diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md index 43c22561d3b4b..8812e97306023 100644 --- a/.github/ISSUE_TEMPLATE/bug-report.md +++ b/.github/ISSUE_TEMPLATE/bug-report.md @@ -11,7 +11,7 @@ about: Report a bug in Roslyn 2. 3. -A minimal repro, with source-code provided, is ideal. Most compiler/language issues can be distilled into a snippet that can be pasted into [sharplab](https://sharplab.io/). +A minimal repro, with source-code provided, is ideal. Most compiler/language issues can be distilled into a snippet that can be pasted into [.NET Lab](https://lab.razor.fyi/#csharp). **Diagnostic Id**: diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 78745a3ada316..eecd040d5dd02 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -103,6 +103,7 @@ "command": "dotnet", "args": [ "build", + "-p:InnerTargets=CopyFilesForDebugging", "-p:GenerateFullPaths=true", "${workspaceFolder}/src/NuGet/Microsoft.Net.Compilers.Toolset/AnyCpu/Microsoft.Net.Compilers.Toolset.Package.csproj" ], diff --git a/Compilers.slnf b/Compilers.slnf index 49acd2063d586..458efec9fbc6d 100644 --- a/Compilers.slnf +++ b/Compilers.slnf @@ -53,6 +53,7 @@ "src\\ExpressionEvaluator\\Core\\Source\\ExpressionCompiler\\Microsoft.CodeAnalysis.ExpressionCompiler.csproj", "src\\ExpressionEvaluator\\VisualBasic\\Source\\ExpressionCompiler\\Microsoft.CodeAnalysis.VisualBasic.ExpressionCompiler.vbproj", "src\\Interactive\\csi\\csi.csproj", + "src\\NuGet\\Microsoft.CodeAnalysis.BuildClient.Package\\Microsoft.CodeAnalysis.BuildClient.Package.csproj", "src\\NuGet\\Microsoft.CodeAnalysis.Compilers.Package\\Microsoft.CodeAnalysis.Compilers.Package.csproj", "src\\NuGet\\Microsoft.CodeAnalysis.Package\\Microsoft.CodeAnalysis.Package.csproj", "src\\NuGet\\Microsoft.Net.Compilers.Toolset\\AnyCpu\\Microsoft.Net.Compilers.Toolset.Package.csproj", diff --git a/NuGet.config b/NuGet.config index 26a2f6f90d445..0472eeb256e12 100644 --- a/NuGet.config +++ b/NuGet.config @@ -5,13 +5,16 @@ + - + + - + - + + diff --git a/Roslyn.sln b/Roslyn.sln index 980009f1a1d57..3e4776aca3d40 100644 --- a/Roslyn.sln +++ b/Roslyn.sln @@ -1,6 +1,6 @@ Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 18 -VisualStudioVersion = 18.0.10623.112 main +# Visual Studio Version 17 +VisualStudioVersion = 17.14.36203.30 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RoslynDeployment", "src\Deployment\RoslynDeployment.csproj", "{600AF682-E097-407B-AD85-EE3CED37E680}" EndProject @@ -374,10 +374,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CompilersIOperationGenerator", "src\Tools\Source\CompilerGeneratorTools\Source\IOperationGenerator\CompilersIOperationGenerator.csproj", "{D55FB2BD-CC9E-454B-9654-94AF5D910BF7}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator", "src\Features\Lsif\Generator\Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.csproj", "{B9899CF1-E0EB-4599-9E24-6939A04B4979}" -EndProject -Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests", "src\Features\Lsif\GeneratorTest\Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests.vbproj", "{D15BF03E-04ED-4BEE-A72B-7620F541F4E2}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Analyzers", "Analyzers", "{4A49D526-1644-4819-AA4F-95B348D447D4}" EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "CompilerExtensions", "src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\CompilerExtensions.shproj", "{EC946164-1E17-410B-B7D9-7DE7E6268D63}" @@ -635,10 +631,6 @@ Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "FlowAnalysis.Utilities", "s EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Refactoring.Utilities", "src\RoslynAnalyzers\Utilities\Refactoring\Refactoring.Utilities.shproj", "{68528C1C-B163-49A6-A19D-24E10F500F90}" EndProject -Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Refactoring.CSharp.Utilities", "src\RoslynAnalyzers\Utilities\Refactoring.CSharp\Refactoring.CSharp.Utilities.shproj", "{3055F932-0D1E-4823-A03A-7B62C7639BDA}" -EndProject -Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Refactoring.VisualBasic.Utilities", "src\RoslynAnalyzers\Utilities\Refactoring.VisualBasic\Refactoring.VisualBasic.Utilities.shproj", "{4C362C30-C4B1-4C4B-A545-DBF67C7E9153}" -EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Workspaces.Utilities", "src\RoslynAnalyzers\Utilities\Workspaces\Workspaces.Utilities.shproj", "{9C4BC501-C0A6-4130-BA68-EF5FB0C640B0}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Utilities", "Utilities", "{0DDCFE67-7D4E-4709-9882-EC032A031789}" @@ -733,6 +725,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Build.Tasks.CodeA EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Build.Tasks.CodeAnalysis.Sdk.UnitTests", "src\Compilers\Core\SdkTaskTests\Microsoft.Build.Tasks.CodeAnalysis.Sdk.UnitTests.csproj", "{5399BBCC-417F-C710-46DE-EB0C0074C34D}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.BuildClient.Package", "src\NuGet\Microsoft.CodeAnalysis.BuildClient.Package\Microsoft.CodeAnalysis.BuildClient.Package.csproj", "{5E4F7448-B00B-4F5B-859F-6ED0354253D5}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -1295,14 +1289,6 @@ Global {D55FB2BD-CC9E-454B-9654-94AF5D910BF7}.Debug|Any CPU.Build.0 = Debug|Any CPU {D55FB2BD-CC9E-454B-9654-94AF5D910BF7}.Release|Any CPU.ActiveCfg = Release|Any CPU {D55FB2BD-CC9E-454B-9654-94AF5D910BF7}.Release|Any CPU.Build.0 = Release|Any CPU - {B9899CF1-E0EB-4599-9E24-6939A04B4979}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B9899CF1-E0EB-4599-9E24-6939A04B4979}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B9899CF1-E0EB-4599-9E24-6939A04B4979}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B9899CF1-E0EB-4599-9E24-6939A04B4979}.Release|Any CPU.Build.0 = Release|Any CPU - {D15BF03E-04ED-4BEE-A72B-7620F541F4E2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D15BF03E-04ED-4BEE-A72B-7620F541F4E2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D15BF03E-04ED-4BEE-A72B-7620F541F4E2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D15BF03E-04ED-4BEE-A72B-7620F541F4E2}.Release|Any CPU.Build.0 = Release|Any CPU {B64766CD-1A1F-4C1B-B11F-C30F82B8E41E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B64766CD-1A1F-4C1B-B11F-C30F82B8E41E}.Debug|Any CPU.Build.0 = Debug|Any CPU {B64766CD-1A1F-4C1B-B11F-C30F82B8E41E}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -1807,6 +1793,10 @@ Global {5399BBCC-417F-C710-46DE-EB0C0074C34D}.Debug|Any CPU.Build.0 = Debug|Any CPU {5399BBCC-417F-C710-46DE-EB0C0074C34D}.Release|Any CPU.ActiveCfg = Release|Any CPU {5399BBCC-417F-C710-46DE-EB0C0074C34D}.Release|Any CPU.Build.0 = Release|Any CPU + {5E4F7448-B00B-4F5B-859F-6ED0354253D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5E4F7448-B00B-4F5B-859F-6ED0354253D5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5E4F7448-B00B-4F5B-859F-6ED0354253D5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5E4F7448-B00B-4F5B-859F-6ED0354253D5}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -1974,8 +1964,6 @@ Global {CE7F7553-DB2D-4839-92E3-F042E4261B4E} = {8DBA5174-B0AA-4561-82B1-A46607697753} {FF38E9C9-7A25-44F0-B2C4-24C9BFD6A8F6} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} {D55FB2BD-CC9E-454B-9654-94AF5D910BF7} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} - {B9899CF1-E0EB-4599-9E24-6939A04B4979} = {D449D505-CC6A-4E0B-AF1B-976E2D0AE67A} - {D15BF03E-04ED-4BEE-A72B-7620F541F4E2} = {D449D505-CC6A-4E0B-AF1B-976E2D0AE67A} {4A49D526-1644-4819-AA4F-95B348D447D4} = {3E5FE3DB-45F7-4D83-9097-8F05D3B3AEC6} {EC946164-1E17-410B-B7D9-7DE7E6268D63} = {7A69EA65-4411-4CD0-B439-035E720C1BD3} {99F594B1-3916-471D-A761-A6731FC50E9A} = {9C1BE25C-5926-4E56-84AE-D2242CB0627E} @@ -2101,8 +2089,6 @@ Global {BE5FE32C-DA73-4EC5-809E-E11B05ACA398} = {0DDCFE67-7D4E-4709-9882-EC032A031789} {FCB56CBA-FA35-46A8-86B7-BAE5433197D9} = {0DDCFE67-7D4E-4709-9882-EC032A031789} {68528C1C-B163-49A6-A19D-24E10F500F90} = {0DDCFE67-7D4E-4709-9882-EC032A031789} - {3055F932-0D1E-4823-A03A-7B62C7639BDA} = {0DDCFE67-7D4E-4709-9882-EC032A031789} - {4C362C30-C4B1-4C4B-A545-DBF67C7E9153} = {0DDCFE67-7D4E-4709-9882-EC032A031789} {9C4BC501-C0A6-4130-BA68-EF5FB0C640B0} = {0DDCFE67-7D4E-4709-9882-EC032A031789} {0DDCFE67-7D4E-4709-9882-EC032A031789} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} {34A07D0C-32E6-E19B-337E-4E6CB722C606} = {0DDCFE67-7D4E-4709-9882-EC032A031789} @@ -2150,6 +2136,7 @@ Global {1B4AC233-B345-123F-E004-DAA28DE1CB08} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} {91F9EAA4-ACA2-87EE-868E-6CC3B73D6A11} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} {5399BBCC-417F-C710-46DE-EB0C0074C34D} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} + {5E4F7448-B00B-4F5B-859F-6ED0354253D5} = {C52D8057-43AF-40E6-A01B-6CDBB7301985} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {604E6B91-7BC0-4126-AE07-D4D2FEFC3D29} @@ -2160,8 +2147,14 @@ Global src\Compilers\CSharp\csc\CscCommandLine.projitems*{0161e25c-918a-4dc8-9648-30fdcc8e31e9}*SharedItemsImports = 5 src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Extensions\Microsoft.CodeAnalysis.Extensions.projitems*{02bcc112-0a29-43aa-84fa-c71c18a9486c}*SharedItemsImports = 13 src\RoslynAnalyzers\Utilities\Compiler\Analyzer.Utilities.projitems*{08735294-3e6b-4420-9916-e7b8c4eb874d}*SharedItemsImports = 13 + src\Dependencies\Collections\Microsoft.CodeAnalysis.Collections.projitems*{0a1267e9-52ff-b8de-8522-802be55f41da}*SharedItemsImports = 5 + src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{0a1267e9-52ff-b8de-8522-802be55f41da}*SharedItemsImports = 5 + src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{0a1267e9-52ff-b8de-8522-802be55f41da}*SharedItemsImports = 5 + src\Dependencies\Threading\Microsoft.CodeAnalysis.Threading.projitems*{0a1267e9-52ff-b8de-8522-802be55f41da}*SharedItemsImports = 5 src\RoslynAnalyzers\Utilities\Compiler\Analyzer.Utilities.projitems*{0a1267e9-52ff-b8de-8522-802be55f41da}*SharedItemsImports = 5 src\RoslynAnalyzers\Utilities\FlowAnalysis\FlowAnalysis.Utilities.projitems*{0a1267e9-52ff-b8de-8522-802be55f41da}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\CompilerExtensions.projitems*{0a1267e9-52ff-b8de-8522-802be55f41da}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Extensions\Microsoft.CodeAnalysis.Extensions.projitems*{0a1267e9-52ff-b8de-8522-802be55f41da}*SharedItemsImports = 5 src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{0c2e1633-1462-4712-88f4-a0c945bad3a8}*SharedItemsImports = 5 src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{0c2e1633-1462-4712-88f4-a0c945bad3a8}*SharedItemsImports = 5 src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{1b4ac233-b345-123f-e004-daa28de1cb08}*SharedItemsImports = 5 @@ -2188,19 +2181,23 @@ Global src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\CompilerExtensions.projitems*{275812ee-dedb-4232-9439-91c9757d2ae4}*SharedItemsImports = 5 src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Extensions\Microsoft.CodeAnalysis.Extensions.projitems*{275812ee-dedb-4232-9439-91c9757d2ae4}*SharedItemsImports = 5 src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{2801f82b-78ce-4bae-b06f-537574751e2e}*SharedItemsImports = 5 - src\RoslynAnalyzers\Utilities\Refactoring.CSharp\Refactoring.CSharp.Utilities.projitems*{3055f932-0d1e-4823-a03a-7b62c7639bda}*SharedItemsImports = 13 src\ExpressionEvaluator\VisualBasic\Source\ResultProvider\BasicResultProvider.projitems*{3140fe61-0856-4367-9aa3-8081b9a80e35}*SharedItemsImports = 13 src\ExpressionEvaluator\CSharp\Source\ResultProvider\CSharpResultProvider.projitems*{3140fe61-0856-4367-9aa3-8081b9a80e36}*SharedItemsImports = 13 src\Analyzers\CSharp\Analyzers\CSharpAnalyzers.projitems*{3973b09a-4fbf-44a5-8359-3d22ceb71f71}*SharedItemsImports = 5 src\Analyzers\CSharp\CodeFixes\CSharpCodeFixes.projitems*{3973b09a-4fbf-44a5-8359-3d22ceb71f71}*SharedItemsImports = 5 src\Compilers\CSharp\CSharpAnalyzerDriver\CSharpAnalyzerDriver.projitems*{3973b09a-4fbf-44a5-8359-3d22ceb71f71}*SharedItemsImports = 5 + src\Dependencies\Collections\Microsoft.CodeAnalysis.Collections.projitems*{3f65d29d-ed95-2d6f-b927-47c5cf070aa5}*SharedItemsImports = 5 + src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{3f65d29d-ed95-2d6f-b927-47c5cf070aa5}*SharedItemsImports = 5 + src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{3f65d29d-ed95-2d6f-b927-47c5cf070aa5}*SharedItemsImports = 5 + src\Dependencies\Threading\Microsoft.CodeAnalysis.Threading.projitems*{3f65d29d-ed95-2d6f-b927-47c5cf070aa5}*SharedItemsImports = 5 src\RoslynAnalyzers\Utilities\Compiler\Analyzer.Utilities.projitems*{3f65d29d-ed95-2d6f-b927-47c5cf070aa5}*SharedItemsImports = 5 src\RoslynAnalyzers\Utilities\Workspaces\Workspaces.Utilities.projitems*{3f65d29d-ed95-2d6f-b927-47c5cf070aa5}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\CompilerExtensions.projitems*{3f65d29d-ed95-2d6f-b927-47c5cf070aa5}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Extensions\Microsoft.CodeAnalysis.Extensions.projitems*{3f65d29d-ed95-2d6f-b927-47c5cf070aa5}*SharedItemsImports = 5 src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{41ed1bfa-fdad-4fe4-8118-db23fb49b0b0}*SharedItemsImports = 5 src\Workspaces\SharedUtilitiesAndExtensions\Workspace\CSharp\CSharpWorkspaceExtensions.projitems*{438db8af-f3f0-4ed9-80b5-13fddd5b8787}*SharedItemsImports = 13 src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{49e7c367-181b-499c-ac2e-8e17c81418d6}*SharedItemsImports = 5 src\Compilers\CSharp\csc\CscCommandLine.projitems*{4b45ca0c-03a0-400f-b454-3d4bcb16af38}*SharedItemsImports = 5 - src\RoslynAnalyzers\Utilities\Refactoring.VisualBasic\Refactoring.VisualBasic.Utilities.projitems*{4c362c30-c4b1-4c4b-a545-dbf67c7e9153}*SharedItemsImports = 13 src\Analyzers\CSharp\Tests\CSharpAnalyzers.UnitTests.projitems*{5018d049-5870-465a-889b-c742ce1e31cb}*SharedItemsImports = 5 src\Compilers\CSharp\CSharpAnalyzerDriver\CSharpAnalyzerDriver.projitems*{54e08bf5-f819-404f-a18d-0ab9ea81ea04}*SharedItemsImports = 13 src\Workspaces\SharedUtilitiesAndExtensions\Compiler\VisualBasic\VisualBasicCompilerExtensions.projitems*{57ca988d-f010-4bf2-9a2e-07d6dcd2ff2c}*SharedItemsImports = 5 @@ -2222,24 +2219,57 @@ Global src\LanguageServer\Microsoft.CommonLanguageServerProtocol.Framework\Microsoft.CommonLanguageServerProtocol.Framework.Shared.projitems*{686bf57e-a6ff-467b-aab3-44de916a9772}*SharedItemsImports = 5 src\Workspaces\SharedUtilitiesAndExtensions\Compiler\CSharp\CSharpCompilerExtensions.projitems*{699fea05-aea7-403d-827e-53cf4e826955}*SharedItemsImports = 13 src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{6fc8e6f5-659c-424d-aeb5-331b95883e29}*SharedItemsImports = 5 + src\Dependencies\Collections\Microsoft.CodeAnalysis.Collections.projitems*{7005dd7b-d3b6-1360-313b-975974aa6254}*SharedItemsImports = 5 + src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{7005dd7b-d3b6-1360-313b-975974aa6254}*SharedItemsImports = 5 + src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{7005dd7b-d3b6-1360-313b-975974aa6254}*SharedItemsImports = 5 + src\Dependencies\Threading\Microsoft.CodeAnalysis.Threading.projitems*{7005dd7b-d3b6-1360-313b-975974aa6254}*SharedItemsImports = 5 src\RoslynAnalyzers\Utilities\Compiler\Analyzer.Utilities.projitems*{7005dd7b-d3b6-1360-313b-975974aa6254}*SharedItemsImports = 5 src\RoslynAnalyzers\Utilities\Workspaces\Workspaces.Utilities.projitems*{7005dd7b-d3b6-1360-313b-975974aa6254}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\CompilerExtensions.projitems*{7005dd7b-d3b6-1360-313b-975974aa6254}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Extensions\Microsoft.CodeAnalysis.Extensions.projitems*{7005dd7b-d3b6-1360-313b-975974aa6254}*SharedItemsImports = 5 src\ExpressionEvaluator\VisualBasic\Source\ResultProvider\BasicResultProvider.projitems*{76242a2d-2600-49dd-8c15-fea07ecb1843}*SharedItemsImports = 5 src\Analyzers\Core\Analyzers\Analyzers.projitems*{76e96966-4780-4040-8197-bde2879516f4}*SharedItemsImports = 13 src\Analyzers\VisualBasic\Tests\VisualBasicAnalyzers.UnitTests.projitems*{7b7f4153-ae93-4908-b8f0-430871589f83}*SharedItemsImports = 13 + src\Dependencies\Collections\Microsoft.CodeAnalysis.Collections.projitems*{8087bde4-6707-05a5-5f84-dfe6628e8ec8}*SharedItemsImports = 5 + src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{8087bde4-6707-05a5-5f84-dfe6628e8ec8}*SharedItemsImports = 5 + src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{8087bde4-6707-05a5-5f84-dfe6628e8ec8}*SharedItemsImports = 5 + src\Dependencies\Threading\Microsoft.CodeAnalysis.Threading.projitems*{8087bde4-6707-05a5-5f84-dfe6628e8ec8}*SharedItemsImports = 5 src\RoslynAnalyzers\Utilities\Compiler\Analyzer.Utilities.projitems*{8087bde4-6707-05a5-5f84-dfe6628e8ec8}*SharedItemsImports = 5 src\RoslynAnalyzers\Utilities\Workspaces\Workspaces.Utilities.projitems*{8087bde4-6707-05a5-5f84-dfe6628e8ec8}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\CompilerExtensions.projitems*{8087bde4-6707-05a5-5f84-dfe6628e8ec8}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Extensions\Microsoft.CodeAnalysis.Extensions.projitems*{8087bde4-6707-05a5-5f84-dfe6628e8ec8}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Workspace\Core\WorkspaceExtensions.projitems*{8087bde4-6707-05a5-5f84-dfe6628e8ec8}*SharedItemsImports = 5 src\Compilers\VisualBasic\vbc\VbcCommandLine.projitems*{810b02ad-2ea5-4422-88ac-b71b8ab0df0b}*SharedItemsImports = 13 + src\Dependencies\Collections\Microsoft.CodeAnalysis.Collections.projitems*{8252a386-069a-0d7d-eab4-b2e77833b443}*SharedItemsImports = 5 + src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{8252a386-069a-0d7d-eab4-b2e77833b443}*SharedItemsImports = 5 + src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{8252a386-069a-0d7d-eab4-b2e77833b443}*SharedItemsImports = 5 + src\Dependencies\Threading\Microsoft.CodeAnalysis.Threading.projitems*{8252a386-069a-0d7d-eab4-b2e77833b443}*SharedItemsImports = 5 src\RoslynAnalyzers\Utilities\Compiler\Analyzer.Utilities.projitems*{8252a386-069a-0d7d-eab4-b2e77833b443}*SharedItemsImports = 5 src\RoslynAnalyzers\Utilities\Workspaces\Workspaces.Utilities.projitems*{8252a386-069a-0d7d-eab4-b2e77833b443}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\CompilerExtensions.projitems*{8252a386-069a-0d7d-eab4-b2e77833b443}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Extensions\Microsoft.CodeAnalysis.Extensions.projitems*{8252a386-069a-0d7d-eab4-b2e77833b443}*SharedItemsImports = 5 + src\Dependencies\Collections\Microsoft.CodeAnalysis.Collections.projitems*{8ce66034-25e2-8ff2-93a1-0bd3672ad86d}*SharedItemsImports = 5 + src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{8ce66034-25e2-8ff2-93a1-0bd3672ad86d}*SharedItemsImports = 5 + src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{8ce66034-25e2-8ff2-93a1-0bd3672ad86d}*SharedItemsImports = 5 + src\Dependencies\Threading\Microsoft.CodeAnalysis.Threading.projitems*{8ce66034-25e2-8ff2-93a1-0bd3672ad86d}*SharedItemsImports = 5 src\RoslynAnalyzers\Utilities\Compiler\Analyzer.Utilities.projitems*{8ce66034-25e2-8ff2-93a1-0bd3672ad86d}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\CompilerExtensions.projitems*{8ce66034-25e2-8ff2-93a1-0bd3672ad86d}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Extensions\Microsoft.CodeAnalysis.Extensions.projitems*{8ce66034-25e2-8ff2-93a1-0bd3672ad86d}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Workspace\Core\WorkspaceExtensions.projitems*{8ce66034-25e2-8ff2-93a1-0bd3672ad86d}*SharedItemsImports = 5 src\Dependencies\Collections\Microsoft.CodeAnalysis.Collections.projitems*{8e2a252e-a140-45a6-a81a-2652996ea589}*SharedItemsImports = 5 src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{8e2a252e-a140-45a6-a81a-2652996ea589}*SharedItemsImports = 5 src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{8e2a252e-a140-45a6-a81a-2652996ea589}*SharedItemsImports = 5 src\Dependencies\Threading\Microsoft.CodeAnalysis.Threading.projitems*{8e2a252e-a140-45a6-a81a-2652996ea589}*SharedItemsImports = 5 src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{91f9eaa4-aca2-87ee-868e-6cc3b73d6a11}*SharedItemsImports = 5 + src\Dependencies\Collections\Microsoft.CodeAnalysis.Collections.projitems*{923e34ba-ca8a-971e-7ff7-51dd346394a1}*SharedItemsImports = 5 + src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{923e34ba-ca8a-971e-7ff7-51dd346394a1}*SharedItemsImports = 5 + src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{923e34ba-ca8a-971e-7ff7-51dd346394a1}*SharedItemsImports = 5 + src\Dependencies\Threading\Microsoft.CodeAnalysis.Threading.projitems*{923e34ba-ca8a-971e-7ff7-51dd346394a1}*SharedItemsImports = 5 src\RoslynAnalyzers\Utilities\Compiler\Analyzer.Utilities.projitems*{923e34ba-ca8a-971e-7ff7-51dd346394a1}*SharedItemsImports = 5 src\RoslynAnalyzers\Utilities\Workspaces\Workspaces.Utilities.projitems*{923e34ba-ca8a-971e-7ff7-51dd346394a1}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\CompilerExtensions.projitems*{923e34ba-ca8a-971e-7ff7-51dd346394a1}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Extensions\Microsoft.CodeAnalysis.Extensions.projitems*{923e34ba-ca8a-971e-7ff7-51dd346394a1}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Workspace\Core\WorkspaceExtensions.projitems*{923e34ba-ca8a-971e-7ff7-51dd346394a1}*SharedItemsImports = 5 src\Analyzers\VisualBasic\Analyzers\VisualBasicAnalyzers.projitems*{94faf461-2e74-4dbb-9813-6b2cde6f1880}*SharedItemsImports = 13 src\Compilers\Server\VBCSCompiler\VBCSCompilerCommandLine.projitems*{9508f118-f62e-4c16-a6f4-7c3b56e166ad}*SharedItemsImports = 5 src\Dependencies\Threading\Microsoft.CodeAnalysis.Threading.projitems*{967723e8-4fdd-447b-99f6-4f8c47cb5433}*SharedItemsImports = 13 @@ -2252,16 +2282,40 @@ Global src\Analyzers\VisualBasic\Analyzers\VisualBasicAnalyzers.projitems*{a1bcd0ce-6c2f-4f8c-9a48-d9d93928e26d}*SharedItemsImports = 5 src\Analyzers\VisualBasic\CodeFixes\VisualBasicCodeFixes.projitems*{a1bcd0ce-6c2f-4f8c-9a48-d9d93928e26d}*SharedItemsImports = 5 src\Compilers\VisualBasic\BasicAnalyzerDriver\BasicAnalyzerDriver.projitems*{a1bcd0ce-6c2f-4f8c-9a48-d9d93928e26d}*SharedItemsImports = 5 - src\RoslynAnalyzers\Utilities\Refactoring.VisualBasic\Refactoring.VisualBasic.Utilities.projitems*{a4a3650e-164f-9339-fa7b-606effd06268}*SharedItemsImports = 5 + src\Dependencies\Collections\Microsoft.CodeAnalysis.Collections.projitems*{a1ebc0bc-d378-b9b7-7a57-ef7df11e3ed7}*SharedItemsImports = 5 + src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{a1ebc0bc-d378-b9b7-7a57-ef7df11e3ed7}*SharedItemsImports = 5 + src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{a1ebc0bc-d378-b9b7-7a57-ef7df11e3ed7}*SharedItemsImports = 5 + src\Dependencies\Threading\Microsoft.CodeAnalysis.Threading.projitems*{a1ebc0bc-d378-b9b7-7a57-ef7df11e3ed7}*SharedItemsImports = 5 + src\RoslynAnalyzers\Utilities\Compiler\Analyzer.Utilities.projitems*{a1ebc0bc-d378-b9b7-7a57-ef7df11e3ed7}*SharedItemsImports = 5 + src\RoslynAnalyzers\Utilities\Workspaces\Workspaces.Utilities.projitems*{a1ebc0bc-d378-b9b7-7a57-ef7df11e3ed7}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\CompilerExtensions.projitems*{a1ebc0bc-d378-b9b7-7a57-ef7df11e3ed7}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Extensions\Microsoft.CodeAnalysis.Extensions.projitems*{a1ebc0bc-d378-b9b7-7a57-ef7df11e3ed7}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Workspace\Core\WorkspaceExtensions.projitems*{a1ebc0bc-d378-b9b7-7a57-ef7df11e3ed7}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\VisualBasic\VisualBasicCompilerExtensions.projitems*{a4a3650e-164f-9339-fa7b-606effd06268}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Workspace\VisualBasic\VisualBasicWorkspaceExtensions.projitems*{a4a3650e-164f-9339-fa7b-606effd06268}*SharedItemsImports = 5 + src\Dependencies\Collections\Microsoft.CodeAnalysis.Collections.projitems*{a6844326-e313-f10a-7e99-89f54c73774c}*SharedItemsImports = 5 + src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{a6844326-e313-f10a-7e99-89f54c73774c}*SharedItemsImports = 5 + src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{a6844326-e313-f10a-7e99-89f54c73774c}*SharedItemsImports = 5 + src\Dependencies\Threading\Microsoft.CodeAnalysis.Threading.projitems*{a6844326-e313-f10a-7e99-89f54c73774c}*SharedItemsImports = 5 src\RoslynAnalyzers\Utilities\Compiler\Analyzer.Utilities.projitems*{a6844326-e313-f10a-7e99-89f54c73774c}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\CompilerExtensions.projitems*{a6844326-e313-f10a-7e99-89f54c73774c}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Extensions\Microsoft.CodeAnalysis.Extensions.projitems*{a6844326-e313-f10a-7e99-89f54c73774c}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Workspace\Core\WorkspaceExtensions.projitems*{a6844326-e313-f10a-7e99-89f54c73774c}*SharedItemsImports = 5 src\Analyzers\CSharp\Analyzers\CSharpAnalyzers.projitems*{aa87bfed-089a-4096-b8d5-690bdc7d5b24}*SharedItemsImports = 5 src\Workspaces\SharedUtilitiesAndExtensions\Compiler\CSharp\CSharpCompilerExtensions.projitems*{aa87bfed-089a-4096-b8d5-690bdc7d5b24}*SharedItemsImports = 5 src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{abdbac1e-350e-4dc3-bb45-3504404545ee}*SharedItemsImports = 5 src\ExpressionEvaluator\Core\Source\ResultProvider\ResultProvider.projitems*{abdbac1e-350e-4dc3-bb45-3504404545ee}*SharedItemsImports = 5 src\ExpressionEvaluator\VisualBasic\Source\ResultProvider\BasicResultProvider.projitems*{ace53515-482c-4c6a-e2d2-4242a687dfee}*SharedItemsImports = 5 + src\Dependencies\Collections\Microsoft.CodeAnalysis.Collections.projitems*{ad0837be-7912-aedf-bda9-2d2e4fe0ce0b}*SharedItemsImports = 5 + src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{ad0837be-7912-aedf-bda9-2d2e4fe0ce0b}*SharedItemsImports = 5 + src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{ad0837be-7912-aedf-bda9-2d2e4fe0ce0b}*SharedItemsImports = 5 + src\Dependencies\Threading\Microsoft.CodeAnalysis.Threading.projitems*{ad0837be-7912-aedf-bda9-2d2e4fe0ce0b}*SharedItemsImports = 5 src\RoslynAnalyzers\Utilities\Compiler\Analyzer.Utilities.projitems*{ad0837be-7912-aedf-bda9-2d2e4fe0ce0b}*SharedItemsImports = 5 src\RoslynAnalyzers\Utilities\Refactoring\Refactoring.Utilities.projitems*{ad0837be-7912-aedf-bda9-2d2e4fe0ce0b}*SharedItemsImports = 5 src\RoslynAnalyzers\Utilities\Workspaces\Workspaces.Utilities.projitems*{ad0837be-7912-aedf-bda9-2d2e4fe0ce0b}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\CompilerExtensions.projitems*{ad0837be-7912-aedf-bda9-2d2e4fe0ce0b}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Extensions\Microsoft.CodeAnalysis.Extensions.projitems*{ad0837be-7912-aedf-bda9-2d2e4fe0ce0b}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Workspace\Core\WorkspaceExtensions.projitems*{ad0837be-7912-aedf-bda9-2d2e4fe0ce0b}*SharedItemsImports = 5 src\Compilers\CSharp\csc\CscCommandLine.projitems*{b021ccbc-b2af-4560-af28-ed055f0ed696}*SharedItemsImports = 13 src\Dependencies\Collections\Microsoft.CodeAnalysis.Collections.projitems*{b1481d94-682e-46ec-adbe-a16eb46feee9}*SharedItemsImports = 5 src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{b1481d94-682e-46ec-adbe-a16eb46feee9}*SharedItemsImports = 5 @@ -2273,7 +2327,13 @@ Global src\RoslynAnalyzers\Utilities\Compiler.CSharp\Analyzer.CSharp.Utilities.projitems*{be5fe32c-da73-4ec5-809e-e11b05aca398}*SharedItemsImports = 13 src\ExpressionEvaluator\CSharp\Source\ResultProvider\CSharpResultProvider.projitems*{bf9dac1e-3a5e-4dc3-bb44-9a64e0d4e9d4}*SharedItemsImports = 5 src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{c1930979-c824-496b-a630-70f5369a636f}*SharedItemsImports = 13 + src\Dependencies\Collections\Microsoft.CodeAnalysis.Collections.projitems*{ce7c15d3-3b1b-84cf-1b4b-da45533e9e83}*SharedItemsImports = 5 + src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{ce7c15d3-3b1b-84cf-1b4b-da45533e9e83}*SharedItemsImports = 5 + src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{ce7c15d3-3b1b-84cf-1b4b-da45533e9e83}*SharedItemsImports = 5 + src\Dependencies\Threading\Microsoft.CodeAnalysis.Threading.projitems*{ce7c15d3-3b1b-84cf-1b4b-da45533e9e83}*SharedItemsImports = 5 src\RoslynAnalyzers\Utilities\Compiler\Analyzer.Utilities.projitems*{ce7c15d3-3b1b-84cf-1b4b-da45533e9e83}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\CompilerExtensions.projitems*{ce7c15d3-3b1b-84cf-1b4b-da45533e9e83}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Extensions\Microsoft.CodeAnalysis.Extensions.projitems*{ce7c15d3-3b1b-84cf-1b4b-da45533e9e83}*SharedItemsImports = 5 src\Workspaces\SharedUtilitiesAndExtensions\Compiler\VisualBasic\VisualBasicCompilerExtensions.projitems*{cec0dce7-8d52-45c3-9295-fc7b16bd2451}*SharedItemsImports = 13 src\Compilers\Core\AnalyzerDriver\AnalyzerDriver.projitems*{d0bc9be7-24f6-40ca-8dc6-fcb93bd44b34}*SharedItemsImports = 13 src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{d2589bce-4f2e-4113-b7e7-37392c0c5492}*SharedItemsImports = 5 @@ -2282,7 +2342,8 @@ Global src\Analyzers\CSharp\CodeFixes\CSharpCodeFixes.projitems*{da973826-c985-4128-9948-0b445e638bdb}*SharedItemsImports = 13 src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{db96c25f-39a9-4a6a-92bc-d1e42717308f}*SharedItemsImports = 5 src\Compilers\Server\VBCSCompiler\VBCSCompilerCommandLine.projitems*{dc8c78cc-b6fe-47bf-93b1-b65a1c67c08d}*SharedItemsImports = 5 - src\RoslynAnalyzers\Utilities\Refactoring.CSharp\Refactoring.CSharp.Utilities.projitems*{dee77b19-9559-d47d-8ec4-c207152a9c2c}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\CSharp\CSharpCompilerExtensions.projitems*{dee77b19-9559-d47d-8ec4-c207152a9c2c}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Workspace\CSharp\CSharpWorkspaceExtensions.projitems*{dee77b19-9559-d47d-8ec4-c207152a9c2c}*SharedItemsImports = 5 src\Analyzers\VisualBasic\Tests\VisualBasicAnalyzers.UnitTests.projitems*{e512c6c1-f085-4ad7-b0d9-e8f1a0a2a510}*SharedItemsImports = 5 src\Compilers\VisualBasic\vbc\VbcCommandLine.projitems*{e58ee9d7-1239-4961-a0c1-f9ec3952c4c1}*SharedItemsImports = 5 src\Analyzers\CSharp\Tests\CSharpAnalyzers.UnitTests.projitems*{e645b517-5766-46fb-aa4a-d4d30c9e3be6}*SharedItemsImports = 5 @@ -2303,7 +2364,13 @@ Global src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{fc2ae90b-2e4b-4045-9fdd-73d4f5ed6c89}*SharedItemsImports = 5 src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{fc2ae90b-2e4b-4045-9fdd-73d4f5ed6c89}*SharedItemsImports = 5 src\RoslynAnalyzers\Utilities\FlowAnalysis\FlowAnalysis.Utilities.projitems*{fcb56cba-fa35-46a8-86b7-bae5433197d9}*SharedItemsImports = 13 + src\Dependencies\Collections\Microsoft.CodeAnalysis.Collections.projitems*{fce0046b-03f8-78f6-86a1-8ddcee8f4c9f}*SharedItemsImports = 5 + src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{fce0046b-03f8-78f6-86a1-8ddcee8f4c9f}*SharedItemsImports = 5 + src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{fce0046b-03f8-78f6-86a1-8ddcee8f4c9f}*SharedItemsImports = 5 + src\Dependencies\Threading\Microsoft.CodeAnalysis.Threading.projitems*{fce0046b-03f8-78f6-86a1-8ddcee8f4c9f}*SharedItemsImports = 5 src\RoslynAnalyzers\Utilities\Compiler\Analyzer.Utilities.projitems*{fce0046b-03f8-78f6-86a1-8ddcee8f4c9f}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\CompilerExtensions.projitems*{fce0046b-03f8-78f6-86a1-8ddcee8f4c9f}*SharedItemsImports = 5 + src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Extensions\Microsoft.CodeAnalysis.Extensions.projitems*{fce0046b-03f8-78f6-86a1-8ddcee8f4c9f}*SharedItemsImports = 5 src\Dependencies\Contracts\Microsoft.CodeAnalysis.Contracts.projitems*{fce88bbd-9bbd-4871-b9b0-de176d73a6b0}*SharedItemsImports = 5 EndGlobalSection EndGlobal diff --git a/azure-pipelines-integration-dartlab.yml b/azure-pipelines-integration-dartlab.yml index c9dca1e99484e..da0b456b9b248 100644 --- a/azure-pipelines-integration-dartlab.yml +++ b/azure-pipelines-integration-dartlab.yml @@ -22,7 +22,7 @@ resources: name: internal/dotnet-roslyn ref: $(Build.SourceBranch) trigger: - - main + - main-vs-deps parameters: - name: prNumber @@ -122,4 +122,4 @@ stages: gitHubConnection: 'dotnet-comment-bot-service-connection' repositoryName: '$(Build.Repository.Name)' id: ${{ parameters.prNumber }} - comment: 'DartLab pipeline [run]($(System.TeamFoundationCollectionUri)$(System.TeamProject)/_build/results?buildId=$(Build.BuildId)) did not complete successfully for ${{ parameters.sha }}' \ No newline at end of file + comment: 'DartLab pipeline [run]($(System.TeamFoundationCollectionUri)$(System.TeamProject)/_build/results?buildId=$(Build.BuildId)) did not complete successfully for ${{ parameters.sha }}' diff --git a/azure-pipelines-integration.yml b/azure-pipelines-integration.yml index cf70c67c5c5d2..afddf6a20c094 100644 --- a/azure-pipelines-integration.yml +++ b/azure-pipelines-integration.yml @@ -68,7 +68,7 @@ parameters: - name: queueName displayName: Queue Name type: string - default: windows.vs2022preview.amd64.open + default: windows.vs2022preview.scout.amd64.open values: - windows.vs2022.amd64.open - windows.vs2022.scout.amd64.open diff --git a/docs/contributing/Compiler Test Plan.md b/docs/contributing/Compiler Test Plan.md index 60a70c63dae06..c9f0f5ea2a3ce 100644 --- a/docs/contributing/Compiler Test Plan.md +++ b/docs/contributing/Compiler Test Plan.md @@ -80,7 +80,7 @@ This document provides guidance for thinking about language interactions and tes - Readonly members on structs (methods, property/indexer accessors, custom event accessors) - SkipLocalsInit - Method override or explicit implementation with `where T : { class, struct, default }` -- `extension` blocks +- `extension` blocks (emitted with content-based names) # Code - Operators (see Eric's list below) diff --git a/docs/features/incremental-generators.cookbook.md b/docs/features/incremental-generators.cookbook.md index a8d9afdde0eda..05958dc20deb6 100644 --- a/docs/features/incremental-generators.cookbook.md +++ b/docs/features/incremental-generators.cookbook.md @@ -21,6 +21,8 @@ of scope in the final design of the shipping feature. - [Pipeline model design](#pipeline-model-design) - [Use `ForAttributeWithMetadataName`](#use-forattributewithmetadataname) - [Use an indented text writer, not `SyntaxNode`s, for generation](#use-an-indented-text-writer-not-syntaxnodes-for-generation) + - [Put `Microsoft.CodeAnalysis.EmbeddedAttribute` on generated marker types](#put-microsoftcodeanalysisembeddedattribute-on-generated-marker-types) + - [Do not scan for types that indirectly implement interfaces, indirectly inherit from types, or are indirectly marked by an attribute from an interface or base type](#do-not-scan-for-types-that-indirectly-implement-interfaces-indirectly-inherit-from-types-or-are-indirectly-marked-by-an-attribute-from-an-interface-or-base-type) - [Designs](#designs) - [Generated class](#generated-class) - [Additional file transformation](#additional-file-transformation) @@ -135,6 +137,27 @@ project, it will not include that type in lookup results. To ensure that `Micros Another option is to provide an assembly in your nuget package that defines your marker attributes, but this can be more difficult to author. We recommend the `EmbeddedAttribute` approach, unless you need to support versions of Roslyn lower than 4.14. +### Do not scan for types that indirectly implement interfaces, indirectly inherit from types, or are indirectly marked by an attribute from an interface or base type + +Using an interface/base type marker can be a very tempting and natural fit for generators. However, scanning for these types of markers is _very_ expensive, and cannot +be done incrementally. Doing so can have an outsized impact on IDE and command-line performance, even for fairly small consuming users. These scenarios are: + +* A user implements an interface on `BaseModelType`, and then the generator looks all derived types from `BaseModelType`. Because the generator cannot know ahead of time + what `BaseModelType` actually is, it means that the generator has to fetch `AllInterfaces` on every single type in the compilation so it can scan for the marker + interface. This will end up occurring either on every keystroke or every file save, depending on what mode the user is running generators in; either one is disastrous + for IDE performance, even when trying to optimize by scoping down the scanning to only types with a base list. +* A user inherits from a generator-defined `BaseSerializerType`, and the generator looks for anything that inherits from that type, either directly or indirectly. Similar + to the above scenario, the generator will need to scan all types with a base type in the entire compilation for the inherited `BaseSerializerType`, which will heavily + impact IDE performance. +* A generator looks among all base types/implemented interfaces for a type that is attributed with a generator's marker attribute. This is effectively either scenario 1 + or 2, just with a different search criteria. +* A generator leaves its marker attribute unsealed, and expects users to be able to derive their own attributes from that marker, as a source of parameter customization. + This has a couple of problems: first, every attributed type needs to be checked to see if the attribute inherits from the marker attribute. While not as performance + impacting as the first three scenarios, this isn't great for performance. Second, and more importantly, there is no good way to retrieve any customizations from the + inherited attribute. These attributes are not instantiated by the source generator, so any parameters passed to the `base()` constructor call or values that are assigned + to any properties of the base attribute are not visible to the generator. Prefer using FAWMN-driven development here, and using an analyzer to inform the user if they + need to inherit from some base class for your generator to work correctly. + ## Designs This section is broken down by user scenarios, with general solutions listed first, and more specific examples later on. diff --git a/eng/Directory.Packages.props b/eng/Directory.Packages.props index 75ead14245059..aa611b4cbb49c 100644 --- a/eng/Directory.Packages.props +++ b/eng/Directory.Packages.props @@ -199,7 +199,7 @@ - + @@ -215,7 +215,7 @@ - + @@ -273,7 +273,7 @@ - + @@ -319,16 +319,16 @@ but not higher than our minimum dogfoodable Visual Studio version, or else the generators we build would load on the command line but not load in IDEs. --> - + - - - - - - + + + + + + diff --git a/eng/Publishing.props b/eng/Publishing.props index 7968b1a8ca5a7..2a0c88ef1b25c 100644 --- a/eng/Publishing.props +++ b/eng/Publishing.props @@ -5,8 +5,9 @@ - + Depending on channel configuration, this means that these assets could be pushed to a different feed. + Do not include these for source-only builds since these files aren't intended to be published in that mode. --> + diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index b6f602b74c189..a1e403bfb4226 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,6 +1,6 @@ - + @@ -110,13 +110,13 @@ - + https://github.com/dotnet/arcade - 086a1771875b63404b4a710d27250fe384dc2810 + 80c4e4d26cb85c86f7e1be77d2d9eceeef0f3493 - + https://github.com/dotnet/arcade - 086a1771875b63404b4a710d27250fe384dc2810 + 80c4e4d26cb85c86f7e1be77d2d9eceeef0f3493 https://github.com/dotnet/symreader @@ -126,9 +126,9 @@ https://github.com/dotnet/roslyn 5d10d428050c0d6afef30a072c4ae68776621877 - + https://github.com/dotnet/arcade - 086a1771875b63404b4a710d27250fe384dc2810 + 80c4e4d26cb85c86f7e1be77d2d9eceeef0f3493 https://github.com/dotnet/roslyn-analyzers diff --git a/eng/Versions.props b/eng/Versions.props index 14c052e19fa99..a70c92287985a 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -8,7 +8,7 @@ 5 0 0 - 1 + 2 $(MajorVersion).$(MinorVersion).$(PatchVersion) + - - 3.11.0 - 1.2.1 - 3.11.0 - 3.11.0 - 4.0.1 - 3.11.0 - 3.11.0 - 3.11.0 - 4.0.1 + 4.12.0 - 4.9.0-3.final - 4.6.0-1.final + 4.12.0 + 4.12.0 - 4.0.1 - $(MicrosoftCodeAnalysisVersionFromSbrp) - $(MicrosoftCodeAnalysisVersionFromSbrp) - $(MicrosoftCodeAnalysisVersionFromSbrp) - $(MicrosoftCodeAnalysisVersionFromSbrp) - $(MicrosoftCodeAnalysisVersionFromSbrp) - $(MicrosoftCodeAnalysisVersionFromSbrp) - $(MicrosoftCodeAnalysisVersionFromSbrp) - $(MicrosoftCodeAnalysisVersionFromSbrp) - $(MicrosoftCodeAnalysisVersionFromSbrp) - $(MicrosoftCodeAnalysisVersionFromSbrp) + 4.12.0 + $(MicrosoftCodeAnalysisVersionFromSbrp) + $(MicrosoftCodeAnalysisVersionFromSbrp) @@ -184,6 +155,6 @@ in Directory.Packages.props - Microsoft.TestPlatform.TranslationLayer and Microsoft.TestPlatform.ObjectModel. This version needs to match the Test SDK version consumed by Arcade. --> - 17.5.0 + 17.13.0 diff --git a/eng/common/CIBuild.cmd b/eng/common/CIBuild.cmd index 56c2f25ac22ff..ac1f72bf94e05 100644 --- a/eng/common/CIBuild.cmd +++ b/eng/common/CIBuild.cmd @@ -1,2 +1,2 @@ @echo off -powershell -ExecutionPolicy ByPass -NoProfile -command "& """%~dp0Build.ps1""" -restore -build -test -sign -pack -publish -ci %*" \ No newline at end of file +powershell -ExecutionPolicy ByPass -NoProfile -command "& """%~dp0Build.ps1""" -restore -build -test -sign -pack -publish -ci %*" diff --git a/eng/common/build.ps1 b/eng/common/build.ps1 index 438f9920c43e4..8cfee107e7a35 100644 --- a/eng/common/build.ps1 +++ b/eng/common/build.ps1 @@ -7,6 +7,7 @@ Param( [string] $msbuildEngine = $null, [bool] $warnAsError = $true, [bool] $nodeReuse = $true, + [switch] $buildCheck = $false, [switch][Alias('r')]$restore, [switch] $deployDeps, [switch][Alias('b')]$build, @@ -20,6 +21,7 @@ Param( [switch] $publish, [switch] $clean, [switch][Alias('pb')]$productBuild, + [switch]$fromVMR, [switch][Alias('bl')]$binaryLog, [switch][Alias('nobl')]$excludeCIBinarylog, [switch] $ci, @@ -71,6 +73,9 @@ function Print-Usage() { Write-Host " -msbuildEngine Msbuild engine to use to run build ('dotnet', 'vs', or unspecified)." Write-Host " -excludePrereleaseVS Set to exclude build engines in prerelease versions of Visual Studio" Write-Host " -nativeToolsOnMachine Sets the native tools on machine environment variable (indicating that the script should use native tools on machine)" + Write-Host " -nodeReuse Sets nodereuse msbuild parameter ('true' or 'false')" + Write-Host " -buildCheck Sets /check msbuild parameter" + Write-Host " -fromVMR Set when building from within the VMR" Write-Host "" Write-Host "Command line arguments not listed above are passed thru to msbuild." @@ -97,6 +102,7 @@ function Build { $bl = if ($binaryLog) { '/bl:' + (Join-Path $LogDir 'Build.binlog') } else { '' } $platformArg = if ($platform) { "/p:Platform=$platform" } else { '' } + $check = if ($buildCheck) { '/check' } else { '' } if ($projects) { # Re-assign properties to a new variable because PowerShell doesn't let us append properties directly for unclear reasons. @@ -113,6 +119,7 @@ function Build { MSBuild $toolsetBuildProj ` $bl ` $platformArg ` + $check ` /p:Configuration=$configuration ` /p:RepoRoot=$RepoRoot ` /p:Restore=$restore ` @@ -122,11 +129,13 @@ function Build { /p:Deploy=$deploy ` /p:Test=$test ` /p:Pack=$pack ` - /p:DotNetBuildRepo=$productBuild ` + /p:DotNetBuild=$productBuild ` + /p:DotNetBuildFromVMR=$fromVMR ` /p:IntegrationTest=$integrationTest ` /p:PerformanceTest=$performanceTest ` /p:Sign=$sign ` /p:Publish=$publish ` + /p:RestoreStaticGraphEnableBinaryLogger=$binaryLog ` @properties } diff --git a/eng/common/build.sh b/eng/common/build.sh index ac1ee8620cd2a..9767bb411a4f0 100755 --- a/eng/common/build.sh +++ b/eng/common/build.sh @@ -42,6 +42,8 @@ usage() echo " --prepareMachine Prepare machine for CI run, clean up processes after build" echo " --nodeReuse Sets nodereuse msbuild parameter ('true' or 'false')" echo " --warnAsError Sets warnaserror msbuild parameter ('true' or 'false')" + echo " --buildCheck Sets /check msbuild parameter" + echo " --fromVMR Set when building from within the VMR" echo "" echo "Command line arguments not listed above are passed thru to msbuild." echo "Arguments can also be passed in with a single hyphen." @@ -63,6 +65,7 @@ restore=false build=false source_build=false product_build=false +from_vmr=false rebuild=false test=false integration_test=false @@ -76,6 +79,7 @@ clean=false warn_as_error=true node_reuse=true +build_check=false binary_log=false exclude_ci_binary_log=false pipelines_log=false @@ -87,7 +91,7 @@ verbosity='minimal' runtime_source_feed='' runtime_source_feed_key='' -properties='' +properties=() while [[ $# > 0 ]]; do opt="$(echo "${1/#--/-}" | tr "[:upper:]" "[:lower:]")" case "$opt" in @@ -127,19 +131,22 @@ while [[ $# > 0 ]]; do -pack) pack=true ;; - -sourcebuild|-sb) + -sourcebuild|-source-build|-sb) build=true source_build=true product_build=true restore=true pack=true ;; - -productBuild|-pb) + -productbuild|-product-build|-pb) build=true product_build=true restore=true pack=true ;; + -fromvmr|-from-vmr) + from_vmr=true + ;; -test|-t) test=true ;; @@ -173,6 +180,9 @@ while [[ $# > 0 ]]; do node_reuse=$2 shift ;; + -buildcheck) + build_check=true + ;; -runtimesourcefeed) runtime_source_feed=$2 shift @@ -182,7 +192,7 @@ while [[ $# > 0 ]]; do shift ;; *) - properties="$properties $1" + properties+=("$1") ;; esac @@ -216,7 +226,7 @@ function Build { InitializeCustomToolset if [[ ! -z "$projects" ]]; then - properties="$properties /p:Projects=$projects" + properties+=("/p:Projects=$projects") fi local bl="" @@ -224,15 +234,21 @@ function Build { bl="/bl:\"$log_dir/Build.binlog\"" fi + local check="" + if [[ "$build_check" == true ]]; then + check="/check" + fi + MSBuild $_InitializeToolset \ $bl \ + $check \ /p:Configuration=$configuration \ /p:RepoRoot="$repo_root" \ /p:Restore=$restore \ /p:Build=$build \ - /p:DotNetBuildRepo=$product_build \ - /p:ArcadeBuildFromSource=$source_build \ + /p:DotNetBuild=$product_build \ /p:DotNetBuildSourceOnly=$source_build \ + /p:DotNetBuildFromVMR=$from_vmr \ /p:Rebuild=$rebuild \ /p:Test=$test \ /p:Pack=$pack \ @@ -240,7 +256,8 @@ function Build { /p:PerformanceTest=$performance_test \ /p:Sign=$sign \ /p:Publish=$publish \ - $properties + /p:RestoreStaticGraphEnableBinaryLogger=$binary_log \ + ${properties[@]+"${properties[@]}"} ExitWithExitCode 0 } diff --git a/eng/common/cibuild.sh b/eng/common/cibuild.sh index 1a02c0dec8fd7..66e3b0ac61c36 100755 --- a/eng/common/cibuild.sh +++ b/eng/common/cibuild.sh @@ -13,4 +13,4 @@ while [[ -h $source ]]; do done scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" -. "$scriptroot/build.sh" --restore --build --test --pack --publish --ci $@ \ No newline at end of file +. "$scriptroot/build.sh" --restore --build --test --pack --publish --ci $@ diff --git a/eng/common/core-templates/job/job.yml b/eng/common/core-templates/job/job.yml index ba53ebfbd5133..6badecba7bcc4 100644 --- a/eng/common/core-templates/job/job.yml +++ b/eng/common/core-templates/job/job.yml @@ -19,10 +19,10 @@ parameters: # publishing defaults artifacts: '' enableMicrobuild: false + enableMicrobuildForMacAndLinux: false enablePublishBuildArtifacts: false enablePublishBuildAssets: false enablePublishTestResults: false - enablePublishUsingPipelines: false enableBuildRetry: false mergeTestResults: false testRunTitle: '' @@ -73,9 +73,6 @@ jobs: - ${{ if ne(parameters.enableTelemetry, 'false') }}: - name: DOTNET_CLI_TELEMETRY_PROFILE value: '$(Build.Repository.Uri)' - - ${{ if eq(parameters.enableRichCodeNavigation, 'true') }}: - - name: EnableRichCodeNavigation - value: 'true' # Retry signature validation up to three times, waiting 2 seconds between attempts. # See https://learn.microsoft.com/en-us/nuget/reference/errors-and-warnings/nu3028#retry-untrusted-root-failures - name: NUGET_EXPERIMENTAL_CHAIN_BUILD_RETRY_POLICY @@ -127,18 +124,11 @@ jobs: - ${{ preStep }} - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - - ${{ if eq(parameters.enableMicrobuild, 'true') }}: - - task: MicroBuildSigningPlugin@4 - displayName: Install MicroBuild plugin - inputs: - signType: $(_SignType) - zipSources: false - feedSource: https://dnceng.pkgs.visualstudio.com/_packaging/MicroBuildToolset/nuget/v3/index.json - env: - TeamName: $(_TeamName) - MicroBuildOutputFolderOverride: '$(Agent.TempDirectory)' + - template: /eng/common/core-templates/steps/install-microbuild.yml + parameters: + enableMicrobuild: ${{ parameters.enableMicrobuild }} + enableMicrobuildForMacAndLinux: ${{ parameters.enableMicrobuildForMacAndLinux }} continueOnError: ${{ parameters.continueOnError }} - condition: and(succeeded(), in(variables['_SignType'], 'real', 'test'), eq(variables['Agent.Os'], 'Windows_NT')) - ${{ if and(eq(parameters.runAsPublic, 'false'), eq(variables['System.TeamProject'], 'internal')) }}: - task: NuGetAuthenticate@1 @@ -154,27 +144,15 @@ jobs: - ${{ each step in parameters.steps }}: - ${{ step }} - - ${{ if eq(parameters.enableRichCodeNavigation, true) }}: - - task: RichCodeNavIndexer@0 - displayName: RichCodeNav Upload - inputs: - languages: ${{ coalesce(parameters.richCodeNavigationLanguage, 'csharp') }} - environment: ${{ coalesce(parameters.richCodeNavigationEnvironment, 'internal') }} - richNavLogOutputDirectory: $(Build.SourcesDirectory)/artifacts/bin - uploadRichNavArtifacts: ${{ coalesce(parameters.richCodeNavigationUploadArtifacts, false) }} - continueOnError: true - - ${{ each step in parameters.componentGovernanceSteps }}: - ${{ step }} - - ${{ if eq(parameters.enableMicrobuild, 'true') }}: - - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - - task: MicroBuildCleanup@1 - displayName: Execute Microbuild cleanup tasks - condition: and(always(), in(variables['_SignType'], 'real', 'test'), eq(variables['Agent.Os'], 'Windows_NT')) + - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: + - template: /eng/common/core-templates/steps/cleanup-microbuild.yml + parameters: + enableMicrobuild: ${{ parameters.enableMicrobuild }} + enableMicrobuildForMacAndLinux: ${{ parameters.enableMicrobuildForMacAndLinux }} continueOnError: ${{ parameters.continueOnError }} - env: - TeamName: $(_TeamName) # Publish test results - ${{ if or(and(eq(parameters.enablePublishTestResults, 'true'), eq(parameters.testResultsFormat, '')), eq(parameters.testResultsFormat, 'xunit')) }}: diff --git a/eng/common/core-templates/job/onelocbuild.yml b/eng/common/core-templates/job/onelocbuild.yml index 00feec8ebbc3a..8034815f4213b 100644 --- a/eng/common/core-templates/job/onelocbuild.yml +++ b/eng/common/core-templates/job/onelocbuild.yml @@ -86,8 +86,7 @@ jobs: isAutoCompletePrSelected: ${{ parameters.AutoCompletePr }} ${{ if eq(parameters.CreatePr, true) }}: isUseLfLineEndingsSelected: ${{ parameters.UseLfLineEndings }} - ${{ if eq(parameters.RepoType, 'gitHub') }}: - isShouldReusePrSelected: ${{ parameters.ReusePr }} + isShouldReusePrSelected: ${{ parameters.ReusePr }} packageSourceAuth: patAuth patVariable: ${{ parameters.CeapexPat }} ${{ if eq(parameters.RepoType, 'gitHub') }}: @@ -118,4 +117,4 @@ jobs: pathToPublish: '$(Build.SourcesDirectory)/eng/Localize/' publishLocation: Container artifactName: Loc - condition: ${{ parameters.condition }} \ No newline at end of file + condition: ${{ parameters.condition }} diff --git a/eng/common/core-templates/job/publish-build-assets.yml b/eng/common/core-templates/job/publish-build-assets.yml index 3d3356e319672..d5303229c97e2 100644 --- a/eng/common/core-templates/job/publish-build-assets.yml +++ b/eng/common/core-templates/job/publish-build-assets.yml @@ -20,9 +20,6 @@ parameters: # if 'true', the build won't run any of the internal only steps, even if it is running in non-public projects. runAsPublic: false - # Optional: whether the build's artifacts will be published using release pipelines or direct feed publishing - publishUsingPipelines: false - # Optional: whether the build's artifacts will be published using release pipelines or direct feed publishing publishAssetsImmediately: false @@ -32,6 +29,15 @@ parameters: is1ESPipeline: '' + # Optional: 🌤️ or not the build has assets it wants to publish to BAR + isAssetlessBuild: false + + # Optional, publishing version + publishingVersion: 3 + + # Optional: A minimatch pattern for the asset manifests to publish to BAR + assetManifestsPattern: '*/manifests/**/*.xml' + jobs: - job: Asset_Registry_Publish @@ -75,15 +81,33 @@ jobs: - checkout: self fetchDepth: 3 clean: true - - - task: DownloadBuildArtifacts@0 - displayName: Download artifact - inputs: - artifactName: AssetManifests - downloadPath: '$(Build.StagingDirectory)/Download' - checkDownloadedFiles: true - condition: ${{ parameters.condition }} - continueOnError: ${{ parameters.continueOnError }} + + - ${{ if eq(parameters.isAssetlessBuild, 'false') }}: + - ${{ if eq(parameters.publishingVersion, 3) }}: + - task: DownloadPipelineArtifact@2 + displayName: Download Asset Manifests + inputs: + artifactName: AssetManifests + targetPath: '$(Build.StagingDirectory)/AssetManifests' + condition: ${{ parameters.condition }} + continueOnError: ${{ parameters.continueOnError }} + - ${{ if eq(parameters.publishingVersion, 4) }}: + - task: DownloadPipelineArtifact@2 + displayName: Download V4 asset manifests + inputs: + itemPattern: '*/manifests/**/*.xml' + targetPath: '$(Build.StagingDirectory)/AllAssetManifests' + condition: ${{ parameters.condition }} + continueOnError: ${{ parameters.continueOnError }} + - task: CopyFiles@2 + displayName: Copy V4 asset manifests to AssetManifests + inputs: + SourceFolder: '$(Build.StagingDirectory)/AllAssetManifests' + Contents: ${{ parameters.assetManifestsPattern }} + TargetFolder: '$(Build.StagingDirectory)/AssetManifests' + flattenFolders: true + condition: ${{ parameters.condition }} + continueOnError: ${{ parameters.continueOnError }} - task: NuGetAuthenticate@1 @@ -95,9 +119,9 @@ jobs: scriptLocation: scriptPath scriptPath: $(Build.SourcesDirectory)/eng/common/sdk-task.ps1 arguments: -task PublishBuildAssets -restore -msbuildEngine dotnet - /p:ManifestsPath='$(Build.StagingDirectory)/Download/AssetManifests' + /p:ManifestsPath='$(Build.StagingDirectory)/AssetManifests' + /p:IsAssetlessBuild=${{ parameters.isAssetlessBuild }} /p:MaestroApiEndpoint=https://maestro.dot.net - /p:PublishUsingPipelines=${{ parameters.publishUsingPipelines }} /p:OfficialBuildId=$(Build.BuildNumber) condition: ${{ parameters.condition }} continueOnError: ${{ parameters.continueOnError }} @@ -120,6 +144,17 @@ jobs: Copy-Item -Path $symbolExclusionfile -Destination "$(Build.StagingDirectory)/ReleaseConfigs" } + - ${{ if eq(parameters.publishingVersion, 4) }}: + - template: /eng/common/core-templates/steps/publish-pipeline-artifacts.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + args: + targetPath: '$(Build.ArtifactStagingDirectory)/MergedManifest.xml' + artifactName: AssetManifests + displayName: 'Publish Merged Manifest' + retryCountOnTaskFailure: 10 # for any logs being locked + sbomEnabled: false # we don't need SBOM for logs + - template: /eng/common/core-templates/steps/publish-build-artifacts.yml parameters: is1ESPipeline: ${{ parameters.is1ESPipeline }} @@ -129,7 +164,7 @@ jobs: publishLocation: Container artifactName: ReleaseConfigs - - ${{ if eq(parameters.publishAssetsImmediately, 'true') }}: + - ${{ if or(eq(parameters.publishAssetsImmediately, 'true'), eq(parameters.isAssetlessBuild, 'true')) }}: - template: /eng/common/core-templates/post-build/setup-maestro-vars.yml parameters: BARBuildId: ${{ parameters.BARBuildId }} @@ -150,6 +185,7 @@ jobs: -WaitPublishingFinish true -ArtifactsPublishingAdditionalParameters '${{ parameters.artifactsPublishingAdditionalParameters }}' -SymbolPublishingAdditionalParameters '${{ parameters.symbolPublishingAdditionalParameters }}' + -SkipAssetsPublishing '${{ parameters.isAssetlessBuild }}' - ${{ if eq(parameters.enablePublishBuildArtifacts, 'true') }}: - template: /eng/common/core-templates/steps/publish-logs.yml diff --git a/eng/common/core-templates/job/source-build.yml b/eng/common/core-templates/job/source-build.yml index d47f09d58fd9a..d805d5faeb947 100644 --- a/eng/common/core-templates/job/source-build.yml +++ b/eng/common/core-templates/job/source-build.yml @@ -12,9 +12,10 @@ parameters: # The name of the job. This is included in the job ID. # targetRID: '' # The name of the target RID to use, instead of the one auto-detected by Arcade. - # nonPortable: false + # portableBuild: false # Enables non-portable mode. This means a more specific RID (e.g. fedora.32-x64 rather than - # linux-x64), and compiling against distro-provided packages rather than portable ones. + # linux-x64), and compiling against distro-provided packages rather than portable ones. The + # default is portable mode. # skipPublishValidation: false # Disables publishing validation. By default, a check is performed to ensure no packages are # published by source-build. diff --git a/eng/common/core-templates/job/source-index-stage1.yml b/eng/common/core-templates/job/source-index-stage1.yml index 8b833332b3ee9..30530359a5d6d 100644 --- a/eng/common/core-templates/job/source-index-stage1.yml +++ b/eng/common/core-templates/job/source-index-stage1.yml @@ -1,8 +1,5 @@ parameters: runAsPublic: false - sourceIndexUploadPackageVersion: 2.0.0-20250425.2 - sourceIndexProcessBinlogPackageVersion: 1.0.1-20250425.2 - sourceIndexPackageSource: https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json sourceIndexBuildCommand: powershell -NoLogo -NoProfile -ExecutionPolicy Bypass -Command "eng/common/build.ps1 -restore -build -binarylog -ci" preSteps: [] binlogPath: artifacts/log/Debug/Build.binlog @@ -16,12 +13,6 @@ jobs: dependsOn: ${{ parameters.dependsOn }} condition: ${{ parameters.condition }} variables: - - name: SourceIndexUploadPackageVersion - value: ${{ parameters.sourceIndexUploadPackageVersion }} - - name: SourceIndexProcessBinlogPackageVersion - value: ${{ parameters.sourceIndexProcessBinlogPackageVersion }} - - name: SourceIndexPackageSource - value: ${{ parameters.sourceIndexPackageSource }} - name: BinlogPath value: ${{ parameters.binlogPath }} - template: /eng/common/core-templates/variables/pool-providers.yml @@ -34,12 +25,10 @@ jobs: pool: ${{ if eq(variables['System.TeamProject'], 'public') }}: name: $(DncEngPublicBuildPool) - image: 1es-windows-2022-open - os: windows + image: windows.vs2022.amd64.open ${{ if eq(variables['System.TeamProject'], 'internal') }}: name: $(DncEngInternalBuildPool) - image: 1es-windows-2022 - os: windows + image: windows.vs2022.amd64 steps: - ${{ if eq(parameters.is1ESPipeline, '') }}: @@ -47,35 +36,9 @@ jobs: - ${{ each preStep in parameters.preSteps }}: - ${{ preStep }} - - - task: UseDotNet@2 - displayName: Use .NET 8 SDK - inputs: - packageType: sdk - version: 8.0.x - installationPath: $(Agent.TempDirectory)/dotnet - workingDirectory: $(Agent.TempDirectory) - - - script: | - $(Agent.TempDirectory)/dotnet/dotnet tool install BinLogToSln --version $(sourceIndexProcessBinlogPackageVersion) --add-source $(SourceIndexPackageSource) --tool-path $(Agent.TempDirectory)/.source-index/tools - $(Agent.TempDirectory)/dotnet/dotnet tool install UploadIndexStage1 --version $(sourceIndexUploadPackageVersion) --add-source $(SourceIndexPackageSource) --tool-path $(Agent.TempDirectory)/.source-index/tools - displayName: Download Tools - # Set working directory to temp directory so 'dotnet' doesn't try to use global.json and use the repo's sdk. - workingDirectory: $(Agent.TempDirectory) - - script: ${{ parameters.sourceIndexBuildCommand }} displayName: Build Repository - - script: $(Agent.TempDirectory)/.source-index/tools/BinLogToSln -i $(BinlogPath) -r $(Build.SourcesDirectory) -n $(Build.Repository.Name) -o .source-index/stage1output - displayName: Process Binlog into indexable sln - - - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - - task: AzureCLI@2 - displayName: Log in to Azure and upload stage1 artifacts to source index - inputs: - azureSubscription: 'SourceDotNet Stage1 Publish' - addSpnToEnvironment: true - scriptType: 'ps' - scriptLocation: 'inlineScript' - inlineScript: | - $(Agent.TempDirectory)/.source-index/tools/UploadIndexStage1 -i .source-index/stage1output -n $(Build.Repository.Name) -s netsourceindexstage1 -b stage1 + - template: /eng/common/core-templates/steps/source-index-stage1-publish.yml + parameters: + binLogPath: ${{ parameters.binLogPath }} \ No newline at end of file diff --git a/eng/common/core-templates/jobs/codeql-build.yml b/eng/common/core-templates/jobs/codeql-build.yml index f2144252cc65c..693b00b370447 100644 --- a/eng/common/core-templates/jobs/codeql-build.yml +++ b/eng/common/core-templates/jobs/codeql-build.yml @@ -15,7 +15,6 @@ jobs: enablePublishBuildArtifacts: false enablePublishTestResults: false enablePublishBuildAssets: false - enablePublishUsingPipelines: false enableTelemetry: true variables: diff --git a/eng/common/core-templates/jobs/jobs.yml b/eng/common/core-templates/jobs/jobs.yml index ea69be4341c62..bf35b78faa60e 100644 --- a/eng/common/core-templates/jobs/jobs.yml +++ b/eng/common/core-templates/jobs/jobs.yml @@ -5,9 +5,6 @@ parameters: # Optional: Include PublishBuildArtifacts task enablePublishBuildArtifacts: false - # Optional: Enable publishing using release pipelines - enablePublishUsingPipelines: false - # Optional: Enable running the source-build jobs to build repo from source enableSourceBuild: false @@ -30,6 +27,9 @@ parameters: # Optional: Publish the assets as soon as the publish to BAR stage is complete, rather doing so in a separate stage. publishAssetsImmediately: false + # Optional: 🌤️ or not the build has assets it wants to publish to BAR + isAssetlessBuild: false + # Optional: If using publishAssetsImmediately and additional parameters are needed, can be used to send along additional parameters (normally sent to post-build.yml) artifactsPublishingAdditionalParameters: '' signingValidationAdditionalParameters: '' @@ -96,7 +96,7 @@ jobs: ${{ parameter.key }}: ${{ parameter.value }} - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - - ${{ if or(eq(parameters.enablePublishBuildAssets, true), eq(parameters.artifacts.publish.manifests, 'true'), ne(parameters.artifacts.publish.manifests, '')) }}: + - ${{ if or(eq(parameters.enablePublishBuildAssets, true), eq(parameters.artifacts.publish.manifests, 'true'), ne(parameters.artifacts.publish.manifests, ''), eq(parameters.isAssetlessBuild, true)) }}: - template: ../job/publish-build-assets.yml parameters: is1ESPipeline: ${{ parameters.is1ESPipeline }} @@ -112,8 +112,8 @@ jobs: - Source_Build_Complete runAsPublic: ${{ parameters.runAsPublic }} - publishUsingPipelines: ${{ parameters.enablePublishUsingPipelines }} - publishAssetsImmediately: ${{ parameters.publishAssetsImmediately }} + publishAssetsImmediately: ${{ or(parameters.publishAssetsImmediately, parameters.isAssetlessBuild) }} + isAssetlessBuild: ${{ parameters.isAssetlessBuild }} enablePublishBuildArtifacts: ${{ parameters.enablePublishBuildArtifacts }} artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} signingValidationAdditionalParameters: ${{ parameters.signingValidationAdditionalParameters }} diff --git a/eng/common/core-templates/jobs/source-build.yml b/eng/common/core-templates/jobs/source-build.yml index a10ccfbee6de6..df24c948ba127 100644 --- a/eng/common/core-templates/jobs/source-build.yml +++ b/eng/common/core-templates/jobs/source-build.yml @@ -14,7 +14,7 @@ parameters: # This is the default platform provided by Arcade, intended for use by a managed-only repo. defaultManagedPlatform: name: 'Managed' - container: 'mcr.microsoft.com/dotnet-buildtools/prereqs:centos-stream9' + container: 'mcr.microsoft.com/dotnet-buildtools/prereqs:centos-stream-10-amd64' # Defines the platforms on which to run build jobs. One job is created for each platform, and the # object in this array is sent to the job template as 'platform'. If no platforms are specified, diff --git a/eng/common/core-templates/post-build/post-build.yml b/eng/common/core-templates/post-build/post-build.yml index 454fd75c7aff1..a151fd811e3e4 100644 --- a/eng/common/core-templates/post-build/post-build.yml +++ b/eng/common/core-templates/post-build/post-build.yml @@ -44,6 +44,11 @@ parameters: displayName: Publish installers and checksums type: boolean default: true + + - name: requireDefaultChannels + displayName: Fail the build if there are no default channel(s) registrations for the current build + type: boolean + default: false - name: SDLValidationParameters type: object @@ -55,6 +60,11 @@ parameters: artifactNames: '' downloadArtifacts: true + - name: isAssetlessBuild + type: boolean + displayName: Is Assetless Build + default: false + # These parameters let the user customize the call to sdk-task.ps1 for publishing # symbols & general artifacts as well as for signing validation - name: symbolPublishingAdditionalParameters @@ -183,9 +193,6 @@ stages: buildId: $(AzDOBuildId) artifactName: PackageArtifacts checkDownloadedFiles: true - itemPattern: | - ** - !**/Microsoft.SourceBuild.Intermediate.*.nupkg # This is necessary whenever we want to publish/restore to an AzDO private feed # Since sdk-task.ps1 tries to restore packages we need to do this authentication here @@ -312,5 +319,7 @@ stages: -PublishingInfraVersion ${{ parameters.publishingInfraVersion }} -AzdoToken '$(System.AccessToken)' -WaitPublishingFinish true + -RequireDefaultChannels ${{ parameters.requireDefaultChannels }} -ArtifactsPublishingAdditionalParameters '${{ parameters.artifactsPublishingAdditionalParameters }}' -SymbolPublishingAdditionalParameters '${{ parameters.symbolPublishingAdditionalParameters }}' + -SkipAssetsPublishing '${{ parameters.isAssetlessBuild }}' diff --git a/eng/common/core-templates/steps/cleanup-microbuild.yml b/eng/common/core-templates/steps/cleanup-microbuild.yml new file mode 100644 index 0000000000000..c0fdcd3379d73 --- /dev/null +++ b/eng/common/core-templates/steps/cleanup-microbuild.yml @@ -0,0 +1,28 @@ +parameters: + # Enable cleanup tasks for MicroBuild + enableMicrobuild: false + # Enable cleanup tasks for MicroBuild on Mac and Linux + # Will be ignored if 'enableMicrobuild' is false or 'Agent.Os' is 'Windows_NT' + enableMicrobuildForMacAndLinux: false + continueOnError: false + +steps: + - ${{ if eq(parameters.enableMicrobuild, 'true') }}: + - task: MicroBuildCleanup@1 + displayName: Execute Microbuild cleanup tasks + condition: and( + always(), + or( + and( + eq(variables['Agent.Os'], 'Windows_NT'), + in(variables['_SignType'], 'real', 'test') + ), + and( + ${{ eq(parameters.enableMicrobuildForMacAndLinux, true) }}, + ne(variables['Agent.Os'], 'Windows_NT'), + eq(variables['_SignType'], 'real') + ) + )) + continueOnError: ${{ parameters.continueOnError }} + env: + TeamName: $(_TeamName) diff --git a/eng/common/core-templates/steps/generate-sbom.yml b/eng/common/core-templates/steps/generate-sbom.yml index 56a090094824f..44a9636cdff90 100644 --- a/eng/common/core-templates/steps/generate-sbom.yml +++ b/eng/common/core-templates/steps/generate-sbom.yml @@ -5,7 +5,7 @@ # IgnoreDirectories - Directories to ignore for SBOM generation. This will be passed through to the CG component detector. parameters: - PackageVersion: 9.0.0 + PackageVersion: 10.0.0 BuildDropPath: '$(Build.SourcesDirectory)/artifacts' PackageName: '.NET' ManifestDirPath: $(Build.ArtifactStagingDirectory)/sbom diff --git a/eng/common/core-templates/steps/get-delegation-sas.yml b/eng/common/core-templates/steps/get-delegation-sas.yml index 9db5617ea7dea..d2901470a7f0b 100644 --- a/eng/common/core-templates/steps/get-delegation-sas.yml +++ b/eng/common/core-templates/steps/get-delegation-sas.yml @@ -31,16 +31,7 @@ steps: # Calculate the expiration of the SAS token and convert to UTC $expiry = (Get-Date).AddHours(${{ parameters.expiryInHours }}).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ") - # Temporarily work around a helix issue where SAS tokens with / in them will cause incorrect downloads - # of correlation payloads. https://github.com/dotnet/dnceng/issues/3484 - $sas = "" - do { - $sas = az storage container generate-sas --account-name ${{ parameters.storageAccount }} --name ${{ parameters.container }} --permissions ${{ parameters.permissions }} --expiry $expiry --auth-mode login --as-user -o tsv - if ($LASTEXITCODE -ne 0) { - Write-Error "Failed to generate SAS token." - exit 1 - } - } while($sas.IndexOf('/') -ne -1) + $sas = az storage container generate-sas --account-name ${{ parameters.storageAccount }} --name ${{ parameters.container }} --permissions ${{ parameters.permissions }} --expiry $expiry --auth-mode login --as-user -o tsv if ($LASTEXITCODE -ne 0) { Write-Error "Failed to generate SAS token." diff --git a/eng/common/core-templates/steps/install-microbuild.yml b/eng/common/core-templates/steps/install-microbuild.yml new file mode 100644 index 0000000000000..a3540ba00c7eb --- /dev/null +++ b/eng/common/core-templates/steps/install-microbuild.yml @@ -0,0 +1,50 @@ +parameters: + # Enable install tasks for MicroBuild + enableMicrobuild: false + # Enable install tasks for MicroBuild on Mac and Linux + # Will be ignored if 'enableMicrobuild' is false or 'Agent.Os' is 'Windows_NT' + enableMicrobuildForMacAndLinux: false + # Location of the MicroBuild output folder + microBuildOutputFolder: '$(Build.SourcesDirectory)' + continueOnError: false + +steps: + - ${{ if eq(parameters.enableMicrobuild, 'true') }}: + - ${{ if eq(parameters.enableMicrobuildForMacAndLinux, 'true') }}: + # Needed to download the MicroBuild plugin nupkgs on Mac and Linux when nuget.exe is unavailable + - task: UseDotNet@2 + displayName: Install .NET 8.0 SDK for MicroBuild Plugin + inputs: + packageType: sdk + version: 8.0.x + installationPath: ${{ parameters.microBuildOutputFolder }}/.dotnet + workingDirectory: ${{ parameters.microBuildOutputFolder }} + condition: and(succeeded(), ne(variables['Agent.Os'], 'Windows_NT')) + + - task: MicroBuildSigningPlugin@4 + displayName: Install MicroBuild plugin + inputs: + signType: $(_SignType) + zipSources: false + feedSource: https://dnceng.pkgs.visualstudio.com/_packaging/MicroBuildToolset/nuget/v3/index.json + ${{ if and(eq(parameters.enableMicrobuildForMacAndLinux, 'true'), ne(variables['Agent.Os'], 'Windows_NT')) }}: + azureSubscription: 'MicroBuild Signing Task (DevDiv)' + useEsrpCli: true + env: + TeamName: $(_TeamName) + MicroBuildOutputFolderOverride: ${{ parameters.microBuildOutputFolder }} + SYSTEM_ACCESSTOKEN: $(System.AccessToken) + continueOnError: ${{ parameters.continueOnError }} + condition: and( + succeeded(), + or( + and( + eq(variables['Agent.Os'], 'Windows_NT'), + in(variables['_SignType'], 'real', 'test') + ), + and( + ${{ eq(parameters.enableMicrobuildForMacAndLinux, true) }}, + ne(variables['Agent.Os'], 'Windows_NT'), + eq(variables['_SignType'], 'real') + ) + )) diff --git a/eng/common/core-templates/steps/publish-logs.yml b/eng/common/core-templates/steps/publish-logs.yml index 80788c5231912..de24d0087c58b 100644 --- a/eng/common/core-templates/steps/publish-logs.yml +++ b/eng/common/core-templates/steps/publish-logs.yml @@ -34,7 +34,9 @@ steps: '$(akams-client-id)' '$(microsoft-symbol-server-pat)' '$(symweb-symbol-server-pat)' + '$(dnceng-symbol-server-pat)' '$(dn-bot-all-orgs-build-rw-code-rw)' + '$(System.AccessToken)' ${{parameters.CustomSensitiveDataList}} continueOnError: true condition: always() @@ -45,6 +47,7 @@ steps: SourceFolder: '$(Build.SourcesDirectory)/PostBuildLogs' Contents: '**' TargetFolder: '$(Build.ArtifactStagingDirectory)/PostBuildLogs' + condition: always() - template: /eng/common/core-templates/steps/publish-build-artifacts.yml parameters: diff --git a/eng/common/core-templates/steps/source-build.yml b/eng/common/core-templates/steps/source-build.yml index 37133b55b7541..0dde553c3ebfb 100644 --- a/eng/common/core-templates/steps/source-build.yml +++ b/eng/common/core-templates/steps/source-build.yml @@ -19,25 +19,12 @@ steps: set -x df -h - # If file changes are detected, set CopyWipIntoInnerSourceBuildRepo to copy the WIP changes into the inner source build repo. - internalRestoreArgs= - if ! git diff --quiet; then - internalRestoreArgs='/p:CopyWipIntoInnerSourceBuildRepo=true' - # The 'Copy WIP' feature of source build uses git stash to apply changes from the original repo. - # This only works if there is a username/email configured, which won't be the case in most CI runs. - git config --get user.email - if [ $? -ne 0 ]; then - git config user.email dn-bot@microsoft.com - git config user.name dn-bot - fi - fi - # If building on the internal project, the internal storage variable may be available (usually only if needed) # In that case, add variables to allow the download of internal runtimes if the specified versions are not found # in the default public locations. internalRuntimeDownloadArgs= if [ '$(dotnetbuilds-internal-container-read-token-base64)' != '$''(dotnetbuilds-internal-container-read-token-base64)' ]; then - internalRuntimeDownloadArgs='/p:DotNetRuntimeSourceFeed=https://dotnetbuilds.blob.core.windows.net/internal /p:DotNetRuntimeSourceFeedKey=$(dotnetbuilds-internal-container-read-token-base64) --runtimesourcefeed https://dotnetbuilds.blob.core.windows.net/internal --runtimesourcefeedkey $(dotnetbuilds-internal-container-read-token-base64)' + internalRuntimeDownloadArgs='/p:DotNetRuntimeSourceFeed=https://ci.dot.net/internal /p:DotNetRuntimeSourceFeedKey=$(dotnetbuilds-internal-container-read-token-base64) --runtimesourcefeed https://ci.dot.net/internal --runtimesourcefeedkey $(dotnetbuilds-internal-container-read-token-base64)' fi buildConfig=Release @@ -46,85 +33,39 @@ steps: buildConfig='$(_BuildConfig)' fi - officialBuildArgs= - if [ '${{ and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}' = 'True' ]; then - officialBuildArgs='/p:DotNetPublishUsingPipelines=true /p:OfficialBuildId=$(BUILD.BUILDNUMBER)' - fi - targetRidArgs= if [ '${{ parameters.platform.targetRID }}' != '' ]; then targetRidArgs='/p:TargetRid=${{ parameters.platform.targetRID }}' fi - runtimeOsArgs= - if [ '${{ parameters.platform.runtimeOS }}' != '' ]; then - runtimeOsArgs='/p:RuntimeOS=${{ parameters.platform.runtimeOS }}' - fi - - baseOsArgs= - if [ '${{ parameters.platform.baseOS }}' != '' ]; then - baseOsArgs='/p:BaseOS=${{ parameters.platform.baseOS }}' + baseRidArgs= + if [ '${{ parameters.platform.baseRID }}' != '' ]; then + baseRidArgs='/p:BaseRid=${{ parameters.platform.baseRID }}' fi - publishArgs= - if [ '${{ parameters.platform.skipPublishValidation }}' != 'true' ]; then - publishArgs='--publish' - fi - - assetManifestFileName=SourceBuild_RidSpecific.xml - if [ '${{ parameters.platform.name }}' != '' ]; then - assetManifestFileName=SourceBuild_${{ parameters.platform.name }}.xml + portableBuildArgs= + if [ '${{ parameters.platform.portableBuild }}' != '' ]; then + portableBuildArgs='/p:PortableBuild=${{ parameters.platform.portableBuild }}' fi ${{ coalesce(parameters.platform.buildScript, './build.sh') }} --ci \ --configuration $buildConfig \ - --restore --build --pack $publishArgs -bl \ + --restore --build --pack -bl \ + --source-build \ ${{ parameters.platform.buildArguments }} \ - $officialBuildArgs \ $internalRuntimeDownloadArgs \ - $internalRestoreArgs \ $targetRidArgs \ - $runtimeOsArgs \ - $baseOsArgs \ - /p:SourceBuildNonPortable=${{ parameters.platform.nonPortable }} \ - /p:ArcadeBuildFromSource=true \ - /p:DotNetBuildSourceOnly=true \ - /p:DotNetBuildRepo=true \ - /p:AssetManifestFileName=$assetManifestFileName + $baseRidArgs \ + $portableBuildArgs \ displayName: Build -# Upload build logs for diagnosis. -- task: CopyFiles@2 - displayName: Prepare BuildLogs staging directory - inputs: - SourceFolder: '$(Build.SourcesDirectory)' - Contents: | - **/*.log - **/*.binlog - artifacts/sb/prebuilt-report/** - TargetFolder: '$(Build.StagingDirectory)/BuildLogs' - CleanTargetFolder: true - continueOnError: true - condition: succeededOrFailed() - - template: /eng/common/core-templates/steps/publish-pipeline-artifacts.yml parameters: is1ESPipeline: ${{ parameters.is1ESPipeline }} args: displayName: Publish BuildLogs - targetPath: '$(Build.StagingDirectory)/BuildLogs' + targetPath: artifacts/log/${{ coalesce(variables._BuildConfig, 'Release') }} artifactName: BuildLogs_SourceBuild_${{ parameters.platform.name }}_Attempt$(System.JobAttempt) continueOnError: true condition: succeededOrFailed() sbomEnabled: false # we don't need SBOM for logs - -# Manually inject component detection so that we can ignore the source build upstream cache, which contains -# a nupkg cache of input packages (a local feed). -# This path must match the upstream cache path in property 'CurrentRepoSourceBuiltNupkgCacheDir' -# in src\Microsoft.DotNet.Arcade.Sdk\tools\SourceBuild\SourceBuildArcade.targets -- template: /eng/common/core-templates/steps/component-governance.yml - parameters: - displayName: Component Detection (Exclude upstream cache) - is1ESPipeline: ${{ parameters.is1ESPipeline }} - componentGovernanceIgnoreDirectories: '$(Build.SourcesDirectory)/artifacts/sb/src/artifacts/obj/source-built-upstream-cache' - disableComponentGovernance: ${{ eq(variables['System.TeamProject'], 'public') }} diff --git a/eng/common/core-templates/steps/source-index-stage1-publish.yml b/eng/common/core-templates/steps/source-index-stage1-publish.yml new file mode 100644 index 0000000000000..c2917c1efc1cb --- /dev/null +++ b/eng/common/core-templates/steps/source-index-stage1-publish.yml @@ -0,0 +1,35 @@ +parameters: + sourceIndexUploadPackageVersion: 2.0.0-20250425.2 + sourceIndexProcessBinlogPackageVersion: 1.0.1-20250515.1 + sourceIndexPackageSource: https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json + binlogPath: artifacts/log/Debug/Build.binlog + +steps: +- task: UseDotNet@2 + displayName: "Source Index: Use .NET 9 SDK" + inputs: + packageType: sdk + version: 9.0.x + installationPath: $(Agent.TempDirectory)/dotnet + workingDirectory: $(Agent.TempDirectory) + +- script: | + $(Agent.TempDirectory)/dotnet/dotnet tool install BinLogToSln --version ${{parameters.sourceIndexProcessBinlogPackageVersion}} --add-source ${{parameters.SourceIndexPackageSource}} --tool-path $(Agent.TempDirectory)/.source-index/tools + $(Agent.TempDirectory)/dotnet/dotnet tool install UploadIndexStage1 --version ${{parameters.sourceIndexUploadPackageVersion}} --add-source ${{parameters.SourceIndexPackageSource}} --tool-path $(Agent.TempDirectory)/.source-index/tools + displayName: "Source Index: Download netsourceindex Tools" + # Set working directory to temp directory so 'dotnet' doesn't try to use global.json and use the repo's sdk. + workingDirectory: $(Agent.TempDirectory) + +- script: $(Agent.TempDirectory)/.source-index/tools/BinLogToSln -i ${{parameters.BinlogPath}} -r $(Build.SourcesDirectory) -n $(Build.Repository.Name) -o .source-index/stage1output + displayName: "Source Index: Process Binlog into indexable sln" + +- ${{ if and(ne(parameters.runAsPublic, 'true'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: + - task: AzureCLI@2 + displayName: "Source Index: Upload Source Index stage1 artifacts to Azure" + inputs: + azureSubscription: 'SourceDotNet Stage1 Publish' + addSpnToEnvironment: true + scriptType: 'ps' + scriptLocation: 'inlineScript' + inlineScript: | + $(Agent.TempDirectory)/.source-index/tools/UploadIndexStage1 -i .source-index/stage1output -n $(Build.Repository.Name) -s netsourceindexstage1 -b stage1 diff --git a/eng/common/cross/arm64/tizen/tizen.patch b/eng/common/cross/arm64/tizen/tizen.patch index af7c8be059068..2cebc547382e3 100644 --- a/eng/common/cross/arm64/tizen/tizen.patch +++ b/eng/common/cross/arm64/tizen/tizen.patch @@ -5,5 +5,5 @@ diff -u -r a/usr/lib/libc.so b/usr/lib/libc.so Use the shared library, but some functions are only in the static library, so try that secondarily. */ OUTPUT_FORMAT(elf64-littleaarch64) --GROUP ( /lib64/libc.so.6 /usr/lib64/libc_nonshared.a AS_NEEDED ( /lib/ld-linux-aarch64.so.1 ) ) +-GROUP ( /lib64/libc.so.6 /usr/lib64/libc_nonshared.a AS_NEEDED ( /lib64/ld-linux-aarch64.so.1 ) ) +GROUP ( libc.so.6 libc_nonshared.a AS_NEEDED ( ld-linux-aarch64.so.1 ) ) diff --git a/eng/common/cross/armel/armel.jessie.patch b/eng/common/cross/armel/armel.jessie.patch deleted file mode 100644 index 2d2615619351f..0000000000000 --- a/eng/common/cross/armel/armel.jessie.patch +++ /dev/null @@ -1,43 +0,0 @@ -diff -u -r a/usr/include/urcu/uatomic/generic.h b/usr/include/urcu/uatomic/generic.h ---- a/usr/include/urcu/uatomic/generic.h 2014-10-22 15:00:58.000000000 -0700 -+++ b/usr/include/urcu/uatomic/generic.h 2020-10-30 21:38:28.550000000 -0700 -@@ -69,10 +69,10 @@ - #endif - #ifdef UATOMIC_HAS_ATOMIC_SHORT - case 2: -- return __sync_val_compare_and_swap_2(addr, old, _new); -+ return __sync_val_compare_and_swap_2((uint16_t*) addr, old, _new); - #endif - case 4: -- return __sync_val_compare_and_swap_4(addr, old, _new); -+ return __sync_val_compare_and_swap_4((uint32_t*) addr, old, _new); - #if (CAA_BITS_PER_LONG == 64) - case 8: - return __sync_val_compare_and_swap_8(addr, old, _new); -@@ -109,7 +109,7 @@ - return; - #endif - case 4: -- __sync_and_and_fetch_4(addr, val); -+ __sync_and_and_fetch_4((uint32_t*) addr, val); - return; - #if (CAA_BITS_PER_LONG == 64) - case 8: -@@ -148,7 +148,7 @@ - return; - #endif - case 4: -- __sync_or_and_fetch_4(addr, val); -+ __sync_or_and_fetch_4((uint32_t*) addr, val); - return; - #if (CAA_BITS_PER_LONG == 64) - case 8: -@@ -187,7 +187,7 @@ - return __sync_add_and_fetch_2(addr, val); - #endif - case 4: -- return __sync_add_and_fetch_4(addr, val); -+ return __sync_add_and_fetch_4((uint32_t*) addr, val); - #if (CAA_BITS_PER_LONG == 64) - case 8: - return __sync_add_and_fetch_8(addr, val); diff --git a/eng/common/cross/build-android-rootfs.sh b/eng/common/cross/build-android-rootfs.sh index 7e9ba2b75ed35..fbd8d80848a6c 100755 --- a/eng/common/cross/build-android-rootfs.sh +++ b/eng/common/cross/build-android-rootfs.sh @@ -6,10 +6,11 @@ usage() { echo "Creates a toolchain and sysroot used for cross-compiling for Android." echo - echo "Usage: $0 [BuildArch] [ApiLevel]" + echo "Usage: $0 [BuildArch] [ApiLevel] [--ndk NDKVersion]" echo echo "BuildArch is the target architecture of Android. Currently only arm64 is supported." echo "ApiLevel is the target Android API level. API levels usually match to Android releases. See https://source.android.com/source/build-numbers.html" + echo "NDKVersion is the version of Android NDK. The default is r21. See https://developer.android.com/ndk/downloads/revision_history" echo echo "By default, the toolchain and sysroot will be generated in cross/android-rootfs/toolchain/[BuildArch]. You can change this behavior" echo "by setting the TOOLCHAIN_DIR environment variable" @@ -25,10 +26,15 @@ __BuildArch=arm64 __AndroidArch=aarch64 __AndroidToolchain=aarch64-linux-android -for i in "$@" - do - lowerI="$(echo $i | tr "[:upper:]" "[:lower:]")" - case $lowerI in +while :; do + if [[ "$#" -le 0 ]]; then + break + fi + + i=$1 + + lowerI="$(echo $i | tr "[:upper:]" "[:lower:]")" + case $lowerI in -?|-h|--help) usage exit 1 @@ -43,6 +49,10 @@ for i in "$@" __AndroidArch=arm __AndroidToolchain=arm-linux-androideabi ;; + --ndk) + shift + __NDK_Version=$1 + ;; *[0-9]) __ApiLevel=$i ;; @@ -50,8 +60,17 @@ for i in "$@" __UnprocessedBuildArgs="$__UnprocessedBuildArgs $i" ;; esac + shift done +if [[ "$__NDK_Version" == "r21" ]] || [[ "$__NDK_Version" == "r22" ]]; then + __NDK_File_Arch_Spec=-x86_64 + __SysRoot=sysroot +else + __NDK_File_Arch_Spec= + __SysRoot=toolchains/llvm/prebuilt/linux-x86_64/sysroot +fi + # Obtain the location of the bash script to figure out where the root of the repo is. __ScriptBaseDir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" @@ -78,6 +97,7 @@ fi echo "Target API level: $__ApiLevel" echo "Target architecture: $__BuildArch" +echo "NDK version: $__NDK_Version" echo "NDK location: $__NDK_Dir" echo "Target Toolchain location: $__ToolchainDir" @@ -85,8 +105,8 @@ echo "Target Toolchain location: $__ToolchainDir" if [ ! -d $__NDK_Dir ]; then echo Downloading the NDK into $__NDK_Dir mkdir -p $__NDK_Dir - wget -q --progress=bar:force:noscroll --show-progress https://dl.google.com/android/repository/android-ndk-$__NDK_Version-linux-x86_64.zip -O $__CrossDir/android-ndk-$__NDK_Version-linux-x86_64.zip - unzip -q $__CrossDir/android-ndk-$__NDK_Version-linux-x86_64.zip -d $__CrossDir + wget -q --progress=bar:force:noscroll --show-progress https://dl.google.com/android/repository/android-ndk-$__NDK_Version-linux$__NDK_File_Arch_Spec.zip -O $__CrossDir/android-ndk-$__NDK_Version-linux.zip + unzip -q $__CrossDir/android-ndk-$__NDK_Version-linux.zip -d $__CrossDir fi if [ ! -d $__lldb_Dir ]; then @@ -116,16 +136,11 @@ for path in $(wget -qO- https://packages.termux.dev/termux-main-21/dists/stable/ fi done -cp -R "$__TmpDir/data/data/com.termux/files/usr/"* "$__ToolchainDir/sysroot/usr/" +cp -R "$__TmpDir/data/data/com.termux/files/usr/"* "$__ToolchainDir/$__SysRoot/usr/" # Generate platform file for build.sh script to assign to __DistroRid echo "Generating platform file..." -echo "RID=android.${__ApiLevel}-${__BuildArch}" > $__ToolchainDir/sysroot/android_platform - -echo "Now to build coreclr, libraries and installers; run:" -echo ROOTFS_DIR=\$\(realpath $__ToolchainDir/sysroot\) ./build.sh --cross --arch $__BuildArch \ - --subsetCategory coreclr -echo ROOTFS_DIR=\$\(realpath $__ToolchainDir/sysroot\) ./build.sh --cross --arch $__BuildArch \ - --subsetCategory libraries -echo ROOTFS_DIR=\$\(realpath $__ToolchainDir/sysroot\) ./build.sh --cross --arch $__BuildArch \ - --subsetCategory installer +echo "RID=android.${__ApiLevel}-${__BuildArch}" > $__ToolchainDir/$__SysRoot/android_platform + +echo "Now to build coreclr, libraries and host; run:" +echo ROOTFS_DIR=$(realpath $__ToolchainDir/$__SysRoot) ./build.sh clr+libs+host --cross --arch $__BuildArch diff --git a/eng/common/cross/build-rootfs.sh b/eng/common/cross/build-rootfs.sh index 4b5e8d7166bd9..8abfb71f72752 100755 --- a/eng/common/cross/build-rootfs.sh +++ b/eng/common/cross/build-rootfs.sh @@ -5,7 +5,7 @@ set -e usage() { echo "Usage: $0 [BuildArch] [CodeName] [lldbx.y] [llvmx[.y]] [--skipunmount] --rootfsdir ]" - echo "BuildArch can be: arm(default), arm64, armel, armv6, ppc64le, riscv64, s390x, x64, x86" + echo "BuildArch can be: arm(default), arm64, armel, armv6, loongarch64, ppc64le, riscv64, s390x, x64, x86" echo "CodeName - optional, Code name for Linux, can be: xenial(default), zesty, bionic, alpine" echo " for alpine can be specified with version: alpineX.YY or alpineedge" echo " for FreeBSD can be: freebsd13, freebsd14" @@ -15,6 +15,7 @@ usage() echo "llvmx[.y] - optional, LLVM version for LLVM related packages." echo "--skipunmount - optional, will skip the unmount of rootfs folder." echo "--skipsigcheck - optional, will skip package signature checks (allowing untrusted packages)." + echo "--skipemulation - optional, will skip qemu and debootstrap requirement when building environment for debian based systems." echo "--use-mirror - optional, use mirror URL to fetch resources, when available." echo "--jobs N - optional, restrict to N jobs." exit 1 @@ -52,28 +53,27 @@ __UbuntuPackages+=" symlinks" __UbuntuPackages+=" libicu-dev" __UbuntuPackages+=" liblttng-ust-dev" __UbuntuPackages+=" libunwind8-dev" -__UbuntuPackages+=" libnuma-dev" __AlpinePackages+=" gettext-dev" __AlpinePackages+=" icu-dev" __AlpinePackages+=" libunwind-dev" __AlpinePackages+=" lttng-ust-dev" __AlpinePackages+=" compiler-rt" -__AlpinePackages+=" numactl-dev" # runtime libraries' dependencies __UbuntuPackages+=" libcurl4-openssl-dev" __UbuntuPackages+=" libkrb5-dev" __UbuntuPackages+=" libssl-dev" __UbuntuPackages+=" zlib1g-dev" +__UbuntuPackages+=" libbrotli-dev" __AlpinePackages+=" curl-dev" __AlpinePackages+=" krb5-dev" __AlpinePackages+=" openssl-dev" __AlpinePackages+=" zlib-dev" -__FreeBSDBase="13.3-RELEASE" -__FreeBSDPkg="1.17.0" +__FreeBSDBase="13.4-RELEASE" +__FreeBSDPkg="1.21.3" __FreeBSDABI="13" __FreeBSDPackages="libunwind" __FreeBSDPackages+=" icu" @@ -91,18 +91,18 @@ __HaikuPackages="gcc_syslibs" __HaikuPackages+=" gcc_syslibs_devel" __HaikuPackages+=" gmp" __HaikuPackages+=" gmp_devel" -__HaikuPackages+=" icu66" -__HaikuPackages+=" icu66_devel" +__HaikuPackages+=" icu[0-9]+" +__HaikuPackages+=" icu[0-9]*_devel" __HaikuPackages+=" krb5" __HaikuPackages+=" krb5_devel" __HaikuPackages+=" libiconv" __HaikuPackages+=" libiconv_devel" -__HaikuPackages+=" llvm12_libunwind" -__HaikuPackages+=" llvm12_libunwind_devel" +__HaikuPackages+=" llvm[0-9]*_libunwind" +__HaikuPackages+=" llvm[0-9]*_libunwind_devel" __HaikuPackages+=" mpfr" __HaikuPackages+=" mpfr_devel" -__HaikuPackages+=" openssl" -__HaikuPackages+=" openssl_devel" +__HaikuPackages+=" openssl3" +__HaikuPackages+=" openssl3_devel" __HaikuPackages+=" zlib" __HaikuPackages+=" zlib_devel" @@ -128,10 +128,12 @@ __AlpineKeys=' 616adfeb:MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAq0BFD1D4lIxQcsqEpQzU\npNCYM3aP1V/fxxVdT4DWvSI53JHTwHQamKdMWtEXetWVbP5zSROniYKFXd/xrD9X\n0jiGHey3lEtylXRIPxe5s+wXoCmNLcJVnvTcDtwx/ne2NLHxp76lyc25At+6RgE6\nADjLVuoD7M4IFDkAsd8UQ8zM0Dww9SylIk/wgV3ZkifecvgUQRagrNUdUjR56EBZ\nraQrev4hhzOgwelT0kXCu3snbUuNY/lU53CoTzfBJ5UfEJ5pMw1ij6X0r5S9IVsy\nKLWH1hiO0NzU2c8ViUYCly4Fe9xMTFc6u2dy/dxf6FwERfGzETQxqZvSfrRX+GLj\n/QZAXiPg5178hT/m0Y3z5IGenIC/80Z9NCi+byF1WuJlzKjDcF/TU72zk0+PNM/H\nKuppf3JT4DyjiVzNC5YoWJT2QRMS9KLP5iKCSThwVceEEg5HfhQBRT9M6KIcFLSs\nmFjx9kNEEmc1E8hl5IR3+3Ry8G5/bTIIruz14jgeY9u5jhL8Vyyvo41jgt9sLHR1\n/J1TxKfkgksYev7PoX6/ZzJ1ksWKZY5NFoDXTNYUgzFUTOoEaOg3BAQKadb3Qbbq\nXIrxmPBdgrn9QI7NCgfnAY3Tb4EEjs3ON/BNyEhUENcXOH6I1NbcuBQ7g9P73kE4\nVORdoc8MdJ5eoKBpO8Ww8HECAwEAAQ== 616ae350:MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAyduVzi1mWm+lYo2Tqt/0\nXkCIWrDNP1QBMVPrE0/ZlU2bCGSoo2Z9FHQKz/mTyMRlhNqTfhJ5qU3U9XlyGOPJ\npiM+b91g26pnpXJ2Q2kOypSgOMOPA4cQ42PkHBEqhuzssfj9t7x47ppS94bboh46\nxLSDRff/NAbtwTpvhStV3URYkxFG++cKGGa5MPXBrxIp+iZf9GnuxVdST5PGiVGP\nODL/b69sPJQNbJHVquqUTOh5Ry8uuD2WZuXfKf7/C0jC/ie9m2+0CttNu9tMciGM\nEyKG1/Xhk5iIWO43m4SrrT2WkFlcZ1z2JSf9Pjm4C2+HovYpihwwdM/OdP8Xmsnr\nDzVB4YvQiW+IHBjStHVuyiZWc+JsgEPJzisNY0Wyc/kNyNtqVKpX6dRhMLanLmy+\nf53cCSI05KPQAcGj6tdL+D60uKDkt+FsDa0BTAobZ31OsFVid0vCXtsbplNhW1IF\nHwsGXBTVcfXg44RLyL8Lk/2dQxDHNHzAUslJXzPxaHBLmt++2COa2EI1iWlvtznk\nOk9WP8SOAIj+xdqoiHcC4j72BOVVgiITIJNHrbppZCq6qPR+fgXmXa+sDcGh30m6\n9Wpbr28kLMSHiENCWTdsFij+NQTd5S47H7XTROHnalYDuF1RpS+DpQidT5tUimaT\nJZDr++FjKrnnijbyNF8b98UCAwEAAQ== 616db30d:MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAnpUpyWDWjlUk3smlWeA0\nlIMW+oJ38t92CRLHH3IqRhyECBRW0d0aRGtq7TY8PmxjjvBZrxTNDpJT6KUk4LRm\na6A6IuAI7QnNK8SJqM0DLzlpygd7GJf8ZL9SoHSH+gFsYF67Cpooz/YDqWrlN7Vw\ntO00s0B+eXy+PCXYU7VSfuWFGK8TGEv6HfGMALLjhqMManyvfp8hz3ubN1rK3c8C\nUS/ilRh1qckdbtPvoDPhSbTDmfU1g/EfRSIEXBrIMLg9ka/XB9PvWRrekrppnQzP\nhP9YE3x/wbFc5QqQWiRCYyQl/rgIMOXvIxhkfe8H5n1Et4VAorkpEAXdsfN8KSVv\nLSMazVlLp9GYq5SUpqYX3KnxdWBgN7BJoZ4sltsTpHQ/34SXWfu3UmyUveWj7wp0\nx9hwsPirVI00EEea9AbP7NM2rAyu6ukcm4m6ATd2DZJIViq2es6m60AE6SMCmrQF\nwmk4H/kdQgeAELVfGOm2VyJ3z69fQuywz7xu27S6zTKi05Qlnohxol4wVb6OB7qG\nLPRtK9ObgzRo/OPumyXqlzAi/Yvyd1ZQk8labZps3e16bQp8+pVPiumWioMFJDWV\nGZjCmyMSU8V6MB6njbgLHoyg2LCukCAeSjbPGGGYhnKLm1AKSoJh3IpZuqcKCk5C\n8CM1S15HxV78s9dFntEqIokCAwEAAQ== +66ba20fe:MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAtfB12w4ZgqsXWZDfUAV/\n6Y4aHUKIu3q4SXrNZ7CXF9nXoAVYrS7NAxJdAodsY3vPCN0g5O8DFXR+390LdOuQ\n+HsGKCc1k5tX5ZXld37EZNTNSbR0k+NKhd9h6X3u6wqPOx7SIKxwAQR8qeeFq4pP\nrt9GAGlxtuYgzIIcKJPwE0dZlcBCg+GnptCUZXp/38BP1eYC+xTXSL6Muq1etYfg\nodXdb7Yl+2h1IHuOwo5rjgY5kpY7GcAs8AjGk3lDD/av60OTYccknH0NCVSmPoXK\nvrxDBOn0LQRNBLcAfnTKgHrzy0Q5h4TNkkyTgxkoQw5ObDk9nnabTxql732yy9BY\ns+hM9+dSFO1HKeVXreYSA2n1ndF18YAvAumzgyqzB7I4pMHXq1kC/8bONMJxwSkS\nYm6CoXKyavp7RqGMyeVpRC7tV+blkrrUml0BwNkxE+XnwDRB3xDV6hqgWe0XrifD\nYTfvd9ScZQP83ip0r4IKlq4GMv/R5shcCRJSkSZ6QSGshH40JYSoiwJf5FHbj9ND\n7do0UAqebWo4yNx63j/wb2ULorW3AClv0BCFSdPsIrCStiGdpgJDBR2P2NZOCob3\nG9uMj+wJD6JJg2nWqNJxkANXX37Qf8plgzssrhrgOvB0fjjS7GYhfkfmZTJ0wPOw\nA8+KzFseBh4UFGgue78KwgkCAwEAAQ== ' __Keyring= __KeyringFile="/usr/share/keyrings/ubuntu-archive-keyring.gpg" __SkipSigCheck=0 +__SkipEmulation=0 __UseMirror=0 __UnprocessedBuildArgs= @@ -162,9 +164,13 @@ while :; do armel) __BuildArch=armel __UbuntuArch=armel - __UbuntuRepo="http://ftp.debian.org/debian/" - __CodeName=jessie + __UbuntuRepo="http://archive.debian.org/debian/" + __CodeName=buster __KeyringFile="/usr/share/keyrings/debian-archive-keyring.gpg" + __LLDB_Package="liblldb-6.0-dev" + __UbuntuPackages="${__UbuntuPackages// libomp-dev/}" + __UbuntuPackages="${__UbuntuPackages// libomp5/}" + __UbuntuSuites= ;; armv6) __BuildArch=armv6 @@ -180,6 +186,18 @@ while :; do __Keyring="--keyring $__KeyringFile" fi ;; + loongarch64) + __BuildArch=loongarch64 + __AlpineArch=loongarch64 + __QEMUArch=loongarch64 + __UbuntuArch=loong64 + __UbuntuSuites=unreleased + __LLDB_Package="liblldb-19-dev" + + if [[ "$__CodeName" == "sid" ]]; then + __UbuntuRepo="http://ftp.ports.debian.org/debian-ports/" + fi + ;; riscv64) __BuildArch=riscv64 __AlpineArch=riscv64 @@ -264,44 +282,21 @@ while :; do ;; xenial) # Ubuntu 16.04 - if [[ "$__CodeName" != "jessie" ]]; then - __CodeName=xenial - fi - ;; - zesty) # Ubuntu 17.04 - if [[ "$__CodeName" != "jessie" ]]; then - __CodeName=zesty - fi + __CodeName=xenial ;; bionic) # Ubuntu 18.04 - if [[ "$__CodeName" != "jessie" ]]; then - __CodeName=bionic - fi + __CodeName=bionic ;; focal) # Ubuntu 20.04 - if [[ "$__CodeName" != "jessie" ]]; then - __CodeName=focal - fi + __CodeName=focal ;; jammy) # Ubuntu 22.04 - if [[ "$__CodeName" != "jessie" ]]; then - __CodeName=jammy - fi + __CodeName=jammy ;; noble) # Ubuntu 24.04 - if [[ "$__CodeName" != "jessie" ]]; then - __CodeName=noble - fi - if [[ -n "$__LLDB_Package" ]]; then - __LLDB_Package="liblldb-18-dev" - fi - ;; - jessie) # Debian 8 - __CodeName=jessie - __KeyringFile="/usr/share/keyrings/debian-archive-keyring.gpg" - - if [[ -z "$__UbuntuRepo" ]]; then - __UbuntuRepo="http://ftp.debian.org/debian/" + __CodeName=noble + if [[ -z "$__LLDB_Package" ]]; then + __LLDB_Package="liblldb-19-dev" fi ;; stretch) # Debian 9 @@ -319,7 +314,7 @@ while :; do __KeyringFile="/usr/share/keyrings/debian-archive-keyring.gpg" if [[ -z "$__UbuntuRepo" ]]; then - __UbuntuRepo="http://ftp.debian.org/debian/" + __UbuntuRepo="http://archive.debian.org/debian/" fi ;; bullseye) # Debian 11 @@ -340,10 +335,28 @@ while :; do ;; sid) # Debian sid __CodeName=sid - __KeyringFile="/usr/share/keyrings/debian-archive-keyring.gpg" + __UbuntuSuites= - if [[ -z "$__UbuntuRepo" ]]; then - __UbuntuRepo="http://ftp.debian.org/debian/" + # Debian-Ports architectures need different values + case "$__UbuntuArch" in + amd64|arm64|armel|armhf|i386|mips64el|ppc64el|riscv64|s390x) + __KeyringFile="/usr/share/keyrings/debian-archive-keyring.gpg" + + if [[ -z "$__UbuntuRepo" ]]; then + __UbuntuRepo="http://ftp.debian.org/debian/" + fi + ;; + *) + __KeyringFile="/usr/share/keyrings/debian-ports-archive-keyring.gpg" + + if [[ -z "$__UbuntuRepo" ]]; then + __UbuntuRepo="http://ftp.ports.debian.org/debian-ports/" + fi + ;; + esac + + if [[ -e "$__KeyringFile" ]]; then + __Keyring="--keyring $__KeyringFile" fi ;; tizen) @@ -370,7 +383,7 @@ while :; do ;; freebsd14) __CodeName=freebsd - __FreeBSDBase="14.0-RELEASE" + __FreeBSDBase="14.2-RELEASE" __FreeBSDABI="14" __SkipUnmount=1 ;; @@ -388,6 +401,9 @@ while :; do --skipsigcheck) __SkipSigCheck=1 ;; + --skipemulation) + __SkipEmulation=1 + ;; --rootfsdir|-rootfsdir) shift __RootfsDir="$1" @@ -420,16 +436,15 @@ case "$__AlpineVersion" in elif [[ "$__AlpineArch" == "x86" ]]; then __AlpineVersion=3.17 # minimum version that supports lldb-dev __AlpinePackages+=" llvm15-libs" - elif [[ "$__AlpineArch" == "riscv64" ]]; then + elif [[ "$__AlpineArch" == "riscv64" || "$__AlpineArch" == "loongarch64" ]]; then + __AlpineVersion=3.21 # minimum version that supports lldb-dev + __AlpinePackages+=" llvm19-libs" + elif [[ -n "$__AlpineMajorVersion" ]]; then + # use whichever alpine version is provided and select the latest toolchain libs __AlpineLlvmLibsLookup=1 - __AlpineVersion=edge # minimum version with APKINDEX.tar.gz (packages archive) else __AlpineVersion=3.13 # 3.13 to maximize compatibility __AlpinePackages+=" llvm10-libs" - - if [[ "$__AlpineArch" == "armv7" ]]; then - __AlpinePackages="${__AlpinePackages//numactl-dev/}" - fi fi esac @@ -439,15 +454,6 @@ if [[ "$__AlpineVersion" =~ 3\.1[345] ]]; then __AlpinePackages="${__AlpinePackages/compiler-rt/compiler-rt-static}" fi -if [[ "$__BuildArch" == "armel" ]]; then - __LLDB_Package="lldb-3.5-dev" -fi - -if [[ "$__CodeName" == "xenial" && "$__UbuntuArch" == "armhf" ]]; then - # libnuma-dev is not available on armhf for xenial - __UbuntuPackages="${__UbuntuPackages//libnuma-dev/}" -fi - __UbuntuPackages+=" ${__LLDB_Package:-}" if [[ -z "$__UbuntuRepo" ]]; then @@ -496,7 +502,7 @@ if [[ "$__CodeName" == "alpine" ]]; then arch="$(uname -m)" ensureDownloadTool - + if [[ "$__hasWget" == 1 ]]; then wget -P "$__ApkToolsDir" "https://gitlab.alpinelinux.org/api/v4/projects/5/packages/generic/v$__ApkToolsVersion/$arch/apk.static" else @@ -512,11 +518,6 @@ if [[ "$__CodeName" == "alpine" ]]; then echo "$__ApkToolsSHA512SUM $__ApkToolsDir/apk.static" | sha512sum -c chmod +x "$__ApkToolsDir/apk.static" - if [[ -f "/usr/bin/qemu-$__QEMUArch-static" ]]; then - mkdir -p "$__RootfsDir"/usr/bin - cp -v "/usr/bin/qemu-$__QEMUArch-static" "$__RootfsDir/usr/bin" - fi - if [[ "$__AlpineVersion" == "edge" ]]; then version=edge else @@ -536,6 +537,10 @@ if [[ "$__CodeName" == "alpine" ]]; then __ApkSignatureArg="--keys-dir $__ApkKeysDir" fi + if [[ "$__SkipEmulation" == "1" ]]; then + __NoEmulationArg="--no-scripts" + fi + # initialize DB # shellcheck disable=SC2086 "$__ApkToolsDir/apk.static" \ @@ -557,7 +562,7 @@ if [[ "$__CodeName" == "alpine" ]]; then "$__ApkToolsDir/apk.static" \ -X "http://dl-cdn.alpinelinux.org/alpine/$version/main" \ -X "http://dl-cdn.alpinelinux.org/alpine/$version/community" \ - -U $__ApkSignatureArg --root "$__RootfsDir" --arch "$__AlpineArch" \ + -U $__ApkSignatureArg --root "$__RootfsDir" --arch "$__AlpineArch" $__NoEmulationArg \ add $__AlpinePackages rm -r "$__ApkToolsDir" @@ -573,7 +578,7 @@ elif [[ "$__CodeName" == "freebsd" ]]; then curl -SL "https://download.freebsd.org/ftp/releases/${__FreeBSDArch}/${__FreeBSDMachineArch}/${__FreeBSDBase}/base.txz" | tar -C "$__RootfsDir" -Jxf - ./lib ./usr/lib ./usr/libdata ./usr/include ./usr/share/keys ./etc ./bin/freebsd-version fi echo "ABI = \"FreeBSD:${__FreeBSDABI}:${__FreeBSDMachineArch}\"; FINGERPRINTS = \"${__RootfsDir}/usr/share/keys\"; REPOS_DIR = [\"${__RootfsDir}/etc/pkg\"]; REPO_AUTOUPDATE = NO; RUN_SCRIPTS = NO;" > "${__RootfsDir}"/usr/local/etc/pkg.conf - echo "FreeBSD: { url: \"pkg+http://pkg.FreeBSD.org/\${ABI}/quarterly\", mirror_type: \"srv\", signature_type: \"fingerprints\", fingerprints: \"${__RootfsDir}/usr/share/keys/pkg\", enabled: yes }" > "${__RootfsDir}"/etc/pkg/FreeBSD.conf + echo "FreeBSD: { url: \"pkg+http://pkg.FreeBSD.org/\${ABI}/quarterly\", mirror_type: \"srv\", signature_type: \"fingerprints\", fingerprints: \"/usr/share/keys/pkg\", enabled: yes }" > "${__RootfsDir}"/etc/pkg/FreeBSD.conf mkdir -p "$__RootfsDir"/tmp # get and build package manager if [[ "$__hasWget" == 1 ]]; then @@ -681,7 +686,7 @@ elif [[ "$__CodeName" == "haiku" ]]; then ensureDownloadTool - echo "Downloading Haiku package tool" + echo "Downloading Haiku package tools" git clone https://github.com/haiku/haiku-toolchains-ubuntu --depth 1 "$__RootfsDir/tmp/script" if [[ "$__hasWget" == 1 ]]; then wget -O "$__RootfsDir/tmp/download/hosttools.zip" "$("$__RootfsDir/tmp/script/fetch.sh" --hosttools)" @@ -691,34 +696,42 @@ elif [[ "$__CodeName" == "haiku" ]]; then unzip -o "$__RootfsDir/tmp/download/hosttools.zip" -d "$__RootfsDir/tmp/bin" - DepotBaseUrl="https://depot.haiku-os.org/__api/v2/pkg/get-pkg" - HpkgBaseUrl="https://eu.hpkg.haiku-os.org/haiku/master/$__HaikuArch/current" + HaikuBaseUrl="https://eu.hpkg.haiku-os.org/haiku/master/$__HaikuArch/current" + HaikuPortsBaseUrl="https://eu.hpkg.haiku-os.org/haikuports/master/$__HaikuArch/current" + + echo "Downloading HaikuPorts package repository index..." + if [[ "$__hasWget" == 1 ]]; then + wget -P "$__RootfsDir/tmp/download" "$HaikuPortsBaseUrl/repo" + else + curl -SLO --create-dirs --output-dir "$__RootfsDir/tmp/download" "$HaikuPortsBaseUrl/repo" + fi - # Download Haiku packages echo "Downloading Haiku packages" read -ra array <<<"$__HaikuPackages" for package in "${array[@]}"; do echo "Downloading $package..." - # API documented here: https://github.com/haiku/haikudepotserver/blob/master/haikudepotserver-api2/src/main/resources/api2/pkg.yaml#L60 - # The schema here: https://github.com/haiku/haikudepotserver/blob/master/haikudepotserver-api2/src/main/resources/api2/pkg.yaml#L598 + hpkgFilename="$(LD_LIBRARY_PATH="$__RootfsDir/tmp/bin" "$__RootfsDir/tmp/bin/package_repo" list -f "$__RootfsDir/tmp/download/repo" | + grep -E "${package}-" | sort -V | tail -n 1 | xargs)" + if [ -z "$hpkgFilename" ]; then + >&2 echo "ERROR: package $package missing." + exit 1 + fi + echo "Resolved filename: $hpkgFilename..." + hpkgDownloadUrl="$HaikuPortsBaseUrl/packages/$hpkgFilename" if [[ "$__hasWget" == 1 ]]; then - hpkgDownloadUrl="$(wget -qO- --post-data '{"name":"'"$package"'","repositorySourceCode":"haikuports_'$__HaikuArch'","versionType":"LATEST","naturalLanguageCode":"en"}' \ - --header 'Content-Type:application/json' "$DepotBaseUrl" | jq -r '.result.versions[].hpkgDownloadURL')" wget -P "$__RootfsDir/tmp/download" "$hpkgDownloadUrl" else - hpkgDownloadUrl="$(curl -sSL -XPOST --data '{"name":"'"$package"'","repositorySourceCode":"haikuports_'$__HaikuArch'","versionType":"LATEST","naturalLanguageCode":"en"}' \ - --header 'Content-Type:application/json' "$DepotBaseUrl" | jq -r '.result.versions[].hpkgDownloadURL')" curl -SLO --create-dirs --output-dir "$__RootfsDir/tmp/download" "$hpkgDownloadUrl" fi done for package in haiku haiku_devel; do echo "Downloading $package..." if [[ "$__hasWget" == 1 ]]; then - hpkgVersion="$(wget -qO- "$HpkgBaseUrl" | sed -n 's/^.*version: "\([^"]*\)".*$/\1/p')" - wget -P "$__RootfsDir/tmp/download" "$HpkgBaseUrl/packages/$package-$hpkgVersion-1-$__HaikuArch.hpkg" + hpkgVersion="$(wget -qO- "$HaikuBaseUrl" | sed -n 's/^.*version: "\([^"]*\)".*$/\1/p')" + wget -P "$__RootfsDir/tmp/download" "$HaikuBaseUrl/packages/$package-$hpkgVersion-1-$__HaikuArch.hpkg" else - hpkgVersion="$(curl -sSL "$HpkgBaseUrl" | sed -n 's/^.*version: "\([^"]*\)".*$/\1/p')" - curl -SLO --create-dirs --output-dir "$__RootfsDir/tmp/download" "$HpkgBaseUrl/packages/$package-$hpkgVersion-1-$__HaikuArch.hpkg" + hpkgVersion="$(curl -sSL "$HaikuBaseUrl" | sed -n 's/^.*version: "\([^"]*\)".*$/\1/p')" + curl -SLO --create-dirs --output-dir "$__RootfsDir/tmp/download" "$HaikuBaseUrl/packages/$package-$hpkgVersion-1-$__HaikuArch.hpkg" fi done @@ -744,25 +757,67 @@ elif [[ "$__CodeName" == "haiku" ]]; then popd rm -rf "$__RootfsDir/tmp" elif [[ -n "$__CodeName" ]]; then + __Suites="$__CodeName $(for suite in $__UbuntuSuites; do echo -n "$__CodeName-$suite "; done)" + + if [[ "$__SkipEmulation" == "1" ]]; then + if [[ -z "$AR" ]]; then + if command -v ar &>/dev/null; then + AR="$(command -v ar)" + elif command -v llvm-ar &>/dev/null; then + AR="$(command -v llvm-ar)" + else + echo "Unable to find ar or llvm-ar on PATH, add them to PATH or set AR environment variable pointing to the available AR tool" + exit 1 + fi + fi + + PYTHON=${PYTHON_EXECUTABLE:-python3} + + # shellcheck disable=SC2086,SC2046 + echo running "$PYTHON" "$__CrossDir/install-debs.py" --arch "$__UbuntuArch" --mirror "$__UbuntuRepo" --rootfsdir "$__RootfsDir" --artool "$AR" \ + $(for suite in $__Suites; do echo -n "--suite $suite "; done) \ + $__UbuntuPackages + + # shellcheck disable=SC2086,SC2046 + "$PYTHON" "$__CrossDir/install-debs.py" --arch "$__UbuntuArch" --mirror "$__UbuntuRepo" --rootfsdir "$__RootfsDir" --artool "$AR" \ + $(for suite in $__Suites; do echo -n "--suite $suite "; done) \ + $__UbuntuPackages + exit 0 + fi + + __UpdateOptions= if [[ "$__SkipSigCheck" == "0" ]]; then __Keyring="$__Keyring --force-check-gpg" + else + __Keyring= + __UpdateOptions="--allow-unauthenticated --allow-insecure-repositories" fi # shellcheck disable=SC2086 echo running debootstrap "--variant=minbase" $__Keyring --arch "$__UbuntuArch" "$__CodeName" "$__RootfsDir" "$__UbuntuRepo" - debootstrap "--variant=minbase" $__Keyring --arch "$__UbuntuArch" "$__CodeName" "$__RootfsDir" "$__UbuntuRepo" + # shellcheck disable=SC2086 + if ! debootstrap "--variant=minbase" $__Keyring --arch "$__UbuntuArch" "$__CodeName" "$__RootfsDir" "$__UbuntuRepo"; then + echo "debootstrap failed! dumping debootstrap.log" + cat "$__RootfsDir/debootstrap/debootstrap.log" + exit 1 + fi + + rm -rf "$__RootfsDir"/etc/apt/*.{sources,list} "$__RootfsDir"/etc/apt/sources.list.d mkdir -p "$__RootfsDir/etc/apt/sources.list.d/" + + # shellcheck disable=SC2086 cat > "$__RootfsDir/etc/apt/sources.list.d/$__CodeName.sources" < token2) - (token1 < token2) + else: + return -1 if isinstance(token1, str) else 1 + + return len(tokens1) - len(tokens2) + +def compare_debian_versions(version1, version2): + """Compare two Debian package versions.""" + epoch1, upstream1, revision1 = parse_debian_version(version1) + epoch2, upstream2, revision2 = parse_debian_version(version2) + + if epoch1 != epoch2: + return epoch1 - epoch2 + + result = compare_upstream_version(upstream1, upstream2) + if result != 0: + return result + + return compare_upstream_version(revision1, revision2) + +def resolve_dependencies(packages, aliases, desired_packages): + """Recursively resolves dependencies for the desired packages.""" + resolved = [] + to_process = deque(desired_packages) + + while to_process: + current = to_process.popleft() + resolved_package = current if current in packages else aliases.get(current, [None])[0] + + if not resolved_package: + print(f"Error: Package '{current}' was not found in the available packages.") + sys.exit(1) + + if resolved_package not in resolved: + resolved.append(resolved_package) + + deps = packages.get(resolved_package, {}).get("Depends", "") + if deps: + deps = [dep.split(' ')[0] for dep in deps.split(', ') if dep] + for dep in deps: + if dep not in resolved and dep not in to_process and dep in packages: + to_process.append(dep) + + return resolved + +def parse_package_index(content): + """Parses the Packages.gz file and returns package information.""" + packages = {} + aliases = {} + entries = re.split(r'\n\n+', content) + + for entry in entries: + fields = dict(re.findall(r'^(\S+): (.+)$', entry, re.MULTILINE)) + if "Package" in fields: + package_name = fields["Package"] + version = fields.get("Version") + filename = fields.get("Filename") + depends = fields.get("Depends") + provides = fields.get("Provides", None) + + # Only update if package_name is not in packages or if the new version is higher + if package_name not in packages or compare_debian_versions(version, packages[package_name]["Version"]) > 0: + packages[package_name] = { + "Version": version, + "Filename": filename, + "Depends": depends + } + + # Update aliases if package provides any alternatives + if provides: + provides_list = [x.strip() for x in provides.split(",")] + for alias in provides_list: + # Strip version specifiers + alias_name = re.sub(r'\s*\(=.*\)', '', alias) + if alias_name not in aliases: + aliases[alias_name] = [] + if package_name not in aliases[alias_name]: + aliases[alias_name].append(package_name) + + return packages, aliases + +def install_packages(mirror, packages_info, aliases, tmp_dir, extract_dir, ar_tool, desired_packages): + """Downloads .deb files and extracts them.""" + resolved_packages = resolve_dependencies(packages_info, aliases, desired_packages) + print(f"Resolved packages (including dependencies): {resolved_packages}") + + packages_to_download = {} + + for pkg in resolved_packages: + if pkg in packages_info: + packages_to_download[pkg] = packages_info[pkg] + + if pkg in aliases: + for alias in aliases[pkg]: + if alias in packages_info: + packages_to_download[alias] = packages_info[alias] + + asyncio.run(download_deb_files_parallel(mirror, packages_to_download, tmp_dir)) + + package_to_deb_file_map = {} + for pkg in resolved_packages: + pkg_info = packages_info.get(pkg) + if pkg_info: + deb_filename = pkg_info.get("Filename") + if deb_filename: + deb_file_path = os.path.join(tmp_dir, os.path.basename(deb_filename)) + package_to_deb_file_map[pkg] = deb_file_path + + for pkg in reversed(resolved_packages): + deb_file = package_to_deb_file_map.get(pkg) + if deb_file and os.path.exists(deb_file): + extract_deb_file(deb_file, tmp_dir, extract_dir, ar_tool) + + print("All done!") + +def extract_deb_file(deb_file, tmp_dir, extract_dir, ar_tool): + """Extract .deb file contents""" + + os.makedirs(extract_dir, exist_ok=True) + + with tempfile.TemporaryDirectory(dir=tmp_dir) as tmp_subdir: + result = subprocess.run(f"{ar_tool} t {os.path.abspath(deb_file)}", cwd=tmp_subdir, check=True, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + + tar_filename = None + for line in result.stdout.decode().splitlines(): + if line.startswith("data.tar"): + tar_filename = line.strip() + break + + if not tar_filename: + raise FileNotFoundError(f"Could not find 'data.tar.*' in {deb_file}.") + + tar_file_path = os.path.join(tmp_subdir, tar_filename) + print(f"Extracting {tar_filename} from {deb_file}..") + + subprocess.run(f"{ar_tool} p {os.path.abspath(deb_file)} {tar_filename} > {tar_file_path}", check=True, shell=True) + + file_extension = os.path.splitext(tar_file_path)[1].lower() + + if file_extension == ".xz": + mode = "r:xz" + elif file_extension == ".gz": + mode = "r:gz" + elif file_extension == ".zst": + # zstd is not supported by standard library yet + decompressed_tar_path = tar_file_path.replace(".zst", "") + with open(tar_file_path, "rb") as zst_file, open(decompressed_tar_path, "wb") as decompressed_file: + dctx = zstandard.ZstdDecompressor() + dctx.copy_stream(zst_file, decompressed_file) + + tar_file_path = decompressed_tar_path + mode = "r" + else: + raise ValueError(f"Unsupported compression format: {file_extension}") + + with tarfile.open(tar_file_path, mode) as tar: + tar.extractall(path=extract_dir, filter='fully_trusted') + +def finalize_setup(rootfsdir): + lib_dir = os.path.join(rootfsdir, 'lib') + usr_lib_dir = os.path.join(rootfsdir, 'usr', 'lib') + + if os.path.exists(lib_dir): + if os.path.islink(lib_dir): + os.remove(lib_dir) + else: + os.makedirs(usr_lib_dir, exist_ok=True) + + for item in os.listdir(lib_dir): + src = os.path.join(lib_dir, item) + dest = os.path.join(usr_lib_dir, item) + + if os.path.isdir(src): + shutil.copytree(src, dest, dirs_exist_ok=True) + else: + shutil.copy2(src, dest) + + shutil.rmtree(lib_dir) + + os.symlink(usr_lib_dir, lib_dir) + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Generate rootfs for .NET runtime on Debian-like OS") + parser.add_argument("--distro", required=False, help="Distro name (e.g., debian, ubuntu, etc.)") + parser.add_argument("--arch", required=True, help="Architecture (e.g., amd64, loong64, etc.)") + parser.add_argument("--rootfsdir", required=True, help="Destination directory.") + parser.add_argument('--suite', required=True, action='append', help='Specify one or more repository suites to collect index data.') + parser.add_argument("--mirror", required=False, help="Mirror (e.g., http://ftp.debian.org/debian-ports etc.)") + parser.add_argument("--artool", required=False, default="ar", help="ar tool to extract debs (e.g., ar, llvm-ar etc.)") + parser.add_argument("packages", nargs="+", help="List of package names to be installed.") + + args = parser.parse_args() + + if args.mirror is None: + if args.distro == "ubuntu": + args.mirror = "http://archive.ubuntu.com/ubuntu" if args.arch in ["amd64", "i386"] else "http://ports.ubuntu.com/ubuntu-ports" + elif args.distro == "debian": + args.mirror = "http://ftp.debian.org/debian-ports" + else: + raise Exception("Unsupported distro") + + DESIRED_PACKAGES = args.packages + [ # base packages + "dpkg", + "busybox", + "libc-bin", + "base-files", + "base-passwd", + "debianutils" + ] + + print(f"Creating rootfs. rootfsdir: {args.rootfsdir}, distro: {args.distro}, arch: {args.arch}, suites: {args.suite}, mirror: {args.mirror}") + + package_index_content = asyncio.run(download_package_index_parallel(args.mirror, args.arch, args.suite)) + + packages_info, aliases = parse_package_index(package_index_content) + + with tempfile.TemporaryDirectory() as tmp_dir: + install_packages(args.mirror, packages_info, aliases, tmp_dir, args.rootfsdir, args.artool, DESIRED_PACKAGES) + + finalize_setup(args.rootfsdir) diff --git a/eng/common/cross/tizen-fetch.sh b/eng/common/cross/tizen-fetch.sh index 28936ceef3a71..37c3a61f1de80 100644 --- a/eng/common/cross/tizen-fetch.sh +++ b/eng/common/cross/tizen-fetch.sh @@ -156,13 +156,8 @@ fetch_tizen_pkgs() done } -if [ "$TIZEN_ARCH" == "riscv64" ]; then - BASE="Tizen-Base-RISCV" - UNIFIED="Tizen-Unified-RISCV" -else - BASE="Tizen-Base" - UNIFIED="Tizen-Unified" -fi +BASE="Tizen-Base" +UNIFIED="Tizen-Unified" Inform "Initialize ${TIZEN_ARCH} base" fetch_tizen_pkgs_init standard $BASE diff --git a/eng/common/cross/toolchain.cmake b/eng/common/cross/toolchain.cmake index 9a7ecfbd42c5f..0ff85cf0367ee 100644 --- a/eng/common/cross/toolchain.cmake +++ b/eng/common/cross/toolchain.cmake @@ -67,6 +67,13 @@ elseif(TARGET_ARCH_NAME STREQUAL "armv6") else() set(TOOLCHAIN "arm-linux-gnueabihf") endif() +elseif(TARGET_ARCH_NAME STREQUAL "loongarch64") + set(CMAKE_SYSTEM_PROCESSOR "loongarch64") + if(EXISTS ${CROSS_ROOTFS}/usr/lib/gcc/loongarch64-alpine-linux-musl) + set(TOOLCHAIN "loongarch64-alpine-linux-musl") + else() + set(TOOLCHAIN "loongarch64-linux-gnu") + endif() elseif(TARGET_ARCH_NAME STREQUAL "ppc64le") set(CMAKE_SYSTEM_PROCESSOR ppc64le) if(EXISTS ${CROSS_ROOTFS}/usr/lib/gcc/powerpc64le-alpine-linux-musl) @@ -118,7 +125,7 @@ elseif(TARGET_ARCH_NAME STREQUAL "x86") set(TIZEN_TOOLCHAIN "i586-tizen-linux-gnu") endif() else() - message(FATAL_ERROR "Arch is ${TARGET_ARCH_NAME}. Only arm, arm64, armel, armv6, ppc64le, riscv64, s390x, x64 and x86 are supported!") + message(FATAL_ERROR "Arch is ${TARGET_ARCH_NAME}. Only arm, arm64, armel, armv6, loongarch64, ppc64le, riscv64, s390x, x64 and x86 are supported!") endif() if(DEFINED ENV{TOOLCHAIN}) @@ -148,6 +155,25 @@ if(TIZEN) include_directories(SYSTEM ${TIZEN_TOOLCHAIN_PATH}/include/c++/${TIZEN_TOOLCHAIN}) endif() +function(locate_toolchain_exec exec var) + set(TOOLSET_PREFIX ${TOOLCHAIN}-) + string(TOUPPER ${exec} EXEC_UPPERCASE) + if(NOT "$ENV{CLR_${EXEC_UPPERCASE}}" STREQUAL "") + set(${var} "$ENV{CLR_${EXEC_UPPERCASE}}" PARENT_SCOPE) + return() + endif() + + find_program(EXEC_LOCATION_${exec} + NAMES + "${TOOLSET_PREFIX}${exec}${CLR_CMAKE_COMPILER_FILE_NAME_VERSION}" + "${TOOLSET_PREFIX}${exec}") + + if (EXEC_LOCATION_${exec} STREQUAL "EXEC_LOCATION_${exec}-NOTFOUND") + message(FATAL_ERROR "Unable to find toolchain executable. Name: ${exec}, Prefix: ${TOOLSET_PREFIX}.") + endif() + set(${var} ${EXEC_LOCATION_${exec}} PARENT_SCOPE) +endfunction() + if(ANDROID) if(TARGET_ARCH_NAME STREQUAL "arm") set(ANDROID_ABI armeabi-v7a) @@ -178,66 +204,24 @@ elseif(FREEBSD) set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -fuse-ld=lld") elseif(ILLUMOS) set(CMAKE_SYSROOT "${CROSS_ROOTFS}") + set(CMAKE_SYSTEM_PREFIX_PATH "${CROSS_ROOTFS}") + set(CMAKE_C_STANDARD_LIBRARIES "${CMAKE_C_STANDARD_LIBRARIES} -lssp") + set(CMAKE_CXX_STANDARD_LIBRARIES "${CMAKE_CXX_STANDARD_LIBRARIES} -lssp") include_directories(SYSTEM ${CROSS_ROOTFS}/include) - set(TOOLSET_PREFIX ${TOOLCHAIN}-) - function(locate_toolchain_exec exec var) - string(TOUPPER ${exec} EXEC_UPPERCASE) - if(NOT "$ENV{CLR_${EXEC_UPPERCASE}}" STREQUAL "") - set(${var} "$ENV{CLR_${EXEC_UPPERCASE}}" PARENT_SCOPE) - return() - endif() - - find_program(EXEC_LOCATION_${exec} - NAMES - "${TOOLSET_PREFIX}${exec}${CLR_CMAKE_COMPILER_FILE_NAME_VERSION}" - "${TOOLSET_PREFIX}${exec}") - - if (EXEC_LOCATION_${exec} STREQUAL "EXEC_LOCATION_${exec}-NOTFOUND") - message(FATAL_ERROR "Unable to find toolchain executable. Name: ${exec}, Prefix: ${TOOLSET_PREFIX}.") - endif() - set(${var} ${EXEC_LOCATION_${exec}} PARENT_SCOPE) - endfunction() - - set(CMAKE_SYSTEM_PREFIX_PATH "${CROSS_ROOTFS}") - locate_toolchain_exec(gcc CMAKE_C_COMPILER) locate_toolchain_exec(g++ CMAKE_CXX_COMPILER) - - set(CMAKE_C_STANDARD_LIBRARIES "${CMAKE_C_STANDARD_LIBRARIES} -lssp") - set(CMAKE_CXX_STANDARD_LIBRARIES "${CMAKE_CXX_STANDARD_LIBRARIES} -lssp") elseif(HAIKU) set(CMAKE_SYSROOT "${CROSS_ROOTFS}") set(CMAKE_PROGRAM_PATH "${CMAKE_PROGRAM_PATH};${CROSS_ROOTFS}/cross-tools-x86_64/bin") - - set(TOOLSET_PREFIX ${TOOLCHAIN}-) - function(locate_toolchain_exec exec var) - string(TOUPPER ${exec} EXEC_UPPERCASE) - if(NOT "$ENV{CLR_${EXEC_UPPERCASE}}" STREQUAL "") - set(${var} "$ENV{CLR_${EXEC_UPPERCASE}}" PARENT_SCOPE) - return() - endif() - - find_program(EXEC_LOCATION_${exec} - NAMES - "${TOOLSET_PREFIX}${exec}${CLR_CMAKE_COMPILER_FILE_NAME_VERSION}" - "${TOOLSET_PREFIX}${exec}") - - if (EXEC_LOCATION_${exec} STREQUAL "EXEC_LOCATION_${exec}-NOTFOUND") - message(FATAL_ERROR "Unable to find toolchain executable. Name: ${exec}, Prefix: ${TOOLSET_PREFIX}.") - endif() - set(${var} ${EXEC_LOCATION_${exec}} PARENT_SCOPE) - endfunction() - set(CMAKE_SYSTEM_PREFIX_PATH "${CROSS_ROOTFS}") + set(CMAKE_C_STANDARD_LIBRARIES "${CMAKE_C_STANDARD_LIBRARIES} -lssp") + set(CMAKE_CXX_STANDARD_LIBRARIES "${CMAKE_CXX_STANDARD_LIBRARIES} -lssp") locate_toolchain_exec(gcc CMAKE_C_COMPILER) locate_toolchain_exec(g++ CMAKE_CXX_COMPILER) - set(CMAKE_C_STANDARD_LIBRARIES "${CMAKE_C_STANDARD_LIBRARIES} -lssp") - set(CMAKE_CXX_STANDARD_LIBRARIES "${CMAKE_CXX_STANDARD_LIBRARIES} -lssp") - # let CMake set up the correct search paths include(Platform/Haiku) else() @@ -307,7 +291,7 @@ endif() # Specify compile options -if((TARGET_ARCH_NAME MATCHES "^(arm|arm64|armel|armv6|ppc64le|riscv64|s390x|x64|x86)$" AND NOT ANDROID AND NOT FREEBSD) OR ILLUMOS OR HAIKU) +if((TARGET_ARCH_NAME MATCHES "^(arm|arm64|armel|armv6|loongarch64|ppc64le|riscv64|s390x|x64|x86)$" AND NOT ANDROID AND NOT FREEBSD) OR ILLUMOS OR HAIKU) set(CMAKE_C_COMPILER_TARGET ${TOOLCHAIN}) set(CMAKE_CXX_COMPILER_TARGET ${TOOLCHAIN}) set(CMAKE_ASM_COMPILER_TARGET ${TOOLCHAIN}) diff --git a/eng/common/darc-init.sh b/eng/common/darc-init.sh index 36dbd45e1ce86..e889f439b8dc9 100755 --- a/eng/common/darc-init.sh +++ b/eng/common/darc-init.sh @@ -68,7 +68,7 @@ function InstallDarcCli { fi fi - local arcadeServicesSource="https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json" + local arcadeServicesSource="https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/index.json" echo "Installing Darc CLI version $darcVersion..." echo "You may need to restart your command shell if this is the first dotnet tool you have installed." diff --git a/eng/common/native/install-dependencies.sh b/eng/common/native/install-dependencies.sh new file mode 100644 index 0000000000000..477a44f335be3 --- /dev/null +++ b/eng/common/native/install-dependencies.sh @@ -0,0 +1,62 @@ +#!/bin/sh + +set -e + +# This is a simple script primarily used for CI to install necessary dependencies +# +# Usage: +# +# ./install-dependencies.sh + +os="$(echo "$1" | tr "[:upper:]" "[:lower:]")" + +if [ -z "$os" ]; then + . "$(dirname "$0")"/init-os-and-arch.sh +fi + +case "$os" in + linux) + if [ -e /etc/os-release ]; then + . /etc/os-release + fi + + if [ "$ID" = "debian" ] || [ "$ID_LIKE" = "debian" ]; then + apt update + + apt install -y build-essential gettext locales cmake llvm clang lld lldb liblldb-dev libunwind8-dev libicu-dev liblttng-ust-dev \ + libssl-dev libkrb5-dev pigz cpio + + localedef -i en_US -c -f UTF-8 -A /usr/share/locale/locale.alias en_US.UTF-8 + elif [ "$ID" = "fedora" ] || [ "$ID" = "rhel" ] || [ "$ID" = "azurelinux" ]; then + pkg_mgr="$(command -v tdnf 2>/dev/null || command -v dnf)" + $pkg_mgr install -y cmake llvm lld lldb clang python curl libicu-devel openssl-devel krb5-devel lttng-ust-devel pigz cpio + elif [ "$ID" = "alpine" ]; then + apk add build-base cmake bash curl clang llvm-dev lld lldb krb5-dev lttng-ust-dev icu-dev openssl-dev pigz cpio + else + echo "Unsupported distro. distro: $ID" + exit 1 + fi + ;; + + osx|maccatalyst|ios|iossimulator|tvos|tvossimulator) + echo "Installed xcode version: $(xcode-select -p)" + + export HOMEBREW_NO_INSTALL_CLEANUP=1 + export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=1 + # Skip brew update for now, see https://github.com/actions/setup-python/issues/577 + # brew update --preinstall + brew bundle --no-upgrade --file=- < Msbuild engine to use to run build ('dotnet', 'vs', or unspecified)." + Write-Host " -excludeCIBinaryLog When running on CI, allow no binary log (short: -nobl)" Write-Host "" Write-Host "Command line arguments not listed above are passed thru to msbuild." } @@ -34,10 +36,11 @@ function Print-Usage() { function Build([string]$target) { $logSuffix = if ($target -eq 'Execute') { '' } else { ".$target" } $log = Join-Path $LogDir "$task$logSuffix.binlog" + $binaryLogArg = if ($binaryLog) { "/bl:$log" } else { "" } $outputPath = Join-Path $ToolsetDir "$task\" MSBuild $taskProject ` - /bl:$log ` + $binaryLogArg ` /t:$target ` /p:Configuration=$configuration ` /p:RepoRoot=$RepoRoot ` @@ -64,7 +67,7 @@ try { $GlobalJson.tools | Add-Member -Name "vs" -Value (ConvertFrom-Json "{ `"version`": `"16.5`" }") -MemberType NoteProperty } if( -not ($GlobalJson.tools.PSObject.Properties.Name -match "xcopy-msbuild" )) { - $GlobalJson.tools | Add-Member -Name "xcopy-msbuild" -Value "17.12.0" -MemberType NoteProperty + $GlobalJson.tools | Add-Member -Name "xcopy-msbuild" -Value "17.13.0" -MemberType NoteProperty } if ($GlobalJson.tools."xcopy-msbuild".Trim() -ine "none") { $xcopyMSBuildToolsFolder = InitializeXCopyMSBuild $GlobalJson.tools."xcopy-msbuild" -install $true diff --git a/eng/common/sdk-task.sh b/eng/common/sdk-task.sh new file mode 100644 index 0000000000000..2f83adc0269fa --- /dev/null +++ b/eng/common/sdk-task.sh @@ -0,0 +1,116 @@ +#!/usr/bin/env bash + +show_usage() { + echo "Common settings:" + echo " --task Name of Arcade task (name of a project in SdkTasks directory of the Arcade SDK package)" + echo " --restore Restore dependencies" + echo " --verbosity Msbuild verbosity: q[uiet], m[inimal], n[ormal], d[etailed], and diag[nostic]" + echo " --help Print help and exit" + echo "" + + echo "Advanced settings:" + echo " --excludeCIBinarylog Don't output binary log (short: -nobl)" + echo "" + echo "Command line arguments not listed above are passed thru to msbuild." +} + +source="${BASH_SOURCE[0]}" + +# resolve $source until the file is no longer a symlink +while [[ -h "$source" ]]; do + scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" + source="$(readlink "$source")" + # if $source was a relative symlink, we need to resolve it relative to the path where the + # symlink file was located + [[ $source != /* ]] && source="$scriptroot/$source" +done +scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" + +Build() { + local target=$1 + local log_suffix="" + [[ "$target" != "Execute" ]] && log_suffix=".$target" + local log="$log_dir/$task$log_suffix.binlog" + local binaryLogArg="" + [[ $binary_log == true ]] && binaryLogArg="/bl:$log" + local output_path="$toolset_dir/$task/" + + MSBuild "$taskProject" \ + $binaryLogArg \ + /t:"$target" \ + /p:Configuration="$configuration" \ + /p:RepoRoot="$repo_root" \ + /p:BaseIntermediateOutputPath="$output_path" \ + /v:"$verbosity" \ + $properties +} + +binary_log=true +configuration="Debug" +verbosity="minimal" +exclude_ci_binary_log=false +restore=false +help=false +properties='' + +while (($# > 0)); do + lowerI="$(echo $1 | tr "[:upper:]" "[:lower:]")" + case $lowerI in + --task) + task=$2 + shift 2 + ;; + --restore) + restore=true + shift 1 + ;; + --verbosity) + verbosity=$2 + shift 2 + ;; + --excludecibinarylog|--nobl) + binary_log=false + exclude_ci_binary_log=true + shift 1 + ;; + --help) + help=true + shift 1 + ;; + *) + properties="$properties $1" + shift 1 + ;; + esac +done + +ci=true +warnAsError=true + +if $help; then + show_usage + exit 0 +fi + +. "$scriptroot/tools.sh" +InitializeToolset + +if [[ -z "$task" ]]; then + Write-PipelineTelemetryError -Category 'Task' -Name 'MissingTask' -Message "Missing required parameter '-task '" + ExitWithExitCode 1 +fi + +taskProject=$(GetSdkTaskProject "$task") +if [[ ! -e "$taskProject" ]]; then + Write-PipelineTelemetryError -Category 'Task' -Name 'UnknownTask' -Message "Unknown task: $task" + ExitWithExitCode 1 +fi + +if $restore; then + Build "Restore" +fi + +Build "Execute" + + +ExitWithExitCode 0 diff --git a/eng/common/sdl/packages.config b/eng/common/sdl/packages.config index 4585cfd6bba1e..e5f543ea68c27 100644 --- a/eng/common/sdl/packages.config +++ b/eng/common/sdl/packages.config @@ -1,4 +1,4 @@ - + diff --git a/eng/common/templates-official/job/job.yml b/eng/common/templates-official/job/job.yml index 817555505aa60..a8a9432874582 100644 --- a/eng/common/templates-official/job/job.yml +++ b/eng/common/templates-official/job/job.yml @@ -31,6 +31,7 @@ jobs: PathtoPublish: '$(Build.ArtifactStagingDirectory)/artifacts' ArtifactName: ${{ coalesce(parameters.artifacts.publish.artifacts.name , 'Artifacts_$(Agent.Os)_$(_BuildConfig)') }} condition: always() + retryCountOnTaskFailure: 10 # for any logs being locked continueOnError: true - ${{ if and(ne(parameters.artifacts.publish.logs, 'false'), ne(parameters.artifacts.publish.logs, '')) }}: - output: pipelineArtifact @@ -39,6 +40,7 @@ jobs: displayName: 'Publish logs' continueOnError: true condition: always() + retryCountOnTaskFailure: 10 # for any logs being locked sbomEnabled: false # we don't need SBOM for logs - ${{ if eq(parameters.enablePublishBuildArtifacts, true) }}: @@ -46,7 +48,7 @@ jobs: displayName: Publish Logs PathtoPublish: '$(Build.ArtifactStagingDirectory)/artifacts/log/$(_BuildConfig)' publishLocation: Container - ArtifactName: ${{ coalesce(parameters.enablePublishBuildArtifacts.artifactName, '$(Agent.Os)_$(Agent.JobName)' ) }} + ArtifactName: ${{ coalesce(parameters.enablePublishBuildArtifacts.artifactName, '$(Agent.Os)_$(Agent.JobName)_Attempt$(System.JobAttempt)' ) }} continueOnError: true condition: always() sbomEnabled: false # we don't need SBOM for logs diff --git a/eng/common/templates-official/steps/publish-build-artifacts.yml b/eng/common/templates-official/steps/publish-build-artifacts.yml index 100a3fc98493c..fcf6637b2ebcc 100644 --- a/eng/common/templates-official/steps/publish-build-artifacts.yml +++ b/eng/common/templates-official/steps/publish-build-artifacts.yml @@ -24,6 +24,10 @@ parameters: - name: is1ESPipeline type: boolean default: true + +- name: retryCountOnTaskFailure + type: string + default: 10 steps: - ${{ if ne(parameters.is1ESPipeline, true) }}: @@ -38,4 +42,5 @@ steps: PathtoPublish: ${{ parameters.pathToPublish }} ${{ if parameters.artifactName }}: ArtifactName: ${{ parameters.artifactName }} - + ${{ if parameters.retryCountOnTaskFailure }}: + retryCountOnTaskFailure: ${{ parameters.retryCountOnTaskFailure }} diff --git a/eng/common/templates-official/steps/source-index-stage1-publish.yml b/eng/common/templates-official/steps/source-index-stage1-publish.yml new file mode 100644 index 0000000000000..9b8b80942b5c3 --- /dev/null +++ b/eng/common/templates-official/steps/source-index-stage1-publish.yml @@ -0,0 +1,7 @@ +steps: +- template: /eng/common/core-templates/steps/source-index-stage1-publish.yml + parameters: + is1ESPipeline: true + + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates/job/job.yml b/eng/common/templates/job/job.yml index d1aeb92fcea51..7cbf668c22bc0 100644 --- a/eng/common/templates/job/job.yml +++ b/eng/common/templates/job/job.yml @@ -46,6 +46,7 @@ jobs: artifactName: ${{ coalesce(parameters.artifacts.publish.artifacts.name , 'Artifacts_$(Agent.Os)_$(_BuildConfig)') }} continueOnError: true condition: always() + retryCountOnTaskFailure: 10 # for any logs being locked - ${{ if and(ne(parameters.artifacts.publish.logs, 'false'), ne(parameters.artifacts.publish.logs, '')) }}: - template: /eng/common/core-templates/steps/publish-pipeline-artifacts.yml parameters: @@ -56,6 +57,7 @@ jobs: displayName: 'Publish logs' continueOnError: true condition: always() + retryCountOnTaskFailure: 10 # for any logs being locked sbomEnabled: false # we don't need SBOM for logs - ${{ if ne(parameters.enablePublishBuildArtifacts, 'false') }}: @@ -66,7 +68,7 @@ jobs: displayName: Publish Logs pathToPublish: '$(Build.ArtifactStagingDirectory)/artifacts/log/$(_BuildConfig)' publishLocation: Container - artifactName: ${{ coalesce(parameters.enablePublishBuildArtifacts.artifactName, '$(Agent.Os)_$(Agent.JobName)' ) }} + artifactName: ${{ coalesce(parameters.enablePublishBuildArtifacts.artifactName, '$(Agent.Os)_$(Agent.JobName)_Attempt$(System.JobAttempt)' ) }} continueOnError: true condition: always() diff --git a/eng/common/templates/steps/publish-build-artifacts.yml b/eng/common/templates/steps/publish-build-artifacts.yml index 6428a98dfef68..605e602e94d13 100644 --- a/eng/common/templates/steps/publish-build-artifacts.yml +++ b/eng/common/templates/steps/publish-build-artifacts.yml @@ -25,6 +25,10 @@ parameters: type: string default: 'Container' +- name: retryCountOnTaskFailure + type: string + default: 10 + steps: - ${{ if eq(parameters.is1ESPipeline, true) }}: - 'eng/common/templates cannot be referenced from a 1ES managed template': error @@ -37,4 +41,6 @@ steps: PublishLocation: ${{ parameters.publishLocation }} PathtoPublish: ${{ parameters.pathToPublish }} ${{ if parameters.artifactName }}: - ArtifactName: ${{ parameters.artifactName }} \ No newline at end of file + ArtifactName: ${{ parameters.artifactName }} + ${{ if parameters.retryCountOnTaskFailure }}: + retryCountOnTaskFailure: ${{ parameters.retryCountOnTaskFailure }} diff --git a/eng/common/templates/steps/source-index-stage1-publish.yml b/eng/common/templates/steps/source-index-stage1-publish.yml new file mode 100644 index 0000000000000..182cec33a7bb7 --- /dev/null +++ b/eng/common/templates/steps/source-index-stage1-publish.yml @@ -0,0 +1,7 @@ +steps: +- template: /eng/common/core-templates/steps/source-index-stage1-publish.yml + parameters: + is1ESPipeline: false + + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates/steps/vmr-sync.yml b/eng/common/templates/steps/vmr-sync.yml new file mode 100644 index 0000000000000..599afb6186b8f --- /dev/null +++ b/eng/common/templates/steps/vmr-sync.yml @@ -0,0 +1,207 @@ +### These steps synchronize new code from product repositories into the VMR (https://github.com/dotnet/dotnet). +### They initialize the darc CLI and pull the new updates. +### Changes are applied locally onto the already cloned VMR (located in $vmrPath). + +parameters: +- name: targetRef + displayName: Target revision in dotnet/ to synchronize + type: string + default: $(Build.SourceVersion) + +- name: vmrPath + displayName: Path where the dotnet/dotnet is checked out to + type: string + default: $(Agent.BuildDirectory)/vmr + +- name: additionalSyncs + displayName: Optional list of package names whose repo's source will also be synchronized in the local VMR, e.g. NuGet.Protocol + type: object + default: [] + +steps: +- checkout: vmr + displayName: Clone dotnet/dotnet + path: vmr + clean: true + +- checkout: self + displayName: Clone $(Build.Repository.Name) + path: repo + fetchDepth: 0 + +# This step is needed so that when we get a detached HEAD / shallow clone, +# we still pull the commit into the temporary repo clone to use it during the sync. +# Also unshallow the clone so that forwardflow command would work. +- script: | + git branch repo-head + git rev-parse HEAD + displayName: Label PR commit + workingDirectory: $(Agent.BuildDirectory)/repo + +- script: | + vmr_sha=$(grep -oP '(?<=Sha=")[^"]*' $(Agent.BuildDirectory)/repo/eng/Version.Details.xml) + echo "##vso[task.setvariable variable=vmr_sha]$vmr_sha" + displayName: Obtain the vmr sha from Version.Details.xml (Unix) + condition: ne(variables['Agent.OS'], 'Windows_NT') + workingDirectory: $(Agent.BuildDirectory)/repo + +- powershell: | + [xml]$xml = Get-Content -Path $(Agent.BuildDirectory)/repo/eng/Version.Details.xml + $vmr_sha = $xml.SelectSingleNode("//Source").Sha + Write-Output "##vso[task.setvariable variable=vmr_sha]$vmr_sha" + displayName: Obtain the vmr sha from Version.Details.xml (Windows) + condition: eq(variables['Agent.OS'], 'Windows_NT') + workingDirectory: $(Agent.BuildDirectory)/repo + +- script: | + git fetch --all + git checkout $(vmr_sha) + displayName: Checkout VMR at correct sha for repo flow + workingDirectory: ${{ parameters.vmrPath }} + +- script: | + git config --global user.name "dotnet-maestro[bot]" + git config --global user.email "dotnet-maestro[bot]@users.noreply.github.com" + displayName: Set git author to dotnet-maestro[bot] + workingDirectory: ${{ parameters.vmrPath }} + +- script: | + ./eng/common/vmr-sync.sh \ + --vmr ${{ parameters.vmrPath }} \ + --tmp $(Agent.TempDirectory) \ + --azdev-pat '$(dn-bot-all-orgs-code-r)' \ + --ci \ + --debug + + if [ "$?" -ne 0 ]; then + echo "##vso[task.logissue type=error]Failed to synchronize the VMR" + exit 1 + fi + displayName: Sync repo into VMR (Unix) + condition: ne(variables['Agent.OS'], 'Windows_NT') + workingDirectory: $(Agent.BuildDirectory)/repo + +- script: | + git config --global diff.astextplain.textconv echo + git config --system core.longpaths true + displayName: Configure Windows git (longpaths, astextplain) + condition: eq(variables['Agent.OS'], 'Windows_NT') + +- powershell: | + ./eng/common/vmr-sync.ps1 ` + -vmr ${{ parameters.vmrPath }} ` + -tmp $(Agent.TempDirectory) ` + -azdevPat '$(dn-bot-all-orgs-code-r)' ` + -ci ` + -debugOutput + + if ($LASTEXITCODE -ne 0) { + echo "##vso[task.logissue type=error]Failed to synchronize the VMR" + exit 1 + } + displayName: Sync repo into VMR (Windows) + condition: eq(variables['Agent.OS'], 'Windows_NT') + workingDirectory: $(Agent.BuildDirectory)/repo + +- ${{ if eq(variables['Build.Reason'], 'PullRequest') }}: + - task: CopyFiles@2 + displayName: Collect failed patches + condition: failed() + inputs: + SourceFolder: '$(Agent.TempDirectory)' + Contents: '*.patch' + TargetFolder: '$(Build.ArtifactStagingDirectory)/FailedPatches' + + - publish: '$(Build.ArtifactStagingDirectory)/FailedPatches' + artifact: $(System.JobDisplayName)_FailedPatches + displayName: Upload failed patches + condition: failed() + +- ${{ each assetName in parameters.additionalSyncs }}: + # The vmr-sync script ends up staging files in the local VMR so we have to commit those + - script: + git commit --allow-empty -am "Forward-flow $(Build.Repository.Name)" + displayName: Commit local VMR changes + workingDirectory: ${{ parameters.vmrPath }} + + - script: | + set -ex + + echo "Searching for details of asset ${{ assetName }}..." + + # Use darc to get dependencies information + dependencies=$(./.dotnet/dotnet darc get-dependencies --name '${{ assetName }}' --ci) + + # Extract repository URL and commit hash + repository=$(echo "$dependencies" | grep 'Repo:' | sed 's/Repo:[[:space:]]*//' | head -1) + + if [ -z "$repository" ]; then + echo "##vso[task.logissue type=error]Asset ${{ assetName }} not found in the dependency list" + exit 1 + fi + + commit=$(echo "$dependencies" | grep 'Commit:' | sed 's/Commit:[[:space:]]*//' | head -1) + + echo "Updating the VMR from $repository / $commit..." + cd .. + git clone $repository ${{ assetName }} + cd ${{ assetName }} + git checkout $commit + git branch "sync/$commit" + + ./eng/common/vmr-sync.sh \ + --vmr ${{ parameters.vmrPath }} \ + --tmp $(Agent.TempDirectory) \ + --azdev-pat '$(dn-bot-all-orgs-code-r)' \ + --ci \ + --debug + + if [ "$?" -ne 0 ]; then + echo "##vso[task.logissue type=error]Failed to synchronize the VMR" + exit 1 + fi + displayName: Sync ${{ assetName }} into (Unix) + condition: ne(variables['Agent.OS'], 'Windows_NT') + workingDirectory: $(Agent.BuildDirectory)/repo + + - powershell: | + $ErrorActionPreference = 'Stop' + + Write-Host "Searching for details of asset ${{ assetName }}..." + + $dependencies = .\.dotnet\dotnet darc get-dependencies --name '${{ assetName }}' --ci + + $repository = $dependencies | Select-String -Pattern 'Repo:\s+([^\s]+)' | Select-Object -First 1 + $repository -match 'Repo:\s+([^\s]+)' | Out-Null + $repository = $matches[1] + + if ($repository -eq $null) { + Write-Error "Asset ${{ assetName }} not found in the dependency list" + exit 1 + } + + $commit = $dependencies | Select-String -Pattern 'Commit:\s+([^\s]+)' | Select-Object -First 1 + $commit -match 'Commit:\s+([^\s]+)' | Out-Null + $commit = $matches[1] + + Write-Host "Updating the VMR from $repository / $commit..." + cd .. + git clone $repository ${{ assetName }} + cd ${{ assetName }} + git checkout $commit + git branch "sync/$commit" + + .\eng\common\vmr-sync.ps1 ` + -vmr ${{ parameters.vmrPath }} ` + -tmp $(Agent.TempDirectory) ` + -azdevPat '$(dn-bot-all-orgs-code-r)' ` + -ci ` + -debugOutput + + if ($LASTEXITCODE -ne 0) { + echo "##vso[task.logissue type=error]Failed to synchronize the VMR" + exit 1 + } + displayName: Sync ${{ assetName }} into (Windows) + condition: ne(variables['Agent.OS'], 'Windows_NT') + workingDirectory: $(Agent.BuildDirectory)/repo diff --git a/eng/common/templates/vmr-build-pr.yml b/eng/common/templates/vmr-build-pr.yml new file mode 100644 index 0000000000000..670cf32c3bd1f --- /dev/null +++ b/eng/common/templates/vmr-build-pr.yml @@ -0,0 +1,33 @@ +trigger: none +pr: + branches: + include: + - main + - release/* + paths: + exclude: + - documentation/* + - README.md + - CODEOWNERS + +variables: +- template: /eng/common/templates/variables/pool-providers.yml@self + +- name: skipComponentGovernanceDetection # we run CG on internal builds only + value: true + +- name: Codeql.Enabled # we run CodeQL on internal builds only + value: false + +resources: + repositories: + - repository: vmr + type: github + name: dotnet/dotnet + endpoint: dotnet + +stages: +- template: /eng/pipelines/templates/stages/vmr-build.yml@vmr + parameters: + isBuiltFromVmr: false + scope: lite diff --git a/eng/common/tools.ps1 b/eng/common/tools.ps1 index 22b49e09d09b5..c9e39595b586c 100644 --- a/eng/common/tools.ps1 +++ b/eng/common/tools.ps1 @@ -65,10 +65,8 @@ $ErrorActionPreference = 'Stop' # Base-64 encoded SAS token that has permission to storage container described by $runtimeSourceFeed [string]$runtimeSourceFeedKey = if (Test-Path variable:runtimeSourceFeedKey) { $runtimeSourceFeedKey } else { $null } -# True if the build is a product build -[bool]$productBuild = if (Test-Path variable:productBuild) { $productBuild } else { $false } - -[String[]]$properties = if (Test-Path variable:properties) { $properties } else { @() } +# True when the build is running within the VMR. +[bool]$fromVMR = if (Test-Path variable:fromVMR) { $fromVMR } else { $false } function Create-Directory ([string[]] $path) { New-Item -Path $path -Force -ItemType 'Directory' | Out-Null @@ -383,8 +381,8 @@ function InitializeVisualStudioMSBuild([bool]$install, [object]$vsRequirements = # If the version of msbuild is going to be xcopied, # use this version. Version matches a package here: - # https://dev.azure.com/dnceng/public/_artifacts/feed/dotnet-eng/NuGet/Microsoft.DotNet.Arcade.MSBuild.Xcopy/versions/17.12.0 - $defaultXCopyMSBuildVersion = '17.12.0' + # https://dev.azure.com/dnceng/public/_artifacts/feed/dotnet-eng/NuGet/Microsoft.DotNet.Arcade.MSBuild.Xcopy/versions/17.13.0 + $defaultXCopyMSBuildVersion = '17.13.0' if (!$vsRequirements) { if (Get-Member -InputObject $GlobalJson.tools -Name 'vs') { @@ -604,14 +602,7 @@ function InitializeBuildTool() { } $dotnetPath = Join-Path $dotnetRoot (GetExecutableFileName 'dotnet') - # Use override if it exists - commonly set by source-build - if ($null -eq $env:_OverrideArcadeInitializeBuildToolFramework) { - $initializeBuildToolFramework="net9.0" - } else { - $initializeBuildToolFramework=$env:_OverrideArcadeInitializeBuildToolFramework - } - - $buildTool = @{ Path = $dotnetPath; Command = 'msbuild'; Tool = 'dotnet'; Framework = $initializeBuildToolFramework } + $buildTool = @{ Path = $dotnetPath; Command = 'msbuild'; Tool = 'dotnet'; Framework = 'net' } } elseif ($msbuildEngine -eq "vs") { try { $msbuildPath = InitializeVisualStudioMSBuild -install:$restore @@ -620,7 +611,7 @@ function InitializeBuildTool() { ExitWithExitCode 1 } - $buildTool = @{ Path = $msbuildPath; Command = ""; Tool = "vs"; Framework = "net472"; ExcludePrereleaseVS = $excludePrereleaseVS } + $buildTool = @{ Path = $msbuildPath; Command = ""; Tool = "vs"; Framework = "netframework"; ExcludePrereleaseVS = $excludePrereleaseVS } } else { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Unexpected value of -msbuildEngine: '$msbuildEngine'." ExitWithExitCode 1 @@ -653,7 +644,6 @@ function GetNuGetPackageCachePath() { $env:NUGET_PACKAGES = Join-Path $env:UserProfile '.nuget\packages\' } else { $env:NUGET_PACKAGES = Join-Path $RepoRoot '.packages\' - $env:RESTORENOHTTPCACHE = $true } } @@ -779,8 +769,10 @@ function MSBuild() { # new scripts need to work with old packages, so we need to look for the old names/versions (Join-Path $basePath (Join-Path $buildTool.Framework 'Microsoft.DotNet.ArcadeLogging.dll')), (Join-Path $basePath (Join-Path $buildTool.Framework 'Microsoft.DotNet.Arcade.Sdk.dll')), - (Join-Path $basePath (Join-Path net7.0 'Microsoft.DotNet.ArcadeLogging.dll')), - (Join-Path $basePath (Join-Path net7.0 'Microsoft.DotNet.Arcade.Sdk.dll')), + + # This list doesn't need to be updated anymore and can eventually be removed. + (Join-Path $basePath (Join-Path net9.0 'Microsoft.DotNet.ArcadeLogging.dll')), + (Join-Path $basePath (Join-Path net9.0 'Microsoft.DotNet.Arcade.Sdk.dll')), (Join-Path $basePath (Join-Path net8.0 'Microsoft.DotNet.ArcadeLogging.dll')), (Join-Path $basePath (Join-Path net8.0 'Microsoft.DotNet.Arcade.Sdk.dll')) ) @@ -857,8 +849,8 @@ function MSBuild-Core() { } # When running on Azure Pipelines, override the returned exit code to avoid double logging. - # Skip this when the build is a child of the VMR orchestrator build. - if ($ci -and $env:SYSTEM_TEAMPROJECT -ne $null -and !$productBuild -and -not($properties -like "*DotNetBuildRepo=true*")) { + # Skip this when the build is a child of the VMR build. + if ($ci -and $env:SYSTEM_TEAMPROJECT -ne $null -and !$fromVMR) { Write-PipelineSetResult -Result "Failed" -Message "msbuild execution failed." # Exiting with an exit code causes the azure pipelines task to log yet another "noise" error # The above Write-PipelineSetResult will cause the task to be marked as failure without adding yet another error diff --git a/eng/common/tools.sh b/eng/common/tools.sh index 01b09b65796c1..a7e8493151067 100755 --- a/eng/common/tools.sh +++ b/eng/common/tools.sh @@ -5,6 +5,9 @@ # CI mode - set to true on CI server for PR validation build or official build. ci=${ci:-false} +# Build mode +source_build=${source_build:-false} + # Set to true to use the pipelines logger which will enable Azure logging output. # https://github.com/Microsoft/azure-pipelines-tasks/blob/master/docs/authoring/commands.md # This flag is meant as a temporary opt-opt for the feature while validate it across @@ -58,7 +61,8 @@ use_installed_dotnet_cli=${use_installed_dotnet_cli:-true} dotnetInstallScriptVersion=${dotnetInstallScriptVersion:-'v1'} # True to use global NuGet cache instead of restoring packages to repository-local directory. -if [[ "$ci" == true ]]; then +# Keep in sync with NuGetPackageroot in Arcade SDK's RepositoryLayout.props. +if [[ "$ci" == true || "$source_build" == true ]]; then use_global_nuget_cache=${use_global_nuget_cache:-false} else use_global_nuget_cache=${use_global_nuget_cache:-true} @@ -68,8 +72,8 @@ fi runtime_source_feed=${runtime_source_feed:-''} runtime_source_feed_key=${runtime_source_feed_key:-''} -# True if the build is a product build -product_build=${product_build:-false} +# True when the build is running within the VMR. +from_vmr=${from_vmr:-false} # Resolve any symlinks in the given path. function ResolvePath { @@ -339,22 +343,14 @@ function InitializeBuildTool { # return values _InitializeBuildTool="$_InitializeDotNetCli/dotnet" _InitializeBuildToolCommand="msbuild" - # use override if it exists - commonly set by source-build - if [[ "${_OverrideArcadeInitializeBuildToolFramework:-x}" == "x" ]]; then - _InitializeBuildToolFramework="net9.0" - else - _InitializeBuildToolFramework="${_OverrideArcadeInitializeBuildToolFramework}" - fi } -# Set RestoreNoHttpCache as a workaround for https://github.com/NuGet/Home/issues/3116 function GetNuGetPackageCachePath { if [[ -z ${NUGET_PACKAGES:-} ]]; then if [[ "$use_global_nuget_cache" == true ]]; then export NUGET_PACKAGES="$HOME/.nuget/packages/" else export NUGET_PACKAGES="$repo_root/.packages/" - export RESTORENOHTTPCACHE=true fi fi @@ -454,10 +450,12 @@ function MSBuild { # new scripts need to work with old packages, so we need to look for the old names/versions local selectedPath= local possiblePaths=() - possiblePaths+=( "$toolset_dir/$_InitializeBuildToolFramework/Microsoft.DotNet.ArcadeLogging.dll" ) - possiblePaths+=( "$toolset_dir/$_InitializeBuildToolFramework/Microsoft.DotNet.Arcade.Sdk.dll" ) - possiblePaths+=( "$toolset_dir/net7.0/Microsoft.DotNet.ArcadeLogging.dll" ) - possiblePaths+=( "$toolset_dir/net7.0/Microsoft.DotNet.Arcade.Sdk.dll" ) + possiblePaths+=( "$toolset_dir/net/Microsoft.DotNet.ArcadeLogging.dll" ) + possiblePaths+=( "$toolset_dir/net/Microsoft.DotNet.Arcade.Sdk.dll" ) + + # This list doesn't need to be updated anymore and can eventually be removed. + possiblePaths+=( "$toolset_dir/net9.0/Microsoft.DotNet.ArcadeLogging.dll" ) + possiblePaths+=( "$toolset_dir/net9.0/Microsoft.DotNet.Arcade.Sdk.dll" ) possiblePaths+=( "$toolset_dir/net8.0/Microsoft.DotNet.ArcadeLogging.dll" ) possiblePaths+=( "$toolset_dir/net8.0/Microsoft.DotNet.Arcade.Sdk.dll" ) for path in "${possiblePaths[@]}"; do @@ -506,8 +504,8 @@ function MSBuild-Core { echo "Build failed with exit code $exit_code. Check errors above." # When running on Azure Pipelines, override the returned exit code to avoid double logging. - # Skip this when the build is a child of the VMR orchestrator build. - if [[ "$ci" == true && -n ${SYSTEM_TEAMPROJECT:-} && "$product_build" != true && "$properties" != *"DotNetBuildRepo=true"* ]]; then + # Skip this when the build is a child of the VMR build. + if [[ "$ci" == true && -n ${SYSTEM_TEAMPROJECT:-} && "$from_vmr" != true ]]; then Write-PipelineSetResult -result "Failed" -message "msbuild execution failed." # Exiting with an exit code causes the azure pipelines task to log yet another "noise" error # The above Write-PipelineSetResult will cause the task to be marked as failure without adding yet another error @@ -530,6 +528,13 @@ function GetDarc { fi "$eng_root/common/darc-init.sh" --toolpath "$darc_path" $version + darc_tool="$darc_path/darc" +} + +# Returns a full path to an Arcade SDK task project file. +function GetSdkTaskProject { + taskName=$1 + echo "$(dirname $_InitializeToolset)/SdkTasks/$taskName.proj" } ResolvePath "${BASH_SOURCE[0]}" diff --git a/eng/common/vmr-sync.ps1 b/eng/common/vmr-sync.ps1 new file mode 100644 index 0000000000000..97302f3205be9 --- /dev/null +++ b/eng/common/vmr-sync.ps1 @@ -0,0 +1,138 @@ +<# +.SYNOPSIS + +This script is used for synchronizing the current repository into a local VMR. +It pulls the current repository's code into the specified VMR directory for local testing or +Source-Build validation. + +.DESCRIPTION + +The tooling used for synchronization will clone the VMR repository into a temporary folder if +it does not already exist. These clones can be reused in future synchronizations, so it is +recommended to dedicate a folder for this to speed up re-runs. + +.EXAMPLE + Synchronize current repository into a local VMR: + ./vmr-sync.ps1 -vmrDir "$HOME/repos/dotnet" -tmpDir "$HOME/repos/tmp" + +.PARAMETER tmpDir +Required. Path to the temporary folder where repositories will be cloned + +.PARAMETER vmrBranch +Optional. Branch of the 'dotnet/dotnet' repo to synchronize. The VMR will be checked out to this branch + +.PARAMETER azdevPat +Optional. Azure DevOps PAT to use for cloning private repositories. + +.PARAMETER vmrDir +Optional. Path to the dotnet/dotnet repository. When null, gets cloned to the temporary folder + +.PARAMETER debugOutput +Optional. Enables debug logging in the darc vmr command. + +.PARAMETER ci +Optional. Denotes that the script is running in a CI environment. +#> +param ( + [Parameter(Mandatory=$true, HelpMessage="Path to the temporary folder where repositories will be cloned")] + [string][Alias('t', 'tmp')]$tmpDir, + [string][Alias('b', 'branch')]$vmrBranch, + [string]$remote, + [string]$azdevPat, + [string][Alias('v', 'vmr')]$vmrDir, + [switch]$ci, + [switch]$debugOutput +) + +function Fail { + Write-Host "> $($args[0])" -ForegroundColor 'Red' +} + +function Highlight { + Write-Host "> $($args[0])" -ForegroundColor 'Cyan' +} + +$verbosity = 'verbose' +if ($debugOutput) { + $verbosity = 'debug' +} +# Validation + +if (-not $tmpDir) { + Fail "Missing -tmpDir argument. Please specify the path to the temporary folder where the repositories will be cloned" + exit 1 +} + +# Sanitize the input + +if (-not $vmrDir) { + $vmrDir = Join-Path $tmpDir 'dotnet' +} + +if (-not (Test-Path -Path $tmpDir -PathType Container)) { + New-Item -ItemType Directory -Path $tmpDir | Out-Null +} + +# Prepare the VMR + +if (-not (Test-Path -Path $vmrDir -PathType Container)) { + Highlight "Cloning 'dotnet/dotnet' into $vmrDir.." + git clone https://github.com/dotnet/dotnet $vmrDir + + if ($vmrBranch) { + git -C $vmrDir switch -c $vmrBranch + } +} +else { + if ((git -C $vmrDir diff --quiet) -eq $false) { + Fail "There are changes in the working tree of $vmrDir. Please commit or stash your changes" + exit 1 + } + + if ($vmrBranch) { + Highlight "Preparing $vmrDir" + git -C $vmrDir checkout $vmrBranch + git -C $vmrDir pull + } +} + +Set-StrictMode -Version Latest + +# Prepare darc + +Highlight 'Installing .NET, preparing the tooling..' +. .\eng\common\tools.ps1 +$dotnetRoot = InitializeDotNetCli -install:$true +$darc = Get-Darc +$dotnet = "$dotnetRoot\dotnet.exe" + +Highlight "Starting the synchronization of VMR.." + +# Synchronize the VMR +$darcArgs = ( + "vmr", "forwardflow", + "--tmp", $tmpDir, + "--$verbosity", + $vmrDir +) + +if ($ci) { + $darcArgs += ("--ci") +} + +if ($azdevPat) { + $darcArgs += ("--azdev-pat", $azdevPat) +} + +& "$darc" $darcArgs + +if ($LASTEXITCODE -eq 0) { + Highlight "Synchronization succeeded" +} +else { + Fail "Synchronization of repo to VMR failed!" + Fail "'$vmrDir' is left in its last state (re-run of this script will reset it)." + Fail "Please inspect the logs which contain path to the failing patch file (use -debugOutput to get all the details)." + Fail "Once you make changes to the conflicting VMR patch, commit it locally and re-run this script." + exit 1 +} diff --git a/eng/common/vmr-sync.sh b/eng/common/vmr-sync.sh new file mode 100644 index 0000000000000..44239e331c0cc --- /dev/null +++ b/eng/common/vmr-sync.sh @@ -0,0 +1,207 @@ +#!/bin/bash + +### This script is used for synchronizing the current repository into a local VMR. +### It pulls the current repository's code into the specified VMR directory for local testing or +### Source-Build validation. +### +### The tooling used for synchronization will clone the VMR repository into a temporary folder if +### it does not already exist. These clones can be reused in future synchronizations, so it is +### recommended to dedicate a folder for this to speed up re-runs. +### +### USAGE: +### Synchronize current repository into a local VMR: +### ./vmr-sync.sh --tmp "$HOME/repos/tmp" "$HOME/repos/dotnet" +### +### Options: +### -t, --tmp, --tmp-dir PATH +### Required. Path to the temporary folder where repositories will be cloned +### +### -b, --branch, --vmr-branch BRANCH_NAME +### Optional. Branch of the 'dotnet/dotnet' repo to synchronize. The VMR will be checked out to this branch +### +### --debug +### Optional. Turns on the most verbose logging for the VMR tooling +### +### --remote name:URI +### Optional. Additional remote to use during the synchronization +### This can be used to synchronize to a commit from a fork of the repository +### Example: 'runtime:https://github.com/yourfork/runtime' +### +### --azdev-pat +### Optional. Azure DevOps PAT to use for cloning private repositories. +### +### -v, --vmr, --vmr-dir PATH +### Optional. Path to the dotnet/dotnet repository. When null, gets cloned to the temporary folder + +source="${BASH_SOURCE[0]}" + +# resolve $source until the file is no longer a symlink +while [[ -h "$source" ]]; do + scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" + source="$(readlink "$source")" + # if $source was a relative symlink, we need to resolve it relative to the path where the + # symlink file was located + [[ $source != /* ]] && source="$scriptroot/$source" +done +scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" + +function print_help () { + sed -n '/^### /,/^$/p' "$source" | cut -b 5- +} + +COLOR_RED=$(tput setaf 1 2>/dev/null || true) +COLOR_CYAN=$(tput setaf 6 2>/dev/null || true) +COLOR_CLEAR=$(tput sgr0 2>/dev/null || true) +COLOR_RESET=uniquesearchablestring +FAILURE_PREFIX='> ' + +function fail () { + echo "${COLOR_RED}$FAILURE_PREFIX${1//${COLOR_RESET}/${COLOR_RED}}${COLOR_CLEAR}" >&2 +} + +function highlight () { + echo "${COLOR_CYAN}$FAILURE_PREFIX${1//${COLOR_RESET}/${COLOR_CYAN}}${COLOR_CLEAR}" +} + +tmp_dir='' +vmr_dir='' +vmr_branch='' +additional_remotes='' +verbosity=verbose +azdev_pat='' +ci=false + +while [[ $# -gt 0 ]]; do + opt="$(echo "$1" | tr "[:upper:]" "[:lower:]")" + case "$opt" in + -t|--tmp|--tmp-dir) + tmp_dir=$2 + shift + ;; + -v|--vmr|--vmr-dir) + vmr_dir=$2 + shift + ;; + -b|--branch|--vmr-branch) + vmr_branch=$2 + shift + ;; + --remote) + additional_remotes="$additional_remotes $2" + shift + ;; + --azdev-pat) + azdev_pat=$2 + shift + ;; + --ci) + ci=true + ;; + -d|--debug) + verbosity=debug + ;; + -h|--help) + print_help + exit 0 + ;; + *) + fail "Invalid argument: $1" + print_help + exit 1 + ;; + esac + + shift +done + +# Validation + +if [[ -z "$tmp_dir" ]]; then + fail "Missing --tmp-dir argument. Please specify the path to the temporary folder where the repositories will be cloned" + exit 1 +fi + +# Sanitize the input + +if [[ -z "$vmr_dir" ]]; then + vmr_dir="$tmp_dir/dotnet" +fi + +if [[ ! -d "$tmp_dir" ]]; then + mkdir -p "$tmp_dir" +fi + +if [[ "$verbosity" == "debug" ]]; then + set -x +fi + +# Prepare the VMR + +if [[ ! -d "$vmr_dir" ]]; then + highlight "Cloning 'dotnet/dotnet' into $vmr_dir.." + git clone https://github.com/dotnet/dotnet "$vmr_dir" + + if [[ -n "$vmr_branch" ]]; then + git -C "$vmr_dir" switch -c "$vmr_branch" + fi +else + if ! git -C "$vmr_dir" diff --quiet; then + fail "There are changes in the working tree of $vmr_dir. Please commit or stash your changes" + exit 1 + fi + + if [[ -n "$vmr_branch" ]]; then + highlight "Preparing $vmr_dir" + git -C "$vmr_dir" checkout "$vmr_branch" + git -C "$vmr_dir" pull + fi +fi + +set -e + +# Prepare darc + +highlight 'Installing .NET, preparing the tooling..' +source "./eng/common/tools.sh" +InitializeDotNetCli true +GetDarc +dotnetDir=$( cd ./.dotnet/; pwd -P ) +dotnet=$dotnetDir/dotnet + +highlight "Starting the synchronization of VMR.." +set +e + +if [[ -n "$additional_remotes" ]]; then + additional_remotes="--additional-remotes $additional_remotes" +fi + +if [[ -n "$azdev_pat" ]]; then + azdev_pat="--azdev-pat $azdev_pat" +fi + +ci_arg='' +if [[ "$ci" == "true" ]]; then + ci_arg="--ci" +fi + +# Synchronize the VMR + +export DOTNET_ROOT="$dotnetDir" + +"$darc_tool" vmr forwardflow \ + --tmp "$tmp_dir" \ + $azdev_pat \ + --$verbosity \ + $ci_arg \ + $additional_remotes \ + "$vmr_dir" + +if [[ $? == 0 ]]; then + highlight "Synchronization succeeded" +else + fail "Synchronization of repo to VMR failed!" + fail "'$vmr_dir' is left in its last state (re-run of this script will reset it)." + fail "Please inspect the logs which contain path to the failing patch file (use --debug to get all the details)." + fail "Once you make changes to the conflicting VMR patch, commit it locally and re-run this script." + exit 1 +fi diff --git a/eng/config/BannedSymbols.txt b/eng/config/BannedSymbols.txt index 8558e121b5dc2..5e56729488866 100644 --- a/eng/config/BannedSymbols.txt +++ b/eng/config/BannedSymbols.txt @@ -47,14 +47,14 @@ M:Microsoft.CodeAnalysis.Editing.SyntaxEditor.#ctor(Microsoft.CodeAnalysis.Synta M:Microsoft.CodeAnalysis.FileTextLoader.#ctor(System.String,System.Text.Encoding); use WorkspaceFileTextLoader that calls on ITextFactoryService to create SourceText M:Microsoft.CodeAnalysis.CSharp.SyntaxFactory.SyntaxTree(Microsoft.CodeAnalysis.SyntaxNode,Microsoft.CodeAnalysis.ParseOptions,System.String,System.Text.Encoding); Use CSharpSyntaxTree sublass that takes checksum algorithm M:Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ParseSyntaxTree(System.String,Microsoft.CodeAnalysis.ParseOptions,System.String,System.Text.Encoding,System.Threading.CancellationToken); Use CSharpSyntaxTree sublass that takes checksum algorithm -M:Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.CreateWithoutClone(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode); Use CSharpSyntaxTree sublass that takes checksum algorithm +M:Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.CreateWithoutClone(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode,Microsoft.CodeAnalysis.CSharp.CSharpParseOptions); Use CSharpSyntaxTree sublass that takes checksum algorithm M:Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.Create(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode, Microsoft.CodeAnalysis.CSharp.CSharpParseOptions options, System.String path, System.Text.Encoding encoding); Use CSharpSyntaxTree sublass that takes checksum algorithm M:Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(System.String,Microsoft.CodeAnalysis.CSharp.CSharpParseOptions,System.String,System.Text.Encoding,System.Threading.CancellationToken); Use API that takes SourceText M:Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(System.String,Microsoft.CodeAnalysis.CSharp.CSharpParseOptions,System.String,System.Text.Encoding,System.Collections.Immutable.ImmutableDictionary{System.String,Microsoft.CodeAnalysis.ReportDiagnostic},System.Nullable{System.Boolean},System.Threading.CancellationToken); Use API that takes SourceText M:Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.SyntaxTree(Microsoft.CodeAnalysis.SyntaxNode,Microsoft.CodeAnalysis.ParseOptions,System.String,System.Text.Encoding); Use VisualBasicSyntaxTree sublass that takes checksum algorithm M:Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.ParseSyntaxTree(System.String,Microsoft.CodeAnalysis.ParseOptions,System.String,System.Text.Encoding,System.Threading.CancellationToken); Use overload with SourceText M:Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.ParseSyntaxTree(System.String,Microsoft.CodeAnalysis.ParseOptions,System.String,System.Text.Encoding,System.Collections.Immutable.ImmutableDictionary{System.String,Microsoft.CodeAnalysis.ReportDiagnostic},System.Threading.CancellationToken); Use overload with SourceText -M:Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.CreateWithoutClone(Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxNode); Use VisualBasicSyntaxTree sublass that takes checksum algorithm +M:Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.CreateWithoutClone(Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxNode,Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions); Use VisualBasicSyntaxTree sublass that takes checksum algorithm M:Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.Create(Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxNode,Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions,System.String,System.Text.Encoding,System.Collections.Immutable.ImmutableDictionary{System.String,Microsoft.CodeAnalysis.ReportDiagnostic}); Use VisualBasicSyntaxTree sublass that takes checksum algorithm M:Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.Create(Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxNode,Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions,System.String,System.Text.Encoding); Use VisualBasicSyntaxTree sublass that takes checksum algorithm M:Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText(System.String,Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions,System.String,System.Text.Encoding,System.Collections.Immutable.ImmutableDictionary{System.String,Microsoft.CodeAnalysis.ReportDiagnostic},System.Threading.CancellationToken); Use overload with SourceText @@ -70,11 +70,4 @@ M:Microsoft.CodeAnalysis.CodeActions.CodeAction.ComputeOperationsAsync(System.Th M:Microsoft.CodeAnalysis.CodeActions.CodeAction.GetChangedSolutionAsync(CSystem.Threading.CancellationToken); Use overload that takes progress M:Microsoft.CodeAnalysis.CodeActions.CodeAction.GetChangedDocumentAsync(CancellationToken); Use overload that takes progress M:Microsoft.CodeAnalysis.DesktopStrongNameProvider.#ctor(System.Collections.Immutable.ImmutableArray{System.String}); Use overload that takes in temp directory -M:System.Diagnostics.Tracing.EventSource.WriteEvent(System.Int32,System.Object[]); Use WriteEventCore instead -E:Microsoft.CodeAnalysis.Workspace.WorkspaceChanged; Use RegisterWorkspaceChangedHandler instead -E:Microsoft.CodeAnalysis.Workspace.WorkspaceFailed; Use RegisterWorkspaceFailedHandler instead -E:Microsoft.CodeAnalysis.Workspace.DocumentOpened; Use RegisterDocumentOpenedHandler instead -E:Microsoft.CodeAnalysis.Workspace.TextDocumentOpened; Use RegisterTextDocumentOpenedHandler instead -E:Microsoft.CodeAnalysis.Workspace.DocumentClosed; Use RegisterDocumentClosedHandler instead -E:Microsoft.CodeAnalysis.Workspace.TextDocumentClosed; Use RegisterTextDocumentClosedHandler instead -E:Microsoft.CodeAnalysis.Workspace.DocumentActiveContextChanged; Use RegisterDocumentActiveContextChangedHandler instead \ No newline at end of file +M:System.Diagnostics.Tracing.EventSource.WriteEvent(System.Int32,System.Object[]); Use WriteEventCore instead \ No newline at end of file diff --git a/eng/config/PublishData.json b/eng/config/PublishData.json index e2ad4fac15ab1..4ad30f47e3744 100644 --- a/eng/config/PublishData.json +++ b/eng/config/PublishData.json @@ -31,6 +31,7 @@ "Microsoft.Net.Compilers.Toolset.Arm64": "arcade", "Microsoft.Net.Compilers.Toolset.Framework": "arcade", "Microsoft.NETCore.Compilers": "arcade", + "Microsoft.CodeAnalysis.BuildClient": "arcade", "Microsoft.CodeAnalysis.Contracts": "arcade", "Microsoft.CodeAnalysis.Debugging": "arcade", "Microsoft.CodeAnalysis.PooledObjects": "arcade", @@ -175,6 +176,15 @@ "insertionTitlePrefix": "[d17.14]", "insertionCreateDraftPR": false }, + "release/dev-next": { + "nugetKind": [ + "Shipping", + "NonShipping" + ], + "vsBranch": "main", + "insertionTitlePrefix": "[dNext]", + "insertionCreateDraftPR": false + }, "main": { "nugetKind": [ "Shipping", @@ -190,8 +200,8 @@ "NonShipping" ], "vsBranch": "main", - "insertionCreateDraftPR": false, - "insertionTitlePrefix": "[d17.15 P1]" + "insertionCreateDraftPR": true, + "insertionTitlePrefix": "[dNext.1]" } } } diff --git a/eng/pipelines/build-unix-job.yml b/eng/pipelines/build-unix-job.yml index dda4777ae5128..9e3a2f3e14db5 100644 --- a/eng/pipelines/build-unix-job.yml +++ b/eng/pipelines/build-unix-job.yml @@ -27,7 +27,7 @@ jobs: - script: ./eng/build.sh --ci --restore --prepareMachine --binaryLog --configuration ${{ parameters.configuration }} displayName: Restore - - script: ./eng/build.sh --ci --build --publish --pack --prepareMachine --binaryLog --skipDocumentation --configuration ${{ parameters.configuration }} + - script: ./eng/build.sh --ci --build --prepareMachine --binaryLog --skipDocumentation --configuration ${{ parameters.configuration }} displayName: Build - script: ./eng/prepare-tests.sh diff --git a/eng/targets/Settings.props b/eng/targets/Settings.props index d6ed357dadc0c..0da58812dbe3a 100644 --- a/eng/targets/Settings.props +++ b/eng/targets/Settings.props @@ -12,7 +12,7 @@ RoslynDev - $(NoWarn);NU1507 + $(NoWarn);NU1507;NU1510 CommonExtensions Microsoft\VBCSharp\LanguageServices @@ -34,7 +34,7 @@ NON_EXISTENT_FILE - 15.0 + 17.0 $(VisualStudioVersion.Substring($([System.Convert]::ToInt32(0)), $(VisualStudioVersion.IndexOf('.')))) $(VisualStudioReferenceMajorVersion).0.0.0 $(VisualStudioVersion) @@ -137,11 +137,6 @@ true - - - false - - $([System.Environment]::ExpandEnvironmentVariables("%VS$(VisualStudioReferenceMajorVersion)0COMNTOOLS%")) $(DevEnvDir)\..\IDE diff --git a/global.json b/global.json index e72c8a57d82a0..765ae32155ef0 100644 --- a/global.json +++ b/global.json @@ -1,19 +1,19 @@ { "sdk": { - "version": "9.0.106", + "version": "10.0.100-preview.5.25277.114", "allowPrerelease": false, "rollForward": "patch" }, "tools": { - "dotnet": "9.0.106", + "dotnet": "10.0.100-preview.5.25277.114", "vs": { - "version": "17.8.0" + "version": "17.14.0" }, "vswhere": "3.1.7" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "9.0.0-beta.25271.1", - "Microsoft.DotNet.Helix.Sdk": "9.0.0-beta.25271.1", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25259.2", + "Microsoft.DotNet.Helix.Sdk": "10.0.0-beta.25259.2", "Microsoft.Build.Traversal": "3.4.0" } -} +} \ No newline at end of file diff --git a/src/Analyzers/CSharp/Analyzers/AddRequiredParentheses/CSharpAddRequiredExpressionParenthesesDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/AddRequiredParentheses/CSharpAddRequiredExpressionParenthesesDiagnosticAnalyzer.cs index 714016c706018..ebee197687030 100644 --- a/src/Analyzers/CSharp/Analyzers/AddRequiredParentheses/CSharpAddRequiredExpressionParenthesesDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/AddRequiredParentheses/CSharpAddRequiredExpressionParenthesesDiagnosticAnalyzer.cs @@ -13,15 +13,10 @@ namespace Microsoft.CodeAnalysis.CSharp.AddRequiredParentheses; [DiagnosticAnalyzer(LanguageNames.CSharp)] -internal sealed class CSharpAddRequiredExpressionParenthesesDiagnosticAnalyzer : +internal sealed class CSharpAddRequiredExpressionParenthesesDiagnosticAnalyzer() : AbstractAddRequiredParenthesesDiagnosticAnalyzer< - ExpressionSyntax, ExpressionSyntax, SyntaxKind> + ExpressionSyntax, ExpressionSyntax, SyntaxKind>(CSharpExpressionPrecedenceService.Instance) { - public CSharpAddRequiredExpressionParenthesesDiagnosticAnalyzer() - : base(CSharpExpressionPrecedenceService.Instance) - { - } - private static readonly ImmutableArray s_kinds = [ SyntaxKind.AddExpression, @@ -56,7 +51,7 @@ protected override int GetPrecedence(ExpressionSyntax binaryLike) protected override bool IsBinaryLike(ExpressionSyntax node) => node is BinaryExpressionSyntax || - node is IsPatternExpressionSyntax isPattern && isPattern.Pattern is ConstantPatternSyntax; + node is IsPatternExpressionSyntax { Pattern: ConstantPatternSyntax }; protected override (ExpressionSyntax, SyntaxToken, ExpressionSyntax) GetPartsOfBinaryLike(ExpressionSyntax binaryLike) { @@ -66,8 +61,8 @@ protected override (ExpressionSyntax, SyntaxToken, ExpressionSyntax) GetPartsOfB case BinaryExpressionSyntax binaryExpression: return (binaryExpression.Left, binaryExpression.OperatorToken, binaryExpression.Right); - case IsPatternExpressionSyntax isPatternExpression: - return (isPatternExpression.Expression, isPatternExpression.IsKeyword, ((ConstantPatternSyntax)isPatternExpression.Pattern).Expression); + case IsPatternExpressionSyntax { Pattern: ConstantPatternSyntax constantPattern } isPatternExpression: + return (isPatternExpression.Expression, isPatternExpression.IsKeyword, constantPattern.Expression); default: throw ExceptionUtilities.UnexpectedValue(binaryLike); @@ -78,4 +73,7 @@ protected override (ExpressionSyntax, SyntaxToken, ExpressionSyntax) GetPartsOfB => binaryLike.Parent is ConstantPatternSyntax ? binaryLike.Parent.Parent as ExpressionSyntax : binaryLike.Parent as ExpressionSyntax; + + protected override bool IsAsExpression(ExpressionSyntax node) + => node.Kind() == SyntaxKind.AsExpression; } diff --git a/src/Analyzers/CSharp/Analyzers/AddRequiredParentheses/CSharpAddRequiredPatternParenthesesDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/AddRequiredParentheses/CSharpAddRequiredPatternParenthesesDiagnosticAnalyzer.cs index 06314ec57184e..d34ba9a664277 100644 --- a/src/Analyzers/CSharp/Analyzers/AddRequiredParentheses/CSharpAddRequiredPatternParenthesesDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/AddRequiredParentheses/CSharpAddRequiredPatternParenthesesDiagnosticAnalyzer.cs @@ -13,15 +13,10 @@ namespace Microsoft.CodeAnalysis.CSharp.AddRequiredParentheses; [DiagnosticAnalyzer(LanguageNames.CSharp)] -internal sealed class CSharpAddRequiredPatternParenthesesDiagnosticAnalyzer : +internal sealed class CSharpAddRequiredPatternParenthesesDiagnosticAnalyzer() : AbstractAddRequiredParenthesesDiagnosticAnalyzer< - PatternSyntax, BinaryPatternSyntax, SyntaxKind> + PatternSyntax, BinaryPatternSyntax, SyntaxKind>(CSharpPatternPrecedenceService.Instance) { - public CSharpAddRequiredPatternParenthesesDiagnosticAnalyzer() - : base(CSharpPatternPrecedenceService.Instance) - { - } - private static readonly ImmutableArray s_kinds = [SyntaxKind.AndPattern, SyntaxKind.OrPattern]; protected override ImmutableArray GetSyntaxNodeKinds() @@ -41,4 +36,7 @@ protected override (PatternSyntax, SyntaxToken, PatternSyntax) GetPartsOfBinaryL protected override PatternSyntax? TryGetAppropriateParent(BinaryPatternSyntax binaryLike) => binaryLike.Parent as PatternSyntax; + + protected override bool IsAsExpression(BinaryPatternSyntax node) + => false; } diff --git a/src/Analyzers/CSharp/Analyzers/ConvertProgram/ConvertProgramAnalysis_ProgramMain.cs b/src/Analyzers/CSharp/Analyzers/ConvertProgram/ConvertProgramAnalysis_ProgramMain.cs index 160c519dc0e26..2f1bd4366343f 100644 --- a/src/Analyzers/CSharp/Analyzers/ConvertProgram/ConvertProgramAnalysis_ProgramMain.cs +++ b/src/Analyzers/CSharp/Analyzers/ConvertProgram/ConvertProgramAnalysis_ProgramMain.cs @@ -8,7 +8,6 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Analyzers.ConvertProgram; diff --git a/src/Analyzers/CSharp/Analyzers/MatchFolderAndNamespace/CSharpMatchFolderAndNamespaceDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/MatchFolderAndNamespace/CSharpMatchFolderAndNamespaceDiagnosticAnalyzer.cs index 43a22404b99d9..e14c37850a6ad 100644 --- a/src/Analyzers/CSharp/Analyzers/MatchFolderAndNamespace/CSharpMatchFolderAndNamespaceDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/MatchFolderAndNamespace/CSharpMatchFolderAndNamespaceDiagnosticAnalyzer.cs @@ -2,13 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Analyzers.MatchFolderAndNamespace; -using Microsoft.CodeAnalysis.LanguageService; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.CSharp.LanguageService; using System; using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Analyzers.MatchFolderAndNamespace; +using Microsoft.CodeAnalysis.CSharp.LanguageService; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.LanguageService; #if !CODE_STYLE using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; diff --git a/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryImports/CSharpRemoveUnnecessaryImportsDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryImports/CSharpRemoveUnnecessaryImportsDiagnosticAnalyzer.cs index c750fbf86a3d3..370eb44b0a60a 100644 --- a/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryImports/CSharpRemoveUnnecessaryImportsDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryImports/CSharpRemoveUnnecessaryImportsDiagnosticAnalyzer.cs @@ -52,18 +52,16 @@ protected override IEnumerable GetFixableDiagnosticSpans( { Contract.ThrowIfFalse(nodes.Any()); - var nodesContainingUnnecessaryUsings = new HashSet(); - foreach (var node in nodes) + foreach (var node in nodes.Select(n => n.GetAncestors().First(n => n is BaseNamespaceDeclarationSyntax or CompilationUnitSyntax)).Distinct()) { - var nodeContainingUnnecessaryUsings = node.GetAncestors().First(n => n is BaseNamespaceDeclarationSyntax or CompilationUnitSyntax); - if (!nodesContainingUnnecessaryUsings.Add(nodeContainingUnnecessaryUsings)) + if (node is BaseNamespaceDeclarationSyntax namespaceDeclaration) { - continue; + yield return namespaceDeclaration.Usings.GetContainedSpan(); + } + else if (node is CompilationUnitSyntax compilationUnit) + { + yield return compilationUnit.Usings.GetContainedSpan(); } - - yield return nodeContainingUnnecessaryUsings is BaseNamespaceDeclarationSyntax namespaceDeclaration - ? namespaceDeclaration.Usings.GetContainedSpan() - : ((CompilationUnitSyntax)nodeContainingUnnecessaryUsings).Usings.GetContainedSpan(); } } } diff --git a/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryNullableDirective/CSharpRemoveUnnecessaryNullableDirectiveDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryNullableDirective/CSharpRemoveUnnecessaryNullableDirectiveDiagnosticAnalyzer.cs index f2db2bf4e7ad5..544731492afc0 100644 --- a/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryNullableDirective/CSharpRemoveUnnecessaryNullableDirectiveDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryNullableDirective/CSharpRemoveUnnecessaryNullableDirectiveDiagnosticAnalyzer.cs @@ -7,6 +7,7 @@ using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Analyzers.RemoveUnnecessaryNullableDirective; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -18,26 +19,19 @@ namespace Microsoft.CodeAnalysis.RemoveUnnecessaryNullableDirective; [DiagnosticAnalyzer(LanguageNames.CSharp)] -internal sealed class CSharpRemoveUnnecessaryNullableDirectiveDiagnosticAnalyzer - : AbstractBuiltInUnnecessaryCodeStyleDiagnosticAnalyzer +internal sealed class CSharpRemoveUnnecessaryNullableDirectiveDiagnosticAnalyzer() + : AbstractBuiltInUnnecessaryCodeStyleDiagnosticAnalyzer(IDEDiagnosticIds.RemoveUnnecessaryNullableDirectiveDiagnosticId, + EnforceOnBuildValues.RemoveUnnecessaryNullableDirective, + option: null, + fadingOption: null, + new LocalizableResourceString(nameof(CSharpAnalyzersResources.Remove_unnecessary_nullable_directive), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), + new LocalizableResourceString(nameof(CSharpAnalyzersResources.Nullable_directive_is_unnecessary), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { - public CSharpRemoveUnnecessaryNullableDirectiveDiagnosticAnalyzer() - : base(IDEDiagnosticIds.RemoveUnnecessaryNullableDirectiveDiagnosticId, - EnforceOnBuildValues.RemoveUnnecessaryNullableDirective, - option: null, - fadingOption: null, - new LocalizableResourceString(nameof(CSharpAnalyzersResources.Remove_unnecessary_nullable_directive), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), - new LocalizableResourceString(nameof(CSharpAnalyzersResources.Nullable_directive_is_unnecessary), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) - { - } - public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; protected override void InitializeWorker(AnalysisContext context) - { - context.RegisterCompilationStartAction(AnalyzeCompilation); - } + => context.RegisterCompilationStartAction(AnalyzeCompilation); private void AnalyzeCompilation(CompilationStartAnalysisContext context) { diff --git a/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryNullableDirective/NullableImpactingSpanWalker.cs b/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryNullableDirective/NullableImpactingSpanWalker.cs index 38622e35bf702..372636faed961 100644 --- a/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryNullableDirective/NullableImpactingSpanWalker.cs +++ b/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryNullableDirective/NullableImpactingSpanWalker.cs @@ -97,6 +97,10 @@ private static bool IsLanguageRestrictedToNonNullForm(TypeSyntax node) return true; } + // An attribute name cannot itself be nullable. `[CLSCompliant?]` is not a thing. + if (node.IsParentKind(SyntaxKind.Attribute)) + return true; + return false; // If this is Y in X.Y, walk up to X.Y diff --git a/src/Analyzers/CSharp/Analyzers/RemoveUnreachableCode/CSharpRemoveUnreachableCodeDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/RemoveUnreachableCode/CSharpRemoveUnreachableCodeDiagnosticAnalyzer.cs index 85512b65664f8..2b5b01f7f4dcc 100644 --- a/src/Analyzers/CSharp/Analyzers/RemoveUnreachableCode/CSharpRemoveUnreachableCodeDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/RemoveUnreachableCode/CSharpRemoveUnreachableCodeDiagnosticAnalyzer.cs @@ -9,7 +9,6 @@ using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Utilities; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.RemoveUnreachableCode; diff --git a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/AbstractCSharpUseCollectionExpressionDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/AbstractCSharpUseCollectionExpressionDiagnosticAnalyzer.cs index b1daeecb8190a..47b500b4a4c8b 100644 --- a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/AbstractCSharpUseCollectionExpressionDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/AbstractCSharpUseCollectionExpressionDiagnosticAnalyzer.cs @@ -7,7 +7,6 @@ using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Shared.Extensions; using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.UseCollectionInitializer; namespace Microsoft.CodeAnalysis.CSharp.UseCollectionExpression; diff --git a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForBuilderDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForBuilderDiagnosticAnalyzer.cs index 7406d96480af4..3f0c11bdaacc0 100644 --- a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForBuilderDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForBuilderDiagnosticAnalyzer.cs @@ -27,7 +27,7 @@ internal sealed partial class CSharpUseCollectionExpressionForBuilderDiagnosticA EnforceOnBuildValues.UseCollectionExpressionForBuilder) { private const string CreateBuilderName = nameof(ImmutableArray.CreateBuilder); - private const string GetInstanceName = nameof(ArrayBuilder.GetInstance); + private const string GetInstanceName = nameof(ArrayBuilder<>.GetInstance); protected override void InitializeWorker(CodeBlockStartAnalysisContext context, INamedTypeSymbol? expressionType) => context.RegisterSyntaxNodeAction(context => AnalyzeInvocationExpression(context, expressionType), SyntaxKind.InvocationExpression); @@ -117,7 +117,7 @@ void FadeOutCode(SyntaxNodeAnalysisContext context, AnalysisResult analysisResul return null; if (memberAccessExpression.Name.Identifier.ValueText == GetInstanceName && - memberAccessExpression.Expression is not GenericNameSyntax { Identifier.ValueText: nameof(ArrayBuilder) }) + memberAccessExpression.Expression is not GenericNameSyntax { Identifier.ValueText: nameof(ArrayBuilder<>) }) { return null; } @@ -217,12 +217,12 @@ identifierName.Parent is MemberAccessExpressionSyntax(SyntaxKind.SimpleMemberAcc memberAccess.Expression == identifierName && memberAccess.Parent is InvocationExpressionSyntax { ArgumentList.Arguments.Count: 0 } invocationExpression && memberAccess.Name.Identifier.ValueText - is nameof(ImmutableArray.Builder.ToImmutable) - or nameof(ImmutableArray.Builder.MoveToImmutable) - or nameof(ImmutableArray.Builder.ToArray) - or nameof(ArrayBuilder.ToImmutableAndClear) - or nameof(ArrayBuilder.ToImmutableAndFree) - or nameof(ArrayBuilder.ToArrayAndFree) + is nameof(ImmutableArray<>.Builder.ToImmutable) + or nameof(ImmutableArray<>.Builder.MoveToImmutable) + or nameof(ImmutableArray<>.Builder.ToArray) + or nameof(ArrayBuilder<>.ToImmutableAndClear) + or nameof(ArrayBuilder<>.ToImmutableAndFree) + or nameof(ArrayBuilder<>.ToArrayAndFree) or nameof(Enumerable.ToList)) { return invocationExpression; diff --git a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForFluentDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForFluentDiagnosticAnalyzer.cs index db35d9137dbb4..c2d735d8cf6a9 100644 --- a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForFluentDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForFluentDiagnosticAnalyzer.cs @@ -13,7 +13,6 @@ using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.CodeStyle; -using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UseCollectionExpression; using Microsoft.CodeAnalysis.UseCollectionInitializer; @@ -21,8 +20,8 @@ namespace Microsoft.CodeAnalysis.CSharp.UseCollectionExpression; -using static UseCollectionExpressionHelpers; using static SyntaxFactory; +using static UseCollectionExpressionHelpers; using FluentState = UpdateExpressionState; [DiagnosticAnalyzer(LanguageNames.CSharp)] @@ -42,24 +41,24 @@ internal sealed partial class CSharpUseCollectionExpressionForFluentDiagnosticAn private static readonly ImmutableArray s_suffixes = [ nameof(Array), - nameof(Span), - nameof(ReadOnlySpan), - nameof(System.Collections.Generic.List), - nameof(HashSet), - nameof(LinkedList), - nameof(Queue), - nameof(SortedSet), - nameof(Stack), - nameof(ICollection), - nameof(IReadOnlyCollection), - nameof(IList), - nameof(IReadOnlyList), - nameof(ImmutableArray), - nameof(ImmutableHashSet), - nameof(ImmutableList), - nameof(ImmutableQueue), - nameof(ImmutableSortedSet), - nameof(ImmutableStack), + nameof(Span<>), + nameof(ReadOnlySpan<>), + nameof(System.Collections.Generic.List<>), + nameof(HashSet<>), + nameof(LinkedList<>), + nameof(Queue<>), + nameof(SortedSet<>), + nameof(Stack<>), + nameof(ICollection<>), + nameof(IReadOnlyCollection<>), + nameof(IList<>), + nameof(IReadOnlyList<>), + nameof(ImmutableArray<>), + nameof(ImmutableHashSet<>), + nameof(ImmutableList<>), + nameof(ImmutableQueue<>), + nameof(ImmutableSortedSet<>), + nameof(ImmutableStack<>), nameof(System.Collections.Immutable), ]; diff --git a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForNewDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForNewDiagnosticAnalyzer.cs index 24db63134a0ba..cd9f1f005d860 100644 --- a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForNewDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForNewDiagnosticAnalyzer.cs @@ -53,7 +53,7 @@ private void AnalyzeBaseObjectCreationExpression( var symbol = semanticModel.GetSymbolInfo(objectCreationExpression, cancellationToken).Symbol; if (symbol is not IMethodSymbol { MethodKind: MethodKind.Constructor, Parameters: [var constructorParameter] } || - constructorParameter.Type.Name != nameof(IEnumerable)) + constructorParameter.Type.Name != nameof(IEnumerable<>)) { return; } diff --git a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/UseCollectionExpressionHelpers.cs b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/UseCollectionExpressionHelpers.cs index 3ad3e5986aad9..4a6ff87c46508 100644 --- a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/UseCollectionExpressionHelpers.cs +++ b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/UseCollectionExpressionHelpers.cs @@ -193,11 +193,11 @@ bool IsSafeConversionWhenTypesDoNotMatch(out bool changesSemantics) var convertedType = originalTypeInfo.ConvertedType; var convertedToReadOnlySpan = - convertedType.Name == nameof(ReadOnlySpan) && + convertedType.Name == nameof(ReadOnlySpan<>) && convertedType.OriginalDefinition.Equals(compilation.ReadOnlySpanOfTType()); var convertedToSpan = - convertedType.Name == nameof(Span) && + convertedType.Name == nameof(Span<>) && convertedType.OriginalDefinition.Equals(compilation.SpanOfTType()); // ReadOnlySpan x = stackalloc[] ... @@ -206,7 +206,7 @@ bool IsSafeConversionWhenTypesDoNotMatch(out bool changesSemantics) // restrictive than Span var isSpanToReadOnlySpan = convertedToReadOnlySpan && - type.Name == nameof(Span) && + type.Name == nameof(Span<>) && type.OriginalDefinition.Equals(compilation.SpanOfTType()) && convertedType.GetTypeArguments()[0].Equals(type.GetTypeArguments()[0]); if (isSpanToReadOnlySpan) @@ -264,7 +264,7 @@ bool IsSafeConversionWhenTypesDoNotMatch(out bool changesSemantics) // disallow converting those types to ensure semantics are preserved. We do this even though // allowSemanticsChange is true because this will basically be certain to break semantics, as opposed to // the more common case where semantics may change slightly, but likely not in a way that breaks code. - if (type.Name is nameof(ObservableCollection) or nameof(ReadOnlyObservableCollection)) + if (type.Name is nameof(ObservableCollection<>) or nameof(ReadOnlyObservableCollection<>)) return false; // If the original expression was creating a set, but is being assigned to one of the well known @@ -933,7 +933,7 @@ bool IsCompatibleSignatureAndArguments( { Type: INamedTypeSymbol { - Name: nameof(IEnumerable), + Name: nameof(IEnumerable<>), TypeArguments: [ITypeParameterSymbol { TypeParameterKind: TypeParameterKind.Method }] } enumerableType }] && @@ -980,7 +980,7 @@ originalCreateMethod.Parameters is [ { Type: INamedTypeSymbol { - Name: nameof(Span) or nameof(ReadOnlySpan), + Name: nameof(Span<>) or nameof(ReadOnlySpan<>), TypeArguments: [ITypeParameterSymbol { TypeParameterKind: TypeParameterKind.Method }] } spanType }]) diff --git a/src/Analyzers/CSharp/Analyzers/UseCollectionInitializer/CSharpUseCollectionInitializerAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseCollectionInitializer/CSharpUseCollectionInitializerAnalyzer.cs index 6a93604eb7369..4e3f515b70bde 100644 --- a/src/Analyzers/CSharp/Analyzers/UseCollectionInitializer/CSharpUseCollectionInitializerAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/UseCollectionInitializer/CSharpUseCollectionInitializerAnalyzer.cs @@ -205,11 +205,20 @@ bool CanSpreadFirstParameter(INamedTypeSymbol constructedType, IParameterSymbol var compilation = this.SemanticModel.Compilation; var ienumerableOfTType = compilation.IEnumerableOfTType(); - if (!Equals(firstParameter.Type.OriginalDefinition, ienumerableOfTType) && - !firstParameter.Type.AllInterfaces.Any(i => Equals(i.OriginalDefinition, ienumerableOfTType))) - { + var implementedInterface = firstParameter.Type + .GetAllInterfacesIncludingThis() + .FirstOrDefault(i => Equals(i.OriginalDefinition, ienumerableOfTType)); + + var elementType = implementedInterface?.GetTypeArguments().SingleOrDefault(); + if (elementType is null) + return false; + + // Ok, the constructor takes some `IEnumerable` type. If it also has an `Add(X)` method, then we + // can take those constructor arguments and pass them along to the final collection by spreading them. + // If not, then we can't convert this to a collection expression. + var addMethods = this.GetAddMethods(cancellationToken); + if (!addMethods.Any(m => m.Parameters is [{ Type: var parameterType }] && Equals(parameterType, elementType))) return false; - } // Looks like something passed to the constructor call that we could potentially spread instead. e.g. `new // HashSet(someList)` can become `[.. someList]`. However, check for certain cases we know where this is diff --git a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper.cs b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper.cs index b1b692a21fb52..8ccc6d381a4ac 100644 --- a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper.cs +++ b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper.cs @@ -3,12 +3,12 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; -using Microsoft.CodeAnalysis.CodeStyle; -using Microsoft.CodeAnalysis.Options; -using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Diagnostics.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using System.Threading; +using Microsoft.CodeAnalysis.CodeStyle; +using Microsoft.CodeAnalysis.CSharp.CodeGeneration; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody; diff --git a/src/Analyzers/CSharp/Analyzers/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationDiagnosticAnalyzer.cs index d452e58779d16..4e4f1ae0a87db 100644 --- a/src/Analyzers/CSharp/Analyzers/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationDiagnosticAnalyzer.cs @@ -16,17 +16,14 @@ namespace Microsoft.CodeAnalysis.CSharp.UseImplicitObjectCreation; [DiagnosticAnalyzer(LanguageNames.CSharp)] -internal sealed class CSharpUseImplicitObjectCreationDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer +internal sealed class CSharpUseImplicitObjectCreationDiagnosticAnalyzer() + : AbstractBuiltInCodeStyleDiagnosticAnalyzer( + IDEDiagnosticIds.UseImplicitObjectCreationDiagnosticId, + EnforceOnBuildValues.UseImplicitObjectCreation, + CSharpCodeStyleOptions.ImplicitObjectCreationWhenTypeIsApparent, + new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_new), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), + new LocalizableResourceString(nameof(CSharpAnalyzersResources.new_expression_can_be_simplified), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { - public CSharpUseImplicitObjectCreationDiagnosticAnalyzer() - : base(IDEDiagnosticIds.UseImplicitObjectCreationDiagnosticId, - EnforceOnBuildValues.UseImplicitObjectCreation, - CSharpCodeStyleOptions.ImplicitObjectCreationWhenTypeIsApparent, - new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_new), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), - new LocalizableResourceString(nameof(CSharpAnalyzersResources.new_expression_can_be_simplified), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) - { - } - public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; @@ -56,7 +53,10 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) context.ReportDiagnostic(DiagnosticHelper.Create( Descriptor, - objectCreation.Type.GetLocation(), + // Place the suggestion on the 'new' keyword. This is both the earliest part of the object creation + // expression, and it also matches the location we place the 'use collection expression' analyzer, + // ensuring consistency between the two analyzers. + objectCreation.NewKeyword.GetLocation(), styleOption.Notification, context.Options, [objectCreation.GetLocation()], diff --git a/src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.InfoCache.cs b/src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.InfoCache.cs index 26ea15936fa4a..dee9c249b8a93 100644 --- a/src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.InfoCache.cs +++ b/src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.InfoCache.cs @@ -158,7 +158,7 @@ private MemberInfo ComputeMemberInfo(IMethodSymbol sliceLikeMethod, bool require // Also, look to see if the type has a `.Slice(int start, int length)` method. // This is also a method the compiler knows to look for when a user writes `x[a..b]` var actualSliceMethod = - sliceLikeMethod.ContainingType.GetMembers(nameof(Span.Slice)) + sliceLikeMethod.ContainingType.GetMembers(nameof(Span<>.Slice)) .OfType() .FirstOrDefault(s => IsTwoArgumentSliceLikeMethod(s)); if (actualSliceMethod != null) diff --git a/src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.cs index f6bfbb9944301..c8d7838f53517 100644 --- a/src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.cs @@ -311,8 +311,6 @@ private Diagnostic CreateDiagnostic(Result result, NotificationOption2 notificat { // Keep track of the invocation node var invocation = result.Invocation; - var additionalLocations = ImmutableArray.Create( - invocation.GetLocation()); // Mark the span under the two arguments to .Slice(..., ...) as what we will be // updating. @@ -325,7 +323,7 @@ private Diagnostic CreateDiagnostic(Result result, NotificationOption2 notificat location, notificationOption, analyzerOptions, - additionalLocations, + [invocation.GetLocation()], ImmutableDictionary.Empty, result.SliceLikeMethod.Name); } diff --git a/src/Analyzers/CSharp/Analyzers/UseNullPropagation/CSharpUseNullPropagationDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseNullPropagation/CSharpUseNullPropagationDiagnosticAnalyzer.cs index 368a8df73ab1e..32ead852438b1 100644 --- a/src/Analyzers/CSharp/Analyzers/UseNullPropagation/CSharpUseNullPropagationDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/UseNullPropagation/CSharpUseNullPropagationDiagnosticAnalyzer.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -26,6 +27,8 @@ internal sealed class CSharpUseNullPropagationDiagnosticAnalyzer : IfStatementSyntax, ExpressionStatementSyntax> { + public static readonly CSharpUseNullPropagationDiagnosticAnalyzer Instance = new(); + protected override SyntaxKind IfStatementSyntaxKind => SyntaxKind.IfStatement; @@ -65,7 +68,7 @@ protected override bool TryAnalyzePatternCondition( protected override bool TryGetPartsOfIfStatement( IfStatementSyntax ifStatement, [NotNullWhen(true)] out ExpressionSyntax? condition, - [NotNullWhen(true)] out StatementSyntax? trueStatement) + out ImmutableArray trueStatements) { // has to be of the form: // @@ -78,23 +81,25 @@ protected override bool TryGetPartsOfIfStatement( // { // statement // } + // + // or + // + // if (...) + // { + // statement + // val = null; + // } condition = ifStatement.Condition; - trueStatement = null; + trueStatements = []; if (ifStatement.Else == null) { - if (ifStatement.Statement is BlockSyntax block) - { - if (block.Statements.Count == 1) - trueStatement = block.Statements[0]; - } - else - { - trueStatement = ifStatement.Statement; - } + trueStatements = ifStatement.Statement is BlockSyntax block + ? [.. block.Statements] + : [ifStatement.Statement]; } - return trueStatement != null; + return true; } } diff --git a/src/Analyzers/CSharp/Analyzers/UsePatternCombinators/CSharpUsePatternCombinatorsAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UsePatternCombinators/CSharpUsePatternCombinatorsAnalyzer.cs index 553259e2d5568..11e32dcd6bb00 100644 --- a/src/Analyzers/CSharp/Analyzers/UsePatternCombinators/CSharpUsePatternCombinatorsAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/UsePatternCombinators/CSharpUsePatternCombinatorsAnalyzer.cs @@ -7,8 +7,8 @@ namespace Microsoft.CodeAnalysis.CSharp.UsePatternCombinators; -using static BinaryOperatorKind; using static AnalyzedPattern; +using static BinaryOperatorKind; internal static class CSharpUsePatternCombinatorsAnalyzer { diff --git a/src/Analyzers/CSharp/Analyzers/UsePatternCombinators/CSharpUsePatternCombinatorsDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UsePatternCombinators/CSharpUsePatternCombinatorsDiagnosticAnalyzer.cs index 0f71c68e633be..4e08c3d57ddbf 100644 --- a/src/Analyzers/CSharp/Analyzers/UsePatternCombinators/CSharpUsePatternCombinatorsDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/UsePatternCombinators/CSharpUsePatternCombinatorsDiagnosticAnalyzer.cs @@ -9,7 +9,6 @@ using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.UsePatternCombinators; diff --git a/src/Analyzers/CSharp/Analyzers/UseSimpleUsingStatement/UseSimpleUsingStatementDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseSimpleUsingStatement/UseSimpleUsingStatementDiagnosticAnalyzer.cs index b560a039097c2..057d50af3bf47 100644 --- a/src/Analyzers/CSharp/Analyzers/UseSimpleUsingStatement/UseSimpleUsingStatementDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/UseSimpleUsingStatement/UseSimpleUsingStatementDiagnosticAnalyzer.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Collections.Immutable; +using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; diff --git a/src/Analyzers/CSharp/Analyzers/UseSystemThreadingLock/CSharpUseSystemThreadingLockDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseSystemThreadingLock/CSharpUseSystemThreadingLockDiagnosticAnalyzer.cs index 3f750b3e7483f..2f7f930d6186a 100644 --- a/src/Analyzers/CSharp/Analyzers/UseSystemThreadingLock/CSharpUseSystemThreadingLockDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/UseSystemThreadingLock/CSharpUseSystemThreadingLockDiagnosticAnalyzer.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.CodeStyle; @@ -13,7 +14,6 @@ using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Collections; -using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UseSystemThreadingLock; diff --git a/src/Analyzers/CSharp/Analyzers/UseUtf8StringLiteral/UseUtf8StringLiteralDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseUtf8StringLiteral/UseUtf8StringLiteralDiagnosticAnalyzer.cs index 18076827975d7..2e869ed4b452a 100644 --- a/src/Analyzers/CSharp/Analyzers/UseUtf8StringLiteral/UseUtf8StringLiteralDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/UseUtf8StringLiteral/UseUtf8StringLiteralDiagnosticAnalyzer.cs @@ -16,7 +16,6 @@ using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Collections; -using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/Analyzers/CSharp/CodeFixes/AddInheritdoc/AddInheritdocCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/AddInheritdoc/AddInheritdocCodeFixProvider.cs index 465f33a6f4f84..06e7c4d91c353 100644 --- a/src/Analyzers/CSharp/CodeFixes/AddInheritdoc/AddInheritdocCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/AddInheritdoc/AddInheritdocCodeFixProvider.cs @@ -9,12 +9,12 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; -using Microsoft.CodeAnalysis.CSharp.Extensions; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.AddInheritdoc; diff --git a/src/Analyzers/CSharp/CodeFixes/ConditionalExpressionInStringInterpolation/CSharpAddParenthesesAroundConditionalExpressionInInterpolatedStringCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/ConditionalExpressionInStringInterpolation/CSharpAddParenthesesAroundConditionalExpressionInInterpolatedStringCodeFixProvider.cs index 61aee9bcc433a..9f1bd6ce979ed 100644 --- a/src/Analyzers/CSharp/CodeFixes/ConditionalExpressionInStringInterpolation/CSharpAddParenthesesAroundConditionalExpressionInInterpolatedStringCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/ConditionalExpressionInStringInterpolation/CSharpAddParenthesesAroundConditionalExpressionInInterpolatedStringCodeFixProvider.cs @@ -13,7 +13,6 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ConditionalExpressionInStringInterpolation; diff --git a/src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceCodeFixProvider.cs index 7bcd0962149a7..f37a7574042de 100644 --- a/src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceCodeFixProvider.cs @@ -17,7 +17,6 @@ using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ConvertNamespace; diff --git a/src/Analyzers/CSharp/CodeFixes/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionCodeFixProvider.cs index 752bc049b3622..d68ba05e14247 100644 --- a/src/Analyzers/CSharp/CodeFixes/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionCodeFixProvider.cs @@ -19,7 +19,6 @@ using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ConvertSwitchStatementToExpression; diff --git a/src/Analyzers/CSharp/CodeFixes/GenerateParameterizedMember/CSharpGenerateParameterizedMemberService.cs b/src/Analyzers/CSharp/CodeFixes/GenerateParameterizedMember/CSharpGenerateParameterizedMemberService.cs index 0ffa1eca11bc4..ad0ecf70a3b22 100644 --- a/src/Analyzers/CSharp/CodeFixes/GenerateParameterizedMember/CSharpGenerateParameterizedMemberService.cs +++ b/src/Analyzers/CSharp/CodeFixes/GenerateParameterizedMember/CSharpGenerateParameterizedMemberService.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System; -using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; diff --git a/src/Analyzers/CSharp/CodeFixes/HideBase/HideBaseCodeFixProvider.AddNewKeywordAction.cs b/src/Analyzers/CSharp/CodeFixes/HideBase/HideBaseCodeFixProvider.AddNewKeywordAction.cs index 566daa3dd5da9..097323ff0681d 100644 --- a/src/Analyzers/CSharp/CodeFixes/HideBase/HideBaseCodeFixProvider.AddNewKeywordAction.cs +++ b/src/Analyzers/CSharp/CodeFixes/HideBase/HideBaseCodeFixProvider.AddNewKeywordAction.cs @@ -2,17 +2,16 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.LanguageService; using Microsoft.CodeAnalysis.CSharp.OrderModifiers; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.OrderModifiers; using Microsoft.CodeAnalysis.Shared.Extensions; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.HideBase; @@ -20,46 +19,36 @@ namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.HideBase; internal sealed partial class HideBaseCodeFixProvider { - private sealed class AddNewKeywordAction(Document document, SyntaxNode node) : CodeAction + private static async Task GetChangedDocumentAsync( + Document document, SyntaxNode node, CancellationToken cancellationToken) { - private readonly Document _document = document; - private readonly SyntaxNode _node = node; + var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + var modifierOrder = await GetModifierOrderAsync(document, cancellationToken).ConfigureAwait(false); - public override string Title => CSharpCodeFixesResources.Hide_base_member; - - protected override async Task GetChangedDocumentAsync(CancellationToken cancellationToken) - { - var root = await _document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - var configOptions = await _document.GetHostAnalyzerConfigOptionsAsync(cancellationToken).ConfigureAwait(false); - - var newNode = GetNewNode(_node, configOptions.GetOption(CSharpCodeStyleOptions.PreferredModifierOrder).Value); - var newRoot = root.ReplaceNode(_node, newNode); + return document.WithSyntaxRoot(root.ReplaceNode(node, GetNewNode(node, modifierOrder))); + } - return _document.WithSyntaxRoot(newRoot); - } + private static SyntaxNode GetNewNode(SyntaxNode node, Dictionary? preferredOrder) + { + var syntaxFacts = CSharpSyntaxFacts.Instance; + var modifiers = syntaxFacts.GetModifiers(node); + var newModifiers = modifiers.Add(NewKeyword); - private static SyntaxNode GetNewNode(SyntaxNode node, string preferredModifierOrder) + if (preferredOrder is null || + !AbstractOrderModifiersHelpers.IsOrdered(preferredOrder, modifiers)) { - var syntaxFacts = CSharpSyntaxFacts.Instance; - var modifiers = syntaxFacts.GetModifiers(node); - var newModifiers = modifiers.Add(NewKeyword); - - if (!CSharpOrderModifiersHelper.Instance.TryGetOrComputePreferredOrder(preferredModifierOrder, out var preferredOrder) || - !AbstractOrderModifiersHelpers.IsOrdered(preferredOrder, modifiers)) - { - return syntaxFacts.WithModifiers(node, newModifiers); - } + return syntaxFacts.WithModifiers(node, newModifiers); + } - var orderedModifiers = new SyntaxTokenList( - newModifiers.OrderBy(CompareModifiers)); + var orderedModifiers = new SyntaxTokenList( + newModifiers.OrderBy(CompareModifiers)); - return syntaxFacts.WithModifiers(node, orderedModifiers); + return syntaxFacts.WithModifiers(node, orderedModifiers); - int CompareModifiers(SyntaxToken left, SyntaxToken right) - => GetOrder(left) - GetOrder(right); + int CompareModifiers(SyntaxToken left, SyntaxToken right) + => GetOrder(left) - GetOrder(right); - int GetOrder(SyntaxToken token) - => preferredOrder.TryGetValue(token.RawKind, out var value) ? value : int.MaxValue; - } + int GetOrder(SyntaxToken token) + => preferredOrder.TryGetValue(token.RawKind, out var value) ? value : int.MaxValue; } } diff --git a/src/Analyzers/CSharp/CodeFixes/HideBase/HideBaseCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/HideBase/HideBaseCodeFixProvider.cs index cfc813e2319e6..0143983311f31 100644 --- a/src/Analyzers/CSharp/CodeFixes/HideBase/HideBaseCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/HideBase/HideBaseCodeFixProvider.cs @@ -2,13 +2,20 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; +using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; +using Microsoft.CodeAnalysis.CSharp.OrderModifiers; using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Editing; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.HideBase; @@ -16,31 +23,60 @@ namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.HideBase; [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.AddNew), Shared] [method: ImportingConstructor] [method: SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] -internal sealed partial class HideBaseCodeFixProvider() : CodeFixProvider +internal sealed partial class HideBaseCodeFixProvider() : SyntaxEditorBasedCodeFixProvider { internal const string CS0108 = nameof(CS0108); // 'SomeClass.SomeMember' hides inherited member 'SomeClass.SomeMember'. Use the new keyword if hiding was intended. public override ImmutableArray FixableDiagnosticIds => [CS0108]; - public override FixAllProvider GetFixAllProvider() - => WellKnownFixAllProviders.BatchFixer; - - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + private static SyntaxNode? GetOriginalNode(SyntaxNode root, Diagnostic diagnostic) { - var root = await context.Document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); - - var diagnostic = context.Diagnostics.First(); var diagnosticSpan = diagnostic.Location.SourceSpan; - var token = root.FindToken(diagnosticSpan.Start); var originalNode = token.GetAncestor() ?? token.GetAncestor() ?? (SyntaxNode?)token.GetAncestor(); + return originalNode; + } + + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + { + var root = await context.Document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); + var originalNode = GetOriginalNode(root, context.Diagnostics.First()); if (originalNode == null) return; - context.RegisterCodeFix(new AddNewKeywordAction(context.Document, originalNode), context.Diagnostics); + context.RegisterCodeFix(CodeAction.Create( + CSharpCodeFixesResources.Hide_base_member, + cancellationToken => GetChangedDocumentAsync(context.Document, originalNode, cancellationToken), + nameof(CSharpCodeFixesResources.Hide_base_member)), + context.Diagnostics); + } + + protected override async Task FixAllAsync( + Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) + { + var modifierOrder = await GetModifierOrderAsync(document, cancellationToken).ConfigureAwait(false); + + var root = editor.OriginalRoot; + foreach (var diagnostic in diagnostics) + { + var originalNode = GetOriginalNode(root, diagnostic); + if (originalNode == null) + continue; + + var newNode = GetNewNode(originalNode, modifierOrder); + editor.ReplaceNode(originalNode, newNode); + } + } + + private static async Task?> GetModifierOrderAsync(Document document, CancellationToken cancellationToken) + { + var configOptions = await document.GetHostAnalyzerConfigOptionsAsync(cancellationToken).ConfigureAwait(false); + var modifierOrder = configOptions.GetOption(CSharpCodeStyleOptions.PreferredModifierOrder).Value; + CSharpOrderModifiersHelper.Instance.TryGetOrComputePreferredOrder(modifierOrder, out var preferredOrder); + return preferredOrder; } } diff --git a/src/Analyzers/CSharp/CodeFixes/Iterator/CSharpChangeToIEnumerableCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/Iterator/CSharpChangeToIEnumerableCodeFixProvider.cs index d707a2b05c0c2..a1ebbb3099f84 100644 --- a/src/Analyzers/CSharp/CodeFixes/Iterator/CSharpChangeToIEnumerableCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/Iterator/CSharpChangeToIEnumerableCodeFixProvider.cs @@ -16,7 +16,6 @@ using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.Iterator; diff --git a/src/Analyzers/CSharp/CodeFixes/MakeMethodAsynchronous/CSharpMakeMethodAsynchronousCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/MakeMethodAsynchronous/CSharpMakeMethodAsynchronousCodeFixProvider.cs index ebdf9616f9161..1450fca34c80f 100644 --- a/src/Analyzers/CSharp/CodeFixes/MakeMethodAsynchronous/CSharpMakeMethodAsynchronousCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/MakeMethodAsynchronous/CSharpMakeMethodAsynchronousCodeFixProvider.cs @@ -131,13 +131,13 @@ private static TypeSyntax FixMethodReturnType( if (IsIEnumerable(returnType, knownTypes) && IsIterator(methodSymbol, cancellationToken)) { newReturnType = knownTypes.IAsyncEnumerableOfTType is null - ? MakeGenericType(nameof(IAsyncEnumerable), methodSymbol.ReturnType) + ? MakeGenericType(nameof(IAsyncEnumerable<>), methodSymbol.ReturnType) : knownTypes.IAsyncEnumerableOfTType.Construct(methodSymbol.ReturnType.GetTypeArguments()[0]).GenerateTypeSyntax(); } else if (IsIEnumerator(returnType, knownTypes) && IsIterator(methodSymbol, cancellationToken)) { newReturnType = knownTypes.IAsyncEnumeratorOfTType is null - ? MakeGenericType(nameof(IAsyncEnumerator), methodSymbol.ReturnType) + ? MakeGenericType(nameof(IAsyncEnumerator<>), methodSymbol.ReturnType) : knownTypes.IAsyncEnumeratorOfTType.Construct(methodSymbol.ReturnType.GetTypeArguments()[0]).GenerateTypeSyntax(); } else if (IsIAsyncEnumerableOrEnumerator(returnType, knownTypes)) diff --git a/src/Analyzers/CSharp/CodeFixes/MisplacedUsingDirectives/MisplacedUsingDirectivesCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/MisplacedUsingDirectives/MisplacedUsingDirectivesCodeFixProvider.cs index 46c989508c2ed..9ba94be199535 100644 --- a/src/Analyzers/CSharp/CodeFixes/MisplacedUsingDirectives/MisplacedUsingDirectivesCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/MisplacedUsingDirectives/MisplacedUsingDirectivesCodeFixProvider.cs @@ -328,10 +328,9 @@ private static SyntaxList GetMembers(SyntaxNode node) private static TSyntaxNode RemoveLeadingBlankLinesFromFirstMember(TSyntaxNode node) where TSyntaxNode : SyntaxNode { var members = GetMembers(node); - if (members.Count == 0) + if (members is not [var firstMember, ..]) return node; - var firstMember = members.First(); var firstMemberTrivia = firstMember.GetLeadingTrivia(); // If there is no leading trivia, then return the node as it is. @@ -367,10 +366,9 @@ private static IEnumerable> SplitIntoLines(SyntaxTrivi private static TSyntaxNode EnsureLeadingBlankLineBeforeFirstMember(TSyntaxNode node) where TSyntaxNode : SyntaxNode { var members = GetMembers(node); - if (members.Count == 0) + if (members is not [var firstMember, ..]) return node; - var firstMember = members.First(); var firstMemberTrivia = firstMember.GetLeadingTrivia(); // If the first member already contains a leading new line then, this will already break up the usings from these members. diff --git a/src/Analyzers/CSharp/CodeFixes/NewLines/ArrowExpressionClausePlacement/ArrowExpressionClausePlacementCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/NewLines/ArrowExpressionClausePlacement/ArrowExpressionClausePlacementCodeFixProvider.cs index 91f10bc2d37bd..8cde1756070e7 100644 --- a/src/Analyzers/CSharp/CodeFixes/NewLines/ArrowExpressionClausePlacement/ArrowExpressionClausePlacementCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/NewLines/ArrowExpressionClausePlacement/ArrowExpressionClausePlacementCodeFixProvider.cs @@ -16,7 +16,6 @@ using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.NewLines.ArrowExpressionClausePlacement; diff --git a/src/Analyzers/CSharp/CodeFixes/NewLines/ConditionalExpressionPlacement/ConditionalExpressionPlacementCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/NewLines/ConditionalExpressionPlacement/ConditionalExpressionPlacementCodeFixProvider.cs index 50cce8f2d95b2..13ba977508273 100644 --- a/src/Analyzers/CSharp/CodeFixes/NewLines/ConditionalExpressionPlacement/ConditionalExpressionPlacementCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/NewLines/ConditionalExpressionPlacement/ConditionalExpressionPlacementCodeFixProvider.cs @@ -16,7 +16,6 @@ using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.NewLines.ConditionalExpressionPlacement; diff --git a/src/Analyzers/CSharp/CodeFixes/RemoveConfusingSuppression/CSharpRemoveConfusingSuppressionCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/RemoveConfusingSuppression/CSharpRemoveConfusingSuppressionCodeFixProvider.cs index 685d47fe4f6cb..f7fbba37cde3c 100644 --- a/src/Analyzers/CSharp/CodeFixes/RemoveConfusingSuppression/CSharpRemoveConfusingSuppressionCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/RemoveConfusingSuppression/CSharpRemoveConfusingSuppressionCodeFixProvider.cs @@ -16,7 +16,6 @@ using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.RemoveConfusingSuppression; diff --git a/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForFluentCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForFluentCodeFixProvider.cs index 0d6ebea4aa39d..907ff9a5a9501 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForFluentCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForFluentCodeFixProvider.cs @@ -9,6 +9,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; @@ -25,8 +26,8 @@ namespace Microsoft.CodeAnalysis.CSharp.UseCollectionExpression; using static CSharpCollectionExpressionRewriter; -using static CSharpUseCollectionExpressionForFluentDiagnosticAnalyzer; using static CSharpSyntaxTokens; +using static CSharpUseCollectionExpressionForFluentDiagnosticAnalyzer; using static SyntaxFactory; [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseCollectionExpressionForFluent), Shared] diff --git a/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForNewCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForNewCodeFixProvider.cs index 4111e3e2db128..fa4e7ac9200d2 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForNewCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForNewCodeFixProvider.cs @@ -23,6 +23,7 @@ namespace Microsoft.CodeAnalysis.CSharp.UseCollectionExpression; using static UseCollectionExpressionHelpers; [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseCollectionExpressionForNew), Shared] +[ExtensionOrder(Before = PredefinedCodeFixProviderNames.UseImplicitObjectCreation)] [method: ImportingConstructor] [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] internal sealed partial class CSharpUseCollectionExpressionForNewCodeFixProvider() diff --git a/src/Analyzers/CSharp/CodeFixes/UseCollectionInitializer/CSharpUseCollectionInitializerCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseCollectionInitializer/CSharpUseCollectionInitializerCodeFixProvider.cs index 0a323d76ecdb0..524292ebe2e50 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseCollectionInitializer/CSharpUseCollectionInitializerCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseCollectionInitializer/CSharpUseCollectionInitializerCodeFixProvider.cs @@ -15,6 +15,7 @@ namespace Microsoft.CodeAnalysis.CSharp.UseCollectionInitializer; [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseCollectionInitializer), Shared] +[ExtensionOrder(Before = PredefinedCodeFixProviderNames.UseImplicitObjectCreation)] [method: ImportingConstructor] [method: SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] internal sealed partial class CSharpUseCollectionInitializerCodeFixProvider() : diff --git a/src/Analyzers/CSharp/CodeFixes/UseExpressionBody/UseExpressionBodyCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseExpressionBody/UseExpressionBodyCodeFixProvider.cs index e0473bf958f77..60291f55e829a 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseExpressionBody/UseExpressionBodyCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseExpressionBody/UseExpressionBodyCodeFixProvider.cs @@ -16,7 +16,6 @@ using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody; diff --git a/src/Analyzers/CSharp/CodeFixes/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationCodeFixProvider.cs index 576f76620d1cb..cd77173715f61 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationCodeFixProvider.cs @@ -25,6 +25,8 @@ namespace Microsoft.CodeAnalysis.CSharp.UseImplicitObjectCreation; using static SyntaxFactory; [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseImplicitObjectCreation), Shared] +[ExtensionOrder(After = PredefinedCodeFixProviderNames.UseCollectionExpressionForNew)] +[ExtensionOrder(After = PredefinedCodeFixProviderNames.UseCollectionInitializer)] [method: ImportingConstructor] [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] internal sealed class CSharpUseImplicitObjectCreationCodeFixProvider() : SyntaxEditorBasedCodeFixProvider diff --git a/src/Analyzers/CSharp/CodeFixes/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorCodeFixProvider.cs index 2cc538d91b2c4..74c11ed1b67a4 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorCodeFixProvider.cs @@ -15,7 +15,6 @@ using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.UseIsNullCheck; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UseIsNullCheck; diff --git a/src/Analyzers/CSharp/CodeFixes/UseLocalFunction/CSharpUseLocalFunctionCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseLocalFunction/CSharpUseLocalFunctionCodeFixProvider.cs index 4b0d32d68b08c..968fc5a76882a 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseLocalFunction/CSharpUseLocalFunctionCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseLocalFunction/CSharpUseLocalFunctionCodeFixProvider.cs @@ -14,6 +14,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeGeneration; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; diff --git a/src/Analyzers/CSharp/CodeFixes/UseNullPropagation/CSharpUseNullPropagationCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseNullPropagation/CSharpUseNullPropagationCodeFixProvider.cs index 84b3074c92ac6..40077ec354ee0 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseNullPropagation/CSharpUseNullPropagationCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseNullPropagation/CSharpUseNullPropagationCodeFixProvider.cs @@ -4,8 +4,10 @@ using System.Composition; using System.Diagnostics.CodeAnalysis; +using System.Linq; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.UseNullPropagation; @@ -15,6 +17,7 @@ namespace Microsoft.CodeAnalysis.CSharp.UseNullPropagation; [method: ImportingConstructor] [method: SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] internal sealed class CSharpUseNullPropagationCodeFixProvider() : AbstractUseNullPropagationCodeFixProvider< + CSharpUseNullPropagationDiagnosticAnalyzer, SyntaxKind, ExpressionSyntax, StatementSyntax, @@ -29,23 +32,18 @@ internal sealed class CSharpUseNullPropagationCodeFixProvider() : AbstractUseNul ExpressionStatementSyntax, BracketedArgumentListSyntax> { - protected override bool TryGetBlock(SyntaxNode? statement, [NotNullWhen(true)] out StatementSyntax? block) - { - if (statement is BlockSyntax statementBlock) - { - block = statementBlock; - return true; - } - - block = null; - return false; - } + protected override CSharpUseNullPropagationDiagnosticAnalyzer Analyzer + => CSharpUseNullPropagationDiagnosticAnalyzer.Instance; - protected override StatementSyntax ReplaceBlockStatements(StatementSyntax block, StatementSyntax newInnerStatement) - => ((BlockSyntax)block).WithStatements([newInnerStatement]); + private static BlockSyntax ReplaceBlockStatements(BlockSyntax block, StatementSyntax newInnerStatement) + => block.WithStatements([newInnerStatement, .. block.Statements.Skip(1).Select(s => s.WithAdditionalAnnotations(Formatter.Annotation))]); - protected override SyntaxNode PostProcessElseIf(IfStatementSyntax ifStatement, StatementSyntax newWhenTrueStatement) + protected override SyntaxNode PostProcessElseIf( + IfStatementSyntax ifStatement, StatementSyntax newWhenTrueStatement) { + if (ifStatement.Statement is BlockSyntax block) + newWhenTrueStatement = ReplaceBlockStatements(block, newWhenTrueStatement); + var elseClauseSyntax = (ElseClauseSyntax)ifStatement.Parent!; return elseClauseSyntax .WithElseKeyword(elseClauseSyntax.ElseKeyword.WithTrailingTrivia()) diff --git a/src/Analyzers/CSharp/CodeFixes/UsePrimaryConstructor/CSharpUsePrimaryConstructorCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UsePrimaryConstructor/CSharpUsePrimaryConstructorCodeFixProvider.cs index 02e9292bf5637..c496dfd59323a 100644 --- a/src/Analyzers/CSharp/CodeFixes/UsePrimaryConstructor/CSharpUsePrimaryConstructorCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UsePrimaryConstructor/CSharpUsePrimaryConstructorCodeFixProvider.cs @@ -28,8 +28,8 @@ namespace Microsoft.CodeAnalysis.CSharp.UsePrimaryConstructor; -using static CSharpUsePrimaryConstructorDiagnosticAnalyzer; using static CSharpSyntaxTokens; +using static CSharpUsePrimaryConstructorDiagnosticAnalyzer; using static SyntaxFactory; [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UsePrimaryConstructor), Shared] diff --git a/src/Analyzers/CSharp/CodeFixes/UsePrimaryConstructor/CSharpUsePrimaryConstructorFixAllProvider.cs b/src/Analyzers/CSharp/CodeFixes/UsePrimaryConstructor/CSharpUsePrimaryConstructorFixAllProvider.cs index 852746d403c20..15e87059cdbef 100644 --- a/src/Analyzers/CSharp/CodeFixes/UsePrimaryConstructor/CSharpUsePrimaryConstructorFixAllProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UsePrimaryConstructor/CSharpUsePrimaryConstructorFixAllProvider.cs @@ -4,6 +4,7 @@ // Ignore Spelling: loc kvp +using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; diff --git a/src/Analyzers/CSharp/CodeFixes/UseSystemThreadingLock/CSharpUseSystemThreadingLockFixAllProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseSystemThreadingLock/CSharpUseSystemThreadingLockFixAllProvider.cs index 055c1a263711e..dbe882b312d1a 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseSystemThreadingLock/CSharpUseSystemThreadingLockFixAllProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseSystemThreadingLock/CSharpUseSystemThreadingLockFixAllProvider.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; diff --git a/src/Analyzers/CSharp/CodeFixes/UseUtf8StringLiteral/UseUtf8StringLiteralCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseUtf8StringLiteral/UseUtf8StringLiteralCodeFixProvider.cs index f82a29f839e6e..067362b58ca4f 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseUtf8StringLiteral/UseUtf8StringLiteralCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseUtf8StringLiteral/UseUtf8StringLiteralCodeFixProvider.cs @@ -206,7 +206,7 @@ private static ExpressionSyntax CreateUtf8String(SyntaxTriviaList leadingTrivia, MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, stringLiteral, - IdentifierName(nameof(ReadOnlySpan.ToArray)))) + IdentifierName(nameof(ReadOnlySpan<>.ToArray)))) .WithTrailingTrivia(trailingTrivia); } } diff --git a/src/Analyzers/CSharp/Tests/AddAccessibilityModifiers/AddOrRemoveAccessibilityModifiersFixAllTests.cs b/src/Analyzers/CSharp/Tests/AddAccessibilityModifiers/AddOrRemoveAccessibilityModifiersFixAllTests.cs index 4b196a1453e0f..a85c02622f160 100644 --- a/src/Analyzers/CSharp/Tests/AddAccessibilityModifiers/AddOrRemoveAccessibilityModifiersFixAllTests.cs +++ b/src/Analyzers/CSharp/Tests/AddAccessibilityModifiers/AddOrRemoveAccessibilityModifiersFixAllTests.cs @@ -23,22 +23,16 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider [Fact, WorkItem("https://github.com/dotnet/vscode-csharp/issues/6611")] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInContainingType_DoesNotCrashInDuplicateProgramInTopLevelStatements() - { - var input = """ + public Task TestFixAllInContainingType_DoesNotCrashInDuplicateProgramInTopLevelStatements() + => TestAsync(""" Console.WriteLine("Hello, World!"); class {|FixAllInContainingType:Program|} { } - """; - - var expected = """ + """, """ Console.WriteLine("Hello, World!"); internal class Program { } - """; - - await TestAsync(input, expected, TestParameters.Default.parseOptions); - } + """, TestParameters.Default.parseOptions); } diff --git a/src/Analyzers/CSharp/Tests/AddAccessibilityModifiers/AddOrRemoveAccessibilityModifiersTests.cs b/src/Analyzers/CSharp/Tests/AddAccessibilityModifiers/AddOrRemoveAccessibilityModifiersTests.cs index 1f39e56ab48d8..326fd779c7579 100644 --- a/src/Analyzers/CSharp/Tests/AddAccessibilityModifiers/AddOrRemoveAccessibilityModifiersTests.cs +++ b/src/Analyzers/CSharp/Tests/AddAccessibilityModifiers/AddOrRemoveAccessibilityModifiersTests.cs @@ -25,9 +25,8 @@ public void TestStandardProperty(AnalyzerProperty property) => VerifyCS.VerifyStandardProperty(property); [Fact] - public async Task TestAllConstructs() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestAllConstructs() + => VerifyCS.VerifyCodeFixAsync( """ using System; namespace Outer @@ -150,12 +149,10 @@ internal enum E } } """); - } [Fact] - public async Task TestRefStructs() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestRefStructs() + => VerifyCS.VerifyCodeFixAsync(""" namespace Test { ref struct [|S1|] { } @@ -166,12 +163,13 @@ namespace Test internal ref struct S1 { } } """); - } [Fact] public async Task TestRecords() { - var source = """ + var test = new VerifyCS.Test + { + TestCode = """ record [|Record|] { int [|field|]; @@ -182,8 +180,8 @@ public sealed class IsExternalInit { } } - """; - var fixedSource = """ + """, + FixedCode = """ internal record Record { private int field; @@ -194,12 +192,7 @@ public sealed class IsExternalInit { } } - """; - - var test = new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp9, }; @@ -209,23 +202,20 @@ public sealed class IsExternalInit [Fact] public async Task TestRecordStructs() { - var source = """ + var test = new VerifyCS.Test + { + TestCode = """ record struct [|Record|] { int [|field|]; } - """; - var fixedSource = """ + """, + FixedCode = """ internal record struct Record { private int field; } - """; - - var test = new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp12, }; @@ -233,9 +223,8 @@ internal record struct Record } [Fact] - public async Task TestReadOnlyStructs() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestReadOnlyStructs() + => VerifyCS.VerifyCodeFixAsync(""" namespace Test { readonly struct [|S1|] { } @@ -246,12 +235,10 @@ namespace Test internal readonly struct S1 { } } """); - } [Fact] - public async Task TestAllConstructsWithOmit() - { - await new VerifyCS.Test + public Task TestAllConstructsWithOmit() + => new VerifyCS.Test { TestState = { @@ -394,12 +381,10 @@ enum E { CodeStyleOptions2.AccessibilityModifiersRequired, AccessibilityModifiersRequired.OmitIfDefault }, }, }.RunAsync(); - } [Fact] - public async Task TestRefStructsWithOmit() - { - await new VerifyCS.Test + public Task TestRefStructsWithOmit() + => new VerifyCS.Test { TestCode = """ namespace Test @@ -418,12 +403,10 @@ ref struct S1 { } { CodeStyleOptions2.AccessibilityModifiersRequired, AccessibilityModifiersRequired.OmitIfDefault }, }, }.RunAsync(); - } [Fact] - public async Task TestReadOnlyStructsWithOmit() - { - await new VerifyCS.Test + public Task TestReadOnlyStructsWithOmit() + => new VerifyCS.Test { TestCode = """ namespace Test @@ -442,12 +425,10 @@ readonly struct S1 { } { CodeStyleOptions2.AccessibilityModifiersRequired, AccessibilityModifiersRequired.OmitIfDefault }, }, }.RunAsync(); - } [Fact] - public async Task TestClassOutsideNamespace() - { - await new VerifyCS.Test + public Task TestClassOutsideNamespace() + => new VerifyCS.Test { TestCode = """ internal class [|C1|] { } @@ -460,12 +441,10 @@ class C1 { } { CodeStyleOptions2.AccessibilityModifiersRequired, AccessibilityModifiersRequired.OmitIfDefault }, }, }.RunAsync(); - } [Fact] - public async Task TestExternMethod() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestExternMethod() + => VerifyCS.VerifyCodeFixAsync(""" using System; using System.Runtime.InteropServices; @@ -485,12 +464,10 @@ internal class Program private static extern int [|MessageBox|](IntPtr h, string m, string c, int type); } """); - } [Fact] - public async Task TestVolatile() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestVolatile() + => VerifyCS.VerifyCodeFixAsync(""" internal class Program { volatile int [|x|]; @@ -502,12 +479,10 @@ internal class Program private volatile int x; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48899")] - public async Task TestAbstractMethod() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestAbstractMethod() + => VerifyCS.VerifyCodeFixAsync(""" public abstract class TestClass { abstract string {|CS0621:[|Test|]|} { get; } @@ -519,12 +494,10 @@ public abstract class TestClass protected abstract string Test { get; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48899")] - public async Task TestOverriddenMethod() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestOverriddenMethod() + => VerifyCS.VerifyCodeFixAsync(""" public abstract class TestClass { public abstract string Test { get; } @@ -546,12 +519,10 @@ public class Derived : TestClass public override string Test { get; } } """); - } [Fact] - public async Task TestFileScopedNamespaces() - { - await new VerifyCS.Test + public Task TestFileScopedNamespaces() + => new VerifyCS.Test { TestCode = """ namespace Test; @@ -565,12 +536,13 @@ internal struct S1 { } """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/55703")] public async Task TestPartial_WithExistingModifier() { - var source = """ + var test = new VerifyCS.Test + { + TestCode = """ partial class [|C|] { } @@ -578,8 +550,8 @@ partial class [|C|] public partial class C { } - """; - var fixedSource = """ + """, + FixedCode = """ public partial class C { } @@ -587,12 +559,7 @@ public partial class C public partial class C { } - """; - - var test = new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp12, }; @@ -602,7 +569,9 @@ public partial class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58914")] public async Task TestStaticOperatorInInterface() { - var source = """ + var test = new VerifyCS.Test + { + TestCode = """ internal interface I where T : I { abstract static int operator +(T x); @@ -615,11 +584,7 @@ internal class C : I throw new System.NotImplementedException(); } } - """; - - var test = new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = Testing.ReferenceAssemblies.Net.Net60 }; @@ -635,28 +600,20 @@ internal class C : I [InlineData("interface")] [InlineData("enum")] [WorkItem("https://github.com/dotnet/roslyn/issues/62259")] - public async Task TestFileDeclaration(string declarationKind) - { - var source = $"file {declarationKind} C {{ }}"; - - await new VerifyCS.Test + public Task TestFileDeclaration(string declarationKind) + => new VerifyCS.Test { - TestCode = source, + TestCode = $"file {declarationKind} C {{ }}", LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/62259")] - public async Task TestFileDelegate() - { - var source = "file delegate void M();"; - - await new VerifyCS.Test + public Task TestFileDelegate() + => new VerifyCS.Test { - TestCode = source, + TestCode = "file delegate void M();", LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Theory] [InlineData("class")] @@ -666,50 +623,41 @@ public async Task TestFileDelegate() [InlineData("interface")] [InlineData("enum")] [WorkItem("https://github.com/dotnet/roslyn/issues/62259")] - public async Task TestNestedFileDeclaration(string declarationKind) - { - var source = $$""" + public Task TestNestedFileDeclaration(string declarationKind) + => new VerifyCS.Test + { + TestCode = $$""" file class C1 { {{declarationKind}} [|C2|] { } } - """; - - var fixedSource = $$""" + """, + FixedCode = $$""" file class C1 { private {{declarationKind}} C2 { } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29633")] public async Task TestTitle1() { - var source = """ + var test = new VerifyCS.Test + { + TestCode = """ internal class C { int [|field|]; } - """; - var fixedSource = """ + """, + FixedCode = """ internal class C { private int field; } - """; - - var test = new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp12, CodeActionEquivalenceKey = nameof(AnalyzersResources.Add_accessibility_modifiers), }; @@ -718,25 +666,21 @@ internal class C } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29633")] - public async Task TestTitle2() - { - var source = """ + public Task TestTitle2() + => new VerifyCS.Test + { + TestCode = """ class C { private int [|field|]; } - """; - var fixedSource = """ + """, + FixedCode = """ class C { int field; } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp12, CodeActionEquivalenceKey = nameof(AnalyzersResources.Remove_accessibility_modifiers), Options = @@ -744,13 +688,10 @@ class C { CodeStyleOptions2.AccessibilityModifiersRequired,AccessibilityModifiersRequired.OmitIfDefault } } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/74244")] - public async Task TestAlwaysForInterfaceMembers() - { - - await new VerifyCS.Test + public Task TestAlwaysForInterfaceMembers() + => new VerifyCS.Test { TestCode = """ using System; @@ -793,12 +734,10 @@ private void M() { } { CodeStyleOptions2.AccessibilityModifiersRequired, AccessibilityModifiersRequired.Always } } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/74244")] - public async Task TestOmitIfDefaultForInterfaceMembers() - { - await new VerifyCS.Test + public Task TestOmitIfDefaultForInterfaceMembers() + => new VerifyCS.Test { TestCode = """ using System; @@ -841,12 +780,10 @@ void M() { } { CodeStyleOptions2.AccessibilityModifiersRequired, AccessibilityModifiersRequired.OmitIfDefault } } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/74244")] - public async Task TestForNonInterfaceMembers() - { - await new VerifyCS.Test + public Task TestForNonInterfaceMembers() + => new VerifyCS.Test { TestCode = """ using System; @@ -889,12 +826,10 @@ private void M() { } { CodeStyleOptions2.AccessibilityModifiersRequired, AccessibilityModifiersRequired.ForNonInterfaceMembers } } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78395")] - public async Task TestOmitIfDefaultWithFixedField() - { - await new VerifyCS.Test + public Task TestOmitIfDefaultWithFixedField() + => new VerifyCS.Test { TestCode = """ unsafe struct MyStruct @@ -915,5 +850,4 @@ unsafe struct MyStruct { CodeStyleOptions2.AccessibilityModifiersRequired, AccessibilityModifiersRequired.OmitIfDefault } } }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/AddAnonymousTypeMemberName/AddAnonymousTypeMemberNameTests.cs b/src/Analyzers/CSharp/Tests/AddAnonymousTypeMemberName/AddAnonymousTypeMemberNameTests.cs index b1aeec63412ec..4383dce76b037 100644 --- a/src/Analyzers/CSharp/Tests/AddAnonymousTypeMemberName/AddAnonymousTypeMemberNameTests.cs +++ b/src/Analyzers/CSharp/Tests/AddAnonymousTypeMemberName/AddAnonymousTypeMemberNameTests.cs @@ -25,9 +25,8 @@ internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProvide => (null, new CSharpAddAnonymousTypeMemberNameCodeFixProvider()); [Fact] - public async Task Test1() - { - await TestInRegularAndScript1Async( + public Task Test1() + => TestInRegularAndScript1Async( """ class C { @@ -46,12 +45,10 @@ void M() } } """); - } [Fact] - public async Task TestExistingName() - { - await TestInRegularAndScript1Async( + public Task TestExistingName() + => TestInRegularAndScript1Async( """ class C { @@ -70,12 +67,10 @@ void M() } } """); - } [Fact] - public async Task TestFixAll1() - { - await TestInRegularAndScript1Async( + public Task TestFixAll1() + => TestInRegularAndScript1Async( """ class C { @@ -94,12 +89,10 @@ void M() } } """); - } [Fact] - public async Task TestFixAll2() - { - await TestInRegularAndScript1Async( + public Task TestFixAll2() + => TestInRegularAndScript1Async( """ class C { @@ -118,12 +111,10 @@ void M() } } """); - } [Fact] - public async Task TestFixAll3() - { - await TestInRegularAndScript1Async( + public Task TestFixAll3() + => TestInRegularAndScript1Async( """ class C { @@ -142,5 +133,4 @@ void M() } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/AddBraces/AddBracesFixAllTests.cs b/src/Analyzers/CSharp/Tests/AddBraces/AddBracesFixAllTests.cs index 867a2c4ac8ff5..47523b9eeaf3f 100644 --- a/src/Analyzers/CSharp/Tests/AddBraces/AddBracesFixAllTests.cs +++ b/src/Analyzers/CSharp/Tests/AddBraces/AddBracesFixAllTests.cs @@ -13,9 +13,8 @@ public sealed partial class AddBracesTests { [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInDocument1() - { - var input = """ + public Task TestFixAllInDocument1() + => TestInRegularAndScriptAsync(""" class Program1 { static void Main() @@ -23,9 +22,7 @@ static void Main() {|FixAllInDocument:if|} (true) if (true) return; } } - """; - - var expected = """ + """, """ class Program1 { static void Main() @@ -39,16 +36,12 @@ static void Main() } } } - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInDocument2() - { - var input = """ + public Task TestFixAllInDocument2() + => TestInRegularAndScriptAsync(""" class Program1 { static void Main() @@ -56,9 +49,7 @@ static void Main() if (true) {|FixAllInDocument:if|} (true) return; } } - """; - - var expected = """ + """, """ class Program1 { static void Main() @@ -72,16 +63,12 @@ static void Main() } } } - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInDocument() - { - var input = """ + public Task TestFixAllInDocument() + => TestInRegularAndScriptAsync(""" @@ -116,9 +103,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -160,16 +145,12 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInProject() - { - var input = """ + public Task TestFixAllInProject() + => TestInRegularAndScriptAsync(""" @@ -203,9 +184,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -245,16 +224,12 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInSolution() - { - var input = """ + public Task TestFixAllInSolution() + => TestInRegularAndScriptAsync(""" @@ -288,9 +263,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -333,16 +306,12 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInContainingMember() - { - var input = """ + public Task TestFixAllInContainingMember() + => TestInRegularAndScriptAsync(""" class Program1 { static void Main() @@ -365,9 +334,7 @@ void OtherMethod() if (true) if (true) return; } } - """; - - var expected = """ + """, """ class Program1 { static void Main() @@ -402,16 +369,12 @@ void OtherMethod() if (true) if (true) return; } } - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInContainingType_AcrossSingleFile() - { - var input = """ + public Task TestFixAllInContainingType_AcrossSingleFile() + => TestInRegularAndScriptAsync(""" class Program1 { static void Main() @@ -434,9 +397,7 @@ void OtherMethod() if (true) if (true) return; } } - """; - - var expected = """ + """, """ class Program1 { static void Main() @@ -477,16 +438,12 @@ void OtherMethod() if (true) if (true) return; } } - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInContainingType_AcrossMultipleFiles() - { - var input = """ + public Task TestFixAllInContainingType_AcrossMultipleFiles() + => TestInRegularAndScriptAsync(""" @@ -525,9 +482,7 @@ void OtherTypeMethod() - """; - - var expected = """ + """, """ @@ -590,10 +545,7 @@ void OtherTypeMethod() - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Theory] [InlineData("FixAllInContainingMember")] @@ -601,9 +553,8 @@ void OtherTypeMethod() [Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInContainingMemberAndType_TopLevelStatements(string fixAllScope) - { - var input = $$""" + public Task TestFixAllInContainingMemberAndType_TopLevelStatements(string fixAllScope) + => TestInRegularAndScriptAsync($$""" {|{{fixAllScope}}:if|} (true) if (true) return; if (false) if (false) return; @@ -615,9 +566,7 @@ void OtherMethod() if (true) if (true) return; } } - """; - - var expected = """ + """, """ if (true) { if (true) @@ -641,18 +590,14 @@ void OtherMethod() if (true) if (true) return; } } - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Theory] [InlineData("FixAllInContainingMember")] [InlineData("FixAllInContainingType")] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInContainingMemberAndType_TopLevelStatements_02(string fixAllScope) - { - var input = $$""" + public Task TestFixAllInContainingMemberAndType_TopLevelStatements_02(string fixAllScope) + => TestInRegularAndScriptAsync($$""" using System; {|{{fixAllScope}}:if|} (true) if (true) return; @@ -669,9 +614,7 @@ void OtherMethod() } } } - """; - - var expected = """ + """, """ using System; if (true) @@ -700,19 +643,14 @@ void OtherMethod() } } } - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Theory] [InlineData("FixAllInContainingMember")] [InlineData("FixAllInContainingType")] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInContainingMemberAndType_TopLevelStatements_ErrorCase(string fixAllScope) - { - // Error case: Global statements should precede non-global statements. - var input = $$""" + public Task TestFixAllInContainingMemberAndType_TopLevelStatements_ErrorCase(string fixAllScope) + => TestMissingInRegularAndScriptAsync($$""" class OtherType { void OtherMethod() @@ -724,8 +662,5 @@ void OtherMethod() {|{{fixAllScope}}:if|} (true) if (true) return; if (false) if (false) return; - """; - - await TestMissingInRegularAndScriptAsync(input); - } + """); } diff --git a/src/Analyzers/CSharp/Tests/AddBraces/AddBracesTests.cs b/src/Analyzers/CSharp/Tests/AddBraces/AddBracesTests.cs index a3eed92e3ca07..4323abdea61f5 100644 --- a/src/Analyzers/CSharp/Tests/AddBraces/AddBracesTests.cs +++ b/src/Analyzers/CSharp/Tests/AddBraces/AddBracesTests.cs @@ -31,9 +31,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] - public async Task DoNotFireForIfWithBraces(int bracesPreference) - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotFireForIfWithBraces(int bracesPreference) + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -47,15 +46,13 @@ static void Main() } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); - } [Theory] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] - public async Task DoNotFireForElseWithBraces(int bracesPreference) - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotFireForElseWithBraces(int bracesPreference) + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -73,15 +70,13 @@ static void Main() } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); - } [Theory] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] - public async Task DoNotFireForElseWithChildIf(int bracesPreference) - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotFireForElseWithChildIf(int bracesPreference) + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -95,15 +90,13 @@ static void Main() } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); - } [Theory] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] - public async Task DoNotFireForForWithBraces(int bracesPreference) - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotFireForForWithBraces(int bracesPreference) + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -117,15 +110,13 @@ static void Main() } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); - } [Theory] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] - public async Task DoNotFireForForEachWithBraces(int bracesPreference) - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotFireForForEachWithBraces(int bracesPreference) + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -139,15 +130,13 @@ static void Main() } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); - } [Theory] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] - public async Task DoNotFireForWhileWithBraces(int bracesPreference) - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotFireForWhileWithBraces(int bracesPreference) + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -161,15 +150,13 @@ static void Main() } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); - } [Theory] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] - public async Task DoNotFireForDoWhileWithBraces(int bracesPreference) - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotFireForDoWhileWithBraces(int bracesPreference) + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -184,15 +171,13 @@ static void Main() } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); - } [Theory] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] - public async Task DoNotFireForUsingWithBraces(int bracesPreference) - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotFireForUsingWithBraces(int bracesPreference) + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -214,15 +199,13 @@ public void Dispose() } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); - } [Theory] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] - public async Task DoNotFireForUsingWithChildUsing(int bracesPreference) - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotFireForUsingWithChildUsing(int bracesPreference) + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -251,15 +234,13 @@ public void Dispose() } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); - } [Theory] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] - public async Task DoNotFireForLockWithBraces(int bracesPreference) - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotFireForLockWithBraces(int bracesPreference) + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -274,15 +255,13 @@ static void Main() } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); - } [Theory] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] - public async Task DoNotFireForLockWithChildLock(int bracesPreference) - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotFireForLockWithChildLock(int bracesPreference) + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -297,15 +276,13 @@ static void Main() } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); - } [Theory] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] - public async Task DoNotFireForFixedWithChildFixed(int bracesPreference) - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotFireForFixedWithChildFixed(int bracesPreference) + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -319,15 +296,13 @@ unsafe static void Main() } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForFixedWithoutBraces(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForFixedWithoutBraces(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -354,15 +329,13 @@ unsafe static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForIfWithoutBraces(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForIfWithoutBraces(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -387,15 +360,13 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/57770")] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForIfWithoutBracesTopLevel(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForIfWithoutBracesTopLevel(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ [|if|] (true) return; """, @@ -407,15 +378,13 @@ await TestAsync( """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForElseWithoutBracesButHasContextBraces(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForElseWithoutBracesButHasContextBraces(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -442,15 +411,13 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForElseWithoutBraces(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForElseWithoutBraces(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -477,15 +444,13 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForStandaloneElseWithoutBraces(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForStandaloneElseWithoutBraces(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -511,15 +476,13 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForIfNestedInElseWithoutBraces(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForIfNestedInElseWithoutBraces(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -546,15 +509,13 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForIfNestedInElseWithoutBracesWithMultilineContext1(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForIfNestedInElseWithoutBracesWithMultilineContext1(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -589,15 +550,13 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForIfNestedInElseWithoutBracesWithMultilineContext2(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForIfNestedInElseWithoutBracesWithMultilineContext2(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -636,15 +595,13 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForIfNestedInElseWithoutBracesWithMultilineContext3(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForIfNestedInElseWithoutBracesWithMultilineContext3(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -682,15 +639,13 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForIfNestedInElseWithoutBracesWithMultilineContext4(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForIfNestedInElseWithoutBracesWithMultilineContext4(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -728,7 +683,6 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } #pragma warning disable CA1200 // Avoid using cref tags with a prefix - Remove the suppression when https://github.com/dotnet/roslyn/issues/42611 is fixed. /// @@ -742,9 +696,8 @@ static void Main() [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForIfNestedInElseWithoutBracesWithMultilineContext5(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForIfNestedInElseWithoutBracesWithMultilineContext5(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -782,15 +735,13 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForForWithoutBraces(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForForWithoutBraces(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -815,15 +766,13 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForMultilineForWithoutBraces1(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForMultilineForWithoutBraces1(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -852,15 +801,13 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForMultilineForWithoutBraces2(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForMultilineForWithoutBraces2(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -887,15 +834,13 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForMultilineForWithoutBraces3(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForMultilineForWithoutBraces3(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -923,15 +868,13 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForForEachWithoutBraces(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForForEachWithoutBraces(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -956,15 +899,13 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForWhileWithoutBraces(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForWhileWithoutBraces(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -989,15 +930,13 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForDoWhileWithoutBraces1(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForDoWhileWithoutBraces1(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -1023,15 +962,13 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForDoWhileWithoutBraces2(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForDoWhileWithoutBraces2(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -1059,15 +996,13 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForMultilineDoWhileWithoutBraces1(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForMultilineDoWhileWithoutBraces1(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -1095,15 +1030,13 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForUsingWithoutBraces(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForUsingWithoutBraces(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -1145,15 +1078,13 @@ public void Dispose() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForUsingWithoutBracesNestedInUsing(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForUsingWithoutBracesNestedInUsing(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -1213,15 +1144,13 @@ public void Dispose() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForMultilineUsingWithoutBracesNestedInUsing1(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForMultilineUsingWithoutBracesNestedInUsing1(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -1283,15 +1212,13 @@ public void Dispose() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForMultilineUsingWithoutBracesNestedInUsing2(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForMultilineUsingWithoutBracesNestedInUsing2(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -1353,15 +1280,13 @@ public void Dispose() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForLockWithoutBraces(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForLockWithoutBraces(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -1389,15 +1314,13 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] - public async Task FireForLockWithoutBracesNestedInLock(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForLockWithoutBracesNestedInLock(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ class Program { @@ -1431,16 +1354,14 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] [WorkItem("https://github.com/dotnet/roslyn/issues/32480")] - public async Task DoNotFireForIfWhenIntercedingDirectiveBefore(int bracesPreference) - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotFireForIfWhenIntercedingDirectiveBefore(int bracesPreference) + => TestMissingInRegularAndScriptAsync( """ #define test class Program @@ -1455,16 +1376,14 @@ static void Main() } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); - } [Theory] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] [WorkItem("https://github.com/dotnet/roslyn/issues/32480")] - public async Task DoNotFireForIfWithIntercedingDirectiveAfter(int bracesPreference) - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotFireForIfWithIntercedingDirectiveAfter(int bracesPreference) + => TestMissingInRegularAndScriptAsync( """ #define test class Program @@ -1479,16 +1398,14 @@ static void Main() } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); - } [Theory] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] [WorkItem("https://github.com/dotnet/roslyn/issues/32480")] - public async Task DoNotFireForIfElseWithIntercedingDirectiveInBoth(int bracesPreference) - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotFireForIfElseWithIntercedingDirectiveInBoth(int bracesPreference) + => TestMissingInRegularAndScriptAsync( """ #define test class Program @@ -1505,16 +1422,14 @@ static void Main() } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem("https://github.com/dotnet/roslyn/issues/32480")] - public async Task OnlyFireForIfWithIntercedingDirectiveInElseAroundIf(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task OnlyFireForIfWithIntercedingDirectiveInElseAroundIf(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ #define test class Program @@ -1550,16 +1465,14 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem("https://github.com/dotnet/roslyn/issues/32480")] - public async Task OnlyFireForElseWithIntercedingDirectiveInIfAroundElse(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task OnlyFireForElseWithIntercedingDirectiveInIfAroundElse(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ #define test class Program @@ -1595,16 +1508,14 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem("https://github.com/dotnet/roslyn/issues/32480")] - public async Task OnlyFireForElseWithIntercedingDirectiveInIf(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task OnlyFireForElseWithIntercedingDirectiveInIf(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ #define test class Program @@ -1640,16 +1551,14 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem("https://github.com/dotnet/roslyn/issues/32480")] - public async Task OnlyFireForIfWithIntercedingDirectiveInElse(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task OnlyFireForIfWithIntercedingDirectiveInElse(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ #define test class Program @@ -1685,16 +1594,14 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem("https://github.com/dotnet/roslyn/issues/32480")] - public async Task FireForIfElseWithDirectiveAroundIf(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForIfElseWithDirectiveAroundIf(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ #define test class Program @@ -1734,16 +1641,14 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem("https://github.com/dotnet/roslyn/issues/32480")] - public async Task FireForIfElseWithDirectiveAroundElse(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForIfElseWithDirectiveAroundElse(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ #define test class Program @@ -1783,16 +1688,14 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem("https://github.com/dotnet/roslyn/issues/32480")] - public async Task FireForIfWithoutIntercedingDirective(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForIfWithoutIntercedingDirective(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ #define test class Program @@ -1824,16 +1727,14 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem("https://github.com/dotnet/roslyn/issues/32480")] - public async Task FireForIfWithDirectiveAfterEmbeddedStatement(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForIfWithDirectiveAfterEmbeddedStatement(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ #define test class Program @@ -1865,16 +1766,14 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem("https://github.com/dotnet/roslyn/issues/32480")] - public async Task FireForInnerNestedStatementWhenDirectiveEntirelyInside(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForInnerNestedStatementWhenDirectiveEntirelyInside(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ #define test class Program @@ -1908,16 +1807,14 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } [Theory] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem("https://github.com/dotnet/roslyn/issues/32480")] - public async Task FireForOuterNestedStatementWhenDirectiveEntirelyInside(int bracesPreference, bool expectDiagnostic) - { - await TestAsync( + public Task FireForOuterNestedStatementWhenDirectiveEntirelyInside(int bracesPreference, bool expectDiagnostic) + => TestAsync( """ #define test class Program @@ -1951,7 +1848,6 @@ static void Main() """, (PreferBracesPreference)bracesPreference, expectDiagnostic); - } private async Task TestAsync(string initialMarkup, string expectedMarkup, PreferBracesPreference bracesPreference, bool expectDiagnostic) { diff --git a/src/Analyzers/CSharp/Tests/AddExplicitCast/AddExplicitCastTests.cs b/src/Analyzers/CSharp/Tests/AddExplicitCast/AddExplicitCastTests.cs index dd4ed4904b05c..483305cd2fb86 100644 --- a/src/Analyzers/CSharp/Tests/AddExplicitCast/AddExplicitCastTests.cs +++ b/src/Analyzers/CSharp/Tests/AddExplicitCast/AddExplicitCastTests.cs @@ -26,9 +26,8 @@ protected override ImmutableArray MassageActions(ImmutableArray FlattenActions(actions); [Fact] - public async Task SimpleVariableDeclaration() - { - await TestInRegularAndScriptAsync( + public Task SimpleVariableDeclaration() + => TestInRegularAndScriptAsync( """ class Program { @@ -53,12 +52,10 @@ void M() } } """); - } [Fact] - public async Task SimpleVariableDeclarationWithFunctionInnvocation() - { - await TestInRegularAndScriptAsync( + public Task SimpleVariableDeclarationWithFunctionInnvocation() + => TestInRegularAndScriptAsync( """ class Program { @@ -93,12 +90,10 @@ void M() } } """); - } [Fact] - public async Task ReturnStatementWithObject() - { - await TestInRegularAndScriptAsync( + public Task ReturnStatementWithObject() + => TestInRegularAndScriptAsync( """ class Program { @@ -123,12 +118,10 @@ Derived returnBase() { } } """); - } [Fact] - public async Task ReturnStatementWithIEnumerable() - { - await TestInRegularAndScriptAsync( + public Task ReturnStatementWithIEnumerable() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; class Program @@ -155,12 +148,10 @@ IEnumerable returnBase() { } } """); - } [Fact] - public async Task ReturnStatementWithIEnumerator() - { - await TestInRegularAndScriptAsync( + public Task ReturnStatementWithIEnumerator() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; class Program @@ -187,12 +178,10 @@ IEnumerator returnBase() { } } """); - } [Fact] - public async Task ReturnStatementWithFunctionInnvocation() - { - await TestInRegularAndScriptAsync( + public Task ReturnStatementWithFunctionInnvocation() + => TestInRegularAndScriptAsync( """ class Program { @@ -225,12 +214,10 @@ Derived returnDerived() { } } """); - } [Fact] - public async Task SimpleFunctionArgumentsWithObject1() - { - await TestInRegularAndScriptAsync( + public Task SimpleFunctionArgumentsWithObject1() + => TestInRegularAndScriptAsync( """ class Program { @@ -269,12 +256,10 @@ void M() { } } """); - } [Fact] - public async Task SimpleFunctionArgumentsWithObject2() - { - await TestInRegularAndScriptAsync( + public Task SimpleFunctionArgumentsWithObject2() + => TestInRegularAndScriptAsync( """ class Program { @@ -313,12 +298,10 @@ void M() { } } """); - } [Fact] - public async Task SimpleFunctionArgumentsWithFunctionInvocation() - { - await TestInRegularAndScriptAsync( + public Task SimpleFunctionArgumentsWithFunctionInvocation() + => TestInRegularAndScriptAsync( """ class Program { @@ -355,12 +338,10 @@ void M() { } } """); - } [Fact] - public async Task YieldReturnStatementWithObject() - { - await TestInRegularAndScriptAsync( + public Task YieldReturnStatementWithObject() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; class Program @@ -387,12 +368,10 @@ IEnumerable returnDerived() { } } """); - } [Fact] - public async Task SimpleConstructorArgumentsWithObject() - { - await TestInRegularAndScriptAsync( + public Task SimpleConstructorArgumentsWithObject() + => TestInRegularAndScriptAsync( """ class Program { @@ -423,12 +402,10 @@ void M() { } } """); - } [Fact] - public async Task ReturnTypeWithTask() - { - await TestInRegularAndScriptAsync( + public Task ReturnTypeWithTask() + => TestInRegularAndScriptAsync( """ using System.Threading.Tasks; @@ -457,12 +434,10 @@ async Task M() { } } """); - } [Fact] - public async Task VariableDeclarationWithPublicFieldMember() - { - await TestInRegularAndScriptAsync( + public Task VariableDeclarationWithPublicFieldMember() + => TestInRegularAndScriptAsync( """ class Program { @@ -497,12 +472,10 @@ void M() { } } """); - } [Fact] - public async Task VariableDeclarationWithPrivateFieldMember() - { - await TestMissingInRegularAndScriptAsync( + public Task VariableDeclarationWithPrivateFieldMember() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -520,12 +493,10 @@ void M() { } } """); - } [Fact] - public async Task PublicMemberFunctionArgument1() - { - await TestInRegularAndScriptAsync( + public Task PublicMemberFunctionArgument1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -556,12 +527,10 @@ void M() { } } """); - } [Fact] - public async Task PublicMemberFunctionArgument2() - { - await TestInRegularAndScriptAsync( + public Task PublicMemberFunctionArgument2() + => TestInRegularAndScriptAsync( """ class Program { @@ -594,12 +563,10 @@ void M() { } } """); - } [Fact] - public async Task PrivateMemberFunctionArgument() - { - await TestMissingInRegularAndScriptAsync( + public Task PrivateMemberFunctionArgument() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -616,12 +583,10 @@ void M() { } } """); - } [Fact] - public async Task MemberFunctions() - { - await TestInRegularAndScriptAsync( + public Task MemberFunctions() + => TestInRegularAndScriptAsync( """ class Program { @@ -656,12 +621,10 @@ void M() { } } """); - } [Fact] - public async Task BaseConstructorArgument() - { - await TestInRegularAndScriptAsync( + public Task BaseConstructorArgument() + => TestInRegularAndScriptAsync( """ class Program { @@ -688,12 +651,10 @@ public Derived_Test (Base b) : base((Derived)b) {} } } """); - } [Fact] - public async Task ThisConstructorArgument() - { - await TestInRegularAndScriptAsync( + public Task ThisConstructorArgument() + => TestInRegularAndScriptAsync( """ class Program { @@ -716,12 +677,10 @@ public Test(Base b, int i) : this((Derived)b) {} } } """); - } [Fact] - public async Task LambdaFunction1() - { - await TestInRegularAndScriptAsync( + public Task LambdaFunction1() + => TestInRegularAndScriptAsync( """ using System; @@ -746,12 +705,10 @@ void M() { } } """); - } [Fact] - public async Task LambdaFunction2() - { - await TestInRegularAndScriptAsync( + public Task LambdaFunction2() + => TestInRegularAndScriptAsync( """ using System; @@ -782,12 +739,10 @@ void Goo() { } } """); - } [Fact] - public async Task LambdaFunction3() - { - await TestInRegularAndScriptAsync( + public Task LambdaFunction3() + => TestInRegularAndScriptAsync( """ using System; @@ -818,12 +773,10 @@ void Goo() { } } """); - } [Fact] - public async Task LambdaFunction4() - { - await TestInRegularAndScriptAsync( + public Task LambdaFunction4() + => TestInRegularAndScriptAsync( """ using System; @@ -854,12 +807,10 @@ Derived Goo() { } } """); - } [Fact] - public async Task LambdaFunction5_ReturnStatement() - { - await TestMissingInRegularAndScriptAsync( + public Task LambdaFunction5_ReturnStatement() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -873,12 +824,10 @@ Action Goo() { } } """); - } [Fact] - public async Task LambdaFunction6_Arguments() - { - await TestInRegularAndScriptAsync( + public Task LambdaFunction6_Arguments() + => TestInRegularAndScriptAsync( """ using System; @@ -909,12 +858,10 @@ void Goo() { } } """); - } [Fact] - public async Task LambdaFunction7_Arguments() - { - await TestMissingInRegularAndScriptAsync( + public Task LambdaFunction7_Arguments() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -930,12 +877,10 @@ void Goo() { } } """); - } [Fact] - public async Task LambdaFunction8_Arguments() - { - await TestInRegularAndScriptAsync( + public Task LambdaFunction8_Arguments() + => TestInRegularAndScriptAsync( """ using System; @@ -966,12 +911,10 @@ void Goo() { } } """); - } [Fact] - public async Task LambdaFunction9_Arguments() - { - await TestMissingInRegularAndScriptAsync( + public Task LambdaFunction9_Arguments() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -987,12 +930,10 @@ void Goo() { } } """); - } [Fact] - public async Task InheritInterfaces1() - { - await TestInRegularAndScriptAsync( + public Task InheritInterfaces1() + => TestInRegularAndScriptAsync( """ class Program { @@ -1017,12 +958,10 @@ void Goo(Base2 b) { } } """); - } [Fact] - public async Task InheritInterfaces2() - { - await TestInRegularAndScriptAsync( + public Task InheritInterfaces2() + => TestInRegularAndScriptAsync( """ class Program { @@ -1049,12 +988,10 @@ void Goo(Base2 b) { } } """); - } [Fact] - public async Task InheritInterfaces3() - { - await TestInRegularAndScriptAsync( + public Task InheritInterfaces3() + => TestInRegularAndScriptAsync( """ class Program { @@ -1077,12 +1014,10 @@ Base2 Goo(Base1 b) { } } """); - } [Fact] - public async Task InheritInterfaces4() - { - await TestInRegularAndScriptAsync( + public Task InheritInterfaces4() + => TestInRegularAndScriptAsync( """ class Program { @@ -1105,12 +1040,10 @@ void Goo(Base1 b) { } } """); - } [Fact] - public async Task InheritInterfaces5() - { - await TestInRegularAndScriptAsync( + public Task InheritInterfaces5() + => TestInRegularAndScriptAsync( """ class Program { @@ -1141,12 +1074,10 @@ void M(Base1 b) { } } """); - } [Fact] - public async Task GenericType() - { - await TestInRegularAndScriptAsync( + public Task GenericType() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -1175,12 +1106,10 @@ void M() } } """); - } [Fact] - public async Task GenericType2() - { - await TestInRegularAndScriptAsync( + public Task GenericType2() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -1211,12 +1140,10 @@ void M() } } """); - } [Fact] - public async Task GenericType3() - { - await TestInRegularAndScriptAsync( + public Task GenericType3() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -1243,12 +1170,10 @@ Func Goo(Func func) } } """); - } [Fact] - public async Task GenericType4() - { - await TestInRegularAndScriptAsync( + public Task GenericType4() + => TestInRegularAndScriptAsync( """ class Program { @@ -1281,12 +1206,10 @@ public interface A where T : IA { } public class B : A where T : CB { } } """); - } [Fact] - public async Task GenericType5() - { - await TestMissingInRegularAndScriptAsync( + public Task GenericType5() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -1303,12 +1226,10 @@ public class A where T : IA { } public class B : A where T : IB { } } """); - } [Fact] - public async Task GenericType6() - { - await TestInRegularAndScriptAsync( + public Task GenericType6() + => TestInRegularAndScriptAsync( """ class Program { @@ -1341,12 +1262,10 @@ public interface A where T : IA { } public class B : A where T : IB { } } """); - } [Fact] - public async Task ObjectInitializer() - { - await TestMissingInRegularAndScriptAsync( + public Task ObjectInitializer() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -1362,12 +1281,10 @@ void M() { } } """); - } [Fact] - public async Task ObjectInitializer2() - { - await TestInRegularAndScriptAsync( + public Task ObjectInitializer2() + => TestInRegularAndScriptAsync( """ class Program { @@ -1398,12 +1315,10 @@ void M() { } } """); - } [Fact] - public async Task ObjectInitializer3() - { - await TestMissingInRegularAndScriptAsync( + public Task ObjectInitializer3() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -1418,12 +1333,10 @@ Derived returnDerived() { } } """); - } [Fact] - public async Task ObjectInitializer4() - { - await TestInRegularAndScriptAsync( + public Task ObjectInitializer4() + => TestInRegularAndScriptAsync( """ class Program { @@ -1452,12 +1365,10 @@ Derived returnDerived() { } } """); - } [Fact] - public async Task ObjectInitializer5() - { - await TestMissingInRegularAndScriptAsync( + public Task ObjectInitializer5() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -1473,12 +1384,10 @@ void Goo() { } } """); - } [Fact] - public async Task ObjectInitializer6() - { - await TestInRegularAndScriptAsync( + public Task ObjectInitializer6() + => TestInRegularAndScriptAsync( """ class Program { @@ -1509,12 +1418,10 @@ void Goo() { } } """); - } [Fact] - public async Task ObjectInitializer7() - { - await TestMissingInRegularAndScriptAsync( + public Task ObjectInitializer7() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -1530,12 +1437,10 @@ void Goo() { } } """); - } [Fact] - public async Task RedundantCast1() - { - await TestInRegularAndScriptAsync( + public Task RedundantCast1() + => TestInRegularAndScriptAsync( """ class Program { @@ -1558,12 +1463,10 @@ void Goo() { } } """); - } [Fact] - public async Task RedundantCast2() - { - await TestInRegularAndScriptAsync( + public Task RedundantCast2() + => TestInRegularAndScriptAsync( """ class Program { @@ -1588,12 +1491,10 @@ void Goo() { } } """); - } [Fact] - public async Task RedundantCast3() - { - await TestInRegularAndScriptAsync( + public Task RedundantCast3() + => TestInRegularAndScriptAsync( """ class Program { @@ -1618,12 +1519,10 @@ void Goo() { } } """); - } [Fact] - public async Task RedundantCast4() - { - await TestInRegularAndScriptAsync( + public Task RedundantCast4() + => TestInRegularAndScriptAsync( """ class Program { @@ -1650,12 +1549,10 @@ void Goo() { } } """); - } [Fact] - public async Task ExactMethodCandidate() - { - await TestMissingInRegularAndScriptAsync( + public Task ExactMethodCandidate() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -1676,12 +1573,10 @@ void M() } } """); - } [Fact] - public async Task MethodCandidates1_ArgumentsInOrder_NoLabels() - { - await TestInRegularAndScriptAsync( + public Task MethodCandidates1_ArgumentsInOrder_NoLabels() + => TestInRegularAndScriptAsync( """ class Program { @@ -1714,12 +1609,10 @@ void M() } } """); - } [Fact] - public async Task MethodCandidates2_ArgumentsInOrder_NoLabels() - { - await TestInRegularAndScriptAsync( + public Task MethodCandidates2_ArgumentsInOrder_NoLabels() + => TestInRegularAndScriptAsync( """ class Program { @@ -1756,12 +1649,10 @@ void M() } } """); - } [Fact] - public async Task MethodCandidates3_ArgumentsInOrder_NoLabels_Params() - { - await TestInRegularAndScriptAsync( + public Task MethodCandidates3_ArgumentsInOrder_NoLabels_Params() + => TestInRegularAndScriptAsync( """ class Program { @@ -1798,12 +1689,10 @@ void M() } } """); - } [Fact] - public async Task MethodCandidates4_ArgumentsInOrder_NoLabels_Params() - { - await TestInRegularAndScriptAsync( + public Task MethodCandidates4_ArgumentsInOrder_NoLabels_Params() + => TestInRegularAndScriptAsync( """ class Program { @@ -1840,12 +1729,10 @@ void M() } } """); - } [Fact] - public async Task MethodCandidates5_ArgumentsInOrder_NoLabels_Params() - { - await TestInRegularAndScriptAsync( + public Task MethodCandidates5_ArgumentsInOrder_NoLabels_Params() + => TestInRegularAndScriptAsync( """ class Program { @@ -1882,12 +1769,10 @@ void M() } } """); - } [Fact] - public async Task MethodCandidates6_ArgumentsInOrder_NoLabels_Params() - { - await TestInRegularAndScriptAsync( + public Task MethodCandidates6_ArgumentsInOrder_NoLabels_Params() + => TestInRegularAndScriptAsync( """ class Program { @@ -1922,12 +1807,10 @@ void M() } } """); - } [Fact] - public async Task MethodCandidates7_ArgumentsInOrder_NoLabels_Params() - { - await TestInRegularAndScriptAsync( + public Task MethodCandidates7_ArgumentsInOrder_NoLabels_Params() + => TestInRegularAndScriptAsync( """ class Program { @@ -1962,12 +1845,10 @@ void M() } } """); - } [Fact] - public async Task MethodCandidates8_ArgumentsInOrder_NoLabels() - { - await TestInRegularAndScriptAsync( + public Task MethodCandidates8_ArgumentsInOrder_NoLabels() + => TestInRegularAndScriptAsync( """ namespace ExtensionMethods { @@ -2012,12 +1893,10 @@ public static void Goo(this string str, Derived d, Derived d2) { } } } """); - } [Fact] - public async Task MethodCandidates9_ArgumentsOutOfOrder_NoLabels() - { - await TestMissingInRegularAndScriptAsync( + public Task MethodCandidates9_ArgumentsOutOfOrder_NoLabels() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -2035,12 +1914,10 @@ void M() } } """); - } [Fact] - public async Task MethodCandidates10_ArgumentsInOrder_SomeLabels() - { - await TestInRegularAndScriptAsync( + public Task MethodCandidates10_ArgumentsInOrder_SomeLabels() + => TestInRegularAndScriptAsync( """ class Program { @@ -2075,12 +1952,10 @@ void M() } } """); - } [Fact] - public async Task MethodCandidates11_ArgumentsInOrder_SomeLabels_Params() - { - await TestInRegularAndScriptAsync( + public Task MethodCandidates11_ArgumentsInOrder_SomeLabels_Params() + => TestInRegularAndScriptAsync( """ class Program { @@ -2117,12 +1992,10 @@ void M() } } """); - } [Fact] - public async Task MethodCandidates12_ArgumentsInOrder_SomeLabels_Params() - { - await TestInRegularAndScriptAsync( + public Task MethodCandidates12_ArgumentsInOrder_SomeLabels_Params() + => TestInRegularAndScriptAsync( """ class Program { @@ -2159,12 +2032,10 @@ void M() } } """); - } [Fact] - public async Task MethodCandidates13_ArgumentsOutOfOrder_SomeLabels() - { - await TestMissingInRegularAndScriptAsync( + public Task MethodCandidates13_ArgumentsOutOfOrder_SomeLabels() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -2183,12 +2054,10 @@ void M() } } """); - } [Fact] - public async Task MethodCandidates14_ArgumentsOutOfOrder_AllLabels() - { - await TestInRegularAndScriptAsync( + public Task MethodCandidates14_ArgumentsOutOfOrder_AllLabels() + => TestInRegularAndScriptAsync( """ class Program { @@ -2225,12 +2094,10 @@ void M() } } """); - } [Fact] - public async Task MethodCandidates15_ArgumentsOutOfOrder_AllLabels() - { - await TestMissingInRegularAndScriptAsync( + public Task MethodCandidates15_ArgumentsOutOfOrder_AllLabels() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -2249,12 +2116,10 @@ void M() } } """); - } [Fact] - public async Task MethodCandidates17_ArgumentsInOrder_SomeLabels() - { - await TestInRegularAndScriptAsync( + public Task MethodCandidates17_ArgumentsInOrder_SomeLabels() + => TestInRegularAndScriptAsync( """ class Program { @@ -2289,12 +2154,10 @@ void M() } } """); - } [Fact] - public async Task MethodCandidates18_ArgumentsInOrder_SomeLabels() - { - await TestInRegularAndScriptAsync( + public Task MethodCandidates18_ArgumentsInOrder_SomeLabels() + => TestInRegularAndScriptAsync( """ class Program { @@ -2331,12 +2194,10 @@ void M() } } """); - } [Fact] - public async Task MethodCandidates19_ArgumentsInOrder_NoLabels_Params() - { - await TestMissingInRegularAndScriptAsync( + public Task MethodCandidates19_ArgumentsInOrder_NoLabels_Params() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -2355,12 +2216,10 @@ void M() } } """); - } [Fact] - public async Task MethodCandidates20_ArgumentsInOrder_NoLabels_Params() - { - await TestMissingInRegularAndScriptAsync( + public Task MethodCandidates20_ArgumentsInOrder_NoLabels_Params() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -2379,12 +2238,10 @@ void M() } } """); - } [Fact] - public async Task MethodCandidates21_ArgumentsInOrder_Labels() - { - await TestMissingInRegularAndScriptAsync( + public Task MethodCandidates21_ArgumentsInOrder_Labels() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -2400,12 +2257,10 @@ void M() } } """); - } [Fact] - public async Task MethodCandidates22_ArgumentsInOrder() - { - await TestMissingInRegularAndScriptAsync( + public Task MethodCandidates22_ArgumentsInOrder() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -2424,12 +2279,10 @@ void M() } } """); - } [Fact] - public async Task ConstructorCandidates1() - { - await TestInRegularAndScriptAsync( + public Task ConstructorCandidates1() + => TestInRegularAndScriptAsync( """ class Program { @@ -2472,12 +2325,10 @@ void M() } } """); - } [Fact] - public async Task ConstructorCandidates2() - { - await TestInRegularAndScriptAsync( + public Task ConstructorCandidates2() + => TestInRegularAndScriptAsync( """ class Program { @@ -2524,12 +2375,10 @@ void M() } } """); - } [Fact] - public async Task ConstructorCandidates3() - { - await TestInRegularAndScriptAsync( + public Task ConstructorCandidates3() + => TestInRegularAndScriptAsync( """ class Program { @@ -2560,7 +2409,6 @@ public Test(string s, Base b, int i, params object[] list) : this(d : (Derived)b } } """); - } [Fact] public async Task MultipleOptions1() @@ -2588,8 +2436,7 @@ public Test(string s, Base b, int i, params object[] list) : this(d : [||]b, s : Assert.Equal(2, actions.Length); } - var expect_0 = - """ + await TestInRegularAndScriptAsync(initialMarkup, """ class Program { class Base { } @@ -2604,12 +2451,9 @@ public Test(string s, Base b, int i, params object[] list) : this(d : (Derived)b Test(string s, Derived2 d, int i) { } } } - """; - await TestInRegularAndScriptAsync(initialMarkup, expect_0, index: 0, + """, index: 0, title: string.Format(CodeFixesResources.Convert_type_to_0, "Derived")); - - var expect_1 = - """ + await TestInRegularAndScriptAsync(initialMarkup, """ class Program { class Base { } @@ -2624,8 +2468,7 @@ public Test(string s, Base b, int i, params object[] list) : this(d : (Derived2) Test(string s, Derived2 d, int i) { } } } - """; - await TestInRegularAndScriptAsync(initialMarkup, expect_1, index: 1, + """, index: 1, title: string.Format(CodeFixesResources.Convert_type_to_0, "Derived2")); } @@ -2656,8 +2499,7 @@ public Test(string s, Base b, int i, params object[] list) : this(d : [||]b, s : Assert.Equal(2, actions.Length); } - var expect_0 = - """ + await TestInRegularAndScriptAsync(initialMarkup, """ class Program { class Base { } @@ -2672,12 +2514,9 @@ public Test(string s, Base b, int i, params object[] list) : this(d : (Derived)b Test(string s, int i, Derived2 d) { } } } - """; - await TestInRegularAndScriptAsync(initialMarkup, expect_0, index: 0, + """, index: 0, title: string.Format(CodeFixesResources.Convert_type_to_0, "Derived")); - - var expect_1 = - """ + await TestInRegularAndScriptAsync(initialMarkup, """ class Program { class Base { } @@ -2692,17 +2531,14 @@ public Test(string s, Base b, int i, params object[] list) : this(d : (Derived2) Test(string s, int i, Derived2 d) { } } } - """; - await TestInRegularAndScriptAsync(initialMarkup, expect_1, index: 1, + """, index: 1, title: string.Format(CodeFixesResources.Convert_type_to_0, "Derived2")); } [Fact] - public async Task MultipleOptions3() - { - var initialMarkup = - """ + public Task MultipleOptions3() + => TestInRegularAndScriptAsync(""" class Program { class Base { } @@ -2717,9 +2553,7 @@ public Test(string s, Base b, int i, params object[] list) : this(d : [||]b, s : Test(string s, Derived d, int i, params object[] list)) { } } } - """; - var expected = - """ + """, """ class Program { class Base { } @@ -2734,15 +2568,11 @@ public Test(string s, Base b, int i, params object[] list) : this(d : (Derived)b Test(string s, Derived d, int i, params object[] list)) { } } } - """; - await TestInRegularAndScriptAsync(initialMarkup, expected); - } + """); [Fact] - public async Task MultipleOptions4() - { - var initialMarkup = - """ + public Task MultipleOptions4() + => TestInRegularAndScriptAsync(""" class Program { class Base { } @@ -2760,9 +2590,7 @@ void M() Goo("", 1, i:1, d: [||]b); } } - """; - var expected = - """ + """, """ class Program { class Base { } @@ -2780,9 +2608,7 @@ void M() Goo("", 1, i:1, d: (Derived)b); } } - """; - await TestInRegularAndScriptAsync(initialMarkup, expected); - } + """); [Fact] public async Task MultipleOptions5() @@ -2813,8 +2639,7 @@ void M() Assert.Equal(2, actions.Length); } - var expect_0 = - """ + await TestInRegularAndScriptAsync(initialMarkup, """ class Program { class Base { } @@ -2832,12 +2657,9 @@ void M() Goo("", d: (Derived)b, list: strlist, i: 1); } } - """; - await TestInRegularAndScriptAsync(initialMarkup, expect_0, index: 0, + """, index: 0, title: string.Format(CodeFixesResources.Convert_type_to_0, "Derived")); - - var expect_1 = - """ + await TestInRegularAndScriptAsync(initialMarkup, """ class Program { class Base { } @@ -2855,8 +2677,7 @@ void M() Goo("", d: (Derived2)b, list: strlist, i: 1); } } - """; - await TestInRegularAndScriptAsync(initialMarkup, expect_1, index: 1, + """, index: 1, title: string.Format(CodeFixesResources.Convert_type_to_0, "Derived2")); } @@ -2892,8 +2713,7 @@ void M() Assert.Equal(3, actions.Length); } - var expect_0 = - """ + await TestInRegularAndScriptAsync(initialMarkup, """ class Program { class Base { @@ -2914,12 +2734,9 @@ void M() Goo("", d: (string)b, i: 1); } } - """; - await TestInRegularAndScriptAsync(initialMarkup, expect_0, index: 0, + """, index: 0, title: string.Format(CodeFixesResources.Convert_type_to_0, "string")); - - var expect_1 = - """ + await TestInRegularAndScriptAsync(initialMarkup, """ class Program { class Base { @@ -2940,12 +2757,9 @@ void M() Goo("", d: (Derived)b, i: 1); } } - """; - await TestInRegularAndScriptAsync(initialMarkup, expect_1, index: 1, + """, index: 1, title: string.Format(CodeFixesResources.Convert_type_to_0, "Derived")); - - var expect_2 = - """ + await TestInRegularAndScriptAsync(initialMarkup, """ class Program { class Base { @@ -2966,16 +2780,13 @@ void M() Goo("", d: (Derived2)b, i: 1); } } - """; - await TestInRegularAndScriptAsync(initialMarkup, expect_2, index: 2, + """, index: 2, title: string.Format(CodeFixesResources.Convert_type_to_0, "Derived2")); } [Fact] - public async Task MultipleOptions7() - { - var initialMarkup = - """ + public Task MultipleOptions7() + => TestInRegularAndScriptAsync(""" class Program { class Base { } @@ -2994,9 +2805,7 @@ void M() Goo(s1:"", 1, d: [||]b); } } - """; - var expected = - """ + """, """ class Program { class Base { } @@ -3015,15 +2824,11 @@ void M() Goo(s1:"", 1, d: (Derived)b); } } - """; - await TestInRegularAndScriptAsync(initialMarkup, expected); - } + """); [Fact] - public async Task MultipleOptions8() - { - var initialMarkup = - """ + public Task MultipleOptions8() + => TestInRegularAndScriptAsync(""" class Program { class Base { } @@ -3041,9 +2846,7 @@ void M() Foo4([||]b, "1", "2", list: strlist); } } - """; - var expected = - """ + """, """ class Program { class Base { } @@ -3061,15 +2864,11 @@ void M() Foo4((Derived)b, "1", "2", list: strlist); } } - """; - await TestInRegularAndScriptAsync(initialMarkup, expected); - } + """); [Fact] - public async Task MultipleOptions9() - { - var initialMarkup = - """ + public Task MultipleOptions9() + => TestMissingInRegularAndScriptAsync(""" class Program { class Base { } @@ -3084,14 +2883,11 @@ void M() { Goo([||]new Base()); } } - """; - await TestMissingInRegularAndScriptAsync(initialMarkup); - } + """); [Fact] - public async Task MultipleErrors1() - { - await TestInRegularAndScriptAsync( + public Task MultipleErrors1() + => TestInRegularAndScriptAsync( """ class Program { @@ -3124,12 +2920,10 @@ void Goo(Base b) { } } """); - } [Fact] - public async Task MultipleErrors2() - { - await TestInRegularAndScriptAsync( + public Task MultipleErrors2() + => TestInRegularAndScriptAsync( """ class Program { @@ -3162,12 +2956,10 @@ void Goo(Base b) { } } """); - } [Fact] - public async Task ErrorType() - { - await TestMissingInRegularAndScriptAsync( + public Task ErrorType() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -3178,12 +2970,10 @@ void M(C c) } } """); - } [Fact] - public async Task AttributeArgument() - { - await TestInRegularAndScriptAsync( + public Task AttributeArgument() + => TestInRegularAndScriptAsync( """ using System; class C @@ -3208,12 +2998,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50493")] - public async Task ArrayAccess() - { - await TestInRegularAndScriptAsync( + public Task ArrayAccess() + => TestInRegularAndScriptAsync( """ class C { @@ -3236,12 +3024,10 @@ public void M(object o) } } """); - } [Fact] - public async Task RemoveExistingCast1() - { - await TestInRegularAndScriptAsync( + public Task RemoveExistingCast1() + => TestInRegularAndScriptAsync( """ class Program { @@ -3266,12 +3052,10 @@ void Goo() { } } """); - } [Fact, WorkItem(56141, "https://github.com/dotnet/roslyn/issues/56141")] - public async Task CompoundAssignment1() - { - await TestInRegularAndScriptAsync( + public Task CompoundAssignment1() + => TestInRegularAndScriptAsync( """ class C { @@ -3294,12 +3078,10 @@ void M() } } """); - } [Fact, WorkItem(56141, "https://github.com/dotnet/roslyn/issues/56141")] - public async Task CompoundAssignment2() - { - await TestInRegularAndScriptAsync( + public Task CompoundAssignment2() + => TestInRegularAndScriptAsync( """ class C { @@ -3322,12 +3104,10 @@ void M() } } """); - } [Fact, WorkItem(56141, "https://github.com/dotnet/roslyn/issues/56141")] - public async Task CompoundAssignment3() - { - await TestInRegularAndScriptAsync( + public Task CompoundAssignment3() + => TestInRegularAndScriptAsync( """ class C { @@ -3350,12 +3130,10 @@ void M() } } """); - } [Fact, WorkItem(56141, "https://github.com/dotnet/roslyn/issues/56141")] - public async Task CompoundAssignment4() - { - await TestInRegularAndScriptAsync( + public Task CompoundAssignment4() + => TestInRegularAndScriptAsync( """ class C { @@ -3378,12 +3156,10 @@ void M() } } """); - } [Fact, WorkItem(56141, "https://github.com/dotnet/roslyn/issues/56141")] - public async Task CompoundAssignment5() - { - await TestInRegularAndScriptAsync( + public Task CompoundAssignment5() + => TestInRegularAndScriptAsync( """ class C { @@ -3406,5 +3182,4 @@ void M() } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/AddExplicitCast/AddExplicitCastTests_FixAllTests.cs b/src/Analyzers/CSharp/Tests/AddExplicitCast/AddExplicitCastTests_FixAllTests.cs index cad6b00cbdf78..d85f3cea7d164 100644 --- a/src/Analyzers/CSharp/Tests/AddExplicitCast/AddExplicitCastTests_FixAllTests.cs +++ b/src/Analyzers/CSharp/Tests/AddExplicitCast/AddExplicitCastTests_FixAllTests.cs @@ -15,9 +15,8 @@ public sealed partial class AddExplicitCastTests [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task CS0266TestFixAllInDocument() - { - var input = """ + public Task CS0266TestFixAllInDocument() + => TestInRegularAndScriptAsync(""" @@ -155,9 +154,7 @@ Derived2 returnD2(Base b) - """; - - var expected = """ + """, """ @@ -295,17 +292,13 @@ Derived2 returnD2(Base b) - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task CS0266TestFixAllInProject() - { - var input = """ + public Task CS0266TestFixAllInProject() + => TestInRegularAndScriptAsync(""" @@ -443,9 +436,7 @@ Derived2 returnD2(Base b) - """; - - var expected = """ + """, """ @@ -583,17 +574,13 @@ Derived2 returnD2(Base b) - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task CS0266TestFixAllInSolution() - { - var input = """ + public Task CS0266TestFixAllInSolution() + => TestInRegularAndScriptAsync(""" @@ -731,9 +718,7 @@ Derived2 returnD2(Base b) - """; - - var expected = """ + """, """ @@ -871,17 +856,13 @@ Derived2 returnD2(Base b) - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task CS1503TestFixAllInDocument() - { - var input = """ + public Task CS1503TestFixAllInDocument() + => TestInRegularAndScriptAsync(""" @@ -1007,9 +988,7 @@ private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2) - """; - - var expected = """ + """, """ @@ -1135,17 +1114,13 @@ private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2) - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task CS1503TestFixAllInProject() - { - var input = """ + public Task CS1503TestFixAllInProject() + => TestInRegularAndScriptAsync(""" @@ -1310,9 +1285,7 @@ private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2) - """; - - var expected = """ + """, """ @@ -1477,17 +1450,13 @@ private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2) - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task CS1503TestFixAllInSolution() - { - var input = """ + public Task CS1503TestFixAllInSolution() + => TestInRegularAndScriptAsync(""" @@ -1615,9 +1584,7 @@ private void M2(Base b, Derived1 d1, Derived2 d2) - """; - - var expected = """ + """, """ @@ -1745,9 +1712,6 @@ private void M2(Base b, Derived1 d1, Derived2 d2) - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); #endregion } diff --git a/src/Analyzers/CSharp/Tests/AddInheritdoc/AddInheritdocTests.cs b/src/Analyzers/CSharp/Tests/AddInheritdoc/AddInheritdocTests.cs index 029b1309b31b1..55327f641a8db 100644 --- a/src/Analyzers/CSharp/Tests/AddInheritdoc/AddInheritdocTests.cs +++ b/src/Analyzers/CSharp/Tests/AddInheritdoc/AddInheritdocTests.cs @@ -31,9 +31,8 @@ private static Task TestMissingAsync(string initialMarkup) => VerifyCS.VerifyCodeFixAsync(initialMarkup, initialMarkup); [Fact] - public async Task AddMissingInheritdocOnOverriddenMethod() - { - await TestAsync( + public Task AddMissingInheritdocOnOverriddenMethod() + => TestAsync( """ /// Some doc. public class BaseClass @@ -61,15 +60,13 @@ public class Derived: BaseClass public override void M() { } } """); - } [Theory] [InlineData("public void {|CS1591:OtherMethod|}() { }")] [InlineData("public void {|CS1591:M|}() { }")] [InlineData("public new void {|CS1591:M|}() { }")] - public async Task DoNotOfferOnNotOverriddenMethod(string methodDefinition) - { - await TestMissingAsync( + public Task DoNotOfferOnNotOverriddenMethod(string methodDefinition) + => TestMissingAsync( $$""" /// Some doc. public class BaseClass @@ -83,12 +80,10 @@ public class Derived: BaseClass {{methodDefinition}} } """); - } [Fact] - public async Task AddMissingInheritdocOnImplicitInterfaceMethod() - { - await TestAsync( + public Task AddMissingInheritdocOnImplicitInterfaceMethod() + => TestAsync( """ /// Some doc. public interface IInterface @@ -116,12 +111,10 @@ public class MyClass: IInterface public void M() { } } """); - } [Fact] - public async Task DoNotOfferOnExplicitInterfaceMethod() - { - await TestMissingAsync( + public Task DoNotOfferOnExplicitInterfaceMethod() + => TestMissingAsync( """ /// Some doc. public interface IInterface @@ -135,11 +128,9 @@ public class MyClass: IInterface void IInterface.M() { } } """); - } [Fact] - public async Task AddMissingInheritdocOnOverriddenProperty() - { - await TestAsync( + public Task AddMissingInheritdocOnOverriddenProperty() + => TestAsync( """ /// Some doc. public class BaseClass @@ -167,12 +158,10 @@ public class Derived: BaseClass public override string P { get; set; } } """); - } [Fact] - public async Task AddMissingInheritdocOnImplicitInterfaceProperty() - { - await TestAsync( + public Task AddMissingInheritdocOnImplicitInterfaceProperty() + => TestAsync( """ /// Some doc. public interface IInterface @@ -200,12 +189,10 @@ public class MyClass: IInterface public string P { get; } } """); - } [Fact] - public async Task AddMissingInheritdocOnImplicitInterfaceEvent() - { - await TestAsync( + public Task AddMissingInheritdocOnImplicitInterfaceEvent() + => TestAsync( """ /// Some doc. public interface IInterface @@ -237,12 +224,10 @@ public class MyClass: IInterface void OnSomething() => SomeEvent?.Invoke(); } """); - } [Fact] - public async Task AddMissingInheritdocTriviaTest_1() - { - await TestAsync( + public Task AddMissingInheritdocTriviaTest_1() + => TestAsync( """ /// Some doc. public class BaseClass @@ -272,12 +257,10 @@ public class Derived: BaseClass public override void M() { } } """); - } [Fact] - public async Task AddMissingInheritdocTriviaTest_2() - { - await TestAsync( + public Task AddMissingInheritdocTriviaTest_2() + => TestAsync( """ /// Some doc. public class BaseClass @@ -307,12 +290,10 @@ public class Derived: BaseClass public /* Comment 3 */ override void M /* Comment 4 */ () /* Comment 5 */ { } /* Comment 6 */ } """); - } [Fact] - public async Task AddMissingInheritdocMethodWithAttribute() - { - await TestAsync( + public Task AddMissingInheritdocMethodWithAttribute() + => TestAsync( """ /// Some doc. [System.AttributeUsage(System.AttributeTargets.Method)] @@ -354,12 +335,10 @@ public class Derived: BaseClass public override void M() { } } """); - } [Fact] - public async Task AddMissingInheritdocFixAll() - { - await TestAsync( + public Task AddMissingInheritdocFixAll() + => TestAsync( """ /// Some doc. public class BaseClass @@ -394,12 +373,10 @@ public override void M() { } public override string P { get; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61562")] - public async Task TestOverrideBelowMember() - { - await TestAsync( + public Task TestOverrideBelowMember() + => TestAsync( """ using System; @@ -455,5 +432,4 @@ public class Class2 : Class1 } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/AddObsoleteAttribute/AddObsoleteAttributeTests.cs b/src/Analyzers/CSharp/Tests/AddObsoleteAttribute/AddObsoleteAttributeTests.cs index a90a3a2687f14..a940ac5dcca60 100644 --- a/src/Analyzers/CSharp/Tests/AddObsoleteAttribute/AddObsoleteAttributeTests.cs +++ b/src/Analyzers/CSharp/Tests/AddObsoleteAttribute/AddObsoleteAttributeTests.cs @@ -3,21 +3,24 @@ // See the LICENSE file in the project root for more information. using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CSharp.AddObsoleteAttribute; +using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; +using Microsoft.CodeAnalysis.Testing; using Xunit; -using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< - Microsoft.CodeAnalysis.Testing.EmptyDiagnosticAnalyzer, - Microsoft.CodeAnalysis.CSharp.AddObsoleteAttribute.CSharpAddObsoleteAttributeCodeFixProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddObsoleteAttribute; +using VerifyCS = CSharpCodeFixVerifier< + EmptyDiagnosticAnalyzer, + CSharpAddObsoleteAttributeCodeFixProvider>; + [Trait(Traits.Feature, Traits.Features.CodeActionsAddObsoleteAttribute)] public sealed class AddObsoleteAttributeTests { [Fact] - public async Task TestObsoleteClassNoMessage() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestObsoleteClassNoMessage() + => VerifyCS.VerifyCodeFixAsync( """ [System.Obsolete] class Base {} @@ -33,12 +36,10 @@ class Base {} class Derived : Base { } """); - } [Fact] - public async Task TestObsoleteClassWithMessage() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestObsoleteClassWithMessage() + => VerifyCS.VerifyCodeFixAsync( """ [System.Obsolete("message")] class Base {} @@ -54,12 +55,10 @@ class Base {} class Derived : Base { } """); - } [Fact] - public async Task TestObsoleteClassWithMessageAndErrorFalse() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestObsoleteClassWithMessageAndErrorFalse() + => VerifyCS.VerifyCodeFixAsync( """ [System.Obsolete("message", error: false)] class Base {} @@ -75,7 +74,6 @@ class Base {} class Derived : Base { } """); - } [Fact] public async Task TestObsoleteClassWithMessageAndErrorTrue() @@ -91,9 +89,8 @@ class Derived : {|CS0619:Base|} { } [Fact] - public async Task TestObsoleteClassUsedInField() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestObsoleteClassUsedInField() + => VerifyCS.VerifyCodeFixAsync( """ [System.Obsolete] class Base { public static int i; } @@ -111,12 +108,10 @@ class Derived { int i = Base.i; } """); - } [Fact] - public async Task TestObsoleteClassUsedInMethod() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestObsoleteClassUsedInMethod() + => VerifyCS.VerifyCodeFixAsync( """ [System.Obsolete] class Base { public static int i; } @@ -138,12 +133,10 @@ void Goo() { } } """); - } [Fact] - public async Task TestObsoleteOverride() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestObsoleteOverride() + => VerifyCS.VerifyCodeFixAsync( """ class Base { [System.Obsolete] @@ -165,12 +158,10 @@ class Derived : Base { protected override void ObMethod() { } } """); - } [Fact] - public async Task TestObsoleteClassFixAll1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestObsoleteClassFixAll1() + => VerifyCS.VerifyCodeFixAsync( """ [System.Obsolete] class Base { public static int i; } @@ -194,12 +185,10 @@ void Goo() { } } """); - } [Fact] - public async Task TestObsoleteClassFixAll2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestObsoleteClassFixAll2() + => VerifyCS.VerifyCodeFixAsync( """ [System.Obsolete] class Base { public static int i; } @@ -223,12 +212,10 @@ void Goo() { } } """); - } [Fact] - public async Task TestObsoleteClassFixAll3() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestObsoleteClassFixAll3() + => VerifyCS.VerifyCodeFixAsync( """ [System.Obsolete] class Base { public static int i; } @@ -259,12 +246,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestObsoleteCollectionAddMethod() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestObsoleteCollectionAddMethod() + => VerifyCS.VerifyCodeFixAsync( """ class Collection : System.Collections.Generic.IEnumerable { [System.Obsolete] @@ -300,12 +285,10 @@ void Goo() { } } """); - } [Fact] - public async Task TestObsoleteCollectionAddMethodWithMessage() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestObsoleteCollectionAddMethodWithMessage() + => VerifyCS.VerifyCodeFixAsync( """ class Collection : System.Collections.Generic.IEnumerable { [System.Obsolete("message")] @@ -341,12 +324,10 @@ void Goo() { } } """); - } [Fact] - public async Task TestObsoleteCollectionAddMethodWithMessageAndErrorFalse() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestObsoleteCollectionAddMethodWithMessageAndErrorFalse() + => VerifyCS.VerifyCodeFixAsync( """ class Collection : System.Collections.Generic.IEnumerable { [System.Obsolete("message", error: false)] @@ -382,7 +363,6 @@ void Goo() { } } """); - } [Fact] public async Task TestObsoleteCollectionAddMethodWithMessageAndErrorTrue() diff --git a/src/Analyzers/CSharp/Tests/AddParameter/AddParameterTests.cs b/src/Analyzers/CSharp/Tests/AddParameter/AddParameterTests.cs index 4ba988c1bd171..c93c2fe17ac50 100644 --- a/src/Analyzers/CSharp/Tests/AddParameter/AddParameterTests.cs +++ b/src/Analyzers/CSharp/Tests/AddParameter/AddParameterTests.cs @@ -29,9 +29,8 @@ protected override ImmutableArray MassageActions(ImmutableArray FlattenActions(actions); [Fact] - public async Task TestMissingWithImplicitConstructor() - { - await TestMissingAsync( + public Task TestMissingWithImplicitConstructor() + => TestMissingAsync( """ class C { @@ -45,12 +44,10 @@ void M() } } """); - } [Fact] - public async Task TestOnEmptyConstructor() - { - await TestInRegularAndScriptAsync( + public Task TestOnEmptyConstructor() + => TestInRegularAndScriptAsync( """ class C { @@ -79,12 +76,10 @@ void M() } } """); - } [Fact] - public async Task TestNamedArg() - { - await TestInRegularAndScriptAsync( + public Task TestNamedArg() + => TestInRegularAndScriptAsync( """ class C { @@ -113,12 +108,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingWithConstructorWithSameNumberOfParams() - { - await TestMissingAsync( + public Task TestMissingWithConstructorWithSameNumberOfParams() + => TestMissingAsync( """ class C { @@ -133,12 +126,10 @@ void M() } } """); - } [Fact] - public async Task TestAddBeforeMatchingArg() - { - await TestInRegularAndScriptAsync( + public Task TestAddBeforeMatchingArg() + => TestInRegularAndScriptAsync( """ class C { @@ -167,12 +158,10 @@ void M() } } """); - } [Fact] - public async Task TestAddAfterMatchingConstructorParam() - { - await TestInRegularAndScriptAsync( + public Task TestAddAfterMatchingConstructorParam() + => TestInRegularAndScriptAsync( """ class C { @@ -201,12 +190,10 @@ void M() } } """); - } [Fact] - public async Task TestParams1() - { - await TestInRegularAndScriptAsync( + public Task TestParams1() + => TestInRegularAndScriptAsync( """ class C { @@ -235,12 +222,10 @@ void M() } } """); - } [Fact] - public async Task TestParams2() - { - await TestMissingAsync( + public Task TestParams2() + => TestMissingAsync( """ class C { @@ -255,12 +240,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20708")] - public async Task TestMultiLineParameters1() - { - await TestInRegularAndScriptAsync( + public Task TestMultiLineParameters1() + => TestInRegularAndScriptAsync( """ class C { @@ -292,12 +275,10 @@ private void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20708")] - public async Task TestMultiLineParameters2() - { - await TestInRegularAndScriptAsync( + public Task TestMultiLineParameters2() + => TestInRegularAndScriptAsync( """ class C { @@ -329,12 +310,10 @@ private void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20708")] - public async Task TestMultiLineParameters3() - { - await TestInRegularAndScriptAsync( + public Task TestMultiLineParameters3() + => TestInRegularAndScriptAsync( """ class C { @@ -366,12 +345,10 @@ private void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20708")] - public async Task TestMultiLineParameters4() - { - await TestInRegularAndScriptAsync( + public Task TestMultiLineParameters4() + => TestInRegularAndScriptAsync( """ class C { @@ -405,12 +382,10 @@ private void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20708")] - public async Task TestMultiLineParameters5() - { - await TestInRegularAndScriptAsync( + public Task TestMultiLineParameters5() + => TestInRegularAndScriptAsync( """ class C { @@ -444,12 +419,10 @@ private void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20708")] - public async Task TestMultiLineParameters6() - { - await TestInRegularAndScriptAsync( + public Task TestMultiLineParameters6() + => TestInRegularAndScriptAsync( """ class C { @@ -483,12 +456,10 @@ private void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20973")] - public async Task TestNullArg1() - { - await TestInRegularAndScriptAsync( + public Task TestNullArg1() + => TestInRegularAndScriptAsync( """ class C { @@ -517,12 +488,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20973")] - public async Task TestNullArg2() - { - await TestInRegularAndScriptAsync( + public Task TestNullArg2() + => TestInRegularAndScriptAsync( """ class C { @@ -551,12 +520,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20973")] - public async Task TestDefaultArg1() - { - await TestInRegularAndScriptAsync( + public Task TestDefaultArg1() + => TestInRegularAndScriptAsync( """ class C { @@ -585,12 +552,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20973")] - public async Task TestDefaultArg2() - { - await TestInRegularAndScriptAsync( + public Task TestDefaultArg2() + => TestInRegularAndScriptAsync( """ class C { @@ -619,12 +584,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocationInstanceMethod1() - { - await TestInRegularAndScriptAsync( + public Task TestInvocationInstanceMethod1() + => TestInRegularAndScriptAsync( """ class C { @@ -651,12 +614,10 @@ void M2() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocationInheritedMethodGetFixed() - { - await TestInRegularAndScriptAsync( + public Task TestInvocationInheritedMethodGetFixed() + => TestInRegularAndScriptAsync( """ class Base { @@ -689,12 +650,10 @@ void M2() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocationInheritedMethodInMetadatGetsNotFixed() - { - await TestMissingAsync( + public Task TestInvocationInheritedMethodInMetadatGetsNotFixed() + => TestMissingAsync( """ class C1 { @@ -705,12 +664,10 @@ void M2() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocationLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestInvocationLocalFunction() + => TestInRegularAndScriptAsync( """ class C1 { @@ -731,13 +688,11 @@ void M1() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] [Trait("TODO", "Fix broken")] - public async Task TestInvocationLambda1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestInvocationLambda1() + => TestMissingInRegularAndScriptAsync( """ using System; class C1 @@ -749,13 +704,10 @@ void M1() } } """); - //Should be Action a = (int v) => { }; - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocationStaticMethod() - { - await TestInRegularAndScriptAsync( + public Task TestInvocationStaticMethod() + => TestInRegularAndScriptAsync( """ class C1 { @@ -780,13 +732,10 @@ void M2() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocationExtensionMethod() - { - var code = - """ + public Task TestInvocationExtensionMethod() + => TestInRegularAndScriptAsync(""" namespace N { static class Extensions { @@ -801,9 +750,7 @@ void M1() new object().[|ExtensionM1|](1); } }} - """; - var fix = - """ + """, """ namespace N { static class Extensions { @@ -818,16 +765,11 @@ void M1() new object().ExtensionM1(1); } }} - """; - await TestInRegularAndScriptAsync(code, fix); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocationExtensionMethod_StaticInvocationStyle() - { - // error CS1501: No overload for method 'ExtensionM1' takes 2 arguments - var code = - """ + public Task TestInvocationExtensionMethod_StaticInvocationStyle() + => TestInRegularAndScriptAsync(""" namespace N { static class Extensions { @@ -842,9 +784,7 @@ void M1() Extensions.[|ExtensionM1|](new object(), 1); } }} - """; - var fix = - """ + """, """ namespace N { static class Extensions { @@ -859,9 +799,7 @@ void M1() Extensions.ExtensionM1(new object(), 1); } }} - """; - await TestInRegularAndScriptAsync(code, fix); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] public async Task TestInvocationOverride() @@ -880,7 +818,7 @@ void M2() } } """; - var fix_DeclarationOnly = """ + await TestInRegularAndScriptAsync(code, """ class Base { protected virtual void M1() { } @@ -893,8 +831,8 @@ void M2() M1(1); } } - """; - var fix_All = """ + """, index: 0); + await TestInRegularAndScriptAsync(code, """ class Base { protected virtual void M1(int v) { } @@ -907,9 +845,7 @@ void M2() M1(1); } } - """; - await TestInRegularAndScriptAsync(code, fix_DeclarationOnly, index: 0); - await TestInRegularAndScriptAsync(code, fix_All, index: 1); + """, index: 1); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] @@ -929,7 +865,7 @@ void M2() } } """; - var fix_DeclarationOnly = """ + await TestInRegularAndScriptAsync(code, """ interface I1 { void M1(int v); @@ -942,8 +878,8 @@ void M2() ((I1)this).M1(1); } } - """; - var fix_All = """ + """, index: 0); + await TestInRegularAndScriptAsync(code, """ interface I1 { void M1(int v); @@ -956,9 +892,7 @@ void M2() ((I1)this).M1(1); } } - """; - await TestInRegularAndScriptAsync(code, fix_DeclarationOnly, index: 0); - await TestInRegularAndScriptAsync(code, fix_All, index: 1); + """, index: 1); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] @@ -979,7 +913,7 @@ void M2() } } """; - var fix_DeclarationOnly = """ + await TestInRegularAndScriptAsync(code, """ interface I1 { void M1(); @@ -992,8 +926,8 @@ void M2() M1(1); } } - """; - var fix_All = """ + """, index: 0); + await TestInRegularAndScriptAsync(code, """ interface I1 { void M1(int v); @@ -1006,9 +940,7 @@ void M2() M1(1); } } - """; - await TestInRegularAndScriptAsync(code, fix_DeclarationOnly, index: 0); - await TestInRegularAndScriptAsync(code, fix_All, index: 1); + """, index: 1); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] @@ -1033,7 +965,7 @@ void M2() } } """; - var fix_DeclarationOnly = """ + await TestInRegularAndScriptAsync(code, """ interface I1 { void M1(); @@ -1050,8 +982,8 @@ void M2() M1(1); } } - """; - var fix_All = """ + """, index: 0); + await TestInRegularAndScriptAsync(code, """ interface I1 { void M1(int v); @@ -1068,16 +1000,13 @@ void M2() M1(1); } } - """; - await TestInRegularAndScriptAsync(code, fix_DeclarationOnly, index: 0); - await TestInRegularAndScriptAsync(code, fix_All, index: 1); + """, index: 1); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] [Trait("TODO", "Fix broken")] - public async Task TestInvocationGenericMethod() - { - await TestInRegularAndScriptAsync( + public Task TestInvocationGenericMethod() + => TestInRegularAndScriptAsync( """ class C1 { @@ -1098,12 +1027,10 @@ void M2() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocationRecursion() - { - await TestInRegularAndScriptAsync( + public Task TestInvocationRecursion() + => TestInRegularAndScriptAsync( """ class C1 { @@ -1122,7 +1049,6 @@ void M1(int v) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] public async Task TestInvocationOverloads1() @@ -1139,8 +1065,7 @@ void M2() } } """; - var fix0 = - """ + await TestInRegularAndScriptAsync(code, """ class C1 { void M1(string s) { } @@ -1150,9 +1075,8 @@ void M2() M1(1, 2); } } - """; - var fix1 = - """ + """, 0); + await TestInRegularAndScriptAsync(code, """ class C1 { void M1(int v, string s) { } @@ -1162,9 +1086,7 @@ void M2() M1(1, 2); } } - """; - await TestInRegularAndScriptAsync(code, fix0, 0); - await TestInRegularAndScriptAsync(code, fix1, 1); + """, 1); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] @@ -1183,8 +1105,7 @@ void M2() } } """; - var fix0 = - """ + await TestInRegularAndScriptAsync(code, """ class C1 { void M1(string s1, string s2) { } @@ -1195,9 +1116,8 @@ void M2() M1(1, 2); } } - """; - var fix1 = - """ + """, 0); + await TestInRegularAndScriptAsync(code, """ class C1 { void M1(string s1, string s2) { } @@ -1208,16 +1128,12 @@ void M2() M1(1, 2); } } - """; - await TestInRegularAndScriptAsync(code, fix0, 0); - await TestInRegularAndScriptAsync(code, fix1, 1); + """, 1); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocationTuple1() - { - var code = - """ + public Task TestInvocationTuple1() + => TestInRegularAndScriptAsync(""" class C1 { void M1((int, int) t1) @@ -1228,9 +1144,7 @@ void M2() [|M1|]((0, 0), (1, "1")); } } - """; - var fix0 = - """ + """, """ class C1 { void M1((int, int) t1, (int, string) value) @@ -1241,15 +1155,11 @@ void M2() M1((0, 0), (1, "1")); } } - """; - await TestInRegularAndScriptAsync(code, fix0, 0); - } + """, 0); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocationTuple2() - { - var code = - """ + public Task TestInvocationTuple2() + => TestInRegularAndScriptAsync(""" class C1 { void M1((int, int) t1) @@ -1261,9 +1171,7 @@ void M2() [|M1|]((0, 0), tup); } } - """; - var fix0 = - """ + """, """ class C1 { void M1((int, int) t1, (int, string) tup) @@ -1275,15 +1183,11 @@ void M2() M1((0, 0), tup); } } - """; - await TestInRegularAndScriptAsync(code, fix0, 0); - } + """, 0); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocationTuple3() - { - var code = - """ + public Task TestInvocationTuple3() + => TestInRegularAndScriptAsync(""" class C1 { void M1((int, int) t1) @@ -1295,9 +1199,7 @@ void M2() [|M1|]((0, 0), tup); } } - """; - var fix0 = - """ + """, """ class C1 { void M1((int, int) t1, (int i, string s) tup) @@ -1309,16 +1211,11 @@ void M2() M1((0, 0), tup); } } - """; - await TestInRegularAndScriptAsync(code, fix0, 0); - } + """, 0); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_Missing_TypeArguments_AddingTypeArgumentAndParameter() - { - // error CS0305: Using the generic method 'C1.M1(T)' requires 1 type arguments - var code = - """ + public Task TestInvocation_Missing_TypeArguments_AddingTypeArgumentAndParameter() + => TestMissingInRegularAndScriptAsync(""" class C1 { void M1(T i) { } @@ -1327,17 +1224,11 @@ void M2() [|M1|](1, true); } } - """; - // Could be fixed as void M1(T i, T1 v) { } - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_Missing_TypeArguments_AddingTypeArgument() - { - // error CS0308: The non-generic method 'C1.M1(int)' cannot be used with type arguments - var code = - """ + public Task TestInvocation_Missing_TypeArguments_AddingTypeArgument() + => TestMissingInRegularAndScriptAsync(""" class C1 { void M1(int i) { } @@ -1346,18 +1237,12 @@ void M2() [|M1|](1, true); } } - """; - // Could be fixed as void M1(int i, T v) { } - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] [Trait("TODO", "Fix missing")] - public async Task TestInvocation_Missing_ExplicitInterfaceImplementation() - { - // error CS0539: 'C1.M1(int)' in explicit interface declaration is not a member of interface - var code = - """ + public Task TestInvocation_Missing_ExplicitInterfaceImplementation() + => TestMissingAsync(""" interface I1 { void M1(); @@ -1367,17 +1252,11 @@ class C1 : I1 void I1.M1() { } void I1.[|M1|](int i) { } } - """; - // Could apply argument to interface method: void M1(int i); - await TestMissingAsync(code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_OverloadResolutionFailure() - { - // error CS1503: Argument 1: cannot convert from 'double' to 'int' - var code = - """ + public Task TestInvocation_OverloadResolutionFailure() + => TestInRegularAndScriptAsync(""" class C1 { void M1(int i1, int i2) { } @@ -1387,9 +1266,7 @@ void M2() M1([|1.0|], 1); } } - """; - var fix0 = - """ + """, """ class C1 { void M1(int i1, int i2) { } @@ -1399,16 +1276,11 @@ void M2() M1(1.0, 1); } } - """; - await TestInRegularAndScriptAsync(code, fix0); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_LambdaExpressionParameter() - { - // error CS1660: Cannot convert lambda expression to type 'int' because it is not a delegate type - var code = - """ + public Task TestInvocation_LambdaExpressionParameter() + => TestInRegularAndScriptAsync(""" class C1 { void M1(int i1, int i2) { } @@ -1418,9 +1290,7 @@ void M2() M1([|()=> { }|], 1); } } - """; - var fix = - """ + """, """ class C1 { void M1(int i1, int i2) { } @@ -1430,16 +1300,11 @@ void M2() M1(()=> { }, 1); } } - """; - await TestInRegularAndScriptAsync(code, fix); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_NamedParameter() - { - // error CS1739: The best overload for 'M1' does not have a parameter named 'i2' - var code = - """ + public Task TestInvocation_NamedParameter() + => TestInRegularAndScriptAsync(""" class C1 { void M1(int i1) { } @@ -1448,9 +1313,7 @@ void M2() M1([|i2|]: 1); } } - """; - var fix = - """ + """, """ class C1 { void M1(int i1, int i2) { } @@ -1459,15 +1322,11 @@ void M2() M1(i2: 1); } } - """; - await TestInRegularAndScriptAsync(code, fix); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocationAddTypeParameter_AddTypeParameterIfUserSpecifiesOne_OnlyTypeArgument() - { - var code = - """ + public Task TestInvocationAddTypeParameter_AddTypeParameterIfUserSpecifiesOne_OnlyTypeArgument() + => TestMissingInRegularAndScriptAsync(""" class C1 { void M1() { } @@ -1476,16 +1335,11 @@ void M2() [|M1|](); } } - """; - // Could be fixed as void M1() { } - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocationAddTypeParameter_AddTypeParameterIfUserSpecifiesOne_TypeArgumentAndParameterArgument() - { - var code = - """ + public Task TestInvocationAddTypeParameter_AddTypeParameterIfUserSpecifiesOne_TypeArgumentAndParameterArgument() + => TestMissingInRegularAndScriptAsync(""" class C1 { void M1() { } @@ -1494,16 +1348,11 @@ void M2() [|M1|](true); } } - """; - // Could be fixed to void M1(T v) { } - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_ExisitingTypeArgumentIsNotGeneralized() - { - var code = - """ + public Task TestInvocation_ExisitingTypeArgumentIsNotGeneralized() + => TestInRegularAndScriptAsync(""" class C1 { void M1(T v) { } @@ -1512,9 +1361,7 @@ void M2() [|M1|](true, true); } } - """; - var fix0 = - """ + """, """ class C1 { void M1(T v, bool v1) { } @@ -1523,16 +1370,11 @@ void M2() M1(true, true); } } - """; - await TestInRegularAndScriptAsync(code, fix0); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_AddParameterToMethodWithParams() - { - // error CS1503: Argument 1: cannot convert from 'bool' to 'int' - var code = - """ + public Task TestInvocation_AddParameterToMethodWithParams() + => TestInRegularAndScriptAsync(""" class C1 { static void M1(params int[] nums) { } @@ -1541,9 +1383,7 @@ static void M2() M1([|true|], 4); } } - """; - var fix0 = - """ + """, """ class C1 { static void M1(bool v, params int[] nums) { } @@ -1552,9 +1392,7 @@ static void M2() M1(true, 4); } } - """; - await TestInRegularAndScriptAsync(code, fix0); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] public async Task TestInvocation_Cascading_FixingVirtualFixesOverrideToo() @@ -1578,8 +1416,7 @@ void M2() } } """; - var fix_DeclarationOnly = - """ + await TestInRegularAndScriptAsync(code, """ class BaseClass { protected virtual void M1(int v) { } @@ -1595,9 +1432,8 @@ void M2() M1(1); } } - """; - var fix_All = - """ + """, index: 0); + await TestInRegularAndScriptAsync(code, """ class BaseClass { protected virtual void M1(int v) { } @@ -1613,16 +1449,12 @@ void M2() M1(1); } } - """; - await TestInRegularAndScriptAsync(code, fix_DeclarationOnly, index: 0); - await TestInRegularAndScriptAsync(code, fix_All, index: 1); + """, index: 1); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_Cascading_PartialMethods() - { - var code = - """ + public Task TestInvocation_Cascading_PartialMethods() + => TestInRegularAndScriptAsync(""" @@ -1649,9 +1481,7 @@ void M1() - """; - var fix0 = - """ + """, """ @@ -1678,15 +1508,11 @@ void M1() - """; - await TestInRegularAndScriptAsync(code, fix0); - } + """); [Fact] - public async Task TestInvocation_Cascading_ExtendedPartialMethods() - { - var code = - """ + public Task TestInvocation_Cascading_ExtendedPartialMethods() + => TestInRegularAndScriptAsync(""" @@ -1713,9 +1539,7 @@ void M1() - """; - var fix0 = - """ + """, """ @@ -1742,15 +1566,11 @@ void M1() - """; - await TestInRegularAndScriptAsync(code, fix0); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_Cascading_PartialMethodsInSameDocument() - { - var code = - """ + public Task TestInvocation_Cascading_PartialMethodsInSameDocument() + => TestInRegularAndScriptAsync(""" namespace N1 { partial class C1 @@ -1766,9 +1586,7 @@ void M1() } } } - """; - var fix0 = - """ + """, """ namespace N1 { partial class C1 @@ -1784,16 +1602,11 @@ void M1() } } } - """; - await TestInRegularAndScriptAsync(code, fix0); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_Cascading_BaseNotInSource() - { - // error CS1501: No overload for method 'M' takes 1 arguments - var code = - """ + public Task TestInvocation_Cascading_BaseNotInSource() + => TestMissingAsync(""" @@ -1821,9 +1634,7 @@ public void M2() - """; - await TestMissingAsync(code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] public async Task TestInvocation_Cascading_RootNotInSource() @@ -1859,7 +1670,7 @@ public void M2() """; - var fixedDocumentWithoutConflictAnnotation = """ + await TestInRegularAndScriptAsync(code, """ namespace N { public class Derived: BaseClass @@ -1874,8 +1685,8 @@ public void M2() } } } - """; - var fixedDocumentWithConflictAnnotation = """ + """, index: 0); + await TestInRegularAndScriptAsync(code, """ namespace N { public class Derived: BaseClass @@ -1890,17 +1701,12 @@ public void M2() } } } - """; - await TestInRegularAndScriptAsync(code, fixedDocumentWithoutConflictAnnotation, index: 0); - await TestInRegularAndScriptAsync(code, fixedDocumentWithConflictAnnotation, index: 1); + """, index: 1); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_Cascading_ManyReferencesInManyProjects() - { - // error CS1501: No overload for method 'M' takes 1 arguments - var code = - """ + public Task TestInvocation_Cascading_ManyReferencesInManyProjects() + => TestInRegularAndScriptAsync(""" @@ -1952,9 +1758,7 @@ public void Test() { - """; - var fix_All = - """ + """, """ @@ -2006,9 +1810,7 @@ public void Test() { - """; - await TestInRegularAndScriptAsync(code, fix_All, index: 1); - } + """, index: 1); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] public async Task TestInvocation_Cascading_OfferFixCascadingForImplicitInterface() @@ -2029,8 +1831,7 @@ void MTest() } } """; - var fix_DeclarationOnly = - """ + await TestInRegularAndScriptAsync(code, """ interface I1 { void M1(); @@ -2043,9 +1844,8 @@ void MTest() M1(1); } } - """; - var fix_All = - """ + """, index: 0); + await TestInRegularAndScriptAsync(code, """ interface I1 { void M1(int v); @@ -2058,9 +1858,7 @@ void MTest() M1(1); } } - """; - await TestInRegularAndScriptAsync(code, fix_DeclarationOnly, index: 0); - await TestInRegularAndScriptAsync(code, fix_All, index: 1); + """, index: 1); } #if !CODE_STYLE @@ -2068,10 +1866,8 @@ void MTest() // CodeStyle layer does not support cross language application of fixes. [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_Cascading_CrossLanguage() - { - var code = - """ + public Task TestInvocation_Cascading_CrossLanguage() + => TestInRegularAndScriptAsync(""" @@ -2102,9 +1898,7 @@ public void Test() { - """; - var fix = - """ + """, """ @@ -2135,9 +1929,7 @@ public void Test() { - """; - await TestInRegularAndScriptAsync(code, fix, index: 1); - } + """, index: 1); #endif @@ -2155,8 +1947,8 @@ void Test() } } """; - var fix0 = - """ + await TestActionCountAsync(code, 1); + await TestInRegularAndScriptAsync(code, """ class C { void M(int v) { } @@ -2165,17 +1957,12 @@ void Test() M(1, 2, 3, 4); } } - """; - await TestActionCountAsync(code, 1); - await TestInRegularAndScriptAsync(code, fix0, index: 0); + """, index: 0); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_InvocationStyles_Positional_WithOptionalParam() - { - // error CS1501: No overload for method 'M' takes 2 arguments - var code = - """ + public Task TestInvocation_InvocationStyles_Positional_WithOptionalParam() + => TestInRegularAndScriptAsync(""" class C { void M(int i = 1) { } @@ -2184,9 +1971,7 @@ void Test() [|M|](1, 2); } } - """; - var fix0 = - """ + """, """ class C { void M(int i = 1, int v = 0) { } @@ -2195,16 +1980,11 @@ void Test() M(1, 2); } } - """; - await TestInRegularAndScriptAsync(code, fix0, index: 0); - } + """, index: 0); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_InvocationStyles_Named_WithOptionalParam() - { - // error CS1739: The best overload for 'M' does not have a parameter named 'i3' - var code = - """ + public Task TestInvocation_InvocationStyles_Named_WithOptionalParam() + => TestInRegularAndScriptAsync(""" class C { void M(int i1, int i2 = 1) { } @@ -2213,9 +1993,7 @@ void Test() M(1, i2: 2, [|i3|]: 3); } } - """; - var fix0 = - """ + """, """ class C { void M(int i1, int i2 = 1, int i3 = 0) { } @@ -2224,16 +2002,11 @@ void Test() M(1, i2: 2, i3: 3); } } - """; - await TestInRegularAndScriptAsync(code, fix0, index: 0); - } + """, index: 0); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_InvocationStyles_Positional_WithParams() - { - // error CS1503: Argument 1: cannot convert from 'string' to 'int' - var code = - """ + public Task TestInvocation_InvocationStyles_Positional_WithParams() + => TestInRegularAndScriptAsync(""" class C { void M(params int[] ints) { } @@ -2242,9 +2015,7 @@ void Test() M([|"text"|]); } } - """; - var fix0 = - """ + """, """ class C { void M(string v, params int[] ints) { } @@ -2253,16 +2024,11 @@ void Test() M("text"); } } - """; - await TestInRegularAndScriptAsync(code, fix0, index: 0); - } + """, index: 0); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_InvocationStyles_Named_WithTypemissmatch() - { - // error CS1503: Argument 1: cannot convert from 'string' to 'int' - var code = - """ + public Task TestInvocation_InvocationStyles_Named_WithTypemissmatch() + => TestMissingInRegularAndScriptAsync(""" class C { void M(int i) { } @@ -2271,16 +2037,11 @@ void Test() M(i: [|"text"|]); } } - """; - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_InvocationStyles_NamedAndPositional1() - { - // error CS1739: The best overload for 'M' does not have a parameter named 'i2' - var code = - """ + public Task TestInvocation_InvocationStyles_NamedAndPositional1() + => TestInRegularAndScriptAsync(""" class C { void M(int i1, string s) { } @@ -2289,9 +2050,7 @@ void Test() M(1, s: "text", [|i2|]: 0); } } - """; - var fix0 = - """ + """, """ class C { void M(int i1, string s, int i2) { } @@ -2300,17 +2059,11 @@ void Test() M(1, s: "text", i2: 0); } } - """; - await TestInRegularAndScriptAsync(code, fix0, index: 0); - } + """, index: 0); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_InvocationStyles_NamedAndPositional2() - { - // CS1744 is not yet a supported diagnostic (just declaring the diagnostic as supported does not work) - // error CS1744: Named argument 's' specifies a parameter for which a positional argument has already been given - var code = - """ + public Task TestInvocation_InvocationStyles_NamedAndPositional2() + => TestMissingInRegularAndScriptAsync(""" class C { void M(string s) { } @@ -2319,16 +2072,11 @@ void Test() M(1, [|s|]: "text"); } } - """; - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_InvocationStyles_Incomplete_1() - { - // error CS1501: No overload for method 'M' takes 1 arguments - var code = - """ + public Task TestInvocation_InvocationStyles_Incomplete_1() + => TestInRegularAndScriptAsync(""" class C { void M() { } @@ -2337,9 +2085,7 @@ void Test() [|M|](1 } } - """; - var fix0 = - """ + """, """ class C { void M(int v) { } @@ -2348,41 +2094,29 @@ void Test() M(1 } } - """; - await TestInRegularAndScriptAsync(code, fix0, index: 0); - } + """, index: 0); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_InvocationStyles_Incomplete_2() - { - // error CS1503: Argument 1: cannot convert from 'string' to 'int' - var code = - """ + public Task TestInvocation_InvocationStyles_Incomplete_2() + => TestInRegularAndScriptAsync(""" class C { void M(int v) { } void Test() { [|M|]("text", 1 - """; - var fix0 = - """ + """, """ class C { void M(string v1, int v) { } void Test() { M("text", 1 - """; - await TestInRegularAndScriptAsync(code, fix0, index: 0); - } + """, index: 0); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_InvocationStyles_RefParameter() - { - // error CS1501: No overload for method 'M' takes 1 arguments - var code = - """ + public Task TestInvocation_InvocationStyles_RefParameter() + => TestInRegularAndScriptAsync(""" class C { void M() { } @@ -2392,9 +2126,7 @@ void Test() [|M|](ref i); } } - """; - var fix0 = - """ + """, """ class C { void M(ref int i) { } @@ -2404,16 +2136,11 @@ void Test() M(ref i); } } - """; - await TestInRegularAndScriptAsync(code, fix0, index: 0); - } + """, index: 0); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_InvocationStyles_OutParameter_WithTypeDeclarationOutsideArgument() - { - // error CS1501: No overload for method 'M' takes 1 arguments - var code = - """ + public Task TestInvocation_InvocationStyles_OutParameter_WithTypeDeclarationOutsideArgument() + => TestInRegularAndScriptAsync(""" class C { void M() { } @@ -2423,9 +2150,7 @@ void Test() [|M|](out i); } } - """; - var fix0 = - """ + """, """ class C { void M(out int i) { } @@ -2435,16 +2160,11 @@ void Test() M(out i); } } - """; - await TestInRegularAndScriptAsync(code, fix0, index: 0); - } + """, index: 0); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_InvocationStyles_OutParameter_WithTypeDeclarationInArgument() - { - // error CS1501: No overload for method 'M' takes 1 arguments - var code = - """ + public Task TestInvocation_InvocationStyles_OutParameter_WithTypeDeclarationInArgument() + => TestInRegularAndScriptAsync(""" class C { void M() { } @@ -2453,9 +2173,7 @@ void Test() [|M|](out int i); } } - """; - var fix0 = - """ + """, """ class C { void M(out int i) { } @@ -2464,16 +2182,11 @@ void Test() M(out int i); } } - """; - await TestInRegularAndScriptAsync(code, fix0, index: 0); - } + """, index: 0); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_InvocationStyles_OutParameter_WithVarTypeDeclarationInArgument() - { - // error CS1501: No overload for method 'M' takes 1 arguments - var code = - """ + public Task TestInvocation_InvocationStyles_OutParameter_WithVarTypeDeclarationInArgument() + => TestInRegularAndScriptAsync(""" class C { void M() { } @@ -2482,9 +2195,7 @@ void Test() [|M|](out var i); } } - """; - var fix0 = - """ + """, """ class C { void M(out object i) { } @@ -2493,18 +2204,11 @@ void Test() M(out var i); } } - """; - await TestInRegularAndScriptAsync(code, fix0, index: 0); - } + """, index: 0); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21446")] - public async Task TestInvocation_Indexer_NotSupported() - { - // Could be fixed by allowing ElementAccessExpression next to InvocationExpression - // in AbstractAddParameterCodeFixProvider.RegisterCodeFixesAsync. - // error CS1501: No overload for method 'this' takes 2 arguments - var code = - """ + public Task TestInvocation_Indexer_NotSupported() + => TestMissingAsync(""" public class C { public int this[int i] { @@ -2516,24 +2220,17 @@ public void Test() { var i = [|this[0,0]|]; } } - """; - await TestMissingAsync(code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29061")] - public async Task TestThis_DoNotOfferToFixTheConstructorWithTheDiagnosticOnIt() - { - // error CS1729: 'C' does not contain a constructor that takes 1 arguments - var code = - """ + public Task TestThis_DoNotOfferToFixTheConstructorWithTheDiagnosticOnIt() + => TestMissingAsync(""" public class C { public C(): [|this|](1) { } } - """; - await TestMissingAsync(code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29061")] public async Task TestThis_Fix_IfACandidateIsAvailable() @@ -2549,8 +2246,7 @@ public C(): [|this|](1, 1) { } } """; - var fix0 = - """ + await TestInRegularAndScriptAsync(code, """ class C { public C(int i, int v) { } @@ -2558,8 +2254,7 @@ public C(int i, int v) { } public C(): this(1, 1) { } } - """; - await TestInRegularAndScriptAsync(code, fix0, index: 0); + """, index: 0); await TestActionCountAsync(code, 1); } @@ -2578,8 +2273,7 @@ public class C : B public C(int i) : [|base|](i) { } } """; - var fix0 = - """ + await TestInRegularAndScriptAsync(code, """ public class B { B(int i) { } @@ -2588,17 +2282,13 @@ public class C : B { public C(int i) : base(i) { } } - """; - await TestInRegularAndScriptAsync(code, fix0, index: 0); + """, index: 0); await TestActionCountAsync(code, 1); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29753")] - public async Task LocalFunction_AddParameterToLocalFunctionWithOneParameter() - { - // CS1501 No overload for method takes 2 arguments - var code = - """ + public Task LocalFunction_AddParameterToLocalFunctionWithOneParameter() + => TestInRegularAndScriptAsync(""" class Rsrp { public void M() @@ -2610,9 +2300,7 @@ void Local(string whatever) } } } - """; - var fix0 = - """ + """, """ class Rsrp { public void M() @@ -2624,16 +2312,11 @@ void Local(string whatever, bool v) } } } - """; - await TestInRegularAndScriptAsync(code, fix0, index: 0); - } + """, index: 0); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29752")] - public async Task LocalFunction_AddNamedParameterToLocalFunctionWithOneParameter() - { - // CS1739: The best overload for 'Local' does not have a parameter named 'mynewparameter' - var code = - """ + public Task LocalFunction_AddNamedParameterToLocalFunctionWithOneParameter() + => TestInRegularAndScriptAsync(""" class Rsrp { public void M() @@ -2645,9 +2328,7 @@ void Local(string whatever) } } } - """; - var fix0 = - """ + """, """ class Rsrp { public void M() @@ -2659,14 +2340,11 @@ void Local(string whatever, bool mynewparameter) } } } - """; - await TestInRegularAndScriptAsync(code, fix0, index: 0); - } + """, index: 0); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39270")] - public async Task TestWithArgThatHasImplicitConversionToParamType1() - { - await TestInRegularAndScriptAsync( + public Task TestWithArgThatHasImplicitConversionToParamType1() + => TestInRegularAndScriptAsync( """ class BaseClass { } @@ -2699,13 +2377,10 @@ void TestFunc() void MyFunc(BaseClass param1, int newparam) { } } """); - } [Fact] - public async Task TestOnExtensionGetEnumerator() - { - var code = - """ + public Task TestOnExtensionGetEnumerator() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; namespace N { static class Extensions @@ -2722,9 +2397,7 @@ void M1() foreach (var a in new object()); } }} - """; - var fix = - """ + """, """ using System.Collections.Generic; namespace N { static class Extensions @@ -2741,9 +2414,7 @@ void M1() foreach (var a in new object()); } }} - """; - await TestInRegularAndScriptAsync(code, fix); - } + """); [Fact] public async Task TestOnExtensionGetAsyncEnumerator() @@ -2792,9 +2463,8 @@ async Task M1() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44271")] - public async Task TopLevelStatement() - { - await TestInRegularAndScriptAsync(""" + public Task TopLevelStatement() + => TestInRegularAndScriptAsync(""" [|local|](1, 2, 3); void local(int x, int y) @@ -2808,12 +2478,10 @@ void local(int x, int y, int v) { } """, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44271")] - public async Task TopLevelStatement_Nested() - { - await TestInRegularAndScriptAsync(""" + public Task TopLevelStatement_Nested() + => TestInRegularAndScriptAsync(""" void outer() { [|local|](1, 2, 3); @@ -2833,12 +2501,10 @@ void local(int x, int y, int v) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42559")] - public async Task TestAddParameter_ImplicitObjectCreation() - { - await TestInRegularAndScriptAsync(""" + public Task TestAddParameter_ImplicitObjectCreation() + => TestInRegularAndScriptAsync(""" class C { C(int i) { } @@ -2860,12 +2526,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48042")] - public async Task TestNamedArgOnExtensionMethod() - { - await TestInRegularAndScriptAsync( + public Task TestNamedArgOnExtensionMethod() + => TestInRegularAndScriptAsync( """ namespace r { @@ -2892,12 +2556,10 @@ void Test() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/54408")] - public async Task TestPositionalRecord() - { - await TestInRegularAndScriptAsync(""" + public Task TestPositionalRecord() + => TestInRegularAndScriptAsync(""" var b = "B"; var r = [|new R(1, b)|]; @@ -2918,12 +2580,10 @@ namespace System.Runtime.CompilerServices public static class IsExternalInit { } } """, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9)); - } [Fact] - public async Task Test_PrimaryConstructor_Class() - { - await TestInRegularAndScriptAsync(""" + public Task Test_PrimaryConstructor_Class() + => TestInRegularAndScriptAsync(""" var b = "B"; var r = [|new R(1, b)|]; @@ -2934,12 +2594,10 @@ class R(int A); class R(int A, string b); """, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp12)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/54408")] - public async Task TestPositionalRecordStruct() - { - await TestInRegularAndScriptAsync(""" + public Task TestPositionalRecordStruct() + => TestInRegularAndScriptAsync(""" var b = "B"; var r = [|new R(1, b)|]; @@ -2960,12 +2618,10 @@ namespace System.Runtime.CompilerServices public static class IsExternalInit { } } """, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9)); - } [Fact] - public async Task Test_PrimaryConstructor_Struct() - { - await TestInRegularAndScriptAsync(""" + public Task Test_PrimaryConstructor_Struct() + => TestInRegularAndScriptAsync(""" var b = "B"; var r = [|new R(1, b)|]; @@ -2976,12 +2632,10 @@ struct R(int A); struct R(int A, string b); """, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp12)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56952")] - public async Task TestRecordsNamingConventions() - { - await TestInRegularAndScript1Async(""" + public Task TestRecordsNamingConventions() + => TestInRegularAndScript1Async(""" [|new Test("repro")|]; record Test(); @@ -2992,12 +2646,10 @@ record Test(); record Test(string V); """); - } [Fact] - public async Task TestNamingConventions_PrimaryConstructor_Class() - { - await TestInRegularAndScript1Async(""" + public Task TestNamingConventions_PrimaryConstructor_Class() + => TestInRegularAndScript1Async(""" [|new Test("repro")|]; class Test(); @@ -3006,12 +2658,10 @@ class Test(); class Test(string v); """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56952")] - public async Task TestRecordsNamingConventions_RecordStruct() - { - await TestInRegularAndScript1Async(""" + public Task TestRecordsNamingConventions_RecordStruct() + => TestInRegularAndScript1Async(""" [|new Test("repro")|]; record struct Test(); @@ -3022,12 +2672,10 @@ record struct Test(); record struct Test(string V); """); - } [Fact] - public async Task TestNamingConventions_PrimaryConstructor_Struct() - { - await TestInRegularAndScript1Async(""" + public Task TestNamingConventions_PrimaryConstructor_Struct() + => TestInRegularAndScript1Async(""" [|new Test("repro")|]; struct Test(); @@ -3036,12 +2684,10 @@ struct Test(); struct Test(string v); """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61715")] - public async Task TestMethodGroup1() - { - await TestInRegularAndScript1Async(""" + public Task TestMethodGroup1() + => TestInRegularAndScript1Async(""" public class Example { public void Add(int x) @@ -3074,12 +2720,10 @@ public void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61715")] - public async Task TestMethodGroup2() - { - await TestInRegularAndScript1Async(""" + public Task TestMethodGroup2() + => TestInRegularAndScript1Async(""" public class Example { public void Add(int x, string y) @@ -3112,12 +2756,10 @@ public void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61715")] - public async Task TestMethodGroup3() - { - await TestInRegularAndScript1Async(""" + public Task TestMethodGroup3() + => TestInRegularAndScript1Async(""" public class Example { public int Add(int x, string y) @@ -3152,12 +2794,10 @@ public void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71428")] - public async Task TestAddConstructorParameterWithExistingField_BlockInitialize() - { - await TestInRegularAndScript1Async( + public Task TestAddConstructorParameterWithExistingField_BlockInitialize() + => TestInRegularAndScript1Async( """ class C { @@ -3203,12 +2843,10 @@ void M(string t) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71428")] - public async Task TestAddConstructorParameterWithExistingField_ExpressionBodyInitialize() - { - await TestInRegularAndScript1Async( + public Task TestAddConstructorParameterWithExistingField_ExpressionBodyInitialize() + => TestInRegularAndScript1Async( """ class C { @@ -3248,12 +2886,10 @@ void M(string t) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71428")] - public async Task TestAddConstructorParameterWithExistingField_TupleInitialize() - { - await TestInRegularAndScript1Async( + public Task TestAddConstructorParameterWithExistingField_TupleInitialize() + => TestInRegularAndScript1Async( """ class C { @@ -3296,12 +2932,10 @@ void M(string i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71428")] - public async Task TestAddConstructorParameterWithExistingField_UnderscoreName() - { - await TestInRegularAndScript1Async( + public Task TestAddConstructorParameterWithExistingField_UnderscoreName() + => TestInRegularAndScript1Async( """ class C { @@ -3339,12 +2973,10 @@ void M(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71428")] - public async Task TestAddConstructorParameterWithExistingField_PrimaryConstructor() - { - await TestInRegularAndScript1Async( + public Task TestAddConstructorParameterWithExistingField_PrimaryConstructor() + => TestInRegularAndScript1Async( """ class C() { @@ -3373,12 +3005,10 @@ void M(string name) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71428")] - public async Task TestAddConstructorParameterWithExistingProperty_PrimaryConstructor() - { - await TestInRegularAndScript1Async( + public Task TestAddConstructorParameterWithExistingProperty_PrimaryConstructor() + => TestInRegularAndScript1Async( """ class C() { @@ -3407,12 +3037,10 @@ void M(string name) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71428")] - public async Task TestAddConstructorParameterWithExistingThrowingProperty_PrimaryConstructor() - { - await TestInRegularAndScript1Async( + public Task TestAddConstructorParameterWithExistingThrowingProperty_PrimaryConstructor() + => TestInRegularAndScript1Async( """ using System; @@ -3445,5 +3073,4 @@ void M(string name) } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/AddRequiredParentheses/AddRequiredExpressionParenthesesTests.cs b/src/Analyzers/CSharp/Tests/AddRequiredParentheses/AddRequiredExpressionParenthesesTests.cs index f2bf61baf6005..4ef7a537ce6e9 100644 --- a/src/Analyzers/CSharp/Tests/AddRequiredParentheses/AddRequiredExpressionParenthesesTests.cs +++ b/src/Analyzers/CSharp/Tests/AddRequiredParentheses/AddRequiredExpressionParenthesesTests.cs @@ -10,6 +10,7 @@ using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; +using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; @@ -29,9 +30,8 @@ private Task TestAsync(string initialMarkup, string expected, OptionsCollection => TestInRegularAndScript1Async(initialMarkup, expected, parameters: new TestParameters(options: options)); [Fact] - public async Task TestArithmeticPrecedence() - { - await TestAsync( + public Task TestArithmeticPrecedence() + => TestAsync( """ class C { @@ -50,12 +50,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestNoArithmeticOnLowerPrecedence() - { - await TestMissingAsync( + public Task TestNoArithmeticOnLowerPrecedence() + => TestMissingAsync( """ class C { @@ -65,12 +63,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestNotIfArithmeticPrecedenceStaysTheSame() - { - await TestMissingAsync( + public Task TestNotIfArithmeticPrecedenceStaysTheSame() + => TestMissingAsync( """ class C { @@ -80,12 +76,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestNotIfArithmeticPrecedenceIsNotEnforced1() - { - await TestMissingAsync( + public Task TestNotIfArithmeticPrecedenceIsNotEnforced1() + => TestMissingAsync( """ class C { @@ -95,12 +89,10 @@ void M() } } """, RequireOtherBinaryParenthesesForClarity); - } [Fact] - public async Task TestNotIfArithmeticPrecedenceIsNotEnforced2() - { - await TestMissingAsync( + public Task TestNotIfArithmeticPrecedenceIsNotEnforced2() + => TestMissingAsync( """ class C { @@ -110,12 +102,10 @@ void M() } } """, RequireOtherBinaryParenthesesForClarity); - } [Fact] - public async Task TestRelationalPrecedence() - { - await TestAsync( + public Task TestRelationalPrecedence() + => TestAsync( """ class C { @@ -134,12 +124,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestLogicalPrecedence() - { - await TestAsync( + public Task TestLogicalPrecedence() + => TestAsync( """ class C { @@ -158,12 +146,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestNoLogicalOnLowerPrecedence() - { - await TestMissingAsync( + public Task TestNoLogicalOnLowerPrecedence() + => TestMissingAsync( """ class C { @@ -173,12 +159,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestNotIfLogicalPrecedenceStaysTheSame() - { - await TestMissingAsync( + public Task TestNotIfLogicalPrecedenceStaysTheSame() + => TestMissingAsync( """ class C { @@ -188,12 +172,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestNotIfLogicalPrecedenceIsNotEnforced() - { - await TestMissingAsync( + public Task TestNotIfLogicalPrecedenceIsNotEnforced() + => TestMissingAsync( """ class C { @@ -203,12 +185,10 @@ void M() } } """, RequireArithmeticBinaryParenthesesForClarity); - } [Fact] - public async Task TestMixedArithmeticAndLogical() - { - await TestMissingAsync( + public Task TestMixedArithmeticAndLogical() + => TestMissingAsync( """ class C { @@ -218,12 +198,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestLogicalPrecedenceMultipleEqualPrecedenceParts1() - { - await TestAsync( + public Task TestLogicalPrecedenceMultipleEqualPrecedenceParts1() + => TestAsync( """ class C { @@ -242,12 +220,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestLogicalPrecedenceMultipleEqualPrecedenceParts2() - { - await TestAsync( + public Task TestLogicalPrecedenceMultipleEqualPrecedenceParts2() + => TestAsync( """ class C { @@ -266,12 +242,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestShiftPrecedence1() - { - await TestAsync( + public Task TestShiftPrecedence1() + => TestAsync( """ class C { @@ -290,12 +264,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestShiftPrecedence2() - { - await TestAsync( + public Task TestShiftPrecedence2() + => TestAsync( """ class C { @@ -314,12 +286,10 @@ void M() } } """, RequireArithmeticBinaryParenthesesForClarity); - } [Fact] - public async Task TestShiftPrecedence3() - { - await TestMissingAsync( + public Task TestShiftPrecedence3() + => TestMissingAsync( """ class C { @@ -329,12 +299,10 @@ void M() } } """, RequireOtherBinaryParenthesesForClarity); - } [Fact] - public async Task TestNotIfShiftPrecedenceStaysTheSame1() - { - await TestMissingAsync( + public Task TestNotIfShiftPrecedenceStaysTheSame1() + => TestMissingAsync( """ class C { @@ -344,12 +312,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestNotIfShiftPrecedenceStaysTheSame2() - { - await TestMissingAsync( + public Task TestNotIfShiftPrecedenceStaysTheSame2() + => TestMissingAsync( """ class C { @@ -359,12 +325,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestEqualityPrecedence1() - { - await TestMissingAsync( + public Task TestEqualityPrecedence1() + => TestMissingAsync( """ class C { @@ -374,12 +338,10 @@ void M() } } """, RequireOtherBinaryParenthesesForClarity); - } [Fact] - public async Task TestEqualityPrecedence2() - { - await TestMissingAsync( + public Task TestEqualityPrecedence2() + => TestMissingAsync( """ class C { @@ -389,12 +351,10 @@ void M() } } """, RequireOtherBinaryParenthesesForClarity); - } [Fact] - public async Task TestEqualityPrecedence3() - { - await TestMissingAsync( + public Task TestEqualityPrecedence3() + => TestMissingAsync( """ class C { @@ -404,12 +364,10 @@ void M() } } """, RequireRelationalBinaryParenthesesForClarity); - } [Fact] - public async Task TestEqualityPrecedence4() - { - await TestMissingAsync( + public Task TestEqualityPrecedence4() + => TestMissingAsync( """ class C { @@ -419,12 +377,10 @@ void M() } } """, RequireRelationalBinaryParenthesesForClarity); - } - [Fact] - public async Task TestCoalescePrecedence1() - { - await TestMissingAsync( + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78841")] + public Task TestCoalescePrecedence1() + => TestAsync( """ class C { @@ -433,13 +389,20 @@ void M() int x = a $$+ b ?? c; } } + """, + """ + class C + { + void M() + { + int x = (a + b) ?? c; + } + } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestCoalescePrecedence2() - { - await TestMissingAsync( + public Task TestCoalescePrecedence2() + => TestMissingAsync( """ class C { @@ -449,10 +412,22 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestCoalescePrecedence3() + public Task TestCoalescePrecedence3() + => TestMissingAsync( + """ + class C + { + void M() + { + int x = a ?? b $$?? c; + } + } + """, RequireAllParenthesesForClarity); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/79286")] + public async Task TestCoalescePrecedence4() { await TestMissingAsync( """ @@ -460,16 +435,15 @@ class C { void M() { - int x = a ?? b $$?? c; + int x = a $$as b ?? c; } } """, RequireAllParenthesesForClarity); } [Fact] - public async Task TestBitwisePrecedence1() - { - await TestAsync( + public Task TestBitwisePrecedence1() + => TestAsync( """ class C { @@ -488,12 +462,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestBitwisePrecedence2() - { - await TestMissingAsync( + public Task TestBitwisePrecedence2() + => TestMissingAsync( """ class C { @@ -503,12 +475,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestBitwisePrecedence3() - { - await TestAsync( + public Task TestBitwisePrecedence3() + => TestAsync( """ class C { @@ -527,12 +497,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestBitwisePrecedence4() - { - await TestMissingAsync( + public Task TestBitwisePrecedence4() + => TestMissingAsync( """ class C { @@ -542,12 +510,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestNotForEqualityAfterEquals() - { - await TestMissingAsync( + public Task TestNotForEqualityAfterEquals() + => TestMissingAsync( """ class C { @@ -557,12 +523,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestNotForAssignmentEqualsAfterLocal() - { - await TestMissingAsync( + public Task TestNotForAssignmentEqualsAfterLocal() + => TestMissingAsync( """ class C { @@ -572,12 +536,10 @@ void M(int a) } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestForAssignmentAndEquality1() - { - await TestMissingAsync( + public Task TestForAssignmentAndEquality1() + => TestMissingAsync( """ class C { @@ -587,12 +549,10 @@ void M(bool x, bool y, bool z) } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestMissingForAssignmentAndEquality2() - { - await TestMissingAsync( + public Task TestMissingForAssignmentAndEquality2() + => TestMissingAsync( """ class C { @@ -602,12 +562,10 @@ void M(bool x, bool y, bool z) } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestUnclearCast1() - { - await TestMissingAsync( + public Task TestUnclearCast1() + => TestMissingAsync( """ class C { @@ -617,12 +575,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestUnclearCast_NotOfferedWithIgnore() - { - await TestMissingAsync( + public Task TestUnclearCast_NotOfferedWithIgnore() + => TestMissingAsync( """ class C { @@ -632,12 +588,10 @@ void M() } } """, IgnoreAllParentheses); - } [Fact] - public async Task TestUnclearCast_NotOfferedWithRemoveForClarity() - { - await TestMissingAsync( + public Task TestUnclearCast_NotOfferedWithRemoveForClarity() + => TestMissingAsync( """ class C { @@ -647,12 +601,10 @@ void M() } } """, RemoveAllUnnecessaryParentheses); - } [Fact] - public async Task TestUnclearCast2() - { - await TestMissingAsync( + public Task TestUnclearCast2() + => TestMissingAsync( """ class C { @@ -662,12 +614,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestUnclearCast3() - { - await TestMissingAsync( + public Task TestUnclearCast3() + => TestMissingAsync( """ class C { @@ -677,12 +627,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestUnclearCast4() - { - await TestMissingAsync( + public Task TestUnclearCast4() + => TestMissingAsync( """ class C { @@ -692,12 +640,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestNotForPrimary() - { - await TestMissingAsync( + public Task TestNotForPrimary() + => TestMissingAsync( """ class C { @@ -707,12 +653,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestNotForMemberAccess() - { - await TestMissingAsync( + public Task TestNotForMemberAccess() + => TestMissingAsync( """ class C { @@ -722,12 +666,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestNotForCastOfCast() - { - await TestMissingAsync( + public Task TestNotForCastOfCast() + => TestMissingAsync( """ class C { @@ -737,12 +679,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestNotForNonAmbiguousUnary() - { - await TestMissingAsync( + public Task TestNotForNonAmbiguousUnary() + => TestMissingAsync( """ class C { @@ -752,12 +692,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestFixAll1() - { - await TestMissingAsync( + public Task TestFixAll1() + => TestMissingAsync( """ class C { @@ -769,12 +707,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestFixAll2() - { - await TestInRegularAndScriptAsync( + public Task TestFixAll2() + => TestInRegularAndScriptAsync( """ class C { @@ -797,12 +733,10 @@ void M() } } """, options: RequireAllParenthesesForClarity); - } [Fact] - public async Task TestFixAll3() - { - await TestMissingAsync( + public Task TestFixAll3() + => TestMissingAsync( """ class C { @@ -814,12 +748,10 @@ void M() } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestSeams1() - { - await TestInRegularAndScriptAsync( + public Task TestSeams1() + => TestInRegularAndScriptAsync( """ class C { @@ -838,5 +770,4 @@ void M() } } """, options: RequireAllParenthesesForClarity); - } } diff --git a/src/Analyzers/CSharp/Tests/AddRequiredParentheses/AddRequiredPatternParenthesesTests.cs b/src/Analyzers/CSharp/Tests/AddRequiredParentheses/AddRequiredPatternParenthesesTests.cs index ab61e7e1401c3..7085621118ab6 100644 --- a/src/Analyzers/CSharp/Tests/AddRequiredParentheses/AddRequiredPatternParenthesesTests.cs +++ b/src/Analyzers/CSharp/Tests/AddRequiredParentheses/AddRequiredPatternParenthesesTests.cs @@ -29,9 +29,8 @@ private Task TestAsync(string initialMarkup, string expected, OptionsCollection => TestInRegularAndScript1Async(initialMarkup, expected, parameters: new TestParameters(options: options)); [Fact] - public async Task TestLogicalPrecedence() - { - await TestAsync( + public Task TestLogicalPrecedence() + => TestAsync( """ class C { @@ -50,12 +49,10 @@ void M(object o) } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestNoLogicalOnLowerPrecedence() - { - await TestMissingAsync( + public Task TestNoLogicalOnLowerPrecedence() + => TestMissingAsync( """ class C { @@ -65,12 +62,10 @@ void M(object o) } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestNotIfLogicalPrecedenceStaysTheSame() - { - await TestMissingAsync( + public Task TestNotIfLogicalPrecedenceStaysTheSame() + => TestMissingAsync( """ class C { @@ -80,12 +75,10 @@ void M(object o) } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestNotIfLogicalPrecedenceIsNotEnforced() - { - await TestMissingAsync( + public Task TestNotIfLogicalPrecedenceIsNotEnforced() + => TestMissingAsync( """ class C { @@ -95,12 +88,10 @@ void M(object o) } } """, RequireArithmeticBinaryParenthesesForClarity); - } [Fact] - public async Task TestLogicalPrecedenceMultipleEqualPrecedenceParts1() - { - await TestAsync( + public Task TestLogicalPrecedenceMultipleEqualPrecedenceParts1() + => TestAsync( """ class C { @@ -119,12 +110,10 @@ void M(object o) } } """, RequireAllParenthesesForClarity); - } [Fact] - public async Task TestLogicalPrecedenceMultipleEqualPrecedenceParts2() - { - await TestAsync( + public Task TestLogicalPrecedenceMultipleEqualPrecedenceParts2() + => TestAsync( """ class C { @@ -143,5 +132,4 @@ void M(object o) } } """, RequireAllParenthesesForClarity); - } } diff --git a/src/Analyzers/CSharp/Tests/AliasAmbiguousType/AliasAmbiguousTypeTests.cs b/src/Analyzers/CSharp/Tests/AliasAmbiguousType/AliasAmbiguousTypeTests.cs index 61a67630c278b..643d25633472c 100644 --- a/src/Analyzers/CSharp/Tests/AliasAmbiguousType/AliasAmbiguousTypeTests.cs +++ b/src/Analyzers/CSharp/Tests/AliasAmbiguousType/AliasAmbiguousTypeTests.cs @@ -19,77 +19,78 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AliasAmbiguousType; [Trait(Traits.Feature, Traits.Features.CodeActionsAliasAmbiguousType)] -public sealed class AliasAmbiguousTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest_NoEditor +public sealed class AliasAmbiguousTypeTests(ITestOutputHelper logger) : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest_NoEditor(logger) { - public AliasAmbiguousTypeTests(ITestOutputHelper logger) - : base(logger) - { - } - internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpAliasAmbiguousTypeCodeFixProvider()); protected override ImmutableArray MassageActions(ImmutableArray actions) => FlattenActions(actions); - private static string GetAmbiguousDefinition(string typeDefinion, string ns1Name = "N1", string ns2Name = "N2") - => $@" -namespace {ns1Name} -{{ - {typeDefinion} -}} -namespace {ns2Name} -{{ - {typeDefinion} -}}"; + private static string GetAmbiguousDefinition(string typeDefinition, string ns1Name = "N1", string ns2Name = "N2") + => $$""" - [Fact] - public async Task TestAmbiguousClassObjectCreationUsingsInNamespace() - { - var classDef = GetAmbiguousDefinition("public class Ambiguous { }"); - var initialMarkup = classDef + @" -namespace Test -{ - using N1; - using N2; - class C - { - void M() + namespace {{ns1Name}} { - var a = new [|Ambiguous|](); + {{typeDefinition}} } - } -}"; - var expectedMarkup0 = classDef + @" -namespace Test -{ - using N1; - using N2; - using Ambiguous = N1.Ambiguous; - - class C - { - void M() + namespace {{ns2Name}} { - var a = new Ambiguous(); + {{typeDefinition}} } - } -}"; - var expectedMarkup1 = classDef + @" -namespace Test -{ - using N1; - using N2; - using Ambiguous = N2.Ambiguous; - class C + """; + + [Fact] + public async Task TestAmbiguousClassObjectCreationUsingsInNamespace() { - void M() - { - var a = new Ambiguous(); - } - } -}"; + var classDef = GetAmbiguousDefinition("public class Ambiguous { }"); + var initialMarkup = classDef + """ + namespace Test + { + using N1; + using N2; + class C + { + void M() + { + var a = new [|Ambiguous|](); + } + } + } + """; + var expectedMarkup0 = classDef + """ + namespace Test + { + using N1; + using N2; + using Ambiguous = N1.Ambiguous; + + class C + { + void M() + { + var a = new Ambiguous(); + } + } + } + """; + var expectedMarkup1 = classDef + """ + namespace Test + { + using N1; + using N2; + using Ambiguous = N2.Ambiguous; + + class C + { + void M() + { + var a = new Ambiguous(); + } + } + } + """; await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup0, index: 0); await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup1, index: 1); await TestSmartTagTextAsync(initialMarkup, "using Ambiguous = N1.Ambiguous;"); @@ -99,211 +100,210 @@ void M() public async Task TestAmbiguousClassObjectCreationUsingsInCompilationUnit() { var classDef = GetAmbiguousDefinition("public class Ambiguous { }"); - await TestInRegularAndScriptAsync(@" -using N1; -using N2; -" + classDef + @" -namespace Test -{ - class C - { - void M() - { - var a = new [|Ambiguous|](); - } - } -}", @" -using N1; -using N2; -using Ambiguous = N1.Ambiguous; -" + classDef + @" -namespace Test -{ - class C - { - void M() - { - var a = new Ambiguous(); - } - } -}"); + await TestInRegularAndScriptAsync(""" + using N1; + using N2; + """ + classDef + """ + namespace Test + { + class C + { + void M() + { + var a = new [|Ambiguous|](); + } + } + } + """, """ + using N1; + using N2; + using Ambiguous = N1.Ambiguous; + """ + classDef + """ + namespace Test + { + class C + { + void M() + { + var a = new Ambiguous(); + } + } + } + """); } [Fact] public async Task TestAmbiguousClassObjectCreationGenericsDoNotOfferDiagnostic() { var genericAmbiguousClassDefinition = GetAmbiguousDefinition("public class Ambiguous { }"); - await TestMissingAsync(@" -using N1; -using N2; -" + genericAmbiguousClassDefinition + @" -namespace Test -{ - class C - { - void M() - { - var a = new [|Ambiguous|](); - } - } -}"); + await TestMissingAsync(""" + using N1; + using N2; + """ + genericAmbiguousClassDefinition + """ + namespace Test + { + class C + { + void M() + { + var a = new [|Ambiguous|](); + } + } + } + """); } [Fact] public async Task TestAmbiguousAttribute() { var classDef = GetAmbiguousDefinition("public class AmbiguousAttribute: System.Attribute { }"); - await TestInRegularAndScriptAsync(@" -using N1; -using N2; -" + classDef + @" -namespace Test -{ - [[|Ambiguous|]] - class C - { - } -}", @" -using N1; -using N2; -using AmbiguousAttribute = N1.AmbiguousAttribute; -" + classDef + @" -namespace Test -{ - [Ambiguous] - class C - { - } -}"); + await TestInRegularAndScriptAsync(""" + using N1; + using N2; + """ + classDef + """ + namespace Test + { + [[|Ambiguous|]] + class C + { + } + } + """, """ + using N1; + using N2; + using AmbiguousAttribute = N1.AmbiguousAttribute; + """ + classDef + """ + namespace Test + { + [Ambiguous] + class C + { + } + } + """); } [Fact] - public async Task TestNamespaceAndTypenameIdenticalOffersNoDiagnostics() - { - // This gives CS0433: The type 'Ambiguous' exists in both 'Assembly1' and 'Assembly2' - // Couldn't get a CS0104 in this situation. Keep the test anyway if someone finds a way to force CS0104 here - // or CS0433 is added as a supported diagnostic for this fix. - await TestMissingAsync(@" - - - -namespace N -{ - public class Ambiguous { } -} - - - - -namespace N -{ - public class Ambiguous { } -} - - - - Assembly1 - Assembly2 - -extern alias A1; -extern alias A2; -using A1::N; -using A2::N; -namespace N1 -{ - public class C - { - void M() - { - var a = new [|Ambiguous|](); - } - } -} - - - -"); - } + public Task TestNamespaceAndTypenameIdenticalOffersNoDiagnostics() + => TestMissingAsync(""" + + + + namespace N + { + public class Ambiguous { } + } + + + + + namespace N + { + public class Ambiguous { } + } + + + + Assembly1 + Assembly2 + + extern alias A1; + extern alias A2; + using A1::N; + using A2::N; + namespace N1 + { + public class C + { + void M() + { + var a = new [|Ambiguous|](); + } + } + } + + + + """); [Fact] - public async Task TestAmbiguousAliasNoDiagnostics() - { - await TestMissingAsync(@" -extern alias alias; -using alias=alias; -class myClass : [|alias|]::Uri - { - } -"); - } + public Task TestAmbiguousAliasNoDiagnostics() + => TestMissingAsync(""" + extern alias alias; + using alias=alias; + class myClass : [|alias|]::Uri + { + } + """); [Fact] public async Task TestAmbiguousNestedClass() { - var initialMarkup = @" -using static Static; -using static Static; - -public static class Static -{ - public class Nested - { - public void M() { } - } -} - -class D -{ - static void Main(string[] args) - { - var c = new [|Nested|](); - c.M(); - } -}"; - var expectedMarkup0 = @" -using static Static; -using static Static; -using Nested = Static.Nested; + var initialMarkup = """ + using static Static; + using static Static; -public static class Static -{ - public class Nested - { - public void M() { } - } -} - -class D -{ - static void Main(string[] args) - { - var c = new Nested(); - c.M(); - } -}"; - var expectedMarkup1 = @" -using static Static; -using static Static; -using Nested = Static.Nested; + public static class Static + { + public class Nested + { + public void M() { } + } + } -public static class Static -{ - public class Nested - { - public void M() { } - } -} - -class D -{ - static void Main(string[] args) - { - var c = new Nested(); - c.M(); - } -}"; - await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup0, index: 0); - await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup1, index: 1); + class D + { + static void Main(string[] args) + { + var c = new [|Nested|](); + c.M(); + } + } + """; + await TestInRegularAndScriptAsync(initialMarkup, """ + using static Static; + using static Static; + using Nested = Static.Nested; + + public static class Static + { + public class Nested + { + public void M() { } + } + } + + class D + { + static void Main(string[] args) + { + var c = new Nested(); + c.M(); + } + } + """, index: 0); + await TestInRegularAndScriptAsync(initialMarkup, """ + using static Static; + using static Static; + using Nested = Static.Nested; + + public static class Static + { + public class Nested + { + public void M() { } + } + } + + class D + { + static void Main(string[] args) + { + var c = new Nested(); + c.M(); + } + } + """, index: 1); await TestSmartTagTextAsync(initialMarkup, "using Nested = Static.Nested;"); } @@ -311,25 +311,25 @@ static void Main(string[] args) public async Task TestAmbiguousClassDiagnosedAtBaseList() { var classDef = GetAmbiguousDefinition(@"public class AmbiguousClass { }"); - var initialMarkup = @" -using N1; -using N2; -" + classDef + @" -namespace NTest -{ - public class Test : [|AmbiguousClass|] { } -} -"; - var expectedMarkup = @" -using N1; -using N2; -using AmbiguousClass = N1.AmbiguousClass; -" + classDef + @" -namespace NTest -{ - public class Test : AmbiguousClass { } -} -"; + var initialMarkup = """ + using N1; + using N2; + """ + classDef + """ + namespace NTest + { + public class Test : [|AmbiguousClass|] { } + } + """; + var expectedMarkup = """ + using N1; + using N2; + using AmbiguousClass = N1.AmbiguousClass; + """ + classDef + """ + namespace NTest + { + public class Test : AmbiguousClass { } + } + """; await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup); } @@ -337,25 +337,25 @@ public class Test : AmbiguousClass { } public async Task TestAmbiguousClassDiagnosedAtTypeConstraint() { var classDef = GetAmbiguousDefinition(@"public class AmbiguousClass { }"); - var initialMarkup = @" -using N1; -using N2; -" + classDef + @" -namespace NTest -{ - public class Test where T : [|AmbiguousClass|] { } -} -"; - var expectedMarkup = @" -using N1; -using N2; -using AmbiguousClass = N1.AmbiguousClass; -" + classDef + @" -namespace NTest -{ - public class Test where T : AmbiguousClass { } -} -"; + var initialMarkup = """ + using N1; + using N2; + """ + classDef + """ + namespace NTest + { + public class Test where T : [|AmbiguousClass|] { } + } + """; + var expectedMarkup = """ + using N1; + using N2; + using AmbiguousClass = N1.AmbiguousClass; + """ + classDef + """ + namespace NTest + { + public class Test where T : AmbiguousClass { } + } + """; await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup); } @@ -363,31 +363,31 @@ public class Test where T : AmbiguousClass { } public async Task TestAmbiguousEnumDiagnosedAtFieldDeclaration() { var enumDef = GetAmbiguousDefinition(@"public enum AmbiguousEnum { }"); - var initialMarkup = @" -using N1; -using N2; -" + enumDef + @" -namespace NTest -{ - public class Test - { - private [|AmbiguousEnum|] _AmbiguousEnum; - } -} -"; - var expectedMarkup = @" -using N1; -using N2; -using AmbiguousEnum = N1.AmbiguousEnum; -" + enumDef + @" -namespace NTest -{ - public class Test - { - private AmbiguousEnum _AmbiguousEnum; - } -} -"; + var initialMarkup = """ + using N1; + using N2; + """ + enumDef + """ + namespace NTest + { + public class Test + { + private [|AmbiguousEnum|] _AmbiguousEnum; + } + } + """; + var expectedMarkup = """ + using N1; + using N2; + using AmbiguousEnum = N1.AmbiguousEnum; + """ + enumDef + """ + namespace NTest + { + public class Test + { + private AmbiguousEnum _AmbiguousEnum; + } + } + """; await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup); } @@ -395,31 +395,31 @@ public class Test public async Task TestAmbiguousStructDiagnosedAtPropertyDeclaration() { var strcutDef = GetAmbiguousDefinition(@"public struct AmbiguousStruct { }"); - var initialMarkup = @" -using N1; -using N2; -" + strcutDef + @" -namespace NTest -{ - public class Test - { - public [|AmbiguousStruct|] AmbiguousStruct { get; } - } -} -"; - var expectedMarkup = @" -using N1; -using N2; -using AmbiguousStruct = N1.AmbiguousStruct; -" + strcutDef + @" -namespace NTest -{ - public class Test - { - public AmbiguousStruct AmbiguousStruct { get; } - } -} -"; + var initialMarkup = """ + using N1; + using N2; + """ + strcutDef + """ + namespace NTest + { + public class Test + { + public [|AmbiguousStruct|] AmbiguousStruct { get; } + } + } + """; + var expectedMarkup = """ + using N1; + using N2; + using AmbiguousStruct = N1.AmbiguousStruct; + """ + strcutDef + """ + namespace NTest + { + public class Test + { + public AmbiguousStruct AmbiguousStruct { get; } + } + } + """; await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup); } @@ -427,37 +427,37 @@ public class Test public async Task TestAmbiguousClassDiagnosedAtTypeArgument() { var classDef = GetAmbiguousDefinition(@"public class AmbiguousClass { }"); - var initialMarkup = @" -using N1; -using N2; -" + classDef + @" -namespace NTest -{ - public class Test - { - public void M() - { - var list = new System.Collections.Generic.List<[|AmbiguousClass|]> { new AmbiguousClass() }; - } - } -} -"; - var expectedMarkup = @" -using N1; -using N2; -using AmbiguousClass = N1.AmbiguousClass; -" + classDef + @" -namespace NTest -{ - public class Test - { - public void M() - { - var list = new System.Collections.Generic.List { new AmbiguousClass() }; - } - } -} -"; + var initialMarkup = """ + using N1; + using N2; + """ + classDef + """ + namespace NTest + { + public class Test + { + public void M() + { + var list = new System.Collections.Generic.List<[|AmbiguousClass|]> { new AmbiguousClass() }; + } + } + } + """; + var expectedMarkup = """ + using N1; + using N2; + using AmbiguousClass = N1.AmbiguousClass; + """ + classDef + """ + namespace NTest + { + public class Test + { + public void M() + { + var list = new System.Collections.Generic.List { new AmbiguousClass() }; + } + } + } + """; await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup); } @@ -465,37 +465,37 @@ public void M() public async Task TestAmbiguousClassDiagnosedAtIdentifierOfIncompleteExpression() { var classDef = GetAmbiguousDefinition(@"public class AmbiguousClass { }"); - var initialMarkup = @" -using N1; -using N2; -" + classDef + @" -namespace NTest -{ - public class Test - { - public void M() - { - [|AmbiguousClass|] - } - } -} -"; - var expectedMarkup = @" -using N1; -using N2; -using AmbiguousClass = N1.AmbiguousClass; -" + classDef + @" -namespace NTest -{ - public class Test - { - public void M() - { - AmbiguousClass - } - } -} -"; + var initialMarkup = """ + using N1; + using N2; + """ + classDef + """ + namespace NTest + { + public class Test + { + public void M() + { + [|AmbiguousClass|] + } + } + } + """; + var expectedMarkup = """ + using N1; + using N2; + using AmbiguousClass = N1.AmbiguousClass; + """ + classDef + """ + namespace NTest + { + public class Test + { + public void M() + { + AmbiguousClass + } + } + } + """; await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup); } @@ -503,35 +503,35 @@ public void M() public async Task TestAmbiguousClassDiagnosedAtMethodParameter() { var classDef = GetAmbiguousDefinition(@"public class AmbiguousClass { }"); - var initialMarkup = @" -using N1; -using N2; -" + classDef + @" -namespace NTest -{ - public class Test - { - public void M([|AmbiguousClass|] a) - { - } - } -} -"; - var expectedMarkup = @" -using N1; -using N2; -using AmbiguousClass = N1.AmbiguousClass; -" + classDef + @" -namespace NTest -{ - public class Test - { - public void M(AmbiguousClass a) - { - } - } -} -"; + var initialMarkup = """ + using N1; + using N2; + """ + classDef + """ + namespace NTest + { + public class Test + { + public void M([|AmbiguousClass|] a) + { + } + } + } + """; + var expectedMarkup = """ + using N1; + using N2; + using AmbiguousClass = N1.AmbiguousClass; + """ + classDef + """ + namespace NTest + { + public class Test + { + public void M(AmbiguousClass a) + { + } + } + } + """; await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup); } @@ -539,41 +539,41 @@ public void M(AmbiguousClass a) public async Task TestAmbiguousClassDiagnosedAtFromClauseTypeIdentifier() { var classDef = GetAmbiguousDefinition(@"public class AmbiguousClass { }"); - var initialMarkup = @" -using N1; -using N2; -using System.Linq; -" + classDef + @" -namespace NTest -{ - public class Test - { - public void M() - { - var qry = from [|AmbiguousClass|] a in new object[] { } - select a; - } - } -} -"; - var expectedMarkup = @" -using N1; -using N2; -using System.Linq; -using AmbiguousClass = N1.AmbiguousClass; -" + classDef + @" -namespace NTest -{ - public class Test - { - public void M() - { - var qry = from AmbiguousClass a in new object[] { } - select a; - } - } -} -"; + var initialMarkup = """ + using N1; + using N2; + using System.Linq; + """ + classDef + """ + namespace NTest + { + public class Test + { + public void M() + { + var qry = from [|AmbiguousClass|] a in new object[] { } + select a; + } + } + } + """; + var expectedMarkup = """ + using N1; + using N2; + using System.Linq; + using AmbiguousClass = N1.AmbiguousClass; + """ + classDef + """ + namespace NTest + { + public class Test + { + public void M() + { + var qry = from AmbiguousClass a in new object[] { } + select a; + } + } + } + """; await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup); } @@ -581,49 +581,52 @@ public void M() public async Task TestSortSystemFirst1() { var classDef = GetAmbiguousDefinition("public class Ambiguous { }", "Microsoft", "System"); - var initialMarkup = classDef + @" -namespace Test -{ - using System; - using Microsoft; - class C - { - void M() - { - var a = new [|Ambiguous|](); - } - } -}"; - var expectedMarkup0 = classDef + @" -namespace Test -{ - using System; - using Microsoft; - using Ambiguous = System.Ambiguous; + var initialMarkup = classDef + """ + namespace Test + { + using System; + using Microsoft; + class C + { + void M() + { + var a = new [|Ambiguous|](); + } + } + } + """; + var expectedMarkup0 = classDef + """ + namespace Test + { + using System; + using Microsoft; + using Ambiguous = System.Ambiguous; - class C - { - void M() - { - var a = new Ambiguous(); - } - } -}"; - var expectedMarkup1 = classDef + @" -namespace Test -{ - using System; - using Microsoft; - using Ambiguous = Microsoft.Ambiguous; + class C + { + void M() + { + var a = new Ambiguous(); + } + } + } + """; + var expectedMarkup1 = classDef + """ + namespace Test + { + using System; + using Microsoft; + using Ambiguous = Microsoft.Ambiguous; - class C - { - void M() - { - var a = new Ambiguous(); - } - } -}"; + class C + { + void M() + { + var a = new Ambiguous(); + } + } + } + """; await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup0, index: 0); await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup1, index: 1); } @@ -632,49 +635,52 @@ void M() public async Task TestSortSystemFirst2() { var classDef = GetAmbiguousDefinition("public class Ambiguous { }", "Microsoft", "System"); - var initialMarkup = classDef + @" -namespace Test -{ - using System; - using Microsoft; - class C - { - void M() - { - var a = new [|Ambiguous|](); - } - } -}"; - var expectedMarkup0 = classDef + @" -namespace Test -{ - using System; - using Microsoft; - using Ambiguous = Microsoft.Ambiguous; + var initialMarkup = classDef + """ + namespace Test + { + using System; + using Microsoft; + class C + { + void M() + { + var a = new [|Ambiguous|](); + } + } + } + """; + var expectedMarkup0 = classDef + """ + namespace Test + { + using System; + using Microsoft; + using Ambiguous = Microsoft.Ambiguous; - class C - { - void M() - { - var a = new Ambiguous(); - } - } -}"; - var expectedMarkup1 = classDef + @" -namespace Test -{ - using System; - using Microsoft; - using Ambiguous = System.Ambiguous; + class C + { + void M() + { + var a = new Ambiguous(); + } + } + } + """; + var expectedMarkup1 = classDef + """ + namespace Test + { + using System; + using Microsoft; + using Ambiguous = System.Ambiguous; - class C - { - void M() - { - var a = new Ambiguous(); - } - } -}"; + class C + { + void M() + { + var a = new Ambiguous(); + } + } + } + """; var options = new OptionsCollection(LanguageNames.CSharp) { { GenerationOptions.PlaceSystemNamespaceFirst, false } diff --git a/src/Analyzers/CSharp/Tests/AssignOutParameters/AssignOutParametersAboveReturnTests.cs b/src/Analyzers/CSharp/Tests/AssignOutParameters/AssignOutParametersAboveReturnTests.cs index 5edcbc84e80ef..a34038ab097a5 100644 --- a/src/Analyzers/CSharp/Tests/AssignOutParameters/AssignOutParametersAboveReturnTests.cs +++ b/src/Analyzers/CSharp/Tests/AssignOutParameters/AssignOutParametersAboveReturnTests.cs @@ -19,9 +19,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AssignOutParameters; public sealed class AssignOutParametersAboveReturnTests { [Fact] - public async Task TestForSimpleReturn() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestForSimpleReturn() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -41,12 +40,10 @@ char M(out int i) } } """); - } [Fact] - public async Task TestForSwitchSectionReturn() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestForSwitchSectionReturn() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -74,7 +71,6 @@ char M(out int i) } } """); - } [Fact] public async Task TestMissingWhenVariableAssigned() @@ -94,9 +90,8 @@ char M(out int i) } [Fact] - public async Task TestWhenNotAssignedThroughAllPaths1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestWhenNotAssignedThroughAllPaths1() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -121,12 +116,10 @@ char M(bool b, out int i) } } """); - } [Fact] - public async Task TestWhenNotAssignedThroughAllPaths2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestWhenNotAssignedThroughAllPaths2() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -158,7 +151,6 @@ bool Try(out int i) } } """); - } [Fact] public async Task TestMissingWhenAssignedThroughAllPaths() @@ -182,9 +174,8 @@ char M(bool b, out int i) } [Fact] - public async Task TestMultiple() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestMultiple() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -205,12 +196,10 @@ char M(out int i, out string s) } } """); - } [Fact] - public async Task TestMultiple_AssignedInReturn1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestMultiple_AssignedInReturn1() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -230,12 +219,10 @@ string M(out int i, out string s) } } """); - } [Fact] - public async Task TestMultiple_AssignedInReturn2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestMultiple_AssignedInReturn2() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -255,12 +242,10 @@ string M(out int i, out string s) } } """); - } [Fact] - public async Task TestNestedReturn() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestNestedReturn() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -286,12 +271,10 @@ char M(out int i) } } """); - } [Fact] - public async Task TestNestedReturnNoBlock() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestNestedReturnNoBlock() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -315,12 +298,10 @@ char M(out int i) } } """); - } [Fact] - public async Task TestNestedReturnEvenWhenWrittenAfter() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestNestedReturnEvenWhenWrittenAfter() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -352,12 +333,10 @@ char M(bool b, out int i) } } """); - } [Fact] - public async Task TestForExpressionBodyMember() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestForExpressionBodyMember() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -374,12 +353,10 @@ char M(out int i) } } """); - } [Fact] - public async Task TestForLambdaExpressionBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestForLambdaExpressionBody() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -400,12 +377,10 @@ void X() } } """); - } [Fact] - public async Task TestMissingForLocalFunctionExpressionBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestMissingForLocalFunctionExpressionBody() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -427,12 +402,10 @@ void X() } } """); - } [Fact] - public async Task TestForLambdaBlockBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestForLambdaBlockBody() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -460,12 +433,10 @@ void X() } } """); - } [Fact] - public async Task TestForLocalFunctionBlockBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestForLocalFunctionBlockBody() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -495,7 +466,6 @@ char D(out int i) } } """); - } [Fact] public async Task TestForOutParamInSinglePath() @@ -521,9 +491,8 @@ char M(bool b, out int i) } [Fact] - public async Task TestFixAll1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFixAll1() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -560,12 +529,10 @@ char M(bool b, out int i, out int j) } } """); - } [Fact] - public async Task TestFixAll1_MultipleMethods() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFixAll1_MultipleMethods() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -628,12 +595,10 @@ char N(bool b, out int i, out int j) } } """); - } [Fact] - public async Task TestFixAll2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFixAll2() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -666,12 +631,10 @@ char M(bool b, out int i, out int j) } } """); - } [Fact] - public async Task TestFixAll2_MultipleMethods() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFixAll2_MultipleMethods() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -726,12 +689,10 @@ char N(bool b, out int i, out int j) } } """); - } [Fact] - public async Task TestFixAll3() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFixAll3() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -770,12 +731,10 @@ char M(bool b, out int i, out int j) } } """); - } [Fact] - public async Task TestFixAll3_MultipleMethods() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFixAll3_MultipleMethods() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -842,5 +801,4 @@ char N(bool b, out int i, out int j) } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/AssignOutParameters/AssignOutParametersAtStartTests.cs b/src/Analyzers/CSharp/Tests/AssignOutParameters/AssignOutParametersAtStartTests.cs index 4635adcafca23..d9f4682861ec3 100644 --- a/src/Analyzers/CSharp/Tests/AssignOutParameters/AssignOutParametersAtStartTests.cs +++ b/src/Analyzers/CSharp/Tests/AssignOutParameters/AssignOutParametersAtStartTests.cs @@ -41,9 +41,8 @@ char M(out int i) } [Fact] - public async Task TestForSwitchSectionReturn() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestForSwitchSectionReturn() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -71,7 +70,6 @@ char M(out int i) } } """); - } [Fact] public async Task TestMissingWhenVariableAssigned() @@ -91,9 +89,8 @@ char M(out int i) } [Fact] - public async Task TestWhenNotAssignedThroughAllPaths1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestWhenNotAssignedThroughAllPaths1() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -119,7 +116,6 @@ char M(bool b, out int i) } } """); - } [Fact] public async Task TestWhenNotAssignedThroughAllPaths2() @@ -217,9 +213,8 @@ string M(out int i, out string s) } [Fact] - public async Task TestNestedReturn() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestNestedReturn() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -245,12 +240,10 @@ char M(out int i) } } """); - } [Fact] - public async Task TestNestedReturnNoBlock() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestNestedReturnNoBlock() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -272,12 +265,10 @@ char M(out int i) } } """); - } [Fact] - public async Task TestNestedReturnEvenWhenWrittenAfter() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestNestedReturnEvenWhenWrittenAfter() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -309,7 +300,6 @@ char M(bool b, out int i) } } """); - } [Fact] public async Task TestForExpressionBodyMember() @@ -428,9 +418,8 @@ char M(bool b, out int i) } [Fact] - public async Task TestFixAll1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFixAll1() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -465,12 +454,10 @@ char M(bool b, out int i, out int j) } } """); - } [Fact] - public async Task TestFixAll1_MultipleMethods() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFixAll1_MultipleMethods() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -529,12 +516,10 @@ char N(bool b, out int i, out int j) } } """); - } [Fact] - public async Task TestFixAll2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFixAll2() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -561,12 +546,10 @@ char M(bool b, out int i, out int j) } } """); - } [Fact] - public async Task TestFixAll2_MultipleMethods() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFixAll2_MultipleMethods() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -609,12 +592,10 @@ char N(bool b, out int i, out int j) } } """); - } [Fact] - public async Task TestFixAll3() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFixAll3() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -653,12 +634,10 @@ char M(bool b, out int i, out int j) } } """); - } [Fact] - public async Task TestFixAll3_MultipleMethods() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFixAll3_MultipleMethods() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -725,5 +704,4 @@ char N(bool b, out int i, out int j) } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/ConditionalExpressionInStringInterpolation/CSharpAddParenthesesAroundConditionalExpressionInInterpolatedStringCodeFixProviderTests.cs b/src/Analyzers/CSharp/Tests/ConditionalExpressionInStringInterpolation/CSharpAddParenthesesAroundConditionalExpressionInInterpolatedStringCodeFixProviderTests.cs index 2fb2222dfad5e..c6efb0a63901f 100644 --- a/src/Analyzers/CSharp/Tests/ConditionalExpressionInStringInterpolation/CSharpAddParenthesesAroundConditionalExpressionInInterpolatedStringCodeFixProviderTests.cs +++ b/src/Analyzers/CSharp/Tests/ConditionalExpressionInStringInterpolation/CSharpAddParenthesesAroundConditionalExpressionInInterpolatedStringCodeFixProviderTests.cs @@ -41,17 +41,14 @@ await TestInRegularAndScriptAsync( } [Fact] - public async Task TestAddParenthesesSimpleConditionalExpression() - { - await TestInMethodAsync( + public Task TestAddParenthesesSimpleConditionalExpression() + => TestInMethodAsync( """var s = $"{ true ? 1 [|:|] 2}";""", """var s = $"{ (true ? 1 : 2)}";"""); - } [Fact] - public async Task TestAddParenthesesMultiLineConditionalExpression1() - { - await TestInMethodAsync(""" + public Task TestAddParenthesesMultiLineConditionalExpression1() + => TestInMethodAsync(""" var s = $@"{ true [|? 1|] : 2}"; @@ -60,12 +57,10 @@ await TestInMethodAsync(""" ? 1 : 2)}"; """); - } [Fact] - public async Task TestAddParenthesesMultiLineConditionalExpression2() - { - await TestInMethodAsync(""" + public Task TestAddParenthesesMultiLineConditionalExpression2() + => TestInMethodAsync(""" var s = $@"{ true ? @@ -82,120 +77,92 @@ await TestInMethodAsync(""" 2 ) }"; """); - } [Fact] - public async Task TestAddParenthesesWithTrivia() - { - await TestInMethodAsync( + public Task TestAddParenthesesWithTrivia() + => TestInMethodAsync( """var s = $"{ /* Leading1 */ true /* Leading2 */ ? /* TruePart1 */ 1 /* TruePart2 */[|:|] /* FalsePart1 */ 2 /* FalsePart2 */ }";""", """var s = $"{ /* Leading1 */ (true /* Leading2 */ ? /* TruePart1 */ 1 /* TruePart2 */: /* FalsePart1 */ 2) /* FalsePart2 */ }";"""); - } [Fact] - public async Task TestAddParenthesesClosingBracketInFalseCondition() - { - await TestInMethodAsync( + public Task TestAddParenthesesClosingBracketInFalseCondition() + => TestInMethodAsync( """var s = $"{ true ? new int[0] [|:|] new int[] {} }";""", """var s = $"{ (true ? new int[0] : new int[] {}) }";"""); - } [Fact] - public async Task TestAddParenthesesStringLiteralInFalseCondition() - { - await TestInMethodAsync( + public Task TestAddParenthesesStringLiteralInFalseCondition() + => TestInMethodAsync( """var s = $"{ true ? "1" [|:|] "2" }";""", """var s = $"{ (true ? "1" : "2") }";"""); - } [Fact] - public async Task TestAddParenthesesVerbatimStringLiteralInFalseCondition() - { - await TestInMethodAsync( + public Task TestAddParenthesesVerbatimStringLiteralInFalseCondition() + => TestInMethodAsync( """"var s = $"{ true ? "1" [|:|] @"""2""" }";"""", """"var s = $"{ (true ? "1" : @"""2""") }";""""); - } [Fact] - public async Task TestAddParenthesesStringLiteralInFalseConditionWithClosingParenthesisInLiteral() - { - await TestInMethodAsync( + public Task TestAddParenthesesStringLiteralInFalseConditionWithClosingParenthesisInLiteral() + => TestInMethodAsync( """var s = $"{ true ? "1" [|:|] "2)" }";""", """var s = $"{ (true ? "1" : "2)") }";"""); - } [Fact] - public async Task TestAddParenthesesStringLiteralInFalseConditionWithEscapedDoubleQuotes() - { - await TestInMethodAsync( + public Task TestAddParenthesesStringLiteralInFalseConditionWithEscapedDoubleQuotes() + => TestInMethodAsync( """var s = $"{ true ? "1" [|:|] "2\"" }";""", """var s = $"{ (true ? "1" : "2\"") }";"""); - } [Fact] - public async Task TestAddParenthesesStringLiteralInFalseConditionWithCodeLikeContent() - { - await TestInMethodAsync( + public Task TestAddParenthesesStringLiteralInFalseConditionWithCodeLikeContent() + => TestInMethodAsync( """var s = $"{ true ? "1" [|:|] "M(new int[] {}, \"Parameter\");" }";""", """var s = $"{ (true ? "1" : "M(new int[] {}, \"Parameter\");") }";"""); - } [Fact] - public async Task TestAddParenthesesNestedConditionalExpression1() - { - await TestInMethodAsync( + public Task TestAddParenthesesNestedConditionalExpression1() + => TestInMethodAsync( """var s2 = $"{ true ? "1" [|:|] (false ? "2" : "3") };""", """var s2 = $"{ (true ? "1" : (false ? "2" : "3")) };"""); - } [Fact] - public async Task TestAddParenthesesNestedConditionalExpression2() - { - await TestInMethodAsync( + public Task TestAddParenthesesNestedConditionalExpression2() + => TestInMethodAsync( """var s2 = $"{ true ? "1" [|:|] false ? "2" : "3" };""", """var s2 = $"{ (true ? "1" : false ? "2" : "3") };"""); - } [Fact] - public async Task TestAddParenthesesNestedConditionalWithNestedInterpolatedString() - { - await TestInMethodAsync( + public Task TestAddParenthesesNestedConditionalWithNestedInterpolatedString() + => TestInMethodAsync( """ var s2 = $"{ (true ? "1" : false ? $"{ true ? "2" [|:|] "3"}" : "4") }" """, """ var s2 = $"{ (true ? "1" : false ? $"{ (true ? "2" : "3")}" : "4") }" """); - } [Fact] - public async Task TestAddParenthesesMultipleInterpolatedSections1() - { - await TestInMethodAsync( + public Task TestAddParenthesesMultipleInterpolatedSections1() + => TestInMethodAsync( """var s3 = $"Text1 { true ? "Text2" [|:|] "Text3"} Text4 { (true ? "Text5" : "Text6")} Text7";""", """var s3 = $"Text1 { (true ? "Text2" : "Text3")} Text4 { (true ? "Text5" : "Text6")} Text7";"""); - } [Fact] - public async Task TestAddParenthesesMultipleInterpolatedSections2() - { - await TestInMethodAsync( + public Task TestAddParenthesesMultipleInterpolatedSections2() + => TestInMethodAsync( """var s3 = $"Text1 { (true ? "Text2" : "Text3")} Text4 { true ? "Text5" [|:|] "Text6"} Text7";""", """var s3 = $"Text1 { (true ? "Text2" : "Text3")} Text4 { (true ? "Text5" : "Text6")} Text7";"""); - } [Fact] - public async Task TestAddParenthesesMultipleInterpolatedSections3() - { - await TestInMethodAsync( + public Task TestAddParenthesesMultipleInterpolatedSections3() + => TestInMethodAsync( """var s3 = $"Text1 { true ? "Text2" [|:|] "Text3"} Text4 { true ? "Text5" : "Text6"} Text7";""", """var s3 = $"Text1 { (true ? "Text2" : "Text3")} Text4 { true ? "Text5" : "Text6"} Text7";"""); - } [Fact] - public async Task TestAddParenthesesWhileTyping1() - { - await TestInMethodAsync( + public Task TestAddParenthesesWhileTyping1() + => TestInMethodAsync( """ PreviousLineOfCode(); var s3 = $"Text1 { true ? "Text2" [|:|] @@ -206,12 +173,10 @@ await TestInMethodAsync( var s3 = $"Text1 { (true ? "Text2" :) NextLineOfCode(); """); - } [Fact] - public async Task TestAddParenthesesWhileTyping2() - { - await TestInMethodAsync( + public Task TestAddParenthesesWhileTyping2() + => TestInMethodAsync( """ PreviousLineOfCode(); var s3 = $"Text1 { true ? "Text2" [|:|] " @@ -222,12 +187,10 @@ await TestInMethodAsync( var s3 = $"Text1 { (true ? "Text2" : ") NextLineOfCode(); """); - } [Fact] - public async Task TestAddParenthesesWhileTyping3() - { - await TestInMethodAsync( + public Task TestAddParenthesesWhileTyping3() + => TestInMethodAsync( """ PreviousLineOfCode(); var s3 = $"Text1 { true ? "Text2" [|:|] "Text3 @@ -238,12 +201,10 @@ await TestInMethodAsync( var s3 = $"Text1 { (true ? "Text2" : "Text3) NextLineOfCode(); """); - } [Fact] - public async Task TestAddParenthesesWhileTyping4() - { - await TestInMethodAsync( + public Task TestAddParenthesesWhileTyping4() + => TestInMethodAsync( """ PreviousLineOfCode(); var s3 = $"Text1 { true ? "Text2" [|:|] "Text3" @@ -254,12 +215,10 @@ await TestInMethodAsync( var s3 = $"Text1 { (true ? "Text2" : "Text3") NextLineOfCode(); """); - } [Fact] - public async Task TestAddParenthesesWhileTyping5() - { - await TestInMethodAsync( + public Task TestAddParenthesesWhileTyping5() + => TestInMethodAsync( """ PreviousLineOfCode(); var s3 = $"Text1 { true ? "Text2" [|:|] "Text3" } @@ -270,12 +229,10 @@ await TestInMethodAsync( var s3 = $"Text1 { (true ? "Text2" : "Text3") } NextLineOfCode(); """); - } [Fact] - public async Task TestAddParenthesesWithCS1026PresentBeforeFixIsApplied1() - { - await TestInMethodAsync( + public Task TestAddParenthesesWithCS1026PresentBeforeFixIsApplied1() + => TestInMethodAsync( """ ( var s3 = $"Text1 { true ? "Text2" [|:|] "Text3" } @@ -286,12 +243,10 @@ await TestInMethodAsync( var s3 = $"Text1 { (true ? "Text2" : "Text3") } NextLineOfCode(); """); - } [Fact] - public async Task TestAddParenthesesWithCS1026PresentBeforeFixIsApplied2() - { - await TestInMethodAsync( + public Task TestAddParenthesesWithCS1026PresentBeforeFixIsApplied2() + => TestInMethodAsync( """ PreviousLineOfCode(); var s3 = $"Text1 { true ? "Text2" [|:|] "Text3" } @@ -302,12 +257,10 @@ await TestInMethodAsync( var s3 = $"Text1 { (true ? "Text2" : "Text3") } NextLineOfCode( """); - } [Fact] - public async Task TestAddParenthesesWithCS1026PresentBeforeFixIsApplied3() - { - await TestInMethodAsync( + public Task TestAddParenthesesWithCS1026PresentBeforeFixIsApplied3() + => TestInMethodAsync( """ PreviousLineOfCode(); var s3 = ($"Text1 { true ? "Text2" [|:|] "Text3" } @@ -318,17 +271,14 @@ await TestInMethodAsync( var s3 = ($"Text1 { (true ? "Text2" : "Text3") } NextLineOfCode(); """); - } [Fact] - public async Task TestAddParenthesesAddOpeningParenthesisOnly() - { - await TestInMethodAsync( + public Task TestAddParenthesesAddOpeningParenthesisOnly() + => TestInMethodAsync( """ var s3 = $"{ true ? 1 [|:|] 2 )}" """, """ var s3 = $"{ (true ? 1 : 2 )}" """); - } } diff --git a/src/Analyzers/CSharp/Tests/ConflictMarkerResolution/ConflictMarkerResolutionTests.cs b/src/Analyzers/CSharp/Tests/ConflictMarkerResolution/ConflictMarkerResolutionTests.cs index 1080fae583157..95eaa07c81bea 100644 --- a/src/Analyzers/CSharp/Tests/ConflictMarkerResolution/ConflictMarkerResolutionTests.cs +++ b/src/Analyzers/CSharp/Tests/ConflictMarkerResolution/ConflictMarkerResolutionTests.cs @@ -19,9 +19,10 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConflictMarkerResolutio public sealed class ConflictMarkerResolutionTests { [Fact] - public async Task TestTakeTop1() - { - var source = """ + public Task TestTakeTop1() + => new VerifyCS.Test + { + TestCode = """ using System; namespace N @@ -46,8 +47,8 @@ static void Main2(string[] args) } {|CS8300:>>>>>>>|} This is theirs! } - """; - var fixedSource = """ + """, + FixedCode = """ using System; namespace N @@ -61,21 +62,16 @@ static void Main(string[] args) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); - } [Fact] - public async Task TestTakeBottom1() - { - var source = """ + public Task TestTakeBottom1() + => new VerifyCS.Test + { + TestCode = """ using System; namespace N @@ -100,8 +96,8 @@ static void Main2(string[] args) } {|CS8300:>>>>>>>|} This is theirs! } - """; - var fixedSource = """ + """, + FixedCode = """ using System; namespace N @@ -115,22 +111,17 @@ static void Main2(string[] args) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); - } [Fact] - public async Task TestTakeBoth1() - { - var source = """ + public Task TestTakeBoth1() + => new VerifyCS.Test + { + TestCode = """ using System; namespace N @@ -155,8 +146,8 @@ static void Main2(string[] args) } {|CS8300:>>>>>>>|} This is theirs! } - """; - var fixedSource = """ + """, + FixedCode = """ using System; namespace N @@ -178,22 +169,17 @@ static void Main2(string[] args) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionIndex = 2, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey, }.RunAsync(); - } [Fact] - public async Task TestEmptyTop_TakeTop() - { - var source = """ + public Task TestEmptyTop_TakeTop() + => new VerifyCS.Test + { + TestCode = """ using System; namespace N @@ -210,28 +196,23 @@ static void Main2(string[] args) } {|CS8300:>>>>>>>|} This is theirs! } - """; - var fixedSource = """ + """, + FixedCode = """ using System; namespace N { } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); - } [Fact] - public async Task TestEmptyTop_TakeBottom() - { - var source = """ + public Task TestEmptyTop_TakeBottom() + => new VerifyCS.Test + { + TestCode = """ using System; namespace N @@ -248,8 +229,8 @@ static void Main2(string[] args) } {|CS8300:>>>>>>>|} This is theirs! } - """; - var fixedSource = """ + """, + FixedCode = """ using System; namespace N @@ -263,22 +244,17 @@ static void Main2(string[] args) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); - } [Fact] - public async Task TestEmptyBottom_TakeTop() - { - var source = """ + public Task TestEmptyBottom_TakeTop() + => new VerifyCS.Test + { + TestCode = """ using System; namespace N @@ -295,8 +271,8 @@ static void Main(string[] args) {|CS8300:=======|} {|CS8300:>>>>>>>|} This is theirs! } - """; - var fixedSource = """ + """, + FixedCode = """ using System; namespace N @@ -310,21 +286,16 @@ static void Main(string[] args) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); - } [Fact] - public async Task TestEmptyBottom_TakeBottom() - { - var source = """ + public Task TestEmptyBottom_TakeBottom() + => new VerifyCS.Test + { + TestCode = """ using System; namespace N @@ -341,29 +312,24 @@ static void Main(string[] args) {|CS8300:=======|} {|CS8300:>>>>>>>|} This is theirs! } - """; - var fixedSource = """ + """, + FixedCode = """ using System; namespace N { } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); - } [Fact] - public async Task TestTakeTop_WhitespaceInSection() - { - var source = """ + public Task TestTakeTop_WhitespaceInSection() + => new VerifyCS.Test + { + TestCode = """ using System; namespace N @@ -390,8 +356,8 @@ static void Main2(string[] args) } {|CS8300:>>>>>>>|} This is theirs! } - """; - var fixedSource = """ + """, + FixedCode = """ using System; namespace N @@ -407,21 +373,16 @@ static void Main(string[] args) } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); - } [Fact] - public async Task TestTakeBottom1_WhitespaceInSection() - { - var source = """ + public Task TestTakeBottom1_WhitespaceInSection() + => new VerifyCS.Test + { + TestCode = """ using System; namespace N @@ -448,8 +409,8 @@ static void Main2(string[] args) {|CS8300:>>>>>>>|} This is theirs! } - """; - var fixedSource = """ + """, + FixedCode = """ using System; namespace N @@ -465,22 +426,17 @@ static void Main2(string[] args) } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); - } [Fact] - public async Task TestTakeBoth_WhitespaceInSection() - { - var source = """ + public Task TestTakeBoth_WhitespaceInSection() + => new VerifyCS.Test + { + TestCode = """ using System; namespace N @@ -509,8 +465,8 @@ static void Main2(string[] args) {|CS8300:>>>>>>>|} This is theirs! } - """; - var fixedSource = """ + """, + FixedCode = """ using System; namespace N @@ -536,22 +492,17 @@ static void Main2(string[] args) } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionIndex = 2, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23847")] - public async Task TestTakeTop_TopCommentedOut() - { - var source = """ + public Task TestTakeTop_TopCommentedOut() + => new VerifyCS.Test + { + TestCode = """ public class Class1 { public void M() @@ -567,8 +518,8 @@ public void M() // */ } } - """; - var fixedSource = """ + """, + FixedCode = """ public class Class1 { public void M() @@ -579,21 +530,16 @@ public void M() // */ } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23847")] - public async Task TestTakeTop_SecondMiddleAndBottomCommentedOut() - { - var source = """ + public Task TestTakeTop_SecondMiddleAndBottomCommentedOut() + => new VerifyCS.Test + { + TestCode = """ public class Class1 { public void M() @@ -608,8 +554,8 @@ public void M() */ } } - """; - var fixedSource = """ + """, + FixedCode = """ public class Class1 { public void M() @@ -619,21 +565,16 @@ public void M() */ } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23847")] - public async Task TestTakeTop_TopInString() - { - var source = """ + public Task TestTakeTop_TopInString() + => new VerifyCS.Test + { + TestCode = """ class X { void x() { var x = @" @@ -644,29 +585,24 @@ void x() { {|CS8300:>>>>>>>|} merge rev } } - """; - var fixedSource = """ + """, + FixedCode = """ class X { void x() { var x = @" a"; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23847")] - public async Task TestTakeBottom_TopInString() - { - var source = """ + public Task TestTakeBottom_TopInString() + => new VerifyCS.Test + { + TestCode = """ class X { void x() { var x = @" @@ -677,78 +613,61 @@ void x() { {|CS8300:>>>>>>>|} merge rev } } - """; - var fixedSource = """ + """, + FixedCode = """ class X { void x() { var x = @" b"; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23847")] - public async Task TestMissingWithMiddleMarkerAtTopOfFile() - { - var source = """ + public Task TestMissingWithMiddleMarkerAtTopOfFile() + => new VerifyCS.Test + { + TestCode = """ {|CS8300:=======|} class X { } {|CS8300:>>>>>>>|} merge rev - """; - - await new VerifyCS.Test - { - TestCode = source, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23847")] - public async Task TestMissingWithMiddleMarkerAtBottomOfFile() - { - var source = """ + public Task TestMissingWithMiddleMarkerAtBottomOfFile() + => new VerifyCS.Test + { + TestCode = """ {|CS8300:<<<<<<<|} working copy class X { } {|CS8300:=======|} - """; - - await new VerifyCS.Test - { - TestCode = source, + """, }.RunAsync(); - } [Fact] - public async Task TestMissingWithFirstMiddleMarkerAtBottomOfFile() - { - var source = """ + public Task TestMissingWithFirstMiddleMarkerAtBottomOfFile() + => new VerifyCS.Test + { + TestCode = """ {|CS8300:<<<<<<<|} working copy class X { } {|CS8300:||||||||} - """; - - await new VerifyCS.Test - { - TestCode = source, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21107")] - public async Task TestFixAll1() - { - var source = """ + public Task TestFixAll1() + => new VerifyCS.Test + { + TestCode = """ using System; namespace N @@ -773,8 +692,8 @@ class Program4 } {|CS8300:>>>>>>>|} This is theirs! } - """; - var fixedSource = """ + """, + FixedCode = """ using System; namespace N @@ -787,21 +706,16 @@ class Program3 { } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 2, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21107")] - public async Task TestFixAll2() - { - var source = """ + public Task TestFixAll2() + => new VerifyCS.Test + { + TestCode = """ using System; namespace N @@ -826,8 +740,8 @@ class Program4 } {|CS8300:>>>>>>>|} This is theirs! } - """; - var fixedSource = """ + """, + FixedCode = """ using System; namespace N @@ -840,22 +754,17 @@ class Program4 { } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 2, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21107")] - public async Task TestFixAll3() - { - var source = """ + public Task TestFixAll3() + => new VerifyCS.Test + { + TestCode = """ using System; namespace N @@ -880,8 +789,8 @@ class Program4 } {|CS8300:>>>>>>>|} This is theirs! } - """; - var fixedSource = """ + """, + FixedCode = """ using System; namespace N @@ -900,22 +809,17 @@ class Program4 { } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 2, CodeActionIndex = 2, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey, }.RunAsync(); - } [Fact] - public async Task TestTakeTop_WithBaseline() - { - var source = """ + public Task TestTakeTop_WithBaseline() + => new VerifyCS.Test + { + TestCode = """ using System; namespace N @@ -942,8 +846,8 @@ static void Main2(string[] args) } {|CS8300:>>>>>>>|} This is theirs! } - """; - var fixedSource = """ + """, + FixedCode = """ using System; namespace N @@ -957,21 +861,16 @@ static void Main(string[] args) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); - } [Fact] - public async Task TestTakeBottom1_WithBaseline() - { - var source = """ + public Task TestTakeBottom1_WithBaseline() + => new VerifyCS.Test + { + TestCode = """ using System; namespace N @@ -998,8 +897,8 @@ static void Main2(string[] args) } {|CS8300:>>>>>>>|} This is theirs! } - """; - var fixedSource = """ + """, + FixedCode = """ using System; namespace N @@ -1013,22 +912,17 @@ static void Main2(string[] args) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); - } [Fact] - public async Task TestTakeBoth1_WithBaseline() - { - var source = """ + public Task TestTakeBoth1_WithBaseline() + => new VerifyCS.Test + { + TestCode = """ using System; namespace N @@ -1055,8 +949,8 @@ static void Main2(string[] args) } {|CS8300:>>>>>>>|} This is theirs! } - """; - var fixedSource = """ + """, + FixedCode = """ using System; namespace N @@ -1078,22 +972,17 @@ static void Main2(string[] args) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionIndex = 2, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey, }.RunAsync(); - } [Fact] - public async Task TestEmptyTop_TakeTop_WithBaseline() - { - var source = """ + public Task TestEmptyTop_TakeTop_WithBaseline() + => new VerifyCS.Test + { + TestCode = """ using System; namespace N @@ -1112,28 +1001,23 @@ static void Main2(string[] args) } {|CS8300:>>>>>>>|} This is theirs! } - """; - var fixedSource = """ + """, + FixedCode = """ using System; namespace N { } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); - } [Fact] - public async Task TestEmptyTop_TakeBottom_WithBaseline() - { - var source = """ + public Task TestEmptyTop_TakeBottom_WithBaseline() + => new VerifyCS.Test + { + TestCode = """ using System; namespace N @@ -1152,8 +1036,8 @@ static void Main2(string[] args) } {|CS8300:>>>>>>>|} This is theirs! } - """; - var fixedSource = """ + """, + FixedCode = """ using System; namespace N @@ -1167,22 +1051,17 @@ static void Main2(string[] args) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); - } [Fact] - public async Task TestEmptyBottom_TakeTop_WithBaseline() - { - var source = """ + public Task TestEmptyBottom_TakeTop_WithBaseline() + => new VerifyCS.Test + { + TestCode = """ using System; namespace N @@ -1201,8 +1080,8 @@ class Removed { } {|CS8300:=======|} {|CS8300:>>>>>>>|} This is theirs! } - """; - var fixedSource = """ + """, + FixedCode = """ using System; namespace N @@ -1216,21 +1095,16 @@ static void Main(string[] args) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); - } [Fact] - public async Task TestEmptyBottom_TakeBottom_WithBaseline() - { - var source = """ + public Task TestEmptyBottom_TakeBottom_WithBaseline() + => new VerifyCS.Test + { + TestCode = """ using System; namespace N @@ -1249,29 +1123,24 @@ class Removed { } {|CS8300:=======|} {|CS8300:>>>>>>>|} This is theirs! } - """; - var fixedSource = """ + """, + FixedCode = """ using System; namespace N { } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); - } [Fact] - public async Task TestTakeTop_TopCommentedOut_WithBaseline() - { - var source = """ + public Task TestTakeTop_TopCommentedOut_WithBaseline() + => new VerifyCS.Test + { + TestCode = """ public class Class1 { public void M() @@ -1290,8 +1159,8 @@ public void M() // */ } } - """; - var fixedSource = """ + """, + FixedCode = """ public class Class1 { public void M() @@ -1302,21 +1171,16 @@ public void M() // */ } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); - } [Fact] - public async Task TestTakeTop_FirstMiddleAndSecondMiddleAndBottomCommentedOut() - { - var source = """ + public Task TestTakeTop_FirstMiddleAndSecondMiddleAndBottomCommentedOut() + => new VerifyCS.Test + { + TestCode = """ public class Class1 { public void M() @@ -1333,8 +1197,8 @@ public void M() */ } } - """; - var fixedSource = """ + """, + FixedCode = """ public class Class1 { public void M() @@ -1344,21 +1208,16 @@ public void M() */ } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); - } [Fact] - public async Task TestTakeTop_TopInString_WithBaseline() - { - var source = """ + public Task TestTakeTop_TopInString_WithBaseline() + => new VerifyCS.Test + { + TestCode = """ class X { void x() { var x = @" @@ -1371,29 +1230,24 @@ void x() { {|CS8300:>>>>>>>|} merge rev } } - """; - var fixedSource = """ + """, + FixedCode = """ class X { void x() { var x = @" a"; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); - } [Fact] - public async Task TestTakeBottom_TopInString_WithBaseline() - { - var source = """ + public Task TestTakeBottom_TopInString_WithBaseline() + => new VerifyCS.Test + { + TestCode = """ class X { void x() { var x = @" @@ -1406,47 +1260,38 @@ void x() { {|CS8300:>>>>>>>|} merge rev } } - """; - var fixedSource = """ + """, + FixedCode = """ class X { void x() { var x = @" b"; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); - } [Fact] - public async Task TestMissingWithFirstMiddleMarkerAtTopOfFile() - { - var source = """ + public Task TestMissingWithFirstMiddleMarkerAtTopOfFile() + => new VerifyCS.Test + { + TestCode = """ {|CS8300:||||||||} baseline {|CS8300:=======|} class X { } {|CS8300:>>>>>>>|} merge rev - """; - - await new VerifyCS.Test - { - TestCode = source, + """, }.RunAsync(); - } [Fact] - public async Task TestFixAll1_WithBaseline() - { - var source = """ + public Task TestFixAll1_WithBaseline() + => new VerifyCS.Test + { + TestCode = """ using System; namespace N @@ -1475,8 +1320,8 @@ class Program4 } {|CS8300:>>>>>>>|} This is theirs! } - """; - var fixedSource = """ + """, + FixedCode = """ using System; namespace N @@ -1489,21 +1334,16 @@ class Program3 { } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 2, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); - } [Fact] - public async Task TestFixAll2_WithBaseline() - { - var source = """ + public Task TestFixAll2_WithBaseline() + => new VerifyCS.Test + { + TestCode = """ using System; namespace N @@ -1532,8 +1372,8 @@ class Program4 } {|CS8300:>>>>>>>|} This is theirs! } - """; - var fixedSource = """ + """, + FixedCode = """ using System; namespace N @@ -1546,22 +1386,17 @@ class Program4 { } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 2, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); - } [Fact] - public async Task TestFixAll3_WithBaseline() - { - var source = """ + public Task TestFixAll3_WithBaseline() + => new VerifyCS.Test + { + TestCode = """ using System; namespace N @@ -1590,8 +1425,8 @@ class Program4 } {|CS8300:>>>>>>>|} This is theirs! } - """; - var fixedSource = """ + """, + FixedCode = """ using System; namespace N @@ -1610,15 +1445,9 @@ class Program4 { } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, NumberOfIncrementalIterations = 2, CodeActionIndex = 2, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/ConvertNamespace/ConvertToBlockScopedNamespaceAnalyzerTests.cs b/src/Analyzers/CSharp/Tests/ConvertNamespace/ConvertToBlockScopedNamespaceAnalyzerTests.cs index d982794e9faaf..ba01489e1d6ea 100644 --- a/src/Analyzers/CSharp/Tests/ConvertNamespace/ConvertToBlockScopedNamespaceAnalyzerTests.cs +++ b/src/Analyzers/CSharp/Tests/ConvertNamespace/ConvertToBlockScopedNamespaceAnalyzerTests.cs @@ -31,9 +31,8 @@ public static IEnumerable EndOfDocumentSequences #region Convert To Block Scoped [Fact] - public async Task TestConvertToBlockScopedInCSharp9() - { - await new VerifyCS.Test + public Task TestConvertToBlockScopedInCSharp9() + => new VerifyCS.Test { TestCode = """ [|{|CS8773:namespace|} N;|] @@ -49,12 +48,10 @@ namespace N { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockScopedInCSharp9_NotSilent() - { - await new VerifyCS.Test + public Task TestConvertToBlockScopedInCSharp9_NotSilent() + => new VerifyCS.Test { TestCode = """ {|CS8773:namespace|} [|N|]; @@ -70,30 +67,25 @@ namespace N { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped, NotificationOption2.Suggestion } } }.RunAsync(); - } [Fact] - public async Task TestNoConvertToBlockScopedInCSharp10WithBlockScopedPreference() - { - var code = """ - namespace N {} - """; - await new VerifyCS.Test + public Task TestNoConvertToBlockScopedInCSharp10WithBlockScopedPreference() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + namespace N {} + """, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Theory] [MemberData(nameof(EndOfDocumentSequences))] - public async Task TestConvertToBlockScopedInCSharp10WithFileScopedPreference(string endOfDocumentSequence) - { - await new VerifyCS.Test + public Task TestConvertToBlockScopedInCSharp10WithFileScopedPreference(string endOfDocumentSequence) + => new VerifyCS.Test { TestCode = $$""" [|namespace N;|]{{endOfDocumentSequence}} @@ -109,13 +101,11 @@ namespace N { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Theory] [MemberData(nameof(EndOfDocumentSequences))] - public async Task TestConvertToBlockScopedInCSharp10WithDirectives1(string endOfDocumentSequence) - { - await new VerifyCS.Test + public Task TestConvertToBlockScopedInCSharp10WithDirectives1(string endOfDocumentSequence) + => new VerifyCS.Test { TestCode = $$""" [|namespace N;|] @@ -136,13 +126,11 @@ namespace N { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Theory] [MemberData(nameof(EndOfDocumentSequences))] - public async Task TestConvertToBlockScopedInCSharp10WithDirectives2(string endOfDocumentSequence) - { - await new VerifyCS.Test + public Task TestConvertToBlockScopedInCSharp10WithDirectives2(string endOfDocumentSequence) + => new VerifyCS.Test { TestCode = $$""" [|namespace N;|] @@ -163,13 +151,11 @@ namespace N { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Theory] [MemberData(nameof(EndOfDocumentSequences))] - public async Task TestConvertToBlockWithMultipleNamespaces(string endOfDocumentSequence) - { - await new VerifyCS.Test + public Task TestConvertToBlockWithMultipleNamespaces(string endOfDocumentSequence) + => new VerifyCS.Test { TestCode = $$""" [|namespace N;|] @@ -192,13 +178,11 @@ namespace N2 { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Theory] [MemberData(nameof(EndOfDocumentSequences))] - public async Task TestConvertToBlockWithNestedNamespaces1(string endOfDocumentSequence) - { - await new VerifyCS.Test + public Task TestConvertToBlockWithNestedNamespaces1(string endOfDocumentSequence) + => new VerifyCS.Test { TestCode = $$""" [|namespace N;|] @@ -220,13 +204,11 @@ namespace N2 { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Theory] [MemberData(nameof(EndOfDocumentSequences))] - public async Task TestConvertToBlockWithNestedNamespaces2(string endOfDocumentSequence) - { - await new VerifyCS.Test + public Task TestConvertToBlockWithNestedNamespaces2(string endOfDocumentSequence) + => new VerifyCS.Test { TestCode = $$""" namespace N @@ -248,13 +230,11 @@ namespace $$N2 { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Theory] [MemberData(nameof(EndOfDocumentSequences))] - public async Task TestConvertToBlockWithNestedNamespaces3(string endOfDocumentSequence) - { - await new VerifyCS.Test + public Task TestConvertToBlockWithNestedNamespaces3(string endOfDocumentSequence) + => new VerifyCS.Test { TestCode = $$""" namespace N @@ -276,13 +256,11 @@ namespace $$N2 { { CSharpFormattingOptions2.NewLineBeforeOpenBrace, CSharpFormattingOptions2.NewLineBeforeOpenBrace.DefaultValue & ~NewLineBeforeOpenBracePlacement.Types }, } }.RunAsync(); - } [Theory] [MemberData(nameof(EndOfDocumentSequences))] - public async Task TestConvertToBlockWithNestedNamespaces4(string endOfDocumentSequence) - { - await new VerifyCS.Test + public Task TestConvertToBlockWithNestedNamespaces4(string endOfDocumentSequence) + => new VerifyCS.Test { TestCode = $$""" namespace N @@ -309,13 +287,11 @@ namespace $$N2 { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Theory] [MemberData(nameof(EndOfDocumentSequences))] - public async Task TestConvertToBlockWithNestedNamespaces5(string endOfDocumentSequence) - { - await new VerifyCS.Test + public Task TestConvertToBlockWithNestedNamespaces5(string endOfDocumentSequence) + => new VerifyCS.Test { TestCode = $$""" namespace N @@ -342,12 +318,10 @@ namespace $$N2 { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockWithTopLevelStatement1() - { - await new VerifyCS.Test + public Task TestConvertToBlockWithTopLevelStatement1() + => new VerifyCS.Test { TestCode = """ {|CS8805:int i = 0;|} @@ -367,12 +341,10 @@ namespace N { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockWithTopLevelStatement2() - { - await new VerifyCS.Test + public Task TestConvertToBlockWithTopLevelStatement2() + => new VerifyCS.Test { TestCode = """ [|namespace N;|] @@ -391,12 +363,10 @@ namespace N { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockScopedWithUsing1() - { - await new VerifyCS.Test + public Task TestConvertToBlockScopedWithUsing1() + => new VerifyCS.Test { TestCode = """ using System; @@ -416,12 +386,10 @@ namespace N { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockScopedWithUsing2() - { - await new VerifyCS.Test + public Task TestConvertToBlockScopedWithUsing2() + => new VerifyCS.Test { TestCode = """ [|namespace N;|] @@ -440,12 +408,10 @@ namespace $$N { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockScopedWithClass() - { - await new VerifyCS.Test + public Task TestConvertToBlockScopedWithClass() + => new VerifyCS.Test { TestCode = """ [|namespace N;|] @@ -468,12 +434,10 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockScopedWithClassWithDocComment() - { - await new VerifyCS.Test + public Task TestConvertToBlockScopedWithClassWithDocComment() + => new VerifyCS.Test { TestCode = """ [|namespace N;|] @@ -498,12 +462,10 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockScopedWithMissingCloseBrace() - { - await new VerifyCS.Test + public Task TestConvertToBlockScopedWithMissingCloseBrace() + => new VerifyCS.Test { TestCode = """ [|namespace N;|] @@ -527,12 +489,10 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockScopedWithCommentOnSemicolon() - { - await new VerifyCS.Test + public Task TestConvertToBlockScopedWithCommentOnSemicolon() + => new VerifyCS.Test { TestCode = """ [|namespace N;|] // comment @@ -555,12 +515,10 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockScopedWithLeadingComment() - { - await new VerifyCS.Test + public Task TestConvertToBlockScopedWithLeadingComment() + => new VerifyCS.Test { TestCode = """ // copyright @@ -585,7 +543,6 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } #endregion } diff --git a/src/Analyzers/CSharp/Tests/ConvertNamespace/ConvertToFileScopedNamespaceAnalyzerTests.cs b/src/Analyzers/CSharp/Tests/ConvertNamespace/ConvertToFileScopedNamespaceAnalyzerTests.cs index 78e14b88c340c..da60ea41d29a0 100644 --- a/src/Analyzers/CSharp/Tests/ConvertNamespace/ConvertToFileScopedNamespaceAnalyzerTests.cs +++ b/src/Analyzers/CSharp/Tests/ConvertNamespace/ConvertToFileScopedNamespaceAnalyzerTests.cs @@ -19,47 +19,40 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertNamespace; public sealed class ConvertToFileScopedNamespaceAnalyzerTests { [Fact] - public async Task TestNoConvertToFileScopedInCSharp9() - { - var code = """ + public Task TestNoConvertToFileScopedInCSharp9() + => new VerifyCS.Test + { + TestCode = """ namespace N { } - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp9, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestNoConvertToFileScopedInCSharp10WithBlockScopedPreference() - { - var code = """ + public Task TestNoConvertToFileScopedInCSharp10WithBlockScopedPreference() + => new VerifyCS.Test + { + TestCode = """ namespace N { } - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedInCSharp10WithBlockScopedPreference() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedInCSharp10WithBlockScopedPreference() + => new VerifyCS.Test { TestCode = """ [|namespace N|] @@ -75,12 +68,10 @@ namespace $$N; { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedInCSharp10WithBlockScopedPreference_NotSilent() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedInCSharp10WithBlockScopedPreference_NotSilent() + => new VerifyCS.Test { TestCode = """ namespace [|N|] @@ -96,12 +87,12 @@ namespace $$N; { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped, NotificationOption2.Suggestion } } }.RunAsync(); - } [Fact] - public async Task TestNoConvertWithMultipleNamespaces() - { - var code = """ + public Task TestNoConvertWithMultipleNamespaces() + => new VerifyCS.Test + { + TestCode = """ namespace N { } @@ -109,74 +100,62 @@ namespace N namespace N2 { } - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestNoConvertWithNestedNamespaces1() - { - var code = """ + public Task TestNoConvertWithNestedNamespaces1() + => new VerifyCS.Test + { + TestCode = """ namespace N { namespace N2 { } } - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestNoConvertWithTopLevelStatement1() - { - var code = """ + public Task TestNoConvertWithTopLevelStatement1() + => new VerifyCS.Test + { + TestCode = """ {|CS8805:int i = 0;|} namespace N { } - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestNoConvertWithTopLevelStatement2() - { - var code = """ + public Task TestNoConvertWithTopLevelStatement2() + => new VerifyCS.Test + { + TestCode = """ namespace N { } int i = 0; - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp10, ExpectedDiagnostics = { @@ -190,12 +169,10 @@ namespace N { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedWithUsing1() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithUsing1() + => new VerifyCS.Test { TestCode = """ using System; @@ -215,12 +192,10 @@ namespace $$N; { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedWithUsing2() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithUsing2() + => new VerifyCS.Test { TestCode = """ [|namespace N|] @@ -239,12 +214,10 @@ namespace $$N; { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedWithClass() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithClass() + => new VerifyCS.Test { TestCode = """ [|namespace N|] @@ -267,12 +240,10 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedWithClassWithDocComment() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithClassWithDocComment() + => new VerifyCS.Test { TestCode = """ [|namespace N|] @@ -297,12 +268,10 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedWithMissingCloseBrace() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithMissingCloseBrace() + => new VerifyCS.Test { TestCode = """ [|namespace N|] @@ -326,12 +295,10 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedWithCommentOnOpenCurly() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithCommentOnOpenCurly() + => new VerifyCS.Test { TestCode = """ [|namespace N|] @@ -354,12 +321,10 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedWithLeadingComment() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithLeadingComment() + => new VerifyCS.Test { TestCode = """ // copyright @@ -384,12 +349,10 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedWithDocComment() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithDocComment() + => new VerifyCS.Test { TestCode = """ [|namespace N|] @@ -414,12 +377,10 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedWithPPDirective1() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithPPDirective1() + => new VerifyCS.Test { TestCode = """ [|namespace N|] @@ -455,12 +416,10 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedWithBlockComment() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithBlockComment() + => new VerifyCS.Test { TestCode = """ [|namespace N|] @@ -489,12 +448,10 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedWithBlockComment2() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithBlockComment2() + => new VerifyCS.Test { TestCode = """ [|namespace N|] @@ -523,12 +480,10 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedWithMultilineString() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithMultilineString() + => new VerifyCS.Test { TestCode = """ [|namespace N|] @@ -571,12 +526,10 @@ void M() { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedWithMultilineString2() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithMultilineString2() + => new VerifyCS.Test { TestCode = """ [|namespace N|] @@ -619,12 +572,10 @@ void M() { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedWithMultilineString3() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithMultilineString3() + => new VerifyCS.Test { TestCode = """ [|namespace N|] @@ -669,12 +620,10 @@ void M() { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Theory, InlineData(""), InlineData("u8")] - public async Task TestConvertToFileScopedWithMultiLineRawString1(string suffix) - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithMultiLineRawString1(string suffix) + => new VerifyCS.Test { TestCode = $$"""" [|namespace N|] @@ -724,12 +673,10 @@ void WriteLine(System.ReadOnlySpan s) { } { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Theory, InlineData(""), InlineData("u8")] - public async Task TestConvertToFileScopedWithMultiLineRawString2(string suffix) - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithMultiLineRawString2(string suffix) + => new VerifyCS.Test { TestCode = $$"""" [|namespace N|] @@ -779,12 +726,10 @@ void WriteLine(System.ReadOnlySpan s) { } { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Theory, InlineData(""), InlineData("u8")] - public async Task TestConvertToFileScopedWithMultiLineRawString3(string suffix) - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithMultiLineRawString3(string suffix) + => new VerifyCS.Test { TestCode = $$"""" [|namespace N|] @@ -834,12 +779,10 @@ void WriteLine(System.ReadOnlySpan s) { } { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedSingleLineNamespace1() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedSingleLineNamespace1() + => new VerifyCS.Test { TestCode = """ [|namespace N|] { class C { } } @@ -853,12 +796,10 @@ namespace $$N; class C { } { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedSingleLineNamespace2() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedSingleLineNamespace2() + => new VerifyCS.Test { TestCode = """ [|namespace N|] @@ -874,12 +815,10 @@ class C { } { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/59728")] - public async Task TestConvertToFileScopedWithNoNewlineAtEnd() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithNoNewlineAtEnd() + => new VerifyCS.Test { TestCode = """ [|namespace N|] @@ -902,12 +841,10 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/59728")] - public async Task TestConvertToFileScopedWithNoMembersAndNoNewlineAtEnd() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithNoMembersAndNoNewlineAtEnd() + => new VerifyCS.Test { TestCode = """ [|namespace N|] @@ -923,12 +860,10 @@ namespace $$N; { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/59728")] - public async Task TestConvertToFileScopedPreserveNewlineAtEnd() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedPreserveNewlineAtEnd() + => new VerifyCS.Test { TestCode = """ [|namespace N|] @@ -951,12 +886,10 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/59728")] - public async Task TestConvertToFileScopedWithNoMembersPreserveNewlineAtEnd() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithNoMembersPreserveNewlineAtEnd() + => new VerifyCS.Test { TestCode = """ [|namespace N|] @@ -972,12 +905,10 @@ namespace $$N; { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/59728")] - public async Task TestConvertToFileScopedPPDirective1() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedPPDirective1() + => new VerifyCS.Test { TestCode = """ [|namespace Goo|] @@ -1002,12 +933,10 @@ class goobar { } { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/59728")] - public async Task TestConvertToFileScopedPPDirective2() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedPPDirective2() + => new VerifyCS.Test { TestCode = """ [|namespace Goo|] @@ -1034,12 +963,10 @@ class goobar { } { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/59728")] - public async Task TestConvertToFileScopedPPDirective3() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedPPDirective3() + => new VerifyCS.Test { TestCode = """ [|namespace Goo|] @@ -1063,12 +990,10 @@ class goobar { } { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/59728")] - public async Task TestConvertToFileScopedPPDirective4() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedPPDirective4() + => new VerifyCS.Test { TestCode = """ [|namespace Goo|] @@ -1093,12 +1018,10 @@ class goobar { } { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestInterpolatedRawString1() - { - await new VerifyCS.Test + public Task TestInterpolatedRawString1() + => new VerifyCS.Test { TestCode = """" [|namespace Microsoft.CodeAnalysis.SQLite.v2|] @@ -1165,12 +1088,10 @@ limit 1 { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestInterpolatedRawString2() - { - await new VerifyCS.Test + public Task TestInterpolatedRawString2() + => new VerifyCS.Test { TestCode = """" [|namespace Microsoft.CodeAnalysis.SQLite.v2|] @@ -1235,12 +1156,10 @@ limit 1 { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestInterpolatedRawString3() - { - await new VerifyCS.Test + public Task TestInterpolatedRawString3() + => new VerifyCS.Test { TestCode = """" [|namespace Microsoft.CodeAnalysis.SQLite.v2|] @@ -1307,12 +1226,10 @@ limit 1 { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestInterpolatedRawString4() - { - await new VerifyCS.Test + public Task TestInterpolatedRawString4() + => new VerifyCS.Test { TestCode = """" [|namespace Microsoft.CodeAnalysis.SQLite.v2|] @@ -1393,12 +1310,10 @@ limit 1 { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestInterpolatedRawString5() - { - await new VerifyCS.Test + public Task TestInterpolatedRawString5() + => new VerifyCS.Test { TestCode = """" [|namespace Microsoft.CodeAnalysis.SQLite.v2|] @@ -1465,12 +1380,10 @@ limit 1 { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestInterpolatedRawString6() - { - await new VerifyCS.Test + public Task TestInterpolatedRawString6() + => new VerifyCS.Test { TestCode = """" [|namespace Microsoft.CodeAnalysis.SQLite.v2|] @@ -1537,12 +1450,10 @@ limit 1 { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/74214")] - public async Task TestNotWithClassAfter() - { - await new VerifyCS.Test + public Task TestNotWithClassAfter() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1558,12 +1469,10 @@ class Outer { } { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/74214")] - public async Task TestNotWithClassBefore() - { - await new VerifyCS.Test + public Task TestNotWithClassBefore() + => new VerifyCS.Test { TestCode = """ class Outer { } @@ -1579,5 +1488,4 @@ class Inner { } { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionFixAllTests.cs b/src/Analyzers/CSharp/Tests/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionFixAllTests.cs index faa0fc8cbb921..251517af8d375 100644 --- a/src/Analyzers/CSharp/Tests/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionFixAllTests.cs +++ b/src/Analyzers/CSharp/Tests/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionFixAllTests.cs @@ -19,9 +19,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertSwitchStatementT public sealed class ConvertSwitchStatementToExpressionFixAllTests { [Fact] - public async Task TestNested_01() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestNested_01() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -166,12 +165,12 @@ int M(int i, int j) } } """); - } [Fact] - public async Task TestNested_02() - { - var input = """ + public Task TestNested_02() + => new VerifyCS.Test + { + TestCode = """ class Program { System.Func M(int i, int j) @@ -191,8 +190,8 @@ System.Func M(int i, int j) } } } - """; - var expected = """ + """, + FixedCode = """ class Program { System.Func M(int i, int j) @@ -213,20 +212,13 @@ System.Func M(int i, int j) }; } } - """; - - await new VerifyCS.Test - { - TestCode = input, - FixedCode = expected, + """, NumberOfFixAllIterations = 2, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37907")] - public async Task TestNested_03() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestNested_03() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -284,11 +276,9 @@ public bool ValueBoolean() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44572")] - public async Task TestImplicitConversion() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestImplicitConversion() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -329,5 +319,4 @@ public bool method(C c) } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionTests.cs b/src/Analyzers/CSharp/Tests/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionTests.cs index 5e16180266fe9..3ad175698b9e2 100644 --- a/src/Analyzers/CSharp/Tests/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionTests.cs +++ b/src/Analyzers/CSharp/Tests/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionTests.cs @@ -31,9 +31,8 @@ public void TestStandardProperty(AnalyzerProperty property) => VerifyCS.VerifyStandardProperty(property); [Fact] - public async Task TestReturn() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestReturn() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -68,12 +67,10 @@ int M(int i) } } """); - } [Fact] - public async Task TestReturnAndThrow() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestReturnAndThrow() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -108,12 +105,10 @@ int M(int i) } } """); - } [Fact] - public async Task TestAssignment_Array() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestAssignment_Array() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -156,7 +151,6 @@ void M(int i) } } """); - } [Fact] public async Task TestMissingOnDifferentIndexerArgs() @@ -327,9 +321,8 @@ void M(int i) } [Fact] - public async Task TestAllThrow() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestAllThrow() + => VerifyCS.VerifyCodeFixAsync( """ using System; class Program @@ -360,12 +353,10 @@ void M(int i) } } """); - } [Fact] - public async Task TestAssignment() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestAssignment() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -403,7 +394,6 @@ void M(int i) } } """); - } [Fact] public async Task TestMissingOnNextStatementMismatch() @@ -461,9 +451,8 @@ int M(int i) } [Fact] - public async Task TestAssignment_Compound() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestAssignment_Compound() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -502,12 +491,10 @@ void M(int i) } } """); - } [Fact] - public async Task TestAssignment_UseBeforeAssignment() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestAssignment_UseBeforeAssignment() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -548,7 +535,6 @@ void M(int i) } } """); - } [Fact] public async Task TestMissingOnMultiAssignment() @@ -607,9 +593,10 @@ void M(int i) } [Fact] - public async Task TestMissingOnMultiCaseSectionWithWhenClause_CSharp9() - { - var code = """ + public Task TestMissingOnMultiCaseSectionWithWhenClause_CSharp9() + => new VerifyCS.Test + { + TestCode = """ class Program { void M(int i) @@ -625,19 +612,15 @@ void M(int i) throw null; } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task TestOnMultiCaseSection_CSharp9() - { - var testCode = """ + public Task TestOnMultiCaseSection_CSharp9() + => new VerifyCS.Test + { + TestCode = """ class Program { void M(int i) @@ -653,8 +636,8 @@ void M(int i) throw null; } } - """; - var fixedCode = """ + """, + FixedCode = """ class Program { void M(int i) @@ -666,15 +649,9 @@ void M(int i) }; } } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - FixedCode = fixedCode, + """, LanguageVersion = CSharp9, }.RunAsync(); - } [Fact] public async Task TestMissingOnMultiCompoundAssignment() @@ -733,9 +710,8 @@ int M(int i) } [Fact] - public async Task TestTrivia_01() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestTrivia_01() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -779,12 +755,10 @@ int M(int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37873")] - public async Task TestTrivia_02() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestTrivia_02() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -823,12 +797,10 @@ static int GetValue(int input) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52258")] - public async Task TestTrivia_03() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestTrivia_03() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -857,13 +829,15 @@ int M(int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36086")] public async Task TestSeverity() { - var source = - """ + var analyzer = new ConvertSwitchStatementToExpressionDiagnosticAnalyzer(); + var descriptor = analyzer.SupportedDiagnostics.First(descriptor => descriptor.Id == IDEDiagnosticIds.ConvertSwitchStatementToExpressionDiagnosticId); + await new VerifyCS.Test + { + TestCode = """ class Program { int M(int i) @@ -881,13 +855,7 @@ int M(int i) } } } - """; - - var analyzer = new ConvertSwitchStatementToExpressionDiagnosticAnalyzer(); - var descriptor = analyzer.SupportedDiagnostics.First(descriptor => descriptor.Id == IDEDiagnosticIds.ConvertSwitchStatementToExpressionDiagnosticId); - await new VerifyCS.Test - { - TestCode = source, + """, ExpectedDiagnostics = { // Test0.cs(5,9): warning IDE0066: Use 'switch' expression @@ -901,9 +869,8 @@ int M(int i) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36995")] - public async Task TestAddParenthesesAroundBinaryExpression() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestAddParenthesesAroundBinaryExpression() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -938,12 +905,10 @@ void M(int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37947")] - public async Task TestMultiLabelWithDefault() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestMultiLabelWithDefault() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -977,7 +942,6 @@ public static string FromDay(DayOfWeek dayOfWeek) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37949")] public async Task TestMissingOnUseInNextStatement() @@ -1004,9 +968,8 @@ public static void Throw(int index) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36876")] - public async Task TestDeclarationInOuterScope() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestDeclarationInOuterScope() + => VerifyCS.VerifyCodeFixAsync( """ using System; using System.IO; @@ -1087,7 +1050,6 @@ public static void Test() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37872")] public async Task TestMissingFixOnDirectives() @@ -1124,21 +1086,18 @@ static int GetValue(int input) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37872")] public async Task TestMissingFixAllOnDirectives() { - var code = """ + var fixedCode = """ class Program { static void Main() { } static int GetValue(int input) { - [|switch|] (input) + return input switch { - case 1: - return 42; - default: - return 80; - } - + 1 => 42, + _ => 80, + }; [|switch|] (input) { case 1: @@ -1157,18 +1116,24 @@ static int GetValue(int input) } } """; - var fixedCode = """ + + await new VerifyCS.Test + { + TestCode = """ class Program { static void Main() { } static int GetValue(int input) { - return input switch + [|switch|] (input) { - 1 => 42, - _ => 80, - }; + case 1: + return 42; + default: + return 80; + } + [|switch|] (input) { case 1: @@ -1186,11 +1151,7 @@ static int GetValue(int input) } } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, FixedState = { Sources = { fixedCode }, @@ -1200,9 +1161,8 @@ static int GetValue(int input) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37950")] - public async Task TestShouldNotCastNullOnNullableValueType_ReturnStatement() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestShouldNotCastNullOnNullableValueType_ReturnStatement() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -1231,12 +1191,10 @@ class Program } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37950")] - public async Task TestShouldNotCastNullOnNullableValueType_Assignment() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestShouldNotCastNullOnNullableValueType_Assignment() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -1266,13 +1224,12 @@ public static void Test(string name) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38771")] - public async Task TestExplicitDeclaration_Interfaces() - { - var input = - """ + public Task TestExplicitDeclaration_Interfaces() + => new VerifyCS.Test + { + TestCode = """ using System; class Program @@ -1301,9 +1258,8 @@ public static void Test(string name) } } } - """; - var expected = - """ + """, + FixedCode = """ using System; class Program @@ -1326,24 +1282,18 @@ public static void Test(string name) }; } } - """; - - await new VerifyCS.Test - { - TestCode = input, - FixedCode = expected, + """, Options = { { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption2.Silent }, }, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38771")] - public async Task TestExplicitDeclaration_Interfaces2() - { - var input = - """ + public Task TestExplicitDeclaration_Interfaces2() + => new VerifyCS.Test + { + TestCode = """ using System; class Program @@ -1372,9 +1322,8 @@ public static void Test(string name) } } } - """; - var expected = - """ + """, + FixedCode = """ using System; class Program @@ -1397,24 +1346,18 @@ public static void Test(string name) }; } } - """; - - await new VerifyCS.Test - { - TestCode = input, - FixedCode = expected, + """, Options = { { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption2.Silent }, }, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38771")] - public async Task TestExplicitDeclaration_Interfaces3() - { - var input = - """ + public Task TestExplicitDeclaration_Interfaces3() + => new VerifyCS.Test + { + TestCode = """ using System; class Program @@ -1443,9 +1386,8 @@ public static void Test(string name) } } } - """; - var expected = - """ + """, + FixedCode = """ using System; class Program @@ -1468,24 +1410,18 @@ public static void Test(string name) }; } } - """; - - await new VerifyCS.Test - { - TestCode = input, - FixedCode = expected, + """, Options = { { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption2.Silent }, }, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38771")] - public async Task TestExplicitDeclaration_ClassInheritance() - { - var input = - """ + public Task TestExplicitDeclaration_ClassInheritance() + => new VerifyCS.Test + { + TestCode = """ using System; class Program @@ -1518,9 +1454,8 @@ public static void Test(string name) } } } - """; - var expected = - """ + """, + FixedCode = """ using System; class Program @@ -1547,24 +1482,18 @@ public static void Test(string name) }; } } - """; - - await new VerifyCS.Test - { - TestCode = input, - FixedCode = expected, + """, Options = { { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption2.Silent }, }, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38771")] - public async Task TestExplicitDeclaration_ClassInheritance2() - { - var input = - """ + public Task TestExplicitDeclaration_ClassInheritance2() + => new VerifyCS.Test + { + TestCode = """ using System; class Program @@ -1593,9 +1522,8 @@ public static void Test(string name) } } } - """; - var expected = - """ + """, + FixedCode = """ using System; class Program @@ -1618,24 +1546,18 @@ public static void Test(string name) }; } } - """; - - await new VerifyCS.Test - { - TestCode = input, - FixedCode = expected, + """, Options = { { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption2.Silent }, }, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38771")] - public async Task TestImplicitDeclaration_ClassInheritance() - { - var input = - """ + public Task TestImplicitDeclaration_ClassInheritance() + => new VerifyCS.Test + { + TestCode = """ using System; class Program @@ -1664,9 +1586,8 @@ public static void Test(string name) } } } - """; - var expected = - """ + """, + FixedCode = """ using System; class Program @@ -1689,24 +1610,18 @@ public static void Test(string name) }; } } - """; - - await new VerifyCS.Test - { - TestCode = input, - FixedCode = expected, + """, Options = { { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption2.Silent }, }, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38771")] - public async Task TestImplicitDeclaration_ClassInheritance2() - { - var input = - """ + public Task TestImplicitDeclaration_ClassInheritance2() + => new VerifyCS.Test + { + TestCode = """ using System; class Program @@ -1735,9 +1650,8 @@ public static void Test(string name) } } } - """; - var expected = - """ + """, + FixedCode = """ using System; class Program @@ -1760,24 +1674,18 @@ public static void Test(string name) }; } } - """; - - await new VerifyCS.Test - { - TestCode = input, - FixedCode = expected, + """, Options = { { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption2.Silent }, }, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38771")] - public async Task TestExplicitDeclaration_AllCasesDefaultLiteral() - { - var input = - """ + public Task TestExplicitDeclaration_AllCasesDefaultLiteral() + => new VerifyCS.Test + { + TestCode = """ class Program { public static void Test() @@ -1795,9 +1703,8 @@ public static void Test() } } } - """; - var expected = - """ + """, + FixedCode = """ class Program { public static void Test() @@ -1810,24 +1717,18 @@ public static void Test() }; } } - """; - - await new VerifyCS.Test - { - TestCode = input, - FixedCode = expected, + """, Options = { { CSharpCodeStyleOptions.VarForBuiltInTypes, true, NotificationOption2.Silent }, }, }.RunAsync(); - } [Fact] - public async Task TestExplicitDeclaration_MixedDefaultLiteralDefaultParameter() - { - var input = - """ + public Task TestExplicitDeclaration_MixedDefaultLiteralDefaultParameter() + => new VerifyCS.Test + { + TestCode = """ class Program { public static void Test() @@ -1845,8 +1746,8 @@ public static void Test() } } } - """; - var expected = """ + """, + FixedCode = """ class Program { public static void Test() @@ -1859,24 +1760,18 @@ public static void Test() }; } } - """; - - await new VerifyCS.Test - { - TestCode = input, - FixedCode = expected, + """, Options = { { CSharpCodeStyleOptions.VarForBuiltInTypes, true, NotificationOption2.Silent }, }, }.RunAsync(); - } [Fact] - public async Task TestImplicitDeclaration_AllCasesDefaultParameter() - { - var input = - """ + public Task TestImplicitDeclaration_AllCasesDefaultParameter() + => new VerifyCS.Test + { + TestCode = """ class Program { public static void Test() @@ -1894,9 +1789,8 @@ public static void Test() } } } - """; - var expected = - """ + """, + FixedCode = """ class Program { public static void Test() @@ -1909,24 +1803,18 @@ public static void Test() }; } } - """; - - await new VerifyCS.Test - { - TestCode = input, - FixedCode = expected, + """, Options = { { CSharpCodeStyleOptions.VarForBuiltInTypes, true, NotificationOption2.Silent }, }, }.RunAsync(); - } [Fact] - public async Task TestExplicitDeclaration_AllCasesDefaultParameter() - { - var input = - """ + public Task TestExplicitDeclaration_AllCasesDefaultParameter() + => new VerifyCS.Test + { + TestCode = """ class Program { public static void Test() @@ -1944,9 +1832,8 @@ public static void Test() } } } - """; - var expected = - """ + """, + FixedCode = """ class Program { public static void Test() @@ -1959,24 +1846,18 @@ public static void Test() }; } } - """; - - await new VerifyCS.Test - { - TestCode = input, - FixedCode = expected, + """, Options = { { CSharpCodeStyleOptions.VarForBuiltInTypes, false, NotificationOption2.Silent }, }, }.RunAsync(); - } [Fact] - public async Task TestExplicitDeclaration_DeclarationTypeDifferentFromAllCaseTypes() - { - var input = - """ + public Task TestExplicitDeclaration_DeclarationTypeDifferentFromAllCaseTypes() + => new VerifyCS.Test + { + TestCode = """ class Program { public static void Test() @@ -1994,9 +1875,8 @@ public static void Test() } } } - """; - var expected = - """ + """, + FixedCode = """ class Program { public static void Test() @@ -2009,18 +1889,12 @@ public static void Test() }; } } - """; - - await new VerifyCS.Test - { - TestCode = input, - FixedCode = expected, + """, Options = { { CSharpCodeStyleOptions.VarForBuiltInTypes, true, NotificationOption2.Silent }, }, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40198")] public async Task TestNotWithRefReturns() @@ -2093,9 +1967,8 @@ static ref int GetRef(int[] mem, int addr, int mode) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40198")] - public async Task TestWithRefInsideConditionalAssignment() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestWithRefInsideConditionalAssignment() + => VerifyCS.VerifyCodeFixAsync( """ using System; class Program @@ -2126,7 +1999,6 @@ static void GetRef(int[] mem, int addr, int mode) } } """); - } [Fact] public async Task TopLevelStatement() @@ -2141,17 +2013,6 @@ public async Task TopLevelStatement() return 7; } """; - - var fixedSource = """ - int i = 0; - return i switch - { - 1 => 4, - _ => 7, - }; - - """; - var test = new VerifyCS.Test { TestState = @@ -2159,7 +2020,15 @@ public async Task TopLevelStatement() OutputKind = OutputKind.ConsoleApplication, Sources = { source }, }, - FixedCode = fixedSource, + FixedCode = """ + int i = 0; + return i switch + { + 1 => 4, + _ => 7, + }; + + """, LanguageVersion = LanguageVersion.CSharp9, }; @@ -2184,8 +2053,13 @@ public async Task TopLevelStatement_FollowedWithThrow() } throw null; """; - - var fixedSource = """ + var test = new VerifyCS.Test + { + TestState = { + Sources = { source }, + OutputKind = OutputKind.ConsoleApplication, + }, + FixedCode = """ int i = 0; int j; j = i switch @@ -2195,15 +2069,7 @@ public async Task TopLevelStatement_FollowedWithThrow() _ => throw null, }; - """; - - var test = new VerifyCS.Test - { - TestState = { - Sources = { source }, - OutputKind = OutputKind.ConsoleApplication, - }, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp9, }; @@ -2211,9 +2077,10 @@ public async Task TopLevelStatement_FollowedWithThrow() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48006")] - public async Task TestOnMultiCaseSection_String_CSharp9() - { - var testCode = """ + public Task TestOnMultiCaseSection_String_CSharp9() + => new VerifyCS.Test + { + TestCode = """ class Program { bool M(string s) @@ -2229,8 +2096,8 @@ bool M(string s) } } } - """; - var fixedCode = """ + """, + FixedCode = """ class Program { bool M(string s) @@ -2242,20 +2109,13 @@ bool M(string s) }; } } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - FixedCode = fixedCode, + """, LanguageVersion = CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49788")] - public async Task TestParenthesizedExpression1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestParenthesizedExpression1() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -2280,12 +2140,10 @@ int M(object i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49788")] - public async Task TestParenthesizedExpression2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestParenthesizedExpression2() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -2310,12 +2168,10 @@ int M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58636")] - public async Task TestRuntimeTypeConversion_Assignment1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestRuntimeTypeConversion_Assignment1() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -2351,12 +2207,10 @@ void M(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58636")] - public async Task TestRuntimeTypeConversion_Assignment2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestRuntimeTypeConversion_Assignment2() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -2396,12 +2250,10 @@ void M(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58636")] - public async Task TestRuntimeTypeConversion_Return1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestRuntimeTypeConversion_Return1() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -2433,12 +2285,10 @@ object M(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58636")] - public async Task TestRuntimeTypeConversion_Return2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestRuntimeTypeConversion_Return2() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -2473,12 +2323,10 @@ object M(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61278")] - public async Task TestLeadingTrivia1() - { - await new VerifyCS.Test + public Task TestLeadingTrivia1() + => new VerifyCS.Test { TestCode = """ @@ -2529,12 +2377,10 @@ public static int RefactorReplacementDemoMethod(int argument) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61278")] - public async Task TestLeadingTrivia2() - { - await new VerifyCS.Test + public Task TestLeadingTrivia2() + => new VerifyCS.Test { TestCode = """ @@ -2586,12 +2432,10 @@ public static int RefactorReplacementDemoMethod(int argument) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/77081")] - public async Task TestTupleSwitch() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestTupleSwitch() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -2625,5 +2469,4 @@ bool M(int i, string j) } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/ConvertToAsync/ConvertToAsyncTests.cs b/src/Analyzers/CSharp/Tests/ConvertToAsync/ConvertToAsyncTests.cs index b7f2be747a64c..63007c394efc8 100644 --- a/src/Analyzers/CSharp/Tests/ConvertToAsync/ConvertToAsyncTests.cs +++ b/src/Analyzers/CSharp/Tests/ConvertToAsync/ConvertToAsyncTests.cs @@ -18,10 +18,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertToAsync; public sealed class ConvertToAsyncTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsChangeToAsync)] - public async Task CantAwaitAsyncVoid() - { - var initial = - """ + public Task CantAwaitAsyncVoid() + => VerifyCS.VerifyCodeFixAsync(""" using System.Threading.Tasks; class Program @@ -35,10 +33,7 @@ async void gt() { } } - """; - - var expected = - """ + """, """ using System.Threading.Tasks; class Program @@ -54,7 +49,5 @@ async Task rtrt() { } } - """; - await VerifyCS.VerifyCodeFixAsync(initial, expected); - } + """); } diff --git a/src/Analyzers/CSharp/Tests/ConvertToRecord/ConvertToRecordCodeFixTests.cs b/src/Analyzers/CSharp/Tests/ConvertToRecord/ConvertToRecordCodeFixTests.cs index e563844bd434d..ed408bcf83780 100644 --- a/src/Analyzers/CSharp/Tests/ConvertToRecord/ConvertToRecordCodeFixTests.cs +++ b/src/Analyzers/CSharp/Tests/ConvertToRecord/ConvertToRecordCodeFixTests.cs @@ -19,7 +19,7 @@ public sealed class ConvertToRecordCodeFixTests [Fact] public async Task TestMovePropertySimpleRecordInheritance_CodeFix() { - var initialMarkup = """ + await TestCodeFixAsync(""" namespace N { public record B @@ -32,8 +32,7 @@ public class C : [|B|] public int P { get; init; } } } - """; - var changedMarkup = """ + """, """ namespace N { public record B @@ -43,14 +42,13 @@ public record B public record C(int P) : B; } - """; - await TestCodeFixAsync(initialMarkup, changedMarkup).ConfigureAwait(false); + """).ConfigureAwait(false); } [Fact] public async Task TestMovePropertyPositionalParameterRecordInheritance_CodeFix() { - var initialMarkup = """ + await TestCodeFixAsync(""" namespace N { public record B(int Foo, int Bar); @@ -60,22 +58,20 @@ public class {|CS1729:C|} : [|B|] public int P { get; init; } } } - """; - var changedMarkup = """ + """, """ namespace N { public record B(int Foo, int Bar); public record C(int Foo, int Bar, int P) : B(Foo, Bar); } - """; - await TestCodeFixAsync(initialMarkup, changedMarkup).ConfigureAwait(false); + """).ConfigureAwait(false); } [Fact] public async Task TestMovePropertyPositionalParameterRecordInheritanceWithComments_CodeFix() { - var initialMarkup = """ + await TestCodeFixAsync(""" namespace N { /// B @@ -90,8 +86,7 @@ public class {|CS1729:C|} : [|B|] public int P { get; init; } } } - """; - var changedMarkup = """ + """, """ namespace N { /// B @@ -105,14 +100,13 @@ public record B(int Foo, int Bar); /// P can be initialized public record C(int Foo, int Bar, int P) : B(Foo, Bar); } - """; - await TestCodeFixAsync(initialMarkup, changedMarkup).ConfigureAwait(false); + """).ConfigureAwait(false); } [Fact] public async Task TestMovePropertyAndReorderWithPositionalParameterRecordInheritance_CodeFix() { - var initialMarkup = """ + await TestCodeFixAsync(""" namespace N { public record B(int Foo, int Bar); @@ -129,16 +123,14 @@ public class C : [|B|] } } } - """; - var changedMarkup = """ + """, """ namespace N { public record B(int Foo, int Bar); public record C(int P, int Bar, int Foo) : B(Foo, Bar); } - """; - await TestCodeFixAsync(initialMarkup, changedMarkup).ConfigureAwait(false); + """).ConfigureAwait(false); } private sealed class CodeFixTest : CSharpCodeFixVerifier.Test diff --git a/src/Analyzers/CSharp/Tests/ConvertTypeOfToNameOf/ConvertTypeOfToNameOfFixAllTests.cs b/src/Analyzers/CSharp/Tests/ConvertTypeOfToNameOf/ConvertTypeOfToNameOfFixAllTests.cs index b8a31b9544564..298a2a195c4c0 100644 --- a/src/Analyzers/CSharp/Tests/ConvertTypeOfToNameOf/ConvertTypeOfToNameOfFixAllTests.cs +++ b/src/Analyzers/CSharp/Tests/ConvertTypeOfToNameOf/ConvertTypeOfToNameOfFixAllTests.cs @@ -18,9 +18,8 @@ public sealed partial class ConvertTypeOfToNameOfTests [Fact] [Trait(Traits.Feature, Traits.Features.ConvertTypeOfToNameOf)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task FixAllDocumentBasic() - { - var input = """ + public Task FixAllDocumentBasic() + => VerifyCS.VerifyCodeFixAsync(""" class Test { static void Main() @@ -30,9 +29,7 @@ static void Main() var typeName3 = [|typeof(Test).Name|]; } } - """; - - var expected = """ + """, """ class Test { static void Main() @@ -42,17 +39,13 @@ static void Main() var typeName3 = nameof(Test); } } - """; - - await VerifyCS.VerifyCodeFixAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.ConvertTypeOfToNameOf)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task FixAllDocumentVariedSingleLine() - { - var input = """ + public Task FixAllDocumentVariedSingleLine() + => VerifyCS.VerifyCodeFixAsync(""" class Test { static void Main() @@ -60,9 +53,7 @@ static void Main() var typeName1 = [|typeof(Test).Name|]; var typeName2 = [|typeof(int).Name|]; var typeName3 = [|typeof(System.String).Name|]; } } - """; - - var expected = """ + """, """ class Test { static void Main() @@ -70,17 +61,13 @@ static void Main() var typeName1 = nameof(Test); var typeName2 = nameof(System.Int32); var typeName3 = nameof(System.String); } } - """; - - await VerifyCS.VerifyCodeFixAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.ConvertTypeOfToNameOf)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task FixAllDocumentVariedWithUsing() - { - var input = """ + public Task FixAllDocumentVariedWithUsing() + => VerifyCS.VerifyCodeFixAsync(""" using System; class Test @@ -93,9 +80,7 @@ static void Main() var typeName4 = [|typeof(System.Double).Name|]; } } - """; - - var expected = """ + """, """ using System; class Test @@ -108,17 +93,13 @@ static void Main() var typeName4 = nameof(Double); } } - """; - - await VerifyCS.VerifyCodeFixAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.ConvertTypeOfToNameOf)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task FixAllProject() - { - await new VerifyCS.Test + public Task FixAllProject() + => new VerifyCS.Test { TestState = { @@ -183,14 +164,12 @@ static void Main() } } }.RunAsync(); - } [Fact] [Trait(Traits.Feature, Traits.Features.ConvertTypeOfToNameOf)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task FixAllSolution() - { - await new VerifyCS.Test + public Task FixAllSolution() + => new VerifyCS.Test { TestState = { @@ -291,5 +270,4 @@ static void Main() } } }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/ConvertTypeOfToNameOf/ConvertTypeOfToNameOfTests.cs b/src/Analyzers/CSharp/Tests/ConvertTypeOfToNameOf/ConvertTypeOfToNameOfTests.cs index a451af09bd7f4..975c8811ea345 100644 --- a/src/Analyzers/CSharp/Tests/ConvertTypeOfToNameOf/ConvertTypeOfToNameOfTests.cs +++ b/src/Analyzers/CSharp/Tests/ConvertTypeOfToNameOf/ConvertTypeOfToNameOfTests.cs @@ -21,9 +21,8 @@ public sealed partial class ConvertTypeOfToNameOfTests private static readonly LanguageVersion CSharp14 = LanguageVersion.Preview; [Fact] - public async Task BasicType() - { - var text = """ + public Task BasicType() + => VerifyCS.VerifyCodeFixAsync(""" class Test { void Method() @@ -31,8 +30,7 @@ void Method() var typeName = [|typeof(Test).Name|]; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -40,14 +38,11 @@ void Method() var typeName = nameof(Test); } } - """; - await VerifyCS.VerifyCodeFixAsync(text, expected); - } + """); [Fact] - public async Task ClassLibraryType() - { - var text = """ + public Task ClassLibraryType() + => VerifyCS.VerifyCodeFixAsync(""" class Test { void Method() @@ -55,8 +50,7 @@ void Method() var typeName = [|typeof(System.String).Name|]; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -64,14 +58,11 @@ void Method() var typeName = nameof(System.String); } } - """; - await VerifyCS.VerifyCodeFixAsync(text, expected); - } + """); [Fact] - public async Task ClassLibraryTypeWithUsing() - { - var text = """ + public Task ClassLibraryTypeWithUsing() + => VerifyCS.VerifyCodeFixAsync(""" using System; class Test @@ -81,8 +72,7 @@ void Method() var typeName = [|typeof(String).Name|]; } } - """; - var expected = """ + """, """ using System; class Test @@ -92,14 +82,11 @@ void Method() var typeName = nameof(String); } } - """; - await VerifyCS.VerifyCodeFixAsync(text, expected); - } + """); [Fact] - public async Task NestedCall() - { - var text = """ + public Task NestedCall() + => VerifyCS.VerifyCodeFixAsync(""" using System; class Test @@ -113,8 +100,7 @@ int Foo(String typeName) { return 0; } } - """; - var expected = """ + """, """ using System; class Test @@ -128,9 +114,7 @@ int Foo(String typeName) { return 0; } } - """; - await VerifyCS.VerifyCodeFixAsync(text, expected); - } + """); [Fact] public async Task NotOnVariableContainingType() @@ -151,9 +135,8 @@ void Method() } [Fact] - public async Task PrimitiveType() - { - var text = """ + public Task PrimitiveType() + => VerifyCS.VerifyCodeFixAsync(""" class Test { void Method() @@ -161,8 +144,7 @@ void Method() var typeName = [|typeof(int).Name|]; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -170,14 +152,11 @@ void Method() var typeName = nameof(System.Int32); } } - """; - await VerifyCS.VerifyCodeFixAsync(text, expected); - } + """); [Fact] - public async Task PrimitiveTypeWithUsing() - { - var text = """ + public Task PrimitiveTypeWithUsing() + => VerifyCS.VerifyCodeFixAsync(""" using System; class Test @@ -187,8 +166,7 @@ void Method() var typeName = [|typeof(int).Name|]; } } - """; - var expected = """ + """, """ using System; class Test @@ -198,9 +176,7 @@ void Method() var typeName = nameof(Int32); } } - """; - await VerifyCS.VerifyCodeFixAsync(text, expected); - } + """); [Fact] public async Task NotOnGenericType() @@ -235,9 +211,8 @@ void Method() } [Fact] - public async Task GenericType_CSharp13() - { - await new VerifyCS.Test + public Task GenericType_CSharp13() + => new VerifyCS.Test { TestCode = """ class Test @@ -253,12 +228,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp13, }.RunAsync(); - } [Fact] - public async Task GenericType_CSharp14() - { - await new VerifyCS.Test + public Task GenericType_CSharp14() + => new VerifyCS.Test { TestCode = """ class Test @@ -274,12 +247,10 @@ void M() """, LanguageVersion = CSharp14, }.RunAsync(); - } [Fact] - public async Task UnboundGenericType_CSharp13() - { - await new VerifyCS.Test + public Task UnboundGenericType_CSharp13() + => new VerifyCS.Test { TestCode = """ class Test @@ -295,12 +266,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp13, }.RunAsync(); - } [Fact] - public async Task UnboundGenericType_CSharp14() - { - await new VerifyCS.Test + public Task UnboundGenericType_CSharp14() + => new VerifyCS.Test { TestCode = """ class Test @@ -316,12 +285,10 @@ void M() """, LanguageVersion = CSharp14, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47129")] - public async Task NestedInGenericType() - { - var text = """ + public Task NestedInGenericType() + => VerifyCS.VerifyCodeFixAsync(""" class Test { class Goo @@ -335,8 +302,7 @@ void M() } } } - """; - var expected = """ + """, """ class Test { class Goo @@ -350,14 +316,11 @@ void M() } } } - """; - await VerifyCS.VerifyCodeFixAsync(text, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47129")] - public async Task NestedInGenericType2_CSharp13() - { - await new VerifyCS.Test + public Task NestedInGenericType2_CSharp13() + => new VerifyCS.Test { TestCode = """ using System; @@ -385,12 +348,10 @@ public void M() """, LanguageVersion = LanguageVersion.CSharp13, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47129")] - public async Task NestedInGenericType2_CSharp14() - { - await new VerifyCS.Test + public Task NestedInGenericType2_CSharp14() + => new VerifyCS.Test { TestCode = """ using System; @@ -418,12 +379,10 @@ public void M() """, LanguageVersion = CSharp14, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47129")] - public async Task NestedInGenericType_UnboundTypeof_CSharp13() - { - await new VerifyCS.Test + public Task NestedInGenericType_UnboundTypeof_CSharp13() + => new VerifyCS.Test { TestCode = """ using System; @@ -439,12 +398,10 @@ public void M() """, LanguageVersion = LanguageVersion.CSharp13, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47129")] - public async Task NestedInGenericType_UnboundTypeof_CSharp14() - { - await new VerifyCS.Test + public Task NestedInGenericType_UnboundTypeof_CSharp14() + => new VerifyCS.Test { TestCode = """ using System; @@ -472,7 +429,6 @@ public void M() """, LanguageVersion = CSharp14, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/54233")] public async Task NotOnVoid() @@ -490,9 +446,8 @@ void M() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47128")] - public async Task TestNint() - { - await new VerifyCS.Test + public Task TestNint() + => new VerifyCS.Test { TestCode = """ using System; @@ -518,5 +473,4 @@ void M() """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/DisambiguateSameVariable/DisambiguateSameVariableTests.cs b/src/Analyzers/CSharp/Tests/DisambiguateSameVariable/DisambiguateSameVariableTests.cs index 09c2325becd73..3e1aa6e6c2e11 100644 --- a/src/Analyzers/CSharp/Tests/DisambiguateSameVariable/DisambiguateSameVariableTests.cs +++ b/src/Analyzers/CSharp/Tests/DisambiguateSameVariable/DisambiguateSameVariableTests.cs @@ -68,9 +68,8 @@ void M() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28290")] - public async Task TestParamToParamWithSameNamedField() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestParamToParamWithSameNamedField() + => VerifyCS.VerifyCodeFixAsync(""" class C { int a; @@ -89,7 +88,6 @@ void M(int a) } } """); - } [Fact] public async Task TestFieldToFieldWithNonMatchingField() @@ -109,9 +107,8 @@ void M() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28290")] - public async Task TestParamToParamWithUnderscoreNamedField() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestParamToParamWithUnderscoreNamedField() + => VerifyCS.VerifyCodeFixAsync(""" class C { int _a; @@ -130,12 +127,10 @@ void M(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28290")] - public async Task TestParamToParamWithCapitalizedField() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestParamToParamWithCapitalizedField() + => VerifyCS.VerifyCodeFixAsync(""" class C { int A; @@ -154,12 +149,10 @@ void M(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28290")] - public async Task TestParamToParamWithProperty() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestParamToParamWithProperty() + => VerifyCS.VerifyCodeFixAsync(""" class C { int A { get; set; } @@ -178,12 +171,10 @@ void M(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28290")] - public async Task TestParamToParamWithReadOnlyFieldInConstructor() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestParamToParamWithReadOnlyFieldInConstructor() + => VerifyCS.VerifyCodeFixAsync(""" class C { readonly int a; @@ -202,13 +193,10 @@ public C(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28290")] - public async Task TestParamToParamWithReadOnlyFieldOutsideOfConstructor() - { - // Not legal, but is at least something they might want. - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestParamToParamWithReadOnlyFieldOutsideOfConstructor() + => VerifyCS.VerifyCodeFixAsync(""" class C { readonly int a; @@ -227,12 +215,10 @@ void M(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28290")] - public async Task TestParamToParamWithAccessibleFieldInBaseType() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestParamToParamWithAccessibleFieldInBaseType() + => VerifyCS.VerifyCodeFixAsync(""" class Base { protected int a; @@ -259,7 +245,6 @@ public C(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28290")] public async Task TestParamToParamNotWithInaccessibleFieldInBaseType() @@ -300,9 +285,8 @@ public C(int a) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28290")] - public async Task TestParamToParamCompareWithSameNamedField() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestParamToParamCompareWithSameNamedField() + => VerifyCS.VerifyCodeFixAsync(""" class C { int a; @@ -325,12 +309,10 @@ void M(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28290")] - public async Task TestFixAll1() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestFixAll1() + => VerifyCS.VerifyCodeFixAsync(""" class C { int a; @@ -351,12 +333,10 @@ void M(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28290")] - public async Task TestFieldToFieldWithPropAvailableOffOfThis() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestFieldToFieldWithPropAvailableOffOfThis() + => VerifyCS.VerifyCodeFixAsync(""" class C { int a; @@ -377,12 +357,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28290")] - public async Task TestFieldToFieldWithPropAvailableOffOfOtherInstance() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestFieldToFieldWithPropAvailableOffOfOtherInstance() + => VerifyCS.VerifyCodeFixAsync(""" class C { int a; @@ -403,5 +381,4 @@ void M(C c) } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/DocumentationComments/AddDocCommentNodesCodeFixProviderTests.cs b/src/Analyzers/CSharp/Tests/DocumentationComments/AddDocCommentNodesCodeFixProviderTests.cs index 8dda228d0c473..d06dda37aae80 100644 --- a/src/Analyzers/CSharp/Tests/DocumentationComments/AddDocCommentNodesCodeFixProviderTests.cs +++ b/src/Analyzers/CSharp/Tests/DocumentationComments/AddDocCommentNodesCodeFixProviderTests.cs @@ -35,10 +35,8 @@ private async Task TestAsync(string initial, string expected) } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddDocCommentNodes)] - public async Task AddsParamTag_NoNodesBefore() - { - var initial = - """ + public Task AddsParamTag_NoNodesBefore() + => TestAsync(""" class Program { /// @@ -47,10 +45,7 @@ class Program /// public void Fizz(int [|i|], int j, int k) {} } - """; - - var expected = - """ + """, """ class Program { /// @@ -61,15 +56,11 @@ class Program /// public void Fizz(int i, int j, int k) {} } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddDocCommentNodes)] - public async Task AddsParamTag_NoNodesAfter() - { - var initial = - """ + public Task AddsParamTag_NoNodesAfter() + => TestAsync(""" class Program { /// @@ -78,10 +69,7 @@ class Program /// public void Fizz(int i, int j, int [|k|]) {} } - """; - - var expected = - """ + """, """ class Program { /// @@ -92,15 +80,11 @@ class Program /// public void Fizz(int i, int j, int k) {} } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddDocCommentNodes)] - public async Task AddsParamTag_NodesBeforeAndAfter() - { - var initial = - """ + public Task AddsParamTag_NodesBeforeAndAfter() + => TestAsync(""" class Program { /// @@ -110,10 +94,7 @@ class Program /// public void Fizz(int i, int [|j|], int k) {} } - """; - - var expected = - """ + """, """ class Program { /// @@ -124,15 +105,11 @@ class Program /// public void Fizz(int i, int j, int k) {} } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddDocCommentNodes)] - public async Task AddsParamTag_NodesBeforeAndAfter_RawTextInComment() - { - var initial = - """ + public Task AddsParamTag_NodesBeforeAndAfter_RawTextInComment() + => TestAsync(""" class Program { /// @@ -143,10 +120,7 @@ class Program /// public void Fizz(int i, int [|j|], int k) {} } - """; - - var expected = - """ + """, """ class Program { /// @@ -158,15 +132,11 @@ class Program /// public void Fizz(int i, int j, int k) {} } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddDocCommentNodes)] - public async Task AddsParamTag_NodesBeforeAndAfter_WithContent() - { - var initial = - """ + public Task AddsParamTag_NodesBeforeAndAfter_WithContent() + => TestAsync(""" class Program { /// @@ -176,10 +146,7 @@ class Program /// Parameter does something else public void Fizz(int i, int [|j|], int k) {} } - """; - - var expected = - """ + """, """ class Program { /// @@ -190,15 +157,11 @@ class Program /// Parameter does something else public void Fizz(int i, int j, int k) {} } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddDocCommentNodes)] - public async Task AddsParamTag_NestedInSummaryTag() - { - var initial = - """ + public Task AddsParamTag_NestedInSummaryTag() + => TestAsync(""" class Program { /// @@ -206,10 +169,7 @@ class Program /// public void Fizz(int i, int j, int [|k|]) {} } - """; - - var expected = - """ + """, """ class Program { /// @@ -219,24 +179,17 @@ class Program /// public void Fizz(int i, int j, int k) {} } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddDocCommentNodes)] - public async Task AddsParamTag_BeforeNode_EverythingOnOneLine() - { - var initial = - """ + public Task AddsParamTag_BeforeNode_EverythingOnOneLine() + => TestAsync(""" class Program { /// public void Fizz(int [|i|], int j, int k) {} } - """; - - var expected = - """ + """, """ class Program { /// @@ -244,24 +197,17 @@ class Program /// public void Fizz(int i, int j, int k) {} } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddDocCommentNodes)] - public async Task AddsParamTag_AfterNode_EverythingOnOneLine() - { - var initial = - """ + public Task AddsParamTag_AfterNode_EverythingOnOneLine() + => TestAsync(""" class Program { /// public void Fizz(int i, int j, int [|k|]) {} } - """; - - var expected = - """ + """, """ class Program { /// @@ -269,24 +215,17 @@ class Program /// public void Fizz(int i, int j, int k) {} } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddDocCommentNodes)] - public async Task AddsParamTag_BeforeNode_JustParamNode() - { - var initial = - """ + public Task AddsParamTag_BeforeNode_JustParamNode() + => TestAsync(""" class Program { /// public void Fizz(int [|i|], int j, int k) {} } - """; - - var expected = - """ + """, """ class Program { /// @@ -294,24 +233,17 @@ class Program /// public void Fizz(int i, int j, int k) {} } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddDocCommentNodes)] - public async Task AddsParamTag_AfterNode_JustParamNode() - { - var initial = - """ + public Task AddsParamTag_AfterNode_JustParamNode() + => TestAsync(""" class Program { /// public void Fizz(int i, int j, int [|k|]) {} } - """; - - var expected = - """ + """, """ class Program { /// @@ -319,15 +251,11 @@ class Program /// public void Fizz(int i, int j, int k) {} } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddDocCommentNodes)] - public async Task AddsParamTag_MultipleDocComments() - { - var initial = - """ + public Task AddsParamTag_MultipleDocComments() + => TestAsync(""" class Program { /// @@ -338,10 +266,7 @@ class Program /// public void Fizz(int [|i|], int j, int k) {} } - """; - - var expected = - """ + """, """ class Program { /// @@ -354,15 +279,11 @@ class Program /// public void Fizz(int i, int j, int k) {} } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddDocCommentNodes)] - public async Task AddsParamTag_Ctor() - { - var initial = - """ + public Task AddsParamTag_Ctor() + => TestAsync(""" class Program { /// @@ -371,10 +292,7 @@ class Program /// public Program(int [|i|], int j, int k) {} } - """; - - var expected = - """ + """, """ class Program { /// @@ -385,15 +303,11 @@ class Program /// public Program(int i, int j, int k) {} } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddDocCommentNodes)] - public async Task AddsParamTag_Delegate() - { - var initial = - """ + public Task AddsParamTag_Delegate() + => TestAsync(""" class Program { /// @@ -402,10 +316,7 @@ class Program /// public delegate int Goo(int [|i|], int j, int k); } - """; - - var expected = - """ + """, """ class Program { /// @@ -416,15 +327,11 @@ class Program /// public delegate int Goo(int [|i|], int j, int k); } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddDocCommentNodes)] - public async Task AddsParamTag_Operator() - { - var initial = - """ + public Task AddsParamTag_Operator() + => TestAsync(""" public struct MyStruct { public int Val { get; } @@ -444,10 +351,7 @@ public MyStruct(int val) return new MyStruct(s1.Val + s2.Val); } } - """; - - var expected = - """ + """, """ public struct MyStruct { public int Val { get; } @@ -468,16 +372,12 @@ public MyStruct(int val) return new MyStruct(s1.Val + s2.Val); } } - """; - await TestAsync(initial, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInDocument_MultipleParamNodesInVariousPlaces() - { - var initial = - """ + public Task TestFixAllInDocument_MultipleParamNodesInVariousPlaces() + => TestAsync(""" class Program { /// @@ -486,10 +386,7 @@ class Program /// public void Fizz(int i, int {|FixAllInDocument:j|}, int k, int l) {} } - """; - - var expected = - """ + """, """ class Program { /// @@ -501,16 +398,12 @@ class Program /// public void Fizz(int i, int j, int k, int l) {} } - """; - - await TestAsync(initial, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInDocument() - { - var initial = """ + public Task TestFixAllInDocument() + => TestAsync(""" @@ -561,9 +454,7 @@ public void Fizz(int i, int j, int k) {} - """; - - var expected = """ + """, """ @@ -616,16 +507,12 @@ public void Fizz(int i, int j, int k) {} - """; - - await TestAsync(initial, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInProject() - { - var initial = """ + public Task TestFixAllInProject() + => TestAsync(""" @@ -670,9 +557,7 @@ class Program3 - """; - - var expected = """ + """, """ @@ -719,16 +604,12 @@ class Program3 - """; - - await TestAsync(initial, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInSolution() - { - var initial = """ + public Task TestFixAllInSolution() + => TestAsync(""" @@ -770,9 +651,7 @@ public void Fizz(int i, int j, int k) {} - """; - - var expected = """ + """, """ @@ -818,24 +697,18 @@ public void Fizz(int i, int j, int k) {} - """; - - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddDocCommentNodes)] [WorkItem("https://github.com/dotnet/roslyn/issues/52738")] - public async Task AddsParamTag_Record() - { - var initial = """ + public Task AddsParamTag_Record() + => TestAsync(""" /// /// /// /// record R(int [|First|], int Second, int Third); - """; - - var expected = """ + """, """ /// /// /// @@ -843,22 +716,17 @@ record R(int [|First|], int Second, int Third); /// /// record R(int First, int Second, int Third); - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddDocCommentNodes)] - public async Task AddsParamTag_Class() - { - var initial = """ + public Task AddsParamTag_Class() + => TestAsync(""" /// /// /// /// class R(int [|First|], int Second, int Third); - """; - - var expected = """ + """, """ /// /// /// @@ -866,22 +734,17 @@ class R(int [|First|], int Second, int Third); /// /// class R(int First, int Second, int Third); - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddDocCommentNodes)] - public async Task AddsParamTag_Struct() - { - var initial = """ + public Task AddsParamTag_Struct() + => TestAsync(""" /// /// /// /// struct R(int [|First|], int Second, int Third); - """; - - var expected = """ + """, """ /// /// /// @@ -889,7 +752,5 @@ struct R(int [|First|], int Second, int Third); /// /// struct R(int First, int Second, int Third); - """; - await TestAsync(initial, expected); - } + """); } diff --git a/src/Analyzers/CSharp/Tests/DocumentationComments/RemoveDocCommentNodeCodeFixProviderTests.cs b/src/Analyzers/CSharp/Tests/DocumentationComments/RemoveDocCommentNodeCodeFixProviderTests.cs index afbba70a017ee..fbdc982d12998 100644 --- a/src/Analyzers/CSharp/Tests/DocumentationComments/RemoveDocCommentNodeCodeFixProviderTests.cs +++ b/src/Analyzers/CSharp/Tests/DocumentationComments/RemoveDocCommentNodeCodeFixProviderTests.cs @@ -35,10 +35,8 @@ private async Task TestAsync(string initial, string expected) } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] - public async Task RemovesDuplicateParamTag() - { - var initial = - """ + public Task RemovesDuplicateParamTag() + => TestAsync(""" class Program { /// @@ -48,10 +46,7 @@ class Program /// public void Fizz(int value) {} } - """; - - var expected = - """ + """, """ class Program { /// @@ -60,39 +55,28 @@ class Program /// public void Fizz(int value) {} } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] - public async Task RemovesDuplicateParamTag_OnlyParamTags() - { - var initial = - """ + public Task RemovesDuplicateParamTag_OnlyParamTags() + => TestAsync(""" class Program { /// /// public void Fizz(int value) {} } - """; - - var expected = - """ + """, """ class Program { /// public void Fizz(int value) {} } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] - public async Task RemovesDuplicateParamTag_TagBelowOffendingParamTag() - { - var initial = - """ + public Task RemovesDuplicateParamTag_TagBelowOffendingParamTag() + => TestAsync(""" class Program { /// @@ -100,25 +84,18 @@ class Program /// public int Fizz(int value) { return 0; } } - """; - - var expected = - """ + """, """ class Program { /// /// public int Fizz(int value) { return 0; } } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] - public async Task RemovesDuplicateParamTag_BothParamTagsOnSameLine_DocCommentTagBetweenThem() - { - var initial = - """ + public Task RemovesDuplicateParamTag_BothParamTagsOnSameLine_DocCommentTagBetweenThem() + => TestAsync(""" class Program { /// @@ -127,10 +104,7 @@ class Program /// /// public void Fizz(int value) {} } - """; - - var expected = - """ + """, """ class Program { /// @@ -139,15 +113,11 @@ class Program /// public void Fizz(int value) {} } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] - public async Task RemovesDuplicateParamTag_BothParamTagsOnSameLine_WhitespaceBetweenThem() - { - var initial = - """ + public Task RemovesDuplicateParamTag_BothParamTagsOnSameLine_WhitespaceBetweenThem() + => TestAsync(""" class Program { /// @@ -156,10 +126,7 @@ class Program /// public void Fizz(int value) {} } - """; - - var expected = - """ + """, """ class Program { /// @@ -168,15 +135,11 @@ class Program /// public void Fizz(int value) {} } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] - public async Task RemovesDuplicateParamTag_BothParamTagsOnSameLine_NothingBetweenThem1() - { - var initial = - """ + public Task RemovesDuplicateParamTag_BothParamTagsOnSameLine_NothingBetweenThem1() + => TestAsync(""" class Program { /// @@ -185,10 +148,7 @@ class Program /// public void Fizz(int value) {} } - """; - - var expected = - """ + """, """ class Program { /// @@ -197,16 +157,12 @@ class Program /// public void Fizz(int value) {} } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] [WorkItem("https://github.com/dotnet/roslyn/issues/13436")] - public async Task RemovesTag_BothParamTagsOnSameLine_NothingBetweenThem2() - { - var initial = - """ + public Task RemovesTag_BothParamTagsOnSameLine_NothingBetweenThem2() + => TestAsync(""" class Program { /// @@ -215,10 +171,7 @@ class Program /// public void Fizz(int value) {} } - """; - - var expected = - """ + """, """ class Program { /// @@ -227,16 +180,12 @@ class Program /// public void Fizz(int value) {} } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] [WorkItem("https://github.com/dotnet/roslyn/issues/13436")] - public async Task RemovesTag_TrailingTextAfterTag() - { - var initial = - """ + public Task RemovesTag_TrailingTextAfterTag() + => TestAsync(""" class Program { /// @@ -245,10 +194,7 @@ class Program /// a public void Fizz(int value) {} } - """; - - var expected = - """ + """, """ class Program { /// @@ -257,15 +203,11 @@ class Program /// a public void Fizz(int value) {} } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] - public async Task RemovesDuplicateParamTag_RawTextBeforeAndAfterNode() - { - var initial = - """ + public Task RemovesDuplicateParamTag_RawTextBeforeAndAfterNode() + => TestAsync(""" class Program { /// @@ -275,10 +217,7 @@ class Program /// some commentout of the XML nodes public void Fizz(int value) {} } - """; - - var expected = - """ + """, """ class Program { /// @@ -288,15 +227,11 @@ class Program /// some commentout of the XML nodes public void Fizz(int value) {} } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] - public async Task RemovesDuplicateTypeparamTag() - { - var initial = - """ + public Task RemovesDuplicateTypeparamTag() + => TestAsync(""" class Program { /// @@ -306,10 +241,7 @@ class Program /// public void Fizz() { } } - """; - - var expected = - """ + """, """ class Program { /// @@ -318,15 +250,11 @@ class Program /// public void Fizz() { } } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] - public async Task RemovesParamTagWithNoMatchingParameter() - { - var initial = - """ + public Task RemovesParamTagWithNoMatchingParameter() + => TestAsync(""" class Program { /// @@ -335,10 +263,7 @@ class Program /// public void Fizz(int value) {} } - """; - - var expected = - """ + """, """ class Program { /// @@ -346,15 +271,11 @@ class Program /// public void Fizz(int value) {} } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] - public async Task RemovesParamTag_NestedInSummaryTag() - { - var initial = - """ + public Task RemovesParamTag_NestedInSummaryTag() + => TestAsync(""" class Program { /// @@ -363,10 +284,7 @@ class Program /// public void Fizz(int value) {} } - """; - - var expected = - """ + """, """ class Program { /// @@ -374,15 +292,11 @@ class Program /// public void Fizz(int value) {} } - """; - await TestAsync(initial, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] - public async Task RemovesParamTag_NestedInSummaryTag_WithChildren() - { - var initial = - """ + public Task RemovesParamTag_NestedInSummaryTag_WithChildren() + => TestAsync(""" class Program { /// @@ -393,10 +307,7 @@ class Program /// public void Fizz(int value) {} } - """; - - var expected = - """ + """, """ class Program { /// @@ -404,15 +315,12 @@ class Program /// public void Fizz(int value) {} } - """; - await TestAsync(initial, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllTypeparamInDocument_DoesNotFixDuplicateParamTags() - { - var initial = """ + public Task TestFixAllTypeparamInDocument_DoesNotFixDuplicateParamTags() + => TestAsync(""" @@ -469,9 +377,7 @@ public void Fizz(int value) {} - """; - - var expected = """ + """, """ @@ -526,16 +432,12 @@ public void Fizz(int value) {} - """; - - await TestAsync(initial, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInDocument() - { - var initial = """ + public Task TestFixAllInDocument() + => TestAsync(""" @@ -586,9 +488,7 @@ public void Fizz(int value) {} - """; - - var expected = """ + """, """ @@ -637,16 +537,12 @@ public void Fizz(int value) {} - """; - - await TestAsync(initial, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInProject() - { - var initial = """ + public Task TestFixAllInProject() + => TestAsync(""" @@ -689,9 +585,7 @@ public void Fizz(int value) {} - """; - - var expected = """ + """, """ @@ -732,16 +626,12 @@ public void Fizz(int value) {} - """; - - await TestAsync(initial, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInSolution() - { - var initial = """ + public Task TestFixAllInSolution() + => TestAsync(""" @@ -784,9 +674,7 @@ public void Fizz(int value) {} - """; - - var expected = """ + """, """ @@ -826,8 +714,5 @@ public void Fizz(int value) {} - """; - - await TestAsync(initial, expected); - } + """); } diff --git a/src/Analyzers/CSharp/Tests/FileHeaders/FileHeaderTests.cs b/src/Analyzers/CSharp/Tests/FileHeaders/FileHeaderTests.cs index b1c04d073df4e..2bc54c7c094ce 100644 --- a/src/Analyzers/CSharp/Tests/FileHeaders/FileHeaderTests.cs +++ b/src/Analyzers/CSharp/Tests/FileHeaders/FileHeaderTests.cs @@ -3,16 +3,19 @@ // See the LICENSE file in the project root for more information. using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CSharp.FileHeaders; +using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; -using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< - Microsoft.CodeAnalysis.CSharp.FileHeaders.CSharpFileHeaderDiagnosticAnalyzer, - Microsoft.CodeAnalysis.CSharp.FileHeaders.CSharpFileHeaderCodeFixProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.FileHeaders; +using VerifyCS = CSharpCodeFixVerifier< + CSharpFileHeaderDiagnosticAnalyzer, + CSharpFileHeaderCodeFixProvider>; + public sealed class FileHeaderTests { private const string TestSettings = """ @@ -33,23 +36,19 @@ public sealed class FileHeaderTests [InlineData("")] [InlineData("file_header_template =")] [InlineData("file_header_template = unset")] - public async Task TestFileHeaderNotConfiguredAsync(string fileHeaderTemplate) - { - var testCode = """ + public Task TestFileHeaderNotConfiguredAsync(string fileHeaderTemplate) + => new VerifyCS.Test + { + TestCode = """ namespace N { } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - EditorConfig = $@" -[*] -{fileHeaderTemplate} -", + """, + EditorConfig = $""" + [*] + {fileHeaderTemplate} + """, }.RunAsync(); - } /// /// Verifies that the analyzer will report a diagnostic when the file is completely missing a header. @@ -92,16 +91,17 @@ namespace N /// /// A representing the asynchronous unit test. [Fact] - public async Task TestNoFileHeaderWithUsingDirectiveAsync() - { - var testCode = """ + public Task TestNoFileHeaderWithUsingDirectiveAsync() + => new VerifyCS.Test + { + TestCode = """ [||]using System; namespace N { } - """; - var fixedCode = """ + """, + FixedCode = """ // Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. @@ -110,32 +110,27 @@ namespace N namespace N { } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - FixedCode = fixedCode, + """, EditorConfig = TestSettings, }.RunAsync(); - } /// /// Verifies that the analyzer will report a diagnostic when the file is completely missing a header. /// /// A representing the asynchronous unit test. [Fact] - public async Task TestNoFileHeaderWithBlankLineAndUsingDirectiveAsync() - { - var testCode = """ + public Task TestNoFileHeaderWithBlankLineAndUsingDirectiveAsync() + => new VerifyCS.Test + { + TestCode = """ [||] using System; namespace N { } - """; - var fixedCode = """ + """, + FixedCode = """ // Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. @@ -144,15 +139,9 @@ namespace N namespace N { } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - FixedCode = fixedCode, + """, EditorConfig = TestSettings, }.RunAsync(); - } /// /// Verifies that the analyzer will report a diagnostic when the file is completely missing a header. @@ -169,7 +158,10 @@ namespace N { } """; - var fixedCode = """ + await new VerifyCS.Test + { + TestCode = testCode, + FixedCode = """ // Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. @@ -178,12 +170,7 @@ namespace N namespace N { } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - FixedCode = fixedCode, + """, EditorConfig = TestSettings, }.RunAsync(); } @@ -193,66 +180,56 @@ namespace N /// /// A representing the asynchronous unit test. [Fact] - public async Task TestFileNameBuiltInVariableAsync() - { - var editorConfig = """ - [*.cs] - file_header_template = {fileName} Copyright (c) SomeCorp. All rights reserved.\nLicensed under the ??? license. See LICENSE file in the project root for full license information. - """; - - var testCode = """ + public Task TestFileNameBuiltInVariableAsync() + => new VerifyCS.Test + { + TestCode = """ [||]namespace N { } - """; - var fixedCode = """ + """, + FixedCode = """ // Test0.cs Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace N { } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - FixedCode = fixedCode, - EditorConfig = editorConfig, + """, + EditorConfig = """ + [*.cs] + file_header_template = {fileName} Copyright (c) SomeCorp. All rights reserved.\nLicensed under the ??? license. See LICENSE file in the project root for full license information. + """, }.RunAsync(); - } /// /// Verifies that a valid file header built using single line comments will not produce a diagnostic message. /// /// A representing the asynchronous unit test. [Fact] - public async Task TestValidFileHeaderWithSingleLineCommentsAsync() - { - var testCode = """ + public Task TestValidFileHeaderWithSingleLineCommentsAsync() + => new VerifyCS.Test + { + TestCode = """ // Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace Bar { } - """; - - await new VerifyCS.Test - { - TestCode = testCode, + """, EditorConfig = TestSettings, }.RunAsync(); - } /// /// Verifies that a valid file header built using multi-line comments will not produce a diagnostic message. /// /// A representing the asynchronous unit test. [Fact] - public async Task TestValidFileHeaderWithMultiLineComments1Async() - { - var testCode = """ + public Task TestValidFileHeaderWithMultiLineComments1Async() + => new VerifyCS.Test + { + TestCode = """ /* Copyright (c) SomeCorp. All rights reserved. * Licensed under the ??? license. See LICENSE file in the project root for full license information. */ @@ -260,37 +237,28 @@ public async Task TestValidFileHeaderWithMultiLineComments1Async() namespace Bar { } - """; - - await new VerifyCS.Test - { - TestCode = testCode, + """, EditorConfig = TestSettings, }.RunAsync(); - } /// /// Verifies that a valid file header built using multi-line comments will not produce a diagnostic message. /// /// A representing the asynchronous unit test. [Fact] - public async Task TestValidFileHeaderWithMultiLineComments2Async() - { - var testCode = """ + public Task TestValidFileHeaderWithMultiLineComments2Async() + => new VerifyCS.Test + { + TestCode = """ /* Copyright (c) SomeCorp. All rights reserved. Licensed under the ??? license. See LICENSE file in the project root for full license information. */ namespace Bar { } - """; - - await new VerifyCS.Test - { - TestCode = testCode, + """, EditorConfig = TestSettings, }.RunAsync(); - } /// /// Verifies that a valid file header built using unterminated multi-line comments will not produce a diagnostic @@ -326,70 +294,63 @@ public async Task TestValidFileHeaderWithMultiLineComments3Async() [Theory] [InlineData("[|//|]")] [InlineData("[|//|] ")] - public async Task TestInvalidFileHeaderWithoutTextAsync(string comment) - { - var testCode = $@"{comment} + public Task TestInvalidFileHeaderWithoutTextAsync(string comment) + => new VerifyCS.Test + { + TestCode = $$""" + {{comment}} -namespace Bar -{{ -}}"; - var fixedCode = """ + namespace Bar + { + } + """, + FixedCode = """ // Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace Bar { } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - FixedCode = fixedCode, + """, EditorConfig = TestSettings, }.RunAsync(); - } /// /// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message. /// /// A representing the asynchronous unit test. [Fact] - public async Task TestInvalidFileHeaderWithWrongTextAsync() - { - var testCode = """ + public Task TestInvalidFileHeaderWithWrongTextAsync() + => new VerifyCS.Test + { + TestCode = """ [|//|] Copyright (c) OtherCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace Bar { } - """; - var fixedCode = """ + """, + FixedCode = """ // Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace Bar { } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - FixedCode = fixedCode, + """, EditorConfig = TestSettings, }.RunAsync(); - } /// /// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message. /// /// A representing the asynchronous unit test. [Fact] - public async Task TestInvalidFileHeaderWithWrongText2Async() - { - var testCode = """ + public Task TestInvalidFileHeaderWithWrongText2Async() + => new VerifyCS.Test + { + TestCode = """ [|/*|] Copyright (c) OtherCorp. All rights reserved. * Licensed under the ??? license. See LICENSE file in the project root for full license information. */ @@ -397,8 +358,8 @@ public async Task TestInvalidFileHeaderWithWrongText2Async() namespace Bar { } - """; - var fixedCode = """ + """, + FixedCode = """ // Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. @@ -409,126 +370,104 @@ namespace Bar namespace Bar { } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - FixedCode = fixedCode, + """, EditorConfig = TestSettings, }.RunAsync(); - } [Theory] [InlineData("", "")] [InlineData(" Header", "")] [InlineData(" Header", " Header")] - public async Task TestValidFileHeaderInRegionAsync(string startLabel, string endLabel) - { - var testCode = $@"#region{startLabel} -// Copyright (c) SomeCorp. All rights reserved. -// Licensed under the ??? license. See LICENSE file in the project root for full license information. -#endregion{endLabel} - -namespace Bar -{{ -}} -"; - - await new VerifyCS.Test + public Task TestValidFileHeaderInRegionAsync(string startLabel, string endLabel) + => new VerifyCS.Test { - TestCode = testCode, + TestCode = $$""" + #region{{startLabel}} + // Copyright (c) SomeCorp. All rights reserved. + // Licensed under the ??? license. See LICENSE file in the project root for full license information. + #endregion{{endLabel}} + + namespace Bar + { + } + """, EditorConfig = TestSettings, }.RunAsync(); - } [Theory] [InlineData("", "")] [InlineData(" Header", "")] [InlineData(" Header", " Header")] - public async Task TestInvalidFileHeaderWithWrongTextInRegionAsync(string startLabel, string endLabel) - { - var testCode = $@"#region{startLabel} -[|//|] Copyright (c) OtherCorp. All rights reserved. -// Licensed under the ??? license. See LICENSE file in the project root for full license information. -#endregion{endLabel} - -namespace Bar -{{ -}} -"; - var fixedCode = $@"// Copyright (c) SomeCorp. All rights reserved. -// Licensed under the ??? license. See LICENSE file in the project root for full license information. - -#region{startLabel} -// Copyright (c) OtherCorp. All rights reserved. -// Licensed under the ??? license. See LICENSE file in the project root for full license information. -#endregion{endLabel} - -namespace Bar -{{ -}} -"; - - await new VerifyCS.Test + public Task TestInvalidFileHeaderWithWrongTextInRegionAsync(string startLabel, string endLabel) + => new VerifyCS.Test { - TestCode = testCode, - FixedCode = fixedCode, + TestCode = $$""" + #region{{startLabel}} + [|//|] Copyright (c) OtherCorp. All rights reserved. + // Licensed under the ??? license. See LICENSE file in the project root for full license information. + #endregion{{endLabel}} + + namespace Bar + { + } + """, + FixedCode = $$""" + // Copyright (c) SomeCorp. All rights reserved. + // Licensed under the ??? license. See LICENSE file in the project root for full license information. + + #region{{startLabel}} + // Copyright (c) OtherCorp. All rights reserved. + // Licensed under the ??? license. See LICENSE file in the project root for full license information. + #endregion{{endLabel}} + + namespace Bar + { + } + """, EditorConfig = TestSettings, }.RunAsync(); - } /// /// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message. /// /// A representing the asynchronous unit test. [Fact] - public async Task TestInvalidFileHeaderWithWrongTextInUnterminatedMultiLineComment1Async() - { - var testCode = """ + public Task TestInvalidFileHeaderWithWrongTextInUnterminatedMultiLineComment1Async() + => new VerifyCS.Test + { + TestCode = """ {|CS1035:|}[|/*|] Copyright (c) OtherCorp. All rights reserved. * Licensed under the ??? license. See LICENSE file in the project root for full license information. - """; - var fixedCode = """ + """, + FixedCode = """ // Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. {|CS1035:|}/* Copyright (c) OtherCorp. All rights reserved. * Licensed under the ??? license. See LICENSE file in the project root for full license information. - """; - - await new VerifyCS.Test - { - TestCode = testCode, - FixedCode = fixedCode, + """, EditorConfig = TestSettings, }.RunAsync(); - } /// /// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message. /// /// A representing the asynchronous unit test. [Fact] - public async Task TestInvalidFileHeaderWithWrongTextInUnterminatedMultiLineComment2Async() - { - var testCode = """ + public Task TestInvalidFileHeaderWithWrongTextInUnterminatedMultiLineComment2Async() + => new VerifyCS.Test + { + TestCode = """ {|CS1035:|}[|/*|]/ - """; - var fixedCode = """ + """, + FixedCode = """ // Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. {|CS1035:|}/*/ - """; - - await new VerifyCS.Test - { - TestCode = testCode, - FixedCode = fixedCode, + """, EditorConfig = TestSettings, }.RunAsync(); - } /// /// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message. @@ -537,40 +476,38 @@ public async Task TestInvalidFileHeaderWithWrongTextInUnterminatedMultiLineComme [Theory] [InlineData("")] [InlineData(" ")] - public async Task TestInvalidFileHeaderWithWrongTextAfterBlankLineAsync(string firstLine) - { - var testCode = $@"{firstLine} -[|//|] Copyright (c) OtherCorp. All rights reserved. -// Licensed under the ??? license. See LICENSE file in the project root for full license information. + public Task TestInvalidFileHeaderWithWrongTextAfterBlankLineAsync(string firstLine) + => new VerifyCS.Test + { + TestCode = $$""" + {{firstLine}} + [|//|] Copyright (c) OtherCorp. All rights reserved. + // Licensed under the ??? license. See LICENSE file in the project root for full license information. -namespace Bar -{{ -}}"; - var fixedCode = """ + namespace Bar + { + } + """, + FixedCode = """ // Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace Bar { } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - FixedCode = fixedCode, + """, EditorConfig = TestSettings, }.RunAsync(); - } /// /// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message. /// /// A representing the asynchronous unit test. [Fact] - public async Task TestInvalidFileHeaderWithWrongTextFollowedByCommentAsync() - { - var testCode = """ + public Task TestInvalidFileHeaderWithWrongTextFollowedByCommentAsync() + => new VerifyCS.Test + { + TestCode = """ [|//|] Copyright (c) OtherCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. @@ -579,8 +516,8 @@ public async Task TestInvalidFileHeaderWithWrongTextFollowedByCommentAsync() namespace Bar { } - """; - var fixedCode = """ + """, + FixedCode = """ // Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. @@ -589,28 +526,23 @@ namespace Bar namespace Bar { } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - FixedCode = fixedCode, + """, EditorConfig = TestSettings, }.RunAsync(); - } [Fact] - public async Task TestHeaderMissingRequiredNewLinesAsync() - { - var testCode = """ + public Task TestHeaderMissingRequiredNewLinesAsync() + => new VerifyCS.Test + { + TestCode = """ [|//|] Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace Bar { } - """; - var fixedCode = """ + """, + FixedCode = """ // // Copyright (c) SomeCorp. All rights reserved. // @@ -620,13 +552,7 @@ namespace Bar namespace Bar { } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - FixedCode = fixedCode, + """, EditorConfig = TestSettingsWithEmptyLines, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/FixIncorrectConstraint/FixIncorrectConstraintTests.cs b/src/Analyzers/CSharp/Tests/FixIncorrectConstraint/FixIncorrectConstraintTests.cs index d9c6f9ae009ea..60c3abd15209d 100644 --- a/src/Analyzers/CSharp/Tests/FixIncorrectConstraint/FixIncorrectConstraintTests.cs +++ b/src/Analyzers/CSharp/Tests/FixIncorrectConstraint/FixIncorrectConstraintTests.cs @@ -17,9 +17,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.FixIncorrectConstraint; public sealed class FixIncorrectConstraintTests { [Fact] - public async Task TestEnumConstraint() - { - await new VerifyCS.Test + public Task TestEnumConstraint() + => new VerifyCS.Test { TestCode = """ class C where T : {|CS9010:enum|} @@ -32,12 +31,10 @@ class C where T : struct, System.Enum } """, }.RunAsync(); - } [Fact] - public async Task TestEnumConstraintWithUsing() - { - await new VerifyCS.Test + public Task TestEnumConstraintWithUsing() + => new VerifyCS.Test { TestCode = """ using System; @@ -54,12 +51,10 @@ class C where T : struct, Enum } """, }.RunAsync(); - } [Fact] - public async Task TestDelegateConstraint() - { - await new VerifyCS.Test + public Task TestDelegateConstraint() + => new VerifyCS.Test { TestCode = """ class C where T : {|CS9011:delegate|} @@ -72,12 +67,10 @@ class C where T : System.Delegate } """, }.RunAsync(); - } [Fact] - public async Task TestDelegateConstraintWithUsing() - { - await new VerifyCS.Test + public Task TestDelegateConstraintWithUsing() + => new VerifyCS.Test { TestCode = """ using System; @@ -94,5 +87,4 @@ class C where T : Delegate } """, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/FixReturnType/FixReturnTypeTests.cs b/src/Analyzers/CSharp/Tests/FixReturnType/FixReturnTypeTests.cs index 319f0e5eb8911..8a76bfc266c4a 100644 --- a/src/Analyzers/CSharp/Tests/FixReturnType/FixReturnTypeTests.cs +++ b/src/Analyzers/CSharp/Tests/FixReturnType/FixReturnTypeTests.cs @@ -21,9 +21,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.FixReturnTy public sealed class FixReturnTypeTests { [Fact] - public async Task Simple() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task Simple() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -40,12 +39,10 @@ int M() } } """); - } [Fact] - public async Task Simple_WithTrivia() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task Simple_WithTrivia() + => VerifyCS.VerifyCodeFixAsync(""" class C { /*A*/ void /*B*/ M() @@ -63,13 +60,10 @@ class C } } """); - // Note: the formatting change is introduced by Formatter.FormatAsync - } [Fact] - public async Task ReturnString() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task ReturnString() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -86,12 +80,10 @@ string M() } } """); - } [Fact] - public async Task ReturnNull() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task ReturnNull() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -108,12 +100,10 @@ object M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65302")] - public async Task ReturnTypelessTuple() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task ReturnTypelessTuple() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -130,12 +120,10 @@ class C } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65302")] - public async Task ReturnTypelessTuple_Nested() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task ReturnTypelessTuple_Nested() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -152,12 +140,10 @@ class C } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65302")] - public async Task ReturnTypelessTuple_Async() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task ReturnTypelessTuple_Async() + => VerifyCS.VerifyCodeFixAsync(""" class C { async void M() @@ -174,12 +160,10 @@ class C } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65302")] - public async Task ReturnTypelessTuple_Nested_Async() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task ReturnTypelessTuple_Nested_Async() + => VerifyCS.VerifyCodeFixAsync(""" class C { async void M() @@ -196,12 +180,10 @@ class C } } """); - } [Fact] - public async Task ReturnLambda() - { - await new VerifyCS.Test + public Task ReturnLambda() + => new VerifyCS.Test { TestCode = """ class C @@ -223,12 +205,10 @@ object M() """, LanguageVersion = LanguageVersion.CSharp10 }.RunAsync(); - } [Fact] - public async Task ReturnC() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task ReturnC() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -245,12 +225,10 @@ C M() } } """); - } [Fact] - public async Task ReturnString_AsyncVoid() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task ReturnString_AsyncVoid() + => VerifyCS.VerifyCodeFixAsync(""" class C { async void M() @@ -267,12 +245,10 @@ async System.Threading.Tasks.Task M() } } """); - } [Fact] - public async Task ReturnString_AsyncVoid_WithUsing() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task ReturnString_AsyncVoid_WithUsing() + => VerifyCS.VerifyCodeFixAsync(""" using System.Threading.Tasks; class C @@ -293,12 +269,10 @@ async Task M() } } """); - } [Fact] - public async Task ReturnString_AsyncTask() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task ReturnString_AsyncTask() + => VerifyCS.VerifyCodeFixAsync(""" class C { async System.Threading.Tasks.Task M() @@ -315,12 +289,10 @@ async System.Threading.Tasks.Task M() } } """); - } [Fact] - public async Task ReturnString_LocalFunction() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task ReturnString_LocalFunction() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -343,12 +315,10 @@ string local() } } """); - } [Fact] - public async Task ReturnString_AsyncVoid_LocalFunction() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task ReturnString_AsyncVoid_LocalFunction() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -371,12 +341,10 @@ async System.Threading.Tasks.Task local() } } """); - } [Fact] - public async Task ExpressionBodied() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task ExpressionBodied() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() => {|CS0201:1|}; @@ -387,7 +355,6 @@ class C int M() => 1; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47089")] public async Task ExpressionAndReturnTypeAreVoid() @@ -407,9 +374,8 @@ void M() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53574")] - public async Task TestAnonymousTypeTopLevel() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestAnonymousTypeTopLevel() + => VerifyCS.VerifyCodeFixAsync(""" class C { public void Method() @@ -426,12 +392,10 @@ public object Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53574")] - public async Task TestAnonymousTypeTopNested() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestAnonymousTypeTopNested() + => VerifyCS.VerifyCodeFixAsync(""" class C { public void Method() @@ -448,12 +412,10 @@ public object Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64901")] - public async Task ReturnString_ValueTask() - { - await new VerifyCS.Test + public Task ReturnString_ValueTask() + => new VerifyCS.Test { TestCode = """ using System.Threading.Tasks; @@ -479,12 +441,12 @@ async ValueTask M() """, ReferenceAssemblies = ReferenceAssemblies.Net.Net60 }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64901")] - public async Task ReturnString_CustomTaskType() - { - var markup = """ + public Task ReturnString_CustomTaskType() + => new VerifyCS.Test + { + TestCode = """ using System.Runtime.CompilerServices; [AsyncMethodBuilder(typeof(C))] @@ -495,12 +457,7 @@ async C M() {|CS1997:return|} ""; } } - """; - - await new VerifyCS.Test - { - TestCode = markup, + """, ReferenceAssemblies = ReferenceAssemblies.Net.Net60 }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/ForEachCast/ForEachCastTests.cs b/src/Analyzers/CSharp/Tests/ForEachCast/ForEachCastTests.cs index 147309969558e..87079fe10fff4 100644 --- a/src/Analyzers/CSharp/Tests/ForEachCast/ForEachCastTests.cs +++ b/src/Analyzers/CSharp/Tests/ForEachCast/ForEachCastTests.cs @@ -18,10 +18,9 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ForEachCast; public sealed class ForEachCastTests { - private static async Task TestWorkerAsync( + private static Task TestWorkerAsync( string testCode, string fixedCode, string optionValue, ReferenceAssemblies? referenceAssemblies) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, @@ -31,7 +30,6 @@ private static async Task TestWorkerAsync( """ + optionValue, ReferenceAssemblies = referenceAssemblies ?? ReferenceAssemblies.Default, }.RunAsync(); - } private static Task TestAlwaysAsync(string markup, string alwaysMarkup, ReferenceAssemblies? referenceAssemblies = null) => TestWorkerAsync(markup, alwaysMarkup, "always", referenceAssemblies); @@ -270,9 +268,8 @@ void Main(IList x) } [Fact] - public async Task NonGenericObjectCollection_Always() - { - var test = """ + public Task NonGenericObjectCollection_Always() + => TestAlwaysAsync(""" using System.Collections; namespace ConsoleApplication1 { @@ -287,8 +284,7 @@ void Main() } } } - """; - var fixedCode = """ + """, """ using System.Collections; using System.Linq; namespace ConsoleApplication1 @@ -304,10 +300,7 @@ void Main() } } } - """; - - await TestAlwaysAsync(test, fixedCode); - } + """); [Fact] public async Task NonGenericObjectCollection_NonLegacy() diff --git a/src/Analyzers/CSharp/Tests/Formatting/FormattingAnalyzerTests.cs b/src/Analyzers/CSharp/Tests/Formatting/FormattingAnalyzerTests.cs index 445a7638f9e2f..8453b09c68053 100644 --- a/src/Analyzers/CSharp/Tests/Formatting/FormattingAnalyzerTests.cs +++ b/src/Analyzers/CSharp/Tests/Formatting/FormattingAnalyzerTests.cs @@ -30,278 +30,228 @@ public async Task TrailingWhitespace() } [Fact] - public async Task TestMissingSpace() - { - var testCode = @" -class TypeName -{ - void Method() - { - if[||](true)[||]return; - } -} -"; - var expected = @" -class TypeName -{ - void Method() - { - if (true) return; - } -} -"; - await Verify.VerifyCodeFixAsync(testCode, expected); - } + public Task TestMissingSpace() + => Verify.VerifyCodeFixAsync(""" + class TypeName + { + void Method() + { + if[||](true)[||]return; + } + } + """, """ + class TypeName + { + void Method() + { + if (true) return; + } + } + """); [Fact] - public async Task TestAlreadyFormatted() - { - var testCode = @" -class MyClass -{ - void MyMethod() - { - } -} -"; - - await Verify.VerifyAnalyzerAsync(testCode); - } + public Task TestAlreadyFormatted() + => Verify.VerifyAnalyzerAsync(""" + class MyClass + { + void MyMethod() + { + } + } + """); [Fact] - public async Task TestNeedsIndentation() - { - var testCode = @" -class MyClass -{ - $$void MyMethod() - $${ - $$} -} -"; - var fixedCode = @" -class MyClass -{ - void MyMethod() - { - } -} -"; - - await Verify.VerifyCodeFixAsync(testCode, fixedCode); - } + public Task TestNeedsIndentation() + => Verify.VerifyCodeFixAsync(""" + class MyClass + { + $$void MyMethod() + $${ + $$} + } + """, """ + class MyClass + { + void MyMethod() + { + } + } + """); [Fact] - public async Task TestNeedsIndentationButSuppressed() - { - var testCode = @" -class MyClass -{ - $$void MyMethod1() - $${ - $$} - -#pragma warning disable format - void MyMethod2() - { - } -#pragma warning restore format - - void MyMethod3() - $${ - $$} -} -"; - var fixedCode = @" -class MyClass -{ - void MyMethod1() - { - } - -#pragma warning disable format - void MyMethod2() - { - } -#pragma warning restore format + public Task TestNeedsIndentationButSuppressed() + => Verify.VerifyCodeFixAsync(""" + class MyClass + { + $$void MyMethod1() + $${ + $$} + + #pragma warning disable format + void MyMethod2() + { + } + #pragma warning restore format + + void MyMethod3() + $${ + $$} + } + """, """ + class MyClass + { + void MyMethod1() + { + } - void MyMethod3() - { - } -} -"; + #pragma warning disable format + void MyMethod2() + { + } + #pragma warning restore format - await Verify.VerifyCodeFixAsync(testCode, fixedCode); - } + void MyMethod3() + { + } + } + """); [Fact] - public async Task TestWhitespaceBetweenMethods1() - { - var testCode = @" -class MyClass -{ - void MyMethod1() - { - } -[| |] - void MyMethod2() - { - } -} -"; - var fixedCode = @" -class MyClass -{ - void MyMethod1() - { - } - - void MyMethod2() - { - } -} -"; + public Task TestWhitespaceBetweenMethods1() + => Verify.VerifyCodeFixAsync(""" + class MyClass + { + void MyMethod1() + { + } + [| |] + void MyMethod2() + { + } + } + """, """ + class MyClass + { + void MyMethod1() + { + } - await Verify.VerifyCodeFixAsync(testCode, fixedCode); - } + void MyMethod2() + { + } + } + """); [Fact] - public async Task TestWhitespaceBetweenMethods2() - { - var testCode = @" -class MyClass -{ - void MyMethod1() - { - }[| |] - - void MyMethod2() - { - } -} -"; - var fixedCode = @" -class MyClass -{ - void MyMethod1() - { - } + public Task TestWhitespaceBetweenMethods2() + => Verify.VerifyCodeFixAsync(""" + class MyClass + { + void MyMethod1() + { + }[| |] - void MyMethod2() - { - } -} -"; + void MyMethod2() + { + } + } + """, """ + class MyClass + { + void MyMethod1() + { + } - await Verify.VerifyCodeFixAsync(testCode, fixedCode); - } + void MyMethod2() + { + } + } + """); [Fact] - public async Task TestWhitespaceBetweenMethods3() - { - // This example has trailing whitespace on both lines preceding MyMethod2 - var testCode = @" -class MyClass -{ - void MyMethod1() - { - }[| - - |]void MyMethod2() - { - } -} -"; - var fixedCode = @" -class MyClass -{ - void MyMethod1() - { - } - - void MyMethod2() - { - } -} -"; + public Task TestWhitespaceBetweenMethods3() + => Verify.VerifyCodeFixAsync(""" + class MyClass + { + void MyMethod1() + { + }[| + + |]void MyMethod2() + { + } + } + """, """ + class MyClass + { + void MyMethod1() + { + } - await Verify.VerifyCodeFixAsync(testCode, fixedCode); - } + void MyMethod2() + { + } + } + """); [Fact] - public async Task TestOverIndentation() - { - var testCode = @" -class MyClass -{ - [| |]void MyMethod() - [| |]{ - [| |]} -} -"; - var fixedCode = @" -class MyClass -{ - void MyMethod() - { - } -} -"; - - await Verify.VerifyCodeFixAsync(testCode, fixedCode); - } + public Task TestOverIndentation() + => Verify.VerifyCodeFixAsync(""" + class MyClass + { + [| |]void MyMethod() + [| |]{ + [| |]} + } + """, """ + class MyClass + { + void MyMethod() + { + } + } + """); [Fact] - public async Task TestIncrementalFixesFullLine() - { - var testCode = @" -class MyClass -{ - int Property1$${$$get;$$set;$$} - int Property2$${$$get;$$} -} -"; - var fixedCode = @" -class MyClass -{ - int Property1 { get; set; } - int Property2 { get; } -} -"; - - await new Verify.Test + public Task TestIncrementalFixesFullLine() + => new Verify.Test { - TestCode = testCode, - FixedCode = fixedCode, + TestCode = """ + class MyClass + { + int Property1$${$$get;$$set;$$} + int Property2$${$$get;$$} + } + """, + FixedCode = """ + class MyClass + { + int Property1 { get; set; } + int Property2 { get; } + } + """, // Each application of a single code fix covers all diagnostics on the same line. In total, two lines // require changes so the number of incremental iterations is exactly 2. NumberOfIncrementalIterations = 2, }.RunAsync(); - } [Fact] public async Task TestEditorConfigUsed() { - var testCode = @" -class MyClass { - void MyMethod()[| |]{ - } -} -"; - var fixedCode = @" -class MyClass { - void MyMethod() - { - } -} -"; - var editorConfig = @" -root = true -[*.cs] -csharp_new_line_before_open_brace = methods -"; - + var testCode = """ + class MyClass { + void MyMethod()[| |]{ + } + } + """; + var fixedCode = """ + class MyClass { + void MyMethod() + { + } + } + """; await new Verify.Test { TestState = @@ -309,7 +259,11 @@ void MyMethod() Sources = { testCode }, AnalyzerConfigFiles = { - ("/.editorconfig", editorConfig), + ("/.editorconfig", """ + root = true + [*.cs] + csharp_new_line_before_open_brace = methods + """), }, }, FixedState = { Sources = { fixedCode } }, @@ -319,167 +273,154 @@ void MyMethod() [Fact] public async Task TestRegion() { - var testCode = @" -class MyClass -{ -#if true - public void M() - { - #region ABC1 - System.Console.WriteLine(); - #endregion - } -#else - public void M() - { - #region ABC2 - System.Console.WriteLine(); - #endregion - } -#endif -} -"; + var testCode = """ + class MyClass + { + #if true + public void M() + { + #region ABC1 + System.Console.WriteLine(); + #endregion + } + #else + public void M() + { + #region ABC2 + System.Console.WriteLine(); + #endregion + } + #endif + } + """; await Verify.VerifyCodeFixAsync(testCode, testCode); } [Fact] - public async Task TestRegion2() - { - var testCode = @" -class MyClass -{ -#if true - public void M() - { -[||]#region OUTER1 - #region ABC1 - System.Console.WriteLine(); - #endregion -[||]#endregion - } -#else - public void M() - { -#region OUTER2 - #region ABC2 - System.Console.WriteLine(); - #endregion -#endregion - } -#endif -} -"; - - var fixedCode = @" -class MyClass -{ -#if true - public void M() - { - #region OUTER1 - #region ABC1 - System.Console.WriteLine(); - #endregion - #endregion - } -#else - public void M() - { -#region OUTER2 - #region ABC2 - System.Console.WriteLine(); - #endregion -#endregion - } -#endif -} -"; - await Verify.VerifyCodeFixAsync(testCode, fixedCode); - } + public Task TestRegion2() + => Verify.VerifyCodeFixAsync(""" + class MyClass + { + #if true + public void M() + { + [||]#region OUTER1 + #region ABC1 + System.Console.WriteLine(); + #endregion + [||]#endregion + } + #else + public void M() + { + #region OUTER2 + #region ABC2 + System.Console.WriteLine(); + #endregion + #endregion + } + #endif + } + """, """ + class MyClass + { + #if true + public void M() + { + #region OUTER1 + #region ABC1 + System.Console.WriteLine(); + #endregion + #endregion + } + #else + public void M() + { + #region OUTER2 + #region ABC2 + System.Console.WriteLine(); + #endregion + #endregion + } + #endif + } + """); [Fact] - public async Task TestRegion3() - { - var testCode = @" -class MyClass -{ -#if true - public void M() - { -[||]#region ABC1 - System.Console.WriteLine(); -[||]#endregion - } -#else - public void M() - { -#region ABC2 - System.Console.WriteLine(); -#endregion - } -#endif -} -"; - var fixedCode = @" -class MyClass -{ -#if true - public void M() - { - #region ABC1 - System.Console.WriteLine(); - #endregion - } -#else - public void M() - { -#region ABC2 - System.Console.WriteLine(); -#endregion - } -#endif -} -"; - await Verify.VerifyCodeFixAsync(testCode, fixedCode); - } + public Task TestRegion3() + => Verify.VerifyCodeFixAsync(""" + class MyClass + { + #if true + public void M() + { + [||]#region ABC1 + System.Console.WriteLine(); + [||]#endregion + } + #else + public void M() + { + #region ABC2 + System.Console.WriteLine(); + #endregion + } + #endif + } + """, """ + class MyClass + { + #if true + public void M() + { + #region ABC1 + System.Console.WriteLine(); + #endregion + } + #else + public void M() + { + #region ABC2 + System.Console.WriteLine(); + #endregion + } + #endif + } + """); [Fact] - public async Task TestRegion4() - { - var testCode = @" -class MyClass -{ -#if true - public void M() - { -[||]#region ABC1 - System.Console.WriteLine(); -[||]#endregion - } -#else - #region ABC2 - public void M() { } - #endregion -#endif -} -"; - var fixedCode = @" -class MyClass -{ -#if true - public void M() - { - #region ABC1 - System.Console.WriteLine(); - #endregion - } -#else - #region ABC2 - public void M() { } - #endregion -#endif -} -"; - await Verify.VerifyCodeFixAsync(testCode, fixedCode); - } + public Task TestRegion4() + => Verify.VerifyCodeFixAsync(""" + class MyClass + { + #if true + public void M() + { + [||]#region ABC1 + System.Console.WriteLine(); + [||]#endregion + } + #else + #region ABC2 + public void M() { } + #endregion + #endif + } + """, """ + class MyClass + { + #if true + public void M() + { + #region ABC1 + System.Console.WriteLine(); + #endregion + } + #else + #region ABC2 + public void M() { } + #endregion + #endif + } + """); } diff --git a/src/Analyzers/CSharp/Tests/GenerateConstructor/GenerateConstructorTests.cs b/src/Analyzers/CSharp/Tests/GenerateConstructor/GenerateConstructorTests.cs index 2d3bdb24c3f20..1ddff5b77c8ad 100644 --- a/src/Analyzers/CSharp/Tests/GenerateConstructor/GenerateConstructorTests.cs +++ b/src/Analyzers/CSharp/Tests/GenerateConstructor/GenerateConstructorTests.cs @@ -28,9 +28,8 @@ internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProvide private readonly NamingStylesTestOptionSets options = new NamingStylesTestOptionSets(LanguageNames.CSharp); [Fact] - public async Task TestWithSimpleArgument() - { - await TestInRegularAndScriptAsync( + public Task TestWithSimpleArgument() + => TestInRegularAndScriptAsync( """ class C { @@ -56,12 +55,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44537")] - public async Task TestWithSimpleArgument_WithProperties() - { - await TestInRegularAndScriptAsync( + public Task TestWithSimpleArgument_WithProperties() + => TestInRegularAndScriptAsync( """ class C { @@ -87,12 +84,10 @@ void M() } } """, index: 1); - } [Fact] - public async Task TestWithSimpleArgument_NoMembers() - { - await TestInRegularAndScriptAsync( + public Task TestWithSimpleArgument_NoMembers() + => TestInRegularAndScriptAsync( """ class C { @@ -115,12 +110,10 @@ void M() } } """, index: 2); - } [Fact] - public async Task TestWithSimpleArgument_UseExpressionBody1() - { - await TestInRegularAndScriptAsync( + public Task TestWithSimpleArgument_UseExpressionBody1() + => TestInRegularAndScriptAsync( """ class C { @@ -143,8 +136,7 @@ void M() } } """, -options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); - } + options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910589")] public async Task TestWithNoArgs() @@ -187,9 +179,8 @@ void M() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910589")] - public async Task TestWithNamedArg() - { - await TestInRegularAndScriptAsync( + public Task TestWithNamedArg() + => TestInRegularAndScriptAsync( """ class C { @@ -215,7 +206,6 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910589")] public async Task TestWithExistingField1() @@ -260,9 +250,8 @@ public D(int goo) } [Fact] - public async Task TestWithExistingField2() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingField2() + => TestInRegularAndScriptAsync( """ class C { @@ -297,12 +286,10 @@ public D(int v1) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44537")] - public async Task TestWithExistingField2_WithProperties() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingField2_WithProperties() + => TestInRegularAndScriptAsync( """ class C { @@ -338,12 +325,10 @@ public D(int v1) public int V { get; } } """, index: 1); - } [Fact] - public async Task TestWithExistingField2_NoMembers() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingField2_NoMembers() + => TestInRegularAndScriptAsync( """ class C { @@ -376,12 +361,10 @@ public D(int v1) } } """, index: 2); - } [Fact] - public async Task TestWithExistingField3() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingField3() + => TestInRegularAndScriptAsync( """ class C { @@ -422,12 +405,10 @@ public D(int v) } } """); - } [Fact] - public async Task TestWithExistingField4() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingField4() + => TestInRegularAndScriptAsync( """ class C { @@ -470,12 +451,10 @@ public D(int v) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539444")] - public async Task TestWithExistingField5() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingField5() + => TestInRegularAndScriptAsync( """ class C { @@ -509,12 +488,10 @@ public D(int x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539444")] - public async Task TestWithExistingField5WithQualification() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingField5WithQualification() + => TestInRegularAndScriptAsync( """ class C { @@ -549,12 +526,10 @@ public D(int x) } """, options: Option(CodeStyleOptions2.QualifyFieldAccess, true, NotificationOption2.Error)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539444")] - public async Task TestWithExistingField6() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingField6() + => TestInRegularAndScriptAsync( """ class C { @@ -597,12 +572,10 @@ public D(int x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539444")] - public async Task TestWithExistingField7() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingField7() + => TestInRegularAndScriptAsync( """ class C { @@ -643,12 +616,10 @@ public D(int x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539444")] - public async Task TestWithExistingField7WithQualification() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingField7WithQualification() + => TestInRegularAndScriptAsync( """ class C { @@ -690,12 +661,10 @@ public D(int x) } """, options: Option(CodeStyleOptions2.QualifyFieldAccess, true, NotificationOption2.Error)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539444")] - public async Task TestWithExistingField8() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingField8() + => TestInRegularAndScriptAsync( """ class C { @@ -738,12 +707,10 @@ public D(int x1) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539444")] - public async Task TestWithExistingField9() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingField9() + => TestInRegularAndScriptAsync( """ class C { @@ -787,12 +754,10 @@ public D(int x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539444")] - public async Task TestWithExistingProperty1() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingProperty1() + => TestInRegularAndScriptAsync( """ class C { @@ -826,12 +791,10 @@ public D(int x) public int X { get; private set; } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539444")] - public async Task TestWithExistingProperty1WithQualification() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingProperty1WithQualification() + => TestInRegularAndScriptAsync( """ class C { @@ -866,12 +829,10 @@ public D(int x) } """, options: Option(CodeStyleOptions2.QualifyPropertyAccess, true, NotificationOption2.Error)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539444")] - public async Task TestWithExistingProperty2() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingProperty2() + => TestInRegularAndScriptAsync( """ class C { @@ -914,12 +875,10 @@ public D(int x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539444")] - public async Task TestWithExistingProperty3() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingProperty3() + => TestInRegularAndScriptAsync( """ class C { @@ -960,12 +919,10 @@ public D(int x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539444")] - public async Task TestWithExistingProperty3WithQualification() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingProperty3WithQualification() + => TestInRegularAndScriptAsync( """ class C { @@ -1007,12 +964,10 @@ public D(int x) } """, options: Option(CodeStyleOptions2.QualifyPropertyAccess, true, NotificationOption2.Error)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539444")] - public async Task TestWithExistingProperty4() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingProperty4() + => TestInRegularAndScriptAsync( """ class C { @@ -1053,12 +1008,10 @@ public D(int x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539444")] - public async Task TestWithExistingProperty4WithQualification() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingProperty4WithQualification() + => TestInRegularAndScriptAsync( """ class C { @@ -1100,12 +1053,10 @@ public D(int x) } """, options: Option(CodeStyleOptions2.QualifyPropertyAccess, true, NotificationOption2.Error)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539444")] - public async Task TestWithExistingProperty5() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingProperty5() + => TestInRegularAndScriptAsync( """ class C { @@ -1148,12 +1099,10 @@ public D(int x) } } """); - } [Fact] - public async Task TestWithOutParam() - { - await TestInRegularAndScriptAsync( + public Task TestWithOutParam() + => TestInRegularAndScriptAsync( """ class C { @@ -1184,7 +1133,6 @@ public D(out int i) } } """); - } [Fact] public async Task TestWithBaseDelegatingConstructor1() @@ -1240,9 +1188,8 @@ public D(int x) : base(x) } [Fact] - public async Task TestWithBaseDelegatingConstructor2() - { - await TestInRegularAndScriptAsync( + public Task TestWithBaseDelegatingConstructor2() + => TestInRegularAndScriptAsync( """ class C { @@ -1289,12 +1236,10 @@ public D(int v) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44537")] - public async Task TestWithBaseDelegatingConstructor2_WithProperties() - { - await TestInRegularAndScriptAsync( + public Task TestWithBaseDelegatingConstructor2_WithProperties() + => TestInRegularAndScriptAsync( """ class C { @@ -1341,12 +1286,10 @@ public D(int v) public int V { get; } } """, index: 1); - } [Fact] - public async Task TestWithBaseDelegatingConstructor2_NoMembers() - { - await TestInRegularAndScriptAsync( + public Task TestWithBaseDelegatingConstructor2_NoMembers() + => TestInRegularAndScriptAsync( """ class C { @@ -1390,12 +1333,10 @@ public D(int v) } } """, index: 2); - } [Fact] - public async Task TestStructInLocalInitializerWithSystemType() - { - await TestInRegularAndScriptAsync( + public Task TestStructInLocalInitializerWithSystemType() + => TestInRegularAndScriptAsync( """ struct S { @@ -1423,12 +1364,10 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] - public async Task TestEscapedName() - { - await TestInRegularAndScriptAsync( + public Task TestEscapedName() + => TestInRegularAndScriptAsync( """ class C { @@ -1454,12 +1393,10 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] - public async Task TestEscapedKeyword() - { - await TestInRegularAndScriptAsync( + public Task TestEscapedKeyword() + => TestInRegularAndScriptAsync( """ class @int { @@ -1485,12 +1422,10 @@ void M() } } """); - } [Fact] - public async Task TestIsSymbolAccessibleWithInternalField() - { - await TestInRegularAndScriptAsync( + public Task TestIsSymbolAccessibleWithInternalField() + => TestInRegularAndScriptAsync( """ class Base { @@ -1527,12 +1462,10 @@ public Derived(int field) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539548")] - public async Task TestFormatting() - { - await TestInRegularAndScriptAsync( + public Task TestFormatting() + => TestInRegularAndScriptAsync( """ class C { @@ -1558,12 +1491,10 @@ void M() } } """); - } [Fact, WorkItem(5864, "DevDiv_Projects/Roslyn")] - public async Task TestNotOnStructConstructor() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOnStructConstructor() + => TestMissingInRegularAndScriptAsync( """ struct Struct { @@ -1573,12 +1504,10 @@ void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539787")] - public async Task TestGenerateIntoCorrectPart() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateIntoCorrectPart() + => TestInRegularAndScriptAsync( """ partial class C { @@ -1612,12 +1541,10 @@ void Method() } } """); - } [Fact] - public async Task TestDelegateToSmallerConstructor1() - { - await TestInRegularAndScriptAsync( + public Task TestDelegateToSmallerConstructor1() + => TestInRegularAndScriptAsync( """ class A { @@ -1668,12 +1595,10 @@ public Delta(string v1, int v2, bool v) : this(v1, v2) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44537")] - public async Task TestDelegateToSmallerConstructor1_WithProperties() - { - await TestInRegularAndScriptAsync( + public Task TestDelegateToSmallerConstructor1_WithProperties() + => TestInRegularAndScriptAsync( """ class A { @@ -1725,12 +1650,10 @@ public Delta(string v1, int v2, bool v) : this(v1, v2) public bool V { get; } } """, index: 1); - } [Fact] - public async Task TestDelegateToSmallerConstructor1_NoMembers() - { - await TestInRegularAndScriptAsync( + public Task TestDelegateToSmallerConstructor1_NoMembers() + => TestInRegularAndScriptAsync( """ class A { @@ -1779,12 +1702,10 @@ public Delta(string v1, int v2, bool v) : this(v1, v2) } } """, index: 2); - } [Fact] - public async Task TestDelegateToSmallerConstructor2() - { - await TestInRegularAndScriptAsync( + public Task TestDelegateToSmallerConstructor2() + => TestInRegularAndScriptAsync( """ class A { @@ -1835,12 +1756,10 @@ public Delta(string a, int b, bool v) : this(a, b) } } """); - } [Fact] - public async Task TestDelegateToSmallerConstructor3() - { - await TestInRegularAndScriptAsync( + public Task TestDelegateToSmallerConstructor3() + => TestInRegularAndScriptAsync( """ class A { @@ -1899,12 +1818,10 @@ public Delta(string v1, int v2, bool v) : base(v1, v2) } } """); - } [Fact] - public async Task TestDelegateToSmallerConstructor4() - { - await TestInRegularAndScriptAsync( + public Task TestDelegateToSmallerConstructor4() + => TestInRegularAndScriptAsync( """ class A { @@ -1955,12 +1872,10 @@ public Delta(string v1, int v2, bool v) : this(v1, v2) } } """); - } [Fact] - public async Task TestGenerateFromThisInitializer1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFromThisInitializer1() + => TestInRegularAndScriptAsync( """ class C { @@ -1984,12 +1899,10 @@ public C(int v) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44537")] - public async Task TestGenerateFromThisInitializer1_WithProperties() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFromThisInitializer1_WithProperties() + => TestInRegularAndScriptAsync( """ class C { @@ -2013,12 +1926,10 @@ public C(int v) public int V { get; } } """, index: 1); - } [Fact] - public async Task TestGenerateFromThisInitializer1_NoMembers() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFromThisInitializer1_NoMembers() + => TestInRegularAndScriptAsync( """ class C { @@ -2039,12 +1950,10 @@ public C(int v) } } """, index: 2); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910589")] - public async Task TestGenerateFromThisInitializer2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFromThisInitializer2() + => TestInRegularAndScriptAsync( """ class C { @@ -2065,12 +1974,10 @@ public C(int i) : this() } } """); - } [Fact] - public async Task TestGenerateFromBaseInitializer1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFromBaseInitializer1() + => TestInRegularAndScriptAsync( """ class C : B { @@ -2101,12 +2008,10 @@ public B(int i) } } """); - } [Fact] - public async Task TestGenerateFromBaseInitializer2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFromBaseInitializer2() + => TestInRegularAndScriptAsync( """ class C : B { @@ -2138,12 +2043,10 @@ public B(int i) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539969")] - public async Task TestNotOnExistingConstructor() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOnExistingConstructor() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2160,12 +2063,10 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539972")] - public async Task TestUnavailableTypeParameters() - { - await TestInRegularAndScriptAsync( + public Task TestUnavailableTypeParameters() + => TestInRegularAndScriptAsync( """ class C { @@ -2200,12 +2101,10 @@ public A(object t1, object t2) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539972")] - public async Task TestUnavailableTypeParameters_WithProperties() - { - await TestInRegularAndScriptAsync( + public Task TestUnavailableTypeParameters_WithProperties() + => TestInRegularAndScriptAsync( """ class C { @@ -2240,12 +2139,10 @@ public A(object t1, object t2) public object T2 { get; } } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539972")] - public async Task TestUnavailableTypeParameters_NoMembers() - { - await TestInRegularAndScriptAsync( + public Task TestUnavailableTypeParameters_NoMembers() + => TestInRegularAndScriptAsync( """ class C { @@ -2275,12 +2172,10 @@ public A(object t1, object t2) } } """, index: 2); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541020")] - public async Task TestGenerateCallToDefaultConstructorInStruct() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateCallToDefaultConstructorInStruct() + => TestInRegularAndScriptAsync( """ class Program { @@ -2325,12 +2220,10 @@ public Apartment(string v) : this() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541121")] - public async Task TestReadonlyFieldDelegation() - { - await TestInRegularAndScriptAsync( + public Task TestReadonlyFieldDelegation() + => TestInRegularAndScriptAsync( """ class C { @@ -2360,12 +2253,10 @@ void Test() } } """); - } [Fact] - public async Task TestNoGenerationIntoEntirelyHiddenType() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNoGenerationIntoEntirelyHiddenType() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2381,12 +2272,10 @@ class D } #line default """); - } [Fact] - public async Task TestNestedConstructorCall() - { - await TestInRegularAndScriptAsync( + public Task TestNestedConstructorCall() + => TestInRegularAndScriptAsync( """ class C { @@ -2429,12 +2318,10 @@ public D(D v) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530003")] - public async Task TestAttributesWithArgument() - { - await TestInRegularAndScriptAsync( + public Task TestAttributesWithArgument() + => TestInRegularAndScriptAsync( """ using System; @@ -2467,12 +2354,10 @@ class D { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530003")] - public async Task TestAttributesWithArgument_WithProperties() - { - await TestInRegularAndScriptAsync( + public Task TestAttributesWithArgument_WithProperties() + => TestInRegularAndScriptAsync( """ using System; @@ -2505,12 +2390,10 @@ class D { } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530003")] - public async Task TestAttributesWithArgument_NoMembers() - { - await TestInRegularAndScriptAsync( + public Task TestAttributesWithArgument_NoMembers() + => TestInRegularAndScriptAsync( """ using System; @@ -2540,12 +2423,10 @@ class D { } """, index: 2); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530003")] - public async Task TestAttributesWithMultipleArguments() - { - await TestInRegularAndScriptAsync( + public Task TestAttributesWithMultipleArguments() + => TestInRegularAndScriptAsync( """ using System; @@ -2582,12 +2463,10 @@ class D { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530003")] - public async Task TestAttributesWithNamedArguments() - { - await TestInRegularAndScriptAsync( + public Task TestAttributesWithNamedArguments() + => TestInRegularAndScriptAsync( """ using System; @@ -2624,12 +2503,10 @@ class D { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530003")] - public async Task TestAttributesWithAdditionalConstructors() - { - await TestInRegularAndScriptAsync( + public Task TestAttributesWithAdditionalConstructors() + => TestInRegularAndScriptAsync( """ using System; @@ -2676,12 +2553,10 @@ class D { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530003")] - public async Task TestAttributesWithOverloading() - { - await TestInRegularAndScriptAsync( + public Task TestAttributesWithOverloading() + => TestInRegularAndScriptAsync( """ using System; @@ -2726,12 +2601,10 @@ class D { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530003")] - public async Task TestAttributesWithOverloadingMultipleParameters() - { - await TestInRegularAndScriptAsync( + public Task TestAttributesWithOverloadingMultipleParameters() + => TestInRegularAndScriptAsync( """ using System; @@ -2782,12 +2655,10 @@ class D { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530003")] - public async Task TestAttributesWithDelegation() - { - await TestMissingInRegularAndScriptAsync( + public Task TestAttributesWithDelegation() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2803,12 +2674,10 @@ class D { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530003")] - public async Task TestAttributesWithLambda() - { - await TestMissingInRegularAndScriptAsync( + public Task TestAttributesWithLambda() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2822,12 +2691,10 @@ class D { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889349")] - public async Task TestConstructorGenerationForDifferentNamedParameter() - { - await TestInRegularAndScriptAsync( + public Task TestConstructorGenerationForDifferentNamedParameter() + => TestInRegularAndScriptAsync( """ class Program { @@ -2863,12 +2730,10 @@ public Program(int wde) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528257")] - public async Task TestGenerateInInaccessibleType() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInInaccessibleType() + => TestInRegularAndScriptAsync( """ class Goo { @@ -2907,12 +2772,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem(1241, @"https://github.com/dotnet/roslyn/issues/1241")] - public async Task TestGenerateConstructorInIncompleteLambda() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateConstructorInIncompleteLambda() + => TestInRegularAndScriptAsync( """ using System.Threading.Tasks; @@ -2944,12 +2807,10 @@ public C(int v) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/5274")] - public async Task TestGenerateIntoDerivedClassWithAbstractBase() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateIntoDerivedClassWithAbstractBase() + => TestInRegularAndScriptAsync( """ class Class1 { @@ -3002,12 +2863,10 @@ public Base(bool val = false) } } """); - } [Fact] - public async Task TestGenerateWithIncorrectConstructorArguments_Crash() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateWithIncorrectConstructorArguments_Crash() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -3049,12 +2908,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/9575")] - public async Task TestMissingOnMethodCall() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnMethodCall() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -3068,12 +2925,10 @@ public bool M(string s, int i, bool b) } } """); - } [Fact] - public async Task Tuple() - { - await TestInRegularAndScriptAsync( + public Task Tuple() + => TestInRegularAndScriptAsync( """ class C { @@ -3101,12 +2956,10 @@ void M() } } """); - } [Fact] - public async Task TupleWithNames() - { - await TestInRegularAndScriptAsync( + public Task TupleWithNames() + => TestInRegularAndScriptAsync( """ class C { @@ -3132,12 +2985,10 @@ void M() } } """); - } [Fact] - public async Task TupleWithOneName() - { - await TestInRegularAndScriptAsync( + public Task TupleWithOneName() + => TestInRegularAndScriptAsync( """ class C { @@ -3163,12 +3014,10 @@ void M() } } """); - } [Fact] - public async Task TupleAndExistingField() - { - await TestInRegularAndScriptAsync( + public Task TupleAndExistingField() + => TestInRegularAndScriptAsync( """ class C { @@ -3202,12 +3051,10 @@ public D((int, string) existing) } } """); - } [Fact] - public async Task TupleWithNamesAndExistingField() - { - await TestInRegularAndScriptAsync( + public Task TupleWithNamesAndExistingField() + => TestInRegularAndScriptAsync( """ class C { @@ -3241,12 +3088,10 @@ public D((int a, string b) existing) } } """); - } [Fact] - public async Task TupleWithDifferentNamesAndExistingField() - { - await TestInRegularAndScriptAsync( + public Task TupleWithDifferentNamesAndExistingField() + => TestInRegularAndScriptAsync( """ class C { @@ -3280,12 +3125,10 @@ public D((int a, string b) existing) } } """); - } [Fact] - public async Task TupleAndDelegatingConstructor() - { - await TestInRegularAndScriptAsync( + public Task TupleAndDelegatingConstructor() + => TestInRegularAndScriptAsync( """ class C { @@ -3329,12 +3172,10 @@ public D((int, string) x) : base(x) } } """); - } [Fact] - public async Task TupleWithNamesAndDelegatingConstructor() - { - await TestInRegularAndScriptAsync( + public Task TupleWithNamesAndDelegatingConstructor() + => TestInRegularAndScriptAsync( """ class C { @@ -3378,12 +3219,10 @@ public D((int a, string b) x) : base(x) } } """); - } [Fact] - public async Task TupleWithDifferentNamesAndDelegatingConstructor() - { - await TestInRegularAndScriptAsync( + public Task TupleWithDifferentNamesAndDelegatingConstructor() + => TestInRegularAndScriptAsync( """ class C { @@ -3427,13 +3266,11 @@ public D((int c, string d) x) : base(x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11563")] [WorkItem("https://github.com/dotnet/roslyn/issues/14077")] - public async Task StripUnderscoresFromParameterNames() - { - await TestInRegularAndScriptAsync( + public Task StripUnderscoresFromParameterNames() + => TestInRegularAndScriptAsync( """ class C { @@ -3474,12 +3311,10 @@ public D(int i, string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11563")] - public async Task DoNotStripSingleUnderscore() - { - await TestInRegularAndScriptAsync( + public Task DoNotStripSingleUnderscore() + => TestInRegularAndScriptAsync( """ class C { @@ -3516,12 +3351,10 @@ public D(int _) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/12147")] - public async Task TestOutVariableDeclaration_ImplicitlyTyped() - { - await TestInRegularAndScriptAsync( + public Task TestOutVariableDeclaration_ImplicitlyTyped() + => TestInRegularAndScriptAsync( """ class C { @@ -3545,12 +3378,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/12147")] - public async Task TestOutVariableDeclaration_ImplicitlyTyped_NamedArgument() - { - await TestInRegularAndScriptAsync( + public Task TestOutVariableDeclaration_ImplicitlyTyped_NamedArgument() + => TestInRegularAndScriptAsync( """ class C { @@ -3574,12 +3405,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/12147")] - public async Task TestOutVariableDeclaration_ExplicitlyTyped() - { - await TestInRegularAndScriptAsync( + public Task TestOutVariableDeclaration_ExplicitlyTyped() + => TestInRegularAndScriptAsync( """ class C { @@ -3603,12 +3432,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/12147")] - public async Task TestOutVariableDeclaration_ExplicitlyTyped_NamedArgument() - { - await TestInRegularAndScriptAsync( + public Task TestOutVariableDeclaration_ExplicitlyTyped_NamedArgument() + => TestInRegularAndScriptAsync( """ class C { @@ -3632,12 +3459,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/12182")] - public async Task TestOutVariableDeclaration_ImplicitlyTyped_CSharp6() - { - await TestAsync( + public Task TestOutVariableDeclaration_ImplicitlyTyped_CSharp6() + => TestAsync( """ class C { @@ -3661,13 +3486,11 @@ void M() } } """, -parseOptions: TestOptions.Regular.WithLanguageVersion(CodeAnalysis.CSharp.LanguageVersion.CSharp6)); - } + parseOptions: TestOptions.Regular.WithLanguageVersion(CodeAnalysis.CSharp.LanguageVersion.CSharp6)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/12182")] - public async Task TestOutVariableDeclaration_ImplicitlyTyped_NamedArgument_CSharp6() - { - await TestAsync( + public Task TestOutVariableDeclaration_ImplicitlyTyped_NamedArgument_CSharp6() + => TestAsync( """ class C { @@ -3691,13 +3514,11 @@ void M() } } """, -parseOptions: TestOptions.Regular.WithLanguageVersion(CodeAnalysis.CSharp.LanguageVersion.CSharp6)); - } + parseOptions: TestOptions.Regular.WithLanguageVersion(CodeAnalysis.CSharp.LanguageVersion.CSharp6)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/12182")] - public async Task TestOutVariableDeclaration_ExplicitlyTyped_CSharp6() - { - await TestAsync( + public Task TestOutVariableDeclaration_ExplicitlyTyped_CSharp6() + => TestAsync( """ class C { @@ -3721,13 +3542,11 @@ void M() } } """, -parseOptions: TestOptions.Regular.WithLanguageVersion(CodeAnalysis.CSharp.LanguageVersion.CSharp6)); - } + parseOptions: TestOptions.Regular.WithLanguageVersion(CodeAnalysis.CSharp.LanguageVersion.CSharp6)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/12182")] - public async Task TestOutVariableDeclaration_ExplicitlyTyped_NamedArgument_CSharp6() - { - await TestAsync( + public Task TestOutVariableDeclaration_ExplicitlyTyped_NamedArgument_CSharp6() + => TestAsync( """ class C { @@ -3751,13 +3570,11 @@ void M() } } """, -parseOptions: TestOptions.Regular.WithLanguageVersion(CodeAnalysis.CSharp.LanguageVersion.CSharp6)); - } + parseOptions: TestOptions.Regular.WithLanguageVersion(CodeAnalysis.CSharp.LanguageVersion.CSharp6)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/13749")] - public async Task Support_Readonly_Properties() - { - await TestInRegularAndScriptAsync( + public Task Support_Readonly_Properties() + => TestInRegularAndScriptAsync( """ class C { public int Prop { get ; } @@ -3787,12 +3604,10 @@ static void M ( ) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21692")] - public async Task TestDelegateConstructor1() - { - await TestInRegularAndScriptAsync( + public Task TestDelegateConstructor1() + => TestInRegularAndScriptAsync( """ class A { @@ -3818,12 +3633,10 @@ public A(int a, int v) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21692")] - public async Task TestDelegateConstructor2() - { - await TestInRegularAndScriptAsync( + public Task TestDelegateConstructor2() + => TestInRegularAndScriptAsync( """ class C { @@ -3847,12 +3660,10 @@ public C(int x, int y) : this(x) public C(int x, int y, int z) : this(x, y) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21692")] - public async Task TestDelegateConstructor3() - { - await TestInRegularAndScriptAsync( + public Task TestDelegateConstructor3() + => TestInRegularAndScriptAsync( """ class C { @@ -3878,12 +3689,10 @@ public C(int x, int y) public C(int x, int y, int z) : this(x, y) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21692")] - public async Task TestDelegateConstructor4() - { - await TestInRegularAndScriptAsync( + public Task TestDelegateConstructor4() + => TestInRegularAndScriptAsync( """ class C { @@ -3911,12 +3720,10 @@ public C(int x, int y, int v) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21692")] - public async Task TestDelegateConstructor5() - { - await TestInRegularAndScriptAsync( + public Task TestDelegateConstructor5() + => TestInRegularAndScriptAsync( """ class C { @@ -3945,66 +3752,60 @@ public C(int a, int y, int z) : this(a) public C(int x, int y, int z, int e) : this(x, y, z) { } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/22293")] [InlineData("void")] [InlineData("int")] - public async Task TestMethodGroupWithMissingSystemActionAndFunc(string returnType) - { - await TestInRegularAndScriptAsync( -$@" - - - - - -", -$@" -class C -{{ - void M() - {{ - new Class(Method); - }} - - {returnType} Method() - {{ - }} -}} - -internal class Class -{{ - private object method; - - public Class(object method) - {{ - this.method = method; - }} -}} -"); - } + public Task TestMethodGroupWithMissingSystemActionAndFunc(string returnType) + => TestInRegularAndScriptAsync( + $$""" + + + + + + """, + $$""" + class C + { + void M() + { + new Class(Method); + } + + {{returnType}} Method() + { + } + } + + internal class Class + { + private object method; + + public Class(object method) + { + this.method = method; + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14077")] - public async Task TestGenerateFieldNoNamingStyle() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldNoNamingStyle() + => TestInRegularAndScriptAsync( """ class Program { @@ -4032,12 +3833,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14077")] - public async Task TestGenerateFieldDefaultNamingStyle() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldDefaultNamingStyle() + => TestInRegularAndScriptAsync( """ class Program { @@ -4065,12 +3864,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14077")] - public async Task TestGenerateFieldWithNamingStyle() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldWithNamingStyle() + => TestInRegularAndScriptAsync( """ class Program { @@ -4098,12 +3895,10 @@ static void Main(string[] args) } } """, options: options.FieldNamesAreCamelCaseWithUnderscorePrefix); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14077")] - public async Task TestFieldWithNamingStyleAlreadyExists() - { - await TestInRegularAndScriptAsync( + public Task TestFieldWithNamingStyleAlreadyExists() + => TestInRegularAndScriptAsync( """ class Program { @@ -4133,12 +3928,10 @@ static void Main(string[] args) } } """, options: options.FieldNamesAreCamelCaseWithUnderscorePrefix); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14077")] - public async Task TestFieldAndParameterNamingStyles() - { - await TestInRegularAndScriptAsync( + public Task TestFieldAndParameterNamingStyles() + => TestInRegularAndScriptAsync( """ class Program { @@ -4166,12 +3959,10 @@ static void Main(string[] args) } } """, options: options.MergeStyles(options.FieldNamesAreCamelCaseWithUnderscorePrefix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefix)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14077")] - public async Task TestAttributeArgumentWithNamingRules() - { - await TestInRegularAndScriptAsync( + public Task TestAttributeArgumentWithNamingRules() + => TestInRegularAndScriptAsync( """ using System; @@ -4204,7 +3995,6 @@ class D { } """, options: options.MergeStyles(options.FieldNamesAreCamelCaseWithUnderscorePrefix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefix)); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/33673")] [InlineData("_s", "s")] @@ -4213,40 +4003,39 @@ class D [InlineData("m_S", "s")] [InlineData("s_s", "s")] [InlineData("t_s", "s")] - public async Task GenerateConstructor_ArgumentHasCommonPrefix(string argumentName, string fieldName) - { - await TestInRegularAndScriptAsync( -$@" -class Program -{{ - static void Main(string[] args) - {{ - string {argumentName} = ""; - new Prog[||]ram({argumentName}); - }} -}}", -$@" -class Program -{{ - private string {fieldName}; - - public Program(string {fieldName}) - {{ - this.{fieldName} = {fieldName}; - }} - - static void Main(string[] args) - {{ - string {argumentName} = ""; - new Program({argumentName}); - }} -}}"); - } + public Task GenerateConstructor_ArgumentHasCommonPrefix(string argumentName, string fieldName) + => TestInRegularAndScriptAsync( + $$""" + class Program + { + static void Main(string[] args) + { + string {{argumentName}} = "; + new Prog[||]ram({{argumentName}}); + } + } + """, + $$""" + class Program + { + private string {{fieldName}}; + + public Program(string {{fieldName}}) + { + this.{{fieldName}} = {{fieldName}}; + } + + static void Main(string[] args) + { + string {{argumentName}} = "; + new Program({{argumentName}}); + } + } + """); [Fact] - public async Task TestWithTopLevelNullability() - { - await TestInRegularAndScriptAsync( + public Task TestWithTopLevelNullability() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -4278,12 +4067,10 @@ void M() } } """); - } [Fact] - public async Task TestWithNestedNullability() - { - await TestInRegularAndScriptAsync( + public Task TestWithNestedNullability() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -4319,12 +4106,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45808")] - public async Task TestWithUnsafe_Field() - { - await TestInRegularAndScriptAsync( + public Task TestWithUnsafe_Field() + => TestInRegularAndScriptAsync( """ class C { @@ -4350,12 +4135,10 @@ unsafe void M(int* x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45808")] - public async Task TestWithUnsafe_Property() - { - await TestInRegularAndScriptAsync( + public Task TestWithUnsafe_Property() + => TestInRegularAndScriptAsync( """ class C { @@ -4381,12 +4164,10 @@ unsafe void M(int* x) } } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45808")] - public async Task TestWithUnsafeInUnsafeClass_Field() - { - await TestInRegularAndScriptAsync( + public Task TestWithUnsafeInUnsafeClass_Field() + => TestInRegularAndScriptAsync( """ unsafe class C { @@ -4412,12 +4193,10 @@ void M(int* x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45808")] - public async Task TestWithUnsafeInUnsafeClass_Property() - { - await TestInRegularAndScriptAsync( + public Task TestWithUnsafeInUnsafeClass_Property() + => TestInRegularAndScriptAsync( """ unsafe class C { @@ -4443,12 +4222,10 @@ void M(int* x) } } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45808")] - public async Task TestUnsafeDelegateConstructor() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafeDelegateConstructor() + => TestInRegularAndScriptAsync( """ class A { @@ -4472,12 +4249,10 @@ public unsafe A(int* a, int b) : this(a) public unsafe A(int* a, int b, int c) : this(a, b) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45808")] - public async Task TestUnsafeDelegateConstructorInUnsafeClass() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafeDelegateConstructorInUnsafeClass() + => TestInRegularAndScriptAsync( """ unsafe class A { @@ -4501,12 +4276,10 @@ public A(int* a, int b) : this(a) public A(int* a, int b, int c) : this(a, b) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44708")] - public async Task TestDoNotGenerateNameFromTypeArgumentIfNotEnumerable() - { - await TestInRegularAndScriptAsync( + public Task TestDoNotGenerateNameFromTypeArgumentIfNotEnumerable() + => TestInRegularAndScriptAsync( """ class Frog { } @@ -4536,12 +4309,10 @@ C M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44708")] - public async Task TestGenerateNameFromTypeArgumentForTupleType() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateNameFromTypeArgumentForTupleType() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4569,12 +4340,10 @@ public C(List<(int, string)> list) C M() => new C(new List<(int, string)>()); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47928")] - public async Task TestGenerateConstructorFromImplicitObjectCreation() - { - await TestInRegularAndScriptAsync(""" + public Task TestGenerateConstructorFromImplicitObjectCreation() + => TestInRegularAndScriptAsync(""" namespace N { public class B @@ -4611,12 +4380,10 @@ public C(int v) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47928")] - public async Task TestGenerateConstructorFromImplicitObjectCreation_Properties() - { - await TestInRegularAndScriptAsync(""" + public Task TestGenerateConstructorFromImplicitObjectCreation_Properties() + => TestInRegularAndScriptAsync(""" namespace N { public class B @@ -4653,12 +4420,10 @@ public C(int v) } } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47928")] - public async Task TestGenerateConstructorFromImplicitObjectCreation_NoField() - { - await TestInRegularAndScriptAsync(""" + public Task TestGenerateConstructorFromImplicitObjectCreation_NoField() + => TestInRegularAndScriptAsync(""" namespace N { public class B @@ -4692,12 +4457,10 @@ public C(int v) } } """, index: 2); - } [Fact] - public async Task TestGenerateConstructorFromImplicitObjectCreation_Delegating() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateConstructorFromImplicitObjectCreation_Delegating() + => TestInRegularAndScriptAsync( """ class C { @@ -4741,7 +4504,6 @@ public D(int x) : base(x) } } """); - } [Fact] public async Task TestGenerateConstructorFromImplicitObjectCreation_DelegatingFromParameter() @@ -4797,9 +4559,8 @@ public D(int x) : base(x) } [Fact] - public async Task TestDelegateWithLambda1() - { - await TestInRegularAndScriptAsync( + public Task TestDelegateWithLambda1() + => TestInRegularAndScriptAsync( """ using System; @@ -4843,12 +4604,10 @@ public Delta(Func f, int v) : this(f) } } """); - } [Fact] - public async Task TestDelegateWithLambda2() - { - await TestInRegularAndScriptAsync( + public Task TestDelegateWithLambda2() + => TestInRegularAndScriptAsync( """ using System; @@ -4889,14 +4648,10 @@ public Delta(Func f, int v) : base(f) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50765")] - public async Task TestDelegateConstructorWithMissingType() - { - // CSharpProjectWithExtraType is added as a project reference to CSharpProjectGeneratingInto - // but not at the place we're actually invoking the fix. - await TestAsync(""" + public Task TestDelegateConstructorWithMissingType() + => TestAsync(""" @@ -4942,12 +4697,10 @@ public C(int v1, int v2) } } """, parseOptions: TestOptions.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38822")] - public async Task TestMissingInLambdaWithCallToExistingConstructor() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingInLambdaWithCallToExistingConstructor() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4968,14 +4721,12 @@ public static void Test() } } """); - } #if !CODE_STYLE [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530003")] - public async Task TestAttributesWithAllValidParameters() - { - await TestInRegularAndScriptAsync( + public Task TestAttributesWithAllValidParameters() + => TestInRegularAndScriptAsync( """ using System; @@ -5038,12 +4789,10 @@ class D { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44708")] - public async Task TestGenerateNameFromTypeArgument() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateNameFromTypeArgument() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -5071,12 +4820,10 @@ public C(List frogs) C M() => new C(new List()); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44708")] - public async Task TestGenerateNameFromTypeArgumentForErrorType() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateNameFromTypeArgumentForErrorType() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -5104,12 +4851,10 @@ public C(List ts) C M() => new C(new List<>()); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44708")] - public async Task TestGenerateNameFromTypeArgumentInNamespace() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateNameFromTypeArgumentInNamespace() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -5141,7 +4886,6 @@ public C(List frogs) } } """); - } #endif } diff --git a/src/Analyzers/CSharp/Tests/GenerateDefaultConstructors/GenerateDefaultConstructorsTests.cs b/src/Analyzers/CSharp/Tests/GenerateDefaultConstructors/GenerateDefaultConstructorsTests.cs index b0c5d8d17feab..6a6d9a2dd5386 100644 --- a/src/Analyzers/CSharp/Tests/GenerateDefaultConstructors/GenerateDefaultConstructorsTests.cs +++ b/src/Analyzers/CSharp/Tests/GenerateDefaultConstructors/GenerateDefaultConstructorsTests.cs @@ -38,27 +38,24 @@ private static async Task TestRefactoringAsync( await TestCodeFixMissingAsync(source); } - private static async Task TestRefactoringOnlyAsync( + private static Task TestRefactoringOnlyAsync( [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string source, [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string fixedSource, int index = 0) - { - await new VerifyRefactoring.Test + => new VerifyRefactoring.Test { TestCode = source, FixedCode = fixedSource, CodeActionIndex = index, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } #endif - private static async Task TestCodeFixAsync( + private static Task TestCodeFixAsync( [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string source, [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string fixedSource, int index = 0) - { - await new VerifyCodeFix.Test + => new VerifyCodeFix.Test { TestCode = source.Replace("[||]", ""), FixedCode = fixedSource, @@ -67,20 +64,14 @@ private static async Task TestCodeFixAsync( }.RunAsync(); #if !CODE_STYLE - await TestRefactoringMissingAsync(source); -#endif - } -#if !CODE_STYLE - private static async Task TestRefactoringMissingAsync( + private static Task TestRefactoringMissingAsync( [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string source) - { - await new VerifyRefactoring.Test + => new VerifyRefactoring.Test { TestCode = source, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } #endif private static async Task TestCodeFixMissingAsync( @@ -95,9 +86,8 @@ private static async Task TestCodeFixMissingAsync( } [Fact] - public async Task TestProtectedBase() - { - await TestCodeFixAsync( + public Task TestProtectedBase() + => TestCodeFixAsync( """ class {|CS7036:C|} : [||]B { @@ -125,12 +115,10 @@ protected B(int x) } } """); - } [Fact] - public async Task TestPublicBase() - { - await TestCodeFixAsync( + public Task TestPublicBase() + => TestCodeFixAsync( """ class {|CS7036:C|} : [||]B { @@ -158,12 +146,10 @@ public B(int x) } } """); - } [Fact] - public async Task TestInternalBase() - { - await TestCodeFixAsync( + public Task TestInternalBase() + => TestCodeFixAsync( """ class {|CS7036:C|} : [||]B { @@ -191,12 +177,10 @@ internal B(int x) } } """); - } [Fact] - public async Task TestRefOutParams() - { - await TestCodeFixAsync( + public Task TestRefOutParams() + => TestCodeFixAsync( """ class {|CS7036:C|} : [||]B { @@ -226,12 +210,10 @@ internal B(ref int x, out string s, params bool[] b) } } """); - } [Fact] - public async Task TestFix1() - { - await TestCodeFixAsync( + public Task TestFix1() + => TestCodeFixAsync( """ class {|CS1729:C|} : [||]B { @@ -275,12 +257,10 @@ public B(bool x) } } """); - } [Fact] - public async Task TestFix2() - { - await TestCodeFixAsync( + public Task TestFix2() + => TestCodeFixAsync( """ class {|CS1729:C|} : [||]B { @@ -324,13 +304,11 @@ public B(bool x) } } """, -index: 1); - } + index: 1); [Fact] - public async Task TestRefactoring1() - { - await TestCodeFixAsync( + public Task TestRefactoring1() + => TestCodeFixAsync( """ class {|CS1729:C|} : [||]B { @@ -374,13 +352,11 @@ public B(bool x) } } """, -index: 2); - } + index: 2); [Fact] - public async Task TestFixAll1() - { - await TestCodeFixAsync( + public Task TestFixAll1() + => TestCodeFixAsync( """ class {|CS1729:C|} : [||]B { @@ -432,13 +408,11 @@ public B(bool x) } } """, -index: 3); - } + index: 3); [Fact, CompilerTrait(CompilerFeature.Tuples)] - public async Task Tuple() - { - await TestCodeFixAsync( + public Task Tuple() + => TestCodeFixAsync( """ class {|CS7036:C|} : [||]B { @@ -466,12 +440,10 @@ public B((int, string) x) } } """); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] - public async Task TupleWithNames() - { - await TestCodeFixAsync( + public Task TupleWithNames() + => TestCodeFixAsync( """ class {|CS7036:C|} : [||]B { @@ -499,12 +471,10 @@ public B((int a, string b) x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/Roslyn/issues/6541")] - public async Task TestGenerateFromDerivedClass() - { - await TestCodeFixAsync( + public Task TestGenerateFromDerivedClass() + => TestCodeFixAsync( """ class Base { @@ -532,12 +502,10 @@ public Derived(string value) : base(value) } } """); - } [Fact, WorkItem("https://github.com/dotnet/Roslyn/issues/6541")] - public async Task TestGenerateFromDerivedClass2() - { - await TestCodeFixAsync( + public Task TestGenerateFromDerivedClass2() + => TestCodeFixAsync( """ class Base { @@ -565,12 +533,10 @@ public Derived(int a, string value = null) : base(a, value) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25238")] - public async Task TestGenerateConstructorFromProtectedConstructor() - { - await TestCodeFixAsync( + public Task TestGenerateConstructorFromProtectedConstructor() + => TestCodeFixAsync( """ abstract class {|CS7036:C|} : [||]B { @@ -598,12 +564,10 @@ protected B(int x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25238")] - public async Task TestGenerateConstructorFromProtectedConstructor2() - { - await TestCodeFixAsync( + public Task TestGenerateConstructorFromProtectedConstructor2() + => TestCodeFixAsync( """ class {|CS7036:C|} : [||]B { @@ -631,13 +595,11 @@ protected B(int x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35208")] [WorkItem("https://github.com/dotnet/roslyn/issues/25238")] - public async Task TestGenerateConstructorInAbstractClassFromPublicConstructor() - { - await TestCodeFixAsync( + public Task TestGenerateConstructorInAbstractClassFromPublicConstructor() + => TestCodeFixAsync( """ abstract class {|CS7036:C|} : [||]B { @@ -665,12 +627,10 @@ public B(int x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25238")] - public async Task TestGenerateConstructorFromPublicConstructor2() - { - await TestCodeFixAsync( + public Task TestGenerateConstructorFromPublicConstructor2() + => TestCodeFixAsync( """ class {|CS7036:C|} : [||]B { @@ -698,12 +658,10 @@ public B(int x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25238")] - public async Task TestGenerateConstructorFromInternalConstructor() - { - await TestCodeFixAsync( + public Task TestGenerateConstructorFromInternalConstructor() + => TestCodeFixAsync( """ abstract class {|CS7036:C|} : [||]B { @@ -731,12 +689,10 @@ internal B(int x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25238")] - public async Task TestGenerateConstructorFromInternalConstructor2() - { - await TestCodeFixAsync( + public Task TestGenerateConstructorFromInternalConstructor2() + => TestCodeFixAsync( """ class {|CS7036:C|} : [||]B { @@ -764,12 +720,10 @@ internal B(int x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25238")] - public async Task TestGenerateConstructorFromProtectedInternalConstructor() - { - await TestCodeFixAsync( + public Task TestGenerateConstructorFromProtectedInternalConstructor() + => TestCodeFixAsync( """ abstract class {|CS7036:C|} : [||]B { @@ -797,12 +751,10 @@ protected internal B(int x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25238")] - public async Task TestGenerateConstructorFromProtectedInternalConstructor2() - { - await TestCodeFixAsync( + public Task TestGenerateConstructorFromProtectedInternalConstructor2() + => TestCodeFixAsync( """ class {|CS7036:C|} : [||]B { @@ -830,12 +782,10 @@ protected internal B(int x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25238")] - public async Task TestGenerateConstructorFromPrivateProtectedConstructor() - { - await TestCodeFixAsync( + public Task TestGenerateConstructorFromPrivateProtectedConstructor() + => TestCodeFixAsync( """ abstract class {|CS7036:C|} : [||]B { @@ -863,12 +813,10 @@ private protected B(int x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25238")] - public async Task TestGenerateConstructorFromPrivateProtectedConstructor2() - { - await TestCodeFixAsync( + public Task TestGenerateConstructorFromPrivateProtectedConstructor2() + => TestCodeFixAsync( """ class {|CS7036:C|} : [||]B { @@ -896,12 +844,10 @@ abstract class B } } """); - } [Fact] - public async Task TestRecord() - { - await TestCodeFixAsync( + public Task TestRecord() + => TestCodeFixAsync( """ record {|CS1729:C|} : [||]B { @@ -929,7 +875,6 @@ public B(int x) } } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58593")] public async Task TestStructWithFieldInitializer() @@ -940,7 +885,10 @@ struct [||]{|CS8983:S|} object X = 1; } """; - var fixedSource = """ + await new VerifyCodeFix.Test + { + TestCode = source.Replace("[||]", ""), + FixedCode = """ struct S { object X = 1; @@ -949,12 +897,7 @@ public S() { } } - """; - - await new VerifyCodeFix.Test - { - TestCode = source.Replace("[||]", ""), - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); @@ -972,7 +915,6 @@ struct [||]S object X; } """; - await TestCodeFixMissingAsync(source); #if !CODE_STYLE @@ -983,9 +925,8 @@ struct [||]S [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/19611")] [InlineData("public")] [InlineData("protected")] - public async Task TestAttributeReferenceInBaseType1(string accessibility) - { - await TestCodeFixAsync( + public Task TestAttributeReferenceInBaseType1(string accessibility) + => TestCodeFixAsync( $$""" using System; @@ -1038,12 +979,10 @@ public Derived([Bar] string goo) : base(goo) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19611")] - public async Task TestAttributeReferenceInBaseType2() - { - await TestCodeFixAsync( + public Task TestAttributeReferenceInBaseType2() + => TestCodeFixAsync( """ using System; @@ -1096,14 +1035,12 @@ public Derived(string goo) : base(goo) } } """); - } #if !CODE_STYLE [Fact] - public async Task TestPrivateBase() - { - await TestRefactoringMissingAsync( + public Task TestPrivateBase() + => TestRefactoringMissingAsync( """ class {|CS1729:C|} : [||]B { @@ -1116,12 +1053,10 @@ private B(int x) } } """); - } [Fact] - public async Task TestFixAll2() - { - await TestRefactoringAsync( + public Task TestFixAll2() + => TestRefactoringAsync( """ class C : [||]B { @@ -1176,13 +1111,11 @@ public B(bool x) } } """, -index: 2); - } + index: 2); [Fact] - public async Task TestFixAll_WithTuples() - { - await TestRefactoringAsync( + public Task TestFixAll_WithTuples() + => TestRefactoringAsync( """ class C : [||]B { @@ -1237,13 +1170,11 @@ public B((bool, bool) x) } } """, -index: 2); - } + index: 2); [Fact] - public async Task TestMissing1() - { - await TestRefactoringMissingAsync( + public Task TestMissing1() + => TestRefactoringMissingAsync( """ class C : [||]B { @@ -1259,12 +1190,10 @@ internal B(int x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889349")] - public async Task TestDefaultConstructorGeneration_1() - { - await TestRefactoringAsync( + public Task TestDefaultConstructorGeneration_1() + => TestRefactoringAsync( """ class C : [||]B { @@ -1299,12 +1228,10 @@ internal B(int x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889349")] - public async Task TestDefaultConstructorGeneration_2() - { - await TestRefactoringAsync( + public Task TestDefaultConstructorGeneration_2() + => TestRefactoringAsync( """ class C : [||]B { @@ -1339,12 +1266,10 @@ internal B(int x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544070")] - public async Task TestException1() - { - await TestRefactoringAsync( + public Task TestException1() + => TestRefactoringAsync( """ using System; class Program : Excep[||]tion @@ -1373,13 +1298,11 @@ protected Program(SerializationInfo info, StreamingContext context) : base(info, } } """, -index: 4); - } + index: 4); [Fact] - public async Task TestException2() - { - await TestRefactoringAsync( + public Task TestException2() + => TestRefactoringAsync( """ using System; using System.Collections.Generic; @@ -1425,13 +1348,11 @@ static void Main(string[] args) } } """, -index: 3); - } + index: 3); [Fact] - public async Task TestException3() - { - await TestRefactoringAsync( + public Task TestException3() + => TestRefactoringAsync( """ using System; using System.Collections.Generic; @@ -1484,12 +1405,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestException4() - { - await TestRefactoringAsync( + public Task TestException4() + => TestRefactoringAsync( """ using System; using System.Collections.Generic; @@ -1538,24 +1457,20 @@ static void Main(string[] args) } } """, -index: 2); - } + index: 2); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19953")] - public async Task TestNotOnEnum() - { - await TestRefactoringMissingAsync( + public Task TestNotOnEnum() + => TestRefactoringMissingAsync( """ enum [||]E { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48318")] - public async Task TestGenerateConstructorFromProtectedConstructorCursorAtTypeOpening() - { - await TestRefactoringOnlyAsync( + public Task TestGenerateConstructorFromProtectedConstructorCursorAtTypeOpening() + => TestRefactoringOnlyAsync( """ class {|CS7036:C|} : B { @@ -1586,12 +1501,10 @@ protected B(int x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48318")] - public async Task TestGenerateConstructorFromProtectedConstructorCursorBetweenTypeMembers() - { - await TestRefactoringOnlyAsync( + public Task TestGenerateConstructorFromProtectedConstructorCursorBetweenTypeMembers() + => TestRefactoringOnlyAsync( """ class {|CS7036:C|} : B { @@ -1627,12 +1540,10 @@ protected B(int x) } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40586")] - public async Task TestGenerateInternalConstructorInSealedClassForProtectedOrInternalBase() - { - await TestRefactoringAsync( + public Task TestGenerateInternalConstructorInSealedClassForProtectedOrInternalBase() + => TestRefactoringAsync( """ class Base { @@ -1660,12 +1571,10 @@ internal Program() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40586")] - public async Task TestGenerateInternalConstructorInSealedClassForProtectedAndInternalBase() - { - await TestRefactoringAsync( + public Task TestGenerateInternalConstructorInSealedClassForProtectedAndInternalBase() + => TestRefactoringAsync( """ class Base { @@ -1693,12 +1602,10 @@ internal Program() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40586")] - public async Task TestGeneratePublicConstructorInSealedClassForProtectedBase() - { - await TestRefactoringAsync( + public Task TestGeneratePublicConstructorInSealedClassForProtectedBase() + => TestRefactoringAsync( """ class Base { @@ -1726,12 +1633,10 @@ public Program() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51049")] - public async Task TestGenerateDefaultConstructorPreserveBinaryCompat1() - { - await TestRefactoringAsync( + public Task TestGenerateDefaultConstructorPreserveBinaryCompat1() + => TestRefactoringAsync( """ class Base { @@ -1767,12 +1672,10 @@ public Program() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51049")] - public async Task TestGenerateDefaultConstructorPreserveBinaryCompat2() - { - await TestRefactoringAsync( + public Task TestGenerateDefaultConstructorPreserveBinaryCompat2() + => TestRefactoringAsync( """ class Base { @@ -1813,7 +1716,6 @@ public Program(int i) : base(i) } """, index: 1); - } #endif } diff --git a/src/Analyzers/CSharp/Tests/GenerateEnumMember/GenerateEnumMemberTests.cs b/src/Analyzers/CSharp/Tests/GenerateEnumMember/GenerateEnumMemberTests.cs index 41acb6145d539..8c59d6e005587 100644 --- a/src/Analyzers/CSharp/Tests/GenerateEnumMember/GenerateEnumMemberTests.cs +++ b/src/Analyzers/CSharp/Tests/GenerateEnumMember/GenerateEnumMemberTests.cs @@ -21,1835 +21,1939 @@ internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProvide => (null, new GenerateEnumMemberCodeFixProvider()); [Fact] - public async Task TestEmptyEnum() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Red|]; - } -} - -enum Color -{ -}", -@"class Program -{ - void Main() - { - Color.Red; - } -} - -enum Color -{ - Red -}"); - } + public Task TestEmptyEnum() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Red|]; + } + } + + enum Color + { + } + """, + """ + class Program + { + void Main() + { + Color.Red; + } + } + + enum Color + { + Red + } + """); [Fact] - public async Task TestWithSingleMember() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Red -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Red, - Blue -}"); - } + public Task TestWithSingleMember() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Red + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Red, + Blue + } + """); [Fact] - public async Task TestWithExistingComma() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Red, -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Red, - Blue, -}"); - } + public Task TestWithExistingComma() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Red, + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Red, + Blue, + } + """); [Fact] - public async Task TestWithMultipleMembers() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Green|]; - } -} - -enum Color -{ - Red, - Blue -}", -@"class Program -{ - void Main() - { - Color.Green; - } -} - -enum Color -{ - Red, - Blue, - Green -}"); - } + public Task TestWithMultipleMembers() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Green|]; + } + } + + enum Color + { + Red, + Blue + } + """, + """ + class Program + { + void Main() + { + Color.Green; + } + } + + enum Color + { + Red, + Blue, + Green + } + """); [Fact] - public async Task TestWithZero() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Red = 0 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Red = 0, - Blue = 1 -}"); - } + public Task TestWithZero() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Red = 0 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Red = 0, + Blue = 1 + } + """); [Fact] - public async Task TestWithIntegralValue() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Red = 1 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Red = 1, - Blue = 2 -}"); - } + public Task TestWithIntegralValue() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Red = 1 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Red = 1, + Blue = 2 + } + """); [Fact] - public async Task TestWithSingleBitIntegral() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Red = 2 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Red = 2, - Blue = 4 -}"); - } + public Task TestWithSingleBitIntegral() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Red = 2 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Red = 2, + Blue = 4 + } + """); [Fact] - public async Task TestGenerateIntoGeometricSequence() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Red = 1, - Yellow = 2, - Green = 4 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Red = 1, - Yellow = 2, - Green = 4, - Blue = 8 -}"); - } + public Task TestGenerateIntoGeometricSequence() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Red = 1, + Yellow = 2, + Green = 4 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Red = 1, + Yellow = 2, + Green = 4, + Blue = 8 + } + """); [Fact] - public async Task TestWithSimpleSequence1() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Red = 1, - Green = 2 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Red = 1, - Green = 2, - Blue = 3 -}"); - } + public Task TestWithSimpleSequence1() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Red = 1, + Green = 2 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Red = 1, + Green = 2, + Blue = 3 + } + """); [Fact] - public async Task TestWithSimpleSequence2() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Yellow = 0, - Red = 1, - Green = 2 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Yellow = 0, - Red = 1, - Green = 2, - Blue = 3 -}"); - } + public Task TestWithSimpleSequence2() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Yellow = 0, + Red = 1, + Green = 2 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Yellow = 0, + Red = 1, + Green = 2, + Blue = 3 + } + """); [Fact] - public async Task TestWithNonZeroInteger() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Green = 5 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Green = 5, - Blue = 6 -}"); - } + public Task TestWithNonZeroInteger() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Green = 5 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Green = 5, + Blue = 6 + } + """); [Fact] - public async Task TestWithLeftShift0() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Green = 1 << 0 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Green = 1 << 0, - Blue = 1 << 1 -}"); - } + public Task TestWithLeftShift0() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Green = 1 << 0 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Green = 1 << 0, + Blue = 1 << 1 + } + """); [Fact] - public async Task TestWithLeftShift5() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Green = 1 << 5 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Green = 1 << 5, - Blue = 1 << 6 -}"); - } + public Task TestWithLeftShift5() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Green = 1 << 5 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Green = 1 << 5, + Blue = 1 << 6 + } + """); [Fact] - public async Task TestWithDifferentStyles() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Red = 2, - Green = 1 << 5 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Red = 2, - Green = 1 << 5, - Blue = 33 -}"); - } + public Task TestWithDifferentStyles() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Red = 2, + Green = 1 << 5 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Red = 2, + Green = 1 << 5, + Blue = 33 + } + """); [Fact] - public async Task TestBinary() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Red = 0b01 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Red = 0b01, - Blue = 0b10 -}"); - } + public Task TestBinary() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Red = 0b01 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Red = 0b01, + Blue = 0b10 + } + """); [Fact] - public async Task TestHex1() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Red = 0x1 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Red = 0x1, - Blue = 0x2 -}"); - } + public Task TestHex1() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Red = 0x1 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Red = 0x1, + Blue = 0x2 + } + """); [Fact] - public async Task TestHex9() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Red = 0x9 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Red = 0x9, - Blue = 0xA -}"); - } + public Task TestHex9() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Red = 0x9 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Red = 0x9, + Blue = 0xA + } + """); [Fact] - public async Task TestHexF() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Red = 0xF -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Red = 0xF, - Blue = 0x10 -}"); - } + public Task TestHexF() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Red = 0xF + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Red = 0xF, + Blue = 0x10 + } + """); [Fact] - public async Task TestGenerateAfterEnumWithIntegerMaxValue() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Red = int.MaxValue -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Red = int.MaxValue, - Blue = int.MinValue -}"); - } + public Task TestGenerateAfterEnumWithIntegerMaxValue() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Red = int.MaxValue + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Red = int.MaxValue, + Blue = int.MinValue + } + """); [Fact] - public async Task TestUnsigned16BitEnums() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color : ushort -{ - Red = 65535 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color : ushort -{ - Red = 65535, - Blue = 0 -}"); - } + public Task TestUnsigned16BitEnums() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color : ushort + { + Red = 65535 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color : ushort + { + Red = 65535, + Blue = 0 + } + """); [Fact] - public async Task TestGenerateEnumMemberOfTypeLong() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color : long -{ - Red = long.MaxValue -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color : long -{ - Red = long.MaxValue, - Blue = long.MinValue -}"); - } + public Task TestGenerateEnumMemberOfTypeLong() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color : long + { + Red = long.MaxValue + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color : long + { + Red = long.MaxValue, + Blue = long.MinValue + } + """); [Fact] - public async Task TestGenerateAfterEnumWithLongMaxValueInBinary() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color : long -{ - Red = 0b0111111111111111111111111111111111111111111111111111111111111111 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color : long -{ - Red = 0b0111111111111111111111111111111111111111111111111111111111111111, - Blue = 0b1000000000000000000000000000000000000000000000000000000000000000 -}"); - } + public Task TestGenerateAfterEnumWithLongMaxValueInBinary() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color : long + { + Red = 0b0111111111111111111111111111111111111111111111111111111111111111 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color : long + { + Red = 0b0111111111111111111111111111111111111111111111111111111111111111, + Blue = 0b1000000000000000000000000000000000000000000000000000000000000000 + } + """); [Fact] - public async Task TestGenerateAfterEnumWithLongMaxValueInHex() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color : long -{ - Red = 0x7FFFFFFFFFFFFFFF -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color : long -{ - Red = 0x7FFFFFFFFFFFFFFF, - Blue = 0x8000000000000000 -}"); - } + public Task TestGenerateAfterEnumWithLongMaxValueInHex() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color : long + { + Red = 0x7FFFFFFFFFFFFFFF + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color : long + { + Red = 0x7FFFFFFFFFFFFFFF, + Blue = 0x8000000000000000 + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528312")] - public async Task TestGenerateAfterEnumWithLongMinValueInHex() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color : long -{ - Red = 0xFFFFFFFFFFFFFFFF -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color : long -{ - Red = 0xFFFFFFFFFFFFFFFF, - Blue -}"); - } + public Task TestGenerateAfterEnumWithLongMinValueInHex() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color : long + { + Red = 0xFFFFFFFFFFFFFFFF + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color : long + { + Red = 0xFFFFFFFFFFFFFFFF, + Blue + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528312")] - public async Task TestGenerateAfterPositiveLongInHex() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color : long -{ - Red = 0xFFFFFFFFFFFFFFFF, - Green = 0x0 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color : long -{ - Red = 0xFFFFFFFFFFFFFFFF, - Green = 0x0, - Blue = 0x1 -}"); - } + public Task TestGenerateAfterPositiveLongInHex() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color : long + { + Red = 0xFFFFFFFFFFFFFFFF, + Green = 0x0 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color : long + { + Red = 0xFFFFFFFFFFFFFFFF, + Green = 0x0, + Blue = 0x1 + } + """); [Fact] - public async Task TestGenerateAfterPositiveLongExprInHex() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color : long -{ - Red = 0x414 / 2 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color : long -{ - Red = 0x414 / 2, - Blue = 523 -}"); - } + public Task TestGenerateAfterPositiveLongExprInHex() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color : long + { + Red = 0x414 / 2 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color : long + { + Red = 0x414 / 2, + Blue = 523 + } + """); [Fact] - public async Task TestGenerateAfterEnumWithULongMaxValue() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color : ulong -{ - Red = ulong.MaxValue -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color : ulong -{ - Red = ulong.MaxValue, - Blue = 0 -}"); - } + public Task TestGenerateAfterEnumWithULongMaxValue() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color : ulong + { + Red = ulong.MaxValue + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color : ulong + { + Red = ulong.MaxValue, + Blue = 0 + } + """); [Fact] - public async Task TestNegativeRangeIn64BitSignedEnums() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color : long -{ - Red = -10 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color : long -{ - Red = -10, - Blue = -9 -}"); - } + public Task TestNegativeRangeIn64BitSignedEnums() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color : long + { + Red = -10 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color : long + { + Red = -10, + Blue = -9 + } + """); [Fact] - public async Task TestGenerateWithImplicitValues() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Red, - Green, - Yellow = -1 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Red, - Green, - Yellow = -1, - Blue = 2 -}"); - } + public Task TestGenerateWithImplicitValues() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Red, + Green, + Yellow = -1 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Red, + Green, + Yellow = -1, + Blue = 2 + } + """); [Fact] - public async Task TestGenerateWithImplicitValues2() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Red, - Green = 10, - Yellow -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Red, - Green = 10, - Yellow, - Blue -}"); - } + public Task TestGenerateWithImplicitValues2() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Red, + Green = 10, + Yellow + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Red, + Green = 10, + Yellow, + Blue + } + """); [Fact] - public async Task TestNoExtraneousStatementTerminatorBeforeCommentedMember() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - static void Main(string[] args) - { - Color . [|Blue|] ; - } -} - -enum Color -{ - Red - //Blue -}", -@"class Program -{ - static void Main(string[] args) - { - Color . Blue ; - } -} - -enum Color -{ - Red, - Blue - //Blue -}"); - } + public Task TestNoExtraneousStatementTerminatorBeforeCommentedMember() + => TestInRegularAndScriptAsync( + """ + class Program + { + static void Main(string[] args) + { + Color . [|Blue|] ; + } + } + + enum Color + { + Red + //Blue + } + """, + """ + class Program + { + static void Main(string[] args) + { + Color . Blue ; + } + } + + enum Color + { + Red, + Blue + //Blue + } + """); [Fact] - public async Task TestNoExtraneousStatementTerminatorBeforeCommentedMember2() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - static void Main(string[] args) - { - Color . [|Blue|] ; - } -} - -enum Color -{ - Red - /*Blue*/ -}", -@"class Program -{ - static void Main(string[] args) - { - Color . Blue ; - } -} - -enum Color -{ - Red, - Blue - /*Blue*/ -}"); - } + public Task TestNoExtraneousStatementTerminatorBeforeCommentedMember2() + => TestInRegularAndScriptAsync( + """ + class Program + { + static void Main(string[] args) + { + Color . [|Blue|] ; + } + } + + enum Color + { + Red + /*Blue*/ + } + """, + """ + class Program + { + static void Main(string[] args) + { + Color . Blue ; + } + } + + enum Color + { + Red, + Blue + /*Blue*/ + } + """); [Fact] - public async Task TestGenerateAfterEnumWithMinValue() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Red = int.MinValue -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Red = int.MinValue, - Blue = -2147483647 -}"); - } + public Task TestGenerateAfterEnumWithMinValue() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Red = int.MinValue + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Red = int.MinValue, + Blue = -2147483647 + } + """); [Fact] - public async Task TestGenerateAfterEnumWithMinValuePlusConstant() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Red = int.MinValue + 100 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Red = int.MinValue + 100, - Blue = -2147483547 -}"); - } + public Task TestGenerateAfterEnumWithMinValuePlusConstant() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Red = int.MinValue + 100 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Red = int.MinValue + 100, + Blue = -2147483547 + } + """); [Fact] - public async Task TestGenerateAfterEnumWithByteMaxValue() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color : byte -{ - Red = 255 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color : byte -{ - Red = 255, - Blue = 0 -}"); - } + public Task TestGenerateAfterEnumWithByteMaxValue() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color : byte + { + Red = 255 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color : byte + { + Red = 255, + Blue = 0 + } + """); [Fact] - public async Task TestGenerateIntoBitshiftEnum1() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Red = 1 << 1, - Green = 1 << 2 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Red = 1 << 1, - Green = 1 << 2, - Blue = 1 << 3 -}"); - } + public Task TestGenerateIntoBitshiftEnum1() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Red = 1 << 1, + Green = 1 << 2 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Red = 1 << 1, + Green = 1 << 2, + Blue = 1 << 3 + } + """); [Fact] - public async Task TestGenerateIntoBitshiftEnum2() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Red = 2 >> 1 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Red = 2 >> 1, - Blue = 2 -}"); - } + public Task TestGenerateIntoBitshiftEnum2() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Red = 2 >> 1 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Red = 2 >> 1, + Blue = 2 + } + """); [Fact] - public async Task TestStandaloneReference() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Red = int.MinValue, - Green = 1 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Red = int.MinValue, - Green = 1, - Blue = 2 -}"); - } + public Task TestStandaloneReference() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Red = int.MinValue, + Green = 1 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Red = int.MinValue, + Green = 1, + Blue = 2 + } + """); [Fact] - public async Task TestCircularEnumsForErrorTolerance() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Circular.[|C|]; - } -} - -enum Circular -{ - A = B, - B -}", -@"class Program -{ - void Main() - { - Circular.C; - } -} - -enum Circular -{ - A = B, - B, - C -}"); - } + public Task TestCircularEnumsForErrorTolerance() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Circular.[|C|]; + } + } + + enum Circular + { + A = B, + B + } + """, + """ + class Program + { + void Main() + { + Circular.C; + } + } + + enum Circular + { + A = B, + B, + C + } + """); [Fact] - public async Task TestEnumWithIncorrectValueForErrorTolerance() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Circular.[|B|]; - } -} - -enum Circular : byte -{ - A = -2 -}", -@"class Program -{ - void Main() - { - Circular.B; - } -} - -enum Circular : byte -{ - A = -2, - B -}"); - } + public Task TestEnumWithIncorrectValueForErrorTolerance() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Circular.[|B|]; + } + } + + enum Circular : byte + { + A = -2 + } + """, + """ + class Program + { + void Main() + { + Circular.B; + } + } + + enum Circular : byte + { + A = -2, + B + } + """); [Fact] - public async Task TestGenerateIntoNewEnum() - { - await TestInRegularAndScriptAsync( -@"class B : A -{ - void Main() - { - BaseColor.[|Blue|]; - } - - public new enum BaseColor - { - Yellow = 3 - } -} - -class A -{ - public enum BaseColor - { - Red = 1, - Green = 2 - } -}", -@"class B : A -{ - void Main() - { - BaseColor.Blue; - } - - public new enum BaseColor - { - Yellow = 3, - Blue = 4 - } -} - -class A -{ - public enum BaseColor - { - Red = 1, - Green = 2 - } -}"); - } + public Task TestGenerateIntoNewEnum() + => TestInRegularAndScriptAsync( + """ + class B : A + { + void Main() + { + BaseColor.[|Blue|]; + } + + public new enum BaseColor + { + Yellow = 3 + } + } + + class A + { + public enum BaseColor + { + Red = 1, + Green = 2 + } + } + """, + """ + class B : A + { + void Main() + { + BaseColor.Blue; + } + + public new enum BaseColor + { + Yellow = 3, + Blue = 4 + } + } + + class A + { + public enum BaseColor + { + Red = 1, + Green = 2 + } + } + """); [Fact] - public async Task TestGenerateIntoDerivedEnumMissingNewKeyword() - { - await TestInRegularAndScriptAsync( -@"class B : A -{ - void Main() - { - BaseColor.[|Blue|]; - } - - public enum BaseColor - { - Yellow = 3 - } -} - -class A -{ - public enum BaseColor - { - Red = 1, - Green = 2 - } -}", -@"class B : A -{ - void Main() - { - BaseColor.Blue; - } - - public enum BaseColor - { - Yellow = 3, - Blue = 4 - } -} - -class A -{ - public enum BaseColor - { - Red = 1, - Green = 2 - } -}"); - } + public Task TestGenerateIntoDerivedEnumMissingNewKeyword() + => TestInRegularAndScriptAsync( + """ + class B : A + { + void Main() + { + BaseColor.[|Blue|]; + } + + public enum BaseColor + { + Yellow = 3 + } + } + + class A + { + public enum BaseColor + { + Red = 1, + Green = 2 + } + } + """, + """ + class B : A + { + void Main() + { + BaseColor.Blue; + } + + public enum BaseColor + { + Yellow = 3, + Blue = 4 + } + } + + class A + { + public enum BaseColor + { + Red = 1, + Green = 2 + } + } + """); [Fact] - public async Task TestGenerateIntoBaseEnum() - { - await TestInRegularAndScriptAsync( -@"class B : A -{ - void Main() - { - BaseColor.[|Blue|]; - } -} - -class A -{ - public enum BaseColor - { - Red = 1, - Green = 2 - } -}", -@"class B : A -{ - void Main() - { - BaseColor.Blue; - } -} - -class A -{ - public enum BaseColor - { - Red = 1, - Green = 2, - Blue = 3 - } -}"); - } + public Task TestGenerateIntoBaseEnum() + => TestInRegularAndScriptAsync( + """ + class B : A + { + void Main() + { + BaseColor.[|Blue|]; + } + } + + class A + { + public enum BaseColor + { + Red = 1, + Green = 2 + } + } + """, + """ + class B : A + { + void Main() + { + BaseColor.Blue; + } + } + + class A + { + public enum BaseColor + { + Red = 1, + Green = 2, + Blue = 3 + } + } + """); [Fact] - public async Task TestGenerationWhenMembersShareValues() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color -{ - Red, - Green, - Yellow = Green -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color -{ - Red, - Green, - Yellow = Green, - Blue = 2 -}"); - } + public Task TestGenerationWhenMembersShareValues() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color + { + Red, + Green, + Yellow = Green + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color + { + Red, + Green, + Yellow = Green, + Blue = 2 + } + """); [Fact] - public async Task TestInvokeFromAddAssignmentStatement() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - int a = 1; - a += Color.[|Blue|]; - } -} - -enum Color -{ - Red, - Green = 10, - Yellow -}", -@"class Program -{ - void Main() - { - int a = 1; - a += Color.Blue; - } -} - -enum Color -{ - Red, - Green = 10, - Yellow, - Blue -}"); - } + public Task TestInvokeFromAddAssignmentStatement() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + int a = 1; + a += Color.[|Blue|]; + } + } + + enum Color + { + Red, + Green = 10, + Yellow + } + """, + """ + class Program + { + void Main() + { + int a = 1; + a += Color.Blue; + } + } + + enum Color + { + Red, + Green = 10, + Yellow, + Blue + } + """); [Fact] - public async Task TestFormatting() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - static void Main(string[] args) - { - Weekday.[|Tuesday|]; - } -} -enum Weekday -{ - Monday -}", -@"class Program -{ - static void Main(string[] args) - { - Weekday.Tuesday; - } -} -enum Weekday -{ - Monday, - Tuesday -}"); - } + public Task TestFormatting() + => TestInRegularAndScriptAsync( + """ + class Program + { + static void Main(string[] args) + { + Weekday.[|Tuesday|]; + } + } + enum Weekday + { + Monday + } + """, + """ + class Program + { + static void Main(string[] args) + { + Weekday.Tuesday; + } + } + enum Weekday + { + Monday, + Tuesday + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540919")] - public async Task TestKeyword() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - static void Main(string[] args) - { - Color.[|@enum|]; - } -} - -enum Color -{ - Red -}", -@"class Program -{ - static void Main(string[] args) - { - Color.@enum; - } -} - -enum Color -{ - Red, - @enum -}"); - } + public Task TestKeyword() + => TestInRegularAndScriptAsync( + """ + class Program + { + static void Main(string[] args) + { + Color.[|@enum|]; + } + } + + enum Color + { + Red + } + """, + """ + class Program + { + static void Main(string[] args) + { + Color.@enum; + } + } + + enum Color + { + Red, + @enum + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544333")] - public async Task TestNotAfterPointer() - { - await TestMissingInRegularAndScriptAsync( -@"struct MyStruct -{ - public int MyField; -} - -class Program -{ - static unsafe void Main(string[] args) - { - MyStruct s = new MyStruct(); - MyStruct* ptr = &s; - var i1 = (() => &s)->[|M|]; - } -}"); - } + public Task TestNotAfterPointer() + => TestMissingInRegularAndScriptAsync( + """ + struct MyStruct + { + public int MyField; + } + + class Program + { + static unsafe void Main(string[] args) + { + MyStruct s = new MyStruct(); + MyStruct* ptr = &s; + var i1 = (() => &s)->[|M|]; + } + } + """); [Fact] - public async Task TestMissingOnHiddenEnum() - { - await TestMissingInRegularAndScriptAsync( -@"using System; - -enum E -{ -#line hidden -} -#line default - -class Program -{ - void Main() - { - Console.WriteLine(E.[|x|]); - } -}"); - } + public Task TestMissingOnHiddenEnum() + => TestMissingInRegularAndScriptAsync( + """ + using System; + + enum E + { + #line hidden + } + #line default + + class Program + { + void Main() + { + Console.WriteLine(E.[|x|]); + } + } + """); [Fact] - public async Task TestMissingOnPartiallyHiddenEnum() - { - await TestMissingInRegularAndScriptAsync( -@"using System; - -enum E -{ - A, - B, - C, -#line hidden -} -#line default - -class Program -{ - void Main() - { - Console.WriteLine(E.[|x|]); - } -}"); - } + public Task TestMissingOnPartiallyHiddenEnum() + => TestMissingInRegularAndScriptAsync( + """ + using System; + + enum E + { + A, + B, + C, + #line hidden + } + #line default + + class Program + { + void Main() + { + Console.WriteLine(E.[|x|]); + } + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545903")] - public async Task TestNoOctal() - { - await TestInRegularAndScriptAsync( -@"enum E -{ - A = 007, -} - -class C -{ - E x = E.[|B|]; -}", -@"enum E -{ - A = 007, - B = 8, -} - -class C -{ - E x = E.B; -}"); - } + public Task TestNoOctal() + => TestInRegularAndScriptAsync( + """ + enum E + { + A = 007, + } + + class C + { + E x = E.[|B|]; + } + """, + """ + enum E + { + A = 007, + B = 8, + } + + class C + { + E x = E.B; + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546654")] - public async Task TestLastValueDoesNotHaveInitializer() - { - await TestInRegularAndScriptAsync( -@"enum E -{ - A = 1, - B -} - -class Program -{ - void Main() - { - E.[|C|] } -}", -@"enum E -{ - A = 1, - B, - C -} - -class Program -{ - void Main() - { - E.C } -}"); - } + public Task TestLastValueDoesNotHaveInitializer() + => TestInRegularAndScriptAsync( + """ + enum E + { + A = 1, + B + } + + class Program + { + void Main() + { + E.[|C|] } + } + """, + """ + enum E + { + A = 1, + B, + C + } + + class Program + { + void Main() + { + E.C } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49679")] - public async Task TestWithLeftShift_Long() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color : long -{ - Green = 1L << 0 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color : long -{ - Green = 1L << 0, - Blue = 1L << 1 -}"); - } + public Task TestWithLeftShift_Long() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color : long + { + Green = 1L << 0 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color : long + { + Green = 1L << 0, + Blue = 1L << 1 + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49679")] - public async Task TestWithLeftShift_UInt() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color : uint -{ - Green = 1u << 0 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color : uint -{ - Green = 1u << 0, - Blue = 1u << 1 -}"); - } + public Task TestWithLeftShift_UInt() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color : uint + { + Green = 1u << 0 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color : uint + { + Green = 1u << 0, + Blue = 1u << 1 + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49679")] - public async Task TestWithLeftShift_ULong() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Main() - { - Color.[|Blue|]; - } -} - -enum Color : ulong -{ - Green = 1UL << 0 -}", -@"class Program -{ - void Main() - { - Color.Blue; - } -} - -enum Color : ulong -{ - Green = 1UL << 0, - Blue = 1UL << 1 -}"); - } + public Task TestWithLeftShift_ULong() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Main() + { + Color.[|Blue|]; + } + } + + enum Color : ulong + { + Green = 1UL << 0 + } + """, + """ + class Program + { + void Main() + { + Color.Blue; + } + } + + enum Color : ulong + { + Green = 1UL << 0, + Blue = 1UL << 1 + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/5468")] - public async Task TestWithColorColorConflict1() - { - await TestInRegularAndScriptAsync( -@"enum Color -{ - Blue, - Green -} - -class Sample1 -{ - Color Color => Color.[|Red|]; - - void Method() - { - if (Color == Color.Red) { } - } -} -", -@"enum Color -{ - Blue, - Green, - Red -} - -class Sample1 -{ - Color Color => Color.Red; - - void Method() - { - if (Color == Color.Red) { } - } -} -"); - } + public Task TestWithColorColorConflict1() + => TestInRegularAndScriptAsync( + """ + enum Color + { + Blue, + Green + } + + class Sample1 + { + Color Color => Color.[|Red|]; + + void Method() + { + if (Color == Color.Red) { } + } + } + """, + """ + enum Color + { + Blue, + Green, + Red + } + + class Sample1 + { + Color Color => Color.Red; + + void Method() + { + if (Color == Color.Red) { } + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/5468")] - public async Task TestWithColorColorConflict2() - { - await TestInRegularAndScriptAsync( -@"enum Color -{ - Blue, - Green -} - -class Sample1 -{ - Color Color => Color.Red; - - void Method() - { - if (Color == Color.[|Red|]) { } - } -} -", -@"enum Color -{ - Blue, - Green, - Red -} - -class Sample1 -{ - Color Color => Color.Red; - - void Method() - { - if (Color == Color.Red) { } - } -} -"); - } + public Task TestWithColorColorConflict2() + => TestInRegularAndScriptAsync( + """ + enum Color + { + Blue, + Green + } + + class Sample1 + { + Color Color => Color.Red; + + void Method() + { + if (Color == Color.[|Red|]) { } + } + } + """, + """ + enum Color + { + Blue, + Green, + Red + } + + class Sample1 + { + Color Color => Color.Red; + + void Method() + { + if (Color == Color.Red) { } + } + } + """); } diff --git a/src/Analyzers/CSharp/Tests/GenerateMethod/GenerateConversionTests.cs b/src/Analyzers/CSharp/Tests/GenerateMethod/GenerateConversionTests.cs index 5d61eb179093c..678f50d7e85b2 100644 --- a/src/Analyzers/CSharp/Tests/GenerateMethod/GenerateConversionTests.cs +++ b/src/Analyzers/CSharp/Tests/GenerateMethod/GenerateConversionTests.cs @@ -22,334 +22,352 @@ internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProvide => (null, new GenerateConversionCodeFixProvider()); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")] - public async Task TestGenerateImplicitConversionGenericClass() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Test(int[] a) - { - C x1 = [|1|]; - } -} - -class C -{ -}", -@"using System; - -class Program -{ - void Test(int[] a) - { - C x1 = 1; - } -} - -class C -{ - public static implicit operator C(int v) - { - throw new NotImplementedException(); - } -}"); - } + public Task TestGenerateImplicitConversionGenericClass() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Test(int[] a) + { + C x1 = [|1|]; + } + } + + class C + { + } + """, + """ + using System; + + class Program + { + void Test(int[] a) + { + C x1 = 1; + } + } + + class C + { + public static implicit operator C(int v) + { + throw new NotImplementedException(); + } + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")] - public async Task TestGenerateImplicitConversionClass() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Test(int[] a) - { - C x1 = [|1|]; - } -} - -class C -{ -}", -@"using System; - -class Program -{ - void Test(int[] a) - { - C x1 = 1; - } -} - -class C -{ - public static implicit operator C(int v) - { - throw new NotImplementedException(); - } -}"); - } + public Task TestGenerateImplicitConversionClass() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Test(int[] a) + { + C x1 = [|1|]; + } + } + + class C + { + } + """, + """ + using System; + + class Program + { + void Test(int[] a) + { + C x1 = 1; + } + } + + class C + { + public static implicit operator C(int v) + { + throw new NotImplementedException(); + } + } + """); [Fact] - public async Task TestGenerateImplicitConversionClass_CodeStyle() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Test(int[] a) - { - C x1 = [|1|]; - } -} - -class C -{ -}", -@"using System; - -class Program -{ - void Test(int[] a) - { - C x1 = 1; - } -} - -class C -{ - public static implicit operator C(int v) => throw new NotImplementedException(); -}", + public Task TestGenerateImplicitConversionClass_CodeStyle() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Test(int[] a) + { + C x1 = [|1|]; + } + } + + class C + { + } + """, + """ + using System; + + class Program + { + void Test(int[] a) + { + C x1 = 1; + } + } + + class C + { + public static implicit operator C(int v) => throw new NotImplementedException(); + } + """, options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")] - public async Task TestGenerateImplicitConversionAwaitExpression() - { - await TestInRegularAndScriptAsync( -@"using System; -using System.Threading.Tasks; - -class Program -{ - async void Test() - { - var a = Task.FromResult(1); - Program x1 = [|await a|]; - } -}", -@"using System; -using System.Threading.Tasks; - -class Program -{ - async void Test() - { - var a = Task.FromResult(1); - Program x1 = await a; - } - - public static implicit operator Program(int v) - { - throw new NotImplementedException(); - } -}"); - } + public Task TestGenerateImplicitConversionAwaitExpression() + => TestInRegularAndScriptAsync( + """ + using System; + using System.Threading.Tasks; + + class Program + { + async void Test() + { + var a = Task.FromResult(1); + Program x1 = [|await a|]; + } + } + """, + """ + using System; + using System.Threading.Tasks; + + class Program + { + async void Test() + { + var a = Task.FromResult(1); + Program x1 = await a; + } + + public static implicit operator Program(int v) + { + throw new NotImplementedException(); + } + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")] - public async Task TestGenerateImplicitConversionTargetTypeNotInSource() - { - await TestInRegularAndScriptAsync( -@"class Digit -{ - public Digit(double d) - { - val = d; - } - - public double val; -} - -class Program -{ - static void Main(string[] args) - { - Digit dig = new Digit(7); - double num = [|dig|]; - } -}", -@"using System; - -class Digit -{ - public Digit(double d) - { - val = d; - } - - public double val; - - public static implicit operator double(Digit v) - { - throw new NotImplementedException(); - } -} - -class Program -{ - static void Main(string[] args) - { - Digit dig = new Digit(7); - double num = dig; - } -}"); - } + public Task TestGenerateImplicitConversionTargetTypeNotInSource() + => TestInRegularAndScriptAsync( + """ + class Digit + { + public Digit(double d) + { + val = d; + } + + public double val; + } + + class Program + { + static void Main(string[] args) + { + Digit dig = new Digit(7); + double num = [|dig|]; + } + } + """, + """ + using System; + + class Digit + { + public Digit(double d) + { + val = d; + } + + public double val; + + public static implicit operator double(Digit v) + { + throw new NotImplementedException(); + } + } + + class Program + { + static void Main(string[] args) + { + Digit dig = new Digit(7); + double num = dig; + } + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")] - public async Task TestGenerateExplicitConversionGenericClass() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Test(int[] a) - { - C x1 = [|(C)1|]; - } -} - -class C -{ -}", -@"using System; - -class Program -{ - void Test(int[] a) - { - C x1 = (C)1; - } -} - -class C -{ - public static explicit operator C(int v) - { - throw new NotImplementedException(); - } -}"); - } + public Task TestGenerateExplicitConversionGenericClass() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Test(int[] a) + { + C x1 = [|(C)1|]; + } + } + + class C + { + } + """, + """ + using System; + + class Program + { + void Test(int[] a) + { + C x1 = (C)1; + } + } + + class C + { + public static explicit operator C(int v) + { + throw new NotImplementedException(); + } + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")] - public async Task TestGenerateExplicitConversionClass() - { - await TestInRegularAndScriptAsync( -@"class Program -{ - void Test(int[] a) - { - C x1 = [|(C)1|]; - } -} - -class C -{ -}", -@"using System; - -class Program -{ - void Test(int[] a) - { - C x1 = (C)1; - } -} - -class C -{ - public static explicit operator C(int v) - { - throw new NotImplementedException(); - } -}"); - } + public Task TestGenerateExplicitConversionClass() + => TestInRegularAndScriptAsync( + """ + class Program + { + void Test(int[] a) + { + C x1 = [|(C)1|]; + } + } + + class C + { + } + """, + """ + using System; + + class Program + { + void Test(int[] a) + { + C x1 = (C)1; + } + } + + class C + { + public static explicit operator C(int v) + { + throw new NotImplementedException(); + } + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")] - public async Task TestGenerateExplicitConversionAwaitExpression() - { - await TestInRegularAndScriptAsync( -@"using System; -using System.Threading.Tasks; - -class Program -{ - async void Test() - { - var a = Task.FromResult(1); - Program x1 = [|(Program)await a|]; - } -}", -@"using System; -using System.Threading.Tasks; - -class Program -{ - async void Test() - { - var a = Task.FromResult(1); - Program x1 = (Program)await a; - } - - public static explicit operator Program(int v) - { - throw new NotImplementedException(); - } -}"); - } + public Task TestGenerateExplicitConversionAwaitExpression() + => TestInRegularAndScriptAsync( + """ + using System; + using System.Threading.Tasks; + + class Program + { + async void Test() + { + var a = Task.FromResult(1); + Program x1 = [|(Program)await a|]; + } + } + """, + """ + using System; + using System.Threading.Tasks; + + class Program + { + async void Test() + { + var a = Task.FromResult(1); + Program x1 = (Program)await a; + } + + public static explicit operator Program(int v) + { + throw new NotImplementedException(); + } + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")] - public async Task TestGenerateExplicitConversionTargetTypeNotInSource() - { - await TestInRegularAndScriptAsync( -@"class Digit -{ - public Digit(double d) - { - val = d; - } - - public double val; -} - -class Program -{ - static void Main(string[] args) - { - Digit dig = new Digit(7); - double num = [|(double)dig|]; - } -}", -@"using System; - -class Digit -{ - public Digit(double d) - { - val = d; - } - - public double val; - - public static explicit operator double(Digit v) - { - throw new NotImplementedException(); - } -} - -class Program -{ - static void Main(string[] args) - { - Digit dig = new Digit(7); - double num = (double)dig; - } -}"); - } + public Task TestGenerateExplicitConversionTargetTypeNotInSource() + => TestInRegularAndScriptAsync( + """ + class Digit + { + public Digit(double d) + { + val = d; + } + + public double val; + } + + class Program + { + static void Main(string[] args) + { + Digit dig = new Digit(7); + double num = [|(double)dig|]; + } + } + """, + """ + using System; + + class Digit + { + public Digit(double d) + { + val = d; + } + + public double val; + + public static explicit operator double(Digit v) + { + throw new NotImplementedException(); + } + } + + class Program + { + static void Main(string[] args) + { + Digit dig = new Digit(7); + double num = (double)dig; + } + } + """); } diff --git a/src/Analyzers/CSharp/Tests/GenerateMethod/GenerateDeconstructMethodTests.cs b/src/Analyzers/CSharp/Tests/GenerateMethod/GenerateDeconstructMethodTests.cs index 7c3e759c3edef..c039dade70df5 100644 --- a/src/Analyzers/CSharp/Tests/GenerateMethod/GenerateDeconstructMethodTests.cs +++ b/src/Analyzers/CSharp/Tests/GenerateMethod/GenerateDeconstructMethodTests.cs @@ -21,385 +21,405 @@ internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProvide => (null, new GenerateDeconstructMethodCodeFixProvider()); [Fact] - public async Task TestDeconstructionDeclaration_Simple() - { - await TestInRegularAndScriptAsync( -@"class Class -{ - void Method() - { - (int x, int y) = [|this|]; - } -}", -@"using System; - -class Class -{ - private void Deconstruct(out int x, out int y) - { - throw new NotImplementedException(); - } - - void Method() - { - (int x, int y) = this; - } -}"); - } + public Task TestDeconstructionDeclaration_Simple() + => TestInRegularAndScriptAsync( + """ + class Class + { + void Method() + { + (int x, int y) = [|this|]; + } + } + """, + """ + using System; + + class Class + { + private void Deconstruct(out int x, out int y) + { + throw new NotImplementedException(); + } + + void Method() + { + (int x, int y) = this; + } + } + """); [Fact] - public async Task TestDeconstructionDeclaration_Simple_Record() - { - await TestInRegularAndScriptAsync( -@"record R -{ - void Method() - { - (int x, int y) = [|this|]; - } -}", -@"using System; - -record R -{ - private void Deconstruct(out int x, out int y) - { - throw new NotImplementedException(); - } - - void Method() - { - (int x, int y) = this; - } -}"); - } + public Task TestDeconstructionDeclaration_Simple_Record() + => TestInRegularAndScriptAsync( + """ + record R + { + void Method() + { + (int x, int y) = [|this|]; + } + } + """, + """ + using System; + + record R + { + private void Deconstruct(out int x, out int y) + { + throw new NotImplementedException(); + } + + void Method() + { + (int x, int y) = this; + } + } + """); [Fact] - public async Task TestDeconstructionDeclaration_TypeParameters() - { - await TestInRegularAndScriptAsync( -@"class Class -{ - void Method() - { - (T x, U y) = [|this|]; - } -}", -@"using System; - -class Class -{ - private void Deconstruct(out T x, out object y) - { - throw new NotImplementedException(); - } - - void Method() - { - (T x, U y) = this; - } -}"); - } + public Task TestDeconstructionDeclaration_TypeParameters() + => TestInRegularAndScriptAsync( + """ + class Class + { + void Method() + { + (T x, U y) = [|this|]; + } + } + """, + """ + using System; + + class Class + { + private void Deconstruct(out T x, out object y) + { + throw new NotImplementedException(); + } + + void Method() + { + (T x, U y) = this; + } + } + """); [Fact] - public async Task TestDeconstructionDeclaration_OtherDeconstructMethods() - { - await TestInRegularAndScriptAsync( -@"class Class -{ - void Method() - { - (int x, int y) = [|this|]; - } - void Deconstruct(out int x) => throw null; - void Deconstruct(out int x, out int y, out int z) => throw null; -}", -@"using System; - -class Class -{ - void Method() - { - (int x, int y) = this; - } - void Deconstruct(out int x) => throw null; - void Deconstruct(out int x, out int y, out int z) => throw null; - - private void Deconstruct(out int x, out int y) - { - throw new NotImplementedException(); - } -}"); - } + public Task TestDeconstructionDeclaration_OtherDeconstructMethods() + => TestInRegularAndScriptAsync( + """ + class Class + { + void Method() + { + (int x, int y) = [|this|]; + } + void Deconstruct(out int x) => throw null; + void Deconstruct(out int x, out int y, out int z) => throw null; + } + """, + """ + using System; + + class Class + { + void Method() + { + (int x, int y) = this; + } + void Deconstruct(out int x) => throw null; + void Deconstruct(out int x, out int y, out int z) => throw null; + + private void Deconstruct(out int x, out int y) + { + throw new NotImplementedException(); + } + } + """); [Fact] - public async Task TestDeconstructionDeclaration_AlreadySuccessfull() - { - await TestMissingInRegularAndScriptAsync( -@"class Class -{ - void Method() - { - (int x, int y) = [|this|]; - } - void Deconstruct(out int x, out int y) => throw null; -}"); - } + public Task TestDeconstructionDeclaration_AlreadySuccessfull() + => TestMissingInRegularAndScriptAsync( + """ + class Class + { + void Method() + { + (int x, int y) = [|this|]; + } + void Deconstruct(out int x, out int y) => throw null; + } + """); [Fact] - public async Task TestDeconstructionDeclaration_UndeterminedType() - { - await TestInRegularAndScript1Async( -@"class Class -{ - void Method() - { - (var x, var y) = [|this|]; - } -}", -@"using System; - -class Class -{ - private void Deconstruct(out object x, out object y) - { - throw new NotImplementedException(); - } - - void Method() - { - (var x, var y) = this; - } -}"); - } + public Task TestDeconstructionDeclaration_UndeterminedType() + => TestInRegularAndScript1Async( + """ + class Class + { + void Method() + { + (var x, var y) = [|this|]; + } + } + """, + """ + using System; + + class Class + { + private void Deconstruct(out object x, out object y) + { + throw new NotImplementedException(); + } + + void Method() + { + (var x, var y) = this; + } + } + """); [Fact] - public async Task TestDeconstructionDeclaration_UndeterminedType2() - { - await TestInRegularAndScript1Async( -@"class Class -{ - void Method() - { - var (x, y) = [|this|]; - } -}", -@"using System; - -class Class -{ - private void Deconstruct(out object x, out object y) - { - throw new NotImplementedException(); - } - - void Method() - { - var (x, y) = this; - } -}"); - } + public Task TestDeconstructionDeclaration_UndeterminedType2() + => TestInRegularAndScript1Async( + """ + class Class + { + void Method() + { + var (x, y) = [|this|]; + } + } + """, + """ + using System; + + class Class + { + private void Deconstruct(out object x, out object y) + { + throw new NotImplementedException(); + } + + void Method() + { + var (x, y) = this; + } + } + """); [Fact] - public async Task TestDeconstructionDeclaration_BuiltinType() - { - await TestMissingInRegularAndScriptAsync( -@"class Class -{ - void Method() - { - (int x, int y) = [|1|]; - } -}"); - } + public Task TestDeconstructionDeclaration_BuiltinType() + => TestMissingInRegularAndScriptAsync( + """ + class Class + { + void Method() + { + (int x, int y) = [|1|]; + } + } + """); [Fact] - public async Task TestDeconstructionAssignment() - { - await TestInRegularAndScriptAsync( -@"class Class -{ - void Method() - { - int x, y; - (x, y) = [|this|]; - } -}", -@"using System; - -class Class -{ - private void Deconstruct(out int x, out int y) - { - throw new NotImplementedException(); - } - - void Method() - { - int x, y; - (x, y) = this; - } -}"); - } + public Task TestDeconstructionAssignment() + => TestInRegularAndScriptAsync( + """ + class Class + { + void Method() + { + int x, y; + (x, y) = [|this|]; + } + } + """, + """ + using System; + + class Class + { + private void Deconstruct(out int x, out int y) + { + throw new NotImplementedException(); + } + + void Method() + { + int x, y; + (x, y) = this; + } + } + """); [Fact] - public async Task TestDeconstructionAssignment_Nested() - { - // We only offer a fix for non-nested deconstruction, at the moment - await TestMissingInRegularAndScriptAsync( -@"class Class -{ - void Method() - { - int x, y, z; - ((x, y), z) = ([|this|], 0); - } -}"); - } + public Task TestDeconstructionAssignment_Nested() + => TestMissingInRegularAndScriptAsync( + """ + class Class + { + void Method() + { + int x, y, z; + ((x, y), z) = ([|this|], 0); + } + } + """); [Fact] - public async Task TestDeconstructionAssignment_Array() - { - await TestMissingInRegularAndScriptAsync( -@"class Class -{ - void Method() - { - int x, y; - (x, y) = [|new[] { this }|]; - } -}"); - } + public Task TestDeconstructionAssignment_Array() + => TestMissingInRegularAndScriptAsync( + """ + class Class + { + void Method() + { + int x, y; + (x, y) = [|new[] { this }|]; + } + } + """); [Fact] - public async Task TestSimpleDeconstructionForeach() - { - await TestInRegularAndScriptAsync( -@"class Class -{ - void Method() - { - foreach ((int x, int y) in new[] { [|this|] }) { } - } -}", -@"using System; - -class Class -{ - private void Deconstruct(out int x, out int y) - { - throw new NotImplementedException(); - } - - void Method() - { - foreach ((int x, int y) in new[] { this }) { } - } -}"); - } + public Task TestSimpleDeconstructionForeach() + => TestInRegularAndScriptAsync( + """ + class Class + { + void Method() + { + foreach ((int x, int y) in new[] { [|this|] }) { } + } + } + """, + """ + using System; + + class Class + { + private void Deconstruct(out int x, out int y) + { + throw new NotImplementedException(); + } + + void Method() + { + foreach ((int x, int y) in new[] { this }) { } + } + } + """); [Fact] - public async Task TestSimpleDeconstructionForeach_AnotherType() - { - await TestInRegularAndScriptAsync( -@"class Class -{ - void Method(D d) - { - foreach ((int x, int y) in new[] { [|d|] }) { } - } -} -class D -{ -}", -@"using System; - -class Class -{ - void Method(D d) - { - foreach ((int x, int y) in new[] { d }) { } - } -} -class D -{ - internal void Deconstruct(out int x, out int y) - { - throw new NotImplementedException(); - } -}"); - } + public Task TestSimpleDeconstructionForeach_AnotherType() + => TestInRegularAndScriptAsync( + """ + class Class + { + void Method(D d) + { + foreach ((int x, int y) in new[] { [|d|] }) { } + } + } + class D + { + } + """, + """ + using System; + + class Class + { + void Method(D d) + { + foreach ((int x, int y) in new[] { d }) { } + } + } + class D + { + internal void Deconstruct(out int x, out int y) + { + throw new NotImplementedException(); + } + } + """); [Fact] - public async Task TestDeconstructionPositionalPattern() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void Method() - { - if(this is C(""""[||])) { } - } -}", -@"using System; - -class C -{ - private void Deconstruct(out string v) - { - throw new NotImplementedException(); - } - - void Method() - { - if(this is C(""""[||])) { } - } -}"); - } + public Task TestDeconstructionPositionalPattern() + => TestInRegularAndScriptAsync( + """ + class C + { + void Method() + { + if(this is C(""[||])) { } + } + } + """, + """ + using System; + + class C + { + private void Deconstruct(out string v) + { + throw new NotImplementedException(); + } + + void Method() + { + if(this is C(""[||])) { } + } + } + """); [Fact] - public async Task TestDeconstructionPositionalPattern_NullExpression() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void Method() - { - if(this is C(""""[||], ref 0)) { } - } -}", -@"using System; - -class C -{ - private void Deconstruct(out string v, out object value) - { - throw new NotImplementedException(); - } - - void Method() - { - if(this is C(""""[||], ref 0)) { } - } -}"); - } + public Task TestDeconstructionPositionalPattern_NullExpression() + => TestInRegularAndScriptAsync( + """ + class C + { + void Method() + { + if(this is C(""[||], ref 0)) { } + } + } + """, + """ + using System; + + class C + { + private void Deconstruct(out string v, out object value) + { + throw new NotImplementedException(); + } + + void Method() + { + if(this is C(""[||], ref 0)) { } + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32510")] - public async Task TestDeconstructionAssignment_InvalidDeclaration() - { - await TestMissingInRegularAndScriptAsync( -@" -using System.Collections.Generic; - -class C -{ - void Method() - { - var stuff = new Dictionary(); - foreach ((key, value) in [|stuff|]) // Invalid variable declarator syntax - { - } - } -}"); - } + public Task TestDeconstructionAssignment_InvalidDeclaration() + => TestMissingInRegularAndScriptAsync( + """ + using System.Collections.Generic; + + class C + { + void Method() + { + var stuff = new Dictionary(); + foreach ((key, value) in [|stuff|]) // Invalid variable declarator syntax + { + } + } + } + """); } diff --git a/src/Analyzers/CSharp/Tests/GenerateMethod/GenerateMethodTests.cs b/src/Analyzers/CSharp/Tests/GenerateMethod/GenerateMethodTests.cs index 37b12812aab52..7bb705ccdc7c1 100644 --- a/src/Analyzers/CSharp/Tests/GenerateMethod/GenerateMethodTests.cs +++ b/src/Analyzers/CSharp/Tests/GenerateMethod/GenerateMethodTests.cs @@ -24,9 +24,8 @@ internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProvide => (null, new GenerateMethodCodeFixProvider()); [Fact] - public async Task TestSimpleInvocationIntoSameType() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleInvocationIntoSameType() + => TestInRegularAndScriptAsync( """ class Class { @@ -52,12 +51,10 @@ private void Goo() } } """); - } [Fact] - public async Task TestOnRightOfNullCoalescingAssignment_NullableBool() - { - await TestInRegularAndScriptAsync( + public Task TestOnRightOfNullCoalescingAssignment_NullableBool() + => TestInRegularAndScriptAsync( """ class Class { @@ -83,12 +80,10 @@ void Method(bool? b) } } """); - } [Fact] - public async Task TestOnRightOfNullCoalescingAssignment_String() - { - await TestInRegularAndScriptAsync( + public Task TestOnRightOfNullCoalescingAssignment_String() + => TestInRegularAndScriptAsync( """ class Class { @@ -114,12 +109,10 @@ private string Goo() } } """); - } [Fact] - public async Task TestSimpleInvocationIntoSameType_CodeStyle1() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleInvocationIntoSameType_CodeStyle1() + => TestInRegularAndScriptAsync( """ class Class { @@ -143,12 +136,10 @@ void Method() } """, options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11518")] - public async Task NameMatchesNamespaceName() - { - await TestInRegularAndScriptAsync( + public Task NameMatchesNamespaceName() + => TestInRegularAndScriptAsync( """ namespace N { @@ -180,12 +171,10 @@ private void N() } } """); - } [Fact] - public async Task TestSimpleInvocationOffOfThis() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleInvocationOffOfThis() + => TestInRegularAndScriptAsync( """ class Class { @@ -211,12 +200,10 @@ private void Goo() } } """); - } [Fact] - public async Task TestSimpleInvocationOffOfType() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleInvocationOffOfType() + => TestInRegularAndScriptAsync( """ class Class { @@ -242,12 +229,10 @@ private static void Goo() } } """); - } [Fact] - public async Task TestSimpleInvocationValueExpressionArg() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleInvocationValueExpressionArg() + => TestInRegularAndScriptAsync( """ class Class { @@ -273,12 +258,10 @@ private void Goo(int v) } } """); - } [Fact] - public async Task TestSimpleInvocationMultipleValueExpressionArg() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleInvocationMultipleValueExpressionArg() + => TestInRegularAndScriptAsync( """ class Class { @@ -304,12 +287,10 @@ private void Goo(int v1, int v2) } } """); - } [Fact] - public async Task TestSimpleInvocationValueArg() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleInvocationValueArg() + => TestInRegularAndScriptAsync( """ class Class { @@ -335,12 +316,10 @@ private void Goo(int i) } } """); - } [Fact] - public async Task TestSimpleInvocationValueNullableReferenceType() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleInvocationValueNullableReferenceType() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -370,12 +349,10 @@ private void Goo(string? s) } } """); - } [Fact] - public async Task TestSimpleInvocationUnassignedNullableReferenceType() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleInvocationUnassignedNullableReferenceType() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -407,12 +384,10 @@ private void Goo(string? s) } } """); - } [Fact] - public async Task TestSimpleInvocationCrossingNullableAnnotationsEnabled() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleInvocationCrossingNullableAnnotationsEnabled() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -453,12 +428,10 @@ internal static void Goo(string s) } } """); - } [Fact] - public async Task TestSimpleInvocationValueNestedNullableReferenceType() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleInvocationValueNestedNullableReferenceType() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -491,12 +464,10 @@ private void Goo(List l) } } """); - } [Fact] - public async Task TestSimpleInvocationNamedValueArg() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleInvocationNamedValueArg() + => TestInRegularAndScriptAsync( """ class Class { @@ -522,12 +493,10 @@ private void Goo(int bar) } } """); - } [Fact] - public async Task TestGenerateAfterMethod() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateAfterMethod() + => TestInRegularAndScriptAsync( """ class Class { @@ -561,12 +530,10 @@ void NextMethod() } } """); - } [Fact] - public async Task TestInterfaceNaming() - { - await TestInRegularAndScriptAsync( + public Task TestInterfaceNaming() + => TestInRegularAndScriptAsync( """ class Class { @@ -600,12 +567,10 @@ IGoo NextMethod() } } """); - } [Fact] - public async Task TestFuncArg0() - { - await TestInRegularAndScriptAsync( + public Task TestFuncArg0() + => TestInRegularAndScriptAsync( """ class Class { @@ -639,12 +604,10 @@ string NextMethod() } } """); - } [Fact] - public async Task TestFuncArg1() - { - await TestInRegularAndScriptAsync( + public Task TestFuncArg1() + => TestInRegularAndScriptAsync( """ class Class { @@ -678,12 +641,10 @@ string NextMethod(int i) } } """); - } [Fact] - public async Task TestActionArg() - { - await TestInRegularAndScriptAsync( + public Task TestActionArg() + => TestInRegularAndScriptAsync( """ class Class { @@ -717,12 +678,10 @@ void NextMethod() } } """); - } [Fact] - public async Task TestActionArg1() - { - await TestInRegularAndScriptAsync( + public Task TestActionArg1() + => TestInRegularAndScriptAsync( """ class Class { @@ -756,15 +715,13 @@ void NextMethod(int i) } } """); - } // Note: we only test type inference once. This is just to verify that it's being used // properly by Generate Method. The full wealth of type inference tests can be found // elsewhere and don't need to be repeated here. [Fact] - public async Task TestTypeInference() - { - await TestInRegularAndScriptAsync( + public Task TestTypeInference() + => TestInRegularAndScriptAsync( """ class Class { @@ -794,12 +751,10 @@ private bool Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/784793")] - public async Task TestOutRefArguments() - { - await TestInRegularAndScriptAsync( + public Task TestOutRefArguments() + => TestInRegularAndScriptAsync( """ class Class { @@ -825,12 +780,10 @@ private void Goo(out object a, ref object b) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/54212")] - public async Task TestInArgument() - { - await TestInRegularAndScriptAsync( + public Task TestInArgument() + => TestInRegularAndScriptAsync( """ using System; @@ -860,12 +813,10 @@ private void M2(in int i) } } """); - } [Fact] - public async Task TestMemberAccessArgumentName() - { - await TestInRegularAndScriptAsync( + public Task TestMemberAccessArgumentName() + => TestInRegularAndScriptAsync( """ class Class { @@ -891,12 +842,10 @@ private void Goo(object bar) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/784793")] - public async Task TestParenthesizedArgumentName() - { - await TestInRegularAndScriptAsync( + public Task TestParenthesizedArgumentName() + => TestInRegularAndScriptAsync( """ class Class { @@ -922,12 +871,10 @@ private void Goo(object bar) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/784793")] - public async Task TestCastedArgumentName() - { - await TestInRegularAndScriptAsync( + public Task TestCastedArgumentName() + => TestInRegularAndScriptAsync( """ class Class { @@ -953,12 +900,10 @@ private void Goo(Bar baz) } } """); - } [Fact] - public async Task TestNullableArgument() - { - await TestInRegularAndScriptAsync( + public Task TestNullableArgument() + => TestInRegularAndScriptAsync( """ class C { @@ -984,12 +929,10 @@ private void Goo(int? v) } } """); - } [Fact] - public async Task TestNullArgument() - { - await TestInRegularAndScriptAsync( + public Task TestNullArgument() + => TestInRegularAndScriptAsync( """ class C { @@ -1015,12 +958,10 @@ private void Goo(object value) } } """); - } [Fact] - public async Task TestTypeofArgument() - { - await TestInRegularAndScriptAsync( + public Task TestTypeofArgument() + => TestInRegularAndScriptAsync( """ class C { @@ -1046,12 +987,10 @@ private void Goo(Type type) } } """); - } [Fact] - public async Task TestDefaultArgument() - { - await TestInRegularAndScriptAsync( + public Task TestDefaultArgument() + => TestInRegularAndScriptAsync( """ class C { @@ -1077,12 +1016,10 @@ private void Goo(int v) } } """); - } [Fact] - public async Task TestAsArgument() - { - await TestInRegularAndScriptAsync( + public Task TestAsArgument() + => TestInRegularAndScriptAsync( """ class C { @@ -1108,12 +1045,10 @@ private void Goo(int? v) } } """); - } [Fact] - public async Task TestPointArgument() - { - await TestInRegularAndScriptAsync( + public Task TestPointArgument() + => TestInRegularAndScriptAsync( """ class C { @@ -1141,12 +1076,10 @@ private unsafe void Goo(int* p) } } """); - } [Fact] - public async Task TestArgumentWithPointerName() - { - await TestInRegularAndScriptAsync( + public Task TestArgumentWithPointerName() + => TestInRegularAndScriptAsync( """ class C { @@ -1174,12 +1107,10 @@ private unsafe void Goo(int* p) } } """); - } [Fact] - public async Task TestArgumentWithPointTo() - { - await TestInRegularAndScriptAsync( + public Task TestArgumentWithPointTo() + => TestInRegularAndScriptAsync( """ class C { @@ -1207,12 +1138,10 @@ private void Goo(int v) } } """); - } [Fact] - public async Task TestArgumentWithAddress() - { - await TestInRegularAndScriptAsync( + public Task TestArgumentWithAddress() + => TestInRegularAndScriptAsync( """ class C { @@ -1240,12 +1169,10 @@ private unsafe void Goo(int* v) } } """); - } [Fact] - public async Task TestGenerateWithPointerReturn() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateWithPointerReturn() + => TestInRegularAndScriptAsync( """ class C { @@ -1271,12 +1198,10 @@ void Method() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/784793")] - public async Task TestDuplicateNames() - { - await TestInRegularAndScriptAsync( + public Task TestDuplicateNames() + => TestInRegularAndScriptAsync( """ class Class { @@ -1302,12 +1227,10 @@ private void Goo(Bar baz1, object baz2) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/784793")] - public async Task TestDuplicateNamesWithNamedArgument() - { - await TestInRegularAndScriptAsync( + public Task TestDuplicateNamesWithNamedArgument() + => TestInRegularAndScriptAsync( """ class Class { @@ -1333,15 +1256,13 @@ private void Goo(Bar baz1, object baz2, object baz) } } """); - } // Note: we do not test the range of places where a delegate type can be inferred. This is // just to verify that it's being used properly by Generate Method. The full wealth of // delegate inference tests can be found elsewhere and don't need to be repeated here. [Fact] - public async Task TestSimpleDelegate() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleDelegate() + => TestInRegularAndScriptAsync( """ using System; @@ -1369,12 +1290,10 @@ private bool Goo(int arg1, string arg2) } } """); - } [Fact] - public async Task TestSimpleAssignmentWithNullableReferenceType() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleAssignmentWithNullableReferenceType() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -1406,15 +1325,10 @@ void Method() } } """); - } [Fact] - public async Task TestGenericAssignmentWithTopLevelNullableReferenceTypeBeingAssignedTo() - { - // Here we assert that if the type argument was string, but the return value was string?, we still - // make the return value T, and assume the user just wanted to assign it to a nullable value because they - // might be assigning null later in the caller. - await TestInRegularAndScriptAsync( + public Task TestGenericAssignmentWithTopLevelNullableReferenceTypeBeingAssignedTo() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -1446,15 +1360,10 @@ private T Goo(T v) } } """); - } [Fact] - public async Task TestGenericAssignmentWithNestedNullableReferenceTypeBeingAssignedTo() - { - // Here, we are asserting that the return type of the generated method is T, effectively discarding - // the difference of nested nullability. Since there's no way to generate a method any other way, - // we're assuming this is betetr than inferring that the return type is explicitly IEnumerable - await TestInRegularAndScriptAsync( + public Task TestGenericAssignmentWithNestedNullableReferenceTypeBeingAssignedTo() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -1488,12 +1397,10 @@ private T Goo(T e) } } """); - } [Fact] - public async Task TestDelegateWithRefParameter() - { - await TestInRegularAndScriptAsync( + public Task TestDelegateWithRefParameter() + => TestInRegularAndScriptAsync( """ class Class { @@ -1523,7 +1430,6 @@ private void Bar(ref int i) delegate void Goo(ref int i); """); - } // TODO(cyrusn): Add delegate tests that cover delegates with interesting signatures (i.e. // out/ref). @@ -1531,9 +1437,8 @@ private void Bar(ref int i) // add negative tests to verify that Generate Method doesn't show up in unexpected places. [Fact] - public async Task TestGenericArgs1() - { - await TestInRegularAndScriptAsync( + public Task TestGenericArgs1() + => TestInRegularAndScriptAsync( """ using System; @@ -1561,12 +1466,10 @@ private void Goo() } } """); - } [Fact] - public async Task TestGenericArgs2() - { - await TestInRegularAndScriptAsync( + public Task TestGenericArgs2() + => TestInRegularAndScriptAsync( """ using System; @@ -1594,12 +1497,10 @@ private void Goo() } } """); - } [Fact] - public async Task TestGenericArgsFromMethod() - { - await TestInRegularAndScriptAsync( + public Task TestGenericArgsFromMethod() + => TestInRegularAndScriptAsync( """ using System; @@ -1627,12 +1528,10 @@ private void Goo(X x) } } """); - } [Fact] - public async Task TestMultipleGenericArgsFromMethod() - { - await TestInRegularAndScriptAsync( + public Task TestMultipleGenericArgsFromMethod() + => TestInRegularAndScriptAsync( """ using System; @@ -1660,12 +1559,10 @@ private void Goo(X x, Y y) } } """); - } [Fact] - public async Task TestMultipleGenericArgsFromMethod2() - { - await TestInRegularAndScriptAsync( + public Task TestMultipleGenericArgsFromMethod2() + => TestInRegularAndScriptAsync( """ using System; @@ -1693,12 +1590,10 @@ private void Goo(Y[] y, Func x) } } """); - } [Fact] - public async Task TestGenericArgThatIsTypeParameter() - { - await TestInRegularAndScriptAsync( + public Task TestGenericArgThatIsTypeParameter() + => TestInRegularAndScriptAsync( """ class Program { @@ -1724,12 +1619,10 @@ private void Goo(T t) } } """); - } [Fact] - public async Task TestMultipleGenericArgsThatAreTypeParameters() - { - await TestInRegularAndScriptAsync( + public Task TestMultipleGenericArgsThatAreTypeParameters() + => TestInRegularAndScriptAsync( """ class Program { @@ -1755,12 +1648,10 @@ private void Goo(T t, U u) } } """); - } [Fact] - public async Task TestGenerateIntoOuterThroughInstance() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateIntoOuterThroughInstance() + => TestInRegularAndScriptAsync( """ class Outer { @@ -1792,12 +1683,10 @@ private void Goo() } } """); - } [Fact] - public async Task TestGenerateIntoOuterThroughClass() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateIntoOuterThroughClass() + => TestInRegularAndScriptAsync( """ class Outer { @@ -1829,12 +1718,10 @@ private static void Goo() } } """); - } [Fact] - public async Task TestGenerateIntoSiblingThroughInstance() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateIntoSiblingThroughInstance() + => TestInRegularAndScriptAsync( """ class Class { @@ -1867,12 +1754,10 @@ internal void Goo() } } """); - } [Fact] - public async Task TestGenerateIntoSiblingThroughClass() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateIntoSiblingThroughClass() + => TestInRegularAndScriptAsync( """ class Class { @@ -1905,12 +1790,10 @@ internal static void Goo() } } """); - } [Fact] - public async Task TestGenerateIntoInterfaceThroughInstance() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateIntoInterfaceThroughInstance() + => TestInRegularAndScriptAsync( """ class Class { @@ -1938,12 +1821,10 @@ interface ISibling void Goo(); } """); - } [Fact] - public async Task TestGenerateIntoInterfaceThroughInstanceWithDelegate() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateIntoInterfaceThroughInstanceWithDelegate() + => TestInRegularAndScriptAsync( """ using System; @@ -1975,12 +1856,10 @@ interface ISibling string Goo(int arg); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29584")] - public async Task TestGenerateAbstractIntoSameType() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateAbstractIntoSameType() + => TestInRegularAndScriptAsync( """ abstract class Class { @@ -2001,13 +1880,11 @@ void Method() protected abstract void Goo(); } """, -index: 1); - } + index: 1); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537906")] - public async Task TestMethodReturningDynamic() - { - await TestInRegularAndScriptAsync( + public Task TestMethodReturningDynamic() + => TestInRegularAndScriptAsync( """ class Class { @@ -2033,12 +1910,10 @@ private dynamic Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537906")] - public async Task TestMethodTakingDynamicArg() - { - await TestInRegularAndScriptAsync( + public Task TestMethodTakingDynamicArg() + => TestInRegularAndScriptAsync( """ class Class { @@ -2064,12 +1939,10 @@ private void Goo(dynamic d) } } """); - } [Fact, WorkItem(3203, "DevDiv_Projects/Roslyn")] - public async Task TestNegativeWithNamedOptionalArg1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNegativeWithNamedOptionalArg1() + => TestMissingInRegularAndScriptAsync( """ namespace SyntaxError { @@ -2089,12 +1962,10 @@ static void Method2() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537972")] - public async Task TestWithNamedOptionalArg2() - { - await TestInRegularAndScriptAsync( + public Task TestWithNamedOptionalArg2() + => TestInRegularAndScriptAsync( """ namespace SyntaxError { @@ -2140,12 +2011,10 @@ static void Method2() } } """); - } [Fact] - public async Task TestArgOrderInNamedArgs() - { - await TestInRegularAndScriptAsync( + public Task TestArgOrderInNamedArgs() + => TestInRegularAndScriptAsync( """ class Goo { @@ -2171,12 +2040,10 @@ private void Method(int v1, int v2, int n1, int n3, int n2, int n0) } } """); - } [Fact] - public async Task TestForMissingOptionalArg() - { - await TestMissingInRegularAndScriptAsync( + public Task TestForMissingOptionalArg() + => TestMissingInRegularAndScriptAsync( """ class Goo { @@ -2190,12 +2057,10 @@ private void Method(double n = 3.14, string s, bool b) } } """); - } [Fact] - public async Task TestNamingOfArgWithClashes() - { - await TestInRegularAndScriptAsync( + public Task TestNamingOfArgWithClashes() + => TestInRegularAndScriptAsync( """ class Goo { @@ -2225,12 +2090,10 @@ private void Method(string s, int i) } } """); - } [Fact] - public async Task TestFixCountGeneratingIntoInterface() - { - await TestActionCountAsync( + public Task TestFixCountGeneratingIntoInterface() + => TestActionCountAsync( """ interface I2 { @@ -2245,13 +2108,11 @@ public void Meth() } } """, -count: 1); - } + count: 1); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527278")] - public async Task TestInvocationOffOfBase() - { - await TestInRegularAndScriptAsync( + public Task TestInvocationOffOfBase() + => TestInRegularAndScriptAsync( """ class C3A { @@ -2284,12 +2145,10 @@ public void C4() } } """); - } [Fact] - public async Task TestInvocationWithinCtor() - { - await TestInRegularAndScriptAsync( + public Task TestInvocationWithinCtor() + => TestInRegularAndScriptAsync( """ class C1 { @@ -2315,12 +2174,10 @@ private void M() } } """); - } [Fact] - public async Task TestInvocationWithinBaseCtor() - { - await TestInRegularAndScriptAsync( + public Task TestInvocationWithinBaseCtor() + => TestInRegularAndScriptAsync( """ class C1 { @@ -2346,12 +2203,10 @@ private void M() } } """); - } [Fact, WorkItem(3095, "DevDiv_Projects/Roslyn")] - public async Task TestForMultipleSmartTagsInvokingWithinCtor() - { - await TestMissingInRegularAndScriptAsync( + public Task TestForMultipleSmartTagsInvokingWithinCtor() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2368,12 +2223,10 @@ private void M() } } """); - } [Fact] - public async Task TestInvocationWithinDestructor() - { - await TestInRegularAndScriptAsync( + public Task TestInvocationWithinDestructor() + => TestInRegularAndScriptAsync( """ class C1 { @@ -2399,12 +2252,10 @@ private void M() } } """); - } [Fact] - public async Task TestInvocationWithinConditional() - { - await TestInRegularAndScriptAsync( + public Task TestInvocationWithinConditional() + => TestInRegularAndScriptAsync( """ class C4 { @@ -2436,12 +2287,10 @@ private string M() } } """); - } [Fact] - public async Task TestGenerateIntoStaticClass() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateIntoStaticClass() + => TestInRegularAndScriptAsync( """ class Bar { @@ -2474,12 +2323,10 @@ internal static void M() } } """); - } [Fact] - public async Task TestGenerateIntoAbstractClass() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateIntoAbstractClass() + => TestInRegularAndScriptAsync( """ class Bar { @@ -2512,12 +2359,10 @@ internal static void M() } } """); - } [Fact] - public async Task TestGenerateIntoAbstractClassThoughInstance1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateIntoAbstractClassThoughInstance1() + => TestInRegularAndScriptAsync( """ class C { @@ -2550,12 +2395,10 @@ internal void M() } } """); - } [Fact] - public async Task TestGenerateIntoAbstractClassThoughInstance2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateIntoAbstractClassThoughInstance2() + => TestInRegularAndScriptAsync( """ class C { @@ -2583,13 +2426,11 @@ abstract class Goo internal abstract void M(); } """, -index: 1); - } + index: 1); [Fact] - public async Task TestGenerateIntoPartialClass1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateIntoPartialClass1() + => TestInRegularAndScriptAsync( """ class Bar { @@ -2630,12 +2471,10 @@ partial class Goo { } """); - } [Fact] - public async Task TestGenerateIntoPartialClass2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateIntoPartialClass2() + => TestInRegularAndScriptAsync( """ partial class Goo { @@ -2669,12 +2508,10 @@ partial class Goo { } """); - } [Fact] - public async Task TestGenerateIntoStruct() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateIntoStruct() + => TestInRegularAndScriptAsync( """ class Goo { @@ -2707,12 +2544,10 @@ internal void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527291")] - public async Task TestInvocationOffOfIndexer() - { - await TestInRegularAndScriptAsync( + public Task TestInvocationOffOfIndexer() + => TestInRegularAndScriptAsync( """ class Bar { @@ -2775,12 +2610,10 @@ internal void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527292")] - public async Task TestInvocationWithinForEach() - { - await TestInRegularAndScriptAsync( + public Task TestInvocationWithinForEach() + => TestInRegularAndScriptAsync( """ class C8 { @@ -2845,12 +2678,10 @@ internal void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48064")] - public async Task TestInvocationWithinSynchronousForEach() - { - await TestInRegularAndScriptAsync( + public Task TestInvocationWithinSynchronousForEach() + => TestInRegularAndScriptAsync( """ class C { @@ -2884,12 +2715,10 @@ interface ISomeInterface IEnumerable GetItems(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48064")] - public async Task TestInvocationWithinAsynchronousForEach_IAsyncEnumerableDoesNotExist_FallbackToIEnumerable() - { - await TestInRegularAndScriptAsync( + public Task TestInvocationWithinAsynchronousForEach_IAsyncEnumerableDoesNotExist_FallbackToIEnumerable() + => TestInRegularAndScriptAsync( """ class C { @@ -2923,12 +2752,10 @@ interface ISomeInterface IEnumerable GetItems(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48064")] - public async Task TestInvocationWithinAsynchronousForEach_IAsyncEnumerableExists_UseIAsyncEnumerable() - { - await TestInRegularAndScriptAsync( + public Task TestInvocationWithinAsynchronousForEach_IAsyncEnumerableExists_UseIAsyncEnumerable() + => TestInRegularAndScriptAsync( """ class C { @@ -2962,12 +2789,10 @@ interface ISomeInterface } """ + IAsyncEnumerable); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48064")] - public async Task TestInvocationWithinAsynchronousForEach_IAsyncEnumerableExists_UseIAsyncEnumerableOfString() - { - await TestInRegularAndScriptAsync( + public Task TestInvocationWithinAsynchronousForEach_IAsyncEnumerableExists_UseIAsyncEnumerableOfString() + => TestInRegularAndScriptAsync( """ class C { @@ -3001,12 +2826,10 @@ interface ISomeInterface } """ + IAsyncEnumerable); - } [Fact] - public async Task TestInvocationOffOfAnotherMethodCall() - { - await TestInRegularAndScriptAsync( + public Task TestInvocationOffOfAnotherMethodCall() + => TestInRegularAndScriptAsync( """ class C9 { @@ -3053,12 +2876,10 @@ internal void M() } } """); - } [Fact] - public async Task TestInvocationIntoNestedNamespaces() - { - await TestInRegularAndScriptAsync( + public Task TestInvocationIntoNestedNamespaces() + => TestInRegularAndScriptAsync( """ namespace NS11X { @@ -3115,12 +2936,10 @@ internal static void M() } } """); - } [Fact] - public async Task TestInvocationIntoAliasedNamespaces() - { - await TestInRegularAndScriptAsync( + public Task TestInvocationIntoAliasedNamespaces() + => TestInRegularAndScriptAsync( """ namespace NS11X { @@ -3174,12 +2993,10 @@ internal static void M() } } """); - } [Fact] - public async Task TestInvocationOnGlobalNamespace() - { - await TestInRegularAndScriptAsync( + public Task TestInvocationOnGlobalNamespace() + => TestInRegularAndScriptAsync( """ namespace NS13X { @@ -3250,12 +3067,10 @@ internal static void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538353")] - public async Task TestGenerateIntoAppropriatePart() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateIntoAppropriatePart() + => TestInRegularAndScriptAsync( """ public partial class C { @@ -3289,12 +3104,10 @@ private void Test() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538541")] - public async Task TestGenerateWithVoidArgument() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateWithVoidArgument() + => TestInRegularAndScriptAsync( """ class C { @@ -3328,12 +3141,10 @@ private void Test(object v) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538993")] - public async Task TestGenerateInSimpleLambda() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInSimpleLambda() + => TestInRegularAndScriptAsync( """ using System; @@ -3361,12 +3172,10 @@ private static int Goo(string x) } } """); - } [Fact] - public async Task TestGenerateInParenthesizedLambda() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInParenthesizedLambda() + => TestInRegularAndScriptAsync( """ using System; @@ -3394,12 +3203,10 @@ private static int Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30232")] - public async Task TestGenerateInAsyncTaskOfTSimpleLambda() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInAsyncTaskOfTSimpleLambda() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -3429,12 +3236,10 @@ private static int Goo(string x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30232")] - public async Task TestGenerateInAsyncTaskOfTParenthesizedLambda() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInAsyncTaskOfTParenthesizedLambda() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -3464,12 +3269,10 @@ private static int Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30232")] - public async Task TestGenerateInAsyncTaskSimpleLambda() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInAsyncTaskSimpleLambda() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -3499,12 +3302,10 @@ private static void Goo(string x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30232")] - public async Task TestGenerateInAsyncTaskParenthesizedLambda() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInAsyncTaskParenthesizedLambda() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -3534,12 +3335,10 @@ private static void Goo() } } """); - } [Fact] - public async Task TestGenerateInAsyncVoidSimpleLambda() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInAsyncVoidSimpleLambda() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -3569,12 +3368,10 @@ private static void Goo(string x) } } """); - } [Fact] - public async Task TestGenerateInAsyncVoidParenthesizedLambda() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInAsyncVoidParenthesizedLambda() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -3604,12 +3401,10 @@ private static void Goo() } } """); - } [Fact] - public async Task TestGenerateInAssignmentInAnonymousMethod() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInAssignmentInAnonymousMethod() + => TestInRegularAndScriptAsync( """ class C { @@ -3639,12 +3434,10 @@ private int Goo(int x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539024")] - public async Task TestGenerateOffOfExplicitInterface1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateOffOfExplicitInterface1() + => TestInRegularAndScriptAsync( """ interface I { @@ -3670,12 +3463,10 @@ void I.Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539024")] - public async Task TestGenerateOffOfExplicitInterface2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateOffOfExplicitInterface2() + => TestInRegularAndScriptAsync( """ interface I { @@ -3701,12 +3492,10 @@ int I.Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539024")] - public async Task TestGenerateOffOfExplicitInterface3() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateOffOfExplicitInterface3() + => TestInRegularAndScriptAsync( """ interface I { @@ -3732,12 +3521,10 @@ void I.Goo(int i) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539024")] - public async Task TestGenerateOffOfExplicitInterface4() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateOffOfExplicitInterface4() + => TestInRegularAndScriptAsync( """ interface I { @@ -3763,12 +3550,10 @@ void I.Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539024")] - public async Task TestGenerateOffOfExplicitInterface5() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateOffOfExplicitInterface5() + => TestInRegularAndScriptAsync( """ interface I { @@ -3794,12 +3579,10 @@ void I.Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539024")] - public async Task TestGenerateOffOfExplicitInterface6() - { - await TestMissingInRegularAndScriptAsync( + public Task TestGenerateOffOfExplicitInterface6() + => TestMissingInRegularAndScriptAsync( """ interface I { @@ -3813,12 +3596,10 @@ class A : I } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539024")] - public async Task TestGenerateOffOfExplicitInterface7() - { - await TestMissingInRegularAndScriptAsync( + public Task TestGenerateOffOfExplicitInterface7() + => TestMissingInRegularAndScriptAsync( """ interface I { @@ -3831,12 +3612,10 @@ class A } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539024")] - public async Task TestGenerateOffOfExplicitInterface8() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateOffOfExplicitInterface8() + => TestInRegularAndScriptAsync( """ interface I { @@ -3862,13 +3641,10 @@ void I.Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539024")] - public async Task TestGenerateOffOfExplicitInterface9() - { - // TODO(cyrusn): It might be nice if we generated "Goo(T i)" here in the future. - await TestInRegularAndScriptAsync( + public Task TestGenerateOffOfExplicitInterface9() + => TestInRegularAndScriptAsync( """ interface I { @@ -3894,12 +3670,10 @@ void I.Goo(int i) } } """); - } [Fact, WorkItem(5016, "DevDiv_Projects/Roslyn")] - public async Task TestGenerateMethodWithArgumentFromBaseConstructorsArgument() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodWithArgumentFromBaseConstructorsArgument() + => TestInRegularAndScriptAsync( """ class A { @@ -3937,12 +3711,10 @@ private static string M(string s) } } """); - } [Fact, WorkItem(5016, "DevDiv_Projects/Roslyn")] - public async Task TestGenerateMethodWithArgumentFromGenericConstructorsArgument() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodWithArgumentFromGenericConstructorsArgument() + => TestInRegularAndScriptAsync( """ class A { @@ -3980,12 +3752,10 @@ private static int M() } } """); - } [Fact] - public async Task TestGenerateMethodWithVar() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodWithVar() + => TestInRegularAndScriptAsync( """ class C { @@ -4013,12 +3783,10 @@ private int Goo(int v) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] - public async Task TestEscapedName() - { - await TestInRegularAndScriptAsync( + public Task TestEscapedName() + => TestInRegularAndScriptAsync( """ class Class { @@ -4044,12 +3812,10 @@ private void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] - public async Task TestEscapedKeyword() - { - await TestInRegularAndScriptAsync( + public Task TestEscapedKeyword() + => TestInRegularAndScriptAsync( """ class Class { @@ -4075,12 +3841,10 @@ private void @int() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539527")] - public async Task TestUnmentionableTypeParameter1() - { - await TestInRegularAndScriptAsync( + public Task TestUnmentionableTypeParameter1() + => TestInRegularAndScriptAsync( """ class Class { @@ -4113,12 +3877,10 @@ internal static void C(A a) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539527")] - public async Task TestUnmentionableTypeParameter2() - { - await TestInRegularAndScriptAsync( + public Task TestUnmentionableTypeParameter2() + => TestInRegularAndScriptAsync( """ class Class { @@ -4144,12 +3906,10 @@ private void C(A a) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539527")] - public async Task TestUnmentionableTypeParameter3() - { - await TestInRegularAndScriptAsync( + public Task TestUnmentionableTypeParameter3() + => TestInRegularAndScriptAsync( """ class Class { @@ -4181,12 +3941,10 @@ private void C(A a) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539527")] - public async Task TestUnmentionableTypeParameter4() - { - await TestInRegularAndScriptAsync( + public Task TestUnmentionableTypeParameter4() + => TestInRegularAndScriptAsync( """ class Class { @@ -4218,12 +3976,10 @@ private void M(A a) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539527")] - public async Task TestUnmentionableTypeParameter5() - { - await TestInRegularAndScriptAsync( + public Task TestUnmentionableTypeParameter5() + => TestInRegularAndScriptAsync( """ class Class { @@ -4255,12 +4011,10 @@ private void M(A a) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539596")] - public async Task TestUnmentionableTypeParameter6() - { - await TestInRegularAndScriptAsync( + public Task TestUnmentionableTypeParameter6() + => TestInRegularAndScriptAsync( """ class Test { @@ -4286,12 +4040,10 @@ private void Goo(object u1, object v1) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539593")] - public async Task TestUnmentionableTypeParameter7() - { - await TestInRegularAndScriptAsync( + public Task TestUnmentionableTypeParameter7() + => TestInRegularAndScriptAsync( """ class H { @@ -4317,12 +4069,10 @@ private T1 Goo(T1 t1) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539593")] - public async Task TestUnmentionableTypeParameter8() - { - await TestInRegularAndScriptAsync( + public Task TestUnmentionableTypeParameter8() + => TestInRegularAndScriptAsync( """ class H { @@ -4348,12 +4098,10 @@ private T1 Goo(T1 t1) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539597")] - public async Task TestOddErrorType() - { - await TestInRegularAndScriptAsync( + public Task TestOddErrorType() + => TestInRegularAndScriptAsync( """ public class C { @@ -4379,12 +4127,10 @@ private @public F() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539594")] - public async Task TestGenericOverloads() - { - await TestInRegularAndScriptAsync( + public Task TestGenericOverloads() + => TestInRegularAndScriptAsync( """ class C { @@ -4432,12 +4178,10 @@ internal static void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537929")] - public async Task TestInScript1() - { - await TestAsync( + public Task TestInScript1() + => TestAsync( """ using System; @@ -4460,12 +4204,10 @@ static void Goo() } """, parseOptions: GetScriptOptions()); - } [Fact] - public async Task TestInTopLevelImplicitClass1() - { - await TestAsync( + public Task TestInTopLevelImplicitClass1() + => TestAsync( """ using System; @@ -4488,12 +4230,10 @@ static void Goo() } """, parseOptions: GetScriptOptions()); - } [Fact] - public async Task TestInNamespaceImplicitClass1() - { - await TestInRegularAndScriptAsync( + public Task TestInNamespaceImplicitClass1() + => TestInRegularAndScriptAsync( """ namespace N { @@ -4521,12 +4261,10 @@ void Goo() } } """); - } [Fact] - public async Task TestInNamespaceImplicitClass_FieldInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestInNamespaceImplicitClass_FieldInitializer() + => TestInRegularAndScriptAsync( """ namespace N { @@ -4548,12 +4286,10 @@ int Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539571")] - public async Task TestSimplification1() - { - await TestInRegularAndScriptAsync( + public Task TestSimplification1() + => TestInRegularAndScriptAsync( """ using System; @@ -4591,12 +4327,10 @@ private static void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539571")] - public async Task TestSimplification2() - { - await TestInRegularAndScriptAsync( + public Task TestSimplification2() + => TestInRegularAndScriptAsync( """ using System; @@ -4624,12 +4358,10 @@ private static Action Bar(DateTime now) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539618")] - public async Task TestClashesWithMethod1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestClashesWithMethod1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4643,12 +4375,10 @@ void Main() private void Goo(int x, bool b); } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539618")] - public async Task TestClashesWithMethod2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestClashesWithMethod2() + => TestMissingInRegularAndScriptAsync( """ class Program : IGoo { @@ -4660,12 +4390,10 @@ class Program : IGoo void Goo(); } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539637")] - public async Task TestReservedParametername1() - { - await TestInRegularAndScriptAsync( + public Task TestReservedParametername1() + => TestInRegularAndScriptAsync( """ class C { @@ -4693,12 +4421,10 @@ private void M(long @long) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539751")] - public async Task TestShadows1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestShadows1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4711,12 +4437,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539769")] - public async Task TestShadows2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestShadows2() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4732,12 +4456,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539781")] - public async Task TestInTopLevelMethod() - { - await TestInRegularAndScriptAsync( + public Task TestInTopLevelMethod() + => TestInRegularAndScriptAsync( """ void M() { @@ -4757,12 +4479,10 @@ void Goo() throw new NotImplementedException(); } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539823")] - public async Task TestLambdaReturnType() - { - await TestInRegularAndScriptAsync( + public Task TestLambdaReturnType() + => TestInRegularAndScriptAsync( """ using System; @@ -4790,12 +4510,10 @@ private static T2 Goo(Func g) } } """); - } [Fact] - public async Task TestGenerateWithThrow() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateWithThrow() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -4827,12 +4545,10 @@ private Exception F() } } """); - } [Fact] - public async Task TestInDelegateConstructor() - { - await TestInRegularAndScriptAsync( + public Task TestInDelegateConstructor() + => TestInRegularAndScriptAsync( """ using System; @@ -4864,12 +4580,10 @@ private void Test(int x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539871")] - public async Task TestDelegateScenario() - { - await TestMissingInRegularAndScriptAsync( + public Task TestDelegateScenario() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -4881,12 +4595,10 @@ static void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539928")] - public async Task TestInheritedTypeParameters1() - { - await TestInRegularAndScriptAsync( + public Task TestInheritedTypeParameters1() + => TestInRegularAndScriptAsync( """ class C { @@ -4916,12 +4628,10 @@ interface I I Goo(); } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539928")] - public async Task TestInheritedTypeParameters2() - { - await TestInRegularAndScriptAsync( + public Task TestInheritedTypeParameters2() + => TestInRegularAndScriptAsync( """ class C { @@ -4951,12 +4661,10 @@ interface I I Goo(); } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539928")] - public async Task TestInheritedTypeParameters3() - { - await TestInRegularAndScriptAsync( + public Task TestInheritedTypeParameters3() + => TestInRegularAndScriptAsync( """ class C { @@ -4986,12 +4694,10 @@ interface I I Goo(); } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538995")] - public async Task TestBug4777() - { - await TestInRegularAndScriptAsync( + public Task TestBug4777() + => TestInRegularAndScriptAsync( """ class C { @@ -5025,12 +4731,10 @@ void F(int x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539856")] - public async Task TestGenerateOnInvalidInvocation() - { - await TestMissingInRegularAndScriptAsync( + public Task TestGenerateOnInvalidInvocation() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -5044,12 +4748,10 @@ public Func Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539752")] - public async Task TestMissingOnMultipleLambdaInferences() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnMultipleLambdaInferences() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -5078,12 +4780,10 @@ public int Sum(Func selector) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540505")] - public async Task TestParameterTypeAmbiguity() - { - await TestInRegularAndScriptAsync( + public Task TestParameterTypeAmbiguity() + => TestInRegularAndScriptAsync( """ namespace N { @@ -5125,12 +4825,10 @@ class C } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541176")] - public async Task TestTernaryWithBodySidesBroken1() - { - await TestInRegularAndScriptAsync( + public Task TestTernaryWithBodySidesBroken1() + => TestInRegularAndScriptAsync( """ public class C { @@ -5158,12 +4856,10 @@ private int M(int a) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541176")] - public async Task TestTernaryWithBodySidesBroken2() - { - await TestInRegularAndScriptAsync( + public Task TestTernaryWithBodySidesBroken2() + => TestInRegularAndScriptAsync( """ public class C { @@ -5191,12 +4887,10 @@ private int M(int b) } } """); - } [Fact] - public async Task TestNotOnLeftOfAssign() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOnLeftOfAssign() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5217,12 +4911,10 @@ public static int ExtensionMethod(this String s) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541405")] - public async Task TestMissingOnImplementedInterfaceMethod() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnImplementedInterfaceMethod() + => TestMissingInRegularAndScriptAsync( """ class Program : ITest { @@ -5236,12 +4928,10 @@ interface ITest void Method(object t); } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541660")] - public async Task TestDelegateNamedVar() - { - await TestInRegularAndScriptAsync( + public Task TestDelegateNamedVar() + => TestInRegularAndScriptAsync( """ using System; @@ -5273,12 +4963,10 @@ private static void M(int x) delegate void var(int x); } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540991")] - public async Task TestErrorVersusNamedTypeInSignature() - { - await TestMissingAsync( + public Task TestErrorVersusNamedTypeInSignature() + => TestMissingAsync( """ using System; @@ -5302,8 +4990,7 @@ internal static void Test(global::Outer.Inner inner) } } """, -new TestParameters(new CSharpParseOptions(kind: SourceCodeKind.Regular))); - } + new TestParameters(new CSharpParseOptions(kind: SourceCodeKind.Regular))); [Theory] [InlineData("class")] @@ -5311,9 +4998,8 @@ internal static void Test(global::Outer.Inner inner) [InlineData("new()")] [InlineData("unmanaged")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542529")] - public async Task TestTypeParameterConstraints(string constraint) - { - await TestInRegularAndScriptAsync( + public Task TestTypeParameterConstraints(string constraint) + => TestInRegularAndScriptAsync( $$""" using System; @@ -5349,12 +5035,10 @@ private static void Bar(A x) where T : {{constraint}} } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542622")] - public async Task TestLambdaTypeParameters() - { - await TestInRegularAndScriptAsync( + public Task TestLambdaTypeParameters() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -5384,7 +5068,6 @@ private static void Bar(Func> value) } } """); - } [Theory] [InlineData("class")] @@ -5392,9 +5075,8 @@ private static void Bar(Func> value) [InlineData("new()")] [InlineData("unmanaged")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542626")] - public async Task TestMethodConstraints(string constraint) - { - await TestInRegularAndScriptAsync( + public Task TestMethodConstraints(string constraint) + => TestInRegularAndScriptAsync( $$""" using System; @@ -5430,12 +5112,10 @@ private static void Bar(A x) where T : {{constraint}} } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542627")] - public async Task TestCaptureMethodTypeParametersReferencedInOuterType1() - { - await TestInRegularAndScriptAsync( + public Task TestCaptureMethodTypeParametersReferencedInOuterType1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -5464,12 +5144,10 @@ private static void Bar(List.Enumerator x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542658")] - public async Task TestCaptureTypeParametersInConstraints() - { - await TestInRegularAndScriptAsync( + public Task TestCaptureTypeParametersInConstraints() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -5499,12 +5177,10 @@ private static void Bar(List x) where T : S } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542659")] - public async Task TestConstraintOrder1() - { - await TestInRegularAndScriptAsync( + public Task TestConstraintOrder1() + => TestInRegularAndScriptAsync( """ using System; @@ -5554,12 +5230,10 @@ private void Bar(A x) where T : Exception, ICloneable } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542678")] - public async Task TestConstraintOrder2() - { - await TestInRegularAndScriptAsync( + public Task TestConstraintOrder2() + => TestInRegularAndScriptAsync( """ using System; @@ -5609,12 +5283,10 @@ private void Bar(A x) where T : Exception, U } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542674")] - public async Task TestGenerateStaticMethodInField() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateStaticMethodInField() + => TestInRegularAndScriptAsync( """ using System; @@ -5636,12 +5308,10 @@ private static int Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542680")] - public async Task TestGenerateIntoConstrainedTypeParameter() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateIntoConstrainedTypeParameter() + => TestInRegularAndScriptAsync( """ interface I { @@ -5669,12 +5339,10 @@ static void Goo(T x) where T : I } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542750")] - public async Task TestCaptureOuterTypeParameter() - { - await TestInRegularAndScriptAsync( + public Task TestCaptureOuterTypeParameter() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -5715,12 +5383,10 @@ internal void Goo(List y) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542744")] - public async Task TestMostDerivedTypeParameter() - { - await TestInRegularAndScriptAsync( + public Task TestMostDerivedTypeParameter() + => TestInRegularAndScriptAsync( """ using System; @@ -5770,12 +5436,10 @@ private void Bar(A x) where T : ArgumentException } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543152")] - public async Task TestAnonymousTypeArgument() - { - await TestInRegularAndScriptAsync( + public Task TestAnonymousTypeArgument() + => TestInRegularAndScriptAsync( """ class C { @@ -5801,12 +5465,10 @@ private void M(object value) } } """); - } [Fact] - public async Task TestListOfAnonymousTypesArgument() - { - await TestInRegularAndScriptAsync( + public Task TestListOfAnonymousTypesArgument() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -5850,12 +5512,10 @@ private List Goo(T v) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543336")] - public async Task TestGenerateImplicitlyTypedArrays() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateImplicitlyTypedArrays() + => TestInRegularAndScriptAsync( """ class C { @@ -5881,12 +5541,10 @@ private int goo(int v) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543510")] - public async Task TestGenericArgWithMissingTypeParameter() - { - await TestMissingInRegularAndScriptAsync( + public Task TestGenericArgWithMissingTypeParameter() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -5901,12 +5559,10 @@ public static int goo(ref int i) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544334")] - public async Task TestDuplicateWithErrorType() - { - await TestMissingInRegularAndScriptAsync( + public Task TestDuplicateWithErrorType() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5923,12 +5579,10 @@ private void Goo(object x) } } """); - } [Fact] - public async Task TestNoGenerationIntoEntirelyHiddenType() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNoGenerationIntoEntirelyHiddenType() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -5944,12 +5598,10 @@ class D } #line default """); - } [Fact] - public async Task TestDoNotGenerateIntoHiddenRegion1() - { - await TestInRegularAndScriptAsync( + public Task TestDoNotGenerateIntoHiddenRegion1() + => TestInRegularAndScriptAsync( """ #line default class C @@ -5979,12 +5631,10 @@ void Goo() #line default } """); - } [Fact] - public async Task TestDoNotGenerateIntoHiddenRegion2() - { - await TestInRegularAndScriptAsync( + public Task TestDoNotGenerateIntoHiddenRegion2() + => TestInRegularAndScriptAsync( """ #line default class C @@ -6022,12 +5672,10 @@ private void Bar() } } """); - } [Fact] - public async Task TestDoNotGenerateIntoHiddenRegion3() - { - await TestInRegularAndScriptAsync( + public Task TestDoNotGenerateIntoHiddenRegion3() + => TestInRegularAndScriptAsync( """ #line default class C @@ -6073,12 +5721,10 @@ void Quux() } } """); - } [Fact] - public async Task TestDoNotAddImportsIntoHiddenRegion() - { - await TestInRegularAndScriptAsync( + public Task TestDoNotAddImportsIntoHiddenRegion() + => TestInRegularAndScriptAsync( """ #line hidden class C @@ -6110,13 +5756,11 @@ void Goo() #line default } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/784793")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545397")] - public async Task TestVarParameterTypeName() - { - await TestInRegularAndScriptAsync( + public Task TestVarParameterTypeName() + => TestInRegularAndScriptAsync( """ using System; @@ -6146,12 +5790,10 @@ private void goo(out object x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545269")] - public async Task TestGenerateInVenus1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestGenerateInVenus1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -6164,12 +5806,10 @@ void Goo() #line hidden } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538521")] - public async Task TestWithYieldReturnInMethod() - { - await TestInRegularAndScriptAsync( + public Task TestWithYieldReturnInMethod() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -6198,12 +5838,10 @@ private int Bar() } } """); - } [Fact] - public async Task TestWithYieldReturnInAsyncMethod() - { - await TestInRegularAndScriptAsync( + public Task TestWithYieldReturnInAsyncMethod() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -6232,12 +5870,10 @@ private int Bar() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30235")] - public async Task TestWithYieldReturnInLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestWithYieldReturnInLocalFunction() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -6272,12 +5908,10 @@ private int Bar() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/784793")] - public async Task TestGenerateMethodMissingForAnyArgumentInInvocationHavingErrorTypeAndNotBelongingToEnclosingNamedType() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodMissingForAnyArgumentInInvocationHavingErrorTypeAndNotBelongingToEnclosingNamedType() + => TestInRegularAndScriptAsync( """ class Program { @@ -6303,12 +5937,10 @@ private static void Main(object value) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907612")] - public async Task TestGenerateMethodWithLambda() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodWithLambda() + => TestInRegularAndScriptAsync( """ using System; @@ -6336,12 +5968,10 @@ private void Baz(Func value) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889349")] - public async Task TestGenerateMethodForDifferentParameterName() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodForDifferentParameterName() + => TestInRegularAndScriptAsync( """ class C { @@ -6371,12 +6001,10 @@ private void M(int x) void M(int y) { } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889349")] - public async Task TestGenerateMethodForDifferentParameterNameCaseSensitive() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodForDifferentParameterNameCaseSensitive() + => TestInRegularAndScriptAsync( """ class C { @@ -6406,12 +6034,10 @@ private void M(int Y) void M(int y) { } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/769760")] - public async Task TestGenerateMethodForSameNamedButGenericUsage() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodForSameNamedButGenericUsage() + => TestInRegularAndScriptAsync( """ using System; @@ -6451,12 +6077,10 @@ private static void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910589")] - public async Task TestGenerateMethodForNewErrorCodeCS7036() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodForNewErrorCodeCS7036() + => TestInRegularAndScriptAsync( """ using System; class C @@ -6482,12 +6106,10 @@ private void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/934729")] - public async Task TestGenerateMethodUnknownReturnTypeInLambda() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodUnknownReturnTypeInLambda() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; class C @@ -6514,12 +6136,10 @@ private void TestMethod(Func value) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] - public async Task TestGenerateMethodInUnsafeMethod() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInUnsafeMethod() + => TestInRegularAndScriptAsync( """ using System; class C { @@ -6541,12 +6161,10 @@ private unsafe void TestMethod(int* v) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] - public async Task TestGenerateMethodInUnsafeMethodWithPointerArray() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInUnsafeMethodWithPointerArray() + => TestInRegularAndScriptAsync( """ class C { @@ -6572,12 +6190,10 @@ private static unsafe void M2(int*[] o) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] - public async Task TestGenerateMethodInUnsafeBlock() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInUnsafeBlock() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -6615,12 +6231,10 @@ private static unsafe void TestMethod(char* value) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] - public async Task TestGenerateMethodInUnsafeMethodNoPointersInParameterList() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInUnsafeMethodNoPointersInParameterList() + => TestInRegularAndScriptAsync( """ using System; class C { @@ -6642,12 +6256,10 @@ private void TestMethod(int a) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] - public async Task TestGenerateMethodInUnsafeBlockNoPointers() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInUnsafeBlockNoPointers() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -6685,12 +6297,10 @@ private static void TestMethod(char value) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] - public async Task TestGenerateMethodUnsafeReturnType() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodUnsafeReturnType() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -6716,12 +6326,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] - public async Task TestGenerateMethodUnsafeClass() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodUnsafeClass() + => TestInRegularAndScriptAsync( """ using System; unsafe class Program @@ -6747,12 +6355,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] - public async Task TestGenerateMethodUnsafeNestedClass() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodUnsafeNestedClass() + => TestInRegularAndScriptAsync( """ using System; unsafe class Program @@ -6784,12 +6390,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] - public async Task TestGenerateMethodUnsafeNestedClass2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodUnsafeNestedClass2() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -6821,12 +6425,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestDoNotOfferMethodWithoutParenthesis() - { - await TestMissingInRegularAndScriptAsync( + public Task TestDoNotOfferMethodWithoutParenthesis() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -6836,12 +6438,10 @@ void Method() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestGenerateMethodInsideNameOf() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInsideNameOf() + => TestInRegularAndScriptAsync( """ class C { @@ -6867,12 +6467,10 @@ private object Z() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestGenerateMethodInsideNameOf2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInsideNameOf2() + => TestInRegularAndScriptAsync( """ class C { @@ -6898,12 +6496,10 @@ private object nameof(object x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestGenerateMethodInsideNameOf3() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInsideNameOf3() + => TestInRegularAndScriptAsync( """ class C { @@ -6929,12 +6525,10 @@ private object nameof(object y) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestGenerateMethodInsideNameOf4() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInsideNameOf4() + => TestInRegularAndScriptAsync( """ using System; @@ -6975,12 +6569,10 @@ internal static object Y() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestGenerateMethodInsideNameOf5() - { - await TestMissingInRegularAndScriptAsync( + public Task TestGenerateMethodInsideNameOf5() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -6990,12 +6582,10 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestGenerateMethodInsideNameOf6() - { - await TestMissingInRegularAndScriptAsync( + public Task TestGenerateMethodInsideNameOf6() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -7006,12 +6596,10 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestGenerateMethodInsideNameOf7() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInsideNameOf7() + => TestInRegularAndScriptAsync( """ class C { @@ -7041,12 +6629,10 @@ private object nameof(int y, string z) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestGenerateMethodInsideNameOf8() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInsideNameOf8() + => TestInRegularAndScriptAsync( """ using System; @@ -7074,12 +6660,10 @@ private object nameof(int v1, string v2) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestGenerateMethodInsideNameOf9() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInsideNameOf9() + => TestInRegularAndScriptAsync( """ class C { @@ -7105,12 +6689,10 @@ private object nameof(object y, object z) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestGenerateMethodInsideNameOf10() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInsideNameOf10() + => TestInRegularAndScriptAsync( """ class C { @@ -7136,12 +6718,10 @@ private object y() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestGenerateMethodInsideNameOf11() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInsideNameOf11() + => TestInRegularAndScriptAsync( """ class C { @@ -7167,12 +6747,10 @@ private object z() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestGenerateMethodInsideNameOf12() - { - await TestMissingInRegularAndScriptAsync( + public Task TestGenerateMethodInsideNameOf12() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -7189,12 +6767,10 @@ private object nameof(object y, object z) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestGenerateMethodInsideNameOf13() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInsideNameOf13() + => TestInRegularAndScriptAsync( """ using System; @@ -7232,12 +6808,10 @@ private object nameof(object y, object z) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestGenerateMethodInsideNameOf14() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInsideNameOf14() + => TestInRegularAndScriptAsync( """ using System; @@ -7275,12 +6849,10 @@ private object nameof(object y, object z) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestGenerateMethodInsideNameOf15() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInsideNameOf15() + => TestInRegularAndScriptAsync( """ using System; @@ -7318,12 +6890,10 @@ private object nameof(object y) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestGenerateMethodInsideNameOf16() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInsideNameOf16() + => TestInRegularAndScriptAsync( """ using System; @@ -7361,12 +6931,10 @@ private object nameof(object y) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1075289")] - public async Task TestGenerateMethodForInaccessibleMethod() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodForInaccessibleMethod() + => TestInRegularAndScriptAsync( """ namespace ConsoleApplication1 { @@ -7420,12 +6988,10 @@ private void Test() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestGenerateMethodInConditionalAccessMissing() - { - await TestMissingInRegularAndScriptAsync( + public Task TestGenerateMethodInConditionalAccessMissing() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -7435,12 +7001,10 @@ void Main(C a) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestGenerateMethodInConditionalAccess() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInConditionalAccess() + => TestInRegularAndScriptAsync( """ public class C { @@ -7466,12 +7030,10 @@ private C B() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestGenerateMethodInConditionalAccess2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInConditionalAccess2() + => TestInRegularAndScriptAsync( """ public class C { @@ -7497,12 +7059,10 @@ private int B() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestGenerateMethodInConditionalAccess3() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInConditionalAccess3() + => TestInRegularAndScriptAsync( """ public class C { @@ -7528,12 +7088,10 @@ private int B() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestGenerateMethodInConditionalAccess4() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInConditionalAccess4() + => TestInRegularAndScriptAsync( """ public class C { @@ -7559,12 +7117,10 @@ private MyStruct B() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestTestGenerateMethodInConditionalAccess5() - { - await TestInRegularAndScriptAsync( + public Task TestTestGenerateMethodInConditionalAccess5() + => TestInRegularAndScriptAsync( """ class C { @@ -7601,12 +7157,10 @@ internal C C() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestGenerateMethodInConditionalAccess6() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInConditionalAccess6() + => TestInRegularAndScriptAsync( """ class C { @@ -7643,12 +7197,10 @@ internal int C() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestGenerateMethodInConditionalAccess7() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInConditionalAccess7() + => TestInRegularAndScriptAsync( """ class C { @@ -7685,12 +7237,10 @@ internal int C() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestGenerateMethodInConditionalAccess7_B() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInConditionalAccess7_B() + => TestInRegularAndScriptAsync( """ class C { @@ -7729,12 +7279,10 @@ internal int C() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestGenerateMethodInConditionalAccess8() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInConditionalAccess8() + => TestInRegularAndScriptAsync( """ class C { @@ -7771,13 +7319,11 @@ internal object C() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [WorkItem("https://github.com/dotnet/roslyn/issues/39001")] - public async Task TestGenerateMethodInConditionalAccess9() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInConditionalAccess9() + => TestInRegularAndScriptAsync( """ struct C { @@ -7803,12 +7349,10 @@ private int Bar() } } """); - } [Fact] - public async Task TestGenerateMethodInPropertyInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInPropertyInitializer() + => TestInRegularAndScriptAsync( """ class Program { @@ -7828,12 +7372,10 @@ private static int y() } } """); - } [Fact] - public async Task TestGenerateMethodInExpressionBodiedProperty() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInExpressionBodiedProperty() + => TestInRegularAndScriptAsync( """ class Program { @@ -7853,12 +7395,10 @@ private int y() } } """); - } [Fact] - public async Task TestGenerateMethodInExpressionBodiedMethod() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInExpressionBodiedMethod() + => TestInRegularAndScriptAsync( """ class C { @@ -7878,12 +7418,10 @@ private static C x() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27647")] - public async Task TestGenerateMethodInExpressionBodiedAsyncTaskOfTMethod() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInExpressionBodiedAsyncTaskOfTMethod() + => TestInRegularAndScriptAsync( """ class C { @@ -7903,12 +7441,10 @@ private static C x() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27647")] - public async Task TestGenerateMethodInExpressionBodiedAsyncTaskMethod() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInExpressionBodiedAsyncTaskMethod() + => TestInRegularAndScriptAsync( """ class C { @@ -7928,12 +7464,10 @@ private static void x() } } """); - } [Fact] - public async Task TestGenerateMethodInExpressionBodiedAsyncVoidMethod() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInExpressionBodiedAsyncVoidMethod() + => TestInRegularAndScriptAsync( """ class C { @@ -7953,12 +7487,10 @@ private static void x() } } """); - } [Fact] - public async Task TestGenerateMethodInExpressionBodiedOperator() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInExpressionBodiedOperator() + => TestInRegularAndScriptAsync( """ class C { @@ -7978,12 +7510,10 @@ private static C x() } } """); - } [Fact] - public async Task TestGenerateMethodInDictionaryInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInDictionaryInitializer() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -8012,12 +7542,10 @@ private static string key() } } """); - } [Fact] - public async Task TestGenerateMethodInDictionaryInitializer2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInDictionaryInitializer2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -8046,12 +7574,10 @@ private static string One() } } """); - } [Fact] - public async Task TestGenerateMethodInDictionaryInitializer3() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInDictionaryInitializer3() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -8080,13 +7606,11 @@ private static int i() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/643")] [WorkItem("https://github.com/dotnet/roslyn/issues/14467")] - public async Task TestGenerateMethodWithConfigureAwaitFalse() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodWithConfigureAwaitFalse() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -8120,13 +7644,11 @@ private static async Task Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/643")] [WorkItem("https://github.com/dotnet/roslyn/issues/14467")] - public async Task TestGenerateMethodWithMethodChaining() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodWithMethodChaining() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -8160,13 +7682,11 @@ private static async Task Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/643")] [WorkItem("https://github.com/dotnet/roslyn/issues/14467")] - public async Task TestGenerateMethodWithMethodChaining2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodWithMethodChaining2() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -8204,12 +7724,10 @@ private static async Task M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] - public async Task TestInCollectionInitializers1() - { - await TestInRegularAndScriptAsync( + public Task TestInCollectionInitializers1() + => TestInRegularAndScriptAsync( """ class C { @@ -8235,12 +7753,10 @@ private int T() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] - public async Task TestInCollectionInitializers2() - { - await TestInRegularAndScriptAsync( + public Task TestInCollectionInitializers2() + => TestInRegularAndScriptAsync( """ class C { @@ -8266,12 +7782,10 @@ private bool T() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/5338")] - public async Task TestGenerateMethodLambdaOverload1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodLambdaOverload1() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Concurrent; @@ -8313,12 +7827,10 @@ private static Func CreateDeserializeDelegate(JToken key) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8010")] - public async Task TestGenerateMethodFromStaticProperty() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodFromStaticProperty() + => TestInRegularAndScriptAsync( """ using System; @@ -8352,12 +7864,10 @@ private static int Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8010")] - public async Task TestGenerateMethodFromStaticProperty_FieldInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodFromStaticProperty_FieldInitializer() + => TestInRegularAndScriptAsync( """ using System; @@ -8407,12 +7917,10 @@ private static OtherClass InitializeProperty() private static OtherClass s_field; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8230")] - public async Task TestGenerateMethodForOverloadedSignatureWithDelegateType() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodForOverloadedSignatureWithDelegateType() + => TestInRegularAndScriptAsync( """ using System; @@ -8462,12 +7970,10 @@ private static void OnChanged(object sender, EventArgs e) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/10004")] - public async Task TestGenerateMethodWithMultipleOfSameGenericType() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodWithMultipleOfSameGenericType() + => TestInRegularAndScriptAsync( """ using System; @@ -8503,12 +8009,10 @@ public static T M1(this T t) where T : C } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11141")] - public async Task InferTypeParameters1() - { - await TestInRegularAndScriptAsync( + public Task InferTypeParameters1() + => TestInRegularAndScriptAsync( """ using System; @@ -8538,12 +8042,10 @@ private T First(List list) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42986")] - public async Task MethodWithNativeIntegerTypes() - { - await TestInRegularAndScriptAsync( + public Task MethodWithNativeIntegerTypes() + => TestInRegularAndScriptAsync( """ class Class { @@ -8569,12 +8071,10 @@ void M(nint i, nuint i2) } } """); - } [Fact] - public async Task MethodWithTuple() - { - await TestInRegularAndScriptAsync( + public Task MethodWithTuple() + => TestInRegularAndScriptAsync( """ class Class { @@ -8600,12 +8100,10 @@ void Method() } } """); - } [Fact] - public async Task MethodWithTupleWithNames() - { - await TestInRegularAndScriptAsync( + public Task MethodWithTupleWithNames() + => TestInRegularAndScriptAsync( """ class Class { @@ -8631,12 +8129,10 @@ void Method() } } """); - } [Fact] - public async Task MethodWithTupleWithOneName() - { - await TestInRegularAndScriptAsync( + public Task MethodWithTupleWithOneName() + => TestInRegularAndScriptAsync( """ class Class { @@ -8662,12 +8158,10 @@ void Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/12147")] - public async Task TestOutVariableDeclaration_ImplicitlyTyped() - { - await TestInRegularAndScriptAsync( + public Task TestOutVariableDeclaration_ImplicitlyTyped() + => TestInRegularAndScriptAsync( """ class Class { @@ -8693,12 +8187,10 @@ private void Undefined(out object c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/12147")] - public async Task TestOutVariableDeclaration_ExplicitlyTyped() - { - await TestInRegularAndScriptAsync( + public Task TestOutVariableDeclaration_ExplicitlyTyped() + => TestInRegularAndScriptAsync( """ class Class { @@ -8724,12 +8216,10 @@ private void Undefined(out int c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/12147")] - public async Task TestOutVariableDeclaration_ImplicitlyTyped_NamedArgument() - { - await TestInRegularAndScriptAsync( + public Task TestOutVariableDeclaration_ImplicitlyTyped_NamedArgument() + => TestInRegularAndScriptAsync( """ class Class { @@ -8755,12 +8245,10 @@ private void Undefined(out object a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/12147")] - public async Task TestOutVariableDeclaration_ExplicitlyTyped_NamedArgument() - { - await TestInRegularAndScriptAsync( + public Task TestOutVariableDeclaration_ExplicitlyTyped_NamedArgument() + => TestInRegularAndScriptAsync( """ class Class { @@ -8786,12 +8274,10 @@ private void Undefined(out int a) } } """); - } [Fact] - public async Task TestOutVariableDeclaration_ImplicitlyTyped_CSharp6() - { - await TestAsync( + public Task TestOutVariableDeclaration_ImplicitlyTyped_CSharp6() + => TestAsync( """ class Class { @@ -8818,12 +8304,10 @@ private void Undefined(out object c) } """, parseOptions: TestOptions.Regular.WithLanguageVersion(CodeAnalysis.CSharp.LanguageVersion.CSharp6)); - } [Fact] - public async Task TestOutVariableDeclaration_ExplicitlyTyped_CSharp6() - { - await TestAsync( + public Task TestOutVariableDeclaration_ExplicitlyTyped_CSharp6() + => TestAsync( """ class Class { @@ -8850,12 +8334,10 @@ private void Undefined(out int c) } """, parseOptions: TestOptions.Regular.WithLanguageVersion(CodeAnalysis.CSharp.LanguageVersion.CSharp6)); - } [Fact] - public async Task TestOutVariableDeclaration_ImplicitlyTyped_NamedArgument_CSharp6() - { - await TestAsync( + public Task TestOutVariableDeclaration_ImplicitlyTyped_NamedArgument_CSharp6() + => TestAsync( """ class Class { @@ -8882,12 +8364,10 @@ private void Undefined(out object a) } """, parseOptions: TestOptions.Regular.WithLanguageVersion(CodeAnalysis.CSharp.LanguageVersion.CSharp6)); - } [Fact] - public async Task TestOutVariableDeclaration_ExplicitlyTyped_NamedArgument_CSharp6() - { - await TestAsync( + public Task TestOutVariableDeclaration_ExplicitlyTyped_NamedArgument_CSharp6() + => TestAsync( """ class Class { @@ -8914,12 +8394,10 @@ private void Undefined(out int a) } """, parseOptions: TestOptions.Regular.WithLanguageVersion(CodeAnalysis.CSharp.LanguageVersion.CSharp6)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14136")] - public async Task TestDeconstruction1() - { - await TestAsync( + public Task TestDeconstruction1() + => TestAsync( """ using System; @@ -8948,12 +8426,10 @@ public void M1() } """, parseOptions: TestOptions.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14136")] - public async Task TestDeconstruction2() - { - await TestAsync( + public Task TestDeconstruction2() + => TestAsync( """ using System; @@ -8982,13 +8458,11 @@ public void M1() } """, parseOptions: TestOptions.Regular); - } [Fact/*(Skip = "https://github.com/dotnet/roslyn/issues/15508")*/] [WorkItem("https://github.com/dotnet/roslyn/issues/14136")] - public async Task TestDeconstruction3() - { - await TestAsync( + public Task TestDeconstruction3() + => TestAsync( """ using System; @@ -9017,12 +8491,10 @@ private object Method() } """, parseOptions: TestOptions.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14136")] - public async Task TestDeconstruction4() - { - await TestAsync( + public Task TestDeconstruction4() + => TestAsync( """ using System; @@ -9051,12 +8523,10 @@ private object Method() } """, parseOptions: TestOptions.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15315")] - public async Task TestInferBooleanTypeBasedOnName1() - { - await TestInRegularAndScriptAsync( + public Task TestInferBooleanTypeBasedOnName1() + => TestInRegularAndScriptAsync( """ class Class { @@ -9082,12 +8552,10 @@ private bool IsPrime(int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15315")] - public async Task TestInferBooleanTypeBasedOnName2() - { - await TestInRegularAndScriptAsync( + public Task TestInferBooleanTypeBasedOnName2() + => TestInRegularAndScriptAsync( """ class Class { @@ -9113,12 +8581,10 @@ private object Issue(int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16398")] - public async Task TestReturnsByRef() - { - await TestInRegularAndScriptAsync( + public Task TestReturnsByRef() + => TestInRegularAndScriptAsync( """ using System; @@ -9146,12 +8612,10 @@ private ref int Bar() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18969")] - public async Task TestTupleElement1() - { - await TestAsync( + public Task TestTupleElement1() + => TestAsync( """ using System; @@ -9180,12 +8644,10 @@ private int Method() } """, parseOptions: TestOptions.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18969")] - public async Task TestTupleElement2() - { - await TestAsync( + public Task TestTupleElement2() + => TestAsync( """ using System; @@ -9214,12 +8676,10 @@ private string Method() } """, parseOptions: TestOptions.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25305")] - public async Task TestTupleAssignment() - { - await TestInRegularAndScriptAsync( + public Task TestTupleAssignment() + => TestInRegularAndScriptAsync( """ using System; @@ -9249,12 +8709,10 @@ void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25305")] - public async Task TestTupleAssignment2() - { - await TestInRegularAndScriptAsync( + public Task TestTupleAssignment2() + => TestInRegularAndScriptAsync( """ using System; @@ -9282,12 +8740,10 @@ void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16975")] - public async Task TestWithSameMethodNameAsTypeName1() - { - await TestAsync( + public Task TestWithSameMethodNameAsTypeName1() + => TestAsync( """ using System; @@ -9320,12 +8776,10 @@ private void Goo() class Goo { } """, parseOptions: TestOptions.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16975")] - public async Task TestWithSameMethodNameAsTypeName2() - { - await TestAsync( + public Task TestWithSameMethodNameAsTypeName2() + => TestAsync( """ using System; @@ -9358,12 +8812,10 @@ private void Goo() interface Goo { } """, parseOptions: TestOptions.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16975")] - public async Task TestWithSameMethodNameAsTypeName3() - { - await TestAsync( + public Task TestWithSameMethodNameAsTypeName3() + => TestAsync( """ using System; @@ -9396,12 +8848,10 @@ private void Goo() struct Goo { } """, parseOptions: TestOptions.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16975")] - public async Task TestWithSameMethodNameAsTypeName4() - { - await TestAsync( + public Task TestWithSameMethodNameAsTypeName4() + => TestAsync( """ using System; @@ -9434,12 +8884,10 @@ private void Goo() delegate void Goo() """, parseOptions: TestOptions.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16975")] - public async Task TestWithSameMethodNameAsTypeName5() - { - await TestAsync( + public Task TestWithSameMethodNameAsTypeName5() + => TestAsync( """ using System; @@ -9472,12 +8920,10 @@ private void Goo() namespace Goo { } """, parseOptions: TestOptions.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16975")] - public async Task TestWithSameMethodNameAsTypeName6() - { - await TestAsync( + public Task TestWithSameMethodNameAsTypeName6() + => TestAsync( """ using System; @@ -9510,12 +8956,10 @@ private void Goo() enum Goo { One } """, parseOptions: TestOptions.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26957")] - public async Task NotOnNonExistedMetadataMemberWhenInsideLambda() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnNonExistedMetadataMemberWhenInsideLambda() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -9534,12 +8978,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26993")] - public async Task TestGenerateMethodInExpressionBodiedGetter() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInExpressionBodiedGetter() + => TestInRegularAndScriptAsync( """ class Class { @@ -9565,12 +9007,10 @@ private int GenerateMethod() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26993")] - public async Task TestGenerateMethodInExpressionBodiedSetter() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInExpressionBodiedSetter() + => TestInRegularAndScriptAsync( """ class Class { @@ -9596,12 +9036,10 @@ private void GenerateMethod(int value) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26993")] - public async Task TestGenerateMethodInExpressionBodiedLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInExpressionBodiedLocalFunction() + => TestInRegularAndScriptAsync( """ class Class { @@ -9627,12 +9065,10 @@ private int GenerateMethod() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27647")] - public async Task TestGenerateMethodInExpressionBodiedAsyncTaskOfTLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInExpressionBodiedAsyncTaskOfTLocalFunction() + => TestInRegularAndScriptAsync( """ class Class { @@ -9658,12 +9094,10 @@ private int GenerateMethod() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27647")] - public async Task TestGenerateMethodInExpressionBodiedAsyncTaskLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInExpressionBodiedAsyncTaskLocalFunction() + => TestInRegularAndScriptAsync( """ class Class { @@ -9689,12 +9123,10 @@ private void GenerateMethod() } } """); - } [Fact] - public async Task TestGenerateMethodInExpressionBodiedAsyncVoidLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInExpressionBodiedAsyncVoidLocalFunction() + => TestInRegularAndScriptAsync( """ class Class { @@ -9720,12 +9152,10 @@ private void GenerateMethod() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26993")] - public async Task TestGenerateMethodInBlockBodiedLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInBlockBodiedLocalFunction() + => TestInRegularAndScriptAsync( """ class Class { @@ -9757,12 +9187,10 @@ private int GenerateMethod() } } """); - } [Fact] - public async Task TestGenerateMethodInBlockBodiedAsyncTaskOfTLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInBlockBodiedAsyncTaskOfTLocalFunction() + => TestInRegularAndScriptAsync( """ class Class { @@ -9794,12 +9222,10 @@ private int GenerateMethod() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26993")] - public async Task TestGenerateMethodInBlockBodiedLocalFunctionInsideLambdaExpression() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInBlockBodiedLocalFunctionInsideLambdaExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -9839,12 +9265,10 @@ private int GenerateMethod() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26993")] - public async Task TestGenerateMethodInExpressionBodiedLocalFunctionInsideLambdaExpression() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateMethodInExpressionBodiedLocalFunctionInsideLambdaExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -9878,12 +9302,10 @@ private int GenerateMethod() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24138")] - public async Task TestInCaseWhenClause() - { - await TestInRegularAndScriptAsync( + public Task TestInCaseWhenClause() + => TestInRegularAndScriptAsync( """ using System; @@ -9919,12 +9341,10 @@ private bool GreaterThanZero(int i) } } """); - } [Fact] - public async Task TestWithFunctionPointerArgument() - { - await TestInRegularAndScriptAsync( + public Task TestWithFunctionPointerArgument() + => TestInRegularAndScriptAsync( """ using System; @@ -9954,12 +9374,10 @@ private unsafe void M2(delegate* y) } } """); - } [Fact] - public async Task TestWithFunctionPointerUnmanagedConvention() - { - await TestInRegularAndScriptAsync( + public Task TestWithFunctionPointerUnmanagedConvention() + => TestInRegularAndScriptAsync( """ using System; @@ -9989,7 +9407,6 @@ private unsafe void M2(delegate* unmanaged y) } } """); - } [Theory] [InlineData("Cdecl")] @@ -9998,9 +9415,8 @@ private unsafe void M2(delegate* unmanaged y) [InlineData("Stdcall")] [InlineData("Thiscall, Stdcall")] [InlineData("Bad")] // Bad conventions should still be generatable - public async Task TestWithFunctionPointerUnmanagedSpecificConvention(string convention) - { - await TestInRegularAndScriptAsync( + public Task TestWithFunctionPointerUnmanagedSpecificConvention(string convention) + => TestInRegularAndScriptAsync( $$""" using System; @@ -10030,12 +9446,10 @@ private unsafe void M2(delegate* unmanaged[{{convention}}] y) } } """); - } [Fact] - public async Task TestWithFunctionPointerUnmanagedMissingConvention() - { - await TestInRegularAndScriptAsync( + public Task TestWithFunctionPointerUnmanagedMissingConvention() + => TestInRegularAndScriptAsync( """ using System; @@ -10065,12 +9479,10 @@ private unsafe void M2(delegate* unmanaged y) } } """); - } [Fact] - public async Task TestNegativeIfGeneratingInDocumentFromSourceGenerator() - { - await TestMissingAsync( + public Task TestNegativeIfGeneratingInDocumentFromSourceGenerator() + => TestMissingAsync( """ @@ -10091,12 +9503,10 @@ public class GeneratedClass """); - } [Fact] - public async Task TestIfGeneratingInPartialClassWithFileFromSourceGenerator() - { - await TestInRegularAndScriptAsync( + public Task TestIfGeneratingInPartialClassWithFileFromSourceGenerator() + => TestInRegularAndScriptAsync( """ @@ -10137,12 +9547,10 @@ internal static void Method() } """); - } [Fact] - public async Task TestInSwitchExpression1() - { - await TestInRegularAndScriptAsync( + public Task TestInSwitchExpression1() + => TestInRegularAndScriptAsync( """ using System; @@ -10176,12 +9584,10 @@ private string Goo() } } """); - } [Fact] - public async Task TestInSwitchExpression2() - { - await TestInRegularAndScriptAsync( + public Task TestInSwitchExpression2() + => TestInRegularAndScriptAsync( """ using System; @@ -10217,12 +9623,10 @@ private string Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63883")] - public async Task TestNullableCoalesce() - { - await TestInRegularAndScriptAsync( + public Task TestNullableCoalesce() + => TestInRegularAndScriptAsync( """ using System; @@ -10248,12 +9652,10 @@ class Example int? C() => null; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28996")] - public async Task TestPreferOverloadWithMatchingParameterCount() - { - await TestInRegularAndScriptAsync( + public Task TestPreferOverloadWithMatchingParameterCount() + => TestInRegularAndScriptAsync( """ using System; @@ -10287,12 +9689,10 @@ private void Baz(object obj) protected abstract void Goo(Action action, object arg); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44861")] - public async Task GenerateBasedOnFutureUsage1() - { - await TestInRegularAndScriptAsync( + public Task GenerateBasedOnFutureUsage1() + => TestInRegularAndScriptAsync( """ using System; @@ -10322,12 +9722,10 @@ private int NewExpr() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44861")] - public async Task GenerateBasedOnFutureUsage2() - { - await TestInRegularAndScriptAsync( + public Task GenerateBasedOnFutureUsage2() + => TestInRegularAndScriptAsync( """ using System; @@ -10361,12 +9759,10 @@ private bool NewExpr() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44861")] - public async Task GenerateBasedOnFutureUsage3() - { - await TestInRegularAndScriptAsync( + public Task GenerateBasedOnFutureUsage3() + => TestInRegularAndScriptAsync( """ using System; @@ -10398,12 +9794,10 @@ private int NewExpr() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44861")] - public async Task GenerateBasedOnFutureUsage4() - { - await TestInRegularAndScriptAsync( + public Task GenerateBasedOnFutureUsage4() + => TestInRegularAndScriptAsync( """ using System; @@ -10437,12 +9831,10 @@ int M() void Goo(string x, int y) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/12708")] - public async Task GenerateEventHookupWithExistingMethod() - { - await TestInRegularAndScriptAsync( + public Task GenerateEventHookupWithExistingMethod() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Specialized; @@ -10478,12 +9870,10 @@ private void OnChanged(object sender, NotifyCollectionChangedEventArgs e) private void OnChanged() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29761")] - public async Task GenerateAlternativeNamesForFuncActionDelegates1() - { - await TestInRegularAndScriptAsync( + public Task GenerateAlternativeNamesForFuncActionDelegates1() + => TestInRegularAndScriptAsync( """ using System; @@ -10527,12 +9917,10 @@ class Context { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29761")] - public async Task GenerateAlternativeNamesForFuncActionDelegates2() - { - await TestInRegularAndScriptAsync( + public Task GenerateAlternativeNamesForFuncActionDelegates2() + => TestInRegularAndScriptAsync( """ using System; @@ -10576,12 +9964,10 @@ class Context { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37825")] - public async Task InferTypeFromNextSwitchArm1() - { - await TestInRegularAndScriptAsync( + public Task InferTypeFromNextSwitchArm1() + => TestInRegularAndScriptAsync( """ using System; @@ -10627,12 +10013,10 @@ private int Bar() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37825")] - public async Task InferTypeFromNextSwitchArm2() - { - await TestInRegularAndScriptAsync( + public Task InferTypeFromNextSwitchArm2() + => TestInRegularAndScriptAsync( """ using System; @@ -10668,12 +10052,10 @@ private object Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37825")] - public async Task InferTypeFromNextSwitchArm3() - { - await TestInRegularAndScriptAsync( + public Task InferTypeFromNextSwitchArm3() + => TestInRegularAndScriptAsync( """ using System; @@ -10709,12 +10091,10 @@ private object Bar() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50764")] - public async Task InferMethodFromAddressOf1() - { - await TestInRegularAndScriptAsync( + public Task InferMethodFromAddressOf1() + => TestInRegularAndScriptAsync( """ using System; @@ -10742,12 +10122,10 @@ private static int Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50764")] - public async Task InferMethodFromAddressOf2() - { - await TestInRegularAndScriptAsync( + public Task InferMethodFromAddressOf2() + => TestInRegularAndScriptAsync( """ using System; @@ -10775,12 +10153,10 @@ private static void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50764")] - public async Task InferMethodFromAddressOf3() - { - await TestInRegularAndScriptAsync( + public Task InferMethodFromAddressOf3() + => TestInRegularAndScriptAsync( """ using System; @@ -10808,12 +10184,10 @@ private static bool Goo(int arg) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70565")] - public async Task GenerateInsideStaticLambda1() - { - await TestInRegularAndScriptAsync( + public Task GenerateInsideStaticLambda1() + => TestInRegularAndScriptAsync( """ using System; @@ -10847,12 +10221,10 @@ private static void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70565")] - public async Task GenerateInsideStaticLocalFunction1() - { - await TestInRegularAndScriptAsync( + public Task GenerateInsideStaticLocalFunction1() + => TestInRegularAndScriptAsync( """ using System; @@ -10886,12 +10258,10 @@ private static void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71980")] - public async Task AssignToTuple1() - { - await TestInRegularAndScriptAsync( + public Task AssignToTuple1() + => TestInRegularAndScriptAsync( """ using System; @@ -10919,12 +10289,10 @@ private object NewExpr() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71980")] - public async Task AssignToTuple2() - { - await TestInRegularAndScriptAsync( + public Task AssignToTuple2() + => TestInRegularAndScriptAsync( """ using System; @@ -10952,12 +10320,10 @@ private object NewExpr() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71980")] - public async Task AssignToTuple3() - { - await TestInRegularAndScriptAsync( + public Task AssignToTuple3() + => TestInRegularAndScriptAsync( """ using System; @@ -10985,12 +10351,10 @@ private object NewExpr() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71980")] - public async Task AssignToTuple4() - { - await TestInRegularAndScriptAsync( + public Task AssignToTuple4() + => TestInRegularAndScriptAsync( """ using System; @@ -11018,12 +10382,10 @@ int M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71980")] - public async Task AssignToTuple5() - { - await TestInRegularAndScriptAsync( + public Task AssignToTuple5() + => TestInRegularAndScriptAsync( """ using System; @@ -11051,12 +10413,10 @@ private object NewExpr() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71980")] - public async Task AssignToTuple6() - { - await TestInRegularAndScriptAsync( + public Task AssignToTuple6() + => TestInRegularAndScriptAsync( """ using System; @@ -11084,12 +10444,10 @@ private object NewExpr() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71980")] - public async Task AssignToTuple7() - { - await TestMissingInRegularAndScriptAsync( + public Task AssignToTuple7() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -11104,12 +10462,10 @@ async Task M() Task<(int, string)> G() => default; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71980")] - public async Task AssignToTuple8() - { - await TestInRegularAndScriptAsync( + public Task AssignToTuple8() + => TestInRegularAndScriptAsync( """ using System; @@ -11137,12 +10493,10 @@ int M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70803")] - public async Task GenerateInPrimaryConstructorBaseList() - { - await TestInRegularAndScriptAsync( + public Task GenerateInPrimaryConstructorBaseList() + => TestInRegularAndScriptAsync( """ using System; @@ -11163,12 +10517,10 @@ private static int NewExpr() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60136")] - public async Task GenerateIntoTopLevelProgramWithPartialType() - { - await TestAsync( + public Task GenerateIntoTopLevelProgramWithPartialType() + => TestAsync( """ Program.[|Test|](); @@ -11189,12 +10541,10 @@ private static void Test() } } """, parseOptions: CSharpParseOptions.Default); - } [Fact] - public async Task TestNullConditionalAssignment1() - { - await TestAsync( + public Task TestNullConditionalAssignment1() + => TestAsync( """ using System; @@ -11226,12 +10576,10 @@ private int Goo() } } """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersionExtensions.CSharpNext)); - } [Fact] - public async Task TestNullConditionalAssignment2() - { - await TestAsync( + public Task TestNullConditionalAssignment2() + => TestAsync( """ using System; @@ -11265,5 +10613,4 @@ private int Goo() } } """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersionExtensions.CSharpNext)); - } } diff --git a/src/Analyzers/CSharp/Tests/HideBase/HideBaseTests.cs b/src/Analyzers/CSharp/Tests/HideBase/HideBaseTests.cs index 5143ad4375571..5125c6203ccff 100644 --- a/src/Analyzers/CSharp/Tests/HideBase/HideBaseTests.cs +++ b/src/Analyzers/CSharp/Tests/HideBase/HideBaseTests.cs @@ -25,9 +25,8 @@ internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProvide => (null, new HideBaseCodeFixProvider()); [Fact] - public async Task TestAddNewToProperty() - { - await TestInRegularAndScriptAsync( + public Task TestAddNewToProperty() + => TestInRegularAndScriptAsync( """ class Application { @@ -50,12 +49,10 @@ class App : Application public static new App Current { get; set; } } """); - } [Fact] - public async Task TestAddNewToMethod() - { - await TestInRegularAndScriptAsync( + public Task TestAddNewToMethod() + => TestInRegularAndScriptAsync( """ class Application { @@ -86,12 +83,10 @@ class App : Application } } """); - } [Fact] - public async Task TestAddNewToField() - { - await TestInRegularAndScriptAsync( + public Task TestAddNewToField() + => TestInRegularAndScriptAsync( """ class Application { @@ -114,12 +109,10 @@ class App : Application public new int Test; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18391")] - public async Task TestAddNewToConstant() - { - await TestInRegularAndScriptAsync( + public Task TestAddNewToConstant() + => TestInRegularAndScriptAsync( """ class Application { @@ -142,12 +135,10 @@ class App : Application public new const int Test = Application.Test + 1; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14455")] - public async Task TestAddNewToConstantInternalFields() - { - await TestInRegularAndScriptAsync( + public Task TestAddNewToConstantInternalFields() + => TestInRegularAndScriptAsync( """ class A { internal const int i = 0; } class B : A { [|internal const int i = 1;|] } @@ -156,7 +147,6 @@ class B : A { [|internal const int i = 1;|] } class A { internal const int i = 0; } class B : A { internal new const int i = 1; } """); - } [Fact] public async Task TestAddNewToDisorderedModifiers() diff --git a/src/Analyzers/CSharp/Tests/ImplementAbstractClass/ImplementAbstractClassTests.cs b/src/Analyzers/CSharp/Tests/ImplementAbstractClass/ImplementAbstractClassTests.cs index 3e3d46bac068b..3a04ca6bf5652 100644 --- a/src/Analyzers/CSharp/Tests/ImplementAbstractClass/ImplementAbstractClassTests.cs +++ b/src/Analyzers/CSharp/Tests/ImplementAbstractClass/ImplementAbstractClassTests.cs @@ -57,9 +57,8 @@ internal Task TestAllOptionsOffAsync( } [Fact] - public async Task TestSimpleMethods() - { - await TestAllOptionsOffAsync( + public Task TestSimpleMethods() + => TestAllOptionsOffAsync( """ abstract class Goo { @@ -116,12 +115,10 @@ protected override string GooMethod() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16434")] - public async Task TestMethodWithTupleNames() - { - await TestAllOptionsOffAsync( + public Task TestMethodWithTupleNames() + => TestAllOptionsOffAsync( """ abstract class Base { @@ -146,12 +143,10 @@ protected override (int a, int b) Method((string, string d) x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70623")] - public async Task TestMethodWithNullableDynamic() - { - await TestInRegularAndScriptAsync( + public Task TestMethodWithNullableDynamic() + => TestInRegularAndScriptAsync( """ abstract class Base { @@ -181,12 +176,10 @@ class Program : Base OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable )); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543234")] - public async Task TestNotAvailableForStruct() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotAvailableForStruct() + => TestMissingInRegularAndScriptAsync( """ abstract class Goo { @@ -197,12 +190,10 @@ struct [|Program|] : Goo { } """); - } [Fact] - public async Task TestOptionalIntParameter() - { - await TestAllOptionsOffAsync( + public Task TestOptionalIntParameter() + => TestAllOptionsOffAsync( """ abstract class d { @@ -227,12 +218,10 @@ public override void goo(int x = 3) } } """); - } [Fact] - public async Task TestOptionalCharParameter() - { - await TestAllOptionsOffAsync( + public Task TestOptionalCharParameter() + => TestAllOptionsOffAsync( """ abstract class d { @@ -257,12 +246,10 @@ public override void goo(char x = 'a') } } """); - } [Fact] - public async Task TestOptionalStringParameter() - { - await TestAllOptionsOffAsync( + public Task TestOptionalStringParameter() + => TestAllOptionsOffAsync( """ abstract class d { @@ -287,12 +274,10 @@ public override void goo(string x = "x") } } """); - } [Fact] - public async Task TestOptionalShortParameter() - { - await TestAllOptionsOffAsync( + public Task TestOptionalShortParameter() + => TestAllOptionsOffAsync( """ abstract class d { @@ -317,12 +302,10 @@ public override void goo(short x = 3) } } """); - } [Fact] - public async Task TestOptionalDecimalParameter() - { - await TestAllOptionsOffAsync( + public Task TestOptionalDecimalParameter() + => TestAllOptionsOffAsync( """ abstract class d { @@ -347,12 +330,10 @@ public override void goo(decimal x = 3) } } """); - } [Fact] - public async Task TestOptionalDoubleParameter() - { - await TestAllOptionsOffAsync( + public Task TestOptionalDoubleParameter() + => TestAllOptionsOffAsync( """ abstract class d { @@ -377,12 +358,10 @@ public override void goo(double x = 3) } } """); - } [Fact] - public async Task TestOptionalLongParameter() - { - await TestAllOptionsOffAsync( + public Task TestOptionalLongParameter() + => TestAllOptionsOffAsync( """ abstract class d { @@ -407,12 +386,10 @@ public override void goo(long x = 3) } } """); - } [Fact] - public async Task TestOptionalFloatParameter() - { - await TestAllOptionsOffAsync( + public Task TestOptionalFloatParameter() + => TestAllOptionsOffAsync( """ abstract class d { @@ -437,12 +414,10 @@ public override void goo(float x = 3) } } """); - } [Fact] - public async Task TestOptionalUshortParameter() - { - await TestAllOptionsOffAsync( + public Task TestOptionalUshortParameter() + => TestAllOptionsOffAsync( """ abstract class d { @@ -467,12 +442,10 @@ public override void goo(ushort x = 3) } } """); - } [Fact] - public async Task TestOptionalUintParameter() - { - await TestAllOptionsOffAsync( + public Task TestOptionalUintParameter() + => TestAllOptionsOffAsync( """ abstract class d { @@ -497,12 +470,10 @@ public override void goo(uint x = 3) } } """); - } [Fact] - public async Task TestOptionalUlongParameter() - { - await TestAllOptionsOffAsync( + public Task TestOptionalUlongParameter() + => TestAllOptionsOffAsync( """ abstract class d { @@ -527,12 +498,10 @@ public override void goo(ulong x = 3) } } """); - } [Fact] - public async Task TestOptionalStructParameter_CSharp7() - { - await TestAllOptionsOffAsync( + public Task TestOptionalStructParameter_CSharp7() + => TestAllOptionsOffAsync( """ struct b { @@ -566,12 +535,10 @@ class c : d } """, parseOptions: TestOptions.Regular7); - } [Fact] - public async Task TestOptionalStructParameter() - { - await TestAllOptionsOffAsync( + public Task TestOptionalStructParameter() + => TestAllOptionsOffAsync( """ struct b { @@ -604,12 +571,10 @@ public override void goo(b x = default) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")] - public async Task TestOptionalNullableStructParameter() - { - await TestAllOptionsOffAsync( + public Task TestOptionalNullableStructParameter() + => TestAllOptionsOffAsync( """ struct b { @@ -642,12 +607,10 @@ public override void m(b? x = null, b? y = null) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")] - public async Task TestOptionalNullableIntParameter() - { - await TestAllOptionsOffAsync( + public Task TestOptionalNullableIntParameter() + => TestAllOptionsOffAsync( """ abstract class d { @@ -672,12 +635,10 @@ public override void m(int? x = 5, int? y = null) } } """); - } [Fact] - public async Task TestOptionalObjectParameter() - { - await TestAllOptionsOffAsync( + public Task TestOptionalObjectParameter() + => TestAllOptionsOffAsync( """ class b { @@ -710,12 +671,10 @@ public override void goo(b x = null) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543883")] - public async Task TestDifferentAccessorAccessibility() - { - await TestAllOptionsOffAsync( + public Task TestDifferentAccessorAccessibility() + => TestAllOptionsOffAsync( """ abstract class c1 { @@ -748,12 +707,10 @@ internal set } } """); - } [Fact] - public async Task TestEvent1() - { - await TestAllOptionsOffAsync( + public Task TestEvent1() + => TestAllOptionsOffAsync( """ using System; @@ -779,12 +736,10 @@ class D : C public override event Action E; } """); - } [Fact] - public async Task TestIndexer1() - { - await TestAllOptionsOffAsync( + public Task TestIndexer1() + => TestAllOptionsOffAsync( """ using System; @@ -839,12 +794,10 @@ internal set } } """); - } [Fact] - public async Task TestMissingInHiddenType() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingInHiddenType() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -859,12 +812,10 @@ class [|Program|] : Goo } #line default """); - } [Fact] - public async Task TestGenerateIfLocationAvailable() - { - await TestAllOptionsOffAsync( + public Task TestGenerateIfLocationAvailable() + => TestAllOptionsOffAsync( """ #line default using System; @@ -902,12 +853,10 @@ void Bar() } #line default """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545585")] - public async Task TestOnlyGenerateUnimplementedAccessors() - { - await TestAllOptionsOffAsync( + public Task TestOnlyGenerateUnimplementedAccessors() + => TestAllOptionsOffAsync( """ using System; @@ -961,12 +910,10 @@ public override int X } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545615")] - public async Task TestParamsArray() - { - await TestAllOptionsOffAsync( + public Task TestParamsArray() + => TestAllOptionsOffAsync( """ class A { @@ -1005,12 +952,10 @@ public override void Goo(int x, params int[] y) } } """); - } [Fact] - public async Task TestParamsCollection() - { - await TestAllOptionsOffAsync( + public Task TestParamsCollection() + => TestAllOptionsOffAsync( """ using System.Collections.Generic; @@ -1053,12 +998,10 @@ public override void Goo(int x, params IEnumerable y) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545636")] - public async Task TestNullPointerType() - { - await TestAllOptionsOffAsync( + public Task TestNullPointerType() + => TestAllOptionsOffAsync( """ abstract class C { @@ -1083,12 +1026,10 @@ public override unsafe void Goo(int* x = null) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545637")] - public async Task TestErrorTypeCalledVar() - { - await TestAllOptionsOffAsync( + public Task TestErrorTypeCalledVar() + => TestAllOptionsOffAsync( """ extern alias var; @@ -1117,12 +1058,10 @@ public override void Goo(X x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] - public async Task Bugfix_581500() - { - await TestAllOptionsOffAsync( + public Task Bugfix_581500() + => TestAllOptionsOffAsync( """ abstract class A { @@ -1153,12 +1092,10 @@ public override void M(B.T x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/625442")] - public async Task Bugfix_625442() - { - await TestAllOptionsOffAsync( + public Task Bugfix_625442() + => TestAllOptionsOffAsync( """ abstract class A { @@ -1185,12 +1122,10 @@ public override void M(A.B>.B.T x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2407")] - public async Task ImplementClassWithInaccessibleMembers() - { - await TestAllOptionsOffAsync( + public Task ImplementClassWithInaccessibleMembers() + => TestAllOptionsOffAsync( """ using System; using System.Globalization; @@ -1274,12 +1209,10 @@ internal override int GetYearInfo(int LunarYear, int Index) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/13149")] - public async Task TestPartialClass1() - { - await TestAllOptionsOffAsync( + public Task TestPartialClass1() + => TestAllOptionsOffAsync( """ using System; @@ -1316,12 +1249,10 @@ partial class A { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/13149")] - public async Task TestPartialClass2() - { - await TestAllOptionsOffAsync( + public Task TestPartialClass2() + => TestAllOptionsOffAsync( """ using System; @@ -1358,12 +1289,10 @@ partial class A : Base { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] - public async Task TestCodeStyle_Method1() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle_Method1() + => TestInRegularAndScriptAsync( """ abstract class A { @@ -1385,12 +1314,10 @@ class T : A public override void M(int x) => throw new System.NotImplementedException(); } """, options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] - public async Task TestCodeStyle_Property1() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle_Property1() + => TestInRegularAndScriptAsync( """ abstract class A { @@ -1412,12 +1339,10 @@ class T : A public override int M => throw new System.NotImplementedException(); } """, options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] - public async Task TestCodeStyle_Property3() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle_Property3() + => TestInRegularAndScriptAsync( """ abstract class A { @@ -1449,12 +1374,10 @@ public override int M { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption2.Silent }, }); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] - public async Task TestCodeStyle_Property4() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle_Property4() + => TestInRegularAndScriptAsync( """ abstract class A { @@ -1491,12 +1414,10 @@ public override int M { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption2.Silent }, }); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] - public async Task TestCodeStyle_Indexers1() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle_Indexers1() + => TestInRegularAndScriptAsync( """ abstract class A { @@ -1518,12 +1439,10 @@ class T : A public override int this[int i] => throw new System.NotImplementedException(); } """, options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] - public async Task TestCodeStyle_Indexer3() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle_Indexer3() + => TestInRegularAndScriptAsync( """ abstract class A { @@ -1555,12 +1474,10 @@ public override int this[int i] { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption2.Silent }, }); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] - public async Task TestCodeStyle_Indexer4() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle_Indexer4() + => TestInRegularAndScriptAsync( """ abstract class A { @@ -1597,12 +1514,10 @@ public override int this[int i] { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption2.Silent }, }); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] - public async Task TestCodeStyle_Accessor1() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle_Accessor1() + => TestInRegularAndScriptAsync( """ abstract class A { @@ -1628,12 +1543,10 @@ class T : A { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never, NotificationOption2.Silent }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent }, }); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] - public async Task TestCodeStyle_Accessor3() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle_Accessor3() + => TestInRegularAndScriptAsync( """ abstract class A { @@ -1655,12 +1568,10 @@ class T : A public override int M { set => throw new System.NotImplementedException(); } } """, options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] - public async Task TestCodeStyle_Accessor4() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle_Accessor4() + => TestInRegularAndScriptAsync( """ abstract class A { @@ -1682,7 +1593,6 @@ class T : A public override int M { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } } """, options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15387")] public async Task TestWithGroupingOff1() @@ -1717,9 +1627,8 @@ void Goo() { } } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17274")] - public async Task TestAddedUsingWithBanner1() - { - await TestInRegularAndScriptAsync( + public Task TestAddedUsingWithBanner1() + => TestInRegularAndScriptAsync( """ // Copyright ... @@ -1759,12 +1668,10 @@ public override void Bar(List values) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17562")] - public async Task TestNullableOptionalParameters_CSharp7() - { - await TestInRegularAndScriptAsync( + public Task TestNullableOptionalParameters_CSharp7() + => TestInRegularAndScriptAsync( """ struct V { } abstract class B @@ -1797,12 +1704,10 @@ public override void M2(T? i = null) } """, parseOptions: TestOptions.Regular7); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17562")] - public async Task TestNullableOptionalParametersCSharp7() - { - await TestAsync( + public Task TestNullableOptionalParametersCSharp7() + => TestAsync( """ struct V { } abstract class B @@ -1834,12 +1739,10 @@ public override void M2(T? i = null) } } """, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp7)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17562")] - public async Task TestNullableOptionalParameters() - { - await TestInRegularAndScriptAsync( + public Task TestNullableOptionalParameters() + => TestInRegularAndScriptAsync( """ struct V { } abstract class B @@ -1871,7 +1774,6 @@ public override void M2(T? i = null) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/5898")] [WorkItem("https://github.com/dotnet/roslyn/issues/13932")] @@ -1914,9 +1816,8 @@ class C : AbstractClass } [Theory, CombinatorialData] - public async Task TestRefWithMethod_Parameters([CombinatorialValues("ref", "in", "ref readonly")] string modifier) - { - await TestInRegularAndScriptAsync( + public Task TestRefWithMethod_Parameters([CombinatorialValues("ref", "in", "ref readonly")] string modifier) + => TestInRegularAndScriptAsync( $$""" abstract class TestParent { @@ -1939,12 +1840,10 @@ public override void Method({{modifier}} int p) } } """); - } [Fact] - public async Task TestRefReadOnlyWithMethod_ReturnType() - { - await TestInRegularAndScriptAsync( + public Task TestRefReadOnlyWithMethod_ReturnType() + => TestInRegularAndScriptAsync( """ abstract class TestParent { @@ -1967,12 +1866,10 @@ public override ref readonly int Method() } } """); - } [Fact] - public async Task TestRefReadOnlyWithProperty() - { - await TestInRegularAndScriptAsync( + public Task TestRefReadOnlyWithProperty() + => TestInRegularAndScriptAsync( """ abstract class TestParent { @@ -1992,12 +1889,10 @@ public class Test : TestParent public override ref readonly int Property => throw new System.NotImplementedException(); } """); - } [Theory, CombinatorialData] - public async Task TestRefWithIndexer_Parameters([CombinatorialValues("ref", "in", "ref readonly")] string modifier) - { - await TestInRegularAndScriptAsync( + public Task TestRefWithIndexer_Parameters([CombinatorialValues("ref", "in", "ref readonly")] string modifier) + => TestInRegularAndScriptAsync( $$""" abstract class TestParent { @@ -2017,12 +1912,10 @@ public class Test : TestParent public override int this[{{modifier}} int p] { set => throw new System.NotImplementedException(); } } """); - } [Fact] - public async Task TestRefReadOnlyWithIndexer_ReturnType() - { - await TestInRegularAndScriptAsync( + public Task TestRefReadOnlyWithIndexer_ReturnType() + => TestInRegularAndScriptAsync( """ abstract class TestParent { @@ -2042,12 +1935,10 @@ public class Test : TestParent public override ref readonly int this[int p] => throw new System.NotImplementedException(); } """); - } [Fact] - public async Task TestUnmanagedConstraint() - { - await TestInRegularAndScriptAsync( + public Task TestUnmanagedConstraint() + => TestInRegularAndScriptAsync( """ public abstract class ParentTest { @@ -2070,12 +1961,10 @@ public override void M() } } """); - } [Fact] - public async Task NothingOfferedWhenInheritanceIsPreventedByInternalAbstractMember() - { - await TestMissingAsync( + public Task NothingOfferedWhenInheritanceIsPreventedByInternalAbstractMember() + => TestMissingAsync( """ @@ -2096,12 +1985,10 @@ class [|Derived|] : Base """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30102")] - public async Task TestWithIncompleteGenericInBaseList() - { - await TestAllOptionsOffAsync( + public Task TestWithIncompleteGenericInBaseList() + => TestAllOptionsOffAsync( """ abstract class A { @@ -2127,12 +2014,10 @@ public override void AbstractMethod() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44907")] - public async Task TestWithRecords() - { - await TestAllOptionsOffAsync( + public Task TestWithRecords() + => TestAllOptionsOffAsync( """ abstract record A { @@ -2158,12 +2043,10 @@ public override void AbstractMethod() } } """, parseOptions: TestOptions.RegularPreview); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44907")] - public async Task TestWithRecordsWithPositionalMembers() - { - await TestAllOptionsOffAsync( + public Task TestWithRecordsWithPositionalMembers() + => TestAllOptionsOffAsync( """ abstract record A { @@ -2189,12 +2072,10 @@ public override void AbstractMethod() } } """, parseOptions: TestOptions.RegularPreview); - } [Fact] - public async Task TestWithClassWithParameters() - { - await TestAllOptionsOffAsync( + public Task TestWithClassWithParameters() + => TestAllOptionsOffAsync( """ abstract class A { @@ -2220,12 +2101,10 @@ public override void AbstractMethod() } } """, parseOptions: TestOptions.RegularPreview); - } [Fact] - public async Task TestWithClassWithSemicolonBody() - { - await TestAllOptionsOffAsync( + public Task TestWithClassWithSemicolonBody() + => TestAllOptionsOffAsync( """ abstract class A { @@ -2249,12 +2128,10 @@ public override void AbstractMethod() } """, parseOptions: TestOptions.RegularPreview); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48742")] - public async Task TestUnconstrainedGenericNullable() - { - await TestAllOptionsOffAsync( + public Task TestUnconstrainedGenericNullable() + => TestAllOptionsOffAsync( """ #nullable enable @@ -2283,12 +2160,10 @@ public override int M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48742")] - public async Task TestUnconstrainedGenericNullable2() - { - await TestAllOptionsOffAsync( + public Task TestUnconstrainedGenericNullable2() + => TestAllOptionsOffAsync( """ #nullable enable @@ -2317,12 +2192,10 @@ public override T M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48742")] - public async Task TestUnconstrainedGenericNullable_Tuple() - { - await TestAllOptionsOffAsync( + public Task TestUnconstrainedGenericNullable_Tuple() + => TestAllOptionsOffAsync( """ #nullable enable @@ -2351,7 +2224,6 @@ public override (T, T) M() } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/48742")] [InlineData("", "T")] @@ -2359,39 +2231,40 @@ public override (T, T) M() [InlineData("", "T?")] [InlineData(" where T : class", "T?")] [InlineData(" where T : struct", "T?")] - public async Task TestUnconstrainedGenericNullable_NoRegression(string constraint, string passToBase) - { - await TestAllOptionsOffAsync( -$@"#nullable enable - -abstract class B -{{ - public abstract T? M(); -}} - -class [|D|] : B<{passToBase}>{constraint} -{{ -}}", -$@"#nullable enable - -abstract class B -{{ - public abstract T? M(); -}} - -class D : B<{passToBase}>{constraint} -{{ - public override T? M() - {{ - throw new System.NotImplementedException(); - }} -}}"); - } + public Task TestUnconstrainedGenericNullable_NoRegression(string constraint, string passToBase) + => TestAllOptionsOffAsync( + $$""" + #nullable enable + + abstract class B + { + public abstract T? M(); + } + + class [|D|] : B<{{passToBase}}>{{constraint}} + { + } + """, + $$""" + #nullable enable + + abstract class B + { + public abstract T? M(); + } + + class D : B<{{passToBase}}>{{constraint}} + { + public override T? M() + { + throw new System.NotImplementedException(); + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53012")] - public async Task TestNullableGenericType() - { - await TestAllOptionsOffAsync( + public Task TestNullableGenericType() + => TestAllOptionsOffAsync( """ abstract class C { @@ -2416,12 +2289,10 @@ public override void M(T1? a, T2 b, T1? c, T3? d) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/62092")] - public async Task TestNullableGenericType2() - { - await TestAllOptionsOffAsync( + public Task TestNullableGenericType2() + => TestAllOptionsOffAsync( """ interface I { } @@ -2457,12 +2328,10 @@ class C2 : C } } """); - } [Fact] - public async Task TestRequiredMember() - { - await TestAllOptionsOffAsync( + public Task TestRequiredMember() + => TestAllOptionsOffAsync( """ abstract class C { @@ -2493,12 +2362,10 @@ public override required int Property } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70530")] - public async Task TestRecordInheritance1() - { - await TestAllOptionsOffAsync( + public Task TestRecordInheritance1() + => TestAllOptionsOffAsync( """ abstract record A() { @@ -2523,12 +2390,10 @@ protected override void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70530")] - public async Task TestRecordInheritance2() - { - await TestAllOptionsOffAsync( + public Task TestRecordInheritance2() + => TestAllOptionsOffAsync( """ abstract record A() { @@ -2553,12 +2418,10 @@ protected override void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75992")] - public async Task InsertMissingBraces() - { - await TestAllOptionsOffAsync( + public Task InsertMissingBraces() + => TestAllOptionsOffAsync( """ abstract class A { @@ -2585,12 +2448,10 @@ public override void M() file class C; """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71225")] - public async Task TestConstrainedTypeParameter1() - { - await TestAllOptionsOffAsync( + public Task TestConstrainedTypeParameter1() + => TestAllOptionsOffAsync( """ #nullable enable using System; @@ -2629,12 +2490,10 @@ protected override void M(I i) where T : class } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71225")] - public async Task TestConstrainedTypeParameter2() - { - await TestAllOptionsOffAsync( + public Task TestConstrainedTypeParameter2() + => TestAllOptionsOffAsync( """ #nullable enable using System; @@ -2673,12 +2532,10 @@ protected override void M(I i) where T : struct } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71225")] - public async Task TestConstrainedTypeParameter3() - { - await TestAllOptionsOffAsync( + public Task TestConstrainedTypeParameter3() + => TestAllOptionsOffAsync( """ #nullable enable using System; @@ -2717,12 +2574,10 @@ protected override void M(I i) where T : class } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71225")] - public async Task TestConstrainedTypeParameter4() - { - await TestAllOptionsOffAsync( + public Task TestConstrainedTypeParameter4() + => TestAllOptionsOffAsync( """ #nullable enable using System; @@ -2761,12 +2616,10 @@ protected override void M(I i) where T : class } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78282")] - public async Task TestInstanceCompoundOperator() - { - await TestAllOptionsOffAsync( + public Task TestInstanceCompoundOperator() + => TestAllOptionsOffAsync( """ abstract class C1 { @@ -2800,5 +2653,4 @@ class C2 : C1 } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/ImplementAbstractClass/ImplementAbstractClassTests_FixAllTests.cs b/src/Analyzers/CSharp/Tests/ImplementAbstractClass/ImplementAbstractClassTests_FixAllTests.cs index 0367a588157cb..90860d6628d9d 100644 --- a/src/Analyzers/CSharp/Tests/ImplementAbstractClass/ImplementAbstractClassTests_FixAllTests.cs +++ b/src/Analyzers/CSharp/Tests/ImplementAbstractClass/ImplementAbstractClassTests_FixAllTests.cs @@ -15,454 +15,438 @@ public sealed partial class ImplementAbstractClassTests [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInDocument() - { - var input = @" - - - -public abstract class A1 -{ - public abstract void F1(); -} - -public interface I1 -{ - void F2(); -} - -class {|FixAllInDocument:B1|} : A1 -{ - class C1 : A1, I1 - { - } -} - - -class B2 : A1 -{ - class C2 : A1, I1 - { - } -} - - - - -class B3 : A1 -{ - class C3 : A1, I1 - { - } -} - - -"; - - var expected = @" - - - -public abstract class A1 -{ - public abstract void F1(); -} - -public interface I1 -{ - void F2(); -} - -class B1 : A1 -{ - public override void F1() - { - throw new System.NotImplementedException(); - } - - class C1 : A1, I1 - { - public override void F1() - { - throw new System.NotImplementedException(); - } - } -} - - -class B2 : A1 -{ - class C2 : A1, I1 - { - } -} - - - - -class B3 : A1 -{ - class C3 : A1, I1 - { - } -} - - -"; - - await TestInRegularAndScriptAsync(input, expected); - } + public Task TestFixAllInDocument() + => TestInRegularAndScriptAsync(""" + + + + public abstract class A1 + { + public abstract void F1(); + } + + public interface I1 + { + void F2(); + } + + class {|FixAllInDocument:B1|} : A1 + { + class C1 : A1, I1 + { + } + } + + + class B2 : A1 + { + class C2 : A1, I1 + { + } + } + + + + + class B3 : A1 + { + class C3 : A1, I1 + { + } + } + + + + """, """ + + + + public abstract class A1 + { + public abstract void F1(); + } + + public interface I1 + { + void F2(); + } + + class B1 : A1 + { + public override void F1() + { + throw new System.NotImplementedException(); + } + + class C1 : A1, I1 + { + public override void F1() + { + throw new System.NotImplementedException(); + } + } + } + + + class B2 : A1 + { + class C2 : A1, I1 + { + } + } + + + + + class B3 : A1 + { + class C3 : A1, I1 + { + } + } + + + + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInProject() - { - var input = @" - - - -public abstract class A1 -{ - public abstract void F1(); -} - -public interface I1 -{ - void F2(); -} - -class {|FixAllInProject:B1|} : A1 -{ - class C1 : A1, I1 - { - } -} - - -class B2 : A1 -{ - class C2 : A1, I1 - { - } -} - - - - -class B3 : A1 -{ - class C3 : A1, I1 - { - } -} - - -"; - - var expected = @" - - - -public abstract class A1 -{ - public abstract void F1(); -} - -public interface I1 -{ - void F2(); -} - -class B1 : A1 -{ - public override void F1() - { - throw new System.NotImplementedException(); - } - - class C1 : A1, I1 - { - public override void F1() - { - throw new System.NotImplementedException(); - } - } -} - - -class B2 : A1 -{ - public override void F1() - { - throw new System.NotImplementedException(); - } - - class C2 : A1, I1 - { - public override void F1() - { - throw new System.NotImplementedException(); - } - } -} - - - - -class B3 : A1 -{ - class C3 : A1, I1 - { - } -} - - -"; - - await TestInRegularAndScriptAsync(input, expected); - } + public Task TestFixAllInProject() + => TestInRegularAndScriptAsync(""" + + + + public abstract class A1 + { + public abstract void F1(); + } + + public interface I1 + { + void F2(); + } + + class {|FixAllInProject:B1|} : A1 + { + class C1 : A1, I1 + { + } + } + + + class B2 : A1 + { + class C2 : A1, I1 + { + } + } + + + + + class B3 : A1 + { + class C3 : A1, I1 + { + } + } + + + + """, """ + + + + public abstract class A1 + { + public abstract void F1(); + } + + public interface I1 + { + void F2(); + } + + class B1 : A1 + { + public override void F1() + { + throw new System.NotImplementedException(); + } + + class C1 : A1, I1 + { + public override void F1() + { + throw new System.NotImplementedException(); + } + } + } + + + class B2 : A1 + { + public override void F1() + { + throw new System.NotImplementedException(); + } + + class C2 : A1, I1 + { + public override void F1() + { + throw new System.NotImplementedException(); + } + } + } + + + + + class B3 : A1 + { + class C3 : A1, I1 + { + } + } + + + + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInSolution() - { - var input = @" - - - -public abstract class A1 -{ - public abstract void F1(); -} - -public interface I1 -{ - void F2(); -} - -class {|FixAllInSolution:B1|} : A1 -{ - class C1 : A1, I1 - { - } -} - - -class B2 : A1 -{ - class C2 : A1, I1 - { - } -} - - - - Assembly1 - -class B3 : A1 -{ - class C3 : A1, I1 - { - } -} - - -"; - - var expected = @" - - - -public abstract class A1 -{ - public abstract void F1(); -} - -public interface I1 -{ - void F2(); -} - -class B1 : A1 -{ - public override void F1() - { - throw new System.NotImplementedException(); - } - - class C1 : A1, I1 - { - public override void F1() - { - throw new System.NotImplementedException(); - } - } -} - - -class B2 : A1 -{ - public override void F1() - { - throw new System.NotImplementedException(); - } - - class C2 : A1, I1 - { - public override void F1() - { - throw new System.NotImplementedException(); - } - } -} - - - - Assembly1 - -class B3 : A1 -{ - public override void F1() - { - throw new System.NotImplementedException(); - } - - class C3 : A1, I1 - { - public override void F1() - { - throw new System.NotImplementedException(); - } - } -} - - -"; - - await TestInRegularAndScriptAsync(input, expected); - } + public Task TestFixAllInSolution() + => TestInRegularAndScriptAsync(""" + + + + public abstract class A1 + { + public abstract void F1(); + } + + public interface I1 + { + void F2(); + } + + class {|FixAllInSolution:B1|} : A1 + { + class C1 : A1, I1 + { + } + } + + + class B2 : A1 + { + class C2 : A1, I1 + { + } + } + + + + Assembly1 + + class B3 : A1 + { + class C3 : A1, I1 + { + } + } + + + + """, """ + + + + public abstract class A1 + { + public abstract void F1(); + } + + public interface I1 + { + void F2(); + } + + class B1 : A1 + { + public override void F1() + { + throw new System.NotImplementedException(); + } + + class C1 : A1, I1 + { + public override void F1() + { + throw new System.NotImplementedException(); + } + } + } + + + class B2 : A1 + { + public override void F1() + { + throw new System.NotImplementedException(); + } + + class C2 : A1, I1 + { + public override void F1() + { + throw new System.NotImplementedException(); + } + } + } + + + + Assembly1 + + class B3 : A1 + { + public override void F1() + { + throw new System.NotImplementedException(); + } + + class C3 : A1, I1 + { + public override void F1() + { + throw new System.NotImplementedException(); + } + } + } + + + + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInSolution_DifferentAssemblyWithSameTypeName() - { - var input = @" - - - -public abstract class A1 -{ - public abstract void F1(); -} - -public interface I1 -{ - void F2(); -} - -class {|FixAllInSolution:B1|} : A1 -{ - class C1 : A1, I1 - { - } -} - - -class B2 : A1 -{ - class C2 : A1, I1 - { - } -} - - - - -public abstract class A1 -{ - public abstract void F2(); -} - -class B3 : A1 -{ - class C3 : A1, I1 - { - } -} - - -"; - - var expected = @" - - - -public abstract class A1 -{ - public abstract void F1(); -} - -public interface I1 -{ - void F2(); -} - -class B1 : A1 -{ - public override void F1() - { - throw new System.NotImplementedException(); - } - - class C1 : A1, I1 - { - public override void F1() - { - throw new System.NotImplementedException(); - } - } -} - - -class B2 : A1 -{ - public override void F1() - { - throw new System.NotImplementedException(); - } - - class C2 : A1, I1 - { - public override void F1() - { - throw new System.NotImplementedException(); - } - } -} - - - - -public abstract class A1 -{ - public abstract void F2(); -} - -class B3 : A1 -{ - class C3 : A1, I1 - { - } -} - - -"; - - await TestInRegularAndScriptAsync(input, expected); - } + public Task TestFixAllInSolution_DifferentAssemblyWithSameTypeName() + => TestInRegularAndScriptAsync(""" + + + + public abstract class A1 + { + public abstract void F1(); + } + + public interface I1 + { + void F2(); + } + + class {|FixAllInSolution:B1|} : A1 + { + class C1 : A1, I1 + { + } + } + + + class B2 : A1 + { + class C2 : A1, I1 + { + } + } + + + + + public abstract class A1 + { + public abstract void F2(); + } + + class B3 : A1 + { + class C3 : A1, I1 + { + } + } + + + + """, """ + + + + public abstract class A1 + { + public abstract void F1(); + } + + public interface I1 + { + void F2(); + } + + class B1 : A1 + { + public override void F1() + { + throw new System.NotImplementedException(); + } + + class C1 : A1, I1 + { + public override void F1() + { + throw new System.NotImplementedException(); + } + } + } + + + class B2 : A1 + { + public override void F1() + { + throw new System.NotImplementedException(); + } + + class C2 : A1, I1 + { + public override void F1() + { + throw new System.NotImplementedException(); + } + } + } + + + + + public abstract class A1 + { + public abstract void F2(); + } + + class B3 : A1 + { + class C3 : A1, I1 + { + } + } + + + + """); #endregion } diff --git a/src/Analyzers/CSharp/Tests/ImplementAbstractClass/ImplementAbstractClassTests_ThroughMember.cs b/src/Analyzers/CSharp/Tests/ImplementAbstractClass/ImplementAbstractClassTests_ThroughMember.cs index 05596b1d7c022..1e5ba0f4fbfeb 100644 --- a/src/Analyzers/CSharp/Tests/ImplementAbstractClass/ImplementAbstractClassTests_ThroughMember.cs +++ b/src/Analyzers/CSharp/Tests/ImplementAbstractClass/ImplementAbstractClassTests_ThroughMember.cs @@ -52,9 +52,8 @@ internal Task TestAllOptionsOffAsync( } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41420")] - public async Task FieldInBaseClassIsNotSuggested() - { - await TestExactActionSetOfferedAsync( + public Task FieldInBaseClassIsNotSuggested() + => TestExactActionSetOfferedAsync( """ abstract class Base { @@ -67,12 +66,10 @@ class [|Derived|] : Base { } """, [AnalyzersResources.Implement_abstract_class]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41420")] - public async Task FieldInMiddleClassIsNotSuggested() - { - await TestExactActionSetOfferedAsync( + public Task FieldInMiddleClassIsNotSuggested() + => TestExactActionSetOfferedAsync( """ abstract class Base { @@ -88,12 +85,10 @@ class [|Derived|] : Base { } """, [AnalyzersResources.Implement_abstract_class]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41420")] - public async Task FieldOfSameDerivedTypeIsSuggested() - { - await TestInRegularAndScriptAsync( + public Task FieldOfSameDerivedTypeIsSuggested() + => TestInRegularAndScriptAsync( """ abstract class Base { @@ -121,12 +116,10 @@ public override void Method() } } """, index: 1, title: string.Format(AnalyzersResources.Implement_through_0, "inner")); - } [Fact] - public async Task RefParameters_Method() - { - await TestInRegularAndScriptAsync( + public Task RefParameters_Method() + => TestInRegularAndScriptAsync( """ abstract class Base { @@ -154,12 +147,10 @@ public override void Method(int a, ref int b, in int c, ref readonly int d, out } } """, index: 1, title: string.Format(AnalyzersResources.Implement_through_0, "inner")); - } [Fact] - public async Task RefParameters_Indexer() - { - await TestInRegularAndScriptAsync( + public Task RefParameters_Indexer() + => TestInRegularAndScriptAsync( """ abstract class Base { @@ -184,12 +175,10 @@ class Derived : Base public override int this[int a, in int b, ref readonly int c, out int d] => inner[a, b, in c, out d]; } """, index: 1, title: string.Format(AnalyzersResources.Implement_through_0, "inner")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41420")] - public async Task SkipInaccessibleMember() - { - await TestInRegularAndScriptAsync( + public Task SkipInaccessibleMember() + => TestInRegularAndScriptAsync( """ abstract class Base { @@ -219,12 +208,10 @@ public override void Method1() } } """, index: 1, title: string.Format(AnalyzersResources.Implement_through_0, "inner")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41420")] - public async Task TestNotOfferedWhenOnlyUnimplementedMemberIsInaccessible() - { - await TestExactActionSetOfferedAsync( + public Task TestNotOfferedWhenOnlyUnimplementedMemberIsInaccessible() + => TestExactActionSetOfferedAsync( """ abstract class Base { @@ -242,12 +229,10 @@ public override void Method1() } } """, [AnalyzersResources.Implement_abstract_class]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41420")] - public async Task FieldOfMoreSpecificTypeIsSuggested() - { - await TestInRegularAndScriptAsync( + public Task FieldOfMoreSpecificTypeIsSuggested() + => TestInRegularAndScriptAsync( """ abstract class Base { @@ -283,12 +268,10 @@ class DerivedAgain : Derived { } """, index: 1, title: string.Format(AnalyzersResources.Implement_through_0, "inner")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41420")] - public async Task FieldOfConstrainedGenericTypeIsSuggested() - { - await TestInRegularAndScriptAsync( + public Task FieldOfConstrainedGenericTypeIsSuggested() + => TestInRegularAndScriptAsync( """ abstract class Base { @@ -316,12 +299,10 @@ public override void Method() } } """, index: 1, title: string.Format(AnalyzersResources.Implement_through_0, "inner")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41420")] - public async Task DistinguishableOptionsAreShownForExplicitPropertyWithSameName() - { - await TestExactActionSetOfferedAsync( + public Task DistinguishableOptionsAreShownForExplicitPropertyWithSameName() + => TestExactActionSetOfferedAsync( """ abstract class Base { @@ -345,12 +326,10 @@ class [|Derived|] : Base, IInterface string.Format(AnalyzersResources.Implement_through_0, "Inner"), string.Format(AnalyzersResources.Implement_through_0, "IInterface.Inner"), ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41420")] - public async Task NotOfferedForDynamicFields() - { - await TestExactActionSetOfferedAsync( + public Task NotOfferedForDynamicFields() + => TestExactActionSetOfferedAsync( """ abstract class Base { @@ -362,12 +341,10 @@ class [|Derived|] : Base dynamic inner; } """, [AnalyzersResources.Implement_abstract_class]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41420")] - public async Task OfferedForStaticFields() - { - await TestInRegularAndScriptAsync( + public Task OfferedForStaticFields() + => TestInRegularAndScriptAsync( """ abstract class Base { @@ -395,12 +372,10 @@ public override void Method() } } """, index: 1, title: string.Format(AnalyzersResources.Implement_through_0, "inner")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41420")] - public async Task PropertyIsDelegated() - { - await TestInRegularAndScriptAsync( + public Task PropertyIsDelegated() + => TestInRegularAndScriptAsync( """ abstract class Base { @@ -425,12 +400,10 @@ class Derived : Base public override int Property { get => inner.Property; set => inner.Property = value; } } """, index: 1, title: string.Format(AnalyzersResources.Implement_through_0, "inner")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41420")] - public async Task PropertyIsDelegated_AllOptionsOff() - { - await TestAllOptionsOffAsync( + public Task PropertyIsDelegated_AllOptionsOff() + => TestAllOptionsOffAsync( """ abstract class Base { @@ -466,12 +439,10 @@ public override int Property } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41420")] - public async Task PropertyWithSingleAccessorIsDelegated() - { - await TestInRegularAndScriptAsync( + public Task PropertyWithSingleAccessorIsDelegated() + => TestInRegularAndScriptAsync( """ abstract class Base { @@ -500,12 +471,10 @@ class Derived : Base public override int SetOnly { set => inner.SetOnly = value; } } """, index: 1, title: string.Format(AnalyzersResources.Implement_through_0, "inner")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41420")] - public async Task PropertyWithSingleAccessorIsDelegated_AllOptionsOff() - { - await TestAllOptionsOffAsync( + public Task PropertyWithSingleAccessorIsDelegated_AllOptionsOff() + => TestAllOptionsOffAsync( """ abstract class Base { @@ -546,12 +515,10 @@ public override int SetOnly } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41420")] - public async Task EventIsDelegated() - { - await TestInRegularAndScriptAsync( + public Task EventIsDelegated() + => TestInRegularAndScriptAsync( """ using System; @@ -591,12 +558,10 @@ public override event Action Event } } """, index: 1, title: string.Format(AnalyzersResources.Implement_through_0, "inner")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41420")] - public async Task OnlyOverridableMethodsAreOverridden() - { - await TestInRegularAndScriptAsync( + public Task OnlyOverridableMethodsAreOverridden() + => TestInRegularAndScriptAsync( """ abstract class Base { @@ -628,12 +593,10 @@ public override void Method() } } """, index: 1, title: string.Format(AnalyzersResources.Implement_through_0, "inner")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41420")] - public async Task ProtectedMethodsCannotBeDelegatedThroughBaseType() - { - await TestExactActionSetOfferedAsync( + public Task ProtectedMethodsCannotBeDelegatedThroughBaseType() + => TestExactActionSetOfferedAsync( """ abstract class Base { @@ -645,12 +608,10 @@ class [|Derived|] : Base Base inner; } """, [AnalyzersResources.Implement_abstract_class]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41420")] - public async Task ProtectedMethodsCanBeDelegatedThroughSameType() - { - await TestInRegularAndScriptAsync( + public Task ProtectedMethodsCanBeDelegatedThroughSameType() + => TestInRegularAndScriptAsync( """ abstract class Base { @@ -678,12 +639,10 @@ protected override void Method() } } """, index: 1, title: string.Format(AnalyzersResources.Implement_through_0, "inner")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41420")] - public async Task ProtectedInternalMethodsAreOverridden() - { - await TestInRegularAndScriptAsync( + public Task ProtectedInternalMethodsAreOverridden() + => TestInRegularAndScriptAsync( """ abstract class Base { @@ -711,12 +670,10 @@ protected internal override void Method() } } """, index: 1, title: string.Format(AnalyzersResources.Implement_through_0, "inner")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41420")] - public async Task InternalMethodsAreOverridden() - { - await TestInRegularAndScriptAsync( + public Task InternalMethodsAreOverridden() + => TestInRegularAndScriptAsync( """ abstract class Base { @@ -744,12 +701,10 @@ internal override void Method() } } """, index: 1, title: string.Format(AnalyzersResources.Implement_through_0, "inner")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41420")] - public async Task PrivateProtectedMethodsCannotBeDelegatedThroughBaseType() - { - await TestExactActionSetOfferedAsync( + public Task PrivateProtectedMethodsCannotBeDelegatedThroughBaseType() + => TestExactActionSetOfferedAsync( """ abstract class Base { @@ -761,12 +716,10 @@ class [|Derived|] : Base Base inner; } """, [AnalyzersResources.Implement_abstract_class]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41420")] - public async Task PrivateProtectedMethodsCanBeDelegatedThroughSameType() - { - await TestInRegularAndScriptAsync( + public Task PrivateProtectedMethodsCanBeDelegatedThroughSameType() + => TestInRegularAndScriptAsync( """ abstract class Base { @@ -794,12 +747,10 @@ private protected override void Method() } } """, index: 1, title: string.Format(AnalyzersResources.Implement_through_0, "inner")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41420")] - public async Task AccessorsWithDifferingVisibilityAreGeneratedCorrectly() - { - await TestInRegularAndScriptAsync( + public Task AccessorsWithDifferingVisibilityAreGeneratedCorrectly() + => TestInRegularAndScriptAsync( """ abstract class Base { @@ -827,12 +778,10 @@ class Derived : Base public override int InternalSet { get => inner.InternalSet; internal set => inner.InternalSet = value; } } """, index: 1, title: string.Format(AnalyzersResources.Implement_through_0, "inner")); - } [Fact] - public async Task TestCrossProjectWithInaccessibleMemberInCase() - { - await TestInRegularAndScriptAsync( + public Task TestCrossProjectWithInaccessibleMemberInCase() + => TestInRegularAndScriptAsync( """ @@ -882,12 +831,10 @@ public override void Method1() """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69177")] - public async Task TestImplementThroughPrimaryConstructorParam1() - { - await TestInRegularAndScriptAsync( + public Task TestImplementThroughPrimaryConstructorParam1() + => TestInRegularAndScriptAsync( """ abstract class Base { @@ -912,13 +859,10 @@ public override int Method() } } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69177")] - public async Task TestImplementThroughPrimaryConstructorParam2() - { - // Don't offer "implement through 'base1'" since this PC parameter is captured as a field. - await TestExactActionSetOfferedAsync( + public Task TestImplementThroughPrimaryConstructorParam2() + => TestExactActionSetOfferedAsync( """ abstract class Base { @@ -930,13 +874,10 @@ class [|Program|](Base base1) : Base private Base _base = base1; } """, [AnalyzersResources.Implement_abstract_class, string.Format(AnalyzersResources.Implement_through_0, "_base")]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69177")] - public async Task TestImplementThroughPrimaryConstructorParam2_B() - { - // Don't offer "implement through 'base1'" since this PC parameter is captured as a field. - await TestExactActionSetOfferedAsync( + public Task TestImplementThroughPrimaryConstructorParam2_B() + => TestExactActionSetOfferedAsync( """ abstract class Base { @@ -948,13 +889,10 @@ class [|Program|](Base base1) : Base private Base _base = (base1); } """, [AnalyzersResources.Implement_abstract_class, string.Format(AnalyzersResources.Implement_through_0, "_base")]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69177")] - public async Task TestImplementThroughPrimaryConstructorParam3() - { - // Don't offer "implement through 'base1'" since this PC parameter is captured as a field. - await TestExactActionSetOfferedAsync( + public Task TestImplementThroughPrimaryConstructorParam3() + => TestExactActionSetOfferedAsync( """ abstract class Base { @@ -966,13 +904,10 @@ class [|Program|](Base base1) : Base private Base B { get; } = base1; } """, [AnalyzersResources.Implement_abstract_class, string.Format(AnalyzersResources.Implement_through_0, "B")]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69177")] - public async Task TestImplementThroughPrimaryConstructorParam3_B() - { - // Don't offer "implement through 'base1'" since this PC parameter is captured as a field. - await TestExactActionSetOfferedAsync( + public Task TestImplementThroughPrimaryConstructorParam3_B() + => TestExactActionSetOfferedAsync( """ abstract class Base { @@ -984,12 +919,10 @@ class [|Program|](Base base1) : Base private Base B { get; } = (base1); } """, [AnalyzersResources.Implement_abstract_class, string.Format(AnalyzersResources.Implement_through_0, "B")]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69177")] - public async Task TestImplementThroughPrimaryConstructorParam4() - { - await TestInRegularAndScriptAsync( + public Task TestImplementThroughPrimaryConstructorParam4() + => TestInRegularAndScriptAsync( """ abstract class Base { @@ -1017,5 +950,4 @@ public override int Method() } } """, index: 1); - } } diff --git a/src/Analyzers/CSharp/Tests/ImplementInterface/ImplementInterfaceTests.cs b/src/Analyzers/CSharp/Tests/ImplementInterface/ImplementInterfaceTests.cs index fe3c747e5daa7..ec10365e15a3c 100644 --- a/src/Analyzers/CSharp/Tests/ImplementInterface/ImplementInterfaceTests.cs +++ b/src/Analyzers/CSharp/Tests/ImplementInterface/ImplementInterfaceTests.cs @@ -73,12 +73,11 @@ private static OptionsCollection AccessorOptionsOn { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, }; - internal static async Task TestWithAllCodeStyleOptionsOffAsync( + internal static Task TestWithAllCodeStyleOptionsOffAsync( [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string initialMarkup, [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string expectedMarkup, (string equivalenceKey, int index)? codeAction = null) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = initialMarkup, FixedCode = expectedMarkup, @@ -86,50 +85,42 @@ internal static async Task TestWithAllCodeStyleOptionsOffAsync( CodeActionIndex = codeAction?.index, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } - internal static async Task TestWithAllCodeStyleOptionsOnAsync( + internal static Task TestWithAllCodeStyleOptionsOnAsync( [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string initialMarkup, [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string expectedMarkup) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = initialMarkup, FixedCode = expectedMarkup, Options = { AllOptionsOn }, }.RunAsync(); - } - internal static async Task TestWithAccessorCodeStyleOptionsOnAsync( + internal static Task TestWithAccessorCodeStyleOptionsOnAsync( [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string initialMarkup, [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string expectedMarkup) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = initialMarkup, FixedCode = expectedMarkup, Options = { AccessorOptionsOn }, }.RunAsync(); - } - private static async Task TestInRegularAndScriptAsync( + private static Task TestInRegularAndScriptAsync( [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string initialMarkup, [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string expectedMarkup, (string equivalenceKey, int index)? codeAction = null) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = initialMarkup, FixedCode = expectedMarkup, CodeActionIndex = codeAction?.index, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMethod() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestMethod() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IInterface { @@ -154,12 +145,10 @@ public void Method1() } } """); - } [Fact] - public async Task TestMethodInRecord() - { - await new VerifyCS.Test + public Task TestMethodInRecord() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp12, TestCode = """ @@ -187,7 +176,6 @@ public void Method1() } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42986")] public async Task TestMethodWithNativeIntegers() @@ -245,9 +233,8 @@ class Class : IInterface } [Fact] - public async Task TestMethodWithTuple() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestMethodWithTuple() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IInterface { @@ -272,12 +259,10 @@ class Class : IInterface } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16793")] - public async Task TestMethodWithValueTupleArity1() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestMethodWithValueTupleArity1() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; interface I @@ -302,12 +287,10 @@ public ValueTuple F() } } """); - } [Fact] - public async Task TestExpressionBodiedMethod1() - { - await TestWithAllCodeStyleOptionsOnAsync( + public Task TestExpressionBodiedMethod1() + => TestWithAllCodeStyleOptionsOnAsync( """ interface IInterface { @@ -329,13 +312,10 @@ class Class : IInterface public void Method1() => throw new System.NotImplementedException(); } """); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] - public async Task TupleWithNamesInMethod() - { - // Note: we're putting the attribute by hand to simulate metadata - await TestWithAllCodeStyleOptionsOffAsync( + public Task TupleWithNamesInMethod() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IInterface { @@ -362,12 +342,10 @@ class Class : IInterface } } """); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] - public async Task TupleWithNamesInMethod_Explicitly() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TupleWithNamesInMethod_Explicitly() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IInterface { @@ -395,12 +373,10 @@ class Class : IInterface } """, codeAction: ("True;False;False:global::IInterface;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] - public async Task TupleWithNamesInProperty() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TupleWithNamesInProperty() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IInterface { @@ -435,12 +411,10 @@ class Class : IInterface } } """); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] - public async Task TupleWithNamesInEvent() - { - await new VerifyCS.Test + public Task TupleWithNamesInEvent() + => new VerifyCS.Test { TestCode = """ interface IInterface @@ -469,12 +443,10 @@ class Class : IInterface """, Options = { AllOptionsOff }, }.RunAsync(); - } [Fact] - public async Task NoDynamicAttributeInMethod() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task NoDynamicAttributeInMethod() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IInterface { @@ -501,7 +473,6 @@ public object Method1() } } """); - } [Fact] public async Task NoNullableAttributesInMethodFromMetadata() @@ -584,9 +555,8 @@ public void M(string? s1, string s2) } [Fact] - public async Task TestMethodWhenClassBracesAreMissing() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestMethodWhenClassBracesAreMissing() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IInterface { @@ -610,13 +580,11 @@ public void Method1() } """); - } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/26323")] - public async Task TestMethodWhenClassBracesAreMissing2( + public Task TestMethodWhenClassBracesAreMissing2( [CombinatorialValues(0, 1)] int behavior) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = """ using System; @@ -658,12 +626,10 @@ static void Main(string[] args) { } } } }.RunAsync(); - } [Fact] - public async Task TestInheritance1() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestInheritance1() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IInterface1 { @@ -696,12 +662,10 @@ public void Method1() } } """); - } [Fact] - public async Task TestInheritance2() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestInheritance2() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IInterface1 { @@ -734,12 +698,10 @@ public void Method1() } } """); - } [Fact] - public async Task TestInheritance3() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestInheritance3() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IInterface1 { @@ -779,12 +741,10 @@ public void Method2() } } """); - } [Fact] - public async Task TestInheritanceMatchingMethod() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestInheritanceMatchingMethod() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IInterface1 { @@ -819,12 +779,10 @@ public void Method1() } } """); - } [Fact] - public async Task TestExistingConflictingMethodReturnType() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestExistingConflictingMethodReturnType() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IInterface1 { @@ -858,12 +816,10 @@ void IInterface1.Method1() } } """); - } [Fact] - public async Task TestExistingConflictingMethodParameters() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestExistingConflictingMethodParameters() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IInterface1 { @@ -895,12 +851,10 @@ public void Method1(int i) } } """); - } [Fact] - public async Task TestImplementGenericType() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementGenericType() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IInterface1 { @@ -925,12 +879,10 @@ public void Method1(int t) } } """); - } [Fact] - public async Task TestImplementGenericTypeWithGenericMethod() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementGenericTypeWithGenericMethod() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IInterface1 { @@ -955,12 +907,10 @@ public void Method1(int t, U u) } } """); - } [Fact] - public async Task TestImplementGenericTypeWithGenericMethodWithNaturalConstraint() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementGenericTypeWithGenericMethodWithNaturalConstraint() + => TestWithAllCodeStyleOptionsOffAsync( """ using System.Collections.Generic; interface IInterface1 @@ -987,12 +937,10 @@ public void Method1(int t, U u) where U : IList } } """); - } [Fact] - public async Task TestImplementGenericTypeWithGenericMethodWithUnexpressibleConstraint() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementGenericTypeWithGenericMethodWithUnexpressibleConstraint() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IInterface1 { @@ -1017,12 +965,10 @@ void IInterface1.Method1(int t, U u) } } """); - } [Fact] - public async Task TestArrayType() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestArrayType() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -1047,12 +993,10 @@ public string[] M() } } """); - } [Fact] - public async Task TestImplementThroughFieldMember() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementThroughFieldMember() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -1080,13 +1024,11 @@ public void Method1() } } """, -codeAction: ("False;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i", 1)); - } + codeAction: ("False;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i", 1)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69177")] - public async Task TestImplementThroughPrimaryConstructorParameter1() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementThroughPrimaryConstructorParameter1() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -1111,13 +1053,11 @@ public void Method1() } } """, -codeAction: ("False;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i", 1)); - } + codeAction: ("False;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i", 1)); [Fact] - public async Task TestImplementThroughFieldMember_FixAll_SameMemberInDifferentType() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementThroughFieldMember_FixAll_SameMemberInDifferentType() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -1160,13 +1100,11 @@ public void Method1() } } """, -codeAction: ("False;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i", 1)); - } + codeAction: ("False;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i", 1)); [Fact] - public async Task TestImplementThroughFieldMember_FixAll_FieldInOnePropInAnother() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementThroughFieldMember_FixAll_FieldInOnePropInAnother() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -1209,8 +1147,7 @@ public void Method1() } } """, -codeAction: ("False;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i", 1)); - } + codeAction: ("False;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i", 1)); [Fact] public async Task TestImplementThroughFieldMember_FixAll_FieldInOneNonViableInAnother() @@ -1270,9 +1207,8 @@ class D : {|CS0535:I|} } [Fact] - public async Task TestImplementThroughFieldMemberInterfaceWithIndexer() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementThroughFieldMemberInterfaceWithIndexer() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IGoo { @@ -1308,13 +1244,11 @@ public int this[int x] } } """, -codeAction: ("False;False;False:global::IGoo;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;f", 1)); - } + codeAction: ("False;False;False:global::IGoo;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;f", 1)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/472")] - public async Task TestImplementThroughFieldMemberRemoveUnnecessaryCast() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementThroughFieldMemberRemoveUnnecessaryCast() + => TestWithAllCodeStyleOptionsOffAsync( """ using System.Collections; @@ -1336,13 +1270,11 @@ public int Compare(object x, object y) } } """, -codeAction: ("False;False;False:global::System.Collections.IComparer;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;x", 1)); - } + codeAction: ("False;False;False:global::System.Collections.IComparer;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;x", 1)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/472")] - public async Task TestImplementThroughFieldMemberRemoveUnnecessaryCastAndThis() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementThroughFieldMemberRemoveUnnecessaryCastAndThis() + => TestWithAllCodeStyleOptionsOffAsync( """ using System.Collections; @@ -1364,13 +1296,11 @@ public int Compare(object x, object y) } } """, -codeAction: ("False;False;False:global::System.Collections.IComparer;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a", 1)); - } + codeAction: ("False;False;False:global::System.Collections.IComparer;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a", 1)); [Fact] - public async Task TestImplementAbstract() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementAbstract() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -1392,13 +1322,11 @@ abstract class C : I public abstract void Method1(); } """, -codeAction: ("False;True;True:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); - } + codeAction: ("False;True;True:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); [Fact] - public async Task TestImplementInterfaceWithRefOutParameters() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementInterfaceWithRefOutParameters() + => TestWithAllCodeStyleOptionsOffAsync( """ class C : {|CS0535:{|CS0535:I|}|} { @@ -1433,13 +1361,11 @@ interface I int Method2(); } """, -codeAction: ("False;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;goo", 1)); - } + codeAction: ("False;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;goo", 1)); [Fact] - public async Task TestConflictingMethods1() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestConflictingMethods1() + => TestWithAllCodeStyleOptionsOffAsync( """ class B { @@ -1480,12 +1406,10 @@ interface I void Method1(); } """); - } [Fact] - public async Task TestConflictingProperties() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestConflictingProperties() + => TestWithAllCodeStyleOptionsOffAsync( """ class Test : {|CS0737:I1|} { @@ -1521,12 +1445,10 @@ interface I1 int Prop { get; set; } } """); - } [Fact] - public async Task TestConflictingProperties2() - { - await TestWithAllCodeStyleOptionsOnAsync( + public Task TestConflictingProperties2() + => TestWithAllCodeStyleOptionsOnAsync( """ class Test : {|CS0737:I1|} { @@ -1550,7 +1472,6 @@ interface I1 int Prop { get; set; } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539043")] public async Task TestExplicitProperties() @@ -1580,9 +1501,8 @@ decimal I2.Calc } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] - public async Task TestEscapedMethodName() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestEscapedMethodName() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IInterface { @@ -1607,12 +1527,10 @@ public void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] - public async Task TestEscapedMethodKeyword() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestEscapedMethodKeyword() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IInterface { @@ -1637,12 +1555,10 @@ public void @int() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] - public async Task TestEscapedInterfaceName1() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestEscapedInterfaceName1() + => TestWithAllCodeStyleOptionsOffAsync( """ interface @IInterface { @@ -1670,12 +1586,10 @@ void IInterface.M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] - public async Task TestEscapedInterfaceName2() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestEscapedInterfaceName2() + => TestWithAllCodeStyleOptionsOffAsync( """ interface @IInterface { @@ -1703,12 +1617,10 @@ void IInterface.M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] - public async Task TestEscapedInterfaceKeyword1() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestEscapedInterfaceKeyword1() + => TestWithAllCodeStyleOptionsOffAsync( """ interface @int { @@ -1736,12 +1648,10 @@ void @int.M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] - public async Task TestEscapedInterfaceKeyword2() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestEscapedInterfaceKeyword2() + => TestWithAllCodeStyleOptionsOffAsync( """ interface @int { @@ -1769,12 +1679,10 @@ void @int.@bool() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")] - public async Task TestPropertyFormatting() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestPropertyFormatting() + => TestWithAllCodeStyleOptionsOffAsync( """ public interface DD { @@ -1805,12 +1713,10 @@ public int Prop } } """); - } [Fact] - public async Task TestProperty_PropertyCodeStyleOn1() - { - await TestWithAllCodeStyleOptionsOnAsync( + public Task TestProperty_PropertyCodeStyleOn1() + => TestWithAllCodeStyleOptionsOnAsync( """ public interface DD { @@ -1832,12 +1738,10 @@ public class A : DD public int Prop => throw new System.NotImplementedException(); } """); - } [Fact] - public async Task TestProperty_AccessorCodeStyleOn1() - { - await TestWithAccessorCodeStyleOptionsOnAsync( + public Task TestProperty_AccessorCodeStyleOn1() + => TestWithAccessorCodeStyleOptionsOnAsync( """ public interface DD { @@ -1859,12 +1763,10 @@ public class A : DD public int Prop { get => throw new System.NotImplementedException(); } } """); - } [Fact] - public async Task TestIndexer_IndexerCodeStyleOn1() - { - await TestWithAllCodeStyleOptionsOnAsync( + public Task TestIndexer_IndexerCodeStyleOn1() + => TestWithAllCodeStyleOptionsOnAsync( """ public interface DD { @@ -1886,12 +1788,10 @@ public class A : DD public int this[int i] => throw new System.NotImplementedException(); } """); - } [Fact] - public async Task TestIndexer_AccessorCodeStyleOn1() - { - await TestWithAccessorCodeStyleOptionsOnAsync( + public Task TestIndexer_AccessorCodeStyleOn1() + => TestWithAccessorCodeStyleOptionsOnAsync( """ public interface DD { @@ -1913,12 +1813,10 @@ public class A : DD public int this[int i] { get => throw new System.NotImplementedException(); } } """); - } [Fact] - public async Task TestMethod_AllCodeStyleOn1() - { - await TestWithAllCodeStyleOptionsOnAsync( + public Task TestMethod_AllCodeStyleOn1() + => TestWithAllCodeStyleOptionsOnAsync( """ public interface DD { @@ -1940,12 +1838,10 @@ public class A : DD public int M() => throw new System.NotImplementedException(); } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")] - public async Task TestReadonlyPropertyExpressionBodyYes1() - { - await TestWithAllCodeStyleOptionsOnAsync( + public Task TestReadonlyPropertyExpressionBodyYes1() + => TestWithAllCodeStyleOptionsOnAsync( """ public interface DD { @@ -1965,12 +1861,10 @@ public class A : DD public int Prop => throw new System.NotImplementedException(); } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")] - public async Task TestReadonlyPropertyAccessorBodyYes1() - { - await TestWithAccessorCodeStyleOptionsOnAsync( + public Task TestReadonlyPropertyAccessorBodyYes1() + => TestWithAccessorCodeStyleOptionsOnAsync( """ public interface DD { @@ -1992,12 +1886,10 @@ public class A : DD public int Prop { get => throw new System.NotImplementedException(); } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")] - public async Task TestReadonlyPropertyAccessorBodyYes2() - { - await TestWithAccessorCodeStyleOptionsOnAsync( + public Task TestReadonlyPropertyAccessorBodyYes2() + => TestWithAccessorCodeStyleOptionsOnAsync( """ public interface DD { @@ -2019,12 +1911,10 @@ public class A : DD public int Prop { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")] - public async Task TestReadonlyPropertyExpressionBodyNo1() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestReadonlyPropertyExpressionBodyNo1() + => TestWithAllCodeStyleOptionsOffAsync( """ public interface DD { @@ -2052,12 +1942,10 @@ public int Prop } } """); - } [Fact] - public async Task TestIndexerExpressionBodyYes1() - { - await TestWithAllCodeStyleOptionsOnAsync( + public Task TestIndexerExpressionBodyYes1() + => TestWithAllCodeStyleOptionsOnAsync( """ public interface DD { @@ -2079,12 +1967,10 @@ public class A : DD public int this[int i] => throw new System.NotImplementedException(); } """); - } [Fact] - public async Task TestIndexerExpressionBodyNo1() - { - await TestWithAllCodeStyleOptionsOnAsync( + public Task TestIndexerExpressionBodyNo1() + => TestWithAllCodeStyleOptionsOnAsync( """ public interface DD { @@ -2106,12 +1992,10 @@ public class A : DD public int this[int i] { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } } """); - } [Fact] - public async Task TestIndexerAccessorExpressionBodyYes1() - { - await TestWithAccessorCodeStyleOptionsOnAsync( + public Task TestIndexerAccessorExpressionBodyYes1() + => TestWithAccessorCodeStyleOptionsOnAsync( """ public interface DD { @@ -2133,12 +2017,10 @@ public class A : DD public int this[int i] { get => throw new System.NotImplementedException(); } } """); - } [Fact] - public async Task TestIndexerAccessorExpressionBodyYes2() - { - await TestWithAllCodeStyleOptionsOnAsync( + public Task TestIndexerAccessorExpressionBodyYes2() + => TestWithAllCodeStyleOptionsOnAsync( """ public interface DD { @@ -2160,12 +2042,10 @@ public class A : DD public int this[int i] { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } } """); - } [Fact] - public async Task TestCommentPlacement() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestCommentPlacement() + => TestWithAllCodeStyleOptionsOffAsync( """ public interface DD { @@ -2190,12 +2070,10 @@ public void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539991")] - public async Task TestBracePlacement() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestBracePlacement() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; class C : {|CS0535:IServiceProvider|}{|CS1513:|}{|CS1514:|} @@ -2211,7 +2089,6 @@ public object GetService(Type serviceType) } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540318")] public async Task TestMissingWithIncompleteMember() @@ -2236,9 +2113,8 @@ class Test : ITest } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541380")] - public async Task TestExplicitProperty() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestExplicitProperty() + => TestWithAllCodeStyleOptionsOffAsync( """ interface i1 { @@ -2271,8 +2147,7 @@ int i1.p } } """, -codeAction: ("True;False;False:global::i1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); - } + codeAction: ("True;False;False:global::i1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541981")] public async Task TestNoDelegateThroughField1() @@ -2363,9 +2238,8 @@ void I.Method1() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")] - public async Task TestImplementIReadOnlyListThroughField() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementIReadOnlyListThroughField() + => TestWithAllCodeStyleOptionsOffAsync( """ using System.Collections.Generic; @@ -2409,13 +2283,11 @@ IEnumerator IEnumerable.GetEnumerator() } } """, -codeAction: ("False;False;False:global::System.Collections.Generic.IReadOnlyList;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;field", 1)); - } + codeAction: ("False;False;False:global::System.Collections.Generic.IReadOnlyList;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;field", 1)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")] - public async Task TestImplementIReadOnlyListThroughProperty() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementIReadOnlyListThroughProperty() + => TestWithAllCodeStyleOptionsOffAsync( """ using System.Collections.Generic; @@ -2459,13 +2331,11 @@ IEnumerator IEnumerable.GetEnumerator() } } """, -codeAction: ("False;False;False:global::System.Collections.Generic.IReadOnlyList;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;field", 1)); - } + codeAction: ("False;False;False:global::System.Collections.Generic.IReadOnlyList;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;field", 1)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")] - public async Task TestImplementInterfaceThroughField() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementInterfaceThroughField() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -2509,8 +2379,7 @@ public int M() } } """, -codeAction: ("False;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a", 1)); - } + codeAction: ("False;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a", 1)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")] public async Task TestImplementInterfaceThroughField_FieldImplementsMultipleInterfaces() @@ -2975,9 +2844,8 @@ public int M2() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18556")] - public async Task TestImplementInterfaceThroughExplicitProperty() - { - await new VerifyCS.Test + public Task TestImplementInterfaceThroughExplicitProperty() + => new VerifyCS.Test { TestCode = """ interface IA @@ -3016,12 +2884,10 @@ public int M() CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length), CodeActionIndex = 1, }.RunAsync(); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")] - public async Task TestNoImplementThroughIndexer() - { - await new VerifyCS.Test + public Task TestNoImplementThroughIndexer() + => new VerifyCS.Test { TestCode = """ interface I @@ -3080,12 +2946,10 @@ public int M() """, CodeActionsVerifier = codeActions => Assert.Equal(2, codeActions.Length), }.RunAsync(); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")] - public async Task TestNoImplementThroughWriteOnlyProperty() - { - await new VerifyCS.Test + public Task TestNoImplementThroughWriteOnlyProperty() + => new VerifyCS.Test { TestCode = """ interface I @@ -3142,12 +3006,10 @@ public int M() """, CodeActionsVerifier = codeActions => Assert.Equal(2, codeActions.Length), }.RunAsync(); - } [Fact] - public async Task TestImplementEventThroughMember() - { - await TestInRegularAndScriptAsync(""" + public Task TestImplementEventThroughMember() + => TestInRegularAndScriptAsync(""" interface IGoo { event System.EventHandler E; @@ -3194,12 +3056,10 @@ public event EventHandler E } } """, codeAction: ("False;False;False:global::IGoo;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;canGoo", 1)); - } [Fact] - public async Task TestImplementEventThroughExplicitMember() - { - await TestInRegularAndScriptAsync( + public Task TestImplementEventThroughExplicitMember() + => TestInRegularAndScriptAsync( @"interface IGoo { event System . EventHandler E ; } class CanGoo : IGoo { event System.EventHandler IGoo.E { add { } remove { } } } class HasCanGoo : {|CS0535:IGoo|} { CanGoo canGoo; }", """ using System; @@ -3221,12 +3081,10 @@ public event EventHandler E } """, codeAction: ("False;False;False:global::IGoo;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;canGoo", 1)); - } [Fact] - public async Task TestImplementEvent() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementEvent() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IGoo { @@ -3250,13 +3108,11 @@ abstract class Goo : IGoo public event EventHandler E; } """, -codeAction: ("False;False;True:global::IGoo;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0)); - } + codeAction: ("False;False;True:global::IGoo;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0)); [Fact] - public async Task TestImplementEventAbstractly() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementEventAbstractly() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IGoo { @@ -3280,13 +3136,11 @@ abstract class Goo : IGoo public abstract event EventHandler E; } """, -codeAction: ("False;True;True:global::IGoo;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); - } + codeAction: ("False;True;True:global::IGoo;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); [Fact] - public async Task TestImplementEventExplicitly() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementEventExplicitly() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IGoo { @@ -3321,13 +3175,11 @@ event EventHandler IGoo.E } } """, -codeAction: ("True;False;False:global::IGoo;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 2)); - } + codeAction: ("True;False;False:global::IGoo;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 2)); [Fact] - public async Task TestFaultToleranceInStaticMembers_01() - { - await new VerifyCS.Test + public Task TestFaultToleranceInStaticMembers_01() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = """ @@ -3343,7 +3195,6 @@ class Program : IFoo } """, }.RunAsync(); - } [Fact] public async Task TestFaultToleranceInStaticMembers_02() @@ -3434,9 +3285,8 @@ public int Goo(string s) } [Fact] - public async Task TestIndexers() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestIndexers() + => TestWithAllCodeStyleOptionsOffAsync( """ public interface ISomeInterface { @@ -3469,12 +3319,10 @@ public int this[int index] } } """); - } [Fact] - public async Task TestIndexersExplicit() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestIndexersExplicit() + => TestWithAllCodeStyleOptionsOffAsync( """ public interface ISomeInterface { @@ -3507,13 +3355,11 @@ int ISomeInterface.this[int index] } } """, -codeAction: ("True;False;False:global::ISomeInterface;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); - } + codeAction: ("True;False;False:global::ISomeInterface;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); [Fact] - public async Task TestIndexersWithASingleAccessor() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestIndexersWithASingleAccessor() + => TestWithAllCodeStyleOptionsOffAsync( """ public interface ISomeInterface { @@ -3541,12 +3387,10 @@ public int this[int index] } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542357")] - public async Task TestConstraints1() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestConstraints1() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -3571,12 +3415,10 @@ public void Goo() where T : class } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542357")] - public async Task TestConstraintsExplicit() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestConstraintsExplicit() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -3601,13 +3443,11 @@ void I.Goo() } } """, -codeAction: ("True;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); - } + codeAction: ("True;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542357")] - public async Task TestUsingAddedForConstraint() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestUsingAddedForConstraint() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -3634,12 +3474,10 @@ public void Goo() where T : Attribute } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542379")] - public async Task TestIndexer() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestIndexer() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -3672,12 +3510,10 @@ public int this[int x] } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542588")] - public async Task TestRecursiveConstraint1() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestRecursiveConstraint1() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -3706,12 +3542,10 @@ public void Goo() where T : IComparable } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542588")] - public async Task TestRecursiveConstraint2() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestRecursiveConstraint2() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -3740,13 +3574,11 @@ void I.Goo() } } """, -codeAction: ("True;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); - } + codeAction: ("True;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] - public async Task TestUnexpressibleConstraint1() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestUnexpressibleConstraint1() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -3771,12 +3603,10 @@ void I.Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] - public async Task TestUnexpressibleConstraint2() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestUnexpressibleConstraint2() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -3801,12 +3631,10 @@ public void Goo() where T : class } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] - public async Task TestUnexpressibleConstraint3() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestUnexpressibleConstraint3() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -3831,13 +3659,11 @@ void I.Goo() } } """, -codeAction: ("True;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); - } + codeAction: ("True;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] - public async Task TestUnexpressibleConstraint4() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestUnexpressibleConstraint4() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -3866,12 +3692,10 @@ void I.Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] - public async Task TestUnexpressibleConstraint5() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestUnexpressibleConstraint5() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -3900,12 +3724,10 @@ void I.Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] - public async Task TestUnexpressibleConstraint6() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestUnexpressibleConstraint6() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -3938,12 +3760,10 @@ void I.Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] - public async Task TestUnexpressibleConstraint7() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestUnexpressibleConstraint7() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -3972,12 +3792,10 @@ void I.Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] - public async Task TestUnexpressibleConstraint8() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestUnexpressibleConstraint8() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -4006,12 +3824,10 @@ void I.Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] - public async Task TestUnexpressibleConstraint9() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestUnexpressibleConstraint9() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -4048,12 +3864,10 @@ class A : I } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542621")] - public async Task TestUnexpressibleConstraint10_CSharp72() - { - await new VerifyCS.Test + public Task TestUnexpressibleConstraint10_CSharp72() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp7_2, TestCode = @@ -4087,12 +3901,10 @@ void I.Goo() } """, }.RunAsync(); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542621")] - public async Task TestUnexpressibleConstraint10_CSharp8() - { - await new VerifyCS.Test + public Task TestUnexpressibleConstraint10_CSharp8() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp8, TestCode = @@ -4126,12 +3938,10 @@ void I.Goo() } """, }.RunAsync(); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542669")] - public async Task TestArrayConstraint() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestArrayConstraint() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -4160,12 +3970,10 @@ void I.Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542743")] - public async Task TestMultipleClassConstraints() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestMultipleClassConstraints() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -4194,12 +4002,10 @@ class C : I } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542751")] - public async Task TestClassConstraintAndRefConstraint() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestClassConstraintAndRefConstraint() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -4228,12 +4034,10 @@ void I.Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542505")] - public async Task TestRenameConflictingTypeParameters1() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestRenameConflictingTypeParameters1() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; using System.Collections.Generic; @@ -4264,12 +4068,10 @@ public void Goo(S x, IList list) where S1 : S } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542505")] - public async Task TestRenameConflictingTypeParameters2() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestRenameConflictingTypeParameters2() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; using System.Collections.Generic; @@ -4300,13 +4102,11 @@ void I.Goo(S x, IList list) } } """, -codeAction: ("True;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); - } + codeAction: ("True;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542505")] - public async Task TestRenameConflictingTypeParameters3() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestRenameConflictingTypeParameters3() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; using System.Collections.Generic; @@ -4343,12 +4143,10 @@ public void Goo(A x, B y, IList list1, IList list2) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542505")] - public async Task TestRenameConflictingTypeParameters4() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestRenameConflictingTypeParameters4() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; using System.Collections.Generic; @@ -4383,13 +4181,11 @@ void I.Goo(A x, B y, IList list1, IList list2) } } """, -codeAction: ("True;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); - } + codeAction: ("True;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542506")] - public async Task TestNameSimplification() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestNameSimplification() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -4432,12 +4228,10 @@ public void Goo(B x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542506")] - public async Task TestNameSimplification2() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestNameSimplification2() + => TestWithAllCodeStyleOptionsOffAsync( """ class A { @@ -4476,12 +4270,10 @@ public void Goo(B[] x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542506")] - public async Task TestNameSimplification3() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestNameSimplification3() + => TestWithAllCodeStyleOptionsOffAsync( """ class A { @@ -4520,12 +4312,10 @@ public void Goo(B[][,][,,][,,,] x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544166")] - public async Task TestImplementAbstractProperty() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementAbstractProperty() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IGoo { @@ -4547,8 +4337,7 @@ abstract class Goo : IGoo public abstract int Gibberish { get; set; } } """, -codeAction: ("False;True;True:global::IGoo;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); - } + codeAction: ("False;True;True:global::IGoo;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544210")] public async Task TestMissingOnWrongArity() @@ -4569,9 +4358,8 @@ class C : {|CS0305:I1|} } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544281")] - public async Task TestImplicitDefaultValue() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplicitDefaultValue() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IOptional { @@ -4596,12 +4384,10 @@ public int Goo(int g = 0) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544281")] - public async Task TestExplicitDefaultValue() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestExplicitDefaultValue() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IOptional { @@ -4626,8 +4412,7 @@ int IOptional.Goo(int g) } } """, -codeAction: ("True;False;False:global::IOptional;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); - } + codeAction: ("True;False;False:global::IOptional;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); [Fact] public async Task TestMissingInHiddenType() @@ -4647,9 +4432,8 @@ class Program : {|CS0535:IComparable|} } [Fact] - public async Task TestGenerateIntoVisiblePart() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestGenerateIntoVisiblePart() + => TestWithAllCodeStyleOptionsOffAsync( """ #line default using System; @@ -4681,12 +4465,10 @@ void Goo() } #line default """); - } [Fact] - public async Task TestGenerateIfAvailableRegionExists() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestGenerateIfAvailableRegionExists() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -4717,7 +4499,6 @@ public int CompareTo(object obj) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545334")] public async Task TestNoGenerateInVenusCase1() @@ -4738,9 +4519,8 @@ class Goo : {|CS0535:IComparable|}{|CS1513:|}{|CS1514:|} } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545476")] - public async Task TestOptionalDateTime1() - { - await new VerifyCS.Test + public Task TestOptionalDateTime1() + => new VerifyCS.Test { TestCode = """ using System; @@ -4779,12 +4559,10 @@ public void Goo([DateTimeConstant(100), Optional] DateTime x) // 🐛 one value is generated with 100L instead of 100 CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545476")] - public async Task TestOptionalDateTime2() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestOptionalDateTime2() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; using System.Runtime.CompilerServices; @@ -4817,13 +4595,11 @@ void IGoo.Goo(DateTime x) } } """, -codeAction: ("True;False;False:global::IGoo;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); - } + codeAction: ("True;False;False:global::IGoo;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545477")] - public async Task TestIUnknownIDispatchAttributes1() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestIUnknownIDispatchAttributes1() + => TestWithAllCodeStyleOptionsOffAsync( """ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -4861,12 +4637,10 @@ public void Goo2([IDispatchConstant, Optional] object x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545477")] - public async Task TestIUnknownIDispatchAttributes2() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestIUnknownIDispatchAttributes2() + => TestWithAllCodeStyleOptionsOffAsync( """ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -4904,13 +4678,11 @@ void IGoo.Goo2(object x) } } """, -codeAction: ("True;False;False:global::IGoo;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); - } + codeAction: ("True;False;False:global::IGoo;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545464")] - public async Task TestTypeNameConflict() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestTypeNameConflict() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IGoo { @@ -4935,12 +4707,10 @@ void IGoo.Goo() } } """); - } [Fact] - public async Task TestStringLiteral() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestStringLiteral() + => TestWithAllCodeStyleOptionsOffAsync( @"interface IGoo { void Goo ( string s = ""\"""" ) ; } class B : {|CS0535:IGoo|} { }", """ interface IGoo { void Goo ( string s = "\"" ) ; } @@ -4952,12 +4722,10 @@ public void Goo(string s = "\"") } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")] - public async Task TestOptionalNullableStructParameter1() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestOptionalNullableStructParameter1() + => TestWithAllCodeStyleOptionsOffAsync( """ struct b { @@ -4990,12 +4758,10 @@ public void m(b? x = null, b? y = null) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")] - public async Task TestOptionalNullableStructParameter2() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestOptionalNullableStructParameter2() + => TestWithAllCodeStyleOptionsOffAsync( """ struct b { @@ -5028,12 +4794,10 @@ void d.m(b? x, b? y) } } """, codeAction: ("True;False;False:global::d;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")] - public async Task TestOptionalNullableIntParameter() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestOptionalNullableIntParameter() + => TestWithAllCodeStyleOptionsOffAsync( """ interface d { @@ -5058,12 +4822,10 @@ public void m(int? x = 5, int? y = null) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545613")] - public async Task TestOptionalWithNoDefaultValue() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestOptionalWithNoDefaultValue() + => TestWithAllCodeStyleOptionsOffAsync( """ using System.Runtime.InteropServices; @@ -5092,12 +4854,10 @@ public void Goo([Optional] I o) } } """); - } [Fact] - public async Task TestIntegralAndFloatLiterals() - { - await new VerifyCS.Test + public Task TestIntegralAndFloatLiterals() + => new VerifyCS.Test { TestCode = """ interface I @@ -5289,12 +5049,10 @@ public void M24(double s = double.MaxValue) // 🐛 one value is generated with 0U instead of 0 CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact] - public async Task TestEnumLiterals() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestEnumLiterals() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -5356,12 +5114,10 @@ public void M2(FlagE e = FlagE.A | FlagE.B) } } """); - } [Fact] - public async Task TestCharLiterals() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestCharLiterals() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -5460,12 +5216,10 @@ public void M11(char c = '\u2029') } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545695")] - public async Task TestRemoveParenthesesAroundTypeReference1() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestRemoveParenthesesAroundTypeReference1() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -5497,12 +5251,10 @@ public void Goo(DayOfWeek x = DayOfWeek.Friday) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545696")] - public async Task TestDecimalConstants1() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestDecimalConstants1() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -5527,12 +5279,10 @@ public void Goo(decimal x = decimal.MaxValue) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545711")] - public async Task TestNullablePrimitiveLiteral() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestNullablePrimitiveLiteral() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -5557,12 +5307,10 @@ public void Goo(decimal? x = decimal.MaxValue) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545715")] - public async Task TestNullableEnumType() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestNullableEnumType() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -5591,12 +5339,10 @@ public void Goo(DayOfWeek? x = DayOfWeek.Friday) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545752")] - public async Task TestByteLiterals() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestByteLiterals() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -5621,7 +5367,6 @@ public void Goo(byte x = 1) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545736")] public async Task TestCastedOptionalParameter1() @@ -5658,9 +5403,8 @@ public void Goo(ConsoleColor x = (ConsoleColor)(-1)) } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545737")] - public async Task TestCastedEnumValue() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestCastedEnumValue() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -5689,12 +5433,10 @@ public void Goo(ConsoleColor x = (ConsoleColor)int.MaxValue) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545785")] - public async Task TestNoCastFromZeroToEnum() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestNoCastFromZeroToEnum() + => TestWithAllCodeStyleOptionsOffAsync( """ enum E { @@ -5729,12 +5471,10 @@ public void Goo(E x = 0) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545793")] - public async Task TestMultiDimArray() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestMultiDimArray() + => TestWithAllCodeStyleOptionsOffAsync( """ using System.Runtime.InteropServices; @@ -5763,12 +5503,10 @@ public void Goo([{|CS1745:DefaultParameterValue|}(1), {|CS1745:Optional|}] int x } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545794")] - public async Task TestParametersAfterOptionalParameter() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestParametersAfterOptionalParameter() + => TestWithAllCodeStyleOptionsOffAsync( """ using System.Runtime.InteropServices; @@ -5797,7 +5535,6 @@ public void Goo([{|CS1745:DefaultParameterValue|}(1), {|CS1745:Optional|}] int x } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545605")] public async Task TestAttributeInParameter() @@ -5845,9 +5582,8 @@ public void Goo([DateTimeConstant(100), Optional] DateTime d1, [IUnknownConstant } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545897")] - public async Task TestNameConflictBetweenMethodAndTypeParameter() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestNameConflictBetweenMethodAndTypeParameter() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -5872,12 +5608,10 @@ public void T1(T x, T2 y) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545895")] - public async Task TestTypeParameterReplacementWithOuterType() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestTypeParameterReplacementWithOuterType() + => TestWithAllCodeStyleOptionsOffAsync( """ using System.Collections.Generic; @@ -5906,12 +5640,10 @@ public void Goo(T y, List.Enumerator x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545864")] - public async Task TestFloatConstant() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestFloatConstant() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -5936,12 +5668,10 @@ public void Goo(float x = 1E+10F) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544640")] - public async Task TestKeywordForTypeParameterName() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestKeywordForTypeParameterName() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -5965,12 +5695,10 @@ public void Goo<@class>() } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545922")] - public async Task TestExtremeDecimals() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestExtremeDecimals() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -6002,12 +5730,10 @@ public void Goo2(decimal x = -10000000000000000000000000000M) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544659")] - public async Task TestNonZeroScaleDecimals() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestNonZeroScaleDecimals() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -6032,12 +5758,10 @@ public void Goo(decimal x = 0.1M) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544639")] - public async Task TestUnterminatedComment() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestUnterminatedComment() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -6059,12 +5783,10 @@ public object GetService(Type serviceType) } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529920")] - public async Task TestNewLineBeforeDirective() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestNewLineBeforeDirective() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -6085,12 +5807,10 @@ public object GetService(Type serviceType) } #pragma warning disable """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529947")] - public async Task TestCommentAfterInterfaceList1() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestCommentAfterInterfaceList1() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -6109,12 +5829,10 @@ public object GetService(Type serviceType) } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529947")] - public async Task TestCommentAfterInterfaceList2() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestCommentAfterInterfaceList2() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -6133,13 +5851,11 @@ public object GetService(Type serviceType) } // Implement interface """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")] - public async Task TestImplementIDisposable_NoDisposePattern() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementIDisposable_NoDisposePattern() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; class C : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|} @@ -6155,32 +5871,30 @@ public void Dispose() } """, codeAction: ("False;False;True:global::System.IDisposable;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")] - public async Task TestImplementIDisposable_DisposePattern() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementIDisposable_DisposePattern() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; class C : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|} """, -$@"using System; -class C : IDisposable -{{ - private bool disposedValue; + $$""" + using System; + class C : IDisposable + { + private bool disposedValue; -{DisposePattern("protected virtual ", "C", "public void ")} -}} -", codeAction: ("False;False;True:global::System.IDisposable;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1)); - } + {{DisposePattern("protected virtual ", "C", "public void ")}} + } + + """, codeAction: ("False;False;True:global::System.IDisposable;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")] - public async Task TestImplementIDisposableExplicitly_NoDisposePattern() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementIDisposableExplicitly_NoDisposePattern() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; class C : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|} @@ -6196,13 +5910,11 @@ void IDisposable.Dispose() } """, codeAction: ("True;False;False:global::System.IDisposable;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 2)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/941469")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")] - public async Task TestImplementIDisposableExplicitly_DisposePattern() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementIDisposableExplicitly_DisposePattern() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; class C : {|CS0535:System.IDisposable|} @@ -6212,24 +5924,24 @@ class IDisposable } } """, -$@"using System; -class C : System.IDisposable -{{ - private bool disposedValue; + $$""" + using System; + class C : System.IDisposable + { + private bool disposedValue; - class IDisposable - {{ - }} + class IDisposable + { + } -{DisposePattern("protected virtual ", "C", "void System.IDisposable.")} -}}", codeAction: ("True;False;False:global::System.IDisposable;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3)); - } + {{DisposePattern("protected virtual ", "C", "void System.IDisposable.")}} + } + """, codeAction: ("True;False;False:global::System.IDisposable;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")] - public async Task TestImplementIDisposableAbstractly_NoDisposePattern() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementIDisposableAbstractly_NoDisposePattern() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; abstract class C : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|} @@ -6242,13 +5954,11 @@ abstract class C : IDisposable } """, codeAction: ("False;True;True:global::System.IDisposable;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 2)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")] - public async Task TestImplementIDisposableThroughMember_NoDisposePattern() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementIDisposableThroughMember_NoDisposePattern() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; class C : {|CS0535:IDisposable|} @@ -6268,32 +5978,30 @@ public void Dispose() } } """, codeAction: ("False;False;False:global::System.IDisposable;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;goo", 2)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/941469")] - public async Task TestImplementIDisposableExplicitly_NoNamespaceImportForSystem() - { - await new VerifyCS.Test + public Task TestImplementIDisposableExplicitly_NoNamespaceImportForSystem() + => new VerifyCS.Test { TestCode = @"class C : {|CS0535:System.IDisposable|}{|CS1513:|}{|CS1514:|}", - FixedCode = $@"class C : System.IDisposable -{{ - private bool disposedValue; + FixedCode = $$""" + class C : System.IDisposable + { + private bool disposedValue; + + {{DisposePattern("protected virtual ", "C", "void System.IDisposable.", gcPrefix: "System.")}} + } -{DisposePattern("protected virtual ", "C", "void System.IDisposable.", gcPrefix: "System.")} -}} -", + """, CodeActionIndex = 3, // 🐛 generated QualifiedName where SimpleMemberAccessExpression was expected CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/951968")] - public async Task TestImplementIDisposableViaBaseInterface_NoDisposePattern() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementIDisposableViaBaseInterface_NoDisposePattern() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; interface I : IDisposable @@ -6323,12 +6031,10 @@ public void F() } } """, codeAction: ("False;False;True:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/951968")] - public async Task TestImplementIDisposableViaBaseInterface() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementIDisposableViaBaseInterface() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; interface I : IDisposable @@ -6339,28 +6045,28 @@ class C : {|CS0535:{|CS0535:I|}|} { } """, -$@"using System; -interface I : IDisposable -{{ - void F(); -}} -class C : I -{{ - private bool disposedValue; + $$""" + using System; + interface I : IDisposable + { + void F(); + } + class C : I + { + private bool disposedValue; - public void F() - {{ - throw new NotImplementedException(); - }} + public void F() + { + throw new NotImplementedException(); + } -{DisposePattern("protected virtual ", "C", "public void ")} -}}", codeAction: ("False;False;True:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1)); - } + {{DisposePattern("protected virtual ", "C", "public void ")}} + } + """, codeAction: ("False;False;True:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/951968")] - public async Task TestImplementIDisposableExplicitlyViaBaseInterface() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementIDisposableExplicitlyViaBaseInterface() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; interface I : IDisposable @@ -6371,28 +6077,28 @@ class C : {|CS0535:{|CS0535:I|}|} { } """, -$@"using System; -interface I : IDisposable -{{ - void F(); -}} -class C : I -{{ - private bool disposedValue; + $$""" + using System; + interface I : IDisposable + { + void F(); + } + class C : I + { + private bool disposedValue; - void I.F() - {{ - throw new NotImplementedException(); - }} + void I.F() + { + throw new NotImplementedException(); + } -{DisposePattern("protected virtual ", "C", "void IDisposable.")} -}}", codeAction: ("True;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3)); - } + {{DisposePattern("protected virtual ", "C", "void IDisposable.")}} + } + """, codeAction: ("True;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/941469")] - public async Task TestDoNotImplementDisposePatternForLocallyDefinedIDisposable() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestDoNotImplementDisposePatternForLocallyDefinedIDisposable() + => TestWithAllCodeStyleOptionsOffAsync( """ namespace System { @@ -6421,12 +6127,10 @@ void IDisposable.Dispose() } } """, codeAction: ("True;False;False:global::System.IDisposable;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); - } [Fact] - public async Task TestDoNotImplementDisposePatternForStructures1() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestDoNotImplementDisposePatternForStructures1() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; struct S : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|} @@ -6442,12 +6146,10 @@ public void Dispose() } """); - } [Fact] - public async Task TestDoNotImplementDisposePatternForStructures2() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestDoNotImplementDisposePatternForStructures2() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; struct S : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|} @@ -6463,7 +6165,6 @@ void IDisposable.Dispose() } """, codeAction: ("True;False;False:global::System.IDisposable;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545924")] public async Task TestEnumNestedInGeneric() @@ -6519,9 +6220,8 @@ public void Goo(C.E x = C.E.X) } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545939")] - public async Task TestUnterminatedString1() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestUnterminatedString1() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -6538,12 +6238,10 @@ public object GetService(Type serviceType) } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545939")] - public async Task TestUnterminatedString2() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestUnterminatedString2() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -6560,12 +6258,10 @@ public object GetService(Type serviceType) } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545939")] - public async Task TestUnterminatedString3() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestUnterminatedString3() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -6582,12 +6278,10 @@ public object GetService(Type serviceType) } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545939")] - public async Task TestUnterminatedString4() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestUnterminatedString4() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -6604,12 +6298,10 @@ public object GetService(Type serviceType) } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545940")] - public async Task TestDecimalENotation() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestDecimalENotation() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -6655,7 +6347,6 @@ public void Goo4(decimal x = -0.000000000000000000000001M) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545938")] public async Task TestGenericEnumWithRenamedTypeParameters() @@ -6711,9 +6402,8 @@ public void Goo(T y, C.E x = C.E.X) } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545919")] - public async Task TestDoNotRenameTypeParameterToParameterName() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestDoNotRenameTypeParameterToParameterName() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -6738,12 +6428,10 @@ public void Goo(T T1) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530265")] - public async Task TestAttributes() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestAttributes() + => TestWithAllCodeStyleOptionsOffAsync( """ using System.Runtime.InteropServices; @@ -6775,12 +6463,10 @@ public bool Goo([MarshalAs(UnmanagedType.U1)] bool x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530265")] - public async Task TestAttributesExplicit() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestAttributesExplicit() + => TestWithAllCodeStyleOptionsOffAsync( """ using System.Runtime.InteropServices; @@ -6811,13 +6497,11 @@ bool I.Goo(bool x) } } """, -codeAction: ("True;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); - } + codeAction: ("True;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546443")] - public async Task TestParameterNameWithTypeName() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestParameterNameWithTypeName() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -6846,12 +6530,10 @@ public void Bar(DateTime DateTime) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530521")] - public async Task TestUnboundGeneric() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestUnboundGeneric() + => TestWithAllCodeStyleOptionsOffAsync( """ using System.Collections.Generic; using System.Runtime.InteropServices; @@ -6885,12 +6567,10 @@ public void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/752436")] - public async Task TestQualifiedNameImplicitInterface() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestQualifiedNameImplicitInterface() + => TestWithAllCodeStyleOptionsOffAsync( """ namespace N { @@ -6921,12 +6601,10 @@ public void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/752436")] - public async Task TestQualifiedNameExplicitInterface() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestQualifiedNameExplicitInterface() + => TestWithAllCodeStyleOptionsOffAsync( """ namespace N { @@ -6959,12 +6637,10 @@ void I.M() } } """, codeAction: ("True;False;False:global::N.I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/847464")] - public async Task TestImplementInterfaceForPartialType() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementInterfaceForPartialType() + => TestWithAllCodeStyleOptionsOffAsync( """ public interface I { @@ -6997,12 +6673,10 @@ void I.Goo() } } """, codeAction: ("True;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/847464")] - public async Task TestImplementInterfaceForPartialType2() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementInterfaceForPartialType2() + => TestWithAllCodeStyleOptionsOffAsync( """ public interface I { @@ -7035,12 +6709,10 @@ partial class C { } """, codeAction: ("True;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/847464")] - public async Task TestImplementInterfaceForPartialType3() - { - await new VerifyCS.Test + public Task TestImplementInterfaceForPartialType3() + => new VerifyCS.Test { TestCode = """ public interface I @@ -7095,7 +6767,6 @@ partial class C : {|CS0535:I2|} CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, CodeActionIndex = 1, }.RunAsync(); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/752447")] public async Task TestExplicitImplOfIndexedProperty() @@ -7159,9 +6830,8 @@ void IGoo.set_IndexProp(int p1, string Value) } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602475")] - public async Task TestImplicitImplOfIndexedProperty() - { - await new VerifyCS.Test + public Task TestImplicitImplOfIndexedProperty() + => new VerifyCS.Test { TestState = { @@ -7214,7 +6884,6 @@ public void set_P(int x, object Value) }, }, }.RunAsync(); - } [Fact] public async Task TestImplementationOfIndexerWithInaccessibleAttributes() @@ -7301,9 +6970,8 @@ class Goo : [|IComparable|] #endif [Fact] - public async Task TestImplementInterfaceForImplicitIDisposable() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementInterfaceForImplicitIDisposable() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -7311,20 +6979,20 @@ class Program : {|CS0535:IDisposable|} { } """, -$@"using System; + $$""" + using System; -class Program : IDisposable -{{ - private bool disposedValue; + class Program : IDisposable + { + private bool disposedValue; -{DisposePattern("protected virtual ", "Program", "public void ")} -}}", codeAction: ("False;False;True:global::System.IDisposable;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1)); - } + {{DisposePattern("protected virtual ", "Program", "public void ")}} + } + """, codeAction: ("False;False;True:global::System.IDisposable;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1)); [Fact] - public async Task TestImplementInterfaceForExplicitIDisposable() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementInterfaceForExplicitIDisposable() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -7333,21 +7001,21 @@ class Program : {|CS0535:IDisposable|} private bool DisposedValue; } """, -$@"using System; + $$""" + using System; -class Program : IDisposable -{{ - private bool DisposedValue; - private bool disposedValue; + class Program : IDisposable + { + private bool DisposedValue; + private bool disposedValue; -{DisposePattern("protected virtual ", "Program", "void IDisposable.")} -}}", codeAction: ("True;False;False:global::System.IDisposable;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3)); - } + {{DisposePattern("protected virtual ", "Program", "void IDisposable.")}} + } + """, codeAction: ("True;False;False:global::System.IDisposable;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3)); [Fact] - public async Task TestImplementInterfaceForIDisposableNonApplicable1() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementInterfaceForIDisposableNonApplicable1() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -7369,12 +7037,10 @@ public void Dispose() } } """, codeAction: ("False;False;True:global::System.IDisposable;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0)); - } [Fact] - public async Task TestImplementInterfaceForIDisposableNonApplicable2() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementInterfaceForIDisposableNonApplicable2() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -7400,12 +7066,10 @@ public void Dispose() } } """, codeAction: ("False;False;True:global::System.IDisposable;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0)); - } [Fact] - public async Task TestImplementInterfaceForExplicitIDisposableWithSealedClass() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementInterfaceForExplicitIDisposableWithSealedClass() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -7413,20 +7077,20 @@ sealed class Program : {|CS0535:IDisposable|} { } """, -$@"using System; + $$""" + using System; -sealed class Program : IDisposable -{{ - private bool disposedValue; + sealed class Program : IDisposable + { + private bool disposedValue; -{DisposePattern("private ", "Program", "void IDisposable.")} -}}", codeAction: ("True;False;False:global::System.IDisposable;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3)); - } + {{DisposePattern("private ", "Program", "void IDisposable.")}} + } + """, codeAction: ("True;False;False:global::System.IDisposable;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/9760")] - public async Task TestImplementInterfaceForExplicitIDisposableWithExistingField() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementInterfaceForExplicitIDisposableWithExistingField() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -7435,21 +7099,21 @@ class Program : {|CS0535:IDisposable|} private bool disposedValue; } """, -$@"using System; + $$""" + using System; -class Program : IDisposable -{{ - private bool disposedValue; - private bool disposedValue1; + class Program : IDisposable + { + private bool disposedValue; + private bool disposedValue1; -{DisposePattern("protected virtual ", "Program", "public void ", disposeField: "disposedValue1")} -}}", codeAction: ("False;False;True:global::System.IDisposable;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1)); - } + {{DisposePattern("protected virtual ", "Program", "public void ", disposeField: "disposedValue1")}} + } + """, codeAction: ("False;False;True:global::System.IDisposable;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/9760")] - public async Task TestImplementInterfaceUnderscoreNameForFields() - { - await new VerifyCS.Test + public Task TestImplementInterfaceUnderscoreNameForFields() + => new VerifyCS.Test { TestCode = """ using System; @@ -7458,26 +7122,26 @@ class Program : {|CS0535:IDisposable|} { } """, - FixedCode = $@"using System; + FixedCode = $$""" + using System; -class Program : IDisposable -{{ - private bool _disposedValue; + class Program : IDisposable + { + private bool _disposedValue; -{DisposePattern("protected virtual ", "Program", "public void ", disposeField: "_disposedValue")} -}}", + {{DisposePattern("protected virtual ", "Program", "public void ", disposeField: "_disposedValue")}} + } + """, Options = { _options.FieldNamesAreCamelCaseWithUnderscorePrefix, }, CodeActionIndex = 1, }.RunAsync(); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939123")] - public async Task TestNoComAliasNameAttributeOnMethodParameters() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestNoComAliasNameAttributeOnMethodParameters() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -7502,12 +7166,10 @@ public void M(int p) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939123")] - public async Task TestNoComAliasNameAttributeOnMethodReturnType() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestNoComAliasNameAttributeOnMethodReturnType() + => TestWithAllCodeStyleOptionsOffAsync( """ using System.Runtime.InteropServices; @@ -7538,12 +7200,10 @@ public long M(int p) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939123")] - public async Task TestNoComAliasNameAttributeOnIndexerParameters() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestNoComAliasNameAttributeOnIndexerParameters() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I { @@ -7571,12 +7231,10 @@ public long this[int p] } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947819")] - public async Task TestMissingOpenBrace() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestMissingOpenBrace() + => TestWithAllCodeStyleOptionsOffAsync( """ namespace Scenarios { @@ -7611,7 +7269,6 @@ public void M1() // Comment } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994328")] public async Task TestDisposePatternWhenAdditionalUsingsAreIntroduced1() @@ -7692,9 +7349,8 @@ public List M(Dictionary> a, TT b, UU c) where UU : TT } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994328")] - public async Task TestDisposePatternWhenAdditionalUsingsAreIntroduced2() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestDisposePatternWhenAdditionalUsingsAreIntroduced2() + => TestWithAllCodeStyleOptionsOffAsync( """ interface I : System.IDisposable, System.IEquatable where U : T { @@ -7746,7 +7402,6 @@ partial class C { } """, codeAction: ("True;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3)); - } private static string DisposePattern( string disposeVisibility, @@ -7788,9 +7443,8 @@ private static string DisposePattern( } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1132014")] - public async Task TestInaccessibleAttributes() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestInaccessibleAttributes() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; @@ -7833,12 +7487,10 @@ private class SomeAttribute : Attribute } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2785")] - public async Task TestImplementInterfaceThroughStaticMemberInGenericClass() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestImplementInterfaceThroughStaticMemberInGenericClass() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; using System.Collections.Generic; @@ -7941,13 +7593,11 @@ IEnumerator IEnumerable.GetEnumerator() } } """, -codeAction: ("False;False;False:global::System.Collections.Generic.IList;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;innerList", 1)); - } + codeAction: ("False;False;False:global::System.Collections.Generic.IList;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;innerList", 1)); [Fact, CompilerTrait(CompilerFeature.Tuples)] - public async Task LongTuple() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task LongTuple() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IInterface { @@ -7975,12 +7625,10 @@ class Class : IInterface } } """); - } [Fact] - public async Task LongTupleWithNames() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task LongTupleWithNames() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IInterface { @@ -8008,12 +7656,10 @@ class Class : IInterface } } """); - } [Fact] - public async Task GenericWithTuple() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task GenericWithTuple() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IInterface { @@ -8041,12 +7687,10 @@ class Class : IInterface<(int, string), int> } } """); - } [Fact] - public async Task GenericWithTupleWithNamess() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task GenericWithTupleWithNamess() + => TestWithAllCodeStyleOptionsOffAsync( """ interface IInterface { @@ -8074,12 +7718,10 @@ class Class : IInterface<(int, string), int> } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15387")] - public async Task TestWithGroupingOff1() - { - await new VerifyCS.Test + public Task TestWithGroupingOff1() + => new VerifyCS.Test { TestCode = """ interface IInterface @@ -8113,12 +7755,10 @@ void M() { } } } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15387")] - public async Task TestDoNotReorderComImportMembers_01() - { - await TestInRegularAndScriptAsync( + public Task TestDoNotReorderComImportMembers_01() + => TestInRegularAndScriptAsync( """ using System.Runtime.InteropServices; @@ -8169,12 +7809,10 @@ public void MOverload(int i) public int Prop => throw new System.NotImplementedException(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15387")] - public async Task TestDoNotReorderComImportMembers_02() - { - await new VerifyCS.Test + public Task TestDoNotReorderComImportMembers_02() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @@ -8215,12 +7853,10 @@ class Class : IComInterface } """, }.RunAsync(); - } [Fact] - public async Task TestRefReturns() - { - await TestInRegularAndScriptAsync( + public Task TestRefReturns() + => TestInRegularAndScriptAsync( """ using System; @@ -8255,13 +7891,11 @@ public ref int IGoo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/5898")] [WorkItem("https://github.com/dotnet/roslyn/issues/13932")] - public async Task TestAutoProperties() - { - await new VerifyCS.Test() + public Task TestAutoProperties() + => new VerifyCS.Test() { TestCode = """ interface IInterface @@ -8298,12 +7932,10 @@ class Class : IInterface } } }.RunAsync(); - } [Fact] - public async Task TestOptionalParameterWithDefaultLiteral() - { - await new VerifyCS.Test + public Task TestOptionalParameterWithDefaultLiteral() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp7_1, TestCode = """ @@ -8336,12 +7968,10 @@ public void Method1(CancellationToken cancellationToken = default) """, Options = { AllOptionsOff }, }.RunAsync(); - } [Theory, CombinatorialData] - public async Task TestRefWithMethod_Parameters([CombinatorialValues("ref", "in", "ref readonly")] string modifier) - { - await TestInRegularAndScriptAsync( + public Task TestRefWithMethod_Parameters([CombinatorialValues("ref", "in", "ref readonly")] string modifier) + => TestInRegularAndScriptAsync( $$""" interface ITest { @@ -8364,12 +7994,10 @@ public void Method({{modifier}} int p) } } """); - } [Fact] - public async Task TestRefReadOnlyWithMethod_ReturnType() - { - await TestInRegularAndScriptAsync( + public Task TestRefReadOnlyWithMethod_ReturnType() + => TestInRegularAndScriptAsync( """ interface ITest { @@ -8392,12 +8020,10 @@ public ref readonly int Method() } } """); - } [Fact] - public async Task TestRefReadOnlyWithProperty() - { - await TestInRegularAndScriptAsync( + public Task TestRefReadOnlyWithProperty() + => TestInRegularAndScriptAsync( """ interface ITest { @@ -8417,12 +8043,10 @@ public class Test : ITest public ref readonly int Property => throw new System.NotImplementedException(); } """); - } [Theory, CombinatorialData] - public async Task TestRefWithIndexer_Parameters([CombinatorialValues("in", "ref readonly")] string modifier) - { - await TestInRegularAndScriptAsync( + public Task TestRefWithIndexer_Parameters([CombinatorialValues("in", "ref readonly")] string modifier) + => TestInRegularAndScriptAsync( $$""" interface ITest { @@ -8442,12 +8066,10 @@ public class Test : ITest public int this[{{modifier}} int p] { set => throw new System.NotImplementedException(); } } """); - } [Fact] - public async Task TestRefReadOnlyWithIndexer_ReturnType() - { - await TestInRegularAndScriptAsync( + public Task TestRefReadOnlyWithIndexer_ReturnType() + => TestInRegularAndScriptAsync( """ interface ITest { @@ -8467,12 +8089,10 @@ public class Test : ITest public ref readonly int this[int p] => throw new System.NotImplementedException(); } """); - } [Fact] - public async Task TestUnmanagedConstraint() - { - await TestInRegularAndScriptAsync( + public Task TestUnmanagedConstraint() + => TestInRegularAndScriptAsync( """ public interface ITest { @@ -8495,12 +8115,10 @@ public void M() where T : unmanaged } } """); - } [Fact] - public async Task TestSealedMember_01() - { - await new VerifyCS.Test + public Task TestSealedMember_01() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = """ @@ -8535,12 +8153,10 @@ public void Method1() """, Options = { AllOptionsOff }, }.RunAsync(); - } [Fact] - public async Task TestSealedMember_02() - { - await new VerifyCS.Test + public Task TestSealedMember_02() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = """ @@ -8576,12 +8192,10 @@ void IInterface.Method1() Options = { AllOptionsOff }, CodeActionIndex = 1, }.RunAsync(); - } [Fact] - public async Task TestSealedMember_03() - { - await new VerifyCS.Test + public Task TestSealedMember_03() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = """ @@ -8614,12 +8228,10 @@ abstract class Class : IInterface Options = { AllOptionsOff }, CodeActionIndex = 1, }.RunAsync(); - } [Fact] - public async Task TestNonPublicMember_01() - { - await new VerifyCS.Test + public Task TestNonPublicMember_01() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = """ @@ -8667,12 +8279,10 @@ void IInterface.M1() Options = { AllOptionsOff }, CodeActionEquivalenceKey = "False;False;True:global::IInterface;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); - } [Fact] - public async Task TestNonPublicMember_02() - { - await new VerifyCS.Test + public Task TestNonPublicMember_02() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = """ @@ -8720,12 +8330,10 @@ void IInterface.M1() DiagnosticSelector = diagnostics => diagnostics[1], CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, }.RunAsync(); - } [Fact] - public async Task TestNonPublicMember_03() - { - await new VerifyCS.Test + public Task TestNonPublicMember_03() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = """ @@ -8770,12 +8378,10 @@ void IInterface.M1() Options = { AllOptionsOff }, CodeActionEquivalenceKey = "False;True;True:global::IInterface;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); - } [Fact] - public async Task TestNonPublicAccessor_01() - { - await new VerifyCS.Test + public Task TestNonPublicAccessor_01() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = """ @@ -8818,12 +8424,10 @@ public void Method1() Options = { AllOptionsOff }, CodeActionEquivalenceKey = "False;False;True:global::IInterface;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); - } [Fact] - public async Task TestNonPublicAccessor_02() - { - await new VerifyCS.Test + public Task TestNonPublicAccessor_02() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = """ @@ -8883,12 +8487,10 @@ int IInterface.P2 Options = { AllOptionsOff }, CodeActionEquivalenceKey = "True;False;False:global::IInterface;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); - } [Fact] - public async Task TestNonPublicAccessor_03() - { - await new VerifyCS.Test + public Task TestNonPublicAccessor_03() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = """ @@ -8928,12 +8530,10 @@ abstract class Class : {|CS0535:{|CS0535:IInterface|}|} Options = { AllOptionsOff }, CodeActionEquivalenceKey = "False;True;True:global::IInterface;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); - } [Fact] - public async Task TestPrivateAccessor_01() - { - await new VerifyCS.Test + public Task TestPrivateAccessor_01() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = """ @@ -8968,12 +8568,10 @@ public void Method1() """, Options = { AllOptionsOff }, }.RunAsync(); - } [Fact] - public async Task TestPrivateAccessor_02() - { - await new VerifyCS.Test + public Task TestPrivateAccessor_02() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = """ @@ -9009,12 +8607,10 @@ void IInterface.Method1() Options = { AllOptionsOff }, CodeActionIndex = 1, }.RunAsync(); - } [Fact] - public async Task TestPrivateAccessor_03() - { - await new VerifyCS.Test + public Task TestPrivateAccessor_03() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = """ @@ -9047,12 +8643,10 @@ abstract class Class : IInterface Options = { AllOptionsOff }, CodeActionIndex = 1, }.RunAsync(); - } [Fact] - public async Task TestInaccessibleMember_01() - { - await new VerifyCS.Test + public Task TestInaccessibleMember_01() + => new VerifyCS.Test { TestState = { @@ -9105,12 +8699,10 @@ public void Method1() // Specify the code action by equivalence key only to avoid trying to implement the interface explicitly with a second code fix pass. CodeActionEquivalenceKey = "False;False;True:global::IInterface;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); - } [Fact] - public async Task TestInaccessibleMember_02() - { - await new VerifyCS.Test + public Task TestInaccessibleMember_02() + => new VerifyCS.Test { TestState = { @@ -9161,12 +8753,10 @@ void IInterface.Method1() Options = { AllOptionsOff }, CodeActionIndex = 1, }.RunAsync(); - } [Fact] - public async Task TestInaccessibleMember_03() - { - await new VerifyCS.Test + public Task TestInaccessibleMember_03() + => new VerifyCS.Test { TestState = { @@ -9216,12 +8806,10 @@ abstract class Class : {|CS0535:{|CS0535:IInterface|}|} // Specify the code action by equivalence key only to avoid trying to execute a second code fix pass with a different action CodeActionEquivalenceKey = "False;True;True:global::IInterface;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4146")] - public async Task TestAccessibility_Property() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestAccessibility_Property() + => TestWithAllCodeStyleOptionsOffAsync( """ internal class Goo {} @@ -9253,12 +8841,10 @@ Goo I.MyProperty } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4146")] - public async Task TestAccessibility_Method_InaccessibleReturnType() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestAccessibility_Method_InaccessibleReturnType() + => TestWithAllCodeStyleOptionsOffAsync( """ internal class Goo {} @@ -9287,12 +8873,10 @@ Goo I.M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4146")] - public async Task TestAccessibility_Method_InaccessibleParameterType() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestAccessibility_Method_InaccessibleParameterType() + => TestWithAllCodeStyleOptionsOffAsync( """ internal class Goo {} @@ -9321,12 +8905,10 @@ void I.M(Goo goo) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4146")] - public async Task TestAccessibility_Event() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestAccessibility_Event() + => TestWithAllCodeStyleOptionsOffAsync( """ internal delegate void MyDelegate(); @@ -9363,12 +8945,10 @@ event MyDelegate I.Event } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4146")] - public async Task TestAccessibility_Indexer_InaccessibleReturnType() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestAccessibility_Indexer_InaccessibleReturnType() + => TestWithAllCodeStyleOptionsOffAsync( """ internal class Goo {} @@ -9400,12 +8980,10 @@ Goo I.this[int i] } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4146")] - public async Task TestAccessibility_Indexer_InaccessibleParameterType() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestAccessibility_Indexer_InaccessibleParameterType() + => TestWithAllCodeStyleOptionsOffAsync( """ internal class Goo {} @@ -9437,12 +9015,10 @@ int I.this[Goo goo] } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4146")] - public async Task TestAccessibility_InaccessibleMemberAsGenericArgument() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestAccessibility_InaccessibleMemberAsGenericArgument() + => TestWithAllCodeStyleOptionsOffAsync( """ using System.Collections.Generic; @@ -9475,12 +9051,10 @@ List I.M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4146")] - public async Task TestAccessibility_InaccessibleMemberDueToContainingType() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestAccessibility_InaccessibleMemberDueToContainingType() + => TestWithAllCodeStyleOptionsOffAsync( """ internal class Container { @@ -9515,12 +9089,10 @@ Container.Goo I.M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4146")] - public async Task TestAccessibility_InaccessibleGenericConstraintAsReturnType() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestAccessibility_InaccessibleGenericConstraintAsReturnType() + => TestWithAllCodeStyleOptionsOffAsync( """ internal class Goo {} @@ -9549,12 +9121,10 @@ T I.M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4146")] - public async Task TestAccessibility_InaccessibleGenericConstraintAsParameter() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestAccessibility_InaccessibleGenericConstraintAsParameter() + => TestWithAllCodeStyleOptionsOffAsync( """ internal class Goo {} @@ -9583,12 +9153,10 @@ void I.M(T arg) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4146")] - public async Task TestAccessibility_InaccessibleGenericConstraintWhichIsNotUsed() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestAccessibility_InaccessibleGenericConstraintWhichIsNotUsed() + => TestWithAllCodeStyleOptionsOffAsync( """ internal class Goo {} @@ -9617,12 +9185,10 @@ void I.M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4146")] - public async Task TestAccessibility_SeveralMembers_ShouldExplicitlyImplementOnlyInaccessible() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestAccessibility_SeveralMembers_ShouldExplicitlyImplementOnlyInaccessible() + => TestWithAllCodeStyleOptionsOffAsync( """ internal class Goo {} @@ -9658,12 +9224,10 @@ Goo I.M() } } """); - } [Fact] - public async Task TestInaccessibleAccessor_01() - { - await new VerifyCS.Test + public Task TestInaccessibleAccessor_01() + => new VerifyCS.Test { TestState = { @@ -9716,12 +9280,10 @@ public void Method1() // Specify the code action by equivalence key only to avoid trying to implement the interface explicitly with a second code fix pass. CodeActionEquivalenceKey = "False;False;True:global::IInterface;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); - } [Fact] - public async Task TestInaccessibleAccessor_02() - { - await new VerifyCS.Test + public Task TestInaccessibleAccessor_02() + => new VerifyCS.Test { TestState = { @@ -9772,12 +9334,10 @@ void IInterface.Method1() Options = { AllOptionsOff }, CodeActionIndex = 1, }.RunAsync(); - } [Fact] - public async Task TestInaccessibleAccessor_03() - { - await new VerifyCS.Test + public Task TestInaccessibleAccessor_03() + => new VerifyCS.Test { TestState = { @@ -9827,12 +9387,10 @@ abstract class Class : {|CS0535:{|CS0535:IInterface|}|} // Specify the code action by equivalence key only to avoid trying to execute a second code fix pass with a different action CodeActionEquivalenceKey = "False;True;True:global::IInterface;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); - } [Fact] - public async Task TestVirtualMember_01() - { - await new VerifyCS.Test + public Task TestVirtualMember_01() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = """ @@ -9867,12 +9425,10 @@ public void Method1() """, Options = { AllOptionsOff }, }.RunAsync(); - } [Fact] - public async Task TestVirtualMember_02() - { - await new VerifyCS.Test + public Task TestVirtualMember_02() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = """ @@ -9908,12 +9464,10 @@ void IInterface.Method1() Options = { AllOptionsOff }, CodeActionIndex = 1, }.RunAsync(); - } [Fact] - public async Task TestVirtualMember_03() - { - await new VerifyCS.Test + public Task TestVirtualMember_03() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = """ @@ -9946,12 +9500,10 @@ abstract class Class : IInterface Options = { AllOptionsOff }, CodeActionIndex = 1, }.RunAsync(); - } [Fact] - public async Task TestStaticMember_01() - { - await new VerifyCS.Test + public Task TestStaticMember_01() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = """ @@ -9990,12 +9542,10 @@ public void Method1() """, Options = { AllOptionsOff }, }.RunAsync(); - } [Fact] - public async Task TestStaticMember_02() - { - await new VerifyCS.Test + public Task TestStaticMember_02() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = """ @@ -10035,12 +9585,10 @@ void IInterface.Method1() Options = { AllOptionsOff }, CodeActionIndex = 1, }.RunAsync(); - } [Fact] - public async Task TestStaticMember_03() - { - await new VerifyCS.Test + public Task TestStaticMember_03() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = """ @@ -10077,12 +9625,10 @@ abstract class Class : IInterface Options = { AllOptionsOff }, CodeActionIndex = 1, }.RunAsync(); - } [Fact] - public async Task TestNotNullConstraint() - { - await TestInRegularAndScriptAsync( + public Task TestNotNullConstraint() + => TestInRegularAndScriptAsync( """ public interface ITest { @@ -10105,12 +9651,10 @@ public void M() where T : notnull } } """); - } [Fact] - public async Task TestWithNullableProperty() - { - await TestInRegularAndScriptAsync( + public Task TestWithNullableProperty() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -10134,7 +9678,6 @@ public class Test : ITest public string? P => throw new System.NotImplementedException(); } """); - } [Fact] public async Task TestWithNullablePropertyAlreadyImplemented() @@ -10156,9 +9699,8 @@ public class Test : ITest } [Fact] - public async Task TestWithNullableMethod() - { - await TestInRegularAndScriptAsync( + public Task TestWithNullableMethod() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -10185,14 +9727,10 @@ public class Test : ITest } } """); - } [Fact] - public async Task TestWithNullableEvent() - { - // Question whether this is needed, - // see https://github.com/dotnet/roslyn/issues/36673 - await TestInRegularAndScriptAsync( + public Task TestWithNullableEvent() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -10220,12 +9758,10 @@ public class Test : ITest public event EventHandler? SomeEvent; } """); - } [Fact] - public async Task TestWithNullableDisabled() - { - await TestInRegularAndScriptAsync( + public Task TestWithNullableDisabled() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -10255,12 +9791,10 @@ public class Test : ITest public string P => throw new System.NotImplementedException(); } """); - } [Fact] - public async Task GenericInterfaceNotNull1() - { - await new VerifyCS.Test + public Task GenericInterfaceNotNull1() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = """ @@ -10311,12 +9845,10 @@ public int Baz([AllowNull] int bar) } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/13427")] - public async Task TestDoNotAddNewWithGenericAndNonGenericMethods() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestDoNotAddNewWithGenericAndNonGenericMethods() + => TestWithAllCodeStyleOptionsOffAsync( """ class B { @@ -10351,12 +9883,10 @@ public void M() } } """); - } [Fact] - public async Task ImplementRemainingExplicitlyWhenPartiallyImplemented() - { - await TestInRegularAndScriptAsync(""" + public Task ImplementRemainingExplicitlyWhenPartiallyImplemented() + => TestInRegularAndScriptAsync(""" interface I { void M1(); @@ -10385,12 +9915,10 @@ void I.M2() } } """, codeAction: ("True;False;True:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 2)); - } [Fact] - public async Task ImplementInitOnlyProperty() - { - await new VerifyCS.Test + public Task ImplementInitOnlyProperty() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.CSharp9, @@ -10416,7 +9944,6 @@ class C : I } """, }.RunAsync(); - } [Fact] public async Task ImplementRemainingExplicitlyMissingWhenAllImplemented() @@ -10439,9 +9966,10 @@ public void M2(){} } [Fact] - public async Task ImplementRemainingExplicitlyMissingWhenAllImplementedAreExplicit() - { - var code = """ + public Task ImplementRemainingExplicitlyMissingWhenAllImplementedAreExplicit() + => new VerifyCS.Test + { + TestCode = """ interface I { void M1(); @@ -10452,8 +9980,8 @@ class C : {|CS0535:I|} { void I.M1(){} } - """; - var fixedCode = """ + """, + FixedCode = """ interface I { void M1(); @@ -10469,20 +9997,13 @@ public void M2() void I.M1(){} } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionsVerifier = codeActions => Assert.Equal(2, codeActions.Length), }.RunAsync(); - } [Fact] - public async Task TestImplementRemainingExplicitlyNonPublicMember() - { - await TestInRegularAndScriptAsync(""" + public Task TestImplementRemainingExplicitlyNonPublicMember() + => TestInRegularAndScriptAsync(""" interface I { void M1(); @@ -10511,12 +10032,10 @@ void I.M2() } } """, codeAction: ("True;False;True:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48295")] - public async Task TestImplementOnRecord_WithSemiColon() - { - await new VerifyCS.Test + public Task TestImplementOnRecord_WithSemiColon() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.CSharp12, @@ -10544,12 +10063,10 @@ public void M1() """, }.RunAsync(); - } [Fact] - public async Task TestImplementOnClass_WithSemiColon() - { - await new VerifyCS.Test + public Task TestImplementOnClass_WithSemiColon() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.CSharp12, @@ -10577,12 +10094,10 @@ public void M1() """, }.RunAsync(); - } [Fact] - public async Task TestImplementOnStruct_WithSemiColon() - { - await new VerifyCS.Test + public Task TestImplementOnStruct_WithSemiColon() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.CSharp12, @@ -10610,12 +10125,10 @@ public void M1() """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48295")] - public async Task TestImplementOnRecord_WithBracesAndTrivia() - { - await new VerifyCS.Test + public Task TestImplementOnRecord_WithBracesAndTrivia() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.CSharp12, @@ -10642,7 +10155,6 @@ public void M1() } // hello """, }.RunAsync(); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/48295")] [InlineData("record")] @@ -10650,41 +10162,42 @@ public void M1() [InlineData("record struct")] [InlineData("class")] [InlineData("struct")] - public async Task TestImplementOnRecord_WithSemiColonAndTrivia(string record) - { - await new VerifyCS.Test + public Task TestImplementOnRecord_WithSemiColonAndTrivia(string record) + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.CSharp12, - TestCode = $@" -interface I -{{ - void M1(); -}} - -{record} C : {{|CS0535:I|}}; // hello -", - FixedCode = $@" -interface I -{{ - void M1(); -}} - -{record} C : {{|CS0535:I|}} // hello -{{ - public void M1() - {{ - throw new System.NotImplementedException(); - }} -}} -", + TestCode = $$""" + + interface I + { + void M1(); + } + + {{record}} C : {|CS0535:I|}; // hello + + """, + FixedCode = $$""" + + interface I + { + void M1(); + } + + {{record}} C : {|CS0535:I|} // hello + { + public void M1() + { + throw new System.NotImplementedException(); + } + } + + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49019")] - public async Task TestUnconstrainedGenericInstantiatedWithValueType() - { - await new VerifyCS.Test + public Task TestUnconstrainedGenericInstantiatedWithValueType() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp9, TestCode = """ @@ -10714,12 +10227,10 @@ public void Bar(int x) } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49019")] - public async Task TestConstrainedGenericInstantiatedWithValueType() - { - await TestInRegularAndScriptAsync(""" + public Task TestConstrainedGenericInstantiatedWithValueType() + => TestInRegularAndScriptAsync(""" interface IGoo where T : struct { void Bar(T? x); @@ -10743,12 +10254,10 @@ public void Bar(int? x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49019")] - public async Task TestUnconstrainedGenericInstantiatedWithReferenceType() - { - await new VerifyCS.Test + public Task TestUnconstrainedGenericInstantiatedWithReferenceType() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp9, TestCode = """ @@ -10780,12 +10289,10 @@ public void Bar(string x) } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49019")] - public async Task TestUnconstrainedGenericInstantiatedWithReferenceType_NullableEnable() - { - await new VerifyCS.Test + public Task TestUnconstrainedGenericInstantiatedWithReferenceType_NullableEnable() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp9, TestCode = """ @@ -10817,12 +10324,10 @@ public void Bar(string? x) } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49019")] - public async Task TestConstrainedGenericInstantiatedWithReferenceType() - { - await new VerifyCS.Test + public Task TestConstrainedGenericInstantiatedWithReferenceType() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp9, TestCode = """ @@ -10852,12 +10357,10 @@ public void Bar(string? x) } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49019")] - public async Task TestConstrainedGenericInstantiatedWithReferenceType_NullableEnable() - { - await TestInRegularAndScriptAsync(""" + public Task TestConstrainedGenericInstantiatedWithReferenceType_NullableEnable() + => TestInRegularAndScriptAsync(""" #nullable enable interface IGoo where T : class @@ -10885,12 +10388,10 @@ public void Bar(string? x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53012")] - public async Task TestNullableTypeParameter() - { - await TestInRegularAndScriptAsync( + public Task TestNullableTypeParameter() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -10919,12 +10420,10 @@ public void M(T1? a, T2 b, T1? c, T3? d) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53012")] - public async Task TestNullableTypeParameter_ExplicitInterfaceImplementation() - { - await TestInRegularAndScriptAsync( + public Task TestNullableTypeParameter_ExplicitInterfaceImplementation() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -10955,12 +10454,10 @@ void I.M(T1? a, T2 b, T1? c, T3? d) } } """, codeAction: ("True;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53012")] - public async Task TestNullableTypeParameter_ExplicitInterfaceImplementationWithClassConstraint() - { - await TestInRegularAndScriptAsync( + public Task TestNullableTypeParameter_ExplicitInterfaceImplementationWithClassConstraint() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -10991,12 +10488,10 @@ void I.M(T1? a, T2 b, T1? c, T3? d) } } """, codeAction: ("True;False;False:global::I;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51779")] - public async Task TestImplementTwoPropertiesOfCSharp5() - { - await new VerifyCS.Test + public Task TestImplementTwoPropertiesOfCSharp5() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp5, TestCode = """ @@ -11037,12 +10532,10 @@ public int Foo } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53925")] - public async Task TestStaticAbstractInterfaceMember() - { - await new VerifyCS.Test + public Task TestStaticAbstractInterfaceMember() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12, @@ -11072,12 +10565,10 @@ public static void M1() """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(CodeFixesResources.Implement_interface, codeAction.Title), }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53925")] - public async Task TestStaticAbstractInterfaceMemberExplicitly() - { - await new VerifyCS.Test + public Task TestStaticAbstractInterfaceMemberExplicitly() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12, @@ -11108,12 +10599,10 @@ static void ITest.M1() CodeActionVerifier = (codeAction, verifier) => verifier.Equal(CodeFixesResources.Implement_all_members_explicitly, codeAction.Title), CodeActionIndex = 1, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53925")] - public async Task TestStaticAbstractInterfaceMember_ImplementAbstractly() - { - await new VerifyCS.Test + public Task TestStaticAbstractInterfaceMember_ImplementAbstractly() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12, @@ -11144,12 +10633,10 @@ public static void M1() CodeActionVerifier = (codeAction, verifier) => verifier.Equal(CodeFixesResources.Implement_interface_abstractly, codeAction.Title), CodeActionIndex = 1, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53927")] - public async Task TestStaticAbstractInterfaceOperator_OnlyExplicitlyImplementable() - { - await new VerifyCS.Test + public Task TestStaticAbstractInterfaceOperator_OnlyExplicitlyImplementable() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12, @@ -11177,12 +10664,10 @@ class C : ITest """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(CodeFixesResources.Implement_all_members_explicitly, codeAction.Title), }.RunAsync(); - } [Fact] - public async Task TestStaticAbstractInterfaceUnsigneRightShiftOperator_OnlyExplicitlyImplementable() - { - await new VerifyCS.Test + public Task TestStaticAbstractInterfaceUnsigneRightShiftOperator_OnlyExplicitlyImplementable() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12, @@ -11210,12 +10695,10 @@ class C : ITest """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(CodeFixesResources.Implement_all_members_explicitly, codeAction.Title), }.RunAsync(); - } [Theory, CombinatorialData] - public async Task TestInstanceIncrementOperator_ImplementExplicitly([CombinatorialValues("++", "--")] string op) - { - await new VerifyCS.Test + public Task TestInstanceIncrementOperator_ImplementExplicitly([CombinatorialValues("++", "--")] string op) + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.Preview, @@ -11244,12 +10727,10 @@ class C : ITest CodeActionVerifier = (codeAction, verifier) => verifier.Equal(CodeFixesResources.Implement_all_members_explicitly, codeAction.Title), CodeActionIndex = 1, }.RunAsync(); - } [Theory, CombinatorialData] - public async Task TestInstanceCompoundAssignmentOperator_ImplementExplicitly([CombinatorialValues("+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", ">>>=")] string op) - { - await new VerifyCS.Test + public Task TestInstanceCompoundAssignmentOperator_ImplementExplicitly([CombinatorialValues("+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", ">>>=")] string op) + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.Preview, @@ -11278,12 +10759,10 @@ class C : ITest CodeActionVerifier = (codeAction, verifier) => verifier.Equal(CodeFixesResources.Implement_all_members_explicitly, codeAction.Title), CodeActionIndex = 1, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53927")] - public async Task TestStaticAbstractInterfaceOperator_ImplementImplicitly() - { - await new VerifyCS.Test + public Task TestStaticAbstractInterfaceOperator_ImplementImplicitly() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12, @@ -11318,12 +10797,10 @@ class C : ITest """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(CodeFixesResources.Implement_interface, codeAction.Title), }.RunAsync(); - } [Fact] - public async Task TestStaticAbstractInterfaceUnsignedRightShiftOperator_ImplementImplicitly() - { - await new VerifyCS.Test + public Task TestStaticAbstractInterfaceUnsignedRightShiftOperator_ImplementImplicitly() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12, @@ -11351,13 +10828,11 @@ class C : ITest """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(CodeFixesResources.Implement_interface, codeAction.Title), }.RunAsync(); - } [Theory] [CombinatorialData] - public async Task TestInstanceIncrementOperator_ImplementImplicitly([CombinatorialValues("++", "--")] string op) - { - await new VerifyCS.Test + public Task TestInstanceIncrementOperator_ImplementImplicitly([CombinatorialValues("++", "--")] string op) + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.Preview, @@ -11387,13 +10862,11 @@ class C : ITest CodeActionEquivalenceKey = "False;False;True:global::ITest;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 0, }.RunAsync(); - } [Theory] [CombinatorialData] - public async Task TestInstanceCompoundAssignmentOperator_ImplementImplicitly([CombinatorialValues("+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", ">>>=")] string op) - { - await new VerifyCS.Test + public Task TestInstanceCompoundAssignmentOperator_ImplementImplicitly([CombinatorialValues("+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", ">>>=")] string op) + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.Preview, @@ -11423,12 +10896,10 @@ class C : ITest CodeActionEquivalenceKey = "False;False;True:global::ITest;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 0, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53927")] - public async Task TestStaticAbstractInterfaceOperator_ImplementExplicitly() - { - await new VerifyCS.Test + public Task TestStaticAbstractInterfaceOperator_ImplementExplicitly() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12, @@ -11457,12 +10928,10 @@ class C : ITest CodeActionVerifier = (codeAction, verifier) => verifier.Equal(CodeFixesResources.Implement_all_members_explicitly, codeAction.Title), CodeActionIndex = 1, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53927")] - public async Task TestStaticAbstractInterfaceOperator_ImplementAbstractly() - { - await new VerifyCS.Test + public Task TestStaticAbstractInterfaceOperator_ImplementAbstractly() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12, @@ -11492,12 +10961,10 @@ abstract class C : ITest CodeActionIndex = 1, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53927")] - public async Task TestStaticAbstractInterface_Explicitly() - { - await new VerifyCS.Test + public Task TestStaticAbstractInterface_Explicitly() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12, @@ -11527,12 +10994,10 @@ static int ITest.M(ITest x) CodeActionIndex = 1, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53927")] - public async Task TestStaticAbstractInterface_Implicitly() - { - await new VerifyCS.Test + public Task TestStaticAbstractInterface_Implicitly() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12, @@ -11560,12 +11025,10 @@ public static int M(ITest x) """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(CodeFixesResources.Implement_interface, codeAction.Title), }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53927")] - public async Task TestStaticAbstractInterface_ImplementImplicitly() - { - await new VerifyCS.Test + public Task TestStaticAbstractInterface_ImplementImplicitly() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12, @@ -11593,12 +11056,10 @@ public static int M(C x) """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(CodeFixesResources.Implement_interface, codeAction.Title), }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53927")] - public async Task TestStaticAbstractInterface_ImplementExplicitly() - { - await new VerifyCS.Test + public Task TestStaticAbstractInterface_ImplementExplicitly() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12, @@ -11628,12 +11089,10 @@ static int ITest.M(C x) CodeActionIndex = 1, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53927")] - public async Task TestStaticAbstractInterface_ImplementAbstractly() - { - await new VerifyCS.Test + public Task TestStaticAbstractInterface_ImplementAbstractly() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12, @@ -11663,12 +11122,10 @@ public static int M(C x) CodeActionIndex = 1, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60214")] - public async Task TestImplementCheckedOperators_Explicitly() - { - await new VerifyCS.Test + public Task TestImplementCheckedOperators_Explicitly() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12, @@ -11738,12 +11195,10 @@ static explicit I1.operator string(C3 x) CodeActionVerifier = (codeAction, verifier) => verifier.Equal(CodeFixesResources.Implement_all_members_explicitly, codeAction.Title), CodeActionIndex = 1, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60214")] - public async Task TestImplementCheckedOperators_Implicitly() - { - await new VerifyCS.Test + public Task TestImplementCheckedOperators_Implicitly() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12, @@ -11812,12 +11267,10 @@ public static explicit operator string(C3 x) """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(CodeFixesResources.Implement_interface, codeAction.Title), }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60214")] - public async Task TestImplementCheckedOperators_Abstractly() - { - await new VerifyCS.Test + public Task TestImplementCheckedOperators_Abstractly() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12, @@ -11887,12 +11340,10 @@ public static explicit operator string(C3 x) CodeActionVerifier = (codeAction, verifier) => verifier.Equal(CodeFixesResources.Implement_interface_abstractly, codeAction.Title), CodeActionIndex = 1, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34580")] - public async Task TestSupportedConstraints1() - { - await new VerifyCS.Test + public Task TestSupportedConstraints1() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp7_3, TestCode = @@ -11926,12 +11377,10 @@ public void TestEnum(T value) where T : Enum } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34580")] - public async Task TestSupportedConstraints2() - { - await new VerifyCS.Test + public Task TestSupportedConstraints2() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp7_2, TestCode = @@ -11965,12 +11414,10 @@ void ITest.TestEnum(T value) } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58136")] - public async Task TestStaticAbstractMembers1() - { - await new VerifyCS.Test + public Task TestStaticAbstractMembers1() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12, @@ -12027,12 +11474,10 @@ static void I.M() """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(CodeFixesResources.Implement_all_members_explicitly, codeAction.Title), }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37374")] - public async Task TestRefReadonly1() - { - await new VerifyCS.Test + public Task TestRefReadonly1() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net60, TestCode = @@ -12083,13 +11528,12 @@ IEnumerator IEnumerable.GetEnumerator() } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70232")] - public async Task TestMissingWhenAlreadyContainingImpl() - { - var code = - """ + public Task TestMissingWhenAlreadyContainingImpl() + => new VerifyCS.Test + { + TestCode = """ interface I { event System.EventHandler Click; @@ -12102,10 +11546,7 @@ event System.EventHandler I.Click { add { } remove { } } event System.EventHandler I.Click } - """; - await new VerifyCS.Test - { - TestCode = code, + """, //LanguageVersion = LanguageVersion.CSharp12, ExpectedDiagnostics = { @@ -12114,12 +11555,10 @@ event System.EventHandler I.Click DiagnosticResult.CompilerError("CS0102").WithSpan(10, 33, 10, 38) } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61263")] - public async Task ImplementStaticConversionsExplicitly() - { - await new VerifyCS.Test + public Task ImplementStaticConversionsExplicitly() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net80, LanguageVersion = LanguageVersion.CSharp12, @@ -12157,12 +11596,10 @@ static explicit I11.operator int(C11 x) CodeActionIndex = 1, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(CodeFixesResources.Implement_all_members_explicitly, codeAction.Title), }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67023")] - public async Task TestIEnumerable1() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestIEnumerable1() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; using System.Collections; @@ -12190,12 +11627,10 @@ IEnumerator IEnumerable.GetEnumerator() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67023")] - public async Task TestIEnumerable2() - { - await TestWithAllCodeStyleOptionsOffAsync( + public Task TestIEnumerable2() + => TestWithAllCodeStyleOptionsOffAsync( """ using System; using System.Collections; @@ -12244,12 +11679,10 @@ public void Reset() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67023")] - public async Task TestIEnumerable3() - { - await TestWithAllCodeStyleOptionsOnAsync( + public Task TestIEnumerable3() + => TestWithAllCodeStyleOptionsOnAsync( """ using System; using System.Collections; @@ -12275,12 +11708,10 @@ class Class : IEnumerator public void Reset() => throw new NotImplementedException(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72380")] - public async Task TestImplementProtectedAbstract_CSharp9() - { - await new VerifyCS.Test + public Task TestImplementProtectedAbstract_CSharp9() + => new VerifyCS.Test { TestCode = """ using System; @@ -12320,12 +11751,10 @@ void I.Method() ReferenceAssemblies = ReferenceAssemblies.Net.Net80, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72380")] - public async Task TestImplementProtectedAbstract_CSharp10() - { - await new VerifyCS.Test + public Task TestImplementProtectedAbstract_CSharp10() + => new VerifyCS.Test { TestCode = """ using System; @@ -12365,12 +11794,10 @@ public void Method() ReferenceAssemblies = ReferenceAssemblies.Net.Net80, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19721")] - public async Task TestMatchPropertyAgainstPropertyWithMoreAccessors1() - { - await TestWithAllCodeStyleOptionsOnAsync( + public Task TestMatchPropertyAgainstPropertyWithMoreAccessors1() + => TestWithAllCodeStyleOptionsOnAsync( """ interface ImmutableView { @@ -12396,12 +11823,10 @@ class Implementation : MutableView public int Prop1 { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78281")] - public async Task TestImplementInstanceAssignmentOperator1() - { - await new VerifyCS.Test + public Task TestImplementInstanceAssignmentOperator1() + => new VerifyCS.Test { TestCode = """ interface I1 @@ -12439,12 +11864,10 @@ class C1 : I1 ReferenceAssemblies = ReferenceAssemblies.Net.Net80, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78281")] - public async Task TestImplementInstanceAssignmentOperator2() - { - await new VerifyCS.Test + public Task TestImplementInstanceAssignmentOperator2() + => new VerifyCS.Test { TestCode = """ interface I1 @@ -12483,5 +11906,4 @@ class C1 : I1 ReferenceAssemblies = ReferenceAssemblies.Net.Net80, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/ImplementInterface/ImplementInterfaceTests_FixAllTests.cs b/src/Analyzers/CSharp/Tests/ImplementInterface/ImplementInterfaceTests_FixAllTests.cs index 5ae2f82b98863..761d785b2eaf6 100644 --- a/src/Analyzers/CSharp/Tests/ImplementInterface/ImplementInterfaceTests_FixAllTests.cs +++ b/src/Analyzers/CSharp/Tests/ImplementInterface/ImplementInterfaceTests_FixAllTests.cs @@ -22,9 +22,8 @@ public sealed class ImplementInterfaceTests_FixAllTests [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInDocument() - { - await new VerifyCS.Test + public Task TestFixAllInDocument() + => new VerifyCS.Test { TestState = { @@ -159,14 +158,12 @@ class C2 : {|CS0535:I1|}, {|CS0535:I2|} CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne | CodeFixTestBehaviors.SkipFixAllInProjectCheck | CodeFixTestBehaviors.SkipFixAllInSolutionCheck, CodeActionEquivalenceKey = "False;False;True:global::I1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); - } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInProject() - { - await new VerifyCS.Test + public Task TestFixAllInProject() + => new VerifyCS.Test { TestState = { @@ -310,14 +307,12 @@ public void F1() CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne | CodeFixTestBehaviors.SkipFixAllInDocumentCheck | CodeFixTestBehaviors.SkipFixAllInSolutionCheck, CodeActionEquivalenceKey = "False;False;True:global::I1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); - } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInSolution() - { - await new VerifyCS.Test + public Task TestFixAllInSolution() + => new VerifyCS.Test { TestState = { @@ -490,14 +485,12 @@ void I2.F1() CodeActionEquivalenceKey = "True;False;False:global::I2;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); - } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInSolution_DifferentAssemblyWithSameTypeName() - { - await new VerifyCS.Test + public Task TestFixAllInSolution_DifferentAssemblyWithSameTypeName() + => new VerifyCS.Test { TestState = { @@ -688,7 +681,6 @@ void I2.F1() CodeActionEquivalenceKey = "True;False;False:global::I2;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); - } #endregion } diff --git a/src/Analyzers/CSharp/Tests/InlineDeclaration/CSharpInlineDeclarationTests.cs b/src/Analyzers/CSharp/Tests/InlineDeclaration/CSharpInlineDeclarationTests.cs index 64fbebc9dafa3..b267491564a50 100644 --- a/src/Analyzers/CSharp/Tests/InlineDeclaration/CSharpInlineDeclarationTests.cs +++ b/src/Analyzers/CSharp/Tests/InlineDeclaration/CSharpInlineDeclarationTests.cs @@ -39,9 +39,8 @@ private OptionsCollection ExplicitTypeEverywhere() }; [Fact] - public async Task InlineVariable1() - { - await TestInRegularAndScript1Async( + public Task InlineVariable1() + => TestInRegularAndScript1Async( """ class C { @@ -65,12 +64,10 @@ void M() } } """); - } [Fact] - public async Task InlineInNestedCall() - { - await TestInRegularAndScript1Async( + public Task InlineInNestedCall() + => TestInRegularAndScript1Async( """ class C { @@ -94,12 +91,10 @@ void M() } } """); - } [Fact] - public async Task InlineVariableWithConstructor1() - { - await TestInRegularAndScript1Async( + public Task InlineVariableWithConstructor1() + => TestInRegularAndScript1Async( """ class C1 { @@ -127,12 +122,10 @@ void M(int v) } } """); - } [Fact] - public async Task InlineVariableMissingWithIndexer1() - { - await TestMissingInRegularAndScriptAsync( + public Task InlineVariableMissingWithIndexer1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -145,12 +138,10 @@ void M() } } """); - } [Fact] - public async Task InlineVariableIntoFirstOut1() - { - await TestInRegularAndScript1Async( + public Task InlineVariableIntoFirstOut1() + => TestInRegularAndScript1Async( """ class C { @@ -174,12 +165,10 @@ void M() } } """); - } [Fact] - public async Task InlineVariableIntoFirstOut2() - { - await TestInRegularAndScript1Async( + public Task InlineVariableIntoFirstOut2() + => TestInRegularAndScript1Async( """ class C { @@ -211,12 +200,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingInCSharp6() - { - await TestMissingAsync( + public Task TestMissingInCSharp6() + => TestMissingAsync( """ class C { @@ -229,12 +216,10 @@ void M() } } """, new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); - } [Fact] - public async Task InlineVariablePreferVar1() - { - await TestInRegularAndScript1Async( + public Task InlineVariablePreferVar1() + => TestInRegularAndScript1Async( """ class C { @@ -258,12 +243,10 @@ void M(string v) } } """, new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeEverywhere())); - } [Fact] - public async Task InlineVariablePreferVarExceptForPredefinedTypes1() - { - await TestInRegularAndScript1Async( + public Task InlineVariablePreferVarExceptForPredefinedTypes1() + => TestInRegularAndScript1Async( """ class C { @@ -287,12 +270,10 @@ void M(string v) } } """, new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeButKeepIntrinsics())); - } [Fact] - public async Task TestAvailableWhenWrittenAfter1() - { - await TestInRegularAndScript1Async( + public Task TestAvailableWhenWrittenAfter1() + => TestInRegularAndScript1Async( """ class C { @@ -320,12 +301,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingWhenWrittenBetween1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWhenWrittenBetween1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -339,12 +318,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingWhenReadBetween1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWhenReadBetween1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -362,12 +339,10 @@ void M1(int i) } } """); - } [Fact] - public async Task TestMissingWithComplexInitializer() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWithComplexInitializer() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -384,12 +359,10 @@ int M1() } } """); - } [Fact] - public async Task TestAvailableInOuterScopeIfNotWrittenOutside() - { - await TestMissingInRegularAndScriptAsync( + public Task TestAvailableInOuterScopeIfNotWrittenOutside() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -406,12 +379,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingIfWrittenAfterInOuterScope() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingIfWrittenAfterInOuterScope() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -428,12 +399,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingIfWrittenBetweenInOuterScope() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingIfWrittenBetweenInOuterScope() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -449,12 +418,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingInNonOut() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingInNonOut() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -467,12 +434,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingInField() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingInField() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -486,12 +451,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingInField2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingInField2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -505,12 +468,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingInNonLocalStatement() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingInNonLocalStatement() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -525,12 +486,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingInEmbeddedStatementWithWriteAfterwards() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingInEmbeddedStatementWithWriteAfterwards() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -546,12 +505,10 @@ void M() } } """); - } [Fact] - public async Task TestInEmbeddedStatement() - { - await TestInRegularAndScript1Async( + public Task TestInEmbeddedStatement() + => TestInRegularAndScript1Async( """ class C { @@ -579,12 +536,10 @@ void M() } } """); - } [Fact] - public async Task TestAvailableInNestedBlock() - { - await TestInRegularAndScript1Async( + public Task TestAvailableInNestedBlock() + => TestInRegularAndScript1Async( """ class C { @@ -614,12 +569,10 @@ void M() } } """); - } [Fact] - public async Task TestOverloadResolutionDoNotUseVar1() - { - await TestInRegularAndScript1Async( + public Task TestOverloadResolutionDoNotUseVar1() + => TestInRegularAndScript1Async( """ class C { @@ -659,12 +612,10 @@ void M2(out string s) } } """, new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeEverywhere())); - } [Fact] - public async Task TestOverloadResolutionDoNotUseVar2() - { - await TestInRegularAndScript1Async( + public Task TestOverloadResolutionDoNotUseVar2() + => TestInRegularAndScript1Async( """ class C { @@ -704,12 +655,10 @@ void M2(out string s) } } """, new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeEverywhere())); - } [Fact] - public async Task TestGenericInferenceDoNotUseVar3() - { - await TestInRegularAndScript1Async( + public Task TestGenericInferenceDoNotUseVar3() + => TestInRegularAndScript1Async( """ class C { @@ -741,12 +690,10 @@ void M2(out T i) } } """, new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeEverywhere())); - } [Fact] - public async Task TestComments1() - { - await TestInRegularAndScript1Async( + public Task TestComments1() + => TestInRegularAndScript1Async( """ class C { @@ -776,12 +723,10 @@ void M() } } """); - } [Fact] - public async Task TestComments2() - { - await TestInRegularAndScript1Async( + public Task TestComments2() + => TestInRegularAndScript1Async( """ class C { @@ -810,12 +755,10 @@ void M() } } """); - } [Fact] - public async Task TestComments3() - { - await TestInRegularAndScript1Async( + public Task TestComments3() + => TestInRegularAndScript1Async( """ class C { @@ -846,12 +789,10 @@ void M() } } """); - } [Fact] - public async Task TestComments4() - { - await TestInRegularAndScript1Async( + public Task TestComments4() + => TestInRegularAndScript1Async( """ class C { @@ -880,12 +821,10 @@ void M() } } """); - } [Fact] - public async Task TestComments5() - { - await TestInRegularAndScript1Async( + public Task TestComments5() + => TestInRegularAndScript1Async( """ class C { @@ -914,12 +853,10 @@ void M() } } """); - } [Fact] - public async Task TestComments6() - { - await TestInRegularAndScript1Async( + public Task TestComments6() + => TestInRegularAndScript1Async( """ class C { @@ -948,12 +885,10 @@ void M() } } """); - } [Fact] - public async Task TestComments7() - { - await TestInRegularAndScript1Async( + public Task TestComments7() + => TestInRegularAndScript1Async( """ class C { @@ -982,12 +917,10 @@ void M() } } """); - } [Fact] - public async Task TestComments8() - { - await TestInRegularAndScript1Async( + public Task TestComments8() + => TestInRegularAndScript1Async( """ class C { @@ -1018,12 +951,10 @@ void M() } } """); - } [Fact] - public async Task TestComments9() - { - await TestInRegularAndScript1Async( + public Task TestComments9() + => TestInRegularAndScript1Async( """ class C { @@ -1055,12 +986,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15994")] - public async Task TestCommentsTrivia1() - { - await TestInRegularAndScript1Async( + public Task TestCommentsTrivia1() + => TestInRegularAndScript1Async( """ using System; @@ -1094,12 +1023,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15994")] - public async Task TestCommentsTrivia2() - { - await TestInRegularAndScript1Async( + public Task TestCommentsTrivia2() + => TestInRegularAndScript1Async( """ using System; @@ -1149,12 +1076,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15336")] - public async Task TestNotMissingIfCapturedInLambdaAndNotUsedAfterwards() - { - await TestInRegularAndScript1Async( + public Task TestNotMissingIfCapturedInLambdaAndNotUsedAfterwards() + => TestInRegularAndScript1Async( """ using System; @@ -1186,12 +1111,10 @@ void Baz(out string s) { } void Bar(Action a) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15336")] - public async Task TestMissingIfCapturedInLambdaAndUsedAfterwards() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingIfCapturedInLambdaAndUsedAfterwards() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1209,12 +1132,10 @@ void Baz(out string s) { } void Bar(Action a) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15408")] - public async Task TestDataFlow1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestDataFlow1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1235,12 +1156,10 @@ private bool TryBaz(out object s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15408")] - public async Task TestDataFlow2() - { - await TestInRegularAndScript1Async( + public Task TestDataFlow2() + => TestInRegularAndScript1Async( """ using System; @@ -1280,12 +1199,10 @@ private bool TryBaz(out object s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16028")] - public async Task TestExpressionTree1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestExpressionTree1() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Linq.Expressions; @@ -1309,12 +1226,10 @@ public static void Method(Expression expression) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16198")] - public async Task TestIndentation1() - { - await TestInRegularAndScript1Async( + public Task TestIndentation1() + => TestInRegularAndScript1Async( """ using System; @@ -1344,12 +1259,10 @@ private int Bar() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17624")] - public async Task TestNotInLoops1() - { - await TestMissingAsync( + public Task TestNotInLoops1() + => TestMissingAsync( """ using System; @@ -1372,12 +1285,10 @@ private static bool TryExtractTokenFromEmail(out string token) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17624")] - public async Task TestNotInLoops2() - { - await TestMissingAsync( + public Task TestNotInLoops2() + => TestMissingAsync( """ using System; @@ -1399,12 +1310,10 @@ private static bool TryExtractTokenFromEmail(out string token) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17624")] - public async Task TestNotInLoops3() - { - await TestMissingAsync( + public Task TestNotInLoops3() + => TestMissingAsync( """ using System; using System.Collections.Generic; @@ -1427,12 +1336,10 @@ private static IEnumerable TryExtractTokenFromEmail(out string token) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17624")] - public async Task TestNotInLoops4() - { - await TestMissingAsync( + public Task TestNotInLoops4() + => TestMissingAsync( """ using System; using System.Collections.Generic; @@ -1455,12 +1362,10 @@ private static bool TryExtractTokenFromEmail(out string token) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18076")] - public async Task TestNotInUsing() - { - await TestMissingAsync( + public Task TestNotInUsing() + => TestMissingAsync( """ using System; @@ -1482,12 +1387,10 @@ private static IDisposable GetDisposableAndValue(out string token) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18076")] - public async Task TestNotInExceptionFilter() - { - await TestMissingAsync( + public Task TestNotInExceptionFilter() + => TestMissingAsync( """ using System; @@ -1512,12 +1415,10 @@ private static bool GetValue(out string token) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18076")] - public async Task TestNotInShortCircuitExpression1() - { - await TestMissingAsync( + public Task TestNotInShortCircuitExpression1() + => TestMissingAsync( """ using System; @@ -1536,12 +1437,10 @@ private static bool GetValue(out string token) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18076")] - public async Task TestNotInShortCircuitExpression2() - { - await TestMissingAsync( + public Task TestNotInShortCircuitExpression2() + => TestMissingAsync( """ using System; @@ -1560,12 +1459,10 @@ private static bool GetValue(out string token) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18076")] - public async Task TestNotInFixed() - { - await TestMissingAsync( + public Task TestNotInFixed() + => TestMissingAsync( """ using System; @@ -1587,12 +1484,10 @@ private static int[] GetValue(out string token) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17624")] - public async Task TestInLoops1() - { - await TestInRegularAndScript1Async( + public Task TestInLoops1() + => TestInRegularAndScript1Async( """ using System; @@ -1632,12 +1527,10 @@ private static bool TryExtractTokenFromEmail(out string token) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17624")] - public async Task TestInLoops2() - { - await TestInRegularAndScript1Async( + public Task TestInLoops2() + => TestInRegularAndScript1Async( """ using System; @@ -1675,12 +1568,10 @@ private static bool TryExtractTokenFromEmail(out string token) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17624")] - public async Task TestInLoops3() - { - await TestInRegularAndScript1Async( + public Task TestInLoops3() + => TestInRegularAndScript1Async( """ using System; using System.Collections.Generic; @@ -1720,12 +1611,10 @@ private static IEnumerable TryExtractTokenFromEmail(out string token) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17624")] - public async Task TestInLoops4() - { - await TestInRegularAndScript1Async( + public Task TestInLoops4() + => TestInRegularAndScript1Async( """ using System; using System.Collections.Generic; @@ -1765,12 +1654,10 @@ private static bool TryExtractTokenFromEmail(out string token) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18076")] - public async Task TestInUsing() - { - await TestInRegularAndScript1Async( + public Task TestInUsing() + => TestInRegularAndScript1Async( """ using System; @@ -1808,12 +1695,10 @@ private static IDisposable GetDisposableAndValue(out string token) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18076")] - public async Task TestInExceptionFilter() - { - await TestInRegularAndScript1Async( + public Task TestInExceptionFilter() + => TestInRegularAndScript1Async( """ using System; @@ -1857,12 +1742,10 @@ private static bool GetValue(out string token) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18076")] - public async Task TestInShortCircuitExpression1() - { - await TestInRegularAndScript1Async( + public Task TestInShortCircuitExpression1() + => TestInRegularAndScript1Async( """ using System; @@ -1896,12 +1779,10 @@ private static bool GetValue(out string token) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18076")] - public async Task TestInShortCircuitExpression2() - { - await TestInRegularAndScript1Async( + public Task TestInShortCircuitExpression2() + => TestInRegularAndScript1Async( """ using System; @@ -1935,12 +1816,10 @@ private static bool GetValue(out string token) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18076")] - public async Task TestInFixed() - { - await TestInRegularAndScript1Async( + public Task TestInFixed() + => TestInRegularAndScript1Async( """ using System; @@ -1978,12 +1857,10 @@ private static int[] GetValue(out string token) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17743")] - public async Task TestInLocalFunction1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestInLocalFunction1() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -2006,12 +1883,10 @@ void F() } } """); - } [Fact] - public async Task TestInLocalFunction2() - { - await TestInRegularAndScript1Async( + public Task TestInLocalFunction2() + => TestInRegularAndScript1Async( """ using System; using System.Collections.Generic; @@ -2055,12 +1930,10 @@ void F() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16676")] - public async Task TestMultipleDeclarationStatementsOnSameLine1() - { - await TestInRegularAndScript1Async( + public Task TestMultipleDeclarationStatementsOnSameLine1() + => TestInRegularAndScript1Async( """ class C { @@ -2081,12 +1954,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16676")] - public async Task TestMultipleDeclarationStatementsOnSameLine2() - { - await TestInRegularAndScript1Async( + public Task TestMultipleDeclarationStatementsOnSameLine2() + => TestInRegularAndScript1Async( """ class C { @@ -2107,12 +1978,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16676")] - public async Task TestMultipleDeclarationStatementsOnSameLine3() - { - await TestInRegularAndScript1Async( + public Task TestMultipleDeclarationStatementsOnSameLine3() + => TestInRegularAndScript1Async( """ class C { @@ -2135,12 +2004,10 @@ void Goo() } } """); - } [Fact] - public async Task TestMissingOnUnderscore() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnUnderscore() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2156,12 +2023,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18668")] - public async Task TestDefiniteAssignmentIssueWithVar() - { - await TestMissingInRegularAndScriptAsync( + public Task TestDefiniteAssignmentIssueWithVar() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2175,12 +2040,10 @@ static void M(bool condition) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18668")] - public async Task TestDefiniteAssignmentIssueWithNonVar() - { - await TestMissingInRegularAndScriptAsync( + public Task TestDefiniteAssignmentIssueWithNonVar() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2194,12 +2057,10 @@ static void M(bool condition) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21907")] - public async Task TestMissingOnCrossFunction1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnCrossFunction1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2224,12 +2085,10 @@ void Local() public static void Out(out T t) => t = default; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21907")] - public async Task TestMissingOnCrossFunction2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnCrossFunction2() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2257,12 +2116,10 @@ void InnerLocal() public static void Out(out T t) => t = default; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21907")] - public async Task TestMissingOnCrossFunction3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnCrossFunction3() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2289,12 +2146,10 @@ void Local() public static void Out(out T t) => t = default; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21907")] - public async Task TestMissingOnCrossFunction4() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnCrossFunction4() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2323,12 +2178,10 @@ void Local() public static void Out(out T t) => t = default; } """); - } [Fact] - public async Task TestDefiniteAssignment1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestDefiniteAssignment1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2346,12 +2199,10 @@ static void M(bool condition) } } """); - } [Fact] - public async Task TestDefiniteAssignment2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestDefiniteAssignment2() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2370,15 +2221,13 @@ static void M(bool condition) } } """); - } [Theory] [InlineData("c && M(out x)", "c && M(out bool x)")] [InlineData("false || M(out x)", "false || M(out bool x)")] [InlineData("M(out x) || M(out x)", "M(out bool x) || M(out x)")] - public async Task TestDefiniteAssignment3(string input, string output) - { - await TestInRegularAndScript1Async( + public Task TestDefiniteAssignment3(string input, string output) + => TestInRegularAndScript1Async( $$""" using System; @@ -2414,12 +2263,10 @@ static void M(bool c) } } """); - } [Fact] - public async Task InlineVariable_NullableEnable() - { - await TestInRegularAndScript1Async(""" + public Task InlineVariable_NullableEnable() + => TestInRegularAndScript1Async(""" #nullable enable class C { @@ -2441,14 +2288,12 @@ void M(out C c2) } } """); - } [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/44429")] [WorkItem("https://github.com/dotnet/roslyn/issues/74736")] - public async Task TopLevelStatement() - { - await TestAsync(""" + public Task TopLevelStatement() + => TestAsync(""" [|int|] i; if (int.TryParse(v, out i)) { @@ -2458,12 +2303,10 @@ await TestAsync(""" { } """, CSharpParseOptions.Default); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47041")] - public async Task CollectionInitializer() - { - await TestInRegularAndScript1Async( + public Task CollectionInitializer() + => TestInRegularAndScript1Async( """ class C { @@ -2482,12 +2325,10 @@ class C }; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22881")] - public async Task PriorRegionClose() - { - await TestInRegularAndScript1Async( + public Task PriorRegionClose() + => TestInRegularAndScript1Async( """ class C { @@ -2527,12 +2368,10 @@ private void TestMethod(out int hello) } } """); - } [Fact] - public async Task TestInSwitchSection() - { - await TestInRegularAndScript1Async( + public Task TestInSwitchSection() + => TestInRegularAndScript1Async( """ class C { @@ -2564,7 +2403,6 @@ void M(object o) } } """); - } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/35993")] public async Task InlineTemporarySpacing( @@ -2631,9 +2469,8 @@ object B(out bool x) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/62805")] - public async Task TestDirectiveWithFixAll1() - { - await TestInRegularAndScript1Async( + public Task TestDirectiveWithFixAll1() + => TestInRegularAndScript1Async( """ class C { @@ -2662,12 +2499,10 @@ void M(out int a, out int b) #endregion } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32427")] - public async Task TestExplicitTypeEverywhere() - { - await TestInRegularAndScriptAsync( + public Task TestExplicitTypeEverywhere() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -2695,12 +2530,10 @@ void A(Dictionary map, TFirst first) } } """, options: ExplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40650")] - public async Task TestReferencedInSwitchArms1() - { - await TestMissingAsync( + public Task TestReferencedInSwitchArms1() + => TestMissingAsync( """ using System.Collections.Generic; @@ -2721,12 +2554,10 @@ private static int Main(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40650")] - public async Task TestReferencedInSwitchArms2() - { - await TestInRegularAndScript1Async( + public Task TestReferencedInSwitchArms2() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; @@ -2764,5 +2595,4 @@ private static int Main(string[] args) } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/InlineDeclaration/CSharpInlineDeclarationTests_FixAllTests.cs b/src/Analyzers/CSharp/Tests/InlineDeclaration/CSharpInlineDeclarationTests_FixAllTests.cs index 89e4c8832610c..d9d37e92bf90d 100644 --- a/src/Analyzers/CSharp/Tests/InlineDeclaration/CSharpInlineDeclarationTests_FixAllTests.cs +++ b/src/Analyzers/CSharp/Tests/InlineDeclaration/CSharpInlineDeclarationTests_FixAllTests.cs @@ -13,9 +13,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InlineDeclaration; public sealed partial class CSharpInlineDeclarationTests { [Fact] - public async Task FixAllInDocument1() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument1() + => TestInRegularAndScriptAsync( """ class C { @@ -39,13 +38,10 @@ void M() } } """); - } [Fact] - public async Task FixAllInDocument2() - { - - await TestInRegularAndScriptAsync( + public Task FixAllInDocument2() + => TestInRegularAndScriptAsync( """ class C { @@ -84,12 +80,10 @@ void M1() } } """); - } [Fact] - public async Task FixAllInDocument3() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument3() + => TestInRegularAndScriptAsync( """ class C { @@ -111,12 +105,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29935")] - public async Task FixAllInDocumentSymbolResolution() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocumentSymbolResolution() + => TestInRegularAndScriptAsync( """ class C { @@ -159,12 +151,10 @@ void A(out string s, out string s2) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28323")] - public async Task FixAllInDocument4() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument4() + => TestInRegularAndScriptAsync( """ class C { @@ -186,12 +176,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28323")] - public async Task FixAllInDocument5() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument5() + => TestInRegularAndScriptAsync( """ class C { @@ -216,12 +204,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28323")] - public async Task FixAllInDocument6() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument6() + => TestInRegularAndScriptAsync( """ class C { @@ -246,12 +232,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28323")] - public async Task FixAllInDocument7() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument7() + => TestInRegularAndScriptAsync( """ class C { @@ -276,12 +260,10 @@ void M() } } """); - } [Fact] - public async Task FixAllInDocument8() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument8() + => TestInRegularAndScriptAsync( """ class C { @@ -306,12 +288,10 @@ void M() } } """); - } [Fact] - public async Task FixAllInDocument9() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument9() + => TestInRegularAndScriptAsync( """ class C { @@ -336,12 +316,10 @@ void M() } } """); - } [Fact] - public async Task FixAllInDocument10() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument10() + => TestInRegularAndScriptAsync( """ class C { @@ -366,12 +344,10 @@ void M() } } """); - } [Fact] - public async Task FixAllInDocument11() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument11() + => TestInRegularAndScriptAsync( """ class C { @@ -393,12 +369,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28323")] - public async Task FixAllInDocumentComments1() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocumentComments1() + => TestInRegularAndScriptAsync( """ class C { @@ -421,12 +395,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28323")] - public async Task FixAllInDocumentComments2() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocumentComments2() + => TestInRegularAndScriptAsync( """ class C { @@ -451,12 +423,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28323")] - public async Task FixAllInDocumentComments3() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocumentComments3() + => TestInRegularAndScriptAsync( """ class C { @@ -482,5 +452,4 @@ void M() } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessTests.cs b/src/Analyzers/CSharp/Tests/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessTests.cs index 300f4aa147927..9ed461328727d 100644 --- a/src/Analyzers/CSharp/Tests/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessTests.cs +++ b/src/Analyzers/CSharp/Tests/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessTests.cs @@ -22,9 +22,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider => (new InvokeDelegateWithConditionalAccessAnalyzer(), new InvokeDelegateWithConditionalAccessCodeFixProvider()); [Fact] - public async Task Test1() - { - await TestInRegularAndScript1Async( + public Task Test1() + => TestInRegularAndScript1Async( """ class C { @@ -51,12 +50,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76423")] - public async Task Test1_TopLevel() - { - await TestInRegularAndScriptAsync( + public Task Test1_TopLevel() + => TestInRegularAndScriptAsync( """ var v = () => {}; [||]if (v != null) @@ -68,12 +65,10 @@ await TestInRegularAndScriptAsync( var v = () => {}; v?.Invoke(); """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76423")] - public async Task Test2_TopLevel() - { - await TestAsync( + public Task Test2_TopLevel() + => TestAsync( """ Action a = null; [||]var v = a; @@ -87,12 +82,10 @@ await TestAsync( a?.Invoke(); """, parseOptions: CSharpParseOptions.Default); - } [Fact] - public async Task TestOnIf() - { - await TestInRegularAndScript1Async( + public Task TestOnIf() + => TestInRegularAndScript1Async( """ class C { @@ -119,12 +112,10 @@ void Goo() } } """); - } [Fact] - public async Task TestOnInvoke() - { - await TestInRegularAndScript1Async( + public Task TestOnInvoke() + => TestInRegularAndScript1Async( """ class C { @@ -151,12 +142,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/13226")] - public async Task TestMissingBeforeCSharp6() - { - await TestMissingAsync( + public Task TestMissingBeforeCSharp6() + => TestMissingAsync( """ class C { @@ -172,12 +161,10 @@ void Goo() } } """, new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5))); - } [Fact] - public async Task TestInvertedIf() - { - await TestInRegularAndScript1Async( + public Task TestInvertedIf() + => TestInRegularAndScript1Async( """ class C { @@ -204,12 +191,10 @@ void Goo() } } """); - } [Fact] - public async Task TestIfWithNoBraces() - { - await TestInRegularAndScript1Async( + public Task TestIfWithNoBraces() + => TestInRegularAndScript1Async( """ class C { @@ -234,12 +219,10 @@ void Goo() } } """); - } [Fact] - public async Task TestWithComplexExpression() - { - await TestInRegularAndScript1Async( + public Task TestWithComplexExpression() + => TestInRegularAndScript1Async( """ class C { @@ -268,12 +251,10 @@ void Goo() } } """); - } [Fact] - public async Task TestMissingWithElseClause() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWithElseClause() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -292,12 +273,10 @@ void Goo() } } """); - } [Fact] - public async Task TestMissingOnDeclarationWithMultipleVariables() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnDeclarationWithMultipleVariables() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -313,16 +292,14 @@ void Goo() } } """); - } /// /// With multiple variables in the same declaration, the fix _is not_ offered on the declaration /// itself, but _is_ offered on the invocation pattern. /// [Fact] - public async Task TestLocationWhereOfferedWithMultipleVariables() - { - await TestInRegularAndScript1Async( + public Task TestLocationWhereOfferedWithMultipleVariables() + => TestInRegularAndScript1Async( """ class C { @@ -350,16 +327,14 @@ void Goo() } } """); - } /// /// If we have a variable declaration and if it is read/written outside the delegate /// invocation pattern, the fix is not offered on the declaration. /// [Fact] - public async Task TestMissingOnDeclarationIfUsedOutside() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnDeclarationIfUsedOutside() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -377,7 +352,6 @@ void Goo() } } """); - } /// /// If we have a variable declaration and if it is read/written outside the delegate @@ -385,9 +359,8 @@ void Goo() /// the invocation pattern itself. /// [Fact] - public async Task TestLocationWhereOfferedIfUsedOutside() - { - await TestInRegularAndScript1Async( + public Task TestLocationWhereOfferedIfUsedOutside() + => TestInRegularAndScript1Async( """ class C { @@ -419,12 +392,10 @@ void Goo() } } """); - } [Fact] - public async Task TestSimpleForm1() - { - await TestInRegularAndScript1Async( + public Task TestSimpleForm1() + => TestInRegularAndScript1Async( """ using System; @@ -454,12 +425,10 @@ void M() } } """); - } [Fact] - public async Task TestSimpleForm2() - { - await TestInRegularAndScript1Async( + public Task TestSimpleForm2() + => TestInRegularAndScript1Async( """ using System; @@ -489,12 +458,10 @@ void M() } } """); - } [Fact] - public async Task TestInElseClause1() - { - await TestInRegularAndScript1Async( + public Task TestInElseClause1() + => TestInRegularAndScript1Async( """ using System; @@ -533,12 +500,10 @@ void M() } } """); - } [Fact] - public async Task TestInElseClause2() - { - await TestInRegularAndScript1Async( + public Task TestInElseClause2() + => TestInRegularAndScript1Async( """ using System; @@ -572,12 +537,10 @@ void M() } } """); - } [Fact] - public async Task TestTrivia1() - { - await TestInRegularAndScript1Async( + public Task TestTrivia1() + => TestInRegularAndScript1Async( """ class C { @@ -604,12 +567,10 @@ void Goo() } } """); - } [Fact] - public async Task TestTrivia2() - { - await TestInRegularAndScript1Async( + public Task TestTrivia2() + => TestInRegularAndScript1Async( """ class C { @@ -635,12 +596,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51563")] - public async Task TestTrivia3() - { - await TestInRegularAndScript1Async( + public Task TestTrivia3() + => TestInRegularAndScript1Async( """ class C { @@ -666,12 +625,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51563")] - public async Task TestTrivia4() - { - await TestInRegularAndScript1Async( + public Task TestTrivia4() + => TestInRegularAndScript1Async( """ class C { @@ -694,15 +651,13 @@ void Goo() } } """); - } /// /// tests locations where the fix is offered. /// [Fact] - public async Task TestFixOfferedOnIf() - { - await TestInRegularAndScript1Async( + public Task TestFixOfferedOnIf() + => TestInRegularAndScript1Async( """ class C { @@ -729,15 +684,13 @@ void Goo() } } """); - } /// /// tests locations where the fix is offered. /// [Fact] - public async Task TestFixOfferedInsideIf() - { - await TestInRegularAndScript1Async( + public Task TestFixOfferedInsideIf() + => TestInRegularAndScript1Async( """ class C { @@ -764,12 +717,10 @@ void Goo() } } """); - } [Fact] - public async Task TestMissingOnConditionalInvocation() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnConditionalInvocation() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -782,12 +733,10 @@ void Goo() } } """); - } [Fact] - public async Task TestMissingOnConditionalInvocation2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnConditionalInvocation2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -800,12 +749,10 @@ void Goo() } } """); - } [Fact] - public async Task TestMissingOnConditionalInvocation3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnConditionalInvocation3() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -817,12 +764,10 @@ void Goo() } } """); - } [Fact] - public async Task TestMissingOnNonNullCheckExpressions() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnNonNullCheckExpressions() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -838,12 +783,10 @@ void Goo() } } """); - } [Fact] - public async Task TestMissingOnNonNullCheckExpressions2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnNonNullCheckExpressions2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -859,16 +802,14 @@ void Goo() } } """); - } /// /// if local declaration is not immediately preceding the invocation pattern, /// the fix is not offered on the declaration. /// [Fact] - public async Task TestLocalNotImmediatelyPrecedingNullCheckAndInvokePattern() - { - await TestMissingInRegularAndScriptAsync( + public Task TestLocalNotImmediatelyPrecedingNullCheckAndInvokePattern() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -885,16 +826,14 @@ void Goo() } } """); - } /// /// if local declaration is not immediately preceding the invocation pattern, /// the fix is not offered on the declaration but is offered on the invocation pattern itself. /// [Fact] - public async Task TestLocalDNotImmediatelyPrecedingNullCheckAndInvokePattern2() - { - await TestInRegularAndScript1Async( + public Task TestLocalDNotImmediatelyPrecedingNullCheckAndInvokePattern2() + => TestInRegularAndScript1Async( """ class C { @@ -924,12 +863,10 @@ void Goo() } } """); - } [Fact] - public async Task TestMissingOnFunc() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnFunc() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -945,12 +882,10 @@ int Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/13226")] - public async Task TestWithLambdaInitializer() - { - await TestInRegularAndScript1Async( + public Task TestWithLambdaInitializer() + => TestInRegularAndScript1Async( """ using System; @@ -978,12 +913,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/13226")] - public async Task TestWithLambdaInitializer2() - { - await TestInRegularAndScript1Async( + public Task TestWithLambdaInitializer2() + => TestInRegularAndScript1Async( """ using System; @@ -1011,12 +944,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/13226")] - public async Task TestForWithAnonymousMethod() - { - await TestInRegularAndScript1Async( + public Task TestForWithAnonymousMethod() + => TestInRegularAndScript1Async( """ using System; @@ -1044,12 +975,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/13226")] - public async Task TestWithMethodReference() - { - await TestInRegularAndScript1Async( + public Task TestWithMethodReference() + => TestInRegularAndScript1Async( """ using System; @@ -1077,12 +1006,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31827")] - public async Task TestWithExplicitInvokeCall1() - { - await TestInRegularAndScript1Async( + public Task TestWithExplicitInvokeCall1() + => TestInRegularAndScript1Async( """ using System; @@ -1110,12 +1037,10 @@ void M() event EventHandler Event; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31827")] - public async Task TestWithExplicitInvokeCall2() - { - await TestInRegularAndScript1Async( + public Task TestWithExplicitInvokeCall2() + => TestInRegularAndScript1Async( """ class C { @@ -1142,12 +1067,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76423")] - public async Task TestWithExplicitInvokeCall2_TopLevel() - { - await TestInRegularAndScriptAsync( + public Task TestWithExplicitInvokeCall2_TopLevel() + => TestInRegularAndScriptAsync( """ var v = () => {}; [||]if (v != null) @@ -1159,12 +1082,10 @@ await TestInRegularAndScriptAsync( var v = () => {}; v?.Invoke(); """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50976")] - public async Task TestMissingOnFunctionPointer() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnFunctionPointer() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1177,12 +1098,10 @@ unsafe void M(delegate* managed func) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76422")] - public async Task TestInvokeMethodOnNonDelegate() - { - await TestMissingAsync( + public Task TestInvokeMethodOnNonDelegate() + => TestMissingAsync( """ class C { @@ -1201,12 +1120,10 @@ class C public void Invoke() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76422")] - public async Task TestInvokeMethodOnNonDelegate_TopLevel() - { - await TestMissingAsync( + public Task TestInvokeMethodOnNonDelegate_TopLevel() + => TestMissingAsync( """ var v = new C(); [||]if (v != null) @@ -1219,5 +1136,4 @@ class C public void Invoke() { } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessTests_FixAllTests.cs b/src/Analyzers/CSharp/Tests/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessTests_FixAllTests.cs index bd43cb4c34bdf..f15549992b359 100644 --- a/src/Analyzers/CSharp/Tests/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessTests_FixAllTests.cs +++ b/src/Analyzers/CSharp/Tests/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessTests_FixAllTests.cs @@ -12,9 +12,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.InvokeDeleg public sealed partial class InvokeDelegateWithConditionalAccessTests { [Fact] - public async Task TestFixAllInDocument1() - { - await TestInRegularAndScriptAsync( + public Task TestFixAllInDocument1() + => TestInRegularAndScriptAsync( """ class C { @@ -48,12 +47,10 @@ void Goo() } } """); - } [Fact] - public async Task TestFixAllInDocument2() - { - await TestInRegularAndScriptAsync( + public Task TestFixAllInDocument2() + => TestInRegularAndScriptAsync( """ class C { @@ -87,12 +84,10 @@ void Goo() } } """); - } [Fact] - public async Task TestFixAllInDocument3() - { - await TestInRegularAndScriptAsync( + public Task TestFixAllInDocument3() + => TestInRegularAndScriptAsync( """ class C { @@ -126,12 +121,10 @@ void Goo() } } """); - } [Fact] - public async Task TestFixAllInDocument4() - { - await TestInRegularAndScriptAsync( + public Task TestFixAllInDocument4() + => TestInRegularAndScriptAsync( """ class C { @@ -165,12 +158,10 @@ void Goo() } } """); - } [Fact] - public async Task TestFixAllInDocument5() - { - await TestInRegularAndScriptAsync( + public Task TestFixAllInDocument5() + => TestInRegularAndScriptAsync( """ class C { @@ -204,12 +195,10 @@ void Goo() } } """); - } [Fact] - public async Task TestFixAllInDocument6() - { - await TestInRegularAndScriptAsync( + public Task TestFixAllInDocument6() + => TestInRegularAndScriptAsync( """ class C { @@ -243,5 +232,4 @@ void Goo() } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/Iterator/AddYieldTests.cs b/src/Analyzers/CSharp/Tests/Iterator/AddYieldTests.cs index 11c13db2aaa3d..3e7aecc8eb96f 100644 --- a/src/Analyzers/CSharp/Tests/Iterator/AddYieldTests.cs +++ b/src/Analyzers/CSharp/Tests/Iterator/AddYieldTests.cs @@ -16,21 +16,15 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Iterator; [Trait(Traits.Feature, Traits.Features.CodeActionsChangeToYield)] public sealed class AddYieldTests { - private static async Task TestMissingInRegularAndScriptAsync(string code) - { - await VerifyCS.VerifyCodeFixAsync(code, code); - } + private static Task TestMissingInRegularAndScriptAsync(string code) + => VerifyCS.VerifyCodeFixAsync(code, code); - private static async Task TestInRegularAndScriptAsync(string code, string fixedCode) - { - await VerifyCS.VerifyCodeFixAsync(code, fixedCode); - } + private static Task TestInRegularAndScriptAsync(string code, string fixedCode) + => VerifyCS.VerifyCodeFixAsync(code, fixedCode); [Fact] - public async Task TestAddYieldIEnumerableReturnNull() - { - var initial = - """ + public Task TestAddYieldIEnumerableReturnNull() + => TestMissingInRegularAndScriptAsync(""" using System; using System.Collections; @@ -41,15 +35,11 @@ static IEnumerable M() return null; } } - """; - await TestMissingInRegularAndScriptAsync(initial); - } + """); [Fact] - public async Task TestAddYieldIEnumerableReturnObject() - { - var initial = - """ + public Task TestAddYieldIEnumerableReturnObject() + => TestInRegularAndScriptAsync(""" using System; using System.Collections; @@ -60,9 +50,7 @@ static IEnumerable M() return {|CS0266:new object()|}; } } - """; - var expected = - """ + """, """ using System; using System.Collections; @@ -73,15 +61,11 @@ static IEnumerable M() yield return new object(); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestAddYieldIEnumeratorReturnObject() - { - var initial = - """ + public Task TestAddYieldIEnumeratorReturnObject() + => TestInRegularAndScriptAsync(""" using System; using System.Collections; @@ -92,9 +76,7 @@ static IEnumerator M() return {|CS0266:new object()|}; } } - """; - var expected = - """ + """, """ using System; using System.Collections; @@ -105,15 +87,11 @@ static IEnumerator M() yield return new object(); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestAddYieldIEnumeratorReturnGenericList() - { - var initial = - """ + public Task TestAddYieldIEnumeratorReturnGenericList() + => TestInRegularAndScriptAsync(""" using System; using System.Collections; using System.Collections.Generic; @@ -125,9 +103,7 @@ static IEnumerator M() return {|CS0266:new List()|}; } } - """; - var expected = - """ + """, """ using System; using System.Collections; using System.Collections.Generic; @@ -139,15 +115,11 @@ static IEnumerator M() yield return new List(); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestAddYieldGenericIEnumeratorReturnObject() - { - var initial = - """ + public Task TestAddYieldGenericIEnumeratorReturnObject() + => TestInRegularAndScriptAsync(""" using System; using System.Collections; using System.Collections.Generic; @@ -159,9 +131,7 @@ static IEnumerator M() return {|CS0266:new object()|}; } } - """; - var expected = - """ + """, """ using System; using System.Collections; using System.Collections.Generic; @@ -173,15 +143,11 @@ static IEnumerator M() yield return new object(); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestAddYieldGenericIEnumerableReturnObject() - { - var initial = - """ + public Task TestAddYieldGenericIEnumerableReturnObject() + => TestInRegularAndScriptAsync(""" using System; using System.Collections; using System.Collections.Generic; @@ -193,9 +159,7 @@ static IEnumerable M() return {|CS0266:new object()|}; } } - """; - var expected = - """ + """, """ using System; using System.Collections; using System.Collections.Generic; @@ -207,15 +171,11 @@ static IEnumerable M() yield return new object(); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestAddYieldIEnumerableReturnGenericList() - { - var initial = - """ + public Task TestAddYieldIEnumerableReturnGenericList() + => TestMissingInRegularAndScriptAsync(""" using System; using System.Collections; using System.Collections.Generic; @@ -227,15 +187,11 @@ static IEnumerable M() return new List(); } } - """; - await TestMissingInRegularAndScriptAsync(initial); - } + """); [Fact] - public async Task TestAddYieldGenericIEnumeratorReturnDefault() - { - var initial = - """ + public Task TestAddYieldGenericIEnumeratorReturnDefault() + => TestInRegularAndScriptAsync(""" using System; using System.Collections; using System.Collections.Generic; @@ -247,9 +203,7 @@ static IEnumerator M() return {|CS0266:default(T)|}; } } - """; - var expected = - """ + """, """ using System; using System.Collections; using System.Collections.Generic; @@ -261,15 +215,11 @@ static IEnumerator M() yield return default(T); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestAddYieldGenericIEnumerableReturnConvertibleToObject() - { - var initial = - """ + public Task TestAddYieldGenericIEnumerableReturnConvertibleToObject() + => TestInRegularAndScriptAsync(""" using System; using System.Collections; using System.Collections.Generic; @@ -281,9 +231,7 @@ static IEnumerable M() return {|CS0029:0|}; } } - """; - var expected = - """ + """, """ using System; using System.Collections; using System.Collections.Generic; @@ -295,15 +243,11 @@ static IEnumerable M() yield return 0; } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestAddYieldGenericIEnumerableReturnConvertibleToFloat() - { - var initial = - """ + public Task TestAddYieldGenericIEnumerableReturnConvertibleToFloat() + => TestInRegularAndScriptAsync(""" using System; using System.Collections; using System.Collections.Generic; @@ -315,9 +259,7 @@ static IEnumerator M() return {|CS0029:0|}; } } - """; - var expected = - """ + """, """ using System; using System.Collections; using System.Collections.Generic; @@ -329,15 +271,11 @@ static IEnumerator M() yield return 0; } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestAddYieldGenericIEnumeratorNonConvertableType() - { - var initial = - """ + public Task TestAddYieldGenericIEnumeratorNonConvertableType() + => TestMissingInRegularAndScriptAsync(""" using System; using System.Collections; using System.Collections.Generic; @@ -349,15 +287,11 @@ static IEnumerator> M() return {|CS0266:new List()|}; } } - """; - await TestMissingInRegularAndScriptAsync(initial); - } + """); [Fact] - public async Task TestAddYieldGenericIEnumeratorConvertableTypeDateTime() - { - var initial = - """ + public Task TestAddYieldGenericIEnumeratorConvertableTypeDateTime() + => TestInRegularAndScriptAsync(""" using System; using System.Collections; using System.Collections.Generic; @@ -369,9 +303,7 @@ static IEnumerator> M() return {|CS0266:new List()|}; } } - """; - var expected = - """ + """, """ using System; using System.Collections; using System.Collections.Generic; @@ -383,15 +315,11 @@ static IEnumerator> M() yield return new List(); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestAddYieldNoTypeArguments() - { - var initial = - """ + public Task TestAddYieldNoTypeArguments() + => TestMissingInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.IO; @@ -437,7 +365,5 @@ static void Main(string[] args) } } } - """; - await TestMissingInRegularAndScriptAsync(initial); - } + """); } diff --git a/src/Analyzers/CSharp/Tests/Iterator/ChangeToIEnumerableTests.cs b/src/Analyzers/CSharp/Tests/Iterator/ChangeToIEnumerableTests.cs index 0e626d0ac1da6..f428dd3339cee 100644 --- a/src/Analyzers/CSharp/Tests/Iterator/ChangeToIEnumerableTests.cs +++ b/src/Analyzers/CSharp/Tests/Iterator/ChangeToIEnumerableTests.cs @@ -25,10 +25,8 @@ internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProvide => (null, new CSharpChangeToIEnumerableCodeFixProvider()); [Fact] - public async Task TestChangeToIEnumerableObjectMethod() - { - var initial = - """ + public Task TestChangeToIEnumerableObjectMethod() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; @@ -39,10 +37,7 @@ class Program yield return 0; } } - """; - - var expected = - """ + """, """ using System; using System.Collections.Generic; @@ -53,15 +48,11 @@ static IEnumerable M() yield return 0; } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestChangeToIEnumerableTupleMethod() - { - var initial = - """ + public Task TestChangeToIEnumerableTupleMethod() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; @@ -72,10 +63,7 @@ class Program yield return 0; } } - """; - - var expected = - """ + """, """ using System; using System.Collections.Generic; @@ -86,15 +74,11 @@ static IEnumerable> M() yield return 0; } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestChangeToIEnumerableListMethod() - { - var initial = - """ + public Task TestChangeToIEnumerableListMethod() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; @@ -105,10 +89,7 @@ class Program yield return 0; } } - """; - - var expected = - """ + """, """ using System; using System.Collections.Generic; @@ -119,15 +100,11 @@ static IEnumerable M() yield return 0; } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestChangeToIEnumerableWithListReturningMethodWithNullableArgument() - { - var initial = - """ + public Task TestChangeToIEnumerableWithListReturningMethodWithNullableArgument() + => TestInRegularAndScriptAsync(""" #nullable enable using System; @@ -140,10 +117,7 @@ class Program yield return ""; } } - """; - - var expected = - """ + """, """ #nullable enable using System; @@ -156,15 +130,11 @@ class Program yield return ""; } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestChangeToIEnumerableGenericIEnumerableMethod() - { - var initial = - """ + public Task TestChangeToIEnumerableGenericIEnumerableMethod() + => TestMissingInRegularAndScriptAsync(""" using System; using System.Collections.Generic; @@ -175,15 +145,11 @@ class Program yield return 0; } } - """; - await TestMissingInRegularAndScriptAsync(initial); - } + """); [Fact] - public async Task TestChangeToIEnumerableGenericIEnumeratorMethod() - { - var initial = - """ + public Task TestChangeToIEnumerableGenericIEnumeratorMethod() + => TestMissingInRegularAndScriptAsync(""" using System; using System.Collections.Generic; @@ -194,15 +160,11 @@ class Program yield return 0; } } - """; - await TestMissingInRegularAndScriptAsync(initial); - } + """); [Fact] - public async Task TestChangeToIEnumerableIEnumeratorMethod() - { - var initial = - """ + public Task TestChangeToIEnumerableIEnumeratorMethod() + => TestMissingInRegularAndScriptAsync(""" using System; using System.Collections; @@ -213,15 +175,11 @@ class Program yield return 0; } } - """; - await TestMissingInRegularAndScriptAsync(initial); - } + """); [Fact] - public async Task TestChangeToIEnumerableIEnumerableMethod() - { - var initial = - """ + public Task TestChangeToIEnumerableIEnumerableMethod() + => TestMissingInRegularAndScriptAsync(""" using System; using System.Collections; @@ -232,15 +190,11 @@ class Program yield return 0; } } - """; - await TestMissingInRegularAndScriptAsync(initial); - } + """); [Fact] - public async Task TestChangeToIEnumerableVoidMethod() - { - var initial = - """ + public Task TestChangeToIEnumerableVoidMethod() + => TestMissingInRegularAndScriptAsync(""" using System; using System.Collections; @@ -251,14 +205,11 @@ class Program yield return 0; } } - """; - await TestMissingInRegularAndScriptAsync(initial); - } + """); [Fact, WorkItem(7087, @"https://github.com/dotnet/roslyn/issues/7087")] - public async Task TestChangeToIEnumerableProperty() - { - await TestInRegularAndScriptAsync( + public Task TestChangeToIEnumerableProperty() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -335,12 +286,10 @@ public bool Equals(IMyInterface other) } } """); - } [Fact, WorkItem(7087, @"https://github.com/dotnet/roslyn/issues/7087")] - public async Task TestChangeToIEnumerableOperator() - { - await TestInRegularAndScriptAsync( + public Task TestChangeToIEnumerableOperator() + => TestInRegularAndScriptAsync( """ using System; using System.Collections; @@ -373,12 +322,10 @@ public class T } } """); - } [Fact, WorkItem(7087, @"https://github.com/dotnet/roslyn/issues/7087")] - public async Task TestChangeToIEnumerableIndexer() - { - await TestInRegularAndScriptAsync( + public Task TestChangeToIEnumerableIndexer() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -413,5 +360,4 @@ public IEnumerable this[int i] } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/MakeAnonymousFunctionStatic/MakeAnonymousFunctionStaticTests.cs b/src/Analyzers/CSharp/Tests/MakeAnonymousFunctionStatic/MakeAnonymousFunctionStaticTests.cs index ba791f0e82d19..9a75106b43a3f 100644 --- a/src/Analyzers/CSharp/Tests/MakeAnonymousFunctionStatic/MakeAnonymousFunctionStaticTests.cs +++ b/src/Analyzers/CSharp/Tests/MakeAnonymousFunctionStatic/MakeAnonymousFunctionStaticTests.cs @@ -17,23 +17,22 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeAnonymousFunctionSt [Trait(Traits.Feature, Traits.Features.CodeActionsMakeAnonymousFunctionStatic)] public sealed class MakeAnonymousFunctionStaticTests { - private static async Task TestWithCSharp9Async(string code, string fixedCode) - { - await new VerifyCS.Test + private static Task TestWithCSharp9Async(string code, string fixedCode) + => new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp9 }.RunAsync(); - } [Theory] [InlineData("i => { }")] [InlineData("(i) => { }")] [InlineData("delegate (int i) { }")] - public async Task TestBelowCSharp9(string anonymousFunctionSyntax) - { - var code = $$""" + public Task TestBelowCSharp9(string anonymousFunctionSyntax) + => new VerifyCS.Test + { + TestCode = $$""" using System; class C @@ -47,22 +46,18 @@ void N(Action a) { } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp8 }.RunAsync(); - } [Theory] [InlineData("i => { }")] [InlineData("(i) => { }")] [InlineData("delegate (int i) { }")] - public async Task TestWithOptionOff(string anonymousFunctionSyntax) - { - var code = $$""" + public Task TestWithOptionOff(string anonymousFunctionSyntax) + => new VerifyCS.Test + { + TestCode = $$""" using System; class C @@ -76,18 +71,13 @@ void N(Action a) { } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp9, Options = { { CSharpCodeStyleOptions.PreferStaticAnonymousFunction, false } } }.RunAsync(); - } [Theory] [InlineData("i => { }")] @@ -118,9 +108,8 @@ void N(Action a) [InlineData("i => { }")] [InlineData("(i) => { }")] [InlineData("delegate (int i) { }")] - public async Task TestNoCaptures(string anonymousFunctionSyntax) - { - var code = $$""" + public Task TestNoCaptures(string anonymousFunctionSyntax) + => TestWithCSharp9Async($$""" using System; class C @@ -134,9 +123,7 @@ void N(Action a) { } } - """; - - var fixedCode = $$""" + """, $$""" using System; class C @@ -150,10 +137,7 @@ void N(Action a) { } } - """; - - await TestWithCSharp9Async(code, fixedCode); - } + """); [Theory] [InlineData("i => _field")] @@ -186,9 +170,8 @@ void N(Func f) [InlineData("i => GetValueFromStaticMethod()")] [InlineData("(i) => GetValueFromStaticMethod()")] [InlineData("delegate (int i) { return GetValueFromStaticMethod(); }")] - public async Task TestNoCaptures_ReferencesStaticMethod(string anonymousFunctionSyntax) - { - var code = $$""" + public Task TestNoCaptures_ReferencesStaticMethod(string anonymousFunctionSyntax) + => TestWithCSharp9Async($$""" using System; class C @@ -204,9 +187,7 @@ void N(Func f) { } } - """; - - var fixedCode = $$""" + """, $$""" using System; class C @@ -222,10 +203,7 @@ void N(Func f) { } } - """; - - await TestWithCSharp9Async(code, fixedCode); - } + """); [Theory] [InlineData("i => x")] @@ -256,9 +234,8 @@ void N(Func f) [InlineData("i => i")] [InlineData("(i) => i")] [InlineData("delegate (int i) { return i; }")] - public async Task TestNoCaptures_SameFunctionParameterNameAsOuterParameterName(string anonymousFunctionSyntax) - { - var code = $$""" + public Task TestNoCaptures_SameFunctionParameterNameAsOuterParameterName(string anonymousFunctionSyntax) + => TestWithCSharp9Async($$""" using System; class C @@ -272,9 +249,7 @@ void N(Func f) { } } - """; - - var fixedCode = $$""" + """, $$""" using System; class C @@ -288,10 +263,7 @@ void N(Func f) { } } - """; - - await TestWithCSharp9Async(code, fixedCode); - } + """); [Theory] [InlineData("i => x")] @@ -323,9 +295,8 @@ void N(Func f) [InlineData("i => i")] [InlineData("(i) => i")] [InlineData("delegate (int i) { return i; }")] - public async Task TestNoCaptures_SameFunctionParameterNameAsOuterLocalName(string anonymousFunctionSyntax) - { - var code = $$""" + public Task TestNoCaptures_SameFunctionParameterNameAsOuterLocalName(string anonymousFunctionSyntax) + => TestWithCSharp9Async($$""" using System; class C @@ -340,9 +311,7 @@ void N(Func f) { } } - """; - - var fixedCode = $$""" + """, $$""" using System; class C @@ -357,15 +326,11 @@ void N(Func f) { } } - """; - - await TestWithCSharp9Async(code, fixedCode); - } + """); [Fact] - public async Task TestNestedLambdasWithNoCaptures() - { - var code = """ + public Task TestNestedLambdasWithNoCaptures() + => TestWithCSharp9Async(""" using System; class C @@ -382,9 +347,7 @@ void N(Action a) { } } - """; - - var fixedCode = """ + """, """ using System; class C @@ -401,15 +364,11 @@ void N(Action a) { } } - """; - - await TestWithCSharp9Async(code, fixedCode); - } + """); [Fact] - public async Task TestNestedAnonymousMethodsWithNoCaptures() - { - var code = """ + public Task TestNestedAnonymousMethodsWithNoCaptures() + => TestWithCSharp9Async(""" using System; class C @@ -426,9 +385,7 @@ void N(Action a) { } } - """; - - var fixedCode = """ + """, """ using System; class C @@ -445,8 +402,5 @@ void N(Action a) { } } - """; - - await TestWithCSharp9Async(code, fixedCode); - } + """); } diff --git a/src/Analyzers/CSharp/Tests/MakeFieldReadonly/MakeFieldReadonlyTests.cs b/src/Analyzers/CSharp/Tests/MakeFieldReadonly/MakeFieldReadonlyTests.cs index 19047d5507cd6..09af96d677b2a 100644 --- a/src/Analyzers/CSharp/Tests/MakeFieldReadonly/MakeFieldReadonlyTests.cs +++ b/src/Analyzers/CSharp/Tests/MakeFieldReadonly/MakeFieldReadonlyTests.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; @@ -21,7 +22,7 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeFieldReadonly; public sealed class MakeFieldReadonlyTests(ITestOutputHelper logger) : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest_NoEditor(logger) { - private static readonly ParseOptions s_strictFeatureFlag = CSharpParseOptions.Default.WithFeatures([KeyValuePairUtil.Create("strict", "true")]); + private static readonly ParseOptions s_strictFeatureFlag = CSharpParseOptions.Default.WithFeatures([KeyValuePair.Create("strict", "true")]); private const string s_inlineArrayAttribute = """ namespace System.Runtime.CompilerServices @@ -48,55 +49,48 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider [InlineData("protected")] [InlineData("protected internal")] [InlineData("private protected")] - public async Task NonPrivateField(string accessibility) - { - await TestMissingInRegularAndScriptAsync( -$@"class MyClass -{{ - {accessibility} int[| _goo |]; -}}"); - } + public Task NonPrivateField(string accessibility) + => TestMissingInRegularAndScriptAsync( + $$""" + class MyClass + { + {{accessibility}} int[| _goo |]; + } + """); [Fact] - public async Task FieldIsEvent() - { - await TestMissingInRegularAndScriptAsync( + public Task FieldIsEvent() + => TestMissingInRegularAndScriptAsync( """ class MyClass { private event System.EventHandler [|Goo|]; } """); - } [Fact] - public async Task FieldIsReadonly() - { - await TestMissingInRegularAndScriptAsync( + public Task FieldIsReadonly() + => TestMissingInRegularAndScriptAsync( """ class MyClass { private readonly int [|_goo|]; } """); - } [Fact] - public async Task FieldIsConst() - { - await TestMissingInRegularAndScriptAsync( + public Task FieldIsConst() + => TestMissingInRegularAndScriptAsync( """ class MyClass { private const int [|_goo|]; } """); - } [Fact] - public async Task FieldNotAssigned() - { - await TestInRegularAndScript1Async( + public Task FieldNotAssigned() + => TestInRegularAndScript1Async( """ class MyClass { @@ -109,12 +103,10 @@ class MyClass private readonly int _goo; } """); - } [Fact] - public async Task FieldNotAssigned_Struct() - { - await TestInRegularAndScript1Async( + public Task FieldNotAssigned_Struct() + => TestInRegularAndScript1Async( """ struct MyStruct { @@ -127,12 +119,10 @@ struct MyStruct private readonly int _goo; } """); - } [Fact] - public async Task FieldAssignedInline() - { - await TestInRegularAndScript1Async( + public Task FieldAssignedInline() + => TestInRegularAndScript1Async( """ class MyClass { @@ -145,12 +135,10 @@ class MyClass private readonly int _goo = 0; } """); - } [Fact] - public async Task MultipleFieldsAssignedInline_AllCanBeReadonly() - { - await TestInRegularAndScript1Async( + public Task MultipleFieldsAssignedInline_AllCanBeReadonly() + => TestInRegularAndScript1Async( """ class MyClass { @@ -164,12 +152,10 @@ class MyClass private int _bar = 0; } """); - } [Fact] - public async Task ThreeFieldsAssignedInline_AllCanBeReadonly_SeparatesAllAndKeepsThemInOrder() - { - await TestInRegularAndScript1Async( + public Task ThreeFieldsAssignedInline_AllCanBeReadonly_SeparatesAllAndKeepsThemInOrder() + => TestInRegularAndScript1Async( """ class MyClass { @@ -184,12 +170,10 @@ class MyClass private int _fizz = 0; } """); - } [Fact] - public async Task MultipleFieldsAssignedInline_OneIsAssignedInMethod() - { - await TestInRegularAndScript1Async( + public Task MultipleFieldsAssignedInline_OneIsAssignedInMethod() + => TestInRegularAndScript1Async( """ class MyClass { @@ -212,12 +196,10 @@ class MyClass } } """); - } [Fact] - public async Task MultipleFieldsAssignedInline_NoInitializer() - { - await TestInRegularAndScript1Async( + public Task MultipleFieldsAssignedInline_NoInitializer() + => TestInRegularAndScript1Async( """ class MyClass { @@ -231,32 +213,32 @@ class MyClass private int _bar = 0; } """); - } [Theory] [InlineData("")] [InlineData("\r\n")] [InlineData("\r\n\r\n")] - public async Task MultipleFieldsAssignedInline_LeadingCommentAndWhitespace(string leadingTrvia) - { - await TestInRegularAndScript1Async( -$@"class MyClass -{{ - //Comment{leadingTrvia} - private int _goo = 0, [|_bar|] = 0; -}}", -$@"class MyClass -{{ - //Comment{leadingTrvia} - private int _goo = 0; - private readonly int _bar = 0; -}}"); - } + public Task MultipleFieldsAssignedInline_LeadingCommentAndWhitespace(string leadingTrvia) + => TestInRegularAndScript1Async( + $$""" + class MyClass + { + //Comment{{leadingTrvia}} + private int _goo = 0, [|_bar|] = 0; + } + """, + $$""" + class MyClass + { + //Comment{{leadingTrvia}} + private int _goo = 0; + private readonly int _bar = 0; + } + """); [Fact] - public async Task FieldAssignedInCtor() - { - await TestInRegularAndScript1Async( + public Task FieldAssignedInCtor() + => TestInRegularAndScript1Async( """ class MyClass { @@ -277,12 +259,10 @@ class MyClass } } """); - } [Fact] - public async Task FieldAssignedInSimpleLambdaInCtor() - { - await TestMissingInRegularAndScriptAsync( + public Task FieldAssignedInSimpleLambdaInCtor() + => TestMissingInRegularAndScriptAsync( """ public class MyClass { @@ -295,12 +275,10 @@ public MyClass() public Action E; } """); - } [Fact] - public async Task FieldAssignedInLambdaInCtor() - { - await TestMissingInRegularAndScriptAsync( + public Task FieldAssignedInLambdaInCtor() + => TestMissingInRegularAndScriptAsync( """ public class MyClass { @@ -313,12 +291,10 @@ public MyClass() public event EventHandler E; } """); - } [Fact] - public async Task FieldAssignedInLambdaWithBlockInCtor() - { - await TestMissingInRegularAndScriptAsync( + public Task FieldAssignedInLambdaWithBlockInCtor() + => TestMissingInRegularAndScriptAsync( """ public class MyClass { @@ -331,12 +307,10 @@ public MyClass() public event EventHandler E; } """); - } [Fact] - public async Task FieldAssignedInAnonymousFunctionInCtor() - { - await TestMissingInRegularAndScriptAsync( + public Task FieldAssignedInAnonymousFunctionInCtor() + => TestMissingInRegularAndScriptAsync( """ public class MyClass { @@ -349,12 +323,10 @@ public MyClass() public Action E; } """); - } [Fact] - public async Task FieldAssignedInLocalFunctionExpressionBodyInCtor() - { - await TestMissingInRegularAndScriptAsync( + public Task FieldAssignedInLocalFunctionExpressionBodyInCtor() + => TestMissingInRegularAndScriptAsync( """ public class MyClass { @@ -365,12 +337,10 @@ public MyClass() } } """); - } [Fact] - public async Task FieldAssignedInLocalFunctionBlockBodyInCtor() - { - await TestMissingInRegularAndScriptAsync( + public Task FieldAssignedInLocalFunctionBlockBodyInCtor() + => TestMissingInRegularAndScriptAsync( """ public class MyClass { @@ -381,12 +351,10 @@ public MyClass() } } """); - } [Fact] - public async Task FieldAssignedInCtor_DifferentInstance() - { - await TestMissingInRegularAndScriptAsync( + public Task FieldAssignedInCtor_DifferentInstance() + => TestMissingInRegularAndScriptAsync( """ class MyClass { @@ -398,12 +366,10 @@ class MyClass } } """); - } [Fact] - public async Task FieldAssignedInCtor_DifferentInstance_ObjectInitializer() - { - await TestMissingInRegularAndScriptAsync( + public Task FieldAssignedInCtor_DifferentInstance_ObjectInitializer() + => TestMissingInRegularAndScriptAsync( """ class MyClass { @@ -414,12 +380,10 @@ class MyClass } } """); - } [Fact] - public async Task FieldAssignedInCtor_QualifiedWithThis() - { - await TestInRegularAndScript1Async( + public Task FieldAssignedInCtor_QualifiedWithThis() + => TestInRegularAndScript1Async( """ class MyClass { @@ -440,12 +404,10 @@ class MyClass } } """); - } [Fact] - public async Task FieldReturnedInProperty() - { - await TestInRegularAndScript1Async( + public Task FieldReturnedInProperty() + => TestInRegularAndScript1Async( """ class MyClass { @@ -466,12 +428,10 @@ int Goo } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29746")] - public async Task FieldReturnedInMethod() - { - await TestInRegularAndScript1Async( + public Task FieldReturnedInMethod() + => TestInRegularAndScript1Async( """ class MyClass { @@ -494,12 +454,10 @@ public string Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29746")] - public async Task FieldReadInMethod() - { - await TestInRegularAndScript1Async( + public Task FieldReadInMethod() + => TestInRegularAndScript1Async( """ class MyClass { @@ -522,12 +480,10 @@ public string Method() } } """); - } [Fact] - public async Task FieldAssignedInProperty() - { - await TestMissingInRegularAndScriptAsync( + public Task FieldAssignedInProperty() + => TestMissingInRegularAndScriptAsync( """ class MyClass { @@ -539,12 +495,10 @@ int Goo } } """); - } [Fact] - public async Task FieldAssignedInMethod() - { - await TestMissingInRegularAndScriptAsync( + public Task FieldAssignedInMethod() + => TestMissingInRegularAndScriptAsync( """ class MyClass { @@ -555,12 +509,10 @@ int Goo() } } """); - } [Fact] - public async Task FieldAssignedInNestedTypeConstructor() - { - await TestMissingInRegularAndScriptAsync( + public Task FieldAssignedInNestedTypeConstructor() + => TestMissingInRegularAndScriptAsync( """ class MyClass { @@ -575,12 +527,10 @@ class Derived : MyClass } } """); - } [Fact] - public async Task FieldAssignedInNestedTypeMethod() - { - await TestMissingInRegularAndScriptAsync( + public Task FieldAssignedInNestedTypeMethod() + => TestMissingInRegularAndScriptAsync( """ class MyClass { @@ -595,12 +545,10 @@ void Method() } } """); - } [Fact] - public async Task FieldInNestedTypeAssignedInConstructor() - { - await TestInRegularAndScript1Async( + public Task FieldInNestedTypeAssignedInConstructor() + => TestInRegularAndScript1Async( """ class MyClass { @@ -629,12 +577,10 @@ public NestedType() } } """); - } [Fact] - public async Task VariableAssignedToFieldInMethod() - { - await TestInRegularAndScript1Async( + public Task VariableAssignedToFieldInMethod() + => TestInRegularAndScript1Async( """ class MyClass { @@ -655,12 +601,10 @@ int Goo() } } """); - } [Fact] - public async Task FieldAssignedInMethodWithCompoundOperator() - { - await TestMissingInRegularAndScriptAsync( + public Task FieldAssignedInMethodWithCompoundOperator() + => TestMissingInRegularAndScriptAsync( """ class MyClass { @@ -671,12 +615,10 @@ int Goo(int value) } } """); - } [Fact] - public async Task FieldUsedWithPostfixIncrement() - { - await TestMissingInRegularAndScriptAsync( + public Task FieldUsedWithPostfixIncrement() + => TestMissingInRegularAndScriptAsync( """ class MyClass { @@ -687,12 +629,10 @@ int Goo(int value) } } """); - } [Fact] - public async Task FieldUsedWithPrefixDecrement() - { - await TestMissingInRegularAndScriptAsync( + public Task FieldUsedWithPrefixDecrement() + => TestMissingInRegularAndScriptAsync( """ class MyClass { @@ -703,12 +643,10 @@ int Goo(int value) } } """); - } [Fact] - public async Task NotAssignedInPartialClass1() - { - await TestInRegularAndScript1Async( + public Task NotAssignedInPartialClass1() + => TestInRegularAndScript1Async( """ partial class MyClass { @@ -721,12 +659,10 @@ partial class MyClass private readonly int _goo; } """); - } [Fact] - public async Task NotAssignedInPartialClass2() - { - await TestInRegularAndScript1Async( + public Task NotAssignedInPartialClass2() + => TestInRegularAndScript1Async( """ partial class MyClass { @@ -745,12 +681,10 @@ partial class MyClass { } """); - } [Fact] - public async Task NotAssignedInPartialClass3() - { - await TestInRegularAndScript1Async( + public Task NotAssignedInPartialClass3() + => TestInRegularAndScript1Async( """ @@ -787,12 +721,10 @@ void M() """); - } [Fact] - public async Task AssignedInPartialClass1() - { - await TestMissingInRegularAndScriptAsync( + public Task AssignedInPartialClass1() + => TestMissingInRegularAndScriptAsync( """ partial class MyClass { @@ -804,12 +736,10 @@ void SetGoo() } } """); - } [Fact] - public async Task AssignedInPartialClass2() - { - await TestMissingInRegularAndScriptAsync( + public Task AssignedInPartialClass2() + => TestMissingInRegularAndScriptAsync( """ partial class MyClass { @@ -823,12 +753,10 @@ void SetGoo() } } """); - } [Fact] - public async Task AssignedInPartialClass3() - { - await TestMissingInRegularAndScriptAsync( + public Task AssignedInPartialClass3() + => TestMissingInRegularAndScriptAsync( """ @@ -848,12 +776,10 @@ void SetGoo() """); - } [Fact] - public async Task PassedAsParameter() - { - await TestInRegularAndScript1Async( + public Task PassedAsParameter() + => TestInRegularAndScript1Async( """ class MyClass { @@ -880,12 +806,10 @@ void Bar(int goo) } } """); - } [Fact] - public async Task PassedAsOutParameter() - { - await TestMissingInRegularAndScriptAsync( + public Task PassedAsOutParameter() + => TestMissingInRegularAndScriptAsync( """ class MyClass { @@ -896,12 +820,10 @@ void Goo() } } """); - } [Fact] - public async Task PassedAsRefParameter() - { - await TestMissingInRegularAndScriptAsync( + public Task PassedAsRefParameter() + => TestMissingInRegularAndScriptAsync( """ class MyClass { @@ -915,12 +837,10 @@ void Bar(ref int goo) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33009")] - public async Task ReturnedByRef1() - { - await TestMissingInRegularAndScriptAsync( + public Task ReturnedByRef1() + => TestMissingInRegularAndScriptAsync( """ class MyClass { @@ -931,12 +851,10 @@ internal ref int Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33009")] - public async Task ReturnedByRef2() - { - await TestMissingInRegularAndScriptAsync( + public Task ReturnedByRef2() + => TestMissingInRegularAndScriptAsync( """ class MyClass { @@ -945,12 +863,10 @@ internal ref int Goo() => ref _goo; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33009")] - public async Task ReturnedByRef3() - { - await TestMissingInRegularAndScriptAsync( + public Task ReturnedByRef3() + => TestMissingInRegularAndScriptAsync( """ class MyClass { @@ -962,7 +878,6 @@ internal struct Accessor } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33009")] public async Task ReturnedByRef4() @@ -1021,9 +936,8 @@ internal ref int Goo(bool first) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33009")] - public async Task ReturnedByRef6() - { - await TestMissingInRegularAndScriptAsync( + public Task ReturnedByRef6() + => TestMissingInRegularAndScriptAsync( """ class MyClass { @@ -1039,12 +953,10 @@ ref int Local() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33009")] - public async Task ReturnedByRef7() - { - await TestMissingInRegularAndScriptAsync( + public Task ReturnedByRef7() + => TestMissingInRegularAndScriptAsync( """ class MyClass { @@ -1059,12 +971,10 @@ internal int Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33009")] - public async Task ReturnedByRef8() - { - await TestMissingInRegularAndScriptAsync( + public Task ReturnedByRef8() + => TestMissingInRegularAndScriptAsync( """ class MyClass { @@ -1079,12 +989,10 @@ internal int Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33009")] - public async Task ReturnedByRefReadonly1() - { - await TestInRegularAndScript1Async( + public Task ReturnedByRefReadonly1() + => TestInRegularAndScript1Async( """ class MyClass { @@ -1105,12 +1013,10 @@ internal ref readonly int Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33009")] - public async Task ReturnedByRefReadonly2() - { - await TestInRegularAndScript1Async( + public Task ReturnedByRefReadonly2() + => TestInRegularAndScript1Async( """ class MyClass { @@ -1127,12 +1033,10 @@ internal ref readonly int Goo() => ref _goo; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33009")] - public async Task ReturnedByRefReadonly3() - { - await TestInRegularAndScript1Async( + public Task ReturnedByRefReadonly3() + => TestInRegularAndScript1Async( """ class MyClass { @@ -1155,7 +1059,6 @@ internal struct Accessor } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33009")] public async Task ReturnedByRefReadonly4() @@ -1254,9 +1157,8 @@ internal ref readonly int Goo(bool first) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33009")] - public async Task ReturnedByRefReadonly6() - { - await TestInRegularAndScript1Async( + public Task ReturnedByRefReadonly6() + => TestInRegularAndScript1Async( """ class MyClass { @@ -1287,12 +1189,10 @@ ref readonly int Local() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33009")] - public async Task ReturnedByRefReadonly7() - { - await TestInRegularAndScript1Async( + public Task ReturnedByRefReadonly7() + => TestInRegularAndScript1Async( """ class MyClass { @@ -1321,12 +1221,10 @@ internal int Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33009")] - public async Task ReturnedByRefReadonly8() - { - await TestInRegularAndScript1Async( + public Task ReturnedByRefReadonly8() + => TestInRegularAndScript1Async( """ class MyClass { @@ -1355,12 +1253,10 @@ internal int Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33009")] - public async Task ConditionOfRefConditional1() - { - await TestInRegularAndScript1Async( + public Task ConditionOfRefConditional1() + => TestInRegularAndScript1Async( """ class MyClass { @@ -1383,12 +1279,10 @@ internal ref int Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33009")] - public async Task ConditionOfRefConditional2() - { - await TestInRegularAndScript1Async( + public Task ConditionOfRefConditional2() + => TestInRegularAndScript1Async( """ class MyClass { @@ -1407,12 +1301,10 @@ internal ref int Goo() => ref (_a ? ref _b : ref _b); } """); - } [Fact] - public async Task PassedAsOutParameterInCtor() - { - await TestInRegularAndScript1Async( + public Task PassedAsOutParameterInCtor() + => TestInRegularAndScript1Async( """ class MyClass { @@ -1433,12 +1325,10 @@ class MyClass } } """); - } [Fact] - public async Task PassedAsRefParameterInCtor() - { - await TestInRegularAndScript1Async( + public Task PassedAsRefParameterInCtor() + => TestInRegularAndScript1Async( """ class MyClass { @@ -1465,12 +1355,10 @@ void Bar(ref int goo) } } """); - } [Fact] - public async Task StaticFieldAssignedInStaticCtor() - { - await TestInRegularAndScript1Async( + public Task StaticFieldAssignedInStaticCtor() + => TestInRegularAndScript1Async( """ class MyClass { @@ -1491,12 +1379,10 @@ static MyClass() } } """); - } [Fact] - public async Task StaticFieldAssignedInNonStaticCtor() - { - await TestMissingInRegularAndScriptAsync( + public Task StaticFieldAssignedInNonStaticCtor() + => TestMissingInRegularAndScriptAsync( """ class MyClass { @@ -1507,12 +1393,10 @@ class MyClass } } """); - } [Fact] - public async Task FieldTypeIsMutableStruct() - { - await TestMissingInRegularAndScriptAsync( + public Task FieldTypeIsMutableStruct() + => TestMissingInRegularAndScriptAsync( """ struct MyStruct { @@ -1523,12 +1407,10 @@ class MyClass private MyStruct [|_goo|]; } """); - } [Fact] - public async Task FieldTypeIsCustomImmutableStruct() - { - await TestInRegularAndScript1Async( + public Task FieldTypeIsCustomImmutableStruct() + => TestInRegularAndScript1Async( """ struct MyStruct { @@ -1553,12 +1435,10 @@ class MyClass private readonly MyStruct _goo; } """); - } [Fact] - public async Task FixAll() - { - await TestInRegularAndScript1Async( + public Task FixAll() + => TestInRegularAndScript1Async( """ class MyClass { @@ -1581,12 +1461,10 @@ class MyClass void Method() { _z = 1; } } """); - } [Fact] - public async Task FixAll2() - { - await TestInRegularAndScript1Async( + public Task FixAll2() + => TestInRegularAndScript1Async( """ using System; @@ -1629,12 +1507,10 @@ partial struct MyClass partial struct MyClass { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26262")] - public async Task FieldAssignedInCtor_InParens() - { - await TestInRegularAndScript1Async( + public Task FieldAssignedInCtor_InParens() + => TestInRegularAndScript1Async( """ class MyClass { @@ -1655,12 +1531,10 @@ class MyClass } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26262")] - public async Task FieldAssignedInCtor_QualifiedWithThis_InParens() - { - await TestInRegularAndScript1Async( + public Task FieldAssignedInCtor_QualifiedWithThis_InParens() + => TestInRegularAndScript1Async( """ class MyClass { @@ -1681,12 +1555,10 @@ class MyClass } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26264")] - public async Task FieldAssignedInMethod_InDeconstruction() - { - await TestMissingAsync( + public Task FieldAssignedInMethod_InDeconstruction() + => TestMissingAsync( """ class C { @@ -1699,12 +1571,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26264")] - public async Task FieldAssignedInMethod_InDeconstruction_InParens() - { - await TestMissingAsync( + public Task FieldAssignedInMethod_InDeconstruction_InParens() + => TestMissingAsync( """ class C { @@ -1717,12 +1587,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26264")] - public async Task FieldAssignedInMethod_InDeconstruction_WithThis_InParens() - { - await TestMissingAsync( + public Task FieldAssignedInMethod_InDeconstruction_WithThis_InParens() + => TestMissingAsync( """ class C { @@ -1735,12 +1603,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26264")] - public async Task FieldUsedInTupleExpressionOnRight() - { - await TestInRegularAndScript1Async( + public Task FieldUsedInTupleExpressionOnRight() + => TestInRegularAndScript1Async( """ class C { @@ -1765,12 +1631,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26264")] - public async Task FieldInTypeWithGeneratedCode() - { - await TestInRegularAndScript1Async( + public Task FieldInTypeWithGeneratedCode() + => TestInRegularAndScript1Async( """ class C { @@ -1797,24 +1661,20 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26364")] - public async Task FieldIsFixed() - { - await TestMissingInRegularAndScriptAsync( + public Task FieldIsFixed() + => TestMissingInRegularAndScriptAsync( """ unsafe struct S { [|private fixed byte b[8];|] } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38995")] - public async Task FieldAssignedToLocalRef() - { - await TestMissingAsync( + public Task FieldAssignedToLocalRef() + => TestMissingAsync( """ class Program { @@ -1827,12 +1687,10 @@ void M() } } """); - } [Fact] - public async Task FieldAssignedToLocalReadOnlyRef() - { - await TestInRegularAndScript1Async( + public Task FieldAssignedToLocalReadOnlyRef() + => TestInRegularAndScript1Async( """ class Program { @@ -1855,12 +1713,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26213")] - public async Task TestFieldAccessesOnLeftOfDot() - { - await TestInRegularAndScript1Async( + public Task TestFieldAccessesOnLeftOfDot() + => TestInRegularAndScript1Async( """ interface IFaceServiceClient { @@ -1893,12 +1749,10 @@ public static void Run() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42759")] - public async Task TestVolatileField1() - { - await TestInRegularAndScript1Async( + public Task TestVolatileField1() + => TestInRegularAndScript1Async( """ class TestClass { @@ -1911,12 +1765,10 @@ class TestClass private readonly object first; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42759")] - public async Task TestVolatileField2() - { - await TestInRegularAndScript1Async( + public Task TestVolatileField2() + => TestInRegularAndScript1Async( """ class TestClass { @@ -1930,12 +1782,10 @@ class TestClass private volatile object second; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42759")] - public async Task TestVolatileField3() - { - await TestInRegularAndScript1Async( + public Task TestVolatileField3() + => TestInRegularAndScript1Async( """ class TestClass { @@ -1949,12 +1799,10 @@ class TestClass private readonly object second; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46785")] - public async Task UsedAsRef_NoDiagnostic() - { - await TestMissingInRegularAndScriptAsync( + public Task UsedAsRef_NoDiagnostic() + => TestMissingInRegularAndScriptAsync( """ public class C { @@ -1967,12 +1815,10 @@ public bool M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57983")] - public async Task UsedAsRef_NoDiagnostic_02() - { - await TestMissingInRegularAndScriptAsync( + public Task UsedAsRef_NoDiagnostic_02() + => TestMissingInRegularAndScriptAsync( """ using System.Runtime.CompilerServices; @@ -1988,12 +1834,10 @@ internal void Repro() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42760")] - public async Task WithThreadStaticAttribute_NoDiagnostic() - { - await TestMissingInRegularAndScriptAsync( + public Task WithThreadStaticAttribute_NoDiagnostic() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2003,12 +1847,10 @@ class Program private static object [|t_obj|]; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50925")] - public async Task Test_MemberUsedInGeneratedCode() - { - await TestMissingInRegularAndScriptAsync( + public Task Test_MemberUsedInGeneratedCode() + => TestMissingInRegularAndScriptAsync( """ @@ -2037,12 +1879,10 @@ public int Value """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40644")] - public async Task ShouldNotWarnForDataMemberFieldsInDataContractClasses() - { - await TestMissingAsync( + public Task ShouldNotWarnForDataMemberFieldsInDataContractClasses() + => TestMissingAsync( """ @@ -2057,12 +1897,10 @@ public class MyClass """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40644")] - public async Task ShouldWarnForDataMemberFieldsInNonDataContractClasses() - { - await TestInRegularAndScript1Async( + public Task ShouldWarnForDataMemberFieldsInNonDataContractClasses() + => TestInRegularAndScript1Async( """ @@ -2089,12 +1927,10 @@ public class MyClass """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40644")] - public async Task ShouldWarnForPrivateNonDataMemberFieldsInDataContractClasses() - { - await TestInRegularAndScript1Async( + public Task ShouldWarnForPrivateNonDataMemberFieldsInDataContractClasses() + => TestInRegularAndScript1Async( """ @@ -2127,12 +1963,10 @@ public class MyClass """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40644")] - public async Task ShouldNotWarnForPublicImplicitDataMemberFieldsInDataContractClasses() - { - await TestMissingAsync( + public Task ShouldNotWarnForPublicImplicitDataMemberFieldsInDataContractClasses() + => TestMissingAsync( """ @@ -2146,12 +1980,10 @@ public class MyClass """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/59577")] - public async Task TestInStruct() - { - await TestInRegularAndScript1Async( + public Task TestInStruct() + => TestInRegularAndScript1Async( """ struct MyClass { @@ -2164,12 +1996,10 @@ struct MyClass private readonly int _goo; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/59577")] - public async Task MissingForMemberInStructThatOverwritesThis() - { - await TestMissingAsync( + public Task MissingForMemberInStructThatOverwritesThis() + => TestMissingAsync( """ struct MyClass { @@ -2181,12 +2011,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38468")] - public async Task PreserveLeadingTrivia1() - { - await TestInRegularAndScript1Async( + public Task PreserveLeadingTrivia1() + => TestInRegularAndScript1Async( """ public class C { @@ -2203,12 +2031,10 @@ public class C readonly int y; } """); - } [Fact, WorkItem(47197, "https://github.com/dotnet/roslyn/issues/47197")] - public async Task StrictFeatureFlagAssignment1() - { - await TestInRegularAndScriptAsync( + public Task StrictFeatureFlagAssignment1() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -2237,12 +2063,10 @@ static C() } } """, parseOptions: s_strictFeatureFlag); - } [Fact, WorkItem(47197, "https://github.com/dotnet/roslyn/issues/47197")] - public async Task StrictFeatureFlagAssignment2() - { - await TestMissingInRegularAndScriptAsync( + public Task StrictFeatureFlagAssignment2() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -2257,12 +2081,10 @@ static C() } } """, new TestParameters(parseOptions: s_strictFeatureFlag)); - } [Fact, WorkItem(47197, "https://github.com/dotnet/roslyn/issues/47197")] - public async Task StrictFeatureFlagAssignment3() - { - await TestMissingInRegularAndScriptAsync( + public Task StrictFeatureFlagAssignment3() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -2277,12 +2099,10 @@ static C() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69143")] - public async Task DoNotAddReadonlyToInlineArrayInstanceMember() - { - await TestMissingInRegularAndScriptAsync($$""" + public Task DoNotAddReadonlyToInlineArrayInstanceMember() + => TestMissingInRegularAndScriptAsync($$""" using System; using System.Runtime.CompilerServices; @@ -2294,12 +2114,10 @@ struct S private int [|i|]; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75995")] - public async Task AddReadonlyToInlineArrayStaticMember1() - { - await TestInRegularAndScriptAsync($$""" + public Task AddReadonlyToInlineArrayStaticMember1() + => TestInRegularAndScriptAsync($$""" using System; using System.Runtime.CompilerServices; @@ -2322,12 +2140,10 @@ struct S private static readonly int j; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47198")] - public async Task TestIndexedAndAssignedField_StructType() - { - await TestMissingAsync( + public Task TestIndexedAndAssignedField_StructType() + => TestMissingAsync( """ class GreenNode { } @@ -2349,12 +2165,10 @@ public AddSkippedTrivia(GreenNode trivia) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47198")] - public async Task TestIndexedAndAssignedField_ClassType() - { - await TestInRegularAndScript1Async( + public Task TestIndexedAndAssignedField_ClassType() + => TestInRegularAndScript1Async( """ class GreenNode { } @@ -2399,12 +2213,10 @@ public AddSkippedTrivia(GreenNode trivia) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49290")] - public async Task TestPropertyMutatedField_StructType() - { - await TestMissingAsync( + public Task TestPropertyMutatedField_StructType() + => TestMissingAsync( """ interface I { @@ -2418,12 +2230,10 @@ class C where T : struct, I public void Foo() => _x.P = 42; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49290")] - public async Task TestPropertyMutatedField_ClassType() - { - await TestInRegularAndScript1Async( + public Task TestPropertyMutatedField_ClassType() + => TestInRegularAndScript1Async( """ interface I { @@ -2450,5 +2260,4 @@ class C where T : class, I public void Foo() => _x.P = 42; } """); - } } diff --git a/src/Analyzers/CSharp/Tests/MakeLocalFunctionStatic/MakeLocalFunctionStaticTests.cs b/src/Analyzers/CSharp/Tests/MakeLocalFunctionStatic/MakeLocalFunctionStaticTests.cs index b26afec63e03d..4dcccd5e1bc03 100644 --- a/src/Analyzers/CSharp/Tests/MakeLocalFunctionStatic/MakeLocalFunctionStaticTests.cs +++ b/src/Analyzers/CSharp/Tests/MakeLocalFunctionStatic/MakeLocalFunctionStaticTests.cs @@ -31,9 +31,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider private static readonly ParseOptions CSharp8ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] - public async Task TestAboveCSharp8() - { - await TestInRegularAndScriptAsync( + public Task TestAboveCSharp8() + => TestInRegularAndScriptAsync( """ using System; @@ -62,13 +61,11 @@ static int fibonacci(int n) } } """, -parseOptions: CSharp8ParseOptions); - } + parseOptions: CSharp8ParseOptions); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseSimpleUsingStatement)] - public async Task TestWithOptionOff() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithOptionOff() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -86,12 +83,10 @@ void M() new TestParameters( parseOptions: CSharp8ParseOptions, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOption2.FalseWithSilentEnforcement))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] - public async Task TestMissingIfAlreadyStatic() - { - await TestMissingAsync( + public Task TestMissingIfAlreadyStatic() + => TestMissingAsync( """ using System; @@ -106,12 +101,10 @@ void M() } } """, parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] - public async Task TestMissingPriorToCSharp8() - { - await TestMissingAsync( + public Task TestMissingPriorToCSharp8() + => TestMissingAsync( """ using System; @@ -126,12 +119,10 @@ void M() } } """, parameters: new TestParameters(parseOptions: CSharp72ParseOptions)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] - public async Task TestMissingIfCapturesValue() - { - await TestMissingAsync( + public Task TestMissingIfCapturesValue() + => TestMissingAsync( """ using System; @@ -146,12 +137,10 @@ void M(int i) } } """, parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] - public async Task TestMissingIfCapturesThis() - { - await TestMissingAsync( + public Task TestMissingIfCapturesThis() + => TestMissingAsync( """ using System; @@ -167,12 +156,10 @@ void M() } } """, parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] - public async Task TestAsyncFunction() - { - await TestInRegularAndScriptAsync( + public Task TestAsyncFunction() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -204,15 +191,13 @@ static async Task fibonacci(int n) } """, parseOptions: CSharp8ParseOptions); - } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [InlineData("")] [InlineData("\r\n")] [InlineData("\r\n\r\n")] - public async Task TestLeadingTriviaAfterSemicolon(string leadingTrivia) - { - await TestInRegularAndScriptAsync( + public Task TestLeadingTriviaAfterSemicolon(string leadingTrivia) + => TestInRegularAndScriptAsync( $$""" using System; @@ -244,15 +229,13 @@ static int fibonacci(int n) } """, parseOptions: CSharp8ParseOptions); - } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [InlineData("")] [InlineData("\r\n")] [InlineData("\r\n\r\n")] - public async Task TestLeadingTriviaAfterOpenBrace(string leadingTrivia) - { - await TestInRegularAndScriptAsync( + public Task TestLeadingTriviaAfterOpenBrace(string leadingTrivia) + => TestInRegularAndScriptAsync( $$""" using System; @@ -282,31 +265,31 @@ static int fibonacci(int n) } """, parseOptions: CSharp8ParseOptions); - } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [InlineData("")] [InlineData("\r\n")] [InlineData("\r\n\r\n")] - public async Task TestLeadingTriviaAfterLocalFunction(string leadingTrivia) - { - await TestInRegularAndScriptAsync( -$@"using System; + public Task TestLeadingTriviaAfterLocalFunction(string leadingTrivia) + => TestInRegularAndScriptAsync( + $$""" + using System; -class C -{{ - void M() - {{ - bool otherFunction() - {{ - return true; - }}{leadingTrivia} - int [||]fibonacci(int n) - {{ - return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); - }} - }} -}}", + class C + { + void M() + { + bool otherFunction() + { + return true; + }{{leadingTrivia}} + int [||]fibonacci(int n) + { + return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); + } + } + } + """, $$""" using System; @@ -326,25 +309,25 @@ static int fibonacci(int n) } """, parseOptions: CSharp8ParseOptions); - } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [InlineData("")] [InlineData("\r\n")] [InlineData("\r\n\r\n")] - public async Task TestLeadingTriviaAfterExpressionBodyLocalFunction(string leadingTrivia) - { - await TestInRegularAndScriptAsync( -$@"using System; + public Task TestLeadingTriviaAfterExpressionBodyLocalFunction(string leadingTrivia) + => TestInRegularAndScriptAsync( + $$""" + using System; -class C -{{ - void M() - {{ - bool otherFunction() => true;{leadingTrivia} - int [||]fibonacci(int n) => n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); - }} -}}", + class C + { + void M() + { + bool otherFunction() => true;{{leadingTrivia}} + int [||]fibonacci(int n) => n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); + } + } + """, $$""" using System; @@ -358,84 +341,86 @@ void M() } """, parseOptions: CSharp8ParseOptions); - } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [InlineData("")] [InlineData("\r\n")] [InlineData("\r\n\r\n")] - public async Task TestLeadingTriviaAfterComment(string leadingTrivia) - { - await TestInRegularAndScriptAsync( -$@"using System; + public Task TestLeadingTriviaAfterComment(string leadingTrivia) + => TestInRegularAndScriptAsync( + $$""" + using System; -class C -{{ - void M() - {{ - //Local function comment{leadingTrivia} - int [||]fibonacci(int n) - {{ - return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); - }} - }} -}}", -$@"using System; + class C + { + void M() + { + //Local function comment{{leadingTrivia}} + int [||]fibonacci(int n) + { + return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); + } + } + } + """, + $$""" + using System; -class C -{{ - void M() - {{ - //Local function comment{leadingTrivia} - static int fibonacci(int n) - {{ - return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); - }} - }} -}}", + class C + { + void M() + { + //Local function comment{{leadingTrivia}} + static int fibonacci(int n) + { + return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); + } + } + } + """, parseOptions: CSharp8ParseOptions); - } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [InlineData("\r\n")] [InlineData("\r\n\r\n")] - public async Task TestLeadingTriviaBeforeComment(string leadingTrivia) - { - await TestInRegularAndScriptAsync( -$@"using System; + public Task TestLeadingTriviaBeforeComment(string leadingTrivia) + => TestInRegularAndScriptAsync( + $$""" + using System; -class C -{{ - void M() - {{{leadingTrivia} - //Local function comment - int [||]fibonacci(int n) - {{ - return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); - }} - }} -}}", -$@"using System; + class C + { + void M() + {{{leadingTrivia}} + //Local function comment + int [||]fibonacci(int n) + { + return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); + } + } + } + """, + $$""" + using System; -class C -{{ - void M() - {{{leadingTrivia} - //Local function comment - static int fibonacci(int n) - {{ - return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); - }} - }} -}}", + class C + { + void M() + {{{leadingTrivia}} + //Local function comment + static int fibonacci(int n) + { + return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); + } + } + } + """, parseOptions: CSharp8ParseOptions); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [WorkItem("https://github.com/dotnet/roslyn/issues/46858")] - public async Task TestMissingIfAnotherLocalFunctionCalled() - { - await TestMissingAsync( + public Task TestMissingIfAnotherLocalFunctionCalled() + => TestMissingAsync( """ using System; @@ -454,12 +439,10 @@ void B() } } """, parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] - public async Task TestCallingStaticLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestCallingStaticLocalFunction() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -498,13 +481,11 @@ static void B() } } """, -parseOptions: CSharp8ParseOptions); - } + parseOptions: CSharp8ParseOptions); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] - public async Task TestCallingNestedLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestCallingNestedLocalFunction() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -543,14 +524,12 @@ void B() } } """, -parseOptions: CSharp8ParseOptions); - } + parseOptions: CSharp8ParseOptions); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [WorkItem("https://github.com/dotnet/roslyn/issues/53179")] - public async Task TestLocalFunctionAsTopLevelStatement() - { - await TestAsync(""" + public Task TestLocalFunctionAsTopLevelStatement() + => TestAsync(""" void [||]A() { } @@ -560,13 +539,11 @@ static void A() } """, parseOptions: CSharp8ParseOptions); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [WorkItem("https://github.com/dotnet/roslyn/issues/59286")] - public async Task TestUnsafeLocalFunction() - { - await TestAsync(""" + public Task TestUnsafeLocalFunction() + => TestAsync(""" unsafe void [||]A() { } @@ -576,5 +553,4 @@ static unsafe void A() } """, parseOptions: CSharp8ParseOptions); - } } diff --git a/src/Analyzers/CSharp/Tests/MakeMemberRequired/MakeMemberRequiredTests.cs b/src/Analyzers/CSharp/Tests/MakeMemberRequired/MakeMemberRequiredTests.cs index 3af2b2741c6af..6cd4689e68f30 100644 --- a/src/Analyzers/CSharp/Tests/MakeMemberRequired/MakeMemberRequiredTests.cs +++ b/src/Analyzers/CSharp/Tests/MakeMemberRequired/MakeMemberRequiredTests.cs @@ -121,29 +121,23 @@ public static IEnumerable AccessorAccessibilityModifierCombinationsWhe } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68478")] - public async Task SimpleSetPropertyMissingRequiredAttribute() - { - var code = - """ + public Task SimpleSetPropertyMissingRequiredAttribute() + => new VerifyCS.Test + { + TestCode = """ #nullable enable class MyClass { public string {|CS8618:MyProperty|} { get; set; } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact] - public async Task SimpleSetProperty() - { - await new VerifyCS.Test + public Task SimpleSetProperty() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -162,12 +156,10 @@ class MyClass LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net70 }.RunAsync(); - } [Fact] - public async Task SimpleInitProperty() - { - await new VerifyCS.Test + public Task SimpleInitProperty() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -186,33 +178,27 @@ class MyClass LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net70 }.RunAsync(); - } [Fact] - public async Task NotOnGetOnlyProperty() - { - var code = """ + public Task NotOnGetOnlyProperty() + => new VerifyCS.Test + { + TestCode = """ #nullable enable class MyClass { public string {|CS8618:MyProperty|} { get; } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net70 }.RunAsync(); - } [Theory] [MemberData(nameof(MemberAccessibilityModifierCombinationsWhereShouldProvideFix))] - public async Task TestEffectivePropertyAccessibilityWhereShouldProvideFix(string outerClassAccessibility, string containingTypeAccessibility, string propertyAccessibility) - { - await new VerifyCS.Test + public Task TestEffectivePropertyAccessibilityWhereShouldProvideFix(string outerClassAccessibility, string containingTypeAccessibility, string propertyAccessibility) + => new VerifyCS.Test { TestCode = $$""" #nullable enable @@ -239,13 +225,11 @@ public async Task TestEffectivePropertyAccessibilityWhereShouldProvideFix(string LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net70 }.RunAsync(); - } [Theory] [MemberData(nameof(MemberAccessibilityModifierCombinationsWhereShouldNotProvideFix))] - public async Task TestEffectivePropertyAccessibilityWhereShouldNotProvideFix(string outerClassAccessibility, string containingTypeAccessibility, string propertyAccessibility) - { - await new VerifyCS.Test + public Task TestEffectivePropertyAccessibilityWhereShouldNotProvideFix(string outerClassAccessibility, string containingTypeAccessibility, string propertyAccessibility) + => new VerifyCS.Test { TestCode = $$""" #nullable enable @@ -261,13 +245,11 @@ public async Task TestEffectivePropertyAccessibilityWhereShouldNotProvideFix(str LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net70 }.RunAsync(); - } [Theory] [MemberData(nameof(AccessorAccessibilityModifierCombinationsWhereShouldProvideFix))] - public async Task TestSetAccessorAccessibilityWhereShouldProvideFix(string containingTypeAccessibility, string setAccessorAccessibility) - { - await new VerifyCS.Test + public Task TestSetAccessorAccessibilityWhereShouldProvideFix(string containingTypeAccessibility, string setAccessorAccessibility) + => new VerifyCS.Test { TestCode = $$""" #nullable enable @@ -288,13 +270,11 @@ public async Task TestSetAccessorAccessibilityWhereShouldProvideFix(string conta LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net70 }.RunAsync(); - } [Theory] [MemberData(nameof(AccessorAccessibilityModifierCombinationsWhereShouldNotProvideFix))] - public async Task TestSetAccessorAccessibilityWhereShouldNotProvideFix(string containingTypeAccessibility, string setAccessorAccessibility) - { - await new VerifyCS.Test + public Task TestSetAccessorAccessibilityWhereShouldNotProvideFix(string containingTypeAccessibility, string setAccessorAccessibility) + => new VerifyCS.Test { TestCode = $$""" #nullable enable @@ -307,13 +287,11 @@ public async Task TestSetAccessorAccessibilityWhereShouldNotProvideFix(string co LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net70 }.RunAsync(); - } [Theory] [MemberData(nameof(AccessorAccessibilityModifierCombinationsWhereShouldProvideFix))] - public async Task TestInitAccessorAccessibilityWhereShouldProvideFix(string containingTypeAccessibility, string setAccessorAccessibility) - { - await new VerifyCS.Test + public Task TestInitAccessorAccessibilityWhereShouldProvideFix(string containingTypeAccessibility, string setAccessorAccessibility) + => new VerifyCS.Test { TestCode = $$""" #nullable enable @@ -334,13 +312,11 @@ public async Task TestInitAccessorAccessibilityWhereShouldProvideFix(string cont LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net70 }.RunAsync(); - } [Theory] [MemberData(nameof(AccessorAccessibilityModifierCombinationsWhereShouldNotProvideFix))] - public async Task TestInitAccessorAccessibilityWhereShouldNotProvideFix(string containingTypeAccessibility, string setAccessorAccessibility) - { - await new VerifyCS.Test + public Task TestInitAccessorAccessibilityWhereShouldNotProvideFix(string containingTypeAccessibility, string setAccessorAccessibility) + => new VerifyCS.Test { TestCode = $$""" #nullable enable @@ -353,12 +329,10 @@ public async Task TestInitAccessorAccessibilityWhereShouldNotProvideFix(string c LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net70 }.RunAsync(); - } [Fact] - public async Task SimpleField() - { - await new VerifyCS.Test + public Task SimpleField() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -379,13 +353,11 @@ class MyClass LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net70 }.RunAsync(); - } [Theory] [MemberData(nameof(MemberAccessibilityModifierCombinationsWhereShouldProvideFix))] - public async Task TestEffectiveFieldAccessibilityWhereShouldProvideFix(string outerClassAccessibility, string containingTypeAccessibility, string fieldAccessibility) - { - await new VerifyCS.Test + public Task TestEffectiveFieldAccessibilityWhereShouldProvideFix(string outerClassAccessibility, string containingTypeAccessibility, string fieldAccessibility) + => new VerifyCS.Test { TestCode = $$""" #nullable enable @@ -412,13 +384,11 @@ public async Task TestEffectiveFieldAccessibilityWhereShouldProvideFix(string ou LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net70 }.RunAsync(); - } [Theory] [MemberData(nameof(MemberAccessibilityModifierCombinationsWhereShouldNotProvideFix))] - public async Task TestEffectiveFieldAccessibilityWhereShouldNotProvideFix(string outerClassAccessibility, string containingTypeAccessibility, string fieldAccessibility) - { - await new VerifyCS.Test + public Task TestEffectiveFieldAccessibilityWhereShouldNotProvideFix(string outerClassAccessibility, string containingTypeAccessibility, string fieldAccessibility) + => new VerifyCS.Test { TestCode = $$""" #nullable enable @@ -434,32 +404,28 @@ public async Task TestEffectiveFieldAccessibilityWhereShouldNotProvideFix(string LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net70 }.RunAsync(); - } [Fact] - public async Task NotForLowerVersionOfCSharp() - { - var code = """ + public Task NotForLowerVersionOfCSharp() + => new VerifyCS.Test + { + TestCode = """ #nullable enable class MyClass { public string {|CS8618:MyProperty|} { get; set; } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp10, ReferenceAssemblies = ReferenceAssemblies.Net.Net70 }.RunAsync(); - } [Fact] - public async Task NotOnConstructorDeclaration() - { - var code = """ + public Task NotOnConstructorDeclaration() + => new VerifyCS.Test + { + TestCode = """ #nullable enable class MyClass @@ -467,40 +433,30 @@ class MyClass public string MyProperty { get; set; } public {|CS8618:MyClass|}() { } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net70 }.RunAsync(); - } [Fact] - public async Task NotOnEventDeclaration() - { - var code = """ + public Task NotOnEventDeclaration() + => new VerifyCS.Test + { + TestCode = """ #nullable enable class MyClass { public event System.EventHandler {|CS8618:MyEvent|}; } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net70 }.RunAsync(); - } [Fact] - public async Task FixAll1() - { - await new VerifyCS.Test + public Task FixAll1() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -521,12 +477,10 @@ class MyClass LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net70 }.RunAsync(); - } [Fact] - public async Task FixAll2() - { - await new VerifyCS.Test + public Task FixAll2() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -547,12 +501,10 @@ class MyClass LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net70 }.RunAsync(); - } [Fact] - public async Task FixAll3() - { - await new VerifyCS.Test + public Task FixAll3() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -571,12 +523,10 @@ class MyClass LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net70 }.RunAsync(); - } [Fact] - public async Task FixAll4() - { - await new VerifyCS.Test + public Task FixAll4() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -595,12 +545,10 @@ class MyClass LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net70 }.RunAsync(); - } [Fact] - public async Task FixAll5() - { - await new VerifyCS.Test + public Task FixAll5() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -621,12 +569,10 @@ class MyClass LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net70 }.RunAsync(); - } [Fact] - public async Task TwoFieldDeclaratorsWithOneIssue() - { - await new VerifyCS.Test + public Task TwoFieldDeclaratorsWithOneIssue() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -645,5 +591,4 @@ class MyClass LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net70 }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/MakeMemberStatic/MakeMemberStaticTests.cs b/src/Analyzers/CSharp/Tests/MakeMemberStatic/MakeMemberStaticTests.cs index 436553fd03b22..7dd86d0b1eee6 100644 --- a/src/Analyzers/CSharp/Tests/MakeMemberStatic/MakeMemberStaticTests.cs +++ b/src/Analyzers/CSharp/Tests/MakeMemberStatic/MakeMemberStaticTests.cs @@ -20,9 +20,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeMemberStatic; public sealed class MakeMemberStaticTests { [Fact] - public async Task TestField() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestField() + => VerifyCS.VerifyCodeFixAsync( """ public static class Foo { @@ -35,12 +34,10 @@ public static class Foo static int i; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/54202")] - public async Task TestTrivia() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestTrivia() + => VerifyCS.VerifyCodeFixAsync( """ public static class Foo { @@ -55,12 +52,10 @@ public static class Foo static readonly int i; } """); - } [Fact] - public async Task TestMethod() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestMethod() + => VerifyCS.VerifyCodeFixAsync( """ public static class Foo { @@ -73,12 +68,10 @@ public static class Foo static void M() { } } """); - } [Fact] - public async Task TestProperty() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestProperty() + => VerifyCS.VerifyCodeFixAsync( """ public static class Foo { @@ -91,12 +84,10 @@ public static class Foo static object P { get; set; } } """); - } [Fact] - public async Task TestEventField() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestEventField() + => VerifyCS.VerifyCodeFixAsync( """ public static class Foo { @@ -109,12 +100,10 @@ public static class Foo static event System.Action E; } """); - } [Fact] - public async Task FixAll() - { - await VerifyCS.VerifyCodeFixAsync( + public Task FixAll() + => VerifyCS.VerifyCodeFixAsync( """ namespace NS { @@ -139,5 +128,4 @@ static void M() { } } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/MakeMethodAsynchronous/MakeMethodAsynchronousTests.cs b/src/Analyzers/CSharp/Tests/MakeMethodAsynchronous/MakeMethodAsynchronousTests.cs index d52397085da8d..0281b9d43df82 100644 --- a/src/Analyzers/CSharp/Tests/MakeMethodAsynchronous/MakeMethodAsynchronousTests.cs +++ b/src/Analyzers/CSharp/Tests/MakeMethodAsynchronous/MakeMethodAsynchronousTests.cs @@ -23,10 +23,8 @@ internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProvide => (null, new CSharpMakeMethodAsynchronousCodeFixProvider()); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33082")] - public async Task AwaitInVoidMethodWithModifiers() - { - var initial = - """ + public Task AwaitInVoidMethodWithModifiers() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; @@ -37,10 +35,7 @@ public static void Test() [|await Task.Delay(1);|] } } - """; - - var expected = - """ + """, """ using System; using System.Threading.Tasks; @@ -51,9 +46,7 @@ public static async void Test() await Task.Delay(1); } } - """; - await TestInRegularAndScriptAsync(initial, expected, index: 1); - } + """, index: 1); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26312")] public async Task AwaitInTaskMainMethodWithModifiers() @@ -71,9 +64,7 @@ public static void Main() } } """; - - var expected = - """ + await TestAsync(initial, """ using System; using System.Threading.Tasks; @@ -84,8 +75,7 @@ public static async Task Main() await Task.Delay(1); } } - """; - await TestAsync(initial, expected, parseOptions: CSharpParseOptions.Default, + """, parseOptions: CSharpParseOptions.Default, compilationOptions: new CSharpCompilationOptions(OutputKind.ConsoleApplication)); // no option offered to keep void @@ -94,10 +84,8 @@ await TestAsync(initial, expected, parseOptions: CSharpParseOptions.Default, [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26312")] [WorkItem("https://github.com/dotnet/roslyn/issues/33082")] - public async Task AwaitInVoidMainMethodWithModifiers_NotEntryPoint() - { - var initial = - """ + public Task AwaitInVoidMainMethodWithModifiers_NotEntryPoint() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; @@ -108,10 +96,7 @@ public void Main() [|await Task.Delay(1);|] } } - """; - - var expected = - """ + """, """ using System; using System.Threading.Tasks; @@ -122,15 +107,11 @@ public async void Main() await Task.Delay(1); } } - """; - await TestInRegularAndScriptAsync(initial, expected, index: 1); - } + """, index: 1); [Fact] - public async Task AwaitInVoidMethodWithModifiers2() - { - var initial = - """ + public Task AwaitInVoidMethodWithModifiers2() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; @@ -141,10 +122,7 @@ public static void Test() [|await Task.Delay(1);|] } } - """; - - var expected = - """ + """, """ using System; using System.Threading.Tasks; @@ -155,15 +133,11 @@ public static async Task TestAsync() await Task.Delay(1); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33082")] - public async Task AwaitInTaskMethodNoModifiers() - { - var initial = - """ + public Task AwaitInTaskMethodNoModifiers() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; @@ -174,10 +148,7 @@ Task Test() [|await Task.Delay(1);|] } } - """; - - var expected = - """ + """, """ using System; using System.Threading.Tasks; @@ -188,15 +159,11 @@ async Task Test() await Task.Delay(1); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33082")] - public async Task AwaitInTaskMethodWithModifiers() - { - var initial = - """ + public Task AwaitInTaskMethodWithModifiers() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; @@ -207,10 +174,7 @@ class Program [|await Task.Delay(1);|] } } - """; - - var expected = - """ + """, """ using System; using System.Threading.Tasks; @@ -221,15 +185,11 @@ class Program await Task.Delay(1); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task AwaitInLambdaFunction() - { - var initial = - """ + public Task AwaitInLambdaFunction() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; @@ -241,10 +201,7 @@ static void Main(string[] args) Func b = () => [|await Task.Run(a);|] } } - """; - - var expected = - """ + """, """ using System; using System.Threading.Tasks; @@ -256,15 +213,11 @@ static void Main(string[] args) Func b = async () => await Task.Run(a); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task AwaitInLambdaAction() - { - var initial = - """ + public Task AwaitInLambdaAction() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; @@ -275,10 +228,7 @@ static void Main(string[] args) Action a = () => [|await Task.Delay(1);|] } } - """; - - var expected = - """ + """, """ using System; using System.Threading.Tasks; @@ -289,15 +239,11 @@ static void Main(string[] args) Action a = async () => await Task.Delay(1); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33082")] - public async Task BadAwaitInNonAsyncMethod() - { - var initial = - """ + public Task BadAwaitInNonAsyncMethod() + => TestInRegularAndScriptAsync(""" using System.Threading.Tasks; class Program { @@ -306,10 +252,7 @@ void Test() [|await Task.Delay(1);|] } } - """; - - var expected = - """ + """, """ using System.Threading.Tasks; class Program { @@ -318,15 +261,11 @@ async void Test() await Task.Delay(1); } } - """; - await TestInRegularAndScriptAsync(initial, expected, index: 1); - } + """, index: 1); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33082")] - public async Task BadAwaitInNonAsyncMethod2() - { - var initial = - """ + public Task BadAwaitInNonAsyncMethod2() + => TestInRegularAndScriptAsync(""" using System.Threading.Tasks; class Program { @@ -335,10 +274,7 @@ Task Test() [|await Task.Delay(1);|] } } - """; - - var expected = - """ + """, """ using System.Threading.Tasks; class Program { @@ -347,15 +283,11 @@ async Task Test() await Task.Delay(1); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33082")] - public async Task BadAwaitInNonAsyncMethod3() - { - var initial = - """ + public Task BadAwaitInNonAsyncMethod3() + => TestInRegularAndScriptAsync(""" using System.Threading.Tasks; class Program { @@ -364,10 +296,7 @@ Task Test() [|await Task.Delay(1);|] } } - """; - - var expected = - """ + """, """ using System.Threading.Tasks; class Program { @@ -376,15 +305,11 @@ async Task Test() await Task.Delay(1); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task BadAwaitInNonAsyncMethod4() - { - var initial = - """ + public Task BadAwaitInNonAsyncMethod4() + => TestInRegularAndScriptAsync(""" using System.Threading.Tasks; class Program { @@ -393,10 +318,7 @@ int Test() [|await Task.Delay(1);|] } } - """; - - var expected = - """ + """, """ using System.Threading.Tasks; class Program { @@ -405,15 +327,11 @@ async Task TestAsync() await Task.Delay(1); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33082")] - public async Task BadAwaitInNonAsyncMethod5() - { - var initial = - """ + public Task BadAwaitInNonAsyncMethod5() + => TestInRegularAndScriptAsync(""" class Program { void Test() @@ -421,10 +339,7 @@ void Test() [|await Task.Delay(1);|] } } - """; - - var expected = - """ + """, """ class Program { async void Test() @@ -432,15 +347,11 @@ async void Test() await Task.Delay(1); } } - """; - await TestInRegularAndScriptAsync(initial, expected, index: 1); - } + """, index: 1); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33082")] - public async Task BadAwaitInNonAsyncMethod6() - { - var initial = - """ + public Task BadAwaitInNonAsyncMethod6() + => TestInRegularAndScriptAsync(""" class Program { Task Test() @@ -448,10 +359,7 @@ Task Test() [|await Task.Delay(1);|] } } - """; - - var expected = - """ + """, """ class Program { async Task Test() @@ -459,15 +367,11 @@ async Task Test() await Task.Delay(1); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33082")] - public async Task BadAwaitInNonAsyncMethod7() - { - var initial = - """ + public Task BadAwaitInNonAsyncMethod7() + => TestInRegularAndScriptAsync(""" class Program { Task Test() @@ -475,10 +379,7 @@ Task Test() [|await Task.Delay(1);|] } } - """; - - var expected = - """ + """, """ class Program { async Task Test() @@ -486,15 +387,11 @@ async Task Test() await Task.Delay(1); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task BadAwaitInNonAsyncMethod8() - { - var initial = - """ + public Task BadAwaitInNonAsyncMethod8() + => TestInRegularAndScriptAsync(""" class Program { int Test() @@ -502,10 +399,7 @@ int Test() [|await Task.Delay(1);|] } } - """; - - var expected = - """ + """, """ using System.Threading.Tasks; class Program @@ -515,15 +409,11 @@ async Task TestAsync() await Task.Delay(1); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task BadAwaitInNonAsyncMethod9() - { - var initial = - """ + public Task BadAwaitInNonAsyncMethod9() + => TestInRegularAndScriptAsync(""" class Program { Program Test() @@ -531,10 +421,7 @@ Program Test() [|await Task.Delay(1);|] } } - """; - - var expected = - """ + """, """ using System.Threading.Tasks; class Program @@ -544,15 +431,11 @@ async Task TestAsync() await Task.Delay(1); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task BadAwaitInNonAsyncMethod10() - { - var initial = - """ + public Task BadAwaitInNonAsyncMethod10() + => TestInRegularAndScriptAsync(""" class Program { asdf Test() @@ -560,10 +443,7 @@ asdf Test() [|await Task.Delay(1);|] } } - """; - - var expected = - """ + """, """ class Program { async System.Threading.Tasks.Task TestAsync() @@ -571,9 +451,7 @@ async System.Threading.Tasks.Task TestAsync() await Task.Delay(1); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] public async Task BadAwaitInEnumerableMethod() @@ -609,10 +487,8 @@ async IAsyncEnumerable TestAsync() } [Fact] - public async Task BadAwaitInEnumerableMethodMissingIAsyncEnumerableType() - { - var initial = - """ + public Task BadAwaitInEnumerableMethodMissingIAsyncEnumerableType() + => TestInRegularAndScriptAsync(""" using System.Threading.Tasks; using System.Collections.Generic; class Program @@ -623,10 +499,7 @@ IEnumerable Test() [|await Task.Delay(1);|] } } - """; - - var expected = - """ + """, """ using System.Threading.Tasks; using System.Collections.Generic; class Program @@ -637,15 +510,11 @@ async IAsyncEnumerable TestAsync() await Task.Delay(1); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task BadAwaitInEnumerableMethodWithReturn() - { - var initial = - """ + public Task BadAwaitInEnumerableMethodWithReturn() + => TestInRegularAndScriptAsync(""" using System.Threading.Tasks; using System.Collections.Generic; class Program @@ -656,10 +525,7 @@ IEnumerable Test() return null; } } - """; - - var expected = - """ + """, """ using System.Threading.Tasks; using System.Collections.Generic; class Program @@ -670,15 +536,11 @@ async Task> TestAsync() return null; } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task BadAwaitInEnumerableMethodWithYieldInsideLocalFunction() - { - var initial = - """ + public Task BadAwaitInEnumerableMethodWithYieldInsideLocalFunction() + => TestInRegularAndScriptAsync(""" using System.Threading.Tasks; using System.Collections.Generic; class Program @@ -694,10 +556,7 @@ IEnumerable local() } } } - """; - - var expected = - """ + """, """ using System.Threading.Tasks; using System.Collections.Generic; class Program @@ -713,15 +572,11 @@ IEnumerable local() } } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task BadAwaitInEnumeratorMethodWithReturn() - { - var initial = - """ + public Task BadAwaitInEnumeratorMethodWithReturn() + => TestInRegularAndScriptAsync(""" using System.Threading.Tasks; using System.Collections.Generic; class Program @@ -732,10 +587,7 @@ IEnumerator Test() return null; } } - """; - - var expected = - """ + """, """ using System.Threading.Tasks; using System.Collections.Generic; class Program @@ -746,9 +598,7 @@ async Task> TestAsync() return null; } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] public async Task BadAwaitInEnumeratorMethod() @@ -889,24 +739,19 @@ async IAsyncEnumerator Test() } [Fact] - public async Task AwaitInMember() - { - var code = - """ + public Task AwaitInMember() + => TestMissingInRegularAndScriptAsync(""" using System.Threading.Tasks; class Program { var x = [|await Task.Delay(3)|]; } - """; - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task AddAsyncInDelegate() - { - await TestInRegularAndScriptAsync( + public Task AddAsyncInDelegate() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -937,12 +782,10 @@ private async void method() } } """); - } [Fact] - public async Task AddAsyncInDelegate2() - { - await TestInRegularAndScriptAsync( + public Task AddAsyncInDelegate2() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -973,12 +816,10 @@ private void method() } } """); - } [Fact] - public async Task AddAsyncInDelegate3() - { - await TestInRegularAndScriptAsync( + public Task AddAsyncInDelegate3() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1009,12 +850,10 @@ private void method() } } """); - } [Fact, WorkItem(6477, @"https://github.com/dotnet/roslyn/issues/6477")] - public async Task NullNodeCrash() - { - await TestMissingInRegularAndScriptAsync( + public Task NullNodeCrash() + => TestMissingInRegularAndScriptAsync( """ using System.Threading.Tasks; @@ -1032,14 +871,11 @@ static async void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33082")] [WorkItem("https://github.com/dotnet/roslyn/issues/17470")] - public async Task AwaitInValueTaskMethod() - { - var initial = - """ + public Task AwaitInValueTaskMethod() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; @@ -1056,10 +892,7 @@ ValueTask Test() [|await Task.Delay(1);|] } } - """; - - var expected = - """ + """, """ using System; using System.Threading.Tasks; @@ -1076,15 +909,11 @@ async ValueTask Test() await Task.Delay(1); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task AwaitInValueTaskWithoutGenericMethod() - { - var initial = - """ + public Task AwaitInValueTaskWithoutGenericMethod() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; @@ -1101,10 +930,7 @@ ValueTask Test() [|await Task.Delay(1);|] } } - """; - - var expected = - """ + """, """ using System; using System.Threading.Tasks; @@ -1121,14 +947,11 @@ async ValueTask Test() await Task.Delay(1); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14133")] - public async Task AddAsyncInLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task AddAsyncInLocalFunction() + => TestInRegularAndScriptAsync( """ using System.Threading.Tasks; @@ -1167,13 +990,11 @@ async Task M3Async() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14133")] [WorkItem("https://github.com/dotnet/roslyn/issues/33082")] - public async Task AddAsyncInLocalFunctionKeepVoidReturn() - { - await TestInRegularAndScriptAsync( + public Task AddAsyncInLocalFunctionKeepVoidReturn() + => TestInRegularAndScriptAsync( """ using System.Threading.Tasks; @@ -1212,8 +1033,7 @@ async Task M3Async() } } """, -index: 1); - } + index: 1); [Theory] [InlineData(0, "void", "Task", "M2Async")] @@ -1222,9 +1042,8 @@ async Task M3Async() [InlineData(0, "Task", "Task", "M2")] [WorkItem("https://github.com/dotnet/roslyn/issues/18307")] [WorkItem("https://github.com/dotnet/roslyn/issues/33082")] - public async Task AddAsyncInLocalFunctionKeepsTrivia(int codeFixIndex, string initialReturn, string expectedReturn, string expectedName) - { - await TestInRegularAndScriptAsync( + public Task AddAsyncInLocalFunctionKeepsTrivia(int codeFixIndex, string initialReturn, string expectedReturn, string expectedName) + => TestInRegularAndScriptAsync( $$""" using System.Threading.Tasks; @@ -1266,7 +1085,6 @@ async Task M3Async() } """, index: codeFixIndex); - } [Theory] [InlineData("", 0, "Task", "M2Async")] @@ -1275,9 +1093,8 @@ async Task M3Async() [InlineData("public", 1, "void", "M2")] [WorkItem("https://github.com/dotnet/roslyn/issues/18307")] [WorkItem("https://github.com/dotnet/roslyn/issues/33082")] - public async Task AddAsyncKeepsTrivia(string modifiers, int codeFixIndex, string expectedReturn, string expectedName) - { - await TestInRegularAndScriptAsync( + public Task AddAsyncKeepsTrivia(string modifiers, int codeFixIndex, string expectedReturn, string expectedName) + => TestInRegularAndScriptAsync( $$""" using System.Threading.Tasks; @@ -1313,12 +1130,10 @@ async Task M3Async() } """, index: codeFixIndex); - } [Fact] - public async Task MethodWithAwaitUsing() - { - await TestInRegularAndScriptAsync( + public Task MethodWithAwaitUsing() + => TestInRegularAndScriptAsync( """ class C { @@ -1343,12 +1158,10 @@ async Task MAsync() } } """); - } [Fact] - public async Task MethodWithRegularUsing() - { - await TestMissingInRegularAndScriptAsync( + public Task MethodWithRegularUsing() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1360,12 +1173,10 @@ void M() } } """); - } [Fact] - public async Task MethodWithAwaitForEach() - { - await TestInRegularAndScriptAsync( + public Task MethodWithAwaitForEach() + => TestInRegularAndScriptAsync( """ class C { @@ -1390,12 +1201,10 @@ async Task MAsync() } } """); - } [Fact] - public async Task MethodWithRegularForEach() - { - await TestMissingInRegularAndScriptAsync( + public Task MethodWithRegularForEach() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1407,12 +1216,10 @@ void M() } } """); - } [Fact] - public async Task MethodWithAwaitForEachVariable() - { - await TestInRegularAndScriptAsync( + public Task MethodWithAwaitForEachVariable() + => TestInRegularAndScriptAsync( """ class C { @@ -1437,12 +1244,10 @@ async Task MAsync() } } """); - } [Fact] - public async Task MethodWithRegularForEachVariable() - { - await TestMissingInRegularAndScriptAsync( + public Task MethodWithRegularForEachVariable() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1454,12 +1259,10 @@ void M() } } """); - } [Fact] - public async Task MethodWithNullableReturn() - { - await TestInRegularAndScriptAsync( + public Task MethodWithNullableReturn() + => TestInRegularAndScriptAsync( """ #nullable enable using System.Threading.Tasks; @@ -1484,7 +1287,6 @@ class C } } """); - } [Fact] public async Task EnumerableMethodWithNullableType() @@ -1557,10 +1359,8 @@ class Program } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25446")] - public async Task TestOnAwaitParsedAsType() - { - var initial = - """ + public Task TestOnAwaitParsedAsType() + => TestInRegularAndScript1Async(""" using System.Threading.Tasks; class C @@ -1571,10 +1371,7 @@ void M() [|await|] task; } } - """; - - var expected = - """ + """, """ using System.Threading.Tasks; class C @@ -1585,15 +1382,11 @@ async Task MAsync() await task; } } - """; - await TestInRegularAndScript1Async(initial, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63404")] - public async Task PartialMethod1() - { - var initial = - """ + public Task PartialMethod1() + => TestInRegularAndScript1Async(""" using System.Threading.Tasks; public partial class C @@ -1608,10 +1401,7 @@ partial void M() [|await|] Task.Delay(1); } } - """; - - var expected = - """ + """, """ using System.Threading.Tasks; public partial class C @@ -1626,15 +1416,11 @@ async partial Task MAsync() await Task.Delay(1); } } - """; - await TestInRegularAndScript1Async(initial, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63404")] - public async Task PartialMethod2() - { - var initial = - """ + public Task PartialMethod2() + => TestInRegularAndScript1Async(""" using System.Threading.Tasks; public partial class C @@ -1649,10 +1435,7 @@ public partial void M() [|await|] Task.Delay(1); } } - """; - - var expected = - """ + """, """ using System.Threading.Tasks; public partial class C @@ -1667,15 +1450,11 @@ public async partial Task MAsync() await Task.Delay(1); } } - """; - await TestInRegularAndScript1Async(initial, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63404")] - public async Task PartialMethod3() - { - var initial = - """ + public Task PartialMethod3() + => TestInRegularAndScript1Async(""" using System.Threading.Tasks; public partial class C @@ -1690,10 +1469,7 @@ partial void M() [|await|] Task.Delay(1); } } - """; - - var expected = - """ + """, """ using System.Threading.Tasks; public partial class C @@ -1708,15 +1484,11 @@ async partial void M() await Task.Delay(1); } } - """; - await TestInRegularAndScript1Async(initial, expected, index: 1); - } + """, index: 1); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63404")] - public async Task PartialMethod4() - { - var initial = - """ + public Task PartialMethod4() + => TestInRegularAndScript1Async(""" using System.Threading.Tasks; public partial class C @@ -1731,10 +1503,7 @@ public partial void M() [|await|] Task.Delay(1); } } - """; - - var expected = - """ + """, """ using System.Threading.Tasks; public partial class C @@ -1749,7 +1518,5 @@ public async partial void M() await Task.Delay(1); } } - """; - await TestInRegularAndScript1Async(initial, expected, index: 1); - } + """, index: 1); } diff --git a/src/Analyzers/CSharp/Tests/MakeMethodSynchronous/MakeMethodSynchronousTests.cs b/src/Analyzers/CSharp/Tests/MakeMethodSynchronous/MakeMethodSynchronousTests.cs index 5747aa4eff078..2ab8c1bf6b9fa 100644 --- a/src/Analyzers/CSharp/Tests/MakeMethodSynchronous/MakeMethodSynchronousTests.cs +++ b/src/Analyzers/CSharp/Tests/MakeMethodSynchronous/MakeMethodSynchronousTests.cs @@ -20,9 +20,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeMethodSynchronous; public sealed class MakeMethodSynchronousTests { [Fact] - public async Task TestTaskReturnType() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestTaskReturnType() + => VerifyCS.VerifyCodeFixAsync( """ using System.Threading.Tasks; @@ -43,12 +42,10 @@ void Goo() } } """); - } [Fact] - public async Task TestTaskOfTReturnType() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestTaskOfTReturnType() + => VerifyCS.VerifyCodeFixAsync( """ using System.Threading.Tasks; @@ -71,12 +68,10 @@ class C } } """); - } [Fact] - public async Task TestSecondModifier() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestSecondModifier() + => VerifyCS.VerifyCodeFixAsync( """ using System.Threading.Tasks; @@ -97,12 +92,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestFirstModifier() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFirstModifier() + => VerifyCS.VerifyCodeFixAsync( """ using System.Threading.Tasks; @@ -123,12 +116,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestTrailingTrivia() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestTrailingTrivia() + => VerifyCS.VerifyCodeFixAsync( """ using System.Threading.Tasks; @@ -150,12 +141,10 @@ void Goo() } } """); - } [Fact] - public async Task TestRenameMethod() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestRenameMethod() + => VerifyCS.VerifyCodeFixAsync( """ using System.Threading.Tasks; @@ -176,12 +165,10 @@ void Goo() } } """); - } [Fact] - public async Task TestRenameMethod1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestRenameMethod1() + => VerifyCS.VerifyCodeFixAsync( """ using System.Threading.Tasks; @@ -212,12 +199,11 @@ void Bar() } } """); - } [Fact] public async Task TestParenthesizedLambda() { - var source = + var expected = """ using System; using System.Threading.Tasks; @@ -227,12 +213,14 @@ class C void Goo() { Func f = - async () {|CS1998:=>|} { }; + () {|#0:=>|} { }; } } """; - var expected = - """ + + await new VerifyCS.Test + { + TestCode = """ using System; using System.Threading.Tasks; @@ -241,14 +229,10 @@ class C void Goo() { Func f = - () {|#0:=>|} { }; + async () {|CS1998:=>|} { }; } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, FixedState = { Sources = { expected }, @@ -264,7 +248,7 @@ void Goo() [Fact] public async Task TestSimpleLambda() { - var source = + var expected = """ using System; using System.Threading.Tasks; @@ -274,12 +258,14 @@ class C void Goo() { Func f = - async a {|CS1998:=>|} { }; + a {|#0:=>|} { }; } } """; - var expected = - """ + + await new VerifyCS.Test + { + TestCode = """ using System; using System.Threading.Tasks; @@ -288,14 +274,10 @@ class C void Goo() { Func f = - a {|#0:=>|} { }; + async a {|CS1998:=>|} { }; } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, FixedState = { Sources = { expected }, @@ -311,7 +293,7 @@ void Goo() [Fact] public async Task TestLambdaWithExpressionBody() { - var source = + var expected = """ using System; using System.Threading.Tasks; @@ -321,12 +303,14 @@ class C void Goo() { Func> f = - async a {|CS1998:=>|} 1; + a => {|#0:1|}; } } """; - var expected = - """ + + await new VerifyCS.Test + { + TestCode = """ using System; using System.Threading.Tasks; @@ -335,14 +319,10 @@ class C void Goo() { Func> f = - a => {|#0:1|}; + async a {|CS1998:=>|} 1; } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, FixedState = { Sources = { expected }, @@ -360,7 +340,7 @@ void Goo() [Fact] public async Task TestAnonymousMethod() { - var source = + var expected = """ using System; using System.Threading.Tasks; @@ -370,12 +350,14 @@ class C void Goo() { Func f = - async {|CS1998:delegate|} { }; + {|#0:delegate|} { }; } } """; - var expected = - """ + + await new VerifyCS.Test + { + TestCode = """ using System; using System.Threading.Tasks; @@ -384,14 +366,10 @@ class C void Goo() { Func f = - {|#0:delegate|} { }; + async {|CS1998:delegate|} { }; } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, FixedState = { Sources = { expected }, @@ -405,9 +383,8 @@ void Goo() } [Fact] - public async Task TestFixAll() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFixAll() + => VerifyCS.VerifyCodeFixAsync( """ using System.Threading.Tasks; @@ -442,48 +419,45 @@ void Goo() } } """); - } [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/13961")] public async Task TestRemoveAwaitFromCaller1() { - var source = + var expected = """ using System.Threading.Tasks; public class Class1 { - async Task {|CS1998:GooAsync|}() + void Goo() { } - async void BarAsync() + async void {|CS1998:BarAsync|}() { - await GooAsync(); + Goo(); } } """; - var expected = - """ + + await new VerifyCS.Test + { + TestCode = """ using System.Threading.Tasks; public class Class1 { - void Goo() + async Task {|CS1998:GooAsync|}() { } - async void {|CS1998:BarAsync|}() + async void BarAsync() { - Goo(); + await GooAsync(); } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, FixedState = { Sources = { expected }, @@ -497,42 +471,40 @@ void Goo() [WorkItem("https://github.com/dotnet/roslyn/issues/13961")] public async Task TestRemoveAwaitFromCaller2() { - var source = + var expected = """ using System.Threading.Tasks; public class Class1 { - async Task {|CS1998:GooAsync|}() + void Goo() { } - async void BarAsync() + async void {|CS1998:BarAsync|}() { - await GooAsync().ConfigureAwait(false); + Goo(); } } """; - var expected = - """ + + await new VerifyCS.Test + { + TestCode = """ using System.Threading.Tasks; public class Class1 { - void Goo() + async Task {|CS1998:GooAsync|}() { } - async void {|CS1998:BarAsync|}() + async void BarAsync() { - Goo(); + await GooAsync().ConfigureAwait(false); } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, FixedState = { Sources = { expected }, @@ -546,42 +518,40 @@ void Goo() [WorkItem("https://github.com/dotnet/roslyn/issues/13961")] public async Task TestRemoveAwaitFromCaller3() { - var source = + var expected = """ using System.Threading.Tasks; public class Class1 { - async Task {|CS1998:GooAsync|}() + void Goo() { } - async void BarAsync() + async void {|CS1998:BarAsync|}() { - await this.GooAsync(); + this.Goo(); } } """; - var expected = - """ + + await new VerifyCS.Test + { + TestCode = """ using System.Threading.Tasks; public class Class1 { - void Goo() + async Task {|CS1998:GooAsync|}() { } - async void {|CS1998:BarAsync|}() + async void BarAsync() { - this.Goo(); + await this.GooAsync(); } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, FixedState = { Sources = { expected }, @@ -595,42 +565,40 @@ void Goo() [WorkItem("https://github.com/dotnet/roslyn/issues/13961")] public async Task TestRemoveAwaitFromCaller4() { - var source = + var expected = """ using System.Threading.Tasks; public class Class1 { - async Task {|CS1998:GooAsync|}() + void Goo() { } - async void BarAsync() + async void {|CS1998:BarAsync|}() { - await this.GooAsync().ConfigureAwait(false); + this.Goo(); } } """; - var expected = - """ + + await new VerifyCS.Test + { + TestCode = """ using System.Threading.Tasks; public class Class1 { - void Goo() + async Task {|CS1998:GooAsync|}() { } - async void {|CS1998:BarAsync|}() + async void BarAsync() { - this.Goo(); + await this.GooAsync().ConfigureAwait(false); } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, FixedState = { Sources = { expected }, @@ -644,44 +612,42 @@ void Goo() [WorkItem("https://github.com/dotnet/roslyn/issues/13961")] public async Task TestRemoveAwaitFromCallerNested1() { - var source = + var expected = """ using System.Threading.Tasks; public class Class1 { - async Task {|CS1998:GooAsync|}(int i) + int Goo(int i) { return 1; } - async void BarAsync() + async void {|CS1998:BarAsync|}() { - await this.GooAsync(await this.GooAsync(0)); + this.Goo(this.Goo(0)); } } """; - var expected = - """ + + await new VerifyCS.Test + { + TestCode = """ using System.Threading.Tasks; public class Class1 { - int Goo(int i) + async Task {|CS1998:GooAsync|}(int i) { return 1; } - async void {|CS1998:BarAsync|}() + async void BarAsync() { - this.Goo(this.Goo(0)); + await this.GooAsync(await this.GooAsync(0)); } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, FixedState = { Sources = { expected }, @@ -695,44 +661,42 @@ int Goo(int i) [WorkItem("https://github.com/dotnet/roslyn/issues/13961")] public async Task TestRemoveAwaitFromCallerNested() { - var source = + var expected = """ using System.Threading.Tasks; public class Class1 { - async Task {|CS1998:GooAsync|}(int i) + int Goo(int i) { return 1; } - async void BarAsync() + async void {|CS1998:BarAsync|}() { - await this.GooAsync(await this.GooAsync(0).ConfigureAwait(false)).ConfigureAwait(false); + this.Goo(this.Goo(0)); } } """; - var expected = - """ + + await new VerifyCS.Test + { + TestCode = """ using System.Threading.Tasks; public class Class1 { - int Goo(int i) + async Task {|CS1998:GooAsync|}(int i) { return 1; } - async void {|CS1998:BarAsync|}() + async void BarAsync() { - this.Goo(this.Goo(0)); + await this.GooAsync(await this.GooAsync(0).ConfigureAwait(false)).ConfigureAwait(false); } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, FixedState = { Sources = { expected }, @@ -744,9 +708,8 @@ int Goo(int i) [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem("https://github.com/dotnet/roslyn/issues/14133")] - public async Task RemoveAsyncInLocalFunction() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveAsyncInLocalFunction() + => VerifyCS.VerifyCodeFixAsync( """ using System.Threading.Tasks; @@ -773,7 +736,6 @@ void M2() } } """); - } [Theory] [InlineData("Task", "C")] @@ -782,9 +744,8 @@ void M2() [InlineData("void", "void")] [Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem("https://github.com/dotnet/roslyn/issues/18307")] - public async Task RemoveAsyncInLocalFunctionKeepsTrivia(string asyncReturn, string expectedReturn) - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveAsyncInLocalFunctionKeepsTrivia(string asyncReturn, string expectedReturn) + => VerifyCS.VerifyCodeFixAsync( $$""" using System; using System.Threading.Tasks; @@ -818,7 +779,6 @@ public void M1() } } """); - } [Theory] [InlineData("", "Task", "\r\n C")] @@ -831,9 +791,8 @@ public void M1() [InlineData("public", "void", " void")] [Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem("https://github.com/dotnet/roslyn/issues/18307")] - public async Task RemoveAsyncKeepsTrivia(string modifiers, string asyncReturn, string expectedReturn) - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveAsyncKeepsTrivia(string modifiers, string asyncReturn, string expectedReturn) + => VerifyCS.VerifyCodeFixAsync( $$""" using System; using System.Threading.Tasks; @@ -860,7 +819,6 @@ class C } } """); - } [Fact] public async Task MethodWithUsingAwait() @@ -892,9 +850,8 @@ async System.Threading.Tasks.Task MAsync() } [Fact] - public async Task MethodWithUsingNoAwait() - { - await VerifyCS.VerifyCodeFixAsync( + public Task MethodWithUsingNoAwait() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -919,7 +876,6 @@ void M() } } """); - } [Fact] public async Task MethodWithAwaitForEach() @@ -945,9 +901,8 @@ await VerifyCS.VerifyCodeFixAsync( } [Fact] - public async Task MethodWithForEachNoAwait() - { - await VerifyCS.VerifyCodeFixAsync( + public Task MethodWithForEachNoAwait() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -970,7 +925,6 @@ void M() } } """); - } [Fact] public async Task MethodWithForEachVariableAwait() @@ -996,9 +950,8 @@ await VerifyCS.VerifyCodeFixAsync( } [Fact] - public async Task MethodWithForEachVariableNoAwait() - { - await VerifyCS.VerifyCodeFixAsync( + public Task MethodWithForEachVariableNoAwait() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -1021,13 +974,13 @@ void M() } } """); - } [Fact] - public async Task TestIAsyncEnumerableReturnType() - { - var source = - """ + public Task TestIAsyncEnumerableReturnType() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21, + TestCode = """ using System.Threading.Tasks; using System.Collections.Generic; @@ -1038,9 +991,8 @@ class C yield return 1; } } - """; - var expected = - """ + """, + FixedCode = """ using System.Threading.Tasks; using System.Collections.Generic; @@ -1051,21 +1003,15 @@ IEnumerable M() yield return 1; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21, - TestCode = source, - FixedCode = expected, + """, }.RunAsync(); - } [Fact] - public async Task TestIAsyncEnumeratorReturnTypeOnLocalFunction() - { - var source = - """ + public Task TestIAsyncEnumeratorReturnTypeOnLocalFunction() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21, + TestCode = """ using System.Threading.Tasks; using System.Collections.Generic; @@ -1079,9 +1025,8 @@ void Method() } } } - """; - var expected = - """ + """, + FixedCode = """ using System.Threading.Tasks; using System.Collections.Generic; @@ -1095,13 +1040,6 @@ IEnumerator M() } } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21, - TestCode = source, - FixedCode = expected, + """, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/MakeStatementAsynchronous/CSharpMakeStatementAsynchronousCodeFixTests.cs b/src/Analyzers/CSharp/Tests/MakeStatementAsynchronous/CSharpMakeStatementAsynchronousCodeFixTests.cs index ee1709e0fe9d6..f463c04a6159a 100644 --- a/src/Analyzers/CSharp/Tests/MakeStatementAsynchronous/CSharpMakeStatementAsynchronousCodeFixTests.cs +++ b/src/Analyzers/CSharp/Tests/MakeStatementAsynchronous/CSharpMakeStatementAsynchronousCodeFixTests.cs @@ -19,9 +19,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.MakeStateme public sealed class CSharpMakeStatementAsynchronousCodeFixTests { [Fact] - public async Task FixAllForeach() - { - await new VerifyCS.Test() + public Task FixAllForeach() + => new VerifyCS.Test() { TestCode = """ class Program @@ -45,12 +44,10 @@ void M(System.Collections.Generic.IAsyncEnumerable collection) """, ReferenceAssemblies = ReferenceAssemblies.Net.Net60 }.RunAsync(); - } [Fact] - public async Task FixAllForeachDeconstruction() - { - await new VerifyCS.Test() + public Task FixAllForeachDeconstruction() + => new VerifyCS.Test() { TestCode = """ class Program @@ -74,12 +71,10 @@ void M(System.Collections.Generic.IAsyncEnumerable<(int, int)> collection) """, ReferenceAssemblies = ReferenceAssemblies.Net.Net60 }.RunAsync(); - } [Fact] - public async Task FixAllUsingStatement() - { - await new VerifyCS.Test() + public Task FixAllUsingStatement() + => new VerifyCS.Test() { TestCode = """ class Program @@ -103,12 +98,10 @@ void M(System.IAsyncDisposable disposable) """, ReferenceAssemblies = ReferenceAssemblies.Net.Net60 }.RunAsync(); - } [Fact] - public async Task FixAllUsingDeclaration() - { - await new VerifyCS.Test() + public Task FixAllUsingDeclaration() + => new VerifyCS.Test() { TestCode = """ class Program @@ -132,12 +125,10 @@ void M(System.IAsyncDisposable disposable) """, ReferenceAssemblies = ReferenceAssemblies.Net.Net60 }.RunAsync(); - } [Fact] - public async Task FixForeach() - { - await new VerifyCS.Test() + public Task FixForeach() + => new VerifyCS.Test() { TestCode = """ class Program @@ -163,12 +154,10 @@ void M(System.Collections.Generic.IAsyncEnumerable collection) """, ReferenceAssemblies = ReferenceAssemblies.Net.Net60 }.RunAsync(); - } [Fact] - public async Task FixForeachDeconstruction() - { - await new VerifyCS.Test() + public Task FixForeachDeconstruction() + => new VerifyCS.Test() { TestCode = """ class Program @@ -194,12 +183,10 @@ void M(System.Collections.Generic.IAsyncEnumerable<(int, int)> collection) """, ReferenceAssemblies = ReferenceAssemblies.Net.Net60 }.RunAsync(); - } [Fact] - public async Task FixUsingStatement() - { - await new VerifyCS.Test() + public Task FixUsingStatement() + => new VerifyCS.Test() { TestCode = """ class Program @@ -225,12 +212,10 @@ void M(System.IAsyncDisposable disposable) """, ReferenceAssemblies = ReferenceAssemblies.Net.Net60 }.RunAsync(); - } [Fact] - public async Task FixUsingDeclaration() - { - await new VerifyCS.Test() + public Task FixUsingDeclaration() + => new VerifyCS.Test() { TestCode = """ class Program @@ -252,5 +237,4 @@ void M(System.IAsyncDisposable disposable) """, ReferenceAssemblies = ReferenceAssemblies.Net.Net60 }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/MakeStructFieldsWritable/MakeStructFieldsWritableTests.cs b/src/Analyzers/CSharp/Tests/MakeStructFieldsWritable/MakeStructFieldsWritableTests.cs index 09e04048a73bb..03eee7a440145 100644 --- a/src/Analyzers/CSharp/Tests/MakeStructFieldsWritable/MakeStructFieldsWritableTests.cs +++ b/src/Analyzers/CSharp/Tests/MakeStructFieldsWritable/MakeStructFieldsWritableTests.cs @@ -21,9 +21,8 @@ public void TestStandardProperty(AnalyzerProperty property) => VerifyCS.VerifyStandardProperty(property); [Fact] - public async Task SingleReadonlyField_ThisAssignmentInMethod() - { - await VerifyCS.VerifyCodeFixAsync( + public Task SingleReadonlyField_ThisAssignmentInMethod() + => VerifyCS.VerifyCodeFixAsync( """ struct [|MyStruct|] { @@ -56,12 +55,10 @@ public void Test() } } """); - } [Fact] - public async Task SingleReadonlyField_ThisAssignmentInMultipleMethods() - { - await VerifyCS.VerifyCodeFixAsync( + public Task SingleReadonlyField_ThisAssignmentInMultipleMethods() + => VerifyCS.VerifyCodeFixAsync( """ struct [|MyStruct|] { @@ -104,7 +101,6 @@ public void Test2() } } """); - } [Fact] public async Task SingleNonReadonlyField_ThisAssignmentInMethod() @@ -130,9 +126,8 @@ public void Test() } [Fact] - public async Task MultipleMixedFields_ThisAssignmentInMethod() - { - await VerifyCS.VerifyCodeFixAsync( + public Task MultipleMixedFields_ThisAssignmentInMethod() + => VerifyCS.VerifyCodeFixAsync( """ struct [|MyStruct|] { @@ -173,7 +168,6 @@ public void Test() } } """); - } [Fact] public async Task SingleReadonlyField_ThisAssignmentInCtor() @@ -217,9 +211,8 @@ public MyStruct(int value) } [Fact] - public async Task SingleReadonlyField_ThisAssignmentInMethod_ReportDiagnostic() - { - await VerifyCS.VerifyCodeFixAsync( + public Task SingleReadonlyField_ThisAssignmentInMethod_ReportDiagnostic() + => VerifyCS.VerifyCodeFixAsync( """ struct [|MyStruct|] { @@ -252,7 +245,6 @@ public void Test() } } """); - } [Fact] public async Task SingleReadonlyField_InClass() @@ -341,9 +333,8 @@ public void Test() } [Fact] - public async Task MultipleStructDeclaration_SingleReadonlyField_ThisAssignmentInMethod() - { - await VerifyCS.VerifyCodeFixAsync( + public Task MultipleStructDeclaration_SingleReadonlyField_ThisAssignmentInMethod() + => VerifyCS.VerifyCodeFixAsync( """ struct [|MyStruct|] { @@ -406,12 +397,10 @@ public void Test() } } """); - } [Fact] - public async Task MultipleStructDeclaration_SingleReadonlyField_ThisAssignmentInMethod_ShouldNotReportDiagnostic() - { - await VerifyCS.VerifyCodeFixAsync( + public Task MultipleStructDeclaration_SingleReadonlyField_ThisAssignmentInMethod_ShouldNotReportDiagnostic() + => VerifyCS.VerifyCodeFixAsync( """ struct MyStruct { @@ -474,12 +463,10 @@ public void Test() } } """); - } [Fact] - public async Task NestedStructDeclaration_SingleNestedReadonlyField_ThisAssignmentInMethod() - { - await VerifyCS.VerifyCodeFixAsync( + public Task NestedStructDeclaration_SingleNestedReadonlyField_ThisAssignmentInMethod() + => VerifyCS.VerifyCodeFixAsync( """ struct [|MyStruct|] { @@ -542,12 +529,10 @@ public void Test() } } """); - } [Fact] - public async Task NestedStructDeclaration_SingleReadonlyField_ThisAssignmentInMethod() - { - await VerifyCS.VerifyCodeFixAsync( + public Task NestedStructDeclaration_SingleReadonlyField_ThisAssignmentInMethod() + => VerifyCS.VerifyCodeFixAsync( """ struct [|MyStruct|] { @@ -610,12 +595,10 @@ public void Test() } } """); - } [Fact] - public async Task StructDeclaration_MixedFields_MixedAssignmentsInMethods() - { - await VerifyCS.VerifyCodeFixAsync( + public Task StructDeclaration_MixedFields_MixedAssignmentsInMethods() + => VerifyCS.VerifyCodeFixAsync( """ struct [|MyStruct|] { @@ -662,12 +645,10 @@ public void Test2() } } """); - } [Fact] - public async Task StructDeclaration_ChangedOrderOfConstructorDeclaration() - { - await VerifyCS.VerifyCodeFixAsync( + public Task StructDeclaration_ChangedOrderOfConstructorDeclaration() + => VerifyCS.VerifyCodeFixAsync( """ struct [|MyStruct|] { @@ -700,7 +681,6 @@ public MyStruct(int value) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57920")] public async Task ReadonlyStaticField() diff --git a/src/Analyzers/CSharp/Tests/MakeStructMemberReadOnly/MakeStructMemberReadOnlyTests.cs b/src/Analyzers/CSharp/Tests/MakeStructMemberReadOnly/MakeStructMemberReadOnlyTests.cs index 5f5a53e1780a5..f7d6ffbbf5e90 100644 --- a/src/Analyzers/CSharp/Tests/MakeStructMemberReadOnly/MakeStructMemberReadOnlyTests.cs +++ b/src/Analyzers/CSharp/Tests/MakeStructMemberReadOnly/MakeStructMemberReadOnlyTests.cs @@ -21,9 +21,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeStructMemberReadOnl public sealed class MakeStructMemberReadOnlyTests { [Fact] - public async Task TestEmptyMethod() - { - await new VerifyCS.Test + public Task TestEmptyMethod() + => new VerifyCS.Test { TestCode = """ struct S @@ -38,57 +37,48 @@ readonly void M() { } } """ }.RunAsync(); - } [Fact] - public async Task TestNotInClass() - { - var test = """ + public Task TestNotInClass() + => new VerifyCS.Test + { + TestCode = """ class S { void M() { } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, }.RunAsync(); - } [Fact] - public async Task TestNotInReadOnlyStruct() - { - var test = """ + public Task TestNotInReadOnlyStruct() + => new VerifyCS.Test + { + TestCode = """ readonly struct S { void M() { } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, }.RunAsync(); - } [Fact] - public async Task TestNotInReadOnlyMember() - { - var test = """ + public Task TestNotInReadOnlyMember() + => new VerifyCS.Test + { + TestCode = """ struct S { readonly void M() { } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, }.RunAsync(); - } [Fact] - public async Task TestNotWithAssignmentToThis() - { - var test = """ + public Task TestNotWithAssignmentToThis() + => new VerifyCS.Test + { + TestCode = """ struct S { void M() @@ -96,17 +86,14 @@ void M() this = default; } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, }.RunAsync(); - } [Fact] - public async Task TestNotWithThisPassedByRef1() - { - var test = """ + public Task TestNotWithThisPassedByRef1() + => new VerifyCS.Test + { + TestCode = """ struct S { void M() @@ -116,17 +103,14 @@ void M() static void G(ref S s) { } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, }.RunAsync(); - } [Fact] - public async Task TestNotWithThisPassedByRef2() - { - var test = """ + public Task TestNotWithThisPassedByRef2() + => new VerifyCS.Test + { + TestCode = """ struct S { void M() @@ -139,17 +123,12 @@ static class X { public static void G(ref this S s) { } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, }.RunAsync(); - } [Fact] - public async Task TestWithThisPassedByIn1_A() - { - await new VerifyCS.Test + public Task TestWithThisPassedByIn1_A() + => new VerifyCS.Test { TestCode = """ struct S @@ -174,12 +153,10 @@ static void G(in S s) { } } """, }.RunAsync(); - } [Fact] - public async Task TestWithThisPassedByIn1_B() - { - await new VerifyCS.Test + public Task TestWithThisPassedByIn1_B() + => new VerifyCS.Test { TestCode = """ struct S @@ -204,12 +181,10 @@ static void G(in S s) { } } """, }.RunAsync(); - } [Fact] - public async Task TestWithThisPassedByIn2() - { - await new VerifyCS.Test + public Task TestWithThisPassedByIn2() + => new VerifyCS.Test { TestCode = """ struct S @@ -240,12 +215,10 @@ public static void G(in this S s) { } } """, }.RunAsync(); - } [Fact] - public async Task TestWithThisPassedByIn3() - { - await new VerifyCS.Test + public Task TestWithThisPassedByIn3() + => new VerifyCS.Test { TestCode = """ struct S @@ -270,12 +243,12 @@ readonly void M() } """, }.RunAsync(); - } [Fact] - public async Task TestNotWithWriteToField1() - { - var test = """ + public Task TestNotWithWriteToField1() + => new VerifyCS.Test + { + TestCode = """ struct S { int x; @@ -284,17 +257,14 @@ void M() x = 0; } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, }.RunAsync(); - } [Fact] - public async Task TestNotWithWriteToField2() - { - var test = """ + public Task TestNotWithWriteToField2() + => new VerifyCS.Test + { + TestCode = """ struct S { int x; @@ -303,17 +273,14 @@ void M() x++; } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, }.RunAsync(); - } [Fact] - public async Task TestNotWithWriteToField3() - { - var test = """ + public Task TestNotWithWriteToField3() + => new VerifyCS.Test + { + TestCode = """ struct S { int x; @@ -324,17 +291,14 @@ void M() static void G(ref int x) { } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, }.RunAsync(); - } [Fact] - public async Task TestNotWithWriteToField4() - { - var test = """ + public Task TestNotWithWriteToField4() + => new VerifyCS.Test + { + TestCode = """ struct S { int x; @@ -345,17 +309,14 @@ void M() static void G(out int x) { x = 0; } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, }.RunAsync(); - } [Fact] - public async Task TestNotWithWriteToField5() - { - var test = """ + public Task TestNotWithWriteToField5() + => new VerifyCS.Test + { + TestCode = """ struct S { int x; @@ -364,17 +325,14 @@ void M() (x, x) = (0, 0); } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, }.RunAsync(); - } [Fact] - public async Task TestNotWithWriteToField6() - { - var test = """ + public Task TestNotWithWriteToField6() + => new VerifyCS.Test + { + TestCode = """ struct D { public int i; @@ -387,17 +345,14 @@ void M() d.i = 0; } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, }.RunAsync(); - } [Fact] - public async Task TestNotWithWriteToField7() - { - var test = """ + public Task TestNotWithWriteToField7() + => new VerifyCS.Test + { + TestCode = """ struct BitVector { int x; @@ -411,17 +366,14 @@ void M() bits[0] = true; } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, }.RunAsync(); - } [Fact] - public async Task TestNotWithWriteToField8() - { - var test = """ + public Task TestNotWithWriteToField8() + => new VerifyCS.Test + { + TestCode = """ struct BitVector { int x; @@ -435,33 +387,25 @@ void M() (bits[0], bits[1]) = (true, false); } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, }.RunAsync(); - } [Fact] - public async Task TestNotInCSharp7() - { - var test = """ + public Task TestNotInCSharp7() + => new VerifyCS.Test + { + TestCode = """ struct S { void M() { } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, LanguageVersion = LanguageVersion.CSharp7, }.RunAsync(); - } [Fact] - public async Task TestPropertyExpressionBody() - { - await new VerifyCS.Test + public Task TestPropertyExpressionBody() + => new VerifyCS.Test { TestCode = """ struct S @@ -476,28 +420,22 @@ struct S } """ }.RunAsync(); - } [Fact] - public async Task TestPropertyAccessor1() - { - var test = """ + public Task TestPropertyAccessor1() + => new VerifyCS.Test + { + TestCode = """ struct S { int P { get; } } - """; - - await new VerifyCS.Test - { - TestCode = test, + """, }.RunAsync(); - } [Fact] - public async Task TestPropertyAccessor2() - { - await new VerifyCS.Test + public Task TestPropertyAccessor2() + => new VerifyCS.Test { TestCode = """ struct S @@ -512,12 +450,10 @@ struct S } """ }.RunAsync(); - } [Fact] - public async Task TestIndexerAccessor2() - { - await new VerifyCS.Test + public Task TestIndexerAccessor2() + => new VerifyCS.Test { TestCode = """ struct S @@ -532,12 +468,10 @@ struct S } """ }.RunAsync(); - } [Fact] - public async Task TestPropertyAccessor3() - { - await new VerifyCS.Test + public Task TestPropertyAccessor3() + => new VerifyCS.Test { TestCode = """ struct S @@ -552,12 +486,10 @@ struct S } """ }.RunAsync(); - } [Fact] - public async Task TestIndexerAccessor3() - { - await new VerifyCS.Test + public Task TestIndexerAccessor3() + => new VerifyCS.Test { TestCode = """ struct S @@ -572,12 +504,10 @@ struct S } """ }.RunAsync(); - } [Fact] - public async Task TestWriteToFieldNotThroughThis() - { - await new VerifyCS.Test + public Task TestWriteToFieldNotThroughThis() + => new VerifyCS.Test { TestCode = """ struct S @@ -604,12 +534,10 @@ readonly void M() } """ }.RunAsync(); - } [Fact] - public async Task TestCallToStaticMethod() - { - await new VerifyCS.Test + public Task TestCallToStaticMethod() + => new VerifyCS.Test { TestCode = """ struct S @@ -638,12 +566,10 @@ static void G() { } } """ }.RunAsync(); - } [Fact] - public async Task TestRecursiveCall() - { - await new VerifyCS.Test + public Task TestRecursiveCall() + => new VerifyCS.Test { TestCode = """ struct S @@ -668,12 +594,10 @@ readonly void M() } """ }.RunAsync(); - } [Fact] - public async Task TestMultipleAccessor() - { - await new VerifyCS.Test + public Task TestMultipleAccessor() + => new VerifyCS.Test { TestCode = """ struct S @@ -692,12 +616,10 @@ struct S } """, }.RunAsync(); - } [Fact] - public async Task TestMultipleIndexerAccessor() - { - await new VerifyCS.Test + public Task TestMultipleIndexerAccessor() + => new VerifyCS.Test { TestCode = """ struct S @@ -716,12 +638,10 @@ struct S } """, }.RunAsync(); - } [Fact] - public async Task TestMultipleAccessor_FixOne1() - { - await new VerifyCS.Test + public Task TestMultipleAccessor_FixOne1() + => new VerifyCS.Test { TestCode = """ struct S @@ -760,12 +680,10 @@ struct S """, CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, }.RunAsync(); - } [Fact] - public async Task TestMultipleIndexerAccessor_FixOne1() - { - await new VerifyCS.Test + public Task TestMultipleIndexerAccessor_FixOne1() + => new VerifyCS.Test { TestCode = """ struct S @@ -804,12 +722,10 @@ struct S """, CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, }.RunAsync(); - } [Fact] - public async Task TestMultipleAccessor2() - { - await new VerifyCS.Test + public Task TestMultipleAccessor2() + => new VerifyCS.Test { TestCode = """ struct S @@ -828,12 +744,10 @@ struct S } """ }.RunAsync(); - } [Fact] - public async Task TestMultipleIndexerAccessor2() - { - await new VerifyCS.Test + public Task TestMultipleIndexerAccessor2() + => new VerifyCS.Test { TestCode = """ struct S @@ -852,12 +766,10 @@ struct S } """ }.RunAsync(); - } [Fact] - public async Task TestTakeRefReadOnlyToField() - { - await new VerifyCS.Test + public Task TestTakeRefReadOnlyToField() + => new VerifyCS.Test { TestCode = """ struct S @@ -882,12 +794,12 @@ readonly void M() } """ }.RunAsync(); - } [Fact] - public async Task TestNotWithAddressOfFieldTaken() - { - var test = """ + public Task TestNotWithAddressOfFieldTaken() + => new VerifyCS.Test + { + TestCode = """ struct S { int x; @@ -898,17 +810,14 @@ unsafe void M() } } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, }.RunAsync(); - } [Fact] - public async Task TestNotWithCallToNonReadOnlyMethod() - { - var test = """ + public Task TestNotWithCallToNonReadOnlyMethod() + => new VerifyCS.Test + { + TestCode = """ struct S { int x; @@ -922,17 +831,14 @@ void X() x = 1; } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, }.RunAsync(); - } [Fact] - public async Task TestNotWithCallToNonReadOnlyIndexer() - { - var test = """ + public Task TestNotWithCallToNonReadOnlyIndexer() + => new VerifyCS.Test + { + TestCode = """ struct S { int x; @@ -943,17 +849,14 @@ void M() var v = this[0]; } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, }.RunAsync(); - } [Fact] - public async Task TestNotWithCaptureOfNonReadOnlyMethod1() - { - var test = """ + public Task TestNotWithCaptureOfNonReadOnlyMethod1() + => new VerifyCS.Test + { + TestCode = """ struct S { int x; @@ -967,17 +870,14 @@ void X() x = 1; } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, }.RunAsync(); - } [Fact] - public async Task TestNotWithCaptureOfNonReadOnlyMethod2() - { - var test = """ + public Task TestNotWithCaptureOfNonReadOnlyMethod2() + => new VerifyCS.Test + { + TestCode = """ struct S { int x; @@ -991,18 +891,13 @@ void X() x = 1; } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task TestCallToObjectMethod() - { - await new VerifyCS.Test + public Task TestCallToObjectMethod() + => new VerifyCS.Test { TestCode = """ struct S @@ -1017,12 +912,10 @@ struct S } """ }.RunAsync(); - } [Fact] - public async Task TestCallToReadOnlyMethod() - { - await new VerifyCS.Test + public Task TestCallToReadOnlyMethod() + => new VerifyCS.Test { TestCode = """ struct S @@ -1039,12 +932,10 @@ readonly void X() { } } """ }.RunAsync(); - } [Fact] - public async Task TestCallToReadOnlyIndexer1() - { - await new VerifyCS.Test + public Task TestCallToReadOnlyIndexer1() + => new VerifyCS.Test { TestCode = """ struct S @@ -1071,12 +962,10 @@ readonly void M() } """ }.RunAsync(); - } [Fact] - public async Task TestCallToReadOnlyIndexer2() - { - await new VerifyCS.Test + public Task TestCallToReadOnlyIndexer2() + => new VerifyCS.Test { TestCode = """ struct S @@ -1103,12 +992,10 @@ readonly void M() } """ }.RunAsync(); - } [Fact] - public async Task TestExplicitInterfaceImpl() - { - await new VerifyCS.Test + public Task TestExplicitInterfaceImpl() + => new VerifyCS.Test { TestCode = """ using System; @@ -1125,12 +1012,12 @@ struct S : IEquatable } """ }.RunAsync(); - } [Fact] - public async Task TestEventMutation() - { - var testCode = """ + public Task TestEventMutation() + => new VerifyCS.Test + { + TestCode = """ using System; struct S { @@ -1141,17 +1028,14 @@ void M() this.E += () => { }; } } - """; - await new VerifyCS.Test - { - TestCode = testCode, + """, }.RunAsync(); - } [Fact] - public async Task TestNotWithNonReadOnlyMethodCallOnField() - { - var testCode = """ + public Task TestNotWithNonReadOnlyMethodCallOnField() + => new VerifyCS.Test + { + TestCode = """ struct T { int i; @@ -1167,17 +1051,12 @@ void Dispose() t.Dispose(); } } - """; - await new VerifyCS.Test - { - TestCode = testCode, + """, }.RunAsync(); - } [Fact] - public async Task TestWithReadOnlyMethodCallOnField() - { - await new VerifyCS.Test + public Task TestWithReadOnlyMethodCallOnField() + => new VerifyCS.Test { TestCode = """ struct T @@ -1212,46 +1091,38 @@ readonly void Dispose() } """, }.RunAsync(); - } [Fact] - public async Task TestNotWithNonReadOnlyMethodOnUnconstrainedField() - { - var testCode = """ + public Task TestNotWithNonReadOnlyMethodOnUnconstrainedField() + => new VerifyCS.Test + { + TestCode = """ using System; struct T where X : IComparable { X x; public void M() { x.CompareTo(null); } } - """; - await new VerifyCS.Test - { - TestCode = testCode, + """, }.RunAsync(); - } [Fact] - public async Task TestNotWithNonReadOnlyMethodOnStructConstrainedField() - { - var testCode = """ + public Task TestNotWithNonReadOnlyMethodOnStructConstrainedField() + => new VerifyCS.Test + { + TestCode = """ using System; struct T where X : struct, IComparable { X x; public void M() { x.CompareTo(null); } } - """; - await new VerifyCS.Test - { - TestCode = testCode, + """, }.RunAsync(); - } [Fact] - public async Task TestWithNonReadOnlyMethodOnClassConstrainedField() - { - await new VerifyCS.Test + public Task TestWithNonReadOnlyMethodOnClassConstrainedField() + => new VerifyCS.Test { TestCode = """ using System; @@ -1270,27 +1141,24 @@ struct T where X : class, IComparable } """, }.RunAsync(); - } [Fact] - public async Task TestNotWithMethodThatOnlyThrows1() - { - var test = """ + public Task TestNotWithMethodThatOnlyThrows1() + => new VerifyCS.Test + { + TestCode = """ struct S { void M() => throw new System.Exception(); } - """; - await new VerifyCS.Test - { - TestCode = test, + """, }.RunAsync(); - } [Fact] - public async Task TestNotWithMethodThatOnlyThrows2() - { - var test = """ + public Task TestNotWithMethodThatOnlyThrows2() + => new VerifyCS.Test + { + TestCode = """ struct S { void M() @@ -1298,17 +1166,14 @@ void M() throw new System.Exception(); } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, }.RunAsync(); - } [Fact] - public async Task TestNotWithBadOperation() - { - var test = """ + public Task TestNotWithBadOperation() + => new VerifyCS.Test + { + TestCode = """ struct S { void M() @@ -1316,17 +1181,12 @@ void M() {|CS0103:Goo|}(); } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, }.RunAsync(); - } [Fact] - public async Task TestWithLinqRewrite() - { - await new VerifyCS.Test + public Task TestWithLinqRewrite() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -1353,12 +1213,10 @@ readonly void M(IEnumerable x) } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67531")] - public async Task TestWithFixedSizeBufferField1() - { - await new VerifyCS.Test + public Task TestWithFixedSizeBufferField1() + => new VerifyCS.Test { TestCode = """ struct Repro @@ -1374,12 +1232,10 @@ private readonly void M(ref byte b) { } } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70116")] - public async Task TestInlineArraySpan1() - { - await new VerifyCS.Test + public Task TestInlineArraySpan1() + => new VerifyCS.Test { TestCode = """ using System; @@ -1406,12 +1262,10 @@ public struct ByteArray20 ReferenceAssemblies = ReferenceAssemblies.Net.Net80, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70116")] - public async Task TestInlineArraySpan2() - { - await new VerifyCS.Test + public Task TestInlineArraySpan2() + => new VerifyCS.Test { TestCode = """ using System; @@ -1440,12 +1294,10 @@ public struct ByteArray20 ReferenceAssemblies = ReferenceAssemblies.Net.Net80, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70116")] - public async Task TestInlineArraySpan2_A() - { - await new VerifyCS.Test + public Task TestInlineArraySpan2_A() + => new VerifyCS.Test { TestCode = """ using System; @@ -1474,12 +1326,10 @@ public struct ByteArray20 ReferenceAssemblies = ReferenceAssemblies.Net.Net80, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70116")] - public async Task TestInlineArraySpan3() - { - await new VerifyCS.Test + public Task TestInlineArraySpan3() + => new VerifyCS.Test { TestCode = """ using System; @@ -1532,12 +1382,10 @@ public struct ByteArray20 ReferenceAssemblies = ReferenceAssemblies.Net.Net80, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70116")] - public async Task TestInlineArraySpan3_A() - { - await new VerifyCS.Test + public Task TestInlineArraySpan3_A() + => new VerifyCS.Test { TestCode = """ using System; @@ -1590,12 +1438,10 @@ public struct ByteArray20 ReferenceAssemblies = ReferenceAssemblies.Net.Net80, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70116")] - public async Task TestInlineArraySpan4() - { - await new VerifyCS.Test + public Task TestInlineArraySpan4() + => new VerifyCS.Test { TestCode = """ using System; @@ -1648,12 +1494,10 @@ public struct ByteArray20 ReferenceAssemblies = ReferenceAssemblies.Net.Net80, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70116")] - public async Task TestInlineArraySpan4_A() - { - await new VerifyCS.Test + public Task TestInlineArraySpan4_A() + => new VerifyCS.Test { TestCode = """ using System; @@ -1706,12 +1550,10 @@ public struct ByteArray20 ReferenceAssemblies = ReferenceAssemblies.Net.Net80, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70780")] - public async Task TestPrimaryConstructorParameterReference0() - { - await new VerifyCS.Test + public Task TestPrimaryConstructorParameterReference0() + => new VerifyCS.Test { TestCode = """ struct Cell(short value) @@ -1726,12 +1568,10 @@ public void RemoveBit(int candidate) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70780")] - public async Task TestPrimaryConstructorParameterReference1() - { - await new VerifyCS.Test + public Task TestPrimaryConstructorParameterReference1() + => new VerifyCS.Test { TestCode = """ struct Cell(short value) @@ -1746,12 +1586,10 @@ public void RemoveBit(int candidate) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70780")] - public async Task TestPrimaryConstructorParameterReference2() - { - await new VerifyCS.Test + public Task TestPrimaryConstructorParameterReference2() + => new VerifyCS.Test { TestCode = """ struct Cell(short value) @@ -1766,12 +1604,10 @@ public void RemoveBit(int candidate) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70780")] - public async Task TestPrimaryConstructorParameterReference3() - { - await new VerifyCS.Test + public Task TestPrimaryConstructorParameterReference3() + => new VerifyCS.Test { TestCode = """ struct Point @@ -1789,12 +1625,10 @@ public void RemoveBit(int candidate) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70780")] - public async Task TestPrimaryConstructorParameterReference4() - { - await new VerifyCS.Test + public Task TestPrimaryConstructorParameterReference4() + => new VerifyCS.Test { TestCode = """ struct Point @@ -1812,12 +1646,10 @@ public void RemoveBit(int candidate) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70780")] - public async Task TestPrimaryConstructorParameterReference5() - { - await new VerifyCS.Test + public Task TestPrimaryConstructorParameterReference5() + => new VerifyCS.Test { TestCode = """ struct Point @@ -1837,12 +1669,10 @@ public void RemoveBit(int candidate) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70780")] - public async Task TestPrimaryConstructorParameterReference6() - { - await new VerifyCS.Test + public Task TestPrimaryConstructorParameterReference6() + => new VerifyCS.Test { TestCode = """ struct Point @@ -1878,12 +1708,10 @@ public readonly void RemoveBit(int candidate) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70780")] - public async Task TestPrimaryConstructorParameterReference7() - { - await new VerifyCS.Test + public Task TestPrimaryConstructorParameterReference7() + => new VerifyCS.Test { TestCode = """ struct Cell(int value) @@ -1905,12 +1733,10 @@ public readonly void RemoveBit(int candidate) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70780")] - public async Task TestPrimaryConstructorParameterReference8() - { - await new VerifyCS.Test + public Task TestPrimaryConstructorParameterReference8() + => new VerifyCS.Test { TestCode = """ struct Cell(string value) @@ -1923,12 +1749,10 @@ public void RemoveBit(int candidate) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70780")] - public async Task TestPrimaryConstructorParameterReference9() - { - await new VerifyCS.Test + public Task TestPrimaryConstructorParameterReference9() + => new VerifyCS.Test { TestCode = """ class Point @@ -1964,12 +1788,10 @@ public readonly void RemoveBit(int candidate) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70780")] - public async Task TestPrimaryConstructorParameterReference10() - { - await new VerifyCS.Test + public Task TestPrimaryConstructorParameterReference10() + => new VerifyCS.Test { TestCode = """ class Point @@ -2005,12 +1827,10 @@ public readonly void RemoveBit(int candidate) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70780")] - public async Task TestPrimaryConstructorParameterReference11() - { - await new VerifyCS.Test + public Task TestPrimaryConstructorParameterReference11() + => new VerifyCS.Test { TestCode = """ using System; @@ -2036,12 +1856,10 @@ public readonly void RemoveBit(int candidate) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70780")] - public async Task TestPrimaryConstructorParameterReference12() - { - await new VerifyCS.Test + public Task TestPrimaryConstructorParameterReference12() + => new VerifyCS.Test { TestCode = """ using System; @@ -2056,12 +1874,10 @@ public void RemoveBit(int candidate) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70780")] - public async Task TestPrimaryConstructorParameterReference13() - { - await new VerifyCS.Test + public Task TestPrimaryConstructorParameterReference13() + => new VerifyCS.Test { TestCode = """ using System; @@ -2076,12 +1892,10 @@ public void RemoveBit(int candidate) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70864")] - public async Task TestInitAccessor1() - { - await new VerifyCS.Test + public Task TestInitAccessor1() + => new VerifyCS.Test { TestCode = """ using System; @@ -2104,12 +1918,10 @@ public readonly int? MaxSize LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70864")] - public async Task TestInitAccessor2() - { - await new VerifyCS.Test + public Task TestInitAccessor2() + => new VerifyCS.Test { TestCode = """ using System; @@ -2148,12 +1960,10 @@ public readonly int? MaxSize LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70864")] - public async Task TestInitAccessor3() - { - await new VerifyCS.Test + public Task TestInitAccessor3() + => new VerifyCS.Test { TestCode = """ using System; @@ -2175,12 +1985,10 @@ public int? MaxSize LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70864")] - public async Task TestInitAccessor4() - { - await new VerifyCS.Test + public Task TestInitAccessor4() + => new VerifyCS.Test { TestCode = """ using System; @@ -2215,12 +2023,10 @@ public readonly int? MaxSize LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71500")] - public async Task TestOnInlineArray() - { - await new VerifyCS.Test + public Task TestOnInlineArray() + => new VerifyCS.Test { TestCode = """ using System; @@ -2263,12 +2069,10 @@ internal struct Values LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71500")] - public async Task TestOnInlineArrayCapturedIntoReadOnlySpan() - { - await new VerifyCS.Test + public Task TestOnInlineArrayCapturedIntoReadOnlySpan() + => new VerifyCS.Test { TestCode = """ using System; @@ -2313,12 +2117,10 @@ internal struct Values LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71500")] - public async Task TestOnInlineArrayRead() - { - await new VerifyCS.Test + public Task TestOnInlineArrayRead() + => new VerifyCS.Test { TestCode = """ using System; @@ -2363,12 +2165,10 @@ internal struct Values LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71500")] - public async Task TestOnInlineArrayReadSafe() - { - await new VerifyCS.Test + public Task TestOnInlineArrayReadSafe() + => new VerifyCS.Test { TestCode = """ using System; @@ -2423,12 +2223,10 @@ public readonly void Safe() { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71500")] - public async Task TestOnInlineArrayReadUnsafe() - { - await new VerifyCS.Test + public Task TestOnInlineArrayReadUnsafe() + => new VerifyCS.Test { TestCode = """ using System; @@ -2459,12 +2257,10 @@ internal struct S LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71500")] - public async Task TestNotOnInlineArrayCapturedIntoSpan() - { - await new VerifyCS.Test + public Task TestNotOnInlineArrayCapturedIntoSpan() + => new VerifyCS.Test { TestCode = """ using System; @@ -2489,12 +2285,10 @@ internal struct Values LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71500")] - public async Task TestNotOnInlineArrayWrittenInfo() - { - await new VerifyCS.Test + public Task TestNotOnInlineArrayWrittenInfo() + => new VerifyCS.Test { TestCode = """ using System; @@ -2519,12 +2313,10 @@ internal struct Values LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71500")] - public async Task TestMultipleAccessors() - { - await new VerifyCS.Test + public Task TestMultipleAccessors() + => new VerifyCS.Test { TestCode = """ struct S @@ -2553,5 +2345,4 @@ public int Z LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/MakeStructReadOnly/MakeStructReadOnlyTests.cs b/src/Analyzers/CSharp/Tests/MakeStructReadOnly/MakeStructReadOnlyTests.cs index a97b130902f31..80d8d4ab8ed85 100644 --- a/src/Analyzers/CSharp/Tests/MakeStructReadOnly/MakeStructReadOnlyTests.cs +++ b/src/Analyzers/CSharp/Tests/MakeStructReadOnly/MakeStructReadOnlyTests.cs @@ -23,33 +23,28 @@ public sealed class MakeStructReadOnlyTests private static Task TestMissingAsync(string testCode, LanguageVersion version = LanguageVersion.CSharp12) => TestAsync(testCode, testCode, version); - private static async Task TestAsync(string testCode, string fixedCode, LanguageVersion version = LanguageVersion.CSharp12) - { - await new VerifyCS.Test + private static Task TestAsync(string testCode, string fixedCode, LanguageVersion version = LanguageVersion.CSharp12) + => new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, LanguageVersion = version, ReferenceAssemblies = ReferenceAssemblies.Net.Net50, }.RunAsync(); - } [Fact] - public async Task ShouldNotTriggerForCSharp7_1() - { - await TestMissingAsync( + public Task ShouldNotTriggerForCSharp7_1() + => TestMissingAsync( """ struct S { readonly int i; } """, LanguageVersion.CSharp7_1); - } [Fact] - public async Task ShouldTriggerFor7_2() - { - await TestAsync( + public Task ShouldTriggerFor7_2() + => TestAsync( """ struct [|S|] { @@ -62,61 +57,51 @@ readonly struct S readonly int i; } """, -LanguageVersion.CSharp7_2); - } + LanguageVersion.CSharp7_2); [Fact] - public async Task TestMissingWithAlreadyReadOnlyStruct() - { - await TestMissingAsync( + public Task TestMissingWithAlreadyReadOnlyStruct() + => TestMissingAsync( """ readonly struct S { readonly int i; } """); - } [Fact] - public async Task TestMissingWithAlreadyReadOnlyRecordStruct() - { - await TestMissingAsync( + public Task TestMissingWithAlreadyReadOnlyRecordStruct() + => TestMissingAsync( """ readonly record struct S { readonly int i; } """); - } [Fact] - public async Task TestMissingWithMutableField() - { - await TestMissingAsync( + public Task TestMissingWithMutableField() + => TestMissingAsync( """ struct S { int i; } """); - } [Fact] - public async Task TestMissingWithMutableFieldRecordStruct() - { - await TestMissingAsync( + public Task TestMissingWithMutableFieldRecordStruct() + => TestMissingAsync( """ record struct S { int i; } """); - } [Fact] - public async Task TestMissingWithMutableAndReadOnlyField() - { - await TestMissingAsync( + public Task TestMissingWithMutableAndReadOnlyField() + => TestMissingAsync( """ struct S { @@ -124,12 +109,10 @@ struct S readonly int j; } """); - } [Fact] - public async Task TestMissingWithMutableAndReadOnlyFieldRecordStruct1() - { - await TestMissingAsync( + public Task TestMissingWithMutableAndReadOnlyFieldRecordStruct1() + => TestMissingAsync( """ record struct S { @@ -137,128 +120,106 @@ record struct S readonly int j; } """); - } [Fact] - public async Task TestMissingWithMutableAndReadOnlyFieldRecordStruct2() - { - await TestMissingAsync( + public Task TestMissingWithMutableAndReadOnlyFieldRecordStruct2() + => TestMissingAsync( """ record struct S(int j) { int i; } """); - } [Fact] - public async Task TestMissingWithMutableAndReadOnlyFieldStruct2() - { - await TestMissingAsync( + public Task TestMissingWithMutableAndReadOnlyFieldStruct2() + => TestMissingAsync( """ struct S(int j) { int i; } """); - } [Fact] - public async Task TestMissingWithMutableProperty() - { - await TestMissingAsync( + public Task TestMissingWithMutableProperty() + => TestMissingAsync( """ struct S { int P { get; set; } } """); - } [Fact] - public async Task TestMissingWithMutablePropertyRecordStruct1() - { - await TestMissingAsync( + public Task TestMissingWithMutablePropertyRecordStruct1() + => TestMissingAsync( """ record struct S { int P { get; set; } } """); - } [Fact] - public async Task TestMissingWithMutablePropertyRecordStruct2() - { - await TestMissingAsync( + public Task TestMissingWithMutablePropertyRecordStruct2() + => TestMissingAsync( """ record struct S(int q) { int P { get; set; } } """); - } [Fact] - public async Task TestMissingWithMutablePropertyStruct2() - { - await TestMissingAsync( + public Task TestMissingWithMutablePropertyStruct2() + => TestMissingAsync( """ struct S(int q) { int P { get; set; } } """); - } [Fact] - public async Task TestMissingWithEmptyStruct() - { - await TestMissingAsync( + public Task TestMissingWithEmptyStruct() + => TestMissingAsync( """ struct S { } """); - } [Fact] - public async Task TestMissingWithEmptyRecordStruct() - { - await TestMissingAsync( + public Task TestMissingWithEmptyRecordStruct() + => TestMissingAsync( """ record struct S { } """); - } [Fact] - public async Task TestMissingWithEmptyRecordStructPrimaryConstructor() - { - await TestMissingAsync( + public Task TestMissingWithEmptyRecordStructPrimaryConstructor() + => TestMissingAsync( """ record struct S() { } """); - } [Fact] - public async Task TestMissingWithEmptyStructPrimaryConstructor() - { - await TestMissingAsync( + public Task TestMissingWithEmptyStructPrimaryConstructor() + => TestMissingAsync( """ struct S() { } """); - } [Fact] - public async Task TestMissingWithOtherReadonlyPartialPart() - { - await TestMissingAsync( + public Task TestMissingWithOtherReadonlyPartialPart() + => TestMissingAsync( """ partial struct S { @@ -269,12 +230,10 @@ readonly partial struct S { } """); - } [Fact] - public async Task TestOnStructWithReadOnlyField() - { - await TestAsync( + public Task TestOnStructWithReadOnlyField() + => TestAsync( """ struct [|S|] { @@ -287,12 +246,10 @@ readonly struct S readonly int i; } """); - } [Fact] - public async Task TestOnRecordStructWithReadOnlyField() - { - await TestAsync( + public Task TestOnRecordStructWithReadOnlyField() + => TestAsync( """ record struct [|S|] { @@ -305,12 +262,10 @@ readonly record struct S readonly int i; } """); - } [Fact] - public async Task TestOnStructWithGetOnlyProperty() - { - await TestAsync( + public Task TestOnStructWithGetOnlyProperty() + => TestAsync( """ struct [|S|] { @@ -323,12 +278,10 @@ readonly struct S int P { get; } } """); - } [Fact] - public async Task TestOnRecordStructWithGetOnlyProperty() - { - await TestAsync( + public Task TestOnRecordStructWithGetOnlyProperty() + => TestAsync( """ record struct [|S|] { @@ -341,12 +294,10 @@ readonly record struct S int P { get; } } """); - } [Fact] - public async Task TestOnStructWithInitOnlyProperty() - { - await TestAsync( + public Task TestOnStructWithInitOnlyProperty() + => TestAsync( """ struct [|S|] { @@ -359,12 +310,10 @@ readonly struct S int P { get; init; } } """); - } [Fact] - public async Task TestOnRecordStructWithInitOnlyProperty() - { - await TestAsync( + public Task TestOnRecordStructWithInitOnlyProperty() + => TestAsync( """ record struct [|S|] { @@ -377,12 +326,10 @@ readonly record struct S int P { get; init; } } """); - } [Fact] - public async Task TestOnRecordStructWithReadOnlyField2() - { - await TestAsync( + public Task TestOnRecordStructWithReadOnlyField2() + => TestAsync( """ record struct [|S|] { @@ -395,46 +342,38 @@ readonly record struct S readonly int i; } """); - } [Fact] - public async Task TestMissingRecordStructWithPrimaryConstructorField() - { - await TestMissingAsync( + public Task TestMissingRecordStructWithPrimaryConstructorField() + => TestMissingAsync( """ record struct S(int i) { } """); - } [Fact] - public async Task TestMissingStructWithPrimaryConstructor() - { - await TestMissingAsync( + public Task TestMissingStructWithPrimaryConstructor() + => TestMissingAsync( """ struct S(int i) { } """); - } [Fact] - public async Task TestMissingOnRecordStructWithPrimaryConstructorFieldAndNormalField() - { - await TestMissingAsync( + public Task TestMissingOnRecordStructWithPrimaryConstructorFieldAndNormalField() + => TestMissingAsync( """ record struct S(int i) { readonly int j; } """); - } [Fact] - public async Task TestOnStructWithPrimaryConstructorAndReadonlyField() - { - await TestAsync( + public Task TestOnStructWithPrimaryConstructorAndReadonlyField() + => TestAsync( """ struct [|S|](int i) { @@ -447,13 +386,11 @@ readonly struct S(int i) readonly int i; } """, -LanguageVersion.CSharp12); - } + LanguageVersion.CSharp12); [Fact] - public async Task TestNestedStructs1() - { - await TestAsync( + public Task TestNestedStructs1() + => TestAsync( """ struct [|S|] { @@ -476,12 +413,10 @@ readonly struct T } } """); - } [Fact] - public async Task TestNestedStructs2() - { - await TestAsync( + public Task TestNestedStructs2() + => TestAsync( """ struct [|S|] { @@ -504,12 +439,10 @@ struct T } } """); - } [Fact] - public async Task TestNestedStructs3() - { - await TestAsync( + public Task TestNestedStructs3() + => TestAsync( """ struct S { @@ -532,12 +465,10 @@ readonly struct T } } """); - } [Fact] - public async Task TestNestedStructs4() - { - await TestAsync( + public Task TestNestedStructs4() + => TestAsync( """ struct [|S|] { @@ -570,12 +501,10 @@ void M() } } """); - } [Fact] - public async Task TestDocComments1() - { - await TestAsync( + public Task TestDocComments1() + => TestAsync( """ /// docs record struct [|S|] @@ -590,12 +519,10 @@ readonly record struct S readonly int j; } """); - } [Fact] - public async Task TestDocComments2() - { - await TestAsync( + public Task TestDocComments2() + => TestAsync( """ namespace N { @@ -616,12 +543,10 @@ readonly record struct S } } """); - } [Fact] - public async Task TestExistingModifier1() - { - await TestAsync( + public Task TestExistingModifier1() + => TestAsync( """ public record struct [|S|] { @@ -634,12 +559,10 @@ public readonly record struct S readonly int j; } """); - } [Fact] - public async Task TestExistingModifier2() - { - await TestAsync( + public Task TestExistingModifier2() + => TestAsync( """ namespace N { @@ -658,12 +581,10 @@ public readonly record struct S } } """); - } [Fact] - public async Task TestOnStructWithReadOnlyFieldAndMutableNormalProp() - { - await TestAsync( + public Task TestOnStructWithReadOnlyFieldAndMutableNormalProp() + => TestAsync( """ struct [|S|] { @@ -680,12 +601,10 @@ readonly struct S int P { set { } } } """); - } [Fact] - public async Task TestOnStructWithReadOnlyFieldAndMutableAutoProp() - { - await TestMissingAsync( + public Task TestOnStructWithReadOnlyFieldAndMutableAutoProp() + => TestMissingAsync( """ struct S { @@ -694,12 +613,10 @@ struct S int P { get; set; } } """); - } [Fact] - public async Task TestMissingOnStructThatWritesToThis1() - { - await TestMissingAsync( + public Task TestMissingOnStructThatWritesToThis1() + => TestMissingAsync( """ struct S { @@ -711,12 +628,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingOnStructThatWritesToThis2() - { - await TestMissingAsync( + public Task TestMissingOnStructThatWritesToThis2() + => TestMissingAsync( """ struct S { @@ -733,12 +648,10 @@ static class Extensions public static void ByRef(ref this S s) { } } """); - } [Fact] - public async Task TestMissingOnStructThatWritesToThis3() - { - await TestMissingAsync( + public Task TestMissingOnStructThatWritesToThis3() + => TestMissingAsync( """ struct S { @@ -752,12 +665,10 @@ void M() void Goo(ref S s) { } } """); - } [Fact] - public async Task TestMissingOnStructThatWritesToThis4() - { - await TestMissingAsync( + public Task TestMissingOnStructThatWritesToThis4() + => TestMissingAsync( """ struct S { @@ -771,12 +682,10 @@ void M() void Goo(out S s) { s = default; } } """); - } [Fact] - public async Task TestMissingOnStructThatWritesToThis5() - { - await TestMissingAsync( + public Task TestMissingOnStructThatWritesToThis5() + => TestMissingAsync( """ struct S { @@ -788,12 +697,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingOnStructThatWritesToThis6() - { - await TestMissingAsync( + public Task TestMissingOnStructThatWritesToThis6() + => TestMissingAsync( """ struct S { @@ -807,12 +714,10 @@ void M() public static S operator++(S s) => default; } """); - } [Fact] - public async Task TestOnStructThatReadsFromThis1() - { - await TestAsync( + public Task TestOnStructThatReadsFromThis1() + => TestAsync( """ struct [|S|] { @@ -839,12 +744,10 @@ void M() void Goo(in S s) { } } """); - } [Fact] - public async Task TestOnStructThatReadsFromThis2() - { - await TestAsync( + public Task TestOnStructThatReadsFromThis2() + => TestAsync( """ struct [|S|] { @@ -871,12 +774,10 @@ void M() void Goo() { } } """); - } [Fact] - public async Task TestOnStructThatReadsFromThis3() - { - await TestAsync( + public Task TestOnStructThatReadsFromThis3() + => TestAsync( """ struct [|S|] { @@ -909,12 +810,10 @@ static class Extensions public static void Goo(this S s) { } } """); - } [Fact] - public async Task TestOnStructThatReadsFromThis4() - { - await TestAsync( + public Task TestOnStructThatReadsFromThis4() + => TestAsync( """ struct [|S|] { @@ -937,12 +836,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69994")] - public async Task NotWithFieldLikeEvent() - { - await TestMissingAsync( + public Task NotWithFieldLikeEvent() + => TestMissingAsync( """ using System; @@ -953,12 +850,10 @@ public struct MyStruct public readonly int MyInt; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69994")] - public async Task WithPropertyLikeEvent1() - { - await TestAsync( + public Task WithPropertyLikeEvent1() + => TestAsync( """ using System; @@ -979,12 +874,10 @@ public event Action MyEvent { add { } remove { } } public readonly int MyInt; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69994")] - public async Task WithPropertyLikeEvent2() - { - await TestAsync( + public Task WithPropertyLikeEvent2() + => TestAsync( """ using System; using System.Collections.Generic; @@ -1011,12 +904,10 @@ public readonly struct MyStruct public MyStruct() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69994")] - public async Task NotWithPropertyLikeEvent1() - { - await TestMissingAsync( + public Task NotWithPropertyLikeEvent1() + => TestMissingAsync( """ using System; using System.Collections.Generic; @@ -1030,5 +921,4 @@ public struct MyStruct public MyStruct() { } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/MakeTypeAbstract/MakeTypeAbstractTests.cs b/src/Analyzers/CSharp/Tests/MakeTypeAbstract/MakeTypeAbstractTests.cs index 91aab30ba0253..40c1c95956b42 100644 --- a/src/Analyzers/CSharp/Tests/MakeTypeAbstract/MakeTypeAbstractTests.cs +++ b/src/Analyzers/CSharp/Tests/MakeTypeAbstract/MakeTypeAbstractTests.cs @@ -26,9 +26,8 @@ internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProvide => (null, new CSharpMakeTypeAbstractCodeFixProvider()); [Fact] - public async Task TestMethod() - { - await TestInRegularAndScript1Async( + public Task TestMethod() + => TestInRegularAndScript1Async( """ public class Goo { @@ -41,12 +40,10 @@ public abstract class Goo public abstract void M(); } """); - } [Fact] - public async Task TestMethodEnclosingClassWithoutAccessibility() - { - await TestInRegularAndScript1Async( + public Task TestMethodEnclosingClassWithoutAccessibility() + => TestInRegularAndScript1Async( """ class Goo { @@ -59,12 +56,10 @@ abstract class Goo public abstract void M(); } """); - } [Fact] - public async Task TestMethodEnclosingClassDocumentationComment() - { - await TestInRegularAndScript1Async( + public Task TestMethodEnclosingClassDocumentationComment() + => TestInRegularAndScript1Async( """ /// /// Some class comment. @@ -83,12 +78,10 @@ public abstract class Goo public abstract void M(); } """); - } [Fact] - public async Task TestPropertyGetter() - { - await TestInRegularAndScript1Async( + public Task TestPropertyGetter() + => TestInRegularAndScript1Async( """ public class Goo { @@ -101,12 +94,10 @@ public abstract class Goo public abstract object P { get; } } """); - } [Fact] - public async Task TestPropertySetter() - { - await TestInRegularAndScript1Async( + public Task TestPropertySetter() + => TestInRegularAndScript1Async( """ public class Goo { @@ -119,12 +110,10 @@ public abstract class Goo public abstract object P { set; } } """); - } [Fact] - public async Task TestIndexerGetter() - { - await TestInRegularAndScript1Async( + public Task TestIndexerGetter() + => TestInRegularAndScript1Async( """ public class Goo { @@ -137,12 +126,10 @@ public abstract class Goo public abstract object this[object o] { get; } } """); - } [Fact] - public async Task TestIndexerSetter() - { - await TestInRegularAndScript1Async( + public Task TestIndexerSetter() + => TestInRegularAndScript1Async( """ public class Goo { @@ -155,12 +142,10 @@ public abstract class Goo public abstract object this[object o] { set; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/54218")] - public async Task TestPartialClass() - { - await TestInRegularAndScript1Async( + public Task TestPartialClass() + => TestInRegularAndScript1Async( """ public partial class Goo { @@ -181,60 +166,50 @@ public partial class Goo { } """); - } [Fact] - public async Task TestEventAdd() - { - await TestMissingInRegularAndScriptAsync( + public Task TestEventAdd() + => TestMissingInRegularAndScriptAsync( """ public class Goo { public abstract event System.EventHandler E { [|add|]; } } """); - } [Fact] - public async Task TestEventRemove() - { - await TestMissingInRegularAndScriptAsync( + public Task TestEventRemove() + => TestMissingInRegularAndScriptAsync( """ public class Goo { public abstract event System.EventHandler E { [|remove|]; } } """); - } [Fact] - public async Task TestMethodWithBody() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMethodWithBody() + => TestMissingInRegularAndScriptAsync( """ public class Goo { public abstract int [|M|]() => 3; } """); - } [Fact] - public async Task TestPropertyGetterWithArrowBody() - { - await TestMissingInRegularAndScriptAsync( + public Task TestPropertyGetterWithArrowBody() + => TestMissingInRegularAndScriptAsync( """ public class Goo { public abstract int [|P|] => 3; } """); - } [Fact] - public async Task TestPropertyGetterWithBody() - { - await TestMissingInRegularAndScriptAsync( + public Task TestPropertyGetterWithBody() + => TestMissingInRegularAndScriptAsync( """ public class Goo { @@ -244,12 +219,10 @@ public abstract int P } } """); - } [Fact] - public async Task TestStructNestedInClass() - { - await TestMissingInRegularAndScriptAsync( + public Task TestStructNestedInClass() + => TestMissingInRegularAndScriptAsync( """ public class C { @@ -259,24 +232,20 @@ public struct S } } """); - } [Fact] - public async Task TestMethodEnclosingClassStatic() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMethodEnclosingClassStatic() + => TestMissingInRegularAndScriptAsync( """ public static class Goo { public abstract void [|M|](); } """); - } [Fact] - public async Task TestRecord() - { - await TestInRegularAndScript1Async( + public Task TestRecord() + => TestInRegularAndScript1Async( """ public record Goo { @@ -289,12 +258,10 @@ public abstract record Goo public abstract void M(); } """); - } [Fact] - public async Task TestRecordClass() - { - await TestInRegularAndScript1Async( + public Task TestRecordClass() + => TestInRegularAndScript1Async( """ public record class Goo { @@ -307,23 +274,19 @@ public abstract record class Goo public abstract void M(); } """); - } [Fact] - public async Task TestRecordStruct() - { - await TestMissingInRegularAndScriptAsync(""" + public Task TestRecordStruct() + => TestMissingInRegularAndScriptAsync(""" public record struct Goo { public abstract void [|M|](); } """); - } [Fact] - public async Task FixAll() - { - await TestInRegularAndScript1Async( + public Task FixAll() + => TestInRegularAndScript1Async( """ namespace NS { @@ -376,5 +339,4 @@ public abstract class InnerClass } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/MakeTypePartial/MakeTypePartialTests.cs b/src/Analyzers/CSharp/Tests/MakeTypePartial/MakeTypePartialTests.cs index f58d5f83e2b14..8c3b4e8dcd1c9 100644 --- a/src/Analyzers/CSharp/Tests/MakeTypePartial/MakeTypePartialTests.cs +++ b/src/Analyzers/CSharp/Tests/MakeTypePartial/MakeTypePartialTests.cs @@ -31,9 +31,8 @@ public static IEnumerable AllValidDeclarationTypes() [Theory] [MemberData(nameof(AllValidDeclarationTypes))] - public async Task OutsideNamespace(string declarationType) - { - await new VerifyCS.Test + public Task OutsideNamespace(string declarationType) + => new VerifyCS.Test { TestCode = $$""" partial {{declarationType}} Declaration @@ -55,13 +54,11 @@ public async Task OutsideNamespace(string declarationType) """, LanguageVersion = LanguageVersion.CSharp10 }.RunAsync(); - } [Theory] [MemberData(nameof(AllValidDeclarationTypes))] - public async Task InsideOneFileScopedNamespace(string declarationType) - { - await new VerifyCS.Test + public Task InsideOneFileScopedNamespace(string declarationType) + => new VerifyCS.Test { TestCode = $$""" namespace TestNamespace; @@ -87,13 +84,11 @@ namespace TestNamespace; """, LanguageVersion = LanguageVersion.CSharp10 }.RunAsync(); - } [Theory] [MemberData(nameof(AllValidDeclarationTypes))] - public async Task InsideOneBlockScopedNamespace(string declarationType) - { - await new VerifyCS.Test + public Task InsideOneBlockScopedNamespace(string declarationType) + => new VerifyCS.Test { TestCode = $$""" namespace TestNamespace @@ -121,13 +116,11 @@ namespace TestNamespace """, LanguageVersion = LanguageVersion.CSharp10 }.RunAsync(); - } [Theory] [MemberData(nameof(AllValidDeclarationTypes))] - public async Task InsideTwoEqualBlockScopedNamespaces(string declarationType) - { - await new VerifyCS.Test + public Task InsideTwoEqualBlockScopedNamespaces(string declarationType) + => new VerifyCS.Test { TestCode = $$""" namespace TestNamespace @@ -161,7 +154,6 @@ namespace TestNamespace """, LanguageVersion = LanguageVersion.CSharp10 }.RunAsync(); - } [Theory] [MemberData(nameof(AllValidDeclarationTypes))] @@ -201,9 +193,8 @@ public async Task InDifferentDocuments(string declarationType) [Theory] [MemberData(nameof(AllValidDeclarationTypes))] - public async Task WithOtherModifiers(string declarationType) - { - await new VerifyCS.Test + public Task WithOtherModifiers(string declarationType) + => new VerifyCS.Test { TestCode = $$""" public partial {{declarationType}} Declaration @@ -225,13 +216,11 @@ public partial {{declarationType}} Declaration """, LanguageVersion = LanguageVersion.CSharp10 }.RunAsync(); - } [Theory] [MemberData(nameof(AllValidDeclarationTypes))] - public async Task NestedType1(string declarationType) - { - await new VerifyCS.Test + public Task NestedType1(string declarationType) + => new VerifyCS.Test { TestCode = $$""" class Test @@ -259,13 +248,11 @@ public partial {{declarationType}} Declaration """, LanguageVersion = LanguageVersion.CSharp10 }.RunAsync(); - } [Theory] [MemberData(nameof(AllValidDeclarationTypes))] - public async Task NestedType2(string declarationType) - { - await new VerifyCS.Test + public Task NestedType2(string declarationType) + => new VerifyCS.Test { TestCode = $$""" partial {{declarationType}} Test @@ -301,7 +288,6 @@ public partial {{declarationType}} Declaration """, LanguageVersion = LanguageVersion.CSharp10 }.RunAsync(); - } [Theory] [MemberData(nameof(AllValidDeclarationTypes))] @@ -355,9 +341,10 @@ public async Task FixOne(string declarationType) [Theory] [MemberData(nameof(AllValidDeclarationTypes))] - public async Task NotInDifferentNamespaces(string declarationType) - { - var markup = $$""" + public Task NotInDifferentNamespaces(string declarationType) + => new VerifyCS.Test + { + TestCode = $$""" namespace TestNamespace1 { partial {{declarationType}} Declaration @@ -371,12 +358,7 @@ namespace TestNamespace2 { } } - """; - - await new VerifyCS.Test - { - TestCode = markup, + """, LanguageVersion = LanguageVersion.CSharp10 }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/MatchFolderAndNamespace/CSharpMatchFolderAndNamespaceTests.cs b/src/Analyzers/CSharp/Tests/MatchFolderAndNamespace/CSharpMatchFolderAndNamespaceTests.cs index 4801d3cf32677..b32b0f64a8476 100644 --- a/src/Analyzers/CSharp/Tests/MatchFolderAndNamespace/CSharpMatchFolderAndNamespaceTests.cs +++ b/src/Analyzers/CSharp/Tests/MatchFolderAndNamespace/CSharpMatchFolderAndNamespaceTests.cs @@ -83,7 +83,8 @@ public Task InvalidFolderName1_NoDiagnostic() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(["3B", "C"]); - var code = + return RunTestAsync( + "File1.cs", """ namespace A.B { @@ -91,11 +92,7 @@ class Class1 { } } - """; - - return RunTestAsync( - "File1.cs", - code, + """, directory: folder); } @@ -104,18 +101,15 @@ public Task InvalidFolderName1_NoDiagnostic_FileScopedNamespace() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(["3B", "C"]); - var code = + return RunTestAsync( + "File1.cs", """ namespace A.B; class Class1 { } - """; - - return RunTestAsync( - "File1.cs", - code, + """, directory: folder); } @@ -124,7 +118,8 @@ public Task InvalidFolderName2_NoDiagnostic() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(["B.3C", "D"]); - var code = + return RunTestAsync( + "File1.cs", """ namespace A.B { @@ -132,11 +127,7 @@ class Class1 { } } - """; - - return RunTestAsync( - "File1.cs", - code, + """, directory: folder); } @@ -145,7 +136,8 @@ public Task InvalidFolderName3_NoDiagnostic() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath([".folder", "..subfolder", "name"]); - var code = + return RunTestAsync( + "File1.cs", """ namespace A.B { @@ -153,11 +145,7 @@ class Class1 { } } - """; - - return RunTestAsync( - "File1.cs", - code, + """, directory: folder); } @@ -165,7 +153,8 @@ class Class1 public Task CaseInsensitiveMatch_NoDiagnostic() { var folder = CreateFolderPath(["A", "B"]); - var code = + return RunTestAsync( + "File1.cs", $$""" namespace {{DefaultNamespace}}.a.b { @@ -173,11 +162,7 @@ class Class1 { } } - """; - - return RunTestAsync( - "File1.cs", - code, + """, directory: folder); } @@ -185,19 +170,16 @@ class Class1 public async Task CodeStyleOptionIsFalse() { var folder = CreateFolderPath("B", "C"); - var code = - """ + await RunTestAsync( + fileName: "Class1.cs", + fileContents: """ namespace A.B { class Class1 { } } - """; - - await RunTestAsync( - fileName: "Class1.cs", - fileContents: code, + """, directory: folder, editorConfig: EditorConfig + """ @@ -209,16 +191,6 @@ await RunTestAsync( public async Task SingleDocumentNoReference() { var folder = CreateFolderPath("B", "C"); - var code = - """ - namespace [|A.B|] - { - class Class1 - { - } - } - """; - var fixedCode = $$""" namespace {{DefaultNamespace}}.B.C @@ -230,7 +202,14 @@ class Class1 """; await RunTestAsync( fileName: "Class1.cs", - fileContents: code, + fileContents: """ + namespace [|A.B|] + { + class Class1 + { + } + } + """, directory: folder, fixedCode: fixedCode); } @@ -239,15 +218,6 @@ await RunTestAsync( public async Task SingleDocumentNoReference_FileScopedNamespace() { var folder = CreateFolderPath("B", "C"); - var code = - """ - namespace [|A.B|]; - - class Class1 - { - } - """; - var fixedCode = $$""" namespace {{DefaultNamespace}}.B.C; @@ -258,7 +228,13 @@ class Class1 """; await RunTestAsync( fileName: "Class1.cs", - fileContents: code, + fileContents: """ + namespace [|A.B|]; + + class Class1 + { + } + """, directory: folder, fixedCode: fixedCode); } @@ -272,16 +248,6 @@ public async Task SingleDocumentNoReference_NoDefaultNamespace() """; var folder = CreateFolderPath("B", "C"); - var code = - """ - namespace [|A.B|] - { - class Class1 - { - } - } - """; - var fixedCode = $$""" namespace B.C @@ -293,7 +259,14 @@ class Class1 """; await RunTestAsync( fileName: "Class1.cs", - fileContents: code, + fileContents: """ + namespace [|A.B|] + { + class Class1 + { + } + } + """, directory: folder, fixedCode: fixedCode, editorConfig: editorConfig, @@ -310,15 +283,6 @@ public async Task SingleDocumentNoReference_NoDefaultNamespace_FileScopedNamespa """; var folder = CreateFolderPath("B", "C"); - var code = - """ - namespace [|A.B|]; - - class Class1 - { - } - """; - var fixedCode = """ namespace B.C; @@ -329,7 +293,13 @@ class Class1 """; await RunTestAsync( fileName: "Class1.cs", - fileContents: code, + fileContents: """ + namespace [|A.B|]; + + class Class1 + { + } + """, directory: folder, fixedCode: fixedCode, editorConfig: editorConfig, @@ -341,19 +311,16 @@ await RunTestAsync( public async Task NamespaceWithSpaces_NoDiagnostic() { var folder = CreateFolderPath("A", "B"); - var code = - $$""" + await RunTestAsync( + fileName: "Class1.cs", + fileContents: $$""" namespace {{DefaultNamespace}}.A . B { class Class1 { } } - """; - - await RunTestAsync( - fileName: "Class1.cs", - fileContents: code, + """, directory: folder); } @@ -364,8 +331,9 @@ public async Task NestedNamespaces_NoDiagnostic() // diagnostic does not report. var folder = CreateFolderPath("B", "C"); - var code = - """ + await RunTestAsync( + fileName: "Class1.cs", + fileContents: """ namespace A.B { namespace C.D @@ -379,11 +347,7 @@ class ABClass { } } - """; - - await RunTestAsync( - fileName: "Class1.cs", - fileContents: code, + """, directory: folder); } @@ -433,19 +397,16 @@ public async Task FileNotInProjectFolder_NoDiagnostic() // diagnostic shown. var folder = Path.Combine("B", "C"); - var code = - $$""" + await RunTestAsync( + fileName: "Class1.cs", + fileContents: $$""" namespace A.B { class ABClass { } } - """; - - await RunTestAsync( - fileName: "Class1.cs", - fileContents: code, + """, directory: folder); } @@ -455,7 +416,8 @@ public async Task SingleDocumentLocalReference() var @namespace = "Bar.Baz"; var folder = CreateFolderPath("A", "B", "C"); - var code = + await RunTestAsync( + "Class1.cs", $$""" namespace [|{{@namespace}}|] { @@ -473,10 +435,9 @@ class Class2 : {{@namespace}}.Class1 void {{@namespace}}.Class1.M1() { } } } - """; - - var expected = - $$""" + """, + folder, + fixedCode: $$""" namespace {{DefaultNamespace}}.A.B.C { delegate void D1(); @@ -493,13 +454,7 @@ class Class2 : Class1 void Class1.M1() { } } } - """; - - await RunTestAsync( - "Class1.cs", - code, - folder, - fixedCode: expected); + """); } [Fact] @@ -591,17 +546,14 @@ class Class2 public async Task DocumentAtRoot_NoDiagnostic() { var folder = CreateFolderPath(); - - var code = $$""" + await RunTestAsync( + "File1.cs", + $$""" namespace {{DefaultNamespace}} { class C { } } - """; - - await RunTestAsync( - "File1.cs", - code, + """, folder); } @@ -609,15 +561,6 @@ await RunTestAsync( public async Task DocumentAtRoot_ChangeNamespace() { var folder = CreateFolderPath(); - - var code = - $$""" - namespace [|{{DefaultNamespace}}.Test|] - { - class C { } - } - """; - var fixedCode = $$""" namespace {{DefaultNamespace}} @@ -628,7 +571,12 @@ class C { } await RunTestAsync( "File1.cs", - code, + $$""" + namespace [|{{DefaultNamespace}}.Test|] + { + class C { } + } + """, folder, fixedCode: fixedCode); } @@ -1008,15 +956,6 @@ public async Task InvalidProjectName_ChangeNamespace() """; var folder = CreateFolderPath(["B", "C"]); - var code = - """ - namespace [|A.B|] - { - class Class1 - { - } - } - """; // The project name is invalid so the default namespace is not prepended var fixedCode = @@ -1031,7 +970,14 @@ class Class1 await RunTestAsync( "Class1.cs", - fileContents: code, + fileContents: """ + namespace [|A.B|] + { + class Class1 + { + } + } + """, fixedCode: fixedCode, directory: folder, editorConfig: editorConfig, @@ -1049,18 +995,14 @@ public async Task InvalidProjectName_DocumentAtRoot_ChangeNamespace() """; var folder = CreateFolderPath(); - - var code = - $$""" + await RunTestAsync( + "Class1.cs", + fileContents: $$""" namespace Test.Code { class C { } } - """; - - await RunTestAsync( - "Class1.cs", - fileContents: code, + """, directory: folder, editorConfig: editorConfig, defaultNamespace: defaultNamespace); @@ -1076,18 +1018,14 @@ public async Task InvalidRootNamespace_DocumentAtRoot_ChangeNamespace() """; var folder = CreateFolderPath(); - - var code = - $$""" + await RunTestAsync( + "Class1.cs", + fileContents: $$""" namespace Test.Code { class C { } } - """; - - await RunTestAsync( - "Class1.cs", - fileContents: code, + """, directory: folder, editorConfig: editorConfig, defaultNamespace: "Invalid-Namespace"); diff --git a/src/Analyzers/CSharp/Tests/MisplacedUsingDirectives/MisplacedUsingDirectivesTests.cs b/src/Analyzers/CSharp/Tests/MisplacedUsingDirectives/MisplacedUsingDirectivesTests.cs index 155884fb77d24..db2deb9a0aca8 100644 --- a/src/Analyzers/CSharp/Tests/MisplacedUsingDirectives/MisplacedUsingDirectivesTests.cs +++ b/src/Analyzers/CSharp/Tests/MisplacedUsingDirectives/MisplacedUsingDirectivesTests.cs @@ -104,28 +104,24 @@ private Task TestInRegularAndScriptAsync( [Fact] public Task WhenPreserve_UsingsInNamespace_ValidUsingStatements() { - var testCode = """ + return TestDiagnosticMissingAsync(""" namespace TestNamespace { [|using System; using System.Threading;|] } - """; - - return TestDiagnosticMissingAsync(testCode, OutsidePreferPreservationOption); + """, OutsidePreferPreservationOption); } [Fact] public Task WhenPreserve_UsingsInNamespace_ValidUsingStatements_FileScopedNamespace() { - var testCode = """ + return TestDiagnosticMissingAsync(""" namespace TestNamespace; [|using System; using System.Threading;|] - """; - - return TestDiagnosticMissingAsync(testCode, OutsidePreferPreservationOption); + """, OutsidePreferPreservationOption); } /// @@ -135,16 +131,14 @@ namespace TestNamespace; [Fact] public Task WhenPreserve_UsingsInCompilationUnitAndNamespace_ValidUsingStatements() { - var testCode = """ + return TestDiagnosticMissingAsync(""" using System; namespace TestNamespace { [|using System.Threading;|] } - """; - - return TestDiagnosticMissingAsync(testCode, OutsidePreferPreservationOption); + """, OutsidePreferPreservationOption); } /// @@ -159,13 +153,11 @@ namespace TestNamespace [InlineData(DelegateDefinition)] public Task WhenPreserve_UsingsInCompilationUnitWithTypeDefinition_ValidUsingStatements(string typeDefinition) { - var testCode = $""" + return TestDiagnosticMissingAsync($""" [|using System;|] {typeDefinition} - """; - - return TestDiagnosticMissingAsync(testCode, InsidePreferPreservationOption); + """, InsidePreferPreservationOption); } /// @@ -174,7 +166,7 @@ public Task WhenPreserve_UsingsInCompilationUnitWithTypeDefinition_ValidUsingSta [Fact] public Task WhenPreserve_UsingsInCompilationUnitWithAttributes_ValidUsingStatements() { - var testCode = """ + return TestDiagnosticMissingAsync(""" [|using System.Reflection;|] [assembly: AssemblyVersion("1.0.0.0")] @@ -184,9 +176,7 @@ namespace TestNamespace using System; using System.Threading; } - """; - - return TestDiagnosticMissingAsync(testCode, InsidePreferPreservationOption); + """, InsidePreferPreservationOption); } /// @@ -196,16 +186,14 @@ namespace TestNamespace [Fact] public Task WhenPreserve_UsingsInCompilationUnit_ValidUsingStatements() { - var testCode = """ + return TestDiagnosticMissingAsync(""" [|using System; using System.Threading;|] namespace TestNamespace { } - """; - - return TestDiagnosticMissingAsync(testCode, InsidePreferPreservationOption); + """, InsidePreferPreservationOption); } #endregion @@ -218,29 +206,25 @@ namespace TestNamespace [Fact] public Task WhenOutsidePreferred_UsingsInCompilationUnit_ValidUsingStatements() { - var testCode = """ + return TestDiagnosticMissingAsync(""" [|using System; using System.Threading;|] namespace TestNamespace { } - """; - - return TestDiagnosticMissingAsync(testCode, OutsideNamespaceOption); + """, OutsideNamespaceOption); } [Fact] public Task WhenOutsidePreferred_UsingsInCompilationUnit_ValidUsingStatements_FileScopedNamespace() { - var testCode = """ + return TestDiagnosticMissingAsync(""" [|using System; using System.Threading;|] namespace TestNamespace; - """; - - return TestDiagnosticMissingAsync(testCode, OutsideNamespaceOption); + """, OutsideNamespaceOption); } /// @@ -255,13 +239,11 @@ namespace TestNamespace; [InlineData(DelegateDefinition)] public Task WhenOutsidePreferred_UsingsInCompilationUnitWithMember_ValidUsingStatements(string typeDefinition) { - var testCode = $""" + return TestDiagnosticMissingAsync($""" [|using System;|] {typeDefinition} - """; - - return TestDiagnosticMissingAsync(testCode, OutsideNamespaceOption); + """, OutsideNamespaceOption); } /// @@ -270,43 +252,37 @@ public Task WhenOutsidePreferred_UsingsInCompilationUnitWithMember_ValidUsingSta [Fact] public Task WhenOutsidePreferred_UsingsInNamespace_UsingsMoved() { - var testCode = """ + return TestInRegularAndScriptAsync(""" namespace TestNamespace { [|using System; using System.Threading;|] } - """; - var fixedTestCode = """ + """, """ {|Warning:using System;|} {|Warning:using System.Threading;|} namespace TestNamespace { } - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); + """, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } [Fact] public Task WhenOutsidePreferred_UsingsInNamespace_UsingsMoved_FileScopedNamespace() { - var testCode = """ + return TestInRegularAndScriptAsync(""" namespace TestNamespace; [|using System; using System.Threading;|] - """; - var fixedTestCode = """ + """, """ {|Warning:using System;|} {|Warning:using System.Threading;|} namespace TestNamespace; - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); + """, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } /// @@ -315,15 +291,14 @@ namespace TestNamespace; [Fact] public Task WhenOutsidePreferred_SimplifiedUsingInNamespace_UsingsMovedAndExpanded() { - var testCode = """ + return TestInRegularAndScriptAsync(""" namespace System { [|using System; using System.Threading; using Reflection;|] } - """; - var fixedTestCode = """ + """, """ {|Warning:using System;|} {|Warning:using System.Threading;|} {|Warning:using System.Reflection;|} @@ -331,9 +306,7 @@ namespace System namespace System { } - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); + """, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } /// @@ -342,25 +315,21 @@ namespace System [Fact] public Task WhenOutsidePreferred_UsingsInBoth_UsingsMoved() { - var testCode = """ + return TestInRegularAndScriptAsync(""" using Microsoft.CodeAnalysis; namespace TestNamespace { [|using System;|] } - """; - - var fixedTestCode = """ + """, """ using Microsoft.CodeAnalysis; {|Warning:using System;|} namespace TestNamespace { } - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); + """, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } /// @@ -369,7 +338,7 @@ namespace TestNamespace [Fact] public Task WhenOutsidePreferred_SimplifiedUsingAliasInNamespace_UsingsMovedAndExpanded() { - var testCode = """ + return TestInRegularAndScriptAsync(""" namespace System.MyExtension { [|using System.Threading; @@ -377,8 +346,7 @@ namespace System.MyExtension using Assembly = Reflection.Assembly; using List = Collections.Generic.IList;|] } - """; - var fixedTestCode = """ + """, """ {|Warning:using System.Threading;|} {|Warning:using System.Reflection;|} {|Warning:using Assembly = System.Reflection.Assembly;|} @@ -387,9 +355,7 @@ namespace System.MyExtension namespace System.MyExtension { } - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); + """, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } /// @@ -398,7 +364,7 @@ namespace System.MyExtension [Fact] public Task WhenOutsidePreferred_UsingsInNamespaceAndCompilationUnitWithAttributes_UsingsMoved() { - var testCode = """ + return TestInRegularAndScriptAsync(""" using System.Reflection; [assembly: AssemblyVersion("1.0.0.0")] @@ -408,8 +374,7 @@ namespace TestNamespace [|using System; using System.Threading;|] } - """; - var fixedTestCode = """ + """, """ using System.Reflection; {|Warning:using System;|} {|Warning:using System.Threading;|} @@ -419,9 +384,7 @@ namespace TestNamespace namespace TestNamespace { } - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); + """, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } /// @@ -430,7 +393,7 @@ namespace TestNamespace [Fact] public Task WhenOutsidePreferred_UsingsInNamespaceAndCompilationUnitHasFileHeader_UsingsMovedAndHeaderPreserved() { - var testCode = """ + return TestInRegularAndScriptAsync(""" // Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. @@ -438,8 +401,7 @@ namespace TestNamespace { [|using System;|] } - """; - var fixedTestCode = """ + """, """ // Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. @@ -448,15 +410,13 @@ namespace TestNamespace namespace TestNamespace { } - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); + """, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } [Fact] public Task WhenOutsidePreferred_UsingsInNamespaceWithCommentsAndCompilationUnitHasFileHeader_UsingsMovedWithCommentsAndHeaderPreserved() { - var testCode = """ + return TestInRegularAndScriptAsync(""" // Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. @@ -468,8 +428,7 @@ namespace TestNamespace // Comment using System;|] } - """; - var fixedTestCode = """ + """, """ // Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. @@ -482,15 +441,13 @@ namespace TestNamespace namespace TestNamespace { } - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); + """, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } [Fact] public Task WhenOutsidePreferred_UsingsInNamespace_UsingsMovedAndSystemPlacedFirstIgnored() { - var testCode = """ + return TestInRegularAndScriptAsync(""" namespace Foo { [|using Microsoft.CodeAnalysis; @@ -508,9 +465,7 @@ public class Bar { } } - """; - - var fixedTestCode = """ + """, """ {|Warning:using Microsoft.CodeAnalysis;|} {|Warning:using SystemAction = System.Action;|} {|Warning:using static System.Math;|} @@ -528,15 +483,13 @@ public class Bar { } } - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); + """, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } [Fact] public Task WhenOutsidePreferred_UsingsInNamespace_UsingsMovedAndAlphaSortIgnored() { - var testCode = """ + return TestInRegularAndScriptAsync(""" namespace Foo { [|using Microsoft.CodeAnalysis; @@ -554,9 +507,7 @@ public class Bar { } } - """; - - var fixedTestCode = """ + """, """ {|Warning:using Microsoft.CodeAnalysis;|} {|Warning:using SystemAction = System.Action;|} {|Warning:using static System.Math;|} @@ -574,9 +525,7 @@ public class Bar { } } - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: false); + """, OutsideNamespaceOption, placeSystemNamespaceFirst: false); } /// @@ -585,7 +534,7 @@ public class Bar [Fact] public Task WhenOutsidePreferred_UsingsInNestedNamespaces_UsingsMovedAndExpanded() { - var testCode = """ + return TestInRegularAndScriptAsync(""" using System; namespace System.Namespace @@ -599,8 +548,7 @@ namespace OtherNamespace using Reflection;|] } } - """; - var fixedTestCode = """ + """, """ using System; // Outer Comment {|Warning:using System.Threading;|} @@ -613,9 +561,7 @@ namespace OtherNamespace { } } - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); + """, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } /// @@ -624,7 +570,7 @@ namespace OtherNamespace [Fact] public Task WhenOutsidePreferred_UsingsInMultipleNamespaces_UsingsMovedAndExpanded() { - var testCode = """ + return TestInRegularAndScriptAsync(""" using System; namespace System.Namespace @@ -638,8 +584,7 @@ namespace System.OtherNamespace // Another Comment using Reflection;|] } - """; - var fixedTestCode = """ + """, """ using System; // A Comment {|Warning:using System.Threading;|} @@ -653,9 +598,7 @@ namespace System.Namespace namespace System.OtherNamespace { } - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); + """, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } /// @@ -664,7 +607,7 @@ namespace System.OtherNamespace [Fact] public Task WhenOutsidePreferred_UsingsInMultipleNamespaces_UsingsMovedAndDeduplicated() { - var testCode = """ + return TestInRegularAndScriptAsync(""" using System; namespace System.Namespace @@ -680,8 +623,7 @@ namespace B // Orphaned Comment 2 using System.Threading;|] } - """; - var fixedTestCode = """ + """, """ using System; // Orphaned Comment 1 // A Comment @@ -695,30 +637,24 @@ namespace System.Namespace namespace B { } - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); + """, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61773")] public Task WhenOutsidePreferred_MoveGlobalUsing1() { - var testCode = """ + return TestInRegularAndScriptAsync(""" namespace N1 { [|global using System;|] } - """; - var fixedTestCode = - """ + """, """ {|Warning:global using System;|} namespace N1 { } - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); + """, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } #endregion @@ -728,15 +664,14 @@ namespace N1 [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43271")] public Task WhenOutsideIgnoringAliasesPreferred_UsingsInNamespace_UsingsMoved() { - var testCode = """ + return TestInRegularAndScriptAsync(""" namespace TestNamespace { [|using System; using System.Threading;|] using SCG = System.Collections.Generic; } - """; - var fixedTestCode = """ + """, """ {|Warning:using System;|} {|Warning:using System.Threading;|} @@ -744,15 +679,13 @@ namespace TestNamespace { using SCG = System.Collections.Generic; } - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceIgnoringAliasesOption, placeSystemNamespaceFirst: true); + """, OutsideNamespaceIgnoringAliasesOption, placeSystemNamespaceFirst: true); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43271")] public Task WhenOutsideIgnoringAliasesPreferred_UsingsInNamespace_UsingsMoved_InnerType() { - var testCode = """ + return TestInRegularAndScriptAsync(""" namespace TestNamespace { [|using System; @@ -763,8 +696,7 @@ class C { } } - """; - var fixedTestCode = """ + """, """ {|Warning:using System;|} {|Warning:using System.Threading;|} @@ -776,15 +708,13 @@ class C { } } - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceIgnoringAliasesOption, placeSystemNamespaceFirst: true); + """, OutsideNamespaceIgnoringAliasesOption, placeSystemNamespaceFirst: true); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43271")] public Task WhenOutsideIgnoringAliasesPreferred_UsingsInNamespace_UsingsMoved_AliasInMiddle() { - var testCode = """ + return TestInRegularAndScriptAsync(""" namespace TestNamespace { [|using System; @@ -795,8 +725,7 @@ class C { } } - """; - var fixedTestCode = """ + """, """ {|Warning:using System;|} {|Warning:using System.Threading;|} @@ -808,9 +737,7 @@ class C { } } - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceIgnoringAliasesOption, placeSystemNamespaceFirst: true); + """, OutsideNamespaceIgnoringAliasesOption, placeSystemNamespaceFirst: true); } #endregion @@ -823,28 +750,24 @@ class C [Fact] public Task WhenInsidePreferred_UsingsInNamespace_ValidUsingStatements() { - var testCode = """ + return TestDiagnosticMissingAsync(""" namespace TestNamespace { [|using System; using System.Threading;|] } - """; - - return TestDiagnosticMissingAsync(testCode, InsideNamespaceOption); + """, InsideNamespaceOption); } [Fact] public Task WhenInsidePreferred_UsingsInNamespace_ValidUsingStatements_FileScopedNamespace() { - var testCode = """ + return TestDiagnosticMissingAsync(""" namespace TestNamespace; [|using System; using System.Threading;|] - """; - - return TestDiagnosticMissingAsync(testCode, InsideNamespaceOption); + """, InsideNamespaceOption); } /// @@ -859,13 +782,11 @@ namespace TestNamespace; [InlineData(DelegateDefinition)] public Task WhenInsidePreferred_UsingsInCompilationUnitWithTypeDefinition_ValidUsingStatements(string typeDefinition) { - var testCode = $""" + return TestDiagnosticMissingAsync($""" [|using System;|] {typeDefinition} - """; - - return TestDiagnosticMissingAsync(testCode, InsideNamespaceOption); + """, InsideNamespaceOption); } /// @@ -874,7 +795,7 @@ public Task WhenInsidePreferred_UsingsInCompilationUnitWithTypeDefinition_ValidU [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnitWithAttributes_ValidUsingStatements() { - var testCode = """ + return TestDiagnosticMissingAsync(""" [|using System.Reflection;|] [assembly: AssemblyVersion("1.0.0.0")] @@ -884,9 +805,7 @@ namespace TestNamespace using System; using System.Threading; } - """; - - return TestDiagnosticMissingAsync(testCode, InsideNamespaceOption); + """, InsideNamespaceOption); } /// @@ -895,7 +814,7 @@ namespace TestNamespace [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnit_UsingsMovedAndSystemPlacedFirstIgnored() { - var testCode = """ + return TestInRegularAndScriptAsync(""" [|using Microsoft.CodeAnalysis; using SystemAction = System.Action; using static System.Math; @@ -913,9 +832,7 @@ public class Bar { } } - """; - - var fixedTestCode = """ + """, """ namespace Foo { {|Warning:using Microsoft.CodeAnalysis;|} @@ -933,9 +850,7 @@ public class Bar { } } - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); + """, InsideNamespaceOption, placeSystemNamespaceFirst: true); } /// @@ -944,7 +859,7 @@ public class Bar [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnit_UsingsAndWithAlphaSortIgnored() { - var testCode = """ + return TestInRegularAndScriptAsync(""" [|using Microsoft.CodeAnalysis; using SystemAction = System.Action; using static System.Math; @@ -962,9 +877,7 @@ public class Bar { } } - """; - - var fixedTestCode = """ + """, """ namespace NamespaceName { {|Warning:using Microsoft.CodeAnalysis;|} @@ -982,9 +895,7 @@ public class Bar { } } - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: false); + """, InsideNamespaceOption, placeSystemNamespaceFirst: false); } /// @@ -993,7 +904,7 @@ public class Bar [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnitWithFileHeader_UsingsMovedNotHeader() { - var testCode = """ + return TestInRegularAndScriptAsync(""" // This is a file header. [|using Microsoft.CodeAnalysis; using System;|] @@ -1001,18 +912,14 @@ public Task WhenInsidePreferred_UsingsInCompilationUnitWithFileHeader_UsingsMove namespace TestNamespace { } - """; - - var fixedTestCode = """ + """, """ // This is a file header. namespace TestNamespace { {|Warning:using Microsoft.CodeAnalysis;|} {|Warning:using System;|} } - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); + """, InsideNamespaceOption, placeSystemNamespaceFirst: true); } /// @@ -1021,46 +928,38 @@ namespace TestNamespace [Fact] public Task WhenInsidePreferred_UsingsInBoth_UsingsMoved() { - var testCode = """ + return TestInRegularAndScriptAsync(""" [|using Microsoft.CodeAnalysis;|] namespace TestNamespace { using System; } - """; - - var fixedTestCode = """ + """, """ namespace TestNamespace { {|Warning:using Microsoft.CodeAnalysis;|} using System; } - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); + """, InsideNamespaceOption, placeSystemNamespaceFirst: true); } [Fact] public Task WhenInsidePreferred_UsingsInBoth_UsingsMoved_FileScopedNamespace() { - var testCode = """ + return TestInRegularAndScriptAsync(""" [|using Microsoft.CodeAnalysis;|] namespace TestNamespace; using System; - """; - - var fixedTestCode = """ + """, """ namespace TestNamespace; {|Warning:using Microsoft.CodeAnalysis;|} using System; - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); + """, InsideNamespaceOption, placeSystemNamespaceFirst: true); } /// @@ -1069,7 +968,7 @@ namespace TestNamespace; [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnitWithFileHeaderAndTrivia_UsingsAndTriviaMovedNotHeader() { - var testCode = """ + return TestInRegularAndScriptAsync(""" // File Header // Leading Comment @@ -1080,9 +979,7 @@ public Task WhenInsidePreferred_UsingsInCompilationUnitWithFileHeaderAndTrivia_U namespace TestNamespace { } - """; - - var fixedTestCode = """ + """, """ // File Header namespace TestNamespace @@ -1092,9 +989,7 @@ namespace TestNamespace {|Warning:using Microsoft.CodeAnalysis;|} {|Warning:using System;|} } - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); + """, InsideNamespaceOption, placeSystemNamespaceFirst: true); } /// @@ -1103,7 +998,7 @@ namespace TestNamespace [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnitWithMultipleNamespaces_NoCodeFixOffered() { - var testCode = """ + return TestMissingAsync(""" [|using System;|] namespace TestNamespace1 @@ -1116,9 +1011,7 @@ public class TestClass1 namespace TestNamespace2 { } - """; - - return TestMissingAsync(testCode, InsideNamespaceOption); + """, InsideNamespaceOption); } /// @@ -1127,7 +1020,7 @@ namespace TestNamespace2 [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnitWithPragma_PragmaMoved() { - var testCode = """ + return TestInRegularAndScriptAsync(""" #pragma warning disable 1573 // Comment [|using System; using System.Threading;|] @@ -1135,18 +1028,14 @@ public Task WhenInsidePreferred_UsingsInCompilationUnitWithPragma_PragmaMoved() namespace TestNamespace { } - """; - - var fixedTestCode = """ + """, """ namespace TestNamespace { #pragma warning disable 1573 // Comment {|Warning:using System;|} {|Warning:using System.Threading;|} } - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); + """, InsideNamespaceOption, placeSystemNamespaceFirst: true); } /// @@ -1155,7 +1044,7 @@ namespace TestNamespace [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnitWithRegion_RegionMoved() { - var testCode = """ + return TestInRegularAndScriptAsync(""" #region Comment #endregion Comment [|using System; @@ -1164,9 +1053,7 @@ public Task WhenInsidePreferred_UsingsInCompilationUnitWithRegion_RegionMoved() namespace TestNamespace { } - """; - - var fixedTestCode = """ + """, """ namespace TestNamespace { #region Comment @@ -1174,9 +1061,7 @@ namespace TestNamespace {|Warning:using System;|} {|Warning:using System.Threading;|} } - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); + """, InsideNamespaceOption, placeSystemNamespaceFirst: true); } /// @@ -1185,7 +1070,7 @@ namespace TestNamespace [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnitWithCommentTrivia_TriviaMoved() { - var testCode = """ + return TestInRegularAndScriptAsync(""" // Some comment [|using System; @@ -1194,9 +1079,7 @@ public Task WhenInsidePreferred_UsingsInCompilationUnitWithCommentTrivia_TriviaM namespace TestNamespace { } - """; - - var fixedTestCode = """ + """, """ namespace TestNamespace { @@ -1204,47 +1087,39 @@ namespace TestNamespace {|Warning:using System;|} {|Warning:using System.Threading;|} } - """; - - return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); + """, InsideNamespaceOption, placeSystemNamespaceFirst: true); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61773")] public Task WhenInsidePreferred_DoNotMoveGlobalUsings1() { - var testCode = """ + return TestMissingAsync(""" [|global using System;|] namespace TestNamespace { } - """; - - return TestMissingAsync(testCode, InsideNamespaceOption); + """, InsideNamespaceOption); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61773")] public Task WhenInsidePreferred_DoNotMoveGlobalUsings2() { - var testCode = """ + return TestInRegularAndScriptAsync(""" [|global using System; using System.Threading;|] namespace TestNamespace { } - """; - - var fixedCode = """ + """, """ global using System; namespace TestNamespace { {|Warning:using System.Threading;|} } - """; - - return TestInRegularAndScriptAsync(testCode, fixedCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); + """, InsideNamespaceOption, placeSystemNamespaceFirst: true); } #endregion diff --git a/src/Analyzers/CSharp/Tests/NamingStyles/NamingStylesTests.cs b/src/Analyzers/CSharp/Tests/NamingStyles/NamingStylesTests.cs index a011670dbdd0d..338d19a599cd2 100644 --- a/src/Analyzers/CSharp/Tests/NamingStyles/NamingStylesTests.cs +++ b/src/Analyzers/CSharp/Tests/NamingStyles/NamingStylesTests.cs @@ -30,20 +30,17 @@ protected override TestComposition GetComposition() => base.GetComposition().AddParts(typeof(TestSymbolRenamedCodeActionOperationFactoryWorkspaceService)); [Fact] - public async Task TestPascalCaseClass_CorrectName() - { - await TestMissingInRegularAndScriptAsync( + public Task TestPascalCaseClass_CorrectName() + => TestMissingInRegularAndScriptAsync( """ class [|C|] { } """, new TestParameters(options: s_options.ClassNamesArePascalCase)); - } [Fact] - public async Task TestPascalCaseClass_NameGetsCapitalized() - { - await TestInRegularAndScriptAsync( + public Task TestPascalCaseClass_NameGetsCapitalized() + => TestInRegularAndScriptAsync( """ class [|c|] { @@ -55,7 +52,6 @@ class C } """, options: s_options.ClassNamesArePascalCase); - } [Theory] [InlineData("M_bar", "bar")] @@ -76,9 +72,8 @@ class C [InlineData("S_", "s_")] [InlineData("T_", "t_")] [InlineData("M_S__T_", "t_")] - public async Task TestCamelCaseField_PrefixGetsStripped(string fieldName, string correctedName) - { - await TestInRegularAndScriptAsync( + public Task TestCamelCaseField_PrefixGetsStripped(string fieldName, string correctedName) + => TestInRegularAndScriptAsync( $$""" class C { @@ -92,7 +87,6 @@ class C } """, options: s_options.FieldNamesAreCamelCase); - } [Theory] [InlineData("M_bar", "_bar")] @@ -114,9 +108,8 @@ class C [InlineData("S_", "_s_")] [InlineData("T_", "_t_")] [InlineData("M_S__T_", "_t_")] - public async Task TestCamelCaseField_PrefixGetsStrippedBeforeAddition(string fieldName, string correctedName) - { - await TestInRegularAndScriptAsync( + public Task TestCamelCaseField_PrefixGetsStrippedBeforeAddition(string fieldName, string correctedName) + => TestInRegularAndScriptAsync( $$""" class C { @@ -130,12 +123,10 @@ class C } """, options: s_options.FieldNamesAreCamelCaseWithUnderscorePrefix); - } [Fact] - public async Task TestPascalCaseMethod_CorrectName() - { - await TestMissingInRegularAndScriptAsync( + public Task TestPascalCaseMethod_CorrectName() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -144,7 +135,6 @@ class C } } """, new TestParameters(options: s_options.MethodNamesArePascalCase)); - } [Theory] [InlineData("")] @@ -289,9 +279,8 @@ class C } [Fact] - public async Task TestPascalCaseMethod_NameGetsCapitalized() - { - await TestInRegularAndScriptAsync( + public Task TestPascalCaseMethod_NameGetsCapitalized() + => TestInRegularAndScriptAsync( """ class C { @@ -309,12 +298,10 @@ void M() } """, options: s_options.MethodNamesArePascalCase); - } [Fact] - public async Task TestPascalCaseMethod_ConstructorsAreIgnored() - { - await TestMissingInRegularAndScriptAsync( + public Task TestPascalCaseMethod_ConstructorsAreIgnored() + => TestMissingInRegularAndScriptAsync( """ class c { @@ -323,24 +310,20 @@ class c } } """, new TestParameters(options: s_options.MethodNamesArePascalCase)); - } [Fact] - public async Task TestPascalCaseMethod_PropertyAccessorsAreIgnored() - { - await TestMissingInRegularAndScriptAsync( + public Task TestPascalCaseMethod_PropertyAccessorsAreIgnored() + => TestMissingInRegularAndScriptAsync( """ class C { public int P { [|get|]; set; } } """, new TestParameters(options: s_options.MethodNamesArePascalCase)); - } [Fact] - public async Task TestPascalCaseMethod_IndexerNameIsIgnored() - { - await TestMissingInRegularAndScriptAsync( + public Task TestPascalCaseMethod_IndexerNameIsIgnored() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -353,12 +336,10 @@ public int [|this|][int index] } } """, new TestParameters(options: s_options.MethodNamesArePascalCase)); - } [Fact] - public async Task TestPascalCaseMethod_LocalFunctionIsIgnored() - { - await TestMissingInRegularAndScriptAsync( + public Task TestPascalCaseMethod_LocalFunctionIsIgnored() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -370,12 +351,10 @@ void M() } } """, new TestParameters(options: s_options.MethodNamesArePascalCase)); - } [Fact] - public async Task TestCamelCaseParameters() - { - await TestInRegularAndScriptAsync( + public Task TestCamelCaseParameters() + => TestInRegularAndScriptAsync( """ class C { @@ -393,12 +372,10 @@ public void M(int x) } """, options: s_options.ParameterNamesAreCamelCase); - } [Fact] - public async Task TestCamelCaseLocals_LocalDeclaration1() - { - await TestInRegularAndScriptAsync( + public Task TestCamelCaseLocals_LocalDeclaration1() + => TestInRegularAndScriptAsync( """ class C { @@ -418,12 +395,10 @@ void M() } """, options: s_options.LocalNamesAreCamelCase); - } [Fact] - public async Task TestCamelCaseLocals_LocalDeclaration2() - { - await TestInRegularAndScriptAsync( + public Task TestCamelCaseLocals_LocalDeclaration2() + => TestInRegularAndScriptAsync( """ class C { @@ -443,12 +418,10 @@ void M() } """, options: s_options.LocalNamesAreCamelCase); - } [Fact] - public async Task TestCamelCaseLocals_UsingVariable1() - { - await TestInRegularAndScriptAsync( + public Task TestCamelCaseLocals_UsingVariable1() + => TestInRegularAndScriptAsync( """ class C { @@ -472,12 +445,10 @@ void M() } """, options: s_options.LocalNamesAreCamelCase); - } [Fact] - public async Task TestCamelCaseLocals_UsingVariable2() - { - await TestInRegularAndScriptAsync( + public Task TestCamelCaseLocals_UsingVariable2() + => TestInRegularAndScriptAsync( """ class C { @@ -501,12 +472,10 @@ void M() } """, options: s_options.LocalNamesAreCamelCase); - } [Fact] - public async Task TestCamelCaseLocals_ForVariable1() - { - await TestInRegularAndScriptAsync( + public Task TestCamelCaseLocals_ForVariable1() + => TestInRegularAndScriptAsync( """ class C { @@ -530,12 +499,10 @@ void M() } """, options: s_options.LocalNamesAreCamelCase); - } [Fact] - public async Task TestCamelCaseLocals_ForVariable2() - { - await TestInRegularAndScriptAsync( + public Task TestCamelCaseLocals_ForVariable2() + => TestInRegularAndScriptAsync( """ class C { @@ -559,12 +526,10 @@ void M() } """, options: s_options.LocalNamesAreCamelCase); - } [Fact] - public async Task TestCamelCaseLocals_ForEachVariable() - { - await TestInRegularAndScriptAsync( + public Task TestCamelCaseLocals_ForEachVariable() + => TestInRegularAndScriptAsync( """ class C { @@ -588,12 +553,10 @@ void M() } """, options: s_options.LocalNamesAreCamelCase); - } [Fact] - public async Task TestCamelCaseLocals_CatchVariable() - { - await TestInRegularAndScriptAsync( + public Task TestCamelCaseLocals_CatchVariable() + => TestInRegularAndScriptAsync( """ using System; class C @@ -625,12 +588,10 @@ void M() } """, options: s_options.LocalNamesAreCamelCase); - } [Fact] - public async Task TestCamelCaseLocals_CatchWithoutVariableIgnored() - { - await TestMissingInRegularAndScriptAsync( + public Task TestCamelCaseLocals_CatchWithoutVariableIgnored() + => TestMissingInRegularAndScriptAsync( """ using System; class C @@ -646,12 +607,10 @@ void M() } } """, new TestParameters(options: s_options.LocalNamesAreCamelCase)); - } [Fact] - public async Task TestCamelCaseLocals_CatchWithoutDeclarationIgnored() - { - await TestMissingInRegularAndScriptAsync( + public Task TestCamelCaseLocals_CatchWithoutDeclarationIgnored() + => TestMissingInRegularAndScriptAsync( """ using System; class C @@ -667,12 +626,10 @@ void M() } } """, new TestParameters(options: s_options.LocalNamesAreCamelCase)); - } [Fact] - public async Task TestCamelCaseLocals_Deconstruction1() - { - await TestInRegularAndScriptAsync( + public Task TestCamelCaseLocals_Deconstruction1() + => TestInRegularAndScriptAsync( """ class C { @@ -694,12 +651,10 @@ void M() } """, options: s_options.LocalNamesAreCamelCase); - } [Fact] - public async Task TestCamelCaseLocals_Deconstruction2() - { - await TestInRegularAndScriptAsync( + public Task TestCamelCaseLocals_Deconstruction2() + => TestInRegularAndScriptAsync( """ class C { @@ -721,12 +676,10 @@ void M() } """, options: s_options.LocalNamesAreCamelCase); - } [Fact] - public async Task TestCamelCaseLocals_ForEachDeconstruction1() - { - await TestInRegularAndScriptAsync( + public Task TestCamelCaseLocals_ForEachDeconstruction1() + => TestInRegularAndScriptAsync( """ class C { @@ -748,12 +701,10 @@ void M() } """, options: s_options.LocalNamesAreCamelCase); - } [Fact] - public async Task TestCamelCaseLocals_ForEachDeconstruction2() - { - await TestInRegularAndScriptAsync( + public Task TestCamelCaseLocals_ForEachDeconstruction2() + => TestInRegularAndScriptAsync( """ class C { @@ -775,12 +726,10 @@ void M() } """, options: s_options.LocalNamesAreCamelCase); - } [Fact] - public async Task TestCamelCaseLocals_OutVariable() - { - await TestInRegularAndScriptAsync( + public Task TestCamelCaseLocals_OutVariable() + => TestInRegularAndScriptAsync( """ class C { @@ -802,12 +751,10 @@ void M() } """, options: s_options.LocalNamesAreCamelCase); - } [Fact] - public async Task TestCamelCaseLocals_PatternVariable() - { - await TestInRegularAndScriptAsync( + public Task TestCamelCaseLocals_PatternVariable() + => TestInRegularAndScriptAsync( """ class C { @@ -829,13 +776,10 @@ void M() } """, options: s_options.LocalNamesAreCamelCase); - } [Fact] - public async Task TestCamelCaseLocals_QueryFromClauseIgnored() - { - // This is an IRangeVariableSymbol, not ILocalSymbol - await TestMissingInRegularAndScriptAsync( + public Task TestCamelCaseLocals_QueryFromClauseIgnored() + => TestMissingInRegularAndScriptAsync( """ using System.Linq; @@ -850,13 +794,10 @@ void M() } } """, new TestParameters(options: s_options.LocalNamesAreCamelCase)); - } [Fact] - public async Task TestCamelCaseLocals_QueryLetClauseIgnored() - { - // This is an IRangeVariableSymbol, not ILocalSymbol - await TestMissingInRegularAndScriptAsync( + public Task TestCamelCaseLocals_QueryLetClauseIgnored() + => TestMissingInRegularAndScriptAsync( """ using System.Linq; @@ -871,12 +812,10 @@ void M() } } """, new TestParameters(options: s_options.LocalNamesAreCamelCase)); - } [Fact] - public async Task TestCamelCaseLocals_ParameterIgnored() - { - await TestMissingInRegularAndScriptAsync( + public Task TestCamelCaseLocals_ParameterIgnored() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -885,12 +824,10 @@ void M(int [|X|]) } } """, new TestParameters(options: s_options.LocalNamesAreCamelCase)); - } [Fact] - public async Task TestCamelCaseLocals_TupleTypeElementNameIgnored1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestCamelCaseLocals_TupleTypeElementNameIgnored1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -900,12 +837,10 @@ void M() } } """, new TestParameters(options: s_options.LocalNamesAreCamelCase)); - } [Fact] - public async Task TestCamelCaseLocals_TupleTypeElementNameIgnored2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestCamelCaseLocals_TupleTypeElementNameIgnored2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -915,12 +850,10 @@ void M() } } """, new TestParameters(options: s_options.LocalNamesAreCamelCase)); - } [Fact] - public async Task TestCamelCaseLocals_TupleExpressionElementNameIgnored() - { - await TestMissingInRegularAndScriptAsync( + public Task TestCamelCaseLocals_TupleExpressionElementNameIgnored() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -930,12 +863,10 @@ void M() } } """, new TestParameters(options: s_options.LocalNamesAreCamelCase)); - } [Fact] - public async Task TestUpperCaseConstants_ConstField() - { - await TestInRegularAndScriptAsync( + public Task TestUpperCaseConstants_ConstField() + => TestInRegularAndScriptAsync( """ class C { @@ -949,12 +880,10 @@ class C } """, options: s_options.ConstantsAreUpperCase); - } [Fact] - public async Task TestUpperCaseConstants_ConstLocal() - { - await TestInRegularAndScriptAsync( + public Task TestUpperCaseConstants_ConstLocal() + => TestInRegularAndScriptAsync( """ class C { @@ -974,24 +903,20 @@ void M() } """, options: s_options.ConstantsAreUpperCase); - } [Fact] - public async Task TestUpperCaseConstants_NonConstFieldIgnored() - { - await TestMissingInRegularAndScriptAsync( + public Task TestUpperCaseConstants_NonConstFieldIgnored() + => TestMissingInRegularAndScriptAsync( """ class C { readonly int [|field|] = 0; } """, new TestParameters(options: s_options.ConstantsAreUpperCase)); - } [Fact] - public async Task TestUpperCaseConstants_NonConstLocalIgnored() - { - await TestMissingInRegularAndScriptAsync( + public Task TestUpperCaseConstants_NonConstLocalIgnored() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1001,12 +926,10 @@ void M() } } """, new TestParameters(options: s_options.ConstantsAreUpperCase)); - } [Fact] - public async Task TestCamelCaseLocalsUpperCaseConstants_ConstLocal() - { - await TestInRegularAndScriptAsync( + public Task TestCamelCaseLocalsUpperCaseConstants_ConstLocal() + => TestInRegularAndScriptAsync( """ class C { @@ -1026,12 +949,10 @@ void M() } """, options: s_options.LocalsAreCamelCaseConstantsAreUpperCase); - } [Fact] - public async Task TestCamelCaseLocalsUpperCaseConstants_NonConstLocal() - { - await TestInRegularAndScriptAsync( + public Task TestCamelCaseLocalsUpperCaseConstants_NonConstLocal() + => TestInRegularAndScriptAsync( """ class C { @@ -1051,12 +972,10 @@ void M() } """, options: s_options.LocalsAreCamelCaseConstantsAreUpperCase); - } [Fact] - public async Task TestCamelCaseLocalFunctions() - { - await TestInRegularAndScriptAsync( + public Task TestCamelCaseLocalFunctions() + => TestInRegularAndScriptAsync( """ class C { @@ -1080,12 +999,10 @@ void f() } """, options: s_options.LocalFunctionNamesAreCamelCase); - } [Fact] - public async Task TestCamelCaseLocalFunctions_MethodIsIgnored() - { - await TestMissingInRegularAndScriptAsync( + public Task TestCamelCaseLocalFunctions_MethodIsIgnored() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1094,12 +1011,10 @@ class C } } """, new TestParameters(options: s_options.LocalFunctionNamesAreCamelCase)); - } [Fact] - public async Task TestAsyncFunctions_AsyncMethod() - { - await TestInRegularAndScriptAsync( + public Task TestAsyncFunctions_AsyncMethod() + => TestInRegularAndScriptAsync( """ class C { @@ -1117,12 +1032,10 @@ async void MAsync() } """, options: s_options.AsyncFunctionNamesEndWithAsync); - } [Fact] - public async Task TestAsyncFunctions_AsyncLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestAsyncFunctions_AsyncLocalFunction() + => TestInRegularAndScriptAsync( """ class C { @@ -1146,12 +1059,10 @@ async void FAsync() } """, options: s_options.AsyncFunctionNamesEndWithAsync); - } [Fact] - public async Task TestAsyncFunctions_NonAsyncMethodIgnored() - { - await TestMissingInRegularAndScriptAsync( + public Task TestAsyncFunctions_NonAsyncMethodIgnored() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1163,12 +1074,10 @@ async void F() } } """, new TestParameters(options: s_options.AsyncFunctionNamesEndWithAsync)); - } [Fact] - public async Task TestAsyncFunctions_NonAsyncLocalFunctionIgnored() - { - await TestMissingInRegularAndScriptAsync( + public Task TestAsyncFunctions_NonAsyncLocalFunctionIgnored() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1180,12 +1089,10 @@ async void M() } } """, new TestParameters(options: s_options.AsyncFunctionNamesEndWithAsync)); - } [Fact] - public async Task TestPascalCaseMethod_InInterfaceWithImplicitImplementation() - { - await TestInRegularAndScriptAsync( + public Task TestPascalCaseMethod_InInterfaceWithImplicitImplementation() + => TestInRegularAndScriptAsync( """ interface I { @@ -1209,12 +1116,10 @@ public void M() { } } """, options: s_options.MethodNamesArePascalCase); - } [Fact] - public async Task TestPascalCaseMethod_InInterfaceWithExplicitImplementation() - { - await TestInRegularAndScriptAsync( + public Task TestPascalCaseMethod_InInterfaceWithExplicitImplementation() + => TestInRegularAndScriptAsync( """ interface I { @@ -1238,12 +1143,10 @@ void I.M() { } } """, options: s_options.MethodNamesArePascalCase); - } [Fact] - public async Task TestPascalCaseMethod_NotInImplicitInterfaceImplementation() - { - await TestMissingInRegularAndScriptAsync( + public Task TestPascalCaseMethod_NotInImplicitInterfaceImplementation() + => TestMissingInRegularAndScriptAsync( """ interface I { @@ -1255,12 +1158,10 @@ class C : I public void [|m|]() { } } """, new TestParameters(options: s_options.MethodNamesArePascalCase)); - } [Fact] - public async Task TestPascalCaseMethod_NotInExplicitInterfaceImplementation() - { - await TestMissingInRegularAndScriptAsync( + public Task TestPascalCaseMethod_NotInExplicitInterfaceImplementation() + => TestMissingInRegularAndScriptAsync( """ interface I { @@ -1272,12 +1173,10 @@ class C : I void I.[|m|]() { } } """, new TestParameters(options: s_options.MethodNamesArePascalCase)); - } [Fact] - public async Task TestPascalCaseMethod_InAbstractType() - { - await TestInRegularAndScriptAsync( + public Task TestPascalCaseMethod_InAbstractType() + => TestInRegularAndScriptAsync( """ abstract class C { @@ -1301,12 +1200,10 @@ public override void M() { } } """, options: s_options.MethodNamesArePascalCase); - } [Fact] - public async Task TestPascalCaseMethod_NotInAbstractMethodImplementation() - { - await TestMissingInRegularAndScriptAsync( + public Task TestPascalCaseMethod_NotInAbstractMethodImplementation() + => TestMissingInRegularAndScriptAsync( """ abstract class C { @@ -1318,12 +1215,10 @@ class D : C public override void [|m|]() { } } """, new TestParameters(options: s_options.MethodNamesArePascalCase)); - } [Fact] - public async Task TestPascalCaseProperty_InInterface() - { - await TestInRegularAndScriptAsync( + public Task TestPascalCaseProperty_InInterface() + => TestInRegularAndScriptAsync( """ interface I { @@ -1347,12 +1242,10 @@ class C : I } """, options: s_options.PropertyNamesArePascalCase); - } [Fact] - public async Task TestPascalCaseProperty_NotInImplicitInterfaceImplementation() - { - await TestMissingInRegularAndScriptAsync( + public Task TestPascalCaseProperty_NotInImplicitInterfaceImplementation() + => TestMissingInRegularAndScriptAsync( """ interface I { @@ -1364,12 +1257,10 @@ class C : I public int [|p|] { get { return 1; } set { } } } """, new TestParameters(options: s_options.PropertyNamesArePascalCase)); - } [Fact] - public async Task TestPascalCaseMethod_OverrideInternalMethod() - { - await TestMissingInRegularAndScriptAsync( + public Task TestPascalCaseMethod_OverrideInternalMethod() + => TestMissingInRegularAndScriptAsync( """ abstract class C { @@ -1381,47 +1272,38 @@ class D : C internal override void [|m|]() { } } """, new TestParameters(options: s_options.MethodNamesArePascalCase)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19106")] - public async Task TestMissingOnSymbolsWithNoName() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnSymbolsWithNoName() + => TestMissingInRegularAndScriptAsync( """ namespace Microsoft.CodeAnalysis.Host { internal interface [|}|] """, new TestParameters(options: s_options.InterfaceNamesStartWithI)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17656")] - public async Task TestInterfacesStartWithIOnTypeThatAlreadyStartsWithI1() - { - await TestInRegularAndScript1Async(""" + public Task TestInterfacesStartWithIOnTypeThatAlreadyStartsWithI1() + => TestInRegularAndScript1Async(""" interface [|InputStream|] { } """, """ interface IInputStream { } """, new TestParameters(options: s_options.InterfaceNamesStartWithI)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17656")] - public async Task TestInterfacesStartWithIOnTypeThatAlreadyStartsWithI2() - { - await TestInRegularAndScript1Async(""" + public Task TestInterfacesStartWithIOnTypeThatAlreadyStartsWithI2() + => TestInRegularAndScript1Async(""" interface [|Stream|] { } """, """ interface IStream { } """, new TestParameters(options: s_options.InterfaceNamesStartWithI)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17656")] - public async Task TestInterfacesStartWithIOnTypeThatAlreadyStartsWithI3() - { - await TestMissingInRegularAndScriptAsync(""" + public Task TestInterfacesStartWithIOnTypeThatAlreadyStartsWithI3() + => TestMissingInRegularAndScriptAsync(""" interface [|IInputStream|] { } """, new TestParameters(options: s_options.InterfaceNamesStartWithI)); - } #if CODE_STYLE [Fact(Skip = "https://github.com/dotnet/roslyn/issues/42218")] @@ -1504,17 +1386,14 @@ public class A } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47508")] - public async Task TestRecordParameter_NoDiagnosticWhenCorrect() - { - await TestMissingInRegularAndScriptAsync( + public Task TestRecordParameter_NoDiagnosticWhenCorrect() + => TestMissingInRegularAndScriptAsync( @"record Foo(int [|MyInt|]);", new TestParameters(options: s_options.MergeStyles(s_options.PropertyNamesArePascalCase, s_options.ParameterNamesAreCamelCaseWithPUnderscorePrefix))); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47508")] - public async Task TestRecordConstructorParameter_NoDiagnosticWhenCorrect() - { - await TestMissingInRegularAndScriptAsync( + public Task TestRecordConstructorParameter_NoDiagnosticWhenCorrect() + => TestMissingInRegularAndScriptAsync( """ record Foo(int MyInt) { @@ -1524,16 +1403,13 @@ public Foo(string [|p_myString|]) : this(1) } """, new TestParameters(options: s_options.MergeStyles(s_options.PropertyNamesArePascalCase, s_options.ParameterNamesAreCamelCaseWithPUnderscorePrefix))); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47508")] - public async Task TestRecordParameter_ParameterFormattedAsProperties() - { - await TestInRegularAndScriptAsync( + public Task TestRecordParameter_ParameterFormattedAsProperties() + => TestInRegularAndScriptAsync( @"public record Foo(int [|myInt|]);", @"public record Foo(int [|MyInt|]);", options: s_options.MergeStyles(s_options.PropertyNamesArePascalCase, s_options.ParameterNamesAreCamelCaseWithPUnderscorePrefix)); - } [Theory] [InlineData("_")] @@ -1541,9 +1417,8 @@ await TestInRegularAndScriptAsync( [InlineData("_123")] [InlineData("__")] [InlineData("___")] - public async Task TestDiscardParameterAsync(string identifier) - { - await TestMissingInRegularAndScriptAsync( + public Task TestDiscardParameterAsync(string identifier) + => TestMissingInRegularAndScriptAsync( $$""" class C { @@ -1552,7 +1427,6 @@ void M(int [|{{identifier}}|]) } } """, new TestParameters(options: s_options.ParameterNamesAreCamelCase)); - } [Theory] [InlineData("_")] @@ -1560,9 +1434,8 @@ void M(int [|{{identifier}}|]) [InlineData("_123")] [InlineData("__")] [InlineData("___")] - public async Task TestDiscardLocalAsync(string identifier) - { - await TestMissingInRegularAndScriptAsync( + public Task TestDiscardLocalAsync(string identifier) + => TestMissingInRegularAndScriptAsync( $$""" class C { @@ -1572,12 +1445,10 @@ void M() } } """, new TestParameters(options: s_options.LocalNamesAreCamelCase)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49535")] - public async Task TestGlobalDirectiveAsync() - { - await TestMissingInRegularAndScriptAsync( + public Task TestGlobalDirectiveAsync() + => TestMissingInRegularAndScriptAsync( """ interface I { @@ -1589,12 +1460,10 @@ class C : I int [|global::I.X|] => 0; } """, new TestParameters(options: s_options.PropertyNamesArePascalCase)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50734")] - public async Task TestAsyncEntryPoint() - { - await TestMissingInRegularAndScriptAsync(""" + public Task TestAsyncEntryPoint() + => TestMissingInRegularAndScriptAsync(""" using System.Threading.Tasks; class C @@ -1605,27 +1474,22 @@ class C } } """, new TestParameters(options: s_options.AsyncFunctionNamesEndWithAsync)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49648")] - public async Task TestAsyncEntryPoint_TopLevel() - { - await TestMissingInRegularAndScriptAsync(""" + public Task TestAsyncEntryPoint_TopLevel() + => TestMissingInRegularAndScriptAsync(""" using System.Threading.Tasks; [|await Task.Delay(0);|] """, new TestParameters(options: s_options.AsyncFunctionNamesEndWithAsync)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51727")] - public async Task TestExternAsync() - { - await TestMissingInRegularAndScriptAsync( + public Task TestExternAsync() + => TestMissingInRegularAndScriptAsync( """ class C { static extern void [|some_p_invoke()|]; } """, new TestParameters(options: s_options.MethodNamesArePascalCase)); - } } diff --git a/src/Analyzers/CSharp/Tests/NewLines/ArrowExpressionClausePlacement/ArrowExpressionClausePlacementTests.cs b/src/Analyzers/CSharp/Tests/NewLines/ArrowExpressionClausePlacement/ArrowExpressionClausePlacementTests.cs index 0f6d30d1ed3cf..f13d5aee9b9b0 100644 --- a/src/Analyzers/CSharp/Tests/NewLines/ArrowExpressionClausePlacement/ArrowExpressionClausePlacementTests.cs +++ b/src/Analyzers/CSharp/Tests/NewLines/ArrowExpressionClausePlacement/ArrowExpressionClausePlacementTests.cs @@ -18,65 +18,50 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NewLines.ArrowExpressio public sealed class ArrowExpressionClausePlacementTests { [Fact] - public async Task TestNotWithOptionOff() - { - var code = - """ + public Task TestNotWithOptionOff() + => new Verify.Test + { + TestCode = """ class C { public int Add() => 1 + 2; } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInArrowExpressionClause, CodeStyleOption2.TrueWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotWithSingleLineMethod() - { - var code = - """ + public Task TestNotWithSingleLineMethod() + => new Verify.Test + { + TestCode = """ class C { public int Add() => 1 + 2; } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInArrowExpressionClause, CodeStyleOption2.TrueWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotWithSingleLineProperty() - { - var code = - """ + public Task TestNotWithSingleLineProperty() + => new Verify.Test + { + TestCode = """ class C { public int Add => 1 + 2; } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInArrowExpressionClause, CodeStyleOption2.TrueWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotWithSingleLineLocalFunction() - { - var code = - """ + public Task TestNotWithSingleLineLocalFunction() + => new Verify.Test + { + TestCode = """ class C { public void Main() @@ -84,20 +69,15 @@ public void Main() int Add() => 1 + 2; } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInArrowExpressionClause, CodeStyleOption2.TrueWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotWithLambda() - { - var code = - """ + public Task TestNotWithLambda() + => new Verify.Test + { + TestCode = """ class C { public void Main() @@ -108,49 +88,36 @@ public void Main() public void Goo(System.Func action) { } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInArrowExpressionClause, CodeStyleOption2.TrueWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestMethodCase() - { - var code = - """ + public Task TestMethodCase() + => new Verify.Test + { + TestCode = """ class C { public int Add() [|=>|] 1 + 2; } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public int Add() => 1 + 2; } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInArrowExpressionClause, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotPropertyAccessor1() - { - var code = - """ + public Task TestNotPropertyAccessor1() + => new Verify.Test + { + TestCode = """ class C { public int Add @@ -159,49 +126,36 @@ public int Add 1 + 2; } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInArrowExpressionClause, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestProperty() - { - var code = - """ + public Task TestProperty() + => new Verify.Test + { + TestCode = """ class C { public int Add [|=>|] 1 + 2; } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public int Add => 1 + 2; } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInArrowExpressionClause, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestLocalFunction() - { - var code = - """ + public Task TestLocalFunction() + => new Verify.Test + { + TestCode = """ class C { void Main() @@ -210,10 +164,8 @@ int Add() [|=>|] 1 + 2; } } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { void Main() @@ -222,78 +174,57 @@ int Add() => 1 + 2; } } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInArrowExpressionClause, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotWithDiagnosticsInDeclaration() - { - var code = - """ + public Task TestNotWithDiagnosticsInDeclaration() + => new Verify.Test + { + TestCode = """ class C { public int Add(int{|CS1001:)|} => 1 + 2; } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInArrowExpressionClause, CodeStyleOption2.TrueWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotWithDiagnosticsInExpression() - { - var code = - """ + public Task TestNotWithDiagnosticsInExpression() + => new Verify.Test + { + TestCode = """ class C { public int Add() => 1 + {|CS1525:;|} } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInArrowExpressionClause, CodeStyleOption2.TrueWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotWithDiagnosticsAtEnd() - { - var code = - """ + public Task TestNotWithDiagnosticsAtEnd() + => new Verify.Test + { + TestCode = """ class C { public int Add() => 1 + 2{|CS1002:|} } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInArrowExpressionClause, CodeStyleOption2.TrueWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotWithFirstExprWithPPTrivia1() - { - var code = - """ + public Task TestNotWithFirstExprWithPPTrivia1() + => new Verify.Test + { + TestCode = """ class C { public int Add() => @@ -301,20 +232,15 @@ public int Add() => 1 + 2; #endif } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInArrowExpressionClause, CodeStyleOption2.TrueWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotWithFirstExprWithPPTrivia2() - { - var code = - """ + public Task TestNotWithFirstExprWithPPTrivia2() + => new Verify.Test + { + TestCode = """ class C { #if true @@ -322,20 +248,15 @@ public int Add() => #endif 1 + 2; } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInArrowExpressionClause, CodeStyleOption2.TrueWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestWithRegion1() - { - var code = - """ + public Task TestWithRegion1() + => new Verify.Test + { + TestCode = """ class C { public int Add() [|=>|] @@ -343,10 +264,8 @@ public int Add() [|=>|] 1 + 2; #endregion } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public int Add() @@ -354,21 +273,15 @@ public int Add() => 1 + 2; #endregion } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInArrowExpressionClause, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestWithRegion2() - { - var code = - """ + public Task TestWithRegion2() + => new Verify.Test + { + TestCode = """ class C { #region section @@ -376,10 +289,8 @@ public int Add() [|=>|] #endregion 1 + 2; } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { #region section @@ -387,197 +298,143 @@ public int Add() #endregion => 1 + 2; } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInArrowExpressionClause, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestWithNullableDirective1() - { - var code = - """ + public Task TestWithNullableDirective1() + => new Verify.Test + { + TestCode = """ class C { public int Add() [|=>|] #nullable enable 1 + 2; } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public int Add() #nullable enable => 1 + 2; } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInArrowExpressionClause, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestTrivia1() - { - var code = - """ + public Task TestTrivia1() + => new Verify.Test + { + TestCode = """ class C { public int Add() [|=>|] 1 + 2; } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public int Add() => 1 + 2; } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInArrowExpressionClause, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestTrivia2() - { - var code = - """ + public Task TestTrivia2() + => new Verify.Test + { + TestCode = """ class C { public int Add() [|=>|] // comment 1 + 2; } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public int Add() // comment => 1 + 2; } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInArrowExpressionClause, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestTrivia3() - { - var code = - """ + public Task TestTrivia3() + => new Verify.Test + { + TestCode = """ class C { public int Add() /* comment */ [|=>|] 1 + 2; } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public int Add() /* comment */ => 1 + 2; } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInArrowExpressionClause, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestTrivia4() - { - var code = - """ + public Task TestTrivia4() + => new Verify.Test + { + TestCode = """ class C { public int Add() /* comment */ [|=>|] 1 + 2; } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public int Add() /* comment */ => 1 + 2; } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInArrowExpressionClause, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestTrivia5() - { - var code = - """ + public Task TestTrivia5() + => new Verify.Test + { + TestCode = """ class C { public int Add() /* comment1 */ [|=>|] /* comment2 */ 1 + 2; } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public int Add() /* comment1 */ /* comment2 */ => 1 + 2; } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInArrowExpressionClause, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestWithDiagnosticsElsewhere() - { - var code = - """ + public Task TestWithDiagnosticsElsewhere() + => new Verify.Test + { + TestCode = """ class C { public C(int{|CS1001:)|} @@ -587,10 +444,8 @@ public C(int{|CS1001:)|} public int Add() [|=>|] 1 + 2; } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public C(int{|CS1001:)|} @@ -600,13 +455,7 @@ public C(int{|CS1001:)|} public int Add() => 1 + 2; } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInArrowExpressionClause, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/NewLines/ConditionalExpressionPlacement/ConditionalExpressionPlacementTests.cs b/src/Analyzers/CSharp/Tests/NewLines/ConditionalExpressionPlacement/ConditionalExpressionPlacementTests.cs index d0ee970721be2..8540bdd0b9448 100644 --- a/src/Analyzers/CSharp/Tests/NewLines/ConditionalExpressionPlacement/ConditionalExpressionPlacementTests.cs +++ b/src/Analyzers/CSharp/Tests/NewLines/ConditionalExpressionPlacement/ConditionalExpressionPlacementTests.cs @@ -18,10 +18,10 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NewLines.ConditionalExp public sealed class ConditionalExpressionPlacementTests { [Fact] - public async Task TestNotWithOptionOff() - { - var code = - """ + public Task TestNotWithOptionOff() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -31,20 +31,15 @@ public C() 1; } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.TrueWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestBaseCase() - { - var code = - """ + public Task TestBaseCase() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -54,10 +49,8 @@ public C() 1; } } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public C() @@ -67,21 +60,15 @@ public C() : 1; } } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotWithDiagnosticsInCondition() - { - var code = - """ + public Task TestNotWithDiagnosticsInCondition() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -91,20 +78,15 @@ public C() 1; } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.TrueWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotWithDiagnosticsInTrue() - { - var code = - """ + public Task TestNotWithDiagnosticsInTrue() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -114,20 +96,15 @@ public C() 1; } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.TrueWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotWithDiagnosticsInFalse() - { - var code = - """ + public Task TestNotWithDiagnosticsInFalse() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -137,20 +114,15 @@ public C() 1 +{|CS1525:;|} } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.TrueWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotWithMissingColon() - { - var code = - """ + public Task TestNotWithMissingColon() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -159,20 +131,15 @@ public C() 0{|CS1003:{|CS1525:;|}|} } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.TrueWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotWithQuestionNotAtEndOfLine() - { - var code = - """ + public Task TestNotWithQuestionNotAtEndOfLine() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -181,20 +148,15 @@ public C() 1; } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.TrueWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotWithColonNotAtEndOfLine() - { - var code = - """ + public Task TestNotWithColonNotAtEndOfLine() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -203,20 +165,15 @@ public C() 1 : 1; } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.TrueWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotWithFirstExprWithPPTrivia1() - { - var code = - """ + public Task TestNotWithFirstExprWithPPTrivia1() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -228,20 +185,15 @@ public C() #endif } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.TrueWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotWithFirstExprWithPPTrivia2() - { - var code = - """ + public Task TestNotWithFirstExprWithPPTrivia2() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -253,20 +205,15 @@ public C() #endif } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.TrueWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotWithFirstExprWithPPTrivia3() - { - var code = - """ + public Task TestNotWithFirstExprWithPPTrivia3() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -278,20 +225,15 @@ public C() 1; } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.TrueWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotWithFirstExprWithPPTrivia4() - { - var code = - """ + public Task TestNotWithFirstExprWithPPTrivia4() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -303,20 +245,15 @@ public C() 1; } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.TrueWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotWithFirstExprWithPPTrivia5() - { - var code = - """ + public Task TestNotWithFirstExprWithPPTrivia5() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -328,20 +265,15 @@ public C() #endif } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.TrueWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestWithRegion1() - { - var code = - """ + public Task TestWithRegion1() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -353,10 +285,8 @@ public C() 1; } } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public C() @@ -368,21 +298,15 @@ public C() : 1; } } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestWithRegion2() - { - var code = - """ + public Task TestWithRegion2() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -394,10 +318,8 @@ public C() #endregion } } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public C() @@ -409,21 +331,15 @@ public C() #endregion } } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestWithNullableDirective1() - { - var code = - """ + public Task TestWithNullableDirective1() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -434,10 +350,8 @@ public C() 1; } } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public C() @@ -448,21 +362,15 @@ public C() : 1; } } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestWithNullableDirective2() - { - var code = - """ + public Task TestWithNullableDirective2() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -473,10 +381,8 @@ public C() 1; } } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public C() @@ -487,21 +393,15 @@ public C() : 1; } } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNested1() - { - var code = - """ + public Task TestNested1() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -513,10 +413,8 @@ true [|?|] 2; } } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public C() @@ -528,21 +426,15 @@ public C() : 2; } } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNested2() - { - var code = - """ + public Task TestNested2() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -553,10 +445,8 @@ public C() 2; } } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public C() @@ -567,21 +457,15 @@ public C() : 2; } } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNested3() - { - var code = - """ + public Task TestNested3() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -592,10 +476,8 @@ true [|?|] 1 : 2; } } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public C() @@ -606,21 +488,15 @@ public C() : 1 : 2; } } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestTrivia1() - { - var code = - """ + public Task TestTrivia1() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -630,10 +506,8 @@ public C() 1; } } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public C() @@ -643,21 +517,15 @@ public C() : 1; } } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestTrivia2() - { - var code = - """ + public Task TestTrivia2() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -667,10 +535,8 @@ public C() 1; } } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public C() @@ -680,21 +546,15 @@ public C() : 1; } } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestTrivia3() - { - var code = - """ + public Task TestTrivia3() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -704,10 +564,8 @@ public C() 1; } } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public C() @@ -717,21 +575,15 @@ public C() : 1; } } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestTrivia4() - { - var code = - """ + public Task TestTrivia4() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -741,10 +593,8 @@ public C() 1; } } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public C() @@ -754,21 +604,15 @@ public C() : 1; } } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestTrivia5() - { - var code = - """ + public Task TestTrivia5() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -778,10 +622,8 @@ public C() 1; } } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public C() @@ -791,21 +633,15 @@ public C() : 1; } } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestWithDiagnosticsElsewhere() - { - var code = - """ + public Task TestWithDiagnosticsElsewhere() + => new Verify.Test + { + TestCode = """ class C { public C(int{|CS1001:)|} @@ -815,10 +651,8 @@ public C(int{|CS1001:)|} 1; } } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public C(int{|CS1001:)|} @@ -828,13 +662,7 @@ public C(int{|CS1001:)|} : 1; } } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterTokenInConditionalExpression, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/NewLines/ConsecutiveBracePlacement/ConsecutiveBracePlacementTests.cs b/src/Analyzers/CSharp/Tests/NewLines/ConsecutiveBracePlacement/ConsecutiveBracePlacementTests.cs index fe339a05909d3..7212e8ab3baea 100644 --- a/src/Analyzers/CSharp/Tests/NewLines/ConsecutiveBracePlacement/ConsecutiveBracePlacementTests.cs +++ b/src/Analyzers/CSharp/Tests/NewLines/ConsecutiveBracePlacement/ConsecutiveBracePlacementTests.cs @@ -18,122 +18,87 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NewLines.ConsecutiveBra public sealed class ConsecutiveBracePlacementTests { [Fact] - public async Task NotForBracesOnSameLineDirectlyTouching() - { - var code = -@"class C { void M() { }}"; - - await new VerifyCS.Test + public Task NotForBracesOnSameLineDirectlyTouching() + => new VerifyCS.Test { - TestCode = code, + TestCode = @"class C { void M() { }}", Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task NotForBracesOnSameLineWithSpace() - { - var code = -@"class C { void M() { } }"; - - await new VerifyCS.Test + public Task NotForBracesOnSameLineWithSpace() + => new VerifyCS.Test { - TestCode = code, + TestCode = @"class C { void M() { } }", Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task NotForBracesOnSameLineWithComment() - { - var code = -@"class C { void M() { }/*goo*/}"; - - await new VerifyCS.Test + public Task NotForBracesOnSameLineWithComment() + => new VerifyCS.Test { - TestCode = code, + TestCode = @"class C { void M() { }/*goo*/}", Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task NotForBracesOnSameLineWithCommentAndSpaces() - { - var code = -@"class C { void M() { } /*goo*/ }"; - - await new VerifyCS.Test + public Task NotForBracesOnSameLineWithCommentAndSpaces() + => new VerifyCS.Test { - TestCode = code, + TestCode = @"class C { void M() { } /*goo*/ }", Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task NotForBracesOnSubsequentLines_TopLevel() - { - var code = - """ + public Task NotForBracesOnSubsequentLines_TopLevel() + => new VerifyCS.Test + { + TestCode = """ class C { void M() { } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task NotForBracesOnSubsequentLinesWithComment1_TopLevel() - { - var code = - """ + public Task NotForBracesOnSubsequentLinesWithComment1_TopLevel() + => new VerifyCS.Test + { + TestCode = """ class C { void M() { } // comment } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task NotForBracesOnSubsequentLinesWithComment2_TopLevel() - { - var code = - """ + public Task NotForBracesOnSubsequentLinesWithComment2_TopLevel() + => new VerifyCS.Test + { + TestCode = """ class C { void M() { } /* comment */ } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task NotForBracesOnSubsequentLinesIndented() - { - var code = - """ + public Task NotForBracesOnSubsequentLinesIndented() + => new VerifyCS.Test + { + TestCode = """ namespace N { class C @@ -143,20 +108,15 @@ void M() } } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task NotForBracesOnSubsequentLinesIndentedWithComment1() - { - var code = - """ + public Task NotForBracesOnSubsequentLinesIndentedWithComment1() + => new VerifyCS.Test + { + TestCode = """ namespace N { class C @@ -166,20 +126,15 @@ void M() } // comment } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task NotForBracesOnSubsequentLinesIndentedWithComment2() - { - var code = - """ + public Task NotForBracesOnSubsequentLinesIndentedWithComment2() + => new VerifyCS.Test + { + TestCode = """ namespace N { class C @@ -189,20 +144,15 @@ void M() } /* comment */ } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task NotForBracesWithBlankLinesIfCommentBetween1_TopLevel() - { - var code = - """ + public Task NotForBracesWithBlankLinesIfCommentBetween1_TopLevel() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -212,20 +162,15 @@ void M() // comment } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task NotForBracesWithBlankLinesIfCommentBetween2_TopLevel() - { - var code = - """ + public Task NotForBracesWithBlankLinesIfCommentBetween2_TopLevel() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -235,20 +180,15 @@ void M() /* comment */ } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task NotForBracesWithBlankLinesIfDirectiveBetween1_TopLeve() - { - var code = - """ + public Task NotForBracesWithBlankLinesIfDirectiveBetween1_TopLeve() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -258,21 +198,16 @@ void M() #nullable enable } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task NotForBracesWithBlankLinesIfCommentBetween1_Nested() - { - var code = - """ + public Task NotForBracesWithBlankLinesIfCommentBetween1_Nested() + => new VerifyCS.Test + { + TestCode = """ namespace N { class C @@ -285,20 +220,15 @@ void M() } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task NotForBracesWithBlankLinesIfCommentBetween2_Nested() - { - var code = - """ + public Task NotForBracesWithBlankLinesIfCommentBetween2_Nested() + => new VerifyCS.Test + { + TestCode = """ namespace N { class C @@ -311,20 +241,15 @@ void M() } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task NotForBracesWithBlankLinesIfDirectiveBetween_Nested() - { - var code = - """ + public Task NotForBracesWithBlankLinesIfDirectiveBetween_Nested() + => new VerifyCS.Test + { + TestCode = """ namespace N { class C @@ -337,21 +262,16 @@ void M() } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task OneBlankLineBetweenBraces_TopLevel() - { - var code = - """ + public Task OneBlankLineBetweenBraces_TopLevel() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -359,30 +279,23 @@ void M() } [|}|] - """; - var fixedCode = - """ + """, + FixedCode = """ class C { void M() { } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task OneBlankLineBetweenBraces_TopLevel_OptionDisabled() - { - var code = - """ + public Task OneBlankLineBetweenBraces_TopLevel_OptionDisabled() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -390,20 +303,15 @@ void M() } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.TrueWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TwoBlankLinesBetweenBraces_TopLevel() - { - var code = - """ + public Task TwoBlankLinesBetweenBraces_TopLevel() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -412,30 +320,23 @@ void M() [|}|] - """; - var fixedCode = - """ + """, + FixedCode = """ class C { void M() { } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task ThreeBlankLinesBetweenBraces_TopLevel() - { - var code = - """ + public Task ThreeBlankLinesBetweenBraces_TopLevel() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -445,30 +346,23 @@ void M() [|}|] - """; - var fixedCode = - """ + """, + FixedCode = """ class C { void M() { } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task BlankLinesBetweenBraces_LeadingComment_TopLevel() - { - var code = - """ + public Task BlankLinesBetweenBraces_LeadingComment_TopLevel() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -478,30 +372,23 @@ void M() /*comment*/[|}|] - """; - var fixedCode = - """ + """, + FixedCode = """ class C { void M() { } /*comment*/} - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task BlankLinesBetweenBraces_TrailingComment_TopLevel() - { - var code = - """ + public Task BlankLinesBetweenBraces_TrailingComment_TopLevel() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -511,30 +398,23 @@ void M() [|}|] - """; - var fixedCode = - """ + """, + FixedCode = """ class C { void M() { } /*comment*/ } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task OneBlankLineBetweenBraces_Nested() - { - var code = - """ + public Task OneBlankLineBetweenBraces_Nested() + => new VerifyCS.Test + { + TestCode = """ namespace N { class C @@ -545,9 +425,8 @@ void M() [|}|] } - """; - var fixedCode = - """ + """, + FixedCode = """ namespace N { class C @@ -557,21 +436,15 @@ void M() } } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TwoBlankLinesBetweenBraces_Nested() - { - var code = - """ + public Task TwoBlankLinesBetweenBraces_Nested() + => new VerifyCS.Test + { + TestCode = """ namespace N { class C @@ -583,9 +456,8 @@ void M() [|}|] } - """; - var fixedCode = - """ + """, + FixedCode = """ namespace N { class C @@ -595,21 +467,15 @@ void M() } } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task ThreeBlankLinesBetweenBraces_Nested() - { - var code = - """ + public Task ThreeBlankLinesBetweenBraces_Nested() + => new VerifyCS.Test + { + TestCode = """ namespace N { class C @@ -622,9 +488,8 @@ void M() [|}|] } - """; - var fixedCode = - """ + """, + FixedCode = """ namespace N { class C @@ -634,21 +499,15 @@ void M() } } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task BlankLinesBetweenBraces_LeadingComment_Nested() - { - var code = - """ + public Task BlankLinesBetweenBraces_LeadingComment_Nested() + => new VerifyCS.Test + { + TestCode = """ namespace N { class C @@ -661,9 +520,8 @@ void M() /*comment*/[|}|] } - """; - var fixedCode = - """ + """, + FixedCode = """ namespace N { class C @@ -673,21 +531,15 @@ void M() } /*comment*/} } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task BlankLinesBetweenBraces_TrailingComment_Nested() - { - var code = - """ + public Task BlankLinesBetweenBraces_TrailingComment_Nested() + => new VerifyCS.Test + { + TestCode = """ namespace N { class C @@ -700,9 +552,8 @@ void M() [|}|] } - """; - var fixedCode = - """ + """, + FixedCode = """ namespace N { class C @@ -712,21 +563,15 @@ void M() } /*comment*/ } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task FixAll1() - { - var code = - """ + public Task FixAll1() + => new VerifyCS.Test + { + TestCode = """ namespace N { class C @@ -738,9 +583,8 @@ void M() [|}|] [|}|] - """; - var fixedCode = - """ + """, + FixedCode = """ namespace N { class C @@ -750,21 +594,15 @@ void M() } } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task RealCode1() - { - var code = - """ + public Task RealCode1() + => new VerifyCS.Test + { + TestCode = """ #nullable enable using System; @@ -795,21 +633,16 @@ internal interface IOption2 #endif } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task RealCode2() - { - var code = - """ + public Task RealCode2() + => new VerifyCS.Test + { + TestCode = """ #define CODE_STYLE #nullable enable @@ -841,13 +674,8 @@ internal interface IOption2 #endif } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/NewLines/ConsecutiveStatementPlacement/ConsecutiveStatementPlacementTests.cs b/src/Analyzers/CSharp/Tests/NewLines/ConsecutiveStatementPlacement/ConsecutiveStatementPlacementTests.cs index 34ef128da0c98..6b14081728774 100644 --- a/src/Analyzers/CSharp/Tests/NewLines/ConsecutiveStatementPlacement/ConsecutiveStatementPlacementTests.cs +++ b/src/Analyzers/CSharp/Tests/NewLines/ConsecutiveStatementPlacement/ConsecutiveStatementPlacementTests.cs @@ -18,48 +18,38 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NewLines.ConsecutiveSta public sealed class ConsecutiveStatementPlacementTests { [Fact] - public async Task TestNotAfterPropertyBlock() - { - var code = - """ + public Task TestNotAfterPropertyBlock() + => new Verify.Test + { + TestCode = """ class C { int X { get; } int Y { get; } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotAfterMethodBlock() - { - var code = - """ + public Task TestNotAfterMethodBlock() + => new Verify.Test + { + TestCode = """ class C { void X() { } void Y() { } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotAfterStatementsOnSingleLine() - { - var code = - """ + public Task TestNotAfterStatementsOnSingleLine() + => new Verify.Test + { + TestCode = """ class C { void M() @@ -67,20 +57,15 @@ void M() if (true) { } return; } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotAfterStatementsOnSingleLineWithComment() - { - var code = - """ + public Task TestNotAfterStatementsOnSingleLineWithComment() + => new Verify.Test + { + TestCode = """ class C { void M() @@ -88,20 +73,15 @@ void M() if (true) { }/*x*/return; } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotAfterStatementsOnMultipleLinesWithCommentBetween1() - { - var code = - """ + public Task TestNotAfterStatementsOnMultipleLinesWithCommentBetween1() + => new Verify.Test + { + TestCode = """ class C { void M() @@ -112,20 +92,15 @@ void M() /*x*/ return; } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotAfterStatementsOnMultipleLinesWithCommentBetween2() - { - var code = - """ + public Task TestNotAfterStatementsOnMultipleLinesWithCommentBetween2() + => new Verify.Test + { + TestCode = """ class C { void M() @@ -136,20 +111,15 @@ void M() /*x*/ return; } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotAfterStatementsWithSingleBlankLines() - { - var code = - """ + public Task TestNotAfterStatementsWithSingleBlankLines() + => new Verify.Test + { + TestCode = """ class C { void M() @@ -161,20 +131,15 @@ void M() return; } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotAfterStatementsWithSingleBlankLinesWithSpaces() - { - var code = - """ + public Task TestNotAfterStatementsWithSingleBlankLinesWithSpaces() + => new Verify.Test + { + TestCode = """ class C { void M() @@ -186,20 +151,15 @@ void M() return; } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotAfterStatementsWithMultipleBlankLines() - { - var code = - """ + public Task TestNotAfterStatementsWithMultipleBlankLines() + => new Verify.Test + { + TestCode = """ class C { void M() @@ -211,20 +171,15 @@ void M() return; } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotAfterStatementsOnMultipleLinesWithPPDirectiveBetween1() - { - var code = - """ + public Task TestNotAfterStatementsOnMultipleLinesWithPPDirectiveBetween1() + => new Verify.Test + { + TestCode = """ class C { void M() @@ -236,20 +191,15 @@ void M() return; } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotBetweenBlockAndElseClause() - { - var code = - """ + public Task TestNotBetweenBlockAndElseClause() + => new Verify.Test + { + TestCode = """ class C { void M() @@ -262,20 +212,15 @@ void M() } } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotBetweenBlockAndOuterBlocker() - { - var code = - """ + public Task TestNotBetweenBlockAndOuterBlocker() + => new Verify.Test + { + TestCode = """ class C { void M() @@ -287,20 +232,15 @@ void M() } } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotBetweenBlockAndCase() - { - var code = - """ + public Task TestNotBetweenBlockAndCase() + => new Verify.Test + { + TestCode = """ class C { void M() @@ -316,19 +256,13 @@ void M() } } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestBetweenBlockAndStatement1() - { - await new Verify.Test + public Task TestBetweenBlockAndStatement1() + => new Verify.Test { TestCode = """ class C @@ -357,12 +291,12 @@ void M() """, Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotBetweenBlockAndStatement1_WhenOptionOff() - { - var code = """ + public Task TestNotBetweenBlockAndStatement1_WhenOptionOff() + => new Verify.Test + { + TestCode = """ class C { void M() @@ -373,19 +307,13 @@ void M() return; } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOption2.TrueWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestBetweenSwitchAndStatement1() - { - await new Verify.Test + public Task TestBetweenSwitchAndStatement1() + => new Verify.Test { TestCode = """ class C @@ -414,12 +342,10 @@ void M() """, Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestBetweenBlockAndStatement2() - { - await new Verify.Test + public Task TestBetweenBlockAndStatement2() + => new Verify.Test { TestCode = """ class C @@ -448,12 +374,10 @@ void M() """, Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestBetweenBlockAndStatement3() - { - await new Verify.Test + public Task TestBetweenBlockAndStatement3() + => new Verify.Test { TestCode = """ class C @@ -478,12 +402,10 @@ void M() """, Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestBetweenBlockAndStatement4() - { - await new Verify.Test + public Task TestBetweenBlockAndStatement4() + => new Verify.Test { TestCode = """ class C @@ -516,12 +438,10 @@ void M() """, Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestFixAll1() - { - await new Verify.Test + public Task TestFixAll1() + => new Verify.Test { TestCode = """ class C @@ -559,12 +479,12 @@ void M() """, Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestSA1513NegativeCases() - { - var code = """ + public Task TestSA1513NegativeCases() + => new Verify.Test + { + TestCode = """ using System; using System.Linq; using System.Collections.Generic; @@ -922,19 +842,13 @@ public void TestTernaryConstruction() : new Dictionary(); } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestSA1513PositiveCases() - { - await new Verify.Test + public Task TestSA1513PositiveCases() + => new Verify.Test { TestCode = """ using System; @@ -1118,5 +1032,4 @@ public void Example() """, Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/NewLines/ConstructorInitializerPlacement/ConstructorInitializerPlacementTests.cs b/src/Analyzers/CSharp/Tests/NewLines/ConstructorInitializerPlacement/ConstructorInitializerPlacementTests.cs index 208d19e8b0a1c..d0301ea1a6766 100644 --- a/src/Analyzers/CSharp/Tests/NewLines/ConstructorInitializerPlacement/ConstructorInitializerPlacementTests.cs +++ b/src/Analyzers/CSharp/Tests/NewLines/ConstructorInitializerPlacement/ConstructorInitializerPlacementTests.cs @@ -18,10 +18,10 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NewLines.ConstructorIni public sealed class ConstructorInitializerPlacementTests { [Fact] - public async Task TestNotWithOptionOff() - { - var code = - """ + public Task TestNotWithOptionOff() + => new Verify.Test + { + TestCode = """ class C { public C() : @@ -29,20 +29,15 @@ public C() : { } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOption2.TrueWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestSimpleCase() - { - var code = - """ + public Task TestSimpleCase() + => new Verify.Test + { + TestCode = """ class C { public C() [|:|] @@ -50,10 +45,8 @@ public C() [|:|] { } } - """; - - var fixedCode = - """ + """, + FixedCode = """ class C { public C() @@ -61,41 +54,30 @@ public C() { } } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotOnSameLine1() - { - var code = - """ + public Task TestNotOnSameLine1() + => new Verify.Test + { + TestCode = """ class C { public C() : base() { } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotOnSameLine2() - { - var code = - """ + public Task TestNotOnSameLine2() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -103,20 +85,15 @@ public C() { } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNotWithColonTrailingComment() - { - var code = - """ + public Task TestNotWithColonTrailingComment() + => new Verify.Test + { + TestCode = """ class C { public C() : //comment @@ -124,20 +101,15 @@ public C() : //comment { } } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestWithCloseParenTrailingComment1() - { - var code = - """ + public Task TestWithCloseParenTrailingComment1() + => new Verify.Test + { + TestCode = """ class C { public C() /*comment*/ [|:|] @@ -145,9 +117,8 @@ public C() /*comment*/ [|:|] { } } - """; - var fixedCode = - """ + """, + FixedCode = """ class C { public C() /*comment*/ @@ -155,21 +126,15 @@ public C() /*comment*/ { } } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestWithColonLeadingComment1() - { - var code = - """ + public Task TestWithColonLeadingComment1() + => new Verify.Test + { + TestCode = """ class C { public C() @@ -179,9 +144,8 @@ public C() { } } - """; - var fixedCode = - """ + """, + FixedCode = """ class C { public C() @@ -191,21 +155,15 @@ public C() { } } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestWithLeadingComment() - { - var code = - """ + public Task TestWithLeadingComment() + => new Verify.Test + { + TestCode = """ class C { public C() [|:|] @@ -214,9 +172,8 @@ public C() [|:|] { } } - """; - var fixedCode = - """ + """, + FixedCode = """ class C { public C() @@ -225,21 +182,15 @@ public C() { } } - """; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestWithLeadingDirective() - { - var code = - """ + public Task TestWithLeadingDirective() + => new Verify.Test + { + TestCode = """ class C { public C() : @@ -249,12 +200,7 @@ public C() : } #endif } - """; - - await new Verify.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementTests.cs b/src/Analyzers/CSharp/Tests/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementTests.cs index 0a19b2c2524dd..d644452258b14 100644 --- a/src/Analyzers/CSharp/Tests/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementTests.cs +++ b/src/Analyzers/CSharp/Tests/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementTests.cs @@ -19,9 +19,10 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NewLines.EmbeddedStatem public sealed class EmbeddedStatementPlacementTests { [Fact] - public async Task NoErrorOnWrappedStatement() - { - var source = """ + public Task NoErrorOnWrappedStatement() + => new VerifyCS.Test + { + TestCode = """ class TestClass { void M() @@ -30,18 +31,15 @@ void M() return; } } - """; - await new VerifyCS.Test - { - TestCode = source, + """, Options = { { CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task ErrorOnNonWrappedIfStatement() - { - var source = """ + public Task ErrorOnNonWrappedIfStatement() + => new VerifyCS.Test + { + TestCode = """ class TestClass { void M() @@ -49,8 +47,8 @@ void M() if (true) [|return|]; } } - """; - var fixedCode = """ + """, + FixedCode = """ class TestClass { void M() @@ -59,19 +57,15 @@ void M() return; } } - """; - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task NoErrorOnNonWrappedIfStatement_WhenOptionDisabled() - { - var source = """ + public Task NoErrorOnNonWrappedIfStatement_WhenOptionDisabled() + => new VerifyCS.Test + { + TestCode = """ class TestClass { void M() @@ -79,18 +73,15 @@ void M() if (true) return; } } - """; - await new VerifyCS.Test - { - TestCode = source, + """, Options = { { CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine, true, NotificationOption2.Suggestion } } }.RunAsync(); - } [Fact] - public async Task NotOnElseIf() - { - var source = """ + public Task NotOnElseIf() + => new VerifyCS.Test + { + TestCode = """ class TestClass { void M() @@ -101,19 +92,15 @@ void M() return; } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, Options = { { CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task ErrorOnElseWithNonIfStatementOnSameLine() - { - var source = """ + public Task ErrorOnElseWithNonIfStatementOnSameLine() + => new VerifyCS.Test + { + TestCode = """ class TestClass { void M() @@ -123,8 +110,8 @@ void M() else [|return|]; } } - """; - var fixedCode = """ + """, + FixedCode = """ class TestClass { void M() @@ -135,19 +122,15 @@ void M() return; } } - """; - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task ErrorOnIfWithSingleLineBlock() - { - var source = """ + public Task ErrorOnIfWithSingleLineBlock() + => new VerifyCS.Test + { + TestCode = """ class TestClass { void M() @@ -155,8 +138,8 @@ void M() if (true) [|{|] return; } } } - """; - var fixedCode = """ + """, + FixedCode = """ class TestClass { void M() @@ -167,19 +150,15 @@ void M() } } } - """; - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task NoWrappingForMemberOrLambdaBlock() - { - var source = """ + public Task NoWrappingForMemberOrLambdaBlock() + => new VerifyCS.Test + { + TestCode = """ using System; class TestClass @@ -197,18 +176,15 @@ int Prop2 get { return 1; } } } - """; - await new VerifyCS.Test - { - TestCode = source, + """, Options = { { CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task WrappingForLocalFunction() - { - var source = """ + public Task WrappingForLocalFunction() + => new VerifyCS.Test + { + TestCode = """ class TestClass { void N() @@ -216,8 +192,8 @@ void N() void Local() [|{|] return; } } } - """; - var fixedCode = """ + """, + FixedCode = """ class TestClass { void N() @@ -228,19 +204,15 @@ void Local() } } } - """; - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task ErrorOnNonWrappedIfStatementWithEmptyBlock() - { - var source = """ + public Task ErrorOnNonWrappedIfStatementWithEmptyBlock() + => new VerifyCS.Test + { + TestCode = """ class TestClass { void M() @@ -248,8 +220,8 @@ void M() if (true) [|{|] } } } - """; - var fixedCode = """ + """, + FixedCode = """ class TestClass { void M() @@ -259,19 +231,15 @@ void M() } } } - """; - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task WrapLambdaWithNestedStatement() - { - var source = """ + public Task WrapLambdaWithNestedStatement() + => new VerifyCS.Test + { + TestCode = """ using System; class TestClass @@ -281,8 +249,8 @@ void N() Action a1 = () => { [|if|] (true) return; }; } } - """; - var fixedCode = """ + """, + FixedCode = """ using System; class TestClass @@ -296,19 +264,15 @@ void N() }; } } - """; - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task FixAll1() - { - var source = """ + public Task FixAll1() + => new VerifyCS.Test + { + TestCode = """ class TestClass { void M() @@ -317,8 +281,8 @@ void M() if (true) [|return|]; } } - """; - var fixedCode = """ + """, + FixedCode = """ class TestClass { void M() @@ -329,19 +293,15 @@ void M() return; } } - """; - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66017")] - public async Task SwitchFollowedByEmptyStatement() - { - var source = """ + public Task SwitchFollowedByEmptyStatement() + => new VerifyCS.Test + { + TestCode = """ class TestClass { void M() @@ -351,8 +311,8 @@ void M() }[|;|] } } - """; - var fixedCode = """ + """, + FixedCode = """ class TestClass { void M() @@ -364,12 +324,7 @@ void M() ; } } - """; - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/NewLines/MultipleBlankLines/MultipleBlankLinesTests.cs b/src/Analyzers/CSharp/Tests/NewLines/MultipleBlankLines/MultipleBlankLinesTests.cs index 2215eb738703c..6fb12af653a1c 100644 --- a/src/Analyzers/CSharp/Tests/NewLines/MultipleBlankLines/MultipleBlankLinesTests.cs +++ b/src/Analyzers/CSharp/Tests/NewLines/MultipleBlankLines/MultipleBlankLinesTests.cs @@ -18,909 +18,789 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NewLines.MultipleBlankL public sealed class MultipleBlankLinesTests { [Fact] - public async Task TestOneBlankLineAtTopOfFile() - { - var code = -@" -// comment"; - - await new Verify.Test + public Task TestOneBlankLineAtTopOfFile() + => new Verify.Test { - TestCode = code, + TestCode = """ + + // comment + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestTwoBlankLineAtTopOfFile() - { - var code = -@"[||] + public Task TestTwoBlankLineAtTopOfFile() + => new Verify.Test + { + TestCode = """ + [||] -// comment"; - var fixedCode = -@" -// comment"; + // comment + """, + FixedCode = """ - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + // comment + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestTwoBlankLineAtTopOfFile_NotWithOptionOff() - { - var code = -@" + public Task TestTwoBlankLineAtTopOfFile_NotWithOptionOff() + => new Verify.Test + { + TestCode = """ -// comment"; - await new Verify.Test - { - TestCode = code, + // comment + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.TrueWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestThreeBlankLineAtTopOfFile() - { - var code = -@"[||] + public Task TestThreeBlankLineAtTopOfFile() + => new Verify.Test + { + TestCode = """ + [||] -// comment"; - var fixedCode = -@" -// comment"; + // comment + """, + FixedCode = """ - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + // comment + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestFourBlankLineAtTopOfFile() - { - var code = -@"[||] + public Task TestFourBlankLineAtTopOfFile() + => new Verify.Test + { + TestCode = """ + [||] -// comment"; - var fixedCode = -@" -// comment"; + // comment + """, + FixedCode = """ - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + // comment + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestOneBlankLineAtTopOfEmptyFile() - { - var code = -@" -"; - - await new Verify.Test + public Task TestOneBlankLineAtTopOfEmptyFile() + => new Verify.Test { - TestCode = code, + TestCode = """ + + + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestTwoBlankLinesAtTopOfEmptyFile() - { - var code = -@"[||] + public Task TestTwoBlankLinesAtTopOfEmptyFile() + => new Verify.Test + { + TestCode = """ + [||] -"; - var fixedCode = -@" -"; - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, + FixedCode = """ + + + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestThreeBlankLinesAtTopOfEmptyFile() - { - var code = -@"[||] + public Task TestThreeBlankLinesAtTopOfEmptyFile() + => new Verify.Test + { + TestCode = """ + [||] -"; - var fixedCode = -@" -"; - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, + FixedCode = """ + + + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestFourBlankLinesAtTopOfEmptyFile() - { - var code = -@"[||] + public Task TestFourBlankLinesAtTopOfEmptyFile() + => new Verify.Test + { + TestCode = """ + [||] -"; - var fixedCode = -@" -"; - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + """, + FixedCode = """ + + + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNoBlankLineAtEndOfFile_1() - { - var code = -@"class C -{ -}"; - - await new Verify.Test + public Task TestNoBlankLineAtEndOfFile_1() + => new Verify.Test { - TestCode = code, + TestCode = """ + class C + { + } + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNoBlankLineAtEndOfFile_2() - { - var code = -@"class C -{ -} -"; - - await new Verify.Test + public Task TestNoBlankLineAtEndOfFile_2() + => new Verify.Test { - TestCode = code, + TestCode = """ + class C + { + } + + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestOneBlankLineAtEndOfFile() - { - var code = -@"class C -{ -} + public Task TestOneBlankLineAtEndOfFile() + => new Verify.Test + { + TestCode = """ + class C + { + } -"; - await new Verify.Test - { - TestCode = code, + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestTwoBlankLineAtEndOfFile() - { - var code = -@"class C -{ -} -[||] + public Task TestTwoBlankLineAtEndOfFile() + => new Verify.Test + { + TestCode = """ + class C + { + } + [||] -"; - var fixedCode = -@"class C -{ -} -"; + """, + FixedCode = """ + class C + { + } - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestThreeBlankLineAtEndOfFile() - { - var code = -@"class C -{ -} -[||] + public Task TestThreeBlankLineAtEndOfFile() + => new Verify.Test + { + TestCode = """ + class C + { + } + [||] -"; - var fixedCode = -@"class C -{ -} -"; + """, + FixedCode = """ + class C + { + } - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestFourBlankLineAtEndOfFile() - { - var code = -@"class C -{ -} -[||] + public Task TestFourBlankLineAtEndOfFile() + => new Verify.Test + { + TestCode = """ + class C + { + } + [||] -"; - var fixedCode = -@"class C -{ -} -"; + """, + FixedCode = """ + class C + { + } - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNoBlankLineBetweenTokens() - { - var code = -@"class C -{ -}"; - - await new Verify.Test + public Task TestNoBlankLineBetweenTokens() + => new Verify.Test { - TestCode = code, + TestCode = """ + class C + { + } + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestOneBlankLineBetweenTokens() - { - var code = -@"class C -{ - -}"; - - await new Verify.Test + public Task TestOneBlankLineBetweenTokens() + => new Verify.Test { - TestCode = code, + TestCode = """ + class C + { + + } + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestTwoBlankLineBetweenTokens() - { - var code = -@"class C -{ -[||] - -}"; - var fixedCode = -@"class C -{ + public Task TestTwoBlankLineBetweenTokens() + => new Verify.Test + { + TestCode = """ + class C + { + [||] -}"; + } + """, + FixedCode = """ + class C + { - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + } + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestThreeBlankLineBetweenTokens() - { - var code = -@"class C -{ -[||] + public Task TestThreeBlankLineBetweenTokens() + => new Verify.Test + { + TestCode = """ + class C + { + [||] -}"; - var fixedCode = -@"class C -{ + } + """, + FixedCode = """ + class C + { -}"; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + } + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestFourBlankLineBetweenTokens() - { - var code = -@"class C -{ -[||] + public Task TestFourBlankLineBetweenTokens() + => new Verify.Test + { + TestCode = """ + class C + { + [||] -}"; - var fixedCode = -@"class C -{ + } + """, + FixedCode = """ + class C + { -}"; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + } + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNoBlankLineAfterComment() - { - var code = -@"class C -{ - // comment -}"; - - await new Verify.Test + public Task TestNoBlankLineAfterComment() + => new Verify.Test { - TestCode = code, + TestCode = """ + class C + { + // comment + } + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestOneBlankLineAfterComment() - { - var code = -@"class C -{ - // comment - -}"; - - await new Verify.Test + public Task TestOneBlankLineAfterComment() + => new Verify.Test { - TestCode = code, + TestCode = """ + class C + { + // comment + + } + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestTwoBlankLineAfterComment() - { - var code = -@"class C -{ - // comment -[||] - -}"; - var fixedCode = -@"class C -{ - // comment + public Task TestTwoBlankLineAfterComment() + => new Verify.Test + { + TestCode = """ + class C + { + // comment + [||] -}"; + } + """, + FixedCode = """ + class C + { + // comment - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + } + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestThreeBlankLineAfterComment() - { - var code = -@"class C -{ - // comment -[||] - + public Task TestThreeBlankLineAfterComment() + => new Verify.Test + { + TestCode = """ + class C + { + // comment + [||] -}"; - var fixedCode = -@"class C -{ - // comment -}"; + } + """, + FixedCode = """ + class C + { + // comment - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + } + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestFourBlankLineAfterComment() - { - var code = -@"class C -{ - // comment -[||] - + public Task TestFourBlankLineAfterComment() + => new Verify.Test + { + TestCode = """ + class C + { + // comment + [||] -}"; - var fixedCode = -@"class C -{ - // comment -}"; + } + """, + FixedCode = """ + class C + { + // comment - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + } + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNoBlankLineAfterDirective() - { - var code = -@"class C -{ - #nullable enable -}"; - - await new Verify.Test + public Task TestNoBlankLineAfterDirective() + => new Verify.Test { - TestCode = code, + TestCode = """ + class C + { + #nullable enable + } + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestOneBlankLineAfterDirective() - { - var code = -@"class C -{ - #nullable enable - -}"; - - await new Verify.Test + public Task TestOneBlankLineAfterDirective() + => new Verify.Test { - TestCode = code, + TestCode = """ + class C + { + #nullable enable + + } + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestTwoBlankLineAfterDirective() - { - var code = -@"class C -{ - #nullable enable -[||] - -}"; - var fixedCode = -@"class C -{ - #nullable enable + public Task TestTwoBlankLineAfterDirective() + => new Verify.Test + { + TestCode = """ + class C + { + #nullable enable + [||] -}"; + } + """, + FixedCode = """ + class C + { + #nullable enable - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + } + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestThreeBlankLineAfterDirective() - { - var code = -@"class C -{ - #nullable enable -[||] + public Task TestThreeBlankLineAfterDirective() + => new Verify.Test + { + TestCode = """ + class C + { + #nullable enable + [||] -}"; - var fixedCode = -@"class C -{ - #nullable enable + } + """, + FixedCode = """ + class C + { + #nullable enable -}"; - - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + } + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestFourBlankLineAfterDirective() - { - var code = -@"class C -{ - #nullable enable -[||] - + public Task TestFourBlankLineAfterDirective() + => new Verify.Test + { + TestCode = """ + class C + { + #nullable enable + [||] -}"; - var fixedCode = -@"class C -{ - #nullable enable -}"; + } + """, + FixedCode = """ + class C + { + #nullable enable - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + } + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNoBlankLineAfterDocComment() - { - var code = -@" -/// -class C -{ -}"; - - await new Verify.Test + public Task TestNoBlankLineAfterDocComment() + => new Verify.Test { - TestCode = code, + TestCode = """ + + /// + class C + { + } + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestOneBlankLineAfterDocComment() - { - var code = -@" -/// + public Task TestOneBlankLineAfterDocComment() + => new Verify.Test + { + TestCode = """ -class C -{ -}"; + /// - await new Verify.Test - { - TestCode = code, + class C + { + } + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestTwoBlankLineAfterDocComment() - { - var code = -@" -/// -[||] + public Task TestTwoBlankLineAfterDocComment() + => new Verify.Test + { + TestCode = """ -class C -{ -}"; - var fixedCode = -@" -/// + /// + [||] -class C -{ -}"; + class C + { + } + """, + FixedCode = """ - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + /// + + class C + { + } + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestThreeBlankLineAfterDocComment() - { - var code = -@" -/// -[||] + public Task TestThreeBlankLineAfterDocComment() + => new Verify.Test + { + TestCode = """ + /// + [||] -class C -{ -}"; - var fixedCode = -@" -/// -class C -{ -}"; + class C + { + } + """, + FixedCode = """ - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + /// + + class C + { + } + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestFourBlankLineAfterDocComment() - { - var code = -@" -/// -[||] + public Task TestFourBlankLineAfterDocComment() + => new Verify.Test + { + TestCode = """ + /// + [||] -class C -{ -}"; - var fixedCode = -@" -/// -class C -{ -}"; + class C + { + } + """, + FixedCode = """ - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + /// + + class C + { + } + """, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestNoBlankLineAllConstructs() - { - var code = -@"/// -// -#nullable enable -class C -{ -}"; - - await new Verify.Test + public Task TestNoBlankLineAllConstructs() + => new Verify.Test { - TestCode = code, + TestCode = """ + /// + // + #nullable enable + class C + { + } + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestOneBlankLineAllConstructs() - { - var code = -@" -/// + public Task TestOneBlankLineAllConstructs() + => new Verify.Test + { + TestCode = """ -// + /// -#nullable enable + // -class C -{ -}"; + #nullable enable - await new Verify.Test - { - TestCode = code, + class C + { + } + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestTwoBlankLineAllConstructs() - { - var code = -@"[||] + public Task TestTwoBlankLineAllConstructs() + => new Verify.Test + { + TestCode = """ + [||] -/// + /// -// + // -#nullable enable + #nullable enable -class C -{ -}"; - var fixedCode = -@" -/// + class C + { + } + """, + FixedCode = """ -// + /// -#nullable enable + // -class C -{ -}"; + #nullable enable - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + class C + { + } + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestThreeBlankLineAllConstructs() - { - var code = -@"[||] + public Task TestThreeBlankLineAllConstructs() + => new Verify.Test + { + TestCode = """ + [||] -/// + /// -// + // -#nullable enable + #nullable enable -class C -{ -}"; - var fixedCode = -@" -/// + class C + { + } + """, + FixedCode = """ -// + /// -#nullable enable + // -class C -{ -}"; + #nullable enable - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + class C + { + } + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestFourBlankLineAllConstructs() - { - var code = -@"[||] + public Task TestFourBlankLineAllConstructs() + => new Verify.Test + { + TestCode = """ + [||] -/// + /// -// + // -#nullable enable + #nullable enable -class C -{ -}"; - var fixedCode = -@" -/// + class C + { + } + """, + FixedCode = """ -// + /// -#nullable enable + // -class C -{ -}"; + #nullable enable - await new Verify.Test - { - TestCode = code, - FixedCode = fixedCode, + class C + { + } + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/Nullable/CSharpDeclareAsNullableCodeFixTests.cs b/src/Analyzers/CSharp/Tests/Nullable/CSharpDeclareAsNullableCodeFixTests.cs index 44aaf0d023636..8f64ae3abab84 100644 --- a/src/Analyzers/CSharp/Tests/Nullable/CSharpDeclareAsNullableCodeFixTests.cs +++ b/src/Analyzers/CSharp/Tests/Nullable/CSharpDeclareAsNullableCodeFixTests.cs @@ -24,9 +24,8 @@ internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProvide private static readonly TestParameters s_nullableFeature = new TestParameters(parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8)); [Fact] - public async Task FixAll() - { - await TestInRegularAndScript1Async( + public Task FixAll() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -61,12 +60,10 @@ class Program } } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixReturnType() - { - await TestInRegularAndScript1Async( + public Task FixReturnType() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -87,12 +84,10 @@ class Program } } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixReturnType_Async() - { - await TestInRegularAndScript1Async( + public Task FixReturnType_Async() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -113,12 +108,10 @@ class Program } } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixReturnType_AsyncLocalFunction() - { - await TestInRegularAndScript1Async( + public Task FixReturnType_AsyncLocalFunction() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -145,12 +138,10 @@ static void M() } } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixReturnType_WithTrivia() - { - await TestInRegularAndScript1Async( + public Task FixReturnType_WithTrivia() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -171,12 +162,10 @@ class Program } } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixReturnType_ArrowBody() - { - await TestInRegularAndScript1Async( + public Task FixReturnType_ArrowBody() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -191,12 +180,10 @@ class Program static string? M() => null; } """, parameters: s_nullableFeature); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26639")] - public async Task FixReturnType_LocalFunction_ArrowBody() - { - await TestMissingInRegularAndScriptAsync( + public Task FixReturnType_LocalFunction_ArrowBody() + => TestMissingInRegularAndScriptAsync( """ #nullable enable class Program @@ -207,12 +194,10 @@ static void M() } } """, parameters: s_nullableFeature); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26639")] - public async Task FixLocalFunctionReturnType() - { - await TestInRegularAndScript1Async( + public Task FixLocalFunctionReturnType() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -239,12 +224,10 @@ void M() } } """, parameters: s_nullableFeature); - } [Fact] - public async Task NoFixAlreadyNullableReturnType() - { - await TestMissingInRegularAndScriptAsync( + public Task NoFixAlreadyNullableReturnType() + => TestMissingInRegularAndScriptAsync( """ #nullable enable class Program @@ -255,12 +238,10 @@ class Program } } """, parameters: s_nullableFeature); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26628")] - public async Task FixField() - { - await TestInRegularAndScript1Async( + public Task FixField() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -275,12 +256,10 @@ class Program string? x = null; } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixFieldEqualsNull() - { - await TestInRegularAndScript1Async( + public Task FixFieldEqualsNull() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -303,12 +282,10 @@ void M() } } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixPropertyEqualsNull() - { - await TestInRegularAndScript1Async( + public Task FixPropertyEqualsNull() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -331,12 +308,10 @@ void M() } } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixLocalDeclaration() - { - await TestInRegularAndScript1Async( + public Task FixLocalDeclaration() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -357,12 +332,10 @@ static void M() } } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixLocalDeclaration_FromAssignment() - { - await TestInRegularAndScript1Async( + public Task FixLocalDeclaration_FromAssignment() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -385,12 +358,10 @@ static void M() } } """, parameters: s_nullableFeature); - } [Fact] - public async Task CannotFixMultiLocalDeclaration_FromAssignment() - { - await TestMissingInRegularAndScriptAsync( + public Task CannotFixMultiLocalDeclaration_FromAssignment() + => TestMissingInRegularAndScriptAsync( """ #nullable enable class Program @@ -402,12 +373,10 @@ static void M() } } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixParameter_FromAssignment() - { - await TestInRegularAndScript1Async( + public Task FixParameter_FromAssignment() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -428,12 +397,10 @@ static void M(out string? x) } } """, parameters: s_nullableFeature); - } [Fact] - public async Task CannotFixParameterOfPartialMethod_FromAssignment() - { - await TestMissingInRegularAndScriptAsync( + public Task CannotFixParameterOfPartialMethod_FromAssignment() + => TestMissingInRegularAndScriptAsync( """ #nullable enable partial class Program @@ -446,12 +413,10 @@ partial void M(out string x) } } """, parameters: s_nullableFeature); - } [Fact] - public async Task CannotFixParameterOfExtendedPartialMethod_FromAssignment() - { - await TestMissingInRegularAndScriptAsync( + public Task CannotFixParameterOfExtendedPartialMethod_FromAssignment() + => TestMissingInRegularAndScriptAsync( """ #nullable enable partial class Program @@ -464,12 +429,10 @@ public partial void M(out string x) } } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixLocalDeclaration_WithVar() - { - await TestMissingInRegularAndScriptAsync( + public Task FixLocalDeclaration_WithVar() + => TestMissingInRegularAndScriptAsync( """ #nullable enable class Program @@ -480,12 +443,10 @@ static void M() } } """, parameters: s_nullableFeature); - } [Fact] - public async Task NoFixMultiDeclaration() - { - await TestMissingInRegularAndScriptAsync( + public Task NoFixMultiDeclaration() + => TestMissingInRegularAndScriptAsync( """ #nullable enable class Program @@ -496,12 +457,10 @@ static void M() } } """, parameters: s_nullableFeature); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26628")] - public async Task FixPropertyDeclaration() - { - await TestInRegularAndScript1Async( + public Task FixPropertyDeclaration() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -516,12 +475,10 @@ class Program string? x { get; set; } = null; } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixPropertyDeclaration_WithReturnNull() - { - await TestInRegularAndScript1Async( + public Task FixPropertyDeclaration_WithReturnNull() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -536,12 +493,10 @@ class Program string? x { get { return null; } } } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixPropertyDeclaration_ArrowBody() - { - await TestInRegularAndScript1Async( + public Task FixPropertyDeclaration_ArrowBody() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -556,13 +511,11 @@ class Program string? x => null; } """, parameters: s_nullableFeature); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26626")] [WorkItem("https://github.com/dotnet/roslyn/issues/30026")] - public async Task FixOptionalParameter() - { - await TestInRegularAndScript1Async( + public Task FixOptionalParameter() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -577,12 +530,10 @@ class Program static void M(string? x = null) { } } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixLocalWithAs() - { - await TestInRegularAndScript1Async( + public Task FixLocalWithAs() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -603,12 +554,10 @@ static void M(object o) } } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixReturnType_Iterator_Enumerable() - { - await TestInRegularAndScript1Async( + public Task FixReturnType_Iterator_Enumerable() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -629,12 +578,10 @@ class Program } } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixReturnType_Iterator_Enumerator() - { - await TestInRegularAndScript1Async( + public Task FixReturnType_Iterator_Enumerator() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -655,12 +602,10 @@ class Program } } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixReturnType_IteratorProperty() - { - await TestInRegularAndScript1Async( + public Task FixReturnType_IteratorProperty() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -687,12 +632,10 @@ class Program } } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixReturnType_Iterator_LocalFunction() - { - await TestInRegularAndScript1Async( + public Task FixReturnType_Iterator_LocalFunction() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -719,12 +662,10 @@ void M() } } """, parameters: s_nullableFeature); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39422")] - public async Task FixReturnType_ConditionalOperator_Function() - { - await TestInRegularAndScript1Async( + public Task FixReturnType_ConditionalOperator_Function() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -745,12 +686,10 @@ class Program } } """, parameters: s_nullableFeature); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39422")] - public async Task FixAllReturnType_ConditionalOperator_Function() - { - await TestInRegularAndScript1Async( + public Task FixAllReturnType_ConditionalOperator_Function() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -801,12 +740,10 @@ string Test2(bool? value) } } """, parameters: s_nullableFeature); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39422")] - public async Task FixAllReturnType_Invocation() - { - await TestInRegularAndScript1Async( + public Task FixAllReturnType_Invocation() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -861,12 +798,10 @@ string Test2(bool? value) } } """, parameters: s_nullableFeature); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39420")] - public async Task FixReturnType_TernaryExpression_Function() - { - await TestInRegularAndScript1Async( + public Task FixReturnType_TernaryExpression_Function() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -887,12 +822,10 @@ class Program } } """, parameters: s_nullableFeature); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39423")] - public async Task FixReturnType_Default() - { - await TestInRegularAndScript1Async( + public Task FixReturnType_Default() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -913,12 +846,10 @@ class Program } } """, parameters: s_nullableFeature); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39423")] - public async Task FixReturnType_DefaultWithNullableType() - { - await TestInRegularAndScript1Async( + public Task FixReturnType_DefaultWithNullableType() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -939,12 +870,10 @@ class Program } } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixInvocation_NamedArgument() - { - await TestInRegularAndScript1Async( + public Task FixInvocation_NamedArgument() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -967,12 +896,10 @@ void M() void M2(string? x) { } } """, parameters: s_nullableFeature); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44338")] - public async Task NoFixInvocationOfExternalMethod_NamedArgument() - { - await TestMissingInRegularAndScriptAsync( + public Task NoFixInvocationOfExternalMethod_NamedArgument() + => TestMissingInRegularAndScriptAsync( """ #nullable enable class Program @@ -984,12 +911,10 @@ void M() } } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixInvocation_NamedArgument_OutOfOrder() - { - await TestInRegularAndScript1Async( + public Task FixInvocation_NamedArgument_OutOfOrder() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -1012,12 +937,10 @@ void M() void M2(int i, string? x) { } } """, parameters: s_nullableFeature); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44338")] - public async Task NoFixInvocationOfExternalMethod_NamedArgument_OutOfOrder() - { - await TestMissingInRegularAndScriptAsync( + public Task NoFixInvocationOfExternalMethod_NamedArgument_OutOfOrder() + => TestMissingInRegularAndScriptAsync( """ #nullable enable class Program @@ -1029,12 +952,10 @@ void M() } } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixInvocation_NamedArgument_Partial() - { - await TestMissingInRegularAndScriptAsync( + public Task FixInvocation_NamedArgument_Partial() + => TestMissingInRegularAndScriptAsync( """ #nullable enable partial class Program @@ -1047,12 +968,10 @@ void M() partial void M2(string x) { } } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixInvocation_PositionArgument() - { - await TestInRegularAndScript1Async( + public Task FixInvocation_PositionArgument() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -1075,12 +994,10 @@ void M() void M2(string? x) { } } """, parameters: s_nullableFeature); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44338")] - public async Task NoFixInvocationOfExternalMethod_PositionArgument() - { - await TestMissingInRegularAndScriptAsync( + public Task NoFixInvocationOfExternalMethod_PositionArgument() + => TestMissingInRegularAndScriptAsync( """ #nullable enable class Program @@ -1092,12 +1009,10 @@ void M() } } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixInvocation_PositionArgument_SecondPosition() - { - await TestInRegularAndScript1Async( + public Task FixInvocation_PositionArgument_SecondPosition() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -1120,12 +1035,10 @@ void M() void M2(int i, string? x) { } } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixInvocation_PositionArgument_Params() - { - await TestMissingInRegularAndScriptAsync( + public Task FixInvocation_PositionArgument_Params() + => TestMissingInRegularAndScriptAsync( """ #nullable enable class Program @@ -1137,13 +1050,10 @@ void M() void M2(params string[] x) { } } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixInvocation_Indexer() - { - // Not supported yet - await TestMissingInRegularAndScriptAsync( + public Task FixInvocation_Indexer() + => TestMissingInRegularAndScriptAsync( """ #nullable enable class Program @@ -1155,12 +1065,10 @@ void M() int this[string x] { get { throw null!; } set { throw null!; } } } """, parameters: s_nullableFeature); - } [Fact] - public async Task FixPropertyDeclaration_Unassigned() - { - await TestInRegularAndScript1Async( + public Task FixPropertyDeclaration_Unassigned() + => TestInRegularAndScript1Async( """ #nullable enable @@ -1178,12 +1086,10 @@ class C } """, parameters: s_nullableFeature); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44983")] - public async Task FixFieldDeclaration_Unassigned() - { - await TestInRegularAndScript1Async( + public Task FixFieldDeclaration_Unassigned() + => TestInRegularAndScript1Async( """ #nullable enable @@ -1201,12 +1107,10 @@ class C } """, parameters: s_nullableFeature); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44983")] - public async Task MultipleDeclarator_NoDiagnostic() - { - await TestMissingInRegularAndScriptAsync( + public Task MultipleDeclarator_NoDiagnostic() + => TestMissingInRegularAndScriptAsync( """ #nullable enable class Program @@ -1214,12 +1118,10 @@ class Program string [|s|], s2 = "hello"; } """, parameters: s_nullableFeature); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46354")] - public async Task FixTupleFieldAssignment() - { - await TestInRegularAndScript1Async( + public Task FixTupleFieldAssignment() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -1242,12 +1144,10 @@ static void F1((string?, string?) t) } } """, parameters: s_nullableFeature); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46354")] - public async Task FixTupleNamedFieldAssignment() - { - await TestInRegularAndScript1Async( + public Task FixTupleNamedFieldAssignment() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -1270,12 +1170,10 @@ static void F1((string? Foo, string? Bar) t) } } """, parameters: s_nullableFeature); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46354")] - public async Task FixTupleGenericFieldAssignment() - { - await TestInRegularAndScript1Async( + public Task FixTupleGenericFieldAssignment() + => TestInRegularAndScript1Async( """ #nullable enable class Program @@ -1302,5 +1200,4 @@ static void F1((T?, T?) t) where T : class } } """, parameters: s_nullableFeature); - } } diff --git a/src/Analyzers/CSharp/Tests/OrderModifiers/OrderModifiersCompilerErrorTests.cs b/src/Analyzers/CSharp/Tests/OrderModifiers/OrderModifiersCompilerErrorTests.cs index 9360507e4f262..4022661bcd239 100644 --- a/src/Analyzers/CSharp/Tests/OrderModifiers/OrderModifiersCompilerErrorTests.cs +++ b/src/Analyzers/CSharp/Tests/OrderModifiers/OrderModifiersCompilerErrorTests.cs @@ -26,11 +26,8 @@ internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProvide [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] [WorkItem("https://github.com/dotnet/roslyn/issues/30352")] - public async Task PartialAtTheEnd() - { - // Verify that the code fix claims it fixes the compiler error (CS0267) in addition to the analyzer diagnostic. - await TestInRegularAndScript1Async( + public Task PartialAtTheEnd() + => TestInRegularAndScript1Async( @"[|partial|] public class C { }", @"public partial class C { }"); - } } diff --git a/src/Analyzers/CSharp/Tests/OrderModifiers/OrderModifiersTests.cs b/src/Analyzers/CSharp/Tests/OrderModifiers/OrderModifiersTests.cs index 2e2287588b157..1d5a862fb95b3 100644 --- a/src/Analyzers/CSharp/Tests/OrderModifiers/OrderModifiersTests.cs +++ b/src/Analyzers/CSharp/Tests/OrderModifiers/OrderModifiersTests.cs @@ -26,9 +26,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider => (new CSharpOrderModifiersDiagnosticAnalyzer(), new CSharpOrderModifiersCodeFixProvider()); [Fact] - public async Task TestClass() - { - await TestInRegularAndScript1Async( + public Task TestClass() + => TestInRegularAndScript1Async( """ [|static|] internal class C { @@ -39,12 +38,10 @@ internal static class C { } """); - } [Fact] - public async Task TestStruct() - { - await TestInRegularAndScript1Async( + public Task TestStruct() + => TestInRegularAndScript1Async( """ [|unsafe|] public struct C { @@ -55,12 +52,10 @@ public unsafe struct C { } """); - } [Fact] - public async Task TestInterface() - { - await TestInRegularAndScript1Async( + public Task TestInterface() + => TestInRegularAndScript1Async( """ [|unsafe|] public interface C { @@ -71,12 +66,10 @@ public unsafe interface C { } """); - } [Fact] - public async Task TestEnum() - { - await TestInRegularAndScript1Async( + public Task TestEnum() + => TestInRegularAndScript1Async( """ [|internal|] protected enum C { @@ -87,20 +80,16 @@ protected internal enum C { } """); - } [Fact] - public async Task TestDelegate() - { - await TestInRegularAndScript1Async( + public Task TestDelegate() + => TestInRegularAndScript1Async( @"[|unsafe|] public delegate void D();", @"public unsafe delegate void D();"); - } [Fact] - public async Task TestMethod() - { - await TestInRegularAndScript1Async( + public Task TestMethod() + => TestInRegularAndScript1Async( """ class C { @@ -113,12 +102,10 @@ class C public unsafe void M() { } } """); - } [Fact] - public async Task TestField() - { - await TestInRegularAndScript1Async( + public Task TestField() + => TestInRegularAndScript1Async( """ class C { @@ -131,12 +118,10 @@ class C public unsafe int a; } """); - } [Fact] - public async Task TestConstructor() - { - await TestInRegularAndScript1Async( + public Task TestConstructor() + => TestInRegularAndScript1Async( """ class C { @@ -149,12 +134,10 @@ class C public unsafe C() { } } """); - } [Fact] - public async Task TestProperty() - { - await TestInRegularAndScript1Async( + public Task TestProperty() + => TestInRegularAndScript1Async( """ class C { @@ -167,12 +150,10 @@ class C public unsafe int P { get; } } """); - } [Fact] - public async Task TestAccessor() - { - await TestInRegularAndScript1Async( + public Task TestAccessor() + => TestInRegularAndScript1Async( """ class C { @@ -185,12 +166,10 @@ class C int P { protected internal get; } } """); - } [Fact] - public async Task TestPropertyEvent() - { - await TestInRegularAndScript1Async( + public Task TestPropertyEvent() + => TestInRegularAndScript1Async( """ class C { @@ -203,12 +182,10 @@ class C protected internal event Action P { add { } remove { } } } """); - } [Fact] - public async Task TestFieldEvent() - { - await TestInRegularAndScript1Async( + public Task TestFieldEvent() + => TestInRegularAndScript1Async( """ class C { @@ -221,12 +198,10 @@ class C protected internal event Action P; } """); - } [Fact] - public async Task TestOperator() - { - await TestInRegularAndScript1Async( + public Task TestOperator() + => TestInRegularAndScript1Async( """ class C { @@ -239,12 +214,10 @@ class C public static C operator +(C c1, C c2) { } } """); - } [Fact] - public async Task TestConversionOperator() - { - await TestInRegularAndScript1Async( + public Task TestConversionOperator() + => TestInRegularAndScript1Async( """ class C { @@ -257,12 +230,10 @@ class C public static implicit operator bool(C c1) { } } """); - } [Fact] - public async Task TestFixAll1() - { - await TestInRegularAndScript1Async( + public Task TestFixAll1() + => TestInRegularAndScript1Async( """ {|FixAllInDocument:static|} internal class C { @@ -275,12 +246,10 @@ internal static class C internal static class Nested { } } """); - } [Fact] - public async Task TestFixAll2() - { - await TestInRegularAndScript1Async( + public Task TestFixAll2() + => TestInRegularAndScript1Async( """ static internal class C { @@ -293,12 +262,10 @@ internal static class C internal static class Nested { } } """); - } [Fact] - public async Task TestTrivia1() - { - await TestInRegularAndScript1Async( + public Task TestTrivia1() + => TestInRegularAndScript1Async( """ /// Doc comment [|static|] internal class C @@ -311,12 +278,10 @@ internal static class C { } """); - } [Fact] - public async Task TestTrivia2() - { - await TestInRegularAndScript1Async( + public Task TestTrivia2() + => TestInRegularAndScript1Async( """ /* start */ [|static|] /* middle */ internal /* end */ class C { @@ -327,12 +292,10 @@ await TestInRegularAndScript1Async( { } """); - } [Fact] - public async Task TestTrivia3() - { - await TestInRegularAndScript1Async( + public Task TestTrivia3() + => TestInRegularAndScript1Async( """ #if true [|static|] internal class C @@ -347,76 +310,58 @@ internal static class C } #endif """); - } [Fact] - public async Task PartialAtTheEndClass1() - { - await TestInRegularAndScript1Async( + public Task PartialAtTheEndClass1() + => TestInRegularAndScript1Async( @"[|partial|] public class C { }", @"public partial class C { }"); - } [Fact] - public async Task PartialAtTheEndClass2() - { - await TestInRegularAndScript1Async( + public Task PartialAtTheEndClass2() + => TestInRegularAndScript1Async( @"[|partial|] abstract class C { }", @"abstract partial class C { }"); - } [Fact] - public async Task PartialAtTheEndClass3() - { - await TestInRegularAndScript1Async( + public Task PartialAtTheEndClass3() + => TestInRegularAndScript1Async( @"[|partial|] sealed class C { }", @"sealed partial class C { }"); - } [Fact] - public async Task PartialAtTheEndClass4() - { - await TestInRegularAndScript1Async( + public Task PartialAtTheEndClass4() + => TestInRegularAndScript1Async( @"[|partial|] static class C { }", @"static partial class C { }"); - } [Fact] - public async Task PartialAtTheEndClass5() - { - await TestInRegularAndScript1Async( + public Task PartialAtTheEndClass5() + => TestInRegularAndScript1Async( @"[|partial|] unsafe class C { }", @"unsafe partial class C { }"); - } [Fact] - public async Task PartialAtTheEndStruct1() - { - await TestInRegularAndScript1Async( + public Task PartialAtTheEndStruct1() + => TestInRegularAndScript1Async( @"[|partial|] public struct S { }", @"public partial struct S { }"); - } [Fact] - public async Task PartialAtTheEndStruct2() - { - await TestInRegularAndScript1Async( + public Task PartialAtTheEndStruct2() + => TestInRegularAndScript1Async( @"[|partial|] unsafe struct S { }", @"unsafe partial struct S { }"); - } [Fact] - public async Task PartialAtTheEndInterface() - { - await TestInRegularAndScript1Async( + public Task PartialAtTheEndInterface() + => TestInRegularAndScript1Async( @"[|partial|] public interface I { }", @"public partial interface I { }"); - } [Fact] - public async Task PartialAtTheEndMethod1() - { - await TestInRegularAndScript1Async( + public Task PartialAtTheEndMethod1() + => TestInRegularAndScript1Async( """ partial class C { @@ -429,12 +374,10 @@ partial class C static partial void M(); } """); - } [Fact] - public async Task PartialAtTheEndMethod2() - { - await TestInRegularAndScript1Async( + public Task PartialAtTheEndMethod2() + => TestInRegularAndScript1Async( """ partial class C { @@ -447,13 +390,10 @@ partial class C unsafe partial void M(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/pull/52297")] - public async Task TestInLocalFunction() - { - // Not handled for performance reason. - await TestMissingInRegularAndScriptAsync( + public Task TestInLocalFunction() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -463,12 +403,10 @@ public static async void M() } } """); - } [Fact] - public async Task TestFixAllInContainingMember_NotApplicable() - { - await TestMissingInRegularAndScriptAsync( + public Task TestFixAllInContainingMember_NotApplicable() + => TestMissingInRegularAndScriptAsync( """ {|FixAllInContainingMember:static|} internal class C { @@ -480,12 +418,10 @@ static internal class C2 static internal class Nested { } } """); - } [Fact] - public async Task TestFixAllInContainingType() - { - await TestInRegularAndScript1Async( + public Task TestFixAllInContainingType() + => TestInRegularAndScript1Async( """ {|FixAllInContainingType:static|} internal class C { @@ -508,12 +444,10 @@ static internal class C2 static internal class Nested { } } """); - } [Fact] - public async Task RequiredAfterAllOnProp() - { - await TestInRegularAndScriptAsync(""" + public Task RequiredAfterAllOnProp() + => TestInRegularAndScriptAsync(""" class C { [|required|] public virtual unsafe int Prop { get; init; } @@ -525,12 +459,10 @@ class C public virtual unsafe required int Prop { get; init; } } """); - } [Fact] - public async Task RequiredAfterAllButVolatileOnField() - { - await TestInRegularAndScriptAsync(""" + public Task RequiredAfterAllButVolatileOnField() + => TestInRegularAndScriptAsync(""" class C { [|required|] public unsafe volatile int Field; @@ -542,12 +474,10 @@ class C public unsafe required volatile int Field; } """); - } [Fact] - public async Task TestFileClass() - { - await TestInRegularAndScriptAsync(""" + public Task TestFileClass() + => TestInRegularAndScriptAsync(""" [|abstract file|] class C { } @@ -557,12 +487,10 @@ file abstract class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/vscode-csharp/issues/7553")] - public async Task TestEmptySelection() - { - await TestInRegularAndScript1Async( + public Task TestEmptySelection() + => TestInRegularAndScript1Async( """ namespace M; [||]static internal class C @@ -575,5 +503,4 @@ internal static class C { } """, TestParameters.Default.WithIncludeDiagnosticsOutsideSelection(false)); - } } diff --git a/src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchExpressionTests.cs b/src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchExpressionTests.cs index 46d228f86fa9a..b90c58c883e8d 100644 --- a/src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchExpressionTests.cs +++ b/src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchExpressionTests.cs @@ -25,9 +25,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider => (new CSharpPopulateSwitchExpressionDiagnosticAnalyzer(), new CSharpPopulateSwitchExpressionCodeFixProvider()); [Fact] - public async Task NotOnRangeToken() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnRangeToken() + => TestMissingInRegularAndScriptAsync( """ namespace ConsoleApplication1 { @@ -53,12 +52,10 @@ void Method() } } """); - } [Fact] - public async Task AllMembersAndDefaultExist() - { - await TestMissingInRegularAndScriptAsync( + public Task AllMembersAndDefaultExist() + => TestMissingInRegularAndScriptAsync( """ namespace ConsoleApplication1 { @@ -85,12 +82,10 @@ void Method() } } """); - } [Fact] - public async Task AllMembersExist_NotDefault() - { - await TestInRegularAndScript1Async( + public Task AllMembersExist_NotDefault() + => TestInRegularAndScript1Async( """ namespace ConsoleApplication1 { @@ -142,12 +137,10 @@ void Method() } } """); - } [Fact] - public async Task AllMembersExist_NotDefault_NoComma() - { - await TestInRegularAndScript1Async( + public Task AllMembersExist_NotDefault_NoComma() + => TestInRegularAndScript1Async( """ namespace ConsoleApplication1 { @@ -199,12 +192,10 @@ void Method() } } """); - } [Fact] - public async Task NotAllMembersExist_NotDefault() - { - await TestInRegularAndScript1Async( + public Task NotAllMembersExist_NotDefault() + => TestInRegularAndScript1Async( """ namespace ConsoleApplication1 { @@ -255,12 +246,10 @@ void Method() } } """, index: 2); - } [Fact] - public async Task NotAllMembersExist_WithDefault() - { - await TestInRegularAndScript1Async( + public Task NotAllMembersExist_WithDefault() + => TestInRegularAndScript1Async( """ namespace ConsoleApplication1 { @@ -312,12 +301,10 @@ void Method() } } """); - } [Fact] - public async Task NotAllMembersExist_NotDefault_EnumHasExplicitType() - { - await TestInRegularAndScript1Async( + public Task NotAllMembersExist_NotDefault_EnumHasExplicitType() + => TestInRegularAndScript1Async( """ namespace ConsoleApplication1 { @@ -368,12 +355,10 @@ void Method() } } """, index: 2); - } [Fact] - public async Task NotAllMembersExist_WithMembersAndDefaultInSection_NewValuesAboveDefaultSection() - { - await TestInRegularAndScript1Async( + public Task NotAllMembersExist_WithMembersAndDefaultInSection_NewValuesAboveDefaultSection() + => TestInRegularAndScript1Async( """ namespace ConsoleApplication1 { @@ -425,12 +410,10 @@ void Method() } } """); - } [Fact] - public async Task NotAllMembersExist_WithMembersAndDefaultInSection_AssumesDefaultIsInLastSection() - { - await TestInRegularAndScript1Async( + public Task NotAllMembersExist_WithMembersAndDefaultInSection_AssumesDefaultIsInLastSection() + => TestInRegularAndScript1Async( """ namespace ConsoleApplication1 { @@ -482,12 +465,10 @@ void Method() } } """); - } [Fact] - public async Task NoMembersExist0() - { - await TestInRegularAndScript1Async( + public Task NoMembersExist0() + => TestInRegularAndScript1Async( """ namespace ConsoleApplication1 { @@ -535,12 +516,10 @@ void Method() } } """, index: 0); - } [Fact] - public async Task NoMembersExist1() - { - await TestInRegularAndScript1Async( + public Task NoMembersExist1() + => TestInRegularAndScript1Async( """ namespace ConsoleApplication1 { @@ -586,12 +565,10 @@ void Method() } } """, index: 1); - } [Fact] - public async Task NoMembersExist2() - { - await TestInRegularAndScript1Async( + public Task NoMembersExist2() + => TestInRegularAndScript1Async( """ namespace ConsoleApplication1 { @@ -640,12 +617,10 @@ void Method() } } """, index: 2); - } [Fact] - public async Task UsingStaticEnum_AllMembersExist() - { - await TestMissingInRegularAndScriptAsync( + public Task UsingStaticEnum_AllMembersExist() + => TestMissingInRegularAndScriptAsync( """ using static System.IO.FileMode; @@ -670,12 +645,10 @@ void Method() } } """); - } [Fact] - public async Task UsingStaticEnum_AllMembersExist_OutOfDefaultOrder() - { - await TestMissingInRegularAndScriptAsync( + public Task UsingStaticEnum_AllMembersExist_OutOfDefaultOrder() + => TestMissingInRegularAndScriptAsync( """ using static System.IO.FileMode; @@ -700,12 +673,10 @@ void Method() } } """); - } [Fact] - public async Task UsingStaticEnum_MembersExist() - { - await TestInRegularAndScript1Async( + public Task UsingStaticEnum_MembersExist() + => TestInRegularAndScript1Async( """ using static System.IO.FileMode; @@ -752,12 +723,10 @@ void Method() } } """); - } [Fact] - public async Task UsingStaticEnum_NoMembersExist() - { - await TestInRegularAndScript1Async( + public Task UsingStaticEnum_NoMembersExist() + => TestInRegularAndScript1Async( """ using static System.IO.FileMode; @@ -799,12 +768,10 @@ void Method() } } """, index: 2); - } [Fact] - public async Task NotAllMembersExist_NotDefault_EnumHasNonFlagsAttribute() - { - await TestInRegularAndScript1Async( + public Task NotAllMembersExist_NotDefault_EnumHasNonFlagsAttribute() + => TestInRegularAndScript1Async( """ namespace ConsoleApplication1 { @@ -857,12 +824,10 @@ void Method() } } """, index: 2); - } [Fact] - public async Task NotAllMembersExist_NotDefault_EnumIsNested() - { - await TestInRegularAndScript1Async( + public Task NotAllMembersExist_NotDefault_EnumIsNested() + => TestInRegularAndScript1Async( """ namespace ConsoleApplication1 { @@ -913,12 +878,10 @@ void Method() } } """, index: 2); - } [Fact] - public async Task NotAllMembersExist_SwitchIsNotEnum() - { - await TestMissingInRegularAndScriptAsync( + public Task NotAllMembersExist_SwitchIsNotEnum() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -939,12 +902,10 @@ void Method() } } """); - } [Fact] - public async Task NotAllMembersExist_NotDefault_UsingConstants() - { - await TestInRegularAndScript1Async( + public Task NotAllMembersExist_NotDefault_UsingConstants() + => TestInRegularAndScript1Async( """ enum MyEnum { @@ -989,12 +950,10 @@ void Method() } } """, index: 2); - } [Fact] - public async Task NotAllMembersExist_NotDefault_WithMismatchingConstantType() - { - await TestInRegularAndScript1Async( + public Task NotAllMembersExist_NotDefault_WithMismatchingConstantType() + => TestInRegularAndScript1Async( """ enum MyEnum { @@ -1040,12 +999,10 @@ void Method() } } """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/40399")] - public async Task AllMissingTokens() - { - await TestInRegularAndScript1Async( + public Task AllMissingTokens() + => TestInRegularAndScript1Async( """ enum MyEnum { @@ -1077,12 +1034,10 @@ void Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40240")] - public async Task TestAddMissingCasesForNullableEnum() - { - await TestInRegularAndScript1Async( + public Task TestAddMissingCasesForNullableEnum() + => TestInRegularAndScript1Async( """ public class Program { @@ -1128,12 +1083,10 @@ public enum Bar } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50982")] - public async Task TestOrPatternIsHandled() - { - await TestInRegularAndScript1Async( + public Task TestOrPatternIsHandled() + => TestInRegularAndScript1Async( """ public static class C { @@ -1186,12 +1139,10 @@ public enum E } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50982")] - public async Task TestOrPatternIsHandled_AllEnumValuesAreHandled_NoDiagnostic() - { - await TestMissingInRegularAndScriptAsync( + public Task TestOrPatternIsHandled_AllEnumValuesAreHandled_NoDiagnostic() + => TestMissingInRegularAndScriptAsync( """ public static class C { @@ -1217,12 +1168,10 @@ public enum E } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50982")] - public async Task TestMixingOrWithAndPatterns() - { - await TestInRegularAndScript1Async( + public Task TestMixingOrWithAndPatterns() + => TestInRegularAndScript1Async( """ public static class C { @@ -1279,12 +1228,10 @@ public enum E } """ ); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50982")] - public async Task TestMixingOrWithAndPatterns2() - { - await TestInRegularAndScript1Async( + public Task TestMixingOrWithAndPatterns2() + => TestInRegularAndScript1Async( """ public static class C { @@ -1339,12 +1286,10 @@ public enum E } """ ); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58468")] - public async Task NotOnOrPatternWhichAlwaysSucceeds1() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnOrPatternWhichAlwaysSucceeds1() + => TestMissingInRegularAndScriptAsync( """ enum Greeting { @@ -1365,12 +1310,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58468")] - public async Task NotOnOrPatternWhichAlwaysSucceeds2() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnOrPatternWhichAlwaysSucceeds2() + => TestMissingInRegularAndScriptAsync( """ enum Greeting { @@ -1391,12 +1334,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58468")] - public async Task NotOnOrPatternWhichAlwaysSucceeds3() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnOrPatternWhichAlwaysSucceeds3() + => TestMissingInRegularAndScriptAsync( """ enum Greeting { @@ -1418,12 +1359,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58468")] - public async Task NotOnOrPatternWhichAlwaysSucceeds4() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnOrPatternWhichAlwaysSucceeds4() + => TestMissingInRegularAndScriptAsync( """ enum Greeting { @@ -1445,12 +1384,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61594")] - public async Task TestForNullableEnum_NullableEnabled() - { - await TestInRegularAndScript1Async( + public Task TestForNullableEnum_NullableEnabled() + => TestInRegularAndScript1Async( """ #nullable enable @@ -1486,12 +1423,10 @@ enum MyEnum Value1, Value2 } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61594")] - public async Task TestForNullableEnum_NullableEnabled_NotGenerateNullArmIfItAlreadyExists() - { - await TestInRegularAndScript1Async( + public Task TestForNullableEnum_NullableEnabled_NotGenerateNullArmIfItAlreadyExists() + => TestInRegularAndScript1Async( """ #nullable enable @@ -1528,12 +1463,10 @@ enum MyEnum Value1, Value2 } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61594")] - public async Task TestForNullableEnum_NullableDisabled() - { - await TestInRegularAndScript1Async( + public Task TestForNullableEnum_NullableDisabled() + => TestInRegularAndScript1Async( """ #nullable disable @@ -1569,12 +1502,10 @@ enum MyEnum Value1, Value2 } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61594")] - public async Task TestForNullableEnum_NullableDisabled_NotGenerateNullArmIfItAlreadyExists() - { - await TestInRegularAndScript1Async( + public Task TestForNullableEnum_NullableDisabled_NotGenerateNullArmIfItAlreadyExists() + => TestInRegularAndScript1Async( """ #nullable disable @@ -1611,12 +1542,10 @@ enum MyEnum Value1, Value2 } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48876")] - public async Task NotOnCompleteBoolean1() - { - await TestMissingAsync( + public Task NotOnCompleteBoolean1() + => TestMissingAsync( """ public class Sample { @@ -1630,12 +1559,10 @@ public string Method(bool boolean) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48876")] - public async Task NotOnCompleteBoolean2() - { - await TestMissingAsync( + public Task NotOnCompleteBoolean2() + => TestMissingAsync( """ public class Sample { @@ -1650,12 +1577,10 @@ public string Method(bool? boolean) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48876")] - public async Task OnIncompleteBoolean1() - { - await TestInRegularAndScript1Async( + public Task OnIncompleteBoolean1() + => TestInRegularAndScript1Async( """ public class Sample { @@ -1681,12 +1606,10 @@ public string Method(bool boolean) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48876")] - public async Task OnIncompleteBoolean2() - { - await TestInRegularAndScript1Async( + public Task OnIncompleteBoolean2() + => TestInRegularAndScript1Async( """ public class Sample { @@ -1714,14 +1637,12 @@ public string Method(bool? boolean) } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/50983")] [InlineData("int")] [InlineData("int i")] - public async Task NullableValueTypeWithNullAndUnderlyingValueArms1(string underlyingTypePattern) - { - await TestMissingInRegularAndScriptAsync($$""" + public Task NullableValueTypeWithNullAndUnderlyingValueArms1(string underlyingTypePattern) + => TestMissingInRegularAndScriptAsync($$""" class C { int M(int? x) @@ -1734,14 +1655,12 @@ int M(int? x) } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/50983")] [InlineData("int")] [InlineData("int i")] - public async Task NullableValueTypeWithNullAndUnderlyingValueArms2(string underlyingTypePattern) - { - await TestMissingInRegularAndScriptAsync($$""" + public Task NullableValueTypeWithNullAndUnderlyingValueArms2(string underlyingTypePattern) + => TestMissingInRegularAndScriptAsync($$""" class C { int M(int? x) @@ -1754,14 +1673,12 @@ int M(int? x) } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/50983")] [InlineData("int")] [InlineData("int i")] - public async Task NullableValueTypeWithNullAndUnderlyingValueArms3(string underlyingTypePattern) - { - await TestMissingInRegularAndScriptAsync($$""" + public Task NullableValueTypeWithNullAndUnderlyingValueArms3(string underlyingTypePattern) + => TestMissingInRegularAndScriptAsync($$""" class C { int M(int? x) @@ -1775,14 +1692,12 @@ int M(int? x) } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/50983")] [InlineData("string")] [InlineData("string s")] - public async Task NullableReferenceTypeWithNullAndUnderlyingValueArms1(string underlyingTypePattern) - { - await TestMissingInRegularAndScriptAsync($$""" + public Task NullableReferenceTypeWithNullAndUnderlyingValueArms1(string underlyingTypePattern) + => TestMissingInRegularAndScriptAsync($$""" class C { int M(string? x) @@ -1795,14 +1710,12 @@ int M(string? x) } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/50983")] [InlineData("string")] [InlineData("string s")] - public async Task NullableReferenceTypeWithNullAndUnderlyingValueArms2(string underlyingTypePattern) - { - await TestMissingInRegularAndScriptAsync($$""" + public Task NullableReferenceTypeWithNullAndUnderlyingValueArms2(string underlyingTypePattern) + => TestMissingInRegularAndScriptAsync($$""" class C { int M(string? x) @@ -1815,14 +1728,12 @@ int M(string? x) } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/50983")] [InlineData("string")] [InlineData("string s")] - public async Task NullableReferenceTypeWithNullAndUnderlyingValueArms3(string underlyingTypePattern) - { - await TestMissingInRegularAndScriptAsync($$""" + public Task NullableReferenceTypeWithNullAndUnderlyingValueArms3(string underlyingTypePattern) + => TestMissingInRegularAndScriptAsync($$""" class C { int M(string? x) @@ -1836,5 +1747,4 @@ int M(string? x) } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchExpressionTests_FixAllTests.cs b/src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchExpressionTests_FixAllTests.cs index 019b68c68908f..699181292c31a 100644 --- a/src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchExpressionTests_FixAllTests.cs +++ b/src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchExpressionTests_FixAllTests.cs @@ -12,9 +12,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.PopulateSwi public sealed partial class PopulateSwitchExpressionTests { [Fact] - public async Task TestFixAllInDocument() - { - var input = """ + public Task TestFixAllInDocument() + => TestInRegularAndScriptAsync(""" @@ -85,9 +84,7 @@ void Method() - """; - - var expected = """ + """, """ @@ -160,15 +157,11 @@ void Method() - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] - public async Task TestFixAllInProject() - { - var input = """ + public Task TestFixAllInProject() + => TestInRegularAndScriptAsync(""" @@ -233,9 +226,7 @@ void Method() - """; - - var expected = """ + """, """ @@ -302,15 +293,11 @@ void Method() - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] - public async Task TestFixAllInSolution() - { - var input = """ + public Task TestFixAllInSolution() + => TestInRegularAndScriptAsync(""" @@ -383,9 +370,7 @@ void Method() - """; - - var expected = """ + """, """ @@ -461,8 +446,5 @@ void Method() - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); } diff --git a/src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchStatementTests.cs b/src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchStatementTests.cs index 9e82cfe8a1b4b..afb4579be5dc4 100644 --- a/src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchStatementTests.cs +++ b/src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchStatementTests.cs @@ -21,9 +21,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider => (new CSharpPopulateSwitchStatementDiagnosticAnalyzer(), new CSharpPopulateSwitchStatementCodeFixProvider()); [Fact] - public async Task OnlyOnFirstToken() - { - await TestMissingInRegularAndScriptAsync( + public Task OnlyOnFirstToken() + => TestMissingInRegularAndScriptAsync( """ namespace ConsoleApplication1 { @@ -50,12 +49,10 @@ void Method() } } """); - } [Fact] - public async Task AllMembersAndDefaultExist() - { - await TestMissingInRegularAndScriptAsync( + public Task AllMembersAndDefaultExist() + => TestMissingInRegularAndScriptAsync( """ namespace ConsoleApplication1 { @@ -83,12 +80,10 @@ void Method() } } """); - } [Fact] - public async Task AllMembersExist_NotDefault() - { - await TestInRegularAndScriptAsync( + public Task AllMembersExist_NotDefault() + => TestInRegularAndScriptAsync( """ namespace ConsoleApplication1 { @@ -143,12 +138,10 @@ void Method() } } """); - } [Fact] - public async Task NotAllMembersExist_NotDefault() - { - await TestInRegularAndScriptAsync( + public Task NotAllMembersExist_NotDefault() + => TestInRegularAndScriptAsync( """ namespace ConsoleApplication1 { @@ -203,12 +196,10 @@ void Method() } } """, index: 2); - } [Fact] - public async Task NotAllMembersExist_WithDefault() - { - await TestInRegularAndScriptAsync( + public Task NotAllMembersExist_WithDefault() + => TestInRegularAndScriptAsync( """ namespace ConsoleApplication1 { @@ -265,12 +256,10 @@ void Method() } } """); - } [Fact] - public async Task NotAllMembersExist_NotDefault_EnumHasExplicitType() - { - await TestInRegularAndScriptAsync( + public Task NotAllMembersExist_NotDefault_EnumHasExplicitType() + => TestInRegularAndScriptAsync( """ namespace ConsoleApplication1 { @@ -325,12 +314,10 @@ void Method() } } """, index: 2); - } [Fact] - public async Task NotAllMembersExist_WithMembersAndDefaultInSection_NewValuesAboveDefaultSection() - { - await TestInRegularAndScriptAsync( + public Task NotAllMembersExist_WithMembersAndDefaultInSection_NewValuesAboveDefaultSection() + => TestInRegularAndScriptAsync( """ namespace ConsoleApplication1 { @@ -385,12 +372,10 @@ void Method() } } """); - } [Fact] - public async Task NotAllMembersExist_WithMembersAndDefaultInSection_AssumesDefaultIsInLastSection() - { - await TestInRegularAndScriptAsync( + public Task NotAllMembersExist_WithMembersAndDefaultInSection_AssumesDefaultIsInLastSection() + => TestInRegularAndScriptAsync( """ namespace ConsoleApplication1 { @@ -447,12 +432,10 @@ void Method() } } """); - } [Fact] - public async Task NoMembersExist0() - { - await TestInRegularAndScriptAsync( + public Task NoMembersExist0() + => TestInRegularAndScriptAsync( """ namespace ConsoleApplication1 { @@ -503,12 +486,10 @@ void Method() } } """, index: 0); - } [Fact] - public async Task NoMembersExist1() - { - await TestInRegularAndScriptAsync( + public Task NoMembersExist1() + => TestInRegularAndScriptAsync( """ namespace ConsoleApplication1 { @@ -555,12 +536,10 @@ void Method() } } """, index: 1); - } [Fact] - public async Task NoMembersExist2() - { - await TestInRegularAndScriptAsync( + public Task NoMembersExist2() + => TestInRegularAndScriptAsync( """ namespace ConsoleApplication1 { @@ -613,12 +592,10 @@ void Method() } } """, index: 2); - } [Fact] - public async Task UsingStaticEnum_AllMembersExist() - { - await TestMissingInRegularAndScriptAsync( + public Task UsingStaticEnum_AllMembersExist() + => TestMissingInRegularAndScriptAsync( """ using static System.IO.FileMode; @@ -650,12 +627,10 @@ void Method() } } """); - } [Fact] - public async Task UsingStaticEnum_AllMembersExist_OutOfDefaultOrder() - { - await TestMissingInRegularAndScriptAsync( + public Task UsingStaticEnum_AllMembersExist_OutOfDefaultOrder() + => TestMissingInRegularAndScriptAsync( """ using static System.IO.FileMode; @@ -687,12 +662,10 @@ void Method() } } """); - } [Fact] - public async Task UsingStaticEnum_MembersExist() - { - await TestInRegularAndScriptAsync( + public Task UsingStaticEnum_MembersExist() + => TestInRegularAndScriptAsync( """ using static System.IO.FileMode; @@ -751,12 +724,10 @@ void Method() } } """); - } [Fact] - public async Task UsingStaticEnum_NoMembersExist() - { - await TestInRegularAndScriptAsync( + public Task UsingStaticEnum_NoMembersExist() + => TestInRegularAndScriptAsync( """ using static System.IO.FileMode; @@ -805,12 +776,10 @@ void Method() } } """, index: 2); - } [Fact] - public async Task NotAllMembersExist_NotDefault_EnumHasNonFlagsAttribute() - { - await TestInRegularAndScriptAsync( + public Task NotAllMembersExist_NotDefault_EnumHasNonFlagsAttribute() + => TestInRegularAndScriptAsync( """ namespace ConsoleApplication1 { @@ -867,12 +836,10 @@ void Method() } } """, index: 2); - } [Fact] - public async Task NotAllMembersExist_NotDefault_EnumIsNested() - { - await TestInRegularAndScriptAsync( + public Task NotAllMembersExist_NotDefault_EnumIsNested() + => TestInRegularAndScriptAsync( """ namespace ConsoleApplication1 { @@ -927,12 +894,10 @@ void Method() } } """, index: 2); - } [Fact] - public async Task NotAllMembersExist_SwitchIsNotEnum() - { - await TestMissingInRegularAndScriptAsync( + public Task NotAllMembersExist_SwitchIsNotEnum() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -954,12 +919,10 @@ void Method() } } """); - } [Fact] - public async Task NotAllMembersExist_NotDefault_UsingConstants() - { - await TestInRegularAndScriptAsync( + public Task NotAllMembersExist_NotDefault_UsingConstants() + => TestInRegularAndScriptAsync( """ enum MyEnum { @@ -1008,12 +971,10 @@ void Method() } } """, index: 2); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/13455")] - public async Task AllMissingTokens() - { - await TestInRegularAndScriptAsync( + public Task AllMissingTokens() + => TestInRegularAndScriptAsync( """ enum MyEnum { @@ -1046,12 +1007,10 @@ void Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40240")] - public async Task TestAddMissingCasesForNullableEnum() - { - await TestInRegularAndScriptAsync( + public Task TestAddMissingCasesForNullableEnum() + => TestInRegularAndScriptAsync( """ public class Program { @@ -1104,12 +1063,10 @@ public enum Bar Option3, } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61594")] - public async Task TestForNullableEnum_NullableEnabled() - { - await TestInRegularAndScript1Async( + public Task TestForNullableEnum_NullableEnabled() + => TestInRegularAndScript1Async( """ #nullable enable @@ -1152,12 +1109,10 @@ enum MyEnum Value1, Value2 } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61594")] - public async Task TestForNullableEnum_NullableEnabled_NotGenerateNullArmIfItAlreadyExists() - { - await TestInRegularAndScript1Async( + public Task TestForNullableEnum_NullableEnabled_NotGenerateNullArmIfItAlreadyExists() + => TestInRegularAndScript1Async( """ #nullable enable @@ -1202,12 +1157,10 @@ enum MyEnum Value1, Value2 } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61594")] - public async Task TestForNullableEnum_NullableDisabled() - { - await TestInRegularAndScript1Async( + public Task TestForNullableEnum_NullableDisabled() + => TestInRegularAndScript1Async( """ #nullable disable @@ -1250,12 +1203,10 @@ enum MyEnum Value1, Value2 } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61594")] - public async Task TestForNullableEnum_NullableDisabled_NotGenerateNullArmIfItAlreadyExists() - { - await TestInRegularAndScript1Async( + public Task TestForNullableEnum_NullableDisabled_NotGenerateNullArmIfItAlreadyExists() + => TestInRegularAndScript1Async( """ #nullable disable @@ -1300,12 +1251,10 @@ enum MyEnum Value1, Value2 } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/pull/61809")] - public async Task TestNotInSwitchWithUnknownType1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotInSwitchWithUnknownType1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1315,18 +1264,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/pull/61809")] - public async Task TestNotInSwitchWithUnknownType2() - { - // Parser currently treats "var v = null switch" as: - // - // var v = null <- ';' is "missing" - // switch - // - // So switch is a statement here. - await TestMissingInRegularAndScriptAsync( + public Task TestNotInSwitchWithUnknownType2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1336,12 +1277,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48876")] - public async Task NotOnCompleteBoolean1() - { - await TestMissingAsync( + public Task NotOnCompleteBoolean1() + => TestMissingAsync( """ public class Sample { @@ -1355,12 +1294,10 @@ public string Method(bool boolean) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48876")] - public async Task NotOnCompleteBoolean2() - { - await TestMissingAsync( + public Task NotOnCompleteBoolean2() + => TestMissingAsync( """ public class Sample { @@ -1375,12 +1312,10 @@ public string Method(bool? boolean) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48876")] - public async Task OnIncompleteBoolean1() - { - await TestInRegularAndScript1Async( + public Task OnIncompleteBoolean1() + => TestInRegularAndScript1Async( """ public class Sample { @@ -1407,12 +1342,10 @@ public string Method(bool boolean) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48876")] - public async Task OnIncompleteBoolean2() - { - await TestInRegularAndScript1Async( + public Task OnIncompleteBoolean2() + => TestInRegularAndScript1Async( """ public class Sample { @@ -1441,12 +1374,10 @@ public string Method(bool? boolean) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71281")] - public async Task NotWithPatternDefault1() - { - await TestMissingInRegularAndScriptAsync( + public Task NotWithPatternDefault1() + => TestMissingInRegularAndScriptAsync( """ namespace ConsoleApplication1 { @@ -1475,12 +1406,10 @@ void Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71281")] - public async Task TestWithPatternDefault_NonConstantGuard1() - { - await TestInRegularAndScriptAsync( + public Task TestWithPatternDefault_NonConstantGuard1() + => TestInRegularAndScriptAsync( """ namespace ConsoleApplication1 { @@ -1539,12 +1468,10 @@ void Method(int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71281")] - public async Task TestNotWithPatternDefault_ConstantGuard1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithPatternDefault_ConstantGuard1() + => TestMissingInRegularAndScriptAsync( """ namespace ConsoleApplication1 { @@ -1573,12 +1500,10 @@ void Method(int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71281")] - public async Task TestWithPatternDefault_NonConstantTrueGuard() - { - await TestInRegularAndScriptAsync( + public Task TestWithPatternDefault_NonConstantTrueGuard() + => TestInRegularAndScriptAsync( """ namespace ConsoleApplication1 { @@ -1637,12 +1562,10 @@ void Method(int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73245")] - public async Task NotAllMembersExist_NotDefault_OrPattern() - { - await TestInRegularAndScriptAsync( + public Task NotAllMembersExist_NotDefault_OrPattern() + => TestInRegularAndScriptAsync( """ namespace ConsoleApplication1 { @@ -1697,12 +1620,10 @@ void Method() } } """, index: 2); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73245")] - public async Task NotAllMembersExist_WithDefault_OrPattern() - { - await TestInRegularAndScriptAsync( + public Task NotAllMembersExist_WithDefault_OrPattern() + => TestInRegularAndScriptAsync( """ namespace ConsoleApplication1 { @@ -1757,14 +1678,12 @@ void Method() } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/50983")] [InlineData("int")] [InlineData("int i")] - public async Task NullableValueTypeWithNullAndUnderlyingValueCases1(string underlyingTypePattern) - { - await TestMissingInRegularAndScriptAsync($$""" + public Task NullableValueTypeWithNullAndUnderlyingValueCases1(string underlyingTypePattern) + => TestMissingInRegularAndScriptAsync($$""" class C { void M(int? x) @@ -1779,14 +1698,12 @@ void M(int? x) } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/50983")] [InlineData("int")] [InlineData("int i")] - public async Task NullableValueTypeWithNullAndUnderlyingValueCases2(string underlyingTypePattern) - { - await TestMissingInRegularAndScriptAsync($$""" + public Task NullableValueTypeWithNullAndUnderlyingValueCases2(string underlyingTypePattern) + => TestMissingInRegularAndScriptAsync($$""" class C { int M(int? x) @@ -1801,14 +1718,12 @@ int M(int? x) } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/50983")] [InlineData("int")] [InlineData("int i")] - public async Task NullableValueTypeWithNullAndUnderlyingValueCases3(string underlyingTypePattern) - { - await TestMissingInRegularAndScriptAsync($$""" + public Task NullableValueTypeWithNullAndUnderlyingValueCases3(string underlyingTypePattern) + => TestMissingInRegularAndScriptAsync($$""" class C { void M(int? x) @@ -1825,12 +1740,10 @@ void M(int? x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50983")] - public async Task NullableValueTypeWithNullAndUnderlyingValueCases4() - { - await TestMissingInRegularAndScriptAsync(""" + public Task NullableValueTypeWithNullAndUnderlyingValueCases4() + => TestMissingInRegularAndScriptAsync(""" class C { int M(int? x) @@ -1844,12 +1757,10 @@ int M(int? x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50983")] - public async Task NullableValueTypeWithNullAndUnderlyingValueCases5() - { - await TestMissingInRegularAndScriptAsync(""" + public Task NullableValueTypeWithNullAndUnderlyingValueCases5() + => TestMissingInRegularAndScriptAsync(""" class C { int M(int? x) @@ -1863,14 +1774,12 @@ int M(int? x) } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/50983")] [InlineData("string")] [InlineData("string s")] - public async Task NullableReferenceTypeWithNullAndUnderlyingValueCases1(string underlyingTypePattern) - { - await TestMissingInRegularAndScriptAsync($$""" + public Task NullableReferenceTypeWithNullAndUnderlyingValueCases1(string underlyingTypePattern) + => TestMissingInRegularAndScriptAsync($$""" class C { void M(string? x) @@ -1885,14 +1794,12 @@ void M(string? x) } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/50983")] [InlineData("string")] [InlineData("string s")] - public async Task NullableReferenceTypeWithNullAndUnderlyingValueCases2(string underlyingTypePattern) - { - await TestMissingInRegularAndScriptAsync($$""" + public Task NullableReferenceTypeWithNullAndUnderlyingValueCases2(string underlyingTypePattern) + => TestMissingInRegularAndScriptAsync($$""" class C { int M(string? x) @@ -1907,14 +1814,12 @@ int M(string? x) } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/50983")] [InlineData("string")] [InlineData("string s")] - public async Task NullableReferenceTypeWithNullAndUnderlyingValueCases3(string underlyingTypePattern) - { - await TestMissingInRegularAndScriptAsync($$""" + public Task NullableReferenceTypeWithNullAndUnderlyingValueCases3(string underlyingTypePattern) + => TestMissingInRegularAndScriptAsync($$""" class C { void M(string? x) @@ -1931,12 +1836,10 @@ void M(string? x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50983")] - public async Task NullableReferenceTypeWithNullAndUnderlyingValueCases4() - { - await TestMissingInRegularAndScriptAsync(""" + public Task NullableReferenceTypeWithNullAndUnderlyingValueCases4() + => TestMissingInRegularAndScriptAsync(""" class C { int M(string? x) @@ -1950,12 +1853,10 @@ int M(string? x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50983")] - public async Task NullableReferenceTypeWithNullAndUnderlyingValueCases5() - { - await TestMissingInRegularAndScriptAsync(""" + public Task NullableReferenceTypeWithNullAndUnderlyingValueCases5() + => TestMissingInRegularAndScriptAsync(""" class C { int M(string? x) @@ -1969,5 +1870,4 @@ int M(string? x) } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchStatementTests_FixAllTests.cs b/src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchStatementTests_FixAllTests.cs index efa25c6d04879..e433e37ceedc1 100644 --- a/src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchStatementTests_FixAllTests.cs +++ b/src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchStatementTests_FixAllTests.cs @@ -15,9 +15,8 @@ public sealed partial class PopulateSwitchStatementTests [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInDocument() - { - var input = """ + public Task TestFixAllInDocument() + => TestInRegularAndScriptAsync(""" @@ -92,9 +91,7 @@ void Method() - """; - - var expected = """ + """, """ @@ -173,17 +170,13 @@ void Method() - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInProject() - { - var input = """ + public Task TestFixAllInProject() + => TestInRegularAndScriptAsync(""" @@ -251,9 +244,7 @@ void Method() - """; - - var expected = """ + """, """ @@ -325,17 +316,13 @@ void Method() - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInSolution() - { - var input = """ + public Task TestFixAllInSolution() + => TestInRegularAndScriptAsync(""" @@ -411,9 +398,7 @@ void Method() - """; - - var expected = """ + """, """ @@ -495,8 +480,5 @@ void Method() - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); } diff --git a/src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests.cs b/src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests.cs index d47d0d6fa7494..f007d522bd52c 100644 --- a/src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests.cs +++ b/src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests.cs @@ -40,9 +40,8 @@ private Task TestMissingAsyncWithOptionAndNotificationOption(string code, PerLan => TestMissingInRegularAndScriptAsync(code, new TestParameters(options: Option(option, true, notification))); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyFieldAccess_LHS() - { - await TestAsyncWithOption( + public Task QualifyFieldAccess_LHS() + => TestAsyncWithOption( """ class Class { @@ -65,13 +64,11 @@ void M() } } """, -CodeStyleOptions2.QualifyFieldAccess); - } + CodeStyleOptions2.QualifyFieldAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyFieldAccess_RHS() - { - await TestAsyncWithOption( + public Task QualifyFieldAccess_RHS() + => TestAsyncWithOption( """ class Class { @@ -94,13 +91,11 @@ void M() } } """, -CodeStyleOptions2.QualifyFieldAccess); - } + CodeStyleOptions2.QualifyFieldAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyFieldAccess_MethodArgument() - { - await TestAsyncWithOption( + public Task QualifyFieldAccess_MethodArgument() + => TestAsyncWithOption( """ class Class { @@ -123,13 +118,11 @@ void M(int ii) } } """, -CodeStyleOptions2.QualifyFieldAccess); - } + CodeStyleOptions2.QualifyFieldAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyFieldAccess_ChainedAccess() - { - await TestAsyncWithOption( + public Task QualifyFieldAccess_ChainedAccess() + => TestAsyncWithOption( """ class Class { @@ -152,13 +145,11 @@ void M() } } """, -CodeStyleOptions2.QualifyFieldAccess); - } + CodeStyleOptions2.QualifyFieldAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyFieldAccess_ConditionalAccess() - { - await TestAsyncWithOption( + public Task QualifyFieldAccess_ConditionalAccess() + => TestAsyncWithOption( """ class Class { @@ -181,13 +172,11 @@ void M() } } """, -CodeStyleOptions2.QualifyFieldAccess); - } + CodeStyleOptions2.QualifyFieldAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyFieldAccess_OnBase() - { - await TestAsyncWithOption( + public Task QualifyFieldAccess_OnBase() + => TestAsyncWithOption( """ class Base { @@ -216,13 +205,11 @@ void M() } } """, -CodeStyleOptions2.QualifyFieldAccess); - } + CodeStyleOptions2.QualifyFieldAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28509")] - public async Task QualifyFieldAccess_InObjectInitializer() - { - await TestAsyncWithOption( + public Task QualifyFieldAccess_InObjectInitializer() + => TestAsyncWithOption( """ class C { @@ -243,13 +230,11 @@ void M() } } """, -CodeStyleOptions2.QualifyFieldAccess); - } + CodeStyleOptions2.QualifyFieldAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28509")] - public async Task QualifyFieldAccess_InCollectionInitializer() - { - await TestAsyncWithOption( + public Task QualifyFieldAccess_InCollectionInitializer() + => TestAsyncWithOption( """ class C { @@ -270,13 +255,11 @@ void M() } } """, -CodeStyleOptions2.QualifyFieldAccess); - } + CodeStyleOptions2.QualifyFieldAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyFieldAccess_NotSuggestedOnInstance() - { - await TestMissingAsyncWithOption( + public Task QualifyFieldAccess_NotSuggestedOnInstance() + => TestMissingAsyncWithOption( """ class Class { @@ -289,13 +272,11 @@ void M() } } """, -CodeStyleOptions2.QualifyFieldAccess); - } + CodeStyleOptions2.QualifyFieldAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyFieldAccess_NotSuggestedOnStatic() - { - await TestMissingAsyncWithOption( + public Task QualifyFieldAccess_NotSuggestedOnStatic() + => TestMissingAsyncWithOption( """ class C { @@ -307,13 +288,11 @@ void M() } } """, -CodeStyleOptions2.QualifyFieldAccess); - } + CodeStyleOptions2.QualifyFieldAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28509")] - public async Task QualifyFieldAccess_NotSuggestedOnLocalVarInObjectInitializer() - { - await TestMissingAsyncWithOption( + public Task QualifyFieldAccess_NotSuggestedOnLocalVarInObjectInitializer() + => TestMissingAsyncWithOption( """ class C { @@ -324,13 +303,11 @@ void M() } } """, -CodeStyleOptions2.QualifyFieldAccess); - } + CodeStyleOptions2.QualifyFieldAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28509")] - public async Task QualifyFieldAccess_NotSuggestedOnLocalVarInCollectionInitializer() - { - await TestMissingAsyncWithOption( + public Task QualifyFieldAccess_NotSuggestedOnLocalVarInCollectionInitializer() + => TestMissingAsyncWithOption( """ class C { @@ -341,13 +318,11 @@ void M() } } """, -CodeStyleOptions2.QualifyFieldAccess); - } + CodeStyleOptions2.QualifyFieldAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28091")] - public async Task QualifyFieldAccess_NotSuggestedOnLocalVarInDictionaryInitializer() - { - await TestMissingAsyncWithOption( + public Task QualifyFieldAccess_NotSuggestedOnLocalVarInDictionaryInitializer() + => TestMissingAsyncWithOption( """ class C { @@ -358,13 +333,11 @@ void M() } } """, -CodeStyleOptions2.QualifyFieldAccess); - } + CodeStyleOptions2.QualifyFieldAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40242")] - public async Task QualifyFieldAccess_Subpattern1() - { - await TestMissingAsyncWithOption( + public Task QualifyFieldAccess_Subpattern1() + => TestMissingAsyncWithOption( """ class Class { @@ -378,13 +351,11 @@ void M(Class c) } } """, -CodeStyleOptions2.QualifyFieldAccess); - } + CodeStyleOptions2.QualifyFieldAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40242")] - public async Task QualifyFieldAccess_Subpattern2() - { - await TestMissingAsyncWithOption( + public Task QualifyFieldAccess_Subpattern2() + => TestMissingAsyncWithOption( """ class Class { @@ -400,13 +371,11 @@ void M(Class c) } } """, -CodeStyleOptions2.QualifyFieldAccess); - } + CodeStyleOptions2.QualifyFieldAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40242")] - public async Task QualifyFieldAccess_Subpattern3() - { - await TestMissingAsyncWithOption( + public Task QualifyFieldAccess_Subpattern3() + => TestMissingAsyncWithOption( """ class Class { @@ -422,13 +391,11 @@ void M(Class c) } } """, -CodeStyleOptions2.QualifyFieldAccess); - } + CodeStyleOptions2.QualifyFieldAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyPropertyAccess_LHS() - { - await TestAsyncWithOption( + public Task QualifyPropertyAccess_LHS() + => TestAsyncWithOption( """ class Class { @@ -451,13 +418,11 @@ void M() } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyPropertyAccess_RHS() - { - await TestAsyncWithOption( + public Task QualifyPropertyAccess_RHS() + => TestAsyncWithOption( """ class Class { @@ -480,13 +445,11 @@ void M() } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40242")] - public async Task QualifyPropertyAccess_PropertySubpattern1() - { - await TestMissingAsyncWithOption( + public Task QualifyPropertyAccess_PropertySubpattern1() + => TestMissingAsyncWithOption( """ class Class { @@ -500,13 +463,11 @@ void M(Class c) } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40242")] - public async Task QualifyPropertyAccess_PropertySubpattern2() - { - await TestMissingAsyncWithOption( + public Task QualifyPropertyAccess_PropertySubpattern2() + => TestMissingAsyncWithOption( """ class Class { @@ -522,13 +483,11 @@ void M(Class c) } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40242")] - public async Task QualifyPropertyAccess_PropertySubpattern3() - { - await TestMissingAsyncWithOption( + public Task QualifyPropertyAccess_PropertySubpattern3() + => TestMissingAsyncWithOption( """ class Class { @@ -544,14 +503,11 @@ void M(Class c) } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40242")] - public async Task QualifyPropertyAccess_PropertySubpattern4() - { - // it's ok that we qualify here because it's not a legal pattern (because it is not const). - await TestAsyncWithOption( + public Task QualifyPropertyAccess_PropertySubpattern4() + => TestAsyncWithOption( """ class Class { @@ -582,13 +538,11 @@ void M(Class c) } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40242")] - public async Task QualifyPropertyAccess_FieldSubpattern1() - { - await TestMissingAsyncWithOption( + public Task QualifyPropertyAccess_FieldSubpattern1() + => TestMissingAsyncWithOption( """ class Class { @@ -602,13 +556,11 @@ void M(Class c) } } """, -CodeStyleOptions2.QualifyFieldAccess); - } + CodeStyleOptions2.QualifyFieldAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40242")] - public async Task QualifyPropertyAccess_FieldSubpattern2() - { - await TestMissingAsyncWithOption( + public Task QualifyPropertyAccess_FieldSubpattern2() + => TestMissingAsyncWithOption( """ class Class { @@ -624,13 +576,11 @@ void M(Class c) } } """, -CodeStyleOptions2.QualifyFieldAccess); - } + CodeStyleOptions2.QualifyFieldAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40242")] - public async Task QualifyPropertyAccess_FieldSubpattern3() - { - await TestMissingAsyncWithOption( + public Task QualifyPropertyAccess_FieldSubpattern3() + => TestMissingAsyncWithOption( """ class Class { @@ -646,14 +596,11 @@ void M(Class c) } } """, -CodeStyleOptions2.QualifyFieldAccess); - } + CodeStyleOptions2.QualifyFieldAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40242")] - public async Task QualifyPropertyAccess_FieldSubpattern4() - { - // it's ok that we qualify here because it's not a legal pattern (because it is not const). - await TestAsyncWithOption( + public Task QualifyPropertyAccess_FieldSubpattern4() + => TestAsyncWithOption( """ class Class { @@ -684,13 +631,11 @@ void M(Class c) } } """, -CodeStyleOptions2.QualifyFieldAccess); - } + CodeStyleOptions2.QualifyFieldAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyPropertyAccess_MethodArgument() - { - await TestAsyncWithOption( + public Task QualifyPropertyAccess_MethodArgument() + => TestAsyncWithOption( """ class Class { @@ -713,13 +658,11 @@ void M(int ii) } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyPropertyAccess_ChainedAccess() - { - await TestAsyncWithOption( + public Task QualifyPropertyAccess_ChainedAccess() + => TestAsyncWithOption( """ class Class { @@ -742,13 +685,11 @@ void M() } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyPropertyAccess_ConditionalAccess() - { - await TestAsyncWithOption( + public Task QualifyPropertyAccess_ConditionalAccess() + => TestAsyncWithOption( """ class Class { @@ -771,13 +712,11 @@ void M() } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyPropertyAccess_OnBase() - { - await TestAsyncWithOption( + public Task QualifyPropertyAccess_OnBase() + => TestAsyncWithOption( """ class Base { @@ -806,13 +745,11 @@ void M() } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyPropertyAccess_NotSuggestedOnInstance() - { - await TestMissingAsyncWithOption( + public Task QualifyPropertyAccess_NotSuggestedOnInstance() + => TestMissingAsyncWithOption( """ class Class { @@ -824,13 +761,11 @@ void M(Class c) } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyPropertyAccess_NotSuggestedOnStatic() - { - await TestMissingAsyncWithOption( + public Task QualifyPropertyAccess_NotSuggestedOnStatic() + => TestMissingAsyncWithOption( """ class C { @@ -842,13 +777,11 @@ void M() } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyMethodAccess_VoidCallWithArguments() - { - await TestAsyncWithOption( + public Task QualifyMethodAccess_VoidCallWithArguments() + => TestAsyncWithOption( """ class Class { @@ -867,13 +800,11 @@ void M(int i) } } """, -CodeStyleOptions2.QualifyMethodAccess); - } + CodeStyleOptions2.QualifyMethodAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyMethodAccess_AsReturn() - { - await TestAsyncWithOption( + public Task QualifyMethodAccess_AsReturn() + => TestAsyncWithOption( """ class Class { @@ -890,13 +821,11 @@ int M() return this.M(); } """, -CodeStyleOptions2.QualifyMethodAccess); - } + CodeStyleOptions2.QualifyMethodAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyMethodAccess_ChainedAccess() - { - await TestAsyncWithOption( + public Task QualifyMethodAccess_ChainedAccess() + => TestAsyncWithOption( """ class Class { @@ -913,13 +842,11 @@ string M() var s = this.M().ToString(); } """, -CodeStyleOptions2.QualifyMethodAccess); - } + CodeStyleOptions2.QualifyMethodAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyMethodAccess_ConditionalAccess() - { - await TestAsyncWithOption( + public Task QualifyMethodAccess_ConditionalAccess() + => TestAsyncWithOption( """ class Class { @@ -936,13 +863,11 @@ string M() return this.M()?.ToString(); } """, -CodeStyleOptions2.QualifyMethodAccess); - } + CodeStyleOptions2.QualifyMethodAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyMethodAccess_EventSubscription1() - { - await TestAsyncWithOption( + public Task QualifyMethodAccess_EventSubscription1() + => TestAsyncWithOption( """ using System; @@ -969,13 +894,11 @@ void Handler(object sender, EventArgs args) } } """, -CodeStyleOptions2.QualifyMethodAccess); - } + CodeStyleOptions2.QualifyMethodAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyMethodAccess_EventSubscription2() - { - await TestAsyncWithOption( + public Task QualifyMethodAccess_EventSubscription2() + => TestAsyncWithOption( """ using System; @@ -1002,13 +925,11 @@ void Handler(object sender, EventArgs args) } } """, -CodeStyleOptions2.QualifyMethodAccess); - } + CodeStyleOptions2.QualifyMethodAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyMethodAccess_OnBase() - { - await TestAsyncWithOption( + public Task QualifyMethodAccess_OnBase() + => TestAsyncWithOption( """ class Base { @@ -1041,13 +962,11 @@ void M() } } """, -CodeStyleOptions2.QualifyMethodAccess); - } + CodeStyleOptions2.QualifyMethodAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyMethodAccess_NotSuggestedOnInstance() - { - await TestMissingAsyncWithOption( + public Task QualifyMethodAccess_NotSuggestedOnInstance() + => TestMissingAsyncWithOption( """ class Class { @@ -1057,13 +976,11 @@ void M(Class c) } } """, -CodeStyleOptions2.QualifyMethodAccess); - } + CodeStyleOptions2.QualifyMethodAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyMethodAccess_NotSuggestedOnStatic() - { - await TestMissingAsyncWithOption( + public Task QualifyMethodAccess_NotSuggestedOnStatic() + => TestMissingAsyncWithOption( """ class C { @@ -1077,13 +994,11 @@ void M() } } """, -CodeStyleOptions2.QualifyMethodAccess); - } + CodeStyleOptions2.QualifyMethodAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28509")] - public async Task QualifyMethodAccess_NotSuggestedOnObjectInitializer() - { - await TestMissingAsyncWithOption( + public Task QualifyMethodAccess_NotSuggestedOnObjectInitializer() + => TestMissingAsyncWithOption( """ class C { @@ -1094,13 +1009,11 @@ void M() } } """, -CodeStyleOptions2.QualifyMethodAccess); - } + CodeStyleOptions2.QualifyMethodAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28509")] - public async Task QualifyLocalMethodAccess_NotSuggestedOnObjectInitializer() - { - await TestMissingAsyncWithOption( + public Task QualifyLocalMethodAccess_NotSuggestedOnObjectInitializer() + => TestMissingAsyncWithOption( """ class C { @@ -1111,13 +1024,11 @@ void M() } } """, -CodeStyleOptions2.QualifyMethodAccess); - } + CodeStyleOptions2.QualifyMethodAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28509")] - public async Task QualifyMethodAccess_NotSuggestedOnCollectionInitializer() - { - await TestMissingAsyncWithOption( + public Task QualifyMethodAccess_NotSuggestedOnCollectionInitializer() + => TestMissingAsyncWithOption( """ class C { @@ -1128,13 +1039,11 @@ void M() } } """, -CodeStyleOptions2.QualifyMethodAccess); - } + CodeStyleOptions2.QualifyMethodAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28509")] - public async Task QualifyLocalMethodAccess_NotSuggestedOnCollectionInitializer() - { - await TestMissingAsyncWithOption( + public Task QualifyLocalMethodAccess_NotSuggestedOnCollectionInitializer() + => TestMissingAsyncWithOption( """ class C { @@ -1145,13 +1054,11 @@ void M() } } """, -CodeStyleOptions2.QualifyMethodAccess); - } + CodeStyleOptions2.QualifyMethodAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28509")] - public async Task QualifyLocalMethodAccess_NotSuggestedInMethodCall() - { - await TestMissingAsyncWithOption( + public Task QualifyLocalMethodAccess_NotSuggestedInMethodCall() + => TestMissingAsyncWithOption( """ class C { @@ -1162,13 +1069,11 @@ void M() } } """, -CodeStyleOptions2.QualifyMethodAccess); - } + CodeStyleOptions2.QualifyMethodAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38043")] - public async Task QualifyLocalMethodAccess_NotSuggestedInNestedMethodCall() - { - await TestMissingAsyncWithOption( + public Task QualifyLocalMethodAccess_NotSuggestedInNestedMethodCall() + => TestMissingAsyncWithOption( """ using System; @@ -1185,13 +1090,11 @@ void Method2(Func LocalFunction) } } """, -CodeStyleOptions2.QualifyMethodAccess); - } + CodeStyleOptions2.QualifyMethodAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38043")] - public async Task QualifyLocalMethodAccess_NotSuggestedInCollectionInitializer() - { - await TestMissingAsyncWithOption( + public Task QualifyLocalMethodAccess_NotSuggestedInCollectionInitializer() + => TestMissingAsyncWithOption( """ using System; using System.Collections.Generic; @@ -1205,13 +1108,11 @@ void Method() } } """, -CodeStyleOptions2.QualifyMethodAccess); - } + CodeStyleOptions2.QualifyMethodAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38043")] - public async Task QualifyLocalMethodAccess_NotSuggestedInObjectMethodInvocation() - { - await TestMissingAsyncWithOption( + public Task QualifyLocalMethodAccess_NotSuggestedInObjectMethodInvocation() + => TestMissingAsyncWithOption( """ using System; @@ -1224,14 +1125,12 @@ void Method() } } """, -CodeStyleOptions2.QualifyMethodAccess); - } + CodeStyleOptions2.QualifyMethodAccess); [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7587")] [WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyEventAccess_EventSubscription() - { - await TestAsyncWithOption( + public Task QualifyEventAccess_EventSubscription() + => TestAsyncWithOption( """ using System; @@ -1258,14 +1157,12 @@ void Handler(object sender, EventArgs args) } } """, -CodeStyleOptions2.QualifyEventAccess); - } + CodeStyleOptions2.QualifyEventAccess); [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7587")] [WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyEventAccessAsProperty_EventSubscription() - { - await TestAsyncWithOption( + public Task QualifyEventAccessAsProperty_EventSubscription() + => TestAsyncWithOption( """ using System; @@ -1310,14 +1207,12 @@ void Handler(object sender, EventArgs args) } } """, -CodeStyleOptions2.QualifyEventAccess); - } + CodeStyleOptions2.QualifyEventAccess); [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7587")] [WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyEventAccess_InvokeEvent1() - { - await TestAsyncWithOption( + public Task QualifyEventAccess_InvokeEvent1() + => TestAsyncWithOption( """ using System; @@ -1344,14 +1239,12 @@ void OnSomeEvent() } } """, -CodeStyleOptions2.QualifyEventAccess); - } + CodeStyleOptions2.QualifyEventAccess); [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7587")] [WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyEventAccess_InvokeEvent2() - { - await TestAsyncWithOption( + public Task QualifyEventAccess_InvokeEvent2() + => TestAsyncWithOption( """ using System; @@ -1378,14 +1271,12 @@ void OnSomeEvent() } } """, -CodeStyleOptions2.QualifyEventAccess); - } + CodeStyleOptions2.QualifyEventAccess); [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7587")] [WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyEventAccess_InvokeEvent3() - { - await TestAsyncWithOption( + public Task QualifyEventAccess_InvokeEvent3() + => TestAsyncWithOption( """ using System; @@ -1412,14 +1303,12 @@ void OnSomeEvent() } } """, -CodeStyleOptions2.QualifyEventAccess); - } + CodeStyleOptions2.QualifyEventAccess); [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7587")] [WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyEventAccess_OnBase() - { - await TestAsyncWithOption( + public Task QualifyEventAccess_OnBase() + => TestAsyncWithOption( """ using System; @@ -1452,13 +1341,11 @@ void Handler(object sender, EventArgs args) } } """, -CodeStyleOptions2.QualifyEventAccess); - } + CodeStyleOptions2.QualifyEventAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyEventAccess_NotSuggestedOnInstance() - { - await TestMissingAsyncWithOption( + public Task QualifyEventAccess_NotSuggestedOnInstance() + => TestMissingAsyncWithOption( """ using System; @@ -1476,13 +1363,11 @@ void Handler(object sender, EventArgs args) } } """, -CodeStyleOptions2.QualifyEventAccess); - } + CodeStyleOptions2.QualifyEventAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7065")] - public async Task QualifyEventAccess_NotSuggestedOnStatic() - { - await TestMissingAsyncWithOption( + public Task QualifyEventAccess_NotSuggestedOnStatic() + => TestMissingAsyncWithOption( """ using System; @@ -1496,13 +1381,11 @@ void Handler(object sender, EventArgs args) [|e|] += Handler; } } """, -CodeStyleOptions2.QualifyEventAccess); - } + CodeStyleOptions2.QualifyEventAccess); [Fact] - public async Task QualifyMemberAccessOnNotificationOptionSilent() - { - await TestAsyncWithOptionAndNotificationOption( + public Task QualifyMemberAccessOnNotificationOptionSilent() + => TestAsyncWithOptionAndNotificationOption( """ class Class { @@ -1525,13 +1408,11 @@ void M() } } """, -CodeStyleOptions2.QualifyPropertyAccess, NotificationOption2.Silent); - } + CodeStyleOptions2.QualifyPropertyAccess, NotificationOption2.Silent); [Fact] - public async Task QualifyMemberAccessOnNotificationOptionInfo() - { - await TestAsyncWithOptionAndNotificationOption( + public Task QualifyMemberAccessOnNotificationOptionInfo() + => TestAsyncWithOptionAndNotificationOption( """ class Class { @@ -1554,13 +1435,11 @@ void M() } } """, -CodeStyleOptions2.QualifyPropertyAccess, NotificationOption2.Suggestion); - } + CodeStyleOptions2.QualifyPropertyAccess, NotificationOption2.Suggestion); [Fact] - public async Task QualifyMemberAccessOnNotificationOptionWarning() - { - await TestAsyncWithOptionAndNotificationOption( + public Task QualifyMemberAccessOnNotificationOptionWarning() + => TestAsyncWithOptionAndNotificationOption( """ class Class { @@ -1583,13 +1462,11 @@ void M() } } """, -CodeStyleOptions2.QualifyPropertyAccess, NotificationOption2.Warning); - } + CodeStyleOptions2.QualifyPropertyAccess, NotificationOption2.Warning); [Fact] - public async Task QualifyMemberAccessOnNotificationOptionError() - { - await TestAsyncWithOptionAndNotificationOption( + public Task QualifyMemberAccessOnNotificationOptionError() + => TestAsyncWithOptionAndNotificationOption( """ class Class { @@ -1612,14 +1489,12 @@ void M() } } """, -CodeStyleOptions2.QualifyPropertyAccess, NotificationOption2.Error); - } + CodeStyleOptions2.QualifyPropertyAccess, NotificationOption2.Error); [Fact(Skip = "https://github.com/dotnet/roslyn/issues/18839")] [WorkItem("https://github.com/dotnet/roslyn/issues/15325")] - public async Task QualifyInstanceMethodInDelegateCreation() - { - await TestAsyncWithOption( + public Task QualifyInstanceMethodInDelegateCreation() + => TestAsyncWithOption( """ using System; @@ -1648,13 +1523,11 @@ void Error() } } """, -CodeStyleOptions2.QualifyMethodAccess); - } + CodeStyleOptions2.QualifyMethodAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15325")] - public async Task DoNotQualifyStaticMethodInDelegateCreation() - { - await TestMissingAsyncWithOption( + public Task DoNotQualifyStaticMethodInDelegateCreation() + => TestMissingAsyncWithOption( """ using System; @@ -1669,13 +1542,11 @@ void Error() } } """, -CodeStyleOptions2.QualifyMethodAccess); - } + CodeStyleOptions2.QualifyMethodAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17711")] - public async Task DoNotReportToQualify_IfBaseQualificationOnField() - { - await TestMissingAsyncWithOption( + public Task DoNotReportToQualify_IfBaseQualificationOnField() + => TestMissingAsyncWithOption( """ class Base { @@ -1686,13 +1557,11 @@ class Derived : Base void M() { [|base.field|] = 0; } } """, -CodeStyleOptions2.QualifyFieldAccess); - } + CodeStyleOptions2.QualifyFieldAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17711")] - public async Task DoNotReportToQualify_IfBaseQualificationOnProperty() - { - await TestMissingAsyncWithOption( + public Task DoNotReportToQualify_IfBaseQualificationOnProperty() + => TestMissingAsyncWithOption( """ class Base { @@ -1703,13 +1572,11 @@ class Derived : Base protected override int Property { get { return [|base.Property|]; } } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17711")] - public async Task DoNotReportToQualify_IfBaseQualificationOnMethod() - { - await TestMissingAsyncWithOption( + public Task DoNotReportToQualify_IfBaseQualificationOnMethod() + => TestMissingAsyncWithOption( """ class Base { @@ -1720,13 +1587,11 @@ class Derived : Base protected override void M() { [|base.M()|]; } } """, -CodeStyleOptions2.QualifyMethodAccess); - } + CodeStyleOptions2.QualifyMethodAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17711")] - public async Task DoNotReportToQualify_IfBaseQualificationOnEvent() - { - await TestMissingAsyncWithOption( + public Task DoNotReportToQualify_IfBaseQualificationOnEvent() + => TestMissingAsyncWithOption( """ class Base { @@ -1741,13 +1606,11 @@ protected override event EventHandler Event } } """, -CodeStyleOptions2.QualifyEventAccess); - } + CodeStyleOptions2.QualifyEventAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21519")] - public async Task DoNotReportToQualify_IfInStaticContext1() - { - await TestMissingAsyncWithOption( + public Task DoNotReportToQualify_IfInStaticContext1() + => TestMissingAsyncWithOption( """ class Program { @@ -1755,13 +1618,11 @@ class Program public static string Bar = nameof([|Foo|]); } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21519")] - public async Task DoNotReportToQualify_IfInStaticContext2() - { - await TestMissingAsyncWithOption( + public Task DoNotReportToQualify_IfInStaticContext2() + => TestMissingAsyncWithOption( """ class Program { @@ -1769,13 +1630,11 @@ class Program public string Bar = nameof([|Foo|]); } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21519")] - public async Task DoNotReportToQualify_IfInStaticContext3() - { - await TestMissingAsyncWithOption( + public Task DoNotReportToQualify_IfInStaticContext3() + => TestMissingAsyncWithOption( """ class Program { @@ -1786,13 +1645,11 @@ static void Main(string[] args) } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21519")] - public async Task DoNotReportToQualify_IfInStaticContext4() - { - await TestMissingAsyncWithOption( + public Task DoNotReportToQualify_IfInStaticContext4() + => TestMissingAsyncWithOption( """ class Program { @@ -1803,13 +1660,11 @@ static void Main(string[] args) } } """, -CodeStyleOptions2.QualifyFieldAccess); - } + CodeStyleOptions2.QualifyFieldAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21519")] - public async Task DoNotReportToQualify_IfInStaticContext5() - { - await TestMissingAsyncWithOption( + public Task DoNotReportToQualify_IfInStaticContext5() + => TestMissingAsyncWithOption( """ class Program { @@ -1822,13 +1677,11 @@ static Program() } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21519")] - public async Task DoNotReportToQualify_IfInStaticContext6() - { - await TestMissingAsyncWithOption( + public Task DoNotReportToQualify_IfInStaticContext6() + => TestMissingAsyncWithOption( """ public class Foo { @@ -1837,13 +1690,11 @@ public class Foo private string Field = nameof([|Bar|]); } """, -CodeStyleOptions2.QualifyEventAccess); - } + CodeStyleOptions2.QualifyEventAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32093")] - public async Task DoNotReportToQualify_IfInBaseConstructor() - { - await TestMissingAsyncWithOption( + public Task DoNotReportToQualify_IfInBaseConstructor() + => TestMissingAsyncWithOption( """ public class Base { @@ -1858,12 +1709,10 @@ public Derived() } """, CodeStyleOptions2.QualifyFieldAccess); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21519")] - public async Task QualifyPropertyAccess_InAccessorExpressionBody() - { - await TestAsyncWithOption( + public Task QualifyPropertyAccess_InAccessorExpressionBody() + => TestAsyncWithOption( """ public class C { @@ -1878,13 +1727,11 @@ public class C public string Bar { get => this.Foo; } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21519")] - public async Task QualifyPropertyAccess_InAccessorWithBodyAndExpressionBody1() - { - await TestAsyncWithOption( + public Task QualifyPropertyAccess_InAccessorWithBodyAndExpressionBody1() + => TestAsyncWithOption( """ public class C { @@ -1899,13 +1746,11 @@ public class C public string Bar { get { return this.Foo; } => Foo; } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21519")] - public async Task QualifyPropertyAccess_InAccessorWithBodyAndExpressionBody2() - { - await TestAsyncWithOption( + public Task QualifyPropertyAccess_InAccessorWithBodyAndExpressionBody2() + => TestAsyncWithOption( """ public class C { @@ -1920,13 +1765,11 @@ public class C public string Bar { get { return Foo; } => this.Foo; } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28509")] - public async Task QualifyPropertyAccess_InObjectInitializer() - { - await TestAsyncWithOption( + public Task QualifyPropertyAccess_InObjectInitializer() + => TestAsyncWithOption( """ class C { @@ -1947,13 +1790,11 @@ void M() } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28509")] - public async Task QualifyPropertyAccess_InCollectionInitializer() - { - await TestAsyncWithOption( + public Task QualifyPropertyAccess_InCollectionInitializer() + => TestAsyncWithOption( """ class C { @@ -1974,13 +1815,11 @@ void M() } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22776")] - public async Task DoNotReportToQualify_InObjectInitializer1() - { - await TestMissingAsyncWithOption( + public Task DoNotReportToQualify_InObjectInitializer1() + => TestMissingAsyncWithOption( """ public class C { @@ -1994,13 +1833,11 @@ public void Bar() } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22776")] - public async Task DoNotReportToQualify_InObjectInitializer2() - { - await TestMissingAsyncWithOption( + public Task DoNotReportToQualify_InObjectInitializer2() + => TestMissingAsyncWithOption( """ public class C { @@ -2014,14 +1851,12 @@ public void Bar() } } """, -CodeStyleOptions2.QualifyFieldAccess); - } + CodeStyleOptions2.QualifyFieldAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22776")] [WorkItem("https://github.com/dotnet/roslyn/issues/64374")] - public async Task DoReportToQualify_InObjectInitializer2() - { - await TestAsyncWithOption( + public Task DoReportToQualify_InObjectInitializer2() + => TestAsyncWithOption( """ public class C { @@ -2049,12 +1884,10 @@ public void Bar() } """, CodeStyleOptions2.QualifyFieldAccess); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26893")] - public async Task DoNotReportToQualify_IfInAttribute1() - { - await TestMissingAsyncWithOption( + public Task DoNotReportToQualify_IfInAttribute1() + => TestMissingAsyncWithOption( """ using System; @@ -2069,13 +1902,11 @@ class Program int Goo { get; set; } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26893")] - public async Task DoNotReportToQualify_IfInAttribute2() - { - await TestMissingAsyncWithOption( + public Task DoNotReportToQualify_IfInAttribute2() + => TestMissingAsyncWithOption( """ using System; @@ -2090,13 +1921,11 @@ class Program int Goo { get; set; } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26893")] - public async Task DoNotReportToQualify_IfInAttribute3() - { - await TestMissingAsyncWithOption( + public Task DoNotReportToQualify_IfInAttribute3() + => TestMissingAsyncWithOption( """ using System; @@ -2112,13 +1941,11 @@ class Program public int Goo { get; set; } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26893")] - public async Task DoNotReportToQualify_IfInAttribute4() - { - await TestMissingAsyncWithOption( + public Task DoNotReportToQualify_IfInAttribute4() + => TestMissingAsyncWithOption( """ using System; @@ -2132,13 +1959,11 @@ class Program int Goo { [My(nameof([|Goo|]))]get; set; } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26893")] - public async Task DoNotReportToQualify_IfInAttribute5() - { - await TestMissingAsyncWithOption( + public Task DoNotReportToQualify_IfInAttribute5() + => TestMissingAsyncWithOption( """ using System; @@ -2153,6 +1978,5 @@ class Program void M([My(nameof([|Goo|]))]int i) { } } """, -CodeStyleOptions2.QualifyPropertyAccess); - } + CodeStyleOptions2.QualifyPropertyAccess); } diff --git a/src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests_FixAllTests.cs b/src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests_FixAllTests.cs index 18d60cdbc7723..832d336ecb98d 100644 --- a/src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests_FixAllTests.cs +++ b/src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests_FixAllTests.cs @@ -16,9 +16,9 @@ public sealed partial class QualifyMemberAccessTests [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInSolution_QualifyMemberAccess() - { - var input = """ + public Task TestFixAllInSolution_QualifyMemberAccess() + => TestInRegularAndScriptAsync( + initialMarkup: """ @@ -53,9 +53,8 @@ void N() - """; - - var expected = """ + """, + expectedMarkup: """ @@ -90,11 +89,6 @@ void N() - """; - - await TestInRegularAndScriptAsync( - initialMarkup: input, - expectedMarkup: expected, + """, options: Option(CodeStyleOptions2.QualifyPropertyAccess, true, NotificationOption2.Suggestion)); - } } diff --git a/src/Analyzers/CSharp/Tests/RemoveAsyncModifier/RemoveAsyncModifierTests.cs b/src/Analyzers/CSharp/Tests/RemoveAsyncModifier/RemoveAsyncModifierTests.cs index 99fad10dcca2d..59c4359e89360 100644 --- a/src/Analyzers/CSharp/Tests/RemoveAsyncModifier/RemoveAsyncModifierTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveAsyncModifier/RemoveAsyncModifierTests.cs @@ -21,9 +21,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveAsyncModifier; public sealed class RemoveAsyncModifierTests { [Fact] - public async Task Method_Task_MultipleAndNested() - { - await VerifyCS.VerifyCodeFixAsync( + public Task Method_Task_MultipleAndNested() + => VerifyCS.VerifyCodeFixAsync( """ using System; using System.Threading.Tasks; @@ -136,12 +135,10 @@ Task Nurk() } } """); - } [Fact] - public async Task Method_Task_EmptyBlockBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task Method_Task_EmptyBlockBody() + => VerifyCS.VerifyCodeFixAsync( """ using System.Threading.Tasks; @@ -161,12 +158,10 @@ Task Goo() } } """); - } [Fact] - public async Task Method_Task_BlockBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task Method_Task_BlockBody() + => VerifyCS.VerifyCodeFixAsync( """ using System.Threading.Tasks; @@ -197,12 +192,13 @@ Task Goo() } } """); - } [Fact] - public async Task Method_ValueTask_BlockBody() - { - var source = """ + public Task Method_ValueTask_BlockBody() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21, + TestCode = """ using System.Threading.Tasks; class C @@ -215,9 +211,8 @@ class C } } } - """; - - var expected = """ + """, + FixedCode = """ using System.Threading.Tasks; class C @@ -232,20 +227,15 @@ ValueTask Goo() return new ValueTask(); } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21, - TestCode = source, - FixedCode = expected, + """, }.RunAsync(); - } [Fact] - public async Task Method_ValueTaskOfT_BlockBody() - { - var source = """ + public Task Method_ValueTaskOfT_BlockBody() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21, + TestCode = """ using System.Threading.Tasks; class C @@ -260,8 +250,8 @@ class C return 3; } } - """; - var expected = """ + """, + FixedCode = """ using System.Threading.Tasks; class C @@ -276,29 +266,23 @@ ValueTask Goo() return new ValueTask(3); } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21, - TestCode = source, - FixedCode = expected, + """, }.RunAsync(); - } [Fact] - public async Task Method_ValueTask_ExpressionBody() - { - var source = """ + public Task Method_ValueTask_ExpressionBody() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21, + TestCode = """ using System.Threading.Tasks; class C { async ValueTask {|CS1998:Goo|}() => System.Console.WriteLine(1); } - """; - - var expected = """ + """, + FixedCode = """ using System.Threading.Tasks; class C @@ -309,49 +293,35 @@ ValueTask Goo() return new ValueTask(); } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21, - TestCode = source, - FixedCode = expected, + """, }.RunAsync(); - } [Fact] - public async Task Method_ValueTaskOfT_ExpressionBody() - { - var source = """ + public Task Method_ValueTaskOfT_ExpressionBody() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21, + TestCode = """ using System.Threading.Tasks; class C { async ValueTask {|CS1998:Goo|}() => 3; } - """; - - var expected = """ + """, + FixedCode = """ using System.Threading.Tasks; class C { ValueTask Goo() => new ValueTask(3); } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21, - TestCode = source, - FixedCode = expected, + """, }.RunAsync(); - } [Fact] - public async Task Method_Task_BlockBody_Throws() - { - await VerifyCS.VerifyCodeFixAsync( + public Task Method_Task_BlockBody_Throws() + => VerifyCS.VerifyCodeFixAsync( """ using System.Threading.Tasks; @@ -384,12 +354,10 @@ Task Goo() } } """); - } [Fact] - public async Task Method_Task_BlockBody_WithLocalFunction() - { - await VerifyCS.VerifyCodeFixAsync( + public Task Method_Task_BlockBody_WithLocalFunction() + => VerifyCS.VerifyCodeFixAsync( """ using System.Threading.Tasks; @@ -430,12 +398,10 @@ long GetTicks() } } """); - } [Fact] - public async Task Method_Task_BlockBody_WithLambda() - { - await VerifyCS.VerifyCodeFixAsync( + public Task Method_Task_BlockBody_WithLambda() + => VerifyCS.VerifyCodeFixAsync( """ using System.Threading.Tasks; @@ -475,12 +441,10 @@ Task Goo() } } """); - } [Fact] - public async Task Method_TaskOfT_BlockBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task Method_TaskOfT_BlockBody() + => VerifyCS.VerifyCodeFixAsync( """ using System.Threading.Tasks; @@ -513,12 +477,10 @@ Task Goo() } } """); - } [Fact] - public async Task Method_TaskOfT_ExpressionBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task Method_TaskOfT_ExpressionBody() + => VerifyCS.VerifyCodeFixAsync( """ using System.Threading.Tasks; @@ -535,12 +497,10 @@ class C Task Goo() => Task.FromResult(2); } """); - } [Fact] - public async Task Method_Task_ExpressionBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task Method_Task_ExpressionBody() + => VerifyCS.VerifyCodeFixAsync( """ using System; using System.Threading.Tasks; @@ -563,12 +523,10 @@ Task Goo() } } """); - } [Fact] - public async Task LocalFunction_Task_BlockBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task LocalFunction_Task_BlockBody() + => VerifyCS.VerifyCodeFixAsync( """ using System.Threading.Tasks; @@ -605,12 +563,10 @@ Task Goo() } } """); - } [Fact] - public async Task LocalFunction_Task_ExpressionBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task LocalFunction_Task_ExpressionBody() + => VerifyCS.VerifyCodeFixAsync( """ using System; using System.Threading.Tasks; @@ -635,12 +591,10 @@ public void M1() } } """); - } [Fact] - public async Task LocalFunction_TaskOfT_BlockBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task LocalFunction_TaskOfT_BlockBody() + => VerifyCS.VerifyCodeFixAsync( """ using System.Threading.Tasks; @@ -669,12 +623,10 @@ Task Goo() } } """); - } [Fact] - public async Task LocalFunction_TaskOfT_ExpressionBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task LocalFunction_TaskOfT_ExpressionBody() + => VerifyCS.VerifyCodeFixAsync( """ using System.Threading.Tasks; @@ -697,12 +649,10 @@ public void M1() } } """); - } [Fact] - public async Task AnonymousFunction_Task_BlockBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task AnonymousFunction_Task_BlockBody() + => VerifyCS.VerifyCodeFixAsync( """ using System; using System.Threading.Tasks; @@ -740,12 +690,10 @@ public void M1() } } """); - } [Fact] - public async Task AnonymousFunction_TaskOfT_BlockBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task AnonymousFunction_TaskOfT_BlockBody() + => VerifyCS.VerifyCodeFixAsync( """ using System; using System.Threading.Tasks; @@ -776,12 +724,10 @@ public void M1() } } """); - } [Fact] - public async Task SimpleLambda_TaskOfT_ExpressionBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task SimpleLambda_TaskOfT_ExpressionBody() + => VerifyCS.VerifyCodeFixAsync( """ using System; using System.Threading.Tasks; @@ -806,12 +752,10 @@ public void M1() } } """); - } [Fact] - public async Task SimpleLambda_TaskOfT_BlockBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task SimpleLambda_TaskOfT_BlockBody() + => VerifyCS.VerifyCodeFixAsync( """ using System; using System.Threading.Tasks; @@ -841,12 +785,10 @@ public void M1() } } """); - } [Fact] - public async Task SimpleLambda_Task_ExpressionBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task SimpleLambda_Task_ExpressionBody() + => VerifyCS.VerifyCodeFixAsync( """ using System; using System.Threading.Tasks; @@ -871,12 +813,10 @@ public void M1() } } """); - } [Fact] - public async Task SimpleLambda_Task_BlockBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task SimpleLambda_Task_BlockBody() + => VerifyCS.VerifyCodeFixAsync( """ using System; using System.Threading.Tasks; @@ -915,12 +855,10 @@ public void M1() } } """); - } [Fact] - public async Task ParenthesizedLambda_TaskOfT_ExpressionBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task ParenthesizedLambda_TaskOfT_ExpressionBody() + => VerifyCS.VerifyCodeFixAsync( """ using System; using System.Threading.Tasks; @@ -945,12 +883,10 @@ public void M1() } } """); - } [Fact] - public async Task ParenthesizedLambda_TaskOfT_BlockBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task ParenthesizedLambda_TaskOfT_BlockBody() + => VerifyCS.VerifyCodeFixAsync( """ using System; using System.Threading.Tasks; @@ -980,12 +916,10 @@ public void M1() } } """); - } [Fact] - public async Task ParenthesizedLambda_Task_ExpressionBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task ParenthesizedLambda_Task_ExpressionBody() + => VerifyCS.VerifyCodeFixAsync( """ using System; using System.Threading.Tasks; @@ -1010,12 +944,10 @@ public void M1() } } """); - } [Fact] - public async Task ParenthesizedLambda_Task_BlockBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task ParenthesizedLambda_Task_BlockBody() + => VerifyCS.VerifyCodeFixAsync( """ using System; using System.Threading.Tasks; @@ -1054,12 +986,10 @@ public void M1() } } """); - } [Fact] - public async Task Method_Task_BlockBody_FullyQualified() - { - await VerifyCS.VerifyCodeFixAsync( + public Task Method_Task_BlockBody_FullyQualified() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -1086,12 +1016,10 @@ System.Threading.Tasks.Task Goo() } } """); - } [Fact] - public async Task Method_TaskOfT_BlockBody_FullyQualified() - { - await VerifyCS.VerifyCodeFixAsync( + public Task Method_TaskOfT_BlockBody_FullyQualified() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -1120,12 +1048,10 @@ System.Threading.Tasks.Task Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65536")] - public async Task Method_TaskOfT_BlockBody_QualifyTaskFromResultType() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task Method_TaskOfT_BlockBody_QualifyTaskFromResultType() + => VerifyCS.VerifyCodeFixAsync(""" using System.Threading.Tasks; using System.Collections.Generic; @@ -1148,7 +1074,6 @@ public Task> M() } } """); - } [Fact] public async Task IAsyncEnumerable_Missing() @@ -1265,9 +1190,8 @@ void M() }.RunAsync(); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65380")] - public async Task TestCloseBraceTrivia() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestCloseBraceTrivia() + => VerifyCS.VerifyCodeFixAsync( """ using System; using System.Threading.Tasks; @@ -1297,5 +1221,4 @@ public Task Goo() } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/RemoveConfusingSuppression/RemoveConfusingSuppressionTests.cs b/src/Analyzers/CSharp/Tests/RemoveConfusingSuppression/RemoveConfusingSuppressionTests.cs index 4d62af858cdf9..10e3a9ca5962b 100644 --- a/src/Analyzers/CSharp/Tests/RemoveConfusingSuppression/RemoveConfusingSuppressionTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveConfusingSuppression/RemoveConfusingSuppressionTests.cs @@ -16,9 +16,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Confusing; public sealed class RemoveConfusingSuppressionTests { [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44872")] - public async Task TestRemoveWithIsExpression1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestRemoveWithIsExpression1() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -41,12 +40,10 @@ void M(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44872")] - public async Task TestRemoveWithIsPattern1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestRemoveWithIsPattern1() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -69,12 +66,10 @@ void M(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44872")] - public async Task TestNegateWithIsExpression_CSharp8() - { - await new VerifyCS.Test + public Task TestNegateWithIsExpression_CSharp8() + => new VerifyCS.Test { TestCode = """ @@ -103,12 +98,10 @@ void M(object o) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp8 }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44872")] - public async Task TestNegateWithIsPattern_CSharp8() - { - await new VerifyCS.Test + public Task TestNegateWithIsPattern_CSharp8() + => new VerifyCS.Test { TestCode = """ @@ -137,12 +130,10 @@ void M(object o) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44872")] - public async Task TestNegateWithIsExpression_CSharp9() - { - await new VerifyCS.Test + public Task TestNegateWithIsExpression_CSharp9() + => new VerifyCS.Test { TestCode = """ @@ -171,12 +162,10 @@ void M(object o) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44872")] - public async Task TestNegateWithIsPattern_CSharp9() - { - await new VerifyCS.Test + public Task TestNegateWithIsPattern_CSharp9() + => new VerifyCS.Test { TestCode = """ @@ -210,12 +199,10 @@ void M(object o) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44872")] - public async Task TestRemoveWithIsExpression_FixAll1() - { - await new VerifyCS.Test + public Task TestRemoveWithIsExpression_FixAll1() + => new VerifyCS.Test { TestCode = """ @@ -250,12 +237,10 @@ void M(object o) NumberOfFixAllIterations = 1, CodeActionEquivalenceKey = CSharpRemoveConfusingSuppressionCodeFixProvider.RemoveOperator, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44872")] - public async Task TestNegateWithIsExpression_FixAll1() - { - await new VerifyCS.Test + public Task TestNegateWithIsExpression_FixAll1() + => new VerifyCS.Test { TestCode = """ @@ -291,12 +276,10 @@ void M(object o) CodeActionEquivalenceKey = CSharpRemoveConfusingSuppressionCodeFixProvider.NegateExpression, NumberOfFixAllIterations = 1, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44872")] - public async Task TestRemoveWithIsPatternExpression_FixAll1() - { - await new VerifyCS.Test + public Task TestRemoveWithIsPatternExpression_FixAll1() + => new VerifyCS.Test { TestCode = """ @@ -331,12 +314,10 @@ void M(object o) NumberOfFixAllIterations = 1, CodeActionEquivalenceKey = CSharpRemoveConfusingSuppressionCodeFixProvider.RemoveOperator, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44872")] - public async Task TestNegateWithIsPatternExpression_FixAll1() - { - await new VerifyCS.Test + public Task TestNegateWithIsPatternExpression_FixAll1() + => new VerifyCS.Test { TestCode = """ @@ -372,5 +353,4 @@ void M(object o) CodeActionIndex = 1, CodeActionEquivalenceKey = CSharpRemoveConfusingSuppressionCodeFixProvider.NegateExpression, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/RemoveInKeyword/RemoveInKeywordCodeFixProviderTests.cs b/src/Analyzers/CSharp/Tests/RemoveInKeyword/RemoveInKeywordCodeFixProviderTests.cs index d4ab823ad2f17..24a714216d804 100644 --- a/src/Analyzers/CSharp/Tests/RemoveInKeyword/RemoveInKeywordCodeFixProviderTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveInKeyword/RemoveInKeywordCodeFixProviderTests.cs @@ -25,9 +25,8 @@ internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProvide => (null, new RemoveInKeywordCodeFixProvider()); [Fact] - public async Task TestRemoveInKeyword() - { - await TestInRegularAndScript1Async( + public Task TestRemoveInKeyword() + => TestInRegularAndScript1Async( """ class Class { @@ -48,12 +47,10 @@ void N(int i) } } """); - } [Fact] - public async Task TestRemoveInKeywordMultipleArguments1() - { - await TestInRegularAndScript1Async( + public Task TestRemoveInKeywordMultipleArguments1() + => TestInRegularAndScript1Async( """ class Class { @@ -74,12 +71,10 @@ void N(int i, string s) } } """); - } [Fact] - public async Task TestRemoveInKeywordMultipleArguments2() - { - await TestInRegularAndScript1Async( + public Task TestRemoveInKeywordMultipleArguments2() + => TestInRegularAndScript1Async( """ class Class { @@ -100,12 +95,10 @@ void N(int i, int j) } } """); - } [Fact] - public async Task TestRemoveInKeywordMultipleArgumentsWithDifferentRefKinds() - { - await TestInRegularAndScript1Async( + public Task TestRemoveInKeywordMultipleArgumentsWithDifferentRefKinds() + => TestInRegularAndScript1Async( """ class Class { @@ -126,12 +119,10 @@ void N(int i, string s) } } """); - } [Fact] - public async Task TestDoNotRemoveInKeyword() - { - await TestMissingInRegularAndScriptAsync( + public Task TestDoNotRemoveInKeyword() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -142,7 +133,6 @@ void N(int i) } } """); - } [Theory] [InlineData("in [|i|]", "i")] @@ -161,9 +151,8 @@ void N(int i) [InlineData( "/* start */in /* middle */ [|i|] /* end */", "/* start */i /* end */")] - public async Task TestRemoveInKeywordWithTrivia(string original, string expected) - { - await TestInRegularAndScript1Async( + public Task TestRemoveInKeywordWithTrivia(string original, string expected) + => TestInRegularAndScript1Async( $$""" class App { @@ -186,12 +175,10 @@ void N(int i) } """); - } [Fact] - public async Task TestRemoveInKeywordFixAllInDocument1() - { - await TestInRegularAndScript1Async( + public Task TestRemoveInKeywordFixAllInDocument1() + => TestInRegularAndScript1Async( """ class Class { @@ -238,12 +225,10 @@ void N3(int i, string s) } } """); - } [Fact] - public async Task TestRemoveInKeywordFixAllInDocument2() - { - await TestInRegularAndScript1Async( + public Task TestRemoveInKeywordFixAllInDocument2() + => TestInRegularAndScript1Async( """ class Class { @@ -290,5 +275,4 @@ void N3(int i, string s) } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/RemoveRedundantEquality/RemoveRedundantEqualityTests.cs b/src/Analyzers/CSharp/Tests/RemoveRedundantEquality/RemoveRedundantEqualityTests.cs index a5b541e8a8bac..9cc271abcf893 100644 --- a/src/Analyzers/CSharp/Tests/RemoveRedundantEquality/RemoveRedundantEqualityTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveRedundantEquality/RemoveRedundantEqualityTests.cs @@ -18,9 +18,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveRedundantEquality public sealed class RemoveRedundantEqualityTests { [Fact] - public async Task TestSimpleCaseForEqualsTrue() - { - var code = """ + public Task TestSimpleCaseForEqualsTrue() + => VerifyCS.VerifyCodeFixAsync(""" public class C { public bool M1(bool x) @@ -28,8 +27,7 @@ public bool M1(bool x) return x [|==|] true; } } - """; - var fixedCode = """ + """, """ public class C { public bool M1(bool x) @@ -37,14 +35,11 @@ public bool M1(bool x) return x; } } - """; - await VerifyCS.VerifyCodeFixAsync(code, fixedCode); - } + """); [Fact] - public async Task TestSimpleCaseForEqualsFalse_NoDiagnostics() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestSimpleCaseForEqualsFalse_NoDiagnostics() + => VerifyCS.VerifyCodeFixAsync(""" public class C { public bool M1(bool x) @@ -61,12 +56,10 @@ public bool M1(bool x) } } """); - } [Fact] - public async Task TestSimpleCaseForNotEqualsFalse() - { - var code = """ + public Task TestSimpleCaseForNotEqualsFalse() + => VerifyCS.VerifyCodeFixAsync(""" public class C { public bool M1(bool x) @@ -74,8 +67,7 @@ public bool M1(bool x) return x [|!=|] false; } } - """; - var fixedCode = """ + """, """ public class C { public bool M1(bool x) @@ -83,14 +75,11 @@ public bool M1(bool x) return x; } } - """; - await VerifyCS.VerifyCodeFixAsync(code, fixedCode); - } + """); [Fact] - public async Task TestSimpleCaseForNotEqualsTrue() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestSimpleCaseForNotEqualsTrue() + => VerifyCS.VerifyCodeFixAsync(""" public class C { public bool M1(bool x) @@ -107,12 +96,10 @@ public bool M1(bool x) } } """); - } [Fact] - public async Task TestNullable_NoDiagnostics() - { - var code = """ + public Task TestNullable_NoDiagnostics() + => VerifyCS.VerifyAnalyzerAsync(""" public class C { public bool M1(bool? x) @@ -120,14 +107,11 @@ public bool M1(bool? x) return x == true; } } - """; - await VerifyCS.VerifyAnalyzerAsync(code); - } + """); [Fact] - public async Task TestWhenConstant_NoDiagnostics() - { - var code = """ + public Task TestWhenConstant_NoDiagnostics() + => VerifyCS.VerifyAnalyzerAsync(""" public class C { public const bool MyTrueConstant = true; @@ -137,14 +121,11 @@ public bool M1(bool x) return x == MyTrueConstant; } } - """; - await VerifyCS.VerifyAnalyzerAsync(code); - } + """); [Fact] - public async Task TestOverloadedOperator_NoDiagnostics() - { - var code = """ + public Task TestOverloadedOperator_NoDiagnostics() + => VerifyCS.VerifyAnalyzerAsync(""" public class C { public static bool operator ==(C a, bool b) => false; @@ -155,14 +136,11 @@ public bool M1(C x) return x == true; } } - """; - await VerifyCS.VerifyAnalyzerAsync(code); - } + """); [Fact] - public async Task TestOnLeftHandSide() - { - var code = """ + public Task TestOnLeftHandSide() + => VerifyCS.VerifyCodeFixAsync(""" public class C { public bool M1(bool x) @@ -170,8 +148,7 @@ public bool M1(bool x) return true [|==|] x; } } - """; - var fixedCode = """ + """, """ public class C { public bool M1(bool x) @@ -179,14 +156,11 @@ public bool M1(bool x) return x; } } - """; - await VerifyCS.VerifyCodeFixAsync(code, fixedCode); - } + """); [Fact] - public async Task TestInArgument() - { - var code = """ + public Task TestInArgument() + => VerifyCS.VerifyCodeFixAsync(""" public class C { public bool M1(bool x) @@ -194,8 +168,7 @@ public bool M1(bool x) return M1(x [|==|] true); } } - """; - var fixedCode = """ + """, """ public class C { public bool M1(bool x) @@ -203,14 +176,11 @@ public bool M1(bool x) return M1(x); } } - """; - await VerifyCS.VerifyCodeFixAsync(code, fixedCode); - } + """); [Fact] - public async Task TestFixAll() - { - var code = """ + public Task TestFixAll() + => VerifyCS.VerifyCodeFixAsync(""" public class C { public bool M1(bool x) @@ -228,8 +198,7 @@ public bool M3(bool x) return x [|==|] true [|==|] true; } } - """; - var fixedCode = """ + """, """ public class C { public bool M1(bool x) @@ -247,14 +216,11 @@ public bool M3(bool x) return x; } } - """; - await VerifyCS.VerifyCodeFixAsync(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48236")] - public async Task TestNullableValueTypes_DoesNotCrash() - { - var code = """ + public Task TestNullableValueTypes_DoesNotCrash() + => VerifyCS.VerifyAnalyzerAsync(""" public class C { public bool M1(int? x) @@ -262,14 +228,11 @@ public bool M1(int? x) return x == null; } } - """; - await VerifyCS.VerifyAnalyzerAsync(code); - } + """); [Fact] - public async Task TestSimpleCaseForIsFalse() - { - var code = """ + public Task TestSimpleCaseForIsFalse() + => VerifyCS.VerifyCodeFixAsync(""" public class C { public bool M1(bool x) @@ -277,8 +240,7 @@ public bool M1(bool x) return x [|is|] false; } } - """; - var fixedCode = """ + """, """ public class C { public bool M1(bool x) @@ -286,14 +248,11 @@ public bool M1(bool x) return !x; } } - """; - await VerifyCS.VerifyCodeFixAsync(code, fixedCode); - } + """); [Fact] - public async Task TestSimpleCaseForIsTrue1() - { - var code = """ + public Task TestSimpleCaseForIsTrue1() + => VerifyCS.VerifyCodeFixAsync(""" public class C { public bool M1(bool x) @@ -301,8 +260,7 @@ public bool M1(bool x) return x [|is|] true; } } - """; - var fixedCode = """ + """, """ public class C { public bool M1(bool x) @@ -310,9 +268,7 @@ public bool M1(bool x) return x; } } - """; - await VerifyCS.VerifyCodeFixAsync(code, fixedCode); - } + """); [Fact] public async Task TestSimpleCaseForIsTrue2() diff --git a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests.cs index df7f3469d4152..9047d5010c850 100644 --- a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests.cs @@ -54,9 +54,8 @@ await VerifyCS.VerifyCodeFixAsync( } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545137"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/870550")] - public async Task ParenthesizeToKeepParseTheSame1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task ParenthesizeToKeepParseTheSame1() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -83,12 +82,10 @@ static void Main() static void Goo(bool a, bool b) { } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545146")] - public async Task ParenthesizeToKeepParseTheSame2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task ParenthesizeToKeepParseTheSame2() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -113,12 +110,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545160")] - public async Task ParenthesizeToKeepParseTheSame3() - { - await VerifyCS.VerifyCodeFixAsync( + public Task ParenthesizeToKeepParseTheSame3() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -141,7 +136,6 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545138")] public async Task DoNotRemoveTypeParameterCastToObject() @@ -206,9 +200,8 @@ static void Main() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545142")] - public async Task DoRemoveCastNotNeededForUserDefinedOperator() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveCastNotNeededForUserDefinedOperator() + => VerifyCS.VerifyCodeFixAsync( """ class A { @@ -242,7 +235,6 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545143")] public async Task DoNotRemovePointerCast1() @@ -286,9 +278,8 @@ static void Main() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545145")] - public async Task DoNotRemoveCastToAnonymousMethodWhenOnLeftOfAsCast() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoNotRemoveCastToAnonymousMethodWhenOnLeftOfAsCast() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -315,7 +306,6 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545147")] public async Task DoNotRemoveCastInFloatingPointOperation() @@ -466,9 +456,8 @@ static void Goo(Action[] x) } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545287"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/880752")] - public async Task RemoveUnneededCastInParameterDefaultValue() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveUnneededCastInParameterDefaultValue() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -485,12 +474,10 @@ static void M1(int? i1 = null) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545289")] - public async Task RemoveUnneededCastInReturnStatement() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveUnneededCastInReturnStatement() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -509,12 +496,10 @@ static long M2() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545288")] - public async Task RemoveUnneededCastInLambda1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveUnneededCastInLambda1() + => VerifyCS.VerifyCodeFixAsync( """ using System; class Program @@ -535,12 +520,10 @@ static void M1() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545288")] - public async Task RemoveUnneededCastInLambda2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveUnneededCastInLambda2() + => VerifyCS.VerifyCodeFixAsync( """ using System; class Program @@ -561,7 +544,6 @@ static void M1() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545288")] public async Task RemoveUnneededCastInLambda3() @@ -683,9 +665,8 @@ public static void Main() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545291")] - public async Task DoNotRemoveUnneededCastInConditionalExpression3() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoNotRemoveUnneededCastInConditionalExpression3() + => VerifyCS.VerifyCodeFixAsync( """ class Test { @@ -708,7 +689,6 @@ public static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545291")] public async Task DoNotRemoveNeededCastInConditionalExpression() @@ -729,10 +709,10 @@ public static void Main() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545291")] - public async Task RemoveUnneededCastInConditionalExpression4() - { - var source = - """ + public Task RemoveUnneededCastInConditionalExpression4() + => new VerifyCS.Test + { + TestCode = """ class Test { public static void Main() @@ -742,9 +722,8 @@ public static void Main() var f1 = (b == 5) ? [|(long)|]4 : [|(long)|]5; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class Test { public static void Main() @@ -754,9 +733,8 @@ public static void Main() var f1 = (b == 5) ? (long)4 : 5; } } - """; - var batchFixedSource = - """ + """, + BatchFixedCode = """ class Test { public static void Main() @@ -766,23 +744,15 @@ public static void Main() var f1 = (b == 5) ? 4 : (long)5; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, - BatchFixedCode = batchFixedSource, + """, CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, DiagnosticSelector = diagnostics => diagnostics[1], }.RunAsync(); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/56938")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545459")] - public async Task RemoveUnneededCastInsideADelegateConstructor() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveUnneededCastInsideADelegateConstructor() + => VerifyCS.VerifyCodeFixAsync( """ using System; class Test @@ -811,12 +781,10 @@ static void Main(string[] args) public static void M1(int i) { } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545419")] - public async Task DoNotRemoveTriviaWhenRemovingCast() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoNotRemoveTriviaWhenRemovingCast() + => VerifyCS.VerifyCodeFixAsync( """ using System; class Test @@ -843,12 +811,10 @@ public static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545422")] - public async Task RemoveUnneededCastInsideCaseLabel() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveUnneededCastInsideCaseLabel() + => VerifyCS.VerifyCodeFixAsync( """ class Test { @@ -875,13 +841,11 @@ static void Main() } } """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/56938")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545578")] - public async Task RemoveUnneededCastInsideGotoCaseStatement() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveUnneededCastInsideGotoCaseStatement() + => VerifyCS.VerifyCodeFixAsync( """ class Test { @@ -910,13 +874,11 @@ static void Main() } } """); - } [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545595")] [Fact(Skip = "529787")] - public async Task RemoveUnneededCastInCollectionInitializer() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveUnneededCastInCollectionInitializer() + => VerifyCS.VerifyCodeFixAsync( """ using System.Collections.Generic; @@ -939,7 +901,6 @@ static void Main() } } """); - } [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529787")] [Fact(Skip = "529787")] @@ -1004,9 +965,8 @@ static void Main() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545607")] - public async Task RemoveUnneededCastInArrayInitializer() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveUnneededCastInArrayInitializer() + => VerifyCS.VerifyCodeFixAsync( """ class X { @@ -1027,12 +987,10 @@ static void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545616")] - public async Task RemoveUnneededCastWithOverloadedBinaryOperator() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveUnneededCastWithOverloadedBinaryOperator() + => VerifyCS.VerifyCodeFixAsync( """ using System; class MyAction @@ -1065,7 +1023,6 @@ static void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545616")] public async Task DoNotRemoveCastFromLambdaToDelegateWithVar1() @@ -1085,9 +1042,8 @@ static void Goo() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545616")] - public async Task DoRemoveCastFromLambdaToDelegateWithTypedVariable() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveCastFromLambdaToDelegateWithTypedVariable() + => VerifyCS.VerifyCodeFixAsync( """ using System; class MyAction @@ -1108,12 +1064,10 @@ static void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545822")] - public async Task RemoveUnnecessaryCastShouldInsertWhitespaceWhereNeededToKeepCorrectParsing() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveUnnecessaryCastShouldInsertWhitespaceWhereNeededToKeepCorrectParsing() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -1138,7 +1092,6 @@ static void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545560")] public async Task DoNotRemoveNecessaryCastWithExplicitUserDefinedConversion() @@ -1257,9 +1210,8 @@ static void Main() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545941")] - public async Task RemoveUnnecessaryCastInThrow() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveUnnecessaryCastInThrow() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -1282,7 +1234,6 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545945")] public async Task DoNotRemoveNecessaryDowncast() @@ -1387,9 +1338,8 @@ await VerifyCS.VerifyCodeFixAsync( } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545750")] - public async Task RemoveUnnecessaryCastToBaseType() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveUnnecessaryCastToBaseType() + => VerifyCS.VerifyCodeFixAsync( """ class X { @@ -1418,12 +1368,10 @@ public override string ToString() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545855")] - public async Task RemoveUnnecessaryLambdaToDelegateCast() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveUnnecessaryLambdaToDelegateCast() + => VerifyCS.VerifyCodeFixAsync( """ using System; using System.Collections.Generic; @@ -1472,12 +1420,10 @@ static bool Any(this ICollection s, Func predicate) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529816")] - public async Task RemoveUnnecessaryCastInQueryExpression() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveUnnecessaryCastInQueryExpression() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -1504,7 +1450,6 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529816")] public async Task DoNotRemoveNecessaryCastInQueryExpression() @@ -1578,9 +1523,8 @@ static void Main() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529831")] - public async Task DoNotRemoveNecessaryCastFromTypeParameterToInterface() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoNotRemoveNecessaryCastFromTypeParameterToInterface() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -1679,12 +1623,10 @@ static void Goo(TAny x, TClass y) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529831")] - public async Task RemoveUnnecessaryCastFromTypeParameterToInterface() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveUnnecessaryCastFromTypeParameterToInterface() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -1765,7 +1707,6 @@ static void Goo(TAny x, TClass y) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545877")] public async Task DoNotCrashOnIncompleteMethodDeclaration() @@ -1793,9 +1734,8 @@ static void Goo(T x, {|CS1001:{|CS1031:)|}|} } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46423")] - public async Task RemoveUnneededTargetTypedCast() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task RemoveUnneededTargetTypedCast() + => VerifyCS.VerifyCodeFixAsync(""" class Other { public short GetScopeIdForTelemetry(FixAllScope scope) @@ -1838,12 +1778,10 @@ public enum FixAllScope } """ ); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545777")] - public async Task DoNotRemoveImportantTrailingTrivia() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoNotRemoveImportantTrailingTrivia() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -1870,12 +1808,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529791")] - public async Task RemoveUnnecessaryCastToNullable1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveUnnecessaryCastToNullable1() + => VerifyCS.VerifyCodeFixAsync( """ class X { @@ -1896,12 +1832,10 @@ static void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545842")] - public async Task RemoveUnnecessaryCastToNullable2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveUnnecessaryCastToNullable2() + => VerifyCS.VerifyCodeFixAsync( """ static class C { @@ -1924,12 +1858,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545850")] - public async Task RemoveSurroundingParentheses() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveSurroundingParentheses() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -1950,7 +1882,6 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529846")] public async Task DoNotRemoveNecessaryCastFromTypeParameterToObject() @@ -2070,9 +2001,8 @@ static void Main() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545882"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/880752")] - public async Task RemoveCastInConstructorInitializer1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastInConstructorInitializer1() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -2087,12 +2017,10 @@ class C C() : this(1) { } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545958"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/880752")] - public async Task RemoveCastInConstructorInitializer2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastInConstructorInitializer2() + => VerifyCS.VerifyCodeFixAsync( """ using System.Collections; @@ -2113,7 +2041,6 @@ class C C() : this("") { } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545957")] public async Task DoNotRemoveCastInConstructorInitializer3() @@ -2140,9 +2067,8 @@ await VerifyCS.VerifyCodeFixAsync( } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545842")] - public async Task RemoveCastToNullableInArithmeticExpression() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastToNullableInArithmeticExpression() + => VerifyCS.VerifyCodeFixAsync( """ static class C { @@ -2165,7 +2091,6 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545942")] public async Task DoNotRemoveCastFromValueTypeToObjectInReferenceEquality() @@ -2396,9 +2321,8 @@ object M1(bool b) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26640")] - public async Task RemoveCastToDoubleFromIntWithTwoInConditionalExpression() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastToDoubleFromIntWithTwoInConditionalExpression() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -2417,7 +2341,6 @@ object M1(bool b) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26640")] public async Task DoNotRemoveCastToDoubleFromIntInConditionalExpression() @@ -2454,9 +2377,8 @@ object M1(bool b) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26640")] - public async Task RemoveUnnecessaryNumericCastToSameTypeInConditionalExpression() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveUnnecessaryNumericCastToSameTypeInConditionalExpression() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -2475,7 +2397,6 @@ object M1(bool b) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545894")] public async Task DoNotRemoveNecessaryCastInAttribute() @@ -2497,9 +2418,8 @@ public A(object x) } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545894")] - public async Task DoRemoveUnnecessaryCastInAttribute() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveUnnecessaryCastInAttribute() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -2522,7 +2442,6 @@ public A(object x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545894")] public async Task DoNotRemoveImplicitConstantConversionToDifferentType() @@ -2544,9 +2463,8 @@ public A() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545894")] - public async Task DoRemoveImplicitConstantConversionToSameType() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveImplicitConstantConversionToSameType() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -2569,7 +2487,6 @@ public A() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545894")] public async Task DoNotRemoveNumericConversionBoxed() @@ -2591,9 +2508,8 @@ public A(int i) } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545894")] - public async Task DoRemoveNumericConversionNotBoxed() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveNumericConversionNotBoxed() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -2616,12 +2532,10 @@ public A(int i) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545894")] - public async Task DoRemoveNonConstantCastInAttribute() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveNonConstantCastInAttribute() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -2644,7 +2558,6 @@ public A(object x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39042")] public async Task DoNotRemoveNecessaryCastForImplicitNumericCastsThatLoseInformation() @@ -2704,9 +2617,8 @@ void IDisposable.Dispose() [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545890")] [WorkItem("https://github.com/dotnet/roslyn/issues/34326")] - public async Task DoRemoveCastToInterfaceForSealedType1() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task DoRemoveCastToInterfaceForSealedType1() + => VerifyCS.VerifyCodeFixAsync(""" using System; interface I @@ -2748,13 +2660,11 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545890")] [WorkItem("https://github.com/dotnet/roslyn/issues/34326")] - public async Task DoRemoveCastToInterfaceForSealedType2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveCastToInterfaceForSealedType2() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -2803,13 +2713,11 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545890")] [WorkItem("https://github.com/dotnet/roslyn/issues/34326")] - public async Task DoRemoveCastToInterfaceForSealedType3() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveCastToInterfaceForSealedType3() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -2862,7 +2770,6 @@ void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545890")] public async Task DoNotRemoveCastToInterfaceForSealedType4() @@ -2895,9 +2802,8 @@ static void Main() [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545890")] [WorkItem("https://github.com/dotnet/roslyn/issues/34326")] - public async Task DoRemoveCastToInterfaceForSealedTypeWhenParameterValuesDifferButExplicitValueIsProvided() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveCastToInterfaceForSealedTypeWhenParameterValuesDifferButExplicitValueIsProvided() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -2940,7 +2846,6 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545888")] public async Task DoNotRemoveCastToInterfaceForSealedType6() @@ -2976,9 +2881,8 @@ static void Main() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545888")] - public async Task DoRemoveCastToInterfaceWhenNoDefaultArgsPassedAndValuesAreTheSame() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveCastToInterfaceWhenNoDefaultArgsPassedAndValuesAreTheSame() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -3021,12 +2925,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545888")] - public async Task DoRemoveCastToInterfaceWhenDefaultArgPassedAndValuesAreDifferent() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveCastToInterfaceWhenDefaultArgPassedAndValuesAreDifferent() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -3069,7 +2971,6 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545888")] public async Task DoNotRemoveCastToInterfaceWhenNoDefaultArgsPassedAndValuesAreDifferent() @@ -3100,9 +3001,8 @@ static void Main() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545888")] - public async Task DoRemoveCastToInterfaceWhenNamesAreTheSameAndNoNameProvided() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveCastToInterfaceWhenNamesAreTheSameAndNoNameProvided() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -3145,12 +3045,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545888")] - public async Task DoRemoveCastToInterfaceWhenNamesAreDifferentAndNoNameProvided() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveCastToInterfaceWhenNamesAreDifferentAndNoNameProvided() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -3193,7 +3091,6 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545888")] public async Task DoNotRemoveCastToInterfaceWhenNamesAreDifferentAndNameProvided() @@ -3392,9 +3289,8 @@ static void Main() [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545834")] [WorkItem("https://github.com/dotnet/roslyn/issues/34326")] - public async Task RemoveCastToInterfaceForStruct2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastToInterfaceForStruct2() + => VerifyCS.VerifyCodeFixAsync( """ using System; using System.Collections.Generic; @@ -3431,15 +3327,10 @@ static List.Enumerator GetEnumerator() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544655")] - public async Task RemoveCastToICloneableForDelegate() - { - // Note: The cast below can be removed because delegates are implicitly - // sealed. - - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastToICloneableForDelegate() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -3464,15 +3355,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545926")] - public async Task RemoveCastToICloneableForArray() - { - // Note: The cast below can be removed because arrays are implicitly - // sealed. - - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastToICloneableForArray() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -3497,12 +3383,10 @@ static void Main() } } """); - } [Fact] - public async Task RemoveCastToInterfaceForString() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastToInterfaceForString() + => VerifyCS.VerifyCodeFixAsync( """ using System; using System.Collections.Generic; @@ -3527,15 +3411,10 @@ static void Main(string s) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529897")] - public async Task RemoveCastToIConvertibleForEnum() - { - // Note: The cast below can be removed because enums are implicitly - // sealed. - - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastToIConvertibleForEnum() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -3560,7 +3439,6 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529897")] public async Task KeepCastToIConvertibleOnNonCopiedStruct() @@ -3580,9 +3458,8 @@ static void Main(DateTime dt) } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529897")] - public async Task RemoveCastToIConvertibleOnCopiedStruct1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastToIConvertibleOnCopiedStruct1() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -3604,7 +3481,6 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529897")] public async Task KeepCastToIConvertibleOnByRefIndexer() @@ -3626,9 +3502,8 @@ void Main() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529897")] - public async Task RemoveCastToIConvertibleOnIndexer() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastToIConvertibleOnIndexer() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -3655,7 +3530,6 @@ void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529897")] public async Task KeepCastToIConvertibleOnByRefProperty() @@ -3677,9 +3551,8 @@ void Main() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529897")] - public async Task RemoveCastToIConvertibleOnProperty() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastToIConvertibleOnProperty() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -3706,7 +3579,6 @@ void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529897")] public async Task KeepCastToIConvertibleOnByRefMethod() @@ -3728,9 +3600,8 @@ void Main() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529897")] - public async Task RemoveCastToIConvertibleOnMethod() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastToIConvertibleOnMethod() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -3757,7 +3628,6 @@ void Main() } } """); - } #endregion @@ -3836,9 +3706,8 @@ static void Goo(params object[][] x) } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529911")] - public async Task RemoveCastToObjectArrayInParamArrayArg1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastToObjectArrayInParamArrayArg1() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -3861,12 +3730,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529911")] - public async Task RemoveCastToStringArrayInParamArrayArg2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastToStringArrayInParamArrayArg2() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -3889,12 +3756,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529911")] - public async Task RemoveCastToIntArrayInParamArrayArg3() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastToIntArrayInParamArrayArg3() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -3917,12 +3782,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529911")] - public async Task RemoveCastToObjectArrayInParamArrayArg4() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastToObjectArrayInParamArrayArg4() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -3945,12 +3808,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529911")] - public async Task RemoveCastToObjectInParamArrayArg5() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastToObjectInParamArrayArg5() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -3973,12 +3834,10 @@ static void Main() } } """); - } [Fact] - public async Task RemoveCastToObjectArrayInParamArrayWithNamedArgument() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastToObjectArrayInParamArrayWithNamedArgument() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -4001,7 +3860,6 @@ static void Main() static void Goo(params object[] x) { } } """); - } #endregion @@ -4237,12 +4095,8 @@ public override void Goo(int x = 2) } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545925")] - public async Task RemoveCastIfOverriddenMethodHaveCompatibleParameterList() - { - // Note: The cast below can be removed because the parameter list - // of Goo and its override have the same default values. - - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastIfOverriddenMethodHaveCompatibleParameterList() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -4285,15 +4139,10 @@ public override void Goo(int x = 1) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529916")] - public async Task RemoveCastInReceiverForMethodGroup() - { - // Note: The cast below can be removed because the it results in - // the same method group. - - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastInReceiverForMethodGroup() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -4320,7 +4169,6 @@ static void Main() static void Goo(this string x) { } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609497")] public async Task Bugfix_609497() @@ -4743,7 +4591,7 @@ static void Goo(T x, object y) [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/640136")] public async Task RemoveUnnecessaryCastAndParseCorrect() { - var source = + var fixedSource = """ using System; using System.Threading.Tasks; @@ -4752,12 +4600,14 @@ class C { void Goo(Task x) { - (([|(Task)|]x).Result)(); + (x.Result)(); } } """; - var fixedSource = - """ + + await new VerifyCS.Test + { + TestCode = """ using System; using System.Threading.Tasks; @@ -4765,14 +4615,10 @@ class C { void Goo(Task x) { - (x.Result)(); + (([|(Task)|]x).Result)(); } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, FixedState = { Sources = { fixedSource }, @@ -4968,9 +4814,8 @@ public enum Directions } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8111")] - public async Task RemoveCastThatDoesntChangeShapeOfAnonymousTypeObject() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastThatDoesntChangeShapeOfAnonymousTypeObject() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -5005,12 +4850,10 @@ public enum Directions } } """); - } [Fact] - public async Task Tuple() - { - await VerifyCS.VerifyCodeFixAsync( + public Task Tuple() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -5029,12 +4872,10 @@ void Main() } } """); - } [Fact] - public async Task TupleWithDifferentNames() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TupleWithDifferentNames() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -5053,12 +4894,10 @@ void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24791")] - public async Task SimpleBoolCast() - { - await VerifyCS.VerifyCodeFixAsync( + public Task SimpleBoolCast() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -5079,7 +4918,6 @@ bool M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/12572")] public async Task DoNotRemoveCastThatUnboxes() @@ -5197,9 +5035,8 @@ await VerifyCS.VerifyCodeFixAsync( } [Fact] - public async Task DoRemoveCastOnCallToMethodWithInvalidParamsArgs() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveCastOnCallToMethodWithInvalidParamsArgs() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -5226,12 +5063,10 @@ private static void TakesParams({|CS0225:params|} Program wrongDefined) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18978")] - public async Task RemoveCastOnCallToMethodWithParamsArgsIfImplicitConversionExists() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastOnCallToMethodWithParamsArgsIfImplicitConversionExists() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -5262,7 +5097,6 @@ private static void TakesParams(params object[] goo) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20630")] public async Task DoNotRemoveCastOnCallToAttributeWithParamsArgs() @@ -5323,9 +5157,8 @@ static void Main() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29264")] - public async Task RemoveCastOnDictionaryIndexer() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastOnDictionaryIndexer() + => VerifyCS.VerifyCodeFixAsync( """ using System; using System.Reflection; @@ -5368,7 +5201,6 @@ static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20630")] public async Task DoNotRemoveCastOnCallToAttributeWithParamsArgsAndProperty() @@ -5440,9 +5272,8 @@ static class Program } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20630")] - public async Task DoRemoveCastOnCallToAttributeWithInvalidParamsArgs() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveCastOnCallToAttributeWithInvalidParamsArgs() + => VerifyCS.VerifyCodeFixAsync( """ using System; sealed class MarkAttribute : Attribute @@ -5473,7 +5304,6 @@ static class Program { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20630")] public async Task RemoveCastOnCallToAttributeWithParamsArgsWithImplicitCast() @@ -5535,9 +5365,8 @@ static class Program } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20630")] - public async Task RemoveCastOnCallToAttributeWithCastInPropertySetter() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveCastOnCallToAttributeWithCastInPropertySetter() + => VerifyCS.VerifyCodeFixAsync( """ using System; sealed class MarkAttribute : Attribute @@ -5568,7 +5397,6 @@ static class Program { } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/18510")] [InlineData("-")] @@ -5625,7 +5453,7 @@ void Goo() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18510")] public async Task RemoveCastOnValidUnaryOperatorEnumValue() { - var source = + var fixedSource = """ enum Sign { @@ -5638,12 +5466,14 @@ class T void Goo() { Sign mySign = Sign.Positive; - Sign invertedSign = (Sign) ( ~[|(int)|] mySign ); + Sign invertedSign = [|(Sign)|] ( ~mySign); } } """; - var fixedSource = - """ + + await new VerifyCS.Test + { + TestCode = """ enum Sign { Positive = 1, @@ -5655,14 +5485,10 @@ class T void Goo() { Sign mySign = Sign.Positive; - Sign invertedSign = [|(Sign)|] ( ~mySign); + Sign invertedSign = (Sign) ( ~[|(int)|] mySign ); } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, FixedState = { Sources = { fixedSource }, @@ -5673,10 +5499,10 @@ void Goo() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18510")] - public async Task RemoveCastOnValidUnaryOperatorEnumValue_Nullable() - { - var source = - """ + public Task RemoveCastOnValidUnaryOperatorEnumValue_Nullable() + => new VerifyCS.Test + { + TestCode = """ enum Sign { Positive = 1, @@ -5691,9 +5517,8 @@ void Goo() Sign? invertedSign = (Sign?)(~[|(int)|] mySign); } } - """; - var fixedSource = - """ + """, + FixedCode = """ enum Sign { Positive = 1, @@ -5708,20 +5533,14 @@ void Goo() Sign? invertedSign = (Sign?)(~mySign); } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18510")] - public async Task DoNotRemoveEnumCastToDifferentRepresentation() - { - var source = - """ + public Task DoNotRemoveEnumCastToDifferentRepresentation() + => new VerifyCS.Test + { + TestCode = """ enum Sign { Positive = 1, @@ -5736,19 +5555,14 @@ void Goo() Sign invertedSign = (Sign) ( ~(long) mySign ); } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25456#issuecomment-373549735")] - public async Task DoNotIntroduceDefaultLiteralInSwitchCase() - { - var source = - """ + public Task DoNotIntroduceDefaultLiteralInSwitchCase() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -5760,20 +5574,15 @@ void M() } } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp7_1, }.RunAsync(); - } [Fact] - public async Task DoNotIntroduceDefaultLiteralInSwitchCase_CastInsideParentheses() - { - var source = - """ + public Task DoNotIntroduceDefaultLiteralInSwitchCase_CastInsideParentheses() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -5785,20 +5594,15 @@ void M() } } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp7_1, }.RunAsync(); - } [Fact] - public async Task DoNotIntroduceDefaultLiteralInSwitchCase_DefaultInsideParentheses() - { - var source = - """ + public Task DoNotIntroduceDefaultLiteralInSwitchCase_DefaultInsideParentheses() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -5810,20 +5614,15 @@ void M() } } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp7_1, }.RunAsync(); - } [Fact] - public async Task DoNotIntroduceDefaultLiteralInSwitchCase_RemoveDoubleCast() - { - var source = - """ + public Task DoNotIntroduceDefaultLiteralInSwitchCase_RemoveDoubleCast() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -5835,9 +5634,8 @@ void M() } } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M() @@ -5849,20 +5647,13 @@ void M() } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp7_1, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/12631")] - public async Task RemoveRedundantBoolCast() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveRedundantBoolCast() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -5883,13 +5674,12 @@ void M() } } """); - } [Fact] - public async Task DoNotIntroduceDefaultLiteralInPatternSwitchCase() - { - var source = - """ + public Task DoNotIntroduceDefaultLiteralInPatternSwitchCase() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -5901,20 +5691,15 @@ void M() } } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp7_1, }.RunAsync(); - } [Fact] - public async Task DoNotIntroduceDefaultLiteralInPatternSwitchCase_CastInsideParentheses() - { - var source = - """ + public Task DoNotIntroduceDefaultLiteralInPatternSwitchCase_CastInsideParentheses() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -5926,20 +5711,15 @@ void M() } } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp7_1, }.RunAsync(); - } [Fact] - public async Task DoNotIntroduceDefaultLiteralInPatternSwitchCase_DefaultInsideParentheses() - { - var source = - """ + public Task DoNotIntroduceDefaultLiteralInPatternSwitchCase_DefaultInsideParentheses() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -5951,20 +5731,15 @@ void M() } } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp7_1, }.RunAsync(); - } [Fact] - public async Task DoNotIntroduceDefaultLiteralInPatternSwitchCase_RemoveDoubleCast() - { - var source = - """ + public Task DoNotIntroduceDefaultLiteralInPatternSwitchCase_RemoveDoubleCast() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -5976,9 +5751,8 @@ void M() } } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M() @@ -5990,21 +5764,15 @@ void M() } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp7_1, }.RunAsync(); - } [Fact] - public async Task DoNotIntroduceDefaultLiteralInPatternSwitchCase_RemoveInsideWhenClause() - { - var source = - """ + public Task DoNotIntroduceDefaultLiteralInPatternSwitchCase_RemoveInsideWhenClause() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -6016,9 +5784,8 @@ void M() } } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M() @@ -6030,21 +5797,15 @@ void M() } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp7_1, }.RunAsync(); - } [Fact] - public async Task DoNotIntroduceDefaultLiteralInPatternIs() - { - var source = - """ + public Task DoNotIntroduceDefaultLiteralInPatternIs() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -6052,20 +5813,15 @@ void M() if (true is (bool)default); } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp7_1, }.RunAsync(); - } [Fact] - public async Task DoNotIntroduceDefaultLiteralInPatternIs_CastInsideParentheses() - { - var source = - """ + public Task DoNotIntroduceDefaultLiteralInPatternIs_CastInsideParentheses() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -6073,20 +5829,15 @@ void M() if (true is ((bool)default)); } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp7_1, }.RunAsync(); - } [Fact] - public async Task DoNotIntroduceDefaultLiteralInPatternIs_DefaultInsideParentheses() - { - var source = - """ + public Task DoNotIntroduceDefaultLiteralInPatternIs_DefaultInsideParentheses() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -6094,20 +5845,15 @@ void M() if (true is (bool)(default)); } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp7_1, }.RunAsync(); - } [Fact] - public async Task DoNotIntroduceDefaultLiteralInPatternIs_RemoveDoubleCast() - { - var source = - """ + public Task DoNotIntroduceDefaultLiteralInPatternIs_RemoveDoubleCast() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -6115,9 +5861,8 @@ void M() if (true is [|(bool)|][|(bool)|]default); } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M() @@ -6125,21 +5870,15 @@ void M() if (true is (bool)default) ; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp7_1, }.RunAsync(); - } [Fact] - public async Task DoNotIntroduceDefaultLiteralInPropertyPattern1() - { - var source = - """ + public Task DoNotIntroduceDefaultLiteralInPropertyPattern1() + => new VerifyCS.Test + { + TestCode = """ class C { void M(string s) @@ -6149,20 +5888,15 @@ void M(string s) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task DoNotIntroduceDefaultLiteralInPropertyPattern2() - { - var source = - """ + public Task DoNotIntroduceDefaultLiteralInPropertyPattern2() + => new VerifyCS.Test + { + TestCode = """ class C { void M(string s) @@ -6172,14 +5906,9 @@ void M(string s) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27239")] public async Task DoNotOfferToRemoveCastWhereNoConversionExists() @@ -6427,9 +6156,8 @@ private unsafe void goo() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38347")] - public async Task TestArgToLocalFunction1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestArgToLocalFunction1() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -6462,13 +6190,12 @@ static void SameScope(decimal sum) { } } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38347")] - public async Task TestArgToLocalFunction2() - { - var source = - """ + public Task TestArgToLocalFunction2() + => new VerifyCS.Test + { + TestCode = """ class Program { public static void M() @@ -6483,9 +6210,8 @@ static void SameScope(decimal sum) { } } } } - """; - var fixedSource = - """ + """, + FixedCode = """ class Program { public static void M() @@ -6500,9 +6226,8 @@ static void SameScope(decimal sum) { } } } } - """; - var batchFixedSource = - """ + """, + BatchFixedCode = """ class Program { public static void M() @@ -6517,17 +6242,10 @@ static void SameScope(decimal sum) { } } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, - BatchFixedCode = batchFixedSource, + """, CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, DiagnosticSelector = diagnostics => diagnostics[1], }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36631")] public async Task TestFormattableString1() @@ -6549,9 +6267,8 @@ private void goo() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36631")] - public async Task TestFormattableString1_1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFormattableString1_1() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -6574,7 +6291,6 @@ private void goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36631")] public async Task TestFormattableString2() @@ -6596,9 +6312,8 @@ private void goo() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36631")] - public async Task TestFormattableString2_2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFormattableString2_2() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -6621,7 +6336,6 @@ private void goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36631")] public async Task TestFormattableString3() @@ -6646,9 +6360,8 @@ private void bar(FormattableString s) { } } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36631")] - public async Task TestFormattableString4() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFormattableString4() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -6675,12 +6388,10 @@ private void goo() private void bar(FormattableString s) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36631")] - public async Task TestFormattableString5() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFormattableString5() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -6703,12 +6414,10 @@ private void goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36631")] - public async Task TestFormattableString6() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFormattableString6() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -6735,7 +6444,6 @@ private void goo() private void bar(IFormattable s) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36631")] public async Task TestFormattableString7() @@ -6863,9 +6571,8 @@ await VerifyCS.VerifyCodeFixAsync( } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34326")] - public async Task TestOnInterfaceCallOnSealedClass() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestOnInterfaceCallOnSealedClass() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -6908,7 +6615,6 @@ void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29726")] public async Task TestDefaultLiteralWithNullableCastInCoalesce() @@ -6988,9 +6694,8 @@ void M() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34873")] - public async Task TestCanRemoveFPIdentityOnFieldRead() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestCanRemoveFPIdentityOnFieldRead() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -7017,12 +6722,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34873")] - public async Task TestCanRemoveFPIdentityOnFieldWrite() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestCanRemoveFPIdentityOnFieldWrite() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -7049,12 +6752,10 @@ void M(float f1) } } """); - } - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34873")] - public async Task TestCanRemoveFPIdentityInFieldInitializer() - { - await VerifyCS.VerifyCodeFixAsync( + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34873")] + public Task TestCanRemoveFPIdentityInFieldInitializer() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -7073,12 +6774,10 @@ public class C static float f2 = f1; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34873")] - public async Task TestCanRemoveFPIdentityOnArrayRead() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestCanRemoveFPIdentityOnArrayRead() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -7105,12 +6804,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34873")] - public async Task TestCanRemoveFPIdentityOnArrayWrite() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestCanRemoveFPIdentityOnArrayWrite() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -7137,12 +6834,10 @@ void M(float f2) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34873")] - public async Task TestCanRemoveFPIdentityOnArrayInitializer1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestCanRemoveFPIdentityOnArrayInitializer1() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -7165,12 +6860,10 @@ void M(float f2) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34873")] - public async Task TestCanRemoveFPIdentityOnArrayInitializer2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestCanRemoveFPIdentityOnArrayInitializer2() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -7193,12 +6886,10 @@ void M(float f2) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34873")] - public async Task TestCanRemoveFPIdentityOnImplicitArrayInitializer() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestCanRemoveFPIdentityOnImplicitArrayInitializer() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -7221,12 +6912,10 @@ void M(float f2) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34873")] - public async Task TestCanRemoveFPWithBoxing1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestCanRemoveFPWithBoxing1() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -7251,12 +6940,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34873")] - public async Task TestCanRemoveFPWithBoxing2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestCanRemoveFPWithBoxing2() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -7281,12 +6968,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37953")] - public async Task TestCanRemoveFromUnnecessarySwitchExpressionCast1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestCanRemoveFromUnnecessarySwitchExpressionCast1() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -7317,7 +7002,6 @@ public static string GetValue(DayOfWeek value) }; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37953")] public async Task TestLeaveNecessarySwitchExpressionCast1() @@ -7412,10 +7096,8 @@ private long Repro() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40414")] - public async Task TestSignExtensionWithAndAssignment1() - { - - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestSignExtensionWithAndAssignment1() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -7445,13 +7127,10 @@ private long Repro() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40414")] - public async Task TestSignExtensionWithAndBinary1() - { - - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestSignExtensionWithAndBinary1() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -7481,13 +7160,10 @@ private long Repro() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40414")] - public async Task TestSignExtensionWithAndBinary2() - { - - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestSignExtensionWithAndBinary2() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -7517,7 +7193,6 @@ private long Repro() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40414")] public async Task TestSignExtensionWithOrCompilerCase1() @@ -7543,10 +7218,8 @@ public static void Main() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40414")] - public async Task TestSignExtensionWithOrCompilerCase2() - { - // there is a sign extension warning both before and after. so this is not worse to remove the cast. - await VerifyCS.VerifyCodeFixAsync( + public Task TestSignExtensionWithOrCompilerCase2() + => VerifyCS.VerifyCodeFixAsync( """ public class sign { @@ -7577,7 +7250,6 @@ public static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40414")] public async Task TestSignExtensionWithOrCompilerCase3() @@ -7603,10 +7275,8 @@ public static void Main() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40414")] - public async Task TestSignExtensionWithOrCompilerCase4() - { - // there is a sign extension warning both before and after. so this is not worse to remove the cast. - await VerifyCS.VerifyCodeFixAsync( + public Task TestSignExtensionWithOrCompilerCase4() + => VerifyCS.VerifyCodeFixAsync( """ public class sign { @@ -7637,13 +7307,10 @@ public static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40414")] - public async Task TestSignExtensionWithOrCompilerCase5() - { - - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestSignExtensionWithOrCompilerCase5() + => VerifyCS.VerifyCodeFixAsync(""" public class sign { public static void Main() @@ -7673,7 +7340,6 @@ public static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40414")] public async Task TestSignExtensionWithOrCompilerCase6() @@ -7791,10 +7457,8 @@ public static void Main() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40414")] - public async Task TestSignExtensionWithOrCompilerCaseNullable2() - { - // there is a sign extension warning both before and after. so this is not worse to remove the cast. - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestSignExtensionWithOrCompilerCaseNullable2() + => VerifyCS.VerifyCodeFixAsync(""" public class sign { public static void Main() @@ -7823,7 +7487,6 @@ public static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40414")] public async Task TestSignExtensionWithOrCompilerCaseNullable3() @@ -7849,10 +7512,8 @@ public static void Main() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40414")] - public async Task TestSignExtensionWithOrCompilerCaseNullable4() - { - // there is a sign extension warning both before and after. so this is not worse to remove the cast. - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestSignExtensionWithOrCompilerCaseNullable4() + => VerifyCS.VerifyCodeFixAsync(""" public class sign { public static void Main() @@ -7881,13 +7542,10 @@ public static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40414")] - public async Task TestSignExtensionWithOrCompilerCaseNullable5() - { - - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestSignExtensionWithOrCompilerCaseNullable5() + => VerifyCS.VerifyCodeFixAsync(""" public class sign { public static void Main() @@ -7917,7 +7575,6 @@ public static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40414")] public async Task TestSignExtensionWithOrCompilerCaseNullable6() @@ -8201,11 +7858,10 @@ static void Main() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20211")] - public async Task DoNotRemoveDoubleNullCastInSwitch1() - { - // Removing the 'object' cast would make `case object:` unreachable. - var source = - """ + public Task DoNotRemoveDoubleNullCastInSwitch1() + => new VerifyCS.Test + { + TestCode = """ class Program { static int Main() @@ -8221,14 +7877,9 @@ static int Main() } } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem(20211, "https://github.com/dotnet/roslyn/issues/21613")] public async Task DoNotRemoveNecessaryCastInConditional1() @@ -8282,10 +7933,10 @@ void M(bool x) } [Fact, WorkItem(20211, "https://github.com/dotnet/roslyn/issues/21613")] - public async Task DoNotRemoveNecessaryCastInConditional4_CSharp8() - { - var source = - """ + public Task DoNotRemoveNecessaryCastInConditional4_CSharp8() + => new VerifyCS.Test + { + TestCode = """ class C { void M(bool x) @@ -8293,19 +7944,13 @@ void M(bool x) int? y = x ? (int?)1 : null; } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp8 }.RunAsync(); - } [Fact, WorkItem(20211, "https://github.com/dotnet/roslyn/issues/21613")] - public async Task DoRemoveUnnecessaryCastInConditional4() - { - await new VerifyCS.Test + public Task DoRemoveUnnecessaryCastInConditional4() + => new VerifyCS.Test { TestCode = """ class C @@ -8327,13 +7972,12 @@ void M(bool x) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem(20211, "https://github.com/dotnet/roslyn/issues/21613")] - public async Task DoNotRemoveNecessaryCastInConditional5_CSharp8() - { - var source = - """ + public Task DoNotRemoveNecessaryCastInConditional5_CSharp8() + => new VerifyCS.Test + { + TestCode = """ class C { void M(bool x) @@ -8341,19 +7985,13 @@ void M(bool x) int? y = x ? ((int?)1) : null; } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp8 }.RunAsync(); - } [Fact, WorkItem(20211, "https://github.com/dotnet/roslyn/issues/21613")] - public async Task DoRemoveUnnecessaryCastInConditional5() - { - await new VerifyCS.Test + public Task DoRemoveUnnecessaryCastInConditional5() + => new VerifyCS.Test { TestCode = """ class C @@ -8375,13 +8013,12 @@ void M(bool x) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem(20211, "https://github.com/dotnet/roslyn/issues/21613")] - public async Task DoNotRemoveNecessaryCastInConditional6_CSharp8() - { - var source = - """ + public Task DoNotRemoveNecessaryCastInConditional6_CSharp8() + => new VerifyCS.Test + { + TestCode = """ class C { void M(bool x) @@ -8389,19 +8026,13 @@ void M(bool x) int? y = x ? (int?)1 : (null); } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); - } [Fact, WorkItem(20211, "https://github.com/dotnet/roslyn/issues/21613")] - public async Task DoRemoveUnnecessaryCastInConditional6_CSharp8() - { - await new VerifyCS.Test + public Task DoRemoveUnnecessaryCastInConditional6_CSharp8() + => new VerifyCS.Test { TestCode = """ class C @@ -8423,7 +8054,6 @@ void M(bool x) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem(20211, "https://github.com/dotnet/roslyn/issues/21613")] public async Task DoNotRemoveNecessaryCastInConditional7() @@ -8477,10 +8107,10 @@ void M(bool x) } [Fact, WorkItem(20211, "https://github.com/dotnet/roslyn/issues/21613")] - public async Task DoNotRemoveNecessaryCastInConditional10_CSharp8() - { - var source = - """ + public Task DoNotRemoveNecessaryCastInConditional10_CSharp8() + => new VerifyCS.Test + { + TestCode = """ class C { void M(bool x) @@ -8488,19 +8118,13 @@ void M(bool x) int? y = x ? null : (int?)1; } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp8 }.RunAsync(); - } [Fact, WorkItem(20211, "https://github.com/dotnet/roslyn/issues/21613")] - public async Task DoRemoveUnnecessaryCastInConditional10() - { - await new VerifyCS.Test + public Task DoRemoveUnnecessaryCastInConditional10() + => new VerifyCS.Test { TestCode = """ class C @@ -8522,13 +8146,12 @@ void M(bool x) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem(20211, "https://github.com/dotnet/roslyn/issues/21613")] - public async Task DoNotRemoveNecessaryCastInConditional11_CSharp() - { - var source = - """ + public Task DoNotRemoveNecessaryCastInConditional11_CSharp() + => new VerifyCS.Test + { + TestCode = """ class C { void M(bool x) @@ -8536,19 +8159,13 @@ void M(bool x) int? y = x ? null : ((int?)1); } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp8 }.RunAsync(); - } [Fact, WorkItem(20211, "https://github.com/dotnet/roslyn/issues/21613")] - public async Task DoRemoveUnnecessaryCastInConditional11() - { - await new VerifyCS.Test + public Task DoRemoveUnnecessaryCastInConditional11() + => new VerifyCS.Test { TestCode = """ class C @@ -8570,13 +8187,12 @@ void M(bool x) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem(20211, "https://github.com/dotnet/roslyn/issues/21613")] - public async Task DoNotRemoveNecessaryCastInConditional12_CSharp8() - { - var source = - """ + public Task DoNotRemoveNecessaryCastInConditional12_CSharp8() + => new VerifyCS.Test + { + TestCode = """ class C { void M(bool x) @@ -8584,19 +8200,13 @@ void M(bool x) int? y = x ? (null) : (int?)1; } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp8 }.RunAsync(); - } [Fact, WorkItem(20211, "https://github.com/dotnet/roslyn/issues/21613")] - public async Task DoRemoveUnnecessaryCastInConditional12() - { - await new VerifyCS.Test + public Task DoRemoveUnnecessaryCastInConditional12() + => new VerifyCS.Test { TestCode = """ class C @@ -8618,7 +8228,6 @@ void M(bool x) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem(20211, "https://github.com/dotnet/roslyn/issues/21613")] public async Task DoNotRemoveNecessaryCastInConditional13() @@ -8655,10 +8264,8 @@ void M(bool x, int? z) } [Fact, WorkItem(20211, "https://github.com/dotnet/roslyn/issues/21613")] - public async Task RemoveUnecessaryCastInConditional1() - { - var source = - """ + public Task RemoveUnecessaryCastInConditional1() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M(bool x) @@ -8666,10 +8273,7 @@ void M(bool x) int? y = x ? [|(int)|]1 : default; } } - """; - - var fixedCode = - """ + """, """ class C { void M(bool x) @@ -8677,16 +8281,11 @@ void M(bool x) int? y = x ? 1 : default; } } - """; - - await VerifyCS.VerifyCodeFixAsync(source, fixedCode); - } + """); [Fact, WorkItem(20211, "https://github.com/dotnet/roslyn/issues/21613")] - public async Task RemoveUnecessaryCastInConditional2() - { - var source = - """ + public Task RemoveUnecessaryCastInConditional2() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M(bool x) @@ -8694,10 +8293,7 @@ void M(bool x) int? y = x ? [|(int)|]1 : 0; } } - """; - - var fixedCode = - """ + """, """ class C { void M(bool x) @@ -8705,16 +8301,11 @@ void M(bool x) int? y = x ? 1 : 0; } } - """; - - await VerifyCS.VerifyCodeFixAsync(source, fixedCode); - } + """); [Fact, WorkItem(20211, "https://github.com/dotnet/roslyn/issues/21613")] - public async Task RemoveUnecessaryCastInConditional3() - { - var source = - """ + public Task RemoveUnecessaryCastInConditional3() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M(bool x, int? z) @@ -8722,10 +8313,7 @@ void M(bool x, int? z) int? y = x ? [|(int)|]1 : z; } } - """; - - var fixedCode = - """ + """, """ class C { void M(bool x, int? z) @@ -8733,16 +8321,11 @@ void M(bool x, int? z) int? y = x ? 1 : z; } } - """; - - await VerifyCS.VerifyCodeFixAsync(source, fixedCode); - } + """); [Fact, WorkItem(20211, "https://github.com/dotnet/roslyn/issues/21613")] - public async Task RemoveUnecessaryCastInConditional4() - { - var source = - """ + public Task RemoveUnecessaryCastInConditional4() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M(bool x, int? z) @@ -8750,10 +8333,7 @@ void M(bool x, int? z) int? y = x ? [|(int?)|]1 : z; } } - """; - - var fixedCode = - """ + """, """ class C { void M(bool x, int? z) @@ -8761,16 +8341,13 @@ void M(bool x, int? z) int? y = x ? 1 : z; } } - """; - - await VerifyCS.VerifyCodeFixAsync(source, fixedCode); - } + """); [Fact, WorkItem(20211, "https://github.com/dotnet/roslyn/issues/21613")] - public async Task RemoveUnecessaryCastInConditional5() - { - var source = - """ + public Task RemoveUnecessaryCastInConditional5() + => new VerifyCS.Test + { + TestCode = """ class C { void M(bool x) @@ -8778,9 +8355,8 @@ void M(bool x) int? y = x ? [|(int?)|]1 : 0; } } - """; - var fixedCode = - """ + """, + FixedCode = """ class C { void M(bool x) @@ -8788,21 +8364,13 @@ void M(bool x) int? y = x ? 1 : 0; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem(20211, "https://github.com/dotnet/roslyn/issues/21613")] - public async Task RemoveUnnecessaryCastInConditional6() - { - var source = - """ + public Task RemoveUnnecessaryCastInConditional6() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M(bool x, int? z) @@ -8810,9 +8378,7 @@ void M(bool x, int? z) int? y = x ? [|(int?)|]z : null; } } - """; - var fixedCode = - """ + """, """ class C { void M(bool x, int? z) @@ -8820,16 +8386,11 @@ void M(bool x, int? z) int? y = x ? z : null; } } - """; - - await VerifyCS.VerifyCodeFixAsync(source, fixedCode); - } + """); [Fact, WorkItem(20211, "https://github.com/dotnet/roslyn/issues/21613")] - public async Task RemoveUnnecessaryCastInConditional7() - { - var source = - """ + public Task RemoveUnnecessaryCastInConditional7() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M(bool x, int? z) @@ -8837,9 +8398,7 @@ void M(bool x, int? z) int? y = x ? [|(int?)|]z : default; } } - """; - var fixedCode = - """ + """, """ class C { void M(bool x, int? z) @@ -8847,10 +8406,7 @@ void M(bool x, int? z) int? y = x ? z : default; } } - """; - - await VerifyCS.VerifyCodeFixAsync(source, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20742")] public async Task DoNotRemoveNamedArgToParamsParameter1() @@ -8875,10 +8431,8 @@ private void TakesParams(bool goo, params object[] bar) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20742")] - public async Task DoRemoveNamedArgToParamsParameter1() - { - var source = - """ + public Task DoRemoveNamedArgToParamsParameter1() + => VerifyCS.VerifyCodeFixAsync(""" class Program { public void M() @@ -8891,9 +8445,7 @@ private void TakesParams(bool goo, params object[] bar) { } } - """; - var fixedCode = - """ + """, """ class Program { public void M() @@ -8906,16 +8458,11 @@ private void TakesParams(bool goo, params object[] bar) { } } - """; - - await VerifyCS.VerifyCodeFixAsync(source, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20742")] - public async Task DoRemoveNamedArgToParamsParameter2() - { - var source = - """ + public Task DoRemoveNamedArgToParamsParameter2() + => VerifyCS.VerifyCodeFixAsync(""" class Program { public void M() @@ -8928,9 +8475,7 @@ private void TakesParams(bool goo, params object[] bar) { } } - """; - var fixedCode = - """ + """, """ class Program { public void M() @@ -8943,16 +8488,11 @@ private void TakesParams(bool goo, params object[] bar) { } } - """; - - await VerifyCS.VerifyCodeFixAsync(source, fixedCode); - } + """); [Fact] - public async Task ObjectCastInInterpolation1() - { - var source = - """ + public Task ObjectCastInInterpolation1() + => VerifyCS.VerifyCodeFixAsync(""" class Program { public void M(int x, int z) @@ -8960,26 +8500,19 @@ public void M(int x, int z) var v = $"x {[|(object)|]1} z"; } } - """; - var fixedCode = - """ + """, """ class Program { public void M(int x, int z) { var v = $"x {1} z"; - } - } - """; - - await VerifyCS.VerifyCodeFixAsync(source, fixedCode); - } + } + } + """); [Fact] - public async Task ObjectCastInInterpolation2() - { - var source = - """ + public Task ObjectCastInInterpolation2() + => VerifyCS.VerifyCodeFixAsync(""" class Program { public void M(int x, int z) @@ -8987,9 +8520,7 @@ public void M(int x, int z) var v = $"x {([|(object)|]1)} z"; } } - """; - var fixedCode = - """ + """, """ class Program { public void M(int x, int z) @@ -8997,16 +8528,11 @@ public void M(int x, int z) var v = $"x {1} z"; } } - """; - - await VerifyCS.VerifyCodeFixAsync(source, fixedCode); - } + """); [Fact] - public async Task TestIdentityDoubleCast() - { - var source = - """ + public Task TestIdentityDoubleCast() + => VerifyCS.VerifyCodeFixAsync(""" class Program { public void M(object x) @@ -9014,9 +8540,7 @@ public void M(object x) var v = [|(int)|](int)x; } } - """; - var fixedCode = - """ + """, """ class Program { public void M(object x) @@ -9024,10 +8548,7 @@ public void M(object x) var v = (int)x; } } - """; - - await VerifyCS.VerifyCodeFixAsync(source, fixedCode); - } + """); [Fact] public async Task TestUnintendedReferenceComparison1() @@ -9570,9 +9091,8 @@ void Goo() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45695")] - public async Task DoRemoveObjectCastInsideInterpolation() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveObjectCastInsideInterpolation() + => VerifyCS.VerifyCodeFixAsync( """ class Other { @@ -9593,32 +9113,26 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47800")] public async Task RemoveNativeIntCastsAsIdentity() { - var source = - """ + var test = new VerifyCS.Test() + { + TestCode = """ using System; public class C { public nint N(IntPtr x) => [|(nint)|]x; } - """; - var fixedCode = - """ + """, + FixedCode = """ using System; public class C { public nint N(IntPtr x) => x; } - """; - - var test = new VerifyCS.Test() - { - TestCode = source, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp9 }; @@ -9628,18 +9142,15 @@ public class C { [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47800")] public async Task DoRemoveNativeIntCasts() { - var source = - """ + var test = new VerifyCS.Test() + { + TestCode = """ using System; public class C { public nuint N(IntPtr x) => (nuint)(nint)x; } - """; - - var test = new VerifyCS.Test() - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp9 }; @@ -9649,27 +9160,22 @@ public class C { [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47800")] public async Task RemoveNativeUIntCastsAsIdentity() { - var source = - """ + var test = new VerifyCS.Test() + { + TestCode = """ using System; public class C { public nuint N(UIntPtr x) => [|(nuint)|]x; } - """; - var fixedCode = - """ + """, + FixedCode = """ using System; public class C { public nuint N(UIntPtr x) => x; } - """; - - var test = new VerifyCS.Test() - { - TestCode = source, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp9 }; @@ -9679,18 +9185,15 @@ public class C { [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51123")] public async Task DoRemoveNativeIntCastsToInt() { - var source = - """ + var test = new VerifyCS.Test() + { + TestCode = """ using System; public class C { public int N(IntPtr x) => (int)(nint)x; } - """; - - var test = new VerifyCS.Test() - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp9 }; @@ -9700,18 +9203,15 @@ public class C { [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47800")] public async Task DoRemoveNativeUIntCasts() { - var source = - """ + var test = new VerifyCS.Test() + { + TestCode = """ using System; public class C { public nint N(UIntPtr x) => (nint)(nuint)x; } - """; - - var test = new VerifyCS.Test() - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp9 }; @@ -9719,10 +9219,8 @@ public class C { } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47800")] - public async Task RemoveIntPtrCastsAsIdentity() - { - var source = - """ + public Task RemoveIntPtrCastsAsIdentity() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -9732,9 +9230,7 @@ public void M(IntPtr x) var v = [|(IntPtr)|]x; } } - """; - var fixedCode = - """ + """, """ using System; class C @@ -9744,16 +9240,11 @@ public void M(IntPtr x) var v = x; } } - """; - - await VerifyCS.VerifyCodeFixAsync(source, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47800")] - public async Task RemoveUIntPtrCastsAsIdentity() - { - var source = - """ + public Task RemoveUIntPtrCastsAsIdentity() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -9763,9 +9254,7 @@ public void M(UIntPtr x) var v = [|(UIntPtr)|]x; } } - """; - var fixedCode = - """ + """, """ using System; class C @@ -9775,16 +9264,14 @@ public void M(UIntPtr x) var v = x; } } - """; - - await VerifyCS.VerifyCodeFixAsync(source, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49140")] public async Task DoNotRemoveBitwiseNotOfUnsignedExtendedValue1() { - var source = - """ + var test = new VerifyCS.Test() + { + TestCode = """ class C { public static ulong P(ulong a, uint b) @@ -9792,11 +9279,7 @@ public static ulong P(ulong a, uint b) return a & ~(ulong)b; } } - """; - - var test = new VerifyCS.Test() - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp9 }; @@ -9806,8 +9289,9 @@ public static ulong P(ulong a, uint b) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49140")] public async Task DoNotRemoveBitwiseNotOfUnsignedExtendedValue2() { - var source = - """ + var test = new VerifyCS.Test() + { + TestCode = """ class C { public static nuint N(nuint a, uint b) @@ -9815,11 +9299,7 @@ public static nuint N(nuint a, uint b) return a & ~(nuint)b; } } - """; - - var test = new VerifyCS.Test() - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp9 }; @@ -9829,8 +9309,9 @@ public static nuint N(nuint a, uint b) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49140")] public async Task DoNotRemoveBitwiseNotOfUnsignedExtendedValue3() { - var source = - """ + var test = new VerifyCS.Test() + { + TestCode = """ class C { public static ulong N() @@ -9838,11 +9319,7 @@ public static ulong N() return ~(ulong)uint.MaxValue; } } - """; - - var test = new VerifyCS.Test() - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp9 }; @@ -9909,9 +9386,8 @@ public static nint N(nint a, int b) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50000")] - public async Task KeepNecessaryCastIfRemovalWouldCreateIllegalConditionalExpression() - { - await new VerifyCS.Test + public Task KeepNecessaryCastIfRemovalWouldCreateIllegalConditionalExpression() + => new VerifyCS.Test { TestCode = """ class C @@ -9922,12 +9398,10 @@ ushort Goo(string s) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50000")] - public async Task RemoveUnnecessaryCastWhenConditionalExpressionIsLegal() - { - await new VerifyCS.Test + public Task RemoveUnnecessaryCastWhenConditionalExpressionIsLegal() + => new VerifyCS.Test { TestCode = """ class C @@ -9945,13 +9419,12 @@ uint Goo(string s) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52524")] - public async Task DoNotRemoveForValueTaskConstrutor() - { - var source = - """ + public Task DoNotRemoveForValueTaskConstrutor() + => new VerifyCS.Test + { + TestCode = """ #nullable enable using System.Threading.Tasks; @@ -9974,20 +9447,15 @@ static void Main() ValueTask v = new((object?)null); } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53698")] - public async Task DoNotRemoveForConditional() - { - var source = - """ + public Task DoNotRemoveForConditional() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class E @@ -10002,20 +9470,15 @@ public E First } } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/55621")] - public async Task DoNotRemoveForNullWithMultipleMatchingParameterTypes() - { - var source = - """ + public Task DoNotRemoveForNullWithMultipleMatchingParameterTypes() + => new VerifyCS.Test + { + TestCode = """ #nullable enable using System; public class TestClass @@ -10025,20 +9488,15 @@ public TestClass(Func value) { } public TestClass Create1() => new ((object?)null); } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56207")] - public async Task DoNotRemoveForNintPointerToVoidPointer() - { - var source = - """ + public Task DoNotRemoveForNintPointerToVoidPointer() + => new VerifyCS.Test + { + TestCode = """ using System; public class TestClass { @@ -10047,19 +9505,13 @@ unsafe void M(nint** ptr) nint value = (nint)(void*)*ptr; } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task RemoveUnnecessaryCastInPattern1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveUnnecessaryCastInPattern1() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -10078,12 +9530,10 @@ void Main(int? n) } } """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/56938")] - public async Task RemoveUnnecessaryNullableCastInPattern1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task RemoveUnnecessaryNullableCastInPattern1() + => VerifyCS.VerifyCodeFixAsync( """ class Program { @@ -10102,7 +9552,6 @@ void Main(int? n) } } """); - } [Fact] public async Task DoNotRemoveBoxingEnumCast() @@ -10122,9 +9571,8 @@ static void M() } [Fact] - public async Task DoRemoveFPCastFromNonFPTypeToWidenedType1() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task DoRemoveFPCastFromNonFPTypeToWidenedType1() + => VerifyCS.VerifyCodeFixAsync(""" using System; class Program @@ -10157,7 +9605,6 @@ static void Main() } } """); - } [Fact] public async Task DoNotRemoveFPCastToWidenedType2() @@ -10278,9 +9725,8 @@ static void Main() } [Fact] - public async Task CanRemoveExplicitCastToReferenceTypeWhenPassedToDynamic1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task CanRemoveExplicitCastToReferenceTypeWhenPassedToDynamic1() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -10307,12 +9753,10 @@ static void Main() } } """); - } [Fact] - public async Task CanRemoveExplicitCastToReferenceTypeWhenPassedToDynamic2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task CanRemoveExplicitCastToReferenceTypeWhenPassedToDynamic2() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -10339,7 +9783,6 @@ static void Main() } } """); - } [Fact] public async Task NotOnWidenedNumericStoredInObject1() @@ -10381,9 +9824,8 @@ static void Main() } [Fact] - public async Task OnNonWidenedNumericStoredInObject1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task OnNonWidenedNumericStoredInObject1() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -10408,12 +9850,10 @@ static void Main() } } """); - } [Fact] - public async Task OnNonWidenedNumericConstantStoredInObject2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task OnNonWidenedNumericConstantStoredInObject2() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -10436,7 +9876,6 @@ static void Main() } } """); - } [Fact] public async Task DisallowNarrowingNullableNumericAsCast() @@ -10460,9 +9899,8 @@ static void Main() } [Fact] - public async Task AllowNonNarrowingNullableNumericAsCast() - { - await VerifyCS.VerifyCodeFixAsync( + public Task AllowNonNarrowingNullableNumericAsCast() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -10489,7 +9927,6 @@ static void Main() } } """); - } [Fact] public async Task CanNotRemoveStackallocToVarOutsideOfUnsafeRegion() @@ -10516,9 +9953,8 @@ static void Main() } [Fact] - public async Task CanRemoveStackallocToSpanOutsideOfUnsafeRegion() - { - await VerifyCS.VerifyCodeFixAsync( + public Task CanRemoveStackallocToSpanOutsideOfUnsafeRegion() + => VerifyCS.VerifyCodeFixAsync( """ using System; namespace System @@ -10553,7 +9989,6 @@ static void Main() } } """); - } [Fact] public async Task CanNotRemoveStackallocToVarInsideOfUnsafeRegion1() @@ -10607,9 +10042,8 @@ unsafe static void Main() } [Fact] - public async Task CanRemoveStackallocToSpanInsideOfUnsafeRegion1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task CanRemoveStackallocToSpanInsideOfUnsafeRegion1() + => VerifyCS.VerifyCodeFixAsync( """ using System; namespace System @@ -10650,12 +10084,10 @@ static void Main() } } """); - } [Fact] - public async Task CanRemoveStackallocToSpanInsideOfUnsafeRegion2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task CanRemoveStackallocToSpanInsideOfUnsafeRegion2() + => VerifyCS.VerifyCodeFixAsync( """ using System; namespace System @@ -10690,7 +10122,6 @@ unsafe static void Main() } } """); - } [Fact] public async Task CanRemoveStackallocToVarInsideOfUnsafeRegion1() @@ -10717,9 +10148,8 @@ unsafe static void Main() } [Fact] - public async Task CanRemoveParenthesizedStackallocToVarInsideOfUnsafeRegion1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task CanRemoveParenthesizedStackallocToVarInsideOfUnsafeRegion1() + => VerifyCS.VerifyCodeFixAsync( """ using System; namespace System @@ -10754,7 +10184,6 @@ unsafe static void Main() } } """); - } [Fact] public async Task CanRemoveStackallocToPointerInsideOfUnsafeRegion1() @@ -10782,9 +10211,8 @@ unsafe static void Main() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57062")] - public async Task DoRemoveIdentityCastInConstantPattern1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveIdentityCastInConstantPattern1() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -10811,12 +10239,10 @@ void M(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57062")] - public async Task DoRemoveIdentityCastInConstantPattern2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveIdentityCastInConstantPattern2() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -10843,7 +10269,6 @@ void M(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57062")] public async Task DoNotRemoveNonIdentityCastInConstantPattern1() @@ -10867,10 +10292,10 @@ void M(object o) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57062")] - public async Task DoNotRemoveNonIdentityCastInConstantPattern2() - { - var source = - """ + public Task DoNotRemoveNonIdentityCastInConstantPattern2() + => new VerifyCS.Test + { + TestCode = """ using System; class C @@ -10882,19 +10307,13 @@ void M(object o) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57062")] - public async Task DoNotRemoveNonIdentityCastInConstantPattern3() - { - await new VerifyCS.Test + public Task DoNotRemoveNonIdentityCastInConstantPattern3() + => new VerifyCS.Test { TestCode = """ using System; @@ -10928,7 +10347,6 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57062")] public async Task DoNotRemoveNonIdentityCastInConstantPattern4() @@ -11064,9 +10482,8 @@ bool M(IAssembly a2, Assembly a1) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57065")] - public async Task DoNotRemoveEqualityWarningSilencingCast5() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoNotRemoveEqualityWarningSilencingCast5() + => VerifyCS.VerifyCodeFixAsync( """ interface IAssembly { @@ -11106,7 +10523,6 @@ bool M(IAssembly a2, Assembly a1) => a1 == [|(object)|]a2; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57065")] public async Task DoNotRemoveEqualityWarningSilencingCast6() @@ -11221,9 +10637,8 @@ bool M(IAssembly a2, Assembly a1) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57065")] - public async Task DoNotRemoveEqualityWarningSilencingCast10() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoNotRemoveEqualityWarningSilencingCast10() + => VerifyCS.VerifyCodeFixAsync( """ interface IAssembly { @@ -11263,7 +10678,6 @@ bool M(IAssembly a2, Assembly a1) => a1 == a2 as object; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57065")] public async Task DoNotRemoveObjectCastToCauseReferenceEqualityWhenUserDefinedComparisonExists1() @@ -11378,9 +10792,8 @@ bool M(Assembly a2, Assembly a1) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57065")] - public async Task DoRemoveObjectCastToCauseReferenceEqualityOnInterface1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveObjectCastToCauseReferenceEqualityOnInterface1() + => VerifyCS.VerifyCodeFixAsync( """ interface IAssembly { @@ -11403,12 +10816,10 @@ bool M(IAssembly a2, IAssembly a1) => a1 == a2; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57065")] - public async Task DoRemoveObjectCastToCauseReferenceEqualityOnInterface2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveObjectCastToCauseReferenceEqualityOnInterface2() + => VerifyCS.VerifyCodeFixAsync( """ interface IAssembly { @@ -11431,12 +10842,10 @@ bool M(IAssembly a2, IAssembly a1) => a1 == a2; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57065")] - public async Task DoRemoveObjectCastToCauseReferenceEqualityOnInterface3() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveObjectCastToCauseReferenceEqualityOnInterface3() + => VerifyCS.VerifyCodeFixAsync( """ interface IAssembly { @@ -11459,12 +10868,10 @@ bool M(IAssembly a2, IAssembly a1) => a1 == a2; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57065")] - public async Task DoRemoveObjectCastToCauseReferenceEqualityOnInterface4() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveObjectCastToCauseReferenceEqualityOnInterface4() + => VerifyCS.VerifyCodeFixAsync( """ interface IAssembly { @@ -11487,12 +10894,10 @@ bool M(IAssembly a2, IAssembly a1) => a1 == a2; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57065")] - public async Task DoRemoveObjectCastToCauseReferenceEqualityOnInterface5() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveObjectCastToCauseReferenceEqualityOnInterface5() + => VerifyCS.VerifyCodeFixAsync( """ interface IAssembly { @@ -11515,12 +10920,10 @@ bool M(IAssembly a2, IAssembly a1) => a1 == a2; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57065")] - public async Task DoRemoveObjectCastToCauseReferenceEqualityOnInterface6() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveObjectCastToCauseReferenceEqualityOnInterface6() + => VerifyCS.VerifyCodeFixAsync( """ interface IAssembly { @@ -11543,7 +10946,6 @@ bool M(IAssembly a2, IAssembly a1) => a1 == a2; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57063")] public async Task DoNotRemoveNullableIntToNullableEnumCast() @@ -11593,9 +10995,8 @@ void M(IList nodes) [Fact(Skip = "https://github.com/dotnet/roslyn/issues/56938")] [WorkItem("https://github.com/dotnet/roslyn/issues/57064")] - public async Task DoRemoveNRTCastInConditional1() - { - await new VerifyCS.Test + public Task DoRemoveNRTCastInConditional1() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -11628,12 +11029,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57064")] - public async Task DoRemoveNRTCastInConditional2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveNRTCastInConditional2() + => VerifyCS.VerifyCodeFixAsync( """ #nullable enable @@ -11662,12 +11061,10 @@ class C } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57064")] - public async Task DoRemoveUnnecessaryWideningConstantCastInConditional1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveUnnecessaryWideningConstantCastInConditional1() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -11686,7 +11083,6 @@ void M(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57064")] public async Task DoNotRemoveNnecessaryWideningConstantCastInConditional1() @@ -11705,9 +11101,8 @@ void M(int a) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57064")] - public async Task DoRemoveUnnecessaryWideningCastInConditional2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveUnnecessaryWideningCastInConditional2() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -11726,7 +11121,6 @@ void M(int a, int b, int c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57064")] public async Task DoNotRemoveNecessaryWideningCastInConditional2() @@ -11744,9 +11138,8 @@ void M(int a, int b, int c) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57064")] - public async Task DoRemoveUnnecessaryWideningNullableConstantCastInConditional3() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveUnnecessaryWideningNullableConstantCastInConditional3() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -11765,7 +11158,6 @@ void M(int a, int b, int c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57064")] public async Task DoNotRemoveNecessaryWideningNullableConstantCastInConditional3() @@ -11784,9 +11176,8 @@ void M(int a, int b, int c) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57064")] - public async Task DoRemoveUnnecessaryWideningNullableCastInConditional3() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveUnnecessaryWideningNullableCastInConditional3() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -11805,7 +11196,6 @@ void M(int a, int b, int c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57064")] public async Task DoNotRemoveNecessaryWideningNullableCastInConditional3() @@ -11824,9 +11214,8 @@ void M(int a, int b, int c) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57064")] - public async Task DoRemoveUnnecessaryWideningConstantCastInConditionalWithDefault3() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveUnnecessaryWideningConstantCastInConditionalWithDefault3() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -11845,7 +11234,6 @@ void M(int a, int b, int c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57064")] public async Task DoNotRemoveNnecessaryWideningConstantCastInConditionalWithDefault3() @@ -11863,9 +11251,8 @@ void M(int a, int b, int c) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57064")] - public async Task DoRemoveUnnecessaryWideningConstantCastInConditionalWithDefault4() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoRemoveUnnecessaryWideningConstantCastInConditionalWithDefault4() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -11884,7 +11271,6 @@ void M(int a, int b, int c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57064")] public async Task DoNotRemoveNecessaryWideningConstantCastInConditionalWithDefault4() @@ -11932,9 +11318,8 @@ void M(int a, int b, int c) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56938")] - public async Task CanRemoveDoubleNullableNumericCast1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task CanRemoveDoubleNullableNumericCast1() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -11957,12 +11342,10 @@ static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56938")] - public async Task CanRemoveTripleNullableNumericCast1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task CanRemoveTripleNullableNumericCast1() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -11985,7 +11368,6 @@ static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57064")] public async Task DoNotRemoveMultipleNullableCastsThroughUserDefinedConversions1() @@ -12064,9 +11446,10 @@ void M() [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/58171")] [CombinatorialData] - public async Task DoNotRemoveMethodGroupToSpecificDelegateType(LanguageVersion version) - { - var source = """ + public Task DoNotRemoveMethodGroupToSpecificDelegateType(LanguageVersion version) + => new VerifyCS.Test + { + TestCode = """ using System; class KeyEventArgs : EventArgs @@ -12086,18 +11469,15 @@ void M() void HandleSymbolKindsPreviewKeyDown(object sender, KeyEventArgs e) { } void AddHandler(Delegate handler) { } } - """; - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = version, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58095")] - public async Task DoNotRemoveNullableCastsInTuples() - { - var source = """ + public Task DoNotRemoveNullableCastsInTuples() + => new VerifyCS.Test + { + TestCode = """ using System.Diagnostics; class C @@ -12116,18 +11496,15 @@ void M() Debug.Assert(expected_b == expected_b_01 && expected_b == expected_b_02); } } - """; - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49954")] - public async Task DoNotRemoveNullableDefaultCast1() - { - var source = """ + public Task DoNotRemoveNullableDefaultCast1() + => new VerifyCS.Test + { + TestCode = """ using System; class C @@ -12135,35 +11512,29 @@ class C protected bool? IsNewResource() => Boolean.TryParse("", out var b) ? b : (bool?)default; } - """; - await new VerifyCS.Test - { - TestCode = source, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34509")] - public async Task DoNotRemoveNullableDefaultCast2() - { - var source = """ + public Task DoNotRemoveNullableDefaultCast2() + => new VerifyCS.Test + { + TestCode = """ using System; class C { static long? TestParse(string val) => long.TryParse(val, out var parseResult) ? (long?)parseResult : default; } - """; - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49690")] - public async Task DoNotRemoveNullableGenericCast() - { - var source = """ + public Task DoNotRemoveNullableGenericCast() + => new VerifyCS.Test + { + TestCode = """ #nullable enable using System.Collections.Generic; @@ -12176,18 +11547,15 @@ static IEnumerable DoThis(IEnumerable notreallynull) return notreallynull.Where(s => s is not null) as IEnumerable; } } - """; - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45925")] - public async Task DoNotRemoveNecesssaryPatternCasts1() - { - var source = """ + public Task DoNotRemoveNecesssaryPatternCasts1() + => new VerifyCS.Test + { + TestCode = """ using System; class C @@ -12198,18 +11566,15 @@ bool M(object obj) or (double)0 or (decimal)0 or (AttributeTargets)0; } } - """; - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37473")] - public async Task DoNotRemoveNecesssaryCastInTupleWrappedInObject1() - { - var source = """ + public Task DoNotRemoveNecesssaryCastInTupleWrappedInObject1() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; public class C @@ -12219,18 +11584,15 @@ public IEnumerable Bar() yield return ("test", (decimal?)1.23); } } - """; - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33143")] - public async Task DoNotRemoveNecesssaryCastInTupleWrappedInObject2() - { - var source = """ + public Task DoNotRemoveNecesssaryCastInTupleWrappedInObject2() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; public class C @@ -12240,18 +11602,15 @@ void M() object x = (true, (IEnumerable)new int[0]); } } - """; - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33043")] - public async Task DoNotRemoveNecesssaryCastInIsNullCheck1() - { - var source = """ + public Task DoNotRemoveNecesssaryCastInIsNullCheck1() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; public class C @@ -12263,18 +11622,15 @@ void M() } } } - """; - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20617")] - public async Task DoNotRemoveNecesssaryBitwiseNotOnUnsignedValue1() - { - var source = """ + public Task DoNotRemoveNecesssaryBitwiseNotOnUnsignedValue1() + => new VerifyCS.Test + { + TestCode = """ using System; public class C @@ -12285,34 +11641,28 @@ public static void MethodName() Console.WriteLine(x); } } - """; - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11008")] - public async Task DoNotRemoveCastThatPreventsOverflowInChecked1() - { - var source = """ + public Task DoNotRemoveCastThatPreventsOverflowInChecked1() + => new VerifyCS.Test + { + TestCode = """ static class Program { static readonly long x = -(long)int.MinValue; } - """; - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34553")] - public async Task DoNotRemoveCastThatPreventsOverflowInChecked2() - { - var source = """ + public Task DoNotRemoveCastThatPreventsOverflowInChecked2() + => new VerifyCS.Test + { + TestCode = """ using System; class Program { @@ -12323,18 +11673,15 @@ void M() Int64 output64_b = checked(-(Int64)input32); } } - """; - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11008")] - public async Task DoNotRemoveCastFromIntToNullableEnum1() - { - var source = """ + public Task DoNotRemoveCastFromIntToNullableEnum1() + => new VerifyCS.Test + { + TestCode = """ enum E { } @@ -12347,18 +11694,15 @@ void M() string s = ((E?)num)?.ToString().Replace('a', 'b'); } } - """; - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11008")] - public async Task DoNotRemoveWideningCastInBitwiseOr1() - { - var source = """ + public Task DoNotRemoveWideningCastInBitwiseOr1() + => new VerifyCS.Test + { + TestCode = """ class C { public uint fn1(sbyte a, sbyte b) @@ -12366,18 +11710,15 @@ public uint fn1(sbyte a, sbyte b) return (uint)((a << 8) | (int)b); } } - """; - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32773")] - public async Task DoNotRemoveWideningCastInBitwiseOr2() - { - var source = """ + public Task DoNotRemoveWideningCastInBitwiseOr2() + => new VerifyCS.Test + { + TestCode = """ class C { public void fn1(int start, int end) @@ -12385,18 +11726,15 @@ public void fn1(int start, int end) var bounds = (((long)end) << 32) | ((long)start); } } - """; - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25165")] - public async Task DoNotRemoveCastInIllegalDelegateCast() - { - var source = """ + public Task DoNotRemoveCastInIllegalDelegateCast() + => new VerifyCS.Test + { + TestCode = """ using System; public delegate void DoSomething(); @@ -12409,18 +11747,15 @@ public Code(DoSomething f) _f = f ?? {|CS0030:(DoSomething)doNothing|}; } } - """; - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31303")] - public async Task DoNotRemoveUnsignedCastInBitwiseNot1() - { - var source = """ + public Task DoNotRemoveUnsignedCastInBitwiseNot1() + => new VerifyCS.Test + { + TestCode = """ using System; public class Code @@ -12432,18 +11767,15 @@ static void CheckRedundantCast() ulong myResult = number1 & ~(ulong)number2; } } - """; - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36755")] - public async Task DoNotRemoveNecessaryCastInSwitchExpressionArm1() - { - var source = """ + public Task DoNotRemoveNecessaryCastInSwitchExpressionArm1() + => new VerifyCS.Test + { + TestCode = """ class Program { void M() @@ -12463,18 +11795,15 @@ enum Numbers One, Two } - """; - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36782")] - public async Task DoNotRemoveNecessaryCastWithOverloadedNegationAndImplicitConversion1() - { - var source = """ + public Task DoNotRemoveNecessaryCastWithOverloadedNegationAndImplicitConversion1() + => new VerifyCS.Test + { + TestCode = """ using System; namespace WrongRedundantCastWarning @@ -12513,18 +11842,15 @@ static void Main(string[] args) } } } - """; - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37041")] - public async Task DoNotRemoveNecessaryMethodGroupToDelegateCast1() - { - var source = """ + public Task DoNotRemoveNecessaryMethodGroupToDelegateCast1() + => new VerifyCS.Test + { + TestCode = """ using System; using System.Collections.Generic; @@ -12554,18 +11880,15 @@ void Run() } } } - """; - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/54388")] - public async Task DoNotRemoveCastFromIntToDecimal() - { - var source = """ + public Task DoNotRemoveCastFromIntToDecimal() + => new VerifyCS.Test + { + TestCode = """ using System; class Program @@ -12581,18 +11904,15 @@ class X public X(decimal d) { } public X(double d) { } } - """; - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33285")] - public async Task DoNotRemoveNullableToStructCast1() - { - var source = """ + public Task DoNotRemoveNullableToStructCast1() + => new VerifyCS.Test + { + TestCode = """ using System; namespace System @@ -12628,18 +11948,19 @@ private C(ReadOnlyMemory? buffer = null) var v = new Lazy>((ReadOnlyMemory)buffer); } } - """; - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58718")] - public async Task FunctionPointerWithImplicitOperator() - { - var source = """ + public Task FunctionPointerWithImplicitOperator() + => new VerifyCS.Test + { + TestState = + { + OutputKind = OutputKind.ConsoleApplication, + }, + TestCode = """ unsafe { PointerDelegate dp = (PointerDelegate)(&Mtd); @@ -12663,28 +11984,21 @@ public TResult Invoke(T param) return this._pointer(param); } } - - public unsafe static implicit operator PointerDelegate(delegate* pointer) - { - return new(pointer); - } - } - """; - await new VerifyCS.Test - { - TestState = - { - OutputKind = OutputKind.ConsoleApplication, - }, - TestCode = source, + + public unsafe static implicit operator PointerDelegate(delegate* pointer) + { + return new(pointer); + } + } + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58709")] - public async Task NotOnNarrowingIntCastInTernary() - { - var source = """ + public Task NotOnNarrowingIntCastInTernary() + => new VerifyCS.Test + { + TestCode = """ class C { protected sbyte ExtractInt8(object data) @@ -12692,18 +12006,13 @@ protected sbyte ExtractInt8(object data) return (data is sbyte value) ? value : (sbyte)0; } } - """; - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58898")] - public async Task SameNullableTypeOnBothSidesOfConditional1() - { - await new VerifyCS.Test + public Task SameNullableTypeOnBothSidesOfConditional1() + => new VerifyCS.Test { TestCode = """ using System; @@ -12729,12 +12038,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58898")] - public async Task SameNullableTypeOnBothSidesOfConditional2() - { - await new VerifyCS.Test + public Task SameNullableTypeOnBothSidesOfConditional2() + => new VerifyCS.Test { TestCode = """ using System; @@ -12760,12 +12067,10 @@ void M(Guid g1, Guid? g2) """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58898")] - public async Task SameNullableTypeOnBothSidesOfConditional3() - { - await new VerifyCS.Test + public Task SameNullableTypeOnBothSidesOfConditional3() + => new VerifyCS.Test { TestCode = """ using System; @@ -12791,12 +12096,10 @@ void M(Guid? g1, Guid g2) """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58898")] - public async Task SameNullableTypeOnBothSidesOfConditional4() - { - await new VerifyCS.Test + public Task SameNullableTypeOnBothSidesOfConditional4() + => new VerifyCS.Test { TestCode = """ using System; @@ -12822,12 +12125,10 @@ void M(Guid g1, Guid g2) """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58898")] - public async Task SameNullableTypeOnBothSidesOfConditional5() - { - await new VerifyCS.Test + public Task SameNullableTypeOnBothSidesOfConditional5() + => new VerifyCS.Test { TestCode = """ using System; @@ -12853,12 +12154,10 @@ void M(Guid g1, Guid g2) """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58898")] - public async Task SameNullableTypeOnBothSidesOfConditional6() - { - await new VerifyCS.Test + public Task SameNullableTypeOnBothSidesOfConditional6() + => new VerifyCS.Test { TestCode = """ using System; @@ -12884,12 +12183,12 @@ void M(Guid g1, Guid g2) """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58804")] - public async Task ConvertingMethodGroupToObject_CastIsNecessary() - { - var code = """ + public Task ConvertingMethodGroupToObject_CastIsNecessary() + => new VerifyCS.Test + { + TestCode = """ class C { static object M(object o) @@ -12897,18 +12196,15 @@ static object M(object o) return (object)o.ToString; } } - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58804")] - public async Task ConvertingMethodGroupToObject_CastIsNecessary2() - { - var code = """ + public Task ConvertingMethodGroupToObject_CastIsNecessary2() + => new VerifyCS.Test + { + TestCode = """ using System; class C @@ -12923,21 +12219,18 @@ static T M2(object o) where T : Delegate return (T)(object)o.ToString; } } - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/58804")] [InlineData("Delegate")] [InlineData("MulticastDelegate")] [InlineData("Func")] - public async Task ConvertingMethodGroupToObject_CastIsUnnecessary(string type) - { - var code = $$""" + public Task ConvertingMethodGroupToObject_CastIsUnnecessary(string type) + => new VerifyCS.Test + { + TestCode = $$""" using System; class C @@ -12947,8 +12240,8 @@ class C return ({{type}})[|(object)|]o.ToString; } } - """; - var fixedCode = $$""" + """, + FixedCode = $$""" using System; class C @@ -12958,21 +12251,17 @@ class C return o.ToString; } } - """; - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp10, NumberOfIncrementalIterations = 2, NumberOfFixAllIterations = 2, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58804")] - public async Task ConvertingMethodGroupToObject_CastIsUnnecessary2() - { - var code = """ + public Task ConvertingMethodGroupToObject_CastIsUnnecessary2() + => new VerifyCS.Test + { + TestCode = """ using System; class C @@ -12982,8 +12271,8 @@ static Delegate M(object o) return (Delegate)[|(object)|]o.ToString; } } - """; - var fixedCode = """ + """, + FixedCode = """ using System; class C @@ -12993,16 +12282,11 @@ static Delegate M(object o) return o.ToString; } } - """; - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp10, NumberOfIncrementalIterations = 2, NumberOfFixAllIterations = 2, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60248")] public async Task RemoveCastInTopLevelPrograms() @@ -13028,9 +12312,10 @@ public async Task RemoveCastInTopLevelPrograms() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60292")] - public async Task KeepNecessaryExplicitNullableCast() - { - var code = """ + public Task KeepNecessaryExplicitNullableCast() + => new VerifyCS.Test + { + TestCode = """ using System; namespace ConsoleApp1 @@ -13068,18 +12353,13 @@ public enum Test Bar = 2, } } - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem(64346, "https://github.com/dotnet/roslyn/issues/61346")] - public async Task CanRemoveCastToObjectInStringInterpolation_NullableDisable() - { - var code = """ + public Task CanRemoveCastToObjectInStringInterpolation_NullableDisable() + => VerifyCS.VerifyCodeFixAsync(""" #nullable disable class C @@ -13089,8 +12369,7 @@ void M() var v = $"{[|(object)|]0}"; } } - """; - var fixedCode = """ + """, """ #nullable disable class C @@ -13100,14 +12379,11 @@ void M() var v = $"{0}"; } } - """; - await VerifyCS.VerifyCodeFixAsync(code, fixedCode); - } + """); [Fact, WorkItem(64346, "https://github.com/dotnet/roslyn/issues/61346")] - public async Task CanRemoveCastToObjectInStringInterpolation_NullableEnable() - { - var code = """ + public Task CanRemoveCastToObjectInStringInterpolation_NullableEnable() + => VerifyCS.VerifyCodeFixAsync(""" #nullable enable class C @@ -13117,8 +12393,7 @@ void M() var v = $"{[|(object)|]0}"; } } - """; - var fixedCode = """ + """, """ #nullable enable class C @@ -13128,14 +12403,11 @@ void M() var v = $"{0}"; } } - """; - await VerifyCS.VerifyCodeFixAsync(code, fixedCode); - } + """); [Fact, WorkItem(64346, "https://github.com/dotnet/roslyn/issues/61346")] - public async Task CanRemoveCastToNullableObjectInStringInterpolation() - { - var code = """ + public Task CanRemoveCastToNullableObjectInStringInterpolation() + => VerifyCS.VerifyCodeFixAsync(""" #nullable enable class C @@ -13145,8 +12417,7 @@ void M() var v = $"{[|(object?)|]0}"; } } - """; - var fixedCode = """ + """, """ #nullable enable class C @@ -13156,9 +12427,7 @@ void M() var v = $"{0}"; } } - """; - await VerifyCS.VerifyCodeFixAsync(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28867")] public async Task DoNotRemoveNullableCastInConditional() @@ -13265,9 +12534,8 @@ public void M() { } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61922")] - public async Task IdentityStructCast2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task IdentityStructCast2() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -13292,12 +12560,10 @@ public void M() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61922")] - public async Task IdentityStructCast3() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task IdentityStructCast3() + => VerifyCS.VerifyCodeFixAsync(""" using System; public class S { public int Field; @@ -13328,12 +12594,10 @@ public void M() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61922")] - public async Task IdentityStructCast4() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task IdentityStructCast4() + => VerifyCS.VerifyCodeFixAsync(""" using System; public readonly struct S { @@ -13366,12 +12630,10 @@ public void M() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61922")] - public async Task IdentityStructCast5() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task IdentityStructCast5() + => VerifyCS.VerifyCodeFixAsync(""" using System; public struct S { @@ -13408,12 +12670,10 @@ public void M() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61922")] - public async Task IdentityStructCast6() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task IdentityStructCast6() + => VerifyCS.VerifyCodeFixAsync(""" using System; public struct S { @@ -13446,12 +12706,10 @@ public void M() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61922")] - public async Task IdentityStructCast7() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task IdentityStructCast7() + => VerifyCS.VerifyCodeFixAsync(""" using System; public struct S { @@ -13484,12 +12742,10 @@ public void M() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61922")] - public async Task IdentityStructCast8() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task IdentityStructCast8() + => VerifyCS.VerifyCodeFixAsync(""" using System; public struct S { public int Field; @@ -13522,12 +12778,10 @@ public void M() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61922")] - public async Task IdentityStructCast9() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task IdentityStructCast9() + => VerifyCS.VerifyCodeFixAsync(""" using System; public struct S { public int Field; @@ -13560,12 +12814,10 @@ public void M() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71511")] - public async Task KeepRequiredCastOnCollectionExpression1() - { - await new VerifyCS.Test + public Task KeepRequiredCastOnCollectionExpression1() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -13577,13 +12829,11 @@ public class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/71511")] - public async Task KeepRequiredCastOnCollectionExpression2( + public Task KeepRequiredCastOnCollectionExpression2( [CombinatorialValues("IEnumerable", "IReadOnlyCollection", "IReadOnlyList")] string type) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Generic; @@ -13595,12 +12845,10 @@ public class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71511")] - public async Task RemoveUnnecessaryCastOnCollectionExpression1() - { - await new VerifyCS.Test + public Task RemoveUnnecessaryCastOnCollectionExpression1() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -13620,14 +12868,12 @@ public class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/71511")] - public async Task RemoveUnnecessaryCastOnCollectionExpression2( + public Task RemoveUnnecessaryCastOnCollectionExpression2( [CombinatorialValues("ICollection", "IList")] string type, [CombinatorialValues("List", "IList")] string castType) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Generic; @@ -13647,12 +12893,10 @@ public class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71511")] - public async Task RemoveUnnecessaryCastOnCollectionExpression3() - { - await new VerifyCS.Test + public Task RemoveUnnecessaryCastOnCollectionExpression3() + => new VerifyCS.Test { TestCode = """ using System; @@ -13681,12 +12925,10 @@ void M2() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71926")] - public async Task NecessaryDelegateCast1() - { - await new VerifyCS.Test + public Task NecessaryDelegateCast1() + => new VerifyCS.Test { TestCode = """ using System; @@ -13704,12 +12946,10 @@ static void Main(string[] args) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72134")] - public async Task NecessaryDelegateCast2() - { - await new VerifyCS.Test + public Task NecessaryDelegateCast2() + => new VerifyCS.Test { TestCode = """ using System; @@ -13734,12 +12974,10 @@ public static implicit operator Goo(Action value) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72933")] - public async Task RemoveCollectionExpressionCastToArray() - { - await new VerifyCS.Test + public Task RemoveCollectionExpressionCastToArray() + => new VerifyCS.Test { TestCode = """ class C @@ -13777,12 +13015,10 @@ void X() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75145")] - public async Task UnnecessaryInterpolationCast1() - { - await new VerifyCS.Test + public Task UnnecessaryInterpolationCast1() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -13815,12 +13051,10 @@ public static void Main() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75145")] - public async Task UnnecessaryInterpolationCast2() - { - await new VerifyCS.Test + public Task UnnecessaryInterpolationCast2() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -13893,12 +13127,10 @@ public void AppendFormatted(object? value) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75145")] - public async Task NecessaryInterpolationCast() - { - await new VerifyCS.Test + public Task NecessaryInterpolationCast() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -13933,12 +13165,10 @@ public void AppendFormatted(T value) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75424")] - public async Task KeepNecessaryObjectOverrideCast() - { - await new VerifyCS.Test + public Task KeepNecessaryObjectOverrideCast() + => new VerifyCS.Test { TestCode = """ using System; @@ -13954,12 +13184,10 @@ public void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71695")] - public async Task TestObjectToDynamic1() - { - await new VerifyCS.Test + public Task TestObjectToDynamic1() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -13975,12 +13203,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71695")] - public async Task TestObjectToDynamic2() - { - await new VerifyCS.Test + public Task TestObjectToDynamic2() + => new VerifyCS.Test { TestCode = """ class C @@ -13994,12 +13220,10 @@ public T M(object o) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71695")] - public async Task TestNumericThroughDynamic() - { - await new VerifyCS.Test + public Task TestNumericThroughDynamic() + => new VerifyCS.Test { TestCode = """ class C @@ -14013,12 +13237,10 @@ public int M(long o) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71695")] - public async Task TestNullableThroughDynamic() - { - await new VerifyCS.Test + public Task TestNullableThroughDynamic() + => new VerifyCS.Test { TestCode = """ class C @@ -14032,12 +13254,10 @@ public int M(int? o) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71695")] - public async Task TestEnumThroughDynamic1() - { - await new VerifyCS.Test + public Task TestEnumThroughDynamic1() + => new VerifyCS.Test { TestCode = """ using System; @@ -14053,12 +13273,10 @@ public int M(ConsoleColor o) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71695")] - public async Task TestEnumThroughDynamic2() - { - await new VerifyCS.Test + public Task TestEnumThroughDynamic2() + => new VerifyCS.Test { TestCode = """ using System; @@ -14074,12 +13292,10 @@ public ConsoleColor M(int o) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71695")] - public async Task TestConstantThroughDynamic() - { - await new VerifyCS.Test + public Task TestConstantThroughDynamic() + => new VerifyCS.Test { TestCode = """ using System; @@ -14095,14 +13311,12 @@ public int M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/68307")] [InlineData(nameof(Delegate))] [InlineData(nameof(MulticastDelegate))] - public async Task KeepNecessaryCastToDelegateAssignedToObject(string typeName) - { - await new VerifyCS.Test + public Task KeepNecessaryCastToDelegateAssignedToObject(string typeName) + => new VerifyCS.Test { TestCode = $$""" using System; @@ -14118,12 +13332,10 @@ public void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60859")] - public async Task UnnecessaryWithinConditionalBranch1() - { - await new VerifyCS.Test + public Task UnnecessaryWithinConditionalBranch1() + => new VerifyCS.Test { TestCode = """ public class IssueClass @@ -14150,12 +13362,10 @@ public object ConvertFieldValueForStorage(object value) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60859")] - public async Task UnnecessaryWithinConditionalBranch2() - { - await new VerifyCS.Test + public Task UnnecessaryWithinConditionalBranch2() + => new VerifyCS.Test { TestCode = """ public class IssueClass @@ -14182,5 +13392,120 @@ public void ConvertFieldValueForStorage(object value) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/79180")] + public Task ImplicitNumericConversionCastInTernary1() + => VerifyCS.VerifyAnalyzerAsync(""" + class C + { + private const int ConstInt = 1; + + uint M(bool condition) + { + return condition ? (uint)ConstInt : 0; + } + } + """); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/79180")] + public Task ImplicitNumericConversionCastInTernary2() + => VerifyCS.VerifyCodeFixAsync(""" + class C + { + private const int ConstInt = 1; + + uint M(bool condition) + { + return condition ? [|(uint)|]ConstInt : 0u; + } + } + """, """ + class C + { + private const int ConstInt = 1; + + uint M(bool condition) + { + return condition ? ConstInt : 0u; + } + } + """); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/79180")] + public Task ImplicitNumericConversionCastInTernary3() + => VerifyCS.VerifyCodeFixAsync(""" + class C + { + private const int ConstInt = 1; + + uint M(bool condition) + { + return condition ? [|(uint)|]ConstInt : [|(uint)|]0; + } + } + """, """ + class C + { + private const int ConstInt = 1; + + uint M(bool condition) + { + return condition ? ConstInt : (uint)0; + } + } + """); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/79180")] + public Task ImplicitNumericConversionCastInTernary4() + => new VerifyCS.Test + { + TestCode = """ + class C + { + private const int ConstInt = 1; + + uint M(bool condition) + { + return condition ? [|(uint)|]ConstInt : [|(uint)|]0; + } + } + """, + FixedCode = """ + class C + { + private const int ConstInt = 1; + + uint M(bool condition) + { + return condition ? (uint)ConstInt : 0; + } + } + """, + CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne | CodeFixTestBehaviors.SkipFixAllCheck, + DiagnosticSelector = d => d[1], + }.RunAsync(); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60720")] + public Task TestNullableWithinGeneric() + => new VerifyCS.Test + { + TestCode = """ + #nullable enable + + using System; + using System.Threading.Tasks; + + Task M(string s, Func> func) + { + return string.IsNullOrWhiteSpace(s) + ? Task.FromResult(null) + : (Task)func(s)!; + } + """, + LanguageVersion = LanguageVersion.CSharp13, + TestState = + { + OutputKind = OutputKind.ConsoleApplication, + }, + }.RunAsync(); } diff --git a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests_FixAllTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests_FixAllTests.cs index f150ea3b8d00d..6cd46db79cc0b 100644 --- a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests_FixAllTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests_FixAllTests.cs @@ -28,9 +28,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryCast)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInDocument() - { - var input = """ + public Task TestFixAllInDocument() + => TestInRegularAndScriptAsync(""" @@ -109,9 +108,7 @@ public void F(int x = (int)0) - """; - - var expected = """ + """, """ @@ -190,17 +187,13 @@ public void F(int x = (int)0) - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryCast)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInProject() - { - var input = """ + public Task TestFixAllInProject() + => TestInRegularAndScriptAsync(""" @@ -267,9 +260,7 @@ public void F(int x = (int)0) - """; - - var expected = """ + """, """ @@ -336,17 +327,13 @@ public void F(int x = (int)0) - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryCast)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInSolution() - { - var input = """ + public Task TestFixAllInSolution() + => TestInRegularAndScriptAsync(""" @@ -413,9 +400,7 @@ public void F(int x = (int)0) - """; - - var expected = """ + """, """ @@ -482,9 +467,6 @@ public void F(int x = 0) - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); #endregion } diff --git a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryDiscardDesignation/RemoveUnnecessaryDiscardDesignationTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryDiscardDesignation/RemoveUnnecessaryDiscardDesignationTests.cs index c6d3118f57068..e480d9809985e 100644 --- a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryDiscardDesignation/RemoveUnnecessaryDiscardDesignationTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryDiscardDesignation/RemoveUnnecessaryDiscardDesignationTests.cs @@ -21,9 +21,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnnecessaryDiscar public sealed class RemoveUnnecessaryDiscardDesignationTests { [Fact] - public async Task TestDeclarationPatternInSwitchStatement() - { - await new VerifyCS.Test + public Task TestDeclarationPatternInSwitchStatement() + => new VerifyCS.Test { TestCode = """ class C @@ -53,12 +52,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestNotInCSharp8() - { - await new VerifyCS.Test + public Task TestNotInCSharp8() + => new VerifyCS.Test { TestCode = """ class C @@ -75,12 +72,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] - public async Task TestDeclarationPatternInSwitchExpression() - { - await new VerifyCS.Test + public Task TestDeclarationPatternInSwitchExpression() + => new VerifyCS.Test { TestCode = """ class C @@ -108,12 +103,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestDeclarationPatternInIfStatement() - { - await new VerifyCS.Test + public Task TestDeclarationPatternInIfStatement() + => new VerifyCS.Test { TestCode = """ class C @@ -135,12 +128,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestRecursivePropertyPattern() - { - await new VerifyCS.Test + public Task TestRecursivePropertyPattern() + => new VerifyCS.Test { TestCode = """ class C @@ -168,12 +159,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestEmptyRecursiveParameterPattern() - { - await new VerifyCS.Test + public Task TestEmptyRecursiveParameterPattern() + => new VerifyCS.Test { TestCode = """ class C @@ -201,12 +190,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestTwoElementRecursiveParameterPattern() - { - await new VerifyCS.Test + public Task TestTwoElementRecursiveParameterPattern() + => new VerifyCS.Test { TestCode = """ class C @@ -234,12 +221,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestNotWithOneElementRecursiveParameterPattern() - { - await new VerifyCS.Test + public Task TestNotWithOneElementRecursiveParameterPattern() + => new VerifyCS.Test { TestCode = """ class C @@ -255,12 +240,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestNestedFixAll() - { - await new VerifyCS.Test + public Task TestNestedFixAll() + => new VerifyCS.Test { TestCode = """ class C @@ -288,12 +271,10 @@ void M(string o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66841")] - public async Task TestPropertyWithTheSameNameAsType() - { - await new VerifyCS.Test + public Task TestPropertyWithTheSameNameAsType() + => new VerifyCS.Test { TestCode = """ using System; @@ -327,12 +308,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66841")] - public async Task TestNotWhenRemovingDiscardChangesMeaning1() - { - await new VerifyCS.Test + public Task TestNotWhenRemovingDiscardChangesMeaning1() + => new VerifyCS.Test { TestCode = """ using System; @@ -351,12 +330,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66841")] - public async Task TestNotWhenRemovingDiscardChangesMeaning2() - { - await new VerifyCS.Test + public Task TestNotWhenRemovingDiscardChangesMeaning2() + => new VerifyCS.Test { TestCode = """ using System; @@ -376,12 +353,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66841")] - public async Task TestNestedPropertyWithTheSameNameAsNestedType() - { - await new VerifyCS.Test + public Task TestNestedPropertyWithTheSameNameAsNestedType() + => new VerifyCS.Test { TestCode = """ using System; @@ -429,12 +404,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66841")] - public async Task TestNotWhenRemovingDiscardChangesMeaning3() - { - await new VerifyCS.Test + public Task TestNotWhenRemovingDiscardChangesMeaning3() + => new VerifyCS.Test { TestCode = """ using System; @@ -460,12 +433,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66841")] - public async Task TestNotWhenRemovingDiscardChangesMeaning4() - { - await new VerifyCS.Test + public Task TestNotWhenRemovingDiscardChangesMeaning4() + => new VerifyCS.Test { TestCode = """ using System; @@ -492,12 +463,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66841")] - public async Task TestPropertyNamedGlobalAndAliasQualifiedName1() - { - await new VerifyCS.Test + public Task TestPropertyNamedGlobalAndAliasQualifiedName1() + => new VerifyCS.Test { TestCode = """ class C @@ -527,12 +496,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66841")] - public async Task TestPropertyNamedGlobalAndAliasQualifiedName2() - { - await new VerifyCS.Test + public Task TestPropertyNamedGlobalAndAliasQualifiedName2() + => new VerifyCS.Test { TestCode = """ class C @@ -563,12 +530,10 @@ void M(object o) LanguageVersion = LanguageVersion.CSharp9, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66841")] - public async Task TestPropertyNamedGlobalAndAliasQualifiedName3() - { - await new VerifyCS.Test + public Task TestPropertyNamedGlobalAndAliasQualifiedName3() + => new VerifyCS.Test { TestCode = """ class C @@ -601,5 +566,4 @@ void M(object o) LanguageVersion = LanguageVersion.CSharp9, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryImports/RemoveUnnecessaryImportsTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryImports/RemoveUnnecessaryImportsTests.cs index de8563ded1116..34aafe8a672d8 100644 --- a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryImports/RemoveUnnecessaryImportsTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryImports/RemoveUnnecessaryImportsTests.cs @@ -24,9 +24,8 @@ public sealed class RemoveUnnecessaryImportsTests private static readonly string s_tab = "\t"; [Fact] - public async Task TestNoReferences() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestNoReferences() + => VerifyCS.VerifyCodeFixAsync( """ [|{|IDE0005:using System; using System.Collections.Generic; @@ -47,12 +46,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestNoReferencesWithCopyright() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestNoReferencesWithCopyright() + => VerifyCS.VerifyCodeFixAsync( """ // Copyright (c) Somebody. @@ -77,12 +74,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27006")] - public async Task TestReferencesWithCopyrightAndPreservableTrivia() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestReferencesWithCopyrightAndPreservableTrivia() + => VerifyCS.VerifyCodeFixAsync( """ // Copyright (c) Somebody. @@ -114,12 +109,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27006")] - public async Task TestReferencesWithCopyrightAndGroupings() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestReferencesWithCopyrightAndGroupings() + => VerifyCS.VerifyCodeFixAsync( """ // Copyright (c) Somebody. @@ -150,12 +143,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestIdentifierReferenceInTypeContext() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestIdentifierReferenceInTypeContext() + => VerifyCS.VerifyCodeFixAsync( """ [|using System; {|IDE0005:using System.Collections.Generic; @@ -180,12 +171,12 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestGeneratedCode() - { - var source = """ + public Task TestGeneratedCode() + => new VerifyCS.Test + { + TestCode = """ // using System; @@ -199,18 +190,12 @@ static void Main(string[] args) List d; } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, }.RunAsync(); - } [Fact] - public async Task TestGenericReferenceInTypeContext() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestGenericReferenceInTypeContext() + => VerifyCS.VerifyCodeFixAsync( """ [|{|IDE0005:using System;|} using System.Collections.Generic; @@ -235,12 +220,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestMultipleReferences() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestMultipleReferences() + => VerifyCS.VerifyCodeFixAsync( """ [|using System; using System.Collections.Generic; @@ -268,12 +251,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestExtensionMethodReference() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestExtensionMethodReference() + => VerifyCS.VerifyCodeFixAsync( """ [|{|IDE0005:using System; using System.Collections.Generic;|} @@ -298,7 +279,6 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541827")] public async Task TestExtensionMethodLinq() @@ -344,9 +324,8 @@ public static IEnumerable Select(this Goo o, Func f) } [Fact] - public async Task TestAliasQualifiedAliasReference() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestAliasQualifiedAliasReference() + => VerifyCS.VerifyCodeFixAsync( """ [|{|IDE0005:using System;|} using G = System.Collections.Generic; @@ -371,12 +350,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestQualifiedAliasReference() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestQualifiedAliasReference() + => VerifyCS.VerifyCodeFixAsync( """ [|{|IDE0005:using System;|} using G = System.Collections.Generic;|] @@ -400,12 +377,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestNestedUnusedUsings() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestNestedUnusedUsings() + => VerifyCS.VerifyCodeFixAsync( """ [|{|IDE0005:using System; using System.Collections.Generic; @@ -438,12 +413,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestNestedUnusedUsings_FileScopedNamespace() - { - await new VerifyCS.Test + public Task TestNestedUnusedUsings_FileScopedNamespace() + => new VerifyCS.Test { TestCode = """ @@ -479,12 +452,10 @@ static void Main(string[] args) """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task TestNestedUsedUsings() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestNestedUsedUsings() + => VerifyCS.VerifyCodeFixAsync( """ [|using System; {|IDE0005:using System.Collections.Generic; @@ -529,12 +500,10 @@ class F DateTime d; } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/712656")] - public async Task TestNestedUsedUsings2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestNestedUsedUsings2() + => VerifyCS.VerifyCodeFixAsync( """ [|using System; {|IDE0005:using System.Collections.Generic; @@ -580,12 +549,10 @@ class F DateTime d; } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/712656")] - public async Task TestNestedUsedUsings2_FileScopedNamespace() - { - await new VerifyCS.Test + public Task TestNestedUsedUsings2_FileScopedNamespace() + => new VerifyCS.Test { TestCode = """ @@ -632,7 +599,6 @@ class F """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] public async Task TestAttribute() @@ -689,9 +655,8 @@ public class SomeClass } [Fact] - public async Task TestRemoveAllWithSurroundingPreprocessor() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestRemoveAllWithSurroundingPreprocessor() + => VerifyCS.VerifyCodeFixAsync( """ #if true @@ -719,12 +684,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestRemoveFirstWithSurroundingPreprocessor() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestRemoveFirstWithSurroundingPreprocessor() + => VerifyCS.VerifyCodeFixAsync( """ #if true @@ -756,12 +719,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestRemoveAllWithSurroundingPreprocessor2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestRemoveAllWithSurroundingPreprocessor2() + => VerifyCS.VerifyCodeFixAsync( """ namespace N { @@ -795,12 +756,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestRemoveOneWithSurroundingPreprocessor2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestRemoveOneWithSurroundingPreprocessor2() + => VerifyCS.VerifyCodeFixAsync( """ namespace N { @@ -838,12 +797,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541817")] - public async Task TestComments8718() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestComments8718() + => VerifyCS.VerifyCodeFixAsync( """ [|using Goo; {|IDE0005:using System.Collections.Generic; /*comment*/|} using Goo2;|] @@ -897,12 +854,10 @@ public class Bar2 } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528609")] - public async Task TestComments() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestComments() + => VerifyCS.VerifyCodeFixAsync( """ //c1 /*c2*/ @@ -922,12 +877,10 @@ class Program { } """); - } [Fact] - public async Task TestUnusedUsing() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestUnusedUsing() + => VerifyCS.VerifyCodeFixAsync( """ [|{|IDE0005:using System.Collections.Generic;|}|] @@ -946,12 +899,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541827")] - public async Task TestSimpleQuery() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestSimpleQuery() + => VerifyCS.VerifyCodeFixAsync( """ [|{|IDE0005:using System; using System.Collections.Generic;|} @@ -980,13 +931,12 @@ where a.Length > 21 } } """); - } [Fact] - public async Task TestUsingStaticClassAccessField1() - { - // Test intentionally uses 'using' instead of 'using static' - var testCode = """ + public Task TestUsingStaticClassAccessField1() + => new VerifyCS.Test + { + TestCode = """ [|{|IDE0005:using {|CS0138:SomeNS.Goo|};|}|] class Program @@ -1004,8 +954,8 @@ static class Goo public static int x; } } - """; - var fixedCode = """ + """, + FixedCode = """ class Program { static void Main() @@ -1021,15 +971,9 @@ static class Goo public static int x; } } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp5, }.RunAsync(); - } [Fact] public async Task TestUsingStaticClassAccessField2() @@ -1058,10 +1002,10 @@ static class Goo } [Fact] - public async Task TestUsingStaticClassAccessMethod1() - { - // Test intentionally uses 'using' instead of 'using static' - var testCode = """ + public Task TestUsingStaticClassAccessMethod1() + => new VerifyCS.Test + { + TestCode = """ [|{|IDE0005:using {|CS0138:SomeNS.Goo|};|}|] class Program @@ -1082,8 +1026,8 @@ public static int X() } } } - """; - var fixedCode = """ + """, + FixedCode = """ [|class Program { static void Main() @@ -1102,15 +1046,9 @@ public static int X() } } }|] - """; - - await new VerifyCS.Test - { - TestCode = testCode, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp5, }.RunAsync(); - } [Fact] public async Task TestUsingStaticClassAccessMethod2() @@ -1142,10 +1080,8 @@ public static int X() } [Fact, WorkItem(8846, "DevDiv_Projects/Roslyn")] - public async Task TestUnusedTypeImportIsRemoved1() - { - // Test intentionally uses 'using' instead of 'using static' - await VerifyCS.VerifyCodeFixAsync( + public Task TestUnusedTypeImportIsRemoved1() + => VerifyCS.VerifyCodeFixAsync( """ [|{|IDE0005:using {|CS0138:SomeNS.Goo|};|}|] @@ -1178,12 +1114,10 @@ static class Goo } } """); - } [Fact] - public async Task TestUnusedTypeImportIsRemoved2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestUnusedTypeImportIsRemoved2() + => VerifyCS.VerifyCodeFixAsync( """ [|{|IDE0005:using static SomeNS.Goo;|}|] @@ -1216,12 +1150,10 @@ static class Goo } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541817")] - public async Task TestRemoveTrailingComment() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestRemoveTrailingComment() + => VerifyCS.VerifyCodeFixAsync( """ {|IDE0005:[|using System.Collections.Generic;|] // comment|} @@ -1240,12 +1172,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541914")] - public async Task TestRemovingUnbindableUsing() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestRemovingUnbindableUsing() + => VerifyCS.VerifyCodeFixAsync( """ [|{|IDE0005:using {|CS0246:gibberish|};|}|] @@ -1258,7 +1188,6 @@ public static class Program { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541937")] public async Task TestAliasInUse() @@ -1286,9 +1215,8 @@ public class Bar } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541914")] - public async Task TestRemoveUnboundUsing() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestRemoveUnboundUsing() + => VerifyCS.VerifyCodeFixAsync( """ [|{|IDE0005:using {|CS0246:gibberish|};|}|] @@ -1301,12 +1229,10 @@ public static class Program { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542016")] - public async Task TestLeadingNewlines1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestLeadingNewlines1() + => VerifyCS.VerifyCodeFixAsync( """ [|{|IDE0005:using System; using System.Collections.Generic; @@ -1329,12 +1255,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542016")] - public async Task TestRemoveLeadingNewLines2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestRemoveLeadingNewLines2() + => VerifyCS.VerifyCodeFixAsync( """ namespace N { @@ -1363,7 +1287,6 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542134")] public async Task TestImportedTypeUsedAsGenericTypeArgument() @@ -1395,32 +1318,27 @@ void goo() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542723")] - public async Task TestRemoveCorrectUsing1() - { - var source = """ + public Task TestRemoveCorrectUsing1() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; namespace Goo { [|{|IDE0005:using Bar = Dictionary;|}|] } - """; - var fixedSource = """ + """, + FixedCode = """ namespace Goo { } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, // Fixing the first diagnostic introduces a second diagnostic to fix. NumberOfIncrementalIterations = 2, NumberOfFixAllIterations = 2, }.RunAsync(); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542723")] public async Task TestRemoveCorrectUsing2() @@ -1443,22 +1361,17 @@ class C } [Fact] - public async Task TestSpan() - { - var code = """ + public Task TestSpan() + => VerifyCS.VerifyCodeFixAsync(""" namespace N { [|{|IDE0005:using System;|}|] } - """; - var fixedCode = """ + """, """ namespace N { } - """; - - await VerifyCS.VerifyCodeFixAsync(code, fixedCode); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543000")] public async Task TestMissingWhenErrorsWouldBeGenerated() @@ -1961,9 +1874,8 @@ class C } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/751283")] - public async Task TestUnusedUsingOverLinq() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestUnusedUsingOverLinq() + => VerifyCS.VerifyCodeFixAsync( """ [|using System; {|IDE0005:using System.Linq; @@ -1988,12 +1900,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1323")] - public async Task TestUsingsInPPRegionWithoutOtherMembers() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestUsingsInPPRegionWithoutOtherMembers() + => VerifyCS.VerifyCodeFixAsync( """ #if true [|{|IDE0005:using System;|}|] @@ -2003,7 +1913,6 @@ await VerifyCS.VerifyCodeFixAsync( #if true #endif """); - } [Theory] [InlineData(0)] @@ -2069,9 +1978,8 @@ static void Main(string[] args) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58972")] - public async Task TestWhitespaceBeforeUnusedUsings_FileScopedNamespace() - { - await new VerifyCS.Test + public Task TestWhitespaceBeforeUnusedUsings_FileScopedNamespace() + => new VerifyCS.Test { TestCode = """ @@ -2104,12 +2012,10 @@ static void Main(string[] args) """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45866")] - public async Task TestUsingGroups_DeleteLeadingBlankLinesIfFirstGroupWasDeleted_SingleUsing() - { - await new VerifyCS.Test + public Task TestUsingGroups_DeleteLeadingBlankLinesIfFirstGroupWasDeleted_SingleUsing() + => new VerifyCS.Test { TestCode = """ @@ -2138,12 +2044,10 @@ static void Main(string[] args) } """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45866")] - public async Task TestUsingGroups_DeleteLeadingBlankLinesIfFirstGroupWasDeleted_MultipleUsings() - { - await new VerifyCS.Test + public Task TestUsingGroups_DeleteLeadingBlankLinesIfFirstGroupWasDeleted_MultipleUsings() + => new VerifyCS.Test { TestCode = """ @@ -2173,12 +2077,10 @@ static void Main(string[] args) } """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45866")] - public async Task TestUsingGroups_NotAllFirstGroupIsDeleted() - { - await new VerifyCS.Test + public Task TestUsingGroups_NotAllFirstGroupIsDeleted() + => new VerifyCS.Test { TestCode = """ @@ -2212,12 +2114,10 @@ static void Main(string[] args) } """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45866")] - public async Task TestUsingGroups_AllLastGroupIsDeleted() - { - await new VerifyCS.Test + public Task TestUsingGroups_AllLastGroupIsDeleted() + => new VerifyCS.Test { TestCode = """ @@ -2247,12 +2147,10 @@ static void Main(string[] args) } """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65114")] - public async Task DoNotTouchInnerNamespaceWithoutUsings() - { - await VerifyCS.VerifyCodeFixAsync( + public Task DoNotTouchInnerNamespaceWithoutUsings() + => VerifyCS.VerifyCodeFixAsync( $$""" [|{|IDE0005:using System; using System.Collections.Generic; @@ -2279,5 +2177,4 @@ static void Main(string[] args) } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryImports/RemoveUnnecessaryImportsTests_FixAllTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryImports/RemoveUnnecessaryImportsTests_FixAllTests.cs index 3db33ef972400..13a13a08ffff2 100644 --- a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryImports/RemoveUnnecessaryImportsTests_FixAllTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryImports/RemoveUnnecessaryImportsTests_FixAllTests.cs @@ -30,9 +30,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInDocument() - { - var input = """ + public Task TestFixAllInDocument() + => TestInRegularAndScriptAsync(""" @@ -66,9 +65,7 @@ class Program3 - """; - - var expected = """ + """, """ @@ -101,17 +98,13 @@ class Program3 - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInProject() - { - var input = """ + public Task TestFixAllInProject() + => TestInRegularAndScriptAsync(""" @@ -145,9 +138,7 @@ class Program3 - """; - - var expected = """ + """, """ @@ -179,17 +170,13 @@ class Program3 - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInProjectSkipsGeneratedCode() - { - var input = """ + public Task TestFixAllInProjectSkipsGeneratedCode() + => TestInRegularAndScriptAsync(""" @@ -223,9 +210,7 @@ class Program3 - """; - - var expected = """ + """, """ @@ -258,17 +243,13 @@ class Program3 - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInSolution() - { - var input = """ + public Task TestFixAllInSolution() + => TestInRegularAndScriptAsync(""" @@ -302,9 +283,7 @@ class Program3 - """; - - var expected = """ + """, """ @@ -335,17 +314,13 @@ class Program3 - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInContainingMember_NotApplicable() - { - var input = """ + public Task TestFixAllInContainingMember_NotApplicable() + => TestMissingInRegularAndScriptAsync(""" @@ -379,17 +354,13 @@ class Program3 - """; - - await TestMissingInRegularAndScriptAsync(input); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInContainingType_NotApplicable() - { - var input = """ + public Task TestFixAllInContainingType_NotApplicable() + => TestMissingInRegularAndScriptAsync(""" @@ -423,9 +394,6 @@ class Program3 - """; - - await TestMissingInRegularAndScriptAsync(input); - } + """); #endregion } diff --git a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryLambdaExpression/RemoveUnnecessaryLambdaExpressionTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryLambdaExpression/RemoveUnnecessaryLambdaExpressionTests.cs index ff8d0b55c2910..576891bc75c89 100644 --- a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryLambdaExpression/RemoveUnnecessaryLambdaExpressionTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryLambdaExpression/RemoveUnnecessaryLambdaExpressionTests.cs @@ -22,13 +22,12 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnnecessaryLambda [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryLambdaExpression)] public sealed class RemoveUnnecessaryLambdaExpressionTests { - private static async Task TestInRegularAndScriptAsync( + private static Task TestInRegularAndScriptAsync( [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string testCode, [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string fixedCode, LanguageVersion version = LanguageVersion.CSharp12, OutputKind? outputKind = null) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, @@ -38,7 +37,6 @@ private static async Task TestInRegularAndScriptAsync( OutputKind = outputKind, } }.RunAsync(); - } private static Task TestMissingInRegularAndScriptAsync( [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string testCode, @@ -47,9 +45,8 @@ private static Task TestMissingInRegularAndScriptAsync( => TestInRegularAndScriptAsync(testCode, testCode, version, outputKind); [Fact] - public async Task TestMissingInCSharp10() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingInCSharp10() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -64,12 +61,10 @@ void Bar(Func f) { } string Quux(int i) => default; } """, LanguageVersion.CSharp10); - } [Fact] - public async Task TestBasicCase() - { - await TestInRegularAndScriptAsync( + public Task TestBasicCase() + => TestInRegularAndScriptAsync( """ using System; @@ -98,12 +93,12 @@ void Bar(Func f) { } string Quux(int i) => default; } """); - } [Fact] - public async Task TestWithOptionOff() - { - var code = """ + public Task TestWithOptionOff() + => new VerifyCS.Test + { + TestCode = """ using System; class C @@ -116,19 +111,14 @@ void Goo() void Bar(Func f) { } string Quux(int i) => default; } - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp12, Options = { { CSharpCodeStyleOptions.PreferMethodGroupConversion, new CodeStyleOption2(false, NotificationOption2.None) } } }.RunAsync(); - } [Fact] - public async Task TestNotOnStaticLambda() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOnStaticLambda() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -143,12 +133,10 @@ void Bar(Func f) { } static string Quux(int i) => default; } """); - } [Fact] - public async Task TestNotWithOptionalParameter() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithOptionalParameter() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -163,12 +151,10 @@ void Bar(Func f) { } static string Quux(int i, int j = 0) => default; } """); - } [Fact] - public async Task TestNotWithParams1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithParams1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -183,12 +169,10 @@ void Bar(Func f) { } static string Quux(int i, params int[] j) => default; } """); - } [Fact] - public async Task TestNotWithParams2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithParams2() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -203,12 +187,10 @@ void Bar(Func f) { } static string Quux(params object[] j) => default; } """); - } [Fact] - public async Task TestWithParams1() - { - await TestInRegularAndScriptAsync( + public Task TestWithParams1() + => TestInRegularAndScriptAsync( """ using System; @@ -237,12 +219,10 @@ void Bar(Func f) { } string Quux(params object[] o) => default; } """); - } [Fact] - public async Task TestNotWithRefChange1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithRefChange1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -257,12 +237,10 @@ void Bar(Func f) { } static string Quux(ref int i) => default; } """); - } [Fact] - public async Task TestNotWithRefChange2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithRefChange2() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -279,12 +257,10 @@ void Bar(X x) { } static string Quux(int i) => default; } """); - } [Fact] - public async Task TestWithSameRef() - { - await TestInRegularAndScriptAsync( + public Task TestWithSameRef() + => TestInRegularAndScriptAsync( """ using System; @@ -318,12 +294,10 @@ void Bar(X x) { } static string Quux(ref int i) => default; } """); - } [Fact] - public async Task TestNotOnConversionToObject() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOnConversionToObject() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -338,12 +312,10 @@ void Bar(Func f) { } static string Quux(int i) => default; } """); - } [Fact] - public async Task TestWithParenthesizedLambda() - { - await TestInRegularAndScriptAsync( + public Task TestWithParenthesizedLambda() + => TestInRegularAndScriptAsync( """ using System; @@ -372,12 +344,10 @@ void Bar(Func f) { } string Quux(int i) => default; } """); - } [Fact] - public async Task TestWithAnonymousMethod() - { - await TestInRegularAndScriptAsync( + public Task TestWithAnonymousMethod() + => TestInRegularAndScriptAsync( """ using System; @@ -406,12 +376,10 @@ void Bar(Func f) { } string Quux(int i) => default; } """); - } [Fact] - public async Task TestWithAnonymousMethodNoParameterList() - { - await TestInRegularAndScriptAsync( + public Task TestWithAnonymousMethodNoParameterList() + => TestInRegularAndScriptAsync( """ using System; @@ -440,12 +408,10 @@ void Bar(Func f) { } string Quux() => default; } """); - } [Fact] - public async Task TestFixCoContravariance1() - { - await TestInRegularAndScriptAsync( + public Task TestFixCoContravariance1() + => TestInRegularAndScriptAsync( """ using System; @@ -474,12 +440,10 @@ void Bar(Func f) { } string Quux(object o) => default; } """); - } [Fact] - public async Task TestFixCoContravariance2() - { - await TestInRegularAndScriptAsync( + public Task TestFixCoContravariance2() + => TestInRegularAndScriptAsync( """ using System; @@ -508,12 +472,10 @@ void Bar(Func f) { } string Quux(object o) => default; } """); - } [Fact] - public async Task TestFixCoContravariance3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestFixCoContravariance3() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -528,12 +490,10 @@ void Bar(Func f) { } object Quux(object o) => default; } """); - } [Fact] - public async Task TestFixCoContravariance4() - { - await TestMissingInRegularAndScriptAsync( + public Task TestFixCoContravariance4() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -548,12 +508,10 @@ void Bar(Func f) { } string Quux(string o) => default; } """); - } [Fact] - public async Task TestFixCoContravariance5() - { - await TestMissingInRegularAndScriptAsync( + public Task TestFixCoContravariance5() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -568,12 +526,10 @@ void Bar(Func f) { } object Quux(string o) => default; } """); - } [Fact] - public async Task TestTwoArgs() - { - await TestInRegularAndScriptAsync( + public Task TestTwoArgs() + => TestInRegularAndScriptAsync( """ using System; @@ -602,12 +558,10 @@ void Bar(Func f) { } string Quux(int i, bool b) => default; } """); - } [Fact] - public async Task TestMultipleArgIncorrectPassing1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMultipleArgIncorrectPassing1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -622,12 +576,10 @@ void Bar(Func f) { } string Quux(int i, int b) => default; } """); - } [Fact] - public async Task TestMultipleArgIncorrectPassing2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMultipleArgIncorrectPassing2() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -642,12 +594,10 @@ void Bar(Func f) { } string Quux(int i, int b) => default; } """); - } [Fact] - public async Task TestMultipleArgIncorrectPassing3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMultipleArgIncorrectPassing3() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -662,12 +612,10 @@ void Bar(Func f) { } string Quux(int i, bool b) => default; } """); - } [Fact] - public async Task TestReturnStatement() - { - await TestInRegularAndScriptAsync( + public Task TestReturnStatement() + => TestInRegularAndScriptAsync( """ using System; @@ -698,12 +646,10 @@ void Bar(Func f) { } string Quux(int i, bool b) => default; } """); - } [Fact] - public async Task TestReturnStatement2() - { - await TestInRegularAndScriptAsync( + public Task TestReturnStatement2() + => TestInRegularAndScriptAsync( """ using System; @@ -734,12 +680,10 @@ void Bar(Func f) { } string Quux(int i, bool b) => default; } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542562")] - public async Task TestMissingOnAmbiguity1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnAmbiguity1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -763,12 +707,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542562")] - public async Task TestWithConstraint1() - { - var code = """ + public Task TestWithConstraint1() + => TestInRegularAndScriptAsync(""" using System; class A { @@ -789,9 +731,7 @@ static void Main() Bar([|x => |]Goo(x)); } } - """; - - var expected = """ + """, """ using System; class A { @@ -812,14 +752,11 @@ static void Main() Bar(Goo); } } - """; - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542562")] - public async Task TestWithConstraint2() - { - var code = """ + public Task TestWithConstraint2() + => TestMissingInRegularAndScriptAsync(""" using System; class A { @@ -840,14 +777,11 @@ static void Main() Bar(x => Goo(x)); } } - """; - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627092")] - public async Task TestMissingOnLambdaWithDynamic_1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnLambdaWithDynamic_1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -878,12 +812,10 @@ static void Goo(object x, T y) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627092")] - public async Task TestWithLambdaWithDynamic() - { - await TestInRegularAndScriptAsync( + public Task TestWithLambdaWithDynamic() + => TestInRegularAndScriptAsync( """ using System; @@ -954,12 +886,10 @@ static void Goo(object x, T y) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544625")] - public async Task ParenthesizeIfParseChanges() - { - var code = """ + public Task ParenthesizeIfParseChanges() + => TestInRegularAndScriptAsync(""" using System; class C { @@ -974,9 +904,7 @@ static void Bar(object a, object b) { } public static bool operator <(Func y, C x) { return true; } public static bool operator >(Func y, C x) { return true; } } - """; - - var expected = """ + """, """ using System; class C { @@ -991,15 +919,11 @@ static void Bar(object a, object b) { } public static bool operator <(Func y, C x) { return true; } public static bool operator >(Func y, C x) { return true; } } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545856")] - public async Task TestNotWithSideEffects() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithSideEffects() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1011,12 +935,10 @@ void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545994")] - public async Task TestExpressionStatement() - { - await TestInRegularAndScriptAsync( + public Task TestExpressionStatement() + => TestInRegularAndScriptAsync( """ using System; @@ -1041,12 +963,10 @@ static void Main() } } """); - } [Fact] - public async Task TestTaskOfT1() - { - await TestInRegularAndScriptAsync( + public Task TestTaskOfT1() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1077,12 +997,10 @@ void Bar(Func> f) { } Task Quux(int i) => default; } """); - } [Fact] - public async Task TestAsyncTaskOfT1() - { - await TestInRegularAndScriptAsync( + public Task TestAsyncTaskOfT1() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1113,12 +1031,10 @@ void Bar(Func> f) { } Task Quux(int i) => default; } """); - } [Fact] - public async Task TestAsyncTaskOfT2() - { - await TestInRegularAndScriptAsync( + public Task TestAsyncTaskOfT2() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1149,12 +1065,10 @@ void Bar(Func> f) { } Task Quux(int i) => default; } """); - } [Fact] - public async Task TestAsyncNoAwait1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestAsyncNoAwait1() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1170,12 +1084,10 @@ void Bar(Func> f) { } string Quux(int i) => default; } """); - } [Fact] - public async Task TestTaskOfT1_Return() - { - await TestInRegularAndScriptAsync( + public Task TestTaskOfT1_Return() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1206,12 +1118,10 @@ void Bar(Func> f) { } Task Quux(int i) => default; } """); - } [Fact] - public async Task TestAsyncTaskOfT1_Return() - { - await TestInRegularAndScriptAsync( + public Task TestAsyncTaskOfT1_Return() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1242,12 +1152,10 @@ void Bar(Func> f) { } Task Quux(int i) => default; } """); - } [Fact] - public async Task TestAsyncTaskOfT2_Return() - { - await TestInRegularAndScriptAsync( + public Task TestAsyncTaskOfT2_Return() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1278,12 +1186,10 @@ void Bar(Func> f) { } Task Quux(int i) => default; } """); - } [Fact] - public async Task TestAsyncNoAwait1_Return() - { - await TestMissingInRegularAndScriptAsync( + public Task TestAsyncNoAwait1_Return() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1299,12 +1205,10 @@ void Bar(Func> f) { } string Quux(int i) => default; } """); - } [Fact] - public async Task TestTask1() - { - await TestInRegularAndScriptAsync( + public Task TestTask1() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1335,12 +1239,10 @@ void Bar(Func f) { } Task Quux(int i) => default; } """); - } [Fact] - public async Task TestAsyncTask1() - { - await TestInRegularAndScriptAsync( + public Task TestAsyncTask1() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1371,12 +1273,10 @@ void Bar(Func f) { } Task Quux(int i) => default; } """); - } [Fact] - public async Task TestAsyncTask2() - { - await TestInRegularAndScriptAsync( + public Task TestAsyncTask2() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1407,12 +1307,10 @@ void Bar(Func f) { } Task Quux(int i) => default; } """); - } [Fact] - public async Task TestTask1_ExpressionStatement() - { - await TestMissingInRegularAndScriptAsync( + public Task TestTask1_ExpressionStatement() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1428,12 +1326,10 @@ void Bar(Func f) { } Task Quux(int i) => default; } """); - } [Fact] - public async Task TestAsyncTask1_ExpressionStatement() - { - await TestInRegularAndScriptAsync( + public Task TestAsyncTask1_ExpressionStatement() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1464,12 +1360,10 @@ void Bar(Func f) { } Task Quux(int i) => default; } """); - } [Fact] - public async Task TestAsyncTask2_ExpressionStatement() - { - await TestInRegularAndScriptAsync( + public Task TestAsyncTask2_ExpressionStatement() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1500,12 +1394,10 @@ void Bar(Func f) { } Task Quux(int i) => default; } """); - } [Fact] - public async Task TestAsyncNoAwait1_ExpressionStatement() - { - await TestMissingInRegularAndScriptAsync( + public Task TestAsyncNoAwait1_ExpressionStatement() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1521,12 +1413,10 @@ void Bar(Func f) { } void Quux(int i) { } } """); - } [Fact] - public async Task TestExplicitGenericCall() - { - await TestInRegularAndScriptAsync( + public Task TestExplicitGenericCall() + => TestInRegularAndScriptAsync( """ using System; @@ -1553,12 +1443,10 @@ void Goo() void Quux() { } } """); - } [Fact] - public async Task TestImplicitGenericCall() - { - await TestMissingInRegularAndScriptAsync( + public Task TestImplicitGenericCall() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1572,12 +1460,10 @@ void Goo() void Quux(T t) { } } """); - } [Fact] - public async Task TestNullabilityChanges() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNullabilityChanges() + => TestMissingInRegularAndScriptAsync( """ #nullable enable @@ -1614,12 +1500,10 @@ public NotNullIfNotNullAttribute(string parameterName) } } """); - } [Fact] - public async Task TestTrivia1() - { - await TestInRegularAndScriptAsync( + public Task TestTrivia1() + => TestInRegularAndScriptAsync( """ using System; @@ -1648,12 +1532,10 @@ void Bar(Func f) { } string Quux(int i) => default; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63465")] - public async Task TestNotWithPartialDefinition() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithPartialDefinition() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Diagnostics; @@ -1670,12 +1552,10 @@ internal void M1() private static void M2(Action a) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63465")] - public async Task TestWithPartialDefinitionAndImplementation() - { - await TestInRegularAndScriptAsync( + public Task TestWithPartialDefinitionAndImplementation() + => TestInRegularAndScriptAsync( """ using System; using System.Diagnostics; @@ -1710,12 +1590,10 @@ partial void M3(string s) { } private static void M2(Action a) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63464")] - public async Task TestNotWithConditionalAttribute() - { - await TestMissingInRegularAndScriptAsync(""" + public Task TestNotWithConditionalAttribute() + => TestMissingInRegularAndScriptAsync(""" using System; using System.Diagnostics; @@ -1732,12 +1610,10 @@ internal void M3(string s) { } private static void M2(Action a) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69094")] - public async Task TestNotWithAssignmentOfInvokedExpression1() - { - await TestMissingInRegularAndScriptAsync(""" + public Task TestNotWithAssignmentOfInvokedExpression1() + => TestMissingInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; @@ -1759,12 +1635,10 @@ internal Helper(Action action) } """, outputKind: OutputKind.ConsoleApplication); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69094")] - public async Task TestWithoutAssignmentOfInvokedExpression1() - { - await TestInRegularAndScriptAsync(""" + public Task TestWithoutAssignmentOfInvokedExpression1() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; @@ -1806,12 +1680,10 @@ internal Helper(Action action) """, outputKind: OutputKind.ConsoleApplication); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69094")] - public async Task TestNotWithAssignmentOfInvokedExpression2() - { - await TestMissingInRegularAndScriptAsync(""" + public Task TestNotWithAssignmentOfInvokedExpression2() + => TestMissingInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; @@ -1839,12 +1711,10 @@ internal Helper(Action action) } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69094")] - public async Task TestWithoutAssignmentOfInvokedExpression2() - { - await TestInRegularAndScriptAsync(""" + public Task TestWithoutAssignmentOfInvokedExpression2() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; @@ -1897,12 +1767,10 @@ internal Helper(Action action) } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69094")] - public async Task TestWithoutAssignmentOfInvokedExpression3() - { - await TestInRegularAndScriptAsync(""" + public Task TestWithoutAssignmentOfInvokedExpression3() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; @@ -1969,12 +1837,10 @@ internal Helper(Action action) } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71300")] - public async Task TestWithWriteInOtherMethod() - { - await TestInRegularAndScriptAsync(""" + public Task TestWithWriteInOtherMethod() + => TestInRegularAndScriptAsync(""" using System; using System.Linq; @@ -2034,12 +1900,10 @@ public string ToStr(int x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71300")] - public async Task PreserveComment() - { - await TestInRegularAndScriptAsync(""" + public Task PreserveComment() + => TestInRegularAndScriptAsync(""" using System; class C @@ -2074,12 +1938,10 @@ void M2(Action a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66950")] - public async Task TestMissingWithMutableStructs() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWithMutableStructs() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2099,12 +1961,10 @@ struct S public void M() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66950")] - public async Task TestWithNonReadonlyStructAndReadonlyMethod() - { - await TestInRegularAndScriptAsync( + public Task TestWithNonReadonlyStructAndReadonlyMethod() + => TestInRegularAndScriptAsync( """ using System; @@ -2143,12 +2003,10 @@ struct S public readonly void M() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66950")] - public async Task TestWithReadonlyStruct() - { - await TestInRegularAndScriptAsync( + public Task TestWithReadonlyStruct() + => TestInRegularAndScriptAsync( """ using System; @@ -2187,5 +2045,4 @@ readonly struct S public void M() { } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryNullableDirective/CSharpRemoveRedundantNullableDirectiveTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryNullableDirective/CSharpRemoveRedundantNullableDirectiveTests.cs index 375fb405eafab..6c3e05d9ff90c 100644 --- a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryNullableDirective/CSharpRemoveRedundantNullableDirectiveTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryNullableDirective/CSharpRemoveRedundantNullableDirectiveTests.cs @@ -27,9 +27,8 @@ public sealed class CSharpRemoveRedundantNullableDirectiveTests [InlineData(NullableContextOptions.Annotations, NullableContextOptions.Enable)] [InlineData(NullableContextOptions.Warnings, NullableContextOptions.Annotations)] [InlineData(NullableContextOptions.Warnings, NullableContextOptions.Enable)] - public async Task TestRedundantEnableDiffersFromCompilation(NullableContextOptions compilationContext, NullableContextOptions codeContext) - { - await VerifyCodeFixAsync( + public Task TestRedundantEnableDiffersFromCompilation(NullableContextOptions compilationContext, NullableContextOptions codeContext) + => VerifyCodeFixAsync( compilationContext, $$""" #nullable {{GetEnableDirectiveContext(codeContext)}} @@ -44,7 +43,6 @@ class Program { } """); - } [Theory] [InlineData(NullableContextOptions.Annotations, NullableContextOptions.Annotations)] @@ -52,9 +50,8 @@ class Program [InlineData(NullableContextOptions.Enable, NullableContextOptions.Annotations)] [InlineData(NullableContextOptions.Enable, NullableContextOptions.Warnings)] [InlineData(NullableContextOptions.Enable, NullableContextOptions.Enable)] - public async Task TestRedundantEnableMatchesCompilation(NullableContextOptions compilationContext, NullableContextOptions codeContext) - { - await VerifyCodeFixAsync( + public Task TestRedundantEnableMatchesCompilation(NullableContextOptions compilationContext, NullableContextOptions codeContext) + => VerifyCodeFixAsync( compilationContext, $$""" [|#nullable {{GetEnableDirectiveContext(codeContext)}}|] @@ -68,7 +65,6 @@ class Program { } """); - } [Theory] [InlineData(NullableContextOptions.Annotations, NullableContextOptions.Annotations)] @@ -78,9 +74,8 @@ class Program [InlineData(NullableContextOptions.Enable, NullableContextOptions.Annotations)] [InlineData(NullableContextOptions.Enable, NullableContextOptions.Warnings)] [InlineData(NullableContextOptions.Enable, NullableContextOptions.Enable)] - public async Task TestRedundantDisableDiffersFromCompilation(NullableContextOptions compilationContext, NullableContextOptions codeContext) - { - await VerifyCodeFixAsync( + public Task TestRedundantDisableDiffersFromCompilation(NullableContextOptions compilationContext, NullableContextOptions codeContext) + => VerifyCodeFixAsync( compilationContext, $$""" #nullable {{GetDisableDirectiveContext(codeContext)}} @@ -95,7 +90,6 @@ class Program { } """); - } [Theory] [InlineData(NullableContextOptions.Disable, NullableContextOptions.Annotations)] @@ -103,9 +97,8 @@ class Program [InlineData(NullableContextOptions.Disable, NullableContextOptions.Enable)] [InlineData(NullableContextOptions.Annotations, NullableContextOptions.Warnings)] [InlineData(NullableContextOptions.Warnings, NullableContextOptions.Annotations)] - public async Task TestRedundantDisableMatchesCompilation(NullableContextOptions compilationContext, NullableContextOptions codeContext) - { - await VerifyCodeFixAsync( + public Task TestRedundantDisableMatchesCompilation(NullableContextOptions compilationContext, NullableContextOptions codeContext) + => VerifyCodeFixAsync( compilationContext, $$""" [|#nullable {{GetDisableDirectiveContext(codeContext)}}|] @@ -119,7 +112,6 @@ class Program { } """); - } [Theory, CombinatorialData] public async Task TestRedundantRestoreDiffersFromPriorContext(NullableContextOptions compilationContext) @@ -145,9 +137,8 @@ class Program } [Theory, CombinatorialData] - public async Task TestRedundantRestoreMatchesCompilation(NullableContextOptions compilationContext) - { - await VerifyCodeFixAsync( + public Task TestRedundantRestoreMatchesCompilation(NullableContextOptions compilationContext) + => VerifyCodeFixAsync( compilationContext, $$""" [|#nullable restore|] @@ -160,12 +151,10 @@ class Program { } """); - } [Fact] - public async Task TestRedundantDirectiveWithFileHeader() - { - await VerifyCodeFixAsync( + public Task TestRedundantDirectiveWithFileHeader() + => VerifyCodeFixAsync( NullableContextOptions.Enable, """ // File Header @@ -183,12 +172,10 @@ class Program { } """); - } [Fact] - public async Task TestRedundantDirectiveBetweenUsingAndNamespace() - { - await VerifyCodeFixAsync( + public Task TestRedundantDirectiveBetweenUsingAndNamespace() + => VerifyCodeFixAsync( NullableContextOptions.Enable, """ using System; @@ -212,12 +199,10 @@ class MyClass } } """); - } [Fact] - public async Task TestRedundantDirectiveBetweenUsingAndNamespace2() - { - await VerifyCodeFixAsync( + public Task TestRedundantDirectiveBetweenUsingAndNamespace2() + => VerifyCodeFixAsync( NullableContextOptions.Enable, """ using System; @@ -240,12 +225,10 @@ class MyClass } } """); - } [Fact] - public async Task TestRedundantDirectiveBetweenUsingAndNamespace3() - { - await VerifyCodeFixAsync( + public Task TestRedundantDirectiveBetweenUsingAndNamespace3() + => VerifyCodeFixAsync( NullableContextOptions.Enable, """ using System; @@ -268,12 +251,10 @@ class MyClass } } """); - } [Fact] - public async Task TestRedundantDirectiveWithNamespaceAndDerivedType() - { - await VerifyCodeFixAsync( + public Task TestRedundantDirectiveWithNamespaceAndDerivedType() + => VerifyCodeFixAsync( NullableContextOptions.Enable, """ [|#nullable enable|] @@ -298,12 +279,10 @@ class ProgramException : Exception } } """); - } [Fact] - public async Task TestRedundantDirectiveMultiple1() - { - await VerifyCodeFixAsync( + public Task TestRedundantDirectiveMultiple1() + => VerifyCodeFixAsync( NullableContextOptions.Enable, """ using System; @@ -328,12 +307,10 @@ class MyClass } } """); - } [Fact] - public async Task TestRedundantDirectiveMultiple2() - { - await VerifyCodeFixAsync( + public Task TestRedundantDirectiveMultiple2() + => VerifyCodeFixAsync( NullableContextOptions.Enable, """ using System; @@ -359,12 +336,10 @@ class MyClass } } """); - } [Fact] - public async Task TestRedundantDirectiveMultiple3() - { - await VerifyCodeFixAsync( + public Task TestRedundantDirectiveMultiple3() + => VerifyCodeFixAsync( NullableContextOptions.Enable, """ using System; @@ -388,12 +363,10 @@ class MyClass } } """); - } [Fact] - public async Task TestRedundantDirectiveMultiple4() - { - await VerifyCodeFixAsync( + public Task TestRedundantDirectiveMultiple4() + => VerifyCodeFixAsync( NullableContextOptions.Enable, """ using System; @@ -418,12 +391,10 @@ class MyClass } } """); - } [Fact] - public async Task TestRedundantDirectiveMultiple5() - { - await VerifyCodeFixAsync( + public Task TestRedundantDirectiveMultiple5() + => VerifyCodeFixAsync( NullableContextOptions.Enable, """ using System; @@ -447,7 +418,6 @@ class MyClass } } """); - } private static string GetDisableDirectiveContext(NullableContextOptions options) { @@ -471,9 +441,8 @@ private static string GetEnableDirectiveContext(NullableContextOptions options) }; } - private static async Task VerifyCodeFixAsync(NullableContextOptions compilationNullableContextOptions, string source, string fixedSource) - { - await new VerifyCS.Test + private static Task VerifyCodeFixAsync(NullableContextOptions compilationNullableContextOptions, string source, string fixedSource) + => new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, @@ -488,5 +457,4 @@ private static async Task VerifyCodeFixAsync(NullableContextOptions compilationN }, }, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryNullableDirective/CSharpRemoveUnnecessaryNullableDirectiveTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryNullableDirective/CSharpRemoveUnnecessaryNullableDirectiveTests.cs index c0be9a6458b7a..b9656bbb5609d 100644 --- a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryNullableDirective/CSharpRemoveUnnecessaryNullableDirectiveTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryNullableDirective/CSharpRemoveUnnecessaryNullableDirectiveTests.cs @@ -8,6 +8,7 @@ using Microsoft.CodeAnalysis.RemoveUnnecessaryNullableDirective; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; +using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.RemoveUnnecessaryNullableDirective; @@ -27,9 +28,8 @@ public sealed class CSharpRemoveUnnecessaryNullableDirectiveTests [InlineData(NullableContextOptions.Enable, NullableContextOptions.Annotations)] [InlineData(NullableContextOptions.Enable, NullableContextOptions.Warnings)] [InlineData(NullableContextOptions.Enable, NullableContextOptions.Enable)] - public async Task TestUnnecessaryDisableDiffersFromCompilation(NullableContextOptions compilationContext, NullableContextOptions codeContext) - { - await VerifyCodeFixAsync( + public Task TestUnnecessaryDisableDiffersFromCompilation(NullableContextOptions compilationContext, NullableContextOptions codeContext) + => VerifyCodeFixAsync( compilationContext, $$""" [|#nullable {{GetDisableDirectiveContext(codeContext)}}|] @@ -42,12 +42,10 @@ class Program { } """); - } [Fact] - public async Task TestUnnecessaryDisableEnumDeclaration() - { - await VerifyCodeFixAsync( + public Task TestUnnecessaryDisableEnumDeclaration() + => VerifyCodeFixAsync( NullableContextOptions.Enable, """ [|#nullable disable|] @@ -64,12 +62,36 @@ enum EnumName Second, } """); - } + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65401")] + public Task TestUnnecessaryDisableEnumDeclaration_WithAttribute() + => VerifyCodeFixAsync( + NullableContextOptions.Enable, + """ + [|#nullable disable|] + using System; + + [CLSCompliant(false)] + enum EnumName + { + First, + Second, + } + """, + """ + using System; + + [CLSCompliant(false)] + enum EnumName + { + First, + Second, + } + """); [Fact] - public async Task TestUnnecessaryDisableEnumDeclarationWithFileHeader() - { - await VerifyCodeFixAsync( + public Task TestUnnecessaryDisableEnumDeclarationWithFileHeader() + => VerifyCodeFixAsync( NullableContextOptions.Enable, """ // File Header @@ -91,12 +113,10 @@ enum EnumName Second, } """); - } [Fact] - public async Task TestUnnecessaryDirectiveWithNamespaceAndDerivedType() - { - await VerifyCodeFixAsync( + public Task TestUnnecessaryDirectiveWithNamespaceAndDerivedType() + => VerifyCodeFixAsync( NullableContextOptions.Enable, """ [|#nullable disable|] @@ -121,12 +141,10 @@ class ProgramException : Exception } } """); - } [Fact] - public async Task TestUnnecessaryDirectiveWithNamespaceAndDerivedFromQualifiedBaseType() - { - await VerifyCodeFixAsync( + public Task TestUnnecessaryDirectiveWithNamespaceAndDerivedFromQualifiedBaseType() + => VerifyCodeFixAsync( NullableContextOptions.Enable, """ [|#nullable disable|] @@ -147,12 +165,10 @@ class ProgramException : System.Exception } } """); - } [Fact] - public async Task TestUnnecessaryDirectiveWithQualifiedUsingDirectives() - { - await VerifyCodeFixAsync( + public Task TestUnnecessaryDirectiveWithQualifiedUsingDirectives() + => VerifyCodeFixAsync( NullableContextOptions.Enable, """ [|#nullable disable|] @@ -169,14 +185,12 @@ await VerifyCodeFixAsync( using CustomException = System.Exception; using static System.String; """); - } [Theory] [InlineData("disable")] [InlineData("restore")] - public async Task TestUnnecessaryDisableAtEndOfFile(string keyword) - { - await VerifyCodeFixAsync( + public Task TestUnnecessaryDisableAtEndOfFile(string keyword) + => VerifyCodeFixAsync( NullableContextOptions.Disable, $$""" #nullable enable @@ -195,7 +209,6 @@ struct StructName } """); - } [Fact] public async Task TestUnnecessaryDisableIgnoredWhenFollowedByConditionalDirective() @@ -226,9 +239,8 @@ private static string GetDisableDirectiveContext(NullableContextOptions options) }; } - private static async Task VerifyCodeFixAsync(NullableContextOptions compilationNullableContextOptions, string source, string fixedSource) - { - await new VerifyCS.Test + private static Task VerifyCodeFixAsync(NullableContextOptions compilationNullableContextOptions, string source, string fixedSource) + => new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, @@ -243,5 +255,4 @@ private static async Task VerifyCodeFixAsync(NullableContextOptions compilationN }, }, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryParentheses/RemoveUnnecessaryExpressionParenthesesTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryParentheses/RemoveUnnecessaryExpressionParenthesesTests.cs index 29ee35446cc0a..d7d9e3b118e6c 100644 --- a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryParentheses/RemoveUnnecessaryExpressionParenthesesTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryParentheses/RemoveUnnecessaryExpressionParenthesesTests.cs @@ -50,9 +50,8 @@ private static DiagnosticDescription GetRemoveUnnecessaryParenthesesDiagnostic(s => TestHelpers.Diagnostic(IDEDiagnosticIds.RemoveUnnecessaryParenthesesDiagnosticId, text, startLocation: new LinePosition(line, column)); [Fact] - public async Task TestVariableInitializer_TestWithAllOptionsSetToIgnore() - { - await TestMissingAsync( + public Task TestVariableInitializer_TestWithAllOptionsSetToIgnore() + => TestMissingAsync( """ class C { @@ -62,12 +61,10 @@ void M() } } """, new TestParameters(options: IgnoreAllParentheses)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29736")] - public async Task TestVariableInitializer_TestMissingParenthesis() - { - await TestMissingAsync( + public Task TestVariableInitializer_TestMissingParenthesis() + => TestMissingAsync( """ class C { @@ -77,12 +74,10 @@ void M() } } """); - } [Fact] - public async Task TestArithmeticRequiredForClarity1() - { - await TestMissingAsync( + public Task TestArithmeticRequiredForClarity1() + => TestMissingAsync( """ class C { @@ -92,12 +87,10 @@ void M() } } """, new TestParameters(options: RequireArithmeticBinaryParenthesesForClarity)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44629")] - public async Task TestStackAlloc() - { - await TestMissingAsync( + public Task TestStackAlloc() + => TestMissingAsync( """ class C { @@ -107,12 +100,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47365")] - public async Task TestDynamic() - { - await TestMissingAsync( + public Task TestDynamic() + => TestMissingAsync( """ class C { @@ -124,12 +115,10 @@ void M() } } """); - } [Fact] - public async Task TestArithmeticRequiredForClarity2() - { - await TestInRegularAndScript1Async( + public Task TestArithmeticRequiredForClarity2() + => TestInRegularAndScript1Async( """ class C { @@ -148,12 +137,10 @@ void M() } } """, parameters: new TestParameters(options: RequireArithmeticBinaryParenthesesForClarity)); - } [Fact] - public async Task TestLogicalRequiredForClarity1() - { - await TestMissingAsync( + public Task TestLogicalRequiredForClarity1() + => TestMissingAsync( """ class C { @@ -163,12 +150,10 @@ void M() } } """, new TestParameters(options: RequireOtherBinaryParenthesesForClarity)); - } [Fact] - public async Task TestLogicalRequiredForClarity2() - { - await TestInRegularAndScript1Async( + public Task TestLogicalRequiredForClarity2() + => TestInRegularAndScript1Async( """ class C { @@ -187,12 +172,10 @@ void M() } } """, parameters: new TestParameters(options: RequireOtherBinaryParenthesesForClarity)); - } [Fact] - public async Task TestArithmeticNotRequiredForClarityWhenPrecedenceStaysTheSame_Integral1() - { - await TestAsync( + public Task TestArithmeticNotRequiredForClarityWhenPrecedenceStaysTheSame_Integral1() + => TestAsync( """ class C { @@ -211,12 +194,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestArithmeticNotRequiredForClarityWhenPrecedenceStaysTheSame_Integral2() - { - await TestAsync( + public Task TestArithmeticNotRequiredForClarityWhenPrecedenceStaysTheSame_Integral2() + => TestAsync( """ class C { @@ -235,12 +216,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestArithmeticRequiredForCorrectnessWhenPrecedenceStaysTheSameIfFloatingPoint() - { - await TestMissingAsync( + public Task TestArithmeticRequiredForCorrectnessWhenPrecedenceStaysTheSameIfFloatingPoint() + => TestMissingAsync( """ class C { @@ -250,12 +229,10 @@ void M() } } """); - } [Fact] - public async Task TestArithmeticNotRequiredForClarityWhenPrecedenceStaysTheSame_Floating2() - { - await TestAsync( + public Task TestArithmeticNotRequiredForClarityWhenPrecedenceStaysTheSame_Floating2() + => TestAsync( """ class C { @@ -274,12 +251,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestLogicalNotRequiredForClarityWhenPrecedenceStaysTheSame1() - { - await TestAsync( + public Task TestLogicalNotRequiredForClarityWhenPrecedenceStaysTheSame1() + => TestAsync( """ class C { @@ -298,12 +273,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestLogicalNotRequiredForClarityWhenPrecedenceStaysTheSame2() - { - await TestAsync( + public Task TestLogicalNotRequiredForClarityWhenPrecedenceStaysTheSame2() + => TestAsync( """ class C { @@ -322,12 +295,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestVariableInitializer_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() - { - await TestAsync( + public Task TestVariableInitializer_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() + => TestAsync( """ class C { @@ -346,12 +317,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestReturnStatement_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() - { - await TestAsync( + public Task TestReturnStatement_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() + => TestAsync( """ class C { @@ -370,12 +339,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestExpressionBody_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() - { - await TestAsync( + public Task TestExpressionBody_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() + => TestAsync( """ class C { @@ -388,12 +355,10 @@ class C int M() => 1 + 2; } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestCheckedExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() - { - await TestAsync( + public Task TestCheckedExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() + => TestAsync( """ class C { @@ -412,12 +377,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestAssignment_TestAvailableWithAlwaysRemove_And_TestNotAvailableWhenRequiredForClarity() - { - await TestAsync( + public Task TestAssignment_TestAvailableWithAlwaysRemove_And_TestNotAvailableWhenRequiredForClarity() + => TestAsync( """ class C { @@ -436,12 +399,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestCompoundAssignment_TestAvailableWithAlwaysRemove_And_TestNotAvailableWhenRequiredForClarity() - { - await TestAsync( + public Task TestCompoundAssignment_TestAvailableWithAlwaysRemove_And_TestNotAvailableWhenRequiredForClarity() + => TestAsync( """ class C { @@ -460,12 +421,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestPimaryAssignment_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() - { - await TestAsync( + public Task TestPimaryAssignment_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() + => TestAsync( """ class C { @@ -484,12 +443,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestNestedParenthesizedExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() - { - await TestAsync( + public Task TestNestedParenthesizedExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() + => TestAsync( """ class C { @@ -508,12 +465,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true, index: 1); - } [Fact] - public async Task TestIncrementExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() - { - await TestAsync( + public Task TestIncrementExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() + => TestAsync( """ class C { @@ -532,12 +487,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestLambdaBody_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() - { - await TestAsync( + public Task TestLambdaBody_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() + => TestAsync( """ class C { @@ -556,12 +509,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestArrayElement_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() - { - await TestAsync( + public Task TestArrayElement_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() + => TestAsync( """ class C { @@ -580,12 +531,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestWhereClause_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() - { - await TestAsync( + public Task TestWhereClause_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() + => TestAsync( """ class C { @@ -608,12 +557,10 @@ where c.Age > 21 } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestCastExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() - { - await TestAsync( + public Task TestCastExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() + => TestAsync( """ class C { @@ -632,12 +579,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestMissingForConditionalAccess1() - { - await TestMissingAsync( + public Task TestMissingForConditionalAccess1() + => TestMissingAsync( """ class C { @@ -647,12 +592,10 @@ void M(string s) } } """, new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37046")] - public async Task TestMissingForConditionalAccess2() - { - await TestMissingAsync( + public Task TestMissingForConditionalAccess2() + => TestMissingAsync( """ class C { @@ -662,12 +605,10 @@ void M(string s) } } """, new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact] - public async Task TestForConditionalAccessNotInExpression() - { - await TestInRegularAndScriptAsync( + public Task TestForConditionalAccessNotInExpression() + => TestInRegularAndScriptAsync( """ class C { @@ -687,12 +628,10 @@ void M(string s) } } """, options: RemoveAllUnnecessaryParentheses); - } [Fact] - public async Task TestMissingForConditionalIndex() - { - await TestMissingAsync( + public Task TestMissingForConditionalIndex() + => TestMissingAsync( """ class C { @@ -702,12 +641,10 @@ void M(string s) } } """, new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact] - public async Task TestBinaryInCastExpression() - { - await TestMissingAsync( + public Task TestBinaryInCastExpression() + => TestMissingAsync( """ class C { @@ -717,12 +654,10 @@ void M() } } """, new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact] - public async Task TestAroundCastExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() - { - await TestAsync( + public Task TestAroundCastExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() + => TestAsync( """ class C { @@ -741,12 +676,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestConditionalInInterpolation() - { - await TestMissingAsync( + public Task TestConditionalInInterpolation() + => TestMissingAsync( """ class C { @@ -756,12 +689,10 @@ void M() } } """, new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact] - public async Task TestConditionalInInterpolation_FixAll_1() - { - await TestAsync( + public Task TestConditionalInInterpolation_FixAll_1() + => TestAsync( """ class C { @@ -782,12 +713,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestConditionalInInterpolation_FixAll_2() - { - await TestAsync( + public Task TestConditionalInInterpolation_FixAll_2() + => TestAsync( """ class C { @@ -808,12 +737,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestNonConditionalInInterpolation_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() - { - await TestAsync( + public Task TestNonConditionalInInterpolation_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() + => TestAsync( """ class C { @@ -832,12 +759,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestBinaryExpression_TestAvailableWithAlwaysRemove_And_NotAvailableWhenRequiredForClarity_1() - { - await TestAsync( + public Task TestBinaryExpression_TestAvailableWithAlwaysRemove_And_NotAvailableWhenRequiredForClarity_1() + => TestAsync( """ class C { @@ -856,12 +781,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: false); - } [Fact] - public async Task TestBinaryExpression_TestAvailableWithAlwaysRemove_And_NotAvailableWhenRequiredForClarity_2() - { - await TestAsync( + public Task TestBinaryExpression_TestAvailableWithAlwaysRemove_And_NotAvailableWhenRequiredForClarity_2() + => TestAsync( """ class C { @@ -880,12 +803,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: false); - } [Fact] - public async Task TestConditionalExpression_TestNotAvailableForComplexChildren1() - { - await TestMissingAsync( + public Task TestConditionalExpression_TestNotAvailableForComplexChildren1() + => TestMissingAsync( """ class C { @@ -895,12 +816,10 @@ void M() } } """, parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact] - public async Task TestConditionalExpression_TestNotAvailableForComplexChildren2() - { - await TestMissingAsync( + public Task TestConditionalExpression_TestNotAvailableForComplexChildren2() + => TestMissingAsync( """ class C { @@ -910,12 +829,10 @@ void M() } } """, parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact] - public async Task TestConditionalExpression_TestNotAvailableForComplexChildren3() - { - await TestMissingAsync( + public Task TestConditionalExpression_TestNotAvailableForComplexChildren3() + => TestMissingAsync( """ class C { @@ -925,12 +842,10 @@ void M() } } """, parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact] - public async Task TestConditionalExpression_TestAvailableForPrimaryChildren1() - { - await TestAsync( + public Task TestConditionalExpression_TestAvailableForPrimaryChildren1() + => TestAsync( """ class C { @@ -949,12 +864,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestConditionalExpression_TestAvailableForPrimaryChildren2() - { - await TestAsync( + public Task TestConditionalExpression_TestAvailableForPrimaryChildren2() + => TestAsync( """ class C { @@ -973,12 +886,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestConditionalExpression_TestAvailableForPrimaryChildren3() - { - await TestAsync( + public Task TestConditionalExpression_TestAvailableForPrimaryChildren3() + => TestAsync( """ class C { @@ -997,12 +908,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestIsPattern_TestAvailableWithAlwaysRemove_And_NotAvailableWhenRequiredForClarity_1() - { - await TestAsync( + public Task TestIsPattern_TestAvailableWithAlwaysRemove_And_NotAvailableWhenRequiredForClarity_1() + => TestAsync( """ class C { @@ -1021,12 +930,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestIsPattern_TestAvailableWithAlwaysRemove_And_NotAvailableWhenRequiredForClarity_2() - { - await TestAsync( + public Task TestIsPattern_TestAvailableWithAlwaysRemove_And_NotAvailableWhenRequiredForClarity_2() + => TestAsync( """ class C { @@ -1045,12 +952,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: false); - } [Fact] - public async Task TestForOverloadedOperatorOnLeft() - { - await TestInRegularAndScript1Async( + public Task TestForOverloadedOperatorOnLeft() + => TestInRegularAndScript1Async( """ class C { @@ -1073,12 +978,10 @@ void M(C c1, C c2, C c3) public static C operator +(C c1, C c2) => null; } """, parameters: new TestParameters(options: RequireAllParenthesesForClarity)); - } [Fact] - public async Task TestMissingForOverloadedOperatorOnRight() - { - await TestMissingAsync( + public Task TestMissingForOverloadedOperatorOnRight() + => TestMissingAsync( """ class C { @@ -1090,12 +993,10 @@ void M(C c1, C c2, C c3) public static C operator +(C c1, C c2) => null; } """, parameters: new TestParameters(options: RequireAllParenthesesForClarity)); - } [Fact] - public async Task TestShiftRequiredForClarity1() - { - await TestMissingAsync( + public Task TestShiftRequiredForClarity1() + => TestMissingAsync( """ class C { @@ -1105,12 +1006,10 @@ void M() } } """, parameters: new TestParameters(options: RequireArithmeticBinaryParenthesesForClarity)); - } [Fact] - public async Task TestShiftRequiredForClarity2() - { - await TestMissingAsync( + public Task TestShiftRequiredForClarity2() + => TestMissingAsync( """ class C { @@ -1120,12 +1019,10 @@ void M() } } """, parameters: new TestParameters(options: RequireAllParenthesesForClarity)); - } [Fact] - public async Task TestDoNotRemoveShiftAcrossPrecedence() - { - await TestMissingAsync( + public Task TestDoNotRemoveShiftAcrossPrecedence() + => TestMissingAsync( """ class C { @@ -1135,12 +1032,10 @@ void M() } } """, parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact] - public async Task TestRemoveShiftIfNotNecessary2() - { - await TestInRegularAndScript1Async( + public Task TestRemoveShiftIfNotNecessary2() + => TestInRegularAndScript1Async( """ class C { @@ -1159,12 +1054,10 @@ void M() } } """, parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact] - public async Task TestDoNotRemoveShiftAcrossSamePrecedenceIfValueWouldChange() - { - await TestMissingAsync( + public Task TestDoNotRemoveShiftAcrossSamePrecedenceIfValueWouldChange() + => TestMissingAsync( """ class C { @@ -1174,12 +1067,10 @@ void M() } } """, parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact] - public async Task TestDoNotRemoveShiftIfShiftKindDiffers() - { - await TestMissingAsync( + public Task TestDoNotRemoveShiftIfShiftKindDiffers() + => TestMissingAsync( """ class C { @@ -1189,12 +1080,10 @@ void M() } } """, parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact] - public async Task TestRemoveCoalesceIfNotNecessary1() - { - await TestMissingAsync( + public Task TestRemoveCoalesceIfNotNecessary1() + => TestMissingAsync( """ class C { @@ -1204,12 +1093,10 @@ void M() } } """, parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact] - public async Task TestRemoveCoalesceIfNotNecessary2() - { - await TestInRegularAndScript1Async( + public Task TestRemoveCoalesceIfNotNecessary2() + => TestInRegularAndScript1Async( """ class C { @@ -1228,12 +1115,10 @@ void M() } } """, parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact] - public async Task TestBitwiseExpression_TestMissingWithDifferencePrecedence1() - { - await TestMissingAsync( + public Task TestBitwiseExpression_TestMissingWithDifferencePrecedence1() + => TestMissingAsync( """ class C { @@ -1243,12 +1128,10 @@ void M() } } """, new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact] - public async Task TestBitwiseExpression_TestMissingWithDifferencePrecedence2() - { - await TestMissingAsync( + public Task TestBitwiseExpression_TestMissingWithDifferencePrecedence2() + => TestMissingAsync( """ class C { @@ -1258,12 +1141,10 @@ void M() } } """, new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact] - public async Task TestBitwiseExpression_TestAvailableWithSamePrecedenceMissingWithDifferencePrecedence2() - { - await TestAsync( + public Task TestBitwiseExpression_TestAvailableWithSamePrecedenceMissingWithDifferencePrecedence2() + => TestAsync( """ class C { @@ -1282,12 +1163,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25554")] - public async Task TestSwitchCase_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() - { - await TestAsync( + public Task TestSwitchCase_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() + => TestAsync( """ class C { @@ -1312,12 +1191,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25554")] - public async Task TestSwitchCase_WithWhenClause_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() - { - await TestAsync( + public Task TestSwitchCase_WithWhenClause_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() + => TestAsync( """ class C { @@ -1342,12 +1219,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25554")] - public async Task TestWhenClause_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() - { - await TestAsync( + public Task TestWhenClause_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() + => TestAsync( """ class C { @@ -1372,12 +1247,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25554")] - public async Task TestConstantPatternExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() - { - await TestAsync( + public Task TestConstantPatternExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() + => TestAsync( """ class C { @@ -1400,12 +1273,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25554")] - public async Task TestConstantPatternExpression_RequiredForPrecedence() - { - await TestMissingAsync( + public Task TestConstantPatternExpression_RequiredForPrecedence() + => TestMissingAsync( """ class C { @@ -1417,12 +1288,10 @@ void M(string s) } } """, new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact] - public async Task TestCastAmbiguity1() - { - await TestMissingAsync( + public Task TestCastAmbiguity1() + => TestMissingAsync( """ class C { @@ -1432,12 +1301,10 @@ void M() } } """); - } [Fact] - public async Task TestCastAmbiguity2() - { - await TestMissingAsync( + public Task TestCastAmbiguity2() + => TestMissingAsync( """ class C { @@ -1447,12 +1314,10 @@ void M() } } """, new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact] - public async Task TestCastAmbiguity3() - { - await TestMissingAsync( + public Task TestCastAmbiguity3() + => TestMissingAsync( """ class C { @@ -1462,12 +1327,10 @@ void M() } } """, new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact] - public async Task TestCastAmbiguity4() - { - await TestMissingAsync( + public Task TestCastAmbiguity4() + => TestMissingAsync( """ class C { @@ -1477,12 +1340,10 @@ void M() } } """, new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact] - public async Task TestPrimitiveCastNoAmbiguity1() - { - await TestAsync( + public Task TestPrimitiveCastNoAmbiguity1() + => TestAsync( """ class C { @@ -1501,12 +1362,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestPrimitiveCastNoAmbiguity2() - { - await TestAsync( + public Task TestPrimitiveCastNoAmbiguity2() + => TestAsync( """ class C { @@ -1525,12 +1384,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestPrimitiveCastNoAmbiguity3() - { - await TestAsync( + public Task TestPrimitiveCastNoAmbiguity3() + => TestAsync( """ class C { @@ -1549,12 +1406,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestPrimitiveCastNoAmbiguity4() - { - await TestAsync( + public Task TestPrimitiveCastNoAmbiguity4() + => TestAsync( """ class C { @@ -1573,12 +1428,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestArrayCastNoAmbiguity1() - { - await TestAsync( + public Task TestArrayCastNoAmbiguity1() + => TestAsync( """ class C { @@ -1597,12 +1450,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestArrayCastNoAmbiguity2() - { - await TestAsync( + public Task TestArrayCastNoAmbiguity2() + => TestAsync( """ class C { @@ -1621,12 +1472,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestArrayCastNoAmbiguity3() - { - await TestAsync( + public Task TestArrayCastNoAmbiguity3() + => TestAsync( """ class C { @@ -1645,12 +1494,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestArrayCastNoAmbiguity4() - { - await TestAsync( + public Task TestArrayCastNoAmbiguity4() + => TestAsync( """ class C { @@ -1669,12 +1516,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestPointerCastNoAmbiguity1() - { - await TestAsync( + public Task TestPointerCastNoAmbiguity1() + => TestAsync( """ class C { @@ -1693,12 +1538,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestPointerCastNoAmbiguity2() - { - await TestAsync( + public Task TestPointerCastNoAmbiguity2() + => TestAsync( """ class C { @@ -1717,12 +1560,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestPointerCastNoAmbiguity3() - { - await TestAsync( + public Task TestPointerCastNoAmbiguity3() + => TestAsync( """ class C { @@ -1741,12 +1582,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestPointerCastNoAmbiguity4() - { - await TestAsync( + public Task TestPointerCastNoAmbiguity4() + => TestAsync( """ class C { @@ -1765,12 +1604,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestNullableCastNoAmbiguity1() - { - await TestAsync( + public Task TestNullableCastNoAmbiguity1() + => TestAsync( """ class C { @@ -1789,12 +1626,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestNullableCastNoAmbiguity2() - { - await TestAsync( + public Task TestNullableCastNoAmbiguity2() + => TestAsync( """ class C { @@ -1813,12 +1648,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestNullableCastNoAmbiguity3() - { - await TestAsync( + public Task TestNullableCastNoAmbiguity3() + => TestAsync( """ class C { @@ -1837,12 +1670,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestNullableCastNoAmbiguity4() - { - await TestAsync( + public Task TestNullableCastNoAmbiguity4() + => TestAsync( """ class C { @@ -1861,12 +1692,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestAliasCastNoAmbiguity1() - { - await TestAsync( + public Task TestAliasCastNoAmbiguity1() + => TestAsync( """ class C { @@ -1885,12 +1714,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestAliasCastNoAmbiguity2() - { - await TestAsync( + public Task TestAliasCastNoAmbiguity2() + => TestAsync( """ class C { @@ -1909,12 +1736,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestAliasCastNoAmbiguity3() - { - await TestAsync( + public Task TestAliasCastNoAmbiguity3() + => TestAsync( """ class C { @@ -1933,12 +1758,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestAliasCastNoAmbiguity4() - { - await TestAsync( + public Task TestAliasCastNoAmbiguity4() + => TestAsync( """ class C { @@ -1957,12 +1780,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestCastOfPrimary() - { - await TestAsync( + public Task TestCastOfPrimary() + => TestAsync( """ class C { @@ -1981,12 +1802,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestCastOfMemberAccess() - { - await TestAsync( + public Task TestCastOfMemberAccess() + => TestAsync( """ class C { @@ -2005,12 +1824,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestCastOfNonAmbiguousUnary() - { - await TestAsync( + public Task TestCastOfNonAmbiguousUnary() + => TestAsync( """ class C { @@ -2029,12 +1846,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestCastOfCast() - { - await TestAsync( + public Task TestCastOfCast() + => TestAsync( """ class C { @@ -2053,12 +1868,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestIsPatternAndLogical_TestWithAllOptionsSetToIgnore() - { - await TestAsync( + public Task TestIsPatternAndLogical_TestWithAllOptionsSetToIgnore() + => TestAsync( """ class C { @@ -2077,13 +1890,11 @@ void M(object expression) } } """, -offeredWhenRequireForClarityIsEnabled: false); - } + offeredWhenRequireForClarityIsEnabled: false); [Fact] - public async Task TestGuardPatternMissing() - { - await TestMissingAsync( + public Task TestGuardPatternMissing() + => TestMissingAsync( """ class C { @@ -2093,12 +1904,10 @@ void M(object expression) } } """); - } [Fact] - public async Task TestParensAroundLValueMemberAccess() - { - await TestAsync( + public Task TestParensAroundLValueMemberAccess() + => TestAsync( """ class C { @@ -2117,13 +1926,11 @@ void M() } } """, -offeredWhenRequireForClarityIsEnabled: true); - } + offeredWhenRequireForClarityIsEnabled: true); [Fact] - public async Task TestParensAroundMultiplicationInAddEquals() - { - await TestAsync( + public Task TestParensAroundMultiplicationInAddEquals() + => TestAsync( """ class C { @@ -2142,13 +1949,11 @@ void M() } } """, -offeredWhenRequireForClarityIsEnabled: true); - } + offeredWhenRequireForClarityIsEnabled: true); [Fact] - public async Task TestParensAroundAddInMultipleEquals() - { - await TestAsync( + public Task TestParensAroundAddInMultipleEquals() + => TestAsync( """ class C { @@ -2167,13 +1972,11 @@ void M() } } """, -offeredWhenRequireForClarityIsEnabled: true); - } + offeredWhenRequireForClarityIsEnabled: true); [Fact] - public async Task TestNecessaryCast() - { - await TestMissingAsync( + public Task TestNecessaryCast() + => TestMissingAsync( """ class C { @@ -2183,12 +1986,10 @@ void M() } } """); - } [Fact] - public async Task TestParensAroundChecked() - { - await TestAsync( + public Task TestParensAroundChecked() + => TestAsync( """ class C { @@ -2207,13 +2008,11 @@ void M() } } """, -offeredWhenRequireForClarityIsEnabled: true); - } + offeredWhenRequireForClarityIsEnabled: true); [Fact] - public async Task TestParensAroundUnchecked() - { - await TestAsync( + public Task TestParensAroundUnchecked() + => TestAsync( """ class C { @@ -2232,13 +2031,11 @@ void M() } } """, -offeredWhenRequireForClarityIsEnabled: true); - } + offeredWhenRequireForClarityIsEnabled: true); [Fact] - public async Task TestParensAroundNameof() - { - await TestAsync( + public Task TestParensAroundNameof() + => TestAsync( """ class C { @@ -2257,13 +2054,11 @@ void M() } } """, -offeredWhenRequireForClarityIsEnabled: true); - } + offeredWhenRequireForClarityIsEnabled: true); [Fact] - public async Task TestParensIsCheck() - { - await TestAsync( + public Task TestParensIsCheck() + => TestAsync( """ class C { @@ -2282,13 +2077,11 @@ void M() } } """, -offeredWhenRequireForClarityIsEnabled: true); - } + offeredWhenRequireForClarityIsEnabled: true); [Fact] - public async Task TestNecessaryParensAroundIs() - { - await TestMissingAsync( + public Task TestNecessaryParensAroundIs() + => TestMissingAsync( """ class C { @@ -2298,12 +2091,10 @@ void M() } } """); - } [Fact] - public async Task TestParensAroundAssignmentInInitialization() - { - await TestAsync( + public Task TestParensAroundAssignmentInInitialization() + => TestAsync( """ class C { @@ -2324,13 +2115,11 @@ void M() } } """, -offeredWhenRequireForClarityIsEnabled: true); - } + offeredWhenRequireForClarityIsEnabled: true); [Fact] - public async Task TestParensAroundLambda1() - { - await TestAsync( + public Task TestParensAroundLambda1() + => TestAsync( """ class C { @@ -2349,13 +2138,11 @@ void M() } } """, -offeredWhenRequireForClarityIsEnabled: true); - } + offeredWhenRequireForClarityIsEnabled: true); [Fact] - public async Task TestParensAroundLambda2() - { - await TestAsync( + public Task TestParensAroundLambda2() + => TestAsync( """ class C { @@ -2374,13 +2161,11 @@ void M() } } """, -offeredWhenRequireForClarityIsEnabled: true); - } + offeredWhenRequireForClarityIsEnabled: true); [Fact] - public async Task TestParensAroundCastedLambda1() - { - await TestMissingAsync( + public Task TestParensAroundCastedLambda1() + => TestMissingAsync( """ class C { @@ -2390,12 +2175,10 @@ void M() } } """); - } [Fact] - public async Task TestParensAroundCastedLambda2() - { - await TestMissingAsync( + public Task TestParensAroundCastedLambda2() + => TestMissingAsync( """ class C { @@ -2405,12 +2188,10 @@ void M() } } """); - } [Fact] - public async Task TestParensAroundCastedLambda3() - { - await TestMissingAsync( + public Task TestParensAroundCastedLambda3() + => TestMissingAsync( """ class C { @@ -2420,12 +2201,10 @@ void M() } } """); - } [Fact] - public async Task TestParensAroundReturnValue1() - { - await TestAsync( + public Task TestParensAroundReturnValue1() + => TestAsync( """ class C { @@ -2444,13 +2223,11 @@ void M() } } """, -offeredWhenRequireForClarityIsEnabled: true); - } + offeredWhenRequireForClarityIsEnabled: true); [Fact] - public async Task TestParensAroundReturnValue2() - { - await TestAsync( + public Task TestParensAroundReturnValue2() + => TestAsync( """ class C { @@ -2469,13 +2246,11 @@ void M() } } """, -offeredWhenRequireForClarityIsEnabled: true); - } + offeredWhenRequireForClarityIsEnabled: true); [Fact] - public async Task TestParensAroundPPDirective1() - { - await TestAsync( + public Task TestParensAroundPPDirective1() + => TestAsync( """ class C { @@ -2496,14 +2271,11 @@ void M() } } """, -offeredWhenRequireForClarityIsEnabled: true); - } + offeredWhenRequireForClarityIsEnabled: true); [Fact] - public async Task TestParensAroundPPDirective2() - { - // Currently producing broken code. - await TestAsync( + public Task TestParensAroundPPDirective2() + => TestAsync( """ class C { @@ -2524,13 +2296,11 @@ void M() } } """, -offeredWhenRequireForClarityIsEnabled: true, index: 1); - } + offeredWhenRequireForClarityIsEnabled: true, index: 1); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57768")] - public async Task TestParensAroundPPDirective3() - { - await TestAsync( + public Task TestParensAroundPPDirective3() + => TestAsync( """ class C { @@ -2553,13 +2323,11 @@ void M() } } """, -offeredWhenRequireForClarityIsEnabled: true); - } + offeredWhenRequireForClarityIsEnabled: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29454")] - public async Task TestMissingForPreIncrement() - { - await TestMissingAsync( + public Task TestMissingForPreIncrement() + => TestMissingAsync( """ class C { @@ -2569,12 +2337,10 @@ void M(int x) } } """, new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29454")] - public async Task TestMissingForPreDecrement() - { - await TestMissingAsync( + public Task TestMissingForPreDecrement() + => TestMissingAsync( """ class C { @@ -2584,12 +2350,10 @@ void M(int x) } } """, new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29454")] - public async Task TestForPostIncrement() - { - await TestInRegularAndScript1Async( + public Task TestForPostIncrement() + => TestInRegularAndScript1Async( """ class C { @@ -2609,12 +2373,10 @@ void M(int x) } } """, parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29454")] - public async Task TestForPostDecrement() - { - await TestInRegularAndScript1Async( + public Task TestForPostDecrement() + => TestInRegularAndScript1Async( """ class C { @@ -2634,12 +2396,10 @@ void M(int x) } } """, parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29454")] - public async Task TestForPreIncrementInLocalDeclaration() - { - await TestInRegularAndScript1Async( + public Task TestForPreIncrementInLocalDeclaration() + => TestInRegularAndScript1Async( """ class C { @@ -2658,12 +2418,10 @@ void M(int x) } } """, parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29454")] - public async Task TestForPreIncrementInSimpleAssignment() - { - await TestInRegularAndScript1Async( + public Task TestForPreIncrementInSimpleAssignment() + => TestInRegularAndScript1Async( """ class C { @@ -2682,12 +2440,10 @@ void M(int x, int v) } } """, parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29454")] - public async Task TestForPreIncrementInArgument() - { - await TestInRegularAndScript1Async( + public Task TestForPreIncrementInArgument() + => TestInRegularAndScript1Async( """ class C { @@ -2706,12 +2462,10 @@ void M(int x) } } """, parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29454")] - public async Task TestMissingForPreIncrementAfterAdd() - { - await TestMissingAsync( + public Task TestMissingForPreIncrementAfterAdd() + => TestMissingAsync( """ class C { @@ -2721,12 +2475,10 @@ void M(int x) } } """, new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29454")] - public async Task TestMissingForUnaryPlusAfterAdd() - { - await TestMissingAsync( + public Task TestMissingForUnaryPlusAfterAdd() + => TestMissingAsync( """ class C { @@ -2736,12 +2488,10 @@ void M(int x) } } """, new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31103")] - public async Task TestMissingForConditionalRefAsLeftHandSideValue() - { - await TestMissingAsync( + public Task TestMissingForConditionalRefAsLeftHandSideValue() + => TestMissingAsync( """ class Bar { @@ -2751,12 +2501,10 @@ void Foo(bool cond, double a, double b) } } """, new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31103")] - public async Task TestConditionalExpressionAsRightHandSideValue() - { - await TestInRegularAndScript1Async( + public Task TestConditionalExpressionAsRightHandSideValue() + => TestInRegularAndScript1Async( """ class Bar { @@ -2775,13 +2523,11 @@ void Foo(bool cond, double a, double b) } } """, -parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } + parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32085")] - public async Task TestMissingForNestedConditionalExpressionInLambda() - { - await TestMissingAsync( + public Task TestMissingForNestedConditionalExpressionInLambda() + => TestMissingAsync( """ class Bar { @@ -2792,7 +2538,6 @@ void Test(bool a) } } """, new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27925")] public async Task TestUnnecessaryParenthesisDiagnosticSingleLineExpression() @@ -2894,9 +2639,8 @@ void M() } [Fact, WorkItem(27925, "https://github.com/dotnet/roslyn/issues/39363")] - public async Task TestUnnecessaryParenthesesInSwitchExpression() - { - await TestAsync( + public Task TestUnnecessaryParenthesesInSwitchExpression() + => TestAsync( """ class C { @@ -2925,12 +2669,10 @@ void M(int x) }; } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26311")] - public async Task TestUnnecessaryParenthesesAroundDefaultLiteral() - { - await TestAsync( + public Task TestUnnecessaryParenthesesAroundDefaultLiteral() + => TestAsync( """ class C { @@ -2953,12 +2695,10 @@ void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestRangeWithConstantExpression() - { - await TestAsync( + public Task TestRangeWithConstantExpression() + => TestAsync( """ class C { @@ -2977,12 +2717,10 @@ void M(string s) } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestRangeWithMemberAccessExpression() - { - await TestAsync( + public Task TestRangeWithMemberAccessExpression() + => TestAsync( """ class C { @@ -3001,12 +2739,10 @@ void M(string s) } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestRangeWithElementAccessExpression() - { - await TestAsync( + public Task TestRangeWithElementAccessExpression() + => TestAsync( """ class C { @@ -3025,12 +2761,10 @@ void M(string s, int[] indices) } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestRangeWithBinaryExpression() - { - await TestMissingAsync( + public Task TestRangeWithBinaryExpression() + => TestMissingAsync( """ class C { @@ -3040,12 +2774,10 @@ void M(string s) } } """, new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact] - public async Task TestAlwaysUnnecessaryForPrimaryPattern1() - { - await TestAsync( + public Task TestAlwaysUnnecessaryForPrimaryPattern1() + => TestAsync( """ class C { @@ -3064,12 +2796,10 @@ void M(object o) } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestAlwaysUnnecessaryForPrimaryPattern2() - { - await TestAsync( + public Task TestAlwaysUnnecessaryForPrimaryPattern2() + => TestAsync( """ class C { @@ -3088,12 +2818,10 @@ void M(object o) } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50025")] - public async Task TestDoNotRemoveWithConstantAndTypeAmbiguity() - { - await TestMissingAsync( + public Task TestDoNotRemoveWithConstantAndTypeAmbiguity() + => TestMissingAsync( """ public class C { @@ -3107,12 +2835,10 @@ public void M(Goo o) public class Goo { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50025")] - public async Task TestDoRemoveWithNoConstantAndTypeAmbiguity() - { - await TestAsync( + public Task TestDoRemoveWithNoConstantAndTypeAmbiguity() + => TestAsync( """ public class C { @@ -3135,12 +2861,10 @@ public void M(object o) } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestElementAccessOfSuppressedExpression1() - { - await TestAsync( + public Task TestElementAccessOfSuppressedExpression1() + => TestAsync( """ public class C { @@ -3159,12 +2883,10 @@ public void M(string[] Strings) } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestElementAccessOfSuppressedExpression2() - { - await TestAsync( + public Task TestElementAccessOfSuppressedExpression2() + => TestAsync( """ public class C { @@ -3187,12 +2909,10 @@ public void M() } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45100")] - public async Task TestArithmeticOverflow1() - { - await TestMissingAsync( + public Task TestArithmeticOverflow1() + => TestMissingAsync( """ class C { @@ -3205,12 +2925,10 @@ void M(int a) } } """, parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45100")] - public async Task TestArithmeticOverflow1_CompilationOption() - { - await TestMissingAsync( + public Task TestArithmeticOverflow1_CompilationOption() + => TestMissingAsync( """ class C { @@ -3222,12 +2940,10 @@ void M(int a) """, parameters: new TestParameters( options: RemoveAllUnnecessaryParentheses, compilationOptions: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, checkOverflow: true))); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45100")] - public async Task TestArithmeticOverflow2() - { - await TestInRegularAndScript1Async( + public Task TestArithmeticOverflow2() + => TestInRegularAndScript1Async( """ class C { @@ -3246,12 +2962,10 @@ void M(int a) } } """, parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43934")] - public async Task TestTupleArgumentsBecomeGenericSyntax1() - { - await TestInRegularAndScriptAsync( + public Task TestTupleArgumentsBecomeGenericSyntax1() + => TestInRegularAndScriptAsync( """ using System; public class C { @@ -3276,12 +2990,10 @@ public void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43934")] - public async Task TestTupleArgumentsBecomeGenericSyntax2() - { - await TestInRegularAndScriptAsync( + public Task TestTupleArgumentsBecomeGenericSyntax2() + => TestInRegularAndScriptAsync( """ using System; public class C { @@ -3306,12 +3018,10 @@ public void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43934")] - public async Task TestTupleArgumentsBecomeGenericSyntax3() - { - await TestInRegularAndScriptAsync( + public Task TestTupleArgumentsBecomeGenericSyntax3() + => TestInRegularAndScriptAsync( """ using System; public class C { @@ -3336,12 +3046,10 @@ public void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43934")] - public async Task TestTupleArgumentsBecomeGenericSyntax4() - { - await TestInRegularAndScriptAsync( + public Task TestTupleArgumentsBecomeGenericSyntax4() + => TestInRegularAndScriptAsync( """ using System; public class C { @@ -3366,12 +3074,10 @@ public void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43934")] - public async Task TestMethodArgumentsBecomeGenericSyntax1() - { - await TestInRegularAndScriptAsync( + public Task TestMethodArgumentsBecomeGenericSyntax1() + => TestInRegularAndScriptAsync( """ using System; public class C { @@ -3396,12 +3102,10 @@ public void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43934")] - public async Task TestMethodArgumentsBecomeGenericSyntax2() - { - await TestInRegularAndScriptAsync( + public Task TestMethodArgumentsBecomeGenericSyntax2() + => TestInRegularAndScriptAsync( """ using System; public class C { @@ -3426,12 +3130,10 @@ public void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43934")] - public async Task TestMethodArgumentsBecomeGenericSyntax3() - { - await TestInRegularAndScriptAsync( + public Task TestMethodArgumentsBecomeGenericSyntax3() + => TestInRegularAndScriptAsync( """ using System; public class C { @@ -3456,12 +3158,10 @@ public void M() } } """); - } [Fact] - public async Task TestRemoveAroundCollectionExpression() - { - await TestInRegularAndScriptAsync( + public Task TestRemoveAroundCollectionExpression() + => TestInRegularAndScriptAsync( """ class C { @@ -3480,12 +3180,10 @@ void M(bool b) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75203")] - public async Task TestConditionalExpressionInWhenClauseAmbiguity1() - { - await TestMissingAsync( + public Task TestConditionalExpressionInWhenClauseAmbiguity1() + => TestMissingAsync( """ class C { @@ -3499,12 +3197,10 @@ public void M(object o, object?[] c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75203")] - public async Task TestConditionalExpressionInWhenClauseAmbiguity2() - { - await TestInRegularAndScript1Async(""" + public Task TestConditionalExpressionInWhenClauseAmbiguity2() + => TestInRegularAndScript1Async(""" class C { public void M(object o, object?[] c) @@ -3529,12 +3225,10 @@ public void M(object o, object?[] c) } } """); - } [Fact] - public async Task TestCollectionExpressionSpread() - { - await TestInRegularAndScript1Async(""" + public Task TestCollectionExpressionSpread() + => TestInRegularAndScript1Async(""" class C { public void M() @@ -3551,12 +3245,10 @@ public void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78331")] - public async Task TestCollectionExpressionInInitializer() - { - await TestMissingInRegularAndScriptAsync(""" + public Task TestCollectionExpressionInInitializer() + => TestMissingInRegularAndScriptAsync(""" class C { public void M() @@ -3565,12 +3257,10 @@ public void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78331")] - public async Task TestAttributedLambdaExpressionInInitializer() - { - await TestMissingInRegularAndScriptAsync(""" + public Task TestAttributedLambdaExpressionInInitializer() + => TestMissingInRegularAndScriptAsync(""" class C { public void M() @@ -3579,5 +3269,4 @@ public void M() } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryParentheses/RemoveUnnecessaryPatternParenthesesTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryParentheses/RemoveUnnecessaryPatternParenthesesTests.cs index 8dcf0dbcd0a65..a63ddf7637602 100644 --- a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryParentheses/RemoveUnnecessaryPatternParenthesesTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryParentheses/RemoveUnnecessaryPatternParenthesesTests.cs @@ -40,9 +40,8 @@ internal override bool ShouldSkipMessageDescriptionVerification(DiagnosticDescri => descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary) && descriptor.DefaultSeverity == DiagnosticSeverity.Hidden; [Fact] - public async Task TestArithmeticRequiredForClarity2() - { - await TestInRegularAndScript1Async( + public Task TestArithmeticRequiredForClarity2() + => TestInRegularAndScript1Async( """ class C { @@ -61,12 +60,10 @@ void M(object o) } } """, parameters: new TestParameters(options: RequireArithmeticBinaryParenthesesForClarity)); - } [Fact] - public async Task TestLogicalRequiredForClarity1() - { - await TestMissingAsync( + public Task TestLogicalRequiredForClarity1() + => TestMissingAsync( """ class C { @@ -76,12 +73,10 @@ void M(object o) } } """, new TestParameters(options: RequireOtherBinaryParenthesesForClarity)); - } [Fact] - public async Task TestLogicalNotRequiredForClarityWhenPrecedenceStaysTheSame1() - { - await TestAsync( + public Task TestLogicalNotRequiredForClarityWhenPrecedenceStaysTheSame1() + => TestAsync( """ class C { @@ -100,12 +95,10 @@ void M(object o) } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestLogicalNotRequiredForClarityWhenPrecedenceStaysTheSame2() - { - await TestAsync( + public Task TestLogicalNotRequiredForClarityWhenPrecedenceStaysTheSame2() + => TestAsync( """ class C { @@ -124,12 +117,10 @@ void M(object o) } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestAlwaysUnnecessaryForIsPattern() - { - await TestAsync( + public Task TestAlwaysUnnecessaryForIsPattern() + => TestAsync( """ class C { @@ -148,12 +139,10 @@ void M(object o) } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestAlwaysUnnecessaryForCasePattern() - { - await TestAsync( + public Task TestAlwaysUnnecessaryForCasePattern() + => TestAsync( """ class C { @@ -180,12 +169,10 @@ void M(object o) } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestAlwaysUnnecessaryForSwitchArmPattern() - { - await TestAsync( + public Task TestAlwaysUnnecessaryForSwitchArmPattern() + => TestAsync( """ class C { @@ -210,12 +197,10 @@ int M(object o) } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestAlwaysUnnecessaryForSubPattern() - { - await TestAsync( + public Task TestAlwaysUnnecessaryForSubPattern() + => TestAsync( """ class C { @@ -234,12 +219,10 @@ void M(object o) } } """, offeredWhenRequireForClarityIsEnabled: true); - } [Fact] - public async Task TestNotAlwaysUnnecessaryForUnaryPattern1() - { - await TestAsync( + public Task TestNotAlwaysUnnecessaryForUnaryPattern1() + => TestAsync( """ class C { @@ -258,12 +241,10 @@ void M(object o) } } """, offeredWhenRequireForClarityIsEnabled: false); - } [Fact] - public async Task TestNotAlwaysUnnecessaryForUnaryPattern2() - { - await TestAsync( + public Task TestNotAlwaysUnnecessaryForUnaryPattern2() + => TestAsync( """ class C { @@ -282,12 +263,10 @@ void M(object o) } } """, offeredWhenRequireForClarityIsEnabled: false); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52589")] - public async Task TestAlwaysNecessaryForDiscard() - { - await TestDiagnosticMissingAsync( + public Task TestAlwaysNecessaryForDiscard() + => TestDiagnosticMissingAsync( """ class C { @@ -299,12 +278,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestUnnecessaryForDiscardInSubpattern() - { - await TestAsync( + public Task TestUnnecessaryForDiscardInSubpattern() + => TestAsync( """ class C { @@ -327,5 +304,4 @@ void M(object o) } } """, offeredWhenRequireForClarityIsEnabled: true); - } } diff --git a/src/Analyzers/CSharp/Tests/RemoveUnnecessarySuppressions/RemoveUnnecessaryAttributeSuppressionsTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnnecessarySuppressions/RemoveUnnecessaryAttributeSuppressionsTests.cs index 587ca9f17fb14..409cfd9bbe7af 100644 --- a/src/Analyzers/CSharp/Tests/RemoveUnnecessarySuppressions/RemoveUnnecessaryAttributeSuppressionsTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveUnnecessarySuppressions/RemoveUnnecessaryAttributeSuppressionsTests.cs @@ -3,17 +3,19 @@ // See the LICENSE file in the project root for more information. using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CSharp.RemoveUnnecessarySuppressions; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; -using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< - Microsoft.CodeAnalysis.CSharp.RemoveUnnecessarySuppressions.CSharpRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer, - Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions.RemoveUnnecessaryAttributeSuppressionsCodeFixProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnnecessarySuppressions; +using VerifyCS = CSharpCodeFixVerifier< + CSharpRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer, + RemoveUnnecessaryAttributeSuppressionsCodeFixProvider>; + [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessarySuppressions)] [WorkItem("https://github.com/dotnet/roslyn/issues/44176")] public sealed class RemoveUnnecessaryAttributeSuppressionsTests @@ -24,162 +26,280 @@ public void TestStandardProperty(AnalyzerProperty property) [Theory] // Field - [InlineData(@"Scope = ""member""", @"Target = ""~F:N.C.F""", "assembly")] + [InlineData(""" + Scope = "member" + """, """ + Target = "~F:N.C.F" + """, "assembly")] // Property - [InlineData(@"Scope = ""member""", @"Target = ""~P:N.C.P""", "assembly")] + [InlineData(""" + Scope = "member" + """, """ + Target = "~P:N.C.P" + """, "assembly")] // Method - [InlineData(@"Scope = ""member""", @"Target = ""~M:N.C.M()""", "assembly")] + [InlineData(""" + Scope = "member" + """, """ + Target = "~M:N.C.M()" + """, "assembly")] // Type - [InlineData(@"Scope = ""member""", @"Target = ""~T:N.C""", "assembly")] + [InlineData(""" + Scope = "member" + """, """ + Target = "~T:N.C" + """, "assembly")] // Namespace - [InlineData(@"Scope = ""namespace""", @"Target = ""~N:N""", "assembly")] + [InlineData(""" + Scope = "namespace" + """, """ + Target = "~N:N" + """, "assembly")] // NamespaceAndDescendants - [InlineData(@"Scope = ""namespaceanddescendants""", @"Target = ""~N:N""", "assembly")] + [InlineData(""" + Scope = "namespaceanddescendants" + """, """ + Target = "~N:N" + """, "assembly")] // Module - no scope, no target [InlineData(null, null, "assembly")] // Module - no target - [InlineData(@"Scope = ""module""", null, "assembly")] + [InlineData(""" + Scope = "module" + """, null, "assembly")] // Module - null target - [InlineData(@"Scope = ""module""", @"Target = null", "assembly")] + [InlineData(""" + Scope = "module" + """, @"Target = null", "assembly")] // Resource - not handled - [InlineData(@"Scope = ""resource""", @"Target = """"", "assembly")] + [InlineData(""" + Scope = "resource" + """, """ + Target = "" + """, "assembly")] // 'module' attribute target - [InlineData(@"Scope = ""member""", @"Target = ""~M:N.C.M()""", "module")] + [InlineData(""" + Scope = "member" + """, """ + Target = "~M:N.C.M()" + """, "module")] // Member with non-matching scope (seems to be respected by suppression decoder) - [InlineData(@"Scope = ""type""", @"Target = ""~M:N.C.M()""", "assembly")] - [InlineData(@"Scope = ""namespace""", @"Target = ""~F:N.C.F""", "assembly")] + [InlineData(""" + Scope = "type" + """, """ + Target = "~M:N.C.M()" + """, "assembly")] + [InlineData(""" + Scope = "namespace" + """, """ + Target = "~F:N.C.F" + """, "assembly")] // Case insensitive scope - [InlineData(@"Scope = ""Member""", @"Target = ""~F:N.C.F""", "assembly")] - [InlineData(@"Scope = ""MEMBER""", @"Target = ""~F:N.C.F""", "assembly")] + [InlineData(""" + Scope = "Member" + """, """ + Target = "~F:N.C.F" + """, "assembly")] + [InlineData(""" + Scope = "MEMBER" + """, """ + Target = "~F:N.C.F" + """, "assembly")] public async Task ValidSuppressions(string? scope, string? target, string attributeTarget) { var scopeString = scope != null ? $@", {scope}" : string.Empty; var targetString = target != null ? $@", {target}" : string.Empty; - var input = $@" -[{attributeTarget}: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Justification = ""Pending""{scopeString}{targetString})] - -namespace N -{{ - class C - {{ - public int F; - public int P {{ get; }} - public void M() {{ }} - }} -}}"; + var input = $$""" + + [{{attributeTarget}}: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "Id: Title", Justification = "Pending"{{scopeString}}{{targetString}})] + + namespace N + { + class C + { + public int F; + public int P { get; } + public void M() { } + } + } + """; await VerifyCS.VerifyCodeFixAsync(input, input); } [Theory] // Field - no matching symbol - [InlineData(@"Scope = ""member""", @"Target = ""~F:N.C.F2""", "assembly")] + [InlineData(""" + Scope = "member" + """, """ + Target = "~F:N.C.F2" + """, "assembly")] // Field - no matching symbol (case insensitive) - [InlineData(@"Scope = ""Member""", @"Target = ""~F:N.C.F2""", "assembly")] - [InlineData(@"Scope = ""MEMBER""", @"Target = ""~F:N.C.F2""", "assembly")] + [InlineData(""" + Scope = "Member" + """, """ + Target = "~F:N.C.F2" + """, "assembly")] + [InlineData(""" + Scope = "MEMBER" + """, """ + Target = "~F:N.C.F2" + """, "assembly")] // Property - invalid scope - [InlineData(@"Scope = ""invalid""", @"Target = ""~P:N.C.P""", "assembly")] + [InlineData(""" + Scope = "invalid" + """, """ + Target = "~P:N.C.P" + """, "assembly")] // Method - wrong signature - [InlineData(@"Scope = ""member""", @"Target = ""~M:N.C.M(System.Int32)""", "assembly")] + [InlineData(""" + Scope = "member" + """, """ + Target = "~M:N.C.M(System.Int32)" + """, "assembly")] // Method - module scope - [InlineData(@"Scope = ""module""", @"Target = ""~M:N.C.M()""", "assembly")] + [InlineData(""" + Scope = "module" + """, """ + Target = "~M:N.C.M()" + """, "assembly")] // Method - null scope - [InlineData(@"Scope = null", @"Target = ""~M:N.C.M()""", "assembly")] + [InlineData(@"Scope = null", """ + Target = "~M:N.C.M()" + """, "assembly")] // Method - no scope - [InlineData(null, @"Target = ""~M:N.C.M()""", "assembly")] + [InlineData(null, """ + Target = "~M:N.C.M()" + """, "assembly")] // Member scope - null target - [InlineData(@"Scope = ""member""", @"Target = null", "assembly")] + [InlineData(""" + Scope = "member" + """, @"Target = null", "assembly")] // Member scope - no target - [InlineData(@"Scope = ""member""", null, "assembly")] + [InlineData(""" + Scope = "member" + """, null, "assembly")] // Type - no matching namespace - [InlineData(@"Scope = ""type""", @"Target = ""~T:N2.C""", "assembly")] + [InlineData(""" + Scope = "type" + """, """ + Target = "~T:N2.C" + """, "assembly")] // Namespace - extra namespace qualification - [InlineData(@"Scope = ""namespace""", @"Target = ""~N:N.N2""", "assembly")] + [InlineData(""" + Scope = "namespace" + """, """ + Target = "~N:N.N2" + """, "assembly")] // NamespaceAndDescendants - empty target - [InlineData(@"Scope = ""namespaceanddescendants""", @"Target = """"", "assembly")] + [InlineData(""" + Scope = "namespaceanddescendants" + """, """ + Target = "" + """, "assembly")] // Module - no scope, empty target - [InlineData(null, @"Target = """"", "assembly")] + [InlineData(null, """ + Target = "" + """, "assembly")] // Module - no scope, non-empty target - [InlineData(null, @"Target = ""~T:N.C""", "assembly")] + [InlineData(null, """ + Target = "~T:N.C" + """, "assembly")] // Module scope, empty target - [InlineData(@"Scope = ""module""", @"Target = """"", "assembly")] + [InlineData(""" + Scope = "module" + """, """ + Target = "" + """, "assembly")] // Module no scope, non-empty target - [InlineData(@"Scope = ""module""", @"Target = ""~T:N.C""", "assembly")] + [InlineData(""" + Scope = "module" + """, """ + Target = "~T:N.C" + """, "assembly")] public async Task InvalidSuppressions(string? scope, string? target, string attributeTarget) { var scopeString = scope != null ? $@", {scope}" : string.Empty; var targetString = target != null ? $@", {target}" : string.Empty; + await VerifyCS.VerifyCodeFixAsync($$""" + + [{{attributeTarget}}: [|System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "Id: Title", Justification = "Pending"{{scopeString}}{{targetString}})|]] - var input = $@" -[{attributeTarget}: [|System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Justification = ""Pending""{scopeString}{targetString})|]] - -namespace N -{{ - class C - {{ - public int F; - public int P {{ get; }} - public void M() {{ }} - }} -}}"; - - var fixedCode = $@" - -namespace N -{{ - class C - {{ - public int F; - public int P {{ get; }} - public void M() {{ }} - }} -}}"; - await VerifyCS.VerifyCodeFixAsync(input, fixedCode); + namespace N + { + class C + { + public int F; + public int P { get; } + public void M() { } + } + } + """, $$""" + + + namespace N + { + class C + { + public int F; + public int P { get; } + public void M() { } + } + } + """); } [Fact] public async Task ValidAndInvalidSuppressions() { - var attributePrefix = @"System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Justification = ""Pending"""; + var attributePrefix = """ + System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "Id: Title", Justification = "Pending" + """; var validSuppression = $@"{attributePrefix}, Scope = ""member"", Target = ""~T:C"")"; var invalidSuppression = $@"[|{attributePrefix}, Scope = ""member"", Target = """")|]"; + await VerifyCS.VerifyCodeFixAsync($$""" + + [assembly: {{validSuppression}}] + [assembly: {{invalidSuppression}}] + [assembly: {{validSuppression}}, {{validSuppression}}] + [assembly: {{invalidSuppression}}, {{invalidSuppression}}] + [assembly: {{validSuppression}}, {{invalidSuppression}}] + [assembly: {{invalidSuppression}}, {{validSuppression}}] + [assembly: {{invalidSuppression}}, {{validSuppression}}, {{invalidSuppression}}, {{validSuppression}}] - var input = $@" -[assembly: {validSuppression}] -[assembly: {invalidSuppression}] -[assembly: {validSuppression}, {validSuppression}] -[assembly: {invalidSuppression}, {invalidSuppression}] -[assembly: {validSuppression}, {invalidSuppression}] -[assembly: {invalidSuppression}, {validSuppression}] -[assembly: {invalidSuppression}, {validSuppression}, {invalidSuppression}, {validSuppression}] - -class C {{ }} -"; - - var fixedCode = $@" -[assembly: {validSuppression}] -[assembly: {validSuppression}, {validSuppression}] -[assembly: {validSuppression}] -[assembly: {validSuppression}] -[assembly: {validSuppression}, {validSuppression}] - -class C {{ }} -"; - await VerifyCS.VerifyCodeFixAsync(input, fixedCode); + class C { } + + """, $$""" + + [assembly: {{validSuppression}}] + [assembly: {{validSuppression}}, {{validSuppression}}] + [assembly: {{validSuppression}}] + [assembly: {{validSuppression}}] + [assembly: {{validSuppression}}, {{validSuppression}}] + + class C { } + + """); } [Theory] [InlineData("")] - [InlineData(@", Scope = ""member"", Target = ""~M:C.M()""")] - [InlineData(@", Scope = ""invalid"", Target = ""invalid""")] + [InlineData(""" + , Scope = "member", Target = "~M:C.M()" + """)] + [InlineData(""" + , Scope = "invalid", Target = "invalid" + """)] public async Task LocalSuppressions(string scopeAndTarget) { - var input = $@" -[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Justification = ""Pending""{scopeAndTarget})] -class C -{{ - public void M() {{ }} -}}"; + var input = $$""" + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "Id: Title", Justification = "Pending"{{scopeAndTarget}})] + class C + { + public void M() { } + } + """; await VerifyCS.VerifyCodeFixAsync(input, input); } @@ -187,13 +307,15 @@ public void M() {{ }} public async Task LegacyModeGlobalSuppressionWithNamespaceAndDescendantsScope() { var target = "N:N.InvalidChild"; - var input = $@" -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Scope = ""namespaceanddescendants"", Target = {{|#0:""{target}""|}})] + var input = $$""" + + [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "Id: Title", Scope = "namespaceanddescendants", Target = {|#0:"{{target}}"|})] -namespace N -{{ - class C {{ }} -}}"; + namespace N + { + class C { } + } + """; var expectedDiagnostic = VerifyCS.Diagnostic(AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer.LegacyFormatTargetDescriptor) .WithLocation(0) .WithArguments(target); diff --git a/src/Analyzers/CSharp/Tests/RemoveUnreachableCode/RemoveUnreachableCodeTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnreachableCode/RemoveUnreachableCodeTests.cs index b5f8797d81f02..03721d3185db8 100644 --- a/src/Analyzers/CSharp/Tests/RemoveUnreachableCode/RemoveUnreachableCodeTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveUnreachableCode/RemoveUnreachableCodeTests.cs @@ -18,9 +18,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnreachableCode; public sealed class RemoveUnreachableCodeTests { [Fact] - public async Task TestSingleUnreachableStatement() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestSingleUnreachableStatement() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -40,12 +39,10 @@ void M() } } """); - } [Fact] - public async Task TestInUnreachableIfBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestInUnreachableIfBody() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -69,12 +66,10 @@ void M() } } """); - } [Fact] - public async Task TestInIfWithNoBlock() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestInIfWithNoBlock() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -96,12 +91,10 @@ void M() } } """); - } [Fact] - public async Task TestRemoveSubsequentStatements() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestRemoveSubsequentStatements() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -122,12 +115,10 @@ void M() } } """); - } [Fact] - public async Task TestFromSubsequentStatement() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFromSubsequentStatement() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -148,12 +139,10 @@ void M() } } """); - } [Fact] - public async Task TestRemoveSubsequentStatementsExcludingLocalFunction() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestRemoveSubsequentStatementsExcludingLocalFunction() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -179,12 +168,10 @@ void Local() {} } } """); - } [Fact] - public async Task TestRemoveSubsequentStatementsExcludingMultipleLocalFunctions() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestRemoveSubsequentStatementsExcludingMultipleLocalFunctions() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -212,12 +199,10 @@ void Local2() {} } } """); - } [Fact] - public async Task TestRemoveSubsequentStatementsInterspersedWithMultipleLocalFunctions() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestRemoveSubsequentStatementsInterspersedWithMultipleLocalFunctions() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -249,12 +234,10 @@ void Local2() {} } } """); - } [Fact] - public async Task TestRemoveSubsequentStatementsInterspersedWithMultipleLocalFunctions2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestRemoveSubsequentStatementsInterspersedWithMultipleLocalFunctions2() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -287,12 +270,10 @@ void Local2() {} } } """); - } [Fact] - public async Task TestRemoveSubsequentStatementsUpToNextLabel() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestRemoveSubsequentStatementsUpToNextLabel() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -317,12 +298,10 @@ void M() } } """); - } [Fact] - public async Task TestOnUnreachableLabel() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestOnUnreachableLabel() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -347,12 +326,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingOnReachableLabel() - { - var code = """ + public Task TestMissingOnReachableLabel() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M(object o) @@ -371,8 +348,7 @@ void M(object o) var y = 1; } } - """; - var fixedCode = """ + """, """ class C { void M(object o) @@ -390,14 +366,11 @@ void M(object o) var y = 1; } } - """; - await VerifyCS.VerifyCodeFixAsync(code, fixedCode); - } + """); [Fact] - public async Task TestInLambda() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestInLambda() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -428,12 +401,10 @@ void M() } } """); - } [Fact] - public async Task TestInLambdaInExpressionBody() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestInLambdaInExpressionBody() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -460,12 +431,10 @@ Action M() }; } """); - } [Fact] - public async Task TestSingleRemovalDoesNotTouchCodeInUnrelatedLocalFunction() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestSingleRemovalDoesNotTouchCodeInUnrelatedLocalFunction() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -496,12 +465,10 @@ void Local() } } """); - } [Fact] - public async Task TestFixAll1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFixAll1() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -532,12 +499,10 @@ void Local() } } """); - } [Fact] - public async Task TestFixAll2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFixAll2() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -576,12 +541,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestFixAll3() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFixAll3() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -631,12 +594,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestFixAll4() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFixAll4() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -676,12 +637,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestFixAll5() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFixAll5() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -707,12 +666,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestInUnreachableInSwitchSection1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestInUnreachableInSwitchSection1() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -741,12 +698,10 @@ void M(int i) } } """); - } [Fact] - public async Task TestDirectives1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestDirectives1() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -772,12 +727,10 @@ void M() } } """); - } [Fact] - public async Task TestDirectives2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestDirectives2() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -801,12 +754,10 @@ void M() } } """); - } [Fact] - public async Task TestDirectives3() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestDirectives3() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -831,12 +782,10 @@ void M() } } """); - } [Fact] - public async Task TestForLoop1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestForLoop1() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -869,12 +818,10 @@ void M() } } """); - } [Fact] - public async Task TestInfiniteForLoop() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestInfiniteForLoop() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -894,84 +841,76 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61810")] - public async Task TestTopLevel_EndingWithNewLine() - { - var code = """ + public Task TestTopLevel_EndingWithNewLine() + => new VerifyCS.Test + { + TestState = + { + OutputKind = OutputKind.ConsoleApplication, + }, + TestCode = """ throw new System.Exception(); [|System.Console.ReadLine(); |] - """; - var fixedCode = """ + """, + FixedCode = """ throw new System.Exception(); - """; - await new VerifyCS.Test + """, + LanguageVersion = LanguageVersion.CSharp9, + }.RunAsync(); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61810")] + public Task TestTopLevel_NotEndingWithNewLine() + => new VerifyCS.Test { TestState = { OutputKind = OutputKind.ConsoleApplication, }, - TestCode = code, - FixedCode = fixedCode, - LanguageVersion = LanguageVersion.CSharp9, - }.RunAsync(); - } - - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61810")] - public async Task TestTopLevel_NotEndingWithNewLine() - { - var code = """ + TestCode = """ throw new System.Exception(); [|System.Console.ReadLine();|] - """; - var fixedCode = """ + """, + FixedCode = """ throw new System.Exception(); - """; - await new VerifyCS.Test + """, + LanguageVersion = LanguageVersion.CSharp9, + }.RunAsync(); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61810")] + public Task TestTopLevel_MultipleUnreachableStatements() + => new VerifyCS.Test { TestState = { OutputKind = OutputKind.ConsoleApplication, }, - TestCode = code, - FixedCode = fixedCode, - LanguageVersion = LanguageVersion.CSharp9, - }.RunAsync(); - } - - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61810")] - public async Task TestTopLevel_MultipleUnreachableStatements() - { - var code = """ + TestCode = """ throw new System.Exception(); [|System.Console.ReadLine(); |][|System.Console.ReadLine(); |] - """; - var fixedCode = """ + """, + FixedCode = """ throw new System.Exception(); - """; - await new VerifyCS.Test + """, + LanguageVersion = LanguageVersion.CSharp9, + }.RunAsync(); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61810")] + public Task TestTopLevel_MultipleUnreachableStatements_HasClassDeclarationInBetween() + => new VerifyCS.Test { TestState = { OutputKind = OutputKind.ConsoleApplication, }, - TestCode = code, - FixedCode = fixedCode, - LanguageVersion = LanguageVersion.CSharp9, - }.RunAsync(); - } - - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61810")] - public async Task TestTopLevel_MultipleUnreachableStatements_HasClassDeclarationInBetween() - { - var code = """ + TestCode = """ throw new System.Exception(); [|System.Console.ReadLine(); |] @@ -979,85 +918,67 @@ public async Task TestTopLevel_MultipleUnreachableStatements_HasClassDeclaration public class C { } [| {|CS8803:System.Console.ReadLine();|}|] - """; - var fixedCode = """ + """, + FixedCode = """ throw new System.Exception(); public class C { } - """; - await new VerifyCS.Test + """, + LanguageVersion = LanguageVersion.CSharp9, + }.RunAsync(); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61810")] + public Task TestTopLevel_MultipleUnreachableStatements_AfterClassDeclaration1() + => new VerifyCS.Test { TestState = { OutputKind = OutputKind.ConsoleApplication, }, - TestCode = code, - FixedCode = fixedCode, - LanguageVersion = LanguageVersion.CSharp9, - }.RunAsync(); - } - - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61810")] - public async Task TestTopLevel_MultipleUnreachableStatements_AfterClassDeclaration1() - { - var code = """ + TestCode = """ throw new System.Exception(); public class C { } [| {|CS8803:System.Console.ReadLine();|}|] - """; - var fixedCode = """ + """, + FixedCode = """ throw new System.Exception(); public class C { } - """; - await new VerifyCS.Test + """, + LanguageVersion = LanguageVersion.CSharp9, + }.RunAsync(); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61810")] + public Task TestTopLevel_MultipleUnreachableStatements_AfterClassDeclaration2() + => new VerifyCS.Test { TestState = { OutputKind = OutputKind.ConsoleApplication, }, - TestCode = code, - FixedCode = fixedCode, - LanguageVersion = LanguageVersion.CSharp9, - }.RunAsync(); - } - - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61810")] - public async Task TestTopLevel_MultipleUnreachableStatements_AfterClassDeclaration2() - { - var code = """ + TestCode = """ public class C { } {|CS8803:throw new System.Exception();|} [|System.Console.ReadLine();|] - """; - var fixedCode = """ + """, + FixedCode = """ public class C { } {|CS8803:throw new System.Exception();|} - """; - await new VerifyCS.Test - { - TestState = - { - OutputKind = OutputKind.ConsoleApplication, - }, - TestCode = code, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72024")] - public async Task TestIncompleteBinaryExpression() - { - await new VerifyCS.Test + public Task TestIncompleteBinaryExpression() + => new VerifyCS.Test { TestCode = """ public class C { } @@ -1077,5 +998,4 @@ public class C { } }, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/RemoveUnusedLocalFunction/RemoveUnusedLocalFunctionTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnusedLocalFunction/RemoveUnusedLocalFunctionTests.cs index 5eca64bc62512..39bc16c63f7cf 100644 --- a/src/Analyzers/CSharp/Tests/RemoveUnusedLocalFunction/RemoveUnusedLocalFunctionTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveUnusedLocalFunction/RemoveUnusedLocalFunctionTests.cs @@ -27,9 +27,8 @@ internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProvide => (null, new CSharpRemoveUnusedLocalFunctionCodeFixProvider()); [Fact] - public async Task RemoveUnusedLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnusedLocalFunction() + => TestInRegularAndScriptAsync( """ class Class { @@ -47,12 +46,10 @@ void Method() } } """); - } [Fact] - public async Task RemoveUnusedLocalFunctionFixAll1() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnusedLocalFunctionFixAll1() + => TestInRegularAndScriptAsync( """ class Class { @@ -71,12 +68,10 @@ void Method() } } """); - } [Fact] - public async Task RemoveUnusedLocalFunctionFixAll2() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnusedLocalFunctionFixAll2() + => TestInRegularAndScriptAsync( """ class Class { @@ -95,12 +90,10 @@ void Method() } } """); - } [Fact] - public async Task RemoveUnusedLocalFunctionFixAll3() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnusedLocalFunctionFixAll3() + => TestInRegularAndScriptAsync( """ class Class { @@ -118,12 +111,10 @@ void Method() } } """); - } [Fact] - public async Task RemoveUnusedLocalFunctionFixAll4() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnusedLocalFunctionFixAll4() + => TestInRegularAndScriptAsync( """ class Class { @@ -141,16 +132,13 @@ void Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44272")] - public async Task TopLevelStatement() - { - await TestAsync(""" + public Task TopLevelStatement() + => TestAsync(""" void [|local()|] { } """, """ """, TestOptions.Regular); - } } diff --git a/src/Analyzers/CSharp/Tests/RemoveUnusedMembers/RemoveUnusedMembersTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnusedMembers/RemoveUnusedMembersTests.cs index 2fd814622f87c..413f8177072c7 100644 --- a/src/Analyzers/CSharp/Tests/RemoveUnusedMembers/RemoveUnusedMembersTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveUnusedMembers/RemoveUnusedMembersTests.cs @@ -27,9 +27,8 @@ public void TestStandardProperty(AnalyzerProperty property) => VerifyCS.VerifyStandardProperty(property); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31582")] - public async Task FieldReadViaSuppression() - { - await new VerifyCS.Test + public Task FieldReadViaSuppression() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -43,7 +42,6 @@ public void M() } """ }.RunAsync(); - } [Theory] [InlineData("public")] @@ -51,9 +49,8 @@ public void M() [InlineData("protected")] [InlineData("protected internal")] [InlineData("private protected")] - public async Task NonPrivateField(string accessibility) - { - await new VerifyCS.Test + public Task NonPrivateField(string accessibility) + => new VerifyCS.Test { TestCode = $$""" class MyClass @@ -63,17 +60,14 @@ class MyClass """, }.RunAsync(); - } - [Theory] [InlineData("public")] [InlineData("internal")] [InlineData("protected")] [InlineData("protected internal")] [InlineData("private protected")] - public async Task NonPrivateFieldWithConstantInitializer(string accessibility) - { - await new VerifyCS.Test + public Task NonPrivateFieldWithConstantInitializer(string accessibility) + => new VerifyCS.Test { TestCode = $$""" class MyClass @@ -82,7 +76,6 @@ class MyClass } """, }.RunAsync(); - } [Theory] [InlineData("public")] @@ -90,9 +83,8 @@ class MyClass [InlineData("protected")] [InlineData("protected internal")] [InlineData("private protected")] - public async Task NonPrivateFieldWithNonConstantInitializer(string accessibility) - { - await new VerifyCS.Test + public Task NonPrivateFieldWithNonConstantInitializer(string accessibility) + => new VerifyCS.Test { TestCode = $$""" class MyClass @@ -102,7 +94,6 @@ class MyClass } """, }.RunAsync(); - } [Theory] [InlineData("public")] @@ -180,9 +171,8 @@ class MyClass } [Fact] - public async Task FieldIsUnused() - { - await VerifyCS.VerifyCodeFixAsync( + public Task FieldIsUnused() + => VerifyCS.VerifyCodeFixAsync( """ class MyClass { @@ -194,12 +184,10 @@ class MyClass { } """); - } [Fact] - public async Task MethodIsUnused() - { - await VerifyCS.VerifyCodeFixAsync( + public Task MethodIsUnused() + => VerifyCS.VerifyCodeFixAsync( """ class MyClass { @@ -211,12 +199,10 @@ class MyClass { } """); - } [Fact] - public async Task GenericMethodIsUnused() - { - await VerifyCS.VerifyCodeFixAsync( + public Task GenericMethodIsUnused() + => VerifyCS.VerifyCodeFixAsync( """ class MyClass { @@ -228,12 +214,10 @@ class MyClass { } """); - } [Fact] - public async Task MethodInGenericTypeIsUnused() - { - await VerifyCS.VerifyCodeFixAsync( + public Task MethodInGenericTypeIsUnused() + => VerifyCS.VerifyCodeFixAsync( """ class MyClass { @@ -245,7 +229,6 @@ class MyClass { } """); - } [Fact] public async Task InstanceConstructorIsUnused_NoArguments() @@ -262,9 +245,8 @@ private MyClass() { } } [Fact] - public async Task InstanceConstructorIsUnused_WithArguments() - { - await VerifyCS.VerifyCodeFixAsync( + public Task InstanceConstructorIsUnused_WithArguments() + => VerifyCS.VerifyCodeFixAsync( """ class MyClass { @@ -276,7 +258,6 @@ class MyClass { } """); - } [Fact] public async Task StaticConstructorIsNotFlagged() @@ -305,9 +286,8 @@ class MyClass } [Fact] - public async Task PropertyIsUnused() - { - await VerifyCS.VerifyCodeFixAsync( + public Task PropertyIsUnused() + => VerifyCS.VerifyCodeFixAsync( """ class MyClass { @@ -319,12 +299,10 @@ class MyClass { } """); - } [Fact] - public async Task IndexerIsUnused() - { - await VerifyCS.VerifyCodeFixAsync( + public Task IndexerIsUnused() + => VerifyCS.VerifyCodeFixAsync( """ class MyClass { @@ -336,12 +314,10 @@ class MyClass { } """); - } [Fact] - public async Task EventIsUnused() - { - await VerifyCS.VerifyCodeFixAsync( + public Task EventIsUnused() + => VerifyCS.VerifyCodeFixAsync( """ class MyClass { @@ -353,7 +329,6 @@ class MyClass { } """); - } [Fact] public async Task EntryPointMethodNotFlagged() @@ -429,15 +404,12 @@ class MyClass } [Fact] - public async Task EntryPointMethodNotFlagged_06() - { - var code = """ - return 0; - """; - - await new VerifyCS.Test + public Task EntryPointMethodNotFlagged_06() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + return 0; + """, ExpectedDiagnostics = { // /0/Test0.cs(2,1): error CS8805: Program using top-level statements must be an executable. @@ -445,7 +417,6 @@ public async Task EntryPointMethodNotFlagged_06() }, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] public async Task EntryPointMethodNotFlagged_07() @@ -522,9 +493,8 @@ public async Task EntryPointMethodNotFlagged_09() } [Fact] - public async Task FieldIsUnused_ReadOnly() - { - await VerifyCS.VerifyCodeFixAsync( + public Task FieldIsUnused_ReadOnly() + => VerifyCS.VerifyCodeFixAsync( """ class MyClass { @@ -536,12 +506,10 @@ class MyClass { } """); - } [Fact] - public async Task PropertyIsUnused_ReadOnly() - { - await VerifyCS.VerifyCodeFixAsync( + public Task PropertyIsUnused_ReadOnly() + => VerifyCS.VerifyCodeFixAsync( """ class MyClass { @@ -553,12 +521,10 @@ class MyClass { } """); - } [Fact] - public async Task EventIsUnused_ReadOnly() - { - await VerifyCS.VerifyCodeFixAsync( + public Task EventIsUnused_ReadOnly() + => VerifyCS.VerifyCodeFixAsync( """ class MyClass { @@ -571,12 +537,10 @@ class MyClass { } """); - } [Fact] - public async Task FieldIsUnused_Static() - { - await VerifyCS.VerifyCodeFixAsync( + public Task FieldIsUnused_Static() + => VerifyCS.VerifyCodeFixAsync( """ class MyClass { @@ -588,12 +552,10 @@ class MyClass { } """); - } [Fact] - public async Task MethodIsUnused_Static() - { - await VerifyCS.VerifyCodeFixAsync( + public Task MethodIsUnused_Static() + => VerifyCS.VerifyCodeFixAsync( """ class MyClass { @@ -605,12 +567,10 @@ class MyClass { } """); - } [Fact] - public async Task PropertyIsUnused_Static() - { - await VerifyCS.VerifyCodeFixAsync( + public Task PropertyIsUnused_Static() + => VerifyCS.VerifyCodeFixAsync( """ class MyClass { @@ -622,12 +582,10 @@ class MyClass { } """); - } [Fact] - public async Task IndexerIsUnused_Static() - { - await VerifyCS.VerifyCodeFixAsync( + public Task IndexerIsUnused_Static() + => VerifyCS.VerifyCodeFixAsync( """ class MyClass { @@ -640,12 +598,10 @@ class MyClass { } """); - } [Fact] - public async Task EventIsUnused_Static() - { - await VerifyCS.VerifyCodeFixAsync( + public Task EventIsUnused_Static() + => VerifyCS.VerifyCodeFixAsync( """ class MyClass { @@ -657,7 +613,6 @@ class MyClass { } """); - } [Fact] public async Task MethodIsUnused_Extern() @@ -760,9 +715,8 @@ event System.Action I.E } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30894")] - public async Task WriteOnlyProperty_NotWritten() - { - await VerifyCS.VerifyCodeFixAsync( + public Task WriteOnlyProperty_NotWritten() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -774,7 +728,6 @@ class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30894")] public async Task WriteOnlyProperty_Written() @@ -791,9 +744,8 @@ int P { set { } } } [Fact] - public async Task FieldIsUnused_Const() - { - await VerifyCS.VerifyCodeFixAsync( + public Task FieldIsUnused_Const() + => VerifyCS.VerifyCodeFixAsync( """ class MyClass { @@ -805,7 +757,6 @@ class MyClass { } """); - } [Fact] public async Task FieldIsRead_ExpressionBody() @@ -1293,9 +1244,8 @@ class MyClass } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31581")] - public async Task MethodInNameOf() - { - await new VerifyCS.Test + public Task MethodInNameOf() + => new VerifyCS.Test { TestCode = """ class MyClass @@ -1305,7 +1255,6 @@ private void M() { } } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33765")] public async Task GenericMethodInNameOf() @@ -1464,9 +1413,8 @@ public void M() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33994")] - public async Task PropertyIsOnlyWritten() - { - await new VerifyCS.Test + public Task PropertyIsOnlyWritten() + => new VerifyCS.Test { TestCode = """ class MyClass @@ -1487,7 +1435,6 @@ public void M() .WithLocation(0), }, }.RunAsync(); - } [Fact] public async Task IndexerIsOnlyWritten() @@ -1745,37 +1692,29 @@ class MyClass } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43191")] - public async Task PropertyIsIncrementedAndValueDropped_VerifyAnalyzerMessage() - { - var code = """ + public Task PropertyIsIncrementedAndValueDropped_VerifyAnalyzerMessage() + => VerifyCS.VerifyAnalyzerAsync(""" class MyClass { private int {|#0:P|} { get; set; } public void M1() { ++P; } } - """; - - await VerifyCS.VerifyAnalyzerAsync(code, new DiagnosticResult( + """, new DiagnosticResult( CSharpRemoveUnusedMembersDiagnosticAnalyzer.s_removeUnreadMembersRule) .WithLocation(0) .WithArguments("MyClass.P") .WithOptions(DiagnosticOptions.IgnoreAdditionalLocations)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43191")] - public async Task PropertyIsIncrementedAndValueDropped_NoDiagnosticWhenPropertyIsReadSomewhereElse() - { - var code = """ + public Task PropertyIsIncrementedAndValueDropped_NoDiagnosticWhenPropertyIsReadSomewhereElse() + => VerifyCS.VerifyAnalyzerAsync(""" class MyClass { private int P { get; set; } public void M1() { ++P; } public int M2() => P; } - """; - - await VerifyCS.VerifyAnalyzerAsync(code, []); - } + """, []); [Fact] public async Task IndexerIsIncrementedAndValueUsed() @@ -1806,9 +1745,8 @@ class MyClass } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43191")] - public async Task IndexerIsIncrementedAndValueDropped_VerifyAnalyzerMessage() - { - await VerifyCS.VerifyAnalyzerAsync(""" + public Task IndexerIsIncrementedAndValueDropped_VerifyAnalyzerMessage() + => VerifyCS.VerifyAnalyzerAsync(""" class MyClass { private int {|#0:this|}[int x] { get { return 0; } set { } } @@ -1819,22 +1757,17 @@ class MyClass .WithLocation(0) .WithArguments("MyClass.this") .WithOptions(DiagnosticOptions.IgnoreAdditionalLocations)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43191")] - public async Task IndexerIsIncrementedAndValueDropped_NoDiagnosticWhenIndexerIsReadSomewhereElse() - { - var code = """ + public Task IndexerIsIncrementedAndValueDropped_NoDiagnosticWhenIndexerIsReadSomewhereElse() + => VerifyCS.VerifyAnalyzerAsync(""" class MyClass { private int this[int x] { get { return 0; } set { } } public void M1(int x) => ++this[x]; public int M2(int x) => this[x]; } - """; - - await VerifyCS.VerifyAnalyzerAsync(code, []); - } + """, []); [Fact] public async Task FieldIsTargetOfCompoundAssignmentAndValueUsed() @@ -1921,37 +1854,29 @@ class MyClass } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43191")] - public async Task PropertyIsTargetOfCompoundAssignmentAndValueDropped_VerifyAnalyzerMessage() - { - var code = """ + public Task PropertyIsTargetOfCompoundAssignmentAndValueDropped_VerifyAnalyzerMessage() + => VerifyCS.VerifyAnalyzerAsync(""" class MyClass { private int {|#0:P|} { get; set; } public void M1(int x) { P += x; } } - """; - - await VerifyCS.VerifyAnalyzerAsync(code, new DiagnosticResult( + """, new DiagnosticResult( CSharpRemoveUnusedMembersDiagnosticAnalyzer.s_removeUnreadMembersRule) .WithLocation(0) .WithArguments("MyClass.P") .WithOptions(DiagnosticOptions.IgnoreAdditionalLocations)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43191")] - public async Task PropertyIsTargetOfCompoundAssignmentAndValueDropped_NoDiagnosticWhenPropertyIsReadSomewhereElse() - { - var code = """ + public Task PropertyIsTargetOfCompoundAssignmentAndValueDropped_NoDiagnosticWhenPropertyIsReadSomewhereElse() + => VerifyCS.VerifyAnalyzerAsync(""" class MyClass { private int P { get; set; } public void M1(int x) { P += x; } public int M2() => P; } - """; - - await VerifyCS.VerifyAnalyzerAsync(code, []); - } + """, []); [Fact] public async Task IndexerIsTargetOfCompoundAssignmentAndValueUsed() @@ -1982,37 +1907,29 @@ class MyClass } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43191")] - public async Task IndexerIsTargetOfCompoundAssignmentAndValueDropped_VerifyAnalyzerMessage() - { - var code = """ + public Task IndexerIsTargetOfCompoundAssignmentAndValueDropped_VerifyAnalyzerMessage() + => VerifyCS.VerifyAnalyzerAsync(""" class MyClass { private int {|#0:this|}[int x] { get { return 0; } set { } } public void M1(int x, int y) => this[x] += y; } - """; - - await VerifyCS.VerifyAnalyzerAsync(code, new DiagnosticResult( + """, new DiagnosticResult( CSharpRemoveUnusedMembersDiagnosticAnalyzer.s_removeUnreadMembersRule) .WithLocation(0) .WithArguments("MyClass.this") .WithOptions(DiagnosticOptions.IgnoreAdditionalLocations)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43191")] - public async Task IndexerIsTargetOfCompoundAssignmentAndValueDropped_NoDiagnosticWhenIndexerIsReadSomewhereElse() - { - var code = """ + public Task IndexerIsTargetOfCompoundAssignmentAndValueDropped_NoDiagnosticWhenIndexerIsReadSomewhereElse() + => VerifyCS.VerifyAnalyzerAsync(""" class MyClass { private int this[int x] { get { return 0; } set { } } public void M1(int x, int y) => this[x] += y; public int M2(int x) => this[x]; } - """; - - await VerifyCS.VerifyAnalyzerAsync(code, []); - } + """, []); [Fact] public async Task FieldIsTargetOfAssignmentAndParenthesized() @@ -2166,9 +2083,8 @@ class MyClass } [Fact] - public async Task MultipleFields_AllUnused() - { - await VerifyCS.VerifyCodeFixAsync( + public Task MultipleFields_AllUnused() + => VerifyCS.VerifyCodeFixAsync( """ class MyClass { @@ -2180,7 +2096,6 @@ class MyClass { } """); - } [Theory, CombinatorialData] public async Task MultipleFields_AllUnused_FixOne( @@ -2188,42 +2103,38 @@ public async Task MultipleFields_AllUnused_FixOne( [CombinatorialValues("[|_bar|]", "[|_bar|] = 2")] string secondField, [CombinatorialValues(0, 1)] int diagnosticIndex) { - var source = $$""" - class MyClass - { - private int {{firstField}}, {{secondField}}; - } - """; var fixedSource = $$""" class MyClass { private int {{(diagnosticIndex == 0 ? secondField : firstField)}}; } """; - var batchFixedSource = """ + await new VerifyCS.Test + { + TestCode = $$""" class MyClass { + private int {{firstField}}, {{secondField}}; } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, FixedState = { Sources = { fixedSource }, MarkupHandling = MarkupMode.Allow, }, - BatchFixedCode = batchFixedSource, + BatchFixedCode = """ + class MyClass + { + } + """, CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, DiagnosticSelector = fixableDiagnostics => fixableDiagnostics[diagnosticIndex], }.RunAsync(); } [Fact] - public async Task MultipleFields_SomeUnused() - { - await VerifyCS.VerifyCodeFixAsync( + public Task MultipleFields_SomeUnused() + => VerifyCS.VerifyCodeFixAsync( """ class MyClass { @@ -2238,12 +2149,10 @@ class MyClass public int M() => _bar; } """); - } [Fact] - public async Task MultipleFields_SomeUnused_02() - { - await VerifyCS.VerifyCodeFixAsync( + public Task MultipleFields_SomeUnused_02() + => VerifyCS.VerifyCodeFixAsync( """ class MyClass { @@ -2258,7 +2167,6 @@ class MyClass public int M() => _goo; } """); - } [Fact] public async Task FieldIsRead_InNestedType() @@ -2297,9 +2205,8 @@ class Derived : MyClass } [Fact] - public async Task FieldOfNestedTypeIsUnused() - { - await VerifyCS.VerifyCodeFixAsync( + public Task FieldOfNestedTypeIsUnused() + => VerifyCS.VerifyCodeFixAsync( """ class MyClass { @@ -2317,7 +2224,6 @@ class NestedType } } """); - } [Fact] public async Task FieldOfNestedTypeIsRead() @@ -2338,9 +2244,8 @@ class NestedType } [Fact] - public async Task FieldIsUnused_PartialClass() - { - await VerifyCS.VerifyCodeFixAsync( + public Task FieldIsUnused_PartialClass() + => VerifyCS.VerifyCodeFixAsync( """ partial class MyClass { @@ -2352,7 +2257,6 @@ partial class MyClass { } """); - } [Fact] public async Task FieldIsRead_PartialClass() @@ -2478,9 +2382,8 @@ public void M() } [Fact] - public async Task FieldInTypeWithGeneratedCode() - { - await VerifyCS.VerifyCodeFixAsync( + public Task FieldInTypeWithGeneratedCode() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -2505,7 +2408,6 @@ public void M() } } """); - } [Fact] public async Task FieldIsGeneratedCode() @@ -2573,9 +2475,8 @@ class C } [Fact] - public async Task FieldIsUnusedInType_SemanticErrorInDifferentType() - { - await VerifyCS.VerifyCodeFixAsync( + public Task FieldIsUnusedInType_SemanticErrorInDifferentType() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -2599,7 +2500,6 @@ class C2 public int M() => {|CS0103:ii|}; } """); - } [Fact] public async Task StructLayoutAttribute_ExplicitLayout() @@ -2897,9 +2797,8 @@ internal struct ProcessEntry32 } [Fact] - public async Task FixAllFields_Document() - { - await VerifyCS.VerifyCodeFixAsync( + public Task FixAllFields_Document() + => VerifyCS.VerifyCodeFixAsync( """ class MyClass { @@ -2918,12 +2817,10 @@ class MyClass public int Method() => _z; } """); - } [Fact] - public async Task FixAllMethods_Document() - { - await VerifyCS.VerifyCodeFixAsync( + public Task FixAllMethods_Document() + => VerifyCS.VerifyCodeFixAsync( """ class MyClass { @@ -2944,12 +2841,10 @@ private class NestedClass } } """); - } [Fact] - public async Task FixAllProperties_Document() - { - await VerifyCS.VerifyCodeFixAsync( + public Task FixAllProperties_Document() + => VerifyCS.VerifyCodeFixAsync( """ class MyClass { @@ -2964,12 +2859,10 @@ class MyClass { } """); - } [Fact] - public async Task FixAllEvents_Document() - { - await VerifyCS.VerifyCodeFixAsync( + public Task FixAllEvents_Document() + => VerifyCS.VerifyCodeFixAsync( """ using System; @@ -3002,7 +2895,6 @@ public void M() } } """); - } [Fact] public async Task FixAllMembers_Project() @@ -3169,9 +3061,8 @@ private static void PrivateExtensionMethod(this string s) { } } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30884")] - public async Task TestMessageForConstructor() - { - await VerifyCS.VerifyAnalyzerAsync( + public Task TestMessageForConstructor() + => VerifyCS.VerifyAnalyzerAsync( """ class C { @@ -3183,7 +3074,6 @@ class C .WithLocation(0) .WithArguments("C.C") .WithOptions(DiagnosticOptions.IgnoreAdditionalLocations)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/62856")] public async Task DoNotWarnForAwaiterMethods() @@ -3244,9 +3134,8 @@ class C } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57470")] - public async Task TestForeach() - { - await new VerifyCS.Test + public Task TestForeach() + => new VerifyCS.Test { TestCode = """ using System; @@ -3270,12 +3159,10 @@ static IEnumerator GetEnumerator(this Range range) LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75995")] - public async Task KeepUsedDeconstructMethod() - { - await new VerifyCS.Test + public Task KeepUsedDeconstructMethod() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -3299,12 +3186,10 @@ void Deconstruct( } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75995")] - public async Task RemoveUnusedDeconstructMethod() - { - await new VerifyCS.Test + public Task RemoveUnusedDeconstructMethod() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -3339,12 +3224,10 @@ public void M( } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69143")] - public async Task KeepInlineArrayInstanceMember() - { - await new VerifyCS.Test + public Task KeepInlineArrayInstanceMember() + => new VerifyCS.Test { TestCode = """ using System.Runtime.CompilerServices; @@ -3368,12 +3251,10 @@ struct S LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/54972")] - public async Task TestNameof1() - { - await new VerifyCS.Test + public Task TestNameof1() + => new VerifyCS.Test { TestCode = """ using System; @@ -3402,12 +3283,10 @@ static void Main(string[] args) LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/54972")] - public async Task TestNameof2() - { - await new VerifyCS.Test + public Task TestNameof2() + => new VerifyCS.Test { TestCode = """ using System; @@ -3425,12 +3304,10 @@ static void Main(string[] args) LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/54972")] - public async Task TestNameof3() - { - await new VerifyCS.Test + public Task TestNameof3() + => new VerifyCS.Test { TestCode = """ using System; @@ -3449,12 +3326,10 @@ static void Main(string[] args) LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71847")] - public async Task TestRefFieldOnlyWrittenTo() - { - await new VerifyCS.Test + public Task TestRefFieldOnlyWrittenTo() + => new VerifyCS.Test { TestCode = """ using System; @@ -3480,12 +3355,10 @@ public unsafe void ToUnmanaged() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71847")] - public async Task TestRefFieldNotReadOrWritten() - { - await new VerifyCS.Test + public Task TestRefFieldNotReadOrWritten() + => new VerifyCS.Test { TestCode = """ using System; @@ -3529,12 +3402,10 @@ public unsafe void ToUnmanaged() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/77251")] - public async Task TestRefFieldWrittenNotRead() - { - await new VerifyCS.Test + public Task TestRefFieldWrittenNotRead() + => new VerifyCS.Test { TestCode = """ public readonly ref struct RefScope @@ -3558,5 +3429,4 @@ public void Dispose() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedParametersTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedParametersTests.cs index 4774532c013b9..a931cb5f752c9 100644 --- a/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedParametersTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedParametersTests.cs @@ -88,9 +88,8 @@ private static async Task TestDiagnosticsAsync([StringSyntax(PredefinedEmbeddedL } [Fact] - public async Task Parameter_Used() - { - await TestDiagnosticMissingAsync( + public Task Parameter_Used() + => TestDiagnosticMissingAsync( """ class C { @@ -100,12 +99,10 @@ void M(int p) } } """); - } [Fact] - public async Task Parameter_Unused() - { - await TestDiagnosticsAsync( + public Task Parameter_Unused() + => TestDiagnosticsAsync( """ class C { @@ -114,14 +111,12 @@ void M(int {|IDE0060:p|}) } } """); - } [Theory] [InlineData("public", "public")] [InlineData("public", "protected")] - public async Task Parameter_Unused_NonPrivate_NotApplicable(string typeAccessibility, string methodAccessibility) - { - await TestDiagnosticMissingAsync( + public Task Parameter_Unused_NonPrivate_NotApplicable(string typeAccessibility, string methodAccessibility) + => TestDiagnosticMissingAsync( $$""" {{typeAccessibility}} class C { @@ -130,7 +125,6 @@ await TestDiagnosticMissingAsync( } } """, NonPublicMethodsOnly); - } [Theory] [InlineData("public", "private")] @@ -139,9 +133,8 @@ await TestDiagnosticMissingAsync( [InlineData("internal", "public")] [InlineData("internal", "internal")] [InlineData("internal", "protected")] - public async Task Parameter_Unused_NonPublicMethod(string typeAccessibility, string methodAccessibility) - { - await TestDiagnosticsAsync( + public Task Parameter_Unused_NonPublicMethod(string typeAccessibility, string methodAccessibility) + => TestDiagnosticsAsync( $$""" {{typeAccessibility}} class C { @@ -150,7 +143,6 @@ await TestDiagnosticsAsync( } } """, NonPublicMethodsOnly); - } [Fact] public async Task Parameter_Unused_UnusedExpressionAssignment_PreferNone() @@ -171,9 +163,8 @@ void M(int p) } [Fact] - public async Task Parameter_WrittenOnly() - { - await TestDiagnosticsAsync( + public Task Parameter_WrittenOnly() + => TestDiagnosticsAsync( """ class C { @@ -183,12 +174,10 @@ void M(int {|IDE0060:p|}) } } """); - } [Fact] - public async Task Parameter_WrittenThenRead() - { - await TestDiagnosticsAsync( + public Task Parameter_WrittenThenRead() + => TestDiagnosticsAsync( """ class C { @@ -199,12 +188,10 @@ void M(int {|IDE0060:p|}) } } """); - } [Fact] - public async Task Parameter_WrittenOnAllControlPaths_BeforeRead() - { - await TestDiagnosticsAsync( + public Task Parameter_WrittenOnAllControlPaths_BeforeRead() + => TestDiagnosticsAsync( """ class C { @@ -223,12 +210,10 @@ void M(int {|IDE0060:p|}, bool flag) } } """); - } [Fact] - public async Task Parameter_WrittenOnSomeControlPaths_BeforeRead() - { - await TestDiagnosticMissingAsync( + public Task Parameter_WrittenOnSomeControlPaths_BeforeRead() + => TestDiagnosticMissingAsync( """ class C { @@ -250,12 +235,10 @@ void M(int p, bool flag, bool flag2) } } """); - } [Fact] - public async Task OptionalParameter_Unused() - { - await TestDiagnosticsAsync( + public Task OptionalParameter_Unused() + => TestDiagnosticsAsync( """ class C { @@ -264,12 +247,10 @@ void M(int {|IDE0060:p|} = 0) } } """); - } [Fact] - public async Task Parameter_UsedInConstructorInitializerOnly() - { - await TestDiagnosticMissingAsync( + public Task Parameter_UsedInConstructorInitializerOnly() + => TestDiagnosticMissingAsync( """ class B { @@ -284,12 +265,10 @@ class C: B } } """); - } [Fact] - public async Task Parameter_NotUsedInConstructorInitializer_UsedInConstructorBody() - { - await TestDiagnosticMissingAsync( + public Task Parameter_NotUsedInConstructorInitializer_UsedInConstructorBody() + => TestDiagnosticMissingAsync( """ class B { @@ -305,12 +284,10 @@ class C: B } } """); - } [Fact] - public async Task Parameter_UsedInConstructorInitializerAndConstructorBody() - { - await TestDiagnosticMissingAsync( + public Task Parameter_UsedInConstructorInitializerAndConstructorBody() + => TestDiagnosticMissingAsync( """ class B { @@ -326,12 +303,10 @@ class C: B } } """); - } [Fact] - public async Task UnusedLocalFunctionParameter() - { - await TestDiagnosticsAsync( + public Task UnusedLocalFunctionParameter() + => TestDiagnosticsAsync( """ class C { @@ -344,12 +319,10 @@ void LocalFunction(int {|IDE0060:p|}) } } """); - } [Fact] - public async Task UnusedLocalFunctionParameter_02() - { - await TestDiagnosticsAsync( + public Task UnusedLocalFunctionParameter_02() + => TestDiagnosticsAsync( """ class C { @@ -362,12 +335,10 @@ void LocalFunction(int {|IDE0060:p|}) } } """); - } [Fact] - public async Task UnusedLocalFunctionParameter_Discard() - { - await TestDiagnosticMissingAsync( + public Task UnusedLocalFunctionParameter_Discard() + => TestDiagnosticMissingAsync( """ class C { @@ -380,12 +351,10 @@ void LocalFunction(int _) } } """); - } [Fact] - public async Task UnusedLocalFunctionParameter_PassedAsDelegateArgument() - { - await TestDiagnosticMissingAsync( + public Task UnusedLocalFunctionParameter_PassedAsDelegateArgument() + => TestDiagnosticMissingAsync( """ using System; @@ -402,13 +371,10 @@ void LocalFunction(int p) void M2(Action a) => a(0); } """); - } [Fact] - public async Task UsedInLambda_ReturnsDelegate() - { - // Currently we bail out from analysis for method returning delegate types. - await TestDiagnosticMissingAsync( + public Task UsedInLambda_ReturnsDelegate() + => TestDiagnosticMissingAsync( """ using System; @@ -420,14 +386,10 @@ private static Action M(object p, Action myDelegate) } } """); - } [Fact] - public async Task UnusedInLambda_ReturnsDelegate() - { - // We bail out from unused value analysis for method returning delegate types. - // We should still report unused parameters. - await TestDiagnosticsAsync( + public Task UnusedInLambda_ReturnsDelegate() + => TestDiagnosticsAsync( """ using System; @@ -439,14 +401,10 @@ private static Action M(object {|IDE0060:p|}) } } """); - } [Fact] - public async Task UnusedInLambda_LambdaPassedAsArgument() - { - // We bail out from unused value analysis when lambda is passed as argument. - // We should still report unused parameters. - await TestDiagnosticsAsync( + public Task UnusedInLambda_LambdaPassedAsArgument() + => TestDiagnosticsAsync( """ using System; @@ -460,12 +418,10 @@ private static void M(object {|IDE0060:p|}) private static void M2(Action _) { } } """); - } [Fact] - public async Task ReadInLambda_LambdaPassedAsArgument() - { - await TestDiagnosticMissingAsync( + public Task ReadInLambda_LambdaPassedAsArgument() + => TestDiagnosticMissingAsync( """ using System; @@ -481,12 +437,10 @@ private static void M2(Action _) { } private static void M3(object _) { } } """); - } [Fact] - public async Task OnlyWrittenInLambda_LambdaPassedAsArgument() - { - await TestDiagnosticMissingAsync( + public Task OnlyWrittenInLambda_LambdaPassedAsArgument() + => TestDiagnosticMissingAsync( """ using System; @@ -502,12 +456,10 @@ private static void M2(Action _) { } private static void M3(out object o) { o = null; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31744")] - public async Task UnusedInExpressionTree_PassedAsArgument() - { - await TestDiagnosticsAsync( + public Task UnusedInExpressionTree_PassedAsArgument() + => TestDiagnosticsAsync( """ using System; using System.Linq.Expressions; @@ -523,12 +475,10 @@ public static void M1(object {|IDE0060:p|}) private int M3() { return 0; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31744")] - public async Task ReadInExpressionTree_PassedAsArgument() - { - await TestDiagnosticMissingAsync( + public Task ReadInExpressionTree_PassedAsArgument() + => TestDiagnosticMissingAsync( """ using System; using System.Linq.Expressions; @@ -544,12 +494,10 @@ public static void M1(object p) private int M3(object _) { return 0; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31744")] - public async Task OnlyWrittenInExpressionTree_PassedAsArgument() - { - await TestDiagnosticMissingAsync( + public Task OnlyWrittenInExpressionTree_PassedAsArgument() + => TestDiagnosticMissingAsync( """ using System; using System.Linq.Expressions; @@ -565,14 +513,10 @@ public static void M1(object p) private int M3(out object o) { o = null; return 0; } } """); - } [Fact] - public async Task UsedInLambda_AssignedToField() - { - // Currently we bail out from analysis if we have a delegate creation that is not assigned - // too a local/parameter. - await TestDiagnosticMissingAsync( + public Task UsedInLambda_AssignedToField() + => TestDiagnosticMissingAsync( """ using System; @@ -585,12 +529,10 @@ private static void M(object p) } } """); - } [Fact] - public async Task MethodWithLockAndControlFlow() - { - await TestDiagnosticMissingAsync( + public Task MethodWithLockAndControlFlow() + => TestDiagnosticMissingAsync( """ using System; @@ -613,12 +555,10 @@ public static C M(object p, int flag, C c1, C c2) private void M2(object _) { } } """); - } [Fact] - public async Task UnusedLambdaParameter() - { - await TestDiagnosticMissingAsync( + public Task UnusedLambdaParameter() + => TestDiagnosticMissingAsync( """ using System; @@ -634,12 +574,10 @@ void M(int y) } } """); - } [Fact] - public async Task UnusedLambdaParameter_Discard() - { - await TestDiagnosticMissingAsync( + public Task UnusedLambdaParameter_Discard() + => TestDiagnosticMissingAsync( """ using System; @@ -655,12 +593,10 @@ void M(int y) } } """); - } [Fact] - public async Task UnusedLambdaParameter_DiscardTwo() - { - await TestDiagnosticMissingAsync( + public Task UnusedLambdaParameter_DiscardTwo() + => TestDiagnosticMissingAsync( """ using System; @@ -676,12 +612,10 @@ void M(int y) } } """); - } [Fact] - public async Task UnusedLocalFunctionParameter_DiscardTwo() - { - await TestDiagnosticMissingAsync( + public Task UnusedLocalFunctionParameter_DiscardTwo() + => TestDiagnosticMissingAsync( """ using System; @@ -697,12 +631,10 @@ void local(int _1, int _2) } } """); - } [Fact] - public async Task UnusedMethodParameter_DiscardTwo() - { - await TestDiagnosticMissingAsync( + public Task UnusedMethodParameter_DiscardTwo() + => TestDiagnosticMissingAsync( """ using System; @@ -718,12 +650,10 @@ void M2(int y) } } """); - } [Fact] - public async Task UsedLocalFunctionParameter() - { - await TestDiagnosticMissingAsync( + public Task UsedLocalFunctionParameter() + => TestDiagnosticMissingAsync( """ class C { @@ -737,12 +667,10 @@ void LocalFunction(int p) } } """); - } [Fact] - public async Task UsedLambdaParameter() - { - await TestDiagnosticMissingAsync( + public Task UsedLambdaParameter() + => TestDiagnosticMissingAsync( """ using System; @@ -759,12 +687,10 @@ void M(int y) } } """); - } [Fact] - public async Task OptionalParameter_Used() - { - await TestDiagnosticMissingAsync( + public Task OptionalParameter_Used() + => TestDiagnosticMissingAsync( """ class C { @@ -774,12 +700,10 @@ void M(int p = 0) } } """); - } [Fact] - public async Task InParameter() - { - await TestDiagnosticsAsync( + public Task InParameter() + => TestDiagnosticsAsync( """ class C { @@ -788,12 +712,10 @@ void M(in int {|IDE0060:p|}) } } """); - } [Fact] - public async Task RefParameter_Unused() - { - await TestDiagnosticsAsync( + public Task RefParameter_Unused() + => TestDiagnosticsAsync( """ class C { @@ -802,12 +724,10 @@ void M(ref int {|IDE0060:p|}) } } """); - } [Fact] - public async Task RefParameter_WrittenOnly() - { - await TestDiagnosticMissingAsync( + public Task RefParameter_WrittenOnly() + => TestDiagnosticMissingAsync( """ class C { @@ -817,12 +737,10 @@ void M(ref int p) } } """); - } [Fact] - public async Task RefParameter_ReadOnly() - { - await TestDiagnosticMissingAsync( + public Task RefParameter_ReadOnly() + => TestDiagnosticMissingAsync( """ class C { @@ -832,12 +750,10 @@ void M(ref int p) } } """); - } [Fact] - public async Task RefParameter_ReadThenWritten() - { - await TestDiagnosticMissingAsync( + public Task RefParameter_ReadThenWritten() + => TestDiagnosticMissingAsync( """ class C { @@ -848,12 +764,10 @@ void M(ref int p) } } """); - } [Fact] - public async Task RefParameter_WrittenAndThenRead() - { - await TestDiagnosticMissingAsync( + public Task RefParameter_WrittenAndThenRead() + => TestDiagnosticMissingAsync( """ class C { @@ -864,12 +778,10 @@ void M(ref int p) } } """); - } [Fact] - public async Task RefParameter_WrittenTwiceNotRead() - { - await TestDiagnosticMissingAsync( + public Task RefParameter_WrittenTwiceNotRead() + => TestDiagnosticMissingAsync( """ class C { @@ -880,12 +792,10 @@ void M(ref int p) } } """); - } [Fact] - public async Task OutParameter_Unused() - { - await TestDiagnosticsAsync( + public Task OutParameter_Unused() + => TestDiagnosticsAsync( """ class C { @@ -894,12 +804,10 @@ class C } } """); - } [Fact] - public async Task OutParameter_WrittenOnly() - { - await TestDiagnosticMissingAsync( + public Task OutParameter_WrittenOnly() + => TestDiagnosticMissingAsync( """ class C { @@ -909,12 +817,10 @@ void M(out int p) } } """); - } [Fact] - public async Task OutParameter_WrittenAndThenRead() - { - await TestDiagnosticMissingAsync( + public Task OutParameter_WrittenAndThenRead() + => TestDiagnosticMissingAsync( """ class C { @@ -925,12 +831,10 @@ void M(out int p) } } """); - } [Fact] - public async Task OutParameter_WrittenTwiceNotRead() - { - await TestDiagnosticMissingAsync( + public Task OutParameter_WrittenTwiceNotRead() + => TestDiagnosticMissingAsync( """ class C { @@ -941,12 +845,10 @@ void M(out int p) } } """); - } [Fact] - public async Task Parameter_ExternMethod() - { - await TestDiagnosticMissingAsync( + public Task Parameter_ExternMethod() + => TestDiagnosticMissingAsync( """ class C { @@ -954,24 +856,20 @@ class C static extern void M(int p); } """); - } [Fact] - public async Task Parameter_AbstractMethod() - { - await TestDiagnosticMissingAsync( + public Task Parameter_AbstractMethod() + => TestDiagnosticMissingAsync( """ abstract class C { protected abstract void M(int p); } """); - } [Fact] - public async Task Parameter_VirtualMethod() - { - await TestDiagnosticMissingAsync( + public Task Parameter_VirtualMethod() + => TestDiagnosticMissingAsync( """ class C { @@ -980,12 +878,10 @@ protected virtual void M(int p) } } """); - } [Fact] - public async Task Parameter_OverriddenMethod() - { - await TestDiagnosticMissingAsync( + public Task Parameter_OverriddenMethod() + => TestDiagnosticMissingAsync( """ class C { @@ -1002,12 +898,10 @@ protected override void M(int p) } } """); - } [Fact] - public async Task Parameter_ImplicitInterfaceImplementationMethod() - { - await TestDiagnosticMissingAsync( + public Task Parameter_ImplicitInterfaceImplementationMethod() + => TestDiagnosticMissingAsync( """ interface I { @@ -1020,12 +914,10 @@ public void M(int p) } } """); - } [Fact] - public async Task Parameter_ExplicitInterfaceImplementationMethod() - { - await TestDiagnosticMissingAsync( + public Task Parameter_ExplicitInterfaceImplementationMethod() + => TestDiagnosticMissingAsync( """ interface I { @@ -1038,12 +930,10 @@ void I.M(int p) } } """); - } [Fact] - public async Task Parameter_IndexerMethod() - { - await TestDiagnosticMissingAsync( + public Task Parameter_IndexerMethod() + => TestDiagnosticMissingAsync( """ class C { @@ -1053,12 +943,10 @@ int this[int p] } } """); - } [Fact] - public async Task Parameter_ConditionalDirective() - { - await TestDiagnosticMissingAsync( + public Task Parameter_ConditionalDirective() + => TestDiagnosticMissingAsync( """ class C { @@ -1070,12 +958,10 @@ void M(int p) } } """); - } [Fact] - public async Task Parameter_EventHandler_FirstParameter() - { - await TestDiagnosticMissingAsync( + public Task Parameter_EventHandler_FirstParameter() + => TestDiagnosticMissingAsync( """ class C { @@ -1084,12 +970,10 @@ public void MyHandler(object obj, System.EventArgs args) } } """); - } [Fact] - public async Task Parameter_EventHandler_SecondParameter() - { - await TestDiagnosticMissingAsync( + public Task Parameter_EventHandler_SecondParameter() + => TestDiagnosticMissingAsync( """ class C { @@ -1098,12 +982,10 @@ public void MyHandler(object obj, System.EventArgs args) } } """); - } [Fact] - public async Task Parameter_MethodUsedAsEventHandler() - { - await TestDiagnosticMissingAsync( + public Task Parameter_MethodUsedAsEventHandler() + => TestDiagnosticMissingAsync( """ using System; @@ -1123,12 +1005,10 @@ void Handler(int x) } } """); - } [Fact] - public async Task Parameter_CustomEventArgs() - { - await TestDiagnosticMissingAsync( + public Task Parameter_CustomEventArgs() + => TestDiagnosticMissingAsync( """ class C { @@ -1141,7 +1021,6 @@ public void MyHandler(object obj, CustomEventArgs args) } } """); - } [Theory] [InlineData(@"[System.Diagnostics.Conditional(nameof(M))]")] @@ -1150,9 +1029,8 @@ public void MyHandler(object obj, CustomEventArgs args) [InlineData(@"[System.Runtime.Serialization.OnDeserializedAttribute]")] [InlineData(@"[System.Runtime.Serialization.OnSerializingAttribute]")] [InlineData(@"[System.Runtime.Serialization.OnSerializedAttribute]")] - public async Task Parameter_MethodsWithSpecialAttributes(string attribute) - { - await TestDiagnosticMissingAsync( + public Task Parameter_MethodsWithSpecialAttributes(string attribute) + => TestDiagnosticMissingAsync( $$""" class C { @@ -1162,14 +1040,12 @@ void M(int p) } } """); - } [Theory] [InlineData("System.Composition", "ImportingConstructorAttribute")] [InlineData("System.ComponentModel.Composition", "ImportingConstructorAttribute")] - public async Task Parameter_ConstructorsWithSpecialAttributes(string attributeNamespace, string attributeName) - { - await TestDiagnosticMissingAsync( + public Task Parameter_ConstructorsWithSpecialAttributes(string attributeNamespace, string attributeName) + => TestDiagnosticMissingAsync( $$""" namespace {{attributeNamespace}} { @@ -1184,12 +1060,10 @@ public C(int p) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32133")] - public async Task Parameter_SerializationConstructor() - { - await TestDiagnosticMissingAsync( + public Task Parameter_SerializationConstructor() + => TestDiagnosticMissingAsync( """ using System; using System.Runtime.Serialization; @@ -1217,7 +1091,6 @@ public void GetObjectData(SerializationInfo info, StreamingContext context) } } """); - } [ConditionalFact(typeof(IsEnglishLocal))] public async Task Parameter_DiagnosticMessages() @@ -1269,9 +1142,8 @@ void M3(int p5) [Theory] [InlineData("int[]")] [InlineData("Span")] - public async Task Parameter_ArrayLikeUsedForReading(string arrayLikeType) - { - await TestDiagnosticMissingAsync( + public Task Parameter_ArrayLikeUsedForReading(string arrayLikeType) + => TestDiagnosticMissingAsync( $$""" using System; class C @@ -1282,14 +1154,12 @@ void M({{arrayLikeType}} p) } } """); - } [Theory] [InlineData("int[]")] [InlineData("Span")] - public async Task Parameter_ArrayLikeUsedForWriting(string arrayLikeType) - { - await TestDiagnosticMissingAsync( + public Task Parameter_ArrayLikeUsedForWriting(string arrayLikeType) + => TestDiagnosticMissingAsync( $$""" using System; class C @@ -1300,12 +1170,10 @@ void M({{arrayLikeType}} p) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32287")] - public async Task Parameter_DeclarationPatternWithNullDeclaredSymbol() - { - await TestDiagnosticMissingAsync( + public Task Parameter_DeclarationPatternWithNullDeclaredSymbol() + => TestDiagnosticMissingAsync( """ class C { @@ -1317,12 +1185,10 @@ void M(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32851")] - public async Task Parameter_Unused_SpecialNames() - { - await TestDiagnosticMissingAsync( + public Task Parameter_Unused_SpecialNames() + => TestDiagnosticMissingAsync( """ class C { @@ -1331,12 +1197,10 @@ void M(int _, char _1, C _3) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32851")] - public async Task Parameter_Used_SemanticError() - { - await TestDiagnosticMissingAsync( + public Task Parameter_Used_SemanticError() + => TestDiagnosticMissingAsync( """ class C { @@ -1349,12 +1213,10 @@ void M(int x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32851")] - public async Task Parameter_Unused_SemanticError() - { - await TestDiagnosticsAsync( + public Task Parameter_Unused_SemanticError() + => TestDiagnosticsAsync( """ class C { @@ -1367,12 +1229,10 @@ void M(int {|IDE0060:x|}) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32973")] - public async Task OutParameter_LocalFunction() - { - await TestDiagnosticMissingAsync( + public Task OutParameter_LocalFunction() + => TestDiagnosticMissingAsync( """ class C { @@ -1388,12 +1248,10 @@ bool LocalFunction(out int y) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32973")] - public async Task RefParameter_Unused_LocalFunction() - { - await TestDiagnosticsAsync( + public Task RefParameter_Unused_LocalFunction() + => TestDiagnosticsAsync( """ class C { @@ -1408,12 +1266,10 @@ bool LocalFunction(ref int {|IDE0060:y|}) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32973")] - public async Task RefParameter_Used_LocalFunction() - { - await TestDiagnosticMissingAsync( + public Task RefParameter_Used_LocalFunction() + => TestDiagnosticMissingAsync( """ class C { @@ -1429,12 +1285,10 @@ bool LocalFunction(ref int y) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33299")] - public async Task NullCoalesceAssignment() - { - await TestDiagnosticMissingAsync( + public Task NullCoalesceAssignment() + => TestDiagnosticMissingAsync( """ class C { @@ -1444,12 +1298,10 @@ public static void M(C x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34301")] - public async Task GenericLocalFunction() - { - await TestDiagnosticsAsync( + public Task GenericLocalFunction() + => TestDiagnosticsAsync( """ class C { @@ -1463,12 +1315,10 @@ void LocalFunc(T {|IDE0060:value|}) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36715")] - public async Task GenericLocalFunction_02() - { - await TestDiagnosticsAsync( + public Task GenericLocalFunction_02() + => TestDiagnosticsAsync( """ using System.Collections.Generic; @@ -1494,12 +1344,10 @@ IEnumerable LocalFunc(T value) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36715")] - public async Task GenericLocalFunction_03() - { - await TestDiagnosticMissingAsync( + public Task GenericLocalFunction_03() + => TestDiagnosticMissingAsync( """ using System; using System.Collections.Generic; @@ -1527,7 +1375,6 @@ IEnumerable LocalFunc(T value) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34830")] public async Task RegressionTest_ShouldReportUnusedParameter() @@ -1594,9 +1441,8 @@ private void myAction() { } #endif [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37483")] - public async Task MethodUsedAsDelegateInGeneratedCode_NoDiagnostic() - { - await TestDiagnosticMissingAsync( + public Task MethodUsedAsDelegateInGeneratedCode_NoDiagnostic() + => TestDiagnosticMissingAsync( """ using System; @@ -1616,12 +1462,10 @@ public void M2(out Action a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37483")] - public async Task UnusedParameterInGeneratedCode_NoDiagnostic() - { - await TestDiagnosticMissingAsync( + public Task UnusedParameterInGeneratedCode_NoDiagnostic() + => TestDiagnosticMissingAsync( """ public partial class C { @@ -1631,13 +1475,11 @@ private void M(int x) } } """); - } [WorkItem("https://github.com/dotnet/roslyn/issues/57814")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] - public async Task UnusedParameterInPartialMethodImplementation_NoDiagnostic() - { - await TestDiagnosticMissingAsync( + public Task UnusedParameterInPartialMethodImplementation_NoDiagnostic() + => TestDiagnosticMissingAsync( """ public partial class C { @@ -1651,24 +1493,20 @@ public partial void M(int x) } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] - public async Task ParameterInPartialMethodDefinition_NoDiagnostic() - { - await TestDiagnosticMissingAsync( + public Task ParameterInPartialMethodDefinition_NoDiagnostic() + => TestDiagnosticMissingAsync( """ public partial class C { partial void M(int x); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36817")] - public async Task ParameterWithoutName_NoDiagnostic() - { - await TestDiagnosticMissingAsync( + public Task ParameterWithoutName_NoDiagnostic() + => TestDiagnosticMissingAsync( """ public class C { @@ -1677,12 +1515,10 @@ public void M(int {|CS1001:)|} } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41236")] - public async Task NotImplementedException_NoDiagnostic1() - { - await TestDiagnosticMissingAsync( + public Task NotImplementedException_NoDiagnostic1() + => TestDiagnosticMissingAsync( """ using System; @@ -1694,12 +1530,10 @@ private void Goo(int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41236")] - public async Task NotImplementedException_NoDiagnostic2() - { - await TestDiagnosticMissingAsync( + public Task NotImplementedException_NoDiagnostic2() + => TestDiagnosticMissingAsync( """ using System; @@ -1709,12 +1543,10 @@ private void Goo(int i) => throw new NotImplementedException(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41236")] - public async Task NotImplementedException_NoDiagnostic3() - { - await TestDiagnosticMissingAsync( + public Task NotImplementedException_NoDiagnostic3() + => TestDiagnosticMissingAsync( """ using System; @@ -1724,12 +1556,10 @@ public C(int i) => throw new NotImplementedException(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56317")] - public async Task NotImplementedException_NoDiagnostic4() - { - await TestDiagnosticMissingAsync( + public Task NotImplementedException_NoDiagnostic4() + => TestDiagnosticMissingAsync( """ using System; @@ -1739,12 +1569,10 @@ private int Goo(int i) => throw new NotImplementedException(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56317")] - public async Task NotImplementedException_NoDiagnostic5() - { - await TestDiagnosticMissingAsync( + public Task NotImplementedException_NoDiagnostic5() + => TestDiagnosticMissingAsync( """ using System; @@ -1756,12 +1584,10 @@ private int Goo(int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41236")] - public async Task NotImplementedException_MultipleStatements1() - { - await TestDiagnosticsAsync( + public Task NotImplementedException_MultipleStatements1() + => TestDiagnosticsAsync( """ using System; @@ -1774,12 +1600,10 @@ private void Goo(int {|IDE0060:i|}) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41236")] - public async Task NotImplementedException_MultipleStatements2() - { - await TestDiagnosticsAsync( + public Task NotImplementedException_MultipleStatements2() + => TestDiagnosticsAsync( """ using System; @@ -1792,19 +1616,15 @@ private void Goo(int {|IDE0060:i|}) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47142")] - public async Task Record_PrimaryConstructorParameter() - { - await TestMissingAsync( + public Task Record_PrimaryConstructorParameter() + => TestMissingAsync( @"record A(int [|X|]);"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47142")] - public async Task Record_NonPrimaryConstructorParameter() - { - await TestDiagnosticsAsync( + public Task Record_NonPrimaryConstructorParameter() + => TestDiagnosticsAsync( """ record A { @@ -1813,32 +1633,26 @@ public A(int {|IDE0060:X|}) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47142")] - public async Task Record_DelegatingPrimaryConstructorParameter() - { - await TestDiagnosticMissingAsync( + public Task Record_DelegatingPrimaryConstructorParameter() + => TestDiagnosticMissingAsync( """ record A(int X); record B(int X, int Y) : A(X); """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47174")] - public async Task RecordPrimaryConstructorParameter_PublicRecord() - { - await TestDiagnosticMissingAsync( + public Task RecordPrimaryConstructorParameter_PublicRecord() + => TestDiagnosticMissingAsync( """ public record Base(int I) { } public record Derived(string S) : Base(42) { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45743")] - public async Task RequiredGetInstanceMethodByICustomMarshaler() - { - await TestDiagnosticMissingAsync(""" + public Task RequiredGetInstanceMethodByICustomMarshaler() + => TestDiagnosticMissingAsync(""" using System; using System.Runtime.InteropServices; @@ -1864,24 +1678,20 @@ public static ICustomMarshaler GetInstance(string s) => null; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65275")] - public async Task TestMethodWithUnusedParameterThrowsExpressionBody() - { - await TestDiagnosticMissingAsync( + public Task TestMethodWithUnusedParameterThrowsExpressionBody() + => TestDiagnosticMissingAsync( """ public class Class { public void Method(int x) => throw new System.Exception(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65275")] - public async Task TestMethodWithUnusedParameterThrowsMethodBody() - { - await TestDiagnosticMissingAsync( + public Task TestMethodWithUnusedParameterThrowsMethodBody() + => TestDiagnosticMissingAsync( """ public class Class { @@ -1891,12 +1701,10 @@ public void Method(int x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65275")] - public async Task TestMethodWithUnusedParameterThrowsConstructorBody() - { - await TestDiagnosticMissingAsync( + public Task TestMethodWithUnusedParameterThrowsConstructorBody() + => TestDiagnosticMissingAsync( """ public class Class { @@ -1906,24 +1714,20 @@ public Class(int x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65275")] - public async Task TestMethodWithUnusedParameterThrowsConstructorExpressionBody() - { - await TestDiagnosticMissingAsync( + public Task TestMethodWithUnusedParameterThrowsConstructorExpressionBody() + => TestDiagnosticMissingAsync( """ public class Class { public Class(int x) => throw new System.Exception(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65275")] - public async Task TestMethodWithUnusedParameterThrowsLocalFunctionExpressionBody() - { - await TestDiagnosticMissingAsync( + public Task TestMethodWithUnusedParameterThrowsLocalFunctionExpressionBody() + => TestDiagnosticMissingAsync( """ public class Class { @@ -1933,12 +1737,10 @@ public void Method() } } """); - } [Fact, WorkItem(67013, "https://github.com/dotnet/roslyn/issues/67013")] - public async Task Test_PrimaryConstructor1() - { - await TestDiagnosticMissingAsync( + public Task Test_PrimaryConstructor1() + => TestDiagnosticMissingAsync( """ using System; @@ -1946,12 +1748,10 @@ class C(int a100) { } """); - } [Fact, WorkItem(67013, "https://github.com/dotnet/roslyn/issues/67013")] - public async Task Test_PrimaryConstructor2() - { - await TestDiagnosticMissingAsync( + public Task Test_PrimaryConstructor2() + => TestDiagnosticMissingAsync( """ using System; @@ -1960,12 +1760,10 @@ class C(int a100) : Object() int M1() => a100; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70276")] - public async Task TestMethodWithNameOf() - { - await TestDiagnosticsAsync(""" + public Task TestMethodWithNameOf() + => TestDiagnosticsAsync(""" class C { void M(int {|IDE0060:x|}) @@ -1974,12 +1772,10 @@ void M(int {|IDE0060:x|}) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58168")] - public async Task TestInterpolatedStringHandler_TwoIntParameters_FirstParameter() - { - await TestDiagnosticMissingAsync(""" + public Task TestInterpolatedStringHandler_TwoIntParameters_FirstParameter() + => TestDiagnosticMissingAsync(""" using System.Runtime.CompilerServices; [InterpolatedStringHandler] @@ -1990,12 +1786,10 @@ public MyInterpolatedStringHandler(int literalLength, int formattedCount) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58168")] - public async Task TestInterpolatedStringHandler_TwoIntParameters_SecondParameter() - { - await TestDiagnosticMissingAsync(""" + public Task TestInterpolatedStringHandler_TwoIntParameters_SecondParameter() + => TestDiagnosticMissingAsync(""" using System.Runtime.CompilerServices; [InterpolatedStringHandler] @@ -2006,13 +1800,11 @@ public MyInterpolatedStringHandler(int literalLength, int formattedCount) } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/58168")] [MemberData(nameof(NonIntTypes))] - public async Task TestInterpolatedStringHandler_TwoParameters_FirstNonIntParameter(string nonIntType) - { - await TestDiagnosticsAsync($$""" + public Task TestInterpolatedStringHandler_TwoParameters_FirstNonIntParameter(string nonIntType) + => TestDiagnosticsAsync($$""" using System.Runtime.CompilerServices; [InterpolatedStringHandler] @@ -2023,13 +1815,11 @@ public MyInterpolatedStringHandler({{nonIntType}} {|IDE0060:literalLength|}, int } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/58168")] [MemberData(nameof(NonIntTypes))] - public async Task TestInterpolatedStringHandler_TwoParameters_SecondNonIntParameter(string nonIntType) - { - await TestDiagnosticsAsync($$""" + public Task TestInterpolatedStringHandler_TwoParameters_SecondNonIntParameter(string nonIntType) + => TestDiagnosticsAsync($$""" using System.Runtime.CompilerServices; [InterpolatedStringHandler] @@ -2040,12 +1830,10 @@ public MyInterpolatedStringHandler(int literalLength, {{nonIntType}} {|IDE0060:f } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58168")] - public async Task TestInterpolatedStringHandler_OneIntParameter() - { - await TestDiagnosticMissingAsync(""" + public Task TestInterpolatedStringHandler_OneIntParameter() + => TestDiagnosticMissingAsync(""" using System.Runtime.CompilerServices; [InterpolatedStringHandler] @@ -2056,13 +1844,11 @@ public MyInterpolatedStringHandler(int literalLength) } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/58168")] [MemberData(nameof(NonIntTypes))] - public async Task TestInterpolatedStringHandler_OneNonIntParameter(string nonIntType) - { - await TestDiagnosticsAsync($$""" + public Task TestInterpolatedStringHandler_OneNonIntParameter(string nonIntType) + => TestDiagnosticsAsync($$""" using System.Runtime.CompilerServices; [InterpolatedStringHandler] @@ -2073,7 +1859,6 @@ public MyInterpolatedStringHandler({{nonIntType}} {|IDE0060:p|}) } } """); - } public static IEnumerable NonIntTypes() { diff --git a/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueAssignmentTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueAssignmentTests.cs index 70413925b1361..cf73e55704571 100644 --- a/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueAssignmentTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueAssignmentTests.cs @@ -42,10 +42,10 @@ public void TestStandardProperty(AnalyzerProperty property) => VerifyCS.VerifyStandardProperty(property); [Fact] - public async Task Initialization_Suppressed() - { - var source = - """ + public Task Initialization_Suppressed() + => new VerifyCS.Test + { + TestCode = """ class C { int M() @@ -55,23 +55,18 @@ int M() return x; } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, UnusedValuePreference.DiscardVariable, NotificationOption2.None }, }, }.RunAsync(); - } [Fact] - public async Task Assignment_Suppressed() - { - var source = - """ + public Task Assignment_Suppressed() + => new VerifyCS.Test + { + TestCode = """ class C { int M() @@ -82,25 +77,20 @@ int M() return x; } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, UnusedValuePreference.DiscardVariable, NotificationOption2.None }, }, }.RunAsync(); - } [Theory] [InlineData(UnusedValuePreference.DiscardVariable)] [InlineData(UnusedValuePreference.UnusedLocalVariable)] - public async Task Initialization_ConstantValue(object option) - { - var source = - """ + public Task Initialization_ConstantValue(object option) + => new VerifyCS.Test + { + TestCode = """ class C { int M() @@ -110,9 +100,8 @@ int M() return x; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { int M() @@ -121,26 +110,20 @@ int M() return x; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, (UnusedValuePreference)option }, }, }.RunAsync(); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/48070")] [InlineData(UnusedValuePreference.DiscardVariable)] [InlineData(UnusedValuePreference.UnusedLocalVariable)] - public async Task Initialization_ConstantValue_DoNotCopyLeadingTriviaDirectives(object option) - { - var source = - """ + public Task Initialization_ConstantValue_DoNotCopyLeadingTriviaDirectives(object option) + => new VerifyCS.Test + { + TestCode = """ class C { void M() { @@ -155,9 +138,8 @@ void M() System.Console.WriteLine(x); } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M() { @@ -171,24 +153,18 @@ void M() System.Console.WriteLine(x); } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, (UnusedValuePreference)option }, }, }.RunAsync(); - } [Fact] - public async Task Initialization_ConstantValue_RemoveUnusedParametersSuppressed() - { - var source = - """ + public Task Initialization_ConstantValue_RemoveUnusedParametersSuppressed() + => new VerifyCS.Test + { + TestCode = """ class C { int M() @@ -198,9 +174,8 @@ int M() return x; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { int M() @@ -209,24 +184,18 @@ int M() return x; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CodeStyleOptions2.UnusedParameters, UnusedParametersPreference.NonPublicMethods, NotificationOption2.None }, }, }.RunAsync(); - } [Fact] - public async Task Initialization_ConstantValue_RemoveUnusedParametersNotApplicable() - { - var source = - """ + public Task Initialization_ConstantValue_RemoveUnusedParametersNotApplicable() + => new VerifyCS.Test + { + TestCode = """ class C { public int M(int {|IDE0060:z|}) @@ -236,9 +205,8 @@ public int M(int {|IDE0060:z|}) return x; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { public int M(int {|IDE0060:z|}) @@ -247,26 +215,20 @@ public int M(int {|IDE0060:z|}) return x; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CodeStyleOptions2.UnusedParameters, UnusedParametersPreference.NonPublicMethods, NotificationOption2.Silent }, }, }.RunAsync(); - } [Theory] [InlineData(UnusedValuePreference.DiscardVariable)] [InlineData(UnusedValuePreference.UnusedLocalVariable)] - public async Task Assignment_ConstantValue(object option) - { - var source = - """ + public Task Assignment_ConstantValue(object option) + => new VerifyCS.Test + { + TestCode = """ class C { int M() @@ -277,9 +239,8 @@ int M() return x; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { int M() @@ -289,26 +250,20 @@ int M() return x; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, (UnusedValuePreference)option }, }, }.RunAsync(); - } [Theory] [InlineData(UnusedValuePreference.DiscardVariable)] [InlineData(UnusedValuePreference.UnusedLocalVariable)] - public async Task Assignment_ConstantValue_NoReads(object option) - { - var source = - """ + public Task Assignment_ConstantValue_NoReads(object option) + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -317,33 +272,26 @@ void M() {|IDE0059:x|} = 1; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M() { } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, (UnusedValuePreference)option }, }, }.RunAsync(); - } [Fact] - public async Task Assignment_NonConstantValue_NoReads_PreferDiscard() - { - var source = - """ + public Task Assignment_NonConstantValue_NoReads_PreferDiscard() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -354,9 +302,8 @@ void M() int M2() => 0; } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M() @@ -366,24 +313,18 @@ void M() int M2() => 0; } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, UnusedValuePreference.DiscardVariable }, }, }.RunAsync(); - } [Fact] - public async Task Assignment_NonConstantValue_NoReads_PreferUnusedLocal() - { - var source = - """ + public Task Assignment_NonConstantValue_NoReads_PreferUnusedLocal() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -394,25 +335,20 @@ void M() int M2() => 0; } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, UnusedValuePreference.UnusedLocalVariable }, }, }.RunAsync(); - } [Theory] [InlineData(UnusedValuePreference.DiscardVariable)] [InlineData(UnusedValuePreference.UnusedLocalVariable)] - public async Task Initialization_NonConstantValue_ParameterReference(object option) - { - var source = - """ + public Task Initialization_NonConstantValue_ParameterReference(object option) + => new VerifyCS.Test + { + TestCode = """ class C { int M(int p) @@ -422,9 +358,8 @@ int M(int p) return x; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { int M(int {|IDE0060:p|}) @@ -433,26 +368,20 @@ int M(int {|IDE0060:p|}) return x; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, (UnusedValuePreference)option }, }, }.RunAsync(); - } [Theory] [InlineData(UnusedValuePreference.DiscardVariable)] [InlineData(UnusedValuePreference.UnusedLocalVariable)] - public async Task Assignment_NonConstantValue_ParameterReference(object option) - { - var source = - """ + public Task Assignment_NonConstantValue_ParameterReference(object option) + => new VerifyCS.Test + { + TestCode = """ class C { int M(int p) @@ -463,9 +392,8 @@ int M(int p) return x; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { int M(int {|IDE0060:p|}) @@ -475,37 +403,18 @@ int M(int {|IDE0060:p|}) return x; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, (UnusedValuePreference)option }, }, }.RunAsync(); - } [Theory, CombinatorialData] public async Task Initialization_NonConstantValue_LocalReference( [CombinatorialValues(UnusedValuePreference.DiscardVariable, UnusedValuePreference.UnusedLocalVariable)] object option, [CombinatorialValues(CodeFixTestBehaviors.None, CodeFixTestBehaviors.FixOne)] CodeFixTestBehaviors testBehaviors) { - var source = - """ - class C - { - int M() - { - int local = 0; - int {|IDE0059:x|} = local; - x = 2; - return x; - } - } - """; var (fixedSource, iterations) = testBehaviors switch { CodeFixTestBehaviors.None => @@ -536,7 +445,18 @@ int M() await new VerifyCS.Test { - TestCode = source, + TestCode = """ + class C + { + int M() + { + int local = 0; + int {|IDE0059:x|} = local; + x = 2; + return x; + } + } + """, FixedState = { Sources = { fixedSource }, MarkupHandling = MarkupMode.Allow }, CodeFixTestBehaviors = testBehaviors, NumberOfIncrementalIterations = iterations, @@ -553,20 +473,6 @@ public async Task Assignment_NonConstantValue_LocalReference( [CombinatorialValues(UnusedValuePreference.DiscardVariable, UnusedValuePreference.UnusedLocalVariable)] object option, [CombinatorialValues(CodeFixTestBehaviors.None, CodeFixTestBehaviors.FixOne)] CodeFixTestBehaviors testBehaviors) { - var source = - """ - class C - { - int M() - { - int local = 0; - int x; - {|IDE0059:x|} = local; - x = 2; - return x; - } - } - """; var (fixedSource, iterations) = testBehaviors switch { CodeFixTestBehaviors.None => @@ -599,7 +505,19 @@ int M() await new VerifyCS.Test { - TestCode = source, + TestCode = """ + class C + { + int M() + { + int local = 0; + int x; + {|IDE0059:x|} = local; + x = 2; + return x; + } + } + """, FixedState = { Sources = { fixedSource }, MarkupHandling = MarkupMode.Allow }, CodeFixTestBehaviors = testBehaviors, NumberOfIncrementalIterations = iterations, @@ -614,10 +532,10 @@ int M() [Theory] [InlineData(UnusedValuePreference.DiscardVariable)] [InlineData(UnusedValuePreference.UnusedLocalVariable)] - public async Task Initialization_NonConstantValue_DefaultExpression(object option) - { - var source = - """ + public Task Initialization_NonConstantValue_DefaultExpression(object option) + => new VerifyCS.Test + { + TestCode = """ struct C { C M() @@ -627,9 +545,8 @@ C M() return c; } } - """; - var fixedSource = - """ + """, + FixedCode = """ struct C { C M() @@ -638,26 +555,20 @@ C M() return c; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, (UnusedValuePreference)option }, }, }.RunAsync(); - } [Theory] [InlineData(UnusedValuePreference.DiscardVariable)] [InlineData(UnusedValuePreference.UnusedLocalVariable)] - public async Task Initialization_NonConstantValue_CastExpression(object option) - { - var source = - """ + public Task Initialization_NonConstantValue_CastExpression(object option) + => new VerifyCS.Test + { + TestCode = """ struct C { C M(object obj) @@ -667,9 +578,8 @@ C M(object obj) return c; } } - """; - var fixedSource = - """ + """, + FixedCode = """ struct C { C M(object {|IDE0060:obj|}) @@ -678,26 +588,20 @@ C M(object {|IDE0060:obj|}) return c; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, (UnusedValuePreference)option }, }, }.RunAsync(); - } [Theory] [InlineData(UnusedValuePreference.DiscardVariable)] [InlineData(UnusedValuePreference.UnusedLocalVariable)] - public async Task Initialization_NonConstantValue_FieldReferenceWithThisReceiver(object option) - { - var source = - """ + public Task Initialization_NonConstantValue_FieldReferenceWithThisReceiver(object option) + => new VerifyCS.Test + { + TestCode = """ class C { private int field; @@ -708,9 +612,8 @@ int M() return x; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { private int field; @@ -720,26 +623,20 @@ int M() return x; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, (UnusedValuePreference)option }, }, }.RunAsync(); - } [Theory] [InlineData(UnusedValuePreference.DiscardVariable)] [InlineData(UnusedValuePreference.UnusedLocalVariable)] - public async Task Assignment_NonConstantValue_FieldReferenceWithNullReceiver(object option) - { - var source = - """ + public Task Assignment_NonConstantValue_FieldReferenceWithNullReceiver(object option) + => new VerifyCS.Test + { + TestCode = """ class C { private static int field; @@ -751,9 +648,8 @@ int M() return x; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { private static int field; @@ -764,26 +660,20 @@ int M() return x; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, (UnusedValuePreference)option }, }, }.RunAsync(); - } [Theory] [InlineData(UnusedValuePreference.DiscardVariable, "_")] [InlineData(UnusedValuePreference.UnusedLocalVariable, "int unused")] - public async Task Assignment_NonConstantValue_FieldReferenceWithReceiver(object option, string fix) - { - var source = - """ + public Task Assignment_NonConstantValue_FieldReferenceWithReceiver(object option, string fix) + => new VerifyCS.Test + { + TestCode = """ class C { private int field; @@ -795,9 +685,8 @@ int M(C c) return x; } } - """; - var fixedSource = - $$""" + """, + FixedCode = $$""" class C { private int field; @@ -809,26 +698,20 @@ int M(C c) return x; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, (UnusedValuePreference)option }, }, }.RunAsync(); - } [Theory] [InlineData(UnusedValuePreference.DiscardVariable, "_")] [InlineData(UnusedValuePreference.UnusedLocalVariable, "int unused")] - public async Task Initialization_NonConstantValue_PropertyReference(object option, string fix) - { - var source = - """ + public Task Initialization_NonConstantValue_PropertyReference(object option, string fix) + => new VerifyCS.Test + { + TestCode = """ class C { private int Property { get { throw new System.Exception(); } } @@ -840,9 +723,8 @@ int M() return x; } } - """; - var fixedSource = - $$""" + """, + FixedCode = $$""" class C { private int Property { get { throw new System.Exception(); } } @@ -854,26 +736,20 @@ int M() return x; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, (UnusedValuePreference)option }, }, }.RunAsync(); - } [Theory] [InlineData(UnusedValuePreference.DiscardVariable, "_")] [InlineData(UnusedValuePreference.UnusedLocalVariable, "int unused")] - public async Task Initialization_NonConstantValue_MethodInvocation(object option, string fix) - { - var source = - """ + public Task Initialization_NonConstantValue_MethodInvocation(object option, string fix) + => new VerifyCS.Test + { + TestCode = """ class C { int M() @@ -885,9 +761,8 @@ int M() int M2() => 0; } - """; - var fixedSource = - $$""" + """, + FixedCode = $$""" class C { int M() @@ -899,25 +774,18 @@ int M() int M2() => 0; } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, (UnusedValuePreference)option }, }, }.RunAsync(); - } [Fact] - public async Task Initialization_NonConstantValue_PreferDiscard_CSharp6() - { - // Discard not supported in C# 6.0, so we fallback to unused local variable. - var source = - """ + public Task Initialization_NonConstantValue_PreferDiscard_CSharp6() + => new VerifyCS.Test + { + TestCode = """ class C { int M() @@ -929,9 +797,8 @@ int M() int M2() => 0; } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { int M() @@ -943,27 +810,21 @@ int M() int M2() => 0; } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, UnusedValuePreference.DiscardVariable }, }, LanguageVersion = LanguageVersion.CSharp6, }.RunAsync(); - } [Theory] [InlineData(UnusedValuePreference.DiscardVariable, "_")] [InlineData(UnusedValuePreference.UnusedLocalVariable, "int unused")] - public async Task Assignment_NonConstantValue_MethodInvocation(object option, string fix) - { - var source = - """ + public Task Assignment_NonConstantValue_MethodInvocation(object option, string fix) + => new VerifyCS.Test + { + TestCode = """ class C { int M() @@ -976,9 +837,8 @@ int M() int M2() => 0; } - """; - var fixedSource = - $$""" + """, + FixedCode = $$""" class C { int M() @@ -991,26 +851,20 @@ int M() int M2() => 0; } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, (UnusedValuePreference)option }, }, }.RunAsync(); - } [Theory] [InlineData(UnusedValuePreference.DiscardVariable)] [InlineData(UnusedValuePreference.UnusedLocalVariable)] - public async Task Assignment_NonConstantValue_ImplicitConversion(object option) - { - var source = - """ + public Task Assignment_NonConstantValue_ImplicitConversion(object option) + => new VerifyCS.Test + { + TestCode = """ class C { int M(int {|IDE0060:x|}, short s) @@ -1020,9 +874,8 @@ int M(int {|IDE0060:x|}, short s) return x; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { int M(int {|IDE0060:x|}, short {|IDE0060:s|}) @@ -1031,26 +884,20 @@ int M(int {|IDE0060:x|}, short {|IDE0060:s|}) return x; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, (UnusedValuePreference)option }, }, }.RunAsync(); - } [Theory] [InlineData(UnusedValuePreference.DiscardVariable, "_")] [InlineData(UnusedValuePreference.UnusedLocalVariable, "int unused")] - public async Task Assignment_NonConstantValue_UserDefinedConversion(object option, string fix) - { - var source = - """ + public Task Assignment_NonConstantValue_UserDefinedConversion(object option, string fix) + => new VerifyCS.Test + { + TestCode = """ class C { int M(int {|IDE0060:x|}, C c) @@ -1070,9 +917,8 @@ public static explicit operator C(int {|IDE0060:i|}) return default(C); } } - """; - var fixedSource = - $$""" + """, + FixedCode = $$""" class C { int M(int {|IDE0060:x|}, C c) @@ -1092,37 +938,18 @@ public static explicit operator C(int {|IDE0060:i|}) return default(C); } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, (UnusedValuePreference)option }, }, }.RunAsync(); - } [Theory, CombinatorialData] public async Task NestedAssignment_ConstantValue( [CombinatorialValues(UnusedValuePreference.DiscardVariable, UnusedValuePreference.UnusedLocalVariable)] object option, [CombinatorialValues(CodeFixTestBehaviors.None, CodeFixTestBehaviors.FixOne | CodeFixTestBehaviors.SkipFixAllCheck)] CodeFixTestBehaviors testBehaviors) { - var source = - """ - class C - { - int M(int {|IDE0060:x|}, int {|IDE0060:y|}) - { - {|IDE0059:y|} = {|IDE0059:x|} = 1; - x = 2; - return x; - } - } - """; - var (fixedSource, iterations) = ((UnusedValuePreference)option, testBehaviors) switch { (UnusedValuePreference.DiscardVariable, CodeFixTestBehaviors.None) => @@ -1165,7 +992,17 @@ int M(int {|IDE0060:x|}, int {|IDE0060:y|}) var test = new VerifyCS.Test { - TestCode = source, + TestCode = """ + class C + { + int M(int {|IDE0060:x|}, int {|IDE0060:y|}) + { + {|IDE0059:y|} = {|IDE0059:x|} = 1; + x = 2; + return x; + } + } + """, FixedState = { Sources = { fixedSource }, MarkupHandling = MarkupMode.Allow }, CodeFixTestBehaviors = testBehaviors, NumberOfIncrementalIterations = iterations, @@ -1189,21 +1026,6 @@ public async Task NestedAssignment_NonConstantValue( [CombinatorialValues(UnusedValuePreference.DiscardVariable, UnusedValuePreference.UnusedLocalVariable)] object option, [CombinatorialValues(CodeFixTestBehaviors.None, CodeFixTestBehaviors.FixOne | CodeFixTestBehaviors.SkipFixAllCheck)] CodeFixTestBehaviors testBehaviors) { - var source = - """ - class C - { - int M(int {|IDE0060:x|}, int {|IDE0060:y|}) - { - {|IDE0059:y|} = {|IDE0059:x|} = M2(); - x = 2; - return x; - } - - int M2() => 0; - } - """; - var fixedSource = ((UnusedValuePreference)option, testBehaviors) switch { (UnusedValuePreference.DiscardVariable, CodeFixTestBehaviors.None) => @@ -1269,7 +1091,19 @@ int M(int {|IDE0060:x|}, int {|IDE0060:y|}) var test = new VerifyCS.Test { - TestCode = source, + TestCode = """ + class C + { + int M(int {|IDE0060:x|}, int {|IDE0060:y|}) + { + {|IDE0059:y|} = {|IDE0059:x|} = M2(); + x = 2; + return x; + } + + int M2() => 0; + } + """, FixedState = { Sources = { fixedSource }, MarkupHandling = MarkupMode.Allow }, CodeFixTestBehaviors = testBehaviors, Options = @@ -1289,10 +1123,10 @@ int M(int {|IDE0060:x|}, int {|IDE0060:y|}) [Theory] [InlineData(UnusedValuePreference.DiscardVariable)] [InlineData(UnusedValuePreference.UnusedLocalVariable)] - public async Task ReadAndWriteInSameExpression_MethodInvocation(object option) - { - var source = - """ + public Task ReadAndWriteInSameExpression_MethodInvocation(object option) + => new VerifyCS.Test + { + TestCode = """ class C { int M() @@ -1304,17 +1138,12 @@ int M() int M2(int x) => x; } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, (UnusedValuePreference)option }, }, }.RunAsync(); - } [Theory, CombinatorialData] public async Task IncrementOrDecrementOperator_ValueUsed_SameStatement( @@ -1377,8 +1206,9 @@ public async Task IncrementOrDecrementOperator_ValueUsed_LaterStatement( [CombinatorialValues(UnusedValuePreference.DiscardVariable, UnusedValuePreference.UnusedLocalVariable)] object option) { var (prefix, postfix) = applyAsPrefix ? (@operator, "") : ("", @operator); - var source = - $$""" + await new VerifyCS.Test + { + TestCode = $$""" class C { int M(int x) @@ -1387,11 +1217,7 @@ int M(int x) return x; } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, (UnusedValuePreference)option }, @@ -1406,8 +1232,9 @@ public async Task IncrementOrDecrementOperator_ValueUnused( [CombinatorialValues(UnusedValuePreference.DiscardVariable, UnusedValuePreference.UnusedLocalVariable)] object option) { var (prefix, postfix) = applyAsPrefix ? (@operator, "") : ("", @operator); - var source = - $$""" + await new VerifyCS.Test + { + TestCode = $$""" class C { void M(int x) @@ -1415,21 +1242,15 @@ void M(int x) {{prefix}}{|IDE0059:x|}{{postfix}}; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int {|IDE0060:x|}) { } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, (UnusedValuePreference)option }, @@ -1494,12 +1315,12 @@ void M(int x) } [Theory, CombinatorialData] - public async Task CompoundAssignmentOperator_ValueUsed_LaterStatement( + public Task CompoundAssignmentOperator_ValueUsed_LaterStatement( [CombinatorialValues("1" /*Constant*/, "M2()" /*Non-constant*/)] string rightHandSide, [CombinatorialValues(UnusedValuePreference.DiscardVariable, UnusedValuePreference.UnusedLocalVariable)] object option) - { - var source = - $$""" + => new VerifyCS.Test + { + TestCode = $$""" class C { int M(int x) @@ -1510,25 +1331,20 @@ int M(int x) int M2() => 0; } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, (UnusedValuePreference)option }, }, }.RunAsync(); - } [Theory, CombinatorialData] - public async Task CompoundLogicalOrOperator_ValueUsed_LaterStatement( + public Task CompoundLogicalOrOperator_ValueUsed_LaterStatement( [CombinatorialValues("true" /*Constant*/, "M2()" /*Non-constant*/)] string rightHandSide, [CombinatorialValues(UnusedValuePreference.DiscardVariable, UnusedValuePreference.UnusedLocalVariable)] object option) - { - var source = - $$""" + => new VerifyCS.Test + { + TestCode = $$""" class C { bool M(bool x) @@ -1539,25 +1355,20 @@ bool M(bool x) bool M2() => true; } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, (UnusedValuePreference)option }, }, }.RunAsync(); - } [Theory, CombinatorialData] - public async Task CompoundLogicalOrOperator_ValueUsed_LaterStatement_02( + public Task CompoundLogicalOrOperator_ValueUsed_LaterStatement_02( [CombinatorialValues("true" /*Constant*/, "M2()" /*Non-constant*/)] string rightHandSide, [CombinatorialValues(UnusedValuePreference.DiscardVariable, UnusedValuePreference.UnusedLocalVariable)] object option) - { - var source = - $$""" + => new VerifyCS.Test + { + TestCode = $$""" class C { bool M() @@ -1569,24 +1380,18 @@ bool M() bool M2() => true; } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, (UnusedValuePreference)option }, }, }.RunAsync(); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task CompoundAssignmentOperator_ValueNotUsed_ConstantValue(string optionName) - { - await TestInRegularAndScriptAsync( + public Task CompoundAssignmentOperator_ValueNotUsed_ConstantValue(string optionName) + => TestInRegularAndScriptAsync( """ class C { @@ -1604,14 +1409,12 @@ int M(int x) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard), "_")] [InlineData(nameof(PreferUnusedLocal), "int unused")] - public async Task CompoundAssignmentOperator_ValueNotUsed_NonConstantValue(string optionName, string fix) - { - await TestInRegularAndScriptAsync( + public Task CompoundAssignmentOperator_ValueNotUsed_NonConstantValue(string optionName, string fix) + => TestInRegularAndScriptAsync( $$""" class C { @@ -1634,14 +1437,12 @@ int M(int x) int M2() => 0; } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task NullCoalescing_ReadWrite(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task NullCoalescing_ReadWrite(string optionName) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1655,14 +1456,12 @@ C M() C M2() => null; } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task LValueFlowCapture_Assignment_ControlFlowInAssignedTarget(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task LValueFlowCapture_Assignment_ControlFlowInAssignedTarget(string optionName) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1676,14 +1475,12 @@ C M(C y) C M2() => null; } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard), "_")] [InlineData(nameof(PreferUnusedLocal), "var unused")] - public async Task LValueFlowCapture_Assignment_ControlFlowInAssignedValue_01(string optionName, string fix) - { - await TestInRegularAndScriptAsync( + public Task LValueFlowCapture_Assignment_ControlFlowInAssignedValue_01(string optionName, string fix) + => TestInRegularAndScriptAsync( """ class C { @@ -1710,14 +1507,12 @@ C M(C y, C z) C M2() => null; } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task LValueFlowCapture_Assignment_ControlFlowInAssignedValue_02(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task LValueFlowCapture_Assignment_ControlFlowInAssignedValue_02(string optionName) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1731,14 +1526,12 @@ C M(C y, C z) C M2() => null; } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task LValueFlowCapture_DeconstructionAssignment_ControlFlowInAssignedTarget(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task LValueFlowCapture_DeconstructionAssignment_ControlFlowInAssignedTarget(string optionName) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1752,14 +1545,12 @@ C M(C y) C M2() => null; } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard), "_")] [InlineData(nameof(PreferUnusedLocal), "var unused")] - public async Task LValueFlowCapture_DeconstructionAssignment_ControlFlowInAssignedValue_01(string optionName, string fix) - { - await TestInRegularAndScriptAsync( + public Task LValueFlowCapture_DeconstructionAssignment_ControlFlowInAssignedValue_01(string optionName, string fix) + => TestInRegularAndScriptAsync( """ class C { @@ -1787,14 +1578,12 @@ C M(C y, C z) C M2() => null; } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task LValueFlowCapture_DeconstructionAssignment_ControlFlowInAssignedValue_02(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task LValueFlowCapture_DeconstructionAssignment_ControlFlowInAssignedValue_02(string optionName) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1808,12 +1597,10 @@ C M(C y, C z) C M2() => null; } """, optionName); - } [Fact] - public async Task Initialization_NonConstantValue_NoReferences_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task Initialization_NonConstantValue_NoReferences_PreferDiscard() + => TestInRegularAndScriptAsync( """ class C { @@ -1836,12 +1623,10 @@ void M() int M2() => 0; } """, options: PreferDiscard); - } [Fact] - public async Task Initialization_NonConstantValue_NoReferences_PreferUnusedLocal() - { - await TestMissingInRegularAndScriptAsync( + public Task Initialization_NonConstantValue_NoReferences_PreferUnusedLocal() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1853,12 +1638,10 @@ void M() int M2() => 0; } """, new TestParameters(options: PreferUnusedLocal)); - } [Fact] - public async Task Initialization_NonConstantValue_NoReadReferences_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task Initialization_NonConstantValue_NoReadReferences_PreferDiscard() + => TestInRegularAndScriptAsync( """ class C { @@ -1883,12 +1666,10 @@ void M() int M2() => 0; } """, options: PreferDiscard); - } [Fact] - public async Task Initialization_NonConstantValue_NoReadReferences_PreferUnusedLocal() - { - await TestMissingInRegularAndScriptAsync( + public Task Initialization_NonConstantValue_NoReadReferences_PreferUnusedLocal() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1901,14 +1682,12 @@ void M() int M2() => 0; } """, new TestParameters(options: PreferUnusedLocal)); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task Initialization_ConstantValue_FirstField(string optionName) - { - await TestInRegularAndScriptAsync( + public Task Initialization_ConstantValue_FirstField(string optionName) + => TestInRegularAndScriptAsync( """ class C { @@ -1931,14 +1710,12 @@ int M() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task Initialization_ConstantValue_MiddleField(string optionName) - { - await TestInRegularAndScriptAsync( + public Task Initialization_ConstantValue_MiddleField(string optionName) + => TestInRegularAndScriptAsync( """ class C { @@ -1961,14 +1738,12 @@ int M() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task Initialization_ConstantValue_LastField(string optionName) - { - await TestInRegularAndScriptAsync( + public Task Initialization_ConstantValue_LastField(string optionName) + => TestInRegularAndScriptAsync( """ class C { @@ -1991,12 +1766,10 @@ int M() } } """, optionName); - } [Fact] - public async Task Initialization_NonConstantValue_FirstField_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task Initialization_NonConstantValue_FirstField_PreferDiscard() + => TestInRegularAndScriptAsync( """ class C { @@ -2024,12 +1797,10 @@ int M() void M2() => 0; } """, options: PreferDiscard); - } [Fact] - public async Task Initialization_NonConstantValue_FirstField_PreferUnusedLocal() - { - await TestInRegularAndScriptAsync( + public Task Initialization_NonConstantValue_FirstField_PreferUnusedLocal() + => TestInRegularAndScriptAsync( """ class C { @@ -2056,12 +1827,10 @@ int M() void M2() => 0; } """, options: PreferUnusedLocal); - } [Fact] - public async Task Initialization_NonConstantValue_MiddleField_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task Initialization_NonConstantValue_MiddleField_PreferDiscard() + => TestInRegularAndScriptAsync( """ class C { @@ -2090,12 +1859,10 @@ int M() void M2() => 0; } """, options: PreferDiscard); - } [Fact] - public async Task Initialization_NonConstantValue_MiddleField_PreferUnusedLocal() - { - await TestInRegularAndScriptAsync( + public Task Initialization_NonConstantValue_MiddleField_PreferUnusedLocal() + => TestInRegularAndScriptAsync( """ class C { @@ -2122,12 +1889,10 @@ int M() void M2() => 0; } """, options: PreferUnusedLocal); - } [Fact] - public async Task Initialization_NonConstantValue_LastField_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task Initialization_NonConstantValue_LastField_PreferDiscard() + => TestInRegularAndScriptAsync( """ class C { @@ -2155,12 +1920,10 @@ int M() void M2() => 0; } """, options: PreferDiscard); - } [Fact] - public async Task Initialization_NonConstantValue_LastField_PreferUnusedLocal() - { - await TestInRegularAndScriptAsync( + public Task Initialization_NonConstantValue_LastField_PreferUnusedLocal() + => TestInRegularAndScriptAsync( """ class C { @@ -2187,14 +1950,12 @@ int M() void M2() => 0; } """, options: PreferUnusedLocal); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task Assignment_BeforeUseAsOutArgument(string optionName) - { - await TestInRegularAndScriptAsync( + public Task Assignment_BeforeUseAsOutArgument(string optionName) + => TestInRegularAndScriptAsync( """ class C { @@ -2222,14 +1983,12 @@ int M() void M2(out int x) => x = 0; } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task NonRedundantAssignment_BeforeUseAsRefArgument(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task NonRedundantAssignment_BeforeUseAsRefArgument(string optionName) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2244,14 +2003,12 @@ int M() void M2(ref int x) => x = 0; } """, optionName); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/40717")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task NonRedundantAssignment_AfterUseAsRefArgument(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task NonRedundantAssignment_AfterUseAsRefArgument(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2274,14 +2031,12 @@ static Span M(ref int value) } } """, optionName); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/40483")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task NonRedundantAssignment_AfterUseAsRefArgument_02(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task NonRedundantAssignment_AfterUseAsRefArgument_02(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2307,14 +2062,12 @@ static void F() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task NonRedundantAssignment_BeforeUseAsInArgument(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task NonRedundantAssignment_BeforeUseAsInArgument(string optionName) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2329,12 +2082,10 @@ int M() void M2(in int x) { } } """, optionName); - } [Fact] - public async Task OutArgument_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task OutArgument_PreferDiscard() + => TestInRegularAndScriptAsync( """ class C { @@ -2363,12 +2114,10 @@ int M() void M2(out int x) => x = 0; } """, options: PreferDiscard); - } [Fact] - public async Task OutArgument_PreferUnusedLocal() - { - await TestInRegularAndScriptAsync( + public Task OutArgument_PreferUnusedLocal() + => TestInRegularAndScriptAsync( """ class C { @@ -2398,12 +2147,10 @@ int M() void M2(out int x) => x = 0; } """, options: PreferUnusedLocal); - } [Fact] - public async Task OutVarArgument_ExpressionBody_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task OutVarArgument_ExpressionBody_PreferDiscard() + => TestInRegularAndScriptAsync( """ class C { @@ -2418,12 +2165,10 @@ class C void M2(out int x) => x = 0; } """, options: PreferDiscard); - } [Fact] - public async Task OutArgument_NoReads_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task OutArgument_NoReads_PreferDiscard() + => TestInRegularAndScriptAsync( """ class C { @@ -2453,12 +2198,10 @@ void M() void M2(out int x) => x = 0; } """, options: PreferDiscard); - } [Fact] - public async Task OutArgument_NoReads_PreferUnusedLocal() - { - await TestMissingInRegularAndScriptAsync( + public Task OutArgument_NoReads_PreferUnusedLocal() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2471,14 +2214,12 @@ void M() void M2(out int x) => x = 0; } """, options: PreferUnusedLocal); - } [Theory] [InlineData(nameof(PreferDiscard), "_")] [InlineData(nameof(PreferUnusedLocal), "var unused")] - public async Task OutDeclarationExpressionArgument(string optionName, string fix) - { - await TestInRegularAndScriptAsync( + public Task OutDeclarationExpressionArgument(string optionName, string fix) + => TestInRegularAndScriptAsync( """ class C { @@ -2505,14 +2246,12 @@ int M() void M2(out int x) => x = 0; } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task NonRedundantRefArgument(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task NonRedundantRefArgument(string optionName) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2526,14 +2265,12 @@ int M(int x) void M2(ref int x) => x = 0; } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task NonRedundantInArgument(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task NonRedundantInArgument(string optionName) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2547,14 +2284,12 @@ int M(int x) void M2(in int x) { } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard), "_")] [InlineData(nameof(PreferUnusedLocal), "unused")] - public async Task DeconstructionDeclarationExpression(string optionName, string fix) - { - await TestInRegularAndScriptAsync( + public Task DeconstructionDeclarationExpression(string optionName, string fix) + => TestInRegularAndScriptAsync( """ class C { @@ -2577,12 +2312,10 @@ int M() } } """, optionName); - } [Fact] - public async Task DeconstructionAssignment_01_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task DeconstructionAssignment_01_PreferDiscard() + => TestInRegularAndScriptAsync( """ class C { @@ -2607,12 +2340,10 @@ int M() } } """, options: PreferDiscard); - } [Fact] - public async Task DeconstructionAssignment_01_PreferUnusedLocal() - { - await TestInRegularAndScriptAsync( + public Task DeconstructionAssignment_01_PreferUnusedLocal() + => TestInRegularAndScriptAsync( """ class C { @@ -2638,14 +2369,12 @@ int M() } } """, options: PreferUnusedLocal); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task DeconstructionAssignment_02(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task DeconstructionAssignment_02(string optionName) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2657,14 +2386,12 @@ int M() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard), "_")] [InlineData(nameof(PreferUnusedLocal), "var unused")] - public async Task TupleExpressionWithDeclarationExpressions(string optionName, string fix) - { - await TestInRegularAndScriptAsync( + public Task TupleExpressionWithDeclarationExpressions(string optionName, string fix) + => TestInRegularAndScriptAsync( """ class C { @@ -2687,12 +2414,10 @@ int M() } } """, optionName); - } [Fact] - public async Task DeclarationPatternInSwitchCase_WithOnlyWriteReference_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task DeclarationPatternInSwitchCase_WithOnlyWriteReference_PreferDiscard() + => TestInRegularAndScriptAsync( """ class C { @@ -2721,12 +2446,10 @@ void M(object p) } } """, options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8)); - } [Fact] - public async Task DeclarationPatternInSwitchCase_WithOnlyWriteReference_PreferDiscard_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task DeclarationPatternInSwitchCase_WithOnlyWriteReference_PreferDiscard_CSharp9() + => TestInRegularAndScriptAsync( """ class C { @@ -2755,13 +2478,11 @@ void M(object p) } } """, options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp9)); - } [Theory, CombinatorialData] - public async Task DeclarationPatternInSwitchCase_WithOnlyWriteReference_PreferUnusedLocal( + public Task DeclarationPatternInSwitchCase_WithOnlyWriteReference_PreferUnusedLocal( [CombinatorialValues(LanguageVersion.CSharp8, LanguageVersion.CSharp9)] LanguageVersion languageVersion) - { - await TestMissingInRegularAndScriptAsync( + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2776,27 +2497,11 @@ void M(object p) } } """, new TestParameters(options: PreferUnusedLocal, parseOptions: new CSharpParseOptions(languageVersion))); - } [Theory, CombinatorialData] public async Task DeclarationPatternInSwitchCase_WithOnlyWriteReference_TypePattern( [CombinatorialValues(CodeFixTestBehaviors.None, CodeFixTestBehaviors.FixOne)] CodeFixTestBehaviors testBehaviors) { - var source = - """ - class C - { - void M(object p) - { - switch (p) - { - case int {|IDE0059:x|}: - {|IDE0059:x|} = 1; - break; - }; - } - } - """; var (fixedSource, iterations) = testBehaviors switch { CodeFixTestBehaviors.None => @@ -2833,7 +2538,20 @@ void M(object p) await new VerifyCS.Test { - TestCode = source, + TestCode = """ + class C + { + void M(object p) + { + switch (p) + { + case int {|IDE0059:x|}: + {|IDE0059:x|} = 1; + break; + }; + } + } + """, FixedState = { Sources = { fixedSource }, MarkupHandling = MarkupMode.Allow }, LanguageVersion = LanguageVersion.CSharp9, CodeFixTestBehaviors = testBehaviors, @@ -2847,9 +2565,8 @@ void M(object p) } [Fact] - public async Task DeclarationPatternInIsPattern_WithNoReference_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task DeclarationPatternInIsPattern_WithNoReference_PreferDiscard() + => TestInRegularAndScriptAsync( """ class C { @@ -2872,12 +2589,10 @@ void M(object p) } } """, options: PreferDiscard); - } [Fact] - public async Task DeclarationPatternInIsPattern_WithNoReference_PreferUnusedLocal() - { - await TestMissingInRegularAndScriptAsync( + public Task DeclarationPatternInIsPattern_WithNoReference_PreferUnusedLocal() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2889,12 +2604,10 @@ void M(object p) } } """, options: PreferUnusedLocal); - } [Fact] - public async Task DeclarationPatternInIsPattern_WithOnlyWriteReference_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task DeclarationPatternInIsPattern_WithOnlyWriteReference_PreferDiscard() + => TestInRegularAndScriptAsync( """ class C { @@ -2919,12 +2632,10 @@ void M(object p) } } """, options: PreferDiscard); - } [Fact] - public async Task DeclarationPatternInIsPattern_WithOnlyWriteReference_PreferUnusedLocal() - { - await TestMissingInRegularAndScriptAsync( + public Task DeclarationPatternInIsPattern_WithOnlyWriteReference_PreferUnusedLocal() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2937,14 +2648,12 @@ void M(object p) } } """, options: PreferUnusedLocal); - } [Theory] [InlineData(nameof(PreferDiscard), "C")] [InlineData(nameof(PreferUnusedLocal), "C unused")] - public async Task DeclarationPatternInIsPattern_WithReadAndWriteReference(string optionName, string fix) - { - await TestInRegularAndScriptAsync( + public Task DeclarationPatternInIsPattern_WithReadAndWriteReference(string optionName, string fix) + => TestInRegularAndScriptAsync( """ class C { @@ -2971,12 +2680,10 @@ void M(object p) } } """, optionName: optionName); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32271")] - public async Task DeclarationPatternInRecursivePattern_WithNoReference_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task DeclarationPatternInRecursivePattern_WithNoReference_PreferDiscard() + => TestInRegularAndScriptAsync( """ class C { @@ -2995,14 +2702,12 @@ void M(object p1, object p2) } } """, options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8)); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32271")] [CombinatorialData] - public async Task DeclarationPatternInRecursivePattern_WithNoReference_PreferUnusedLocal( + public Task DeclarationPatternInRecursivePattern_WithNoReference_PreferUnusedLocal( [CombinatorialValues(LanguageVersion.CSharp8, LanguageVersion.CSharp9)] LanguageVersion languageVersion) - { - await TestMissingInRegularAndScriptAsync( + => TestMissingInRegularAndScriptAsync( """ class C { @@ -3012,24 +2717,12 @@ void M(object p1, object p2) } } """, options: PreferUnusedLocal, parseOptions: new CSharpParseOptions(languageVersion)); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32271")] [CombinatorialData] public async Task DeclarationPatternInRecursivePattern_WithNoReference_TypePattern( [CombinatorialValues(CodeFixTestBehaviors.None, CodeFixTestBehaviors.FixOne)] CodeFixTestBehaviors testBehaviors) { - var source = - """ - class C - { - bool M(object p1, object p2) - { - var isZero = (p1, p2) switch { (0, 0) => true, (int {|IDE0059:x1|}, int {|IDE0059:x2|}) => false }; - return isZero; - } - } - """; var batchFixedSource = """ class C @@ -3060,7 +2753,16 @@ bool M(object p1, object p2) await new VerifyCS.Test { - TestCode = source, + TestCode = """ + class C + { + bool M(object p1, object p2) + { + var isZero = (p1, p2) switch { (0, 0) => true, (int {|IDE0059:x1|}, int {|IDE0059:x2|}) => false }; + return isZero; + } + } + """, FixedState = { Sources = { fixedSource }, MarkupHandling = MarkupMode.Allow }, BatchFixedCode = batchFixedSource, LanguageVersion = LanguageVersion.CSharp9, @@ -3073,9 +2775,8 @@ bool M(object p1, object p2) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32271")] - public async Task DeclarationPatternInRecursivePattern_WithOnlyWriteReference_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task DeclarationPatternInRecursivePattern_WithOnlyWriteReference_PreferDiscard() + => TestInRegularAndScriptAsync( """ class C { @@ -3107,14 +2808,12 @@ bool M2(out int x) } } """, options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8)); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32271")] [CombinatorialData] - public async Task DeclarationPatternInRecursivePattern_WithOnlyWriteReference_PreferUnusedLocal( + public Task DeclarationPatternInRecursivePattern_WithOnlyWriteReference_PreferUnusedLocal( [CombinatorialValues(LanguageVersion.CSharp8, LanguageVersion.CSharp9)] LanguageVersion languageVersion) - { - await TestMissingInRegularAndScriptAsync( + => TestMissingInRegularAndScriptAsync( """ class C { @@ -3130,20 +2829,19 @@ bool M2(out int x) } } """, options: PreferUnusedLocal, parseOptions: new CSharpParseOptions(languageVersion)); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32271")] [CombinatorialData] public async Task DeclarationPatternInRecursivePattern_WithOnlyWriteReference_TypePattern( [CombinatorialValues(CodeFixTestBehaviors.None, CodeFixTestBehaviors.FixOne)] CodeFixTestBehaviors testBehaviors) { - var source = + var batchFixedSource = """ class C { bool M(object p1, object p2) { - var isZero = (p1, p2) switch { (0, 0) => true, (int {|IDE0059:x1|}, int {|IDE0059:x2|}) => M2(out {|IDE0059:x1|}) }; + var isZero = (p1, p2) switch { (0, 0) => true, (int, int) => M2(out _) }; return isZero; } @@ -3154,13 +2852,17 @@ bool M2(out int x) } } """; - var batchFixedSource = + var fixedSource = testBehaviors switch + { + CodeFixTestBehaviors.None => batchFixedSource, + CodeFixTestBehaviors.FixOne => """ class C { bool M(object p1, object p2) { - var isZero = (p1, p2) switch { (0, 0) => true, (int, int) => M2(out _) }; + int x1; + var isZero = (p1, p2) switch { (0, 0) => true, (int, int {|IDE0059:x2|}) => M2(out {|IDE0059:x1|}) }; return isZero; } @@ -3170,18 +2872,18 @@ bool M2(out int x) return false; } } - """; - var fixedSource = testBehaviors switch + """, + _ => throw ExceptionUtilities.Unreachable(), + }; + + await new VerifyCS.Test { - CodeFixTestBehaviors.None => batchFixedSource, - CodeFixTestBehaviors.FixOne => - """ + TestCode = """ class C { bool M(object p1, object p2) { - int x1; - var isZero = (p1, p2) switch { (0, 0) => true, (int, int {|IDE0059:x2|}) => M2(out {|IDE0059:x1|}) }; + var isZero = (p1, p2) switch { (0, 0) => true, (int {|IDE0059:x1|}, int {|IDE0059:x2|}) => M2(out {|IDE0059:x1|}) }; return isZero; } @@ -3192,12 +2894,6 @@ bool M2(out int x) } } """, - _ => throw ExceptionUtilities.Unreachable(), - }; - - await new VerifyCS.Test - { - TestCode = source, FixedState = { Sources = { fixedSource }, MarkupHandling = MarkupMode.Allow }, BatchFixedCode = batchFixedSource, LanguageVersion = LanguageVersion.CSharp9, @@ -3212,9 +2908,8 @@ bool M2(out int x) [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32271")] [InlineData(nameof(PreferDiscard), "_")] [InlineData(nameof(PreferUnusedLocal), "unused")] - public async Task DeclarationPatternInRecursivePattern_WithReadAndWriteReference(string optionName, string fix) - { - await TestInRegularAndScriptAsync( + public Task DeclarationPatternInRecursivePattern_WithReadAndWriteReference(string optionName, string fix) + => TestInRegularAndScriptAsync( """ class C { @@ -3244,14 +2939,12 @@ bool M2(int x) } } """, optionName: optionName, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8)); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32271")] [InlineData(nameof(PreferDiscard), "")] [InlineData(nameof(PreferUnusedLocal), " unused")] - public async Task DeclarationPatternInRecursivePattern_WithReadAndWriteReference_TypePatternxxxxxxxxxxxxxxxxxxxxxx(string optionName, string fix) - { - await TestInRegularAndScriptAsync( + public Task DeclarationPatternInRecursivePattern_WithReadAndWriteReference_TypePatternxxxxxxxxxxxxxxxxxxxxxx(string optionName, string fix) + => TestInRegularAndScriptAsync( """ class C { @@ -3281,7 +2974,6 @@ bool M2(int x) } } """, optionName: optionName, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp9)); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32271")] [CombinatorialData] @@ -3289,23 +2981,6 @@ public async Task DeclarationPatternInRecursivePattern_WithReadAndWriteReference [CombinatorialValues(UnusedValuePreference.DiscardVariable, UnusedValuePreference.UnusedLocalVariable)] object option, [CombinatorialValues(CodeFixTestBehaviors.None, CodeFixTestBehaviors.FixOne | CodeFixTestBehaviors.SkipFixAllCheck)] CodeFixTestBehaviors testBehaviors) { - var source = - """ - class C - { - bool M(object p1, object p2) - { - var isZero = (p1, p2) switch { (0, 0) => true, (int {|IDE0059:x1|}, int {|#0:x2|}) => M2(x1 = 0) && M2(x1) }; - return isZero; - } - - bool M2(int {|IDE0060:x|}) - { - return false; - } - } - """; - var fixedSource = ((UnusedValuePreference)option, testBehaviors) switch { (UnusedValuePreference.DiscardVariable, CodeFixTestBehaviors.None) => @@ -3364,7 +3039,21 @@ bool M2(int {|IDE0060:x|}) var test = new VerifyCS.Test { - TestCode = source, + TestCode = """ + class C + { + bool M(object p1, object p2) + { + var isZero = (p1, p2) switch { (0, 0) => true, (int {|IDE0059:x1|}, int {|#0:x2|}) => M2(x1 = 0) && M2(x1) }; + return isZero; + } + + bool M2(int {|IDE0060:x|}) + { + return false; + } + } + """, FixedState = { Sources = { fixedSource }, MarkupHandling = MarkupMode.Allow }, LanguageVersion = LanguageVersion.CSharp9, CodeFixTestBehaviors = testBehaviors, @@ -3387,9 +3076,8 @@ bool M2(int {|IDE0060:x|}) [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLambda_WithInvocation(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLambda_WithInvocation(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -3407,14 +3095,12 @@ void M(object p) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLocalFunction_WithInvocation_DefinedAtStart(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLocalFunction_WithInvocation_DefinedAtStart(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -3432,14 +3118,12 @@ void LocalFunction() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLocalFunction_WithInvocation_DefinedAtEnd(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLocalFunction_WithInvocation_DefinedAtEnd(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -3457,14 +3141,12 @@ void LocalFunction() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLambda_WithoutInvocation(string optionName) - { - await TestInRegularAndScriptAsync( + public Task UseInLambda_WithoutInvocation(string optionName) + => TestInRegularAndScriptAsync( """ using System; @@ -3494,14 +3176,12 @@ void M(object p) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLocalFunction_WithoutInvocation_DefinedAtStart(string optionName) - { - await TestInRegularAndScriptAsync( + public Task UseInLocalFunction_WithoutInvocation_DefinedAtStart(string optionName) + => TestInRegularAndScriptAsync( """ using System; @@ -3531,14 +3211,12 @@ void LocalFunction() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLocalFunction_WithoutInvocation_DefinedAtEnd(string optionName) - { - await TestInRegularAndScriptAsync( + public Task UseInLocalFunction_WithoutInvocation_DefinedAtEnd(string optionName) + => TestInRegularAndScriptAsync( """ using System; @@ -3568,14 +3246,12 @@ void LocalFunction() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task NotUseInLambda_WithInvocation(string optionName) - { - await TestInRegularAndScriptAsync( + public Task NotUseInLambda_WithInvocation(string optionName) + => TestInRegularAndScriptAsync( """ using System; @@ -3605,14 +3281,12 @@ void M(object p) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task NotUseInLocalFunction_WithInvocation(string optionName) - { - await TestInRegularAndScriptAsync( + public Task NotUseInLocalFunction_WithInvocation(string optionName) + => TestInRegularAndScriptAsync( """ using System; @@ -3642,14 +3316,12 @@ void LocalFunction() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task NotUseInLambda_WithoutInvocation(string optionName) - { - await TestInRegularAndScriptAsync( + public Task NotUseInLambda_WithoutInvocation(string optionName) + => TestInRegularAndScriptAsync( """ using System; @@ -3677,14 +3349,12 @@ void M(object p) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task NotUseInLocalFunction_WithoutInvocation(string optionName) - { - await TestInRegularAndScriptAsync( + public Task NotUseInLocalFunction_WithoutInvocation(string optionName) + => TestInRegularAndScriptAsync( """ using System; @@ -3712,14 +3382,12 @@ void LocalFunction() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task RedundantWriteInLambda_WithInvocation(string optionName) - { - await TestInRegularAndScriptAsync( + public Task RedundantWriteInLambda_WithInvocation(string optionName) + => TestInRegularAndScriptAsync( """ using System; @@ -3749,14 +3417,12 @@ void M(object p) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task RedundantWriteInLocalFunction_WithInvocation(string optionName) - { - await TestInRegularAndScriptAsync( + public Task RedundantWriteInLocalFunction_WithInvocation(string optionName) + => TestInRegularAndScriptAsync( """ using System; @@ -3786,14 +3452,12 @@ void LocalFunction() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task WriteThenReadInLambda_WithInvocation(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task WriteThenReadInLambda_WithInvocation(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -3810,14 +3474,12 @@ void M(object p) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task WriteThenReadInLocalFunction_WithInvocation(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task WriteThenReadInLocalFunction_WithInvocation(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -3834,14 +3496,12 @@ void LocalFunction() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task RedundantWriteInLambda_WithoutInvocation(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task RedundantWriteInLambda_WithoutInvocation(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -3856,14 +3516,12 @@ void M(object p) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task RedundantWriteInLocalFunction_WithoutInvocation(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task RedundantWriteInLocalFunction_WithoutInvocation(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -3878,14 +3536,12 @@ void LocalFunction() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLambda_Nested(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLambda_Nested(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -3910,14 +3566,12 @@ void M(object p) void M2(Action a) => a(); } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLocalFunction_NestedLocalFunction(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLocalFunction_NestedLocalFunction(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -3942,14 +3596,12 @@ void InnerLocalFunction() void M2(Action a) => a(); } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLambda_NestedLocalFunction(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLambda_NestedLocalFunction(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -3969,14 +3621,12 @@ void InnerLocalFunction() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLocalFunction_NestedLambda(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLocalFunction_NestedLambda(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -3997,14 +3647,12 @@ void OuterLocalFunction() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInNestedLambda_InvokedInOuterFunction(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInNestedLambda_InvokedInOuterFunction(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4026,14 +3674,12 @@ void OuterLocalFunction() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInNestedLocalFunction_InvokedInOuterFunction(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInNestedLocalFunction_InvokedInOuterFunction(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4056,14 +3702,12 @@ void NestedLocalFunction() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLambda_ArgumentToLambda(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLambda_ArgumentToLambda(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4076,14 +3720,12 @@ void M(object p, Action myDelegate) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLambda_ArgumentToLambda_02(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLambda_ArgumentToLambda_02(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4096,14 +3738,12 @@ Action M(object p, Action myDelegate) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLambda_PassedAsArgument(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLambda_PassedAsArgument(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4121,14 +3761,12 @@ void M(object p) void M2(Action a) => a(); } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLambda_PassedAsArgument_02(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLambda_PassedAsArgument_02(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4154,14 +3792,12 @@ public static bool M() private static bool M2(C c) => c.Flag; } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLocalFunction_PassedAsArgument(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLocalFunction_PassedAsArgument(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4181,14 +3817,12 @@ void LocalFunction() void M2(Action a) => a(); } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLambda_PassedAsArgument_CustomDelegate(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLambda_PassedAsArgument_CustomDelegate(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4208,14 +3842,12 @@ void M(object p) void M2(MyAction a) => a(); } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLocalFunction_PassedAsArgument_CustomDelegate(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLocalFunction_PassedAsArgument_CustomDelegate(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4237,15 +3869,12 @@ void LocalFunction() void M2(MyAction a) => a(); } """, optionName); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/31744")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UnusedInExpressionTree_PassedAsArgument(string optionName) - { - // Currently we bail out of analysis in presence of expression trees. - await TestMissingInRegularAndScriptAsync( + public Task UnusedInExpressionTree_PassedAsArgument(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; using System.Linq.Expressions; @@ -4262,15 +3891,12 @@ public static void M1() private int M3() { return 0; } } """, optionName); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/31744")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task ReadInExpressionTree_PassedAsArgument(string optionName) - { - // Currently we bail out of analysis in presence of expression trees. - await TestMissingInRegularAndScriptAsync( + public Task ReadInExpressionTree_PassedAsArgument(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; using System.Linq.Expressions; @@ -4287,15 +3913,12 @@ public static void M1() private int M3(object o) { return 0; } } """, optionName); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/31744")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task OnlyWrittenInExpressionTree_PassedAsArgument(string optionName) - { - // Currently we bail out of analysis in presence of expression trees. - await TestMissingInRegularAndScriptAsync( + public Task OnlyWrittenInExpressionTree_PassedAsArgument(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; using System.Linq.Expressions; @@ -4312,14 +3935,12 @@ public static void M1() private int M3(out object o) { o = null; return 0; } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLambda_PassedAsArgument_CastFromDelegateType(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLambda_PassedAsArgument_CastFromDelegateType(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4340,14 +3961,12 @@ void M(object p) void M2(object a) => ((Action)a)(); } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLocalFunction_PassedAsArgument_CastFromDelegateType(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLocalFunction_PassedAsArgument_CastFromDelegateType(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4368,14 +3987,12 @@ void LocalFunction() void M2(object a) => ((Action)a)(); } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLambda_DelegateCreationPassedAsArgument(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLambda_DelegateCreationPassedAsArgument(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4393,14 +4010,12 @@ void M(object p) void M2(Action a) => a(); } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLocalFunction_DelegateCreationPassedAsArgument(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLocalFunction_DelegateCreationPassedAsArgument(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4420,14 +4035,12 @@ void LocalFunction() void M2(Action a) => a(); } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLambda_DelegatePassedAsArgument(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLambda_DelegatePassedAsArgument(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4447,14 +4060,12 @@ void M(object p) void M2(Action a) => a(); } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLocalFunction_DelegatePassedAsArgument(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLocalFunction_DelegatePassedAsArgument(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4475,14 +4086,12 @@ void LocalFunction() void M2(Action a) => a(); } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task WrittenInLambda_DelegatePassedAsArgument(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task WrittenInLambda_DelegatePassedAsArgument(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4504,14 +4113,12 @@ void M(object p, object p2) void M2(Action a) => a(); } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task WrittenInLocalFunction_DelegatePassedAsArgument(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task WrittenInLocalFunction_DelegatePassedAsArgument(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4533,14 +4140,12 @@ void LocalFunction() void M2(Action a) => a(); } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task WrittenInLambdaAndLocalFunctionTargets_DelegatePassedAsArgument(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task WrittenInLambdaAndLocalFunctionTargets_DelegatePassedAsArgument(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4577,14 +4182,12 @@ void LocalFunction() void M2(Action a) => a(); } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLambda_ReturnedDelegateCreation(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLambda_ReturnedDelegateCreation(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4600,14 +4203,12 @@ Action M(object p) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLocalFunction_ReturnedDelegateCreation(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLocalFunction_ReturnedDelegateCreation(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4625,14 +4226,12 @@ void LocalFunction() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLambda_ReturnedDelegate(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLambda_ReturnedDelegate(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4650,14 +4249,12 @@ Action M(object p) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLocalFunction_ReturnedDelegate(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLocalFunction_ReturnedDelegate(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4675,14 +4272,12 @@ void LocalFunction() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLambda_InvokedDelegate_ControlFlow(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLambda_InvokedDelegate_ControlFlow(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4703,14 +4298,12 @@ void M(object p, bool flag) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLocalFunction_InvokedDelegate_ControlFlow(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLocalFunction_InvokedDelegate_ControlFlow(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4732,14 +4325,12 @@ void LocalFunction2() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLambda_LambdaAndLocalFunctionTargets(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLambda_LambdaAndLocalFunctionTargets(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4762,16 +4353,12 @@ void LocalFunction() { } void M2() { } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task NotUsed_LambdaAndLocalFunctionTargets(string optionName) - { - // Below should be changed to verify diagnostic/fix once we - // perform points-to-analysis for accurate delegate target tracking. - await TestMissingInRegularAndScriptAsync( + public Task NotUsed_LambdaAndLocalFunctionTargets(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4793,14 +4380,12 @@ void LocalFunction() { } void M2() { } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLambda_LambdaAndLocalFunctionTargets_ThroughLocalsAndParameters(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLambda_LambdaAndLocalFunctionTargets_ThroughLocalsAndParameters(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4858,14 +4443,12 @@ void LocalFunction() { } void M2() { } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task NotUsed_LambdaAndLocalFunctionTargets_ThroughLocalsAndParameters(string optionName) - { - await TestInRegularAndScriptAsync( + public Task NotUsed_LambdaAndLocalFunctionTargets_ThroughLocalsAndParameters(string optionName) + => TestInRegularAndScriptAsync( """ using System; @@ -4975,14 +4558,12 @@ void LocalFunction() { } void M2() { } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task AssignedInLambda_UsedAfterInvocation(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task AssignedInLambda_UsedAfterInvocation(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5000,14 +4581,12 @@ int M(int x) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task AssignedInLocalFunction_UsedAfterInvocation(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task AssignedInLocalFunction_UsedAfterInvocation(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5026,14 +4605,12 @@ void a() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task AssignedInLambda_UsedAfterSecondInvocation(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task AssignedInLambda_UsedAfterSecondInvocation(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5053,14 +4630,12 @@ int M(int x) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task AssignedInLocalFunction_UsedAfterSecondInvocation(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task AssignedInLocalFunction_UsedAfterSecondInvocation(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5080,14 +4655,12 @@ void a() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task AssignedInLambda_MayBeUsedAfterOneOfTheInvocations(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task AssignedInLambda_MayBeUsedAfterOneOfTheInvocations(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5115,14 +4688,12 @@ int M(int x, bool flag, bool flag2) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task AssignedInLocalFunction_MayBeUsedAfterOneOfTheInvocations(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task AssignedInLocalFunction_MayBeUsedAfterOneOfTheInvocations(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5150,14 +4721,12 @@ void a() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task AssignedInLambda_NotUsedAfterInvocation(string optionName) - { - await TestInRegularAndScriptAsync( + public Task AssignedInLambda_NotUsedAfterInvocation(string optionName) + => TestInRegularAndScriptAsync( """ using System; @@ -5187,14 +4756,12 @@ void M(int x) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task AssignedInLocalFunction_NotUsedAfterInvocation(string optionName) - { - await TestInRegularAndScriptAsync( + public Task AssignedInLocalFunction_NotUsedAfterInvocation(string optionName) + => TestInRegularAndScriptAsync( """ using System; @@ -5226,14 +4793,12 @@ void a() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLocalFunction_WithRecursiveInvocation(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLocalFunction_WithRecursiveInvocation(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5252,14 +4817,12 @@ void LocalFunction() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task NotUseInLocalFunction_WithRecursiveInvocation(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task NotUseInLocalFunction_WithRecursiveInvocation(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5277,15 +4840,12 @@ void LocalFunction() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task Lambda_WithNonReachableExit(string optionName) - { - // We bail out from analysis for delegate passed an argument. - await TestMissingInRegularAndScriptAsync( + public Task Lambda_WithNonReachableExit(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5305,14 +4865,12 @@ void M(object p) void M2(Action a) { } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task Lambda_WithMultipleInvocations(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task Lambda_WithMultipleInvocations(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5336,12 +4894,10 @@ void M2(Action a) } } """, optionName); - } [Fact] - public async Task UnusedValue_DelegateTypeOptionalParameter_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task UnusedValue_DelegateTypeOptionalParameter_PreferDiscard() + => TestInRegularAndScriptAsync( """ using System; @@ -5368,12 +4924,10 @@ void M() C M2(Action c = null) => null; } """, options: PreferDiscard); - } [Fact] - public async Task UnusedValue_DelegateTypeOptionalParameter_PreferUnusedLocal() - { - await TestMissingInRegularAndScriptAsync( + public Task UnusedValue_DelegateTypeOptionalParameter_PreferUnusedLocal() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5387,14 +4941,12 @@ void M() C M2(Action c = null) => null; } """, options: PreferUnusedLocal); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLocalFunction_NestedInvocation(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLocalFunction_NestedInvocation(string optionName) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -5421,14 +4973,12 @@ void LocalFunction() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard), "_")] [InlineData(nameof(PreferUnusedLocal), "unused")] - public async Task DeclarationPatternInSwitchCase_WithReadAndWriteReferences(string optionName, string fix) - { - await TestInRegularAndScriptAsync( + public Task DeclarationPatternInSwitchCase_WithReadAndWriteReferences(string optionName, string fix) + => TestInRegularAndScriptAsync( """ class C { @@ -5459,12 +5009,10 @@ void M(object p) } } """, optionName, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8)); - } [Fact] - public async Task CatchClause_ExceptionVariable_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task CatchClause_ExceptionVariable_PreferDiscard() + => TestInRegularAndScriptAsync( """ using System; @@ -5497,12 +5045,10 @@ void M(object p) } } """, options: PreferDiscard); - } [Fact] - public async Task CatchClause_ExceptionVariable_PreferUnusedLocal_01() - { - await TestMissingInRegularAndScriptAsync( + public Task CatchClause_ExceptionVariable_PreferUnusedLocal_01() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5519,12 +5065,10 @@ void M(object p) } } """, options: PreferUnusedLocal); - } [Fact] - public async Task CatchClause_ExceptionVariable_PreferUnusedLocal_02() - { - await TestInRegularAndScriptAsync( + public Task CatchClause_ExceptionVariable_PreferUnusedLocal_02() + => TestInRegularAndScriptAsync( """ using System; @@ -5561,14 +5105,12 @@ void M(object p) } } """, options: PreferUnusedLocal); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task AssignedOutsideTry_UsedOnlyInCatchClause(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task AssignedOutsideTry_UsedOnlyInCatchClause(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5587,14 +5129,12 @@ void M(int x) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task AssignedOutsideTry_UsedOnlyInCatchFilter(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task AssignedOutsideTry_UsedOnlyInCatchFilter(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5612,14 +5152,12 @@ void M(int x) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task AssignedOutsideTry_UsedOnlyInFinally(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task AssignedOutsideTry_UsedOnlyInFinally(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5638,14 +5176,12 @@ void M(int x) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task AssignedInsideTry_UsedOnlyInCatchClause(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task AssignedInsideTry_UsedOnlyInCatchClause(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5664,14 +5200,12 @@ void M(int x) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task AssignedInsideNestedBlockInTry_UsedOnlyInCatchClause(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task AssignedInsideNestedBlockInTry_UsedOnlyInCatchClause(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5693,14 +5227,12 @@ void M(int x) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task AssignedInCatchClause_UsedAfterTryCatch(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task AssignedInCatchClause_UsedAfterTryCatch(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5720,14 +5252,12 @@ void M(int x) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task AssignedInNestedCatchClause_UsedInOuterFinally(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task AssignedInNestedCatchClause_UsedInOuterFinally(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5752,14 +5282,12 @@ void M(int x) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task AssignedInCatchClause_UsedInFinally(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task AssignedInCatchClause_UsedInFinally(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5781,14 +5309,12 @@ void M(int x) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task AssignedInCatchFilter_UsedAfterTryCatch(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task AssignedInCatchFilter_UsedAfterTryCatch(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5809,14 +5335,12 @@ void M(int x) bool M2(out int x) { x = 0; return true; } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task AssignedInFinally_UsedAfterTryFinally(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task AssignedInFinally_UsedAfterTryFinally(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5836,14 +5360,12 @@ void M(int x) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task AssignedInNestedFinally_UsedInOuterFinally(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task AssignedInNestedFinally_UsedInOuterFinally(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5868,12 +5390,10 @@ void M(int x) } } """, optionName); - } [Fact] - public async Task IfElse_AssignedInCondition_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task IfElse_AssignedInCondition_PreferDiscard() + => TestInRegularAndScriptAsync( """ class C { @@ -5912,12 +5432,10 @@ void M(bool flag) bool M2(out int x) => x = 0; } """, options: PreferDiscard); - } [Fact] - public async Task IfElse_DeclaredInCondition_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task IfElse_DeclaredInCondition_PreferDiscard() + => TestInRegularAndScriptAsync( """ class C { @@ -5955,12 +5473,10 @@ void M(bool flag) bool M2(out int x) => x = 0; } """, options: PreferDiscard); - } [Fact] - public async Task IfElseAssignedInCondition_ReadAfter_PreferUnusedLocal() - { - await TestInRegularAndScriptAsync( + public Task IfElseAssignedInCondition_ReadAfter_PreferUnusedLocal() + => TestInRegularAndScriptAsync( """ class C { @@ -6004,12 +5520,10 @@ int M(bool flag) bool M2(out int x) => x = 0; } """, options: PreferUnusedLocal); - } [Fact] - public async Task IfElse_AssignedInCondition_NoReads_PreferUnusedLocal() - { - await TestMissingInRegularAndScriptAsync( + public Task IfElse_AssignedInCondition_NoReads_PreferUnusedLocal() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -6029,12 +5543,10 @@ void M(bool flag) bool M2(out int x) => x = 0; } """, new TestParameters(options: PreferUnusedLocal)); - } [Fact] - public async Task IfElse_DeclaredInCondition_ReadAfter_PreferUnusedLocal() - { - await TestInRegularAndScriptAsync( + public Task IfElse_DeclaredInCondition_ReadAfter_PreferUnusedLocal() + => TestInRegularAndScriptAsync( """ class C { @@ -6076,12 +5588,10 @@ int M(bool flag) bool M2(out int x) => x = 0; } """, options: PreferUnusedLocal); - } [Fact] - public async Task IfElse_DeclaredInCondition_NoReads_PreferUnusedLocal() - { - await TestMissingInRegularAndScriptAsync( + public Task IfElse_DeclaredInCondition_NoReads_PreferUnusedLocal() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -6100,7 +5610,6 @@ void M(bool flag) bool M2(out int x) => x = 0; } """, new TestParameters(options: PreferUnusedLocal)); - } [Theory] // Simple if-else. @@ -6117,9 +5626,8 @@ void M(bool flag) //Multi-level nesting. [InlineData(@"if(flag) { x = 1; } else { if(flag2) { if(flag3) { x = 2; } else { x = 3; } } else { x = 4; } }", @"x = 5;")] - public async Task IfElse_OverwrittenInAllControlFlowPaths(string ifBranchCode, string elseBranchCode) - { - await TestInRegularAndScriptWithAllOptionsAsync( + public Task IfElse_OverwrittenInAllControlFlowPaths(string ifBranchCode, string elseBranchCode) + => TestInRegularAndScriptWithAllOptionsAsync( $$""" class C { @@ -6158,7 +5666,6 @@ int M(bool flag, bool flag2, bool flag3) } } """); - } [Theory] // Overwrite missing in if path. @@ -6177,9 +5684,8 @@ int M(bool flag, bool flag2, bool flag3) // Overwrite missing in one path with multi-level nesting. [InlineData(@"if(flag) { x = 1; } else { if(flag2) { if(flag3) { x = 2; } } else { x = 3; } }", @"x = 4;")] - public async Task IfElse_OverwrittenInSomeControlFlowPaths(string ifBranchCode, string elseBranchCode) - { - await TestMissingInRegularAndScriptWithAllOptionsAsync( + public Task IfElse_OverwrittenInSomeControlFlowPaths(string ifBranchCode, string elseBranchCode) + => TestMissingInRegularAndScriptWithAllOptionsAsync( $$""" class C { @@ -6199,16 +5705,14 @@ int M(bool flag, bool flag2, bool flag3) } } """); - } [Theory] // Overitten in condition when true, overwritten in else code block when false. [InlineData("flag && M2(out x)", ";", "x = 2;")] // Overitten in condition when false, overwritten in if code block when true. [InlineData("flag || M2(out x)", "x = 2;", ";")] - public async Task IfElse_Overwritten_CodeInOneBranch_ConditionInOtherBranch(string condition, string ifBranchCode, string elseBranchCode) - { - await TestInRegularAndScriptWithAllOptionsAsync( + public Task IfElse_Overwritten_CodeInOneBranch_ConditionInOtherBranch(string condition, string ifBranchCode, string elseBranchCode) + => TestInRegularAndScriptWithAllOptionsAsync( $$""" class C { @@ -6253,7 +5757,6 @@ int M(bool flag) int M3() => 0; } """); - } [Theory] // Overwrite missing in condition when left of || is true. @@ -6262,9 +5765,8 @@ int M(bool flag) [InlineData("flag && M2(out x)")] // Overwrite missing in condition when left of || is true, but both both sides of && have an overwrite. [InlineData("flag || M2(out x) && (x = M3()) > 0")] - public async Task IfElse_MayBeOverwrittenInCondition_LogicalOperators(string condition) - { - await TestMissingInRegularAndScriptWithAllOptionsAsync( + public Task IfElse_MayBeOverwrittenInCondition_LogicalOperators(string condition) + => TestMissingInRegularAndScriptWithAllOptionsAsync( $$""" class C { @@ -6285,7 +5787,6 @@ int M(bool flag) int M3() => 0; } """); - } [Theory] [InlineData("M2(out x) || flag")] @@ -6296,9 +5797,8 @@ int M(bool flag) [InlineData("(flag || M2(out x)) && (x = M3()) > 0")] [InlineData("M2(out x) && flag || (x = M3()) > 0")] [InlineData("flag && M2(out x) || (x = M3()) > 0 && flag")] - public async Task IfElse_OverwrittenInCondition_LogicalOperators(string condition) - { - await TestInRegularAndScriptWithAllOptionsAsync( + public Task IfElse_OverwrittenInCondition_LogicalOperators(string condition) + => TestInRegularAndScriptWithAllOptionsAsync( $$""" class C { @@ -6339,14 +5839,12 @@ int M(bool flag) int M3() => 0; } """); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task ElselessIf(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task ElselessIf(string optionName) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -6362,14 +5860,12 @@ int M(bool flag) } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UnusedDefinition_NotFlagged_InUnreachableBlock(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UnusedDefinition_NotFlagged_InUnreachableBlock(string optionName) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -6392,12 +5888,10 @@ void M() bool M2(out int x) { x = 0; return true; } } """, optionName); - } [Fact] - public async Task SwitchCase_UnusedValueWithOnlyWrite_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task SwitchCase_UnusedValueWithOnlyWrite_PreferDiscard() + => TestInRegularAndScriptAsync( """ class C { @@ -6436,12 +5930,10 @@ int M(int flag) int M2() => 0; } """, options: PreferDiscard); - } [Fact] - public async Task SwitchCase_UnusedValueWithOnlyWrite_PreferUnusedLocal() - { - await TestMissingInRegularAndScriptAsync( + public Task SwitchCase_UnusedValueWithOnlyWrite_PreferUnusedLocal() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -6461,14 +5953,12 @@ int M(int flag) int M2() => 0; } """, options: PreferUnusedLocal); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task SwitchCase_UnusedConstantValue_WithReadsAndWrites(string optionName) - { - await TestInRegularAndScriptAsync( + public Task SwitchCase_UnusedConstantValue_WithReadsAndWrites(string optionName) + => TestInRegularAndScriptAsync( """ class C { @@ -6508,14 +5998,12 @@ int M(int flag) int M2() => 0; } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard), "_")] [InlineData(nameof(PreferUnusedLocal), "int unused")] - public async Task SwitchCase_UnusedNonConstantValue_WithReadsAndWrites(string optionName, string fix) - { - await TestInRegularAndScriptAsync( + public Task SwitchCase_UnusedNonConstantValue_WithReadsAndWrites(string optionName, string fix) + => TestInRegularAndScriptAsync( """ class C { @@ -6556,7 +6044,6 @@ int M(int flag) int M2() => 0; } """, optionName); - } [Theory] // For loop, assignment in body, read on back edge. @@ -6584,10 +6071,9 @@ int M(int flag) while(i++ < 10) """, "x = 2;")] - public async Task Loops_Overwritten_InSomeControlFlowPaths( + public Task Loops_Overwritten_InSomeControlFlowPaths( string loopHeader, string loopBody, string? loopFooter = null) - { - await TestMissingInRegularAndScriptWithAllOptionsAsync( + => TestMissingInRegularAndScriptWithAllOptionsAsync( $$""" class C { @@ -6605,7 +6091,6 @@ int M(int i, int x, bool flag) void M2(int x) { } } """); - } [Theory] // For loop, assignment in body, re-assigned on back edge before read in loop and re-assigned at loop exit. @@ -6655,11 +6140,10 @@ void M2(int x) { } M2(x); """, "x = 4;")] - public async Task Loops_Overwritten_InAllControlFlowPaths( + public Task Loops_Overwritten_InAllControlFlowPaths( string loopHeader, string loopBody, string loopFooter, string fixedLoopHeader, string fixedLoopBody, string fixedLoopFooter) - { - await TestInRegularAndScriptWithAllOptionsAsync( + => TestInRegularAndScriptWithAllOptionsAsync( $$""" class C { @@ -6694,12 +6178,10 @@ int M(int i, int x, bool flag) void M2(int x) { } } """); - } [Fact] - public async Task FixAll_NonConstantValue_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task FixAll_NonConstantValue_PreferDiscard() + => TestInRegularAndScriptAsync( """ class C { @@ -6790,12 +6272,10 @@ int M(bool flag) int M2() => 0; } """, options: PreferDiscard); - } [Fact] - public async Task FixAll_NonConstantValue_PreferUnusedLocal() - { - await TestInRegularAndScriptAsync( + public Task FixAll_NonConstantValue_PreferUnusedLocal() + => TestInRegularAndScriptAsync( """ class C { @@ -6891,14 +6371,12 @@ int M(bool flag) int M2() => 0; } """, options: PreferUnusedLocal); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task FixAll_ConstantValue_RemoveRedundantAssignments(string optionName) - { - await TestInRegularAndScriptAsync( + public Task FixAll_ConstantValue_RemoveRedundantAssignments(string optionName) + => TestInRegularAndScriptAsync( """ class C { @@ -6991,12 +6469,10 @@ int M(bool flag, int p) int M2() => 0; } """, optionName); - } [Fact] - public async Task FixAll_MoveMultipleVariableDeclarations_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task FixAll_MoveMultipleVariableDeclarations_PreferDiscard() + => TestInRegularAndScriptAsync( """ class C { @@ -7055,12 +6531,10 @@ int M(bool flag, int p) int M2() => 0; } """, options: PreferDiscard); - } [Fact] - public async Task FixAll_MoveMultipleVariableDeclarations_PreferUnusedLocal() - { - await TestInRegularAndScriptAsync( + public Task FixAll_MoveMultipleVariableDeclarations_PreferUnusedLocal() + => TestInRegularAndScriptAsync( """ class C { @@ -7118,12 +6592,10 @@ int M(bool flag, int p) int M2() => 0; } """, options: PreferUnusedLocal); - } [Fact] - public async Task NonConstantValue_Trivia_PreferDiscard_01() - { - await TestInRegularAndScriptAsync( + public Task NonConstantValue_Trivia_PreferDiscard_01() + => TestInRegularAndScriptAsync( """ class C { @@ -7156,12 +6628,10 @@ int M() int M2() => 0; } """, options: PreferDiscard); - } [Fact] - public async Task NonConstantValue_Trivia_PreferDiscard_02() - { - await TestInRegularAndScriptAsync( + public Task NonConstantValue_Trivia_PreferDiscard_02() + => TestInRegularAndScriptAsync( """ class C { @@ -7196,12 +6666,10 @@ int M() int M2() => 0; } """, options: PreferDiscard); - } [Fact] - public async Task NonConstantValue_Trivia_PreferUnusedLocal_01() - { - await TestInRegularAndScriptAsync( + public Task NonConstantValue_Trivia_PreferUnusedLocal_01() + => TestInRegularAndScriptAsync( """ class C { @@ -7236,12 +6704,10 @@ int M() int M2() => 0; } """, options: PreferUnusedLocal); - } [Fact] - public async Task NonConstantValue_Trivia_PreferUnusedLocal_02() - { - await TestInRegularAndScriptAsync( + public Task NonConstantValue_Trivia_PreferUnusedLocal_02() + => TestInRegularAndScriptAsync( """ class C { @@ -7277,14 +6743,12 @@ int M() int M2() => 0; } """, options: PreferUnusedLocal); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task ConstantValue_Trivia_01(string optionName) - { - await TestInRegularAndScriptAsync( + public Task ConstantValue_Trivia_01(string optionName) + => TestInRegularAndScriptAsync( """ class C { @@ -7319,14 +6783,12 @@ int M() int M2() => 0; } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task ConstantValue_Trivia_02(string optionName) - { - await TestInRegularAndScriptAsync( + public Task ConstantValue_Trivia_02(string optionName) + => TestInRegularAndScriptAsync( """ class C { @@ -7362,12 +6824,10 @@ int M() int M2() => 0; } """, optionName); - } [Fact] - public async Task ExistingDiscardDeclarationInLambda_UseOutsideLambda() - { - await TestInRegularAndScriptAsync( + public Task ExistingDiscardDeclarationInLambda_UseOutsideLambda() + => TestInRegularAndScriptAsync( """ using System; @@ -7406,12 +6866,10 @@ void M() int M2() => 0; } """, options: PreferDiscard); - } [Fact] - public async Task ExistingDiscardDeclarationInLambda_UseInsideLambda() - { - await TestInRegularAndScriptAsync( + public Task ExistingDiscardDeclarationInLambda_UseInsideLambda() + => TestInRegularAndScriptAsync( """ using System; @@ -7450,14 +6908,12 @@ void M() int M2() => 0; } """, options: PreferDiscard); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task ValueOverwrittenByOutVar_ConditionalAndExpression(string optionName) - { - await TestInRegularAndScriptAsync( + public Task ValueOverwrittenByOutVar_ConditionalAndExpression(string optionName) + => TestInRegularAndScriptAsync( """ using System; @@ -7517,14 +6973,12 @@ bool M2(out int x) } } """, optionName); - } [Theory] [InlineData("var")] [InlineData("int")] - public async Task UnusedOutVariableDeclaration_PreferDiscard(string typeName) - { - await TestInRegularAndScriptAsync( + public Task UnusedOutVariableDeclaration_PreferDiscard(string typeName) + => TestInRegularAndScriptAsync( $$""" class C { @@ -7559,12 +7013,10 @@ bool M2(out int x) } } """, options: PreferDiscard); - } [Fact] - public async Task UnusedOutVariableDeclaration_MethodOverloads_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task UnusedOutVariableDeclaration_MethodOverloads_PreferDiscard() + => TestInRegularAndScriptAsync( """ class C { @@ -7611,14 +7063,12 @@ bool M2(out char x) } } """, options: PreferDiscard); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/31583")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task MissingImports(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task MissingImports(string optionName) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -7628,14 +7078,12 @@ void M() } } """, optionName); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/31583")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UsedAssignment_ConditionalPreprocessorDirective(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UsedAssignment_ConditionalPreprocessorDirective(string optionName) + => TestMissingInRegularAndScriptAsync( """ #define DEBUG @@ -7651,14 +7099,12 @@ int M() } } """, optionName); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32855")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task RefLocalInitialization(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task RefLocalInitialization(string optionName) + => TestMissingInRegularAndScriptAsync( """ class Test { @@ -7671,14 +7117,12 @@ void Method() } } """, optionName); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32855")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task RefLocalAssignment(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task RefLocalAssignment(string optionName) + => TestMissingInRegularAndScriptAsync( """ class Test { @@ -7692,14 +7136,12 @@ int Method() } } """, optionName); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32903")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task DelegateCreationWrappedInATuple_UsedInReturnedLambda(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task DelegateCreationWrappedInATuple_UsedInReturnedLambda(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -7717,12 +7159,10 @@ public class C } } """, optionName); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32923")] - public async Task UnusedLocal_ForEach() - { - await TestDiagnosticsAsync( + public Task UnusedLocal_ForEach() + => TestDiagnosticsAsync( """ using System; @@ -7748,13 +7188,11 @@ void M(S s) } } """, new TestParameters(options: PreferDiscard, retainNonFixableDiagnostics: true), -Diagnostic("IDE0059")); - } + Diagnostic("IDE0059")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60030")] - public async Task UnusedLocal_ForEach_TopLevelStatement() - { - await TestMissingInRegularAndScriptAsync( + public Task UnusedLocal_ForEach_TopLevelStatement() + => TestMissingInRegularAndScriptAsync( """ var items = new[] { new { x = 1 } }; @@ -7762,16 +7200,14 @@ await TestMissingInRegularAndScriptAsync( { } """, PreferDiscard, new CSharpParseOptions(LanguageVersion.CSharp9)); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32923")] [InlineData("_", nameof(PreferDiscard))] [InlineData("_", nameof(PreferUnusedLocal))] [InlineData("_1", nameof(PreferDiscard))] [InlineData("_1", nameof(PreferUnusedLocal))] - public async Task UnusedLocal_SpecialName_01(string variableName, string optionName) - { - await TestDiagnosticMissingAsync( + public Task UnusedLocal_SpecialName_01(string variableName, string optionName) + => TestDiagnosticMissingAsync( $$""" using System; @@ -7797,16 +7233,14 @@ void M(S s) } } """, new TestParameters(options: GetOptions(optionName), retainNonFixableDiagnostics: true)); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32923")] [InlineData("_", nameof(PreferDiscard))] [InlineData("_", nameof(PreferUnusedLocal))] [InlineData("_3", nameof(PreferDiscard))] [InlineData("_3", nameof(PreferUnusedLocal))] - public async Task UnusedLocal_SpecialName_02(string variableName, string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UnusedLocal_SpecialName_02(string variableName, string optionName) + => TestMissingInRegularAndScriptAsync( $$""" using System; @@ -7818,12 +7252,10 @@ public void M(int p) } } """, optionName); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32959")] - public async Task UsedVariable_BailOutOnSemanticError() - { - await TestMissingInRegularAndScriptAsync( + public Task UsedVariable_BailOutOnSemanticError() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -7838,12 +7270,10 @@ void M() } } """, options: PreferDiscard); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32959")] - public async Task UnusedVariable_BailOutOnSemanticError() - { - await TestMissingInRegularAndScriptAsync( + public Task UnusedVariable_BailOutOnSemanticError() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -7858,12 +7288,10 @@ void M() } } """, options: PreferDiscard); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32946")] - public async Task DelegateEscape_01() - { - await TestMissingInRegularAndScriptAsync( + public Task DelegateEscape_01() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -7876,12 +7304,10 @@ Action[] M() } } """, options: PreferDiscard); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32946")] - public async Task DelegateEscape_02() - { - await TestMissingInRegularAndScriptAsync( + public Task DelegateEscape_02() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -7895,12 +7321,10 @@ Action[] M(Action[] actions) } } """, options: PreferDiscard); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32946")] - public async Task DelegateEscape_03() - { - await TestMissingInRegularAndScriptAsync( + public Task DelegateEscape_03() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -7914,12 +7338,10 @@ class C } } """, options: PreferDiscard); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32946")] - public async Task DelegateEscape_04() - { - await TestMissingInRegularAndScriptAsync( + public Task DelegateEscape_04() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -7933,12 +7355,10 @@ List M() } } """, options: PreferDiscard); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32946")] - public async Task DelegateEscape_05() - { - await TestMissingInRegularAndScriptAsync( + public Task DelegateEscape_05() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -7954,12 +7374,10 @@ List M() } } """, options: PreferDiscard); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32924")] - public async Task DelegateEscape_06() - { - await TestMissingInRegularAndScriptAsync( + public Task DelegateEscape_06() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -7972,12 +7390,10 @@ void M() } } """, options: PreferDiscard); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32924")] - public async Task DelegateEscape_07() - { - await TestMissingInRegularAndScriptAsync( + public Task DelegateEscape_07() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -7993,12 +7409,10 @@ void M() } } """, options: PreferDiscard); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32856")] - public async Task RedundantAssignment_IfStatementParent() - { - await TestInRegularAndScriptAsync( + public Task RedundantAssignment_IfStatementParent() + => TestInRegularAndScriptAsync( """ class C { @@ -8023,12 +7437,10 @@ void M(int j) bool M2() => true; } """, options: PreferDiscard); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32856")] - public async Task RedundantAssignment_LoopStatementParent() - { - await TestInRegularAndScriptAsync( + public Task RedundantAssignment_LoopStatementParent() + => TestInRegularAndScriptAsync( """ class C { @@ -8049,12 +7461,10 @@ void M(int j, int[] array) } } """, options: PreferDiscard); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40336")] - public async Task RedundantAssignment_ForStatementVariableDeclarationConstant() - { - await TestInRegularAndScriptAsync( + public Task RedundantAssignment_ForStatementVariableDeclarationConstant() + => TestInRegularAndScriptAsync( """ class C { @@ -8077,12 +7487,10 @@ void M() } } """, options: PreferDiscard); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40336")] - public async Task RedundantAssignment_ForStatementVariableDeclarationMethod() - { - await TestInRegularAndScriptAsync( + public Task RedundantAssignment_ForStatementVariableDeclarationMethod() + => TestInRegularAndScriptAsync( """ class C { @@ -8109,12 +7517,10 @@ void M() } } """, options: PreferDiscard); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40336")] - public async Task RedundantAssignment_ForStatementVariableDeclarationStaticMethod() - { - await TestInRegularAndScriptAsync( + public Task RedundantAssignment_ForStatementVariableDeclarationStaticMethod() + => TestInRegularAndScriptAsync( """ class C { @@ -8141,12 +7547,10 @@ void M() } } """, options: PreferDiscard); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40336")] - public async Task RedundantAssignment_ForStatementVariableDeclarationInsideUsedLambda() - { - await TestInRegularAndScriptAsync( + public Task RedundantAssignment_ForStatementVariableDeclarationInsideUsedLambda() + => TestInRegularAndScriptAsync( """ using System; @@ -8181,13 +7585,10 @@ void M() } } """, options: PreferDiscard); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40336")] - public async Task RedundantAssignment_ForStatementVariableDeclarationInsideUnusedLambda() - { - //NOTE: Currently the diagnostic is only reported on the outer unused variable a. - await TestDiagnosticMissingAsync( + public Task RedundantAssignment_ForStatementVariableDeclarationInsideUnusedLambda() + => TestDiagnosticMissingAsync( """ using System; @@ -8204,12 +7605,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33299")] - public async Task NullCoalesceAssignment_01() - { - await TestMissingInRegularAndScriptWithAllOptionsAsync( + public Task NullCoalesceAssignment_01() + => TestMissingInRegularAndScriptWithAllOptionsAsync( """ class C { @@ -8222,12 +7621,10 @@ public static void M(C x) private static C M2() => null; } """, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33299")] - public async Task NullCoalesceAssignment_02() - { - await TestMissingInRegularAndScriptWithAllOptionsAsync( + public Task NullCoalesceAssignment_02() + => TestMissingInRegularAndScriptWithAllOptionsAsync( """ class C { @@ -8238,12 +7635,10 @@ public static C M(C x) } } """, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33299")] - public async Task NullCoalesceAssignment_03() - { - await TestInRegularAndScriptAsync( + public Task NullCoalesceAssignment_03() + => TestInRegularAndScriptAsync( """ class C { @@ -8262,12 +7657,10 @@ public static void M(C x) } } """, optionName: nameof(PreferDiscard), parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33299")] - public async Task NullCoalesceAssignment_04() - { - await TestInRegularAndScriptAsync( + public Task NullCoalesceAssignment_04() + => TestInRegularAndScriptAsync( """ class C { @@ -8286,12 +7679,10 @@ public static C M(C x) } } """, optionName: nameof(PreferDiscard), parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33299")] - public async Task NullCoalesceAssignment_05() - { - await TestInRegularAndScriptAsync( + public Task NullCoalesceAssignment_05() + => TestInRegularAndScriptAsync( """ class C { @@ -8306,12 +7697,10 @@ public static C M(C x) => x ?? new C(); } """, optionName: nameof(PreferDiscard), parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8)); - } [Fact, WorkItem(32856, "https://github.com/dotnet/roslyn/issues/33312")] - public async Task RedundantAssignment_WithLeadingAndTrailingComment() - { - await TestInRegularAndScriptAsync( + public Task RedundantAssignment_WithLeadingAndTrailingComment() + => TestInRegularAndScriptAsync( """ class C { @@ -8344,12 +7733,10 @@ void M() } } """, options: PreferUnusedLocal); - } [Fact, WorkItem(32856, "https://github.com/dotnet/roslyn/issues/33312")] - public async Task MultipleRedundantAssignment_WithLeadingAndTrailingComment() - { - await TestInRegularAndScriptAsync( + public Task MultipleRedundantAssignment_WithLeadingAndTrailingComment() + => TestInRegularAndScriptAsync( """ class C { @@ -8387,12 +7774,10 @@ void M() } } """, options: PreferUnusedLocal); - } [Fact, WorkItem(32856, "https://github.com/dotnet/roslyn/issues/33312")] - public async Task MultipleRedundantAssignment_WithInnerComment() - { - await TestInRegularAndScriptAsync( + public Task MultipleRedundantAssignment_WithInnerComment() + => TestInRegularAndScriptAsync( """ class C { @@ -8421,12 +7806,10 @@ void M() } } """, options: PreferUnusedLocal); - } [Fact, WorkItem(32856, "https://github.com/dotnet/roslyn/issues/33312")] - public async Task DeclarationPatternInSwitchCase_WithTrivia_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task DeclarationPatternInSwitchCase_WithTrivia_PreferDiscard() + => TestInRegularAndScriptAsync( """ class C { @@ -8457,14 +7840,12 @@ void M(object p) } } """, options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8)); - } [Theory, WorkItem(32856, "https://github.com/dotnet/roslyn/issues/33312")] [CombinatorialData] - public async Task DeclarationPatternInSwitchCase_WithTrivia_PreferUnusedLocal( + public Task DeclarationPatternInSwitchCase_WithTrivia_PreferUnusedLocal( [CombinatorialValues(LanguageVersion.CSharp8, LanguageVersion.CSharp9)] LanguageVersion languageVersion) - { - await TestMissingInRegularAndScriptAsync( + => TestMissingInRegularAndScriptAsync( """ class C { @@ -8480,29 +7861,12 @@ void M(object p) } } """, PreferUnusedLocal, parseOptions: new CSharpParseOptions(languageVersion)); - } [Theory, WorkItem(32856, "https://github.com/dotnet/roslyn/issues/33312")] [CombinatorialData] public async Task DeclarationPatternInSwitchCase_WithTrivia_TypePattern( [CombinatorialValues(CodeFixTestBehaviors.None, CodeFixTestBehaviors.FixOne)] CodeFixTestBehaviors testBehaviors) { - var source = - """ - class C - { - void M(object p) - { - switch (p) - { - case /*Inline trivia*/ int {|IDE0059:x|}: - // Other trivia - {|IDE0059:x|} = 1; - break; - }; - } - } - """; var (fixedSource, iterations) = testBehaviors switch { CodeFixTestBehaviors.None => @@ -8541,7 +7905,21 @@ void M(object p) await new VerifyCS.Test { - TestCode = source, + TestCode = """ + class C + { + void M(object p) + { + switch (p) + { + case /*Inline trivia*/ int {|IDE0059:x|}: + // Other trivia + {|IDE0059:x|} = 1; + break; + }; + } + } + """, FixedState = { Sources = { fixedSource }, MarkupHandling = MarkupMode.Allow }, LanguageVersion = LanguageVersion.CSharp9, CodeFixTestBehaviors = testBehaviors, @@ -8557,9 +7935,8 @@ void M(object p) [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/33949")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UsedInArgumentAfterAnArgumentWithControlFlow(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UsedInArgumentAfterAnArgumentWithControlFlow(string optionName) + => TestMissingInRegularAndScriptAsync( """ class A { @@ -8575,14 +7952,12 @@ private static A M2(int? x, A a) } } """, optionName); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/33949")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task CompoundAssignmentWithControlFlowInValue(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task CompoundAssignmentWithControlFlowInValue(string optionName) + => TestMissingInRegularAndScriptAsync( """ class A { @@ -8595,14 +7970,12 @@ public static void M(int? x) private static int M2(int? x) => 0; } """, optionName); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/33843")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UsedValueWithUsingStatementAndLocalFunction(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UsedValueWithUsingStatementAndLocalFunction(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -8619,14 +7992,12 @@ public int M() } } """, optionName); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/33843")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UsedValueWithUsingStatementAndLambda(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UsedValueWithUsingStatementAndLambda(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -8643,14 +8014,12 @@ public int M() } } """, optionName); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/33843")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UsedValueWithUsingStatementAndLambda_02(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UsedValueWithUsingStatementAndLambda_02(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -8669,14 +8038,12 @@ public int M() } } """, optionName); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/33843")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UsedValueWithUsingStatementAndLambda_03(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UsedValueWithUsingStatementAndLambda_03(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -8695,14 +8062,12 @@ public int M() } } """, optionName); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/33937")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task AssignedInCatchUsedInFinally_ThrowInCatch(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task AssignedInCatchUsedInFinally_ThrowInCatch(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -8730,14 +8095,12 @@ public static void Test() } } """, optionName); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/33937")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task AssignedInCatchUsedInFinally_NoThrowInCatch(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task AssignedInCatchUsedInFinally_NoThrowInCatch(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -8761,12 +8124,10 @@ public static void Test() } } """, optionName); - } [Fact] - public async Task DoesNotUseLocalFunctionName_PreferUnused() - { - await TestInRegularAndScriptAsync( + public Task DoesNotUseLocalFunctionName_PreferUnused() + => TestInRegularAndScriptAsync( """ class C { @@ -8797,12 +8158,10 @@ void unused() { } int M2() => 0; } """, options: PreferUnusedLocal); - } [Fact] - public async Task CanUseLocalFunctionParameterName_PreferUnused() - { - await TestInRegularAndScriptAsync( + public Task CanUseLocalFunctionParameterName_PreferUnused() + => TestInRegularAndScriptAsync( """ class C { @@ -8833,12 +8192,10 @@ void MLocal(int unused) { } int M2() => 0; } """, options: PreferUnusedLocal); - } [Fact] - public async Task DoesNotUseLambdaFunctionParameterNameWithCSharpLessThan8_PreferUnused() - { - await TestInRegularAndScriptAsync( + public Task DoesNotUseLambdaFunctionParameterNameWithCSharpLessThan8_PreferUnused() + => TestInRegularAndScriptAsync( """ using System; class C @@ -8871,12 +8228,10 @@ int M() int M2() => 0; } """, options: PreferUnusedLocal, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp7_3)); - } [Fact] - public async Task CanUseLambdaFunctionParameterNameWithCSharp8_PreferUnused() - { - await TestInRegularAndScriptAsync( + public Task CanUseLambdaFunctionParameterNameWithCSharp8_PreferUnused() + => TestInRegularAndScriptAsync( """ using System; class C @@ -8909,12 +8264,10 @@ int M() int M2() => 0; } """, options: PreferUnusedLocal, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33464")] - public async Task UsingDeclaration() - { - await TestMissingInRegularAndScriptAsync( + public Task UsingDeclaration() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -8930,13 +8283,11 @@ void M() } } """, options: PreferDiscard, -parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); - } + parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33464")] - public async Task UsingDeclarationWithInitializer() - { - await TestMissingInRegularAndScriptAsync( + public Task UsingDeclarationWithInitializer() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -8953,13 +8304,11 @@ void M() } } """, options: PreferDiscard, -parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); - } + parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37709")] - public async Task RefParameter_WrittenBeforeThrow() - { - await TestDiagnosticMissingAsync( + public Task RefParameter_WrittenBeforeThrow() + => TestDiagnosticMissingAsync( """ using System; @@ -8975,12 +8324,10 @@ public void DoSomething(ref bool p) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37709")] - public async Task OutParameter_WrittenBeforeThrow() - { - await TestDiagnosticMissingAsync( + public Task OutParameter_WrittenBeforeThrow() + => TestDiagnosticMissingAsync( """ using System; @@ -9000,12 +8347,10 @@ public void DoSomething(out bool p, bool x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37871")] - public async Task RefParameter_RefAssignmentFollowedByAssignment() - { - await TestDiagnosticMissingAsync( + public Task RefParameter_RefAssignmentFollowedByAssignment() + => TestDiagnosticMissingAsync( """ using System; @@ -9021,12 +8366,10 @@ static void T1(ref int param) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37871")] - public async Task RefParameter_RefConditionalAssignment() - { - await TestDiagnosticMissingAsync( + public Task RefParameter_RefConditionalAssignment() + => TestDiagnosticMissingAsync( """ using System; @@ -9042,12 +8385,10 @@ static void T1(ref int param, bool flag) } } """); - } [Fact] - public async Task LocalFunction_OutParameter_UsedInCaller() - { - await TestDiagnosticMissingAsync( + public Task LocalFunction_OutParameter_UsedInCaller() + => TestDiagnosticMissingAsync( """ public class C { @@ -9066,12 +8407,10 @@ bool GetVal(out string val) } } """); - } [Fact] - public async Task TupleMember_UsedAfterContinueBranch() - { - await TestDiagnosticMissingAsync( + public Task TupleMember_UsedAfterContinueBranch() + => TestDiagnosticMissingAsync( """ using System; using System.Collections.Generic; @@ -9092,12 +8431,10 @@ void M(List<(int, int)> list) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38640")] - public async Task DeclarationPatternInSwitchExpressionArm_UsedLocal() - { - await TestDiagnosticMissingAsync( + public Task DeclarationPatternInSwitchExpressionArm_UsedLocal() + => TestDiagnosticMissingAsync( """ class C { @@ -9111,14 +8448,12 @@ string M(object obj) } } """, new TestParameters(options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8))); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/38640")] [CombinatorialData] - public async Task DeclarationPatternInSwitchExpressionArm_UnusedLocal_PreferUnusedLocal( + public Task DeclarationPatternInSwitchExpressionArm_UnusedLocal_PreferUnusedLocal( [CombinatorialValues(LanguageVersion.CSharp8, LanguageVersion.CSharp9)] LanguageVersion languageVersion) - { - await TestDiagnosticMissingAsync( + => TestDiagnosticMissingAsync( """ class C { @@ -9132,12 +8467,10 @@ string M(object obj) } } """, new TestParameters(options: PreferUnusedLocal, parseOptions: new CSharpParseOptions(languageVersion))); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40499")] - public async Task LocalUsedWithPropertySubPattern() - { - await TestDiagnosticMissingAsync( + public Task LocalUsedWithPropertySubPattern() + => TestDiagnosticMissingAsync( """ class C { @@ -9149,12 +8482,10 @@ void M() } } """, new TestParameters(options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8))); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40499")] - public async Task UnusedLocalDefinedInPropertySubPattern_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task UnusedLocalDefinedInPropertySubPattern_PreferDiscard() + => TestInRegularAndScriptAsync( """ class C { @@ -9175,13 +8506,12 @@ void M(C c) } } """, options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40499")] - public async Task UnusedLocalDefinedInPropertySubPattern_TypePattern() - { - var source = - """ + public Task UnusedLocalDefinedInPropertySubPattern_TypePattern() + => new VerifyCS.Test + { + TestCode = """ class C { public object P { get; } @@ -9191,9 +8521,8 @@ bool M(C c) return x; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { public object P { get; } @@ -9203,26 +8532,19 @@ bool M(C c) return x; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp9, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, UnusedValuePreference.DiscardVariable }, }, }.RunAsync(); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/40499")] [CombinatorialData] - public async Task UnusedVarLocalDefinedInPropertySubPattern_PreferDiscard( + public Task UnusedVarLocalDefinedInPropertySubPattern_PreferDiscard( [CombinatorialValues(LanguageVersion.CSharp8, LanguageVersion.CSharp9)] LanguageVersion languageVersion) - { - await TestInRegularAndScriptAsync( + => TestInRegularAndScriptAsync( """ class C { @@ -9243,14 +8565,12 @@ void M(C c) } } """, options: PreferDiscard, parseOptions: new CSharpParseOptions(languageVersion)); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/40499")] [CombinatorialData] - public async Task UnusedLocalDefinedInPropertySubPattern_PreferUnusedLocal( + public Task UnusedLocalDefinedInPropertySubPattern_PreferUnusedLocal( [CombinatorialValues(LanguageVersion.CSharp8, LanguageVersion.CSharp9)] LanguageVersion languageVersion) - { - await TestDiagnosticMissingAsync( + => TestDiagnosticMissingAsync( """ class C { @@ -9261,12 +8581,10 @@ void M(C c) } } """, new TestParameters(options: PreferUnusedLocal, parseOptions: new CSharpParseOptions(languageVersion))); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38640")] - public async Task DeclarationPatternInSwitchExpressionArm_UnusedLocal_PreferDiscard() - { - await TestInRegularAndScriptAsync( + public Task DeclarationPatternInSwitchExpressionArm_UnusedLocal_PreferDiscard() + => TestInRegularAndScriptAsync( """ class C { @@ -9293,13 +8611,12 @@ string M(object obj) } } """, options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38640")] - public async Task DeclarationPatternInSwitchExpressionArm_UnusedLocal_TypePattern() - { - var source = - """ + public Task DeclarationPatternInSwitchExpressionArm_UnusedLocal_TypePattern() + => new VerifyCS.Test + { + TestCode = """ class C { string M(object obj) @@ -9311,9 +8628,8 @@ string M(object obj) }; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { string M(object obj) @@ -9325,24 +8641,17 @@ string M(object obj) }; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp9, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, UnusedValuePreference.DiscardVariable }, }, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39344")] - public async Task AssignmentInTry_UsedInFinally_NoDiagnostic() - { - await TestDiagnosticMissingAsync( + public Task AssignmentInTry_UsedInFinally_NoDiagnostic() + => TestDiagnosticMissingAsync( """ using System; @@ -9368,12 +8677,10 @@ void M(int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39755")] - public async Task AssignmentInTry_UsedInFinally_NoDiagnostic_02() - { - await TestDiagnosticMissingAsync( + public Task AssignmentInTry_UsedInFinally_NoDiagnostic_02() + => TestDiagnosticMissingAsync( """ using System; @@ -9401,12 +8708,10 @@ void M() bool Some(IntPtr a) => true; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39755")] - public async Task AssignmentInTry_NotUsedInFinally_Diagnostic() - { - await TestInRegularAndScriptAsync( + public Task AssignmentInTry_NotUsedInFinally_Diagnostic() + => TestInRegularAndScriptAsync( """ using System; @@ -9448,12 +8753,10 @@ void M(int i) } } """, options: PreferDiscard); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38507")] - public async Task TestCodeFixTitleForBlockBodyRedundantCompoundAssignmentReturn() - { - var source = """ + public Task TestCodeFixTitleForBlockBodyRedundantCompoundAssignmentReturn() + => TestExactActionSetOfferedAsync(""" class C { C M(C x) @@ -9463,29 +8766,22 @@ C M(C x) C M2() => new C(); } - """; - - await TestExactActionSetOfferedAsync(source, [CodeFixesResources.Remove_redundant_assignment]); - } + """, [CodeFixesResources.Remove_redundant_assignment]); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38507")] - public async Task TestCodeFixTitleForExpressionBodyRedundantCompoundAssignmentReturn() - { - var source = """ + public Task TestCodeFixTitleForExpressionBodyRedundantCompoundAssignmentReturn() + => TestExactActionSetOfferedAsync(""" class C { C M(C x) => [|x ??= M2()|]; C M2() => new C(); } - """; - await TestExactActionSetOfferedAsync(source, [CodeFixesResources.Remove_redundant_assignment]); - } + """, [CodeFixesResources.Remove_redundant_assignment]); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38507")] - public async Task TestCodeFixTitleForPatternMatching() - { - var source = """ + public Task TestCodeFixTitleForPatternMatching() + => TestExactActionSetOfferedAsync(""" class C { void M() @@ -9498,15 +8794,12 @@ void M() C M2() => new C(); } - """; - - await TestExactActionSetOfferedAsync(source, [CodeFixesResources.Remove_redundant_assignment]); - } + """, [CodeFixesResources.Remove_redundant_assignment]); [Fact, WorkItem(38507, "https://github.com/dotnet/roslyn/issues/46251")] public async Task TestCodeFixForAllInDocumentForNestedDiagnostic() { - var source = """ + await TestInRegularAndScriptAsync(""" using System; namespace ConsoleApp { @@ -9528,8 +8821,7 @@ public static bool Bar() } } } - """; - var expected = """ + """, """ using System; namespace ConsoleApp { @@ -9551,14 +8843,12 @@ public static bool Bar() } } } - """; - await TestInRegularAndScriptAsync(source, expected, options: PreferDiscard).ConfigureAwait(false); + """, options: PreferDiscard).ConfigureAwait(false); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45768")] - public async Task UnusedVarPattern_PartOfCase() - { - await TestInRegularAndScriptAsync( + public Task UnusedVarPattern_PartOfCase() + => TestInRegularAndScriptAsync( """ static class Program { @@ -9589,12 +8879,10 @@ public static void Main() } } """, options: PreferDiscard); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45768")] - public async Task UnusedVarPattern_PartOfIs() - { - await TestInRegularAndScriptAsync( + public Task UnusedVarPattern_PartOfIs() + => TestInRegularAndScriptAsync( """ static class Program { @@ -9617,12 +8905,10 @@ public static void Main() } } """, options: PreferDiscard); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45768")] - public async Task UnusedVarPattern_TestTrivia() - { - await TestInRegularAndScriptAsync( + public Task UnusedVarPattern_TestTrivia() + => TestInRegularAndScriptAsync( """ static class Program { @@ -9645,15 +8931,13 @@ public static void Main() } } """, options: PreferDiscard); - } [WorkItem("https://github.com/dotnet/roslyn/issues/57650")] [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task UseInLambda_WithInvocationOutsideLocalScope(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task UseInLambda_WithInvocationOutsideLocalScope(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System; @@ -9670,13 +8954,12 @@ void M() } } """, optionName); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64291")] - public async Task TestImplicitObjectCreationInInitialization() - { - var source = - """ + public Task TestImplicitObjectCreationInInitialization() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -9684,9 +8967,8 @@ void M() C {|IDE0059:c|} = new(); } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M() @@ -9694,25 +8976,19 @@ void M() _ = new C(); } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, UnusedValuePreference.DiscardVariable }, }, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64291")] - public async Task TestImplicitObjectCreationInAssignment() - { - var source = - """ + public Task TestImplicitObjectCreationInAssignment() + => new VerifyCS.Test + { + TestCode = """ class C { void M(C c) @@ -9721,9 +8997,8 @@ void M(C c) {|IDE0059:c|} = new(); } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(C c) @@ -9732,24 +9007,19 @@ void M(C c) _ = new C(); } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, UnusedValuePreference.DiscardVariable }, }, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66573")] - public async Task TestPropertyPatternAssignment1() - { - var source = """ + public Task TestPropertyPatternAssignment1() + => new VerifyCS.Test + { + TestCode = """ class C { void M(object obj) @@ -9760,9 +9030,8 @@ void M(object obj) } } } - """; - - var fixedSource = """ + """, + FixedCode = """ class C { void M(object obj) @@ -9773,24 +9042,19 @@ void M(object obj) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, UnusedValuePreference.DiscardVariable }, }, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66573")] - public async Task TestPropertyPatternAssignment2() - { - var source = """ + public Task TestPropertyPatternAssignment2() + => new VerifyCS.Test + { + TestCode = """ class C { void M(object obj) @@ -9801,9 +9065,8 @@ void M(object obj) } } } - """; - - var fixedSource = """ + """, + FixedCode = """ class C { void M(object obj) @@ -9814,24 +9077,19 @@ void M(object obj) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, UnusedValuePreference.DiscardVariable }, }, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66573")] - public async Task TestPropertyPatternAssignment3() - { - var source = """ + public Task TestPropertyPatternAssignment3() + => new VerifyCS.Test + { + TestCode = """ class C { void M(object obj) @@ -9842,9 +9100,8 @@ void M(object obj) } } } - """; - - var fixedSource = """ + """, + FixedCode = """ class C { void M(object obj) @@ -9855,24 +9112,19 @@ void M(object obj) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, UnusedValuePreference.DiscardVariable }, }, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66573")] - public async Task TestPropertyPatternAssignment4() - { - var source = """ + public Task TestPropertyPatternAssignment4() + => new VerifyCS.Test + { + TestCode = """ class C { void M(object obj) @@ -9883,9 +9135,8 @@ void M(object obj) } } } - """; - - var fixedSource = """ + """, + FixedCode = """ class C { void M(object obj) @@ -9896,24 +9147,19 @@ void M(object obj) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, UnusedValuePreference.DiscardVariable }, }, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66573")] - public async Task TestListPatternAssignment1() - { - var source = """ + public Task TestListPatternAssignment1() + => new VerifyCS.Test + { + TestCode = """ class C { void M(string s) @@ -9924,9 +9170,8 @@ void M(string s) } } } - """; - - var fixedSource = """ + """, + FixedCode = """ class C { void M(string s) @@ -9937,12 +9182,7 @@ void M(string s) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, UnusedValuePreference.DiscardVariable }, @@ -9950,12 +9190,12 @@ void M(string s) LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66573")] - public async Task TestListPatternAssignment2() - { - var source = """ + public Task TestListPatternAssignment2() + => new VerifyCS.Test + { + TestCode = """ class C { void M(string[] ss) @@ -9966,9 +9206,8 @@ void M(string[] ss) } } } - """; - - var fixedSource = """ + """, + FixedCode = """ class C { void M(string[] ss) @@ -9979,12 +9218,7 @@ void M(string[] ss) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, UnusedValuePreference.DiscardVariable }, @@ -9992,12 +9226,12 @@ void M(string[] ss) LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66573")] - public async Task TestListPatternAssignment3() - { - var source = """ + public Task TestListPatternAssignment3() + => new VerifyCS.Test + { + TestCode = """ class C { void M(string[] ss) @@ -10008,9 +9242,8 @@ void M(string[] ss) } } } - """; - - var fixedSource = """ + """, + FixedCode = """ class C { void M(string[] ss) @@ -10021,12 +9254,7 @@ void M(string[] ss) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, UnusedValuePreference.DiscardVariable }, @@ -10034,22 +9262,18 @@ void M(string[] ss) LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69643")] - public async Task TestPrimaryConstructorParameterAssignment() - { - var source = """ + public Task TestPrimaryConstructorParameterAssignment() + => new VerifyCS.Test + { + TestCode = """ class C(string str) { public void Reset() { str = string.Empty; } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, Options = { { CSharpCodeStyleOptions.UnusedValueAssignment, UnusedValuePreference.DiscardVariable }, @@ -10057,12 +9281,10 @@ public void Reset() { LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72829")] - public async Task RemoveRedundantAssignment_PreservesUsingVar() - { - await TestInRegularAndScriptAsync( + public Task RemoveRedundantAssignment_PreservesUsingVar() + => TestInRegularAndScriptAsync( """ class C { @@ -10086,12 +9308,10 @@ void M() } } """); - } [Fact] - public async Task TestWriteIntoPropertyOfRefStructParameter() - { - await new VerifyCS.Test + public Task TestWriteIntoPropertyOfRefStructParameter() + => new VerifyCS.Test { TestCode = """ using System; @@ -10106,12 +9326,10 @@ private static void M(ref int destinationIndex, Span buffer) """, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestWriteIntoPropertyOfRefStructParameterThenWriteTheParameter() - { - await new VerifyCS.Test + public Task TestWriteIntoPropertyOfRefStructParameterThenWriteTheParameter() + => new VerifyCS.Test { TestCode = """ using System; @@ -10128,12 +9346,10 @@ private static void M(ref int destinationIndex, Span buffer) """, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestWriteIntoPropertyOfStructParameter() - { - await new VerifyCS.Test + public Task TestWriteIntoPropertyOfStructParameter() + => new VerifyCS.Test { TestCode = """ using System; @@ -10154,12 +9370,10 @@ private static void M(ref int destinationIndex, S buffer) """, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/77258")] - public async Task TestWriteIntoStructIndexer() - { - await new VerifyCS.Test + public Task TestWriteIntoStructIndexer() + => new VerifyCS.Test { TestCode = """ using System; @@ -10187,5 +9401,4 @@ public int this[int index] OutputKind = OutputKind.ConsoleApplication, } }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueExpressionStatementTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueExpressionStatementTests.cs index 1ab42e50193b3..667c6f72a60ce 100644 --- a/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueExpressionStatementTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueExpressionStatementTests.cs @@ -37,9 +37,8 @@ private protected override OptionsCollection PreferUnusedLocal new CodeStyleOption2(UnusedValuePreference.UnusedLocalVariable, NotificationOption2.Silent)); [Fact] - public async Task ExpressionStatement_Suppressed() - { - await TestMissingInRegularAndScriptAsync( + public Task ExpressionStatement_Suppressed() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -51,13 +50,10 @@ void M() int M2() => 0; } """, options: PreferNone); - } [Fact] - public async Task ExpressionStatement_PreferDiscard_CSharp6() - { - // Discard not supported in C# 6.0, so we fallback to unused local variable. - await TestInRegularAndScriptAsync( + public Task ExpressionStatement_PreferDiscard_CSharp6() + => TestInRegularAndScriptAsync( """ class C { @@ -80,15 +76,13 @@ void M() int M2() => 0; } """, options: PreferDiscard, -parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)); - } + parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)); [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task ExpressionStatement_VariableInitialization(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task ExpressionStatement_VariableInitialization(string optionName) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -100,14 +94,12 @@ void M() int M2() => 0; } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard), "_")] [InlineData(nameof(PreferUnusedLocal), "var unused")] - public async Task ExpressionStatement_NonConstantPrimitiveTypeValue(string optionName, string fix) - { - await TestInRegularAndScriptAsync( + public Task ExpressionStatement_NonConstantPrimitiveTypeValue(string optionName, string fix) + => TestInRegularAndScriptAsync( """ class C { @@ -130,14 +122,12 @@ void M() int M2() => 0; } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard), "_")] [InlineData(nameof(PreferUnusedLocal), "var unused")] - public async Task ExpressionStatement_UserDefinedType(string optionName, string fix) - { - await TestInRegularAndScriptAsync( + public Task ExpressionStatement_UserDefinedType(string optionName, string fix) + => TestInRegularAndScriptAsync( """ class C { @@ -160,14 +150,12 @@ void M() C M2() => new C(); } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task ExpressionStatement_ConstantValue(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task ExpressionStatement_ConstantValue(string optionName) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -177,14 +165,12 @@ void M() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task ExpressionStatement_SyntaxError(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task ExpressionStatement_SyntaxError(string optionName) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -196,14 +182,12 @@ void M() int M2() => 0; } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task ExpressionStatement_SemanticError(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task ExpressionStatement_SemanticError(string optionName) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -213,14 +197,12 @@ void M() } } """, optionName); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/33073")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task ExpressionStatement_SemanticError_02(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task ExpressionStatement_SemanticError_02(string optionName) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -232,14 +214,12 @@ void M() UndefinedType M2() => null; } """, optionName); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/33073")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task ExpressionStatement_SemanticError_03(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task ExpressionStatement_SemanticError_03(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System.Threading.Tasks; @@ -252,14 +232,12 @@ private async Task M() } } """, optionName); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/33073")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task ExpressionStatement_SemanticError_04(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task ExpressionStatement_SemanticError_04(string optionName) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -272,14 +250,12 @@ private async Task M() } } """, optionName); - } [Theory] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task ExpressionStatement_VoidReturningMethodCall(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task ExpressionStatement_VoidReturningMethodCall(string optionName) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -291,14 +267,12 @@ void M() void M2() { } } """, optionName); - } [Theory] [InlineData("=")] [InlineData("+=")] - public async Task ExpressionStatement_AssignmentExpression(string op) - { - await TestMissingInRegularAndScriptWithAllOptionsAsync( + public Task ExpressionStatement_AssignmentExpression(string op) + => TestMissingInRegularAndScriptWithAllOptionsAsync( $$""" class C { @@ -310,16 +284,14 @@ void M(int x) int M2() => 0; } """); - } [Theory] [InlineData("x++")] [InlineData("x--")] [InlineData("++x")] [InlineData("--x")] - public async Task ExpressionStatement_IncrementOrDecrement(string incrementOrDecrement) - { - await TestMissingInRegularAndScriptWithAllOptionsAsync( + public Task ExpressionStatement_IncrementOrDecrement(string incrementOrDecrement) + => TestMissingInRegularAndScriptWithAllOptionsAsync( $$""" class C { @@ -330,12 +302,10 @@ int M(int x) } } """); - } [Fact] - public async Task ExpressionStatement_UnusedLocal_NameAlreadyUsed() - { - await TestInRegularAndScriptAsync( + public Task ExpressionStatement_UnusedLocal_NameAlreadyUsed() + => TestInRegularAndScriptAsync( """ class C { @@ -360,12 +330,10 @@ void M() int M2() => 0; } """, options: PreferUnusedLocal); - } [Fact] - public async Task ExpressionStatement_UnusedLocal_NameAlreadyUsed_02() - { - await TestInRegularAndScriptAsync( + public Task ExpressionStatement_UnusedLocal_NameAlreadyUsed_02() + => TestInRegularAndScriptAsync( """ class C { @@ -390,12 +358,10 @@ void M() int M2() => 0; } """, options: PreferUnusedLocal); - } [Fact] - public async Task ExpressionStatement_UnusedLocal_NameAlreadyUsed_03() - { - await TestInRegularAndScriptAsync( + public Task ExpressionStatement_UnusedLocal_NameAlreadyUsed_03() + => TestInRegularAndScriptAsync( """ class C { @@ -426,12 +392,10 @@ void M(int p) int M2() => 0; } """, options: PreferUnusedLocal); - } [Fact] - public async Task ExpressionStatement_UnusedLocal_NameAlreadyUsed_04() - { - await TestInRegularAndScriptAsync( + public Task ExpressionStatement_UnusedLocal_NameAlreadyUsed_04() + => TestInRegularAndScriptAsync( """ class C { @@ -468,14 +432,12 @@ void M(int p) int M2() => 0; } """, options: PreferUnusedLocal); - } [Theory] [InlineData(nameof(PreferDiscard), "_", "_", "_")] [InlineData(nameof(PreferUnusedLocal), "var unused", "var unused", "var unused3")] - public async Task ExpressionStatement_FixAll(string optionName, string fix1, string fix2, string fix3) - { - await TestInRegularAndScriptAsync( + public Task ExpressionStatement_FixAll(string optionName, string fix1, string fix2, string fix3) + => TestInRegularAndScriptAsync( """ class C { @@ -514,12 +476,10 @@ void M(int unused1, int unused2) int M2() => 0; } """, optionName); - } [Fact] - public async Task ExpressionStatement_Trivia_PreferDiscard_01() - { - await TestInRegularAndScriptAsync( + public Task ExpressionStatement_Trivia_PreferDiscard_01() + => TestInRegularAndScriptAsync( """ class C { @@ -546,12 +506,10 @@ void M() int M2() => 0; } """, options: PreferDiscard); - } [Fact] - public async Task ExpressionStatement_Trivia_PreferDiscard_02() - { - await TestInRegularAndScriptAsync( + public Task ExpressionStatement_Trivia_PreferDiscard_02() + => TestInRegularAndScriptAsync( """ class C { @@ -577,12 +535,10 @@ void M() int M2() => 0; } """, options: PreferDiscard); - } [Fact] - public async Task ExpressionStatement_Trivia_PreferUnusedLocal_01() - { - await TestInRegularAndScriptAsync( + public Task ExpressionStatement_Trivia_PreferUnusedLocal_01() + => TestInRegularAndScriptAsync( """ class C { @@ -609,12 +565,10 @@ void M() int M2() => 0; } """, options: PreferUnusedLocal); - } [Fact] - public async Task ExpressionStatement_Trivia_PreferUnusedLocal_02() - { - await TestInRegularAndScriptAsync( + public Task ExpressionStatement_Trivia_PreferUnusedLocal_02() + => TestInRegularAndScriptAsync( """ class C { @@ -640,14 +594,12 @@ void M() int M2() => 0; } """, options: PreferUnusedLocal); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32942")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task ExpressionBodiedMember_01(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task ExpressionBodiedMember_01(string optionName) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -655,14 +607,12 @@ class C int M2() => 0; } """, optionName); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32942")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task ExpressionBodiedMember_02(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task ExpressionBodiedMember_02(string optionName) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -674,14 +624,12 @@ void M() int M2() => 0; } """, optionName); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32942")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task ExpressionBodiedMember_03(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task ExpressionBodiedMember_03(string optionName) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -696,14 +644,12 @@ void M() int M2() => 0; } """, optionName); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/43648")] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] - public async Task ExpressionStatement_Dynamic(string optionName) - { - await TestMissingInRegularAndScriptAsync( + public Task ExpressionStatement_Dynamic(string optionName) + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -719,5 +665,4 @@ void M() } } """, optionName); - } } diff --git a/src/Analyzers/CSharp/Tests/ReplaceDefaultLiteral/ReplaceDefaultLiteralTests.cs b/src/Analyzers/CSharp/Tests/ReplaceDefaultLiteral/ReplaceDefaultLiteralTests.cs index 78981d0d19d07..1792c4b0e0115 100644 --- a/src/Analyzers/CSharp/Tests/ReplaceDefaultLiteral/ReplaceDefaultLiteralTests.cs +++ b/src/Analyzers/CSharp/Tests/ReplaceDefaultLiteral/ReplaceDefaultLiteralTests.cs @@ -54,9 +54,8 @@ await TestMissingInRegularAndScriptAsync(initialMarkup, } [Fact] - public async Task TestCSharp7_1_InCaseSwitchLabel_Int() - { - await TestWithLanguageVersionsAsync( + public Task TestCSharp7_1_InCaseSwitchLabel_Int() + => TestWithLanguageVersionsAsync( """ class C { @@ -75,12 +74,10 @@ void M() } } """, s_csharp7_1above); - } [Fact] - public async Task TestCSharp7_1_InCaseSwitchLabel_Int_InParentheses() - { - await TestWithLanguageVersionsAsync( + public Task TestCSharp7_1_InCaseSwitchLabel_Int_InParentheses() + => TestWithLanguageVersionsAsync( """ class C { @@ -99,12 +96,10 @@ void M() } } """, s_csharp7_1above); - } [Fact] - public async Task TestCSharp7_1_InCaseSwitchLabel_Int_NotInsideCast() - { - await TestMissingWithLanguageVersionsAsync( + public Task TestCSharp7_1_InCaseSwitchLabel_Int_NotInsideCast() + => TestMissingWithLanguageVersionsAsync( """ class C { @@ -114,12 +109,10 @@ void M() } } """, s_csharp7_1above); - } [Fact] - public async Task TestCSharp7_1_InCaseSwitchLabel_Int_NotOnDefaultExpression() - { - await TestMissingWithLanguageVersionsAsync( + public Task TestCSharp7_1_InCaseSwitchLabel_Int_NotOnDefaultExpression() + => TestMissingWithLanguageVersionsAsync( """ class C { @@ -129,12 +122,10 @@ void M() } } """, s_csharp7_1above); - } [Fact] - public async Task TestCSharp7_1_InCaseSwitchLabel_Int_NotOnNumericLiteral() - { - await TestMissingWithLanguageVersionsAsync( + public Task TestCSharp7_1_InCaseSwitchLabel_Int_NotOnNumericLiteral() + => TestMissingWithLanguageVersionsAsync( """ class C { @@ -144,13 +135,10 @@ void M() } } """, 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( + public Task TestCSharp7_1_InCaseSwitchLabel_DateTime() + => TestWithLanguageVersionsAsync( """ class C { @@ -169,13 +157,10 @@ void M() } } """, 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( + public Task TestCSharp7_1_InCaseSwitchLabel_TupleType() + => TestWithLanguageVersionsAsync( """ class C { @@ -194,7 +179,6 @@ void M() } } """, s_csharp7_1above); - } [Theory] [InlineData("value")] @@ -202,9 +186,8 @@ void M() [InlineData("default")] [InlineData("() => { }")] [InlineData("")] - public async Task TestCSharp7_1_InCaseSwitchLabel_NotForInvalidType(string expression) - { - await TestMissingWithLanguageVersionsAsync( + public Task TestCSharp7_1_InCaseSwitchLabel_NotForInvalidType(string expression) + => TestMissingWithLanguageVersionsAsync( $$""" class C { @@ -214,12 +197,10 @@ void M() } } """, s_csharp7_1above); - } [Fact] - public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int() - { - await TestWithLanguageVersionsAsync( + public Task TestCSharp7_1_InCasePatternSwitchLabel_Int() + => TestWithLanguageVersionsAsync( """ class C { @@ -238,12 +219,10 @@ void M() } } """, s_csharp7_1above); - } [Fact] - public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int_InParentheses() - { - await TestWithLanguageVersionsAsync( + public Task TestCSharp7_1_InCasePatternSwitchLabel_Int_InParentheses() + => TestWithLanguageVersionsAsync( """ class C { @@ -262,12 +241,10 @@ void M() } } """, s_csharp7_1above); - } [Fact] - public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int_NotInsideCast() - { - await TestMissingWithLanguageVersionsAsync( + public Task TestCSharp7_1_InCasePatternSwitchLabel_Int_NotInsideCast() + => TestMissingWithLanguageVersionsAsync( """ class C { @@ -277,12 +254,10 @@ void M() } } """, s_csharp7_1above); - } [Fact] - public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int_NotOnDefaultExpression() - { - await TestMissingWithLanguageVersionsAsync( + public Task TestCSharp7_1_InCasePatternSwitchLabel_Int_NotOnDefaultExpression() + => TestMissingWithLanguageVersionsAsync( """ class C { @@ -292,12 +267,10 @@ void M() } } """, s_csharp7_1above); - } [Fact] - public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int_NotOnNumericLiteral() - { - await TestMissingWithLanguageVersionsAsync( + public Task TestCSharp7_1_InCasePatternSwitchLabel_Int_NotOnNumericLiteral() + => TestMissingWithLanguageVersionsAsync( """ class C { @@ -307,13 +280,10 @@ void M() } } """, 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( + public Task TestCSharp7_1_InCasePatternSwitchLabel_DateTime() + => TestWithLanguageVersionsAsync( """ class C { @@ -332,13 +302,10 @@ void M() } } """, 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( + public Task TestCSharp7_1_InCasePatternSwitchLabel_TupleType() + => TestWithLanguageVersionsAsync( """ class C { @@ -357,7 +324,6 @@ void M() } } """, s_csharp7_1above); - } [Theory] [InlineData("value")] @@ -365,9 +331,8 @@ void M() [InlineData("default")] [InlineData("() => { }")] [InlineData("")] - public async Task TestCSharp7_1_InCasePatternSwitchLabel_NotForInvalidType(string expression) - { - await TestMissingWithLanguageVersionsAsync( + public Task TestCSharp7_1_InCasePatternSwitchLabel_NotForInvalidType(string expression) + => TestMissingWithLanguageVersionsAsync( $$""" class C { @@ -377,12 +342,10 @@ void M() } } """, s_csharp7_1above); - } [Fact] - public async Task TestCSharp7_1_InIsPattern_Bool() - { - await TestWithLanguageVersionsAsync( + public Task TestCSharp7_1_InIsPattern_Bool() + => TestWithLanguageVersionsAsync( """ class C { @@ -401,12 +364,10 @@ void M() } } """, s_csharp7_1above); - } [Fact] - public async Task TestCSharp7_1_InIsPattern_Bool_InParentheses() - { - await TestWithLanguageVersionsAsync( + public Task TestCSharp7_1_InIsPattern_Bool_InParentheses() + => TestWithLanguageVersionsAsync( """ class C { @@ -425,12 +386,10 @@ void M() } } """, s_csharp7_1above); - } [Fact] - public async Task TestCSharp7_1_InIsPattern_Bool_NotInsideCast() - { - await TestMissingWithLanguageVersionsAsync( + public Task TestCSharp7_1_InIsPattern_Bool_NotInsideCast() + => TestMissingWithLanguageVersionsAsync( """ class C { @@ -440,12 +399,10 @@ void M() } } """, s_csharp7_1above); - } [Fact] - public async Task TestCSharp7_1_InIsPattern_Bool_NotOnDefaultExpression() - { - await TestMissingWithLanguageVersionsAsync( + public Task TestCSharp7_1_InIsPattern_Bool_NotOnDefaultExpression() + => TestMissingWithLanguageVersionsAsync( """ class C { @@ -455,12 +412,10 @@ void M() } } """, s_csharp7_1above); - } [Fact] - public async Task TestCSharp7_1_InIsPattern_Bool_NotOnFalseLiteral() - { - await TestMissingWithLanguageVersionsAsync( + public Task TestCSharp7_1_InIsPattern_Bool_NotOnFalseLiteral() + => TestMissingWithLanguageVersionsAsync( """ class C { @@ -470,7 +425,6 @@ void M() } } """, s_csharp7_1above); - } [Theory] [InlineData("int", "0")] @@ -487,9 +441,8 @@ void M() [InlineData("char", "'\\0'")] [InlineData("string", "null")] [InlineData("object", "null")] - public async Task TestCSharp7_1_InIsPattern_BuiltInType(string type, string expectedLiteral) - { - await TestWithLanguageVersionsAsync( + public Task TestCSharp7_1_InIsPattern_BuiltInType(string type, string expectedLiteral) + => TestWithLanguageVersionsAsync( $$""" class C { @@ -508,13 +461,10 @@ void M({{type}} value) } } """, 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( + public Task TestCSharp7_1_InIsPattern_DateTime() + => TestWithLanguageVersionsAsync( """ class C { @@ -533,13 +483,10 @@ void M() } } """, 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( + public Task TestCSharp7_1_InIsPattern_TupleType() + => TestWithLanguageVersionsAsync( """ class C { @@ -558,15 +505,13 @@ void M() } } """, 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( + public Task TestCSharp7_1_InIsPattern_CustomReferenceType(string typeDeclaration) + => TestWithLanguageVersionsAsync( $$""" class C { @@ -587,7 +532,6 @@ void M() } } """, s_csharp7_1above); - } [Theory] [InlineData("enum Enum { }")] @@ -596,9 +540,8 @@ void M() [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( + public Task TestCSharp7_1_InIsPattern_CustomEnum_WithoutSpecialMember(string enumDeclaration) + => TestWithLanguageVersionsAsync( $$""" class C { @@ -619,7 +562,6 @@ void M() } } """, s_csharp7_1above); - } [Theory] [InlineData("[System.Flags] enum Enum : int { None = 0 }")] @@ -633,9 +575,8 @@ void M() [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( + public Task TestCSharp7_1_InIsPattern_CustomEnum_WithSpecialMember(string enumDeclaration) + => TestWithLanguageVersionsAsync( $$""" class C { @@ -656,13 +597,10 @@ void M() } } """, 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( + public Task TestCSharp7_1_InIsPattern_CustomStruct() + => TestWithLanguageVersionsAsync( """ class C { @@ -683,12 +621,10 @@ void M() } } """, s_csharp7_1above); - } [Fact] - public async Task TestCSharp7_1_InIsPattern_AnonymousType() - { - await TestWithLanguageVersionsAsync( + public Task TestCSharp7_1_InIsPattern_AnonymousType() + => TestWithLanguageVersionsAsync( """ class C { @@ -707,15 +643,13 @@ void M() } } """, 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( + public Task TestCSharp7_1_InIsPattern_CustomReferenceTypeOfAnonymousType(string typeDeclaration) + => TestWithLanguageVersionsAsync( $$""" class C { @@ -738,12 +672,10 @@ void M() } } """, s_csharp7_1above); - } [Fact] - public async Task TestCSharp7_1_InIsPattern_NotForCustomStructOfAnonymousType() - { - await TestMissingWithLanguageVersionsAsync( + public Task TestCSharp7_1_InIsPattern_NotForCustomStructOfAnonymousType() + => TestMissingWithLanguageVersionsAsync( """ class C { @@ -755,13 +687,11 @@ void M() } } """, s_csharp7_1above); - } [Theory] [InlineData("System.Threading", "CancellationToken", "None")] - public async Task TestCSharp7_1_InIsPattern_SpecialTypeQualified1(string @namespace, string type, string member) - { - await TestWithLanguageVersionsAsync( + public Task TestCSharp7_1_InIsPattern_SpecialTypeQualified1(string @namespace, string type, string member) + => TestWithLanguageVersionsAsync( $$""" class C { @@ -780,14 +710,12 @@ void M() } } """, s_csharp7_1above); - } [Theory] [InlineData("System", "IntPtr", "Zero")] [InlineData("System", "UIntPtr", "Zero")] - public async Task TestCSharp7_1_InIsPattern_SpecialTypeQualified2(string @namespace, string type, string member) - { - await TestWithLanguageVersionsAsync( + public Task TestCSharp7_1_InIsPattern_SpecialTypeQualified2(string @namespace, string type, string member) + => TestWithLanguageVersionsAsync( $$""" class C { @@ -806,13 +734,11 @@ void M() } } """, [LanguageVersion.CSharp7_1, LanguageVersion.CSharp10, LanguageVersion.CSharp11, LanguageVersion.Latest]); - } [Theory] [InlineData("System.Threading", "CancellationToken", "None")] - public async Task TestCSharp7_1_InIsPattern_SpecialTypeUnqualifiedWithUsing1(string @namespace, string type, string member) - { - await TestWithLanguageVersionsAsync( + public Task TestCSharp7_1_InIsPattern_SpecialTypeUnqualifiedWithUsing1(string @namespace, string type, string member) + => TestWithLanguageVersionsAsync( $$""" using {{@namespace}}; class C @@ -833,14 +759,12 @@ void M() } } """, s_csharp7_1above); - } [Theory] [InlineData("System", "IntPtr", "Zero")] [InlineData("System", "UIntPtr", "Zero")] - public async Task TestCSharp7_1_InIsPattern_SpecialTypeUnqualifiedWithUsing2(string @namespace, string type, string member) - { - await TestWithLanguageVersionsAsync( + public Task TestCSharp7_1_InIsPattern_SpecialTypeUnqualifiedWithUsing2(string @namespace, string type, string member) + => TestWithLanguageVersionsAsync( $$""" using {{@namespace}}; class C @@ -861,15 +785,13 @@ void M() } } """, [LanguageVersion.CSharp7_1, LanguageVersion.CSharp10, LanguageVersion.CSharp11, LanguageVersion.Latest]); - } [Theory] [InlineData("CancellationToken")] [InlineData("IntPtr")] [InlineData("UIntPtr")] - public async Task TestCSharp7_1_InIsPattern_NotForSpecialTypeUnqualifiedWithoutUsing(string type) - { - await TestMissingWithLanguageVersionsAsync( + public Task TestCSharp7_1_InIsPattern_NotForSpecialTypeUnqualifiedWithoutUsing(string type) + => TestMissingWithLanguageVersionsAsync( $$""" class C { @@ -879,12 +801,10 @@ void M() } } """, s_csharp7_1above); - } [Fact] - public async Task TestCSharp7_1_InIsPattern_NotForInvalidType1() - { - await TestMissingWithLanguageVersionsAsync( + public Task TestCSharp7_1_InIsPattern_NotForInvalidType1() + => TestMissingWithLanguageVersionsAsync( """ class C { @@ -895,16 +815,14 @@ void M() } } """, s_csharp7_1above); - } [Theory] [InlineData("value")] [InlineData("null")] [InlineData("default")] [InlineData("")] - public async Task TestCSharp7_1_InIsPattern_NotForInvalidType2(string expression) - { - await TestMissingWithLanguageVersionsAsync( + public Task TestCSharp7_1_InIsPattern_NotForInvalidType2(string expression) + => TestMissingWithLanguageVersionsAsync( $$""" class C { @@ -915,7 +833,6 @@ void M() } } """, s_csharp7_1above); - } [Theory] [InlineData("value")] @@ -923,9 +840,8 @@ void M() [InlineData("default")] [InlineData("() => { }")] [InlineData("")] - public async Task TestCSharp7_1_InIsPattern_NotForInvalidType3(string expression) - { - await TestMissingWithLanguageVersionsAsync( + public Task TestCSharp7_1_InIsPattern_NotForInvalidType3(string expression) + => TestMissingWithLanguageVersionsAsync( $$""" class C { @@ -935,12 +851,10 @@ void M() } } """, s_csharp7_1above); - } [Fact] - public async Task TestCSharp7_1_InIsPattern_Lambda() - { - await TestMissingWithLanguageVersionsAsync( + public Task TestCSharp7_1_InIsPattern_Lambda() + => TestMissingWithLanguageVersionsAsync( """ class C { @@ -951,12 +865,10 @@ void M() } } """, [LanguageVersion.CSharp7_1]); - } [Fact] - public async Task TestCSharpLatest_InIsPattern_Lambda() - { - await TestWithLanguageVersionsAsync( + public Task TestCSharpLatest_InIsPattern_Lambda() + => TestWithLanguageVersionsAsync( """ class C { @@ -977,12 +889,10 @@ void M() } } """, [LanguageVersion.Latest]); - } [Fact] - public async Task TestCSharp7_1_InIsPattern_Bool_Trivia() - { - await TestWithLanguageVersionsAsync( + public Task TestCSharp7_1_InIsPattern_Bool_Trivia() + => TestWithLanguageVersionsAsync( """ class C { @@ -1003,12 +913,10 @@ void M() } } """, s_csharp7_1above); - } [Fact] - public async Task TestCSharp7_1_InIsPattern_DateTime_Trivia() - { - await TestWithLanguageVersionsAsync( + public Task TestCSharp7_1_InIsPattern_DateTime_Trivia() + => TestWithLanguageVersionsAsync( """ class C { @@ -1029,12 +937,10 @@ void M() } } """, s_csharp7_1above); - } [Fact] - public async Task TestCSharp7_1_NotInsideExpression() - { - await TestMissingWithLanguageVersionsAsync( + public Task TestCSharp7_1_NotInsideExpression() + => TestMissingWithLanguageVersionsAsync( """ class C { @@ -1044,12 +950,10 @@ void M() } } """, s_csharp7_1above); - } [Fact] - public async Task TestCSharp7_1_NotInsideExpression_InvalidType() - { - await TestMissingWithLanguageVersionsAsync( + public Task TestCSharp7_1_NotInsideExpression_InvalidType() + => TestMissingWithLanguageVersionsAsync( """ class C { @@ -1059,12 +963,10 @@ void M() } } """, s_csharp7_1above); - } [Fact] - public async Task TestCSharp7Lower_NotInsideExpression() - { - await TestMissingWithLanguageVersionsAsync( + public Task TestCSharp7Lower_NotInsideExpression() + => TestMissingWithLanguageVersionsAsync( """ class C { @@ -1074,5 +976,4 @@ void M() } } """, s_csharp7below); - } } diff --git a/src/Analyzers/CSharp/Tests/SimplifyBooleanExpression/SimplifyConditionalTests.cs b/src/Analyzers/CSharp/Tests/SimplifyBooleanExpression/SimplifyConditionalTests.cs index 1ab085cbe14d4..f8fd213cd2a69 100644 --- a/src/Analyzers/CSharp/Tests/SimplifyBooleanExpression/SimplifyConditionalTests.cs +++ b/src/Analyzers/CSharp/Tests/SimplifyBooleanExpression/SimplifyConditionalTests.cs @@ -23,9 +23,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider => (new CSharpSimplifyConditionalDiagnosticAnalyzer(), new SimplifyConditionalCodeFixProvider()); [Fact] - public async Task TestSimpleCase() - { - await TestInRegularAndScript1Async( + public Task TestSimpleCase() + => TestInRegularAndScript1Async( """ using System; @@ -54,12 +53,10 @@ bool M() private bool Y() => throw new NotImplementedException(); } """); - } [Fact] - public async Task TestSimpleNegatedCase() - { - await TestInRegularAndScript1Async( + public Task TestSimpleNegatedCase() + => TestInRegularAndScript1Async( """ using System; @@ -88,12 +85,10 @@ bool M() private bool Y() => throw new NotImplementedException(); } """); - } [Fact] - public async Task TestMustBeBool1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMustBeBool1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -108,12 +103,10 @@ string M() private bool Y() => throw new NotImplementedException(); } """); - } [Fact] - public async Task TestMustBeBool2() - { - await TestMissingAsync( + public Task TestMustBeBool2() + => TestMissingAsync( """ using System; @@ -128,12 +121,10 @@ string M() private bool Y() => throw new NotImplementedException(); } """); - } [Fact] - public async Task TestWithTrueTrue() - { - await TestInRegularAndScript1Async( + public Task TestWithTrueTrue() + => TestInRegularAndScript1Async( """ using System; @@ -162,12 +153,10 @@ bool M() private bool Y() => throw new NotImplementedException(); } """); - } [Fact] - public async Task TestWithFalseFalse() - { - await TestInRegularAndScript1Async( + public Task TestWithFalseFalse() + => TestInRegularAndScript1Async( """ using System; @@ -196,12 +185,10 @@ bool M() private bool Y() => throw new NotImplementedException(); } """); - } [Fact] - public async Task TestWhenTrueIsTrueAndWhenFalseIsUnknown() - { - await TestInRegularAndScript1Async( + public Task TestWhenTrueIsTrueAndWhenFalseIsUnknown() + => TestInRegularAndScript1Async( """ using System; @@ -230,12 +217,10 @@ string M() private bool Y() => throw new NotImplementedException(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71418")] - public async Task TestWhenTrueIsTrueAndWhenFalseIsUnknown_A() - { - await TestInRegularAndScript1Async( + public Task TestWhenTrueIsTrueAndWhenFalseIsUnknown_A() + => TestInRegularAndScript1Async( """ using System; @@ -266,12 +251,10 @@ string M() private bool Y() => throw new NotImplementedException(); } """); - } [Fact] - public async Task TestWhenTrueIsFalseAndWhenFalseIsUnknown() - { - await TestInRegularAndScript1Async( + public Task TestWhenTrueIsFalseAndWhenFalseIsUnknown() + => TestInRegularAndScript1Async( """ using System; @@ -300,12 +283,10 @@ string M() private bool Y() => throw new NotImplementedException(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71418")] - public async Task TestWhenTrueIsFalseAndWhenFalseIsUnknown_A() - { - await TestInRegularAndScript1Async( + public Task TestWhenTrueIsFalseAndWhenFalseIsUnknown_A() + => TestInRegularAndScript1Async( """ using System; @@ -336,12 +317,10 @@ string M() private bool Y() => throw new NotImplementedException(); } """); - } [Fact] - public async Task TestWhenTrueIsUnknownAndWhenFalseIsTrue() - { - await TestInRegularAndScript1Async( + public Task TestWhenTrueIsUnknownAndWhenFalseIsTrue() + => TestInRegularAndScript1Async( """ using System; @@ -370,12 +349,10 @@ string M() private bool Y() => throw new NotImplementedException(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71418")] - public async Task TestWhenTrueIsUnknownAndWhenFalseIsTrue_A() - { - await TestInRegularAndScript1Async( + public Task TestWhenTrueIsUnknownAndWhenFalseIsTrue_A() + => TestInRegularAndScript1Async( """ using System; @@ -406,12 +383,10 @@ string M() private bool Y() => throw new NotImplementedException(); } """); - } [Fact] - public async Task TestWhenTrueIsUnknownAndWhenFalseIsFalse() - { - await TestInRegularAndScript1Async( + public Task TestWhenTrueIsUnknownAndWhenFalseIsFalse() + => TestInRegularAndScript1Async( """ using System; @@ -440,12 +415,10 @@ string M() private bool Y() => throw new NotImplementedException(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71418")] - public async Task TestWhenTrueIsUnknownAndWhenFalseIsFalse_A() - { - await TestInRegularAndScript1Async( + public Task TestWhenTrueIsUnknownAndWhenFalseIsFalse_A() + => TestInRegularAndScript1Async( """ using System; @@ -476,12 +449,10 @@ string M() private bool Y() => throw new NotImplementedException(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/62827")] - public async Task TestFixAll() - { - await TestInRegularAndScriptAsync( + public Task TestFixAll() + => TestInRegularAndScriptAsync( """ using System; @@ -504,5 +475,4 @@ public bool M(object x, object y, Func isEqual) } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/SimplifyInterpolation/SimplifyInterpolationTests.cs b/src/Analyzers/CSharp/Tests/SimplifyInterpolation/SimplifyInterpolationTests.cs index 95a6e6ddfa1f5..5478527faf472 100644 --- a/src/Analyzers/CSharp/Tests/SimplifyInterpolation/SimplifyInterpolationTests.cs +++ b/src/Analyzers/CSharp/Tests/SimplifyInterpolation/SimplifyInterpolationTests.cs @@ -47,9 +47,8 @@ void M(string someValue) } [Fact] - public async Task ToStringWithNoParameter() - { - await TestInRegularAndScript1Async( + public Task ToStringWithNoParameter() + => TestInRegularAndScript1Async( """ class C { @@ -68,12 +67,10 @@ void M(string someValue) } } """); - } [Fact] - public async Task ToStringWithParameter() - { - await TestInRegularAndScript1Async( + public Task ToStringWithParameter() + => TestInRegularAndScript1Async( """ class C { @@ -92,12 +89,10 @@ void M(int someValue) } } """); - } [Fact] - public async Task ToStringWithEscapeSequences() - { - await TestInRegularAndScript1Async( + public Task ToStringWithEscapeSequences() + => TestInRegularAndScript1Async( """ class C { @@ -116,12 +111,10 @@ void M(System.DateTime someValue) } } """); - } [Fact] - public async Task ToStringWithVerbatimEscapeSequencesInsideVerbatimInterpolatedString() - { - await TestInRegularAndScript1Async( + public Task ToStringWithVerbatimEscapeSequencesInsideVerbatimInterpolatedString() + => TestInRegularAndScript1Async( """ class C { @@ -140,12 +133,10 @@ void M(System.DateTime someValue) } } """); - } [Fact] - public async Task ToStringWithVerbatimEscapeSequencesInsideNonVerbatimInterpolatedString() - { - await TestInRegularAndScript1Async( + public Task ToStringWithVerbatimEscapeSequencesInsideNonVerbatimInterpolatedString() + => TestInRegularAndScript1Async( """ class C { @@ -164,12 +155,10 @@ void M(System.DateTime someValue) } } """); - } [Fact] - public async Task ToStringWithNonVerbatimEscapeSequencesInsideVerbatimInterpolatedString() - { - await TestInRegularAndScript1Async( + public Task ToStringWithNonVerbatimEscapeSequencesInsideVerbatimInterpolatedString() + => TestInRegularAndScript1Async( """ class C { @@ -188,12 +177,10 @@ void M(System.DateTime someValue) } } """); - } [Fact] - public async Task ToStringWithStringConstantParameter() - { - await TestMissingInRegularAndScriptAsync( + public Task ToStringWithStringConstantParameter() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -204,12 +191,10 @@ void M(System.DateTime someValue) } } """); - } [Fact] - public async Task ToStringWithCharacterLiteralParameter() - { - await TestMissingInRegularAndScriptAsync( + public Task ToStringWithCharacterLiteralParameter() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -221,14 +206,10 @@ void M(C someValue) public string ToString(object obj) => null; } """); - } [Fact] - public async Task ToStringWithFormatProvider() - { - // (If someone is explicitly specifying culture, an implicit form should not be encouraged.) - - await TestMissingInRegularAndScriptAsync( + public Task ToStringWithFormatProvider() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -238,14 +219,10 @@ void M(System.DateTime someValue) } } """); - } [Fact] - public async Task ToStringWithInvariantCultureInsideFormattableStringInvariant() - { - // Invariance remains explicit, so this is okay. - - await TestInRegularAndScript1Async( + public Task ToStringWithInvariantCultureInsideFormattableStringInvariant() + => TestInRegularAndScript1Async( """ class C { @@ -264,12 +241,10 @@ void M(System.DateTime someValue) } } """); - } [Fact] - public async Task DateTimeFormatInfoInvariantInfoIsRecognized() - { - await TestInRegularAndScript1Async( + public Task DateTimeFormatInfoInvariantInfoIsRecognized() + => TestInRegularAndScript1Async( """ class C { @@ -288,12 +263,10 @@ void M(System.DateTime someValue) } } """); - } [Fact] - public async Task NumberFormatInfoInvariantInfoIsRecognized() - { - await TestInRegularAndScript1Async( + public Task NumberFormatInfoInvariantInfoIsRecognized() + => TestInRegularAndScript1Async( """ class C { @@ -312,12 +285,10 @@ void M(int someValue) } } """); - } [Fact] - public async Task ToStringWithInvariantCultureOutsideFormattableStringInvariant() - { - await TestMissingInRegularAndScriptAsync( + public Task ToStringWithInvariantCultureOutsideFormattableStringInvariant() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -327,12 +298,10 @@ void M(System.DateTime someValue) } } """); - } [Fact] - public async Task ToStringWithFormatAndInvariantCultureInsideFormattableStringInvariant() - { - await TestInRegularAndScript1Async( + public Task ToStringWithFormatAndInvariantCultureInsideFormattableStringInvariant() + => TestInRegularAndScript1Async( """ class C { @@ -351,12 +320,10 @@ void M(System.DateTime someValue) } } """); - } [Fact] - public async Task ToStringWithFormatAndInvariantCultureOutsideFormattableStringInvariant() - { - await TestMissingInRegularAndScriptAsync( + public Task ToStringWithFormatAndInvariantCultureOutsideFormattableStringInvariant() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -366,12 +333,10 @@ void M(System.DateTime someValue) } } """); - } [Fact] - public async Task PadLeftWithIntegerLiteral() - { - await TestInRegularAndScript1Async( + public Task PadLeftWithIntegerLiteral() + => TestInRegularAndScript1Async( """ class C { @@ -390,12 +355,10 @@ void M(string someValue) } } """); - } [Fact] - public async Task PadRightWithIntegerLiteral() - { - await TestInRegularAndScript1Async( + public Task PadRightWithIntegerLiteral() + => TestInRegularAndScript1Async( """ class C { @@ -414,12 +377,10 @@ void M(string someValue) } } """); - } [Fact] - public async Task PadLeftWithComplexConstantExpression() - { - await TestInRegularAndScript1Async( + public Task PadLeftWithComplexConstantExpression() + => TestInRegularAndScript1Async( """ class C { @@ -440,12 +401,10 @@ void M(string someValue) } } """); - } [Fact] - public async Task PadLeftWithSpaceChar() - { - await TestInRegularAndScript1Async( + public Task PadLeftWithSpaceChar() + => TestInRegularAndScript1Async( """ class C { @@ -464,12 +423,10 @@ void M(string someValue) } } """); - } [Fact] - public async Task PadRightWithSpaceChar() - { - await TestInRegularAndScript1Async( + public Task PadRightWithSpaceChar() + => TestInRegularAndScript1Async( """ class C { @@ -488,12 +445,10 @@ void M(string someValue) } } """); - } [Fact] - public async Task PadLeftWithNonSpaceChar() - { - await TestMissingInRegularAndScriptAsync( + public Task PadLeftWithNonSpaceChar() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -503,12 +458,10 @@ void M(string someValue) } } """); - } [Fact] - public async Task PadRightWithNonSpaceChar() - { - await TestMissingInRegularAndScriptAsync( + public Task PadRightWithNonSpaceChar() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -518,12 +471,10 @@ void M(string someValue) } } """); - } [Fact] - public async Task PadRightWithComplexConstantExpressionRequiringParentheses() - { - await TestInRegularAndScript1Async( + public Task PadRightWithComplexConstantExpressionRequiringParentheses() + => TestInRegularAndScript1Async( """ class C { @@ -544,12 +495,10 @@ void M(string someValue) } } """); - } [Fact] - public async Task ToStringWithNoParameterWhenFormattingComponentIsSpecified() - { - await TestMissingInRegularAndScriptAsync( + public Task ToStringWithNoParameterWhenFormattingComponentIsSpecified() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -559,12 +508,10 @@ void M(string someValue) } } """); - } [Fact] - public async Task ToStringWithStringLiteralParameterWhenFormattingComponentIsSpecified() - { - await TestMissingInRegularAndScriptAsync( + public Task ToStringWithStringLiteralParameterWhenFormattingComponentIsSpecified() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -574,12 +521,10 @@ void M(string someValue) } } """); - } [Fact] - public async Task ToStringWithNoParameterWhenAlignmentComponentIsSpecified() - { - await TestInRegularAndScript1Async( + public Task ToStringWithNoParameterWhenAlignmentComponentIsSpecified() + => TestInRegularAndScript1Async( """ class C { @@ -598,12 +543,10 @@ void M(string someValue) } } """); - } [Fact] - public async Task ToStringWithNoParameterWhenBothComponentsAreSpecified() - { - await TestMissingInRegularAndScriptAsync( + public Task ToStringWithNoParameterWhenBothComponentsAreSpecified() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -613,12 +556,10 @@ void M(string someValue) } } """); - } [Fact] - public async Task ToStringWithStringLiteralParameterWhenBothComponentsAreSpecified() - { - await TestMissingInRegularAndScriptAsync( + public Task ToStringWithStringLiteralParameterWhenBothComponentsAreSpecified() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -628,12 +569,10 @@ void M(string someValue) } } """); - } [Fact] - public async Task PadLeftWhenFormattingComponentIsSpecified() - { - await TestInRegularAndScript1Async( + public Task PadLeftWhenFormattingComponentIsSpecified() + => TestInRegularAndScript1Async( """ class C { @@ -652,12 +591,10 @@ void M(string someValue) } } """); - } [Fact] - public async Task PadRightWhenFormattingComponentIsSpecified() - { - await TestInRegularAndScript1Async( + public Task PadRightWhenFormattingComponentIsSpecified() + => TestInRegularAndScript1Async( """ class C { @@ -676,12 +613,10 @@ void M(string someValue) } } """); - } [Fact] - public async Task PadLeftWhenAlignmentComponentIsSpecified() - { - await TestMissingInRegularAndScriptAsync( + public Task PadLeftWhenAlignmentComponentIsSpecified() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -691,12 +626,10 @@ void M(string someValue) } } """); - } [Fact] - public async Task PadRightWhenAlignmentComponentIsSpecified() - { - await TestMissingInRegularAndScriptAsync( + public Task PadRightWhenAlignmentComponentIsSpecified() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -706,12 +639,10 @@ void M(string someValue) } } """); - } [Fact] - public async Task PadLeftWhenBothComponentsAreSpecified() - { - await TestMissingInRegularAndScriptAsync( + public Task PadLeftWhenBothComponentsAreSpecified() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -721,12 +652,10 @@ void M(string someValue) } } """); - } [Fact] - public async Task PadRightWhenBothComponentsAreSpecified() - { - await TestMissingInRegularAndScriptAsync( + public Task PadRightWhenBothComponentsAreSpecified() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -736,12 +665,10 @@ void M(string someValue) } } """); - } [Fact] - public async Task ToStringWithoutFormatThenPadLeft() - { - await TestInRegularAndScript1Async( + public Task ToStringWithoutFormatThenPadLeft() + => TestInRegularAndScript1Async( """ class C { @@ -759,12 +686,10 @@ void M(string someValue) } } """); - } [Fact] - public async Task PadLeftThenToStringWithoutFormat() - { - await TestInRegularAndScript1Async( + public Task PadLeftThenToStringWithoutFormat() + => TestInRegularAndScript1Async( """ class C { @@ -782,12 +707,10 @@ void M(string someValue) } } """); - } [Fact] - public async Task PadLeftThenToStringWithoutFormatWhenAlignmentComponentIsSpecified() - { - await TestInRegularAndScript1Async( + public Task PadLeftThenToStringWithoutFormatWhenAlignmentComponentIsSpecified() + => TestInRegularAndScript1Async( """ class C { @@ -805,12 +728,10 @@ void M(string someValue) } } """); - } [Fact] - public async Task PadLeftThenPadRight_WithoutAlignment() - { - await TestInRegularAndScript1Async( + public Task PadLeftThenPadRight_WithoutAlignment() + => TestInRegularAndScript1Async( """ class C { @@ -828,12 +749,10 @@ void M(string someValue) } } """); - } [Fact] - public async Task PadLeftThenPadRight_WithAlignment() - { - await TestMissingAsync( + public Task PadLeftThenPadRight_WithAlignment() + => TestMissingAsync( """ class C { @@ -843,12 +762,10 @@ void M(string someValue) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41381")] - public async Task MissingOnImplicitToStringReceiver() - { - await TestMissingAsync( + public Task MissingOnImplicitToStringReceiver() + => TestMissingAsync( """ class C { @@ -857,12 +774,10 @@ class C string GetViaInterpolation() => $"Hello {ToString[||]()}"; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41381")] - public async Task MissingOnImplicitToStringReceiverWithArg() - { - await TestMissingAsync( + public Task MissingOnImplicitToStringReceiverWithArg() + => TestMissingAsync( """ class C { @@ -871,12 +786,10 @@ class C string GetViaInterpolation() => $"Hello {ToString[||]("g")}"; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41381")] - public async Task MissingOnStaticToStringReceiver() - { - await TestMissingAsync( + public Task MissingOnStaticToStringReceiver() + => TestMissingAsync( """ class C { @@ -885,12 +798,10 @@ class C string GetViaInterpolation() => $"Hello {ToString[||]()}"; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41381")] - public async Task MissingOnStaticToStringReceiverWithArg() - { - await TestMissingAsync( + public Task MissingOnStaticToStringReceiverWithArg() + => TestMissingAsync( """ class C { @@ -899,12 +810,10 @@ class C string GetViaInterpolation() => $"Hello {ToString[||]("g")}"; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41381")] - public async Task MissingOnImplicitPadLeft() - { - await TestMissingAsync( + public Task MissingOnImplicitPadLeft() + => TestMissingAsync( """ class C { @@ -916,12 +825,10 @@ void M(string someValue) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41381")] - public async Task MissingOnStaticPadLeft() - { - await TestMissingAsync( + public Task MissingOnStaticPadLeft() + => TestMissingAsync( """ class C { @@ -933,12 +840,10 @@ void M(string someValue) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42247")] - public async Task OnConstantAlignment1() - { - await TestInRegularAndScript1Async( + public Task OnConstantAlignment1() + => TestInRegularAndScript1Async( """ using System; using System.Linq; @@ -976,12 +881,10 @@ public static void PrintRightAligned ( String[] strings ) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42247")] - public async Task MissingOnNonConstantAlignment() - { - await TestMissingAsync( + public Task MissingOnNonConstantAlignment() + => TestMissingAsync( """ using System; using System.Linq; @@ -1000,36 +903,30 @@ public static void PrintRightAligned ( String[] strings ) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42669")] - public async Task MissingOnBaseToString() - { - await TestMissingAsync( + public Task MissingOnBaseToString() + => TestMissingAsync( """ class C { public override string ToString() => $"Test: {base[||].ToString()}"; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42669")] - public async Task MissingOnBaseToStringEvenWhenNotOverridden() - { - await TestMissingAsync( + public Task MissingOnBaseToStringEvenWhenNotOverridden() + => TestMissingAsync( """ class C { string M() => $"Test: {base[||].ToString()}"; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42669")] - public async Task MissingOnBaseToStringWithArgument() - { - await TestMissingAsync( + public Task MissingOnBaseToStringWithArgument() + => TestMissingAsync( """ class Base { @@ -1041,12 +938,10 @@ class Derived : Base public override string ToString() => $"Test: {base[||].ToString("a")}"; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42669")] - public async Task PadLeftSimplificationIsStillOfferedOnBaseToString() - { - await TestInRegularAndScript1Async( + public Task PadLeftSimplificationIsStillOfferedOnBaseToString() + => TestInRegularAndScript1Async( """ class C { @@ -1059,12 +954,10 @@ class C public override string ToString() => $"Test: {base.ToString(),10}"; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42887")] - public async Task FormatComponentSimplificationIsNotOfferedOnNonIFormattableType() - { - await TestMissingInRegularAndScriptAsync( + public Task FormatComponentSimplificationIsNotOfferedOnNonIFormattableType() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1076,12 +969,10 @@ struct TypeNotImplementingIFormattable public string ToString(string format) => "A"; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42887")] - public async Task FormatComponentSimplificationIsOfferedOnIFormattableType() - { - await TestInRegularAndScript1Async( + public Task FormatComponentSimplificationIsOfferedOnIFormattableType() + => TestInRegularAndScript1Async( """ using System; @@ -1112,12 +1003,10 @@ struct TypeImplementingIFormattable : IFormattable string IFormattable.ToString(string format, IFormatProvider formatProvider) => "B"; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42887")] - public async Task ParameterlessToStringSimplificationIsStillOfferedOnNonIFormattableType() - { - await TestInRegularAndScript1Async( + public Task ParameterlessToStringSimplificationIsStillOfferedOnNonIFormattableType() + => TestInRegularAndScript1Async( """ class C { @@ -1140,12 +1029,10 @@ struct TypeNotImplementingIFormattable public string ToString(string format) => "A"; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42887")] - public async Task PadLeftSimplificationIsStillOfferedOnNonIFormattableType() - { - await TestInRegularAndScript1Async( + public Task PadLeftSimplificationIsStillOfferedOnNonIFormattableType() + => TestInRegularAndScript1Async( """ class C { @@ -1168,12 +1055,10 @@ struct TypeNotImplementingIFormattable public string ToString(string format) => "A"; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42936")] - public async Task ToStringSimplificationIsNotOfferedOnRefStruct() - { - await TestMissingInRegularAndScriptAsync( + public Task ToStringSimplificationIsNotOfferedOnRefStruct() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1185,12 +1070,10 @@ ref struct RefStruct public override string ToString() => "A"; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42936")] - public async Task PadLeftSimplificationIsStillOfferedOnRefStruct() - { - await TestInRegularAndScript1Async( + public Task PadLeftSimplificationIsStillOfferedOnRefStruct() + => TestInRegularAndScript1Async( """ class C { @@ -1213,12 +1096,10 @@ ref struct RefStruct public override string ToString() => "A"; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46011")] - public async Task ShadowedToString() - { - await TestMissingInRegularAndScriptAsync( + public Task ShadowedToString() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1226,12 +1107,10 @@ class C static string M(C c) => $"{c[||].ToString()}"; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46011")] - public async Task OverridenShadowedToString() - { - await TestMissingInRegularAndScriptAsync( + public Task OverridenShadowedToString() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1244,12 +1123,10 @@ class B : C static string M(C c) => $"{c[||].ToString()}"; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46011")] - public async Task DoubleOverridenToString() - { - await TestInRegularAndScript1Async( + public Task DoubleOverridenToString() + => TestInRegularAndScript1Async( """ class C { @@ -1282,12 +1159,10 @@ void M(B someValue) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49647")] - public async Task ConditionalExpressionMustRemainParenthesizedWhenUsingParameterlessToString() - { - await TestInRegularAndScript1Async( + public Task ConditionalExpressionMustRemainParenthesizedWhenUsingParameterlessToString() + => TestInRegularAndScript1Async( """ class C { @@ -1306,12 +1181,10 @@ void M(bool cond) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49647")] - public async Task ConditionalExpressionMustRemainParenthesizedWhenUsingParameterizedToString() - { - await TestInRegularAndScript1Async( + public Task ConditionalExpressionMustRemainParenthesizedWhenUsingParameterizedToString() + => TestInRegularAndScript1Async( """ class C { @@ -1330,12 +1203,10 @@ void M(bool cond) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49647")] - public async Task ConditionalExpressionMustRemainParenthesizedWhenUsingPadLeft() - { - await TestInRegularAndScript1Async( + public Task ConditionalExpressionMustRemainParenthesizedWhenUsingPadLeft() + => TestInRegularAndScript1Async( """ class C { @@ -1354,12 +1225,10 @@ void M(bool cond) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47956")] - public async Task TestNotPassedToFormattableString1() - { - await TestMissingAsync( + public Task TestNotPassedToFormattableString1() + => TestMissingAsync( """ class C { @@ -1372,5 +1241,4 @@ void M(FormattableString fs) } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/SimplifyLinqExpression/CSharpSimplifyLinqExpressionFixAllTests.cs b/src/Analyzers/CSharp/Tests/SimplifyLinqExpression/CSharpSimplifyLinqExpressionFixAllTests.cs index 5035452850dc1..01a68d6020991 100644 --- a/src/Analyzers/CSharp/Tests/SimplifyLinqExpression/CSharpSimplifyLinqExpressionFixAllTests.cs +++ b/src/Analyzers/CSharp/Tests/SimplifyLinqExpression/CSharpSimplifyLinqExpressionFixAllTests.cs @@ -19,9 +19,8 @@ namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.SimplifyLinqExpressi public partial class CSharpSimplifyLinqExpressionTests { [Fact] - public async Task FixAllInDocument() - { - await new VerifyCS.Test + public Task FixAllInDocument() + => new VerifyCS.Test { TestCode = """ using System; @@ -60,13 +59,10 @@ static void M() } """, }.RunAsync(); - } [Fact] - public async Task FixAllInDocumentExplicitCall() - { - - var testCode = """ + public Task FixAllInDocumentExplicitCall() + => VerifyCS.VerifyCodeFixAsync(""" using System; using System.Linq; using System.Collections.Generic; @@ -83,8 +79,7 @@ static void M() var test5 = [|Enumerable.Where(test, x => x.Equals("!")).FirstOrDefault()|]; } } - """; - var fixedCode = """ + """, """ using System; using System.Linq; using System.Collections.Generic; @@ -101,15 +96,11 @@ static void M() var test5 = Enumerable.FirstOrDefault(test, x => x.Equals("!")); } } - """; - await VerifyCS.VerifyCodeFixAsync(testCode, fixedCode); - } + """); [Fact] - public async Task NestedInDocument() - { - - await new VerifyCS.Test + public Task NestedInDocument() + => new VerifyCS.Test { TestCode = """ using System; @@ -150,5 +141,4 @@ static void M() } """, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/SimplifyLinqExpression/CSharpSimplifyLinqExpressionTests.cs b/src/Analyzers/CSharp/Tests/SimplifyLinqExpression/CSharpSimplifyLinqExpressionTests.cs index a5dbeba909967..2bd82856f50c9 100644 --- a/src/Analyzers/CSharp/Tests/SimplifyLinqExpression/CSharpSimplifyLinqExpressionTests.cs +++ b/src/Analyzers/CSharp/Tests/SimplifyLinqExpression/CSharpSimplifyLinqExpressionTests.cs @@ -20,7 +20,7 @@ namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.SimplifyLinqExpressi public sealed partial class CSharpSimplifyLinqExpressionTests { [Theory, CombinatorialData] - public static async Task TestAllowedMethodTypes( + public static Task TestAllowedMethodTypes( [CombinatorialValues( "x => x==1", "(x) => x==1", @@ -37,8 +37,7 @@ public static async Task TestAllowedMethodTypes( "FirstOrDefault", "LastOrDefault")] string methodName) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = $$""" using System; @@ -79,10 +78,9 @@ static IEnumerable Data() } """ }.RunAsync(); - } [Theory, CombinatorialData] - public static async Task TestWhereWithIndexMethodTypes( + public static Task TestWhereWithIndexMethodTypes( [CombinatorialValues( "(x, index) => x==index", "(x, index) => { return x==index; }")] @@ -97,8 +95,7 @@ public static async Task TestWhereWithIndexMethodTypes( "FirstOrDefault", "LastOrDefault")] string methodName) - { - var testCode = $$""" + => VerifyCS.VerifyAnalyzerAsync($$""" using System; using System.Linq; using System.Collections.Generic; @@ -116,12 +113,10 @@ static IEnumerable Data() var test = Data().Where({{lambda}}).{{methodName}}(); } } - """; - await VerifyCS.VerifyAnalyzerAsync(testCode); - } + """); [Theory, CombinatorialData] - public async Task TestQueryComprehensionSyntax( + public Task TestQueryComprehensionSyntax( [CombinatorialValues( "x => x==1", "x => { return x==1; }")] @@ -136,8 +131,7 @@ public async Task TestQueryComprehensionSyntax( "FirstOrDefault", "LastOrDefault")] string methodName) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = $$""" using System.Linq; @@ -162,7 +156,6 @@ static void M() } """ }.RunAsync(); - } [Theory] [InlineData("First")] @@ -173,9 +166,8 @@ static void M() [InlineData("SingleOrDefault")] [InlineData("FirstOrDefault")] [InlineData("LastOrDefault")] - public async Task TestMultiLineLambda(string methodName) - { - await new VerifyCS.Test + public Task TestMultiLineLambda(string methodName) + => new VerifyCS.Test { TestCode = $$""" using System; @@ -224,7 +216,6 @@ static IEnumerable Data() } """ }.RunAsync(); - } [Theory] [InlineData("First", "string")] @@ -235,9 +226,8 @@ static IEnumerable Data() [InlineData("SingleOrDefault", "string")] [InlineData("FirstOrDefault", "string")] [InlineData("LastOrDefault", "string")] - public async Task TestOutsideFunctionCallLambda(string methodName, string returnType) - { - await new VerifyCS.Test + public Task TestOutsideFunctionCallLambda(string methodName, string returnType) + => new VerifyCS.Test { TestCode = $$""" using System; @@ -272,7 +262,6 @@ public static bool FooTest(string input) } """ }.RunAsync(); - } [Theory] [InlineData("First")] @@ -283,9 +272,8 @@ public static bool FooTest(string input) [InlineData("SingleOrDefault")] [InlineData("FirstOrDefault")] [InlineData("LastOrDefault")] - public async Task TestQueryableIsNotConsidered(string methodName) - { - var source = $$""" + public Task TestQueryableIsNotConsidered(string methodName) + => VerifyCS.VerifyAnalyzerAsync($$""" using System; using System.Linq; using System.Collections.Generic; @@ -301,12 +289,10 @@ void M() } } } - """; - await VerifyCS.VerifyAnalyzerAsync(source); - } + """); [Theory, CombinatorialData] - public async Task TestNestedLambda( + public Task TestNestedLambda( [CombinatorialValues( "First", "Last", @@ -327,8 +313,8 @@ public async Task TestNestedLambda( "FirstOrDefault", "LastOrDefault")] string secondMethod) - { - var testCode = $$""" + => VerifyCS.VerifyCodeFixAsync( + $$""" using System; using System.Linq; using System.Collections.Generic; @@ -341,8 +327,8 @@ void M() var test5 = [|test.Where(a => [|a.Where(s => s.Equals("hello")).{{secondMethod}}()|].Equals("hello")).{{firstMethod}}()|]; } } - """; - var fixedCode = $$""" + """, + $$""" using System; using System.Linq; using System.Collections.Generic; @@ -355,11 +341,7 @@ void M() var test5 = test.{{firstMethod}}(a => a.{{secondMethod}}(s => s.Equals("hello")).Equals("hello")); } } - """; - await VerifyCS.VerifyCodeFixAsync( - testCode, - fixedCode); - } + """); [Theory] [InlineData("First")] @@ -370,9 +352,8 @@ await VerifyCS.VerifyCodeFixAsync( [InlineData("SingleOrDefault")] [InlineData("FirstOrDefault")] [InlineData("LastOrDefault")] - public async Task TestExplicitEnumerableCall(string methodName) - { - await new VerifyCS.Test + public Task TestExplicitEnumerableCall(string methodName) + => new VerifyCS.Test { TestCode = $$""" using System; @@ -405,12 +386,10 @@ static void Main() } """ }.RunAsync(); - } [Fact] - public async Task TestUserDefinedWhere() - { - var source = """ + public Task TestUserDefinedWhere() + => VerifyCS.VerifyAnalyzerAsync(""" using System; using System.Linq; using System.Collections.Generic; @@ -440,9 +419,7 @@ static void Main() } } } - """; - await VerifyCS.VerifyAnalyzerAsync(source); - } + """); [Theory] [InlineData("First")] @@ -453,9 +430,8 @@ static void Main() [InlineData("SingleOrDefault")] [InlineData("FirstOrDefault")] [InlineData("LastOrDefault")] - public async Task TestArgumentsInSecondCall(string methodName) - { - var source = $$""" + public Task TestArgumentsInSecondCall(string methodName) + => VerifyCS.VerifyAnalyzerAsync($$""" using System; using System.Linq; using System.Collections.Generic; @@ -468,14 +444,11 @@ static void M() var test2 = test1.Where(x => x == "!").{{methodName}}(x => x.Length == 1); } } - """; - await VerifyCS.VerifyAnalyzerAsync(source); - } + """); [Fact] - public async Task TestUnsupportedMethod() - { - var source = """ + public Task TestUnsupportedMethod() + => VerifyCS.VerifyAnalyzerAsync(""" using System; using System.Linq; using System.Collections; @@ -492,14 +465,11 @@ void M() int test2 = new Test().Where(x => x > 0).Count(); } } - """; - await VerifyCS.VerifyAnalyzerAsync(source); - } + """); [Fact] - public async Task TestExpressionTreeInput() - { - var source = """ + public Task TestExpressionTreeInput() + => VerifyCS.VerifyAnalyzerAsync(""" using System; using System.Linq; using System.Collections.Generic; @@ -529,14 +499,11 @@ void Main() string result = queryableData.Where(Expression.Lambda>(predicateBody, new ParameterExpression[] { pe })).First(); } } - """; - await VerifyCS.VerifyAnalyzerAsync(source); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52283")] - public static async Task TestTrivia1() - { - await new VerifyCS.Test + public static Task TestTrivia1() + => new VerifyCS.Test { TestCode = """ using System; @@ -567,12 +534,10 @@ static void Main(string[] args) } """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71293")] - public static async Task TestOffOfObjectCreation() - { - await new VerifyCS.Test + public static Task TestOffOfObjectCreation() + => new VerifyCS.Test { TestCode = """ using System; @@ -601,12 +566,10 @@ public void Test() } """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71293")] - public static async Task TestOffOfFieldReference() - { - await new VerifyCS.Test + public static Task TestOffOfFieldReference() + => new VerifyCS.Test { TestCode = """ using System; @@ -639,12 +602,10 @@ public void Test() } """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75845")] - public static async Task TestSelectSum() - { - await new VerifyCS.Test + public static Task TestSelectSum() + => new VerifyCS.Test { TestCode = """ using System; @@ -673,5 +634,4 @@ public void Test(int[] numbers) } """ }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/SimplifyLinqExpression/CSharpSimplifyLinqTypeCheckAndCastTests.cs b/src/Analyzers/CSharp/Tests/SimplifyLinqExpression/CSharpSimplifyLinqTypeCheckAndCastTests.cs index af8407685b83b..62286bddfa990 100644 --- a/src/Analyzers/CSharp/Tests/SimplifyLinqExpression/CSharpSimplifyLinqTypeCheckAndCastTests.cs +++ b/src/Analyzers/CSharp/Tests/SimplifyLinqExpression/CSharpSimplifyLinqTypeCheckAndCastTests.cs @@ -18,9 +18,8 @@ namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.SimplifyLinqExpressi public sealed partial class CSharpSimplifyLinqTypeCheckAndCast { [Fact] - public async Task TestCastMethod() - { - await new VerifyCS.Test + public Task TestCastMethod() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -45,12 +44,10 @@ void M(object[] objs) } """, }.RunAsync(); - } [Fact] - public async Task TestCastMethod_Incorrect1() - { - await new VerifyCS.Test + public Task TestCastMethod_Incorrect1() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -64,12 +61,10 @@ void M(object[] objs) } """, }.RunAsync(); - } [Fact] - public async Task TestCastMethod_Incorrect2() - { - await new VerifyCS.Test + public Task TestCastMethod_Incorrect2() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -83,12 +78,10 @@ void M(object[] objs) } """, }.RunAsync(); - } [Fact] - public async Task TestCastMethod_Incorrect3() - { - await new VerifyCS.Test + public Task TestCastMethod_Incorrect3() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -102,12 +95,10 @@ void M(object[] objs) } """, }.RunAsync(); - } [Fact] - public async Task TestCastMethod_Incorrect4() - { - await new VerifyCS.Test + public Task TestCastMethod_Incorrect4() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -121,12 +112,10 @@ void M(object[] objs) } """, }.RunAsync(); - } [Fact] - public async Task TestCastMethod_Incorrect5() - { - await new VerifyCS.Test + public Task TestCastMethod_Incorrect5() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -140,12 +129,10 @@ void M(object[] objs) } """, }.RunAsync(); - } [Fact] - public async Task TestCastMethod_Incorrect6() - { - await new VerifyCS.Test + public Task TestCastMethod_Incorrect6() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -159,12 +146,10 @@ void M(object[] objs) } """, }.RunAsync(); - } [Fact] - public async Task TestCastMethod_Incorrect7() - { - await new VerifyCS.Test + public Task TestCastMethod_Incorrect7() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -178,12 +163,10 @@ void M(object[] objs) } """, }.RunAsync(); - } [Fact] - public async Task TestSelectWithCast() - { - await new VerifyCS.Test + public Task TestSelectWithCast() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -208,12 +191,10 @@ void M(object[] objs) } """, }.RunAsync(); - } [Fact] - public async Task TestSelectWithCast_Incorrect1() - { - await new VerifyCS.Test + public Task TestSelectWithCast_Incorrect1() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -227,12 +208,10 @@ void M(object[] objs) } """, }.RunAsync(); - } [Fact] - public async Task TestSelectWithCast_Incorrect2() - { - await new VerifyCS.Test + public Task TestSelectWithCast_Incorrect2() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -246,12 +225,10 @@ void M(object[] objs) } """, }.RunAsync(); - } [Fact] - public async Task TestSelectWithCast_Incorrect3() - { - await new VerifyCS.Test + public Task TestSelectWithCast_Incorrect3() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -265,12 +242,10 @@ void M(object[] objs) } """, }.RunAsync(); - } [Fact] - public async Task TestSelectWithCast_Incorrect4() - { - await new VerifyCS.Test + public Task TestSelectWithCast_Incorrect4() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -284,12 +259,10 @@ void M(object[] objs) } """, }.RunAsync(); - } [Fact] - public async Task TestSelectWithCast_Incorrect5() - { - await new VerifyCS.Test + public Task TestSelectWithCast_Incorrect5() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -303,12 +276,10 @@ void M(object[] objs) } """, }.RunAsync(); - } [Fact] - public async Task TestSelectWithCast_Incorrect6() - { - await new VerifyCS.Test + public Task TestSelectWithCast_Incorrect6() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -322,12 +293,10 @@ void M(object[] objs) } """, }.RunAsync(); - } [Fact] - public async Task TestSelectWithCast_Incorrect7() - { - await new VerifyCS.Test + public Task TestSelectWithCast_Incorrect7() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -341,5 +310,4 @@ void M(object[] objs) } """, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/TransposeRecordKeyword/TransposeRecordKeywordTests.cs b/src/Analyzers/CSharp/Tests/TransposeRecordKeyword/TransposeRecordKeywordTests.cs index 82554c74f3893..53e008f75127f 100644 --- a/src/Analyzers/CSharp/Tests/TransposeRecordKeyword/TransposeRecordKeywordTests.cs +++ b/src/Analyzers/CSharp/Tests/TransposeRecordKeyword/TransposeRecordKeywordTests.cs @@ -18,42 +18,35 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.TransposeRecordKeyword; public sealed class TransposeRecordKeywordTests { [Fact] - public async Task TestStructRecord() - { - await new VerifyCS.Test + public Task TestStructRecord() + => new VerifyCS.Test { TestCode = @"struct {|CS9012:record|} C { }", FixedCode = @"record struct C { }", LanguageVersion = LanguageVersion.CSharp10 }.RunAsync(); - } [Fact] - public async Task TestClassRecord() - { - await new VerifyCS.Test + public Task TestClassRecord() + => new VerifyCS.Test { TestCode = @"class {|CS9012:record|} C { }", FixedCode = @"record class C { }", LanguageVersion = LanguageVersion.CSharp10 }.RunAsync(); - } [Fact] - public async Task TestWithModifiers() - { - await new VerifyCS.Test + public Task TestWithModifiers() + => new VerifyCS.Test { TestCode = @"public struct {|CS9012:record|} C { }", FixedCode = @"public record struct C { }", LanguageVersion = LanguageVersion.CSharp10 }.RunAsync(); - } [Fact] - public async Task TestWithComment() - { - await new VerifyCS.Test + public Task TestWithComment() + => new VerifyCS.Test { TestCode = """ // my struct @@ -65,12 +58,10 @@ public record struct C { } """, LanguageVersion = LanguageVersion.CSharp10 }.RunAsync(); - } [Fact] - public async Task TestWithDocComment() - { - await new VerifyCS.Test + public Task TestWithDocComment() + => new VerifyCS.Test { TestCode = """ /// @@ -82,12 +73,10 @@ public record struct C { } """, LanguageVersion = LanguageVersion.CSharp10 }.RunAsync(); - } [Fact] - public async Task TestWithAttributes1() - { - await new VerifyCS.Test + public Task TestWithAttributes1() + => new VerifyCS.Test { TestCode = """ [System.CLSCompliant(false)] @@ -99,12 +88,10 @@ record struct C { } """, LanguageVersion = LanguageVersion.CSharp10 }.RunAsync(); - } [Fact] - public async Task TestWithAttributes2() - { - await new VerifyCS.Test + public Task TestWithAttributes2() + => new VerifyCS.Test { TestCode = """ [System.CLSCompliant(false)] struct {|CS9012:record|} C { } @@ -114,12 +101,10 @@ public async Task TestWithAttributes2() """, LanguageVersion = LanguageVersion.CSharp10 }.RunAsync(); - } [Fact] - public async Task TestNestedRecord() - { - await new VerifyCS.Test + public Task TestNestedRecord() + => new VerifyCS.Test { TestCode = """ class {|CS9012:record|} C @@ -135,12 +120,10 @@ record struct D { } """, LanguageVersion = LanguageVersion.CSharp10 }.RunAsync(); - } [Fact] - public async Task TestNestedRecordWithComments() - { - await new VerifyCS.Test + public Task TestNestedRecordWithComments() + => new VerifyCS.Test { TestCode = """ // my class @@ -160,12 +143,10 @@ record struct D { } """, LanguageVersion = LanguageVersion.CSharp10 }.RunAsync(); - } [Fact] - public async Task TestTriviaBeforeAfter() - { - await new VerifyCS.Test + public Task TestTriviaBeforeAfter() + => new VerifyCS.Test { TestCode = """ /*1*/ @@ -181,5 +162,4 @@ class /*4*/ C { } """, LanguageVersion = LanguageVersion.CSharp10 }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UnsealClass/UnsealClassTests.cs b/src/Analyzers/CSharp/Tests/UnsealClass/UnsealClassTests.cs index dd46340be7b03..320586edc82ee 100644 --- a/src/Analyzers/CSharp/Tests/UnsealClass/UnsealClassTests.cs +++ b/src/Analyzers/CSharp/Tests/UnsealClass/UnsealClassTests.cs @@ -19,9 +19,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UnsealClass; public sealed class UnsealClassTests { [Fact] - public async Task RemovedFromSealedClass() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task RemovedFromSealedClass() + => VerifyCS.VerifyCodeFixAsync(""" sealed class C { } @@ -36,12 +35,10 @@ class D : C { } """); - } [Fact] - public async Task RemovedFromSealedClassWithOtherModifiersPreserved() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task RemovedFromSealedClassWithOtherModifiersPreserved() + => VerifyCS.VerifyCodeFixAsync(""" public sealed unsafe class C { } @@ -56,12 +53,10 @@ class D : C { } """); - } [Fact] - public async Task RemovedFromSealedClassWithConstructedGeneric() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task RemovedFromSealedClassWithConstructedGeneric() + => VerifyCS.VerifyCodeFixAsync(""" sealed class C { } @@ -76,7 +71,6 @@ class D : C { } """); - } [Fact] public async Task NotOfferedForNonSealedClass() @@ -162,9 +156,8 @@ class D : {|CS0509:System.ApplicationId|} } [Fact] - public async Task RemovedFromAllPartialClassDeclarationsInSameFile() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task RemovedFromAllPartialClassDeclarationsInSameFile() + => VerifyCS.VerifyCodeFixAsync(""" public sealed partial class C { } @@ -191,7 +184,6 @@ class D : C { } """); - } [Fact] public async Task RemovedFromAllPartialClassDeclarationsAcrossFiles() diff --git a/src/Analyzers/CSharp/Tests/UpdateLegacySuppressions/UpdateLegacySuppressionsTests.cs b/src/Analyzers/CSharp/Tests/UpdateLegacySuppressions/UpdateLegacySuppressionsTests.cs index e11fddc734cf9..a28518bbe3648 100644 --- a/src/Analyzers/CSharp/Tests/UpdateLegacySuppressions/UpdateLegacySuppressionsTests.cs +++ b/src/Analyzers/CSharp/Tests/UpdateLegacySuppressions/UpdateLegacySuppressionsTests.cs @@ -3,17 +3,20 @@ // See the LICENSE file in the project root for more information. using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CSharp.RemoveUnnecessarySuppressions; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions; using Microsoft.CodeAnalysis.Test.Utilities; +using Microsoft.CodeAnalysis.UpdateLegacySuppressions; using Roslyn.Test.Utilities; using Xunit; -using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< - Microsoft.CodeAnalysis.CSharp.RemoveUnnecessarySuppressions.CSharpRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer, - Microsoft.CodeAnalysis.UpdateLegacySuppressions.UpdateLegacySuppressionsCodeFixProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UpdateLegacySuppressions; +using VerifyCS = CSharpCodeFixVerifier< + CSharpRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer, + UpdateLegacySuppressionsCodeFixProvider>; + [Trait(Traits.Feature, Traits.Features.CodeActionsUpdateLegacySuppressions)] [WorkItem("https://github.com/dotnet/roslyn/issues/44362")] public sealed class UpdateLegacySuppressionsTests @@ -39,7 +42,10 @@ public void TestStandardProperty(AnalyzerProperty property) [Theory] public async Task LegacySuppressions(string scope, string target, string fixedTarget) { - var input = $$""" + var expectedDiagnostic = VerifyCS.Diagnostic(AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer.LegacyFormatTargetDescriptor) + .WithLocation(0) + .WithArguments(target); + await VerifyCS.VerifyCodeFixAsync($$""" [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "Id: Title", Scope = "{{scope}}", Target = {|#0:"{{target}}"|})] namespace N @@ -57,13 +63,7 @@ class D } } } - """; - - var expectedDiagnostic = VerifyCS.Diagnostic(AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer.LegacyFormatTargetDescriptor) - .WithLocation(0) - .WithArguments(target); - - var fixedCode = $$""" + """, expectedDiagnostic, $$""" [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "Id: Title", Scope = "{{scope}}", Target = "{{fixedTarget}}")] namespace N @@ -81,7 +81,6 @@ class D } } } - """; - await VerifyCS.VerifyCodeFixAsync(input, expectedDiagnostic, fixedCode); + """); } } diff --git a/src/Analyzers/CSharp/Tests/UpdateProjectToAllowUnsafe/UpdateProjectToAllowUnsafeTests.cs b/src/Analyzers/CSharp/Tests/UpdateProjectToAllowUnsafe/UpdateProjectToAllowUnsafeTests.cs index 7f914ac50ce8e..0441ca89e289c 100644 --- a/src/Analyzers/CSharp/Tests/UpdateProjectToAllowUnsafe/UpdateProjectToAllowUnsafeTests.cs +++ b/src/Analyzers/CSharp/Tests/UpdateProjectToAllowUnsafe/UpdateProjectToAllowUnsafeTests.cs @@ -45,20 +45,17 @@ private async Task TestAllowUnsafeEnabledIfDisabledAsync(string initialMarkup) } [Fact] - public async Task OnUnsafeClass() - { - await TestAllowUnsafeEnabledIfDisabledAsync( + public Task OnUnsafeClass() + => TestAllowUnsafeEnabledIfDisabledAsync( """ unsafe class [|C|] // The compiler reports this on the name, not the 'unsafe' keyword. { } """); - } [Fact] - public async Task OnUnsafeMethod() - { - await TestAllowUnsafeEnabledIfDisabledAsync( + public Task OnUnsafeMethod() + => TestAllowUnsafeEnabledIfDisabledAsync( """ class C { @@ -67,12 +64,10 @@ class C } } """); - } [Fact] - public async Task OnUnsafeLocalFunction() - { - await TestAllowUnsafeEnabledIfDisabledAsync( + public Task OnUnsafeLocalFunction() + => TestAllowUnsafeEnabledIfDisabledAsync( """ class C { @@ -84,12 +79,10 @@ void M() } } """); - } [Fact] - public async Task OnUnsafeBlock() - { - await TestAllowUnsafeEnabledIfDisabledAsync( + public Task OnUnsafeBlock() + => TestAllowUnsafeEnabledIfDisabledAsync( """ class C { @@ -101,12 +94,10 @@ void M() } } """); - } [Fact] - public async Task NotInsideUnsafeBlock() - { - await TestMissingAsync( + public Task NotInsideUnsafeBlock() + => TestMissingAsync( """ class C { @@ -119,5 +110,4 @@ void M() } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/UpgradeProject/UpgradeProjectTests.cs b/src/Analyzers/CSharp/Tests/UpgradeProject/UpgradeProjectTests.cs index 6fe7c81abff4b..cd8e2c63fe3ee 100644 --- a/src/Analyzers/CSharp/Tests/UpgradeProject/UpgradeProjectTests.cs +++ b/src/Analyzers/CSharp/Tests/UpgradeProject/UpgradeProjectTests.cs @@ -65,9 +65,8 @@ private async Task TestLanguageVersionNotUpgradedAsync(string initialMarkup, Par } [Fact] - public async Task UpgradeProjectFromCSharp7_2ToCSharp8() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectFromCSharp7_2ToCSharp8() + => TestLanguageVersionUpgradedAsync( """ class C { @@ -76,12 +75,10 @@ class C """, LanguageVersion.CSharp8, new CSharpParseOptions(LanguageVersion.CSharp7_2)); - } [Fact] - public async Task UpgradeProjectFromCSharp7ToCSharp8() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectFromCSharp7ToCSharp8() + => TestLanguageVersionUpgradedAsync( """ class C { @@ -90,12 +87,10 @@ class C """, LanguageVersion.CSharp8, new CSharpParseOptions(LanguageVersion.CSharp7)); - } [Fact] - public async Task UpgradeProjectFromCSharp6ToCSharp7() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectFromCSharp6ToCSharp7() + => TestLanguageVersionUpgradedAsync( """ class Program { @@ -107,12 +102,10 @@ void A() """, LanguageVersion.CSharp7, new CSharpParseOptions(LanguageVersion.CSharp6)); - } [Fact] - public async Task UpgradeProjectFromCSharp5ToCSharp6() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectFromCSharp5ToCSharp6() + => TestLanguageVersionUpgradedAsync( """ class Program { @@ -124,12 +117,10 @@ void A() """, LanguageVersion.CSharp6, new CSharpParseOptions(LanguageVersion.CSharp5)); - } [Fact] - public async Task UpgradeProjectFromCSharp4ToCSharp5() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectFromCSharp4ToCSharp5() + => TestLanguageVersionUpgradedAsync( """ class Program { @@ -141,12 +132,10 @@ void A() """, LanguageVersion.CSharp5, new CSharpParseOptions(LanguageVersion.CSharp4)); - } [Fact] - public async Task UpgradeProjectFromCSharp7ToLatest() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectFromCSharp7ToLatest() + => TestLanguageVersionUpgradedAsync( $$""" class Program { @@ -155,12 +144,10 @@ class Program """, LanguageVersion.Latest.MapSpecifiedToEffectiveVersion(), new CSharpParseOptions(LanguageVersion.CSharp7)); - } [Fact] - public async Task UpgradeProjectFromCSharp7To7_1_TriggeredByInferredTupleNames() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectFromCSharp7To7_1_TriggeredByInferredTupleNames() + => TestLanguageVersionUpgradedAsync( """ class Program { @@ -189,12 +176,10 @@ public ValueTuple(T1 item1, T2 item2) """, LanguageVersion.CSharp7_1, new CSharpParseOptions(LanguageVersion.CSharp7)); - } [Fact] - public async Task UpgradeProjectFromCSharp7_1ToLatest() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectFromCSharp7_1ToLatest() + => TestLanguageVersionUpgradedAsync( $$""" class Program { @@ -203,12 +188,10 @@ class Program """, LanguageVersion.Latest.MapSpecifiedToEffectiveVersion(), new CSharpParseOptions(LanguageVersion.CSharp7_1)); - } [Fact] - public async Task UpgradeProjectFromCSharp7ToCSharp7_1() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectFromCSharp7ToCSharp7_1() + => TestLanguageVersionUpgradedAsync( """ class Program { @@ -217,12 +200,10 @@ class Program """, LanguageVersion.CSharp7_1, new CSharpParseOptions(LanguageVersion.CSharp7)); - } [Fact] - public async Task UpgradeProjectWithNonTrailingNamedArgumentToCSharp7_2() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectWithNonTrailingNamedArgumentToCSharp7_2() + => TestLanguageVersionUpgradedAsync( """ class Program { @@ -234,12 +215,10 @@ void M() """, LanguageVersion.CSharp7_2, new CSharpParseOptions(LanguageVersion.CSharp7_1)); - } [Fact] - public async Task UpgradeProjectFromCSharp7ToCSharp7_1_B() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectFromCSharp7ToCSharp7_1_B() + => TestLanguageVersionUpgradedAsync( """ public class Base { } public class Derived : Base { } @@ -253,13 +232,11 @@ public static void M(T x) where T: Base """, LanguageVersion.CSharp7_1, new CSharpParseOptions(LanguageVersion.CSharp7)); - } #region C# 7.3 [Fact] - public async Task UpgradeProjectFromCSharp7_2ToLatest() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectFromCSharp7_2ToLatest() + => TestLanguageVersionUpgradedAsync( $$""" class Program { @@ -268,12 +245,10 @@ class Program """, LanguageVersion.Latest.MapSpecifiedToEffectiveVersion(), new CSharpParseOptions(LanguageVersion.CSharp7_2)); - } [Fact] - public async Task UpgradeProjectFromCSharp7_2To7_3_TriggeredByAttributeOnBackingField() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectFromCSharp7_2To7_3_TriggeredByAttributeOnBackingField() + => TestLanguageVersionUpgradedAsync( """ class A : System.Attribute { } class Program @@ -284,12 +259,10 @@ class Program """, LanguageVersion.CSharp7_3, new CSharpParseOptions(LanguageVersion.CSharp7_2)); - } [Fact] - public async Task UpgradeProjectFromCSharp7_2To7_3_EnumConstraint() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectFromCSharp7_2To7_3_EnumConstraint() + => TestLanguageVersionUpgradedAsync( """ public class X where T : [|System.Enum|] { @@ -297,12 +270,10 @@ public class X where T : [|System.Enum|] """, LanguageVersion.CSharp7_3, new CSharpParseOptions(LanguageVersion.CSharp7_2)); - } [Fact] - public async Task UpgradeProjectFromCSharp7_2To7_3_DelegateConstraint() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectFromCSharp7_2To7_3_DelegateConstraint() + => TestLanguageVersionUpgradedAsync( """ public class X where T : [|System.Delegate|] { @@ -310,12 +281,10 @@ public class X where T : [|System.Delegate|] """, LanguageVersion.CSharp7_3, new CSharpParseOptions(LanguageVersion.CSharp7_2)); - } [Fact] - public async Task UpgradeProjectFromCSharp7_2To7_3_MulticastDelegateConstraint() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectFromCSharp7_2To7_3_MulticastDelegateConstraint() + => TestLanguageVersionUpgradedAsync( """ public class X where T : [|System.MulticastDelegate|] { @@ -323,14 +292,12 @@ public class X where T : [|System.MulticastDelegate|] """, LanguageVersion.CSharp7_3, new CSharpParseOptions(LanguageVersion.CSharp7_2)); - } #endregion C# 7.3 #region C# 8.0 [Fact(Skip = "https://github.com/dotnet/roslyn/pull/29820")] - public async Task UpgradeProjectFromCSharp7_3ToLatest() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectFromCSharp7_3ToLatest() + => TestLanguageVersionUpgradedAsync( $$""" class Program { @@ -339,12 +306,10 @@ class Program """, LanguageVersion.Latest.MapSpecifiedToEffectiveVersion(), new CSharpParseOptions(LanguageVersion.CSharp7_3)); - } [Fact(Skip = "https://github.com/dotnet/roslyn/pull/29820")] - public async Task UpgradeProjectFromCSharp7_3To8_0() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectFromCSharp7_3To8_0() + => TestLanguageVersionUpgradedAsync( $$""" class Program { @@ -353,12 +318,10 @@ class Program """, LanguageVersion.Latest.MapSpecifiedToEffectiveVersion(), new CSharpParseOptions(LanguageVersion.CSharp7_3)); - } [Fact] - public async Task UpgradeProjectForVerbatimInterpolatedString() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectForVerbatimInterpolatedString() + => TestLanguageVersionUpgradedAsync( """ class Program { @@ -370,13 +333,11 @@ void A() """, expected: LanguageVersion.CSharp8, new CSharpParseOptions(LanguageVersion.CSharp7_3)); - } #endregion [Fact] - public async Task UpgradeAllProjectsToCSharp7() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeAllProjectsToCSharp7() + => TestLanguageVersionUpgradedAsync( """ @@ -401,12 +362,10 @@ void A() LanguageVersion.CSharp7, parseOptions: null, index: 1); - } [Fact] - public async Task UpgradeAllProjectsToCSharp8() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeAllProjectsToCSharp8() + => TestLanguageVersionUpgradedAsync( """ @@ -428,12 +387,10 @@ class C LanguageVersion.CSharp8, parseOptions: null, index: 1); - } [Fact] - public async Task UpgradeAllProjectsToCSharp8_NullableReferenceType() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeAllProjectsToCSharp8_NullableReferenceType() + => TestLanguageVersionUpgradedAsync( """ @@ -459,12 +416,10 @@ void A(string[|?|] s) LanguageVersion.CSharp8, parseOptions: null, index: 1); - } [Fact] - public async Task UpgradeAllProjectsToCSharp9() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeAllProjectsToCSharp9() + => TestLanguageVersionUpgradedAsync( """ @@ -485,12 +440,10 @@ await TestLanguageVersionUpgradedAsync( LanguageVersion.CSharp9, parseOptions: null, index: 1); - } [Fact] - public async Task ListAllSuggestions() - { - await TestExactActionSetOfferedAsync( + public Task ListAllSuggestions() + => TestExactActionSetOfferedAsync( """ @@ -515,12 +468,10 @@ void A() string.Format(CSharpCodeFixesResources.Upgrade_this_project_to_csharp_language_version_0, "7.0"), string.Format(CSharpCodeFixesResources.Upgrade_all_csharp_projects_to_language_version_0, "7.0") ]); - } [Fact] - public async Task ListAllSuggestions_CSharp8() - { - await TestExactActionSetOfferedAsync( + public Task ListAllSuggestions_CSharp8() + => TestExactActionSetOfferedAsync( """ @@ -546,12 +497,10 @@ void A() string.Format(CSharpCodeFixesResources.Upgrade_all_csharp_projects_to_language_version_0, "8.0") ] ); - } [Fact] - public async Task FixAllProjectsNotOffered() - { - await TestExactActionSetOfferedAsync( + public Task FixAllProjectsNotOffered() + => TestExactActionSetOfferedAsync( """ @@ -573,12 +522,10 @@ void A() [ string.Format(CSharpCodeFixesResources.Upgrade_this_project_to_csharp_language_version_0, "7.0") ]); - } [Fact] - public async Task OnlyOfferFixAllProjectsFromCSharp6ToCSharp7WhenApplicable() - { - await TestExactActionSetOfferedAsync( + public Task OnlyOfferFixAllProjectsFromCSharp6ToCSharp7WhenApplicable() + => TestExactActionSetOfferedAsync( """ @@ -602,7 +549,6 @@ void A() [ string.Format(CSharpCodeFixesResources.Upgrade_this_project_to_csharp_language_version_0, "7.0") ]); - } [Fact] public async Task OnlyOfferFixAllProjectsFromCSharp6ToDefaultWhenApplicable() @@ -636,9 +582,8 @@ void A() } [Fact] - public async Task OnlyOfferFixAllProjectsToCSharp8WhenApplicable() - { - await TestExactActionSetOfferedAsync( + public Task OnlyOfferFixAllProjectsToCSharp8WhenApplicable() + => TestExactActionSetOfferedAsync( """ @@ -656,7 +601,6 @@ class C """, [string.Format(CSharpCodeFixesResources.Upgrade_this_project_to_csharp_language_version_0, "8.0")]); - } [Fact] public async Task OnlyOfferFixAllProjectsToDefaultWhenApplicable() @@ -689,9 +633,8 @@ void A() } [Fact] - public async Task UpgradeProjectWithUnconstrainedNullableTypeParameter() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectWithUnconstrainedNullableTypeParameter() + => TestLanguageVersionUpgradedAsync( """ #nullable enable class C @@ -701,12 +644,10 @@ static void F([|T?|] t) { } """, LanguageVersion.CSharp9, new CSharpParseOptions(LanguageVersion.CSharp8)); - } [Fact] - public async Task UpgradeProjectWithUnmanagedConstraintTo7_3_Type() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectWithUnmanagedConstraintTo7_3_Type() + => TestLanguageVersionUpgradedAsync( """ class Test where T : [|unmanaged|] { @@ -714,12 +655,10 @@ class Test where T : [|unmanaged|] """, LanguageVersion.CSharp7_3, new CSharpParseOptions(LanguageVersion.CSharp7)); - } [Fact] - public async Task UpgradeProjectWithUnmanagedConstraintTo7_3_Type_AlreadyDefined() - { - await TestExactActionSetOfferedAsync( + public Task UpgradeProjectWithUnmanagedConstraintTo7_3_Type_AlreadyDefined() + => TestExactActionSetOfferedAsync( """ @@ -733,12 +672,10 @@ class Test<T> where T : [|unmanaged|] """, expectedActionSet: []); - } [Fact] - public async Task UpgradeProjectWithUnmanagedConstraintTo7_3_Method() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectWithUnmanagedConstraintTo7_3_Method() + => TestLanguageVersionUpgradedAsync( """ class Test { @@ -747,12 +684,10 @@ public void M() where T : [|unmanaged|] { } """, LanguageVersion.CSharp7_3, new CSharpParseOptions(LanguageVersion.CSharp7)); - } [Fact] - public async Task UpgradeProjectWithUnmanagedConstraintTo7_3_Method_AlreadyDefined() - { - await TestExactActionSetOfferedAsync( + public Task UpgradeProjectWithUnmanagedConstraintTo7_3_Method_AlreadyDefined() + => TestExactActionSetOfferedAsync( """ @@ -767,21 +702,17 @@ class Test """, expectedActionSet: []); - } [Fact] - public async Task UpgradeProjectWithUnmanagedConstraintTo7_3_Delegate() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectWithUnmanagedConstraintTo7_3_Delegate() + => TestLanguageVersionUpgradedAsync( @"delegate void D() where T : [|unmanaged|];", LanguageVersion.CSharp7_3, new CSharpParseOptions(LanguageVersion.CSharp7)); - } [Fact] - public async Task UpgradeProjectWithUnmanagedConstraintTo7_3_Delegate_AlreadyDefined() - { - await TestExactActionSetOfferedAsync( + public Task UpgradeProjectWithUnmanagedConstraintTo7_3_Delegate_AlreadyDefined() + => TestExactActionSetOfferedAsync( """ @@ -793,12 +724,10 @@ interface unmanaged { } """, expectedActionSet: []); - } [Fact] - public async Task UpgradeProjectWithUnmanagedConstraintTo7_3_LocalFunction() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectWithUnmanagedConstraintTo7_3_LocalFunction() + => TestLanguageVersionUpgradedAsync( """ class Test { @@ -810,12 +739,10 @@ void M() where T : [|unmanaged|] { } """, LanguageVersion.CSharp7_3, new CSharpParseOptions(LanguageVersion.CSharp7)); - } [Fact] - public async Task UpgradeProjectWithUnmanagedConstraintTo7_3_LocalFunction_AlreadyDefined() - { - await TestExactActionSetOfferedAsync( + public Task UpgradeProjectWithUnmanagedConstraintTo7_3_LocalFunction_AlreadyDefined() + => TestExactActionSetOfferedAsync( """ @@ -833,12 +760,10 @@ public void N() """, expectedActionSet: []); - } [Fact] - public async Task UpgradeProjectForDefaultInterfaceImplementation_CS8703() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectForDefaultInterfaceImplementation_CS8703() + => TestLanguageVersionUpgradedAsync( """ public interface I1 { @@ -847,12 +772,10 @@ public interface I1 """, expected: LanguageVersion.CSharp8, new CSharpParseOptions(LanguageVersion.CSharp7_3)); - } [Fact] - public async Task UpgradeProjectForDefaultInterfaceImplementation_CS8706() - { - await TestLanguageVersionNotUpgradedAsync( + public Task UpgradeProjectForDefaultInterfaceImplementation_CS8706() + => TestLanguageVersionNotUpgradedAsync( """ @@ -875,12 +798,10 @@ void M1() """, new CSharpParseOptions(LanguageVersion.CSharp7_3)); - } [Fact] - public async Task UpgradeProjectWithOpenTypeMatchingConstantPattern_01() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectWithOpenTypeMatchingConstantPattern_01() + => TestLanguageVersionUpgradedAsync( """ class Test { @@ -889,12 +810,10 @@ class Test """, LanguageVersion.CSharp8, new CSharpParseOptions(LanguageVersion.CSharp7_3)); - } [Fact] - public async Task UpgradeProjectWithOpenTypeMatchingConstantPattern_02() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectWithOpenTypeMatchingConstantPattern_02() + => TestLanguageVersionUpgradedAsync( """ class Test { @@ -903,12 +822,10 @@ class Test """, LanguageVersion.CSharp8, new CSharpParseOptions(LanguageVersion.CSharp7_3)); - } [Fact] - public async Task UpgradeProjectWithOpenTypeMatchingConstantPattern_03() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectWithOpenTypeMatchingConstantPattern_03() + => TestLanguageVersionUpgradedAsync( """ class Test { @@ -917,12 +834,10 @@ class Test """, LanguageVersion.CSharp8, new CSharpParseOptions(LanguageVersion.CSharp7_3)); - } [Fact] - public async Task UpgradeProjectWithNotNullConstraintTo8_0_Type() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectWithNotNullConstraintTo8_0_Type() + => TestLanguageVersionUpgradedAsync( """ class Test where T : [|notnull|] { @@ -930,12 +845,10 @@ class Test where T : [|notnull|] """, LanguageVersion.CSharp8, new CSharpParseOptions(LanguageVersion.CSharp7_3)); - } [Fact] - public async Task UpgradeProjectWithNotNullConstraintTo8_0_Type_AlreadyDefined() - { - await TestExactActionSetOfferedAsync( + public Task UpgradeProjectWithNotNullConstraintTo8_0_Type_AlreadyDefined() + => TestExactActionSetOfferedAsync( """ @@ -949,12 +862,10 @@ class Test<T> where T : [|notnull|] """, expectedActionSet: []); - } [Fact] - public async Task UpgradeProjectWithNotNullConstraintTo8_0_Method() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectWithNotNullConstraintTo8_0_Method() + => TestLanguageVersionUpgradedAsync( """ class Test { @@ -963,12 +874,10 @@ public void M() where T : [|notnull|] { } """, LanguageVersion.CSharp8, new CSharpParseOptions(LanguageVersion.CSharp7_3)); - } [Fact] - public async Task UpgradeProjectWithNotNullConstraintTo8_0_Method_AlreadyDefined() - { - await TestExactActionSetOfferedAsync( + public Task UpgradeProjectWithNotNullConstraintTo8_0_Method_AlreadyDefined() + => TestExactActionSetOfferedAsync( """ @@ -983,21 +892,17 @@ class Test """, expectedActionSet: []); - } [Fact] - public async Task UpgradeProjectWithNotNullConstraintTo8_0_Delegate() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectWithNotNullConstraintTo8_0_Delegate() + => TestLanguageVersionUpgradedAsync( @"delegate void D() where T : [|notnull|];", LanguageVersion.CSharp8, new CSharpParseOptions(LanguageVersion.CSharp7_3)); - } [Fact] - public async Task UpgradeProjectWithNotNullConstraintTo8_0_Delegate_AlreadyDefined() - { - await TestExactActionSetOfferedAsync( + public Task UpgradeProjectWithNotNullConstraintTo8_0_Delegate_AlreadyDefined() + => TestExactActionSetOfferedAsync( """ @@ -1009,12 +914,10 @@ interface notnull { } """, expectedActionSet: []); - } [Fact] - public async Task UpgradeProjectWithNotNullConstraintTo8_0_LocalFunction() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectWithNotNullConstraintTo8_0_LocalFunction() + => TestLanguageVersionUpgradedAsync( """ class Test { @@ -1026,12 +929,10 @@ void M() where T : [|notnull|] { } """, LanguageVersion.CSharp8, new CSharpParseOptions(LanguageVersion.CSharp7_3)); - } [Fact] - public async Task UpgradeProjectWithNotNullConstraintTo8_0_LocalFunction_AlreadyDefined() - { - await TestExactActionSetOfferedAsync( + public Task UpgradeProjectWithNotNullConstraintTo8_0_LocalFunction_AlreadyDefined() + => TestExactActionSetOfferedAsync( """ @@ -1049,12 +950,10 @@ public void N() """, expectedActionSet: []); - } [Fact] - public async Task UpgradeProjectForVarianceSafetyForStaticInterfaceMembers_CS8904() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectForVarianceSafetyForStaticInterfaceMembers_CS8904() + => TestLanguageVersionUpgradedAsync( """ interface I2 { @@ -1063,12 +962,10 @@ interface I2 """, expected: LanguageVersion.CSharp9, new CSharpParseOptions(LanguageVersion.CSharp8)); - } [Fact] - public async Task UpgradeProjectForSealedToStringInRecords_CS8912() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectForSealedToStringInRecords_CS8912() + => TestLanguageVersionUpgradedAsync( """ @@ -1089,78 +986,64 @@ public record Base """, expected: LanguageVersion.CSharp10, new CSharpParseOptions(LanguageVersion.CSharp9)); - } [Fact] - public async Task UpgradeProjectForPrimaryConstructors_Class() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectForPrimaryConstructors_Class() + => TestLanguageVersionUpgradedAsync( """ class Program[|()|]; """, LanguageVersion.CSharp12, new CSharpParseOptions(LanguageVersion.CSharp11)); - } [Fact] - public async Task UpgradeProjectForPrimaryConstructors_Struct() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectForPrimaryConstructors_Struct() + => TestLanguageVersionUpgradedAsync( """ struct Program[|()|]; """, LanguageVersion.CSharp12, new CSharpParseOptions(LanguageVersion.CSharp11)); - } [Fact] - public async Task UpgradeProjectForSemicolonBody_Class() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectForSemicolonBody_Class() + => TestLanguageVersionUpgradedAsync( """ class Program[|;|] """, LanguageVersion.CSharp12, new CSharpParseOptions(LanguageVersion.CSharp11)); - } [Fact] - public async Task UpgradeProjectForSemicolonBody_Struct() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectForSemicolonBody_Struct() + => TestLanguageVersionUpgradedAsync( """ struct Program[|;|] """, LanguageVersion.CSharp12, new CSharpParseOptions(LanguageVersion.CSharp11)); - } [Fact] - public async Task UpgradeProjectForSemicolonBody_Interface() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectForSemicolonBody_Interface() + => TestLanguageVersionUpgradedAsync( """ interface Program[|;|] """, LanguageVersion.CSharp12, new CSharpParseOptions(LanguageVersion.CSharp11)); - } [Fact] - public async Task UpgradeProjectForSemicolonBody_Enum() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectForSemicolonBody_Enum() + => TestLanguageVersionUpgradedAsync( """ enum Program[|;|] """, LanguageVersion.CSharp12, new CSharpParseOptions(LanguageVersion.CSharp11)); - } [Fact] - public async Task UpgradeProjectForTargetTypedNew() - { - await TestLanguageVersionUpgradedAsync(""" + public Task UpgradeProjectForTargetTypedNew() + => TestLanguageVersionUpgradedAsync(""" class Test { Test t = [|new()|]; @@ -1168,22 +1051,18 @@ class Test """, LanguageVersion.CSharp9, new CSharpParseOptions(LanguageVersion.CSharp8)); - } [Fact] - public async Task UpgradeProjectForGlobalUsing() - { - await TestLanguageVersionUpgradedAsync(""" + public Task UpgradeProjectForGlobalUsing() + => TestLanguageVersionUpgradedAsync(""" [|global using System;|] """, LanguageVersion.CSharp10, new CSharpParseOptions(LanguageVersion.CSharp9)); - } [Fact] - public async Task UpgradeProjectForImplicitImplementationOfNonPublicMembers_CS8704() - { - await TestLanguageVersionUpgradedAsync( + public Task UpgradeProjectForImplicitImplementationOfNonPublicMembers_CS8704() + => TestLanguageVersionUpgradedAsync( """ public interface I1 { @@ -1197,12 +1076,10 @@ class C1 : I1 """, expected: LanguageVersion.CSharp10, new CSharpParseOptions(LanguageVersion.CSharp9)); - } [Fact] - public async Task UpgradeProjectForTargetTypedConditional() - { - await TestLanguageVersionUpgradedAsync(""" + public Task UpgradeProjectForTargetTypedConditional() + => TestLanguageVersionUpgradedAsync(""" class C { void M(bool b) @@ -1213,12 +1090,10 @@ void M(bool b) """, expected: LanguageVersion.CSharp9, new CSharpParseOptions(LanguageVersion.CSharp8)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57154")] - public async Task UpgradeProjectForNewLinesInInterpolations() - { - await TestLanguageVersionUpgradedAsync(""" + public Task UpgradeProjectForNewLinesInInterpolations() + => TestLanguageVersionUpgradedAsync(""" class Test { void M() @@ -1231,12 +1106,10 @@ void M() """, expected: LanguageVersion.CSharp11, new CSharpParseOptions(LanguageVersion.CSharp8)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60167")] - public async Task UpgradeProjectForStructAutoDefaultError_1() - { - await TestLanguageVersionUpgradedAsync(""" + public Task UpgradeProjectForStructAutoDefaultError_1() + => TestLanguageVersionUpgradedAsync(""" struct Test { public int X; @@ -1245,12 +1118,10 @@ struct Test """, expected: LanguageVersion.CSharp11, new CSharpParseOptions(LanguageVersion.CSharp10)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60167")] - public async Task UpgradeProjectForStructAutoDefaultError_2() - { - await TestLanguageVersionUpgradedAsync(""" + public Task UpgradeProjectForStructAutoDefaultError_2() + => TestLanguageVersionUpgradedAsync(""" struct Test { public int X; @@ -1259,12 +1130,10 @@ struct Test """, expected: LanguageVersion.CSharp11, new CSharpParseOptions(LanguageVersion.CSharp10)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60167")] - public async Task UpgradeProjectForStructAutoDefaultError_3() - { - await TestLanguageVersionUpgradedAsync(""" + public Task UpgradeProjectForStructAutoDefaultError_3() + => TestLanguageVersionUpgradedAsync(""" struct Test { public int X { get; set; } @@ -1273,12 +1142,10 @@ struct Test """, expected: LanguageVersion.CSharp11, new CSharpParseOptions(LanguageVersion.CSharp10)); - } [Fact] - public async Task UpgradeProjectForRefInMismatch() - { - await TestLanguageVersionUpgradedAsync(""" + public Task UpgradeProjectForRefInMismatch() + => TestLanguageVersionUpgradedAsync(""" class C { void M1(in int x) { } @@ -1290,5 +1157,4 @@ void M2(ref int y) """, expected: LanguageVersion.CSharp12, new CSharpParseOptions(LanguageVersion.CSharp11)); - } } diff --git a/src/Analyzers/CSharp/Tests/UseAutoProperty/UseAutoPropertyTests.cs b/src/Analyzers/CSharp/Tests/UseAutoProperty/UseAutoPropertyTests.cs index 600dd05a4ac29..b216a35ff164c 100644 --- a/src/Analyzers/CSharp/Tests/UseAutoProperty/UseAutoPropertyTests.cs +++ b/src/Analyzers/CSharp/Tests/UseAutoProperty/UseAutoPropertyTests.cs @@ -27,9 +27,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider => (new CSharpUseAutoPropertyAnalyzer(), GetCSharpUseAutoPropertyCodeFixProvider()); [Fact] - public async Task TestSingleGetterFromField() - { - await TestInRegularAndScript1Async( + public Task TestSingleGetterFromField() + => TestInRegularAndScript1Async( """ class Class { @@ -50,12 +49,10 @@ class Class int P { get; } } """); - } [Fact] - public async Task TestSingleGetterFromField_FileScopedNamespace() - { - await TestInRegularAndScript1Async( + public Task TestSingleGetterFromField_FileScopedNamespace() + => TestInRegularAndScript1Async( """ namespace N; @@ -80,12 +77,10 @@ class Class int P { get; } } """); - } [Fact] - public async Task TestSingleGetterFromField_InRecord() - { - await TestInRegularAndScript1Async( + public Task TestSingleGetterFromField_InRecord() + => TestInRegularAndScript1Async( """ record Class { @@ -106,13 +101,10 @@ record Class int P { get; } } """, new TestParameters(TestOptions.RegularPreview)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28511")] - public async Task TestNullable1() - { - // ⚠ The expected outcome of this test should not change. - await TestMissingInRegularAndScriptAsync( + public Task TestNullable1() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -128,12 +120,10 @@ class Class } struct MutableInt { public int Value; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28511")] - public async Task TestNullable2() - { - await TestInRegularAndScript1Async( + public Task TestNullable2() + => TestInRegularAndScript1Async( """ class Class { @@ -156,12 +146,10 @@ class Class } struct MutableInt { public int Value; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28511")] - public async Task TestNullable3() - { - await TestInRegularAndScript1Async( + public Task TestNullable3() + => TestInRegularAndScript1Async( """ class Class { @@ -182,12 +170,10 @@ class Class int? P { get; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28511")] - public async Task TestNullable4() - { - await TestInRegularAndScript1Async( + public Task TestNullable4() + => TestInRegularAndScript1Async( """ class Class { @@ -208,13 +194,10 @@ class Class int? P { get; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28511")] - public async Task TestNullable5() - { - // Recursive type check - await TestMissingInRegularAndScriptAsync( + public Task TestNullable5() + => TestMissingInRegularAndScriptAsync( """ using System; class Class @@ -231,12 +214,10 @@ class Class } struct MutableInt { public int Value; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28511")] - public async Task TestMutableValueType1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMutableValueType1() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -252,12 +233,10 @@ MutableInt P } struct MutableInt { public int Value; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28511")] - public async Task TestMutableValueType2() - { - await TestInRegularAndScript1Async( + public Task TestMutableValueType2() + => TestInRegularAndScript1Async( """ class Class { @@ -280,12 +259,10 @@ class Class } struct MutableInt { public int Value; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28511")] - public async Task TestMutableValueType3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMutableValueType3() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -301,12 +278,10 @@ MutableInt P } struct MutableInt { public int Value { get; set; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28511")] - public async Task TestErrorType1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestErrorType1() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -321,12 +296,10 @@ ErrorType P } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28511")] - public async Task TestErrorType2() - { - await TestInRegularAndScript1Async( + public Task TestErrorType2() + => TestInRegularAndScript1Async( """ class Class { @@ -347,12 +320,10 @@ class Class ErrorType P { get; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28511")] - public async Task TestErrorType3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestErrorType3() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -367,12 +338,10 @@ class Class } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28511")] - public async Task TestErrorType4() - { - await TestInRegularAndScript1Async( + public Task TestErrorType4() + => TestInRegularAndScript1Async( """ class Class { @@ -393,12 +362,10 @@ class Class ErrorType? P { get; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28511")] - public async Task TestErrorType5() - { - await TestInRegularAndScript1Async( + public Task TestErrorType5() + => TestInRegularAndScript1Async( """ class Class { @@ -419,12 +386,10 @@ class Class ErrorType[] P { get; } } """); - } [Fact] - public async Task TestCSharp5_1() - { - await TestAsync( + public Task TestCSharp5_1() + => TestAsync( """ class Class { @@ -445,13 +410,11 @@ class Class public int P { get; private set; } } """, - CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)); - } + CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)); [Fact] - public async Task TestCSharp5_2() - { - await TestMissingAsync( + public Task TestCSharp5_2() + => TestMissingAsync( """ class Class { @@ -466,12 +429,10 @@ int P } } """, new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5))); - } [Fact] - public async Task TestInitializer() - { - await TestInRegularAndScript1Async( + public Task TestInitializer() + => TestInRegularAndScript1Async( """ class Class { @@ -492,12 +453,10 @@ class Class int P { get; } = 1; } """); - } [Fact] - public async Task TestInitializer_CSharp5() - { - await TestMissingAsync( + public Task TestInitializer_CSharp5() + => TestMissingAsync( """ class Class { @@ -512,12 +471,10 @@ int P } } """, new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5))); - } [Fact] - public async Task TestSingleGetterFromProperty() - { - await TestInRegularAndScript1Async( + public Task TestSingleGetterFromProperty() + => TestInRegularAndScript1Async( """ class Class { @@ -538,12 +495,10 @@ class Class int P { get; } } """); - } [Fact] - public async Task TestSingleSetter() - { - await TestMissingInRegularAndScriptAsync( + public Task TestSingleSetter() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -558,12 +513,10 @@ int P } } """); - } [Fact] - public async Task TestGetterAndSetter() - { - await TestInRegularAndScript1Async( + public Task TestGetterAndSetter() + => TestInRegularAndScript1Async( """ class Class { @@ -589,12 +542,10 @@ class Class int P { get; set; } } """); - } [Fact] - public async Task TestSingleGetterWithThis() - { - await TestInRegularAndScript1Async( + public Task TestSingleGetterWithThis() + => TestInRegularAndScript1Async( """ class Class { @@ -615,12 +566,10 @@ class Class int P { get; } } """); - } [Fact] - public async Task TestSingleSetterWithThis() - { - await TestMissingInRegularAndScriptAsync( + public Task TestSingleSetterWithThis() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -635,12 +584,10 @@ int P } } """); - } [Fact] - public async Task TestGetterAndSetterWithThis() - { - await TestInRegularAndScript1Async( + public Task TestGetterAndSetterWithThis() + => TestInRegularAndScript1Async( """ class Class { @@ -666,12 +613,10 @@ class Class int P { get; set; } } """); - } [Fact] - public async Task TestGetterWithMultipleStatements_CSharp12() - { - await TestMissingInRegularAndScriptAsync( + public Task TestGetterWithMultipleStatements_CSharp12() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -687,12 +632,10 @@ int P } } """, new TestParameters(parseOptions: CSharp12)); - } [Fact] - public async Task TestSetterWithMultipleStatements_CSharp12() - { - await TestMissingInRegularAndScriptAsync( + public Task TestSetterWithMultipleStatements_CSharp12() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -708,12 +651,10 @@ int P } } """); - } [Fact] - public async Task TestSetterWithMultipleStatementsAndGetterWithSingleStatement() - { - await TestMissingInRegularAndScriptAsync( + public Task TestSetterWithMultipleStatementsAndGetterWithSingleStatement() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -734,12 +675,10 @@ int P } } """, new TestParameters(parseOptions: CSharp12)); - } [Fact] - public async Task TestGetterAndSetterUseDifferentFields() - { - await TestMissingInRegularAndScriptAsync( + public Task TestGetterAndSetterUseDifferentFields() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -760,12 +699,10 @@ int P } } """); - } [Fact] - public async Task TestFieldAndPropertyHaveDifferentStaticInstance() - { - await TestMissingInRegularAndScriptAsync( + public Task TestFieldAndPropertyHaveDifferentStaticInstance() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -780,12 +717,10 @@ int P } } """); - } [Fact] - public async Task TestNotIfFieldUsedInRefArgument1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotIfFieldUsedInRefArgument1() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -805,12 +740,10 @@ void M(ref int x) } } """); - } [Fact] - public async Task TestNotIfFieldUsedInRefArgument2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotIfFieldUsedInRefArgument2() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -830,12 +763,10 @@ void M(ref int x) } } """); - } [Fact] - public async Task TestNotIfFieldUsedInOutArgument() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotIfFieldUsedInOutArgument() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -855,12 +786,10 @@ void M(out int x) } } """); - } [Fact] - public async Task TestNotIfFieldUsedInInArgument() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotIfFieldUsedInInArgument() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -880,12 +809,10 @@ void M(in int x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25429")] - public async Task TestNotIfFieldUsedInRefExpression() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotIfFieldUsedInRefExpression() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -905,12 +832,10 @@ void M() } } """); - } [Fact] - public async Task TestNotIfFieldUsedInRefExpression_AsCandidateSymbol() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotIfFieldUsedInRefExpression_AsCandidateSymbol() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -932,12 +857,10 @@ void M() } } """); - } [Fact] - public async Task TestIfUnrelatedSymbolUsedInRefExpression() - { - await TestInRegularAndScript1Async( + public Task TestIfUnrelatedSymbolUsedInRefExpression() + => TestInRegularAndScript1Async( """ class Class { @@ -975,12 +898,10 @@ void M() } } """); - } [Fact] - public async Task TestNotWithVirtualProperty() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithVirtualProperty() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -995,12 +916,10 @@ public virtual int P } } """); - } [Fact] - public async Task TestNotWithConstField() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithConstField() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -1015,12 +934,10 @@ int P } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25379")] - public async Task TestNotWithVolatileField() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithVolatileField() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -1035,12 +952,10 @@ int P } } """); - } [Fact] - public async Task TestFieldWithMultipleDeclarators1() - { - await TestInRegularAndScript1Async( + public Task TestFieldWithMultipleDeclarators1() + => TestInRegularAndScript1Async( """ class Class { @@ -1063,12 +978,10 @@ class Class int P { get; } } """); - } [Fact] - public async Task TestFieldWithMultipleDeclarators2() - { - await TestInRegularAndScript1Async( + public Task TestFieldWithMultipleDeclarators2() + => TestInRegularAndScript1Async( """ class Class { @@ -1091,12 +1004,10 @@ class Class int P { get; } } """); - } [Fact] - public async Task TestFieldWithMultipleDeclarators3() - { - await TestInRegularAndScript1Async( + public Task TestFieldWithMultipleDeclarators3() + => TestInRegularAndScript1Async( """ class Class { @@ -1119,12 +1030,10 @@ class Class int P { get; } } """); - } [Fact] - public async Task TestFieldAndPropertyInDifferentParts() - { - await TestInRegularAndScript1Async( + public Task TestFieldAndPropertyInDifferentParts() + => TestInRegularAndScript1Async( """ partial class Class { @@ -1152,12 +1061,10 @@ partial class Class int P { get; } } """); - } [Fact] - public async Task TestWithFieldWithAttribute() - { - await TestInRegularAndScriptAsync( + public Task TestWithFieldWithAttribute() + => TestInRegularAndScriptAsync( """ class Class { @@ -1180,12 +1087,10 @@ class Class int P { get; } } """); - } [Fact] - public async Task TestUpdateReferences() - { - await TestInRegularAndScript1Async( + public Task TestUpdateReferences() + => TestInRegularAndScript1Async( """ class Class { @@ -1216,12 +1121,10 @@ public Class() } } """); - } [Fact] - public async Task TestUpdateReferencesConflictResolution() - { - await TestInRegularAndScript1Async( + public Task TestUpdateReferencesConflictResolution() + => TestInRegularAndScript1Async( """ class Class { @@ -1252,12 +1155,10 @@ public Class(int P) } } """); - } [Fact] - public async Task TestWriteInConstructor() - { - await TestInRegularAndScript1Async( + public Task TestWriteInConstructor() + => TestInRegularAndScript1Async( """ class Class { @@ -1288,12 +1189,10 @@ public Class() } } """); - } [Fact] - public async Task TestWriteInNotInConstructor1() - { - await TestInRegularAndScript1Async( + public Task TestWriteInNotInConstructor1() + => TestInRegularAndScript1Async( """ class Class { @@ -1324,12 +1223,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestWriteInNotInConstructor2() - { - await TestInRegularAndScript1Async( + public Task TestWriteInNotInConstructor2() + => TestInRegularAndScript1Async( """ class Class { @@ -1360,12 +1257,10 @@ public void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30108")] - public async Task TestWriteInSimpleExpressionLambdaInConstructor() - { - await TestInRegularAndScript1Async( + public Task TestWriteInSimpleExpressionLambdaInConstructor() + => TestInRegularAndScript1Async( """ using System; @@ -1393,12 +1288,10 @@ class C } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30108")] - public async Task TestWriteInSimpleBlockLambdaInConstructor() - { - await TestInRegularAndScript1Async( + public Task TestWriteInSimpleBlockLambdaInConstructor() + => TestInRegularAndScript1Async( """ using System; @@ -1432,12 +1325,10 @@ class C } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30108")] - public async Task TestWriteInParenthesizedExpressionLambdaInConstructor() - { - await TestInRegularAndScript1Async( + public Task TestWriteInParenthesizedExpressionLambdaInConstructor() + => TestInRegularAndScript1Async( """ using System; @@ -1465,12 +1356,10 @@ class C } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30108")] - public async Task TestWriteInParenthesizedBlockLambdaInConstructor() - { - await TestInRegularAndScript1Async( + public Task TestWriteInParenthesizedBlockLambdaInConstructor() + => TestInRegularAndScript1Async( """ using System; @@ -1504,12 +1393,10 @@ class C } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30108")] - public async Task TestWriteInAnonymousMethodInConstructor() - { - await TestInRegularAndScript1Async( + public Task TestWriteInAnonymousMethodInConstructor() + => TestInRegularAndScript1Async( """ using System; @@ -1543,12 +1430,10 @@ class C } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30108")] - public async Task TestWriteInLocalFunctionInConstructor() - { - await TestInRegularAndScript1Async( + public Task TestWriteInLocalFunctionInConstructor() + => TestInRegularAndScript1Async( """ class C { @@ -1578,12 +1463,10 @@ void F() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30108")] - public async Task TestWriteInExpressionBodiedLocalFunctionInConstructor() - { - await TestInRegularAndScript1Async( + public Task TestWriteInExpressionBodiedLocalFunctionInConstructor() + => TestInRegularAndScript1Async( """ class C { @@ -1607,12 +1490,10 @@ class C } } """); - } [Fact] - public async Task TestReadInExpressionBodiedLocalFunctionInConstructor() - { - await TestInRegularAndScript1Async( + public Task TestReadInExpressionBodiedLocalFunctionInConstructor() + => TestInRegularAndScript1Async( """ class C { @@ -1636,36 +1517,30 @@ class C } } """); - } [Fact] - public async Task TestAlreadyAutoPropertyWithGetterWithNoBody() - { - await TestMissingInRegularAndScriptAsync( + public Task TestAlreadyAutoPropertyWithGetterWithNoBody() + => TestMissingInRegularAndScriptAsync( """ class Class { public int [|P|] { get; } } """); - } [Fact] - public async Task TestAlreadyAutoPropertyWithGetterAndSetterWithNoBody() - { - await TestMissingInRegularAndScriptAsync( + public Task TestAlreadyAutoPropertyWithGetterAndSetterWithNoBody() + => TestMissingInRegularAndScriptAsync( """ class Class { public int [|P|] { get; set; } } """); - } [Fact] - public async Task TestSingleLine1() - { - await TestInRegularAndScript1Async( + public Task TestSingleLine1() + => TestInRegularAndScript1Async( """ class Class { @@ -1679,12 +1554,10 @@ class Class int P { get; } } """); - } [Fact] - public async Task TestSingleLine2() - { - await TestInRegularAndScript1Async( + public Task TestSingleLine2() + => TestInRegularAndScript1Async( """ class Class { @@ -1701,12 +1574,10 @@ class Class int P { get; } } """); - } [Fact] - public async Task TestSingleLine3() - { - await TestInRegularAndScript1Async( + public Task TestSingleLine3() + => TestInRegularAndScript1Async( """ class Class { @@ -1724,12 +1595,10 @@ class Class int P { get; set; } } """); - } [Fact] - public async Task Tuple_SingleGetterFromField() - { - await TestInRegularAndScript1Async( + public Task Tuple_SingleGetterFromField() + => TestInRegularAndScript1Async( """ class Class { @@ -1750,12 +1619,10 @@ class Class (int, string) P { get; } } """); - } [Fact] - public async Task TupleWithNames_SingleGetterFromField() - { - await TestInRegularAndScript1Async( + public Task TupleWithNames_SingleGetterFromField() + => TestInRegularAndScript1Async( """ class Class { @@ -1776,12 +1643,10 @@ class Class (int a, string b) P { get; } } """); - } [Fact] - public async Task TupleWithDifferentNames_SingleGetterFromField() - { - await TestMissingInRegularAndScriptAsync( + public Task TupleWithDifferentNames_SingleGetterFromField() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -1796,12 +1661,10 @@ class Class } } """); - } [Fact] - public async Task TupleWithOneName_SingleGetterFromField() - { - await TestInRegularAndScript1Async( + public Task TupleWithOneName_SingleGetterFromField() + => TestInRegularAndScript1Async( """ class Class { @@ -1822,12 +1685,10 @@ class Class (int a, string) P { get; } } """); - } [Fact] - public async Task Tuple_Initializer() - { - await TestInRegularAndScript1Async( + public Task Tuple_Initializer() + => TestInRegularAndScript1Async( """ class Class { @@ -1848,12 +1709,10 @@ class Class (int, string) P { get; } = (1, "hello"); } """); - } [Fact] - public async Task Tuple_GetterAndSetter() - { - await TestMissingInRegularAndScriptAsync( + public Task Tuple_GetterAndSetter() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -1873,13 +1732,11 @@ class Class } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23216")] [WorkItem("https://github.com/dotnet/roslyn/issues/23215")] - public async Task TestFixAllInDocument1() - { - await TestInRegularAndScript1Async( + public Task TestFixAllInDocument1() + => TestInRegularAndScript1Async( """ class Class { @@ -1912,12 +1769,10 @@ class Class int Q { get; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26527")] - public async Task TestFixAllInDocument2() - { - await TestInRegularAndScript1Async( + public Task TestFixAllInDocument2() + => TestInRegularAndScript1Async( """ internal struct StringFormat { @@ -1959,12 +1814,10 @@ internal struct StringFormat public object[] Arguments { get; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23735")] - public async Task ExplicitInterfaceImplementationGetterOnly() - { - await TestMissingInRegularAndScriptAsync(""" + public Task ExplicitInterfaceImplementationGetterOnly() + => TestMissingInRegularAndScriptAsync(""" namespace RoslynSandbox { public interface IFoo @@ -1988,12 +1841,10 @@ object IFoo.Bar } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23735")] - public async Task ExplicitInterfaceImplementationGetterAndSetter() - { - await TestMissingInRegularAndScriptAsync(""" + public Task ExplicitInterfaceImplementationGetterAndSetter() + => TestMissingInRegularAndScriptAsync(""" namespace RoslynSandbox { public interface IFoo @@ -2018,12 +1869,10 @@ object IFoo.Bar } } """); - } [Fact] - public async Task ExpressionBodiedMemberGetOnly() - { - await TestInRegularAndScript1Async( + public Task ExpressionBodiedMemberGetOnly() + => TestInRegularAndScript1Async( """ class Class { @@ -2040,12 +1889,10 @@ class Class int P { get; } } """); - } [Fact] - public async Task ExpressionBodiedMemberGetOnlyWithInitializer() - { - await TestInRegularAndScript1Async( + public Task ExpressionBodiedMemberGetOnlyWithInitializer() + => TestInRegularAndScript1Async( """ class Class { @@ -2062,12 +1909,10 @@ class Class int P { get; } = 1; } """); - } [Fact] - public async Task ExpressionBodiedMemberGetOnlyWithInitializerAndNeedsSetter() - { - await TestInRegularAndScript1Async( + public Task ExpressionBodiedMemberGetOnlyWithInitializerAndNeedsSetter() + => TestInRegularAndScript1Async( """ class Class { @@ -2086,12 +1931,10 @@ class Class void M() { P = 2; } } """); - } [Fact] - public async Task ExpressionBodiedMemberGetterAndSetter() - { - await TestInRegularAndScript1Async( + public Task ExpressionBodiedMemberGetterAndSetter() + => TestInRegularAndScript1Async( """ class Class { @@ -2109,12 +1952,10 @@ class Class int P { get; set; } } """); - } [Fact] - public async Task ExpressionBodiedMemberGetter() - { - await TestInRegularAndScript1Async( + public Task ExpressionBodiedMemberGetter() + => TestInRegularAndScript1Async( """ class Class { @@ -2128,12 +1969,10 @@ class Class int P { get; } } """); - } [Fact] - public async Task ExpressionBodiedMemberGetterWithSetterNeeded() - { - await TestInRegularAndScript1Async( + public Task ExpressionBodiedMemberGetterWithSetterNeeded() + => TestInRegularAndScript1Async( """ class Class { @@ -2149,12 +1988,10 @@ class Class void M() { P = 1; } } """); - } [Fact] - public async Task ExpressionBodiedMemberGetterWithInitializer() - { - await TestInRegularAndScript1Async( + public Task ExpressionBodiedMemberGetterWithInitializer() + => TestInRegularAndScript1Async( """ class Class { @@ -2168,12 +2005,10 @@ class Class int P { get; } = 1; } """); - } [Fact] - public async Task ExpressionBodiedGetterAndSetter() - { - await TestInRegularAndScript1Async( + public Task ExpressionBodiedGetterAndSetter() + => TestInRegularAndScript1Async( """ class Class { @@ -2190,12 +2025,10 @@ class Class int P { get; set; } } """); - } [Fact] - public async Task ExpressionBodiedGetterAndSetterWithInitializer() - { - await TestInRegularAndScript1Async( + public Task ExpressionBodiedGetterAndSetterWithInitializer() + => TestInRegularAndScript1Async( """ class Class { @@ -2212,12 +2045,10 @@ class Class int P { get; set; } = 1; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25401")] - public async Task TestGetterAccessibilityDiffers() - { - await TestInRegularAndScript1Async( + public Task TestGetterAccessibilityDiffers() + => TestInRegularAndScript1Async( """ class Class { @@ -2243,12 +2074,10 @@ class Class public int P { protected get; set; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25401")] - public async Task TestSetterAccessibilityDiffers() - { - await TestInRegularAndScript1Async( + public Task TestSetterAccessibilityDiffers() + => TestInRegularAndScript1Async( """ class Class { @@ -2274,12 +2103,10 @@ class Class public int P { get; protected set; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26858")] - public async Task TestPreserveTrailingTrivia1() - { - await TestInRegularAndScript1Async( + public Task TestPreserveTrailingTrivia1() + => TestInRegularAndScript1Async( """ class Goo { @@ -2296,12 +2123,10 @@ class Goo public int Baz => 0; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26858")] - public async Task TestPreserveTrailingTrivia2() - { - await TestInRegularAndScript1Async( + public Task TestPreserveTrailingTrivia2() + => TestInRegularAndScript1Async( """ class Goo { @@ -2318,12 +2143,10 @@ class Goo public int Baz => 0; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26858")] - public async Task TestPreserveTrailingTrivia3() - { - await TestInRegularAndScript1Async( + public Task TestPreserveTrailingTrivia3() + => TestInRegularAndScript1Async( """ class Goo { @@ -2342,12 +2165,10 @@ class Goo public int Baz => 0; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26858")] - public async Task TestKeepLeadingBlank() - { - await TestInRegularAndScript1Async( + public Task TestKeepLeadingBlank() + => TestInRegularAndScript1Async( """ class Goo { @@ -2368,12 +2189,10 @@ class Goo public int Baz => 0; } """); - } [Fact] - public async Task TestMultipleFieldsAbove1() - { - await TestInRegularAndScript1Async( + public Task TestMultipleFieldsAbove1() + => TestInRegularAndScript1Async( """ class Class { @@ -2397,12 +2216,10 @@ class Class int P { get; } } """); - } [Fact] - public async Task TestMultipleFieldsAbove2() - { - await TestInRegularAndScript1Async( + public Task TestMultipleFieldsAbove2() + => TestInRegularAndScript1Async( """ class Class { @@ -2426,12 +2243,10 @@ class Class int P { get; } } """); - } [Fact] - public async Task TestMultipleFieldsAbove3() - { - await TestInRegularAndScript1Async( + public Task TestMultipleFieldsAbove3() + => TestInRegularAndScript1Async( """ class Class { @@ -2456,12 +2271,10 @@ class Class int P { get; } } """); - } [Fact] - public async Task TestMultipleFieldsAbove4() - { - await TestInRegularAndScript1Async( + public Task TestMultipleFieldsAbove4() + => TestInRegularAndScript1Async( """ class Class { @@ -2486,12 +2299,10 @@ class Class int P { get; } } """); - } [Fact] - public async Task TestMultipleFieldsBelow1() - { - await TestInRegularAndScript1Async( + public Task TestMultipleFieldsBelow1() + => TestInRegularAndScript1Async( """ class Class { @@ -2515,12 +2326,10 @@ class Class int j; } """); - } [Fact] - public async Task TestMultipleFieldsBelow2() - { - await TestInRegularAndScript1Async( + public Task TestMultipleFieldsBelow2() + => TestInRegularAndScript1Async( """ class Class { @@ -2544,12 +2353,10 @@ class Class int j; } """); - } [Fact] - public async Task TestMultipleFieldsBelow3() - { - await TestInRegularAndScript1Async( + public Task TestMultipleFieldsBelow3() + => TestInRegularAndScript1Async( """ class Class { @@ -2574,12 +2381,10 @@ class Class int j; } """); - } [Fact] - public async Task TestMultipleFieldsBelow4() - { - await TestInRegularAndScript1Async( + public Task TestMultipleFieldsBelow4() + => TestInRegularAndScript1Async( """ class Class { @@ -2604,12 +2409,10 @@ class Class int j; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27675")] - public async Task TestSingleLineWithDirective() - { - await TestInRegularAndScript1Async( + public Task TestSingleLineWithDirective() + => TestInRegularAndScript1Async( """ class Class { @@ -2635,12 +2438,10 @@ class Class int P { get; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27675")] - public async Task TestMultipleFieldsWithDirective() - { - await TestInRegularAndScript1Async( + public Task TestMultipleFieldsWithDirective() + => TestInRegularAndScript1Async( """ class Class { @@ -2670,12 +2471,10 @@ class Class } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27675")] - public async Task TestSingleLineWithDoubleDirectives() - { - await TestInRegularAndScript1Async( + public Task TestSingleLineWithDoubleDirectives() + => TestInRegularAndScript1Async( """ class TestClass { @@ -2702,12 +2501,10 @@ class TestClass #endregion } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40622")] - public async Task TestUseTabs() - { - await TestInRegularAndScript1Async( + public Task TestUseTabs() + => TestInRegularAndScript1Async( """ public class Foo { @@ -2722,12 +2519,10 @@ public class Foo public object O { get; } } """, new TestParameters(options: Option(FormattingOptions2.UseTabs, true))); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40622")] - public async Task TestUseSpaces() - { - await TestInRegularAndScript1Async( + public Task TestUseSpaces() + => TestInRegularAndScript1Async( """ public class Foo { @@ -2742,12 +2537,10 @@ public class Foo public object O { get; } } """, new TestParameters(options: Option(FormattingOptions2.UseTabs, false))); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40622")] - public async Task TestUseTabs_Editorconfig() - { - await TestInRegularAndScript1Async( + public Task TestUseTabs_Editorconfig() + => TestInRegularAndScript1Async( """ @@ -2782,12 +2575,10 @@ public class Foo """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40622")] - public async Task TestUseSpaces_Editorconfig() - { - await TestInRegularAndScript1Async( + public Task TestUseSpaces_Editorconfig() + => TestInRegularAndScript1Async( """ @@ -2822,12 +2613,10 @@ public class Foo """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34783")] - public async Task TestNotOnSerializableType() - { - await TestMissingAsync( + public Task TestNotOnSerializableType() + => TestMissingAsync( """ [System.Serializable] class Class @@ -2843,12 +2632,10 @@ int P } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47999")] - public async Task TestPropertyIsReadOnlyAndSetterNeeded() - { - await TestInRegularAndScript1Async( + public Task TestPropertyIsReadOnlyAndSetterNeeded() + => TestInRegularAndScript1Async( """ struct S { @@ -2864,12 +2651,10 @@ struct S public void SetP(int value) => P = value; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47999")] - public async Task TestPropertyIsReadOnlyWithNoAccessModifierAndSetterNeeded() - { - await TestInRegularAndScript1Async( + public Task TestPropertyIsReadOnlyWithNoAccessModifierAndSetterNeeded() + => TestInRegularAndScript1Async( """ struct S { @@ -2885,12 +2670,10 @@ struct S public void SetP(int value) => P = value; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47999")] - public async Task TestPropertyIsReadOnlyAndSetterUnneeded() - { - await TestInRegularAndScript1Async( + public Task TestPropertyIsReadOnlyAndSetterUnneeded() + => TestInRegularAndScript1Async( """ struct S { @@ -2904,12 +2687,10 @@ struct S public readonly int P { get; } } """); - } [Fact] - public async Task TestPropertyInRecordStruct() - { - await TestInRegularAndScript1Async( + public Task TestPropertyInRecordStruct() + => TestInRegularAndScript1Async( """ record struct S { @@ -2923,12 +2704,10 @@ record struct S public readonly int P { get; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38286")] - public async Task TestPointer1() - { - await TestInRegularAndScriptAsync( + public Task TestPointer1() + => TestInRegularAndScriptAsync( """ class Class { @@ -2943,12 +2722,10 @@ class Class int* P { get; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38286")] - public async Task TestPointer2() - { - await TestMissingAsync( + public Task TestPointer2() + => TestMissingAsync( """ class Class { @@ -2964,12 +2741,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25408")] - public async Task TestLinkedFile() - { - await TestInRegularAndScript1Async( + public Task TestLinkedFile() + => TestInRegularAndScript1Async( """ @@ -3004,12 +2779,10 @@ public C(int value) public int Value { get; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32597")] - public async Task TestUnassignedVariable1() - { - await TestMissingAsync( + public Task TestUnassignedVariable1() + => TestMissingAsync( """ public struct UInt128 { @@ -3026,12 +2799,10 @@ public static void Create(out UInt128 c, uint r0, uint r1, uint r2, uint r3) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32597")] - public async Task TestAssignedVariable1() - { - await TestInRegularAndScript1Async( + public Task TestAssignedVariable1() + => TestInRegularAndScript1Async( """ public struct UInt128 { @@ -3065,12 +2836,10 @@ public static void Create(out UInt128 c, uint r0, uint r1, uint r2, uint r3) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71032")] - public async Task TestWithInitProperty1() - { - await TestInRegularAndScriptAsync( + public Task TestWithInitProperty1() + => TestInRegularAndScriptAsync( """ using System; @@ -3092,12 +2861,10 @@ public class C public required string Action { get; init; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71032")] - public async Task TestNotWithInitProperty1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithInitProperty1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -3113,12 +2880,10 @@ public required string Action private void SetAction(string newAction) => _action = newAction; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76634")] - public async Task TestRefField() - { - await TestMissingInRegularAndScriptAsync( + public Task TestRefField() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -3133,12 +2898,10 @@ int P } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78225")] - public async Task TestRefProperty1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestRefProperty1() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -3153,12 +2916,10 @@ ref int P } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78225")] - public async Task TestRefProperty2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestRefProperty2() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -3167,12 +2928,10 @@ class Class ref int P => ref i; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78225")] - public async Task TestRefProperty3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestRefProperty3() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -3181,5 +2940,4 @@ class Class readonly ref int P => ref i; } """); - } } diff --git a/src/Analyzers/CSharp/Tests/UseAutoProperty/UseAutoPropertyTests_Field.cs b/src/Analyzers/CSharp/Tests/UseAutoProperty/UseAutoPropertyTests_Field.cs index 24d1b83ee50e0..16b8a592ac025 100644 --- a/src/Analyzers/CSharp/Tests/UseAutoProperty/UseAutoPropertyTests_Field.cs +++ b/src/Analyzers/CSharp/Tests/UseAutoProperty/UseAutoPropertyTests_Field.cs @@ -18,9 +18,8 @@ public sealed partial class UseAutoPropertyTests private static readonly ParseOptions CSharp14 = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersionExtensions.CSharpNext); [Fact] - public async Task TestNotInCSharp13() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotInCSharp13() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -35,12 +34,10 @@ string P } } """, new(parseOptions: CSharp13)); - } [Fact] - public async Task TestFieldSimplestCase() - { - await TestInRegularAndScriptAsync( + public Task TestFieldSimplestCase() + => TestInRegularAndScriptAsync( """ class Class { @@ -67,12 +64,10 @@ string P } } """, parseOptions: CSharp14); - } [Fact] - public async Task TestFieldWithInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestFieldWithInitializer() + => TestInRegularAndScriptAsync( """ class Class { @@ -99,12 +94,10 @@ string P } = ""; } """, parseOptions: CSharp14); - } [Fact] - public async Task TestFieldAccessOffOfThis() - { - await TestInRegularAndScriptAsync( + public Task TestFieldAccessOffOfThis() + => TestInRegularAndScriptAsync( """ class Class { @@ -131,12 +124,10 @@ string P } } """, parseOptions: CSharp14); - } [Fact] - public async Task TestStaticField() - { - await TestInRegularAndScriptAsync( + public Task TestStaticField() + => TestInRegularAndScriptAsync( """ class Class { @@ -163,12 +154,10 @@ static string P } } """, parseOptions: CSharp14); - } [Fact] - public async Task TestGetterWithMultipleStatements_Field() - { - await TestInRegularAndScriptAsync( + public Task TestGetterWithMultipleStatements_Field() + => TestInRegularAndScriptAsync( """ class Class { @@ -197,12 +186,10 @@ int P } } """, parseOptions: CSharp14); - } [Fact] - public async Task TestSetterWithMultipleStatementsAndGetterWithSingleStatement_Field() - { - await TestInRegularAndScriptAsync( + public Task TestSetterWithMultipleStatementsAndGetterWithSingleStatement_Field() + => TestInRegularAndScriptAsync( """ class Class { @@ -238,12 +225,10 @@ int P } } """, parseOptions: CSharp14); - } [Fact] - public async Task TestSetterWithMultipleStatementsAndGetterWithSingleStatement_Field2() - { - await TestInRegularAndScriptAsync( + public Task TestSetterWithMultipleStatementsAndGetterWithSingleStatement_Field2() + => TestInRegularAndScriptAsync( """ class Class { @@ -276,12 +261,10 @@ int P } } """, parseOptions: CSharp14); - } [Fact] - public async Task TestSimpleFieldInExpressionBody() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleFieldInExpressionBody() + => TestInRegularAndScriptAsync( """ class Class { @@ -296,12 +279,10 @@ class Class string P => field.Trim(); } """, parseOptions: CSharp14); - } [Fact] - public async Task TestMultipleFields_NoClearChoice() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMultipleFields_NoClearChoice() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -310,12 +291,10 @@ class Class int Total => x + y; } """, new(parseOptions: CSharp14)); - } [Fact] - public async Task TestMultipleFields_NoClearChoice2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMultipleFields_NoClearChoice2() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -332,12 +311,10 @@ int Total } } """, new(parseOptions: CSharp14)); - } [Fact] - public async Task TestMultipleFields_ClearChoice() - { - await TestInRegularAndScriptAsync( + public Task TestMultipleFields_ClearChoice() + => TestInRegularAndScriptAsync( """ class Class { @@ -365,12 +342,10 @@ int Total } } """, parseOptions: CSharp14); - } [Fact] - public async Task TestMultipleFields_PickByName1() - { - await TestInRegularAndScriptAsync( + public Task TestMultipleFields_PickByName1() + => TestInRegularAndScriptAsync( """ class Class { @@ -387,12 +362,10 @@ class Class int X => field + y; } """, parseOptions: CSharp14); - } [Fact] - public async Task TestMultipleFields_PickByName2() - { - await TestInRegularAndScriptAsync( + public Task TestMultipleFields_PickByName2() + => TestInRegularAndScriptAsync( """ class Class { @@ -409,12 +382,10 @@ class Class int X => field + y; } """, parseOptions: CSharp14); - } [Fact] - public async Task TestNotWhenAlreadyUsingField() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWhenAlreadyUsingField() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -430,12 +401,10 @@ string P } } """, new(parseOptions: CSharp14)); - } [Fact] - public async Task TestNotWhenUsingNameof1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWhenUsingNameof1() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -452,12 +421,10 @@ string P } } """, new(parseOptions: CSharp14)); - } [Fact] - public async Task TestNotWhenUsingNameof2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWhenUsingNameof2() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -474,12 +441,10 @@ string P } } """, new(parseOptions: CSharp14)); - } [Fact] - public async Task TestNotWhenUsingNameof3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWhenUsingNameof3() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -500,12 +465,10 @@ void M() } } """, new(parseOptions: CSharp14)); - } [Fact] - public async Task TestNotWhenUsingNameof4() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWhenUsingNameof4() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -526,12 +489,10 @@ void M() } } """, new(parseOptions: CSharp14)); - } [Fact] - public async Task TestNotWhenUsingNameof5() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWhenUsingNameof5() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -540,12 +501,10 @@ class Class string P => s; } """, new(parseOptions: CSharp13)); - } [Fact] - public async Task TestWithRefArgumentUseInside() - { - await TestInRegularAndScriptAsync( + public Task TestWithRefArgumentUseInside() + => TestInRegularAndScriptAsync( """ class Class { @@ -568,12 +527,10 @@ void Init(ref string s) } } """, parseOptions: CSharp14); - } [Fact] - public async Task TestNotWithRefArgumentUseOutside() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithRefArgumentUseOutside() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -591,12 +548,10 @@ void Init(ref string s) } } """, new(parseOptions: CSharp14)); - } [Fact] - public async Task TestWithRefUseInside() - { - await TestInRegularAndScriptAsync( + public Task TestWithRefUseInside() + => TestInRegularAndScriptAsync( """ class Class { @@ -625,12 +580,10 @@ string P } } """, parseOptions: CSharp14); - } [Fact] - public async Task TestNotWithRefUseOutside() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithRefUseOutside() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -650,12 +603,10 @@ void M() } } """, new(parseOptions: CSharp14)); - } [Fact] - public async Task TestWithAddressOfInside() - { - await TestInRegularAndScriptAsync( + public Task TestWithAddressOfInside() + => TestInRegularAndScriptAsync( """ class Class { @@ -690,12 +641,10 @@ int P } } """, parseOptions: CSharp14); - } [Fact] - public async Task TestNotWithAddressOfOutside() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithAddressOfOutside() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -718,12 +667,10 @@ unsafe void M() } } """, new(parseOptions: CSharp14)); - } [Fact] - public async Task TestNotChainedPattern1() - { - await TestInRegularAndScriptAsync( + public Task TestNotChainedPattern1() + => TestInRegularAndScriptAsync( """ class Builder { @@ -749,12 +696,10 @@ public bool StrictMode } } """, parseOptions: CSharp14); - } [Fact] - public async Task TestLazyInit1() - { - await TestInRegularAndScriptAsync( + public Task TestLazyInit1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -773,12 +718,10 @@ class Builder public List List => field ??= new(); } """, parseOptions: CSharp14); - } [Fact] - public async Task TestRefSetAccessor1() - { - await TestInRegularAndScriptAsync( + public Task TestRefSetAccessor1() + => TestInRegularAndScriptAsync( """ class Builder { @@ -796,12 +739,10 @@ class Builder void Set(ref int a, int b) { } } """, parseOptions: CSharp14); - } [Fact] - public async Task TestRefSetAccessor2() - { - await TestInRegularAndScriptAsync( + public Task TestRefSetAccessor2() + => TestInRegularAndScriptAsync( """ class Builder { @@ -838,12 +779,10 @@ void Set(ref int a, int b) { } void OnPropChanged() { } } """, parseOptions: CSharp14); - } [Fact] - public async Task TestAttributesOnField() - { - await TestInRegularAndScriptAsync( + public Task TestAttributesOnField() + => TestInRegularAndScriptAsync( """ class C { @@ -859,12 +798,10 @@ class C public int Prop { get; set; } } """, parseOptions: CSharp14); - } [Fact] - public async Task TestAttributesOnField2() - { - await TestInRegularAndScriptAsync( + public Task TestAttributesOnField2() + => TestInRegularAndScriptAsync( """ class C { @@ -880,12 +817,10 @@ class C public string Prop => field.Trim(); } """, parseOptions: CSharp14); - } [Fact] - public async Task TestAttributesOnField3() - { - await TestInRegularAndScriptAsync( + public Task TestAttributesOnField3() + => TestInRegularAndScriptAsync( """ class C { @@ -904,12 +839,10 @@ class C public string Prop => field.Trim(); } """, parseOptions: CSharp14); - } [Fact] - public async Task TestAttributesOnField4() - { - await TestInRegularAndScriptAsync( + public Task TestAttributesOnField4() + => TestInRegularAndScriptAsync( """ class C { @@ -930,12 +863,10 @@ class C public string Prop => field.Trim(); } """, parseOptions: CSharp14); - } [Fact] - public async Task TestAttributesOnField5() - { - await TestInRegularAndScriptAsync( + public Task TestAttributesOnField5() + => TestInRegularAndScriptAsync( """ class C { @@ -956,12 +887,10 @@ class C public string Prop => field.Trim(); } """, parseOptions: CSharp14); - } [Fact] - public async Task TestAttributesOnField6() - { - await TestInRegularAndScriptAsync( + public Task TestAttributesOnField6() + => TestInRegularAndScriptAsync( """ class C { @@ -980,12 +909,10 @@ class C public string Prop => field.Trim(); } """, parseOptions: CSharp14); - } [Fact] - public async Task TestAttributesOnField7() - { - await TestInRegularAndScriptAsync( + public Task TestAttributesOnField7() + => TestInRegularAndScriptAsync( """ class C { @@ -1005,12 +932,10 @@ class C public string Prop => field.Trim(); } """, parseOptions: CSharp14); - } [Fact] - public async Task TestFieldUsedInObjectInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestFieldUsedInObjectInitializer() + => TestInRegularAndScriptAsync( """ class C { @@ -1039,12 +964,10 @@ public string Prop } } """, parseOptions: CSharp14); - } [Fact] - public async Task TestSimpleFieldInExpressionBody_FieldWrittenElsewhere1() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleFieldInExpressionBody_FieldWrittenElsewhere1() + => TestInRegularAndScriptAsync( """ class Class { @@ -1069,12 +992,10 @@ void M() } } """, parseOptions: CSharp14); - } [Fact] - public async Task TestSimpleFieldInExpressionBody_FieldWrittenElsewhere2() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleFieldInExpressionBody_FieldWrittenElsewhere2() + => TestInRegularAndScriptAsync( """ class Class { @@ -1099,12 +1020,10 @@ void M() } } """, parseOptions: CSharp14); - } [Fact] - public async Task TestSimpleFieldInExpressionBody_FieldWrittenElsewhere3() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleFieldInExpressionBody_FieldWrittenElsewhere3() + => TestInRegularAndScriptAsync( """ class Class { @@ -1135,12 +1054,10 @@ void M() } } """, parseOptions: CSharp14); - } [Fact] - public async Task TestSimpleFieldInExpressionBody_FieldWrittenElsewhere4() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleFieldInExpressionBody_FieldWrittenElsewhere4() + => TestInRegularAndScriptAsync( """ class Class { @@ -1179,12 +1096,10 @@ void M() } } """, parseOptions: CSharp14); - } [Fact] - public async Task TestNonTrivialGetterWithExternalRead1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNonTrivialGetterWithExternalRead1() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -1198,12 +1113,10 @@ void M() } } """, new(parseOptions: CSharp14)); - } [Fact] - public async Task TestNonTrivialGetterWithExternalRead2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNonTrivialGetterWithExternalRead2() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -1217,12 +1130,10 @@ void M() } } """, new(parseOptions: CSharp14)); - } [Fact] - public async Task TestNonTrivialSetterWithExternalWrite1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNonTrivialSetterWithExternalWrite1() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -1236,12 +1147,10 @@ void M() } } """, new(parseOptions: CSharp14)); - } [Fact] - public async Task TestNonTrivialSetterWithExternalWrite2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNonTrivialSetterWithExternalWrite2() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -1255,12 +1164,10 @@ void M() } } """, new(parseOptions: CSharp14)); - } [Fact] - public async Task TestNonTrivialSetterWithNoExternalWrite1() - { - await TestInRegularAndScriptAsync( + public Task TestNonTrivialSetterWithNoExternalWrite1() + => TestInRegularAndScriptAsync( """ class Class { @@ -1275,12 +1182,10 @@ class Class public int I { get; set => field = value / 2; } } """, parseOptions: CSharp14); - } [Fact] - public async Task TestNonTrivialGetterWithExternalReadWrite1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNonTrivialGetterWithExternalReadWrite1() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -1294,12 +1199,10 @@ void M() } } """, new(parseOptions: CSharp14)); - } [Fact] - public async Task TestNonTrivialSetterWithExternalReadWrite1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNonTrivialSetterWithExternalReadWrite1() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -1313,12 +1216,10 @@ void M() } } """, new(parseOptions: CSharp14)); - } [Fact] - public async Task TestTrivialGetterWithExternalRead1() - { - await TestInRegularAndScriptAsync( + public Task TestTrivialGetterWithExternalRead1() + => TestInRegularAndScriptAsync( """ class Class { @@ -1343,12 +1244,10 @@ void M() } } """, parseOptions: CSharp14); - } [Fact] - public async Task TestNoSetterWithExternalWrite1() - { - await TestInRegularAndScriptAsync( + public Task TestNoSetterWithExternalWrite1() + => TestInRegularAndScriptAsync( """ class Class { @@ -1373,12 +1272,10 @@ void M() } } """, parseOptions: CSharp14); - } [Fact] - public async Task TestFormatString() - { - await TestInRegularAndScriptAsync( + public Task TestFormatString() + => TestInRegularAndScriptAsync( """ class C { @@ -1392,12 +1289,10 @@ class C public string Prop => $"{field:prop}"; } """, parseOptions: CSharp14); - } [Fact] - public async Task TestNoSetterButWrittenOutside() - { - await TestInRegularAndScriptAsync( + public Task TestNoSetterButWrittenOutside() + => TestInRegularAndScriptAsync( """ class C { @@ -1415,12 +1310,10 @@ class C void M() { Prop = "..."; } } """, parseOptions: CSharp14); - } [Fact] - public async Task TestNotWithNameofInAttribute() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithNameofInAttribute() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1429,12 +1322,10 @@ class C public string Prop { get => prop; set => prop = value; } } """, new(parseOptions: CSharp14)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75516")] - public async Task TestBackingFieldUsedAsArgument1() - { - await TestInRegularAndScriptAsync(""" + public Task TestBackingFieldUsedAsArgument1() + => TestInRegularAndScriptAsync(""" class C { [|int _i;|] @@ -1466,12 +1357,10 @@ int P void M(int i) { } } """, parseOptions: CSharp14); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75516")] - public async Task TestBackingFieldUsedAsArgument2() - { - await TestInRegularAndScriptAsync(""" + public Task TestBackingFieldUsedAsArgument2() + => TestInRegularAndScriptAsync(""" class C { [|int _i;|] @@ -1503,12 +1392,10 @@ int P void M(ref int i) { } } """, parseOptions: CSharp14); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26527")] - public async Task TestFixAllInDocument3() - { - await TestInRegularAndScript1Async( + public Task TestFixAllInDocument3() + => TestInRegularAndScript1Async( """ using System; @@ -1538,12 +1425,10 @@ public sealed class SomeViewModel private void Set(ref T field, T value) => throw new NotImplementedException(); } """, new TestParameters(parseOptions: CSharp14)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76790")] - public async Task TestFixAllInDocument4() - { - await TestInRegularAndScript1Async( + public Task TestFixAllInDocument4() + => TestInRegularAndScript1Async( """ class C { @@ -1572,12 +1457,10 @@ void M() public bool B { get => !field; private set; } } """, new TestParameters(parseOptions: CSharp14)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76790")] - public async Task TestWrittenInConstructor() - { - await TestInRegularAndScript1Async( + public Task TestWrittenInConstructor() + => TestInRegularAndScript1Async( """ class C { @@ -1601,12 +1484,10 @@ void M() public bool B { get => !field; private set; } } """, new TestParameters(parseOptions: CSharp14)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76901")] - public async Task TestReadAndWrite() - { - await TestInRegularAndScript1Async( + public Task TestReadAndWrite() + => TestInRegularAndScript1Async( """ class C { @@ -1629,12 +1510,10 @@ public int CustomGetter } } """, new TestParameters(parseOptions: CSharp14)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76901")] - public async Task TestContractCall() - { - await TestInRegularAndScript1Async( + public Task TestContractCall() + => TestInRegularAndScript1Async( """ class C { @@ -1665,12 +1544,10 @@ public int CustomSetter } } """, new TestParameters(parseOptions: CSharp14)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76901")] - public async Task TestDelegateInvoke() - { - await TestInRegularAndScript1Async( + public Task TestDelegateInvoke() + => TestInRegularAndScript1Async( """ using System; @@ -1708,5 +1585,4 @@ public int ObservableProp } } """, new TestParameters(parseOptions: CSharp14)); - } } diff --git a/src/Analyzers/CSharp/Tests/UseCoalesceExpression/UseCoalesceExpressionForIfNullStatementCheckTests.cs b/src/Analyzers/CSharp/Tests/UseCoalesceExpression/UseCoalesceExpressionForIfNullStatementCheckTests.cs index 5929c1d2c2a70..833547d44fb03 100644 --- a/src/Analyzers/CSharp/Tests/UseCoalesceExpression/UseCoalesceExpressionForIfNullStatementCheckTests.cs +++ b/src/Analyzers/CSharp/Tests/UseCoalesceExpression/UseCoalesceExpressionForIfNullStatementCheckTests.cs @@ -20,9 +20,8 @@ namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.UseCoalesceExpressio public sealed class UseCoalesceExpressionForIfNullStatementCheckTests { [Fact] - public async Task TestLocalDeclaration_ThrowStatement() - { - await new VerifyCS.Test + public Task TestLocalDeclaration_ThrowStatement() + => new VerifyCS.Test { TestCode = """ class C @@ -49,12 +48,10 @@ void M() } """ }.RunAsync(); - } [Fact] - public async Task TestLocalDeclaration_Block() - { - await new VerifyCS.Test + public Task TestLocalDeclaration_Block() + => new VerifyCS.Test { TestCode = """ class C @@ -83,12 +80,10 @@ void M() } """ }.RunAsync(); - } [Fact] - public async Task TestLocalDeclaration_IsPattern() - { - await new VerifyCS.Test + public Task TestLocalDeclaration_IsPattern() + => new VerifyCS.Test { TestCode = """ class C @@ -115,12 +110,10 @@ void M() } """ }.RunAsync(); - } [Fact] - public async Task TestLocalDeclaration_Assignment1() - { - await new VerifyCS.Test + public Task TestLocalDeclaration_Assignment1() + => new VerifyCS.Test { TestCode = """ class C @@ -147,12 +140,10 @@ void M() } """ }.RunAsync(); - } [Fact] - public async Task TestLocalDeclaration_Assignment2() - { - await new VerifyCS.Test + public Task TestLocalDeclaration_Assignment2() + => new VerifyCS.Test { TestCode = """ class C @@ -180,12 +171,12 @@ void M() """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestLocalDeclaration_NotWithWrongItemChecked() - { - var text = """ + public Task TestLocalDeclaration_NotWithWrongItemChecked() + => new VerifyCS.Test + { + TestCode = """ class C { void M(C item1) @@ -197,18 +188,14 @@ void M(C item1) object FindItem() => null; } - """; - - await new VerifyCS.Test - { - TestCode = text, + """, }.RunAsync(); - } [Fact] - public async Task TestLocalDeclaration_NotWithWrongCondition() - { - var text = """ + public Task TestLocalDeclaration_NotWithWrongCondition() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -220,18 +207,14 @@ void M() object FindItem() => null; } - """; - - await new VerifyCS.Test - { - TestCode = text, + """, }.RunAsync(); - } [Fact] - public async Task TestLocalDeclaration_NotWithWrongPattern() - { - var text = """ + public Task TestLocalDeclaration_NotWithWrongPattern() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -243,19 +226,15 @@ void M() object FindItem() => null; } - """; - - await new VerifyCS.Test - { - TestCode = text, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestLocalDeclaration_NotWithWrongAssignment() - { - var text = """ + public Task TestLocalDeclaration_NotWithWrongAssignment() + => new VerifyCS.Test + { + TestCode = """ class C { void M(C item1) @@ -267,18 +246,14 @@ void M(C item1) object FindItem() => null; } - """; - - await new VerifyCS.Test - { - TestCode = text, + """, }.RunAsync(); - } [Fact] - public async Task TestLocalDeclaration_NotWithElseBlock() - { - var text = """ + public Task TestLocalDeclaration_NotWithElseBlock() + => new VerifyCS.Test + { + TestCode = """ class C { void M(C item1) @@ -292,18 +267,14 @@ void M(C item1) object FindItem() => null; } - """; - - await new VerifyCS.Test - { - TestCode = text, + """, }.RunAsync(); - } [Fact] - public async Task TestLocalDeclaration_NotWithMultipleWhenTrueStatements() - { - var text = """ + public Task TestLocalDeclaration_NotWithMultipleWhenTrueStatements() + => new VerifyCS.Test + { + TestCode = """ class C { void M(C item1) @@ -318,18 +289,14 @@ void M(C item1) object FindItem() => null; } - """; - - await new VerifyCS.Test - { - TestCode = text, + """, }.RunAsync(); - } [Fact] - public async Task TestLocalDeclaration_NotWithNoWhenTrueStatements() - { - var text = """ + public Task TestLocalDeclaration_NotWithNoWhenTrueStatements() + => new VerifyCS.Test + { + TestCode = """ class C { void M(C item1) @@ -342,18 +309,14 @@ void M(C item1) object FindItem() => null; } - """; - - await new VerifyCS.Test - { - TestCode = text, + """, }.RunAsync(); - } [Fact] - public async Task TestLocalDeclaration_NotWithThrowWithoutExpression() - { - var text = """ + public Task TestLocalDeclaration_NotWithThrowWithoutExpression() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -371,18 +334,14 @@ void M() object FindItem() => null; } - """; - - await new VerifyCS.Test - { - TestCode = text, + """, }.RunAsync(); - } [Fact] - public async Task TestLocalDeclaration_NotWithLocalWithoutInitializer() - { - var text = """ + public Task TestLocalDeclaration_NotWithLocalWithoutInitializer() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -394,18 +353,14 @@ void M() object FindItem() => null; } - """; - - await new VerifyCS.Test - { - TestCode = text, + """, }.RunAsync(); - } [Fact] - public async Task TestLocalDeclaration_NotWithValueTypeInitializer() - { - var text = """ + public Task TestLocalDeclaration_NotWithValueTypeInitializer() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -417,18 +372,14 @@ void M() object FindItem() => null; } - """; - - await new VerifyCS.Test - { - TestCode = text, + """, }.RunAsync(); - } [Fact] - public async Task TestLocalDeclaration_NotWithReferenceToVariableInThrow() - { - var text = """ + public Task TestLocalDeclaration_NotWithReferenceToVariableInThrow() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -440,19 +391,13 @@ void M() object FindItem() => null; } - """; - - await new VerifyCS.Test - { - TestCode = text, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/74460")] - public async Task TestLocalDeclaration_CastWithParenthesizedExpression() - { - await new VerifyCS.Test + public Task TestLocalDeclaration_CastWithParenthesizedExpression() + => new VerifyCS.Test { TestCode = """ @@ -495,12 +440,10 @@ class D : I } """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/74460")] - public async Task TestLocalDeclaration_CastWithoutParenthesizedExpression() - { - await new VerifyCS.Test + public Task TestLocalDeclaration_CastWithoutParenthesizedExpression() + => new VerifyCS.Test { TestCode = """ @@ -543,12 +486,10 @@ class D : I } """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/74460")] - public async Task TestLocalDeclaration_NoCastWhenEqualSymbol() - { - await new VerifyCS.Test + public Task TestLocalDeclaration_NoCastWhenEqualSymbol() + => new VerifyCS.Test { TestCode = """ @@ -583,12 +524,10 @@ void M(C c1, C c2) } """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/74460")] - public async Task TestLocalDeclaration_NoCastWhenDerivedClass() - { - await new VerifyCS.Test + public Task TestLocalDeclaration_NoCastWhenDerivedClass() + => new VerifyCS.Test { TestCode = """ @@ -631,12 +570,10 @@ class D : C } """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/74460")] - public async Task TestLocalDeclaration_NoCastWhenDerivedClassReversed() - { - await new VerifyCS.Test + public Task TestLocalDeclaration_NoCastWhenDerivedClassReversed() + => new VerifyCS.Test { TestCode = """ @@ -679,12 +616,10 @@ class D : I } """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70514")] - public async Task TestNotAcrossPreprocessorRegion() - { - await new VerifyCS.Test + public Task TestNotAcrossPreprocessorRegion() + => new VerifyCS.Test { TestCode = """ #define DEBUG @@ -704,5 +639,4 @@ void M() } """, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UseCoalesceExpression/UseCoalesceExpressionForNullableTernaryConditionalCheckTests.cs b/src/Analyzers/CSharp/Tests/UseCoalesceExpression/UseCoalesceExpressionForNullableTernaryConditionalCheckTests.cs index 35c21bbcbd8b2..c0ce194d899c4 100644 --- a/src/Analyzers/CSharp/Tests/UseCoalesceExpression/UseCoalesceExpressionForNullableTernaryConditionalCheckTests.cs +++ b/src/Analyzers/CSharp/Tests/UseCoalesceExpression/UseCoalesceExpressionForNullableTernaryConditionalCheckTests.cs @@ -28,9 +28,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider new UseCoalesceExpressionForNullableTernaryConditionalCheckCodeFixProvider()); [Fact] - public async Task TestOnLeft_Equals() - { - await TestInRegularAndScriptAsync( + public Task TestOnLeft_Equals() + => TestInRegularAndScriptAsync( """ using System; @@ -53,12 +52,10 @@ void M(int? x, int? y) } } """); - } [Fact] - public async Task TestOnLeft_NotEquals() - { - await TestInRegularAndScriptAsync( + public Task TestOnLeft_NotEquals() + => TestInRegularAndScriptAsync( """ using System; @@ -81,12 +78,10 @@ void M(int? x, int? y) } } """); - } [Fact] - public async Task TestComplexExpression() - { - await TestInRegularAndScriptAsync( + public Task TestComplexExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -109,12 +104,10 @@ void M(int? x, int? y) } } """); - } [Fact] - public async Task TestParens1() - { - await TestInRegularAndScriptAsync( + public Task TestParens1() + => TestInRegularAndScriptAsync( """ using System; @@ -137,12 +130,10 @@ void M(int? x, int? y) } } """); - } [Fact] - public async Task TestFixAll1() - { - await TestInRegularAndScriptAsync( + public Task TestFixAll1() + => TestInRegularAndScriptAsync( """ using System; @@ -167,12 +158,10 @@ void M(int? x, int? y) } } """); - } [Fact] - public async Task TestFixAll2() - { - await TestInRegularAndScriptAsync( + public Task TestFixAll2() + => TestInRegularAndScriptAsync( """ using System; @@ -195,12 +184,10 @@ void M(int? x, int? y, int? z) } } """); - } [Fact] - public async Task TestFixAll3() - { - await TestInRegularAndScriptAsync( + public Task TestFixAll3() + => TestInRegularAndScriptAsync( """ using System; @@ -223,12 +210,10 @@ void M(int? x, int? y, int? z) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17028")] - public async Task TestInExpressionOfT() - { - await TestInRegularAndScriptAsync( + public Task TestInExpressionOfT() + => TestInRegularAndScriptAsync( """ using System; using System.Linq.Expressions; @@ -253,12 +238,10 @@ void M(int? x, int? y) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69087")] - public async Task TestNotWithTargetTyping1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithTargetTyping1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -270,12 +253,10 @@ void M(int? x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69087")] - public async Task TestWithNonTargetTyping1() - { - await TestInRegularAndScriptAsync( + public Task TestWithNonTargetTyping1() + => TestInRegularAndScriptAsync( """ using System; @@ -298,12 +279,10 @@ void M(int? x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69087")] - public async Task TestNotWithTargetTyping2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithTargetTyping2() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -314,12 +293,10 @@ class C public string InterpolatedText => $"{([||]Index.HasValue ? Index.Value : "???")}: rest of the text"; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69087")] - public async Task TestWithNonTargetTyping2() - { - await TestInRegularAndScriptAsync( + public Task TestWithNonTargetTyping2() + => TestInRegularAndScriptAsync( """ using System; @@ -340,5 +317,4 @@ class C public string InterpolatedText => $"{(Index ?? 0)}: rest of the text"; } """); - } } diff --git a/src/Analyzers/CSharp/Tests/UseCoalesceExpression/UseCoalesceExpressionForTernaryConditionalCheckTests.cs b/src/Analyzers/CSharp/Tests/UseCoalesceExpression/UseCoalesceExpressionForTernaryConditionalCheckTests.cs index d0411c53c22d4..e3e2e98154f75 100644 --- a/src/Analyzers/CSharp/Tests/UseCoalesceExpression/UseCoalesceExpressionForTernaryConditionalCheckTests.cs +++ b/src/Analyzers/CSharp/Tests/UseCoalesceExpression/UseCoalesceExpressionForTernaryConditionalCheckTests.cs @@ -28,9 +28,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider new UseCoalesceExpressionForTernaryConditionalCheckCodeFixProvider()); [Fact] - public async Task TestOnLeft_Equals() - { - await TestInRegularAndScript1Async( + public Task TestOnLeft_Equals() + => TestInRegularAndScript1Async( """ using System; @@ -53,12 +52,10 @@ void M(string x, string y) } } """); - } [Fact] - public async Task TestOnLeft_NotEquals() - { - await TestInRegularAndScript1Async( + public Task TestOnLeft_NotEquals() + => TestInRegularAndScript1Async( """ using System; @@ -81,12 +78,10 @@ void M(string x, string y) } } """); - } [Fact] - public async Task TestOnRight_Equals() - { - await TestInRegularAndScript1Async( + public Task TestOnRight_Equals() + => TestInRegularAndScript1Async( """ using System; @@ -109,12 +104,10 @@ void M(string x, string y) } } """); - } [Fact] - public async Task TestOnRight_NotEquals() - { - await TestInRegularAndScript1Async( + public Task TestOnRight_NotEquals() + => TestInRegularAndScript1Async( """ using System; @@ -137,12 +130,10 @@ void M(string x, string y) } } """); - } [Fact] - public async Task TestComplexExpression() - { - await TestInRegularAndScript1Async( + public Task TestComplexExpression() + => TestInRegularAndScript1Async( """ using System; @@ -165,12 +156,10 @@ void M(string x, string y) } } """); - } [Fact] - public async Task TestParens1() - { - await TestInRegularAndScript1Async( + public Task TestParens1() + => TestInRegularAndScript1Async( """ using System; @@ -193,12 +182,10 @@ void M(string x, string y) } } """); - } [Fact] - public async Task TestParens2() - { - await TestInRegularAndScript1Async( + public Task TestParens2() + => TestInRegularAndScript1Async( """ using System; @@ -221,12 +208,10 @@ void M(string x, string y) } } """); - } [Fact] - public async Task TestParens3() - { - await TestInRegularAndScript1Async( + public Task TestParens3() + => TestInRegularAndScript1Async( """ using System; @@ -249,12 +234,10 @@ void M(string x, string y) } } """); - } [Fact] - public async Task TestParens4() - { - await TestInRegularAndScript1Async( + public Task TestParens4() + => TestInRegularAndScript1Async( """ using System; @@ -277,12 +260,10 @@ void M(string x, string y) } } """); - } [Fact] - public async Task TestFixAll1() - { - await TestInRegularAndScript1Async( + public Task TestFixAll1() + => TestInRegularAndScript1Async( """ using System; @@ -307,12 +288,10 @@ void M(string x, string y) } } """); - } [Fact] - public async Task TestFixAll2() - { - await TestInRegularAndScript1Async( + public Task TestFixAll2() + => TestInRegularAndScript1Async( """ using System; @@ -335,12 +314,10 @@ void M(string x, string y, string z) } } """); - } [Fact] - public async Task TestFixAll3() - { - await TestInRegularAndScript1Async( + public Task TestFixAll3() + => TestInRegularAndScript1Async( """ using System; @@ -363,12 +340,10 @@ void M(string x, string y, string z) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16025")] - public async Task TestTrivia1() - { - await TestInRegularAndScript1Async( + public Task TestTrivia1() + => TestInRegularAndScript1Async( """ using System; @@ -395,12 +370,10 @@ public Program() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17028")] - public async Task TestInExpressionOfT() - { - await TestInRegularAndScript1Async( + public Task TestInExpressionOfT() + => TestInRegularAndScript1Async( """ using System; using System.Linq.Expressions; @@ -425,12 +398,10 @@ void Main(string s, string y) } } """); - } [Fact] - public async Task TestUnconstrainedTypeParameter() - { - await TestMissingInRegularAndScriptAsync( + public Task TestUnconstrainedTypeParameter() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -440,12 +411,10 @@ void Main(T t) } } """); - } [Fact] - public async Task TestStructConstrainedTypeParameter() - { - await TestMissingInRegularAndScriptAsync( + public Task TestStructConstrainedTypeParameter() + => TestMissingInRegularAndScriptAsync( """ class C where T : struct { @@ -455,12 +424,10 @@ void Main(T t) } } """); - } [Fact] - public async Task TestClassConstrainedTypeParameter() - { - await TestInRegularAndScript1Async( + public Task TestClassConstrainedTypeParameter() + => TestInRegularAndScript1Async( """ class C where T : class { @@ -479,12 +446,10 @@ void Main(T t) } } """); - } [Fact] - public async Task TestNotOnNullable() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOnNullable() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -494,12 +459,10 @@ void Main(int? t) } } """); - } [Fact] - public async Task TestOnArray() - { - await TestInRegularAndScript1Async( + public Task TestOnArray() + => TestInRegularAndScript1Async( """ class C { @@ -518,12 +481,10 @@ void Main(int[] t) } } """); - } [Fact] - public async Task TestOnInterface() - { - await TestInRegularAndScript1Async( + public Task TestOnInterface() + => TestInRegularAndScript1Async( """ class C { @@ -542,12 +503,10 @@ void Main(System.ICloneable t) } } """); - } [Fact] - public async Task TestOnDynamic() - { - await TestInRegularAndScript1Async( + public Task TestOnDynamic() + => TestInRegularAndScript1Async( """ class C { @@ -566,12 +525,10 @@ void Main(dynamic t) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38066")] - public async Task TestSemicolonPlacement() - { - await TestInRegularAndScript1Async( + public Task TestSemicolonPlacement() + => TestInRegularAndScript1Async( """ class C { @@ -592,12 +549,10 @@ void M(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38066")] - public async Task TestParenthesisPlacement() - { - await TestInRegularAndScript1Async( + public Task TestParenthesisPlacement() + => TestInRegularAndScript1Async( """ class C { @@ -618,12 +573,10 @@ void M(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38066")] - public async Task TestAnotherConditionalPlacement() - { - await TestInRegularAndScript1Async( + public Task TestAnotherConditionalPlacement() + => TestInRegularAndScript1Async( """ class C { @@ -648,12 +601,10 @@ void M(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53190")] - public async Task TestNotWithTargetTyping() - { - await TestMissingAsync( + public Task TestNotWithTargetTyping() + => TestMissingAsync( """ class Program { @@ -669,5 +620,4 @@ static void Main(string[] args) } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForArrayTests.cs b/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForArrayTests.cs index 49622fce27f7e..a7523d9dc6770 100644 --- a/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForArrayTests.cs +++ b/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForArrayTests.cs @@ -21,9 +21,8 @@ namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.UseCollectionExpress public sealed class UseCollectionExpressionForArrayTests { [Fact] - public async Task TestNotInCSharp11() - { - await new VerifyCS.Test + public Task TestNotInCSharp11() + => new VerifyCS.Test { TestCode = """ class C @@ -33,12 +32,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp11, }.RunAsync(); - } [Fact] - public async Task TestInCSharp12() - { - await new VerifyCS.Test + public Task TestInCSharp12() + => new VerifyCS.Test { TestCode = """ class C @@ -54,12 +51,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestSingleLine_TrailingComma() - { - await new VerifyCS.Test + public Task TestSingleLine_TrailingComma() + => new VerifyCS.Test { TestCode = """ class C @@ -75,12 +70,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestSingleLine_Trivia() - { - await new VerifyCS.Test + public Task TestSingleLine_Trivia() + => new VerifyCS.Test { TestCode = """ class C @@ -96,12 +89,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultiLine() - { - await new VerifyCS.Test + public Task TestMultiLine() + => new VerifyCS.Test { TestCode = """ class C @@ -121,12 +112,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultiLine_TrailingComma() - { - await new VerifyCS.Test + public Task TestMultiLine_TrailingComma() + => new VerifyCS.Test { TestCode = """ class C @@ -146,12 +135,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestEmpty1() - { - await new VerifyCS.Test + public Task TestEmpty1() + => new VerifyCS.Test { TestCode = """ class C @@ -167,12 +154,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestEmpty2() - { - await new VerifyCS.Test + public Task TestEmpty2() + => new VerifyCS.Test { TestCode = """ class C @@ -188,12 +173,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithIncompatibleExplicitArrays_Strict() - { - await new VerifyCS.Test + public Task TestNotWithIncompatibleExplicitArrays_Strict() + => new VerifyCS.Test { TestCode = """ class C @@ -207,12 +190,10 @@ class C dotnet_style_prefer_collection_expression=when_types_exactly_match """ }.RunAsync(); - } [Fact] - public async Task TestNotWithIncompatibleExplicitArrays() - { - await new VerifyCS.Test + public Task TestNotWithIncompatibleExplicitArrays() + => new VerifyCS.Test { TestCode = """ class C @@ -228,12 +209,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithCompatibleExplicitArrays1() - { - await new VerifyCS.Test + public Task TestWithCompatibleExplicitArrays1() + => new VerifyCS.Test { TestCode = """ class C @@ -249,12 +228,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithCompatibleExplicitArrays2() - { - await new VerifyCS.Test + public Task TestWithCompatibleExplicitArrays2() + => new VerifyCS.Test { TestCode = """ class C @@ -276,12 +253,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithCompatibleExplicitArrays_Empty() - { - await new VerifyCS.Test + public Task TestWithCompatibleExplicitArrays_Empty() + => new VerifyCS.Test { TestCode = """ class C @@ -297,12 +272,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithCompatibleExplicitArrays_TrailingComma() - { - await new VerifyCS.Test + public Task TestWithCompatibleExplicitArrays_TrailingComma() + => new VerifyCS.Test { TestCode = """ class C @@ -318,12 +291,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithExplicitArray_ExplicitSize() - { - await new VerifyCS.Test + public Task TestWithExplicitArray_ExplicitSize() + => new VerifyCS.Test { TestCode = """ class C @@ -339,12 +310,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithExplicitArray_MultiDimensionalArray_ExplicitSizes1() - { - await new VerifyCS.Test + public Task TestWithExplicitArray_MultiDimensionalArray_ExplicitSizes1() + => new VerifyCS.Test { TestCode = """ class C @@ -354,12 +323,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithExplicitArray_MultiDimensionalArray_ExplicitSizes2() - { - await new VerifyCS.Test + public Task TestWithExplicitArray_MultiDimensionalArray_ExplicitSizes2() + => new VerifyCS.Test { TestCode = """ class C @@ -369,12 +336,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithExplicitArray_MultiDimensionalArray_ImplicitSizes1() - { - await new VerifyCS.Test + public Task TestWithExplicitArray_MultiDimensionalArray_ImplicitSizes1() + => new VerifyCS.Test { TestCode = """ class C @@ -384,12 +349,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithIncompatibleImplicitArrays() - { - await new VerifyCS.Test + public Task TestNotWithIncompatibleImplicitArrays() + => new VerifyCS.Test { TestCode = """ class C @@ -405,12 +368,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithIncompatibleImplicitArrays_Strict() - { - await new VerifyCS.Test + public Task TestNotWithIncompatibleImplicitArrays_Strict() + => new VerifyCS.Test { TestCode = """ class C @@ -424,12 +385,10 @@ class C dotnet_style_prefer_collection_expression=when_types_exactly_match """ }.RunAsync(); - } [Fact] - public async Task TestWithCompatibleImplicitArrays1() - { - await new VerifyCS.Test + public Task TestWithCompatibleImplicitArrays1() + => new VerifyCS.Test { TestCode = """ class C @@ -445,12 +404,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithCompatibleImplicitArrays2() - { - await new VerifyCS.Test + public Task TestWithCompatibleImplicitArrays2() + => new VerifyCS.Test { TestCode = """ class C @@ -472,12 +429,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMissingOnEmptyImplicitArray() - { - await new VerifyCS.Test + public Task TestMissingOnEmptyImplicitArray() + => new VerifyCS.Test { TestCode = """ class C @@ -487,12 +442,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithCompatibleImplicitArrays_TrailingComma() - { - await new VerifyCS.Test + public Task TestWithCompatibleImplicitArrays_TrailingComma() + => new VerifyCS.Test { TestCode = """ class C @@ -508,13 +461,11 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Theory, CombinatorialData] - public async Task TestNotWithVar_ExplicitArrayType( + public Task TestNotWithVar_ExplicitArrayType( [CombinatorialValues(["var", "object", "dynamic"])] string type) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = $$""" class C @@ -527,13 +478,11 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Theory, CombinatorialData] - public async Task TestNotWithVar_ExplicitArrayType2( + public Task TestNotWithVar_ExplicitArrayType2( [CombinatorialValues(["var", "object", "dynamic"])] string type) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = $$""" class C @@ -546,13 +495,11 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Theory, CombinatorialData] - public async Task TestNotWithVar_ImplicitArrayType( + public Task TestNotWithVar_ImplicitArrayType( [CombinatorialValues(["var", "object", "dynamic"])] string type) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = $$""" class C @@ -565,13 +512,11 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Theory, CombinatorialData] - public async Task TestNotWithVar_ImplicitArrayType2( + public Task TestNotWithVar_ImplicitArrayType2( [CombinatorialValues(["var", "object", "dynamic"])] string type) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = $$""" class C @@ -584,12 +529,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithExtension() - { - await new VerifyCS.Test + public Task TestNotWithExtension() + => new VerifyCS.Test { TestCode = """ using System; @@ -605,12 +548,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestTargetTypedToField() - { - await new VerifyCS.Test + public Task TestTargetTypedToField() + => new VerifyCS.Test { TestCode = """ class C @@ -626,12 +567,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestTargetTypedToProperty() - { - await new VerifyCS.Test + public Task TestTargetTypedToProperty() + => new VerifyCS.Test { TestCode = """ class C @@ -647,12 +586,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestTargetTypedToComplexCast() - { - await new VerifyCS.Test + public Task TestTargetTypedToComplexCast() + => new VerifyCS.Test { TestCode = """ class C @@ -674,12 +611,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestTargetTypedToComplexCast2() - { - await new VerifyCS.Test + public Task TestTargetTypedToComplexCast2() + => new VerifyCS.Test { TestCode = """ class C @@ -692,12 +627,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithNaturalType1() - { - await new VerifyCS.Test + public Task TestNotWithNaturalType1() + => new VerifyCS.Test { TestCode = """ class C @@ -710,12 +643,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithNaturalType2() - { - await new VerifyCS.Test + public Task TestNotWithNaturalType2() + => new VerifyCS.Test { TestCode = """ class C @@ -728,12 +659,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotTargetTypedWithIdentifierCast() - { - await new VerifyCS.Test + public Task TestNotTargetTypedWithIdentifierCast() + => new VerifyCS.Test { TestCode = """ using IntArray = int[]; @@ -748,12 +677,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestTargetTypedInConditional1() - { - await new VerifyCS.Test + public Task TestTargetTypedInConditional1() + => new VerifyCS.Test { TestCode = """ class C @@ -775,12 +702,10 @@ void M(int[] x) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestTargetTypedInConditional2() - { - await new VerifyCS.Test + public Task TestTargetTypedInConditional2() + => new VerifyCS.Test { TestCode = """ class C @@ -802,12 +727,10 @@ void M(int[] x) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestTargetTypedInConditional3() - { - await new VerifyCS.Test + public Task TestTargetTypedInConditional3() + => new VerifyCS.Test { TestCode = """ class C @@ -829,12 +752,10 @@ void M(int[] x) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotTargetTypedInConditional4() - { - await new VerifyCS.Test + public Task TestNotTargetTypedInConditional4() + => new VerifyCS.Test { TestCode = """ class C @@ -847,12 +768,10 @@ void M(int[] x) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestTargetTypedInSwitchExpressionArm1() - { - await new VerifyCS.Test + public Task TestTargetTypedInSwitchExpressionArm1() + => new VerifyCS.Test { TestCode = """ class C @@ -874,12 +793,10 @@ void M(int[] x, bool b) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestTargetTypedInSwitchExpressionArm2() - { - await new VerifyCS.Test + public Task TestTargetTypedInSwitchExpressionArm2() + => new VerifyCS.Test { TestCode = """ class C @@ -901,12 +818,10 @@ void M(int[] x, bool b) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestTargetTypedInSwitchExpressionArm3() - { - await new VerifyCS.Test + public Task TestTargetTypedInSwitchExpressionArm3() + => new VerifyCS.Test { TestCode = """ class C @@ -928,12 +843,10 @@ void M(int[] x, bool b) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotTargetTypedInSwitchExpressionArm4() - { - await new VerifyCS.Test + public Task TestNotTargetTypedInSwitchExpressionArm4() + => new VerifyCS.Test { TestCode = """ class C @@ -946,12 +859,10 @@ void M(int[] x, bool b) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotTargetTypedInitializer1() - { - await new VerifyCS.Test + public Task TestNotTargetTypedInitializer1() + => new VerifyCS.Test { TestCode = """ class C @@ -964,12 +875,10 @@ void M(int[] x, bool b) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestTargetTypedInitializer2() - { - await new VerifyCS.Test + public Task TestTargetTypedInitializer2() + => new VerifyCS.Test { TestCode = """ class C @@ -991,12 +900,10 @@ void M(int[] x, bool b) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestTargetTypedInitializer3() - { - await new VerifyCS.Test + public Task TestTargetTypedInitializer3() + => new VerifyCS.Test { TestCode = """ class C @@ -1018,12 +925,10 @@ void M(int[] x, bool b) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestTargetTypedInitializer4() - { - await new VerifyCS.Test + public Task TestTargetTypedInitializer4() + => new VerifyCS.Test { TestCode = """ class C @@ -1036,12 +941,10 @@ void M(int[] x, bool b) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestTargetTypedInitializer5() - { - await new VerifyCS.Test + public Task TestTargetTypedInitializer5() + => new VerifyCS.Test { TestCode = """ class C @@ -1074,12 +977,10 @@ void M(int[] x, bool b) LanguageVersion = LanguageVersion.CSharp12, CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, }.RunAsync(); - } [Fact] - public async Task TestTargetTypedArgument1() - { - await new VerifyCS.Test + public Task TestTargetTypedArgument1() + => new VerifyCS.Test { TestCode = """ class C @@ -1105,12 +1006,10 @@ void X(int[] x) { } """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72337")] - public async Task TestTargetTypedArgumentPrimaryConstructor1() - { - await new VerifyCS.Test + public Task TestTargetTypedArgumentPrimaryConstructor1() + => new VerifyCS.Test { TestCode = """ class C(int[] x); @@ -1122,12 +1021,10 @@ class C2() : C([1, 2, 3]); """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotTargetTypedArgument2() - { - await new VerifyCS.Test + public Task TestNotTargetTypedArgument2() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -1144,12 +1041,10 @@ void X(List x) { } """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestTargetTypedAttributeArgument1() - { - await new VerifyCS.Test + public Task TestTargetTypedAttributeArgument1() + => new VerifyCS.Test { TestCode = """ [X([|[|new|] int[]|] { 1, 2, 3 })] @@ -1175,12 +1070,10 @@ public XAttribute(int[] values) { } """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNonTargetTypedAttributeArgument1() - { - await new VerifyCS.Test + public Task TestNonTargetTypedAttributeArgument1() + => new VerifyCS.Test { TestCode = """ [X(new string[] { })] @@ -1195,12 +1088,10 @@ public XAttribute(object values) { } """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNonTargetTypedAttributeArgument2() - { - await new VerifyCS.Test + public Task TestNonTargetTypedAttributeArgument2() + => new VerifyCS.Test { TestCode = """ [X(new string[] { "" })] @@ -1215,12 +1106,10 @@ public XAttribute(object values) { } """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNonTargetTypedAttributeArgument3() - { - await new VerifyCS.Test + public Task TestNonTargetTypedAttributeArgument3() + => new VerifyCS.Test { TestCode = """ [X(new[] { "" })] @@ -1235,12 +1124,10 @@ public XAttribute(object values) { } """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestTargetTypedReturn1() - { - await new VerifyCS.Test + public Task TestTargetTypedReturn1() + => new VerifyCS.Test { TestCode = """ class C @@ -1262,12 +1149,10 @@ int[] M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestAssignment1() - { - await new VerifyCS.Test + public Task TestAssignment1() + => new VerifyCS.Test { TestCode = """ class C @@ -1289,12 +1174,10 @@ void M(int[] x) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestAssignment2() - { - await new VerifyCS.Test + public Task TestAssignment2() + => new VerifyCS.Test { TestCode = """ class C @@ -1326,12 +1209,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestCoalesce1() - { - await new VerifyCS.Test + public Task TestCoalesce1() + => new VerifyCS.Test { TestCode = """ class C @@ -1353,12 +1234,10 @@ void M(int[] x) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithLinqLet() - { - await new VerifyCS.Test + public Task TestNotWithLinqLet() + => new VerifyCS.Test { TestCode = """ using System; @@ -1376,12 +1255,10 @@ void M(int[] x) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting1() - { - await new VerifyCS.Test + public Task TestInitializerFormatting1() + => new VerifyCS.Test { TestCode = """ class C @@ -1397,12 +1274,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting2() - { - await new VerifyCS.Test + public Task TestInitializerFormatting2() + => new VerifyCS.Test { TestCode = """ class C @@ -1420,12 +1295,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting3() - { - await new VerifyCS.Test + public Task TestInitializerFormatting3() + => new VerifyCS.Test { TestCode = """ class C @@ -1445,12 +1318,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting4() - { - await new VerifyCS.Test + public Task TestInitializerFormatting4() + => new VerifyCS.Test { TestCode = """ class C @@ -1472,12 +1343,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting5() - { - await new VerifyCS.Test + public Task TestInitializerFormatting5() + => new VerifyCS.Test { TestCode = """ class C @@ -1495,12 +1364,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting6() - { - await new VerifyCS.Test + public Task TestInitializerFormatting6() + => new VerifyCS.Test { TestCode = """ class C @@ -1520,12 +1387,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting7() - { - await new VerifyCS.Test + public Task TestInitializerFormatting7() + => new VerifyCS.Test { TestCode = """ class C @@ -1547,12 +1412,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting8() - { - await new VerifyCS.Test + public Task TestInitializerFormatting8() + => new VerifyCS.Test { TestCode = """ class C @@ -1576,12 +1439,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting1_Explicit() - { - await new VerifyCS.Test + public Task TestInitializerFormatting1_Explicit() + => new VerifyCS.Test { TestCode = """ class C @@ -1597,12 +1458,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting2_Explicit() - { - await new VerifyCS.Test + public Task TestInitializerFormatting2_Explicit() + => new VerifyCS.Test { TestCode = """ class C @@ -1620,12 +1479,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting3_Explicit() - { - await new VerifyCS.Test + public Task TestInitializerFormatting3_Explicit() + => new VerifyCS.Test { TestCode = """ class C @@ -1645,12 +1502,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting4_Explicit() - { - await new VerifyCS.Test + public Task TestInitializerFormatting4_Explicit() + => new VerifyCS.Test { TestCode = """ class C @@ -1672,12 +1527,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting5_Explicit() - { - await new VerifyCS.Test + public Task TestInitializerFormatting5_Explicit() + => new VerifyCS.Test { TestCode = """ class C @@ -1700,12 +1553,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting6_Explicit() - { - await new VerifyCS.Test + public Task TestInitializerFormatting6_Explicit() + => new VerifyCS.Test { TestCode = """ class C @@ -1727,12 +1578,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting7_Explicit() - { - await new VerifyCS.Test + public Task TestInitializerFormatting7_Explicit() + => new VerifyCS.Test { TestCode = """ class C @@ -1755,12 +1604,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting8_Explicit() - { - await new VerifyCS.Test + public Task TestInitializerFormatting8_Explicit() + => new VerifyCS.Test { TestCode = """ class C @@ -1782,12 +1629,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting9_Explicit() - { - await new VerifyCS.Test + public Task TestInitializerFormatting9_Explicit() + => new VerifyCS.Test { TestCode = """ class C @@ -1807,12 +1652,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting10_Explicit() - { - await new VerifyCS.Test + public Task TestInitializerFormatting10_Explicit() + => new VerifyCS.Test { TestCode = """ class C @@ -1837,12 +1680,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting1_Implicit() - { - await new VerifyCS.Test + public Task TestInitializerFormatting1_Implicit() + => new VerifyCS.Test { TestCode = """ class C @@ -1858,12 +1699,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting2_Implicit() - { - await new VerifyCS.Test + public Task TestInitializerFormatting2_Implicit() + => new VerifyCS.Test { TestCode = """ class C @@ -1881,12 +1720,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting3_Implicit() - { - await new VerifyCS.Test + public Task TestInitializerFormatting3_Implicit() + => new VerifyCS.Test { TestCode = """ class C @@ -1906,12 +1743,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting4_Implicit() - { - await new VerifyCS.Test + public Task TestInitializerFormatting4_Implicit() + => new VerifyCS.Test { TestCode = """ class C @@ -1933,12 +1768,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting5_Implicit() - { - await new VerifyCS.Test + public Task TestInitializerFormatting5_Implicit() + => new VerifyCS.Test { TestCode = """ class C @@ -1961,12 +1794,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting6_Implicit() - { - await new VerifyCS.Test + public Task TestInitializerFormatting6_Implicit() + => new VerifyCS.Test { TestCode = """ class C @@ -1988,12 +1819,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting7_Implicit() - { - await new VerifyCS.Test + public Task TestInitializerFormatting7_Implicit() + => new VerifyCS.Test { TestCode = """ class C @@ -2016,12 +1845,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting8_Implicit() - { - await new VerifyCS.Test + public Task TestInitializerFormatting8_Implicit() + => new VerifyCS.Test { TestCode = """ class C @@ -2043,12 +1870,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting9_Implicit() - { - await new VerifyCS.Test + public Task TestInitializerFormatting9_Implicit() + => new VerifyCS.Test { TestCode = """ class C @@ -2068,12 +1893,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInitializerFormatting10_Implicit() - { - await new VerifyCS.Test + public Task TestInitializerFormatting10_Implicit() + => new VerifyCS.Test { TestCode = """ class C @@ -2098,12 +1921,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoMultiLineEvenWhenLongIfAllElementsAlreadyPresent() - { - await new VerifyCS.Test + public Task TestNoMultiLineEvenWhenLongIfAllElementsAlreadyPresent() + => new VerifyCS.Test { TestCode = """ using System; @@ -2149,12 +1970,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_MultiLine1() - { - await new VerifyCS.Test + public Task TestNoInitializer_MultiLine1() + => new VerifyCS.Test { TestCode = """ using System; @@ -2186,12 +2005,10 @@ void M(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_MultiLine2() - { - await new VerifyCS.Test + public Task TestNoInitializer_MultiLine2() + => new VerifyCS.Test { TestCode = """ using System; @@ -2227,12 +2044,10 @@ void M(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_ZeroSize() - { - await new VerifyCS.Test + public Task TestNoInitializer_ZeroSize() + => new VerifyCS.Test { TestCode = """ using System; @@ -2258,12 +2073,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_NotEnoughFollowingStatements() - { - await new VerifyCS.Test + public Task TestNoInitializer_NotEnoughFollowingStatements() + => new VerifyCS.Test { TestCode = """ using System; @@ -2278,12 +2091,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_WrongFollowingStatement() - { - await new VerifyCS.Test + public Task TestNoInitializer_WrongFollowingStatement() + => new VerifyCS.Test { TestCode = """ using System; @@ -2299,12 +2110,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_NotLocalStatementInitializer() - { - await new VerifyCS.Test + public Task TestNoInitializer_NotLocalStatementInitializer() + => new VerifyCS.Test { TestCode = """ using System; @@ -2322,12 +2131,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_ExpressionStatementNotAssignment() - { - await new VerifyCS.Test + public Task TestNoInitializer_ExpressionStatementNotAssignment() + => new VerifyCS.Test { TestCode = """ using System; @@ -2343,12 +2150,10 @@ void M(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_AssignmentNotElementAccess() - { - await new VerifyCS.Test + public Task TestNoInitializer_AssignmentNotElementAccess() + => new VerifyCS.Test { TestCode = """ using System; @@ -2364,12 +2169,10 @@ void M(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_ElementAccessNotToIdentifier() - { - await new VerifyCS.Test + public Task TestNoInitializer_ElementAccessNotToIdentifier() + => new VerifyCS.Test { TestCode = """ using System; @@ -2387,12 +2190,10 @@ void M(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_IdentifierNotEqualToVariableName() - { - await new VerifyCS.Test + public Task TestNoInitializer_IdentifierNotEqualToVariableName() + => new VerifyCS.Test { TestCode = """ using System; @@ -2410,12 +2211,10 @@ void M(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_ArgumentNotConstant() - { - await new VerifyCS.Test + public Task TestNoInitializer_ArgumentNotConstant() + => new VerifyCS.Test { TestCode = """ using System; @@ -2431,12 +2230,10 @@ void M(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_ConstantArgumentNotCorrect1() - { - await new VerifyCS.Test + public Task TestNoInitializer_ConstantArgumentNotCorrect1() + => new VerifyCS.Test { TestCode = """ using System; @@ -2452,12 +2249,10 @@ void M(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_ConstantArgumentNotCorrect2() - { - await new VerifyCS.Test + public Task TestNoInitializer_ConstantArgumentNotCorrect2() + => new VerifyCS.Test { TestCode = """ using System; @@ -2474,12 +2269,10 @@ void M(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_OneElement() - { - await new VerifyCS.Test + public Task TestNoInitializer_OneElement() + => new VerifyCS.Test { TestCode = """ using System; @@ -2506,12 +2299,10 @@ void M(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_OneElement_MultipleFollowingStatements() - { - await new VerifyCS.Test + public Task TestNoInitializer_OneElement_MultipleFollowingStatements() + => new VerifyCS.Test { TestCode = """ using System; @@ -2540,12 +2331,10 @@ void M(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_TwoElement2() - { - await new VerifyCS.Test + public Task TestNoInitializer_TwoElement2() + => new VerifyCS.Test { TestCode = """ using System; @@ -2573,12 +2362,10 @@ void M(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_TwoElement2_Constant() - { - await new VerifyCS.Test + public Task TestNoInitializer_TwoElement2_Constant() + => new VerifyCS.Test { TestCode = """ using System; @@ -2608,12 +2395,10 @@ void M(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_TwoElement2_SecondWrongIndex() - { - await new VerifyCS.Test + public Task TestNoInitializer_TwoElement2_SecondWrongIndex() + => new VerifyCS.Test { TestCode = """ using System; @@ -2630,12 +2415,10 @@ void M(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_TwoElement2_SecondNonConstant() - { - await new VerifyCS.Test + public Task TestNoInitializer_TwoElement2_SecondNonConstant() + => new VerifyCS.Test { TestCode = """ using System; @@ -2653,12 +2436,10 @@ void M(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_TwoElement2_SecondWrongDestination() - { - await new VerifyCS.Test + public Task TestNoInitializer_TwoElement2_SecondWrongDestination() + => new VerifyCS.Test { TestCode = """ using System; @@ -2678,12 +2459,10 @@ void M(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_TwoElement_TwoDimensional1() - { - await new VerifyCS.Test + public Task TestNoInitializer_TwoElement_TwoDimensional1() + => new VerifyCS.Test { TestCode = """ using System; @@ -2711,12 +2490,10 @@ void M(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_TwoElement_TwoDimensional2() - { - await new VerifyCS.Test + public Task TestNoInitializer_TwoElement_TwoDimensional2() + => new VerifyCS.Test { TestCode = """ using System; @@ -2744,12 +2521,10 @@ void M(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_TwoElement_TwoDimensional2_Trivia1() - { - await new VerifyCS.Test + public Task TestNoInitializer_TwoElement_TwoDimensional2_Trivia1() + => new VerifyCS.Test { TestCode = """ using System; @@ -2784,12 +2559,10 @@ void M(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_TwoElement_TwoDimensional2_Trivia2() - { - await new VerifyCS.Test + public Task TestNoInitializer_TwoElement_TwoDimensional2_Trivia2() + => new VerifyCS.Test { TestCode = """ using System; @@ -2829,12 +2602,10 @@ void M(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestGlobalStatement1() - { - await new VerifyCS.Test + public Task TestGlobalStatement1() + => new VerifyCS.Test { TestCode = """ int[] i = [|{|] 1, 2, 3 }; @@ -2848,12 +2619,10 @@ public async Task TestGlobalStatement1() OutputKind = OutputKind.ConsoleApplication, }, }.RunAsync(); - } [Fact] - public async Task TestGlobalStatement2() - { - await new VerifyCS.Test + public Task TestGlobalStatement2() + => new VerifyCS.Test { TestCode = """ int[] i = @@ -2877,14 +2646,12 @@ public async Task TestGlobalStatement2() OutputKind = OutputKind.ConsoleApplication, }, }.RunAsync(); - } [Theory] [InlineData("\n")] [InlineData("\r\n")] - public async Task TestWithDifferentNewLines(string endOfLine) - { - await new VerifyCS.Test + public Task TestWithDifferentNewLines(string endOfLine) + => new VerifyCS.Test { TestCode = """ int[] i = @@ -2908,7 +2675,6 @@ public async Task TestWithDifferentNewLines(string endOfLine) OutputKind = OutputKind.ConsoleApplication, }, }.RunAsync(); - } public static readonly IEnumerable EmptyOrConstantsOnly = new object[][] { @@ -2919,9 +2685,8 @@ public async Task TestWithDifferentNewLines(string endOfLine) }; [Theory, MemberData(nameof(EmptyOrConstantsOnly))] - public async Task TestForSpanField(string expression, string expected) - { - await new VerifyCS.Test + public Task TestForSpanField(string expression, string expected) + => new VerifyCS.Test { TestCode = $$""" using System; @@ -2950,12 +2715,10 @@ public C() { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestForSpanField2() - { - await new VerifyCS.Test + public Task TestForSpanField2() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -2973,12 +2736,10 @@ public C() { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(EmptyOrConstantsOnly))] - public async Task TestForSpanProperty1(string expression, string expected) - { - await new VerifyCS.Test + public Task TestForSpanProperty1(string expression, string expected) + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3003,12 +2764,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(EmptyOrConstantsOnly))] - public async Task TestForSpanProperty2(string expression, string expected) - { - await new VerifyCS.Test + public Task TestForSpanProperty2(string expression, string expected) + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3033,12 +2792,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(EmptyOrConstantsOnly))] - public async Task TestForSpanProperty3(string expression, string expected) - { - await new VerifyCS.Test + public Task TestForSpanProperty3(string expression, string expected) + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3063,12 +2820,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestForSpanProperty4() - { - await new VerifyCS.Test + public Task TestForSpanProperty4() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3084,12 +2839,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(EmptyOrConstantsOnly))] - public async Task TestForMethodReturn(string expression, string expected) - { - await new VerifyCS.Test + public Task TestForMethodReturn(string expression, string expected) + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3114,12 +2867,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestForSpanMethodReturn2() - { - await new VerifyCS.Test + public Task TestForSpanMethodReturn2() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3135,12 +2886,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(EmptyOrConstantsOnly))] - public async Task TestForMethodLocal1(string expression, string expected) - { - await new VerifyCS.Test + public Task TestForMethodLocal1(string expression, string expected) + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3171,12 +2920,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(EmptyOrConstantsOnly))] - public async Task TestForArgument(string expression, string expected) - { - await new VerifyCS.Test + public Task TestForArgument(string expression, string expected) + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3211,12 +2958,10 @@ void X(ReadOnlySpan span) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan1() - { - await new VerifyCS.Test + public Task TestLocalSpan1() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3247,12 +2992,10 @@ void M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan2() - { - await new VerifyCS.Test + public Task TestLocalSpan2() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3285,12 +3028,10 @@ void M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan3() - { - await new VerifyCS.Test + public Task TestLocalSpan3() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3329,12 +3070,10 @@ ReadOnlySpan M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan4() - { - await new VerifyCS.Test + public Task TestLocalSpan4() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3367,12 +3106,10 @@ void M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan5() - { - await new VerifyCS.Test + public Task TestLocalSpan5() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3409,12 +3146,10 @@ void X(ReadOnlySpan span) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan6() - { - await new VerifyCS.Test + public Task TestLocalSpan6() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3451,12 +3186,10 @@ ReadOnlySpan M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan7() - { - await new VerifyCS.Test + public Task TestLocalSpan7() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3489,12 +3222,10 @@ void M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan7_A() - { - await new VerifyCS.Test + public Task TestLocalSpan7_A() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3527,12 +3258,10 @@ string M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan8() - { - await new VerifyCS.Test + public Task TestLocalSpan8() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3569,12 +3298,10 @@ ReadOnlySpan M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan9() - { - await new VerifyCS.Test + public Task TestLocalSpan9() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3611,12 +3338,10 @@ ReadOnlySpan M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan9_A() - { - await new VerifyCS.Test + public Task TestLocalSpan9_A() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3649,12 +3374,10 @@ int M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan10() - { - await new VerifyCS.Test + public Task TestLocalSpan10() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3687,12 +3410,10 @@ int M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan11() - { - await new VerifyCS.Test + public Task TestLocalSpan11() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3725,12 +3446,10 @@ int M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan12() - { - await new VerifyCS.Test + public Task TestLocalSpan12() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3749,12 +3468,10 @@ ReadOnlySpan M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan13() - { - await new VerifyCS.Test + public Task TestLocalSpan13() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3772,12 +3489,10 @@ ReadOnlySpan M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan13_A() - { - await new VerifyCS.Test + public Task TestLocalSpan13_A() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3793,12 +3508,10 @@ ReadOnlySpan M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan14() - { - await new VerifyCS.Test + public Task TestLocalSpan14() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3818,12 +3531,10 @@ ReadOnlySpan M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan14_A() - { - await new VerifyCS.Test + public Task TestLocalSpan14_A() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3841,12 +3552,10 @@ ReadOnlySpan M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan15() - { - await new VerifyCS.Test + public Task TestLocalSpan15() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3866,12 +3575,10 @@ ReadOnlySpan M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan15_A() - { - await new VerifyCS.Test + public Task TestLocalSpan15_A() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3889,12 +3596,10 @@ ReadOnlySpan M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan16() - { - await new VerifyCS.Test + public Task TestLocalSpan16() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3913,12 +3618,10 @@ ReadOnlySpan M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan17() - { - await new VerifyCS.Test + public Task TestLocalSpan17() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3937,12 +3640,10 @@ ReadOnlySpan M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan18() - { - await new VerifyCS.Test + public Task TestLocalSpan18() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3962,12 +3663,10 @@ ReadOnlySpan M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan19() - { - await new VerifyCS.Test + public Task TestLocalSpan19() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -3987,12 +3686,10 @@ ReadOnlySpan M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan20() - { - await new VerifyCS.Test + public Task TestLocalSpan20() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -4014,12 +3711,10 @@ ReadOnlySpan M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan21() - { - await new VerifyCS.Test + public Task TestLocalSpan21() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -4041,12 +3736,10 @@ ReadOnlySpan M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan21_A() - { - await new VerifyCS.Test + public Task TestLocalSpan21_A() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -4068,12 +3761,10 @@ ReadOnlySpan M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan22() - { - await new VerifyCS.Test + public Task TestLocalSpan22() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -4112,12 +3803,10 @@ ReadOnlySpan M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan23() - { - await new VerifyCS.Test + public Task TestLocalSpan23() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -4154,12 +3843,10 @@ void M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestLocalSpan24() - { - await new VerifyCS.Test + public Task TestLocalSpan24() + => new VerifyCS.Test { TestCode = $$""" using System; @@ -4198,12 +3885,10 @@ ReadOnlySpan M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestFixAllConditionalExpression1() - { - await new VerifyCS.Test + public Task TestFixAllConditionalExpression1() + => new VerifyCS.Test { TestCode = $$""" class C @@ -4235,12 +3920,10 @@ void M(bool b) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestFixAllConditionalExpression2() - { - await new VerifyCS.Test + public Task TestFixAllConditionalExpression2() + => new VerifyCS.Test { TestCode = $$""" class C @@ -4272,12 +3955,10 @@ void M(bool b) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestSelfReference() - { - await new VerifyCS.Test + public Task TestSelfReference() + => new VerifyCS.Test { TestCode = """ using System; @@ -4293,12 +3974,10 @@ void M(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71012")] - public async Task TestInLambda() - { - await new VerifyCS.Test + public Task TestInLambda() + => new VerifyCS.Test { TestCode = """ @@ -4330,12 +4009,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71012")] - public async Task TestNotInLambda1() - { - await new VerifyCS.Test + public Task TestNotInLambda1() + => new VerifyCS.Test { TestCode = """ @@ -4353,12 +4030,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71012")] - public async Task TestNotInExpressionTree() - { - await new VerifyCS.Test + public Task TestNotInExpressionTree() + => new VerifyCS.Test { TestCode = """ @@ -4376,12 +4051,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70998")] - public async Task ForMismatchedTupleNames1() - { - await new VerifyCS.Test + public Task ForMismatchedTupleNames1() + => new VerifyCS.Test { TestCode = """ using System; @@ -4408,12 +4081,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70998")] - public async Task ForMismatchedTupleNames2() - { - await new VerifyCS.Test + public Task ForMismatchedTupleNames2() + => new VerifyCS.Test { TestCode = """ using System; @@ -4434,12 +4105,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70816")] - public async Task NotWithInvalidNumericInference() - { - await new VerifyCS.Test + public Task NotWithInvalidNumericInference() + => new VerifyCS.Test { TestCode = """ using System; @@ -4456,12 +4125,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestFixAllImplicitArray1() - { - await new VerifyCS.Test + public Task TestFixAllImplicitArray1() + => new VerifyCS.Test { TestCode = $$""" class C @@ -4496,12 +4163,10 @@ void M(bool b) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70996")] - public async Task TestInterfaceOn() - { - await new VerifyCS.Test + public Task TestInterfaceOn() + => new VerifyCS.Test { TestCode = """ @@ -4533,12 +4198,10 @@ IEnumerable M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70996")] - public async Task TestInterfaceOn_ReadWriteDestination() - { - await new VerifyCS.Test + public Task TestInterfaceOn_ReadWriteDestination() + => new VerifyCS.Test { TestCode = """ @@ -4570,12 +4233,10 @@ IList M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70996")] - public async Task TestInterfaceOff() - { - await new VerifyCS.Test + public Task TestInterfaceOff() + => new VerifyCS.Test { TestCode = """ @@ -4597,13 +4258,11 @@ IEnumerable M() dotnet_style_prefer_collection_expression=when_types_exactly_match """ }.RunAsync(); - } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/71522")] - public async Task TestTargetTypedConditional1( + public Task TestTargetTypedConditional1( [CombinatorialValues("", "#nullable enable")] string nullable) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = $$""" {{nullable}} @@ -4639,13 +4298,11 @@ void M(string[] args) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/71522")] - public async Task TestTargetTypedConditional2( + public Task TestTargetTypedConditional2( [CombinatorialValues("", "#nullable enable")] string nullable) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = $$""" {{nullable}} @@ -4674,13 +4331,11 @@ static void M(string[] args) { } LanguageVersion = LanguageVersion.CSharp12, TestState = { OutputKind = OutputKind.ConsoleApplication } }.RunAsync(); - } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/71522")] - public async Task TestTargetTypedConditional3( + public Task TestTargetTypedConditional3( [CombinatorialValues("", "#nullable enable")] string nullable) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = $$""" {{nullable}} @@ -4730,12 +4385,10 @@ static void M(string[] args) { } LanguageVersion = LanguageVersion.CSharp12, TestState = { OutputKind = OutputKind.ConsoleApplication } }.RunAsync(); - } [Fact] - public async Task TestNullableArrays1() - { - await new VerifyCS.Test + public Task TestNullableArrays1() + => new VerifyCS.Test { TestCode = """ #nullable disable @@ -4801,12 +4454,10 @@ public static void GetActiveStatementDebugInfosCSharp( """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultiDimensionalArray1() - { - await new VerifyCS.Test + public Task TestMultiDimensionalArray1() + => new VerifyCS.Test { TestCode = """ @@ -4840,12 +4491,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultiDimensionalArray1_Strict() - { - await new VerifyCS.Test + public Task TestMultiDimensionalArray1_Strict() + => new VerifyCS.Test { TestCode = """ @@ -4868,12 +4517,10 @@ class C dotnet_style_prefer_collection_expression=when_types_exactly_match """ }.RunAsync(); - } [Fact] - public async Task TestMultiDimensionalArray2() - { - await new VerifyCS.Test + public Task TestMultiDimensionalArray2() + => new VerifyCS.Test { TestCode = """ @@ -4922,12 +4569,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultiDimensionalArray2_Strict() - { - await new VerifyCS.Test + public Task TestMultiDimensionalArray2_Strict() + => new VerifyCS.Test { TestCode = """ @@ -4950,12 +4595,10 @@ class C dotnet_style_prefer_collection_expression=when_types_exactly_match """ }.RunAsync(); - } [Fact] - public async Task TestMultiDimensionalArray3() - { - await new VerifyCS.Test + public Task TestMultiDimensionalArray3() + => new VerifyCS.Test { TestCode = """ @@ -4989,12 +4632,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultiDimensionalArray3_Strict() - { - await new VerifyCS.Test + public Task TestMultiDimensionalArray3_Strict() + => new VerifyCS.Test { TestCode = """ @@ -5017,12 +4658,10 @@ class C dotnet_style_prefer_collection_expression=when_types_exactly_match """ }.RunAsync(); - } [Fact] - public async Task TestMultiDimensionalArray4() - { - await new VerifyCS.Test + public Task TestMultiDimensionalArray4() + => new VerifyCS.Test { TestCode = """ @@ -5056,12 +4695,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultiDimensionalArray4_Strict() - { - await new VerifyCS.Test + public Task TestMultiDimensionalArray4_Strict() + => new VerifyCS.Test { TestCode = """ @@ -5084,12 +4721,10 @@ class C dotnet_style_prefer_collection_expression=when_types_exactly_match """ }.RunAsync(); - } [Fact] - public async Task TestMultiDimensionalArray5() - { - await new VerifyCS.Test + public Task TestMultiDimensionalArray5() + => new VerifyCS.Test { TestCode = """ @@ -5138,12 +4773,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultiDimensionalArray6() - { - await new VerifyCS.Test + public Task TestMultiDimensionalArray6() + => new VerifyCS.Test { TestCode = """ @@ -5192,12 +4825,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestArray1() - { - await new VerifyCS.Test + public Task TestArray1() + => new VerifyCS.Test { TestCode = """ @@ -5215,12 +4846,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestArray2() - { - await new VerifyCS.Test + public Task TestArray2() + => new VerifyCS.Test { TestCode = """ @@ -5238,12 +4867,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72640")] - public async Task TestDynamic1() - { - await new VerifyCS.Test + public Task TestDynamic1() + => new VerifyCS.Test { TestCode = """ @@ -5261,12 +4888,10 @@ public void Test(dynamic obj) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72640")] - public async Task TestDynamic2() - { - await new VerifyCS.Test + public Task TestDynamic2() + => new VerifyCS.Test { TestCode = """ @@ -5284,12 +4909,10 @@ public void Test(dynamic obj) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72640")] - public async Task TestDynamic3() - { - await new VerifyCS.Test + public Task TestDynamic3() + => new VerifyCS.Test { TestCode = """ @@ -5307,12 +4930,10 @@ public void Test(dynamic obj) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72640")] - public async Task TestDynamic4() - { - await new VerifyCS.Test + public Task TestDynamic4() + => new VerifyCS.Test { TestCode = """ @@ -5330,12 +4951,10 @@ public void Test(dynamic obj) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72640")] - public async Task TestDynamic5() - { - await new VerifyCS.Test + public Task TestDynamic5() + => new VerifyCS.Test { TestCode = """ @@ -5353,12 +4972,10 @@ public void Test(dynamic obj) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72640")] - public async Task TestDynamic6() - { - await new VerifyCS.Test + public Task TestDynamic6() + => new VerifyCS.Test { TestCode = """ @@ -5380,12 +4997,10 @@ private void Test1(dynamic obj, params int?[][] args) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72640")] - public async Task TestDynamic7() - { - await new VerifyCS.Test + public Task TestDynamic7() + => new VerifyCS.Test { TestCode = """ @@ -5407,12 +5022,10 @@ private void Test1(dynamic obj, int?[] args) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73740")] - public async Task PreservesTrailingTriviaAfterInitializer1() - { - await new VerifyCS.Test + public Task PreservesTrailingTriviaAfterInitializer1() + => new VerifyCS.Test { TestCode = """ class C @@ -5431,12 +5044,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73740")] - public async Task PreservesTrailingTriviaAfterInitializer2() - { - await new VerifyCS.Test + public Task PreservesTrailingTriviaAfterInitializer2() + => new VerifyCS.Test { TestCode = """ class C @@ -5454,12 +5065,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73740")] - public async Task PreservesTrailingTriviaAfterInitializer3() - { - await new VerifyCS.Test + public Task PreservesTrailingTriviaAfterInitializer3() + => new VerifyCS.Test { TestCode = """ class C @@ -5495,12 +5104,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73740")] - public async Task PreservesTrailingTriviaAfterInitializer4() - { - await new VerifyCS.Test + public Task PreservesTrailingTriviaAfterInitializer4() + => new VerifyCS.Test { TestCode = """ class C @@ -5518,12 +5125,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73740")] - public async Task PreservesTrailingTriviaAfterInitializer5() - { - await new VerifyCS.Test + public Task PreservesTrailingTriviaAfterInitializer5() + => new VerifyCS.Test { TestCode = """ class C @@ -5541,12 +5146,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73740")] - public async Task PreservesTrailingTriviaAfterInitializer6() - { - await new VerifyCS.Test + public Task PreservesTrailingTriviaAfterInitializer6() + => new VerifyCS.Test { TestCode = """ class C @@ -5564,12 +5167,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73740")] - public async Task PreservesTrailingTriviaAfterInitializer7() - { - await new VerifyCS.Test + public Task PreservesTrailingTriviaAfterInitializer7() + => new VerifyCS.Test { TestCode = """ class C @@ -5586,12 +5187,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73740")] - public async Task PreservesTrailingTriviaAfterInitializer8() - { - await new VerifyCS.Test + public Task PreservesTrailingTriviaAfterInitializer8() + => new VerifyCS.Test { TestCode = """ class C @@ -5610,12 +5209,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73740")] - public async Task PreservesTrailingTriviaAfterInitializer9() - { - await new VerifyCS.Test + public Task PreservesTrailingTriviaAfterInitializer9() + => new VerifyCS.Test { TestCode = """ class C @@ -5633,12 +5230,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73740")] - public async Task PreservesTrailingTriviaAfterInitializer10() - { - await new VerifyCS.Test + public Task PreservesTrailingTriviaAfterInitializer10() + => new VerifyCS.Test { TestCode = """ class C @@ -5674,12 +5269,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73740")] - public async Task PreservesTrailingTriviaAfterInitializer11() - { - await new VerifyCS.Test + public Task PreservesTrailingTriviaAfterInitializer11() + => new VerifyCS.Test { TestCode = """ class C @@ -5697,12 +5290,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73740")] - public async Task PreservesTrailingTriviaAfterInitializer12() - { - await new VerifyCS.Test + public Task PreservesTrailingTriviaAfterInitializer12() + => new VerifyCS.Test { TestCode = """ class C @@ -5720,12 +5311,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73740")] - public async Task PreservesTrailingTriviaAfterInitializer14() - { - await new VerifyCS.Test + public Task PreservesTrailingTriviaAfterInitializer14() + => new VerifyCS.Test { TestCode = """ class C @@ -5757,12 +5346,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/74931")] - public async Task AllowSwitchToReadOnlySpanCSharp12(bool implicitType, bool whenTypesLooselyMatch) - { - await new VerifyCS.Test + public Task AllowSwitchToReadOnlySpanCSharp12(bool implicitType, bool whenTypesLooselyMatch) + => new VerifyCS.Test { TestCode = $$""" using System; @@ -5799,12 +5386,10 @@ void Split(ReadOnlySpan p) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/74931")] - public async Task AllowSwitchToReadOnlySpanCSharp13(bool implicitType, bool whenTypesLooselyMatch) - { - await new VerifyCS.Test + public Task AllowSwitchToReadOnlySpanCSharp13(bool implicitType, bool whenTypesLooselyMatch) + => new VerifyCS.Test { TestCode = $$""" using System; @@ -5841,12 +5426,10 @@ void Split(ReadOnlySpan p) { } LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/74931")] - public async Task AllowSwitchToReadOnlySpanGeneric1(bool implicitType, bool whenTypesLooselyMatch) - { - await new VerifyCS.Test + public Task AllowSwitchToReadOnlySpanGeneric1(bool implicitType, bool whenTypesLooselyMatch) + => new VerifyCS.Test { TestCode = $$""" using System; @@ -5883,5 +5466,4 @@ void Split(ReadOnlySpan p) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForBuilderTests.cs b/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForBuilderTests.cs index 4887f7fe07d6e..8840665845de2 100644 --- a/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForBuilderTests.cs +++ b/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForBuilderTests.cs @@ -64,9 +64,8 @@ public void Clear() { } ]; [Theory, MemberData(nameof(FailureCreationPatterns))] - public async Task TestNotInCSharp11(string pattern) - { - await new VerifyCS.Test + public Task TestNotInCSharp11(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -84,12 +83,10 @@ ImmutableArray M() LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(FailureCreationPatterns))] - public async Task TestInCSharp12_Net70(string pattern) - { - await new VerifyCS.Test + public Task TestInCSharp12_Net70(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -107,12 +104,10 @@ ImmutableArray M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Theory, MemberData(nameof(SuccessCreationPatterns))] - public async Task TestInCSharp12_Net80(string pattern) - { - await new VerifyCS.Test + public Task TestInCSharp12_Net80(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -141,12 +136,10 @@ ImmutableArray M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(SuccessCreationPatterns))] - public async Task TestCast(string pattern) - { - await new VerifyCS.Test + public Task TestCast(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -175,12 +168,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(FailureCreationPatterns))] - public async Task TestIdentifierCast(string pattern) - { - await new VerifyCS.Test + public Task TestIdentifierCast(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -199,12 +190,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(SuccessCreationPatterns))] - public async Task TestPassToArgument(string pattern) - { - await new VerifyCS.Test + public Task TestPassToArgument(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -237,12 +226,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestWithCapacity_CreateBuilder() - { - await new VerifyCS.Test + public Task TestWithCapacity_CreateBuilder() + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -275,12 +262,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestWithCapacity_ArrayBuilder1() - { - await new VerifyCS.Test + public Task TestWithCapacity_ArrayBuilder1() + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -313,12 +298,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestWithCapacity_ArrayBuilder2() - { - await new VerifyCS.Test + public Task TestWithCapacity_ArrayBuilder2() + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -351,12 +334,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(FailureCreationPatterns))] - public async Task TestNotWithOtherBuilderUsage(string pattern) - { - await new VerifyCS.Test + public Task TestNotWithOtherBuilderUsage(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -377,12 +358,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(FailureCreationPatterns))] - public async Task TestNotWithNoBuilderMutation(string pattern) - { - await new VerifyCS.Test + public Task TestNotWithNoBuilderMutation(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -401,12 +380,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(SuccessCreationPatterns))] - public async Task TestWithForeach1(string pattern) - { - await new VerifyCS.Test + public Task TestWithForeach1(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -442,12 +419,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(SuccessCreationPatterns))] - public async Task TestWithForeach2(string pattern) - { - await new VerifyCS.Test + public Task TestWithForeach2(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -485,12 +460,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(FailureCreationPatterns))] - public async Task TestWithForeach3(string pattern) - { - await new VerifyCS.Test + public Task TestWithForeach3(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -515,12 +488,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(FailureCreationPatterns))] - public async Task TestWithForeach4(string pattern) - { - await new VerifyCS.Test + public Task TestWithForeach4(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -545,12 +516,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(SuccessCreationPatterns))] - public async Task TestWithForeach5(string pattern) - { - await new VerifyCS.Test + public Task TestWithForeach5(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -592,12 +561,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(SuccessCreationPatterns))] - public async Task TestWithForeach6(string pattern) - { - await new VerifyCS.Test + public Task TestWithForeach6(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -639,12 +606,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(SuccessCreationPatterns))] - public async Task TestWithForeach7(string pattern) - { - await new VerifyCS.Test + public Task TestWithForeach7(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -686,12 +651,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory(Skip = "https://github.com/dotnet/roslyn/issues/70172"), MemberData(nameof(SuccessCreationPatterns)), WorkItem("https://github.com/dotnet/roslyn/issues/69277")] - public async Task TestWithIfStatement1(string pattern) - { - await new VerifyCS.Test + public Task TestWithIfStatement1(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -726,12 +689,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(SuccessCreationPatterns))] - public async Task TestWithIfStatement2(string pattern) - { - await new VerifyCS.Test + public Task TestWithIfStatement2(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -768,12 +729,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory(Skip = "https://github.com/dotnet/roslyn/issues/70172"), MemberData(nameof(SuccessCreationPatterns)), WorkItem("https://github.com/dotnet/roslyn/issues/69277")] - public async Task TestWithIfStatement3(string pattern) - { - await new VerifyCS.Test + public Task TestWithIfStatement3(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -810,12 +769,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(SuccessCreationPatterns))] - public async Task TestWithIfStatement4(string pattern) - { - await new VerifyCS.Test + public Task TestWithIfStatement4(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -856,12 +813,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(SuccessCreationPatterns))] - public async Task TestAddRange1(string pattern) - { - await new VerifyCS.Test + public Task TestAddRange1(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -894,12 +849,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(SuccessCreationPatterns))] - public async Task TestAddRange2(string pattern) - { - await new VerifyCS.Test + public Task TestAddRange2(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -932,12 +885,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(SuccessCreationPatterns))] - public async Task TestAddRange3(string pattern) - { - await new VerifyCS.Test + public Task TestAddRange3(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -970,12 +921,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(FailureCreationPatterns))] - public async Task TestAddRange4(string pattern) - { - await new VerifyCS.Test + public Task TestAddRange4(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -995,13 +944,11 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(SuccessCreationPatterns))] [WorkItem("https://github.com/dotnet/roslyn/issues/71607")] - public async Task TestAddRange5(string pattern) - { - await new VerifyCS.Test + public Task TestAddRange5(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -1034,12 +981,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestMoveToImmutable() - { - await new VerifyCS.Test + public Task TestMoveToImmutable() + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -1072,12 +1017,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestToImmutableAndFree() - { - await new VerifyCS.Test + public Task TestToImmutableAndFree() + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -1110,12 +1053,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestToImmutableAndClear() - { - await new VerifyCS.Test + public Task TestToImmutableAndClear() + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -1148,12 +1089,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(SuccessCreationPatterns))] - public async Task TestToArray(string pattern) - { - await new VerifyCS.Test + public Task TestToArray(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -1186,12 +1125,10 @@ void Goo(int[] values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(FailureCreationPatterns))] - public async Task TestNotWithOtherBuilderUsageAfter(string pattern) - { - await new VerifyCS.Test + public Task TestNotWithOtherBuilderUsageAfter(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -1212,12 +1149,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNotWithOtherDisposableUsageAfter() - { - await new VerifyCS.Test + public Task TestNotWithOtherDisposableUsageAfter() + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -1238,12 +1173,10 @@ void Goo(ImmutableArray values) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(SuccessCreationPatterns))] - public async Task TestTrivia1(string pattern) - { - await new VerifyCS.Test + public Task TestTrivia1(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -1278,12 +1211,10 @@ ImmutableArray M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(SuccessCreationPatterns))] - public async Task TestMultiLine1(string pattern) - { - await new VerifyCS.Test + public Task TestMultiLine1(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -1317,12 +1248,10 @@ ImmutableArray M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(SuccessCreationPatterns))] - public async Task TestMultiLine2(string pattern) - { - await new VerifyCS.Test + public Task TestMultiLine2(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -1360,12 +1289,10 @@ ImmutableArray M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestOnFillWithValue() - { - await new VerifyCS.Test + public Task TestOnFillWithValue() + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -1383,12 +1310,10 @@ ImmutableArray M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(SuccessCreationPatterns))] - public async Task TestGlobalStatement1(string pattern) - { - await new VerifyCS.Test + public Task TestGlobalStatement1(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -1409,12 +1334,10 @@ public async Task TestGlobalStatement1(string pattern) OutputKind = OutputKind.ConsoleApplication, }, }.RunAsync(); - } [Theory, MemberData(nameof(SuccessCreationPatterns))] - public async Task TestGlobalStatement2(string pattern) - { - await new VerifyCS.Test + public Task TestGlobalStatement2(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -1446,12 +1369,10 @@ public async Task TestGlobalStatement2(string pattern) OutputKind = OutputKind.ConsoleApplication, }, }.RunAsync(); - } [Fact] - public async Task TestNested1() - { - await new VerifyCS.Test + public Task TestNested1() + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -1483,14 +1404,12 @@ ImmutableArray> M() ReferenceAssemblies = ReferenceAssemblies.Net.Net80, NumberOfFixAllIterations = 2, }.RunAsync(); - } [Theory] [InlineData("\n")] [InlineData("\r\n")] - public async Task TestWithDifferentNewLines(string endOfLine) - { - await new VerifyCS.Test + public Task TestWithDifferentNewLines(string endOfLine) + => new VerifyCS.Test { TestCode = ($$""" using System.Collections.Immutable; @@ -1522,13 +1441,11 @@ ImmutableArray> M() ReferenceAssemblies = ReferenceAssemblies.Net.Net80, NumberOfFixAllIterations = 2, }.RunAsync(); - } [Theory, MemberData(nameof(SuccessCreationPatterns))] [WorkItem("https://github.com/dotnet/roslyn/issues/70996")] - public async Task TestInterfaceOn(string pattern) - { - await new VerifyCS.Test + public Task TestInterfaceOn(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Generic; @@ -1559,13 +1476,11 @@ IEnumerable M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, MemberData(nameof(FailureCreationPatterns))] [WorkItem("https://github.com/dotnet/roslyn/issues/70996")] - public async Task TestInterfaceOff(string pattern) - { - await new VerifyCS.Test + public Task TestInterfaceOff(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Generic; @@ -1588,13 +1503,11 @@ IEnumerable M() dotnet_style_prefer_collection_expression=when_types_exactly_match """ }.RunAsync(); - } [Theory, MemberData(nameof(SuccessCreationPatterns))] [WorkItem("https://github.com/dotnet/roslyn/issues/74208")] - public async Task TestComment(string pattern) - { - await new VerifyCS.Test + public Task TestComment(string pattern) + => new VerifyCS.Test { TestCode = $$""" using System.Collections.Immutable; @@ -1625,5 +1538,4 @@ ImmutableArray M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForCreateTests.cs b/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForCreateTests.cs index b1f841fad05ca..7db5019b8a700 100644 --- a/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForCreateTests.cs +++ b/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForCreateTests.cs @@ -61,10 +61,8 @@ interface IMyCollection : System.Collections.Generic.IEnumerable """; [Fact] - public async Task TestNotInCSharp11() - { - - await new VerifyCS.Test + public Task TestNotInCSharp11() + => new VerifyCS.Test { TestCode = """ using System.Collections.Immutable; @@ -77,12 +75,10 @@ class C LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestInCSharp12_Net70() - { - await new VerifyCS.Test + public Task TestInCSharp12_Net70() + => new VerifyCS.Test { TestCode = """ class C @@ -99,12 +95,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestEmpty() - { - await new VerifyCS.Test + public Task TestEmpty() + => new VerifyCS.Test { TestCode = """ class C @@ -121,12 +115,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestCast() - { - await new VerifyCS.Test + public Task TestCast() + => new VerifyCS.Test { TestCode = """ class C @@ -149,12 +141,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestIdentifierCast() - { - await new VerifyCS.Test + public Task TestIdentifierCast() + => new VerifyCS.Test { TestCode = """ using X = MyCollection; @@ -170,12 +160,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestOneElement() - { - await new VerifyCS.Test + public Task TestOneElement() + => new VerifyCS.Test { TestCode = """ class C @@ -192,12 +180,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestTwoElements() - { - await new VerifyCS.Test + public Task TestTwoElements() + => new VerifyCS.Test { TestCode = """ class C @@ -214,12 +200,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestThreeElements() - { - await new VerifyCS.Test + public Task TestThreeElements() + => new VerifyCS.Test { TestCode = """ class C @@ -236,12 +220,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestFourElements() - { - await new VerifyCS.Test + public Task TestFourElements() + => new VerifyCS.Test { TestCode = """ class C @@ -258,12 +240,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestParamsWithMultipleElements() - { - await new VerifyCS.Test + public Task TestParamsWithMultipleElements() + => new VerifyCS.Test { TestCode = """ class C @@ -280,12 +260,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestParamsWithExplicitArrayArgument1() - { - await new VerifyCS.Test + public Task TestParamsWithExplicitArrayArgument1() + => new VerifyCS.Test { TestCode = """ class C @@ -296,12 +274,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestParamsWithExplicitArrayArgument2() - { - await new VerifyCS.Test + public Task TestParamsWithExplicitArrayArgument2() + => new VerifyCS.Test { TestCode = """ class C @@ -318,12 +294,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestParamsWithExplicitArrayArgument3() - { - await new VerifyCS.Test + public Task TestParamsWithExplicitArrayArgument3() + => new VerifyCS.Test { TestCode = """ class C @@ -340,12 +314,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestParamsWithImplicitArrayArgument1() - { - await new VerifyCS.Test + public Task TestParamsWithImplicitArrayArgument1() + => new VerifyCS.Test { TestCode = """ class C @@ -362,12 +334,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestReadOnlySpan_ExplicitStackAlloc_Net70() - { - await new VerifyCS.Test + public Task TestReadOnlySpan_ExplicitStackAlloc_Net70() + => new VerifyCS.Test { TestCode = """ class C @@ -378,12 +348,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestReadOnlySpan_ImplicitStackAlloc_Net70() - { - await new VerifyCS.Test + public Task TestReadOnlySpan_ImplicitStackAlloc_Net70() + => new VerifyCS.Test { TestCode = """ class C @@ -394,12 +362,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestReadOnlySpan_ExplicitStackAlloc_Net80_1() - { - await new VerifyCS.Test + public Task TestReadOnlySpan_ExplicitStackAlloc_Net80_1() + => new VerifyCS.Test { TestCode = """ class C @@ -416,12 +382,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestReadOnlySpan_ExplicitStackAlloc_Net80_2() - { - await new VerifyCS.Test + public Task TestReadOnlySpan_ExplicitStackAlloc_Net80_2() + => new VerifyCS.Test { TestCode = """ class C @@ -438,12 +402,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestReadOnlySpan_ImplicitStackAlloc_Net80_1() - { - await new VerifyCS.Test + public Task TestReadOnlySpan_ImplicitStackAlloc_Net80_1() + => new VerifyCS.Test { TestCode = """ class C @@ -460,12 +422,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestCreateRange_Null() - { - await new VerifyCS.Test + public Task TestCreateRange_Null() + => new VerifyCS.Test { TestCode = """ class C @@ -476,12 +436,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestCreateRange_ComputedExpression() - { - await new VerifyCS.Test + public Task TestCreateRange_ComputedExpression() + => new VerifyCS.Test { TestCode = """ using System; @@ -508,12 +466,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestCreateRange_ExplicitArray1() - { - await new VerifyCS.Test + public Task TestCreateRange_ExplicitArray1() + => new VerifyCS.Test { TestCode = """ class C @@ -530,12 +486,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestCreateRange_ExplicitArray2() - { - await new VerifyCS.Test + public Task TestCreateRange_ExplicitArray2() + => new VerifyCS.Test { TestCode = """ class C @@ -552,12 +506,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestCreateRange_ExplicitArray3() - { - await new VerifyCS.Test + public Task TestCreateRange_ExplicitArray3() + => new VerifyCS.Test { TestCode = """ class C @@ -574,12 +526,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestCreateRange_ImplicitArray1() - { - await new VerifyCS.Test + public Task TestCreateRange_ImplicitArray1() + => new VerifyCS.Test { TestCode = """ class C @@ -596,12 +546,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestCreateRange_NewObjectWithArgument() - { - await new VerifyCS.Test + public Task TestCreateRange_NewObjectWithArgument() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -614,12 +562,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestCreateRange_NewObjectWithArgument2() - { - await new VerifyCS.Test + public Task TestCreateRange_NewObjectWithArgument2() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -632,12 +578,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestCreateRange_NewObjectWithoutArgument() - { - await new VerifyCS.Test + public Task TestCreateRange_NewObjectWithoutArgument() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -658,12 +602,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestCreateRange_NewObjectWithInitializer1() - { - await new VerifyCS.Test + public Task TestCreateRange_NewObjectWithInitializer1() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -684,12 +626,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestCreateRange_NewObjectWithInitializer2() - { - await new VerifyCS.Test + public Task TestCreateRange_NewObjectWithInitializer2() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -710,12 +650,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestCreateRange_NewObjectWithInitializer3() - { - await new VerifyCS.Test + public Task TestCreateRange_NewObjectWithInitializer3() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -736,12 +674,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestCreateRange_NewObjectWithInitializer4() - { - await new VerifyCS.Test + public Task TestCreateRange_NewObjectWithInitializer4() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -762,12 +698,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestCreateRange_NewImplicitObject() - { - await new VerifyCS.Test + public Task TestCreateRange_NewImplicitObject() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -788,12 +722,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestInterfaceDestination() - { - await new VerifyCS.Test + public Task TestInterfaceDestination() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -807,12 +739,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestTrivia1() - { - await new VerifyCS.Test + public Task TestTrivia1() + => new VerifyCS.Test { TestCode = """ class C @@ -829,12 +759,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestMultiLine1() - { - await new VerifyCS.Test + public Task TestMultiLine1() + => new VerifyCS.Test { TestCode = """ class C @@ -853,12 +781,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestMultiLine2() - { - await new VerifyCS.Test + public Task TestMultiLine2() + => new VerifyCS.Test { TestCode = """ class C @@ -884,12 +810,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69507")] - public async Task NotForImmutableArrayNet70() - { - await new VerifyCS.Test + public Task NotForImmutableArrayNet70() + => new VerifyCS.Test { TestCode = """ using System; @@ -906,12 +830,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69507")] - public async Task ForImmutableArrayNet80() - { - await new VerifyCS.Test + public Task ForImmutableArrayNet80() + => new VerifyCS.Test { TestCode = """ using System; @@ -940,12 +862,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69507"), WorkItem("https://github.com/dotnet/roslyn/issues/69521")] - public async Task NotForImmutableListNet70() - { - await new VerifyCS.Test + public Task NotForImmutableListNet70() + => new VerifyCS.Test { TestCode = """ using System; @@ -962,12 +882,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69507")] - public async Task ForImmutableListNet80() - { - await new VerifyCS.Test + public Task ForImmutableListNet80() + => new VerifyCS.Test { TestCode = """ using System; @@ -996,12 +914,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestGlobalStatement1() - { - await new VerifyCS.Test + public Task TestGlobalStatement1() + => new VerifyCS.Test { TestCode = """ MyCollection i = [|MyCollection.[|Create|](|]); @@ -1016,12 +932,10 @@ public async Task TestGlobalStatement1() OutputKind = OutputKind.ConsoleApplication, }, }.RunAsync(); - } [Fact] - public async Task TestGlobalStatement2() - { - await new VerifyCS.Test + public Task TestGlobalStatement2() + => new VerifyCS.Test { TestCode = """ MyCollection i = [|MyCollection.[|Create|](|]1 + @@ -1044,12 +958,10 @@ public async Task TestGlobalStatement2() OutputKind = OutputKind.ConsoleApplication, }, }.RunAsync(); - } [Fact] - public async Task TestNested1() - { - await new VerifyCS.Test + public Task TestNested1() + => new VerifyCS.Test { TestCode = """ using System; @@ -1079,14 +991,12 @@ void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net80, NumberOfFixAllIterations = 2, }.RunAsync(); - } [Theory] [InlineData("\n")] [InlineData("\r\n")] - public async Task TestWithDifferentNewLines(string endOfLine) - { - await new VerifyCS.Test + public Task TestWithDifferentNewLines(string endOfLine) + => new VerifyCS.Test { TestCode = """ using System; @@ -1116,12 +1026,10 @@ void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net80, NumberOfFixAllIterations = 2, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71012")] - public async Task TestInLambda() - { - await new VerifyCS.Test + public Task TestInLambda() + => new VerifyCS.Test { TestCode = """ @@ -1156,12 +1064,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71012")] - public async Task TestNotInLambda1() - { - await new VerifyCS.Test + public Task TestNotInLambda1() + => new VerifyCS.Test { TestCode = """ @@ -1181,12 +1087,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71012")] - public async Task TestNotInExpressionTree() - { - await new VerifyCS.Test + public Task TestNotInExpressionTree() + => new VerifyCS.Test { TestCode = """ @@ -1206,12 +1110,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70998")] - public async Task ForMismatchedTupleNames() - { - await new VerifyCS.Test + public Task ForMismatchedTupleNames() + => new VerifyCS.Test { TestCode = """ using System; @@ -1240,12 +1142,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70996")] - public async Task TestInterfaceOn() - { - await new VerifyCS.Test + public Task TestInterfaceOn() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -1266,12 +1166,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70996")] - public async Task TestInterfaceOff() - { - await new VerifyCS.Test + public Task TestInterfaceOff() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -1288,12 +1186,10 @@ class C dotnet_style_prefer_collection_expression=when_types_exactly_match """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75870")] - public async Task TestIEnumerablePassedToCreateRange() - { - await new VerifyCS.Test + public Task TestIEnumerablePassedToCreateRange() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -1324,5 +1220,4 @@ ImmutableArray GetFormattedRange() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForEmptyTests.cs b/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForEmptyTests.cs index 3771e7b17b192..9d784cbba8ed4 100644 --- a/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForEmptyTests.cs +++ b/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForEmptyTests.cs @@ -32,9 +32,8 @@ public CollectionBuilderAttribute(Type builderType, string methodName) { } """; [Fact] - public async Task ArrayEmpty1() - { - await new VerifyCS.Test + public Task ArrayEmpty1() + => new VerifyCS.Test { TestCode = """ using System; @@ -49,12 +48,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task ArrayEmpty2() - { - await new VerifyCS.Test + public Task ArrayEmpty2() + => new VerifyCS.Test { TestCode = """ using System; @@ -80,12 +77,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task ArrayEmpty2_A() - { - await new VerifyCS.Test + public Task ArrayEmpty2_A() + => new VerifyCS.Test { TestCode = """ using System; @@ -111,12 +106,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task ArrayEmpty3() - { - await new VerifyCS.Test + public Task ArrayEmpty3() + => new VerifyCS.Test { TestCode = """ using System; @@ -140,12 +133,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task ArrayEmpty3_Strict() - { - await new VerifyCS.Test + public Task ArrayEmpty3_Strict() + => new VerifyCS.Test { TestCode = """ using System; @@ -163,12 +154,10 @@ void M() dotnet_style_prefer_collection_expression=when_types_exactly_match """ }.RunAsync(); - } [Fact] - public async Task ArrayEmpty5_InterfacesOn() - { - await new VerifyCS.Test + public Task ArrayEmpty5_InterfacesOn() + => new VerifyCS.Test { TestCode = """ using System; @@ -196,12 +185,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task ArrayEmpty5_InterfacesOff() - { - await new VerifyCS.Test + public Task ArrayEmpty5_InterfacesOff() + => new VerifyCS.Test { TestCode = """ using System; @@ -221,12 +208,10 @@ void M() dotnet_style_prefer_collection_expression=when_types_exactly_match """ }.RunAsync(); - } [Fact] - public async Task ArrayEmpty6() - { - await new VerifyCS.Test + public Task ArrayEmpty6() + => new VerifyCS.Test { TestCode = """ using System; @@ -252,12 +237,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task ArrayEmpty7() - { - await new VerifyCS.Test + public Task ArrayEmpty7() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -285,12 +268,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task ArrayEmpty8() - { - await new VerifyCS.Test + public Task ArrayEmpty8() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -318,12 +299,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task ArrayEmpty9() - { - await new VerifyCS.Test + public Task ArrayEmpty9() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -351,12 +330,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task ArrayEmpty10() - { - await new VerifyCS.Test + public Task ArrayEmpty10() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -384,12 +361,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestCast() - { - await new VerifyCS.Test + public Task TestCast() + => new VerifyCS.Test { TestCode = """ using System; @@ -415,12 +390,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestIdentifierCast() - { - await new VerifyCS.Test + public Task TestIdentifierCast() + => new VerifyCS.Test { TestCode = """ using System; @@ -436,12 +409,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestTrivia() - { - await new VerifyCS.Test + public Task TestTrivia() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -469,12 +440,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNonCollection() - { - await new VerifyCS.Test + public Task TestNonCollection() + => new VerifyCS.Test { TestCode = """ using System; @@ -494,12 +463,10 @@ class X """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestProperty1() - { - await new VerifyCS.Test + public Task TestProperty1() + => new VerifyCS.Test { TestCode = """ using System; @@ -551,12 +518,10 @@ public void Add(T value) { } """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestBuilder1() - { - await new VerifyCS.Test + public Task TestBuilder1() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net70, TestCode = """ @@ -619,12 +584,10 @@ static class MyList """ + CollectionBuilderAttributeDefinition, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestBuilder2() - { - await new VerifyCS.Test + public Task TestBuilder2() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net70, TestCode = """ @@ -687,12 +650,10 @@ static class MyList """ + CollectionBuilderAttributeDefinition, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task ReadOnlySpan1() - { - await new VerifyCS.Test + public Task ReadOnlySpan1() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net70, TestCode = """ @@ -719,12 +680,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69507")] - public async Task NotForImmutableArrayNet70() - { - await new VerifyCS.Test + public Task NotForImmutableArrayNet70() + => new VerifyCS.Test { TestCode = """ using System; @@ -741,12 +700,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69507")] - public async Task ForImmutableArrayNet80() - { - await new VerifyCS.Test + public Task ForImmutableArrayNet80() + => new VerifyCS.Test { TestCode = """ using System; @@ -775,12 +732,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69507")] - public async Task NotForImmutableListNet70() - { - await new VerifyCS.Test + public Task NotForImmutableListNet70() + => new VerifyCS.Test { TestCode = """ using System; @@ -797,12 +752,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69507")] - public async Task ForImmutableListNet80() - { - await new VerifyCS.Test + public Task ForImmutableListNet80() + => new VerifyCS.Test { TestCode = """ using System; @@ -831,12 +784,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69507")] - public async Task NotForValueTypeWithoutNoArgConstructorAndWithoutCollectionBuilderAttribute() - { - await new VerifyCS.Test + public Task NotForValueTypeWithoutNoArgConstructorAndWithoutCollectionBuilderAttribute() + => new VerifyCS.Test { TestCode = """ using System; @@ -864,12 +815,10 @@ public void Add(T x) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69507")] - public async Task NotForValueTypeWithOneArgConstructorAndWithoutCollectionBuilderAttribute() - { - await new VerifyCS.Test + public Task NotForValueTypeWithOneArgConstructorAndWithoutCollectionBuilderAttribute() + => new VerifyCS.Test { TestCode = """ using System; @@ -899,7 +848,6 @@ public void Add(T x) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69507")] public async Task ForValueTypeWithCapacityConstructor() @@ -1246,9 +1194,8 @@ void M() } [Fact] - public async Task TestNotWhenChildOfInvocation() - { - await new VerifyCS.Test + public Task TestNotWhenChildOfInvocation() + => new VerifyCS.Test { TestCode = """ using System; @@ -1267,12 +1214,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestGlobalStatement() - { - await new VerifyCS.Test + public Task TestGlobalStatement() + => new VerifyCS.Test { TestCode = """ using System; @@ -1290,14 +1235,12 @@ public async Task TestGlobalStatement() OutputKind = OutputKind.ConsoleApplication, }, }.RunAsync(); - } [Theory] [InlineData("\n")] [InlineData("\r\n")] - public async Task TestWithDifferentNewLines(string endOfLine) - { - await new VerifyCS.Test + public Task TestWithDifferentNewLines(string endOfLine) + => new VerifyCS.Test { TestCode = """ using System; @@ -1317,12 +1260,10 @@ public async Task TestWithDifferentNewLines(string endOfLine) OutputKind = OutputKind.ConsoleApplication, }, }.RunAsync(); - } [Fact] - public async Task TestForSpanField() - { - await new VerifyCS.Test + public Task TestForSpanField() + => new VerifyCS.Test { TestCode = """ using System; @@ -1351,12 +1292,10 @@ public C() { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestForSpanProperty1() - { - await new VerifyCS.Test + public Task TestForSpanProperty1() + => new VerifyCS.Test { TestCode = """ using System; @@ -1381,12 +1320,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestForSpanProperty2() - { - await new VerifyCS.Test + public Task TestForSpanProperty2() + => new VerifyCS.Test { TestCode = """ using System; @@ -1411,12 +1348,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestForSpanProperty3() - { - await new VerifyCS.Test + public Task TestForSpanProperty3() + => new VerifyCS.Test { TestCode = """ using System; @@ -1441,12 +1376,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestForMethodReturn() - { - await new VerifyCS.Test + public Task TestForMethodReturn() + => new VerifyCS.Test { TestCode = """ using System; @@ -1471,12 +1404,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestForMethodLocal1() - { - await new VerifyCS.Test + public Task TestForMethodLocal1() + => new VerifyCS.Test { TestCode = """ using System; @@ -1507,12 +1438,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestForArgument() - { - await new VerifyCS.Test + public Task TestForArgument() + => new VerifyCS.Test { TestCode = """ using System; @@ -1547,12 +1476,10 @@ void X(ReadOnlySpan span) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71012")] - public async Task TestInLambda() - { - await new VerifyCS.Test + public Task TestInLambda() + => new VerifyCS.Test { TestCode = """ @@ -1584,12 +1511,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71012")] - public async Task TestNotInLambda1() - { - await new VerifyCS.Test + public Task TestNotInLambda1() + => new VerifyCS.Test { TestCode = """ @@ -1607,12 +1532,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71012")] - public async Task TestNotInExpressionTree() - { - await new VerifyCS.Test + public Task TestNotInExpressionTree() + => new VerifyCS.Test { TestCode = """ @@ -1630,14 +1553,12 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/70996")] - public async Task TestInterfaceOn( + public Task TestInterfaceOn( [CombinatorialValues("IEnumerable", "IReadOnlyCollection", "IReadOnlyList")] string type, [CombinatorialValues("Array.[|Empty|]()", "ImmutableArray.[|Empty|]")] string expression) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = $$""" using System; @@ -1668,14 +1589,12 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/70996")] - public async Task TestInterfaceOn_ReadWriteDestination( + public Task TestInterfaceOn_ReadWriteDestination( [CombinatorialValues("IList", "ICollection")] string type, [CombinatorialValues("Array.Empty()", "ImmutableArray.Empty")] string expression) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = $$""" using System; @@ -1693,12 +1612,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70996")] - public async Task TestInterfaceOff() - { - await new VerifyCS.Test + public Task TestInterfaceOff() + => new VerifyCS.Test { TestCode = """ using System; @@ -1718,5 +1635,4 @@ void M() dotnet_style_prefer_collection_expression=when_types_exactly_match """ }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForFluentTests.cs b/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForFluentTests.cs index c76d9cef5d86c..cfe3c0a8c5ed3 100644 --- a/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForFluentTests.cs +++ b/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForFluentTests.cs @@ -20,9 +20,8 @@ namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.UseCollectionExpress public sealed class UseCollectionExpressionForFluentTests { [Fact] - public async Task TestNotInCSharp11() - { - await new VerifyCS.Test + public Task TestNotInCSharp11() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -39,12 +38,10 @@ void M() LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestInCSharp12_Net70() - { - await new VerifyCS.Test + public Task TestInCSharp12_Net70() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -73,12 +70,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestInCSharp12_Net80() - { - await new VerifyCS.Test + public Task TestInCSharp12_Net80() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -107,12 +102,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestCast() - { - await new VerifyCS.Test + public Task TestCast() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -141,12 +134,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestIdentifierCast() - { - await new VerifyCS.Test + public Task TestIdentifierCast() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -164,12 +155,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestOnlyOnOutermost() - { - await new VerifyCS.Test + public Task TestOnlyOnOutermost() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -198,12 +187,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestExplicitArrayCreation() - { - await new VerifyCS.Test + public Task TestExplicitArrayCreation() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -232,12 +219,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestExplicitArrayCreation_NoInitializer() - { - await new VerifyCS.Test + public Task TestExplicitArrayCreation_NoInitializer() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -254,12 +239,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestArrayEmpty() - { - await new VerifyCS.Test + public Task TestArrayEmpty() + => new VerifyCS.Test { TestCode = """ using System; @@ -290,12 +273,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestImmutableArrayEmpty() - { - await new VerifyCS.Test + public Task TestImmutableArrayEmpty() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -326,12 +307,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestImmutableArrayEmptyAndAdd() - { - await new VerifyCS.Test + public Task TestImmutableArrayEmptyAndAdd() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -362,12 +341,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestImmutableArrayEmptyAndAddRange1() - { - await new VerifyCS.Test + public Task TestImmutableArrayEmptyAndAddRange1() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -398,12 +375,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestImmutableArrayEmptyAndAddRange2() - { - await new VerifyCS.Test + public Task TestImmutableArrayEmptyAndAddRange2() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -434,12 +409,10 @@ void M(int[] x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestImmutableArrayEmptyAndAddRange3() - { - await new VerifyCS.Test + public Task TestImmutableArrayEmptyAndAddRange3() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -470,12 +443,10 @@ void M(IEnumerable x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestImmutableArrayCreate() - { - await new VerifyCS.Test + public Task TestImmutableArrayCreate() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -506,12 +477,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestImmutableArrayCreateAndAdd() - { - await new VerifyCS.Test + public Task TestImmutableArrayCreateAndAdd() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -542,12 +511,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestImmutableArrayCreateAndAddRange1() - { - await new VerifyCS.Test + public Task TestImmutableArrayCreateAndAddRange1() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -578,12 +545,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestImmutableArrayCreateAndAddRange2() - { - await new VerifyCS.Test + public Task TestImmutableArrayCreateAndAddRange2() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -614,12 +579,10 @@ void M(int[] x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestImmutableArrayCreateAndAddRange3() - { - await new VerifyCS.Test + public Task TestImmutableArrayCreateAndAddRange3() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -650,12 +613,10 @@ void M(IEnumerable x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestImmutableArrayCreateAndAddRange4() - { - await new VerifyCS.Test + public Task TestImmutableArrayCreateAndAddRange4() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -686,12 +647,10 @@ void M(IEnumerable x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNotOnNonListEmpty() - { - await new VerifyCS.Test + public Task TestNotOnNonListEmpty() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -709,12 +668,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNotOnNonListCreate() - { - await new VerifyCS.Test + public Task TestNotOnNonListCreate() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -732,12 +689,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNotOnNonListEmptyAndAdd() - { - await new VerifyCS.Test + public Task TestNotOnNonListEmptyAndAdd() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -755,12 +710,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestInitializerMultiLine1() - { - await new VerifyCS.Test + public Task TestInitializerMultiLine1() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -795,12 +748,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestConcat1() - { - await new VerifyCS.Test + public Task TestConcat1() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -831,12 +782,10 @@ void M(int[] x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNotEndingWithConcat() - { - await new VerifyCS.Test + public Task TestNotEndingWithConcat() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -854,7 +803,6 @@ void M(int[] x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] public async Task TestSingleValueConcat() @@ -901,9 +849,8 @@ void M(int x) } [Fact] - public async Task TestAppend1() - { - await new VerifyCS.Test + public Task TestAppend1() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -934,12 +881,10 @@ void M(int x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNotEndingWithAppend() - { - await new VerifyCS.Test + public Task TestNotEndingWithAppend() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -957,12 +902,10 @@ void M(int x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestObjectCreation1() - { - await new VerifyCS.Test + public Task TestObjectCreation1() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -993,12 +936,10 @@ void M(int[] x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestObjectCreation2() - { - await new VerifyCS.Test + public Task TestObjectCreation2() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -1029,12 +970,10 @@ void M(int[] x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestObjectCreation3() - { - await new VerifyCS.Test + public Task TestObjectCreation3() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -1071,12 +1010,10 @@ void M(int[] x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestObjectCreation3_B() - { - await new VerifyCS.Test + public Task TestObjectCreation3_B() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -1118,12 +1055,10 @@ void M(int[] x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestObjectCreation4() - { - await new VerifyCS.Test + public Task TestObjectCreation4() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -1160,12 +1095,10 @@ void M(int[] x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestObjectCreation4_B() - { - await new VerifyCS.Test + public Task TestObjectCreation4_B() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -1207,12 +1140,10 @@ void M(int[] x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNotWithObjectCreationWithArg() - { - await new VerifyCS.Test + public Task TestNotWithObjectCreationWithArg() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -1233,12 +1164,10 @@ void M(int[] x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNotWithNonListLikeObjectCreation() - { - await new VerifyCS.Test + public Task TestNotWithNonListLikeObjectCreation() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -1259,12 +1188,10 @@ void M(int[] x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNotWithInnerCollectionInitializer() - { - await new VerifyCS.Test + public Task TestNotWithInnerCollectionInitializer() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -1285,12 +1212,10 @@ void M(int[] x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNotOnEmptyDictionary() - { - await new VerifyCS.Test + public Task TestNotOnEmptyDictionary() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -1310,12 +1235,10 @@ void M(int[] x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNotOnBuilder() - { - await new VerifyCS.Test + public Task TestNotOnBuilder() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -1335,12 +1258,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestEndsWithAdd1() - { - await new VerifyCS.Test + public Task TestEndsWithAdd1() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -1371,12 +1292,10 @@ void M(IEnumerable x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestEndsWithAddRange1() - { - await new VerifyCS.Test + public Task TestEndsWithAddRange1() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -1407,12 +1326,10 @@ void M(IEnumerable x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestEndsWithAddRange2() - { - await new VerifyCS.Test + public Task TestEndsWithAddRange2() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -1443,12 +1360,10 @@ void M(IEnumerable x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestAsSpan1() - { - await new VerifyCS.Test + public Task TestAsSpan1() + => new VerifyCS.Test { TestCode = """ using System; @@ -1481,12 +1396,10 @@ void M(IEnumerable x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestAsSpan2() - { - await new VerifyCS.Test + public Task TestAsSpan2() + => new VerifyCS.Test { TestCode = """ using System; @@ -1519,12 +1432,10 @@ void M(IEnumerable x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70101")] - public async Task TestAsSpan3() - { - await new VerifyCS.Test + public Task TestAsSpan3() + => new VerifyCS.Test { TestCode = """ using System; @@ -1543,12 +1454,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70101")] - public async Task TestAsSpan4() - { - await new VerifyCS.Test + public Task TestAsSpan4() + => new VerifyCS.Test { TestCode = """ using System; @@ -1570,12 +1479,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70101")] - public async Task TestAsSpan5() - { - await new VerifyCS.Test + public Task TestAsSpan5() + => new VerifyCS.Test { TestCode = """ using System; @@ -1608,12 +1515,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestStringToArray() - { - await new VerifyCS.Test + public Task TestStringToArray() + => new VerifyCS.Test { TestCode = """ using System; @@ -1646,12 +1551,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestMultiLine1() - { - await new VerifyCS.Test + public Task TestMultiLine1() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -1684,12 +1587,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestMultiLine2() - { - await new VerifyCS.Test + public Task TestMultiLine2() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -1728,12 +1629,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestMultiLine3() - { - await new VerifyCS.Test + public Task TestMultiLine3() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -1772,12 +1671,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestMultiLine4() - { - await new VerifyCS.Test + public Task TestMultiLine4() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -1810,12 +1707,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestMultiLine5() - { - await new VerifyCS.Test + public Task TestMultiLine5() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -1848,12 +1743,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestMultiLine6() - { - await new VerifyCS.Test + public Task TestMultiLine6() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -1894,12 +1787,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestMultiLine7() - { - await new VerifyCS.Test + public Task TestMultiLine7() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -1939,12 +1830,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestTrivia1() - { - await new VerifyCS.Test + public Task TestTrivia1() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -1973,12 +1862,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestGlobalStatement1() - { - await new VerifyCS.Test + public Task TestGlobalStatement1() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -1999,12 +1886,10 @@ public async Task TestGlobalStatement1() OutputKind = OutputKind.ConsoleApplication, }, }.RunAsync(); - } [Fact] - public async Task TestGlobalStatement2() - { - await new VerifyCS.Test + public Task TestGlobalStatement2() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -2035,12 +1920,10 @@ public async Task TestGlobalStatement2() OutputKind = OutputKind.ConsoleApplication, }, }.RunAsync(); - } [Fact] - public async Task TestNested1() - { - await new VerifyCS.Test + public Task TestNested1() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -2080,12 +1963,10 @@ void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net80, CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, }.RunAsync(); - } [Fact] - public async Task TestNested2() - { - await new VerifyCS.Test + public Task TestNested2() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -2115,12 +1996,10 @@ void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net80, CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, }.RunAsync(); - } [Fact] - public async Task TestReifyExistingCollection1() - { - await new VerifyCS.Test + public Task TestReifyExistingCollection1() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -2149,12 +2028,10 @@ void M(int[] x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestReifyExistingCollection2() - { - await new VerifyCS.Test + public Task TestReifyExistingCollection2() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -2183,12 +2060,10 @@ void M(int[] x, int[] y) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestReifyExistingCollection3() - { - await new VerifyCS.Test + public Task TestReifyExistingCollection3() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -2206,12 +2081,10 @@ void M(ImmutableArray x, int y) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestReifyExistingCollection3_B() - { - await new VerifyCS.Test + public Task TestReifyExistingCollection3_B() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -2242,12 +2115,10 @@ void M(ImmutableArray x, int y) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestReifyExistingCollection4() - { - await new VerifyCS.Test + public Task TestReifyExistingCollection4() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -2265,12 +2136,10 @@ void M(ImmutableArray x, int[] y) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestReifyExistingCollection4_B() - { - await new VerifyCS.Test + public Task TestReifyExistingCollection4_B() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -2301,12 +2170,10 @@ void M(ImmutableArray x, int[] y) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestReifyExistingCollection5() - { - await new VerifyCS.Test + public Task TestReifyExistingCollection5() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -2324,12 +2191,10 @@ void M(ImmutableArray x, int y, int z) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestReifyExistingCollection5_B() - { - await new VerifyCS.Test + public Task TestReifyExistingCollection5_B() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -2360,14 +2225,12 @@ void M(ImmutableArray x, int y, int z) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory] [InlineData("\n")] [InlineData("\r\n")] - public async Task TestWithDifferentNewLines(string endOfLine) - { - await new VerifyCS.Test + public Task TestWithDifferentNewLines(string endOfLine) + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -2398,12 +2261,10 @@ void M(ImmutableArray x, int y, int z) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70833")] - public async Task SpreadFormatting1() - { - await new VerifyCS.Test + public Task SpreadFormatting1() + => new VerifyCS.Test { TestCode = """ using System; @@ -2432,12 +2293,10 @@ static class EnumValueCache LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70833")] - public async Task SpreadFormatting2() - { - await new VerifyCS.Test + public Task SpreadFormatting2() + => new VerifyCS.Test { TestCode = """ using System; @@ -2466,12 +2325,10 @@ static class EnumValueCache LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70833")] - public async Task SpreadFormatting3() - { - await new VerifyCS.Test + public Task SpreadFormatting3() + => new VerifyCS.Test { TestCode = """ using System; @@ -2501,12 +2358,10 @@ static class EnumValueCache LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70833")] - public async Task SpreadFormatting4() - { - await new VerifyCS.Test + public Task SpreadFormatting4() + => new VerifyCS.Test { TestCode = """ using System; @@ -2536,12 +2391,10 @@ static class EnumValueCache LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70833")] - public async Task SpreadFormatting5() - { - await new VerifyCS.Test + public Task SpreadFormatting5() + => new VerifyCS.Test { TestCode = """ using System; @@ -2573,12 +2426,10 @@ static class EnumValueCache LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70833")] - public async Task SpreadFormatting6() - { - await new VerifyCS.Test + public Task SpreadFormatting6() + => new VerifyCS.Test { TestCode = """ using System; @@ -2610,12 +2461,10 @@ static class EnumValueCache LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71012")] - public async Task TestInLambda() - { - await new VerifyCS.Test + public Task TestInLambda() + => new VerifyCS.Test { TestCode = """ @@ -2649,12 +2498,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71012")] - public async Task TestNotInLambda1() - { - await new VerifyCS.Test + public Task TestNotInLambda1() + => new VerifyCS.Test { TestCode = """ @@ -2673,12 +2520,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71012")] - public async Task TestNotInExpressionTree() - { - await new VerifyCS.Test + public Task TestNotInExpressionTree() + => new VerifyCS.Test { TestCode = """ @@ -2697,12 +2542,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71145")] - public async Task TestNotInParallelEnumerable1() - { - await new VerifyCS.Test + public Task TestNotInParallelEnumerable1() + => new VerifyCS.Test { TestCode = """ @@ -2725,12 +2568,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71145")] - public async Task TestNotInParallelEnumerable2() - { - await new VerifyCS.Test + public Task TestNotInParallelEnumerable2() + => new VerifyCS.Test { TestCode = """ @@ -2776,12 +2617,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70996")] - public async Task TestInterfaceOn() - { - await new VerifyCS.Test + public Task TestInterfaceOn() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -2810,12 +2649,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70996")] - public async Task TestInterfaceOff() - { - await new VerifyCS.Test + public Task TestInterfaceOff() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -2836,12 +2673,10 @@ void M() dotnet_style_prefer_collection_expression=when_types_exactly_match """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71607")] - public async Task TestAddRangeOfCollectionExpression1() - { - await new VerifyCS.Test + public Task TestAddRangeOfCollectionExpression1() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -2872,12 +2707,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71607")] - public async Task TestAddRangeOfCollectionExpression2() - { - await new VerifyCS.Test + public Task TestAddRangeOfCollectionExpression2() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -2908,12 +2741,10 @@ void M(int[] x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71788")] - public async Task NotOnBannedType() - { - await new VerifyCS.Test + public Task NotOnBannedType() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -2935,12 +2766,10 @@ interface IIListProvider : IEnumerable LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestObjectCreation_PreservesTrivia() - { - await new VerifyCS.Test + public Task TestObjectCreation_PreservesTrivia() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -2978,12 +2807,10 @@ void M(int[] x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72699")] - public async Task TestObjectCreationArgument1() - { - await new VerifyCS.Test + public Task TestObjectCreationArgument1() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -3012,12 +2839,10 @@ void M(int[] values) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72699")] - public async Task TestObjectCreationArgument2() - { - await new VerifyCS.Test + public Task TestObjectCreationArgument2() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -3046,12 +2871,10 @@ void M(int[] values) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72699")] - public async Task TestObjectCreationArgument3() - { - await new VerifyCS.Test + public Task TestObjectCreationArgument3() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -3080,12 +2903,10 @@ void M(int[] values, int[] x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72699")] - public async Task TestObjectCreationArgument4() - { - await new VerifyCS.Test + public Task TestObjectCreationArgument4() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -3114,12 +2935,10 @@ void M(int[] values, int[] x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75870")] - public async Task TestSelectToImmutableArray() - { - await new VerifyCS.Test + public Task TestSelectToImmutableArray() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -3150,5 +2969,4 @@ ImmutableArray GetFormattedNumbers(ImmutableArray numbers) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForNewTests.cs b/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForNewTests.cs index 22a59b3203216..4cbead1937cd6 100644 --- a/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForNewTests.cs +++ b/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForNewTests.cs @@ -22,9 +22,8 @@ public sealed class UseCollectionExpressionForNewTests [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/75870")] [InlineData("List")] [InlineData("")] - public async Task TestIEnumerablePassedToListConstructor(string typeName) - { - await new VerifyCS.Test + public Task TestIEnumerablePassedToListConstructor(string typeName) + => new VerifyCS.Test { TestCode = $$""" using System.Linq; @@ -55,14 +54,12 @@ List GetNumbers() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/75870")] [InlineData("List")] [InlineData("")] - public async Task TestArrayPassedToListConstructor(string typeName) - { - await new VerifyCS.Test + public Task TestArrayPassedToListConstructor(string typeName) + => new VerifyCS.Test { TestCode = $$""" using System.Linq; @@ -93,12 +90,10 @@ List GetNumbers() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76683")] - public async Task TestNotOnStack() - { - await new VerifyCS.Test + public Task TestNotOnStack() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -116,12 +111,10 @@ Stack GetNumbers(T[] values) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/77177")] - public async Task TestNotOnQueue() - { - await new VerifyCS.Test + public Task TestNotOnQueue() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -136,5 +129,4 @@ class Container(IEnumerable items) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForStackAllocTests.cs b/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForStackAllocTests.cs index c90ecaf9da0f0..eef6c4a9a9007 100644 --- a/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForStackAllocTests.cs +++ b/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForStackAllocTests.cs @@ -19,9 +19,8 @@ namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.UseCollectionExpress public sealed class UseCollectionExpressionForStackAllocTests { [Fact] - public async Task TestNotInCSharp11() - { - await new VerifyCS.Test + public Task TestNotInCSharp11() + => new VerifyCS.Test { TestCode = """ using System; @@ -37,12 +36,10 @@ void M() LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNotInCSharp11_Implicit() - { - await new VerifyCS.Test + public Task TestNotInCSharp11_Implicit() + => new VerifyCS.Test { TestCode = """ using System; @@ -58,12 +55,10 @@ void M() LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNotInCSharp12_Net70() - { - await new VerifyCS.Test + public Task TestNotInCSharp12_Net70() + => new VerifyCS.Test { TestCode = """ using System; @@ -79,12 +74,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestNotInCSharp12_Net70_Implicit() - { - await new VerifyCS.Test + public Task TestNotInCSharp12_Net70_Implicit() + => new VerifyCS.Test { TestCode = """ using System; @@ -100,12 +93,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestInCSharp12() - { - await new VerifyCS.Test + public Task TestInCSharp12() + => new VerifyCS.Test { TestCode = """ using System; @@ -132,12 +123,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestInCSharp12_Implicit() - { - await new VerifyCS.Test + public Task TestInCSharp12_Implicit() + => new VerifyCS.Test { TestCode = """ using System; @@ -164,12 +153,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestInCSharp12_Span() - { - await new VerifyCS.Test + public Task TestInCSharp12_Span() + => new VerifyCS.Test { TestCode = """ using System; @@ -196,12 +183,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestInCSharp12_Span_Implicit() - { - await new VerifyCS.Test + public Task TestInCSharp12_Span_Implicit() + => new VerifyCS.Test { TestCode = """ using System; @@ -228,12 +213,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestMultipleArraySizes() - { - await new VerifyCS.Test + public Task TestMultipleArraySizes() + => new VerifyCS.Test { TestCode = """ using System; @@ -249,12 +232,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestMismatchedSize1() - { - await new VerifyCS.Test + public Task TestMismatchedSize1() + => new VerifyCS.Test { TestCode = """ using System; @@ -270,12 +251,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestMismatchedSize2() - { - await new VerifyCS.Test + public Task TestMismatchedSize2() + => new VerifyCS.Test { TestCode = """ using System; @@ -291,12 +270,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNonConstSize() - { - await new VerifyCS.Test + public Task TestNonConstSize() + => new VerifyCS.Test { TestCode = """ using System; @@ -312,12 +289,10 @@ void M(int size) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestConstSize() - { - await new VerifyCS.Test + public Task TestConstSize() + => new VerifyCS.Test { TestCode = """ using System; @@ -346,12 +321,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestWithPointer() - { - await new VerifyCS.Test + public Task TestWithPointer() + => new VerifyCS.Test { TestCode = """ using System; @@ -367,12 +340,10 @@ unsafe void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestWithPointer_Implicit() - { - await new VerifyCS.Test + public Task TestWithPointer_Implicit() + => new VerifyCS.Test { TestCode = """ using System; @@ -388,12 +359,10 @@ unsafe void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestWithVar() - { - await new VerifyCS.Test + public Task TestWithVar() + => new VerifyCS.Test { TestCode = """ using System; @@ -409,12 +378,10 @@ unsafe void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestWithVar_Implicit() - { - await new VerifyCS.Test + public Task TestWithVar_Implicit() + => new VerifyCS.Test { TestCode = """ using System; @@ -430,12 +397,10 @@ unsafe void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestWithSpanArgument() - { - await new VerifyCS.Test + public Task TestWithSpanArgument() + => new VerifyCS.Test { TestCode = """ using System; @@ -466,12 +431,10 @@ void Goo(ReadOnlySpan span) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestWithSpanArgument_Implicit() - { - await new VerifyCS.Test + public Task TestWithSpanArgument_Implicit() + => new VerifyCS.Test { TestCode = """ using System; @@ -502,12 +465,10 @@ void Goo(ReadOnlySpan span) { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestEmpty() - { - await new VerifyCS.Test + public Task TestEmpty() + => new VerifyCS.Test { TestCode = """ using System; @@ -534,12 +495,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestCast() - { - await new VerifyCS.Test + public Task TestCast() + => new VerifyCS.Test { TestCode = """ using System; @@ -566,12 +525,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestIdentifierCast() - { - await new VerifyCS.Test + public Task TestIdentifierCast() + => new VerifyCS.Test { TestCode = """ using System; @@ -588,12 +545,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestEmptyWithSize() - { - await new VerifyCS.Test + public Task TestEmptyWithSize() + => new VerifyCS.Test { TestCode = """ using System; @@ -620,12 +575,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestEmpty_Implicit() - { - await new VerifyCS.Test + public Task TestEmpty_Implicit() + => new VerifyCS.Test { TestCode = """ using System; @@ -641,12 +594,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_ZeroSize() - { - await new VerifyCS.Test + public Task TestNoInitializer_ZeroSize() + => new VerifyCS.Test { TestCode = """ using System; @@ -673,12 +624,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_NotEnoughFollowingStatements() - { - await new VerifyCS.Test + public Task TestNoInitializer_NotEnoughFollowingStatements() + => new VerifyCS.Test { TestCode = """ using System; @@ -694,12 +643,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_WrongFollowingStatement() - { - await new VerifyCS.Test + public Task TestNoInitializer_WrongFollowingStatement() + => new VerifyCS.Test { TestCode = """ using System; @@ -716,12 +663,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_NotLocalStatementInitializer() - { - await new VerifyCS.Test + public Task TestNoInitializer_NotLocalStatementInitializer() + => new VerifyCS.Test { TestCode = """ using System; @@ -740,12 +685,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_ExpressionStatementNotAssignment() - { - await new VerifyCS.Test + public Task TestNoInitializer_ExpressionStatementNotAssignment() + => new VerifyCS.Test { TestCode = """ using System; @@ -762,12 +705,10 @@ void M(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_AssignmentNotElementAccess() - { - await new VerifyCS.Test + public Task TestNoInitializer_AssignmentNotElementAccess() + => new VerifyCS.Test { TestCode = """ using System; @@ -784,12 +725,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_ElementAccessNotToIdentifier() - { - await new VerifyCS.Test + public Task TestNoInitializer_ElementAccessNotToIdentifier() + => new VerifyCS.Test { TestCode = """ using System; @@ -808,12 +747,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_IdentifierNotEqualToVariableName() - { - await new VerifyCS.Test + public Task TestNoInitializer_IdentifierNotEqualToVariableName() + => new VerifyCS.Test { TestCode = """ using System; @@ -832,12 +769,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_ArgumentNotConstant() - { - await new VerifyCS.Test + public Task TestNoInitializer_ArgumentNotConstant() + => new VerifyCS.Test { TestCode = """ using System; @@ -854,12 +789,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_ConstantArgumentNotCorrect1() - { - await new VerifyCS.Test + public Task TestNoInitializer_ConstantArgumentNotCorrect1() + => new VerifyCS.Test { TestCode = """ using System; @@ -876,12 +809,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_ConstantArgumentNotCorrect2() - { - await new VerifyCS.Test + public Task TestNoInitializer_ConstantArgumentNotCorrect2() + => new VerifyCS.Test { TestCode = """ using System; @@ -899,12 +830,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_OneElement() - { - await new VerifyCS.Test + public Task TestNoInitializer_OneElement() + => new VerifyCS.Test { TestCode = """ using System; @@ -932,12 +861,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_OneElement_MultipleFollowingStatements() - { - await new VerifyCS.Test + public Task TestNoInitializer_OneElement_MultipleFollowingStatements() + => new VerifyCS.Test { TestCode = """ using System; @@ -967,12 +894,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_TwoElement2() - { - await new VerifyCS.Test + public Task TestNoInitializer_TwoElement2() + => new VerifyCS.Test { TestCode = """ using System; @@ -1001,12 +926,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_TwoElement2_Constant() - { - await new VerifyCS.Test + public Task TestNoInitializer_TwoElement2_Constant() + => new VerifyCS.Test { TestCode = """ using System; @@ -1037,12 +960,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_TwoElement2_SecondWrongIndex() - { - await new VerifyCS.Test + public Task TestNoInitializer_TwoElement2_SecondWrongIndex() + => new VerifyCS.Test { TestCode = """ using System; @@ -1060,12 +981,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_TwoElement2_SecondNonConstant() - { - await new VerifyCS.Test + public Task TestNoInitializer_TwoElement2_SecondNonConstant() + => new VerifyCS.Test { TestCode = """ using System; @@ -1084,12 +1003,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_TwoElement2_SecondWrongDestination() - { - await new VerifyCS.Test + public Task TestNoInitializer_TwoElement2_SecondWrongDestination() + => new VerifyCS.Test { TestCode = """ using System; @@ -1110,12 +1027,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestTrivia1() - { - await new VerifyCS.Test + public Task TestTrivia1() + => new VerifyCS.Test { TestCode = """ using System; @@ -1150,12 +1065,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestTrivia2() - { - await new VerifyCS.Test + public Task TestTrivia2() + => new VerifyCS.Test { TestCode = """ using System; @@ -1190,12 +1103,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestExistingInitializer_MultiLine1() - { - await new VerifyCS.Test + public Task TestExistingInitializer_MultiLine1() + => new VerifyCS.Test { TestCode = """ using System; @@ -1228,12 +1139,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestExistingInitializer_MultiLine2() - { - await new VerifyCS.Test + public Task TestExistingInitializer_MultiLine2() + => new VerifyCS.Test { TestCode = """ using System; @@ -1268,12 +1177,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestExistingInitializer_MultiLine3() - { - await new VerifyCS.Test + public Task TestExistingInitializer_MultiLine3() + => new VerifyCS.Test { TestCode = """ using System; @@ -1304,12 +1211,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestExistingInitializer_MultiLine4() - { - await new VerifyCS.Test + public Task TestExistingInitializer_MultiLine4() + => new VerifyCS.Test { TestCode = """ using System; @@ -1342,12 +1247,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestExistingInitializer_MultiLine1_Implicit() - { - await new VerifyCS.Test + public Task TestExistingInitializer_MultiLine1_Implicit() + => new VerifyCS.Test { TestCode = """ using System; @@ -1380,12 +1283,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestExistingInitializer_MultiLine2_Implicit() - { - await new VerifyCS.Test + public Task TestExistingInitializer_MultiLine2_Implicit() + => new VerifyCS.Test { TestCode = """ using System; @@ -1420,12 +1321,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestExistingInitializer_MultiLine3_Implicit() - { - await new VerifyCS.Test + public Task TestExistingInitializer_MultiLine3_Implicit() + => new VerifyCS.Test { TestCode = """ using System; @@ -1456,12 +1355,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestExistingInitializer_MultiLine4_Implicit() - { - await new VerifyCS.Test + public Task TestExistingInitializer_MultiLine4_Implicit() + => new VerifyCS.Test { TestCode = """ using System; @@ -1494,12 +1391,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_MultiLine1() - { - await new VerifyCS.Test + public Task TestNoInitializer_MultiLine1() + => new VerifyCS.Test { TestCode = """ using System; @@ -1532,12 +1427,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNoInitializer_MultiLine2() - { - await new VerifyCS.Test + public Task TestNoInitializer_MultiLine2() + => new VerifyCS.Test { TestCode = """ using System; @@ -1574,12 +1467,10 @@ void M(int i, int j) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestGlobalStatement1() - { - await new VerifyCS.Test + public Task TestGlobalStatement1() + => new VerifyCS.Test { TestCode = """ using System; @@ -1598,12 +1489,10 @@ public async Task TestGlobalStatement1() OutputKind = OutputKind.ConsoleApplication, }, }.RunAsync(); - } [Fact] - public async Task TestGlobalStatement2() - { - await new VerifyCS.Test + public Task TestGlobalStatement2() + => new VerifyCS.Test { TestCode = """ using System; @@ -1634,5 +1523,4 @@ public async Task TestGlobalStatement2() OutputKind = OutputKind.ConsoleApplication, }, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UseCollectionInitializer/UseCollectionInitializerTests.cs b/src/Analyzers/CSharp/Tests/UseCollectionInitializer/UseCollectionInitializerTests.cs index f33a25452afca..8a8af0ee60d29 100644 --- a/src/Analyzers/CSharp/Tests/UseCollectionInitializer/UseCollectionInitializerTests.cs +++ b/src/Analyzers/CSharp/Tests/UseCollectionInitializer/UseCollectionInitializerTests.cs @@ -52,9 +52,8 @@ private static async Task TestMissingInRegularAndScriptAsync(string testCode, La } [Fact] - public async Task TestOnVariableDeclarator() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -81,12 +80,10 @@ void M() } } """); - } [Fact] - public async Task TestNotInField1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotInField1() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -95,12 +92,10 @@ class C List v = new List(); } """); - } [Fact] - public async Task TestNotInField2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotInField2() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -109,12 +104,10 @@ class C List v = new List() { 1, 2, 3 }; } """); - } [Fact] - public async Task TestOnVariableDeclarator_AddRange() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator_AddRange() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -143,12 +136,10 @@ void M(int[] x) } } """); - } [Fact] - public async Task TestOnVariableDeclarator_Foreach() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator_Foreach() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -179,12 +170,10 @@ void M(int[] x) } } """); - } [Fact] - public async Task TestOnVariableDeclarator_If1() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator_If1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -215,12 +204,10 @@ void M(bool b) } } """); - } [Fact] - public async Task TestOnVariableDeclarator_If2() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator_If2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -255,12 +242,10 @@ void M(bool b) } } """); - } [Fact] - public async Task TestOnVariableDeclarator_If3() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator_If3() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -295,12 +280,10 @@ void M(bool b) } } """); - } [Fact] - public async Task TestIndexAccess1() - { - await TestInRegularAndScriptAsync( + public Task TestIndexAccess1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; class C @@ -325,12 +308,10 @@ void M() } } """); - } [Fact] - public async Task TestIndexAccess1_NotInCSharp5() - { - await TestMissingInRegularAndScriptAsync( + public Task TestIndexAccess1_NotInCSharp5() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; class C @@ -342,12 +323,10 @@ void M() } } """, LanguageVersion.CSharp5); - } [Fact] - public async Task TestComplexIndexAccess1() - { - await TestInRegularAndScriptAsync( + public Task TestComplexIndexAccess1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -394,12 +373,10 @@ void M(A a) } } """); - } [Fact] - public async Task TestIndexAccess2() - { - await TestInRegularAndScriptAsync( + public Task TestIndexAccess2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; class C @@ -426,12 +403,10 @@ void M() } } """); - } [Fact] - public async Task TestIndexAccess3() - { - await TestInRegularAndScriptAsync( + public Task TestIndexAccess3() + => TestInRegularAndScriptAsync( """ using System.Collections; @@ -480,12 +455,10 @@ class X : IEnumerable public void Add(int i) { } } """); - } [Fact] - public async Task TestIndexFollowedByInvocation() - { - await TestInRegularAndScriptAsync( + public Task TestIndexFollowedByInvocation() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; class C @@ -512,12 +485,10 @@ void M() } } """); - } [Fact] - public async Task TestInvocationFollowedByIndex() - { - await TestInRegularAndScriptAsync( + public Task TestInvocationFollowedByIndex() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; class C @@ -544,12 +515,10 @@ void M() } } """); - } [Fact] - public async Task TestWithInterimStatement() - { - await TestInRegularAndScriptAsync( + public Task TestWithInterimStatement() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -584,12 +553,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingBeforeCSharp3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingBeforeCSharp3() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -602,12 +569,10 @@ void M() } } """, LanguageVersion.CSharp2); - } [Fact] - public async Task TestMissingOnNonIEnumerable() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnNonIEnumerable() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -622,12 +587,10 @@ void M() void Add(int i) { } } """); - } [Fact] - public async Task TestMissingOnNonIEnumerableEvenWithAdd() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnNonIEnumerableEvenWithAdd() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -644,12 +607,10 @@ public void Add(int i) } } """); - } [Fact] - public async Task TestWithCreationArguments() - { - await TestInRegularAndScriptAsync( + public Task TestWithCreationArguments() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -676,12 +637,10 @@ void M() } } """); - } [Fact] - public async Task TestOnAssignmentExpression() - { - await TestInRegularAndScriptAsync( + public Task TestOnAssignmentExpression() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -710,12 +669,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingOnRefAdd() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnRefAdd() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -736,12 +693,10 @@ public void Add(ref int i) } } """); - } [Fact] - public async Task TestComplexInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestComplexInitializer() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -770,12 +725,10 @@ void M(List[] array) } } """); - } [Fact] - public async Task TestNotOnNamedArg() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOnNamedArg() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -788,12 +741,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39146")] - public async Task TestWithExistingInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingInitializer() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -824,12 +775,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39146")] - public async Task TestWithExistingInitializerWithComma() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingInitializerWithComma() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -860,12 +809,10 @@ void M() } } """); - } [Fact] - public async Task TestFixAllInDocument1() - { - await TestInRegularAndScriptAsync( + public Task TestFixAllInDocument1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -902,12 +849,10 @@ void M(List[] array) } } """); - } [Fact] - public async Task TestFixAllInDocument2() - { - await TestInRegularAndScriptAsync( + public Task TestFixAllInDocument2() + => TestInRegularAndScriptAsync( """ using System; using System.Collections; @@ -963,12 +908,10 @@ public Bar(Action action) { } public void Add(int i) { } } """); - } [Fact] - public async Task TestFixAllInDocument3() - { - await new VerifyCS.Test + public Task TestFixAllInDocument3() + => new VerifyCS.Test { TestCode = """ @@ -1029,12 +972,10 @@ void M() } """, }.RunAsync(); - } [Fact] - public async Task TestTrivia1() - { - await TestInRegularAndScriptAsync( + public Task TestTrivia1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; class C @@ -1061,12 +1002,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46670")] - public async Task TestTriviaRemoveLeadingBlankLinesForFirstElement() - { - await TestInRegularAndScriptAsync( + public Task TestTriviaRemoveLeadingBlankLinesForFirstElement() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; class C @@ -1100,12 +1039,10 @@ void M() } } """); - } [Fact] - public async Task TestComplexInitializer2() - { - await TestInRegularAndScriptAsync( + public Task TestComplexInitializer2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1134,12 +1071,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16158")] - public async Task TestIncorrectAddName() - { - await TestInRegularAndScriptAsync( + public Task TestIncorrectAddName() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1174,12 +1109,10 @@ public static void Bar() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16241")] - public async Task TestNestedCollectionInitializer() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNestedCollectionInitializer() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; using System.Linq; @@ -1194,12 +1127,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17823")] - public async Task TestMissingWhenReferencedInInitializer() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWhenReferencedInInitializer() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1212,12 +1143,10 @@ static void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17823")] - public async Task TestWhenReferencedInInitializer_LocalVar() - { - await TestInRegularAndScriptAsync( + public Task TestWhenReferencedInInitializer_LocalVar() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1246,12 +1175,10 @@ static void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17823")] - public async Task TestWhenReferencedInInitializer_LocalVar2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWhenReferencedInInitializer_LocalVar2() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; using System.Linq; @@ -1265,12 +1192,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18260")] - public async Task TestWhenReferencedInInitializer_Assignment() - { - await TestInRegularAndScriptAsync( + public Task TestWhenReferencedInInitializer_Assignment() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1301,12 +1226,10 @@ static void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18260")] - public async Task TestWhenReferencedInInitializer_Assignment2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWhenReferencedInInitializer_Assignment2() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; using System.Linq; @@ -1321,12 +1244,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18260")] - public async Task TestFieldReference() - { - await TestMissingInRegularAndScriptAsync( + public Task TestFieldReference() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1340,12 +1261,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17853")] - public async Task TestMissingForDynamic() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingForDynamic() + => TestMissingInRegularAndScriptAsync( """ using System.Dynamic; @@ -1358,12 +1277,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17953")] - public async Task TestMissingAcrossPreprocessorDirective() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingAcrossPreprocessorDirective() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1378,12 +1295,10 @@ public void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17953")] - public async Task TestAvailableInsidePreprocessorDirective() - { - await TestInRegularAndScriptAsync( + public Task TestAvailableInsidePreprocessorDirective() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1414,12 +1329,10 @@ public void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18242")] - public async Task TestObjectInitializerAssignmentAmbiguity() - { - await TestInRegularAndScriptAsync( + public Task TestObjectInitializerAssignmentAmbiguity() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1448,12 +1361,10 @@ public void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18242")] - public async Task TestObjectInitializerCompoundAssignment() - { - await TestInRegularAndScriptAsync( + public Task TestObjectInitializerCompoundAssignment() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1482,12 +1393,10 @@ public void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19253")] - public async Task TestKeepBlankLinesAfter() - { - await TestInRegularAndScriptAsync( + public Task TestKeepBlankLinesAfter() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1518,12 +1427,10 @@ public void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23672")] - public async Task TestMissingWithExplicitImplementedAddMethod() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWithExplicitImplementedAddMethod() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; using System.Dynamic; @@ -1539,12 +1446,10 @@ public void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47632")] - public async Task TestWhenReferencedInInitializerLeft() - { - await TestInRegularAndScriptAsync( + public Task TestWhenReferencedInInitializerLeft() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1573,12 +1478,10 @@ static void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47632")] - public async Task TestWithIndexerInInitializerLeft() - { - await TestInRegularAndScriptAsync( + public Task TestWithIndexerInInitializerLeft() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1607,12 +1510,10 @@ static void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47632")] - public async Task TestWithImplicitObjectCreation() - { - await TestInRegularAndScriptAsync( + public Task TestWithImplicitObjectCreation() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1639,12 +1540,10 @@ static void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61066")] - public async Task TestInTopLevelStatements() - { - await TestInRegularAndScriptAsync( + public Task TestInTopLevelStatements() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1660,12 +1559,10 @@ await TestInRegularAndScriptAsync( }; """, OutputKind.ConsoleApplication); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71245")] - public async Task TestCollectionExpressionArgument1() - { - await TestInRegularAndScriptAsync( + public Task TestCollectionExpressionArgument1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1681,12 +1578,10 @@ await TestInRegularAndScriptAsync( }; """, OutputKind.ConsoleApplication, LanguageVersion.CSharp12); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71245")] - public async Task TestCollectionExpressionArgument2() - { - await TestInRegularAndScriptAsync( + public Task TestCollectionExpressionArgument2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1713,12 +1608,10 @@ void M() } } """, languageVersion: LanguageVersion.CSharp12); - } [Fact] - public async Task TestDictionaryInitializerAmbiguity1() - { - await new VerifyCS.Test + public Task TestDictionaryInitializerAmbiguity1() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -1748,12 +1641,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestDictionaryInitializerAmbiguity2() - { - await new VerifyCS.Test + public Task TestDictionaryInitializerAmbiguity2() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -1785,12 +1676,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75214")] - public async Task TestComplexForeach() - { - await new VerifyCS.Test + public Task TestComplexForeach() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -1826,12 +1715,10 @@ void M(List? list1) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/77416")] - public async Task TestNoCollectionExpressionForBlockingCollection() - { - await new VerifyCS.Test + public Task TestNoCollectionExpressionForBlockingCollection() + => new VerifyCS.Test { TestCode = """ using System; @@ -1864,5 +1751,4 @@ public void Main(ConcurrentQueue queue) LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UseCollectionInitializer/UseCollectionInitializerTests_CollectionExpression.cs b/src/Analyzers/CSharp/Tests/UseCollectionInitializer/UseCollectionInitializerTests_CollectionExpression.cs index c9c54808822da..44b6cc9193c99 100644 --- a/src/Analyzers/CSharp/Tests/UseCollectionInitializer/UseCollectionInitializerTests_CollectionExpression.cs +++ b/src/Analyzers/CSharp/Tests/UseCollectionInitializer/UseCollectionInitializerTests_CollectionExpression.cs @@ -21,9 +21,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseCollectionInitialize [Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public sealed partial class UseCollectionInitializerTests_CollectionExpression { - private static async Task TestInRegularAndScriptAsync([StringSyntax("C#-test")] string testCode, [StringSyntax("C#-test")] string fixedCode, OutputKind outputKind = OutputKind.DynamicallyLinkedLibrary) - { - await new VerifyCS.Test + private static Task TestInRegularAndScriptAsync([StringSyntax("C#-test")] string testCode, [StringSyntax("C#-test")] string fixedCode, OutputKind outputKind = OutputKind.DynamicallyLinkedLibrary) + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = testCode, @@ -31,15 +30,13 @@ private static async Task TestInRegularAndScriptAsync([StringSyntax("C#-test")] LanguageVersion = LanguageVersion.CSharp12, TestState = { OutputKind = outputKind } }.RunAsync(); - } private static Task TestMissingInRegularAndScriptAsync([StringSyntax("C#-test")] string testCode) => TestInRegularAndScriptAsync(testCode, testCode); [Fact] - public async Task TestNotOnVarVariableDeclarator() - { - await TestInRegularAndScriptAsync( + public Task TestNotOnVarVariableDeclarator() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -66,12 +63,10 @@ void M() } } """); - } [Fact] - public async Task TestNotWithConstructorArguments1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithConstructorArguments1() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -83,12 +78,10 @@ void M() } } """); - } [Fact] - public async Task TestWithConstructorArguments2() - { - await TestInRegularAndScriptAsync( + public Task TestWithConstructorArguments2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -115,12 +108,10 @@ void M() } } """); - } [Fact] - public async Task TestInField1() - { - await TestInRegularAndScriptAsync( + public Task TestInField1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -137,12 +128,10 @@ class C List c = []; } """); - } [Fact] - public async Task TestInField2() - { - await TestInRegularAndScriptAsync( + public Task TestInField2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -159,12 +148,10 @@ class C List c = [1, 2, 3]; } """); - } [Fact] - public async Task TestInField3() - { - await TestInRegularAndScriptAsync( + public Task TestInField3() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -191,12 +178,10 @@ class C ]; } """); - } [Fact] - public async Task TestInField4() - { - await TestInRegularAndScriptAsync(""" + public Task TestInField4() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; class C @@ -211,12 +196,10 @@ class C List c = [.. new[] { 1, 2, 3 }]; } """); - } [Fact] - public async Task TestInField5() - { - await TestInRegularAndScriptAsync( + public Task TestInField5() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -233,12 +216,10 @@ class C List c = []; } """); - } [Fact] - public async Task TestInField6() - { - await TestInRegularAndScriptAsync( + public Task TestInField6() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -255,12 +236,10 @@ class C List c = [1, 2, 3]; } """); - } [Fact] - public async Task TestInField7() - { - await TestInRegularAndScriptAsync( + public Task TestInField7() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -287,12 +266,10 @@ class C ]; } """); - } [Fact] - public async Task TestInArgument1() - { - await TestInRegularAndScriptAsync( + public Task TestInArgument1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -319,12 +296,10 @@ void M() void X(List list) { } } """); - } [Fact] - public async Task TestInArgument2_InterfacesOn() - { - await TestInRegularAndScriptAsync( + public Task TestInArgument2_InterfacesOn() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -351,12 +326,10 @@ void M() void X(IEnumerable list) { } } """); - } [Fact] - public async Task TestInArgument2_InterfacesOff() - { - await new VerifyCS.Test + public Task TestInArgument2_InterfacesOff() + => new VerifyCS.Test { ReferenceAssemblies = Testing.ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = """ @@ -378,12 +351,10 @@ void X(IEnumerable list) { } dotnet_style_prefer_collection_expression=when_types_exactly_match """ }.RunAsync(); - } [Fact] - public async Task TestOnVariableDeclarator() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -407,12 +378,10 @@ void M() } } """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/70172"), WorkItem("https://github.com/dotnet/roslyn/issues/69277")] - public async Task TestOnVariableDeclarator_If1() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator_If1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -438,12 +407,10 @@ void M(bool b) } } """); - } [Fact] - public async Task TestOnVariableDeclarator_If2() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator_If2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -471,12 +438,10 @@ void M(bool b) } } """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/70172"), WorkItem("https://github.com/dotnet/roslyn/issues/69277")] - public async Task TestOnVariableDeclarator_If3() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator_If3() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -504,12 +469,10 @@ void M(bool b) } } """); - } [Fact] - public async Task TestOnVariableDeclarator_If4() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator_If4() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -541,12 +504,10 @@ void M(bool b) } } """); - } [Fact] - public async Task TestOnVariableDeclarator_If5() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator_If5() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -580,12 +541,10 @@ void M(bool b) } } """); - } [Fact] - public async Task TestOnVariableDeclarator_If6() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator_If6() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -627,12 +586,10 @@ void M(bool b) } } """); - } [Fact] - public async Task TestOnVariableDeclarator_If7() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator_If7() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -662,12 +619,10 @@ void M(bool b) } } """); - } [Fact] - public async Task TestOnVariableDeclarator_If8() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator_If8() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -705,14 +660,12 @@ void M(bool b) } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/73879")] [InlineData("IList")] [InlineData("ICollection")] - public async Task TestOnVariableDeclaratorDifferentType_Interface_LooseMatch_MutableInterface(string collectionType) - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclaratorDifferentType_Interface_LooseMatch_MutableInterface(string collectionType) + => TestInRegularAndScriptAsync( $$""" using System.Collections.Generic; @@ -736,12 +689,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73879")] - public async Task TestOnVariableDeclaratorDifferentType_Interface_LooseMatch_ReadOnlyInterface() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclaratorDifferentType_Interface_LooseMatch_ReadOnlyInterface() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -764,12 +715,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73879")] - public async Task TestOnVariableDeclaratorDifferentType_Interface_ExactlyMatch_MutableInterface() - { - await new VerifyCS.Test + public Task TestOnVariableDeclaratorDifferentType_Interface_ExactlyMatch_MutableInterface() + => new VerifyCS.Test { ReferenceAssemblies = Testing.ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = """ @@ -801,12 +750,10 @@ void M() dotnet_style_prefer_collection_expression=when_types_exactly_match """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73879")] - public async Task TestOnVariableDeclaratorDifferentType_Interface_ExactlyMatch_ReadOnlyInterface() - { - await new VerifyCS.Test + public Task TestOnVariableDeclaratorDifferentType_Interface_ExactlyMatch_ReadOnlyInterface() + => new VerifyCS.Test { ReferenceAssemblies = Testing.ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = """ @@ -826,12 +773,10 @@ void M() dotnet_style_prefer_collection_expression=when_types_exactly_match """ }.RunAsync(); - } [Fact] - public async Task TestOnVariableDeclarator_Foreach1() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator_Foreach1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -857,12 +802,10 @@ void M(int[] x) } } """); - } [Fact] - public async Task TestOnVariableDeclarator_Foreach1_A() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator_Foreach1_A() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -890,12 +833,10 @@ void M(int[] x) } } """); - } [Fact] - public async Task TestOnVariableDeclarator_Foreach1_B() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator_Foreach1_B() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -927,12 +868,10 @@ void M(int[] x) } } """); - } [Fact] - public async Task TestOnVariableDeclarator_Foreach1_C() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator_Foreach1_C() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -964,12 +903,10 @@ void M(int[] x, int z) } } """); - } [Fact] - public async Task TestOnVariableDeclarator_Foreach2() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator_Foreach2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -997,12 +934,10 @@ void M(int[] x, int[] y) } } """); - } [Fact] - public async Task TestOnVariableDeclarator_Foreach3() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator_Foreach3() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1030,12 +965,10 @@ void M(int[] x, int[] y) } } """); - } [Fact] - public async Task TestOnVariableDeclarator_Foreach4() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator_Foreach4() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1063,12 +996,10 @@ void M(int[] x, int[] y) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70388")] - public async Task TestOnVariableDeclarator_AwaitForeach1() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator_AwaitForeach1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1096,12 +1027,10 @@ async void M(IAsyncEnumerable x) } } """); - } [Fact] - public async Task TestOnVariableDeclarator_AddRange1() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator_AddRange1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1126,12 +1055,10 @@ void M(int[] x) } } """); - } [Fact] - public async Task TestOnVariableDeclarator_AddRangeAndForeach1() - { - await TestInRegularAndScriptAsync( + public Task TestOnVariableDeclarator_AddRangeAndForeach1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1158,12 +1085,10 @@ void M(int[] x, int[] y) } } """); - } [Fact] - public async Task TestIndexAccess1() - { - await TestInRegularAndScriptAsync( + public Task TestIndexAccess1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; class C @@ -1188,12 +1113,10 @@ void M() } } """); - } [Fact] - public async Task TestIndexAccess1_Foreach() - { - await TestInRegularAndScriptAsync( + public Task TestIndexAccess1_Foreach() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; class C @@ -1222,12 +1145,10 @@ void M(int[] x) } } """); - } [Fact] - public async Task TestComplexIndexAccess1() - { - await TestInRegularAndScriptAsync( + public Task TestComplexIndexAccess1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1274,12 +1195,10 @@ void M(A a) } } """); - } [Fact] - public async Task TestIndexAccess2() - { - await TestInRegularAndScriptAsync( + public Task TestIndexAccess2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; class C @@ -1306,12 +1225,10 @@ void M() } } """); - } [Fact] - public async Task TestIndexAccess3() - { - await TestInRegularAndScriptAsync( + public Task TestIndexAccess3() + => TestInRegularAndScriptAsync( """ using System.Collections; @@ -1360,12 +1277,10 @@ class X : IEnumerable public void Add(int i) { } } """); - } [Fact] - public async Task TestIndexFollowedByInvocation() - { - await TestInRegularAndScriptAsync( + public Task TestIndexFollowedByInvocation() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; class C @@ -1392,12 +1307,10 @@ void M() } } """); - } [Fact] - public async Task TestInvocationFollowedByIndex() - { - await TestInRegularAndScriptAsync( + public Task TestInvocationFollowedByIndex() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; class C @@ -1421,12 +1334,10 @@ void M() } } """); - } [Fact] - public async Task TestWithInterimStatement() - { - await TestInRegularAndScriptAsync( + public Task TestWithInterimStatement() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1457,12 +1368,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingOnNonIEnumerable() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnNonIEnumerable() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1477,12 +1386,10 @@ void M() void Add(int i) { } } """); - } [Fact] - public async Task TestMissingOnNonIEnumerableEvenWithAdd() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnNonIEnumerableEvenWithAdd() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1499,12 +1406,10 @@ public void Add(int i) } } """); - } [Fact] - public async Task TestWithCreationArguments() - { - await TestInRegularAndScriptAsync( + public Task TestWithCreationArguments() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1528,12 +1433,10 @@ void M() } } """); - } [Fact] - public async Task TestOnAssignmentExpression() - { - await TestInRegularAndScriptAsync( + public Task TestOnAssignmentExpression() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1559,12 +1462,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingOnRefAdd() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnRefAdd() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1585,12 +1486,10 @@ public void Add(ref int i) } } """); - } [Fact] - public async Task TestComplexInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestComplexInitializer() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1615,12 +1514,10 @@ void M(List[] array) } } """); - } [Fact] - public async Task TestOnNamedArg() - { - await TestInRegularAndScriptAsync( + public Task TestOnNamedArg() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1645,12 +1542,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39146")] - public async Task TestWithExistingInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingInitializer() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1680,12 +1575,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39146")] - public async Task TestWithExistingInitializer_NoParens() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingInitializer_NoParens() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1715,12 +1608,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39146")] - public async Task TestWithExistingInitializerWithComma() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingInitializerWithComma() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1750,12 +1641,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39146")] - public async Task TestWithExistingInitializer2() - { - await TestInRegularAndScriptAsync( + public Task TestWithExistingInitializer2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1786,12 +1675,10 @@ void M(int[] x) } } """); - } [Fact] - public async Task TestFixAllInDocument1() - { - await TestInRegularAndScriptAsync( + public Task TestFixAllInDocument1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1820,12 +1707,10 @@ void M(List[] array) } } """); - } [Fact] - public async Task TestFixAllInDocument2() - { - await TestInRegularAndScriptAsync( + public Task TestFixAllInDocument2() + => TestInRegularAndScriptAsync( """ using System; using System.Collections; @@ -1878,12 +1763,10 @@ public Bar(Action action) { } public void Add(int i) { } } """); - } [Fact] - public async Task TestFixAllInDocument3() - { - await new VerifyCS.Test + public Task TestFixAllInDocument3() + => new VerifyCS.Test { TestCode = """ @@ -1940,12 +1823,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestTrivia1() - { - await TestInRegularAndScriptAsync( + public Task TestTrivia1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; class C @@ -1972,12 +1853,10 @@ void M() } } """); - } [Fact] - public async Task TestTrivia2() - { - await TestInRegularAndScriptAsync( + public Task TestTrivia2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; class C @@ -2011,12 +1890,10 @@ void M(int[] x, int[] y) } } """); - } [Fact] - public async Task TestTrivia3() - { - await TestInRegularAndScriptAsync( + public Task TestTrivia3() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; class C @@ -2054,12 +1931,10 @@ void M(int[] x, int[] y) } } """); - } [Fact] - public async Task TestTrivia4() - { - await TestInRegularAndScriptAsync( + public Task TestTrivia4() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; class C @@ -2101,12 +1976,10 @@ void M(bool b1, bool b2) } } """); - } [Fact] - public async Task TestTrivia5() - { - await TestInRegularAndScriptAsync( + public Task TestTrivia5() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; class C @@ -2152,13 +2025,11 @@ void M(bool b1, bool b2) } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)] [WorkItem("https://github.com/dotnet/roslyn/issues/46670")] - public async Task TestTriviaRemoveLeadingBlankLinesForFirstElement() - { - await TestInRegularAndScriptAsync( + public Task TestTriviaRemoveLeadingBlankLinesForFirstElement() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; class C @@ -2191,12 +2062,10 @@ void M() } } """); - } [Fact] - public async Task TestComplexInitializer2() - { - await TestInRegularAndScriptAsync( + public Task TestComplexInitializer2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -2225,12 +2094,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16158")] - public async Task TestIncorrectAddName() - { - await TestInRegularAndScriptAsync( + public Task TestIncorrectAddName() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -2262,12 +2129,10 @@ public static void Bar() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16241")] - public async Task TestNestedCollectionInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestNestedCollectionInitializer() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; using System.Linq; @@ -2296,12 +2161,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17823")] - public async Task TestWhenReferencedInInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestWhenReferencedInInitializer() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -2326,12 +2189,10 @@ static void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17823")] - public async Task TestWhenReferencedInInitializer_LocalVar() - { - await TestInRegularAndScriptAsync( + public Task TestWhenReferencedInInitializer_LocalVar() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -2360,12 +2221,10 @@ static void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17823")] - public async Task TestWhenReferencedInInitializer_LocalVar2() - { - await TestInRegularAndScriptAsync(""" + public Task TestWhenReferencedInInitializer_LocalVar2() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; @@ -2390,12 +2249,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18260")] - public async Task TestWhenReferencedInInitializer_Assignment() - { - await TestInRegularAndScriptAsync( + public Task TestWhenReferencedInInitializer_Assignment() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -2426,12 +2283,10 @@ static void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18260")] - public async Task TestWhenReferencedInInitializer_Assignment2() - { - await TestInRegularAndScriptAsync( + public Task TestWhenReferencedInInitializer_Assignment2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; using System.Linq; @@ -2460,12 +2315,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18260")] - public async Task TestFieldReference() - { - await TestInRegularAndScriptAsync( + public Task TestFieldReference() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -2492,12 +2345,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17853")] - public async Task TestMissingForDynamic() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingForDynamic() + => TestMissingInRegularAndScriptAsync( """ using System.Dynamic; @@ -2510,12 +2361,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17953")] - public async Task TestMissingAcrossPreprocessorDirective() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingAcrossPreprocessorDirective() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -2530,12 +2379,10 @@ public void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17953")] - public async Task TestAvailableInsidePreprocessorDirective() - { - await TestInRegularAndScriptAsync( + public Task TestAvailableInsidePreprocessorDirective() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -2563,12 +2410,10 @@ public void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18242")] - public async Task TestObjectInitializerAssignmentAmbiguity() - { - await TestInRegularAndScriptAsync( + public Task TestObjectInitializerAssignmentAmbiguity() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -2594,12 +2439,10 @@ public void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18242")] - public async Task TestObjectInitializerCompoundAssignment() - { - await TestInRegularAndScriptAsync( + public Task TestObjectInitializerCompoundAssignment() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -2625,12 +2468,10 @@ public void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19253")] - public async Task TestKeepBlankLinesAfter() - { - await TestInRegularAndScriptAsync( + public Task TestKeepBlankLinesAfter() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -2658,12 +2499,10 @@ public void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23672")] - public async Task TestMissingWithExplicitImplementedAddMethod() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWithExplicitImplementedAddMethod() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; using System.Dynamic; @@ -2679,12 +2518,10 @@ public void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47632")] - public async Task TestWhenReferencedInInitializerLeft() - { - await TestInRegularAndScriptAsync( + public Task TestWhenReferencedInInitializerLeft() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -2713,12 +2550,10 @@ static void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47632")] - public async Task TestWithIndexerInInitializerLeft() - { - await TestInRegularAndScriptAsync( + public Task TestWithIndexerInInitializerLeft() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -2747,12 +2582,10 @@ static void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47632")] - public async Task TestWithImplicitObjectCreation() - { - await TestInRegularAndScriptAsync( + public Task TestWithImplicitObjectCreation() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -2779,13 +2612,11 @@ static void M() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)] [WorkItem("https://github.com/dotnet/roslyn/issues/61066")] - public async Task TestInTopLevelStatements() - { - await TestInRegularAndScriptAsync( + public Task TestInTopLevelStatements() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -2798,12 +2629,10 @@ await TestInRegularAndScriptAsync( List list = [1]; """, OutputKind.ConsoleApplication); - } [Fact] - public async Task TestUpdateExistingCollectionInitializerToExpression1() - { - await TestInRegularAndScriptAsync( + public Task TestUpdateExistingCollectionInitializerToExpression1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -2826,12 +2655,10 @@ void M() } } """); - } [Fact] - public async Task TestUpdateExistingCollectionInitializerToExpression2() - { - await TestInRegularAndScriptAsync( + public Task TestUpdateExistingCollectionInitializerToExpression2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -2860,12 +2687,10 @@ void M() } } """); - } [Fact] - public async Task TestUpdateExistingCollectionInitializerToExpression3() - { - await TestInRegularAndScriptAsync( + public Task TestUpdateExistingCollectionInitializerToExpression3() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -2894,12 +2719,10 @@ void M() } } """); - } [Fact] - public async Task TestUpdateExistingCollectionInitializerToExpression4() - { - await TestInRegularAndScriptAsync( + public Task TestUpdateExistingCollectionInitializerToExpression4() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -2930,12 +2753,10 @@ void M() } } """); - } [Fact] - public async Task TestUpdateExistingCollectionInitializerToExpression5() - { - await TestInRegularAndScriptAsync( + public Task TestUpdateExistingCollectionInitializerToExpression5() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -2966,12 +2787,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NoElements_ExistingInitializer1() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NoElements_ExistingInitializer1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -2994,12 +2813,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NoElements_ExistingInitializer2() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NoElements_ExistingInitializer2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3023,12 +2840,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NoElements_ExistingInitializer3() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NoElements_ExistingInitializer3() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3052,12 +2867,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NoElements_ExistingInitializer4() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NoElements_ExistingInitializer4() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3082,12 +2895,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NoElements_ExistingInitializer5() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NoElements_ExistingInitializer5() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3113,12 +2924,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NoElements_ExistingInitializer6() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NoElements_ExistingInitializer6() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3145,12 +2954,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NoElements_ExistingInitializer7() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NoElements_ExistingInitializer7() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3175,12 +2982,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NoElements_ExistingInitializer8() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NoElements_ExistingInitializer8() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3204,12 +3009,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_ExistingElements_ExistingInitializer1() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_ExistingElements_ExistingInitializer1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3232,12 +3035,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_ExistingElements_ExistingInitializer2() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_ExistingElements_ExistingInitializer2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3261,12 +3062,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_ExistingElements_ExistingInitializer3() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_ExistingElements_ExistingInitializer3() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3295,12 +3094,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_ExistingElements_ExistingInitializer4() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_ExistingElements_ExistingInitializer4() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3325,12 +3122,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_ExistingElements_ExistingInitializer5() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_ExistingElements_ExistingInitializer5() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3356,12 +3151,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_ExistingElements_ExistingInitializer6() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_ExistingElements_ExistingInitializer6() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3393,12 +3186,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_ExistingElements_ExistingInitializer7() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_ExistingElements_ExistingInitializer7() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3429,12 +3220,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_ExistingElements_ExistingInitializer8() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_ExistingElements_ExistingInitializer8() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3463,12 +3252,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_ExistingElements_ExistingInitializer9() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_ExistingElements_ExistingInitializer9() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3498,12 +3285,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_ExistingElements_ExistingInitializer10() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_ExistingElements_ExistingInitializer10() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3533,12 +3318,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NewSingleLineElements_ExistingElements_ExistingInitializer1() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NewSingleLineElements_ExistingElements_ExistingInitializer1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3562,12 +3345,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NewSingleLineElements_ExistingElements_ExistingInitializer2() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NewSingleLineElements_ExistingElements_ExistingInitializer2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3592,12 +3373,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NewSingleLineElements_ExistingElements_ExistingInitializer3() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NewSingleLineElements_ExistingElements_ExistingInitializer3() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3628,12 +3407,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NewSingleLineElements_ExistingElements_ExistingInitializer4() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NewSingleLineElements_ExistingElements_ExistingInitializer4() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3659,12 +3436,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NewSingleLineElements_ExistingElements_ExistingInitializer5() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NewSingleLineElements_ExistingElements_ExistingInitializer5() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3691,12 +3466,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NewSingleLineElements_ExistingElements_ExistingInitializer6() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NewSingleLineElements_ExistingElements_ExistingInitializer6() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3730,12 +3503,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NewSingleLineElements_ExistingElements_ExistingInitializer7() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NewSingleLineElements_ExistingElements_ExistingInitializer7() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3768,12 +3539,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NewSingleLineElements_ExistingElements_ExistingInitializer8() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NewSingleLineElements_ExistingElements_ExistingInitializer8() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3804,12 +3573,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NewSingleLineElements_ExistingElements_ExistingInitializer9() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NewSingleLineElements_ExistingElements_ExistingInitializer9() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3839,12 +3606,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NewSingleLineElements_ExistingElements_ExistingInitializer10() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NewSingleLineElements_ExistingElements_ExistingInitializer10() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3874,12 +3639,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NewMultiLineElements_ExistingElements_ExistingInitializer1() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NewMultiLineElements_ExistingElements_ExistingInitializer1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3909,12 +3672,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NewMultiLineElements_ExistingElements_ExistingInitializer2() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NewMultiLineElements_ExistingElements_ExistingInitializer2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3945,12 +3706,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NewMultiLineElements_ExistingElements_ExistingInitializer3() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NewMultiLineElements_ExistingElements_ExistingInitializer3() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3983,12 +3742,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NewMultiLineElements_ExistingElements_ExistingInitializer4() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NewMultiLineElements_ExistingElements_ExistingInitializer4() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4019,12 +3776,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NewMultiLineElements_ExistingElements_ExistingInitializer5() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NewMultiLineElements_ExistingElements_ExistingInitializer5() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4056,12 +3811,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NewMultiLineElements_ExistingElements_ExistingInitializer6() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NewMultiLineElements_ExistingElements_ExistingInitializer6() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4097,12 +3850,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NewMultiLineElements_ExistingElements_ExistingInitializer7() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NewMultiLineElements_ExistingElements_ExistingInitializer7() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4137,12 +3888,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NewMultiLineElements_ExistingElements_ExistingInitializer8() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NewMultiLineElements_ExistingElements_ExistingInitializer8() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4175,12 +3924,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NewMultiLineElements_ExistingElements_ExistingInitializer9() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NewMultiLineElements_ExistingElements_ExistingInitializer9() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4211,12 +3958,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NewMultiLineElements_ExistingElements_ExistingInitializer10() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NewMultiLineElements_ExistingElements_ExistingInitializer10() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4247,12 +3992,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NewMultiLineElements_NoInitializer1() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NewMultiLineElements_NoInitializer1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4281,12 +4024,10 @@ void M() } } """); - } [Fact] - public async Task TestReplacementLocation_NewMultiLineElements_NoInitializer2() - { - await TestInRegularAndScriptAsync( + public Task TestReplacementLocation_NewMultiLineElements_NoInitializer2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4319,12 +4060,10 @@ void M() } } """); - } [Fact] - public async Task TestNoMultiLineEvenWhenLongIfAllElementsAlreadyPresent() - { - await new VerifyCS.Test + public Task TestNoMultiLineEvenWhenLongIfAllElementsAlreadyPresent() + => new VerifyCS.Test { TestCode = """ using System; @@ -4384,12 +4123,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestCapacity1() - { - await TestInRegularAndScriptAsync( + public Task TestCapacity1() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4412,12 +4149,10 @@ void M() } } """); - } [Fact] - public async Task TestCapacity2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestCapacity2() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4429,12 +4164,10 @@ void M() } } """); - } [Fact] - public async Task TestCapacity3() - { - await TestInRegularAndScriptAsync( + public Task TestCapacity3() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4458,12 +4191,10 @@ void M() } } """); - } [Fact] - public async Task TestCapacity4() - { - await TestInRegularAndScriptAsync( + public Task TestCapacity4() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4490,12 +4221,10 @@ void M() } } """); - } [Fact] - public async Task TestCapacity5() - { - await TestInRegularAndScriptAsync( + public Task TestCapacity5() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4520,12 +4249,10 @@ void M(int[] x) } } """); - } [Fact] - public async Task TestCapacity6() - { - await TestInRegularAndScriptAsync( + public Task TestCapacity6() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4550,12 +4277,10 @@ void M(int[] x) } } """); - } [Fact] - public async Task TestCapacity7() - { - await TestInRegularAndScriptAsync( + public Task TestCapacity7() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4581,12 +4306,10 @@ void M(int[] x) } } """); - } [Fact] - public async Task TestCapacity8() - { - await TestInRegularAndScriptAsync( + public Task TestCapacity8() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4613,12 +4336,10 @@ void M(int[] x, int[] y) } } """); - } [Fact] - public async Task TestCapacity9() - { - await TestInRegularAndScriptAsync( + public Task TestCapacity9() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4645,12 +4366,10 @@ void M(int[] x, int[] y) } } """); - } [Fact] - public async Task TestCapacity10() - { - await TestInRegularAndScriptAsync( + public Task TestCapacity10() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4677,12 +4396,10 @@ void M(int[] x, IList y) } } """); - } [Fact] - public async Task TestCapacity11() - { - await TestInRegularAndScriptAsync( + public Task TestCapacity11() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; using System.Linq; @@ -4711,12 +4428,10 @@ void M(int[] x, IEnumerable y) } } """); - } [Fact] - public async Task TestCapacity12() - { - await TestInRegularAndScriptAsync( + public Task TestCapacity12() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; using System.Linq; @@ -4743,12 +4458,10 @@ void M(int[] x, IEnumerable y) } } """); - } [Fact] - public async Task TestCapacity13() - { - await TestInRegularAndScriptAsync( + public Task TestCapacity13() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4774,12 +4487,10 @@ void M(int[] x) } } """); - } [Fact] - public async Task TestCapacity14() - { - await TestInRegularAndScriptAsync( + public Task TestCapacity14() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; using System.Linq; @@ -4808,12 +4519,10 @@ void M(int[] x, IEnumerable y) } } """); - } [Fact] - public async Task TestCapacity15() - { - await TestInRegularAndScriptAsync( + public Task TestCapacity15() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; using System.Linq; @@ -4848,12 +4557,10 @@ void M(int[] x, IEnumerable y) } } """); - } [Fact] - public async Task TestCapacity16() - { - await TestInRegularAndScriptAsync( + public Task TestCapacity16() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4882,12 +4589,10 @@ void M(int[] x, IEnumerable y) } } """); - } [Fact] - public async Task TestCapacity17() - { - await TestInRegularAndScriptAsync( + public Task TestCapacity17() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4916,12 +4621,10 @@ void M(int[] x, IEnumerable y) } } """); - } [Fact] - public async Task TestCapacity18() - { - await TestInRegularAndScriptAsync( + public Task TestCapacity18() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4950,12 +4653,10 @@ void M(int[] x, int[] y) } } """); - } [Fact] - public async Task TestCapacity19() - { - await TestInRegularAndScriptAsync( + public Task TestCapacity19() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -4980,12 +4681,10 @@ void M(int[] x, int[] y) } } """); - } [Fact] - public async Task TestCapacity20() - { - await TestInRegularAndScriptAsync( + public Task TestCapacity20() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; using System.Linq; @@ -5013,12 +4712,10 @@ void M(int[] x, IEnumerable y) } } """); - } [Fact] - public async Task TestCapacity21() - { - await TestInRegularAndScriptAsync( + public Task TestCapacity21() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; using System.Linq; @@ -5049,12 +4746,10 @@ void M(int[] x, IEnumerable y) } } """); - } [Fact] - public async Task TestCapacity22() - { - await TestInRegularAndScriptAsync( + public Task TestCapacity22() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -5081,12 +4776,10 @@ void M(int[] x, IList y) } } """); - } [Fact] - public async Task TestCapacity23() - { - await TestInRegularAndScriptAsync( + public Task TestCapacity23() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -5119,12 +4812,10 @@ void M(int[] x, IList y) } } """); - } [Fact] - public async Task TestCapacity24() - { - await TestInRegularAndScriptAsync( + public Task TestCapacity24() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -5157,12 +4848,10 @@ void M(int[] x, IList y) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71012")] - public async Task TestInLambda() - { - await TestInRegularAndScriptAsync( + public Task TestInLambda() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -5189,12 +4878,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71012")] - public async Task TestNotInLambda1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotInLambda1() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -5208,12 +4895,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71012")] - public async Task TestNotInExpressionTree() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotInExpressionTree() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -5227,12 +4912,10 @@ void M() } } """); - } [Fact] - public async Task TestInDictionary_Empty() - { - await TestInRegularAndScriptAsync( + public Task TestInDictionary_Empty() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; class Program @@ -5253,12 +4936,10 @@ static void Main() } } """); - } [Fact] - public async Task TestInDictionary_NotEmpty() - { - await TestMissingInRegularAndScriptAsync( + public Task TestInDictionary_NotEmpty() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; class Program @@ -5269,12 +4950,10 @@ static void Main() } } """); - } [Fact] - public async Task TestInIEnumerableAndIncompatibleAdd_Empty() - { - await TestInRegularAndScriptAsync( + public Task TestInIEnumerableAndIncompatibleAdd_Empty() + => TestInRegularAndScriptAsync( """ using System.Collections; class Program @@ -5305,12 +4984,10 @@ public void Add(string s) { } IEnumerator IEnumerable.GetEnumerator() => null; } """); - } [Fact] - public async Task TestInIEnumerableAndIncompatibleAdd_NotEmpty() - { - await new VerifyCS.Test + public Task TestInIEnumerableAndIncompatibleAdd_NotEmpty() + => new VerifyCS.Test { ReferenceAssemblies = Testing.ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = """ @@ -5349,12 +5026,10 @@ public void Add(string s) { } OutputKind = OutputKind.DynamicallyLinkedLibrary, }, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71607")] - public async Task TestAddRangeOfCollectionExpression1() - { - await new VerifyCS.Test + public Task TestAddRangeOfCollectionExpression1() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -5386,12 +5061,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71607")] - public async Task TestAddRangeOfCollectionExpression2() - { - await new VerifyCS.Test + public Task TestAddRangeOfCollectionExpression2() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -5423,12 +5096,10 @@ void M(int[] x) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72169")] - public async Task TestInValueTuple1() - { - await new VerifyCS.Test + public Task TestInValueTuple1() + => new VerifyCS.Test { TestCode = """ @@ -5457,12 +5128,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72169")] - public async Task TestInValueTuple2() - { - await new VerifyCS.Test + public Task TestInValueTuple2() + => new VerifyCS.Test { TestCode = """ @@ -5491,12 +5160,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72169")] - public async Task TestInValueTuple3() - { - await new VerifyCS.Test + public Task TestInValueTuple3() + => new VerifyCS.Test { TestCode = """ @@ -5525,12 +5192,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72169")] - public async Task TestInValueTuple4() - { - await new VerifyCS.Test + public Task TestInValueTuple4() + => new VerifyCS.Test { TestCode = """ @@ -5569,12 +5234,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72169")] - public async Task TestInValueTuple5() - { - await new VerifyCS.Test + public Task TestInValueTuple5() + => new VerifyCS.Test { TestCode = """ @@ -5603,12 +5266,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72169")] - public async Task TestInValueTuple6() - { - await new VerifyCS.Test + public Task TestInValueTuple6() + => new VerifyCS.Test { TestCode = """ @@ -5637,12 +5298,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72169")] - public async Task TestInValueTuple7() - { - await new VerifyCS.Test + public Task TestInValueTuple7() + => new VerifyCS.Test { TestCode = """ @@ -5681,12 +5340,10 @@ class C LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72701")] - public async Task TestNotWithObservableCollection1() - { - await new VerifyCS.Test + public Task TestNotWithObservableCollection1() + => new VerifyCS.Test { TestCode = """ @@ -5705,12 +5362,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72701")] - public async Task TestNotWithObservableCollection2() - { - await new VerifyCS.Test + public Task TestNotWithObservableCollection2() + => new VerifyCS.Test { TestCode = """ @@ -5743,12 +5398,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72699")] - public async Task TestObjectCreationArgument1() - { - await new VerifyCS.Test + public Task TestObjectCreationArgument1() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -5777,12 +5430,10 @@ void M(int[] values) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72699")] - public async Task TestObjectCreationArgument2() - { - await new VerifyCS.Test + public Task TestObjectCreationArgument2() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -5811,12 +5462,10 @@ void M(int[] values) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73362")] - public async Task TestWithOverloadResolution1() - { - await new VerifyCS.Test + public Task TestWithOverloadResolution1() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -5865,12 +5514,10 @@ public class Class2 { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75894")] - public async Task TestNotOnDictionaryConstructor() - { - await new VerifyCS.Test + public Task TestNotOnDictionaryConstructor() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -5887,12 +5534,10 @@ void Main() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76092")] - public async Task TestNotOnSetAssignedToNonSet() - { - await new VerifyCS.Test + public Task TestNotOnSetAssignedToNonSet() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -5908,12 +5553,10 @@ void Main() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76092")] - public async Task TestOnSetAssignedToSet() - { - await new VerifyCS.Test + public Task TestOnSetAssignedToSet() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -5940,12 +5583,10 @@ void Main() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76683")] - public async Task TestNotOnStack() - { - await new VerifyCS.Test + public Task TestNotOnStack() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -5963,12 +5604,10 @@ Stack GetNumbers(T[] values) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/77962")] - public async Task TestNotOnBindingList() - { - await new VerifyCS.Test + public Task TestNotOnBindingList() + => new VerifyCS.Test { TestCode = """ using System.ComponentModel; @@ -5984,5 +5623,90 @@ BindingList GetNumbers(T[] values) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/79156")] + public Task TestNotWithConstructorArgNotValidAsAddArgument() + => new VerifyCS.Test + { + TestCode = """ + using System; + using System.Collections; + + Goo _ = new("goobar"); + + public class Goo(string s = "") : IEnumerable + { + public void Add(Bar b) { } + + IEnumerator IEnumerable.GetEnumerator() + => throw new NotImplementedException(); + } + + public class Bar { } + """, + LanguageVersion = LanguageVersion.CSharp12, + ReferenceAssemblies = ReferenceAssemblies.Net.Net80, + TestState = { OutputKind = OutputKind.ConsoleApplication }, + }.RunAsync(); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/79156")] + public Task TestWithConstructorArgValidAsAddArgument() + => new VerifyCS.Test + { + TestCode = """ + using System; + using System.Collections; + using System.Collections.Generic; + + IEnumerable bars = null; + Goo _ = [|new|](bars); + + public class Goo : IEnumerable + { + public Goo() { } + + public Goo(IEnumerable bars) + { + foreach (var bar in bars) + Add(bar); + } + + public void Add(Bar b) { } + + IEnumerator IEnumerable.GetEnumerator() + => throw new NotImplementedException(); + } + + public class Bar { } + """, + FixedCode = """ + using System; + using System.Collections; + using System.Collections.Generic; + + IEnumerable bars = null; + Goo _ = [.. bars]; + + public class Goo : IEnumerable + { + public Goo() { } + + public Goo(IEnumerable bars) + { + foreach (var bar in bars) + Add(bar); + } + + public void Add(Bar b) { } + + IEnumerator IEnumerable.GetEnumerator() + => throw new NotImplementedException(); + } + + public class Bar { } + """, + LanguageVersion = LanguageVersion.CSharp12, + ReferenceAssemblies = ReferenceAssemblies.Net.Net80, + TestState = { OutputKind = OutputKind.ConsoleApplication }, + }.RunAsync(); } diff --git a/src/Analyzers/CSharp/Tests/UseCompoundAssignment/UseCompoundAssignmentTests.cs b/src/Analyzers/CSharp/Tests/UseCompoundAssignment/UseCompoundAssignmentTests.cs index 11e55c5abc1cb..18cc9d6d92a4f 100644 --- a/src/Analyzers/CSharp/Tests/UseCompoundAssignment/UseCompoundAssignmentTests.cs +++ b/src/Analyzers/CSharp/Tests/UseCompoundAssignment/UseCompoundAssignmentTests.cs @@ -21,9 +21,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseCompoundAssignment; public sealed class UseCompoundAssignmentTests { [Fact] - public async Task TestAddExpression() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestAddExpression() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(int a) @@ -40,12 +39,10 @@ void M(int a) } } """); - } [Fact] - public async Task TestSubtractExpression() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestSubtractExpression() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(int a) @@ -62,12 +59,10 @@ void M(int a) } } """); - } [Fact] - public async Task TestMultiplyExpression() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestMultiplyExpression() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(int a) @@ -84,12 +79,10 @@ void M(int a) } } """); - } [Fact] - public async Task TestDivideExpression() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestDivideExpression() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(int a) @@ -106,12 +99,10 @@ void M(int a) } } """); - } [Fact] - public async Task TestModuloExpression() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestModuloExpression() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(int a) @@ -128,12 +119,10 @@ void M(int a) } } """); - } [Fact] - public async Task TestBitwiseAndExpression() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestBitwiseAndExpression() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(int a) @@ -150,12 +139,10 @@ void M(int a) } } """); - } [Fact] - public async Task TestExclusiveOrExpression() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestExclusiveOrExpression() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(int a) @@ -172,12 +159,10 @@ void M(int a) } } """); - } [Fact] - public async Task TestBitwiseOrExpression() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestBitwiseOrExpression() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(int a) @@ -194,12 +179,10 @@ void M(int a) } } """); - } [Fact] - public async Task TestLeftShiftExpression() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestLeftShiftExpression() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(int a) @@ -216,12 +199,10 @@ void M(int a) } } """); - } [Fact] - public async Task TestRightShiftExpression() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestRightShiftExpression() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(int a) @@ -238,12 +219,10 @@ void M(int a) } } """); - } [Fact] - public async Task TestCoalesceExpressionCSharp8OrGreater() - { - await new VerifyCS.Test() + public Task TestCoalesceExpressionCSharp8OrGreater() + => new VerifyCS.Test() { TestCode = """ public class C @@ -265,12 +244,12 @@ void M(int? a) """, LanguageVersion = LanguageVersion.CSharp8 }.RunAsync(); - } [Fact] - public async Task TestCoalesceExpressionCSharp7() - { - var code = """ + public Task TestCoalesceExpressionCSharp7() + => new VerifyCS.Test() + { + TestCode = """ public class C { void M(int? a) @@ -278,19 +257,15 @@ void M(int? a) a = a ?? 10; } } - """; - - await new VerifyCS.Test() - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp7_3 }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36467")] - public async Task TestNotSuggestedWhenRightHandIsThrowExpression() - { - var code = """ + public Task TestNotSuggestedWhenRightHandIsThrowExpression() + => new VerifyCS.Test() + { + TestCode = """ using System; public class C { @@ -299,19 +274,13 @@ void M(int? a) a = a ?? throw new Exception(); } } - """; - - await new VerifyCS.Test() - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp8 }.RunAsync(); - } [Fact] - public async Task TestField() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestField() + => VerifyCS.VerifyCodeFixAsync(""" public class C { int a; @@ -332,12 +301,10 @@ void M() } } """); - } [Fact] - public async Task TestFieldWithThis() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestFieldWithThis() + => VerifyCS.VerifyCodeFixAsync(""" public class C { int a; @@ -358,12 +325,10 @@ void M() } } """); - } [Fact] - public async Task TestTriviaInsensitive() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestTriviaInsensitive() + => VerifyCS.VerifyCodeFixAsync(""" public class C { int a; @@ -384,12 +349,10 @@ void M() } } """); - } [Fact] - public async Task TestStaticFieldThroughType() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestStaticFieldThroughType() + => VerifyCS.VerifyCodeFixAsync(""" public class C { static int a; @@ -410,12 +373,10 @@ void M() } } """); - } [Fact] - public async Task TestStaticFieldThroughNamespaceAndType() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestStaticFieldThroughNamespaceAndType() + => VerifyCS.VerifyCodeFixAsync(""" namespace NS { public class C @@ -442,12 +403,10 @@ void M() } } """); - } [Fact] - public async Task TestParenthesized() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestParenthesized() + => VerifyCS.VerifyCodeFixAsync(""" public class C { int a; @@ -468,12 +427,10 @@ void M() } } """); - } [Fact] - public async Task TestThroughBase() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestThroughBase() + => VerifyCS.VerifyCodeFixAsync(""" public class C { public int a; @@ -500,12 +457,10 @@ void M() } } """); - } [Fact] - public async Task TestMultiAccess() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestMultiAccess() + => VerifyCS.VerifyCodeFixAsync(""" public class C { public int a; @@ -536,12 +491,10 @@ void M() } } """); - } [Fact] - public async Task TestOnTopLevelProp1() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestOnTopLevelProp1() + => VerifyCS.VerifyCodeFixAsync(""" public class C { int a { get; set; } @@ -562,12 +515,10 @@ void M() } } """); - } [Fact] - public async Task TestOnTopLevelProp2() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestOnTopLevelProp2() + => VerifyCS.VerifyCodeFixAsync(""" public class C { int a { get; set; } @@ -588,12 +539,10 @@ void M() } } """); - } [Fact] - public async Task TestOnTopLevelProp3() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestOnTopLevelProp3() + => VerifyCS.VerifyCodeFixAsync(""" public class C { int a { get; set; } @@ -614,7 +563,6 @@ void M() } } """); - } [Fact] public async Task TestNotOnTopLevelRefProp() @@ -757,9 +705,8 @@ void M() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35870")] - public async Task TestRightExpressionOnNextLine() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestRightExpressionOnNextLine() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(int a) @@ -777,12 +724,10 @@ void M(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35870")] - public async Task TestRightExpressionSeparatedWithSeveralLines() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestRightExpressionSeparatedWithSeveralLines() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(int a) @@ -801,12 +746,10 @@ void M(int a) } } """); - } [Fact] - public async Task TestTrivia() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestTrivia() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(int a) @@ -825,12 +768,10 @@ void M(int a) } } """); - } [Fact] - public async Task TestTrivia2() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestTrivia2() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(int a) @@ -847,12 +788,10 @@ void M(int a) } } """); - } [Fact] - public async Task TestFixAll() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestFixAll() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(int a, int b) @@ -871,12 +810,10 @@ void M(int a, int b) } } """); - } [Fact] - public async Task TestNestedAssignment() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestNestedAssignment() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(int a, int b) @@ -893,7 +830,6 @@ void M(int a, int b) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33382")] public async Task TestNotOnObjectInitializer() @@ -938,9 +874,10 @@ InsertionPoint Up() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49294")] - public async Task TestNotOnRecord() - { - var code = """ + public Task TestNotOnRecord() + => new VerifyCS.Test + { + TestCode = """ record InsertionPoint(int level) { InsertionPoint Up() @@ -951,20 +888,14 @@ InsertionPoint Up() }; } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp9, ReferenceAssemblies = ReferenceAssemblies.Net.Net60 }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38137")] - public async Task TestParenthesizedExpression() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestParenthesizedExpression() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(int a) @@ -981,12 +912,10 @@ void M(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38054")] - public async Task TestIncrement() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestIncrement() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(int a) @@ -1003,12 +932,10 @@ void M(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38054")] - public async Task TestDecrement() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestDecrement() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(int a) @@ -1025,12 +952,10 @@ void M(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38054")] - public async Task TestMinusIncrement() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestMinusIncrement() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(int a) @@ -1047,12 +972,10 @@ void M(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38054")] - public async Task TestIncrementDouble() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestIncrementDouble() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(double a) @@ -1069,12 +992,10 @@ void M(double a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38054")] - public async Task TestIncrementNotOnString() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestIncrementNotOnString() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(string a) @@ -1091,12 +1012,10 @@ void M(string a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38054")] - public async Task TestIncrementChar() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestIncrementChar() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(char a) @@ -1113,12 +1032,10 @@ void M(char a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38054")] - public async Task TestIncrementEnum() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestIncrementEnum() + => VerifyCS.VerifyCodeFixAsync(""" public enum E {} public class C { @@ -1137,12 +1054,10 @@ void M(E a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38054")] - public async Task TestIncrementDecimal() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestIncrementDecimal() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(decimal a) @@ -1159,7 +1074,6 @@ void M(decimal a) } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/38054")] [InlineData("byte")] @@ -1167,9 +1081,8 @@ void M(decimal a) [InlineData("long")] [InlineData("float")] [InlineData("decimal")] - public async Task TestIncrementLiteralConversion(string typeName) - { - await new VerifyCS.Test() + public Task TestIncrementLiteralConversion(string typeName) + => new VerifyCS.Test() { TestCode = $$""" public class C @@ -1191,7 +1104,6 @@ void M({{typeName}} a) """, CompilerDiagnostics = CompilerDiagnostics.None }.RunAsync(); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/38054")] [InlineData("byte")] @@ -1199,9 +1111,8 @@ void M({{typeName}} a) [InlineData("long")] [InlineData("float")] [InlineData("decimal")] - public async Task TestIncrementImplicitLiteralConversion(string typeName) - { - await new VerifyCS.Test() + public Task TestIncrementImplicitLiteralConversion(string typeName) + => new VerifyCS.Test() { TestCode = $$""" public class C @@ -1223,12 +1134,10 @@ void M({{typeName}} a) """, CompilerDiagnostics = CompilerDiagnostics.None }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38054")] - public async Task TestIncrementLoopVariable() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestIncrementLoopVariable() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M() @@ -1249,12 +1158,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53969")] - public async Task TestIncrementInExpressionContext() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestIncrementInExpressionContext() + => VerifyCS.VerifyCodeFixAsync(""" public class C { void M(int i) @@ -1271,7 +1178,6 @@ void M(int i) } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/53969")] [InlineData("switch($$) { }")] @@ -1338,9 +1244,8 @@ int M(int i) [InlineData( "M( /* Before */ i [|=|] i - 1 /* After */ );", "M( /* Before */ --i /* After */ );")] - public async Task TestTriviaPreserved(string before, string after) - { - await VerifyCS.VerifyCodeFixAsync($$""" + public Task TestTriviaPreserved(string before, string after) + => VerifyCS.VerifyCodeFixAsync($$""" public class C { void M(int i) @@ -1357,12 +1262,10 @@ void M(int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70651")] - public async Task TestIncrementWithUserDefinedOperators_IncrementOperatorNotDefined() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestIncrementWithUserDefinedOperators_IncrementOperatorNotDefined() + => VerifyCS.VerifyCodeFixAsync(""" class C { int data; @@ -1405,12 +1308,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70651")] - public async Task TestIncrementWithUserDefinedOperators_IncrementOperatorDefined() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestIncrementWithUserDefinedOperators_IncrementOperatorDefined() + => VerifyCS.VerifyCodeFixAsync(""" class C { int data; @@ -1463,12 +1364,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70651")] - public async Task TestDecrementWithUserDefinedOperators_DecrementOperatorNotDefined() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestDecrementWithUserDefinedOperators_DecrementOperatorNotDefined() + => VerifyCS.VerifyCodeFixAsync(""" class C { int data; @@ -1511,12 +1410,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70651")] - public async Task TestDecrementWithUserDefinedOperators_DecrementOperatorDefined() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestDecrementWithUserDefinedOperators_DecrementOperatorDefined() + => VerifyCS.VerifyCodeFixAsync(""" class C { int data; @@ -1569,12 +1466,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76633")] - public async Task TestFieldKeyword1() - { - await new VerifyCS.Test + public Task TestFieldKeyword1() + => new VerifyCS.Test { TestCode = """ public class C @@ -1604,5 +1499,4 @@ int M """, LanguageVersion = LanguageVersion.Preview, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UseCompoundAssignment/UseCompoundCoalesceAssignmentTests.cs b/src/Analyzers/CSharp/Tests/UseCompoundAssignment/UseCompoundCoalesceAssignmentTests.cs index d992b0edcbd34..bbd58c7acdd9b 100644 --- a/src/Analyzers/CSharp/Tests/UseCompoundAssignment/UseCompoundCoalesceAssignmentTests.cs +++ b/src/Analyzers/CSharp/Tests/UseCompoundAssignment/UseCompoundCoalesceAssignmentTests.cs @@ -20,28 +20,23 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseCompoundAssignment; [Trait(Traits.Feature, Traits.Features.CodeActionsUseCompoundAssignment)] public sealed class UseCompoundCoalesceAssignmentTests { - private static async Task TestInRegularAndScriptAsync(string testCode, string fixedCode) - { - await new VerifyCS.Test + private static Task TestInRegularAndScriptAsync(string testCode, string fixedCode) + => new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, }.RunAsync(); - } - private static async Task TestMissingAsync(string testCode, LanguageVersion languageVersion = LanguageVersion.CSharp8) - { - await new VerifyCS.Test + private static Task TestMissingAsync(string testCode, LanguageVersion languageVersion = LanguageVersion.CSharp8) + => new VerifyCS.Test { TestCode = testCode, LanguageVersion = languageVersion, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38059")] - public async Task TestBaseCase() - { - await TestInRegularAndScriptAsync( + public Task TestBaseCase() + => TestInRegularAndScriptAsync( """ class Program { @@ -56,12 +51,10 @@ class Program private static string Goo => s_goo ??= new string('c', 42); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44793")] - public async Task TestMissingBeforeCSharp8() - { - await TestMissingAsync( + public Task TestMissingBeforeCSharp8() + => TestMissingAsync( """ class Program { @@ -69,12 +62,10 @@ class Program private static string Goo => s_goo ?? (s_goo = new string('c', 42)); } """, LanguageVersion.CSharp7_3); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38059")] - public async Task TestRightMustBeParenthesized() - { - await TestMissingAsync( + public Task TestRightMustBeParenthesized() + => TestMissingAsync( """ class Program { @@ -82,12 +73,10 @@ class Program private static string Goo => {|CS0131:s_goo ?? s_goo|} = new string('c', 42); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38059")] - public async Task TestRightMustBeAssignment() - { - await TestMissingAsync( + public Task TestRightMustBeAssignment() + => TestMissingAsync( """ class Program { @@ -95,12 +84,10 @@ class Program private static string Goo => {|CS0019:s_goo ?? (s_goo == new string('c', 42))|}; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38059")] - public async Task TestRightMustBeSimpleAssignment() - { - await TestMissingAsync( + public Task TestRightMustBeSimpleAssignment() + => TestMissingAsync( """ class Program { @@ -108,12 +95,10 @@ class Program private static string Goo => s_goo ?? (s_goo ??= new string('c', 42)); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38059")] - public async Task TestShapesMustBeTheSame() - { - await TestMissingAsync( + public Task TestShapesMustBeTheSame() + => TestMissingAsync( """ class Program { @@ -122,12 +107,10 @@ class Program private static string Goo => s_goo ?? (s_goo2 = new string('c', 42)); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38059")] - public async Task TestNoSideEffects1() - { - await TestMissingAsync( + public Task TestNoSideEffects1() + => TestMissingAsync( """ class Program { @@ -135,12 +118,10 @@ class Program private static string Goo => s_goo.GetType() ?? ({|CS0131:s_goo.GetType()|} = new string('c', 42)); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38059")] - public async Task TestNoSideEffects2() - { - await TestInRegularAndScriptAsync( + public Task TestNoSideEffects2() + => TestInRegularAndScriptAsync( """ class Program { @@ -155,12 +136,10 @@ class Program private string Goo => this.goo ??= new string('c', 42); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38059")] - public async Task TestNullableValueType() - { - await TestInRegularAndScriptAsync( + public Task TestNullableValueType() + => TestInRegularAndScriptAsync( """ class Program { @@ -181,12 +160,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38059")] - public async Task TestCastIfWouldAffectSemantics() - { - await TestInRegularAndScriptAsync( + public Task TestCastIfWouldAffectSemantics() + => TestInRegularAndScriptAsync( """ using System; class C @@ -215,12 +192,10 @@ static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38059")] - public async Task TestDoNotCastIfNotNecessary() - { - await TestInRegularAndScriptAsync( + public Task TestDoNotCastIfNotNecessary() + => TestInRegularAndScriptAsync( """ using System; class C @@ -247,12 +222,10 @@ static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32985")] - public async Task TestIfStatement1() - { - await TestInRegularAndScriptAsync( + public Task TestIfStatement1() + => TestInRegularAndScriptAsync( """ using System; class C @@ -276,12 +249,10 @@ static void Main(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32985")] - public async Task TestIfStatement_NotBeforeCSharp8() - { - await TestMissingAsync( + public Task TestIfStatement_NotBeforeCSharp8() + => TestMissingAsync( """ using System; class C @@ -295,12 +266,10 @@ static void Main(object o) } } """, LanguageVersion.CSharp7_3); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32985")] - public async Task TestIfStatement_NotWithElseClause() - { - await TestMissingAsync( + public Task TestIfStatement_NotWithElseClause() + => TestMissingAsync( """ using System; class C @@ -318,12 +287,10 @@ static void Main(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32985")] - public async Task TestIfStatementWithoutBlock() - { - await TestInRegularAndScriptAsync( + public Task TestIfStatementWithoutBlock() + => TestInRegularAndScriptAsync( """ using System; class C @@ -345,12 +312,10 @@ static void Main(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32985")] - public async Task TestIfStatement_WithEmptyBlock() - { - await TestMissingAsync( + public Task TestIfStatement_WithEmptyBlock() + => TestMissingAsync( """ using System; class C @@ -363,12 +328,10 @@ static void Main(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32985")] - public async Task TestIfStatement_WithMultipleStatements() - { - await TestMissingAsync( + public Task TestIfStatement_WithMultipleStatements() + => TestMissingAsync( """ using System; class C @@ -383,12 +346,10 @@ static void Main(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32985")] - public async Task TestIfStatement_EqualsEqualsCheck() - { - await TestInRegularAndScriptAsync( + public Task TestIfStatement_EqualsEqualsCheck() + => TestInRegularAndScriptAsync( """ using System; class C @@ -412,12 +373,10 @@ static void Main(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32985")] - public async Task TestIfStatement_ReferenceEqualsCheck1() - { - await TestInRegularAndScriptAsync( + public Task TestIfStatement_ReferenceEqualsCheck1() + => TestInRegularAndScriptAsync( """ using System; class C @@ -441,12 +400,10 @@ static void Main(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32985")] - public async Task TestIfStatement_ReferenceEqualsCheck2() - { - await TestInRegularAndScriptAsync( + public Task TestIfStatement_ReferenceEqualsCheck2() + => TestInRegularAndScriptAsync( """ using System; class C @@ -470,12 +427,10 @@ static void Main(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32985")] - public async Task TestIfStatement_ReferenceEqualsCheck3() - { - await TestInRegularAndScriptAsync( + public Task TestIfStatement_ReferenceEqualsCheck3() + => TestInRegularAndScriptAsync( """ using System; class C @@ -499,12 +454,10 @@ static void Main(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32985")] - public async Task TestIfStatement_ReferenceEqualsCheck4() - { - await TestMissingAsync( + public Task TestIfStatement_ReferenceEqualsCheck4() + => TestMissingAsync( """ using System; class C @@ -518,12 +471,10 @@ static void Main(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32985")] - public async Task TestIfStatement_NotSimpleAssignment() - { - await TestMissingAsync( + public Task TestIfStatement_NotSimpleAssignment() + => TestMissingAsync( """ using System; class C @@ -537,12 +488,10 @@ static void Main(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32985")] - public async Task TestIfStatement_OverloadedEquals_OkForString() - { - await TestInRegularAndScriptAsync( + public Task TestIfStatement_OverloadedEquals_OkForString() + => TestInRegularAndScriptAsync( """ using System; class C @@ -566,12 +515,10 @@ static void Main(string o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32985")] - public async Task TestIfStatement_OverloadedEquals() - { - await TestMissingAsync( + public Task TestIfStatement_OverloadedEquals() + => TestMissingAsync( """ using System; @@ -592,12 +539,10 @@ static void Main(X o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32985")] - public async Task TestIfStatement_AssignmentToDifferentValue() - { - await TestMissingAsync( + public Task TestIfStatement_AssignmentToDifferentValue() + => TestMissingAsync( """ using System; @@ -612,12 +557,10 @@ static void Main(object o1, object o2) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32985")] - public async Task TestIfStatement_SideEffects1() - { - await TestMissingAsync( + public Task TestIfStatement_SideEffects1() + => TestMissingAsync( """ using System; @@ -634,12 +577,10 @@ static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32985")] - public async Task TestIfStatement_SideEffects2() - { - await TestInRegularAndScriptAsync( + public Task TestIfStatement_SideEffects2() + => TestInRegularAndScriptAsync( """ using System; class C @@ -663,12 +604,10 @@ static void Main(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32985")] - public async Task TestIfStatement_Trivia1() - { - await TestInRegularAndScriptAsync( + public Task TestIfStatement_Trivia1() + => TestInRegularAndScriptAsync( """ using System; class C @@ -694,12 +633,10 @@ static void Main(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32985")] - public async Task TestIfStatement_Trivia2() - { - await TestInRegularAndScriptAsync( + public Task TestIfStatement_Trivia2() + => TestInRegularAndScriptAsync( """ using System; class C @@ -725,12 +662,10 @@ static void Main(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32985")] - public async Task TestIfStatement_Trivia3() - { - await TestInRegularAndScriptAsync( + public Task TestIfStatement_Trivia3() + => TestInRegularAndScriptAsync( """ using System; class C @@ -758,12 +693,10 @@ static void Main(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63552")] - public async Task TestIfStatementWithPreprocessorBlock1() - { - await TestMissingAsync( + public Task TestIfStatementWithPreprocessorBlock1() + => TestMissingAsync( """ using System; class C @@ -779,12 +712,10 @@ static void Main(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63552")] - public async Task TestIfStatementWithPreprocessorBlock2() - { - await TestMissingAsync( + public Task TestIfStatementWithPreprocessorBlock2() + => TestMissingAsync( """ using System; class C @@ -801,12 +732,10 @@ static void Main(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63552")] - public async Task TestIfStatementWithPreprocessorBlock3() - { - await TestMissingAsync( + public Task TestIfStatementWithPreprocessorBlock3() + => TestMissingAsync( """ using System; class C @@ -824,12 +753,10 @@ static void Main(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63552")] - public async Task TestIfStatementWithPreprocessorBlock4() - { - await TestMissingAsync( + public Task TestIfStatementWithPreprocessorBlock4() + => TestMissingAsync( """ using System; class C @@ -847,12 +774,10 @@ static void Main(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63552")] - public async Task TestIfStatementWithPreprocessorBlock5() - { - await TestMissingAsync( + public Task TestIfStatementWithPreprocessorBlock5() + => TestMissingAsync( """ using System; class C @@ -870,12 +795,10 @@ static void Main(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63552")] - public async Task TestIfStatementWithPreprocessorBlock6() - { - await TestMissingAsync( + public Task TestIfStatementWithPreprocessorBlock6() + => TestMissingAsync( """ using System; class C @@ -893,12 +816,10 @@ static void Main(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63552")] - public async Task TestIfStatementWithPreprocessorBlock7() - { - await TestMissingAsync( + public Task TestIfStatementWithPreprocessorBlock7() + => TestMissingAsync( """ using System; class C @@ -912,12 +833,10 @@ static void Main(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63552")] - public async Task TestIfStatementWithPreprocessorBlock8() - { - await TestMissingAsync( + public Task TestIfStatementWithPreprocessorBlock8() + => TestMissingAsync( """ using System; class C @@ -933,17 +852,10 @@ static void Main(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/62473")] - public async Task TestPointerCannotUseCoalesceAssignment() - { - // The purpose of this test is to keep track of whether the language - // allows ??= for pointers in future. It should be kept in 'Preview'. - // If the test failed because language added support and this is no longer - // an error. The behavior for test 'TestPointer' below should be updated as well to suggest ??= - // Note that, when ??= is supported for pointers, the analyzer should check the language version which supports it. - await TestMissingAsync(""" + public Task TestPointerCannotUseCoalesceAssignment() + => TestMissingAsync(""" unsafe class Program { private static void Main() @@ -955,12 +867,10 @@ private static void Main() static byte* Get() => null; } """, LanguageVersion.CSharp12); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/62473")] - public async Task TestPointer() - { - await TestMissingAsync(""" + public Task TestPointer() + => TestMissingAsync(""" unsafe class Program { private static void Main() @@ -975,12 +885,10 @@ private static void Main() static byte* Get() => null; } """, LanguageVersion.CSharp12); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63551")] - public async Task TestFunctionPointer() - { - await TestMissingAsync(""" + public Task TestFunctionPointer() + => TestMissingAsync(""" using System.Runtime.InteropServices; public unsafe class C { [DllImport("A")] @@ -998,12 +906,10 @@ public unsafe class C { } } """, LanguageVersion.CSharp12); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76633")] - public async Task TestFieldKeyword1() - { - await new VerifyCS.Test + public Task TestFieldKeyword1() + => new VerifyCS.Test { TestCode = """ using System; @@ -1040,5 +946,4 @@ string Goo """, LanguageVersion = LanguageVersion.Preview, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UseConditionalExpression/UseConditionalExpressionForAssignmentTests.cs b/src/Analyzers/CSharp/Tests/UseConditionalExpression/UseConditionalExpressionForAssignmentTests.cs index 29193e52345ca..423cf3781fc34 100644 --- a/src/Analyzers/CSharp/Tests/UseConditionalExpression/UseConditionalExpressionForAssignmentTests.cs +++ b/src/Analyzers/CSharp/Tests/UseConditionalExpression/UseConditionalExpressionForAssignmentTests.cs @@ -38,14 +38,13 @@ private static async Task TestMissingAsync( await test.RunAsync(); } - private static async Task TestInRegularAndScript1Async( + private static Task TestInRegularAndScript1Async( [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string testCode, [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string fixedCode, LanguageVersion languageVersion = LanguageVersion.CSharp8, OptionsCollection? options = null, string? equivalenceKey = null) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, @@ -53,7 +52,6 @@ private static async Task TestInRegularAndScript1Async( CodeActionEquivalenceKey = equivalenceKey, Options = { options }, }.RunAsync(); - } private static readonly OptionsCollection PreferImplicitTypeAlways = new(LanguageNames.CSharp) { @@ -63,9 +61,8 @@ private static async Task TestInRegularAndScript1Async( }; [Fact] - public async Task TestOnSimpleAssignment() - { - await TestInRegularAndScript1Async( + public Task TestOnSimpleAssignment() + => TestInRegularAndScript1Async( """ class C { @@ -91,12 +88,10 @@ void M(int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestOnSimpleAssignment_Throw1() - { - await TestInRegularAndScript1Async( + public Task TestOnSimpleAssignment_Throw1() + => TestInRegularAndScript1Async( """ class C { @@ -122,12 +117,10 @@ void M(int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestOnSimpleAssignment_Throw2() - { - await TestInRegularAndScript1Async( + public Task TestOnSimpleAssignment_Throw2() + => TestInRegularAndScript1Async( """ class C { @@ -153,12 +146,10 @@ void M(int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestNotWithTwoThrows() - { - await TestMissingAsync( + public Task TestNotWithTwoThrows() + => TestMissingAsync( """ class C { @@ -175,12 +166,10 @@ void M(int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestNotOnSimpleAssignment_Throw1_CSharp6() - { - await TestMissingAsync( + public Task TestNotOnSimpleAssignment_Throw1_CSharp6() + => TestMissingAsync( """ class C { @@ -197,12 +186,10 @@ void M(int i) } } """, LanguageVersion.CSharp6); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestWithSimpleThrow() - { - await TestMissingAsync( + public Task TestWithSimpleThrow() + => TestMissingAsync( """ class C { @@ -219,12 +206,10 @@ void M(int i) } } """); - } [Fact] - public async Task TestOnSimpleAssignmentNoBlocks() - { - await TestInRegularAndScript1Async( + public Task TestOnSimpleAssignmentNoBlocks() + => TestInRegularAndScript1Async( """ class C { @@ -246,12 +231,10 @@ void M(int i) } } """); - } [Fact] - public async Task TestOnSimpleAssignmentNoBlocks_NotInBlock() - { - await TestInRegularAndScript1Async( + public Task TestOnSimpleAssignmentNoBlocks_NotInBlock() + => TestInRegularAndScript1Async( """ class C { @@ -275,12 +258,10 @@ void M(int i) } } """); - } [Fact] - public async Task TestNotOnSimpleAssignmentToDifferentTargets() - { - await TestMissingAsync( + public Task TestNotOnSimpleAssignmentToDifferentTargets() + => TestMissingAsync( """ class C { @@ -297,12 +278,10 @@ void M(int i, int j) } } """); - } [Fact] - public async Task TestOnAssignmentToUndefinedField() - { - await TestInRegularAndScript1Async( + public Task TestOnAssignmentToUndefinedField() + => TestInRegularAndScript1Async( """ class C { @@ -328,12 +307,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestOnAssignmentToUndefinedField_Throw() - { - await TestInRegularAndScript1Async( + public Task TestOnAssignmentToUndefinedField_Throw() + => TestInRegularAndScript1Async( """ class C { @@ -359,12 +336,10 @@ void M() } } """); - } [Fact] - public async Task TestOnNonUniformTargetSyntax() - { - await TestInRegularAndScript1Async( + public Task TestOnNonUniformTargetSyntax() + => TestInRegularAndScript1Async( """ class C { @@ -394,12 +369,10 @@ void M() } } """); - } [Fact] - public async Task TestOnAssignmentToDefinedField() - { - await TestInRegularAndScript1Async( + public Task TestOnAssignmentToDefinedField() + => TestInRegularAndScript1Async( """ class C { @@ -429,12 +402,10 @@ void M() } } """); - } [Fact] - public async Task TestOnAssignmentToAboveLocalNoInitializer() - { - await TestInRegularAndScript1Async( + public Task TestOnAssignmentToAboveLocalNoInitializer() + => TestInRegularAndScript1Async( """ class C { @@ -461,12 +432,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestOnAssignmentToAboveLocalNoInitializer_Throw1() - { - await TestInRegularAndScript1Async( + public Task TestOnAssignmentToAboveLocalNoInitializer_Throw1() + => TestInRegularAndScript1Async( """ class C { @@ -493,12 +462,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestOnAssignmentToAboveLocalNoInitializer_Throw2() - { - await TestInRegularAndScript1Async( + public Task TestOnAssignmentToAboveLocalNoInitializer_Throw2() + => TestInRegularAndScript1Async( """ class C { @@ -525,12 +492,10 @@ void M() } } """); - } [Fact] - public async Task TestOnAssignmentToAboveLocalLiteralInitializer() - { - await TestInRegularAndScript1Async( + public Task TestOnAssignmentToAboveLocalLiteralInitializer() + => TestInRegularAndScript1Async( """ class C { @@ -557,12 +522,10 @@ void M() } } """); - } [Fact] - public async Task TestOnAssignmentToAboveLocalDefaultLiteralInitializer() - { - await TestInRegularAndScript1Async( + public Task TestOnAssignmentToAboveLocalDefaultLiteralInitializer() + => TestInRegularAndScript1Async( """ class C { @@ -589,12 +552,10 @@ void M() } } """, LanguageVersion.Latest); - } [Fact] - public async Task TestOnAssignmentToAboveLocalDefaultExpressionInitializer() - { - await TestInRegularAndScript1Async( + public Task TestOnAssignmentToAboveLocalDefaultExpressionInitializer() + => TestInRegularAndScript1Async( """ class C { @@ -621,12 +582,10 @@ void M() } } """); - } [Fact] - public async Task TestDoNotMergeAssignmentToAboveLocalWithComplexInitializer() - { - await TestInRegularAndScript1Async( + public Task TestDoNotMergeAssignmentToAboveLocalWithComplexInitializer() + => TestInRegularAndScript1Async( """ class C { @@ -658,12 +617,10 @@ void M() int Foo() => 0; } """); - } [Fact] - public async Task TestDoNotMergeAssignmentToAboveLocalIfIntermediaryStatement() - { - await TestInRegularAndScript1Async( + public Task TestDoNotMergeAssignmentToAboveLocalIfIntermediaryStatement() + => TestInRegularAndScript1Async( """ using System; @@ -697,12 +654,10 @@ void M() } } """); - } [Fact] - public async Task TestDoNotMergeAssignmentToAboveIfLocalUsedInIfCondition() - { - await TestInRegularAndScript1Async( + public Task TestDoNotMergeAssignmentToAboveIfLocalUsedInIfCondition() + => TestInRegularAndScript1Async( """ class C { @@ -734,12 +689,10 @@ void M() bool Bar(int i) => true; } """); - } [Fact] - public async Task TestDoNotMergeAssignmentToAboveIfMultiDecl() - { - await TestInRegularAndScript1Async( + public Task TestDoNotMergeAssignmentToAboveIfMultiDecl() + => TestInRegularAndScript1Async( """ class C { @@ -767,12 +720,10 @@ void M() } } """); - } [Fact] - public async Task TestUseImplicitTypeForIntrinsicTypes() - { - await TestInRegularAndScript1Async( + public Task TestUseImplicitTypeForIntrinsicTypes() + => TestInRegularAndScript1Async( """ class C { @@ -799,12 +750,10 @@ void M() } } """, options: new OptionsCollection(LanguageNames.CSharp) { { CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOption2.TrueWithSilentEnforcement } }); - } [Fact] - public async Task TestUseImplicitTypeWhereApparent() - { - await TestInRegularAndScript1Async( + public Task TestUseImplicitTypeWhereApparent() + => TestInRegularAndScript1Async( """ class C { @@ -831,12 +780,10 @@ void M() } } """, options: new OptionsCollection(LanguageNames.CSharp) { { CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOption2.TrueWithSilentEnforcement } }); - } [Fact] - public async Task TestUseImplicitTypeWherePossible() - { - await TestInRegularAndScript1Async( + public Task TestUseImplicitTypeWherePossible() + => TestInRegularAndScript1Async( """ class C { @@ -863,12 +810,10 @@ void M() } } """, options: new OptionsCollection(LanguageNames.CSharp) { { CSharpCodeStyleOptions.VarElsewhere, CodeStyleOption2.TrueWithSilentEnforcement } }); - } [Fact] - public async Task TestMissingWithoutElse() - { - await TestMissingAsync( + public Task TestMissingWithoutElse() + => TestMissingAsync( """ class C { @@ -881,12 +826,10 @@ void M(int i) } } """); - } [Fact] - public async Task TestMissingWithoutElseWithStatementAfterwards() - { - await TestMissingAsync( + public Task TestMissingWithoutElseWithStatementAfterwards() + => TestMissingAsync( """ class C { @@ -901,12 +844,10 @@ void M(int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestMissingWithoutElseWithThrowStatementAfterwards() - { - await TestMissingAsync( + public Task TestMissingWithoutElseWithThrowStatementAfterwards() + => TestMissingAsync( """ class C { @@ -921,12 +862,10 @@ void M(int i) } } """); - } [Fact] - public async Task TestConversionWithUseVarForAll_CastInsertedToKeepTypeSame() - { - await TestInRegularAndScript1Async( + public Task TestConversionWithUseVarForAll_CastInsertedToKeepTypeSame() + => TestInRegularAndScript1Async( """ class C { @@ -955,12 +894,10 @@ void M() } } """, options: PreferImplicitTypeAlways); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestConversionWithUseVarForAll_CastInsertedToKeepTypeSame_Throw1_CSharp8() - { - await TestInRegularAndScript1Async( + public Task TestConversionWithUseVarForAll_CastInsertedToKeepTypeSame_Throw1_CSharp8() + => TestInRegularAndScript1Async( """ class C { @@ -987,12 +924,10 @@ void M() } } """, LanguageVersion.CSharp8, PreferImplicitTypeAlways); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestConversionWithUseVarForAll_CastInsertedToKeepTypeSame_Throw1_CSharp9() - { - await TestInRegularAndScript1Async( + public Task TestConversionWithUseVarForAll_CastInsertedToKeepTypeSame_Throw1_CSharp9() + => TestInRegularAndScript1Async( """ class C { @@ -1019,12 +954,10 @@ void M() } } """, LanguageVersion.CSharp9, options: PreferImplicitTypeAlways); - } [Fact] - public async Task TestConversionWithUseVarForAll_CastInsertedToKeepTypeSame_Throw2() - { - await TestInRegularAndScript1Async( + public Task TestConversionWithUseVarForAll_CastInsertedToKeepTypeSame_Throw2() + => TestInRegularAndScript1Async( """ class C { @@ -1051,12 +984,10 @@ void M() } } """, options: PreferImplicitTypeAlways); - } [Fact] - public async Task TestConversionWithUseVarForAll_CanUseVarBecauseConditionalTypeMatches() - { - await TestInRegularAndScript1Async( + public Task TestConversionWithUseVarForAll_CanUseVarBecauseConditionalTypeMatches() + => TestInRegularAndScript1Async( """ class C { @@ -1083,12 +1014,10 @@ void M() } } """, options: PreferImplicitTypeAlways); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestConversionWithUseVarForAll_CanUseVarBecauseConditionalTypeMatches_Throw1() - { - await TestInRegularAndScript1Async( + public Task TestConversionWithUseVarForAll_CanUseVarBecauseConditionalTypeMatches_Throw1() + => TestInRegularAndScript1Async( """ class C { @@ -1115,12 +1044,10 @@ void M() } } """, options: PreferImplicitTypeAlways); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestConversionWithUseVarForAll_CanUseVarBecauseConditionalTypeMatches_Throw2() - { - await TestInRegularAndScript1Async( + public Task TestConversionWithUseVarForAll_CanUseVarBecauseConditionalTypeMatches_Throw2() + => TestInRegularAndScript1Async( """ class C { @@ -1147,12 +1074,10 @@ void M() } } """, options: PreferImplicitTypeAlways); - } [Fact] - public async Task TestConversionWithUseVarForAll_CanUseVarButRequiresCastOfConditionalBranch_CSharp8() - { - await TestInRegularAndScript1Async( + public Task TestConversionWithUseVarForAll_CanUseVarButRequiresCastOfConditionalBranch_CSharp8() + => TestInRegularAndScript1Async( """ class C { @@ -1179,12 +1104,10 @@ void M() } } """, LanguageVersion.CSharp8, PreferImplicitTypeAlways); - } [Fact] - public async Task TestConversionWithUseVarForAll_CanUseVarButRequiresCastOfConditionalBranch_CSharp9() - { - await TestInRegularAndScript1Async( + public Task TestConversionWithUseVarForAll_CanUseVarButRequiresCastOfConditionalBranch_CSharp9() + => TestInRegularAndScript1Async( """ class C { @@ -1211,12 +1134,10 @@ void M() } } """, LanguageVersion.CSharp9, options: PreferImplicitTypeAlways); - } [Fact] - public async Task TestKeepTriviaAroundIf() - { - await TestInRegularAndScript1Async( + public Task TestKeepTriviaAroundIf() + => TestInRegularAndScript1Async( """ class C { @@ -1244,12 +1165,10 @@ void M(int i) } } """); - } [Fact] - public async Task TestFixAll1() - { - await TestInRegularAndScript1Async( + public Task TestFixAll1() + => TestInRegularAndScript1Async( """ class C { @@ -1287,12 +1206,10 @@ void M(int i) } } """); - } [Fact] - public async Task TestMultiLine1() - { - await TestInRegularAndScript1Async( + public Task TestMultiLine1() + => TestInRegularAndScript1Async( """ class C { @@ -1326,12 +1243,10 @@ void M(int i) int Foo(int x, int y, int z) => 0; } """); - } [Fact] - public async Task TestMultiLine2() - { - await TestInRegularAndScript1Async( + public Task TestMultiLine2() + => TestInRegularAndScript1Async( """ class C { @@ -1365,12 +1280,10 @@ void M(int i) int Foo(int x, int y, int z) => 0; } """); - } [Fact] - public async Task TestMultiLine3() - { - await TestInRegularAndScript1Async( + public Task TestMultiLine3() + => TestInRegularAndScript1Async( """ class C { @@ -1406,12 +1319,10 @@ void M(int i) int Foo(int x, int y, int z) => 0; } """); - } [Fact] - public async Task TestElseIfWithBlock() - { - await TestInRegularAndScript1Async( + public Task TestElseIfWithBlock() + => TestInRegularAndScript1Async( """ class C { @@ -1446,12 +1357,10 @@ void M(int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestElseIfWithBlock_Throw1() - { - await TestInRegularAndScript1Async( + public Task TestElseIfWithBlock_Throw1() + => TestInRegularAndScript1Async( """ class C { @@ -1486,12 +1395,10 @@ void M(int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestElseIfWithBlock_Throw2() - { - await TestInRegularAndScript1Async( + public Task TestElseIfWithBlock_Throw2() + => TestInRegularAndScript1Async( """ class C { @@ -1526,12 +1433,10 @@ void M(int i) } } """); - } [Fact] - public async Task TestElseIfWithoutBlock() - { - await new VerifyCS.Test + public Task TestElseIfWithoutBlock() + => new VerifyCS.Test { TestCode = """ class C @@ -1564,12 +1469,10 @@ void M(int i) } } }.RunAsync(); - } [Fact] - public async Task TestRefAssignment1() - { - await TestInRegularAndScript1Async( + public Task TestRefAssignment1() + => TestInRegularAndScript1Async( """ class C { @@ -1597,12 +1500,10 @@ void M(ref int i, ref int j) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestRefAssignment1_Throw1() - { - await TestMissingAsync( + public Task TestRefAssignment1_Throw1() + => TestMissingAsync( """ class C { @@ -1620,12 +1521,10 @@ void M(ref int i, ref int j) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestRefAssignment1_Throw2() - { - await TestMissingAsync( + public Task TestRefAssignment1_Throw2() + => TestMissingAsync( """ class C { @@ -1643,12 +1542,10 @@ void M(ref int i, ref int j) } } """); - } [Fact] - public async Task TestTrueFalse1() - { - await TestInRegularAndScript1Async( + public Task TestTrueFalse1() + => TestInRegularAndScript1Async( """ class C { @@ -1674,12 +1571,10 @@ void M(bool i, int j) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestTrueFalse_Throw1() - { - await TestInRegularAndScript1Async( + public Task TestTrueFalse_Throw1() + => TestInRegularAndScript1Async( """ class C { @@ -1705,12 +1600,10 @@ void M(bool i, int j) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestTrueFalse_Throw2() - { - await TestInRegularAndScript1Async( + public Task TestTrueFalse_Throw2() + => TestInRegularAndScript1Async( """ class C { @@ -1736,12 +1629,10 @@ void M(bool i, int j) } } """); - } [Fact] - public async Task TestTrueFalse2() - { - await TestInRegularAndScript1Async( + public Task TestTrueFalse2() + => TestInRegularAndScript1Async( """ class C { @@ -1767,12 +1658,10 @@ void M(bool i, int j) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestFalseTrue_Throw1() - { - await TestInRegularAndScript1Async( + public Task TestFalseTrue_Throw1() + => TestInRegularAndScript1Async( """ class C { @@ -1798,12 +1687,10 @@ void M(bool i, int j) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestFalseTrue_Throw2() - { - await TestInRegularAndScript1Async( + public Task TestFalseTrue_Throw2() + => TestInRegularAndScript1Async( """ class C { @@ -1829,12 +1716,10 @@ void M(bool i, int j) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58898")] - public async Task TestRemoveRedundantCast() - { - await TestInRegularAndScript1Async( + public Task TestRemoveRedundantCast() + => TestInRegularAndScript1Async( """ using System; @@ -1866,12 +1751,10 @@ void M() } } """, options: PreferImplicitTypeAlways); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33284")] - public async Task TestConditionalWithLambdas() - { - await TestInRegularAndScript1Async( + public Task TestConditionalWithLambdas() + => TestInRegularAndScript1Async( """ using System; @@ -1903,12 +1786,10 @@ void M(bool containsHighBits) } } """, LanguageVersion.CSharp9); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39260")] - public async Task TestTitleWhenSimplifying() - { - await TestInRegularAndScript1Async( + public Task TestTitleWhenSimplifying() + => TestInRegularAndScript1Async( """ using System; @@ -1949,7 +1830,6 @@ private bool AreSimilarCore(string node1, string node2) } } """, LanguageVersion.CSharp9, equivalenceKey: nameof(AnalyzersResources.Simplify_check)); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67649")] [InlineData("int", "int")] @@ -1958,9 +1838,8 @@ private bool AreSimilarCore(string node1, string node2) [InlineData("object", "string")] [InlineData("int", "long")] [InlineData("long", "int")] - public async Task TestForDiscardsWithMatchingOrConvertibleExpressionTypes(string originalFirstType, string originalSecondType) - { - await TestInRegularAndScript1Async($$""" + public Task TestForDiscardsWithMatchingOrConvertibleExpressionTypes(string originalFirstType, string originalSecondType) + => TestInRegularAndScript1Async($$""" class MyClass { void M(bool flag) @@ -1990,12 +1869,10 @@ void M(bool flag) {{originalSecondType}} B() => default; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67649")] - public async Task TestMissingForDiscardsWithDifferentTypes() - { - await TestMissingAsync(""" + public Task TestMissingForDiscardsWithDifferentTypes() + => TestMissingAsync(""" class MyClass { void M(bool flag) @@ -2014,12 +1891,10 @@ void M(bool flag) string B() => default; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67649")] - public async Task TestMissingForDiscardsWithBothImplicitConversions() - { - await TestMissingAsync(""" + public Task TestMissingForDiscardsWithBothImplicitConversions() + => TestMissingAsync(""" class MyClass { void M(bool flag) @@ -2044,12 +1919,10 @@ class C public static implicit operator string(C c) => ""; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68578")] - public async Task TestMissingWhenAssignmentReferencesPatternVariable() - { - await TestMissingAsync(""" + public Task TestMissingWhenAssignmentReferencesPatternVariable() + => TestMissingAsync(""" using System; public class Class1 @@ -2072,12 +1945,10 @@ public static void Test(object obj) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68578")] - public async Task TestMissingWhenAssignmentReferencesOutVariable() - { - await TestMissingAsync(""" + public Task TestMissingWhenAssignmentReferencesOutVariable() + => TestMissingAsync(""" using System; public class Class1 @@ -2102,12 +1973,10 @@ public static void Test(object obj) private static bool TryGetValue(out Class1 c) => throw new NotImplementedException(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71403")] - public async Task TestGlobalStatements() - { - await new VerifyCS.Test + public Task TestGlobalStatements() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -2145,12 +2014,10 @@ public async Task TestGlobalStatements() OutputKind = OutputKind.ConsoleApplication, } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58897")] - public async Task TestCommentsOnElse() - { - await TestInRegularAndScript1Async( + public Task TestCommentsOnElse() + => TestInRegularAndScript1Async( """ using System; @@ -2186,12 +2053,10 @@ void M(bool containsHighBits) } } """, LanguageVersion.CSharp9); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60859")] - public async Task UnnecessaryWithinConditionalBranch2() - { - await TestInRegularAndScript1Async( + public Task UnnecessaryWithinConditionalBranch2() + => TestInRegularAndScript1Async( """ public class IssueClass { @@ -2222,12 +2087,10 @@ public void ConvertFieldValueForStorage(object value) } } """, LanguageVersion.CSharp13); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63441")] - public async Task TestNullCheck1() - { - await TestMissingAsync(""" + public Task TestNullCheck1() + => TestMissingAsync(""" using System; public class Program { @@ -2248,12 +2111,10 @@ public class Test } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63441")] - public async Task TestNullCheck1_B() - { - await TestMissingAsync(""" + public Task TestNullCheck1_B() + => TestMissingAsync(""" using System; public class Program { @@ -2274,12 +2135,10 @@ public class Test } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63441")] - public async Task TestNullCheck2() - { - await TestMissingAsync(""" + public Task TestNullCheck2() + => TestMissingAsync(""" using System; public class Program { @@ -2300,12 +2159,10 @@ public class Test } } """, LanguageVersion.CSharp9); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63441")] - public async Task TestNullCheck3() - { - await TestMissingAsync(""" + public Task TestNullCheck3() + => TestMissingAsync(""" using System; public class Program { @@ -2326,12 +2183,10 @@ public class Test } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63441")] - public async Task TestNullCheck4() - { - await TestMissingAsync(""" + public Task TestNullCheck4() + => TestMissingAsync(""" using System; public class Program { @@ -2352,12 +2207,10 @@ public class Test } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63441")] - public async Task TestNullCheck5() - { - await TestMissingAsync(""" + public Task TestNullCheck5() + => TestMissingAsync(""" using System; public class Program { @@ -2378,12 +2231,10 @@ public class Test } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63441")] - public async Task TestNullCheck6() - { - await TestMissingAsync(""" + public Task TestNullCheck6() + => TestMissingAsync(""" using System; public class Program { @@ -2404,12 +2255,10 @@ public class Test } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75200")] - public async Task TestNullCheck7() - { - await TestMissingAsync(""" + public Task TestNullCheck7() + => TestMissingAsync(""" using System; public class Program { @@ -2423,12 +2272,10 @@ public void N(object[] parent, int i, object value) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63441")] - public async Task TestNullCheck_Positive1() - { - await TestInRegularAndScript1Async(""" + public Task TestNullCheck_Positive1() + => TestInRegularAndScript1Async(""" using System; public class Program { @@ -2462,12 +2309,10 @@ public class Test } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72464")] - public async Task TestMissingWithVariableCollisions() - { - await TestMissingAsync( + public Task TestMissingWithVariableCollisions() + => TestMissingAsync( """ using System; @@ -2487,12 +2332,10 @@ public void Convert(Type type, string body) } } """); - } [Fact] - public async Task TestOnNullConditionalAssignment1() - { - await TestInRegularAndScript1Async( + public Task TestOnNullConditionalAssignment1() + => TestInRegularAndScript1Async( """ class C { @@ -2523,5 +2366,4 @@ void M(C c) } """, languageVersion: LanguageVersionExtensions.CSharpNext); - } } diff --git a/src/Analyzers/CSharp/Tests/UseConditionalExpression/UseConditionalExpressionForReturnTests.cs b/src/Analyzers/CSharp/Tests/UseConditionalExpression/UseConditionalExpressionForReturnTests.cs index d15fcbfd1b2dc..61f2db91daf1b 100644 --- a/src/Analyzers/CSharp/Tests/UseConditionalExpression/UseConditionalExpressionForReturnTests.cs +++ b/src/Analyzers/CSharp/Tests/UseConditionalExpression/UseConditionalExpressionForReturnTests.cs @@ -27,9 +27,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider new CSharpUseConditionalExpressionForReturnCodeFixProvider()); [Fact] - public async Task TestOnSimpleReturn() - { - await TestInRegularAndScript1Async( + public Task TestOnSimpleReturn() + => TestInRegularAndScript1Async( """ class C { @@ -55,12 +54,10 @@ int M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestOnSimpleReturn_Throw1() - { - await TestInRegularAndScript1Async( + public Task TestOnSimpleReturn_Throw1() + => TestInRegularAndScript1Async( """ class C { @@ -86,12 +83,10 @@ int M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestOnSimpleReturn_Throw2() - { - await TestInRegularAndScript1Async( + public Task TestOnSimpleReturn_Throw2() + => TestInRegularAndScript1Async( """ class C { @@ -117,12 +112,10 @@ int M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestNotWithTwoThrows() - { - await TestMissingAsync( + public Task TestNotWithTwoThrows() + => TestMissingAsync( """ class C { @@ -139,12 +132,10 @@ int M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestNotOnSimpleReturn_Throw1_CSharp6() - { - await TestMissingAsync( + public Task TestNotOnSimpleReturn_Throw1_CSharp6() + => TestMissingAsync( """ class C { @@ -161,12 +152,10 @@ int M() } } """, parameters: new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestNotWithSimpleThrow() - { - await TestMissingAsync( + public Task TestNotWithSimpleThrow() + => TestMissingAsync( """ class C { @@ -183,12 +172,10 @@ int M() } } """); - } [Fact] - public async Task TestOnSimpleReturnNoBlocks() - { - await TestInRegularAndScript1Async( + public Task TestOnSimpleReturnNoBlocks() + => TestInRegularAndScript1Async( """ class C { @@ -210,12 +197,10 @@ int M() } } """); - } [Fact] - public async Task TestOnSimpleReturnNoBlocks_NotInBlock() - { - await TestInRegularAndScript1Async( + public Task TestOnSimpleReturnNoBlocks_NotInBlock() + => TestInRegularAndScript1Async( """ class C { @@ -239,12 +224,10 @@ int M() } } """); - } [Fact] - public async Task TestMissingReturnValue1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingReturnValue1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -261,12 +244,10 @@ int M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestMissingReturnValue1_Throw() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingReturnValue1_Throw() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -283,12 +264,10 @@ int M() } } """); - } [Fact] - public async Task TestMissingReturnValue2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingReturnValue2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -305,12 +284,10 @@ int M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestMissingReturnValue2_Throw() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingReturnValue2_Throw() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -327,12 +304,10 @@ int M() } } """); - } [Fact] - public async Task TestMissingReturnValue3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingReturnValue3() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -349,12 +324,10 @@ int M() } } """); - } [Fact] - public async Task TestWithNoElseBlockButFollowingReturn() - { - await TestInRegularAndScript1Async( + public Task TestWithNoElseBlockButFollowingReturn() + => TestInRegularAndScript1Async( """ class C { @@ -378,12 +351,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestWithNoElseBlockButFollowingReturn_Throw1() - { - await TestInRegularAndScript1Async( + public Task TestWithNoElseBlockButFollowingReturn_Throw1() + => TestInRegularAndScript1Async( """ class C { @@ -407,12 +378,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestWithNoElseBlockButFollowingReturn_Throw2() - { - await TestInRegularAndScript1Async( + public Task TestWithNoElseBlockButFollowingReturn_Throw2() + => TestInRegularAndScript1Async( """ class C { @@ -436,12 +405,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingWithoutElse() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWithoutElse() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -454,12 +421,10 @@ int M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestMissingWithoutElse_Throw() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWithoutElse_Throw() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -472,12 +437,10 @@ int M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70750")] - public async Task TestMissingWithChecked() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWithChecked() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -496,12 +459,10 @@ int M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70748")] - public async Task TestMissingWithCheckedInIf() - { - await TestInRegularAndScriptAsync( + public Task TestMissingWithCheckedInIf() + => TestInRegularAndScriptAsync( """ class C { @@ -531,12 +492,10 @@ int M() } } """, parseOptions: CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70748")] - public async Task TestMissingWithUncheckedInIf() - { - await TestInRegularAndScriptAsync( + public Task TestMissingWithUncheckedInIf() + => TestInRegularAndScriptAsync( """ class C { @@ -566,12 +525,10 @@ int M() } } """, parseOptions: CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70748")] - public async Task TestMissingWithCheckedInTrueStatement() - { - await TestInRegularAndScriptAsync( + public Task TestMissingWithCheckedInTrueStatement() + => TestInRegularAndScriptAsync( """ class C { @@ -601,12 +558,10 @@ int M() } } """, parseOptions: CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70748")] - public async Task TestMissingWithUncheckedInTrueStatement() - { - await TestInRegularAndScriptAsync( + public Task TestMissingWithUncheckedInTrueStatement() + => TestInRegularAndScriptAsync( """ class C { @@ -636,12 +591,10 @@ int M() } } """, parseOptions: CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70748")] - public async Task TestMissingWithCheckedInFalseStatement() - { - await TestInRegularAndScriptAsync( + public Task TestMissingWithCheckedInFalseStatement() + => TestInRegularAndScriptAsync( """ class C { @@ -671,12 +624,10 @@ int M() } } """, parseOptions: CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70748")] - public async Task TestMissingWithUncheckedInFalseStatement() - { - await TestInRegularAndScriptAsync( + public Task TestMissingWithUncheckedInFalseStatement() + => TestInRegularAndScriptAsync( """ class C { @@ -706,12 +657,10 @@ int M() } } """, parseOptions: CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70750")] - public async Task TestMissingWithUnchecked() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWithUnchecked() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -730,12 +679,10 @@ int M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70750")] - public async Task TestMissingWithUnsafe() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWithUnsafe() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -754,12 +701,10 @@ int M() } } """); - } [Fact] - public async Task TestConversion1_CSharp8() - { - await TestInRegularAndScriptAsync( + public Task TestConversion1_CSharp8() + => TestInRegularAndScriptAsync( """ class C { @@ -785,12 +730,10 @@ object M() } } """, parseOptions: CSharp8); - } [Fact] - public async Task TestConversion1_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task TestConversion1_CSharp9() + => TestInRegularAndScriptAsync( """ class C { @@ -816,12 +759,10 @@ object M() } } """, parseOptions: CSharp9); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestConversion1_Throw1_CSharp8() - { - await TestInRegularAndScriptAsync( + public Task TestConversion1_Throw1_CSharp8() + => TestInRegularAndScriptAsync( """ class C { @@ -847,12 +788,10 @@ object M() } } """, parseOptions: CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestConversion1_Throw1_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task TestConversion1_Throw1_CSharp9() + => TestInRegularAndScriptAsync( """ class C { @@ -878,12 +817,10 @@ object M() } } """, parseOptions: CSharp9); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestConversion1_Throw2_CSharp8() - { - await TestInRegularAndScriptAsync( + public Task TestConversion1_Throw2_CSharp8() + => TestInRegularAndScriptAsync( """ class C { @@ -909,12 +846,10 @@ object M() } } """, parseOptions: CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestConversion1_Throw2_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task TestConversion1_Throw2_CSharp9() + => TestInRegularAndScriptAsync( """ class C { @@ -940,12 +875,10 @@ object M() } } """, parseOptions: CSharp9); - } [Fact] - public async Task TestConversion2() - { - await TestInRegularAndScript1Async( + public Task TestConversion2() + => TestInRegularAndScript1Async( """ class C { @@ -971,14 +904,12 @@ string M() } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] [InlineData(LanguageVersion.CSharp8, "(string)null")] [InlineData(LanguageVersion.CSharp9, "null")] - public async Task TestConversion2_Throw1(LanguageVersion languageVersion, string expectedFalseExpression) - { - await TestInRegularAndScript1Async( + public Task TestConversion2_Throw1(LanguageVersion languageVersion, string expectedFalseExpression) + => TestInRegularAndScript1Async( """ class C { @@ -1006,12 +937,10 @@ string M() } } """, parameters: new(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(languageVersion))); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestConversion2_Throw2() - { - await TestInRegularAndScript1Async( + public Task TestConversion2_Throw2() + => TestInRegularAndScript1Async( """ class C { @@ -1037,14 +966,12 @@ string M() } } """); - } [Theory] [InlineData(LanguageVersion.CSharp8, "(string)null")] [InlineData(LanguageVersion.CSharp9, "null")] - public async Task TestConversion3(LanguageVersion languageVersion, string expectedFalseExpression) - { - await TestInRegularAndScript1Async( + public Task TestConversion3(LanguageVersion languageVersion, string expectedFalseExpression) + => TestInRegularAndScript1Async( """ class C { @@ -1072,14 +999,12 @@ string M() } } """, parameters: new(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(languageVersion))); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] [InlineData(LanguageVersion.CSharp8, "(string)null")] [InlineData(LanguageVersion.CSharp9, "null")] - public async Task TestConversion3_Throw1(LanguageVersion languageVersion, string expectedFalseExpression) - { - await TestInRegularAndScript1Async( + public Task TestConversion3_Throw1(LanguageVersion languageVersion, string expectedFalseExpression) + => TestInRegularAndScript1Async( """ class C { @@ -1107,14 +1032,12 @@ string M() } } """, parameters: new(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(languageVersion))); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] [InlineData(LanguageVersion.CSharp8, "(string)null")] [InlineData(LanguageVersion.CSharp9, "null")] - public async Task TestConversion3_Throw2(LanguageVersion languageVersion, string expectedTrue) - { - await TestInRegularAndScript1Async( + public Task TestConversion3_Throw2(LanguageVersion languageVersion, string expectedTrue) + => TestInRegularAndScript1Async( """ class C { @@ -1142,12 +1065,10 @@ string M() } } """, parameters: new(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(languageVersion))); - } [Fact] - public async Task TestKeepTriviaAroundIf() - { - await TestInRegularAndScript1Async( + public Task TestKeepTriviaAroundIf() + => TestInRegularAndScript1Async( """ class C { @@ -1175,12 +1096,10 @@ int M() } } """); - } [Fact] - public async Task TestFixAll1() - { - await TestInRegularAndScript1Async( + public Task TestFixAll1() + => TestInRegularAndScript1Async( """ class C { @@ -1215,12 +1134,10 @@ int M() } } """); - } [Fact] - public async Task TestMultiLine1() - { - await TestInRegularAndScript1Async( + public Task TestMultiLine1() + => TestInRegularAndScript1Async( """ class C { @@ -1250,12 +1167,10 @@ int M() } } """); - } [Fact] - public async Task TestMultiLine2() - { - await TestInRegularAndScript1Async( + public Task TestMultiLine2() + => TestInRegularAndScript1Async( """ class C { @@ -1285,12 +1200,10 @@ int M() } } """); - } [Fact] - public async Task TestMultiLine3() - { - await TestInRegularAndScript1Async( + public Task TestMultiLine3() + => TestInRegularAndScript1Async( """ class C { @@ -1322,12 +1235,10 @@ int M() } } """); - } [Fact] - public async Task TestElseIfWithBlock() - { - await TestInRegularAndScript1Async( + public Task TestElseIfWithBlock() + => TestInRegularAndScript1Async( """ class C { @@ -1362,12 +1273,10 @@ int M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestElseIfWithBlock_Throw1() - { - await TestInRegularAndScript1Async( + public Task TestElseIfWithBlock_Throw1() + => TestInRegularAndScript1Async( """ class C { @@ -1402,12 +1311,10 @@ int M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestElseIfWithBlock_Throw2() - { - await TestInRegularAndScript1Async( + public Task TestElseIfWithBlock_Throw2() + => TestInRegularAndScript1Async( """ class C { @@ -1442,12 +1349,10 @@ int M() } } """); - } [Fact] - public async Task TestElseIfWithoutBlock() - { - await TestInRegularAndScript1Async( + public Task TestElseIfWithoutBlock() + => TestInRegularAndScript1Async( """ class C { @@ -1469,12 +1374,10 @@ int M() } } """); - } [Fact] - public async Task TestRefReturns1() - { - await TestInRegularAndScript1Async( + public Task TestRefReturns1() + => TestInRegularAndScript1Async( """ class C { @@ -1500,12 +1403,10 @@ ref int M(ref int i, ref int j) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestRefReturns1_Throw1() - { - await TestMissingAsync( + public Task TestRefReturns1_Throw1() + => TestMissingAsync( """ class C { @@ -1522,12 +1423,10 @@ ref int M(ref int i, ref int j) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestRefReturns1_Throw2() - { - await TestMissingAsync( + public Task TestRefReturns1_Throw2() + => TestMissingAsync( """ class C { @@ -1544,12 +1443,10 @@ ref int M(ref int i, ref int j) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27960")] - public async Task TestOnYieldReturn() - { - await TestInRegularAndScript1Async( + public Task TestOnYieldReturn() + => TestInRegularAndScript1Async( """ class C { @@ -1575,13 +1472,11 @@ int M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27960")] [WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestOnYieldReturn_Throw1() - { - await TestInRegularAndScript1Async( + public Task TestOnYieldReturn_Throw1() + => TestInRegularAndScript1Async( """ class C { @@ -1607,13 +1502,11 @@ int M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27960")] [WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestOnYieldReturn_Throw2() - { - await TestInRegularAndScript1Async( + public Task TestOnYieldReturn_Throw2() + => TestInRegularAndScript1Async( """ class C { @@ -1639,12 +1532,10 @@ int M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27960")] - public async Task TestOnYieldReturn_IEnumerableReturnType() - { - await TestInRegularAndScript1Async( + public Task TestOnYieldReturn_IEnumerableReturnType() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; @@ -1674,12 +1565,10 @@ IEnumerable M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27960")] - public async Task TestNotOnMixedYields() - { - await TestMissingAsync( + public Task TestNotOnMixedYields() + => TestMissingAsync( """ class C { @@ -1696,13 +1585,11 @@ int M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27960")] [WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestNotOnMixedYields_Throw1() - { - await TestMissingAsync( + public Task TestNotOnMixedYields_Throw1() + => TestMissingAsync( """ class C { @@ -1719,12 +1606,10 @@ int M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27960")] - public async Task TestNotOnMixedYields_IEnumerableReturnType() - { - await TestMissingAsync( + public Task TestNotOnMixedYields_IEnumerableReturnType() + => TestMissingAsync( """ using System.Collections.Generic; @@ -1743,12 +1628,10 @@ IEnumerable M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27960")] - public async Task TestNotWithNoElseBlockButFollowingYieldReturn() - { - await TestMissingAsync( + public Task TestNotWithNoElseBlockButFollowingYieldReturn() + => TestMissingAsync( """ class C { @@ -1763,13 +1646,11 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27960")] [WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestWithNoElseBlockButFollowingYieldReturn_Throw1() - { - await TestInRegularAndScript1Async( + public Task TestWithNoElseBlockButFollowingYieldReturn_Throw1() + => TestInRegularAndScript1Async( """ class C { @@ -1794,13 +1675,11 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27960")] [WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestNotWithNoElseBlockButFollowingYieldReturn_Throw2() - { - await TestMissingAsync( + public Task TestNotWithNoElseBlockButFollowingYieldReturn_Throw2() + => TestMissingAsync( """ class C { @@ -1815,12 +1694,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27960")] - public async Task TestNotWithNoElseBlockButFollowingYieldReturn_IEnumerableReturnType() - { - await TestMissingAsync( + public Task TestNotWithNoElseBlockButFollowingYieldReturn_IEnumerableReturnType() + => TestMissingAsync( """ using System.Collections.Generic; @@ -1837,12 +1714,10 @@ IEnumerable M() } } """); - } [Fact] - public async Task TestReturnTrueFalse1() - { - await TestInRegularAndScript1Async( + public Task TestReturnTrueFalse1() + => TestInRegularAndScript1Async( """ class C { @@ -1868,12 +1743,10 @@ bool M(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestReturnTrueFalse1_Throw1() - { - await TestInRegularAndScript1Async( + public Task TestReturnTrueFalse1_Throw1() + => TestInRegularAndScript1Async( """ class C { @@ -1899,12 +1772,10 @@ bool M(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestReturnTrueFalse1_Throw2() - { - await TestInRegularAndScript1Async( + public Task TestReturnTrueFalse1_Throw2() + => TestInRegularAndScript1Async( """ class C { @@ -1930,12 +1801,10 @@ bool M(int a) } } """); - } [Fact] - public async Task TestReturnTrueFalse2() - { - await TestInRegularAndScript1Async( + public Task TestReturnTrueFalse2() + => TestInRegularAndScript1Async( """ class C { @@ -1961,12 +1830,10 @@ bool M(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestReturnTrueFalse2_Throw1() - { - await TestInRegularAndScript1Async( + public Task TestReturnTrueFalse2_Throw1() + => TestInRegularAndScript1Async( """ class C { @@ -1992,12 +1859,10 @@ bool M(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestReturnTrueFalse2_Throw2() - { - await TestInRegularAndScript1Async( + public Task TestReturnTrueFalse2_Throw2() + => TestInRegularAndScript1Async( """ class C { @@ -2023,12 +1888,10 @@ bool M(int a) } } """); - } [Fact] - public async Task TestReturnTrueFalse3() - { - await TestInRegularAndScript1Async( + public Task TestReturnTrueFalse3() + => TestInRegularAndScript1Async( """ class C { @@ -2052,12 +1915,10 @@ bool M(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestReturnTrueFalse3_Throw1() - { - await TestInRegularAndScript1Async( + public Task TestReturnTrueFalse3_Throw1() + => TestInRegularAndScript1Async( """ class C { @@ -2081,12 +1942,10 @@ bool M(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestReturnTrueFalse3_Throw2() - { - await TestInRegularAndScript1Async( + public Task TestReturnTrueFalse3_Throw2() + => TestInRegularAndScript1Async( """ class C { @@ -2110,12 +1969,10 @@ bool M(int a) } } """); - } [Fact] - public async Task TestReturnTrueFalse4() - { - await TestInRegularAndScript1Async( + public Task TestReturnTrueFalse4() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; @@ -2145,12 +2002,10 @@ IEnumerable M(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestReturnTrueFalse4_Throw1() - { - await TestInRegularAndScript1Async( + public Task TestReturnTrueFalse4_Throw1() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; @@ -2180,12 +2035,10 @@ IEnumerable M(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43291")] - public async Task TestReturnTrueFalse4_Throw2() - { - await TestInRegularAndScript1Async( + public Task TestReturnTrueFalse4_Throw2() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; @@ -2215,12 +2068,10 @@ IEnumerable M(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36117")] - public async Task TestMissingWhenCrossingPreprocessorDirective() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWhenCrossingPreprocessorDirective() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2235,12 +2086,10 @@ int M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39260")] - public async Task TestTitleWhenSimplifying() - { - await TestInRegularAndScriptAsync( + public Task TestTitleWhenSimplifying() + => TestInRegularAndScriptAsync( """ class C { @@ -2276,12 +2125,10 @@ private bool AreSimilarCore(string node1, string node2) } } """, title: AnalyzersResources.Simplify_check); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38879")] - public async Task TesSuppressionOperator() - { - await TestInRegularAndScript1Async(""" + public Task TesSuppressionOperator() + => TestInRegularAndScript1Async(""" #nullable enable class Program @@ -2307,12 +2154,10 @@ public static string Method(bool empty) } } """); - } [Fact] - public async Task TestWithCollectionExpressions() - { - await TestInRegularAndScript1Async( + public Task TestWithCollectionExpressions() + => TestInRegularAndScript1Async( """ class C { @@ -2338,12 +2183,10 @@ int[] M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60859")] - public async Task UnnecessaryWithinConditionalBranch2() - { - await TestInRegularAndScript1Async( + public Task UnnecessaryWithinConditionalBranch2() + => TestInRegularAndScript1Async( """ public class IssueClass { @@ -2373,12 +2216,10 @@ public object ConvertFieldValueForStorage(object value) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72464")] - public async Task TestMissingWithVariableCollisions() - { - await TestMissingAsync( + public Task TestMissingWithVariableCollisions() + => TestMissingAsync( """ using System; @@ -2397,5 +2238,4 @@ public object Convert(Type type, string body) } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/UseDeconstruction/UseDeconstructionTests.cs b/src/Analyzers/CSharp/Tests/UseDeconstruction/UseDeconstructionTests.cs index 669553ce6d82b..f3e65ded21238 100644 --- a/src/Analyzers/CSharp/Tests/UseDeconstruction/UseDeconstructionTests.cs +++ b/src/Analyzers/CSharp/Tests/UseDeconstruction/UseDeconstructionTests.cs @@ -21,9 +21,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseDeconstruction; public sealed class UseDeconstructionTests { [Fact] - public async Task TestVar() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestVar() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -44,7 +43,6 @@ void M() (string name, int age) GetPerson() => default; } """); - } [Fact] public async Task TestNotIfNameInInnerScope() @@ -88,9 +86,8 @@ void M() } [Fact] - public async Task TestUpdateReference() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestUpdateReference() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -113,12 +110,10 @@ void M() (string name, int age) GetPerson() => default; } """); - } [Fact] - public async Task TestTupleType() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestTupleType() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -141,12 +136,10 @@ void M() (string name, int age) GetPerson() => default; } """); - } [Fact] - public async Task TestVarInForEach() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestVarInForEach() + => VerifyCS.VerifyCodeFixAsync(""" using System.Collections.Generic; class C @@ -173,12 +166,10 @@ void M() IEnumerable<(string name, int age)> GetPeople() => default; } """); - } [Fact] - public async Task TestTupleTypeInForEach() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestTupleTypeInForEach() + => VerifyCS.VerifyCodeFixAsync(""" using System.Collections.Generic; class C @@ -205,12 +196,10 @@ void M() IEnumerable<(string name, int age)> GetPeople() => default; } """); - } [Fact] - public async Task TestFixAll1() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestFixAll1() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -233,12 +222,10 @@ void M() (string name, int age) GetPerson() => default; } """); - } [Fact] - public async Task TestFixAll2() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestFixAll2() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -269,12 +256,10 @@ void M2() (string name, int age) GetPerson() => default; } """); - } [Fact] - public async Task TestFixAll3() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestFixAll3() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -297,12 +282,10 @@ void M() (string name, int age) GetPerson() => default; } """); - } [Fact] - public async Task TestFixAll4() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestFixAll4() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -325,7 +308,6 @@ void M() (string name, int age) GetPerson() => default; } """); - } [Fact] public async Task TestNotIfDefaultTupleNameWithVar() @@ -346,9 +328,8 @@ void M() } [Fact] - public async Task TestWithUserNamesThatMatchDefaultTupleNameWithVar1() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestWithUserNamesThatMatchDefaultTupleNameWithVar1() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -369,12 +350,10 @@ void M() (string Item1, int Item2) GetPerson() => default; } """); - } [Fact] - public async Task TestWithUserNamesThatMatchDefaultTupleNameWithVar2() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestWithUserNamesThatMatchDefaultTupleNameWithVar2() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -397,7 +376,6 @@ void M() (string Item1, int Item2) GetPerson() => default; } """); - } [Fact] public async Task TestNotIfDefaultTupleNameWithTupleType() @@ -494,9 +472,8 @@ void M() } [Fact] - public async Task TestTrivia1() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestTrivia1() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -519,12 +496,10 @@ void M() (string name, int age) GetPerson() => default; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25260")] - public async Task TestNotWithDefaultLiteralInitializer() - { - await new VerifyCS.Test() + public Task TestNotWithDefaultLiteralInitializer() + => new VerifyCS.Test() { TestCode = """ class C @@ -538,12 +513,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestWithDefaultExpressionInitializer() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestWithDefaultExpressionInitializer() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -562,7 +535,6 @@ void M() } } """); - } [Fact] public async Task TestNotWithImplicitConversionFromNonTuple() @@ -587,9 +559,8 @@ void M() } [Fact] - public async Task TestWithExplicitImplicitConversionFromNonTuple() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestWithExplicitImplicitConversionFromNonTuple() + => VerifyCS.VerifyCodeFixAsync(""" class C { class Person @@ -618,7 +589,6 @@ void M() } } """); - } [Fact] public async Task TestNotWithImplicitConversionFromNonTupleInForEach() @@ -643,9 +613,8 @@ void M() } [Fact] - public async Task TestWithExplicitImplicitConversionFromNonTupleInForEach() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestWithExplicitImplicitConversionFromNonTupleInForEach() + => VerifyCS.VerifyCodeFixAsync(""" using System.Linq; class C { @@ -676,12 +645,10 @@ void M() } } """); - } [Fact] - public async Task TestWithTupleLiteralConversion() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestWithTupleLiteralConversion() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -700,12 +667,10 @@ void M() } } """); - } [Fact] - public async Task TestWithImplicitTupleConversion() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestWithImplicitTupleConversion() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -728,12 +693,10 @@ void M() (string name, int age) GetPerson() => default; } """); - } [Fact] - public async Task TestWithImplicitTupleConversionInForEach() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestWithImplicitTupleConversionInForEach() + => VerifyCS.VerifyCodeFixAsync(""" using System.Collections.Generic; class C { @@ -758,12 +721,10 @@ void M() IEnumerable<(string name, int age)> GetPeople() => default; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27251")] - public async Task TestEscapedContextualKeywordAsTupleName() - { - await new VerifyCS.Test() + public Task TestEscapedContextualKeywordAsTupleName() + => new VerifyCS.Test() { TestCode = """ using System.Collections.Generic; @@ -799,12 +760,10 @@ void M() """, CodeActionValidationMode = Testing.CodeActionValidationMode.None }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42770")] - public async Task TestPreserveAwait() - { - await new VerifyCS.Test + public Task TestPreserveAwait() + => new VerifyCS.Test { TestCode = """ using System; @@ -854,12 +813,10 @@ static async Task Main(string[] args) """, ReferenceAssemblies = ReferenceAssemblies.Net.Net60 }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66994")] - public async Task TestTopLevelDeconstruct1() - { - await new VerifyCS.Test() + public Task TestTopLevelDeconstruct1() + => new VerifyCS.Test() { TestCode = """ (int A, int B) ints = (1, 1); @@ -876,12 +833,10 @@ void M((int, int) i) }, LanguageVersion = LanguageVersion.CSharp9 }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66994")] - public async Task TestTopLevelDeconstruct2() - { - await new VerifyCS.Test + public Task TestTopLevelDeconstruct2() + => new VerifyCS.Test { TestCode = """ (int A, int B) [|ints|] = (1, 1); @@ -911,5 +866,4 @@ void M(int x, int y) }, LanguageVersion = LanguageVersion.CSharp9 }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UseDefaultLiteral/UseDefaultLiteralTests.cs b/src/Analyzers/CSharp/Tests/UseDefaultLiteral/UseDefaultLiteralTests.cs index 68873902147a4..900c503daa8fb 100644 --- a/src/Analyzers/CSharp/Tests/UseDefaultLiteral/UseDefaultLiteralTests.cs +++ b/src/Analyzers/CSharp/Tests/UseDefaultLiteral/UseDefaultLiteralTests.cs @@ -20,28 +20,23 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseDefaultLiteral; public sealed class UseDefaultLiteralTests { [Fact] - public async Task TestNotInCSharp7() - { - var code = """ + public Task TestNotInCSharp7() + => new VerifyCS.Test() + { + TestCode = """ class C { void Goo(string s = default(string)) { } } - """; - - await new VerifyCS.Test() - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp7 }.RunAsync(); - } [Fact] - public async Task TestInParameterList() - { - await new VerifyCS.Test + public Task TestInParameterList() + => new VerifyCS.Test { TestCode = """ class C @@ -61,12 +56,10 @@ void Goo(string s = default) """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestInIfCheck() - { - await new VerifyCS.Test + public Task TestInIfCheck() + => new VerifyCS.Test { TestCode = """ class C @@ -88,12 +81,10 @@ void Goo(string s) """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestInReturnStatement() - { - await new VerifyCS.Test + public Task TestInReturnStatement() + => new VerifyCS.Test { TestCode = """ class C @@ -115,12 +106,12 @@ string Goo() """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestInReturnStatement2() - { - var code = """ + public Task TestInReturnStatement2() + => new VerifyCS.Test() + { + TestCode = """ class C { string Goo() @@ -128,19 +119,13 @@ string Goo() return {|CS0029:default(int)|}; } } - """; - - await new VerifyCS.Test() - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestInLambda1() - { - await new VerifyCS.Test + public Task TestInLambda1() + => new VerifyCS.Test { TestCode = """ using System; @@ -166,12 +151,12 @@ void Goo() """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestInLambda2() - { - var code = """ + public Task TestInLambda2() + => new VerifyCS.Test() + { + TestCode = """ using System; class C @@ -181,19 +166,13 @@ void Goo() Func f = () => {|CS1662:{|CS0029:default(int)|}|}; } } - """; - - await new VerifyCS.Test() - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestInLocalInitializer() - { - await new VerifyCS.Test + public Task TestInLocalInitializer() + => new VerifyCS.Test { TestCode = """ class C @@ -215,12 +194,12 @@ void Goo() """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestInLocalInitializer2() - { - var code = """ + public Task TestInLocalInitializer2() + => new VerifyCS.Test() + { + TestCode = """ class C { void Goo() @@ -228,19 +207,15 @@ void Goo() string s = {|CS0029:default(int)|}; } } - """; - - await new VerifyCS.Test() - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestNotForVar() - { - var code = """ + public Task TestNotForVar() + => new VerifyCS.Test() + { + TestCode = """ class C { void Goo() @@ -248,19 +223,13 @@ void Goo() var s = default(string); } } - """; - - await new VerifyCS.Test() - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestInInvocationExpression() - { - await new VerifyCS.Test + public Task TestInInvocationExpression() + => new VerifyCS.Test { TestCode = """ class C @@ -286,12 +255,12 @@ void Bar(string s) { } """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestNotWithMultipleOverloads() - { - var code = """ + public Task TestNotWithMultipleOverloads() + => new VerifyCS.Test() + { + TestCode = """ class C { void Goo() @@ -302,19 +271,13 @@ void Goo() void Bar(string s) { } void Bar(int i) { } } - """; - - await new VerifyCS.Test() - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestLeftSideOfTernary() - { - await new VerifyCS.Test + public Task TestLeftSideOfTernary() + => new VerifyCS.Test { TestCode = """ class C @@ -338,12 +301,10 @@ void Goo(bool b) DiagnosticSelector = d => d[0], CodeFixTestBehaviors = Testing.CodeFixTestBehaviors.FixOne | Testing.CodeFixTestBehaviors.SkipFixAllCheck }.RunAsync(); - } [Fact] - public async Task TestRightSideOfTernary() - { - await new VerifyCS.Test + public Task TestRightSideOfTernary() + => new VerifyCS.Test { TestCode = """ class C @@ -367,12 +328,10 @@ void Goo(bool b) DiagnosticSelector = d => d[1], CodeFixTestBehaviors = Testing.CodeFixTestBehaviors.FixOne | Testing.CodeFixTestBehaviors.SkipFixAllCheck }.RunAsync(); - } [Fact] - public async Task TestFixAll1() - { - await new VerifyCS.Test + public Task TestFixAll1() + => new VerifyCS.Test { TestCode = """ class C @@ -396,12 +355,10 @@ void Goo() """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestFixAll2() - { - await new VerifyCS.Test + public Task TestFixAll2() + => new VerifyCS.Test { TestCode = """ class C @@ -423,12 +380,10 @@ void Goo(bool b) """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestFixAll3() - { - await new VerifyCS.Test + public Task TestFixAll3() + => new VerifyCS.Test { TestCode = """ class C @@ -452,12 +407,12 @@ void Goo() """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestDoNotOfferIfTypeWouldChange() - { - var code = """ + public Task TestDoNotOfferIfTypeWouldChange() + => new VerifyCS.Test() + { + TestCode = """ struct S { void M() @@ -471,19 +426,15 @@ public override bool Equals(object obj) return base.Equals(obj); } } - """; - - await new VerifyCS.Test() - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestDoNotOfferIfTypeWouldChange2() - { - var code = """ + public Task TestDoNotOfferIfTypeWouldChange2() + => new VerifyCS.Test() + { + TestCode = """ struct S { void M() @@ -497,19 +448,13 @@ public override bool Equals(object obj) return base.Equals(obj); } } - """; - - await new VerifyCS.Test() - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestOnShadowedMethod() - { - await new VerifyCS.Test + public Task TestOnShadowedMethod() + => new VerifyCS.Test { TestCode = """ struct S @@ -537,12 +482,12 @@ void M() """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25456")] - public async Task TestNotInSwitchCase() - { - var code = """ + public Task TestNotInSwitchCase() + => new VerifyCS.Test() + { + TestCode = """ class C { void M() @@ -553,19 +498,15 @@ void M() } } } - """; - - await new VerifyCS.Test() - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestNotInSwitchCase_InsideParentheses() - { - var code = """ + public Task TestNotInSwitchCase_InsideParentheses() + => new VerifyCS.Test() + { + TestCode = """ class C { void M() @@ -576,19 +517,13 @@ void M() } } } - """; - - await new VerifyCS.Test() - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestInSwitchCase_InsideCast() - { - await new VerifyCS.Test + public Task TestInSwitchCase_InsideCast() + => new VerifyCS.Test { TestCode = """ class C @@ -616,12 +551,12 @@ void M() """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestNotInPatternSwitchCase() - { - var code = """ + public Task TestNotInPatternSwitchCase() + => new VerifyCS.Test() + { + TestCode = """ class C { void M() @@ -632,19 +567,15 @@ void M() } } } - """; - - await new VerifyCS.Test() - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestNotInPatternSwitchCase_InsideParentheses() - { - var code = """ + public Task TestNotInPatternSwitchCase_InsideParentheses() + => new VerifyCS.Test() + { + TestCode = """ class C { void M() @@ -655,19 +586,13 @@ void M() } } } - """; - - await new VerifyCS.Test() - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestInPatternSwitchCase_InsideCast() - { - await new VerifyCS.Test + public Task TestInPatternSwitchCase_InsideCast() + => new VerifyCS.Test { TestCode = """ class C @@ -695,12 +620,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestInPatternSwitchCase_InsideWhenClause() - { - await new VerifyCS.Test + public Task TestInPatternSwitchCase_InsideWhenClause() + => new VerifyCS.Test { TestCode = """ class C @@ -728,12 +651,12 @@ void M() """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestNotInPatternIs() - { - var code = """ + public Task TestNotInPatternIs() + => new VerifyCS.Test() + { + TestCode = """ class C { void M() @@ -741,19 +664,15 @@ void M() if (true is default(bool)); } } - """; - - await new VerifyCS.Test() - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestNotInPatternIs_InsideParentheses() - { - var code = """ + public Task TestNotInPatternIs_InsideParentheses() + => new VerifyCS.Test() + { + TestCode = """ class C { void M() @@ -761,19 +680,13 @@ void M() if (true is (default(bool))); } } - """; - - await new VerifyCS.Test() - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } [Fact] - public async Task TestInPatternIs_InsideCast() - { - await new VerifyCS.Test + public Task TestInPatternIs_InsideCast() + => new VerifyCS.Test { TestCode = """ class C @@ -795,5 +708,4 @@ void M() """, LanguageVersion = LanguageVersion.CSharp7_1 }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UseExplicitTupleName/UseExplicitTupleNameTests.cs b/src/Analyzers/CSharp/Tests/UseExplicitTupleName/UseExplicitTupleNameTests.cs index 402f7560bcd1d..7e05b0c9eaa5b 100644 --- a/src/Analyzers/CSharp/Tests/UseExplicitTupleName/UseExplicitTupleNameTests.cs +++ b/src/Analyzers/CSharp/Tests/UseExplicitTupleName/UseExplicitTupleNameTests.cs @@ -20,9 +20,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExplicitTupleName; public sealed class UseExplicitTupleNameTests { [Fact] - public async Task TestNamedTuple1() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestNamedTuple1() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -41,12 +40,10 @@ void M() } } """); - } [Fact] - public async Task TestInArgument() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestInArgument() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -69,12 +66,10 @@ void M() void Goo(int i) { } } """); - } [Fact] - public async Task TestNamedTuple2() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestNamedTuple2() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -93,7 +88,6 @@ void M() } } """); - } [Fact] public async Task TestMissingOnMatchingName1() @@ -130,9 +124,8 @@ void M() } [Fact] - public async Task TestWrongCasing() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestWrongCasing() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -151,12 +144,10 @@ void M() } } """); - } [Fact] - public async Task TestFixAll1() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestFixAll1() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -177,12 +168,10 @@ void M() } } """); - } [Fact] - public async Task TestFixAll2() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestFixAll2() + => VerifyCS.VerifyCodeFixAsync(""" class C { void M() @@ -201,12 +190,12 @@ void M() } } """); - } [Fact] - public async Task TestFalseOptionImplicitTuple() - { - var code = """ + public Task TestFalseOptionImplicitTuple() + => new VerifyCS.Test() + { + TestCode = """ class C { void M() @@ -215,22 +204,18 @@ void M() var v2 = v1.Item1; } } - """; - - await new VerifyCS.Test() - { - TestCode = code, + """, Options = { { CodeStyleOptions2.PreferExplicitTupleNames, false, NotificationOption2.Warning } } }.RunAsync(); - } [Fact] - public async Task TestFalseOptionExplicitTuple() - { - var code = """ + public Task TestFalseOptionExplicitTuple() + => new VerifyCS.Test() + { + TestCode = """ class C { void M() @@ -239,17 +224,12 @@ void M() var v2 = v1.i; } } - """; - - await new VerifyCS.Test() - { - TestCode = code, + """, Options = { { CodeStyleOptions2.PreferExplicitTupleNames, false, NotificationOption2.Warning } } }.RunAsync(); - } [Fact] public async Task TestOnRestField() diff --git a/src/Analyzers/CSharp/Tests/UseExplicitTypeForConst/UseExplicitTypeForConstTests.cs b/src/Analyzers/CSharp/Tests/UseExplicitTypeForConst/UseExplicitTypeForConstTests.cs index 8444ac27faa7f..32fc41fe0f985 100644 --- a/src/Analyzers/CSharp/Tests/UseExplicitTypeForConst/UseExplicitTypeForConstTests.cs +++ b/src/Analyzers/CSharp/Tests/UseExplicitTypeForConst/UseExplicitTypeForConstTests.cs @@ -25,9 +25,8 @@ internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProvide => (null, new UseExplicitTypeForConstCodeFixProvider()); [Fact] - public async Task TestWithIntLiteral() - { - await TestInRegularAndScriptAsync( + public Task TestWithIntLiteral() + => TestInRegularAndScriptAsync( """ class C { @@ -46,12 +45,10 @@ void M() } } """); - } [Fact] - public async Task TestWithStringConstant() - { - await TestInRegularAndScriptAsync( + public Task TestWithStringConstant() + => TestInRegularAndScriptAsync( """ class C { @@ -72,12 +69,10 @@ void M() } } """); - } [Fact] - public async Task TestWithQualifiedType() - { - await TestInRegularAndScriptAsync( + public Task TestWithQualifiedType() + => TestInRegularAndScriptAsync( """ class C { @@ -96,12 +91,10 @@ void M() } } """); - } [Fact] - public async Task TestWithNonConstantInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestWithNonConstantInitializer() + => TestInRegularAndScriptAsync( """ class C { @@ -120,12 +113,10 @@ void M() } } """); - } [Fact] - public async Task TestWithNonConstantTupleType() - { - await TestInRegularAndScriptAsync( + public Task TestWithNonConstantTupleType() + => TestInRegularAndScriptAsync( """ class C { @@ -144,12 +135,10 @@ void M() } } """); - } [Fact] - public async Task TestNotWithNullLiteral() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithNullLiteral() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -159,12 +148,10 @@ void M() } } """); - } [Fact] - public async Task TestNotWithDefaultLiteral() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithDefaultLiteral() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -174,12 +161,10 @@ void M() } } """); - } [Fact] - public async Task TestWithLambda() - { - await TestInRegularAndScriptAsync( + public Task TestWithLambda() + => TestInRegularAndScriptAsync( """ class C { @@ -198,12 +183,10 @@ void M() } } """); - } [Fact] - public async Task TestNotWithAnonymousType() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithAnonymousType() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -213,12 +196,10 @@ void M() } } """); - } [Fact] - public async Task TestNotWithArrayInitializer() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithArrayInitializer() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -228,12 +209,10 @@ void M() } } """); - } [Fact] - public async Task TestNotWithMissingInitializer() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithMissingInitializer() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -243,12 +222,10 @@ void M() } } """); - } [Fact] - public async Task TestNotWithClassVar() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithClassVar() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -259,24 +236,20 @@ void M() } } """); - } [Fact] - public async Task TestNotOnField() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOnField() + => TestMissingInRegularAndScriptAsync( """ class C { const [|var|] v = 0; } """); - } [Fact] - public async Task TestNotWithMultipleDeclarators() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithMultipleDeclarators() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -286,5 +259,4 @@ void M() } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForAccessorsAnalyzerTests.cs b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForAccessorsAnalyzerTests.cs index 206bad6e08a15..a11699e9d14f0 100644 --- a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForAccessorsAnalyzerTests.cs +++ b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForAccessorsAnalyzerTests.cs @@ -45,12 +45,11 @@ private static async Task TestWithUseExpressionBody( await test.RunAsync(); } - private static async Task TestWithUseExpressionBodyIncludingPropertiesAndIndexers( + private static Task TestWithUseExpressionBodyIncludingPropertiesAndIndexers( [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string code, [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) - { - await new VerifyCS.Test + => new VerifyCS.Test { ReferenceAssemblies = version == LanguageVersion.CSharp9 ? ReferenceAssemblies.Net.Net50 : ReferenceAssemblies.Default, TestCode = code, @@ -63,14 +62,12 @@ private static async Task TestWithUseExpressionBodyIncludingPropertiesAndIndexer { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenPossible }, } }.RunAsync(); - } - private static async Task TestWithUseBlockBodyIncludingPropertiesAndIndexers( + private static Task TestWithUseBlockBodyIncludingPropertiesAndIndexers( [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string code, [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) - { - await new VerifyCS.Test + => new VerifyCS.Test { ReferenceAssemblies = version == LanguageVersion.CSharp9 ? ReferenceAssemblies.Net.Net50 : ReferenceAssemblies.Default, TestCode = code, @@ -83,12 +80,10 @@ private static async Task TestWithUseBlockBodyIncludingPropertiesAndIndexers( { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, } }.RunAsync(); - } [Fact] - public async Task TestUseExpressionBody1() - { - var code = """ + public Task TestUseExpressionBody1() + => TestWithUseExpressionBody(""" class C { int Bar() { return 0; } @@ -101,8 +96,7 @@ int Goo }|} } } - """; - var fixedCode = """ + """, """ class C { int Bar() { return 0; } @@ -112,15 +106,11 @@ int Goo get => Bar(); } } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUpdatePropertyInsteadOfAccessor() - { - // TODO: Should this test move to properties tests? - var code = """ + public Task TestUpdatePropertyInsteadOfAccessor() + => TestWithUseExpressionBodyIncludingPropertiesAndIndexers(""" class C { int Bar() { return 0; } @@ -133,22 +123,18 @@ class C } }|} } - """; - var fixedCode = """ + """, """ class C { int Bar() { return 0; } int Goo => Bar(); } - """; - await TestWithUseExpressionBodyIncludingPropertiesAndIndexers(code, fixedCode); - } + """); [Fact] - public async Task TestOnIndexer1() - { - var code = """ + public Task TestOnIndexer1() + => TestWithUseExpressionBody(""" class C { int Bar() { return 0; } @@ -161,8 +147,7 @@ int this[int i] }|} } } - """; - var fixedCode = """ + """, """ class C { int Bar() { return 0; } @@ -172,15 +157,11 @@ int this[int i] get => Bar(); } } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUpdateIndexerIfIndexerAndAccessorCanBeUpdated() - { - // TODO: Should this test move to indexers tests? - var code = """ + public Task TestUpdateIndexerIfIndexerAndAccessorCanBeUpdated() + => TestWithUseExpressionBodyIncludingPropertiesAndIndexers(""" class C { int Bar() { return 0; } @@ -193,22 +174,18 @@ class C } }|} } - """; - var fixedCode = """ + """, """ class C { int Bar() { return 0; } int this[int i] => Bar(); } - """; - await TestWithUseExpressionBodyIncludingPropertiesAndIndexers(code, fixedCode); - } + """); [Fact] - public async Task TestOnSetter1() - { - var code = """ + public Task TestOnSetter1() + => TestWithUseExpressionBody(""" class C { void Bar() { } @@ -221,8 +198,7 @@ int Goo }|} } } - """; - var fixedCode = """ + """, """ class C { void Bar() { } @@ -232,15 +208,11 @@ int Goo set => Bar(); } } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestOnInit1() - { - var code = - """ + public Task TestOnInit1() + => TestWithUseExpressionBody(""" class C { int Goo @@ -253,9 +225,7 @@ int Goo int Bar() { return 0; } } - """; - var fixedCode = - """ + """, """ class C { int Goo @@ -265,14 +235,11 @@ int Goo int Bar() { return 0; } } - """; - await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp9); - } + """, LanguageVersion.CSharp9); [Fact] - public async Task TestMissingWithOnlySetter() - { - await VerifyCS.VerifyAnalyzerAsync(""" + public Task TestMissingWithOnlySetter() + => VerifyCS.VerifyAnalyzerAsync(""" class C { void Bar() { } @@ -283,13 +250,13 @@ int Goo } } """); - } [Fact] - public async Task TestMissingWithOnlyInit() - { - var code = - """ + public Task TestMissingWithOnlyInit() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.Net.Net50, + TestCode = """ class C { int Goo @@ -299,20 +266,13 @@ int Goo int Bar() { return 0; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.Net.Net50, - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestUseExpressionBody3() - { - var code = """ + public Task TestUseExpressionBody3() + => TestWithUseExpressionBody(""" using System; class C @@ -325,8 +285,7 @@ int Goo }|} } } - """; - var fixedCode = """ + """, """ using System; class C @@ -336,14 +295,11 @@ int Goo get => throw new NotImplementedException(); } } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseExpressionBody4() - { - var code = """ + public Task TestUseExpressionBody4() + => TestWithUseExpressionBody(""" using System; class C @@ -356,8 +312,7 @@ int Goo }|} } } - """; - var fixedCode = """ + """, """ using System; class C @@ -367,14 +322,11 @@ int Goo get => throw new NotImplementedException(); // comment } } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/59255")] - public async Task TestUseExpressionBody5() - { - var code = """ + public Task TestUseExpressionBody5() + => TestWithUseExpressionBody(""" using System; class C @@ -392,8 +344,7 @@ event EventHandler Goo }|} } } - """; - var fixedCode = """ + """, """ using System; class C @@ -405,14 +356,11 @@ event EventHandler Goo remove => throw new NotImplementedException(); } } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBody1() - { - var code = """ + public Task TestUseBlockBody1() + => TestWithUseBlockBodyIncludingPropertiesAndIndexers(""" class C { int Bar() { return 0; } @@ -422,8 +370,7 @@ int Goo {|IDE0027:get => Bar();|} } } - """; - var fixedCode = """ + """, """ class C { int Bar() { return 0; } @@ -436,14 +383,11 @@ int Goo } } } - """; - await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBodyForSetter1() - { - var code = """ + public Task TestUseBlockBodyForSetter1() + => TestWithUseBlockBodyIncludingPropertiesAndIndexers(""" class C { void Bar() { } @@ -453,8 +397,7 @@ int Goo {|IDE0027:set => Bar();|} } } - """; - var fixedCode = """ + """, """ class C { void Bar() { } @@ -467,15 +410,11 @@ int Goo } } } - """; - await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBodyForInit1() - { - var code = - """ + public Task TestUseBlockBodyForInit1() + => TestWithUseBlockBodyIncludingPropertiesAndIndexers(""" class C { int Goo @@ -485,9 +424,7 @@ int Goo int Bar() { return 0; } } - """; - var fixedCode = - """ + """, """ class C { int Goo @@ -500,15 +437,11 @@ int Goo int Bar() { return 0; } } - """; - - await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode, LanguageVersion.CSharp9); - } + """, LanguageVersion.CSharp9); [Fact] - public async Task TestUseBlockBody3() - { - var code = """ + public Task TestUseBlockBody3() + => TestWithUseBlockBodyIncludingPropertiesAndIndexers(""" using System; class C @@ -518,8 +451,7 @@ int Goo {|IDE0027:get => throw new NotImplementedException();|} } } - """; - var fixedCode = """ + """, """ using System; class C @@ -532,14 +464,11 @@ int Goo } } } - """; - await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBody4() - { - var code = """ + public Task TestUseBlockBody4() + => TestWithUseBlockBodyIncludingPropertiesAndIndexers(""" using System; class C @@ -549,8 +478,7 @@ int Goo {|IDE0027:get => throw new NotImplementedException();|} // comment } } - """; - var fixedCode = """ + """, """ using System; class C @@ -563,14 +491,13 @@ int Goo } } } - """; - await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31308")] - public async Task TestUseBlockBody5() - { - var code = """ + public Task TestUseBlockBody5() + => new VerifyCS.Test + { + TestCode = """ class C { C this[int index] @@ -578,10 +505,7 @@ C this[int index] get => default; } } - """; - await new VerifyCS.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.None }, @@ -589,12 +513,10 @@ C this[int index] { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.None }, } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/59255")] - public async Task TestUseBlockBody6() - { - var code = """ + public Task TestUseBlockBody6() + => TestWithUseBlockBodyIncludingPropertiesAndIndexers(""" using System; class C @@ -605,8 +527,7 @@ event EventHandler Goo {|IDE0027:remove => throw new NotImplementedException();|} } } - """; - var fixedCode = """ + """, """ using System; class C @@ -624,22 +545,18 @@ event EventHandler Goo } } } - """; - await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20350")] - public async Task TestAccessorListFormatting() - { - var code = """ + public Task TestAccessorListFormatting() + => TestWithUseBlockBodyIncludingPropertiesAndIndexers(""" class C { int Bar() { return 0; } int Goo { {|IDE0027:get => Bar();|} } } - """; - var fixedCode = """ + """, """ class C { int Bar() { return 0; } @@ -652,23 +569,13 @@ int Goo } } } - """; - await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); - } + """); [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/20350")] [WorkItem("https://github.com/dotnet/roslyn/issues/61279")] public async Task TestAccessorListFormatting_FixAll1() { - var code = """ - class C - { - int Bar() { return 0; } - - int Goo { {|IDE0027:get => Bar();|} {|IDE0027:set => Bar();|} } - } - """; var fixedCode = """ class C { @@ -690,7 +597,14 @@ int Goo """; await new VerifyCS.Test { - TestCode = code, + TestCode = """ + class C + { + int Bar() { return 0; } + + int Goo { {|IDE0027:get => Bar();|} {|IDE0027:set => Bar();|} } + } + """, FixedCode = fixedCode, BatchFixedCode = fixedCode, Options = @@ -705,17 +619,18 @@ int Goo [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/20350")] [WorkItem("https://github.com/dotnet/roslyn/issues/61279")] - public async Task TestAccessorListFormatting_FixAll2() - { - var code = """ + public Task TestAccessorListFormatting_FixAll2() + => new VerifyCS.Test + { + TestCode = """ class C { int Bar() { return 0; } int Goo { {|IDE0027:get => Bar();|} {|IDE0027:set => Bar();|} } } - """; - var fixedCode = """ + """, + FixedCode = """ class C { int Bar() { return 0; } @@ -729,8 +644,8 @@ int Goo set => Bar(); } } - """; - var batchFixedCode = """ + """, + BatchFixedCode = """ class C { int Bar() { return 0; } @@ -748,12 +663,7 @@ int Goo } } } - """; - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, - BatchFixedCode = batchFixedCode, + """, DiagnosticSelector = diagnostics => diagnostics[0], CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, Options = @@ -771,22 +681,22 @@ int Goo } }, }.RunAsync(); - } [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/20350")] [WorkItem("https://github.com/dotnet/roslyn/issues/61279")] - public async Task TestAccessorListFormatting_FixAll3() - { - var code = """ + public Task TestAccessorListFormatting_FixAll3() + => new VerifyCS.Test + { + TestCode = """ class C { int Bar() { return 0; } int Goo { {|IDE0027:get => Bar();|} {|IDE0027:set => Bar();|} } } - """; - var fixedCode = """ + """, + FixedCode = """ class C { int Bar() { return 0; } @@ -800,8 +710,8 @@ int Goo } } } - """; - var batchFixedCode = """ + """, + BatchFixedCode = """ class C { int Bar() { return 0; } @@ -819,12 +729,7 @@ int Goo } } } - """; - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, - BatchFixedCode = batchFixedCode, + """, DiagnosticSelector = diagnostics => diagnostics[1], CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, Options = @@ -842,22 +747,12 @@ int Goo } }, }.RunAsync(); - } [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/20350")] [WorkItem("https://github.com/dotnet/roslyn/issues/61279")] public async Task TestAccessorListFormatting_FixAll4() { - var code = - """ - class C - { - int Goo { {|IDE0027:get => Bar();|} {|IDE0027:init => Bar();|} } - - int Bar() { return 0; } - } - """; var fixedCode = """ class C @@ -882,7 +777,14 @@ int Goo await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, - TestCode = code, + TestCode = """ + class C + { + int Goo { {|IDE0027:get => Bar();|} {|IDE0027:init => Bar();|} } + + int Bar() { return 0; } + } + """, FixedCode = fixedCode, BatchFixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp9, @@ -896,16 +798,14 @@ int Goo } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20362")] - public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp7() - { - var code = """ + public Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp7() + => TestWithUseExpressionBody(""" using System; class C { int Goo { {|IDE0027:get {|CS8059:=>|} {|CS8059:throw|} new NotImplementedException();|} } } - """; - var fixedCode = """ + """, """ using System; class C { @@ -917,22 +817,18 @@ int Goo } } } - """; - await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); - } + """, LanguageVersion.CSharp6); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20362")] - public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp7_FixAll() - { - var code = """ + public Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp7_FixAll() + => TestWithUseExpressionBody(""" using System; class C { int Goo { {|IDE0027:get {|CS8059:=>|} {|CS8059:throw|} new NotImplementedException();|} } int Bar { {|IDE0027:get {|CS8059:=>|} {|CS8059:throw|} new NotImplementedException();|} } } - """; - var fixedCode = """ + """, """ using System; class C { @@ -951,7 +847,5 @@ int Bar } } } - """; - await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); - } + """, LanguageVersion.CSharp6); } diff --git a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForConstructorsAnalyzerTests.cs b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForConstructorsAnalyzerTests.cs index c32c861fc9a21..36394ae720e77 100644 --- a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForConstructorsAnalyzerTests.cs +++ b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForConstructorsAnalyzerTests.cs @@ -21,31 +21,26 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody; [Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public sealed class UseExpressionBodyForConstructorsAnalyzerTests { - private static async Task TestWithUseExpressionBody(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) - { - await new VerifyCS.Test + private static Task TestWithUseExpressionBody(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) + => new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, ExpressionBodyPreference.WhenPossible } } }.RunAsync(); - } - private static async Task TestWithUseBlockBody(string code, string fixedCode) - { - await new VerifyCS.Test + private static Task TestWithUseBlockBody(string code, string fixedCode) + => new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, ExpressionBodyPreference.Never } } }.RunAsync(); - } [Fact] - public async Task TestUseExpressionBody1() - { - var code = """ + public Task TestUseExpressionBody1() + => TestWithUseExpressionBody(""" class C { void Bar() { } @@ -55,22 +50,18 @@ void Bar() { } Bar(); }|} } - """; - var fixedCode = """ + """, """ class C { void Bar() { } public C() => Bar(); } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseExpressionBody2() - { - var code = """ + public Task TestUseExpressionBody2() + => TestWithUseExpressionBody(""" class C { int a; @@ -82,8 +73,7 @@ class C int Bar() { return 0; } } - """; - var fixedCode = """ + """, """ class C { int a; @@ -92,14 +82,11 @@ class C int Bar() { return 0; } } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseExpressionBody3() - { - var code = """ + public Task TestUseExpressionBody3() + => TestWithUseExpressionBody(""" using System; class C @@ -109,22 +96,18 @@ class C throw new NotImplementedException(); }|} } - """; - var fixedCode = """ + """, """ using System; class C { public C() => throw new NotImplementedException(); } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseExpressionBody4() - { - var code = """ + public Task TestUseExpressionBody4() + => TestWithUseExpressionBody(""" using System; class C @@ -134,30 +117,25 @@ class C throw new NotImplementedException(); // comment }|} } - """; - var fixedCode = """ + """, """ using System; class C { public C() => throw new NotImplementedException(); // comment } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBody1() - { - var code = """ + public Task TestUseBlockBody1() + => TestWithUseBlockBody(""" class C { {|IDE0021:public C() => Bar();|} void Bar() { } } - """; - var fixedCode = """ + """, """ class C { public C() @@ -167,14 +145,11 @@ public C() void Bar() { } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBody2() - { - var code = """ + public Task TestUseBlockBody2() + => TestWithUseBlockBody(""" class C { int a; @@ -183,8 +158,7 @@ class C int Bar() { return 0; } } - """; - var fixedCode = """ + """, """ class C { int a; @@ -196,22 +170,18 @@ public C() int Bar() { return 0; } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBody3() - { - var code = """ + public Task TestUseBlockBody3() + => TestWithUseBlockBody(""" using System; class C { {|IDE0021:public C() => throw new NotImplementedException();|} } - """; - var fixedCode = """ + """, """ using System; class C @@ -221,22 +191,18 @@ public C() throw new NotImplementedException(); } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBody4() - { - var code = """ + public Task TestUseBlockBody4() + => TestWithUseBlockBody(""" using System; class C { {|IDE0021:public C() => throw new NotImplementedException();|} // comment } - """; - var fixedCode = """ + """, """ using System; class C @@ -246,21 +212,17 @@ public C() throw new NotImplementedException(); // comment } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20362")] - public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp7() - { - var code = """ + public Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp7() + => TestWithUseExpressionBody(""" using System; class C { {|IDE0021:public C() {|CS8059:=>|} {|CS8059:throw|} new NotImplementedException();|} } - """; - var fixedCode = """ + """, """ using System; class C { @@ -269,22 +231,18 @@ public C() throw new NotImplementedException(); } } - """; - await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); - } + """, LanguageVersion.CSharp6); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20362")] - public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp7_FixAll() - { - var code = """ + public Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp7_FixAll() + => TestWithUseExpressionBody(""" using System; class C { {|IDE0021:public C() {|CS8059:=>|} {|CS8059:throw|} new NotImplementedException();|} {|IDE0021:public C(int i) {|CS8059:=>|} {|CS8059:throw|} new NotImplementedException();|} } - """; - var fixedCode = """ + """, """ using System; class C { @@ -298,7 +256,5 @@ public C(int i) throw new NotImplementedException(); } } - """; - await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); - } + """, LanguageVersion.CSharp6); } diff --git a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForConversionOperatorsAnalyzerTests.cs b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForConversionOperatorsAnalyzerTests.cs index 085d814073656..17ae43745aa5c 100644 --- a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForConversionOperatorsAnalyzerTests.cs +++ b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForConversionOperatorsAnalyzerTests.cs @@ -19,30 +19,25 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody; [Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public sealed class UseExpressionBodyForConversionOperatorsAnalyzerTests { - private static async Task TestWithUseExpressionBody(string code, string fixedCode) - { - await new VerifyCS.Test + private static Task TestWithUseExpressionBody(string code, string fixedCode) + => new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedOperators, ExpressionBodyPreference.WhenPossible } } }.RunAsync(); - } - private static async Task TestWithUseBlockBody(string code, string fixedCode) - { - await new VerifyCS.Test + private static Task TestWithUseBlockBody(string code, string fixedCode) + => new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedOperators, ExpressionBodyPreference.Never } } }.RunAsync(); - } [Fact] - public async Task TestUseExpressionBody1() - { - var code = """ + public Task TestUseExpressionBody1() + => TestWithUseExpressionBody(""" class C { static int Bar() { return 0; } @@ -52,22 +47,18 @@ class C Bar(); }|} } - """; - var fixedCode = """ + """, """ class C { static int Bar() { return 0; } public static implicit operator C(int i) => Bar(); } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseExpressionBody2() - { - var code = """ + public Task TestUseExpressionBody2() + => TestWithUseExpressionBody(""" class C { static int Bar() { return 0; } @@ -77,22 +68,18 @@ class C return Bar(); }|} } - """; - var fixedCode = """ + """, """ class C { static int Bar() { return 0; } public static implicit operator C(int i) => Bar(); } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseExpressionBody3() - { - var code = """ + public Task TestUseExpressionBody3() + => TestWithUseExpressionBody(""" using System; class C @@ -102,22 +89,18 @@ class C throw new NotImplementedException(); }|} } - """; - var fixedCode = """ + """, """ using System; class C { public static implicit operator C(int i) => throw new NotImplementedException(); } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseExpressionBody4() - { - var code = """ + public Task TestUseExpressionBody4() + => TestWithUseExpressionBody(""" using System; class C @@ -127,30 +110,25 @@ class C throw new NotImplementedException(); // comment }|} } - """; - var fixedCode = """ + """, """ using System; class C { public static implicit operator C(int i) => throw new NotImplementedException(); // comment } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBody1() - { - var code = """ + public Task TestUseBlockBody1() + => TestWithUseBlockBody(""" class C { static int Bar() { return 0; } {|IDE0023:public static implicit operator C(int i) => Bar();|} } - """; - var fixedCode = """ + """, """ class C { static int Bar() { return 0; } @@ -160,22 +138,18 @@ public static implicit operator C(int i) return Bar(); } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBody3() - { - var code = """ + public Task TestUseBlockBody3() + => TestWithUseBlockBody(""" using System; class C { {|IDE0023:public static implicit operator C(int i) => throw new NotImplementedException();|} } - """; - var fixedCode = """ + """, """ using System; class C @@ -185,22 +159,18 @@ public static implicit operator C(int i) throw new NotImplementedException(); } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBody4() - { - var code = """ + public Task TestUseBlockBody4() + => TestWithUseBlockBody(""" using System; class C { {|IDE0023:public static implicit operator C(int i) => throw new NotImplementedException();|} // comment } - """; - var fixedCode = """ + """, """ using System; class C @@ -210,7 +180,5 @@ public static implicit operator C(int i) throw new NotImplementedException(); // comment } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); } diff --git a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForIndexersAnalyzerTests.cs b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForIndexersAnalyzerTests.cs index edab33e19c9b6..e8f444576fad4 100644 --- a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForIndexersAnalyzerTests.cs +++ b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForIndexersAnalyzerTests.cs @@ -20,9 +20,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody; [Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public sealed class UseExpressionBodyForIndexersAnalyzerTests { - private static async Task TestWithUseExpressionBody(string code, string fixedCode) - { - await new VerifyCS.Test + private static Task TestWithUseExpressionBody(string code, string fixedCode) + => new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, @@ -32,11 +31,9 @@ private static async Task TestWithUseExpressionBody(string code, string fixedCod { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never }, } }.RunAsync(); - } - private static async Task TestWithUseBlockBody(string code, string fixedCode) - { - await new VerifyCS.Test + private static Task TestWithUseBlockBody(string code, string fixedCode) + => new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, @@ -46,12 +43,10 @@ private static async Task TestWithUseBlockBody(string code, string fixedCode) { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never }, } }.RunAsync(); - } [Fact] - public async Task TestUseExpressionBody1() - { - var code = """ + public Task TestUseExpressionBody1() + => TestWithUseExpressionBody(""" class C { int Bar() { return 0; } @@ -64,17 +59,14 @@ class C } }|} } - """; - var fixedCode = """ + """, """ class C { int Bar() { return 0; } int this[int i] => Bar(); } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] public async Task TestMissingWithSetter() @@ -121,9 +113,8 @@ int this[int i] } [Fact] - public async Task TestUseExpressionBody3() - { - var code = """ + public Task TestUseExpressionBody3() + => TestWithUseExpressionBody(""" using System; class C @@ -136,22 +127,18 @@ class C } }|} } - """; - var fixedCode = """ + """, """ using System; class C { int this[int i] => throw new NotImplementedException(); } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseExpressionBody4() - { - var code = """ + public Task TestUseExpressionBody4() + => TestWithUseExpressionBody(""" using System; class C @@ -164,30 +151,25 @@ class C } }|} } - """; - var fixedCode = """ + """, """ using System; class C { int this[int i] => throw new NotImplementedException(); // comment } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBody1() - { - var code = """ + public Task TestUseBlockBody1() + => TestWithUseBlockBody(""" class C { int Bar() { return 0; } {|IDE0026:int this[int i] => Bar();|} } - """; - var fixedCode = """ + """, """ class C { int Bar() { return 0; } @@ -200,22 +182,21 @@ int this[int i] } } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20363")] - public async Task TestUseBlockBodyForAccessorEventWhenAccessorWantExpression1() - { - var code = """ + public Task TestUseBlockBodyForAccessorEventWhenAccessorWantExpression1() + => new VerifyCS.Test + { + TestCode = """ class C { int Bar() { return 0; } {|IDE0026:int this[int i] => Bar();|} } - """; - var fixedCode = """ + """, + FixedCode = """ class C { int Bar() { return 0; } @@ -225,11 +206,7 @@ int this[int i] get => Bar(); } } - """; - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, @@ -238,20 +215,17 @@ int this[int i] NumberOfFixAllIterations = 2, NumberOfIncrementalIterations = 2, }.RunAsync(); - } [Fact] - public async Task TestUseBlockBody3() - { - var code = """ + public Task TestUseBlockBody3() + => TestWithUseBlockBody(""" using System; class C { {|IDE0026:int this[int i] => throw new NotImplementedException();|} } - """; - var fixedCode = """ + """, """ using System; class C @@ -264,22 +238,18 @@ int this[int i] } } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBody4() - { - var code = """ + public Task TestUseBlockBody4() + => TestWithUseBlockBody(""" using System; class C { {|IDE0026:int this[int i] => throw new NotImplementedException();|} // comment } - """; - var fixedCode = """ + """, """ using System; class C @@ -292,7 +262,5 @@ int this[int i] } } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); } diff --git a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForLocalFunctionsAnalyzerTests.cs b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForLocalFunctionsAnalyzerTests.cs index 63566f2a6fa17..767b47d785c85 100644 --- a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForLocalFunctionsAnalyzerTests.cs +++ b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForLocalFunctionsAnalyzerTests.cs @@ -22,41 +22,34 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody; [Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public sealed class UseExpressionBodyForLocalFunctionsAnalyzerTests { - private static async Task TestWithUseExpressionBody(string code, string fixedCode) - { - await new VerifyCS.Test + private static Task TestWithUseExpressionBody(string code, string fixedCode) + => new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, ExpressionBodyPreference.WhenPossible } } }.RunAsync(); - } - private static async Task TestWithUseExpressionBodyWhenOnSingleLine(string code, string fixedCode) - { - await new VerifyCS.Test + private static Task TestWithUseExpressionBodyWhenOnSingleLine(string code, string fixedCode) + => new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, ExpressionBodyPreference.WhenOnSingleLine } } }.RunAsync(); - } - private static async Task TestWithUseBlockBody(string code, string fixedCode, ReferenceAssemblies? referenceAssemblies = null) - { - await new VerifyCS.Test + private static Task TestWithUseBlockBody(string code, string fixedCode, ReferenceAssemblies? referenceAssemblies = null) + => new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, ExpressionBodyPreference.Never } }, ReferenceAssemblies = referenceAssemblies ?? ReferenceAssemblies.Default, }.RunAsync(); - } [Fact] - public async Task TestUseExpressionBody1() - { - var code = """ + public Task TestUseExpressionBody1() + => TestWithUseExpressionBody(""" class C { void Test() { } @@ -69,8 +62,7 @@ void Goo() }|} } } - """; - var fixedCode = """ + """, """ class C { void Test() { } @@ -80,14 +72,11 @@ void Goo() void Bar() => Test(); } } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseExpressionBody2() - { - var code = """ + public Task TestUseExpressionBody2() + => TestWithUseExpressionBody(""" class C { int Test() { return 0; } @@ -100,8 +89,7 @@ void Goo() }|} } } - """; - var fixedCode = """ + """, """ class C { int Test() { return 0; } @@ -111,14 +99,11 @@ void Goo() int Bar() => Test(); } } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseExpressionBody3() - { - var code = """ + public Task TestUseExpressionBody3() + => TestWithUseExpressionBody(""" using System; class C @@ -131,8 +116,7 @@ void Goo() }|} } } - """; - var fixedCode = """ + """, """ using System; class C @@ -142,14 +126,11 @@ void Goo() int Bar() => throw new NotImplementedException(); } } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseExpressionBody4() - { - var code = """ + public Task TestUseExpressionBody4() + => TestWithUseExpressionBody(""" using System; class C @@ -162,8 +143,7 @@ void Goo() }|} } } - """; - var fixedCode = """ + """, """ using System; class C @@ -173,9 +153,7 @@ void Goo() int Bar() => throw new NotImplementedException(); // comment } } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] public async Task TestUseExpressionBodyWhenOnSingleLineMissing() @@ -198,9 +176,8 @@ int Bar() } [Fact] - public async Task TestUseExpressionBodyWhenOnSingleLine() - { - var code = """ + public Task TestUseExpressionBodyWhenOnSingleLine() + => TestWithUseExpressionBodyWhenOnSingleLine(""" class C { void Goo() @@ -211,8 +188,7 @@ void Goo() }|} } } - """; - var fixedCode = """ + """, """ class C { void Goo() @@ -220,14 +196,11 @@ void Goo() int Bar() => 1 + 2 + 3; } } - """; - await TestWithUseExpressionBodyWhenOnSingleLine(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBody1() - { - var code = """ + public Task TestUseBlockBody1() + => TestWithUseBlockBody(""" class C { void Test() { } @@ -237,8 +210,7 @@ void Goo() {|IDE0061:void Bar() => Test();|} } } - """; - var fixedCode = """ + """, """ class C { void Test() { } @@ -251,14 +223,11 @@ void Bar() } } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBody2() - { - var code = """ + public Task TestUseBlockBody2() + => TestWithUseBlockBody(""" class C { int Test() { return 0; } @@ -268,8 +237,7 @@ void Goo() {|IDE0061:int Bar() => Test();|} } } - """; - var fixedCode = """ + """, """ class C { int Test() { return 0; } @@ -282,14 +250,11 @@ int Bar() } } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBody3() - { - var code = """ + public Task TestUseBlockBody3() + => TestWithUseBlockBody(""" using System; class C @@ -299,8 +264,7 @@ void Goo() {|IDE0061:int Bar() => throw new NotImplementedException();|} } } - """; - var fixedCode = """ + """, """ using System; class C @@ -313,14 +277,11 @@ int Bar() } } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBody4() - { - var code = """ + public Task TestUseBlockBody4() + => TestWithUseBlockBody(""" using System; class C @@ -330,8 +291,7 @@ void Goo() {|IDE0061:int Bar() => throw new NotImplementedException();|} // comment } } - """; - var fixedCode = """ + """, """ using System; class C @@ -344,14 +304,11 @@ int Bar() } } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact] - public async Task TestComments1() - { - var code = """ + public Task TestComments1() + => TestWithUseExpressionBody(""" class C { void Test() { } @@ -365,8 +322,7 @@ void Goo() }|} } } - """; - var fixedCode = """ + """, """ class C { void Test() { } @@ -378,14 +334,11 @@ void Bar() => Test(); } } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestComments2() - { - var code = """ + public Task TestComments2() + => TestWithUseExpressionBody(""" class C { int Test() { return 0; } @@ -399,8 +352,7 @@ void Goo() }|} } } - """; - var fixedCode = """ + """, """ class C { int Test() { return 0; } @@ -412,14 +364,11 @@ int Bar() => Test(); } } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestComments3() - { - var code = """ + public Task TestComments3() + => TestWithUseExpressionBody(""" using System; class C @@ -435,8 +384,7 @@ void Goo() }|} } } - """; - var fixedCode = """ + """, """ using System; class C @@ -450,14 +398,11 @@ void Bar() => throw Test(); } } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestComments4() - { - var code = """ + public Task TestComments4() + => TestWithUseExpressionBody(""" class C { void Test() { } @@ -470,8 +415,7 @@ void Goo() }|} } } - """; - var fixedCode = """ + """, """ class C { void Test() { } @@ -481,14 +425,11 @@ void Goo() void Bar() => Test(); // Comment } } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestComments5() - { - var code = """ + public Task TestComments5() + => TestWithUseExpressionBody(""" class C { int Test() { return 0; } @@ -501,8 +442,7 @@ void Goo() }|} } } - """; - var fixedCode = """ + """, """ class C { int Test() { return 0; } @@ -512,14 +452,11 @@ void Goo() int Bar() => Test(); // Comment } } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestComments6() - { - var code = """ + public Task TestComments6() + => TestWithUseExpressionBody(""" using System; class C @@ -534,8 +471,7 @@ void Goo() }|} } } - """; - var fixedCode = """ + """, """ using System; class C @@ -547,14 +483,11 @@ void Goo() void Bar() => throw Test(); // Comment } } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestDirectives1() - { - var code = """ + public Task TestDirectives1() + => TestWithUseExpressionBody(""" #define DEBUG using System; @@ -570,8 +503,7 @@ void Method() }|} } } - """; - var fixedCode = """ + """, """ #define DEBUG using System; @@ -586,14 +518,11 @@ void Bar() => } } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestDirectives2() - { - var code = """ + public Task TestDirectives2() + => TestWithUseExpressionBody(""" #define DEBUG using System; @@ -611,8 +540,7 @@ void Method() }|} } } - """; - var fixedCode = """ + """, """ #define DEBUG using System; @@ -629,14 +557,11 @@ void Bar() => } } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBodyAsync1() - { - var code = """ + public Task TestUseBlockBodyAsync1() + => TestWithUseBlockBody(""" using System.Threading.Tasks; class C @@ -648,8 +573,7 @@ async Task Goo() Task Test() { return Task.CompletedTask; } } - """; - var fixedCode = """ + """, """ using System.Threading.Tasks; class C @@ -664,14 +588,11 @@ async Task Bar() Task Test() { return Task.CompletedTask; } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBodyAsync2() - { - var code = """ + public Task TestUseBlockBodyAsync2() + => TestWithUseBlockBody(""" using System.Threading.Tasks; class C @@ -683,8 +604,7 @@ async void Goo() Task Test() { return Task.CompletedTask; } } - """; - var fixedCode = """ + """, """ using System.Threading.Tasks; class C @@ -699,14 +619,11 @@ async void Bar() Task Test() { return Task.CompletedTask; } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBodyAsync3() - { - var code = """ + public Task TestUseBlockBodyAsync3() + => TestWithUseBlockBody(""" using System.Threading.Tasks; class C @@ -718,8 +635,7 @@ void Goo() Task Bar() { return Task.CompletedTask; } } - """; - var fixedCode = """ + """, """ using System.Threading.Tasks; class C @@ -734,14 +650,11 @@ async ValueTask Test() Task Bar() { return Task.CompletedTask; } } - """; - await TestWithUseBlockBody(code, fixedCode, ReferenceAssemblies.NetStandard.NetStandard21); - } + """, ReferenceAssemblies.NetStandard.NetStandard21); [Fact] - public async Task TestUseBlockBodyAsync4() - { - var code = """ + public Task TestUseBlockBodyAsync4() + => TestWithUseBlockBody(""" using System.Threading.Tasks; class C @@ -753,8 +666,7 @@ void Goo() Task Bar() { return Task.FromResult(0); } } - """; - var fixedCode = """ + """, """ using System.Threading.Tasks; class C @@ -769,14 +681,11 @@ Task Test() Task Bar() { return Task.FromResult(0); } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBodyAsync5() - { - var code = """ + public Task TestUseBlockBodyAsync5() + => TestWithUseBlockBody(""" using System.Threading.Tasks; class C @@ -788,8 +697,7 @@ void Goo() Task Bar() { return Task.CompletedTask; } } - """; - var fixedCode = """ + """, """ using System.Threading.Tasks; class C @@ -804,14 +712,11 @@ Task Test() Task Bar() { return Task.CompletedTask; } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBodyNestedLocalFunction() - { - var code = """ + public Task TestUseBlockBodyNestedLocalFunction() + => TestWithUseBlockBody(""" class C { void NestedTest() { } @@ -824,8 +729,7 @@ void Bar() } } } - """; - var fixedCode = """ + """, """ class C { void NestedTest() { } @@ -841,14 +745,11 @@ void Test() } } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseExpressionBodyNestedLocalFunction() - { - var code = """ + public Task TestUseExpressionBodyNestedLocalFunction() + => TestWithUseExpressionBody(""" class C { void NestedTest() { } @@ -864,8 +765,7 @@ void Bar() } } } - """; - var fixedCode = """ + """, """ class C { void NestedTest() { } @@ -878,14 +778,11 @@ void Bar() } } } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57570")] - public async Task TestUseExpressionBodyTopLevelStatment() - { - await new VerifyCS.Test + public Task TestUseExpressionBodyTopLevelStatment() + => new VerifyCS.Test { TestState = { @@ -912,12 +809,10 @@ public async Task TestUseExpressionBodyTopLevelStatment() LanguageVersion = LanguageVersion.CSharp9, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, ExpressionBodyPreference.WhenPossible } }, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57570")] - public async Task TestUseBlockBodyTopLevelStatment() - { - await new VerifyCS.Test + public Task TestUseBlockBodyTopLevelStatment() + => new VerifyCS.Test { TestState = { @@ -941,5 +836,4 @@ public async Task TestUseBlockBodyTopLevelStatment() LanguageVersion = LanguageVersion.CSharp9, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, ExpressionBodyPreference.Never } }, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForMethodsAnalyzerTests.cs b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForMethodsAnalyzerTests.cs index a18a3ba22b7cc..e59d05e8281db 100644 --- a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForMethodsAnalyzerTests.cs +++ b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForMethodsAnalyzerTests.cs @@ -22,27 +22,23 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody; [Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public sealed class UseExpressionBodyForMethodsAnalyzerTests { - private static async Task TestWithUseExpressionBody(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) - { - await new VerifyCS.Test + private static Task TestWithUseExpressionBody(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) + => new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedMethods, ExpressionBodyPreference.WhenPossible } } }.RunAsync(); - } - private static async Task TestWithUseBlockBody(string code, string fixedCode, ReferenceAssemblies? referenceAssemblies = null) - { - await new VerifyCS.Test + private static Task TestWithUseBlockBody(string code, string fixedCode, ReferenceAssemblies? referenceAssemblies = null) + => new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedMethods, ExpressionBodyPreference.Never } }, ReferenceAssemblies = referenceAssemblies ?? ReferenceAssemblies.Default, }.RunAsync(); - } [Fact] public void TestOptionEditorConfig1() @@ -81,9 +77,8 @@ public void TestOptionEditorConfig1() } [Fact] - public async Task TestUseExpressionBody1() - { - var code = """ + public Task TestUseExpressionBody1() + => TestWithUseExpressionBody(""" class C { void Bar() => Bar(); @@ -93,22 +88,18 @@ class C Bar(); }|} } - """; - var fixedCode = """ + """, """ class C { void Bar() => Bar(); void Goo() => Bar(); } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseExpressionBody2() - { - var code = """ + public Task TestUseExpressionBody2() + => TestWithUseExpressionBody(""" class C { int Bar() => 0; @@ -118,22 +109,18 @@ class C return Bar(); }|} } - """; - var fixedCode = """ + """, """ class C { int Bar() => 0; int Goo() => Bar(); } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseExpressionBody3() - { - var code = """ + public Task TestUseExpressionBody3() + => TestWithUseExpressionBody(""" using System; class C @@ -143,22 +130,18 @@ class C throw new NotImplementedException(); }|} } - """; - var fixedCode = """ + """, """ using System; class C { int Goo() => throw new NotImplementedException(); } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseExpressionBody4() - { - var code = """ + public Task TestUseExpressionBody4() + => TestWithUseExpressionBody(""" using System; class C @@ -168,30 +151,25 @@ class C throw new NotImplementedException(); // comment }|} } - """; - var fixedCode = """ + """, """ using System; class C { int Goo() => throw new NotImplementedException(); // comment } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBody1() - { - var code = """ + public Task TestUseBlockBody1() + => TestWithUseBlockBody(""" class C { void Bar() { } {|IDE0022:void Goo() => Bar();|} } - """; - var fixedCode = """ + """, """ class C { void Bar() { } @@ -201,22 +179,18 @@ void Goo() Bar(); } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBody2() - { - var code = """ + public Task TestUseBlockBody2() + => TestWithUseBlockBody(""" class C { int Bar() { return 0; } {|IDE0022:int Goo() => Bar();|} } - """; - var fixedCode = """ + """, """ class C { int Bar() { return 0; } @@ -226,22 +200,18 @@ int Goo() return Bar(); } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBody3() - { - var code = """ + public Task TestUseBlockBody3() + => TestWithUseBlockBody(""" using System; class C { {|IDE0022:int Goo() => throw new NotImplementedException();|} } - """; - var fixedCode = """ + """, """ using System; class C @@ -251,22 +221,18 @@ int Goo() throw new NotImplementedException(); } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBody4() - { - var code = """ + public Task TestUseBlockBody4() + => TestWithUseBlockBody(""" using System; class C { {|IDE0022:int Goo() => throw new NotImplementedException();|} // comment } - """; - var fixedCode = """ + """, """ using System; class C @@ -276,14 +242,11 @@ int Goo() throw new NotImplementedException(); // comment } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact] - public async Task TestComments1() - { - var code = """ + public Task TestComments1() + => TestWithUseExpressionBody(""" class C { void Bar() => Bar(); @@ -294,8 +257,7 @@ class C Bar(); }|} } - """; - var fixedCode = """ + """, """ class C { void Bar() => Bar(); @@ -304,14 +266,11 @@ void Goo() => // Comment Bar(); } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestComments2() - { - var code = """ + public Task TestComments2() + => TestWithUseExpressionBody(""" class C { int Bar() => 0; @@ -322,8 +281,7 @@ class C return Bar(); }|} } - """; - var fixedCode = """ + """, """ class C { int Bar() => 0; @@ -332,14 +290,11 @@ int Goo() => // Comment Bar(); } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestComments3() - { - var code = """ + public Task TestComments3() + => TestWithUseExpressionBody(""" using System; class C @@ -352,8 +307,7 @@ class C throw Bar(); }|} } - """; - var fixedCode = """ + """, """ using System; class C @@ -364,14 +318,11 @@ void Goo() => // Comment throw Bar(); } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestComments4() - { - var code = """ + public Task TestComments4() + => TestWithUseExpressionBody(""" class C { void Bar() => Bar(); @@ -381,22 +332,18 @@ class C Bar(); // Comment }|} } - """; - var fixedCode = """ + """, """ class C { void Bar() => Bar(); void Goo() => Bar(); // Comment } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestComments5() - { - var code = """ + public Task TestComments5() + => TestWithUseExpressionBody(""" class C { int Bar() => 0; @@ -406,22 +353,18 @@ class C return Bar(); // Comment }|} } - """; - var fixedCode = """ + """, """ class C { int Bar() => 0; int Goo() => Bar(); // Comment } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestComments6() - { - var code = """ + public Task TestComments6() + => TestWithUseExpressionBody(""" using System; class C @@ -433,8 +376,7 @@ class C throw Bar(); // Comment }|} } - """; - var fixedCode = """ + """, """ using System; class C @@ -443,14 +385,11 @@ class C void Goo() => throw Bar(); // Comment } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17120")] - public async Task TestDirectives1() - { - var code = """ + public Task TestDirectives1() + => TestWithUseExpressionBody(""" #define DEBUG using System; @@ -463,8 +402,7 @@ class Program #endif }|} } - """; - var fixedCode = """ + """, """ #define DEBUG using System; @@ -476,14 +414,11 @@ void Method() => #endif } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17120")] - public async Task TestDirectives2() - { - var code = """ + public Task TestDirectives2() + => TestWithUseExpressionBody(""" #define DEBUG using System; @@ -498,8 +433,7 @@ class Program #endif }|} } - """; - var fixedCode = """ + """, """ #define DEBUG using System; @@ -513,9 +447,7 @@ void Method() => #endif } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69783")] public async Task TestDirectives3() @@ -541,9 +473,8 @@ void Method() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17120")] - public async Task TestDirectives4() - { - var code = """ + public Task TestDirectives4() + => TestWithUseExpressionBody(""" #define RELEASE using System; @@ -558,8 +489,7 @@ class Program #endif }|} } - """; - var fixedCode = """ + """, """ #define RELEASE using System; @@ -573,14 +503,11 @@ void Method() => #endif } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17120")] - public async Task TestDirectives5() - { - var code = """ + public Task TestDirectives5() + => TestWithUseExpressionBody(""" #define DEBUG using System; @@ -595,8 +522,7 @@ class Program #endif }|} } - """; - var fixedCode = """ + """, """ #define DEBUG using System; @@ -610,14 +536,11 @@ void Method() => #endif } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17120")] - public async Task TestDirectives6() - { - var code = """ + public Task TestDirectives6() + => TestWithUseExpressionBody(""" #define RELEASE using System; @@ -632,8 +555,7 @@ class Program #endif }|} } - """; - var fixedCode = """ + """, """ #define RELEASE using System; @@ -647,9 +569,7 @@ void Method() => #endif } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69783")] public async Task TestDirectives7() @@ -717,9 +637,8 @@ void Method() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17120")] - public async Task TestDirectives10() - { - var code = """ + public Task TestDirectives10() + => TestWithUseExpressionBody(""" #define DEBUG using System; @@ -736,8 +655,7 @@ class Program #endif }|} } - """; - var fixedCode = """ + """, """ #define DEBUG using System; @@ -753,14 +671,11 @@ void Method() => #endif } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17120")] - public async Task TestDirectives11() - { - var code = """ + public Task TestDirectives11() + => TestWithUseExpressionBody(""" #define RELEASE using System; @@ -777,8 +692,7 @@ class Program #endif }|} } - """; - var fixedCode = """ + """, """ #define RELEASE using System; @@ -794,14 +708,11 @@ void Method() => #endif } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17120")] - public async Task TestDirectives12() - { - var code = """ + public Task TestDirectives12() + => TestWithUseExpressionBody(""" #define OTHER using System; @@ -818,8 +729,7 @@ class Program #endif }|} } - """; - var fixedCode = """ + """, """ #define OTHER using System; @@ -835,21 +745,17 @@ void Method() => #endif } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20362")] - public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp6() - { - var code = """ + public Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp6() + => TestWithUseExpressionBody(""" using System; class C { {|IDE0022:void M() {|CS8026:=>|} {|CS8026:throw|} new NotImplementedException();|} } - """; - var fixedCode = """ + """, """ using System; class C { @@ -858,9 +764,7 @@ void M() throw new NotImplementedException(); } } - """; - await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp5); - } + """, LanguageVersion.CSharp5); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20352")] public async Task TestDoNotOfferToConvertToBlockIfExpressionBodyPreferredIfCSharp6() @@ -876,24 +780,20 @@ class C } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20352")] - public async Task TestOfferToConvertToExpressionIfCSharp6() - { - var code = """ + public Task TestOfferToConvertToExpressionIfCSharp6() + => TestWithUseExpressionBody(""" using System; class C { {|IDE0022:int M() { return 0; }|} } - """; - var fixedCode = """ + """, """ using System; class C { int M() => 0; } - """; - await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); - } + """, LanguageVersion.CSharp6); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20352")] public async Task TestDoNotOfferToConvertToExpressionInCSharp6IfThrowExpression() @@ -910,9 +810,8 @@ class C } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20362")] - public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp6_FixAll() - { - var code = """ + public Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp6_FixAll() + => TestWithUseExpressionBody(""" using System; class C { @@ -920,8 +819,7 @@ class C {|IDE0022:void M(int i) => {|CS8059:throw|} new NotImplementedException();|} int M(bool b) => 0; } - """; - var fixedCode = """ + """, """ using System; class C { @@ -937,14 +835,11 @@ void M(int i) int M(bool b) => 0; } - """; - await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); - } + """, LanguageVersion.CSharp6); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25202")] - public async Task TestUseBlockBodyAsync1() - { - var code = """ + public Task TestUseBlockBodyAsync1() + => TestWithUseBlockBody(""" using System.Threading.Tasks; class C @@ -953,8 +848,7 @@ class C Task Bar() { return Task.CompletedTask; } } - """; - var fixedCode = """ + """, """ using System.Threading.Tasks; class C @@ -966,14 +860,11 @@ async Task Goo() Task Bar() { return Task.CompletedTask; } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25202")] - public async Task TestUseBlockBodyAsync2() - { - var code = """ + public Task TestUseBlockBodyAsync2() + => TestWithUseBlockBody(""" using System.Threading.Tasks; class C @@ -982,8 +873,7 @@ class C Task Bar() { return Task.CompletedTask; } } - """; - var fixedCode = """ + """, """ using System.Threading.Tasks; class C @@ -995,14 +885,11 @@ async void Goo() Task Bar() { return Task.CompletedTask; } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25202")] - public async Task TestUseBlockBodyAsync3() - { - var code = """ + public Task TestUseBlockBodyAsync3() + => TestWithUseBlockBody(""" using System.Threading.Tasks; class C @@ -1011,8 +898,7 @@ class C Task Bar() { return Task.CompletedTask; } } - """; - var fixedCode = """ + """, """ using System.Threading.Tasks; class C @@ -1024,14 +910,11 @@ async void Goo() Task Bar() { return Task.CompletedTask; } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25202")] - public async Task TestUseBlockBodyAsync4() - { - var code = """ + public Task TestUseBlockBodyAsync4() + => TestWithUseBlockBody(""" using System.Threading.Tasks; class C @@ -1040,8 +923,7 @@ class C Task Bar() { return Task.CompletedTask; } } - """; - var fixedCode = """ + """, """ using System.Threading.Tasks; class C @@ -1053,14 +935,11 @@ async ValueTask Goo() Task Bar() { return Task.CompletedTask; } } - """; - await TestWithUseBlockBody(code, fixedCode, ReferenceAssemblies.NetStandard.NetStandard21); - } + """, ReferenceAssemblies.NetStandard.NetStandard21); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25202")] - public async Task TestUseBlockBodyAsync5() - { - var code = """ + public Task TestUseBlockBodyAsync5() + => TestWithUseBlockBody(""" using System.Threading.Tasks; class C @@ -1069,8 +948,7 @@ class C Task Bar() { return Task.FromResult(0); } } - """; - var fixedCode = """ + """, """ using System.Threading.Tasks; class C @@ -1082,14 +960,11 @@ async Task Goo() Task Bar() { return Task.FromResult(0); } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25202")] - public async Task TestUseBlockBodyAsync6() - { - var code = """ + public Task TestUseBlockBodyAsync6() + => TestWithUseBlockBody(""" using System.Threading.Tasks; class C @@ -1098,8 +973,7 @@ class C Task Bar() { return Task.CompletedTask; } } - """; - var fixedCode = """ + """, """ using System.Threading.Tasks; class C @@ -1111,14 +985,11 @@ Task Goo() Task Bar() { return Task.CompletedTask; } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53532")] - public async Task TestUseBlockBodyTrivia1() - { - var code = """ + public Task TestUseBlockBodyTrivia1() + => TestWithUseBlockBody(""" using System; class C { @@ -1126,8 +997,7 @@ class C // Test => Console.WriteLine();|} } - """; - var fixedCode = """ + """, """ using System; class C { @@ -1137,7 +1007,5 @@ void M() Console.WriteLine(); } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); } diff --git a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForOperatorsAnalyzerTests.cs b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForOperatorsAnalyzerTests.cs index f0ec6c3371706..ec99df8df4bbb 100644 --- a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForOperatorsAnalyzerTests.cs +++ b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForOperatorsAnalyzerTests.cs @@ -19,30 +19,25 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody; [Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public sealed class UseExpressionBodyForOperatorsAnalyzerTests { - private static async Task TestWithUseExpressionBody(string code, string fixedCode) - { - await new VerifyCS.Test + private static Task TestWithUseExpressionBody(string code, string fixedCode) + => new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedOperators, ExpressionBodyPreference.WhenPossible } } }.RunAsync(); - } - private static async Task TestWithUseBlockBody(string code, string fixedCode) - { - await new VerifyCS.Test + private static Task TestWithUseBlockBody(string code, string fixedCode) + => new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedOperators, ExpressionBodyPreference.Never } } }.RunAsync(); - } [Fact] - public async Task TestUseExpressionBody1() - { - var code = """ + public Task TestUseExpressionBody1() + => TestWithUseExpressionBody(""" class C { private static C Bar() { return new C(); } @@ -52,22 +47,18 @@ class C Bar(); }|} } - """; - var fixedCode = """ + """, """ class C { private static C Bar() { return new C(); } public static C operator +(C c1, C c2) => Bar(); } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseExpressionBody2() - { - var code = """ + public Task TestUseExpressionBody2() + => TestWithUseExpressionBody(""" class C { private static C Bar() { return new C(); } @@ -77,22 +68,18 @@ class C return Bar(); }|} } - """; - var fixedCode = """ + """, """ class C { private static C Bar() { return new C(); } public static C operator +(C c1, C c2) => Bar(); } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseExpressionBody3() - { - var code = """ + public Task TestUseExpressionBody3() + => TestWithUseExpressionBody(""" using System; class C @@ -102,22 +89,18 @@ class C throw new NotImplementedException(); }|} } - """; - var fixedCode = """ + """, """ using System; class C { public static C operator +(C c1, C c2) => throw new NotImplementedException(); } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseExpressionBody4() - { - var code = """ + public Task TestUseExpressionBody4() + => TestWithUseExpressionBody(""" using System; class C @@ -127,30 +110,25 @@ class C throw new NotImplementedException(); // comment }|} } - """; - var fixedCode = """ + """, """ using System; class C { public static C operator +(C c1, C c2) => throw new NotImplementedException(); // comment } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBody1() - { - var code = """ + public Task TestUseBlockBody1() + => TestWithUseBlockBody(""" class C { private static C Bar() { return new C(); } {|IDE0024:public static C operator +(C c1, C c2) => Bar();|} } - """; - var fixedCode = """ + """, """ class C { private static C Bar() { return new C(); } @@ -160,22 +138,18 @@ class C return Bar(); } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBody3() - { - var code = """ + public Task TestUseBlockBody3() + => TestWithUseBlockBody(""" using System; class C { {|IDE0024:public static C operator +(C c1, C c2) => throw new NotImplementedException();|} } - """; - var fixedCode = """ + """, """ using System; class C @@ -185,22 +159,18 @@ class C throw new NotImplementedException(); } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBody4() - { - var code = """ + public Task TestUseBlockBody4() + => TestWithUseBlockBody(""" using System; class C { {|IDE0024:public static C operator +(C c1, C c2) => throw new NotImplementedException();|} // comment } - """; - var fixedCode = """ + """, """ using System; class C @@ -210,7 +180,5 @@ class C throw new NotImplementedException(); // comment } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); } diff --git a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForPropertiesAnalyzerTests.cs b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForPropertiesAnalyzerTests.cs index 74b213cd90b3f..9f44f21c09cf6 100644 --- a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForPropertiesAnalyzerTests.cs +++ b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForPropertiesAnalyzerTests.cs @@ -24,12 +24,11 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody; [Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public sealed class UseExpressionBodyForPropertiesAnalyzerTests { - private static async Task TestWithUseExpressionBody( + private static Task TestWithUseExpressionBody( [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string code, [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, @@ -41,13 +40,11 @@ private static async Task TestWithUseExpressionBody( }, MarkupOptions = MarkupOptions.None, }.RunAsync(); - } - private static async Task TestWithUseBlockBody( + private static Task TestWithUseBlockBody( [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string code, [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string fixedCode) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, @@ -58,12 +55,10 @@ private static async Task TestWithUseBlockBody( }, MarkupOptions = MarkupOptions.None, }.RunAsync(); - } [Fact] - public async Task TestUseExpressionBody1() - { - var code = """ + public Task TestUseExpressionBody1() + => TestWithUseExpressionBody(""" class C { int Bar() { return 0; } @@ -76,17 +71,14 @@ class C } }|} } - """; - var fixedCode = """ + """, """ class C { int Bar() { return 0; } int Goo => Bar(); } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] public async Task TestMissingWithSetter() @@ -158,9 +150,8 @@ int Goo } [Fact] - public async Task TestUseExpressionBody3() - { - var code = """ + public Task TestUseExpressionBody3() + => TestWithUseExpressionBody(""" using System; class C @@ -173,22 +164,18 @@ class C } }|} } - """; - var fixedCode = """ + """, """ using System; class C { int Goo => throw new NotImplementedException(); } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseExpressionBody4() - { - var code = """ + public Task TestUseExpressionBody4() + => TestWithUseExpressionBody(""" using System; class C @@ -201,30 +188,25 @@ class C } }|} } - """; - var fixedCode = """ + """, """ using System; class C { int Goo => throw new NotImplementedException(); // comment } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBody1() - { - var code = """ + public Task TestUseBlockBody1() + => TestWithUseBlockBody(""" class C { int Bar() { return 0; } {|IDE0025:int Goo => Bar();|} } - """; - var fixedCode = """ + """, """ class C { int Bar() { return 0; } @@ -237,22 +219,21 @@ int Goo } } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20363")] - public async Task TestUseBlockBodyForAccessorEventWhenAccessorWantExpression1() - { - var code = """ + public Task TestUseBlockBodyForAccessorEventWhenAccessorWantExpression1() + => new VerifyCS.Test + { + TestCode = """ class C { int Bar() { return 0; } {|IDE0025:int Goo => Bar();|} } - """; - var fixedCode = """ + """, + FixedCode = """ class C { int Bar() { return 0; } @@ -262,11 +243,7 @@ int Goo get => Bar(); } } - """; - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, @@ -276,20 +253,17 @@ int Goo NumberOfFixAllIterations = 2, NumberOfIncrementalIterations = 2, }.RunAsync(); - } [Fact] - public async Task TestUseBlockBody3() - { - var code = """ + public Task TestUseBlockBody3() + => TestWithUseBlockBody(""" using System; class C { {|IDE0025:int Goo => throw new NotImplementedException();|} } - """; - var fixedCode = """ + """, """ using System; class C @@ -302,22 +276,18 @@ int Goo } } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact] - public async Task TestUseBlockBody4() - { - var code = """ + public Task TestUseBlockBody4() + => TestWithUseBlockBody(""" using System; class C { {|IDE0025:int Goo => throw new NotImplementedException();|} // comment } - """; - var fixedCode = """ + """, """ using System; class C @@ -330,14 +300,11 @@ int Goo } } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16386")] - public async Task TestUseExpressionBodyKeepTrailingTrivia() - { - var code = """ + public Task TestUseExpressionBodyKeepTrailingTrivia() + => TestWithUseExpressionBody(""" class C { private string _prop = "HELLO THERE!"; @@ -345,8 +312,7 @@ class C public string OtherThing => "Pickles"; } - """; - var fixedCode = """ + """, """ class C { private string _prop = "HELLO THERE!"; @@ -354,14 +320,11 @@ class C public string OtherThing => "Pickles"; } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19235")] - public async Task TestDirectivesInBlockBody1() - { - var code = """ + public Task TestDirectivesInBlockBody1() + => TestWithUseExpressionBody(""" class C { int Bar() { return 0; } @@ -379,8 +342,7 @@ class C } }|} } - """; - var fixedCode = """ + """, """ class C { int Bar() { return 0; } @@ -394,14 +356,11 @@ class C #endif } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19235")] - public async Task TestDirectivesInBlockBody2() - { - var code = """ + public Task TestDirectivesInBlockBody2() + => TestWithUseExpressionBody(""" class C { int Bar() { return 0; } @@ -419,8 +378,7 @@ class C } }|} } - """; - var fixedCode = """ + """, """ class C { int Bar() { return 0; } @@ -434,9 +392,7 @@ class C #endif } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19235")] public async Task TestMissingWithDirectivesInExpressionBody1() @@ -479,18 +435,15 @@ class C } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19193")] - public async Task TestMoveTriviaFromExpressionToReturnStatement() - { - // TODO: This test is unrelated to properties. It should be moved to UseExpressionBodyForMethodsAnalyzerTests. - var code = """ + public Task TestMoveTriviaFromExpressionToReturnStatement() + => TestWithUseBlockBody(""" class C { {|IDE0022:int Goo(int i) => //comment i * i;|} } - """; - var fixedCode = """ + """, """ class C { int Goo(int i) @@ -499,21 +452,17 @@ int Goo(int i) return i * i; } } - """; - await TestWithUseBlockBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20362")] - public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfHasThrowExpressionPriorToCSharp7() - { - var code = """ + public Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfHasThrowExpressionPriorToCSharp7() + => TestWithUseExpressionBody(""" using System; class C { {|IDE0025:int Goo => {|CS8059:throw|} new NotImplementedException();|} } - """; - var fixedCode = """ + """, """ using System; class C { @@ -525,22 +474,18 @@ int Goo } } } - """; - await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); - } + """, LanguageVersion.CSharp6); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20362")] - public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfHasThrowExpressionPriorToCSharp7_FixAll() - { - var code = """ + public Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfHasThrowExpressionPriorToCSharp7_FixAll() + => TestWithUseExpressionBody(""" using System; class C { {|IDE0025:int Goo => {|CS8059:throw|} new NotImplementedException();|} {|IDE0025:int Bar => {|CS8059:throw|} new NotImplementedException();|} } - """; - var fixedCode = """ + """, """ using System; class C { @@ -560,14 +505,11 @@ int Bar } } } - """; - await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); - } + """, LanguageVersion.CSharp6); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50181")] - public async Task TestUseExpressionBodyPreserveComments() - { - var code = """ + public Task TestUseExpressionBodyPreserveComments() + => TestWithUseExpressionBody(""" public class C { {|IDE0025:public long Length //N @@ -576,17 +518,14 @@ public class C get { return 1 + 2; } }|} } - """; - var fixedCode = """ + """, """ public class C { public long Length //N // N = N1 + N2 => 1 + 2; } - """; - await TestWithUseExpressionBody(code, fixedCode); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/77473")] public async Task TestMissingWithInitializer1() diff --git a/src/Analyzers/CSharp/Tests/UseExpressionBodyForLambda/UseExpressionBodyForLambdasAnalyzerTests.cs b/src/Analyzers/CSharp/Tests/UseExpressionBodyForLambda/UseExpressionBodyForLambdasAnalyzerTests.cs index 53bad0b48a336..ef6380fd84eff 100644 --- a/src/Analyzers/CSharp/Tests/UseExpressionBodyForLambda/UseExpressionBodyForLambdasAnalyzerTests.cs +++ b/src/Analyzers/CSharp/Tests/UseExpressionBodyForLambda/UseExpressionBodyForLambdasAnalyzerTests.cs @@ -30,9 +30,8 @@ private OptionsCollection UseBlockBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedLambdas, CSharpCodeStyleOptions.NeverWithSuggestionEnforcement); [Fact] - public async Task UseExpressionBodyInMethod() - { - await TestInRegularAndScriptAsync( + public Task UseExpressionBodyInMethod() + => TestInRegularAndScriptAsync( """ using System; @@ -58,12 +57,10 @@ void Goo() } } """, options: UseExpressionBody); - } [Fact] - public async Task TestMissingWhenAlreadyAndExpressionBody() - { - await TestMissingAsync( + public Task TestMissingWhenAlreadyAndExpressionBody() + => TestMissingAsync( """ using System; @@ -75,12 +72,10 @@ void Goo() } } """, new TestParameters(options: UseExpressionBody)); - } [Fact] - public async Task UseBlockBodyInMethod() - { - await TestInRegularAndScriptAsync( + public Task UseBlockBodyInMethod() + => TestInRegularAndScriptAsync( """ using System; @@ -106,12 +101,10 @@ void Goo() } } """, options: UseBlockBody); - } [Fact] - public async Task MissingWhenAlreadyHasBlockBody() - { - await TestMissingAsync( + public Task MissingWhenAlreadyHasBlockBody() + => TestMissingAsync( """ using System; @@ -123,12 +116,10 @@ void Goo() } } """, new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task UseExpressionBodyInArgument() - { - await TestInRegularAndScriptAsync( + public Task UseExpressionBodyInArgument() + => TestInRegularAndScriptAsync( """ using System; @@ -158,12 +149,10 @@ void Goo() void TargetMethod(Func targetParam) { } } """, options: UseExpressionBody); - } [Fact] - public async Task UseBlockBodyInArgument() - { - await TestInRegularAndScriptAsync( + public Task UseBlockBodyInArgument() + => TestInRegularAndScriptAsync( """ using System; @@ -193,12 +182,10 @@ void Goo() void TargetMethod(Func targetParam) { } } """, options: UseBlockBody); - } [Fact] - public async Task UseExpressionBodyFromReturnKeyword() - { - await TestMissingInRegularAndScriptAsync( + public Task UseExpressionBodyFromReturnKeyword() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -213,12 +200,10 @@ void Goo() } } """, new TestParameters(options: UseExpressionBody)); - } [Fact] - public async Task UseExpressionBodyFromLambdaOpeningBrace() - { - await TestMissingInRegularAndScriptAsync( + public Task UseExpressionBodyFromLambdaOpeningBrace() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -233,12 +218,10 @@ void Goo() } } """, new TestParameters(options: UseExpressionBody)); - } [Fact] - public async Task UseExpressionBodyFromLambdaClosingBrace() - { - await TestMissingInRegularAndScriptAsync( + public Task UseExpressionBodyFromLambdaClosingBrace() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -253,12 +236,10 @@ void Goo() } } """, new TestParameters(options: UseExpressionBody)); - } [Fact] - public async Task UseExpressionBodyThrowing() - { - await TestInRegularAndScriptAsync( + public Task UseExpressionBodyThrowing() + => TestInRegularAndScriptAsync( """ using System; @@ -284,12 +265,10 @@ void Goo() } } """, options: UseExpressionBody); - } [Fact] - public async Task UseBlockBodyThrowing() - { - await TestInRegularAndScriptAsync( + public Task UseBlockBodyThrowing() + => TestInRegularAndScriptAsync( """ using System; @@ -315,12 +294,10 @@ void Goo() } } """, options: UseBlockBody); - } [Fact] - public async Task UseExpressionBodyWithVoidReturn() - { - await TestInRegularAndScriptAsync( + public Task UseExpressionBodyWithVoidReturn() + => TestInRegularAndScriptAsync( """ using System; @@ -346,12 +323,10 @@ void Goo() } } """, options: UseExpressionBody); - } [Fact] - public async Task UseExpressionBodyWithVoidReturnThrowing() - { - await TestInRegularAndScriptAsync( + public Task UseExpressionBodyWithVoidReturnThrowing() + => TestInRegularAndScriptAsync( """ using System; @@ -377,12 +352,10 @@ void Goo() } } """, options: UseExpressionBody); - } [Fact] - public async Task UseBlockBodyWithVoidReturn() - { - await TestInRegularAndScriptAsync( + public Task UseBlockBodyWithVoidReturn() + => TestInRegularAndScriptAsync( """ using System; @@ -408,12 +381,10 @@ void Goo() } } """, options: UseBlockBody); - } [Fact] - public async Task UseBlockBodyWithVoidReturnThrowing() - { - await TestInRegularAndScriptAsync( + public Task UseBlockBodyWithVoidReturnThrowing() + => TestInRegularAndScriptAsync( """ using System; @@ -439,12 +410,10 @@ void Goo() } } """, options: UseBlockBody); - } [Fact] - public async Task UseExpressionBodyWithAsyncVoidReturn() - { - await TestInRegularAndScriptAsync( + public Task UseExpressionBodyWithAsyncVoidReturn() + => TestInRegularAndScriptAsync( """ using System; @@ -470,12 +439,10 @@ void Goo() } } """, options: UseExpressionBody); - } [Fact] - public async Task UseExpressionBodyWithAsyncVoidReturnThrowing() - { - await TestInRegularAndScriptAsync( + public Task UseExpressionBodyWithAsyncVoidReturnThrowing() + => TestInRegularAndScriptAsync( """ using System; @@ -501,12 +468,10 @@ void Goo() } } """, options: UseExpressionBody); - } [Fact] - public async Task UseBlockBodyWithAsyncVoidReturn() - { - await TestInRegularAndScriptAsync( + public Task UseBlockBodyWithAsyncVoidReturn() + => TestInRegularAndScriptAsync( """ using System; @@ -532,12 +497,10 @@ void Goo() } } """, options: UseBlockBody); - } [Fact] - public async Task UseBlockBodyWithAsyncVoidReturnThrowing() - { - await TestInRegularAndScriptAsync( + public Task UseBlockBodyWithAsyncVoidReturnThrowing() + => TestInRegularAndScriptAsync( """ using System; @@ -563,12 +526,10 @@ void Goo() } } """, options: UseBlockBody); - } [Fact] - public async Task UseExpressionBodyWithTaskReturn() - { - await TestInRegularAndScriptAsync( + public Task UseExpressionBodyWithTaskReturn() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -596,12 +557,10 @@ void Goo() } } """, options: UseExpressionBody); - } [Fact] - public async Task UseExpressionBodyWithTaskReturnThrowing() - { - await TestInRegularAndScriptAsync( + public Task UseExpressionBodyWithTaskReturnThrowing() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -629,12 +588,10 @@ void Goo() } } """, options: UseExpressionBody); - } [Fact] - public async Task UseBlockBodyWithTaskReturn() - { - await TestInRegularAndScriptAsync( + public Task UseBlockBodyWithTaskReturn() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -662,12 +619,10 @@ void Goo() } } """, options: UseBlockBody); - } [Fact] - public async Task UseBlockBodyWithTaskReturnThrowing() - { - await TestInRegularAndScriptAsync( + public Task UseBlockBodyWithTaskReturnThrowing() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -695,12 +650,10 @@ void Goo() } } """, options: UseBlockBody); - } [Fact] - public async Task UseExpressionBodyWithAsyncTaskReturn() - { - await TestInRegularAndScriptAsync( + public Task UseExpressionBodyWithAsyncTaskReturn() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -728,12 +681,10 @@ void Goo() } } """, options: UseExpressionBody); - } [Fact] - public async Task UseExpressionBodyWithAsyncTaskReturnThrowing() - { - await TestInRegularAndScriptAsync( + public Task UseExpressionBodyWithAsyncTaskReturnThrowing() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -761,12 +712,10 @@ void Goo() } } """, options: UseExpressionBody); - } [Fact] - public async Task UseBlockBodyWithAsyncTaskReturn() - { - await TestInRegularAndScriptAsync( + public Task UseBlockBodyWithAsyncTaskReturn() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -794,12 +743,10 @@ void Goo() } } """, options: UseBlockBody); - } [Fact] - public async Task UseBlockBodyWithAsyncTaskReturnThrowing() - { - await TestInRegularAndScriptAsync( + public Task UseBlockBodyWithAsyncTaskReturnThrowing() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -827,12 +774,10 @@ void Goo() } } """, options: UseBlockBody); - } [Fact] - public async Task UseExpressionBodyWithTaskTReturn() - { - await TestInRegularAndScriptAsync( + public Task UseExpressionBodyWithTaskTReturn() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -860,12 +805,10 @@ void Goo() } } """, options: UseExpressionBody); - } [Fact] - public async Task UseExpressionBodyWithTaskTReturnThrowing() - { - await TestInRegularAndScriptAsync( + public Task UseExpressionBodyWithTaskTReturnThrowing() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -893,12 +836,10 @@ void Goo() } } """, options: UseExpressionBody); - } [Fact] - public async Task UseBlockBodyWithTaskTReturn() - { - await TestInRegularAndScriptAsync( + public Task UseBlockBodyWithTaskTReturn() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -926,12 +867,10 @@ void Goo() } } """, options: UseBlockBody); - } [Fact] - public async Task UseBlockBodyWithTaskTReturnThrowing() - { - await TestInRegularAndScriptAsync( + public Task UseBlockBodyWithTaskTReturnThrowing() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -959,12 +898,10 @@ void Goo() } } """, options: UseBlockBody); - } [Fact] - public async Task UseExpressionBodyWithAsyncTaskTReturn() - { - await TestInRegularAndScriptAsync( + public Task UseExpressionBodyWithAsyncTaskTReturn() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -992,12 +929,10 @@ void Goo() } } """, options: UseExpressionBody); - } [Fact] - public async Task UseExpressionBodyWithAsyncTaskTReturnThrowing() - { - await TestInRegularAndScriptAsync( + public Task UseExpressionBodyWithAsyncTaskTReturnThrowing() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1025,12 +960,10 @@ void Goo() } } """, options: UseExpressionBody); - } [Fact] - public async Task UseBlockBodyWithAsyncTaskTReturn() - { - await TestInRegularAndScriptAsync( + public Task UseBlockBodyWithAsyncTaskTReturn() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1058,12 +991,10 @@ void Goo() } } """, options: UseBlockBody); - } [Fact] - public async Task UseBlockBodyWithAsyncTaskTReturnThrowing() - { - await TestInRegularAndScriptAsync( + public Task UseBlockBodyWithAsyncTaskTReturnThrowing() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1091,12 +1022,10 @@ void Goo() } } """, options: UseBlockBody); - } [Fact] - public async Task UseExpressionBodyWithPrecedingComment() - { - await TestInRegularAndScriptAsync( + public Task UseExpressionBodyWithPrecedingComment() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1127,12 +1056,10 @@ void Goo() } } """, options: UseExpressionBody); - } [Fact] - public async Task UseExpressionBodyWithEndingComment() - { - await TestInRegularAndScriptAsync( + public Task UseExpressionBodyWithEndingComment() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1160,12 +1087,10 @@ void Goo() } } """, options: UseExpressionBody); - } [Fact] - public async Task UseBlockBodyWithEndingComment() - { - await TestInRegularAndScriptAsync( + public Task UseBlockBodyWithEndingComment() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1193,12 +1118,10 @@ void Goo() } } """, options: UseBlockBody); - } [Fact] - public async Task UseExpressionBodyInMethod_FixAll1() - { - await TestInRegularAndScriptAsync( + public Task UseExpressionBodyInMethod_FixAll1() + => TestInRegularAndScriptAsync( """ using System; @@ -1227,12 +1150,10 @@ void Goo() } } """, options: UseExpressionBody); - } [Fact] - public async Task UseExpressionBodyInMethod_FixAll2() - { - await TestInRegularAndScriptAsync( + public Task UseExpressionBodyInMethod_FixAll2() + => TestInRegularAndScriptAsync( """ using System; @@ -1261,12 +1182,10 @@ void Goo() } } """, options: UseExpressionBody); - } [Fact] - public async Task UseBlockBodyInMethod_FixAll1() - { - await TestInRegularAndScriptAsync( + public Task UseBlockBodyInMethod_FixAll1() + => TestInRegularAndScriptAsync( """ using System; @@ -1295,12 +1214,10 @@ void Goo() } } """, options: UseBlockBody); - } [Fact] - public async Task UseBlockBodyInMethod_FixAll2() - { - await TestInRegularAndScriptAsync( + public Task UseBlockBodyInMethod_FixAll2() + => TestInRegularAndScriptAsync( """ using System; @@ -1329,12 +1246,10 @@ void Goo() } } """, options: UseBlockBody); - } [Fact] - public async Task FixAllNested1() - { - await TestInRegularAndScriptAsync( + public Task FixAllNested1() + => TestInRegularAndScriptAsync( """ using System; @@ -1363,12 +1278,10 @@ void Goo() } } """, options: UseExpressionBody); - } [Fact] - public async Task FixAllNested2() - { - await TestInRegularAndScriptAsync( + public Task FixAllNested2() + => TestInRegularAndScriptAsync( """ using System; @@ -1397,12 +1310,10 @@ void Goo() } } """, options: UseExpressionBody); - } [Fact] - public async Task FixAllNested3() - { - await TestInRegularAndScriptAsync( + public Task FixAllNested3() + => TestInRegularAndScriptAsync( """ using System; @@ -1431,12 +1342,10 @@ void Goo() } } """, options: UseBlockBody); - } [Fact] - public async Task FixAllNested4() - { - await TestInRegularAndScriptAsync( + public Task FixAllNested4() + => TestInRegularAndScriptAsync( """ using System; @@ -1465,12 +1374,10 @@ void Goo() } } """, options: UseBlockBody); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76645")] - public async Task TestMethodOverloadResolutionChange() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMethodOverloadResolutionChange() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1488,5 +1395,4 @@ void Execute(Action action) { } void Execute(Func function) { } } """, new(options: UseExpressionBody)); - } } diff --git a/src/Analyzers/CSharp/Tests/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationTests.cs b/src/Analyzers/CSharp/Tests/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationTests.cs index 4b8804b9c6f34..f21849ab4a63c 100644 --- a/src/Analyzers/CSharp/Tests/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationTests.cs +++ b/src/Analyzers/CSharp/Tests/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationTests.cs @@ -22,30 +22,26 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseImplicitObjectCreati public sealed class UseImplicitObjectCreationTests { [Fact] - public async Task TestMissingBeforeCSharp9() - { - var source = """ + public Task TestMissingBeforeCSharp9() + => new VerifyCS.Test + { + LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp8, + TestCode = """ class C { C c = new C(); } - """; - await new VerifyCS.Test - { - LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp8, - TestCode = source, + """, }.RunAsync(); - } [Fact] - public async Task TestAfterCSharp9() - { - await new VerifyCS.Test + public Task TestAfterCSharp9() + => new VerifyCS.Test { TestCode = """ class C { - C c = new [|C|](); + C c = [|new|] C(); } """, FixedCode = """ @@ -56,17 +52,15 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestWithObjectInitializer() - { - await new VerifyCS.Test + public Task TestWithObjectInitializer() + => new VerifyCS.Test { TestCode = """ class C { - C c = new [|C|]() { }; + C c = [|new|] C() { }; } """, FixedCode = """ @@ -77,17 +71,15 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestWithObjectInitializerWithoutArguments() - { - await new VerifyCS.Test + public Task TestWithObjectInitializerWithoutArguments() + => new VerifyCS.Test { TestCode = """ class C { - C c = new [|C|] { }; + C c = [|new|] C { }; } """, FixedCode = """ @@ -98,17 +90,15 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestWithTriviaAfterNew() - { - await new VerifyCS.Test + public Task TestWithTriviaAfterNew() + => new VerifyCS.Test { TestCode = """ class C { - C c = new /*x*/ [|C|](); + C c = [|new|] /*x*/ C(); } """, FixedCode = """ @@ -119,12 +109,10 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestNotWithDifferentTypes() - { - await new VerifyCS.Test + public Task TestNotWithDifferentTypes() + => new VerifyCS.Test { TestCode = """ class C @@ -134,12 +122,10 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestNotWithErrorTypes() - { - await new VerifyCS.Test + public Task TestNotWithErrorTypes() + => new VerifyCS.Test { TestState = { Sources = @@ -161,12 +147,10 @@ class C }, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestNotWithDynamic() - { - await new VerifyCS.Test + public Task TestNotWithDynamic() + => new VerifyCS.Test { TestCode = """ class C @@ -176,12 +160,10 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestNotWithArrayTypes() - { - await new VerifyCS.Test + public Task TestNotWithArrayTypes() + => new VerifyCS.Test { TestCode = """ class C @@ -191,17 +173,15 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestWithTypeParameter() - { - await new VerifyCS.Test + public Task TestWithTypeParameter() + => new VerifyCS.Test { TestCode = """ class C where T : new() { - T t = new [|T|](); + T t = [|new|] T(); } """, FixedCode = """ @@ -212,19 +192,17 @@ public async Task TestWithTypeParameter() """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestWithLocalWhenUserDoesNotPreferVar() - { - await new VerifyCS.Test + public Task TestWithLocalWhenUserDoesNotPreferVar() + => new VerifyCS.Test { TestCode = """ class C { void M() { - C c = new [|C|](); + C c = [|new|] C(); } } """, @@ -243,12 +221,10 @@ void M() { CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOption2.FalseWithSuggestionEnforcement }, } }.RunAsync(); - } [Fact] - public async Task TestNotWithLocalWhenUserDoesPreferVar() - { - await new VerifyCS.Test + public Task TestNotWithLocalWhenUserDoesPreferVar() + => new VerifyCS.Test { TestCode = """ class C @@ -265,19 +241,17 @@ void M() { CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOption2.TrueWithSuggestionEnforcement }, } }.RunAsync(); - } [Fact] - public async Task TestWithForVariable() - { - await new VerifyCS.Test + public Task TestWithForVariable() + => new VerifyCS.Test { TestCode = """ class C { void M() { - for (C c = new [|C|]();;) + for (C c = [|new|] C();;) { } } @@ -296,19 +270,17 @@ void M() """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestWithLocalFunctionExpressionBody() - { - await new VerifyCS.Test + public Task TestWithLocalFunctionExpressionBody() + => new VerifyCS.Test { TestCode = """ class C { void M() { - C Func() => new [|C|](); + C Func() => [|new|] C(); } } """, @@ -323,17 +295,15 @@ void M() """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestWithMethodExpressionBody() - { - await new VerifyCS.Test + public Task TestWithMethodExpressionBody() + => new VerifyCS.Test { TestCode = """ class C { - C Func() => new [|C|](); + C Func() => [|new|] C(); } """, FixedCode = """ @@ -344,17 +314,15 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestWithConversionExpressionBody() - { - await new VerifyCS.Test + public Task TestWithConversionExpressionBody() + => new VerifyCS.Test { TestCode = """ class C { - public static implicit operator C(int i) => new [|C|](); + public static implicit operator C(int i) => [|new|] C(); } """, FixedCode = """ @@ -365,17 +333,15 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestWithOperatorExpressionBody() - { - await new VerifyCS.Test + public Task TestWithOperatorExpressionBody() + => new VerifyCS.Test { TestCode = """ class C { - public static C operator +(C c1, C c2) => new [|C|](); + public static C operator +(C c1, C c2) => [|new|] C(); } """, FixedCode = """ @@ -386,17 +352,15 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestWithPropertyExpressionBody() - { - await new VerifyCS.Test + public Task TestWithPropertyExpressionBody() + => new VerifyCS.Test { TestCode = """ class C { - C P => new [|C|](); + C P => [|new|] C(); } """, FixedCode = """ @@ -407,17 +371,15 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestWithPropertyAccessorExpressionBody() - { - await new VerifyCS.Test + public Task TestWithPropertyAccessorExpressionBody() + => new VerifyCS.Test { TestCode = """ class C { - C P { get => new [|C|](); } + C P { get => [|new|] C(); } } """, FixedCode = """ @@ -428,12 +390,10 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestNotWithPropertySetAccessorExpressionBody() - { - await new VerifyCS.Test + public Task TestNotWithPropertySetAccessorExpressionBody() + => new VerifyCS.Test { TestCode = """ class C @@ -443,17 +403,15 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestWithIndexerExpressionBody() - { - await new VerifyCS.Test + public Task TestWithIndexerExpressionBody() + => new VerifyCS.Test { TestCode = """ class C { - C this[int i] => new [|C|](); + C this[int i] => [|new|] C(); } """, FixedCode = """ @@ -464,17 +422,15 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestWithIndexerAccessorExpressionBody() - { - await new VerifyCS.Test + public Task TestWithIndexerAccessorExpressionBody() + => new VerifyCS.Test { TestCode = """ class C { - C this[int i] { get => new [|C|](); } + C this[int i] { get => [|new|] C(); } } """, FixedCode = """ @@ -485,12 +441,10 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestNotWithMethodBlockBody() - { - await new VerifyCS.Test + public Task TestNotWithMethodBlockBody() + => new VerifyCS.Test { TestCode = """ class C @@ -500,12 +454,10 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestNotInNonApparentCode1() - { - await new VerifyCS.Test + public Task TestNotInNonApparentCode1() + => new VerifyCS.Test { TestCode = """ class C @@ -516,12 +468,10 @@ void Bar(C c) { } """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestNotInNonApparentCode2() - { - await new VerifyCS.Test + public Task TestNotInNonApparentCode2() + => new VerifyCS.Test { TestCode = """ class C @@ -535,18 +485,16 @@ void X() """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestQualifiedUnqualified1() - { - await new VerifyCS.Test + public Task TestQualifiedUnqualified1() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; class C { - List list = new [|System.Collections.Generic.List|](); + List list = [|new|] System.Collections.Generic.List(); } """, FixedCode = """ @@ -558,18 +506,16 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestQualifiedUnqualified2() - { - await new VerifyCS.Test + public Task TestQualifiedUnqualified2() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; class C { - System.Collections.Generic.List list = new [|List|](); + System.Collections.Generic.List list = [|new|] List(); } """, FixedCode = """ @@ -581,19 +527,17 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestAlias() - { - await new VerifyCS.Test + public Task TestAlias() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; using X = System.Collections.Generic.List; class C { - System.Collections.Generic.List list = new [|X|](); + System.Collections.Generic.List list = [|new|] X(); } """, FixedCode = """ @@ -606,12 +550,10 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestFixAll1() - { - await new VerifyCS.Test + public Task TestFixAll1() + => new VerifyCS.Test { TestCode = """ using System; @@ -620,9 +562,9 @@ class C public C() { } public C(Action action) { } - C c1 = new [|C|](() => + C c1 = [|new|] C(() => { - C c2 = new [|C|](); + C c2 = [|new|] C(); }); } """, @@ -641,18 +583,16 @@ public C(Action action) { } """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49291")] - public async Task TestListOfTuplesWithLabels() - { - await new VerifyCS.Test + public Task TestListOfTuplesWithLabels() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; class C { - List<(int SomeName, int SomeOtherName, int YetAnotherName)> list = new [|List<(int SomeName, int SomeOtherName, int YetAnotherName)>|](); + List<(int SomeName, int SomeOtherName, int YetAnotherName)> list = [|new|] List<(int SomeName, int SomeOtherName, int YetAnotherName)>(); } """, FixedCode = """ @@ -664,18 +604,16 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49291")] - public async Task TestListOfTuplesWithoutLabels() - { - await new VerifyCS.Test + public Task TestListOfTuplesWithoutLabels() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; class C { - List<(int SomeName, int SomeOtherName, int YetAnotherName)> list = new [|List<(int, int, int)>|](); + List<(int SomeName, int SomeOtherName, int YetAnotherName)> list = [|new|] List<(int, int, int)>(); } """, FixedCode = """ @@ -687,12 +625,10 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49291")] - public async Task TestListOfTuplesWithoutLabelsAsLocal() - { - await new VerifyCS.Test + public Task TestListOfTuplesWithoutLabelsAsLocal() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -700,7 +636,7 @@ class C { void M() { - List<(int SomeName, int SomeOtherName, int YetAnotherName)> list = new [|List<(int, int, int)>|](); + List<(int SomeName, int SomeOtherName, int YetAnotherName)> list = [|new|] List<(int, int, int)>(); } } """, @@ -716,34 +652,29 @@ void M() """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57777")] - public async Task TestMissingOnNullableStruct() - { - var source = """ + public Task TestMissingOnNullableStruct() + => new VerifyCS.Test + { + LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, + TestCode = """ class C { int? i = new int?(); } - """; - await new VerifyCS.Test - { - LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, - TestCode = source, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57777")] - public async Task TestOnNullableReferenceType() - { - await new VerifyCS.Test + public Task TestOnNullableReferenceType() + => new VerifyCS.Test { TestCode = """ #nullable enable class C { - C? c = new [|C|](); + C? c = [|new|] C(); } """, FixedCode = """ @@ -755,19 +686,17 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57789")] - public async Task TestOnSingleDimensionalCollectionConstruction1() - { - await new VerifyCS.Test + public Task TestOnSingleDimensionalCollectionConstruction1() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; class C { - IList list = new List { new [|C|]() }; + IList list = new List { [|new|] C() }; } """, FixedCode = """ @@ -780,19 +709,17 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57789")] - public async Task TestOnSingleDimensionalCollectionConstruction2() - { - await new VerifyCS.Test + public Task TestOnSingleDimensionalCollectionConstruction2() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; class C { - IList list = new List() { new [|C|]() }; + IList list = new List() { [|new|] C() }; } """, FixedCode = """ @@ -805,19 +732,17 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57789")] - public async Task TestOnSingleDimensionalCollectionConstruction3() - { - await new VerifyCS.Test + public Task TestOnSingleDimensionalCollectionConstruction3() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; class C { - List list = new [|List|]() { new [|C|]() }; + List list = [|new|] List() { [|new|] C() }; } """, FixedCode = """ @@ -830,12 +755,10 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57789")] - public async Task TestNotOnSingleDimensionalImplicitCollectionConstruction2() - { - await new VerifyCS.Test + public Task TestNotOnSingleDimensionalImplicitCollectionConstruction2() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -847,12 +770,10 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57789")] - public async Task TestNotOnMultiDimensionalImplicitCollectionConstruction2() - { - await new VerifyCS.Test + public Task TestNotOnMultiDimensionalImplicitCollectionConstruction2() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -864,19 +785,17 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57789")] - public async Task TestOnSingleDimensionalArrayConstruction1() - { - await new VerifyCS.Test + public Task TestOnSingleDimensionalArrayConstruction1() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; class C { - C[] list = new C[] { new [|C|]() }; + C[] list = new C[] { [|new|] C() }; } """, FixedCode = """ @@ -889,19 +808,17 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57789")] - public async Task TestOnSingleDimensionalArrayConstruction2() - { - await new VerifyCS.Test + public Task TestOnSingleDimensionalArrayConstruction2() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; class C { - C[] list = { new [|C|]() }; + C[] list = { [|new|] C() }; } """, FixedCode = """ @@ -914,12 +831,10 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57789")] - public async Task TestNotOnSingleDimensionalImplicitArrayConstruction2() - { - await new VerifyCS.Test + public Task TestNotOnSingleDimensionalImplicitArrayConstruction2() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -931,12 +846,10 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57789")] - public async Task TestNotOnTwoDimensionalArrayConstruction1() - { - await new VerifyCS.Test + public Task TestNotOnTwoDimensionalArrayConstruction1() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -948,19 +861,17 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57789")] - public async Task TestOnInnerJaggedArray1() - { - await new VerifyCS.Test + public Task TestOnInnerJaggedArray1() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; class C { - C[][] list = new C[][] { new C[] { new [|C|]() } }; + C[][] list = new C[][] { new C[] { [|new|] C() } }; } """, FixedCode = """ @@ -973,5 +884,4 @@ class C """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests.cs b/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests.cs index 42dea9a5b0822..49ac416acaa23 100644 --- a/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests.cs +++ b/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests.cs @@ -74,9 +74,8 @@ private OptionsCollection ExplicitTypeSilentEnforcement() #region Error Cases [Fact] - public async Task NotOnFieldDeclaration() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnFieldDeclaration() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -85,12 +84,10 @@ class Program [|var|] _myfield = 5; } """, new TestParameters(options: ExplicitTypeEverywhere())); - } [Fact] - public async Task NotOnFieldLikeEvents() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnFieldLikeEvents() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -99,7 +96,6 @@ class Program public event [|var|] _myevent; } """, new TestParameters(options: ExplicitTypeEverywhere())); - } [Fact] public async Task OnAnonymousMethodExpression() @@ -170,9 +166,8 @@ void Method() } [Fact] - public async Task NotOnDeclarationWithMultipleDeclarators() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnDeclarationWithMultipleDeclarators() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -184,12 +179,10 @@ void Method() } } """, new TestParameters(options: ExplicitTypeEverywhere())); - } [Fact] - public async Task NotOnDeclarationWithoutInitializer() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnDeclarationWithoutInitializer() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -201,12 +194,10 @@ void Method() } } """, new TestParameters(options: ExplicitTypeEverywhere())); - } [Fact] - public async Task NotDuringConflicts() - { - await TestMissingInRegularAndScriptAsync( + public Task NotDuringConflicts() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -222,12 +213,10 @@ class var } } """, new TestParameters(options: ExplicitTypeEverywhere())); - } [Fact] - public async Task NotIfAlreadyExplicitlyTyped() - { - await TestMissingInRegularAndScriptAsync( + public Task NotIfAlreadyExplicitlyTyped() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -239,12 +228,10 @@ void Method() } } """, new TestParameters(options: ExplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27221")] - public async Task NotIfRefTypeAlreadyExplicitlyTyped() - { - await TestMissingInRegularAndScriptAsync( + public Task NotIfRefTypeAlreadyExplicitlyTyped() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -257,12 +244,10 @@ void Method() ref Program Ref() => throw null; } """, new TestParameters(options: ExplicitTypeEverywhere())); - } [Fact] - public async Task NotOnRHS() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnRHS() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -278,12 +263,10 @@ class var { } """); - } [Fact] - public async Task NotOnErrorSymbol() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnErrorSymbol() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -295,12 +278,10 @@ void Method() } } """, new TestParameters(options: ExplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29718")] - public async Task NotOnErrorConvertedType_ForEachVariableStatement() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnErrorConvertedType_ForEachVariableStatement() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -317,12 +298,10 @@ void M() } } """, new TestParameters(options: ExplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29718")] - public async Task NotOnErrorConvertedType_AssignmentExpressionStatement() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnErrorConvertedType_AssignmentExpressionStatement() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -337,7 +316,6 @@ void M(C c) } } """, new TestParameters(options: ExplicitTypeEverywhere())); - } #endregion @@ -353,7 +331,8 @@ void Method() } } """; - var after = """ + // The type is apparent and not intrinsic + await TestInRegularAndScriptAsync(before, """ class Program { void Method() @@ -361,9 +340,7 @@ void Method() Program[] x = new Program[0]; } } - """; - // The type is apparent and not intrinsic - await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); + """, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeExceptWhereApparent())); } @@ -1186,9 +1163,8 @@ void Method(out int x) } [Fact] - public async Task NotOnDynamic() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnDynamic() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1200,12 +1176,10 @@ void Method() } } """, new TestParameters(options: ExplicitTypeEverywhere())); - } [Fact] - public async Task NotOnForEachVarWithAnonymousType() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnForEachVarWithAnonymousType() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Linq; @@ -1223,12 +1197,10 @@ void Method() } } """, new TestParameters(options: ExplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23752")] - public async Task OnDeconstructionVarParens() - { - await TestInRegularAndScriptAsync( + public Task OnDeconstructionVarParens() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -1250,12 +1222,10 @@ void M() void Deconstruct(out int i, out string s) { i = 1; s = "hello"; } } """, options: ExplicitTypeEverywhere()); - } [Fact] - public async Task OnDeconstructionVar() - { - await TestInRegularAndScriptAsync( + public Task OnDeconstructionVar() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -1277,12 +1247,10 @@ void M() void Deconstruct(out int i, out string s) { i = 1; s = "hello"; } } """, options: ExplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23752")] - public async Task OnNestedDeconstructionVar() - { - await TestInRegularAndScriptAsync( + public Task OnNestedDeconstructionVar() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -1304,12 +1272,10 @@ void M() void Deconstruct(out int i, out Program s) { i = 1; s = null; } } """, options: ExplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23752")] - public async Task OnBadlyFormattedNestedDeconstructionVar() - { - await TestInRegularAndScriptAsync( + public Task OnBadlyFormattedNestedDeconstructionVar() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -1331,12 +1297,10 @@ void M() void Deconstruct(out int i, out Program s) { i = 1; s = null; } } """, options: ExplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23752")] - public async Task OnForeachNestedDeconstructionVar() - { - await TestInRegularAndScriptAsync( + public Task OnForeachNestedDeconstructionVar() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -1358,12 +1322,10 @@ void M() void Deconstruct(out int i, out Program s) { i = 1; s = null; } } """, options: ExplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23752")] - public async Task OnNestedDeconstructionVarWithTrivia() - { - await TestInRegularAndScriptAsync( + public Task OnNestedDeconstructionVarWithTrivia() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -1385,12 +1347,10 @@ void M() void Deconstruct(out int i, out Program s) { i = 1; s = null; } } """, options: ExplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23752")] - public async Task OnDeconstructionVarWithDiscard() - { - await TestInRegularAndScriptAsync( + public Task OnDeconstructionVarWithDiscard() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -1412,12 +1372,10 @@ void M() void Deconstruct(out int i, out string s) { i = 1; s = "hello"; } } """, options: ExplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23752")] - public async Task OnDeconstructionVarWithErrorType() - { - await TestInRegularAndScriptAsync( + public Task OnDeconstructionVarWithErrorType() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -1439,12 +1397,10 @@ void M() void Deconstruct(out int i, out Error s) { i = 1; s = null; } } """, options: ExplicitTypeEverywhere()); - } [Fact] - public async Task OnForEachVarWithExplicitType() - { - await TestInRegularAndScriptAsync( + public Task OnForEachVarWithExplicitType() + => TestInRegularAndScriptAsync( """ using System; using System.Linq; @@ -1479,12 +1435,10 @@ void Method() } } """, options: ExplicitTypeEverywhere()); - } [Fact] - public async Task NotOnAnonymousType() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnAnonymousType() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1496,12 +1450,10 @@ void Method() } } """, new TestParameters(options: ExplicitTypeEverywhere())); - } [Fact] - public async Task NotOnArrayOfAnonymousType() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnArrayOfAnonymousType() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1513,12 +1465,10 @@ void Method() } } """, new TestParameters(options: ExplicitTypeEverywhere())); - } [Fact] - public async Task NotOnEnumerableOfAnonymousTypeFromAQueryExpression() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnEnumerableOfAnonymousTypeFromAQueryExpression() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -1540,12 +1490,10 @@ class Product public int Price { get; set; } } """); - } [Fact] - public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeString() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeOnLocalWithIntrinsicTypeString() + => TestInRegularAndScriptAsync( """ using System; @@ -1568,12 +1516,10 @@ static void M() } } """, options: ExplicitTypeEverywhere()); - } [Fact] - public async Task SuggestExplicitTypeOnIntrinsicType() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeOnIntrinsicType() + => TestInRegularAndScriptAsync( """ using System; @@ -1596,12 +1542,10 @@ static void M() } } """, options: ExplicitTypeEverywhere()); - } [Fact] - public async Task SuggestExplicitTypeOnFrameworkType() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeOnFrameworkType() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1624,12 +1568,10 @@ static void M() } } """, options: ExplicitTypeEverywhere()); - } [Fact] - public async Task SuggestExplicitTypeOnUserDefinedType() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeOnUserDefinedType() + => TestInRegularAndScriptAsync( """ using System; @@ -1652,12 +1594,10 @@ void M() } } """, options: ExplicitTypeEverywhere()); - } [Fact] - public async Task SuggestExplicitTypeOnGenericType() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeOnGenericType() + => TestInRegularAndScriptAsync( """ using System; @@ -1680,12 +1620,10 @@ static void M() } } """, options: ExplicitTypeEverywhere()); - } [Fact] - public async Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator() + => TestInRegularAndScriptAsync( """ using System; @@ -1708,12 +1646,10 @@ static void M() } } """, options: ExplicitTypeEverywhere()); - } [Fact] - public async Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator2() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator2() + => TestInRegularAndScriptAsync( """ using System; @@ -1736,12 +1672,10 @@ static void M() } } """, options: ExplicitTypeEverywhere()); - } [Fact] - public async Task SuggestExplicitTypeOnSingleDimensionalJaggedArrayType() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeOnSingleDimensionalJaggedArrayType() + => TestInRegularAndScriptAsync( """ using System; @@ -1770,12 +1704,10 @@ static void M() } } """, options: ExplicitTypeEverywhere()); - } [Fact] - public async Task SuggestExplicitTypeOnDeclarationWithObjectInitializer() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeOnDeclarationWithObjectInitializer() + => TestInRegularAndScriptAsync( """ using System; @@ -1808,12 +1740,10 @@ private class Customer } } """, options: ExplicitTypeEverywhere()); - } [Fact] - public async Task SuggestExplicitTypeOnDeclarationWithCollectionInitializer() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeOnDeclarationWithCollectionInitializer() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -1838,12 +1768,10 @@ static void M() } } """, options: ExplicitTypeEverywhere()); - } [Fact] - public async Task SuggestExplicitTypeOnDeclarationWithCollectionAndObjectInitializers() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeOnDeclarationWithCollectionAndObjectInitializers() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -1884,12 +1812,10 @@ private class Customer } } """, options: ExplicitTypeEverywhere()); - } [Fact] - public async Task SuggestExplicitTypeOnForStatement() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeOnForStatement() + => TestInRegularAndScriptAsync( """ using System; @@ -1916,12 +1842,10 @@ static void M() } } """, options: ExplicitTypeEverywhere()); - } [Fact] - public async Task SuggestExplicitTypeOnForeachStatement() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeOnForeachStatement() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -1952,12 +1876,10 @@ static void M() } } """, options: ExplicitTypeEverywhere()); - } [Fact] - public async Task SuggestExplicitTypeOnQueryExpression() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeOnQueryExpression() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -2002,12 +1924,10 @@ private class Customer } } """, options: ExplicitTypeEverywhere()); - } [Fact] - public async Task SuggestExplicitTypeInUsingStatement() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeInUsingStatement() + => TestInRegularAndScriptAsync( """ using System; @@ -2050,12 +1970,10 @@ public void Dispose() } } """, options: ExplicitTypeEverywhere()); - } [Fact] - public async Task SuggestExplicitTypeOnInterpolatedString() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeOnInterpolatedString() + => TestInRegularAndScriptAsync( """ using System; @@ -2078,12 +1996,10 @@ void Method() } } """, options: ExplicitTypeEverywhere()); - } [Fact] - public async Task SuggestExplicitTypeOnExplicitConversion() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeOnExplicitConversion() + => TestInRegularAndScriptAsync( """ using System; @@ -2108,12 +2024,10 @@ static void M() } } """, options: ExplicitTypeEverywhere()); - } [Fact] - public async Task SuggestExplicitTypeOnConditionalAccessExpression() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeOnConditionalAccessExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -2148,12 +2062,10 @@ C Test() } } """, options: ExplicitTypeEverywhere()); - } [Fact] - public async Task SuggestExplicitTypeInCheckedExpression() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeInCheckedExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -2178,12 +2090,10 @@ static void M() } } """, options: ExplicitTypeEverywhere()); - } [Fact] - public async Task SuggestExplicitTypeInAwaitExpression() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeInAwaitExpression() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -2218,12 +2128,10 @@ private async Task ReadTextAsync(string filePath) } } """, options: ExplicitTypeEverywhere()); - } [Fact] - public async Task SuggestExplicitTypeInBuiltInNumericType() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeInBuiltInNumericType() + => TestInRegularAndScriptAsync( """ using System; @@ -2246,12 +2154,10 @@ public void ProcessRead() } } """, options: ExplicitTypeForBuiltInTypesOnly()); - } [Fact] - public async Task SuggestExplicitTypeInBuiltInCharType() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeInBuiltInCharType() + => TestInRegularAndScriptAsync( """ using System; @@ -2278,14 +2184,10 @@ public void ProcessRead() public char GetChar() => 'c'; } """, options: ExplicitTypeForBuiltInTypesOnly()); - } [Fact] - public async Task SuggestExplicitTypeInBuiltInType_string() - { - // though string isn't an intrinsic type per the compiler - // we in the IDE treat it as an intrinsic type for this feature. - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeInBuiltInType_string() + => TestInRegularAndScriptAsync( """ using System; @@ -2308,14 +2210,10 @@ public void ProcessRead() } } """, options: ExplicitTypeForBuiltInTypesOnly()); - } [Fact] - public async Task SuggestExplicitTypeInBuiltInType_object() - { - // object isn't an intrinsic type per the compiler - // we in the IDE treat it as an intrinsic type for this feature. - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeInBuiltInType_object() + => TestInRegularAndScriptAsync( """ using System; @@ -2340,13 +2238,10 @@ public void ProcessRead() } } """, options: ExplicitTypeForBuiltInTypesOnly()); - } [Fact] - public async Task SuggestExplicitTypeNotificationLevelSilent() - { - var source = - """ + public Task SuggestExplicitTypeNotificationLevelSilent() + => TestDiagnosticInfoAsync(""" using System; class C { @@ -2355,18 +2250,14 @@ static void M() [|var|] n1 = new C(); } } - """; - await TestDiagnosticInfoAsync(source, + """, options: ExplicitTypeSilentEnforcement(), diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Hidden); - } [Fact] - public async Task SuggestExplicitTypeNotificationLevelInfo() - { - var source = - """ + public Task SuggestExplicitTypeNotificationLevelInfo() + => TestDiagnosticInfoAsync(""" using System; class C { @@ -2375,18 +2266,14 @@ static void M() [|var|] s = 5; } } - """; - await TestDiagnosticInfoAsync(source, + """, options: ExplicitTypeEnforcements(), diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Info); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23907")] - public async Task SuggestExplicitTypeNotificationLevelWarning() - { - var source = - """ + public Task SuggestExplicitTypeNotificationLevelWarning() + => TestDiagnosticInfoAsync(""" using System; class C { @@ -2395,18 +2282,14 @@ static void M() [|var|] n1 = new[] { new C() }; // type not apparent and not intrinsic } } - """; - await TestDiagnosticInfoAsync(source, + """, options: ExplicitTypeEnforcements(), diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Warning); - } [Fact] - public async Task SuggestExplicitTypeNotificationLevelError() - { - var source = - """ + public Task SuggestExplicitTypeNotificationLevelError() + => TestDiagnosticInfoAsync(""" using System; class C { @@ -2415,17 +2298,14 @@ static void M() [|var|] n1 = new C(); } } - """; - await TestDiagnosticInfoAsync(source, + """, options: ExplicitTypeEnforcements(), diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Error); - } [Fact] - public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTuple() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTuple() + => TestInRegularAndScriptAsync( """ class C { @@ -2444,13 +2324,11 @@ static void M() } } """, -options: ExplicitTypeEverywhere()); - } + options: ExplicitTypeEverywhere()); [Fact] - public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithNames() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithNames() + => TestInRegularAndScriptAsync( """ class C { @@ -2469,13 +2347,11 @@ static void M() } } """, -options: ExplicitTypeEverywhere()); - } + options: ExplicitTypeEverywhere()); [Fact] - public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithOneName() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithOneName() + => TestInRegularAndScriptAsync( """ class C { @@ -2494,13 +2370,11 @@ static void M() } } """, -options: ExplicitTypeEverywhere()); - } + options: ExplicitTypeEverywhere()); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20437")] - public async Task SuggestExplicitTypeOnDeclarationExpressionSyntax() - { - await TestInRegularAndScriptAsync( + public Task SuggestExplicitTypeOnDeclarationExpressionSyntax() + => TestInRegularAndScriptAsync( """ using System; @@ -2523,13 +2397,11 @@ static void M() } } """, -options: ExplicitTypeEverywhere()); - } + options: ExplicitTypeEverywhere()); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20244")] - public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames1() - { - await TestMissingInRegularAndScriptAsync( + public Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2541,12 +2413,10 @@ void Method() } } """, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20244")] - public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames2() - { - await TestMissingInRegularAndScriptAsync( + public Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames2() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2560,12 +2430,10 @@ void Main() } } """, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20244")] - public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames3() - { - await TestMissingInRegularAndScriptAsync( + public Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames3() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2577,12 +2445,10 @@ void Main() } } """, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20244")] - public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames4() - { - await TestMissingInRegularAndScriptAsync( + public Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames4() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2598,12 +2464,10 @@ void Main() } } """, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20244")] - public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames5() - { - await TestMissingInRegularAndScriptAsync( + public Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames5() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -2616,12 +2480,10 @@ void Main() } } """, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20244")] - public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames6() - { - await TestMissingInRegularAndScriptAsync( + public Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames6() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2634,12 +2496,10 @@ void Main() } } """, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20244")] - public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames7() - { - await TestMissingInRegularAndScriptAsync( + public Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames7() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2652,12 +2512,10 @@ void Main() } } """, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20244")] - public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames8() - { - await TestMissingInRegularAndScriptAsync( + public Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames8() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -2675,12 +2533,10 @@ private async Task ReadTextAsync(string filePath) } } """, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20244")] - public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames9() - { - await TestMissingInRegularAndScriptAsync( + public Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames9() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2693,12 +2549,10 @@ void Main() } } """, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20244")] - public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames10() - { - await TestMissingInRegularAndScriptAsync( + public Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames10() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2712,12 +2566,10 @@ void Main() } } """, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20244")] - public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames11() - { - await TestMissingInRegularAndScriptAsync( + public Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames11() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -2730,12 +2582,10 @@ void Main() } } """, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26923")] - public async Task NoSuggestionOnForeachCollectionExpression() - { - await TestMissingInRegularAndScriptAsync( + public Task NoSuggestionOnForeachCollectionExpression() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -2751,13 +2601,10 @@ void Method(List var) } } """, new TestParameters(options: ExplicitTypeEverywhere())); - } [Fact] - public async Task NotOnConstVar() - { - // This error case is handled by a separate code fix (UseExplicitTypeForConst). - await TestMissingInRegularAndScriptAsync( + public Task NotOnConstVar() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2767,7 +2614,6 @@ void M() } } """, new TestParameters(options: ExplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23907")] public async Task WithNormalFuncSynthesizedLambdaType() @@ -2815,9 +2661,8 @@ void Method() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58404")] - public async Task TestLambdaNaturalType() - { - await TestInRegularAndScriptAsync( + public Task TestLambdaNaturalType() + => TestInRegularAndScriptAsync( """ using System; @@ -2840,5 +2685,4 @@ static void M() } } """, options: ExplicitTypeEverywhere()); - } } diff --git a/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests_FixAllTests.cs b/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests_FixAllTests.cs index 13720b33529d7..a76c5826b86be 100644 --- a/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests_FixAllTests.cs +++ b/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests_FixAllTests.cs @@ -17,9 +17,8 @@ public partial class UseExplicitTypeTests [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInDocumentScope_PreferExplicitTypeEverywhere() - { - var input = """ + public Task TestFixAllInDocumentScope_PreferExplicitTypeEverywhere() + => TestInRegularAndScriptAsync(""" @@ -71,9 +70,7 @@ static int F(int x, int y) - """; - - var expected = """ + """, """ @@ -125,17 +122,13 @@ static int F(int x, int y) - """; - - await TestInRegularAndScriptAsync(input, expected, options: ExplicitTypeEverywhere()); - } + """, options: ExplicitTypeEverywhere()); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInProject_PreferExplicitTypeEverywhere() - { - var input = """ + public Task TestFixAllInProject_PreferExplicitTypeEverywhere() + => TestInRegularAndScriptAsync(""" @@ -187,9 +180,7 @@ static int F(int x, int y) - """; - - var expected = """ + """, """ @@ -241,17 +232,13 @@ static int F(int x, int y) - """; - - await TestInRegularAndScriptAsync(input, expected, options: ExplicitTypeEverywhere()); - } + """, options: ExplicitTypeEverywhere()); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInSolution_PreferExplicitTypeEverywhere() - { - var input = """ + public Task TestFixAllInSolution_PreferExplicitTypeEverywhere() + => TestInRegularAndScriptAsync(""" @@ -303,9 +290,7 @@ static int F(int x, int y) - """; - - var expected = """ + """, """ @@ -357,17 +342,13 @@ static int F(int x, int y) - """; - - await TestInRegularAndScriptAsync(input, expected, options: ExplicitTypeEverywhere()); - } + """, options: ExplicitTypeEverywhere()); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInDocumentScope_PreferExplicitTypeExceptWhereApparent() - { - var input = """ + public Task TestFixAllInDocumentScope_PreferExplicitTypeExceptWhereApparent() + => TestInRegularAndScriptAsync(""" @@ -387,9 +368,7 @@ static int F(int x, int y) - """; - - var expected = """ + """, """ @@ -409,10 +388,7 @@ static int F(int x, int y) - """; - - await TestInRegularAndScriptAsync(input, expected, options: ExplicitTypeExceptWhereApparent()); - } + """, options: ExplicitTypeExceptWhereApparent()); #endregion } diff --git a/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseImplicitTypeTests.cs b/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseImplicitTypeTests.cs index a7618888129c4..75db660d4d9d8 100644 --- a/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseImplicitTypeTests.cs +++ b/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseImplicitTypeTests.cs @@ -81,9 +81,8 @@ private OptionsCollection ImplicitTypeSilentEnforcement() }; [Fact] - public async Task NotOnFieldDeclaration() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnFieldDeclaration() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -92,12 +91,10 @@ class Program [|int|] _myfield = 5; } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact] - public async Task NotOnFieldLikeEvents() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnFieldLikeEvents() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -106,12 +103,10 @@ class Program public event [|D|] _myevent; } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact] - public async Task NotOnConstants() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnConstants() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -123,12 +118,10 @@ void Method() } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact] - public async Task NotOnNullLiteral() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnNullLiteral() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -140,12 +133,10 @@ void Method() } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27221")] - public async Task NotOnRefVar() - { - await TestMissingInRegularAndScriptAsync(""" + public Task NotOnRefVar() + => TestMissingInRegularAndScriptAsync(""" class Program { void Method() @@ -155,12 +146,10 @@ void Method() ref int Method2() => throw null; } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact] - public async Task NotOnDynamic() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnDynamic() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -172,12 +161,10 @@ void Method() } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact] - public async Task NotOnAnonymousMethodExpression() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnAnonymousMethodExpression() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -191,12 +178,10 @@ void Method() } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact] - public async Task NotOnLambdaExpression() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnLambdaExpression() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -208,12 +193,10 @@ void Method() } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact] - public async Task NotOnMethodGroup() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnMethodGroup() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -225,12 +208,10 @@ void Method() } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact] - public async Task NotOnDeclarationWithMultipleDeclarators() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnDeclarationWithMultipleDeclarators() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -242,12 +223,10 @@ void Method() } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact] - public async Task NotOnDeclarationWithoutInitializer() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnDeclarationWithoutInitializer() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -259,12 +238,10 @@ void Method() } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact] - public async Task NotOnIFormattable() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnIFormattable() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -276,12 +253,10 @@ void Method() } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact] - public async Task NotOnFormattableString() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnFormattableString() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -293,12 +268,10 @@ void Method() } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact] - public async Task NotInCatchDeclaration() - { - await TestMissingInRegularAndScriptAsync( + public Task NotInCatchDeclaration() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -316,12 +289,10 @@ void Method() } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact] - public async Task NotDuringConflicts() - { - await TestMissingInRegularAndScriptAsync( + public Task NotDuringConflicts() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -337,12 +308,10 @@ class var } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact] - public async Task NotIfAlreadyImplicitlyTyped() - { - await TestMissingInRegularAndScriptAsync( + public Task NotIfAlreadyImplicitlyTyped() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -354,12 +323,10 @@ void Method() } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact] - public async Task NotOnImplicitConversion() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnImplicitConversion() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -372,12 +339,10 @@ void Method() } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact] - public async Task NotOnBoxingImplicitConversion() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnBoxingImplicitConversion() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -390,12 +355,10 @@ void Method() } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact] - public async Task NotOnRHS() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnRHS() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -407,12 +370,10 @@ void M() } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact] - public async Task NotOnVariablesUsedInInitalizerExpression() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnVariablesUsedInInitalizerExpression() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -424,12 +385,10 @@ void M() } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26894")] - public async Task NotOnVariablesOfEnumTypeNamedAsEnumTypeUsedInInitalizerExpressionAtFirstPosition() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnVariablesOfEnumTypeNamedAsEnumTypeUsedInInitalizerExpressionAtFirstPosition() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -443,12 +402,10 @@ void M() } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26894")] - public async Task NotOnVariablesNamedAsTypeUsedInInitalizerExpressionContainingTypeNameAtFirstPositionOfMemberAccess() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnVariablesNamedAsTypeUsedInInitalizerExpressionContainingTypeNameAtFirstPositionOfMemberAccess() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -465,12 +422,10 @@ void M() } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26894")] - public async Task SuggestOnVariablesUsedInInitalizerExpressionAsInnerPartsOfQualifiedNameStartedWithGlobal() - { - await TestAsync( + public Task SuggestOnVariablesUsedInInitalizerExpressionAsInnerPartsOfQualifiedNameStartedWithGlobal() + => TestAsync( """ enum A { X, Y } @@ -493,12 +448,10 @@ void M() } } """, CSharpParseOptions.Default, options: ImplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26894")] - public async Task SuggestOnVariablesUsedInInitalizerExpressionAsInnerPartsOfQualifiedName() - { - await TestInRegularAndScriptAsync( + public Task SuggestOnVariablesUsedInInitalizerExpressionAsInnerPartsOfQualifiedName() + => TestInRegularAndScriptAsync( """ using System; @@ -537,12 +490,10 @@ void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26894")] - public async Task SuggestOnVariablesUsedInInitalizerExpressionAsLastPartOfQualifiedName() - { - await TestInRegularAndScriptAsync( + public Task SuggestOnVariablesUsedInInitalizerExpressionAsLastPartOfQualifiedName() + => TestInRegularAndScriptAsync( """ using System; @@ -579,12 +530,10 @@ void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task NotOnAssignmentToInterfaceType() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnAssignmentToInterfaceType() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -604,12 +553,10 @@ interface IInterface { } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact] - public async Task NotOnArrayInitializerWithoutNewKeyword() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnArrayInitializerWithoutNewKeyword() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -626,12 +573,10 @@ static void M() } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact] - public async Task SuggestVarOnLocalWithIntrinsicTypeString() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarOnLocalWithIntrinsicTypeString() + => TestInRegularAndScriptAsync( """ using System; @@ -654,12 +599,10 @@ static void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task SuggestVarOnIntrinsicType() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarOnIntrinsicType() + => TestInRegularAndScriptAsync( """ using System; @@ -682,12 +625,10 @@ static void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27221")] - public async Task SuggestVarOnRefIntrinsicType() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarOnRefIntrinsicType() + => TestInRegularAndScriptAsync( """ using System; @@ -712,12 +653,10 @@ static void M() static ref int Ref() => throw null; } """, options: ImplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27221")] - public async Task WithRefIntrinsicTypeInForeach() - { - var before = """ + public Task WithRefIntrinsicTypeInForeach() + => TestInRegularAndScriptAsync(""" class E { public ref int Current => throw null; @@ -729,8 +668,7 @@ void M() foreach (ref [|int|] x in this) { } } } - """; - var after = """ + """, """ class E { public ref int Current => throw null; @@ -742,14 +680,11 @@ void M() foreach (ref var x in this) { } } } - """; - await TestInRegularAndScriptAsync(before, after, options: ImplicitTypeEverywhere()); - } + """, options: ImplicitTypeEverywhere()); [Fact] - public async Task SuggestVarOnFrameworkType() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarOnFrameworkType() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -772,12 +707,10 @@ static void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task SuggestVarOnUserDefinedType() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarOnUserDefinedType() + => TestInRegularAndScriptAsync( """ using System; @@ -800,12 +733,10 @@ void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task SuggestVarOnGenericType() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarOnGenericType() + => TestInRegularAndScriptAsync( """ using System; @@ -828,12 +759,10 @@ static void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task SuggestVarOnSeeminglyConflictingType() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarOnSeeminglyConflictingType() + => TestInRegularAndScriptAsync( """ using System; @@ -856,12 +785,10 @@ void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task SuggestVarOnSingleDimensionalArrayTypeWithNewOperator() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarOnSingleDimensionalArrayTypeWithNewOperator() + => TestInRegularAndScriptAsync( """ using System; @@ -884,12 +811,10 @@ static void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task SuggestVarOnSingleDimensionalArrayTypeWithNewOperator2() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarOnSingleDimensionalArrayTypeWithNewOperator2() + => TestInRegularAndScriptAsync( """ using System; @@ -912,12 +837,10 @@ static void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task SuggestVarOnSingleDimensionalJaggedArrayType() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarOnSingleDimensionalJaggedArrayType() + => TestInRegularAndScriptAsync( """ using System; @@ -946,12 +869,10 @@ static void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task SuggestVarOnDeclarationWithObjectInitializer() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarOnDeclarationWithObjectInitializer() + => TestInRegularAndScriptAsync( """ using System; @@ -984,12 +905,10 @@ private class Customer } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task SuggestVarOnDeclarationWithCollectionInitializer() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarOnDeclarationWithCollectionInitializer() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -1014,12 +933,10 @@ static void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task SuggestVarOnDeclarationWithCollectionAndObjectInitializers() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarOnDeclarationWithCollectionAndObjectInitializers() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -1060,12 +977,10 @@ private class Customer } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task SuggestVarOnForStatement() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarOnForStatement() + => TestInRegularAndScriptAsync( """ using System; @@ -1092,12 +1007,10 @@ static void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task SuggestVarOnForeachStatement() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarOnForeachStatement() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -1128,12 +1041,10 @@ static void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task SuggestVarOnQueryExpression() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarOnQueryExpression() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -1178,12 +1089,10 @@ private class Customer } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task SuggestVarInUsingStatement() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarInUsingStatement() + => TestInRegularAndScriptAsync( """ using System; @@ -1226,12 +1135,10 @@ public void Dispose() } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task SuggestVarOnExplicitConversion() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarOnExplicitConversion() + => TestInRegularAndScriptAsync( """ using System; @@ -1256,12 +1163,10 @@ void Method() } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task SuggestVarInConditionalAccessExpression() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarInConditionalAccessExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -1296,12 +1201,10 @@ C Test() } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task SuggestVarInCheckedExpression() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarInCheckedExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -1326,12 +1229,10 @@ static void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task SuggestVarInUnCheckedExpression() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarInUnCheckedExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -1356,12 +1257,10 @@ static void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task SuggestVarInAwaitExpression() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarInAwaitExpression() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1396,12 +1295,10 @@ private async Task ReadTextAsync(string filePath) } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task SuggestVarInParenthesizedExpression() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarInParenthesizedExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -1424,12 +1321,10 @@ public void ProcessRead() } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task DoNotSuggestVarOnBuiltInType_Literal_WithOption() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotSuggestVarOnBuiltInType_Literal_WithOption() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1441,12 +1336,10 @@ static void M() } } """, new TestParameters(options: ImplicitTypeButKeepIntrinsics())); - } [Fact] - public async Task DoNotSuggestVarOnBuiltInType_WithOption() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotSuggestVarOnBuiltInType_WithOption() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1460,12 +1353,10 @@ static void M() } } """, new TestParameters(options: ImplicitTypeButKeepIntrinsics())); - } [Fact] - public async Task DoNotSuggestVarOnFrameworkTypeEquivalentToBuiltInType() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotSuggestVarOnFrameworkTypeEquivalentToBuiltInType() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1479,12 +1370,10 @@ static void M() } } """, new TestParameters(options: ImplicitTypeButKeepIntrinsics())); - } [Fact] - public async Task SuggestVarWhereTypeIsEvident_DefaultExpression() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarWhereTypeIsEvident_DefaultExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -1507,12 +1396,10 @@ public void Process() } } """, options: ImplicitTypeWhereApparent()); - } [Fact] - public async Task SuggestVarWhereTypeIsEvident_Literals() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarWhereTypeIsEvident_Literals() + => TestInRegularAndScriptAsync( """ using System; @@ -1535,12 +1422,10 @@ public void Process() } } """, options: ImplicitTypeWhereApparentAndForIntrinsics()); - } [Fact] - public async Task DoNotSuggestVarWhereTypeIsEvident_Literals() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotSuggestVarWhereTypeIsEvident_Literals() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1552,12 +1437,10 @@ public void Process() } } """, new TestParameters(options: ImplicitTypeWhereApparent())); - } [Fact] - public async Task SuggestVarWhereTypeIsEvident_ObjectCreationExpression() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarWhereTypeIsEvident_ObjectCreationExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -1580,12 +1463,10 @@ public void Process() } } """, options: ImplicitTypeWhereApparent()); - } [Fact] - public async Task SuggestVarWhereTypeIsEvident_CastExpression() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarWhereTypeIsEvident_CastExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -1610,12 +1491,10 @@ public void Process() } } """, options: ImplicitTypeWhereApparent()); - } [Fact] - public async Task DoNotSuggestVar_BuiltInTypesRulePrecedesOverTypeIsApparentRule1() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotSuggestVar_BuiltInTypesRulePrecedesOverTypeIsApparentRule1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1628,12 +1507,10 @@ public void Process() } } """, new TestParameters(options: ImplicitTypeWhereApparent())); - } [Fact] - public async Task DoNotSuggestVar_BuiltInTypesRulePrecedesOverTypeIsApparentRule2() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotSuggestVar_BuiltInTypesRulePrecedesOverTypeIsApparentRule2() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1646,12 +1523,10 @@ public void Process() } } """, new TestParameters(options: ImplicitTypeWhereApparent())); - } [Fact] - public async Task DoNotSuggestVarWhereTypeIsEvident_IsExpression() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotSuggestVarWhereTypeIsEvident_IsExpression() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1672,12 +1547,10 @@ interface IInterface { } """, new TestParameters(options: ImplicitTypeWhereApparent())); - } [Fact] - public async Task SuggestVarWhereTypeIsEvident_AsExpression() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarWhereTypeIsEvident_AsExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -1718,12 +1591,10 @@ interface IInterface { } """, options: ImplicitTypeWhereApparent()); - } [Fact] - public async Task SuggestVarWhereTypeIsEvident_ConversionHelpers() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarWhereTypeIsEvident_ConversionHelpers() + => TestInRegularAndScriptAsync( """ using System; @@ -1746,12 +1617,10 @@ public void Process() } } """, options: ImplicitTypeWhereApparent()); - } [Fact] - public async Task SuggestVarWhereTypeIsEvident_CreationHelpers() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarWhereTypeIsEvident_CreationHelpers() + => TestInRegularAndScriptAsync( """ class C { @@ -1780,12 +1649,10 @@ class XElement internal static XElement Load() => return null; } """, options: ImplicitTypeWhereApparent()); - } [Fact] - public async Task SuggestVarWhereTypeIsEvident_CreationHelpersWithInferredTypeArguments() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarWhereTypeIsEvident_CreationHelpersWithInferredTypeArguments() + => TestInRegularAndScriptAsync( """ using System; @@ -1808,12 +1675,10 @@ public void Process() } } """, options: ImplicitTypeWhereApparent()); - } [Fact] - public async Task SuggestVarWhereTypeIsEvident_ConvertToType() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarWhereTypeIsEvident_ConvertToType() + => TestInRegularAndScriptAsync( """ using System; @@ -1838,12 +1703,10 @@ public void Process() } } """, options: ImplicitTypeWhereApparent()); - } [Fact] - public async Task SuggestVarWhereTypeIsEvident_IConvertibleToType() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarWhereTypeIsEvident_IConvertibleToType() + => TestInRegularAndScriptAsync( """ using System; @@ -1870,13 +1733,10 @@ public void Process() } } """, options: ImplicitTypeWhereApparent()); - } [Fact] - public async Task SuggestVarNotificationLevelSilent() - { - var source = - """ + public Task SuggestVarNotificationLevelSilent() + => TestDiagnosticInfoAsync(""" using System; class C { @@ -1885,18 +1745,14 @@ static void M() [|C|] n1 = new C(); } } - """; - await TestDiagnosticInfoAsync(source, + """, options: ImplicitTypeSilentEnforcement(), diagnosticId: IDEDiagnosticIds.UseImplicitTypeDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Hidden); - } [Fact] - public async Task SuggestVarNotificationLevelInfo() - { - var source = - """ + public Task SuggestVarNotificationLevelInfo() + => TestDiagnosticInfoAsync(""" using System; class C { @@ -1905,18 +1761,14 @@ static void M() [|int|] s = 5; } } - """; - await TestDiagnosticInfoAsync(source, + """, options: ImplicitTypeEnforcements(), diagnosticId: IDEDiagnosticIds.UseImplicitTypeDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Info); - } [Fact] - public async Task SuggestVarNotificationLevelWarning() - { - var source = - """ + public Task SuggestVarNotificationLevelWarning() + => TestDiagnosticInfoAsync(""" using System; class C { @@ -1925,18 +1777,14 @@ static void M() [|C[]|] n1 = new[] { new C() }; // type not apparent and not intrinsic } } - """; - await TestDiagnosticInfoAsync(source, + """, options: ImplicitTypeEnforcements(), diagnosticId: IDEDiagnosticIds.UseImplicitTypeDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Warning); - } [Fact] - public async Task SuggestVarNotificationLevelError() - { - var source = - """ + public Task SuggestVarNotificationLevelError() + => TestDiagnosticInfoAsync(""" using System; class C { @@ -1945,21 +1793,18 @@ static void M() [|C|] n1 = new C(); } } - """; - await TestDiagnosticInfoAsync(source, + """, options: ImplicitTypeEnforcements(), diagnosticId: IDEDiagnosticIds.UseImplicitTypeDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Error); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23893")] public async Task SuggestVarOnLocalWithIntrinsicArrayType() { var before = @"class C { static void M() { [|int[]|] s = new int[0]; } }"; - var after = @"class C { static void M() { var s = new int[0]; } }"; //The type is intrinsic and apparent - await TestInRegularAndScriptAsync(before, after, options: ImplicitTypeEverywhere()); + await TestInRegularAndScriptAsync(before, @"class C { static void M() { var s = new int[0]; } }", options: ImplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ImplicitTypeButKeepIntrinsics())); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ImplicitTypeWhereApparent())); // Preference of intrinsic types dominates } @@ -2021,17 +1866,14 @@ public async Task SuggestVarOnLocalWithIntrinsicTypeTuple() public async Task SuggestVarOnLocalWithNonApparentTupleType() { var before = @"class C { static void M(C c) { [|(int a, C b)|] s = (a: 1, b: c); } }"; - var after = @"class C { static void M(C c) { var s = (a: 1, b: c); } }"; - - await TestInRegularAndScriptAsync(before, after, options: ImplicitTypeEverywhere()); + await TestInRegularAndScriptAsync(before, @"class C { static void M(C c) { var s = (a: 1, b: c); } }", options: ImplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ImplicitTypeWhereApparentAndForIntrinsics())); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ImplicitTypeWhereApparent())); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11154")] - public async Task ValueTupleCreate() - { - await TestInRegularAndScriptAsync( + public Task ValueTupleCreate() + => TestInRegularAndScriptAsync( """ using System; @@ -2055,12 +1897,10 @@ static void M() } """ + trivial2uple, options: ImplicitTypeWhereApparent()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11095")] - public async Task ValueTupleCreate_2() - { - await TestInRegularAndScriptAsync( + public Task ValueTupleCreate_2() + => TestInRegularAndScriptAsync( """ using System; @@ -2084,12 +1924,10 @@ static void M() } """ + trivial2uple, options: ImplicitTypeWhereApparent()); - } [Fact] - public async Task TupleWithDifferentNames() - { - await TestMissingInRegularAndScriptAsync( + public Task TupleWithDifferentNames() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2099,13 +1937,11 @@ static void M() } } """, -new TestParameters(options: ImplicitTypeEverywhere())); - } + new TestParameters(options: ImplicitTypeEverywhere())); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14052")] - public async Task DoNotOfferOnForEachConversionIfItChangesSemantics() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotOfferOnForEachConversionIfItChangesSemantics() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -2136,13 +1972,11 @@ static void M() } } """, -new TestParameters(options: ImplicitTypeEverywhere())); - } + new TestParameters(options: ImplicitTypeEverywhere())); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14052")] - public async Task OfferOnForEachConversionIfItDoesNotChangesSemantics() - { - await TestInRegularAndScriptAsync( + public Task OfferOnForEachConversionIfItDoesNotChangesSemantics() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -2203,12 +2037,10 @@ static void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20437")] - public async Task SuggestVarOnDeclarationExpressionSyntax() - { - await TestInRegularAndScriptAsync( + public Task SuggestVarOnDeclarationExpressionSyntax() + => TestInRegularAndScriptAsync( """ using System; @@ -2231,14 +2063,11 @@ static void M() } } """, -options: ImplicitTypeEverywhere()); - } + options: ImplicitTypeEverywhere()); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23893")] - public async Task DoNotSuggestVarOnDeclarationExpressionSyntaxWithIntrinsicType() - { - var before = - """ + public Task DoNotSuggestVarOnDeclarationExpressionSyntaxWithIntrinsicType() + => TestMissingInRegularAndScriptAsync(""" class C { static void M(out int x) @@ -2246,14 +2075,11 @@ static void M(out int x) M([|out int|] x); } } - """; - await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ImplicitTypeButKeepIntrinsics())); - } + """, new TestParameters(options: ImplicitTypeButKeepIntrinsics())); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22768")] - public async Task DoNotSuggestVarOnStackAllocExpressions_SpanType() - { - await TestMissingInRegularAndScriptAsync(""" + public Task DoNotSuggestVarOnStackAllocExpressions_SpanType() + => TestMissingInRegularAndScriptAsync(""" using System; namespace System { @@ -2270,12 +2096,12 @@ static void M() } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22768")] - public async Task DoNotSuggestVarOnStackAllocExpressions_SpanType_NestedConditional() - { - await TestMissingInRegularAndScriptAsync(""" + [Fact] + [WorkItem("https://github.com/dotnet/roslyn/issues/22768")] + [WorkItem("https://github.com/dotnet/roslyn/issues/79337")] + public Task DoSuggestVarOnStackAllocExpressions_SpanType_NestedConditional() + => TestInRegularAndScript1Async(""" using System; namespace System { @@ -2291,13 +2117,29 @@ static void M(bool choice) [|Span|] x = choice ? stackalloc int [10] : stackalloc int [100]; } } + """, """ + using System; + namespace System + { + public readonly ref struct Span + { + unsafe public Span(void* pointer, int length) { } + } + } + class C + { + static void M(bool choice) + { + var x = choice ? stackalloc int [10] : stackalloc int [100]; + } + } """, new TestParameters(options: ImplicitTypeEverywhere())); - } - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22768")] - public async Task DoNotSuggestVarOnStackAllocExpressions_SpanType_NestedCast() - { - await TestMissingInRegularAndScriptAsync(""" + [Fact] + [WorkItem("https://github.com/dotnet/roslyn/issues/22768")] + [WorkItem("https://github.com/dotnet/roslyn/issues/79337")] + public Task DoSuggestVarOnStackAllocExpressions_SpanType_NestedCast() + => TestInRegularAndScript1Async(""" using System; namespace System { @@ -2313,13 +2155,27 @@ static void M() [|Span|] x = (Span)stackalloc int [100]; } } + """, """ + using System; + namespace System + { + public readonly ref struct Span + { + unsafe public Span(void* pointer, int length) { } + } + } + class C + { + static void M() + { + var x = (Span)stackalloc int [100]; + } + } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22768")] - public async Task SuggestVarOnLambdasWithNestedStackAllocs() - { - await TestInRegularAndScriptAsync(""" + public Task SuggestVarOnLambdasWithNestedStackAllocs() + => TestInRegularAndScriptAsync(""" using System.Linq; class C { @@ -2346,12 +2202,10 @@ unsafe static void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22768")] - public async Task SuggestVarOnAnonymousMethodsWithNestedStackAllocs() - { - await TestInRegularAndScriptAsync(""" + public Task SuggestVarOnAnonymousMethodsWithNestedStackAllocs() + => TestInRegularAndScriptAsync(""" using System.Linq; class C { @@ -2378,12 +2232,10 @@ unsafe static void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22768")] - public async Task SuggestVarOnStackAllocsNestedInLambdas() - { - await TestInRegularAndScriptAsync(""" + public Task SuggestVarOnStackAllocsNestedInLambdas() + => TestInRegularAndScriptAsync(""" using System.Linq; class C { @@ -2410,12 +2262,10 @@ unsafe static void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22768")] - public async Task SuggestVarOnStackAllocsNestedInAnonymousMethods() - { - await TestInRegularAndScriptAsync(""" + public Task SuggestVarOnStackAllocsNestedInAnonymousMethods() + => TestInRegularAndScriptAsync(""" using System.Linq; class C { @@ -2442,12 +2292,10 @@ unsafe static void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22768")] - public async Task SuggestVarOnStackAllocsInOuterMethodScope() - { - await TestInRegularAndScriptAsync(""" + public Task SuggestVarOnStackAllocsInOuterMethodScope() + => TestInRegularAndScriptAsync(""" class C { unsafe static void M() @@ -2464,12 +2312,10 @@ unsafe static void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23116")] - public async Task DoSuggestForDeclarationExpressionIfItWouldNotChangeOverloadResolution2() - { - await TestInRegularAndScriptAsync(""" + public Task DoSuggestForDeclarationExpressionIfItWouldNotChangeOverloadResolution2() + => TestInRegularAndScriptAsync(""" class Program { static int Main(string[] args) @@ -2494,12 +2340,10 @@ static int Main(string[] args) public static bool TryGetValue(string key, out bool value, int x) => false; } """, options: ImplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23116")] - public async Task DoNotSuggestForDeclarationExpressionIfItWouldChangeOverloadResolution() - { - await TestMissingInRegularAndScriptAsync(""" + public Task DoNotSuggestForDeclarationExpressionIfItWouldChangeOverloadResolution() + => TestMissingInRegularAndScriptAsync(""" class Program { static int Main(string[] args) @@ -2513,12 +2357,10 @@ static int Main(string[] args) public static bool TryGetValue(string key, out T value) => false; } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23116")] - public async Task DoNotSuggestIfChangesGenericTypeInference() - { - await TestMissingInRegularAndScriptAsync(""" + public Task DoNotSuggestIfChangesGenericTypeInference() + => TestMissingInRegularAndScriptAsync(""" class Program { static int Main(string[] args) @@ -2530,12 +2372,10 @@ static int Main(string[] args) public static bool TryGetValue(string key, out T value) => false; } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23116")] - public async Task SuggestIfDoesNotChangeGenericTypeInference1() - { - await TestInRegularAndScriptAsync(""" + public Task SuggestIfDoesNotChangeGenericTypeInference1() + => TestInRegularAndScriptAsync(""" class Program { static int Main(string[] args) @@ -2558,12 +2398,10 @@ static int Main(string[] args) public static bool TryGetValue(string key, out T value) => false; } """, options: ImplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23116")] - public async Task SuggestIfDoesNotChangeGenericTypeInference2() - { - await TestInRegularAndScriptAsync(""" + public Task SuggestIfDoesNotChangeGenericTypeInference2() + => TestInRegularAndScriptAsync(""" class Program { static int Main(string[] args) @@ -2586,12 +2424,10 @@ static int Main(string[] args) public static bool TryGetValue(T key, out T value) => false; } """, options: ImplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23711")] - public async Task SuggestVarForDelegateType() - { - await TestInRegularAndScriptAsync(""" + public Task SuggestVarForDelegateType() + => TestInRegularAndScriptAsync(""" class Program { static void Main(string[] args) @@ -2616,12 +2452,10 @@ static void Main(string[] args) delegate object GetHandler(); } """, options: ImplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23711")] - public async Task DoNotSuggestVarForDelegateType1() - { - await TestMissingInRegularAndScriptAsync(""" + public Task DoNotSuggestVarForDelegateType1() + => TestMissingInRegularAndScriptAsync(""" class Program { static void Main(string[] args) @@ -2634,12 +2468,10 @@ static void Main(string[] args) delegate object GetHandler(); } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23711")] - public async Task DoNotSuggestVarForDelegateType2() - { - await TestMissingInRegularAndScriptAsync(""" + public Task DoNotSuggestVarForDelegateType2() + => TestMissingInRegularAndScriptAsync(""" class Program { static void Main(string[] args) @@ -2654,12 +2486,10 @@ static void Main(string[] args) delegate object GetHandler(); } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23711")] - public async Task DoNotSuggestVarForDelegateType3() - { - await TestMissingInRegularAndScriptAsync(""" + public Task DoNotSuggestVarForDelegateType3() + => TestMissingInRegularAndScriptAsync(""" class Program { static void Main(string[] args) @@ -2672,12 +2502,10 @@ static void Main(string[] args) delegate object GetHandler(); } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24262")] - public async Task DoNotSuggestVarForInterfaceVariableInForeachStatement() - { - await TestMissingInRegularAndScriptAsync(""" + public Task DoNotSuggestVarForInterfaceVariableInForeachStatement() + => TestMissingInRegularAndScriptAsync(""" public interface ITest { string Value { get; } @@ -2700,12 +2528,10 @@ public void TestIt() } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24262")] - public async Task DoNotSuggestVarForInterfaceVariableInDeclarationStatement() - { - await TestMissingInRegularAndScriptAsync(""" + public Task DoNotSuggestVarForInterfaceVariableInDeclarationStatement() + => TestMissingInRegularAndScriptAsync(""" public interface ITest { string Value { get; } @@ -2724,12 +2550,10 @@ public void TestIt() } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24262")] - public async Task DoNotSuggestVarForAbstractClassVariableInForeachStatement() - { - await TestMissingInRegularAndScriptAsync(""" + public Task DoNotSuggestVarForAbstractClassVariableInForeachStatement() + => TestMissingInRegularAndScriptAsync(""" public abstract class MyAbClass { string Value { get; } @@ -2753,12 +2577,10 @@ public void TestIt() } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24262")] - public async Task DoNotSuggestVarForAbstractClassVariableInDeclarationStatement() - { - await TestMissingInRegularAndScriptAsync(""" + public Task DoNotSuggestVarForAbstractClassVariableInDeclarationStatement() + => TestMissingInRegularAndScriptAsync(""" public abstract class MyAbClass { string Value { get; } @@ -2779,12 +2601,10 @@ public void TestIt() } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact] - public async Task DoNoSuggestVarForRefForeachVar() - { - await TestMissingInRegularAndScriptAsync(""" + public Task DoNoSuggestVarForRefForeachVar() + => TestMissingInRegularAndScriptAsync(""" using System; namespace System { @@ -2811,12 +2631,10 @@ public void M(Span span) } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26923")] - public async Task NoSuggestionOnForeachCollectionExpression() - { - await TestMissingInRegularAndScriptAsync( + public Task NoSuggestionOnForeachCollectionExpression() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -2832,12 +2650,10 @@ static void Main(string[] args) } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39171")] - public async Task NoSuggestionForSwitchExpressionDifferentTypes() - { - await TestMissingInRegularAndScriptAsync( + public Task NoSuggestionForSwitchExpressionDifferentTypes() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -2858,12 +2674,10 @@ public static void Test(string name) } } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39171")] - public async Task SuggestSwitchExpressionSameOrInheritedTypes() - { - await TestInRegularAndScriptAsync( + public Task SuggestSwitchExpressionSameOrInheritedTypes() + => TestInRegularAndScriptAsync( """ using System; @@ -2906,12 +2720,10 @@ void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32088")] - public async Task DoNotSuggestVarOnDeclarationExpressionWithInferredTupleNames() - { - await TestMissingAsync( + public Task DoNotSuggestVarOnDeclarationExpressionWithInferredTupleNames() + => TestMissingAsync( """ using System.Collections.Generic; using System.Linq; @@ -2930,12 +2742,10 @@ static void Main(string[] args) new Dictionary>(); } """, parameters: new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32088")] - public async Task DoSuggestVarOnDeclarationExpressionWithMatchingTupleNames() - { - await TestInRegularAndScriptAsync( + public Task DoSuggestVarOnDeclarationExpressionWithMatchingTupleNames() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; using System.Linq; @@ -2972,13 +2782,11 @@ static void Main(string[] args) new Dictionary>(); } """, -options: ImplicitTypeEverywhere()); - } + options: ImplicitTypeEverywhere()); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44507")] - public async Task DoNotSuggestVarInAmbiguousSwitchExpression() - { - await TestMissingAsync( + public Task DoNotSuggestVarInAmbiguousSwitchExpression() + => TestMissingAsync( """ using System; @@ -3004,12 +2812,10 @@ class B : C { } """, parameters: new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44507")] - public async Task DoNotSuggestVarInSwitchExpressionWithDelegateType() - { - await TestMissingAsync( + public Task DoNotSuggestVarInSwitchExpressionWithDelegateType() + => TestMissingAsync( """ using System; @@ -3032,12 +2838,10 @@ private void M(object sender, EventArgs e) private readonly Action f2; } """, parameters: new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact] - public async Task DoNotSuggestVarForImplicitObjectCreation() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotSuggestVarForImplicitObjectCreation() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -3050,7 +2854,6 @@ void Method() } """, new TestParameters(options: ImplicitTypeEverywhere())); - } [Fact] public Task SuggestForNullable1() @@ -3083,7 +2886,7 @@ class C string? NullableString() => null; } """, -options: ImplicitTypeEverywhere()); + options: ImplicitTypeEverywhere()); [Fact] public Task SuggestForNullable2() @@ -3116,7 +2919,7 @@ class C string NonNullString() => string.Empty; } """, -options: ImplicitTypeEverywhere()); + options: ImplicitTypeEverywhere()); [Fact] public Task SuggestForNullable3() @@ -3149,7 +2952,7 @@ class C string NonNullString() => string.Empty; } """, -options: ImplicitTypeEverywhere()); + options: ImplicitTypeEverywhere()); [Fact] public Task SuggestForNullableOut1() @@ -3198,7 +3001,7 @@ bool GetNullString(out string? s) } } """, -options: ImplicitTypeEverywhere()); + options: ImplicitTypeEverywhere()); [Fact] public Task SuggestForNullableOut2() @@ -3247,7 +3050,7 @@ bool GetNonNullString(out string s) } } """, -options: ImplicitTypeEverywhere()); + options: ImplicitTypeEverywhere()); [Fact] public Task SuggestForNullableOut3() @@ -3296,12 +3099,11 @@ bool GetNonNullString(out string s) } } """, -options: ImplicitTypeEverywhere()); + options: ImplicitTypeEverywhere()); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41780")] - public async Task SuggestOnRefType1() - { - await TestAsync( + public Task SuggestOnRefType1() + => TestAsync( """ class C { @@ -3320,12 +3122,10 @@ void Method(ref int x) } } """, CSharpParseOptions.Default, options: ImplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58404")] - public async Task TestLambdaNaturalType1() - { - await TestInRegularAndScriptAsync( + public Task TestLambdaNaturalType1() + => TestInRegularAndScriptAsync( """ using System; @@ -3348,12 +3148,10 @@ static void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58404")] - public async Task TestLambdaNaturalType1_CSharp9() - { - await TestMissingInRegularAndScriptAsync( + public Task TestLambdaNaturalType1_CSharp9() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -3365,12 +3163,10 @@ static void M() } } """, new(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9), options: ImplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58404")] - public async Task TestLambdaNaturalType2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestLambdaNaturalType2() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -3382,12 +3178,10 @@ static void M() } } """, new(options: ImplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58404")] - public async Task TestLambdaNaturalType3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestLambdaNaturalType3() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -3401,12 +3195,10 @@ static void M() } } """, new(options: ImplicitTypeEverywhere())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64902")] - public async Task TestNotOnAwaitedTask() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOnAwaitedTask() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; using System.Threading.Tasks; @@ -3433,5 +3225,4 @@ public static IEnumerable DoSomeWorkGeneric() } } """, new(options: ImplicitTypeWhereApparent())); - } } diff --git a/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseImplicitTypeTests_FixAllTests.cs b/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseImplicitTypeTests_FixAllTests.cs index e6ad934c8b88f..6b62c66bfbd9d 100644 --- a/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseImplicitTypeTests_FixAllTests.cs +++ b/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseImplicitTypeTests_FixAllTests.cs @@ -17,9 +17,8 @@ public partial class UseImplicitTypeTests [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInDocumentScope_PreferImplicitTypeEverywhere() - { - var input = """ + public Task TestFixAllInDocumentScope_PreferImplicitTypeEverywhere() + => TestInRegularAndScriptAsync(""" @@ -71,9 +70,7 @@ static int F(int x, int y) - """; - - var expected = """ + """, """ @@ -125,17 +122,13 @@ static int F(int x, int y) - """; - - await TestInRegularAndScriptAsync(input, expected, options: ImplicitTypeEverywhere()); - } + """, options: ImplicitTypeEverywhere()); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInProject_PreferImplicitTypeEverywhere() - { - var input = """ + public Task TestFixAllInProject_PreferImplicitTypeEverywhere() + => TestInRegularAndScriptAsync(""" @@ -187,9 +180,7 @@ static int F(int x, int y) - """; - - var expected = """ + """, """ @@ -241,17 +232,13 @@ static int F(int x, int y) - """; - - await TestInRegularAndScriptAsync(input, expected, options: ImplicitTypeEverywhere()); - } + """, options: ImplicitTypeEverywhere()); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInSolution_PreferImplicitTypeEverywhere() - { - var input = """ + public Task TestFixAllInSolution_PreferImplicitTypeEverywhere() + => TestInRegularAndScriptAsync(""" @@ -303,9 +290,7 @@ static int F(int x, int y) - """; - - var expected = """ + """, """ @@ -357,17 +342,13 @@ static int F(int x, int y) - """; - - await TestInRegularAndScriptAsync(input, expected, options: ImplicitTypeEverywhere()); - } + """, options: ImplicitTypeEverywhere()); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInDocumentScope_PreferBuiltInTypes() - { - var input = """ + public Task TestFixAllInDocumentScope_PreferBuiltInTypes() + => TestInRegularAndScriptAsync(""" @@ -387,9 +368,7 @@ static int F(int x, int y) - """; - - var expected = """ + """, """ @@ -409,10 +388,7 @@ static int F(int x, int y) - """; - - await TestInRegularAndScriptAsync(input, expected, options: ImplicitTypeButKeepIntrinsics()); - } + """, options: ImplicitTypeButKeepIntrinsics()); #endregion } diff --git a/src/Analyzers/CSharp/Tests/UseImplicitlyTypedLambdaExpression/UseImplicitlyTypedLambdaExpressionTests.cs b/src/Analyzers/CSharp/Tests/UseImplicitlyTypedLambdaExpression/UseImplicitlyTypedLambdaExpressionTests.cs index ea122efc4460d..a69145b5040a0 100644 --- a/src/Analyzers/CSharp/Tests/UseImplicitlyTypedLambdaExpression/UseImplicitlyTypedLambdaExpressionTests.cs +++ b/src/Analyzers/CSharp/Tests/UseImplicitlyTypedLambdaExpression/UseImplicitlyTypedLambdaExpressionTests.cs @@ -22,9 +22,8 @@ public sealed class UseImplicitlyTypedLambdaExpressionTests private static readonly LanguageVersion CSharp14 = LanguageVersionExtensions.CSharpNext; [Fact] - public async Task TestAssignedToObject() - { - await new VerifyCS.Test + public Task TestAssignedToObject() + => new VerifyCS.Test { TestCode = """ using System; @@ -39,12 +38,10 @@ void M() """, LanguageVersion = CSharp14, }.RunAsync(); - } [Fact] - public async Task TestCastedToDelegate() - { - await new VerifyCS.Test + public Task TestCastedToDelegate() + => new VerifyCS.Test { TestCode = """ using System; @@ -59,12 +56,10 @@ void M() """, LanguageVersion = CSharp14, }.RunAsync(); - } [Fact] - public async Task TestCastedToObject() - { - await new VerifyCS.Test + public Task TestCastedToObject() + => new VerifyCS.Test { TestCode = """ using System; @@ -79,12 +74,10 @@ void M() """, LanguageVersion = CSharp14, }.RunAsync(); - } [Fact] - public async Task TestAssignedToDelegate() - { - await new VerifyCS.Test + public Task TestAssignedToDelegate() + => new VerifyCS.Test { TestCode = """ using System; @@ -99,12 +92,10 @@ void M() """, LanguageVersion = CSharp14, }.RunAsync(); - } [Fact] - public async Task TestAssignedToVar() - { - await new VerifyCS.Test + public Task TestAssignedToVar() + => new VerifyCS.Test { TestCode = """ using System; @@ -119,12 +110,10 @@ void M() """, LanguageVersion = CSharp14, }.RunAsync(); - } [Fact] - public async Task TestAssignedToStronglyTypedDelegate() - { - await new VerifyCS.Test + public Task TestAssignedToStronglyTypedDelegate() + => new VerifyCS.Test { TestCode = """ using System; @@ -150,12 +139,10 @@ void M() """, LanguageVersion = CSharp14, }.RunAsync(); - } [Fact] - public async Task TestExplicitReturnType() - { - await new VerifyCS.Test + public Task TestExplicitReturnType() + => new VerifyCS.Test { TestCode = """ using System; @@ -170,12 +157,10 @@ void M() """, LanguageVersion = CSharp14, }.RunAsync(); - } [Fact] - public async Task TestWithDefaultVAlue() - { - await new VerifyCS.Test + public Task TestWithDefaultVAlue() + => new VerifyCS.Test { TestCode = """ using System; @@ -190,12 +175,10 @@ void M() """, LanguageVersion = CSharp14, }.RunAsync(); - } [Fact] - public async Task TestCastToStronglyTypedDelegate() - { - await new VerifyCS.Test + public Task TestCastToStronglyTypedDelegate() + => new VerifyCS.Test { TestCode = """ using System; @@ -221,12 +204,10 @@ void M() """, LanguageVersion = CSharp14, }.RunAsync(); - } [Fact] - public async Task TestCreationOfStronglyTypedDelegate() - { - await new VerifyCS.Test + public Task TestCreationOfStronglyTypedDelegate() + => new VerifyCS.Test { TestCode = """ using System; @@ -252,12 +233,10 @@ void M() """, LanguageVersion = CSharp14, }.RunAsync(); - } [Fact] - public async Task TestArgument() - { - await new VerifyCS.Test + public Task TestArgument() + => new VerifyCS.Test { TestCode = """ using System; @@ -283,12 +262,10 @@ void M(Action action) """, LanguageVersion = CSharp14, }.RunAsync(); - } [Fact] - public async Task TestOverloadResolution() - { - await new VerifyCS.Test + public Task TestOverloadResolution() + => new VerifyCS.Test { TestCode = """ using System; @@ -307,12 +284,10 @@ void M(Action action) """, LanguageVersion = CSharp14, }.RunAsync(); - } [Fact] - public async Task TestModifier_CSharp13() - { - await new VerifyCS.Test + public Task TestModifier_CSharp13() + => new VerifyCS.Test { TestCode = """ using System; @@ -329,12 +304,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp13, }.RunAsync(); - } [Fact] - public async Task TestModifier_CSharp14() - { - await new VerifyCS.Test + public Task TestModifier_CSharp14() + => new VerifyCS.Test { TestCode = """ using System; @@ -364,12 +337,10 @@ void M() """, LanguageVersion = CSharp14, }.RunAsync(); - } [Fact] - public async Task TestNested() - { - await new VerifyCS.Test + public Task TestNested() + => new VerifyCS.Test { TestCode = """ using System; @@ -401,12 +372,10 @@ void M() """, LanguageVersion = CSharp14, }.RunAsync(); - } [Fact] - public async Task TestParams() - { - await new VerifyCS.Test + public Task TestParams() + => new VerifyCS.Test { TestCode = """ using System; @@ -436,12 +405,10 @@ void M() """, LanguageVersion = CSharp14, }.RunAsync(); - } [Fact] - public async Task TestMultiLine() - { - await new VerifyCS.Test + public Task TestMultiLine() + => new VerifyCS.Test { TestCode = """ using System; @@ -473,12 +440,10 @@ void M() """, LanguageVersion = CSharp14, }.RunAsync(); - } [Fact] - public async Task TestAttribute() - { - await new VerifyCS.Test + public Task TestAttribute() + => new VerifyCS.Test { TestCode = """ using System; @@ -512,5 +477,4 @@ void M() """, LanguageVersion = CSharp14, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UseIndexOrRangeOperator/UseIndexOperatorTests.cs b/src/Analyzers/CSharp/Tests/UseIndexOrRangeOperator/UseIndexOperatorTests.cs index e79f348f6f993..1f0016e80cb99 100644 --- a/src/Analyzers/CSharp/Tests/UseIndexOrRangeOperator/UseIndexOperatorTests.cs +++ b/src/Analyzers/CSharp/Tests/UseIndexOrRangeOperator/UseIndexOperatorTests.cs @@ -21,10 +21,11 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseIndexOrRangeOperator public sealed class UseIndexOperatorTests { [Fact] - public async Task TestNotInCSharp7() - { - var source = - """ + public Task TestNotInCSharp7() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string s) @@ -32,15 +33,9 @@ void Goo(string s) var v = s[s.Length - 1]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp7, }.RunAsync(); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)] public async Task TestWithMissingReference() @@ -78,10 +73,11 @@ class {|#0:C|} } [Fact] - public async Task TestSimple() - { - var source = - """ + public Task TestSimple() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string s) @@ -89,9 +85,8 @@ void Goo(string s) var v = s[[|s.Length - 1|]]; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void Goo(string s) @@ -99,15 +94,8 @@ void Goo(string s) var v = s[^1]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] public async Task TestMultipleDefinitions() @@ -122,16 +110,6 @@ void Goo(string s) } } """; - var fixedSource = - """ - class C - { - void Goo(string s) - { - var v = s[^1]; - } - } - """; // Adding a dependency with internal definitions of Index and Range should not break the feature var source1 = "namespace System { internal struct Index { } internal struct Range { } }"; @@ -152,15 +130,24 @@ void Goo(string s) }, AdditionalProjectReferences = { "DependencyProject" }, }, - FixedCode = fixedSource, + FixedCode = """ + class C + { + void Goo(string s) + { + var v = s[^1]; + } + } + """, }.RunAsync(); } [Fact] - public async Task TestComplexSubtaction() - { - var source = - """ + public Task TestComplexSubtaction() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string s) @@ -168,9 +155,8 @@ void Goo(string s) var v = s[[|s.Length - (1 + 1)|]]; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void Goo(string s) @@ -178,21 +164,15 @@ void Goo(string s) var v = s[^(1 + 1)]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestComplexInstance() - { - var source = - """ + public Task TestComplexInstance() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ using System.Linq; class C @@ -202,9 +182,8 @@ void Goo(string[] ss) var v = ss.Last()[[|ss.Last().Length - 3|]]; } } - """; - var fixedSource = - """ + """, + FixedCode = """ using System.Linq; class C @@ -214,21 +193,15 @@ void Goo(string[] ss) var v = ss.Last()[^3]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestNotWithoutSubtraction1() - { - var source = - """ + public Task TestNotWithoutSubtraction1() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string s) @@ -236,20 +209,15 @@ void Goo(string s) var v = s[s.Length]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, + """, }.RunAsync(); - } [Fact] - public async Task TestNotWithoutSubtraction2() - { - var source = - """ + public Task TestNotWithoutSubtraction2() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string s) @@ -257,20 +225,15 @@ void Goo(string s) var v = s[s.Length + 1]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, + """, }.RunAsync(); - } [Fact] - public async Task TestNotWithMultipleArgs() - { - var source = - """ + public Task TestNotWithMultipleArgs() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ struct S { public int Length { get; } public int this[int i] { get => 0; } public int this[int i, int j] { get => 0; } public int this[System.Index i] { get => 0; } } class C { @@ -279,20 +242,15 @@ void Goo(S s) var v = s[s.Length - 1, 2]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, + """, }.RunAsync(); - } [Fact] - public async Task TestUserDefinedTypeWithLength() - { - var source = - """ + public Task TestUserDefinedTypeWithLength() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ struct S { public int Length { get; } public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { @@ -301,9 +259,8 @@ void Goo(S s) var v = s[[|s.Length - 2|]]; } } - """; - var fixedSource = - """ + """, + FixedCode = """ struct S { public int Length { get; } public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { @@ -312,21 +269,15 @@ void Goo(S s) var v = s[^2]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestUserDefinedTypeWithCount() - { - var source = - """ + public Task TestUserDefinedTypeWithCount() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ struct S { public int Count { get; } public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { @@ -335,9 +286,8 @@ void Goo(S s) var v = s[[|s.Count - 2|]]; } } - """; - var fixedSource = - """ + """, + FixedCode = """ struct S { public int Count { get; } public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { @@ -346,21 +296,15 @@ void Goo(S s) var v = s[^2]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestUserDefinedTypeWithNoLengthOrCount() - { - var source = - """ + public Task TestUserDefinedTypeWithNoLengthOrCount() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ struct S { public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { @@ -369,20 +313,15 @@ void Goo(S s) var v = s[s.{|CS1061:Count|} - 2]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, + """, }.RunAsync(); - } [Fact] - public async Task TestUserDefinedTypeWithNoInt32Indexer() - { - var source = - """ + public Task TestUserDefinedTypeWithNoInt32Indexer() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ struct S { public int Length { get; } public int this[System.Index i] { get => 0; } } class C { @@ -391,20 +330,15 @@ void Goo(S s) var v = s[s.Length - 2]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, + """, }.RunAsync(); - } [Fact] - public async Task TestUserDefinedTypeWithNoIndexIndexer() - { - var source = - """ + public Task TestUserDefinedTypeWithNoIndexIndexer() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ struct S { public int Count { get; } public int this[int i] { get => 0; } } class C { @@ -413,9 +347,8 @@ void Goo(S s) var v = s[[|s.Count - 2|]]; } } - """; - var fixedSource = - """ + """, + FixedCode = """ struct S { public int Count { get; } public int this[int i] { get => 0; } } class C { @@ -424,21 +357,15 @@ void Goo(S s) var v = s[^2]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestMethodToMethod() - { - var source = - """ + public Task TestMethodToMethod() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ struct S { public int Length { get; } public int Get(int i) => 0; public int Get(System.Index i) => 0; } class C { @@ -447,9 +374,8 @@ void Goo(S s) var v = s.Get([|s.Length - 1|]); } } - """; - var fixedSource = - """ + """, + FixedCode = """ struct S { public int Length { get; } public int Get(int i) => 0; public int Get(System.Index i) => 0; } class C { @@ -458,21 +384,15 @@ void Goo(S s) var v = s.Get(^1); } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestMethodToMethodMissingIndexIndexer() - { - var source = - """ + public Task TestMethodToMethodMissingIndexIndexer() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ struct S { public int Length { get; } public int Get(int i) => 0; } class C { @@ -481,20 +401,15 @@ void Goo(S s) var v = s.Get(s.Length - 1); } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, + """, }.RunAsync(); - } [Fact] - public async Task TestMethodToMethodWithIntIndexer() - { - var source = - """ + public Task TestMethodToMethodWithIntIndexer() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ struct S { public int Length { get; } public int Get(int i) => 0; public int this[int i] { get => 0; } } class C { @@ -503,20 +418,15 @@ void Goo(S s) var v = s.Get(s.Length - 1); } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36909")] - public async Task TestMissingWithNoSystemIndex() - { - var source = - """ + public Task TestMissingWithNoSystemIndex() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp20, + TestCode = """ class C { void Goo(string[] s) @@ -524,15 +434,9 @@ void Goo(string[] s) var v = s[s.Length - 1]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp20, - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] public async Task TestMissingWithInaccessibleSystemIndex() @@ -572,10 +476,11 @@ void Goo(string[] s) } [Fact] - public async Task TestArray() - { - var source = - """ + public Task TestArray() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string[] s) @@ -583,9 +488,8 @@ void Goo(string[] s) var v = s[[|s.Length - 1|]]; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void Goo(string[] s) @@ -593,21 +497,15 @@ void Goo(string[] s) var v = s[^1]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestFixAll1() - { - var source = - """ + public Task TestFixAll1() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string s) @@ -616,9 +514,8 @@ void Goo(string s) var v2 = s[[|s.Length - 1|]]; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void Goo(string s) @@ -627,21 +524,15 @@ void Goo(string s) var v2 = s[^1]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestNestedFixAll1() - { - var source = - """ + public Task TestNestedFixAll1() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string[] s) @@ -649,9 +540,8 @@ void Goo(string[] s) var v1 = s[[|s.Length - 2|]][[|s[[|s.Length - 2|]].Length - 1|]]; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void Goo(string[] s) @@ -659,21 +549,15 @@ void Goo(string[] s) var v1 = s[^2][^1]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestNestedFixAll2() - { - var source = - """ + public Task TestNestedFixAll2() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string[] s) @@ -681,9 +565,8 @@ void Goo(string[] s) var v1 = s[[|s.Length - 2|]][[|s[[|s.Length - 2|]].Length - 1|]]; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void Goo(string[] s) @@ -691,21 +574,15 @@ void Goo(string[] s) var v1 = s[^2][^1]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestSimple_NoIndexIndexer_SupportsIntIndexer() - { - var source = - """ + public Task TestSimple_NoIndexIndexer_SupportsIntIndexer() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ using System.Collections.Generic; class C { @@ -714,9 +591,8 @@ void Goo(List s) var v = s[[|s.Count - 1|]]; } } - """; - var fixedSource = - """ + """, + FixedCode = """ using System.Collections.Generic; class C { @@ -725,21 +601,15 @@ void Goo(List s) var v = s[^1]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestSimple_NoIndexIndexer_SupportsIntIndexer_Set() - { - var source = - """ + public Task TestSimple_NoIndexIndexer_SupportsIntIndexer_Set() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ using System.Collections.Generic; class C { @@ -748,9 +618,8 @@ void Goo(List s) s[[|s.Count - 1|]] = 1; } } - """; - var fixedSource = - """ + """, + FixedCode = """ using System.Collections.Generic; class C { @@ -759,21 +628,15 @@ void Goo(List s) s[^1] = 1; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task NotOnConstructedIndexer() - { - var source = - """ + public Task NotOnConstructedIndexer() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ using System.Collections.Generic; class C { @@ -782,20 +645,15 @@ void Goo(Dictionary s) var v = s[s.Count - 1]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49347")] - public async Task TestNotInExpressionTree() - { - var source = - """ + public Task TestNotInExpressionTree() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ using System; using System.Collections.Generic; using System.Linq.Expressions; @@ -806,12 +664,6 @@ void Goo(List s) Expression> f = () => s[s.Count - 1]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, + """, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UseIndexOrRangeOperator/UseRangeOperatorTests.cs b/src/Analyzers/CSharp/Tests/UseIndexOrRangeOperator/UseRangeOperatorTests.cs index e7b4cafd19474..a803df3b64794 100644 --- a/src/Analyzers/CSharp/Tests/UseIndexOrRangeOperator/UseRangeOperatorTests.cs +++ b/src/Analyzers/CSharp/Tests/UseIndexOrRangeOperator/UseRangeOperatorTests.cs @@ -21,10 +21,11 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseIndexOrRangeOperator public sealed class UseRangeOperatorTests { [Fact] - public async Task TestNotInCSharp7() - { - var source = - """ + public Task TestNotInCSharp7() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string s) @@ -32,15 +33,9 @@ void Goo(string s) var v = s.Substring(1, s.Length - 1); } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp7, }.RunAsync(); - } [Fact] public async Task TestWithMissingReference() @@ -80,10 +75,11 @@ class {|#0:C|} } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36909")] - public async Task TestNotWithoutSystemRange() - { - var source = - """ + public Task TestNotWithoutSystemRange() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp20, + TestCode = """ class C { void Goo(string s) @@ -91,15 +87,9 @@ void Goo(string s) var v = s.Substring(1, s.Length - 1); } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp20, - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] public async Task TestNotWithInaccessibleSystemRange() @@ -139,10 +129,11 @@ void Goo(string s) } [Fact] - public async Task TestSimple() - { - var source = - """ + public Task TestSimple() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string s) @@ -150,9 +141,8 @@ void Goo(string s) var v = s.Substring([|1, s.Length - 1|]); } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void Goo(string s) @@ -160,15 +150,8 @@ void Goo(string s) var v = s[1..]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestMultipleDefinitions() @@ -183,16 +166,6 @@ void Goo(string s) } } """; - var fixedSource = - """ - class C - { - void Goo(string s) - { - var v = s[1..]; - } - } - """; // Adding a dependency with internal definitions of Index and Range should not break the feature var source1 = "namespace System { internal struct Index { } internal struct Range { } }"; @@ -213,15 +186,24 @@ void Goo(string s) }, AdditionalProjectReferences = { "DependencyProject" }, }, - FixedCode = fixedSource, + FixedCode = """ + class C + { + void Goo(string s) + { + var v = s[1..]; + } + } + """, }.RunAsync(); } [Fact] - public async Task TestComplexSubstraction() - { - var source = - """ + public Task TestComplexSubstraction() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string s, int bar, int baz) @@ -229,9 +211,8 @@ void Goo(string s, int bar, int baz) var v = s.Substring([|bar, s.Length - baz - bar|]); } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void Goo(string s, int bar, int baz) @@ -239,21 +220,15 @@ void Goo(string s, int bar, int baz) var v = s[bar..^baz]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestSubstringOneArgument() - { - var source = - """ + public Task TestSubstringOneArgument() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string s) @@ -261,9 +236,8 @@ void Goo(string s) var v = s.Substring([|1|]); } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void Goo(string s) @@ -271,21 +245,15 @@ void Goo(string s) var v = s[1..]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestSliceOneArgument() - { - var source = - """ + public Task TestSliceOneArgument() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ using System; class C { @@ -294,9 +262,8 @@ void Goo(Span s) var v = s.Slice([|1|]); } } - """; - var fixedSource = - """ + """, + FixedCode = """ using System; class C { @@ -305,21 +272,15 @@ void Goo(Span s) var v = s[1..]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestExpressionOneArgument() - { - var source = - """ + public Task TestExpressionOneArgument() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string s, int bar) @@ -327,9 +288,8 @@ void Goo(string s, int bar) var v = s.Substring([|bar|]); } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void Goo(string s, int bar) @@ -337,21 +297,15 @@ void Goo(string s, int bar) var v = s[bar..]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestConstantSubtraction1() - { - var source = - """ + public Task TestConstantSubtraction1() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string s) @@ -359,9 +313,8 @@ void Goo(string s) var v = s.Substring([|1, s.Length - 2|]); } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void Goo(string s) @@ -369,21 +322,15 @@ void Goo(string s) var v = s[1..^1]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestNotWithoutSubtraction() - { - var source = - """ + public Task TestNotWithoutSubtraction() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string s) @@ -391,21 +338,16 @@ void Goo(string s) var v = s.Substring(1, 2); } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp7, }.RunAsync(); - } [Fact] - public async Task TestNonStringType() - { - var source = - """ + public Task TestNonStringType() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ struct S { public S Slice(int start, int length) => default; public int Length { get; } public S this[System.Range r] { get => default; } } class C { @@ -414,9 +356,8 @@ void Goo(S s) var v = s.Slice([|1, s.Length - 2|]); } } - """; - var fixedSource = - """ + """, + FixedCode = """ struct S { public S Slice(int start, int length) => default; public int Length { get; } public S this[System.Range r] { get => default; } } class C { @@ -425,21 +366,15 @@ void Goo(S s) var v = s[1..^1]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestNonStringTypeWithoutRangeIndexer() - { - var source = - """ + public Task TestNonStringTypeWithoutRangeIndexer() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ struct S { public S Slice(int start, int length) => default; public int Length { get; } } class C { @@ -448,9 +383,8 @@ void Goo(S s) var v = s.Slice([|1, s.Length - 2|]); } } - """; - var fixedSource = - """ + """, + FixedCode = """ struct S { public S Slice(int start, int length) => default; public int Length { get; } } class C { @@ -459,21 +393,15 @@ void Goo(S s) var v = s[1..^1]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestNonStringType_Assignment() - { - var source = - """ + public Task TestNonStringType_Assignment() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ struct S { public ref S Slice(int start, int length) => throw null; public int Length { get; } public ref S this[System.Range r] { get => throw null; } } class C { @@ -482,9 +410,8 @@ void Goo(S s) s.Slice([|1, s.Length - 2|]) = default; } } - """; - var fixedSource = - """ + """, + FixedCode = """ struct S { public ref S Slice(int start, int length) => throw null; public int Length { get; } public ref S this[System.Range r] { get => throw null; } } class C { @@ -493,20 +420,15 @@ void Goo(S s) s[1..^1] = default; } } - """; - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestMethodToMethod() - { - var source = - """ + public Task TestMethodToMethod() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ struct S { public int Slice(int start, int length) => 0; public int Length { get; } public int Slice(System.Range r) => 0; } class C { @@ -515,9 +437,8 @@ void Goo(S s) var v = s.Slice([|1, s.Length - 2|]); } } - """; - var fixedSource = - """ + """, + FixedCode = """ struct S { public int Slice(int start, int length) => 0; public int Length { get; } public int Slice(System.Range r) => 0; } class C { @@ -526,23 +447,15 @@ void Goo(S s) var v = s.Slice(1..^1); } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestFixAllInvocationToElementAccess1() - { - // Note: once the IOp tree has support for range operators, this should - // simplify even further. - var source = - """ + public Task TestFixAllInvocationToElementAccess1() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string s, string t) @@ -550,9 +463,8 @@ void Goo(string s, string t) var v = t.Substring([|s.Substring([|1, s.Length - 2|])[0], t.Length - s.Substring([|1, s.Length - 2|])[0]|]); } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void Goo(string s, string t) @@ -560,23 +472,15 @@ void Goo(string s, string t) var v = t[s[1..^1][0]..]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestFixAllInvocationToElementAccess2() - { - // Note: once the IOp tree has support for range operators, this should - // simplify even further. - var source = - """ + public Task TestFixAllInvocationToElementAccess2() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string s, string t) @@ -584,9 +488,8 @@ void Goo(string s, string t) var v = t.Substring([|s.Substring([|1|])[0]|]); } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void Goo(string s, string t) @@ -594,21 +497,15 @@ void Goo(string s, string t) var v = t[s[1..][0]..]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestWithTypeWithActualSliceMethod1() - { - var source = - """ + public Task TestWithTypeWithActualSliceMethod1() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ using System; class C { @@ -617,9 +514,8 @@ void Goo(Span s) var v = s.Slice([|1, s.Length - 1|]); } } - """; - var fixedSource = - """ + """, + FixedCode = """ using System; class C { @@ -628,21 +524,15 @@ void Goo(Span s) var v = s[1..]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestWithTypeWithActualSliceMethod2() - { - var source = - """ + public Task TestWithTypeWithActualSliceMethod2() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ using System; class C { @@ -651,9 +541,8 @@ void Goo(Span s) var v = s.Slice([|1, s.Length - 2|]); } } - """; - var fixedSource = - """ + """, + FixedCode = """ using System; class C { @@ -662,21 +551,15 @@ void Goo(Span s) var v = s[1..^1]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43202")] - public async Task TestWritableType() - { - var source = - """ + public Task TestWritableType() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ using System; struct S { public ref S Slice(int start, int length) => throw null; @@ -691,19 +574,14 @@ void Goo(S s) s.Slice(1, s.Length - 2) = default; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, + """, }.RunAsync(); - } [Fact] - public async Task TestReturnByRef() - { - var source = - """ + public Task TestReturnByRef() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ struct S { public ref S Slice(int start, int length) => throw null; public int Length { get; } public S this[System.Range r] { get => throw null; } } class C { @@ -712,9 +590,8 @@ void Goo(S s) var x = s.Slice([|1, s.Length - 2|]); } } - """; - var fixedSource = - """ + """, + FixedCode = """ struct S { public ref S Slice(int start, int length) => throw null; public int Length { get; } public S this[System.Range r] { get => throw null; } } class C { @@ -723,20 +600,15 @@ void Goo(S s) var x = s[1..^1]; } } - """; - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43202")] - public async Task TestIntWritableType() - { - var source = - """ + public Task TestIntWritableType() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ using System; struct S { public ref S Slice(int start, int length) => throw null; @@ -751,9 +623,8 @@ void Goo(S s) s.Slice([|1, s.Length - 2|]) = default; } } - """; - var fixedSource = - """ + """, + FixedCode = """ using System; struct S { public ref S Slice(int start, int length) => throw null; @@ -768,21 +639,15 @@ void Goo(S s) s[1..^1] = default; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43202")] - public async Task TestReadWriteProperty() - { - var source = - """ + public Task TestReadWriteProperty() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ using System; struct S { public ref S Slice(int start, int length) => throw null; @@ -797,9 +662,8 @@ void Goo(S s) s.Slice([|1, s.Length - 2|]) = default; } } - """; - var fixedSource = - """ + """, + FixedCode = """ using System; struct S { public ref S Slice(int start, int length) => throw null; @@ -814,20 +678,15 @@ void Goo(S s) s[1..^1] = default; } } - """; - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestWithTypeWithActualSliceMethod3() - { - var source = - """ + public Task TestWithTypeWithActualSliceMethod3() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ using System; class C { @@ -836,9 +695,8 @@ void Goo(Span s) var v = s.Slice([|1|]); } } - """; - var fixedSource = - """ + """, + FixedCode = """ using System; class C { @@ -847,20 +705,15 @@ void Goo(Span s) var v = s[1..]; } } - """; - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36997")] - public async Task TestExpressionWithAddOperatorArgument() - { - var source = - """ + public Task TestExpressionWithAddOperatorArgument() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string s, int bar) @@ -868,9 +721,8 @@ void Goo(string s, int bar) var v = s.Substring([|bar + 1|]); } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void Goo(string s, int bar) @@ -878,21 +730,15 @@ void Goo(string s, int bar) var v = s[(bar + 1)..]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact] - public async Task TestExpressionWithElementAccessShouldNotAddParentheses() - { - var source = - """ + public Task TestExpressionWithElementAccessShouldNotAddParentheses() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string s, int[] bar) @@ -900,9 +746,8 @@ void Goo(string s, int[] bar) _ = s.Substring([|bar[0]|]); } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void Goo(string s, int[] bar) @@ -910,71 +755,52 @@ void Goo(string s, int[] bar) _ = s[bar[0]..]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47183")] - public async Task TestExpressionWithNullConditionalAccess() - { - var source = - """ + public Task TestExpressionWithNullConditionalAccess() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ #nullable enable public class Test { public string? M(string? arg) => arg?.Substring([|42|]); } - """; - var fixedSource = - """ + """, + FixedCode = """ #nullable enable public class Test { public string? M(string? arg) => arg?[42..]; } - """; - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47183")] - public async Task TestExpressionWithNullConditionalAccessWithPropertyAccess() - { - var source = - """ + public Task TestExpressionWithNullConditionalAccessWithPropertyAccess() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ public class Test { public int? M(string arg) => arg?.Substring([|42|]).Length; } - """; - var fixedSource = - """ + """, + FixedCode = """ public class Test { public int? M(string arg) => arg?[42..].Length; } - """; - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/47183")] [InlineData( @@ -992,10 +818,11 @@ public class Test [InlineData( "c?.Prop?.Substring([|42|])", "c?.Prop?[42..]")] - public async Task TestExpressionWithNullConditionalAccessVariations(string subStringCode, string rangeCode) - { - var source = - $$""" + public Task TestExpressionWithNullConditionalAccessVariations(string subStringCode, string rangeCode) + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = $$""" public class C { public string Prop { get; set; } @@ -1005,9 +832,8 @@ public class Test public object M(C c) => {{subStringCode}}; } - """; - var fixedSource = - $$""" + """, + FixedCode = $$""" public class C { public string Prop { get; set; } @@ -1017,20 +843,15 @@ public class Test public object M(C c) => {{rangeCode}}; } - """; - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38055")] - public async Task TestStringMethod() - { - var source = - """ + public Task TestStringMethod() + => new VerifyCS.Test + { + ReferenceAssemblies = new ReferenceAssemblies("nostdlib"), + TestCode = """ namespace System { public class Object {} @@ -1056,9 +877,8 @@ public class String : Object string Foo(int x) => Substring([|1, x - 1|]); } } - """; - var fixedSource = - """ + """, + FixedCode = """ namespace System { public class Object {} @@ -1084,21 +904,15 @@ public class String : Object string Foo(int x) => this[1..x]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = new ReferenceAssemblies("nostdlib"), - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38055")] - public async Task TestSliceOnThis() - { - var source = - """ + public Task TestSliceOnThis() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { public int Length => 0; @@ -1106,9 +920,8 @@ class C public C Foo(int x) => Slice([|1, x - 1|]); } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { public int Length => 0; @@ -1116,21 +929,15 @@ class C public C Foo(int x) => this[1..x]; } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56269")] - public async Task TestStartingFromZero() - { - var source = - """ + public Task TestStartingFromZero() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string s) @@ -1138,9 +945,8 @@ void Goo(string s) var v = s.Substring([|0|]); } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void Goo(string s) @@ -1148,21 +954,15 @@ void Goo(string s) var v = s[..]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56269")] - public async Task TestStartingFromAribtraryPosition() - { - var source = - """ + public Task TestStartingFromAribtraryPosition() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string s) @@ -1170,9 +970,8 @@ void Goo(string s) var v = s.Substring([|5|]); } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void Goo(string s) @@ -1180,21 +979,15 @@ void Goo(string s) var v = s[5..]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56269")] - public async Task TestStartingFromZeroToArbitraryEnd() - { - var source = - """ + public Task TestStartingFromZeroToArbitraryEnd() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string s) @@ -1202,9 +995,8 @@ void Goo(string s) var v = s.Substring([|0, 5|]); } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void Goo(string s) @@ -1212,21 +1004,15 @@ void Goo(string s) var v = s[..5]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56269")] - public async Task TestStartingFromZeroGoingToLength() - { - var source = - """ + public Task TestStartingFromZeroGoingToLength() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string s) @@ -1234,9 +1020,8 @@ void Goo(string s) var v = s.Substring([|0, s.Length|]); } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void Goo(string s) @@ -1244,21 +1029,15 @@ void Goo(string s) var v = s[..]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40438")] - public async Task TestStartingFromZeroGoingToLengthMinus1() - { - var source = - """ + public Task TestStartingFromZeroGoingToLengthMinus1() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ class C { void Goo(string s) @@ -1266,9 +1045,8 @@ void Goo(string s) var v = s.Substring([|0, s.Length - 1|]); } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void Goo(string s) @@ -1276,21 +1054,15 @@ void Goo(string s) var v = s[..^1]; } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, - FixedCode = fixedSource, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49347")] - public async Task TestNotInExpressionTree() - { - var source = - """ + public Task TestNotInExpressionTree() + => new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, + TestCode = """ using System; using System.Linq.Expressions; @@ -1301,19 +1073,12 @@ void M() Expression> e = (s, i) => s.Substring(i); } } - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, - TestCode = source, + """, }.RunAsync(); - } [Fact, WorkItem(60988, "https://github.com/dotnet/roslyn/issues/60988")] - public async Task TestCheckedExpression() - { - await new VerifyCS.Test + public Task TestCheckedExpression() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = @@ -1347,12 +1112,10 @@ void M() } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76091")] - public async Task TestRemoveFromZeroToArbitraryLocation() - { - await new VerifyCS.Test + public Task TestRemoveFromZeroToArbitraryLocation() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = """ @@ -1374,12 +1137,10 @@ void Goo(string s, int x) } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76091")] - public async Task TestRemoveFromZeroToArbitraryLocation1() - { - await new VerifyCS.Test + public Task TestRemoveFromZeroToArbitraryLocation1() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = """ @@ -1401,12 +1162,10 @@ void Goo(string s, int x) } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76091")] - public async Task TestRemoveFromZeroToLengthMinusSomeAmount() - { - await new VerifyCS.Test + public Task TestRemoveFromZeroToLengthMinusSomeAmount() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = """ @@ -1428,12 +1187,10 @@ void Goo(string s, int x) } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76091")] - public async Task TestRemoveFromZeroToLengthMinusSomeAmount1() - { - await new VerifyCS.Test + public Task TestRemoveFromZeroToLengthMinusSomeAmount1() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = """ @@ -1455,12 +1212,10 @@ void Goo(string s, int x) } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76091")] - public async Task TestRemoveFromPositionToLengthMinusThatPosition() - { - await new VerifyCS.Test + public Task TestRemoveFromPositionToLengthMinusThatPosition() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = """ @@ -1482,12 +1237,10 @@ void Goo(string s, int x) } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76091")] - public async Task TestRemoveFromLengthMinusPositionToPosition() - { - await new VerifyCS.Test + public Task TestRemoveFromLengthMinusPositionToPosition() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = """ @@ -1509,12 +1262,10 @@ void Goo(string s, int x) } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76091")] - public async Task TestRemoveFromLengthMinusPositionToPosition2() - { - await new VerifyCS.Test + public Task TestRemoveFromLengthMinusPositionToPosition2() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = """ @@ -1536,12 +1287,10 @@ void Goo(string s, int x) } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76091")] - public async Task TestOneArgRemove() - { - await new VerifyCS.Test + public Task TestOneArgRemove() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = """ @@ -1563,12 +1312,10 @@ void Goo(string s, int x) } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76091")] - public async Task TestOneArgRemove1() - { - await new VerifyCS.Test + public Task TestOneArgRemove1() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = """ @@ -1590,12 +1337,10 @@ void Goo(string s, int x) } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76091")] - public async Task TestOneArgFromEnd() - { - await new VerifyCS.Test + public Task TestOneArgFromEnd() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = """ @@ -1617,5 +1362,4 @@ void Goo(string s, int x) } """, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UseInferredMemberName/UseInferredMemberNameTests.cs b/src/Analyzers/CSharp/Tests/UseInferredMemberName/UseInferredMemberNameTests.cs index 68dde8df9574b..e53c94d09f339 100644 --- a/src/Analyzers/CSharp/Tests/UseInferredMemberName/UseInferredMemberNameTests.cs +++ b/src/Analyzers/CSharp/Tests/UseInferredMemberName/UseInferredMemberNameTests.cs @@ -30,9 +30,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Latest); [Fact] - public async Task TestInferredTupleName() - { - await TestAsync( + public Task TestInferredTupleName() + => TestAsync( """ class C { @@ -53,12 +52,10 @@ void M() } } """, parseOptions: s_parseOptions); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24480")] - public async Task TestInferredTupleName_WithAmbiguity() - { - await TestMissingAsync( + public Task TestInferredTupleName_WithAmbiguity() + => TestMissingAsync( """ class C { @@ -69,12 +66,10 @@ void M() } } """, parameters: new TestParameters(parseOptions: s_parseOptions)); - } [Fact] - public async Task TestInferredTupleNameAfterCommaWithCSharp6() - { - await TestActionCountAsync( + public Task TestInferredTupleNameAfterCommaWithCSharp6() + => TestActionCountAsync( """ class C { @@ -85,12 +80,10 @@ void M() } } """, count: 0, parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); - } [Fact] - public async Task TestInferredTupleNameAfterCommaWithCSharp7() - { - await TestActionCountAsync( + public Task TestInferredTupleNameAfterCommaWithCSharp7() + => TestActionCountAsync( """ class C { @@ -101,12 +94,10 @@ void M() } } """, count: 0, parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7))); - } [Fact] - public async Task TestFixAllInferredTupleNameWithTrivia() - { - await TestAsync( + public Task TestFixAllInferredTupleNameWithTrivia() + => TestAsync( """ class C { @@ -129,12 +120,10 @@ void M() } } """, parseOptions: s_parseOptions); - } [Fact] - public async Task TestInferredAnonymousTypeMemberName() - { - await TestAsync( + public Task TestInferredAnonymousTypeMemberName() + => TestAsync( """ class C { @@ -155,12 +144,10 @@ void M() } } """, parseOptions: s_parseOptions); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24480")] - public async Task TestInferredAnonymousTypeMemberName_WithAmbiguity() - { - await TestMissingAsync( + public Task TestInferredAnonymousTypeMemberName_WithAmbiguity() + => TestMissingAsync( """ class C { @@ -171,12 +158,10 @@ void M() } } """, parameters: new TestParameters(parseOptions: s_parseOptions)); - } [Fact] - public async Task TestFixAllInferredAnonymousTypeMemberNameWithTrivia() - { - await TestAsync( + public Task TestFixAllInferredAnonymousTypeMemberNameWithTrivia() + => TestAsync( """ class C { @@ -199,5 +184,4 @@ void M() } } """, parseOptions: s_parseOptions); - } } diff --git a/src/Analyzers/CSharp/Tests/UseInterpolatedVerbatimString/UseInterpolatedVerbatimStringCodeFixTests.cs b/src/Analyzers/CSharp/Tests/UseInterpolatedVerbatimString/UseInterpolatedVerbatimStringCodeFixTests.cs index 0e252e45b2d46..9d1f6221277bf 100644 --- a/src/Analyzers/CSharp/Tests/UseInterpolatedVerbatimString/UseInterpolatedVerbatimStringCodeFixTests.cs +++ b/src/Analyzers/CSharp/Tests/UseInterpolatedVerbatimString/UseInterpolatedVerbatimStringCodeFixTests.cs @@ -26,9 +26,8 @@ internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProvide => (null, new CSharpUseInterpolatedVerbatimStringCodeFixProvider()); [Fact] - public async Task Simple() - { - await TestInRegularAndScript1Async( + public Task Simple() + => TestInRegularAndScript1Async( """ class C { @@ -47,12 +46,10 @@ void M() } } """, parameters: new TestParameters().WithParseOptions(new CSharpParseOptions(LanguageVersion.CSharp7_3))); - } [Fact] - public async Task AfterString() - { - await TestMissingInRegularAndScriptAsync( + public Task AfterString() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -62,12 +59,10 @@ void M() } } """, parameters: new TestParameters().WithParseOptions(new CSharpParseOptions(LanguageVersion.CSharp7_3))); - } [Fact] - public async Task InCall() - { - await TestInRegularAndScript1Async( + public Task InCall() + => TestInRegularAndScript1Async( """ class C { @@ -86,12 +81,10 @@ void M(string x) } } """, parameters: new TestParameters().WithParseOptions(new CSharpParseOptions(LanguageVersion.CSharp7_3))); - } [Fact] - public async Task FixAllInDocument() - { - await TestInRegularAndScript1Async( + public Task FixAllInDocument() + => TestInRegularAndScript1Async( """ class C { @@ -112,12 +105,10 @@ void M() } } """, parameters: new TestParameters().WithParseOptions(new CSharpParseOptions(LanguageVersion.CSharp7_3))); - } [Fact] - public async Task MissingOnInterpolatedVerbatimString() - { - await TestMissingAsync( + public Task MissingOnInterpolatedVerbatimString() + => TestMissingAsync( """ class C { @@ -127,12 +118,10 @@ void M() } } """, parameters: new TestParameters().WithParseOptions(new CSharpParseOptions(LanguageVersion.CSharp7_3))); - } [Fact] - public async Task MissingInCSharp8() - { - await TestMissingAsync( + public Task MissingInCSharp8() + => TestMissingAsync( """ class C { @@ -142,5 +131,4 @@ void M() } } """, parameters: new TestParameters().WithParseOptions(new CSharpParseOptions(LanguageVersion.CSharp8))); - } } diff --git a/src/Analyzers/CSharp/Tests/UseIsNullCheck/UseIsNullCheckForCastAndEqualityOperatorTests.cs b/src/Analyzers/CSharp/Tests/UseIsNullCheck/UseIsNullCheckForCastAndEqualityOperatorTests.cs index f9e6e48acd4fb..a2cf50f327673 100644 --- a/src/Analyzers/CSharp/Tests/UseIsNullCheck/UseIsNullCheckForCastAndEqualityOperatorTests.cs +++ b/src/Analyzers/CSharp/Tests/UseIsNullCheck/UseIsNullCheckForCastAndEqualityOperatorTests.cs @@ -27,9 +27,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider => (new CSharpUseIsNullCheckForCastAndEqualityOperatorDiagnosticAnalyzer(), new CSharpUseIsNullCheckForCastAndEqualityOperatorCodeFixProvider()); [Fact] - public async Task TestEquality() - { - await TestInRegularAndScriptAsync( + public Task TestEquality() + => TestInRegularAndScriptAsync( """ using System; @@ -54,12 +53,10 @@ void M(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58483")] - public async Task TestIsNullTitle() - { - await TestExactActionSetOfferedAsync( + public Task TestIsNullTitle() + => TestExactActionSetOfferedAsync( """ using System; @@ -72,13 +69,11 @@ void M(string s) } } """, -[CSharpAnalyzersResources.Use_is_null_check]); - } + [CSharpAnalyzersResources.Use_is_null_check]); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58483")] - public async Task TestIsObjectTitle() - { - await TestExactActionSetOfferedAsync( + public Task TestIsObjectTitle() + => TestExactActionSetOfferedAsync( """ using System; @@ -91,14 +86,12 @@ void M(string s) } } """, -[CSharpAnalyzersResources.Use_is_object_check], -new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); - } + [CSharpAnalyzersResources.Use_is_object_check], + new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58483")] - public async Task TestIsNotNullTitle() - { - await TestExactActionSetOfferedAsync( + public Task TestIsNotNullTitle() + => TestExactActionSetOfferedAsync( """ using System; @@ -111,14 +104,12 @@ void M(string s) } } """, -[CSharpAnalyzersResources.Use_is_not_null_check], -new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9))); - } + [CSharpAnalyzersResources.Use_is_not_null_check], + new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9))); [Fact] - public async Task TestEqualitySwapped() - { - await TestInRegularAndScriptAsync( + public Task TestEqualitySwapped() + => TestInRegularAndScriptAsync( """ using System; @@ -143,12 +134,10 @@ void M(string s) } } """); - } [Fact] - public async Task TestNotEquality_CSharp8() - { - await TestInRegularAndScriptAsync( + public Task TestNotEquality_CSharp8() + => TestInRegularAndScriptAsync( """ using System; @@ -173,12 +162,10 @@ void M(string s) } } """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8)); - } [Fact] - public async Task TestNotEquality_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task TestNotEquality_CSharp9() + => TestInRegularAndScriptAsync( """ using System; @@ -203,12 +190,10 @@ void M(string s) } } """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); - } [Fact] - public async Task TestNotEqualitySwapped_CSharp8() - { - await TestInRegularAndScriptAsync( + public Task TestNotEqualitySwapped_CSharp8() + => TestInRegularAndScriptAsync( """ using System; @@ -233,12 +218,10 @@ void M(string s) } } """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8)); - } [Fact] - public async Task TestNotEqualitySwapped_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task TestNotEqualitySwapped_CSharp9() + => TestInRegularAndScriptAsync( """ using System; @@ -263,12 +246,10 @@ void M(string s) } } """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); - } [Fact] - public async Task TestMissingPreCSharp7() - { - await TestMissingAsync( + public Task TestMissingPreCSharp7() + => TestMissingAsync( """ using System; @@ -281,12 +262,10 @@ void M(string s) } } """, parameters: new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); - } [Fact] - public async Task TestOnlyForObjectCast() - { - await TestMissingAsync( + public Task TestOnlyForObjectCast() + => TestMissingAsync( """ using System; @@ -299,12 +278,10 @@ void M(string s) } } """); - } [Fact] - public async Task TestFixAll1() - { - await TestInRegularAndScriptAsync( + public Task TestFixAll1() + => TestInRegularAndScriptAsync( """ using System; @@ -335,12 +312,10 @@ void M(string s) } } """); - } [Fact] - public async Task TestFixAllNested1() - { - await TestInRegularAndScriptAsync( + public Task TestFixAllNested1() + => TestInRegularAndScriptAsync( """ using System; @@ -365,12 +340,10 @@ void M(string s2) } } """); - } [Fact] - public async Task TestTrivia1() - { - await TestInRegularAndScriptAsync( + public Task TestTrivia1() + => TestInRegularAndScriptAsync( """ using System; @@ -395,12 +368,10 @@ void M(string s) } } """); - } [Fact] - public async Task TestTrivia2() - { - await TestInRegularAndScriptAsync( + public Task TestTrivia2() + => TestInRegularAndScriptAsync( """ using System; @@ -425,12 +396,10 @@ void M(string s) } } """); - } [Fact] - public async Task TestConstrainedTypeParameter() - { - await TestInRegularAndScriptAsync( + public Task TestConstrainedTypeParameter() + => TestInRegularAndScriptAsync( """ using System; @@ -455,12 +424,10 @@ void M(T s) where T : class } } """); - } [Fact] - public async Task TestUnconstrainedTypeParameter() - { - await TestMissingAsync( + public Task TestUnconstrainedTypeParameter() + => TestMissingAsync( """ using System; @@ -473,12 +440,10 @@ void M(T s) } } """); - } [Fact] - public async Task TestComplexExpr() - { - await TestInRegularAndScriptAsync( + public Task TestComplexExpr() + => TestInRegularAndScriptAsync( """ using System; @@ -503,12 +468,10 @@ void M(string[] s) } } """); - } [Fact] - public async Task TestNotOnDefault() - { - await TestMissingAsync( + public Task TestNotOnDefault() + => TestMissingAsync( """ using System; @@ -521,5 +484,4 @@ void M(string[] s) } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/UseIsNullCheck/UseIsNullCheckForReferenceEqualsTests.cs b/src/Analyzers/CSharp/Tests/UseIsNullCheck/UseIsNullCheckForReferenceEqualsTests.cs index b0490b8431e42..20d674120f5ee 100644 --- a/src/Analyzers/CSharp/Tests/UseIsNullCheck/UseIsNullCheckForReferenceEqualsTests.cs +++ b/src/Analyzers/CSharp/Tests/UseIsNullCheck/UseIsNullCheckForReferenceEqualsTests.cs @@ -31,9 +31,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider => (new CSharpUseIsNullCheckForReferenceEqualsDiagnosticAnalyzer(), new CSharpUseIsNullCheckForReferenceEqualsCodeFixProvider()); [Fact] - public async Task TestIdentifierName() - { - await TestInRegularAndScript1Async( + public Task TestIdentifierName() + => TestInRegularAndScript1Async( """ using System; @@ -58,12 +57,10 @@ void M(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58483")] - public async Task TestIsNullTitle() - { - await TestExactActionSetOfferedAsync( + public Task TestIsNullTitle() + => TestExactActionSetOfferedAsync( """ using System; @@ -76,13 +73,11 @@ void M(string s) } } """, -[CSharpAnalyzersResources.Use_is_null_check]); - } + [CSharpAnalyzersResources.Use_is_null_check]); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58483")] - public async Task TestIsObjectTitle() - { - await TestExactActionSetOfferedAsync( + public Task TestIsObjectTitle() + => TestExactActionSetOfferedAsync( """ using System; @@ -95,14 +90,12 @@ void M(string s) } } """, -[CSharpAnalyzersResources.Use_is_object_check], -new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); - } + [CSharpAnalyzersResources.Use_is_object_check], + new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58483")] - public async Task TestIsNotNullTitle() - { - await TestExactActionSetOfferedAsync( + public Task TestIsNotNullTitle() + => TestExactActionSetOfferedAsync( """ using System; @@ -115,14 +108,12 @@ void M(string s) } } """, -[CSharpAnalyzersResources.Use_is_not_null_check], -new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9))); - } + [CSharpAnalyzersResources.Use_is_not_null_check], + new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9))); [Fact] - public async Task TestBuiltInType() - { - await TestInRegularAndScript1Async( + public Task TestBuiltInType() + => TestInRegularAndScript1Async( """ using System; @@ -147,12 +138,10 @@ void M(string s) } } """); - } [Fact] - public async Task TestNamedType() - { - await TestInRegularAndScript1Async( + public Task TestNamedType() + => TestInRegularAndScript1Async( """ using System; @@ -177,12 +166,10 @@ void M(string s) } } """); - } [Fact] - public async Task TestReversed() - { - await TestInRegularAndScript1Async( + public Task TestReversed() + => TestInRegularAndScript1Async( """ using System; @@ -207,12 +194,10 @@ void M(string s) } } """); - } [Fact] - public async Task TestNegated_CSharp7() - { - await TestInRegularAndScript1Async( + public Task TestNegated_CSharp7() + => TestInRegularAndScript1Async( """ using System; @@ -237,12 +222,10 @@ void M(string s) } } """, new TestParameters(parseOptions: CSharp7)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task TestNegated_CSharp9() - { - await TestInRegularAndScript1Async( + public Task TestNegated_CSharp9() + => TestInRegularAndScript1Async( """ using System; @@ -267,12 +250,10 @@ void M(string s) } } """, new TestParameters(parseOptions: CSharp9)); - } [Fact] - public async Task TestNotInCSharp6() - { - await TestMissingAsync( + public Task TestNotInCSharp6() + => TestMissingAsync( """ using System; @@ -285,12 +266,10 @@ void M(string s) } } """, parameters: new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); - } [Fact] - public async Task TestFixAll1() - { - await TestInRegularAndScript1Async( + public Task TestFixAll1() + => TestInRegularAndScript1Async( """ using System; @@ -317,12 +296,10 @@ void M(string s1, string s2) } } """); - } [Fact] - public async Task TestFixAll2() - { - await TestInRegularAndScript1Async( + public Task TestFixAll2() + => TestInRegularAndScript1Async( """ using System; @@ -349,12 +326,10 @@ void M(string s1, string s2) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23581")] - public async Task TestValueParameterTypeIsUnconstrainedGeneric_CSharp7() - { - await TestInRegularAndScript1Async( + public Task TestValueParameterTypeIsUnconstrainedGeneric_CSharp7() + => TestInRegularAndScript1Async( """ class C { @@ -378,12 +353,10 @@ public static void NotNull(T value) } } """, new TestParameters(parseOptions: CSharp7)); - } [Fact, WorkItem(23581, "https://github.com/dotnet/roslyn/issues/47972")] - public async Task TestValueParameterTypeIsUnconstrainedGeneric_CSharp8() - { - await TestInRegularAndScript1Async( + public Task TestValueParameterTypeIsUnconstrainedGeneric_CSharp8() + => TestInRegularAndScript1Async( """ using System; @@ -412,12 +385,10 @@ public static void NotNull(T value) } } """, new TestParameters(parseOptions: CSharp8)); - } [Fact] - public async Task TestValueParameterTypeIsUnconstrainedGenericNegated_CSharp7() - { - await TestInRegularAndScript1Async( + public Task TestValueParameterTypeIsUnconstrainedGenericNegated_CSharp7() + => TestInRegularAndScript1Async( """ class C { @@ -441,12 +412,10 @@ public static void NotNull(T value) } } """, new TestParameters(parseOptions: CSharp7)); - } [Fact] - public async Task TestValueParameterTypeIsUnconstrainedGenericNegated_CSharp9() - { - await TestInRegularAndScript1Async( + public Task TestValueParameterTypeIsUnconstrainedGenericNegated_CSharp9() + => TestInRegularAndScript1Async( """ class C { @@ -470,12 +439,10 @@ public static void NotNull(T value) } } """, new TestParameters(parseOptions: CSharp9)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23581")] - public async Task TestValueParameterTypeIsRefConstraintGeneric() - { - await TestInRegularAndScript1Async( + public Task TestValueParameterTypeIsRefConstraintGeneric() + => TestInRegularAndScript1Async( """ class C { @@ -500,12 +467,10 @@ public static void NotNull(T value) where T:class } } """); - } [Fact] - public async Task TestValueParameterTypeIsRefConstraintGenericNegated_CSharp7() - { - await TestInRegularAndScript1Async( + public Task TestValueParameterTypeIsRefConstraintGenericNegated_CSharp7() + => TestInRegularAndScript1Async( """ class C { @@ -530,12 +495,10 @@ public static void NotNull(T value) where T:class } } """, new TestParameters(parseOptions: CSharp7)); - } [Fact] - public async Task TestValueParameterTypeIsRefConstraintGenericNegated_CSharp9() - { - await TestInRegularAndScript1Async( + public Task TestValueParameterTypeIsRefConstraintGenericNegated_CSharp9() + => TestInRegularAndScript1Async( """ class C { @@ -560,12 +523,10 @@ public static void NotNull(T value) where T:class } } """, new TestParameters(parseOptions: CSharp9)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23581")] - public async Task TestValueParameterTypeIsValueConstraintGeneric() - { - await TestMissingAsync( + public Task TestValueParameterTypeIsValueConstraintGeneric() + => TestMissingAsync( """ class C { @@ -578,12 +539,10 @@ public static void NotNull(T value) where T:struct } } """); - } [Fact] - public async Task TestValueParameterTypeIsValueConstraintGenericNegated() - { - await TestMissingAsync( + public Task TestValueParameterTypeIsValueConstraintGenericNegated() + => TestMissingAsync( """ class C { @@ -596,12 +555,10 @@ public static void NotNull(T value) where T:struct } } """); - } [Fact] - public async Task TestFixAllNested1() - { - await TestInRegularAndScript1Async( + public Task TestFixAllNested1() + => TestInRegularAndScript1Async( """ using System; @@ -626,12 +583,10 @@ void M(string s2) } } """); - } [Fact, WorkItem(23581, "https://github.com/dotnet/roslyn/issues/47972")] - public async Task TestValueParameterTypeIsBaseTypeConstraintGeneric() - { - await TestInRegularAndScript1Async( + public Task TestValueParameterTypeIsBaseTypeConstraintGeneric() + => TestInRegularAndScript1Async( """ using System; @@ -660,5 +615,4 @@ public static void NotNull(T value) where T:C } } """, new TestParameters(parseOptions: CSharp7)); - } } diff --git a/src/Analyzers/CSharp/Tests/UseIsNullCheck/UseNullCheckOverTypeCheckDiagnosticAnalyzerTests.cs b/src/Analyzers/CSharp/Tests/UseIsNullCheck/UseNullCheckOverTypeCheckDiagnosticAnalyzerTests.cs index 9cf027e7ba3d0..68ec767bb32bf 100644 --- a/src/Analyzers/CSharp/Tests/UseIsNullCheck/UseNullCheckOverTypeCheckDiagnosticAnalyzerTests.cs +++ b/src/Analyzers/CSharp/Tests/UseIsNullCheck/UseNullCheckOverTypeCheckDiagnosticAnalyzerTests.cs @@ -17,15 +17,13 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseIsNullCheck; [Trait(Traits.Feature, Traits.Features.CodeActionsUseIsNullCheck)] public sealed class CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzerTests { - private static async Task VerifyAsync(string source, string fixedSource, LanguageVersion languageVersion) - { - await new VerifyCS.Test + private static Task VerifyAsync(string source, string fixedSource, LanguageVersion languageVersion) + => new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, LanguageVersion = languageVersion, }.RunAsync(); - } private static async Task VerifyCSharp9Async(string source, string fixedSource) => await VerifyAsync(source, fixedSource, LanguageVersion.CSharp9); @@ -49,9 +47,8 @@ public bool M(string value) } [Fact] - public async Task TestIsObject() - { - var source = """ + public Task TestIsObject() + => VerifyCSharp9Async(""" public class C { public bool M(string value) @@ -59,8 +56,7 @@ public bool M(string value) return [|value is object|]/*comment*/; } } - """; - var fixedSource = """ + """, """ public class C { public bool M(string value) @@ -68,9 +64,7 @@ public bool M(string value) return value is not null/*comment*/; } } - """; - await VerifyCSharp9Async(source, fixedSource); - } + """); [Fact] public async Task TestIsObject2() @@ -88,9 +82,8 @@ public bool M(string value) } [Fact] - public async Task TestIsNotObject() - { - var source = """ + public Task TestIsNotObject() + => VerifyCSharp9Async(""" public class C { public bool M(string value) @@ -98,8 +91,7 @@ public bool M(string value) return value is [|not object|]; } } - """; - var fixedSource = """ + """, """ public class C { public bool M(string value) @@ -107,9 +99,7 @@ public bool M(string value) return value is null; } } - """; - await VerifyCSharp9Async(source, fixedSource); - } + """); [Fact] public async Task TestIsNotObject2() @@ -142,9 +132,8 @@ public bool M(object value) } [Fact] - public async Task TestIsStringAgainstString() - { - var source = """ + public Task TestIsStringAgainstString() + => VerifyCSharp9Async(""" public class C { public bool M(string value) @@ -152,8 +141,7 @@ public bool M(string value) return [|value is string|]; } } - """; - var fixedSource = """ + """, """ public class C { public bool M(string value) @@ -161,9 +149,7 @@ public bool M(string value) return value is not null; } } - """; - await VerifyCSharp9Async(source, fixedSource); - } + """); [Fact] public async Task TestIsNotStringAgainstObject_NoDiagnostic() @@ -181,9 +167,8 @@ public bool M(object value) } [Fact] - public async Task TestIsNotStringAgainstString() - { - var source = """ + public Task TestIsNotStringAgainstString() + => VerifyCSharp9Async(""" public class C { public bool M(string value) @@ -191,8 +176,7 @@ public bool M(string value) return value is [|not string|]; } } - """; - var fixedSource = """ + """, """ public class C { public bool M(string value) @@ -200,9 +184,7 @@ public bool M(string value) return value is null; } } - """; - await VerifyCSharp9Async(source, fixedSource); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58377")] public async Task TestNotInExpressionTree() diff --git a/src/Analyzers/CSharp/Tests/UseLocalFunction/UseLocalFunctionTests.cs b/src/Analyzers/CSharp/Tests/UseLocalFunction/UseLocalFunctionTests.cs index e81bac9537532..6e8f2086c7aba 100644 --- a/src/Analyzers/CSharp/Tests/UseLocalFunction/UseLocalFunctionTests.cs +++ b/src/Analyzers/CSharp/Tests/UseLocalFunction/UseLocalFunctionTests.cs @@ -29,9 +29,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider private static readonly ParseOptions CSharp72ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_2); [Fact] - public async Task TestMissingBeforeCSharp7() - { - await TestMissingAsync( + public Task TestMissingBeforeCSharp7() + => TestMissingAsync( """ using System; @@ -51,12 +50,10 @@ void M() } } """, parameters: new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); - } [Fact] - public async Task TestMissingIfWrittenAfter() - { - await TestMissingAsync( + public Task TestMissingIfWrittenAfter() + => TestMissingAsync( """ using System; @@ -78,12 +75,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingIfWrittenInside() - { - await TestMissingAsync( + public Task TestMissingIfWrittenInside() + => TestMissingAsync( """ using System; @@ -104,12 +99,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingForErrorType() - { - await TestMissingAsync( + public Task TestMissingForErrorType() + => TestMissingAsync( """ class C { @@ -128,12 +121,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingForMultipleVariables() - { - await TestMissingAsync( + public Task TestMissingForMultipleVariables() + => TestMissingAsync( """ using System; @@ -153,12 +144,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingForField() - { - await TestMissingAsync( + public Task TestMissingForField() + => TestMissingAsync( """ using System; @@ -175,12 +164,10 @@ class C }; } """); - } [Fact] - public async Task TestSimpleInitialization_SimpleLambda_Block() - { - await TestInRegularAndScript1Async( + public Task TestSimpleInitialization_SimpleLambda_Block() + => TestInRegularAndScript1Async( """ using System; @@ -219,12 +206,10 @@ static int fibonacci(int v) } } """); - } [Fact] - public async Task TestSimpleInitialization_ParenLambdaNoType_Block() - { - await TestInRegularAndScript1Async( + public Task TestSimpleInitialization_ParenLambdaNoType_Block() + => TestInRegularAndScript1Async( """ using System; @@ -263,12 +248,10 @@ static int fibonacci(int v) } } """); - } [Fact] - public async Task TestSimpleInitialization_ParenLambdaWithType_Block() - { - await TestInRegularAndScript1Async( + public Task TestSimpleInitialization_ParenLambdaWithType_Block() + => TestInRegularAndScript1Async( """ using System; @@ -307,12 +290,10 @@ static int fibonacci(int v) } } """); - } [Fact] - public async Task TestSimpleInitialization_AnonymousMethod() - { - await TestInRegularAndScript1Async( + public Task TestSimpleInitialization_AnonymousMethod() + => TestInRegularAndScript1Async( """ using System; @@ -351,12 +332,10 @@ static int fibonacci(int v) } } """); - } [Fact] - public async Task TestSimpleInitialization_SimpleLambda_ExprBody() - { - await TestInRegularAndScript1Async( + public Task TestSimpleInitialization_SimpleLambda_ExprBody() + => TestInRegularAndScript1Async( """ using System; @@ -385,12 +364,10 @@ static int fibonacci(int v) => } } """); - } [Fact] - public async Task TestSimpleInitialization_ParenLambdaNoType_ExprBody() - { - await TestInRegularAndScript1Async( + public Task TestSimpleInitialization_ParenLambdaNoType_ExprBody() + => TestInRegularAndScript1Async( """ using System; @@ -419,12 +396,10 @@ static int fibonacci(int v) => } } """); - } [Fact] - public async Task TestSimpleInitialization_ParenLambdaWithType_ExprBody() - { - await TestInRegularAndScript1Async( + public Task TestSimpleInitialization_ParenLambdaWithType_ExprBody() + => TestInRegularAndScript1Async( """ using System; @@ -453,12 +428,10 @@ static int fibonacci(int v) => } } """); - } [Fact] - public async Task TestCastInitialization_SimpleLambda_Block() - { - await TestInRegularAndScript1Async( + public Task TestCastInitialization_SimpleLambda_Block() + => TestInRegularAndScript1Async( """ using System; @@ -497,12 +470,10 @@ static int fibonacci(int v) } } """); - } [Fact] - public async Task TestCastInitialization_SimpleLambda_Block_ExtraParens() - { - await TestInRegularAndScript1Async( + public Task TestCastInitialization_SimpleLambda_Block_ExtraParens() + => TestInRegularAndScript1Async( """ using System; @@ -541,12 +512,10 @@ static int fibonacci(int v) } } """); - } [Fact] - public async Task TestCastInitialization_ParenLambdaNoType_Block() - { - await TestInRegularAndScript1Async( + public Task TestCastInitialization_ParenLambdaNoType_Block() + => TestInRegularAndScript1Async( """ using System; @@ -585,12 +554,10 @@ static int fibonacci(int v) } } """); - } [Fact] - public async Task TestCastInitialization_ParenLambdaWithType_Block() - { - await TestInRegularAndScript1Async( + public Task TestCastInitialization_ParenLambdaWithType_Block() + => TestInRegularAndScript1Async( """ using System; @@ -629,12 +596,10 @@ static int fibonacci(int v) } } """); - } [Fact] - public async Task TestCastInitialization_AnonymousMethod() - { - await TestInRegularAndScript1Async( + public Task TestCastInitialization_AnonymousMethod() + => TestInRegularAndScript1Async( """ using System; @@ -673,12 +638,10 @@ static int fibonacci(int v) } } """); - } [Fact] - public async Task TestCastInitialization_SimpleLambda_ExprBody() - { - await TestInRegularAndScript1Async( + public Task TestCastInitialization_SimpleLambda_ExprBody() + => TestInRegularAndScript1Async( """ using System; @@ -707,12 +670,10 @@ static int fibonacci(int v) => } } """); - } [Fact] - public async Task TestCastInitialization_ParenLambdaNoType_ExprBody() - { - await TestInRegularAndScript1Async( + public Task TestCastInitialization_ParenLambdaNoType_ExprBody() + => TestInRegularAndScript1Async( """ using System; @@ -741,12 +702,10 @@ static int fibonacci(int v) => } } """); - } [Fact] - public async Task TestCastInitialization_ParenLambdaWithType_ExprBody() - { - await TestInRegularAndScript1Async( + public Task TestCastInitialization_ParenLambdaWithType_ExprBody() + => TestInRegularAndScript1Async( """ using System; @@ -775,12 +734,10 @@ static int fibonacci(int v) => } } """); - } [Fact] - public async Task TestSplitInitialization_WrongName() - { - await TestMissingAsync( + public Task TestSplitInitialization_WrongName() + => TestMissingAsync( """ using System; @@ -801,12 +758,10 @@ void M() } } """); - } [Fact] - public async Task TestSplitInitialization_InitializedToOtherValue() - { - await TestMissingAsync( + public Task TestSplitInitialization_InitializedToOtherValue() + => TestMissingAsync( """ using System; @@ -827,12 +782,10 @@ void M() } } """); - } [Fact] - public async Task TestSplitInitialization_SimpleLambda_Block() - { - await TestInRegularAndScript1Async( + public Task TestSplitInitialization_SimpleLambda_Block() + => TestInRegularAndScript1Async( """ using System; @@ -872,12 +825,10 @@ static int fibonacci(int v) } } """); - } [Fact] - public async Task TestSplitInitialization_SimpleLambda_Block_NoInitializer() - { - await TestInRegularAndScript1Async( + public Task TestSplitInitialization_SimpleLambda_Block_NoInitializer() + => TestInRegularAndScript1Async( """ using System; @@ -917,12 +868,10 @@ static int fibonacci(int v) } } """); - } [Fact] - public async Task TestSplitInitialization_SimpleLambda_Block_DefaultLiteral() - { - await TestInRegularAndScript1Async( + public Task TestSplitInitialization_SimpleLambda_Block_DefaultLiteral() + => TestInRegularAndScript1Async( """ using System; @@ -965,12 +914,10 @@ int fibonacci(int v) // 7.1 is required for default literals, so 7.2 should be sufficient // and is used in other tests new TestParameters(parseOptions: CSharp72ParseOptions)); - } [Fact] - public async Task TestSplitInitialization_SimpleLambda_Block_DefaultExpression() - { - await TestInRegularAndScript1Async( + public Task TestSplitInitialization_SimpleLambda_Block_DefaultExpression() + => TestInRegularAndScript1Async( """ using System; @@ -1010,12 +957,10 @@ static int fibonacci(int v) } } """); - } [Fact] - public async Task TestSplitInitialization_SimpleLambda_Block_DefaultExpression_var() - { - await TestInRegularAndScript1Async( + public Task TestSplitInitialization_SimpleLambda_Block_DefaultExpression_var() + => TestInRegularAndScript1Async( """ using System; @@ -1055,12 +1000,10 @@ static int fibonacci(int v) } } """); - } [Fact] - public async Task TestSplitInitialization_ParenLambdaNoType_Block() - { - await TestInRegularAndScript1Async( + public Task TestSplitInitialization_ParenLambdaNoType_Block() + => TestInRegularAndScript1Async( """ using System; @@ -1100,12 +1043,10 @@ static int fibonacci(int v) } } """); - } [Fact] - public async Task TestSplitInitialization_ParenLambdaWithType_Block() - { - await TestInRegularAndScript1Async( + public Task TestSplitInitialization_ParenLambdaWithType_Block() + => TestInRegularAndScript1Async( """ using System; @@ -1145,12 +1086,10 @@ static int fibonacci(int v) } } """); - } [Fact] - public async Task TestSplitInitialization_AnonymousMethod() - { - await TestInRegularAndScript1Async( + public Task TestSplitInitialization_AnonymousMethod() + => TestInRegularAndScript1Async( """ using System; @@ -1190,12 +1129,10 @@ static int fibonacci(int v) } } """); - } [Fact] - public async Task TestSplitInitialization_SimpleLambda_ExprBody() - { - await TestInRegularAndScript1Async( + public Task TestSplitInitialization_SimpleLambda_ExprBody() + => TestInRegularAndScript1Async( """ using System; @@ -1225,12 +1162,10 @@ static int fibonacci(int v) => } } """); - } [Fact] - public async Task TestSplitInitialization_ParenLambdaNoType_ExprBody() - { - await TestInRegularAndScript1Async( + public Task TestSplitInitialization_ParenLambdaNoType_ExprBody() + => TestInRegularAndScript1Async( """ using System; @@ -1260,12 +1195,10 @@ static int fibonacci(int v) => } } """); - } [Fact] - public async Task TestSplitInitialization_ParenLambdaWithType_ExprBody() - { - await TestInRegularAndScript1Async( + public Task TestSplitInitialization_ParenLambdaWithType_ExprBody() + => TestInRegularAndScript1Async( """ using System; @@ -1295,12 +1228,10 @@ static int fibonacci(int v) => } } """); - } [Fact] - public async Task TestFixAll1() - { - await TestInRegularAndScript1Async( + public Task TestFixAll1() + => TestInRegularAndScript1Async( """ using System; @@ -1333,12 +1264,10 @@ static int fibonacci(int v) } } """); - } [Fact] - public async Task TestFixAll2() - { - await TestInRegularAndScript1Async( + public Task TestFixAll2() + => TestInRegularAndScript1Async( """ using System; @@ -1371,12 +1300,10 @@ static int fibonacci(int v) } } """); - } [Fact] - public async Task TestFixAll3() - { - await TestInRegularAndScript1Async( + public Task TestFixAll3() + => TestInRegularAndScript1Async( """ using System; @@ -1410,12 +1337,10 @@ static int fibonacci(int v) } } """); - } [Fact] - public async Task TestFixAll4() - { - await TestInRegularAndScript1Async( + public Task TestFixAll4() + => TestInRegularAndScript1Async( """ using System; @@ -1449,12 +1374,10 @@ static int fibonacci(int v) } } """); - } [Fact] - public async Task TestTrivia() - { - await TestInRegularAndScript1Async( + public Task TestTrivia() + => TestInRegularAndScript1Async( """ using System; @@ -1495,12 +1418,10 @@ static int fibonacci(int v) } } """); - } [Fact] - public async Task TestInWithParameters() - { - await TestInRegularAndScript1Async( + public Task TestInWithParameters() + => TestInRegularAndScript1Async( """ delegate void D(in int p); class C @@ -1523,12 +1444,10 @@ void M() """, // Run with 7.2 to get read-only references new TestParameters(parseOptions: CSharp72ParseOptions)); - } [Fact] - public async Task TestRefReadOnlyWithReturnType() - { - await TestInRegularAndScript1Async( + public Task TestRefReadOnlyWithReturnType() + => TestInRegularAndScript1Async( """ delegate ref readonly int D(); class C @@ -1549,12 +1468,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23118")] - public async Task TestMissingIfConvertedToNonDelegate() - { - await TestMissingAsync( + public Task TestMissingIfConvertedToNonDelegate() + => TestMissingAsync( """ using System; using System.Threading.Tasks; @@ -1571,12 +1488,10 @@ static void Main(string[] args) public static void AssertSame(object expected, object actual) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23118")] - public async Task TestAvailableIfConvertedToDelegate() - { - await TestInRegularAndScript1Async( + public Task TestAvailableIfConvertedToDelegate() + => TestInRegularAndScript1Async( """ using System; using System.Threading.Tasks; @@ -1609,12 +1524,10 @@ static void Main(string[] args) public static void AssertSame(Func expected, object actual) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23118")] - public async Task TestNotAvailableIfConvertedToSystemDelegate() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotAvailableIfConvertedToSystemDelegate() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1629,12 +1542,10 @@ static void Main(string[] args) public static void M(Delegate expected) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23118")] - public async Task TestNotAvailableIfConvertedToSystemMulticastDelegate() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotAvailableIfConvertedToSystemMulticastDelegate() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1649,12 +1560,10 @@ static void Main(string[] args) public static void M(MulticastDelegate expected) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23118")] - public async Task TestAvailableIfConvertedToCoContraVariantDelegate0() - { - await TestInRegularAndScript1Async( + public Task TestAvailableIfConvertedToCoContraVariantDelegate0() + => TestInRegularAndScript1Async( """ using System; @@ -1683,13 +1592,11 @@ static void Main(string[] args) public static void M(Func expected) { } } """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/56938")] [WorkItem("https://github.com/dotnet/roslyn/issues/23118")] - public async Task TestAvailableIfConvertedToCoContraVariantDelegate1() - { - await TestInRegularAndScript1Async( + public Task TestAvailableIfConvertedToCoContraVariantDelegate1() + => TestInRegularAndScript1Async( """ using System; @@ -1718,13 +1625,11 @@ static void Main(string[] args) public static void M(Func expected) { } } """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/56938")] [WorkItem("https://github.com/dotnet/roslyn/issues/23118")] - public async Task TestAvailableIfConvertedToCoContraVariantDelegate2() - { - await TestInRegularAndScript1Async( + public Task TestAvailableIfConvertedToCoContraVariantDelegate2() + => TestInRegularAndScript1Async( """ using System; @@ -1753,13 +1658,11 @@ static void Main(string[] args) public static void M(Func expected) { } } """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/56938")] [WorkItem("https://github.com/dotnet/roslyn/issues/23118")] - public async Task TestAvailableIfConvertedToCoContraVariantDelegate3() - { - await TestInRegularAndScript1Async( + public Task TestAvailableIfConvertedToCoContraVariantDelegate3() + => TestInRegularAndScript1Async( """ using System; @@ -1788,12 +1691,10 @@ static void Main(string[] args) public static void M(Func expected) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22672")] - public async Task TestMissingIfAdded() - { - await TestMissingAsync( + public Task TestMissingIfAdded() + => TestMissingAsync( """ using System; using System.Linq.Expressions; @@ -1813,12 +1714,10 @@ public void Caller() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22672")] - public async Task TestMissingIfUsedInMemberAccess1() - { - await TestMissingAsync( + public Task TestMissingIfUsedInMemberAccess1() + => TestMissingAsync( """ using System; @@ -1837,12 +1736,10 @@ public void Caller() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23150")] - public async Task TestMissingIfUsedInMemberAccess2() - { - await TestMissingAsync( + public Task TestMissingIfUsedInMemberAccess2() + => TestMissingAsync( """ using System; @@ -1864,12 +1761,10 @@ public void Caller(T t) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22672")] - public async Task TestMissingIfUsedInExpressionTree() - { - await TestMissingAsync( + public Task TestMissingIfUsedInExpressionTree() + => TestMissingAsync( """ using System; using System.Linq.Expressions; @@ -1889,12 +1784,10 @@ public void Caller() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24344")] - public async Task TestMissingIfUsedInExpressionTree2() - { - await TestMissingAsync( + public Task TestMissingIfUsedInExpressionTree2() + => TestMissingAsync( """ using System; using System.Linq.Expressions; @@ -1910,12 +1803,10 @@ Expression Example() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23150")] - public async Task TestWithInvokeMethod1() - { - await TestInRegularAndScript1Async( + public Task TestWithInvokeMethod1() + => TestInRegularAndScript1Async( """ using System; @@ -1952,12 +1843,10 @@ public void Caller() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23150")] - public async Task TestWithInvokeMethod2() - { - await TestInRegularAndScript1Async( + public Task TestWithInvokeMethod2() + => TestInRegularAndScript1Async( """ using System; @@ -1994,12 +1883,10 @@ public void Caller(T t) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23150")] - public async Task TestWithInvokeMethod3() - { - await TestInRegularAndScript1Async( + public Task TestWithInvokeMethod3() + => TestInRegularAndScript1Async( """ using System; @@ -2042,12 +1929,10 @@ public void Caller(T t) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23150")] - public async Task TestWithInvokeMethod4() - { - await TestInRegularAndScript1Async( + public Task TestWithInvokeMethod4() + => TestInRegularAndScript1Async( """ using System; @@ -2090,12 +1975,10 @@ public void Caller(T t) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24760#issuecomment-364807853")] - public async Task TestWithRecursiveInvokeMethod1() - { - await TestInRegularAndScript1Async( + public Task TestWithRecursiveInvokeMethod1() + => TestInRegularAndScript1Async( """ using System; @@ -2119,12 +2002,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24760#issuecomment-364807853")] - public async Task TestWithRecursiveInvokeMethod2() - { - await TestInRegularAndScript1Async( + public Task TestWithRecursiveInvokeMethod2() + => TestInRegularAndScript1Async( """ using System; @@ -2148,12 +2029,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24760#issuecomment-364935495")] - public async Task TestWithNestedInvokeMethod() - { - await TestInRegularAndScript1Async( + public Task TestWithNestedInvokeMethod() + => TestInRegularAndScript1Async( """ using System; @@ -2178,12 +2057,10 @@ void M() } } """); - } [Fact] - public async Task TestWithNestedRecursiveInvokeMethod() - { - await TestInRegularAndScript1Async( + public Task TestWithNestedRecursiveInvokeMethod() + => TestInRegularAndScript1Async( """ using System; @@ -2207,12 +2084,10 @@ void M() } } """); - } [Fact] - public async Task TestWithDefaultParameter1() - { - await TestInRegularAndScript1Async( + public Task TestWithDefaultParameter1() + => TestInRegularAndScript1Async( """ class C { @@ -2235,12 +2110,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24760#issuecomment-364655480")] - public async Task TestWithDefaultParameter2() - { - await TestInRegularAndScript1Async( + public Task TestWithDefaultParameter2() + => TestInRegularAndScript1Async( """ class C { @@ -2263,12 +2136,10 @@ void M() } } """); - } [Fact] - public async Task TestWithDefaultParameter3() - { - await TestInRegularAndScript1Async( + public Task TestWithDefaultParameter3() + => TestInRegularAndScript1Async( """ class C { @@ -2291,12 +2162,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24760#issuecomment-364764542")] - public async Task TestWithUnmatchingParameterList1() - { - await TestInRegularAndScript1Async( + public Task TestWithUnmatchingParameterList1() + => TestInRegularAndScript1Async( """ using System; @@ -2319,12 +2188,10 @@ static void x(object a, object b) { } } } """); - } [Fact] - public async Task TestWithUnmatchingParameterList2() - { - await TestInRegularAndScript1Async( + public Task TestWithUnmatchingParameterList2() + => TestInRegularAndScript1Async( """ using System; @@ -2347,12 +2214,10 @@ static void x(string a, int b) { } } } """); - } [Fact] - public async Task TestWithAsyncLambdaExpression() - { - await TestInRegularAndScript1Async( + public Task TestWithAsyncLambdaExpression() + => TestInRegularAndScript1Async( """ using System; using System.Threading.Tasks; @@ -2377,12 +2242,10 @@ void M() } } """); - } [Fact] - public async Task TestWithAsyncAnonymousMethod() - { - await TestInRegularAndScript1Async( + public Task TestWithAsyncAnonymousMethod() + => TestInRegularAndScript1Async( """ using System; using System.Threading.Tasks; @@ -2407,12 +2270,10 @@ void M() } } """); - } [Fact] - public async Task TestWithParameterlessAnonymousMethod() - { - await TestInRegularAndScript1Async( + public Task TestWithParameterlessAnonymousMethod() + => TestInRegularAndScript1Async( """ using System; @@ -2443,12 +2304,10 @@ static void handler(object sender, EventArgs e) { } event EventHandler E; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24764")] - public async Task TestWithNamedArguments1() - { - await TestInRegularAndScript1Async( + public Task TestWithNamedArguments1() + => TestInRegularAndScript1Async( """ using System; @@ -2477,12 +2336,10 @@ static void x(string a1, int a2, int a3) { } } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24764")] - public async Task TestWithNamedArguments2() - { - await TestInRegularAndScript1Async( + public Task TestWithNamedArguments2() + => TestInRegularAndScript1Async( """ using System; @@ -2513,12 +2370,10 @@ static void x(string a1, int a2, int a3) } } """); - } [Fact] - public async Task TestWithNamedArgumentsAndBrokenCode1() - { - await TestInRegularAndScript1Async( + public Task TestWithNamedArgumentsAndBrokenCode1() + => TestInRegularAndScript1Async( """ using System; @@ -2549,12 +2404,10 @@ static void x(int a1, string a2, string a3, object a4) { } } } """); - } [Fact] - public async Task TestWithNamedArgumentsAndBrokenCode2() - { - await TestInRegularAndScript1Async( + public Task TestWithNamedArgumentsAndBrokenCode2() + => TestInRegularAndScript1Async( """ using System; @@ -2587,12 +2440,10 @@ static void x(string a1, int a2) } } """); - } [Fact] - public async Task TestWithNamedAndDefaultArguments() - { - await TestInRegularAndScript1Async( + public Task TestWithNamedAndDefaultArguments() + => TestInRegularAndScript1Async( """ class C { @@ -2624,12 +2475,10 @@ static string x(string a1, int a2 = 2, int a3 = 3) } } """); - } [Fact] - public async Task TestWithNamedAndDefaultArgumentsAndNestedRecursiveInvocations_FixAll() - { - await TestInRegularAndScript1Async( + public Task TestWithNamedAndDefaultArgumentsAndNestedRecursiveInvocations_FixAll() + => TestInRegularAndScript1Async( """ class C { @@ -2681,12 +2530,10 @@ string b(string b1, int b2 = 2, int b3 = 3) => } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23872")] - public async Task TestSimpleInitialization_SingleLine1() - { - await TestInRegularAndScript1Async( + public Task TestSimpleInitialization_SingleLine1() + => TestInRegularAndScript1Async( """ using System; class C @@ -2709,12 +2556,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23872")] - public async Task TestSimpleInitialization_SingleLine2() - { - await TestInRegularAndScript1Async( + public Task TestSimpleInitialization_SingleLine2() + => TestInRegularAndScript1Async( """ using System; class C @@ -2737,12 +2582,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23872")] - public async Task TestSimpleInitialization_SingleLine2Async() - { - await TestInRegularAndScript1Async( + public Task TestSimpleInitialization_SingleLine2Async() + => TestInRegularAndScript1Async( """ using System; class C @@ -2765,12 +2608,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23872")] - public async Task TestSimpleInitialization_SingleLine2MultiToken() - { - await TestInRegularAndScript1Async( + public Task TestSimpleInitialization_SingleLine2MultiToken() + => TestInRegularAndScript1Async( """ using System; class C @@ -2791,12 +2632,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23872")] - public async Task TestSimpleInitialization_SingleLine2MultiTokenAsync() - { - await TestInRegularAndScript1Async( + public Task TestSimpleInitialization_SingleLine2MultiTokenAsync() + => TestInRegularAndScript1Async( """ using System; using System.Threading.Tasks; @@ -2819,12 +2658,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23872")] - public async Task TestSimpleInitialization_SingleLine3() - { - await TestInRegularAndScript1Async( + public Task TestSimpleInitialization_SingleLine3() + => TestInRegularAndScript1Async( """ using System; class C @@ -2847,12 +2684,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23872")] - public async Task TestSimpleInitialization_SingleLine4() - { - await TestInRegularAndScript1Async( + public Task TestSimpleInitialization_SingleLine4() + => TestInRegularAndScript1Async( """ using System; class C @@ -2875,12 +2710,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23872")] - public async Task TestSimpleInitialization_SingleLine4Async() - { - await TestInRegularAndScript1Async( + public Task TestSimpleInitialization_SingleLine4Async() + => TestInRegularAndScript1Async( """ using System; class C @@ -2903,12 +2736,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23872")] - public async Task TestCastInitialization_SingleLine1() - { - await TestInRegularAndScript1Async( + public Task TestCastInitialization_SingleLine1() + => TestInRegularAndScript1Async( """ using System; class C @@ -2931,12 +2762,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23872")] - public async Task TestCastInitialization_SingleLine2() - { - await TestInRegularAndScript1Async( + public Task TestCastInitialization_SingleLine2() + => TestInRegularAndScript1Async( """ using System; class C @@ -2959,12 +2788,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23872")] - public async Task TestCastInitialization_SingleLine2Async() - { - await TestInRegularAndScript1Async( + public Task TestCastInitialization_SingleLine2Async() + => TestInRegularAndScript1Async( """ using System; class C @@ -2987,12 +2814,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23872")] - public async Task TestCastInitialization_SingleLine3() - { - await TestInRegularAndScript1Async( + public Task TestCastInitialization_SingleLine3() + => TestInRegularAndScript1Async( """ using System; class C @@ -3015,12 +2840,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23872")] - public async Task TestCastInitialization_SingleLine4() - { - await TestInRegularAndScript1Async( + public Task TestCastInitialization_SingleLine4() + => TestInRegularAndScript1Async( """ using System; class C @@ -3043,12 +2866,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23872")] - public async Task TestCastInitialization_SingleLine4Async() - { - await TestInRegularAndScript1Async( + public Task TestCastInitialization_SingleLine4Async() + => TestInRegularAndScript1Async( """ using System; class C @@ -3071,12 +2892,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23872")] - public async Task TestSplitInitialization_SingleLine1() - { - await TestInRegularAndScript1Async( + public Task TestSplitInitialization_SingleLine1() + => TestInRegularAndScript1Async( """ using System; class C @@ -3100,12 +2919,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23872")] - public async Task TestSplitInitialization_SingleLine2() - { - await TestInRegularAndScript1Async( + public Task TestSplitInitialization_SingleLine2() + => TestInRegularAndScript1Async( """ using System; class C @@ -3129,12 +2946,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23872")] - public async Task TestSplitInitialization_SingleLine2Async() - { - await TestInRegularAndScript1Async( + public Task TestSplitInitialization_SingleLine2Async() + => TestInRegularAndScript1Async( """ using System; class C @@ -3158,12 +2973,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23872")] - public async Task TestSplitInitialization_SingleLine3() - { - await TestInRegularAndScript1Async( + public Task TestSplitInitialization_SingleLine3() + => TestInRegularAndScript1Async( """ using System; class C @@ -3187,12 +3000,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23872")] - public async Task TestSplitInitialization_SingleLine4() - { - await TestInRegularAndScript1Async( + public Task TestSplitInitialization_SingleLine4() + => TestInRegularAndScript1Async( """ using System; class C @@ -3216,12 +3027,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23872")] - public async Task TestSplitInitialization_SingleLine4Async() - { - await TestInRegularAndScript1Async( + public Task TestSplitInitialization_SingleLine4Async() + => TestInRegularAndScript1Async( """ using System; class C @@ -3245,12 +3054,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23149")] - public async Task TestNotAvailableIfTypeParameterChanged1() - { - await TestMissingAsync( + public Task TestNotAvailableIfTypeParameterChanged1() + => TestMissingAsync( """ using System; @@ -3269,12 +3076,10 @@ public void Caller() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23149")] - public async Task TestNotAvailableIfTypeParameterChanged2() - { - await TestMissingAsync( + public Task TestNotAvailableIfTypeParameterChanged2() + => TestMissingAsync( """ using System; @@ -3296,12 +3101,10 @@ public void Caller() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23149")] - public async Task TestNotAvailableIfTypeParameterChanged3() - { - await TestMissingAsync( + public Task TestNotAvailableIfTypeParameterChanged3() + => TestMissingAsync( """ public class Class { @@ -3318,12 +3121,10 @@ void Some(T t) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23149")] - public async Task TestNotAvailableIfTypeParameterChanged4() - { - await TestMissingAsync( + public Task TestNotAvailableIfTypeParameterChanged4() + => TestMissingAsync( """ using System; @@ -3345,13 +3146,11 @@ public void Caller() } } """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/27950")] [WorkItem("https://github.com/dotnet/roslyn/issues/23149")] - public async Task TestAvailableIfTypeParameterNotChanged1() - { - await TestInRegularAndScript1Async( + public Task TestAvailableIfTypeParameterNotChanged1() + => TestInRegularAndScript1Async( """ using System; @@ -3390,12 +3189,10 @@ public void Caller() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23149")] - public async Task TestAvailableIfTypeParameterNotChanged2() - { - await TestInRegularAndScript1Async( + public Task TestAvailableIfTypeParameterNotChanged2() + => TestInRegularAndScript1Async( """ using System; @@ -3434,13 +3231,11 @@ public void Caller() } } """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/56963")] [WorkItem("https://github.com/dotnet/roslyn/issues/26526")] - public async Task TestAvailableWithCastIntroducedIfAssignedToVar() - { - await TestInRegularAndScript1Async( + public Task TestAvailableWithCastIntroducedIfAssignedToVar() + => TestInRegularAndScript1Async( """ using System; @@ -3467,12 +3262,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26526")] - public async Task TestAvailableWithCastIntroducedForGenericTypeInference1() - { - await TestInRegularAndScript1Async( + public Task TestAvailableWithCastIntroducedForGenericTypeInference1() + => TestInRegularAndScript1Async( """ using System; @@ -3507,12 +3300,10 @@ void Method(Func o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26526")] - public async Task TestAvailableWithCastIntroducedForGenericTypeInference2() - { - await TestInRegularAndScript1Async( + public Task TestAvailableWithCastIntroducedForGenericTypeInference2() + => TestInRegularAndScript1Async( """ using System; @@ -3555,12 +3346,10 @@ void Method(string o) } } """); - } [Fact] - public async Task TestAvailableWithCastIntroducedForOverloadResolution() - { - await TestInRegularAndScript1Async( + public Task TestAvailableWithCastIntroducedForOverloadResolution() + => TestInRegularAndScript1Async( """ using System; @@ -3607,12 +3396,10 @@ void Method(CustomDelegate o) } } """); - } [Fact] - public async Task TestAvailableWithoutCastIfUnnecessaryForOverloadResolution() - { - await TestInRegularAndScript1Async( + public Task TestAvailableWithoutCastIfUnnecessaryForOverloadResolution() + => TestInRegularAndScript1Async( """ using System; @@ -3659,12 +3446,10 @@ void Method(CustomDelegate o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29793")] - public async Task TestNotAvailableWithInvalidDeclaration() - { - await TestMissingAsync( + public Task TestNotAvailableWithInvalidDeclaration() + => TestMissingAsync( """ using System; @@ -3682,12 +3467,10 @@ void Method(Func o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29793")] - public async Task TestNotAvailableWithInvalidDeclaration2() - { - await TestMissingAsync( + public Task TestNotAvailableWithInvalidDeclaration2() + => TestMissingAsync( """ using System; @@ -3705,12 +3488,10 @@ void Method(Func o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29793")] - public async Task TestNotAvailableWithInvalidDeclaration3() - { - await TestMissingAsync( + public Task TestNotAvailableWithInvalidDeclaration3() + => TestMissingAsync( """ using System; @@ -3728,12 +3509,10 @@ void Method(Func o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29793")] - public async Task TestWithInvalidUnrelatedCode() - { - await TestInRegularAndScript1Async( + public Task TestWithInvalidUnrelatedCode() + => TestInRegularAndScript1Async( """ using System; @@ -3768,12 +3547,10 @@ void Method(Func o)) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29793")] - public async Task TestWithInvalidUnrelatedCode2() - { - await TestInRegularAndScript1Async( + public Task TestWithInvalidUnrelatedCode2() + => TestInRegularAndScript1Async( """ using System; @@ -3808,12 +3585,10 @@ void Method(Func o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29793")] - public async Task TestWithObsoleteCode() - { - await TestInRegularAndScript1Async( + public Task TestWithObsoleteCode() + => TestInRegularAndScript1Async( """ using System; @@ -3860,12 +3635,10 @@ void Method(Func o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29793")] - public async Task TestWithDeclarationWarning() - { - await TestInRegularAndScript1Async( + public Task TestWithDeclarationWarning() + => TestInRegularAndScript1Async( """ using System; @@ -3902,12 +3675,10 @@ void Method(Func o) } } """); - } [Fact] - public async Task TestMakeStaticIfNoCaptures() - { - await TestInRegularAndScript1Async( + public Task TestMakeStaticIfNoCaptures() + => TestInRegularAndScript1Async( """ using System; @@ -3946,12 +3717,10 @@ static int fibonacci(int v) } } """); - } [Fact] - public async Task TestDoNotMakeStaticIfCaptures() - { - await TestInRegularAndScript1Async( + public Task TestDoNotMakeStaticIfCaptures() + => TestInRegularAndScript1Async( """ using System; @@ -3992,12 +3761,10 @@ int fibonacci(int v) } } """); - } [Fact] - public async Task TestWithAsyncLambdaExpression_MakeStatic() - { - await TestInRegularAndScript1Async( + public Task TestWithAsyncLambdaExpression_MakeStatic() + => TestInRegularAndScript1Async( """ using System; using System.Threading.Tasks; @@ -4022,12 +3789,10 @@ void M() } } """); - } [Fact] - public async Task TestWithNullableParameterAndReturn() - { - await TestInRegularAndScript1Async( + public Task TestWithNullableParameterAndReturn() + => TestInRegularAndScript1Async( """ #nullable enable @@ -4054,12 +3819,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestWithDiscardParameters() - { - await TestInRegularAndScript1Async( + public Task TestWithDiscardParameters() + => TestInRegularAndScript1Async( """ class Program { @@ -4078,12 +3841,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestWithOptionalParameter() - { - await TestInRegularAndScript1Async( + public Task TestWithOptionalParameter() + => TestInRegularAndScript1Async( """ class Program { @@ -4108,12 +3869,10 @@ static int fibonacci(int n = 1) } } """); - } [Fact] - public async Task TestWithParamsArray() - { - await TestInRegularAndScript1Async( + public Task TestWithParamsArray() + => TestInRegularAndScript1Async( """ class Program { @@ -4138,12 +3897,10 @@ static int last(params int[] xs) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68439")] - public async Task TestImplicitlyTypedLambdaCSharp10() - { - await TestInRegularAndScriptAsync( + public Task TestImplicitlyTypedLambdaCSharp10() + => TestInRegularAndScriptAsync( """ class Program { @@ -4163,12 +3920,10 @@ static void Main() } """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68439")] - public async Task TestImplicitlyTypedLambdaCSharp9() - { - await TestMissingInRegularAndScriptAsync( + public Task TestImplicitlyTypedLambdaCSharp9() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -4179,5 +3934,4 @@ static void Main() } """, new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9))); - } } diff --git a/src/Analyzers/CSharp/Tests/UseNullPropagation/UseNullPropagationTests.cs b/src/Analyzers/CSharp/Tests/UseNullPropagation/UseNullPropagationTests.cs index f58110404e1af..175f952005d1c 100644 --- a/src/Analyzers/CSharp/Tests/UseNullPropagation/UseNullPropagationTests.cs +++ b/src/Analyzers/CSharp/Tests/UseNullPropagation/UseNullPropagationTests.cs @@ -5,7 +5,6 @@ using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Shared.Extensions; using Microsoft.CodeAnalysis.CSharp.UseNullPropagation; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; @@ -23,13 +22,12 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseNullPropagation; [Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)] public sealed partial class UseNullPropagationTests { - private static async Task TestInRegularAndScript1Async( + private static Task TestInRegularAndScript1Async( [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string testCode, [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string fixedCode, OutputKind outputKind = OutputKind.DynamicallyLinkedLibrary, LanguageVersion languageVersion = LanguageVersion.CSharp9) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, @@ -43,23 +41,19 @@ private static async Task TestInRegularAndScript1Async( OutputKind = outputKind, }, }.RunAsync(); - } - private static async Task TestMissingInRegularAndScriptAsync( + private static Task TestMissingInRegularAndScriptAsync( [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string testCode, LanguageVersion languageVersion = LanguageVersion.CSharp9) - { - await new VerifyCS.Test + => new VerifyCS.Test { TestCode = testCode, LanguageVersion = languageVersion, }.RunAsync(); - } [Fact] - public async Task TestLeft_Equals() - { - await TestInRegularAndScript1Async( + public Task TestLeft_Equals() + => TestInRegularAndScript1Async( """ using System; @@ -82,12 +76,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestLeft_Equals_IfStatement() - { - await TestInRegularAndScript1Async( + public Task TestLeft_Equals_IfStatement() + => TestInRegularAndScript1Async( """ using System; @@ -111,12 +103,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestIfStatement_WithBlock() - { - await TestInRegularAndScript1Async( + public Task TestIfStatement_WithBlock() + => TestInRegularAndScript1Async( """ using System; @@ -142,12 +132,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestIfStatement_NotWithElse() - { - await TestMissingInRegularAndScriptAsync( + public Task TestIfStatement_NotWithElse() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -163,12 +151,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestIfStatement_NotWithMultipleStatements() - { - await TestMissingInRegularAndScriptAsync( + public Task TestIfStatement_NotWithMultipleStatements() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -184,12 +170,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestLeft_Equals_IfStatement_TopLevel() - { - await TestInRegularAndScript1Async( + public Task TestLeft_Equals_IfStatement_TopLevel() + => TestInRegularAndScript1Async( """ using System; @@ -203,12 +187,10 @@ await TestInRegularAndScript1Async( object o = null; o?.ToString(); """, OutputKind.ConsoleApplication); - } [Fact] - public async Task TestLeft_IsNull() - { - await TestInRegularAndScript1Async( + public Task TestLeft_IsNull() + => TestInRegularAndScript1Async( """ using System; @@ -231,12 +213,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestLeft_IsNotNull() - { - await TestInRegularAndScript1Async( + public Task TestLeft_IsNotNull() + => TestInRegularAndScript1Async( """ using System; @@ -259,12 +239,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestLeft_IsNotNull_IfStatement() - { - await TestInRegularAndScript1Async( + public Task TestLeft_IsNotNull_IfStatement() + => TestInRegularAndScript1Async( """ using System; @@ -288,12 +266,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestMissingOnCSharp5() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnCSharp5() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -305,12 +281,10 @@ void M(object o) } } """, LanguageVersion.CSharp5); - } [Fact] - public async Task TestMissingOnCSharp5_IfStatement() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnCSharp5_IfStatement() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -323,12 +297,10 @@ void M(object o) } } """, LanguageVersion.CSharp5); - } [Fact] - public async Task TestRight_Equals() - { - await TestInRegularAndScript1Async( + public Task TestRight_Equals() + => TestInRegularAndScript1Async( """ using System; @@ -351,12 +323,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestRight_Equals_IfStatement() - { - await TestInRegularAndScript1Async( + public Task TestRight_Equals_IfStatement() + => TestInRegularAndScript1Async( """ using System; @@ -380,12 +350,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestLeft_NotEquals() - { - await TestInRegularAndScript1Async( + public Task TestLeft_NotEquals() + => TestInRegularAndScript1Async( """ using System; @@ -408,12 +376,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestWithNullableType() - { - await TestInRegularAndScript1Async( + public Task TestWithNullableType() + => TestInRegularAndScript1Async( """ class C { @@ -434,12 +400,10 @@ void M(C c) } } """); - } [Fact] - public async Task TestWithNullableType_IfStatement() - { - await TestInRegularAndScript1Async( + public Task TestWithNullableType_IfStatement() + => TestInRegularAndScript1Async( """ class C { @@ -461,12 +425,10 @@ void M(C c) } } """); - } [Fact] - public async Task TestWithNullableTypeAndObjectCast() - { - await TestInRegularAndScript1Async( + public Task TestWithNullableTypeAndObjectCast() + => TestInRegularAndScript1Async( """ class C { @@ -487,12 +449,10 @@ void M(C c) } } """); - } [Fact] - public async Task TestWithNullableTypeAndObjectCast_IfStatement() - { - await TestInRegularAndScript1Async( + public Task TestWithNullableTypeAndObjectCast_IfStatement() + => TestInRegularAndScript1Async( """ class C { @@ -514,12 +474,10 @@ void M(C c) } } """); - } [Fact] - public async Task TestRight_NotEquals() - { - await TestInRegularAndScript1Async( + public Task TestRight_NotEquals() + => TestInRegularAndScript1Async( """ using System; @@ -542,12 +500,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestIndexer() - { - await TestInRegularAndScript1Async( + public Task TestIndexer() + => TestInRegularAndScript1Async( """ using System; @@ -570,12 +526,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestIndexer_IfStatement() - { - await TestInRegularAndScript1Async( + public Task TestIndexer_IfStatement() + => TestInRegularAndScript1Async( """ using System; @@ -599,12 +553,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestConditionalAccess() - { - await TestInRegularAndScript1Async( + public Task TestConditionalAccess() + => TestInRegularAndScript1Async( """ using System; @@ -627,12 +579,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestConditionalAccess_IfStatement() - { - await TestInRegularAndScript1Async( + public Task TestConditionalAccess_IfStatement() + => TestInRegularAndScript1Async( """ using System; @@ -656,12 +606,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestMemberAccess() - { - await TestInRegularAndScript1Async( + public Task TestMemberAccess() + => TestInRegularAndScript1Async( """ using System; @@ -684,12 +632,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestMemberAccess_IfStatement() - { - await TestInRegularAndScript1Async( + public Task TestMemberAccess_IfStatement() + => TestInRegularAndScript1Async( """ using System; @@ -713,12 +659,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestMissingOnSimpleMatch() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnSimpleMatch() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -730,12 +674,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestMissingOnSimpleMatch_IfStatement() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnSimpleMatch_IfStatement() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -748,12 +690,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestParenthesizedCondition() - { - await TestInRegularAndScript1Async( + public Task TestParenthesizedCondition() + => TestInRegularAndScript1Async( """ using System; @@ -776,12 +716,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestFixAll1() - { - await TestInRegularAndScript1Async( + public Task TestFixAll1() + => TestInRegularAndScript1Async( """ using System; @@ -806,12 +744,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestFixAll2() - { - await TestInRegularAndScript1Async( + public Task TestFixAll2() + => TestInRegularAndScript1Async( """ using System; @@ -834,12 +770,10 @@ void M(object o1, object o2) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15505")] - public async Task TestOtherValueIsNotNull1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestOtherValueIsNotNull1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -851,12 +785,10 @@ void M(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15505")] - public async Task TestOtherValueIsNotNull2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestOtherValueIsNotNull2() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -868,12 +800,10 @@ void M(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16287")] - public async Task TestMethodGroup() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMethodGroup() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -887,12 +817,10 @@ void Goo() } class C { public void M(string s) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17623")] - public async Task TestInExpressionTree() - { - await TestMissingInRegularAndScriptAsync( + public Task TestInExpressionTree() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Linq.Expressions; @@ -909,13 +837,11 @@ public void Method(Expression> functor) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17623")] [WorkItem("https://github.com/dotnet/roslyn/issues/33992")] - public async Task TestInExpressionTree2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestInExpressionTree2() + => TestMissingInRegularAndScriptAsync( """ using System.Linq; @@ -928,13 +854,11 @@ void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17623")] [WorkItem("https://github.com/dotnet/roslyn/issues/33992")] - public async Task TestInExpressionTree3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestInExpressionTree3() + => TestMissingInRegularAndScriptAsync( """ using System.Linq; @@ -948,13 +872,11 @@ void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17623")] [WorkItem("https://github.com/dotnet/roslyn/issues/33992")] - public async Task TestInExpressionTree4() - { - await TestMissingInRegularAndScriptAsync( + public Task TestInExpressionTree4() + => TestMissingInRegularAndScriptAsync( """ using System.Linq; @@ -968,12 +890,10 @@ void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19774")] - public async Task TestNullableMemberAccess() - { - await TestInRegularAndScript1Async( + public Task TestNullableMemberAccess() + => TestInRegularAndScript1Async( """ using System; @@ -997,12 +917,10 @@ void Main(DateTime? toDate) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19774")] - public async Task TestNullableMemberAccess_IfStatement() - { - await TestInRegularAndScript1Async( + public Task TestNullableMemberAccess_IfStatement() + => TestInRegularAndScript1Async( """ using System; @@ -1027,12 +945,10 @@ void Main(DateTime? toDate) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19774")] - public async Task TestNullableElementAccess() - { - await TestInRegularAndScript1Async( + public Task TestNullableElementAccess() + => TestInRegularAndScript1Async( """ using System; @@ -1066,12 +982,10 @@ void Main(S? s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndIsNull() - { - await TestInRegularAndScript1Async( + public Task TestWithNullableTypeAndIsNull() + => TestInRegularAndScript1Async( """ class C { @@ -1092,12 +1006,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndIsNotNull() - { - await TestInRegularAndScript1Async( + public Task TestWithNullableTypeAndIsNotNull() + => TestInRegularAndScript1Async( """ class C { @@ -1118,12 +1030,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndIsNotNull_IfStatement() - { - await TestInRegularAndScript1Async( + public Task TestWithNullableTypeAndIsNotNull_IfStatement() + => TestInRegularAndScript1Async( """ class C { @@ -1145,12 +1055,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndIsType() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithNullableTypeAndIsType() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1161,12 +1069,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndIsType_IfStatement1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithNullableTypeAndIsType_IfStatement1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1178,12 +1084,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndIsType_IfStatement2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithNullableTypeAndIsType_IfStatement2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1195,12 +1099,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndIsType_IfStatement3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithNullableTypeAndIsType_IfStatement3() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1212,12 +1114,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestIsOtherConstant() - { - await TestMissingInRegularAndScriptAsync( + public Task TestIsOtherConstant() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1227,12 +1127,10 @@ void M(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndReferenceEquals1() - { - await TestInRegularAndScript1Async( + public Task TestWithNullableTypeAndReferenceEquals1() + => TestInRegularAndScript1Async( """ class C { @@ -1253,12 +1151,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndReferenceEquals1_IfStatement() - { - await TestInRegularAndScript1Async( + public Task TestWithNullableTypeAndReferenceEquals1_IfStatement() + => TestInRegularAndScript1Async( """ class C { @@ -1280,12 +1176,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndReferenceEquals2() - { - await TestInRegularAndScript1Async( + public Task TestWithNullableTypeAndReferenceEquals2() + => TestInRegularAndScript1Async( """ class C { @@ -1306,12 +1200,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndReferenceEquals2_IfStatement() - { - await TestInRegularAndScript1Async( + public Task TestWithNullableTypeAndReferenceEquals2_IfStatement() + => TestInRegularAndScript1Async( """ class C { @@ -1333,12 +1225,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndReferenceEqualsOtherValue1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithNullableTypeAndReferenceEqualsOtherValue1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1349,12 +1239,10 @@ void M(C c, C other) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndReferenceEqualsOtherValue1_IfStatement1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithNullableTypeAndReferenceEqualsOtherValue1_IfStatement1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1366,12 +1254,10 @@ void M(C c, C other) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndReferenceEqualsOtherValue1_IfStatement2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithNullableTypeAndReferenceEqualsOtherValue1_IfStatement2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1383,12 +1269,10 @@ void M(C c, C other) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndReferenceEqualsOtherValue2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithNullableTypeAndReferenceEqualsOtherValue2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1399,12 +1283,10 @@ void M(C c, C other) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndReferenceEqualsWithObject1() - { - await TestInRegularAndScript1Async( + public Task TestWithNullableTypeAndReferenceEqualsWithObject1() + => TestInRegularAndScript1Async( """ class C { @@ -1425,12 +1307,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndReferenceEqualsWithObject1_IfStatement() - { - await TestInRegularAndScript1Async( + public Task TestWithNullableTypeAndReferenceEqualsWithObject1_IfStatement() + => TestInRegularAndScript1Async( """ class C { @@ -1452,12 +1332,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndReferenceEqualsWithObject2() - { - await TestInRegularAndScript1Async( + public Task TestWithNullableTypeAndReferenceEqualsWithObject2() + => TestInRegularAndScript1Async( """ class C { @@ -1478,12 +1356,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndReferenceEqualsWithObject2_IfStatement() - { - await TestInRegularAndScript1Async( + public Task TestWithNullableTypeAndReferenceEqualsWithObject2_IfStatement() + => TestInRegularAndScript1Async( """ class C { @@ -1505,12 +1381,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndReferenceEqualsOtherValueWithObject1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithNullableTypeAndReferenceEqualsOtherValueWithObject1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1521,12 +1395,10 @@ void M(C c, C other) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndReferenceEqualsOtherValueWithObject2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithNullableTypeAndReferenceEqualsOtherValueWithObject2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1537,12 +1409,10 @@ void M(C c, C other) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndNotIsNull() - { - await TestInRegularAndScript1Async( + public Task TestWithNullableTypeAndNotIsNull() + => TestInRegularAndScript1Async( """ class C { @@ -1563,12 +1433,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndNotIsNotNull() - { - await TestInRegularAndScript1Async( + public Task TestWithNullableTypeAndNotIsNotNull() + => TestInRegularAndScript1Async( """ class C { @@ -1589,12 +1457,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndNotIsType() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithNullableTypeAndNotIsType() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1605,12 +1471,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndNotIsOtherConstant() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithNullableTypeAndNotIsOtherConstant() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1620,12 +1484,10 @@ void M(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndLogicalNotReferenceEquals1() - { - await TestInRegularAndScript1Async( + public Task TestWithNullableTypeAndLogicalNotReferenceEquals1() + => TestInRegularAndScript1Async( """ class C { @@ -1646,12 +1508,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndLogicalNotReferenceEquals2() - { - await TestInRegularAndScript1Async( + public Task TestWithNullableTypeAndLogicalNotReferenceEquals2() + => TestInRegularAndScript1Async( """ class C { @@ -1672,12 +1532,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndLogicalNotReferenceEqualsOtherValue1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithNullableTypeAndLogicalNotReferenceEqualsOtherValue1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1688,12 +1546,10 @@ void M(C c, C other) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndLogicalNotReferenceEqualsOtherValue2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithNullableTypeAndLogicalNotReferenceEqualsOtherValue2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1704,12 +1560,10 @@ void M(C c, C other) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndLogicalNotReferenceEqualsWithObject1() - { - await TestInRegularAndScript1Async( + public Task TestWithNullableTypeAndLogicalNotReferenceEqualsWithObject1() + => TestInRegularAndScript1Async( """ class C { @@ -1730,12 +1584,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndLogicalNotReferenceEqualsWithObject2() - { - await TestInRegularAndScript1Async( + public Task TestWithNullableTypeAndLogicalNotReferenceEqualsWithObject2() + => TestInRegularAndScript1Async( """ class C { @@ -1756,12 +1608,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndLogicalNotReferenceEqualsOtherValueWithObject1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithNullableTypeAndLogicalNotReferenceEqualsOtherValueWithObject1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1772,12 +1622,10 @@ void M(C c, C other) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestWithNullableTypeAndLogicalNotReferenceEqualsOtherValueWithObject2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithNullableTypeAndLogicalNotReferenceEqualsOtherValueWithObject2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1788,12 +1636,10 @@ void M(C c, C other) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestEqualsWithLogicalNot() - { - await TestInRegularAndScript1Async( + public Task TestEqualsWithLogicalNot() + => TestInRegularAndScript1Async( """ class C { @@ -1814,12 +1660,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestEqualsWithLogicalNot_IfStatement() - { - await TestInRegularAndScript1Async( + public Task TestEqualsWithLogicalNot_IfStatement() + => TestInRegularAndScript1Async( """ class C { @@ -1841,12 +1685,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestNotEqualsWithLogicalNot() - { - await TestInRegularAndScript1Async( + public Task TestNotEqualsWithLogicalNot() + => TestInRegularAndScript1Async( """ class C { @@ -1867,12 +1709,10 @@ void M(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestEqualsOtherValueWithLogicalNot() - { - await TestMissingInRegularAndScriptAsync( + public Task TestEqualsOtherValueWithLogicalNot() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1883,12 +1723,10 @@ void M(C c, C other) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23043")] - public async Task TestNotEqualsOtherValueWithLogicalNot() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotEqualsOtherValueWithLogicalNot() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1899,12 +1737,10 @@ void M(C c, C other) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49517")] - public async Task TestParenthesizedExpression() - { - await TestInRegularAndScript1Async( + public Task TestParenthesizedExpression() + => TestInRegularAndScript1Async( """ using System; @@ -1927,12 +1763,10 @@ void M(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49517")] - public async Task TestReversedParenthesizedExpression() - { - await TestInRegularAndScript1Async( + public Task TestReversedParenthesizedExpression() + => TestInRegularAndScript1Async( """ using System; @@ -1955,12 +1789,10 @@ void M(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/74273")] - public async Task TestParenthesizedPropertyAccess() - { - await TestInRegularAndScript1Async(""" + public Task TestParenthesizedPropertyAccess() + => TestInRegularAndScript1Async(""" using System; class C @@ -1975,12 +1807,10 @@ class C int? Length(Array array) => (array?.Length); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/74273")] - public async Task TestReversedParenthesizedPropertyAccess() - { - await TestInRegularAndScript1Async(""" + public Task TestReversedParenthesizedPropertyAccess() + => TestInRegularAndScript1Async(""" using System; class C @@ -1995,12 +1825,10 @@ class C int? Length(Array array) => (array?.Length); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49517")] - public async Task TestParenthesizedNull() - { - await TestInRegularAndScript1Async( + public Task TestParenthesizedNull() + => TestInRegularAndScript1Async( """ using System; @@ -2023,12 +1851,10 @@ void M(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49517")] - public async Task TestReversedParenthesizedNull() - { - await TestInRegularAndScript1Async( + public Task TestReversedParenthesizedNull() + => TestInRegularAndScript1Async( """ using System; @@ -2051,12 +1877,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestIfStatement_Trivia1() - { - await TestInRegularAndScript1Async( + public Task TestIfStatement_Trivia1() + => TestInRegularAndScript1Async( """ using System; @@ -2082,12 +1906,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestIfStatement_Trivia2() - { - await TestInRegularAndScript1Async( + public Task TestIfStatement_Trivia2() + => TestInRegularAndScript1Async( """ using System; @@ -2115,12 +1937,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestIfStatement_Trivia3() - { - await TestInRegularAndScript1Async( + public Task TestIfStatement_Trivia3() + => TestInRegularAndScript1Async( """ using System; @@ -2150,12 +1970,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestIfStatement_Trivia4() - { - await TestInRegularAndScript1Async( + public Task TestIfStatement_Trivia4() + => TestInRegularAndScript1Async( """ using System; @@ -2185,12 +2003,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestIfStatement_Trivia5() - { - await TestInRegularAndScript1Async( + public Task TestIfStatement_Trivia5() + => TestInRegularAndScript1Async( """ using System; @@ -2220,12 +2036,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestNotOnPointer_IfStatement() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOnPointer_IfStatement() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2238,12 +2052,10 @@ unsafe void M(int* i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63557")] - public async Task TestNotWithColorColorStaticCase() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithColorColorStaticCase() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2266,12 +2078,10 @@ public void Test() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63557")] - public async Task TestWithColorColorInstanceCase() - { - await TestInRegularAndScript1Async( + public Task TestWithColorColorInstanceCase() + => TestInRegularAndScript1Async( """ using System; @@ -2313,12 +2123,10 @@ public void Test() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53860")] - public async Task TestWithMethodGroupReference() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithMethodGroupReference() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -2328,12 +2136,10 @@ class C Action M(List p) => p is null ? null : p.Add; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66036")] - public async Task TestElseIfStatement1() - { - await TestInRegularAndScript1Async(""" + public Task TestElseIfStatement1() + => TestInRegularAndScript1Async(""" class C { void M(string s) @@ -2362,12 +2168,44 @@ void M(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66036")] - public async Task TestElseIfStatement2() - { - await TestInRegularAndScript1Async(""" + public Task TestElseIfStatement_NullAssignment1() + => TestInRegularAndScript1Async(""" + class C + { + void M(string s) + { + if (true) + { + } + else [|if|] (s != null) + { + s.ToString(); + s = null; + } + } + } + """, """ + class C + { + void M(string s) + { + if (true) + { + } + else + { + s?.ToString(); + s = null; + } + } + } + """); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66036")] + public Task TestElseIfStatement2() + => TestInRegularAndScript1Async(""" class C { void M(string s) @@ -2392,12 +2230,10 @@ void M(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66036")] - public async Task TestElseIfStatement_Trivia() - { - await TestInRegularAndScript1Async(""" + public Task TestElseIfStatement_Trivia() + => TestInRegularAndScript1Async(""" class C { void M(string s) @@ -2428,12 +2264,10 @@ void M(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66036")] - public async Task TestElseIfStatement_KeepBracePlacementStyle() - { - await TestInRegularAndScript1Async(""" + public Task TestElseIfStatement_KeepBracePlacementStyle() + => TestInRegularAndScript1Async(""" class C { void M(string s) @@ -2460,12 +2294,10 @@ void M(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66141")] - public async Task TestOnValueOffOfNullableValueType1() - { - await TestInRegularAndScript1Async( + public Task TestOnValueOffOfNullableValueType1() + => TestInRegularAndScript1Async( """ using System; @@ -2488,12 +2320,10 @@ void M(byte? o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66141")] - public async Task TestOnValueOffOfNullableValueType2() - { - await TestInRegularAndScript1Async( + public Task TestOnValueOffOfNullableValueType2() + => TestInRegularAndScript1Async( """ using System; @@ -2516,12 +2346,10 @@ void M(byte? o) } } """); - } [Fact] - public async Task TestNullConditionalAssignment1() - { - await TestInRegularAndScript1Async( + public Task TestNullConditionalAssignment1() + => TestInRegularAndScript1Async( """ using System; @@ -2550,12 +2378,10 @@ void M(C c) } """, languageVersion: LanguageVersionExtensions.CSharpNext); - } [Fact] - public async Task TestNullConditionalAssignment2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNullConditionalAssignment2() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2570,5 +2396,272 @@ void M(C c) } } """); - } + + [Fact] + public Task TestNullAssignmentAfterOperation1() + => TestInRegularAndScript1Async( + """ + using System; + + class C + { + int x; + + void M(C c) + { + [|if|] (c != null) + { + c.x = 1; + c = null; + } + } + } + """, + """ + using System; + + class C + { + int x; + + void M(C c) + { + c?.x = 1; + c = null; + } + } + """, + languageVersion: LanguageVersionExtensions.CSharpNext); + + [Fact] + public Task TestNullAssignmentAfterOperation2() + => TestInRegularAndScript1Async( + """ + using System; + + class C + { + int x; + + void M(C c) + { + [|if|] (c != null) + { + c.x = 1; + // Leading comment. + c = null; + } + } + } + """, + """ + using System; + + class C + { + int x; + + void M(C c) + { + c?.x = 1; + // Leading comment. + c = null; + } + } + """, + languageVersion: LanguageVersionExtensions.CSharpNext); + + [Fact] + public Task TestNotNullAssignmentAfterOperation1() + => TestMissingInRegularAndScriptAsync( + """ + using System; + + class C + { + int x; + + void M(C c) + { + if (c != null) + { + c.x = 1; + return; + } + } + } + """, + languageVersion: LanguageVersionExtensions.CSharpNext); + + [Fact] + public Task TestNotNullAssignmentAfterOperation2() + => TestMissingInRegularAndScriptAsync( + """ + using System; + + class C + { + int x; + + void M(C c) + { + if (c != null) + { + c.x = 1; + c = new(); + } + } + } + """, + languageVersion: LanguageVersionExtensions.CSharpNext); + + [Fact] + public Task TestNotNullAssignmentAfterOperation3() + => TestMissingInRegularAndScriptAsync( + """ + using System; + + class C + { + int x; + + void M(C c, C d) + { + if (c != null) + { + c.x = 1; + d = null; + } + } + } + """, + languageVersion: LanguageVersionExtensions.CSharpNext); + + [Fact] + public Task TestNotNullAssignmentAfterOperation4() + => TestMissingInRegularAndScriptAsync( + """ + using System; + + class C + { + C c; + + void M(C c) + { + if (c != null) + { + c.c = null; + c.c = null; + } + } + } + """, + languageVersion: LanguageVersionExtensions.CSharpNext); + + [Fact] + public Task TestNullAssignmentAfterOperation_TopLevel1() + => TestInRegularAndScript1Async( + """ + using System; + + C c = null; + [|if|] (c != null) + { + c.x = 1; + c = null; + } + + class C + { + public int x; + } + """, + """ + using System; + + C c = null; + + c?.x = 1; + c = null; + + class C + { + public int x; + } + """, + OutputKind.ConsoleApplication, + LanguageVersionExtensions.CSharpNext); + + [Fact] + public Task TestNullAssignmentAfterOperation_TopLevel2() + => TestInRegularAndScript1Async( + """ + using System; + + C c = null; + [|if|] (c != null) + { + c.x = 1; + // Comment + c = null; + } + + class C + { + public int x; + } + """, + """ + using System; + + C c = null; + + c?.x = 1; + // Comment + c = null; + + class C + { + public int x; + } + """, + OutputKind.ConsoleApplication, + LanguageVersionExtensions.CSharpNext); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/79338")] + public Task TestNestedNullPropagation_DifferentForms() + => TestInRegularAndScript1Async( + """ + using System; + + class C + { + string S; + + void M(C c) + { + [|if|] (c != null) + c.X([|c == null ? null : c.S|]); + } + + void X(string s) { } + } + """, + """ + using System; + + class C + { + string S; + + void M(C c) + { + c?.X(c?.S); + } + + void X(string s) { } + } + """, + languageVersion: LanguageVersionExtensions.CSharpNext); } diff --git a/src/Analyzers/CSharp/Tests/UseObjectInitializer/UseObjectInitializerTests.cs b/src/Analyzers/CSharp/Tests/UseObjectInitializer/UseObjectInitializerTests.cs index 5826cccbb01a6..15668e4a50920 100644 --- a/src/Analyzers/CSharp/Tests/UseObjectInitializer/UseObjectInitializerTests.cs +++ b/src/Analyzers/CSharp/Tests/UseObjectInitializer/UseObjectInitializerTests.cs @@ -36,9 +36,10 @@ private static async Task TestMissingInRegularAndScriptAsync( } [Fact] - public async Task TestOnVariableDeclarator() - { - var testCode = """ + public Task TestOnVariableDeclarator() + => new VerifyCS.Test + { + TestCode = """ class C { int i; @@ -49,8 +50,13 @@ void M() {|#2:c.|}i = 1{|#3:;|} } } - """; - var fixedCode = """ + """, + ExpectedDiagnostics = + { + // /0/Test0.cs(6,19): info IDE0017: Object initialization can be simplified + VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), + }, + FixedCode = """ class C { int i; @@ -63,61 +69,43 @@ void M() }; } } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - ExpectedDiagnostics = - { - // /0/Test0.cs(6,19): info IDE0017: Object initialization can be simplified - VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), - }, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotForField1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotForField1() + => TestMissingInRegularAndScriptAsync( """ class C { C c = new C(); } """); - } [Fact] - public async Task TestNotForField2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotForField2() + => TestMissingInRegularAndScriptAsync( """ class C { C c = new C() { }; } """); - } [Fact] - public async Task TestNotForField3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotForField3() + => TestMissingInRegularAndScriptAsync( """ class C { C c = new C { }; } """); - } [Fact] - public async Task TestNotForField4() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotForField4() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -125,12 +113,10 @@ class C C c = new C() { P = 1 }; } """); - } [Fact] - public async Task TestNotForField5() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotForField5() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -138,12 +124,12 @@ class C C c = new C { P = 1 }; } """); - } [Fact] - public async Task TestDoNotUpdateAssignmentThatReferencesInitializedValue1Async() - { - var testCode = """ + public Task TestDoNotUpdateAssignmentThatReferencesInitializedValue1Async() + => new VerifyCS.Test + { + TestCode = """ class C { int i; @@ -155,8 +141,13 @@ void M() c.i = c.i + 1; } } - """; - var fixedCode = """ + """, + ExpectedDiagnostics = + { + // /0/Test0.cs(7,17): info IDE0017: Object initialization can be simplified + VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), + }, + FixedCode = """ class C { int i; @@ -170,25 +161,13 @@ void M() c.i = c.i + 1; } } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - ExpectedDiagnostics = - { - // /0/Test0.cs(7,17): info IDE0017: Object initialization can be simplified - VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), - }, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestDoNotUpdateAssignmentThatReferencesInitializedValue2Async() - { - await TestMissingInRegularAndScriptAsync( + public Task TestDoNotUpdateAssignmentThatReferencesInitializedValue2Async() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -201,12 +180,12 @@ void M() } } """); - } [Fact] - public async Task TestDoNotUpdateAssignmentThatReferencesInitializedValue3Async() - { - var testCode = """ + public Task TestDoNotUpdateAssignmentThatReferencesInitializedValue3Async() + => new VerifyCS.Test + { + TestCode = """ class C { int i; @@ -219,8 +198,13 @@ void M() c.i = c.i + 1; } } - """; - var fixedCode = """ + """, + ExpectedDiagnostics = + { + // /0/Test0.cs(6,19): info IDE0017: Object initialization can be simplified + VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), + }, + FixedCode = """ class C { int i; @@ -235,25 +219,13 @@ void M() c.i = c.i + 1; } } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - ExpectedDiagnostics = - { - // /0/Test0.cs(6,19): info IDE0017: Object initialization can be simplified - VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), - }, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestDoNotUpdateAssignmentThatReferencesInitializedValue4Async() - { - await TestMissingInRegularAndScriptAsync( + public Task TestDoNotUpdateAssignmentThatReferencesInitializedValue4Async() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -267,12 +239,12 @@ void M() } } """); - } [Fact] - public async Task TestOnAssignmentExpression() - { - var testCode = """ + public Task TestOnAssignmentExpression() + => new VerifyCS.Test + { + TestCode = """ class C { int i; @@ -284,8 +256,13 @@ void M() {|#2:c.|}i = 1{|#3:;|} } } - """; - var fixedCode = """ + """, + ExpectedDiagnostics = + { + // /0/Test0.cs(8,13): info IDE0017: Object initialization can be simplified + VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), + }, + FixedCode = """ class C { int i; @@ -299,25 +276,15 @@ void M() }; } } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - ExpectedDiagnostics = - { - // /0/Test0.cs(8,13): info IDE0017: Object initialization can be simplified - VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), - }, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestStopOnDuplicateMember() - { - var testCode = """ + public Task TestStopOnDuplicateMember() + => new VerifyCS.Test + { + TestCode = """ class C { int i; @@ -329,8 +296,13 @@ void M() c.i = 2; } } - """; - var fixedCode = """ + """, + ExpectedDiagnostics = + { + // /0/Test0.cs(7,17): info IDE0017: Object initialization can be simplified + VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), + }, + FixedCode = """ class C { int i; @@ -344,25 +316,15 @@ void M() c.i = 2; } } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - ExpectedDiagnostics = - { - // /0/Test0.cs(7,17): info IDE0017: Object initialization can be simplified - VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), - }, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestComplexInitializer() - { - var testCode = """ + public Task TestComplexInitializer() + => new VerifyCS.Test + { + TestCode = """ class C { int i; @@ -375,8 +337,13 @@ void M(C[] array) {|#4:array[0].|}j = 2{|#5:;|} } } - """; - var fixedCode = """ + """, + ExpectedDiagnostics = + { + // /0/Test0.cs(8,20): info IDE0017: Object initialization can be simplified + VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3).WithLocation(4).WithLocation(5), + }, + FixedCode = """ class C { int i; @@ -391,25 +358,15 @@ void M(C[] array) }; } } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - ExpectedDiagnostics = - { - // /0/Test0.cs(8,20): info IDE0017: Object initialization can be simplified - VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3).WithLocation(4).WithLocation(5), - }, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotOnCompoundAssignment() - { - var testCode = """ + public Task TestNotOnCompoundAssignment() + => new VerifyCS.Test + { + TestCode = """ class C { int i; @@ -422,8 +379,13 @@ void M() c.j += 1; } } - """; - var fixedCode = """ + """, + ExpectedDiagnostics = + { + // /0/Test0.cs(8,17): info IDE0017: Object initialization can be simplified + VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), + }, + FixedCode = """ class C { int i; @@ -438,25 +400,15 @@ void M() c.j += 1; } } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - ExpectedDiagnostics = - { - // /0/Test0.cs(8,17): info IDE0017: Object initialization can be simplified - VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), - }, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39146")] - public async Task TestWithExistingInitializer() - { - var testCode = """ + public Task TestWithExistingInitializer() + => new VerifyCS.Test + { + TestCode = """ class C { int i; @@ -468,8 +420,13 @@ void M() {|#2:c.|}j = 1{|#3:;|} } } - """; - var fixedCode = """ + """, + ExpectedDiagnostics = + { + // /0/Test0.cs(8,17): info IDE0017: Object initialization can be simplified + VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), + }, + FixedCode = """ class C { int i; @@ -484,25 +441,15 @@ void M() }; } } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - ExpectedDiagnostics = - { - // /0/Test0.cs(8,17): info IDE0017: Object initialization can be simplified - VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), - }, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39146")] - public async Task TestWithExistingInitializerComma() - { - var testCode = """ + public Task TestWithExistingInitializerComma() + => new VerifyCS.Test + { + TestCode = """ class C { int i; @@ -517,8 +464,13 @@ void M() {|#2:c.|}j = 1{|#3:;|} } } - """; - var fixedCode = """ + """, + ExpectedDiagnostics = + { + // /0/Test0.cs(8,17): info IDE0017: Object initialization can be simplified + VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), + }, + FixedCode = """ class C { int i; @@ -533,25 +485,15 @@ void M() }; } } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - ExpectedDiagnostics = - { - // /0/Test0.cs(8,17): info IDE0017: Object initialization can be simplified - VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), - }, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39146")] - public async Task TestWithExistingInitializerNotIfAlreadyInitialized() - { - var testCode = """ + public Task TestWithExistingInitializerNotIfAlreadyInitialized() + => new VerifyCS.Test + { + TestCode = """ class C { int i; @@ -567,8 +509,13 @@ void M() c.i = 2; } } - """; - var fixedCode = """ + """, + ExpectedDiagnostics = + { + // /0/Test0.cs(8,17): info IDE0017: Object initialization can be simplified + VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), + }, + FixedCode = """ class C { int i; @@ -584,25 +531,13 @@ void M() c.i = 2; } } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - ExpectedDiagnostics = - { - // /0/Test0.cs(8,17): info IDE0017: Object initialization can be simplified - VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), - }, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMissingBeforeCSharp3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingBeforeCSharp3() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -616,12 +551,12 @@ void M() } } """, LanguageVersion.CSharp2); - } [Fact] - public async Task TestFixAllInDocument1() - { - var testCode = """ + public Task TestFixAllInDocument1() + => new VerifyCS.Test + { + TestCode = """ class C { int i; @@ -639,8 +574,15 @@ void M() {|#2:v.|}j = 2{|#3:;|} } } - """; - var fixedCode = """ + """, + ExpectedDiagnostics = + { + // /0/Test0.cs(11,17): info IDE0017: Object initialization can be simplified + VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), + // /0/Test0.cs(12,22): info IDE0017: Object initialization can be simplified + VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(4).WithLocation(5).WithLocation(6).WithLocation(7), + }, + FixedCode = """ class C { int i; @@ -663,27 +605,15 @@ void M() }; } } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - ExpectedDiagnostics = - { - // /0/Test0.cs(11,17): info IDE0017: Object initialization can be simplified - VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), - // /0/Test0.cs(12,22): info IDE0017: Object initialization can be simplified - VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(4).WithLocation(5).WithLocation(6).WithLocation(7), - }, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestFixAllInDocument2() - { - var testCode = """ + public Task TestFixAllInDocument2() + => new VerifyCS.Test + { + TestCode = """ class C { int i; @@ -698,8 +628,15 @@ void M() }{|#3:;|} } } - """; - var fixedCode = """ + """, + ExpectedDiagnostics = + { + // /0/Test0.cs(8,17): info IDE0017: Object initialization can be simplified + VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), + // /0/Test0.cs(10,22): info IDE0017: Object initialization can be simplified + VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(4).WithLocation(5).WithLocation(6).WithLocation(7), + }, + FixedCode = """ class C { int i; @@ -719,27 +656,15 @@ void M() }; } } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - ExpectedDiagnostics = - { - // /0/Test0.cs(8,17): info IDE0017: Object initialization can be simplified - VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), - // /0/Test0.cs(10,22): info IDE0017: Object initialization can be simplified - VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(4).WithLocation(5).WithLocation(6).WithLocation(7), - }, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestFixAllInDocument3() - { - var testCode = """ + public Task TestFixAllInDocument3() + => new VerifyCS.Test + { + TestCode = """ class C { int i; @@ -755,8 +680,15 @@ void M(C[] array) {|#10:array[1].|}j = 4{|#11:;|} } } - """; - var fixedCode = """ + """, + ExpectedDiagnostics = + { + // /0/Test0.cs(8,20): info IDE0017: Object initialization can be simplified + VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3).WithLocation(4).WithLocation(5), + // /0/Test0.cs(11,20): info IDE0017: Object initialization can be simplified + VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(6).WithLocation(7).WithLocation(8).WithLocation(9).WithLocation(10).WithLocation(11), + }, + FixedCode = """ class C { int i; @@ -776,27 +708,15 @@ void M(C[] array) }; } } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - ExpectedDiagnostics = - { - // /0/Test0.cs(8,20): info IDE0017: Object initialization can be simplified - VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3).WithLocation(4).WithLocation(5), - // /0/Test0.cs(11,20): info IDE0017: Object initialization can be simplified - VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(6).WithLocation(7).WithLocation(8).WithLocation(9).WithLocation(10).WithLocation(11), - }, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestTrivia1() - { - var testCode = """ + public Task TestTrivia1() + => new VerifyCS.Test + { + TestCode = """ class C { int i; @@ -808,8 +728,13 @@ void M() {|#4:c.|}j = 2{|#5:;|} // Bar } } - """; - var fixedCode = """ + """, + ExpectedDiagnostics = + { + // /0/Test0.cs(7,17): info IDE0017: Object initialization can be simplified + VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3).WithLocation(4).WithLocation(5), + }, + FixedCode = """ class C { int i; @@ -823,25 +748,15 @@ void M() }; } } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - ExpectedDiagnostics = - { - // /0/Test0.cs(7,17): info IDE0017: Object initialization can be simplified - VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3).WithLocation(4).WithLocation(5), - }, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46670")] - public async Task TestTriviaRemoveLeadingBlankLinesForFirstProperty() - { - var testCode = """ + public Task TestTriviaRemoveLeadingBlankLinesForFirstProperty() + => new VerifyCS.Test + { + TestCode = """ class C { int i; @@ -857,8 +772,13 @@ void M() {|#4:c.|}j = 2{|#5:;|} } } - """; - var fixedCode = """ + """, + ExpectedDiagnostics = + { + // /0/Test0.cs(7,17): info IDE0017: Object initialization can be simplified + VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3).WithLocation(4).WithLocation(5), + }, + FixedCode = """ class C { int i; @@ -875,25 +795,13 @@ void M() }; } } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - ExpectedDiagnostics = - { - // /0/Test0.cs(7,17): info IDE0017: Object initialization can be simplified - VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3).WithLocation(4).WithLocation(5), - }, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15459")] - public async Task TestMissingInNonTopLevelObjectInitializer() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingInNonTopLevelObjectInitializer() + => TestMissingInRegularAndScriptAsync( """ class C { int a; @@ -904,12 +812,10 @@ C Add(int x) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17853")] - public async Task TestMissingForDynamic() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingForDynamic() + => TestMissingInRegularAndScriptAsync( """ using System.Dynamic; @@ -922,12 +828,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17953")] - public async Task TestMissingAcrossPreprocessorDirective() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingAcrossPreprocessorDirective() + => TestMissingInRegularAndScriptAsync( """ public class Goo { @@ -942,12 +846,12 @@ public void M() public string Value { get; set; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17953")] - public async Task TestAvailableInsidePreprocessorDirective() - { - var testCode = """ + public Task TestAvailableInsidePreprocessorDirective() + => new VerifyCS.Test + { + TestCode = """ public class Goo { public void M() @@ -960,8 +864,13 @@ public void M() public string Value { get; set; } } - """; - var fixedCode = """ + """, + ExpectedDiagnostics = + { + // /0/Test0.cs(6,19): info IDE0017: Object initialization can be simplified + VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), + }, + FixedCode = """ public class Goo { public void M() @@ -976,25 +885,15 @@ public void M() public string Value { get; set; } } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - ExpectedDiagnostics = - { - // /0/Test0.cs(6,19): info IDE0017: Object initialization can be simplified - VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), - }, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19253")] - public async Task TestKeepBlankLinesAfter() - { - var testCode = """ + public Task TestKeepBlankLinesAfter() + => new VerifyCS.Test + { + TestCode = """ class Goo { public int Bar { get; set; } @@ -1010,8 +909,13 @@ public void Main() int horse = 1; } } - """; - var fixedCode = """ + """, + ExpectedDiagnostics = + { + // /0/Test0.cs(6,19): info IDE0017: Object initialization can be simplified + VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), + }, + FixedCode = """ class Goo { public int Bar { get; set; } @@ -1029,25 +933,13 @@ public void Main() int horse = 1; } } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - ExpectedDiagnostics = - { - // /0/Test0.cs(6,19): info IDE0017: Object initialization can be simplified - VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), - }, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23368")] - public async Task TestWithExplicitImplementedInterfaceMembers1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithExplicitImplementedInterfaceMembers1() + => TestMissingInRegularAndScriptAsync( """ interface IExample { string Name { get; set; } @@ -1066,12 +958,10 @@ public void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23368")] - public async Task TestWithExplicitImplementedInterfaceMembers2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithExplicitImplementedInterfaceMembers2() + => TestMissingInRegularAndScriptAsync( """ interface IExample { string Name { get; set; } @@ -1093,12 +983,12 @@ public void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23368")] - public async Task TestWithExplicitImplementedInterfaceMembers3() - { - var testCode = """ + public Task TestWithExplicitImplementedInterfaceMembers3() + => new VerifyCS.Test + { + TestCode = """ interface IExample { string Name { get; set; } string LastName { get; set; } @@ -1118,8 +1008,13 @@ public void Main() e.Name = string.Empty; } } - """; - var fixedCode = """ + """, + ExpectedDiagnostics = + { + // /0/Test0.cs(15,22): info IDE0017: Object initialization can be simplified + VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), + }, + FixedCode = """ interface IExample { string Name { get; set; } string LastName { get; set; } @@ -1141,25 +1036,13 @@ public void Main() e.Name = string.Empty; } } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - ExpectedDiagnostics = - { - // /0/Test0.cs(15,22): info IDE0017: Object initialization can be simplified - VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), - }, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37675")] - public async Task TestDoNotOfferForUsingDeclaration() - { - await TestMissingInRegularAndScriptAsync( + public Task TestDoNotOfferForUsingDeclaration() + => TestMissingInRegularAndScriptAsync( """ class C : System.IDisposable { @@ -1176,12 +1059,12 @@ public void Dispose() } } """); - } [Fact] - public async Task TestImplicitObject() - { - var testCode = """ + public Task TestImplicitObject() + => new VerifyCS.Test + { + TestCode = """ class C { int i; @@ -1192,8 +1075,13 @@ void M() {|#2:c.|}i = 1{|#3:;|} } } - """; - var fixedCode = """ + """, + ExpectedDiagnostics = + { + // /0/Test0.cs(6,19): info IDE0017: Object initialization can be simplified + VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), + }, + FixedCode = """ class C { int i; @@ -1206,25 +1094,15 @@ void M() }; } } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - ExpectedDiagnostics = - { - // /0/Test0.cs(6,19): info IDE0017: Object initialization can be simplified - VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), - }, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61066")] - public async Task TestInTopLevelStatements() - { - var testCode = """ + public Task TestInTopLevelStatements() + => new VerifyCS.Test + { + TestCode = """ MyClass cl = {|#1:{|#0:new|}()|}; {|#2:cl.|}MyProperty = 5{|#3:;|} @@ -1232,8 +1110,13 @@ class MyClass { public int MyProperty { get; set; } } - """; - var fixedCode = """ + """, + ExpectedDiagnostics = + { + // /0/Test0.cs(6,19): info IDE0017: Object initialization can be simplified + VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), + }, + FixedCode = """ MyClass cl = new() { MyProperty = 5 @@ -1243,21 +1126,10 @@ class MyClass { public int MyProperty { get; set; } } - """; - - await new VerifyCS.Test - { - TestCode = testCode, - ExpectedDiagnostics = - { - // /0/Test0.cs(6,19): info IDE0017: Object initialization can be simplified - VerifyCS.Diagnostic().WithSeverity(DiagnosticSeverity.Info).WithLocation(0).WithLocation(1).WithLocation(2).WithLocation(3), - }, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp12, TestState = { OutputKind = OutputKind.ConsoleApplication }, }.RunAsync(); - } [Theory] [CombinatorialData] @@ -1382,17 +1254,6 @@ void M() } } """; - - var globalConfig = - $""" - is_global = true - - dotnet_style_object_initializer = true - dotnet_diagnostic.IDE0017.severity = warning - - build_property.EnableCodeStyleSeverity = {enabled} - """; - await new VerifyCS.Test { TestState = @@ -1405,7 +1266,14 @@ void M() }, AnalyzerConfigFiles = { - ("/.globalconfig", globalConfig), + ("/.globalconfig", $""" + is_global = true + + dotnet_style_object_initializer = true + dotnet_diagnostic.IDE0017.severity = warning + + build_property.EnableCodeStyleSeverity = {enabled} + """), } }, FixedState = { Sources = { fixedCode } }, @@ -1414,9 +1282,8 @@ void M() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46665")] - public async Task TestIndentationOfMultiLineExpressions1() - { - await new VerifyCS.Test + public Task TestIndentationOfMultiLineExpressions1() + => new VerifyCS.Test { TestCode = """ class C @@ -1454,12 +1321,10 @@ void M(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46665")] - public async Task TestIndentationOfMultiLineExpressions2() - { - await new VerifyCS.Test + public Task TestIndentationOfMultiLineExpressions2() + => new VerifyCS.Test { TestCode = """ class C @@ -1501,12 +1366,10 @@ void M(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46665")] - public async Task TestIndentationOfMultiLineExpressions3() - { - await new VerifyCS.Test + public Task TestIndentationOfMultiLineExpressions3() + => new VerifyCS.Test { TestCode = """ class C @@ -1544,12 +1407,10 @@ void M(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46665")] - public async Task TestIndentationOfMultiLineExpressions4() - { - await new VerifyCS.Test + public Task TestIndentationOfMultiLineExpressions4() + => new VerifyCS.Test { TestCode = """ class C @@ -1591,5 +1452,4 @@ void M(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpAsAndMemberAccessTests.cs b/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpAsAndMemberAccessTests.cs index aa89437512e55..62d078853ecc3 100644 --- a/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpAsAndMemberAccessTests.cs +++ b/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpAsAndMemberAccessTests.cs @@ -20,9 +20,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UsePatternMatching; public sealed partial class CSharpAsAndMemberAccessTests { [Fact] - public async Task TestCoreCase() - { - await new VerifyCS.Test + public Task TestCoreCase() + => new VerifyCS.Test { TestCode = """ class C @@ -47,12 +46,12 @@ void M(object o) } """, }.RunAsync(); - } [Fact] - public async Task TestNotInCSharp7() - { - var test = """ + public Task TestNotInCSharp7() + => new VerifyCS.Test + { + TestCode = """ class C { void M(object o) @@ -62,18 +61,15 @@ void M(object o) } } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, LanguageVersion = LanguageVersion.CSharp7, }.RunAsync(); - } [Fact] - public async Task TestNotWithNonConstant() - { - var test = """ + public Task TestNotWithNonConstant() + => new VerifyCS.Test + { + TestCode = """ class C { void M(object o, int length) @@ -83,18 +79,15 @@ void M(object o, int length) } } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, LanguageVersion = LanguageVersion.CSharp7, }.RunAsync(); - } [Fact] - public async Task TestNotWithoutTest() - { - var test = """ + public Task TestNotWithoutTest() + => new VerifyCS.Test + { + TestCode = """ class C { void M(object o, int length) @@ -102,18 +95,15 @@ void M(object o, int length) var v = (o as string)?.Length; } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, LanguageVersion = LanguageVersion.CSharp7, }.RunAsync(); - } [Fact] - public async Task TestNotWithNonMemberBinding1() - { - var test = """ + public Task TestNotWithNonMemberBinding1() + => new VerifyCS.Test + { + TestCode = """ class C { C[] X; @@ -126,18 +116,15 @@ void M(object o, int length) } } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, LanguageVersion = LanguageVersion.CSharp7, }.RunAsync(); - } [Fact] - public async Task TestNotEqualsConstant_CSharp8() - { - var test = """ + public Task TestNotEqualsConstant_CSharp8() + => new VerifyCS.Test + { + TestCode = """ class C { void M(object o) @@ -147,18 +134,15 @@ void M(object o) } } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] - public async Task TestNotEqualsConstant_CSharp9() - { - var test = """ + public Task TestNotEqualsConstant_CSharp9() + => new VerifyCS.Test + { + TestCode = """ class C { void M(object o) @@ -168,18 +152,15 @@ void M(object o) } } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestNotEqualsNull_ValueType_CSharp8() - { - var test = """ + public Task TestNotEqualsNull_ValueType_CSharp8() + => new VerifyCS.Test + { + TestCode = """ class C { void M(object o) @@ -189,18 +170,15 @@ void M(object o) } } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] - public async Task TestNotEqualsNull_ValueType_CSharp9() - { - var test = """ + public Task TestNotEqualsNull_ValueType_CSharp9() + => new VerifyCS.Test + { + TestCode = """ class C { void M(object o) @@ -210,18 +188,15 @@ void M(object o) } } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestNotEqualsNull_ValueType2_CSharp9() - { - var test = """ + public Task TestNotEqualsNull_ValueType2_CSharp9() + => new VerifyCS.Test + { + TestCode = """ class C { C X; @@ -234,18 +209,15 @@ void M(object o) } } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestNotEqualsNull_ReferenceType_CSharp8() - { - var test = """ + public Task TestNotEqualsNull_ReferenceType_CSharp8() + => new VerifyCS.Test + { + TestCode = """ class C { string X; @@ -257,18 +229,13 @@ void M(object o) } } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] - public async Task TestNotEqualsNull_ReferenceType_CSharp9() - { - await new VerifyCS.Test + public Task TestNotEqualsNull_ReferenceType_CSharp9() + => new VerifyCS.Test { TestCode = """ class C @@ -298,12 +265,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestNotEqualsNull_ReferenceType_CSharp10() - { - await new VerifyCS.Test + public Task TestNotEqualsNull_ReferenceType_CSharp10() + => new VerifyCS.Test { TestCode = """ class C @@ -335,12 +300,12 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task TestNotEqualsNull_NullableType_CSharp8() - { - var test = """ + public Task TestNotEqualsNull_NullableType_CSharp8() + => new VerifyCS.Test + { + TestCode = """ class C { int? X; @@ -352,18 +317,15 @@ void M(object o) } } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] - public async Task TestNotEqualsNull_NullableType2_CSharp8() - { - var test = """ + public Task TestNotEqualsNull_NullableType2_CSharp8() + => new VerifyCS.Test + { + TestCode = """ class C { int? X; @@ -375,18 +337,13 @@ void M(object o) } } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] - public async Task TestNotEqualsNull_NullableType_CSharp10() - { - await new VerifyCS.Test + public Task TestNotEqualsNull_NullableType_CSharp10() + => new VerifyCS.Test { TestCode = """ class C @@ -418,12 +375,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task TestGreaterThan() - { - await new VerifyCS.Test + public Task TestGreaterThan() + => new VerifyCS.Test { TestCode = """ class C @@ -449,12 +404,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestGreaterThanEquals() - { - await new VerifyCS.Test + public Task TestGreaterThanEquals() + => new VerifyCS.Test { TestCode = """ class C @@ -480,12 +433,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestLessThan() - { - await new VerifyCS.Test + public Task TestLessThan() + => new VerifyCS.Test { TestCode = """ class C @@ -515,12 +466,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestLessThanEquals() - { - await new VerifyCS.Test + public Task TestLessThanEquals() + => new VerifyCS.Test { TestCode = """ class C @@ -546,12 +495,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestIsConstantPattern1() - { - await new VerifyCS.Test + public Task TestIsConstantPattern1() + => new VerifyCS.Test { TestCode = """ class C @@ -576,12 +523,12 @@ void M(object o) } """, }.RunAsync(); - } [Fact] - public async Task TestIsNotConstantPattern() - { - var test = """ + public Task TestIsNotConstantPattern() + => new VerifyCS.Test + { + TestCode = """ class C { void M(object o) @@ -591,18 +538,15 @@ void M(object o) } } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestIsNullPattern() - { - var test = """ + public Task TestIsNullPattern() + => new VerifyCS.Test + { + TestCode = """ class C { void M(object o) @@ -612,18 +556,15 @@ void M(object o) } } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestIsNotNullPattern_ValueType() - { - var test = """ + public Task TestIsNotNullPattern_ValueType() + => new VerifyCS.Test + { + TestCode = """ class C { void M(object o) @@ -633,18 +574,15 @@ void M(object o) } } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestIsNotNullPattern_ValueType2() - { - var test = """ + public Task TestIsNotNullPattern_ValueType2() + => new VerifyCS.Test + { + TestCode = """ class C { C X; @@ -657,18 +595,13 @@ void M(object o) } } } - """; - await new VerifyCS.Test - { - TestCode = test, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestIsNotNullPattern_ReferenceType() - { - await new VerifyCS.Test + public Task TestIsNotNullPattern_ReferenceType() + => new VerifyCS.Test { TestCode = """ class C @@ -698,12 +631,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestIsNotNullPattern_ReferenceType_CSharp10() - { - await new VerifyCS.Test + public Task TestIsNotNullPattern_ReferenceType_CSharp10() + => new VerifyCS.Test { TestCode = """ class C @@ -735,12 +666,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task TestIsNotNullPattern_NullableValueType() - { - await new VerifyCS.Test + public Task TestIsNotNullPattern_NullableValueType() + => new VerifyCS.Test { TestCode = """ class C @@ -770,12 +699,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestIsNotNullPattern_NullableValueType_CSharp10() - { - await new VerifyCS.Test + public Task TestIsNotNullPattern_NullableValueType_CSharp10() + => new VerifyCS.Test { TestCode = """ class C @@ -807,12 +734,12 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task TestMemberAccess1_CSharp9() - { - var test = """ + public Task TestMemberAccess1_CSharp9() + => new VerifyCS.Test + { + TestCode = """ class C { C X; @@ -825,19 +752,13 @@ void M(object o) } } } - """; - - await new VerifyCS.Test - { - TestCode = test, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestMemberAccess1_CSharp10() - { - await new VerifyCS.Test + public Task TestMemberAccess1_CSharp10() + => new VerifyCS.Test { TestCode = """ class C @@ -869,12 +790,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task TestParenthesizedParent() - { - await new VerifyCS.Test + public Task TestParenthesizedParent() + => new VerifyCS.Test { TestCode = """ class C @@ -899,12 +818,10 @@ void M(object o) } """, }.RunAsync(); - } [Fact] - public async Task TestBinaryParent() - { - await new VerifyCS.Test + public Task TestBinaryParent() + => new VerifyCS.Test { TestCode = """ class C @@ -929,12 +846,10 @@ void M(object o) } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67010")] - public async Task TestIsTypePattern() - { - await new VerifyCS.Test + public Task TestIsTypePattern() + => new VerifyCS.Test { TestCode = """ using System; @@ -961,12 +876,10 @@ void M(object o) } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67010")] - public async Task TestIsNotTypePattern() - { - await new VerifyCS.Test + public Task TestIsNotTypePattern() + => new VerifyCS.Test { TestCode = """ using System; @@ -982,12 +895,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67010")] - public async Task TestIsVarPattern() - { - await new VerifyCS.Test + public Task TestIsVarPattern() + => new VerifyCS.Test { TestCode = """ using System; @@ -1014,12 +925,10 @@ void M(object o) } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67010")] - public async Task TestIsNotVarPattern() - { - await new VerifyCS.Test + public Task TestIsNotVarPattern() + => new VerifyCS.Test { TestCode = """ using System; @@ -1035,12 +944,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67010")] - public async Task TestIsRecursivePattern1() - { - await new VerifyCS.Test + public Task TestIsRecursivePattern1() + => new VerifyCS.Test { TestCode = """ using System; @@ -1067,12 +974,10 @@ void M(object o) } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67010")] - public async Task TestIsRecursivePattern2() - { - await new VerifyCS.Test + public Task TestIsRecursivePattern2() + => new VerifyCS.Test { TestCode = """ using System; @@ -1099,12 +1004,10 @@ void M(object o) } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67010")] - public async Task TestIsNotRecursivePattern1() - { - await new VerifyCS.Test + public Task TestIsNotRecursivePattern1() + => new VerifyCS.Test { TestCode = """ using System; @@ -1132,12 +1035,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67010")] - public async Task TestIsNotRecursivePattern2() - { - await new VerifyCS.Test + public Task TestIsNotRecursivePattern2() + => new VerifyCS.Test { TestCode = """ using System; @@ -1153,12 +1054,10 @@ void M(object o) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76372")] - public async Task TestPullNotUpwards() - { - await new VerifyCS.Test + public Task TestPullNotUpwards() + => new VerifyCS.Test { TestCode = """ using System; @@ -1226,5 +1125,4 @@ public enum G """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpAsAndNullCheckTests.cs b/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpAsAndNullCheckTests.cs index 109a03a57cda4..c9ae32fd6104c 100644 --- a/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpAsAndNullCheckTests.cs +++ b/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpAsAndNullCheckTests.cs @@ -56,9 +56,8 @@ public async Task InlineTypeCheck1(string input, string output, LanguageVersion public async Task InlineTypeCheck2(string input, string output) => await TestStatement($"while ({input}) {{ }}", $"while ({output}) {{ }}"); - private async Task TestStatement(string input, string output, LanguageVersion version = LanguageVersion.CSharp8) - { - await TestInRegularAndScript1Async( + private Task TestStatement(string input, string output, LanguageVersion version = LanguageVersion.CSharp8) + => TestInRegularAndScript1Async( $$""" class C { @@ -78,12 +77,10 @@ void M(object o) } } """, new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(version))); - } [Fact] - public async Task TestMissingInCSharp6() - { - await TestMissingAsync( + public Task TestMissingInCSharp6() + => TestMissingAsync( """ class C { @@ -96,12 +93,10 @@ void M() } } """, new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); - } [Fact] - public async Task TestMissingInWrongName() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingInWrongName() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -114,12 +109,10 @@ void M() } } """); - } [Fact] - public async Task TestInSwitchSection() - { - await TestInRegularAndScript1Async( + public Task TestInSwitchSection() + => TestInRegularAndScript1Async( """ class C { @@ -151,12 +144,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33345")] - public async Task TestRemoveNewLinesInSwitchStatement() - { - await TestInRegularAndScript1Async( + public Task TestRemoveNewLinesInSwitchStatement() + => TestInRegularAndScript1Async( """ class C { @@ -191,12 +182,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingOnNonDeclaration() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnNonDeclaration() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -209,12 +198,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25237")] - public async Task TestMissingOnReturnStatement() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnReturnStatement() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -224,12 +211,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingOnIsExpression() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnIsExpression() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -242,12 +227,10 @@ void M() } } """); - } [Fact] - public async Task InlineTypeCheckComplexExpression1() - { - await TestInRegularAndScript1Async( + public Task InlineTypeCheckComplexExpression1() + => TestInRegularAndScript1Async( """ class C { @@ -271,12 +254,10 @@ void M() } } """); - } [Fact] - public async Task TestInlineTypeCheckWithElse() - { - await TestInRegularAndScript1Async( + public Task TestInlineTypeCheckWithElse() + => TestInRegularAndScript1Async( """ class C { @@ -306,12 +287,10 @@ void M() } } """); - } [Fact] - public async Task TestComments1() - { - await TestInRegularAndScript1Async( + public Task TestComments1() + => TestInRegularAndScript1Async( """ class C { @@ -337,12 +316,10 @@ void M() } } """); - } [Fact] - public async Task TestComments2() - { - await TestInRegularAndScript1Async( + public Task TestComments2() + => TestInRegularAndScript1Async( """ class C { @@ -367,12 +344,10 @@ void M() } } """); - } [Fact] - public async Task TestComments3() - { - await TestInRegularAndScript1Async( + public Task TestComments3() + => TestInRegularAndScript1Async( """ class C { @@ -399,12 +374,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33345")] - public async Task TestRemoveNewLines() - { - await TestInRegularAndScript1Async( + public Task TestRemoveNewLines() + => TestInRegularAndScript1Async( """ class C { @@ -431,12 +404,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33345")] - public async Task TestRemoveNewLinesWhereBlankLineIsNotEmpty() - { - await TestInRegularAndScript1Async( + public Task TestRemoveNewLinesWhereBlankLineIsNotEmpty() + => TestInRegularAndScript1Async( """ class C { @@ -463,12 +434,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33345")] - public async Task TestRemoveNewLines2() - { - await TestInRegularAndScript1Async( + public Task TestRemoveNewLines2() + => TestInRegularAndScript1Async( """ class C { @@ -498,12 +467,10 @@ void M() } } """); - } [Fact] - public async Task InlineTypeCheckComplexCondition1() - { - await TestInRegularAndScript1Async( + public Task InlineTypeCheckComplexCondition1() + => TestInRegularAndScript1Async( """ class C { @@ -527,12 +494,10 @@ void M() } } """); - } [Fact] - public async Task InlineTypeCheckComplexCondition2() - { - await TestInRegularAndScript1Async( + public Task InlineTypeCheckComplexCondition2() + => TestInRegularAndScript1Async( """ class C { @@ -556,12 +521,10 @@ void M() } } """); - } [Fact] - public async Task InlineTypeCheckComplexCondition3() - { - await TestInRegularAndScript1Async( + public Task InlineTypeCheckComplexCondition3() + => TestInRegularAndScript1Async( """ class C { @@ -585,12 +548,10 @@ void M() } } """); - } [Fact] - public async Task TestDefiniteAssignment1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestDefiniteAssignment1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -606,12 +567,10 @@ void M() } } """); - } [Fact] - public async Task TestDefiniteAssignment2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestDefiniteAssignment2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -626,12 +585,10 @@ void M() } } """); - } [Fact] - public async Task TestDefiniteAssignment3() - { - await TestInRegularAndScript1Async( + public Task TestDefiniteAssignment3() + => TestInRegularAndScript1Async( """ class C { @@ -662,12 +619,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21097")] - public async Task TestDefiniteAssignment4() - { - await TestMissingInRegularAndScriptAsync( + public Task TestDefiniteAssignment4() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -687,12 +642,10 @@ void M(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24286")] - public async Task TestDefiniteAssignment5() - { - await TestMissingInRegularAndScriptAsync( + public Task TestDefiniteAssignment5() + => TestMissingInRegularAndScriptAsync( """ public class Test { @@ -706,12 +659,10 @@ public void TestIt(object o1, object o2) } } """); - } [Fact] - public async Task TestDefiniteAssignment6() - { - await TestMissingInRegularAndScriptAsync( + public Task TestDefiniteAssignment6() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -728,12 +679,10 @@ void M() } } """); - } [Fact] - public async Task TestDefiniteAssignment7() - { - await TestMissingInRegularAndScriptAsync( + public Task TestDefiniteAssignment7() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -749,12 +698,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28821")] - public async Task TestDefiniteAssignment8() - { - await TestMissingInRegularAndScriptAsync( + public Task TestDefiniteAssignment8() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -776,12 +723,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28866")] - public async Task TestWrittenExpressionBeforeNullCheck() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWrittenExpressionBeforeNullCheck() + => TestMissingInRegularAndScriptAsync( """ class Goo { @@ -800,12 +745,10 @@ void DoGoo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15957")] - public async Task TestTrivia1() - { - await TestInRegularAndScript1Async( + public Task TestTrivia1() + => TestInRegularAndScript1Async( """ class C { @@ -837,12 +780,10 @@ void M(object y) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17129")] - public async Task TestTrivia2() - { - await TestInRegularAndScript1Async( + public Task TestTrivia2() + => TestInRegularAndScript1Async( """ using System; namespace N @@ -884,12 +825,10 @@ public static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17122")] - public async Task TestMissingOnNullableType() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnNullableType() + => TestMissingInRegularAndScriptAsync( """ using System; namespace N @@ -906,12 +845,10 @@ public static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18053")] - public async Task TestMissingWhenTypesDoNotMatch() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWhenTypesDoNotMatch() + => TestMissingInRegularAndScriptAsync( """ class SyntaxNode { @@ -940,12 +877,10 @@ static void M(ParameterSyntax parameter) } } """); - } [Fact] - public async Task TestMissingOnWhileNoInline() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnWhileNoInline() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -958,12 +893,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestWhileDefiniteAssignment1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWhileDefiniteAssignment1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -978,12 +911,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestWhileDefiniteAssignment2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWhileDefiniteAssignment2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -998,12 +929,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestWhileDefiniteAssignment3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWhileDefiniteAssignment3() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1017,12 +946,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestWhileDefiniteAssignment4() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWhileDefiniteAssignment4() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1036,12 +963,10 @@ void M(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23504")] - public async Task DoNotChangeOriginalFormatting1() - { - await TestInRegularAndScript1Async( + public Task DoNotChangeOriginalFormatting1() + => TestInRegularAndScript1Async( """ class Program { @@ -1069,12 +994,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23504")] - public async Task DoNotChangeOriginalFormatting2() - { - await TestInRegularAndScript1Async( + public Task DoNotChangeOriginalFormatting2() + => TestInRegularAndScript1Async( """ class Program { @@ -1098,12 +1021,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21172")] - public async Task TestMissingWithDynamic() - { - await TestMissingAsync( + public Task TestMissingWithDynamic() + => TestMissingAsync( """ class C { @@ -1116,12 +1037,10 @@ void M(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21551")] - public async Task TestOverloadedUserOperator() - { - await TestMissingAsync( + public Task TestOverloadedUserOperator() + => TestMissingAsync( """ class C { @@ -1137,12 +1056,10 @@ public static void Main() public static bool operator !=(C c1, C c2) => false; } """); - } [Fact] - public async Task TestNegativeDefiniteAssignment1() - { - await TestInRegularAndScript1Async( + public Task TestNegativeDefiniteAssignment1() + => TestInRegularAndScript1Async( """ class C { @@ -1164,12 +1081,10 @@ string M(object o) } } """, parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); - } [Fact] - public async Task TestNegativeDefiniteAssignment2() - { - await TestInRegularAndScript1Async( + public Task TestNegativeDefiniteAssignment2() + => TestInRegularAndScript1Async( """ class C { @@ -1203,12 +1118,10 @@ string M(object o, bool b) } } """, parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25993")] - public async Task TestEmbeddedStatement1() - { - await TestInRegularAndScript1Async( + public Task TestEmbeddedStatement1() + => TestInRegularAndScript1Async( """ class C { @@ -1244,12 +1157,10 @@ void M(object e) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25993")] - public async Task TestEmbeddedStatement2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestEmbeddedStatement2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1268,12 +1179,10 @@ void M(object e) } } """); - } [Fact] - public async Task TestUseBeforeDeclaration() - { - await TestMissingInRegularAndScriptAsync( + public Task TestUseBeforeDeclaration() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1294,12 +1203,10 @@ void M(object e) } """); - } [Fact] - public async Task TestPossiblyUnassigned() - { - await TestMissingInRegularAndScriptAsync( + public Task TestPossiblyUnassigned() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1322,12 +1229,10 @@ void M(object e) } } """); - } [Fact] - public async Task TestOutOfScope() - { - await TestMissingInRegularAndScriptAsync( + public Task TestOutOfScope() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1348,12 +1253,10 @@ void M(object e) } } """); - } [Fact] - public async Task TestDeclarationOnOuterBlock() - { - await TestInRegularAndScript1Async( + public Task TestDeclarationOnOuterBlock() + => TestInRegularAndScript1Async( """ class C { @@ -1387,12 +1290,10 @@ void M(object e) } } """); - } [Fact] - public async Task TestConditionalExpression() - { - await TestInRegularAndScript1Async( + public Task TestConditionalExpression() + => TestInRegularAndScript1Async( """ class C { @@ -1412,12 +1313,10 @@ void M(object e) } } """); - } [Fact] - public async Task TestConditionalExpression_OppositeBranch() - { - await TestMissingInRegularAndScriptAsync( + public Task TestConditionalExpression_OppositeBranch() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1428,12 +1327,10 @@ void M(object e) } } """); - } [Fact] - public async Task TestForStatement_NoInlineTypeCheck() - { - await TestMissingInRegularAndScriptAsync( + public Task TestForStatement_NoInlineTypeCheck() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1444,12 +1341,10 @@ void M(object e) } } """); - } [Fact] - public async Task TestForStatement_InlineTypeCheck() - { - await TestInRegularAndScript1Async( + public Task TestForStatement_InlineTypeCheck() + => TestInRegularAndScript1Async( """ class C { @@ -1469,12 +1364,10 @@ void M(object e) } } """, parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); - } [Fact] - public async Task TestForStatement_InScope() - { - await TestInRegularAndScript1Async( + public Task TestForStatement_InScope() + => TestInRegularAndScript1Async( """ class C { @@ -1500,12 +1393,10 @@ void M(object e) } } """, parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); - } [Fact] - public async Task TestForStatement_NotAssignedBeforeAccess() - { - await TestMissingInRegularAndScriptAsync( + public Task TestForStatement_NotAssignedBeforeAccess() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1520,12 +1411,10 @@ void M(object e) } } """); - } [Fact] - public async Task TestForStatement_AssignedBeforeAccess() - { - await TestInRegularAndScript1Async( + public Task TestForStatement_AssignedBeforeAccess() + => TestInRegularAndScript1Async( """ class C { @@ -1555,12 +1444,10 @@ void M(object e, bool b) } } """, parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); - } [Fact] - public async Task TestForStatement_MultipleDeclarators() - { - await TestInRegularAndScript1Async( + public Task TestForStatement_MultipleDeclarators() + => TestInRegularAndScript1Async( """ class C { @@ -1587,12 +1474,10 @@ void M(object e) } } """, parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); - } [Fact] - public async Task TestForStatement_UseBeforeDeclaration() - { - await TestMissingInRegularAndScriptAsync( + public Task TestForStatement_UseBeforeDeclaration() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1606,12 +1491,10 @@ void M(object e) } } """); - } [Fact] - public async Task TestForStatement_Initializer() - { - await TestMissingInRegularAndScriptAsync( + public Task TestForStatement_Initializer() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1625,12 +1508,10 @@ void M(object e) } } """); - } [Fact] - public async Task TestLocalFunction() - { - await TestInRegularAndScript1Async( + public Task TestLocalFunction() + => TestInRegularAndScript1Async( """ class C { @@ -1650,12 +1531,10 @@ void M(object e) } } """, parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); - } [Fact] - public async Task TestLocalFunction_UseOutOfScope() - { - await TestMissingInRegularAndScriptAsync( + public Task TestLocalFunction_UseOutOfScope() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1667,12 +1546,10 @@ C M(object e) } } """); - } [Fact] - public async Task TestExpressionLambda() - { - await TestInRegularAndScript1Async( + public Task TestExpressionLambda() + => TestInRegularAndScript1Async( """ class C { @@ -1692,12 +1569,10 @@ void M(object e) } } """, parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); - } [Fact] - public async Task TestExpressionLambda_UseOutOfScope() - { - await TestMissingInRegularAndScriptAsync( + public Task TestExpressionLambda_UseOutOfScope() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1709,12 +1584,10 @@ C M(object e) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31388")] - public async Task TestUseBetweenAssignmentAndIfCondition() - { - await TestMissingInRegularAndScriptAsync( + public Task TestUseBetweenAssignmentAndIfCondition() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1731,12 +1604,10 @@ void M(object o) void M2(bool b) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40007")] - public async Task TestSpaceAfterGenericType() - { - await TestInRegularAndScript1Async( + public Task TestSpaceAfterGenericType() + => TestInRegularAndScript1Async( """ #nullable enable @@ -1774,12 +1645,10 @@ static void Goo(object items) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45596")] - public async Task TestMissingInUsingDeclaration() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingInUsingDeclaration() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1792,12 +1661,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45596")] - public async Task TestMissingInUsingStatement() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingInUsingStatement() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1812,12 +1679,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37398")] - public async Task TestPrecedingDirectiveTrivia() - { - await TestInRegularAndScript1Async( + public Task TestPrecedingDirectiveTrivia() + => TestInRegularAndScript1Async( """ class C { @@ -1851,12 +1716,10 @@ public static void M(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40006")] - public async Task TestArrayOfNullables() - { - await TestInRegularAndScript1Async( + public Task TestArrayOfNullables() + => TestInRegularAndScript1Async( """ #nullable enable @@ -1886,12 +1749,10 @@ static void Set(object obj, object? item) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/55782")] - public async Task TestLocalReferencedAcrossScopes1() - { - var code = """ + public Task TestLocalReferencedAcrossScopes1() + => TestMissingInRegularAndScriptAsync(""" using System.Transactions; class BaseObject { } @@ -1932,15 +1793,11 @@ static int Main(string[] args) return 0; } } - """; - - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/55782")] - public async Task TestLocalReferencedAcrossScopes2() - { - await TestInRegularAndScript1Async(""" + public Task TestLocalReferencedAcrossScopes2() + => TestInRegularAndScript1Async(""" using System.Transactions; class BaseObject { } @@ -2021,12 +1878,10 @@ static int Main(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37875")] - public async Task TestNullableWhenWrittenTo1() - { - await TestInRegularAndScript1Async(""" + public Task TestNullableWhenWrittenTo1() + => TestInRegularAndScript1Async(""" #nullable enable using System; @@ -2055,12 +1910,10 @@ static void Goo(object o1, object o2) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37875")] - public async Task TestNullableWhenWrittenTo2() - { - await TestInRegularAndScript1Async(""" + public Task TestNullableWhenWrittenTo2() + => TestInRegularAndScript1Async(""" #nullable enable using System; @@ -2091,12 +1944,10 @@ static void Goo(object o1, object o2) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37875")] - public async Task TestNullableWhenWrittenTo3() - { - await TestMissingInRegularAndScriptAsync(""" + public Task TestNullableWhenWrittenTo3() + => TestMissingInRegularAndScriptAsync(""" #nullable enable using System; @@ -2112,12 +1963,10 @@ static void Goo(object o1, object o2) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37875")] - public async Task TestNullableWhenWrittenTo4() - { - await TestMissingInRegularAndScriptAsync(""" + public Task TestNullableWhenWrittenTo4() + => TestMissingInRegularAndScriptAsync(""" #nullable enable using System; @@ -2133,12 +1982,10 @@ static void Goo(object o1, object o2) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39600")] - public async Task TestNotWithInterveningMutation() - { - await TestMissingInRegularAndScriptAsync(""" + public Task TestNotWithInterveningMutation() + => TestMissingInRegularAndScriptAsync(""" using System; class Program @@ -2155,5 +2002,4 @@ void Goo(object[] values, int index) } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpAsAndNullCheckTests_FixAllTests.cs b/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpAsAndNullCheckTests_FixAllTests.cs index 30616278ee4fa..4fc2f134ef58e 100644 --- a/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpAsAndNullCheckTests_FixAllTests.cs +++ b/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpAsAndNullCheckTests_FixAllTests.cs @@ -16,9 +16,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UsePatternMatching; public sealed partial class CSharpAsAndNullCheckTests { [Fact] - public async Task FixAllInDocument1() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument1() + => TestInRegularAndScriptAsync( """ class C { @@ -70,12 +69,10 @@ int M() } } """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8)); - } [Fact] - public async Task FixAllInDocument1_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument1_CSharp9() + => TestInRegularAndScriptAsync( """ class C { @@ -127,12 +124,10 @@ int M() } } """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); - } [Fact] - public async Task FixAllInDocument2() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument2() + => TestInRegularAndScriptAsync( """ class Symbol { @@ -182,12 +177,10 @@ void M(object o, bool b0, bool b1) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26679")] - public async Task FixAllInDocument3() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument3() + => TestInRegularAndScriptAsync( """ class Test { @@ -251,12 +244,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26680")] - public async Task FixAllInDocument4() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument4() + => TestInRegularAndScriptAsync( """ class Test { @@ -283,5 +274,4 @@ void M() } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpIsAndCastCheckDiagnosticAnalyzerTests.cs b/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpIsAndCastCheckDiagnosticAnalyzerTests.cs index d37ac35f44286..a4a169103b22a 100644 --- a/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpIsAndCastCheckDiagnosticAnalyzerTests.cs +++ b/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpIsAndCastCheckDiagnosticAnalyzerTests.cs @@ -31,9 +31,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider => (new CSharpIsAndCastCheckDiagnosticAnalyzer(), new CSharpIsAndCastCheckCodeFixProvider()); [Fact] - public async Task InlineTypeCheck1() - { - await TestInRegularAndScript1Async( + public Task InlineTypeCheck1() + => TestInRegularAndScript1Async( """ class C { @@ -57,12 +56,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingInCSharp6() - { - await TestMissingAsync( + public Task TestMissingInCSharp6() + => TestMissingAsync( """ class C { @@ -75,12 +72,10 @@ void M() } } """, new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); - } [Fact] - public async Task TestMissingInWrongName() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingInWrongName() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -93,12 +88,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingInWrongType() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingInWrongType() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -111,12 +104,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingOnMultiVar() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnMultiVar() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -129,12 +120,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingOnNonDeclaration() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnNonDeclaration() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -147,12 +136,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingOnAsExpression() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnAsExpression() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -165,12 +152,10 @@ void M() } } """); - } [Fact] - public async Task InlineTypeCheckComplexExpression1() - { - await TestInRegularAndScript1Async( + public Task InlineTypeCheckComplexExpression1() + => TestInRegularAndScript1Async( """ class C { @@ -194,12 +179,10 @@ void M() } } """); - } [Fact] - public async Task TestInlineTypeCheckWithElse() - { - await TestInRegularAndScript1Async( + public Task TestInlineTypeCheckWithElse() + => TestInRegularAndScript1Async( """ class C { @@ -229,12 +212,10 @@ void M() } } """); - } [Fact] - public async Task TestComments1() - { - await TestInRegularAndScript1Async( + public Task TestComments1() + => TestInRegularAndScript1Async( """ class C { @@ -260,12 +241,10 @@ void M() } } """); - } [Fact] - public async Task TestComments2() - { - await TestInRegularAndScript1Async( + public Task TestComments2() + => TestInRegularAndScript1Async( """ class C { @@ -290,12 +269,10 @@ void M() } } """); - } [Fact] - public async Task TestComments3() - { - await TestInRegularAndScript1Async( + public Task TestComments3() + => TestInRegularAndScript1Async( """ class C { @@ -322,12 +299,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17126")] - public async Task TestComments4() - { - await TestInRegularAndScript1Async( + public Task TestComments4() + => TestInRegularAndScript1Async( """ using System; namespace N { @@ -364,12 +339,10 @@ public static void Main() } } """); - } [Fact] - public async Task InlineTypeCheckParenthesized1() - { - await TestInRegularAndScript1Async( + public Task InlineTypeCheckParenthesized1() + => TestInRegularAndScript1Async( """ class C { @@ -393,12 +366,10 @@ void M() } } """); - } [Fact] - public async Task InlineTypeCheckParenthesized2() - { - await TestInRegularAndScript1Async( + public Task InlineTypeCheckParenthesized2() + => TestInRegularAndScript1Async( """ class C { @@ -422,12 +393,10 @@ void M() } } """); - } [Fact] - public async Task InlineTypeCheckParenthesized3() - { - await TestInRegularAndScript1Async( + public Task InlineTypeCheckParenthesized3() + => TestInRegularAndScript1Async( """ class C { @@ -451,12 +420,10 @@ void M() } } """); - } [Fact] - public async Task InlineTypeCheckScopeConflict1() - { - await TestMissingInRegularAndScriptAsync( + public Task InlineTypeCheckScopeConflict1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -473,12 +440,10 @@ void M() } } """); - } [Fact] - public async Task InlineTypeCheckScopeConflict2() - { - await TestMissingInRegularAndScriptAsync( + public Task InlineTypeCheckScopeConflict2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -496,12 +461,10 @@ void M() } } """); - } [Fact] - public async Task InlineTypeCheckScopeConflict3() - { - await TestMissingInRegularAndScriptAsync( + public Task InlineTypeCheckScopeConflict3() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -519,12 +482,10 @@ void M() } } """); - } [Fact] - public async Task InlineTypeCheckScopeNonConflict1() - { - await TestInRegularAndScript1Async( + public Task InlineTypeCheckScopeNonConflict1() + => TestInRegularAndScript1Async( """ class C { @@ -560,12 +521,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18053")] - public async Task TestMissingWhenTypesDoNotMatch() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWhenTypesDoNotMatch() + => TestMissingInRegularAndScriptAsync( """ class SyntaxNode { @@ -593,12 +552,10 @@ static void N(ParameterSyntax parameter) } } """); - } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/429612")] - public async Task TestMissingWithNullableType() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWithNullableType() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -613,12 +570,10 @@ public object Convert(object value) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21172")] - public async Task TestMissingWithDynamic() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWithDynamic() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -633,7 +588,6 @@ public object Convert(object value) } } """); - } [Fact] public async Task TestSeverity() @@ -663,9 +617,8 @@ void M() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24287")] - public async Task TestWithVariableDesignation1() - { - await TestInRegularAndScriptAsync( + public Task TestWithVariableDesignation1() + => TestInRegularAndScriptAsync( """ public class Test { @@ -695,12 +648,10 @@ public void TestIt(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24287")] - public async Task TestWithVariableDesignation2() - { - await TestMissingAsync( + public Task TestWithVariableDesignation2() + => TestMissingAsync( """ public class Test { @@ -716,12 +667,10 @@ public void TestIt(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24287")] - public async Task TestWithVariableDesignation3() - { - await TestMissingAsync( + public Task TestWithVariableDesignation3() + => TestMissingAsync( """ public class Test { @@ -742,12 +691,10 @@ private bool TryGetValue(object o, out string result) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42462")] - public async Task TestWithLocalInsideTryBlock() - { - await TestInRegularAndScript1Async( + public Task TestWithLocalInsideTryBlock() + => TestInRegularAndScript1Async( """ class Program { @@ -789,5 +736,4 @@ static void Main(string[] args) } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpIsAndCastCheckDiagnosticAnalyzerTests_FixAllTests.cs b/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpIsAndCastCheckDiagnosticAnalyzerTests_FixAllTests.cs index ca571d54a03a0..cd88700b504aa 100644 --- a/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpIsAndCastCheckDiagnosticAnalyzerTests_FixAllTests.cs +++ b/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpIsAndCastCheckDiagnosticAnalyzerTests_FixAllTests.cs @@ -14,9 +14,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UsePatternMatching; public sealed partial class CSharpIsAndCastCheckDiagnosticAnalyzerTests { [Fact] - public async Task FixAllInDocument1() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument1() + => TestInRegularAndScriptAsync( """ class C { @@ -49,12 +48,10 @@ void M() } } """); - } [Fact] - public async Task FixAllInDocument2() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument2() + => TestInRegularAndScriptAsync( """ class C { @@ -87,5 +84,4 @@ void M() } } """); - } } diff --git a/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpUseNotPatternTests.cs b/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpUseNotPatternTests.cs index 61eaf6bb18864..b869063a728be 100644 --- a/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpUseNotPatternTests.cs +++ b/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpUseNotPatternTests.cs @@ -20,9 +20,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UsePatternMatching; public sealed partial class CSharpUseNotPatternTests { [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50690")] - public async Task BinaryIsExpression() - { - await new VerifyCS.Test + public Task BinaryIsExpression() + => new VerifyCS.Test { TestCode = """ class C @@ -48,12 +47,10 @@ void M(object x) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task BinaryIsExpression2() - { - await new VerifyCS.Test + public Task BinaryIsExpression2() + => new VerifyCS.Test { TestCode = """ class C @@ -79,12 +76,10 @@ void M(object x) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50690")] - public async Task ConstantPattern() - { - await new VerifyCS.Test + public Task ConstantPattern() + => new VerifyCS.Test { TestCode = """ class C @@ -110,12 +105,10 @@ void M(object x) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64292")] - public async Task BooleanValueConstantPattern() - { - await new VerifyCS.Test + public Task BooleanValueConstantPattern() + => new VerifyCS.Test { TestCode = """ class C @@ -141,12 +134,10 @@ void M(bool x) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64292")] - public async Task NonBooleanValueConstantPattern() - { - await new VerifyCS.Test + public Task NonBooleanValueConstantPattern() + => new VerifyCS.Test { TestCode = """ class C @@ -172,12 +163,10 @@ void M(object x) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46699")] - public async Task UseNotPattern() - { - await new VerifyCS.Test + public Task UseNotPattern() + => new VerifyCS.Test { TestCode = """ class C @@ -203,12 +192,10 @@ void M(object x) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72370")] - public async Task UseNotPattern2() - { - await new VerifyCS.Test + public Task UseNotPattern2() + => new VerifyCS.Test { TestCode = """ public class Program @@ -246,12 +233,10 @@ public static void Main() """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72370")] - public async Task UseNotPattern3() - { - await new VerifyCS.Test + public Task UseNotPattern3() + => new VerifyCS.Test { TestCode = """ public class Program @@ -283,12 +268,10 @@ public static void Main(object O) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task UnavailableInCSharp8() - { - await new VerifyCS.Test + public Task UnavailableInCSharp8() + => new VerifyCS.Test { TestCode = """ class C @@ -303,12 +286,10 @@ void M(object x) """, LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50690")] - public async Task BinaryIsObject() - { - await new VerifyCS.Test + public Task BinaryIsObject() + => new VerifyCS.Test { TestCode = """ class C @@ -334,12 +315,10 @@ void M(object x) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50690")] - public async Task BinaryIsObject2() - { - await new VerifyCS.Test + public Task BinaryIsObject2() + => new VerifyCS.Test { TestCode = """ class C @@ -365,12 +344,10 @@ void M(object x) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task BinaryIsObject3() - { - await new VerifyCS.Test + public Task BinaryIsObject3() + => new VerifyCS.Test { TestCode = """ using System; @@ -400,12 +377,10 @@ void M(object x) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68784")] - public async Task NotInExpressionTree() - { - await new VerifyCS.Test + public Task NotInExpressionTree() + => new VerifyCS.Test { TestCode = """ using System.Linq; @@ -420,12 +395,10 @@ IQueryable M(IQueryable query) """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70964")] - public async Task TestMissingOnNullable1() - { - await new VerifyCS.Test + public Task TestMissingOnNullable1() + => new VerifyCS.Test { TestCode = """ using System; @@ -443,12 +416,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70964")] - public async Task TestMissingOnNullable2() - { - await new VerifyCS.Test + public Task TestMissingOnNullable2() + => new VerifyCS.Test { TestCode = """ using System; @@ -466,12 +437,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/62078")] - public async Task TestTypeVersusMemberAmbiguity() - { - await new VerifyCS.Test + public Task TestTypeVersusMemberAmbiguity() + => new VerifyCS.Test { TestCode = """ class Color { } @@ -506,5 +475,4 @@ void M(object x) LanguageVersion = LanguageVersion.CSharp9, CodeActionValidationMode = Testing.CodeActionValidationMode.None, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UsePrimaryConstructor/UsePrimaryConstructorTests.cs b/src/Analyzers/CSharp/Tests/UsePrimaryConstructor/UsePrimaryConstructorTests.cs index 238322577e0f9..d3fc50bded192 100644 --- a/src/Analyzers/CSharp/Tests/UsePrimaryConstructor/UsePrimaryConstructorTests.cs +++ b/src/Analyzers/CSharp/Tests/UsePrimaryConstructor/UsePrimaryConstructorTests.cs @@ -20,9 +20,8 @@ namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.UsePrimaryConstructo public sealed class UsePrimaryConstructorTests { [Fact] - public async Task TestInCSharp12() - { - await new VerifyCS.Test + public Task TestInCSharp12() + => new VerifyCS.Test { TestCode = """ class C @@ -39,12 +38,10 @@ class C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotInCSharp11() - { - await new VerifyCS.Test + public Task TestNotInCSharp11() + => new VerifyCS.Test { TestCode = """ class C @@ -56,12 +53,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp11, }.RunAsync(); - } [Fact] - public async Task TestNotWithNonPublicConstructor() - { - await new VerifyCS.Test + public Task TestNotWithNonPublicConstructor() + => new VerifyCS.Test { TestCode = """ class C @@ -73,12 +68,10 @@ private C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestStruct() - { - await new VerifyCS.Test + public Task TestStruct() + => new VerifyCS.Test { TestCode = """ struct C @@ -95,12 +88,10 @@ struct C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithUnchainedConstructor() - { - await new VerifyCS.Test + public Task TestNotWithUnchainedConstructor() + => new VerifyCS.Test { TestCode = """ class C @@ -116,12 +107,10 @@ public C() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithThisChainedConstructor() - { - await new VerifyCS.Test + public Task TestWithThisChainedConstructor() + => new VerifyCS.Test { TestCode = """ class C @@ -145,12 +134,10 @@ public C() : this(0) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithBaseChainedConstructor1() - { - await new VerifyCS.Test + public Task TestWithBaseChainedConstructor1() + => new VerifyCS.Test { TestCode = """ class B(int i) @@ -182,12 +169,10 @@ public C() : this(0) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithBaseChainedConstructor2() - { - await new VerifyCS.Test + public Task TestWithBaseChainedConstructor2() + => new VerifyCS.Test { TestCode = """ class B(int i) @@ -219,12 +204,10 @@ public C() : this(0) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithBaseChainedConstructor3() - { - await new VerifyCS.Test + public Task TestWithBaseChainedConstructor3() + => new VerifyCS.Test { TestCode = """ class B(int i, int j) @@ -258,12 +241,10 @@ public C() : this(0, 0) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithBaseChainedConstructor4() - { - await new VerifyCS.Test + public Task TestWithBaseChainedConstructor4() + => new VerifyCS.Test { TestCode = """ class B(int i, int j) @@ -297,12 +278,10 @@ public C() : this(0, 0) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithBaseChainedConstructor5() - { - await new VerifyCS.Test + public Task TestWithBaseChainedConstructor5() + => new VerifyCS.Test { TestCode = """ class B(int i, int j) @@ -338,12 +317,10 @@ public C() : this(0, 0) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithBadExpressionBody() - { - await new VerifyCS.Test + public Task TestNotWithBadExpressionBody() + => new VerifyCS.Test { TestCode = """ class C @@ -354,12 +331,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithBadBlockBody() - { - await new VerifyCS.Test + public Task TestNotWithBadBlockBody() + => new VerifyCS.Test { TestCode = """ class C @@ -372,12 +347,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithExpressionBodyAssignmentToField1() - { - await new VerifyCS.Test + public Task TestWithExpressionBodyAssignmentToField1() + => new VerifyCS.Test { TestCode = """ class C @@ -396,12 +369,10 @@ class C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithExpressionBodyAssignmentToProperty1() - { - await new VerifyCS.Test + public Task TestWithExpressionBodyAssignmentToProperty1() + => new VerifyCS.Test { TestCode = """ class C @@ -420,12 +391,10 @@ class C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithExpressionBodyAssignmentToField2() - { - await new VerifyCS.Test + public Task TestWithExpressionBodyAssignmentToField2() + => new VerifyCS.Test { TestCode = """ class C @@ -444,12 +413,10 @@ class C(int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithExpressionBodyAssignmentToField3() - { - await new VerifyCS.Test + public Task TestWithExpressionBodyAssignmentToField3() + => new VerifyCS.Test { TestCode = """ class C @@ -468,12 +435,10 @@ class C(int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithAssignmentToBaseField1() - { - await new VerifyCS.Test + public Task TestNotWithAssignmentToBaseField1() + => new VerifyCS.Test { TestCode = """ class B @@ -489,12 +454,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithAssignmentToBaseField2() - { - await new VerifyCS.Test + public Task TestNotWithAssignmentToBaseField2() + => new VerifyCS.Test { TestCode = """ class B @@ -510,12 +473,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithCompoundAssignmentToField() - { - await new VerifyCS.Test + public Task TestNotWithCompoundAssignmentToField() + => new VerifyCS.Test { TestCode = """ class C @@ -528,12 +489,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithTwoWritesToTheSameMember() - { - await new VerifyCS.Test + public Task TestNotWithTwoWritesToTheSameMember() + => new VerifyCS.Test { TestCode = """ class C @@ -549,12 +508,10 @@ public C(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithComplexRightSide1() - { - await new VerifyCS.Test + public Task TestWithComplexRightSide1() + => new VerifyCS.Test { TestCode = """ class C @@ -573,12 +530,10 @@ class C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestBlockWithMultipleAssignments1() - { - await new VerifyCS.Test + public Task TestBlockWithMultipleAssignments1() + => new VerifyCS.Test { TestCode = """ class C @@ -602,12 +557,10 @@ class C(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestBlockWithMultipleAssignments2() - { - await new VerifyCS.Test + public Task TestBlockWithMultipleAssignments2() + => new VerifyCS.Test { TestCode = """ class C @@ -629,12 +582,10 @@ class C(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestRemoveMembers1() - { - await new VerifyCS.Test + public Task TestRemoveMembers1() + => new VerifyCS.Test { TestCode = """ class C @@ -657,12 +608,10 @@ class C(int i, int j) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestRemoveMembers2() - { - await new VerifyCS.Test + public Task TestRemoveMembers2() + => new VerifyCS.Test { TestCode = """ class C @@ -685,12 +634,10 @@ class C(int i, int j) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestRemoveMembersOnlyWithMatchingType() - { - await new VerifyCS.Test + public Task TestRemoveMembersOnlyWithMatchingType() + => new VerifyCS.Test { TestCode = """ class C @@ -714,12 +661,10 @@ class C(int i, int j) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestDoNotRemovePublicMembers1() - { - await new VerifyCS.Test + public Task TestDoNotRemovePublicMembers1() + => new VerifyCS.Test { TestCode = """ class C @@ -737,12 +682,10 @@ class C CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task DoNotRemoveMembersUsedInNestedTypes() - { - await new VerifyCS.Test + public Task DoNotRemoveMembersUsedInNestedTypes() + => new VerifyCS.Test { TestCode = """ using System; @@ -792,12 +735,10 @@ public Enumerator(OuterType c) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestRemoveMembersUpdateReferences1() - { - await new VerifyCS.Test + public Task TestRemoveMembersUpdateReferences1() + => new VerifyCS.Test { TestCode = """ using System; @@ -831,12 +772,10 @@ void M() CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestRemoveMembersUpdateReferences2() - { - await new VerifyCS.Test + public Task TestRemoveMembersUpdateReferences2() + => new VerifyCS.Test { TestCode = """ using System; @@ -870,12 +809,10 @@ void M() CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestRemoveMembersUpdateReferencesWithRename1() - { - await new VerifyCS.Test + public Task TestRemoveMembersUpdateReferencesWithRename1() + => new VerifyCS.Test { TestCode = """ using System; @@ -909,12 +846,10 @@ void M() CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestRemoveMembersOnlyPrivateMembers() - { - await new VerifyCS.Test + public Task TestRemoveMembersOnlyPrivateMembers() + => new VerifyCS.Test { TestCode = """ using System; @@ -950,12 +885,10 @@ void M() CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestRemoveMembersOnlyMembersWithoutAttributes() - { - await new VerifyCS.Test + public Task TestRemoveMembersOnlyMembersWithoutAttributes() + => new VerifyCS.Test { TestCode = """ using System; @@ -993,12 +926,10 @@ void M() CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestRemoveMembersAccessedOffThis() - { - await new VerifyCS.Test + public Task TestRemoveMembersAccessedOffThis() + => new VerifyCS.Test { TestCode = """ using System; @@ -1036,12 +967,10 @@ void M(C c) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWhenRightSideReferencesThis1() - { - await new VerifyCS.Test + public Task TestNotWhenRightSideReferencesThis1() + => new VerifyCS.Test { TestCode = """ class C @@ -1058,12 +987,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWhenRightSideReferencesThis2() - { - await new VerifyCS.Test + public Task TestNotWhenRightSideReferencesThis2() + => new VerifyCS.Test { TestCode = """ class C @@ -1080,12 +1007,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWhenRightSideDoesNotReferenceThis() - { - await new VerifyCS.Test + public Task TestWhenRightSideDoesNotReferenceThis() + => new VerifyCS.Test { TestCode = """ class C @@ -1110,12 +1035,10 @@ class C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveConstructorDocCommentWhenNothingOnType_SingleLine_1() - { - await new VerifyCS.Test + public Task TestMoveConstructorDocCommentWhenNothingOnType_SingleLine_1() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1146,12 +1069,10 @@ class C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveConstructorDocCommentWhenNothingOnType_IfDef1() - { - await new VerifyCS.Test + public Task TestMoveConstructorDocCommentWhenNothingOnType_IfDef1() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1186,12 +1107,10 @@ class C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveConstructorDocCommentWhenNothingOnType_SingleLine_2() - { - await new VerifyCS.Test + public Task TestMoveConstructorDocCommentWhenNothingOnType_SingleLine_2() + => new VerifyCS.Test { TestCode = """ class C @@ -1216,12 +1135,10 @@ class C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveConstructorDocCommentWhenNothingOnType_MultiLine_1() - { - await new VerifyCS.Test + public Task TestMoveConstructorDocCommentWhenNothingOnType_MultiLine_1() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1264,12 +1181,10 @@ class C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveConstructorDocCommentWhenNothingOnType_MultiLine_2() - { - await new VerifyCS.Test + public Task TestMoveConstructorDocCommentWhenNothingOnType_MultiLine_2() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1308,12 +1223,10 @@ class C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveConstructorDocCommentWhenNothingOnType_MultiLine_3() - { - await new VerifyCS.Test + public Task TestMoveConstructorDocCommentWhenNothingOnType_MultiLine_3() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1348,12 +1261,10 @@ class C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveConstructorParamDocCommentsIntoTypeDocComments1() - { - await new VerifyCS.Test + public Task TestMoveConstructorParamDocCommentsIntoTypeDocComments1() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1397,12 +1308,10 @@ class C(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveConstructorParamDocCommentsIntoTypeDocComments2() - { - await new VerifyCS.Test + public Task TestMoveConstructorParamDocCommentsIntoTypeDocComments2() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1444,12 +1353,10 @@ class C(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestRemoveMembersMoveDocComments_WhenNoTypeDocComments1() - { - await new VerifyCS.Test + public Task TestRemoveMembersMoveDocComments_WhenNoTypeDocComments1() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1486,12 +1393,10 @@ class C(int i, int j) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestRemoveMembersMoveDocComments_WhenNoTypeDocComments_MembersWithDifferentNames1() - { - await new VerifyCS.Test + public Task TestRemoveMembersMoveDocComments_WhenNoTypeDocComments_MembersWithDifferentNames1() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1528,12 +1433,10 @@ class C(int i, int j) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestRemoveMembersMoveDocComments_WhenTypeDocComments1() - { - await new VerifyCS.Test + public Task TestRemoveMembersMoveDocComments_WhenTypeDocComments1() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1576,12 +1479,10 @@ class C(int i, int j) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestRemoveMembersKeepConstructorDocs1() - { - await new VerifyCS.Test + public Task TestRemoveMembersKeepConstructorDocs1() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1624,12 +1525,10 @@ class C(int i, int j) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestRemoveMembersKeepConstructorDocs2() - { - await new VerifyCS.Test + public Task TestRemoveMembersKeepConstructorDocs2() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1671,12 +1570,10 @@ class C(int i, int j) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestRemoveMembersKeepConstructorDocs3() - { - await new VerifyCS.Test + public Task TestRemoveMembersKeepConstructorDocs3() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1720,12 +1617,10 @@ class C(int i, int j) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestFixAll1() - { - await new VerifyCS.Test + public Task TestFixAll1() + => new VerifyCS.Test { TestCode = """ class C @@ -1753,12 +1648,10 @@ class D(int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestFixAll2() - { - await new VerifyCS.Test + public Task TestFixAll2() + => new VerifyCS.Test { TestCode = """ class C @@ -1785,12 +1678,10 @@ class D(int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestFixAll3() - { - await new VerifyCS.Test + public Task TestFixAll3() + => new VerifyCS.Test { TestCode = """ class C @@ -1826,12 +1717,10 @@ class D(int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestFixAll4() - { - await new VerifyCS.Test + public Task TestFixAll4() + => new VerifyCS.Test { TestCode = """ using System; @@ -1887,12 +1776,10 @@ void N() CodeActionIndex = 1, NumberOfFixAllIterations = 1, }.RunAsync(); - } [Fact] - public async Task TestMoveConstructorAttributes1() - { - await new VerifyCS.Test + public Task TestMoveConstructorAttributes1() + => new VerifyCS.Test { TestCode = """ using System; @@ -1913,12 +1800,10 @@ class C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveConstructorAttributes1A() - { - await new VerifyCS.Test + public Task TestMoveConstructorAttributes1A() + => new VerifyCS.Test { TestCode = """ using System; @@ -1941,12 +1826,10 @@ class C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveConstructorAttributes2() - { - await new VerifyCS.Test + public Task TestMoveConstructorAttributes2() + => new VerifyCS.Test { TestCode = """ using System; @@ -1975,12 +1858,10 @@ class C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveConstructorAttributes2A() - { - await new VerifyCS.Test + public Task TestMoveConstructorAttributes2A() + => new VerifyCS.Test { TestCode = """ using System; @@ -2011,12 +1892,10 @@ class C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveConstructorAttributes3() - { - await new VerifyCS.Test + public Task TestMoveConstructorAttributes3() + => new VerifyCS.Test { TestCode = """ using System; @@ -2048,12 +1927,10 @@ class C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveConstructorAttributes3A() - { - await new VerifyCS.Test + public Task TestMoveConstructorAttributes3A() + => new VerifyCS.Test { TestCode = """ using System; @@ -2087,12 +1964,10 @@ class C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveConstructorAttributes4() - { - await new VerifyCS.Test + public Task TestMoveConstructorAttributes4() + => new VerifyCS.Test { TestCode = """ using System; @@ -2119,12 +1994,10 @@ class C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveConstructorAttributes4A() - { - await new VerifyCS.Test + public Task TestMoveConstructorAttributes4A() + => new VerifyCS.Test { TestCode = """ using System; @@ -2154,12 +2027,10 @@ class C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultipleParametersMove1() - { - await new VerifyCS.Test + public Task TestMultipleParametersMove1() + => new VerifyCS.Test { TestCode = """ using System; @@ -2182,12 +2053,10 @@ class C(int i, """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultipleParametersMove1A() - { - await new VerifyCS.Test + public Task TestMultipleParametersMove1A() + => new VerifyCS.Test { TestCode = """ using System; @@ -2216,12 +2085,10 @@ class C(int i, """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultipleParametersMove2() - { - await new VerifyCS.Test + public Task TestMultipleParametersMove2() + => new VerifyCS.Test { TestCode = """ using System; @@ -2246,12 +2113,10 @@ class C( """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultipleParametersMove2A() - { - await new VerifyCS.Test + public Task TestMultipleParametersMove2A() + => new VerifyCS.Test { TestCode = """ using System; @@ -2282,12 +2147,10 @@ class C( """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultipleParametersMove3() - { - await new VerifyCS.Test + public Task TestMultipleParametersMove3() + => new VerifyCS.Test { TestCode = """ using System; @@ -2310,12 +2173,10 @@ class C( """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultipleParametersMove3A() - { - await new VerifyCS.Test + public Task TestMultipleParametersMove3A() + => new VerifyCS.Test { TestCode = """ using System; @@ -2344,12 +2205,10 @@ class C( """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultipleParametersMove4() - { - await new VerifyCS.Test + public Task TestMultipleParametersMove4() + => new VerifyCS.Test { TestCode = """ using System; @@ -2374,12 +2233,10 @@ class C( """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultipleParametersMove4A() - { - await new VerifyCS.Test + public Task TestMultipleParametersMove4A() + => new VerifyCS.Test { TestCode = """ using System; @@ -2410,12 +2267,10 @@ class C( """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestReferenceToNestedType1() - { - await new VerifyCS.Test + public Task TestReferenceToNestedType1() + => new VerifyCS.Test { TestCode = """ class C @@ -2439,12 +2294,10 @@ public class D """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestReferenceToNestedType2() - { - await new VerifyCS.Test + public Task TestReferenceToNestedType2() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -2472,12 +2325,10 @@ public class D """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestReferenceToNestedType3() - { - await new VerifyCS.Test + public Task TestReferenceToNestedType3() + => new VerifyCS.Test { TestCode = """ class C @@ -2501,12 +2352,10 @@ public class D """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestReferenceToNestedType4() - { - await new VerifyCS.Test + public Task TestReferenceToNestedType4() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -2534,12 +2383,10 @@ public class D """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70586")] - public async Task TestReferenceToNestedType5() - { - await new VerifyCS.Test + public Task TestReferenceToNestedType5() + => new VerifyCS.Test { TestCode = """ public class B(B.A a) @@ -2564,12 +2411,10 @@ public class C(B.A a) : B(a) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithNonAutoProperty() - { - await new VerifyCS.Test + public Task TestNotWithNonAutoProperty() + => new VerifyCS.Test { TestCode = """ class C @@ -2585,12 +2430,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInParameter1() - { - await new VerifyCS.Test + public Task TestInParameter1() + => new VerifyCS.Test { TestCode = """ class C @@ -2611,12 +2454,10 @@ class C(in int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInParameter2() - { - await new VerifyCS.Test + public Task TestInParameter2() + => new VerifyCS.Test { TestCode = """ class C @@ -2637,12 +2478,10 @@ class C(int i) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithPreprocessorRegion1() - { - await new VerifyCS.Test + public Task TestNotWithPreprocessorRegion1() + => new VerifyCS.Test { TestCode = """ using System; @@ -2659,12 +2498,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithPreprocessorRegion2() - { - await new VerifyCS.Test + public Task TestNotWithPreprocessorRegion2() + => new VerifyCS.Test { TestCode = """ using System; @@ -2681,12 +2518,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithPreprocessorRegion3() - { - await new VerifyCS.Test + public Task TestNotWithPreprocessorRegion3() + => new VerifyCS.Test { TestCode = """ using System; @@ -2705,12 +2540,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithPreprocessorRegion4() - { - await new VerifyCS.Test + public Task TestNotWithPreprocessorRegion4() + => new VerifyCS.Test { TestCode = """ using System; @@ -2729,12 +2562,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithPreprocessorRegion5() - { - await new VerifyCS.Test + public Task TestNotWithPreprocessorRegion5() + => new VerifyCS.Test { TestCode = """ using System; @@ -2753,12 +2584,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithPreprocessorRegion6() - { - await new VerifyCS.Test + public Task TestNotWithPreprocessorRegion6() + => new VerifyCS.Test { TestCode = """ using System; @@ -2777,12 +2606,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithPreprocessorRegion7() - { - await new VerifyCS.Test + public Task TestNotWithPreprocessorRegion7() + => new VerifyCS.Test { TestCode = """ using System; @@ -2803,12 +2630,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithPreprocessorRegion8() - { - await new VerifyCS.Test + public Task TestNotWithPreprocessorRegion8() + => new VerifyCS.Test { TestCode = """ using System; @@ -2829,12 +2654,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithRegionDirective1() - { - await new VerifyCS.Test + public Task TestWithRegionDirective1() + => new VerifyCS.Test { TestCode = """ class C @@ -2862,12 +2685,10 @@ class C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithRegionDirective2() - { - await new VerifyCS.Test + public Task TestWithRegionDirective2() + => new VerifyCS.Test { TestCode = """ class C @@ -2903,12 +2724,10 @@ public C(string s) : this(s.Length) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestSeeTag1() - { - await new VerifyCS.Test + public Task TestSeeTag1() + => new VerifyCS.Test { TestCode = """ /// @@ -2935,12 +2754,10 @@ class C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestSeeTag2() - { - await new VerifyCS.Test + public Task TestSeeTag2() + => new VerifyCS.Test { TestCode = """ /// @@ -2967,12 +2784,10 @@ class C(int i) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestReferenceToConstantInParameterInitializer1() - { - await new VerifyCS.Test + public Task TestReferenceToConstantInParameterInitializer1() + => new VerifyCS.Test { TestCode = """ class C @@ -2995,12 +2810,10 @@ class C(int i = C.Default) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestReferenceToConstantInParameterInitializer2() - { - await new VerifyCS.Test + public Task TestReferenceToConstantInParameterInitializer2() + => new VerifyCS.Test { TestCode = """ class C @@ -3023,12 +2836,10 @@ class C(int i = C.Default) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestReferenceToConstantInParameterInitializer3() - { - await new VerifyCS.Test + public Task TestReferenceToConstantInParameterInitializer3() + => new VerifyCS.Test { TestCode = """ class C @@ -3051,12 +2862,10 @@ class C(int i = C.Default) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMergeConstructorSummaryIntoTypeDocComment() - { - await new VerifyCS.Test + public Task TestMergeConstructorSummaryIntoTypeDocComment() + => new VerifyCS.Test { TestCode = """ using System; @@ -3128,12 +2937,10 @@ internal readonly struct ManagedInstructionId( """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70658")] - public async Task TestPartialType1() - { - await new VerifyCS.Test + public Task TestPartialType1() + => new VerifyCS.Test { TestCode = """ class Base(int i) @@ -3166,12 +2973,10 @@ partial class C : Base """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70658")] - public async Task TestPartialType2() - { - await new VerifyCS.Test + public Task TestPartialType2() + => new VerifyCS.Test { TestCode = """ using System; @@ -3211,12 +3016,10 @@ partial class C : Base """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70658")] - public async Task TestPartialType3() - { - await new VerifyCS.Test + public Task TestPartialType3() + => new VerifyCS.Test { TestCode = """ class Base(int i) @@ -3249,12 +3052,10 @@ partial class C : Base """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70658")] - public async Task TestPartialType4() - { - await new VerifyCS.Test + public Task TestPartialType4() + => new VerifyCS.Test { TestCode = """ using System; @@ -3291,12 +3092,10 @@ partial class C : Base """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70868")] - public async Task TestSideEffects1() - { - await new VerifyCS.Test + public Task TestSideEffects1() + => new VerifyCS.Test { TestCode = """ class C @@ -3320,12 +3119,10 @@ class C(int value) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70868")] - public async Task TestSideEffects1_A() - { - await new VerifyCS.Test + public Task TestSideEffects1_A() + => new VerifyCS.Test { TestCode = """ class C @@ -3342,12 +3139,10 @@ public C(int value) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70868")] - public async Task TestSideEffects2() - { - await new VerifyCS.Test + public Task TestSideEffects2() + => new VerifyCS.Test { TestCode = """ class C @@ -3369,12 +3164,10 @@ class C(int value) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70868")] - public async Task TestSideEffects2_A() - { - await new VerifyCS.Test + public Task TestSideEffects2_A() + => new VerifyCS.Test { TestCode = """ class C @@ -3390,12 +3183,10 @@ public C(int value) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70868")] - public async Task TestSideEffects3() - { - await new VerifyCS.Test + public Task TestSideEffects3() + => new VerifyCS.Test { TestCode = """ class C @@ -3419,12 +3210,10 @@ class C(int value) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70868")] - public async Task TestSideEffects3_A() - { - await new VerifyCS.Test + public Task TestSideEffects3_A() + => new VerifyCS.Test { TestCode = """ class C @@ -3441,12 +3230,10 @@ public C(int value) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70868")] - public async Task TestSideEffects4() - { - await new VerifyCS.Test + public Task TestSideEffects4() + => new VerifyCS.Test { TestCode = """ partial class C @@ -3467,12 +3254,10 @@ partial class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70868")] - public async Task TestSideEffects5() - { - await new VerifyCS.Test + public Task TestSideEffects5() + => new VerifyCS.Test { TestCode = """ class C @@ -3496,12 +3281,10 @@ class C(int value1, int value2) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70868")] - public async Task TestSideEffects5_A() - { - await new VerifyCS.Test + public Task TestSideEffects5_A() + => new VerifyCS.Test { TestCode = """ class C @@ -3525,12 +3308,10 @@ class C(int value1, int value2) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70868")] - public async Task TestSideEffects6() - { - await new VerifyCS.Test + public Task TestSideEffects6() + => new VerifyCS.Test { TestCode = """ class C @@ -3554,12 +3335,10 @@ class C(int value) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70868")] - public async Task TestSideEffects6_A() - { - await new VerifyCS.Test + public Task TestSideEffects6_A() + => new VerifyCS.Test { TestCode = """ class C @@ -3583,12 +3362,10 @@ class C(int value) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestAbstractClass1() - { - await new VerifyCS.Test + public Task TestAbstractClass1() + => new VerifyCS.Test { TestCode = """ abstract class C @@ -3605,12 +3382,10 @@ abstract class C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestAbstractClass2() - { - await new VerifyCS.Test + public Task TestAbstractClass2() + => new VerifyCS.Test { TestCode = """ abstract class C @@ -3627,12 +3402,10 @@ abstract class C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestAbstractClass3() - { - await new VerifyCS.Test + public Task TestAbstractClass3() + => new VerifyCS.Test { TestCode = """ abstract class C @@ -3644,12 +3417,10 @@ internal C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71117")] - public async Task TestNullableMismatch() - { - await new VerifyCS.Test + public Task TestNullableMismatch() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -3691,12 +3462,10 @@ public void Remove() CodeActionsVerifier = actions => Assert.Single(actions), LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71119")] - public async Task TestPragma1() - { - await new VerifyCS.Test + public Task TestPragma1() + => new VerifyCS.Test { TestCode = """ public class Test @@ -3727,12 +3496,10 @@ public class Test(object value) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71119")] - public async Task TestPragma2() - { - await new VerifyCS.Test + public Task TestPragma2() + => new VerifyCS.Test { TestCode = """ public class Test @@ -3764,12 +3531,10 @@ public class Test(object value2) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71152")] - public async Task TestOutVariableInConstructor1() - { - await new VerifyCS.Test + public Task TestOutVariableInConstructor1() + => new VerifyCS.Test { TestCode = """ public class Test @@ -3790,12 +3555,10 @@ public class Test(string x) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71152")] - public async Task TestOutVariableInConstructor2() - { - await new VerifyCS.Test + public Task TestOutVariableInConstructor2() + => new VerifyCS.Test { TestCode = """ public class Test @@ -3812,12 +3575,10 @@ public Test(string x) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71152")] - public async Task TestPatternVariableInConstructor1() - { - await new VerifyCS.Test + public Task TestPatternVariableInConstructor1() + => new VerifyCS.Test { TestCode = """ public class Test @@ -3838,12 +3599,10 @@ public class Test(object x) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71167")] - public async Task TestMemberReferenceInAttribute1() - { - await new VerifyCS.Test + public Task TestMemberReferenceInAttribute1() + => new VerifyCS.Test { TestCode = """ using System.Diagnostics.CodeAnalysis; @@ -3869,12 +3628,10 @@ public class Goo([NotNullIfNotNull(nameof(Goo.Name))] string name) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71167")] - public async Task TestMemberReferenceInAttribute2() - { - await new VerifyCS.Test + public Task TestMemberReferenceInAttribute2() + => new VerifyCS.Test { TestCode = """ using System; @@ -3912,12 +3669,10 @@ public class Nested { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71167")] - public async Task TestMemberReferenceInAttribute3() - { - await new VerifyCS.Test + public Task TestMemberReferenceInAttribute3() + => new VerifyCS.Test { TestCode = """ using System; @@ -3955,12 +3710,10 @@ public class Goo([My(nameof(Goo.E))] string name) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71167")] - public async Task TestMemberReferenceInAttribute4() - { - await new VerifyCS.Test + public Task TestMemberReferenceInAttribute4() + => new VerifyCS.Test { TestCode = """ using System; @@ -3998,12 +3751,10 @@ public void M() { } LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71749")] - public async Task TestNotOnSuppressedAssignmentToAnotherField() - { - await new VerifyCS.Test + public Task TestNotOnSuppressedAssignmentToAnotherField() + => new VerifyCS.Test { TestCode = """ using System; @@ -4027,12 +3778,10 @@ public C(Type type) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72784")] - public async Task TestQualifyNestedEnum() - { - await new VerifyCS.Test + public Task TestQualifyNestedEnum() + => new VerifyCS.Test { TestCode = """ public class MyClass @@ -4070,12 +3819,10 @@ public enum MyEnum LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73695")] - public async Task TestAttributeOnEmptyConstructor() - { - await new VerifyCS.Test + public Task TestAttributeOnEmptyConstructor() + => new VerifyCS.Test { TestCode = """ using System; @@ -4098,12 +3845,10 @@ class C() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73614")] - public async Task TestNotWithRefStruct() - { - await new VerifyCS.Test + public Task TestNotWithRefStruct() + => new VerifyCS.Test { TestCode = """ using System; @@ -4125,12 +3870,10 @@ public void MoveNext() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69012")] - public async Task TestLeadingComment1() - { - await new VerifyCS.Test + public Task TestLeadingComment1() + => new VerifyCS.Test { TestCode = """ class C @@ -4157,12 +3900,10 @@ class C(int i, int j) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69012")] - public async Task TestLeadingComment2() - { - await new VerifyCS.Test + public Task TestLeadingComment2() + => new VerifyCS.Test { TestCode = """ class C @@ -4186,12 +3927,10 @@ class C(int i, int j) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69012")] - public async Task TestLeadingComment3() - { - await new VerifyCS.Test + public Task TestLeadingComment3() + => new VerifyCS.Test { TestCode = """ class C @@ -4218,12 +3957,10 @@ class C(int i, int j) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69012")] - public async Task TestLeadingComment4() - { - await new VerifyCS.Test + public Task TestLeadingComment4() + => new VerifyCS.Test { TestCode = """ class C @@ -4247,12 +3984,10 @@ class C(int i, int j) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69012")] - public async Task TestLeadingComment5() - { - await new VerifyCS.Test + public Task TestLeadingComment5() + => new VerifyCS.Test { TestCode = """ class C @@ -4278,12 +4013,10 @@ class C(int i, int j) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69012")] - public async Task TestLeadingComment6() - { - await new VerifyCS.Test + public Task TestLeadingComment6() + => new VerifyCS.Test { TestCode = """ class C @@ -4306,12 +4039,10 @@ class C(int i, int j) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69012")] - public async Task TestLeadingComment7() - { - await new VerifyCS.Test + public Task TestLeadingComment7() + => new VerifyCS.Test { TestCode = """ class C @@ -4339,12 +4070,10 @@ class C(int i, int j) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69012")] - public async Task TestLeadingComment8() - { - await new VerifyCS.Test + public Task TestLeadingComment8() + => new VerifyCS.Test { TestCode = """ class C @@ -4369,12 +4098,10 @@ class C(int i, int j) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69012")] - public async Task TestLeadingComment9() - { - await new VerifyCS.Test + public Task TestLeadingComment9() + => new VerifyCS.Test { TestCode = """ class C @@ -4403,12 +4130,10 @@ class C(int i) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69012")] - public async Task TestLeadingComment10() - { - await new VerifyCS.Test + public Task TestLeadingComment10() + => new VerifyCS.Test { TestCode = """ class C @@ -4434,12 +4159,10 @@ class C(int i) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69012")] - public async Task TestLeadingComment11() - { - await new VerifyCS.Test + public Task TestLeadingComment11() + => new VerifyCS.Test { TestCode = """ class C @@ -4466,12 +4189,10 @@ class C(int i, int j) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69012")] - public async Task TestLeadingComment12() - { - await new VerifyCS.Test + public Task TestLeadingComment12() + => new VerifyCS.Test { TestCode = """ class C @@ -4501,5 +4222,4 @@ class C(int i, int j) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UseSimpleUsingStatement/UseSimpleUsingStatementTests.cs b/src/Analyzers/CSharp/Tests/UseSimpleUsingStatement/UseSimpleUsingStatementTests.cs index bcae949e0e205..978087bb4006f 100644 --- a/src/Analyzers/CSharp/Tests/UseSimpleUsingStatement/UseSimpleUsingStatementTests.cs +++ b/src/Analyzers/CSharp/Tests/UseSimpleUsingStatement/UseSimpleUsingStatementTests.cs @@ -22,9 +22,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseSimpleUsingStatement public sealed class UseSimpleUsingStatementTests { [Fact] - public async Task TestAboveCSharp8() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestAboveCSharp8() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -47,12 +46,10 @@ void M() } } """); - } [Fact] - public async Task TestWithOptionOff() - { - await new VerifyCS.Test + public Task TestWithOptionOff() + => new VerifyCS.Test { TestCode = """ using System; @@ -72,12 +69,10 @@ void M() { CSharpCodeStyleOptions.PreferSimpleUsingStatement, CodeStyleOption2.FalseWithSilentEnforcement } } }.RunAsync(); - } [Fact] - public async Task TestMultiDeclaration() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestMultiDeclaration() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -100,12 +95,10 @@ void M() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] - public async Task TestMissingIfOnSimpleUsingStatement() - { - await new VerifyCS.Test + public Task TestMissingIfOnSimpleUsingStatement() + => new VerifyCS.Test { TestCode = """ using System; @@ -119,12 +112,10 @@ void M() } """ }.RunAsync(); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] - public async Task TestMissingPriorToCSharp8() - { - await new VerifyCS.Test + public Task TestMissingPriorToCSharp8() + => new VerifyCS.Test { TestCode = """ using System; @@ -141,12 +132,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp7_2 }.RunAsync(); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] - public async Task TestMissingIfExpressionUsing() - { - await new VerifyCS.Test + public Task TestMissingIfExpressionUsing() + => new VerifyCS.Test { TestCode = """ using System; @@ -162,12 +151,10 @@ void M() } """ }.RunAsync(); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] - public async Task TestMissingIfCodeFollows() - { - await new VerifyCS.Test + public Task TestMissingIfCodeFollows() + => new VerifyCS.Test { TestCode = """ using System; @@ -184,13 +171,10 @@ void M() } """ }.RunAsync(); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] - public async Task TestAsyncUsing() - { - // not actually legal code. - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestAsyncUsing() + => VerifyCS.VerifyCodeFixAsync(""" using System; using System.Threading.Tasks; @@ -215,12 +199,10 @@ void M() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] - public async Task TestAwaitUsing() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestAwaitUsing() + => VerifyCS.VerifyCodeFixAsync(""" using System; using System.Threading.Tasks; @@ -245,12 +227,10 @@ void M() } } """); - } [Fact] - public async Task TestWithBlockBodyWithContents() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestWithBlockBodyWithContents() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -275,12 +255,10 @@ void M() } } """); - } [Fact] - public async Task TestWithNonBlockBody() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestWithNonBlockBody() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -303,12 +281,10 @@ void M() } } """); - } [Fact] - public async Task TestMultiUsing() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestMultiUsing() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -335,12 +311,10 @@ void M() } } """); - } [Fact] - public async Task TestFixAll1() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestFixAll1() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -369,12 +343,10 @@ void M() } } """); - } [Fact] - public async Task TestFixAll2() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestFixAll2() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -407,12 +379,10 @@ void M() } } """); - } [Fact] - public async Task TestFixAll3() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestFixAll3() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -447,12 +417,10 @@ void M() } } """); - } [Fact] - public async Task TestFixAll4() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestFixAll4() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -475,12 +443,10 @@ void M() } } """); - } [Fact] - public async Task TestWithFollowingReturn() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestWithFollowingReturn() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -505,12 +471,10 @@ void M() } } """); - } [Fact] - public async Task TestWithFollowingBreak() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestWithFollowingBreak() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -547,12 +511,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingInSwitchSection() - { - await new VerifyCS.Test + public Task TestMissingInSwitchSection() + => new VerifyCS.Test { TestCode = """ using System; @@ -573,12 +535,10 @@ void M() } """ }.RunAsync(); - } [Fact] - public async Task TestMissingWithJumpInsideToOutside() - { - await new VerifyCS.Test + public Task TestMissingWithJumpInsideToOutside() + => new VerifyCS.Test { TestCode = """ using System; @@ -596,12 +556,10 @@ void M() } """ }.RunAsync(); - } [Fact] - public async Task TestMissingWithJumpBeforeToAfter() - { - await new VerifyCS.Test + public Task TestMissingWithJumpBeforeToAfter() + => new VerifyCS.Test { TestCode = """ using System; @@ -621,12 +579,10 @@ void M() } """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35879")] - public async Task TestCollision1() - { - await new VerifyCS.Test + public Task TestCollision1() + => new VerifyCS.Test { TestCode = """ using System.IO; @@ -645,12 +601,10 @@ static void Main() } """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35879")] - public async Task TestNoCollision1() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestNoCollision1() + => VerifyCS.VerifyCodeFixAsync(""" using System.IO; class Program @@ -679,12 +633,10 @@ static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35879")] - public async Task TestCollision2() - { - await new VerifyCS.Test + public Task TestCollision2() + => new VerifyCS.Test { TestCode = """ using System.IO; @@ -704,12 +656,10 @@ static void Main() } """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35879")] - public async Task TestNoCollision2() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestNoCollision2() + => VerifyCS.VerifyCodeFixAsync(""" using System.IO; class Program @@ -740,12 +690,10 @@ static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35879")] - public async Task TestCollision3() - { - await new VerifyCS.Test + public Task TestCollision3() + => new VerifyCS.Test { TestCode = """ using System.IO; @@ -765,12 +713,10 @@ static void Main() } """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35879")] - public async Task TestNoCollision3() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestNoCollision3() + => VerifyCS.VerifyCodeFixAsync(""" using System.IO; class Program @@ -801,12 +747,10 @@ static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35879")] - public async Task TestCollision4() - { - await new VerifyCS.Test + public Task TestCollision4() + => new VerifyCS.Test { TestCode = """ using System.IO; @@ -824,12 +768,10 @@ static void Main() } """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35879")] - public async Task TestNoCollision4() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestNoCollision4() + => VerifyCS.VerifyCodeFixAsync(""" using System.IO; class Program @@ -858,12 +800,10 @@ static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35879")] - public async Task TestCollision5() - { - await new VerifyCS.Test + public Task TestCollision5() + => new VerifyCS.Test { TestCode = """ using System.IO; @@ -883,12 +823,10 @@ static void Main() } """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35879")] - public async Task TestNoCollision5() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestNoCollision5() + => VerifyCS.VerifyCodeFixAsync(""" using System.IO; class Program @@ -919,12 +857,10 @@ static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37678")] - public async Task TestCopyTrivia() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestCopyTrivia() + => VerifyCS.VerifyCodeFixAsync(""" class Program { static void Main(string[] args) @@ -945,12 +881,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37678")] - public async Task TestMultiCopyTrivia() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestMultiCopyTrivia() + => VerifyCS.VerifyCodeFixAsync(""" class Program { static void Main(string[] args) @@ -973,12 +907,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestFixAll_WithTrivia() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestFixAll_WithTrivia() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -1011,12 +943,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38737")] - public async Task TestCopyCompilerDirectiveTrivia() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestCopyCompilerDirectiveTrivia() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -1059,12 +989,10 @@ static void M() static void LegacyMethod() => throw new NotImplementedException(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38737")] - public async Task TestCopyCompilerDirectiveAndCommentTrivia_AfterRestore() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestCopyCompilerDirectiveAndCommentTrivia_AfterRestore() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -1109,12 +1037,10 @@ static void M() static void LegacyMethod() => throw new NotImplementedException(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38737")] - public async Task TestCopyCompilerDirectiveAndCommentTrivia_BeforeRestore() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestCopyCompilerDirectiveAndCommentTrivia_BeforeRestore() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -1159,12 +1085,10 @@ static void M() static void LegacyMethod() => throw new NotImplementedException(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38737")] - public async Task TestCopyCompilerDirectiveAndCommentTrivia_AfterDisable() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestCopyCompilerDirectiveAndCommentTrivia_AfterDisable() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -1209,12 +1133,10 @@ static void M() static void LegacyMethod() => throw new NotImplementedException(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38737")] - public async Task TestCopyCompilerDirectiveAndCommentTrivia_BeforeDisable() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestCopyCompilerDirectiveAndCommentTrivia_BeforeDisable() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -1259,12 +1181,10 @@ static void M() static void LegacyMethod() => throw new NotImplementedException(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38737")] - public async Task TestCopyCompilerDirectiveTrivia_PreserveCodeBeforeAndAfterDirective() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestCopyCompilerDirectiveTrivia_PreserveCodeBeforeAndAfterDirective() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -1311,12 +1231,10 @@ static void M() static void LegacyMethod() => throw new NotImplementedException(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38842")] - public async Task TestNextLineIndentation1() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestNextLineIndentation1() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -1351,12 +1269,10 @@ void Goo(IDisposable disposable) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38842")] - public async Task TestNextLineIndentation2() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestNextLineIndentation2() + => VerifyCS.VerifyCodeFixAsync(""" using System; using System.IO; @@ -1387,12 +1303,10 @@ static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48586")] - public async Task TestKeepSurroundingComments() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestKeepSurroundingComments() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -1419,12 +1333,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48586")] - public async Task TestKeepSurroundingComments2() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestKeepSurroundingComments2() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -1455,12 +1367,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48586")] - public async Task TestKeepSurroundingComments3() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestKeepSurroundingComments3() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -1499,12 +1409,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52970")] - public async Task TestWithBlockBodyWithOpeningBracketOnSameLine() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestWithBlockBodyWithOpeningBracketOnSameLine() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -1528,12 +1436,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52970")] - public async Task TestWithBlockBodyWithOpeningBracketOnSameLine2() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestWithBlockBodyWithOpeningBracketOnSameLine2() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -1557,12 +1463,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52970")] - public async Task TestWithBlockBodyWithOpeningBracketAndCommentOnSameLine() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestWithBlockBodyWithOpeningBracketAndCommentOnSameLine() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -1586,12 +1490,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52970")] - public async Task TestWithBlockBodyWithOpeningBracketOnSameLineWithNoStatements() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestWithBlockBodyWithOpeningBracketOnSameLineWithNoStatements() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -1613,12 +1515,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52970")] - public async Task TestWithBlockBodyWithOpeningBracketOnSameLineAndCommentInBlock() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestWithBlockBodyWithOpeningBracketOnSameLineAndCommentInBlock() + => VerifyCS.VerifyCodeFixAsync(""" using System; class C @@ -1642,12 +1542,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58911")] - public async Task TestUsingWithoutSpace() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestUsingWithoutSpace() + => VerifyCS.VerifyCodeFixAsync(""" using System; using System.Collections.Generic; @@ -1692,12 +1590,10 @@ public class Test public static IDisposable Get() => throw new NotImplementedException(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42194")] - public async Task TestWithConstantReturn1() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestWithConstantReturn1() + => VerifyCS.VerifyCodeFixAsync(""" using System.IO; class C @@ -1724,12 +1620,10 @@ bool M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42194")] - public async Task TestWithNonConstantReturn1() - { - await new VerifyCS.Test + public Task TestWithNonConstantReturn1() + => new VerifyCS.Test { TestCode = """ using System.IO; @@ -1747,12 +1641,10 @@ bool M(int a, int b) } """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42194")] - public async Task TestWithLocalFunctions1() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestWithLocalFunctions1() + => VerifyCS.VerifyCodeFixAsync(""" using System.IO; class C @@ -1781,12 +1673,10 @@ void Inner2() { } } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42194")] - public async Task TestWithLocalFunctions2() - { - await new VerifyCS.Test + public Task TestWithLocalFunctions2() + => new VerifyCS.Test { TestCode = """ using System.IO; @@ -1807,12 +1697,10 @@ void Inner2() { } } """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42194")] - public async Task TestWithLocalFunctionsAndConstantReturn() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestWithLocalFunctionsAndConstantReturn() + => VerifyCS.VerifyCodeFixAsync(""" using System.IO; class C @@ -1845,12 +1733,10 @@ void Inner2() { } } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58861")] - public async Task TestOpenBraceTrivia1() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestOpenBraceTrivia1() + => VerifyCS.VerifyCodeFixAsync(""" using System.Security.Cryptography; class C @@ -1879,12 +1765,10 @@ public static byte[] ComputeMD5Hash(byte[] source) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58861")] - public async Task TestOpenBraceTrivia2() - { - await VerifyCS.VerifyCodeFixAsync(""" + public Task TestOpenBraceTrivia2() + => VerifyCS.VerifyCodeFixAsync(""" using System.Security.Cryptography; class C @@ -1914,12 +1798,10 @@ public static byte[] ComputeMD5Hash(byte[] source) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75917")] - public async Task TestGlobalStatement1() - { - await new VerifyCS.Test + public Task TestGlobalStatement1() + => new VerifyCS.Test { TestCode = """ using System; @@ -1947,12 +1829,10 @@ class C OutputKind = OutputKind.ConsoleApplication, } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75917")] - public async Task TestGlobalStatement2() - { - await new VerifyCS.Test + public Task TestGlobalStatement2() + => new VerifyCS.Test { TestCode = """ using System; @@ -1982,12 +1862,10 @@ class C OutputKind = OutputKind.ConsoleApplication, } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75917")] - public async Task TestGlobalStatement3() - { - await new VerifyCS.Test + public Task TestGlobalStatement3() + => new VerifyCS.Test { TestCode = """ using System; @@ -2008,12 +1886,10 @@ class C OutputKind = OutputKind.ConsoleApplication, } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75917")] - public async Task TestGlobalStatement4() - { - await new VerifyCS.Test + public Task TestGlobalStatement4() + => new VerifyCS.Test { TestCode = """ using System; @@ -2047,12 +1923,10 @@ class C OutputKind = OutputKind.ConsoleApplication, } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75917")] - public async Task TestGlobalStatement5() - { - await new VerifyCS.Test + public Task TestGlobalStatement5() + => new VerifyCS.Test { TestCode = """ using System; @@ -2082,12 +1956,10 @@ class C OutputKind = OutputKind.ConsoleApplication, } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75917")] - public async Task TestGlobalStatement6() - { - await new VerifyCS.Test + public Task TestGlobalStatement6() + => new VerifyCS.Test { TestCode = """ using System; @@ -2119,5 +1991,4 @@ class C OutputKind = OutputKind.ConsoleApplication, } }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UseSystemHashCode/UseSystemHashCodeTests.cs b/src/Analyzers/CSharp/Tests/UseSystemHashCode/UseSystemHashCodeTests.cs index 4208a2b63937c..f545430a59937 100644 --- a/src/Analyzers/CSharp/Tests/UseSystemHashCode/UseSystemHashCodeTests.cs +++ b/src/Analyzers/CSharp/Tests/UseSystemHashCode/UseSystemHashCodeTests.cs @@ -41,9 +41,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider } [Fact] - public async Task TestDerivedClassWithFieldWithBase() - { - await TestInRegularAndScript1Async( + public Task TestDerivedClassWithFieldWithBase() + => TestInRegularAndScript1Async( """ namespace System { public struct HashCode { } } @@ -83,12 +82,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestDerivedClassWithFieldWithNoBase() - { - await TestInRegularAndScript1Async( + public Task TestDerivedClassWithFieldWithNoBase() + => TestInRegularAndScript1Async( """ namespace System { public struct HashCode { } } @@ -127,12 +124,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestDerivedClassWithNoFieldWithBase() - { - await TestInRegularAndScript1Async( + public Task TestDerivedClassWithNoFieldWithBase() + => TestInRegularAndScript1Async( """ namespace System { public struct HashCode { } } @@ -171,12 +166,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestFieldAndProp() - { - await TestInRegularAndScript1Async( + public Task TestFieldAndProp() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -212,12 +205,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestUnchecked() - { - await TestInRegularAndScript1Async( + public Task TestUnchecked() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -256,12 +247,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestNotOnNonGetHashCode() - { - await TestMissingAsync( + public Task TestNotOnNonGetHashCode() + => TestMissingAsync( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -281,12 +270,10 @@ class C } } """); - } [Fact] - public async Task TestNotWithoutReturn() - { - await TestMissingAsync( + public Task TestNotWithoutReturn() + => TestMissingAsync( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -305,12 +292,10 @@ class C } } """); - } [Fact] - public async Task TestNotWithoutLocal() - { - await TestMissingAsync( + public Task TestNotWithoutLocal() + => TestMissingAsync( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -329,12 +314,10 @@ class C } } """); - } [Fact] - public async Task TestNotWithMultipleLocals() - { - await TestMissingAsync( + public Task TestNotWithMultipleLocals() + => TestMissingAsync( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -354,12 +337,10 @@ class C } } """); - } [Fact] - public async Task TestNotWithoutInitializer() - { - await TestMissingAsync( + public Task TestNotWithoutInitializer() + => TestMissingAsync( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -379,12 +360,10 @@ class C } } """); - } [Fact] - public async Task TestNotReturningAccumulator() - { - await TestMissingAsync( + public Task TestNotReturningAccumulator() + => TestMissingAsync( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -404,12 +383,10 @@ class C } } """); - } [Fact] - public async Task TestAcumulatorInitializedToField() - { - await TestInRegularAndScript1Async( + public Task TestAcumulatorInitializedToField() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -444,12 +421,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestAcumulatorInitializedToHashedField() - { - await TestInRegularAndScript1Async( + public Task TestAcumulatorInitializedToHashedField() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -484,12 +459,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestMissingOnThisGetHashCode() - { - await TestMissingAsync( + public Task TestMissingOnThisGetHashCode() + => TestMissingAsync( """ namespace System { public struct HashCode { } } @@ -511,12 +484,10 @@ class C : B } } """); - } [Fact] - public async Task TestMissingWithNoSystemHashCode() - { - await TestMissingAsync( + public Task TestMissingWithNoSystemHashCode() + => TestMissingAsync( """ class B { @@ -536,12 +507,10 @@ class C : B } } """); - } [Fact] - public async Task TestDirectNullCheck1() - { - await TestInRegularAndScript1Async( + public Task TestDirectNullCheck1() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -577,12 +546,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestDirectNullCheck2() - { - await TestInRegularAndScript1Async( + public Task TestDirectNullCheck2() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -618,12 +585,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestInt64Pattern() - { - await TestInRegularAndScript1Async( + public Task TestInt64Pattern() + => TestInRegularAndScript1Async( """ namespace System { public struct HashCode { } } @@ -652,12 +617,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestInt64Pattern2() - { - await TestInRegularAndScript1Async( + public Task TestInt64Pattern2() + => TestInRegularAndScript1Async( """ namespace System { public struct HashCode { } } @@ -686,12 +649,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestTuple() - { - await TestInRegularAndScript1Async( + public Task TestTuple() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -724,12 +685,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestNullable1() - { - await TestInRegularAndScript1Async( + public Task TestNullable1() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -765,12 +724,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestNullable2() - { - await TestInRegularAndScript1Async( + public Task TestNullable2() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -806,12 +763,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestNullable3() - { - await TestInRegularAndScript1Async( + public Task TestNullable3() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -847,12 +802,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestNullable4() - { - await TestInRegularAndScript1Async( + public Task TestNullable4() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -888,12 +841,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestNullable_Enable_1() - { - await TestInRegularAndScript1Async( + public Task TestNullable_Enable_1() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -933,12 +884,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestNullable_Enable_2() - { - await TestInRegularAndScript1Async( + public Task TestNullable_Enable_2() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -978,12 +927,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestNullable_Enable_3() - { - await TestInRegularAndScript1Async( + public Task TestNullable_Enable_3() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -1023,12 +970,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestNullable_Enable_4() - { - await TestInRegularAndScript1Async( + public Task TestNullable_Enable_4() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -1068,12 +1013,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestNullable_Disable_1() - { - await TestInRegularAndScript1Async( + public Task TestNullable_Disable_1() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -1113,12 +1056,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestNullable_Disable_2() - { - await TestInRegularAndScript1Async( + public Task TestNullable_Disable_2() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -1158,12 +1099,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestNullable_Disable_3() - { - await TestInRegularAndScript1Async( + public Task TestNullable_Disable_3() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -1203,12 +1142,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestNullable_Disable_4() - { - await TestInRegularAndScript1Async( + public Task TestNullable_Disable_4() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -1248,12 +1185,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestNotOnExistingUsageOfSystemHashCode() - { - await TestMissingAsync( + public Task TestNotOnExistingUsageOfSystemHashCode() + => TestMissingAsync( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -1270,12 +1205,10 @@ class C } } """); - } [Fact] - public async Task TestNotOnExistingUsageOfSystemHashCode2() - { - await TestMissingAsync( + public Task TestNotOnExistingUsageOfSystemHashCode2() + => TestMissingAsync( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -1295,12 +1228,10 @@ class C } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39916")] - public async Task TestManyFields_ImplicitType() - { - await TestInRegularAndScript1Async( + public Task TestManyFields_ImplicitType() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -1349,12 +1280,10 @@ public override int GetHashCode() } } """, new TestParameters(options: this.PreferImplicitTypeWithInfo())); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39916")] - public async Task TestManyFields_ExplicitType() - { - await TestInRegularAndScript1Async( + public Task TestManyFields_ExplicitType() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; namespace System { public struct HashCode { } } @@ -1403,12 +1332,10 @@ public override int GetHashCode() } } """); - } [Fact] - public async Task TestNotOnSingleReturnedMember() - { - await TestMissingAsync( + public Task TestNotOnSingleReturnedMember() + => TestMissingAsync( """ namespace System { public struct HashCode { } } @@ -1422,12 +1349,10 @@ class C } } """); - } [Fact] - public async Task TestNotOnSingleMemberWithInvokedGetHashCode() - { - await TestMissingAsync( + public Task TestNotOnSingleMemberWithInvokedGetHashCode() + => TestMissingAsync( """ namespace System { public struct HashCode { } } @@ -1441,12 +1366,10 @@ class C } } """); - } [Fact] - public async Task TestNotOnSimpleBaseReturn() - { - await TestMissingAsync( + public Task TestNotOnSimpleBaseReturn() + => TestMissingAsync( """ namespace System { public struct HashCode { } } @@ -1460,17 +1383,14 @@ class C } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/74315")] - public async Task TestMissingBaseType() - { - await TestMissingAsync(""" + public Task TestMissingBaseType() + => TestMissingAsync(""" using System; namespace System { public struct HashCode { } } record $$B(int I) : A(I); """); - } } diff --git a/src/Analyzers/CSharp/Tests/UseSystemThreadingLock/UseSystemThreadingLockTests.cs b/src/Analyzers/CSharp/Tests/UseSystemThreadingLock/UseSystemThreadingLockTests.cs index 37b03c6e16868..f6315d700edee 100644 --- a/src/Analyzers/CSharp/Tests/UseSystemThreadingLock/UseSystemThreadingLockTests.cs +++ b/src/Analyzers/CSharp/Tests/UseSystemThreadingLock/UseSystemThreadingLockTests.cs @@ -44,9 +44,8 @@ public void Dispose() { } """; [Fact] - public async Task TestNotInCSharp13_Net80() - { - await new VerifyCS.Test + public Task TestNotInCSharp13_Net80() + => new VerifyCS.Test { TestCode = """ class C @@ -64,12 +63,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNotInCSharp12_Net80() - { - await new VerifyCS.Test + public Task TestNotInCSharp12_Net80() + => new VerifyCS.Test { TestCode = """ class C @@ -87,12 +84,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNotInCSharp12_Net80_PolyFill() - { - await new VerifyCS.Test + public Task TestNotInCSharp12_Net80_PolyFill() + => new VerifyCS.Test { TestCode = """ class C @@ -110,12 +105,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNotInCSharp12_Net90() - { - await new VerifyCS.Test + public Task TestNotInCSharp12_Net90() + => new VerifyCS.Test { TestCode = """ class C @@ -133,12 +126,10 @@ void M() LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestInCSharp13_Net80_PolyFill() - { - await new VerifyCS.Test + public Task TestInCSharp13_Net80_PolyFill() + => new VerifyCS.Test { TestCode = """ class C @@ -171,12 +162,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestInCSharp13_Net90() - { - await new VerifyCS.Test + public Task TestInCSharp13_Net90() + => new VerifyCS.Test { TestCode = """ class C @@ -209,12 +198,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestNotWithPolyFill_InternalLock() - { - await new VerifyCS.Test + public Task TestNotWithPolyFill_InternalLock() + => new VerifyCS.Test { TestCode = """ class C @@ -232,12 +219,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNotWithPolyFill_NoInnerScopeType() - { - await new VerifyCS.Test + public Task TestNotWithPolyFill_NoInnerScopeType() + => new VerifyCS.Test { TestCode = """ class C @@ -255,12 +240,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNotWithPolyFill_PrivateScopeType() - { - await new VerifyCS.Test + public Task TestNotWithPolyFill_PrivateScopeType() + => new VerifyCS.Test { TestCode = """ class C @@ -280,12 +263,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestNotWithPolyFill_NotRefStructScopeType() - { - await new VerifyCS.Test + public Task TestNotWithPolyFill_NotRefStructScopeType() + => new VerifyCS.Test { TestCode = """ class C @@ -303,12 +284,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestWithDocCommentReference() - { - await new VerifyCS.Test + public Task TestWithDocCommentReference() + => new VerifyCS.Test { TestCode = """ class C @@ -343,12 +322,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestWithFullType1() - { - await new VerifyCS.Test + public Task TestWithFullType1() + => new VerifyCS.Test { TestCode = """ class C @@ -381,12 +358,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestWithFullType2() - { - await new VerifyCS.Test + public Task TestWithFullType2() + => new VerifyCS.Test { TestCode = """ using System; @@ -422,12 +397,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestWithParenthesizedInitializer() - { - await new VerifyCS.Test + public Task TestWithParenthesizedInitializer() + => new VerifyCS.Test { TestCode = """ class C @@ -460,12 +433,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestNotWithInnerYield() - { - await new VerifyCS.Test + public Task TestNotWithInnerYield() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -486,12 +457,10 @@ IEnumerable M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestWithYieldOutsideLock() - { - await new VerifyCS.Test + public Task TestWithYieldOutsideLock() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -531,12 +500,10 @@ IEnumerable M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestWithYieldInsideLocalFunctionInsideLock() - { - await new VerifyCS.Test + public Task TestWithYieldInsideLocalFunctionInsideLock() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -584,12 +551,10 @@ IEnumerable LocalFunction() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestNotWithoutLock() - { - await new VerifyCS.Test + public Task TestNotWithoutLock() + => new VerifyCS.Test { TestCode = """ class C @@ -604,12 +569,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestNotWithUnsupportedOperation1() - { - await new VerifyCS.Test + public Task TestNotWithUnsupportedOperation1() + => new VerifyCS.Test { TestCode = """ class C @@ -631,12 +594,10 @@ void Goo(object o) { } LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestNotWithUnsupportedOperation2() - { - await new VerifyCS.Test + public Task TestNotWithUnsupportedOperation2() + => new VerifyCS.Test { TestCode = """ class C @@ -656,12 +617,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestNotWithPublicGate() - { - await new VerifyCS.Test + public Task TestNotWithPublicGate() + => new VerifyCS.Test { TestCode = """ class C @@ -679,12 +638,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestNotWithNonObjectInitializerValue1() - { - await new VerifyCS.Test + public Task TestNotWithNonObjectInitializerValue1() + => new VerifyCS.Test { TestCode = """ class C @@ -702,12 +659,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestNotWithNonObjectInitializerValue_InField() - { - await new VerifyCS.Test + public Task TestNotWithNonObjectInitializerValue_InField() + => new VerifyCS.Test { TestCode = """ class C @@ -725,12 +680,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestNotWithNonObjectInitializerValue_InConstructor() - { - await new VerifyCS.Test + public Task TestNotWithNonObjectInitializerValue_InConstructor() + => new VerifyCS.Test { TestCode = """ class C @@ -753,12 +706,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestNotWithNonObjectAssignment() - { - await new VerifyCS.Test + public Task TestNotWithNonObjectAssignment() + => new VerifyCS.Test { TestCode = """ class C @@ -781,12 +732,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestNotWithMultipleDeclarators() - { - await new VerifyCS.Test + public Task TestNotWithMultipleDeclarators() + => new VerifyCS.Test { TestCode = """ class C @@ -804,12 +753,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestNotWithNonObjectType() - { - await new VerifyCS.Test + public Task TestNotWithNonObjectType() + => new VerifyCS.Test { TestCode = """ class C @@ -827,12 +774,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestWithinStruct1() - { - await new VerifyCS.Test + public Task TestWithinStruct1() + => new VerifyCS.Test { TestCode = """ struct C @@ -873,12 +818,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestWithinStruct2() - { - await new VerifyCS.Test + public Task TestWithinStruct2() + => new VerifyCS.Test { TestCode = """ struct C @@ -921,12 +864,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestWithMemberAccess1() - { - await new VerifyCS.Test + public Task TestWithMemberAccess1() + => new VerifyCS.Test { TestCode = """ class C @@ -959,12 +900,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestWithMemberAccess2() - { - await new VerifyCS.Test + public Task TestWithMemberAccess2() + => new VerifyCS.Test { TestCode = """ class C @@ -997,12 +936,10 @@ void M(C c) LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestWithGenericMemberAccess() - { - await new VerifyCS.Test + public Task TestWithGenericMemberAccess() + => new VerifyCS.Test { TestCode = """ class C @@ -1035,12 +972,10 @@ void M(C c) LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestWithImplicitObjectCreation_InField() - { - await new VerifyCS.Test + public Task TestWithImplicitObjectCreation_InField() + => new VerifyCS.Test { TestCode = """ class C @@ -1073,12 +1008,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestWithImplicitObjectCreation_InConstructor() - { - await new VerifyCS.Test + public Task TestWithImplicitObjectCreation_InConstructor() + => new VerifyCS.Test { TestCode = """ struct C @@ -1121,12 +1054,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestWithObjectCreation_InConstructor1() - { - await new VerifyCS.Test + public Task TestWithObjectCreation_InConstructor1() + => new VerifyCS.Test { TestCode = """ class C @@ -1169,12 +1100,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestWithObjectCreation_InConstructor2() - { - await new VerifyCS.Test + public Task TestWithObjectCreation_InConstructor2() + => new VerifyCS.Test { TestCode = """ class C @@ -1217,12 +1146,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestWithObjectCreation_InConstructor3() - { - await new VerifyCS.Test + public Task TestWithObjectCreation_InConstructor3() + => new VerifyCS.Test { TestCode = """ class C @@ -1265,12 +1192,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestWithObjectCreation_InInitializer1() - { - await new VerifyCS.Test + public Task TestWithObjectCreation_InInitializer1() + => new VerifyCS.Test { TestCode = """ class C @@ -1321,12 +1246,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestWithObjectCreation_InInitializer2() - { - await new VerifyCS.Test + public Task TestWithObjectCreation_InInitializer2() + => new VerifyCS.Test { TestCode = """ class C @@ -1377,12 +1300,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestWithNameOf() - { - await new VerifyCS.Test + public Task TestWithNameOf() + => new VerifyCS.Test { TestCode = """ class C @@ -1417,12 +1338,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestWithMultipleFieldsNoneLocked() - { - await new VerifyCS.Test + public Task TestWithMultipleFieldsNoneLocked() + => new VerifyCS.Test { TestCode = """ class C @@ -1438,12 +1357,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestWithMultipleFieldsOneLocked() - { - await new VerifyCS.Test + public Task TestWithMultipleFieldsOneLocked() + => new VerifyCS.Test { TestCode = """ class C @@ -1478,12 +1395,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestWithMultipleFieldsBothLocked() - { - await new VerifyCS.Test + public Task TestWithMultipleFieldsBothLocked() + => new VerifyCS.Test { TestCode = """ class C @@ -1524,12 +1439,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestWithOtherField1() - { - await new VerifyCS.Test + public Task TestWithOtherField1() + => new VerifyCS.Test { TestCode = """ class C @@ -1568,12 +1481,10 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } [Fact] - public async Task TestWithOtherField2() - { - await new VerifyCS.Test + public Task TestWithOtherField2() + => new VerifyCS.Test { TestCode = """ class C @@ -1612,5 +1523,4 @@ void M() LanguageVersion = LanguageVersion.CSharp13, ReferenceAssemblies = ReferenceAssemblies.Net.Net90, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UseThrowExpression/UseThrowExpressionTests.cs b/src/Analyzers/CSharp/Tests/UseThrowExpression/UseThrowExpressionTests.cs index 15b624cd8fadd..54e96c6f0b746 100644 --- a/src/Analyzers/CSharp/Tests/UseThrowExpression/UseThrowExpressionTests.cs +++ b/src/Analyzers/CSharp/Tests/UseThrowExpression/UseThrowExpressionTests.cs @@ -28,9 +28,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider => (new CSharpUseThrowExpressionDiagnosticAnalyzer(), new UseThrowExpressionCodeFixProvider()); [Fact] - public async Task WithoutBraces() - { - await TestInRegularAndScriptAsync( + public Task WithoutBraces() + => TestInRegularAndScriptAsync( """ using System; @@ -55,12 +54,10 @@ void M(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/pull/38136")] - public async Task TestMissingOnIf() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnIf() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -74,12 +71,10 @@ void M(string s) } } """); - } [Fact] - public async Task WithBraces() - { - await TestInRegularAndScriptAsync( + public Task WithBraces() + => TestInRegularAndScriptAsync( """ using System; @@ -107,12 +102,10 @@ void M(string s) } } """); - } [Fact] - public async Task TestNotOnAssign() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOnAssign() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -126,12 +119,10 @@ void M(string s) } } """); - } [Fact] - public async Task OnlyInCSharp7AndHigher() - { - await TestMissingAsync( + public Task OnlyInCSharp7AndHigher() + => TestMissingAsync( """ using System; @@ -146,12 +137,10 @@ void M(string s) } } """, new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); - } [Fact] - public async Task WithIntermediaryStatements() - { - await TestInRegularAndScriptAsync( + public Task WithIntermediaryStatements() + => TestInRegularAndScriptAsync( """ using System; @@ -189,12 +178,10 @@ void M(string s, string t) } } """); - } [Fact] - public async Task NotWithIntermediaryWrite() - { - await TestMissingInRegularAndScriptAsync( + public Task NotWithIntermediaryWrite() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -211,12 +198,10 @@ void M(string s, string t) } } """); - } [Fact] - public async Task NotWithIntermediaryMemberAccess() - { - await TestMissingInRegularAndScriptAsync( + public Task NotWithIntermediaryMemberAccess() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -233,12 +218,10 @@ void M(string s, string t) } } """); - } [Fact] - public async Task TestNullCheckOnLeft() - { - await TestInRegularAndScriptAsync( + public Task TestNullCheckOnLeft() + => TestInRegularAndScriptAsync( """ using System; @@ -263,12 +246,10 @@ void M(string s) } } """); - } [Fact] - public async Task TestWithLocal() - { - await TestInRegularAndScriptAsync( + public Task TestWithLocal() + => TestInRegularAndScriptAsync( """ using System; @@ -295,12 +276,10 @@ void M() } } """); - } [Fact] - public async Task TestNotOnField() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOnField() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -316,12 +295,10 @@ void M() } } """); - } [Fact] - public async Task TestAssignBeforeCheck() - { - await TestMissingInRegularAndScriptAsync( + public Task TestAssignBeforeCheck() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -335,12 +312,10 @@ void M(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16234")] - public async Task TestNotInExpressionTree() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotInExpressionTree() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Linq.Expressions; @@ -361,12 +336,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=404142")] - public async Task TestNotWithAsCheck() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithAsCheck() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -396,12 +369,10 @@ public interface ISyntax { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18670")] - public async Task TestNotWithElseClause() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithElseClause() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -424,12 +395,10 @@ public C(int? x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19377")] - public async Task TestNotWithMultipleStatementsInIf1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithMultipleStatementsInIf1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -446,12 +415,10 @@ void M(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19377")] - public async Task TestNotWithMultipleStatementsInIf2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithMultipleStatementsInIf2() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -468,12 +435,10 @@ void M(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21612")] - public async Task TestNotWhenAccessedOnLeftOfAssignment() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWhenAccessedOnLeftOfAssignment() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -493,12 +458,10 @@ public B(A a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24628")] - public async Task TestNotWhenAccessedOnLineBefore() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWhenAccessedOnLineBefore() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -517,12 +480,10 @@ public B(object arg) object MakeKey(object x) => null; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22926")] - public async Task TestNotWhenUnconstrainedTypeParameter() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWhenUnconstrainedTypeParameter() + => TestMissingInRegularAndScriptAsync( """ using System; class A @@ -535,12 +496,10 @@ public A(T t) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22926")] - public async Task TestWhenClassConstrainedTypeParameter() - { - await TestInRegularAndScriptAsync( + public Task TestWhenClassConstrainedTypeParameter() + => TestInRegularAndScriptAsync( """ using System; class A where T: class @@ -564,12 +523,10 @@ public A(T t) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22926")] - public async Task TestWhenStructConstrainedTypeParameter() - { - await TestInRegularAndScriptAsync( + public Task TestWhenStructConstrainedTypeParameter() + => TestInRegularAndScriptAsync( """ using System; class A where T: struct @@ -593,12 +550,10 @@ public A(T? t) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44454")] - public async Task TopLevelStatement() - { - await TestAsync( + public Task TopLevelStatement() + => TestAsync( """ using System; string s = null; @@ -613,12 +568,10 @@ await TestAsync( x = s ?? throw new ArgumentNullException(); """, TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38102")] - public async Task PreserveTrailingTrivia1() - { - await TestAsync( + public Task PreserveTrailingTrivia1() + => TestAsync( """ using System; @@ -649,12 +602,10 @@ public Program(object arg) } } """, TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38102")] - public async Task PreserveTrailingTrivia2() - { - await TestAsync( + public Task PreserveTrailingTrivia2() + => TestAsync( """ using System; @@ -686,5 +637,4 @@ public Program(object arg) } } """, TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9)); - } } diff --git a/src/Analyzers/CSharp/Tests/UseThrowExpression/UseThrowExpressionTests_FixAllTests.cs b/src/Analyzers/CSharp/Tests/UseThrowExpression/UseThrowExpressionTests_FixAllTests.cs index bf9eca46f758d..a910d3f33f8b0 100644 --- a/src/Analyzers/CSharp/Tests/UseThrowExpression/UseThrowExpressionTests_FixAllTests.cs +++ b/src/Analyzers/CSharp/Tests/UseThrowExpression/UseThrowExpressionTests_FixAllTests.cs @@ -14,9 +14,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseThrowExpression; public sealed partial class UseThrowExpressionTests { [Fact] - public async Task FixAllInDocument1() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument1() + => TestInRegularAndScriptAsync( """ using System; @@ -51,12 +50,10 @@ void M(string s, string t) } } """); - } [Fact] - public async Task FixAllInDocument2() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument2() + => TestInRegularAndScriptAsync( """ using System; @@ -91,12 +88,10 @@ void M(string s, string t) } } """); - } [Fact] - public async Task FixAllInDocument3() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument3() + => TestInRegularAndScriptAsync( """ using System; @@ -131,12 +126,10 @@ void M(string s, string t) } } """); - } [Fact] - public async Task FixAllInDocument4() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument4() + => TestInRegularAndScriptAsync( """ using System; @@ -171,12 +164,10 @@ void M(string s, string t) } } """); - } [Fact] - public async Task FixAllInDocumentDoNotTouchOtherDocuments() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocumentDoNotTouchOtherDocuments() + => TestInRegularAndScriptAsync( """ @@ -248,12 +239,10 @@ void M(string s, string t) """); - } [Fact] - public async Task FixAllInProject1() - { - await TestInRegularAndScriptAsync( + public Task FixAllInProject1() + => TestInRegularAndScriptAsync( """ @@ -320,5 +309,4 @@ void M(string s, string t) """); - } } diff --git a/src/Analyzers/CSharp/Tests/UseTupleSwap/UseTupleSwapTests.cs b/src/Analyzers/CSharp/Tests/UseTupleSwap/UseTupleSwapTests.cs index 1a6209f36c637..11e07ee7a51cc 100644 --- a/src/Analyzers/CSharp/Tests/UseTupleSwap/UseTupleSwapTests.cs +++ b/src/Analyzers/CSharp/Tests/UseTupleSwap/UseTupleSwapTests.cs @@ -22,9 +22,10 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseTupleSwap; public sealed class UseTupleSwapTests { [Fact] - public async Task TestMissingBeforeCSharp7() - { - var code = """ + public Task TestMissingBeforeCSharp7() + => new VerifyCS.Test + { + TestCode = """ class C { void M(string[] args) @@ -34,19 +35,15 @@ void M(string[] args) args[1] = temp; } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp6, }.RunAsync(); - } [Fact] - public async Task TestMissingWithFeatureOff() - { - var code = """ + public Task TestMissingWithFeatureOff() + => new VerifyCS.Test + { + TestCode = """ class C { void M(string[] args) @@ -56,22 +53,16 @@ void M(string[] args) args[1] = temp; } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, Options = { { CSharpCodeStyleOptions.PreferTupleSwap, false, CodeStyle.NotificationOption2.Silent } } }.RunAsync(); - } [Fact] - public async Task TestBasicCase() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestBasicCase() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -92,12 +83,12 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestNotWithRef() - { - var code = """ + public Task TestNotWithRef() + => new VerifyCS.Test + { + TestCode = """ class C { void M(ref int a, ref int b) @@ -107,18 +98,12 @@ void M(ref int a, ref int b) b = ref temp; } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, }.RunAsync(); - } [Fact] - public async Task TestArbitraryParens() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestArbitraryParens() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -139,12 +124,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestTrivia1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestTrivia1() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -167,12 +150,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestTrivia2() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestTrivia2() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -193,12 +174,12 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestSimpleAssignment1() - { - var code = """ + public Task TestSimpleAssignment1() + => new VerifyCS.Test + { + TestCode = """ class C { void M(string[] args) @@ -208,18 +189,14 @@ void M(string[] args) args[1] = temp; } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, }.RunAsync(); - } [Fact] - public async Task TestSimpleAssignment2() - { - var code = """ + public Task TestSimpleAssignment2() + => new VerifyCS.Test + { + TestCode = """ class C { void M(string[] args) @@ -229,18 +206,14 @@ void M(string[] args) args[1] += temp; } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, }.RunAsync(); - } [Fact] - public async Task TestNotSwap1() - { - var code = """ + public Task TestNotSwap1() + => new VerifyCS.Test + { + TestCode = """ class C { void M(string[] args, string temp1) @@ -250,18 +223,14 @@ void M(string[] args, string temp1) args[1] = temp1; } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, }.RunAsync(); - } [Fact] - public async Task TestNotSwap2() - { - var code = """ + public Task TestNotSwap2() + => new VerifyCS.Test + { + TestCode = """ class C { void M(string[] args) @@ -271,18 +240,14 @@ void M(string[] args) args[0] = args[1]; } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, }.RunAsync(); - } [Fact] - public async Task TestNotSwap3() - { - var code = """ + public Task TestNotSwap3() + => new VerifyCS.Test + { + TestCode = """ class C { void M(string[] args) @@ -292,18 +257,14 @@ void M(string[] args) args[0] = temp; } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, }.RunAsync(); - } [Fact] - public async Task TestNotSwap4() - { - var code = """ + public Task TestNotSwap4() + => new VerifyCS.Test + { + TestCode = """ class C { void M(string[] args) @@ -313,18 +274,14 @@ void M(string[] args) args[0] = temp; } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, }.RunAsync(); - } [Fact] - public async Task TestNotSwap5() - { - var code = """ + public Task TestNotSwap5() + => new VerifyCS.Test + { + TestCode = """ class C { void M(string[] args) @@ -334,18 +291,12 @@ void M(string[] args) args[1] = {|CS0165:temp|}; } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, }.RunAsync(); - } [Fact] - public async Task TestInSwitch() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestInSwitch() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -376,12 +327,10 @@ void M(string[] args, int x) } } """); - } [Fact] - public async Task TestFixAll1() - { - await VerifyCS.VerifyCodeFixAsync( + public Task TestFixAll1() + => VerifyCS.VerifyCodeFixAsync( """ class C { @@ -412,12 +361,12 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestNotWithMultipleVariables() - { - var code = """ + public Task TestNotWithMultipleVariables() + => new VerifyCS.Test + { + TestCode = """ class C { void M(string[] args) @@ -427,18 +376,12 @@ void M(string[] args) args[1] = temp; } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58759")] - public async Task TestTopLevelStatements() - { - await new VerifyCS.Test + public Task TestTopLevelStatements() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.CSharp9, @@ -459,12 +402,12 @@ public async Task TestTopLevelStatements() """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66427")] - public async Task NotOnRefStruct() - { - var code = """ + public Task NotOnRefStruct() + => new VerifyCS.Test + { + TestCode = """ ref struct S { } class C @@ -479,18 +422,12 @@ void M() v1 = vTmp; } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66427")] - public async Task OnNormalStruct() - { - await new VerifyCS.Test + public Task OnNormalStruct() + => new VerifyCS.Test { TestCode = """ struct S { } @@ -523,12 +460,12 @@ void M() } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66427")] - public async Task NotOnPointer() - { - var code = """ + public Task NotOnPointer() + => new VerifyCS.Test + { + TestCode = """ class C { unsafe void M(int* v0, int* v1) @@ -538,11 +475,6 @@ unsafe void M(int* v0, int* v1) v1 = vTmp; } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UseUnboundGenericTypeInNameOf/UseUnboundGenericTypeInNameOfTests.cs b/src/Analyzers/CSharp/Tests/UseUnboundGenericTypeInNameOf/UseUnboundGenericTypeInNameOfTests.cs index 4add90eb881f0..1b5801b775133 100644 --- a/src/Analyzers/CSharp/Tests/UseUnboundGenericTypeInNameOf/UseUnboundGenericTypeInNameOfTests.cs +++ b/src/Analyzers/CSharp/Tests/UseUnboundGenericTypeInNameOf/UseUnboundGenericTypeInNameOfTests.cs @@ -21,9 +21,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseUnboundGenericTypeIn public sealed class UseUnboundGenericTypeInNameOfTests { [Fact] - public async Task TestBaseCase() - { - await new VerifyCS.Test + public Task TestBaseCase() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -49,12 +48,10 @@ void M(string[] args) """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestNotIfAlreadyOmitted() - { - await new VerifyCS.Test + public Task TestNotIfAlreadyOmitted() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -69,12 +66,10 @@ void M(string[] args) """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestMissingBeforeCSharp14() - { - await new VerifyCS.Test + public Task TestMissingBeforeCSharp14() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -89,12 +84,10 @@ void M(string[] args) """, LanguageVersion = LanguageVersion.CSharp13, }.RunAsync(); - } [Fact] - public async Task TestMissingWithFeatureOff() - { - await new VerifyCS.Test + public Task TestMissingWithFeatureOff() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -113,12 +106,10 @@ void M(string[] args) }, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestMultipleTypeArguments() - { - await new VerifyCS.Test + public Task TestMultipleTypeArguments() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -144,12 +135,10 @@ void M(string[] args) """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestGlobal() - { - await new VerifyCS.Test + public Task TestGlobal() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -175,12 +164,10 @@ void M(string[] args) """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestNestedArgs() - { - await new VerifyCS.Test + public Task TestNestedArgs() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -206,12 +193,10 @@ void M(string[] args) """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestNestedType1() - { - await new VerifyCS.Test + public Task TestNestedType1() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -241,12 +226,10 @@ class Outer { public class Inner { } } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestNestedType2() - { - await new VerifyCS.Test + public Task TestNestedType2() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -276,12 +259,10 @@ class Outer { public class Inner { } } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestNestedType3() - { - await new VerifyCS.Test + public Task TestNestedType3() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -311,12 +292,10 @@ class Outer { public class Inner { } } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestNestedType4() - { - await new VerifyCS.Test + public Task TestNestedType4() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -333,5 +312,4 @@ class Outer { public class Inner { } } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/UseUtf8StringLiteral/UseUtf8StringLiteralTests.cs b/src/Analyzers/CSharp/Tests/UseUtf8StringLiteral/UseUtf8StringLiteralTests.cs index 37ff4ca8bcf6e..6d97675c12f3a 100644 --- a/src/Analyzers/CSharp/Tests/UseUtf8StringLiteral/UseUtf8StringLiteralTests.cs +++ b/src/Analyzers/CSharp/Tests/UseUtf8StringLiteral/UseUtf8StringLiteralTests.cs @@ -20,9 +20,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseUtf8StringLiteral; public sealed class UseUtf8StringLiteralTests { [Fact] - public async Task TestNotInAttribute() - { - await new VerifyCS.Test + public Task TestNotInAttribute() + => new VerifyCS.Test { TestCode = """ @@ -44,12 +43,10 @@ public void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestNotInCSharp10() - { - await new VerifyCS.Test + public Task TestNotInCSharp10() + => new VerifyCS.Test { TestCode = """ @@ -63,12 +60,10 @@ public void M() """, LanguageVersion = LanguageVersion.CSharp10 }.RunAsync(); - } [Fact] - public async Task TestNotWhenNoReadOnlySpan() - { - await new VerifyCS.Test + public Task TestNotWhenNoReadOnlySpan() + => new VerifyCS.Test { TestCode = """ @@ -83,12 +78,10 @@ public void M() ReferenceAssemblies = ReferenceAssemblies.NetFramework.Net20.Default, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestNotWithoutInitializer() - { - await new VerifyCS.Test + public Task TestNotWithoutInitializer() + => new VerifyCS.Test { TestCode = """ @@ -103,12 +96,10 @@ public void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestNotInExpressionTree() - { - await new VerifyCS.Test + public Task TestNotInExpressionTree() + => new VerifyCS.Test { TestCode = """ @@ -130,12 +121,10 @@ public void N(Expression> f) ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestNotWhenNotByteArray() - { - await new VerifyCS.Test + public Task TestNotWhenNotByteArray() + => new VerifyCS.Test { TestCode = """ @@ -150,12 +139,10 @@ public void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestNotWhenOptionNotSet() - { - await new VerifyCS.Test + public Task TestNotWhenOptionNotSet() + => new VerifyCS.Test { TestCode = """ @@ -174,12 +161,10 @@ public void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestNotWhenNonLiteralElement() - { - await new VerifyCS.Test + public Task TestNotWhenNonLiteralElement() + => new VerifyCS.Test { TestCode = """ @@ -196,12 +181,10 @@ public void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestNotWhenMultidimensionalArray() - { - await new VerifyCS.Test + public Task TestNotWhenMultidimensionalArray() + => new VerifyCS.Test { TestCode = """ @@ -216,12 +199,10 @@ public void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestSimpleByteArray() - { - await new VerifyCS.Test + public Task TestSimpleByteArray() + => new VerifyCS.Test { TestCode = """ @@ -247,12 +228,10 @@ public void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestConstant() - { - await new VerifyCS.Test + public Task TestConstant() + => new VerifyCS.Test { TestCode = """ @@ -280,12 +259,10 @@ public void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestImplicitArray() - { - await new VerifyCS.Test + public Task TestImplicitArray() + => new VerifyCS.Test { TestCode = """ @@ -311,12 +288,10 @@ public void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestExplicitCast() - { - await new VerifyCS.Test + public Task TestExplicitCast() + => new VerifyCS.Test { TestCode = """ @@ -342,12 +317,10 @@ public void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestHexLiteral() - { - await new VerifyCS.Test + public Task TestHexLiteral() + => new VerifyCS.Test { TestCode = """ @@ -373,12 +346,10 @@ public void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestBinaryExpression() - { - await new VerifyCS.Test + public Task TestBinaryExpression() + => new VerifyCS.Test { TestCode = """ @@ -404,12 +375,10 @@ public void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestEmptyArray() - { - await new VerifyCS.Test + public Task TestEmptyArray() + => new VerifyCS.Test { TestCode = """ @@ -434,12 +403,10 @@ public void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestTrivia1() - { - await new VerifyCS.Test + public Task TestTrivia1() + => new VerifyCS.Test { TestCode = """ @@ -465,12 +432,10 @@ public void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestTrivia2() - { - await new VerifyCS.Test + public Task TestTrivia2() + => new VerifyCS.Test { TestCode = """ @@ -496,12 +461,10 @@ public void M(byte[] b) ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestMultiple() - { - await new VerifyCS.Test + public Task TestMultiple() + => new VerifyCS.Test { TestCode = """ @@ -531,12 +494,10 @@ public void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestEscapeChars() - { - await new VerifyCS.Test + public Task TestEscapeChars() + => new VerifyCS.Test { TestCode = """ @@ -562,12 +523,10 @@ public void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestEmoji() - { - await new VerifyCS.Test + public Task TestEmoji() + => new VerifyCS.Test { TestCode = """ @@ -593,12 +552,10 @@ public void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestHalfEmoji1() - { - await new VerifyCS.Test + public Task TestHalfEmoji1() + => new VerifyCS.Test { TestCode = """ @@ -614,12 +571,10 @@ public void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestHalfEmoji2() - { - await new VerifyCS.Test + public Task TestHalfEmoji2() + => new VerifyCS.Test { TestCode = """ @@ -635,12 +590,10 @@ public void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestHalfEmoji3() - { - await new VerifyCS.Test + public Task TestHalfEmoji3() + => new VerifyCS.Test { TestCode = """ @@ -656,15 +609,10 @@ public void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestUnicodeReplacementChar() - { - // The unicode replacement character is what is returned when, for example, an unpaired - // surrogate is converted to a UTF-8 string. This test just ensures that the presence of - // that character isn't being used to detect a failure state of some kind. - await new VerifyCS.Test + public Task TestUnicodeReplacementChar() + => new VerifyCS.Test { TestCode = """ @@ -690,12 +638,10 @@ public void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestCollectionInitializer() - { - await new VerifyCS.Test + public Task TestCollectionInitializer() + => new VerifyCS.Test { TestCode = """ @@ -771,14 +717,10 @@ IEnumerator IEnumerable.GetEnumerator() ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestUsingWithParamArray() - { - // From: https://github.com/dotnet/roslyn/blob/0c7c0b33f0871fc4308eb2d75d77b87fc9293290/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IUsingStatement.cs#L1189-L1194 - // There is an array creation operation for the param array - await new VerifyCS.Test + public Task TestUsingWithParamArray() + => new VerifyCS.Test { TestCode = """ @@ -799,7 +741,6 @@ public void Dispose(int a = 1, bool b = true, params byte[] others) { } ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Theory] // Standard C# escape characters @@ -817,9 +758,8 @@ public void Dispose(int a = 1, bool b = true, params byte[] others) { } [InlineData(new byte[] { 0x3f, 0x01 })] // DaysInMonth365 from https://github.com/dotnet/runtime/blob/b5a8ece073110140e2d9696cdfdc047ec78c2fa1/src/libraries/System.Private.CoreLib/src/System/DateTime.cs [InlineData(new byte[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 })] - public async Task TestInvalidUtf8Strings(byte[] bytes) - { - await new VerifyCS.Test + public Task TestInvalidUtf8Strings(byte[] bytes) + => new VerifyCS.Test { TestCode = $$""" @@ -832,13 +772,12 @@ public class C ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestDoesNotOfferForControlCharacters() - { - // Copied from https://github.com/dotnet/runtime/blob/6a889d234267a4c96ed21d0e1660dce787d78a38/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Conversion.cs - var input = """ + public Task TestDoesNotOfferForControlCharacters() + => new VerifyCS.Test + { + TestCode = """ class C { internal enum ConvKind @@ -878,21 +817,15 @@ internal enum ConvKind new byte[] /* U8 */ { EXP, EXP, EXP, EXP, IMP, IMP, IUD, EXP, NO, EXP, EXP, EXP, ID }, }; } - """; - - await new VerifyCS.Test - { - TestCode = input, + """, CodeActionValidationMode = CodeActionValidationMode.None, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestParamArray1() - { - await new VerifyCS.Test + public Task TestParamArray1() + => new VerifyCS.Test { TestCode = """ @@ -918,12 +851,10 @@ public void M(params byte[] b) ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestParamArray2() - { - await new VerifyCS.Test + public Task TestParamArray2() + => new VerifyCS.Test { TestCode = """ @@ -949,12 +880,10 @@ public void M(int i, params byte[] b) ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestParamArray3() - { - await new VerifyCS.Test + public Task TestParamArray3() + => new VerifyCS.Test { TestCode = """ @@ -980,12 +909,10 @@ public void M(params byte[] b) ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestParamArray4() - { - await new VerifyCS.Test + public Task TestParamArray4() + => new VerifyCS.Test { TestCode = """ @@ -1011,12 +938,10 @@ public void M(params byte[] b) ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestParamArray5() - { - await new VerifyCS.Test + public Task TestParamArray5() + => new VerifyCS.Test { TestCode = """ @@ -1042,12 +967,10 @@ public void M(params byte[] b) ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestParamArray6() - { - await new VerifyCS.Test + public Task TestParamArray6() + => new VerifyCS.Test { TestCode = """ @@ -1073,12 +996,10 @@ public void M(params byte[] b) ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestParamArray7() - { - await new VerifyCS.Test + public Task TestParamArray7() + => new VerifyCS.Test { TestCode = """ @@ -1093,12 +1014,10 @@ public void M(int x, params byte[] b) ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestParamArray8() - { - await new VerifyCS.Test + public Task TestParamArray8() + => new VerifyCS.Test { TestCode = """ @@ -1124,12 +1043,10 @@ public void M(int x, params byte[] b) ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestParamArray9() - { - await new VerifyCS.Test + public Task TestParamArray9() + => new VerifyCS.Test { TestCode = """ @@ -1155,12 +1072,10 @@ public void M(int x, params byte[] b) ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestParamArray10() - { - await new VerifyCS.Test + public Task TestParamArray10() + => new VerifyCS.Test { TestCode = """ @@ -1186,12 +1101,10 @@ public void M(int x, params byte[] b) ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestParamArray11() - { - await new VerifyCS.Test + public Task TestParamArray11() + => new VerifyCS.Test { TestCode = """ @@ -1217,12 +1130,10 @@ public void M(int x, int y, int z, params byte[] b) ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestParamArray12() - { - await new VerifyCS.Test + public Task TestParamArray12() + => new VerifyCS.Test { TestCode = """ @@ -1248,12 +1159,10 @@ public C(params byte[] b) ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestParamArray13() - { - await new VerifyCS.Test + public Task TestParamArray13() + => new VerifyCS.Test { TestCode = """ @@ -1289,12 +1198,10 @@ public void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestParamArray14() - { - await new VerifyCS.Test + public Task TestParamArray14() + => new VerifyCS.Test { TestCode = """ @@ -1344,12 +1251,10 @@ public sealed class IsExternalInit ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestParamArray15() - { - await new VerifyCS.Test + public Task TestParamArray15() + => new VerifyCS.Test { TestCode = """ @@ -1433,12 +1338,10 @@ public B(params byte[] bytes) ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestParamArray16() - { - await new VerifyCS.Test + public Task TestParamArray16() + => new VerifyCS.Test { TestCode = """ @@ -1464,12 +1367,10 @@ public void M(int[] i, byte[] b) ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestParamArray17() - { - await new VerifyCS.Test + public Task TestParamArray17() + => new VerifyCS.Test { TestCode = """ @@ -1495,12 +1396,10 @@ public void M(int[] i, params byte[] b) ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestMultidimensionalArray() - { - await new VerifyCS.Test + public Task TestMultidimensionalArray() + => new VerifyCS.Test { TestCode = """ @@ -1526,12 +1425,10 @@ public void M(byte[][] i, byte[] b) ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestTargettingReadOnlySpan1() - { - await new VerifyCS.Test + public Task TestTargettingReadOnlySpan1() + => new VerifyCS.Test { TestCode = """ @@ -1561,12 +1458,10 @@ public void M() ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } [Fact] - public async Task TestTargettingReadOnlySpan2() - { - await new VerifyCS.Test + public Task TestTargettingReadOnlySpan2() + => new VerifyCS.Test { TestCode = """ @@ -1596,5 +1491,4 @@ public void M(ReadOnlySpan x) ReferenceAssemblies = ReferenceAssemblies.Net.Net60, LanguageVersion = LanguageVersion.CSharp12 }.RunAsync(); - } } diff --git a/src/Analyzers/CSharp/Tests/ValidateFormatString/ValidateFormatStringTests.cs b/src/Analyzers/CSharp/Tests/ValidateFormatString/ValidateFormatStringTests.cs index 86434c0a18a40..c53cf8420a48b 100644 --- a/src/Analyzers/CSharp/Tests/ValidateFormatString/ValidateFormatStringTests.cs +++ b/src/Analyzers/CSharp/Tests/ValidateFormatString/ValidateFormatStringTests.cs @@ -27,9 +27,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider?) CreateDiagnosticProvide => (new CSharpValidateFormatStringDiagnosticAnalyzer(), null); [Fact] - public async Task OnePlaceholder() - { - await TestDiagnosticMissingAsync(""" + public Task OnePlaceholder() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -38,12 +37,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TwoPlaceholders() - { - await TestDiagnosticMissingAsync(""" + public Task TwoPlaceholders() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -52,12 +49,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task ThreePlaceholders() - { - await TestDiagnosticMissingAsync(""" + public Task ThreePlaceholders() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -66,12 +61,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task FourPlaceholders() - { - await TestDiagnosticMissingAsync(""" + public Task FourPlaceholders() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -81,12 +74,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task ObjectArray() - { - await TestDiagnosticMissingAsync(""" + public Task ObjectArray() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -96,12 +87,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task MultipleObjectArrays() - { - await TestDiagnosticMissingAsync(""" + public Task MultipleObjectArrays() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -111,12 +100,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task IntArray() - { - await TestDiagnosticMissingAsync(""" + public Task IntArray() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -126,12 +113,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task StringArray() - { - await TestDiagnosticMissingAsync(""" + public Task StringArray() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -141,12 +126,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task LiteralArray() - { - await TestDiagnosticMissingAsync(""" + public Task LiteralArray() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -155,12 +138,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task StringArrayOutOfBounds_NoDiagnostic() - { - await TestDiagnosticMissingAsync(""" + public Task StringArrayOutOfBounds_NoDiagnostic() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -170,12 +151,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task IFormatProviderAndOnePlaceholder() - { - await TestDiagnosticMissingAsync(""" + public Task IFormatProviderAndOnePlaceholder() + => TestDiagnosticMissingAsync(""" using System.Globalization; class Program { @@ -185,12 +164,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task IFormatProviderAndTwoPlaceholders() - { - await TestDiagnosticMissingAsync(""" + public Task IFormatProviderAndTwoPlaceholders() + => TestDiagnosticMissingAsync(""" using System.Globalization; class Program { @@ -200,12 +177,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task IFormatProviderAndThreePlaceholders() - { - await TestDiagnosticMissingAsync(""" + public Task IFormatProviderAndThreePlaceholders() + => TestDiagnosticMissingAsync(""" using System.Globalization; class Program { @@ -216,12 +191,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task IFormatProviderAndFourPlaceholders() - { - await TestDiagnosticMissingAsync(""" + public Task IFormatProviderAndFourPlaceholders() + => TestDiagnosticMissingAsync(""" using System.Globalization; class Program { @@ -232,12 +205,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task IFormatProviderAndObjectArray() - { - await TestDiagnosticMissingAsync(""" + public Task IFormatProviderAndObjectArray() + => TestDiagnosticMissingAsync(""" using System.Globalization; class Program { @@ -248,12 +219,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task WithComma() - { - await TestDiagnosticMissingAsync(""" + public Task WithComma() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -262,12 +231,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task WithColon() - { - await TestDiagnosticMissingAsync(""" + public Task WithColon() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -276,12 +243,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task WithCommaAndColon() - { - await TestDiagnosticMissingAsync(""" + public Task WithCommaAndColon() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -290,12 +255,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task WithPlaceholderAtBeginning() - { - await TestDiagnosticMissingAsync(""" + public Task WithPlaceholderAtBeginning() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -304,12 +267,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task WithPlaceholderAtEnd() - { - await TestDiagnosticMissingAsync(""" + public Task WithPlaceholderAtEnd() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -318,12 +279,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task WithDoubleBraces() - { - await TestDiagnosticMissingAsync(""" + public Task WithDoubleBraces() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -332,12 +291,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task WithDoubleBracesAtBeginning() - { - await TestDiagnosticMissingAsync(""" + public Task WithDoubleBracesAtBeginning() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -346,12 +303,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task WithDoubleBracesAtEnd() - { - await TestDiagnosticMissingAsync(""" + public Task WithDoubleBracesAtEnd() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -360,12 +315,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task WithTripleBraces() - { - await TestDiagnosticMissingAsync(""" + public Task WithTripleBraces() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -374,12 +327,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task NamedParameters() - { - await TestDiagnosticMissingAsync(""" + public Task NamedParameters() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -388,12 +339,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task NamedParametersWithIFormatProvider() - { - await TestDiagnosticMissingAsync(""" + public Task NamedParametersWithIFormatProvider() + => TestDiagnosticMissingAsync(""" using System.Globalization; class Program { @@ -403,12 +352,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task NamespaceAliasForStringClass() - { - await TestDiagnosticMissingAsync(""" + public Task NamespaceAliasForStringClass() + => TestDiagnosticMissingAsync(""" using stringAlias = System.String; class Program { @@ -418,12 +365,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task MethodCallAsAnArgumentToAnotherMethod() - { - await TestDiagnosticMissingAsync(""" + public Task MethodCallAsAnArgumentToAnotherMethod() + => TestDiagnosticMissingAsync(""" using System.IO; class Program { @@ -433,12 +378,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task VerbatimMultipleLines() - { - await TestDiagnosticMissingAsync(""" + public Task VerbatimMultipleLines() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -448,12 +391,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task Interpolated() - { - await TestDiagnosticMissingAsync(""" + public Task Interpolated() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -465,12 +406,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task Empty() - { - await TestDiagnosticMissingAsync(""" + public Task Empty() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -479,12 +418,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task LeftParenOnly() - { - await TestDiagnosticMissingAsync(""" + public Task LeftParenOnly() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -493,12 +430,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task ParenthesesOnly() - { - await TestDiagnosticMissingAsync(""" + public Task ParenthesesOnly() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -507,12 +442,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task EmptyString() - { - await TestDiagnosticMissingAsync(""" + public Task EmptyString() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -521,12 +454,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task FormatOnly_NoStringDot() - { - await TestDiagnosticMissingAsync(""" + public Task FormatOnly_NoStringDot() + => TestDiagnosticMissingAsync(""" using static System.String class Program { @@ -536,12 +467,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task NamedParameters_BlankName() - { - await TestDiagnosticMissingAsync(""" + public Task NamedParameters_BlankName() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -550,12 +479,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task DuplicateNamedArgs() - { - await TestDiagnosticMissingAsync(""" + public Task DuplicateNamedArgs() + => TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -564,12 +491,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task GenericIdentifier() - { - await TestDiagnosticMissingAsync(""" + public Task GenericIdentifier() + => TestDiagnosticMissingAsync(""" using System; using System.Collections; using System.Collections.Generic; @@ -595,12 +520,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task ClassNamedString() - { - await TestDiagnosticMissingAsync(""" + public Task ClassNamedString() + => TestDiagnosticMissingAsync(""" using System; namespace System @@ -619,12 +542,14 @@ static void Main(string[] args) } } """); - } [Fact] public async Task TestOption_Enabled() { - var source = """ + var options = Option(FormatStringValidationOptionStorage.ReportInvalidPlaceholdersInStringDotFormatCalls, true); + + await TestDiagnosticInfoAsync( + """ class Program { static void Main(string[] args) @@ -632,11 +557,7 @@ static void Main(string[] args) string.Format("This [|{1}|] is my test", "teststring1"); } } - """; - var options = Option(FormatStringValidationOptionStorage.ReportInvalidPlaceholdersInStringDotFormatCalls, true); - - await TestDiagnosticInfoAsync( - source, + """, options: options, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, @@ -646,7 +567,9 @@ await TestDiagnosticInfoAsync( [Fact] public async Task TestOption_Disabled() { - var source = """ + var options = Option(FormatStringValidationOptionStorage.ReportInvalidPlaceholdersInStringDotFormatCalls, false); + + await TestDiagnosticMissingAsync(""" class Program { static void Main(string[] args) @@ -654,16 +577,12 @@ static void Main(string[] args) string.Format("This [|{1}|] is my test", "teststring1"); } } - """; - var options = Option(FormatStringValidationOptionStorage.ReportInvalidPlaceholdersInStringDotFormatCalls, false); - - await TestDiagnosticMissingAsync(source, new TestParameters(options: options)); + """, new TestParameters(options: options)); } [Fact] - public async Task OnePlaceholderOutOfBounds() - { - await TestDiagnosticInfoAsync(""" + public Task OnePlaceholderOutOfBounds() + => TestDiagnosticInfoAsync(""" class Program { static void Main(string[] args) @@ -676,12 +595,10 @@ static void Main(string[] args) diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); - } [Fact] - public async Task TwoPlaceholdersWithOnePlaceholderOutOfBounds() - { - await TestDiagnosticInfoAsync(""" + public Task TwoPlaceholdersWithOnePlaceholderOutOfBounds() + => TestDiagnosticInfoAsync(""" class Program { static void Main(string[] args) @@ -694,12 +611,10 @@ static void Main(string[] args) diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); - } [Fact] - public async Task ThreePlaceholdersWithOnePlaceholderOutOfBounds() - { - await TestDiagnosticInfoAsync(""" + public Task ThreePlaceholdersWithOnePlaceholderOutOfBounds() + => TestDiagnosticInfoAsync(""" class Program { static void Main(string[] args) @@ -712,12 +627,10 @@ static void Main(string[] args) diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); - } [Fact] - public async Task FourPlaceholdersWithOnePlaceholderOutOfBounds() - { - await TestDiagnosticInfoAsync(""" + public Task FourPlaceholdersWithOnePlaceholderOutOfBounds() + => TestDiagnosticInfoAsync(""" class Program { static void Main(string[] args) @@ -731,12 +644,10 @@ static void Main(string[] args) diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); - } [Fact] - public async Task iFormatProviderAndOnePlaceholderOutOfBounds() - { - await TestDiagnosticInfoAsync(""" + public Task iFormatProviderAndOnePlaceholderOutOfBounds() + => TestDiagnosticInfoAsync(""" using System.Globalization; class Program { @@ -750,12 +661,10 @@ static void Main(string[] args) diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); - } [Fact] - public async Task iFormatProviderAndTwoPlaceholdersWithOnePlaceholderOutOfBounds() - { - await TestDiagnosticInfoAsync(""" + public Task iFormatProviderAndTwoPlaceholdersWithOnePlaceholderOutOfBounds() + => TestDiagnosticInfoAsync(""" using System.Globalization; class Program { @@ -769,12 +678,10 @@ static void Main(string[] args) diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); - } [Fact] - public async Task IFormatProviderAndThreePlaceholdersWithOnePlaceholderOutOfBounds() - { - await TestDiagnosticInfoAsync(""" + public Task IFormatProviderAndThreePlaceholdersWithOnePlaceholderOutOfBounds() + => TestDiagnosticInfoAsync(""" using System.Globalization; class Program { @@ -789,12 +696,10 @@ static void Main(string[] args) diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); - } [Fact] - public async Task IFormatProviderAndFourPlaceholdersWithOnePlaceholderOutOfBounds() - { - await TestDiagnosticInfoAsync(""" + public Task IFormatProviderAndFourPlaceholdersWithOnePlaceholderOutOfBounds() + => TestDiagnosticInfoAsync(""" using System.Globalization; class Program { @@ -809,12 +714,10 @@ static void Main(string[] args) diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); - } [Fact] - public async Task PlaceholderAtBeginningWithOnePlaceholderOutOfBounds() - { - await TestDiagnosticInfoAsync(""" + public Task PlaceholderAtBeginningWithOnePlaceholderOutOfBounds() + => TestDiagnosticInfoAsync(""" class Program { static void Main(string[] args) @@ -827,12 +730,10 @@ static void Main(string[] args) diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); - } [Fact] - public async Task PlaceholderAtEndWithOnePlaceholderOutOfBounds() - { - await TestDiagnosticInfoAsync(""" + public Task PlaceholderAtEndWithOnePlaceholderOutOfBounds() + => TestDiagnosticInfoAsync(""" class Program { static void Main(string[] args) @@ -845,12 +746,10 @@ static void Main(string[] args) diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); - } [Fact] - public async Task DoubleBracesAtBeginningWithOnePlaceholderOutOfBounds() - { - await TestDiagnosticInfoAsync(""" + public Task DoubleBracesAtBeginningWithOnePlaceholderOutOfBounds() + => TestDiagnosticInfoAsync(""" class Program { static void Main(string[] args) @@ -863,12 +762,10 @@ static void Main(string[] args) diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); - } [Fact] - public async Task DoubleBracesAtEndWithOnePlaceholderOutOfBounds() - { - await TestDiagnosticInfoAsync(""" + public Task DoubleBracesAtEndWithOnePlaceholderOutOfBounds() + => TestDiagnosticInfoAsync(""" class Program { static void Main(string[] args) @@ -881,12 +778,10 @@ static void Main(string[] args) diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); - } [Fact] - public async Task NamedParametersOneOutOfBounds() - { - await TestDiagnosticInfoAsync(""" + public Task NamedParametersOneOutOfBounds() + => TestDiagnosticInfoAsync(""" using System.Globalization; class Program { @@ -900,12 +795,10 @@ static void Main(string[] args) diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); - } [Fact] - public async Task NamedParametersWithIFormatProviderOneOutOfBounds() - { - await TestDiagnosticInfoAsync(""" + public Task NamedParametersWithIFormatProviderOneOutOfBounds() + => TestDiagnosticInfoAsync(""" using System.Globalization; class Program { @@ -919,12 +812,10 @@ static void Main(string[] args) diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); - } [Fact] - public async Task FormatOnly_NoStringDot_OneOutOfBounds() - { - await TestDiagnosticInfoAsync(""" + public Task FormatOnly_NoStringDot_OneOutOfBounds() + => TestDiagnosticInfoAsync(""" using static System.String class Program { @@ -938,12 +829,10 @@ static void Main(string[] args) diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); - } [Fact] - public async Task Net45TestOutOfBounds() - { - var input = """ + public Task Net45TestOutOfBounds() + => TestDiagnosticInfoAsync(""" < Workspace > < Project Language = "C#" AssemblyName="Assembly1" CommonReferencesNet45="true"> - """; - await TestDiagnosticInfoAsync(input, + """, options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); - } [Fact] - public async Task VerbatimMultipleLinesPlaceholderOutOfBounds() - { - await TestDiagnosticInfoAsync(""" + public Task VerbatimMultipleLinesPlaceholderOutOfBounds() + => TestDiagnosticInfoAsync(""" class Program { static void Main(string[] args) @@ -984,12 +870,10 @@ static void Main(string[] args) diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); - } [Fact] - public async Task IntArrayOutOfBounds() - { - await TestDiagnosticInfoAsync(""" + public Task IntArrayOutOfBounds() + => TestDiagnosticInfoAsync(""" class Program { static void Main(string[] args) @@ -1003,12 +887,10 @@ static void Main(string[] args) diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); - } [Fact] - public async Task FirstPlaceholderOutOfBounds() - { - await TestDiagnosticInfoAsync(""" + public Task FirstPlaceholderOutOfBounds() + => TestDiagnosticInfoAsync(""" class Program { static void Main(string[] args) @@ -1022,12 +904,10 @@ static void Main(string[] args) diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); - } [Fact] - public async Task SecondPlaceholderOutOfBounds() - { - await TestDiagnosticInfoAsync(""" + public Task SecondPlaceholderOutOfBounds() + => TestDiagnosticInfoAsync(""" class Program { static void Main(string[] args) @@ -1041,12 +921,10 @@ static void Main(string[] args) diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); - } [Fact] - public async Task FirstOfMultipleSameNamedPlaceholderOutOfBounds() - { - await TestDiagnosticInfoAsync(""" + public Task FirstOfMultipleSameNamedPlaceholderOutOfBounds() + => TestDiagnosticInfoAsync(""" class Program { static void Main(string[] args) @@ -1060,12 +938,10 @@ static void Main(string[] args) diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); - } [Fact] - public async Task SecondOfMultipleSameNamedPlaceholderOutOfBounds() - { - await TestDiagnosticInfoAsync(""" + public Task SecondOfMultipleSameNamedPlaceholderOutOfBounds() + => TestDiagnosticInfoAsync(""" class Program { static void Main(string[] args) @@ -1079,12 +955,10 @@ static void Main(string[] args) diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); - } [Fact] - public async Task EmptyPlaceholder() - { - await TestDiagnosticInfoAsync(""" + public Task EmptyPlaceholder() + => TestDiagnosticInfoAsync(""" class Program { static void Main(string[] args) @@ -1098,12 +972,10 @@ static void Main(string[] args) diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29398")] - public async Task LocalFunctionNamedFormat() - { - await TestDiagnosticMissingAsync(""" + public Task LocalFunctionNamedFormat() + => TestDiagnosticMissingAsync(""" public class C { public void M() @@ -1113,5 +985,4 @@ void Format() { } } } """); - } } diff --git a/src/Analyzers/Core/Analyzers/AddRequiredParentheses/AbstractAddRequiredParenthesesDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/AddRequiredParentheses/AbstractAddRequiredParenthesesDiagnosticAnalyzer.cs index 75fe79115341b..e7ce5526c2da4 100644 --- a/src/Analyzers/Core/Analyzers/AddRequiredParentheses/AbstractAddRequiredParenthesesDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/AddRequiredParentheses/AbstractAddRequiredParenthesesDiagnosticAnalyzer.cs @@ -12,15 +12,19 @@ namespace Microsoft.CodeAnalysis.AddRequiredParentheses; internal abstract class AbstractAddRequiredParenthesesDiagnosticAnalyzer< - TExpressionSyntax, TBinaryLikeExpressionSyntax, TLanguageKindEnum> - : AbstractBuiltInCodeStyleDiagnosticAnalyzer + TExpressionSyntax, TBinaryLikeExpressionSyntax, TLanguageKindEnum>(IPrecedenceService precedenceService) + : AbstractBuiltInCodeStyleDiagnosticAnalyzer(IDEDiagnosticIds.AddRequiredParenthesesDiagnosticId, + EnforceOnBuildValues.AddRequiredParentheses, + options: ParenthesesDiagnosticAnalyzersHelper.Options, + new LocalizableResourceString(nameof(AnalyzersResources.Add_parentheses_for_clarity), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), + new LocalizableResourceString(nameof(AnalyzersResources.Parentheses_should_be_added_for_clarity), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) where TExpressionSyntax : SyntaxNode where TBinaryLikeExpressionSyntax : TExpressionSyntax where TLanguageKindEnum : struct { private static readonly Dictionary<(bool includeInFixAll, string equivalenceKey), ImmutableDictionary> s_cachedProperties = []; - private readonly IPrecedenceService _precedenceService; + private readonly IPrecedenceService _precedenceService = precedenceService; static AbstractAddRequiredParenthesesDiagnosticAnalyzer() { @@ -42,6 +46,14 @@ static AbstractAddRequiredParenthesesDiagnosticAnalyzer() } } + private static PrecedenceKind CollapsePrecedenceGroups(PrecedenceKind precedenceKind) + => precedenceKind switch + { + PrecedenceKind.Arithmetic or PrecedenceKind.Shift or PrecedenceKind.Bitwise => PrecedenceKind.Arithmetic, + PrecedenceKind.Relational or PrecedenceKind.Equality => PrecedenceKind.Relational, + _ => precedenceKind, + }; + protected static string GetEquivalenceKey(PrecedenceKind precedenceKind) => precedenceKind switch { @@ -62,16 +74,7 @@ protected static ImmutableArray GetAllEquivalenceKeys() protected abstract TExpressionSyntax? TryGetAppropriateParent(TBinaryLikeExpressionSyntax binaryLike); protected abstract bool IsBinaryLike(TExpressionSyntax node); protected abstract (TExpressionSyntax, SyntaxToken, TExpressionSyntax) GetPartsOfBinaryLike(TBinaryLikeExpressionSyntax binaryLike); - - protected AbstractAddRequiredParenthesesDiagnosticAnalyzer(IPrecedenceService precedenceService) - : base(IDEDiagnosticIds.AddRequiredParenthesesDiagnosticId, - EnforceOnBuildValues.AddRequiredParentheses, - options: ParenthesesDiagnosticAnalyzersHelper.Options, - new LocalizableResourceString(nameof(AnalyzersResources.Add_parentheses_for_clarity), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), - new LocalizableResourceString(nameof(AnalyzersResources.Parentheses_should_be_added_for_clarity), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) - { - _precedenceService = precedenceService; - } + protected abstract bool IsAsExpression(TBinaryLikeExpressionSyntax node); public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; @@ -86,28 +89,21 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) var binaryLike = (TBinaryLikeExpressionSyntax)context.Node; var parent = TryGetAppropriateParent(binaryLike); if (parent == null || !IsBinaryLike(parent)) - { return; - } var parentBinaryLike = (TBinaryLikeExpressionSyntax)parent; if (GetPrecedence(binaryLike) == GetPrecedence(parentBinaryLike)) - { return; - } var options = context.GetAnalyzerOptions(); var childPrecedenceKind = _precedenceService.GetPrecedenceKind(binaryLike); var parentPrecedenceKind = _precedenceService.GetPrecedenceKind(parentBinaryLike); - var childEquivalenceKey = GetEquivalenceKey(childPrecedenceKind); - var parentEquivalenceKey = GetEquivalenceKey(parentPrecedenceKind); + var collapsedChildPrecedenceKind = CollapsePrecedenceGroups(childPrecedenceKind); + var collapsedParentPrecedenceKind = CollapsePrecedenceGroups(parentPrecedenceKind); - // only add parentheses within the same precedence band. - if (childEquivalenceKey != parentEquivalenceKey) - { + if (IsClearPrecedenceBoundary()) return; - } var preference = ParenthesesDiagnosticAnalyzersHelper.GetLanguageOption(options, childPrecedenceKind); if (preference.Value != ParenthesesPreference.AlwaysForClarity @@ -124,7 +120,45 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) // both *'s. AddDiagnostics( context, binaryLike, precedence, preference.Notification, - additionalLocations, childEquivalenceKey, includeInFixAll: true); + additionalLocations, GetEquivalenceKey(childPrecedenceKind), includeInFixAll: true); + + bool IsClearPrecedenceBoundary() + { + // Generally, we only add parentheses within the same precedence band, as normally it is clear + // between bands that there is no precedence concern. For example, `a + b == c + d`. Users + // generally understand that `==` will have lower precedence and will not somehow group the + // expression like `a + (b == c) + d`. This is also generally quite clear as the type domains + // are commonly different. e.g. `a + b` will operate on some numeric type domain, while `==` is + // operating in the boolean domain. So you would immediately have a type error in the common + // case if grouping didn't operate as expected. + // + // this is not always the case though. `??` in particular can be quite confusing as it generally + // operates in teh same type domain (or the nullable extension of that type). For example: + // + // a + b ?? c + // + // Is this `(a + b) ?? c` or `a + (b ?? c)`. It is not particularly clear, and both interpretations + // can often work due to the compatibility of the type domains. + + // If the expressions have the same precedence, then they definitely don't have a clear precedence + // boundary between then. + if (collapsedChildPrecedenceKind == collapsedParentPrecedenceKind) + return false; + + // They are in different precedence classes, but 'coalesce' is itself quite confusing, so this should + // still be parenthesized for clarity if the user has that option on. + if (collapsedParentPrecedenceKind is PrecedenceKind.Coalesce) + { + // Note: we have an exception for `a as b ?? c`. In this case, because `as` so clearly only accepts + // a type on the RHS, this is idiomatically understood to be `(a as b) ?? c`, not `a as (b ?? c). + // So we don't parenthesize this case. + if (collapsedChildPrecedenceKind < PrecedenceKind.Coalesce && !IsAsExpression(binaryLike)) + return false; + } + + // Otherwise, this is clear enough on its face, and we should do nothing + return true; + } } private void AddDiagnostics( diff --git a/src/Analyzers/Core/Analyzers/Analyzers.projitems b/src/Analyzers/Core/Analyzers/Analyzers.projitems index 45e0c4005a393..0c0389522e839 100644 --- a/src/Analyzers/Core/Analyzers/Analyzers.projitems +++ b/src/Analyzers/Core/Analyzers/Analyzers.projitems @@ -104,6 +104,7 @@ + diff --git a/src/Analyzers/Core/Analyzers/DiagnosticCustomTags.cs b/src/Analyzers/Core/Analyzers/DiagnosticCustomTags.cs index 3fdd9a4de185c..c3e2f7ac5d67b 100644 --- a/src/Analyzers/Core/Analyzers/DiagnosticCustomTags.cs +++ b/src/Analyzers/Core/Analyzers/DiagnosticCustomTags.cs @@ -13,56 +13,50 @@ internal static class DiagnosticCustomTags { private static readonly string s_enforceOnBuildNeverTag = EnforceOnBuild.Never.ToCustomTag(); - private static readonly string[] s_microsoftCustomTags = [WellKnownDiagnosticTags.Telemetry]; - private static readonly string[] s_editAndContinueCustomTags = [WellKnownDiagnosticTags.EditAndContinue, WellKnownDiagnosticTags.Telemetry, WellKnownDiagnosticTags.NotConfigurable, s_enforceOnBuildNeverTag]; - private static readonly string[] s_unnecessaryCustomTags = [WellKnownDiagnosticTags.Unnecessary, WellKnownDiagnosticTags.Telemetry]; - private static readonly string[] s_notConfigurableCustomTags = [WellKnownDiagnosticTags.NotConfigurable, s_enforceOnBuildNeverTag, WellKnownDiagnosticTags.Telemetry]; - private static readonly string[] s_unnecessaryAndNotConfigurableCustomTags = [WellKnownDiagnosticTags.Unnecessary, WellKnownDiagnosticTags.NotConfigurable, s_enforceOnBuildNeverTag, WellKnownDiagnosticTags.Telemetry]; - public static string[] Microsoft { get { - Assert(s_microsoftCustomTags, WellKnownDiagnosticTags.Telemetry); - return s_microsoftCustomTags; + Assert(field, WellKnownDiagnosticTags.Telemetry); + return field; } - } + } = [WellKnownDiagnosticTags.Telemetry]; public static string[] EditAndContinue { get { - Assert(s_editAndContinueCustomTags, WellKnownDiagnosticTags.EditAndContinue, WellKnownDiagnosticTags.Telemetry, WellKnownDiagnosticTags.NotConfigurable, s_enforceOnBuildNeverTag); - return s_editAndContinueCustomTags; + Assert(field, WellKnownDiagnosticTags.EditAndContinue, WellKnownDiagnosticTags.Telemetry, WellKnownDiagnosticTags.NotConfigurable, s_enforceOnBuildNeverTag); + return field; } - } + } = [WellKnownDiagnosticTags.EditAndContinue, WellKnownDiagnosticTags.Telemetry, WellKnownDiagnosticTags.NotConfigurable, s_enforceOnBuildNeverTag]; public static string[] Unnecessary { get { - Assert(s_unnecessaryCustomTags, WellKnownDiagnosticTags.Unnecessary, WellKnownDiagnosticTags.Telemetry); - return s_unnecessaryCustomTags; + Assert(field, WellKnownDiagnosticTags.Unnecessary, WellKnownDiagnosticTags.Telemetry); + return field; } - } + } = [WellKnownDiagnosticTags.Unnecessary, WellKnownDiagnosticTags.Telemetry]; public static string[] NotConfigurable { get { - Assert(s_notConfigurableCustomTags, WellKnownDiagnosticTags.NotConfigurable, s_enforceOnBuildNeverTag, WellKnownDiagnosticTags.Telemetry); - return s_notConfigurableCustomTags; + Assert(field, WellKnownDiagnosticTags.NotConfigurable, s_enforceOnBuildNeverTag, WellKnownDiagnosticTags.Telemetry); + return field; } - } + } = [WellKnownDiagnosticTags.NotConfigurable, s_enforceOnBuildNeverTag, WellKnownDiagnosticTags.Telemetry]; public static string[] UnnecessaryAndNotConfigurable { get { - Assert(s_unnecessaryAndNotConfigurableCustomTags, WellKnownDiagnosticTags.Unnecessary, WellKnownDiagnosticTags.NotConfigurable, s_enforceOnBuildNeverTag, WellKnownDiagnosticTags.Telemetry); - return s_unnecessaryAndNotConfigurableCustomTags; + Assert(field, WellKnownDiagnosticTags.Unnecessary, WellKnownDiagnosticTags.NotConfigurable, s_enforceOnBuildNeverTag, WellKnownDiagnosticTags.Telemetry); + return field; } - } + } = [WellKnownDiagnosticTags.Unnecessary, WellKnownDiagnosticTags.NotConfigurable, s_enforceOnBuildNeverTag, WellKnownDiagnosticTags.Telemetry]; [Conditional("DEBUG")] private static void Assert(string[] customTags, params ReadOnlySpan tags) diff --git a/src/Analyzers/Core/Analyzers/ForEachCast/AbstractForEachCastDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/ForEachCast/AbstractForEachCastDiagnosticAnalyzer.cs index de67dfecef5ff..9f6fb9d14e4ec 100644 --- a/src/Analyzers/Core/Analyzers/ForEachCast/AbstractForEachCastDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/ForEachCast/AbstractForEachCastDiagnosticAnalyzer.cs @@ -9,7 +9,6 @@ using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Operations; -using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ForEachCast; diff --git a/src/Analyzers/Core/Analyzers/Formatting/AbstractFormattingAnalyzer.cs b/src/Analyzers/Core/Analyzers/Formatting/AbstractFormattingAnalyzer.cs index 4d168bbc826ef..dcdcc4d83d5aa 100644 --- a/src/Analyzers/Core/Analyzers/Formatting/AbstractFormattingAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/Formatting/AbstractFormattingAnalyzer.cs @@ -6,7 +6,6 @@ using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Text; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeStyle; diff --git a/src/Analyzers/Core/Analyzers/Helpers/DeserializationConstructorCheck.cs b/src/Analyzers/Core/Analyzers/Helpers/DeserializationConstructorCheck.cs index 5138c7ea6d79b..61de4f0a8d6b9 100644 --- a/src/Analyzers/Core/Analyzers/Helpers/DeserializationConstructorCheck.cs +++ b/src/Analyzers/Core/Analyzers/Helpers/DeserializationConstructorCheck.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Microsoft.CodeAnalysis.Shared.Extensions; - namespace Microsoft.CodeAnalysis.Shared.Utilities; internal readonly struct DeserializationConstructorCheck(Compilation compilation) diff --git a/src/Analyzers/Core/Analyzers/Helpers/HashCodeAnalyzer/HashCodeAnalyzer.cs b/src/Analyzers/Core/Analyzers/Helpers/HashCodeAnalyzer/HashCodeAnalyzer.cs index 4931395a53f80..f158e00b66003 100644 --- a/src/Analyzers/Core/Analyzers/Helpers/HashCodeAnalyzer/HashCodeAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/Helpers/HashCodeAnalyzer/HashCodeAnalyzer.cs @@ -14,23 +14,15 @@ namespace Microsoft.CodeAnalysis.Shared.Utilities; /// /// Helper code to support analysis of HashCode methods /// -internal readonly partial struct HashCodeAnalyzer +internal readonly partial struct HashCodeAnalyzer( + IMethodSymbol objectGetHashCodeMethod, + INamedTypeSymbol? equalityComparerType, + INamedTypeSymbol systemHashCodeType) { - private readonly Compilation _compilation; - private readonly IMethodSymbol _objectGetHashCodeMethod; - private readonly INamedTypeSymbol? _equalityComparerType; + private readonly IMethodSymbol _objectGetHashCodeMethod = objectGetHashCodeMethod; + private readonly INamedTypeSymbol? _equalityComparerType = equalityComparerType; - public readonly INamedTypeSymbol SystemHashCodeType; - - private HashCodeAnalyzer( - Compilation compilation, IMethodSymbol objectGetHashCodeMethod, - INamedTypeSymbol? equalityComparerType, INamedTypeSymbol systemHashCodeType) - { - _compilation = compilation; - _objectGetHashCodeMethod = objectGetHashCodeMethod; - _equalityComparerType = equalityComparerType; - SystemHashCodeType = systemHashCodeType; - } + public readonly INamedTypeSymbol SystemHashCodeType = systemHashCodeType; public static bool TryGetAnalyzer(Compilation compilation, [NotNullWhen(true)] out HashCodeAnalyzer analyzer) { @@ -47,7 +39,7 @@ public static bool TryGetAnalyzer(Compilation compilation, [NotNullWhen(true)] o if (systemHashCodeType == null) return false; - analyzer = new HashCodeAnalyzer(compilation, objectGetHashCodeMethod, equalityComparerType, systemHashCodeType); + analyzer = new HashCodeAnalyzer(objectGetHashCodeMethod, equalityComparerType, systemHashCodeType); return true; } @@ -129,31 +121,19 @@ public static bool TryGetAnalyzer(Compilation compilation, [NotNullWhen(true)] o // First statement has to be the declaration of the accumulator. // Last statement has to be the return of it. - if (statements.First() is not IVariableDeclarationGroupOperation varDeclStatement || - !(statements.Last() is IReturnOperation { ReturnedValue: { } returnedValue })) - { + if (statements is not [IVariableDeclarationGroupOperation varDeclStatement, .., IReturnOperation { ReturnedValue: { } returnedValue }]) return null; - } var variables = varDeclStatement.GetDeclaredVariables(); - if (variables.Length != 1 || - varDeclStatement.Declarations.Length != 1) - { + if (variables.Length != 1) return null; - } - var declaration = varDeclStatement.Declarations[0]; - if (declaration.Declarators.Length != 1) - { + if (varDeclStatement.Declarations is not [{ Declarators: [var declarator] } declaration]) return null; - } - var declarator = declaration.Declarators[0]; var initializerValue = declaration.Initializer?.Value ?? declarator.Initializer?.Value; if (initializerValue == null) - { return null; - } var hashCodeVariable = declarator.Symbol; if (!(IsLocalReference(returnedValue, hashCodeVariable))) diff --git a/src/Analyzers/Core/Analyzers/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsDiagnosticAnalyzer.cs index 72325a9dc6379..7c8df9538f1e3 100644 --- a/src/Analyzers/Core/Analyzers/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsDiagnosticAnalyzer.cs @@ -8,10 +8,10 @@ using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; -using Microsoft.CodeAnalysis.LanguageService; namespace Microsoft.CodeAnalysis.RemoveUnnecessaryImports; diff --git a/src/Analyzers/Core/Analyzers/RemoveUnnecessarySuppressions/AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/RemoveUnnecessarySuppressions/AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer.cs index 2db23be7731c2..e8555ba286a46 100644 --- a/src/Analyzers/Core/Analyzers/RemoveUnnecessarySuppressions/AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/RemoveUnnecessarySuppressions/AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer.cs @@ -7,7 +7,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CodeQuality; using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions; diff --git a/src/Analyzers/Core/Analyzers/SimplifyInterpolation/AbstractSimplifyInterpolationDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/SimplifyInterpolation/AbstractSimplifyInterpolationDiagnosticAnalyzer.cs index 8f8028e5618cf..2f9fcb812fe18 100644 --- a/src/Analyzers/Core/Analyzers/SimplifyInterpolation/AbstractSimplifyInterpolationDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/SimplifyInterpolation/AbstractSimplifyInterpolationDiagnosticAnalyzer.cs @@ -8,7 +8,6 @@ using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Operations; -using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.SimplifyInterpolation; diff --git a/src/Analyzers/Core/Analyzers/UseCoalesceExpression/AbstractUseCoalesceExpressionForNullableTernaryConditionalCheckDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseCoalesceExpression/AbstractUseCoalesceExpressionForNullableTernaryConditionalCheckDiagnosticAnalyzer.cs index 515eb7d8a2efa..92251b50c672f 100644 --- a/src/Analyzers/Core/Analyzers/UseCoalesceExpression/AbstractUseCoalesceExpressionForNullableTernaryConditionalCheckDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/UseCoalesceExpression/AbstractUseCoalesceExpressionForNullableTernaryConditionalCheckDiagnosticAnalyzer.cs @@ -80,7 +80,7 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) syntaxFacts.GetPartsOfMemberAccessExpression(conditionMemberAccess, out var conditionExpression, out var conditionSimpleName); syntaxFacts.GetNameAndArityOfSimpleName(conditionSimpleName, out var conditionName, out _); - if (conditionName != nameof(Nullable.HasValue)) + if (conditionName != nameof(Nullable<>.HasValue)) return; var whenPartToCheck = notHasValueExpression ? whenFalseNodeLow : whenTrueNodeLow; @@ -90,7 +90,7 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) syntaxFacts.GetPartsOfMemberAccessExpression(whenPartMemberAccess, out var whenPartExpression, out var whenPartSimpleName); syntaxFacts.GetNameAndArityOfSimpleName(whenPartSimpleName, out var whenPartName, out _); - if (whenPartName != nameof(Nullable.Value)) + if (whenPartName != nameof(Nullable<>.Value)) return; if (!syntaxFacts.AreEquivalent(conditionExpression, whenPartExpression)) diff --git a/src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractUseCollectionInitializerAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractUseCollectionInitializerAnalyzer.cs index e5093ced3782a..86321d0d8333e 100644 --- a/src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractUseCollectionInitializerAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractUseCollectionInitializerAnalyzer.cs @@ -2,6 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; @@ -194,17 +197,21 @@ protected sealed override bool ShouldAnalyze(CancellationToken cancellationToken if (this.HasExistingInvalidInitializerForCollection()) return false; + return GetAddMethods(cancellationToken).Any(); + } + + protected ImmutableArray GetAddMethods(CancellationToken cancellationToken) + { var type = this.SemanticModel.GetTypeInfo(_objectCreationExpression, cancellationToken).Type; if (type == null) - return false; + return []; var addMethods = this.SemanticModel.LookupSymbols( _objectCreationExpression.SpanStart, container: type, name: WellKnownMemberNames.CollectionInitializerAddMethodName, includeReducedExtensionMethods: true); - - return addMethods.Any(static m => m is IMethodSymbol methodSymbol && methodSymbol.Parameters.Any()); + return addMethods.SelectAsArray(s => s is IMethodSymbol { Parameters: [_, ..] }, s => (IMethodSymbol)s); } private bool TryAnalyzeIndexAssignment( diff --git a/src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractUseCollectionInitializerDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractUseCollectionInitializerDiagnosticAnalyzer.cs index d4410ebb3eaee..6ef40360f6665 100644 --- a/src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractUseCollectionInitializerDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractUseCollectionInitializerDiagnosticAnalyzer.cs @@ -6,11 +6,11 @@ using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Shared.CodeStyle; using Microsoft.CodeAnalysis.Shared.Collections; -using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.UseCollectionExpression; namespace Microsoft.CodeAnalysis.UseCollectionInitializer; @@ -232,7 +232,7 @@ private void AnalyzeNode( if (!CanUseCollectionExpression(semanticModel, objectCreationExpression, expressionType, preMatches, allowSemanticsChange, cancellationToken, out var changesSemantics2)) return null; - return (preMatches.Concat(postMatches), shouldUseCollectionExpression: true, changesSemantics1 || changesSemantics2); + return ([.. preMatches, .. postMatches], shouldUseCollectionExpression: true, changesSemantics1 || changesSemantics2); } } diff --git a/src/Analyzers/Core/Analyzers/UseCollectionInitializer/UpdateExpressionState.cs b/src/Analyzers/Core/Analyzers/UseCollectionInitializer/UpdateExpressionState.cs index 73fd6a7f9a76f..274f8c9dc8f3f 100644 --- a/src/Analyzers/Core/Analyzers/UseCollectionInitializer/UpdateExpressionState.cs +++ b/src/Analyzers/Core/Analyzers/UseCollectionInitializer/UpdateExpressionState.cs @@ -26,7 +26,7 @@ internal readonly struct UpdateExpressionState< { private static readonly ImmutableArray<(string name, bool isLinq)> s_multiAddNames = [ - (nameof(List.AddRange), isLinq: false), + (nameof(List<>.AddRange), isLinq: false), (nameof(Enumerable.Concat), isLinq: true), (nameof(Enumerable.Append), isLinq: true), ]; diff --git a/src/Analyzers/Core/Analyzers/UseConditionalExpression/ForAssignment/UseConditionalExpressionForAssignmentHelpers.cs b/src/Analyzers/Core/Analyzers/UseConditionalExpression/ForAssignment/UseConditionalExpressionForAssignmentHelpers.cs index cb2916d775d49..b0199a564c2a4 100644 --- a/src/Analyzers/Core/Analyzers/UseConditionalExpression/ForAssignment/UseConditionalExpressionForAssignmentHelpers.cs +++ b/src/Analyzers/Core/Analyzers/UseConditionalExpression/ForAssignment/UseConditionalExpressionForAssignmentHelpers.cs @@ -9,7 +9,6 @@ using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseConditionalExpression; diff --git a/src/Analyzers/Core/Analyzers/UseNullPropagation/AbstractUseNullPropagationDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseNullPropagation/AbstractUseNullPropagationDiagnosticAnalyzer.cs index 4bec6bacab283..ab6ac47e21dfe 100644 --- a/src/Analyzers/Core/Analyzers/UseNullPropagation/AbstractUseNullPropagationDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/UseNullPropagation/AbstractUseNullPropagationDiagnosticAnalyzer.cs @@ -22,7 +22,7 @@ internal static class UseNullPropagationHelpers public static bool IsSystemNullableValueProperty([NotNullWhen(true)] ISymbol? symbol) => symbol is { - Name: nameof(Nullable.Value), + Name: nameof(Nullable<>.Value), ContainingType.OriginalDefinition.SpecialType: SpecialType.System_Nullable_T, }; } @@ -45,7 +45,12 @@ internal abstract partial class AbstractUseNullPropagationDiagnosticAnalyzer< TElementAccessExpressionSyntax, TMemberAccessExpressionSyntax, TIfStatementSyntax, - TExpressionStatementSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer + TExpressionStatementSyntax>() : AbstractBuiltInCodeStyleDiagnosticAnalyzer( + IDEDiagnosticIds.UseNullPropagationDiagnosticId, + EnforceOnBuildValues.UseNullPropagation, + CodeStyleOptions2.PreferNullPropagation, + new LocalizableResourceString(nameof(AnalyzersResources.Use_null_propagation), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), + new LocalizableResourceString(nameof(AnalyzersResources.Null_check_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) where TSyntaxKind : struct where TExpressionSyntax : SyntaxNode where TStatementSyntax : SyntaxNode @@ -61,15 +66,6 @@ internal abstract partial class AbstractUseNullPropagationDiagnosticAnalyzer< private static readonly ImmutableDictionary s_whenPartIsNullableProperties = ImmutableDictionary.Empty.Add(UseNullPropagationHelpers.WhenPartIsNullable, ""); - protected AbstractUseNullPropagationDiagnosticAnalyzer() - : base(IDEDiagnosticIds.UseNullPropagationDiagnosticId, - EnforceOnBuildValues.UseNullPropagation, - CodeStyleOptions2.PreferNullPropagation, - new LocalizableResourceString(nameof(AnalyzersResources.Use_null_propagation), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), - new LocalizableResourceString(nameof(AnalyzersResources.Null_check_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) - { - } - public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; @@ -83,6 +79,16 @@ protected abstract bool TryAnalyzePatternCondition( ISyntaxFacts syntaxFacts, TExpressionSyntax conditionNode, [NotNullWhen(true)] out TExpressionSyntax? conditionPartToCheck, out bool isEquals); + public (INamedTypeSymbol? expressionType, IMethodSymbol? referenceEqualsMethod) GetAnalysisSymbols(Compilation compilation) + { + var expressionType = compilation.ExpressionOfTType(); + var objectType = compilation.GetSpecialType(SpecialType.System_Object); + var referenceEqualsMethod = objectType?.GetMembers(nameof(ReferenceEquals)) + .OfType() + .FirstOrDefault(m => m is { DeclaredAccessibility: Accessibility.Public, Parameters.Length: 2 }); + return (expressionType, referenceEqualsMethod); + } + protected override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(context => @@ -92,22 +98,33 @@ protected override void InitializeWorker(AnalysisContext context) var expressionType = context.Compilation.ExpressionOfTType(); - var objectType = context.Compilation.GetSpecialType(SpecialType.System_Object); - var referenceEqualsMethod = objectType?.GetMembers(nameof(ReferenceEquals)) - .OfType() - .FirstOrDefault(m => m is { DeclaredAccessibility: Accessibility.Public, Parameters.Length: 2 }); + var (objectType, referenceEqualsMethod) = GetAnalysisSymbols(context.Compilation); var syntaxKinds = this.SyntaxFacts.SyntaxKinds; context.RegisterSyntaxNodeAction( - context => AnalyzeTernaryConditionalExpression(context, expressionType, referenceEqualsMethod), + context => AnalyzeTernaryConditionalExpressionAndReportDiagnostic(context, expressionType, referenceEqualsMethod), syntaxKinds.Convert(syntaxKinds.TernaryConditionalExpression)); context.RegisterSyntaxNodeAction( - context => AnalyzeIfStatement(context, referenceEqualsMethod), + context => AnalyzeIfStatementAndReportDiagnostic(context, referenceEqualsMethod), IfStatementSyntaxKind); }); } - private void AnalyzeTernaryConditionalExpression( + public (TExpressionSyntax conditionalPart, SyntaxNode whenPart)? GetPartsOfConditionalExpression( + SemanticModel semanticModel, + TConditionalExpressionSyntax conditionalExpression, + CancellationToken cancellationToken) + { + var (objectType, referenceEqualsMethod) = GetAnalysisSymbols(semanticModel.Compilation); + var analysisResult = AnalyzeTernaryConditionalExpression( + semanticModel, objectType, referenceEqualsMethod, conditionalExpression, cancellationToken); + if (analysisResult is null) + return null; + + return (analysisResult.Value.ConditionPartToCheck, analysisResult.Value.WhenPartToCheck); + } + + private void AnalyzeTernaryConditionalExpressionAndReportDiagnostic( SyntaxNodeAnalysisContext context, INamedTypeSymbol? expressionType, IMethodSymbol? referenceEqualsMethod) @@ -119,6 +136,27 @@ private void AnalyzeTernaryConditionalExpression( if (!option.Value || ShouldSkipAnalysis(context, option.Notification)) return; + var analysisResult = AnalyzeTernaryConditionalExpression( + context.SemanticModel, expressionType, referenceEqualsMethod, conditionalExpression, cancellationToken); + if (analysisResult is null) + return; + + context.ReportDiagnostic(DiagnosticHelper.Create( + Descriptor, + conditionalExpression.GetLocation(), + option.Notification, + context.Options, + additionalLocations: [conditionalExpression.GetLocation()], + analysisResult.Value.Properties)); + } + + public ConditionalExpressionAnalysisResult? AnalyzeTernaryConditionalExpression( + SemanticModel semanticModel, + INamedTypeSymbol? expressionType, + IMethodSymbol? referenceEqualsMethod, + TConditionalExpressionSyntax conditionalExpression, + CancellationToken cancellationToken) + { var syntaxFacts = this.SyntaxFacts; syntaxFacts.GetPartsOfConditionalExpression( conditionalExpression, out var condition, out var whenTrue, out var whenFalse); @@ -129,32 +167,31 @@ private void AnalyzeTernaryConditionalExpression( var whenFalseNode = (TExpressionSyntax)syntaxFacts.WalkDownParentheses(whenFalse); if (!TryAnalyzeCondition( - context, syntaxFacts, referenceEqualsMethod, conditionNode, - out var conditionPartToCheck, out var isEquals)) + semanticModel, referenceEqualsMethod, conditionNode, + out var conditionPartToCheck, out var isEquals, cancellationToken)) { - return; + return null; } // Needs to be of the form: // x == null ? null : ... or // x != null ? ... : null; if (isEquals && !syntaxFacts.IsNullLiteralExpression(whenTrueNode)) - return; + return null; if (!isEquals && !syntaxFacts.IsNullLiteralExpression(whenFalseNode)) - return; + return null; var whenPartToCheck = isEquals ? whenFalseNode : whenTrueNode; - var semanticModel = context.SemanticModel; var whenPartMatch = GetWhenPartMatch(syntaxFacts, semanticModel, conditionPartToCheck, whenPartToCheck, cancellationToken); if (whenPartMatch == null) - return; + return null; // can't use ?. on a pointer var whenPartType = semanticModel.GetTypeInfo(whenPartMatch, cancellationToken).Type; if (whenPartType is IPointerTypeSymbol) - return; + return null; var type = semanticModel.GetTypeInfo(conditionalExpression, cancellationToken).Type; if (type?.IsValueType == true) @@ -164,7 +201,7 @@ private void AnalyzeTernaryConditionalExpression( // User has something like: If(str is nothing, nothing, str.Length) // In this case, converting to str?.Length changes the type of this from // int to int? - return; + return null; } // But for a nullable type, such as If(c is nothing, nothing, c.nullable) // converting to c?.nullable doesn't affect the type @@ -176,7 +213,7 @@ private void AnalyzeTernaryConditionalExpression( // `x == null ? x : x.M` cannot be converted to `x?.M` when M is a method symbol. var memberSymbol = semanticModel.GetSymbolInfo(whenPartToCheck, cancellationToken).GetAnySymbol(); if (memberSymbol is IMethodSymbol) - return; + return null; // `x == null ? x : x.Value` will be converted to just 'x'. if (UseNullPropagationHelpers.IsSystemNullableValueProperty(memberSymbol)) @@ -185,12 +222,7 @@ private void AnalyzeTernaryConditionalExpression( // ?. is not available in expression-trees. Disallow the fix in that case. if (this.SemanticFacts.IsInExpressionTree(semanticModel, conditionNode, expressionType, cancellationToken)) - return; - - var locations = ImmutableArray.Create( - conditionalExpression.GetLocation(), - conditionPartToCheck.GetLocation(), - whenPartToCheck.GetLocation()); + return null; var whenPartIsNullable = whenPartType?.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T; var properties = whenPartIsNullable @@ -200,23 +232,21 @@ private void AnalyzeTernaryConditionalExpression( if (isTrivialNullableValueAccess) properties = properties.Add(UseNullPropagationHelpers.IsTrivialNullableValueAccess, UseNullPropagationHelpers.IsTrivialNullableValueAccess); - context.ReportDiagnostic(DiagnosticHelper.Create( - Descriptor, - conditionalExpression.GetLocation(), - option.Notification, - context.Options, - locations, - properties)); + return new( + conditionPartToCheck, + whenPartToCheck, + properties); } private bool TryAnalyzeCondition( - SyntaxNodeAnalysisContext context, - ISyntaxFacts syntaxFacts, + SemanticModel semanticModel, IMethodSymbol? referenceEqualsMethod, TExpressionSyntax condition, [NotNullWhen(true)] out TExpressionSyntax? conditionPartToCheck, - out bool isEquals) + out bool isEquals, + CancellationToken cancellationToken) { + var syntaxFacts = this.SyntaxFacts; condition = (TExpressionSyntax)syntaxFacts.WalkDownParentheses(condition); var conditionIsNegated = false; if (syntaxFacts.IsLogicalNotExpression(condition)) @@ -232,8 +262,7 @@ private bool TryAnalyzeCondition( syntaxFacts, binaryExpression, out conditionPartToCheck, out isEquals), TInvocationExpressionSyntax invocation => TryAnalyzeInvocationCondition( - context, syntaxFacts, referenceEqualsMethod, invocation, - out conditionPartToCheck, out isEquals), + semanticModel, syntaxFacts, referenceEqualsMethod, invocation, out conditionPartToCheck, out isEquals, cancellationToken), _ => TryAnalyzePatternCondition(syntaxFacts, condition, out conditionPartToCheck, out isEquals), }; @@ -265,12 +294,13 @@ private static bool TryAnalyzeBinaryExpressionCondition( } private static bool TryAnalyzeInvocationCondition( - SyntaxNodeAnalysisContext context, + SemanticModel semanticModel, ISyntaxFacts syntaxFacts, IMethodSymbol? referenceEqualsMethod, TInvocationExpressionSyntax invocation, [NotNullWhen(true)] out TExpressionSyntax? conditionPartToCheck, - out bool isEquals) + out bool isEquals, + CancellationToken cancellationToken) { conditionPartToCheck = null; isEquals = true; @@ -315,8 +345,6 @@ private static bool TryAnalyzeInvocationCondition( return false; } - var semanticModel = context.SemanticModel; - var cancellationToken = context.CancellationToken; var symbol = semanticModel.GetSymbolInfo(invocation, cancellationToken).Symbol; return referenceEqualsMethod.Equals(symbol); } @@ -341,7 +369,8 @@ private static bool TryAnalyzeInvocationCondition( return conditionRightIsNull ? conditionLeft : conditionRight; } - internal static TExpressionSyntax? GetWhenPartMatch( +#pragma warning disable CA1822 // Mark members as static. Helper method that doesn't want to call through generic form. + public TExpressionSyntax? GetWhenPartMatch( ISyntaxFacts syntaxFacts, SemanticModel semanticModel, TExpressionSyntax expressionToMatch, @@ -365,6 +394,7 @@ private static bool TryAnalyzeInvocationCondition( current = unwrapped; } } +#pragma warning restore CA1822 // Mark members as static private static TExpressionSyntax RemoveObjectCastIfAny( ISyntaxFacts syntaxFacts, SemanticModel semanticModel, TExpressionSyntax node, CancellationToken cancellationToken) diff --git a/src/Analyzers/Core/Analyzers/UseNullPropagation/AbstractUseNullPropagationDiagnosticAnalyzer_IfStatement.cs b/src/Analyzers/Core/Analyzers/UseNullPropagation/AbstractUseNullPropagationDiagnosticAnalyzer_IfStatement.cs index 2a36c47b42d47..7b672dceb6dfc 100644 --- a/src/Analyzers/Core/Analyzers/UseNullPropagation/AbstractUseNullPropagationDiagnosticAnalyzer_IfStatement.cs +++ b/src/Analyzers/Core/Analyzers/UseNullPropagation/AbstractUseNullPropagationDiagnosticAnalyzer_IfStatement.cs @@ -4,7 +4,9 @@ using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; +using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.UseNullPropagation; @@ -23,9 +25,11 @@ internal abstract partial class AbstractUseNullPropagationDiagnosticAnalyzer< TExpressionStatementSyntax> { protected abstract bool TryGetPartsOfIfStatement( - TIfStatementSyntax ifStatement, [NotNullWhen(true)] out TExpressionSyntax? condition, [NotNullWhen(true)] out TStatementSyntax? trueStatement); + TIfStatementSyntax ifStatement, + [NotNullWhen(true)] out TExpressionSyntax? condition, + out ImmutableArray trueStatements); - private void AnalyzeIfStatement( + private void AnalyzeIfStatementAndReportDiagnostic( SyntaxNodeAnalysisContext context, IMethodSymbol? referenceEqualsMethod) { @@ -34,32 +38,83 @@ private void AnalyzeIfStatement( if (!option.Value || ShouldSkipAnalysis(context, option.Notification)) return; - var syntaxFacts = this.SyntaxFacts; var ifStatement = (TIfStatementSyntax)context.Node; + var analysisResultOpt = AnalyzeIfStatement( + context.SemanticModel, referenceEqualsMethod, ifStatement, cancellationToken); + if (analysisResultOpt is not IfStatementAnalysisResult analysisResult) + return; + + context.ReportDiagnostic(DiagnosticHelper.Create( + Descriptor, + ifStatement.GetFirstToken().GetLocation(), + option.Notification, + context.Options, + additionalLocations: [ifStatement.GetLocation()], + properties: analysisResult.Properties)); + + } + + public IfStatementAnalysisResult? AnalyzeIfStatement( + SemanticModel semanticModel, + IMethodSymbol? referenceEqualsMethod, + TIfStatementSyntax ifStatement, + CancellationToken cancellationToken) + { + var syntaxFacts = this.SyntaxFacts; // The true-statement if the if-statement has to be a statement of the form `.Name(...)`; - if (!TryGetPartsOfIfStatement(ifStatement, out var condition, out var trueStatement)) - return; + if (!TryGetPartsOfIfStatement(ifStatement, out var condition, out var trueStatement, out var nullAssignmentOpt)) + return null; if (trueStatement is not TExpressionStatementSyntax expressionStatement) - return; + return null; + + if (nullAssignmentOpt is not null and not TExpressionStatementSyntax) + return null; // Now see if the `if ()` looks like an appropriate null check. - if (!TryAnalyzeCondition(context, syntaxFacts, referenceEqualsMethod, condition, out var conditionPartToCheck, out var isEquals)) - return; + if (!TryAnalyzeCondition( + semanticModel, referenceEqualsMethod, condition, + out var conditionPartToCheck, out var isEquals, + cancellationToken)) + { + return null; + } // Ok, we have `if ( == null)` or `if ( != null)` (or some similar form of that. `conditionPartToCheck` will be `` here. // We only support `if ( != null)`. Fail out if we have the alternate form. if (isEquals) - return; + return null; + + if (nullAssignmentOpt != null) + { + // If we have a second statement in the if-statement, it must be ` = null;`. + // This is fine to convert to a null-conditional access. Here's why: say we started with: + // + // `if ( != null) { .Method(); = null; }` + // + // If 'expr' is not null, then we execute the body and then end up with expr being null. So `expr?.Method(); expr = null;` + // preserves those semantics. Simialrly, if is expr is null, then `expr?.Method();` does nothing, and `expr = null` keeps it + // the same as well. So this is a valid conversion in all cases. + if (!syntaxFacts.IsSimpleAssignmentStatement(nullAssignmentOpt)) + return null; + + syntaxFacts.GetPartsOfAssignmentStatement(nullAssignmentOpt, out var assignLeft, out _, out var assignRight); + if (!syntaxFacts.AreEquivalent(assignLeft, conditionPartToCheck) || + !syntaxFacts.IsNullLiteralExpression(assignRight)) + { + return null; + } + + // Looks good. we can convert this block. + } - var semanticModel = context.SemanticModel; var whenPartMatch = GetWhenPartMatch( syntaxFacts, semanticModel, conditionPartToCheck, (TExpressionSyntax)syntaxFacts.GetExpressionOfExpressionStatement(expressionStatement), cancellationToken); if (whenPartMatch == null) - return; + return null; // If we have: // @@ -78,25 +133,40 @@ private void AnalyzeIfStatement( { var memberSymbol = semanticModel.GetSymbolInfo(memberAccess, cancellationToken).GetAnySymbol(); if (memberSymbol?.IsStatic is true) - return; + return null; } // can't use ?. on a pointer var whenPartType = semanticModel.GetTypeInfo(whenPartMatch, cancellationToken).Type; if (whenPartType is IPointerTypeSymbol or IFunctionPointerTypeSymbol) - return; + return null; - var whenPartIsNullable = semanticModel.GetTypeInfo(whenPartMatch).Type?.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T; + var whenPartIsNullable = semanticModel.GetTypeInfo(whenPartMatch, cancellationToken).Type?.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T; var properties = whenPartIsNullable ? s_whenPartIsNullableProperties : ImmutableDictionary.Empty; - context.ReportDiagnostic(DiagnosticHelper.Create( - Descriptor, - ifStatement.GetFirstToken().GetLocation(), - option.Notification, - context.Options, - [ifStatement.GetLocation(), trueStatement.GetLocation(), whenPartMatch.GetLocation()], - properties)); + return new(trueStatement, whenPartMatch, nullAssignmentOpt, properties); + } + + private bool TryGetPartsOfIfStatement( + TIfStatementSyntax ifStatement, + [NotNullWhen(true)] out TExpressionSyntax? condition, + [NotNullWhen(true)] out TStatementSyntax? trueStatement, + out TStatementSyntax? nullAssignmentOpt) + { + trueStatement = null; + nullAssignmentOpt = null; + + if (!this.TryGetPartsOfIfStatement(ifStatement, out condition, out var trueStatements)) + return false; + + if (trueStatements.Length is < 1 or > 2) + return false; + + trueStatement = trueStatements[0]; + if (trueStatements.Length == 2) + nullAssignmentOpt = trueStatements[1]; + return true; } } diff --git a/src/Analyzers/Core/Analyzers/UseNullPropagation/AnalysisResults.cs b/src/Analyzers/Core/Analyzers/UseNullPropagation/AnalysisResults.cs new file mode 100644 index 0000000000000..ac4bcd870dd47 --- /dev/null +++ b/src/Analyzers/Core/Analyzers/UseNullPropagation/AnalysisResults.cs @@ -0,0 +1,46 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.UseNullPropagation; + +internal abstract partial class AbstractUseNullPropagationDiagnosticAnalyzer< + TSyntaxKind, + TExpressionSyntax, + TStatementSyntax, + TConditionalExpressionSyntax, + TBinaryExpressionSyntax, + TInvocationExpressionSyntax, + TConditionalAccessExpressionSyntax, + TElementAccessExpressionSyntax, + TMemberAccessExpressionSyntax, + TIfStatementSyntax, + TExpressionStatementSyntax> where TSyntaxKind : struct + where TExpressionSyntax : SyntaxNode + where TStatementSyntax : SyntaxNode + where TConditionalExpressionSyntax : TExpressionSyntax + where TBinaryExpressionSyntax : TExpressionSyntax + where TInvocationExpressionSyntax : TExpressionSyntax + where TConditionalAccessExpressionSyntax : TExpressionSyntax + where TElementAccessExpressionSyntax : TExpressionSyntax + where TMemberAccessExpressionSyntax : TExpressionSyntax + where TIfStatementSyntax : TStatementSyntax + where TExpressionStatementSyntax : TStatementSyntax +{ + public readonly struct ConditionalExpressionAnalysisResult(TExpressionSyntax conditionPartToCheck, TExpressionSyntax whenPartToCheck, ImmutableDictionary properties) + { + public TExpressionSyntax ConditionPartToCheck { get; } = conditionPartToCheck; + public TExpressionSyntax WhenPartToCheck { get; } = whenPartToCheck; + public ImmutableDictionary Properties { get; } = properties; + } + + public readonly struct IfStatementAnalysisResult(TStatementSyntax trueStatement, TExpressionSyntax whenPartMatch, TStatementSyntax? nullAssignmentOpt, ImmutableDictionary properties) + { + public TStatementSyntax TrueStatement { get; } = trueStatement; + public TExpressionSyntax WhenPartMatch { get; } = whenPartMatch; + public TStatementSyntax? NullAssignmentOpt { get; } = nullAssignmentOpt; + public ImmutableDictionary Properties { get; } = properties; + } +} diff --git a/src/Analyzers/Core/Analyzers/UseObjectInitializer/AbstractUseObjectInitializerDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseObjectInitializer/AbstractUseObjectInitializerDiagnosticAnalyzer.cs index 74d6e02d130d5..e13de8a6c92a9 100644 --- a/src/Analyzers/Core/Analyzers/UseObjectInitializer/AbstractUseObjectInitializerDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/UseObjectInitializer/AbstractUseObjectInitializerDiagnosticAnalyzer.cs @@ -5,6 +5,7 @@ using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Shared.Collections; diff --git a/src/Analyzers/Core/CodeFixes/AddAccessibilityModifiers/AbstractAddAccessibilityModifiersCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/AddAccessibilityModifiers/AbstractAddAccessibilityModifiersCodeFixProvider.cs index 3253d23929b57..048011d9bf94b 100644 --- a/src/Analyzers/Core/CodeFixes/AddAccessibilityModifiers/AbstractAddAccessibilityModifiersCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/AddAccessibilityModifiers/AbstractAddAccessibilityModifiersCodeFixProvider.cs @@ -11,7 +11,6 @@ using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddOrRemoveAccessibilityModifiers; diff --git a/src/Analyzers/Core/CodeFixes/AddExplicitCast/AbstractAddExplicitCastCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/AddExplicitCast/AbstractAddExplicitCastCodeFixProvider.cs index 7b54e0983f306..e1b4db9d86367 100644 --- a/src/Analyzers/Core/CodeFixes/AddExplicitCast/AbstractAddExplicitCastCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/AddExplicitCast/AbstractAddExplicitCastCodeFixProvider.cs @@ -8,6 +8,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Analyzers/Core/CodeFixes/AddParameter/AbstractAddParameterCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/AddParameter/AbstractAddParameterCodeFixProvider.cs index 720e35109b0b7..703b783492333 100644 --- a/src/Analyzers/Core/CodeFixes/AddParameter/AbstractAddParameterCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/AddParameter/AbstractAddParameterCodeFixProvider.cs @@ -11,6 +11,7 @@ using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeGeneration; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; diff --git a/src/Analyzers/Core/CodeFixes/AliasAmbiguousType/AbstractAliasAmbiguousTypeCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/AliasAmbiguousType/AbstractAliasAmbiguousTypeCodeFixProvider.cs index a3f98de9b4f4d..a306a2720e6d3 100644 --- a/src/Analyzers/Core/CodeFixes/AliasAmbiguousType/AbstractAliasAmbiguousTypeCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/AliasAmbiguousType/AbstractAliasAmbiguousTypeCodeFixProvider.cs @@ -10,6 +10,7 @@ using Microsoft.CodeAnalysis.AddImport; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Analyzers/Core/CodeFixes/AnalyzerOptionsProviders.cs b/src/Analyzers/Core/CodeFixes/AnalyzerOptionsProviders.cs index e270d3156c84e..b21d7d0cc80d2 100644 --- a/src/Analyzers/Core/CodeFixes/AnalyzerOptionsProviders.cs +++ b/src/Analyzers/Core/CodeFixes/AnalyzerOptionsProviders.cs @@ -4,8 +4,8 @@ using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Options; +using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Diagnostics; diff --git a/src/Analyzers/Core/CodeFixes/ConflictMarkerResolution/AbstractConflictMarkerCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/ConflictMarkerResolution/AbstractConflictMarkerCodeFixProvider.cs index 7cc576637c8ec..57a761f4d5b96 100644 --- a/src/Analyzers/Core/CodeFixes/ConflictMarkerResolution/AbstractConflictMarkerCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/ConflictMarkerResolution/AbstractConflictMarkerCodeFixProvider.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Immutable; using System.Diagnostics; +using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; diff --git a/src/Analyzers/Core/CodeFixes/ConvertToAsync/AbstractConvertToAsyncCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/ConvertToAsync/AbstractConvertToAsyncCodeFixProvider.cs index 7ae8e12d88b05..9bf189a0dcdf0 100644 --- a/src/Analyzers/Core/CodeFixes/ConvertToAsync/AbstractConvertToAsyncCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/ConvertToAsync/AbstractConvertToAsyncCodeFixProvider.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; diff --git a/src/Analyzers/Core/CodeFixes/ForEachCast/AbstractForEachCastCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/ForEachCast/AbstractForEachCastCodeFixProvider.cs index cfd86259a4a42..db699f6212104 100644 --- a/src/Analyzers/Core/CodeFixes/ForEachCast/AbstractForEachCastCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/ForEachCast/AbstractForEachCastCodeFixProvider.cs @@ -13,7 +13,6 @@ using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ForEachCast; @@ -29,7 +28,7 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) { if (context.Diagnostics.First().Properties.ContainsKey(ForEachCastHelpers.IsFixable)) { - RegisterCodeFix(context, AnalyzersResources.Add_explicit_cast, nameof(AbstractForEachCastCodeFixProvider)); + RegisterCodeFix(context, AnalyzersResources.Add_explicit_cast, nameof(AbstractForEachCastCodeFixProvider<>)); } return Task.CompletedTask; diff --git a/src/Analyzers/Core/CodeFixes/Formatting/FormattingCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/Formatting/FormattingCodeFixProvider.cs index 4ab1ea8d5f6a7..6597bb53b059a 100644 --- a/src/Analyzers/Core/CodeFixes/Formatting/FormattingCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/Formatting/FormattingCodeFixProvider.cs @@ -30,6 +30,14 @@ public sealed override ImmutableArray FixableDiagnosticIds protected abstract ISyntaxFormatting SyntaxFormatting { get; } +#if WORKSPACE + /// + /// This refactoring provider touches syntax only. So we can speed up fix all by having it only clean syntax + /// and not semantics. + /// + protected override CodeActionCleanup Cleanup => CodeActionCleanup.SyntaxOnly; +#endif + /// /// Fixing formatting is high priority. It's something the user wants to be able to fix quickly, is driven by /// them acting on an error reported in code, and can be computed fast as it only uses syntax not semantics. diff --git a/src/Analyzers/Core/CodeFixes/GenerateConstructor/AbstractGenerateConstructorService.State.cs b/src/Analyzers/Core/CodeFixes/GenerateConstructor/AbstractGenerateConstructorService.State.cs index 3c7d215fba9f5..4e74c53e2e03c 100644 --- a/src/Analyzers/Core/CodeFixes/GenerateConstructor/AbstractGenerateConstructorService.State.cs +++ b/src/Analyzers/Core/CodeFixes/GenerateConstructor/AbstractGenerateConstructorService.State.cs @@ -19,12 +19,6 @@ using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; -#if CODE_STYLE -using DeclarationModifiers = Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers; -#else -using DeclarationModifiers = Microsoft.CodeAnalysis.Editing.DeclarationModifiers; -#endif - namespace Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor; using static GenerateConstructorHelpers; @@ -440,7 +434,7 @@ public async Task GetChangedDocumentAsync( var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default, accessibility: Accessibility.Public, - modifiers: new DeclarationModifiers(isUnsafe: generateUnsafe), + modifiers: DeclarationModifiers.None.WithIsUnsafe(generateUnsafe), typeName: TypeToGenerateIn.Name, parameters: newParameters, statements: assignments, diff --git a/src/Analyzers/Core/CodeFixes/GenerateDefaultConstructors/GenerateDefaultConstructorsCodeAction.cs b/src/Analyzers/Core/CodeFixes/GenerateDefaultConstructors/GenerateDefaultConstructorsCodeAction.cs index 67ef2bbaac580..dbbe972977376 100644 --- a/src/Analyzers/Core/CodeFixes/GenerateDefaultConstructors/GenerateDefaultConstructorsCodeAction.cs +++ b/src/Analyzers/Core/CodeFixes/GenerateDefaultConstructors/GenerateDefaultConstructorsCodeAction.cs @@ -11,12 +11,6 @@ using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; -#if CODE_STYLE -using DeclarationModifiers = Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers; -#else -using DeclarationModifiers = Microsoft.CodeAnalysis.Editing.DeclarationModifiers; -#endif - namespace Microsoft.CodeAnalysis.GenerateDefaultConstructors; internal abstract partial class AbstractGenerateDefaultConstructorsService @@ -62,7 +56,7 @@ private IMethodSymbol CreateConstructorDefinition( return CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default, accessibility: accessibility, - modifiers: new DeclarationModifiers(), + modifiers: DeclarationModifiers.None, typeName: classType.Name, parameters: baseConstructor.Parameters.SelectAsArray(p => WithoutInaccessibleAttributes(p, classType)), statements: default, diff --git a/src/Analyzers/Core/CodeFixes/GenerateEnumMember/AbstractGenerateEnumMemberService.CodeAction.cs b/src/Analyzers/Core/CodeFixes/GenerateEnumMember/AbstractGenerateEnumMemberService.CodeAction.cs index 6d2852a2ede75..51855dbec335d 100644 --- a/src/Analyzers/Core/CodeFixes/GenerateEnumMember/AbstractGenerateEnumMemberService.CodeAction.cs +++ b/src/Analyzers/Core/CodeFixes/GenerateEnumMember/AbstractGenerateEnumMemberService.CodeAction.cs @@ -6,9 +6,9 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; +using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Shared.Utilities; -using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateEnumMember; diff --git a/src/Analyzers/Core/CodeFixes/GenerateMember/AbstractGenerateMemberCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/GenerateMember/AbstractGenerateMemberCodeFixProvider.cs index c254ca042d3ac..ffd9e180dff18 100644 --- a/src/Analyzers/Core/CodeFixes/GenerateMember/AbstractGenerateMemberCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/GenerateMember/AbstractGenerateMemberCodeFixProvider.cs @@ -11,7 +11,6 @@ using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes.GenerateMember; diff --git a/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateMethodService.State.cs b/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateMethodService.State.cs index c558aa0d8f354..5e252f1496c75 100644 --- a/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateMethodService.State.cs +++ b/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateMethodService.State.cs @@ -167,7 +167,7 @@ private bool TryInitializeSimpleName( { // If we inferred Func/Action here, attempt to create better parameter names than the default // 'arg1/arg2/arg3' form that the delegate specifies. - var parameterNames = delegateInvokeMethod.ContainingType is { Name: nameof(Action) or nameof(Func), ContainingNamespace.Name: nameof(System) } + var parameterNames = delegateInvokeMethod.ContainingType is { Name: nameof(Action) or nameof(Func<>), ContainingNamespace.Name: nameof(System) } ? GenerateParameterNamesBasedOnParameterTypes(delegateInvokeMethod.Parameters) : delegateInvokeMethod.Parameters.SelectAsArray(p => p.Name); diff --git a/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateParameterizedMemberService.SignatureInfo.cs b/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateParameterizedMemberService.SignatureInfo.cs index 2c87d938875cc..3a0fca8de4ccb 100644 --- a/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateParameterizedMemberService.SignatureInfo.cs +++ b/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateParameterizedMemberService.SignatureInfo.cs @@ -19,12 +19,6 @@ using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; -#if CODE_STYLE -using DeclarationModifiers = Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers; -#else -using DeclarationModifiers = Microsoft.CodeAnalysis.Editing.DeclarationModifiers; -#endif - namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember; internal abstract partial class AbstractGenerateParameterizedMemberService @@ -82,7 +76,7 @@ internal async ValueTask GeneratePropertyAsync( return CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: default, accessibility: accessibility, - modifiers: new DeclarationModifiers(isStatic: State.IsStatic, isAbstract: isAbstract), + modifiers: DeclarationModifiers.None.WithIsStatic(State.IsStatic).WithIsAbstract(isAbstract), type: await DetermineReturnTypeAsync(cancellationToken).ConfigureAwait(false), refKind: DetermineRefKind(cancellationToken), explicitInterfaceImplementations: default, @@ -110,8 +104,8 @@ public async ValueTask GenerateMethodAsync( var method = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, accessibility: DetermineAccessibility(isAbstract), - modifiers: new DeclarationModifiers( - isStatic: State.IsStatic, isAbstract: isAbstract, isUnsafe: isUnsafe, isAsync: knownTypes.IsTaskLike(returnType)), + modifiers: DeclarationModifiers.None + .WithIsStatic(State.IsStatic).WithIsAbstract(isAbstract).WithIsUnsafe(isUnsafe).WithAsync(knownTypes.IsTaskLike(returnType)), returnType: returnType, refKind: DetermineRefKind(cancellationToken), explicitInterfaceImplementations: default, diff --git a/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateParameterizedMemberService.State.cs b/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateParameterizedMemberService.State.cs index a166774d68938..ce6a1619e54a6 100644 --- a/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateParameterizedMemberService.State.cs +++ b/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateParameterizedMemberService.State.cs @@ -10,10 +10,10 @@ using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; +using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; -using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember; diff --git a/src/Analyzers/Core/CodeFixes/GenerateVariable/AbstractGenerateVariableService.CodeAction.cs b/src/Analyzers/Core/CodeFixes/GenerateVariable/AbstractGenerateVariableService.CodeAction.cs index c14118aca3ee6..3b4f58ece7ace 100644 --- a/src/Analyzers/Core/CodeFixes/GenerateVariable/AbstractGenerateVariableService.CodeAction.cs +++ b/src/Analyzers/Core/CodeFixes/GenerateVariable/AbstractGenerateVariableService.CodeAction.cs @@ -13,12 +13,6 @@ using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; -#if CODE_STYLE -using DeclarationModifiers = Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers; -#else -using DeclarationModifiers = Microsoft.CodeAnalysis.Editing.DeclarationModifiers; -#endif - namespace Microsoft.CodeAnalysis.GenerateMember.GenerateVariable; internal abstract partial class AbstractGenerateVariableService @@ -72,7 +66,7 @@ protected override async Task GetChangedDocumentAsync(CancellationToke var propertySymbol = CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: default, accessibility: _state.DetermineMaximalAccessibility(), - modifiers: new DeclarationModifiers(isStatic: _state.IsStatic, isUnsafe: generateUnsafe), + modifiers: DeclarationModifiers.None.WithIsStatic(_state.IsStatic).WithIsUnsafe(generateUnsafe), type: _state.TypeMemberType, refKind: _refKind, explicitInterfaceImplementations: default, @@ -91,8 +85,8 @@ protected override async Task GetChangedDocumentAsync(CancellationToke attributes: default, accessibility: DetermineMinimalAccessibility(_state), modifiers: _isConstant - ? new DeclarationModifiers(isConst: true, isUnsafe: generateUnsafe) - : new DeclarationModifiers(isStatic: _state.IsStatic, isReadOnly: _isReadonly, isUnsafe: generateUnsafe), + ? DeclarationModifiers.None.WithIsConst(true).WithIsUnsafe(generateUnsafe) + : DeclarationModifiers.None.WithIsStatic(_state.IsStatic).WithIsReadOnly(_isReadonly).WithIsUnsafe(generateUnsafe), type: _state.TypeMemberType, name: _state.IdentifierToken.ValueText); diff --git a/src/Analyzers/Core/CodeFixes/GenerateVariable/AbstractGenerateVariableService.GenerateLocalCodeAction.cs b/src/Analyzers/Core/CodeFixes/GenerateVariable/AbstractGenerateVariableService.GenerateLocalCodeAction.cs index 55d8128618c3a..65bbdb634e476 100644 --- a/src/Analyzers/Core/CodeFixes/GenerateVariable/AbstractGenerateVariableService.GenerateLocalCodeAction.cs +++ b/src/Analyzers/Core/CodeFixes/GenerateVariable/AbstractGenerateVariableService.GenerateLocalCodeAction.cs @@ -10,7 +10,6 @@ using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateVariable; diff --git a/src/Analyzers/Core/CodeFixes/ImplementAbstractClass/ImplementAbstractClassData.cs b/src/Analyzers/Core/CodeFixes/ImplementAbstractClass/ImplementAbstractClassData.cs index 6478678cade58..5068f96582a34 100644 --- a/src/Analyzers/Core/CodeFixes/ImplementAbstractClass/ImplementAbstractClassData.cs +++ b/src/Analyzers/Core/CodeFixes/ImplementAbstractClass/ImplementAbstractClassData.cs @@ -21,12 +21,6 @@ using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; -#if CODE_STYLE -using DeclarationModifiers = Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers; -#else -using DeclarationModifiers = Microsoft.CodeAnalysis.Editing.DeclarationModifiers; -#endif - namespace Microsoft.CodeAnalysis.ImplementAbstractClass; internal sealed class ImplementAbstractClassData( @@ -152,7 +146,7 @@ private ImmutableArray GenerateMembers( Compilation compilation, ISymbol member, ISymbol? throughMember, bool addUnsafe, ImplementTypePropertyGenerationBehavior propertyGenerationBehavior) { - var modifiers = new DeclarationModifiers(isOverride: true, isUnsafe: addUnsafe, isRequired: member.IsRequired()); + var modifiers = DeclarationModifiers.Override.WithIsUnsafe(addUnsafe).WithIsRequired(member.IsRequired()); var accessibility = member.ComputeResultantAccessibility(ClassType); // only call through one of members for this symbol if we can actually access the symbol diff --git a/src/Analyzers/Core/CodeFixes/ImplementInterface/ImplementInterfaceGenerator.cs b/src/Analyzers/Core/CodeFixes/ImplementInterface/ImplementInterfaceGenerator.cs index 95a2631ed8499..fc5078f1ea994 100644 --- a/src/Analyzers/Core/CodeFixes/ImplementInterface/ImplementInterfaceGenerator.cs +++ b/src/Analyzers/Core/CodeFixes/ImplementInterface/ImplementInterfaceGenerator.cs @@ -18,12 +18,6 @@ using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; -#if CODE_STYLE -using DeclarationModifiers = Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers; -#else -using DeclarationModifiers = Microsoft.CodeAnalysis.Editing.DeclarationModifiers; -#endif - namespace Microsoft.CodeAnalysis.ImplementInterface; using static ImplementHelpers; @@ -99,7 +93,7 @@ private async Task ImplementInterfaceAsync( autoInsertionLocation: groupMembers, sortMembers: groupMembers)), State.ClassOrStructType, - memberDefinitions.Concat(extraMembers), + [.. memberDefinitions, .. extraMembers], cancellationToken).ConfigureAwait(false); } @@ -293,7 +287,7 @@ public ImmutableArray GenerateMembers( ImplementTypePropertyGenerationBehavior propertyGenerationBehavior) { var factory = Document.GetRequiredLanguageService(); - var modifiers = new DeclarationModifiers(isStatic: member.IsStatic, isAbstract: generateAbstractly, isNew: addNew, isUnsafe: addUnsafe); + var modifiers = DeclarationModifiers.None.WithIsStatic(member.IsStatic).WithIsAbstract(generateAbstractly).WithIsNew(addNew).WithIsUnsafe(addUnsafe); var useExplicitInterfaceSymbol = generateInvisibly || !Service.CanImplementImplicitly; var accessibility = member.Name == memberName || generateAbstractly diff --git a/src/Analyzers/Core/CodeFixes/ImplementInterface/ImplementInterfaceGenerator_Conflicts.cs b/src/Analyzers/Core/CodeFixes/ImplementInterface/ImplementInterfaceGenerator_Conflicts.cs index 0d3489a6fe31f..fb554b99f4494 100644 --- a/src/Analyzers/Core/CodeFixes/ImplementInterface/ImplementInterfaceGenerator_Conflicts.cs +++ b/src/Analyzers/Core/CodeFixes/ImplementInterface/ImplementInterfaceGenerator_Conflicts.cs @@ -10,12 +10,6 @@ using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; -#if CODE_STYLE -using DeclarationModifiers = Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers; -#else -using DeclarationModifiers = Microsoft.CodeAnalysis.Editing.DeclarationModifiers; -#endif - namespace Microsoft.CodeAnalysis.ImplementInterface; internal abstract partial class AbstractImplementInterfaceService diff --git a/src/Analyzers/Core/CodeFixes/ImplementInterface/ImplementInterfaceGenerator_DisposePattern.cs b/src/Analyzers/Core/CodeFixes/ImplementInterface/ImplementInterfaceGenerator_DisposePattern.cs index fd02292c6e66c..0887f5f52ce86 100644 --- a/src/Analyzers/Core/CodeFixes/ImplementInterface/ImplementInterfaceGenerator_DisposePattern.cs +++ b/src/Analyzers/Core/CodeFixes/ImplementInterface/ImplementInterfaceGenerator_DisposePattern.cs @@ -18,12 +18,6 @@ using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; -#if CODE_STYLE -using DeclarationModifiers = Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers; -#else -using DeclarationModifiers = Microsoft.CodeAnalysis.Editing.DeclarationModifiers; -#endif - namespace Microsoft.CodeAnalysis.ImplementInterface; using static ImplementHelpers; diff --git a/src/Analyzers/Core/CodeFixes/ImplementInterface/ImplementInterfaceGenerator_Method.cs b/src/Analyzers/Core/CodeFixes/ImplementInterface/ImplementInterfaceGenerator_Method.cs index 8ac028421aefd..48a343cdcfe7c 100644 --- a/src/Analyzers/Core/CodeFixes/ImplementInterface/ImplementInterfaceGenerator_Method.cs +++ b/src/Analyzers/Core/CodeFixes/ImplementInterface/ImplementInterfaceGenerator_Method.cs @@ -9,12 +9,6 @@ using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Shared.Extensions; -#if CODE_STYLE -using DeclarationModifiers = Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers; -#else -using DeclarationModifiers = Microsoft.CodeAnalysis.Editing.DeclarationModifiers; -#endif - namespace Microsoft.CodeAnalysis.ImplementInterface; internal abstract partial class AbstractImplementInterfaceService diff --git a/src/Analyzers/Core/CodeFixes/ImplementInterface/ImplementInterfaceGenerator_Property.cs b/src/Analyzers/Core/CodeFixes/ImplementInterface/ImplementInterfaceGenerator_Property.cs index 9390f123877c1..b31a55c26bbe1 100644 --- a/src/Analyzers/Core/CodeFixes/ImplementInterface/ImplementInterfaceGenerator_Property.cs +++ b/src/Analyzers/Core/CodeFixes/ImplementInterface/ImplementInterfaceGenerator_Property.cs @@ -5,6 +5,7 @@ using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeGeneration; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ImplementType; using Microsoft.CodeAnalysis.LanguageService; @@ -13,12 +14,6 @@ using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; -#if CODE_STYLE -using DeclarationModifiers = Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers; -#else -using DeclarationModifiers = Microsoft.CodeAnalysis.Editing.DeclarationModifiers; -#endif - namespace Microsoft.CodeAnalysis.ImplementInterface; internal abstract partial class AbstractImplementInterfaceService diff --git a/src/Analyzers/Core/CodeFixes/NamingStyle/NamingStyleCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/NamingStyle/NamingStyleCodeFixProvider.cs index 4deb60395c3e6..205085ef2daae 100644 --- a/src/Analyzers/Core/CodeFixes/NamingStyle/NamingStyleCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/NamingStyle/NamingStyleCodeFixProvider.cs @@ -12,13 +12,13 @@ using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.NamingStyles; using Microsoft.CodeAnalysis.Rename; -using Microsoft.CodeAnalysis.Shared.Extensions; -using Roslyn.Utilities; using Microsoft.CodeAnalysis.Shared.Collections; +using Microsoft.CodeAnalysis.Shared.Extensions; #if !CODE_STYLE // https://github.com/dotnet/roslyn/issues/42218 removing dependency on WorkspaceServices. using Microsoft.CodeAnalysis.CodeActions.WorkspaceServices; diff --git a/src/Analyzers/Core/CodeFixes/OrderModifiers/AbstractOrderModifiersCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/OrderModifiers/AbstractOrderModifiersCodeFixProvider.cs index b061646a01f88..ae3eb36cf82fa 100644 --- a/src/Analyzers/Core/CodeFixes/OrderModifiers/AbstractOrderModifiersCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/OrderModifiers/AbstractOrderModifiersCodeFixProvider.cs @@ -6,8 +6,8 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageService; diff --git a/src/Analyzers/Core/CodeFixes/PopulateSwitch/AbstractPopulateSwitchCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/PopulateSwitch/AbstractPopulateSwitchCodeFixProvider.cs index cd6a904563b7b..f8bd8a1e1d7e3 100644 --- a/src/Analyzers/Core/CodeFixes/PopulateSwitch/AbstractPopulateSwitchCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/PopulateSwitch/AbstractPopulateSwitchCodeFixProvider.cs @@ -15,7 +15,6 @@ using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.PopulateSwitch; diff --git a/src/Analyzers/Core/CodeFixes/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsCodeFixProvider.cs index 73858ed2b065a..61d48f8bc0827 100644 --- a/src/Analyzers/Core/CodeFixes/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsCodeFixProvider.cs @@ -7,20 +7,25 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.RemoveUnnecessaryImports; -internal abstract class AbstractRemoveUnnecessaryImportsCodeFixProvider : CodeFixProvider +internal abstract class AbstractRemoveUnnecessaryImportsCodeFixProvider : SyntaxEditorBasedCodeFixProvider { + protected abstract string GetTitle(); protected abstract ISyntaxFormatting GetSyntaxFormatting(); public sealed override ImmutableArray FixableDiagnosticIds => [RemoveUnnecessaryImportsConstants.DiagnosticFixableId]; - public sealed override FixAllProvider GetFixAllProvider() - => WellKnownFixAllProviders.BatchFixer; +#if !CODE_STYLE + // We don't need to perform any cleanup for this code fix. It simply removes code, leaving + // things in the state it already needs to be in. + protected override CodeActionCleanup Cleanup => CodeActionCleanup.None; +#endif public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { @@ -37,8 +42,6 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) return Task.CompletedTask; } - protected abstract string GetTitle(); - private static Task RemoveUnnecessaryImportsAsync( Document document, CancellationToken cancellationToken) @@ -46,4 +49,13 @@ private static Task RemoveUnnecessaryImportsAsync( var service = document.GetRequiredLanguageService(); return service.RemoveUnnecessaryImportsAsync(document, cancellationToken); } + + protected sealed override async Task FixAllAsync( + Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) + { + var newDocument = await RemoveUnnecessaryImportsAsync(document, cancellationToken).ConfigureAwait(false); + var newRoot = await newDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + + editor.ReplaceNode(editor.OriginalRoot, newRoot); + } } diff --git a/src/Analyzers/Core/CodeFixes/UpgradeProject/AbstractUpgradeProjectCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UpgradeProject/AbstractUpgradeProjectCodeFixProvider.cs index b70f1d64ba778..e3df429eb4302 100644 --- a/src/Analyzers/Core/CodeFixes/UpgradeProject/AbstractUpgradeProjectCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UpgradeProject/AbstractUpgradeProjectCodeFixProvider.cs @@ -125,7 +125,7 @@ internal sealed class ProjectOptionsChangeAction : SolutionChangeAction public override ImmutableArray Tags => RequiresNonDocumentChangeTags; private ProjectOptionsChangeAction(string title, Func, CancellationToken, Task> createChangedSolution) - : base(title, createChangedSolution, equivalenceKey: null, priority: CodeActionPriority.Default, createdFromFactoryMethod: true) + : base(title, createChangedSolution, equivalenceKey: null, priority: CodeActionPriority.Default, CodeActionCleanup.Default, createdFromFactoryMethod: true) { } diff --git a/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForAssignment/AbstractUseConditionalExpressionForAssignmentCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForAssignment/AbstractUseConditionalExpressionForAssignmentCodeFixProvider.cs index 2b3ed157e4237..5d492d9355e9b 100644 --- a/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForAssignment/AbstractUseConditionalExpressionForAssignmentCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForAssignment/AbstractUseConditionalExpressionForAssignmentCodeFixProvider.cs @@ -14,7 +14,6 @@ using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; -using Roslyn.Utilities; using static Microsoft.CodeAnalysis.UseConditionalExpression.UseConditionalExpressionCodeFixHelpers; namespace Microsoft.CodeAnalysis.UseConditionalExpression; diff --git a/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnCodeFixProvider.cs index 61ab3eec1b0cd..3d1cc7843dd7b 100644 --- a/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnCodeFixProvider.cs @@ -13,7 +13,6 @@ using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; -using Roslyn.Utilities; using static Microsoft.CodeAnalysis.UseConditionalExpression.UseConditionalExpressionCodeFixHelpers; namespace Microsoft.CodeAnalysis.UseConditionalExpression; diff --git a/src/Analyzers/Core/CodeFixes/UseNullPropagation/AbstractUseNullPropagationCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseNullPropagation/AbstractUseNullPropagationCodeFixProvider.cs index c1e6714f1e0ac..a530ed5473855 100644 --- a/src/Analyzers/Core/CodeFixes/UseNullPropagation/AbstractUseNullPropagationCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseNullPropagation/AbstractUseNullPropagationCodeFixProvider.cs @@ -5,8 +5,8 @@ using System; using System.Collections.Immutable; using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Linq; +using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; @@ -14,12 +14,14 @@ using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageService; +using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseNullPropagation; internal abstract class AbstractUseNullPropagationCodeFixProvider< + TAnalyzer, TSyntaxKind, TExpressionSyntax, TStatementSyntax, @@ -32,7 +34,12 @@ internal abstract class AbstractUseNullPropagationCodeFixProvider< TElementBindingExpressionSyntax, TIfStatementSyntax, TExpressionStatementSyntax, - TElementBindingArgumentListSyntax> : SyntaxEditorBasedCodeFixProvider + TElementBindingArgumentListSyntax> : ForkingSyntaxEditorBasedCodeFixProvider + where TAnalyzer : AbstractUseNullPropagationDiagnosticAnalyzer< + TSyntaxKind, TExpressionSyntax, TStatementSyntax, + TConditionalExpressionSyntax, TBinaryExpressionSyntax, TInvocationExpressionSyntax, + TConditionalAccessExpressionSyntax, TElementAccessExpressionSyntax, TMemberAccessExpressionSyntax, + TIfStatementSyntax, TExpressionStatementSyntax> where TSyntaxKind : struct where TExpressionSyntax : SyntaxNode where TStatementSyntax : SyntaxNode @@ -47,76 +54,71 @@ internal abstract class AbstractUseNullPropagationCodeFixProvider< where TExpressionStatementSyntax : TStatementSyntax where TElementBindingArgumentListSyntax : SyntaxNode { - protected abstract bool TryGetBlock(SyntaxNode? node, [NotNullWhen(true)] out TStatementSyntax? block); - protected abstract TStatementSyntax ReplaceBlockStatements(TStatementSyntax block, TStatementSyntax newInnerStatement); protected abstract SyntaxNode PostProcessElseIf(TIfStatementSyntax ifStatement, TStatementSyntax newWhenTrueStatement); protected abstract TElementBindingExpressionSyntax ElementBindingExpression(TElementBindingArgumentListSyntax argumentList); + protected abstract TAnalyzer Analyzer { get; } + public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.UseNullPropagationDiagnosticId]; - protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) - => !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary); - - public override Task RegisterCodeFixesAsync(CodeFixContext context) + protected override (string title, string equivalenceKey) GetTitleAndEquivalenceKey(CodeFixContext context) { var firstDiagnostic = context.Diagnostics.First(); - var title = IsTrivialNullableValueAccess(firstDiagnostic) + var title = IsTrivialNullableValueAccess(firstDiagnostic.Properties) ? AnalyzersResources.Simplify_conditional_expression : AnalyzersResources.Use_null_propagation; - RegisterCodeFix(context, title, nameof(AnalyzersResources.Use_null_propagation)); - return Task.CompletedTask; + return (title, nameof(AnalyzersResources.Use_null_propagation)); } - private static bool IsTrivialNullableValueAccess(Diagnostic firstDiagnostic) - { - return firstDiagnostic.Properties.ContainsKey(UseNullPropagationHelpers.IsTrivialNullableValueAccess); - } + private static bool IsTrivialNullableValueAccess(ImmutableDictionary properties) + => properties.ContainsKey(UseNullPropagationHelpers.IsTrivialNullableValueAccess); - protected override async Task FixAllAsync( - Document document, ImmutableArray diagnostics, - SyntaxEditor editor, CancellationToken cancellationToken) + protected override async Task FixAsync( + Document document, + SyntaxEditor editor, + SyntaxNode conditionalExpressionOrIfStatement, + ImmutableDictionary properties, + CancellationToken cancellationToken) { - var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); - var root = editor.OriginalRoot; - - foreach (var diagnostic in diagnostics) + if (conditionalExpressionOrIfStatement is TIfStatementSyntax ifStatement) { - var conditionalExpressionOrIfStatement = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true); - if (conditionalExpressionOrIfStatement is TIfStatementSyntax ifStatement) - { - FixIfStatement(document, editor, diagnostic, ifStatement); - } - else - { - FixConditionalExpression(document, editor, semanticModel, diagnostic, conditionalExpressionOrIfStatement, cancellationToken); - } + await FixIfStatementAsync( + document, editor, ifStatement, properties, cancellationToken).ConfigureAwait(false); + } + else + { + await FixConditionalExpressionAsync( + document, editor, (TConditionalExpressionSyntax)conditionalExpressionOrIfStatement, properties, cancellationToken).ConfigureAwait(false); } } - private void FixConditionalExpression( + private async Task FixConditionalExpressionAsync( Document document, SyntaxEditor editor, - SemanticModel semanticModel, - Diagnostic diagnostic, - SyntaxNode conditionalExpression, + TConditionalExpressionSyntax conditionalExpression, + ImmutableDictionary properties, CancellationToken cancellationToken) { var root = editor.OriginalRoot; + var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService(); var generator = document.GetRequiredLanguageService(); - var conditionalPart = root.FindNode(diagnostic.AdditionalLocations[1].SourceSpan, getInnermostNodeForTie: true); - var whenPart = root.FindNode(diagnostic.AdditionalLocations[2].SourceSpan, getInnermostNodeForTie: true); + var conditionalExpressionParts = this.GetPartsOfConditionalExpression( + semanticModel, conditionalExpression, cancellationToken); + if (conditionalExpressionParts is not var (conditionalPart, whenPart)) + return; + syntaxFacts.GetPartsOfConditionalExpression( conditionalExpression, out _, out var whenTrue, out _); whenTrue = syntaxFacts.WalkDownParentheses(whenTrue); // `x == null ? x : x.Value` will be converted to just 'x'. - if (IsTrivialNullableValueAccess(diagnostic)) + if (IsTrivialNullableValueAccess(properties)) { editor.ReplaceNode( conditionalExpression, @@ -124,7 +126,7 @@ private void FixConditionalExpression( return; } - var whenPartIsNullable = diagnostic.Properties.ContainsKey(UseNullPropagationHelpers.WhenPartIsNullable); + var whenPartIsNullable = properties.ContainsKey(UseNullPropagationHelpers.WhenPartIsNullable); editor.ReplaceNode( conditionalExpression, (conditionalExpression, _) => @@ -136,12 +138,8 @@ private void FixConditionalExpression( var unwrappedCurrentWhenPartToCheck = syntaxFacts.WalkDownParentheses(currentWhenPartToCheck); - var match = AbstractUseNullPropagationDiagnosticAnalyzer< - TSyntaxKind, TExpressionSyntax, TStatementSyntax, - TConditionalExpressionSyntax, TBinaryExpressionSyntax, TInvocationExpressionSyntax, - TConditionalAccessExpressionSyntax, TElementAccessExpressionSyntax, TMemberAccessExpressionSyntax, - TIfStatementSyntax, TExpressionStatementSyntax>.GetWhenPartMatch( - syntaxFacts, semanticModel, (TExpressionSyntax)conditionalPart, (TExpressionSyntax)unwrappedCurrentWhenPartToCheck, cancellationToken); + var match = this.Analyzer.GetWhenPartMatch( + syntaxFacts, semanticModel, conditionalPart, (TExpressionSyntax)unwrappedCurrentWhenPartToCheck, cancellationToken); if (match == null) { return conditionalExpression; @@ -155,24 +153,26 @@ private void FixConditionalExpression( }); } - private void FixIfStatement( + private async Task FixIfStatementAsync( Document document, SyntaxEditor editor, - Diagnostic diagnostic, - TIfStatementSyntax ifStatement) + TIfStatementSyntax ifStatement, + ImmutableDictionary properties, + CancellationToken cancellationToken) { var root = editor.OriginalRoot; + var semanticModel = await document.GetRequiredSemanticModelAsync(CancellationToken.None).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService(); var generator = document.GetRequiredLanguageService(); - var whenTrueStatement = (TStatementSyntax)root.FindNode(diagnostic.AdditionalLocations[1].SourceSpan); - var match = (TExpressionSyntax)root.FindNode(diagnostic.AdditionalLocations[2].SourceSpan, getInnermostNodeForTie: true); + var ifStatementParts = this.GetPartsOfIfStatement(semanticModel, ifStatement, cancellationToken); + if (ifStatementParts is not var (whenTrueStatement, match, nullAssignmentOpt)) + return; - var whenPartIsNullable = diagnostic.Properties.ContainsKey(UseNullPropagationHelpers.WhenPartIsNullable); + var whenPartIsNullable = properties.ContainsKey(UseNullPropagationHelpers.WhenPartIsNullable); SyntaxNode nodeToBeReplaced = ifStatement; - SyntaxNode? replacementNode = null; // we have `if (x != null) x.Y();`. Update `x.Y()` to be `x?.Y()`, then replace the entire // if-statement with that expression statement. @@ -180,54 +180,61 @@ private void FixIfStatement( syntaxFacts, generator, whenPartIsNullable, whenTrueStatement, match); Contract.ThrowIfNull(newWhenTrueStatement); - var isElseIf = syntaxFacts.IsElseClause(ifStatement.Parent); - - // If we have code like: - // ... - // else if (v != null) - // { - // v.M(); - // } - // then we want to keep the result statement in a block: - // else - // { - // v?.M(); - // } - // Applies only to C# since VB doesn't have a general-purpose block syntax - if (isElseIf && - TryGetBlock(whenTrueStatement.Parent, out var block)) - { - newWhenTrueStatement = ReplaceBlockStatements(block, newWhenTrueStatement); - } - - // If there's leading trivia on the original inner statement, then combine that with the leading - // trivia on the if-statement. We'll need to add a formatting annotation so that the leading comments - // are put in the right location. - if (newWhenTrueStatement.GetLeadingTrivia().Any(syntaxFacts.IsRegularComment)) + if (syntaxFacts.IsElseClause(ifStatement.Parent)) { - newWhenTrueStatement = newWhenTrueStatement - .WithPrependedLeadingTrivia(ifStatement.GetLeadingTrivia()) - .WithAdditionalAnnotations(Formatter.Annotation); + // If we have code like: + // ... + // else if (v != null) + // { + // v.M(); + // } + // then we want to keep the result statement in a block: + // else + // { + // v?.M(); + // } + // Applies only to C# since VB doesn't have a general-purpose block syntax + editor.ReplaceNode(ifStatement.Parent, PostProcessElseIf(ifStatement, newWhenTrueStatement)); } else { - if (isElseIf) + // If there's leading trivia on the original inner statement, then combine that with the leading + // trivia on the if-statement. We'll need to add a formatting annotation so that the leading comments + // are put in the right location. + if (newWhenTrueStatement.GetLeadingTrivia().Any(syntaxFacts.IsRegularComment)) { - nodeToBeReplaced = ifStatement.Parent!; - replacementNode = PostProcessElseIf(ifStatement, newWhenTrueStatement); + newWhenTrueStatement = newWhenTrueStatement + .WithPrependedLeadingTrivia(ifStatement.GetLeadingTrivia()) + .WithAdditionalAnnotations(Formatter.Annotation); } else { newWhenTrueStatement = newWhenTrueStatement.WithLeadingTrivia(ifStatement.GetLeadingTrivia()); } - } - // If there's trailing comments on the original inner statement, then preserve that. Otherwise, - // replace it with the trailing trivia of hte original if-statement. - if (!newWhenTrueStatement.GetTrailingTrivia().Any(syntaxFacts.IsRegularComment) && !isElseIf) - newWhenTrueStatement = newWhenTrueStatement.WithTrailingTrivia(ifStatement.GetTrailingTrivia()); + // If there's trailing comments on the original inner statement, then preserve that. Otherwise, + // replace it with the trailing trivia of hte original if-statement. + if (!newWhenTrueStatement.GetTrailingTrivia().Any(syntaxFacts.IsRegularComment)) + newWhenTrueStatement = newWhenTrueStatement.WithTrailingTrivia(ifStatement.GetTrailingTrivia()); + + // If we don't have a `x = null;` statement, then we just replace the if-statement with the new expr?.Statement(); + // If we do have a `x = null;` statement, then insert `expr?.Statement();` and it after the if-statement, then + // remove the if-statement. + if (nullAssignmentOpt is null) + { + editor.ReplaceNode(nodeToBeReplaced, newWhenTrueStatement); + } + else + { + using var _ = ArrayBuilder.GetInstance(out var replacementNodes); + replacementNodes.Add(newWhenTrueStatement); + + replacementNodes.Add(nullAssignmentOpt.WithAdditionalAnnotations(Formatter.Annotation)); - editor.ReplaceNode(nodeToBeReplaced, replacementNode ?? newWhenTrueStatement); + editor.InsertAfter(nodeToBeReplaced, replacementNodes); + editor.RemoveNode(nodeToBeReplaced); + } + } } private TContainer? CreateConditionalAccessExpression( @@ -243,7 +250,7 @@ private void FixIfStatement( syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out var name, out var arity); var comparer = syntaxFacts.StringComparer; - if (arity == 0 && comparer.Equals(name, nameof(Nullable.Value))) + if (arity == 0 && comparer.Equals(name, nameof(Nullable<>.Value))) { // They're calling ".Value" off of a nullable. Because we're moving to ?. // we want to remove the .Value as well. i.e. we should generate: @@ -284,4 +291,28 @@ private void FixIfStatement( return null; } + + private (TStatementSyntax whenTrueStatement, TExpressionSyntax whenPartMatch, TStatementSyntax? nullAssignmentOpt)? GetPartsOfIfStatement( + SemanticModel semanticModel, TIfStatementSyntax ifStatement, CancellationToken cancellationToken) + { + var (_, referenceEqualsMethod) = this.Analyzer.GetAnalysisSymbols(semanticModel.Compilation); + var analysisResult = this.Analyzer.AnalyzeIfStatement( + semanticModel, referenceEqualsMethod, ifStatement, cancellationToken); + if (analysisResult is null) + return null; + + return (analysisResult.Value.TrueStatement, analysisResult.Value.WhenPartMatch, analysisResult.Value.NullAssignmentOpt); + } + + private (TExpressionSyntax conditionalPart, SyntaxNode whenPart)? GetPartsOfConditionalExpression( + SemanticModel semanticModel, TConditionalExpressionSyntax conditionalExpression, CancellationToken cancellationToken) + { + var (expressionType, referenceEqualsMethod) = this.Analyzer.GetAnalysisSymbols(semanticModel.Compilation); + var analysisResult = this.Analyzer.AnalyzeTernaryConditionalExpression( + semanticModel, expressionType, referenceEqualsMethod, conditionalExpression, cancellationToken); + if (analysisResult is null) + return null; + + return (analysisResult.Value.ConditionPartToCheck, analysisResult.Value.WhenPartToCheck); + } } diff --git a/src/Analyzers/VisualBasic/Analyzers/AddRequiredParentheses/VisualBasicAddRequiredParenthesesDiagnosticAnalyzer.vb b/src/Analyzers/VisualBasic/Analyzers/AddRequiredParentheses/VisualBasicAddRequiredParenthesesDiagnosticAnalyzer.vb index 085971af789a3..f4c398604a371 100644 --- a/src/Analyzers/VisualBasic/Analyzers/AddRequiredParentheses/VisualBasicAddRequiredParenthesesDiagnosticAnalyzer.vb +++ b/src/Analyzers/VisualBasic/Analyzers/AddRequiredParentheses/VisualBasicAddRequiredParenthesesDiagnosticAnalyzer.vb @@ -10,7 +10,7 @@ Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.AddRequiredParentheses - Friend Class VisualBasicAddRequiredParenthesesForBinaryLikeExpressionDiagnosticAnalyzer + Friend NotInheritable Class VisualBasicAddRequiredParenthesesForBinaryLikeExpressionDiagnosticAnalyzer Inherits AbstractAddRequiredParenthesesDiagnosticAnalyzer(Of ExpressionSyntax, BinaryExpressionSyntax, SyntaxKind) @@ -63,5 +63,11 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.AddRequiredParentheses Protected Overrides Function IsBinaryLike(node As ExpressionSyntax) As Boolean Return TypeOf node Is BinaryExpressionSyntax End Function + + Protected Overrides Function IsAsExpression(node As BinaryExpressionSyntax) As Boolean + ' VB does not have an 'as' node that is a binary-expression like C# does. Instead, it is TryCast(a, b) + ' which is not a binary expression and never needs extra parentheses. + Return False + End Function End Class End Namespace diff --git a/src/Analyzers/VisualBasic/Analyzers/UseCoalesceExpression/VisualBasicUseCoalesceExpressionForIfNullStatementCheckDiagnosticAnalyzer.vb b/src/Analyzers/VisualBasic/Analyzers/UseCoalesceExpression/VisualBasicUseCoalesceExpressionForIfNullStatementCheckDiagnosticAnalyzer.vb index 99e10147447b6..9f3171f0242d2 100644 --- a/src/Analyzers/VisualBasic/Analyzers/UseCoalesceExpression/VisualBasicUseCoalesceExpressionForIfNullStatementCheckDiagnosticAnalyzer.vb +++ b/src/Analyzers/VisualBasic/Analyzers/UseCoalesceExpression/VisualBasicUseCoalesceExpressionForIfNullStatementCheckDiagnosticAnalyzer.vb @@ -3,11 +3,9 @@ ' See the LICENSE file in the project root for more information. Imports System.Diagnostics.CodeAnalysis -Imports System.Threading Imports Microsoft.CodeAnalysis.Analyzers.UseCoalesceExpression Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.LanguageService -Imports Microsoft.CodeAnalysis.UseCoalesceExpression Imports Microsoft.CodeAnalysis.VisualBasic.LanguageService Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Analyzers/VisualBasic/Analyzers/UseInferredMemberName/VisualBasicUseInferredMemberNameDiagnosticAnalyzer.vb b/src/Analyzers/VisualBasic/Analyzers/UseInferredMemberName/VisualBasicUseInferredMemberNameDiagnosticAnalyzer.vb index ea2a222b81b09..08cfd653e6895 100644 --- a/src/Analyzers/VisualBasic/Analyzers/UseInferredMemberName/VisualBasicUseInferredMemberNameDiagnosticAnalyzer.vb +++ b/src/Analyzers/VisualBasic/Analyzers/UseInferredMemberName/VisualBasicUseInferredMemberNameDiagnosticAnalyzer.vb @@ -3,8 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.Threading -Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.UseInferredMemberName diff --git a/src/Analyzers/VisualBasic/Analyzers/UseNullPropagation/VisualBasicUseNullPropagationDiagnosticAnalyzer.vb b/src/Analyzers/VisualBasic/Analyzers/UseNullPropagation/VisualBasicUseNullPropagationDiagnosticAnalyzer.vb index c8412f9972f8f..bdcd276e32ca5 100644 --- a/src/Analyzers/VisualBasic/Analyzers/UseNullPropagation/VisualBasicUseNullPropagationDiagnosticAnalyzer.vb +++ b/src/Analyzers/VisualBasic/Analyzers/UseNullPropagation/VisualBasicUseNullPropagationDiagnosticAnalyzer.vb @@ -2,17 +2,15 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Diagnostics.CodeAnalysis -Imports System.Threading +Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.UseNullPropagation -Imports Microsoft.CodeAnalysis.VisualBasic.LanguageService Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UseNullPropagation - Friend Class VisualBasicUseNullPropagationDiagnosticAnalyzer + Friend NotInheritable Class VisualBasicUseNullPropagationDiagnosticAnalyzer Inherits AbstractUseNullPropagationDiagnosticAnalyzer(Of SyntaxKind, ExpressionSyntax, @@ -26,6 +24,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.UseNullPropagation MultiLineIfBlockSyntax, ExpressionStatementSyntax) + Public Shared ReadOnly Instance As New VisualBasicUseNullPropagationDiagnosticAnalyzer() + Protected Overrides ReadOnly Property IfStatementSyntaxKind As SyntaxKind = SyntaxKind.MultiLineIfBlock Protected Overrides ReadOnly Property SemanticFacts As ISemanticFacts = VisualBasicSemanticFacts.Instance @@ -44,7 +44,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.UseNullPropagation Protected Overrides Function TryGetPartsOfIfStatement( ifStatement As MultiLineIfBlockSyntax, ByRef condition As ExpressionSyntax, - ByRef trueStatement As ExecutableStatementSyntax) As Boolean + ByRef trueStatements As ImmutableArray(Of ExecutableStatementSyntax)) As Boolean condition = ifStatement.IfStatement.Condition @@ -56,12 +56,16 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.UseNullPropagation Return False End If - If ifStatement.Statements.Count <> 1 Then + If ifStatement.Statements.Count > 2 Then + Return False + End If + + If Not ifStatement.Statements.All(Function(s) TypeOf s Is ExecutableStatementSyntax) Then Return False End If - trueStatement = TryCast(ifStatement.Statements(0), ExecutableStatementSyntax) - Return trueStatement IsNot Nothing + trueStatements = ifStatement.Statements.Cast(Of ExecutableStatementSyntax)().ToImmutableArrayOrEmpty() + Return True End Function End Class End Namespace diff --git a/src/Analyzers/VisualBasic/CodeFixes/GenerateConstructor/GenerateConstructorCodeFixProvider.vb b/src/Analyzers/VisualBasic/CodeFixes/GenerateConstructor/GenerateConstructorCodeFixProvider.vb index 3992689a627f3..6667ce236ee64 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/GenerateConstructor/GenerateConstructorCodeFixProvider.vb +++ b/src/Analyzers/VisualBasic/CodeFixes/GenerateConstructor/GenerateConstructorCodeFixProvider.vb @@ -9,8 +9,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeFixes.GenerateMember -Imports Microsoft.CodeAnalysis.CodeGeneration -Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Analyzers/VisualBasic/CodeFixes/GenerateEnumMember/GenerateEnumMemberCodeFixProvider.vb b/src/Analyzers/VisualBasic/CodeFixes/GenerateEnumMember/GenerateEnumMemberCodeFixProvider.vb index 276998efdd7b1..5c5cac736bceb 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/GenerateEnumMember/GenerateEnumMemberCodeFixProvider.vb +++ b/src/Analyzers/VisualBasic/CodeFixes/GenerateEnumMember/GenerateEnumMemberCodeFixProvider.vb @@ -9,7 +9,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeFixes.GenerateMember -Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.GenerateMember.GenerateEnumMember Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Analyzers/VisualBasic/CodeFixes/GenerateParameterizedMember/GenerateConversionCodeFixProvider.vb b/src/Analyzers/VisualBasic/CodeFixes/GenerateParameterizedMember/GenerateConversionCodeFixProvider.vb index eba274d4bf834..2202be6f64a5a 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/GenerateParameterizedMember/GenerateConversionCodeFixProvider.vb +++ b/src/Analyzers/VisualBasic/CodeFixes/GenerateParameterizedMember/GenerateConversionCodeFixProvider.vb @@ -9,7 +9,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeFixes.GenerateMember -Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Analyzers/VisualBasic/CodeFixes/GenerateParameterizedMember/GenerateParameterizedMemberCodeFixProvider.vb b/src/Analyzers/VisualBasic/CodeFixes/GenerateParameterizedMember/GenerateParameterizedMemberCodeFixProvider.vb index ab2feaf6fe4e9..32345e1bd47ef 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/GenerateParameterizedMember/GenerateParameterizedMemberCodeFixProvider.vb +++ b/src/Analyzers/VisualBasic/CodeFixes/GenerateParameterizedMember/GenerateParameterizedMemberCodeFixProvider.vb @@ -9,7 +9,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeFixes.GenerateMember -Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Analyzers/VisualBasic/CodeFixes/GenerateParameterizedMember/VisualBasicGenerateParameterizedMemberService.vb b/src/Analyzers/VisualBasic/CodeFixes/GenerateParameterizedMember/VisualBasicGenerateParameterizedMemberService.vb index 7ac08d83fd613..0d47db992151d 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/GenerateParameterizedMember/VisualBasicGenerateParameterizedMemberService.vb +++ b/src/Analyzers/VisualBasic/CodeFixes/GenerateParameterizedMember/VisualBasicGenerateParameterizedMemberService.vb @@ -10,7 +10,6 @@ Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember -Imports Microsoft.CodeAnalysis.Utilities Imports System.Collections.Immutable Namespace Microsoft.CodeAnalysis.VisualBasic.GenerateMember.GenerateMethod diff --git a/src/Analyzers/VisualBasic/CodeFixes/GenerateVariable/VisualBasicGenerateVariableCodeFixProvider.vb b/src/Analyzers/VisualBasic/CodeFixes/GenerateVariable/VisualBasicGenerateVariableCodeFixProvider.vb index 9dd8c5a4bb849..320b93ad7614a 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/GenerateVariable/VisualBasicGenerateVariableCodeFixProvider.vb +++ b/src/Analyzers/VisualBasic/CodeFixes/GenerateVariable/VisualBasicGenerateVariableCodeFixProvider.vb @@ -9,7 +9,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeFixes.GenerateMember -Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.GenerateMember.GenerateVariable Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Analyzers/VisualBasic/CodeFixes/OrderModifiers/VisualBasicOrderModifiersCodeFixProvider.vb b/src/Analyzers/VisualBasic/CodeFixes/OrderModifiers/VisualBasicOrderModifiersCodeFixProvider.vb index 1e33cae146d2c..e40ed6fdd365c 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/OrderModifiers/VisualBasicOrderModifiersCodeFixProvider.vb +++ b/src/Analyzers/VisualBasic/CodeFixes/OrderModifiers/VisualBasicOrderModifiersCodeFixProvider.vb @@ -9,7 +9,6 @@ Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.OrderModifiers -Imports Microsoft.CodeAnalysis.VisualBasic.CodeStyle Imports Microsoft.CodeAnalysis.VisualBasic.LanguageService Namespace Microsoft.CodeAnalysis.VisualBasic.OrderModifiers diff --git a/src/Analyzers/VisualBasic/CodeFixes/RemoveUnnecessaryByVal/VisualBasicRemoveUnnecessaryByValCodeFixProvider.vb b/src/Analyzers/VisualBasic/CodeFixes/RemoveUnnecessaryByVal/VisualBasicRemoveUnnecessaryByValCodeFixProvider.vb index 11cd4e7dfc9c5..c471251872944 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/RemoveUnnecessaryByVal/VisualBasicRemoveUnnecessaryByValCodeFixProvider.vb +++ b/src/Analyzers/VisualBasic/CodeFixes/RemoveUnnecessaryByVal/VisualBasicRemoveUnnecessaryByValCodeFixProvider.vb @@ -4,9 +4,7 @@ Imports System.Collections.Immutable Imports System.Composition -Imports System.Diagnostics.CodeAnalysis Imports System.Threading -Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editing diff --git a/src/Analyzers/VisualBasic/CodeFixes/RemoveUnnecessaryCast/VisualBasicRemoveUnnecessaryCastCodeFixProvider.vb b/src/Analyzers/VisualBasic/CodeFixes/RemoveUnnecessaryCast/VisualBasicRemoveUnnecessaryCastCodeFixProvider.vb index 5da4201250f97..fb4976b324bfa 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/RemoveUnnecessaryCast/VisualBasicRemoveUnnecessaryCastCodeFixProvider.vb +++ b/src/Analyzers/VisualBasic/CodeFixes/RemoveUnnecessaryCast/VisualBasicRemoveUnnecessaryCastCodeFixProvider.vb @@ -7,7 +7,6 @@ Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editing diff --git a/src/Analyzers/VisualBasic/CodeFixes/SimplifyObjectCreation/VisualBasicSimplifyObjectCreationCodeFixProvider.vb b/src/Analyzers/VisualBasic/CodeFixes/SimplifyObjectCreation/VisualBasicSimplifyObjectCreationCodeFixProvider.vb index e39dfdb1b486d..216834f39d94b 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/SimplifyObjectCreation/VisualBasicSimplifyObjectCreationCodeFixProvider.vb +++ b/src/Analyzers/VisualBasic/CodeFixes/SimplifyObjectCreation/VisualBasicSimplifyObjectCreationCodeFixProvider.vb @@ -5,7 +5,6 @@ Imports System.Collections.Immutable Imports System.Composition Imports System.Threading -Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editing diff --git a/src/Analyzers/VisualBasic/CodeFixes/UseConditionalExpression/VisualBasicUseConditionalExpressionForAssignmentCodeFixProvider.vb b/src/Analyzers/VisualBasic/CodeFixes/UseConditionalExpression/VisualBasicUseConditionalExpressionForAssignmentCodeFixProvider.vb index f9632f142f40a..f952aa7820788 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/UseConditionalExpression/VisualBasicUseConditionalExpressionForAssignmentCodeFixProvider.vb +++ b/src/Analyzers/VisualBasic/CodeFixes/UseConditionalExpression/VisualBasicUseConditionalExpressionForAssignmentCodeFixProvider.vb @@ -11,7 +11,6 @@ Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.Operations Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.UseConditionalExpression -Imports Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Imports Microsoft.CodeAnalysis.VisualBasic.Formatting Imports Microsoft.CodeAnalysis.VisualBasic.LanguageService Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Analyzers/VisualBasic/CodeFixes/UseIsNotExpression/VisualBasicUseIsNotExpressionCodeFixProvider.vb b/src/Analyzers/VisualBasic/CodeFixes/UseIsNotExpression/VisualBasicUseIsNotExpressionCodeFixProvider.vb index 7df3b32d7cf4d..278d11549ffc3 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/UseIsNotExpression/VisualBasicUseIsNotExpressionCodeFixProvider.vb +++ b/src/Analyzers/VisualBasic/CodeFixes/UseIsNotExpression/VisualBasicUseIsNotExpressionCodeFixProvider.vb @@ -6,11 +6,9 @@ Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading -Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editing -Imports Microsoft.CodeAnalysis.UseIsNullCheck Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UseIsNotExpression diff --git a/src/Analyzers/VisualBasic/CodeFixes/UseNullPropagation/VisualBasicUseNullPropagationCodeFixProvider.vb b/src/Analyzers/VisualBasic/CodeFixes/UseNullPropagation/VisualBasicUseNullPropagationCodeFixProvider.vb index d2844caf72300..2ae8f4e063bdc 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/UseNullPropagation/VisualBasicUseNullPropagationCodeFixProvider.vb +++ b/src/Analyzers/VisualBasic/CodeFixes/UseNullPropagation/VisualBasicUseNullPropagationCodeFixProvider.vb @@ -10,8 +10,9 @@ Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UseNullPropagation - Friend Class VisualBasicUseNullPropagationCodeFixProvider + Friend NotInheritable Class VisualBasicUseNullPropagationCodeFixProvider Inherits AbstractUseNullPropagationCodeFixProvider(Of + VisualBasicUseNullPropagationDiagnosticAnalyzer, SyntaxKind, ExpressionSyntax, ExecutableStatementSyntax, @@ -31,13 +32,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.UseNullPropagation Public Sub New() End Sub - Protected Overrides Function TryGetBlock(node As SyntaxNode, ByRef block As ExecutableStatementSyntax) As Boolean - Return False - End Function - - Protected Overrides Function ReplaceBlockStatements(block As ExecutableStatementSyntax, newInnerStatement As ExecutableStatementSyntax) As ExecutableStatementSyntax - Throw ExceptionUtilities.Unreachable() - End Function + Protected Overrides ReadOnly Property Analyzer As VisualBasicUseNullPropagationDiagnosticAnalyzer = VisualBasicUseNullPropagationDiagnosticAnalyzer.Instance Protected Overrides Function PostProcessElseIf(ifStatement As MultiLineIfBlockSyntax, newWhenTrueStatement As ExecutableStatementSyntax) As SyntaxNode Throw ExceptionUtilities.Unreachable() diff --git a/src/Analyzers/VisualBasic/CodeFixes/UseObjectInitializer/VisualBasicUseObjectInitializerCodeFixProvider.vb b/src/Analyzers/VisualBasic/CodeFixes/UseObjectInitializer/VisualBasicUseObjectInitializerCodeFixProvider.vb index 1aa0f5fb45ef5..f719030afc0e2 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/UseObjectInitializer/VisualBasicUseObjectInitializerCodeFixProvider.vb +++ b/src/Analyzers/VisualBasic/CodeFixes/UseObjectInitializer/VisualBasicUseObjectInitializerCodeFixProvider.vb @@ -7,7 +7,6 @@ Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Formatting -Imports Microsoft.CodeAnalysis.Indentation Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.UseObjectInitializer diff --git a/src/Analyzers/VisualBasic/Tests/AddRequiredParentheses/AddRequiredParenthesesTests.vb b/src/Analyzers/VisualBasic/Tests/AddRequiredParentheses/AddRequiredParenthesesTests.vb index 4f1189e9fc8b3..a1a07cfeb5a06 100644 --- a/src/Analyzers/VisualBasic/Tests/AddRequiredParentheses/AddRequiredParenthesesTests.vb +++ b/src/Analyzers/VisualBasic/Tests/AddRequiredParentheses/AddRequiredParenthesesTests.vb @@ -2,12 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.AddRequiredParentheses -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic.AddRequiredParentheses - Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of Microsoft.CodeAnalysis.VisualBasic.AddRequiredParentheses.VisualBasicAddRequiredParenthesesForBinaryLikeExpressionDiagnosticAnalyzer, Microsoft.CodeAnalysis.AddRequiredParentheses.AddRequiredParenthesesCodeFixProvider) Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AddRequiredParentheses diff --git a/src/Analyzers/VisualBasic/Tests/GenerateEnumMember/GenerateEnumMemberTests.vb b/src/Analyzers/VisualBasic/Tests/GenerateEnumMember/GenerateEnumMemberTests.vb index af76a833710ba..71437f970a9b6 100644 --- a/src/Analyzers/VisualBasic/Tests/GenerateEnumMember/GenerateEnumMemberTests.vb +++ b/src/Analyzers/VisualBasic/Tests/GenerateEnumMember/GenerateEnumMemberTests.vb @@ -3,8 +3,8 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateEnumMember Imports Microsoft.CodeAnalysis.Diagnostics +Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateEnumMember Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.GenerateEnumMember diff --git a/src/Analyzers/VisualBasic/Tests/GenerateMethod/GenerateConversionTests.vb b/src/Analyzers/VisualBasic/Tests/GenerateMethod/GenerateConversionTests.vb index 845cf4e9293fb..b480e5ce641e3 100644 --- a/src/Analyzers/VisualBasic/Tests/GenerateMethod/GenerateConversionTests.vb +++ b/src/Analyzers/VisualBasic/Tests/GenerateMethod/GenerateConversionTests.vb @@ -3,8 +3,8 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateMethod Imports Microsoft.CodeAnalysis.Diagnostics +Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateMethod Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.GenerateMethod Partial Public NotInheritable Class GenerateMethodTests diff --git a/src/Analyzers/VisualBasic/Tests/ImplementAbstractClass/ImplementAbstractClassTests.vb b/src/Analyzers/VisualBasic/Tests/ImplementAbstractClass/ImplementAbstractClassTests.vb index 2e44de7baf4b7..5ebbd5d1cf4e9 100644 --- a/src/Analyzers/VisualBasic/Tests/ImplementAbstractClass/ImplementAbstractClassTests.vb +++ b/src/Analyzers/VisualBasic/Tests/ImplementAbstractClass/ImplementAbstractClassTests.vb @@ -2,12 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.ImplementType -Imports Microsoft.CodeAnalysis.SymbolSearch Imports Microsoft.CodeAnalysis.VisualBasic.ImplementAbstractClass Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ImplementAbstractClass diff --git a/src/Analyzers/VisualBasic/Tests/ImplementAbstractClass/ImplementAbstractClassTests_FixAllTests.vb b/src/Analyzers/VisualBasic/Tests/ImplementAbstractClass/ImplementAbstractClassTests_FixAllTests.vb index a3c24b00c7ec6..dfdb9f13231bd 100644 --- a/src/Analyzers/VisualBasic/Tests/ImplementAbstractClass/ImplementAbstractClassTests_FixAllTests.vb +++ b/src/Analyzers/VisualBasic/Tests/ImplementAbstractClass/ImplementAbstractClassTests_FixAllTests.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.ImplementAbstractClass - Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ImplementAbstractClass Partial Public Class ImplementAbstractClassTests diff --git a/src/Analyzers/VisualBasic/Tests/ImplementInterface/ImplementInterfaceTests.vb b/src/Analyzers/VisualBasic/Tests/ImplementInterface/ImplementInterfaceTests.vb index a3db069eff8ad..9b9f0deaa814b 100644 --- a/src/Analyzers/VisualBasic/Tests/ImplementInterface/ImplementInterfaceTests.vb +++ b/src/Analyzers/VisualBasic/Tests/ImplementInterface/ImplementInterfaceTests.vb @@ -2,12 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.ImplementType -Imports Microsoft.CodeAnalysis.SymbolSearch Imports Microsoft.CodeAnalysis.VisualBasic.ImplementInterface Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ImplementInterface diff --git a/src/Analyzers/VisualBasic/Tests/Iterator/IteratorTests.vb b/src/Analyzers/VisualBasic/Tests/Iterator/IteratorTests.vb index 9d2552ac7532c..9001a5941146e 100644 --- a/src/Analyzers/VisualBasic/Tests/Iterator/IteratorTests.vb +++ b/src/Analyzers/VisualBasic/Tests/Iterator/IteratorTests.vb @@ -2,12 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.Testing -Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.Iterator - Imports VerifyConvertToIterator = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of Microsoft.CodeAnalysis.Testing.EmptyDiagnosticAnalyzer, Microsoft.CodeAnalysis.VisualBasic.CodeFixes.Iterator.VisualBasicConvertToIteratorCodeFixProvider) Imports VerifyConvertToYield = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of Microsoft.CodeAnalysis.Testing.EmptyDiagnosticAnalyzer, Microsoft.CodeAnalysis.VisualBasic.CodeFixes.Iterator.VisualBasicChangeToYieldCodeFixProvider) diff --git a/src/Analyzers/VisualBasic/Tests/NewLines/ConsecutiveStatementPlacement/ConsecutiveStatementPlacementTests.vb b/src/Analyzers/VisualBasic/Tests/NewLines/ConsecutiveStatementPlacement/ConsecutiveStatementPlacementTests.vb index ef76ea226d9cf..5afad4002c235 100644 --- a/src/Analyzers/VisualBasic/Tests/NewLines/ConsecutiveStatementPlacement/ConsecutiveStatementPlacementTests.vb +++ b/src/Analyzers/VisualBasic/Tests/NewLines/ConsecutiveStatementPlacement/ConsecutiveStatementPlacementTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeStyle - Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of Microsoft.CodeAnalysis.VisualBasic.NewLines.ConsecutiveStatementPlacement.VisualBasicConsecutiveStatementPlacementDiagnosticAnalyzer, Microsoft.CodeAnalysis.NewLines.ConsecutiveStatementPlacement.ConsecutiveStatementPlacementCodeFixProvider) diff --git a/src/Analyzers/VisualBasic/Tests/QualifyMemberAccess/QualifyMemberAccessTests.vb b/src/Analyzers/VisualBasic/Tests/QualifyMemberAccess/QualifyMemberAccessTests.vb index 0c2fef590c574..5308984210d03 100644 --- a/src/Analyzers/VisualBasic/Tests/QualifyMemberAccess/QualifyMemberAccessTests.vb +++ b/src/Analyzers/VisualBasic/Tests/QualifyMemberAccess/QualifyMemberAccessTests.vb @@ -5,8 +5,8 @@ Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics +Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.QualifyMemberAccess Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.QualifyMemberAccess diff --git a/src/Analyzers/VisualBasic/Tests/RemoveUnnecessaryParentheses/RemoveUnnecessaryParenthesesTests.vb b/src/Analyzers/VisualBasic/Tests/RemoveUnnecessaryParentheses/RemoveUnnecessaryParenthesesTests.vb index 7e31e9e9bb5c2..5b7e600d503b9 100644 --- a/src/Analyzers/VisualBasic/Tests/RemoveUnnecessaryParentheses/RemoveUnnecessaryParenthesesTests.vb +++ b/src/Analyzers/VisualBasic/Tests/RemoveUnnecessaryParentheses/RemoveUnnecessaryParenthesesTests.vb @@ -4,7 +4,6 @@ Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryParentheses @@ -16,7 +15,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.RemoveUnnecessaryP ''' whose current option is set to something other than 'Ignore'. ''' - Partial Public Class RemoveUnnecessaryParenthesesTests + Partial Public NotInheritable Class RemoveUnnecessaryParenthesesTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest_NoEditor Private Shared ReadOnly CheckOverflow As CompilationOptions = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, checkOverflow:=True) @@ -652,7 +651,16 @@ end class" Assert.Equal("[1,2]", diagnostic.Properties.Item(WellKnownDiagnosticTags.Unnecessary)) End Using + End Function + + Public Async Function TestWithNullMemberAccess() As Task + Await TestMissingAsync( +"class C + sub M() + RoundTime($$(d.EndDate - d.StartDate)?.TotalMinutes / 60) + end sub +end class", New TestParameters(options:=RequireArithmeticBinaryParenthesesForClarity)) End Function End Class End Namespace diff --git a/src/Analyzers/VisualBasic/Tests/SimplifyLinqExpression/VisualBasicSimplifyLinqExpressionTests.vb b/src/Analyzers/VisualBasic/Tests/SimplifyLinqExpression/VisualBasicSimplifyLinqExpressionTests.vb index aee8a775f2dad..47127af6ceb2b 100644 --- a/src/Analyzers/VisualBasic/Tests/SimplifyLinqExpression/VisualBasicSimplifyLinqExpressionTests.vb +++ b/src/Analyzers/VisualBasic/Tests/SimplifyLinqExpression/VisualBasicSimplifyLinqExpressionTests.vb @@ -2,9 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions -Imports Microsoft.CodeAnalysis.SimplifyLinqExpression - Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of Microsoft.CodeAnalysis.VisualBasic.SimplifyLinqExpression.VisualBasicSimplifyLinqExpressionDiagnosticAnalyzer, Microsoft.CodeAnalysis.SimplifyLinqExpression.SimplifyLinqExpressionCodeFixProvider) diff --git a/src/Analyzers/VisualBasic/Tests/UseCoalesceExpression/UseCoalesceExpressionForIfNullStatementCheckTests.vb b/src/Analyzers/VisualBasic/Tests/UseCoalesceExpression/UseCoalesceExpressionForIfNullStatementCheckTests.vb index 61cc9e0559e24..b911b54e7268c 100644 --- a/src/Analyzers/VisualBasic/Tests/UseCoalesceExpression/UseCoalesceExpressionForIfNullStatementCheckTests.vb +++ b/src/Analyzers/VisualBasic/Tests/UseCoalesceExpression/UseCoalesceExpressionForIfNullStatementCheckTests.vb @@ -2,12 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics -Imports Microsoft.CodeAnalysis.UseCoalesceExpression -Imports Microsoft.CodeAnalysis.VisualBasic.UseCoalesceExpression - Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of Microsoft.CodeAnalysis.VisualBasic.UseCoalesceExpression.VisualBasicUseCoalesceExpressionForIfNullStatementCheckDiagnosticAnalyzer, Microsoft.CodeAnalysis.VisualBasic.UseCoalesceExpression.VisualBasicUseCoalesceExpressionForIfNullStatementCheckCodeFixProvider) diff --git a/src/Analyzers/VisualBasic/Tests/UseIsNullCheck/UseIsNullCheckForReferenceEqualsTests.vb b/src/Analyzers/VisualBasic/Tests/UseIsNullCheck/UseIsNullCheckForReferenceEqualsTests.vb index 8284fc1ac174c..428e76975edd8 100644 --- a/src/Analyzers/VisualBasic/Tests/UseIsNullCheck/UseIsNullCheckForReferenceEqualsTests.vb +++ b/src/Analyzers/VisualBasic/Tests/UseIsNullCheck/UseIsNullCheckForReferenceEqualsTests.vb @@ -3,9 +3,9 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.VisualBasic.UseIsNullCheck Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics +Imports Microsoft.CodeAnalysis.VisualBasic.UseIsNullCheck Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.UseIsNullCheck diff --git a/src/CodeStyle/Core/Analyzers/Microsoft.CodeAnalysis.CodeStyle.csproj b/src/CodeStyle/Core/Analyzers/Microsoft.CodeAnalysis.CodeStyle.csproj index 928ffeb9c512a..82c8908463820 100644 --- a/src/CodeStyle/Core/Analyzers/Microsoft.CodeAnalysis.CodeStyle.csproj +++ b/src/CodeStyle/Core/Analyzers/Microsoft.CodeAnalysis.CodeStyle.csproj @@ -35,9 +35,6 @@ - - - diff --git a/src/CodeStyle/Core/Analyzers/PublicAPI.Unshipped.txt b/src/CodeStyle/Core/Analyzers/PublicAPI.Unshipped.txt index 775a62fbdb05a..e69de29bb2d1d 100644 --- a/src/CodeStyle/Core/Analyzers/PublicAPI.Unshipped.txt +++ b/src/CodeStyle/Core/Analyzers/PublicAPI.Unshipped.txt @@ -1,100 +0,0 @@ -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.AddAccessor = 26 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Attribute = 22 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Class = 2 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.CompilationUnit = 1 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Constructor = 10 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.ConversionOperator = 9 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.CustomEvent = 17 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Delegate = 6 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Destructor = 11 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Enum = 5 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.EnumMember = 15 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Event = 16 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Field = 12 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.GetAccessor = 24 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Indexer = 14 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Interface = 4 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.LambdaExpression = 23 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Method = 7 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Namespace = 18 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.NamespaceImport = 19 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.None = 0 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Operator = 8 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Parameter = 20 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Property = 13 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.RaiseAccessor = 28 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.RecordClass = 29 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.RemoveAccessor = 27 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.SetAccessor = 25 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Struct = 3 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Variable = 21 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.DeclarationModifiers() -> void -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsAbstract.get -> bool -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsAsync.get -> bool -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsConst.get -> bool -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsExtern.get -> bool -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsNew.get -> bool -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsOverride.get -> bool -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsPartial.get -> bool -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsReadOnly.get -> bool -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsRef.get -> bool -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsRequired.get -> bool -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsFile.get -> bool -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsSealed.get -> bool -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsStatic.get -> bool -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsUnsafe.get -> bool -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsVirtual.get -> bool -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsVolatile.get -> bool -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsWithEvents.get -> bool -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsWriteOnly.get -> bool -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithAsync(bool isAsync) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsAbstract(bool isAbstract) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsConst(bool isConst) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsExtern(bool isExtern) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsNew(bool isNew) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsOverride(bool isOverride) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsReadOnly(bool isReadOnly) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsRef(bool isRef) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsRequired(bool isRequired) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsFile(bool isFile) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsSealed(bool isSealed) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsStatic(bool isStatic) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsUnsafe(bool isUnsafe) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsVirtual(bool isVirtual) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsVolatile(bool isVolatile) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsWriteOnly(bool isWriteOnly) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithPartial(bool isPartial) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithWithEvents(bool withEvents) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -override Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Equals(object obj) -> bool -override Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.GetHashCode() -> int -override Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.ToString() -> string -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Abstract.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Async.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Const.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Extern.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.From(Microsoft.CodeAnalysis.ISymbol symbol) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.New.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.None.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.operator !=(Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers right) -> bool -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.operator &(Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers right) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.operator +(Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers right) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.operator -(Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers right) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.operator ==(Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers right) -> bool -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.operator |(Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers right) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Override.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Partial.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.ReadOnly.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Ref.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Required.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.File.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Sealed.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Static.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.TryParse(string value, out Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers modifiers) -> bool -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Unsafe.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Virtual.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Volatile.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithEvents.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WriteOnly.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Equals(Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers other) -> bool diff --git a/src/CodeStyle/Core/CodeFixes/Host/Mef/CodeStyleHostLanguageServices.cs b/src/CodeStyle/Core/CodeFixes/Host/Mef/CodeStyleHostLanguageServices.cs index 340b67afd3947..75a5c586d5ffd 100644 --- a/src/CodeStyle/Core/CodeFixes/Host/Mef/CodeStyleHostLanguageServices.cs +++ b/src/CodeStyle/Core/CodeFixes/Host/Mef/CodeStyleHostLanguageServices.cs @@ -48,8 +48,8 @@ private static ImmutableArray CreateAssemblies(string languageName) break; } - return MefHostServices.DefaultAssemblies.Concat( - MefHostServicesHelpers.LoadNearbyAssemblies(assemblyNames.ToImmutableAndClear())); + return [.. MefHostServices.DefaultAssemblies, + .. MefHostServicesHelpers.LoadNearbyAssemblies(assemblyNames.ToImmutableAndClear())]; } IEnumerable> IMefHostExportProvider.GetExports() diff --git a/src/CodeStyle/Core/CodeFixes/LanguageServices/SemanticModelWorkspaceService/SemanticModelWorkspaceServiceFactory.SemanticModelWorkspaceService.cs b/src/CodeStyle/Core/CodeFixes/LanguageServices/SemanticModelWorkspaceService/SemanticModelWorkspaceServiceFactory.SemanticModelWorkspaceService.cs deleted file mode 100644 index 0c525bec56899..0000000000000 --- a/src/CodeStyle/Core/CodeFixes/LanguageServices/SemanticModelWorkspaceService/SemanticModelWorkspaceServiceFactory.SemanticModelWorkspaceService.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Threading; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis.Host.Mef; -using Microsoft.CodeAnalysis.Shared.Extensions; - -namespace Microsoft.CodeAnalysis.SemanticModelReuse; - -internal partial class SemanticModelReuseWorkspaceServiceFactory : IWorkspaceServiceFactory -{ - private sealed class SemanticModelReuseWorkspaceService : ISemanticModelReuseWorkspaceService - { - public SemanticModelReuseWorkspaceService(Workspace _) - { - } - - public ValueTask ReuseExistingSpeculativeModelAsync(Document document, SyntaxNode node, CancellationToken cancellationToken) - { - // TODO: port the GetSemanticModelForNodeAsync implementation from Workspaces layer, - // which currently relies on a bunch of internal APIs. - // For now, we fall back to the public API to fetch document's SemanticModel. - return document.GetRequiredSemanticModelAsync(cancellationToken); - } - } -} diff --git a/src/CodeStyle/VisualBasic/Analyzers/Microsoft.CodeAnalysis.VisualBasic.CodeStyle.vbproj b/src/CodeStyle/VisualBasic/Analyzers/Microsoft.CodeAnalysis.VisualBasic.CodeStyle.vbproj index cebd20e77c10b..c868e2860f921 100644 --- a/src/CodeStyle/VisualBasic/Analyzers/Microsoft.CodeAnalysis.VisualBasic.CodeStyle.vbproj +++ b/src/CodeStyle/VisualBasic/Analyzers/Microsoft.CodeAnalysis.VisualBasic.CodeStyle.vbproj @@ -10,31 +10,6 @@ true - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Compilers/.editorconfig b/src/Compilers/.editorconfig index 8882ce84e8ca5..05f8a377cac7d 100644 --- a/src/Compilers/.editorconfig +++ b/src/Compilers/.editorconfig @@ -12,6 +12,9 @@ dotnet_diagnostic.RS0100.severity = none # RS0102: Braces must not have blank lines between them dotnet_diagnostic.RS0102.severity = none +# IDE0051: Unused member +dotnet_diagnostic.IDE0051.severity = none + # IDE0170: Prefer extended property pattern dotnet_diagnostic.IDE0170.severity = suggestion diff --git a/src/Compilers/CSharp/Portable/Binder/Binder.CapturedParametersFinder.cs b/src/Compilers/CSharp/Portable/Binder/Binder.CapturedParametersFinder.cs index ed16cb85c3dab..58e9111966db4 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder.CapturedParametersFinder.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder.CapturedParametersFinder.cs @@ -165,7 +165,7 @@ protected override bool CheckAndClearLookupResult(Binder enclosingBinder, Identi Debug.Assert(lookupResult.SingleSymbolOrDefault == (object)parameter); // Check for left of potential color color member access - if (isTypeOrValueReceiver(enclosingBinder, id, parameter.Type, out SyntaxNode? memberAccessNode, out string? memberName, out int targetMemberArity, out bool invoked)) + if (IsTypeOrValueReceiver(enclosingBinder, id, parameter.Type, out SyntaxNode? memberAccessNode, out string? memberName, out int targetMemberArity, out bool invoked)) { lookupResult.Clear(); if (TreatAsInstanceMemberAccess(enclosingBinder, parameter.Type, memberAccessNode, memberName, targetMemberArity, invoked, lookupResult)) diff --git a/src/Compilers/CSharp/Portable/Binder/Binder.IdentifierUsedAsValueFinder.cs b/src/Compilers/CSharp/Portable/Binder/Binder.IdentifierUsedAsValueFinder.cs index e879cd4f2cf04..6d569e9449e3c 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder.IdentifierUsedAsValueFinder.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder.IdentifierUsedAsValueFinder.cs @@ -204,7 +204,7 @@ private bool CheckIdentifier(Binder enclosingBinder, IdentifierNameSyntax id) protected abstract bool CheckAndClearLookupResult(Binder enclosingBinder, IdentifierNameSyntax id, LookupResult lookupResult); - protected static bool isTypeOrValueReceiver( + protected static bool IsTypeOrValueReceiver( Binder enclosingBinder, IdentifierNameSyntax id, TypeSymbol type, @@ -278,7 +278,7 @@ protected static bool TreatAsInstanceMemberAccess( bool haveInstanceCandidates; lookupResult.Clear(); - enclosingBinder.CheckWhatCandidatesWeHave(members, type, memberName, targetMemberArity, + enclosingBinder.CheckWhatCandidatesWeHave(members, type, memberName, targetMemberArity, invoked, ref lookupResult, ref useSiteInfo, out haveInstanceCandidates, out _); @@ -286,7 +286,6 @@ protected static bool TreatAsInstanceMemberAccess( } else { - // methods are special because of extension methods. Debug.Assert(symbol.Kind != SymbolKind.Method); treatAsInstanceMemberAccess = !(symbol.IsStatic || symbol.Kind == SymbolKind.NamedType); } @@ -295,8 +294,17 @@ protected static bool TreatAsInstanceMemberAccess( } else { - // At this point this could only be an extension method access or an error - treatAsInstanceMemberAccess = true; + // At this point this could only be an extension member access or an error + bool haveInstanceCandidates; + lookupResult.Clear(); + var members = ArrayBuilder.GetInstance(); + + enclosingBinder.CheckWhatCandidatesWeHave(members, type, memberName, targetMemberArity, invoked, + ref lookupResult, ref useSiteInfo, + out haveInstanceCandidates, out _); + + members.Free(); + treatAsInstanceMemberAccess = haveInstanceCandidates; } lookupResult.Clear(); diff --git a/src/Compilers/CSharp/Portable/Binder/Binder.ValueChecks.cs b/src/Compilers/CSharp/Portable/Binder/Binder.ValueChecks.cs index c7bf068473af2..05292c47a0ac5 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder.ValueChecks.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder.ValueChecks.cs @@ -7,6 +7,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Linq; using Microsoft.CodeAnalysis.CSharp.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; @@ -93,7 +94,7 @@ internal MethodInfo ReplaceWithExtensionImplementation(out bool wasError) wasError = (Method is not null && method is null) || (SetMethod is not null && setMethod is null); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Test with indexers (ie. "method") and in compound assignment (ie. "setMethod") + // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Test in compound assignment (ie. "setMethod") return new MethodInfo(symbol, method, setMethod); static MethodSymbol? replace(MethodSymbol? method) @@ -3717,6 +3718,13 @@ internal SafeContext GetRefEscape(BoundExpression expr, SafeContext localScopeDe compoundMethod.HasUnsupportedMetadata || compoundMethod.RefKind == RefKind.None)); break; + + case BoundKind.IncrementOperator: + Debug.Assert(expr is BoundIncrementOperator incrementOperator && + (incrementOperator.MethodOpt is not { } incrementMethod || + incrementMethod.HasUnsupportedMetadata || + incrementMethod.RefKind == RefKind.None)); + break; } // At this point we should have covered all the possible cases for anything that is not a strict RValue. @@ -4088,6 +4096,13 @@ internal bool CheckRefEscape(SyntaxNode node, BoundExpression expr, SafeContext compoundMethod.RefKind == RefKind.None)); break; + case BoundKind.IncrementOperator: + Debug.Assert(expr is BoundIncrementOperator incrementOperator && + (incrementOperator.MethodOpt is not { } incrementMethod || + incrementMethod.HasUnsupportedMetadata || + incrementMethod.RefKind == RefKind.None)); + break; + case BoundKind.ThrowExpression: return true; } @@ -4487,7 +4502,32 @@ internal SafeContext GetValEscape(BoundExpression expr, SafeContext localScopeDe return GetValEscape(((BoundNullCoalescingAssignmentOperator)expr).RightOperand, localScopeDepth); case BoundKind.IncrementOperator: - return GetValEscape(((BoundIncrementOperator)expr).Operand, localScopeDepth); + var increment = (BoundIncrementOperator)expr; + if (increment.MethodOpt is { IsStatic: true } incrementMethod) + { + Debug.Assert(increment.OperatorKind.IsUserDefined()); + + var prefix = increment.OperatorKind.Operator() is UnaryOperatorKind.PrefixIncrement or UnaryOperatorKind.PrefixDecrement; + Debug.Assert(prefix || increment.OperatorKind.Operator() is UnaryOperatorKind.PostfixIncrement or UnaryOperatorKind.PostfixDecrement); + + // Prefix increment can be analyzed like the underlying method call since that's what it returns. + // Postfix increment is better analyzed as only the operand since that's what it returns. + if (prefix) + { + return GetInvocationEscapeScope( + MethodInfo.Create(incrementMethod), + receiver: null, + receiverIsSubjectToCloning: ThreeState.Unknown, + incrementMethod.Parameters, + argsOpt: [increment.Operand], + argRefKindsOpt: default, + argsToParamsOpt: default, + localScopeDepth: localScopeDepth, + isRefEscape: false); + } + } + + return GetValEscape(increment.Operand, localScopeDepth); case BoundKind.CompoundAssignmentOperator: var compound = (BoundCompoundAssignmentOperator)expr; @@ -5283,6 +5323,34 @@ internal bool CheckValEscape(SyntaxNode node, BoundExpression expr, SafeContext case BoundKind.IncrementOperator: var increment = (BoundIncrementOperator)expr; + if (increment.MethodOpt is { IsStatic: true } incrementMethod) + { + Debug.Assert(increment.OperatorKind.IsUserDefined()); + + var prefix = increment.OperatorKind.Operator() is UnaryOperatorKind.PrefixIncrement or UnaryOperatorKind.PrefixDecrement; + Debug.Assert(prefix || increment.OperatorKind.Operator() is UnaryOperatorKind.PostfixIncrement or UnaryOperatorKind.PostfixDecrement); + + // Prefix increment can be analyzed like the underlying method call since that's what it returns. + // Postfix increment is better analyzed as only the operand since that's what it returns. + if (prefix) + { + return CheckInvocationEscape( + increment.Syntax, + MethodInfo.Create(incrementMethod), + receiver: null, + receiverIsSubjectToCloning: ThreeState.Unknown, + incrementMethod.Parameters, + argsOpt: [increment.Operand], + argRefKindsOpt: default, + argsToParamsOpt: default, + checkingReceiver: checkingReceiver, + escapeFrom: escapeFrom, + escapeTo: escapeTo, + diagnostics, + isRefEscape: false); + } + } + return CheckValEscape(node, increment.Operand, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics); case BoundKind.CompoundAssignmentOperator: diff --git a/src/Compilers/CSharp/Portable/Binder/Binder.WithQueryLambdaParametersBinder.cs b/src/Compilers/CSharp/Portable/Binder/Binder.WithQueryLambdaParametersBinder.cs index e671be09cf790..e773ab539994a 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder.WithQueryLambdaParametersBinder.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder.WithQueryLambdaParametersBinder.cs @@ -96,7 +96,7 @@ private BoundExpression SelectField(SimpleNameSyntax node, BoundExpression recei LookupMembersWithFallback(lookupResult, receiver.Type, name, 0, ref useSiteInfo, basesBeingResolved: null, options: options); diagnostics.Add(node, useSiteInfo); - var result = BindMemberOfType(node, node, name, 0, indexed: false, receiver, default(SeparatedSyntaxList), default(ImmutableArray), lookupResult, BoundMethodGroupFlags.None, diagnostics); + var result = BindMemberOfType(node, node, name, 0, invoked: false, indexed: false, receiver, default(SeparatedSyntaxList), default(ImmutableArray), lookupResult, BoundMethodGroupFlags.None, diagnostics); lookupResult.Free(); return result; } diff --git a/src/Compilers/CSharp/Portable/Binder/Binder.cs b/src/Compilers/CSharp/Portable/Binder/Binder.cs index 4411b2b1e45ea..45b90a0e710ed 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder.cs @@ -749,6 +749,19 @@ internal static void ReportDiagnosticsIfObsoleteInternal(BindingDiagnosticBag di } } + internal static bool IsDisallowedExtensionInOlderLangVer(MethodSymbol symbol) + { + return symbol.GetIsNewExtensionMember() && (symbol.IsStatic || symbol.MethodKind != MethodKind.Ordinary); + } + + internal static void ReportDiagnosticsIfDisallowedExtension(BindingDiagnosticBag diagnostics, MethodSymbol method, SyntaxNode syntax) + { + if (IsDisallowedExtensionInOlderLangVer(method)) + { + MessageID.IDS_FeatureExtensions.CheckFeatureAvailability(diagnostics, syntax); + } + } + internal static void ReportDiagnosticsIfUnmanagedCallersOnly(BindingDiagnosticBag diagnostics, MethodSymbol symbol, SyntaxNodeOrToken syntax, bool isDelegateConversion) { var unmanagedCallersOnlyAttributeData = symbol.GetUnmanagedCallersOnlyAttributeData(forceComplete: false); diff --git a/src/Compilers/CSharp/Portable/Binder/Binder_Constraints.cs b/src/Compilers/CSharp/Portable/Binder/Binder_Constraints.cs index 919492dbcd291..447fb63515e40 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder_Constraints.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder_Constraints.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/Binder/Binder_Conversions.cs b/src/Compilers/CSharp/Portable/Binder/Binder_Conversions.cs index 3cb962361b12a..70bd7b97240b5 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder_Conversions.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder_Conversions.cs @@ -1069,6 +1069,7 @@ private bool HasCollectionInitializerTypeInProgress(SyntaxNode syntax, TypeSymbo ReportDiagnosticsIfObsolete(diagnostics, collectionBuilderMethod.ContainingType, syntax, hasBaseReceiver: false); ReportDiagnosticsIfObsolete(diagnostics, collectionBuilderMethod, syntax, hasBaseReceiver: false); ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, collectionBuilderMethod, syntax, isDelegateConversion: false); + Debug.Assert(!collectionBuilderMethod.GetIsNewExtensionMember()); return collectionBuilderMethod; } @@ -1430,11 +1431,14 @@ static bool bindMethodGroupInvocation( { addMethodBinder.ReportDiagnosticsIfObsolete(diagnostics, addMethods[0], syntax, hasBaseReceiver: false); ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, addMethods[0], syntax, isDelegateConversion: false); + Debug.Assert(!IsDisallowedExtensionInOlderLangVer(addMethods[0])); } } } else { + Debug.Assert(!resolution.OverloadResolutionResult.Succeeded); + result = bindInvocationExpressionContinued( addMethodBinder, syntax, expression, resolution.OverloadResolutionResult, resolution.AnalyzedArguments, resolution.MethodGroup, diagnostics: diagnostics, out var addMethod); @@ -1467,7 +1471,7 @@ static ImmutableArray filterOutBadGenericMethods( if (!typeParameters.IsEmpty) { - if (resolution.IsExtensionMethodGroup) // Tracked by https://github.com/dotnet/roslyn/issues/76130 : we need to handle new extension methods + if (resolution.IsExtensionMethodGroup) // Tracked by https://github.com/dotnet/roslyn/issues/78960 : we need to handle new extension methods { // We need to validate an ability to infer type arguments as well as check conversion to 'this' parameter. // Overload resolution doesn't check the conversion when 'this' type refers to a type parameter @@ -1518,7 +1522,7 @@ static ImmutableArray filterOutBadGenericMethods( parameterTypes, parameterRefKinds, ImmutableArray.Create(methodGroup.ReceiverOpt, new BoundValuePlaceholder(syntax, secondArgumentType) { WasCompilerGenerated = true }), - ref useSiteInfo); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : we may need to override ordinals here + ref useSiteInfo); // Tracked by https://github.com/dotnet/roslyn/issues/78960 : we may need to override ordinals here if (!inferenceResult.Success) { @@ -1601,7 +1605,7 @@ static bool bindInvocationExpressionContinued( var methodResult = result.ValidResult; var method = methodResult.Member; - // Tracked by https://github.com/dotnet/roslyn/issues/76130: It looks like we added a bunch of code in BindInvocationExpressionContinued at this position + // Tracked by https://github.com/dotnet/roslyn/issues/78960: It looks like we added a bunch of code in BindInvocationExpressionContinued at this position // that specifically deals with new extension methods. It adjusts analyzedArguments, etc. // It is very likely we need to do the same here. @@ -1622,6 +1626,7 @@ static bool bindInvocationExpressionContinued( addMethodBinder.ReportDiagnosticsIfObsolete(diagnostics, method, node, hasBaseReceiver: false); ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, method, node, isDelegateConversion: false); + ReportDiagnosticsIfDisallowedExtension(diagnostics, method, node); // No use site errors, but there could be use site warnings. // If there are any use site warnings, they have already been reported by overload resolution. @@ -1663,7 +1668,7 @@ internal static BoundExpression GetUnderlyingCollectionExpressionElement(BoundCo // Add methods. This case can be hit for spreads and non-spread elements. Debug.Assert(call.HasErrors); Debug.Assert(call.Method.Name == "Add"); - return call.Arguments[call.InvokedAsExtensionMethod ? 1 : 0]; // Tracked by https://github.com/dotnet/roslyn/issues/76130: Add test coverage for new extensions + return call.Arguments[call.InvokedAsExtensionMethod ? 1 : 0]; // Tracked by https://github.com/dotnet/roslyn/issues/78960: Add test coverage for new extensions case BoundBadExpression badExpression: Debug.Assert(false); // Add test if we hit this assert. return badExpression; @@ -1712,7 +1717,7 @@ internal bool TryGetCollectionIterationType(SyntaxNode syntax, TypeSymbol collec out iterationType, builder: out var builder); // Collection expression target types require instance method GetEnumerator. - if (result && builder.ViaExtensionMethod) // Tracked by https://github.com/dotnet/roslyn/issues/76130: Add test coverage for new extensions + if (result && builder.ViaExtensionMethod) // Tracked by https://github.com/dotnet/roslyn/issues/78960: Add test coverage for new extensions { iterationType = default; return false; @@ -3051,6 +3056,7 @@ private bool MethodGroupConversionHasErrors( ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, selectedMethod, syntax, isDelegateConversion: true); } ReportDiagnosticsIfObsolete(diagnostics, selectedMethod, syntax, hasBaseReceiver: false); + ReportDiagnosticsIfDisallowedExtension(diagnostics, selectedMethod, syntax); // No use site errors, but there could be use site warnings. // If there are use site warnings, they were reported during the overload resolution process diff --git a/src/Compilers/CSharp/Portable/Binder/Binder_Crefs.cs b/src/Compilers/CSharp/Portable/Binder/Binder_Crefs.cs index 8758bf909e6f3..bc1173c91df88 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder_Crefs.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder_Crefs.cs @@ -222,7 +222,6 @@ private ImmutableArray BindIndexerMemberCref(IndexerMemberCrefSyntax syn private ImmutableArray BindExtensionMemberCref(ExtensionMemberCrefSyntax syntax, NamespaceOrTypeSymbol? containerOpt, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : handle extension operators CheckFeatureAvailability(syntax, MessageID.IDS_FeatureExtensions, diagnostics); if (containerOpt is not NamedTypeSymbol namedContainer) @@ -231,22 +230,34 @@ private ImmutableArray BindExtensionMemberCref(ExtensionMemberCrefSyntax return ImmutableArray.Empty; } - ImmutableArray sortedSymbols = default; int arity = 0; TypeArgumentListSyntax? typeArgumentListSyntax = null; CrefParameterListSyntax? parameters = null; + string? memberName = null; if (syntax.Member is NameMemberCrefSyntax { Name: SimpleNameSyntax simpleName } nameMember) { arity = simpleName.Arity; typeArgumentListSyntax = simpleName is GenericNameSyntax genericName ? genericName.TypeArgumentList : null; parameters = nameMember.Parameters; + memberName = simpleName.Identifier.ValueText; + } + else if (syntax.Member is OperatorMemberCrefSyntax operatorSyntax) + { + memberName = GetOperatorMethodName(operatorSyntax); + parameters = operatorSyntax.Parameters; + } - TypeArgumentListSyntax? extensionTypeArguments = syntax.TypeArgumentList; - int extensionArity = extensionTypeArguments?.Arguments.Count ?? 0; - sortedSymbols = computeSortedAndFilteredCrefExtensionMembers(namedContainer, simpleName.Identifier.ValueText, extensionArity, arity, extensionTypeArguments, diagnostics, syntax); + if (memberName == null) + { + ambiguityWinner = null; + return ImmutableArray.Empty; } + TypeArgumentListSyntax? extensionTypeArguments = syntax.TypeArgumentList; + int extensionArity = extensionTypeArguments?.Arguments.Count ?? 0; + ImmutableArray sortedSymbols = computeSortedAndFilteredCrefExtensionMembers(namedContainer, memberName, extensionArity, arity, extensionTypeArguments, diagnostics, syntax); + if (sortedSymbols.IsDefaultOrEmpty) { ambiguityWinner = null; @@ -362,7 +373,34 @@ private ImmutableArray BindOperatorMemberCref(OperatorMemberCrefSyntax s { const int arity = 0; - CrefParameterListSyntax? parameterListSyntax = syntax.Parameters; + string? memberName = GetOperatorMethodName(syntax); + + if (memberName == null) + { + ambiguityWinner = null; + return ImmutableArray.Empty; + } + + ImmutableArray sortedSymbols = ComputeSortedCrefMembers(syntax, containerOpt, memberName, memberNameText: memberName, arity, syntax.Parameters != null, diagnostics); + + if (sortedSymbols.IsEmpty) + { + ambiguityWinner = null; + return ImmutableArray.Empty; + } + + return ProcessCrefMemberLookupResults( + sortedSymbols, + arity, + syntax, + typeArgumentListSyntax: null, + parameterListSyntax: syntax.Parameters, + ambiguityWinner: out ambiguityWinner, + diagnostics: diagnostics); + } + + private static string? GetOperatorMethodName(OperatorMemberCrefSyntax syntax) + { bool isChecked = syntax.CheckedKeyword.IsKind(SyntaxKind.CheckedKeyword); SyntaxKind operatorTokenKind = syntax.OperatorToken.Kind(); @@ -374,6 +412,8 @@ private ImmutableArray BindOperatorMemberCref(OperatorMemberCrefSyntax s } else { + CrefParameterListSyntax? parameterListSyntax = syntax.Parameters; + // NOTE: Prefer binary to unary, unless there is exactly one parameter. // CONSIDER: we're following dev11 by never using a binary operator name if there's // exactly one parameter, but doing so would allow us to match single-parameter constructors. @@ -394,29 +434,13 @@ private ImmutableArray BindOperatorMemberCref(OperatorMemberCrefSyntax s } } - if (memberName == null || + if (memberName != null && (isChecked && !syntax.OperatorToken.IsMissing && !SyntaxFacts.IsCheckedOperator(memberName))) // the operator cannot be checked { - ambiguityWinner = null; - return ImmutableArray.Empty; + memberName = null; } - ImmutableArray sortedSymbols = ComputeSortedCrefMembers(syntax, containerOpt, memberName, memberNameText: memberName, arity, syntax.Parameters != null, diagnostics); - - if (sortedSymbols.IsEmpty) - { - ambiguityWinner = null; - return ImmutableArray.Empty; - } - - return ProcessCrefMemberLookupResults( - sortedSymbols, - arity, - syntax, - typeArgumentListSyntax: null, - parameterListSyntax: parameterListSyntax, - ambiguityWinner: out ambiguityWinner, - diagnostics: diagnostics); + return memberName; } // NOTE: not guaranteed to be a method (e.g. class op_Implicit) diff --git a/src/Compilers/CSharp/Portable/Binder/Binder_Expressions.cs b/src/Compilers/CSharp/Portable/Binder/Binder_Expressions.cs index 301cbb675dc7c..571b91b1fb10b 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder_Expressions.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder_Expressions.cs @@ -1646,6 +1646,8 @@ private BoundExpression BindIdentifier( Debug.Assert(members.Count > 0); var receiver = SynthesizeMethodGroupReceiver(node, members); + Debug.Assert(GetValueExpressionIfTypeOrValueReceiver(receiver) is null); + expression = ConstructBoundMemberGroupAndReportOmittedTypeArguments( node, typeArgumentList, @@ -7894,7 +7896,7 @@ BoundExpression tryBindMemberAccessWithBoundTypeLeft( if (lookupResult.IsMultiViable) { CheckFeatureAvailability(boundLeft.Syntax, MessageID.IDS_FeatureStaticAbstractMembersInInterfaces, diagnostics); - return BindMemberOfType(node, right, rightName, rightArity, indexed, boundLeft, typeArgumentsSyntax, typeArguments, lookupResult, BoundMethodGroupFlags.None, diagnostics: diagnostics); + return BindMemberOfType(node, right, rightName, rightArity, invoked, indexed, boundLeft, typeArgumentsSyntax, typeArguments, lookupResult, BoundMethodGroupFlags.None, diagnostics: diagnostics); } else if (lookupResult.IsClear) { @@ -7915,7 +7917,7 @@ BoundExpression tryBindMemberAccessWithBoundTypeLeft( if (lookupResult.IsMultiViable) { - return BindMemberOfType(node, right, rightName, rightArity, indexed, boundLeft, typeArgumentsSyntax, typeArguments, lookupResult, BoundMethodGroupFlags.SearchExtensions, diagnostics: diagnostics); + return BindMemberOfType(node, right, rightName, rightArity, invoked, indexed, boundLeft, typeArgumentsSyntax, typeArguments, lookupResult, BoundMethodGroupFlags.SearchExtensions, diagnostics: diagnostics); } if (!invoked) @@ -8030,6 +8032,7 @@ private BoundExpression MakeMemberAccessValue(BoundExpression expr, BindingDiagn private BoundExpression GetExtensionMemberAccess(SyntaxNode syntax, BoundExpression? receiver, Symbol extensionMember, BindingDiagnosticBag diagnostics) { + MessageID.IDS_FeatureExtensions.CheckFeatureAvailability(diagnostics, syntax); receiver = ReplaceTypeOrValueReceiver(receiver, useType: extensionMember.IsStatic, diagnostics); switch (extensionMember) @@ -8045,7 +8048,7 @@ private BoundExpression GetExtensionMemberAccess(SyntaxNode syntax, BoundExpress return BindPropertyAccess(syntax, receiver, propertySymbol, diagnostics, LookupResultKind.Viable, hasErrors: false); case ExtendedErrorTypeSymbol errorTypeSymbol: - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : we should likely reduce (ie. do type inference and substitute) the candidates (like ToBadExpression) + // Tracked by https://github.com/dotnet/roslyn/issues/78957 : public API, we should likely reduce (ie. do type inference and substitute) the candidates (like ToBadExpression) return new BoundBadExpression(syntax, LookupResultKind.Viable, errorTypeSymbol.CandidateSymbols!, [receiver], CreateErrorType()); default: @@ -8096,17 +8099,14 @@ private BoundExpression BindInstanceMemberAccess( if (lookupResult.IsMultiViable) { - return BindMemberOfType(node, right, rightName, rightArity, indexed, boundLeft, typeArgumentsSyntax, typeArgumentsWithAnnotations, lookupResult, flags, diagnostics); + return BindMemberOfType(node, right, rightName, rightArity, invoked, indexed, boundLeft, typeArgumentsSyntax, typeArgumentsWithAnnotations, lookupResult, flags, diagnostics); } if (searchExtensionsIfNecessary) { - BoundExpression colorColorValueReceiver = GetValueExpressionIfTypeOrValueReceiver(boundLeft); - - if (IsPossiblyCapturingPrimaryConstructorParameterReference(colorColorValueReceiver, out _)) - { - boundLeft = ReplaceTypeOrValueReceiver(boundLeft, useType: false, diagnostics); - } + var members = ArrayBuilder.GetInstance(); + boundLeft = CheckAmbiguousPrimaryConstructorParameterAsColorColorReceiver(boundLeft, right, rightName, typeArgumentsWithAnnotations, invoked, members, diagnostics); + members.Free(); if (!invoked) { @@ -8337,12 +8337,14 @@ private TypeSymbol GetNonMethodMemberType(Symbol symbolOpt) return resultType ?? CreateErrorType(); } +#nullable enable + /// /// Combine the receiver and arguments of an extension method /// invocation into a single argument list to allow overload resolution /// to treat the invocation as a static method invocation with no receiver. /// - private static void CombineExtensionMethodArguments(BoundExpression receiver, AnalyzedArguments originalArguments, AnalyzedArguments extensionMethodArguments) + private static void CombineExtensionMethodArguments(BoundExpression receiver, AnalyzedArguments? originalArguments, AnalyzedArguments extensionMethodArguments) { Debug.Assert(receiver != null); Debug.Assert(extensionMethodArguments.Arguments.Count == 0); @@ -8351,21 +8353,27 @@ private static void CombineExtensionMethodArguments(BoundExpression receiver, An extensionMethodArguments.IncludesReceiverAsArgument = true; extensionMethodArguments.Arguments.Add(receiver); - extensionMethodArguments.Arguments.AddRange(originalArguments.Arguments); - if (originalArguments.Names.Count > 0) + if (originalArguments is not null) + { + extensionMethodArguments.Arguments.AddRange(originalArguments.Arguments); + } + + if (originalArguments?.Names.Count > 0) { extensionMethodArguments.Names.Add(null); extensionMethodArguments.Names.AddRange(originalArguments.Names); } - if (originalArguments.RefKinds.Count > 0) + if (originalArguments?.RefKinds.Count > 0) { extensionMethodArguments.RefKinds.Add(RefKind.None); extensionMethodArguments.RefKinds.AddRange(originalArguments.RefKinds); } } +#nullable disable + private static void InitializeExtensionPropertyArguments(BoundExpression receiver, AnalyzedArguments extensionPropertyArguments) { Debug.Assert(receiver != null); @@ -8385,6 +8393,7 @@ private BoundExpression BindMemberOfType( SyntaxNode right, string plainName, int arity, + bool invoked, bool indexed, BoundExpression left, SeparatedSyntaxList typeArgumentsSyntax, @@ -8416,6 +8425,8 @@ private BoundExpression BindMemberOfType( // the receiver of the method group, even though the spec notes that there is // no associated instance expression.) + left = CheckAmbiguousPrimaryConstructorParameterAsColorColorReceiver(left, right, plainName, typeArgumentsWithAnnotations, invoked, members, diagnostics); + result = ConstructBoundMemberGroupAndReportOmittedTypeArguments( node, typeArgumentsSyntax, @@ -8430,7 +8441,6 @@ private BoundExpression BindMemberOfType( } else { - // methods are special because of extension methods. Debug.Assert(symbol.Kind != SymbolKind.Method); left = ReplaceTypeOrValueReceiver(left, symbol.IsStatic || symbol.Kind == SymbolKind.NamedType, diagnostics); diff --git a/src/Compilers/CSharp/Portable/Binder/Binder_InterpolatedString.cs b/src/Compilers/CSharp/Portable/Binder/Binder_InterpolatedString.cs index fb21a3e6ba53a..43b9267700cc7 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder_InterpolatedString.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder_InterpolatedString.cs @@ -339,7 +339,7 @@ private BoundInterpolatedString BindUnconvertedInterpolatedExpressionToFactory( SyntaxNode syntax = unconvertedSource.Syntax; ImmutableArray expressions = makeInterpolatedStringFactoryArguments(syntax, parts, diagnostics); - BoundExpression construction = MakeInvocationExpression( // Tracked by https://github.com/dotnet/roslyn/issues/76130 : test this scenario with a delegate-returning property (should be blocked by virtue of allowFieldsAndProperties: false) + BoundExpression construction = MakeInvocationExpression( // Tracked by https://github.com/dotnet/roslyn/issues/78965 : interpolated string, test this scenario with a delegate-returning property (should be blocked by virtue of allowFieldsAndProperties: false) syntax, new BoundTypeExpression(syntax, null, factoryType) { WasCompilerGenerated = true }, factoryMethod, diff --git a/src/Compilers/CSharp/Portable/Binder/Binder_Invocation.cs b/src/Compilers/CSharp/Portable/Binder/Binder_Invocation.cs index 41b580dc6a935..b98aea751c268 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder_Invocation.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder_Invocation.cs @@ -1325,6 +1325,7 @@ private BoundCall BindInvocationExpressionContinued( ReportDiagnosticsIfObsolete(diagnostics, method, node, hasBaseReceiver); ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, method, node, isDelegateConversion: false); + ReportDiagnosticsIfDisallowedExtension(diagnostics, method, node); // No use site errors, but there could be use site warnings. // If there are any use site warnings, they have already been reported by overload resolution. @@ -2305,21 +2306,29 @@ private BoundExpression BindNameofOperatorInternal(InvocationExpressionSyntax no var boundArgument = BindExpression(argument, diagnostics); bool syntaxIsOk = CheckSyntaxForNameofArgument(argument, out string name, boundArgument.HasAnyErrors ? BindingDiagnosticBag.Discarded : diagnostics); - if (!boundArgument.HasAnyErrors && syntaxIsOk && boundArgument.Kind == BoundKind.MethodGroup) + if (boundArgument is BoundMethodGroup methodGroup) { - var methodGroup = (BoundMethodGroup)boundArgument; - if (!methodGroup.TypeArgumentsOpt.IsDefaultOrEmpty) + if (!boundArgument.HasAnyErrors && syntaxIsOk) { - // method group with type parameters not allowed - diagnostics.Add(ErrorCode.ERR_NameofMethodGroupWithTypeParameters, argument.Location); + if (!methodGroup.TypeArgumentsOpt.IsDefaultOrEmpty) + { + // method group with type parameters not allowed + diagnostics.Add(ErrorCode.ERR_NameofMethodGroupWithTypeParameters, argument.Location); + } + else + { + EnsureNameofExpressionSymbols(methodGroup, diagnostics); + } } - else + } + else if (boundArgument is BoundPropertyAccess propertyAccess) + { + if (propertyAccess.PropertySymbol.GetIsNewExtensionMember()) { - EnsureNameofExpressionSymbols(methodGroup, diagnostics); + diagnostics.Add(ErrorCode.ERR_NameofExtensionMember, boundArgument.Syntax); } } - - if (boundArgument is BoundNamespaceExpression nsExpr) + else if (boundArgument is BoundNamespaceExpression nsExpr) { diagnostics.AddAssembliesUsedByNamespaceReference(nsExpr.NamespaceSymbol); } diff --git a/src/Compilers/CSharp/Portable/Binder/Binder_Lookup.cs b/src/Compilers/CSharp/Portable/Binder/Binder_Lookup.cs index d5ac10f288222..e85e16ee1e047 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder_Lookup.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder_Lookup.cs @@ -202,37 +202,34 @@ internal void EnumerateAllExtensionMembersInSingleBinder(ArrayBuilder? implementationsToShadow = null; // 1. Collect new extension members - if (this.Compilation.LanguageVersion.AllowNewExtensions()) - { - var extensionDeclarations = ArrayBuilder.GetInstance(); - this.GetExtensionDeclarations(extensionDeclarations, originalBinder); + var extensionDeclarations = ArrayBuilder.GetInstance(); + this.GetExtensionDeclarations(extensionDeclarations, originalBinder); - foreach (NamedTypeSymbol extensionDeclaration in extensionDeclarations) + foreach (NamedTypeSymbol extensionDeclaration in extensionDeclarations) + { + if (extensionDeclaration.ExtensionParameter is null) { - if (extensionDeclaration.ExtensionParameter is null) - { - continue; - } + continue; + } - var candidates = name is null ? extensionDeclaration.GetMembers() : extensionDeclaration.GetMembers(name); + var candidates = name is null ? extensionDeclaration.GetMembers() : extensionDeclaration.GetMembers(name); - foreach (var candidate in candidates) - { - SingleLookupResult resultOfThisMember = originalBinder.CheckViability(candidate, arity, options, null, diagnose: true, useSiteInfo: ref useSiteInfo); - result.Add(resultOfThisMember); + foreach (var candidate in candidates) + { + SingleLookupResult resultOfThisMember = originalBinder.CheckViability(candidate, arity, options, null, diagnose: true, useSiteInfo: ref useSiteInfo); + result.Add(resultOfThisMember); - if (candidate is MethodSymbol { IsStatic: false } shadows && - shadows.OriginalDefinition.TryGetCorrespondingExtensionImplementationMethod() is { } toShadow) - { - implementationsToShadow ??= PooledHashSet.GetInstance(); - implementationsToShadow.Add(toShadow); - } + if (candidate is MethodSymbol { IsStatic: false } shadows && + shadows.OriginalDefinition.TryGetCorrespondingExtensionImplementationMethod() is { } toShadow) + { + implementationsToShadow ??= PooledHashSet.GetInstance(); + implementationsToShadow.Add(toShadow); } } - - extensionDeclarations.Free(); } + extensionDeclarations.Free(); + // 2. Collect classic extension methods var extensionMethods = ArrayBuilder.GetInstance(); this.GetCandidateExtensionMethods(extensionMethods, name, arity, options, originalBinder: originalBinder); diff --git a/src/Compilers/CSharp/Portable/Binder/Binder_Operators.cs b/src/Compilers/CSharp/Portable/Binder/Binder_Operators.cs index 1e81912b14d95..c6adf9256d58e 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder_Operators.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder_Operators.cs @@ -114,11 +114,26 @@ private BoundExpression BindCompoundAssignment(AssignmentExpressionSyntax node, leftPlaceholder: null, leftConversion: null, finalPlaceholder: null, finalConversion: null, LookupResultKind.NotAVariable, CreateErrorType(), hasErrors: true); } + if (!IsTypelessExpressionAllowedInBinaryOperator(kind, left, right)) + { + return createBadCompoundAssignmentOperator(node, kind, left, right, LookupResultKind.OverloadResolutionFailure, default(ImmutableArray), diagnostics); + } + + bool checkOverflowAtRuntime = CheckOverflowAtRuntime; + // Try an in-place user-defined operator - BoundCompoundAssignmentOperator? inPlaceResult = tryApplyUserDefinedInstanceOperator(node, node.OperatorToken, kind, left, right, diagnostics); - if (inPlaceResult is not null) + bool tryInstance = shouldTryUserDefinedInstanceOperator(node, checkOverflowAtRuntime, left, out string? checkedInstanceOperatorName, out string? ordinaryInstanceOperatorName); + + if (tryInstance) { - return inPlaceResult; + Debug.Assert(ordinaryInstanceOperatorName is not null); + + BoundCompoundAssignmentOperator? inPlaceResult = tryApplyUserDefinedInstanceOperator(node, kind, checkOverflowAtRuntime, checkedInstanceOperatorName, ordinaryInstanceOperatorName, + left, right, diagnostics); + if (inPlaceResult is not null) + { + return inPlaceResult; + } } // A compound operator, say, x |= y, is bound as x = (X)( ((T)x) | ((T)y) ). We must determine @@ -132,14 +147,52 @@ private BoundExpression BindCompoundAssignment(AssignmentExpressionSyntax node, LookupResultKind resultKind; ImmutableArray originalUserDefinedOperators; - BinaryOperatorAnalysisResult best = this.BinaryOperatorOverloadResolution(kind, isChecked: CheckOverflowAtRuntime, left, right, node, diagnostics, out resultKind, out originalUserDefinedOperators); + + OverloadResolution.GetStaticUserDefinedBinaryOperatorMethodNames(kind, checkOverflowAtRuntime, out string staticOperatorName1, out string? staticOperatorName2Opt); + BinaryOperatorAnalysisResult best = BinaryOperatorNonExtensionOverloadResolution(kind, isChecked: checkOverflowAtRuntime, staticOperatorName1, staticOperatorName2Opt, left, right, node, diagnostics, out resultKind, out originalUserDefinedOperators); + + Debug.Assert(resultKind is LookupResultKind.Viable or LookupResultKind.Ambiguous or LookupResultKind.OverloadResolutionFailure or LookupResultKind.Empty); + Debug.Assert(best.HasValue == (resultKind is LookupResultKind.Viable)); + Debug.Assert(resultKind is not (LookupResultKind.OverloadResolutionFailure or LookupResultKind.Empty) || originalUserDefinedOperators.IsEmpty); + + if (!best.HasValue && resultKind != LookupResultKind.Ambiguous) + { + Debug.Assert(resultKind is LookupResultKind.OverloadResolutionFailure or LookupResultKind.Empty); + Debug.Assert(originalUserDefinedOperators.IsEmpty); + + LookupResultKind staticExtensionResultKind; + ImmutableArray staticExtensionOriginalUserDefinedOperators; + BinaryOperatorAnalysisResult? staticExtensionBest; + BoundCompoundAssignmentOperator? instanceExtensionResult = tryApplyUserDefinedExtensionOperator( + node, kind, tryInstance, checkOverflowAtRuntime, + staticOperatorName1, staticOperatorName2Opt, + checkedInstanceOperatorName, ordinaryInstanceOperatorName, + left, right, diagnostics, + out staticExtensionBest, out staticExtensionResultKind, out staticExtensionOriginalUserDefinedOperators); + + if (instanceExtensionResult is not null) + { + Debug.Assert(instanceExtensionResult.ResultKind is LookupResultKind.Viable || !instanceExtensionResult.OriginalUserDefinedOperatorsOpt.IsDefaultOrEmpty); + return instanceExtensionResult; + } + + if (staticExtensionBest.HasValue) + { + best = staticExtensionBest.GetValueOrDefault(); + resultKind = staticExtensionResultKind; + originalUserDefinedOperators = staticExtensionOriginalUserDefinedOperators; + } + } + if (!best.HasValue) { - ReportAssignmentOperatorError(node, kind, diagnostics, left, right, resultKind); - left = BindToTypeForErrorRecovery(left); - right = BindToTypeForErrorRecovery(right); - return new BoundCompoundAssignmentOperator(node, BinaryOperatorSignature.Error, left, right, - leftPlaceholder: null, leftConversion: null, finalPlaceholder: null, finalConversion: null, resultKind, originalUserDefinedOperators, CreateErrorType(), hasErrors: true); + return createBadCompoundAssignmentOperator(node, kind, left, right, resultKind, originalUserDefinedOperators, diagnostics); + } + + if (best.Signature.Method is { } bestMethod) + { + ReportObsoleteAndFeatureAvailabilityDiagnostics(bestMethod, node, diagnostics); + ReportUseSite(bestMethod, diagnostics, node); } // The rules in the spec for determining additional errors are bit confusing. In particular @@ -191,10 +244,10 @@ private BoundExpression BindCompoundAssignment(AssignmentExpressionSyntax node, CheckConstraintLanguageVersionAndRuntimeSupportForOperator(node, bestSignature.Method, isUnsignedRightShift: bestSignature.Kind.Operator() == BinaryOperatorKind.UnsignedRightShift, bestSignature.ConstrainedToTypeOpt, diagnostics); - if (CheckOverflowAtRuntime) + if (checkOverflowAtRuntime) { bestSignature = new BinaryOperatorSignature( - bestSignature.Kind.WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), + bestSignature.Kind.WithOverflowChecksIfApplicable(checkOverflowAtRuntime), bestSignature.LeftType, bestSignature.RightType, bestSignature.ReturnType, @@ -233,7 +286,7 @@ private BoundExpression BindCompoundAssignment(AssignmentExpressionSyntax node, isPredefinedOperator && !kind.IsShift()) { - Conversion rightToLeftConversion = this.Conversions.ClassifyConversionFromExpression(right, leftType, isChecked: CheckOverflowAtRuntime, ref useSiteInfo); + Conversion rightToLeftConversion = this.Conversions.ClassifyConversionFromExpression(right, leftType, isChecked: checkOverflowAtRuntime, ref useSiteInfo); if (!rightToLeftConversion.IsImplicit || !rightToLeftConversion.IsValid) { hasError = true; @@ -243,7 +296,7 @@ private BoundExpression BindCompoundAssignment(AssignmentExpressionSyntax node, diagnostics.Add(node, useSiteInfo); - if (!hasError && leftType.IsVoidPointer()) + if (!hasError && !bestSignature.Kind.IsUserDefined() && leftType.IsVoidPointer()) { Error(diagnostics, ErrorCode.ERR_VoidError, node); hasError = true; @@ -259,58 +312,140 @@ private BoundExpression BindCompoundAssignment(AssignmentExpressionSyntax node, return new BoundCompoundAssignmentOperator(node, bestSignature, left, rightConverted, leftPlaceholder, leftConversion, finalPlaceholder, finalConversion, resultKind, originalUserDefinedOperators, leftType, hasError); - BoundCompoundAssignmentOperator? tryApplyUserDefinedInstanceOperator(ExpressionSyntax node, SyntaxToken operatorToken, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, BindingDiagnosticBag diagnostics) + BoundCompoundAssignmentOperator createBadCompoundAssignmentOperator( + AssignmentExpressionSyntax node, + BinaryOperatorKind kind, + BoundExpression left, + BoundExpression right, + LookupResultKind resultKind, + ImmutableArray originalUserDefinedOperators, + BindingDiagnosticBag diagnostics) + { + ReportAssignmentOperatorError(node, kind, diagnostics, left, right, resultKind); + left = BindToTypeForErrorRecovery(left); + right = BindToTypeForErrorRecovery(right); + return new BoundCompoundAssignmentOperator(node, BinaryOperatorSignature.Error, left, right, + leftPlaceholder: null, leftConversion: null, finalPlaceholder: null, finalConversion: null, resultKind, originalUserDefinedOperators, CreateErrorType(), hasErrors: true); + } + + bool shouldTryUserDefinedInstanceOperator(AssignmentExpressionSyntax node, bool checkOverflowAtRuntime, BoundExpression left, out string? checkedName, out string? ordinaryName) { var leftType = left.Type; Debug.Assert(!left.HasDynamicType()); + checkedName = null; + ordinaryName = null; + if (leftType is null || - !SyntaxFacts.IsOverloadableCompoundAssignmentOperator(operatorToken.Kind()) || - leftType.SpecialType.IsNumericType() || + !SyntaxFacts.IsOverloadableCompoundAssignmentOperator(node.OperatorToken.Kind()) || !node.IsFeatureEnabled(MessageID.IDS_FeatureUserDefinedCompoundAssignmentOperators)) { - return null; + return false; } if (!CheckValueKind(node, left, BindValueKind.RefersToLocation | BindValueKind.Assignable, checkingReceiver: false, BindingDiagnosticBag.Discarded)) { - return null; + return false; } - bool checkOverflowAtRuntime = CheckOverflowAtRuntime; - CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); - string? checkedName = null; - if (checkOverflowAtRuntime) { - checkedName = OperatorFacts.CompoundAssignmentOperatorNameFromSyntaxKind(operatorToken.Kind(), isChecked: true); + checkedName = OperatorFacts.CompoundAssignmentOperatorNameFromSyntaxKind(node.OperatorToken.Kind(), isChecked: true); if (!SyntaxFacts.IsCheckedOperator(checkedName)) { checkedName = null; } } + ordinaryName = OperatorFacts.CompoundAssignmentOperatorNameFromSyntaxKind(node.OperatorToken.Kind(), isChecked: false); + + return true; + } + + BoundCompoundAssignmentOperator? tryApplyUserDefinedInstanceOperator( + AssignmentExpressionSyntax node, + BinaryOperatorKind kind, + bool checkOverflowAtRuntime, + string? checkedName, + string ordinaryName, + BoundExpression left, + BoundExpression right, + BindingDiagnosticBag diagnostics) + { + var leftType = left.Type; + Debug.Assert(leftType is not null); + + if (leftType.SpecialType.IsNumericType()) + { + return null; + } + + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + ArrayBuilder? methods = LookupUserDefinedInstanceOperators( leftType, checkedName: checkedName, - ordinaryName: OperatorFacts.CompoundAssignmentOperatorNameFromSyntaxKind(operatorToken.Kind(), isChecked: false), + ordinaryName: ordinaryName, parameterCount: 1, ref useSiteInfo); + diagnostics.Add(node, useSiteInfo); + if (methods?.IsEmpty != false) { - diagnostics.Add(node, useSiteInfo); methods?.Free(); return null; } + AnalyzedArguments? analyzedArguments = null; + + BoundCompoundAssignmentOperator? inPlaceResult = tryInstanceOperatorOverloadResolutionAndFreeMethods(node, kind, checkOverflowAtRuntime, isExtension: false, left, right, ref analyzedArguments, methods, diagnostics); + + Debug.Assert(analyzedArguments is not null); + analyzedArguments.Free(); + + return inPlaceResult; + } + + BoundCompoundAssignmentOperator? tryInstanceOperatorOverloadResolutionAndFreeMethods( + AssignmentExpressionSyntax node, + BinaryOperatorKind kind, + bool checkOverflowAtRuntime, + bool isExtension, + BoundExpression left, + BoundExpression right, + ref AnalyzedArguments? analyzedArguments, + ArrayBuilder methods, + BindingDiagnosticBag diagnostics) + { Debug.Assert(!methods.IsEmpty); var overloadResolutionResult = OverloadResolutionResult.GetInstance(); var typeArguments = ArrayBuilder.GetInstance(); - var analyzedArguments = AnalyzedArguments.GetInstance(); + var leftType = left.Type; + Debug.Assert(leftType is not null); + + if (analyzedArguments == null) + { + analyzedArguments = AnalyzedArguments.GetInstance(); + + if (isExtension) + { + // Create a set of arguments for overload resolution including the receiver. + CombineExtensionMethodArguments(left, originalArguments: null, analyzedArguments); - analyzedArguments.Arguments.Add(right); + if (leftType.IsValueType) + { + Debug.Assert(analyzedArguments.RefKinds.Count == 0); + analyzedArguments.RefKinds.Add(RefKind.Ref); + analyzedArguments.RefKinds.Add(RefKind.None); + } + } + + analyzedArguments.Arguments.Add(right); + } + + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); OverloadResolution.MethodInvocationOverloadResolution( methods, @@ -319,26 +454,53 @@ private BoundExpression BindCompoundAssignment(AssignmentExpressionSyntax node, analyzedArguments, overloadResolutionResult, ref useSiteInfo, - OverloadResolution.Options.DisallowExpandedForm); + OverloadResolution.Options.DisallowExpandedForm | (isExtension ? OverloadResolution.Options.IsExtensionMethodResolution : OverloadResolution.Options.None)); typeArguments.Free(); diagnostics.Add(node, useSiteInfo); BoundCompoundAssignmentOperator? inPlaceResult; - if (overloadResolutionResult.Succeeded) { var method = overloadResolutionResult.ValidResult.Member; - BoundExpression rightConverted = CreateConversion(right, overloadResolutionResult.ValidResult.Result.ConversionForArg(0), method.Parameters[0].Type, diagnostics); + BoundExpression rightConverted = CreateConversion(right, overloadResolutionResult.ValidResult.Result.ConversionForArg(isExtension ? 1 : 0), method.Parameters[0].Type, diagnostics); ReportDiagnosticsIfObsolete(diagnostics, method, node, hasBaseReceiver: false); ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, method, node, isDelegateConversion: false); + BoundValuePlaceholder? leftPlaceholder = null; + BoundExpression? leftConversion = null; + + if (isExtension) + { + Debug.Assert(method.ContainingType.ExtensionParameter is not null); + + if (Compilation.SourceModule != method.ContainingModule) + { + // While this code path is reachable, its effect is not observable + // because instance operators are simply not considered when the target + // version is C#13 or earlier. Coincidentally the following line + // would produce diagnostics only for C#13 or earlier. + CheckFeatureAvailability(node, MessageID.IDS_FeatureExtensions, diagnostics); + } + + Conversion conversion = overloadResolutionResult.ValidResult.Result.ConversionForArg(0); + + if (conversion.Kind is not ConversionKind.Identity) + { + Debug.Assert(conversion.Kind is ConversionKind.ImplicitReference); + Debug.Assert(leftType.IsReferenceType); + + leftPlaceholder = new BoundValuePlaceholder(left.Syntax, leftType).MakeCompilerGenerated(); + leftConversion = CreateConversion(node, leftPlaceholder, conversion, isCast: false, conversionGroupOpt: null, method.ContainingType.ExtensionParameter.Type, diagnostics); + } + } + inPlaceResult = new BoundCompoundAssignmentOperator( node, new BinaryOperatorSignature( - kind.WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), + kind.WithOverflowChecksIfApplicable(checkOverflowAtRuntime), leftType: leftType, rightType: method.Parameters[0].Type, returnType: leftType, @@ -346,7 +508,7 @@ private BoundExpression BindCompoundAssignment(AssignmentExpressionSyntax node, constrainedToTypeOpt: null), left: left, right: rightConverted, - leftPlaceholder: null, leftConversion: null, finalPlaceholder: null, finalConversion: null, + leftPlaceholder: leftPlaceholder, leftConversion: leftConversion, finalPlaceholder: null, finalConversion: null, resultKind: LookupResultKind.Viable, originalUserDefinedOperatorsOpt: ImmutableArray.Empty, getResultType(node, leftType, diagnostics)); @@ -358,7 +520,7 @@ private BoundExpression BindCompoundAssignment(AssignmentExpressionSyntax node, ImmutableArray methodsArray = methods.ToImmutableAndFree(); overloadResolutionResult.ReportDiagnostics( - binder: this, location: operatorToken.GetLocation(), nodeOpt: node, diagnostics: diagnostics, name: operatorToken.ValueText, + binder: this, location: node.OperatorToken.GetLocation(), nodeOpt: node, diagnostics: diagnostics, name: node.OperatorToken.ValueText, receiver: left, invokedExpression: node, arguments: analyzedArguments, memberGroup: methodsArray, typeContainingConstructor: null, delegateTypeBeingInvoked: null); @@ -366,7 +528,7 @@ private BoundExpression BindCompoundAssignment(AssignmentExpressionSyntax node, node, BinaryOperatorSignature.Error, left, - right, + BindToTypeForErrorRecovery(right), leftPlaceholder: null, leftConversion: null, finalPlaceholder: null, finalConversion: null, resultKind: LookupResultKind.OverloadResolutionFailure, originalUserDefinedOperatorsOpt: methodsArray, @@ -378,9 +540,7 @@ private BoundExpression BindCompoundAssignment(AssignmentExpressionSyntax node, methods.Free(); } - analyzedArguments.Free(); overloadResolutionResult.Free(); - return inPlaceResult; } @@ -388,6 +548,100 @@ TypeSymbol getResultType(ExpressionSyntax node, TypeSymbol leftType, BindingDiag { return ResultIsUsed(node) ? leftType : GetSpecialType(SpecialType.System_Void, diagnostics, node); } + + // This method returns result in two ways: + // - If it has a result due to instance extensions, it returns ready to use BoundCompoundAssignmentOperator + // - If it has static extensions result, it returns information via out parameters (staticBest, staticResultKind, staticOriginalUserDefinedOperators). + BoundCompoundAssignmentOperator? tryApplyUserDefinedExtensionOperator( + AssignmentExpressionSyntax node, + BinaryOperatorKind kind, + bool tryInstance, + bool checkOverflowAtRuntime, + string staticOperatorName1, + string? staticOperatorName2Opt, + string? checkedInstanceOperatorName, + string? ordinaryInstanceOperatorName, + BoundExpression left, + BoundExpression right, + BindingDiagnosticBag diagnostics, + out BinaryOperatorAnalysisResult? staticBest, + out LookupResultKind staticResultKind, + out ImmutableArray staticOriginalUserDefinedOperators) + { + staticBest = null; + staticResultKind = LookupResultKind.Empty; + staticOriginalUserDefinedOperators = []; + + var result = BinaryOperatorOverloadResolutionResult.GetInstance(); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + var extensionDeclarationsInSingleScope = ArrayBuilder.GetInstance(); + BoundCompoundAssignmentOperator? inPlaceResult = null; + AnalyzedArguments? analyzedArguments = null; + + foreach (var scope in new ExtensionScopes(this)) + { + extensionDeclarationsInSingleScope.Clear(); + scope.Binder.GetExtensionDeclarations(extensionDeclarationsInSingleScope, this); + + // Try an in-place user-defined operator + if (tryInstance) + { + Debug.Assert(ordinaryInstanceOperatorName is not null); + + inPlaceResult = tryApplyUserDefinedInstanceExtensionOperatorInSingleScope( + node, extensionDeclarationsInSingleScope, kind, checkOverflowAtRuntime, + checkedInstanceOperatorName, ordinaryInstanceOperatorName, + left, right, ref analyzedArguments, diagnostics); + if (inPlaceResult is not null) + { + break; + } + } + + if (this.OverloadResolution.BinaryOperatorExtensionOverloadResolutionInSingleScope( + extensionDeclarationsInSingleScope, kind, checkOverflowAtRuntime, + staticOperatorName1, staticOperatorName2Opt, + left, right, result, ref useSiteInfo)) + { + staticBest = BinaryOperatorAnalyzeOverloadResolutionResult(result, out staticResultKind, out staticOriginalUserDefinedOperators); + break; + } + } + + diagnostics.Add(node, useSiteInfo); + + analyzedArguments?.Free(); + extensionDeclarationsInSingleScope.Free(); + result.Free(); + return inPlaceResult; + } + + BoundCompoundAssignmentOperator? tryApplyUserDefinedInstanceExtensionOperatorInSingleScope( + AssignmentExpressionSyntax node, + ArrayBuilder extensionDeclarationsInSingleScope, + BinaryOperatorKind kind, + bool checkOverflowAtRuntime, + string? checkedName, + string ordinaryName, + BoundExpression left, + BoundExpression right, + ref AnalyzedArguments? analyzedArguments, + BindingDiagnosticBag diagnostics) + { + ArrayBuilder? methods = LookupUserDefinedInstanceExtensionOperatorsInSingleScope( + extensionDeclarationsInSingleScope, + checkedName: checkedName, + ordinaryName: ordinaryName, + parameterCount: 1); + + if (methods?.IsEmpty != false) + { + methods?.Free(); + return null; + } + + return tryInstanceOperatorOverloadResolutionAndFreeMethods(node, kind, checkOverflowAtRuntime, isExtension: true, left, right, ref analyzedArguments, methods, diagnostics); + } } #nullable disable @@ -750,13 +1004,14 @@ private BoundExpression BindSimpleBinaryOperator(BinaryExpressionSyntax node, Bi if ((resultOperatorKind & BinaryOperatorKind.Pointer) == BinaryOperatorKind.Pointer && leftType?.TypeKind == TypeKind.FunctionPointer && rightType?.TypeKind == TypeKind.FunctionPointer) { + Debug.Assert(!resultOperatorKind.IsUserDefined()); // Comparison of function pointers might yield an unexpected result, since pointers to the same function may be distinct. Error(diagnostics, ErrorCode.WRN_DoNotCompareFunctionPointers, node.OperatorToken); } break; default: - if (leftType.IsVoidPointer() || rightType.IsVoidPointer()) + if (!resultOperatorKind.IsUserDefined() && (leftType.IsVoidPointer() || rightType.IsVoidPointer())) { // CONSIDER: dev10 cascades this, but roslyn doesn't have to. Error(diagnostics, ErrorCode.ERR_VoidError, node); @@ -844,25 +1099,57 @@ private bool BindSimpleBinaryOperatorParts(BinaryExpressionSyntax node, BindingD out LookupResultKind resultKind, out ImmutableArray originalUserDefinedOperators, out BinaryOperatorSignature resultSignature, out BinaryOperatorAnalysisResult best) { - bool foundOperator; - best = this.BinaryOperatorOverloadResolution(kind, isChecked: CheckOverflowAtRuntime, left, right, node, diagnostics, out resultKind, out originalUserDefinedOperators); - - // However, as an implementation detail, we never "fail to find an applicable - // operator" during overload resolution if we have x == null, x == default, etc. We always - // find at least the reference conversion object == object; the overload resolution - // code does not reject that. Therefore what we should do is only bind - // "x == null" as a nullable-to-null comparison if overload resolution chooses - // the reference conversion. - - if (!best.HasValue) + if (!IsTypelessExpressionAllowedInBinaryOperator(kind, left, right)) { + resultKind = LookupResultKind.OverloadResolutionFailure; + originalUserDefinedOperators = default(ImmutableArray); + best = default(BinaryOperatorAnalysisResult); resultSignature = new BinaryOperatorSignature(kind, leftType: null, rightType: null, CreateErrorType()); - foundOperator = false; + return false; } - else - { + + bool isChecked = CheckOverflowAtRuntime; + OverloadResolution.GetStaticUserDefinedBinaryOperatorMethodNames(kind, isChecked, out string name1, out string name2Opt); + best = this.BinaryOperatorOverloadResolution(kind, isChecked, name1, name2Opt, left, right, node, diagnostics, out resultKind, out originalUserDefinedOperators); + + return bindSimpleBinaryOperatorPartsContinue(node, diagnostics, left, right, kind, ref resultKind, ref originalUserDefinedOperators, out resultSignature, ref best, isChecked, name1, name2Opt); + + bool bindSimpleBinaryOperatorPartsContinue( + BinaryExpressionSyntax node, + BindingDiagnosticBag diagnostics, + BoundExpression left, + BoundExpression right, + BinaryOperatorKind kind, + ref LookupResultKind resultKind, + ref ImmutableArray originalUserDefinedOperators, + out BinaryOperatorSignature resultSignature, + ref BinaryOperatorAnalysisResult best, + bool isChecked, + string name1, + string name2Opt) + { + // However, as an implementation detail, we never "fail to find an applicable + // operator" during overload resolution if we have x == null, x == default, etc. We always + // find at least the reference conversion object == object; the overload resolution + // code does not reject that. Therefore what we should do is only bind + // "x == null" as a nullable-to-null comparison if overload resolution chooses + // the reference conversion. + + if (!best.HasValue) + { + resultSignature = new BinaryOperatorSignature(kind, leftType: null, rightType: null, CreateErrorType()); + return false; + } + + bool foundOperator; var signature = best.Signature; + if (signature.Method is { } bestMethod) + { + ReportObsoleteAndFeatureAvailabilityDiagnostics(bestMethod, node, diagnostics); + ReportUseSite(bestMethod, diagnostics, node); + } + bool isObjectEquality = signature.Kind == BinaryOperatorKind.ObjectEqual || signature.Kind == BinaryOperatorKind.ObjectNotEqual; bool leftNull = left.IsLiteralNull(); @@ -891,9 +1178,27 @@ private bool BindSimpleBinaryOperatorParts(BinaryExpressionSyntax node, BindingD bool rightDefault = right.IsLiteralDefault(); foundOperator = !isObjectEquality || BuiltInOperators.IsValidObjectEquality(Conversions, leftType, leftNull, leftDefault, rightType, rightNull, rightDefault, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); + + if (!foundOperator) + { + Debug.Assert(isObjectEquality); + + // Try extension operators since predefined object equality was not applicable + LookupResultKind extensionResultKind; + ImmutableArray extensionOriginalUserDefinedOperators; + BinaryOperatorAnalysisResult? extensionBest = BinaryOperatorExtensionOverloadResolution(kind, isChecked, name1, name2Opt, left, right, node, diagnostics, out extensionResultKind, out extensionOriginalUserDefinedOperators); + + if (extensionBest.HasValue) + { + best = extensionBest.GetValueOrDefault(); + resultKind = extensionResultKind; + originalUserDefinedOperators = extensionOriginalUserDefinedOperators; + foundOperator = bindSimpleBinaryOperatorPartsContinue(node, diagnostics, left, right, kind, ref resultKind, ref originalUserDefinedOperators, out resultSignature, ref best, isChecked, name1, name2Opt); + } + } } + return foundOperator; } - return foundOperator; } #nullable enable @@ -928,6 +1233,9 @@ BoundExpression doRebind(BindingDiagnosticBag diagnostics, BoundBinaryOperator? BoundBinaryOperator b => doRebind(diagnostics, b), _ => throw ExceptionUtilities.UnexpectedValue(current.Right.Kind) }; + + // https://github.com/dotnet/roslyn/issues/78965: Add test coverage for this code path + left = BindSimpleBinaryOperator((BinaryExpressionSyntax)current.Syntax, diagnostics, left ?? current.Left, right, leaveUnconvertedIfInterpolatedString: false); } @@ -1107,7 +1415,18 @@ private BoundExpression BindConditionalLogicalOperator(BinaryExpressionSyntax no LookupResultKind lookupResult; ImmutableArray originalUserDefinedOperators; - var best = this.BinaryOperatorOverloadResolution(kind, isChecked: CheckOverflowAtRuntime, left, right, node, diagnostics, out lookupResult, out originalUserDefinedOperators); + BinaryOperatorAnalysisResult best; + + if (!IsTypelessExpressionAllowedInBinaryOperator(kind, left, right)) + { + lookupResult = LookupResultKind.OverloadResolutionFailure; + originalUserDefinedOperators = default(ImmutableArray); + best = default(BinaryOperatorAnalysisResult); + } + else + { + best = this.BinaryOperatorOverloadResolution(kind, isChecked: CheckOverflowAtRuntime, left, right, node, diagnostics, out lookupResult, out originalUserDefinedOperators); + } // SPEC: If overload resolution fails to find a single best operator, or if overload // SPEC: resolution selects one of the predefined integer logical operators, a binding- @@ -1129,6 +1448,12 @@ private BoundExpression BindConditionalLogicalOperator(BinaryExpressionSyntax no // bool, or we've got a valid user-defined operator. BinaryOperatorSignature signature = best.Signature; + if (signature.Method is { } bestMethod) + { + ReportObsoleteAndFeatureAvailabilityDiagnostics(bestMethod, node, diagnostics); + ReportUseSite(bestMethod, diagnostics, node); + } + bool bothBool = signature.LeftType.SpecialType == SpecialType.System_Boolean && signature.RightType.SpecialType == SpecialType.System_Boolean; @@ -1295,163 +1620,282 @@ private bool IsValidUserDefinedConditionalLogicalOperator( out MethodSymbol falseOperator) { Debug.Assert(signature.Kind.OperandTypes() == BinaryOperatorKind.UserDefined); + Debug.Assert(signature.Method is not null); - // SPEC: When the operands of && or || are of types that declare an applicable - // SPEC: user-defined operator & or |, both of the following must be true, where - // SPEC: T is the type in which the selected operator is defined: + if (signature.Method.GetIsNewExtensionMember()) + { + return isValidExtensionUserDefinedConditionalLogicalOperator(syntax, signature, diagnostics, out trueOperator, out falseOperator); + } + else + { + return isValidNonExtensionUserDefinedConditionalLogicalOperator(syntax, signature, diagnostics, out trueOperator, out falseOperator); + } - // SPEC VIOLATION: - // - // The native compiler violates the specification, the native compiler allows: - // - // public static D? operator &(D? d1, D? d2) { ... } - // public static bool operator true(D? d) { ... } - // public static bool operator false(D? d) { ... } - // - // to be used as D? && D? or D? || D?. But if you do this: - // - // public static D operator &(D d1, D d2) { ... } - // public static bool operator true(D? d) { ... } - // public static bool operator false(D? d) { ... } - // - // And use the *lifted* form of the operator, this is disallowed. - // - // public static D? operator &(D? d1, D d2) { ... } - // public static bool operator true(D? d) { ... } - // public static bool operator false(D? d) { ... } - // - // Is not allowed because "the return type must be the same as the type of both operands" - // which is not at all what the spec says. - // - // We ought not to break backwards compatibility with the native compiler. The spec - // is plausibly in error; it is possible that this section of the specification was - // never updated when nullable types and lifted operators were added to the language. - // And it seems like the native compiler's behavior of allowing a nullable - // version but not a lifted version is a bug that should be fixed. - // - // Therefore we will do the following in Roslyn: - // - // * The return and parameter types of the chosen operator, whether lifted or unlifted, - // must be the same. - // * The return and parameter types must be either the enclosing type, or its corresponding - // nullable type. - // * There must be an operator true/operator false that takes the left hand type of the operator. + bool isValidNonExtensionUserDefinedConditionalLogicalOperator( + CSharpSyntaxNode syntax, + BinaryOperatorSignature signature, + BindingDiagnosticBag diagnostics, + out MethodSymbol trueOperator, + out MethodSymbol falseOperator) + { + // SPEC: When the operands of && or || are of types that declare an applicable + // SPEC: user-defined operator & or |, both of the following must be true, where + // SPEC: T is the type in which the selected operator is defined: + + // SPEC VIOLATION: + // + // The native compiler violates the specification, the native compiler allows: + // + // public static D? operator &(D? d1, D? d2) { ... } + // public static bool operator true(D? d) { ... } + // public static bool operator false(D? d) { ... } + // + // to be used as D? && D? or D? || D?. But if you do this: + // + // public static D operator &(D d1, D d2) { ... } + // public static bool operator true(D? d) { ... } + // public static bool operator false(D? d) { ... } + // + // And use the *lifted* form of the operator, this is disallowed. + // + // public static D? operator &(D? d1, D d2) { ... } + // public static bool operator true(D? d) { ... } + // public static bool operator false(D? d) { ... } + // + // Is not allowed because "the return type must be the same as the type of both operands" + // which is not at all what the spec says. + // + // We ought not to break backwards compatibility with the native compiler. The spec + // is plausibly in error; it is possible that this section of the specification was + // never updated when nullable types and lifted operators were added to the language. + // And it seems like the native compiler's behavior of allowing a nullable + // version but not a lifted version is a bug that should be fixed. + // + // Therefore we will do the following in Roslyn: + // + // * The return and parameter types of the chosen operator, whether lifted or unlifted, + // must be the same. + // * The return and parameter types must be either the enclosing type, or its corresponding + // nullable type. + // * There must be an operator true/operator false that takes the left hand type of the operator. + + // Only classes and structs contain user-defined operators, so we know it is a named type symbol. + NamedTypeSymbol t = (NamedTypeSymbol)signature.Method.ContainingType; + + // SPEC: The return type and the type of each parameter of the selected operator + // SPEC: must be T. + + // As mentioned above, we relax this restriction. The types must all be the same. + + bool typesAreSame = TypeSymbol.Equals(signature.LeftType, signature.RightType, TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(signature.LeftType, signature.ReturnType, TypeCompareKind.ConsiderEverything2); + MethodSymbol definition; + bool typeMatchesContainer = TypeSymbol.Equals(signature.ReturnType.StrippedType(), t, TypeCompareKind.ConsiderEverything2) || + (t.IsInterface && (signature.Method.IsAbstract || signature.Method.IsVirtual) && + SourceUserDefinedOperatorSymbol.IsSelfConstrainedTypeParameter((definition = signature.Method.OriginalDefinition).ReturnType.StrippedType(), definition.ContainingType)); + + if (!typesAreSame || !typeMatchesContainer) + { + // CS0217: In order to be applicable as a short circuit operator a user-defined logical + // operator ('{0}') must have the same return type and parameter types - // Only classes and structs contain user-defined operators, so we know it is a named type symbol. - NamedTypeSymbol t = (NamedTypeSymbol)signature.Method.ContainingType; + Error(diagnostics, ErrorCode.ERR_BadBoolOp, syntax, signature.Method); - // SPEC: The return type and the type of each parameter of the selected operator - // SPEC: must be T. + trueOperator = null; + falseOperator = null; + return false; + } - // As mentioned above, we relax this restriction. The types must all be the same. + // SPEC: T must contain declarations of operator true and operator false. - bool typesAreSame = TypeSymbol.Equals(signature.LeftType, signature.RightType, TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(signature.LeftType, signature.ReturnType, TypeCompareKind.ConsiderEverything2); - MethodSymbol definition; - bool typeMatchesContainer = TypeSymbol.Equals(signature.ReturnType.StrippedType(), t, TypeCompareKind.ConsiderEverything2) || - (t.IsInterface && (signature.Method.IsAbstract || signature.Method.IsVirtual) && - SourceUserDefinedOperatorSymbol.IsSelfConstrainedTypeParameter((definition = signature.Method.OriginalDefinition).ReturnType.StrippedType(), definition.ContainingType)); + // As mentioned above, we need more than just op true and op false existing; we need + // to know that the first operand can be passed to it. - if (!typesAreSame || !typeMatchesContainer) - { - // CS0217: In order to be applicable as a short circuit operator a user-defined logical - // operator ('{0}') must have the same return type and parameter types + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + if (!HasApplicableBooleanOperator(t, WellKnownMemberNames.TrueOperatorName, signature.LeftType, ref useSiteInfo, out trueOperator) || + !HasApplicableBooleanOperator(t, WellKnownMemberNames.FalseOperatorName, signature.LeftType, ref useSiteInfo, out falseOperator)) + { + // I have changed the wording of this error message. The original wording was: - Error(diagnostics, ErrorCode.ERR_BadBoolOp, syntax, signature.Method); + // CS0218: The type ('T') must contain declarations of operator true and operator false - trueOperator = null; - falseOperator = null; - return false; - } + // I have changed that to: - // SPEC: T must contain declarations of operator true and operator false. + // CS0218: In order to be applicable as a short circuit operator, the declaring type + // '{1}' of user-defined operator '{0}' must declare operator true and operator false. - // As mentioned above, we need more than just op true and op false existing; we need - // to know that the first operand can be passed to it. + Error(diagnostics, ErrorCode.ERR_MustHaveOpTF, syntax, signature.Method, t); + diagnostics.Add(syntax, useSiteInfo); - CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); - if (!HasApplicableBooleanOperator(t, WellKnownMemberNames.TrueOperatorName, signature.LeftType, ref useSiteInfo, out trueOperator) || - !HasApplicableBooleanOperator(t, WellKnownMemberNames.FalseOperatorName, signature.LeftType, ref useSiteInfo, out falseOperator)) + trueOperator = null; + falseOperator = null; + return false; + } + + diagnostics.Add(syntax, useSiteInfo); + + // For the remainder of this method the comments WOLOG assume that we're analyzing an &&. The + // exact same issues apply to ||. + + // Note that the mere *existence* of operator true and operator false is sufficient. They + // are already constrained to take either T or T?. Since we know that the applicable + // T.& takes (T, T), we know that both sides of the && are implicitly convertible + // to T, and therefore the left side is implicitly convertible to T or T?. + + // SPEC: The expression x && y is evaluated as T.false(x) ? x : T.&(x,y) ... except that + // SPEC: x is only evaluated once. + // + // DELIBERATE SPEC VIOLATION: The native compiler does not actually evaluate x&&y in this + // manner. Suppose X is of type X. The code above is equivalent to: + // + // X temp = x, then evaluate: + // T.false(temp) ? temp : T.&(temp, y) + // + // What the native compiler actually evaluates is: + // + // T temp = x, then evaluate + // T.false(temp) ? temp : T.&(temp, y) + // + // That is a small difference but it has an observable effect. For example: + // + // class V { public static implicit operator T(V v) { ... } } + // class X : V { public static implicit operator T?(X x) { ... } } + // struct T { + // public static operator false(T? t) { ... } + // public static operator true(T? t) { ... } + // public static T operator &(T t1, T t2) { ... } + // } + // + // Under the spec'd interpretation, if we had x of type X and y of type T then x && y is + // + // X temp = x; + // T.false(temp) ? temp : T.&(temp, y) + // + // which would then be analyzed as: + // + // T.false(X.op_Implicit_To_Nullable_T(temp)) ? + // V.op_Implicit_To_T(temp) : + // T.&(op_Implicit_To_T(temp), y) + // + // But the native compiler actually generates: + // + // T temp = V.Op_Implicit_To_T(x); + // T.false(new T?(temp)) ? temp : T.&(temp, y) + // + // That is, the native compiler converts the temporary to the type of the declaring operator type + // regardless of the fact that there is a better conversion for the T.false call. + // + // We choose to match the native compiler behavior here; we might consider fixing + // the spec to match the compiler. + // + // With this decision we need not keep track of any extra information in the bound + // binary operator node; we need to know the left hand side converted to T, the right + // hand side converted to T, and the method symbol of the chosen T.&(T, T) method. + // The rewriting pass has enough information to deduce which T.false is to be called, + // and can convert the T to T? if necessary. + + return true; + } + +#nullable enable + + bool isValidExtensionUserDefinedConditionalLogicalOperator( + CSharpSyntaxNode syntax, + BinaryOperatorSignature signature, + BindingDiagnosticBag diagnostics, + out MethodSymbol? trueOperator, + out MethodSymbol? falseOperator) { - // I have changed the wording of this error message. The original wording was: + // SPEC: The return type and the type of each parameter of the selected operator + // SPEC: must be T. - // CS0218: The type ('T') must contain declarations of operator true and operator false + if (!TypeSymbol.Equals(signature.LeftType, signature.RightType, TypeCompareKind.AllIgnoreOptions) || + !TypeSymbol.Equals(signature.LeftType, signature.ReturnType, TypeCompareKind.AllIgnoreOptions)) + { + // Note, isValidNonExtensionUserDefinedConditionalLogicalOperator also performs a check that the signature type + // matches the declaring type, but that is actually enforced at the point of declaration. We also don't have a + // single test that observes the effect of that check in isValidNonExtensionUserDefinedConditionalLogicalOperator. + // This is somewhat expected, because in order to observe the effect, one should consume a type with operators + // that do not follow C# rules for their signature. + // It is probably not worth guarding against a situation like that, we are not doing this for regular binary operators, + // for example. + + // CS0217: In order to be applicable as a short circuit operator a user-defined logical + // operator ('{0}') must have the same return type and parameter types + + Error(diagnostics, ErrorCode.ERR_BadBoolOp, syntax, signature.Method); + + trueOperator = null; + falseOperator = null; + return false; + } + + // SPEC: T must contain declarations of operator true and operator false. + + var leftPlaceholder = new BoundValuePlaceholder(syntax, signature.LeftType).MakeCompilerGenerated(); + var result = UnaryOperatorOverloadResolutionResult.GetInstance(); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + var extensions = ArrayBuilder.GetInstance(); - // I have changed that to: + NamespaceSymbol.AddExtensionContainersInType(signature.Method.OriginalDefinition.ContainingType.ContainingType, extensions); - // CS0218: In order to be applicable as a short circuit operator, the declaring type - // '{1}' of user-defined operator '{0}' must declare operator true and operator false. + UnaryOperatorAnalysisResult? bestTrue = unaryOperatorOverloadResolution(syntax, extensions, result, UnaryOperatorKind.True, leftPlaceholder, ref useSiteInfo); + UnaryOperatorAnalysisResult? bestFalse = null; - Error(diagnostics, ErrorCode.ERR_MustHaveOpTF, syntax, signature.Method, t); + if (bestTrue?.HasValue == true) + { + bestFalse = unaryOperatorOverloadResolution(syntax, extensions, result, UnaryOperatorKind.False, leftPlaceholder, ref useSiteInfo); + } + + extensions.Free(); + result.Free(); diagnostics.Add(syntax, useSiteInfo); - trueOperator = null; - falseOperator = null; - return false; - } + if (bestTrue?.HasValue != true || bestFalse?.HasValue != true) + { + Error(diagnostics, ErrorCode.ERR_MustHaveOpTF, syntax, signature.Method, signature.Method.OriginalDefinition.ContainingType.ContainingType); - diagnostics.Add(syntax, useSiteInfo); + trueOperator = null; + falseOperator = null; + return false; + } - // For the remainder of this method the comments WOLOG assume that we're analyzing an &&. The - // exact same issues apply to ||. + Debug.Assert(bestTrue is { HasValue: true }); + Debug.Assert(bestFalse is { HasValue: true }); + Debug.Assert(!bestTrue.GetValueOrDefault().Signature.Kind.IsLifted()); + Debug.Assert(!bestFalse.GetValueOrDefault().Signature.Kind.IsLifted()); - // Note that the mere *existence* of operator true and operator false is sufficient. They - // are already constrained to take either T or T?. Since we know that the applicable - // T.& takes (T, T), we know that both sides of the && are implicitly convertible - // to T, and therefore the left side is implicitly convertible to T or T?. + trueOperator = bestTrue.GetValueOrDefault().Signature.Method; + falseOperator = bestFalse.GetValueOrDefault().Signature.Method; - // SPEC: The expression x && y is evaluated as T.false(x) ? x : T.&(x,y) ... except that - // SPEC: x is only evaluated once. - // - // DELIBERATE SPEC VIOLATION: The native compiler does not actually evaluate x&&y in this - // manner. Suppose X is of type X. The code above is equivalent to: - // - // X temp = x, then evaluate: - // T.false(temp) ? temp : T.&(temp, y) - // - // What the native compiler actually evaluates is: - // - // T temp = x, then evaluate - // T.false(temp) ? temp : T.&(temp, y) - // - // That is a small difference but it has an observable effect. For example: - // - // class V { public static implicit operator T(V v) { ... } } - // class X : V { public static implicit operator T?(X x) { ... } } - // struct T { - // public static operator false(T? t) { ... } - // public static operator true(T? t) { ... } - // public static T operator &(T t1, T t2) { ... } - // } - // - // Under the spec'd interpretation, if we had x of type X and y of type T then x && y is - // - // X temp = x; - // T.false(temp) ? temp : T.&(temp, y) - // - // which would then be analyzed as: - // - // T.false(X.op_Implicit_To_Nullable_T(temp)) ? - // V.op_Implicit_To_T(temp) : - // T.&(op_Implicit_To_T(temp), y) - // - // But the native compiler actually generates: - // - // T temp = V.Op_Implicit_To_T(x); - // T.false(new T?(temp)) ? temp : T.&(temp, y) - // - // That is, the native compiler converts the temporary to the type of the declaring operator type - // regardless of the fact that there is a better conversion for the T.false call. - // - // We choose to match the native compiler behavior here; we might consider fixing - // the spec to match the compiler. - // - // With this decision we need not keep track of any extra information in the bound - // binary operator node; we need to know the left hand side converted to T, the right - // hand side converted to T, and the method symbol of the chosen T.&(T, T) method. - // The rewriting pass has enough information to deduce which T.false is to be called, - // and can convert the T to T? if necessary. + return true; - return true; + UnaryOperatorAnalysisResult? unaryOperatorOverloadResolution( + CSharpSyntaxNode syntax, + ArrayBuilder extensions, + UnaryOperatorOverloadResolutionResult result, + UnaryOperatorKind kind, + BoundValuePlaceholder leftPlaceholder, + ref CompoundUseSiteInfo useSiteInfo) + { + UnaryOperatorAnalysisResult? possiblyBest = null; + + if (this.OverloadResolution.UnaryOperatorExtensionOverloadResolutionInSingleScope( + extensions, + kind, + isChecked: false, + OperatorFacts.UnaryOperatorNameFromOperatorKind(kind, isChecked: false), + name2Opt: null, + leftPlaceholder, + result, ref useSiteInfo)) + { + possiblyBest = AnalyzeUnaryOperatorOverloadResolutionResult(result, kind, leftPlaceholder, syntax, diagnostics: BindingDiagnosticBag.Discarded, resultKind: out _, originalUserDefinedOperators: out _); + } + + return possiblyBest; + } + } + +#nullable disable } private bool HasApplicableBooleanOperator(NamedTypeSymbol containingType, string name, TypeSymbol argumentType, ref CompoundUseSiteInfo useSiteInfo, out MethodSymbol @operator) @@ -1499,9 +1943,112 @@ private TypeSymbol GetBinaryOperatorErrorType(BinaryOperatorKind kind, BindingDi } } - private BinaryOperatorAnalysisResult BinaryOperatorOverloadResolution( + private BinaryOperatorAnalysisResult BinaryOperatorOverloadResolution( + BinaryOperatorKind kind, + bool isChecked, + BoundExpression left, + BoundExpression right, + CSharpSyntaxNode node, + BindingDiagnosticBag diagnostics, + out LookupResultKind resultKind, + out ImmutableArray originalUserDefinedOperators) + { + OverloadResolution.GetStaticUserDefinedBinaryOperatorMethodNames(kind, isChecked, out string name1, out string name2Opt); + + return BinaryOperatorOverloadResolution(kind, isChecked, name1, name2Opt, left, right, node, diagnostics, out resultKind, out originalUserDefinedOperators); + } + + private BinaryOperatorAnalysisResult BinaryOperatorOverloadResolution( + BinaryOperatorKind kind, + bool isChecked, + string name1, + string name2Opt, + BoundExpression left, + BoundExpression right, + CSharpSyntaxNode node, + BindingDiagnosticBag diagnostics, + out LookupResultKind resultKind, + out ImmutableArray originalUserDefinedOperators) + { + BinaryOperatorAnalysisResult possiblyBest = BinaryOperatorNonExtensionOverloadResolution(kind, isChecked, name1, name2Opt, left, right, node, diagnostics, out resultKind, out originalUserDefinedOperators); + + Debug.Assert(resultKind is LookupResultKind.Viable or LookupResultKind.Ambiguous or LookupResultKind.OverloadResolutionFailure or LookupResultKind.Empty); + Debug.Assert(possiblyBest.HasValue == (resultKind is LookupResultKind.Viable)); + Debug.Assert(resultKind is not (LookupResultKind.OverloadResolutionFailure or LookupResultKind.Empty) || originalUserDefinedOperators.IsEmpty); + + if (!possiblyBest.HasValue && resultKind != LookupResultKind.Ambiguous) + { + Debug.Assert(resultKind is LookupResultKind.OverloadResolutionFailure or LookupResultKind.Empty); + Debug.Assert(originalUserDefinedOperators.IsEmpty); + + LookupResultKind extensionResultKind; + ImmutableArray extensionOriginalUserDefinedOperators; + BinaryOperatorAnalysisResult? extensionBest = BinaryOperatorExtensionOverloadResolution(kind, isChecked, name1, name2Opt, left, right, node, diagnostics, out extensionResultKind, out extensionOriginalUserDefinedOperators); + + if (extensionBest.HasValue) + { + possiblyBest = extensionBest.GetValueOrDefault(); + resultKind = extensionResultKind; + originalUserDefinedOperators = extensionOriginalUserDefinedOperators; + } + } + + return possiblyBest; + } + +#nullable enable + + private BinaryOperatorAnalysisResult? BinaryOperatorExtensionOverloadResolution( + BinaryOperatorKind kind, + bool isChecked, + string name1, + string name2Opt, + BoundExpression left, + BoundExpression right, + CSharpSyntaxNode node, + BindingDiagnosticBag diagnostics, + out LookupResultKind resultKind, + out ImmutableArray originalUserDefinedOperators) + { + resultKind = LookupResultKind.Empty; + originalUserDefinedOperators = []; + + if (left.Type is null && right.Type is null) + { + return null; + } + + var result = BinaryOperatorOverloadResolutionResult.GetInstance(); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + var extensionDeclarationsInSingleScope = ArrayBuilder.GetInstance(); + BinaryOperatorAnalysisResult? possiblyBest = null; + + foreach (var scope in new ExtensionScopes(this)) + { + extensionDeclarationsInSingleScope.Clear(); + scope.Binder.GetExtensionDeclarations(extensionDeclarationsInSingleScope, this); + + if (this.OverloadResolution.BinaryOperatorExtensionOverloadResolutionInSingleScope(extensionDeclarationsInSingleScope, kind, isChecked, name1, name2Opt, left, right, result, ref useSiteInfo)) + { + possiblyBest = BinaryOperatorAnalyzeOverloadResolutionResult(result, out resultKind, out originalUserDefinedOperators); + break; + } + } + + diagnostics.Add(node, useSiteInfo); + + extensionDeclarationsInSingleScope.Free(); + result.Free(); + return possiblyBest; + } + +#nullable disable + + private BinaryOperatorAnalysisResult BinaryOperatorNonExtensionOverloadResolution( BinaryOperatorKind kind, bool isChecked, + string name1, + string name2Opt, BoundExpression left, BoundExpression right, CSharpSyntaxNode node, @@ -1509,18 +2056,23 @@ private BinaryOperatorAnalysisResult BinaryOperatorOverloadResolution( out LookupResultKind resultKind, out ImmutableArray originalUserDefinedOperators) { - if (!IsTypelessExpressionAllowedInBinaryOperator(kind, left, right)) - { - resultKind = LookupResultKind.OverloadResolutionFailure; - originalUserDefinedOperators = default(ImmutableArray); - return default(BinaryOperatorAnalysisResult); - } - var result = BinaryOperatorOverloadResolutionResult.GetInstance(); CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); - this.OverloadResolution.BinaryOperatorOverloadResolution(kind, isChecked, left, right, result, ref useSiteInfo); + this.OverloadResolution.BinaryOperatorOverloadResolution(kind, isChecked, name1, name2Opt, left, right, result, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); + var possiblyBest = BinaryOperatorAnalyzeOverloadResolutionResult(result, out resultKind, out originalUserDefinedOperators); + result.Free(); + + Debug.Assert(resultKind is LookupResultKind.Viable or LookupResultKind.Ambiguous or LookupResultKind.OverloadResolutionFailure or LookupResultKind.Empty); + Debug.Assert(possiblyBest.HasValue == (resultKind is LookupResultKind.Viable)); + Debug.Assert(resultKind is not (LookupResultKind.OverloadResolutionFailure or LookupResultKind.Empty) || originalUserDefinedOperators.IsEmpty); + + return possiblyBest; + } + + private static BinaryOperatorAnalysisResult BinaryOperatorAnalyzeOverloadResolutionResult(BinaryOperatorOverloadResolutionResult result, out LookupResultKind resultKind, out ImmutableArray originalUserDefinedOperators) + { var possiblyBest = result.Best; if (result.Results.Any()) @@ -1555,13 +2107,6 @@ private BinaryOperatorAnalysisResult BinaryOperatorOverloadResolution( resultKind = possiblyBest.HasValue ? LookupResultKind.Viable : LookupResultKind.Empty; } - if (possiblyBest is { HasValue: true, Signature: { Method: { } bestMethod } }) - { - ReportObsoleteAndFeatureAvailabilityDiagnostics(bestMethod, node, diagnostics); - ReportUseSite(bestMethod, diagnostics, node); - } - - result.Free(); return possiblyBest; } @@ -1608,12 +2153,72 @@ private UnaryOperatorAnalysisResult UnaryOperatorOverloadResolution( BindingDiagnosticBag diagnostics, out LookupResultKind resultKind, out ImmutableArray originalUserDefinedOperators) + { + bool isChecked = CheckOverflowAtRuntime; + OverloadResolution.GetStaticUserDefinedUnaryOperatorMethodNames(kind, isChecked, out string name1, out string name2Opt); + + var best = UnaryOperatorNonExtensionOverloadResolution(kind, isChecked, name1, name2Opt, operand, node, diagnostics, out resultKind, out originalUserDefinedOperators); + + Debug.Assert(resultKind is LookupResultKind.Viable or LookupResultKind.Ambiguous or LookupResultKind.OverloadResolutionFailure or LookupResultKind.Empty); + Debug.Assert(best.HasValue == (resultKind is LookupResultKind.Viable)); + Debug.Assert(resultKind is not (LookupResultKind.OverloadResolutionFailure or LookupResultKind.Empty) || originalUserDefinedOperators.IsEmpty); + + if (!best.HasValue && resultKind != LookupResultKind.Ambiguous) + { + Debug.Assert(resultKind is LookupResultKind.OverloadResolutionFailure or LookupResultKind.Empty); + Debug.Assert(originalUserDefinedOperators.IsEmpty); + + LookupResultKind extensionResultKind; + ImmutableArray extensionOriginalUserDefinedOperators; + UnaryOperatorAnalysisResult? extensionBest = this.UnaryOperatorExtensionOverloadResolution(kind, isChecked, name1, name2Opt, operand, node, diagnostics, out extensionResultKind, out extensionOriginalUserDefinedOperators); + + if (extensionBest.HasValue) + { + best = extensionBest.GetValueOrDefault(); + resultKind = extensionResultKind; + originalUserDefinedOperators = extensionOriginalUserDefinedOperators; + } + } + + return best; + } + + private UnaryOperatorAnalysisResult UnaryOperatorNonExtensionOverloadResolution( + UnaryOperatorKind kind, + bool isChecked, + string name1, + string name2Opt, + BoundExpression operand, + CSharpSyntaxNode node, + BindingDiagnosticBag diagnostics, + out LookupResultKind resultKind, + out ImmutableArray originalUserDefinedOperators) { var result = UnaryOperatorOverloadResolutionResult.GetInstance(); CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); - this.OverloadResolution.UnaryOperatorOverloadResolution(kind, isChecked: CheckOverflowAtRuntime, operand, result, ref useSiteInfo); + this.OverloadResolution.UnaryOperatorOverloadResolution(kind, isChecked, name1, name2Opt, operand, result, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); + UnaryOperatorAnalysisResult possiblyBest = AnalyzeUnaryOperatorOverloadResolutionResult(result, kind, operand, node, diagnostics, out resultKind, out originalUserDefinedOperators); + + result.Free(); + + Debug.Assert(resultKind is LookupResultKind.Viable or LookupResultKind.Ambiguous or LookupResultKind.OverloadResolutionFailure or LookupResultKind.Empty); + Debug.Assert(possiblyBest.HasValue == (resultKind is LookupResultKind.Viable)); + Debug.Assert(resultKind is not (LookupResultKind.OverloadResolutionFailure or LookupResultKind.Empty) || originalUserDefinedOperators.IsEmpty); + + return possiblyBest; + } + + UnaryOperatorAnalysisResult AnalyzeUnaryOperatorOverloadResolutionResult( + UnaryOperatorOverloadResolutionResult result, + UnaryOperatorKind kind, + BoundExpression operand, + CSharpSyntaxNode node, + BindingDiagnosticBag diagnostics, + out LookupResultKind resultKind, + out ImmutableArray originalUserDefinedOperators) + { var possiblyBest = result.Best; if (result.Results.Any()) @@ -1670,7 +2275,6 @@ private UnaryOperatorAnalysisResult UnaryOperatorOverloadResolution( ReportUseSite(bestMethod, diagnostics, node); } - result.Free(); return possiblyBest; static bool isNuint(TypeSymbol type) @@ -1680,6 +2284,54 @@ static bool isNuint(TypeSymbol type) } } +#nullable enable + + private UnaryOperatorAnalysisResult? UnaryOperatorExtensionOverloadResolution( + UnaryOperatorKind kind, + bool isChecked, + string name1, + string? name2Opt, + BoundExpression operand, + CSharpSyntaxNode node, + BindingDiagnosticBag diagnostics, + out LookupResultKind resultKind, + out ImmutableArray originalUserDefinedOperators) + { + resultKind = LookupResultKind.Empty; + originalUserDefinedOperators = []; + + if (operand.IsLiteralDefault() || // Reported not being able to target-type `default` elsewhere, so we can avoid doing more work + operand.Type is null) // GetUserDefinedOperators performs this check too, let's optimize early + { + return null; + } + + var result = UnaryOperatorOverloadResolutionResult.GetInstance(); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + var extensionDeclarationsInSingleScope = ArrayBuilder.GetInstance(); + UnaryOperatorAnalysisResult? possiblyBest = null; + + foreach (var scope in new ExtensionScopes(this)) + { + extensionDeclarationsInSingleScope.Clear(); + scope.Binder.GetExtensionDeclarations(extensionDeclarationsInSingleScope, this); + + if (this.OverloadResolution.UnaryOperatorExtensionOverloadResolutionInSingleScope(extensionDeclarationsInSingleScope, kind, isChecked, name1, name2Opt, operand, result, ref useSiteInfo)) + { + possiblyBest = AnalyzeUnaryOperatorOverloadResolutionResult(result, kind, operand, node, diagnostics, out resultKind, out originalUserDefinedOperators); + break; + } + } + + diagnostics.Add(node, useSiteInfo); + + extensionDeclarationsInSingleScope.Free(); + result.Free(); + return possiblyBest; + } + +#nullable disable + private static object FoldDecimalBinaryOperators(BinaryOperatorKind kind, ConstantValue valueLeft, ConstantValue valueRight) { Debug.Assert(valueLeft != null); @@ -2455,6 +3107,13 @@ public static BinaryOperatorKind SyntaxKindToBinaryOperatorKind(SyntaxKind kind) #nullable enable + private enum InstanceUserDefinedIncrementUsageMode : byte + { + None, + ResultIsNotUsed, + ResultIsUsed + } + private BoundExpression BindIncrementOperator(ExpressionSyntax node, ExpressionSyntax operandSyntax, SyntaxToken operatorToken, BindingDiagnosticBag diagnostics) { operandSyntax.CheckDeconstructionCompatibleArgument(diagnostics); @@ -2503,16 +3162,62 @@ private BoundExpression BindIncrementOperator(ExpressionSyntax node, ExpressionS hasErrors: false); } + bool isChecked = CheckOverflowAtRuntime; + // Try an in-place user-defined operator - BoundIncrementOperator? inPlaceResult = tryApplyUserDefinedInstanceOperator(node, operatorToken, kind, operand, diagnostics); - if (inPlaceResult is not null) + InstanceUserDefinedIncrementUsageMode mode = getInstanceUserDefinedIncrementUsageMode(node, kind, isChecked, operand, out string? checkedInstanceOperatorName, out string? ordinaryInstanceOperatorName); + + if (mode != InstanceUserDefinedIncrementUsageMode.None) { - return inPlaceResult; + Debug.Assert(ordinaryInstanceOperatorName is not null); + + BoundIncrementOperator? inPlaceResult = tryApplyUserDefinedInstanceOperator(node, operatorToken, kind, mode, isChecked, checkedInstanceOperatorName, ordinaryInstanceOperatorName, operand, diagnostics); + if (inPlaceResult is not null) + { + return inPlaceResult; + } } + OverloadResolution.GetStaticUserDefinedUnaryOperatorMethodNames(kind, isChecked, out string staticOperatorName1, out string? staticOperatorName2Opt); + LookupResultKind resultKind; ImmutableArray originalUserDefinedOperators; - var best = this.UnaryOperatorOverloadResolution(kind, operand, node, diagnostics, out resultKind, out originalUserDefinedOperators); + var best = this.UnaryOperatorNonExtensionOverloadResolution(kind, isChecked, staticOperatorName1, staticOperatorName2Opt, operand, node, diagnostics, out resultKind, out originalUserDefinedOperators); + + Debug.Assert(resultKind is LookupResultKind.Viable or LookupResultKind.Ambiguous or LookupResultKind.OverloadResolutionFailure or LookupResultKind.Empty); + Debug.Assert(best.HasValue == (resultKind is LookupResultKind.Viable)); + Debug.Assert(resultKind is not (LookupResultKind.OverloadResolutionFailure or LookupResultKind.Empty) || originalUserDefinedOperators.IsEmpty); + + if (!best.HasValue && resultKind != LookupResultKind.Ambiguous) + { + Debug.Assert(resultKind is LookupResultKind.OverloadResolutionFailure or LookupResultKind.Empty); + Debug.Assert(originalUserDefinedOperators.IsEmpty); + + // Check for extension operators + LookupResultKind staticExtensionResultKind; + ImmutableArray staticExtensionOriginalUserDefinedOperators; + UnaryOperatorAnalysisResult? staticExtensionBest; + BoundIncrementOperator? instanceExtensionResult = tryApplyUserDefinedExtensionOperator( + node, kind, mode, isChecked, + staticOperatorName1, staticOperatorName2Opt, + checkedInstanceOperatorName, ordinaryInstanceOperatorName, + operand, diagnostics, + out staticExtensionBest, out staticExtensionResultKind, out staticExtensionOriginalUserDefinedOperators); + + if (instanceExtensionResult is not null) + { + Debug.Assert(instanceExtensionResult.ResultKind is LookupResultKind.Viable || !instanceExtensionResult.OriginalUserDefinedOperatorsOpt.IsDefaultOrEmpty); + return instanceExtensionResult; + } + + if (staticExtensionBest.HasValue) + { + best = staticExtensionBest.GetValueOrDefault(); + resultKind = staticExtensionResultKind; + originalUserDefinedOperators = staticExtensionOriginalUserDefinedOperators; + } + } + if (!best.HasValue) { ReportUnaryOperatorError(node, diagnostics, operatorToken.Text, operand, resultKind); @@ -2555,11 +3260,12 @@ private BoundExpression BindIncrementOperator(ExpressionSyntax node, ExpressionS if (!hasErrors && operandType.IsVoidPointer()) { + Debug.Assert(!signature.Kind.IsUserDefined()); Error(diagnostics, ErrorCode.ERR_VoidError, node); hasErrors = true; } - var operandPlaceholder = new BoundValuePlaceholder(operand.Syntax, operand.Type).MakeCompilerGenerated(); + var operandPlaceholder = new BoundValuePlaceholder(operand.Syntax, operandType).MakeCompilerGenerated(); var operandConversion = CreateConversion(node, operandPlaceholder, best.Conversion, isCast: false, conversionGroupOpt: null, best.Signature.OperandType, diagnostics); return new BoundIncrementOperator( @@ -2577,17 +3283,27 @@ private BoundExpression BindIncrementOperator(ExpressionSyntax node, ExpressionS operandType, hasErrors); - BoundIncrementOperator? tryApplyUserDefinedInstanceOperator(ExpressionSyntax node, SyntaxToken operatorToken, UnaryOperatorKind kind, BoundExpression operand, BindingDiagnosticBag diagnostics) + InstanceUserDefinedIncrementUsageMode getInstanceUserDefinedIncrementUsageMode( + ExpressionSyntax node, + UnaryOperatorKind kind, + bool checkOverflowAtRuntime, + BoundExpression operand, + out string? checkedName, + out string? ordinaryName) { var operandType = operand.Type; Debug.Assert(operandType is not null); Debug.Assert(!operandType.IsDynamic()); + Debug.Assert(kind is (UnaryOperatorKind.PrefixIncrement or UnaryOperatorKind.PrefixDecrement or UnaryOperatorKind.PostfixIncrement or UnaryOperatorKind.PostfixDecrement)); + + checkedName = null; + ordinaryName = null; if (kind is not (UnaryOperatorKind.PrefixIncrement or UnaryOperatorKind.PrefixDecrement or UnaryOperatorKind.PostfixIncrement or UnaryOperatorKind.PostfixDecrement) || operandType.SpecialType.IsNumericType() || !node.IsFeatureEnabled(MessageID.IDS_FeatureUserDefinedCompoundAssignmentOperators)) { - return null; + return InstanceUserDefinedIncrementUsageMode.None; } bool resultIsUsed = ResultIsUsed(node); @@ -2595,37 +3311,98 @@ private BoundExpression BindIncrementOperator(ExpressionSyntax node, ExpressionS if ((kind is (UnaryOperatorKind.PostfixIncrement or UnaryOperatorKind.PostfixDecrement) && resultIsUsed) || !CheckValueKind(node, operand, BindValueKind.RefersToLocation | BindValueKind.Assignable, checkingReceiver: false, BindingDiagnosticBag.Discarded)) { - return null; + return InstanceUserDefinedIncrementUsageMode.None; } - bool checkOverflowAtRuntime = CheckOverflowAtRuntime; - CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); - - ArrayBuilder? methods = LookupUserDefinedInstanceOperators( - operandType, - checkedName: checkOverflowAtRuntime ? + checkedName = checkOverflowAtRuntime ? (kind is UnaryOperatorKind.PrefixIncrement or UnaryOperatorKind.PostfixIncrement ? WellKnownMemberNames.CheckedIncrementAssignmentOperatorName : WellKnownMemberNames.CheckedDecrementAssignmentOperatorName) : - null, - ordinaryName: kind is UnaryOperatorKind.PrefixIncrement or UnaryOperatorKind.PostfixIncrement ? + null; + ordinaryName = kind is UnaryOperatorKind.PrefixIncrement or UnaryOperatorKind.PostfixIncrement ? WellKnownMemberNames.IncrementAssignmentOperatorName : - WellKnownMemberNames.DecrementAssignmentOperatorName, + WellKnownMemberNames.DecrementAssignmentOperatorName; + + return resultIsUsed ? InstanceUserDefinedIncrementUsageMode.ResultIsUsed : InstanceUserDefinedIncrementUsageMode.ResultIsNotUsed; + } + + BoundIncrementOperator? tryApplyUserDefinedInstanceOperator( + ExpressionSyntax node, + SyntaxToken operatorToken, + UnaryOperatorKind kind, + InstanceUserDefinedIncrementUsageMode mode, + bool isChecked, + string? checkedName, + string ordinaryName, + BoundExpression operand, + BindingDiagnosticBag diagnostics) + { + Debug.Assert(operand.Type is not null); + Debug.Assert(mode != InstanceUserDefinedIncrementUsageMode.None); + + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + + ArrayBuilder? methods = LookupUserDefinedInstanceOperators( + operand.Type, + checkedName: checkedName, + ordinaryName: ordinaryName, parameterCount: 0, ref useSiteInfo); + diagnostics.Add(node, useSiteInfo); + if (methods?.IsEmpty != false) { - diagnostics.Add(node, useSiteInfo); methods?.Free(); return null; } + AnalyzedArguments? analyzedArguments = null; + BoundIncrementOperator? inPlaceResult = tryInstanceOperatorOverloadResolutionAndFreeMethods(node, operatorToken, kind, mode, isChecked, isExtension: false, operand, ref analyzedArguments, methods, diagnostics); + Debug.Assert(analyzedArguments is not null); + analyzedArguments.Free(); + + return inPlaceResult; + } + + BoundIncrementOperator? tryInstanceOperatorOverloadResolutionAndFreeMethods( + ExpressionSyntax node, + SyntaxToken operatorToken, + UnaryOperatorKind kind, + InstanceUserDefinedIncrementUsageMode mode, + bool checkOverflowAtRuntime, + bool isExtension, + BoundExpression operand, + ref AnalyzedArguments? analyzedArguments, + ArrayBuilder methods, + BindingDiagnosticBag diagnostics) + { Debug.Assert(!methods.IsEmpty); + var operandType = operand.Type; + Debug.Assert(operandType is not null); + var overloadResolutionResult = OverloadResolutionResult.GetInstance(); var typeArguments = ArrayBuilder.GetInstance(); - var analyzedArguments = AnalyzedArguments.GetInstance(); + + if (analyzedArguments == null) + { + analyzedArguments = AnalyzedArguments.GetInstance(); + + if (isExtension) + { + // Create a set of arguments for overload resolution including the receiver. + CombineExtensionMethodArguments(operand, originalArguments: null, analyzedArguments); + + if (operandType.IsValueType) + { + Debug.Assert(analyzedArguments.RefKinds.Count == 0); + analyzedArguments.RefKinds.Add(RefKind.Ref); + } + } + } + + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); OverloadResolution.MethodInvocationOverloadResolution( methods, @@ -2634,7 +3411,7 @@ private BoundExpression BindIncrementOperator(ExpressionSyntax node, ExpressionS analyzedArguments, overloadResolutionResult, ref useSiteInfo, - OverloadResolution.Options.DisallowExpandedForm); + OverloadResolution.Options.DisallowExpandedForm | (isExtension ? OverloadResolution.Options.IsExtensionMethodResolution : OverloadResolution.Options.None)); typeArguments.Free(); diagnostics.Add(node, useSiteInfo); @@ -2648,19 +3425,47 @@ private BoundExpression BindIncrementOperator(ExpressionSyntax node, ExpressionS ReportDiagnosticsIfObsolete(diagnostics, method, node, hasBaseReceiver: false); ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, method, node, isDelegateConversion: false); + BoundValuePlaceholder? operandPlaceholder = null; + BoundExpression? operandConversion = null; + + if (isExtension) + { + Debug.Assert(method.ContainingType.ExtensionParameter is not null); + + if (Compilation.SourceModule != method.ContainingModule) + { + // While this code path is reachable, its effect is not observable + // because instance operators are simply not considered when the target + // version is C#13 or earlier. Coincidentally the following line + // would produce diagnostics only for C#13 or earlier. + CheckFeatureAvailability(node, MessageID.IDS_FeatureExtensions, diagnostics); + } + + Conversion conversion = overloadResolutionResult.ValidResult.Result.ConversionForArg(0); + + if (conversion.Kind is not ConversionKind.Identity) + { + Debug.Assert(conversion.Kind is ConversionKind.ImplicitReference); + Debug.Assert(operandType.IsReferenceType); + + operandPlaceholder = new BoundValuePlaceholder(operand.Syntax, operandType).MakeCompilerGenerated(); + operandConversion = CreateConversion(node, operandPlaceholder, conversion, isCast: false, conversionGroupOpt: null, method.ContainingType.ExtensionParameter.Type, diagnostics); + } + } + inPlaceResult = new BoundIncrementOperator( node, (kind | UnaryOperatorKind.UserDefined).WithOverflowChecksIfApplicable(checkOverflowAtRuntime), operand, methodOpt: method, constrainedToTypeOpt: null, - operandPlaceholder: null, - operandConversion: null, + operandPlaceholder: operandPlaceholder, + operandConversion: operandConversion, resultPlaceholder: null, resultConversion: null, LookupResultKind.Viable, ImmutableArray.Empty, - getResultType(node, operandType, resultIsUsed, diagnostics)); + getResultType(node, operandType, mode, diagnostics)); methods.Free(); } @@ -2685,7 +3490,7 @@ private BoundExpression BindIncrementOperator(ExpressionSyntax node, ExpressionS resultConversion: null, LookupResultKind.OverloadResolutionFailure, methodsArray, - getResultType(node, operandType, resultIsUsed, diagnostics)); + getResultType(node, operandType, mode, diagnostics)); } else { @@ -2693,15 +3498,111 @@ private BoundExpression BindIncrementOperator(ExpressionSyntax node, ExpressionS methods.Free(); } - analyzedArguments.Free(); overloadResolutionResult.Free(); + return inPlaceResult; + } + + TypeSymbol getResultType(ExpressionSyntax node, TypeSymbol operandType, InstanceUserDefinedIncrementUsageMode mode, BindingDiagnosticBag diagnostics) + { + return mode == InstanceUserDefinedIncrementUsageMode.ResultIsUsed ? operandType : GetSpecialType(SpecialType.System_Void, diagnostics, node); + } + + // This method returns result in two ways: + // - If it has a result due to instance extensions, it returns ready to use BoundIncrementOperator + // - If it has static extensions result, it returns information via out parameters (staticBest, staticResultKind, staticOriginalUserDefinedOperators). + BoundIncrementOperator? tryApplyUserDefinedExtensionOperator( + ExpressionSyntax node, + UnaryOperatorKind kind, + InstanceUserDefinedIncrementUsageMode mode, + bool isChecked, + string staticOperatorName1, + string? staticOperatorName2Opt, + string? checkedInstanceOperatorName, + string? ordinaryInstanceOperatorName, + BoundExpression operand, + BindingDiagnosticBag diagnostics, + out UnaryOperatorAnalysisResult? staticBest, + out LookupResultKind staticResultKind, + out ImmutableArray staticOriginalUserDefinedOperators) + { + Debug.Assert(operand.Type is not null); + + staticBest = null; + staticResultKind = LookupResultKind.Empty; + staticOriginalUserDefinedOperators = []; + + var result = UnaryOperatorOverloadResolutionResult.GetInstance(); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + var extensionDeclarationsInSingleScope = ArrayBuilder.GetInstance(); + BoundIncrementOperator? inPlaceResult = null; + AnalyzedArguments? analyzedArguments = null; + + foreach (var scope in new ExtensionScopes(this)) + { + extensionDeclarationsInSingleScope.Clear(); + scope.Binder.GetExtensionDeclarations(extensionDeclarationsInSingleScope, this); + + // Try an in-place user-defined operator + if (mode != InstanceUserDefinedIncrementUsageMode.None) + { + Debug.Assert(ordinaryInstanceOperatorName is not null); + inPlaceResult = tryApplyUserDefinedInstanceExtensionOperatorInSingleScope( + node, operatorToken, extensionDeclarationsInSingleScope, kind, mode, isChecked, + checkedInstanceOperatorName, ordinaryInstanceOperatorName, + operand, ref analyzedArguments, diagnostics); + if (inPlaceResult is not null) + { + break; + } + } + + if (this.OverloadResolution.UnaryOperatorExtensionOverloadResolutionInSingleScope( + extensionDeclarationsInSingleScope, kind, isChecked, + staticOperatorName1, staticOperatorName2Opt, + operand, result, ref useSiteInfo)) + { + staticBest = AnalyzeUnaryOperatorOverloadResolutionResult(result, kind, operand, node, diagnostics, out staticResultKind, out staticOriginalUserDefinedOperators); + break; + } + } + + diagnostics.Add(node, useSiteInfo); + + analyzedArguments?.Free(); + extensionDeclarationsInSingleScope.Free(); + result.Free(); return inPlaceResult; } - TypeSymbol getResultType(ExpressionSyntax node, TypeSymbol operandType, bool resultIsUsed, BindingDiagnosticBag diagnostics) + BoundIncrementOperator? tryApplyUserDefinedInstanceExtensionOperatorInSingleScope( + ExpressionSyntax node, + SyntaxToken operatorToken, + ArrayBuilder extensionDeclarationsInSingleScope, + UnaryOperatorKind kind, + InstanceUserDefinedIncrementUsageMode mode, + bool isChecked, + string? checkedName, + string ordinaryName, + BoundExpression operand, + ref AnalyzedArguments? analyzedArguments, + BindingDiagnosticBag diagnostics) { - return resultIsUsed ? operandType : GetSpecialType(SpecialType.System_Void, diagnostics, node); + Debug.Assert(mode != InstanceUserDefinedIncrementUsageMode.None); + + ArrayBuilder? methods = LookupUserDefinedInstanceExtensionOperatorsInSingleScope( + extensionDeclarationsInSingleScope, + checkedName: checkedName, + ordinaryName: ordinaryName, + parameterCount: 0); + + if (methods?.IsEmpty != false) + { + methods?.Free(); + return null; + } + + return tryInstanceOperatorOverloadResolutionAndFreeMethods(node, operatorToken, kind, mode, isChecked, isExtension: true, operand, ref analyzedArguments, methods, diagnostics); } } @@ -2745,7 +3646,7 @@ TypeSymbol getResultType(ExpressionSyntax node, TypeSymbol operandType, bool res foreach (MethodSymbol method in lookupResult.Symbols) { - if (isViable(method, parameterCount) && !existing.Contains(method.GetLeastOverriddenMethod(ContainingType))) + if (IsViableInstanceOperator(method, parameterCount) && !existing.Contains(method.GetLeastOverriddenMethod(ContainingType))) { methods.Add(method); } @@ -2761,18 +3662,99 @@ static void appendViableMethods(LookupResult lookupResult, int parameterCount, A { foreach (MethodSymbol method in lookupResult.Symbols) { - if (isViable(method, parameterCount)) + if (IsViableInstanceOperator(method, parameterCount)) { methods.Add(method); } } } + } + + private static bool IsViableInstanceOperator(MethodSymbol method, int parameterCount) + { + Debug.Assert(parameterCount is 0 or 1); + return method.ParameterCount == parameterCount && method.ReturnsVoid && !method.IsVararg && + (parameterCount == 0 || method.Parameters[0].RefKind is RefKind.None or RefKind.In); + } + + private ArrayBuilder? LookupUserDefinedInstanceExtensionOperatorsInSingleScope( + ArrayBuilder extensionDeclarationsInSingleScope, + string? checkedName, + string ordinaryName, + int parameterCount) + { + Debug.Assert(parameterCount is 0 or 1); + ArrayBuilder? checkedMethods = null; + + if (checkedName is not null) + { + Debug.Assert(SyntaxFacts.IsCheckedOperator(checkedName)); + lookupUserDefinedInstanceExtensionOperatorsInSingleScope(extensionDeclarationsInSingleScope, name: checkedName, parameterCount, ref checkedMethods); + } + + ArrayBuilder? ordinaryMethods = null; + lookupUserDefinedInstanceExtensionOperatorsInSingleScope(extensionDeclarationsInSingleScope, name: ordinaryName, parameterCount, ref ordinaryMethods); + + if (ordinaryMethods is not null) + { + if (checkedMethods is null) + { + return ordinaryMethods; + } + else + { + var existing = new HashSet(OverloadResolution.PairedExtensionOperatorSignatureComparer.Instance); + existing.AddRange(checkedMethods); + + foreach (MethodSymbol method in ordinaryMethods) + { + if (!existing.Contains(method)) + { + checkedMethods.Add(method); + } + } + } + } - static bool isViable(MethodSymbol method, int parameterCount) + return checkedMethods; + + static void lookupUserDefinedInstanceExtensionOperatorsInSingleScope( + ArrayBuilder extensionDeclarationsInSingleScope, + string name, + int parameterCount, + ref ArrayBuilder? methods) { - Debug.Assert(parameterCount is 0 or 1); - return method.ParameterCount == parameterCount && method.ReturnsVoid && !method.IsVararg && - (parameterCount == 0 || method.Parameters[0].RefKind is RefKind.None or RefKind.In); + ArrayBuilder? typeOperators = null; + + foreach (NamedTypeSymbol extensionDeclaration in extensionDeclarationsInSingleScope) + { + Debug.Assert(extensionDeclaration.IsExtension); + + if (extensionDeclaration.ExtensionParameter is not { } extensionParameter || + !((extensionParameter.Type.IsValueType && extensionParameter.RefKind == RefKind.Ref) || + (extensionParameter.Type.IsReferenceType && extensionParameter.RefKind == RefKind.None))) + { + continue; + } + + typeOperators ??= ArrayBuilder.GetInstance(); + typeOperators.Clear(); + extensionDeclaration.AddOperators(name, typeOperators); + + foreach (MethodSymbol op in typeOperators) + { + // If we're in error recovery, we might have bad operators. Just ignore them. + if (op.IsStatic || !IsViableInstanceOperator(op, parameterCount)) + { + continue; + } + + methods ??= ArrayBuilder.GetInstance(); + methods.Add(op); + } + } + + typeOperators?.Free(); } } @@ -2862,7 +3844,11 @@ private bool CheckConstraintLanguageVersionAndRuntimeSupportForOperator(SyntaxNo if (Compilation.SourceModule != methodOpt.ContainingModule) { - if (SyntaxFacts.IsCheckedOperator(methodOpt.Name)) + if (methodOpt.GetIsNewExtensionMember()) + { + result &= CheckFeatureAvailability(node, MessageID.IDS_FeatureExtensions, diagnostics); + } + else if (SyntaxFacts.IsCheckedOperator(methodOpt.Name)) { result &= CheckFeatureAvailability(node, MessageID.IDS_FeatureCheckedUserDefinedOperators, diagnostics); } diff --git a/src/Compilers/CSharp/Portable/Binder/Binder_Patterns.cs b/src/Compilers/CSharp/Portable/Binder/Binder_Patterns.cs index 860fbe3e56536..5912f8a975ef6 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder_Patterns.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder_Patterns.cs @@ -6,6 +6,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/Binder/Binder_Statements.cs b/src/Compilers/CSharp/Portable/Binder/Binder_Statements.cs index 535959ca12a0a..bdd3129820b58 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder_Statements.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder_Statements.cs @@ -2723,8 +2723,6 @@ internal BoundExpression BindBooleanExpression(ExpressionSyntax node, BindingDia if (!best.HasValue) { // No. Give a "not convertible to bool" error. - Debug.Assert(resultKind == LookupResultKind.Empty, "How could overload resolution fail if a user-defined true operator was found?"); - Debug.Assert(originalUserDefinedOperators.IsEmpty, "How could overload resolution fail if a user-defined true operator was found?"); GenerateImplicitConversionError(diagnostics, node, conversion, expr, boolean); return BoundConversion.Synthesized(node, expr, Conversion.NoConversion, false, explicitCastInCode: false, conversionGroupOpt: null, ConstantValue.NotAvailable, boolean, hasErrors: true); } diff --git a/src/Compilers/CSharp/Portable/Binder/Binder_Symbols.cs b/src/Compilers/CSharp/Portable/Binder/Binder_Symbols.cs index 5781f9598c1e0..9916068baa36e 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder_Symbols.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder_Symbols.cs @@ -1359,8 +1359,8 @@ private TypeWithAnnotations BindTypeArgument(TypeSyntax typeArgument, BindingDia // BackCompat. The compiler would previously suppress reporting errors for pointers in generic types. This // was intended so you would get a specific error in CheckBasicConstraints.CheckBasicConstraints for a type // like (like `List`). i.e. you would get the error about an unsafe type not being a legal type argument, - // but not the error about not being in an unsafe context. This had the unfortunate consequence though of - // preventing the latter check for something like `List`. Here, this is a legal generic type, but we + // but not the error about not being in an unsafe context. This had the unfortunate consequence though of + // preventing the latter check for something like `List`. Here, this is a legal generic type, but we // still want to report the error that you need to be in an unsafe context. So, to maintain compat, we only // do the suppression if you're on C# 11 and prior. In later versions we do the correct check. var binder = !Compilation.IsFeatureEnabled(MessageID.IDS_FeatureUsingTypeAlias) @@ -1442,48 +1442,6 @@ private BoundMethodOrPropertyGroup ConstructBoundMemberGroupAndReportOmittedType Debug.Assert(members.Count > 0); - BoundExpression colorColorValueReceiver = GetValueExpressionIfTypeOrValueReceiver(receiver); - - Debug.Assert(colorColorValueReceiver is null || (methodGroupFlags & BoundMethodGroupFlags.SearchExtensions) != 0); - - if (IsPossiblyCapturingPrimaryConstructorParameterReference(colorColorValueReceiver, out ParameterSymbol parameter)) - { - bool haveInstanceCandidates, haveStaticCandidates; - LookupResult tempLookupResult = null; - - CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); - CheckWhatCandidatesWeHave(members, parameter.Type, plainName, - typeArguments.IsDefault ? 0 : typeArguments.Length, - ref tempLookupResult, ref useSiteInfo, - out haveInstanceCandidates, out haveStaticCandidates); - tempLookupResult?.Free(); - diagnostics.Add(colorColorValueReceiver.Syntax, useSiteInfo); - - if (haveInstanceCandidates) - { - BindingDiagnosticBag discarded = null; - if (haveStaticCandidates) - { - Error(diagnostics, ErrorCode.ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver, colorColorValueReceiver.Syntax, parameter.Name, parameter.Type, parameter); - discarded = BindingDiagnosticBag.GetInstance(diagnostics); - } - - receiver = ReplaceTypeOrValueReceiver(receiver, useType: false, discarded ?? diagnostics); - discarded?.Free(); - - if (haveStaticCandidates) - { - // Wrap into bad expression with HasErrors in an attempt to suppress cascading diagnostics - receiver = new BoundBadExpression(receiver.Syntax, LookupResultKind.Ambiguous, ImmutableArray.Empty, ImmutableArray.Create(receiver), receiver.Type, hasErrors: true).MakeCompilerGenerated(); - } - } - else - { - Debug.Assert(haveStaticCandidates); - receiver = ReplaceTypeOrValueReceiver(receiver, useType: true, diagnostics); - } - } - switch (members[0].Kind) { case SymbolKind.Method: @@ -1511,25 +1469,78 @@ private BoundMethodOrPropertyGroup ConstructBoundMemberGroupAndReportOmittedType } } - private bool IsPossiblyCapturingPrimaryConstructorParameterReference(BoundExpression colorColorValueReceiver, out ParameterSymbol parameterSymbol) + private BoundExpression CheckAmbiguousPrimaryConstructorParameterAsColorColorReceiver(BoundExpression receiver, SyntaxNode right, string plainName, + ImmutableArray typeArguments, bool invoked, ArrayBuilder members, BindingDiagnosticBag diagnostics) { - if (colorColorValueReceiver is BoundParameter { ParameterSymbol: { ContainingSymbol: SynthesizedPrimaryConstructor primaryConstructor } parameter } && - IsInDeclaringTypeInstanceMember(primaryConstructor) && - !InFieldInitializer && - this.ContainingMember() != (object)primaryConstructor && - !IsInsideNameof) + if (!isPossiblyCapturingPrimaryConstructorParameterReference(receiver, out ParameterSymbol parameter)) { - parameterSymbol = parameter; - return true; + return receiver; } - parameterSymbol = null; - return false; + bool haveInstanceCandidates, haveStaticCandidates; + LookupResult tempLookupResult = null; + + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + CheckWhatCandidatesWeHave(members, parameter.Type, plainName, + typeArguments.IsDefault ? 0 : typeArguments.Length, + invoked, + ref tempLookupResult, ref useSiteInfo, + out haveInstanceCandidates, out haveStaticCandidates); + tempLookupResult?.Free(); + diagnostics.Add(receiver.Syntax, useSiteInfo); + + if (haveInstanceCandidates) + { + BindingDiagnosticBag discarded = null; + if (haveStaticCandidates) + { + Error(diagnostics, ErrorCode.ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver, receiver.Syntax, parameter.Name, parameter.Type, parameter); + discarded = BindingDiagnosticBag.GetInstance(diagnostics); + } + + receiver = ReplaceTypeOrValueReceiver(receiver, useType: false, discarded ?? diagnostics); + discarded?.Free(); + + if (haveStaticCandidates) + { + // Wrap into bad expression with HasErrors in an attempt to suppress cascading diagnostics + receiver = new BoundBadExpression(receiver.Syntax, LookupResultKind.Ambiguous, ImmutableArray.Empty, ImmutableArray.Create(receiver), receiver.Type, hasErrors: true).MakeCompilerGenerated(); + } + } + else if (haveStaticCandidates) + { + receiver = ReplaceTypeOrValueReceiver(receiver, useType: true, diagnostics); + } + else + { + Error(diagnostics, ErrorCode.ERR_NoSuchMemberOrExtension, right, receiver.Type, plainName); + receiver = new BoundBadExpression(receiver.Syntax, LookupResultKind.Empty, ImmutableArray.Empty, childBoundNodes: [receiver], receiver.Type, hasErrors: true).MakeCompilerGenerated(); + } + + return receiver; + + bool isPossiblyCapturingPrimaryConstructorParameterReference(BoundExpression receiver, out ParameterSymbol parameterSymbol) + { + BoundExpression colorColorValueReceiver = GetValueExpressionIfTypeOrValueReceiver(receiver); + + if (colorColorValueReceiver is BoundParameter { ParameterSymbol: { ContainingSymbol: SynthesizedPrimaryConstructor primaryConstructor } parameter } && + IsInDeclaringTypeInstanceMember(primaryConstructor) && + !InFieldInitializer && + this.ContainingMember() != (object)primaryConstructor && + !IsInsideNameof) + { + parameterSymbol = parameter; + return true; + } + + parameterSymbol = null; + return false; + } } private void CheckWhatCandidatesWeHave( ArrayBuilder members, TypeSymbol receiverType, - string plainName, int arity, + string plainName, int arity, bool invoked, ref LookupResult lookupResult, ref CompoundUseSiteInfo useSiteInfo, out bool haveInstanceCandidates, out bool haveStaticCandidates) @@ -1537,36 +1548,65 @@ private void CheckWhatCandidatesWeHave( Debug.Assert(lookupResult?.IsClear != false); haveInstanceCandidates = members.Any(m => !m.IsStatic); haveStaticCandidates = members.Any(m => m.IsStatic); - Debug.Assert(haveStaticCandidates || haveInstanceCandidates); - if (!haveInstanceCandidates && members[0].Kind == SymbolKind.Method) + if (haveStaticCandidates && haveInstanceCandidates) { - // See if there could be extension methods in scope - foreach (var scope in new ExtensionScopes(this)) - { - lookupResult ??= LookupResult.GetInstance(); - LookupExtensionMethods(lookupResult, scope, plainName, arity, ref useSiteInfo); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : account for new extension members + // No additional information to be collected by inspecting extension candidates + return; + } - if (lookupResult.IsMultiViable) + // look for applicable extensions in scope and whether they are instance or static + LookupOptions options = (arity == 0) ? LookupOptions.AllMethodsOnArityZero : LookupOptions.Default; + if (invoked) + { + options |= LookupOptions.MustBeInvocableIfMember; + } + + foreach (var scope in new ExtensionScopes(this)) + { + lookupResult ??= LookupResult.GetInstance(); + + scope.Binder.LookupAllExtensionMembersInSingleBinder( + lookupResult, plainName, arity, options, + originalBinder: this, useSiteInfo: ref useSiteInfo, classicExtensionUseSiteInfo: ref useSiteInfo); + + if (lookupResult.IsMultiViable) + { + foreach (Symbol symbol in lookupResult.Symbols) { - foreach (var symbol in lookupResult.Symbols) + if (symbol is MethodSymbol { IsExtensionMethod: true } extensionMethod) { - var method = (MethodSymbol)symbol; - if (method.ReduceExtensionMethod(receiverType, Compilation) is not null) + if (!haveInstanceCandidates + && extensionMethod.ReduceExtensionMethod(receiverType, Compilation) is { } reduced) { haveInstanceCandidates = true; - break; } } - } - - lookupResult.Clear(); + else + { + Debug.Assert(symbol.GetIsNewExtensionMember()); + if (SourceNamedTypeSymbol.GetCompatibleSubstitutedMember(this.Compilation, symbol, receiverType) is { } compatibleSubstitutedMember) + { + if (compatibleSubstitutedMember.IsStatic) + { + haveStaticCandidates = true; + } + else + { + haveInstanceCandidates = true; + } + } + } - if (haveInstanceCandidates) - { - break; + if (haveStaticCandidates && haveInstanceCandidates) + { + // No additional information to be collected by inspecting further scopes + return; + } } } + + lookupResult.Clear(); } } @@ -1728,7 +1768,7 @@ internal static bool TryGetSpecialTypeMember(CSharpCompilation compilat } } - // No need to track assemblies used by special members or types. They are coming from core library, which + // No need to track assemblies used by special members or types. They are coming from core library, which // doesn't have any dependencies. return true; } @@ -2049,7 +2089,7 @@ Symbol resultSymbol( // https://github.com/dotnet/roslyn/issues/62331 // some "single symbol" diagnostics are missed here for similar reasons // that make us miss diagnostics when reporting WRN_SameFullNameThisAggAgg. - // + // return first; } diff --git a/src/Compilers/CSharp/Portable/Binder/DecisionDagBuilder.cs b/src/Compilers/CSharp/Portable/Binder/DecisionDagBuilder.cs index 8597cc16bdf25..a755c9101810e 100644 --- a/src/Compilers/CSharp/Portable/Binder/DecisionDagBuilder.cs +++ b/src/Compilers/CSharp/Portable/Binder/DecisionDagBuilder.cs @@ -9,10 +9,10 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Shared.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp diff --git a/src/Compilers/CSharp/Portable/Binder/DecisionDagBuilder_ListPatterns.cs b/src/Compilers/CSharp/Portable/Binder/DecisionDagBuilder_ListPatterns.cs index 1a23e72c651d4..ea073fd9bf837 100644 --- a/src/Compilers/CSharp/Portable/Binder/DecisionDagBuilder_ListPatterns.cs +++ b/src/Compilers/CSharp/Portable/Binder/DecisionDagBuilder_ListPatterns.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; +using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/Binder/ForEachLoopBinder.cs b/src/Compilers/CSharp/Portable/Binder/ForEachLoopBinder.cs index 58cc8001b1d3e..1f3ac35d1a2b3 100644 --- a/src/Compilers/CSharp/Portable/Binder/ForEachLoopBinder.cs +++ b/src/Compilers/CSharp/Portable/Binder/ForEachLoopBinder.cs @@ -465,12 +465,16 @@ private BoundForEachStatement BindForEachPartsWorker(BindingDiagnosticBag diagno var foreachKeyword = _syntax.ForEachKeyword; ReportDiagnosticsIfObsolete(diagnostics, getEnumeratorMethod, foreachKeyword, hasBaseReceiver: false); ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, getEnumeratorMethod, foreachKeyword, isDelegateConversion: false); + Debug.Assert(!IsDisallowedExtensionInOlderLangVer(getEnumeratorMethod)); + // MoveNext is an instance method, so it does not need to have unmanaged callers only diagnostics reported. // Either a diagnostic was reported at the declaration of the method (for the invalid attribute), or MoveNext // is marked as not supported and we won't get here in the first place (for metadata import). ReportDiagnosticsIfObsolete(diagnostics, builder.MoveNextInfo.Method, foreachKeyword, hasBaseReceiver: false); ReportDiagnosticsIfObsolete(diagnostics, builder.CurrentPropertyGetter, foreachKeyword, hasBaseReceiver: false); ReportDiagnosticsIfObsolete(diagnostics, builder.CurrentPropertyGetter.AssociatedSymbol, foreachKeyword, hasBaseReceiver: false); + Debug.Assert(!IsDisallowedExtensionInOlderLangVer(builder.MoveNextInfo.Method)); + Debug.Assert(!IsDisallowedExtensionInOlderLangVer(builder.CurrentPropertyGetter)); // We want to convert from inferredType in the array/string case and builder.ElementType in the enumerator case, // but it turns out that these are equivalent (when both are available). diff --git a/src/Compilers/CSharp/Portable/Binder/InMethodBinder.cs b/src/Compilers/CSharp/Portable/Binder/InMethodBinder.cs index b835e700c620f..ba0646367dcba 100644 --- a/src/Compilers/CSharp/Portable/Binder/InMethodBinder.cs +++ b/src/Compilers/CSharp/Portable/Binder/InMethodBinder.cs @@ -8,6 +8,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; diff --git a/src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/ConversionsBase.cs b/src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/ConversionsBase.cs index dee269ee6edde..0a499dddee287 100644 --- a/src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/ConversionsBase.cs +++ b/src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/ConversionsBase.cs @@ -7,11 +7,11 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { diff --git a/src/Compilers/CSharp/Portable/Binder/Semantics/Operators/BinaryOperatorOverloadResolution.cs b/src/Compilers/CSharp/Portable/Binder/Semantics/Operators/BinaryOperatorOverloadResolution.cs index 7d49320cd9f33..30f77f21183da 100644 --- a/src/Compilers/CSharp/Portable/Binder/Semantics/Operators/BinaryOperatorOverloadResolution.cs +++ b/src/Compilers/CSharp/Portable/Binder/Semantics/Operators/BinaryOperatorOverloadResolution.cs @@ -8,16 +8,25 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Shared.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class OverloadResolution { - public void BinaryOperatorOverloadResolution(BinaryOperatorKind kind, bool isChecked, BoundExpression left, BoundExpression right, BinaryOperatorOverloadResolutionResult result, ref CompoundUseSiteInfo useSiteInfo) + public void BinaryOperatorOverloadResolution( + BinaryOperatorKind kind, + bool isChecked, + string name1, + string name2Opt, + BoundExpression left, + BoundExpression right, + BinaryOperatorOverloadResolutionResult result, + ref CompoundUseSiteInfo useSiteInfo) { // We can do a table lookup for well-known problems in overload resolution. BinaryOperatorOverloadResolution_EasyOut(kind, left, right, result); @@ -26,7 +35,7 @@ public void BinaryOperatorOverloadResolution(BinaryOperatorKind kind, bool isChe return; } - BinaryOperatorOverloadResolution_NoEasyOut(kind, isChecked, left, right, result, ref useSiteInfo); + BinaryOperatorOverloadResolution_NoEasyOut(kind, isChecked, name1, name2Opt, left, right, result, ref useSiteInfo); } internal void BinaryOperatorOverloadResolution_EasyOut(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, BinaryOperatorOverloadResolutionResult result) @@ -48,6 +57,8 @@ internal void BinaryOperatorOverloadResolution_EasyOut(BinaryOperatorKind kind, internal void BinaryOperatorOverloadResolution_NoEasyOut( BinaryOperatorKind kind, bool isChecked, + string name1, + string name2Opt, BoundExpression left, BoundExpression right, BinaryOperatorOverloadResolutionResult result, @@ -96,7 +107,7 @@ internal void BinaryOperatorOverloadResolution_NoEasyOut( if ((object)leftOperatorSourceOpt != null && !leftSourceIsInterface) { - hadApplicableCandidates = GetUserDefinedOperators(kind, isChecked, leftOperatorSourceOpt, left, right, result.Results, ref useSiteInfo); + hadApplicableCandidates = GetUserDefinedOperators(kind, isChecked, name1, name2Opt, leftOperatorSourceOpt, left, right, result.Results, ref useSiteInfo); if (!hadApplicableCandidates) { result.Results.Clear(); @@ -108,7 +119,7 @@ internal void BinaryOperatorOverloadResolution_NoEasyOut( if (!isShift && (object)rightOperatorSourceOpt != null && !rightSourceIsInterface && !rightOperatorSourceOpt.Equals(leftOperatorSourceOpt)) { var rightOperators = ArrayBuilder.GetInstance(); - if (GetUserDefinedOperators(kind, isChecked, rightOperatorSourceOpt, left, right, rightOperators, ref useSiteInfo)) + if (GetUserDefinedOperators(kind, isChecked, name1, name2Opt, rightOperatorSourceOpt, left, right, rightOperators, ref useSiteInfo)) { hadApplicableCandidates = true; AddDistinctOperators(result.Results, rightOperators); @@ -148,7 +159,7 @@ internal void BinaryOperatorOverloadResolution_NoEasyOut( secondSourceIsInterface = rightSourceIsInterface; } - hadApplicableCandidates = GetUserDefinedBinaryOperatorsFromInterfaces(kind, isChecked, + hadApplicableCandidates = GetUserDefinedBinaryOperatorsFromInterfaces(kind, isChecked, name1, name2Opt, firstOperatorSourceOpt, firstSourceIsInterface, left, right, ref useSiteInfo, lookedInInterfaces, result.Results); if (!hadApplicableCandidates) { @@ -158,7 +169,7 @@ internal void BinaryOperatorOverloadResolution_NoEasyOut( if (!isShift && (object)secondOperatorSourceOpt != null && !secondOperatorSourceOpt.Equals(firstOperatorSourceOpt)) { var rightOperators = ArrayBuilder.GetInstance(); - if (GetUserDefinedBinaryOperatorsFromInterfaces(kind, isChecked, + if (GetUserDefinedBinaryOperatorsFromInterfaces(kind, isChecked, name1, name2Opt, secondOperatorSourceOpt, secondSourceIsInterface, left, right, ref useSiteInfo, lookedInInterfaces, rightOperators)) { hadApplicableCandidates = true; @@ -207,6 +218,8 @@ internal void BinaryOperatorOverloadResolution_NoEasyOut( } private bool GetUserDefinedBinaryOperatorsFromInterfaces(BinaryOperatorKind kind, bool isChecked, + string name1, + string name2Opt, TypeSymbol operatorSourceOpt, bool sourceIsInterface, BoundExpression left, BoundExpression right, ref CompoundUseSiteInfo useSiteInfo, Dictionary lookedInInterfaces, ArrayBuilder candidates) @@ -228,7 +241,7 @@ private bool GetUserDefinedBinaryOperatorsFromInterfaces(BinaryOperatorKind kind if (!lookedInInterfaces.TryGetValue(operatorSourceOpt, out _)) { var operators = ArrayBuilder.GetInstance(); - GetUserDefinedBinaryOperatorsFromType(constrainedToTypeOpt, (NamedTypeSymbol)operatorSourceOpt, kind, isChecked, operators); + GetUserDefinedBinaryOperatorsFromType(constrainedToTypeOpt, (NamedTypeSymbol)operatorSourceOpt, kind, name1, name2Opt, operators); hadUserDefinedCandidateFromInterfaces = CandidateOperators(isChecked, operators, left, right, candidates, ref useSiteInfo); operators.Free(); Debug.Assert(hadUserDefinedCandidateFromInterfaces == candidates.Any(r => r.IsValid)); @@ -281,7 +294,7 @@ private bool GetUserDefinedBinaryOperatorsFromInterfaces(BinaryOperatorKind kind operators.Clear(); results.Clear(); - GetUserDefinedBinaryOperatorsFromType(constrainedToTypeOpt, @interface, kind, isChecked, operators); + GetUserDefinedBinaryOperatorsFromType(constrainedToTypeOpt, @interface, kind, name1, name2Opt, operators); hadUserDefinedCandidate = CandidateOperators(isChecked, operators, left, right, results, ref useSiteInfo); Debug.Assert(hadUserDefinedCandidate == results.Any(r => r.IsValid)); lookedInInterfaces.Add(@interface, hadUserDefinedCandidate); @@ -851,6 +864,8 @@ private static void AddDistinctOperators(ArrayBuilder operators) { Debug.Assert(operators.Count == 0); - string name1 = OperatorFacts.BinaryOperatorNameFromOperatorKind(kind, isChecked); + GetDeclaredUserDefinedBinaryOperators(constrainedToTypeOpt, type, kind, name1, operators); - getDeclaredOperators(constrainedToTypeOpt, type, kind, name1, operators); - - if (isChecked && SyntaxFacts.IsCheckedOperator(name1)) + if (name2Opt is not null) { - string name2 = OperatorFacts.BinaryOperatorNameFromOperatorKind(kind, isChecked: false); var operators2 = ArrayBuilder.GetInstance(); // Add regular operators as well. - getDeclaredOperators(constrainedToTypeOpt, type, kind, name2, operators2); + GetDeclaredUserDefinedBinaryOperators(constrainedToTypeOpt, type, kind, name2Opt, operators2); // Drop operators that have a match among the checked ones. if (operators.Count != 0) @@ -954,58 +983,60 @@ private void GetUserDefinedBinaryOperatorsFromType( operators2.Free(); } - addLiftedOperators(constrainedToTypeOpt, kind, operators); + AddLiftedUserDefinedBinaryOperators(constrainedToTypeOpt, kind, operators); + } - void getDeclaredOperators(TypeSymbol constrainedToTypeOpt, NamedTypeSymbol type, BinaryOperatorKind kind, string name, ArrayBuilder operators) - { - var typeOperators = ArrayBuilder.GetInstance(); - type.AddOperators(name, typeOperators); + private static void GetDeclaredUserDefinedBinaryOperators(TypeSymbol? constrainedToTypeOpt, NamedTypeSymbol type, BinaryOperatorKind kind, string name, ArrayBuilder operators) + { + var typeOperators = ArrayBuilder.GetInstance(); + type.AddOperators(name, typeOperators); - foreach (MethodSymbol op in typeOperators) + foreach (MethodSymbol op in typeOperators) + { + // If we're in error recovery, we might have bad operators. Just ignore it. + if (op.ParameterCount != 2 || op.ReturnsVoid) { - // If we're in error recovery, we might have bad operators. Just ignore it. - if (op.ParameterCount != 2 || op.ReturnsVoid) - { - continue; - } - - TypeSymbol leftOperandType = op.GetParameterType(0); - TypeSymbol rightOperandType = op.GetParameterType(1); - TypeSymbol resultType = op.ReturnType; - - operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UserDefined | kind, leftOperandType, rightOperandType, resultType, op, constrainedToTypeOpt)); + continue; } - typeOperators.Free(); + TypeSymbol leftOperandType = op.GetParameterType(0); + TypeSymbol rightOperandType = op.GetParameterType(1); + TypeSymbol resultType = op.ReturnType; + + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UserDefined | kind, leftOperandType, rightOperandType, resultType, op, constrainedToTypeOpt)); } - void addLiftedOperators(TypeSymbol constrainedToTypeOpt, BinaryOperatorKind kind, ArrayBuilder operators) + typeOperators.Free(); + } + + void AddLiftedUserDefinedBinaryOperators(TypeSymbol? constrainedToTypeOpt, BinaryOperatorKind kind, ArrayBuilder operators) + { + for (int i = operators.Count - 1; i >= 0; i--) { - for (int i = operators.Count - 1; i >= 0; i--) - { - MethodSymbol op = operators[i].Method; - TypeSymbol leftOperandType = op.GetParameterType(0); - TypeSymbol rightOperandType = op.GetParameterType(1); - TypeSymbol resultType = op.ReturnType; + MethodSymbol op = operators[i].Method; + TypeSymbol leftOperandType = op.GetParameterType(0); + TypeSymbol rightOperandType = op.GetParameterType(1); + TypeSymbol resultType = op.ReturnType; - LiftingResult lifting = UserDefinedBinaryOperatorCanBeLifted(leftOperandType, rightOperandType, resultType, kind); + LiftingResult lifting = UserDefinedBinaryOperatorCanBeLifted(leftOperandType, rightOperandType, resultType, kind); - if (lifting == LiftingResult.LiftOperandsAndResult) - { - operators.Add(new BinaryOperatorSignature( - BinaryOperatorKind.Lifted | BinaryOperatorKind.UserDefined | kind, - MakeNullable(leftOperandType), MakeNullable(rightOperandType), MakeNullable(resultType), op, constrainedToTypeOpt)); - } - else if (lifting == LiftingResult.LiftOperandsButNotResult) - { - operators.Add(new BinaryOperatorSignature( - BinaryOperatorKind.Lifted | BinaryOperatorKind.UserDefined | kind, - MakeNullable(leftOperandType), MakeNullable(rightOperandType), resultType, op, constrainedToTypeOpt)); - } + if (lifting == LiftingResult.LiftOperandsAndResult) + { + operators.Add(new BinaryOperatorSignature( + BinaryOperatorKind.Lifted | BinaryOperatorKind.UserDefined | kind, + MakeNullable(leftOperandType), MakeNullable(rightOperandType), MakeNullable(resultType), op, constrainedToTypeOpt)); + } + else if (lifting == LiftingResult.LiftOperandsButNotResult) + { + operators.Add(new BinaryOperatorSignature( + BinaryOperatorKind.Lifted | BinaryOperatorKind.UserDefined | kind, + MakeNullable(leftOperandType), MakeNullable(rightOperandType), resultType, op, constrainedToTypeOpt)); } } } +#nullable disable + private enum LiftingResult { NotLifted, @@ -1233,6 +1264,19 @@ private BetterResult BetterOperator(BinaryOperatorSignature op1, BinaryOperatorS if (Conversions.HasIdentityConversion(op1.LeftType, op2.LeftType) && Conversions.HasIdentityConversion(op1.RightType, op2.RightType)) { + // SPEC: If Mp is a non-generic method and Mq is a generic method, then Mp is better than Mq. + if (op1.Method?.GetMemberArityIncludingExtension() is null or 0) + { + if (op2.Method?.GetMemberArityIncludingExtension() > 0) + { + return BetterResult.Left; + } + } + else if (op2.Method?.GetMemberArityIncludingExtension() is null or 0) + { + return BetterResult.Right; + } + // NOTE: The native compiler does not follow these rules; effectively, the native // compiler checks for liftedness first, and then for specificity. For example: // struct S where T : struct { @@ -1373,5 +1417,216 @@ private static void AssertNotChecked(BinaryOperatorKind kind) { Debug.Assert((kind & ~BinaryOperatorKind.Checked) == kind, "Did not expect operator to be checked. Consider using .Operator() to mask."); } + +#nullable enable + + public bool BinaryOperatorExtensionOverloadResolutionInSingleScope( + ArrayBuilder extensionDeclarationsInSingleScope, + BinaryOperatorKind kind, + bool isChecked, + string name1, + string? name2Opt, + BoundExpression left, + BoundExpression right, + BinaryOperatorOverloadResolutionResult result, + ref CompoundUseSiteInfo useSiteInfo) + { + Debug.Assert(isChecked || name2Opt is null); + + var operators = ArrayBuilder.GetInstance(); + + getDeclaredUserDefinedBinaryOperatorsInScope(extensionDeclarationsInSingleScope, kind, name1, name2Opt, operators); + + if (left.Type?.IsNullableType() == true || right.Type?.IsNullableType() == true) // Wouldn't be applicable to the receiver type otherwise + { + AddLiftedUserDefinedBinaryOperators(constrainedToTypeOpt: null, kind, operators); + } + + inferTypeArgumentsAndRemoveInapplicableToReceiverType(kind, left, right, operators, ref useSiteInfo); + + bool hadApplicableCandidates = false; + + if (!operators.IsEmpty) + { + var results = result.Results; + results.Clear(); + if (CandidateOperators(isChecked, operators, left, right, results, ref useSiteInfo)) + { + BinaryOperatorOverloadResolution(left, right, result, ref useSiteInfo); + hadApplicableCandidates = true; + } + } + + operators.Free(); + + return hadApplicableCandidates; + + static void getDeclaredUserDefinedBinaryOperatorsInScope(ArrayBuilder extensionDeclarationsInSingleScope, BinaryOperatorKind kind, string name1, string? name2Opt, ArrayBuilder operators) + { + getDeclaredUserDefinedBinaryOperators(extensionDeclarationsInSingleScope, kind, name1, operators); + + if (name2Opt is not null) + { + if (!operators.IsEmpty) + { + var existing = new HashSet(PairedExtensionOperatorSignatureComparer.Instance); + existing.AddRange(operators.Select(static (op) => op.Method)); + + var operators2 = ArrayBuilder.GetInstance(); + getDeclaredUserDefinedBinaryOperators(extensionDeclarationsInSingleScope, kind, name2Opt, operators2); + + foreach (var op in operators2) + { + if (!existing.Contains(op.Method)) + { + operators.Add(op); + } + } + + operators2.Free(); + } + else + { + getDeclaredUserDefinedBinaryOperators(extensionDeclarationsInSingleScope, kind, name2Opt, operators); + } + } + } + + static void getDeclaredUserDefinedBinaryOperators(ArrayBuilder extensionDeclarationsInSingleScope, BinaryOperatorKind kind, string name, ArrayBuilder operators) + { + foreach (NamedTypeSymbol extensionDeclaration in extensionDeclarationsInSingleScope) + { + Debug.Assert(extensionDeclaration.IsExtension); + + if (extensionDeclaration.ExtensionParameter is null) + { + continue; + } + + GetDeclaredUserDefinedBinaryOperators(constrainedToTypeOpt: null, extensionDeclaration, kind, name, operators); + } + } + + void inferTypeArgumentsAndRemoveInapplicableToReceiverType(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, ArrayBuilder operators, ref CompoundUseSiteInfo useSiteInfo) + { + for (int i = operators.Count - 1; i >= 0; i--) + { + var candidate = operators[i]; + MethodSymbol method = candidate.Method; + NamedTypeSymbol extension = method.ContainingType; + + if (extension.Arity == 0) + { + if (isApplicableToReceiver(in candidate, left, right, ref useSiteInfo)) + { + continue; + } + } + else + { + // Infer type arguments + var inferenceResult = MethodTypeInferrer.Infer( + _binder, + this.Conversions, + extension.TypeParameters, + extension, + [TypeWithAnnotations.Create(candidate.LeftType), TypeWithAnnotations.Create(candidate.RightType)], + method.ParameterRefKinds, + [left, right], + ref useSiteInfo, + ordinals: null); + + if (inferenceResult.Success) + { + extension = extension.Construct(inferenceResult.InferredTypeArguments); + method = method.AsMember(extension); + + if (!FailsConstraintChecks(method, out ArrayBuilder constraintFailureDiagnosticsOpt, template: CompoundUseSiteInfo.Discarded)) + { + TypeSymbol leftOperandType = method.GetParameterType(0); + TypeSymbol rightOperandType = method.GetParameterType(1); + TypeSymbol resultType = method.ReturnType; + + BinaryOperatorSignature inferredCandidate; + + if (candidate.Kind.IsLifted()) + { + LiftingResult lifting = UserDefinedBinaryOperatorCanBeLifted(leftOperandType, rightOperandType, resultType, kind); + Debug.Assert(lifting is LiftingResult.LiftOperandsAndResult or LiftingResult.LiftOperandsButNotResult); + + inferredCandidate = new BinaryOperatorSignature( + BinaryOperatorKind.Lifted | BinaryOperatorKind.UserDefined | kind, + MakeNullable(leftOperandType), + MakeNullable(rightOperandType), + lifting == LiftingResult.LiftOperandsButNotResult ? resultType : MakeNullable(resultType), + method, constrainedToTypeOpt: null); + } + else + { + inferredCandidate = new BinaryOperatorSignature(BinaryOperatorKind.UserDefined | kind, leftOperandType, rightOperandType, resultType, method, constrainedToTypeOpt: null); + } + + if (isApplicableToReceiver(in inferredCandidate, left, right, ref useSiteInfo)) + { + operators[i] = inferredCandidate; + continue; + } + } + + constraintFailureDiagnosticsOpt?.Free(); + } + } + + operators.RemoveAt(i); + } + } + + bool isApplicableToReceiver(in BinaryOperatorSignature candidate, BoundExpression left, BoundExpression right, ref CompoundUseSiteInfo useSiteInfo) + { + Debug.Assert(candidate.Method.ContainingType.ExtensionParameter is not null); + + if (left.Type is not null && parameterMatchesReceiver(in candidate, 0) && isOperandApplicableToReceiver(in candidate, left, ref useSiteInfo)) + { + return true; + } + + if (!kind.IsShift() && right.Type is not null && parameterMatchesReceiver(in candidate, 1) && isOperandApplicableToReceiver(in candidate, right, ref useSiteInfo)) + { + return true; + } + + return false; + } + + static bool parameterMatchesReceiver(in BinaryOperatorSignature candidate, int paramIndex) + { + var method = candidate.Method.OriginalDefinition; + var extensionParameter = method.ContainingType.ExtensionParameter; + Debug.Assert(extensionParameter is not null); + + return SourceUserDefinedOperatorSymbolBase.ExtensionOperatorParameterTypeMatchesExtendedType(method.Parameters[paramIndex].Type, extensionParameter.Type); + } + + bool isOperandApplicableToReceiver(in BinaryOperatorSignature candidate, BoundExpression operand, ref CompoundUseSiteInfo useSiteInfo) + { + Debug.Assert(operand.Type is not null); + Debug.Assert(candidate.Method.ContainingType.ExtensionParameter is not null); + + if (candidate.Kind.IsLifted() && operand.Type.IsNullableType()) + { + if (!candidate.Method.ContainingType.ExtensionParameter.Type.IsValidNullableTypeArgument() || + !Conversions.ConvertExtensionMethodThisArg(MakeNullable(candidate.Method.ContainingType.ExtensionParameter.Type), operand.Type, ref useSiteInfo, isMethodGroupConversion: false).Exists) + { + return false; + } + } + else if (!Conversions.ConvertExtensionMethodThisArg(candidate.Method.ContainingType.ExtensionParameter.Type, operand.Type, ref useSiteInfo, isMethodGroupConversion: false).Exists) + { + return false; + } + + return true; + } + } } } diff --git a/src/Compilers/CSharp/Portable/Binder/Semantics/Operators/BinaryOperatorSignature.cs b/src/Compilers/CSharp/Portable/Binder/Semantics/Operators/BinaryOperatorSignature.cs index 19e732246b906..628f9e79e33a5 100644 --- a/src/Compilers/CSharp/Portable/Binder/Semantics/Operators/BinaryOperatorSignature.cs +++ b/src/Compilers/CSharp/Portable/Binder/Semantics/Operators/BinaryOperatorSignature.cs @@ -63,7 +63,7 @@ public bool Equals(BinaryOperatorSignature other) TypeSymbol.Equals(this.LeftType, other.LeftType, TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(this.RightType, other.RightType, TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(this.ReturnType, other.ReturnType, TypeCompareKind.ConsiderEverything2) && - this.Method == other.Method; + Symbol.Equals(this.Method, other.Method, TypeCompareKind.ConsiderEverything); } public static bool operator ==(BinaryOperatorSignature x, BinaryOperatorSignature y) diff --git a/src/Compilers/CSharp/Portable/Binder/Semantics/Operators/UnaryOperatorOverloadResolution.cs b/src/Compilers/CSharp/Portable/Binder/Semantics/Operators/UnaryOperatorOverloadResolution.cs index 2085f07fa3b12..f4eb223b6c22f 100644 --- a/src/Compilers/CSharp/Portable/Binder/Semantics/Operators/UnaryOperatorOverloadResolution.cs +++ b/src/Compilers/CSharp/Portable/Binder/Semantics/Operators/UnaryOperatorOverloadResolution.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; @@ -20,7 +21,14 @@ private NamedTypeSymbol MakeNullable(TypeSymbol type) return Compilation.GetSpecialType(SpecialType.System_Nullable_T).Construct(type); } - public void UnaryOperatorOverloadResolution(UnaryOperatorKind kind, bool isChecked, BoundExpression operand, UnaryOperatorOverloadResolutionResult result, ref CompoundUseSiteInfo useSiteInfo) + public void UnaryOperatorOverloadResolution( + UnaryOperatorKind kind, + bool isChecked, + string name1, + string name2Opt, + BoundExpression operand, + UnaryOperatorOverloadResolutionResult result, + ref CompoundUseSiteInfo useSiteInfo) { Debug.Assert(operand != null); Debug.Assert(result.Results.Count == 0); @@ -38,7 +46,7 @@ public void UnaryOperatorOverloadResolution(UnaryOperatorKind kind, bool isCheck // SPEC: The set of candidate user-defined operators provided by X for the operation operator // SPEC: op(x) is determined using the rules of 7.3.5. - bool hadUserDefinedCandidate = GetUserDefinedOperators(kind, isChecked, operand, result.Results, ref useSiteInfo); + bool hadUserDefinedCandidate = GetUserDefinedOperators(kind, isChecked, name1, name2Opt, operand, result.Results, ref useSiteInfo); // SPEC: If the set of candidate user-defined operators is not empty, then this becomes the // SPEC: set of candidate operators for the operation. Otherwise, the predefined unary operator @@ -59,6 +67,233 @@ public void UnaryOperatorOverloadResolution(UnaryOperatorKind kind, bool isCheck UnaryOperatorOverloadResolution(operand, result, ref useSiteInfo); } +#nullable enable + + public bool UnaryOperatorExtensionOverloadResolutionInSingleScope( + ArrayBuilder extensionDeclarationsInSingleScope, + UnaryOperatorKind kind, + bool isChecked, + string name1, + string? name2Opt, + BoundExpression operand, + UnaryOperatorOverloadResolutionResult result, + ref CompoundUseSiteInfo useSiteInfo) + { + Debug.Assert(isChecked || name2Opt is null); + Debug.Assert(operand.Type is not null); + + var operators = ArrayBuilder.GetInstance(); + + getDeclaredUserDefinedUnaryOperatorsInScope(extensionDeclarationsInSingleScope, kind, name1, name2Opt, operators); + + if (operand.Type.IsNullableType()) // Wouldn't be applicable to the receiver type otherwise + { + AddLiftedUserDefinedUnaryOperators(constrainedToTypeOpt: null, kind, operators); + } + + inferTypeArgumentsAndRemoveInapplicableToReceiverType(kind, operand, operators, ref useSiteInfo); + + bool hadApplicableCandidates = false; + + if (!operators.IsEmpty) + { + var results = result.Results; + results.Clear(); + if (CandidateOperators(isChecked, operators, operand, results, ref useSiteInfo)) + { + UnaryOperatorOverloadResolution(operand, result, ref useSiteInfo); + hadApplicableCandidates = true; + } + } + + operators.Free(); + + return hadApplicableCandidates; + + static void getDeclaredUserDefinedUnaryOperatorsInScope(ArrayBuilder extensionDeclarationsInSingleScope, UnaryOperatorKind kind, string name1, string? name2Opt, ArrayBuilder operators) + { + getDeclaredUserDefinedUnaryOperators(extensionDeclarationsInSingleScope, kind, name1, operators); + + if (name2Opt is not null) + { + if (!operators.IsEmpty) + { + var existing = new HashSet(PairedExtensionOperatorSignatureComparer.Instance); + existing.AddRange(operators.Select(static (op) => op.Method)); + + var operators2 = ArrayBuilder.GetInstance(); + getDeclaredUserDefinedUnaryOperators(extensionDeclarationsInSingleScope, kind, name2Opt, operators2); + + foreach (var op in operators2) + { + if (!existing.Contains(op.Method)) + { + operators.Add(op); + } + } + + operators2.Free(); + } + else + { + getDeclaredUserDefinedUnaryOperators(extensionDeclarationsInSingleScope, kind, name2Opt, operators); + } + } + } + + static void getDeclaredUserDefinedUnaryOperators(ArrayBuilder extensionDeclarationsInSingleScope, UnaryOperatorKind kind, string name, ArrayBuilder operators) + { + foreach (NamedTypeSymbol extensionDeclaration in extensionDeclarationsInSingleScope) + { + Debug.Assert(extensionDeclaration.IsExtension); + + if (extensionDeclaration.ExtensionParameter is null) + { + continue; + } + + GetDeclaredUserDefinedUnaryOperators(constrainedToTypeOpt: null, extensionDeclaration, kind, name, operators); + } + } + + void inferTypeArgumentsAndRemoveInapplicableToReceiverType(UnaryOperatorKind kind, BoundExpression operand, ArrayBuilder operators, ref CompoundUseSiteInfo useSiteInfo) + { + for (int i = operators.Count - 1; i >= 0; i--) + { + var candidate = operators[i]; + MethodSymbol method = candidate.Method; + NamedTypeSymbol extension = method.ContainingType; + + if (extension.Arity == 0) + { + if (isApplicableToReceiver(in candidate, operand, ref useSiteInfo)) + { + continue; + } + } + else + { + // Infer type arguments + var inferenceResult = MethodTypeInferrer.Infer( + _binder, + this.Conversions, + extension.TypeParameters, + extension, + [TypeWithAnnotations.Create(candidate.OperandType)], + method.ParameterRefKinds, + [operand], + ref useSiteInfo, + ordinals: null); + + if (inferenceResult.Success) + { + extension = extension.Construct(inferenceResult.InferredTypeArguments); + method = method.AsMember(extension); + + if (!FailsConstraintChecks(method, out ArrayBuilder constraintFailureDiagnosticsOpt, template: CompoundUseSiteInfo.Discarded)) + { + TypeSymbol operandType = method.GetParameterType(0); + TypeSymbol resultType = method.ReturnType; + + UnaryOperatorSignature inferredCandidate; + + if (candidate.Kind.IsLifted()) + { + inferredCandidate = new UnaryOperatorSignature(UnaryOperatorKind.Lifted | UnaryOperatorKind.UserDefined | kind, MakeNullable(operandType), MakeNullable(resultType), method, constrainedToTypeOpt: null); + } + else + { + inferredCandidate = new UnaryOperatorSignature(UnaryOperatorKind.UserDefined | kind, operandType, resultType, method, constrainedToTypeOpt: null); + } + + if (isApplicableToReceiver(in inferredCandidate, operand, ref useSiteInfo)) + { + operators[i] = inferredCandidate; + continue; + } + } + + constraintFailureDiagnosticsOpt?.Free(); + } + } + + operators.RemoveAt(i); + } + } + + bool isApplicableToReceiver(in UnaryOperatorSignature candidate, BoundExpression operand, ref CompoundUseSiteInfo useSiteInfo) + { + Debug.Assert(operand.Type is not null); + Debug.Assert(candidate.Method.ContainingType.ExtensionParameter is not null); + + if (candidate.Kind.IsLifted()) + { + Debug.Assert(operand.Type.IsNullableType()); + + if (!candidate.Method.ContainingType.ExtensionParameter.Type.IsValidNullableTypeArgument() || + !Conversions.ConvertExtensionMethodThisArg(MakeNullable(candidate.Method.ContainingType.ExtensionParameter.Type), operand.Type, ref useSiteInfo, isMethodGroupConversion: false).Exists) + { + return false; + } + } + else if (!Conversions.ConvertExtensionMethodThisArg(candidate.Method.ContainingType.ExtensionParameter.Type, operand.Type, ref useSiteInfo, isMethodGroupConversion: false).Exists) + { + return false; // Conversion to 'this' parameter failed + } + + return true; + } + } + + internal class PairedExtensionOperatorSignatureComparer : IEqualityComparer + { + public static readonly PairedExtensionOperatorSignatureComparer Instance = new PairedExtensionOperatorSignatureComparer(); + + private PairedExtensionOperatorSignatureComparer() { } + + public bool Equals(MethodSymbol? x, MethodSymbol? y) + { + Debug.Assert(x is { }); + Debug.Assert(y is { }); + + if (x.OriginalDefinition.ContainingType.ContainingType != (object)x.OriginalDefinition.ContainingType.ContainingType) + { + return false; + } + + var xGroupingKey = new SourceMemberContainerTypeSymbol.ExtensionGroupingKey(x.OriginalDefinition.ContainingType); + var yGroupingKey = new SourceMemberContainerTypeSymbol.ExtensionGroupingKey(y.OriginalDefinition.ContainingType); + + if (!xGroupingKey.Equals(yGroupingKey)) + { + return false; + } + + return SourceMemberContainerTypeSymbol.DoOperatorsPair( + x.OriginalDefinition.AsMember(xGroupingKey.NormalizedExtension), + y.OriginalDefinition.AsMember(yGroupingKey.NormalizedExtension)); + } + + public int GetHashCode(MethodSymbol op) + { + var typeComparer = Symbols.SymbolEqualityComparer.AllIgnoreOptions; + + int result = typeComparer.GetHashCode(op.OriginalDefinition.ContainingType.ContainingType); + + var groupingKey = new SourceMemberContainerTypeSymbol.ExtensionGroupingKey(op.OriginalDefinition.ContainingType); + result = Hash.Combine(result, groupingKey.GetHashCode()); + + foreach (var parameter in op.OriginalDefinition.AsMember(groupingKey.NormalizedExtension).Parameters) + { + result = Hash.Combine(result, typeComparer.GetHashCode(parameter.Type)); + } + + return result; + } + } + +#nullable disable + // Takes a list of candidates and mutates the list to throw out the ones that are worse than // another applicable candidate. private void UnaryOperatorOverloadResolution( @@ -200,6 +435,19 @@ private BetterResult BetterOperator(UnaryOperatorSignature op1, UnaryOperatorSig if (Conversions.HasIdentityConversion(op1.OperandType, op2.OperandType)) { + // SPEC: If Mp is a non-generic method and Mq is a generic method, then Mp is better than Mq. + if (op1.Method?.GetMemberArityIncludingExtension() is null or 0) + { + if (op2.Method?.GetMemberArityIncludingExtension() > 0) + { + return BetterResult.Left; + } + } + else if (op2.Method?.GetMemberArityIncludingExtension() is null or 0) + { + return BetterResult.Right; + } + // SPEC: If Mp has more specific parameter types than Mq then Mp is better than Mq. // Under what circumstances can two unary operators with identical signatures be "more specific" @@ -344,7 +592,14 @@ private void GetEnumOperations(UnaryOperatorKind kind, BoundExpression operand, } // Returns true if there were any applicable candidates. - private bool GetUserDefinedOperators(UnaryOperatorKind kind, bool isChecked, BoundExpression operand, ArrayBuilder results, ref CompoundUseSiteInfo useSiteInfo) + private bool GetUserDefinedOperators( + UnaryOperatorKind kind, + bool isChecked, + string name1, + string name2Opt, + BoundExpression operand, + ArrayBuilder results, + ref CompoundUseSiteInfo useSiteInfo) { Debug.Assert(operand != null); @@ -403,7 +658,7 @@ private bool GetUserDefinedOperators(UnaryOperatorKind kind, bool isChecked, Bou { operators.Clear(); - GetUserDefinedUnaryOperatorsFromType(constrainedToTypeOpt, current, kind, isChecked, operators); + GetUserDefinedUnaryOperatorsFromType(constrainedToTypeOpt, current, kind, name1, name2Opt, operators); results.Clear(); if (CandidateOperators(isChecked, operators, operand, results, ref useSiteInfo)) @@ -448,7 +703,7 @@ private bool GetUserDefinedOperators(UnaryOperatorKind kind, bool isChecked, Bou operators.Clear(); resultsFromInterface.Clear(); - GetUserDefinedUnaryOperatorsFromType(constrainedToTypeOpt, @interface, kind, isChecked, operators); + GetUserDefinedUnaryOperatorsFromType(constrainedToTypeOpt, @interface, kind, name1, name2Opt, operators); if (CandidateOperators(isChecked, operators, operand, resultsFromInterface, ref useSiteInfo)) { hadApplicableCandidates = true; @@ -469,26 +724,40 @@ private bool GetUserDefinedOperators(UnaryOperatorKind kind, bool isChecked, Bou return hadApplicableCandidates; } +#nullable enable + + internal static void GetStaticUserDefinedUnaryOperatorMethodNames(UnaryOperatorKind kind, bool isChecked, out string name1, out string? name2Opt) + { + name1 = OperatorFacts.UnaryOperatorNameFromOperatorKind(kind, isChecked); + + if (isChecked && SyntaxFacts.IsCheckedOperator(name1)) + { + name2Opt = OperatorFacts.UnaryOperatorNameFromOperatorKind(kind, isChecked: false); + } + else + { + name2Opt = null; + } + } + private void GetUserDefinedUnaryOperatorsFromType( TypeSymbol constrainedToTypeOpt, NamedTypeSymbol type, UnaryOperatorKind kind, - bool isChecked, + string name1, + string? name2Opt, ArrayBuilder operators) { Debug.Assert(operators.Count == 0); - string name1 = OperatorFacts.UnaryOperatorNameFromOperatorKind(kind, isChecked); + GetDeclaredUserDefinedUnaryOperators(constrainedToTypeOpt, type, kind, name1, operators); - getDeclaredOperators(constrainedToTypeOpt, type, kind, name1, operators); - - if (isChecked && SyntaxFacts.IsCheckedOperator(name1)) + if (name2Opt is not null) { - string name2 = OperatorFacts.UnaryOperatorNameFromOperatorKind(kind, isChecked: false); var operators2 = ArrayBuilder.GetInstance(); // Add regular operators as well. - getDeclaredOperators(constrainedToTypeOpt, type, kind, name2, operators2); + GetDeclaredUserDefinedUnaryOperators(constrainedToTypeOpt, type, kind, name2Opt, operators2); // Drop operators that have a match among the checked ones. if (operators.Count != 0) @@ -510,63 +779,63 @@ private void GetUserDefinedUnaryOperatorsFromType( operators2.Free(); } - addLiftedOperators(constrainedToTypeOpt, kind, operators); + AddLiftedUserDefinedUnaryOperators(constrainedToTypeOpt, kind, operators); + } + + private static void GetDeclaredUserDefinedUnaryOperators(TypeSymbol? constrainedToTypeOpt, NamedTypeSymbol type, UnaryOperatorKind kind, string name, ArrayBuilder operators) + { + var typeOperators = ArrayBuilder.GetInstance(); + type.AddOperators(name, typeOperators); - static void getDeclaredOperators(TypeSymbol constrainedToTypeOpt, NamedTypeSymbol type, UnaryOperatorKind kind, string name, ArrayBuilder operators) + foreach (MethodSymbol op in typeOperators) { - var typeOperators = ArrayBuilder.GetInstance(); - type.AddOperators(name, typeOperators); - - foreach (MethodSymbol op in typeOperators) + // If we're in error recovery, we might have bad operators. Just ignore it. + if (op.ParameterCount != 1 || op.ReturnsVoid) { - // If we're in error recovery, we might have bad operators. Just ignore it. - if (op.ParameterCount != 1 || op.ReturnsVoid) - { - continue; - } - - TypeSymbol operandType = op.GetParameterType(0); - TypeSymbol resultType = op.ReturnType; - - operators.Add(new UnaryOperatorSignature(UnaryOperatorKind.UserDefined | kind, operandType, resultType, op, constrainedToTypeOpt)); + continue; } - typeOperators.Free(); + TypeSymbol operandType = op.GetParameterType(0); + TypeSymbol resultType = op.ReturnType; + + operators.Add(new UnaryOperatorSignature(UnaryOperatorKind.UserDefined | kind, operandType, resultType, op, constrainedToTypeOpt)); } - void addLiftedOperators(TypeSymbol constrainedToTypeOpt, UnaryOperatorKind kind, ArrayBuilder operators) + typeOperators.Free(); + } + + private void AddLiftedUserDefinedUnaryOperators(TypeSymbol? constrainedToTypeOpt, UnaryOperatorKind kind, ArrayBuilder operators) + { + // SPEC: For the unary operators + ++ - -- ! ~ a lifted form of an operator exists + // SPEC: if the operand and its result types are both non-nullable value types. + // SPEC: The lifted form is constructed by adding a single ? modifier to the + // SPEC: operator and result types. + switch (kind) { - // SPEC: For the unary operators + ++ - -- ! ~ a lifted form of an operator exists - // SPEC: if the operand and its result types are both non-nullable value types. - // SPEC: The lifted form is constructed by adding a single ? modifier to the - // SPEC: operator and result types. - switch (kind) - { - case UnaryOperatorKind.UnaryPlus: - case UnaryOperatorKind.PrefixDecrement: - case UnaryOperatorKind.PrefixIncrement: - case UnaryOperatorKind.UnaryMinus: - case UnaryOperatorKind.PostfixDecrement: - case UnaryOperatorKind.PostfixIncrement: - case UnaryOperatorKind.LogicalNegation: - case UnaryOperatorKind.BitwiseComplement: - - for (int i = operators.Count - 1; i >= 0; i--) - { - MethodSymbol op = operators[i].Method; - TypeSymbol operandType = op.GetParameterType(0); - TypeSymbol resultType = op.ReturnType; + case UnaryOperatorKind.UnaryPlus: + case UnaryOperatorKind.PrefixDecrement: + case UnaryOperatorKind.PrefixIncrement: + case UnaryOperatorKind.UnaryMinus: + case UnaryOperatorKind.PostfixDecrement: + case UnaryOperatorKind.PostfixIncrement: + case UnaryOperatorKind.LogicalNegation: + case UnaryOperatorKind.BitwiseComplement: - if (operandType.IsValidNullableTypeArgument() && - resultType.IsValidNullableTypeArgument()) - { - operators.Add(new UnaryOperatorSignature( - UnaryOperatorKind.Lifted | UnaryOperatorKind.UserDefined | kind, - MakeNullable(operandType), MakeNullable(resultType), op, constrainedToTypeOpt)); - } + for (int i = operators.Count - 1; i >= 0; i--) + { + MethodSymbol op = operators[i].Method; + TypeSymbol operandType = op.GetParameterType(0); + TypeSymbol resultType = op.ReturnType; + + if (operandType.IsValidNullableTypeArgument() && + resultType.IsValidNullableTypeArgument()) + { + operators.Add(new UnaryOperatorSignature( + UnaryOperatorKind.Lifted | UnaryOperatorKind.UserDefined | kind, + MakeNullable(operandType), MakeNullable(resultType), op, constrainedToTypeOpt)); } - break; - } + } + break; } } } diff --git a/src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/OverloadResolution.cs b/src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/OverloadResolution.cs index 9a42ca2d20e14..ab854182e00cb 100644 --- a/src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/OverloadResolution.cs +++ b/src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/OverloadResolution.cs @@ -10,9 +10,9 @@ using System.Diagnostics; using System.Linq; using Microsoft.Cci; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; @@ -4560,13 +4560,19 @@ private MemberAnalysisResult IsApplicable( if (forExtensionMethodThisArg) { - Debug.Assert(argumentRefKind == RefKind.None); - if (parameterRefKind == RefKind.Ref) + if (argumentRefKind == RefKind.None) { - // For ref extension methods, we omit the "ref" modifier on the receiver arguments - // Passing the parameter RefKind for finding the correct conversion. - // For ref-readonly extension methods, argumentRefKind is always None. - argumentRefKind = parameterRefKind; + if (parameterRefKind == RefKind.Ref) + { + // For ref extension methods, we omit the "ref" modifier on the receiver arguments + // Passing the parameter RefKind for finding the correct conversion. + // For ref-readonly extension methods, argumentRefKind is always None. + argumentRefKind = parameterRefKind; + } + } + else + { + Debug.Assert(candidate is MethodSymbol { MethodKind: MethodKind.UserDefinedOperator }); } } diff --git a/src/Compilers/CSharp/Portable/Binder/SwitchExpressionBinder.cs b/src/Compilers/CSharp/Portable/Binder/SwitchExpressionBinder.cs index 73ff46d298ef9..a1cad682cb94e 100644 --- a/src/Compilers/CSharp/Portable/Binder/SwitchExpressionBinder.cs +++ b/src/Compilers/CSharp/Portable/Binder/SwitchExpressionBinder.cs @@ -5,10 +5,10 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Shared.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp diff --git a/src/Compilers/CSharp/Portable/BoundTree/BoundDecisionDag.cs b/src/Compilers/CSharp/Portable/BoundTree/BoundDecisionDag.cs index 1deac891fe1d9..181d6aad426b1 100644 --- a/src/Compilers/CSharp/Portable/BoundTree/BoundDecisionDag.cs +++ b/src/Compilers/CSharp/Portable/BoundTree/BoundDecisionDag.cs @@ -9,9 +9,9 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Shared.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp diff --git a/src/Compilers/CSharp/Portable/BoundTree/BoundExpression.cs b/src/Compilers/CSharp/Portable/BoundTree/BoundExpression.cs index 06204dd5e723a..5f484eb0cd70b 100644 --- a/src/Compilers/CSharp/Portable/BoundTree/BoundExpression.cs +++ b/src/Compilers/CSharp/Portable/BoundTree/BoundExpression.cs @@ -418,6 +418,13 @@ internal partial class BoundBinaryOperator internal partial class BoundUserDefinedConditionalLogicalOperator { + private partial void Validate() + { + Debug.Assert(LogicalOperator.ParameterCount == 2); + Debug.Assert(TrueOperator.ParameterCount == 1); + Debug.Assert(FalseOperator.ParameterCount == 1); + } + public override Symbol ExpressionSymbol { get { return this.LogicalOperator; } diff --git a/src/Compilers/CSharp/Portable/BoundTree/BoundMethodDefIndex.cs b/src/Compilers/CSharp/Portable/BoundTree/BoundMethodDefIndex.cs new file mode 100644 index 0000000000000..1c15feea0b816 --- /dev/null +++ b/src/Compilers/CSharp/Portable/BoundTree/BoundMethodDefIndex.cs @@ -0,0 +1,16 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp +{ + internal partial class BoundMethodDefIndex + { + private partial void Validate() + { + Debug.Assert(Method.IsDefinition); + } + } +} diff --git a/src/Compilers/CSharp/Portable/BoundTree/BoundNodes.xml b/src/Compilers/CSharp/Portable/BoundTree/BoundNodes.xml index df26f273ec1d1..09913bb162695 100644 --- a/src/Compilers/CSharp/Portable/BoundTree/BoundNodes.xml +++ b/src/Compilers/CSharp/Portable/BoundTree/BoundNodes.xml @@ -496,7 +496,7 @@ - + @@ -518,7 +518,7 @@ - + @@ -746,7 +746,7 @@ - + diff --git a/src/Compilers/CSharp/Portable/BoundTree/NullabilityRewriter.cs b/src/Compilers/CSharp/Portable/BoundTree/NullabilityRewriter.cs index fe7f968060731..7f279795b1e8e 100644 --- a/src/Compilers/CSharp/Portable/BoundTree/NullabilityRewriter.cs +++ b/src/Compilers/CSharp/Portable/BoundTree/NullabilityRewriter.cs @@ -104,8 +104,20 @@ private BoundNode VisitBinaryOperatorBase(BoundBinaryOperatorBase binaryOperator leftChild, right, type!), - // https://github.com/dotnet/roslyn/issues/35031: We'll need to update logical.LogicalOperator - BoundUserDefinedConditionalLogicalOperator logical => logical.Update(logical.OperatorKind, logical.LogicalOperator, logical.TrueOperator, logical.FalseOperator, logical.TrueFalseOperandPlaceholder, logical.TrueFalseOperandConversion, logical.ConstrainedToTypeOpt, logical.ResultKind, logical.OriginalUserDefinedOperatorsOpt, leftChild, right, type!), + + BoundUserDefinedConditionalLogicalOperator logical => logical.Update( + logical.OperatorKind, + GetUpdatedSymbol(logical, logical.LogicalOperator), + logical.TrueOperator, + logical.FalseOperator, + logical.TrueFalseOperandPlaceholder, + logical.TrueFalseOperandConversion, + logical.ConstrainedToTypeOpt, + logical.ResultKind, + logical.OriginalUserDefinedOperatorsOpt, + leftChild, + right, + type!), _ => throw ExceptionUtilities.UnexpectedValue(currentBinary.Kind), }; @@ -122,6 +134,36 @@ private BoundNode VisitBinaryOperatorBase(BoundBinaryOperatorBase binaryOperator return currentBinary!; } + public override BoundNode? VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) + { + ImmutableArray originalUserDefinedOperatorsOpt = GetUpdatedArray(node, node.OriginalUserDefinedOperatorsOpt); + BoundExpression left = (BoundExpression)this.Visit(node.Left); + BoundExpression right = (BoundExpression)this.Visit(node.Right); + BoundValuePlaceholder? leftPlaceholder = node.LeftPlaceholder; + BoundExpression? leftConversion = node.LeftConversion; + BoundValuePlaceholder? finalPlaceholder = node.FinalPlaceholder; + BoundExpression? finalConversion = node.FinalConversion; + BoundCompoundAssignmentOperator updatedNode; + + var op = node.Operator; + + if (op.Method is not null) + { + op = new BinaryOperatorSignature(op.Kind, op.LeftType, op.RightType, op.ReturnType, GetUpdatedSymbol(node, op.Method), op.ConstrainedToTypeOpt); + } + + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo Info, TypeSymbol? Type) infoAndType)) + { + updatedNode = node.Update(op, left, right, leftPlaceholder, leftConversion, finalPlaceholder, finalConversion, node.ResultKind, originalUserDefinedOperatorsOpt, infoAndType.Type!); + updatedNode.TopLevelNullability = infoAndType.Info; + } + else + { + updatedNode = node.Update(op, left, right, leftPlaceholder, leftConversion, finalPlaceholder, finalConversion, node.ResultKind, originalUserDefinedOperatorsOpt, node.Type); + } + return updatedNode; + } + private T GetUpdatedSymbol(BoundNode expr, T sym) where T : Symbol? { if (sym is null) return sym; diff --git a/src/Compilers/CSharp/Portable/CSharpResources.resx b/src/Compilers/CSharp/Portable/CSharpResources.resx index ced190df61062..04dad7cc7f1d0 100644 --- a/src/Compilers/CSharp/Portable/CSharpResources.resx +++ b/src/Compilers/CSharp/Portable/CSharpResources.resx @@ -1601,7 +1601,7 @@ If such a class is used as a base class and if the deriving class defines a dest Predefined type '{0}' is not defined or imported - + Predefined type '{0}' is declared in multiple referenced assemblies: '{1}' and '{2}' @@ -1806,7 +1806,7 @@ If such a class is used as a base class and if the deriving class defines a dest Invalid value for named attribute argument '{0}' - The DllImport attribute must be specified on a method marked 'static' and 'extern' + The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member Cannot emit update; {0} '{1}' is missing. @@ -8188,4 +8188,31 @@ To remove the warning, you can use /reference instead (set the Embed Interop Typ An extension member syntax is disallowed in nested position within an extension member syntax + + Extension members are not allowed as an argument to 'nameof'. + + + The parameter of a unary operator must be the extended type. + + + The parameter type for ++ or -- operator must be the extended type. + + + One of the parameters of a binary operator must be the extended type. + + + The first operand of an overloaded shift operator must have the same type as the extended type + + + An extension block extending a static class cannot contain user-defined operators + + + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + + + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + + + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + diff --git a/src/Compilers/CSharp/Portable/CodeGen/EmitExpression.cs b/src/Compilers/CSharp/Portable/CodeGen/EmitExpression.cs index f54ef8c053578..86b3e463535e1 100644 --- a/src/Compilers/CSharp/Portable/CodeGen/EmitExpression.cs +++ b/src/Compilers/CSharp/Portable/CodeGen/EmitExpression.cs @@ -3565,7 +3565,7 @@ private void EmitParameterIdExpression(BoundParameterId node) if (node.HoistedField is null) { - _builder.EmitIntConstant(node.Parameter.Ordinal); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Follow up + _builder.EmitIntConstant(node.Parameter.Ordinal); // Tracked by https://github.com/dotnet/roslyn/issues/78963 : Follow up } else { diff --git a/src/Compilers/CSharp/Portable/Compilation/CSharpDeterministicKeyBuilder.cs b/src/Compilers/CSharp/Portable/Compilation/CSharpDeterministicKeyBuilder.cs index 29e2bee7f183b..67dba337835d8 100644 --- a/src/Compilers/CSharp/Portable/Compilation/CSharpDeterministicKeyBuilder.cs +++ b/src/Compilers/CSharp/Portable/Compilation/CSharpDeterministicKeyBuilder.cs @@ -3,8 +3,7 @@ // See the LICENSE file in the project root for more information. using System; -using System.Collections.Generic; -using System.Text; +using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp diff --git a/src/Compilers/CSharp/Portable/Compilation/CSharpSemanticModel.cs b/src/Compilers/CSharp/Portable/Compilation/CSharpSemanticModel.cs index dcdc84c7f6706..757547a9ba86b 100644 --- a/src/Compilers/CSharp/Portable/Compilation/CSharpSemanticModel.cs +++ b/src/Compilers/CSharp/Portable/Compilation/CSharpSemanticModel.cs @@ -10,6 +10,7 @@ using System.Diagnostics; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; @@ -3371,7 +3372,7 @@ private OneOrMany GetSemanticSymbols( case BoundKind.PropertyGroup: symbols = GetPropertyGroupSemanticSymbols((BoundPropertyGroup)boundNode, boundNodeForSyntacticParent, binderOpt, out resultKind, out memberGroup); break; - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : handle BoundPropertyAccess (which now may have a member group) + // Tracked by https://github.com/dotnet/roslyn/issues/78957 : public API, consider handling BoundPropertyAccess (which now may have a member group) case BoundKind.BadExpression: { diff --git a/src/Compilers/CSharp/Portable/Compilation/MemberSemanticModel.cs b/src/Compilers/CSharp/Portable/Compilation/MemberSemanticModel.cs index 1d90cfbda29fd..c47758ddfb516 100644 --- a/src/Compilers/CSharp/Portable/Compilation/MemberSemanticModel.cs +++ b/src/Compilers/CSharp/Portable/Compilation/MemberSemanticModel.cs @@ -11,6 +11,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Operations; diff --git a/src/Compilers/CSharp/Portable/Compilation/SymbolInfoFactory.cs b/src/Compilers/CSharp/Portable/Compilation/SymbolInfoFactory.cs index ad650e8980a15..01f91ced2c5cf 100644 --- a/src/Compilers/CSharp/Portable/Compilation/SymbolInfoFactory.cs +++ b/src/Compilers/CSharp/Portable/Compilation/SymbolInfoFactory.cs @@ -8,6 +8,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/Compilers/CSharp/Portable/Declarations/MergedTypeDeclaration.cs b/src/Compilers/CSharp/Portable/Declarations/MergedTypeDeclaration.cs index 54f19e2e69e0b..c7849169701f9 100644 --- a/src/Compilers/CSharp/Portable/Declarations/MergedTypeDeclaration.cs +++ b/src/Compilers/CSharp/Portable/Declarations/MergedTypeDeclaration.cs @@ -8,6 +8,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/Emitter/Model/MethodSymbolAdapter.cs b/src/Compilers/CSharp/Portable/Emitter/Model/MethodSymbolAdapter.cs index 5ec5fde9c5af4..9d811e630d82d 100644 --- a/src/Compilers/CSharp/Portable/Emitter/Model/MethodSymbolAdapter.cs +++ b/src/Compilers/CSharp/Portable/Emitter/Model/MethodSymbolAdapter.cs @@ -395,7 +395,7 @@ bool Cci.IMethodDefinition.IsExternal { CheckDefinitionInvariant(); - return AdaptedMethodSymbol.IsExternal; + return !AdaptedMethodSymbol.ContainingType.IsExtension && AdaptedMethodSymbol.IsExternal; } } @@ -422,7 +422,7 @@ bool Cci.IMethodDefinition.IsPlatformInvoke get { CheckDefinitionInvariant(); - return AdaptedMethodSymbol.GetDllImportData() != null; + return !AdaptedMethodSymbol.ContainingType.IsExtension && AdaptedMethodSymbol.GetDllImportData() != null; } } #nullable disable @@ -431,14 +431,14 @@ Cci.IPlatformInvokeInformation Cci.IMethodDefinition.PlatformInvokeData get { CheckDefinitionInvariant(); - return AdaptedMethodSymbol.GetDllImportData(); + return AdaptedMethodSymbol.ContainingType.IsExtension ? null : AdaptedMethodSymbol.GetDllImportData(); } } System.Reflection.MethodImplAttributes Cci.IMethodDefinition.GetImplementationAttributes(EmitContext context) { CheckDefinitionInvariant(); - return AdaptedMethodSymbol.ImplementationAttributes; + return AdaptedMethodSymbol.ContainingType.IsExtension ? default : AdaptedMethodSymbol.ImplementationAttributes; } bool Cci.IMethodDefinition.IsRuntimeSpecial diff --git a/src/Compilers/CSharp/Portable/Errors/ErrorCode.cs b/src/Compilers/CSharp/Portable/Errors/ErrorCode.cs index 3db0d158c3a63..2b1bd65a866c4 100644 --- a/src/Compilers/CSharp/Portable/Errors/ErrorCode.cs +++ b/src/Compilers/CSharp/Portable/Errors/ErrorCode.cs @@ -1544,7 +1544,7 @@ internal enum ErrorCode ERR_OutAttrOnInParam = 8355, #endregion diagnostics introduced for `ref readonly`, `ref conditional` and `ref-like` features in C# 7.2 - ERR_PredefinedValueTupleTypeAmbiguous3 = 8356, + ERR_PredefinedTypeAmbiguous = 8356, ERR_InvalidVersionFormatDeterministic = 8357, ERR_AttributeCtorInParameter = 8358, @@ -2409,6 +2409,16 @@ internal enum ErrorCode ERR_PPShebangInProjectBasedProgram = 9314, ERR_TooManyUserStrings_RestartRequired = 9315, + ERR_NameofExtensionMember = 9316, + + ERR_BadExtensionUnaryOperatorSignature = 9317, + ERR_BadExtensionIncDecSignature = 9318, + ERR_BadExtensionBinaryOperatorSignature = 9319, + ERR_BadExtensionShiftOperatorSignature = 9320, + ERR_OperatorInExtensionOfStaticClass = 9321, + ERR_InstanceOperatorStructExtensionWrongReceiverRefKind = 9322, + ERR_InstanceOperatorExtensionWrongReceiverType = 9323, + ERR_ExpressionTreeContainsExtensionBasedConditionalLogicalOperator = 9324, // Note: you will need to do the following after adding errors: // 1) Update ErrorFacts.IsBuildOnlyDiagnostic (src/Compilers/CSharp/Portable/Errors/ErrorFacts.cs) diff --git a/src/Compilers/CSharp/Portable/Errors/ErrorFacts.cs b/src/Compilers/CSharp/Portable/Errors/ErrorFacts.cs index 3b7d348d06638..40101888aabb9 100644 --- a/src/Compilers/CSharp/Portable/Errors/ErrorFacts.cs +++ b/src/Compilers/CSharp/Portable/Errors/ErrorFacts.cs @@ -1868,7 +1868,7 @@ or ErrorCode.ERR_EscapeVariable or ErrorCode.ERR_EscapeStackAlloc or ErrorCode.ERR_RefReturnThis or ErrorCode.ERR_OutAttrOnInParam - or ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3 + or ErrorCode.ERR_PredefinedTypeAmbiguous or ErrorCode.ERR_InvalidVersionFormatDeterministic or ErrorCode.ERR_AttributeCtorInParameter or ErrorCode.WRN_FilterIsConstantFalse @@ -2522,6 +2522,15 @@ or ErrorCode.ERR_CloseUnimplementedInterfaceMemberOperatorMismatch or ErrorCode.ERR_OperatorMismatchOnOverride or ErrorCode.ERR_BadCompoundAssignmentOpArgs or ErrorCode.ERR_PPShebangInProjectBasedProgram + or ErrorCode.ERR_NameofExtensionMember + or ErrorCode.ERR_BadExtensionUnaryOperatorSignature + or ErrorCode.ERR_BadExtensionIncDecSignature + or ErrorCode.ERR_BadExtensionBinaryOperatorSignature + or ErrorCode.ERR_BadExtensionShiftOperatorSignature + or ErrorCode.ERR_OperatorInExtensionOfStaticClass + or ErrorCode.ERR_InstanceOperatorStructExtensionWrongReceiverRefKind + or ErrorCode.ERR_InstanceOperatorExtensionWrongReceiverType + or ErrorCode.ERR_ExpressionTreeContainsExtensionBasedConditionalLogicalOperator => false, }; #pragma warning restore CS8524 // The switch expression does not handle some values of its input type (it is not exhaustive) involving an unnamed enum value. diff --git a/src/Compilers/CSharp/Portable/FlowAnalysis/AbstractFlowPass.cs b/src/Compilers/CSharp/Portable/FlowAnalysis/AbstractFlowPass.cs index f7c338a9b554a..87df26ed04d42 100644 --- a/src/Compilers/CSharp/Portable/FlowAnalysis/AbstractFlowPass.cs +++ b/src/Compilers/CSharp/Portable/FlowAnalysis/AbstractFlowPass.cs @@ -628,7 +628,7 @@ protected void VisitCondition(BoundExpression node) AdjustConditionalState(node); } - private void AdjustConditionalState(BoundExpression node) + protected void AdjustConditionalState(BoundExpression node) { if (IsConstantTrue(node)) { @@ -2450,14 +2450,36 @@ private void VisitBinaryLogicalOperatorChildren(BoundExpression node) stack.Push(binary); } + VisitBinaryLogicalOperatorChildren(stack); + stack.Free(); + } + + protected virtual void VisitBinaryLogicalOperatorChildren(ArrayBuilder stack) + { + BoundExpression binary; Debug.Assert(stack.Count > 0); + binary = stack.Pop(); + + BoundExpression child; + switch (binary.Kind) + { + case BoundKind.BinaryOperator: + var binOp = (BoundBinaryOperator)binary; + child = binOp.Left; + break; + case BoundKind.UserDefinedConditionalLogicalOperator: + var udBinOp = (BoundUserDefinedConditionalLogicalOperator)binary; + child = udBinOp.Left; + break; + default: + throw ExceptionUtilities.UnexpectedValue(binary.Kind); + } + VisitCondition(child); while (true) { - binary = stack.Pop(); - BinaryOperatorKind kind; BoundExpression right; switch (binary.Kind) @@ -2479,6 +2501,7 @@ private void VisitBinaryLogicalOperatorChildren(BoundExpression node) var op = kind.Operator(); var isAnd = op == BinaryOperatorKind.And; var isBool = kind.OperandTypes() == BinaryOperatorKind.Bool; + Debug.Assert(!isBool || binary.Kind != BoundKind.UserDefinedConditionalLogicalOperator); Debug.Assert(isAnd || op == BinaryOperatorKind.Or); @@ -2494,10 +2517,8 @@ private void VisitBinaryLogicalOperatorChildren(BoundExpression node) } AdjustConditionalState(binary); + binary = stack.Pop(); } - - Debug.Assert((object)binary == node); - stack.Free(); } protected virtual void AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression binary, BoundExpression right, bool isAnd, bool isBool, ref TLocalState leftTrue, ref TLocalState leftFalse) diff --git a/src/Compilers/CSharp/Portable/FlowAnalysis/ControlFlowPass.cs b/src/Compilers/CSharp/Portable/FlowAnalysis/ControlFlowPass.cs index c490fe273e06b..5ae593d4d07de 100644 --- a/src/Compilers/CSharp/Portable/FlowAnalysis/ControlFlowPass.cs +++ b/src/Compilers/CSharp/Portable/FlowAnalysis/ControlFlowPass.cs @@ -5,12 +5,11 @@ #nullable disable using System.Collections.Immutable; +using System.Collections.Generic; using System.Diagnostics; using System.Linq; -using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { diff --git a/src/Compilers/CSharp/Portable/FlowAnalysis/DefiniteAssignment.cs b/src/Compilers/CSharp/Portable/FlowAnalysis/DefiniteAssignment.cs index d865cdcbaafef..9a0abb4afede5 100644 --- a/src/Compilers/CSharp/Portable/FlowAnalysis/DefiniteAssignment.cs +++ b/src/Compilers/CSharp/Portable/FlowAnalysis/DefiniteAssignment.cs @@ -22,6 +22,7 @@ using System.Diagnostics; using System.Linq; using System.Text; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.DebugVerifier.cs b/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.DebugVerifier.cs index 22612b3c49caf..6ca44ec1fa896 100644 --- a/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.DebugVerifier.cs +++ b/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.DebugVerifier.cs @@ -123,9 +123,7 @@ private void VerifyExpression(BoundExpression expression, bool overrideSkippedEx return null; } - // See NullableWalker.VisitCollectionExpression.getCollectionDetails() which - // does not have an element type for the ImplementsIEnumerable case. - bool hasElementType = node.CollectionTypeKind is not (CollectionExpressionTypeKind.None or CollectionExpressionTypeKind.ImplementsIEnumerable); + bool hasElementType = node.CollectionTypeKind is not CollectionExpressionTypeKind.None; foreach (var element in node.Elements) { if (element is BoundCollectionExpressionSpreadElement spread) @@ -276,7 +274,8 @@ private void VisitForEachEnumeratorInfo(ForEachEnumeratorInfo enumeratorInfo) public override BoundNode? VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) { - if (node.LeftConversion is BoundConversion leftConversion) + if (node.LeftConversion is BoundConversion leftConversion && + !(node.Operator.Method is { IsStatic: false } method && method.GetIsNewExtensionMember())) { VerifyExpression(leftConversion); } diff --git a/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs b/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs index 7be3fd3d3ef48..b9f8452c5a4cb 100644 --- a/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs +++ b/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs @@ -3850,19 +3850,85 @@ protected override void VisitStatement(BoundStatement statement) var (collectionKind, targetElementType) = getCollectionDetails(node, node.Type); var resultBuilder = ArrayBuilder.GetInstance(node.Elements.Length); - var elementConversionCompletions = ArrayBuilder>.GetInstance(); + var elementConversionCompletions = ArrayBuilder>.GetInstance(); foreach (var element in node.Elements) + { + visitElement(element, node, targetElementType, elementConversionCompletions); + resultBuilder.Add(_visitResult); + } + + if (node.WasTargetTyped) + { + // We're in the context of a conversion, so the analysis of element conversions and the final visit result + // will be completed later (when that conversion is processed). + TargetTypedAnalysisCompletion[node] = + (TypeWithAnnotations resultTypeWithAnnotations) => convertCollection(node, resultTypeWithAnnotations, elementConversionCompletions); + } + else + { + // We're not in the context of a conversion, so don't expect any target-type information to be provided later, + // so we're done. For example, `[1, 2].ToString()`. + elementConversionCompletions.Free(); + } + + var resultType = TypeWithAnnotations.Create(node.Type); + var visitResult = new VisitResult(TypeWithState.Create(resultType), resultType, + nestedVisitResults: resultBuilder.ToArrayAndFree()); + + SetResult(node, visitResult, updateAnalyzedNullability: !node.WasTargetTyped, isLvalue: false); + return null; + + void visitElement(BoundNode element, BoundCollectionExpression node, TypeWithAnnotations targetElementType, ArrayBuilder> elementConversionCompletions) { switch (element) { case BoundCollectionElementInitializer initializer: - // We don't visit the Add methods - // But we should check conversion to the iteration type - // Tracked by https://github.com/dotnet/roslyn/issues/68786 + // The initializer generally represents a call to an Add method. + // We do not analyze the full call or all the arguments. + // We only analyze the single argument that represents the collection-expression element. SetUnknownResultNullability(initializer); Debug.Assert(node.Placeholder is { }); SetUnknownResultNullability(node.Placeholder); - VisitRvalue(initializer.Arguments[0]); + + var argIndex = initializer.AddMethod.IsExtensionMethod ? 1 : 0; + Debug.Assert(initializer.ArgsToParamsOpt.IsDefault); + var addArgument = initializer.Arguments[argIndex]; + VisitRvalue(addArgument); + var addArgumentResult = _visitResult; + + elementConversionCompletions.Add((_, targetCollectionType) => + { + // Reinfer the addMethod signature and convert the argument to parameter type + var addMethod = initializer.AddMethod; + MethodSymbol reinferredAddMethod; + if (!addMethod.IsExtensionMethod) + { + reinferredAddMethod = (MethodSymbol)AsMemberOfType(targetCollectionType, addMethod); + } + else + { + // https://github.com/dotnet/roslyn/issues/68786: reinfer type arguments of a generic extension Add method + reinferredAddMethod = addMethod; + } + + var reinferredParameter = reinferredAddMethod.Parameters[argIndex]; + var resultType = VisitConversion( + conversionOpt: null, + addArgument, + Conversion.Identity, // as only a nullable reinference is being done we expect an identity conversion + reinferredParameter.TypeWithAnnotations, + addArgumentResult.RValueType, + checkConversion: true, + fromExplicitCast: false, + useLegacyWarnings: false, + parameterOpt: reinferredParameter, + assignmentKind: AssignmentKind.Argument, + reportTopLevelWarnings: true, + reportRemainingWarnings: true, + trackMembers: false); + return resultType; + }); + break; case BoundCollectionExpressionSpreadElement spread: Visit(spread); @@ -3872,11 +3938,17 @@ spread.ElementPlaceholder is { } elementPlaceholder && { var itemResult = spread.EnumeratorInfoOpt == null ? default : _visitResult; var iteratorBody = ((BoundExpressionStatement)spread.IteratorBody).Expression; + + // Consider a collection expression like List x = [y, ..z] + // Lowering is comparable to the following: + // List __tmp = new(...); + // __tmp.Add(y); + // foreach (var z1 in z) + // __tmp.Add(z1); + // + // In other words, the spread contains a BoundCollectionElementInitializer which needs to be further deconstructed and 'z1' converted to 'TElem'. AddPlaceholderReplacement(elementPlaceholder, expression: elementPlaceholder, itemResult); - var completion = VisitOptionalImplicitConversion(iteratorBody, targetElementType, - useLegacyWarnings: false, trackMembers: false, AssignmentKind.Assignment, delayCompletionForTargetType: true).completion; - Debug.Assert(completion is not null); - elementConversionCompletions.Add(completion); + visitElement(iteratorBody, node, targetElementType, elementConversionCompletions); RemovePlaceholderReplacement(elementPlaceholder); } break; @@ -3892,36 +3964,13 @@ spread.ElementPlaceholder is { } elementPlaceholder && useLegacyWarnings: false, trackMembers: false, AssignmentKind.Assignment, delayCompletionForTargetType: true).completion; Debug.Assert(completion is not null); - elementConversionCompletions.Add(completion); + elementConversionCompletions.Add((elementType, _) => completion(elementType)); } break; } - - resultBuilder.Add(_visitResult); } - if (node.WasTargetTyped) - { - // We're in the context of a conversion, so the analysis of element conversions and the final visit result - // will be completed later (when that conversion is processed). - TargetTypedAnalysisCompletion[node] = - (TypeWithAnnotations resultTypeWithAnnotations) => convertCollection(node, resultTypeWithAnnotations, elementConversionCompletions); - } - else - { - // We're not in the context of a conversion, so don't expect any target-type information to be provided later, - // so we're done. For example, `[1, 2].ToString()`. - elementConversionCompletions.Free(); - } - - var resultType = TypeWithAnnotations.Create(node.Type); - var visitResult = new VisitResult(TypeWithState.Create(resultType), resultType, - nestedVisitResults: resultBuilder.ToArrayAndFree()); - - SetResult(node, visitResult, updateAnalyzedNullability: !node.WasTargetTyped, isLvalue: false); - return null; - - TypeWithState convertCollection(BoundCollectionExpression node, TypeWithAnnotations targetCollectionType, ArrayBuilder> completions) + TypeWithState convertCollection(BoundCollectionExpression node, TypeWithAnnotations targetCollectionType, ArrayBuilder> completions) { var strippedTargetCollectionType = targetCollectionType.Type.StrippedType(); Debug.Assert(TypeSymbol.Equals(strippedTargetCollectionType, node.Type, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); @@ -3937,7 +3986,7 @@ TypeWithState convertCollection(BoundCollectionExpression node, TypeWithAnnotati foreach (var completion in completions) { - _ = completion(targetElementType); + _ = completion(targetElementType, strippedTargetCollectionType); } completions.Free(); @@ -3975,6 +4024,11 @@ static NullableFlowState getResultState(BoundCollectionExpression node, Collecti Debug.Assert(foundIterationType); } } + else if (collectionKind is CollectionExpressionTypeKind.ImplementsIEnumerable) + { + Debug.Assert(!targetElementType.HasType); + _binder.TryGetCollectionIterationType(node.Syntax, collectionType, out targetElementType); + } return (collectionKind, targetElementType); } @@ -5252,14 +5306,13 @@ private TypeWithState ReinferAndVisitBinaryOperator( if (operatorKind.IsUserDefined() && method?.ParameterCount == 2) { - // Update method based on inferred operand type. - TypeSymbol methodContainer = method.ContainingType; bool isLifted = operatorKind.IsLifted(); TypeWithState leftUnderlyingType = GetNullableUnderlyingTypeIfNecessary(isLifted, leftType); TypeWithState rightUnderlyingType = GetNullableUnderlyingTypeIfNecessary(isLifted, rightType); - TypeSymbol asMemberOfType = getTypeIfContainingType(methodContainer, leftUnderlyingType.Type, leftOperand) ?? - getTypeIfContainingType(methodContainer, rightUnderlyingType.Type, rightOperand) ?? methodContainer; - var reinferredMethod = (MethodSymbol)AsMemberOfType(asMemberOfType, method); + + // Update method based on inferred operand type. + MethodSymbol reinferredMethod = ReInferBinaryOperator(binary.Syntax, method, leftOperand, rightOperand, leftUnderlyingType, rightUnderlyingType); + SetUpdatedSymbol(binary, method, reinferredMethod); method = reinferredMethod; @@ -5313,6 +5366,61 @@ void visitOperandConversion( var inferredResult = InferResultNullability(operatorKind, method, returnType, leftType, rightType); return inferredResult; + } + + private MethodSymbol ReInferBinaryOperator( + SyntaxNode syntax, + MethodSymbol method, + BoundExpression leftOperand, + BoundExpression rightOperand, + TypeWithState leftUnderlyingType, + TypeWithState rightUnderlyingType) + { + TypeSymbol methodContainer = method.ContainingType; + MethodSymbol reinferredMethod; + + if (!method.GetIsNewExtensionMember()) + { + TypeSymbol asMemberOfType = getTypeIfContainingType(methodContainer, leftUnderlyingType.Type, leftOperand) ?? + getTypeIfContainingType(methodContainer, rightUnderlyingType.Type, rightOperand) ?? methodContainer; + reinferredMethod = (MethodSymbol)AsMemberOfType(asMemberOfType, method); + } + else if (method.ContainingType.Arity != 0) + { + NamedTypeSymbol extension = method.OriginalDefinition.ContainingType; + var discardedUseSiteInfo = CompoundUseSiteInfo.Discarded; + + var inferenceResult = MethodTypeInferrer.Infer( + _binder, + _conversions, + extension.TypeParameters, + extension, + method.OriginalDefinition.ParameterTypesWithAnnotations, + method.OriginalDefinition.ParameterRefKinds, + // https://github.com/dotnet/roslyn/issues/78828: https://github.com/dotnet/roslyn/pull/79103#discussion_r2162657025 + // In analysis of invocations (`VisitCall`/`VisitArguments`), we use `GetArgumentsForMethodTypeInference` to get inputs to `MethodTypeInferrer.Infer`. + // Do we need the same thing here (it has extra cases to deal with lambda, collection expressions and typeless expressions)? + [new BoundExpressionWithNullability(leftOperand.Syntax, leftOperand, leftUnderlyingType.ToTypeWithAnnotations(compilation).NullableAnnotation, leftUnderlyingType.Type), + new BoundExpressionWithNullability(rightOperand.Syntax, rightOperand, rightUnderlyingType.ToTypeWithAnnotations(compilation).NullableAnnotation, rightUnderlyingType.Type)], + ref discardedUseSiteInfo, + new MethodInferenceExtensions(this), + ordinals: null); + + if (inferenceResult.Success) + { + extension = extension.Construct(inferenceResult.InferredTypeArguments); + method = method.OriginalDefinition.AsMember(extension); + } + + CheckMethodConstraints(syntax, method); + reinferredMethod = method; + } + else + { + reinferredMethod = method; + } + + return reinferredMethod; TypeSymbol? getTypeIfContainingType(TypeSymbol baseType, TypeSymbol? derivedType, BoundExpression operand) { @@ -5331,9 +5439,11 @@ void visitOperandConversion( } } - private void VisitBinaryOperatorOperandConversionAndPostConditions(BoundExpression expr, BoundExpression operand, Conversion conversion, ParameterSymbol parameter, TypeWithState operandType, bool isLifted) + private TypeWithState VisitBinaryOperatorOperandConversion( + BoundExpression expr, BoundExpression operand, Conversion conversion, ParameterSymbol parameter, TypeWithState operandType, bool isLifted, + out FlowAnalysisAnnotations parameterAnnotations) { - var parameterAnnotations = GetParameterAnnotations(parameter); + parameterAnnotations = GetParameterAnnotations(parameter); var targetTypeWithNullability = ApplyLValueAnnotations(parameter.TypeWithAnnotations, parameterAnnotations); if (isLifted && targetTypeWithNullability.Type.IsNonNullableValueType()) @@ -5341,7 +5451,7 @@ private void VisitBinaryOperatorOperandConversionAndPostConditions(BoundExpressi targetTypeWithNullability = TypeWithAnnotations.Create(MakeNullableOf(targetTypeWithNullability)); } - var resultType = VisitConversion( + return VisitConversion( expr as BoundConversion, operand, conversion, @@ -5352,6 +5462,12 @@ private void VisitBinaryOperatorOperandConversionAndPostConditions(BoundExpressi useLegacyWarnings: false, AssignmentKind.Argument, parameter); + } + + private void VisitBinaryOperatorOperandConversionAndPostConditions(BoundExpression expr, BoundExpression operand, Conversion conversion, ParameterSymbol parameter, TypeWithState operandType, bool isLifted) + { + FlowAnalysisAnnotations parameterAnnotations; + TypeWithState resultType = VisitBinaryOperatorOperandConversion(expr, operand, conversion, parameter, operandType, isLifted, out parameterAnnotations); if (CheckDisallowedNullAssignment(resultType, parameterAnnotations, expr.Syntax, operand)) { @@ -6435,44 +6551,24 @@ bool tryGetReceiver(BoundCall node, [MaybeNullWhen(returnValue: false)] out Boun TypeWithState visitAndCheckReceiver(BoundCall node) { - TypeWithState receiverType = default; - - // The receiver for new extension methods will be analyzed as an argument - if (node.ReceiverOpt is { } receiver && !node.Method.GetIsNewExtensionMember()) - { - receiverType = VisitRvalueWithState(receiver); - CheckCallReceiver(receiver, receiverType, node.Method); - } - - return receiverType; + return VisitAndCheckReceiver(node.ReceiverOpt, node.Method); } void reinferMethodAndVisitArguments(BoundCall node, TypeWithState receiverType, VisitResult? firstArgumentResult = null) { - MethodSymbol? method = node.Method; - Debug.Assert(method is not null); - - bool adjustForNewExtension = method.GetIsNewExtensionMember() && !node.HasErrors; - - ImmutableArray refKindsOpt = GetArgumentRefKinds(node.ArgumentRefKindsOpt, adjustForNewExtension, method, node.Arguments.Length); - - if (!receiverType.HasNullType) - { - // Update method based on inferred receiver type. - method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); - } - - ImmutableArray arguments = getArguments(node.Arguments, adjustForNewExtension, node.ReceiverOpt); - ImmutableArray parameters = getParameters(method.Parameters, adjustForNewExtension, method); - ImmutableArray argsToParamsOpt = GetArgsToParamsOpt(node.ArgsToParamsOpt, adjustForNewExtension); - - ImmutableArray results; - bool returnNotNull; - (method, results, returnNotNull) = VisitArguments(node, arguments, refKindsOpt, parameters, argsToParamsOpt, node.DefaultArguments, - node.Expanded, node.InvokedAsExtensionMethod, method, firstArgumentResult: firstArgumentResult); - - Debug.Assert(method is not null); - ApplyMemberPostConditions(node.ReceiverOpt, method); + (MethodSymbol method, ImmutableArray results, bool returnNotNull) = ReInferMethodAndVisitArguments( + node, + node.ReceiverOpt, + receiverType, + node.Method, + node.Arguments, + node.ArgumentRefKindsOpt, + node.ArgsToParamsOpt, + node.DefaultArguments, + node.Expanded, + node.InvokedAsExtensionMethod, + suppressAdjustmentForNewExtension: node.HasErrors, + firstArgumentResult); LearnFromEqualsMethod(method, node, receiverType, results); @@ -6485,6 +6581,59 @@ void reinferMethodAndVisitArguments(BoundCall node, TypeWithState receiverType, SetResult(node, returnState, method.ReturnTypeWithAnnotations); SetUpdatedSymbol(node, node.Method, method); } + } + + private TypeWithState VisitAndCheckReceiver(BoundExpression? receiverOpt, MethodSymbol method) + { + TypeWithState receiverType = default; + + // The receiver for new extension methods will be analyzed as an argument + if (receiverOpt is { } receiver && !method.GetIsNewExtensionMember()) + { + receiverType = VisitRvalueWithState(receiver); + CheckCallReceiver(receiver, receiverType, method); + } + + return receiverType; + } + + private (MethodSymbol method, ImmutableArray results, bool returnNotNull) ReInferMethodAndVisitArguments( + BoundExpression node, + BoundExpression? receiverOpt, + TypeWithState receiverType, + MethodSymbol method, + ImmutableArray arguments, + ImmutableArray refKindsOpt, + ImmutableArray argsToParamsOpt, + BitVector defaultArguments, + bool expanded, + bool invokedAsExtensionMethod, + bool suppressAdjustmentForNewExtension, + VisitResult? firstArgumentResult = null) + { + bool adjustForNewExtension = method.GetIsNewExtensionMember() && !suppressAdjustmentForNewExtension; + + refKindsOpt = GetArgumentRefKinds(refKindsOpt, adjustForNewExtension, method, arguments.Length); + + if (!receiverType.HasNullType) + { + // Update method based on inferred receiver type. + method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); + } + + arguments = getArguments(arguments, adjustForNewExtension, receiverOpt); + ImmutableArray parameters = getParameters(method.Parameters, adjustForNewExtension, method); + argsToParamsOpt = GetArgsToParamsOpt(argsToParamsOpt, adjustForNewExtension); + + ImmutableArray results; + bool returnNotNull; + (var newMethod, results, returnNotNull) = VisitArguments(node, arguments, refKindsOpt, parameters, argsToParamsOpt, defaultArguments, + expanded, invokedAsExtensionMethod, method, firstArgumentResult: firstArgumentResult); + + Debug.Assert(newMethod is not null); + ApplyMemberPostConditions(receiverOpt, newMethod); + + return (newMethod, results, returnNotNull); static ImmutableArray getArguments(ImmutableArray arguments, bool isNewExtension, BoundExpression? receiver) { @@ -6955,7 +7104,7 @@ private static bool HasImplicitTypeArguments(BoundNode node) return true; } - if (node is BoundPropertyAccess) + if (node is BoundPropertyAccess or BoundIncrementOperator or BoundCompoundAssignmentOperator) { return true; } @@ -8583,7 +8732,7 @@ private static Symbol AsMemberOfType(TypeSymbol? type, Symbol symbol) } } - Debug.Assert(false); // If this assert fails, add an appropriate test. + Debug.Assert(false); return symbol; bool tryAsMemberOfSingleType(NamedTypeSymbol singleType, [NotNullWhen(true)] out Symbol? result) @@ -10788,23 +10937,86 @@ private ImmutableArray GetDeconstructionRightParts(BoundExpress { Debug.Assert(!IsConditionalState); + if (node.MethodOpt is { } method ? + !method.IsStatic : + (!node.OriginalUserDefinedOperatorsOpt.IsDefaultOrEmpty && !node.OriginalUserDefinedOperatorsOpt[0].IsStatic)) + { + if (node.MethodOpt is { } instanceMethod) + { + int extensionReceiverSlot = -1; + + if (instanceMethod.GetIsNewExtensionMember()) + { + extensionReceiverSlot = MakeSlot(node.Operand) is > 0 and int slot ? slot : GetOrCreatePlaceholderSlot(node.Operand); + } + + TypeWithState receiverType = VisitAndCheckReceiver(node.Operand, instanceMethod); + (instanceMethod, ImmutableArray results, bool returnNotNull) = ReInferMethodAndVisitArguments( + node, + node.Operand, + receiverType, + instanceMethod, + arguments: [], + refKindsOpt: default, + argsToParamsOpt: default, + defaultArguments: default, + expanded: false, + invokedAsExtensionMethod: false, + suppressAdjustmentForNewExtension: false); + + if (node.Type.IsVoidType()) + { + SetNotNullResult(node); + } + else if (!instanceMethod.GetIsNewExtensionMember()) + { + SetResultType(node, TypeWithState.Create(receiverType.Type, NullableFlowState.NotNull)); + } + else if (extensionReceiverSlot > 0) + { + SetResultType(node, TypeWithState.Create(results[0].RValueType.Type, GetState(ref State, extensionReceiverSlot))); + } + else + { + SetResult(node, results[0], updateAnalyzedNullability: true, isLvalue: false); + } + + SetUpdatedSymbol(node, node.MethodOpt, instanceMethod); + } + else + { + // An error case + var opType = VisitRvalueWithState(node.Operand); + + if (node.Type.IsVoidType()) + { + SetNotNullResult(node); + } + else + { + SetResultType(node, TypeWithState.Create(opType.Type, NullableFlowState.NotNull)); + } + } + + return null; + } + var operandType = VisitRvalueWithState(node.Operand); var operandLvalue = LvalueResultType; bool setResult = false; if (this.State.Reachable) { - if (node.MethodOpt is { } method ? - !method.IsStatic : - (!node.OriginalUserDefinedOperatorsOpt.IsDefaultOrEmpty && !node.OriginalUserDefinedOperatorsOpt[0].IsStatic)) + bool isLifted = node.OperatorKind.IsLifted(); + MethodSymbol? incrementOperator = (node.OperatorKind.IsUserDefined() && node.MethodOpt?.ParameterCount == 1) ? node.MethodOpt : null; + + // Update increment method based on operand type. + if (incrementOperator is not null) { - CheckCallReceiver(node.Operand, operandType, node.MethodOpt ?? node.OriginalUserDefinedOperatorsOpt[0]); - SetNotNullResult(node); - return null; + incrementOperator = ReInferUnaryOperator(node.Syntax, incrementOperator, node.Operand, GetNullableUnderlyingTypeIfNecessary(isLifted, operandType)); + SetUpdatedSymbol(node, node.MethodOpt!, incrementOperator); } - // https://github.com/dotnet/roslyn/issues/29961 Update increment method based on operand type. - MethodSymbol? incrementOperator = (node.OperatorKind.IsUserDefined() && node.MethodOpt?.ParameterCount == 1) ? node.MethodOpt : null; TypeWithAnnotations targetTypeOfOperandConversion; AssignmentKind assignmentKind = AssignmentKind.Assignment; ParameterSymbol? parameter = null; @@ -10818,6 +11030,12 @@ private ImmutableArray GetDeconstructionRightParts(BoundExpress else if (incrementOperator is object) { targetTypeOfOperandConversion = incrementOperator.Parameters[0].TypeWithAnnotations; + + if (isLifted) + { + targetTypeOfOperandConversion = TypeWithAnnotations.Create(MakeNullableOf(targetTypeOfOperandConversion)); + } + assignmentKind = AssignmentKind.Argument; parameter = incrementOperator.Parameters[0]; } @@ -10858,7 +11076,7 @@ private ImmutableArray GetDeconstructionRightParts(BoundExpress } else { - resultOfIncrementType = incrementOperator.ReturnTypeWithAnnotations.ToTypeWithState(); + resultOfIncrementType = GetLiftedReturnTypeIfNecessary(isLifted, incrementOperator.ReturnTypeWithAnnotations, operandType.State); } var operandTypeWithAnnotations = operandType.ToTypeWithAnnotations(compilation); @@ -10895,6 +11113,76 @@ private ImmutableArray GetDeconstructionRightParts(BoundExpress public override BoundNode? VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) { + Debug.Assert(!IsConditionalState); + + if (node.Operator.Method is { } method ? + !method.IsStatic : + (!node.OriginalUserDefinedOperatorsOpt.IsDefaultOrEmpty && !node.OriginalUserDefinedOperatorsOpt[0].IsStatic)) + { + if (node.Operator.Method is { } instanceMethod) + { + int extensionReceiverSlot = -1; + + if (instanceMethod.GetIsNewExtensionMember()) + { + extensionReceiverSlot = MakeSlot(node.Left) is > 0 and int slot ? slot : GetOrCreatePlaceholderSlot(node.Left); + } + + TypeWithState receiverType = VisitAndCheckReceiver(node.Left, instanceMethod); + (instanceMethod, ImmutableArray results, bool returnNotNull) = ReInferMethodAndVisitArguments( + node, + node.Left, + receiverType, + instanceMethod, + arguments: [node.Right], + refKindsOpt: default, + argsToParamsOpt: default, + defaultArguments: default, + expanded: false, + invokedAsExtensionMethod: false, + suppressAdjustmentForNewExtension: false); + + if (node.Type.IsVoidType()) + { + SetNotNullResult(node); + } + else if (!instanceMethod.GetIsNewExtensionMember()) + { + SetResultType(node, TypeWithState.Create(receiverType.Type, NullableFlowState.NotNull)); + } + else if (extensionReceiverSlot > 0) + { + SetResultType(node, TypeWithState.Create(results[0].RValueType.Type, GetState(ref State, extensionReceiverSlot))); + } + else + { + SetResult(node, results[0], updateAnalyzedNullability: true, isLvalue: false); + } + + SetUpdatedSymbol(node, node.Operator.Method, instanceMethod); + } + else + { + // An error case + Visit(node.Left); + var opType = ResultType; + Unsplit(); + + VisitRvalue(node.Right); + + if (node.Type.IsVoidType()) + { + SetNotNullResult(node); + } + else + { + SetResultType(node, TypeWithState.Create(opType.Type, NullableFlowState.NotNull)); + } + } + + return null; + } + // visit 'x' Visit(node.Left); Unsplit(); @@ -10908,29 +11196,6 @@ private ImmutableArray GetDeconstructionRightParts(BoundExpress // visit 'y' var rightTypeWithState = VisitRvalueWithState(rightConversionOperand); - if (node.Operator.Method is { } method) - { - if (!method.IsStatic) - { - // Update method based on inferred operand type. - var reinferredMethod = (MethodSymbol)AsMemberOfType(leftTypeWithState.Type, method); - SetUpdatedSymbol(node, method, reinferredMethod); - method = reinferredMethod; - - CheckCallReceiver(node.Left, leftTypeWithState, method); - VisitBinaryOperatorOperandConversionAndPostConditions(node.Right, rightConversionOperand, rightConversion, method.Parameters[0], rightTypeWithState, isLifted: false); - - SetNotNullResult(node); - return null; - } - } - else if (!node.OriginalUserDefinedOperatorsOpt.IsDefaultOrEmpty && !node.OriginalUserDefinedOperatorsOpt[0].IsStatic) - { - // This is an error scenario - SetNotNullResult(node); - return null; - } - // for an operator like: 'TResult operator op(TLeftParam left, TRightParam right);' // and usage like: 'x op= y;' // expansion is (roughly): 'x = (TLeftArg)((TLeftParam)x op (TRightParam)y);' @@ -11002,17 +11267,6 @@ private ImmutableArray GetDeconstructionRightParts(BoundExpress return null; } - private void ReportArgumentWarnings(BoundExpression argument, TypeWithState argumentType, ParameterSymbol parameter) - { - var paramType = parameter.TypeWithAnnotations; - ReportNullableAssignmentIfNecessary(argument, paramType, argumentType, useLegacyWarnings: false, AssignmentKind.Argument, parameterOpt: parameter); - - if (argumentType.Type is { } argType && IsNullabilityMismatch(paramType.Type, argType)) - { - ReportNullabilityMismatchInArgument(argument.Syntax, argType, parameter, paramType.Type, forOutput: false); - } - } - private void ReportNullabilityMismatchInRefArgument(BoundExpression argument, TypeSymbol argumentType, ParameterSymbol parameter, TypeSymbol parameterType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, @@ -11696,7 +11950,8 @@ node.MethodOpt is MethodSymbol method && bool isLifted = node.OperatorKind.IsLifted(); var operandType = GetNullableUnderlyingTypeIfNecessary(isLifted, operandResult); // Update method based on inferred operand type. - method = (MethodSymbol)AsMemberOfType(operandType.Type!.StrippedType(), method); + method = ReInferUnaryOperator(node.Syntax, method, operand, operandType); + // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 var parameter = method.Parameters[0]; _ = VisitConversion( @@ -11728,6 +11983,44 @@ TypeWithState adjustForLifting(TypeWithState argumentResult) => TypeWithState.Create(node.Type, node.OperatorKind.IsLifted() ? argumentResult.State : NullableFlowState.NotNull); } + /// + /// The must be stripped of Nullable if we are dealing with lifted form of a unary operator. + /// + private MethodSymbol ReInferUnaryOperator(SyntaxNode syntax, MethodSymbol method, BoundExpression operand, TypeWithState operandType) + { + if (!method.GetIsNewExtensionMember()) + { + method = (MethodSymbol)AsMemberOfType(operandType.Type!.StrippedType(), method); + } + else if (method.ContainingType.Arity != 0) + { + NamedTypeSymbol extension = method.OriginalDefinition.ContainingType; + var discardedUseSiteInfo = CompoundUseSiteInfo.Discarded; + + var inferenceResult = MethodTypeInferrer.Infer( + _binder, + _conversions, + extension.TypeParameters, + extension, + method.OriginalDefinition.ParameterTypesWithAnnotations, + method.OriginalDefinition.ParameterRefKinds, + [new BoundExpressionWithNullability(operand.Syntax, operand, operandType.ToTypeWithAnnotations(compilation).NullableAnnotation, operandType.Type)], + ref discardedUseSiteInfo, + new MethodInferenceExtensions(this), + ordinals: null); + + if (inferenceResult.Success) + { + extension = extension.Construct(inferenceResult.InferredTypeArguments); + method = method.OriginalDefinition.AsMember(extension); + } + + CheckMethodConstraints(syntax, method); + } + + return method; + } + public override BoundNode? VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) { var result = base.VisitPointerIndirectionOperator(node); @@ -11766,94 +12059,159 @@ TypeWithState adjustForLifting(TypeWithState argumentResult) => return result; } - private TypeWithState InferResultNullability(BoundUserDefinedConditionalLogicalOperator node) + protected override void VisitBinaryLogicalOperatorChildren(ArrayBuilder stack) { - if (node.OperatorKind.IsLifted()) - { - // https://github.com/dotnet/roslyn/issues/33879 Conversions: Lifted operator - // Should this use the updated flow type and state? How should it compute nullability? - return TypeWithState.Create(node.Type, NullableFlowState.NotNull); - } + BoundExpression binary; + Debug.Assert(stack.Count > 0); - // Update method based on inferred operand types: see https://github.com/dotnet/roslyn/issues/29605. - // Analyze operator result properly (honoring [Maybe|NotNull] and [Maybe|NotNullWhen] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 - if ((object)node.LogicalOperator != null && node.LogicalOperator.ParameterCount == 2) - { - return GetReturnTypeWithState(node.LogicalOperator); - } - else - { - return default; - } - } + binary = stack.Pop(); - protected override void AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression node, BoundExpression right, bool isAnd, bool isBool, ref LocalState leftTrue, ref LocalState leftFalse) - { - Debug.Assert(!IsConditionalState); - TypeWithState leftType = ResultType; - // https://github.com/dotnet/roslyn/issues/29605 Update operator methods based on inferred operand types. - MethodSymbol? logicalOperator = null; - MethodSymbol? trueFalseOperator = null; - BoundExpression? left = null; + BoundExpression? leftOperand = null; + Conversion leftConversion = Conversion.Identity; - switch (node.Kind) + switch (binary) { - case BoundKind.BinaryOperator: - Debug.Assert(!((BoundBinaryOperator)node).OperatorKind.IsUserDefined()); + case BoundBinaryOperator binOp: + VisitCondition(binOp.Left); break; - case BoundKind.UserDefinedConditionalLogicalOperator: - var binary = (BoundUserDefinedConditionalLogicalOperator)node; - if (binary.LogicalOperator != null && binary.LogicalOperator.ParameterCount == 2) - { - logicalOperator = binary.LogicalOperator; - left = binary.Left; - trueFalseOperator = isAnd ? binary.FalseOperator : binary.TrueOperator; - - if ((object)trueFalseOperator != null && trueFalseOperator.ParameterCount != 1) - { - trueFalseOperator = null; - } - } + case BoundUserDefinedConditionalLogicalOperator udBinOp: + (leftOperand, leftConversion) = RemoveConversion(udBinOp.Left, includeExplicitConversions: false); + Visit(leftOperand); break; default: - throw ExceptionUtilities.UnexpectedValue(node.Kind); + throw ExceptionUtilities.UnexpectedValue(binary.Kind); } - Debug.Assert(trueFalseOperator is null || logicalOperator is object); - Debug.Assert(logicalOperator is null || left is object); - - // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 - if (trueFalseOperator is object) + while (true) { - ReportArgumentWarnings(left!, leftType, trueFalseOperator.Parameters[0]); + switch (binary) + { + case BoundBinaryOperator binOp: + afterLeftChildOfBoundBinaryOperatorHasBeenVisited(binOp); + break; + case BoundUserDefinedConditionalLogicalOperator udBinOp: + Debug.Assert(leftOperand is not null); + afterLeftChildOfBoundUserDefinedConditionalLogicalOperatorHasBeenVisited(udBinOp, leftOperand, leftConversion); + break; + default: + throw ExceptionUtilities.UnexpectedValue(binary.Kind); + } + + if (stack.Count == 0) + { + break; + } + + AdjustConditionalState(binary); + + leftOperand = binary; + leftConversion = Conversion.Identity; + + binary = stack.Pop(); } - if (logicalOperator is object) + static void getBinaryConditionalOperatorInfo(BinaryOperatorKind kind, out bool isAnd, out bool isBool) { - ReportArgumentWarnings(left!, leftType, logicalOperator.Parameters[0]); + BinaryOperatorKind op = kind.Operator(); + isAnd = op == BinaryOperatorKind.And; + isBool = kind.OperandTypes() == BinaryOperatorKind.Bool; + Debug.Assert(isAnd || op == BinaryOperatorKind.Or); } - Visit(right); - TypeWithState rightType = ResultType; + void afterLeftChildOfBoundBinaryOperatorHasBeenVisited(BoundBinaryOperator node) + { + Debug.Assert(IsConditionalState); + TypeWithState leftType = ResultType; - SetResultType(node, InferResultNullabilityOfBinaryLogicalOperator(node, leftType, rightType)); + getBinaryConditionalOperatorInfo(node.OperatorKind, out bool isAnd, out bool isBool); - if (logicalOperator is object) - { - ReportArgumentWarnings(right, rightType, logicalOperator.Parameters[1]); + var leftTrue = this.StateWhenTrue; + var leftFalse = this.StateWhenFalse; + SetState(isAnd ? leftTrue : leftFalse); + + Visit(node.Right); + TypeWithState rightType = ResultType; + SetResultType(node, InferResultNullability(node.OperatorKind, node.Method, node.Type, leftType, rightType)); + AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(node.Right, isAnd, isBool, ref leftTrue, ref leftFalse); } - AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(right, isAnd, isBool, ref leftTrue, ref leftFalse); + void afterLeftChildOfBoundUserDefinedConditionalLogicalOperatorHasBeenVisited(BoundUserDefinedConditionalLogicalOperator binary, BoundExpression leftOperand, Conversion leftConversion) + { + TypeWithState leftType = ResultType; + + Unsplit(); + Split(); + + var leftTrue = this.StateWhenTrue; + var leftFalse = this.StateWhenFalse; + + getBinaryConditionalOperatorInfo(binary.OperatorKind, out bool isAnd, out bool isBool); + Debug.Assert(!isBool); + SetState(isAnd ? leftTrue : leftFalse); + + var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); + + VisitRvalue(rightOperand); + var rightType = ResultType; + Unsplit(); + + var rightState = State.Clone(); + + // Analyze operator calls properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 + + bool isLifted = binary.OperatorKind.IsLifted(); + TypeWithState leftUnderlyingType = GetNullableUnderlyingTypeIfNecessary(isLifted, leftType); + TypeWithState rightUnderlyingType = GetNullableUnderlyingTypeIfNecessary(isLifted, rightType); + + MethodSymbol logicalOperator = binary.LogicalOperator; + + // Update method based on inferred operand type. + MethodSymbol reInferredMethod = ReInferBinaryOperator(binary.Syntax, logicalOperator, leftOperand, rightOperand, leftUnderlyingType, rightUnderlyingType); + + SetUpdatedSymbol(binary, logicalOperator, reInferredMethod); + logicalOperator = reInferredMethod; + + // Conversion of the left operand is actually done before the split (before the true/false check) + var leftState = isAnd ? leftFalse : leftTrue; + SetState(leftState); + + var parameters = logicalOperator.Parameters; + leftType = VisitBinaryOperatorOperandConversion(binary.Left, leftOperand, leftConversion, parameters[0], leftUnderlyingType, isLifted, out _); + + // True/False call is done before the split, short-circuiting happens based on its result + MethodSymbol trueFalseOperator = isAnd ? binary.FalseOperator : binary.TrueOperator; + + // Update operator method based on inferred operand type. + var updatedTrueFalseOperator = ReInferUnaryOperator(leftOperand.Syntax, trueFalseOperator, binary.Left, leftType); + SetUpdatedSymbol(binary, trueFalseOperator, updatedTrueFalseOperator); + trueFalseOperator = updatedTrueFalseOperator; + + var trueFalseParameter = trueFalseOperator.Parameters[0]; + _ = VisitConversion( + conversionOpt: null, + binary.Left, + BoundNode.GetConversion(binary.TrueFalseOperandConversion, binary.TrueFalseOperandPlaceholder), + trueFalseParameter.TypeWithAnnotations, + leftType, + checkConversion: true, + fromExplicitCast: false, + useLegacyWarnings: false, + assignmentKind: AssignmentKind.Argument, + parameterOpt: trueFalseParameter); + + SetState(rightState); + + rightType = VisitBinaryOperatorOperandConversion(binary.Right, rightOperand, rightConversion, parameters[1], rightUnderlyingType, isLifted, out _); + + SetResultType(binary, InferResultNullability(binary.OperatorKind, logicalOperator, binary.Type, leftType, rightType)); + + AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(binary.Right, isAnd, isBool, ref leftTrue, ref leftFalse); + } } - private TypeWithState InferResultNullabilityOfBinaryLogicalOperator(BoundExpression node, TypeWithState leftType, TypeWithState rightType) + protected override void AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression node, BoundExpression right, bool isAnd, bool isBool, ref LocalState leftTrue, ref LocalState leftFalse) { - return node switch - { - BoundBinaryOperator binary => InferResultNullability(binary.OperatorKind, binary.Method, binary.Type, leftType, rightType), - BoundUserDefinedConditionalLogicalOperator userDefined => InferResultNullability(userDefined), - _ => throw ExceptionUtilities.UnexpectedValue(node) - }; + throw ExceptionUtilities.Unreachable(); } public override BoundNode? VisitAwaitExpression(BoundAwaitExpression node) diff --git a/src/Compilers/CSharp/Portable/Generated/BoundNodes.xml.Generated.cs b/src/Compilers/CSharp/Portable/Generated/BoundNodes.xml.Generated.cs index 2ef46101bb585..53b501da5e0db 100644 --- a/src/Compilers/CSharp/Portable/Generated/BoundNodes.xml.Generated.cs +++ b/src/Compilers/CSharp/Portable/Generated/BoundNodes.xml.Generated.cs @@ -1731,8 +1731,12 @@ public BoundUserDefinedConditionalLogicalOperator(SyntaxNode syntax, BinaryOpera this.ConstrainedToTypeOpt = constrainedToTypeOpt; this.ResultKind = resultKind; this.OriginalUserDefinedOperatorsOpt = originalUserDefinedOperatorsOpt; + Validate(); } + [Conditional("DEBUG")] + private partial void Validate(); + public BinaryOperatorKind OperatorKind { get; } public MethodSymbol LogicalOperator { get; } public MethodSymbol TrueOperator { get; } @@ -2292,8 +2296,12 @@ public BoundMethodDefIndex(SyntaxNode syntax, MethodSymbol method, TypeSymbol ty RoslynDebug.Assert(type is object, "Field 'type' cannot be null (make the type nullable in BoundNodes.xml to remove this check)"); this.Method = method; + Validate(); } + [Conditional("DEBUG")] + private partial void Validate(); + public BoundMethodDefIndex(SyntaxNode syntax, MethodSymbol method, TypeSymbol type) : base(BoundKind.MethodDefIndex, syntax, type) { @@ -12940,29 +12948,6 @@ public NullabilityRewriter(ImmutableDictionary originalUserDefinedOperatorsOpt = GetUpdatedArray(node, node.OriginalUserDefinedOperatorsOpt); - BoundExpression left = (BoundExpression)this.Visit(node.Left); - BoundExpression right = (BoundExpression)this.Visit(node.Right); - BoundValuePlaceholder? leftPlaceholder = node.LeftPlaceholder; - BoundExpression? leftConversion = node.LeftConversion; - BoundValuePlaceholder? finalPlaceholder = node.FinalPlaceholder; - BoundExpression? finalConversion = node.FinalConversion; - BoundCompoundAssignmentOperator updatedNode; - - if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo Info, TypeSymbol? Type) infoAndType)) - { - updatedNode = node.Update(node.Operator, left, right, leftPlaceholder, leftConversion, finalPlaceholder, finalConversion, node.ResultKind, node.OriginalUserDefinedOperatorsOpt, infoAndType.Type!); - updatedNode.TopLevelNullability = infoAndType.Info; - } - else - { - updatedNode = node.Update(node.Operator, left, right, leftPlaceholder, leftConversion, finalPlaceholder, finalConversion, node.ResultKind, node.OriginalUserDefinedOperatorsOpt, node.Type); - } - return updatedNode; - } - public override BoundNode? VisitAssignmentOperator(BoundAssignmentOperator node) { BoundExpression left = (BoundExpression)this.Visit(node.Left); diff --git a/src/Compilers/CSharp/Portable/LanguageVersion.cs b/src/Compilers/CSharp/Portable/LanguageVersion.cs index ec5d56afa9904..4d429582030ef 100644 --- a/src/Compilers/CSharp/Portable/LanguageVersion.cs +++ b/src/Compilers/CSharp/Portable/LanguageVersion.cs @@ -572,10 +572,5 @@ internal static bool AllowImprovedOverloadCandidates(this LanguageVersion self) { return self >= MessageID.IDS_FeatureImprovedOverloadCandidates.RequiredVersion(); } - - internal static bool AllowNewExtensions(this LanguageVersion self) - { - return self >= MessageID.IDS_FeatureExtensions.RequiredVersion(); - } } } diff --git a/src/Compilers/CSharp/Portable/Lowering/BoundTreeToDifferentEnclosingContextRewriter.cs b/src/Compilers/CSharp/Portable/Lowering/BoundTreeToDifferentEnclosingContextRewriter.cs index d77e402f9aada..07fd38f7fef3f 100644 --- a/src/Compilers/CSharp/Portable/Lowering/BoundTreeToDifferentEnclosingContextRewriter.cs +++ b/src/Compilers/CSharp/Portable/Lowering/BoundTreeToDifferentEnclosingContextRewriter.cs @@ -203,6 +203,13 @@ public override BoundNode VisitAwaitableValuePlaceholder(BoundAwaitableValuePlac ; } + public override BoundNode? VisitMethodDefIndex(BoundMethodDefIndex node) + { + // Cannot replace a MethodDefIndex's Method/Type with a substituted symbol. + Debug.Assert(node.Type.Equals(VisitType(node.Type), TypeCompareKind.ConsiderEverything)); + return node; + } + [return: NotNullIfNotNull(nameof(method))] public override MethodSymbol? VisitMethodSymbol(MethodSymbol? method) { diff --git a/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureConversion.Analysis.cs b/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureConversion.Analysis.cs index 123b2a23e4f7d..8346d6b4caeaf 100644 --- a/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureConversion.Analysis.cs +++ b/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureConversion.Analysis.cs @@ -5,6 +5,7 @@ #nullable disable using System.Collections.Immutable; +using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; diff --git a/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/SynthesizedClosureMethod.cs b/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/SynthesizedClosureMethod.cs index 000a43b663390..b2407901552d0 100644 --- a/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/SynthesizedClosureMethod.cs +++ b/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/SynthesizedClosureMethod.cs @@ -36,7 +36,7 @@ internal SynthesizedClosureMethod( originalMethod, blockSyntax, originalMethod.DeclaringSyntaxReferences[0].GetLocation(), - originalMethod is LocalFunctionSymbol + originalMethod is { MethodKind: MethodKind.LocalFunction } ? MakeName(topLevelMethod.Name, originalMethod.Name, topLevelMethodId, closureKind, lambdaId) : MakeName(topLevelMethod.Name, topLevelMethodId, closureKind, lambdaId), MakeDeclarationModifiers(closureKind, originalMethod), @@ -103,7 +103,7 @@ originalMethod is LocalFunctionSymbol EnsureAttributesExist(compilationState); // static local functions should be emitted as static. - Debug.Assert(!(originalMethod is LocalFunctionSymbol) || !originalMethod.IsStatic || IsStatic); + Debug.Assert(originalMethod is not { MethodKind: MethodKind.LocalFunction } || !originalMethod.IsStatic || IsStatic); } private void EnsureAttributesExist(TypeCompilationState compilationState) diff --git a/src/Compilers/CSharp/Portable/Lowering/DiagnosticsPass_ExpressionTrees.cs b/src/Compilers/CSharp/Portable/Lowering/DiagnosticsPass_ExpressionTrees.cs index 7eb5688d29da3..e8629aa3de96c 100644 --- a/src/Compilers/CSharp/Portable/Lowering/DiagnosticsPass_ExpressionTrees.cs +++ b/src/Compilers/CSharp/Portable/Lowering/DiagnosticsPass_ExpressionTrees.cs @@ -755,6 +755,22 @@ public override BoundNode VisitUserDefinedConditionalLogicalOperator(BoundUserDe { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } + + if (binary.GetIsNewExtensionMember()) + { + // An expression tree factory isn't happy in this case. It throws + // System.ArgumentException : The user-defined operator method 'op_BitwiseOr' for operator 'OrElse' must have associated boolean True and False operators. + // or + // System.ArgumentException : The user-defined operator method 'op_BitwiseAnd' for operator 'AndAlso' must have associated boolean True and False operators. + // + // from Expression.ValidateUserDefinedConditionalLogicOperator(ExpressionType nodeType, Type left, Type right, MethodInfo method) + Error(ErrorCode.ERR_ExpressionTreeContainsExtensionBasedConditionalLogicalOperator, node); + } + else + { + Debug.Assert(!node.TrueOperator.GetIsNewExtensionMember()); + Debug.Assert(!node.FalseOperator.GetIsNewExtensionMember()); + } } return base.VisitUserDefinedConditionalLogicalOperator(node); diff --git a/src/Compilers/CSharp/Portable/Lowering/ExtensionMethodBodyRewriter.cs b/src/Compilers/CSharp/Portable/Lowering/ExtensionMethodBodyRewriter.cs index 806b65f34ee61..d2c8f6b6dccf1 100644 --- a/src/Compilers/CSharp/Portable/Lowering/ExtensionMethodBodyRewriter.cs +++ b/src/Compilers/CSharp/Portable/Lowering/ExtensionMethodBodyRewriter.cs @@ -198,5 +198,15 @@ public override BoundNode VisitFunctionPointerLoad(BoundFunctionPointerLoad node Debug.Assert(symbol?.GetIsNewExtensionMember() != true); return base.VisitPropertySymbol(symbol); } + + public override BoundNode VisitUnaryOperator(BoundUnaryOperator node) + { + return ExtensionMethodReferenceRewriter.VisitUnaryOperator(this, node); + } + + protected override BoundBinaryOperator.UncommonData? VisitBinaryOperatorData(BoundBinaryOperator node) + { + return ExtensionMethodReferenceRewriter.VisitBinaryOperatorData(this, node); + } } } diff --git a/src/Compilers/CSharp/Portable/Lowering/ExtensionMethodReferenceRewriter.cs b/src/Compilers/CSharp/Portable/Lowering/ExtensionMethodReferenceRewriter.cs index 286d0a5b86d9d..5f8c01d75ad56 100644 --- a/src/Compilers/CSharp/Portable/Lowering/ExtensionMethodReferenceRewriter.cs +++ b/src/Compilers/CSharp/Portable/Lowering/ExtensionMethodReferenceRewriter.cs @@ -5,6 +5,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; @@ -73,6 +74,8 @@ public static BoundNode VisitCall(BoundTreeRewriter rewriter, BoundCall node) static BoundExpression visitArgumentsAndFinishRewrite(BoundTreeRewriter rewriter, BoundCall node, BoundExpression? rewrittenReceiver) { + Debug.Assert(node.Method.MethodKind == MethodKind.LocalFunction || node.Method.IsStatic || node.ReceiverOpt is not null); + return updateCall( node, VisitMethodSymbolWithExtensionRewrite(rewriter, node.Method), @@ -165,6 +168,8 @@ static RefKind argumentRefKindFromReceiverRefKind(RefKind receiverRefKind) Debug.Assert(method?.GetIsNewExtensionMember() != true || method.OriginalDefinition.TryGetCorrespondingExtensionImplementationMethod() is null); // All possibly interesting methods should go through VisitMethodSymbolWithExtensionRewrite first + + /* Debug.Assert(method is null || method.ContainingSymbol is not NamedTypeSymbol || method.MethodKind is (MethodKind.Constructor or MethodKind.StaticConstructor) || @@ -176,13 +181,13 @@ method.OriginalDefinition is ErrorMethodSymbol || { Name: nameof(VisitReadOnlySpanFromArray) } => method is { Name: "op_Implicit", IsExtensionMethod: false }, // Conversion operator from array to span cannot be an extension method { Name: nameof(VisitLoweredConditionalAccess) } => // Nullable.HasValue cannot be an extension method method.ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_HasValue) == (object)method.OriginalDefinition, - { Name: nameof(VisitUnaryOperator) } => !method.IsExtensionMethod, // Expression tree context. At the moment an operator cannot be an extension method { Name: nameof(VisitUserDefinedConditionalLogicalOperator) } => !method.IsExtensionMethod, // Expression tree context. At the moment an operator cannot be an extension method { Name: nameof(VisitCollectionElementInitializer) } => !method.IsExtensionMethod, // Expression tree context. At the moment an extension method cannot be used in expression tree here. { Name: nameof(VisitAwaitableInfo) } => method is { Name: "GetResult" or "Await" or "AwaitAwaiter" or "UnsafeAwaitAwaiter", IsExtensionMethod: false }, // Cannot be an extension method { Name: nameof(VisitMethodSymbolWithExtensionRewrite), DeclaringType: { } declaringType } => declaringType == typeof(ExtensionMethodReferenceRewriter), _ => false }); + */ return base.VisitMethodSymbol(method); } @@ -190,7 +195,7 @@ method.OriginalDefinition is ErrorMethodSymbol || public override BoundNode? VisitMethodDefIndex(BoundMethodDefIndex node) { MethodSymbol method = node.Method; - Debug.Assert(method.IsDefinition); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : From the code coverage and other instrumentations perspective, should we remap the index to the implementation symbol? + Debug.Assert(method.IsDefinition); // Tracked by https://github.com/dotnet/roslyn/issues/78962 : From the code coverage and other instrumentations perspective, should we remap the index to the implementation symbol? TypeSymbol? type = this.VisitType(node.Type); return node.Update(method, type); } @@ -231,10 +236,27 @@ public static BoundNode VisitFunctionPointerLoad(BoundTreeRewriter rewriter, Bou protected override BoundBinaryOperator.UncommonData? VisitBinaryOperatorData(BoundBinaryOperator node) { - Debug.Assert(node.Method is null || - (!node.Method.IsExtensionMethod && !node.Method.GetIsNewExtensionMember())); // Expression tree context. At the moment an operator cannot be an extension method + return VisitBinaryOperatorData(this, node); + } + + public static BoundBinaryOperator.UncommonData? VisitBinaryOperatorData(BoundTreeRewriter rewriter, BoundBinaryOperator node) + { + // Local rewriter should have already rewritten interpolated strings into their final form of calls and gotos + Debug.Assert(node.InterpolatedStringHandlerData is null); + + MethodSymbol? method = VisitMethodSymbolWithExtensionRewrite(rewriter, node.Method); + TypeSymbol? constrainedToType = rewriter.VisitType(node.ConstrainedToType); + + if (Symbol.Equals(method, node.Method, TypeCompareKind.AllIgnoreOptions) && TypeSymbol.Equals(constrainedToType, node.ConstrainedToType, TypeCompareKind.AllIgnoreOptions)) + { + return node.Data; + } - return base.VisitBinaryOperatorData(node); + return BoundBinaryOperator.UncommonData.CreateIfNeeded( + node.ConstantValueOpt, + method, + constrainedToType, + node.OriginalUserDefinedOperatorsOpt); } [return: NotNullIfNotNull(nameof(symbol))] @@ -243,5 +265,20 @@ public static BoundNode VisitFunctionPointerLoad(BoundTreeRewriter rewriter, Bou Debug.Assert(symbol?.GetIsNewExtensionMember() != true); return base.VisitPropertySymbol(symbol); } + + public override BoundNode VisitUnaryOperator(BoundUnaryOperator node) + { + return VisitUnaryOperator(this, node); + } + + public static BoundNode VisitUnaryOperator(BoundTreeRewriter rewriter, BoundUnaryOperator node) + { + MethodSymbol? methodOpt = VisitMethodSymbolWithExtensionRewrite(rewriter, node.MethodOpt); + ImmutableArray originalUserDefinedOperatorsOpt = rewriter.VisitSymbols(node.OriginalUserDefinedOperatorsOpt); + BoundExpression operand = (BoundExpression)rewriter.Visit(node.Operand); + TypeSymbol? constrainedToTypeOpt = rewriter.VisitType(node.ConstrainedToTypeOpt); + TypeSymbol? type = rewriter.VisitType(node.Type); + return node.Update(node.OperatorKind, operand, node.ConstantValueOpt, methodOpt, constrainedToTypeOpt, node.ResultKind, originalUserDefinedOperatorsOpt, type); + } } } diff --git a/src/Compilers/CSharp/Portable/Lowering/Instrumentation/CodeCoverageInstrumenter.cs b/src/Compilers/CSharp/Portable/Lowering/Instrumentation/CodeCoverageInstrumenter.cs index 5c57cc091dab8..d0afa61287337 100644 --- a/src/Compilers/CSharp/Portable/Lowering/Instrumentation/CodeCoverageInstrumenter.cs +++ b/src/Compilers/CSharp/Portable/Lowering/Instrumentation/CodeCoverageInstrumenter.cs @@ -8,10 +8,10 @@ using System.Linq; using Microsoft.Cci; using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/Compilers/CSharp/Portable/Lowering/Instrumentation/CompoundInstrumenter.cs b/src/Compilers/CSharp/Portable/Lowering/Instrumentation/CompoundInstrumenter.cs index 289614c47adf9..63ff518f4538d 100644 --- a/src/Compilers/CSharp/Portable/Lowering/Instrumentation/CompoundInstrumenter.cs +++ b/src/Compilers/CSharp/Portable/Lowering/Instrumentation/CompoundInstrumenter.cs @@ -4,9 +4,9 @@ using System.Collections.Immutable; using System.Diagnostics; -using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; -using Microsoft.CodeAnalysis.Shared.Collections; +using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp { diff --git a/src/Compilers/CSharp/Portable/Lowering/Instrumentation/DebugInfoInjector.cs b/src/Compilers/CSharp/Portable/Lowering/Instrumentation/DebugInfoInjector.cs index a9fabf63b6b51..49760be514ac3 100644 --- a/src/Compilers/CSharp/Portable/Lowering/Instrumentation/DebugInfoInjector.cs +++ b/src/Compilers/CSharp/Portable/Lowering/Instrumentation/DebugInfoInjector.cs @@ -5,9 +5,9 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/Compilers/CSharp/Portable/Lowering/Instrumentation/Instrumenter.cs b/src/Compilers/CSharp/Portable/Lowering/Instrumentation/Instrumenter.cs index 0114fd9055ac3..8f02adf29cec6 100644 --- a/src/Compilers/CSharp/Portable/Lowering/Instrumentation/Instrumenter.cs +++ b/src/Compilers/CSharp/Portable/Lowering/Instrumentation/Instrumenter.cs @@ -3,12 +3,12 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; -using Microsoft.CodeAnalysis.Shared.Collections; -using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp { diff --git a/src/Compilers/CSharp/Portable/Lowering/Instrumentation/LocalStateTracingInstrumenter.cs b/src/Compilers/CSharp/Portable/Lowering/Instrumentation/LocalStateTracingInstrumenter.cs index 021bccf5534bb..3062aac04cda0 100644 --- a/src/Compilers/CSharp/Portable/Lowering/Instrumentation/LocalStateTracingInstrumenter.cs +++ b/src/Compilers/CSharp/Portable/Lowering/Instrumentation/LocalStateTracingInstrumenter.cs @@ -7,9 +7,9 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Shared.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp diff --git a/src/Compilers/CSharp/Portable/Lowering/Instrumentation/ModuleCancellationInstrumenter.cs b/src/Compilers/CSharp/Portable/Lowering/Instrumentation/ModuleCancellationInstrumenter.cs index 9862d2b8aec17..36ddeb80d1cd7 100644 --- a/src/Compilers/CSharp/Portable/Lowering/Instrumentation/ModuleCancellationInstrumenter.cs +++ b/src/Compilers/CSharp/Portable/Lowering/Instrumentation/ModuleCancellationInstrumenter.cs @@ -7,9 +7,9 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; -using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; -using Microsoft.CodeAnalysis.Shared.Collections; +using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp; diff --git a/src/Compilers/CSharp/Portable/Lowering/Instrumentation/StackOverflowProbingInstrumenter.cs b/src/Compilers/CSharp/Portable/Lowering/Instrumentation/StackOverflowProbingInstrumenter.cs index fc0ae9f838722..abd28c78f83be 100644 --- a/src/Compilers/CSharp/Portable/Lowering/Instrumentation/StackOverflowProbingInstrumenter.cs +++ b/src/Compilers/CSharp/Portable/Lowering/Instrumentation/StackOverflowProbingInstrumenter.cs @@ -4,8 +4,8 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; -using Microsoft.CodeAnalysis.Shared.Collections; namespace Microsoft.CodeAnalysis.CSharp; diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/DelegateCacheContainer.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/DelegateCacheContainer.cs index 68c424eb9ffa1..fd23f7a415ea1 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/DelegateCacheContainer.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/DelegateCacheContainer.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Diagnostics; +using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols; diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/DynamicSiteContainer.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/DynamicSiteContainer.cs index a02f486447157..e625c50a14770 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/DynamicSiteContainer.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/DynamicSiteContainer.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Collections.Immutable; -using Microsoft.CodeAnalysis.CSharp.Symbols; using System.Diagnostics; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Block.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Block.cs index e7daac5c20c07..cdc914abda867 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Block.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Block.cs @@ -3,9 +3,9 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Shared.Collections; namespace Microsoft.CodeAnalysis.CSharp { diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Call.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Call.cs index 913c4f7053771..45e694684715d 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Call.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Call.cs @@ -147,6 +147,18 @@ private void InterceptCallAndAdjustArguments( return; } + if (interceptor.GetIsNewExtensionMember()) + { + if (interceptor.TryGetCorrespondingExtensionImplementationMethod() is { } implementationMethod) + { + interceptor = implementationMethod; + } + else + { + throw ExceptionUtilities.Unreachable(); + } + } + Debug.Assert(nameSyntax != null); Debug.Assert(interceptor.IsDefinition); Debug.Assert(!interceptor.ContainingType.IsGenericType); @@ -228,9 +240,12 @@ private void InterceptCallAndAdjustArguments( this._diagnostics.Add(ErrorCode.WRN_InterceptorSignatureMismatch, attributeLocation, method, interceptor); } - method.TryGetThisParameter(out var methodThisParameter); - var interceptorThisParameterForCompare = needToReduce ? interceptor.Parameters[0] : + ParameterSymbol? methodThisParameter; + _ = method.TryGetInstanceExtensionParameter(out methodThisParameter) || method.TryGetThisParameter(out methodThisParameter); + + ParameterSymbol? interceptorThisParameterForCompare = needToReduce ? interceptor.Parameters[0] : interceptor.TryGetThisParameter(out var interceptorThisParameter) ? interceptorThisParameter : null; + switch (methodThisParameter, interceptorThisParameterForCompare) { case (not null, null): diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_CollectionExpression.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_CollectionExpression.cs index fe1967fcf02b7..edee10378aa07 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_CollectionExpression.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_CollectionExpression.cs @@ -10,7 +10,6 @@ using Microsoft.CodeAnalysis.CSharp.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Shared.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_CompoundAssignmentOperator.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_CompoundAssignmentOperator.cs index b0b67aaa12a5a..06a182f35e000 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_CompoundAssignmentOperator.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_CompoundAssignmentOperator.cs @@ -36,32 +36,46 @@ private BoundExpression VisitCompoundAssignmentOperator(BoundCompoundAssignmentO private BoundExpression VisitInstanceCompoundAssignmentOperator(BoundCompoundAssignmentOperator node, bool used) { Debug.Assert(node.Operator.Method is { }); + Debug.Assert(node.LeftConversion is null || (node.Left.Type!.IsReferenceType && node.Operator.Method.GetIsNewExtensionMember())); + Debug.Assert(node.FinalConversion is null); SyntaxNode syntax = node.Syntax; if (!used) { - return BoundCall.Synthesized(syntax, VisitExpression(node.Left), initialBindingReceiverIsSubjectToCloning: ThreeState.False, node.Operator.Method, VisitExpression(node.Right)); + return BoundCall.Synthesized(syntax, + ApplyConversionIfNotIdentity(node.LeftConversion, node.LeftPlaceholder, VisitExpression(node.Left)), + initialBindingReceiverIsSubjectToCloning: ThreeState.False, + node.Operator.Method, + VisitExpression(node.Right)); } TypeSymbol? leftType = node.Left.Type; // type of the target Debug.Assert(leftType is { }); Debug.Assert(TypeSymbol.Equals(leftType, node.Type, TypeCompareKind.AllIgnoreOptions)); - BoundAssignmentOperator tempAssignment; - BoundLocal targetOfCompoundOperation; - if (leftType.IsReferenceType) { - targetOfCompoundOperation = _factory.StoreToTemp(VisitExpression(node.Left), out tempAssignment); + BoundAssignmentOperator tempAssignment; + BoundLocal targetOfCompoundOperation = _factory.StoreToTemp(VisitExpression(node.Left), out tempAssignment); return new BoundSequence( syntax: syntax, locals: [targetOfCompoundOperation.LocalSymbol], - sideEffects: [tempAssignment, BoundCall.Synthesized(syntax, targetOfCompoundOperation, initialBindingReceiverIsSubjectToCloning: ThreeState.False, node.Operator.Method, VisitExpression(node.Right))], + sideEffects: + [ + tempAssignment, + BoundCall.Synthesized(syntax, + ApplyConversionIfNotIdentity(node.LeftConversion, node.LeftPlaceholder, targetOfCompoundOperation), + initialBindingReceiverIsSubjectToCloning: ThreeState.False, + node.Operator.Method, + VisitExpression(node.Right)) + ], value: targetOfCompoundOperation, type: leftType); } + Debug.Assert(node.LeftConversion is null); + return MakeInstanceCompoundAssignmentOperatorResult(node.Syntax, node.Left, node.Right, node.Operator.Method, node.Operator.Kind.IsChecked()); } @@ -260,7 +274,16 @@ BoundExpression rewriteAssignment(BoundExpression leftRead, BoundExpression righ Debug.Assert(rewrittenReceiver.Type is { }); var variableRepresentsLocation = rewrittenReceiver.Type.IsValueType || rewrittenReceiver.Type.Kind == SymbolKind.TypeParameter; - var receiverTemp = _factory.StoreToTemp(rewrittenReceiver, out assignmentToTemp, refKind: variableRepresentsLocation ? RefKind.Ref : RefKind.None); + var receiverTemp = _factory.StoreToTemp( + rewrittenReceiver, + out assignmentToTemp, + refKind: variableRepresentsLocation ? RefKind.Ref : RefKind.None, + isKnownToReferToTempIfReferenceType: !variableRepresentsLocation || rewrittenReceiver.Type.IsValueType || + !CodeGenerator.HasHome(rewrittenReceiver, + CodeGenerator.AddressKind.Constrained, + _factory.CurrentFunction, + peVerifyCompatEnabled: false, + stackLocalsOpt: null)); temps.Add(receiverTemp.LocalSymbol); if (!isRegularCompoundAssignment && @@ -462,7 +485,6 @@ private BoundIndexerAccess TransformIndexerAccessContinued( private BoundExpression TransformImplicitIndexerAccess( BoundImplicitIndexerAccess indexerAccess, - bool isRegularCompoundAssignment, ArrayBuilder stores, ArrayBuilder temps, bool isDynamicAssignment) @@ -472,19 +494,19 @@ private BoundExpression TransformImplicitIndexerAccess( _compilation.GetWellKnownType(WellKnownType.System_Index), TypeCompareKind.ConsiderEverything)) { - return TransformIndexPatternIndexerAccess(indexerAccess, isRegularCompoundAssignment, stores, temps, isDynamicAssignment); + return TransformIndexPatternIndexerAccess(indexerAccess, stores, temps, isDynamicAssignment); } throw ExceptionUtilities.UnexpectedValue(indexerAccess.Argument.Type); } - private BoundExpression TransformIndexPatternIndexerAccess(BoundImplicitIndexerAccess implicitIndexerAccess, bool isRegularCompoundAssignment, ArrayBuilder stores, ArrayBuilder temps, bool isDynamicAssignment) + private BoundExpression TransformIndexPatternIndexerAccess(BoundImplicitIndexerAccess implicitIndexerAccess, ArrayBuilder stores, ArrayBuilder temps, bool isDynamicAssignment) { Debug.Assert(implicitIndexerAccess.IndexerOrSliceAccess.GetRefKind() == RefKind.None); var access = GetUnderlyingIndexerOrSliceAccess( implicitIndexerAccess, isLeftOfAssignment: true, - isRegularAssignmentOrRegularCompoundAssignment: isRegularCompoundAssignment, + isRegularAssignment: false, cacheAllArgumentsOnly: false, stores, temps); @@ -682,7 +704,7 @@ private BoundExpression TransformCompoundAssignmentLHS(BoundExpression originalL if (implicitIndexerAccess.GetRefKind() == RefKind.None) { - return TransformImplicitIndexerAccess(implicitIndexerAccess, isRegularCompoundAssignment, stores, temps, isDynamicAssignment); + return TransformImplicitIndexerAccess(implicitIndexerAccess, stores, temps, isDynamicAssignment); } } break; @@ -782,6 +804,7 @@ private BoundExpression TransformCompoundAssignmentLHS(BoundExpression originalL if (eventAccess.EventSymbol.IsWindowsRuntimeEvent) { + Debug.Assert(!isRegularCompoundAssignment); // This is a temporary object that will be rewritten away before the lowering completes. return eventAccess.Update(TransformPropertyOrEventReceiver(eventAccess.EventSymbol, eventAccess.ReceiverOpt, isRegularCompoundAssignment, stores, temps), diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ForEachStatement.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ForEachStatement.cs index 0a099fe3229ed..44fe74506b1b0 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ForEachStatement.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ForEachStatement.cs @@ -6,6 +6,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_IndexerAccess.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_IndexerAccess.cs index ad0ab5f035580..23f967dac28de 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_IndexerAccess.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_IndexerAccess.cs @@ -458,7 +458,7 @@ private BoundExpression VisitIndexPatternIndexerAccess(BoundImplicitIndexerAcces BoundExpression rewrittenIndexerAccess = GetUnderlyingIndexerOrSliceAccess( node, isLeftOfAssignment, - isRegularAssignmentOrRegularCompoundAssignment: isLeftOfAssignment, + isRegularAssignment: isLeftOfAssignment, cacheAllArgumentsOnly: false, sideeffects, locals); @@ -471,7 +471,7 @@ private BoundExpression VisitIndexPatternIndexerAccess(BoundImplicitIndexerAcces private BoundExpression GetUnderlyingIndexerOrSliceAccess( BoundImplicitIndexerAccess node, bool isLeftOfAssignment, - bool isRegularAssignmentOrRegularCompoundAssignment, + bool isRegularAssignment, bool cacheAllArgumentsOnly, ArrayBuilder sideeffects, ArrayBuilder locals) @@ -508,7 +508,7 @@ private BoundExpression GetUnderlyingIndexerOrSliceAccess( if (receiverLocal.LocalSymbol.IsRef && CodeGenerator.IsPossibleReferenceTypeReceiverOfConstrainedCall(receiverLocal) && !CodeGenerator.ReceiverIsKnownToReferToTempIfReferenceType(receiverLocal) && - ((isLeftOfAssignment && !isRegularAssignmentOrRegularCompoundAssignment) || + ((isLeftOfAssignment && !isRegularAssignment) || !CodeGenerator.IsSafeToDereferenceReceiverRefAfterEvaluatingArguments(ImmutableArray.Create(makeOffsetInput)))) { BoundAssignmentOperator? extraRefInitialization; diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectOrCollectionInitializerExpression.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectOrCollectionInitializerExpression.cs index d773ccb44eb24..a8e846b07b23f 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectOrCollectionInitializerExpression.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectOrCollectionInitializerExpression.cs @@ -519,7 +519,7 @@ private void AddObjectInitializer( rewrittenAccess = GetUnderlyingIndexerOrSliceAccess( implicitIndexer, isLeftOfAssignment: !isRhsNestedInitializer, - isRegularAssignmentOrRegularCompoundAssignment: true, + isRegularAssignment: true, cacheAllArgumentsOnly: true, result, temps); diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_UnaryOperator.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_UnaryOperator.cs index 6ca0582defaf7..57ce82276c47b 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_UnaryOperator.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_UnaryOperator.cs @@ -6,6 +6,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; @@ -404,13 +405,17 @@ private BoundExpression VisitIncrementOperator(BoundIncrementOperator node, bool private BoundExpression VisitInstanceIncrementOperator(BoundIncrementOperator node, bool used) { Debug.Assert(node.MethodOpt is { }); + Debug.Assert(node.OperandConversion is null || (node.Operand.Type!.IsReferenceType && node.MethodOpt.GetIsNewExtensionMember())); SyntaxNode syntax = node.Syntax; if (!used) { Debug.Assert(node.Type.IsVoidType()); - return BoundCall.Synthesized(syntax, VisitExpression(node.Operand), initialBindingReceiverIsSubjectToCloning: ThreeState.False, node.MethodOpt); + return BoundCall.Synthesized(syntax, + ApplyConversionIfNotIdentity(node.OperandConversion, node.OperandPlaceholder, VisitExpression(node.Operand)), + initialBindingReceiverIsSubjectToCloning: ThreeState.False, + node.MethodOpt); } TypeSymbol? operandType = node.Operand.Type; //type of the variable being incremented @@ -431,11 +436,20 @@ private BoundExpression VisitInstanceIncrementOperator(BoundIncrementOperator no return new BoundSequence( syntax: syntax, locals: [boundTemp.LocalSymbol], - sideEffects: [tempAssignment, BoundCall.Synthesized(syntax, boundTemp, initialBindingReceiverIsSubjectToCloning: ThreeState.False, node.MethodOpt)], + sideEffects: + [ + tempAssignment, + BoundCall.Synthesized(syntax, + ApplyConversionIfNotIdentity(node.OperandConversion, node.OperandPlaceholder, boundTemp), + initialBindingReceiverIsSubjectToCloning: ThreeState.False, + node.MethodOpt) + ], value: boundTemp, type: operandType); } + Debug.Assert(node.OperandConversion is null); + return MakeInstanceCompoundAssignmentOperatorResult(node.Syntax, node.Operand, rightOpt: null, node.MethodOpt, node.OperatorKind.IsChecked()); } @@ -568,7 +582,7 @@ public BoundExpression VisitBuiltInOrStaticIncrementOperator(BoundIncrementOpera // This will be filled in with the LHS that uses temporaries to prevent // double-evaluation of side effects. - BoundExpression transformedLHS = TransformCompoundAssignmentLHS(node.Operand, isRegularCompoundAssignment: true, tempInitializers, tempSymbols, isDynamic); + BoundExpression transformedLHS = TransformCompoundAssignmentLHS(node.Operand, isRegularCompoundAssignment: false, tempInitializers, tempSymbols, isDynamic); TypeSymbol? operandType = transformedLHS.Type; //type of the variable being incremented Debug.Assert(operandType is { }); Debug.Assert(TypeSymbol.Equals(operandType, node.Type, TypeCompareKind.ConsiderEverything2)); diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LoweredDynamicOperationFactory.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LoweredDynamicOperationFactory.cs index d2543a5cbf121..e42b6608f4cb2 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LoweredDynamicOperationFactory.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LoweredDynamicOperationFactory.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Immutable; using System.Diagnostics; +using System.Linq; using Microsoft.CodeAnalysis.CSharp.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/Lowering/SyntheticBoundNodeFactory.cs b/src/Compilers/CSharp/Portable/Lowering/SyntheticBoundNodeFactory.cs index 15748f836eb9c..f5b0564e0e5bc 100644 --- a/src/Compilers/CSharp/Portable/Lowering/SyntheticBoundNodeFactory.cs +++ b/src/Compilers/CSharp/Portable/Lowering/SyntheticBoundNodeFactory.cs @@ -10,11 +10,11 @@ using System.Linq; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.CodeGen; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/Compilers/CSharp/Portable/Parser/AbstractLexer.cs b/src/Compilers/CSharp/Portable/Parser/AbstractLexer.cs index 74d7865c81f87..6eb8346d6fdd3 100644 --- a/src/Compilers/CSharp/Portable/Parser/AbstractLexer.cs +++ b/src/Compilers/CSharp/Portable/Parser/AbstractLexer.cs @@ -4,8 +4,6 @@ using System; using System.Collections.Generic; -using Microsoft.CodeAnalysis.CSharp.Symbols; -using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax @@ -21,6 +19,8 @@ protected AbstractLexer(SourceText text) this.TextWindow = new SlidingTextWindow(text); } + protected int LexemeStartPosition => this.TextWindow.LexemeStartPosition; + public virtual void Dispose() { this.TextWindow.Dispose(); @@ -131,9 +131,18 @@ protected XmlSyntaxDiagnosticInfo MakeError(int position, int width, XmlParseErr private int GetLexemeOffsetFromPosition(int position) { - return position >= TextWindow.LexemeStartPosition ? position - TextWindow.LexemeStartPosition : position; + return position >= LexemeStartPosition ? position - LexemeStartPosition : position; } + protected string GetNonInternedLexemeText() + => TextWindow.GetText(intern: false); + + protected string GetInternedLexemeText() + => TextWindow.GetText(intern: true); + + protected int CurrentLexemeWidth + => this.TextWindow.Position - LexemeStartPosition; + protected static SyntaxDiagnosticInfo MakeError(ErrorCode code) { return new SyntaxDiagnosticInfo(code); diff --git a/src/Compilers/CSharp/Portable/Parser/LanguageParser.cs b/src/Compilers/CSharp/Portable/Parser/LanguageParser.cs index 6eb6490e76872..03c05482213f6 100644 --- a/src/Compilers/CSharp/Portable/Parser/LanguageParser.cs +++ b/src/Compilers/CSharp/Portable/Parser/LanguageParser.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; @@ -14,7 +15,6 @@ namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { - using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Syntax.InternalSyntax; internal sealed partial class LanguageParser : SyntaxParser diff --git a/src/Compilers/CSharp/Portable/Parser/LanguageParser_Patterns.cs b/src/Compilers/CSharp/Portable/Parser/LanguageParser_Patterns.cs index 712ddc1633420..d351e40e201da 100644 --- a/src/Compilers/CSharp/Portable/Parser/LanguageParser_Patterns.cs +++ b/src/Compilers/CSharp/Portable/Parser/LanguageParser_Patterns.cs @@ -47,7 +47,7 @@ when ConvertExpressionToType(expr, out var leftType): default: type = null; return false; - }; + } } private PatternSyntax ParsePattern(Precedence precedence, bool afterIs = false, bool inSwitchArmPattern = false) diff --git a/src/Compilers/CSharp/Portable/Parser/Lexer.cs b/src/Compilers/CSharp/Portable/Parser/Lexer.cs index c7f270cbf813f..0304312bc20a5 100644 --- a/src/Compilers/CSharp/Portable/Parser/Lexer.cs +++ b/src/Compilers/CSharp/Portable/Parser/Lexer.cs @@ -467,7 +467,7 @@ private void ScanSyntaxToken(ref TokenInfo info) { var atDotPosition = this.TextWindow.Position; if (atDotPosition >= 1 && - atDotPosition == this.TextWindow.LexemeStartPosition) + atDotPosition == this.LexemeStartPosition) { // We have something like: .0 // @@ -636,12 +636,12 @@ private void ScanSyntaxToken(ref TokenInfo info) this.AddError(TextWindow.Position + 1, width: 1, ErrorCode.ERR_ExpectedVerbatimLiteral); this.ScanToEndOfLine(); - info.Text = TextWindow.GetText(false); + info.Text = this.GetNonInternedLexemeText(); break; } this.ConsumeAtSignSequence(); - info.Text = TextWindow.GetText(intern: true); + info.Text = this.GetInternedLexemeText(); this.AddError(ErrorCode.ERR_ExpectedVerbatimLiteral); } break; @@ -727,7 +727,7 @@ private void ScanSyntaxToken(ref TokenInfo info) // number of errors. if (_badTokenCount++ <= 200) { - info.Text = TextWindow.GetText(intern: true); + info.Text = this.GetInternedLexemeText(); } else { @@ -925,7 +925,7 @@ private bool ScanNumericLiteral(ref TokenInfo info) { // Previously, in DebuggerSyntax mode, "123#" was a valid identifier. TextWindow.AdvanceChar(); - info.StringValue = info.Text = TextWindow.GetText(intern: true); + info.StringValue = info.Text = this.GetInternedLexemeText(); info.Kind = SyntaxKind.IdentifierToken; this.AddError(MakeError(ErrorCode.ERR_LegacyObjectIdSyntax)); return true; @@ -1048,7 +1048,7 @@ private bool ScanNumericLiteral(ref TokenInfo info) } info.Kind = SyntaxKind.NumericLiteralToken; - info.Text = TextWindow.GetText(true); + info.Text = this.GetInternedLexemeText(); Debug.Assert(info.Text != null); var valueText = TextWindow.Intern(_builder); ulong val; @@ -1597,10 +1597,10 @@ private bool ScanIdentifier_SlowPath(ref TokenInfo info) } LoopExit: - var width = TextWindow.Width; // exact size of input characters + var width = this.CurrentLexemeWidth; // exact size of input characters if (_identLen > 0) { - info.Text = TextWindow.GetInternedText(); + info.Text = GetInternedLexemeText(); // id buffer is identical to width in input if (_identLen == width) @@ -1806,18 +1806,18 @@ private bool ScanIdentifier_CrefSlowPath(ref TokenInfo info) // The text does not have to be interned (and probably shouldn't be // if it contains entities (else-case). - var width = TextWindow.Width; // exact size of input characters + var width = this.CurrentLexemeWidth; // exact size of input characters // id buffer is identical to width in input if (_identLen == width) { - info.StringValue = TextWindow.GetInternedText(); + info.StringValue = this.GetInternedLexemeText(); info.Text = info.StringValue; } else { info.StringValue = TextWindow.Intern(_identBuffer, 0, _identLen); - info.Text = TextWindow.GetText(intern: false); + info.Text = this.GetNonInternedLexemeText(); } return true; @@ -2056,7 +2056,7 @@ private void LexSyntaxTrivia(bool isFollowingToken, bool isTrailing, ref SyntaxL void lexSingleLineComment(ref SyntaxListBuilder triviaList) { this.ScanToEndOfLine(); - var text = TextWindow.GetText(false); + var text = this.GetNonInternedLexemeText(); this.AddTrivia(SyntaxFactory.Comment(text), ref triviaList); } @@ -2070,7 +2070,7 @@ void lexMultiLineComment(ref SyntaxListBuilder triviaList, char delimiter) this.AddError(ErrorCode.ERR_OpenEndedComment); } - var text = TextWindow.GetText(false); + var text = this.GetNonInternedLexemeText(); this.AddTrivia(SyntaxFactory.Comment(text), ref triviaList); } } @@ -2166,9 +2166,9 @@ private SyntaxListBuilder LexConflictMarkerDisabledText(bool atSecondMiddleMarke this.TextWindow.AdvanceChar(); } - if (this.TextWindow.Width > 0) + if (this.CurrentLexemeWidth > 0) { - this.AddTrivia(SyntaxFactory.DisabledText(TextWindow.GetText(false)), ref triviaList); + this.AddTrivia(SyntaxFactory.DisabledText(this.GetNonInternedLexemeText()), ref triviaList); } if (hitNextMarker) @@ -2187,9 +2187,9 @@ private void LexConflictMarkerEndOfLine(ref SyntaxListBuilder triviaList) this.TextWindow.AdvanceChar(); } - if (this.TextWindow.Width > 0) + if (this.CurrentLexemeWidth > 0) { - this.AddTrivia(SyntaxFactory.EndOfLine(TextWindow.GetText(false)), ref triviaList); + this.AddTrivia(SyntaxFactory.EndOfLine(this.GetNonInternedLexemeText()), ref triviaList); } } @@ -2206,7 +2206,7 @@ private void LexConflictMarkerHeader(ref SyntaxListBuilder triviaList) this.TextWindow.AdvanceChar(); } - this.AddTrivia(SyntaxFactory.ConflictMarker(TextWindow.GetText(false)), ref triviaList); + this.AddTrivia(SyntaxFactory.ConflictMarker(this.GetNonInternedLexemeText()), ref triviaList); } private void AddTrivia(CSharpSyntaxNode trivia, [NotNull] ref SyntaxListBuilder? list) @@ -2326,20 +2326,18 @@ private SyntaxTrivia ScanWhitespace() break; } - if (TextWindow.Width == 1 && onlySpaces) + if (this.CurrentLexemeWidth == 1 && onlySpaces) { return SyntaxFactory.Space; } else { - var width = TextWindow.Width; + var width = this.CurrentLexemeWidth; if (width < MaxCachedTokenSize) { return _cache.LookupTrivia( - TextWindow.CharacterWindow, - TextWindow.LexemeRelativeStart, - width, + TextWindow.CharacterWindow.AsSpan(TextWindow.LexemeRelativeStart, width), hashCode, CreateWhitespaceTrivia, TextWindow); @@ -2455,7 +2453,7 @@ private CSharpSyntaxNode ParseDirective( } followedByDirective = false; - return TextWindow.Width > 0 ? SyntaxFactory.DisabledText(TextWindow.GetText(false)) : null; + return this.CurrentLexemeWidth > 0 ? SyntaxFactory.DisabledText(this.GetNonInternedLexemeText()) : null; case '#': if (!_allowPreprocessorDirectives) goto default; followedByDirective = true; @@ -2465,7 +2463,7 @@ private CSharpSyntaxNode ParseDirective( } TextWindow.Reset(lastLineStart); // reset so directive parser can consume the starting whitespace on this line - return TextWindow.Width > 0 ? SyntaxFactory.DisabledText(TextWindow.GetText(false)) : null; + return this.CurrentLexemeWidth > 0 ? SyntaxFactory.DisabledText(this.GetNonInternedLexemeText()) : null; case '\r': case '\n': this.ScanEndOfLine(); @@ -2678,7 +2676,7 @@ private bool ScanDirectiveToken(ref TokenInfo info) case '9': this.ScanInteger(); info.Kind = SyntaxKind.NumericLiteralToken; - info.Text = TextWindow.GetText(true); + info.Text = this.GetInternedLexemeText(); info.ValueKind = SpecialType.System_Int32; info.IntValue = this.GetValueInt32(info.Text, false); break; @@ -2726,7 +2724,7 @@ private bool ScanDirectiveToken(ref TokenInfo info) } info.Kind = SyntaxKind.None; - info.Text = TextWindow.GetText(true); + info.Text = this.GetInternedLexemeText(); } break; @@ -2781,7 +2779,7 @@ private void LexDirectiveTrailingTrivia(bool includeEndOfLine, ref SyntaxListBui { // normal single line comment this.ScanToEndOfLine(); - var text = TextWindow.GetText(false); + var text = this.GetNonInternedLexemeText(); trivia = SyntaxFactory.Comment(text); } @@ -2836,7 +2834,7 @@ private CSharpSyntaxNode LexXmlDocComment(XmlDocCommentStyle style) // The comment didn't end. Report an error at the start point. // NOTE: report this error even if the DocumentationMode is less than diagnose - the comment // would be malformed as a non-doc comment as well. - this.AddError(TextWindow.LexemeStartPosition, TextWindow.Width, ErrorCode.ERR_OpenEndedComment); + this.AddError(this.LexemeStartPosition, this.CurrentLexemeWidth, ErrorCode.ERR_OpenEndedComment); } return docComment; @@ -2915,7 +2913,7 @@ private bool ScanXmlToken(ref TokenInfo info) private void ScanXmlTextLiteralNewLineToken(ref TokenInfo info) { this.ScanEndOfLine(); - info.StringValue = info.Text = TextWindow.GetText(intern: false); + info.StringValue = info.Text = this.GetNonInternedLexemeText(); info.Kind = SyntaxKind.XmlTextLiteralNewLineToken; this.MutateLocation(XmlDocCommentLocation.Exterior); } @@ -3057,7 +3055,7 @@ private void ScanXmlEntity(ref TokenInfo info) if (MatchesProductionForXmlChar(charValue)) { char lowSurrogate; - char highSurrogate = SlidingTextWindow.GetCharsFromUtf32(charValue, out lowSurrogate); + char highSurrogate = GetCharsFromUtf32(charValue, out lowSurrogate); _builder.Append(highSurrogate); if (lowSurrogate != SlidingTextWindow.InvalidCharacter) @@ -3111,7 +3109,7 @@ private void ScanXmlEntity(ref TokenInfo info) // If we don't have a value computed from above, then we don't recognize the entity, in which // case we will simply use the text. - info.Text = TextWindow.GetText(true); + info.Text = this.GetInternedLexemeText(); if (info.StringValue == null) { info.StringValue = info.Text; @@ -3142,7 +3140,7 @@ private void ScanXmlText(ref TokenInfo info) if (TextWindow.PeekChar() == ']' && TextWindow.PeekChar(1) == ']' && TextWindow.PeekChar(2) == '>') { TextWindow.AdvanceChar(3); - info.StringValue = info.Text = TextWindow.GetText(false); + info.StringValue = info.Text = this.GetNonInternedLexemeText(); this.AddError(XmlParseErrorCode.XML_CDataEndTagNotAllowed); return; } @@ -3158,20 +3156,20 @@ private void ScanXmlText(ref TokenInfo info) goto default; } - info.StringValue = info.Text = TextWindow.GetText(false); + info.StringValue = info.Text = this.GetNonInternedLexemeText(); return; case '&': case '<': case '\r': case '\n': - info.StringValue = info.Text = TextWindow.GetText(false); + info.StringValue = info.Text = this.GetNonInternedLexemeText(); return; case '*': if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') { // we're at the end of the comment, but don't lex it yet. - info.StringValue = info.Text = TextWindow.GetText(false); + info.StringValue = info.Text = this.GetNonInternedLexemeText(); return; } @@ -3180,7 +3178,7 @@ private void ScanXmlText(ref TokenInfo info) case ']': if (TextWindow.PeekChar(1) == ']' && TextWindow.PeekChar(2) == '>') { - info.StringValue = info.Text = TextWindow.GetText(false); + info.StringValue = info.Text = this.GetNonInternedLexemeText(); return; } @@ -3320,7 +3318,7 @@ private bool ScanXmlElementTagToken(ref TokenInfo info) { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.None; - info.StringValue = info.Text = TextWindow.GetText(false); + info.StringValue = info.Text = this.GetNonInternedLexemeText(); } break; @@ -3484,7 +3482,7 @@ private void ScanXmlAttributeText(ref TokenInfo info) case '"': if (this.ModeIs(LexerMode.XmlAttributeTextDoubleQuote)) { - info.StringValue = info.Text = TextWindow.GetText(false); + info.StringValue = info.Text = this.GetNonInternedLexemeText(); return; } @@ -3493,7 +3491,7 @@ private void ScanXmlAttributeText(ref TokenInfo info) case '\'': if (this.ModeIs(LexerMode.XmlAttributeTextQuote)) { - info.StringValue = info.Text = TextWindow.GetText(false); + info.StringValue = info.Text = this.GetNonInternedLexemeText(); return; } @@ -3503,7 +3501,7 @@ private void ScanXmlAttributeText(ref TokenInfo info) case '<': case '\r': case '\n': - info.StringValue = info.Text = TextWindow.GetText(false); + info.StringValue = info.Text = this.GetNonInternedLexemeText(); return; case SlidingTextWindow.InvalidCharacter: @@ -3512,14 +3510,14 @@ private void ScanXmlAttributeText(ref TokenInfo info) goto default; } - info.StringValue = info.Text = TextWindow.GetText(false); + info.StringValue = info.Text = this.GetNonInternedLexemeText(); return; case '*': if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') { // we're at the end of the comment, but don't lex it yet. - info.StringValue = info.Text = TextWindow.GetText(false); + info.StringValue = info.Text = this.GetNonInternedLexemeText(); return; } @@ -3657,7 +3655,7 @@ private bool ScanXmlCrefToken(ref TokenInfo info) break; case '<': - info.Text = TextWindow.GetText(intern: false); + info.Text = this.GetNonInternedLexemeText(); this.AddError(XmlParseErrorCode.XML_LessThanInAttributeValue, info.Text); //ErrorCode.WRN_XMLParseError return true; @@ -3821,7 +3819,7 @@ private bool ScanXmlCrefToken(ref TokenInfo info) Debug.Assert(info.StringValue == null, "Haven't tried to set it yet."); string valueText = SyntaxFacts.GetText(info.Kind); - string actualText = TextWindow.GetText(intern: false); + string actualText = this.GetNonInternedLexemeText(); if (!string.IsNullOrEmpty(valueText) && actualText != valueText) { info.RequiresTextForXmlEntity = true; @@ -3870,7 +3868,7 @@ private bool ScanXmlCrefToken(ref TokenInfo info) if (TextWindow.PeekChar() == '@') { TextWindow.NextChar(); - info.Text = TextWindow.GetText(intern: true); + info.Text = this.GetInternedLexemeText(); info.StringValue = ""; // Can't be null for an identifier. } else @@ -3890,7 +3888,7 @@ private bool ScanXmlCrefToken(ref TokenInfo info) else { char bad = TextWindow.NextChar(); - info.Text = TextWindow.GetText(intern: false); + info.Text = this.GetNonInternedLexemeText(); // If it's valid in XML, then it was unexpected in cref mode. // Otherwise, it's just bad XML. @@ -4086,7 +4084,7 @@ private void ScanXmlCDataSectionText(ref TokenInfo info) case ']': if (TextWindow.PeekChar(1) == ']' && TextWindow.PeekChar(2) == '>') { - info.StringValue = info.Text = TextWindow.GetText(false); + info.StringValue = info.Text = this.GetNonInternedLexemeText(); return; } @@ -4094,7 +4092,7 @@ private void ScanXmlCDataSectionText(ref TokenInfo info) case '\r': case '\n': - info.StringValue = info.Text = TextWindow.GetText(false); + info.StringValue = info.Text = this.GetNonInternedLexemeText(); return; case SlidingTextWindow.InvalidCharacter: @@ -4103,14 +4101,14 @@ private void ScanXmlCDataSectionText(ref TokenInfo info) goto default; } - info.StringValue = info.Text = TextWindow.GetText(false); + info.StringValue = info.Text = this.GetNonInternedLexemeText(); return; case '*': if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') { // we're at the end of the comment, but don't lex it yet. - info.StringValue = info.Text = TextWindow.GetText(false); + info.StringValue = info.Text = this.GetNonInternedLexemeText(); return; } @@ -4216,7 +4214,7 @@ private void ScanXmlCommentText(ref TokenInfo info) case '-': if (TextWindow.PeekChar(1) == '-') { - info.StringValue = info.Text = TextWindow.GetText(false); + info.StringValue = info.Text = this.GetNonInternedLexemeText(); return; } @@ -4224,7 +4222,7 @@ private void ScanXmlCommentText(ref TokenInfo info) case '\r': case '\n': - info.StringValue = info.Text = TextWindow.GetText(false); + info.StringValue = info.Text = this.GetNonInternedLexemeText(); return; case SlidingTextWindow.InvalidCharacter: @@ -4233,14 +4231,14 @@ private void ScanXmlCommentText(ref TokenInfo info) goto default; } - info.StringValue = info.Text = TextWindow.GetText(false); + info.StringValue = info.Text = this.GetNonInternedLexemeText(); return; case '*': if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') { // we're at the end of the comment, but don't lex it yet. - info.StringValue = info.Text = TextWindow.GetText(false); + info.StringValue = info.Text = this.GetNonInternedLexemeText(); return; } @@ -4340,7 +4338,7 @@ private void ScanXmlProcessingInstructionText(ref TokenInfo info) case '?': if (TextWindow.PeekChar(1) == '>') { - info.StringValue = info.Text = TextWindow.GetText(false); + info.StringValue = info.Text = this.GetNonInternedLexemeText(); return; } @@ -4348,7 +4346,7 @@ private void ScanXmlProcessingInstructionText(ref TokenInfo info) case '\r': case '\n': - info.StringValue = info.Text = TextWindow.GetText(false); + info.StringValue = info.Text = this.GetNonInternedLexemeText(); return; case SlidingTextWindow.InvalidCharacter: @@ -4357,14 +4355,14 @@ private void ScanXmlProcessingInstructionText(ref TokenInfo info) goto default; } - info.StringValue = info.Text = TextWindow.GetText(false); + info.StringValue = info.Text = this.GetNonInternedLexemeText(); return; case '*': if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') { // we're at the end of the comment, but don't lex it yet. - info.StringValue = info.Text = TextWindow.GetText(false); + info.StringValue = info.Text = this.GetNonInternedLexemeText(); return; } @@ -4403,7 +4401,7 @@ private void LexXmlDocCommentLeadingTrivia(ref SyntaxListBuilder? trivia) && TextWindow.PeekChar(3) != '*') { TextWindow.AdvanceChar(3); - var text = TextWindow.GetText(true); + var text = this.GetInternedLexemeText(); this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia); this.MutateLocation(XmlDocCommentLocation.Interior); return; @@ -4432,7 +4430,7 @@ private void LexXmlDocCommentLeadingTrivia(ref SyntaxListBuilder? trivia) if (this.StyleIs(XmlDocCommentStyle.SingleLine) && TextWindow.PeekChar(1) == '/' && TextWindow.PeekChar(2) == '/' && TextWindow.PeekChar(3) != '/') { TextWindow.AdvanceChar(3); - var text = TextWindow.GetText(true); + var text = this.GetInternedLexemeText(); this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia); this.MutateLocation(XmlDocCommentLocation.Interior); return; @@ -4448,7 +4446,7 @@ private void LexXmlDocCommentLeadingTrivia(ref SyntaxListBuilder? trivia) TextWindow.AdvanceChar(); } - var text = TextWindow.GetText(true); + var text = this.GetInternedLexemeText(); if (!String.IsNullOrEmpty(text)) { this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia); @@ -4494,7 +4492,7 @@ private void LexXmlDocCommentLeadingTrivia(ref SyntaxListBuilder? trivia) { Debug.Assert(this.StyleIs(XmlDocCommentStyle.Delimited)); - var text = TextWindow.GetText(true); + var text = this.GetInternedLexemeText(); if (!String.IsNullOrEmpty(text)) this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia); this.MutateLocation(XmlDocCommentLocation.Interior); @@ -4509,7 +4507,7 @@ private void LexXmlDocCommentLeadingTrivia(ref SyntaxListBuilder? trivia) if (TextWindow.PeekChar() == '*' && TextWindow.PeekChar(1) == '/') { TextWindow.AdvanceChar(2); - var text = TextWindow.GetText(true); + var text = this.GetInternedLexemeText(); this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia); this.MutateLocation(XmlDocCommentLocation.End); } @@ -4861,12 +4859,12 @@ public bool TryScanXmlEntity(out char ch, out char surrogate) private SyntaxDiagnosticInfo CreateIllegalEscapeDiagnostic(int start) { - return new SyntaxDiagnosticInfo(start - TextWindow.LexemeStartPosition, + return new SyntaxDiagnosticInfo(start - this.LexemeStartPosition, TextWindow.Position - start, ErrorCode.ERR_IllegalEscape); } - internal static char GetCharsFromUtf32(uint codepoint, out char lowSurrogate) + private static char GetCharsFromUtf32(uint codepoint, out char lowSurrogate) { if (codepoint < (uint)0x00010000) { diff --git a/src/Compilers/CSharp/Portable/Parser/LexerCache.cs b/src/Compilers/CSharp/Portable/Parser/LexerCache.cs index 539783ac11355..af20e88e0f25a 100644 --- a/src/Compilers/CSharp/Portable/Parser/LexerCache.cs +++ b/src/Compilers/CSharp/Portable/Parser/LexerCache.cs @@ -182,19 +182,17 @@ internal bool TryGetKeywordKind(string key, out SyntaxKind kind) } internal SyntaxTrivia LookupTrivia( - char[] textBuffer, - int keyStart, - int keyLength, + ReadOnlySpan textBuffer, int hashCode, Func createTriviaFunction, TArg data) { - var value = TriviaMap.FindItem(textBuffer, keyStart, keyLength, hashCode); + var value = TriviaMap.FindItem(textBuffer, hashCode); if (value == null) { value = createTriviaFunction(data); - TriviaMap.AddItem(textBuffer, keyStart, keyLength, hashCode, value); + TriviaMap.AddItem(textBuffer, hashCode, value); } return value; @@ -222,14 +220,12 @@ private static void Miss() #endif internal SyntaxToken LookupToken( - char[] textBuffer, - int keyStart, - int keyLength, + ReadOnlySpan textBuffer, int hashCode, Func createTokenFunction, TArg data) { - var value = TokenMap.FindItem(textBuffer, keyStart, keyLength, hashCode); + var value = TokenMap.FindItem(textBuffer, hashCode); if (value == null) { @@ -237,7 +233,7 @@ internal SyntaxToken LookupToken( Miss(); #endif value = createTokenFunction(data); - TokenMap.AddItem(textBuffer, keyStart, keyLength, hashCode, value); + TokenMap.AddItem(textBuffer, hashCode, value); } else { diff --git a/src/Compilers/CSharp/Portable/Parser/Lexer_RawStringLiteral.cs b/src/Compilers/CSharp/Portable/Parser/Lexer_RawStringLiteral.cs index 067f78a2e77d1..2bcb4e991ef90 100644 --- a/src/Compilers/CSharp/Portable/Parser/Lexer_RawStringLiteral.cs +++ b/src/Compilers/CSharp/Portable/Parser/Lexer_RawStringLiteral.cs @@ -87,7 +87,7 @@ private void ScanRawStringLiteral(ref TokenInfo info, bool inDirective) // trusting the contents. if (this.HasErrors) { - var afterStartDelimiter = TextWindow.LexemeStartPosition + startingQuoteCount; + var afterStartDelimiter = this.LexemeStartPosition + startingQuoteCount; var valueLength = TextWindow.Position - afterStartDelimiter; info.StringValue = TextWindow.GetText( @@ -117,10 +117,10 @@ private void ScanRawStringLiteral(ref TokenInfo info, bool inDirective) default: throw ExceptionUtilities.UnexpectedValue(info.Kind); - }; + } } - info.Text = TextWindow.GetText(intern: true); + info.Text = this.GetInternedLexemeText(); } private void ScanSingleLineRawStringLiteral(ref TokenInfo info, int startingQuoteCount) @@ -169,7 +169,7 @@ private void ScanSingleLineRawStringLiteral(ref TokenInfo info, int startingQuot } // We have enough quotes to finish this string at this point. - var afterStartDelimiter = TextWindow.LexemeStartPosition + startingQuoteCount; + var afterStartDelimiter = this.LexemeStartPosition + startingQuoteCount; var valueLength = beforeEndDelimiter - afterStartDelimiter; info.StringValue = TextWindow.GetText( diff --git a/src/Compilers/CSharp/Portable/Parser/Lexer_StringLiteral.cs b/src/Compilers/CSharp/Portable/Parser/Lexer_StringLiteral.cs index dae9e5809da36..09dcf9e03b64d 100644 --- a/src/Compilers/CSharp/Portable/Parser/Lexer_StringLiteral.cs +++ b/src/Compilers/CSharp/Portable/Parser/Lexer_StringLiteral.cs @@ -60,7 +60,7 @@ private void ScanStringLiteral(ref TokenInfo info, bool inDirective) //String and character literals can contain any Unicode character. They are not limited //to valid UTF-16 characters. So if we get the SlidingTextWindow's sentinel value, //double check that it was not real user-code contents. This will be rare. - Debug.Assert(TextWindow.Width > 0); + Debug.Assert(this.CurrentLexemeWidth > 0); this.AddError(ErrorCode.ERR_NewlineInConst); break; } @@ -73,7 +73,7 @@ private void ScanStringLiteral(ref TokenInfo info, bool inDirective) if (quoteCharacter == '\'') { - info.Text = TextWindow.GetText(intern: true); + info.Text = this.GetInternedLexemeText(); info.Kind = SyntaxKind.CharacterLiteralToken; if (_builder.Length != 1) { @@ -102,7 +102,7 @@ private void ScanStringLiteral(ref TokenInfo info, bool inDirective) info.Kind = SyntaxKind.StringLiteralToken; } - info.Text = TextWindow.GetText(intern: true); + info.Text = this.GetInternedLexemeText(); if (_builder.Length > 0) { @@ -247,7 +247,7 @@ private void ScanVerbatimStringLiteral(ref TokenInfo info) info.Kind = SyntaxKind.StringLiteralToken; } - info.Text = TextWindow.GetText(intern: false); + info.Text = this.GetNonInternedLexemeText(); info.StringValue = _builder.ToString(); } @@ -290,7 +290,7 @@ internal void ScanInterpolatedStringLiteralTop( subScanner.ScanInterpolatedStringLiteralTop(out kind, out openQuoteRange, interpolations, out closeQuoteRange); error = subScanner.Error; info.Kind = SyntaxKind.InterpolatedStringToken; - info.Text = TextWindow.GetText(intern: false); + info.Text = this.GetNonInternedLexemeText(); } /// diff --git a/src/Compilers/CSharp/Portable/Parser/QuickScanner.cs b/src/Compilers/CSharp/Portable/Parser/QuickScanner.cs index 0084d14b53f80..8c2719757aec3 100644 --- a/src/Compilers/CSharp/Portable/Parser/QuickScanner.cs +++ b/src/Compilers/CSharp/Portable/Parser/QuickScanner.cs @@ -235,9 +235,7 @@ private enum CharFlags : byte { // this is a good token! var token = _cache.LookupToken( - TextWindow.CharacterWindow, - TextWindow.LexemeRelativeStart, - i - TextWindow.LexemeRelativeStart, + TextWindow.CharacterWindow.AsSpan(TextWindow.LexemeRelativeStart, i - TextWindow.LexemeRelativeStart), hashCode, CreateQuickToken, this); diff --git a/src/Compilers/CSharp/Portable/Parser/SlidingTextWindow.cs b/src/Compilers/CSharp/Portable/Parser/SlidingTextWindow.cs index 6e39642976469..fa5fd29df9885 100644 --- a/src/Compilers/CSharp/Portable/Parser/SlidingTextWindow.cs +++ b/src/Compilers/CSharp/Portable/Parser/SlidingTextWindow.cs @@ -416,7 +416,7 @@ public string Intern(StringBuilder text) public string Intern(char[] array, int start, int length) { - return _strings.Add(array, start, length); + return _strings.Add(array.AsSpan(start, length)); } public string GetInternedText() @@ -481,21 +481,6 @@ public string GetText(int position, int length, bool intern) } } - internal static char GetCharsFromUtf32(uint codepoint, out char lowSurrogate) - { - if (codepoint < (uint)0x00010000) - { - lowSurrogate = InvalidCharacter; - return (char)codepoint; - } - else - { - Debug.Assert(codepoint > 0x0000FFFF && codepoint <= 0x0010FFFF); - lowSurrogate = (char)((codepoint - 0x00010000) % 0x0400 + 0xDC00); - return (char)((codepoint - 0x00010000) / 0x0400 + 0xD800); - } - } - internal TestAccessor GetTestAccessor() => new TestAccessor(this); diff --git a/src/Compilers/CSharp/Portable/SymbolDisplay/SymbolDisplayVisitor.Types.cs b/src/Compilers/CSharp/Portable/SymbolDisplay/SymbolDisplayVisitor.Types.cs index 988793c924187..6b8fd91e46265 100644 --- a/src/Compilers/CSharp/Portable/SymbolDisplay/SymbolDisplayVisitor.Types.cs +++ b/src/Compilers/CSharp/Portable/SymbolDisplay/SymbolDisplayVisitor.Types.cs @@ -345,7 +345,7 @@ private void AddNameAndTypeArgumentsOrParameters(INamedTypeSymbol symbol) { if (Format.CompilerInternalOptions.HasFlag(SymbolDisplayCompilerInternalOptions.UseMetadataMemberNames)) { - var extensionIdentifier = underlyingTypeSymbol!.ExtensionName; // Tracked by https://github.com/dotnet/roslyn/issues/76130 : use public API once it's available + var extensionIdentifier = underlyingTypeSymbol!.ExtensionName; // Tracked by https://github.com/dotnet/roslyn/issues/78957 : public API, use public API once it's available Builder.Add(CreatePart(SymbolDisplayPartKind.ClassName, symbol, extensionIdentifier)); } else diff --git a/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/AnonymousTypeDescriptor.cs b/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/AnonymousTypeDescriptor.cs index b6a807e6393ab..a3789ff205df4 100644 --- a/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/AnonymousTypeDescriptor.cs +++ b/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/AnonymousTypeDescriptor.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Immutable; using System.Diagnostics; +using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols diff --git a/src/Compilers/CSharp/Portable/Symbols/Compilation_WellKnownMembers.cs b/src/Compilers/CSharp/Portable/Symbols/Compilation_WellKnownMembers.cs index 65292086a7814..4f9e927d0a7f1 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Compilation_WellKnownMembers.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Compilation_WellKnownMembers.cs @@ -154,25 +154,27 @@ internal NamedTypeSymbol GetWellKnownType(WellKnownType type) if (result is null) { MetadataTypeName emittedName = MetadataTypeName.FromFullName(mdName, useCLSCompliantNameArityEncoding: true); - if (type.IsValueTupleType()) + + CSDiagnosticInfo? errorInfo; + if (conflicts is ({ } conflict1, { } conflict2)) { - CSDiagnosticInfo errorInfo; - if (conflicts.Item1 is null) + errorInfo = new CSDiagnosticInfo(ErrorCode.ERR_PredefinedTypeAmbiguous, emittedName.FullName, conflict1, conflict2); + } + else + { + Debug.Assert(conflicts is (null, null)); + + if (type.IsValueTupleType()) { - Debug.Assert(conflicts.Item2 is null); errorInfo = new CSDiagnosticInfo(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, emittedName.FullName); } else { - errorInfo = new CSDiagnosticInfo(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, emittedName.FullName, conflicts.Item1, conflicts.Item2); + errorInfo = null; } - - result = new MissingMetadataTypeSymbol.TopLevel(this.Assembly.Modules[0], ref emittedName, type, errorInfo); - } - else - { - result = new MissingMetadataTypeSymbol.TopLevel(this.Assembly.Modules[0], ref emittedName, type); } + + result = new MissingMetadataTypeSymbol.TopLevel(this.Assembly.Modules[0], ref emittedName, type, errorInfo); } if (Interlocked.CompareExchange(ref _lazyWellKnownTypes[index], result, null) is object) diff --git a/src/Compilers/CSharp/Portable/Symbols/ErrorMethodSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/ErrorMethodSymbol.cs index ac17af6693ab3..438004549e8c2 100644 --- a/src/Compilers/CSharp/Portable/Symbols/ErrorMethodSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/ErrorMethodSymbol.cs @@ -83,6 +83,8 @@ internal sealed override ObsoleteAttributeData ObsoleteAttributeData internal sealed override UnmanagedCallersOnlyAttributeData GetUnmanagedCallersOnlyAttributeData(bool forceComplete) => null; + internal sealed override bool HasSpecialNameAttribute => throw ExceptionUtilities.Unreachable(); + public override Accessibility DeclaredAccessibility { get { return Accessibility.Public; } diff --git a/src/Compilers/CSharp/Portable/Symbols/Extensions/RewrittenMethodSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Extensions/RewrittenMethodSymbol.cs index 2ffc82ff8e75f..f8dcc80e55b6e 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Extensions/RewrittenMethodSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Extensions/RewrittenMethodSymbol.cs @@ -21,7 +21,7 @@ protected RewrittenMethodSymbol(MethodSymbol originalMethod, TypeMap typeMap, Im Debug.Assert(originalMethod.ExplicitInterfaceImplementations.IsEmpty); _originalMethod = originalMethod; - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Are we creating type parameters with the right emit behavior? Attributes, etc. + // Tracked by https://github.com/dotnet/roslyn/issues/78963 : Are we creating type parameters with the right emit behavior? Attributes, etc. _typeMap = typeMap.WithAlphaRename(typeParametersToAlphaRename, this, out _typeParameters); } @@ -76,6 +76,8 @@ internal sealed override int CalculateLocalSyntaxOffset(int localPosition, Synta internal sealed override UnmanagedCallersOnlyAttributeData? GetUnmanagedCallersOnlyAttributeData(bool forceComplete) => _originalMethod.GetUnmanagedCallersOnlyAttributeData(forceComplete); + internal sealed override bool HasSpecialNameAttribute => throw ExceptionUtilities.Unreachable(); + public sealed override ImmutableArray RefCustomModifiers { get { return _typeMap.SubstituteCustomModifiers(_originalMethod.RefCustomModifiers); } diff --git a/src/Compilers/CSharp/Portable/Symbols/Extensions/RewrittenParameterSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Extensions/RewrittenParameterSymbol.cs index ccf32fb12c6d3..c7da897fcb269 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Extensions/RewrittenParameterSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Extensions/RewrittenParameterSymbol.cs @@ -22,8 +22,8 @@ public RewrittenParameterSymbol(ParameterSymbol originalParameter) : internal sealed override int CallerArgumentExpressionParameterIndex => _underlyingParameter.CallerArgumentExpressionParameterIndex; - internal sealed override ImmutableArray InterpolatedStringHandlerArgumentIndexes => throw ExceptionUtilities.Unreachable(); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Follow up + internal sealed override ImmutableArray InterpolatedStringHandlerArgumentIndexes => throw ExceptionUtilities.Unreachable(); // Tracked by https://github.com/dotnet/roslyn/issues/78965 : interpolated string, Follow up - internal sealed override bool HasInterpolatedStringHandlerArgumentError => throw ExceptionUtilities.Unreachable(); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Follow up + internal sealed override bool HasInterpolatedStringHandlerArgumentError => throw ExceptionUtilities.Unreachable(); // Tracked by https://github.com/dotnet/roslyn/issues/78965 : interpolated string, Follow up } } diff --git a/src/Compilers/CSharp/Portable/Symbols/Extensions/SourceExtensionImplementationMethodSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Extensions/SourceExtensionImplementationMethodSymbol.cs index 0d171d66e31b4..6af7d0ce1c6d8 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Extensions/SourceExtensionImplementationMethodSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Extensions/SourceExtensionImplementationMethodSymbol.cs @@ -6,6 +6,7 @@ using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; +using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; @@ -22,10 +23,8 @@ public SourceExtensionImplementationMethodSymbol(MethodSymbol sourceMethod) { Debug.Assert(sourceMethod.GetIsNewExtensionMember()); Debug.Assert(sourceMethod.IsStatic || sourceMethod.ContainingType.ExtensionParameter is not null); - Debug.Assert(!sourceMethod.IsExtern); - Debug.Assert(!sourceMethod.IsExternal); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Are we creating type parameters with the right emit behavior? Attributes, etc. + // Tracked by https://github.com/dotnet/roslyn/issues/78963 : Are we creating type parameters with the right emit behavior? Attributes, etc. // Also, they should be IsImplicitlyDeclared } @@ -36,7 +35,7 @@ public SourceExtensionImplementationMethodSymbol(MethodSymbol sourceMethod) public override MethodKind MethodKind => MethodKind.Ordinary; public override bool IsImplicitlyDeclared => true; - internal override bool HasSpecialName => false; + internal override bool HasSpecialName => _originalMethod.HasSpecialNameAttribute; internal override int ParameterCount { @@ -59,9 +58,9 @@ internal override int ParameterCount internal sealed override bool IsAccessCheckedOnOverride => false; - public sealed override bool IsExtern => false; - public sealed override DllImportData? GetDllImportData() => null; - internal sealed override bool IsExternal => false; + public sealed override bool IsExtern => _originalMethod.IsExtern; + public sealed override DllImportData? GetDllImportData() => _originalMethod.GetDllImportData(); + internal sealed override bool IsExternal => _originalMethod.IsExternal; internal sealed override bool IsDeclaredReadOnly => false; @@ -126,7 +125,7 @@ protected override ImmutableArray MakeParameters() if (!_originalMethod.IsStatic) { - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Need to confirm if this rewrite going to break LocalStateTracingInstrumenter + // Tracked by https://github.com/dotnet/roslyn/issues/78962 : Need to confirm if this rewrite going to break LocalStateTracingInstrumenter // Specifically BoundParameterId, etc. parameters.Add(new ExtensionMetadataMethodParameterSymbol(this, ((SourceNamedTypeSymbol)_originalMethod.ContainingType).ExtensionParameter!)); } diff --git a/src/Compilers/CSharp/Portable/Symbols/Extensions/SynthesizedExtensionMarker.cs b/src/Compilers/CSharp/Portable/Symbols/Extensions/SynthesizedExtensionMarker.cs index 2aa870db3b6a8..b29188c225f51 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Extensions/SynthesizedExtensionMarker.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Extensions/SynthesizedExtensionMarker.cs @@ -4,6 +4,7 @@ using System.Collections.Immutable; using System.Diagnostics; +using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerMethodSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerMethodSymbol.cs index f0ed88d0c3f4c..6b17d777b376d 100644 --- a/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerMethodSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerMethodSymbol.cs @@ -848,6 +848,7 @@ public override bool IsVararg internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) => false; internal override bool IsMetadataVirtual(IsMetadataVirtualOption option = IsMetadataVirtualOption.None) => false; internal sealed override UnmanagedCallersOnlyAttributeData? GetUnmanagedCallersOnlyAttributeData(bool forceComplete) => null; + internal sealed override bool HasSpecialNameAttribute => throw ExceptionUtilities.Unreachable(); internal override bool GenerateDebugInfo => throw ExceptionUtilities.Unreachable(); internal override ObsoleteAttributeData? ObsoleteAttributeData => throw ExceptionUtilities.Unreachable(); diff --git a/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEMethodSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEMethodSymbol.cs index 4fb32a34b8fe3..87fc964ce8666 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEMethodSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEMethodSymbol.cs @@ -1682,6 +1682,8 @@ internal override ObsoleteAttributeData ObsoleteAttributeData return _uncommonFields?._lazyUnmanagedCallersOnlyAttributeData; } + + internal sealed override bool HasSpecialNameAttribute => throw ExceptionUtilities.Unreachable(); #nullable disable internal override bool GenerateDebugInfo => false; diff --git a/src/Compilers/CSharp/Portable/Symbols/MethodSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/MethodSymbol.cs index 7a54b67c0588e..c02a97054ac3e 100644 --- a/src/Compilers/CSharp/Portable/Symbols/MethodSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/MethodSymbol.cs @@ -96,6 +96,8 @@ public virtual bool IsGenericMethod /// internal virtual bool IsDirectlyExcludedFromCodeCoverage { get => false; } + internal abstract bool HasSpecialNameAttribute { get; } + /// /// If a method is annotated with `[MemberNotNull(...)]` attributes, returns the list of members /// listed in those attributes. diff --git a/src/Compilers/CSharp/Portable/Symbols/NamedTypeSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/NamedTypeSymbol.cs index 54d2be2cc783b..af11d43a6abfb 100644 --- a/src/Compilers/CSharp/Portable/Symbols/NamedTypeSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/NamedTypeSymbol.cs @@ -13,7 +13,6 @@ using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; @@ -212,6 +211,11 @@ internal void AddOperators(string name, ArrayBuilder operators) if (candidates.IsEmpty) return; + AddOperators(operators, candidates); + } + + internal static void AddOperators(ArrayBuilder operators, ImmutableArray candidates) + { foreach (var candidate in candidates) { if (candidate is MethodSymbol { MethodKind: MethodKind.UserDefinedOperator or MethodKind.Conversion } method) @@ -355,7 +359,7 @@ internal void DoGetExtensionMethods(ArrayBuilder methods, string n { var thisParam = method.Parameters.First(); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : we should use similar logic when looking up new extension members + // Tracked by https://github.com/dotnet/roslyn/issues/78827 : MQ, we should use similar logic when looking up new extension members if ((thisParam.RefKind == RefKind.Ref && !thisParam.Type.IsValueType) || (thisParam.RefKind is RefKind.In or RefKind.RefReadOnlyParameter && thisParam.Type.TypeKind != TypeKind.Struct)) { diff --git a/src/Compilers/CSharp/Portable/Symbols/NamespaceSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/NamespaceSymbol.cs index 6a4d263435209..ae41a5dbd7abb 100644 --- a/src/Compilers/CSharp/Portable/Symbols/NamespaceSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/NamespaceSymbol.cs @@ -363,7 +363,7 @@ internal virtual void GetExtensionContainers(ArrayBuilder exten } } - protected void AddExtensionContainersInType(NamedTypeSymbol type, ArrayBuilder extensions) + internal static void AddExtensionContainersInType(NamedTypeSymbol type, ArrayBuilder extensions) { // Consider whether IsClassType could be used instead. Tracked by https://github.com/dotnet/roslyn/issues/78275 if (!type.IsReferenceType || !type.IsStatic || type.IsGenericType || !type.MightContainExtensionMethods) return; diff --git a/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs index f736683de149d..b3359712b498d 100644 --- a/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs @@ -374,6 +374,8 @@ public override ImmutableArray Parameters internal override UnmanagedCallersOnlyAttributeData? GetUnmanagedCallersOnlyAttributeData(bool forceComplete) => UnderlyingMethod.GetUnmanagedCallersOnlyAttributeData(forceComplete); + internal sealed override bool HasSpecialNameAttribute => throw ExceptionUtilities.Unreachable(); + public override Symbol? AssociatedSymbol => _associatedSymbol; internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) diff --git a/src/Compilers/CSharp/Portable/Symbols/ReducedExtensionMethodSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/ReducedExtensionMethodSymbol.cs index 15b50a8d4a989..d9137ab7b57e5 100644 --- a/src/Compilers/CSharp/Portable/Symbols/ReducedExtensionMethodSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/ReducedExtensionMethodSymbol.cs @@ -444,6 +444,8 @@ internal sealed override ObsoleteAttributeData ObsoleteAttributeData internal sealed override UnmanagedCallersOnlyAttributeData GetUnmanagedCallersOnlyAttributeData(bool forceComplete) => _reducedFrom.GetUnmanagedCallersOnlyAttributeData(forceComplete); + internal sealed override bool HasSpecialNameAttribute => throw ExceptionUtilities.Unreachable(); + public override Accessibility DeclaredAccessibility { get { return _reducedFrom.DeclaredAccessibility; } diff --git a/src/Compilers/CSharp/Portable/Symbols/ReferenceManager.cs b/src/Compilers/CSharp/Portable/Symbols/ReferenceManager.cs index cbd68b2b7f72d..b2d08f32491ab 100644 --- a/src/Compilers/CSharp/Portable/Symbols/ReferenceManager.cs +++ b/src/Compilers/CSharp/Portable/Symbols/ReferenceManager.cs @@ -6,15 +6,14 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; - +using System.Linq; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; -using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; -using Roslyn.Utilities; using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { diff --git a/src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingMethodSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingMethodSymbol.cs index 3254b2c21a799..0f8235b6adb53 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingMethodSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingMethodSymbol.cs @@ -256,6 +256,8 @@ public override ImmutableArray GetReturnTypeAttributes() return _lazyUnmanagedAttributeData; } + internal sealed override bool HasSpecialNameAttribute => throw ExceptionUtilities.Unreachable(); + internal override bool TryGetThisParameter(out ParameterSymbol? thisParameter) { if (!_underlyingMethod.TryGetThisParameter(out var underlyingParameter)) diff --git a/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs index 7afa024b16661..dadb95533fb2c 100644 --- a/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs @@ -124,6 +124,8 @@ internal sealed override bool HasAsyncMethodBuilderAttribute(out TypeSymbol buil internal sealed override UnmanagedCallersOnlyAttributeData GetUnmanagedCallersOnlyAttributeData(bool forceComplete) => throw ExceptionUtilities.Unreachable(); + internal sealed override bool HasSpecialNameAttribute => throw ExceptionUtilities.Unreachable(); + internal override ImmutableArray GetAppliedConditionalSymbols() { throw ExceptionUtilities.Unreachable(); } public override ImmutableArray TypeArgumentsWithAnnotations { get { throw ExceptionUtilities.Unreachable(); } } diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/FieldSymbolWithAttributesAndModifiers.cs b/src/Compilers/CSharp/Portable/Symbols/Source/FieldSymbolWithAttributesAndModifiers.cs index 23835977ee21b..7094d7c84fb69 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/FieldSymbolWithAttributesAndModifiers.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/FieldSymbolWithAttributesAndModifiers.cs @@ -9,6 +9,7 @@ using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/GlobalExpressionVariable.cs b/src/Compilers/CSharp/Portable/Symbols/Source/GlobalExpressionVariable.cs index 3403885c3079f..4934b9b2ea09d 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/GlobalExpressionVariable.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/GlobalExpressionVariable.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/LambdaParameterSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/LambdaParameterSymbol.cs index ad457db77f884..3fa7b3cfed3a3 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/LambdaParameterSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/LambdaParameterSymbol.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/LambdaSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/LambdaSymbol.cs index 7e3f09b39ca49..06571e6802fb1 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/LambdaSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/LambdaSymbol.cs @@ -6,6 +6,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceComplexParameterSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceComplexParameterSymbol.cs index 6f02978674217..c0fd0dc399dcf 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceComplexParameterSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceComplexParameterSymbol.cs @@ -9,6 +9,7 @@ using System.Diagnostics; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceConstructorSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceConstructorSymbol.cs index a570212d8250e..4e71714542d32 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceConstructorSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceConstructorSymbol.cs @@ -6,6 +6,7 @@ using System.Diagnostics; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceConstructorSymbolBase.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceConstructorSymbolBase.cs index 8b2f328bc6ae7..b90a8cc9d701b 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceConstructorSymbolBase.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceConstructorSymbolBase.cs @@ -6,6 +6,7 @@ using System.Collections.Immutable; using System.Diagnostics; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceCustomEventAccessorSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceCustomEventAccessorSymbol.cs index 8ffcd5b794056..dd805e55c8668 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceCustomEventAccessorSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceCustomEventAccessorSymbol.cs @@ -5,6 +5,7 @@ #nullable disable using System.Diagnostics; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceDelegateMethodSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceDelegateMethodSymbol.cs index 4bdec7c9aec71..397c3b6d232b3 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceDelegateMethodSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceDelegateMethodSymbol.cs @@ -8,6 +8,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceDestructorSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceDestructorSymbol.cs index 1252f9f3d5e83..8851720b789fc 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceDestructorSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceDestructorSymbol.cs @@ -6,6 +6,7 @@ using System.Collections.Immutable; using System.Diagnostics; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceEnumConstantSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceEnumConstantSymbol.cs index a2f5dd94a71f9..7cd6903b411ee 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceEnumConstantSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceEnumConstantSymbol.cs @@ -9,6 +9,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceEventSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceEventSymbol.cs index dfcef501fc5d6..9aaae522c33ca 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceEventSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceEventSymbol.cs @@ -8,6 +8,7 @@ using System.Globalization; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceFieldLikeEventSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceFieldLikeEventSymbol.cs index 3148d00a9ad3e..b8eea2e6e5e84 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceFieldLikeEventSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceFieldLikeEventSymbol.cs @@ -7,6 +7,7 @@ using System.Diagnostics; using System.Reflection; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol.cs index c6a185b77d2c9..fb9b111e317e1 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol.cs @@ -1813,7 +1813,7 @@ protected void AfterMembersChecks(BindingDiagnosticBag diagnostics) } CheckMemberNamesDistinctFromType(diagnostics); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Should this check "see through" extensions? - CheckMemberNameConflicts(diagnostics); + CheckMemberNameConflictsAndUnmatchedOperators(diagnostics); CheckRecordMemberNames(diagnostics); CheckSpecialMemberErrors(diagnostics); CheckTypeParameterNameConflicts(diagnostics); @@ -1822,7 +1822,6 @@ protected void AfterMembersChecks(BindingDiagnosticBag diagnostics) CheckSequentialOnPartialType(diagnostics); CheckForProtectedInStaticClass(diagnostics); - CheckForUnmatchedOperators(diagnostics); CheckForRequiredMemberAttribute(diagnostics); if (IsScriptClass || IsSubmissionClass) @@ -2341,7 +2340,7 @@ private static void CheckIndexerSignatureCollisions( } } - private void CheckMemberNameConflicts(BindingDiagnosticBag diagnostics) + private void CheckMemberNameConflictsAndUnmatchedOperators(BindingDiagnosticBag diagnostics) { if (IsExtension) { @@ -2354,6 +2353,12 @@ private void CheckMemberNameConflicts(BindingDiagnosticBag diagnostics) } checkMemberNameConflicts(GetMembersByName(), GetTypeMembersDictionary(), GetMembersUnordered(), diagnostics); + + // We also produce a warning if == / != is overridden without also overriding + // Equals and GetHashCode, or if Equals is overridden without GetHashCode. + + CheckForEqualityAndGetHashCode(diagnostics); + return; void checkMemberNameConflicts( @@ -2365,6 +2370,7 @@ void checkMemberNameConflicts( bool mightHaveMembersFromDistinctNonPartialDeclarations = !(Locations.Length == 1 || IsPartial); CheckMemberNameConflicts(this, mightHaveMembersFromDistinctNonPartialDeclarations, typesByName, membersByName, diagnostics); CheckAccessorNameConflicts(this, mightHaveMembersFromDistinctNonPartialDeclarations, membersByName, membersUnordered, diagnostics); + CheckForUnmatchedOperators(membersByName, diagnostics); } void checkMemberNameConflictsInExtensions(BindingDiagnosticBag diagnostics) @@ -2474,27 +2480,40 @@ static ImmutableArray concatMembers(ImmutableArray existingMembe } } - private readonly struct ExtensionGroupingKey : IEquatable + internal readonly struct ExtensionGroupingKey : IEquatable { - public readonly int ExtensionArity; - public readonly TypeSymbol ReceiverType; + public readonly NamedTypeSymbol NormalizedExtension; public ExtensionGroupingKey(NamedTypeSymbol extension) { - ExtensionArity = extension.Arity; - if (extension.Arity != 0) { extension = extension.Construct(IndexedTypeParameterSymbol.Take(extension.Arity)); } - if (extension.ExtensionParameter is { } receiverParameter) + NormalizedExtension = extension; + } + + private readonly int ExtensionArity + { + get { - ReceiverType = receiverParameter.Type; + return NormalizedExtension.Arity; } - else + } + + private readonly TypeSymbol ReceiverType + { + get { - ReceiverType = ErrorTypeSymbol.UnknownResultType; + if (NormalizedExtension.ExtensionParameter is { } receiverParameter) + { + return receiverParameter.Type; + } + else + { + return ErrorTypeSymbol.UnknownResultType; + } } } @@ -2702,7 +2721,9 @@ private void CheckForProtectedInStaticClass(BindingDiagnosticBag diagnostics) } } - private void CheckForUnmatchedOperators(BindingDiagnosticBag diagnostics) + private static void CheckForUnmatchedOperators( + Dictionary, ImmutableArray> membersByName, + BindingDiagnosticBag diagnostics) { // SPEC: The true and false unary operators require pairwise declaration. // SPEC: A compile-time error occurs if a class or struct declares one @@ -2720,42 +2741,39 @@ private void CheckForUnmatchedOperators(BindingDiagnosticBag diagnostics) // SPEC: type for each parameter. The following operators require pairwise // SPEC: declaration: == and !=, > and <, >= and <=. - CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.TrueOperatorName, WellKnownMemberNames.FalseOperatorName); - CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.EqualityOperatorName, WellKnownMemberNames.InequalityOperatorName); - CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.LessThanOperatorName, WellKnownMemberNames.GreaterThanOperatorName); - CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.LessThanOrEqualOperatorName, WellKnownMemberNames.GreaterThanOrEqualOperatorName); - - CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.CheckedDecrementOperatorName, WellKnownMemberNames.DecrementOperatorName, symmetricCheck: false); - CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.CheckedIncrementOperatorName, WellKnownMemberNames.IncrementOperatorName, symmetricCheck: false); - CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.CheckedUnaryNegationOperatorName, WellKnownMemberNames.UnaryNegationOperatorName, symmetricCheck: false); - CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.CheckedAdditionOperatorName, WellKnownMemberNames.AdditionOperatorName, symmetricCheck: false); - CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.CheckedDivisionOperatorName, WellKnownMemberNames.DivisionOperatorName, symmetricCheck: false); - CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.CheckedMultiplyOperatorName, WellKnownMemberNames.MultiplyOperatorName, symmetricCheck: false); - CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.CheckedSubtractionOperatorName, WellKnownMemberNames.SubtractionOperatorName, symmetricCheck: false); - CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.CheckedExplicitConversionName, WellKnownMemberNames.ExplicitConversionName, symmetricCheck: false); - - CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.CheckedAdditionAssignmentOperatorName, WellKnownMemberNames.AdditionAssignmentOperatorName, symmetricCheck: false); - CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.CheckedDivisionAssignmentOperatorName, WellKnownMemberNames.DivisionAssignmentOperatorName, symmetricCheck: false); - CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.CheckedMultiplicationAssignmentOperatorName, WellKnownMemberNames.MultiplicationAssignmentOperatorName, symmetricCheck: false); - CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.CheckedSubtractionAssignmentOperatorName, WellKnownMemberNames.SubtractionAssignmentOperatorName, symmetricCheck: false); - CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.CheckedDecrementAssignmentOperatorName, WellKnownMemberNames.DecrementAssignmentOperatorName, symmetricCheck: false); - CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.CheckedIncrementAssignmentOperatorName, WellKnownMemberNames.IncrementAssignmentOperatorName, symmetricCheck: false); + CheckForUnmatchedOperator(membersByName, diagnostics, WellKnownMemberNames.TrueOperatorName, WellKnownMemberNames.FalseOperatorName); + CheckForUnmatchedOperator(membersByName, diagnostics, WellKnownMemberNames.EqualityOperatorName, WellKnownMemberNames.InequalityOperatorName); + CheckForUnmatchedOperator(membersByName, diagnostics, WellKnownMemberNames.LessThanOperatorName, WellKnownMemberNames.GreaterThanOperatorName); + CheckForUnmatchedOperator(membersByName, diagnostics, WellKnownMemberNames.LessThanOrEqualOperatorName, WellKnownMemberNames.GreaterThanOrEqualOperatorName); - // We also produce a warning if == / != is overridden without also overriding - // Equals and GetHashCode, or if Equals is overridden without GetHashCode. + CheckForUnmatchedOperator(membersByName, diagnostics, WellKnownMemberNames.CheckedDecrementOperatorName, WellKnownMemberNames.DecrementOperatorName, symmetricCheck: false); + CheckForUnmatchedOperator(membersByName, diagnostics, WellKnownMemberNames.CheckedIncrementOperatorName, WellKnownMemberNames.IncrementOperatorName, symmetricCheck: false); + CheckForUnmatchedOperator(membersByName, diagnostics, WellKnownMemberNames.CheckedUnaryNegationOperatorName, WellKnownMemberNames.UnaryNegationOperatorName, symmetricCheck: false); + CheckForUnmatchedOperator(membersByName, diagnostics, WellKnownMemberNames.CheckedAdditionOperatorName, WellKnownMemberNames.AdditionOperatorName, symmetricCheck: false); + CheckForUnmatchedOperator(membersByName, diagnostics, WellKnownMemberNames.CheckedDivisionOperatorName, WellKnownMemberNames.DivisionOperatorName, symmetricCheck: false); + CheckForUnmatchedOperator(membersByName, diagnostics, WellKnownMemberNames.CheckedMultiplyOperatorName, WellKnownMemberNames.MultiplyOperatorName, symmetricCheck: false); + CheckForUnmatchedOperator(membersByName, diagnostics, WellKnownMemberNames.CheckedSubtractionOperatorName, WellKnownMemberNames.SubtractionOperatorName, symmetricCheck: false); + CheckForUnmatchedOperator(membersByName, diagnostics, WellKnownMemberNames.CheckedExplicitConversionName, WellKnownMemberNames.ExplicitConversionName, symmetricCheck: false); - CheckForEqualityAndGetHashCode(diagnostics); + CheckForUnmatchedOperator(membersByName, diagnostics, WellKnownMemberNames.CheckedAdditionAssignmentOperatorName, WellKnownMemberNames.AdditionAssignmentOperatorName, symmetricCheck: false); + CheckForUnmatchedOperator(membersByName, diagnostics, WellKnownMemberNames.CheckedDivisionAssignmentOperatorName, WellKnownMemberNames.DivisionAssignmentOperatorName, symmetricCheck: false); + CheckForUnmatchedOperator(membersByName, diagnostics, WellKnownMemberNames.CheckedMultiplicationAssignmentOperatorName, WellKnownMemberNames.MultiplicationAssignmentOperatorName, symmetricCheck: false); + CheckForUnmatchedOperator(membersByName, diagnostics, WellKnownMemberNames.CheckedSubtractionAssignmentOperatorName, WellKnownMemberNames.SubtractionAssignmentOperatorName, symmetricCheck: false); + CheckForUnmatchedOperator(membersByName, diagnostics, WellKnownMemberNames.CheckedDecrementAssignmentOperatorName, WellKnownMemberNames.DecrementAssignmentOperatorName, symmetricCheck: false); + CheckForUnmatchedOperator(membersByName, diagnostics, WellKnownMemberNames.CheckedIncrementAssignmentOperatorName, WellKnownMemberNames.IncrementAssignmentOperatorName, symmetricCheck: false); } - private void CheckForUnmatchedOperator(BindingDiagnosticBag diagnostics, string operatorName1, string operatorName2, bool symmetricCheck = true) + private static void CheckForUnmatchedOperator( + Dictionary, ImmutableArray> membersByName, + BindingDiagnosticBag diagnostics, string operatorName1, string operatorName2, bool symmetricCheck = true) { var ops1 = ArrayBuilder.GetInstance(); - this.AddOperators(operatorName1, ops1); + addOperators(membersByName, operatorName1, ops1); if (symmetricCheck) { var ops2 = ArrayBuilder.GetInstance(); - this.AddOperators(operatorName2, ops2); + addOperators(membersByName, operatorName2, ops2); CheckForUnmatchedOperator(diagnostics, ops1, ops2, operatorName2, reportOperatorNeedsMatch); CheckForUnmatchedOperator(diagnostics, ops2, ops1, operatorName1, reportOperatorNeedsMatch); ops2.Free(); @@ -2763,7 +2781,7 @@ private void CheckForUnmatchedOperator(BindingDiagnosticBag diagnostics, string else if (!ops1.IsEmpty) { var ops2 = ArrayBuilder.GetInstance(); - this.AddOperators(operatorName2, ops2); + addOperators(membersByName, operatorName2, ops2); CheckForUnmatchedOperator(diagnostics, ops1, ops2, operatorName2, reportCheckedOperatorNeedsMatch); ops2.Free(); } @@ -2783,6 +2801,16 @@ static void reportCheckedOperatorNeedsMatch(BindingDiagnosticBag diagnostics, st { diagnostics.Add(ErrorCode.ERR_CheckedOperatorNeedsMatch, op1.GetFirstLocation(), op1); } + + static void addOperators( + Dictionary, ImmutableArray> membersByName, + string operatorName1, ArrayBuilder ops1) + { + if (membersByName.TryGetValue(operatorName1.AsMemory(), out ImmutableArray candidates)) + { + AddOperators(ops1, candidates); + } + } } private static void CheckForUnmatchedOperator( @@ -2841,6 +2869,8 @@ internal static bool DoOperatorsPair(MethodSymbol op1, MethodSymbol op2) private void CheckForEqualityAndGetHashCode(BindingDiagnosticBag diagnostics) { + Debug.Assert(!this.IsExtension); + if (this.IsInterfaceType()) { // Interfaces are allowed to define Equals without GetHashCode if they want. @@ -4635,7 +4665,6 @@ internal static bool IsAllowedExtensionMember(Symbol member) { case MethodKind.Constructor: case MethodKind.Conversion: - case MethodKind.UserDefinedOperator: case MethodKind.Destructor: case MethodKind.EventAdd: case MethodKind.EventRemove: @@ -4643,6 +4672,7 @@ internal static bool IsAllowedExtensionMember(Symbol member) case MethodKind.ExplicitInterfaceImplementation: break; case MethodKind.Ordinary: + case MethodKind.UserDefinedOperator: case MethodKind.PropertyGet: case MethodKind.PropertySet: return true; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberFieldSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberFieldSymbol.cs index 9f179a98f89be..6877e5eda7b8e 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberFieldSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberFieldSymbol.cs @@ -4,16 +4,17 @@ #nullable disable -using Microsoft.CodeAnalysis.CSharp.Emit; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.PooledObjects; -using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceMethodSymbolWithAttributes.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceMethodSymbolWithAttributes.cs index 59208bca2b6f0..52e05c153fb98 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceMethodSymbolWithAttributes.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceMethodSymbolWithAttributes.cs @@ -5,7 +5,6 @@ #nullable disable using System; -using System.Buffers.Binary; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; @@ -17,7 +16,6 @@ using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Shared.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols @@ -836,7 +834,7 @@ private void DecodeDllImportAttribute(ref DecodeWellKnownAttributeArguments arguments) { Debug.Assert(arguments.AttributeSyntaxOpt != null); @@ -1688,11 +1683,13 @@ internal override bool HasSpecialName return true; } - var data = GetDecodedWellKnownAttributeData(); - return data != null && data.HasSpecialNameAttribute; + return HasSpecialNameAttribute; } } + internal sealed override bool HasSpecialNameAttribute => + GetDecodedWellKnownAttributeData()?.HasSpecialNameAttribute == true; + internal sealed override bool IsDirectlyExcludedFromCodeCoverage => GetDecodedWellKnownAttributeData()?.HasExcludeFromCodeCoverageAttribute == true; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceModuleSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceModuleSymbol.cs index 0dcce524cce4b..00c4471f378ce 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceModuleSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceModuleSymbol.cs @@ -13,6 +13,7 @@ using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceNamedTypeSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceNamedTypeSymbol.cs index a0ac7ea54bc39..fbc9121fa8658 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceNamedTypeSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceNamedTypeSymbol.cs @@ -13,6 +13,7 @@ using System.Linq; using System.Runtime.InteropServices; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceNamedTypeSymbol_Extension.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceNamedTypeSymbol_Extension.cs index 198b63ea7a5ce..40eac32abdf74 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceNamedTypeSymbol_Extension.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceNamedTypeSymbol_Extension.cs @@ -2,12 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Runtime.CompilerServices; +using System.Text; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; @@ -63,6 +64,316 @@ internal override string ExtensionName } } + /// + /// This name uses an IL-looking format to encode CLR-level information of an extension block (ie. arity, constraints, extended type). + /// It is meant be to hashed to produce the content-based name for the extension grouping type. + /// + internal string ComputeExtensionGroupingRawName() + { + Debug.Assert(this.IsExtension && this.IsDefinition); + + var pooledBuilder = PooledStringBuilder.GetInstance(); + var builder = pooledBuilder.Builder; + builder.Append("extension"); + + if (this.Arity > 0) + { + builder.Append("<"); + + foreach (var typeParameter in this.TypeParameters) + { + if (typeParameter.Ordinal > 0) + { + builder.Append(", "); + } + + appendTypeParameterDeclaration(typeParameter, builder); + } + + builder.Append(">"); + } + + builder.Append("("); + if (this.ExtensionParameter is { } extensionParameter) + { + appendType(extensionParameter.Type, builder); + } + + builder.Append(")"); + + return pooledBuilder.ToStringAndFree(); + + static void appendType(TypeSymbol type, StringBuilder builder) + { + if (type is NamedTypeSymbol namedType) + { + appendNamedType(type, builder, namedType); + } + else if (type is TypeParameterSymbol typeParameter) + { + appendTypeParameterReference(typeParameter, builder); + } + else if (type is ArrayTypeSymbol array) + { + appendArrayType(array, builder); + } + else if (type is PointerTypeSymbol pointer) + { + appendType(pointer.PointedAtType, builder); + builder.Append('*'); + } + else if (type is FunctionPointerTypeSymbol functionPointer) + { + appendFunctionPointerType(functionPointer, builder); + } + else if (type is DynamicTypeSymbol) + { + builder.Append("System.Object"); + } + else + { + throw ExceptionUtilities.UnexpectedValue(type); + } + } + + static void appendNamedType(TypeSymbol type, StringBuilder builder, NamedTypeSymbol namedType) + { + Debug.Assert(type.CustomModifierCount() == 0); + + if (namedType.SpecialType == SpecialType.System_Void) + { + builder.Append("void"); + return; + } + + if (namedType.Name == "void") + { + builder.Append("'void'"); + return; + } + + // Note: in valid IL, we need a "class" or "valuetype" keyword in many contexts + appendNamespace(namedType.ContainingNamespace, builder); + appendContainingType(namedType, builder); + builder.Append(namedType.MetadataName); + appendTypeArguments(namedType, builder); + } + + static void appendNamespace(NamespaceSymbol ns, StringBuilder builder) + { + if (ns is not null && !ns.IsGlobalNamespace) + { + appendNamespace(ns.ContainingNamespace, builder); + builder.Append(ns.Name); + builder.Append('.'); + } + } + + static void appendContainingType(NamedTypeSymbol namedType, StringBuilder builder) + { + // Note: using slash for nested type to match CIL: ECMA-335 I.10.7.2 + if (namedType.ContainingType is { } containingType) + { + appendContainingType(containingType, builder); + builder.Append(containingType.MetadataName); + builder.Append('/'); + } + } + + static void appendTypeArguments(NamedTypeSymbol namedType, StringBuilder builder) + { + var typeArguments = ArrayBuilder.GetInstance(); + namedType.GetAllTypeArgumentsNoUseSiteDiagnostics(typeArguments); + if (typeArguments.Count > 0) + { + builder.Append('<'); + for (int i = 0; i < typeArguments.Count; i++) + { + if (i > 0) + { + builder.Append(", "); + } + + appendType(typeArguments[i].Type, builder); + Debug.Assert(typeArguments[i].CustomModifiers.IsEmpty); + } + + builder.Append('>'); + } + + typeArguments.Free(); + } + + static void appendTypeParameterDeclaration(TypeParameterSymbol typeParameter, StringBuilder builder) + { + if (typeParameter.HasReferenceTypeConstraint) + { + builder.Append("class "); + } + else if (typeParameter.HasValueTypeConstraint || typeParameter.HasUnmanagedTypeConstraint) + { + builder.Append("valuetype "); + } + + if (typeParameter.AllowsRefLikeType) + { + builder.Append("byreflike "); + } + + if (typeParameter.HasConstructorConstraint || typeParameter.HasValueTypeConstraint || typeParameter.HasUnmanagedTypeConstraint) + { + builder.Append(".ctor "); + } + + appendTypeParameterTypeConstraints(typeParameter, builder); + + // Note: skipping identifier and variance + if (builder[builder.Length - 1] == ' ') + { + builder.Remove(startIndex: builder.Length - 1, length: 1); + } + } + + static void appendTypeParameterReference(TypeParameterSymbol typeParameter, StringBuilder builder) + { + if (typeParameter.ContainingType.IsExtension) + { + builder.Append("!"); + builder.Append(StringExtensions.GetNumeral(typeParameter.Ordinal)); + } + else + { + // error scenario + builder.Append("!"); + builder.Append(typeParameter.Name); + } + } + + static void appendTypeParameterTypeConstraints(TypeParameterSymbol typeParameter, StringBuilder builder) + { + ImmutableArray typeConstraints = typeParameter.GetConstraintTypes(ConsList.Empty); + if (typeConstraints.IsEmpty && !typeParameter.HasUnmanagedTypeConstraint && !typeParameter.HasValueTypeConstraint) + { + return; + } + + var typeConstraintStrings = ArrayBuilder.GetInstance(typeConstraints.Length); + foreach (var typeConstraint in typeConstraints) + { + var constraintBuilder = PooledStringBuilder.GetInstance(); + appendType(typeConstraint.Type, constraintBuilder.Builder); + typeConstraintStrings.Add(constraintBuilder.ToStringAndFree()); + } + + if (typeParameter.HasUnmanagedTypeConstraint) + { + typeConstraintStrings.Add("System.ValueType modreq(System.Runtime.InteropServices.UnmanagedType)"); + } + else if (typeParameter.HasValueTypeConstraint) + { + typeConstraintStrings.Add("System.ValueType"); + } + + typeConstraintStrings.Sort(StringComparer.Ordinal); // Actual order doesn't matter - just want to be deterministic + + builder.Append('('); + for (int i = 0; i < typeConstraintStrings.Count; i++) + { + if (i > 0) + { + builder.Append(", "); + } + + builder.Append(typeConstraintStrings[i]); + } + + typeConstraintStrings.Free(); + builder.Append(")"); + } + + static void appendArrayType(ArrayTypeSymbol array, StringBuilder builder) + { + Debug.Assert(array.Sizes.IsEmpty && array.LowerBounds.IsDefault); // We only deal with source array types + + appendType(array.ElementType, builder); + builder.Append('['); + for (int i = 1; i < array.Rank; i++) + { + builder.Append(','); + } + + builder.Append(']'); + } + + static void appendFunctionPointerType(FunctionPointerTypeSymbol functionPointer, StringBuilder builder) + { + builder.Append("method "); + + // When calling convention is a single one of the four special calling conventions, we just use flags + // Otherwise, we use "unmanaged" flag and also add return modifiers below + var callingConvention = functionPointer.Signature.CallingConvention switch + { + Cci.CallingConvention.Default => null, // managed is the default + Cci.CallingConvention.Unmanaged => "unmanaged ", + Cci.CallingConvention.CDecl => "unmanaged cdecl ", + Cci.CallingConvention.Standard => "unmanaged stdcall ", + Cci.CallingConvention.ThisCall => "unmanaged thiscall ", + Cci.CallingConvention.FastCall => "unmanaged fastcall ", + _ => throw ExceptionUtilities.UnexpectedValue(functionPointer.Signature.CallingConvention) + }; + + builder.Append(callingConvention); + + appendType(functionPointer.Signature.ReturnType, builder); + if (functionPointer.Signature.RefKind != RefKind.None) + { + builder.Append('&'); + appendModifiers(functionPointer.Signature.RefCustomModifiers, builder); + Debug.Assert(functionPointer.Signature.ReturnTypeWithAnnotations.CustomModifiers.IsEmpty); // We're only dealing with source function pointers + } + else + { + appendModifiers(functionPointer.Signature.ReturnTypeWithAnnotations.CustomModifiers, builder); + } + + builder.Append(" *("); + var parameters = functionPointer.Signature.Parameters; + for (int i = 0; i < parameters.Length; i++) + { + if (i > 0) + { + builder.Append(", "); + } + + ParameterSymbol parameter = parameters[i]; + appendType(parameter.Type, builder); + Debug.Assert(parameter.TypeWithAnnotations.CustomModifiers.IsEmpty); + if (parameter.RefKind != RefKind.None) + { + builder.Append('&'); + appendModifiers(parameter.RefCustomModifiers, builder); + } + } + + builder.Append(')'); + } + + static void appendModifiers(ImmutableArray customModifiers, StringBuilder builder) + { + // Order of modifiers is significant in metadata so we preserve the order. + foreach (CustomModifier modifier in customModifiers) + { + var modifierBuilder = PooledStringBuilder.GetInstance(); + modifierBuilder.Builder.Append(modifier.IsOptional ? " modopt(" : " modreq("); + + appendType(((CSharpCustomModifier)modifier).ModifierSymbol, modifierBuilder.Builder); + modifierBuilder.Builder.Append(')'); + + builder.Append(modifierBuilder.ToStringAndFree()); + } + } + } + internal sealed override ParameterSymbol? ExtensionParameter { get diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceNamespaceSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceNamespaceSymbol.cs index 4f2c775890bc6..4663544e1fc33 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceNamespaceSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceNamespaceSymbol.cs @@ -8,6 +8,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceOrdinaryMethodSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceOrdinaryMethodSymbol.cs index c790fea46b620..9458646f01eed 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceOrdinaryMethodSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceOrdinaryMethodSymbol.cs @@ -10,6 +10,7 @@ using System.Globalization; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; @@ -247,6 +248,10 @@ protected sealed override void ExtensionMethodChecks(BindingDiagnosticBag diagno CheckExtensionAttributeAvailability(DeclaringCompilation, syntax.ParameterList.Parameters[0].Modifiers.FirstOrDefault(SyntaxKind.ThisKeyword).GetLocation(), diagnostics); } } + else if (ContainingType is { IsExtension: true, ExtensionParameter.Name: "" } && !IsStatic) + { + diagnostics.Add(ErrorCode.ERR_InstanceMemberWithUnnamedExtensionsParameter, _location, Name); + } } internal static void CheckExtensionAttributeAvailability(CSharpCompilation compilation, Location location, BindingDiagnosticBag diagnostics) @@ -771,12 +776,7 @@ private static (DeclarationModifiers mods, bool hasExplicitAccessMod) MakeModifi allowedModifiers |= DeclarationModifiers.Static; } - allowedModifiers |= DeclarationModifiers.Async; - - if (!isExtension) - { - allowedModifiers |= DeclarationModifiers.Extern; - } + allowedModifiers |= DeclarationModifiers.Async | DeclarationModifiers.Extern; if (containingType.IsStructType()) { @@ -936,10 +936,6 @@ private void CheckModifiers(bool isExplicitInterfaceImplementation, Location loc { diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), location, this); } - else if (ContainingType is { IsExtension: true, ExtensionParameter.Name: "" } && !IsStatic) - { - diagnostics.Add(ErrorCode.ERR_InstanceMemberWithUnnamedExtensionsParameter, location, Name); - } else if (ContainingType.IsStatic && !IsStatic) { diagnostics.Add(ErrorCode.ERR_InstanceMemberInStaticClass, location, Name); diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceOrdinaryMethodSymbolBase.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceOrdinaryMethodSymbolBase.cs index 769d31c34ca28..ff65539da5c71 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceOrdinaryMethodSymbolBase.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceOrdinaryMethodSymbolBase.cs @@ -9,6 +9,7 @@ using System.Globalization; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertyAccessorSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertyAccessorSymbol.cs index 841e253decc7c..a42ea9e1210df 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertyAccessorSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertyAccessorSymbol.cs @@ -7,6 +7,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbol.cs index 0cd3e3fb7fdf1..9ece43e96e082 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbol.cs @@ -7,6 +7,7 @@ using System.Diagnostics; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; @@ -449,10 +450,7 @@ private static (DeclarationModifiers modifiers, bool hasExplicitAccessMod) MakeM allowedModifiers |= DeclarationModifiers.ReadOnly; } - if (!isExtension) - { - allowedModifiers |= DeclarationModifiers.Extern; - } + allowedModifiers |= DeclarationModifiers.Extern; bool hasExplicitAccessMod; var mods = ModifierUtils.MakeAndCheckNonTypeMemberModifiers(isOrdinaryMethod: false, isForInterfaceMember: isInterface, diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbolBase.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbolBase.cs index 1f51f81bfffa0..871ad99a6f392 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbolBase.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbolBase.cs @@ -11,6 +11,7 @@ using System.Linq; using System.Runtime.CompilerServices; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; @@ -501,7 +502,7 @@ static bool isPossibleIndexerNameAttribute(AttributeSyntax node, Binder? rootBin static bool isPossibleIndexerNameAttributeInExtension(AttributeSyntax node, Binder? rootBinderOpt) { - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Temporarily limit binding to a string literal argument in order to avoid a binding cycle. + // Tracked by https://github.com/dotnet/roslyn/issues/78829 : extension indexers, Temporarily limit binding to a string literal argument in order to avoid a binding cycle. if (node.ArgumentList?.Arguments is not [{ NameColon: null, NameEquals: null, Expression: LiteralExpressionSyntax { RawKind: (int)SyntaxKind.StringLiteralExpression } }]) { return false; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceTypeParameterSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceTypeParameterSymbol.cs index 76abe90229d18..a0566c52b9a04 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceTypeParameterSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceTypeParameterSymbol.cs @@ -10,6 +10,7 @@ using System.Diagnostics; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceUserDefinedConversionSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceUserDefinedConversionSymbol.cs index d78ecec39cbc0..2d8b6e67cd671 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceUserDefinedConversionSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceUserDefinedConversionSymbol.cs @@ -6,6 +6,7 @@ using System.Collections.Immutable; using System.Diagnostics; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceUserDefinedOperatorSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceUserDefinedOperatorSymbol.cs index 32abd4c830a1b..ab820074dd94b 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceUserDefinedOperatorSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceUserDefinedOperatorSymbol.cs @@ -7,6 +7,7 @@ using System; using System.Collections.Immutable; using System.Diagnostics; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceUserDefinedOperatorSymbolBase.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceUserDefinedOperatorSymbolBase.cs index a265b651e07f7..3a66b8efc86d2 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceUserDefinedOperatorSymbolBase.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceUserDefinedOperatorSymbolBase.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; @@ -77,6 +78,12 @@ protected SourceUserDefinedOperatorSymbolBase( return; } + if (this.ContainingType is { IsExtension: true, ExtensionParameter.Type.IsStatic: true }) + { + diagnostics.Add(ErrorCode.ERR_OperatorInExtensionOfStaticClass, location); + return; + } + // SPEC: An operator declaration must include both a public and a // SPEC: static modifier if (this.IsExplicitInterfaceImplementation) @@ -168,11 +175,11 @@ protected SourceUserDefinedOperatorSymbolBase( protected static DeclarationModifiers MakeDeclarationModifiers(bool isCompoundAssignmentOrIncrementAssignment, MethodKind methodKind, SourceMemberContainerTypeSymbol containingType, BaseMethodDeclarationSyntax syntax, Location location, BindingDiagnosticBag diagnostics) { bool inInterface = containingType.IsInterface; + bool inExtension = containingType.IsExtension; bool isExplicitInterfaceImplementation = methodKind == MethodKind.ExplicitInterfaceImplementation; var defaultAccess = inInterface && !isExplicitInterfaceImplementation ? DeclarationModifiers.Public : DeclarationModifiers.Private; var allowedModifiers = - DeclarationModifiers.Extern | - DeclarationModifiers.Unsafe; + DeclarationModifiers.Unsafe | DeclarationModifiers.Extern; if (!isCompoundAssignmentOrIncrementAssignment) { @@ -193,7 +200,7 @@ protected static DeclarationModifiers MakeDeclarationModifiers(bool isCompoundAs } } - if (isCompoundAssignmentOrIncrementAssignment) + if (isCompoundAssignmentOrIncrementAssignment && !inExtension) { if (inInterface) { @@ -375,6 +382,54 @@ protected override void MethodChecks(BindingDiagnosticBag diagnostics) protected sealed override void ExtensionMethodChecks(BindingDiagnosticBag diagnostics) { + if (ContainingType is { IsExtension: true, ExtensionParameter: { Type.IsStatic: false } extensionParameter } && !IsStatic && + OperatorFacts.IsCompoundAssignmentOperatorName(Name)) + { + if (extensionParameter.Name == "") + { + diagnostics.Add(ErrorCode.ERR_InstanceMemberWithUnnamedExtensionsParameter, _location, new FormattedSymbol(this, SymbolDisplayFormat.ShortFormat)); + } + + // Require receiver type to be known as a class or as a struct, and + // require: + // - struct receiver to be a 'ref' + // - class receiver to be 'by val' (not 'ref', not 'in', not 'ref readonly') + + // We don't report every invalid combination here in order to avoid producing too much noise. + switch (extensionParameter.RefKind) + { + case RefKind.Out: // 'out' is disallowed in general + case RefKind.Ref: // 'ref' receivers are disallowed for types not known to be a struct + break; + + case RefKind.In: + case RefKind.RefReadOnlyParameter: + // 'in' and 'ref readonly' receivers are disallowed for anything that is not a concrete struct (class or a type parameter) + if (extensionParameter.Type.IsStructType()) + { + diagnostics.Add(ErrorCode.ERR_InstanceOperatorStructExtensionWrongReceiverRefKind, _location); + } + + break; + + case RefKind.None: + switch (extensionParameter.Type) + { + case { IsValueType: true }: + diagnostics.Add(ErrorCode.ERR_InstanceOperatorStructExtensionWrongReceiverRefKind, _location); + break; + + case { TypeKind: TypeKind.TypeParameter, IsReferenceType: false }: + diagnostics.Add(ErrorCode.ERR_InstanceOperatorExtensionWrongReceiverType, _location); + break; + } + + break; + + default: + throw ExceptionUtilities.UnexpectedValue(extensionParameter.RefKind); + } + } } protected sealed override MethodSymbol FindExplicitlyImplementedMethod(BindingDiagnosticBag diagnostics) @@ -475,7 +530,7 @@ private void CheckOperatorSignatures(BindingDiagnosticBag diagnostics) case WellKnownMemberNames.EqualityOperatorName: case WellKnownMemberNames.InequalityOperatorName: - if (IsAbstract || IsVirtual) + if (IsInInterfaceAndAbstractOrVirtual()) { CheckAbstractEqualitySignature(diagnostics); } @@ -517,6 +572,10 @@ private void CheckOperatorSignatures(BindingDiagnosticBag diagnostics) break; } } + private bool IsInInterfaceAndAbstractOrVirtual() + { + return ContainingType.IsInterface && (IsAbstract || IsVirtual); + } private static bool DoesOperatorHaveCorrectArity(string name, int parameterCount) { @@ -593,14 +652,14 @@ private void CheckUserDefinedConversionSignature(BindingDiagnosticBag diagnostic // SPEC: Either S0 or T0 is the class or struct type in which the operator // SPEC: declaration takes place. - if (!MatchesContainingType(source0) && - !MatchesContainingType(target0) && + if (!MatchesContainingType(source0, checkStrippedType: false) && + !MatchesContainingType(target0, checkStrippedType: false) && // allow conversion between T and Nullable in declaration of Nullable - !MatchesContainingType(source) && - !MatchesContainingType(target)) + !MatchesContainingType(source, checkStrippedType: false) && + !MatchesContainingType(target, checkStrippedType: false)) { // CS0556: User-defined conversion must convert to or from the enclosing type - diagnostics.Add(IsAbstract || IsVirtual ? ErrorCode.ERR_AbstractConversionNotInvolvingContainedType : ErrorCode.ERR_ConversionNotInvolvingContainedType, this.GetFirstLocation()); + diagnostics.Add(IsInInterfaceAndAbstractOrVirtual() ? ErrorCode.ERR_AbstractConversionNotInvolvingContainedType : ErrorCode.ERR_ConversionNotInvolvingContainedType, this.GetFirstLocation()); return; } @@ -686,7 +745,7 @@ private void CheckUserDefinedConversionSignature(BindingDiagnosticBag diagnostic TypeSymbol same; TypeSymbol different; - if (MatchesContainingType(source0)) + if (MatchesContainingType(source0, checkStrippedType: false)) { same = source; different = target; @@ -733,13 +792,22 @@ private void CheckUnarySignature(BindingDiagnosticBag diagnostics) // SPEC: A unary + - ! ~ operator must take a single parameter of type // SPEC: T or T? and can return any type. - if (!MatchesContainingType(this.GetParameterType(0).StrippedType())) + CheckUnaryParameterType(diagnostics); + CheckReturnIsNotVoid(diagnostics); + } + + private void CheckUnaryParameterType(BindingDiagnosticBag diagnostics) + { + if (!MatchesContainingType(this.GetParameterType(0), checkStrippedType: true)) { // The parameter of a unary operator must be the containing type - diagnostics.Add((IsAbstract || IsVirtual) ? ErrorCode.ERR_BadAbstractUnaryOperatorSignature : ErrorCode.ERR_BadUnaryOperatorSignature, this.GetFirstLocation()); + diagnostics.Add(IsInInterfaceAndAbstractOrVirtual() ? + ErrorCode.ERR_BadAbstractUnaryOperatorSignature : + (ContainingType.IsExtension ? + ErrorCode.ERR_BadExtensionUnaryOperatorSignature : + ErrorCode.ERR_BadUnaryOperatorSignature), + this.GetFirstLocation()); } - - CheckReturnIsNotVoid(diagnostics); } private void CheckTrueFalseSignature(BindingDiagnosticBag diagnostics) @@ -753,11 +821,7 @@ private void CheckTrueFalseSignature(BindingDiagnosticBag diagnostics) diagnostics.Add(ErrorCode.ERR_OpTFRetType, this.GetFirstLocation()); } - if (!MatchesContainingType(this.GetParameterType(0).StrippedType())) - { - // The parameter of a unary operator must be the containing type - diagnostics.Add((IsAbstract || IsVirtual) ? ErrorCode.ERR_BadAbstractUnaryOperatorSignature : ErrorCode.ERR_BadUnaryOperatorSignature, this.GetFirstLocation()); - } + CheckUnaryParameterType(diagnostics); } private void CheckIncrementDecrementSignature(BindingDiagnosticBag diagnostics) @@ -803,27 +867,53 @@ private void CheckIncrementDecrementSignature(BindingDiagnosticBag diagnostics) var parameterType = this.GetParameterType(0); var useSiteInfo = new CompoundUseSiteInfo(diagnostics, ContainingAssembly); - if (!MatchesContainingType(parameterType.StrippedType())) + if (!MatchesContainingType(parameterType, checkStrippedType: true)) { // CS0559: The parameter type for ++ or -- operator must be the containing type - diagnostics.Add((IsAbstract || IsVirtual) ? ErrorCode.ERR_BadAbstractIncDecSignature : ErrorCode.ERR_BadIncDecSignature, this.GetFirstLocation()); + diagnostics.Add(IsInInterfaceAndAbstractOrVirtual() ? + ErrorCode.ERR_BadAbstractIncDecSignature : + (ContainingType.IsExtension ? + ErrorCode.ERR_BadExtensionIncDecSignature : + ErrorCode.ERR_BadIncDecSignature), + this.GetFirstLocation()); } else if (!(parameterType.IsTypeParameter() ? this.ReturnType.Equals(parameterType, ComparisonForUserDefinedOperators) : - (((IsAbstract || IsVirtual) && IsContainingType(parameterType) && IsSelfConstrainedTypeParameter(this.ReturnType)) || + ((IsInInterfaceAndAbstractOrVirtual() && IsContainingType(parameterType) && IsSelfConstrainedTypeParameter(this.ReturnType)) || this.ReturnType.EffectiveTypeNoUseSiteDiagnostics.IsEqualToOrDerivedFrom(parameterType, ComparisonForUserDefinedOperators, useSiteInfo: ref useSiteInfo)))) { // CS0448: The return type for ++ or -- operator must match the parameter type // or be derived from the parameter type - diagnostics.Add((IsAbstract || IsVirtual) ? ErrorCode.ERR_BadAbstractIncDecRetType : ErrorCode.ERR_BadIncDecRetType, this.GetFirstLocation()); + diagnostics.Add(IsInInterfaceAndAbstractOrVirtual() ? ErrorCode.ERR_BadAbstractIncDecRetType : ErrorCode.ERR_BadIncDecRetType, this.GetFirstLocation()); } diagnostics.Add(this.GetFirstLocation(), useSiteInfo); } - private bool MatchesContainingType(TypeSymbol type) + private bool MatchesContainingType(TypeSymbol type, bool checkStrippedType) + { + if (ContainingType is { IsExtension: true, ExtensionParameter.Type: var extendedType }) + { + if (extendedType is null) + { + return true; // An error scenario + } + + return ExtensionOperatorParameterTypeMatchesExtendedType(type, extendedType); + } + + if (checkStrippedType) + { + type = type.StrippedType(); + } + + return IsContainingType(type) || + (IsInInterfaceAndAbstractOrVirtual() && IsSelfConstrainedTypeParameter(type)); + } + + internal static bool ExtensionOperatorParameterTypeMatchesExtendedType(TypeSymbol type, TypeSymbol extendedType) { - return IsContainingType(type) || ((IsAbstract || IsVirtual) && IsSelfConstrainedTypeParameter(type)); + return type.Equals(extendedType, ComparisonForUserDefinedOperators); } private bool IsContainingType(TypeSymbol type) @@ -851,11 +941,14 @@ private void CheckShiftSignature(BindingDiagnosticBag diagnostics) // SPEC: of which must have type T or T?, the second of which can // SPEC: have any type. The operator can return any type. - if (!MatchesContainingType(this.GetParameterType(0).StrippedType())) + if (!MatchesContainingType(this.GetParameterType(0), checkStrippedType: true)) { // CS0546: The first operand of an overloaded shift operator must have the // same type as the containing type - diagnostics.Add((IsAbstract || IsVirtual) ? ErrorCode.ERR_BadAbstractShiftOperatorSignature : ErrorCode.ERR_BadShiftOperatorSignature, this.GetFirstLocation()); + diagnostics.Add(IsInInterfaceAndAbstractOrVirtual() ? + ErrorCode.ERR_BadAbstractShiftOperatorSignature : + (ContainingType.IsExtension ? ErrorCode.ERR_BadExtensionShiftOperatorSignature : ErrorCode.ERR_BadShiftOperatorSignature), + this.GetFirstLocation()); } else if (this.GetParameterType(1).StrippedType().SpecialType != SpecialType.System_Int32) { @@ -870,11 +963,14 @@ private void CheckBinarySignature(BindingDiagnosticBag 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 (!MatchesContainingType(this.GetParameterType(0).StrippedType()) && - !MatchesContainingType(this.GetParameterType(1).StrippedType())) + if (!MatchesContainingType(this.GetParameterType(0), checkStrippedType: true) && + !MatchesContainingType(this.GetParameterType(1), checkStrippedType: true)) { // CS0563: One of the parameters of a binary operator must be the containing type - diagnostics.Add((IsAbstract || IsVirtual) ? ErrorCode.ERR_BadAbstractBinaryOperatorSignature : ErrorCode.ERR_BadBinaryOperatorSignature, this.GetFirstLocation()); + diagnostics.Add(IsInInterfaceAndAbstractOrVirtual() ? + ErrorCode.ERR_BadAbstractBinaryOperatorSignature : + (ContainingType.IsExtension ? ErrorCode.ERR_BadExtensionBinaryOperatorSignature : ErrorCode.ERR_BadBinaryOperatorSignature), + this.GetFirstLocation()); } CheckReturnIsNotVoid(diagnostics); diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SynthesizedSourceOrdinaryMethodSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SynthesizedSourceOrdinaryMethodSymbol.cs index 5b642de3e2371..3b4cbaca3ab48 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SynthesizedSourceOrdinaryMethodSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SynthesizedSourceOrdinaryMethodSymbol.cs @@ -6,6 +6,7 @@ using System.Diagnostics; using System.Globalization; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/Symbols/SubstitutedMethodSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/SubstitutedMethodSymbol.cs index 86494a5ead675..d45d302dfb4bf 100644 --- a/src/Compilers/CSharp/Portable/Symbols/SubstitutedMethodSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/SubstitutedMethodSymbol.cs @@ -216,6 +216,8 @@ public override ImmutableArray GetReturnTypeAttributes() internal sealed override UnmanagedCallersOnlyAttributeData GetUnmanagedCallersOnlyAttributeData(bool forceComplete) => this.OriginalDefinition.GetUnmanagedCallersOnlyAttributeData(forceComplete); + internal sealed override bool HasSpecialNameAttribute => throw ExceptionUtilities.Unreachable(); + public sealed override Symbol AssociatedSymbol { get diff --git a/src/Compilers/CSharp/Portable/Symbols/Symbol_Attributes.cs b/src/Compilers/CSharp/Portable/Symbols/Symbol_Attributes.cs index ba230880ac8b7..a1ca8bd1fd943 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Symbol_Attributes.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Symbol_Attributes.cs @@ -10,6 +10,7 @@ using System.Diagnostics; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedPrimaryConstructorParameterBackingFieldSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedPrimaryConstructorParameterBackingFieldSymbol.cs index f373c80aade14..18e3b4b1024b0 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedPrimaryConstructorParameterBackingFieldSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedPrimaryConstructorParameterBackingFieldSymbol.cs @@ -4,6 +4,7 @@ using System.Collections.Immutable; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordEqualityContractProperty.cs b/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordEqualityContractProperty.cs index bf26af38968aa..3639394150e15 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordEqualityContractProperty.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordEqualityContractProperty.cs @@ -4,6 +4,7 @@ using System.Collections.Immutable; using System.Diagnostics; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordEqualityOperatorBase.cs b/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordEqualityOperatorBase.cs index 302e4b28e3a43..4c70588627b2d 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordEqualityOperatorBase.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordEqualityOperatorBase.cs @@ -6,6 +6,7 @@ using System.Diagnostics; using System.Globalization; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordPropertySymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordPropertySymbol.cs index 45a0afecdc918..5c9c0c277698b 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordPropertySymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordPropertySymbol.cs @@ -4,8 +4,9 @@ using System.Collections.Immutable; using System.Diagnostics; +using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { diff --git a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedAccessorValueParameterSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedAccessorValueParameterSymbol.cs index 4e63b427f00ff..568a75ebe2ca3 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedAccessorValueParameterSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedAccessorValueParameterSymbol.cs @@ -5,6 +5,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedBackingFieldSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedBackingFieldSymbol.cs index 719c26cb08b16..f635e571f4b61 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedBackingFieldSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedBackingFieldSymbol.cs @@ -8,6 +8,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEntryPointSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEntryPointSymbol.cs index ac668411c2d52..9be2ba82b0fdd 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEntryPointSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEntryPointSymbol.cs @@ -205,6 +205,8 @@ internal sealed override ObsoleteAttributeData ObsoleteAttributeData internal sealed override UnmanagedCallersOnlyAttributeData GetUnmanagedCallersOnlyAttributeData(bool forceComplete) => null; + internal sealed override bool HasSpecialNameAttribute => throw ExceptionUtilities.Unreachable(); + internal override Cci.CallingConvention CallingConvention { get { return 0; } diff --git a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEventAccessorSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEventAccessorSymbol.cs index 3fafab5d05194..b5086c12c28e4 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEventAccessorSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEventAccessorSymbol.cs @@ -6,6 +6,7 @@ using System.Diagnostics; using System.Reflection; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedGlobalMethodSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedGlobalMethodSymbol.cs index 811658bfbe4f5..565572822f98e 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedGlobalMethodSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedGlobalMethodSymbol.cs @@ -145,6 +145,8 @@ internal sealed override ObsoleteAttributeData ObsoleteAttributeData internal sealed override UnmanagedCallersOnlyAttributeData GetUnmanagedCallersOnlyAttributeData(bool forceComplete) => null; + internal sealed override bool HasSpecialNameAttribute => throw ExceptionUtilities.Unreachable(); + internal sealed override ImmutableArray GetAppliedConditionalSymbols() { return ImmutableArray.Empty; diff --git a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedIntrinsicOperatorSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedIntrinsicOperatorSymbol.cs index 12ec047f2ef23..0e96ec4aba326 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedIntrinsicOperatorSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedIntrinsicOperatorSymbol.cs @@ -408,6 +408,8 @@ internal override ObsoleteAttributeData ObsoleteAttributeData internal sealed override UnmanagedCallersOnlyAttributeData GetUnmanagedCallersOnlyAttributeData(bool forceComplete) => null; + internal sealed override bool HasSpecialNameAttribute => throw ExceptionUtilities.Unreachable(); + internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { throw ExceptionUtilities.Unreachable(); diff --git a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedMethodSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedMethodSymbol.cs index de0966d0f8ac4..58d4b0dd8ae00 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedMethodSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedMethodSymbol.cs @@ -72,6 +72,8 @@ internal sealed override ObsoleteAttributeData ObsoleteAttributeData internal sealed override UnmanagedCallersOnlyAttributeData GetUnmanagedCallersOnlyAttributeData(bool forceComplete) => null; + internal sealed override bool HasSpecialNameAttribute => throw ExceptionUtilities.Unreachable(); + internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { throw ExceptionUtilities.Unreachable(); diff --git a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedStaticConstructor.cs b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedStaticConstructor.cs index df7e6416e5419..9853f23e7f023 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedStaticConstructor.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedStaticConstructor.cs @@ -367,6 +367,8 @@ internal sealed override ObsoleteAttributeData? ObsoleteAttributeData internal sealed override UnmanagedCallersOnlyAttributeData? GetUnmanagedCallersOnlyAttributeData(bool forceComplete) => null; + internal sealed override bool HasSpecialNameAttribute => throw ExceptionUtilities.Unreachable(); + internal override ImmutableArray GetAppliedConditionalSymbols() { return ImmutableArray.Empty; diff --git a/src/Compilers/CSharp/Portable/Symbols/TypeSymbolExtensions.cs b/src/Compilers/CSharp/Portable/Symbols/TypeSymbolExtensions.cs index 9c31d578b65cc..0bbd226cf71c6 100644 --- a/src/Compilers/CSharp/Portable/Symbols/TypeSymbolExtensions.cs +++ b/src/Compilers/CSharp/Portable/Symbols/TypeSymbolExtensions.cs @@ -7,6 +7,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/Compilers/CSharp/Portable/Syntax/CSharpSyntaxNode.cs b/src/Compilers/CSharp/Portable/Syntax/CSharpSyntaxNode.cs index 3b09234ad0c18..3f27691d9e952 100644 --- a/src/Compilers/CSharp/Portable/Syntax/CSharpSyntaxNode.cs +++ b/src/Compilers/CSharp/Portable/Syntax/CSharpSyntaxNode.cs @@ -9,9 +9,7 @@ using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { @@ -73,8 +71,8 @@ private static SyntaxTree ComputeSyntaxTree(CSharpSyntaxNode node) if (parent == null) { // set the tree on the root node atomically -#pragma warning disable RS0030 // Do not use banned APIs (CreateWithoutClone is intended to be used from this call site only) - Interlocked.CompareExchange(ref node._syntaxTree, CSharpSyntaxTree.CreateWithoutClone(node), null); +#pragma warning disable RS0030 // Do not use banned APIs (CreateWithoutClone is intended to be used from this call site) + Interlocked.CompareExchange(ref node._syntaxTree, CSharpSyntaxTree.CreateWithoutClone(node, CSharpParseOptions.Default), null); #pragma warning restore tree = node._syntaxTree; break; diff --git a/src/Compilers/CSharp/Portable/Syntax/CSharpSyntaxTree.cs b/src/Compilers/CSharp/Portable/Syntax/CSharpSyntaxTree.cs index 6cf328da50821..103c8509f5c28 100644 --- a/src/Compilers/CSharp/Portable/Syntax/CSharpSyntaxTree.cs +++ b/src/Compilers/CSharp/Portable/Syntax/CSharpSyntaxTree.cs @@ -8,8 +8,6 @@ using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -390,10 +388,10 @@ internal static SyntaxTree CreateForDebugger(CSharpSyntaxNode root, SourceText t /// Internal helper for class to create a new syntax tree rooted at the given root node. /// This method does not create a clone of the given root, but instead preserves it's reference identity. /// - /// NOTE: This method is only intended to be used from property. + /// NOTE: This method is only intended to be used from property and SyntaxFactory.Parse* methods. /// NOTE: Do not use this method elsewhere, instead use method for creating a syntax tree. /// - internal static SyntaxTree CreateWithoutClone(CSharpSyntaxNode root) + internal static SyntaxTree CreateWithoutClone(CSharpSyntaxNode root, CSharpParseOptions options) { Debug.Assert(root != null); @@ -402,7 +400,7 @@ internal static SyntaxTree CreateWithoutClone(CSharpSyntaxNode root) encodingOpt: null, checksumAlgorithm: SourceHashAlgorithm.Sha1, path: "", - options: CSharpParseOptions.Default, + options: options, root: root, directives: default, diagnosticOptions: null, diff --git a/src/Compilers/CSharp/Portable/Syntax/Syntax.xml b/src/Compilers/CSharp/Portable/Syntax/Syntax.xml index ee5d7ede378e0..c8dc72b771244 100644 --- a/src/Compilers/CSharp/Portable/Syntax/Syntax.xml +++ b/src/Compilers/CSharp/Portable/Syntax/Syntax.xml @@ -4359,7 +4359,7 @@ - + Gets the identifier. diff --git a/src/Compilers/CSharp/Portable/Syntax/SyntaxFactory.cs b/src/Compilers/CSharp/Portable/Syntax/SyntaxFactory.cs index a1cbe33a1b30f..5b57505194954 100644 --- a/src/Compilers/CSharp/Portable/Syntax/SyntaxFactory.cs +++ b/src/Compilers/CSharp/Portable/Syntax/SyntaxFactory.cs @@ -1694,7 +1694,7 @@ public static NameSyntax ParseName(string text, int offset = 0, bool consumeFull { var node = parser.ParseName(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); - return (NameSyntax)node.CreateRed(); + return CreateRed(node, lexer.Options); } } @@ -1718,7 +1718,7 @@ public static TypeSyntax ParseTypeName(string text, int offset = 0, ParseOptions { var node = parser.ParseTypeName(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); - return (TypeSyntax)node.CreateRed(); + return CreateRed(node, lexer.Options); } } @@ -1737,7 +1737,7 @@ public static ExpressionSyntax ParseExpression(string text, int offset = 0, Pars { var node = parser.ParseExpression(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); - return (ExpressionSyntax)node.CreateRed(); + return CreateRed(node, lexer.Options); } } @@ -1756,7 +1756,7 @@ public static StatementSyntax ParseStatement(string text, int offset = 0, ParseO { var node = parser.ParseStatement(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); - return (StatementSyntax)node.CreateRed(); + return CreateRed(node, lexer.Options); } } @@ -1780,7 +1780,7 @@ public static StatementSyntax ParseStatement(string text, int offset = 0, ParseO return null; } - return (MemberDeclarationSyntax)(consumeFullText ? parser.ConsumeUnexpectedTokens(node) : node).CreateRed(); + return CreateRed(consumeFullText ? parser.ConsumeUnexpectedTokens(node) : node, lexer.Options); } } @@ -1800,7 +1800,7 @@ public static CompilationUnitSyntax ParseCompilationUnit(string text, int offset using (var parser = MakeParser(lexer)) { var node = parser.ParseCompilationUnit(); - return (CompilationUnitSyntax)node.CreateRed(); + return CreateRed(node, lexer.Options); } } @@ -1819,7 +1819,7 @@ public static ParameterListSyntax ParseParameterList(string text, int offset = 0 { var node = parser.ParseParenthesizedParameterList(forExtension: false); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); - return (ParameterListSyntax)node.CreateRed(); + return CreateRed(node, lexer.Options); } } @@ -1838,7 +1838,7 @@ public static BracketedParameterListSyntax ParseBracketedParameterList(string te { var node = parser.ParseBracketedParameterList(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); - return (BracketedParameterListSyntax)node.CreateRed(); + return CreateRed(node, lexer.Options); } } @@ -1857,7 +1857,7 @@ public static ArgumentListSyntax ParseArgumentList(string text, int offset = 0, { var node = parser.ParseParenthesizedArgumentList(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); - return (ArgumentListSyntax)node.CreateRed(); + return CreateRed(node, lexer.Options); } } @@ -1876,7 +1876,7 @@ public static BracketedArgumentListSyntax ParseBracketedArgumentList(string text { var node = parser.ParseBracketedArgumentList(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); - return (BracketedArgumentListSyntax)node.CreateRed(); + return CreateRed(node, lexer.Options); } } @@ -1902,7 +1902,18 @@ public static BracketedArgumentListSyntax ParseBracketedArgumentList(string text annotations: null); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); - return (AttributeArgumentListSyntax)node.CreateRed(); + return CreateRed(node, lexer.Options); + } + + private static TSyntax CreateRed(InternalSyntax.CSharpSyntaxNode green, CSharpParseOptions options) + where TSyntax : CSharpSyntaxNode + { + var red = (TSyntax)green.CreateRed(); + Debug.Assert(red._syntaxTree is null); +#pragma warning disable RS0030 // Do not use banned APIs (CreateWithoutClone is intended to be used from this call site) + red._syntaxTree = CSharpSyntaxTree.CreateWithoutClone(red, options); +#pragma warning restore + return red; } /// diff --git a/src/Compilers/CSharp/Portable/Syntax/SyntaxKindFacts.cs b/src/Compilers/CSharp/Portable/Syntax/SyntaxKindFacts.cs index 5e22aa093ff31..7b0fd1c1de5a0 100644 --- a/src/Compilers/CSharp/Portable/Syntax/SyntaxKindFacts.cs +++ b/src/Compilers/CSharp/Portable/Syntax/SyntaxKindFacts.cs @@ -853,7 +853,7 @@ public static SyntaxKind GetBaseTypeDeclarationKind(SyntaxKind kind) return kind == SyntaxKind.EnumKeyword ? SyntaxKind.EnumDeclaration : GetTypeDeclarationKind(kind); } - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : decide what we want for extension declaration + // Tracked by https://github.com/dotnet/roslyn/issues/78957 : public API, decide what we want for extension declaration public static SyntaxKind GetTypeDeclarationKind(SyntaxKind kind) { switch (kind) diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.cs.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.cs.xlf index 8c739fc5d1b4d..b30c1f0cc7f1f 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.cs.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.cs.xlf @@ -227,11 +227,31 @@ V asynchronním příkazu foreach nejde použít kolekce dynamického typu. + + One of the parameters of a binary operator must be the extended type. + One of the parameters of a binary operator must be the extended type. + + Extensions must be declared in a top-level, non-generic, static class Extensions must be declared in a top-level, non-generic, static class + + The parameter type for ++ or -- operator must be the extended type. + The parameter type for ++ or -- operator must be the extended type. + + + + The first operand of an overloaded shift operator must have the same type as the extended type + The first operand of an overloaded shift operator must have the same type as the extended type + + + + The parameter of a unary operator must be the extended type. + The parameter of a unary operator must be the extended type. + + The type '{0}' may not be used for a field of a record. Typ {0} se nedá použít pro pole záznamu. @@ -732,6 +752,11 @@ Strom výrazů nesmí obsahovat výraz kolekce. + + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + + An expression tree may not contain an extension property access An expression tree may not contain an extension property access @@ -1102,6 +1127,16 @@ '{0}': cannot declare instance members in an extension block with an unnamed receiver parameter + + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + + + + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + + Instance properties in interfaces cannot have initializers. Vlastnosti instance v rozhraních nemůžou mít inicializátory. @@ -1557,6 +1592,11 @@ Přístup k vloženému poli nemůže mít specifikátor pojmenovaného argumentu. + + Extension members are not allowed as an argument to 'nameof'. + Extension members are not allowed as an argument to 'nameof'. + + The 'new()' constraint cannot be used with the 'unmanaged' constraint Omezení new() nejde používat s omezením unmanaged. @@ -1697,6 +1737,11 @@ Uživatelsky definovaný operátor {0} nejde deklarovat zaškrtnutý. + + An extension block extending a static class cannot contain user-defined operators + An extension block extending a static class cannot contain user-defined operators + + '{0}': cannot override inherited member '{1}' because one of them is not an operator. '{0}': cannot override inherited member '{1}' because one of them is not an operator. @@ -7602,7 +7647,7 @@ Pokud se taková třída používá jako základní třída a pokud odvozující Předdefinovaný typ {0} není definovaný ani importovaný. - + Predefined type '{0}' is declared in multiple referenced assemblies: '{1}' and '{2}' Předdefinovaný typ {0} je deklarovaný v několika odkazovaných sestaveních: {1} a {2}. @@ -7918,8 +7963,8 @@ Pokud se taková třída používá jako základní třída a pokud odvozující - The DllImport attribute must be specified on a method marked 'static' and 'extern' - Pro metodu s deklarací static a extern musí být zadaný atribut DllImport. + The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member + Pro metodu s deklarací static a extern musí být zadaný atribut DllImport. diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.de.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.de.xlf index 687feee638dbd..11263622daaba 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.de.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.de.xlf @@ -227,11 +227,31 @@ Eine Sammlung des dynamic-Typs kann in einem asynchronen foreach nicht verwendet werden. + + One of the parameters of a binary operator must be the extended type. + One of the parameters of a binary operator must be the extended type. + + Extensions must be declared in a top-level, non-generic, static class Extensions must be declared in a top-level, non-generic, static class + + The parameter type for ++ or -- operator must be the extended type. + The parameter type for ++ or -- operator must be the extended type. + + + + The first operand of an overloaded shift operator must have the same type as the extended type + The first operand of an overloaded shift operator must have the same type as the extended type + + + + The parameter of a unary operator must be the extended type. + The parameter of a unary operator must be the extended type. + + The type '{0}' may not be used for a field of a record. Der Typ "{0}" darf nicht für ein Feld eines Datensatzes verwendet werden. @@ -732,6 +752,11 @@ Eine Ausdrucksbaumstruktur darf keinen Sammlungsausdruck enthalten. + + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + + An expression tree may not contain an extension property access An expression tree may not contain an extension property access @@ -1102,6 +1127,16 @@ '{0}': cannot declare instance members in an extension block with an unnamed receiver parameter + + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + + + + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + + Instance properties in interfaces cannot have initializers. Instanzeigenschaften in Schnittstellen können keine Initialisierer aufweisen. @@ -1557,6 +1592,11 @@ Ein Inlinearrayzugriff verfügt möglicherweise nicht über einen benannten Argumentspezifizierer. + + Extension members are not allowed as an argument to 'nameof'. + Extension members are not allowed as an argument to 'nameof'. + + The 'new()' constraint cannot be used with the 'unmanaged' constraint Die new()-Einschränkung kann nicht mit der unmanaged-Einschränkung verwendet werden. @@ -1697,6 +1737,11 @@ Der benutzerdefinierte Operator "{0}" kann nicht als überprüft deklariert werden. + + An extension block extending a static class cannot contain user-defined operators + An extension block extending a static class cannot contain user-defined operators + + '{0}': cannot override inherited member '{1}' because one of them is not an operator. '{0}': cannot override inherited member '{1}' because one of them is not an operator. @@ -7602,7 +7647,7 @@ Wenn solch eine Klasse als Basisklasse verwendet wird und die ableitende Klasse Der vordefinierte Typ "{0}" ist nicht definiert oder importiert. - + Predefined type '{0}' is declared in multiple referenced assemblies: '{1}' and '{2}' Der vordefinierte Typ "{0}" wurde in mehreren referenzierten Assemblys deklariert: "{1}" und "{2}" @@ -7918,8 +7963,8 @@ Wenn solch eine Klasse als Basisklasse verwendet wird und die ableitende Klasse - The DllImport attribute must be specified on a method marked 'static' and 'extern' - Das DllImport-Attribut muss für eine Methode angegeben werden, die als "static" und "extern" markiert ist. + The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member + Das DllImport-Attribut muss für eine Methode angegeben werden, die als "static" und "extern" markiert ist. diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.es.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.es.xlf index 20ee0d17e8855..c2b21cbe11444 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.es.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.es.xlf @@ -227,11 +227,31 @@ No se puede usar una colección de tipo dinámico en una instrucción foreach asincrónica. + + One of the parameters of a binary operator must be the extended type. + One of the parameters of a binary operator must be the extended type. + + Extensions must be declared in a top-level, non-generic, static class Extensions must be declared in a top-level, non-generic, static class + + The parameter type for ++ or -- operator must be the extended type. + The parameter type for ++ or -- operator must be the extended type. + + + + The first operand of an overloaded shift operator must have the same type as the extended type + The first operand of an overloaded shift operator must have the same type as the extended type + + + + The parameter of a unary operator must be the extended type. + The parameter of a unary operator must be the extended type. + + The type '{0}' may not be used for a field of a record. No se puede usar el tipo "{0}" para un campo de un registro. @@ -732,6 +752,11 @@ Un árbol de expresión no puede contener una expresión de colección. + + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + + An expression tree may not contain an extension property access An expression tree may not contain an extension property access @@ -1102,6 +1127,16 @@ '{0}': cannot declare instance members in an extension block with an unnamed receiver parameter + + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + + + + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + + Instance properties in interfaces cannot have initializers. Las propiedades de la instancia en las interfaces no pueden tener inicializadores. @@ -1557,6 +1592,11 @@ Un acceso de matriz insertado no puede tener un especificador de argumento con nombre + + Extension members are not allowed as an argument to 'nameof'. + Extension members are not allowed as an argument to 'nameof'. + + The 'new()' constraint cannot be used with the 'unmanaged' constraint La restricción "new()" no se puede utilizar con la restricción "unmanaged" @@ -1697,6 +1737,11 @@ El operador definido por el usuario '{0}' no se puede declarar como comprobado + + An extension block extending a static class cannot contain user-defined operators + An extension block extending a static class cannot contain user-defined operators + + '{0}': cannot override inherited member '{1}' because one of them is not an operator. '{0}': cannot override inherited member '{1}' because one of them is not an operator. @@ -7602,7 +7647,7 @@ Si se utiliza una clase de este tipo como clase base y si la clase derivada defi El tipo predefinido '{0}' no está definido ni importado - + Predefined type '{0}' is declared in multiple referenced assemblies: '{1}' and '{2}' El tipo "{0}" predefinido se declara en varios ensamblados a los que se hace referencia: "{1}" y "{2}" @@ -7918,8 +7963,8 @@ Si se utiliza una clase de este tipo como clase base y si la clase derivada defi - The DllImport attribute must be specified on a method marked 'static' and 'extern' - El atributo DllImport se debe especificar en un método marcado como 'static' y 'extern' + The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member + El atributo DllImport se debe especificar en un método marcado como 'static' y 'extern' diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.fr.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.fr.xlf index 120060b6aa3f5..8b74f1d907f9e 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.fr.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.fr.xlf @@ -227,11 +227,31 @@ Impossible d'utiliser une collection de type dynamique dans un foreach asynchrone + + One of the parameters of a binary operator must be the extended type. + One of the parameters of a binary operator must be the extended type. + + Extensions must be declared in a top-level, non-generic, static class Extensions must be declared in a top-level, non-generic, static class + + The parameter type for ++ or -- operator must be the extended type. + The parameter type for ++ or -- operator must be the extended type. + + + + The first operand of an overloaded shift operator must have the same type as the extended type + The first operand of an overloaded shift operator must have the same type as the extended type + + + + The parameter of a unary operator must be the extended type. + The parameter of a unary operator must be the extended type. + + The type '{0}' may not be used for a field of a record. Le type '{0}' ne doit pas être utilisé pour un champ d'enregistrement. @@ -732,6 +752,11 @@ Une arborescence de l’expression ne peut pas contenir une expression de collection. + + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + + An expression tree may not contain an extension property access An expression tree may not contain an extension property access @@ -1102,6 +1127,16 @@ '{0}': cannot declare instance members in an extension block with an unnamed receiver parameter + + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + + + + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + + Instance properties in interfaces cannot have initializers. Les propriétés d'instance dans les interfaces ne peuvent pas avoir d'initialiseurs. @@ -1557,6 +1592,11 @@ Un accès au tableau en ligne peut ne pas avoir de spécificateur d'argument nommé + + Extension members are not allowed as an argument to 'nameof'. + Extension members are not allowed as an argument to 'nameof'. + + The 'new()' constraint cannot be used with the 'unmanaged' constraint La contrainte 'new()' ne peut pas être utilisée avec la contrainte 'unmanaged' @@ -1697,6 +1737,11 @@ Impossible de vérifier l’opérateur défini par l’utilisateur '{0}' + + An extension block extending a static class cannot contain user-defined operators + An extension block extending a static class cannot contain user-defined operators + + '{0}': cannot override inherited member '{1}' because one of them is not an operator. '{0}': cannot override inherited member '{1}' because one of them is not an operator. @@ -7602,7 +7647,7 @@ Si une telle classe est utilisée en tant que classe de base et si la classe dé Le type prédéfini '{0}' n'est pas défini ou importé - + Predefined type '{0}' is declared in multiple referenced assemblies: '{1}' and '{2}' Le type prédéfini '{0}' est déclaré dans plusieurs assemblys référencés : '{1}' et '{2}' @@ -7918,8 +7963,8 @@ Si une telle classe est utilisée en tant que classe de base et si la classe dé - The DllImport attribute must be specified on a method marked 'static' and 'extern' - L'attribut DllImport doit être spécifié sur une méthode marquée 'static' et 'extern' + The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member + L'attribut DllImport doit être spécifié sur une méthode marquée 'static' et 'extern' diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.it.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.it.xlf index 44e10a1c36ea6..10a0c31e96a6c 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.it.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.it.xlf @@ -227,11 +227,31 @@ Non è possibile usare una raccolta di tipo dinamico in un'istruzione foreach asincrona + + One of the parameters of a binary operator must be the extended type. + One of the parameters of a binary operator must be the extended type. + + Extensions must be declared in a top-level, non-generic, static class Extensions must be declared in a top-level, non-generic, static class + + The parameter type for ++ or -- operator must be the extended type. + The parameter type for ++ or -- operator must be the extended type. + + + + The first operand of an overloaded shift operator must have the same type as the extended type + The first operand of an overloaded shift operator must have the same type as the extended type + + + + The parameter of a unary operator must be the extended type. + The parameter of a unary operator must be the extended type. + + The type '{0}' may not be used for a field of a record. Il tipo '{0}' non può essere usato per un campo di un record. @@ -732,6 +752,11 @@ Un albero delle espressioni non può contenere un'espressione di raccolta. + + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + + An expression tree may not contain an extension property access An expression tree may not contain an extension property access @@ -1102,6 +1127,16 @@ '{0}': cannot declare instance members in an extension block with an unnamed receiver parameter + + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + + + + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + + Instance properties in interfaces cannot have initializers. Le proprietà di istanza nelle interfacce non possono avere inizializzatori. @@ -1557,6 +1592,11 @@ Un accesso a matrice inline non può includere un identificatore di argomento denominato + + Extension members are not allowed as an argument to 'nameof'. + Extension members are not allowed as an argument to 'nameof'. + + The 'new()' constraint cannot be used with the 'unmanaged' constraint Non è possibile usare il vincolo 'new()' con il vincolo 'unmanaged' @@ -1697,6 +1737,11 @@ Impossibile dichiarare controllato l'operatore '{0}' definito dall'utente + + An extension block extending a static class cannot contain user-defined operators + An extension block extending a static class cannot contain user-defined operators + + '{0}': cannot override inherited member '{1}' because one of them is not an operator. '{0}': cannot override inherited member '{1}' because one of them is not an operator. @@ -7602,7 +7647,7 @@ Se si usa tale classe come classe base e se la classe di derivazione definisce u Il tipo predefinito '{0}' non è definito né importato - + Predefined type '{0}' is declared in multiple referenced assemblies: '{1}' and '{2}' Il tipo predefinito '{0}' è dichiarato in più assembly di riferimento: '{1}' e '{2}' @@ -7918,8 +7963,8 @@ Se si usa tale classe come classe base e se la classe di derivazione definisce u - The DllImport attribute must be specified on a method marked 'static' and 'extern' - L'attributo DllImport deve essere specificato in un metodo contrassegnato come 'static' ed 'extern' + The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member + L'attributo DllImport deve essere specificato in un metodo contrassegnato come 'static' ed 'extern' diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.ja.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.ja.xlf index a24d8c00b293a..231f60fdf6b6c 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.ja.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.ja.xlf @@ -227,11 +227,31 @@ 非同期 foreach では動的な型のコレクションを使用できません + + One of the parameters of a binary operator must be the extended type. + One of the parameters of a binary operator must be the extended type. + + Extensions must be declared in a top-level, non-generic, static class Extensions must be declared in a top-level, non-generic, static class + + The parameter type for ++ or -- operator must be the extended type. + The parameter type for ++ or -- operator must be the extended type. + + + + The first operand of an overloaded shift operator must have the same type as the extended type + The first operand of an overloaded shift operator must have the same type as the extended type + + + + The parameter of a unary operator must be the extended type. + The parameter of a unary operator must be the extended type. + + The type '{0}' may not be used for a field of a record. レコードのフィールドに対して型 '{0}' を使用することはできません。 @@ -732,6 +752,11 @@ 式ツリーにコレクション式を含めることはできません。 + + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + + An expression tree may not contain an extension property access An expression tree may not contain an extension property access @@ -1102,6 +1127,16 @@ '{0}': cannot declare instance members in an extension block with an unnamed receiver parameter + + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + + + + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + + Instance properties in interfaces cannot have initializers. インターフェイス内のインスタンス プロパティは初期化子を持つことができません。 @@ -1557,6 +1592,11 @@ インライン配列のアクセスには名前付き引数の指定子を指定できません + + Extension members are not allowed as an argument to 'nameof'. + Extension members are not allowed as an argument to 'nameof'. + + The 'new()' constraint cannot be used with the 'unmanaged' constraint new()' 制約は 'unmanaged' 制約と一緒には使用できません @@ -1697,6 +1737,11 @@ ユーザー定義演算子 '{0}' はチェック済みと宣言できません。 + + An extension block extending a static class cannot contain user-defined operators + An extension block extending a static class cannot contain user-defined operators + + '{0}': cannot override inherited member '{1}' because one of them is not an operator. '{0}': cannot override inherited member '{1}' because one of them is not an operator. @@ -7602,7 +7647,7 @@ If such a class is used as a base class and if the deriving class defines a dest 定義済みの型 '{0}' は定義、またはインポートされていません - + Predefined type '{0}' is declared in multiple referenced assemblies: '{1}' and '{2}' 定義済みの型 '{0}' が複数の参照先アセンブリで宣言されています: '{1}' と '{2}' @@ -7918,8 +7963,8 @@ If such a class is used as a base class and if the deriving class defines a dest - The DllImport attribute must be specified on a method marked 'static' and 'extern' - static または extern に指定されているメソッドでは、DllImport 属性を指定する必要があります + The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member + static または extern に指定されているメソッドでは、DllImport 属性を指定する必要があります diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.ko.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.ko.xlf index 85abbd7b43313..a7ba61b02b0ca 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.ko.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.ko.xlf @@ -227,11 +227,31 @@ 비동기 foreach에는 동적 형식 컬렉션을 사용할 수 없습니다. + + One of the parameters of a binary operator must be the extended type. + One of the parameters of a binary operator must be the extended type. + + Extensions must be declared in a top-level, non-generic, static class Extensions must be declared in a top-level, non-generic, static class + + The parameter type for ++ or -- operator must be the extended type. + The parameter type for ++ or -- operator must be the extended type. + + + + The first operand of an overloaded shift operator must have the same type as the extended type + The first operand of an overloaded shift operator must have the same type as the extended type + + + + The parameter of a unary operator must be the extended type. + The parameter of a unary operator must be the extended type. + + The type '{0}' may not be used for a field of a record. '{0}' 형식은 레코드의 필드에 사용할 수 없습니다. @@ -732,6 +752,11 @@ 식 트리에는 컬렉션 식이 포함될 수 없습니다. + + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + + An expression tree may not contain an extension property access An expression tree may not contain an extension property access @@ -1102,6 +1127,16 @@ '{0}': cannot declare instance members in an extension block with an unnamed receiver parameter + + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + + + + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + + Instance properties in interfaces cannot have initializers. 인터페이스의 인스턴스 속성은 이니셜라이저를 사용할 수 없습니다. @@ -1557,6 +1592,11 @@ 인라인 배열 액세스에는 명명된 인수 지정자가 없을 수 있습니다. + + Extension members are not allowed as an argument to 'nameof'. + Extension members are not allowed as an argument to 'nameof'. + + The 'new()' constraint cannot be used with the 'unmanaged' constraint new()' 제약 조건은 'unmanaged' 제약 조건과 함께 사용할 수 없습니다. @@ -1697,6 +1737,11 @@ 사용자 정의 연산자 '{0}'은(는) 선언할 수 없습니다. + + An extension block extending a static class cannot contain user-defined operators + An extension block extending a static class cannot contain user-defined operators + + '{0}': cannot override inherited member '{1}' because one of them is not an operator. '{0}': cannot override inherited member '{1}' because one of them is not an operator. @@ -7602,7 +7647,7 @@ If such a class is used as a base class and if the deriving class defines a dest 미리 정의된 형식 '{0}'을(를) 정의하지 않았거나 가져오지 않았습니다. - + Predefined type '{0}' is declared in multiple referenced assemblies: '{1}' and '{2}' 미리 정의된 형식 '{0}'이(가) 여러 참조된 어셈블리('{1}' 및 '{2}')에서 선언되었습니다. @@ -7918,8 +7963,8 @@ If such a class is used as a base class and if the deriving class defines a dest - The DllImport attribute must be specified on a method marked 'static' and 'extern' - DllImport 특성은 'static' 및 'extern'으로 표시된 메서드에만 지정할 수 있습니다. + The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member + DllImport 특성은 'static' 및 'extern'으로 표시된 메서드에만 지정할 수 있습니다. diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.pl.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.pl.xlf index 7808486f9b304..6036b054ea4ab 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.pl.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.pl.xlf @@ -227,11 +227,31 @@ Nie można użyć kolekcji typu dynamicznego w asynchronicznej instrukcji foreach + + One of the parameters of a binary operator must be the extended type. + One of the parameters of a binary operator must be the extended type. + + Extensions must be declared in a top-level, non-generic, static class Extensions must be declared in a top-level, non-generic, static class + + The parameter type for ++ or -- operator must be the extended type. + The parameter type for ++ or -- operator must be the extended type. + + + + The first operand of an overloaded shift operator must have the same type as the extended type + The first operand of an overloaded shift operator must have the same type as the extended type + + + + The parameter of a unary operator must be the extended type. + The parameter of a unary operator must be the extended type. + + The type '{0}' may not be used for a field of a record. Typ „{0}” nie może być używany dla pola rekordu. @@ -732,6 +752,11 @@ Drzewo wyrażenia nie może zawierać wyrażenia kolekcji. + + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + + An expression tree may not contain an extension property access An expression tree may not contain an extension property access @@ -1102,6 +1127,16 @@ '{0}': cannot declare instance members in an extension block with an unnamed receiver parameter + + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + + + + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + + Instance properties in interfaces cannot have initializers. Właściwości wystąpienia w interfejsach nie mogą mieć inicjatorów. @@ -1557,6 +1592,11 @@ Dostęp do tablicy śródwierszowej nie może mieć specyfikatora argumentu nazwanego + + Extension members are not allowed as an argument to 'nameof'. + Extension members are not allowed as an argument to 'nameof'. + + The 'new()' constraint cannot be used with the 'unmanaged' constraint Ograniczenie „new()” nie może być używane z ograniczeniem „unmanaged” @@ -1697,6 +1737,11 @@ Nie można zadeklarować operatora „{0}” zdefiniowanego przez użytkownika + + An extension block extending a static class cannot contain user-defined operators + An extension block extending a static class cannot contain user-defined operators + + '{0}': cannot override inherited member '{1}' because one of them is not an operator. '{0}': cannot override inherited member '{1}' because one of them is not an operator. @@ -7602,7 +7647,7 @@ Jeśli taka klasa zostanie użyta jako klasa bazowa i klasa pochodna definiuje d Wstępnie zdefiniowany typ „{0}” nie został zdefiniowany ani zaimportowany. - + Predefined type '{0}' is declared in multiple referenced assemblies: '{1}' and '{2}' Wstępnie zdefiniowany typ „{0}” jest zadeklarowany w wielu przywoływanych zestawach: „{1}” i „{2}” @@ -7918,8 +7963,8 @@ Jeśli taka klasa zostanie użyta jako klasa bazowa i klasa pochodna definiuje d - The DllImport attribute must be specified on a method marked 'static' and 'extern' - Dla metody oznaczonej przy użyciu słów kluczowych „static” i „extern” musi zostać określony atrybut DllImport + The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member + Dla metody oznaczonej przy użyciu słów kluczowych „static” i „extern” musi zostać określony atrybut DllImport diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.pt-BR.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.pt-BR.xlf index 3d7f1b33a89f9..6e44daf57a97f 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.pt-BR.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.pt-BR.xlf @@ -227,11 +227,31 @@ Não é possível usar uma coleção do tipo dinâmico em uma foreach assíncrona + + One of the parameters of a binary operator must be the extended type. + One of the parameters of a binary operator must be the extended type. + + Extensions must be declared in a top-level, non-generic, static class Extensions must be declared in a top-level, non-generic, static class + + The parameter type for ++ or -- operator must be the extended type. + The parameter type for ++ or -- operator must be the extended type. + + + + The first operand of an overloaded shift operator must have the same type as the extended type + The first operand of an overloaded shift operator must have the same type as the extended type + + + + The parameter of a unary operator must be the extended type. + The parameter of a unary operator must be the extended type. + + The type '{0}' may not be used for a field of a record. O tipo '{0}' não pode ser usado para um campo de um registro. @@ -732,6 +752,11 @@ Uma árvore de expressão não pode conter uma expressão de coleção. + + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + + An expression tree may not contain an extension property access An expression tree may not contain an extension property access @@ -1102,6 +1127,16 @@ '{0}': cannot declare instance members in an extension block with an unnamed receiver parameter + + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + + + + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + + Instance properties in interfaces cannot have initializers. As propriedades da instância nas interfaces não podem ter inicializadores. @@ -1557,6 +1592,11 @@ Um acesso à matriz não pode ter um especificador de argumento nomeado + + Extension members are not allowed as an argument to 'nameof'. + Extension members are not allowed as an argument to 'nameof'. + + The 'new()' constraint cannot be used with the 'unmanaged' constraint A restrição 'new()' não pode ser usada com a restrição 'unmanaged' @@ -1697,6 +1737,11 @@ O operador definido pelo usuário '{0}' não pode ser declarado verificado + + An extension block extending a static class cannot contain user-defined operators + An extension block extending a static class cannot contain user-defined operators + + '{0}': cannot override inherited member '{1}' because one of them is not an operator. '{0}': cannot override inherited member '{1}' because one of them is not an operator. @@ -7602,7 +7647,7 @@ Se tal classe for usada como uma classe base e se a classe derivada definir um d O tipo pré-definido "{0}" não foi definido ou importado - + Predefined type '{0}' is declared in multiple referenced assemblies: '{1}' and '{2}' O tipo predefinido ‘{0}’ é declarado em vários assemblies referenciados: ‘{1}’ e ‘{2}’ @@ -7918,8 +7963,8 @@ Se tal classe for usada como uma classe base e se a classe derivada definir um d - The DllImport attribute must be specified on a method marked 'static' and 'extern' - O atributo DllImport deve ser especificado em um método marcado como 'static' e 'extern' + The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member + O atributo DllImport deve ser especificado em um método marcado como 'static' e 'extern' diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.ru.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.ru.xlf index 3bdbf01e5b6f0..cb8c90d83676d 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.ru.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.ru.xlf @@ -227,11 +227,31 @@ Не удается использовать коллекцию динамического типа в асинхронном операторе foreach + + One of the parameters of a binary operator must be the extended type. + One of the parameters of a binary operator must be the extended type. + + Extensions must be declared in a top-level, non-generic, static class Extensions must be declared in a top-level, non-generic, static class + + The parameter type for ++ or -- operator must be the extended type. + The parameter type for ++ or -- operator must be the extended type. + + + + The first operand of an overloaded shift operator must have the same type as the extended type + The first operand of an overloaded shift operator must have the same type as the extended type + + + + The parameter of a unary operator must be the extended type. + The parameter of a unary operator must be the extended type. + + The type '{0}' may not be used for a field of a record. Тип "{0}" не может быть использован для поля записи. @@ -732,6 +752,11 @@ Дерево выражения не может содержать выражение коллекции. + + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + + An expression tree may not contain an extension property access An expression tree may not contain an extension property access @@ -1102,6 +1127,16 @@ '{0}': cannot declare instance members in an extension block with an unnamed receiver parameter + + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + + + + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + + Instance properties in interfaces cannot have initializers. Свойства экземпляра в интерфейсах не могут иметь инициализаторы. @@ -1557,6 +1592,11 @@ Доступ к встроенному массиву может не иметь спецификатора именованного аргумента. + + Extension members are not allowed as an argument to 'nameof'. + Extension members are not allowed as an argument to 'nameof'. + + The 'new()' constraint cannot be used with the 'unmanaged' constraint Ограничение "new()" невозможно использовать вместе с ограничением "unmanaged" @@ -1697,6 +1737,11 @@ Невозможно объявить определяемый пользователем оператор "{0}" как проверенный + + An extension block extending a static class cannot contain user-defined operators + An extension block extending a static class cannot contain user-defined operators + + '{0}': cannot override inherited member '{1}' because one of them is not an operator. '{0}': cannot override inherited member '{1}' because one of them is not an operator. @@ -7603,7 +7648,7 @@ If such a class is used as a base class and if the deriving class defines a dest Предопределенный тип "{0}" не определен или не импортирован - + Predefined type '{0}' is declared in multiple referenced assemblies: '{1}' and '{2}' Предопределенный тип "{0}" объявлен в нескольких сборках, на которые имеются ссылки: "{1}" и "{2}" @@ -7919,8 +7964,8 @@ If such a class is used as a base class and if the deriving class defines a dest - The DllImport attribute must be specified on a method marked 'static' and 'extern' - Атрибут DllImport должен быть указан для метода, который помечен как "static" и "extern". + The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member + Атрибут DllImport должен быть указан для метода, который помечен как "static" и "extern". diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.tr.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.tr.xlf index 94b142d48f3c6..723b083a6944f 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.tr.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.tr.xlf @@ -227,11 +227,31 @@ Zaman uyumsuz bir foreach içinde dinamik tür koleksiyonu oluşturulamaz + + One of the parameters of a binary operator must be the extended type. + One of the parameters of a binary operator must be the extended type. + + Extensions must be declared in a top-level, non-generic, static class Extensions must be declared in a top-level, non-generic, static class + + The parameter type for ++ or -- operator must be the extended type. + The parameter type for ++ or -- operator must be the extended type. + + + + The first operand of an overloaded shift operator must have the same type as the extended type + The first operand of an overloaded shift operator must have the same type as the extended type + + + + The parameter of a unary operator must be the extended type. + The parameter of a unary operator must be the extended type. + + The type '{0}' may not be used for a field of a record. '{0}' türü, kayıt alanı için kullanılamaz. @@ -732,6 +752,11 @@ İfade ağacı bir koleksiyon ifadesi içermeyebilir. + + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + + An expression tree may not contain an extension property access An expression tree may not contain an extension property access @@ -1102,6 +1127,16 @@ '{0}': cannot declare instance members in an extension block with an unnamed receiver parameter + + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + + + + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + + Instance properties in interfaces cannot have initializers. Arabirimlerdeki örnek özelliklerinin başlatıcıları olamaz. @@ -1557,6 +1592,11 @@ Satır içi dizi erişiminin adlandırılmış bağımsız değişken belirticisi olamaz + + Extension members are not allowed as an argument to 'nameof'. + Extension members are not allowed as an argument to 'nameof'. + + The 'new()' constraint cannot be used with the 'unmanaged' constraint 'new()' kısıtlaması, 'unmanaged' kısıtlamasıyla kullanılamaz @@ -1697,6 +1737,11 @@ Kullanıcı tanımlı '{0}' işleci işaretlenmiş olarak bildirilemiyor + + An extension block extending a static class cannot contain user-defined operators + An extension block extending a static class cannot contain user-defined operators + + '{0}': cannot override inherited member '{1}' because one of them is not an operator. '{0}': cannot override inherited member '{1}' because one of them is not an operator. @@ -7602,7 +7647,7 @@ Bu sınıf temel sınıf olarak kullanılırsa ve türetilen sınıf bir yıkıc Önceden tanımlanmış '{0}' türü tanımlanmamış veya içeri aktarılmamış - + Predefined type '{0}' is declared in multiple referenced assemblies: '{1}' and '{2}' Önceden tanımlı '{0}' türü birden çok başvurulan bütünleştirilmiş kodda bildirildi: '{1}' ve '{2}' @@ -7918,8 +7963,8 @@ Bu sınıf temel sınıf olarak kullanılırsa ve türetilen sınıf bir yıkıc - The DllImport attribute must be specified on a method marked 'static' and 'extern' - DllImport özniteliği 'static' ve 'extern' olarak işaretlenmiş bir yöntem üzerinde belirtilmelidir + The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member + DllImport özniteliği 'static' ve 'extern' olarak işaretlenmiş bir yöntem üzerinde belirtilmelidir diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.zh-Hans.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.zh-Hans.xlf index 5517f41b81002..063e9ed2efbee 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.zh-Hans.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.zh-Hans.xlf @@ -227,11 +227,31 @@ 无法在异步 foreach 中使用动态类型集合 + + One of the parameters of a binary operator must be the extended type. + One of the parameters of a binary operator must be the extended type. + + Extensions must be declared in a top-level, non-generic, static class Extensions must be declared in a top-level, non-generic, static class + + The parameter type for ++ or -- operator must be the extended type. + The parameter type for ++ or -- operator must be the extended type. + + + + The first operand of an overloaded shift operator must have the same type as the extended type + The first operand of an overloaded shift operator must have the same type as the extended type + + + + The parameter of a unary operator must be the extended type. + The parameter of a unary operator must be the extended type. + + The type '{0}' may not be used for a field of a record. 类型“{0}”不能用于记录的字段。 @@ -732,6 +752,11 @@ 表达式树不能包含集合表达式。 + + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + + An expression tree may not contain an extension property access An expression tree may not contain an extension property access @@ -1102,6 +1127,16 @@ '{0}': cannot declare instance members in an extension block with an unnamed receiver parameter + + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + + + + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + + Instance properties in interfaces cannot have initializers. 接口中的实例属性不能具有初始值设定项。 @@ -1557,6 +1592,11 @@ 内联数组访问可能没有命名参数说明符 + + Extension members are not allowed as an argument to 'nameof'. + Extension members are not allowed as an argument to 'nameof'. + + The 'new()' constraint cannot be used with the 'unmanaged' constraint "new()" 约束不能与 "unmanaged" 约束一起使用 @@ -1697,6 +1737,11 @@ 用户定义的运算符 '{0}' 无法声明为已验证 + + An extension block extending a static class cannot contain user-defined operators + An extension block extending a static class cannot contain user-defined operators + + '{0}': cannot override inherited member '{1}' because one of them is not an operator. '{0}': cannot override inherited member '{1}' because one of them is not an operator. @@ -7602,7 +7647,7 @@ If such a class is used as a base class and if the deriving class defines a dest 预定义类型“{0}”未定义或导入 - + Predefined type '{0}' is declared in multiple referenced assemblies: '{1}' and '{2}' 已在多个引用的程序集(“{1}”和“{2}”)中声明了预定义类型“{0}” @@ -7918,8 +7963,8 @@ If such a class is used as a base class and if the deriving class defines a dest - The DllImport attribute must be specified on a method marked 'static' and 'extern' - 必须在标记为 "static" 和 "extern" 的方法上指定 DllImport 特性 + The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member + 必须在标记为 "static" 和 "extern" 的方法上指定 DllImport 特性 diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.zh-Hant.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.zh-Hant.xlf index 44853d257d6f1..9c6611cb4bf88 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.zh-Hant.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.zh-Hant.xlf @@ -227,11 +227,31 @@ 無法在非同步 foreach 中使用動態類型的集合 + + One of the parameters of a binary operator must be the extended type. + One of the parameters of a binary operator must be the extended type. + + Extensions must be declared in a top-level, non-generic, static class Extensions must be declared in a top-level, non-generic, static class + + The parameter type for ++ or -- operator must be the extended type. + The parameter type for ++ or -- operator must be the extended type. + + + + The first operand of an overloaded shift operator must have the same type as the extended type + The first operand of an overloaded shift operator must have the same type as the extended type + + + + The parameter of a unary operator must be the extended type. + The parameter of a unary operator must be the extended type. + + The type '{0}' may not be used for a field of a record. 類型 '{0}' 不可用於記錄的欄位。 @@ -732,6 +752,11 @@ 運算式樹狀架構不得包含集合運算式。 + + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + + An expression tree may not contain an extension property access An expression tree may not contain an extension property access @@ -1102,6 +1127,16 @@ '{0}': cannot declare instance members in an extension block with an unnamed receiver parameter + + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + + + + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + + Instance properties in interfaces cannot have initializers. 介面中的執行個體屬性不可有初始設定式。 @@ -1557,6 +1592,11 @@ 內嵌陣列存取不能有具名引數指定名稱 + + Extension members are not allowed as an argument to 'nameof'. + Extension members are not allowed as an argument to 'nameof'. + + The 'new()' constraint cannot be used with the 'unmanaged' constraint new()' 條件約束不能和 'unmanaged' 條件約束一起使用 @@ -1697,6 +1737,11 @@ 使用者定義的運算子 '{0}' 無法宣告為已檢查 + + An extension block extending a static class cannot contain user-defined operators + An extension block extending a static class cannot contain user-defined operators + + '{0}': cannot override inherited member '{1}' because one of them is not an operator. '{0}': cannot override inherited member '{1}' because one of them is not an operator. @@ -7602,7 +7647,7 @@ If such a class is used as a base class and if the deriving class defines a dest 未定義或匯入預先定義的類型 '{0}' - + Predefined type '{0}' is declared in multiple referenced assemblies: '{1}' and '{2}' 在多個參考組件中宣告了預先定義的類型 '{0}': '{1}' 與 '{2}' @@ -7918,8 +7963,8 @@ If such a class is used as a base class and if the deriving class defines a dest - The DllImport attribute must be specified on a method marked 'static' and 'extern' - DllImport 屬性必須指定在標記為 'static' 和 'extern' 的方法上 + The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member + DllImport 屬性必須指定在標記為 'static' 和 'extern' 的方法上 diff --git a/src/Compilers/CSharp/Test/CommandLine/CommandLineTests.cs b/src/Compilers/CSharp/Test/CommandLine/CommandLineTests.cs index c064d59fca859..f873604e966d7 100644 --- a/src/Compilers/CSharp/Test/CommandLine/CommandLineTests.cs +++ b/src/Compilers/CSharp/Test/CommandLine/CommandLineTests.cs @@ -8630,7 +8630,7 @@ public static int Main() CleanupAllGeneratedFiles(source); } - [Fact(), WorkItem(546025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546025")] + [ConditionalFact(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/79351"), WorkItem(546025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546025")] public void TestWin32ResWithBadResFile_CS1583ERR_BadWin32Res_01() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Test { static void Main() {} }").Path; @@ -11506,16 +11506,16 @@ public void PathMapParser() parsedArgs = DefaultParse(new[] { "/pathmap:K1=V1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); - Assert.Equal(KeyValuePairUtil.Create("K1" + s, "V1" + s), parsedArgs.PathMap[0]); + Assert.Equal(KeyValuePair.Create("K1" + s, "V1" + s), parsedArgs.PathMap[0]); parsedArgs = DefaultParse(new[] { $"/pathmap:abc{s}=/", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); - Assert.Equal(KeyValuePairUtil.Create("abc" + s, "/"), parsedArgs.PathMap[0]); + Assert.Equal(KeyValuePair.Create("abc" + s, "/"), parsedArgs.PathMap[0]); parsedArgs = DefaultParse(new[] { "/pathmap:K1=V1,K2=V2", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); - Assert.Equal(KeyValuePairUtil.Create("K1" + s, "V1" + s), parsedArgs.PathMap[0]); - Assert.Equal(KeyValuePairUtil.Create("K2" + s, "V2" + s), parsedArgs.PathMap[1]); + Assert.Equal(KeyValuePair.Create("K1" + s, "V1" + s), parsedArgs.PathMap[0]); + Assert.Equal(KeyValuePair.Create("K2" + s, "V2" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { "/pathmap:,", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); @@ -11548,28 +11548,28 @@ public void PathMapParser() parsedArgs = DefaultParse(new[] { "/pathmap:\"supporting spaces=is hard\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); - Assert.Equal(KeyValuePairUtil.Create("supporting spaces" + s, "is hard" + s), parsedArgs.PathMap[0]); + Assert.Equal(KeyValuePair.Create("supporting spaces" + s, "is hard" + s), parsedArgs.PathMap[0]); parsedArgs = DefaultParse(new[] { "/pathmap:\"K 1=V 1\",\"K 2=V 2\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); - Assert.Equal(KeyValuePairUtil.Create("K 1" + s, "V 1" + s), parsedArgs.PathMap[0]); - Assert.Equal(KeyValuePairUtil.Create("K 2" + s, "V 2" + s), parsedArgs.PathMap[1]); + Assert.Equal(KeyValuePair.Create("K 1" + s, "V 1" + s), parsedArgs.PathMap[0]); + Assert.Equal(KeyValuePair.Create("K 2" + s, "V 2" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { "/pathmap:\"K 1\"=\"V 1\",\"K 2\"=\"V 2\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); - Assert.Equal(KeyValuePairUtil.Create("K 1" + s, "V 1" + s), parsedArgs.PathMap[0]); - Assert.Equal(KeyValuePairUtil.Create("K 2" + s, "V 2" + s), parsedArgs.PathMap[1]); + Assert.Equal(KeyValuePair.Create("K 1" + s, "V 1" + s), parsedArgs.PathMap[0]); + Assert.Equal(KeyValuePair.Create("K 2" + s, "V 2" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { "/pathmap:\"a ==,,b\"=\"1,,== 2\",\"x ==,,y\"=\"3 4\",", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); - Assert.Equal(KeyValuePairUtil.Create("a =,b" + s, "1,= 2" + s), parsedArgs.PathMap[0]); - Assert.Equal(KeyValuePairUtil.Create("x =,y" + s, "3 4" + s), parsedArgs.PathMap[1]); + Assert.Equal(KeyValuePair.Create("a =,b" + s, "1,= 2" + s), parsedArgs.PathMap[0]); + Assert.Equal(KeyValuePair.Create("x =,y" + s, "3 4" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { @"/pathmap:C:\temp\=/_1/,C:\temp\a\=/_2/,C:\temp\a\b\=/_3/", "a.cs", @"a\b.cs", @"a\b\c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); - Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\a\b\", "/_3/"), parsedArgs.PathMap[0]); - Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\a\", "/_2/"), parsedArgs.PathMap[1]); - Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\", "/_1/"), parsedArgs.PathMap[2]); + Assert.Equal(KeyValuePair.Create(@"C:\temp\a\b\", "/_3/"), parsedArgs.PathMap[0]); + Assert.Equal(KeyValuePair.Create(@"C:\temp\a\", "/_2/"), parsedArgs.PathMap[1]); + Assert.Equal(KeyValuePair.Create(@"C:\temp\", "/_1/"), parsedArgs.PathMap[2]); } [Theory] @@ -12253,7 +12253,7 @@ public void MicrosoftDiaSymReaderNativeAltLoadPath() cscCopy, arguments + " /deterministic", workingDirectory: dir.Path, - additionalEnvironmentVars: new[] { KeyValuePairUtil.Create("MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH", "") }); + additionalEnvironmentVars: new[] { KeyValuePair.Create("MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH", "") }); AssertEx.AssertEqualToleratingWhitespaceDifferences( "error CS0041: Unexpected error writing debug information -- 'Unable to load DLL 'Microsoft.DiaSymReader.Native.amd64.dll': " + @@ -12268,7 +12268,7 @@ public void MicrosoftDiaSymReaderNativeAltLoadPath() cscCopy, arguments + " /deterministic", workingDirectory: dir.Path, - additionalEnvironmentVars: new[] { KeyValuePairUtil.Create("MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH", cscDir) }); + additionalEnvironmentVars: new[] { KeyValuePair.Create("MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH", cscDir) }); Assert.Equal("", result.Output.Trim()); } diff --git a/src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenAsyncIteratorTests.cs b/src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenAsyncIteratorTests.cs index 5478059d72df6..6b49e879285a3 100644 --- a/src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenAsyncIteratorTests.cs +++ b/src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenAsyncIteratorTests.cs @@ -10,9 +10,11 @@ using System.Runtime.CompilerServices; using System.Text; using Basic.Reference.Assemblies; +using Microsoft.CodeAnalysis.CSharp.DynamicAnalysis.UnitTests; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; +using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; @@ -10855,5 +10857,257 @@ static void validate(ModuleSymbol m) m.GlobalNamespace.GetMember("Test1.d__0.<>3__x").GetAttributes().Select(a => a.ToString())); } } + + [Fact] + [WorkItem(78640, "https://github.com/dotnet/roslyn/issues/78640")] + public void Repro_78640() + { + var source = """ + using System.Collections.Generic; + using System.Runtime.CompilerServices; + using System.Threading; + using System; + + static class C + { + #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously + public static async IAsyncEnumerable AsAsyncEnumerable(this IEnumerable enumerable, [EnumeratorCancellation] CancellationToken cancellationToken) + #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously + { + ArgumentNullException.ThrowIfNull(enumerable); + + cancellationToken.ThrowIfCancellationRequested(); + foreach (T item in enumerable) + { + yield return item; + cancellationToken.ThrowIfCancellationRequested(); + } + } + } + """; + + var verifier = CompileAndVerify( + [source, DynamicAnalysisResourceTests.InstrumentationHelperSource], + targetFramework: TargetFramework.NetCoreApp, + emitOptions: EmitOptions.Default.WithInstrumentationKinds([InstrumentationKind.TestCoverage]), + verify: Verification.Skipped); + verifier.VerifyDiagnostics(); + verifier.VerifyIL("C.d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", """ + { + // Code size 518 (0x206) + .maxstack 6 + .locals init (int V_0, + T V_1, //item + System.Exception V_2) + IL_0000: ldarg.0 + IL_0001: ldfld "int C.d__0.<>1__state" + IL_0006: stloc.0 + .try + { + IL_0007: ldloc.0 + IL_0008: ldc.i4.s -4 + IL_000a: beq IL_00b4 + IL_000f: ldloc.0 + IL_0010: ldc.i4.s -3 + IL_0012: pop + IL_0013: pop + IL_0014: ldarg.0 + IL_0015: ldfld "bool C.d__0.<>w__disposeMode" + IL_001a: brfalse.s IL_0021 + IL_001c: leave IL_01a5 + IL_0021: ldarg.0 + IL_0022: ldc.i4.m1 + IL_0023: dup + IL_0024: stloc.0 + IL_0025: stfld "int C.d__0.<>1__state" + IL_002a: ldarg.0 + IL_002b: ldsfld "bool[][] .PayloadRoot0" + IL_0030: ldtoken "System.Collections.Generic.IAsyncEnumerable C.AsAsyncEnumerable(System.Collections.Generic.IEnumerable, System.Threading.CancellationToken)" + IL_0035: ldelem.ref + IL_0036: stfld "bool[] C.d__0.<>7__wrap1" + IL_003b: ldarg.0 + IL_003c: ldfld "bool[] C.d__0.<>7__wrap1" + IL_0041: brtrue.s IL_006d + IL_0043: ldarg.0 + IL_0044: ldsfld "System.Guid .MVID" + IL_0049: ldtoken "System.Collections.Generic.IAsyncEnumerable C.AsAsyncEnumerable(System.Collections.Generic.IEnumerable, System.Threading.CancellationToken)" + IL_004e: ldtoken Source Document 0 + IL_0053: ldsfld "bool[][] .PayloadRoot0" + IL_0058: ldtoken "System.Collections.Generic.IAsyncEnumerable C.AsAsyncEnumerable(System.Collections.Generic.IEnumerable, System.Threading.CancellationToken)" + IL_005d: ldelema "bool[]" + IL_0062: ldc.i4.6 + IL_0063: call "bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)" + IL_0068: stfld "bool[] C.d__0.<>7__wrap1" + IL_006d: ldarg.0 + IL_006e: ldfld "bool[] C.d__0.<>7__wrap1" + IL_0073: ldc.i4.0 + IL_0074: ldc.i4.1 + IL_0075: stelem.i1 + IL_0076: ldarg.0 + IL_0077: ldfld "bool[] C.d__0.<>7__wrap1" + IL_007c: ldc.i4.1 + IL_007d: ldc.i4.1 + IL_007e: stelem.i1 + IL_007f: ldarg.0 + IL_0080: ldfld "System.Collections.Generic.IEnumerable C.d__0.enumerable" + IL_0085: ldstr "enumerable" + IL_008a: call "void System.ArgumentNullException.ThrowIfNull(object, string)" + IL_008f: ldarg.0 + IL_0090: ldfld "bool[] C.d__0.<>7__wrap1" + IL_0095: ldc.i4.2 + IL_0096: ldc.i4.1 + IL_0097: stelem.i1 + IL_0098: ldarg.0 + IL_0099: ldflda "System.Threading.CancellationToken C.d__0.cancellationToken" + IL_009e: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + IL_00a3: ldarg.0 + IL_00a4: ldarg.0 + IL_00a5: ldfld "System.Collections.Generic.IEnumerable C.d__0.enumerable" + IL_00aa: callvirt "System.Collections.Generic.IEnumerator System.Collections.Generic.IEnumerable.GetEnumerator()" + IL_00af: stfld "System.Collections.Generic.IEnumerator C.d__0.<>7__wrap2" + IL_00b4: nop + .try + { + IL_00b5: ldloc.0 + IL_00b6: ldc.i4.s -4 + IL_00b8: beq.s IL_00f0 + IL_00ba: br.s IL_0115 + IL_00bc: ldarg.0 + IL_00bd: ldfld "bool[] C.d__0.<>7__wrap1" + IL_00c2: ldc.i4.5 + IL_00c3: ldc.i4.1 + IL_00c4: stelem.i1 + IL_00c5: ldarg.0 + IL_00c6: ldfld "System.Collections.Generic.IEnumerator C.d__0.<>7__wrap2" + IL_00cb: callvirt "T System.Collections.Generic.IEnumerator.Current.get" + IL_00d0: stloc.1 + IL_00d1: ldarg.0 + IL_00d2: ldfld "bool[] C.d__0.<>7__wrap1" + IL_00d7: ldc.i4.3 + IL_00d8: ldc.i4.1 + IL_00d9: stelem.i1 + IL_00da: ldarg.0 + IL_00db: ldloc.1 + IL_00dc: stfld "T C.d__0.<>2__current" + IL_00e1: ldarg.0 + IL_00e2: ldc.i4.s -4 + IL_00e4: dup + IL_00e5: stloc.0 + IL_00e6: stfld "int C.d__0.<>1__state" + IL_00eb: leave IL_01f9 + IL_00f0: ldarg.0 + IL_00f1: ldc.i4.m1 + IL_00f2: dup + IL_00f3: stloc.0 + IL_00f4: stfld "int C.d__0.<>1__state" + IL_00f9: ldarg.0 + IL_00fa: ldfld "bool C.d__0.<>w__disposeMode" + IL_00ff: brtrue.s IL_0122 + IL_0101: ldarg.0 + IL_0102: ldfld "bool[] C.d__0.<>7__wrap1" + IL_0107: ldc.i4.4 + IL_0108: ldc.i4.1 + IL_0109: stelem.i1 + IL_010a: ldarg.0 + IL_010b: ldflda "System.Threading.CancellationToken C.d__0.cancellationToken" + IL_0110: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + IL_0115: ldarg.0 + IL_0116: ldfld "System.Collections.Generic.IEnumerator C.d__0.<>7__wrap2" + IL_011b: callvirt "bool System.Collections.IEnumerator.MoveNext()" + IL_0120: brtrue.s IL_00bc + IL_0122: leave.s IL_013c + } + finally + { + IL_0124: ldloc.0 + IL_0125: ldc.i4.m1 + IL_0126: bne.un.s IL_013b + IL_0128: ldarg.0 + IL_0129: ldfld "System.Collections.Generic.IEnumerator C.d__0.<>7__wrap2" + IL_012e: brfalse.s IL_013b + IL_0130: ldarg.0 + IL_0131: ldfld "System.Collections.Generic.IEnumerator C.d__0.<>7__wrap2" + IL_0136: callvirt "void System.IDisposable.Dispose()" + IL_013b: endfinally + } + IL_013c: ldarg.0 + IL_013d: ldfld "bool C.d__0.<>w__disposeMode" + IL_0142: brfalse.s IL_0146 + IL_0144: leave.s IL_01a5 + IL_0146: ldarg.0 + IL_0147: ldnull + IL_0148: stfld "System.Collections.Generic.IEnumerator C.d__0.<>7__wrap2" + IL_014d: leave.s IL_01a5 + } + catch System.Exception + { + IL_014f: stloc.2 + IL_0150: ldarg.0 + IL_0151: ldc.i4.s -2 + IL_0153: stfld "int C.d__0.<>1__state" + IL_0158: ldarg.0 + IL_0159: ldnull + IL_015a: stfld "bool[] C.d__0.<>7__wrap1" + IL_015f: ldarg.0 + IL_0160: ldnull + IL_0161: stfld "System.Collections.Generic.IEnumerator C.d__0.<>7__wrap2" + IL_0166: ldarg.0 + IL_0167: ldfld "System.Threading.CancellationTokenSource C.d__0.<>x__combinedTokens" + IL_016c: brfalse.s IL_0180 + IL_016e: ldarg.0 + IL_016f: ldfld "System.Threading.CancellationTokenSource C.d__0.<>x__combinedTokens" + IL_0174: callvirt "void System.Threading.CancellationTokenSource.Dispose()" + IL_0179: ldarg.0 + IL_017a: ldnull + IL_017b: stfld "System.Threading.CancellationTokenSource C.d__0.<>x__combinedTokens" + IL_0180: ldarg.0 + IL_0181: ldflda "T C.d__0.<>2__current" + IL_0186: initobj "T" + IL_018c: ldarg.0 + IL_018d: ldflda "System.Runtime.CompilerServices.AsyncIteratorMethodBuilder C.d__0.<>t__builder" + IL_0192: call "void System.Runtime.CompilerServices.AsyncIteratorMethodBuilder.Complete()" + IL_0197: ldarg.0 + IL_0198: ldflda "System.Threading.Tasks.Sources.ManualResetValueTaskSourceCore C.d__0.<>v__promiseOfValueOrEnd" + IL_019d: ldloc.2 + IL_019e: call "void System.Threading.Tasks.Sources.ManualResetValueTaskSourceCore.SetException(System.Exception)" + IL_01a3: leave.s IL_0205 + } + IL_01a5: ldarg.0 + IL_01a6: ldc.i4.s -2 + IL_01a8: stfld "int C.d__0.<>1__state" + IL_01ad: ldarg.0 + IL_01ae: ldnull + IL_01af: stfld "bool[] C.d__0.<>7__wrap1" + IL_01b4: ldarg.0 + IL_01b5: ldnull + IL_01b6: stfld "System.Collections.Generic.IEnumerator C.d__0.<>7__wrap2" + IL_01bb: ldarg.0 + IL_01bc: ldfld "System.Threading.CancellationTokenSource C.d__0.<>x__combinedTokens" + IL_01c1: brfalse.s IL_01d5 + IL_01c3: ldarg.0 + IL_01c4: ldfld "System.Threading.CancellationTokenSource C.d__0.<>x__combinedTokens" + IL_01c9: callvirt "void System.Threading.CancellationTokenSource.Dispose()" + IL_01ce: ldarg.0 + IL_01cf: ldnull + IL_01d0: stfld "System.Threading.CancellationTokenSource C.d__0.<>x__combinedTokens" + IL_01d5: ldarg.0 + IL_01d6: ldflda "T C.d__0.<>2__current" + IL_01db: initobj "T" + IL_01e1: ldarg.0 + IL_01e2: ldflda "System.Runtime.CompilerServices.AsyncIteratorMethodBuilder C.d__0.<>t__builder" + IL_01e7: call "void System.Runtime.CompilerServices.AsyncIteratorMethodBuilder.Complete()" + IL_01ec: ldarg.0 + IL_01ed: ldflda "System.Threading.Tasks.Sources.ManualResetValueTaskSourceCore C.d__0.<>v__promiseOfValueOrEnd" + IL_01f2: ldc.i4.0 + IL_01f3: call "void System.Threading.Tasks.Sources.ManualResetValueTaskSourceCore.SetResult(bool)" + IL_01f8: ret + IL_01f9: ldarg.0 + IL_01fa: ldflda "System.Threading.Tasks.Sources.ManualResetValueTaskSourceCore C.d__0.<>v__promiseOfValueOrEnd" + IL_01ff: ldc.i4.1 + IL_0200: call "void System.Threading.Tasks.Sources.ManualResetValueTaskSourceCore.SetResult(bool)" + IL_0205: ret + } + """); + } } } diff --git a/src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenOverridingAndHiding.cs b/src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenOverridingAndHiding.cs index 5b7dedd7554d8..5eb58c48d9361 100644 --- a/src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenOverridingAndHiding.cs +++ b/src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenOverridingAndHiding.cs @@ -4126,7 +4126,7 @@ static void Main() if (isFromMetadata) { VerifyParamArrayAttribute(parameterB); - }; + } }; var verifier = CompileAndVerify(source, symbolValidator: validator(true), sourceSymbolValidator: validator(false), expectedOutput: @"System.Int32[]"); diff --git a/src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenTupleTest.cs b/src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenTupleTest.cs index 37e621fc00955..cf2c3915c8926 100644 --- a/src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenTupleTest.cs +++ b/src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenTupleTest.cs @@ -4320,7 +4320,7 @@ public static void Main() comp.VerifyDiagnostics( // (6,17): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // var x = (1, 1); - Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, 1)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 17) + Diagnostic(ErrorCode.ERR_PredefinedTypeAmbiguous, "(1, 1)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 17) ); } @@ -4343,10 +4343,10 @@ public static void Main() comp.VerifyDiagnostics( // (6,9): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // (int, int) x = (1, 1); - Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(int, int)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 9), + Diagnostic(ErrorCode.ERR_PredefinedTypeAmbiguous, "(int, int)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 9), // (6,24): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // (int, int) x = (1, 1); - Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, 1)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 24) + Diagnostic(ErrorCode.ERR_PredefinedTypeAmbiguous, "(1, 1)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 24) ); } @@ -4368,7 +4368,7 @@ public void M((int, int) x) { } comp.VerifyDiagnostics( // (4,19): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // public void M((int, int) x) { } - Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(int, int)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(4, 19) + Diagnostic(ErrorCode.ERR_PredefinedTypeAmbiguous, "(int, int)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(4, 19) ); } @@ -5525,7 +5525,7 @@ public static void Main() comp.VerifyDiagnostics( // (7,14): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // x.M1((1, 1)); - Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, 1)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 14) + Diagnostic(ErrorCode.ERR_PredefinedTypeAmbiguous, "(1, 1)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 14) ); comp = CreateCompilationWithMscorlib40(source, @@ -16796,7 +16796,7 @@ public static void Main() comp.VerifyDiagnostics( // (6,17): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // var x = (1, 1); - Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, 1)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 17) + Diagnostic(ErrorCode.ERR_PredefinedTypeAmbiguous, "(1, 1)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 17) ); comp = CreateCompilationWithMscorlib40(source, @@ -16807,7 +16807,7 @@ public static void Main() comp.VerifyDiagnostics( // (6,17): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // var x = (1, 1); - Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, 1)").WithArguments("System.ValueTuple`2", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 17) + Diagnostic(ErrorCode.ERR_PredefinedTypeAmbiguous, "(1, 1)").WithArguments("System.ValueTuple`2", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 17) ); comp = CreateCompilationWithMscorlib40(source, @@ -16858,7 +16858,7 @@ public static void Main() comp.VerifyDiagnostics( // (6,16): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // "x".M1((1, null)); - Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, null)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 16) + Diagnostic(ErrorCode.ERR_PredefinedTypeAmbiguous, "(1, null)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 16) ); comp = CreateCompilationWithMscorlib40(source3, @@ -16930,10 +16930,10 @@ public static void Main() comp.VerifyDiagnostics( // (6,16): error CS8356: Predefined type 'System.ValueTuple`3' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // "x".M1((1, null, 1, null, 1, null, 1, null, 1, null)); - Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, null, 1, null, 1, null, 1, null, 1, null)").WithArguments("System.ValueTuple`3", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 16), + Diagnostic(ErrorCode.ERR_PredefinedTypeAmbiguous, "(1, null, 1, null, 1, null, 1, null, 1, null)").WithArguments("System.ValueTuple`3", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 16), // (6,16): error CS8356: Predefined type 'System.ValueTuple`8' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // "x".M1((1, null, 1, null, 1, null, 1, null, 1, null)); - Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, null, 1, null, 1, null, 1, null, 1, null)").WithArguments("System.ValueTuple`8", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 16) + Diagnostic(ErrorCode.ERR_PredefinedTypeAmbiguous, "(1, null, 1, null, 1, null, 1, null, 1, null)").WithArguments("System.ValueTuple`8", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 16) ); comp = CreateCompilationWithMscorlib40(source3, @@ -22398,7 +22398,7 @@ public static void Main() comp.VerifyDiagnostics( // (7,14): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // x.M1((1, 1)); - Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, 1)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 14) + Diagnostic(ErrorCode.ERR_PredefinedTypeAmbiguous, "(1, 1)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 14) ); } diff --git a/src/Compilers/CSharp/Test/Emit/CodeGen/GotoTest.cs b/src/Compilers/CSharp/Test/Emit/CodeGen/GotoTest.cs index 546e068951632..b209cff23fce5 100644 --- a/src/Compilers/CSharp/Test/Emit/CodeGen/GotoTest.cs +++ b/src/Compilers/CSharp/Test/Emit/CodeGen/GotoTest.cs @@ -4,6 +4,7 @@ #nullable disable +using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; @@ -1124,7 +1125,7 @@ public void LoadedFile() @"#load ""a.csx"" goto B; B: goto A;"; - var resolver = TestSourceReferenceResolver.Create(KeyValuePairUtil.Create("a.csx", sourceA)); + var resolver = TestSourceReferenceResolver.Create(KeyValuePair.Create("a.csx", sourceA)); var options = TestOptions.DebugDll.WithSourceReferenceResolver(resolver); var compilation = CreateCompilationWithMscorlib461(sourceB, options: options, parseOptions: TestOptions.Script); compilation.GetDiagnostics().Verify( diff --git a/src/Compilers/CSharp/Test/Emit/CodeGen/WinMdDelegateTests.cs b/src/Compilers/CSharp/Test/Emit/CodeGen/WinMdDelegateTests.cs index f5a6b14470f75..992b62c248d58 100644 --- a/src/Compilers/CSharp/Test/Emit/CodeGen/WinMdDelegateTests.cs +++ b/src/Compilers/CSharp/Test/Emit/CodeGen/WinMdDelegateTests.cs @@ -41,7 +41,7 @@ public void SimpleDelegateMembersTest(string ob, string cb) GetMember("voidDelegate").GetMembers().ToArray(); AssertEx.SetEqual(actualMembers.Select(s => s.Name), expectedMembers); - }; + } }; VerifyType verify = (winmd, expected) => diff --git a/src/Compilers/CSharp/Test/Emit/Emit/DynamicAnalysis/DynamicAnalysisResourceTests.cs b/src/Compilers/CSharp/Test/Emit/Emit/DynamicAnalysis/DynamicAnalysisResourceTests.cs index 4ef7056bb216e..072fa30ed81f1 100644 --- a/src/Compilers/CSharp/Test/Emit/Emit/DynamicAnalysis/DynamicAnalysisResourceTests.cs +++ b/src/Compilers/CSharp/Test/Emit/Emit/DynamicAnalysis/DynamicAnalysisResourceTests.cs @@ -20,7 +20,7 @@ namespace Microsoft.CodeAnalysis.CSharp.DynamicAnalysis.UnitTests { public class DynamicAnalysisResourceTests : CSharpTestBase { - const string InstrumentationHelperSource = @" + public const string InstrumentationHelperSource = @" namespace Microsoft.CodeAnalysis.Runtime { public static class Instrumentation diff --git a/src/Compilers/CSharp/Test/Emit/Emit/InAttributeModifierTests.cs b/src/Compilers/CSharp/Test/Emit/Emit/InAttributeModifierTests.cs index 85dab8e75c6d1..60ea480e8d200 100644 --- a/src/Compilers/CSharp/Test/Emit/Emit/InAttributeModifierTests.cs +++ b/src/Compilers/CSharp/Test/Emit/Emit/InAttributeModifierTests.cs @@ -4454,7 +4454,7 @@ public class Exception { } } "; - var corlibWithoutInAttributeRef = CreateEmptyCompilation(corlib_cs).EmitToImageReference(); + var corlibWithoutInAttributeRef = CreateEmptyCompilation(corlib_cs, assemblyName: "corlibWithoutInAttributeRef").EmitToImageReference(); var refCode = @" namespace System.Runtime.InteropServices @@ -4462,8 +4462,8 @@ namespace System.Runtime.InteropServices public class InAttribute {} }"; - var ref1 = CreateEmptyCompilation(refCode, references: new[] { corlibWithoutInAttributeRef }).EmitToImageReference(); - var ref2 = CreateEmptyCompilation(refCode, references: new[] { corlibWithoutInAttributeRef }).EmitToImageReference(); + var ref1 = CreateEmptyCompilation(refCode, references: new[] { corlibWithoutInAttributeRef }, assemblyName: "ref1").EmitToImageReference(); + var ref2 = CreateEmptyCompilation(refCode, references: new[] { corlibWithoutInAttributeRef }, assemblyName: "ref2").EmitToImageReference(); var user = @" public class Test @@ -4473,9 +4473,9 @@ public class Test CreateEmptyCompilation(user, references: new[] { ref1, ref2, corlibWithoutInAttributeRef }) .VerifyDiagnostics( - // (4,12): error CS0518: Predefined type 'System.Runtime.InteropServices.InAttribute' is not defined or imported + // (4,12): error CS8356: Predefined type 'System.Runtime.InteropServices.InAttribute' is declared in multiple referenced assemblies: 'ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // public ref readonly int M() => throw null; - Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "ref readonly int").WithArguments("System.Runtime.InteropServices.InAttribute").WithLocation(4, 12)); + Diagnostic(ErrorCode.ERR_PredefinedTypeAmbiguous, "ref readonly int").WithArguments("System.Runtime.InteropServices.InAttribute", "ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(4, 12)); } [Fact] diff --git a/src/Compilers/CSharp/Test/Emit2/CodeGen/CodeGenCallTests.cs b/src/Compilers/CSharp/Test/Emit2/CodeGen/CodeGenCallTests.cs index e65f4aca1a281..e46aa26e10165 100644 --- a/src/Compilers/CSharp/Test/Emit2/CodeGen/CodeGenCallTests.cs +++ b/src/Compilers/CSharp/Test/Emit2/CodeGen/CodeGenCallTests.cs @@ -21968,39 +21968,45 @@ .locals init (T V_0, verifier.VerifyIL("Program.Shift2", @" { - // Code size 77 (0x4d) + // Code size 83 (0x53) .maxstack 4 .locals init (T& V_0, - int V_1, - T V_2) + T V_1, + T& V_2, + int V_3, + T V_4) IL_0000: ldarga.s V_0 - IL_0002: stloc.0 - IL_0003: ldloc.0 - IL_0004: constrained. ""T"" - IL_000a: callvirt ""int IMoveable.Length.get"" - IL_000f: ldc.i4.1 - IL_0010: sub - IL_0011: stloc.1 - IL_0012: ldloc.0 - IL_0013: ldloca.s V_2 - IL_0015: initobj ""T"" - IL_001b: ldloc.2 - IL_001c: box ""T"" - IL_0021: brtrue.s IL_002b - IL_0023: ldobj ""T"" - IL_0028: stloc.2 - IL_0029: ldloca.s V_2 - IL_002b: ldloc.1 - IL_002c: ldloc.0 - IL_002d: ldloc.1 - IL_002e: constrained. ""T"" - IL_0034: callvirt ""int IMoveable.this[int].get"" - IL_0039: ldarga.s V_0 - IL_003b: call ""int Program.GetOffset(ref T)"" - IL_0040: add - IL_0041: constrained. ""T"" - IL_0047: callvirt ""void IMoveable.this[int].set"" - IL_004c: ret + IL_0002: stloc.2 + IL_0003: ldloca.s V_4 + IL_0005: initobj ""T"" + IL_000b: ldloc.s V_4 + IL_000d: box ""T"" + IL_0012: brtrue.s IL_001f + IL_0014: ldloc.2 + IL_0015: ldobj ""T"" + IL_001a: stloc.1 + IL_001b: ldloca.s V_1 + IL_001d: br.s IL_0020 + IL_001f: ldloc.2 + IL_0020: stloc.0 + IL_0021: ldloc.0 + IL_0022: constrained. ""T"" + IL_0028: callvirt ""int IMoveable.Length.get"" + IL_002d: ldc.i4.1 + IL_002e: sub + IL_002f: stloc.3 + IL_0030: ldloc.0 + IL_0031: ldloc.3 + IL_0032: ldloc.0 + IL_0033: ldloc.3 + IL_0034: constrained. ""T"" + IL_003a: callvirt ""int IMoveable.this[int].get"" + IL_003f: ldarga.s V_0 + IL_0041: call ""int Program.GetOffset(ref T)"" + IL_0046: add + IL_0047: constrained. ""T"" + IL_004d: callvirt ""void IMoveable.this[int].set"" + IL_0052: ret } "); @@ -22234,39 +22240,45 @@ .locals init (T V_0, verifier.VerifyIL("Program.Shift2", @" { - // Code size 75 (0x4b) + // Code size 81 (0x51) .maxstack 4 .locals init (T& V_0, - int V_1, - T V_2) + T V_1, + T& V_2, + int V_3, + T V_4) IL_0000: ldarg.0 - IL_0001: stloc.0 - IL_0002: ldloc.0 - IL_0003: constrained. ""T"" - IL_0009: callvirt ""int IMoveable.Length.get"" - IL_000e: ldc.i4.1 - IL_000f: sub - IL_0010: stloc.1 - IL_0011: ldloc.0 - IL_0012: ldloca.s V_2 - IL_0014: initobj ""T"" - IL_001a: ldloc.2 - IL_001b: box ""T"" - IL_0020: brtrue.s IL_002a - IL_0022: ldobj ""T"" - IL_0027: stloc.2 - IL_0028: ldloca.s V_2 - IL_002a: ldloc.1 - IL_002b: ldloc.0 - IL_002c: ldloc.1 - IL_002d: constrained. ""T"" - IL_0033: callvirt ""int IMoveable.this[int].get"" - IL_0038: ldarg.0 - IL_0039: call ""int Program.GetOffset(ref T)"" - IL_003e: add - IL_003f: constrained. ""T"" - IL_0045: callvirt ""void IMoveable.this[int].set"" - IL_004a: ret + IL_0001: stloc.2 + IL_0002: ldloca.s V_4 + IL_0004: initobj ""T"" + IL_000a: ldloc.s V_4 + IL_000c: box ""T"" + IL_0011: brtrue.s IL_001e + IL_0013: ldloc.2 + IL_0014: ldobj ""T"" + IL_0019: stloc.1 + IL_001a: ldloca.s V_1 + IL_001c: br.s IL_001f + IL_001e: ldloc.2 + IL_001f: stloc.0 + IL_0020: ldloc.0 + IL_0021: constrained. ""T"" + IL_0027: callvirt ""int IMoveable.Length.get"" + IL_002c: ldc.i4.1 + IL_002d: sub + IL_002e: stloc.3 + IL_002f: ldloc.0 + IL_0030: ldloc.3 + IL_0031: ldloc.0 + IL_0032: ldloc.3 + IL_0033: constrained. ""T"" + IL_0039: callvirt ""int IMoveable.this[int].get"" + IL_003e: ldarg.0 + IL_003f: call ""int Program.GetOffset(ref T)"" + IL_0044: add + IL_0045: constrained. ""T"" + IL_004b: callvirt ""void IMoveable.this[int].set"" + IL_0050: ret } "); @@ -22589,7 +22601,7 @@ .locals init (int V_0, verifier.VerifyIL("Program.d__2.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { - // Code size 311 (0x137) + // Code size 359 (0x167) .maxstack 4 .locals init (int V_0, int V_1, @@ -22603,112 +22615,128 @@ .locals init (int V_0, .try { IL_0007: ldloc.0 - IL_0008: brfalse IL_00a0 - IL_000d: ldarg.0 - IL_000e: ldflda ""T Program.d__2.item"" - IL_0013: constrained. ""T"" - IL_0019: callvirt ""int IMoveable.Length.get"" - IL_001e: ldc.i4.1 - IL_001f: sub - IL_0020: stloc.1 - IL_0021: ldloca.s V_3 - IL_0023: initobj ""T"" - IL_0029: ldloc.3 - IL_002a: box ""T"" - IL_002f: brtrue.s IL_003d - IL_0031: ldarg.0 - IL_0032: ldarg.0 - IL_0033: ldfld ""T Program.d__2.item"" - IL_0038: stfld ""T Program.d__2.<>7__wrap1"" - IL_003d: ldarg.0 - IL_003e: ldloc.1 - IL_003f: stfld ""int Program.d__2.<>7__wrap2"" - IL_0044: ldarg.0 - IL_0045: ldarg.0 - IL_0046: ldflda ""T Program.d__2.item"" - IL_004b: ldloc.1 - IL_004c: constrained. ""T"" - IL_0052: callvirt ""int IMoveable.this[int].get"" - IL_0057: stfld ""int Program.d__2.<>7__wrap3"" + IL_0008: brfalse IL_00d0 + IL_000d: ldloca.s V_3 + IL_000f: initobj ""T"" + IL_0015: ldloc.3 + IL_0016: box ""T"" + IL_001b: brtrue.s IL_0029 + IL_001d: ldarg.0 + IL_001e: ldarg.0 + IL_001f: ldfld ""T Program.d__2.item"" + IL_0024: stfld ""T Program.d__2.<>7__wrap1"" + IL_0029: ldloca.s V_3 + IL_002b: initobj ""T"" + IL_0031: ldloc.3 + IL_0032: box ""T"" + IL_0037: brtrue.s IL_0041 + IL_0039: ldarg.0 + IL_003a: ldflda ""T Program.d__2.<>7__wrap1"" + IL_003f: br.s IL_0047 + IL_0041: ldarg.0 + IL_0042: ldflda ""T Program.d__2.item"" + IL_0047: constrained. ""T"" + IL_004d: callvirt ""int IMoveable.Length.get"" + IL_0052: ldc.i4.1 + IL_0053: sub + IL_0054: stloc.1 + IL_0055: ldarg.0 + IL_0056: ldloc.1 + IL_0057: stfld ""int Program.d__2.<>7__wrap2"" IL_005c: ldarg.0 - IL_005d: ldflda ""T Program.d__2.item"" - IL_0062: call ""int Program.GetOffset(ref T)"" - IL_0067: call ""System.Threading.Tasks.Task Program.GetOffsetAsync(int)"" - IL_006c: callvirt ""System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()"" - IL_0071: stloc.s V_4 - IL_0073: ldloca.s V_4 - IL_0075: call ""bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get"" - IL_007a: brtrue.s IL_00bd - IL_007c: ldarg.0 - IL_007d: ldc.i4.0 - IL_007e: dup - IL_007f: stloc.0 - IL_0080: stfld ""int Program.d__2.<>1__state"" - IL_0085: ldarg.0 - IL_0086: ldloc.s V_4 - IL_0088: stfld ""System.Runtime.CompilerServices.TaskAwaiter Program.d__2.<>u__1"" - IL_008d: ldarg.0 - IL_008e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.d__2.<>t__builder"" - IL_0093: ldloca.s V_4 - IL_0095: ldarg.0 - IL_0096: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted, Program.d__2>(ref System.Runtime.CompilerServices.TaskAwaiter, ref Program.d__2)"" - IL_009b: leave IL_0136 - IL_00a0: ldarg.0 - IL_00a1: ldfld ""System.Runtime.CompilerServices.TaskAwaiter Program.d__2.<>u__1"" - IL_00a6: stloc.s V_4 - IL_00a8: ldarg.0 - IL_00a9: ldflda ""System.Runtime.CompilerServices.TaskAwaiter Program.d__2.<>u__1"" - IL_00ae: initobj ""System.Runtime.CompilerServices.TaskAwaiter"" - IL_00b4: ldarg.0 - IL_00b5: ldc.i4.m1 - IL_00b6: dup - IL_00b7: stloc.0 - IL_00b8: stfld ""int Program.d__2.<>1__state"" - IL_00bd: ldloca.s V_4 - IL_00bf: call ""int System.Runtime.CompilerServices.TaskAwaiter.GetResult()"" - IL_00c4: stloc.2 - IL_00c5: ldloca.s V_3 - IL_00c7: initobj ""T"" - IL_00cd: ldloc.3 - IL_00ce: box ""T"" - IL_00d3: brtrue.s IL_00dd - IL_00d5: ldarg.0 - IL_00d6: ldflda ""T Program.d__2.<>7__wrap1"" - IL_00db: br.s IL_00e3 - IL_00dd: ldarg.0 - IL_00de: ldflda ""T Program.d__2.item"" - IL_00e3: ldarg.0 - IL_00e4: ldfld ""int Program.d__2.<>7__wrap2"" - IL_00e9: ldarg.0 - IL_00ea: ldfld ""int Program.d__2.<>7__wrap3"" - IL_00ef: ldloc.2 - IL_00f0: add - IL_00f1: constrained. ""T"" - IL_00f7: callvirt ""void IMoveable.this[int].set"" - IL_00fc: ldarg.0 - IL_00fd: ldflda ""T Program.d__2.<>7__wrap1"" - IL_0102: initobj ""T"" - IL_0108: leave.s IL_0123 + IL_005d: ldloca.s V_3 + IL_005f: initobj ""T"" + IL_0065: ldloc.3 + IL_0066: box ""T"" + IL_006b: brtrue.s IL_0075 + IL_006d: ldarg.0 + IL_006e: ldflda ""T Program.d__2.<>7__wrap1"" + IL_0073: br.s IL_007b + IL_0075: ldarg.0 + IL_0076: ldflda ""T Program.d__2.item"" + IL_007b: ldloc.1 + IL_007c: constrained. ""T"" + IL_0082: callvirt ""int IMoveable.this[int].get"" + IL_0087: stfld ""int Program.d__2.<>7__wrap3"" + IL_008c: ldarg.0 + IL_008d: ldflda ""T Program.d__2.item"" + IL_0092: call ""int Program.GetOffset(ref T)"" + IL_0097: call ""System.Threading.Tasks.Task Program.GetOffsetAsync(int)"" + IL_009c: callvirt ""System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()"" + IL_00a1: stloc.s V_4 + IL_00a3: ldloca.s V_4 + IL_00a5: call ""bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get"" + IL_00aa: brtrue.s IL_00ed + IL_00ac: ldarg.0 + IL_00ad: ldc.i4.0 + IL_00ae: dup + IL_00af: stloc.0 + IL_00b0: stfld ""int Program.d__2.<>1__state"" + IL_00b5: ldarg.0 + IL_00b6: ldloc.s V_4 + IL_00b8: stfld ""System.Runtime.CompilerServices.TaskAwaiter Program.d__2.<>u__1"" + IL_00bd: ldarg.0 + IL_00be: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.d__2.<>t__builder"" + IL_00c3: ldloca.s V_4 + IL_00c5: ldarg.0 + IL_00c6: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted, Program.d__2>(ref System.Runtime.CompilerServices.TaskAwaiter, ref Program.d__2)"" + IL_00cb: leave IL_0166 + IL_00d0: ldarg.0 + IL_00d1: ldfld ""System.Runtime.CompilerServices.TaskAwaiter Program.d__2.<>u__1"" + IL_00d6: stloc.s V_4 + IL_00d8: ldarg.0 + IL_00d9: ldflda ""System.Runtime.CompilerServices.TaskAwaiter Program.d__2.<>u__1"" + IL_00de: initobj ""System.Runtime.CompilerServices.TaskAwaiter"" + IL_00e4: ldarg.0 + IL_00e5: ldc.i4.m1 + IL_00e6: dup + IL_00e7: stloc.0 + IL_00e8: stfld ""int Program.d__2.<>1__state"" + IL_00ed: ldloca.s V_4 + IL_00ef: call ""int System.Runtime.CompilerServices.TaskAwaiter.GetResult()"" + IL_00f4: stloc.2 + IL_00f5: ldloca.s V_3 + IL_00f7: initobj ""T"" + IL_00fd: ldloc.3 + IL_00fe: box ""T"" + IL_0103: brtrue.s IL_010d + IL_0105: ldarg.0 + IL_0106: ldflda ""T Program.d__2.<>7__wrap1"" + IL_010b: br.s IL_0113 + IL_010d: ldarg.0 + IL_010e: ldflda ""T Program.d__2.item"" + IL_0113: ldarg.0 + IL_0114: ldfld ""int Program.d__2.<>7__wrap2"" + IL_0119: ldarg.0 + IL_011a: ldfld ""int Program.d__2.<>7__wrap3"" + IL_011f: ldloc.2 + IL_0120: add + IL_0121: constrained. ""T"" + IL_0127: callvirt ""void IMoveable.this[int].set"" + IL_012c: ldarg.0 + IL_012d: ldflda ""T Program.d__2.<>7__wrap1"" + IL_0132: initobj ""T"" + IL_0138: leave.s IL_0153 } catch System.Exception { - IL_010a: stloc.s V_5 - IL_010c: ldarg.0 - IL_010d: ldc.i4.s -2 - IL_010f: stfld ""int Program.d__2.<>1__state"" - IL_0114: ldarg.0 - IL_0115: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.d__2.<>t__builder"" - IL_011a: ldloc.s V_5 - IL_011c: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" - IL_0121: leave.s IL_0136 + IL_013a: stloc.s V_5 + IL_013c: ldarg.0 + IL_013d: ldc.i4.s -2 + IL_013f: stfld ""int Program.d__2.<>1__state"" + IL_0144: ldarg.0 + IL_0145: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.d__2.<>t__builder"" + IL_014a: ldloc.s V_5 + IL_014c: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" + IL_0151: leave.s IL_0166 } - IL_0123: ldarg.0 - IL_0124: ldc.i4.s -2 - IL_0126: stfld ""int Program.d__2.<>1__state"" - IL_012b: ldarg.0 - IL_012c: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.d__2.<>t__builder"" - IL_0131: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" - IL_0136: ret + IL_0153: ldarg.0 + IL_0154: ldc.i4.s -2 + IL_0156: stfld ""int Program.d__2.<>1__state"" + IL_015b: ldarg.0 + IL_015c: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.d__2.<>t__builder"" + IL_0161: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" + IL_0166: ret } "); @@ -33505,5 +33533,2059 @@ .locals init (T V_0) "); CompileAndVerify(source, options: TestOptions.DebugExe, verify: Verification.Fails, expectedOutput: expectedOutput).VerifyDiagnostics(); } + + [Fact] + public void GenericTypeParameterAsReceiver_PropertyAccess_PrefixIncrementAssignment_01() + { + var src = """ +interface I1 +{ + public int P1 {get; set;} +} + +struct S1 : I1 +{ + public int F1; + + public int P1 + { + get + { + System.Console.Write(F1); + Program.F.F1++; + return 0; + } + set + { + System.Console.Write(F1); + } + } +} + +class Program +{ + public static S1 F; + + static void Main() + { + F = new S1 { F1 = 123 }; + Test1(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new S1 { F1 = 123 }; + Test2(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new S1 { F1 = 123 }; + Test3(ref F); + System.Console.Write(F.F1); + } + + static void Test1(ref T f) where T : I1 + { + ++f.P1; + } + + static void Test2(ref T f) where T : struct, I1 + { + ++f.P1; + } + + static void Test3(ref S1 f) + { + ++f.P1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "123124124:123124124:123124124").VerifyDiagnostics(); + } + + [Fact] + public void GenericTypeParameterAsReceiver_PropertyAccess_PrefixIncrementAssignment_02() + { + var src = """ +interface I1 +{ + public int P1 {get; set;} +} + +class C1 : I1 +{ + public int F1; + + public int P1 + { + get + { + System.Console.Write(F1); + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + return 0; + } + set + { + System.Console.Write(F1); + } + } +} + +class Program +{ + public static C1 F; + + static void Main() + { + F = new C1 { F1 = 123 }; + Test1(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + Test2(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + Test3(ref F); + System.Console.Write(F.F1); + } + + static void Test1(ref T f) where T : I1 + { + ++f.P1; + } + + static void Test2(ref T f) where T : class, I1 + { + ++f.P1; + } + + static void Test3(ref C1 f) + { + ++f.P1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + var verifier = CompileAndVerify(comp, expectedOutput: "123123124:123123124:123123124").VerifyDiagnostics(); + + verifier.VerifyIL("Program.Test1(ref T)", +@" +{ + // Code size 60 (0x3c) + .maxstack 3 + .locals init (T V_0, + T& V_1, + int V_2, + T V_3) + IL_0000: nop + IL_0001: ldarg.0 + IL_0002: stloc.1 + IL_0003: ldloca.s V_3 + IL_0005: initobj ""T"" + IL_000b: ldloc.3 + IL_000c: box ""T"" + IL_0011: brtrue.s IL_001e + IL_0013: ldloc.1 + IL_0014: ldobj ""T"" + IL_0019: stloc.0 + IL_001a: ldloca.s V_0 + IL_001c: br.s IL_001f + IL_001e: ldloc.1 + IL_001f: dup + IL_0020: constrained. ""T"" + IL_0026: callvirt ""int I1.P1.get"" + IL_002b: ldc.i4.1 + IL_002c: add + IL_002d: stloc.2 + IL_002e: ldloc.2 + IL_002f: constrained. ""T"" + IL_0035: callvirt ""void I1.P1.set"" + IL_003a: nop + IL_003b: ret +} +"); + + verifier.VerifyIL("Program.Test2(ref T)", +@" +{ + // Code size 39 (0x27) + .maxstack 3 + .locals init (T V_0, + int V_1) + IL_0000: nop + IL_0001: ldarg.0 + IL_0002: ldobj ""T"" + IL_0007: stloc.0 + IL_0008: ldloca.s V_0 + IL_000a: dup + IL_000b: constrained. ""T"" + IL_0011: callvirt ""int I1.P1.get"" + IL_0016: ldc.i4.1 + IL_0017: add + IL_0018: stloc.1 + IL_0019: ldloc.1 + IL_001a: constrained. ""T"" + IL_0020: callvirt ""void I1.P1.set"" + IL_0025: nop + IL_0026: ret +} +"); + } + + [Fact] + public void GenericTypeParameterAsReceiver_PropertyAccess_PostfixIncrementAssignment_01() + { + var src = """ +interface I1 +{ + public int P1 {get; set;} +} + +struct S1 : I1 +{ + public int F1; + + public int P1 + { + get + { + System.Console.Write(F1); + Program.F.F1++; + return 0; + } + set + { + System.Console.Write(F1); + } + } +} + +class Program +{ + public static S1 F; + + static void Main() + { + F = new S1 { F1 = 123 }; + Test1(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new S1 { F1 = 123 }; + Test2(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new S1 { F1 = 123 }; + Test3(ref F); + System.Console.Write(F.F1); + } + + static void Test1(ref T f) where T : I1 + { + f.P1++; + } + + static void Test2(ref T f) where T : struct, I1 + { + f.P1++; + } + + static void Test3(ref S1 f) + { + f.P1++; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "123124124:123124124:123124124").VerifyDiagnostics(); + } + + [Fact] + public void GenericTypeParameterAsReceiver_PropertyAccess_PostfixIncrementAssignment_02() + { + var src = """ +interface I1 +{ + public int P1 {get; set;} +} + +class C1 : I1 +{ + public int F1; + + public int P1 + { + get + { + System.Console.Write(F1); + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + return 0; + } + set + { + System.Console.Write(F1); + } + } +} + +class Program +{ + public static C1 F; + + static void Main() + { + F = new C1 { F1 = 123 }; + Test1(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + Test2(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + Test3(ref F); + System.Console.Write(F.F1); + } + + static void Test1(ref T f) where T : I1 + { + f.P1++; + } + + static void Test2(ref T f) where T : class, I1 + { + f.P1++; + } + + static void Test3(ref C1 f) + { + f.P1++; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + var verifier = CompileAndVerify(comp, expectedOutput: "123123124:123123124:123123124").VerifyDiagnostics(); + + verifier.VerifyIL("Program.Test1(ref T)", +@" +{ + // Code size 60 (0x3c) + .maxstack 3 + .locals init (T V_0, + T& V_1, + int V_2, + T V_3) + IL_0000: nop + IL_0001: ldarg.0 + IL_0002: stloc.1 + IL_0003: ldloca.s V_3 + IL_0005: initobj ""T"" + IL_000b: ldloc.3 + IL_000c: box ""T"" + IL_0011: brtrue.s IL_001e + IL_0013: ldloc.1 + IL_0014: ldobj ""T"" + IL_0019: stloc.0 + IL_001a: ldloca.s V_0 + IL_001c: br.s IL_001f + IL_001e: ldloc.1 + IL_001f: dup + IL_0020: constrained. ""T"" + IL_0026: callvirt ""int I1.P1.get"" + IL_002b: stloc.2 + IL_002c: ldloc.2 + IL_002d: ldc.i4.1 + IL_002e: add + IL_002f: constrained. ""T"" + IL_0035: callvirt ""void I1.P1.set"" + IL_003a: nop + IL_003b: ret +} +"); + + verifier.VerifyIL("Program.Test2(ref T)", +@" +{ + // Code size 39 (0x27) + .maxstack 3 + .locals init (T V_0, + int V_1) + IL_0000: nop + IL_0001: ldarg.0 + IL_0002: ldobj ""T"" + IL_0007: stloc.0 + IL_0008: ldloca.s V_0 + IL_000a: dup + IL_000b: constrained. ""T"" + IL_0011: callvirt ""int I1.P1.get"" + IL_0016: stloc.1 + IL_0017: ldloc.1 + IL_0018: ldc.i4.1 + IL_0019: add + IL_001a: constrained. ""T"" + IL_0020: callvirt ""void I1.P1.set"" + IL_0025: nop + IL_0026: ret +} +"); + } + + [Fact] + public void GenericTypeParameterAsReceiver_IndexerAccess_PrefixIncrementAssignment_01() + { + var src = """ +interface I1 +{ + public int this[int x] {get; set;} +} + +struct S1 : I1 +{ + public int F1; + + public int this[int x] + { + get + { + System.Console.Write(F1); + Program.F.F1++; + return 0; + } + set + { + System.Console.Write(F1); + } + } +} + +class Program +{ + public static S1 F; + + static void Main() + { + F = new S1 { F1 = 123 }; + Test1(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new S1 { F1 = 123 }; + Test2(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new S1 { F1 = 123 }; + Test3(ref F); + System.Console.Write(F.F1); + } + + static void Test1(ref T f) where T : I1 + { + ++f[0]; + } + + static void Test2(ref T f) where T : struct, I1 + { + ++f[0]; + } + + static void Test3(ref S1 f) + { + ++f[0]; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "123124124:123124124:123124124").VerifyDiagnostics(); + } + + [Fact] + public void GenericTypeParameterAsReceiver_IndexerAccess_PrefixIncrementAssignment_02() + { + var src = """ +interface I1 +{ + public int this[int x] {get; set;} +} + +class C1 : I1 +{ + public int F1; + + public int this[int x] + { + get + { + System.Console.Write(F1); + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + return 0; + } + set + { + System.Console.Write(F1); + } + } +} + +class Program +{ + public static C1 F; + + static void Main() + { + F = new C1 { F1 = 123 }; + Test1(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + Test2(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + Test3(ref F); + System.Console.Write(F.F1); + } + + static void Test1(ref T f) where T : I1 + { + ++f[0]; + } + + static void Test2(ref T f) where T : class, I1 + { + ++f[0]; + } + + static void Test3(ref C1 f) + { + ++f[0]; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + var verifier = CompileAndVerify(comp, expectedOutput: "123123124:123123124:123123124").VerifyDiagnostics(); + + verifier.VerifyIL("Program.Test1(ref T)", +@" +{ + // Code size 62 (0x3e) + .maxstack 3 + .locals init (T V_0, + T& V_1, + int V_2, + T V_3) + IL_0000: nop + IL_0001: ldarg.0 + IL_0002: stloc.1 + IL_0003: ldloca.s V_3 + IL_0005: initobj ""T"" + IL_000b: ldloc.3 + IL_000c: box ""T"" + IL_0011: brtrue.s IL_001e + IL_0013: ldloc.1 + IL_0014: ldobj ""T"" + IL_0019: stloc.0 + IL_001a: ldloca.s V_0 + IL_001c: br.s IL_001f + IL_001e: ldloc.1 + IL_001f: dup + IL_0020: ldc.i4.0 + IL_0021: constrained. ""T"" + IL_0027: callvirt ""int I1.this[int].get"" + IL_002c: ldc.i4.1 + IL_002d: add + IL_002e: stloc.2 + IL_002f: ldc.i4.0 + IL_0030: ldloc.2 + IL_0031: constrained. ""T"" + IL_0037: callvirt ""void I1.this[int].set"" + IL_003c: nop + IL_003d: ret +} +"); + + verifier.VerifyIL("Program.Test2(ref T)", +@" +{ + // Code size 41 (0x29) + .maxstack 3 + .locals init (T V_0, + int V_1) + IL_0000: nop + IL_0001: ldarg.0 + IL_0002: ldobj ""T"" + IL_0007: stloc.0 + IL_0008: ldloca.s V_0 + IL_000a: dup + IL_000b: ldc.i4.0 + IL_000c: constrained. ""T"" + IL_0012: callvirt ""int I1.this[int].get"" + IL_0017: ldc.i4.1 + IL_0018: add + IL_0019: stloc.1 + IL_001a: ldc.i4.0 + IL_001b: ldloc.1 + IL_001c: constrained. ""T"" + IL_0022: callvirt ""void I1.this[int].set"" + IL_0027: nop + IL_0028: ret +} +"); + } + + [Fact] + public void GenericTypeParameterAsReceiver_IndexerAccess_PrefixIncrementAssignment_03() + { + var src = """ +using System.Threading.Tasks; + +interface I1 +{ + public int this[int x] {get; set;} +} + +class C1 : I1 +{ + public int F1; + + public int this[int x] + { + get + { + System.Console.Write(F1); + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + return 0; + } + set + { + System.Console.Write(F1); + } + } +} + +class Program +{ + public static C1 F; + + static async Task Main() + { + F = new C1 { F1 = 123 }; + await Test1(); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + await Test2(); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + await Test3(); + System.Console.Write(F.F1); + } + + static async Task Test1() where T : I1 + { + ++F[await Get0()]; + } + + static async Task Test2() where T : class, I1 + { + ++F[await Get0()]; + } + + static async Task Test3() + { + ++F[await Get0()]; + } + + static async Task Get0() + { + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + await Task.Yield(); + return 0; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "123123125:123123125:123123125").VerifyDiagnostics(); + } + + [Fact] + public void GenericTypeParameterAsReceiver_IndexerAccess_PostfixIncrementAssignment_01() + { + var src = """ +interface I1 +{ + public int this[int x] {get; set;} +} + +struct S1 : I1 +{ + public int F1; + + public int this[int x] + { + get + { + System.Console.Write(F1); + Program.F.F1++; + return 0; + } + set + { + System.Console.Write(F1); + } + } +} + +class Program +{ + public static S1 F; + + static void Main() + { + F = new S1 { F1 = 123 }; + Test1(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new S1 { F1 = 123 }; + Test2(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new S1 { F1 = 123 }; + Test3(ref F); + System.Console.Write(F.F1); + } + + static void Test1(ref T f) where T : I1 + { + f[0]++; + } + + static void Test2(ref T f) where T : struct, I1 + { + f[0]++; + } + + static void Test3(ref S1 f) + { + f[0]++; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "123124124:123124124:123124124").VerifyDiagnostics(); + } + + [Fact] + public void GenericTypeParameterAsReceiver_IndexerAccess_PostfixIncrementAssignment_02() + { + var src = """ +interface I1 +{ + public int this[int x] {get; set;} +} + +class C1 : I1 +{ + public int F1; + + public int this[int x] + { + get + { + System.Console.Write(F1); + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + return 0; + } + set + { + System.Console.Write(F1); + } + } +} + +class Program +{ + public static C1 F; + + static void Main() + { + F = new C1 { F1 = 123 }; + Test1(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + Test2(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + Test3(ref F); + System.Console.Write(F.F1); + } + + static void Test1(ref T f) where T : I1 + { + f[0]++; + } + + static void Test2(ref T f) where T : class, I1 + { + f[0]++; + } + + static void Test3(ref C1 f) + { + f[0]++; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + var verifier = CompileAndVerify(comp, expectedOutput: "123123124:123123124:123123124").VerifyDiagnostics(); + + verifier.VerifyIL("Program.Test1(ref T)", +@" +{ + // Code size 62 (0x3e) + .maxstack 4 + .locals init (T V_0, + T& V_1, + int V_2, + T V_3) + IL_0000: nop + IL_0001: ldarg.0 + IL_0002: stloc.1 + IL_0003: ldloca.s V_3 + IL_0005: initobj ""T"" + IL_000b: ldloc.3 + IL_000c: box ""T"" + IL_0011: brtrue.s IL_001e + IL_0013: ldloc.1 + IL_0014: ldobj ""T"" + IL_0019: stloc.0 + IL_001a: ldloca.s V_0 + IL_001c: br.s IL_001f + IL_001e: ldloc.1 + IL_001f: dup + IL_0020: ldc.i4.0 + IL_0021: constrained. ""T"" + IL_0027: callvirt ""int I1.this[int].get"" + IL_002c: stloc.2 + IL_002d: ldc.i4.0 + IL_002e: ldloc.2 + IL_002f: ldc.i4.1 + IL_0030: add + IL_0031: constrained. ""T"" + IL_0037: callvirt ""void I1.this[int].set"" + IL_003c: nop + IL_003d: ret +} +"); + + verifier.VerifyIL("Program.Test2(ref T)", +@" +{ + // Code size 41 (0x29) + .maxstack 4 + .locals init (T V_0, + int V_1) + IL_0000: nop + IL_0001: ldarg.0 + IL_0002: ldobj ""T"" + IL_0007: stloc.0 + IL_0008: ldloca.s V_0 + IL_000a: dup + IL_000b: ldc.i4.0 + IL_000c: constrained. ""T"" + IL_0012: callvirt ""int I1.this[int].get"" + IL_0017: stloc.1 + IL_0018: ldc.i4.0 + IL_0019: ldloc.1 + IL_001a: ldc.i4.1 + IL_001b: add + IL_001c: constrained. ""T"" + IL_0022: callvirt ""void I1.this[int].set"" + IL_0027: nop + IL_0028: ret +} +"); + } + + [Fact] + public void GenericTypeParameterAsReceiver_IndexerAccess_PostfixIncrementAssignment_03() + { + var src = """ +using System.Threading.Tasks; + +interface I1 +{ + public int this[int x] {get; set;} +} + +class C1 : I1 +{ + public int F1; + + public int this[int x] + { + get + { + System.Console.Write(F1); + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + return 0; + } + set + { + System.Console.Write(F1); + } + } +} + +class Program +{ + public static C1 F; + + static async Task Main() + { + F = new C1 { F1 = 123 }; + await Test1(); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + await Test2(); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + await Test3(); + System.Console.Write(F.F1); + } + + static async Task Test1() where T : I1 + { + F[await Get0()]++; + } + + static async Task Test2() where T : class, I1 + { + F[await Get0()]++; + } + + static async Task Test3() + { + F[await Get0()]++; + } + + static async Task Get0() + { + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + await Task.Yield(); + return 0; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "123123125:123123125:123123125").VerifyDiagnostics(); + } + + [Fact] + public void GenericTypeParameterAsReceiver_PropertyAccess_CompoundAssignment_01() + { + var src = """ +interface I1 +{ + public int P1 {get; set;} +} + +struct S1 : I1 +{ + public int F1; + + public int P1 + { + get + { + System.Console.Write(F1); + Program.F.F1++; + return 0; + } + set + { + System.Console.Write(F1); + } + } +} + +class Program +{ + public static S1 F; + + static void Main() + { + F = new S1 { F1 = 123 }; + Test1(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new S1 { F1 = 123 }; + Test2(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new S1 { F1 = 123 }; + Test3(ref F); + System.Console.Write(F.F1); + } + + static void Test1(ref T f) where T : I1 + { + f.P1 += 1; + } + + static void Test2(ref T f) where T : struct, I1 + { + f.P1 += 1; + } + + static void Test3(ref S1 f) + { + f.P1 += 1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "123124124:123124124:123124124").VerifyDiagnostics(); + } + + [Fact] + public void GenericTypeParameterAsReceiver_PropertyAccess_CompoundAssignment_02() + { + var src = """ +interface I1 +{ + public int P1 {get; set;} +} + +class C1 : I1 +{ + public int F1; + + public int P1 + { + get + { + System.Console.Write(F1); + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + return 0; + } + set + { + System.Console.Write(F1); + } + } +} + +class Program +{ + public static C1 F; + + static void Main() + { + F = new C1 { F1 = 123 }; + Test1(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + Test2(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + Test3(ref F); + System.Console.Write(F.F1); + } + + static void Test1(ref T f) where T : I1 + { + f.P1 += 1; + } + + static void Test2(ref T f) where T : class, I1 + { + f.P1 += 1; + } + + static void Test3(ref C1 f) + { + f.P1 += 1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "123123124:123123124:123123124").VerifyDiagnostics(); + } + + [Fact] + public void GenericTypeParameterAsReceiver_IndexerAccess_CompoundAssignment_01() + { + var src = """ +interface I1 +{ + public int this[int x] {get; set;} +} + +struct S1 : I1 +{ + public int F1; + + public int this[int x] + { + get + { + System.Console.Write(F1); + Program.F.F1++; + return 0; + } + set + { + System.Console.Write(F1); + } + } +} + +class Program +{ + public static S1 F; + + static void Main() + { + F = new S1 { F1 = 123 }; + Test1(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new S1 { F1 = 123 }; + Test2(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new S1 { F1 = 123 }; + Test3(ref F); + System.Console.Write(F.F1); + } + + static void Test1(ref T f) where T : I1 + { + f[0] += 1; + } + + static void Test2(ref T f) where T : struct, I1 + { + f[0] += 1; + } + + static void Test3(ref S1 f) + { + f[0] += 1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "123124124:123124124:123124124").VerifyDiagnostics(); + } + + [Fact] + public void GenericTypeParameterAsReceiver_IndexerAccess_CompoundAssignment_02() + { + var src = """ +interface I1 +{ + public int this[int x] {get; set;} +} + +class C1 : I1 +{ + public int F1; + + public int this[int x] + { + get + { + System.Console.Write(F1); + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + return 0; + } + set + { + System.Console.Write(F1); + } + } +} + +class Program +{ + public static C1 F; + + static void Main() + { + F = new C1 { F1 = 123 }; + Test1(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + Test2(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + Test3(ref F); + System.Console.Write(F.F1); + } + + static void Test1(ref T f) where T : I1 + { + f[0] += 1; + } + + static void Test2(ref T f) where T : class, I1 + { + f[0] += 1; + } + + static void Test3(ref C1 f) + { + f[0] += 1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "123123124:123123124:123123124").VerifyDiagnostics(); + } + + [Fact] + public void GenericTypeParameterAsReceiver_IndexerAccess_CompoundAssignment_03() + { + var src = """ +using System.Threading.Tasks; + +interface I1 +{ + public int this[int x] {get; set;} +} + +class C1 : I1 +{ + public int F1; + + public int this[int x] + { + get + { + System.Console.Write(F1); + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + return 0; + } + set + { + System.Console.Write(F1); + } + } +} + +class Program +{ + public static C1 F; + + static async Task Main() + { + F = new C1 { F1 = 123 }; + await Test1(); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + await Test2(); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + await Test3(); + System.Console.Write(F.F1); + } + + static async Task Test1() where T : I1 + { + F[await Get0()] += 1; + } + + static async Task Test2() where T : class, I1 + { + F[await Get0()] += 1; + } + + static async Task Test3() + { + F[await Get0()] += 1; + } + + static async Task Get0() + { + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + await Task.Yield(); + return 0; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "123123125:123123125:123123125").VerifyDiagnostics(); + } + + [Fact] + public void GenericTypeParameterAsReceiver_IndexerAccess_CompoundAssignment_04() + { + var src = """ +using System.Threading.Tasks; + +interface I1 +{ + public int this[int x] {get; set;} +} + +class C1 : I1 +{ + public int F1; + + public int this[int x] + { + get + { + System.Console.Write(F1); + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + return 0; + } + set + { + System.Console.Write(F1); + } + } +} + +class Program +{ + public static C1 F; + + static async Task Main() + { + F = new C1 { F1 = 123 }; + await Test1(); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + await Test2(); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + await Test3(); + System.Console.Write(F.F1); + } + + static async Task Test1() where T : I1 + { + F[0] += await Get1(); + } + + static async Task Test2() where T : class, I1 + { + F[0] += await Get1(); + } + + static async Task Test3() + { + F[0] += await Get1(); + } + + static async Task Get1() + { + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + await Task.Yield(); + return 1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "123123125:123123125:123123125").VerifyDiagnostics(); + } + + [Fact] + public void GenericTypeParameterAsReceiver_IndexerAccess_CompoundAssignment_05() + { + var src = """ +using System.Threading.Tasks; + +interface I1 +{ + public int this[int x] {get; set;} +} + +class C1 : I1 +{ + public int F1; + + public int this[int x] + { + get + { + System.Console.Write(F1); + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + return 0; + } + set + { + System.Console.Write(F1); + } + } +} + +class Program +{ + public static C1 F; + + static async Task Main() + { + F = new C1 { F1 = 123 }; + await Test1(); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + await Test2(); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + await Test3(); + System.Console.Write(F.F1); + } + + static async Task Test1() where T : I1 + { + F[await Get0()] += await Get1(); + } + + static async Task Test2() where T : class, I1 + { + F[await Get0()] += await Get1(); + } + + static async Task Test3() + { + F[await Get0()] += await Get1(); + } + + static async Task Get0() + { + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + await Task.Yield(); + return 1; + } + + static async Task Get1() + { + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + await Task.Yield(); + return 1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "123123126:123123126:123123126").VerifyDiagnostics(); + } + + [ConditionalFact(typeof(CoreClrOnly))] + public void GenericTypeParameterAsReceiver_ImplicitIndexerAccess_CompoundAssignment_01() + { + var src = """ +interface I1 +{ + public int this[int x] {get; set;} + public int Length {get;} +} + +struct S1 : I1 +{ + public int F1; + + public int this[int x] + { + get + { + System.Console.Write(F1); + Program.F.F1++; + return 0; + } + set + { + System.Console.Write(F1); + } + } + + public int Length + { + get + { + Program.F.F1++; + return 5; + } + } +} + +class Program +{ + public static S1 F; + + static void Main() + { + F = new S1 { F1 = 123 }; + Test1(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new S1 { F1 = 123 }; + Test2(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new S1 { F1 = 123 }; + Test3(ref F); + System.Console.Write(F.F1); + } + + static void Test1(ref T f) where T : I1 + { + f[^0] += 1; + } + + static void Test2(ref T f) where T : struct, I1 + { + f[^0] += 1; + } + + static void Test3(ref S1 f) + { + f[^0] += 1; + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.NetLatest, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "124125125:124125125:124125125").VerifyDiagnostics(); + } + + [ConditionalFact(typeof(CoreClrOnly))] + public void GenericTypeParameterAsReceiver_ImplicitIndexerAccess_CompoundAssignment_02() + { + var src = """ +interface I1 +{ + public int this[int x] {get; set;} + public int Length {get;} +} + +class C1 : I1 +{ + public int F1; + + public int this[int x] + { + get + { + System.Console.Write(F1); + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + return 0; + } + set + { + System.Console.Write(F1); + } + } + + public int Length + { + get + { + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + return 5; + } + } +} + +class Program +{ + public static C1 F; + + static void Main() + { + F = new C1 { F1 = 123 }; + Test1(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + Test2(ref F); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + Test3(ref F); + System.Console.Write(F.F1); + } + + static void Test1(ref T f) where T : I1 + { + f[^0] += 1; + } + + static void Test2(ref T f) where T : class, I1 + { + f[^0] += 1; + } + + static void Test3(ref C1 f) + { + f[^0] += 1; + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.NetLatest, options: TestOptions.DebugExe); + var verifier = CompileAndVerify(comp, expectedOutput: "123123125:123123125:123123125").VerifyDiagnostics(); + + verifier.VerifyIL("Program.Test1(ref T)", +@" +{ + // Code size 76 (0x4c) + .maxstack 4 + .locals init (T& V_0, + T V_1, + T& V_2, + int V_3, + T V_4) + IL_0000: nop + IL_0001: ldarg.0 + IL_0002: stloc.2 + IL_0003: ldloca.s V_4 + IL_0005: initobj ""T"" + IL_000b: ldloc.s V_4 + IL_000d: box ""T"" + IL_0012: brtrue.s IL_001f + IL_0014: ldloc.2 + IL_0015: ldobj ""T"" + IL_001a: stloc.1 + IL_001b: ldloca.s V_1 + IL_001d: br.s IL_0020 + IL_001f: ldloc.2 + IL_0020: stloc.0 + IL_0021: ldloc.0 + IL_0022: constrained. ""T"" + IL_0028: callvirt ""int I1.Length.get"" + IL_002d: stloc.3 + IL_002e: ldloc.0 + IL_002f: ldloc.3 + IL_0030: ldloc.0 + IL_0031: ldloc.3 + IL_0032: constrained. ""T"" + IL_0038: callvirt ""int I1.this[int].get"" + IL_003d: ldc.i4.1 + IL_003e: add + IL_003f: constrained. ""T"" + IL_0045: callvirt ""void I1.this[int].set"" + IL_004a: nop + IL_004b: ret +} +"); + + verifier.VerifyIL("Program.Test2(ref T)", +@" +{ + // Code size 48 (0x30) + .maxstack 4 + .locals init (T V_0, + int V_1) + IL_0000: nop + IL_0001: ldarg.0 + IL_0002: ldobj ""T"" + IL_0007: stloc.0 + IL_0008: ldloc.0 + IL_0009: box ""T"" + IL_000e: callvirt ""int I1.Length.get"" + IL_0013: stloc.1 + IL_0014: ldloc.0 + IL_0015: box ""T"" + IL_001a: ldloc.1 + IL_001b: ldloc.0 + IL_001c: box ""T"" + IL_0021: ldloc.1 + IL_0022: callvirt ""int I1.this[int].get"" + IL_0027: ldc.i4.1 + IL_0028: add + IL_0029: callvirt ""void I1.this[int].set"" + IL_002e: nop + IL_002f: ret +} +"); + } + + [ConditionalFact(typeof(CoreClrOnly))] + public void GenericTypeParameterAsReceiver_ImplicitIndexerAccess_CompoundAssignment_03() + { + var src = """ +using System.Threading.Tasks; + +interface I1 +{ + public int this[int x] {get; set;} + public int Length {get;} +} + +class C1 : I1 +{ + public int F1; + + public int this[int x] + { + get + { + System.Console.Write(F1); + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + return 0; + } + set + { + System.Console.Write(F1); + } + } + + public int Length + { + get + { + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + return 5; + } + } +} + +class Program +{ + public static C1 F; + + static async Task Main() + { + F = new C1 { F1 = 123 }; + await Test1(); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + await Test2(); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + await Test3(); + System.Console.Write(F.F1); + } + + static async Task Test1() where T : I1 + { + F[^await Get0()] += 1; + } + + static async Task Test2() where T : class, I1 + { + F[^await Get0()] += 1; + } + + static async Task Test3() + { + F[^await Get0()] += 1; + } + + static async Task Get0() + { + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + await Task.Yield(); + return 0; + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.NetLatest, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "123123126:123123126:123123126").VerifyDiagnostics(); + } + + [ConditionalFact(typeof(CoreClrOnly))] + public void GenericTypeParameterAsReceiver_ImplicitIndexerAccess_CompoundAssignment_04() + { + var src = """ +using System.Threading.Tasks; + +interface I1 +{ + public int this[int x] {get; set;} + public int Length {get;} +} + +class C1 : I1 +{ + public int F1; + + public int this[int x] + { + get + { + System.Console.Write(F1); + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + return 0; + } + set + { + System.Console.Write(F1); + } + } + + public int Length + { + get + { + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + return 5; + } + } +} + +class Program +{ + public static C1 F; + + static async Task Main() + { + F = new C1 { F1 = 123 }; + await Test1(); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + await Test2(); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + await Test3(); + System.Console.Write(F.F1); + } + + static async Task Test1() where T : I1 + { + F[^0] += await Get1(); + } + + static async Task Test2() where T : class, I1 + { + F[^0] += await Get1(); + } + + static async Task Test3() + { + F[^0] += await Get1(); + } + + static async Task Get1() + { + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + await Task.Yield(); + return 1; + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.NetLatest, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "123123126:123123126:123123126").VerifyDiagnostics(); + } + + [ConditionalFact(typeof(CoreClrOnly))] + public void GenericTypeParameterAsReceiver_ImplicitIndexerAccess_CompoundAssignment_05() + { + var src = """ +using System.Threading.Tasks; + +interface I1 +{ + public int this[int x] {get; set;} + public int Length {get;} +} + +class C1 : I1 +{ + public int F1; + + public int this[int x] + { + get + { + System.Console.Write(F1); + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + return 0; + } + set + { + System.Console.Write(F1); + } + } + + public int Length + { + get + { + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + return 5; + } + } +} + +class Program +{ + public static C1 F; + + static async Task Main() + { + F = new C1 { F1 = 123 }; + await Test1(); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + await Test2(); + System.Console.Write(F.F1); + + System.Console.Write(":"); + + F = new C1 { F1 = 123 }; + await Test3(); + System.Console.Write(F.F1); + } + + static async Task Test1() where T : I1 + { + F[^await Get0()] += await Get1(); + } + + static async Task Test2() where T : class, I1 + { + F[^await Get0()] += await Get1(); + } + + static async Task Test3() + { + F[^await Get0()] += await Get1(); + } + + static async Task Get0() + { + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + await Task.Yield(); + return 1; + } + + static async Task Get1() + { + Program.F = new C1 { F1 = Program.F.F1 + 1 }; + await Task.Yield(); + return 1; + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.NetLatest, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "123123127:123123127:123123127").VerifyDiagnostics(); + } } } diff --git a/src/Compilers/CSharp/Test/Emit2/Emit/UnmanagedTypeModifierTests.cs b/src/Compilers/CSharp/Test/Emit2/Emit/UnmanagedTypeModifierTests.cs index dfc1fbea048ae..4203834769194 100644 --- a/src/Compilers/CSharp/Test/Emit2/Emit/UnmanagedTypeModifierTests.cs +++ b/src/Compilers/CSharp/Test/Emit2/Emit/UnmanagedTypeModifierTests.cs @@ -1140,7 +1140,7 @@ public enum AttributeTargets { } } "; - var corlibWithoutUnmanagedTypeRef = CreateEmptyCompilation(corlib_cs).EmitToImageReference(); + var corlibWithoutUnmanagedTypeRef = CreateEmptyCompilation(corlib_cs, assemblyName: "corlibWithoutUnmanagedTypeRef").EmitToImageReference(); var refCode = @" namespace System.Runtime.InteropServices @@ -1148,8 +1148,8 @@ namespace System.Runtime.InteropServices public class UnmanagedType {} }"; - var ref1 = CreateEmptyCompilation(refCode, references: new[] { corlibWithoutUnmanagedTypeRef }).EmitToImageReference(); - var ref2 = CreateEmptyCompilation(refCode, references: new[] { corlibWithoutUnmanagedTypeRef }).EmitToImageReference(); + var ref1 = CreateEmptyCompilation(refCode, references: new[] { corlibWithoutUnmanagedTypeRef }, assemblyName: "ref1").EmitToImageReference(); + var ref2 = CreateEmptyCompilation(refCode, references: new[] { corlibWithoutUnmanagedTypeRef }, assemblyName: "ref2").EmitToImageReference(); var user = @" public class Test where T : unmanaged @@ -1158,9 +1158,9 @@ public class Test where T : unmanaged CreateEmptyCompilation(user, references: new[] { ref1, ref2, corlibWithoutUnmanagedTypeRef }) .VerifyDiagnostics( - // (2,32): error CS0518: Predefined type 'System.Runtime.InteropServices.UnmanagedType' is not defined or imported + // (2,32): error CS8356: Predefined type 'System.Runtime.InteropServices.UnmanagedType' is declared in multiple referenced assemblies: 'ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // public class Test where T : unmanaged - Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "unmanaged").WithArguments("System.Runtime.InteropServices.UnmanagedType").WithLocation(2, 32)); + Diagnostic(ErrorCode.ERR_PredefinedTypeAmbiguous, "unmanaged").WithArguments("System.Runtime.InteropServices.UnmanagedType", "ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 32)); } [Fact] diff --git a/src/Compilers/CSharp/Test/Emit3/Attributes/AttributeTests_IsByRefLike.cs b/src/Compilers/CSharp/Test/Emit3/Attributes/AttributeTests_IsByRefLike.cs index 3ffeb25f39ec7..7b4cc1d64e6cc 100644 --- a/src/Compilers/CSharp/Test/Emit3/Attributes/AttributeTests_IsByRefLike.cs +++ b/src/Compilers/CSharp/Test/Emit3/Attributes/AttributeTests_IsByRefLike.cs @@ -683,7 +683,7 @@ void validate(ModuleSymbol module) AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsByRefLikeAttribute, Accessibility.Public); AssertHasCompilerFeatureRequired(includeCompilerFeatureRequired, peType, peModule, new MetadataDecoder(peModule)); } - }; + } CompileAndVerify(new[] { text, GetCompilerFeatureRequiredAttributeText(includeCompilerFeatureRequired) }, verify: Verification.Passes, symbolValidator: validate, sourceSymbolValidator: validate); } diff --git a/src/Compilers/CSharp/Test/Emit3/Attributes/AttributeTests_NullableContext.cs b/src/Compilers/CSharp/Test/Emit3/Attributes/AttributeTests_NullableContext.cs index f7a436c606ee1..550edbe1950a3 100644 --- a/src/Compilers/CSharp/Test/Emit3/Attributes/AttributeTests_NullableContext.cs +++ b/src/Compilers/CSharp/Test/Emit3/Attributes/AttributeTests_NullableContext.cs @@ -5,6 +5,7 @@ #nullable disable using System; +using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; diff --git a/src/Compilers/CSharp/Test/Emit3/Attributes/AttributeTests_WellKnownAttributes.cs b/src/Compilers/CSharp/Test/Emit3/Attributes/AttributeTests_WellKnownAttributes.cs index cb4ef10c97def..1eb8e2d5893a9 100644 --- a/src/Compilers/CSharp/Test/Emit3/Attributes/AttributeTests_WellKnownAttributes.cs +++ b/src/Compilers/CSharp/Test/Emit3/Attributes/AttributeTests_WellKnownAttributes.cs @@ -3614,13 +3614,13 @@ public class C2 { } // (13,9): error CS0501: 'C.F2(int, string)' must declare a body because it is not marked abstract, extern, or partial // int F2(int bufSize, string buf); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "F2").WithArguments("C.F2(int, string)").WithLocation(13, 9), - // (6,6): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' + // (6,6): error CS0601: The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member // [DllImport("D.DLL")] Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(6, 6), // (9,6): error CS0592: Attribute 'DllImport' is not valid on this declaration type. It is only valid on 'method' declarations. // [DllImport("D.DLL")] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "DllImport").WithArguments("DllImport", "method").WithLocation(9, 6), - // (12,6): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' + // (12,6): error CS0601: The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member // [DllImport("D.DLL")] Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(12, 6), // (15,6): error CS0592: Attribute 'DllImport' is not valid on this declaration type. It is only valid on 'method' declarations. @@ -5752,7 +5752,7 @@ void metadataValidator(ModuleSymbol module) Assert.Equal(new[] { "CompilerGeneratedAttribute" }, GetAttributeNames(method.GetAttributes())); Assert.True(method.RequiresSecurityObject); - }; + } var verifier = CompileAndVerify( source, diff --git a/src/Compilers/CSharp/Test/Emit3/Diagnostics/DiagnosticAnalyzerTests.cs b/src/Compilers/CSharp/Test/Emit3/Diagnostics/DiagnosticAnalyzerTests.cs index 770ca4c93fc5f..ad1e6be964805 100644 --- a/src/Compilers/CSharp/Test/Emit3/Diagnostics/DiagnosticAnalyzerTests.cs +++ b/src/Compilers/CSharp/Test/Emit3/Diagnostics/DiagnosticAnalyzerTests.cs @@ -142,7 +142,7 @@ int x1(int x2) }"; // TODO: Compilation create doesn't accept analyzers anymore. var options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions( - new[] { KeyValuePairUtil.Create("CA9999_UseOfVariableThatStartsWithX", ReportDiagnostic.Suppress) }); + new[] { KeyValuePair.Create("CA9999_UseOfVariableThatStartsWithX", ReportDiagnostic.Suppress) }); CreateCompilationWithMscorlib461(source, options: options/*, analyzers: new IDiagnosticAnalyzerFactory[] { new ComplainAboutX() }*/).VerifyDiagnostics( // (2,18): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) @@ -165,7 +165,7 @@ int x1(int x2) }"; // TODO: Compilation create doesn't accept analyzers anymore. var options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions( - new[] { KeyValuePairUtil.Create("CA9999_UseOfVariableThatStartsWithX", ReportDiagnostic.Error) }); + new[] { KeyValuePair.Create("CA9999_UseOfVariableThatStartsWithX", ReportDiagnostic.Error) }); CreateCompilationWithMscorlib461(source, options: options).VerifyDiagnostics( // (2,18): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) diff --git a/src/Compilers/CSharp/Test/Emit3/OverloadResolutionPriorityTests.cs b/src/Compilers/CSharp/Test/Emit3/OverloadResolutionPriorityTests.cs index 987440c7778f6..a6b6516bf8d82 100644 --- a/src/Compilers/CSharp/Test/Emit3/OverloadResolutionPriorityTests.cs +++ b/src/Compilers/CSharp/Test/Emit3/OverloadResolutionPriorityTests.cs @@ -69,7 +69,7 @@ static void validate(ModuleSymbol module) Assert.Equal(0, m.OverloadResolutionPriority); } } - }; + } } [Theory, CombinatorialData] diff --git a/src/Compilers/CSharp/Test/Emit3/Semantics/CollectionExpressionTests.cs b/src/Compilers/CSharp/Test/Emit3/Semantics/CollectionExpressionTests.cs index 45dd91e11bc0f..292b8336a9ee2 100644 --- a/src/Compilers/CSharp/Test/Emit3/Semantics/CollectionExpressionTests.cs +++ b/src/Compilers/CSharp/Test/Emit3/Semantics/CollectionExpressionTests.cs @@ -25,8 +25,8 @@ public class CollectionExpressionTests : CSharpTestBase { private static readonly IEnumerable> WithSpanAllocWarning = new[] { - KeyValuePairUtil.Create(GetIdForErrorCode(ErrorCode.WRN_CollectionExpressionRefStructMayAllocate), ReportDiagnostic.Warn), - KeyValuePairUtil.Create(GetIdForErrorCode(ErrorCode.WRN_CollectionExpressionRefStructSpreadMayAllocate), ReportDiagnostic.Warn) + KeyValuePair.Create(GetIdForErrorCode(ErrorCode.WRN_CollectionExpressionRefStructMayAllocate), ReportDiagnostic.Warn), + KeyValuePair.Create(GetIdForErrorCode(ErrorCode.WRN_CollectionExpressionRefStructSpreadMayAllocate), ReportDiagnostic.Warn) }; private static string IncludeExpectedOutput(string expectedOutput) => ExecutionConditionUtil.IsMonoOrCoreClr ? expectedOutput : null; @@ -14046,13 +14046,17 @@ static void Main() } """; - // We should check conversion to the iteration type - // Tracked by https://github.com/dotnet/roslyn/issues/68786 var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // x[0].ToString(); // 1 - Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x[0]").WithLocation(8, 9)); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x[0]").WithLocation(8, 9), + // (9,27): warning CS8625: Cannot convert null literal to non-nullable reference type. + // List y = [null]; // 2 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(9, 27), + // (11,17): warning CS8625: Cannot convert null literal to non-nullable reference type. + // y = [2, null]; // 3 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(11, 17)); } [Fact] @@ -14073,9 +14077,9 @@ static void Main() { S x = [1]; x[0].ToString(); // 1 - S y = [null]; + S y = [null]; // 2 y[0].ToString(); - y = [2, null]; + y = [2, null]; // 3 y[1].ToString(); } } @@ -14084,7 +14088,13 @@ static void Main() comp.VerifyEmitDiagnostics( // (14,9): warning CS8602: Dereference of a possibly null reference. // x[0].ToString(); // 1 - Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x[0]").WithLocation(14, 9)); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x[0]").WithLocation(14, 9), + // (15,24): warning CS8625: Cannot convert null literal to non-nullable reference type. + // S y = [null]; // 2 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(15, 24), + // (17,17): warning CS8625: Cannot convert null literal to non-nullable reference type. + // y = [2, null]; // 3 + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(17, 17)); } [Fact] @@ -31962,8 +31972,10 @@ public void Add(object o) { } } """; - // We don't analyze the Add methods - CreateCompilation(src).VerifyEmitDiagnostics(); + CreateCompilation(src).VerifyEmitDiagnostics( + // (5,16): warning CS8625: Cannot convert null literal to non-nullable reference type. + // CNotNull x1 = [null]; + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 16)); } [Fact] @@ -31986,7 +31998,7 @@ public void ElementNullability_Inference_IEnumerableCollection_AnalyzeAddMethods M(CreateUnannotated(maybeNull), [maybeNull]); M(CreateUnannotated(maybeNull), [notNull]); - M(CreateUnannotated(notNull), [maybeNull]); + M(CreateUnannotated(notNull), [maybeNull]); // 1 M(CreateUnannotated(notNull), [notNull]); void M(T t1, T t2) { } @@ -32007,8 +32019,10 @@ public void Add(T t) { } } """; - // We don't analyze the Add methods - CreateCompilation(source).VerifyEmitDiagnostics(); + CreateCompilation(source).VerifyEmitDiagnostics( + // (17,32): warning CS8604: Possible null reference argument for parameter 't' in 'void CUnannotated.Add(object t)'. + // M(CreateUnannotated(notNull), [maybeNull]); + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "maybeNull").WithArguments("t", "void CUnannotated.Add(object t)").WithLocation(17, 32)); } [Fact] @@ -32037,8 +32051,10 @@ public void Add(T t) where T : notnull { } } """; - // We don't analyze the Add methods - CreateCompilation(source).VerifyEmitDiagnostics(); + CreateCompilation(source).VerifyEmitDiagnostics( + // (8,13): warning CS8604: Possible null reference argument for parameter 't' in 'void C.Add(object t)'. + // M(new C(), [maybeNull]); + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "maybeNull").WithArguments("t", "void C.Add(object t)").WithLocation(8, 13)); } [Fact] @@ -32084,11 +32100,10 @@ public void Add(T t) { } } """; - // Should we also produce W-warnings on `M(CreateAnnotated(notNull), [maybeNull])` and `M(CreateUnannotated(notNull), [maybeNull])`? - // Tracked by https://github.com/dotnet/roslyn/issues/68786 - - // We don't analyze the Add methods - CreateCompilation(source).VerifyEmitDiagnostics(); + CreateCompilation(source).VerifyEmitDiagnostics( + // (17,32): warning CS8604: Possible null reference argument for parameter 't' in 'void CUnannotated.Add(object t)'. + // M(CreateUnannotated(notNull), [maybeNull]); // 1 + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "maybeNull").WithArguments("t", "void CUnannotated.Add(object t)").WithLocation(17, 32)); } [Fact] @@ -32102,7 +32117,7 @@ public void ElementNullability_Inference_IEnumerableTCollection_AnalyzeAddMethod object? maybeNull = null; object? notNull = new object(); - M(new C(), [maybeNull]); + M(new C(), [maybeNull]); // 1 C c1 = [maybeNull]; M(new C(), [notNull]); @@ -32118,8 +32133,10 @@ public void Add(T t) where T : notnull { } } """; - // We don't analyze the Add methods - CreateCompilation(source).VerifyEmitDiagnostics(); + CreateCompilation(source).VerifyEmitDiagnostics( + // (8,13): warning CS8604: Possible null reference argument for parameter 't' in 'void C.Add(object t)'. + // M(new C(), [maybeNull]); // 1 + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "maybeNull").WithArguments("t", "void C.Add(object t)").WithLocation(8, 13)); } [Fact] @@ -32133,13 +32150,13 @@ public void ElementNullability_IEnumerableTCollection_AnalyzeAddMethods() object? maybeNull = null; object notNull = new object(); - CAnnotated c1 = [maybeNull]; // 1 + CAnnotated c1 = [maybeNull]; CAnnotated c2 = [maybeNull]; CAnnotated c3 = [notNull]; CAnnotated c4 = [notNull]; - CUnannotated c5 = [maybeNull]; // 2 + CUnannotated c5 = [maybeNull]; // 1 CUnannotated c6 = [maybeNull]; CUnannotated c7 = [notNull]; @@ -32160,10 +32177,10 @@ public void Add(T t) { } } """; - // We should produce W-warnings on `c1` and `c5` for implicit conversion from the element to the iteration type. - // Tracked by https://github.com/dotnet/roslyn/issues/68786 - // We don't analyze the Add methods - CreateCompilation(source).VerifyEmitDiagnostics(); + CreateCompilation(source).VerifyEmitDiagnostics( + // (14,28): warning CS8604: Possible null reference argument for parameter 't' in 'void CUnannotated.Add(object t)'. + // CUnannotated c5 = [maybeNull]; // 1 + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "maybeNull").WithArguments("t", "void CUnannotated.Add(object t)").WithLocation(14, 28)); } [Fact] @@ -32183,10 +32200,10 @@ public void ElementNullability_Inference_IEnumerableTCollection_AnalyzeAddMethod M(CreateAnnotated(notNull), [maybeNull]); M(CreateAnnotated(notNull), [notNull]); - M(CreateUnannotated(maybeNull), [maybeNull]); + M(CreateUnannotated(maybeNull), [maybeNull]); // 1 M(CreateUnannotated(maybeNull), [notNull]); - M(CreateUnannotated(notNull), [maybeNull]); + M(CreateUnannotated(notNull), [maybeNull]); // 1 M(CreateUnannotated(notNull), [notNull]); void M(T t1, T t2) { } @@ -32209,8 +32226,10 @@ public void Add(U u) where U : notnull { } } """; - // We don't analyze the Add methods - CreateCompilation(source).VerifyEmitDiagnostics(); + CreateCompilation(source).VerifyEmitDiagnostics( + // (14,34): warning CS8604: Possible null reference argument for parameter 'u' in 'void CUnannotated.Add(object u)'. + // M(CreateUnannotated(maybeNull), [maybeNull]); + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "maybeNull").WithArguments("u", "void CUnannotated.Add(object u)").WithLocation(14, 34)); } [Fact] @@ -32473,9 +32492,10 @@ public class Container } """; - // We should check conversion to the iteration type - // Tracked by https://github.com/dotnet/roslyn/issues/68786 - var comp = CreateCompilation(src).VerifyEmitDiagnostics(); + var comp = CreateCompilation(src).VerifyEmitDiagnostics( + // (6,26): warning CS8620: Argument of type 'Container' cannot be used for parameter 'item' of type 'Container' in 'void List>.Add(Container item)' due to differences in the nullability of reference types. + // var collection = IdList([element1, element2]); // 1 + Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "element1").WithArguments("Container", "Container", "item", "void List>.Add(Container item)").WithLocation(6, 26)); var tree = comp.SyntaxTrees.First(); var invocation = GetSyntax(tree, "IdList([element1, element2])"); @@ -40102,6 +40122,63 @@ static void Main() Diagnostic(ErrorCode.ERR_BadArgTypesForCollectionAdd, "y").WithArguments("MyCollection.Add(string)").WithLocation(8, 37)); } + [Fact] + public void AddMethod_Extension_Nullability() + { + string sourceA = """ + using System.Collections; + using System.Collections.Generic; + public class MyCollection : IEnumerable + { + private readonly List _list = new(); + IEnumerator IEnumerable.GetEnumerator() => _list.GetEnumerator(); + internal void __AddInternal(T t) { _list.Add(t); } + } + namespace N + { + internal static class Extensions + { + public static void Add(this MyCollection collection, T t) { collection.__AddInternal(t); } + } + } + """; + var comp = CreateCompilation(sourceA); + var refA = comp.EmitToImageReference(); + + string sourceB = """ + using N; + class Program + { + static void Main() + { + MyCollection c1 = [null]; // missing warning + c1.Report(); + c1 = ["a"]; + c1.Report(); + c1 = [..(string[])["a"], "b"]; + c1.Report(); + } + } + """; + + // https://github.com/dotnet/roslyn/issues/68786 + // Warnings for element conversions to reinferred extension Add parameter types are not implemented. + var verifier = CompileAndVerify([sourceB, sourceA, s_collectionExtensions], expectedOutput: "[null], [a], [a, b],"); + verifier.VerifyDiagnostics(); + + comp = CreateCompilation([sourceB, s_collectionExtensions], references: [refA]); + comp.VerifyEmitDiagnostics( + // (6,35): error CS1061: 'MyCollection' does not contain a definition for 'Add' and no accessible extension method 'Add' accepting a first argument of type 'MyCollection' could be found (are you missing a using directive or an assembly reference?) + // MyCollection c1 = [null]; + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "[null]").WithArguments("MyCollection", "Add").WithLocation(6, 35), + // (8,14): error CS1061: 'MyCollection' does not contain a definition for 'Add' and no accessible extension method 'Add' accepting a first argument of type 'MyCollection' could be found (are you missing a using directive or an assembly reference?) + // c1 = ["a"]; + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, @"[""a""]").WithArguments("MyCollection", "Add").WithLocation(8, 14), + // (10,14): error CS1061: 'MyCollection' does not contain a definition for 'Add' and no accessible extension method 'Add' accepting a first argument of type 'MyCollection' could be found (are you missing a using directive or an assembly reference?) + // c1 = [..(string[])["a"], "b"]; + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, @"[..(string[])[""a""], ""b""]").WithArguments("MyCollection", "Add").WithLocation(10, 14)); + } + [Fact] public void AddMethod_08() { diff --git a/src/Compilers/CSharp/Test/Emit3/Semantics/ExtensionOperatorsTests.cs b/src/Compilers/CSharp/Test/Emit3/Semantics/ExtensionOperatorsTests.cs new file mode 100644 index 0000000000000..0308f927e18f5 --- /dev/null +++ b/src/Compilers/CSharp/Test/Emit3/Semantics/ExtensionOperatorsTests.cs @@ -0,0 +1,27414 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. +#nullable disable + +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Test.Utilities; +using Microsoft.CodeAnalysis.Test.Utilities; +using Roslyn.Test.Utilities; +using Xunit; + +using static Microsoft.CodeAnalysis.CSharp.UnitTests.UserDefinedCompoundAssignmentOperatorsTests; + +namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics +{ + [CompilerTrait(CompilerFeature.Extensions)] + public class ExtensionOperatorsTests : CompilingTestBase + { + [Fact] + public void Conversions_001_Declaration() + { + var src = $$$""" +static class Extensions +{ + extension(S1) + { + public static implicit operator int(S1 x) => 0; + } + + extension(S2) + { + public static explicit operator int(S2 x) => 0; + } +} + +struct S1 +{} + +struct S2 +{} + +static class C1 +{ + static void Test() + { + var s1 = new S1(); + var i1 = (int)s1; + + var s2 = new S2(); + var i2 = (int)s2; + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (5,41): error CS9282: This member is not allowed in an extension block + // public static implicit operator int(S1 x) => 0; + Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "int").WithLocation(5, 41), + // (10,41): error CS9282: This member is not allowed in an extension block + // public static explicit operator int(S2 x) => 0; + Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "int").WithLocation(10, 41), + // (25,18): error CS0030: Cannot convert type 'S1' to 'int' + // var i1 = (int)s1; + Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int)s1").WithArguments("S1", "int").WithLocation(25, 18), + // (28,18): error CS0030: Cannot convert type 'S2' to 'int' + // var i2 = (int)s2; + Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int)s2").WithArguments("S2", "int").WithLocation(28, 18) + ); + } + + [Theory] + [CombinatorialData] + public void Unary_001_Declaration([CombinatorialValues("+", "-", "!", "~")] string op) + { + var src = $$$""" +static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op}}}(S1 x) => default; + public static S1? operator {{{op}}}(S1? x) => default; + } +} + +static class Extensions2 +{ + extension(S1) + { + public static S2 operator {{{op}}}(S1 x) => default; + public static S1 operator {{{op}}}(S2 x) => default; + } +} + +static class Extensions3 +{ + extension(S1) + { + public static void operator {{{op}}}(S1 x) {} + } +} + +static class Extensions4 +{ + extension(S1) + { + static S1 operator {{{op}}}(S1 x) => default; + } + + extension(S2) + { + public S2 operator {{{op}}}(S2 x) => default; + } + + extension(C1) + { + public static S1 operator {{{op}}}(C1 x) => default; + } +} + +static class Extensions5 +{ + extension(S1?) + { + public static S1 operator {{{op}}}(S1 x) => default; + public static S2 operator {{{op}}}(S1? x) => default; + } +} + +struct S1 +{} + +struct S2 +{} + +static class C1 +{} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (6,36): error CS9317: The parameter of a unary operator must be the extended type. + // public static S1? operator +(S1? x) => default; + Diagnostic(ErrorCode.ERR_BadExtensionUnaryOperatorSignature, op).WithLocation(6, 36), + // (15,35): error CS9317: The parameter of a unary operator must be the extended type. + // public static S1 operator +(S2 x) => default; + Diagnostic(ErrorCode.ERR_BadExtensionUnaryOperatorSignature, op).WithLocation(15, 35), + // (23,37): error CS0590: User-defined operators cannot return void + // public static void operator +(S1 x) {} + Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, op).WithLocation(23, 37), + // (31,28): error CS0558: User-defined operator 'Extensions4.extension(S1).operator +(S1)' must be declared static and public + // static S1 operator +(S1 x) => default; + Diagnostic(ErrorCode.ERR_OperatorsMustBeStaticAndPublic, op).WithArguments("Extensions4.extension(S1).operator " + op + "(S1)").WithLocation(31, 28), + // (36,28): error CS0558: User-defined operator 'Extensions4.extension(S2).operator +(S2)' must be declared static and public + // public S2 operator +(S2 x) => default; + Diagnostic(ErrorCode.ERR_OperatorsMustBeStaticAndPublic, op).WithArguments("Extensions4.extension(S2).operator " + op + "(S2)").WithLocation(36, 28), + // (41,35): error CS9321: An extension block extending a static class cannot contain user-defined operators + // public static S1 operator +(C1 x) => default; + Diagnostic(ErrorCode.ERR_OperatorInExtensionOfStaticClass, op).WithLocation(41, 35), + // (41,37): error CS0721: 'C1': static types cannot be used as parameters + // public static S1 operator +(C1 x) => default; + Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "C1").WithArguments("C1").WithLocation(41, 37), + // (49,35): error CS9317: The parameter of a unary operator must be the extended type. + // public static S1 operator +(S1 x) => default; + Diagnostic(ErrorCode.ERR_BadExtensionUnaryOperatorSignature, op).WithLocation(49, 35) + ); + } + + [Theory] + [CombinatorialData] + public void Unary_002_Declaration([CombinatorialValues("++", "--")] string op) + { + var src = $$$""" +static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op}}}(S1 x) => default; + public static S1? operator {{{op}}}(S1? x) => default; + } +} + +static class Extensions2 +{ + extension(S1) + { + public static S2 operator {{{op}}}(S1 x) => default; + public static S1 operator {{{op}}}(S2 x) => default; + } +} + +static class Extensions3 +{ + extension(S1) + { + static S1 operator {{{op}}}(S1 x) => default; + } + + extension(S2) + { + public S2 operator {{{op}}}(S2 x) => default; + } + + extension(C1) + { + public static C1 operator {{{op}}}(C1 x) => default; + } +} + +static class Extensions4 +{ + extension(S1?) + { + public static S1 operator {{{op}}}(S1 x) => default; + public static S1 operator {{{op}}}(S1? x) => default; + } +} + +static class Extensions5 +{ + extension(S1?) + { + public static S1? operator {{{op}}}(S1? x) => default; + } +} + +struct S1 +{} + +struct S2 +{} + +static class C1 +{} +"""; + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (6,36): error CS9318: The parameter type for ++ or -- operator must be the extended type. + // public static S1? operator ++(S1? x) => default; + Diagnostic(ErrorCode.ERR_BadExtensionIncDecSignature, op).WithLocation(6, 36), + // (14,35): error CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type + // public static S2 operator ++(S1 x) => default; + Diagnostic(ErrorCode.ERR_BadIncDecRetType, op).WithLocation(14, 35), + // (15,35): error CS9318: The parameter type for ++ or -- operator must be the extended type. + // public static S1 operator ++(S2 x) => default; + Diagnostic(ErrorCode.ERR_BadExtensionIncDecSignature, op).WithLocation(15, 35), + // (23,28): error CS0558: User-defined operator 'Extensions3.extension(S1).operator ++(S1)' must be declared static and public + // static S1 operator ++(S1 x) => default; + Diagnostic(ErrorCode.ERR_OperatorsMustBeStaticAndPublic, op).WithArguments("Extensions3.extension(S1).operator " + op + "(S1)").WithLocation(23, 28), + // (28,28): error CS0558: User-defined operator 'Extensions3.extension(S2).operator ++(S2)' must be declared static and public + // public S2 operator ++(S2 x) => default; + Diagnostic(ErrorCode.ERR_OperatorsMustBeStaticAndPublic, op).WithArguments("Extensions3.extension(S2).operator " + op + "(S2)").WithLocation(28, 28), + // (33,23): error CS0722: 'C1': static types cannot be used as return types + // public static C1 operator ++(C1 x) => default; + Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "C1").WithArguments("C1").WithLocation(33, 23), + // (33,35): error CS9321: An extension block extending a static class cannot contain user-defined operators + // public static C1 operator ++(C1 x) => default; + Diagnostic(ErrorCode.ERR_OperatorInExtensionOfStaticClass, op).WithLocation(33, 35), + // (33,38): error CS0721: 'C1': static types cannot be used as parameters + // public static C1 operator ++(C1 x) => default; + Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "C1").WithArguments("C1").WithLocation(33, 38), + // (41,35): error CS9318: The parameter type for ++ or -- operator must be the extended type. + // public static S1 operator ++(S1 x) => default; + Diagnostic(ErrorCode.ERR_BadExtensionIncDecSignature, op).WithLocation(41, 35), + // (42,35): error CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type + // public static S1 operator ++(S1? x) => default; + Diagnostic(ErrorCode.ERR_BadIncDecRetType, op).WithLocation(42, 35) + ); + } + + [Fact] + public void Unary_003_Declaration() + { + var src = """ +static class Extensions1 +{ + extension(S1) + { +#line 100 + public static bool operator true(S1 x) => default; + public static bool operator false(S1 x) => default; + public static bool operator true(S1? x) => default; + public static bool operator false(S1? x) => default; + } +} + +static class Extensions2 +{ + extension(S1) + { +#line 200 + public static bool operator true(S1 x) => default; + } + + extension(S1) + { +#line 300 + public static bool operator false(S1 x) => default; + } +} + +static class Extensions3 +{ + extension(S1) + { +#line 400 + public static bool operator true(S1 x) => default; + } + + extension(S2) + { + public static bool operator false(S2 x) => default; + } +} + +static class Extensions4 +{ + extension(S1) + { +#line 500 + public static S1 operator true(S1 x) => default; + } +} + +static class Extensions5 +{ + extension(S1) + { +#line 600 + public static bool operator true(S2 x) => default; + public static bool operator false(S2 x) => default; + } +} + +static class Extensions6 +{ + extension(S1) + { +#line 700 + static bool operator true(S1 x) => default; + public bool operator false(S1 x) => default; + } + + extension(C1) + { +#line 800 + public static bool operator true(C1 x) => default; + public static bool operator false(C1 x) => default; + } +} + +static class Extensions7 +{ + extension(S1?) + { +#line 900 + public static bool operator true(S1 x) => default; + public static bool operator false(S1 x) => default; + public static bool operator true(S1? x) => default; + public static bool operator false(S1? x) => default; + } +} + +struct S1 +{} + +struct S2 +{} + +static class C1 +{} +"""; + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (102,37): error CS9317: The parameter of a unary operator must be the extended type. + // public static bool operator true(S1? x) => default; + Diagnostic(ErrorCode.ERR_BadExtensionUnaryOperatorSignature, "true").WithLocation(102, 37), + // (103,37): error CS9317: The parameter of a unary operator must be the extended type. + // public static bool operator false(S1? x) => default; + Diagnostic(ErrorCode.ERR_BadExtensionUnaryOperatorSignature, "false").WithLocation(103, 37), + // (400,37): error CS0216: The operator 'Extensions3.extension(S1).operator true(S1)' requires a matching operator 'false' to also be defined + // public static bool operator true(S1 x) => default; + Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "true").WithArguments("Extensions3.extension(S1).operator true(S1)", "false").WithLocation(400, 37), + // (405,37): error CS0216: The operator 'Extensions3.extension(S2).operator false(S2)' requires a matching operator 'true' to also be defined + // public static bool operator false(S2 x) => default; + Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "false").WithArguments("Extensions3.extension(S2).operator false(S2)", "true").WithLocation(405, 37), + // (500,35): error CS0215: The return type of operator True or False must be bool + // public static S1 operator true(S1 x) => default; + Diagnostic(ErrorCode.ERR_OpTFRetType, "true").WithLocation(500, 35), + // (500,35): error CS0216: The operator 'Extensions4.extension(S1).operator true(S1)' requires a matching operator 'false' to also be defined + // public static S1 operator true(S1 x) => default; + Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "true").WithArguments("Extensions4.extension(S1).operator true(S1)", "false").WithLocation(500, 35), + // (600,37): error CS9317: The parameter of a unary operator must be the extended type. + // public static bool operator true(S2 x) => default; + Diagnostic(ErrorCode.ERR_BadExtensionUnaryOperatorSignature, "true").WithLocation(600, 37), + // (601,37): error CS9317: The parameter of a unary operator must be the extended type. + // public static bool operator false(S2 x) => default; + Diagnostic(ErrorCode.ERR_BadExtensionUnaryOperatorSignature, "false").WithLocation(601, 37), + // (700,30): error CS0558: User-defined operator 'Extensions6.extension(S1).operator true(S1)' must be declared static and public + // static bool operator true(S1 x) => default; + Diagnostic(ErrorCode.ERR_OperatorsMustBeStaticAndPublic, "true").WithArguments("Extensions6.extension(S1).operator true(S1)").WithLocation(700, 30), + // (701,30): error CS0558: User-defined operator 'Extensions6.extension(S1).operator false(S1)' must be declared static and public + // public bool operator false(S1 x) => default; + Diagnostic(ErrorCode.ERR_OperatorsMustBeStaticAndPublic, "false").WithArguments("Extensions6.extension(S1).operator false(S1)").WithLocation(701, 30), + // (800,37): error CS9321: An extension block extending a static class cannot contain user-defined operators + // public static bool operator true(C1 x) => default; + Diagnostic(ErrorCode.ERR_OperatorInExtensionOfStaticClass, "true").WithLocation(800, 37), + // (800,42): error CS0721: 'C1': static types cannot be used as parameters + // public static bool operator true(C1 x) => default; + Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "C1").WithArguments("C1").WithLocation(800, 42), + // (801,37): error CS9321: An extension block extending a static class cannot contain user-defined operators + // public static bool operator false(C1 x) => default; + Diagnostic(ErrorCode.ERR_OperatorInExtensionOfStaticClass, "false").WithLocation(801, 37), + // (801,43): error CS0721: 'C1': static types cannot be used as parameters + // public static bool operator false(C1 x) => default; + Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "C1").WithArguments("C1").WithLocation(801, 43), + // (900,37): error CS9317: The parameter of a unary operator must be the extended type. + // public static bool operator true(S1 x) => default; + Diagnostic(ErrorCode.ERR_BadExtensionUnaryOperatorSignature, "true").WithLocation(900, 37), + // (901,37): error CS9317: The parameter of a unary operator must be the extended type. + // public static bool operator false(S1 x) => default; + Diagnostic(ErrorCode.ERR_BadExtensionUnaryOperatorSignature, "false").WithLocation(901, 37) + ); + } + + [Theory] + [CombinatorialData] + public void Unary_004_Declaration([CombinatorialValues("+", "-", "!", "~")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op}}}(S1 x) => default; + } +} + +public struct S1 +{} +"""; + var comp = CreateCompilation(src); + CompileAndVerify(comp, symbolValidator: verify, sourceSymbolValidator: verify).VerifyDiagnostics(); + + void verify(ModuleSymbol m) + { + var name = UnaryOperatorName(op); + var method = m.GlobalNamespace.GetMember("Extensions1." + name); + + AssertEx.Equal("Extensions1." + name + "(S1)", method.ToDisplayString()); + Assert.Equal(MethodKind.Ordinary, method.MethodKind); + Assert.True(method.IsStatic); + Assert.False(method.IsExtensionMethod); + Assert.False(method.HasSpecialName); + Assert.False(method.HasRuntimeSpecialName); + Assert.False(method.HasUnsupportedMetadata); + } + } + + private static string UnaryOperatorName(string op, bool isChecked = false) + { + return OperatorFacts.UnaryOperatorNameFromSyntaxKind(SyntaxFactory.ParseToken(op).Kind(), isChecked: isChecked); + } + + [Theory] + [CombinatorialData] + public void Unary_005_Declaration([CombinatorialValues("++", "--")] string op) + { + var src = $$$""" +static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op}}}(S1 x) => default; + } +} + +struct S1 +{} +"""; + var comp = CreateCompilation(src); + CompileAndVerify(comp, symbolValidator: verify, sourceSymbolValidator: verify).VerifyDiagnostics(); + + void verify(ModuleSymbol m) + { + var name = UnaryOperatorName(op); + var method = m.GlobalNamespace.GetMember("Extensions1." + name); + + AssertEx.Equal("Extensions1." + name + "(S1)", method.ToDisplayString()); + Assert.Equal(MethodKind.Ordinary, method.MethodKind); + Assert.True(method.IsStatic); + Assert.False(method.IsExtensionMethod); + Assert.False(method.HasSpecialName); + Assert.False(method.HasRuntimeSpecialName); + Assert.False(method.HasUnsupportedMetadata); + } + } + + [Fact] + public void Unary_006_Declaration() + { + var src = """ +static class Extensions1 +{ + extension(S1) + { + public static bool operator true(S1 x) => default; + public static bool operator false(S1 x) => default; + } +} + +struct S1 +{} +"""; + var comp = CreateCompilation(src); + CompileAndVerify(comp, symbolValidator: verify, sourceSymbolValidator: verify).VerifyDiagnostics(); + + void verify(ModuleSymbol m) + { + var method = m.GlobalNamespace.GetMember("Extensions1." + WellKnownMemberNames.TrueOperatorName); + AssertEx.Equal("Extensions1." + WellKnownMemberNames.TrueOperatorName + "(S1)", method.ToDisplayString()); + verifyMethod(method); + + method = m.GlobalNamespace.GetMember("Extensions1." + WellKnownMemberNames.FalseOperatorName); + AssertEx.Equal("Extensions1." + WellKnownMemberNames.FalseOperatorName + "(S1)", method.ToDisplayString()); + verifyMethod(method); + } + + static void verifyMethod(MethodSymbol method) + { + Assert.Equal(MethodKind.Ordinary, method.MethodKind); + Assert.True(method.IsStatic); + Assert.False(method.IsExtensionMethod); + Assert.False(method.HasSpecialName); + Assert.False(method.HasRuntimeSpecialName); + Assert.False(method.HasUnsupportedMetadata); + } + } + + [Theory] + [CombinatorialData] + public void Unary_007_Declaration([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op, [CombinatorialValues("virtual", "abstract", "new", "override", "sealed", "readonly")] string modifier) + { + var src = $$$""" +static class Extensions1 +{ + extension(S1) + { + {{{modifier}}} + public static S1 operator {{{op}}}(S1 x) => default; + } +} + +struct S1 +{} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (6,35): error CS0106: The modifier 'abstract' is not valid for this item + // public static S1 operator !(S1 x) => default; + Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments(modifier).WithLocation(6, 35) + ); + } + + [Theory] + [CombinatorialData] + public void Unary_008_Declaration([CombinatorialValues("virtual", "abstract", "new", "override", "sealed", "readonly")] string modifier) + { + var src = $$$""" +static class Extensions1 +{ + extension(S1) + { + {{{modifier}}} + public static bool operator true(S1 x) => default; + + {{{modifier}}} + public static bool operator false(S1 x) => default; + } +} + +struct S1 +{} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (6,37): error CS0106: The modifier 'abstract' is not valid for this item + // public static bool operator true(S1 x) => default; + Diagnostic(ErrorCode.ERR_BadMemberFlag, "true").WithArguments(modifier).WithLocation(6, 37), + // (9,37): error CS0106: The modifier 'abstract' is not valid for this item + // public static bool operator false(S1 x) => default; + Diagnostic(ErrorCode.ERR_BadMemberFlag, "false").WithArguments(modifier).WithLocation(9, 37) + ); + } + + [Theory] + [CombinatorialData] + public void Unary_009_Declaration([CombinatorialValues("-", "++", "--")] string op) + { + var src = $$$""" +static class Extensions1 +{ + extension(S1) + { + public static S1 operator checked {{{op}}}(S1 x) => default; + public static S1 operator {{{op}}}(S1 x) => default; + } +} + +static class Extensions2 +{ + extension(S1) + { +#line 100 + public static S1 operator checked {{{op}}}(S1 x) => default; + } + extension(S1) + { + public static S1 operator {{{op}}}(S1 x) => default; + } +} + +static class Extensions3 +{ + extension(S1) + { + public static S1 operator checked {{{op}}}(S1 x) => default; + } +} + +struct S1 +{} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (112,43): error CS9025: The operator 'Extensions3.extension(S1).operator checked ++(S1)' requires a matching non-checked version of the operator to also be defined + // public static S1 operator checked ++(S1 x) => default; + Diagnostic(ErrorCode.ERR_CheckedOperatorNeedsMatch, op).WithArguments("Extensions3.extension(S1).operator checked " + op + "(S1)").WithLocation(112, 43) + ); + } + + [Theory] + [CombinatorialData] + public void Unary_010_Consumption(bool fromMetadata, [CombinatorialValues("+", "-", "!", "~")] string op, [CombinatorialValues("struct", "class")] string typeKind) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op}}}(S1 x) + { + System.Console.Write("operator1:"); + System.Console.Write(x.F); + return new S1 { F = x.F + 1 }; + } + } +} + +public {{{typeKind}}} S1 +{ + public int F; +} +"""; + + var src2 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1() { F = 101 }; + var s2 = {{{op}}}s1; + System.Console.Write(":"); + System.Console.Write(s1.F); + System.Console.Write(":"); + System.Console.Write(s2.F); + } +} +"""; + + var comp1 = CreateCompilation(src1); + var comp1Ref = fromMetadata ? comp1.EmitToImageReference() : comp1.ToMetadataReference(); + + var comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp2, expectedOutput: "operator1:101:101:102").VerifyDiagnostics(); + + var tree = comp2.SyntaxTrees.First(); + var model = comp2.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("Extensions1.extension(S1).operator " + op + "(S1)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S1", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: "operator1:101:101:102").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (6,18): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // var s2 = +s1; + Diagnostic(ErrorCode.ERR_FeatureInPreview, op + "s1").WithArguments("extensions").WithLocation(6, 18) + ); + + var opName = UnaryOperatorName(op); + var src3 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1(); + Extensions1.{{{opName}}}(s1); + } +} +"""; + var comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp3, expectedOutput: "operator1:0").VerifyDiagnostics(); + + comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp3, expectedOutput: "operator1:0").VerifyDiagnostics(); + + comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + CompileAndVerify(comp3, expectedOutput: "operator1:0").VerifyDiagnostics(); + + var src4 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1(); + s1.{{{opName}}}(); + S1.{{{opName}}}(s1); + } +} +"""; + var comp4 = CreateCompilation(src4, references: [comp1Ref]); + comp4.VerifyEmitDiagnostics( + // (6,12): error CS1061: 'S1' does not contain a definition for 'op_UnaryPlus' and no accessible extension method 'op_UnaryPlus' accepting a first argument of type 'S1' could be found (are you missing a using directive or an assembly reference?) + // s1.op_UnaryPlus(); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, opName).WithArguments("S1", opName).WithLocation(6, 12), + // (7,12): error CS0117: 'S1' does not contain a definition for 'op_UnaryPlus' + // S1.op_UnaryPlus(s1); + Diagnostic(ErrorCode.ERR_NoSuchMember, opName).WithArguments("S1", opName).WithLocation(7, 12) + ); + } + + [Fact] + public void Unary_011_Consumption_PredefinedComesFirst() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator +(S2 x) => throw null; + } +} + +public struct S2 +{ + public static implicit operator int(S2 x) + { + System.Console.Write("operator2"); + return 0; + } +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + int x = +s2; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("int.operator +(int)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("System.Int32", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Unary_012_Consumption_NonExtensionComesFirst() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator +(S2 x) => throw null; + } +} + +public struct S2 +{ + public static S2 operator +(S2 x) + { + System.Console.Write("operator2"); + return x; + } +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + _ = +s2; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("S2.operator +(S2)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S2", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Unary_013_Consumption_ScopeByScope() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator +(S1 x) => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{} + +namespace NS1 +{ + public static class Extensions2 + { + extension(S1) + { + public static S1 operator +(S1 x) + { + System.Console.Write("operator1"); + return x; + } + } + } + + namespace NS2 + { + public static class Extensions3 + { + extension(S2) + { + public static S2 operator +(S2 x) => throw null; + } + } + + class Program + { + static void Main() + { + var s1 = new S1(); + _ = +s1; + } + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("NS1.Extensions2.extension(S1).operator +(S1)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S1", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Unary_014_Consumption_NonExtensionAmbiguity() + { + var src = $$$""" +public interface I1 +{ + public static I1 operator -(I1 x) => x; +} + +public interface I3 +{ + public static I3 operator -(I3 x) => x; +} + +public interface I4 : I1, I3 +{ +} + +public interface I2 : I4 +{ +} + +public static class Extensions1 +{ + extension(I2) + { + public static I2 operator -(I2 x) => x; + } +} + +class Test2 : I2 +{ + static void Main() + { + I2 x = new Test2(); + var y = -x; + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (32,17): error CS0035: Operator '-' is ambiguous on an operand of type 'I2' + // var y = -x; + Diagnostic(ErrorCode.ERR_AmbigUnaryOp, "-x").WithArguments("-", "I2").WithLocation(32, 17) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); + Assert.Equal(2, symbolInfo.CandidateSymbols.Length); + AssertEx.Equal("I1.operator -(I1)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("I3.operator -(I3)", symbolInfo.CandidateSymbols[1].ToDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + [WorkItem("https://github.com/dotnet/roslyn/issues/78830")] + public void Unary_015_Consumption_ExtensionAmbiguity() + { + var src = $$$""" +public interface I1; +public interface I3; +public interface I4 : I1, I3; +public interface I2 : I4; + +public static class Extensions1 +{ + extension(I2) + { + public static I2 operator -(I2 x) => x; + } +} + +namespace NS1 +{ + public static class Extensions2 + { + extension(I1) + { + public static I1 operator -(I1 x) => x; + } + + extension(I3) + { + public static I3 operator -(I3 x) => x; + } + } + + class Test2 : I2 + { + static void Main() + { + I2 x = new Test2(); + var y = -x; + } + } +} +"""; + + var comp = CreateCompilation(src); + + // https://github.com/dotnet/roslyn/issues/78830: We might want to include more information into the error. Like what methods conflict. + comp.VerifyEmitDiagnostics( + // (34,21): error CS0035: Operator '-' is ambiguous on an operand of type 'I2' + // var y = -x; + Diagnostic(ErrorCode.ERR_AmbigUnaryOp, "-x").WithArguments("-", "I2").WithLocation(34, 21) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); + Assert.Equal(2, symbolInfo.CandidateSymbols.Length); + AssertEx.Equal("NS1.Extensions2.extension(I1).operator -(I1)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("NS1.Extensions2.extension(I3).operator -(I3)", symbolInfo.CandidateSymbols[1].ToDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Theory] + [CombinatorialData] + public void Unary_016_Consumption_Lifted([CombinatorialValues("+", "-", "!", "~")] string op) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op}}}(S1 x) + { + System.Console.Write("operator1"); + return new S1 { F = x.F + 1 }; + } + } +} + +public struct S1 +{ + public int F; +} +"""; + var src2 = $$$""" +class Program +{ + static void Main() + { + S1? s1 = new S1() { F = 101 }; + var s2 = {{{op}}}s1; + System.Console.Write(":"); + System.Console.Write(s2.Value.F); + System.Console.Write(":"); + s1 = null; + s2 = {{{op}}}s1; + System.Console.Write(s2?.F ?? -1); + } +} +"""; + + var comp1 = CreateCompilation([src1, src2], options: TestOptions.DebugExe); + CompileAndVerify(comp1, expectedOutput: "operator1:102:-1").VerifyDiagnostics(); + + var comp2 = CreateCompilation([src1, src2], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: "operator1:102:-1").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1.ToMetadataReference()], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (6,18): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // var s2 = +s1; + Diagnostic(ErrorCode.ERR_FeatureInPreview, op + "s1").WithArguments("extensions").WithLocation(6, 18), + // (11,14): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // s2 = +s1; + Diagnostic(ErrorCode.ERR_FeatureInPreview, op + "s1").WithArguments("extensions").WithLocation(11, 14) + ); + } + + [Fact] + public void Unary_017_Consumption_LiftedIsWorse() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator +(S1 x) => throw null; + } + extension(S1?) + { + public static S1? operator +(S1? x) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? s1 = new S1(); + _ = +s1; + System.Console.Write(":"); + s1 = null; + _ = +s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1:operator1").VerifyDiagnostics(); + } + + [Fact] + public void Unary_018_Consumption_ExtendedTypeIsNullable() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1?) + { + public static S1? operator +(S1? x) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1 s1 = new S1(); + _ = +s1; + Extensions1.op_UnaryPlus(s1); + + S1? s2 = new S1(); + _ = +s2; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (21,13): error CS0023: Operator '+' cannot be applied to operand of type 'S1' + // _ = +s1; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "+s1").WithArguments("+", "S1").WithLocation(21, 13) + ); + } + + [Fact] + public void Unary_019_Consumption_ReceiverTypeMismatch() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator +(S2 x) => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{ + public static implicit operator S2(S1 x) => default; +} + +class Program +{ + static void Main() + { + S1 s1 = new S1(); + _ = +s1; + Extensions1.op_UnaryPlus(s1); + + S1? s2 = new S1(); + _ = +s2; + Extensions1.op_UnaryPlus(s2); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (22,13): error CS0023: Operator '+' cannot be applied to operand of type 'S1' + // _ = +s1; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "+s1").WithArguments("+", "S1").WithLocation(22, 13), + // (26,13): error CS0023: Operator '+' cannot be applied to operand of type 'S1?' + // _ = +s2; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "+s2").WithArguments("+", "S1?").WithLocation(26, 13), + // (27,34): error CS1503: Argument 1: cannot convert from 'S1?' to 'S2' + // Extensions1.op_UnaryPlus(s2); + Diagnostic(ErrorCode.ERR_BadArgType, "s2").WithArguments("1", "S1?", "S2").WithLocation(27, 34) + ); + } + + [Fact] + public void Unary_020_Consumption_Generic() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) where T : struct + { + public static S1 operator +(S1 x) + { + System.Console.Write(typeof(T).ToString()); + return x; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + var s1 = new S1(); + s1 = +s1; + Extensions1.op_UnaryPlus(s1); + + S1? s2 = new S1(); + _ = (+s2).GetValueOrDefault(); + s2 = null; + System.Console.Write(":"); + _ = (+s2).GetValueOrDefault(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "System.Int32System.Int32System.Int32:").VerifyDiagnostics(); + } + + [Fact] + public void Unary_020_Consumption_Generic_Worse() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator +(S1 x) + { + System.Console.Write("[S1]"); + return x; + } + } + + extension(S1?) + { + public static S1? operator +(S1? x) + { + System.Console.Write("[S1?]"); + return x; + } + } + + extension(S1) + { + public static S1 operator +(S1 x) + { + System.Console.Write("[S1]"); + return x; + } + } + + extension(S2) + { + public static S2 operator +(in S2 x) => throw null; + + public static S2 operator +(S2 x) + { + System.Console.Write("[S2]"); + return x; + } + } + + extension(S2) + { + public static S2 operator +(in S2 x) + { + System.Console.Write("[in S2]"); + return x; + } + } +} + +public struct S1 +{} + +public struct S2 +{} + +class Program +{ + static void Main() + { + var s11 = new S1(); + s11 = +s11; + Extensions1.op_UnaryPlus(s11); + + System.Console.WriteLine(); + + var s12 = new S1(); + s12 = +s12; + Extensions1.op_UnaryPlus(s12); + + System.Console.WriteLine(); + + var s21 = new S2(); + s21 = +s21; + Extensions1.op_UnaryPlus(s21); + + System.Console.WriteLine(); + + var s22 = new S2(); + s22 = +s22; + Extensions1.op_UnaryPlus(s22); + + System.Console.WriteLine(); + + S1? s13 = new S1(); + s13 = +s13; + s13 = null; + s13 = +s13; + + System.Console.WriteLine(); + + S1? s14 = new S1(); + s14 = +s14; + s14 = null; + s14 = +s14; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: @" +[S1][S1] +[S1][S1] +[in S2][in S2] +[S2][S2] +[S1] +[S1?][S1?] +").VerifyDiagnostics(); + } + + [Fact] + public void Unary_021_Consumption_Generic_ConstraintsViolation() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) where T : class + { + public static S1 operator +(S1 x) => throw null; + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + var s1 = new S1(); + _ = +s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (17,13): error CS0023: Operator '+' cannot be applied to operand of type 'S1' + // _ = +s1; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "+s1").WithArguments("+", "S1").WithLocation(17, 13) + ); + } + + [Fact] + public void Unary_022_Consumption_OverloadResolutionPriority() + { + var src = $$$""" +using System.Runtime.CompilerServices; + +public static class Extensions1 +{ + extension(C1) + { + [OverloadResolutionPriority(1)] + public static C1 operator +(C1 x) + { + System.Console.Write("C1"); + return x; + } + } + extension(C2) + { + public static C2 operator +(C2 x) + { + System.Console.Write("C2"); + return x; + } + } + extension(C3) + { + public static C3 operator +(C3 x) + { + System.Console.Write("C3"); + return x; + } + } + extension(C4) + { + public static C4 operator +(C4 x) + { + System.Console.Write("C4"); + return x; + } + } +} + +public class C1; +public class C2 : C1; + +public class C3; +public class C4 : C3; + +class Program +{ + static void Main() + { + var c2 = new C2(); + _ = +c2; + var c4 = new C4(); + _ = +c4; + } +} +"""; + + var comp = CreateCompilation([src, OverloadResolutionPriorityAttributeDefinition], options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "C1C4").VerifyDiagnostics(); + } + + [Fact] + public void Unary_023_Consumption_Checked() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator -(C1 x) + { + System.Console.Write("regular"); + return x; + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = -c1; + + checked + { + _ = -c1; + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "regularregular").VerifyDiagnostics(); + } + + [Fact] + public void Unary_023_Consumption_Checked_CheckedFormNotSupported() + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator +(C1 x) => throw null; + public static C1 operator checked +(C1 x) => throw null; + } +} + +public class C1; +"""; + + var comp1 = CreateCompilation(src1); + comp1.VerifyEmitDiagnostics( + // (6,35): error CS9023: User-defined operator '+' cannot be declared checked + // public static C1 operator checked +(C1 x) => throw null; + Diagnostic(ErrorCode.ERR_OperatorCantBeChecked, "checked").WithArguments("+").WithLocation(6, 35), + // (6,43): error CS0111: Type 'Extensions1' already defines a member called 'op_UnaryPlus' with the same parameter types + // public static C1 operator checked +(C1 x) => throw null; + Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "+").WithArguments("op_UnaryPlus", "Extensions1").WithLocation(6, 43) + ); + + var src2 = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator +(C1 x) + { + System.Console.Write("regular"); + return x; + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = +c1; + + checked + { + _ = +c1; + } + } +} +"""; + + var comp2 = CreateCompilation(src2, options: TestOptions.DebugExe); + CompileAndVerify(comp2, expectedOutput: "regularregular").VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void Unary_024_Consumption_Checked([CombinatorialValues("struct", "class")] string typeKind) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator -(C1 x) + { + System.Console.Write("regular"); + return x; + } + public static C1 operator checked -(C1 x) + { + System.Console.Write("checked"); + return x; + } + } +} + +public {{{typeKind}}} C1; +"""; + var src2 = $$$""" +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = -c1; + + checked + { + _ = -c1; + } + } +} +"""; + + var comp1 = CreateCompilation([src1, src2], options: TestOptions.DebugExe); + CompileAndVerify(comp1, expectedOutput: "regularchecked").VerifyDiagnostics(); + + var comp2 = CreateCompilation([src1, src2], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: "regularchecked").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1.ToMetadataReference()], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (6,13): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = -c1; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "-c1").WithArguments("extensions").WithLocation(6, 13), + // (10,17): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = -c1; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "-c1").WithArguments("extensions").WithLocation(10, 17) + ); + } + + [Fact] + public void Unary_025_Consumption_Checked() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator -(C1 x) + { + System.Console.Write("regular"); + return x; + } + } + extension(C1) + { + public static C1 operator checked -(C1 x) + { + System.Console.Write("checked"); + return x; + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = -c1; + + checked + { + _ = -c1; + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "regularchecked").VerifyDiagnostics(); + } + + [Fact] + public void Unary_026_Consumption_Checked() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator -(C1 x) + { + return x; + } + + public static C1 operator checked -(C1 x) + { + return x; + } + } +} + +public static class Extensions2 +{ + extension(C1) + { + public static C1 operator -(C1 x) + { + return x; + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = -c1; + + checked + { + _ = -c1; + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (35,13): error CS0035: Operator '-' is ambiguous on an operand of type 'C1' + // _ = -c1; + Diagnostic(ErrorCode.ERR_AmbigUnaryOp, "-c1").WithArguments("-", "C1").WithLocation(35, 13), + // (39,17): error CS0035: Operator '-' is ambiguous on an operand of type 'C1' + // _ = -c1; + Diagnostic(ErrorCode.ERR_AmbigUnaryOp, "-c1").WithArguments("-", "C1").WithLocation(39, 17) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().Last(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); + Assert.Equal(2, symbolInfo.CandidateSymbols.Length); + AssertEx.Equal("Extensions1.extension(C1).operator checked -(C1)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("Extensions2.extension(C1).operator -(C1)", symbolInfo.CandidateSymbols[1].ToDisplayString()); + } + + [Fact] + public void Unary_027_Consumption_CheckedLiftedIsWorse() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator -(S1 x) => throw null; + public static S1 operator checked -(S1 x) => throw null; + } + extension(S1?) + { + public static S1? operator -(S1? x) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? s1 = new S1(); + _ = -s1; + System.Console.Write(":"); + + checked + { + _ = -s1; + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1:operator1").VerifyDiagnostics(); + } + + [Fact] + public void Unary_028_Consumption_OverloadResolutionPlusRegularVsChecked() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator -(C1 x) + { + System.Console.Write("C1"); + return x; + } + public static C1 operator checked -(C1 x) + { + System.Console.Write("checkedC1"); + return x; + } + } + extension(C2) + { + public static C2 operator -(C2 x) + { + System.Console.Write("C2"); + return x; + } + } +} + +public class C1; +public class C2 : C1; +public class C3 : C1; + +class Program +{ + static void Main() + { + var c3 = new C3(); + _ = -c3; + + checked + { + _ = -c3; + } + + var c2 = new C2(); + _ = -c2; + + checked + { + _ = -c2; + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "C1checkedC1C2C2").VerifyDiagnostics(); + } + + [Fact] + public void Unary_029_Consumption() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1? operator +(S1? x) + { + System.Console.Write("operator1"); + return x; + } + + public static void M1(S1? x) {} + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? s1 = new S1(); +#line 21 + _ = +s1; + S1 s2 = new S1(); + _ = +s2; + + System.Nullable.M1(s1); + S1.M1(s1); + S1.M1(s2); + } +} + +public static class Extensions2 +{ + extension(S2) + { + public static S2? operator +(S2 x) + { + return x; + } + } +} + +public struct S2 +{} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + + comp.VerifyEmitDiagnostics( + // (5,36): error CS9317: The parameter of a unary operator must be the extended type. + // public static S1? operator +(S1? x) + Diagnostic(ErrorCode.ERR_BadExtensionUnaryOperatorSignature, "+").WithLocation(5, 36), + // (21,13): error CS0023: Operator '+' cannot be applied to operand of type 'S1?' + // _ = +s1; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "+s1").WithArguments("+", "S1?").WithLocation(21, 13), + // (25,9): error CS1929: 'S1?' does not contain a definition for 'M1' and the best extension method overload 'Extensions1.extension(S1).M1(S1?)' requires a receiver of type 'S1' + // System.Nullable.M1(s1); + Diagnostic(ErrorCode.ERR_BadInstanceArgType, "System.Nullable").WithArguments("S1?", "M1", "Extensions1.extension(S1).M1(S1?)", "S1").WithLocation(25, 9) + ); + } + + [Fact] + public void Unary_030_Consumption_OnObject() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object) + { + public static object operator +(object x) + { + System.Console.Write("operator1"); + return x; + } + } +} + +class Program +{ + static void Main() + { + var s1 = new object(); + _ = +s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1").VerifyDiagnostics(); + } + + [Fact] + public void Unary_031_Consumption_NotOnDynamic() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object) + { + public static object operator +(object x) + { + System.Console.Write("operator1"); + return x; + } + } +} + +class Program +{ + static void Main() + { + dynamic s1 = new object(); + try + { + _ = +s1; + } + catch + { + System.Console.Write("exception"); + } + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "exception").VerifyDiagnostics(); + } + + [Fact] + public void Unary_032_Consumption_BadOperand() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object) + { + public static object operator +(object x) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} +class Program +{ + static void Main() + { + _ = +null; + _ = +default; + _ = +new(); + _ = +(() => 1); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (19,13): error CS8310: Operator '+' cannot be applied to operand '' + // _ = +null; + Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "+null").WithArguments("+", "").WithLocation(19, 13), + // (20,14): error CS8716: There is no target type for the default literal. + // _ = +default; + Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(20, 14), + // (21,14): error CS8754: There is no target type for 'new()' + // _ = +new(); + Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(21, 14), + // (22,13): error CS0023: Operator '+' cannot be applied to operand of type 'lambda expression' + // _ = +(() => 1); + Diagnostic(ErrorCode.ERR_BadUnaryOp, "+(() => 1)").WithArguments("+", "lambda expression").WithLocation(22, 13) + ); + } + + [Fact] + public void Unary_033_Consumption_BadReceiver() + { + var src = $$$""" +public static class Extensions1 +{ + extension(__arglist) + { + public static object operator +(object x) + { + return x; + } + } +} + +class Program +{ + static void Main() + { + var s1 = new object(); + _ = +s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (3,15): error CS1669: __arglist is not valid in this context + // extension(__arglist) + Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(3, 15), + // (5,39): error CS9317: The parameter of a unary operator must be the extended type. + // public static object operator +(object x) + Diagnostic(ErrorCode.ERR_BadExtensionUnaryOperatorSignature, "+").WithLocation(5, 39), + // (17,13): error CS0023: Operator '+' cannot be applied to operand of type 'object' + // _ = +s1; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "+s1").WithArguments("+", "object").WithLocation(17, 13) + ); + } + + [Fact] + public void Unary_034_Consumption_Checked_Generic() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator -(C1 x) + { + System.Console.Write("regular"); + return x; + } + } + extension(C1) + { + public static C1 operator checked -(C1 x) + { + System.Console.Write("checked"); + return x; + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = -c1; + + checked + { + _ = -c1; + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "regularchecked").VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void Unary_035_Consumption_True(bool fromMetadata, [CombinatorialValues("struct", "class")] string typeKind) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static bool operator true(S1 x) + { + System.Console.Write("operator1"); + return x.F; + } + public static bool operator false(S1 x) => throw null; + } +} + +public {{{typeKind}}} S1 +{ + public bool F; +} +"""; + + var src2 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1() { F = true }; + if (s1) + { + System.Console.Write(":true:"); + } + + s1 = new S1() { F = false }; + if (s1) + {} + else + { + System.Console.Write(":false"); + } + } +} +"""; + + var comp1 = CreateCompilation(src1); + var comp1Ref = fromMetadata ? comp1.EmitToImageReference() : comp1.ToMetadataReference(); + + var comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp2, expectedOutput: "operator1:true:operator1:false").VerifyDiagnostics(); + + var tree = comp2.SyntaxTrees.First(); + var model = comp2.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First().Condition; + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("s1", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S1", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: "operator1:true:operator1:false").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (6,13): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // if (s1) + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s1").WithArguments("extensions").WithLocation(6, 13), + // (12,13): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // if (s1) + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s1").WithArguments("extensions").WithLocation(12, 13) + ); + + var src3 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1(); + Extensions1.op_True(s1); + } +} +"""; + var comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp3, expectedOutput: "operator1").VerifyDiagnostics(); + + comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp3, expectedOutput: "operator1").VerifyDiagnostics(); + + comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + CompileAndVerify(comp3, expectedOutput: "operator1").VerifyDiagnostics(); + + var src4 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1(); + s1.op_True(); + S1.op_True(s1); + } +} +"""; + var comp4 = CreateCompilation(src4, references: [comp1Ref]); + comp4.VerifyEmitDiagnostics( + // (6,12): error CS1061: 'S1' does not contain a definition for 'op_True' and no accessible extension method 'op_True' accepting a first argument of type 'S1' could be found (are you missing a using directive or an assembly reference?) + // s1.op_True(); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "op_True").WithArguments("S1", "op_True").WithLocation(6, 12), + // (7,12): error CS0117: 'S1' does not contain a definition for 'op_True' + // S1.op_True(s1); + Diagnostic(ErrorCode.ERR_NoSuchMember, "op_True").WithArguments("S1", "op_True").WithLocation(7, 12) + ); + } + + [Fact] + public void Unary_036_Consumption_True_ConversionComesFirst() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static bool operator true(S2 x) => throw null; + public static bool operator false(S2 x) => throw null; + } +} + +public struct S2 +{ + public static implicit operator bool(S2 x) + { + System.Console.Write("operator2"); + return true; + } +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + if(s2) + {} + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2").VerifyDiagnostics(); + } + + [Fact] + public void Unary_037_Consumption_True_NonExtensionComesFirst() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static bool operator true(S2 x) => throw null; + public static bool operator false(S2 x) => throw null; + } +} + +public struct S2 +{ + public static bool operator true(S2 x) + { + System.Console.Write("operator2"); + return true; + } + public static bool operator false(S2 x) => throw null; +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + if(s2) + {} + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2").VerifyDiagnostics(); + } + + [Fact] + public void Unary_038_Consumption_True_ScopeByScope() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static bool operator true(S1 x) => throw null; + public static bool operator false(S1 x) => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{} + +namespace NS1 +{ + public static class Extensions2 + { + extension(S1) + { + public static bool operator true(S1 x) + { + System.Console.Write("operator1"); + return true; + } + public static bool operator false(S1 x) => throw null; + } + } + + namespace NS2 + { + public static class Extensions3 + { + extension(S2) + { + public static bool operator true(S2 x) => throw null; + public static bool operator false(S2 x) => throw null; + } + } + + class Program + { + static void Main() + { + var s1 = new S1(); + if(s1) + {} + } + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1").VerifyDiagnostics(); + } + + [Fact] + public void Unary_039_Consumption_True_NonExtensionAmbiguity() + { + var src = $$$""" +public interface I1 +{ + public static bool operator true(I1 x) => true; + public static bool operator false(I1 x) => false; +} + +public interface I3 +{ + public static bool operator true(I3 x) => true; + public static bool operator false(I3 x) => false; +} + +public interface I4 : I1, I3 +{ +} + +public interface I2 : I4 +{ +} + +public static class Extensions1 +{ + extension(I2) + { + public static bool operator true(I2 x) => true; + public static bool operator false(I2 x) => false; + } +} + +class Test2 : I2 +{ + static void Main() + { + I2 x = new Test2(); + if(x) + {} + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (35,12): error CS0029: Cannot implicitly convert type 'I2' to 'bool' + // if(x) + Diagnostic(ErrorCode.ERR_NoImplicitConv, "x").WithArguments("I2", "bool").WithLocation(35, 12) + ); + } + + [Fact] + public void Unary_040_Consumption_True_ExtensionAmbiguity() + { + var src = $$$""" +public interface I1; +public interface I3; +public interface I4 : I1, I3; +public interface I2 : I4; + +public static class Extensions1 +{ + extension(I2) + { + public static bool operator true(I2 x) => true; + public static bool operator false(I2 x) => false; + } +} + +namespace NS1 +{ + public static class Extensions2 + { + extension(I1) + { + public static bool operator true(I1 x) => true; + public static bool operator false(I1 x) => false; + } + + extension(I3) + { + public static bool operator true(I3 x) => true; + public static bool operator false(I3 x) => false; + } + } + + class Test2 : I2 + { + static void Main() + { + I2 x = new Test2(); + if(x) + {} + } + } +} +"""; + + var comp = CreateCompilation(src); + + comp.VerifyEmitDiagnostics( + // (37,16): error CS0029: Cannot implicitly convert type 'I2' to 'bool' + // if(x) + Diagnostic(ErrorCode.ERR_NoImplicitConv, "x").WithArguments("I2", "bool").WithLocation(37, 16) + ); + } + + [Fact] + public void Unary_041_Consumption_True_NoLiftedForm() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static bool operator true(S1 x) + { + System.Console.Write("operator1"); + return true; + } + public static bool operator false(S1 x) => throw null; + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? s1 = new S1(); + if (s1) + {} + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (22,13): error CS0029: Cannot implicitly convert type 'S1?' to 'bool' + // if (s1) + Diagnostic(ErrorCode.ERR_NoImplicitConv, "s1").WithArguments("S1?", "bool").WithLocation(22, 13) + ); + } + + [Fact] + public void Unary_042_Consumption_True_ExtendedTypeIsNullable() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1?) + { + public static bool operator true(S1? x) + { + System.Console.Write("operator1"); + return true; + } + public static bool operator false(S1? x) => throw null; + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1 s1 = new S1(); + if (s1) + {} + Extensions1.op_True(s1); + + S1? s2 = new S1(); + if (s2) + {} + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (22,13): error CS0029: Cannot implicitly convert type 'S1' to 'bool' + // if (s1) + Diagnostic(ErrorCode.ERR_NoImplicitConv, "s1").WithArguments("S1", "bool").WithLocation(22, 13) + ); + } + + [Fact] + public void Unary_043_Consumption_True() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static bool operator true(S1? x) + { + System.Console.Write("operator1"); + return true; + } + public static bool operator false(S1? x) => throw null; + + public static void M1(S1? x) {} + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? s1 = new S1(); +#line 22 + if (s1) + {} + S1 s2 = new S1(); + if (s2) + {} + + System.Nullable.M1(s1); + S1.M1(s1); + S1.M1(s2); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + + comp.VerifyEmitDiagnostics( + // (5,37): error CS9317: The parameter of a unary operator must be the extended type. + // public static bool operator true(S1? x) + Diagnostic(ErrorCode.ERR_BadExtensionUnaryOperatorSignature, "true").WithLocation(5, 37), + // (10,37): error CS9317: The parameter of a unary operator must be the extended type. + // public static bool operator false(S1? x) => throw null; + Diagnostic(ErrorCode.ERR_BadExtensionUnaryOperatorSignature, "false").WithLocation(10, 37), + // (22,13): error CS0029: Cannot implicitly convert type 'S1?' to 'bool' + // if (s1) + Diagnostic(ErrorCode.ERR_NoImplicitConv, "s1").WithArguments("S1?", "bool").WithLocation(22, 13), + // (28,9): error CS1929: 'S1?' does not contain a definition for 'M1' and the best extension method overload 'Extensions1.extension(S1).M1(S1?)' requires a receiver of type 'S1' + // System.Nullable.M1(s1); + Diagnostic(ErrorCode.ERR_BadInstanceArgType, "System.Nullable").WithArguments("S1?", "M1", "Extensions1.extension(S1).M1(S1?)", "S1").WithLocation(28, 9) + ); + } + + [Fact] + public void Unary_044_Consumption_True_OnObject() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object) + { + public static bool operator true(object x) + { + System.Console.Write("operator1"); + return true; + } + public static bool operator false(object x) => throw null; + } +} + +class Program +{ + static void Main() + { + var s1 = new object(); + if (s1) + {} + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1").VerifyDiagnostics(); + } + + [Fact] + public void Unary_045_Consumption_True_NotOnDynamic() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object) + { + public static bool operator true(object x) + { + System.Console.Write("operator1"); + return true; + } + public static bool operator false(object x) => throw null; + } +} + +class Program +{ + static void Main() + { + dynamic s1 = new object(); + try + { + if (s1) + {} + } + catch + { + System.Console.Write("exception"); + } + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "exception").VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void Unary_046_Consumption_TupleComparison(bool fromMetadata) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static bool operator true(S1 x) => throw null; + public static bool operator false(S1 x) + { + System.Console.Write("operator1"); + return true; + } + } +} + +public struct S1 +{ + public static S1 operator ==(S1 x, S1 y) + { + return x; + } + public static S1 operator !=(S1 x, S1 y) => throw null; + + public override bool Equals(object o) => throw null; + public override int GetHashCode() => throw null; +} +"""; + + var src2 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1(); + if ((s1, 1) == (s1, 1)) + {} + } +} +"""; + + var comp1 = CreateCompilation(src1); + var comp1Ref = fromMetadata ? comp1.EmitToImageReference() : comp1.ToMetadataReference(); + + var comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp2, expectedOutput: "operator1").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: "operator1").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (6,13): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // if ((s1, 1) == (s1, 1)) + Diagnostic(ErrorCode.ERR_FeatureInPreview, "(s1, 1) == (s1, 1)").WithArguments("extensions").WithLocation(6, 13) + ); + } + + [Theory] + [CombinatorialData] + public void Unary_047_Consumption_ExpressionTree([CombinatorialValues("+", "-", "!", "~")] string op) + { + var src = $$$""" +using System.Linq.Expressions; + +public static class Extensions1 +{ + extension(S1 s1) + { + public static S1 operator {{{op}}}(S1 x) + { + System.Console.Write("operator1"); + return x; + } + + public void Test() + { + Expression> ex = (s1) => {{{op}}}s1; + ex.Compile()(s1); + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + Expression> ex = (s1) => {{{op}}}s1; + + var s1 = new S1(); + ex.Compile()(s1); + + s1.Test(); + + System.Console.Write(":"); + System.Console.Write(ex); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1operator1:s1 => " + (op is "!" or "~" ? "Not(" : op) + "s1" + (op is "!" or "~" ? ")" : "")).VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void Unary_048_Consumption_Lifted_ExpressionTree([CombinatorialValues("+", "-", "!", "~")] string op) + { + var src = $$$""" +using System.Linq.Expressions; + +public static class Extensions1 +{ + extension(S1 s1) + { + public static S1 operator {{{op}}}(S1 x) + { + System.Console.Write("operator1"); + return x; + } + + public void Test() + { + Expression> ex = (s1) => {{{op}}}s1; + var d = ex.Compile(); + + d(s1); + System.Console.Write(":"); + d(null); + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + Expression> ex = (s1) => {{{op}}}s1; + + var s1 = new S1(); + var d = ex.Compile(); + + d(s1); + System.Console.Write(":"); + d(null); + + System.Console.Write(":"); + s1.Test(); + + System.Console.Write(":"); + System.Console.Write(ex); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1::operator1::s1 => " + (op is "!" or "~" ? "Not(" : op) + "s1" + (op is "!" or "~" ? ")" : "")).VerifyDiagnostics(); + } + + [Fact] + public void Unary_049_Consumption_True_ExpressionTree() + { + var src = $$$""" +using System.Linq.Expressions; + +public static class Extensions1 +{ + extension(S1 s1) + { + public static bool operator true(S1 x) + { + System.Console.Write("operator1"); + return true; + } + public static bool operator false(S1 x) => throw null; + + public void Test() + { + Expression> ex = (s1) => s1 ? 1 : 0; + ex.Compile()(s1); + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + Expression> ex = (s1) => s1 ? 1 : 0; + + var s1 = new S1(); + ex.Compile()(s1); + + s1.Test(); + + System.Console.Write(":"); + System.Console.Write(ex); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1operator1:s1 => IIF(op_True(s1), 1, 0)").VerifyDiagnostics(); + } + + [Fact] + public void Unary_050_Consumption_True_ExpressionTree() + { + var src = $$$""" +using System.Linq.Expressions; + +public static class Extensions1 +{ + extension(S1 s1) + { + public static bool operator true(S1 x) + { + System.Console.Write("operator1"); + return true; + } + public static bool operator false(S1 x) => throw null; + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + Expression> ex = (s1) => s1 ? 1 : 0; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (23,56): error CS0029: Cannot implicitly convert type 'S1?' to 'bool' + // Expression> ex = (s1) => s1 ? 1 : 0; + Diagnostic(ErrorCode.ERR_NoImplicitConv, "s1").WithArguments("S1?", "bool").WithLocation(23, 56) + ); + } + + [Fact] + public void Unary_051_Consumption_True_ExpressionTree() + { + var src = $$$""" +using System.Linq.Expressions; + +public static class Extensions1 +{ + extension(S1? s1) + { + public static bool operator true(S1? x) + { + System.Console.Write("operator1"); + return true; + } + public static bool operator false(S1? x) => throw null; + + public void Test() + { + Expression> ex = (s1) => s1 ? 1 : 0; + ex.Compile()(s1); + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + Expression> ex = (s1) => s1 ? 1 : 0; + + S1? s1 = new S1(); + ex.Compile()(s1); + + s1.Test(); + + System.Console.Write(":"); + System.Console.Write(ex); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1operator1:s1 => IIF(op_True(s1), 1, 0)").VerifyDiagnostics(); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedUnaryOperator_RefStruct + /// + [Fact] + public void Unary_052_RefSafety() + { + var source = """ +class C +{ + S M1() + { + S s; + s = +s; // 1 + return s; + } + + S M2() + { + return +new S(); // 2 + } + + S M3(in S x) + { + S s; + s = +x; // 3 + return s; + } + + S M4(in S x) + { + return +x; + } + + S M4s(scoped in S x) + { + return +x; // 4 + } + + S M5(in S x) + { + S s = +x; + return s; + } + + S M5s(scoped in S x) + { + S s = +x; + return s; // 5 + } + + S M6() + { + S s = +new S(); + return s; // 6 + } + + void M7(in S x) + { + scoped S s; + s = +x; + s = +new S(); + } +} + +ref struct S +{ +} + +static class Extensions +{ + extension(S) + { + public static S operator+(in S s) => throw null; + } +} +"""; + CreateCompilation(source).VerifyDiagnostics( + // (6,13): error CS8347: Cannot use a result of 'Extensions.extension(S).operator +(in S)' in this context because it may expose variables referenced by parameter 's' outside of their declaration scope + // s = +s; // 1 + Diagnostic(ErrorCode.ERR_EscapeCall, "+s").WithArguments("Extensions.extension(S).operator +(in S)", "s").WithLocation(6, 13), + // (6,14): error CS8168: Cannot return local 's' by reference because it is not a ref local + // s = +s; // 1 + Diagnostic(ErrorCode.ERR_RefReturnLocal, "s").WithArguments("s").WithLocation(6, 14), + // (12,16): error CS8347: Cannot use a result of 'Extensions.extension(S).operator +(in S)' in this context because it may expose variables referenced by parameter 's' outside of their declaration scope + // return +new S(); // 2 + Diagnostic(ErrorCode.ERR_EscapeCall, "+new S()").WithArguments("Extensions.extension(S).operator +(in S)", "s").WithLocation(12, 16), + // (12,17): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference + // return +new S(); // 2 + Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "new S()").WithLocation(12, 17), + // (18,13): error CS8347: Cannot use a result of 'Extensions.extension(S).operator +(in S)' in this context because it may expose variables referenced by parameter 's' outside of their declaration scope + // s = +x; // 3 + Diagnostic(ErrorCode.ERR_EscapeCall, "+x").WithArguments("Extensions.extension(S).operator +(in S)", "s").WithLocation(18, 13), + // (18,14): error CS9077: Cannot return a parameter by reference 'x' through a ref parameter; it can only be returned in a return statement + // s = +x; // 3 + Diagnostic(ErrorCode.ERR_RefReturnOnlyParameter, "x").WithArguments("x").WithLocation(18, 14), + // (29,16): error CS8347: Cannot use a result of 'Extensions.extension(S).operator +(in S)' in this context because it may expose variables referenced by parameter 's' outside of their declaration scope + // return +x; // 4 + Diagnostic(ErrorCode.ERR_EscapeCall, "+x").WithArguments("Extensions.extension(S).operator +(in S)", "s").WithLocation(29, 16), + // (29,17): error CS9075: Cannot return a parameter by reference 'x' because it is scoped to the current method + // return +x; // 4 + Diagnostic(ErrorCode.ERR_RefReturnScopedParameter, "x").WithArguments("x").WithLocation(29, 17), + // (41,16): error CS8352: Cannot use variable 's' in this context because it may expose referenced variables outside of their declaration scope + // return s; // 5 + Diagnostic(ErrorCode.ERR_EscapeVariable, "s").WithArguments("s").WithLocation(41, 16), + // (47,16): error CS8352: Cannot use variable 's' in this context because it may expose referenced variables outside of their declaration scope + // return s; // 6 + Diagnostic(ErrorCode.ERR_EscapeVariable, "s").WithArguments("s").WithLocation(47, 16) + ); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedUnaryOperator_RefStruct_Scoped + /// + [Fact] + public void Unary_053_RefSafety() + { + var source = """ +ref struct R +{ + private ref readonly int _i; + public R(in int i) { _i = ref i; } +} +class Program +{ + static R F() + { + return !new R(0); + } +} + +static class Extensions +{ + extension(R) + { + public static R operator !(scoped R r) => default; + } +} +"""; + CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics(); + } + + [Fact] + public void Unary_054_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator -(C1 x) + { + System.Console.Write("operator1"); + return x; + } + } + + extension(C2) + { + public static C2 operator -(C2? x) + { + System.Console.Write("operator2"); + return new C2(); + } + } +} + +public class C1 +{} + +public class C2 +{} + +class Program +{ + static void Main() + { + C1? x = null; +#line 23 + _ = -x; + C1 y = new C1(); + y = -y; + C2? z = null; + _ = -z; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (23,14): warning CS8604: Possible null reference argument for parameter 'x' in 'C1 extension(C1).operator -(C1 x)'. + // _ = -x; + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "C1 extension(C1).operator -(C1 x)").WithLocation(23, 14) + ); + } + + [Fact] + public void Unary_055_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1) + { + public static C1? operator -(C1 x) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public class C1 +{} + +class Program +{ + static void Main() + { + var x = new C1(); + C1 y = -x; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (23,16): warning CS8600: Converting null literal or possible null value to non-nullable type. + // C1 y = -x; + Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "-x").WithLocation(23, 16) + ); + } + + [Fact] + public void Unary_056_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(T) + { + public static T operator -(T x) + { + return x; + } + } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + C2? x = null; + (-x).ToString(); + var y = new C2(); + (-y).ToString(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (22,10): warning CS8602: Dereference of a possibly null reference. + // (-x).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "-x").WithLocation(22, 10) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNodes = tree.GetRoot().DescendantNodes().OfType().ToArray(); + + Assert.Equal(2, opNodes.Length); + AssertEx.Equal("Extensions1.extension(C2?).operator -(C2?)", model.GetSymbolInfo(opNodes[0]).Symbol.ToDisplayString()); + AssertEx.Equal("Extensions1.extension(C2).operator -(C2)", model.GetSymbolInfo(opNodes[1]).Symbol.ToDisplayString()); + } + + [Fact] + public void Unary_057_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1) where T : new() + { + public static T operator -(C1 x) + { + return x.F; + } + } +} + +public class C1 where T : new() +{ + public T F = new T(); +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = Get((C2?)null); + (-x).ToString(); + var y = Get(new C2()); + (-y).ToString(); + } + + static C1 Get(T x) where T : new() + { + return new C1(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (27,10): warning CS8602: Dereference of a possibly null reference. + // (-x).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "-x").WithLocation(27, 10) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNodes = tree.GetRoot().DescendantNodes().OfType().ToArray(); + + Assert.Equal(2, opNodes.Length); + AssertEx.Equal("Extensions1.extension(C1).operator -(C1)", model.GetSymbolInfo(opNodes[0]).Symbol.ToDisplayString()); + AssertEx.Equal("Extensions1.extension(C1).operator -(C1)", model.GetSymbolInfo(opNodes[1]).Symbol.ToDisplayString()); + } + + [Fact] + public void Unary_058_NullableAnalysis_Lifted() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(S1) where T : new() + { + public static S1 operator -(S1 x) + { + return x; + } + } +} + +public struct S1 where T : new() +{ + public T F; +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = -Get((C2?)null); + + if (x != null) + x.Value.F.ToString(); + + var y = -Get(new C2()); + + if (y != null) + y.Value.F.ToString(); + } + + static S1? Get(T x) where T : new() + { + return new S1(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (29,13): warning CS8602: Dereference of a possibly null reference. + // x.Value.F.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Value.F").WithLocation(29, 13) + ); + } + + [Fact] + public void Unary_059_NullableAnalysis_Constraints() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(T) where T : notnull + { + public static object operator -(T x) + { + return x; + } + } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + C2? x = null; + (-x).ToString(); + var y = new C2(); + (-y).ToString(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (22,10): warning CS8714: The type 'C2?' cannot be used as type parameter 'T' in the generic type or method 'Extensions1.extension(T)'. Nullability of type argument 'C2?' doesn't match 'notnull' constraint. + // (-x).ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "-x").WithArguments("Extensions1.extension(T)", "T", "C2?").WithLocation(22, 10) + ); + } + + [Fact] + public void Unary_060_NullableAnalysis_Constraints() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1) where T : notnull, new() + { + public static T operator -(C1 x) + { + return x.F; + } + } +} + +public class C1 where T : new() +{ + public T F = new T(); +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = Get((C2?)null); + (-x).ToString(); + var y = Get(new C2()); + (-y).ToString(); + } + + static C1 Get(T x) where T : new() + { + return new C1(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (27,10): warning CS8714: The type 'C2?' cannot be used as type parameter 'T' in the generic type or method 'Extensions1.extension(C1)'. Nullability of type argument 'C2?' doesn't match 'notnull' constraint. + // (-x).ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "-x").WithArguments("Extensions1.extension(C1)", "T", "C2?").WithLocation(27, 10), + // (27,10): warning CS8602: Dereference of a possibly null reference. + // (-x).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "-x").WithLocation(27, 10) + ); + } + + [Fact] + public void Unary_061_NullableAnalysis_True() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1) + { + public static bool operator true(C1 x) => true; + public static bool operator false(C1 x) => false; + } + + extension(C2) + { + public static bool operator true(C2? x) => true; + public static bool operator false(C2? x) => false; + } +} + +public class C1 +{} + +public class C2 +{} + +class Program +{ + static void Main() + { + C1? x = null; +#line 20 + if (x) + {} + + C1 y = new C1(); + if (y) + {} + + C2? z= null; + if (z) + {} + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (20,13): warning CS8604: Possible null reference argument for parameter 'x' in 'bool extension(C1).operator true(C1 x)'. + // if (x) + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "bool extension(C1).operator true(C1 x)").WithLocation(20, 13) + ); + } + + [Fact] + public void Unary_062_NullableAnalysis_True_Constraints() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(T) where T : notnull + { + public static bool operator true(T x) => true; + public static bool operator false(T x) => false; + } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + C2? x = null; + if (x) + {} + + var y = new C2(); + if (y) + {} + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (20,13): warning CS8714: The type 'C2?' cannot be used as type parameter 'T' in the generic type or method 'Extensions1.extension(T)'. Nullability of type argument 'C2?' doesn't match 'notnull' constraint. + // if (x) + Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "x").WithArguments("Extensions1.extension(T)", "T", "C2?").WithLocation(20, 13) + ); + } + + [Fact] + public void Unary_063_Declaration_Extern() + { + var src = $$$""" +using System.Runtime.InteropServices; + +public static class Extensions1 +{ + extension(C2) + { + extern public static C2 operator -(C2 x) => x; + + [DllImport("something.dll")] + public static C2 operator !(C2 x) => x; + } +} + +public class C2 +{} +"""; + + var comp = CreateCompilation(src); + comp.VerifyDiagnostics( + // (7,42): error CS0179: 'Extensions1.extension(C2).operator -(C2)' cannot be extern and declare a body + // extern public static C2 operator -(C2 x) => x; + Diagnostic(ErrorCode.ERR_ExternHasBody, "-").WithArguments("Extensions1.extension(C2).operator -(C2)").WithLocation(7, 42), + // (9,10): error CS0601: The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member + // [DllImport("something.dll")] + Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(9, 10) + ); + } + + [Fact] + public void Unary_064_Declaration_Extern() + { + var source = """ +using System.Runtime.InteropServices; +static class E +{ + extension(C2) + { + [DllImport("something.dll")] + extern public static C2 operator -(C2 x); + } +} + +public class C2 +{} +"""; + var verifier = CompileAndVerify(source).VerifyDiagnostics(); + + verifier.VerifyTypeIL("E", """ +.class private auto ansi abstract sealed beforefieldinit E + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( + 01 00 00 00 + ) + // Nested Types + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + // Methods + .method private hidebysig specialname static + void '$' ( + class C2 '' + ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( + 01 00 00 00 + ) + // Method begins at RVA 0x206f + // Code size 1 (0x1) + .maxstack 8 + IL_0000: ret + } // end of method '<>E__0'::'$' + .method public hidebysig specialname static + class C2 op_UnaryNegation ( + class C2 x + ) cil managed + { + // Method begins at RVA 0x2071 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::op_UnaryNegation + } // end of class <>E__0 + // Methods + .method public hidebysig static pinvokeimpl("something.dll" winapi) + class C2 op_UnaryNegation ( + class C2 x + ) cil managed preservesig + { + } // end of method E::op_UnaryNegation +} // end of class E +""".Replace("[mscorlib]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[mscorlib]")); + } + + [Fact] + public void Unary_065_Declaration_Extern() + { + var source = """ +static class E +{ + extension(C2) + { + extern public static C2 operator -(C2 x); + } +} + +public class C2 +{} +"""; + var verifier = CompileAndVerify(source, verify: Verification.FailsPEVerify with { PEVerifyMessage = """ + Error: Method marked Abstract, Runtime, InternalCall or Imported must have zero RVA, and vice versa. + Type load failed. + """ }); + + verifier.VerifyDiagnostics( + // (5,42): warning CS0626: Method, operator, or accessor 'E.extension(C2).operator -(C2)' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. + // extern public static C2 operator -(C2 x); + Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "-").WithArguments("E.extension(C2).operator -(C2)").WithLocation(5, 42) + ); + + verifier.VerifyTypeIL("E", """ +.class private auto ansi abstract sealed beforefieldinit E + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( + 01 00 00 00 + ) + // Nested Types + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + // Methods + .method private hidebysig specialname static + void '$' ( + class C2 '' + ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( + 01 00 00 00 + ) + // Method begins at RVA 0x206f + // Code size 1 (0x1) + .maxstack 8 + IL_0000: ret + } // end of method '<>E__0'::'$' + .method public hidebysig specialname static + class C2 op_UnaryNegation ( + class C2 x + ) cil managed + { + // Method begins at RVA 0x2071 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::op_UnaryNegation + } // end of class <>E__0 + // Methods + .method public hidebysig static + class C2 op_UnaryNegation ( + class C2 x + ) cil managed + { + } // end of method E::op_UnaryNegation +} // end of class E +""".Replace("[mscorlib]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[mscorlib]")); + } + + [Fact] + public void Unary_066_Declaration_Extern() + { + var source = """ +static class E +{ + extension(C2) + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)] + extern public static C2 operator -(C2 x); + } +} + +public class C2 +{} +"""; + var verifier = CompileAndVerify(source).VerifyDiagnostics(); + + verifier.VerifyTypeIL("E", """ +.class private auto ansi abstract sealed beforefieldinit E + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( + 01 00 00 00 + ) + // Nested Types + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + // Methods + .method private hidebysig specialname static + void '$' ( + class C2 '' + ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( + 01 00 00 00 + ) + // Method begins at RVA 0x206f + // Code size 1 (0x1) + .maxstack 8 + IL_0000: ret + } // end of method '<>E__0'::'$' + .method public hidebysig specialname static + class C2 op_UnaryNegation ( + class C2 x + ) cil managed + { + // Method begins at RVA 0x2071 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::op_UnaryNegation + } // end of class <>E__0 + // Methods + .method public hidebysig static + class C2 op_UnaryNegation ( + class C2 x + ) cil managed internalcall + { + } // end of method E::op_UnaryNegation +} // end of class E +""".Replace("[mscorlib]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[mscorlib]")); + } + + [Theory] + [CombinatorialData] + public void Unary_067_Consumption_CRef([CombinatorialValues("!", "~")] string op) + { + var src = $$$""" +/// +/// +public static class E +{ + /// + extension(S1) + { + /// + public static S1 operator {{{op}}}(S1 x) => throw null; + } +} + +/// +public struct S1; +"""; + + var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreviewWithDocumentationComments); + comp.VerifyEmitDiagnostics(); + + var opName = UnaryOperatorName(op); + + var e = comp.GetMember("E"); + AssertEx.Equal($$$""" + + + + + +""", e.GetDocumentationCommentXml()); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + AssertEx.Equal([ + "(E.extension(S1).operator " + op + ", S1 E.<>E__0." + opName + "(S1 x))", + "(E.extension(S1).operator " + op + "(S1), S1 E.<>E__0." + opName + "(S1 x))"], + ExtensionTests.PrintXmlCrefSymbols(tree, model)); + } + + [Theory] + [CombinatorialData] + public void Unary_068_Consumption_CRef([CombinatorialValues("+", "-")] string op) + { + var src = $$$""" +/// +public static class E +{ + /// + extension(S1) + { + /// + public static S1 operator {{{op}}}(S1 x) => throw null; + } +} + +/// +public struct S1; +"""; + + var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreviewWithDocumentationComments); + comp.VerifyEmitDiagnostics(); + + var opName = UnaryOperatorName(op); + + var e = comp.GetMember("E"); + AssertEx.Equal($$$""" + + + + +""", e.GetDocumentationCommentXml()); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + AssertEx.Equal(["(E.extension(S1).operator " + op + "(S1), S1 E.<>E__0." + opName + "(S1 x))"], + ExtensionTests.PrintXmlCrefSymbols(tree, model)); + } + + [Fact] + public void Unary_068_Consumption_CRef_Checked() + { + var src = $$$""" +/// +public static class E +{ + /// + extension(S1) + { + /// + public static S1 operator -(S1 x) => throw null; + /// + public static S1 operator checked -(S1 x) => throw null; + } +} + +/// +public struct S1; +"""; + + var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreviewWithDocumentationComments); + comp.VerifyEmitDiagnostics(); + + var opName = UnaryOperatorName("-", isChecked: true); + + var e = comp.GetMember("E"); + AssertEx.Equal($$$""" + + + + +""", e.GetDocumentationCommentXml()); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + AssertEx.Equal(["(E.extension(S1).operator checked -(S1), S1 E.<>E__0." + opName + "(S1 x))"], + ExtensionTests.PrintXmlCrefSymbols(tree, model)); + } + + [Fact] + public void Unary_069_Consumption_CRef_TrueFalse() + { + var src = $$$""" +/// +/// +/// +/// +public static class E +{ + /// + extension(S1) + { + /// + public static bool operator true(S1 x) => throw null; + /// + public static bool operator false(S1 x) => throw null; + } +} + +/// +public struct S1; +"""; + + var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreviewWithDocumentationComments); + comp.VerifyEmitDiagnostics(); + + var trueName = UnaryOperatorName("true"); + var falseName = UnaryOperatorName("false"); + + var e = comp.GetMember("E"); + AssertEx.Equal($$$""" + + + + + + + +""", e.GetDocumentationCommentXml()); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + AssertEx.Equal([ + "(E.extension(S1).operator true, System.Boolean E.<>E__0." + trueName + "(S1 x))", + "(E.extension(S1).operator true(S1), System.Boolean E.<>E__0." + trueName + "(S1 x))", + "(E.extension(S1).operator false, System.Boolean E.<>E__0." + falseName + "(S1 x))", + "(E.extension(S1).operator false(S1), System.Boolean E.<>E__0." + falseName + "(S1 x))"], + ExtensionTests.PrintXmlCrefSymbols(tree, model)); + } + + [Theory] + [CombinatorialData] + public void Unary_070_Consumption_CRef_Error([CombinatorialValues("+", "-", "!", "~")] string op) + { + var src = $$$""" +/// +/// +/// +/// +/// +/// +public static class E +{ + /// + extension(S1) + { + } +} + +/// +public struct S1; +"""; + + var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreviewWithDocumentationComments); + comp.VerifyEmitDiagnostics( + // (1,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator !' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator " + op).WithArguments("extension(S1).operator " + op).WithLocation(1, 16), + // (2,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator !()' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator " + op + "()").WithArguments("extension(S1).operator " + op + "()").WithLocation(2, 16), + // (3,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator !(S1)' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator " + op + "(S1)").WithArguments("extension(S1).operator " + op + "(S1)").WithLocation(3, 16), + // (4,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator checked !' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator checked " + op).WithArguments("extension(S1).operator checked " + op).WithLocation(4, 16), + // (5,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator checked !()' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator checked " + op + "()").WithArguments("extension(S1).operator checked " + op + "()").WithLocation(5, 16), + // (6,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator checked !(S1)' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator checked " + op + "(S1)").WithArguments("extension(S1).operator checked " + op + "(S1)").WithLocation(6, 16) + ); + } + + [Fact] + public void Unary_071_Consumption_CRef_Error() + { + var src = $$$""" +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +public static class E +{ + /// + extension(S1) + { + } +} + +/// +public struct S1; +"""; + + var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreviewWithDocumentationComments); + comp.VerifyEmitDiagnostics( + // (1,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator true' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator true").WithArguments("extension(S1).operator true").WithLocation(1, 16), + // (2,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator true()' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator true()").WithArguments("extension(S1).operator true()").WithLocation(2, 16), + // (3,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator true(S1)' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator true(S1)").WithArguments("extension(S1).operator true(S1)").WithLocation(3, 16), + // (4,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator false' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator false").WithArguments("extension(S1).operator false").WithLocation(4, 16), + // (5,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator false()' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator false()").WithArguments("extension(S1).operator false()").WithLocation(5, 16), + // (6,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator false(S1)' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator false(S1)").WithArguments("extension(S1).operator false(S1)").WithLocation(6, 16), + // (7,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator checked true' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator checked true").WithArguments("extension(S1).operator checked true").WithLocation(7, 16), + // (8,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator checked true()' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator checked true()").WithArguments("extension(S1).operator checked true()").WithLocation(8, 16), + // (9,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator checked true(S1)' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator checked true(S1)").WithArguments("extension(S1).operator checked true(S1)").WithLocation(9, 16), + // (10,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator checked false' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator checked false").WithArguments("extension(S1).operator checked false").WithLocation(10, 16), + // (11,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator checked false()' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator checked false()").WithArguments("extension(S1).operator checked false()").WithLocation(11, 16), + // (12,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator checked false(S1)' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator checked false(S1)").WithArguments("extension(S1).operator checked false(S1)").WithLocation(12, 16) + ); + } + + [Theory] + [CombinatorialData] + public void Unary_072_ERR_VoidError([CombinatorialValues("+", "-", "!", "~")] string op) + { + var src = $$$""" +unsafe public static class Extensions1 +{ + extension(void*) + { + public static void* operator {{{op}}}(void* x) => x; + } +} + +class Program +{ + unsafe void* Test(void* x) => {{{op}}}x; +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugDll.WithAllowUnsafe(true)); + comp.VerifyDiagnostics( + // (3,15): error CS1103: The receiver parameter of an extension cannot be of type 'void*' + // extension(void*) + Diagnostic(ErrorCode.ERR_BadTypeforThis, "void*").WithArguments("void*").WithLocation(3, 15) + ); + } + + [Fact] + public void Unary_073_ERR_VoidError_True() + { + var src = $$$""" +unsafe public static class Extensions1 +{ + extension(void*) + { + public static bool operator true(void* x) => true; + public static bool operator false(void* x) => false; + } +} + +class Program +{ + unsafe void Test(void* x) + { + if (x) + {} + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugDll.WithAllowUnsafe(true)); + comp.VerifyDiagnostics( + // (3,15): error CS1103: The receiver parameter of an extension cannot be of type 'void*' + // extension(void*) + Diagnostic(ErrorCode.ERR_BadTypeforThis, "void*").WithArguments("void*").WithLocation(3, 15) + ); + } + + [Fact] + public void Unary_074_Consumption_ErrorScenarioCandidates() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator -(S2 x) => throw null; + } +} + +public static class Extensions2 +{ + extension(S2) + { + public static S2 operator -(S2 x) => throw null; + } +} + +public struct S2 +{ +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + _ = -s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (26,13): error CS0035: Operator '-' is ambiguous on an operand of type 'S2' + // _ = -s2; + Diagnostic(ErrorCode.ERR_AmbigUnaryOp, "-s2").WithArguments("-", "S2").WithLocation(26, 13) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); + +#if DEBUG // Collection of extension blocks depends on GetTypeMembersUnordered for namespace, which conditionally de-orders types for DEBUG only. + AssertEx.Equal("Extensions2.extension(S2).operator -(S2)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("Extensions1.extension(S2).operator -(S2)", symbolInfo.CandidateSymbols[1].ToDisplayString()); +#else + AssertEx.Equal("Extensions1.extension(S2).operator -(S2)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("Extensions2.extension(S2).operator -(S2)", symbolInfo.CandidateSymbols[1].ToDisplayString()); +#endif + } + + [Theory] + [CombinatorialData] + public void Increment_001_Declaration([CombinatorialValues("++", "--")] string op) + { + var src = $$$""" +static class Extensions1 +{ + extension(ref S1 s1) + { + public void operator {{{op}}}() {} + } +} + +static class Extensions2 +{ + extension(ref S1 s1) + { + public S1 operator {{{op}}}() => throw null; + } +} + +static class Extensions3 +{ + extension(ref S1 s1) + { + void operator {{{op}}}() {} + } + extension(C1) + { + public void operator {{{op}}}() {} + } +} + +static class Extensions4 +{ + extension(ref S1? s1) + { + public void operator {{{op}}}() {} + } +} + +static class Extensions5 +{ + extension(S1 s1) + { +#line 600 + public void operator {{{op}}}() {} + } +#line 700 + extension(ref C2 c2) + { + public void operator {{{op}}}() {} + } +} + +static class Extensions6 +{ + extension(C2 c2) + { + public void operator {{{op}}}() {} + } +} + +static class Extensions7 +{ + extension(in S1 s1) + { +#line 800 + public void operator {{{op}}}() {} + } +#line 900 + extension(in C2 c2) + { + public void operator {{{op}}}() {} + } +} + +static class Extensions8 +{ + extension(ref readonly S1 s1) + { +#line 1000 + public void operator {{{op}}}() {} + } +#line 1100 + extension(ref readonly C2 c2) + { + public void operator {{{op}}}() {} + } +} + +static class Extensions9 +{ + extension(T t) where T : struct + { +#line 1200 + public void operator {{{op}}}() {} + } +} + +static class Extensions10 +{ + extension(T t) where T : class + { + public void operator {{{op}}}() {} + } +} + +static class Extensions11 +{ + extension(T t) + { +#line 1300 + public void operator {{{op}}}() {} + } +} + +static class Extensions12 +{ + extension(ref T t) where T : struct + { + public void operator {{{op}}}() {} + } +} + +static class Extensions13 +{ +#line 1400 + extension(ref T t) where T : class + { + public void operator {{{op}}}() {} + } +} + +static class Extensions14 +{ +#line 1500 + extension(ref T t) + { + public void operator {{{op}}}() {} + } +} + +static class Extensions15 +{ +#line 1600 + extension(in T t) where T : struct + { + public void operator {{{op}}}() {} + } +} + +static class Extensions16 +{ +#line 1700 + extension(in T t) where T : class + { + public void operator {{{op}}}() {} + } +} + +static class Extensions17 +{ +#line 1800 + extension(in T t) + { + public void operator {{{op}}}() {} + } +} + +static class Extensions18 +{ +#line 1900 + extension(ref readonly T t) where T : struct + { + public void operator {{{op}}}() {} + } +} + +static class Extensions19 +{ +#line 2000 + extension(ref readonly T t) where T : class + { + public void operator {{{op}}}() {} + } +} + +static class Extensions20 +{ +#line 2100 + extension(ref readonly T t) + { + public void operator {{{op}}}() {} + } +} + +static class Extensions21 +{ + extension(C2) + { +#line 2200 + public void operator {{{op}}}() {} + } +} + +struct S1 +{} + +static class C1 +{} + +class C2 +{} +"""; + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (13,28): error CS9503: The return type for this operator must be void + // public S1 operator ++() => throw null; + Diagnostic(ErrorCode.ERR_OperatorMustReturnVoid, op).WithLocation(13, 28), + // (21,23): error CS9501: User-defined operator 'Extensions3.extension(ref S1).operator ++()' must be declared public + // void operator ++() {} + Diagnostic(ErrorCode.ERR_OperatorsMustBePublic, op).WithArguments("Extensions3.extension(ref S1).operator " + op + "()").WithLocation(21, 23), + // (25,30): error CS9321: An extension block extending a static class cannot contain user-defined operators + // public void operator ++() {} + Diagnostic(ErrorCode.ERR_OperatorInExtensionOfStaticClass, op).WithLocation(25, 30), + // (600,30): error CS9322: Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + // public void operator ++() {} + Diagnostic(ErrorCode.ERR_InstanceOperatorStructExtensionWrongReceiverRefKind, op).WithLocation(600, 30), + // (700,19): error CS9300: The 'ref' receiver parameter of an extension block must be a value type or a generic type constrained to struct. + // extension(ref C2 c2) + Diagnostic(ErrorCode.ERR_RefExtensionParameterMustBeValueTypeOrConstrainedToOne, "C2").WithLocation(700, 19), + // (800,30): error CS9322: Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + // public void operator ++() {} + Diagnostic(ErrorCode.ERR_InstanceOperatorStructExtensionWrongReceiverRefKind, op).WithLocation(800, 30), + // (900,18): error CS9301: The 'in' or 'ref readonly' receiver parameter of extension must be a concrete (non-generic) value type. + // extension(in C2 c2) + Diagnostic(ErrorCode.ERR_InExtensionParameterMustBeValueType, "C2").WithLocation(900, 18), + // (1000,30): error CS9322: Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + // public void operator ++() {} + Diagnostic(ErrorCode.ERR_InstanceOperatorStructExtensionWrongReceiverRefKind, op).WithLocation(1000, 30), + // (1100,28): error CS9301: The 'in' or 'ref readonly' receiver parameter of extension must be a concrete (non-generic) value type. + // extension(ref readonly C2 c2) + Diagnostic(ErrorCode.ERR_InExtensionParameterMustBeValueType, "C2").WithLocation(1100, 28), + // (1200,30): error CS9322: Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + // public void operator ++() {} + Diagnostic(ErrorCode.ERR_InstanceOperatorStructExtensionWrongReceiverRefKind, op).WithLocation(1200, 30), + // (1300,30): error CS9323: Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + // public void operator ++() {} + Diagnostic(ErrorCode.ERR_InstanceOperatorExtensionWrongReceiverType, op).WithLocation(1300, 30), + // (1400,22): error CS9300: The 'ref' receiver parameter of an extension block must be a value type or a generic type constrained to struct. + // extension(ref T t) where T : class + Diagnostic(ErrorCode.ERR_RefExtensionParameterMustBeValueTypeOrConstrainedToOne, "T").WithLocation(1400, 22), + // (1500,22): error CS9300: The 'ref' receiver parameter of an extension block must be a value type or a generic type constrained to struct. + // extension(ref T t) + Diagnostic(ErrorCode.ERR_RefExtensionParameterMustBeValueTypeOrConstrainedToOne, "T").WithLocation(1500, 22), + // (1600,21): error CS9301: The 'in' or 'ref readonly' receiver parameter of extension must be a concrete (non-generic) value type. + // extension(in T t) where T : struct + Diagnostic(ErrorCode.ERR_InExtensionParameterMustBeValueType, "T").WithLocation(1600, 21), + // (1700,21): error CS9301: The 'in' or 'ref readonly' receiver parameter of extension must be a concrete (non-generic) value type. + // extension(in T t) where T : class + Diagnostic(ErrorCode.ERR_InExtensionParameterMustBeValueType, "T").WithLocation(1700, 21), + // (1800,21): error CS9301: The 'in' or 'ref readonly' receiver parameter of extension must be a concrete (non-generic) value type. + // extension(in T t) + Diagnostic(ErrorCode.ERR_InExtensionParameterMustBeValueType, "T").WithLocation(1800, 21), + // (1900,31): error CS9301: The 'in' or 'ref readonly' receiver parameter of extension must be a concrete (non-generic) value type. + // extension(ref readonly T t) where T : struct + Diagnostic(ErrorCode.ERR_InExtensionParameterMustBeValueType, "T").WithLocation(1900, 31), + // (2000,31): error CS9301: The 'in' or 'ref readonly' receiver parameter of extension must be a concrete (non-generic) value type. + // extension(ref readonly T t) where T : class + Diagnostic(ErrorCode.ERR_InExtensionParameterMustBeValueType, "T").WithLocation(2000, 31), + // (2100,31): error CS9301: The 'in' or 'ref readonly' receiver parameter of extension must be a concrete (non-generic) value type. + // extension(ref readonly T t) + Diagnostic(ErrorCode.ERR_InExtensionParameterMustBeValueType, "T").WithLocation(2100, 31), + // (2200,30): error CS9303: 'operator ++': cannot declare instance members in an extension block with an unnamed receiver parameter + // public void operator ++() {} + Diagnostic(ErrorCode.ERR_InstanceMemberWithUnnamedExtensionsParameter, op).WithArguments("operator " + op).WithLocation(2200, 30) + ); + } + + [Theory] + [CombinatorialData] + public void Increment_002_Declaration([CombinatorialValues("++", "--")] string op) + { + var src = $$$""" +static class Extensions1 +{ + extension(ref S1 s1) + { + public void operator {{{op}}}() {} + } +} + +struct S1 +{} +"""; + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + CompileAndVerify(comp, symbolValidator: verify, sourceSymbolValidator: verify, verify: Verification.FailsPEVerify).VerifyDiagnostics(); + + void verify(ModuleSymbol m) + { + var name = CompoundAssignmentOperatorName(op); + var method = m.GlobalNamespace.GetMember("Extensions1." + name); + + AssertEx.Equal("Extensions1." + name + "(ref S1)", method.ToDisplayString()); + Assert.Equal(MethodKind.Ordinary, method.MethodKind); + Assert.True(method.IsStatic); + Assert.False(method.IsExtensionMethod); + Assert.False(method.HasSpecialName); + Assert.False(method.HasRuntimeSpecialName); + Assert.False(method.HasUnsupportedMetadata); + } + } + + [Theory] + [CombinatorialData] + public void Increment_003_Declaration([CombinatorialValues("++", "--")] string op) + { + var src = $$$""" +static class Extensions1 +{ + extension(S1 s1) + { + public void operator {{{op}}}() {} + public static S1 operator {{{op}}}(S1 x) => default; + } +} + +class S1 +{} +"""; + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + + CompileAndVerify(comp, symbolValidator: verify, sourceSymbolValidator: verify, verify: Verification.FailsPEVerify).VerifyDiagnostics(); + + void verify(ModuleSymbol m) + { + var name = CompoundAssignmentOperatorName(op); + var method = m.GlobalNamespace.GetMember("Extensions1." + name); + + AssertEx.Equal("Extensions1." + name + "(S1)", method.ToDisplayString()); + Assert.Equal(MethodKind.Ordinary, method.MethodKind); + Assert.True(method.IsStatic); + Assert.False(method.IsExtensionMethod); + Assert.False(method.HasSpecialName); + Assert.False(method.HasRuntimeSpecialName); + Assert.False(method.HasUnsupportedMetadata); + + name = op == "++" ? WellKnownMemberNames.IncrementOperatorName : WellKnownMemberNames.DecrementOperatorName; + method = m.GlobalNamespace.GetMember("Extensions1." + name); + + AssertEx.Equal("Extensions1." + name + "(S1)", method.ToDisplayString()); + Assert.Equal(MethodKind.Ordinary, method.MethodKind); + Assert.True(method.IsStatic); + Assert.False(method.IsExtensionMethod); + Assert.False(method.HasSpecialName); + Assert.False(method.HasRuntimeSpecialName); + Assert.False(method.HasUnsupportedMetadata); + } + } + + [Theory] + [CombinatorialData] + public void Increment_004_Declaration_2([CombinatorialValues("++", "--")] string op) + { + var src = $$$""" +static class Extensions1 +{ + extension(ref S1 s1) + { + public void operator checked {{{op}}}() {} + public void operator {{{op}}}() {} + } +} + +static class Extensions2 +{ + extension(ref S1 s1) + { +#line 100 + public void operator checked {{{op}}}() {} + } + extension(ref S1 s1) + { + public void operator {{{op}}}() {} + } +} + +static class Extensions3 +{ + extension(ref S1 s1) + { + public void operator checked {{{op}}}() {} + } +} + +struct S1 +{} +"""; + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (112,38): error CS9025: The operator 'Extensions3.extension(ref S1).operator checked ++()' requires a matching non-checked version of the operator to also be defined + // public void operator checked ++() {} + Diagnostic(ErrorCode.ERR_CheckedOperatorNeedsMatch, op).WithArguments("Extensions3.extension(ref S1).operator checked " + op + "()").WithLocation(112, 38) + ); + } + + [Theory] + [CombinatorialData] + public void Increment_004_Declaration([CombinatorialValues("++", "--")] string op, [CombinatorialValues("virtual", "abstract", "new", "override", "sealed", "readonly")] string modifier) + { + var src = $$$""" +static class Extensions1 +{ + extension(ref S1 s1) + { + {{{modifier}}} + public void operator {{{op}}}() {} + } +} + +struct S1 +{} +"""; + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (6,30): error CS0106: The modifier 'abstract' is not valid for this item + // public void operator ++() {} + Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments(modifier).WithLocation(6, 30) + ); + } + + [Theory] + [CombinatorialData] + public void Increment_005_Consumption(bool fromMetadata, [CombinatorialValues("++", "--")] string op, [CombinatorialValues("struct", "class")] string typeKind) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op}}}(S1 x) + { + System.Console.Write("operator1:"); + System.Console.Write(x.F); + return new S1 { F = x.F + 1 }; + } + } +} + +public {{{typeKind}}} S1 +{ + public int F; +} +"""; + + var src2 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1() { F = 101 }; + {{{op}}}s1; + System.Console.Write(":"); + System.Console.Write(s1.F); + System.Console.Write(":"); + var s2 = {{{op}}}s1; + System.Console.Write(":"); + System.Console.Write(s2.F); + System.Console.Write(":"); + System.Console.Write(s1.F); + } +} +"""; + + var comp1 = CreateCompilation(src1); + var comp1Ref = fromMetadata ? comp1.EmitToImageReference() : comp1.ToMetadataReference(); + + var comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp2, expectedOutput: "operator1:101:102:operator1:102:103:103").VerifyDiagnostics(); + + var tree = comp2.SyntaxTrees.First(); + var model = comp2.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("Extensions1.extension(S1).operator " + op + "(S1)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S1", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: "operator1:101:102:operator1:102:103:103").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (6,9): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // ++s1; + Diagnostic(ErrorCode.ERR_FeatureInPreview, op + "s1").WithArguments("extensions").WithLocation(6, 9), + // (10,18): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // var s2 = ++s1; + Diagnostic(ErrorCode.ERR_FeatureInPreview, op + "s1").WithArguments("extensions").WithLocation(10, 18) + ); + + var opName = UnaryOperatorName(op); + var src3 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1(); + Extensions1.{{{opName}}}(s1); + } +} +"""; + var comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp3, expectedOutput: "operator1:0").VerifyDiagnostics(); + + comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp3, expectedOutput: "operator1:0").VerifyDiagnostics(); + + comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + CompileAndVerify(comp3, expectedOutput: "operator1:0").VerifyDiagnostics(); + + var src4 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1(); + s1.{{{opName}}}(); + S1.{{{opName}}}(s1); + } +} +"""; + var comp4 = CreateCompilation(src4, references: [comp1Ref]); + comp4.VerifyEmitDiagnostics( + // (6,12): error CS1061: 'S1' does not contain a definition for 'op_Increment' and no accessible extension method 'op_Increment' accepting a first argument of type 'S1' could be found (are you missing a using directive or an assembly reference?) + // s1.op_Increment(); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, opName).WithArguments("S1", opName).WithLocation(6, 12), + // (7,12): error CS0117: 'S1' does not contain a definition for 'op_Increment' + // S1.op_Increment(s1); + Diagnostic(ErrorCode.ERR_NoSuchMember, opName).WithArguments("S1", opName).WithLocation(7, 12) + ); + } + + [Theory] + [CombinatorialData] + public void Increment_006_Consumption(bool fromMetadata, [CombinatorialValues("++", "--")] string op) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(ref S1 x) + { + public void operator {{{op}}}() + { + System.Console.Write("operator1:"); + System.Console.Write(x.F); + x.F++; + } + } +} + +public struct S1 +{ + public int F; +} + +""" + CompilerFeatureRequiredAttribute; + + var src2 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1() { F = 101 }; + {{{op}}}s1; + System.Console.Write(":"); + System.Console.Write(s1.F); + System.Console.Write(":"); + var s2 = {{{op}}}s1; + System.Console.Write(":"); + System.Console.Write(s2.F); + System.Console.Write(":"); + System.Console.Write(s1.F); + } +} +"""; + + var comp1 = CreateCompilation(src1); + var comp1Ref = fromMetadata ? comp1.EmitToImageReference() : comp1.ToMetadataReference(); + + var comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp2, expectedOutput: "operator1:101:102:operator1:102:103:103").VerifyDiagnostics(); + + var tree = comp2.SyntaxTrees.First(); + var model = comp2.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().ElementAt(1); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("Extensions1.extension(ref S1).operator " + op + "()", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S1", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: "operator1:101:102:operator1:102:103:103").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (6,9): error CS0023: Operator '++' cannot be applied to operand of type 'S1' + // ++s1; + Diagnostic(ErrorCode.ERR_BadUnaryOp, op + "s1").WithArguments(op, "S1").WithLocation(6, 9), + // (10,18): error CS0023: Operator '++' cannot be applied to operand of type 'S1' + // var s2 = ++s1; + Diagnostic(ErrorCode.ERR_BadUnaryOp, op + "s1").WithArguments(op, "S1").WithLocation(10, 18) + ); + + var opName = CompoundAssignmentOperatorName(op); + + var src3 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1(); + Extensions1.{{{opName}}}(ref s1); + } +} +"""; + var comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp3, expectedOutput: "operator1:0").VerifyDiagnostics(); + + comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp3, expectedOutput: "operator1:0").VerifyDiagnostics(); + + comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + CompileAndVerify(comp3, expectedOutput: "operator1:0").VerifyDiagnostics(); + + var src4 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1(); + s1.{{{opName}}}(); + S1.{{{opName}}}(ref s1); + } +} +"""; + var comp4 = CreateCompilation(src4, references: [comp1Ref]); + comp4.VerifyEmitDiagnostics( + // (6,12): error CS1061: 'S1' does not contain a definition for 'op_IncrementAssignment' and no accessible extension method 'op_IncrementAssignment' accepting a first argument of type 'S1' could be found (are you missing a using directive or an assembly reference?) + // s1.op_IncrementAssignment(); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, opName).WithArguments("S1", opName).WithLocation(6, 12), + // (7,12): error CS0117: 'S1' does not contain a definition for 'op_IncrementAssignment' + // S1.op_IncrementAssignment(ref s1); + Diagnostic(ErrorCode.ERR_NoSuchMember, opName).WithArguments("S1", opName).WithLocation(7, 12) + ); + + var src5 = $$$""" +public static class Extensions1 +{ + extension(C1 x) + { + public void operator {{{op}}}() + { + System.Console.Write("operator1:"); + System.Console.Write(x.F); + x.F++; + } + } +} + +public class C1 +{ + public int F; +} + +""" + CompilerFeatureRequiredAttribute; + + var src6 = $$$""" +class Program +{ + static void Main() + { + var c1 = new C1() { F = 101 }; + var c2 = c1; + {{{op}}}c1; + System.Console.Write(":"); + System.Console.Write(c1.F); + System.Console.Write(":"); + System.Console.Write(ReferenceEquals(c1, c2) ? "True" : "False"); + System.Console.Write(":"); + var c3 = {{{op}}}c1; + System.Console.Write(":"); + System.Console.Write(c1.F); + System.Console.Write(":"); + System.Console.Write(ReferenceEquals(c1, c2) ? "True" : "False"); + System.Console.Write(":"); + System.Console.Write(ReferenceEquals(c1, c3) ? "True" : "False"); + } +} +"""; + + var comp5 = CreateCompilation(src5); + var comp5Ref = fromMetadata ? comp5.EmitToImageReference() : comp5.ToMetadataReference(); + + var comp6 = CreateCompilation(src6, references: [comp5Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp6, expectedOutput: "operator1:101:102:True:operator1:102:103:True:True").VerifyDiagnostics(); + + comp6 = CreateCompilation(src6, references: [comp5Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp6, expectedOutput: "operator1:101:102:True:operator1:102:103:True:True").VerifyDiagnostics(); + + comp6 = CreateCompilation(src6, references: [comp5Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp6.VerifyEmitDiagnostics( + // (7,9): error CS0023: Operator '--' cannot be applied to operand of type 'C1' + // --c1; + Diagnostic(ErrorCode.ERR_BadUnaryOp, op + "c1").WithArguments(op, "C1").WithLocation(7, 9), + // (13,18): error CS0023: Operator '--' cannot be applied to operand of type 'C1' + // var c3 = --c1; + Diagnostic(ErrorCode.ERR_BadUnaryOp, op + "c1").WithArguments(op, "C1").WithLocation(13, 18) + ); + } + + [Fact] + public void Increment_007_Consumption_PredefinedComesFirst() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator ++(S2 x) => throw null; + } +} + +public struct S2 +{ + public static implicit operator int(S2 x) + { + System.Console.Write("operator2"); + return 0; + } + public static implicit operator S2(int x) + { + System.Console.Write("operator3"); + return default; + } +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + ++s2; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2operator3").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("S2.operator ++(S2)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S2", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Increment_008_Consumption_PredefinedComesFirst() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S2 x) + { + public void operator ++() => throw null; + } +} + +public struct S2 +{ + public static implicit operator int(S2 x) + { + System.Console.Write("operator2"); + return 0; + } + public static implicit operator S2(int x) + { + System.Console.Write("operator3"); + return default; + } +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + ++s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2operator3").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("S2.operator ++(S2)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S2", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Increment_009_Consumption_NonExtensionComesFirst() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator ++(S2 x) => throw null; + } +} + +public struct S2 +{ + public static S2 operator ++(S2 x) + { + System.Console.Write("operator2"); + return x; + } +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + _ = ++s2; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("S2.operator ++(S2)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S2", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Increment_010_Consumption_NonExtensionComesFirst() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator ++(S2 x) => throw null; + } +} + +public struct S2 +{ + public void operator ++() + { + System.Console.Write("operator2"); + } +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + _ = ++s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("S2.operator ++()", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S2", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Increment_011_Consumption_NonExtensionComesFirst() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S2 x) + { + public void operator ++() => throw null; + } +} + +public struct S2 +{ + public static S2 operator ++(S2 x) + { + System.Console.Write("operator2"); + return x; + } +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + _ = ++s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("S2.operator ++(S2)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S2", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Increment_012_Consumption_NonExtensionComesFirst() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S2 x) + { + public void operator ++() => throw null; + } +} + +public struct S2 +{ + public void operator ++() + { + System.Console.Write("operator2"); + } +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + _ = ++s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("S2.operator ++()", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S2", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Increment_013_Consumption_InstanceInTheSameScopeComesFirst() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S2 x) + { + public void operator ++() + { + System.Console.Write("operator2"); + } + + public static S2 operator ++(S2 y) => throw null; + } +} + +public struct S2 +{ +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + _ = ++s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("Extensions1.extension(ref S2).operator ++()", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S2", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Increment_014_Consumption_InstanceInTheSameScopeComesFirst() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S2 x) + { + public void operator ++() + { + System.Console.Write("operator2"); + } + } + extension(S2) + { + public static S2 operator ++(S2 y) => throw null; + } +} + +public struct S2 +{ +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + _ = ++s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("Extensions1.extension(ref S2).operator ++()", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S2", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Increment_015_Consumption_InstanceInTheSameScopeComesFirst() + { + var src = $$$""" +public static class Extensions2 +{ + extension(S2) + { + public static S2 operator ++(S2 y) => throw null; + } +} + +public static class Extensions1 +{ + extension(ref S2 x) + { + public void operator ++() + { + System.Console.Write("operator2"); + } + } +} + +public struct S2 +{ +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + _ = ++s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("Extensions1.extension(ref S2).operator ++()", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S2", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Increment_016_Consumption_StaticTriedAfterInapplicableInstanceInTheSameScope() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S1 x) + { + public void operator ++() => throw null; + } + extension(S2) + { + public static S2 operator ++(S2 y) + { + System.Console.Write("operator2"); + return y; + } + } +} + +public struct S1 +{ +} + +public struct S2 +{ +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + _ = ++s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2").VerifyDiagnostics(); + } + + [Fact] + public void Increment_017_Consumption_ScopeByScope() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator ++(S1 x) => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{} + +namespace NS1 +{ + public static class Extensions2 + { + extension(S1) + { + public static S1 operator ++(S1 x) + { + System.Console.Write("operator1"); + return x; + } + } + } + + namespace NS2 + { + public static class Extensions3 + { + extension(S2) + { + public static S2 operator ++(S2 x) => throw null; + } + } + + class Program + { + static void Main() + { + var s1 = new S1(); + _ = ++s1; + } + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("NS1.Extensions2.extension(S1).operator ++(S1)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S1", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Increment_018_Consumption_ScopeByScope() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S1 x) + { + public void operator ++() => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{} + +namespace NS1 +{ + public static class Extensions2 + { + extension(S1) + { + public static S1 operator ++(S1 x) + { + System.Console.Write("operator1"); + return x; + } + } + } + + namespace NS2 + { + public static class Extensions3 + { + extension(ref S2 x) + { + public void operator ++() => throw null; + } + } + + class Program + { + static void Main() + { + var s1 = new S1(); + _ = ++s1; + } + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("NS1.Extensions2.extension(S1).operator ++(S1)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S1", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Increment_019_Consumption_ScopeByScope() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S1 x) + { + public void operator ++() => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{} + +namespace NS1 +{ + public static class Extensions2 + { + extension(ref S1 x) + { + public void operator ++() + { + System.Console.Write("operator1"); + } + } + } + + namespace NS2 + { + public static class Extensions3 + { + extension(ref S2 x) + { + public void operator ++() => throw null; + } + } + + class Program + { + static void Main() + { + var s1 = new S1(); + _ = ++s1; + } + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("NS1.Extensions2.extension(ref S1).operator ++()", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S1", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Increment_020_Consumption_ScopeByScope() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator ++(S1 x) => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{} + +namespace NS1 +{ + public static class Extensions2 + { + extension(ref S1 x) + { + public void operator ++() + { + System.Console.Write("operator1"); + } + } + } + + namespace NS2 + { + public static class Extensions3 + { + extension(S2) + { + public static S2 operator ++(S2 x) => throw null; + } + } + + class Program + { + static void Main() + { + var s1 = new S1(); + _ = ++s1; + } + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("NS1.Extensions2.extension(ref S1).operator ++()", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S1", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Increment_021_Consumption_NonExtensionAmbiguity() + { + var src = $$$""" +public interface I1 +{ + public static I1 operator --(I1 x) => x; +} + +public interface I3 +{ + public static I3 operator --(I3 x) => x; +} + +public interface I4 : I1, I3 +{ +} + +public interface I2 : I4 +{ +} + +public static class Extensions1 +{ + extension(I2 x) + { + public void operator --() {} + public static I2 operator --(I2 y) => y; + } +} + +class Test2 : I2 +{ + static void Main() + { + I2 x = new Test2(); + var y = --x; + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (33,17): error CS0035: Operator '--' is ambiguous on an operand of type 'I2' + // var y = --x; + Diagnostic(ErrorCode.ERR_AmbigUnaryOp, "--x").WithArguments("--", "I2").WithLocation(33, 17) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); + Assert.Equal(2, symbolInfo.CandidateSymbols.Length); + AssertEx.Equal("I1.operator --(I1)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("I3.operator --(I3)", symbolInfo.CandidateSymbols[1].ToDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Increment_022_Consumption_NonExtensionAmbiguity() + { + var src = $$$""" +public interface I1 +{ + public void operator --() {} +} + +public interface I3 +{ + public void operator --() {} +} + +public interface I4 : I1, I3 +{ +} + +public interface I2 : I4 +{ +} + +public static class Extensions1 +{ + extension(I2 x) + { + public void operator --() {} + public static I2 operator --(I2 y) => y; + } +} + +class Test2 : I2 +{ + static void Main() + { + I2 x = new Test2(); + var y = --x; + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (33,17): error CS0121: The call is ambiguous between the following methods or properties: 'I1.operator --()' and 'I3.operator --()' + // var y = --x; + Diagnostic(ErrorCode.ERR_AmbigCall, "--").WithArguments("I1.operator --()", "I3.operator --()").WithLocation(33, 17) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); + Assert.Equal(2, symbolInfo.CandidateSymbols.Length); + AssertEx.Equal("I1.operator --()", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("I3.operator --()", symbolInfo.CandidateSymbols[1].ToDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Increment_023_Consumption_NonExtensionAmbiguity() + { + var src = $$$""" +public interface I1 +{ + public void operator --() {} +} + +public interface I3 +{ + public void operator --() {} +} + +public interface I4 : I1, I3 +{ +} + +public interface I2 : I4 +{ + public static I2 operator --(I2 y) => y; +} + +public static class Extensions1 +{ + extension(I2 x) + { + public void operator --() {} + public static I2 operator --(I2 y) => y; + } +} + +class Test2 : I2 +{ + static void Main() + { + I2 x = new Test2(); +#line 33 + var y = --x; + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (33,17): error CS0121: The call is ambiguous between the following methods or properties: 'I1.operator --()' and 'I3.operator --()' + // var y = --x; + Diagnostic(ErrorCode.ERR_AmbigCall, "--").WithArguments("I1.operator --()", "I3.operator --()").WithLocation(33, 17) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); + Assert.Equal(2, symbolInfo.CandidateSymbols.Length); + AssertEx.Equal("I1.operator --()", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("I3.operator --()", symbolInfo.CandidateSymbols[1].ToDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + [WorkItem("https://github.com/dotnet/roslyn/issues/78830")] + public void Increment_024_Consumption_ExtensionAmbiguity() + { + var src = $$$""" +public interface I1; +public interface I3; +public interface I4 : I1, I3; +public interface I2 : I4; + +public static class Extensions1 +{ + extension(I2 y) + { + public void operator --() {} + public static I2 operator --(I2 x) => x; + } +} + +namespace NS1 +{ + public static class Extensions2 + { + extension(I1) + { + public static I1 operator --(I1 x) => x; + } + + extension(I3) + { + public static I3 operator --(I3 x) => x; + } + } + + class Test2 : I2 + { + static void Main() + { + I2 x = new Test2(); + var y = --x; + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src); + + // https://github.com/dotnet/roslyn/issues/78830: We might want to include more information into the error. Like what methods conflict. + comp.VerifyEmitDiagnostics( + // (35,21): error CS0035: Operator '--' is ambiguous on an operand of type 'I2' + // var y = --x; + Diagnostic(ErrorCode.ERR_AmbigUnaryOp, "--x").WithArguments("--", "I2").WithLocation(35, 21) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); + Assert.Equal(2, symbolInfo.CandidateSymbols.Length); + AssertEx.Equal("NS1.Extensions2.extension(I1).operator --(I1)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("NS1.Extensions2.extension(I3).operator --(I3)", symbolInfo.CandidateSymbols[1].ToDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Increment_025_Consumption_ExtensionAmbiguity() + { + var src = $$$""" +public interface I1; +public interface I3; +public interface I4 : I1, I3; +public interface I2 : I4; + +public static class Extensions1 +{ + extension(I2 y) + { + public void operator --() {} + public static I2 operator --(I2 x) => x; + } +} + +namespace NS1 +{ + public static class Extensions2 + { + extension(I1 x) + { + public void operator --() {} + } + + extension(I3 x) + { + public void operator --() {} + } + } + + class Test2 : I2 + { + static void Main() + { + I2 x = new Test2(); + var y = --x; + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src); + + comp.VerifyEmitDiagnostics( + // (35,21): error CS0121: The call is ambiguous between the following methods or properties: 'Extensions2.extension(I1).operator --()' and 'Extensions2.extension(I3).operator --()' + // var y = --x; + Diagnostic(ErrorCode.ERR_AmbigCall, "--").WithArguments("NS1.Extensions2.extension(I1).operator --()", "NS1.Extensions2.extension(I3).operator --()").WithLocation(35, 21) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); + Assert.Equal(2, symbolInfo.CandidateSymbols.Length); + AssertEx.Equal("NS1.Extensions2.extension(I1).operator --()", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("NS1.Extensions2.extension(I3).operator --()", symbolInfo.CandidateSymbols[1].ToDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Increment_026_Consumption_ExtensionAmbiguity() + { + var src = $$$""" +public interface I1; +public interface I3; +public interface I4 : I1, I3; +public interface I2 : I4; + +public static class Extensions1 +{ + extension(I2 y) + { + public void operator --() {} + public static I2 operator --(I2 x) => x; + } +} + +namespace NS1 +{ + public static class Extensions2 + { + extension(I1 x) + { + public void operator --() {} + } + + extension(I3 x) + { + public void operator --() {} + } + + extension(I2) + { + public static I2 operator --(I2 x) => x; + } + } + + class Test2 : I2 + { + static void Main() + { + I2 x = new Test2(); +#line 35 + var y = --x; + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src); + + comp.VerifyEmitDiagnostics( + // (35,21): error CS0121: The call is ambiguous between the following methods or properties: 'Extensions2.extension(I1).operator --()' and 'Extensions2.extension(I3).operator --()' + // var y = --x; + Diagnostic(ErrorCode.ERR_AmbigCall, "--").WithArguments("NS1.Extensions2.extension(I1).operator --()", "NS1.Extensions2.extension(I3).operator --()").WithLocation(35, 21) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); + Assert.Equal(2, symbolInfo.CandidateSymbols.Length); + AssertEx.Equal("NS1.Extensions2.extension(I1).operator --()", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("NS1.Extensions2.extension(I3).operator --()", symbolInfo.CandidateSymbols[1].ToDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Theory] + [CombinatorialData] + public void Increment_027_Consumption_Lifted([CombinatorialValues("++", "--")] string op) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(ref S1 y) + { + public void operator {{{op}}}() => throw null; + + public static S1 operator {{{op}}}(S1 x) + { + System.Console.Write("operator1:"); + System.Console.Write(x.F); + return new S1 { F = x.F + 1 }; + } + } +} + +public struct S1 +{ + public int F; +} +"""; + var src2 = $$$""" +class Program +{ + static void Main() + { + S1? s1 = new S1() { F = 101 }; + {{{op}}}s1; + System.Console.Write(":"); + System.Console.Write(s1.Value.F); + System.Console.Write(":"); + var s2 = {{{op}}}s1; + System.Console.Write(":"); + System.Console.Write(s2.Value.F); + System.Console.Write(":"); + System.Console.Write(s1.Value.F); + System.Console.Write(":"); + s1 = null; + {{{op}}}s1; + System.Console.Write(s1?.F ?? -1); + System.Console.Write(":"); + s2 = {{{op}}}s1; + System.Console.Write(s2?.F ?? -1); + System.Console.Write(":"); + System.Console.Write(s1?.F ?? -1); + + System.Console.Write(" | "); + + s1 = new S1() { F = 101 }; + s1{{{op}}}; + System.Console.Write(":"); + System.Console.Write(s1.Value.F); + System.Console.Write(":"); + s2 = s1{{{op}}}; + System.Console.Write(":"); + System.Console.Write(s2.Value.F); + System.Console.Write(":"); + System.Console.Write(s1.Value.F); + System.Console.Write(":"); + s1 = null; + s1{{{op}}}; + System.Console.Write(s1?.F ?? -1); + System.Console.Write(":"); + s2 = s1{{{op}}}; + System.Console.Write(s2?.F ?? -1); + System.Console.Write(":"); + System.Console.Write(s1?.F ?? -1); + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp1 = CreateCompilation([src1, src2], options: TestOptions.DebugExe); + CompileAndVerify(comp1, expectedOutput: "operator1:101:102:operator1:102:103:103:-1:-1:-1 | operator1:101:102:operator1:102:102:103:-1:-1:-1").VerifyDiagnostics(); + + var comp2 = CreateCompilation([src1, src2], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: "operator1:101:102:operator1:102:103:103:-1:-1:-1 | operator1:101:102:operator1:102:102:103:-1:-1:-1").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1.ToMetadataReference()], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (6,9): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // ++s1; + Diagnostic(ErrorCode.ERR_FeatureInPreview, op + "s1").WithArguments("extensions").WithLocation(6, 9), + // (10,18): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // var s2 = ++s1; + Diagnostic(ErrorCode.ERR_FeatureInPreview, op + "s1").WithArguments("extensions").WithLocation(10, 18), + // (17,9): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // ++s1; + Diagnostic(ErrorCode.ERR_FeatureInPreview, op + "s1").WithArguments("extensions").WithLocation(17, 9), + // (20,14): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // s2 = ++s1; + Diagnostic(ErrorCode.ERR_FeatureInPreview, op + "s1").WithArguments("extensions").WithLocation(20, 14), + // (28,9): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // s1++; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s1" + op).WithArguments("extensions").WithLocation(28, 9), + // (32,14): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // s2 = s1++; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s1" + op).WithArguments("extensions").WithLocation(32, 14), + // (39,9): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // s1++; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s1" + op).WithArguments("extensions").WithLocation(39, 9), + // (42,14): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // s2 = s1++; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s1" + op).WithArguments("extensions").WithLocation(42, 14) + ); + } + + [Fact] + public void Increment_028_Consumption_Lifted() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S1 x) + { + public void operator ++() + { + System.Console.Write("operator1"); + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? s1 = new S1(); + _ = ++s1; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (20,13): error CS0023: Operator '++' cannot be applied to operand of type 'S1?' + // _ = ++s1; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "++s1").WithArguments("++", "S1?").WithLocation(20, 13) + ); + } + + [Fact] + public void Increment_029_Consumption_LiftedIsWorse() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator ++(S1 x) => throw null; + } + extension(S1?) + { + public static S1? operator ++(S1? x) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? s1 = new S1(); + _ = ++s1; + System.Console.Write(":"); + s1 = null; + _ = ++s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1:operator1").VerifyDiagnostics(); + } + + [Fact] + public void Increment_030_Consumption_ExtendedTypeIsNullable() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1?) + { + public static S1? operator ++(S1? x) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1 s1 = new S1(); + _ = ++s1; + Extensions1.op_Increment(s1); + + S1? s2 = new S1(); + _ = ++s2; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (21,13): error CS0023: Operator '++' cannot be applied to operand of type 'S1' + // _ = ++s1; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "++s1").WithArguments("++", "S1").WithLocation(21, 13) + ); + } + + [Fact] + public void Increment_031_Consumption_ExtendedTypeIsNullable() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S1? x) + { + public void operator ++() + { + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1 s1 = new S1(); + _ = ++s1; + Extensions1.op_IncrementAssignment(s1); + Extensions1.op_IncrementAssignment(ref s1); + + S1? s2 = new S1(); + _ = ++s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (19,13): error CS0023: Operator '++' cannot be applied to operand of type 'S1' + // _ = ++s1; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "++s1").WithArguments("++", "S1").WithLocation(19, 13), + // (20,44): error CS1620: Argument 1 must be passed with the 'ref' keyword + // Extensions1.op_IncrementAssignment(s1); + Diagnostic(ErrorCode.ERR_BadArgRef, "s1").WithArguments("1", "ref").WithLocation(20, 44), + // (21,48): error CS1503: Argument 1: cannot convert from 'ref S1' to 'ref S1?' + // Extensions1.op_IncrementAssignment(ref s1); + Diagnostic(ErrorCode.ERR_BadArgType, "s1").WithArguments("1", "ref S1", "ref S1?").WithLocation(21, 48) + ); + } + + [Fact] + public void Increment_032_Consumption_ReceiverTypeMismatch() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator ++(S2 x) => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{ + public static implicit operator S2(S1 x) => default; +} + +class Program +{ + static void Main() + { + S1 s1 = new S1(); + _ = ++s1; + Extensions1.op_Increment(s1); + + S1? s2 = new S1(); + _ = ++s2; + Extensions1.op_Increment(s2); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (22,13): error CS0023: Operator '++' cannot be applied to operand of type 'S1' + // _ = ++s1; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "++s1").WithArguments("++", "S1").WithLocation(22, 13), + // (26,13): error CS0023: Operator '++' cannot be applied to operand of type 'S1?' + // _ = ++s2; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "++s2").WithArguments("++", "S1?").WithLocation(26, 13), + // (27,34): error CS1503: Argument 1: cannot convert from 'S1?' to 'S2' + // Extensions1.op_Increment(s2); + Diagnostic(ErrorCode.ERR_BadArgType, "s2").WithArguments("1", "S1?", "S2").WithLocation(27, 34) + ); + } + + [Fact] + public void Increment_033_Consumption_ReceiverTypeMismatch() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S2 x) + { + public void operator ++() => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{ + public static implicit operator S2(S1 x) => default; +} + +class Program +{ + static void Main() + { + S1 s1 = new S1(); + _ = ++s1; + Extensions1.op_IncrementAssignment(ref s1); + + S1? s2 = new S1(); + _ = ++s2; + Extensions1.op_IncrementAssignment(ref s2); + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (22,13): error CS0023: Operator '++' cannot be applied to operand of type 'S1' + // _ = ++s1; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "++s1").WithArguments("++", "S1").WithLocation(22, 13), + // (23,48): error CS1503: Argument 1: cannot convert from 'ref S1' to 'ref S2' + // Extensions1.op_IncrementAssignment(ref s1); + Diagnostic(ErrorCode.ERR_BadArgType, "s1").WithArguments("1", "ref S1", "ref S2").WithLocation(23, 48), + // (26,13): error CS0023: Operator '++' cannot be applied to operand of type 'S1?' + // _ = ++s2; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "++s2").WithArguments("++", "S1?").WithLocation(26, 13), + // (27,48): error CS1503: Argument 1: cannot convert from 'ref S1?' to 'ref S2' + // Extensions1.op_IncrementAssignment(ref s2); + Diagnostic(ErrorCode.ERR_BadArgType, "s2").WithArguments("1", "ref S1?", "ref S2").WithLocation(27, 48) + ); + } + + [Fact] + public void Increment_034_Consumption_ReceiverTypeMismatch() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object) + { + public static S1 operator ++(object x) + { + System.Console.Write("operator1"); + return default; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1 s1 = new S1(); + s1 = ++s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1").VerifyDiagnostics(); + } + + [Fact] + public void Increment_035_Consumption_ReceiverTypeMismatch() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object x) + { + public void operator ++() => throw null; + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1 s1 = new S1(); + _ = ++s1; + Extensions1.op_IncrementAssignment(s1); + + S1? s2 = new S1(); + _ = ++s2; + Extensions1.op_IncrementAssignment(s2); + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (17,13): error CS0023: Operator '++' cannot be applied to operand of type 'S1' + // _ = ++s1; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "++s1").WithArguments("++", "S1").WithLocation(17, 13), + // (21,13): error CS0023: Operator '++' cannot be applied to operand of type 'S1?' + // _ = ++s2; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "++s2").WithArguments("++", "S1?").WithLocation(21, 13) + ); + } + + [Fact] + public void Increment_036_Consumption_ReceiverTypeMismatch() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object) + { + public static C1 operator ++(object x) + { + System.Console.Write("operator1"); + return null; + } + } +} + +public class C1 +{} + +class Program +{ + static void Main() + { + var c1 = new C1(); + c1 = ++c1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1").VerifyDiagnostics(); + } + + [Fact] + public void Increment_037_Consumption_ReceiverTypeMismatch() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1Base x) + { + public void operator ++() + { + System.Console.Write("operator1:"); + System.Console.Write(x.F); + x.F++; + } + } +} + + +public class C1Base +{ + public int F; +} + +public class C1 : C1Base +{} + +class Program +{ + static void Main() + { + var c1 = new C1() { F = 101 }; + var c2 = c1; + ++c1; + System.Console.Write(":"); + System.Console.Write(c1.F); + System.Console.Write(":"); + System.Console.Write(ReferenceEquals(c1, c2) ? "True" : "False"); + System.Console.Write(":"); + var c3 = ++c1; + System.Console.Write(":"); + System.Console.Write(c1.F); + System.Console.Write(":"); + System.Console.Write(ReferenceEquals(c1, c2) ? "True" : "False"); + System.Console.Write(":"); + System.Console.Write(ReferenceEquals(c1, c3) ? "True" : "False"); + System.Console.Write(":"); + c1++; + System.Console.Write(":"); + System.Console.Write(c1.F); + System.Console.Write(":"); + System.Console.Write(ReferenceEquals(c1, c2) ? "True" : "False"); + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1:101:102:True:operator1:102:103:True:True:operator1:103:104:True").VerifyDiagnostics(); + } + + [Fact] + public void Increment_038_Consumption_ReceiverTypeMismatch() + { + var src = $$$""" +public static class Extensions1 +{ + extension(dynamic x) + { + public void operator ++() + { + System.Console.Write("operator1"); + } + } +} + +public class C1 +{} + +class Program +{ + static void Main() + { + var c1 = new C1(); + c1 = ++c1; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (3,15): error CS1103: The receiver parameter of an extension cannot be of type 'dynamic' + // extension(dynamic x) + Diagnostic(ErrorCode.ERR_BadTypeforThis, "dynamic").WithArguments("dynamic").WithLocation(3, 15) + ); + } + + [Fact] + public void Increment_039_Consumption_ReceiverTypeMismatch() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object x) + { + public void operator ++() + { + System.Console.Write("operator1"); + } + } +} + +public class C1 +{} + +class Program +{ + static void Main() + { + Test(new C1()); + } + + static void Test(T c1) where T : class + { + ++c1; + c1 = ++c1; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1operator1").VerifyDiagnostics(); + } + + [Fact] + public void Increment_040_Consumption_ReceiverTypeMismatch() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref System.Span x) + { + public void operator ++() => throw null; + } +} + +class Program +{ + static void Main() + { + int[] a1 = null; +#line 17 + _ = ++a1; + Extensions1.op_IncrementAssignment(ref a1); + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (17,13): error CS0023: Operator '++' cannot be applied to operand of type 'int[]' + // _ = ++a1; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "++a1").WithArguments("++", "int[]").WithLocation(17, 13), + // (18,48): error CS1503: Argument 1: cannot convert from 'ref int[]' to 'ref System.Span' + // Extensions1.op_IncrementAssignment(ref a1); + Diagnostic(ErrorCode.ERR_BadArgType, "a1").WithArguments("1", "ref int[]", "ref System.Span").WithLocation(18, 48) + ); + } + + [Fact] + public void Increment_041_Consumption_Generic() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) where T : struct + { + public static S1 operator ++(S1 x) + { + System.Console.Write(typeof(T).ToString()); + return x; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + var s1 = new S1(); + s1 = ++s1; + Extensions1.op_Increment(s1); + + S1? s2 = new S1(); + _ = (++s2).GetValueOrDefault(); + s2 = null; + System.Console.Write(":"); + _ = (++s2).GetValueOrDefault(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "System.Int32System.Int32System.Int32:").VerifyDiagnostics(); + } + + [Fact] + public void Increment_042_Consumption_Generic() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S1 x) where T : struct + { + public void operator ++() + { + System.Console.Write(typeof(T).ToString()); + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + var s1 = new S1(); + s1 = ++s1; + Extensions1.op_IncrementAssignment(ref s1); + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "System.Int32System.Int32").VerifyDiagnostics(); + } + + [Fact] + public void Increment_043_Consumption_Generic_Worse() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator ++(S1 x) + { + System.Console.Write("[S1]"); + return x; + } + } + + extension(S1?) + { + public static S1? operator ++(S1? x) + { + System.Console.Write("[S1?]"); + return x; + } + } + + extension(S1) + { + public static S1 operator ++(S1 x) + { + System.Console.Write("[S1]"); + return x; + } + } + + extension(S2) + { + public static S2 operator ++(in S2 x) => throw null; + + public static S2 operator ++(S2 x) + { + System.Console.Write("[S2]"); + return x; + } + } + + extension(S2) + { + public static S2 operator ++(in S2 x) + { + System.Console.Write("[in S2]"); + return x; + } + } +} + +public struct S1 +{} + +public struct S2 +{} + +class Program +{ + static void Main() + { + var s11 = new S1(); + s11 = ++s11; + Extensions1.op_Increment(s11); + + System.Console.WriteLine(); + + var s12 = new S1(); + s12 = ++s12; + Extensions1.op_Increment(s12); + + System.Console.WriteLine(); + + var s21 = new S2(); + s21 = ++s21; + Extensions1.op_Increment(s21); + + System.Console.WriteLine(); + + var s22 = new S2(); + s22 = ++s22; + Extensions1.op_Increment(s22); + + System.Console.WriteLine(); + + S1? s13 = new S1(); + s13 = ++s13; + s13 = null; + s13 = ++s13; + + System.Console.WriteLine(); + + S1? s14 = new S1(); + s14 = ++s14; + s14 = null; + s14 = ++s14; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: @" +[S1][S1] +[S1][S1] +[in S2][in S2] +[S2][S2] +[S1] +[S1?][S1?] +").VerifyDiagnostics(); + } + + [Fact] + public void Increment_044_Consumption_Generic_Worse() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S1 x) + { + public void operator ++() + { + System.Console.Write("[S1]"); + } + } + + extension(ref S1? x) + { + public void operator ++() + { + System.Console.Write("[S1?]"); + } + } + + extension(ref S1 x) + { + public void operator ++() + { + System.Console.Write("[S1]"); + } + } + + extension(ref S1? x) + { + public void operator ++() + { + System.Console.Write("[S1?]"); + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + var s11 = new S1(); + s11 = ++s11; + Extensions1.op_IncrementAssignment(ref s11); + + System.Console.WriteLine(); + + var s12 = new S1(); + s12 = ++s12; + Extensions1.op_IncrementAssignment(ref s12); + + System.Console.WriteLine(); + + S1? s13 = new S1(); + s13 = ++s13; + s13 = null; + s13 = ++s13; + + System.Console.WriteLine(); + + S1? s14 = new S1(); + s14 = ++s14; + s14 = null; + s14 = ++s14; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: @" +[S1][S1] +[S1][S1] +[S1?][S1?] +[S1?][S1?] +").VerifyDiagnostics(); + } + + [Fact] + public void Increment_045_Consumption_Generic_ConstraintsViolation() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) where T : class + { + public static S1 operator ++(S1 x) => throw null; + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + var s1 = new S1(); + _ = ++s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (17,13): error CS0023: Operator '++' cannot be applied to operand of type 'S1' + // _ = ++s1; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "++s1").WithArguments("++", "S1").WithLocation(17, 13) + ); + } + + [Fact] + public void Increment_046_Consumption_Generic_ConstraintsViolation() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S1 x) where T : class + { + public void operator ++() => throw null; + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + var s1 = new S1(); + _ = ++s1; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (17,13): error CS0023: Operator '++' cannot be applied to operand of type 'S1' + // _ = ++s1; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "++s1").WithArguments("++", "S1").WithLocation(17, 13) + ); + } + + [Fact] + public void Increment_047_Consumption_OverloadResolutionPriority() + { + var src = $$$""" +using System.Runtime.CompilerServices; + +public static class Extensions1 +{ + extension(C1) + { + [OverloadResolutionPriority(1)] + public static C2 operator ++(C1 x) + { + System.Console.Write("C1"); + return (C2)x; + } + } + extension(C2) + { + public static C2 operator ++(C2 x) + { + System.Console.Write("C2"); + return x; + } + } + extension(C3) + { + public static C4 operator ++(C3 x) + { + System.Console.Write("C3"); + return (C4)x; + } + } + extension(C4) + { + public static C4 operator ++(C4 x) + { + System.Console.Write("C4"); + return x; + } + } +} + +public class C1; +public class C2 : C1; + +public class C3; +public class C4 : C3; + +class Program +{ + static void Main() + { + var c2 = new C2(); + _ = ++c2; + var c4 = new C4(); + _ = ++c4; + } +} +"""; + + var comp = CreateCompilation([src, OverloadResolutionPriorityAttributeDefinition], options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "C1C4").VerifyDiagnostics(); + } + + [Fact] + public void Increment_048_Consumption_OverloadResolutionPriority() + { + var src = $$$""" +using System.Runtime.CompilerServices; + +public static class Extensions1 +{ + extension(C1 x) + { + [OverloadResolutionPriority(1)] + public void operator ++() + { + System.Console.Write("C1"); + } + } + extension(C2 x) + { + public void operator ++() + { + System.Console.Write("C2"); + } + } + extension(C3 x) + { + public void operator ++() + { + System.Console.Write("C3"); + } + } + extension(C4 x) + { + public void operator ++() + { + System.Console.Write("C4"); + } + } +} + +public class C1; +public class C2 : C1; + +public class C3; +public class C4 : C3; + +class Program +{ + static void Main() + { + var c2 = new C2(); + _ = ++c2; + var c4 = new C4(); + _ = ++c4; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation([src, OverloadResolutionPriorityAttributeDefinition], options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "C1C4").VerifyDiagnostics(); + } + + [Fact] + public void Increment_049_Consumption_Checked() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator --(C1 x) + { + System.Console.Write("regular"); + return x; + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = --c1; + + checked + { + _ = --c1; + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "regularregular").VerifyDiagnostics(); + } + + [Fact] + public void Increment_050_Consumption_Checked() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1 x) + { + public void operator --() + { + System.Console.Write("regular"); + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = --c1; + + checked + { + _ = --c1; + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "regularregular").VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void Increment_051_Consumption_Checked([CombinatorialValues("++", "--")] string op, [CombinatorialValues("struct", "class")] string typeKind) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator {{{op}}}(C1 x) + { + System.Console.Write("regular"); + return x; + } + public static C1 operator checked {{{op}}}(C1 x) + { + System.Console.Write("checked"); + return x; + } + } +} + +public {{{typeKind}}} C1; +"""; + var src2 = $$$""" +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = {{{op}}}c1; + + checked + { + _ = {{{op}}}c1; + } + } +} +"""; + + var comp1 = CreateCompilation([src1, src2], options: TestOptions.DebugExe); + CompileAndVerify(comp1, expectedOutput: "regularchecked").VerifyDiagnostics(); + + var comp2 = CreateCompilation([src1, src2], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: "regularchecked").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1.ToMetadataReference()], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (6,13): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = ++c1; + Diagnostic(ErrorCode.ERR_FeatureInPreview, op + "c1").WithArguments("extensions").WithLocation(6, 13), + // (10,17): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = ++c1; + Diagnostic(ErrorCode.ERR_FeatureInPreview, op + "c1").WithArguments("extensions").WithLocation(10, 17) + ); + } + + [Theory] + [CombinatorialData] + public void Increment_052_Consumption_Checked([CombinatorialValues("++", "--")] string op, [CombinatorialValues("struct", "class")] string typeKind) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension({{{(typeKind == "struct" ? "ref " : "")}}}C1 x) + { + public void operator {{{op}}}() + { + System.Console.Write("regular"); + } + public void operator checked {{{op}}}() + { + System.Console.Write("checked"); + } + } +} + +public {{{typeKind}}} C1; +"""; + var src2 = $$$""" +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = {{{op}}}c1; + + checked + { + _ = {{{op}}}c1; + } + } +} +"""; + + var comp1 = CreateCompilation([src1, src2, CompilerFeatureRequiredAttribute], options: TestOptions.DebugExe); + CompileAndVerify(comp1, expectedOutput: "regularchecked").VerifyDiagnostics(); + + var comp2 = CreateCompilation([src1, src2, CompilerFeatureRequiredAttribute], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: "regularchecked").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1.ToMetadataReference()], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (6,13): error CS0023: Operator '--' cannot be applied to operand of type 'C1' + // _ = --c1; + Diagnostic(ErrorCode.ERR_BadUnaryOp, op + "c1").WithArguments(op, "C1").WithLocation(6, 13), + // (10,17): error CS0023: Operator '--' cannot be applied to operand of type 'C1' + // _ = --c1; + Diagnostic(ErrorCode.ERR_BadUnaryOp, op + "c1").WithArguments(op, "C1").WithLocation(10, 17) + ); + } + + [Fact] + public void Increment_053_Consumption_Checked() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator --(C1 x) + { + System.Console.Write("regular"); + return x; + } + } + extension(C1) + { + public static C1 operator checked --(C1 x) + { + System.Console.Write("checked"); + return x; + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = --c1; + + checked + { + _ = --c1; + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "regularchecked").VerifyDiagnostics(); + } + + [Fact] + public void Increment_054_Consumption_Checked() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1 x) + { + public void operator --() + { + System.Console.Write("regular"); + } + } + extension(C1 x) + { + public void operator checked --() + { + System.Console.Write("checked"); + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = --c1; + + checked + { + _ = --c1; + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "regularchecked").VerifyDiagnostics(); + } + + [Fact] + public void Increment_055_Consumption_Checked() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator --(C1 x) + { + return x; + } + + public static C1 operator checked --(C1 x) + { + return x; + } + } +} + +public static class Extensions2 +{ + extension(C1) + { + public static C1 operator --(C1 x) + { + return x; + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = --c1; + + checked + { + _ = --c1; + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (35,13): error CS0035: Operator '--' is ambiguous on an operand of type 'C1' + // _ = --c1; + Diagnostic(ErrorCode.ERR_AmbigUnaryOp, "--c1").WithArguments("--", "C1").WithLocation(35, 13), + // (39,17): error CS0035: Operator '--' is ambiguous on an operand of type 'C1' + // _ = --c1; + Diagnostic(ErrorCode.ERR_AmbigUnaryOp, "--c1").WithArguments("--", "C1").WithLocation(39, 17) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().Last(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); + Assert.Equal(2, symbolInfo.CandidateSymbols.Length); + AssertEx.Equal("Extensions1.extension(C1).operator checked --(C1)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("Extensions2.extension(C1).operator --(C1)", symbolInfo.CandidateSymbols[1].ToDisplayString()); + } + + [Fact] + [WorkItem("https://github.com/dotnet/roslyn/issues/78968")] + public void Increment_056_Consumption_Checked() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1 x) + { + public void operator --() + { + } + + public void operator checked --() + { + } + } +} + +public static class Extensions2 +{ + extension(C1 x) + { + public void operator --() + { + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = --c1; + + checked + { + _ = --c1; + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + +#if DEBUG // Collection of extension blocks depends on GetTypeMembersUnordered for namespace, which conditionally de-orders types for DEBUG only. + comp.VerifyEmitDiagnostics( + // (32,13): error CS0121: The call is ambiguous between the following methods or properties: 'Extensions2.extension(C1).operator --()' and 'Extensions1.extension(C1).operator --()' + // _ = --c1; + Diagnostic(ErrorCode.ERR_AmbigCall, "--").WithArguments("Extensions2.extension(C1).operator --()", "Extensions1.extension(C1).operator --()").WithLocation(32, 13), + // (36,17): error CS0121: The call is ambiguous between the following methods or properties: 'Extensions1.extension(C1).operator checked --()' and 'Extensions2.extension(C1).operator --()' + // _ = --c1; + Diagnostic(ErrorCode.ERR_AmbigCall, "--").WithArguments("Extensions1.extension(C1).operator checked --()", "Extensions2.extension(C1).operator --()").WithLocation(36, 17) + ); +#else + // https://github.com/dotnet/roslyn/issues/78968: Understand what is causing DEBUG/RELEASE behavior difference + comp.VerifyEmitDiagnostics( + // (32,13): error CS0121: The call is ambiguous between the following methods or properties: 'Extensions1.extension(C1).operator --()' and 'Extensions2.extension(C1).operator --()' + // _ = --c1; + Diagnostic(ErrorCode.ERR_AmbigCall, "--").WithArguments("Extensions1.extension(C1).operator --()", "Extensions2.extension(C1).operator --()").WithLocation(32, 13), + // (36,17): error CS0121: The call is ambiguous between the following methods or properties: 'Extensions1.extension(C1).operator checked --()' and 'Extensions2.extension(C1).operator --()' + // _ = --c1; + Diagnostic(ErrorCode.ERR_AmbigCall, "--").WithArguments("Extensions1.extension(C1).operator checked --()", "Extensions2.extension(C1).operator --()").WithLocation(36, 17) + ); +#endif + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().Last(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); + Assert.Equal(2, symbolInfo.CandidateSymbols.Length); + AssertEx.Equal("Extensions1.extension(C1).operator checked --()", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("Extensions2.extension(C1).operator --()", symbolInfo.CandidateSymbols[1].ToDisplayString()); + } + + [Fact] + public void Increment_057_Consumption_CheckedLiftedIsWorse() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator --(S1 x) => throw null; + public static S1 operator checked --(S1 x) => throw null; + } + extension(S1?) + { + public static S1? operator --(S1? x) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? s1 = new S1(); + _ = --s1; + System.Console.Write(":"); + + checked + { + _ = --s1; + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1:operator1").VerifyDiagnostics(); + } + + [Fact] + public void Increment_058_Consumption_CheckedNoLiftedForm() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S1 x) + { + public void operator --() => throw null; + public void operator checked --() => throw null; + } + extension(ref S1? x) + { + public void operator --() + { + System.Console.Write("operator1"); + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? s1 = new S1(); + _ = --s1; + System.Console.Write(":"); + + checked + { + _ = --s1; + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1:operator1").VerifyDiagnostics(); + } + + [Fact] + public void Increment_059_Consumption_OverloadResolutionPlusRegularVsChecked() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C3 operator --(C1 x) + { + System.Console.Write("C1"); + return (C3)x; + } + public static C3 operator checked --(C1 x) + { + System.Console.Write("checkedC1"); + return (C3)x; + } + } + extension(C2) + { + public static C2 operator --(C2 x) + { + System.Console.Write("C2"); + return x; + } + } +} + +public class C1; +public class C2 : C1; +public class C3 : C1; + +class Program +{ + static void Main() + { + var c3 = new C3(); + _ = --c3; + + checked + { + _ = --c3; + } + + var c2 = new C2(); + _ = --c2; + + checked + { + _ = --c2; + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "C1checkedC1C2C2").VerifyDiagnostics(); + } + + [Fact] + public void Increment_060_Consumption_OverloadResolutionPlusRegularVsChecked() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1 x) + { + public void operator --() + { + System.Console.Write("C1"); + } + public void operator checked --() + { + System.Console.Write("checkedC1"); + } + } + extension(C2 x) + { + public void operator --() + { + System.Console.Write("C2"); + } + } +} + +public class C1; +public class C2 : C1; +public class C3 : C1; + +class Program +{ + static void Main() + { + var c3 = new C3(); + _ = --c3; + + checked + { + _ = --c3; + } + + var c2 = new C2(); + _ = --c2; + + checked + { + _ = --c2; + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "C1checkedC1C2C2").VerifyDiagnostics(); + } + + [Fact] + public void Increment_061_Consumption() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1? operator ++(S1? x) + { + System.Console.Write("operator1"); + return x; + } + + public static void M1(S1? x) {} + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? s1 = new S1(); +#line 21 + _ = ++s1; + S1 s2 = new S1(); + _ = ++s2; + + System.Nullable.M1(s1); + S1.M1(s1); + S1.M1(s2); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + + comp.VerifyEmitDiagnostics( + // (5,36): error CS9318: The parameter type for ++ or -- operator must be the extended type. + // public static S1? operator ++(S1? x) + Diagnostic(ErrorCode.ERR_BadExtensionIncDecSignature, "++").WithLocation(5, 36), + // (21,13): error CS0023: Operator '++' cannot be applied to operand of type 'S1?' + // _ = ++s1; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "++s1").WithArguments("++", "S1?").WithLocation(21, 13), + // (23,13): error CS0266: Cannot implicitly convert type 'S1?' to 'S1'. An explicit conversion exists (are you missing a cast?) + // _ = ++s2; + Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "++s2").WithArguments("S1?", "S1").WithLocation(23, 13), + // (25,9): error CS1929: 'S1?' does not contain a definition for 'M1' and the best extension method overload 'Extensions1.extension(S1).M1(S1?)' requires a receiver of type 'S1' + // System.Nullable.M1(s1); + Diagnostic(ErrorCode.ERR_BadInstanceArgType, "System.Nullable").WithArguments("S1?", "M1", "Extensions1.extension(S1).M1(S1?)", "S1").WithLocation(25, 9) + ); + } + + [Fact] + public void Increment_062_Consumption_OnObject() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object) + { + public static object operator ++(object x) + { + System.Console.Write("operator1"); + return x; + } + } +} + +class Program +{ + static void Main() + { + var s1 = new object(); + _ = ++s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1").VerifyDiagnostics(); + } + + [Fact] + public void Increment_063_Consumption_OnObject() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object x) + { + public void operator ++() + { + System.Console.Write("operator1"); + } + } +} + +class Program +{ + static void Main() + { + var s1 = new object(); + _ = ++s1; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1").VerifyDiagnostics(); + } + + [Fact] + public void Increment_064_Consumption_NotOnDynamic() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object y) + { + public static object operator ++(object x) + { + System.Console.Write("operator1"); + return x; + } + public void operator ++() + { + System.Console.Write("operator2"); + } + } +} + +class Program +{ + static void Main() + { + dynamic s1 = new object(); + try + { + _ = ++s1; + } + catch + { + System.Console.Write("exception"); + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "exception").VerifyDiagnostics(); + } + + [Fact] + public void Increment_065_Consumption_BadOperand() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object y) + { + public static object operator ++(object x) + { + System.Console.Write("operator1"); + return x; + } + public void operator ++() + { + System.Console.Write("operator2"); + } + } +} + +class Program +{ + static void Main() + { +#line 19 + _ = ++null; + _ = ++default; + _ = ++new(); + _ = ++(() => 1); + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (19,15): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer + // _ = ++null; + Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "null").WithLocation(19, 15), + // (20,15): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer + // _ = ++default; + Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "default").WithLocation(20, 15), + // (21,15): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer + // _ = ++new(); + Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "new()").WithLocation(21, 15), + // (22,16): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer + // _ = ++(() => 1); + Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "() => 1").WithLocation(22, 16) + ); + } + + [Fact] + public void Increment_066_Consumption_BadOperand() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object y) + { + public void operator ++() + { + System.Console.Write("operator2"); + } + } +} + +class Program +{ + static object P {get; set;} + + static void Main() + { + _ = ++P; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (18,13): error CS0023: Operator '++' cannot be applied to operand of type 'object' + // _ = ++P; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "++P").WithArguments("++", "object").WithLocation(18, 13) + ); + } + + [Fact] + public void Increment_067_Consumption_BadReceiver() + { + var src = $$$""" +public static class Extensions1 +{ + extension(__arglist) + { + public static object operator ++(object x) + { + return x; + } + public void operator ++() + { + } + } +} + +class Program +{ + static void Main() + { + var s1 = new object(); +#line 17 + _ = ++s1; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (3,15): error CS1669: __arglist is not valid in this context + // extension(__arglist) + Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(3, 15), + // (5,39): error CS9318: The parameter type for ++ or -- operator must be the extended type. + // public static object operator ++(object x) + Diagnostic(ErrorCode.ERR_BadExtensionIncDecSignature, "++").WithLocation(5, 39), + // (17,13): error CS0023: Operator '++' cannot be applied to operand of type 'object' + // _ = ++s1; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "++s1").WithArguments("++", "object").WithLocation(17, 13) + ); + } + + [Fact] + public void Increment_068_Consumption_Checked_Generic() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator --(C1 x) + { + System.Console.Write("regular"); + return x; + } + } + extension(C1) + { + public static C1 operator checked --(C1 x) + { + System.Console.Write("checked"); + return x; + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = --c1; + + checked + { + _ = --c1; + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "regularchecked").VerifyDiagnostics(); + } + + [Fact] + public void Increment_069_Consumption_Checked_Generic() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1 x) + { + public void operator --() + { + System.Console.Write("regular"); + } + } + extension(C1 x) + { + public void operator checked --() + { + System.Console.Write("checked"); + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = --c1; + + checked + { + _ = --c1; + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "regularchecked").VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void Increment_070_Consumption_Postfix(bool fromMetadata) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator ++(S1 x) + { + System.Console.Write("operator1:"); + System.Console.Write(x.F); + return new S1 { F = x.F + 1 }; + } + } +} + +public struct S1 +{ + public int F; +} +"""; + + var src2 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1() { F = 101 }; + s1++; + System.Console.Write(":"); + System.Console.Write(s1.F); + System.Console.Write(":"); + var s2 = s1++; + System.Console.Write(":"); + System.Console.Write(s2.F); + System.Console.Write(":"); + System.Console.Write(s1.F); + } +} +"""; + + var comp1 = CreateCompilation(src1); + var comp1Ref = fromMetadata ? comp1.EmitToImageReference() : comp1.ToMetadataReference(); + + var comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp2, expectedOutput: "operator1:101:102:operator1:102:102:103").VerifyDiagnostics(); + + var tree = comp2.SyntaxTrees.First(); + var model = comp2.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("Extensions1.extension(S1).operator ++(S1)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S1", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: "operator1:101:102:operator1:102:102:103").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (6,9): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // s1++; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s1++").WithArguments("extensions").WithLocation(6, 9), + // (10,18): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // var s2 = s1++; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s1++").WithArguments("extensions").WithLocation(10, 18) + ); + } + + [Theory] + [CombinatorialData] + public void Increment_071_Consumption_Postfix(bool fromMetadata) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(ref S1 x) + { + public void operator ++() + { + System.Console.Write("operator1:"); + System.Console.Write(x.F); + x.F++; + } + } +} + +public struct S1 +{ + public int F; +} + +""" + CompilerFeatureRequiredAttribute; + + var src2 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1() { F = 101 }; + s1++; + System.Console.Write(":"); + System.Console.Write(s1.F); + } +} +"""; + + var comp1 = CreateCompilation(src1); + var comp1Ref = fromMetadata ? comp1.EmitToImageReference() : comp1.ToMetadataReference(); + + var comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp2, expectedOutput: "operator1:101:102").VerifyDiagnostics(); + + var tree = comp2.SyntaxTrees.First(); + var model = comp2.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("Extensions1.extension(ref S1).operator ++()", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("System.Void", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: "operator1:101:102").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (6,9): error CS0023: Operator '++' cannot be applied to operand of type 'S1' + // s1++; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "s1++").WithArguments("++", "S1").WithLocation(6, 9) + ); + + var src3 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1(); + _ = s1++; + } +} +"""; + var comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe); + comp3.VerifyDiagnostics( + // (6,13): error CS0023: Operator '++' cannot be applied to operand of type 'S1' + // _ = s1++; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "s1++").WithArguments("++", "S1").WithLocation(6, 13) + ); + + var src4 = $$$""" +public static class Extensions1 +{ + extension(C1 x) + { + public void operator ++() + { + System.Console.Write("operator1:"); + System.Console.Write(x.F); + x.F++; + } + } +} + +public class C1 +{ + public int F; +} + +""" + CompilerFeatureRequiredAttribute; + + var src5 = $$$""" +class Program +{ + static void Main() + { + var c1 = new C1() { F = 101 }; + var c2 = c1; + c1++; + System.Console.Write(":"); + System.Console.Write(c1.F); + System.Console.Write(":"); + System.Console.Write(ReferenceEquals(c1, c2) ? "True" : "False"); + } +} +"""; + + var comp4 = CreateCompilation(src4); + var comp4Ref = fromMetadata ? comp4.EmitToImageReference() : comp4.ToMetadataReference(); + + var comp5 = CreateCompilation(src5, references: [comp4Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp5, expectedOutput: "operator1:101:102:True").VerifyDiagnostics(); + + var src6 = $$$""" +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = c1++; + } +} +"""; + var comp6 = CreateCompilation(src6, references: [comp4Ref], options: TestOptions.DebugExe); + comp6.VerifyDiagnostics( + // (6,13): error CS0023: Operator '++' cannot be applied to operand of type 'C1' + // _ = c1++; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "c1++").WithArguments("++", "C1").WithLocation(6, 13) + ); + } + + [Fact] + public void Increment_072_Consumption_ExpressionTree() + { + var src = $$$""" +using System.Linq.Expressions; + +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator ++(S1 x) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + Expression> ex = (s1) => ++s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (22,54): error CS0832: An expression tree may not contain an assignment operator + // Expression> ex = (s1) => ++s1; + Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "++s1").WithLocation(22, 54) + ); + } + + [Fact] + public void Increment_073_Consumption_ExpressionTree() + { + var src = $$$""" +using System.Linq.Expressions; + +public static class Extensions1 +{ + extension(ref S1 x) + { + public void operator --() + { + System.Console.Write("operator1"); + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + Expression> ex = (s1) => --s1; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (21,54): error CS0832: An expression tree may not contain an assignment operator + // Expression> ex = (s1) => --s1; + Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "--s1").WithLocation(21, 54) + ); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Compound_Scoped_Left + /// + [Fact] + public void Increment_074_RefSafety() + { + var source = """ +public ref struct C +{ + public static C X(scoped C left) => throw null; + public void M(scoped C c1) + { +#line 7 + ++c1; +#line 9 + c1 = X(c1); + } +} + +static class Extensions +{ + extension(C) + { + public static C operator ++(scoped C left) => throw null; + } +} +"""; + + CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics(); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Compound_Scoped_Left + /// + [Fact] + [WorkItem("https://github.com/dotnet/roslyn/issues/78964")] + public void Increment_075_RefSafety() + { + var source = """ +public ref struct C +{ + public static C X(scoped C left) => throw null; + public C M(C c, scoped C c1) + { +#line 7 + c = ++c1; +#line 9 + c = X(c1); + return c; + } +} + +static class Extensions +{ + extension(C) + { + public static C operator ++(scoped C left) => throw null; + } +} +"""; + CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics(); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Compound_Scoped_Left + /// + [Fact] + public void Increment_076_RefSafety() + { + var source = """ +public ref struct C +{ + public C M(C c, scoped C c1) + { +#line 7 + c = c1++; + return c; + } +} + +static class Extensions +{ + extension(C) + { + public static C operator ++(scoped C left) => throw null; + } +} +"""; + CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( + // (7,13): error CS8352: Cannot use variable 'scoped C c1' in this context because it may expose referenced variables outside of their declaration scope + // c = c1++; + Diagnostic(ErrorCode.ERR_EscapeVariable, "c1++").WithArguments("scoped C c1").WithLocation(7, 13) + ); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Compound_ScopedTarget_01 + /// + [Fact] + public void Increment_077_RefSafety() + { + var source = """ +public ref struct C +{ + public C M(scoped C c, C c1) + { + c = ++c1; + return c1; + } +} + +static class Extensions +{ + extension(C) + { + public static C operator ++(C right) => right; + } +} +"""; + CreateCompilation(source).VerifyDiagnostics(); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Compound_ScopedTarget_01 + /// + [Fact] + public void Increment_078_RefSafety() + { + var source = """ +public ref struct C +{ + public C M(scoped C c, C c1) + { + c = c1++; + return c1; + } +} + +static class Extensions +{ + extension(C) + { + public static C operator ++(C right) => right; + } +} +"""; + CreateCompilation(source).VerifyDiagnostics(); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Compound_Scoped_Left + /// + [Fact] + public void Increment_079_RefSafety() + { + var source = """ +public ref struct C +{ + public void X() => throw null; + public void M(scoped C c1) + { +#line 7 + ++c1; +#line 9 + c1.X(); + } +} + +static class Extensions +{ + extension(scoped ref C left) + { + public void operator ++() => throw null; + } +} +"""; + + CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics(); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Compound_Scoped_Left + /// + [Fact] + public void Increment_080_RefSafety() + { + var source = """ +public ref struct C +{ + public void X() => throw null; + public C M(C c, scoped C c1) + { +#line 7 + c = ++c1; +#line 9 + c1.X(); + c = c1; + return c; + } +} + +static class Extensions +{ + extension(scoped ref C left) + { + public void operator ++() => throw null; + } +} +"""; + CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( + // (7,13): error CS8352: Cannot use variable 'scoped C c1' in this context because it may expose referenced variables outside of their declaration scope + // c = ++c1; + Diagnostic(ErrorCode.ERR_EscapeVariable, "++c1").WithArguments("scoped C c1").WithLocation(7, 13), + // (10,13): error CS8352: Cannot use variable 'scoped C c1' in this context because it may expose referenced variables outside of their declaration scope + // c = c1; + Diagnostic(ErrorCode.ERR_EscapeVariable, "c1").WithArguments("scoped C c1").WithLocation(10, 13) + ); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Compound_ScopedTarget_01 + /// + [Fact] + public void Increment_081_RefSafety() + { + var source = """ +public ref struct C +{ + public C M(scoped C c, C c1) + { + c = ++c1; + return c1; + } +} + +static class Extensions +{ + extension(ref C right) + { + public void operator ++() {} + } +} + +""" + CompilerFeatureRequiredAttribute; + + CreateCompilation(source).VerifyDiagnostics(); + } + + [Fact] + public void Increment_082_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator --(C1 x) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public class C1 +{} + +class Program +{ + static void Main() + { + C1? x = null; + _ = --x; + C1 y = new C1(); + y = --y; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (23,15): warning CS8604: Possible null reference argument for parameter 'x' in 'C1 extension(C1).operator --(C1 x)'. + // _ = --x; + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "C1 extension(C1).operator --(C1 x)").WithLocation(23, 15) + ); + } + + [Fact] + [WorkItem("https://github.com/dotnet/roslyn/issues/79011")] + public void Increment_083_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1) + { + public static C1? operator --(C1 x) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public class C1 +{} + +class Program +{ + static void Main() + { + C1? x = new C1(); + C1 y = --x; + C1 z = new C1(); + --z; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // This warning is unexpected - https://github.com/dotnet/roslyn/issues/79011 + // (23,16): warning CS8601: Possible null reference assignment. + // C1 y = --x; + Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "--x").WithLocation(23, 16), + + // (23,16): warning CS8600: Converting null literal or possible null value to non-nullable type. + // C1 y = --x; + Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "--x").WithLocation(23, 16), + // (25,9): warning CS8601: Possible null reference assignment. + // --z; + Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "--z").WithLocation(25, 9) + ); + } + + [Fact] + public void Increment_084_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(T) + { + public static T operator --(T x) + { + return x; + } + } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + C2? x = null; + (--x).ToString(); + var y = new C2(); + (--y).ToString(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + + comp.VerifyDiagnostics( + // (22,10): warning CS8602: Dereference of a possibly null reference. + // (--x).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "--x").WithLocation(22, 10) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNodes = tree.GetRoot().DescendantNodes().OfType().ToArray(); + + Assert.Equal(2, opNodes.Length); + AssertEx.Equal("Extensions1.extension(C2?).operator --(C2?)", model.GetSymbolInfo(opNodes[0]).Symbol.ToDisplayString()); + AssertEx.Equal("Extensions1.extension(C2).operator --(C2)", model.GetSymbolInfo(opNodes[1]).Symbol.ToDisplayString()); + } + + [Fact] + public void Increment_085_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1) where T : new() + { + public static C1 operator --(C1 x) + { + return x; + } + } +} + +public class C1 where T : new() +{ + public T F = new T(); +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = Get((C2?)null); + (--x).F.ToString(); + var y = Get(new C2()); + (--y).F.ToString(); + } + + static C1 Get(T x) where T : new() + { + return new C1(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (27,9): warning CS8602: Dereference of a possibly null reference. + // (--x).F.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(--x).F").WithLocation(27, 9) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNodes = tree.GetRoot().DescendantNodes().OfType().ToArray(); + + Assert.Equal(2, opNodes.Length); + AssertEx.Equal("Extensions1.extension(C1).operator --(C1)", model.GetSymbolInfo(opNodes[0]).Symbol.ToDisplayString()); + AssertEx.Equal("Extensions1.extension(C1).operator --(C1)", model.GetSymbolInfo(opNodes[1]).Symbol.ToDisplayString()); + } + + [Fact] + public void Increment_086_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public class C1 where T : new() +{ + public T F = new T(); + + public static C1 operator --(C1 x) + { + return x; + } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = Get((C2?)null); +#line 27 + (--x).F.ToString(); + var y = Get(new C2()); + (--y).F.ToString(); + } + + static C1 Get(T x) where T : new() + { + return new C1(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (27,9): warning CS8602: Dereference of a possibly null reference. + // (--x).F.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(--x).F").WithLocation(27, 9) + ); + } + + [Fact] + public void Increment_087_NullableAnalysis_Lifted() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(S1) where T : new() + { + public static S1 operator --(S1 x) + { + return x; + } + } +} + +public struct S1 where T : new() +{ + public T F; +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = --Get((C2?)null); + + if (x != null) + x.Value.F.ToString(); + + var y = --Get(new C2()); + + if (y != null) + y.Value.F.ToString(); + } + + static ref S1? Get(T x) where T : new() + { + throw null!; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (29,13): warning CS8602: Dereference of a possibly null reference. + // x.Value.F.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Value.F").WithLocation(29, 13) + ); + } + + [Fact] + public void Increment_088_NullableAnalysis_Lifted() + { + var src = $$$""" +#nullable enable + +public struct S1 where T : new() +{ + public T F; + + public static S1 operator --(S1 x) + { + return x; + } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = --Get((C2?)null); + + if (x != null) +#line 29 + x.Value.F.ToString(); + + var y = --Get(new C2()); + + if (y != null) + y.Value.F.ToString(); + } + + static ref S1? Get(T x) where T : new() + { + throw null!; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (29,13): warning CS8602: Dereference of a possibly null reference. + // x.Value.F.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Value.F").WithLocation(29, 13) + ); + } + + [Fact] + public void Increment_089_NullableAnalysis_Constraints() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(T) where T : notnull + { + public static T operator --(T x) + { + return x; + } + } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + C2? x = null; + (--x).ToString(); + var y = new C2(); + (--y).ToString(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + + comp.VerifyDiagnostics( + // (22,10): warning CS8714: The type 'C2?' cannot be used as type parameter 'T' in the generic type or method 'Extensions1.extension(T)'. Nullability of type argument 'C2?' doesn't match 'notnull' constraint. + // (--x).ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "--x").WithArguments("Extensions1.extension(T)", "T", "C2?").WithLocation(22, 10), + // (22,10): warning CS8602: Dereference of a possibly null reference. + // (--x).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "--x").WithLocation(22, 10) + ); + } + + [Fact] + public void Increment_090_NullableAnalysis_Constraints() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1) where T : notnull, new() + { + public static C1 operator --(C1 x) + { + return x; + } + } +} + +public class C1 where T : new() +{ + public T F = new T(); +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = Get((C2?)null); + (--x).F.ToString(); + var y = Get(new C2()); + (--y).F.ToString(); + } + + static C1 Get(T x) where T : new() + { + return new C1(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (27,9): warning CS8602: Dereference of a possibly null reference. + // (--x).F.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(--x).F").WithLocation(27, 9), + // (27,10): warning CS8714: The type 'C2?' cannot be used as type parameter 'T' in the generic type or method 'Extensions1.extension(C1)'. Nullability of type argument 'C2?' doesn't match 'notnull' constraint. + // (--x).F.ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "--x").WithArguments("Extensions1.extension(C1)", "T", "C2?").WithLocation(27, 10) + ); + } + + [Fact] + public void Increment_091_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1 x) + { + public void operator --() {} + } + + extension(C2? x) + { + public void operator --() {} + } +} + +public class C1 +{} + +public class C2 +{} + +class Program +{ + static void Main() + { + C1? x = null; + var x1 = --x; + x.ToString(); + x1.ToString(); + + C1 y = new C1(); + var y1 = --y; + y.ToString(); + y1.ToString(); + + C2? z = null; + var z1 = --z; + z.ToString(); + z1.ToString(); + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (27,20): warning CS8604: Possible null reference argument for parameter 'x' in 'extension(C1)'. + // var x1 = --x; + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "extension(C1)").WithLocation(27, 20), + // (38,9): warning CS8602: Dereference of a possibly null reference. + // z.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(38, 9), + // (39,9): warning CS8602: Dereference of a possibly null reference. + // z1.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z1").WithLocation(39, 9) + ); + } + + [Fact] + public void Increment_092_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +using System.Diagnostics.CodeAnalysis; + +public static class Extensions1 +{ + extension([NotNull] ref S1? x) + { + public void operator --() { throw null!; } + } + + extension([NotNull] C2? x) + { + public void operator --() { throw null!; } + } +} + +public struct S1 +{} + +public class C2 +{} + +class Program +{ + static void Main() + { + S1? x = null; + var x1 = --x; + _ = x.Value; + _ = x1.Value; + + C2? z = null; + var z1 = --z; + z.ToString(); + z1.ToString(); + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: TestOptions.DebugExe); + comp.VerifyDiagnostics(); + } + + [Fact] + public void Increment_093_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(ref S1? x) + { + public void operator --() {} + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? x = null; + var x1 = --x; + _ = x.Value; + _ = x1.Value; + + S1? y = new S1(); + var y1 = --y; + _ = y.Value; + _ = y1.Value; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (20,13): warning CS8629: Nullable value type may be null. + // _ = x.Value; + Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x").WithLocation(20, 13), + // (21,13): warning CS8629: Nullable value type may be null. + // _ = x1.Value; + Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x1").WithLocation(21, 13), + // (25,13): warning CS8629: Nullable value type may be null. + // _ = y.Value; + Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y").WithLocation(25, 13), + // (26,13): warning CS8629: Nullable value type may be null. + // _ = y1.Value; + Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y1").WithLocation(26, 13) + ); + } + + [Fact] + public void Increment_094_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(ref S1? x) + { + public void operator --() {} + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + _ = Get(new S1()).Value; + var y1 = --Get(new S1()); +#line 26 + _ = y1.Value; + } + + [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull("x")] + static ref S1? Get(S1? x) => throw null!; +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (26,13): warning CS8629: Nullable value type may be null. + // _ = y1.Value; + Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y1").WithLocation(26, 13) + ); + } + + [Fact] + public void Increment_095_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1Base x) + { + public void operator --() {} + } + + extension(C2Base? x) + { + public void operator --() {} + } +} + +public class C1Base {} +public class C1 : C1Base {} + +public class C2Base {} +public class C2 : C2Base {} + +class Program +{ + static void Main() + { + C1? x = null; + var x1 = --x; + x.ToString(); + x1.ToString(); + + C1 y = new C1(); + var y1 = --y; + y.ToString(); + y1.ToString(); + + C2? z = null; + var z1 = --z; + z.ToString(); + z1.ToString(); + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (27,20): warning CS8604: Possible null reference argument for parameter 'x' in 'extension(C1Base)'. + // var x1 = --x; + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "extension(C1Base)").WithLocation(27, 20), + // (38,9): warning CS8602: Dereference of a possibly null reference. + // z.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(38, 9), + // (39,9): warning CS8602: Dereference of a possibly null reference. + // z1.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z1").WithLocation(39, 9) + ); + } + + [Fact] + public void Increment_096_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C2Base x) + { + public void operator --() {} + } +} + +public class C2Base {} +public class C2 : C2Base {} + +class Program +{ + static void Main() + { + C2 z = new C2(); + var z1 = --z; + z.ToString(); + z1.ToString(); + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (19,20): warning CS8620: Argument of type 'C2' cannot be used for parameter 'x' of type 'C2Base' in 'extension(C2Base)' due to differences in the nullability of reference types. + // var z1 = --z; + Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("C2", "C2Base", "x", "extension(C2Base)").WithLocation(19, 20) + ); + } + + [Fact] + public void Increment_097_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +using System.Diagnostics.CodeAnalysis; + +public static class Extensions1 +{ + extension([NotNull] C2Base? x) + { + public void operator --() { throw null!; } + } +} + +public class C2Base +{} + +public class C2 : C2Base +{} + +class Program +{ + static void Main() + { + C2? z = null; + var z1 = --z; + z.ToString(); + z1.ToString(); + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: TestOptions.DebugExe); + comp.VerifyDiagnostics(); + } + + [Fact] + public void Increment_098_NullableAnalysis_Constraints() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(T x) where T : class + { + public void operator --() {} + } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + C2? x = null; + (--x).ToString(); + var y = new C2(); + (--y).ToString(); + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (19,10): warning CS8634: The type 'C2?' cannot be used as type parameter 'T' in the generic type or method 'Extensions1.extension(T)'. Nullability of type argument 'C2?' doesn't match 'class' constraint. + // (--x).ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "--x").WithArguments("Extensions1.extension(T)", "T", "C2?").WithLocation(19, 10), + // (19,10): warning CS8602: Dereference of a possibly null reference. + // (--x).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "--x").WithLocation(19, 10) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNodes = tree.GetRoot().DescendantNodes().OfType().ToArray(); + + Assert.Equal(2, opNodes.Length); + AssertEx.Equal("Extensions1.extension(C2?).operator --()", model.GetSymbolInfo(opNodes[0]).Symbol.ToDisplayString()); + AssertEx.Equal("Extensions1.extension(C2).operator --()", model.GetSymbolInfo(opNodes[1]).Symbol.ToDisplayString()); + } + + [Fact] + public void Increment_099_NullableAnalysis_Constraints() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1 x) where T : notnull, new() + { + public void operator --() {} + } +} + +public class C1 where T : new() +{ + public T F = new T(); +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = Get((C2?)null); + (--x).F.ToString(); + var y = Get(new C2()); + (--y).F.ToString(); + } + + static C1 Get(T x) where T : new() + { + return new C1(); + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (24,9): warning CS8602: Dereference of a possibly null reference. + // (--x).F.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(--x).F").WithLocation(24, 9), + // (24,10): warning CS8714: The type 'C2?' cannot be used as type parameter 'T' in the generic type or method 'Extensions1.extension(C1)'. Nullability of type argument 'C2?' doesn't match 'notnull' constraint. + // (--x).F.ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "--x").WithArguments("Extensions1.extension(C1)", "T", "C2?").WithLocation(24, 10) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNodes = tree.GetRoot().DescendantNodes().OfType().ToArray(); + + Assert.Equal(2, opNodes.Length); + AssertEx.Equal("Extensions1.extension(C1).operator --()", model.GetSymbolInfo(opNodes[0]).Symbol.ToDisplayString()); + AssertEx.Equal("Extensions1.extension(C1).operator --()", model.GetSymbolInfo(opNodes[1]).Symbol.ToDisplayString()); + } + + [Fact] + public void Increment_100_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(T x) where T : class? + { + public void operator --() {} + } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + C2? x = null; + (--x).ToString(); + var y = new C2(); + (--y).ToString(); + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (19,10): warning CS8602: Dereference of a possibly null reference. + // (--x).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "--x").WithLocation(19, 10) + ); + } + + [Fact] + public void Increment_101_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1 x) where T : new() + { + public void operator --() {} + } +} + +public class C1 where T : new() +{ + public T F = new T(); +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = Get((C2?)null); + (--x).F.ToString(); + var y = Get(new C2()); + (--y).F.ToString(); + } + + static C1 Get(T x) where T : new() + { + return new C1(); + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (24,9): warning CS8602: Dereference of a possibly null reference. + // (--x).F.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(--x).F").WithLocation(24, 9) + ); + } + + [Fact] + public void Increment_102_Declaration_Extern() + { + var src = $$$""" +using System.Runtime.InteropServices; + +public static class Extensions1 +{ + extension(C2 x) + { + extern public void operator --() {} + + [DllImport("something.dll")] + public void operator ++() {} + } +} + +public class C2 +{} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src); + comp.VerifyDiagnostics( + // (7,37): error CS0179: 'Extensions1.extension(C2).operator --()' cannot be extern and declare a body + // extern public void operator --() {} + Diagnostic(ErrorCode.ERR_ExternHasBody, "--").WithArguments("Extensions1.extension(C2).operator --()").WithLocation(7, 37), + // (9,10): error CS0601: The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member + // [DllImport("something.dll")] + Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(9, 10) + ); + } + + [Fact] + public void Increment_103_Declaration_Extern() + { + var source = """ +using System.Runtime.InteropServices; +static class E +{ + extension(C2 x) + { + [DllImport("something.dll")] + extern public void operator --(); + } +} + +public class C2 +{} + +""" + CompilerFeatureRequiredAttribute; + + var verifier = CompileAndVerify(source).VerifyDiagnostics(); + + verifier.VerifyTypeIL("E", """ +.class private auto ansi abstract sealed beforefieldinit E + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( + 01 00 00 00 + ) + // Nested Types + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + // Methods + .method private hidebysig specialname static + void '$' ( + class C2 x + ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( + 01 00 00 00 + ) + // Method begins at RVA 0x2097 + // Code size 1 (0x1) + .maxstack 8 + IL_0000: ret + } // end of method '<>E__0'::'$' + .method public hidebysig specialname + instance void op_DecrementAssignment () cil managed + { + .custom instance void System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute::.ctor(string) = ( + 01 00 26 55 73 65 72 44 65 66 69 6e 65 64 43 6f + 6d 70 6f 75 6e 64 41 73 73 69 67 6e 6d 65 6e 74 + 4f 70 65 72 61 74 6f 72 73 00 00 + ) + // Method begins at RVA 0x2099 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::op_DecrementAssignment + } // end of class <>E__0 + // Methods + .method public hidebysig static pinvokeimpl("something.dll" winapi) + void op_DecrementAssignment ( + class C2 x + ) cil managed preservesig + { + } // end of method E::op_DecrementAssignment +} // end of class E +""".Replace("[mscorlib]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[mscorlib]")); + } + + [Fact] + public void Increment_104_Declaration_Extern() + { + var source = """ +static class E +{ + extension(C2 x) + { + extern public void operator --(); + } +} + +public class C2 +{} + +""" + CompilerFeatureRequiredAttribute; + + var verifier = CompileAndVerify(source, verify: Verification.FailsPEVerify with { PEVerifyMessage = """ + Error: Method marked Abstract, Runtime, InternalCall or Imported must have zero RVA, and vice versa. + Type load failed. + """ }); + + verifier.VerifyDiagnostics( + // (5,37): warning CS0626: Method, operator, or accessor 'E.extension(C2).operator --()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. + // extern public void operator --(); + Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "--").WithArguments("E.extension(C2).operator --()").WithLocation(5, 37) + ); + + verifier.VerifyTypeIL("E", """ +.class private auto ansi abstract sealed beforefieldinit E + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( + 01 00 00 00 + ) + // Nested Types + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + // Methods + .method private hidebysig specialname static + void '$' ( + class C2 x + ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( + 01 00 00 00 + ) + // Method begins at RVA 0x2097 + // Code size 1 (0x1) + .maxstack 8 + IL_0000: ret + } // end of method '<>E__0'::'$' + .method public hidebysig specialname + instance void op_DecrementAssignment () cil managed + { + .custom instance void System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute::.ctor(string) = ( + 01 00 26 55 73 65 72 44 65 66 69 6e 65 64 43 6f + 6d 70 6f 75 6e 64 41 73 73 69 67 6e 6d 65 6e 74 + 4f 70 65 72 61 74 6f 72 73 00 00 + ) + // Method begins at RVA 0x2099 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::op_DecrementAssignment + } // end of class <>E__0 + // Methods + .method public hidebysig static + void op_DecrementAssignment ( + class C2 x + ) cil managed + { + } // end of method E::op_DecrementAssignment +} // end of class E +""".Replace("[mscorlib]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[mscorlib]")); + } + + [Fact] + public void Increment_105_Declaration_Extern() + { + var source = """ +static class E +{ + extension(C2 x) + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)] + extern public void operator --(); + } +} + +public class C2 +{} + +""" + CompilerFeatureRequiredAttribute; + + var verifier = CompileAndVerify(source).VerifyDiagnostics(); + + verifier.VerifyTypeIL("E", """ +.class private auto ansi abstract sealed beforefieldinit E + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( + 01 00 00 00 + ) + // Nested Types + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + // Methods + .method private hidebysig specialname static + void '$' ( + class C2 x + ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( + 01 00 00 00 + ) + // Method begins at RVA 0x2097 + // Code size 1 (0x1) + .maxstack 8 + IL_0000: ret + } // end of method '<>E__0'::'$' + .method public hidebysig specialname + instance void op_DecrementAssignment () cil managed + { + .custom instance void System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute::.ctor(string) = ( + 01 00 26 55 73 65 72 44 65 66 69 6e 65 64 43 6f + 6d 70 6f 75 6e 64 41 73 73 69 67 6e 6d 65 6e 74 + 4f 70 65 72 61 74 6f 72 73 00 00 + ) + // Method begins at RVA 0x2099 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::op_DecrementAssignment + } // end of class <>E__0 + // Methods + .method public hidebysig static + void op_DecrementAssignment ( + class C2 x + ) cil managed internalcall + { + } // end of method E::op_DecrementAssignment +} // end of class E +""".Replace("[mscorlib]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[mscorlib]")); + } + + [Theory] + [CombinatorialData] + public void Increment_106_Consumption_CRef([CombinatorialValues("++", "--")] string op) + { + var src = $$$""" +/// +/// +public static class E +{ + /// + extension(S1) + { + /// + public static S1 operator {{{op}}}(S1 x) => throw null; + } +} + +/// +public struct S1; +"""; + + var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreviewWithDocumentationComments); + comp.VerifyEmitDiagnostics(); + + var opName = UnaryOperatorName(op); + + var e = comp.GetMember("E"); + AssertEx.Equal($$$""" + + + + + +""", e.GetDocumentationCommentXml()); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + AssertEx.Equal([ + "(E.extension(S1).operator " + op + ", S1 E.<>E__0." + opName + "(S1 x))", + "(E.extension(S1).operator " + op + "(S1), S1 E.<>E__0." + opName + "(S1 x))"], + ExtensionTests.PrintXmlCrefSymbols(tree, model)); + } + + [Theory] + [CombinatorialData] + public void Increment_107_Consumption_CRef([CombinatorialValues("++", "--")] string op) + { + var src = $$$""" +/// +public static class E +{ + /// + extension(ref S1 x) + { + /// + public void operator {{{op}}}() => throw null; + } +} + +/// +public struct S1; +"""; + + var comp = CreateCompilation([src, CompilerFeatureRequiredAttribute], parseOptions: TestOptions.RegularPreviewWithDocumentationComments); + comp.VerifyEmitDiagnostics(); + + var opName = CompoundAssignmentOperatorName(op); + + var e = comp.GetMember("E"); + AssertEx.Equal($$$""" + + + + +""", e.GetDocumentationCommentXml()); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + AssertEx.Equal(["(E.extension(ref S1).operator " + op + "(), void E.<>E__0." + opName + "())"], + ExtensionTests.PrintXmlCrefSymbols(tree, model)); + } + + [Theory] + [CombinatorialData] + public void Increment_108_Consumption_CRef_Checked([CombinatorialValues("++", "--")] string op) + { + var src = $$$""" +/// +/// +public static class E +{ + /// + extension(S1) + { + /// + public static S1 operator {{{op}}}(S1 x) => throw null; + /// + public static S1 operator checked {{{op}}}(S1 x) => throw null; + } +} + +/// +public struct S1; +"""; + + var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreviewWithDocumentationComments); + comp.VerifyEmitDiagnostics(); + + var opName = UnaryOperatorName(op, isChecked: true); + + var e = comp.GetMember("E"); + AssertEx.Equal($$$""" + + + + + +""", e.GetDocumentationCommentXml()); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + AssertEx.Equal([ + "(E.extension(S1).operator checked " + op + ", S1 E.<>E__0." + opName + "(S1 x))", + "(E.extension(S1).operator checked " + op + "(S1), S1 E.<>E__0." + opName + "(S1 x))"], + ExtensionTests.PrintXmlCrefSymbols(tree, model)); + } + + [Theory] + [CombinatorialData] + public void Increment_109_Consumption_CRef_Checked([CombinatorialValues("++", "--")] string op) + { + var src = $$$""" +/// +public static class E +{ + /// + extension(ref S1 x) + { + /// + public void operator {{{op}}}() => throw null; + /// + public void operator checked {{{op}}}() => throw null; + } +} + +/// +public struct S1; +"""; + + var comp = CreateCompilation([src, CompilerFeatureRequiredAttribute], parseOptions: TestOptions.RegularPreviewWithDocumentationComments); + comp.VerifyEmitDiagnostics(); + + var opName = CompoundAssignmentOperatorName(op, isChecked: true); + + var e = comp.GetMember("E"); + AssertEx.Equal($$$""" + + + + +""", e.GetDocumentationCommentXml()); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + AssertEx.Equal(["(E.extension(ref S1).operator checked " + op + "(), void E.<>E__0." + opName + "())"], + ExtensionTests.PrintXmlCrefSymbols(tree, model)); + } + + [Theory] + [CombinatorialData] + public void Increment_110_Consumption_CRef_Error([CombinatorialValues("++", "--")] string op) + { + var src = $$$""" +/// +/// +/// +/// +/// +/// +public static class E +{ + /// + extension(S1) + { + } +} + +/// +public struct S1; +"""; + + var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreviewWithDocumentationComments); + comp.VerifyEmitDiagnostics( + // (1,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator ++' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator " + op).WithArguments("extension(S1).operator " + op).WithLocation(1, 16), + // (2,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator ++()' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator " + op + "()").WithArguments("extension(S1).operator " + op + "()").WithLocation(2, 16), + // (3,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator ++(S1)' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator " + op + "(S1)").WithArguments("extension(S1).operator " + op + "(S1)").WithLocation(3, 16), + // (4,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator checked ++' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator checked " + op).WithArguments("extension(S1).operator checked " + op).WithLocation(4, 16), + // (5,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator checked ++()' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator checked " + op + "()").WithArguments("extension(S1).operator checked " + op + "()").WithLocation(5, 16), + // (6,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator checked ++(S1)' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator checked " + op + "(S1)").WithArguments("extension(S1).operator checked " + op + "(S1)").WithLocation(6, 16) + ); + } + + [Theory] + [CombinatorialData] + public void Increment_111_ERR_VoidError([CombinatorialValues("++", "--")] string op) + { + var src = $$$""" +unsafe public static class Extensions1 +{ + extension(void*) + { + public static void* operator {{{op}}}(void* x) => x; + } +} + +class Program +{ + unsafe void* Test(void* x) => {{{op}}}x; +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugDll.WithAllowUnsafe(true)); + comp.VerifyDiagnostics( + // (3,15): error CS1103: The receiver parameter of an extension cannot be of type 'void*' + // extension(void*) + Diagnostic(ErrorCode.ERR_BadTypeforThis, "void*").WithArguments("void*").WithLocation(3, 15), + // (11,35): error CS0242: The operation in question is undefined on void pointers + // unsafe void* Test(void* x) => ++x; + Diagnostic(ErrorCode.ERR_VoidError, op + "x").WithLocation(11, 35) + ); + } + + [Theory] + [CombinatorialData] + public void Increment_112_ERR_VoidError([CombinatorialValues("++", "--")] string op) + { + var src = $$$""" +unsafe public static class Extensions1 +{ + extension(ref void* x) + { + public void operator {{{op}}}() {} + } +} + +class Program +{ + unsafe void* Test(void* x) => {{{op}}}x; +} +"""; + + var comp = CreateCompilation([src, CompilerFeatureRequiredAttribute], options: TestOptions.DebugDll.WithAllowUnsafe(true)); + comp.VerifyDiagnostics( + // (3,19): error CS1103: The receiver parameter of an extension cannot be of type 'void*' + // extension(ref void* x) + Diagnostic(ErrorCode.ERR_BadTypeforThis, "void*").WithArguments("void*").WithLocation(3, 19), + // (11,35): error CS0242: The operation in question is undefined on void pointers + // unsafe void* Test(void* x) => ++x; + Diagnostic(ErrorCode.ERR_VoidError, op + "x").WithLocation(11, 35) + ); + } + + [Fact] + public void Increment_113_Consumption_ErrorScenarioCandidates() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S2 x) + { + public void operator ++() => throw null; + } +} + +public static class Extensions2 +{ + extension(ref S2 x) + { + public void operator ++() => throw null; + } +} + +public struct S2 +{ +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + ++s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + +#if DEBUG // Collection of extension blocks depends on GetTypeMembersUnordered for namespace, which conditionally de-orders types for DEBUG only. + comp.VerifyDiagnostics( + // (26,9): error CS0121: The call is ambiguous between the following methods or properties: 'Extensions2.extension(ref S2).operator ++()' and 'Extensions1.extension(ref S2).operator ++()' + // ++s2; + Diagnostic(ErrorCode.ERR_AmbigCall, "++").WithArguments("Extensions2.extension(ref S2).operator ++()", "Extensions1.extension(ref S2).operator ++()").WithLocation(26, 9) + ); +#else + comp.VerifyDiagnostics( + // (26,9): error CS0121: The call is ambiguous between the following methods or properties: 'Extensions1.extension(ref S2).operator ++()' and 'Extensions2.extension(ref S2).operator ++()' + // ++s2; + Diagnostic(ErrorCode.ERR_AmbigCall, "++").WithArguments("Extensions1.extension(ref S2).operator ++()", "Extensions2.extension(ref S2).operator ++()").WithLocation(26, 9) + ); +#endif + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); + +#if DEBUG // Collection of extension blocks depends on GetTypeMembersUnordered for namespace, which conditionally de-orders types for DEBUG only. + AssertEx.Equal("Extensions2.extension(ref S2).operator ++()", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("Extensions1.extension(ref S2).operator ++()", symbolInfo.CandidateSymbols[1].ToDisplayString()); +#else + AssertEx.Equal("Extensions1.extension(ref S2).operator ++()", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("Extensions2.extension(ref S2).operator ++()", symbolInfo.CandidateSymbols[1].ToDisplayString()); +#endif + } + + [Fact] + public void Increment_114_Consumption_ErrorScenarioCandidates() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator ++(S2 x) => throw null; + } +} + +public static class Extensions2 +{ + extension(S2) + { + public static S2 operator ++(S2 x) => throw null; + } +} + +public struct S2 +{ +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + ++s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (26,9): error CS0035: Operator '++' is ambiguous on an operand of type 'S2' + // ++s2; + Diagnostic(ErrorCode.ERR_AmbigUnaryOp, "++s2").WithArguments("++", "S2").WithLocation(26, 9) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); + +#if DEBUG // Collection of extension blocks depends on GetTypeMembersUnordered for namespace, which conditionally de-orders types for DEBUG only. + AssertEx.Equal("Extensions2.extension(S2).operator ++(S2)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("Extensions1.extension(S2).operator ++(S2)", symbolInfo.CandidateSymbols[1].ToDisplayString()); +#else + AssertEx.Equal("Extensions1.extension(S2).operator ++(S2)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("Extensions2.extension(S2).operator ++(S2)", symbolInfo.CandidateSymbols[1].ToDisplayString()); +#endif + } + + [Theory] + [CombinatorialData] + public void Binary_001_Declaration([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^")] string op) + { + var src = $$$""" +static class Extensions1 +{ + extension(S1) + { + public static S2 operator {{{op}}}(S1 x, S2 y) => default; + public static S2? operator {{{op}}}(S1? x, S2 y) => default; + public static S2 operator {{{op}}}(S2 y, S1 x) => default; + public static S2? operator {{{op}}}(S2 y, S1? x) => default; + } +} + +static class Extensions2 +{ + extension(S1) + { + public static S1 operator {{{op}}}(S2 x, S2 y) => default; + } +} + +static class Extensions3 +{ + extension(S1) + { + public static void operator {{{op}}}(S1 x, S2 y) {} + } +} + +static class Extensions4 +{ + extension(S1) + { + static S1 operator {{{op}}}(S1 x, S1 y) => default; + } + + extension(S2) + { + public S2 operator {{{op}}}(S2 x, S2 y) => default; + } + + extension(C1) + { + public static S1 operator {{{op}}}(C1 x, S1 y) => default; + } +} + +static class Extensions5 +{ + extension(S1?) + { + public static S2 operator {{{op}}}(S1 x, S1 y) => default; + public static S2 operator {{{op}}}(S1? x, S2 y) => default; + public static S2 operator {{{op}}}(S2 y, S1? x) => default; + } +} + +struct S1 +{} + +struct S2 +{} + +static class C1 +{} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (6,36): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S2? operator +(S1? x, S2 y) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, op).WithLocation(6, 36), + // (8,36): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S2? operator +(S2 y, S1? x) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, op).WithLocation(8, 36), + // (16,35): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S1 operator -(S2 x, S2 y) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, op).WithLocation(16, 35), + // (24,37): error CS0590: User-defined operators cannot return void + // public static void operator +(S1 x, S2 y) {} + Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, op).WithLocation(24, 37), + // (32,28): error CS0558: User-defined operator 'Extensions4.extension(S1).operator +(S1, S1)' must be declared static and public + // static S1 operator +(S1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_OperatorsMustBeStaticAndPublic, op).WithArguments("Extensions4.extension(S1).operator " + op + "(S1, S1)").WithLocation(32, 28), + // (37,28): error CS0558: User-defined operator 'Extensions4.extension(S2).operator +(S2, S2)' must be declared static and public + // public S2 operator +(S2 x, S2 y) => default; + Diagnostic(ErrorCode.ERR_OperatorsMustBeStaticAndPublic, op).WithArguments("Extensions4.extension(S2).operator " + op + "(S2, S2)").WithLocation(37, 28), + // (42,35): error CS9321: An extension block extending a static class cannot contain user-defined operators + // public static S1 operator +(C1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_OperatorInExtensionOfStaticClass, op).WithLocation(42, 35), + // (42,37): error CS0721: 'C1': static types cannot be used as parameters + // public static S1 operator +(C1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "C1").WithArguments("C1").WithLocation(42, 37), + // (50,35): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S2 operator +(S1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, op).WithLocation(50, 35) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_002_Declaration([CombinatorialValues("<<", ">>", ">>>")] string op) + { + var src = $$$""" +static class Extensions1 +{ + extension(S1) + { + public static S2 operator {{{op}}}(S1 x, S2 y) => default; + public static S2? operator {{{op}}}(S1? x, S2 y) => default; + } +} + +static class Extensions2 +{ + extension(S1) + { + public static S1 operator {{{op}}}(S2 x, S1 y) => default; + } +} + +static class Extensions3 +{ + extension(S1) + { + public static void operator {{{op}}}(S1 x, S2 y) {} + } +} + +static class Extensions4 +{ + extension(S1) + { + static S1 operator {{{op}}}(S1 x, S1 y) => default; + } + extension(S2) + { + public S2 operator {{{op}}}(S2 x, S2 y) => default; + } + extension(C1) + { + public static S1 operator {{{op}}}(C1 x, S1 y) => default; + } +} + +static class Extensions5 +{ + extension(S1?) + { + public static S2 operator {{{op}}}(S1 x, S1 y) => default; + public static S2 operator {{{op}}}(S1? x, S2 y) => default; + public static S2 operator {{{op}}}(S2 y, S1? x) => default; + } +} + +struct S1 +{} + +struct S2 +{} + +static class C1 +{} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (6,36): error CS9320: The first operand of an overloaded shift operator must have the same type as the extended type + // public static S2? operator <<(S1? x, S2 y) => default; + Diagnostic(ErrorCode.ERR_BadExtensionShiftOperatorSignature, op).WithLocation(6, 36), + // (14,35): error CS9320: The first operand of an overloaded shift operator must have the same type as the extended type + // public static S1 operator <<(S2 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_BadExtensionShiftOperatorSignature, op).WithLocation(14, 35), + // (22,37): error CS0590: User-defined operators cannot return void + // public static void operator <<(S1 x, S2 y) {} + Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, op).WithLocation(22, 37), + // (30,28): error CS0558: User-defined operator 'Extensions4.extension(S1).operator <<(S1, S1)' must be declared static and public + // static S1 operator <<(S1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_OperatorsMustBeStaticAndPublic, op).WithArguments("Extensions4.extension(S1).operator " + op + "(S1, S1)").WithLocation(30, 28), + // (34,28): error CS0558: User-defined operator 'Extensions4.extension(S2).operator <<(S2, S2)' must be declared static and public + // public S2 operator <<(S2 x, S2 y) => default; + Diagnostic(ErrorCode.ERR_OperatorsMustBeStaticAndPublic, op).WithArguments("Extensions4.extension(S2).operator " + op + "(S2, S2)").WithLocation(34, 28), + // (38,35): error CS9321: An extension block extending a static class cannot contain user-defined operators + // public static S1 operator >>>(C1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_OperatorInExtensionOfStaticClass, op).WithLocation(38, 35), + // (38,39): error CS0721: 'C1': static types cannot be used as parameters + // public static S1 operator >>>(C1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "C1").WithArguments("C1").WithLocation(38, 39 - (op == ">>>" ? 0 : 1)), + // (46,35): error CS9320: The first operand of an overloaded shift operator must have the same type as the extended type + // public static S2 operator <<(S1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_BadExtensionShiftOperatorSignature, op).WithLocation(46, 35), + // (48,35): error CS9320: The first operand of an overloaded shift operator must have the same type as the extended type + // public static S2 operator <<(S2 y, S1? x) => default; + Diagnostic(ErrorCode.ERR_BadExtensionShiftOperatorSignature, op).WithLocation(48, 35) + ); + } + + [Fact] + public void Binary_003_Declaration() + { + var src = """ +static class Extensions1 +{ + extension(S1) + { +#line 100 + public static S2 operator !=(S1 x, S2 y) => default; + public static S2 operator ==(S1 x, S2 y) => default; + public static S2? operator !=(S1? x, S2 y) => default; + public static S2? operator ==(S1? x, S2 y) => default; + public static S2 operator !=(S2 y, S1 x) => default; + public static S2 operator ==(S2 y, S1 x) => default; + public static S2? operator !=(S2 y, S1? x) => default; + public static S2? operator ==(S2 y, S1? x) => default; + } +} + +static class Extensions2 +{ + extension(S1) + { +#line 200 + public static bool operator !=(S1 x, S2 y) => default; + } + + extension(S1) + { +#line 300 + public static bool operator ==(S1 x, S2 y) => default; + } +} + +static class Extensions3 +{ + extension(S1) + { +#line 400 + public static bool operator !=(S1 x, S2 y) => default; + } + + extension(S2) + { + public static bool operator ==(S2 x, S1 y) => default; + } +} + +static class Extensions4 +{ + extension(S1) + { +#line 500 + public static bool operator !=(S2 x, S2 y) => default; + public static bool operator ==(S2 x, S2 y) => default; + } +} + +static class Extensions5 +{ + extension(S1) + { +#line 600 + public static void operator !=(S1 x, S2 y) {} + public static void operator ==(S1 x, S2 y) {} + } +} + +static class Extensions6 +{ + extension(S1) + { +#line 700 + static S1 operator !=(S1 x, S1 y) => default; + public S1 operator ==(S1 x, S1 y) => default; + } + extension(C1) + { +#line 800 + public static S1 operator !=(C1 x, S1 y) => default; + public static S1 operator ==(C1 x, S1 y) => default; + } +} + +static class Extensions7 +{ + extension(S1?) + { +#line 900 + public static S2 operator !=(S1 x, S1 y) => default; + public static S2 operator !=(S1? x, S2 y) => default; + public static S2 operator !=(S2 y, S1? x) => default; + + public static S2 operator ==(S1 x, S1 y) => default; + public static S2 operator ==(S1? x, S2 y) => default; + public static S2 operator ==(S2 y, S1? x) => default; + } +} + +struct S1 +{} + +struct S2 +{} + +static class C1 +{} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (102,36): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S2? operator !=(S1? x, S2 y) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, "!=").WithLocation(102, 36), + // (103,36): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S2? operator ==(S1? x, S2 y) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, "==").WithLocation(103, 36), + // (106,36): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S2? operator !=(S2 y, S1? x) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, "!=").WithLocation(106, 36), + // (107,36): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S2? operator ==(S2 y, S1? x) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, "==").WithLocation(107, 36), + // (400,37): error CS0216: The operator 'Extensions3.extension(S1).operator !=(S1, S2)' requires a matching operator '==' to also be defined + // public static bool operator !=(S1 x, S2 y) => default; + Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "!=").WithArguments("Extensions3.extension(S1).operator !=(S1, S2)", "==").WithLocation(400, 37), + // (405,37): error CS0216: The operator 'Extensions3.extension(S2).operator ==(S2, S1)' requires a matching operator '!=' to also be defined + // public static bool operator ==(S2 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "==").WithArguments("Extensions3.extension(S2).operator ==(S2, S1)", "!=").WithLocation(405, 37), + // (500,37): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static bool operator !=(S2 x, S2 y) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, "!=").WithLocation(500, 37), + // (501,37): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static bool operator ==(S2 x, S2 y) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, "==").WithLocation(501, 37), + // (600,37): error CS0590: User-defined operators cannot return void + // public static void operator !=(S1 x, S2 y) {} + Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, "!=").WithLocation(600, 37), + // (601,37): error CS0590: User-defined operators cannot return void + // public static void operator ==(S1 x, S2 y) {} + Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, "==").WithLocation(601, 37), + // (700,28): error CS0558: User-defined operator 'Extensions6.extension(S1).operator !=(S1, S1)' must be declared static and public + // static S1 operator !=(S1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_OperatorsMustBeStaticAndPublic, "!=").WithArguments("Extensions6.extension(S1).operator !=(S1, S1)").WithLocation(700, 28), + // (701,28): error CS0558: User-defined operator 'Extensions6.extension(S1).operator ==(S1, S1)' must be declared static and public + // public S1 operator ==(S1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_OperatorsMustBeStaticAndPublic, "==").WithArguments("Extensions6.extension(S1).operator ==(S1, S1)").WithLocation(701, 28), + // (800,35): error CS9321: An extension block extending a static class cannot contain user-defined operators + // public static S1 operator !=(C1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_OperatorInExtensionOfStaticClass, "!=").WithLocation(800, 35), + // (800,38): error CS0721: 'C1': static types cannot be used as parameters + // public static S1 operator !=(C1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "C1").WithArguments("C1").WithLocation(800, 38), + // (801,35): error CS9321: An extension block extending a static class cannot contain user-defined operators + // public static S1 operator ==(C1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_OperatorInExtensionOfStaticClass, "==").WithLocation(801, 35), + // (801,38): error CS0721: 'C1': static types cannot be used as parameters + // public static S1 operator ==(C1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "C1").WithArguments("C1").WithLocation(801, 38), + // (900,35): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S2 operator !=(S1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, "!=").WithLocation(900, 35), + // (904,35): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S2 operator ==(S1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, "==").WithLocation(904, 35) + ); + } + + [Fact] + public void Binary_004_Declaration() + { + var src = """ +static class Extensions1 +{ + extension(S1) + { +#line 100 + public static S2 operator >=(S1 x, S2 y) => default; + public static S2 operator <=(S1 x, S2 y) => default; + public static S2? operator >=(S1? x, S2 y) => default; + public static S2? operator <=(S1? x, S2 y) => default; + public static S2 operator >=(S2 y, S1 x) => default; + public static S2 operator <=(S2 y, S1 x) => default; + public static S2? operator >=(S2 y, S1? x) => default; + public static S2? operator <=(S2 y, S1? x) => default; + } +} + +static class Extensions2 +{ + extension(S1) + { +#line 200 + public static bool operator >=(S1 x, S2 y) => default; + } + + extension(S1) + { +#line 300 + public static bool operator <=(S1 x, S2 y) => default; + } +} + +static class Extensions3 +{ + extension(S1) + { +#line 400 + public static bool operator >=(S1 x, S2 y) => default; + } + + extension(S2) + { + public static bool operator <=(S2 x, S1 y) => default; + } +} + +static class Extensions4 +{ + extension(S1) + { +#line 500 + public static bool operator >=(S2 x, S2 y) => default; + public static bool operator <=(S2 x, S2 y) => default; + } +} + +static class Extensions5 +{ + extension(S1) + { +#line 600 + public static void operator >=(S1 x, S2 y) {} + public static void operator <=(S1 x, S2 y) {} + } +} + +static class Extensions6 +{ + extension(S1) + { +#line 700 + static S1 operator >=(S1 x, S1 y) => default; + public S1 operator <=(S1 x, S1 y) => default; + } + extension(C1) + { +#line 800 + public static S1 operator >=(C1 x, S1 y) => default; + public static S1 operator <=(C1 x, S1 y) => default; + } +} + +static class Extensions7 +{ + extension(S1?) + { +#line 900 + public static S2 operator >=(S1 x, S1 y) => default; + public static S2 operator >=(S1? x, S2 y) => default; + public static S2 operator >=(S2 y, S1? x) => default; + + public static S2 operator <=(S1 x, S1 y) => default; + public static S2 operator <=(S1? x, S2 y) => default; + public static S2 operator <=(S2 y, S1? x) => default; + } +} + +struct S1 +{} + +struct S2 +{} + +static class C1 +{} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (102,36): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S2? operator >=(S1? x, S2 y) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, ">=").WithLocation(102, 36), + // (103,36): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S2? operator <=(S1? x, S2 y) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, "<=").WithLocation(103, 36), + // (106,36): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S2? operator >=(S2 y, S1? x) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, ">=").WithLocation(106, 36), + // (107,36): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S2? operator <=(S2 y, S1? x) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, "<=").WithLocation(107, 36), + // (400,37): error CS0216: The operator 'Extensions3.extension(S1).operator >=(S1, S2)' requires a matching operator '<=' to also be defined + // public static bool operator >=(S1 x, S2 y) => default; + Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, ">=").WithArguments("Extensions3.extension(S1).operator >=(S1, S2)", "<=").WithLocation(400, 37), + // (405,37): error CS0216: The operator 'Extensions3.extension(S2).operator <=(S2, S1)' requires a matching operator '>=' to also be defined + // public static bool operator <=(S2 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "<=").WithArguments("Extensions3.extension(S2).operator <=(S2, S1)", ">=").WithLocation(405, 37), + // (500,37): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static bool operator >=(S2 x, S2 y) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, ">=").WithLocation(500, 37), + // (501,37): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static bool operator <=(S2 x, S2 y) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, "<=").WithLocation(501, 37), + // (600,37): error CS0590: User-defined operators cannot return void + // public static void operator >=(S1 x, S2 y) {} + Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, ">=").WithLocation(600, 37), + // (601,37): error CS0590: User-defined operators cannot return void + // public static void operator <=(S1 x, S2 y) {} + Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, "<=").WithLocation(601, 37), + // (700,28): error CS0558: User-defined operator 'Extensions6.extension(S1).operator >=(S1, S1)' must be declared static and public + // static S1 operator >=(S1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_OperatorsMustBeStaticAndPublic, ">=").WithArguments("Extensions6.extension(S1).operator >=(S1, S1)").WithLocation(700, 28), + // (701,28): error CS0558: User-defined operator 'Extensions6.extension(S1).operator <=(S1, S1)' must be declared static and public + // public S1 operator <=(S1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_OperatorsMustBeStaticAndPublic, "<=").WithArguments("Extensions6.extension(S1).operator <=(S1, S1)").WithLocation(701, 28), + // (800,35): error CS9321: An extension block extending a static class cannot contain user-defined operators + // public static S1 operator >=(C1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_OperatorInExtensionOfStaticClass, ">=").WithLocation(800, 35), + // (800,38): error CS0721: 'C1': static types cannot be used as parameters + // public static S1 operator >=(C1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "C1").WithArguments("C1").WithLocation(800, 38), + // (801,35): error CS9321: An extension block extending a static class cannot contain user-defined operators + // public static S1 operator <=(C1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_OperatorInExtensionOfStaticClass, "<=").WithLocation(801, 35), + // (801,38): error CS0721: 'C1': static types cannot be used as parameters + // public static S1 operator <=(C1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "C1").WithArguments("C1").WithLocation(801, 38), + // (900,35): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S2 operator >=(S1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, ">=").WithLocation(900, 35), + // (904,35): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S2 operator <=(S1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, "<=").WithLocation(904, 35) + ); + } + + [Fact] + public void Binary_005_Declaration() + { + var src = """ +static class Extensions1 +{ + extension(S1) + { +#line 100 + public static S2 operator >(S1 x, S2 y) => default; + public static S2 operator <(S1 x, S2 y) => default; + public static S2? operator >(S1? x, S2 y) => default; + public static S2? operator <(S1? x, S2 y) => default; + public static S2 operator >(S2 y, S1 x) => default; + public static S2 operator <(S2 y, S1 x) => default; + public static S2? operator >(S2 y, S1? x) => default; + public static S2? operator <(S2 y, S1? x) => default; + } +} + +static class Extensions2 +{ + extension(S1) + { +#line 200 + public static bool operator >(S1 x, S2 y) => default; + } + + extension(S1) + { +#line 300 + public static bool operator <(S1 x, S2 y) => default; + } +} + +static class Extensions3 +{ + extension(S1) + { +#line 400 + public static bool operator >(S1 x, S2 y) => default; + } + + extension(S2) + { + public static bool operator <(S2 x, S1 y) => default; + } +} + +static class Extensions4 +{ + extension(S1) + { +#line 500 + public static bool operator >(S2 x, S2 y) => default; + public static bool operator <(S2 x, S2 y) => default; + } +} + +static class Extensions5 +{ + extension(S1) + { +#line 600 + public static void operator >(S1 x, S2 y) {} + public static void operator <(S1 x, S2 y) {} + } +} + +static class Extensions6 +{ + extension(S1) + { +#line 700 + static S1 operator >(S1 x, S1 y) => default; + public S1 operator <(S1 x, S1 y) => default; + } + extension(C1) + { +#line 800 + public static S1 operator >(C1 x, S1 y) => default; + public static S1 operator <(C1 x, S1 y) => default; + } +} + +static class Extensions7 +{ + extension(S1?) + { +#line 900 + public static S2 operator >(S1 x, S1 y) => default; + public static S2 operator >(S1? x, S2 y) => default; + public static S2 operator >(S2 y, S1? x) => default; + + public static S2 operator <(S1 x, S1 y) => default; + public static S2 operator <(S1? x, S2 y) => default; + public static S2 operator <(S2 y, S1? x) => default; + } +} + +struct S1 +{} + +struct S2 +{} + +static class C1 +{} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (102,36): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S2? operator >(S1? x, S2 y) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, ">").WithLocation(102, 36), + // (103,36): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S2? operator <(S1? x, S2 y) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, "<").WithLocation(103, 36), + // (106,36): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S2? operator >(S2 y, S1? x) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, ">").WithLocation(106, 36), + // (107,36): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S2? operator <(S2 y, S1? x) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, "<").WithLocation(107, 36), + // (400,37): error CS0216: The operator 'Extensions3.extension(S1).operator >(S1, S2)' requires a matching operator '<' to also be defined + // public static bool operator >(S1 x, S2 y) => default; + Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, ">").WithArguments("Extensions3.extension(S1).operator >(S1, S2)", "<").WithLocation(400, 37), + // (405,37): error CS0216: The operator 'Extensions3.extension(S2).operator <(S2, S1)' requires a matching operator '>' to also be defined + // public static bool operator <(S2 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "<").WithArguments("Extensions3.extension(S2).operator <(S2, S1)", ">").WithLocation(405, 37), + // (500,37): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static bool operator >(S2 x, S2 y) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, ">").WithLocation(500, 37), + // (501,37): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static bool operator <(S2 x, S2 y) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, "<").WithLocation(501, 37), + // (600,37): error CS0590: User-defined operators cannot return void + // public static void operator >(S1 x, S2 y) {} + Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, ">").WithLocation(600, 37), + // (601,37): error CS0590: User-defined operators cannot return void + // public static void operator <(S1 x, S2 y) {} + Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, "<").WithLocation(601, 37), + // (700,28): error CS0558: User-defined operator 'Extensions6.extension(S1).operator >(S1, S1)' must be declared static and public + // static S1 operator >(S1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_OperatorsMustBeStaticAndPublic, ">").WithArguments("Extensions6.extension(S1).operator >(S1, S1)").WithLocation(700, 28), + // (701,28): error CS0558: User-defined operator 'Extensions6.extension(S1).operator <(S1, S1)' must be declared static and public + // public S1 operator <(S1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_OperatorsMustBeStaticAndPublic, "<").WithArguments("Extensions6.extension(S1).operator <(S1, S1)").WithLocation(701, 28), + // (800,35): error CS9321: An extension block extending a static class cannot contain user-defined operators + // public static S1 operator >(C1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_OperatorInExtensionOfStaticClass, ">").WithLocation(800, 35), + // (800,37): error CS0721: 'C1': static types cannot be used as parameters + // public static S1 operator >(C1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "C1").WithArguments("C1").WithLocation(800, 37), + // (801,35): error CS9321: An extension block extending a static class cannot contain user-defined operators + // public static S1 operator <(C1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_OperatorInExtensionOfStaticClass, "<").WithLocation(801, 35), + // (801,37): error CS0721: 'C1': static types cannot be used as parameters + // public static S1 operator <(C1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "C1").WithArguments("C1").WithLocation(801, 37), + // (900,35): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S2 operator >(S1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, ">").WithLocation(900, 35), + // (904,35): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S2 operator <(S1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, "<").WithLocation(904, 35) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_006_Declaration([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", ">>>")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op}}}(S1 x, S1 y) => default; + } +} + +public struct S1 +{} +"""; + var comp = CreateCompilation(src); + CompileAndVerify(comp, symbolValidator: verify, sourceSymbolValidator: verify).VerifyDiagnostics(); + + void verify(ModuleSymbol m) + { + var name = BinaryOperatorName(op); + var method = m.GlobalNamespace.GetMember("Extensions1." + name); + + AssertEx.Equal("Extensions1." + name + "(S1, S1)", method.ToDisplayString()); + Assert.Equal(MethodKind.Ordinary, method.MethodKind); + Assert.True(method.IsStatic); + Assert.False(method.IsExtensionMethod); + Assert.False(method.HasSpecialName); + Assert.False(method.HasRuntimeSpecialName); + Assert.False(method.HasUnsupportedMetadata); + } + } + + private static string BinaryOperatorName(string op, bool isChecked = false) + { + var kind = op switch + { + ">>" => SyntaxKind.GreaterThanGreaterThanToken, + ">>>" => SyntaxKind.GreaterThanGreaterThanGreaterThanToken, + _ => SyntaxFactory.ParseToken(op).Kind(), + }; + return OperatorFacts.BinaryOperatorNameFromSyntaxKind(kind, isChecked); + } + + [Fact] + public void Binary_007_Declaration() + { + var src = """ +static class Extensions1 +{ + extension(S1) + { + public static bool operator !=(S1 x, S1 y) => default; + public static bool operator ==(S1 x, S1 y) => default; + public static bool operator >=(S1 x, S1 y) => default; + public static bool operator <=(S1 x, S1 y) => default; + public static bool operator >(S1 x, S1 y) => default; + public static bool operator <(S1 x, S1 y) => default; + } +} + +struct S1 +{} +"""; + var comp = CreateCompilation(src); + CompileAndVerify(comp, symbolValidator: verify, sourceSymbolValidator: verify).VerifyDiagnostics(); + + void verify(ModuleSymbol m) + { + var method = m.GlobalNamespace.GetMember("Extensions1." + WellKnownMemberNames.EqualityOperatorName); + AssertEx.Equal("Extensions1." + WellKnownMemberNames.EqualityOperatorName + "(S1, S1)", method.ToDisplayString()); + verifyMethod(method); + + method = m.GlobalNamespace.GetMember("Extensions1." + WellKnownMemberNames.InequalityOperatorName); + AssertEx.Equal("Extensions1." + WellKnownMemberNames.InequalityOperatorName + "(S1, S1)", method.ToDisplayString()); + verifyMethod(method); + + method = m.GlobalNamespace.GetMember("Extensions1." + WellKnownMemberNames.GreaterThanOrEqualOperatorName); + AssertEx.Equal("Extensions1." + WellKnownMemberNames.GreaterThanOrEqualOperatorName + "(S1, S1)", method.ToDisplayString()); + verifyMethod(method); + + method = m.GlobalNamespace.GetMember("Extensions1." + WellKnownMemberNames.LessThanOrEqualOperatorName); + AssertEx.Equal("Extensions1." + WellKnownMemberNames.LessThanOrEqualOperatorName + "(S1, S1)", method.ToDisplayString()); + verifyMethod(method); + + method = m.GlobalNamespace.GetMember("Extensions1." + WellKnownMemberNames.GreaterThanOperatorName); + AssertEx.Equal("Extensions1." + WellKnownMemberNames.GreaterThanOperatorName + "(S1, S1)", method.ToDisplayString()); + verifyMethod(method); + + method = m.GlobalNamespace.GetMember("Extensions1." + WellKnownMemberNames.LessThanOperatorName); + AssertEx.Equal("Extensions1." + WellKnownMemberNames.LessThanOperatorName + "(S1, S1)", method.ToDisplayString()); + verifyMethod(method); + } + + static void verifyMethod(MethodSymbol method) + { + Assert.Equal(MethodKind.Ordinary, method.MethodKind); + Assert.True(method.IsStatic); + Assert.False(method.IsExtensionMethod); + Assert.False(method.HasSpecialName); + Assert.False(method.HasRuntimeSpecialName); + Assert.False(method.HasUnsupportedMetadata); + } + } + + [Theory] + [CombinatorialData] + public void Binary_008_Declaration([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", ">>>")] string op, [CombinatorialValues("virtual", "abstract", "new", "override", "sealed", "readonly")] string modifier) + { + var src = $$$""" +static class Extensions1 +{ + extension(S1) + { + {{{modifier}}} + public static S1 operator {{{op}}}(S1 x, S1 y) => default; + } +} + +struct S1 +{} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (6,35): error CS0106: The modifier 'abstract' is not valid for this item + // public static S1 operator -(S1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments(modifier).WithLocation(6, 35) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_009_Declaration([CombinatorialValues("virtual", "abstract", "new", "override", "sealed", "readonly")] string modifier) + { + var src = $$$""" +static class Extensions1 +{ + extension(S1) + { + {{{modifier}}} + public static bool operator !=(S1 x, S1 y) => default; + + {{{modifier}}} + public static bool operator ==(S1 x, S1 y) => default; + + {{{modifier}}} + public static bool operator >=(S1 x, S1 y) => default; + + {{{modifier}}} + public static bool operator <=(S1 x, S1 y) => default; + + {{{modifier}}} + public static bool operator >(S1 x, S1 y) => default; + + {{{modifier}}} + public static bool operator <(S1 x, S1 y) => default; + } +} + +struct S1 +{} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (6,37): error CS0106: The modifier 'abstract' is not valid for this item + // public static bool operator !=(S1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments(modifier).WithLocation(6, 37), + // (9,37): error CS0106: The modifier 'abstract' is not valid for this item + // public static bool operator ==(S1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments(modifier).WithLocation(9, 37), + // (12,37): error CS0106: The modifier 'abstract' is not valid for this item + // public static bool operator >=(S1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_BadMemberFlag, ">=").WithArguments(modifier).WithLocation(12, 37), + // (15,37): error CS0106: The modifier 'abstract' is not valid for this item + // public static bool operator <=(S1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_BadMemberFlag, "<=").WithArguments(modifier).WithLocation(15, 37), + // (18,37): error CS0106: The modifier 'abstract' is not valid for this item + // public static bool operator >(S1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_BadMemberFlag, ">").WithArguments(modifier).WithLocation(18, 37), + // (21,37): error CS0106: The modifier 'abstract' is not valid for this item + // public static bool operator <(S1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_BadMemberFlag, "<").WithArguments(modifier).WithLocation(21, 37) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_010_Declaration([CombinatorialValues("+", "-", "*", "/")] string op) + { + var src = $$$""" +static class Extensions1 +{ + extension(S1) + { + public static S1 operator checked {{{op}}}(S1 x, S1 y) => default; + public static S1 operator {{{op}}}(S1 x, S1 y) => default; + } +} + +static class Extensions2 +{ + extension(S1) + { +#line 100 + public static S1 operator checked {{{op}}}(S1 x, S1 y) => default; + } + extension(S1) + { + public static S1 operator {{{op}}}(S1 x, S1 y) => default; + } +} + +static class Extensions3 +{ + extension(S1) + { + public static S1 operator checked {{{op}}}(S1 x, S1 y) => default; + } +} + +struct S1 +{} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (112,43): error CS9025: The operator 'Extensions3.extension(S1).operator checked +(S1, S1)' requires a matching non-checked version of the operator to also be defined + // public static S1 operator checked +(S1 x, S1 y) => default; + Diagnostic(ErrorCode.ERR_CheckedOperatorNeedsMatch, op).WithArguments("Extensions3.extension(S1).operator checked " + op + "(S1, S1)").WithLocation(112, 43) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_011_Consumption(bool fromMetadata, [CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", ">>>", ">", "<", ">=", "<=", "==", "!=")] string op, [CombinatorialValues("struct", "class")] string typeKind) + { + if (op is ("==" or "!=") && typeKind is "class") + { + return; + } + + string pairedOp = ""; + + if (op is ">" or "<" or ">=" or "<=" or "==" or "!=") + { + pairedOp = $$$""" + public static S1 operator {{{op switch { ">" => "<", ">=" => "<=", "==" => "!=", "<" => ">", "<=" => ">=", "!=" => "==", _ => throw ExceptionUtilities.UnexpectedValue(op) }}}}(S1 x, S1 y) => throw null; +"""; + } + + var src1 = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op}}}(S1 x, S1 y) + { + System.Console.Write("operator1:"); + System.Console.Write(x.F); + System.Console.Write(":"); + System.Console.Write(y.F); + return new S1 { F = x.F + y.F }; + } +{{{pairedOp}}} + } +} + +public {{{typeKind}}} S1 +{ + public int F; +} +"""; + + var src2 = $$$""" +class Program +{ + static void Main() + { + var s11 = new S1() { F = 101 }; + var s12 = new S1() { F = 202 }; + var s2 = s11 {{{op}}} s12; + System.Console.Write(":"); + System.Console.Write(s11.F); + System.Console.Write(":"); + System.Console.Write(s12.F); + System.Console.Write(":"); + System.Console.Write(s2.F); + } +} +"""; + + var comp1 = CreateCompilation(src1); + var comp1Ref = fromMetadata ? comp1.EmitToImageReference() : comp1.ToMetadataReference(); + + var comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp2, expectedOutput: "operator1:101:202:101:202:303").VerifyDiagnostics(); + + var tree = comp2.SyntaxTrees.First(); + var model = comp2.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("Extensions1.extension(S1).operator " + op + "(S1, S1)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S1", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: "operator1:101:202:101:202:303").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (7,18): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // var s2 = s11 + s12; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s11 " + op + " s12").WithArguments("extensions").WithLocation(7, 18) + ); + + var opName = BinaryOperatorName(op); + var src3 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1(); + Extensions1.{{{opName}}}(s1, s1); + } +} +"""; + var comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp3, expectedOutput: "operator1:0:0").VerifyDiagnostics(); + + comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp3, expectedOutput: "operator1:0:0").VerifyDiagnostics(); + + comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + CompileAndVerify(comp3, expectedOutput: "operator1:0:0").VerifyDiagnostics(); + + var src4 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1(); + s1.{{{opName}}}(s1); + S1.{{{opName}}}(s1, s1); + } +} +"""; + var comp4 = CreateCompilation(src4, references: [comp1Ref]); + comp4.VerifyEmitDiagnostics( + // (6,12): error CS1061: 'S1' does not contain a definition for 'op_Addition' and no accessible extension method 'op_Addition' accepting a first argument of type 'S1' could be found (are you missing a using directive or an assembly reference?) + // s1.op_Addition(s1); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, opName).WithArguments("S1", opName).WithLocation(6, 12), + // (7,12): error CS0117: 'S1' does not contain a definition for 'op_Addition' + // S1.op_Addition(s1, s1); + Diagnostic(ErrorCode.ERR_NoSuchMember, opName).WithArguments("S1", opName).WithLocation(7, 12) + ); + } + + [Fact] + public void Binary_012_Consumption_PredefinedComesFirst() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator +(S2 x, S2 y) => throw null; + } +} + +public struct S2 +{ + public static implicit operator int(S2 x) + { + System.Console.Write("operator2"); + return 0; + } +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + int x = s2 + s2; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2operator2").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("int.operator +(int, int)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("System.Int32", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Binary_013_Consumption_NonExtensionComesFirst() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator +(S2 x, S2 y) => throw null; + } +} + +public struct S2 +{ + public static S2 operator +(S2 x, S2 y) + { + System.Console.Write("operator2"); + return x; + } +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + _ = s2 + s2; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("S2.operator +(S2, S2)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S2", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Binary_014_Consumption_ScopeByScope() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator +(S1 x, S1 y) => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{} + +namespace NS1 +{ + public static class Extensions2 + { + extension(S1) + { + public static S1 operator +(S1 x, S1 y) + { + System.Console.Write("operator1"); + return x; + } + } + } + + namespace NS2 + { + public static class Extensions3 + { + extension(S2) + { + public static S2 operator +(S2 x, S2 y) => throw null; + } + } + + class Program + { + static void Main() + { + var s1 = new S1(); + _ = s1 + s1; + } + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("NS1.Extensions2.extension(S1).operator +(S1, S1)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S1", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Binary_015_Consumption_NonExtensionAmbiguity() + { + var src = $$$""" +public interface I1 +{ + public static I1 operator -(I1 x, I1 y) => x; +} + +public interface I3 +{ + public static I3 operator -(I3 x, I3 y) => x; +} + +public interface I4 : I1, I3 +{ +} + +public interface I2 : I4 +{ +} + +public static class Extensions1 +{ + extension(I2) + { + public static I2 operator -(I2 x, I2 y) => x; + } +} + +class Test2 : I2 +{ + static void Main() + { + I2 x = new Test2(); + var y = x - x; + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (32,17): error CS0034: Operator '-' is ambiguous on operands of type 'I2' and 'I2' + // var y = x - x; + Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "x - x").WithArguments("-", "I2", "I2").WithLocation(32, 17) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); + Assert.Equal(2, symbolInfo.CandidateSymbols.Length); + AssertEx.Equal("I1.operator -(I1, I1)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("I3.operator -(I3, I3)", symbolInfo.CandidateSymbols[1].ToDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + [WorkItem("https://github.com/dotnet/roslyn/issues/78830")] + public void Binary_016_Consumption_ExtensionAmbiguity() + { + var src = $$$""" +public interface I1; +public interface I3; +public interface I4 : I1, I3; +public interface I2 : I4; + +public static class Extensions1 +{ + extension(I2) + { + public static I2 operator -(I2 x, I2 y) => x; + } +} + +namespace NS1 +{ + public static class Extensions2 + { + extension(I1) + { + public static I1 operator -(I1 x, I1 y) => x; + } + + extension(I3) + { + public static I3 operator -(I3 x, I3 y) => x; + } + } + + class Test2 : I2 + { + static void Main() + { + I2 x = new Test2(); + var y = x - x; + } + } +} +"""; + + var comp = CreateCompilation(src); + + // https://github.com/dotnet/roslyn/issues/78830: We might want to include more information into the error. Like what methods conflict. + comp.VerifyEmitDiagnostics( + // (34,21): error CS0034: Operator '-' is ambiguous on operands of type 'I2' and 'I2' + // var y = x - x; + Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "x - x").WithArguments("-", "I2", "I2").WithLocation(34, 21) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); + Assert.Equal(2, symbolInfo.CandidateSymbols.Length); + AssertEx.Equal("NS1.Extensions2.extension(I1).operator -(I1, I1)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("NS1.Extensions2.extension(I3).operator -(I3, I3)", symbolInfo.CandidateSymbols[1].ToDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Theory] + [CombinatorialData] + public void Binary_017_Consumption_Lifted([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", ">>>")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op}}}(S1 x, S1 y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? s11 = new S1(); + S1? s12 = new S1(); + _ = s11 {{{op}}} s12; + System.Console.Write(":"); + s11 = null; + _ = s11 {{{op}}} s12; + _ = s12 {{{op}}} s11; + _ = s11 {{{op}}} s11; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1:").VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void Binary_018_Consumption_Lifted_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", ">>>")] string op) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op}}}(S1 x, S1 y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} +"""; + var src2 = $$$""" +class Program +{ + static void Main() + { + S1? s11 = new S1(); + S1 s12 = new S1(); + _ = s11 {{{op}}} s12; + _ = s12 {{{op}}} s11; + System.Console.Write(":"); + s11 = null; + _ = s11 {{{op}}} s12; + _ = s12 {{{op}}} s11; + } +} +"""; + + var comp1 = CreateCompilation([src1, src2], options: TestOptions.DebugExe); + CompileAndVerify(comp1, expectedOutput: "operator1operator1:").VerifyDiagnostics(); + + var comp2 = CreateCompilation([src1, src2], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: "operator1operator1:").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1.ToMetadataReference()], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (7,13): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = s11 + s12; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s11 " + op + " s12").WithArguments("extensions").WithLocation(7, 13), + // (8,13): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = s12 + s11; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s12 " + op + " s11").WithArguments("extensions").WithLocation(8, 13), + // (11,13): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = s11 + s12; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s11 " + op + " s12").WithArguments("extensions").WithLocation(11, 13), + // (12,13): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = s12 + s11; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s12 " + op + " s11").WithArguments("extensions").WithLocation(12, 13) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_018_Consumption_Lifted_02([CombinatorialValues(">", "<", ">=", "<=", "==", "!=")] string op) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static bool operator {{{op}}}(S1 x, S1 y) + { + System.Console.Write("operator1"); + return true; + } + + public static bool operator {{{op switch { ">" => "<", ">=" => "<=", "==" => "!=", "<" => ">", "<=" => ">=", "!=" => "==", _ => throw ExceptionUtilities.UnexpectedValue(op) }}}}(S1 x, S1 y) => throw null; + } +} + +public struct S1 +{} +"""; + var src2 = $$$""" +class Program +{ + static void Main() + { + S1? s11 = new S1(); + S1 s12 = new S1(); + _ = s11 {{{op}}} s12; + _ = s12 {{{op}}} s11; + System.Console.Write(":"); + s11 = null; + _ = s11 {{{op}}} s12; + _ = s12 {{{op}}} s11; + } +} +"""; + + var comp1 = CreateCompilation([src1, src2], options: TestOptions.DebugExe); + CompileAndVerify(comp1, expectedOutput: "operator1operator1:").VerifyDiagnostics(); + + var comp2 = CreateCompilation([src1, src2], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: "operator1operator1:").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1.ToMetadataReference()], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (7,13): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = s11 + s12; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s11 " + op + " s12").WithArguments("extensions").WithLocation(7, 13), + // (8,13): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = s12 + s11; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s12 " + op + " s11").WithArguments("extensions").WithLocation(8, 13), + // (11,13): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = s11 + s12; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s11 " + op + " s12").WithArguments("extensions").WithLocation(11, 13), + // (12,13): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = s12 + s11; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s12 " + op + " s11").WithArguments("extensions").WithLocation(12, 13) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_019_Consumption_Lifted([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op}}}(S1 x, S2 y) + { + System.Console.Write("operator1"); + return x; + } + public static S1 operator {{{op}}}(S2 x, S1 y) + { + System.Console.Write("operator2"); + return y; + } + } +} + +public struct S1 +{} + +public struct S2 +{} + +class Program +{ + static void Main() + { + S1? s1 = new S1(); + S2? s2 = new S2(); + _ = s1 {{{op}}} s2; + _ = s2 {{{op}}} s1; + System.Console.Write(":"); + s1 = null; + _ = s1 {{{op}}} s2; + _ = s2 {{{op}}} s1; + s1 = new S1(); + s2 = null; + _ = s1 {{{op}}} s2; + _ = s2 {{{op}}} s1; + s1 = null; + _ = s1 {{{op}}} s2; + _ = s2 {{{op}}} s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1operator2:").VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void Binary_020_Consumption_Lifted_Shift([CombinatorialValues("<<", ">>", ">>>")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op}}}(S1 x, S2 y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} + +public struct S2 +{} + +class Program +{ + static void Main() + { + S1? s1 = new S1(); + S2? s2 = new S2(); + _ = s1 {{{op}}} s2; + System.Console.Write(":"); + s1 = null; + _ = s1 {{{op}}} s2; + s1 = new S1(); + s2 = null; + _ = s1 {{{op}}} s2; + s1 = null; + _ = s1 {{{op}}} s2; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1:").VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void Binary_021_Consumption_Lifted([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op}}}(S1 x, S2 y) + { + System.Console.Write("operator1:"); + System.Console.Write(x.F); + System.Console.Write(":"); + System.Console.Write(y.F); + return new S1 { F = x.F * 1000 + y.F }; + } + public static S1 operator {{{op}}}(S2 x, S1 y) + { + System.Console.Write("operator2:"); + System.Console.Write(x.F); + System.Console.Write(":"); + System.Console.Write(y.F); + return new S1 { F = x.F * 1000 + y.F }; + } + } +} + +public struct S1 +{ + public int F; +} + +public struct S2 +{ + public int F; +} + +class Program +{ + static void Main() + { + S1? s11 = new S1() { F = 101 }; + S2 s12 = new S2() { F = 202 }; + S1 s21 = new S1() { F = 303 }; + S2? s22 = new S2() { F = 404 }; + Print(s11 {{{op}}} s12); + System.Console.WriteLine(); + Print(s12 {{{op}}} s11); + System.Console.WriteLine(); + Print(s21 {{{op}}} s22); + System.Console.WriteLine(); + Print(s22 {{{op}}} s21); + System.Console.WriteLine(); + s11 = null; + s22 = null; + Print(s11 {{{op}}} s12); + System.Console.WriteLine(); + Print(s12 {{{op}}} s11); + System.Console.WriteLine(); + Print(s21 {{{op}}} s22); + System.Console.WriteLine(); + Print(s22 {{{op}}} s21); + System.Console.WriteLine(); + Print(s11 {{{op}}} s22); + System.Console.WriteLine(); + Print(s22 {{{op}}} s11); + } + + static void Print(S1? x) + { + System.Console.Write(":"); + System.Console.Write(x?.F ?? -1); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: +@" +operator1:101:202:101202 +operator2:202:101:202101 +operator1:303:404:303404 +operator2:404:303:404303 +:-1 +:-1 +:-1 +:-1 +:-1 +:-1 +").VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void Binary_022_Consumption_Lifted_Shift([CombinatorialValues("<<", ">>", ">>>")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op}}}(S1 x, S2 y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} + +public struct S2 +{} + +class Program +{ + static void Main() + { + S1? s11 = new S1(); + S2 s12 = new S2(); + S1 s21 = new S1(); + S2? s22 = new S2(); + _ = s11 {{{op}}} s12; + _ = s21 {{{op}}} s22; + System.Console.Write(":"); + s11 = null; + s22 = null; + _ = s11 {{{op}}} s12; + _ = s21 {{{op}}} s22; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1operator1:").VerifyDiagnostics(); + } + + [Fact] + public void Binary_023_Consumption_LiftedIsWorse() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator +(S1 x, S1 y) => throw null; + } + extension(S1?) + { + public static S1? operator +(S1? x, S1? y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? s1 = new S1(); + _ = s1 + s1; + System.Console.Write(":"); + s1 = null; + _ = s1 + s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1:operator1").VerifyDiagnostics(); + } + + [Fact] + public void Binary_024_Consumption_ExtendedTypeIsNullable() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1?) + { + public static S1? operator +(S1? x, S1? y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1 s1 = new S1(); + _ = s1 + s1; + Extensions1.op_Addition(s1, s1); + + S1? s2 = new S1(); + _ = s2 + s2; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (21,13): error CS0019: Operator '+' cannot be applied to operands of type 'S1' and 'S1' + // _ = s1 + s1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 + s1").WithArguments("+", "S1", "S1").WithLocation(21, 13) + ); + } + + [Fact] + public void Binary_025_Consumption_ReceiverTypeMismatch() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator +(S2 x, S2 y) => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{ + public static implicit operator S2(S1 x) => default; +} + +class Program +{ + static void Main() + { + S1 s1 = new S1(); + S2 s2 = new S2(); + _ = s1 + s2; + _ = s2 + s1; + _ = s1 + s1; + Extensions1.op_Addition(s1, s1); + + S1? s3 = new S1(); + _ = s3 + s3; + Extensions1.op_Addition(s3, s3); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (25,13): error CS0019: Operator '+' cannot be applied to operands of type 'S1' and 'S1' + // _ = s1 + s1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 + s1").WithArguments("+", "S1", "S1").WithLocation(25, 13), + // (29,13): error CS0019: Operator '+' cannot be applied to operands of type 'S1?' and 'S1?' + // _ = s3 + s3; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s3 + s3").WithArguments("+", "S1?", "S1?").WithLocation(29, 13), + // (30,33): error CS1503: Argument 1: cannot convert from 'S1?' to 'S2' + // Extensions1.op_Addition(s3, s3); + Diagnostic(ErrorCode.ERR_BadArgType, "s3").WithArguments("1", "S1?", "S2").WithLocation(30, 33), + // (30,37): error CS1503: Argument 2: cannot convert from 'S1?' to 'S2' + // Extensions1.op_Addition(s3, s3); + Diagnostic(ErrorCode.ERR_BadArgType, "s3").WithArguments("2", "S1?", "S2").WithLocation(30, 37) + ); + + var src1 = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator +(S2 x, S1 y) => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{ + public static implicit operator S2(S1 x) => default; + public static implicit operator S1(S2 x) => default; +} + +class Program +{ + static void Main() + { + S1 s1 = new S1(); + S2 s2 = new S2(); + _ = s1 + s1; + _ = s1 + s2; + _ = s2 + s1; + _ = s2 + s2; + Extensions1.op_Addition(s1, s1); + Extensions1.op_Addition(s1, s2); + } +} +"""; + + var comp1 = CreateCompilation(src1, options: TestOptions.DebugExe); + comp1.VerifyEmitDiagnostics( + // (24,13): error CS0019: Operator '+' cannot be applied to operands of type 'S1' and 'S1' + // _ = s1 + s1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 + s1").WithArguments("+", "S1", "S1").WithLocation(24, 13), + // (25,13): error CS0019: Operator '+' cannot be applied to operands of type 'S1' and 'S2' + // _ = s1 + s2; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 + s2").WithArguments("+", "S1", "S2").WithLocation(25, 13) + ); + + var src2 = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator +(S1 x, S2 y) => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{ + public static implicit operator S2(S1 x) => default; + public static implicit operator S1(S2 x) => default; +} + +class Program +{ + static void Main() + { + S1 s1 = new S1(); + S2 s2 = new S2(); + _ = s1 + s1; + _ = s1 + s2; + _ = s2 + s1; + _ = s2 + s2; + Extensions1.op_Addition(s1, s1); + Extensions1.op_Addition(s2, s1); + } +} +"""; + + var comp2 = CreateCompilation(src2, options: TestOptions.DebugExe); + comp2.VerifyEmitDiagnostics( + // (24,13): error CS0019: Operator '+' cannot be applied to operands of type 'S1' and 'S1' + // _ = s1 + s1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 + s1").WithArguments("+", "S1", "S1").WithLocation(24, 13), + // (26,13): error CS0019: Operator '+' cannot be applied to operands of type 'S2' and 'S1' + // _ = s2 + s1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s2 + s1").WithArguments("+", "S2", "S1").WithLocation(26, 13) + ); + + var src3 = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2? operator +(S2? x, S1? y) => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{ + public static implicit operator S2(S1 x) => default; + public static implicit operator S1(S2 x) => default; +} + +class Program +{ + static void Main() + { + S1 s1 = new S1(); + S2 s2 = new S2(); + _ = s1 + s1; + _ = s1 + s2; + _ = s2 + s1; + _ = s2 + s2; + Extensions1.op_Addition(s1, s1); + Extensions1.op_Addition(s1, s2); + } +} +"""; + + var comp3 = CreateCompilation(src3, options: TestOptions.DebugExe); + comp3.VerifyEmitDiagnostics( + // (5,36): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S2? operator +(S2? x, S1? y) => throw null; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, "+").WithLocation(5, 36), + // (24,13): error CS0019: Operator '+' cannot be applied to operands of type 'S1' and 'S1' + // _ = s1 + s1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 + s1").WithArguments("+", "S1", "S1").WithLocation(24, 13), + // (25,13): error CS0019: Operator '+' cannot be applied to operands of type 'S1' and 'S2' + // _ = s1 + s2; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 + s2").WithArguments("+", "S1", "S2").WithLocation(25, 13), + // (26,13): error CS0019: Operator '+' cannot be applied to operands of type 'S2' and 'S1' + // _ = s2 + s1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s2 + s1").WithArguments("+", "S2", "S1").WithLocation(26, 13), + // (27,13): error CS0019: Operator '+' cannot be applied to operands of type 'S2' and 'S2' + // _ = s2 + s2; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s2 + s2").WithArguments("+", "S2", "S2").WithLocation(27, 13) + ); + + var src4 = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2? operator +(S1? x, S2? y) => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{ + public static implicit operator S2(S1 x) => default; + public static implicit operator S1(S2 x) => default; +} + +class Program +{ + static void Main() + { + S1 s1 = new S1(); + S2 s2 = new S2(); + _ = s1 + s1; + _ = s1 + s2; + _ = s2 + s1; + _ = s2 + s2; + Extensions1.op_Addition(s1, s1); + Extensions1.op_Addition(s2, s1); + } +} +"""; + + var comp4 = CreateCompilation(src4, options: TestOptions.DebugExe); + comp4.VerifyEmitDiagnostics( + // (5,36): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S2? operator +(S1? x, S2? y) => throw null; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, "+").WithLocation(5, 36), + // (24,13): error CS0019: Operator '+' cannot be applied to operands of type 'S1' and 'S1' + // _ = s1 + s1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 + s1").WithArguments("+", "S1", "S1").WithLocation(24, 13), + // (25,13): error CS0019: Operator '+' cannot be applied to operands of type 'S1' and 'S2' + // _ = s1 + s2; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 + s2").WithArguments("+", "S1", "S2").WithLocation(25, 13), + // (26,13): error CS0019: Operator '+' cannot be applied to operands of type 'S2' and 'S1' + // _ = s2 + s1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s2 + s1").WithArguments("+", "S2", "S1").WithLocation(26, 13), + // (27,13): error CS0019: Operator '+' cannot be applied to operands of type 'S2' and 'S2' + // _ = s2 + s2; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s2 + s2").WithArguments("+", "S2", "S2").WithLocation(27, 13) + ); + } + + [Fact] + public void Binary_026_Consumption_ReceiverTypeMismatch_Shift() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator <<(S2 x, S2 y) => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{ + public static implicit operator S2(S1 x) => default; +} + +class Program +{ + static void Main() + { + S1 s1 = new S1(); + S2 s2 = new S2(); + _ = s1 << s2; + _ = s2 << s1; + _ = s1 << s1; + Extensions1.op_LeftShift(s1, s1); + + S1? s3 = new S1(); + _ = s3 << s3; + Extensions1.op_LeftShift(s3, s3); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (23,13): error CS0019: Operator '<<' cannot be applied to operands of type 'S1' and 'S2' + // _ = s1 << s2; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 << s2").WithArguments("<<", "S1", "S2").WithLocation(23, 13), + // (25,13): error CS0019: Operator '<<' cannot be applied to operands of type 'S1' and 'S1' + // _ = s1 << s1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 << s1").WithArguments("<<", "S1", "S1").WithLocation(25, 13), + // (29,13): error CS0019: Operator '<<' cannot be applied to operands of type 'S1?' and 'S1?' + // _ = s3 << s3; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s3 << s3").WithArguments("<<", "S1?", "S1?").WithLocation(29, 13), + // (30,34): error CS1503: Argument 1: cannot convert from 'S1?' to 'S2' + // Extensions1.op_LeftShift(s3, s3); + Diagnostic(ErrorCode.ERR_BadArgType, "s3").WithArguments("1", "S1?", "S2").WithLocation(30, 34), + // (30,38): error CS1503: Argument 2: cannot convert from 'S1?' to 'S2' + // Extensions1.op_LeftShift(s3, s3); + Diagnostic(ErrorCode.ERR_BadArgType, "s3").WithArguments("2", "S1?", "S2").WithLocation(30, 38) + ); + } + + [Fact] + public void Binary_027_Consumption_Generic() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) where T : struct + { + public static S1 operator +(S1 x, S1 y) + { + System.Console.Write(typeof(T).ToString()); + return x; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + var s1 = new S1(); + s1 = s1 + s1; + Extensions1.op_Addition(s1, s1); + + S1? s2 = new S1(); + _ = (s2 + s2).GetValueOrDefault(); + s2 = null; + System.Console.Write(":"); + _ = (s2 + s2).GetValueOrDefault(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "System.Int32System.Int32System.Int32:").VerifyDiagnostics(); + } + + [Fact] + public void Binary_027_Consumption_Generic_Worse() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator +(S1 x, S1 y) + { + System.Console.Write("[S1]"); + return x; + } + } + + extension(S1?) + { + public static S1? operator +(S1? x, S1? y) + { + System.Console.Write("[S1?]"); + return x; + } + } + + extension(S1) + { + public static S1 operator +(S1 x, S1 y) + { + System.Console.Write("[S1]"); + return x; + } + } + + extension(S2) + { + public static S2 operator +(in S2 x, S2 y) => throw null; + + public static S2 operator +(S2 x, S2 y) + { + System.Console.Write("[S2]"); + return x; + } + } + + extension(S2) + { + public static S2 operator +(in S2 x, S2 y) + { + System.Console.Write("[in S2]"); + return x; + } + } +} + +public struct S1 +{} + +public struct S2 +{} + +class Program +{ + static void Main() + { + var s11 = new S1(); + s11 = s11 + s11; + Extensions1.op_Addition(s11, s11); + + System.Console.WriteLine(); + + var s12 = new S1(); + s12 = s12 + s12; + Extensions1.op_Addition(s12, s12); + + System.Console.WriteLine(); + + var s21 = new S2(); + s21 = s21 + s21; + Extensions1.op_Addition(s21, s21); + + System.Console.WriteLine(); + + var s22 = new S2(); + s22 = s22 + s22; + Extensions1.op_Addition(s22, s22); + + System.Console.WriteLine(); + + S1? s13 = new S1(); + s13 = s13 + s13; + s13 = null; + s13 = s13 + s13; + + System.Console.WriteLine(); + + S1? s14 = new S1(); + s14 = s14 + s14; + s14 = null; + s14 = s14 + s14; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: @" +[S1][S1] +[S1][S1] +[in S2][in S2] +[S2][S2] +[S1] +[S1?][S1?] +").VerifyDiagnostics(); + } + + [Fact] + public void Binary_028_Consumption_Generic() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) where T : struct + { + public static bool operator >(S1 x, S1 y) + { + System.Console.Write(typeof(T).ToString()); + return true; + } + public static bool operator <(S1 x, S1 y) => throw null; + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + var s11 = new S1(); + var s12 = new S1(); + bool b = s11 > s12; + Extensions1.op_GreaterThan(s11, s12); + + S1? s21 = new S1(); + S1? s22 = new S1(); + b = s21 > s22; + s22 = null; + System.Console.Write(":"); + b = s21 > s22; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "System.Int32System.Int32System.Int32:").VerifyDiagnostics(); + } + + [Fact] + public void Binary_029_Consumption_Generic_ConstraintsViolation() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) where T : class + { + public static S1 operator +(S1 x, S1 y) => throw null; + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + var s1 = new S1(); + _ = s1 + s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (17,13): error CS0019: Operator '+' cannot be applied to operands of type 'S1' and 'S1' + // _ = s1 + s1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 + s1").WithArguments("+", "S1", "S1").WithLocation(17, 13) + ); + } + + [Fact] + public void Binary_030_Consumption_OverloadResolutionPriority() + { + var src = $$$""" +using System.Runtime.CompilerServices; + +public static class Extensions1 +{ + extension(C1) + { + [OverloadResolutionPriority(1)] + public static C1 operator +(C1 x, C1 y) + { + System.Console.Write("C1"); + return x; + } + } + extension(C2) + { + public static C2 operator +(C2 x, C2 y) + { + System.Console.Write("C2"); + return x; + } + } + extension(C3) + { + public static C3 operator +(C3 x, C3 y) + { + System.Console.Write("C3"); + return x; + } + } + extension(C4) + { + public static C4 operator +(C4 x, C4 y) + { + System.Console.Write("C4"); + return x; + } + } +} + +public class C1; +public class C2 : C1; + +public class C3; +public class C4 : C3; + +class Program +{ + static void Main() + { + var c2 = new C2(); + _ = c2 + c2; + var c4 = new C4(); + _ = c4 + c4; + } +} +"""; + + var comp = CreateCompilation([src, OverloadResolutionPriorityAttributeDefinition], options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "C1C4").VerifyDiagnostics(); + } + + [Fact] + public void Binary_031_Consumption_Checked() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator -(C1 x, C1 y) + { + System.Console.Write("regular"); + return x; + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = c1 - c1; + + checked + { + _ = c1 - c1; + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "regularregular").VerifyDiagnostics(); + } + + [Fact] + public void Binary_031_Consumption_Checked_CheckedFormNotSupported() + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator |(C1 x, C1 y) => throw null; + public static C1 operator checked |(C1 x, C1 y) => throw null; + } +} + +public class C1; +"""; + + var comp1 = CreateCompilation(src1); + comp1.VerifyEmitDiagnostics( + // (6,35): error CS9023: User-defined operator '|' cannot be declared checked + // public static C1 operator checked |(C1 x, C1 y) => throw null; + Diagnostic(ErrorCode.ERR_OperatorCantBeChecked, "checked").WithArguments("|").WithLocation(6, 35), + // (6,43): error CS0111: Type 'Extensions1' already defines a member called 'op_BitwiseOr' with the same parameter types + // public static C1 operator checked |(C1 x, C1 y) => throw null; + Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "|").WithArguments("op_BitwiseOr", "Extensions1").WithLocation(6, 43) + ); + + var src2 = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator |(C1 x, C1 y) + { + System.Console.Write("regular"); + return x; + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = c1 | c1; + + checked + { + _ = c1 | c1; + } + } +} +"""; + + var comp2 = CreateCompilation(src2, options: TestOptions.DebugExe); + CompileAndVerify(comp2, expectedOutput: "regularregular").VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void Binary_032_Consumption_Checked([CombinatorialValues("+", "-", "*", "/")] string op, [CombinatorialValues("struct", "class")] string typeKind) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator {{{op}}}(C1 x, C1 y) + { + System.Console.Write("regular"); + return x; + } + public static C1 operator checked {{{op}}}(C1 x, C1 y) + { + System.Console.Write("checked"); + return x; + } + } +} + +public {{{typeKind}}} C1; +"""; + var src2 = $$$""" +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = c1 {{{op}}} c1; + + checked + { + _ = c1 {{{op}}} c1; + } + } +} +"""; + + var comp1 = CreateCompilation([src1, src2], options: TestOptions.DebugExe); + CompileAndVerify(comp1, expectedOutput: "regularchecked").VerifyDiagnostics(); + + var comp2 = CreateCompilation([src1, src2], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: "regularchecked").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1.ToMetadataReference()], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (6,13): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = c1 - c1; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "c1 " + op + " c1").WithArguments("extensions").WithLocation(6, 13), + // (10,17): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = c1 - c1; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "c1 " + op + " c1").WithArguments("extensions").WithLocation(10, 17) + ); + } + + [Fact] + public void Binary_033_Consumption_Checked() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator -(C1 x, C1 y) + { + System.Console.Write("regular"); + return x; + } + } + extension(C1) + { + public static C1 operator checked -(C1 x, C1 y) + { + System.Console.Write("checked"); + return x; + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = c1 - c1; + + checked + { + _ = c1 - c1; + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "regularchecked").VerifyDiagnostics(); + } + + [Fact] + public void Binary_034_Consumption_Checked() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator -(C1 x, C1 y) + { + return x; + } + + public static C1 operator checked -(C1 x, C1 y) + { + return x; + } + } +} + +public static class Extensions2 +{ + extension(C1) + { + public static C1 operator -(C1 x, C1 y) + { + return x; + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = c1 - c1; + + checked + { + _ = c1 - c1; + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (35,13): error CS0034: Operator '-' is ambiguous on operands of type 'C1' and 'C1' + // _ = c1 - c1; + Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "c1 - c1").WithArguments("-", "C1", "C1").WithLocation(35, 13), + // (39,17): error CS0034: Operator '-' is ambiguous on operands of type 'C1' and 'C1' + // _ = c1 - c1; + Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "c1 - c1").WithArguments("-", "C1", "C1").WithLocation(39, 17) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().Last(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); + Assert.Equal(2, symbolInfo.CandidateSymbols.Length); + AssertEx.Equal("Extensions1.extension(C1).operator checked -(C1, C1)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("Extensions2.extension(C1).operator -(C1, C1)", symbolInfo.CandidateSymbols[1].ToDisplayString()); + } + + [Fact] + public void Binary_035_Consumption_CheckedLiftedIsWorse() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator -(S1 x, S1 y) => throw null; + public static S1 operator checked -(S1 x, S1 y) => throw null; + } + extension(S1?) + { + public static S1? operator -(S1? x, S1? y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? s1 = new S1(); + _ = s1 - s1; + System.Console.Write(":"); + + checked + { + _ = s1 - s1; + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1:operator1").VerifyDiagnostics(); + } + + [Fact] + public void Binary_036_Consumption_OverloadResolutionPlusRegularVsChecked() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator -(C1 x, C1 y) + { + System.Console.Write("C1"); + return x; + } + public static C1 operator checked -(C1 x, C1 y) + { + System.Console.Write("checkedC1"); + return x; + } + } + extension(C2) + { + public static C2 operator -(C2 x, C2 y) + { + System.Console.Write("C2"); + return x; + } + } +} + +public class C1; +public class C2 : C1; +public class C3 : C1; + +class Program +{ + static void Main() + { + var c3 = new C3(); + _ = c3 - c3; + + checked + { + _ = c3 - c3; + } + + var c2 = new C2(); + _ = c2 - c2; + + checked + { + _ = c2 - c2; + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "C1checkedC1C2C2").VerifyDiagnostics(); + } + + [Fact] + public void Binary_037_Consumption() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1? operator +(S1? x, S1? y) + { + System.Console.Write("operator1"); + return x; + } + + public static void M1(S1? x) {} + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? s1 = new S1(); +#line 21 + _ = s1 + s1; + S1 s2 = new S1(); + _ = s2 + s2; + + System.Nullable.M1(s1); + S1.M1(s1); + S1.M1(s2); + } +} + +public static class Extensions2 +{ + extension(S2) + { + public static S2? operator +(S2 x, S2 y) + { + return x; + } + } +} + +public struct S2 +{} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + + comp.VerifyEmitDiagnostics( + // (5,36): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S1? operator +(S1? x, S1? y) + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, "+").WithLocation(5, 36), + // (21,13): error CS0019: Operator '+' cannot be applied to operands of type 'S1?' and 'S1?' + // _ = s1 + s1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 + s1").WithArguments("+", "S1?", "S1?").WithLocation(21, 13), + // (23,13): error CS0019: Operator '+' cannot be applied to operands of type 'S1' and 'S1' + // _ = s2 + s2; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s2 + s2").WithArguments("+", "S1", "S1").WithLocation(23, 13), + // (25,9): error CS1929: 'S1?' does not contain a definition for 'M1' and the best extension method overload 'Extensions1.extension(S1).M1(S1?)' requires a receiver of type 'S1' + // System.Nullable.M1(s1); + Diagnostic(ErrorCode.ERR_BadInstanceArgType, "System.Nullable").WithArguments("S1?", "M1", "Extensions1.extension(S1).M1(S1?)", "S1").WithLocation(25, 9) + ); + } + + [Fact] + public void Binary_038_Consumption_OnObject() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object) + { + public static object operator +(object x, object y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +class Program +{ + static void Main() + { + var s1 = new object(); + _ = s1 + s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1").VerifyDiagnostics(); + } + + [Fact] + public void Binary_039_Consumption_NotOnDynamic() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object) + { + public static object operator +(object x, object y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +class Program +{ + static void Main() + { + dynamic s1 = new object(); + var s2 = new object(); + try + { + _ = s1 + s2; + } + catch + { + System.Console.Write("exception1"); + } + + try + { + _ = s2 + s1; + } + catch + { + System.Console.Write("exception2"); + } + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "exception1exception2").VerifyDiagnostics(); + } + + [Fact] + public void Binary_040_Consumption_WithLambda() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator +(S1 x, System.Func y) + { + System.Console.Write("operator1"); + return x; + } + public static S1 operator +(System.Func y, S1 x) + { + System.Console.Write("operator2"); + return x; + } + } +} + +public struct S1 +{} + +public class Program +{ + static void Main() + { + S1 s1 = new S1(); + _ = s1 + (() => 1); + _ = (() => 1) + s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1operator2").VerifyDiagnostics(); + } + + [Fact] + public void Binary_041_Consumption_BadOperand() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator +(S1 x, S2 y) + { + System.Console.Write("operator1"); + return x; + } + public static S1 operator +(S2 y, S1 x) + { + System.Console.Write("operator2"); + return x; + } + } +} + +public struct S1 +{} +public struct S2 +{} + +public class Program +{ + static void Main() + { + S1 s1 = new S1(); + _ = s1 + new(); + _ = new() + s1; + _ = new() + new(); + _ = s1 + default; + _ = default + s1; + _ = default + default; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (28,13): error CS8310: Operator '+' cannot be applied to operand 'new()' + // _ = s1 + new(); + Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "s1 + new()").WithArguments("+", "new()").WithLocation(28, 13), + // (29,13): error CS8310: Operator '+' cannot be applied to operand 'new()' + // _ = new() + s1; + Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() + s1").WithArguments("+", "new()").WithLocation(29, 13), + // (30,13): error CS8310: Operator '+' cannot be applied to operand 'new()' + // _ = new() + new(); + Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "new() + new()").WithArguments("+", "new()").WithLocation(30, 13), + // (31,13): error CS8310: Operator '+' cannot be applied to operand 'default' + // _ = s1 + default; + Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "s1 + default").WithArguments("+", "default").WithLocation(31, 13), + // (32,13): error CS8310: Operator '+' cannot be applied to operand 'default' + // _ = default + s1; + Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "default + s1").WithArguments("+", "default").WithLocation(32, 13), + // (33,13): error CS8310: Operator '+' cannot be applied to operand 'default' + // _ = default + default; + Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "default + default").WithArguments("+", "default").WithLocation(33, 13) + ); + } + + [Fact] + public void Binary_042_Consumption_BadReceiver() + { + var src = $$$""" +public static class Extensions1 +{ + extension(__arglist) + { + public static object operator +(object x, object y) + { + return x; + } + } +} + +class Program +{ + static void Main() + { + var s1 = new object(); + _ = s1 + s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (3,15): error CS1669: __arglist is not valid in this context + // extension(__arglist) + Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(3, 15), + // (5,39): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static object operator +(object x, object y) + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, "+").WithLocation(5, 39), + // (17,13): error CS0019: Operator '+' cannot be applied to operands of type 'object' and 'object' + // _ = s1 + s1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 + s1").WithArguments("+", "object", "object").WithLocation(17, 13) + ); + } + + [Fact] + public void Binary_043_Consumption_Checked_Generic() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator -(C1 x, C1 y) + { + System.Console.Write("regular"); + return x; + } + } + extension(C1) + { + public static C1 operator checked -(C1 x, C1 y) + { + System.Console.Write("checked"); + return x; + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = c1 - c1; + + checked + { + _ = c1 - c1; + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "regularchecked").VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void Binary_044_Consumption_Logical(bool fromMetadata, [CombinatorialValues("&&", "||")] string op, [CombinatorialValues("struct", "class")] string typeKind) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op[0]}}}(S1 x, S1 y) + { + System.Console.Write("operator1:"); + System.Console.Write(x.F); + System.Console.Write(":"); + System.Console.Write(y.F); + return new S1 { F = x.F {{{op[0]}}} y.F }; + } + + public static bool operator true(S1 x) + { + System.Console.Write("operator2:"); + System.Console.Write(x.F); + System.Console.Write(":"); + return x.F; + } + + public static bool operator false(S1 x) + { + System.Console.Write("operator3:"); + System.Console.Write(x.F); + System.Console.Write(":"); + return !x.F; + } + } +} + +public {{{typeKind}}} S1 +{ + public bool F; +} +"""; + + var src2 = $$$""" +class Program +{ + static void Main() + { + S1[] s = [new S1() { F = false }, new S1() { F = true }]; + + foreach (var s1 in s) + { + foreach (var s2 in s) + { + Print(s1 {{{op}}} s2); + System.Console.WriteLine(); + } + } + } + + static void Print(S1 x) + { + System.Console.Write(":"); + System.Console.Write(x.F); + } +} +"""; + + string expected = op == "&&" ? +@" +operator3:False::False +operator3:False::False +operator3:True:operator1:True:False:False +operator3:True:operator1:True:True:True +" +: +@" +operator2:False:operator1:False:False:False +operator2:False:operator1:False:True:True +operator2:True::True +operator2:True::True +"; + + var comp1 = CreateCompilation(src1); + var comp1Ref = fromMetadata ? comp1.EmitToImageReference() : comp1.ToMetadataReference(); + + var comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp2, expectedOutput: expected).VerifyDiagnostics(); + + var tree = comp2.SyntaxTrees.First(); + var model = comp2.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("Extensions1.extension(S1).operator " + op[0] + "(S1, S1)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S1", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: expected).VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (11,23): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // Print(s1 && s2); + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s1 " + op + " s2").WithArguments("extensions").WithLocation(11, 23) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_045_Consumption_Logical_InDifferentBlocks([CombinatorialValues("&&", "||")] string op) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op[0]}}}(S1 x, S1 y) + { + System.Console.Write("operator1"); + return x; + } + } + extension(S1) + { + public static bool operator {{{(op == "&&" ? "false" : "true")}}}(S1 x) + { + System.Console.Write("operator2"); + return false; + } + } + extension(S1) + { + public static bool operator {{{(op == "&&" ? "true" : "false")}}}(S1 x) => throw null; + } +} + +public struct S1 +{} +"""; + var src2 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1(); + s1 = s1 {{{op}}} s1; + } +} +"""; + + var comp = CreateCompilation([src1, src2], options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2operator1").VerifyDiagnostics(); + + var comp1 = CreateCompilation(src1, options: TestOptions.DebugDll); + + comp = CreateCompilation(src2, references: [comp1.ToMetadataReference()], options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2operator1").VerifyDiagnostics(); + + comp = CreateCompilation(src2, references: [comp1.EmitToImageReference()], options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2operator1").VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void Binary_046_Consumption_Logical_DifferentTupleNames([CombinatorialValues("&&", "||")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension((int a, int b)) + { + public static (int c, int d) operator {{{op[0]}}}((int e, int f) x, (int g, int h) y) + { + System.Console.Write("operator1"); + return x; + } + + public static bool operator {{{(op == "&&" ? "false" : "true")}}}((int i, int j) x) + { + System.Console.Write("operator2"); + return false; + } + + public static bool operator {{{(op == "&&" ? "true" : "false")}}}((int k, int l) x) => throw null; + } +} + +class Program +{ + static void Main() + { + var s1 = (1, 2); + s1 = s1 {{{op}}} s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2operator1").VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void Binary_047_Consumption_Logical_DifferentParameterTypes([CombinatorialValues("&&", "||")] string op) + { + var src1 = $$$""" +namespace NS +{ + public static class Extensions1 + { + extension(S1) + { + public static S1 operator {{{op[0]}}}(S1 x, S2 y) + { + System.Console.Write("operator1"); + return x; + } + public static bool operator {{{(op == "&&" ? "false" : "true")}}}(S1 x) + { + System.Console.Write("operator2"); + return false; + } + + public static bool operator {{{(op == "&&" ? "true" : "false")}}}(S1 x) => throw null; + } + } + + class Program + { + static void Main() + { + S1 s1 = new S1(); + S2 s2 = new S2(); + _ = s1 {{{op}}} s2; + } + } +} + +public struct S1 +{} + +public struct S2 +{ + public static implicit operator S1(S2 x) => default; +} +"""; + var src2 = $$$""" +public static class Extensions2 +{ + extension(S1) + { + public static S1 operator {{{op[0]}}}(S1 x, S1 y) + { + System.Console.Write("operator3"); + return x; + } + public static bool operator {{{(op == "&&" ? "false" : "true")}}}(S1 x) + { + System.Console.Write("operator4"); + return false; + } + + public static bool operator {{{(op == "&&" ? "true" : "false")}}}(S1 x) => throw null; + } +} +"""; + + var comp = CreateCompilation(src1, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (28,17): error CS0217: In order to be applicable as a short circuit operator a user-defined logical operator ('Extensions1.extension(S1).operator &(S1, S2)') must have the same return type and parameter types + // _ = s1 && s2; + Diagnostic(ErrorCode.ERR_BadBoolOp, "s1 " + op + " s2").WithArguments("NS.Extensions1.extension(S1).operator " + op[0] + "(S1, S2)").WithLocation(28, 17) + ); + + comp = CreateCompilation([src1, src2], options: TestOptions.DebugExe); + + comp.VerifyEmitDiagnostics( + // (28,17): error CS0217: In order to be applicable as a short circuit operator a user-defined logical operator ('Extensions1.extension(S1).operator &(S1, S2)') must have the same return type and parameter types + // _ = s1 && s2; + Diagnostic(ErrorCode.ERR_BadBoolOp, "s1 " + op + " s2").WithArguments("NS.Extensions1.extension(S1).operator " + op[0] + "(S1, S2)").WithLocation(28, 17) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_048_Consumption_Logical_DifferentReturnType([CombinatorialValues("&&", "||")] string op) + { + var src1 = $$$""" +namespace NS +{ + public static class Extensions1 + { + extension(S1) + { + public static S2 operator {{{op[0]}}}(S1 x, S1 y) + { + System.Console.Write("operator1"); + return default; + } + public static bool operator {{{(op == "&&" ? "false" : "true")}}}(S1 x) + { + System.Console.Write("operator2"); + return false; + } + + public static bool operator {{{(op == "&&" ? "true" : "false")}}}(S1 x) => throw null; + } + } + + class Program + { + static void Main() + { + S1 s1 = new S1(); + S2 s2 = new S2(); + _ = s1 {{{op}}} s2; + } + } +} + +public struct S1 +{} + +public struct S2 +{ + public static implicit operator S1(S2 x) => default; +} +"""; + var src2 = $$$""" +public static class Extensions2 +{ + extension(S1) + { + public static S1 operator {{{op[0]}}}(S1 x, S1 y) + { + System.Console.Write("operator3"); + return x; + } + public static bool operator {{{(op == "&&" ? "false" : "true")}}}(S1 x) + { + System.Console.Write("operator4"); + return false; + } + + public static bool operator {{{(op == "&&" ? "true" : "false")}}}(S1 x) => throw null; + } +} +"""; + + var comp = CreateCompilation(src1, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (28,17): error CS0217: In order to be applicable as a short circuit operator a user-defined logical operator ('Extensions1.extension(S1).operator &(S1, S1)') must have the same return type and parameter types + // _ = s1 && s2; + Diagnostic(ErrorCode.ERR_BadBoolOp, "s1 " + op + " s2").WithArguments("NS.Extensions1.extension(S1).operator " + op[0] + "(S1, S1)").WithLocation(28, 17) + ); + + comp = CreateCompilation([src1, src2], options: TestOptions.DebugExe); + + comp.VerifyEmitDiagnostics( + // (28,17): error CS0217: In order to be applicable as a short circuit operator a user-defined logical operator ('Extensions1.extension(S1).operator &(S1, S1)') must have the same return type and parameter types + // _ = s1 && s2; + Diagnostic(ErrorCode.ERR_BadBoolOp, "s1 " + op + " s2").WithArguments("NS.Extensions1.extension(S1).operator " + op[0] + "(S1, S1)").WithLocation(28, 17) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_049_Consumption_Logical_TrueFalseBetterness([CombinatorialValues("&&", "||")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension((T, S)) + { + public static (T, S) operator {{{op[0]}}}((T, S) x, (T, S) y) + { + System.Console.Write("operator1"); + return x; + } + + public static bool operator true((T, S) x) => throw null; + public static bool operator false((T, S) x) => throw null; + } + + extension((int, int)) + { + public static bool operator {{{(op == "&&" ? "false" : "true")}}}((int, int) x) + { + System.Console.Write("operator2"); + return false; + } + + public static bool operator {{{(op == "&&" ? "true" : "false")}}}((int, int) x) => throw null; + } +} + +class Program +{ + static void Main() + { + var s1 = (1, 2); + s1 = s1 {{{op}}} s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2operator1").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + AssertEx.Equal("Extensions1.extension((int, int)).operator " + op[0] + "((int, int), (int, int))", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + } + + [Theory] + [CombinatorialData] + public void Binary_050_Consumption_Logical_TrueFalseApplicability([CombinatorialValues("&&", "||")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator {{{op[0]}}}(C1 x, C1 y) + { + System.Console.Write("operator1"); + return x; + } + + public static bool operator {{{(op == "&&" ? "false" : "true")}}}(C1 x) + { + System.Console.Write("operator2"); + return false; + } + + public static bool operator {{{(op == "&&" ? "true" : "false")}}}(C1 x) => throw null; + } + + extension(C2) + { + public static bool operator true(C2 x) => throw null; + public static bool operator false(C2 x) => throw null; + } +} + +public class C1 +{} + +public class C2 : C1 +{} + +class Program +{ + static void Main() + { + C1 c1 = new C1(); + c1 = c1 {{{op}}} c1; + + C2 c2 = new C2(); + c1 = c2 {{{op}}} c2; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2operator1operator2operator1").VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void Binary_051_Consumption_Logical_TrueFalseApplicability([CombinatorialValues("&&", "||")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static bool operator {{{(op == "&&" ? "false" : "true")}}}(C1 x) + { + System.Console.Write("operator2"); + return false; + } + + public static bool operator {{{(op == "&&" ? "true" : "false")}}}(C1 x) => throw null; + } + + extension(C2) + { + public static C2 operator {{{op[0]}}}(C2 x, C2 y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public class C1 +{} + +public class C2 : C1 +{} + +class Program +{ + static void Main() + { + C2 c2 = new C2(); + c2 = c2 {{{op}}} c2; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2operator1").VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void Binary_052_Consumption_Logical_TrueFalseApplicability([CombinatorialValues("&&", "||")] string op) + { + var src1 = $$$""" +namespace NS +{ + public static class Extensions1 + { + extension(C1) + { + public static C1 operator {{{op[0]}}}(C1 x, C1 y) => throw null; + } + + extension(C2) + { + public static bool operator true(C2 x) => throw null; + public static bool operator false(C2 x) => throw null; + } + } + + class Program + { + static void Main() + { + C1 c1 = new C1(); + c1 = c1 {{{op}}} c1; + + C2 c2 = new C2(); + c1 = c2 {{{op}}} c2; + } + } +} + +public class C1 +{} + +public class C2 : C1 +{} +"""; + var src2 = $$$""" +public static class Extensions2 +{ + extension(C1) + { + public static C1 operator {{{op[0]}}}(C1 x, C1 y) => throw null; + public static bool operator true(C1 x) => throw null; + public static bool operator false(C1 x) => throw null; + } +} +"""; + + var comp = CreateCompilation(src1, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (22,18): error CS0218: In order for 'NS.Extensions1.extension(C1).operator &(C1, C1)' to be applicable as a short circuit operator, its declaring type 'NS.Extensions1' must define operator true and operator false + // c1 = c1 && c1; + Diagnostic(ErrorCode.ERR_MustHaveOpTF, "c1 " + op + " c1").WithArguments("NS.Extensions1.extension(C1).operator " + op[0] + "(C1, C1)", "NS.Extensions1").WithLocation(22, 18), + // (25,18): error CS0218: In order for 'NS.Extensions1.extension(C1).operator &(C1, C1)' to be applicable as a short circuit operator, its declaring type 'NS.Extensions1' must define operator true and operator false + // c1 = c2 && c2; + Diagnostic(ErrorCode.ERR_MustHaveOpTF, "c2 " + op + " c2").WithArguments("NS.Extensions1.extension(C1).operator " + op[0] + "(C1, C1)", "NS.Extensions1").WithLocation(25, 18) + ); + + comp = CreateCompilation([src1, src2], options: TestOptions.DebugExe); + + comp.VerifyEmitDiagnostics( + // (22,18): error CS0218: In order for 'NS.Extensions1.extension(C1).operator &(C1, C1)' to be applicable as a short circuit operator, its declaring type 'NS.Extensions1' must define operator true and operator false + // c1 = c1 && c1; + Diagnostic(ErrorCode.ERR_MustHaveOpTF, "c1 " + op + " c1").WithArguments("NS.Extensions1.extension(C1).operator " + op[0] + "(C1, C1)", "NS.Extensions1").WithLocation(22, 18), + // (25,18): error CS0218: In order for 'NS.Extensions1.extension(C1).operator &(C1, C1)' to be applicable as a short circuit operator, its declaring type 'NS.Extensions1' must define operator true and operator false + // c1 = c2 && c2; + Diagnostic(ErrorCode.ERR_MustHaveOpTF, "c2 " + op + " c2").WithArguments("NS.Extensions1.extension(C1).operator " + op[0] + "(C1, C1)", "NS.Extensions1").WithLocation(25, 18) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_053_Consumption_Logical_TrueOrFalseInDifferentClass([CombinatorialValues("&&", "||")] string op) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op[0]}}}(S1 x, S1 y) + { + System.Console.Write("operator1"); + return x; + } + } + extension(S1) + { + public static bool operator {{{(op == "&&" ? "true" : "false")}}}(S1 x) => throw null; + } +} + +public static class Extensions2 +{ + extension(S1) + { + public static bool operator {{{(op == "&&" ? "false" : "true")}}}(S1 x) + { + System.Console.Write("operator2"); + return false; + } + } +} + +public struct S1 +{} +"""; + var src2 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1(); + s1 = s1 {{{op}}} s1; + } +} +"""; + + var comp1 = CreateCompilation(src1); + var comp2 = CreateCompilation(src2, references: [comp1.ToMetadataReference()], options: TestOptions.DebugExe); + comp2.VerifyEmitDiagnostics( + // (6,14): error CS0218: In order for 'Extensions1.extension(S1).operator &(S1, S1)' to be applicable as a short circuit operator, its declaring type 'Extensions1' must define operator true and operator false + // s1 = s1 && s1; + Diagnostic(ErrorCode.ERR_MustHaveOpTF, "s1 " + op + " s1").WithArguments("Extensions1.extension(S1).operator " + op[0] + "(S1, S1)", "Extensions1").WithLocation(6, 14) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_054_Consumption_Logical_TrueOrFalseInDifferentClass([CombinatorialValues("&&", "||")] string op) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op[0]}}}(S1 x, S1 y) + { + System.Console.Write("operator1"); + return x; + } + } + extension(S1) + { + public static bool operator {{{(op == "&&" ? "false" : "true")}}}(S1 x) + { + System.Console.Write("operator2"); + return false; + } + } +} + +public static class Extensions2 +{ + extension(S1) + { + public static bool operator {{{(op == "&&" ? "true" : "false")}}}(S1 x) => throw null; + } +} + +public struct S1 +{} +"""; + var src2 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1(); + s1 = s1 {{{op}}} s1; + } +} +"""; + + var comp1 = CreateCompilation(src1); + var comp2 = CreateCompilation(src2, references: [comp1.ToMetadataReference()], options: TestOptions.DebugExe); + comp2.VerifyEmitDiagnostics( + // (6,14): error CS0218: In order for 'Extensions1.extension(S1).operator &(S1, S1)' to be applicable as a short circuit operator, its declaring type 'Extensions1' must define operator true and operator false + // s1 = s1 && s1; + Diagnostic(ErrorCode.ERR_MustHaveOpTF, "s1 " + op + " s1").WithArguments("Extensions1.extension(S1).operator " + op[0] + "(S1, S1)", "Extensions1").WithLocation(6, 14) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_055_Consumption_Logical_TrueOrFalseInDifferentClass([CombinatorialValues("&&", "||")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op[0]}}}(S1 x, S1 y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public static class Extensions2 +{ + extension(S1) + { + public static bool operator false(S1 x) => throw null; + public static bool operator true(S1 x) => throw null; + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + var s1 = new S1(); +#line 6 + s1 = s1 {{{op}}} s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (6,14): error CS0218: In order for 'Extensions1.extension(S1).operator &(S1, S1)' to be applicable as a short circuit operator, its declaring type 'Extensions1' must define operator true and operator false + // s1 = s1 && s1; + Diagnostic(ErrorCode.ERR_MustHaveOpTF, "s1 " + op + " s1").WithArguments("Extensions1.extension(S1).operator " + op[0] + "(S1, S1)", "Extensions1").WithLocation(6, 14) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_056_Consumption_Logical_TrueFalseTakesNullable([CombinatorialValues("&&", "||")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op[0]}}}(S1 x, S1 y) + { + System.Console.Write("operator1"); + return x; + } + + public static bool operator true(S1? x) => throw null; + + public static bool operator false(S1? x) => throw null; + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + var s1 = new S1(); + s1 = s1 {{{op}}} s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (11,37): error CS9317: The parameter of a unary operator must be the extended type. + // public static bool operator true(S1? x) => throw null; + Diagnostic(ErrorCode.ERR_BadExtensionUnaryOperatorSignature, "true").WithLocation(11, 37), + // (13,37): error CS9317: The parameter of a unary operator must be the extended type. + // public static bool operator false(S1? x) => throw null; + Diagnostic(ErrorCode.ERR_BadExtensionUnaryOperatorSignature, "false").WithLocation(13, 37) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_057_Consumption_Logical_TrueFalseTakesNullable([CombinatorialValues("&&", "||")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op[0]}}}(S1 x, S1 y) + { + System.Console.Write("operator1"); + return x; + } + } + extension(S1?) + { + public static bool operator {{{(op == "&&" ? "false" : "true")}}}(S1? x) + { + System.Console.Write("operator2"); + return false; + } + + public static bool operator {{{(op == "&&" ? "true" : "false")}}}(S1? x) => throw null; + + public static void M1(S1? x) {} + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + var s1 = new S1(); + s1 = s1 {{{op}}} s1; + + S1.M1(s1); + System.Nullable.M1(s1); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (33,14): error CS0218: In order for 'Extensions1.extension(S1).operator &(S1, S1)' to be applicable as a short circuit operator, its declaring type 'Extensions1' must define operator true and operator false + // s1 = s1 && s1; + Diagnostic(ErrorCode.ERR_MustHaveOpTF, "s1 " + op + " s1").WithArguments("Extensions1.extension(S1).operator " + op[0] + "(S1, S1)", "Extensions1").WithLocation(33, 14), + // (35,9): error CS1929: 'S1' does not contain a definition for 'M1' and the best extension method overload 'Extensions1.extension(S1?).M1(S1?)' requires a receiver of type 'S1?' + // S1.M1(s1); + Diagnostic(ErrorCode.ERR_BadInstanceArgType, "S1").WithArguments("S1", "M1", "Extensions1.extension(S1?).M1(S1?)", "S1?").WithLocation(35, 9) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_058_Consumption_Logical_TrueFalseTakesNullable([CombinatorialValues("&&", "||")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1? operator {{{op[0]}}}(S1? x, S1? y) => throw null; + } + extension(S1) + { + public static bool operator true(S1? x) => throw null; + + public static bool operator false(S1? x) => throw null; + + public static void M1(S1? x) {} + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + var s1 = new S1(); +#line 33 + s1 = s1 {{{op}}} s1; + + S1.M1(s1); + System.Nullable.M1(s1); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (5,36): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S1? operator &(S1? x, S1? y) => throw null; + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, op[..1]).WithLocation(5, 36), + // (9,37): error CS9317: The parameter of a unary operator must be the extended type. + // public static bool operator true(S1? x) => throw null; + Diagnostic(ErrorCode.ERR_BadExtensionUnaryOperatorSignature, "true").WithLocation(9, 37), + // (11,37): error CS9317: The parameter of a unary operator must be the extended type. + // public static bool operator false(S1? x) => throw null; + Diagnostic(ErrorCode.ERR_BadExtensionUnaryOperatorSignature, "false").WithLocation(11, 37), + // (33,14): error CS0019: Operator '&&' cannot be applied to operands of type 'S1' and 'S1' + // s1 = s1 && s1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 " + op + " s1").WithArguments(op, "S1", "S1").WithLocation(33, 14), + // (36,9): error CS1929: 'S1?' does not contain a definition for 'M1' and the best extension method overload 'Extensions1.extension(S1).M1(S1?)' requires a receiver of type 'S1' + // System.Nullable.M1(s1); + Diagnostic(ErrorCode.ERR_BadInstanceArgType, "System.Nullable").WithArguments("S1?", "M1", "Extensions1.extension(S1).M1(S1?)", "S1").WithLocation(36, 9) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_059_Consumption_Logical_TrueFalseTakesNullable([CombinatorialValues("&&", "||")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1? operator {{{op[0]}}}(S1? x, S1? y) + { + System.Console.Write("operator1"); + return x; + } + } + extension(S1?) + { + public static bool operator {{{(op == "&&" ? "false" : "true")}}}(S1? x) + { + System.Console.Write("operator2"); + return false; + } + + public static bool operator {{{(op == "&&" ? "true" : "false")}}}(S1? x) => throw null; + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + var s1 = new S1(); + s1 = (s1 {{{op}}} s1).GetValueOrDefault(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (5,36): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static S1? operator &(S1? x, S1? y) + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, op[..1]).WithLocation(5, 36), + // (31,15): error CS0019: Operator '&&' cannot be applied to operands of type 'S1' and 'S1' + // s1 = (s1 && s1).GetValueOrDefault(); + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 " + op + " s1").WithArguments(op, "S1", "S1").WithLocation(31, 15) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_060_Consumption_Logical_TrueFalseTakesNullable([CombinatorialValues("&&", "||")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1?) + { + public static S1? operator {{{op[0]}}}(S1? x, S1? y) + { + System.Console.Write("operator1"); + return x; + } + + public static bool operator {{{(op == "&&" ? "false" : "true")}}}(S1? x) + { + System.Console.Write("operator2"); + return false; + } + + public static bool operator {{{(op == "&&" ? "true" : "false")}}}(S1? x) => throw null; + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? s1 = new S1(); + s1 = (s1 {{{op}}} s1).GetValueOrDefault(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2operator1").VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void Binary_061_Consumption_Logical_TrueFalseTakesObject([CombinatorialValues("&&", "||")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op[0]}}}(S1 x, S1 y) + { + System.Console.Write("operator1"); + return x; + } + } + extension(object) + { + public static bool operator {{{(op == "&&" ? "false" : "true")}}}(object x) + { + System.Console.Write("operator2"); + return false; + } + + public static bool operator {{{(op == "&&" ? "true" : "false")}}}(object x) => throw null; + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + var s1 = new S1(); + s1 = s1 {{{op}}} s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2operator1").VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void Binary_062_Consumption_Logical_TrueFalseTakesSpan([CombinatorialValues("&&", "||")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(int[]) + { + public static int[] operator {{{op[0]}}}(int[] x, int[] y) + { + System.Console.Write("operator1"); + return x; + } + } + extension(System.Span) + { + public static bool operator {{{(op == "&&" ? "false" : "true")}}}(System.Span x) + { + System.Console.Write("operator2"); + return false; + } + + public static bool operator {{{(op == "&&" ? "true" : "false")}}}(System.Span x) => throw null; + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + var s1 = new int[] {}; + s1 = s1 {{{op}}} s1; + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "operator2operator1" : null, verify: Verification.FailsPEVerify).VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void Binary_063_Consumption_Logical_TrueFalseTakesDifferentTuple([CombinatorialValues("&&", "||")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension((int, int)) + { + public static (int, int) operator {{{op[0]}}}((int, int) x, (int, int) y) + { + System.Console.Write("operator1"); + return x; + } + } + extension((int, object)) + { + public static bool operator {{{(op == "&&" ? "false" : "true")}}}((int, object) x) + { + System.Console.Write("operator2"); + return false; + } + + public static bool operator {{{(op == "&&" ? "true" : "false")}}}((int, object) x) => throw null; + } +} + +class Program +{ + static void Main() + { + var s1 = (1, 2); + s1 = s1 {{{op}}} s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2operator1").VerifyDiagnostics(); + } + + [Fact] + public void Binary_064_Consumption_Logical_PredefinedComesFirst() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator &(S2 x, S2 y) => throw null; + public static bool operator true (S2 x) => throw null; + public static bool operator false(S2 x) => throw null; + } +} + +public struct S2 +{ + public static implicit operator bool(S2 x) + { + System.Console.Write("operator3"); + return true; + } +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + bool x = s2 && s2; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator3operator3").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + + Assert.Equal("System.Boolean", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + } + + [Fact] + public void Binary_065_Consumption_Logical_NonExtensionComesFirst() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator &(S2 x, S2 y) => throw null; + public static bool operator false(S2 x) => throw null; + public static bool operator true(S2 x) => throw null; + } +} + +public struct S2 +{ + public static S2 operator &(S2 x, S2 y) + { + System.Console.Write("operator2"); + return x; + } + public static bool operator false(S2 x) + { + System.Console.Write("operator1"); + return false; + } + + public static bool operator true(S2 x) => throw null; +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + _ = s2 && s2; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1operator2").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("S2.operator &(S2, S2)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S2", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Binary_066_Consumption_Logical_NonExtensionComesFirst_DifferentParameterTypes() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator &(S2 x, S2 y) => throw null; + public static bool operator false(S2 x) => throw null; + public static bool operator true(S2 x) => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{ + public static S2 operator &(S2 x, S1 y) + { + return x; + } + + public static implicit operator S2(S1 x) => default; +} + +class Program +{ + static void Main() + { + var s1 = new S1(); + var s2 = new S2(); + _ = s2 && s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + + comp.VerifyEmitDiagnostics( + // (30,13): error CS0217: In order to be applicable as a short circuit operator a user-defined logical operator ('S2.operator &(S2, S1)') must have the same return type and parameter types + // _ = s2 && s1; + Diagnostic(ErrorCode.ERR_BadBoolOp, "s2 && s1").WithArguments("S2.operator &(S2, S1)").WithLocation(30, 13) + ); + } + + [Fact] + public void Binary_067_Consumption_Logical_NonExtensionComesFirst_TrueFalseIsMissing() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator &(S2 x, S2 y) => throw null; + public static bool operator false(S2 x) => throw null; + public static bool operator true(S2 x) => throw null; + } +} + +public struct S2 +{ + public static S2 operator &(S2 x, S2 y) + { + return x; + } +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + _ = s2 && s2; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + + comp.VerifyEmitDiagnostics( + // (24,13): error CS0218: In order for 'S2.operator &(S2, S2)' to be applicable as a short circuit operator, its declaring type 'S2' must define operator true and operator false + // _ = s2 && s2; + Diagnostic(ErrorCode.ERR_MustHaveOpTF, "s2 && s2").WithArguments("S2.operator &(S2, S2)", "S2").WithLocation(24, 13) + ); + } + + [Fact] + public void Binary_068_Consumption_Logical_ScopeByScope() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator &(S1 x, S1 y) => throw null; + public static bool operator true(S1 x) => throw null; + public static bool operator false(S1 x) => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{} + +namespace NS1 +{ + public static class Extensions2 + { + extension(S1) + { + public static S1 operator &(S1 x, S1 y) + { + System.Console.Write("operator2"); + return x; + } + + public static bool operator true(S1 x) => throw null; + public static bool operator false(S1 x) + { + System.Console.Write("operator1"); + return false; + } + } + } + + namespace NS2 + { + public static class Extensions3 + { + extension(S2) + { + public static S2 operator &(S2 x, S2 y) => throw null; + public static bool operator true(S2 x) => throw null; + public static bool operator false(S2 x) => throw null; + } + } + + class Program + { + static void Main() + { + var s1 = new S1(); + _ = s1 && s1; + } + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1operator2").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("NS1.Extensions2.extension(S1).operator &(S1, S1)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S1", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Binary_069_Consumption_Logical_NonExtensionAmbiguity() + { + var src = $$$""" +public interface I1 +{ + public static I1 operator &(I1 x, I1 y) => x; + public static bool operator true(I1 x) => true; + public static bool operator false(I1 x) => false; +} + +public interface I3 +{ + public static I3 operator &(I3 x, I3 y) => x; + public static bool operator true(I3 x) => true; + public static bool operator false(I3 x) => false; +} + +public interface I4 : I1, I3 +{ +} + +public interface I2 : I4 +{ +} + +public static class Extensions1 +{ + extension(I2) + { + public static I2 operator &(I2 x, I2 y) => x; + public static bool operator true(I2 x) => true; + public static bool operator false(I2 x) => false; + } +} + +class Test2 : I2 +{ + static void Main() + { + I2 x = new Test2(); + var y = x && x; + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (38,17): error CS0034: Operator '&&' is ambiguous on operands of type 'I2' and 'I2' + // var y = x && x; + Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "x && x").WithArguments("&&", "I2", "I2").WithLocation(38, 17) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); + Assert.Equal(2, symbolInfo.CandidateSymbols.Length); + AssertEx.Equal("I1.operator &(I1, I1)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("I3.operator &(I3, I3)", symbolInfo.CandidateSymbols[1].ToDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Binary_070_Consumption_Logical_NonExtensionAmbiguity() + { + var src = $$$""" +public interface I1 +{ + public static I1 operator &(I1 x, I1 y) => x; +} + +public interface I3 +{ + public static I3 operator &(I3 x, I3 y) => x; +} + +public interface I4 : I1, I3 +{ +} + +public interface I2 : I4 +{ +} + +public static class Extensions1 +{ + extension(I2) + { + public static I2 operator &(I2 x, I2 y) => x; + public static bool operator true(I2 x) => true; + public static bool operator false(I2 x) => false; + } +} + +class Test2 : I2 +{ + static void Main() + { + I2 x = new Test2(); + var y = x && x; + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + + comp.VerifyEmitDiagnostics( + // (34,17): error CS0034: Operator '&&' is ambiguous on operands of type 'I2' and 'I2' + // var y = x && x; + Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "x && x").WithArguments("&&", "I2", "I2").WithLocation(34, 17) + ); + } + + [Fact] + [WorkItem("https://github.com/dotnet/roslyn/issues/78830")] + public void Binary_071_Consumption_Logical_ExtensionAmbiguity() + { + var src = $$$""" +public interface I1; +public interface I3; +public interface I4 : I1, I3; +public interface I2 : I4; + +public static class Extensions1 +{ + extension(I2) + { + public static I2 operator &(I2 x, I2 y) => x; + public static bool operator true(I2 x) => true; + public static bool operator false(I2 x) => false; + } +} + +namespace NS1 +{ + public static class Extensions2 + { + extension(I1) + { + public static I1 operator &(I1 x, I1 y) => x; + public static bool operator true(I1 x) => true; + public static bool operator false(I1 x) => false; + } + + extension(I3) + { + public static I3 operator &(I3 x, I3 y) => x; + public static bool operator true(I3 x) => true; + public static bool operator false(I3 x) => false; + } + } + + class Test2 : I2 + { + static void Main() + { + I2 x = new Test2(); + var y = x && x; + } + } +} +"""; + + var comp = CreateCompilation(src); + + // https://github.com/dotnet/roslyn/issues/78830: We might want to include more information into the error. Like what methods conflict. + comp.VerifyEmitDiagnostics( + // (40,21): error CS0034: Operator '&&' is ambiguous on operands of type 'I2' and 'I2' + // var y = x && x; + Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "x && x").WithArguments("&&", "I2", "I2").WithLocation(40, 21) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); + Assert.Equal(2, symbolInfo.CandidateSymbols.Length); + AssertEx.Equal("NS1.Extensions2.extension(I1).operator &(I1, I1)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("NS1.Extensions2.extension(I3).operator &(I3, I3)", symbolInfo.CandidateSymbols[1].ToDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void Binary_072_Consumption_Logical_ExtensionAmbiguity() + { + var src = $$$""" +public interface I1; +public interface I3; +public interface I4 : I1, I3; +public interface I2 : I4; + +public static class Extensions2 +{ + extension(I2) + { + public static I2 operator &(I2 x, I2 y) => x; + public static bool operator true(I2 x) => true; + public static bool operator false(I2 x) => false; + } +} + +namespace NS1 +{ + public static class Extensions2 + { + extension(I1) + { + public static I1 operator &(I1 x, I1 y) => x; + } + + extension(I3) + { + public static I3 operator &(I3 x, I3 y) => x; + } + } + + class Test2 : I2 + { + static void Main() + { + I2 x = new Test2(); + var y = x && x; + } + } +} +"""; + + var comp = CreateCompilation(src); + + comp.VerifyEmitDiagnostics( + // (36,21): error CS0034: Operator '&&' is ambiguous on operands of type 'I2' and 'I2' + // var y = x && x; + Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "x && x").WithArguments("&&", "I2", "I2").WithLocation(36, 21) + ); + } + + [Fact] + public void Binary_073_Consumption_Logical_ExtensionAmbiguity() + { + var src = $$$""" +public interface I1; +public interface I3; +public interface I4 : I1, I3; +public interface I2 : I4; + +public static class Extensions2 +{ + extension(I1) + { + public static I1 operator &(I1 x, I1 y) => x; + public static bool operator true(I1 x) => true; + public static bool operator false(I1 x) => false; + } + + extension(I3) + { + public static I3 operator &(I3 x, I3 y) => x; + } +} + +class Test2 : I2 +{ + static void Main() + { + I2 x = new Test2(); + var y = x && x; + } +} +"""; + + var comp = CreateCompilation(src); + + comp.VerifyEmitDiagnostics( + // (26,17): error CS0034: Operator '&&' is ambiguous on operands of type 'I2' and 'I2' + // var y = x && x; + Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "x && x").WithArguments("&&", "I2", "I2").WithLocation(26, 17) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_074_Consumption_Logical_Lifted([CombinatorialValues("&&", "||")] string op) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op[0]}}}(S1 x, S1 y) + { + System.Console.Write("operator1:"); + System.Console.Write(x.F); + System.Console.Write(":"); + System.Console.Write(y.F); + return new S1 { F = x.F {{{op[0]}}} y.F }; + } + } + extension(S1?) + { + public static bool operator true(S1? x) + { + System.Console.Write("operator2:"); + System.Console.Write(x?.F.ToString() ?? "null"); + System.Console.Write(":"); + return x?.F == true; + } + + public static bool operator false(S1? x) + { + System.Console.Write("operator3:"); + System.Console.Write(x?.F.ToString() ?? "null"); + System.Console.Write(":"); + return x?.F == false; + } + } +} + +public struct S1 +{ + public bool F; +} +"""; + var src2 = $$$""" +class Program +{ + static void Main() + { + S1?[] s = [new S1() { F = false }, new S1() { F = true }, null]; + + foreach (var s1 in s) + { + foreach (var s2 in s) + { + Print(s1 {{{op}}} s2); + System.Console.WriteLine(); + } + } + } + + static void Print(S1? x) + { + System.Console.Write(":"); + System.Console.Write(x?.F.ToString() ?? "null"); + } +} +"""; + + string expected = op == "&&" ? +@" +operator3:False::False +operator3:False::False +operator3:False::False +operator3:True:operator1:True:False:False +operator3:True:operator1:True:True:True +operator3:True::null +operator3:null::null +operator3:null::null +operator3:null::null +" +: +@" +operator2:False:operator1:False:False:False +operator2:False:operator1:False:True:True +operator2:False::null +operator2:True::True +operator2:True::True +operator2:True::True +operator2:null::null +operator2:null::null +operator2:null::null +"; + + var comp1 = CreateCompilation([src1, src2], options: TestOptions.DebugExe); + CompileAndVerify(comp1, expectedOutput: expected).VerifyDiagnostics(); + + var comp2 = CreateCompilation([src1, src2], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: expected).VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1.ToMetadataReference()], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (11,23): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // Print(s1 && s2); + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s1 " + op + " s2").WithArguments("extensions").WithLocation(11, 23) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_075_Consumption_Logical_Lifted([CombinatorialValues("&&", "||")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op[0]}}}(S1 x, S1 y) + { + System.Console.Write("operator1:"); + System.Console.Write(x.F); + System.Console.Write(":"); + System.Console.Write(y.F); + return new S1 { F = x.F {{{op[0]}}} y.F }; + } + } + extension(S1?) + { + public static bool operator true(S1? x) + { + System.Console.Write("operator2:"); + System.Console.Write(x?.F.ToString() ?? "null"); + System.Console.Write(":"); + return x?.F == true; + } + + public static bool operator false(S1? x) + { + System.Console.Write("operator3:"); + System.Console.Write(x?.F.ToString() ?? "null"); + System.Console.Write(":"); + return x?.F == false; + } + } +} + +public struct S1 +{ + public bool F; +} + +class Program +{ + static void Main() + { + S1?[] s1 = [new S1() { F = false }, new S1() { F = true }, null]; + S1[] s2 = [new S1() { F = false }, new S1() { F = true }]; + + foreach (var s11 in s1) + { + foreach (var s12 in s2) + { + Print(s11 {{{op}}} s12); + System.Console.WriteLine(); + } + } + + foreach (var s11 in s2) + { + foreach (var s12 in s1) + { + Print(s11 {{{op}}} s12); + System.Console.WriteLine(); + } + } + } + + static void Print(S1? x) + { + System.Console.Write(":"); + System.Console.Write(x?.F.ToString() ?? "null"); + } +} +"""; + + string expected = op == "&&" ? +@" +operator3:False::False +operator3:False::False +operator3:True:operator1:True:False:False +operator3:True:operator1:True:True:True +operator3:null::null +operator3:null::null +operator3:False::False +operator3:False::False +operator3:False::False +operator3:True:operator1:True:False:False +operator3:True:operator1:True:True:True +operator3:True::null +" +: +@" +operator2:False:operator1:False:False:False +operator2:False:operator1:False:True:True +operator2:True::True +operator2:True::True +operator2:null::null +operator2:null::null +operator2:False:operator1:False:False:False +operator2:False:operator1:False:True:True +operator2:False::null +operator2:True::True +operator2:True::True +operator2:True::True +"; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: expected).VerifyDiagnostics(); + } + + [Fact] + public void Binary_076_Consumption_Logical_LiftedIsWorse() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator &(S1 x, S1 y) => throw null; + } + extension(S1?) + { + public static S1? operator &(S1? x, S1? y) + { + System.Console.Write("operator1"); + return x; + } + public static bool operator false(S1? x) + { + System.Console.Write("operator2"); + return false; + } + + public static bool operator true(S1? x) => throw null; + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? s1 = new S1(); + _ = s1 && s1; + System.Console.Write(":"); + s1 = null; + _ = s1 && s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2operator1:operator2operator1").VerifyDiagnostics(); + } + + [Fact] + [WorkItem("https://github.com/dotnet/roslyn/issues/78830")] + public void Binary_077_Consumption_Logical_NoLiftedFormForTrueFalse() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator &(S1 x, S1 y) => throw null; + public static bool operator false(S1 x) => throw null; + public static bool operator true(S1 x) => throw null; + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? s1 = new S1(); + _ = s1 && s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + + // https://github.com/dotnet/roslyn/issues/78830: The wording is somewhat confusing because there are operators for S1, what is missing are the true/false operators for S1?. + comp.VerifyEmitDiagnostics( + // (19,13): error CS0218: In order for 'Extensions1.extension(S1).operator &(S1, S1)' to be applicable as a short circuit operator, its declaring type 'Extensions1' must define operator true and operator false + // _ = s1 && s1; + Diagnostic(ErrorCode.ERR_MustHaveOpTF, "s1 && s1").WithArguments("Extensions1.extension(S1).operator &(S1, S1)", "Extensions1").WithLocation(19, 13) + ); + } + + [Fact] + public void Binary_078_Consumption_Logical_OnObject() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object) + { + public static object operator &(object x, object y) + { + System.Console.Write("operator1"); + return x; + } + public static bool operator false(object x) + { + System.Console.Write("operator2"); + return false; + } + + public static bool operator true(object x) => throw null; + } +} + +class Program +{ + static void Main() + { + var s1 = new object(); + _ = s1 && s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2operator1").VerifyDiagnostics(); + } + + [Fact] + public void Binary_079_Consumption_Logical_NotOnDynamic() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object) + { + public static object operator &(object x, object y) + { + System.Console.Write("operator1"); + return x; + } + public static bool operator false(object x) + { + System.Console.Write("operator2"); + return false; + } + + public static bool operator true(object x) => throw null; + } +} + +class Program +{ + static void Main() + { + dynamic s1 = new object(); + var s2 = new object(); + + try + { + _ = s1 && s2; + } + catch + { + System.Console.Write("exception1"); + } + + + try + { + _ = s1 && s1; + } + catch + { + System.Console.Write("exception2"); + } + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "exception1exception2").VerifyDiagnostics(); + } + + [Fact] + public void Binary_080_Consumption_Logical_NotOnDynamic() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object) + { + public static object operator &(object x, object y) + { + System.Console.Write("operator1"); + return x; + } + public static bool operator false(object x) + { + System.Console.Write("operator2"); + return false; + } + + public static bool operator true(object x) => throw null; + } +} + +class Program +{ + static void Main() + { + dynamic s1 = new object(); + var s2 = new object(); + _ = s2 && s1; + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); + + // Note, an attempt to do compile time optimization using non-dynamic static type of 's2' ignores true/false extensions. + // This is desirable because runtime binder wouldn't be able to use them as well. + comp.VerifyEmitDiagnostics( + // (26,13): error CS7083: Expression must be implicitly convertible to Boolean or its type 'object' must define operator 'false'. + // _ = s2 && s1; + Diagnostic(ErrorCode.ERR_InvalidDynamicCondition, "s2").WithArguments("object", "false").WithLocation(26, 13) + ); + } + + [Fact] + public void Binary_081_Consumption_Logical_WithLambda() + { + var src = $$$""" +public static class Extensions1 +{ + extension(System.Func) + { + public static System.Func operator &(System.Func x, System.Func y) + { + System.Console.Write("operator1"); + return x; + } + public static bool operator false(System.Func x) + { + System.Console.Write("operator2"); + return false; + } + + public static bool operator true(System.Func x) => throw null; + } +} + +public struct S1 +{} + +public class Program +{ + static void Main() + { + System.Func s1 = null; + s1 = s1 && (() => 1); + s1 = (() => 1) && s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2operator1operator2operator1").VerifyDiagnostics(); + } + + [Fact] + public void Binary_082_Consumption_Logical_WithLambda() + { + var src = $$$""" +public static class Extensions1 +{ + extension(System.Func) + { + public static System.Func operator &(System.Func x, System.Func y) + { + System.Console.Write("operator1"); + return x; + } + public static bool operator false(System.Func x) + { + System.Console.Write("operator2"); + return false; + } + + public static bool operator true(System.Func x) => throw null; + } +} + +public struct S1 +{} + +public class Program +{ + static void Main() + { + _ = (() => 1) && (() => 1); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (27,13): error CS0019: Operator '&&' cannot be applied to operands of type 'lambda expression' and 'lambda expression' + // _ = (() => 1) && (() => 1); + Diagnostic(ErrorCode.ERR_BadBinaryOps, "(() => 1) && (() => 1)").WithArguments("&&", "lambda expression", "lambda expression").WithLocation(27, 13) + ); + } + + [Fact] + public void Binary_083_Consumption_Logical_BadOperand() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object) + { + public static object operator &(object x, object y) + { + System.Console.Write("operator1"); + return x; + } + public static bool operator false(object x) + { + System.Console.Write("operator2"); + return false; + } + + public static bool operator true(object x) => throw null; + } +} + +class Program +{ + static void Main() + { + var s1 = new object(); + _ = s1 && new(); + _ = new() && s1; + _ = new() && new(); + _ = s1 && default; + _ = default && s1; + _ = default && default; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (25,19): error CS8754: There is no target type for 'new()' + // _ = s1 && new(); + Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(25, 19), + // (26,13): error CS8754: There is no target type for 'new()' + // _ = new() && s1; + Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(26, 13), + // (27,13): error CS8754: There is no target type for 'new()' + // _ = new() && new(); + Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(27, 13), + // (27,22): error CS8754: There is no target type for 'new()' + // _ = new() && new(); + Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(27, 22), + // (28,19): error CS8716: There is no target type for the default literal. + // _ = s1 && default; + Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(28, 19), + // (29,13): error CS8716: There is no target type for the default literal. + // _ = default && s1; + Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(29, 13), + // (30,13): error CS8716: There is no target type for the default literal. + // _ = default && default; + Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(30, 13), + // (30,24): error CS8716: There is no target type for the default literal. + // _ = default && default; + Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(30, 24) + ); + } + + [Fact] + public void Binary_084_Consumption_Logical_BadReceiver() + { + var src = $$$""" +public static class Extensions1 +{ + extension(__arglist) + { + public static object operator &(object x, object y) + { + return x; + } + public static bool operator false(object x) + { + System.Console.Write("operator2"); + return false; + } + + public static bool operator true(object x) => throw null; + } +} + +class Program +{ + static void Main() + { + var s1 = new object(); + _ = s1 && s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (3,15): error CS1669: __arglist is not valid in this context + // extension(__arglist) + Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(3, 15), + // (5,39): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static object operator &(object x, object y) + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, "&").WithLocation(5, 39), + // (9,37): error CS9317: The parameter of a unary operator must be the extended type. + // public static bool operator false(object x) + Diagnostic(ErrorCode.ERR_BadExtensionUnaryOperatorSignature, "false").WithLocation(9, 37), + // (15,37): error CS9317: The parameter of a unary operator must be the extended type. + // public static bool operator true(object x) => throw null; + Diagnostic(ErrorCode.ERR_BadExtensionUnaryOperatorSignature, "true").WithLocation(15, 37), + // (24,13): error CS0019: Operator '&&' cannot be applied to operands of type 'object' and 'object' + // _ = s1 && s1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 && s1").WithArguments("&&", "object", "object").WithLocation(24, 13) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_085_Consumption_Logical_Generic([CombinatorialValues("&&", "||")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension((T, S)) + { + public static (T, S) operator {{{op[0]}}}((T, S) x, (T, S) y) + { + System.Console.Write("operator1"); + return x; + } + + public static bool operator {{{(op == "&&" ? "false" : "true")}}}((T, S) x) + { + System.Console.Write("operator2"); + return false; + } + + public static bool operator {{{(op == "&&" ? "true" : "false")}}}((T, S) x) => throw null; + } +} + +class Program +{ + static void Main() + { + var s1 = (1, 2); + s1 = s1 {{{op}}} s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2operator1").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + AssertEx.Equal("Extensions1.extension((int, int)).operator " + op[0] + "((int, int), (int, int))", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + } + + [Theory] + [CombinatorialData] + public void Binary_086_Consumption_Logical_Generic([CombinatorialValues("&&", "||")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension((T, S)) + { + public static (T, S) operator {{{op[0]}}}((T, S) x, (T, S) y) + { + System.Console.Write("operator1"); + return x; + } + } + + extension(U) + { + public static bool operator {{{(op == "&&" ? "false" : "true")}}}(U x) + { + System.Console.Write("operator2"); + return false; + } + + public static bool operator {{{(op == "&&" ? "true" : "false")}}}(U x) => throw null; + } +} + +class Program +{ + static void Main() + { + var s1 = (1, 2); + s1 = s1 {{{op}}} s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2operator1").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + AssertEx.Equal("Extensions1.extension((int, int)).operator " + op[0] + "((int, int), (int, int))", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + } + + [Theory] + [CombinatorialData] + public void Binary_087_Consumption_ExpressionTree([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", ">", "<", ">=", "<=", "==", "!=")] string op) + { + string pairedOp = ""; + + if (op is ">" or "<" or ">=" or "<=" or "==" or "!=") + { + pairedOp = $$$""" + public static S1 operator {{{op switch { ">" => "<", ">=" => "<=", "==" => "!=", "<" => ">", "<=" => ">=", "!=" => "==", _ => throw ExceptionUtilities.UnexpectedValue(op) }}}}(S1 x, S1 y) => throw null; +"""; + } + + var src = $$$""" +using System.Linq.Expressions; + +#pragma warning disable CS1718 // Comparison made to same variable; did you mean to compare something else? + +public static class Extensions1 +{ + extension(S1 s1) + { + public static S1 operator {{{op}}}(S1 x, S1 y) + { + System.Console.Write("operator1"); + return x; + } +{{{pairedOp}}} + + public void Test() + { + Expression> ex = (s1) => s1 {{{op}}} s1; + ex.Compile()(s1); + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + Expression> ex = (s1) => s1 {{{op}}} s1; + + var s1 = new S1(); + ex.Compile()(s1); + + s1.Test(); + + System.Console.Write(":"); + System.Console.Write(ex); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1operator1:s1 => (s1 " + op + " s1)").VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void Binary_088_Consumption_ExpressionTree_Lifted([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>")] string op) + { + var src = $$$""" +using System.Linq.Expressions; + +public static class Extensions1 +{ + extension(S1 s1) + { + public static S1 operator {{{op}}}(S1 x, S1 y) + { + System.Console.Write("operator1"); + return x; + } + + public void Test() + { + Expression> ex = (s1) => s1 {{{op}}} s1; + var d = ex.Compile(); + d(s1); + System.Console.Write(":"); + d(null); + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + Expression> ex = (s1) => s1 {{{op}}} s1; + + var s1 = new S1(); + var d = ex.Compile(); + d(s1); + System.Console.Write(":"); + d(null); + + System.Console.Write(":"); + s1.Test(); + + System.Console.Write(":"); + System.Console.Write(ex); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1::operator1::s1 => (s1 " + op + " s1)").VerifyDiagnostics(); + } + + [Fact] + public void Binary_089_Consumption_UnsignedRightShift_ExpressionTree() + { + var src = $$$""" +using System.Linq.Expressions; + +public static class Extensions1 +{ + extension(S1 s1) + { + public static S1 operator >>>(S1 x, S1 y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + Expression> ex = (s1) => s1 >>> s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (22,54): error CS7053: An expression tree may not contain '>>>' + // Expression> ex = (s1) => s1 >>> s1; + Diagnostic(ErrorCode.ERR_FeatureNotValidInExpressionTree, "s1 >>> s1").WithArguments(">>>").WithLocation(22, 54) + ); + } + + [Fact] + public void Binary_090_Consumption_UnsignedRightShift_Lifted_ExpressionTree() + { + var src = $$$""" +using System.Linq.Expressions; + +public static class Extensions1 +{ + extension(S1 s1) + { + public static S1 operator >>>(S1 x, S1 y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + Expression> ex = (s1) => s1 >>> s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (22,56): error CS7053: An expression tree may not contain '>>>' + // Expression> ex = (s1) => s1 >>> s1; + Diagnostic(ErrorCode.ERR_FeatureNotValidInExpressionTree, "s1 >>> s1").WithArguments(">>>").WithLocation(22, 56) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_091_Consumption_Logical_ExpressionTree([CombinatorialValues("&&", "||")] string op) + { + var src = $$$""" +using System.Linq.Expressions; + +public static class Extensions1 +{ + extension(S1 s1) + { + public static S1 operator {{{op[0]}}}(S1 x, S1 y) + { + System.Console.Write("operator1"); + return x; + } + + public static bool operator {{{(op == "&&" ? "false" : "true")}}}(S1 x) + { + System.Console.Write("operator2"); + return false; + } + + public static bool operator {{{(op == "&&" ? "true" : "false")}}}(S1 x) => throw null; + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + Expression> ex = (s1) => s1 {{{op}}} s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (30,54): error CS9324: An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + // Expression> ex = (s1) => s1 && s1; + Diagnostic(ErrorCode.ERR_ExpressionTreeContainsExtensionBasedConditionalLogicalOperator, "s1 " + op + " s1").WithLocation(30, 54) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_092_Consumption_Logical_Lifted_ExpressionTree([CombinatorialValues("&&", "||")] string op) + { + var src = $$$""" +using System.Linq.Expressions; + +public static class Extensions1 +{ + extension(S1 s1) + { + public static S1 operator {{{op[0]}}}(S1 x, S1 y) + { + System.Console.Write("operator1"); + return x; + } + } + + extension(S1? s1) + { + public static bool operator {{{(op == "&&" ? "false" : "true")}}}(S1? x) + { + System.Console.Write("operator2"); + return false; + } + + public static bool operator {{{(op == "&&" ? "true" : "false")}}}(S1? x) => throw null; + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + Expression> ex = (s1) => s1 {{{op}}} s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (33,56): error CS9324: An expression tree may not contain '&&' or '||' operators that use extension user defined operators. + // Expression> ex = (s1) => s1 && s1; + Diagnostic(ErrorCode.ERR_ExpressionTreeContainsExtensionBasedConditionalLogicalOperator, "s1 " + op + " s1").WithLocation(33, 56) + ); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct + /// + [Fact] + public void Binary_093_RefSafety() + { + var source = """ +class C +{ + S M1() + { + S s; + s = 100 + default(S); // 1 + return s; + } + + S M2() + { + return 200 + default(S); // 2 + } + + S M3(in int x) + { + S s; + s = x + default(S); // 3 + return s; + } + + S M4(in int x) + { + return x + default(S); + } + + S M4s(scoped in int x) + { + return x + default(S); // 4 + } + + S M5(in int x) + { + S s = x + default(S); + return s; + } + + S M5s(scoped in int x) + { + S s = x + default(S); + return s; // 5 + } + + S M6() + { + S s = 300 + default(S); + return s; // 6 + } + + void M7(in int x) + { + scoped S s; + s = x + default(S); + s = 100 + default(S); + } +} + +ref struct S +{ +} + +static class Extensions +{ + extension(S) + { + public static S operator+(in int x, S y) => throw null; + } +} +"""; + CreateCompilation(source).VerifyDiagnostics( + // (6,13): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference + // s = 100 + default(S); // 1 + Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "100").WithLocation(6, 13), + // (6,13): error CS8347: Cannot use a result of 'Extensions.extension(S).operator +(in int, S)' in this context because it may expose variables referenced by parameter 'x' outside of their declaration scope + // s = 100 + default(S); // 1 + Diagnostic(ErrorCode.ERR_EscapeCall, "100 + default(S)").WithArguments("Extensions.extension(S).operator +(in int, S)", "x").WithLocation(6, 13), + // (12,16): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference + // return 200 + default(S); // 2 + Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "200").WithLocation(12, 16), + // (12,16): error CS8347: Cannot use a result of 'Extensions.extension(S).operator +(in int, S)' in this context because it may expose variables referenced by parameter 'x' outside of their declaration scope + // return 200 + default(S); // 2 + Diagnostic(ErrorCode.ERR_EscapeCall, "200 + default(S)").WithArguments("Extensions.extension(S).operator +(in int, S)", "x").WithLocation(12, 16), + // (18,13): error CS9077: Cannot return a parameter by reference 'x' through a ref parameter; it can only be returned in a return statement + // s = x + default(S); // 3 + Diagnostic(ErrorCode.ERR_RefReturnOnlyParameter, "x").WithArguments("x").WithLocation(18, 13), + // (18,13): error CS8347: Cannot use a result of 'Extensions.extension(S).operator +(in int, S)' in this context because it may expose variables referenced by parameter 'x' outside of their declaration scope + // s = x + default(S); // 3 + Diagnostic(ErrorCode.ERR_EscapeCall, "x + default(S)").WithArguments("Extensions.extension(S).operator +(in int, S)", "x").WithLocation(18, 13), + // (29,16): error CS9075: Cannot return a parameter by reference 'x' because it is scoped to the current method + // return x + default(S); // 4 + Diagnostic(ErrorCode.ERR_RefReturnScopedParameter, "x").WithArguments("x").WithLocation(29, 16), + // (29,16): error CS8347: Cannot use a result of 'Extensions.extension(S).operator +(in int, S)' in this context because it may expose variables referenced by parameter 'x' outside of their declaration scope + // return x + default(S); // 4 + Diagnostic(ErrorCode.ERR_EscapeCall, "x + default(S)").WithArguments("Extensions.extension(S).operator +(in int, S)", "x").WithLocation(29, 16), + // (41,16): error CS8352: Cannot use variable 's' in this context because it may expose referenced variables outside of their declaration scope + // return s; // 5 + Diagnostic(ErrorCode.ERR_EscapeVariable, "s").WithArguments("s").WithLocation(41, 16), + // (47,16): error CS8352: Cannot use variable 's' in this context because it may expose referenced variables outside of their declaration scope + // return s; // 6 + Diagnostic(ErrorCode.ERR_EscapeVariable, "s").WithArguments("s").WithLocation(47, 16) + ); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Nested + /// + [Fact] + public void Binary_094_RefSafety() + { + var source = """ +class C +{ + S M() + { + S s; + s = default(S) + 100 + 200; + return s; + } +} + +ref struct S +{ +} + +static class Extensions +{ + extension(S) + { + public static S operator+(S y, in int x) => throw null; + } +} +"""; + CreateCompilation(source).VerifyDiagnostics( + // (6,13): error CS8347: Cannot use a result of 'Extensions.extension(S).operator +(S, in int)' in this context because it may expose variables referenced by parameter 'x' outside of their declaration scope + // s = default(S) + 100 + 200; + Diagnostic(ErrorCode.ERR_EscapeCall, "default(S) + 100").WithArguments("Extensions.extension(S).operator +(S, in int)", "x").WithLocation(6, 13), + // (6,13): error CS8347: Cannot use a result of 'Extensions.extension(S).operator +(S, in int)' in this context because it may expose variables referenced by parameter 'y' outside of their declaration scope + // s = default(S) + 100 + 200; + Diagnostic(ErrorCode.ERR_EscapeCall, "default(S) + 100 + 200").WithArguments("Extensions.extension(S).operator +(S, in int)", "y").WithLocation(6, 13), + // (6,26): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference + // s = default(S) + 100 + 200; + Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "100").WithLocation(6, 26) + ); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Scoped_Left + /// + [Fact] + public void Binary_095_RefSafety() + { + var source = """ +ref struct R +{ + private ref readonly int _i; + public R(in int i) { _i = ref i; } +} +class Program +{ + static R F() + { +#line 11 + return new R(1) + new R(2); + } +} + +static class Extensions +{ + extension(R) + { + public static R operator +(scoped R x, R y) => default; + } +} +"""; + CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( + // (11,16): error CS8347: Cannot use a result of 'Extensions.extension(R).operator +(scoped R, R)' in this context because it may expose variables referenced by parameter 'y' outside of their declaration scope + // return new R(1) + new R(2); + Diagnostic(ErrorCode.ERR_EscapeCall, "new R(1) + new R(2)").WithArguments("Extensions.extension(R).operator +(scoped R, R)", "y").WithLocation(11, 16), + // (11,27): error CS8347: Cannot use a result of 'R.R(in int)' in this context because it may expose variables referenced by parameter 'i' outside of their declaration scope + // return new R(1) + new R(2); + Diagnostic(ErrorCode.ERR_EscapeCall, "new R(2)").WithArguments("R.R(in int)", "i").WithLocation(11, 27), + // (11,33): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference + // return new R(1) + new R(2); + Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "2").WithLocation(11, 33) + ); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Scoped_Right + /// + [Fact] + public void Binary_096_RefSafety() + { + var source = """ +ref struct R +{ + private ref readonly int _i; + public R(in int i) { _i = ref i; } +} +class Program +{ + static R F() + { +#line 11 + return new R(1) + new R(2); + } +} + +static class Extensions +{ + extension(R) + { + public static R operator +(R x, scoped R y) => default; + } +} +"""; + CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( + // (11,16): error CS8347: Cannot use a result of 'R.R(in int)' in this context because it may expose variables referenced by parameter 'i' outside of their declaration scope + // return new R(1) + new R(2); + Diagnostic(ErrorCode.ERR_EscapeCall, "new R(1)").WithArguments("R.R(in int)", "i").WithLocation(11, 16), + // (11,16): error CS8347: Cannot use a result of 'Extensions.extension(R).operator +(R, scoped R)' in this context because it may expose variables referenced by parameter 'x' outside of their declaration scope + // return new R(1) + new R(2); + Diagnostic(ErrorCode.ERR_EscapeCall, "new R(1) + new R(2)").WithArguments("Extensions.extension(R).operator +(R, scoped R)", "x").WithLocation(11, 16), + // (11,22): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference + // return new R(1) + new R(2); + Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "1").WithLocation(11, 22) + ); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Scoped_Both + /// + [Fact] + public void Binary_097_RefSafety() + { + var source = """ +ref struct R +{ + private ref readonly int _i; + public R(in int i) { _i = ref i; } +} +class Program +{ + static R F() + { + return new R(1) + new R(2); + } +} + +static class Extensions +{ + extension(R) + { + public static R operator +(scoped R x, scoped R y) => default; + } +} +"""; + CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics(); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Scoped_None + /// + [Fact] + public void Binary_098_RefSafety() + { + var source = """ +ref struct R +{ + private ref readonly int _i; + public R(in int i) { _i = ref i; } +} +class Program +{ + static R F() + { +#line 11 + return new R(1) + new R(2); + } +} + +static class Extensions +{ + extension(R) + { + public static R operator +(R x, R y) => default; + } +} +"""; + CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( + // (11,16): error CS8347: Cannot use a result of 'R.R(in int)' in this context because it may expose variables referenced by parameter 'i' outside of their declaration scope + // return new R(1) + new R(2); + Diagnostic(ErrorCode.ERR_EscapeCall, "new R(1)").WithArguments("R.R(in int)", "i").WithLocation(11, 16), + // (11,16): error CS8347: Cannot use a result of 'Extensions.extension(R).operator +(R, R)' in this context because it may expose variables referenced by parameter 'x' outside of their declaration scope + // return new R(1) + new R(2); + Diagnostic(ErrorCode.ERR_EscapeCall, "new R(1) + new R(2)").WithArguments("Extensions.extension(R).operator +(R, R)", "x").WithLocation(11, 16), + // (11,22): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference + // return new R(1) + new R(2); + Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "1").WithLocation(11, 22) + ); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedLogical + /// + [Fact] + public void Binary_099_RefSafety_Logical() + { + var text = @" +using System; +class Program +{ + static void Main() + { + } + + S1 Test() + { + S1 global = default; + S1 local = stackalloc int[100]; + + // ok + local = global && local; + local = local && local; + + // ok + global = global && global; + + // error + global = local && global; + + // error + return global || local; + } +} + +ref struct S1 +{ + public static implicit operator S1(Span o) => default; +} + +static class Extensions +{ + extension(S1) + { + public static bool operator true(S1 o) => true; + public static bool operator false(S1 o) => false; + + public static S1 operator &(S1 x, S1 y) => x; + public static S1 operator |(S1 x, S1 y) => x; + } +} +"; + CreateCompilation(text, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( + // (22,18): error CS8352: Cannot use variable 'local' in this context because it may expose referenced variables outside of their declaration scope + // global = local && global; + Diagnostic(ErrorCode.ERR_EscapeVariable, "local").WithArguments("local").WithLocation(22, 18), + // (22,18): error CS8347: Cannot use a result of 'Extensions.extension(S1).operator &(S1, S1)' in this context because it may expose variables referenced by parameter 'x' outside of their declaration scope + // global = local && global; + Diagnostic(ErrorCode.ERR_EscapeCall, "local && global").WithArguments("Extensions.extension(S1).operator &(S1, S1)", "x").WithLocation(22, 18), + // (25,16): error CS8347: Cannot use a result of 'Extensions.extension(S1).operator |(S1, S1)' in this context because it may expose variables referenced by parameter 'y' outside of their declaration scope + // return global || local; + Diagnostic(ErrorCode.ERR_EscapeCall, "global || local").WithArguments("Extensions.extension(S1).operator |(S1, S1)", "y").WithLocation(25, 16), + // (25,26): error CS8352: Cannot use variable 'local' in this context because it may expose referenced variables outside of their declaration scope + // return global || local; + Diagnostic(ErrorCode.ERR_EscapeVariable, "local").WithArguments("local").WithLocation(25, 26) + ); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedLogicalOperator_RefStruct + /// + [Fact] + public void Binary_100_RefSafety_Logical() + { + var source = """ +class C +{ + S M1(S s1, S s2) + { + S s = s1 && s2; + return s; // 1 + } + + S M2(S s1, S s2) + { + return s1 && s2; // 2 + } + + S M3(in S s1, in S s2) + { + S s = s1 && s2; + return s; + } + + S M4(scoped in S s1, in S s2) + { + S s = s1 && s2; + return s; // 3 + } + + S M5(in S s1, scoped in S s2) + { + S s = s1 && s2; + return s; // 4 + } +} + +ref struct S +{ +} + +static class Extensions +{ + extension(S) + { + public static bool operator true(in S s) => throw null; + public static bool operator false(in S s) => throw null; + public static S operator &(in S x, in S y) => throw null; + public static S operator |(in S x, in S y) => throw null; + } +} +"""; + CreateCompilation(source).VerifyDiagnostics( + // (6,16): error CS8352: Cannot use variable 's' in this context because it may expose referenced variables outside of their declaration scope + // return s; // 1 + Diagnostic(ErrorCode.ERR_EscapeVariable, "s").WithArguments("s").WithLocation(6, 16), + // (11,16): error CS8166: Cannot return a parameter by reference 's1' because it is not a ref parameter + // return s1 && s2; // 2 + Diagnostic(ErrorCode.ERR_RefReturnParameter, "s1").WithArguments("s1").WithLocation(11, 16), + // (11,16): error CS8347: Cannot use a result of 'Extensions.extension(S).operator &(in S, in S)' in this context because it may expose variables referenced by parameter 'x' outside of their declaration scope + // return s1 && s2; // 2 + Diagnostic(ErrorCode.ERR_EscapeCall, "s1 && s2").WithArguments("Extensions.extension(S).operator &(in S, in S)", "x").WithLocation(11, 16), + // (23,16): error CS8352: Cannot use variable 's' in this context because it may expose referenced variables outside of their declaration scope + // return s; // 3 + Diagnostic(ErrorCode.ERR_EscapeVariable, "s").WithArguments("s").WithLocation(23, 16), + // (29,16): error CS8352: Cannot use variable 's' in this context because it may expose referenced variables outside of their declaration scope + // return s; // 4 + Diagnostic(ErrorCode.ERR_EscapeVariable, "s").WithArguments("s").WithLocation(29, 16) + ); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedLogicalOperator_RefStruct_Scoped_Left + /// + [Fact] + public void Binary_101_RefSafety_Logical() + { + var source = """ +ref struct R +{ + private ref readonly int _i; + public R(in int i) { _i = ref i; } +} +class Program +{ + static R F() + { +#line 13 + return new R(1) || new R(2); + } + + static R F2() + { + return new R(1) | new R(2); + } +} + +static class Extensions +{ + extension(R) + { + public static bool operator true(R r) => true; + public static bool operator false(R r) => false; + public static R operator |(scoped R x, R y) => default; + } +} +"""; + CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( + // (13,16): error CS8347: Cannot use a result of 'Extensions.extension(R).operator |(scoped R, R)' in this context because it may expose variables referenced by parameter 'y' outside of their declaration scope + // return new R(1) || new R(2); + Diagnostic(ErrorCode.ERR_EscapeCall, "new R(1) || new R(2)").WithArguments("Extensions.extension(R).operator |(scoped R, R)", "y").WithLocation(13, 16), + // (13,28): error CS8347: Cannot use a result of 'R.R(in int)' in this context because it may expose variables referenced by parameter 'i' outside of their declaration scope + // return new R(1) || new R(2); + Diagnostic(ErrorCode.ERR_EscapeCall, "new R(2)").WithArguments("R.R(in int)", "i").WithLocation(13, 28), + // (13,34): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference + // return new R(1) || new R(2); + Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "2").WithLocation(13, 34), + // (18,16): error CS8347: Cannot use a result of 'Extensions.extension(R).operator |(scoped R, R)' in this context because it may expose variables referenced by parameter 'y' outside of their declaration scope + // return new R(1) | new R(2); + Diagnostic(ErrorCode.ERR_EscapeCall, "new R(1) | new R(2)").WithArguments("Extensions.extension(R).operator |(scoped R, R)", "y").WithLocation(18, 16), + // (18,27): error CS8347: Cannot use a result of 'R.R(in int)' in this context because it may expose variables referenced by parameter 'i' outside of their declaration scope + // return new R(1) | new R(2); + Diagnostic(ErrorCode.ERR_EscapeCall, "new R(2)").WithArguments("R.R(in int)", "i").WithLocation(18, 27), + // (18,33): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference + // return new R(1) | new R(2); + Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "2").WithLocation(18, 33) + ); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedLogicalOperator_RefStruct_Scoped_Right + /// + [Fact] + public void Binary_102_RefSafety_Logical() + { + var source = """ +ref struct R +{ + private ref readonly int _i; + public R(in int i) { _i = ref i; } +} +class Program +{ + static R F() + { +#line 13 + return new R(1) || new R(2); + } + + static R F2() + { + return new R(1) | new R(2); + } +} + +static class Extensions +{ + extension(R) + { + public static bool operator true(R r) => true; + public static bool operator false(R r) => false; + public static R operator |(R x, scoped R y) => default; + } +} +"""; + CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( + // (13,16): error CS8347: Cannot use a result of 'R.R(in int)' in this context because it may expose variables referenced by parameter 'i' outside of their declaration scope + // return new R(1) || new R(2); + Diagnostic(ErrorCode.ERR_EscapeCall, "new R(1)").WithArguments("R.R(in int)", "i").WithLocation(13, 16), + // (13,16): error CS8347: Cannot use a result of 'Extensions.extension(R).operator |(R, scoped R)' in this context because it may expose variables referenced by parameter 'x' outside of their declaration scope + // return new R(1) || new R(2); + Diagnostic(ErrorCode.ERR_EscapeCall, "new R(1) || new R(2)").WithArguments("Extensions.extension(R).operator |(R, scoped R)", "x").WithLocation(13, 16), + // (13,22): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference + // return new R(1) || new R(2); + Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "1").WithLocation(13, 22), + // (18,16): error CS8347: Cannot use a result of 'R.R(in int)' in this context because it may expose variables referenced by parameter 'i' outside of their declaration scope + // return new R(1) | new R(2); + Diagnostic(ErrorCode.ERR_EscapeCall, "new R(1)").WithArguments("R.R(in int)", "i").WithLocation(18, 16), + // (18,16): error CS8347: Cannot use a result of 'Extensions.extension(R).operator |(R, scoped R)' in this context because it may expose variables referenced by parameter 'x' outside of their declaration scope + // return new R(1) | new R(2); + Diagnostic(ErrorCode.ERR_EscapeCall, "new R(1) | new R(2)").WithArguments("Extensions.extension(R).operator |(R, scoped R)", "x").WithLocation(18, 16), + // (18,22): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference + // return new R(1) | new R(2); + Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "1").WithLocation(18, 22) + ); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedLogicalOperator_RefStruct_Scoped_Both + /// + [Fact] + public void Binary_103_RefSafety_Logical() + { + var source = """ +ref struct R +{ + private ref readonly int _i; + public R(in int i) { _i = ref i; } +} +class Program +{ + static R F() + { + return new R(1) || new R(2); + } + + static R F2() + { + return new R(1) | new R(2); + } +} + +static class Extensions +{ + extension(R) + { + public static bool operator true(R r) => true; + public static bool operator false(R r) => false; + public static R operator |(scoped R x, scoped R y) => default; + } +} +"""; + CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics(); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedLogicalOperator_RefStruct_Scoped_None + /// + [Fact] + public void Binary_104_RefSafety_Logical() + { + var source = """ +ref struct R +{ + private ref readonly int _i; + public R(in int i) { _i = ref i; } +} +class Program +{ + static R F() + { +#line 13 + return new R(1) || new R(2); + } + + static R F2() + { + return new R(1) | new R(2); + } +} + +static class Extensions +{ + extension(R) + { + public static bool operator true(R r) => true; + public static bool operator false(R r) => false; + public static R operator |(R x, R y) => default; + } +} +"""; + CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( + // (13,16): error CS8347: Cannot use a result of 'R.R(in int)' in this context because it may expose variables referenced by parameter 'i' outside of their declaration scope + // return new R(1) || new R(2); + Diagnostic(ErrorCode.ERR_EscapeCall, "new R(1)").WithArguments("R.R(in int)", "i").WithLocation(13, 16), + // (13,16): error CS8347: Cannot use a result of 'Extensions.extension(R).operator |(R, R)' in this context because it may expose variables referenced by parameter 'x' outside of their declaration scope + // return new R(1) || new R(2); + Diagnostic(ErrorCode.ERR_EscapeCall, "new R(1) || new R(2)").WithArguments("Extensions.extension(R).operator |(R, R)", "x").WithLocation(13, 16), + // (13,22): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference + // return new R(1) || new R(2); + Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "1").WithLocation(13, 22), + // (18,16): error CS8347: Cannot use a result of 'R.R(in int)' in this context because it may expose variables referenced by parameter 'i' outside of their declaration scope + // return new R(1) | new R(2); + Diagnostic(ErrorCode.ERR_EscapeCall, "new R(1)").WithArguments("R.R(in int)", "i").WithLocation(18, 16), + // (18,16): error CS8347: Cannot use a result of 'Extensions.extension(R).operator |(R, R)' in this context because it may expose variables referenced by parameter 'x' outside of their declaration scope + // return new R(1) | new R(2); + Diagnostic(ErrorCode.ERR_EscapeCall, "new R(1) | new R(2)").WithArguments("Extensions.extension(R).operator |(R, R)", "x").WithLocation(18, 16), + // (18,22): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference + // return new R(1) | new R(2); + Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "1").WithLocation(18, 22) + ); + } + + [Fact] + public void Binary_105_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator -(C1 x, C1 y) + { + System.Console.Write("operator1"); + return x; + } + } + + extension(C2) + { + public static C2 operator -(C2? x, C2? y) + { + System.Console.Write("operator2"); + return new C2(); + } + } +} + +public class C1 +{} + +public class C2 +{} + +class Program +{ + static void Main() + { + C1? x1 = null; + C1? x2 = null; + C1 y = new C1(); +#line 25 + _ = x1 - y; + y = y - x2; + + C2? z = null; + _ = z - z; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (25,13): warning CS8604: Possible null reference argument for parameter 'x' in 'C1 extension(C1).operator -(C1 x, C1 y)'. + // _ = x1 - y; + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "C1 extension(C1).operator -(C1 x, C1 y)").WithLocation(25, 13), + // (26,17): warning CS8604: Possible null reference argument for parameter 'y' in 'C1 extension(C1).operator -(C1 x, C1 y)'. + // y = y - x2; + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("y", "C1 extension(C1).operator -(C1 x, C1 y)").WithLocation(26, 17) + ); + } + + [Fact] + public void Binary_106_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1) + { + public static C1? operator -(C1 x, C1 y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public class C1 +{} + +class Program +{ + static void Main() + { + var x = new C1(); + C1 y = x - x; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (23,16): warning CS8600: Converting null literal or possible null value to non-nullable type. + // C1 y = x - x; + Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x - x").WithLocation(23, 16) + ); + } + + [Fact] + public void Binary_107_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(T) + { + public static T operator -(T x, T y) + { + return x; + } + } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + C2? x1 = null; + C2? x2 = null; + var y = new C2(); + (x1 - y).ToString(); + (y - x2).ToString(); + (y - y).ToString(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (24,10): warning CS8602: Dereference of a possibly null reference. + // (x1 - y).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1 - y").WithLocation(24, 10), + // (25,10): warning CS8602: Dereference of a possibly null reference. + // (y - x2).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y - x2").WithLocation(25, 10) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNodes = tree.GetRoot().DescendantNodes().OfType().ToArray(); + + Assert.Equal(3, opNodes.Length); + AssertEx.Equal("Extensions1.extension(C2?).operator -(C2?, C2?)", model.GetSymbolInfo(opNodes[0]).Symbol.ToDisplayString()); + AssertEx.Equal("Extensions1.extension(C2?).operator -(C2?, C2?)", model.GetSymbolInfo(opNodes[1]).Symbol.ToDisplayString()); + AssertEx.Equal("Extensions1.extension(C2).operator -(C2, C2)", model.GetSymbolInfo(opNodes[2]).Symbol.ToDisplayString()); + } + + [Fact] + public void Binary_108_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(T) + { + public static T operator -(int x, T y) + { + return y; + } + } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + C2? x = null; + var y = new C2(); + (1 - x).ToString(); + (1 - y).ToString(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (23,10): warning CS8602: Dereference of a possibly null reference. + // (1 - x).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "1 - x").WithLocation(23, 10) + ); + } + + [Fact] + public void Binary_109_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(T) + { + public static T operator -(T x, int y) + { + return x; + } + } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + C2? x = null; + var y = new C2(); + (x - 1).ToString(); + (y - 1).ToString(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (23,10): warning CS8602: Dereference of a possibly null reference. + // (x - 1).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x - 1").WithLocation(23, 10) + ); + } + + [Fact] + public void Binary_110_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1) where T : new() where S : new() + { + public static T operator -(C1 x, C1 y) + { + return x.F; + } + } +} + +public class C1 where T : new() +{ + public T F = new T(); +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = Get((C2?)null); + var y = Get(new C2()); + + (x - y).ToString(); + (y - x).ToString(); + } + + static C1 Get(T x) where T : new() + { + return new C1(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (29,10): warning CS8602: Dereference of a possibly null reference. + // (x - y).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x - y").WithLocation(29, 10) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNodes = tree.GetRoot().DescendantNodes().OfType().ToArray(); + + Assert.Equal(2, opNodes.Length); + AssertEx.Equal("Extensions1.extension(C1).operator -(C1, C1)", model.GetSymbolInfo(opNodes[0]).Symbol.ToDisplayString()); + AssertEx.Equal("Extensions1.extension(C1).operator -(C1, C1)", model.GetSymbolInfo(opNodes[1]).Symbol.ToDisplayString()); + } + + [Fact] + public void Binary_111_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1) where T : new() where S : new() + { + public static T operator -(C1 y, C1 x) + { + return x.F; + } + } +} + +public class C1 where T : new() +{ + public T F = new T(); +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = Get((C2?)null); + var y = Get(new C2()); + + (x - y).ToString(); + (y - x).ToString(); + } + + static C1 Get(T x) where T : new() + { + return new C1(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (30,10): warning CS8602: Dereference of a possibly null reference. + // (y - x).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y - x").WithLocation(30, 10) + ); + } + + [Fact] + public void Binary_112_NullableAnalysis_Lifted() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(S1) where T : new() + { + public static S1 operator -(S1 x, int y) + { + return x; + } + } +} + +public struct S1 where T : new() +{ + public T F; +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = Get((C2?)null) - 1; + + if (x != null) + x.Value.F.ToString(); + + var y = Get(new C2()) - 1; + + if (y != null) + y.Value.F.ToString(); + } + + static S1? Get(T x) where T : new() + { + return new S1(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (29,13): warning CS8602: Dereference of a possibly null reference. + // x.Value.F.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Value.F").WithLocation(29, 13) + ); + } + + [Fact] + public void Binary_113_NullableAnalysis_Lifted() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(S1) where T : new() + { + public static S1 operator -(int y, S1 x) + { + return x; + } + } +} + +public struct S1 where T : new() +{ + public T F; +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = 1 - Get((C2?)null); + + if (x != null) + x.Value.F.ToString(); + + var y = 1 - Get(new C2()); + + if (y != null) + y.Value.F.ToString(); + } + + static S1? Get(T x) where T : new() + { + return new S1(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (29,13): warning CS8602: Dereference of a possibly null reference. + // x.Value.F.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Value.F").WithLocation(29, 13) + ); + } + + [Fact] + public void Binary_114_NullableAnalysis_Constraints() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(T) where T : notnull + { + public static object operator -(T x, T y) + { + return x; + } + } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + C2? x = null; + var y = new C2(); + (x - y).ToString(); + (y - x).ToString(); + (y - y).ToString(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (23,10): warning CS8714: The type 'C2?' cannot be used as type parameter 'T' in the generic type or method 'Extensions1.extension(T)'. Nullability of type argument 'C2?' doesn't match 'notnull' constraint. + // (x - y).ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "x - y").WithArguments("Extensions1.extension(T)", "T", "C2?").WithLocation(23, 10), + // (24,10): warning CS8714: The type 'C2?' cannot be used as type parameter 'T' in the generic type or method 'Extensions1.extension(T)'. Nullability of type argument 'C2?' doesn't match 'notnull' constraint. + // (y - x).ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "y - x").WithArguments("Extensions1.extension(T)", "T", "C2?").WithLocation(24, 10) + ); + } + + [Fact] + public void Binary_115_NullableAnalysis_Constraints() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1) where T : notnull, new() where S : notnull, new() + { + public static T operator -(C1 x, C1 y) + { + return x.F; + } + } +} + +public class C1 where T : new() +{ + public T F = new T(); +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = Get((C2?)null); + var y = Get(new C2()); + (x - y).ToString(); + (y - x).ToString(); + (y - y).ToString(); + } + + static C1 Get(T x) where T : new() + { + return new C1(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (28,10): warning CS8714: The type 'C2?' cannot be used as type parameter 'T' in the generic type or method 'Extensions1.extension(C1)'. Nullability of type argument 'C2?' doesn't match 'notnull' constraint. + // (x - y).ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "x - y").WithArguments("Extensions1.extension(C1)", "T", "C2?").WithLocation(28, 10), + // (28,10): warning CS8602: Dereference of a possibly null reference. + // (x - y).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x - y").WithLocation(28, 10), + // (29,10): warning CS8714: The type 'C2?' cannot be used as type parameter 'S' in the generic type or method 'Extensions1.extension(C1)'. Nullability of type argument 'C2?' doesn't match 'notnull' constraint. + // (y - x).ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "y - x").WithArguments("Extensions1.extension(C1)", "S", "C2?").WithLocation(29, 10) + ); + } + + [Fact] + public void Binary_116_NullableAnalysis_Logical() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator &(C1 x, C1 y) + { + System.Console.Write("operator1"); + return x; + } + + public static bool operator true(C1 x) => true; + public static bool operator false(C1 x) => false; + } + + extension(C2) + { + public static C2 operator &(C2? x, C2? y) + { + System.Console.Write("operator1"); + return new C2(); + } + + public static bool operator true(C2? x) => true; + public static bool operator false(C2? x) => false; + } +} + +public class C1 +{} + +public class C2 +{} + +class Program +{ + static void Main() + { + C1? x1 = null; + C1? x2 = null; + C1 y = new C1(); +#line 28 + _ = x1 && y; + y = y && x2; + + C2? z = null; + _ = z && z; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (28,13): warning CS8604: Possible null reference argument for parameter 'x' in 'bool extension(C1).operator false(C1 x)'. + // _ = x1 && y; + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "bool extension(C1).operator false(C1 x)").WithLocation(28, 13), + // (28,13): warning CS8604: Possible null reference argument for parameter 'x' in 'C1 extension(C1).operator &(C1 x, C1 y)'. + // _ = x1 && y; + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "C1 extension(C1).operator &(C1 x, C1 y)").WithLocation(28, 13), + // (29,18): warning CS8604: Possible null reference argument for parameter 'y' in 'C1 extension(C1).operator &(C1 x, C1 y)'. + // y = y && x2; + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("y", "C1 extension(C1).operator &(C1 x, C1 y)").WithLocation(29, 18) + ); + } + + [Fact] + public void Binary_117_NullableAnalysis_Logical() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1) + { + public static C1? operator &(C1 x, C1 y) + { + System.Console.Write("operator1"); + return x; + } + + public static bool operator true(C1 x) => true; + public static bool operator false(C1 x) => false; + } +} + +public class C1 +{} + +class Program +{ + static void Main() + { + var x = new C1(); + C1 y = x && x; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (26,16): warning CS8600: Converting null literal or possible null value to non-nullable type. + // C1 y = x && x; + Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x && x").WithLocation(26, 16) + ); + } + + [Fact] + [WorkItem("https://github.com/dotnet/roslyn/issues/29605")] + public void Binary_118_NullableAnalysis_Logical() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(T) + { + public static T operator &(T x, T y) + { + return x; + } + + public static bool operator true(T x) => true; + public static bool operator false(T x) => false; + } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + C2? x1 = null; + C2? x2 = null; + var y = new C2(); + (x1 && y).ToString(); + (y && x2).ToString(); + (y && y).ToString(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + + comp.VerifyDiagnostics( + // (27,10): warning CS8602: Dereference of a possibly null reference. + // (x1 && y).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1 && y").WithLocation(27, 10), + // (28,10): warning CS8602: Dereference of a possibly null reference. + // (y && x2).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y && x2").WithLocation(28, 10) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNodes = tree.GetRoot().DescendantNodes().OfType().ToArray(); + + Assert.Equal(3, opNodes.Length); + AssertEx.Equal("Extensions1.extension(C2?).operator &(C2?, C2?)", model.GetSymbolInfo(opNodes[0]).Symbol.ToDisplayString()); + AssertEx.Equal("Extensions1.extension(C2?).operator &(C2?, C2?)", model.GetSymbolInfo(opNodes[1]).Symbol.ToDisplayString()); + AssertEx.Equal("Extensions1.extension(C2).operator &(C2, C2)", model.GetSymbolInfo(opNodes[2]).Symbol.ToDisplayString()); + } + + [Fact] + public void Binary_119_NullableAnalysis_Logical() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator &(C1 x, C1 y) + { + return x; + } + + public static bool operator true(C1 x) => true; + public static bool operator false(C1 x) => false; + } +} + +public interface C1 +{ + public T F { get; } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = Get((C2?)null); + var y = Get(new C2()); + + (x && y).F.ToString(); + (y && x).F.ToString(); + + var z = Get((C2?)null); + (y && z).F.ToString(); + (y && y).F.ToString(); + } + + static C1 Get(T x) + { + throw null!; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (32,9): warning CS8602: Dereference of a possibly null reference. + // (x && y).F.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(x && y).F").WithLocation(32, 9), + // (33,9): warning CS8602: Dereference of a possibly null reference. + // (y && x).F.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(y && x).F").WithLocation(33, 9), + // (36,9): warning CS8602: Dereference of a possibly null reference. + // (y && z).F.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(y && z).F").WithLocation(36, 9) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNodes = tree.GetRoot().DescendantNodes().OfType().ToArray(); + + Assert.Equal(4, opNodes.Length); + AssertEx.Equal("Extensions1.extension(C1).operator &(C1, C1)", model.GetSymbolInfo(opNodes[0]).Symbol.ToDisplayString()); + AssertEx.Equal("Extensions1.extension(C1).operator &(C1, C1)", model.GetSymbolInfo(opNodes[1]).Symbol.ToDisplayString()); + AssertEx.Equal("Extensions1.extension(C1).operator &(C1, C1)", model.GetSymbolInfo(opNodes[2]).Symbol.ToDisplayString()); + AssertEx.Equal("Extensions1.extension(C1).operator &(C1, C1)", model.GetSymbolInfo(opNodes[3]).Symbol.ToDisplayString()); + } + + [Fact] + public void Binary_120_NullableAnalysis_Logical() + { + var src = $$$""" +#nullable enable + +public interface C1 +{ + public T F { get; } + + public static C1 operator &(C1 x, C1 y) + { + return x; + } + + public static bool operator true(C1 x) => true; + public static bool operator false(C1 x) => false; +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = Get((C2?)null); + var y = Get(new C2()); + + (x && y).F.ToString(); + (y && x).F.ToString(); + + var z = Get((C2?)null); + (y && z).F.ToString(); + (y && y).F.ToString(); + } + + static C1 Get(T x) + { + throw null!; + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (26,9): warning CS8602: Dereference of a possibly null reference. + // (x && y).F.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(x && y).F").WithLocation(26, 9), + // (27,15): warning CS8620: Argument of type 'C1' cannot be used for parameter 'y' of type 'C1' in 'C1 C1.operator &(C1 x, C1 y)' due to differences in the nullability of reference types. + // (y && x).F.ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("C1", "C1", "y", "C1 C1.operator &(C1 x, C1 y)").WithLocation(27, 15), + // (30,15): warning CS8620: Argument of type 'C1' cannot be used for parameter 'y' of type 'C1' in 'C1 C1.operator &(C1 x, C1 y)' due to differences in the nullability of reference types. + // (y && z).F.ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("C1", "C1", "y", "C1 C1.operator &(C1 x, C1 y)").WithLocation(30, 15) + ); + } + + [Fact] + [WorkItem("https://github.com/dotnet/roslyn/issues/29605")] + public void Binary_121_NullableAnalysis_Logical_Lifted() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(S1) where T : new() + { + public static S1 operator &(S1 x, S1 y) + { + return x; + } + } + + extension(S1?) where T : new() + { + public static bool operator true(S1? x) => true; + public static bool operator false(S1? x) => false; + } +} + +public struct S1 where T : new() +{ + public T F; +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = Get((C2?)null); + var x1 = x && x; + + if (x1 != null) + x1.Value.F.ToString(); + + var y = Get(new C2()); + var y1 = y && y; + + if (y1 != null) + y1.Value.F.ToString(); + } + + static S1? Get(T x) where T : new() + { + return new S1(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + + comp.VerifyDiagnostics( + // (36,13): warning CS8602: Dereference of a possibly null reference. + // x1.Value.F.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1.Value.F").WithLocation(36, 13) + ); + } + + [Fact] + [WorkItem("https://github.com/dotnet/roslyn/issues/29605")] + public void Binary_122_NullableAnalysis_Logical_Lifted() + { + var src = $$$""" +#nullable enable + +public struct S1 where T : new() +{ + public T F; + + public static S1 operator &(S1 x, S1 y) + { + return x; + } + + public static bool operator true(S1? x) => true; + public static bool operator false(S1? x) => false; +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = Get((C2?)null); + var x1 = x && x; + + if (x1 != null) + x1.Value.F.ToString(); + + var y = Get(new C2()); + var y1 = y && y; + + if (y1 != null) + y1.Value.F.ToString(); + } + + static S1? Get(T x) where T : new() + { + return new S1(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + + comp.VerifyDiagnostics( + // (27,13): warning CS8602: Dereference of a possibly null reference. + // x1.Value.F.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1.Value.F").WithLocation(27, 13) + ); + } + + [Fact] + [WorkItem("https://github.com/dotnet/roslyn/issues/29605")] + public void Binary_123_NullableAnalysis_Logical_Constraints() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(T) where T : notnull + { + public static T operator &(T x, T y) + { + return x; + } + } + + extension(T) + { + public static bool operator true(T x) => true; + public static bool operator false(T x) => false; + } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + C2? x = null; + var y = new C2(); + (x && y).ToString(); + (y && x).ToString(); + (y && y).ToString(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + + comp.VerifyDiagnostics( + // (29,10): warning CS8714: The type 'C2?' cannot be used as type parameter 'T' in the generic type or method 'Extensions1.extension(T)'. Nullability of type argument 'C2?' doesn't match 'notnull' constraint. + // (x && y).ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "x && y").WithArguments("Extensions1.extension(T)", "T", "C2?").WithLocation(29, 10), + // (29,10): warning CS8602: Dereference of a possibly null reference. + // (x && y).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x && y").WithLocation(29, 10), + // (30,10): warning CS8714: The type 'C2?' cannot be used as type parameter 'T' in the generic type or method 'Extensions1.extension(T)'. Nullability of type argument 'C2?' doesn't match 'notnull' constraint. + // (y && x).ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "y && x").WithArguments("Extensions1.extension(T)", "T", "C2?").WithLocation(30, 10), + // (30,10): warning CS8602: Dereference of a possibly null reference. + // (y && x).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y && x").WithLocation(30, 10) + ); + } + + [Fact] + [WorkItem("https://github.com/dotnet/roslyn/issues/29605")] + public void Binary_124_NullableAnalysis_Logical_Constraints() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(T) + { + public static T operator &(T x, T y) + { + return x; + } + } + + extension(T) where T : notnull + { + public static bool operator true(T x) => true; + public static bool operator false(T x) => false; + } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + C2? x = null; + var y = new C2(); + (x && y).ToString(); + (y && x).ToString(); + (y && y).ToString(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + + comp.VerifyDiagnostics( + // (29,10): warning CS8714: The type 'C2?' cannot be used as type parameter 'T' in the generic type or method 'Extensions1.extension(T)'. Nullability of type argument 'C2?' doesn't match 'notnull' constraint. + // (x && y).ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "x").WithArguments("Extensions1.extension(T)", "T", "C2?").WithLocation(29, 10), + // (29,10): warning CS8602: Dereference of a possibly null reference. + // (x && y).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x && y").WithLocation(29, 10), + // (30,10): warning CS8602: Dereference of a possibly null reference. + // (y && x).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y && x").WithLocation(30, 10) + ); + } + + [Fact] + public void Binary_125_NullableAnalysis_Logical_Constraints() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1) where T : notnull + { + public static C1 operator &(C1 x, C1 y) + { + return x; + } + + public static bool operator true(C1 x) => true; + public static bool operator false(C1 x) => false; + } +} + +public interface C1 +{ + public T F { get; } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = Get((C2?)null); + var y = Get(new C2()); + (x && y).F.ToString(); + (y && x).F.ToString(); + (y && y).F.ToString(); + } + + static C1 Get(T x) + { + throw null!; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (31,9): warning CS8602: Dereference of a possibly null reference. + // (x && y).F.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(x && y).F").WithLocation(31, 9), + // (31,10): warning CS8714: The type 'C2?' cannot be used as type parameter 'T' in the generic type or method 'Extensions1.extension(C1)'. Nullability of type argument 'C2?' doesn't match 'notnull' constraint. + // (x && y).F.ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "x && y").WithArguments("Extensions1.extension(C1)", "T", "C2?").WithLocation(31, 10), + // (31,10): warning CS8714: The type 'C2?' cannot be used as type parameter 'T' in the generic type or method 'Extensions1.extension(C1)'. Nullability of type argument 'C2?' doesn't match 'notnull' constraint. + // (x && y).F.ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "x").WithArguments("Extensions1.extension(C1)", "T", "C2?").WithLocation(31, 10), + // (32,9): warning CS8602: Dereference of a possibly null reference. + // (y && x).F.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(y && x).F").WithLocation(32, 9), + // (32,10): warning CS8714: The type 'C2?' cannot be used as type parameter 'T' in the generic type or method 'Extensions1.extension(C1)'. Nullability of type argument 'C2?' doesn't match 'notnull' constraint. + // (y && x).F.ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "y && x").WithArguments("Extensions1.extension(C1)", "T", "C2?").WithLocation(32, 10), + // (32,10): warning CS8714: The type 'C2?' cannot be used as type parameter 'T' in the generic type or method 'Extensions1.extension(C1)'. Nullability of type argument 'C2?' doesn't match 'notnull' constraint. + // (y && x).F.ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "y").WithArguments("Extensions1.extension(C1)", "T", "C2?").WithLocation(32, 10) + ); + } + + [Fact] + public void Binary_126_NullableAnalysis_Logical_Constraints() + { + var src = $$$""" +#nullable enable + +public interface C1 where T : notnull +{ + public T F { get; } + + public static C1 operator &(C1 x, C1 y) + { + return x; + } + + public static bool operator true(C1 x) => true; + public static bool operator false(C1 x) => false; +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = Get((C2?)null); + var y = Get(new C2()); + (x && y).F.ToString(); + (y && x).F.ToString(); + (y && y).F.ToString(); + } + + static C1 Get(T x) where T : notnull + { + throw null!; + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (23,17): warning CS8714: The type 'C2?' cannot be used as type parameter 'T' in the generic type or method 'Program.Get(T)'. Nullability of type argument 'C2?' doesn't match 'notnull' constraint. + // var x = Get((C2?)null); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "Get").WithArguments("Program.Get(T)", "T", "C2?").WithLocation(23, 17), + // (25,10): warning CS8620: Argument of type 'C1' cannot be used for parameter 'x' of type 'C1' in 'C1 C1.operator &(C1 x, C1 y)' due to differences in the nullability of reference types. + // (x && y).F.ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("C1", "C1", "x", "C1 C1.operator &(C1 x, C1 y)").WithLocation(25, 10), + // (26,15): warning CS8620: Argument of type 'C1' cannot be used for parameter 'y' of type 'C1' in 'C1 C1.operator &(C1 x, C1 y)' due to differences in the nullability of reference types. + // (y && x).F.ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("C1", "C1", "y", "C1 C1.operator &(C1 x, C1 y)").WithLocation(26, 15) + ); + } + + [Fact] + [WorkItem("https://github.com/dotnet/roslyn/issues/78828")] + public void Binary_127_NullableAnalysis_WithLambda() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(T) + { + public static T operator -(T x, System.Func y) + { + return x; + } + } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + C2? x1 = null; + var y = new C2(); + (y - (() => x1)).ToString(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + + // https://github.com/dotnet/roslyn/issues/78828: Expect to infer T as C2? and get a null dereference warning. + comp.VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNodes = tree.GetRoot().DescendantNodes().OfType().ToArray(); + + Assert.Equal(1, opNodes.Length); + AssertEx.Equal("Extensions1.extension(C2).operator -(C2, System.Func)", model.GetSymbolInfo(opNodes[0]).Symbol.ToDisplayString()); + } + + [Fact] + public void Binary_128_NullableAnalysis_Logical_Chained() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(T) + { + public static T operator &(T x, T y) + { + return x; + } + + public static bool operator true(T x) => true; + public static bool operator false(T x) => false; + } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + C2? x1 = null; + var y = new C2(); + (x1 && y && y && y && y && y).ToString(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + + comp.VerifyDiagnostics( + // (26,10): warning CS8602: Dereference of a possibly null reference. + // (x1 && y && y && y && y && y).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1 && y && y && y && y && y").WithLocation(26, 10) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNodes = tree.GetRoot().DescendantNodes().OfType().ToArray(); + + Assert.Equal(5, opNodes.Length); + AssertEx.Equal("Extensions1.extension(C2?).operator &(C2?, C2?)", model.GetSymbolInfo(opNodes[0]).Symbol.ToDisplayString()); + AssertEx.Equal("Extensions1.extension(C2?).operator &(C2?, C2?)", model.GetSymbolInfo(opNodes[1]).Symbol.ToDisplayString()); + AssertEx.Equal("Extensions1.extension(C2?).operator &(C2?, C2?)", model.GetSymbolInfo(opNodes[2]).Symbol.ToDisplayString()); + AssertEx.Equal("Extensions1.extension(C2?).operator &(C2?, C2?)", model.GetSymbolInfo(opNodes[3]).Symbol.ToDisplayString()); + AssertEx.Equal("Extensions1.extension(C2?).operator &(C2?, C2?)", model.GetSymbolInfo(opNodes[4]).Symbol.ToDisplayString()); + } + + [Fact] + public void Binary_129_Declaration_Extern() + { + var src = $$$""" +using System.Runtime.InteropServices; + +public static class Extensions1 +{ + extension(C2) + { + extern public static C2 operator -(C2 x, C2 y) => x; + + [DllImport("something.dll")] + public static C2 operator +(C2 x, C2 y) => x; + } +} + +public class C2 +{} +"""; + + var comp = CreateCompilation(src); + comp.VerifyDiagnostics( + // (7,42): error CS0179: 'Extensions1.extension(C2).operator -(C2, C2)' cannot be extern and declare a body + // extern public static C2 operator -(C2 x, C2 y) => x; + Diagnostic(ErrorCode.ERR_ExternHasBody, "-").WithArguments("Extensions1.extension(C2).operator -(C2, C2)").WithLocation(7, 42), + // (9,10): error CS0601: The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member + // [DllImport("something.dll")] + Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(9, 10) + ); + } + + [Fact] + public void Binary_130_Declaration_Extern() + { + var source = """ +using System.Runtime.InteropServices; +static class E +{ + extension(C2) + { + [DllImport("something.dll")] + extern public static C2 operator -(C2 x, C2 y); + } +} + +public class C2 +{} +"""; + var verifier = CompileAndVerify(source).VerifyDiagnostics(); + + verifier.VerifyTypeIL("E", """ +.class private auto ansi abstract sealed beforefieldinit E + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( + 01 00 00 00 + ) + // Nested Types + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + // Methods + .method private hidebysig specialname static + void '$' ( + class C2 '' + ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( + 01 00 00 00 + ) + // Method begins at RVA 0x206f + // Code size 1 (0x1) + .maxstack 8 + IL_0000: ret + } // end of method '<>E__0'::'$' + .method public hidebysig specialname static + class C2 op_Subtraction ( + class C2 x, + class C2 y + ) cil managed + { + // Method begins at RVA 0x2071 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::op_Subtraction + } // end of class <>E__0 + // Methods + .method public hidebysig static pinvokeimpl("something.dll" winapi) + class C2 op_Subtraction ( + class C2 x, + class C2 y + ) cil managed preservesig + { + } // end of method E::op_Subtraction +} // end of class E +""".Replace("[mscorlib]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[mscorlib]")); + } + + [Fact] + public void Binary_131_Declaration_Extern() + { + var source = """ +static class E +{ + extension(C2) + { + extern public static C2 operator -(C2 x, C2 y); + } +} + +public class C2 +{} +"""; + var verifier = CompileAndVerify(source, verify: Verification.FailsPEVerify with { PEVerifyMessage = """ + Error: Method marked Abstract, Runtime, InternalCall or Imported must have zero RVA, and vice versa. + Type load failed. + """ }); + + verifier.VerifyDiagnostics( + // (5,42): warning CS0626: Method, operator, or accessor 'E.extension(C2).operator -(C2, C2)' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. + // extern public static C2 operator -(C2 x, C2 y); + Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "-").WithArguments("E.extension(C2).operator -(C2, C2)").WithLocation(5, 42) + ); + + verifier.VerifyTypeIL("E", """ +.class private auto ansi abstract sealed beforefieldinit E + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( + 01 00 00 00 + ) + // Nested Types + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + // Methods + .method private hidebysig specialname static + void '$' ( + class C2 '' + ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( + 01 00 00 00 + ) + // Method begins at RVA 0x206f + // Code size 1 (0x1) + .maxstack 8 + IL_0000: ret + } // end of method '<>E__0'::'$' + .method public hidebysig specialname static + class C2 op_Subtraction ( + class C2 x, + class C2 y + ) cil managed + { + // Method begins at RVA 0x2071 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::op_Subtraction + } // end of class <>E__0 + // Methods + .method public hidebysig static + class C2 op_Subtraction ( + class C2 x, + class C2 y + ) cil managed + { + } // end of method E::op_Subtraction +} // end of class E +""".Replace("[mscorlib]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[mscorlib]")); + } + + [Fact] + public void Binary_132_Declaration_Extern() + { + var source = """ +static class E +{ + extension(C2) + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)] + extern public static C2 operator -(C2 x, C2 y); + } +} + +public class C2 +{} +"""; + var verifier = CompileAndVerify(source).VerifyDiagnostics(); + + verifier.VerifyTypeIL("E", """ +.class private auto ansi abstract sealed beforefieldinit E + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( + 01 00 00 00 + ) + // Nested Types + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + // Methods + .method private hidebysig specialname static + void '$' ( + class C2 '' + ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( + 01 00 00 00 + ) + // Method begins at RVA 0x206f + // Code size 1 (0x1) + .maxstack 8 + IL_0000: ret + } // end of method '<>E__0'::'$' + .method public hidebysig specialname static + class C2 op_Subtraction ( + class C2 x, + class C2 y + ) cil managed + { + // Method begins at RVA 0x2071 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::op_Subtraction + } // end of class <>E__0 + // Methods + .method public hidebysig static + class C2 op_Subtraction ( + class C2 x, + class C2 y + ) cil managed internalcall + { + } // end of method E::op_Subtraction +} // end of class E +""".Replace("[mscorlib]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[mscorlib]")); + } + + [Theory] + [CombinatorialData] + public void Binary_133_Consumption_TupleComparison(bool fromMetadata) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static bool operator ==(S1 x, S1 y) + { + System.Console.Write("operator1"); + return x.F == y.F; + } + + public static bool operator !=(S1 x, S1 y) + { + System.Console.Write("operator2"); + return x.F != y.F; + } + } + + extension((S1, int)) + { + public static bool operator ==((S1, int) x, (S1, int) y) => throw null; + public static bool operator !=((S1, int) x, (S1, int) y) => throw null; + } +} + +public struct S1 +{ + public int F; +} +"""; + + var src2 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1() { F = 101 }; + var s2 = new S1() { F = 202 }; + + if ((s1, 1) == (s1, 1)) + { + System.Console.Write(": =="); + } + + System.Console.Write(":"); + + if ((s1, 1) == (s2, 1)) + {} + else + { + System.Console.Write(": !="); + } + + System.Console.Write(":"); + + if ((s1, 1) != (s1, 1)) + {} + else + { + System.Console.Write(": =="); + } + + System.Console.Write(":"); + + if ((s1, 1) != (s2, 1)) + { + System.Console.Write(": !="); + } + } +} +"""; + + var comp1 = CreateCompilation(src1); + var comp1Ref = fromMetadata ? comp1.EmitToImageReference() : comp1.ToMetadataReference(); + + var comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp2, expectedOutput: "operator1: ==:operator1: !=:operator2: ==:operator2: !=").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: "operator1: ==:operator1: !=:operator2: ==:operator2: !=").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (8,13): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // if ((s1, 1) == (s1, 1)) + Diagnostic(ErrorCode.ERR_FeatureInPreview, "(s1, 1) == (s1, 1)").WithArguments("extensions").WithLocation(8, 13), + // (15,13): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // if ((s1, 1) == (s2, 1)) + Diagnostic(ErrorCode.ERR_FeatureInPreview, "(s1, 1) == (s2, 1)").WithArguments("extensions").WithLocation(15, 13), + // (24,13): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // if ((s1, 1) != (s1, 1)) + Diagnostic(ErrorCode.ERR_FeatureInPreview, "(s1, 1) != (s1, 1)").WithArguments("extensions").WithLocation(24, 13), + // (33,13): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // if ((s1, 1) != (s2, 1)) + Diagnostic(ErrorCode.ERR_FeatureInPreview, "(s1, 1) != (s2, 1)").WithArguments("extensions").WithLocation(33, 13) + ); + + var src3 = $$$""" +public static class Extensions1 +{ + extension((S1, int)) + { + public static bool operator ==((S1, int) x, (S1, int) y) => throw null; + public static bool operator !=((S1, int) x, (S1, int) y) => throw null; + } +} + +public struct S1 +{ + public int F; +} +"""; + + var comp3 = CreateCompilation(src3); + var comp3Ref = fromMetadata ? comp3.EmitToImageReference() : comp3.ToMetadataReference(); + + var comp4 = CreateCompilation(src2, references: [comp3Ref], options: TestOptions.DebugExe); + comp4.VerifyDiagnostics( + // (8,13): error CS0019: Operator '==' cannot be applied to operands of type 'S1' and 'S1' + // if ((s1, 1) == (s1, 1)) + Diagnostic(ErrorCode.ERR_BadBinaryOps, "(s1, 1) == (s1, 1)").WithArguments("==", "S1", "S1").WithLocation(8, 13), + // (15,13): error CS0019: Operator '==' cannot be applied to operands of type 'S1' and 'S1' + // if ((s1, 1) == (s2, 1)) + Diagnostic(ErrorCode.ERR_BadBinaryOps, "(s1, 1) == (s2, 1)").WithArguments("==", "S1", "S1").WithLocation(15, 13), + // (24,13): error CS0019: Operator '!=' cannot be applied to operands of type 'S1' and 'S1' + // if ((s1, 1) != (s1, 1)) + Diagnostic(ErrorCode.ERR_BadBinaryOps, "(s1, 1) != (s1, 1)").WithArguments("!=", "S1", "S1").WithLocation(24, 13), + // (33,13): error CS0019: Operator '!=' cannot be applied to operands of type 'S1' and 'S1' + // if ((s1, 1) != (s2, 1)) + Diagnostic(ErrorCode.ERR_BadBinaryOps, "(s1, 1) != (s2, 1)").WithArguments("!=", "S1", "S1").WithLocation(33, 13) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_134_Consumption_ReferenceTypeEquality_UnrelatedTypes(bool fromMetadata, [CombinatorialValues("==", "!=")] string op) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator {{{op}}}(C1 x, C2 y) + { + System.Console.Write("operator1:"); + System.Console.Write(x.F); + System.Console.Write(":"); + System.Console.Write(y.F); + return new C1 { F = x.F + y.F }; + } + + public static C1 operator {{{op switch { "==" => "!=", "!=" => "==", _ => throw ExceptionUtilities.UnexpectedValue(op) }}}}(C1 x, C2 y) => throw null; + } +} + +public class C1 +{ + public int F; +} + +public class C2 +{ + public int F; +} +"""; + + var src2 = $$$""" +class Program +{ + static void Main() + { + var s11 = new C1() { F = 101 }; + var s12 = new C2() { F = 202 }; + var s2 = s11 {{{op}}} s12; + System.Console.Write(":"); + System.Console.Write(s11.F); + System.Console.Write(":"); + System.Console.Write(s12.F); + System.Console.Write(":"); + System.Console.Write(s2.F); + } +} +"""; + + var comp1 = CreateCompilation(src1); + var comp1Ref = fromMetadata ? comp1.EmitToImageReference() : comp1.ToMetadataReference(); + + var comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp2, expectedOutput: "operator1:101:202:101:202:303").VerifyDiagnostics(); + + var tree = comp2.SyntaxTrees.First(); + var model = comp2.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("Extensions1.extension(C1).operator " + op + "(C1, C2)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("C1", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: "operator1:101:202:101:202:303").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (7,18): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // var s2 = s11 + s12; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s11 " + op + " s12").WithArguments("extensions").WithLocation(7, 18) + ); + + var opName = BinaryOperatorName(op); + var src3 = $$$""" +class Program +{ + static void Main() + { + var s1 = new C1(); + var s2 = new C2(); + Extensions1.{{{opName}}}(s1, s2); + } +} +"""; + var comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp3, expectedOutput: "operator1:0:0").VerifyDiagnostics(); + + comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp3, expectedOutput: "operator1:0:0").VerifyDiagnostics(); + + comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + CompileAndVerify(comp3, expectedOutput: "operator1:0:0").VerifyDiagnostics(); + + var src4 = $$$""" +class Program +{ + static void Main() + { + var s1 = new C1(); + var s2 = new C2(); +#line 6 + s1.{{{opName}}}(s1); + C1.{{{opName}}}(s1, s2); + } +} +"""; + var comp4 = CreateCompilation(src4, references: [comp1Ref]); + comp4.VerifyEmitDiagnostics( + // (6,12): error CS1061: 'S1' does not contain a definition for 'op_Addition' and no accessible extension method 'op_Addition' accepting a first argument of type 'S1' could be found (are you missing a using directive or an assembly reference?) + // s1.op_Addition(s1); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, opName).WithArguments("C1", opName).WithLocation(6, 12), + // (7,12): error CS0117: 'S1' does not contain a definition for 'op_Addition' + // C1.op_Addition(s1, s1); + Diagnostic(ErrorCode.ERR_NoSuchMember, opName).WithArguments("C1", opName).WithLocation(7, 12) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_135_Consumption_ReferenceTypeEquality_UnrelatedTypes(bool fromMetadata, [CombinatorialValues("==", "!=")] string op) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator {{{op}}}(C1 x, C1 y) + { + System.Console.Write("operator1:"); + System.Console.Write(x.F); + System.Console.Write(":"); + System.Console.Write(y.F); + return new C1 { F = x.F + y.F }; + } + + public static C1 operator {{{op switch { "==" => "!=", "!=" => "==", _ => throw ExceptionUtilities.UnexpectedValue(op) }}}}(C1 x, C1 y) => throw null; + } +} + +public class C1 +{ + public int F; +} + +public class C2 +{ + public int F; + + public static implicit operator C1(C2 x) => new C1 { F = x.F }; +} +"""; + + var src2 = $$$""" +class Program +{ + static void Main() + { + var s11 = new C1() { F = 101 }; + var s12 = new C2() { F = 202 }; + var s2 = s11 {{{op}}} s12; + System.Console.Write(":"); + System.Console.Write(s11.F); + System.Console.Write(":"); + System.Console.Write(s12.F); + System.Console.Write(":"); + System.Console.Write(s2.F); + } +} +"""; + + var comp1 = CreateCompilation(src1); + var comp1Ref = fromMetadata ? comp1.EmitToImageReference() : comp1.ToMetadataReference(); + + var comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp2, expectedOutput: "operator1:101:202:101:202:303").VerifyDiagnostics(); + + var tree = comp2.SyntaxTrees.First(); + var model = comp2.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("Extensions1.extension(C1).operator " + op + "(C1, C1)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("C1", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: "operator1:101:202:101:202:303").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (7,18): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // var s2 = s11 + s12; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s11 " + op + " s12").WithArguments("extensions").WithLocation(7, 18) + ); + + var opName = BinaryOperatorName(op); + var src3 = $$$""" +class Program +{ + static void Main() + { + var s1 = new C1(); + var s2 = new C2(); + Extensions1.{{{opName}}}(s1, s2); + } +} +"""; + var comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp3, expectedOutput: "operator1:0:0").VerifyDiagnostics(); + + comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp3, expectedOutput: "operator1:0:0").VerifyDiagnostics(); + + comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + CompileAndVerify(comp3, expectedOutput: "operator1:0:0").VerifyDiagnostics(); + + var src4 = $$$""" +class Program +{ + static void Main() + { + var s1 = new C1(); + var s2 = new C2(); +#line 6 + s1.{{{opName}}}(s1); + C1.{{{opName}}}(s1, s2); + } +} +"""; + var comp4 = CreateCompilation(src4, references: [comp1Ref]); + comp4.VerifyEmitDiagnostics( + // (6,12): error CS1061: 'S1' does not contain a definition for 'op_Addition' and no accessible extension method 'op_Addition' accepting a first argument of type 'S1' could be found (are you missing a using directive or an assembly reference?) + // s1.op_Addition(s1); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, opName).WithArguments("C1", opName).WithLocation(6, 12), + // (7,12): error CS0117: 'S1' does not contain a definition for 'op_Addition' + // C1.op_Addition(s1, s1); + Diagnostic(ErrorCode.ERR_NoSuchMember, opName).WithArguments("C1", opName).WithLocation(7, 12) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_136_Consumption_ReferenceTypeEquality_RelatedTypes([CombinatorialValues("==", "!=")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator {{{op}}}(C1 x, C2 y) => throw null; + public static C1 operator {{{op switch { "==" => "!=", "!=" => "==", _ => throw ExceptionUtilities.UnexpectedValue(op) }}}}(C1 x, C2 y) => throw null; + } +} + +public class C1 +{ +} + +public class C2 : C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + var c2 = new C2(); + var c3 = c1; + System.Console.Write(c1 {{{op}}} c2); + System.Console.Write(c1 {{{op}}} c3); + } +} +"""; + + var comp2 = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp2, expectedOutput: op == "==" ? "FalseTrue" : "TrueFalse").VerifyDiagnostics(); + + var tree = comp2.SyntaxTrees.First(); + var model = comp2.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("object.operator " + op + "(object, object)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("System.Boolean", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Theory] + [CombinatorialData] + public void Binary_137_Consumption_ReferenceTypeEquality_RelatedTypes([CombinatorialValues("==", "!=")] string op) + { + var src = $$$""" +#pragma warning disable CS0660 // 'C1' defines operator == or operator != but does not override Object.Equals(object o) +#pragma warning disable CS0661 // 'C1' defines operator == or operator != but does not override Object.GetHashCode() + +public class C1 +{ + public int F; + + public static C1 operator {{{op}}}(C1 x, C2 y) + { + System.Console.Write("operator1:"); + System.Console.Write(x.F); + System.Console.Write(":"); + System.Console.Write(y.F); + return new C1 { F = x.F + y.F }; + } + + public static C1 operator {{{op switch { "==" => "!=", "!=" => "==", _ => throw ExceptionUtilities.UnexpectedValue(op) }}}}(C1 x, C2 y) => throw null; +} + +public class C2 : C1; + +class Program +{ + static void Main() + { + var s11 = new C1() { F = 101 }; + var s12 = new C2() { F = 202 }; + var s2 = s11 {{{op}}} s12; + System.Console.Write(":"); + System.Console.Write(s11.F); + System.Console.Write(":"); + System.Console.Write(s12.F); + System.Console.Write(":"); + System.Console.Write(s2.F); + } +} +"""; + + var comp2 = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp2, expectedOutput: "operator1:101:202:101:202:303").VerifyDiagnostics(); + + var tree = comp2.SyntaxTrees.First(); + var model = comp2.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().Where(a => a.Kind() != SyntaxKind.AddExpression).First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + AssertEx.Equal("C1.operator " + op + "(C1, C2)", symbolInfo.Symbol.ToDisplayString()); + } + + [Theory] + [CombinatorialData] + public void Binary_138_Consumption_TypeParameterEquality([CombinatorialValues("==", "!=")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(T) where T : I1 + { + public static bool operator {{{op}}}(T x, T y) + { + System.Console.Write("operator1:"); + return x.F.Equals(y.F); + } + + public static bool operator {{{op switch { "==" => "!=", "!=" => "==", _ => throw ExceptionUtilities.UnexpectedValue(op) }}}}(T x, T y) => throw null; + } +} + +public interface I1 +{ + public int F {get;} +} + +public class C1 : I1 +{ + public int F {get; set;} +} + +class Program +{ + static void Main() + { + var s1 = new C1() { F = 101 }; + var s2 = new C1() { F = 202 }; + var s3 = new C1() { F = 101 }; + Compare(s1, s2); + System.Console.Write(":"); + Compare(s1, s1); + System.Console.Write(":"); + Compare(s1, s3); + } + + static void Compare(T x, T y) where T : I1 + { + System.Console.Write(x {{{op}}} y); + } +} +"""; + + var comp2 = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp2, expectedOutput: "operator1:False:operator1:True:operator1:True").VerifyDiagnostics(); + + var tree = comp2.SyntaxTrees.First(); + var model = comp2.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("Extensions1.extension(T).operator " + op + "(T, T)", symbolInfo.Symbol.ToDisplayString()); + } + + [Theory] + [CombinatorialData] + public void Binary_139_Consumption_NullableTypeEquality_WithNull([CombinatorialValues("==", "!=")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1?) + { + public static S1? operator {{{op}}}(S1? x, S1? y) => throw null; + public static S1? operator {{{op switch { "==" => "!=", "!=" => "==", _ => throw ExceptionUtilities.UnexpectedValue(op) }}}}(S1? x, S1? y) => throw null; + } +} + +public struct S1 +{ +} + +class Program +{ + static void Main() + { + S1? s = new S1(); + System.Console.Write(s {{{op}}} null); + } +} +"""; + + var comp2 = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp2, expectedOutput: op == "==" ? "False" : "True").VerifyDiagnostics(); + + var tree = comp2.SyntaxTrees.First(); + var model = comp2.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("object.operator " + op + "(object, object)", symbolInfo.Symbol.ToDisplayString()); + } + + [Theory] + [CombinatorialData] + public void Binary_140_Consumption_NullableTypeEquality_WithNull([CombinatorialValues("==", "!=")] string op) + { + var src = $$$""" +#pragma warning disable CS0660 // 'S1' defines operator == or operator != but does not override Object.Equals(object o) +#pragma warning disable CS0661 // 'S1' defines operator == or operator != but does not override Object.GetHashCode() + +public struct S1 +{ + public int F; + + public static S1 operator {{{op}}}(S1? x, S1? y) + { + System.Console.Write("operator1:"); + return new S1 { F = (x?.F ?? 0) + (y?.F ?? 0) }; + } + + public static S1 operator {{{op switch { "==" => "!=", "!=" => "==", _ => throw ExceptionUtilities.UnexpectedValue(op) }}}}(S1? x, S1? y) => throw null; +} + +class Program +{ + static void Main() + { + S1? s1 = new S1() { F = 101 }; + var s2 = s1 {{{op}}} null; + System.Console.Write(s2.F); + } +} +"""; + + var comp2 = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp2, expectedOutput: "operator1:101").VerifyDiagnostics(); + + var tree = comp2.SyntaxTrees.First(); + var model = comp2.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().Where(a => a.Kind() is not (SyntaxKind.AddExpression or SyntaxKind.CoalesceExpression)).First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("S1.operator " + op + "(S1?, S1?)", symbolInfo.Symbol.ToDisplayString()); + } + + [Theory] + [CombinatorialData] + public void Binary_141_Consumption_CRef([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", ">>>", ">", "<", ">=", "<=", "==", "!=")] string op) + { + string pairedOp = ""; + + if (op is ">" or "<" or ">=" or "<=" or "==" or "!=") + { + pairedOp = $$$""" + /// + public static S1 operator {{{op switch { ">" => "<", ">=" => "<=", "==" => "!=", "<" => ">", "<=" => ">=", "!=" => "==", _ => throw ExceptionUtilities.UnexpectedValue(op) }}}}(S1 x, S1 y) => throw null; +"""; + } + + var src = $$$""" +/// +/// +public static class E +{ + /// + extension(S1) + { + /// + public static S1 operator {{{op}}}(S1 x, S1 y) => throw null; +{{{pairedOp}}} + } +} + +/// +public struct S1; +"""; + + var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreviewWithDocumentationComments); + comp.VerifyEmitDiagnostics(); + + var opName = BinaryOperatorName(op); + + var e = comp.GetMember("E"); + AssertEx.Equal($$$""" + + + + + +""", e.GetDocumentationCommentXml()); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + AssertEx.Equal([ + "(E.extension(S1).operator " + ToCRefOp(op) + ", S1 E.<>E__0." + opName + "(S1 x, S1 y))", + "(E.extension(S1).operator " + ToCRefOp(op) + "(S1, S1), S1 E.<>E__0." + opName + "(S1 x, S1 y))"], + ExtensionTests.PrintXmlCrefSymbols(tree, model)); + } + + [Theory] + [CombinatorialData] + public void Binary_142_Consumption_CRef_Checked([CombinatorialValues("+", "-", "*", "/")] string op) + { + var src = $$$""" +/// +/// +public static class E +{ + /// + extension(S1) + { + /// + public static S1 operator {{{op}}}(S1 x, S1 y) => throw null; + /// + public static S1 operator checked {{{op}}}(S1 x, S1 y) => throw null; + } +} + +/// +public struct S1; +"""; + + var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreviewWithDocumentationComments); + comp.VerifyEmitDiagnostics(); + + var opName = BinaryOperatorName(op, isChecked: true); + + var e = comp.GetMember("E"); + AssertEx.Equal($$$""" + + + + + +""", e.GetDocumentationCommentXml()); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + AssertEx.Equal([ + "(E.extension(S1).operator checked " + ToCRefOp(op) + ", S1 E.<>E__0." + opName + "(S1 x, S1 y))", + "(E.extension(S1).operator checked " + ToCRefOp(op) + "(S1, S1), S1 E.<>E__0." + opName + "(S1 x, S1 y))"], + ExtensionTests.PrintXmlCrefSymbols(tree, model)); + } + + [Theory] + [CombinatorialData] + public void Binary_143_Consumption_CRef_Error([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", ">>>", ">", "<", ">=", "<=", "==", "!=")] string op) + { + var src = $$$""" +/// +/// +/// +/// +/// +/// +/// +/// +public static class E +{ + /// + extension(S1) + { + } +} + +/// +public struct S1; +"""; + + var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreviewWithDocumentationComments); + comp.VerifyEmitDiagnostics( + // (1,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator +' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator " + ToCRefOp(op)).WithArguments("extension(S1).operator " + ToCRefOp(op)).WithLocation(1, 16), + // (2,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator +()' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator " + ToCRefOp(op) + "()").WithArguments("extension(S1).operator " + ToCRefOp(op) + "()").WithLocation(2, 16), + // (3,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator +(S1)' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator " + ToCRefOp(op) + "(S1)").WithArguments("extension(S1).operator " + ToCRefOp(op) + "(S1)").WithLocation(3, 16), + // (4,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator +(S1, S1)' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator " + ToCRefOp(op) + "(S1, S1)").WithArguments("extension(S1).operator " + ToCRefOp(op) + "(S1, S1)").WithLocation(4, 16), + // (5,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator checked +' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator checked " + ToCRefOp(op)).WithArguments("extension(S1).operator checked " + ToCRefOp(op)).WithLocation(5, 16), + // (6,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator checked +()' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator checked " + ToCRefOp(op) + "()").WithArguments("extension(S1).operator checked " + ToCRefOp(op) + "()").WithLocation(6, 16), + // (7,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator checked +(S1)' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator checked " + ToCRefOp(op) + "(S1)").WithArguments("extension(S1).operator checked " + ToCRefOp(op) + "(S1)").WithLocation(7, 16), + // (8,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator checked +(S1, S1)' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator checked " + ToCRefOp(op) + "(S1, S1)").WithArguments("extension(S1).operator checked " + ToCRefOp(op) + "(S1, S1)").WithLocation(8, 16) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_144_ERR_VoidError([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", ">>>", ">", "<", ">=", "<=", "==", "!=")] string op) + { + string pairedOp = ""; + + if (op is ">" or "<" or ">=" or "<=" or "==" or "!=") + { + pairedOp = $$$""" + public static void* operator {{{op switch { ">" => "<", ">=" => "<=", "==" => "!=", "<" => ">", "<=" => ">=", "!=" => "==", _ => throw ExceptionUtilities.UnexpectedValue(op) }}}}(void* x, S1 y) => throw null; +"""; + } + + var src = $$$""" +unsafe public static class Extensions1 +{ + extension(void*) + { + public static void* operator {{{op}}}(void* x, S1 y) => x; +{{{pairedOp}}} + } +} + +public struct S1; + +class Program +{ + unsafe void* Test(void* x, S1 y) => x {{{op}}} y; +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugDll.WithAllowUnsafe(true)); + comp.VerifyDiagnostics( + // (3,15): error CS1103: The receiver parameter of an extension cannot be of type 'void*' + // extension(void*) + Diagnostic(ErrorCode.ERR_BadTypeforThis, "void*").WithArguments("void*").WithLocation(3, 15) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_145_ERR_VoidError([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", ">", "<", ">=", "<=", "==", "!=")] string op) + { + string pairedOp = ""; + + if (op is ">" or "<" or ">=" or "<=" or "==" or "!=") + { + pairedOp = $$$""" + public static void* operator {{{op switch { ">" => "<", ">=" => "<=", "==" => "!=", "<" => ">", "<=" => ">=", "!=" => "==", _ => throw ExceptionUtilities.UnexpectedValue(op) }}}}(S1 x, void* y) => throw null; +"""; + } + + var src = $$$""" +unsafe public static class Extensions1 +{ + extension(void*) + { + public static void* operator {{{op}}}(S1 x, void* y) => y; +{{{pairedOp}}} + } +} + +public struct S1; + +class Program +{ + unsafe void* Test(void* x, S1 y) => y {{{op}}} x; +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugDll.WithAllowUnsafe(true)); + comp.VerifyDiagnostics( + // (3,15): error CS1103: The receiver parameter of an extension cannot be of type 'void*' + // extension(void*) + Diagnostic(ErrorCode.ERR_BadTypeforThis, "void*").WithArguments("void*").WithLocation(3, 15) + ); + } + + [Theory] + [CombinatorialData] + public void Binary_146_ERR_VoidError([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", ">", "<", ">=", "<=", "==", "!=")] string op) + { + string pairedOp = ""; + + if (op is ">" or "<" or ">=" or "<=" or "==" or "!=") + { + pairedOp = $$$""" + public unsafe static void* operator {{{op switch { ">" => "<", ">=" => "<=", "==" => "!=", "<" => ">", "<=" => ">=", "!=" => "==", _ => throw ExceptionUtilities.UnexpectedValue(op) }}}}(void* x, S1 y) => throw null; +"""; + } + + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + unsafe public static void* operator {{{op}}}(void* x, S1 y) + { + System.Console.Write("operator1"); + return x; + } +{{{pairedOp}}} + } +} + +public struct S1; + +class Program +{ + unsafe static void Main() + { + void* s11 = null; + var s12 = new S1(); + var s2 = s11 {{{op}}} s12; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe.WithAllowUnsafe(true)); + CompileAndVerify(comp, expectedOutput: "operator1", verify: Verification.Skipped).VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void Binary_147_ERR_VoidError([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", ">", "<", ">=", "<=", "==", "!=")] string op) + { + string pairedOp = ""; + + if (op is ">" or "<" or ">=" or "<=" or "==" or "!=") + { + pairedOp = $$$""" + public unsafe static void* operator {{{op switch { ">" => "<", ">=" => "<=", "==" => "!=", "<" => ">", "<=" => ">=", "!=" => "==", _ => throw ExceptionUtilities.UnexpectedValue(op) }}}}(void* x, S1 y) => throw null; +"""; + } + + var src = $$$""" +public struct S1 +{ + unsafe public static void* operator {{{op}}}(void* x, S1 y) + { + System.Console.Write("operator1"); + return x; + } +{{{pairedOp}}} + + public override bool Equals(object other) => throw null; + public override int GetHashCode() => throw null; +} + +class Program +{ + unsafe static void Main() + { + void* s11 = null; + var s12 = new S1(); + var s2 = s11 {{{op}}} s12; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe.WithAllowUnsafe(true)); + CompileAndVerify(comp, expectedOutput: "operator1", verify: Verification.Skipped).VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void Binary_148_ERR_VoidError([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", ">>>", ">", "<", ">=", "<=", "==", "!=")] string op) + { + string pairedOp = ""; + + if (op is ">" or "<" or ">=" or "<=" or "==" or "!=") + { + pairedOp = $$$""" + public unsafe static S1 operator {{{op switch { ">" => "<", ">=" => "<=", "==" => "!=", "<" => ">", "<=" => ">=", "!=" => "==", _ => throw ExceptionUtilities.UnexpectedValue(op) }}}}(S1 x, void* y) => throw null; +"""; + } + + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + unsafe public static S1 operator {{{op}}}(S1 x, void* y) + { + System.Console.Write("operator1"); + return x; + } +{{{pairedOp}}} + } +} + +public struct S1; + +class Program +{ + unsafe static void Main() + { + void* s11 = null; + var s12 = new S1(); + var s2 = s12 {{{op}}} s11; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe.WithAllowUnsafe(true)); + CompileAndVerify(comp, expectedOutput: "operator1", verify: Verification.Skipped).VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void Binary_149_ERR_VoidError([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", ">>>", ">", "<", ">=", "<=", "==", "!=")] string op) + { + string pairedOp = ""; + + if (op is ">" or "<" or ">=" or "<=" or "==" or "!=") + { + pairedOp = $$$""" + public unsafe static S1 operator {{{op switch { ">" => "<", ">=" => "<=", "==" => "!=", "<" => ">", "<=" => ">=", "!=" => "==", _ => throw ExceptionUtilities.UnexpectedValue(op) }}}}(S1 x, void* y) => throw null; +"""; + } + + var src = $$$""" +public struct S1 +{ + unsafe public static S1 operator {{{op}}}(S1 x, void* y) + { + System.Console.Write("operator1"); + return x; + } +{{{pairedOp}}} + + public override bool Equals(object other) => throw null; + public override int GetHashCode() => throw null; +} + +class Program +{ + unsafe static void Main() + { + void* s11 = null; + var s12 = new S1(); + var s2 = s12 {{{op}}} s11; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe.WithAllowUnsafe(true)); + CompileAndVerify(comp, expectedOutput: "operator1", verify: Verification.Skipped).VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void Binary_150_ERR_VoidError_Logical([CombinatorialValues("&&", "||")] string op) + { + var src = $$$""" +unsafe public static class Extensions1 +{ + extension(void*) + { + public static void* operator {{{op[0]}}}(void* x, void* y) => x; + public static bool operator true(void* x) => true; + public static bool operator false(void* x) => false; + } +} + +class Program +{ + unsafe void* Test(void* x, void* y) => x {{{op}}} y; +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugDll.WithAllowUnsafe(true)); + comp.VerifyDiagnostics( + // (3,15): error CS1103: The receiver parameter of an extension cannot be of type 'void*' + // extension(void*) + Diagnostic(ErrorCode.ERR_BadTypeforThis, "void*").WithArguments("void*").WithLocation(3, 15) + ); + } + + [Fact] + public void Binary_151_Consumption_ErrorScenarioCandidates() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator +(S2 x, int y) => throw null; + } +} + +public struct S2 +{ + public static S2 operator +(S2 x, int y) + { + return x; + } +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + _ = s2 + s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (22,13): error CS0019: Operator '+' cannot be applied to operands of type 'S2' and 'S2' + // _ = s2 + s2; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s2 + s2").WithArguments("+", "S2", "S2").WithLocation(22, 13) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + } + + [Fact] + public void Binary_152_Consumption_ErrorScenarioCandidates() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator +(S2 x, C1 y) => throw null; + public static S2 operator +(S2 x, C2 y) => throw null; + } +} + +public struct S2 +{ + public static S2 operator +(S2 x, int y) + { + return x; + } + + public static implicit operator C1 (S2 x) => null; + public static implicit operator C2 (S2 x) => null; +} + +public class C1; +public class C2; + +class Program +{ + static void Main() + { + var s2 = new S2(); + _ = s2 + s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (29,13): error CS0034: Operator '+' is ambiguous on operands of type 'S2' and 'S2' + // _ = s2 + s2; + Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "s2 + s2").WithArguments("+", "S2", "S2").WithLocation(29, 13) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); + AssertEx.Equal("Extensions1.extension(S2).operator +(S2, C1)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("Extensions1.extension(S2).operator +(S2, C2)", symbolInfo.CandidateSymbols[1].ToDisplayString()); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_001_Declaration([CombinatorialValues("+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", ">>>=")] string op) + { + var src = $$$""" +static class Extensions1 +{ + extension(ref S1 s1) + { + public void operator {{{op}}}(int x) {} + } +} + +static class Extensions2 +{ + extension(ref S1 s1) + { + public S1 operator {{{op}}}(int x) => throw null; + } +} + +static class Extensions3 +{ + extension(ref S1 s1) + { + void operator {{{op}}}(int x) {} + } + extension(C1) + { + public void operator {{{op}}}(int x) {} + } +} + +static class Extensions4 +{ + extension(ref S1? s1) + { + public void operator {{{op}}}(int x) {} + } +} + +static class Extensions5 +{ + extension(S1 s1) + { +#line 600 + public void operator {{{op}}}(int x) {} + } +#line 700 + extension(ref C2 c2) + { + public void operator {{{op}}}(int x) {} + } +} + +static class Extensions6 +{ + extension(C2 c2) + { + public void operator {{{op}}}(int x) {} + } +} + +static class Extensions7 +{ + extension(in S1 s1) + { +#line 800 + public void operator {{{op}}}(int x) {} + } +#line 900 + extension(in C2 c2) + { + public void operator {{{op}}}(int x) {} + } +} + +static class Extensions8 +{ + extension(ref readonly S1 s1) + { +#line 1000 + public void operator {{{op}}}(int x) {} + } +#line 1100 + extension(ref readonly C2 c2) + { + public void operator {{{op}}}(int x) {} + } +} + +static class Extensions9 +{ + extension(T t) where T : struct + { +#line 1200 + public void operator {{{op}}}(int x) {} + } +} + +static class Extensions10 +{ + extension(T t) where T : class + { + public void operator {{{op}}}(int x) {} + } +} + +static class Extensions11 +{ + extension(T t) + { +#line 1300 + public void operator {{{op}}}(int x) {} + } +} + +static class Extensions12 +{ + extension(ref T t) where T : struct + { + public void operator {{{op}}}(int x) {} + } +} + +static class Extensions13 +{ +#line 1400 + extension(ref T t) where T : class + { + public void operator {{{op}}}(int x) {} + } +} + +static class Extensions14 +{ +#line 1500 + extension(ref T t) + { + public void operator {{{op}}}(int x) {} + } +} + +static class Extensions15 +{ +#line 1600 + extension(in T t) where T : struct + { + public void operator {{{op}}}(int x) {} + } +} + +static class Extensions16 +{ +#line 1700 + extension(in T t) where T : class + { + public void operator {{{op}}}(int x) {} + } +} + +static class Extensions17 +{ +#line 1800 + extension(in T t) + { + public void operator {{{op}}}(int x) {} + } +} + +static class Extensions18 +{ +#line 1900 + extension(ref readonly T t) where T : struct + { + public void operator {{{op}}}(int x) {} + } +} + +static class Extensions19 +{ +#line 2000 + extension(ref readonly T t) where T : class + { + public void operator {{{op}}}(int x) {} + } +} + +static class Extensions20 +{ +#line 2100 + extension(ref readonly T t) + { + public void operator {{{op}}}(int x) {} + } +} + +static class Extensions21 +{ + extension(C2) + { +#line 2200 + public void operator {{{op}}}(int x) {} + } +} + +struct S1 +{} + +static class C1 +{} + +class C2 +{} +"""; + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (13,28): error CS9503: The return type for this operator must be void + // public S1 operator +=(int x) => throw null; + Diagnostic(ErrorCode.ERR_OperatorMustReturnVoid, op).WithLocation(13, 28), + // (21,23): error CS9501: User-defined operator 'Extensions3.extension(ref S1).operator +=(int)' must be declared public + // void operator +=(int x) {} + Diagnostic(ErrorCode.ERR_OperatorsMustBePublic, op).WithArguments("Extensions3.extension(ref S1).operator " + op + "(int)").WithLocation(21, 23), + // (25,30): error CS9321: An extension block extending a static class cannot contain user-defined operators + // public void operator +=(int x) {} + Diagnostic(ErrorCode.ERR_OperatorInExtensionOfStaticClass, op).WithLocation(25, 30), + // (600,30): error CS9322: Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + // public void operator +=(int x) {} + Diagnostic(ErrorCode.ERR_InstanceOperatorStructExtensionWrongReceiverRefKind, op).WithLocation(600, 30), + // (700,19): error CS9300: The 'ref' receiver parameter of an extension block must be a value type or a generic type constrained to struct. + // extension(ref C2 c2) + Diagnostic(ErrorCode.ERR_RefExtensionParameterMustBeValueTypeOrConstrainedToOne, "C2").WithLocation(700, 19), + // (800,30): error CS9322: Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + // public void operator +=(int x) {} + Diagnostic(ErrorCode.ERR_InstanceOperatorStructExtensionWrongReceiverRefKind, op).WithLocation(800, 30), + // (900,18): error CS9301: The 'in' or 'ref readonly' receiver parameter of extension must be a concrete (non-generic) value type. + // extension(in C2 c2) + Diagnostic(ErrorCode.ERR_InExtensionParameterMustBeValueType, "C2").WithLocation(900, 18), + // (1000,30): error CS9322: Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + // public void operator +=(int x) {} + Diagnostic(ErrorCode.ERR_InstanceOperatorStructExtensionWrongReceiverRefKind, op).WithLocation(1000, 30), + // (1100,28): error CS9301: The 'in' or 'ref readonly' receiver parameter of extension must be a concrete (non-generic) value type. + // extension(ref readonly C2 c2) + Diagnostic(ErrorCode.ERR_InExtensionParameterMustBeValueType, "C2").WithLocation(1100, 28), + // (1200,30): error CS9322: Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + // public void operator +=(int x) {} + Diagnostic(ErrorCode.ERR_InstanceOperatorStructExtensionWrongReceiverRefKind, op).WithLocation(1200, 30), + // (1300,30): error CS9323: Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class + // public void operator +=(int x) {} + Diagnostic(ErrorCode.ERR_InstanceOperatorExtensionWrongReceiverType, op).WithLocation(1300, 30), + // (1400,22): error CS9300: The 'ref' receiver parameter of an extension block must be a value type or a generic type constrained to struct. + // extension(ref T t) where T : class + Diagnostic(ErrorCode.ERR_RefExtensionParameterMustBeValueTypeOrConstrainedToOne, "T").WithLocation(1400, 22), + // (1500,22): error CS9300: The 'ref' receiver parameter of an extension block must be a value type or a generic type constrained to struct. + // extension(ref T t) + Diagnostic(ErrorCode.ERR_RefExtensionParameterMustBeValueTypeOrConstrainedToOne, "T").WithLocation(1500, 22), + // (1600,21): error CS9301: The 'in' or 'ref readonly' receiver parameter of extension must be a concrete (non-generic) value type. + // extension(in T t) where T : struct + Diagnostic(ErrorCode.ERR_InExtensionParameterMustBeValueType, "T").WithLocation(1600, 21), + // (1700,21): error CS9301: The 'in' or 'ref readonly' receiver parameter of extension must be a concrete (non-generic) value type. + // extension(in T t) where T : class + Diagnostic(ErrorCode.ERR_InExtensionParameterMustBeValueType, "T").WithLocation(1700, 21), + // (1800,21): error CS9301: The 'in' or 'ref readonly' receiver parameter of extension must be a concrete (non-generic) value type. + // extension(in T t) + Diagnostic(ErrorCode.ERR_InExtensionParameterMustBeValueType, "T").WithLocation(1800, 21), + // (1900,31): error CS9301: The 'in' or 'ref readonly' receiver parameter of extension must be a concrete (non-generic) value type. + // extension(ref readonly T t) where T : struct + Diagnostic(ErrorCode.ERR_InExtensionParameterMustBeValueType, "T").WithLocation(1900, 31), + // (2000,31): error CS9301: The 'in' or 'ref readonly' receiver parameter of extension must be a concrete (non-generic) value type. + // extension(ref readonly T t) where T : class + Diagnostic(ErrorCode.ERR_InExtensionParameterMustBeValueType, "T").WithLocation(2000, 31), + // (2100,31): error CS9301: The 'in' or 'ref readonly' receiver parameter of extension must be a concrete (non-generic) value type. + // extension(ref readonly T t) + Diagnostic(ErrorCode.ERR_InExtensionParameterMustBeValueType, "T").WithLocation(2100, 31), + // (2200,30): error CS9303: 'operator +=': cannot declare instance members in an extension block with an unnamed receiver parameter + // public void operator +=(int x) {} + Diagnostic(ErrorCode.ERR_InstanceMemberWithUnnamedExtensionsParameter, op).WithArguments("operator " + op).WithLocation(2200, 30) + ); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_002_Declaration([CombinatorialValues("+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", ">>>=")] string op) + { + var src = $$$""" +static class Extensions1 +{ + extension(ref S1 s1) + { + public void operator {{{op}}}(int x) {} + } +} + +struct S1 +{} +"""; + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + CompileAndVerify(comp, symbolValidator: verify, sourceSymbolValidator: verify, verify: Verification.FailsPEVerify).VerifyDiagnostics(); + + void verify(ModuleSymbol m) + { + var name = CompoundAssignmentOperatorName(op); + var method = m.GlobalNamespace.GetMember("Extensions1." + name); + + AssertEx.Equal("Extensions1." + name + "(ref S1, int)", method.ToDisplayString()); + Assert.Equal(MethodKind.Ordinary, method.MethodKind); + Assert.True(method.IsStatic); + Assert.False(method.IsExtensionMethod); + Assert.False(method.HasSpecialName); + Assert.False(method.HasRuntimeSpecialName); + Assert.False(method.HasUnsupportedMetadata); + } + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_003_Declaration([CombinatorialValues("+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", ">>>=")] string op, [CombinatorialValues("virtual", "abstract", "new", "override", "sealed", "readonly")] string modifier) + { + var src = $$$""" +static class Extensions1 +{ + extension(ref S1 s1) + { + {{{modifier}}} + public void operator {{{op}}}(int x) {} + } +} + +struct S1 +{} +"""; + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (6,30): error CS0106: The modifier 'abstract' is not valid for this item + // public void operator %=(int x) {} + Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments(modifier).WithLocation(6, 30) + ); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_004_Declaration([CombinatorialValues("+=", "-=", "*=", "/=")] string op) + { + var src = $$$""" +static class Extensions1 +{ + extension(ref S1 s1) + { + public void operator checked {{{op}}}(int x) {} + public void operator {{{op}}}(int x) {} + } +} + +static class Extensions2 +{ + extension(ref S1 s1) + { +#line 100 + public void operator checked {{{op}}}(int x) {} + } + extension(ref S1 s1) + { + public void operator {{{op}}}(int x) {} + } +} + +static class Extensions3 +{ + extension(ref S1 s1) + { + public void operator checked {{{op}}}(int x) {} + } +} + +struct S1 +{} +"""; + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (112,38): error CS9025: The operator 'Extensions3.extension(ref S1).operator checked +=(int)' requires a matching non-checked version of the operator to also be defined + // public void operator checked +=(int x) {} + Diagnostic(ErrorCode.ERR_CheckedOperatorNeedsMatch, op).WithArguments("Extensions3.extension(ref S1).operator checked " + op + "(int)").WithLocation(112, 38) + ); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_005_Consumption(bool fromMetadata, [CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", ">>>")] string op, [CombinatorialValues("struct", "class")] string typeKind) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op}}}(S1 x, S1 y) + { + System.Console.Write("operator1:"); + System.Console.Write(x.F); + System.Console.Write(":"); + System.Console.Write(y.F); + return new S1 { F = x.F + y.F }; + } + } +} + +public {{{typeKind}}} S1 +{ + public int F; +} +"""; + + var src2 = $$$""" +class Program +{ + static void Main() + { + var s11 = new S1() { F = 101 }; + var s12 = new S1() { F = 202 }; + + s11 {{{op}}}= s12; + System.Console.Write(":"); + System.Console.Write(s11.F); + System.Console.Write(":"); + System.Console.Write(s12.F); + System.Console.Write(":"); + + var s2 = s11 {{{op}}}= s12; + System.Console.Write(":"); + System.Console.Write(s11.F); + System.Console.Write(":"); + System.Console.Write(s12.F); + System.Console.Write(":"); + System.Console.Write(s2.F); + } +} +"""; + + var comp1 = CreateCompilation(src1); + var comp1Ref = fromMetadata ? comp1.EmitToImageReference() : comp1.ToMetadataReference(); + + var comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp2, expectedOutput: "operator1:101:202:303:202:operator1:303:202:505:202:505").VerifyDiagnostics(); + + var tree = comp2.SyntaxTrees.First(); + var model = comp2.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().Where(a => a.Kind() != SyntaxKind.SimpleAssignmentExpression).First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("Extensions1.extension(S1).operator " + op + "(S1, S1)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S1", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: "operator1:101:202:303:202:operator1:303:202:505:202:505").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (8,9): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // s11 += s12; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s11 " + op + "= s12").WithArguments("extensions").WithLocation(8, 9), + // (15,18): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // var s2 = s11 += s12; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s11 " + op + "= s12").WithArguments("extensions").WithLocation(15, 18) + ); + + var opName = BinaryOperatorName(op); + var src3 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1(); + s1 = Extensions1.{{{opName}}}(s1, s1); + } +} +"""; + var comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp3, expectedOutput: "operator1:0:0").VerifyDiagnostics(); + + comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp3, expectedOutput: "operator1:0:0").VerifyDiagnostics(); + + comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + CompileAndVerify(comp3, expectedOutput: "operator1:0:0").VerifyDiagnostics(); + + var src4 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1(); + s1.{{{opName}}}(s1); + S1.{{{opName}}}(s1, s1); + } +} +"""; + var comp4 = CreateCompilation(src4, references: [comp1Ref]); + comp4.VerifyEmitDiagnostics( + // (6,12): error CS1061: 'S1' does not contain a definition for 'op_Addition' and no accessible extension method 'op_Addition' accepting a first argument of type 'S1' could be found (are you missing a using directive or an assembly reference?) + // s1.op_Addition(s1); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, opName).WithArguments("S1", opName).WithLocation(6, 12), + // (7,12): error CS0117: 'S1' does not contain a definition for 'op_Addition' + // S1.op_Addition(s1, s1); + Diagnostic(ErrorCode.ERR_NoSuchMember, opName).WithArguments("S1", opName).WithLocation(7, 12) + ); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_006_Consumption(bool fromMetadata, [CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", ">>>")] string op) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(ref S1 x) + { + public void operator {{{op}}}=(S1 y) + { + System.Console.Write("operator1:"); + System.Console.Write(x.F); + System.Console.Write(":"); + System.Console.Write(y.F); + x.F = x.F + y.F; + } + } +} + +public struct S1 +{ + public int F; +} + +""" + CompilerFeatureRequiredAttribute; + + var src2 = $$$""" +class Program +{ + static void Main() + { + var s11 = new S1() { F = 101 }; + var s12 = new S1() { F = 202 }; + + s11 {{{op}}}= s12; + System.Console.Write(":"); + System.Console.Write(s11.F); + System.Console.Write(":"); + System.Console.Write(s12.F); + System.Console.Write(":"); + + var s2 = s11 {{{op}}}= s12; + System.Console.Write(":"); + System.Console.Write(s11.F); + System.Console.Write(":"); + System.Console.Write(s12.F); + System.Console.Write(":"); + System.Console.Write(s2.F); + } +} +"""; + + var comp1 = CreateCompilation(src1); + var comp1Ref = fromMetadata ? comp1.EmitToImageReference() : comp1.ToMetadataReference(); + + var comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp2, expectedOutput: "operator1:101:202:303:202:operator1:303:202:505:202:505").VerifyDiagnostics(); + + var tree = comp2.SyntaxTrees.First(); + var model = comp2.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().Where(a => a.Kind() != SyntaxKind.SimpleAssignmentExpression).First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("Extensions1.extension(ref S1).operator " + op + "=(S1)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("System.Void", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: "operator1:101:202:303:202:operator1:303:202:505:202:505").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (8,9): error CS0019: Operator '+=' cannot be applied to operands of type 'S1' and 'S1' + // s11 += s12; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s11 " + op + "= s12").WithArguments(op + "=", "S1", "S1").WithLocation(8, 9), + // (15,18): error CS0019: Operator '+=' cannot be applied to operands of type 'S1' and 'S1' + // var s2 = s11 += s12; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s11 " + op + "= s12").WithArguments(op + "=", "S1", "S1").WithLocation(15, 18) + ); + + var opName = CompoundAssignmentOperatorName(op + "="); + var src3 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1(); + Extensions1.{{{opName}}}(ref s1, s1); + } +} +"""; + var comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp3, expectedOutput: "operator1:0:0").VerifyDiagnostics(); + + comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp3, expectedOutput: "operator1:0:0").VerifyDiagnostics(); + + comp3 = CreateCompilation(src3, references: [comp1Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + CompileAndVerify(comp3, expectedOutput: "operator1:0:0").VerifyDiagnostics(); + + var src4 = $$$""" +class Program +{ + static void Main() + { + var s1 = new S1(); + s1.{{{opName}}}(s1); + S1.{{{opName}}}(ref s1, s1); + } +} +"""; + var comp4 = CreateCompilation(src4, references: [comp1Ref]); + comp4.VerifyEmitDiagnostics( + // (6,12): error CS1061: 'S1' does not contain a definition for 'op_AdditionAssignment' and no accessible extension method 'op_AdditionAssignment' accepting a first argument of type 'S1' could be found (are you missing a using directive or an assembly reference?) + // s1.op_AdditionAssignment(s1); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, opName).WithArguments("S1", opName).WithLocation(6, 12), + // (7,12): error CS0117: 'S1' does not contain a definition for 'op_AdditionAssignment' + // S1.op_AdditionAssignment(ref s1, s1); + Diagnostic(ErrorCode.ERR_NoSuchMember, opName).WithArguments("S1", opName).WithLocation(7, 12) + ); + + var src5 = $$$""" +public static class Extensions1 +{ + extension(C1 x) + { + public void operator {{{op}}}=(C1 y) + { + System.Console.Write("operator1:"); + System.Console.Write(x.F); + System.Console.Write(":"); + System.Console.Write(y.F); + x.F = x.F + y.F; + } + } +} + +public class C1 +{ + public int F; +} + +""" + CompilerFeatureRequiredAttribute; + + var src6 = $$$""" +class Program +{ + static void Main() + { + var c11 = new C1() { F = 101 }; + var c1 = c11; + var c12 = new C1() { F = 202 }; + + c11 {{{op}}}= c12; + System.Console.Write(":"); + System.Console.Write(c11.F); + System.Console.Write(":"); + System.Console.Write(c12.F); + System.Console.Write(":"); + System.Console.Write(ReferenceEquals(c11, c1) ? "True" : "False"); + System.Console.Write(":"); + + var c2 = c11 {{{op}}}= c12; + System.Console.Write(":"); + System.Console.Write(c11.F); + System.Console.Write(":"); + System.Console.Write(c12.F); + System.Console.Write(":"); + System.Console.Write(ReferenceEquals(c11, c1) ? "True" : "False"); + System.Console.Write(":"); + System.Console.Write(ReferenceEquals(c11, c2) ? "True" : "False"); + } +} +"""; + + var comp5 = CreateCompilation(src5); + var comp5Ref = fromMetadata ? comp5.EmitToImageReference() : comp5.ToMetadataReference(); + + var comp6 = CreateCompilation(src6, references: [comp5Ref], options: TestOptions.DebugExe); + CompileAndVerify(comp6, expectedOutput: "operator1:101:202:303:202:True:operator1:303:202:505:202:True:True").VerifyDiagnostics(); + + comp6 = CreateCompilation(src6, references: [comp5Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp6, expectedOutput: "operator1:101:202:303:202:True:operator1:303:202:505:202:True:True").VerifyDiagnostics(); + + comp6 = CreateCompilation(src6, references: [comp5Ref], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp6.VerifyEmitDiagnostics( + // (9,9): error CS0019: Operator '+=' cannot be applied to operands of type 'C1' and 'C1' + // c11 += c12; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "c11 " + op + "= c12").WithArguments(op + "=", "C1", "C1").WithLocation(9, 9), + // (18,18): error CS0019: Operator '+=' cannot be applied to operands of type 'C1' and 'C1' + // var c2 = c11 += c12; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "c11 " + op + "= c12").WithArguments(op + "=", "C1", "C1").WithLocation(18, 18) + ); + } + + [Fact] + public void CompoundAssignment_007_Consumption_PredefinedComesFirst() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator +(S2 x, S2 y) => throw null; + } +} + +public struct S2 +{ + public static implicit operator int(S2 x) + { + System.Console.Write("operator2"); + return 0; + } + public static implicit operator S2(int x) + { + System.Console.Write("operator3"); + return default; + } +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + s2 += s2; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2operator2operator3").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("int.operator +(int, int)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S2", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void CompoundAssignment_008_Consumption_PredefinedComesFirst() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S2 x) + { + public void operator +=(S2 y) => throw null; + } +} + +public struct S2 +{ + public static implicit operator int(S2 x) + { + System.Console.Write("operator2"); + return 0; + } + public static implicit operator S2(int x) + { + System.Console.Write("operator3"); + return default; + } +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + s2 += s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2operator2operator3").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("int.operator +(int, int)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S2", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void CompoundAssignment_009_Consumption_NonExtensionComesFirst() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator +(S2 x, S2 y) => throw null; + } +} + +public struct S2 +{ + public static S2 operator +(S2 x, S2 y) + { + System.Console.Write("operator2"); + return x; + } +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + s2 += s2; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("S2.operator +(S2, S2)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S2", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void CompoundAssignment_010_Consumption_NonExtensionComesFirst() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator +(S2 x, S2 y) => throw null; + } +} + +public struct S2 +{ + public void operator +=(S2 y) + { + System.Console.Write("operator2"); + } +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + _ = s2 += s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().ElementAt(1); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("S2.operator +=(S2)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S2", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void CompoundAssignment_011_Consumption_NonExtensionComesFirst() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S2 x) + { + public void operator +=(S2 y) => throw null; + } +} + +public struct S2 +{ + public static S2 operator +(S2 x, S2 y) + { + System.Console.Write("operator2"); + return x; + } +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + s2 += s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("S2.operator +(S2, S2)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S2", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void CompoundAssignment_012_Consumption_NonExtensionComesFirst() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S2 x) + { + public void operator +=(S2 y) => throw null; + } +} + +public struct S2 +{ + public void operator +=(S2 y) + { + System.Console.Write("operator2"); + } +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + _ = s2 += s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().ElementAt(1); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("S2.operator +=(S2)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S2", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void CompoundAssignment_013_Consumption_InstanceInTheSameScopeComesFirst() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S2 x) + { + public void operator +=(S2 y) + { + System.Console.Write("operator2"); + } + + public static S2 operator +(S2 y, S2 z) => throw null; + } +} + +public struct S2 +{ +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + _ = s2 += s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().ElementAt(1); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("Extensions1.extension(ref S2).operator +=(S2)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S2", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void CompoundAssignment_014_Consumption_InstanceInTheSameScopeComesFirst() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S2 x) + { + public void operator +=(S2 y) + { + System.Console.Write("operator2"); + } + } + extension(S2) + { + public static S2 operator +(S2 x, S2 y) => throw null; + } +} + +public struct S2 +{ +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + _ = s2 += s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().ElementAt(1); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("Extensions1.extension(ref S2).operator +=(S2)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S2", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void CompoundAssignment_015_Consumption_InstanceInTheSameScopeComesFirst() + { + var src = $$$""" +public static class Extensions2 +{ + extension(S2) + { + public static S2 operator +(S2 x, S2 y) => throw null; + } +} + +public static class Extensions1 +{ + extension(ref S2 x) + { + public void operator +=(S2 y) + { + System.Console.Write("operator2"); + } + } +} + +public struct S2 +{ +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + _ = s2 += s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().ElementAt(1); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("Extensions1.extension(ref S2).operator +=(S2)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S2", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void CompoundAssignment_016_Consumption_StaticTriedAfterInapplicableInstanceInTheSameScope() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S1 x) + { + public void operator +=(S2 y) => throw null; + } + extension(S2) + { + public static S2 operator +(S2 x, S2 y) + { + System.Console.Write("operator2"); + return y; + } + } +} + +public struct S1 +{ +} + +public struct S2 +{ +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + _ = s2 += s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator2").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_017_Consumption_ScopeByScope() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator +(S1 x, S1 y) => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{} + +namespace NS1 +{ + public static class Extensions2 + { + extension(S1) + { + public static S1 operator +(S1 x, S1 y) + { + System.Console.Write("operator1"); + return x; + } + } + } + + namespace NS2 + { + public static class Extensions3 + { + extension(S2) + { + public static S2 operator +(S2 x, S2 y) => throw null; + } + } + + class Program + { + static void Main() + { + var s1 = new S1(); + _ = s1 += s1; + } + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().ElementAt(1); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("NS1.Extensions2.extension(S1).operator +(S1, S1)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S1", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void CompoundAssignment_018_Consumption_ScopeByScope() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S1 x) + { + public void operator +=(S1 y) => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{} + +namespace NS1 +{ + public static class Extensions2 + { + extension(S1) + { + public static S1 operator +(S1 x, S1 y) + { + System.Console.Write("operator1"); + return x; + } + } + } + + namespace NS2 + { + public static class Extensions3 + { + extension(ref S2 x) + { + public void operator +=(S2 y) => throw null; + } + } + + class Program + { + static void Main() + { + var s1 = new S1(); + _ = s1 += s1; + } + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().ElementAt(1); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("NS1.Extensions2.extension(S1).operator +(S1, S1)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S1", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void CompoundAssignment_019_Consumption_ScopeByScope() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S1 x) + { + public void operator +=(S1 y) => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{} + +namespace NS1 +{ + public static class Extensions2 + { + extension(ref S1 x) + { + public void operator +=(S1 y) + { + System.Console.Write("operator1"); + } + } + } + + namespace NS2 + { + public static class Extensions3 + { + extension(ref S2 x) + { + public void operator +=(S2 y) => throw null; + } + } + + class Program + { + static void Main() + { + var s1 = new S1(); + _ = s1 += s1; + } + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().ElementAt(1); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("NS1.Extensions2.extension(ref S1).operator +=(S1)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S1", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void CompoundAssignment_020_Consumption_ScopeByScope() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator +(S1 x, S1 y) => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{} + +namespace NS1 +{ + public static class Extensions2 + { + extension(ref S1 x) + { + public void operator +=(S1 y) + { + System.Console.Write("operator1"); + } + } + } + + namespace NS2 + { + public static class Extensions3 + { + extension(S2) + { + public static S2 operator +(S2 x, S2 y) => throw null; + } + } + + class Program + { + static void Main() + { + var s1 = new S1(); + _ = s1 += s1; + } + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().ElementAt(1); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Equal("NS1.Extensions2.extension(ref S1).operator +=(S1)", symbolInfo.Symbol.ToDisplayString()); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + Assert.Equal("S1", model.GetTypeInfo(opNode).Type.ToTestDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void CompoundAssignment_021_Consumption_NonExtensionAmbiguity() + { + var src = $$$""" +public interface I1 +{ + public static I1 operator -(I1 x, I1 y) => x; +} + +public interface I3 +{ + public static I3 operator -(I3 x, I3 y) => x; +} + +public interface I4 : I1, I3 +{ +} + +public interface I2 : I4 +{ +} + +public static class Extensions1 +{ + extension(I2 z) + { + public void operator -=(I2 y) {} + public static I2 operator -(I2 x, I2 y) => x; + } +} + +class Test2 : I2 +{ + static void Main() + { + I2 x = new Test2(); + var y = x -= x; + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (33,17): error CS0034: Operator '-=' is ambiguous on operands of type 'I2' and 'I2' + // var y = x -= x; + Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "x -= x").WithArguments("-=", "I2", "I2").WithLocation(33, 17) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); + Assert.Equal(2, symbolInfo.CandidateSymbols.Length); + AssertEx.Equal("I1.operator -(I1, I1)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("I3.operator -(I3, I3)", symbolInfo.CandidateSymbols[1].ToDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void CompoundAssignment_022_Consumption_NonExtensionAmbiguity() + { + var src = $$$""" +public interface I1 +{ + public void operator -=(I1 y) {} +} + +public interface I3 +{ + public void operator -=(I3 y) {} +} + +public interface I4 : I1, I3 +{ +} + +public interface I2 : I4 +{ +} + +public static class Extensions1 +{ + extension(I2 z) + { + public void operator -=(I2 y) {} + public static I2 operator -(I2 x, I2 y) => x; + } +} + +class Test2 : I2 +{ + static void Main() + { + I2 x = new Test2(); + var y = x -= x; + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (33,19): error CS0121: The call is ambiguous between the following methods or properties: 'I1.operator -=(I1)' and 'I3.operator -=(I3)' + // var y = x -= x; + Diagnostic(ErrorCode.ERR_AmbigCall, "-=").WithArguments("I1.operator -=(I1)", "I3.operator -=(I3)").WithLocation(33, 19) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); + Assert.Equal(2, symbolInfo.CandidateSymbols.Length); + AssertEx.Equal("I1.operator -=(I1)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("I3.operator -=(I3)", symbolInfo.CandidateSymbols[1].ToDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void CompoundAssignment_023_Consumption_NonExtensionAmbiguity() + { + var src = $$$""" +public interface I1 +{ + public void operator -=(I1 y) {} +} + +public interface I3 +{ + public void operator -=(I3 y) {} +} + +public interface I4 : I1, I3 +{ +} + +public interface I2 : I4 +{ + public static I2 operator -(I2 x, I2 y) => y; +} + +public static class Extensions1 +{ + extension(I2 z) + { + public void operator -=(I2 y) {} + public static I2 operator -(I2 x, I2 y) => x; + } +} + +class Test2 : I2 +{ + static void Main() + { + I2 x = new Test2(); +#line 33 + var y = x -= x; + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (33,19): error CS0121: The call is ambiguous between the following methods or properties: 'I1.operator -=(I1)' and 'I3.operator -=(I3)' + // var y = x -= x; + Diagnostic(ErrorCode.ERR_AmbigCall, "-=").WithArguments("I1.operator -=(I1)", "I3.operator -=(I3)").WithLocation(33, 19) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); + Assert.Equal(2, symbolInfo.CandidateSymbols.Length); + AssertEx.Equal("I1.operator -=(I1)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("I3.operator -=(I3)", symbolInfo.CandidateSymbols[1].ToDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + [WorkItem("https://github.com/dotnet/roslyn/issues/78830")] + public void CompoundAssignment_024_Consumption_ExtensionAmbiguity() + { + var src = $$$""" +public interface I1; +public interface I3; +public interface I4 : I1, I3; +public interface I2 : I4; + +public static class Extensions1 +{ + extension(I2 z) + { + public void operator -=(I2 y) {} + public static I2 operator -(I2 x, I2 y) => x; + } +} + +namespace NS1 +{ + public static class Extensions2 + { + extension(I1) + { + public static I1 operator -(I1 x, I1 y) => x; + } + + extension(I3) + { + public static I3 operator -(I3 x, I3 y) => x; + } + } + + class Test2 : I2 + { + static void Main() + { + I2 x = new Test2(); + var y = x -= x; + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src); + + // https://github.com/dotnet/roslyn/issues/78830: We might want to include more information into the error. Like what methods conflict. + comp.VerifyEmitDiagnostics( + // (35,21): error CS0034: Operator '-=' is ambiguous on operands of type 'I2' and 'I2' + // var y = x -= x; + Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "x -= x").WithArguments("-=", "I2", "I2").WithLocation(35, 21) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); + Assert.Equal(2, symbolInfo.CandidateSymbols.Length); + AssertEx.Equal("NS1.Extensions2.extension(I1).operator -(I1, I1)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("NS1.Extensions2.extension(I3).operator -(I3, I3)", symbolInfo.CandidateSymbols[1].ToDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void CompoundAssignment_025_Consumption_ExtensionAmbiguity() + { + var src = $$$""" +public interface I1; +public interface I3; +public interface I4 : I1, I3; +public interface I2 : I4; + +public static class Extensions1 +{ + extension(I2 z) + { + public void operator -=(I2 y) {} + public static I2 operator -(I2 x, I2 y) => x; + } +} + +namespace NS1 +{ + public static class Extensions2 + { + extension(I1 x) + { + public void operator -=(I1 y) {} + } + + extension(I3 x) + { + public void operator -=(I3 y) {} + } + } + + class Test2 : I2 + { + static void Main() + { + I2 x = new Test2(); + var y = x -= x; + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src); + + comp.VerifyEmitDiagnostics( + // (35,23): error CS0121: The call is ambiguous between the following methods or properties: 'Extensions2.extension(I1).operator -=(I1)' and 'Extensions2.extension(I3).operator -=(I3)' + // var y = x -= x; + Diagnostic(ErrorCode.ERR_AmbigCall, "-=").WithArguments("NS1.Extensions2.extension(I1).operator -=(I1)", "NS1.Extensions2.extension(I3).operator -=(I3)").WithLocation(35, 23) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); + Assert.Equal(2, symbolInfo.CandidateSymbols.Length); + AssertEx.Equal("NS1.Extensions2.extension(I1).operator -=(I1)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("NS1.Extensions2.extension(I3).operator -=(I3)", symbolInfo.CandidateSymbols[1].ToDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Fact] + public void CompoundAssignment_026_Consumption_ExtensionAmbiguity() + { + var src = $$$""" +public interface I1; +public interface I3; +public interface I4 : I1, I3; +public interface I2 : I4; + +public static class Extensions1 +{ + extension(I2 z) + { + public void operator -=(I2 y) {} + public static I2 operator -(I2 x, I2 y) => x; + } +} + +namespace NS1 +{ + public static class Extensions2 + { + extension(I1 x) + { + public void operator -=(I1 y) {} + } + + extension(I3 x) + { + public void operator -=(I3 y) {} + } + + extension(I2) + { + public static I2 operator -(I2 x, I2 y) => x; + } + } + + class Test2 : I2 + { + static void Main() + { + I2 x = new Test2(); +#line 35 + var y = x -= x; + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src); + + comp.VerifyEmitDiagnostics( + // (35,23): error CS0121: The call is ambiguous between the following methods or properties: 'Extensions2.extension(I1).operator -=(I1)' and 'Extensions2.extension(I3).operator -=(I3)' + // var y = x -= x; + Diagnostic(ErrorCode.ERR_AmbigCall, "-=").WithArguments("NS1.Extensions2.extension(I1).operator -=(I1)", "NS1.Extensions2.extension(I3).operator -=(I3)").WithLocation(35, 23) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); + Assert.Equal(2, symbolInfo.CandidateSymbols.Length); + AssertEx.Equal("NS1.Extensions2.extension(I1).operator -=(I1)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("NS1.Extensions2.extension(I3).operator -=(I3)", symbolInfo.CandidateSymbols[1].ToDisplayString()); + + var group = model.GetMemberGroup(opNode); + Assert.Empty(group); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_027_Consumption_Lifted([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", ">>>")] string op) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(ref S1 z) + { + public void operator {{{op}}}=(S1 y) => throw null; + + public static S1 operator {{{op}}}(S1 x, S1 y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} +"""; + var src2 = $$$""" +class Program +{ + static void Main() + { + S1? s11 = new S1(); + S1? s12 = new S1(); + _ = s11 {{{op}}}= s12; + System.Console.Write(":"); + s11 = null; + _ = s11 {{{op}}}= s12; + _ = s12 {{{op}}}= s11; + _ = s11 {{{op}}}= s11; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp1 = CreateCompilation([src1, src2], options: TestOptions.DebugExe); + CompileAndVerify(comp1, expectedOutput: "operator1:").VerifyDiagnostics(); + + var comp2 = CreateCompilation([src1, src2], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: "operator1:").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1.ToMetadataReference()], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (7,13): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = s11 -= s12; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s11 " + op + "= s12").WithArguments("extensions").WithLocation(7, 13), + // (10,13): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = s11 -= s12; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s11 " + op + "= s12").WithArguments("extensions").WithLocation(10, 13), + // (11,13): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = s12 -= s11; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s12 " + op + "= s11").WithArguments("extensions").WithLocation(11, 13), + // (12,13): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = s11 -= s11; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "s11 " + op + "= s11").WithArguments("extensions").WithLocation(12, 13) + ); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_028_Consumption_Lifted([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", ">>>")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S1 z) + { + public void operator {{{op}}}=(S1 y) => throw null; + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? s11 = new S1(); + S1? s12 = new S1(); + _ = s11 {{{op}}}= s12; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (18,13): error CS0019: Operator '+=' cannot be applied to operands of type 'S1?' and 'S1?' + // _ = s11 += s12; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s11 " + op + "= s12").WithArguments(op + "=", "S1?", "S1?").WithLocation(18, 13) + ); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_029_Consumption_Lifted([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", ">>>")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S1 z) + { + public void operator {{{op}}}=(S1 y) => throw null; + + public static S1 operator {{{op}}}(S1 x, S1 y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? s11 = new S1(); + S1 s12 = new S1(); + _ = s11 {{{op}}}= s12; + System.Console.Write(":"); + s11 = null; + _ = s11 {{{op}}}= s12; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1:").VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_030_Consumption_Lifted([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", ">>>")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S1 z) + { + public void operator {{{op}}}=(S1 y) => throw null; + + public static S1 operator {{{op}}}(S1 x, S1 y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? s11 = new S1(); + S1 s12 = new S1(); + _ = s12 {{{op}}}= s11; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (24,13): error CS0266: Cannot implicitly convert type 'S1?' to 'S1'. An explicit conversion exists (are you missing a cast?) + // _ = s12 += s11; + Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "s12 " + op + "= s11").WithArguments("S1?", "S1").WithLocation(24, 13) + ); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_031_Consumption_Lifted([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", ">>>")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S1 z) + { + public void operator {{{op}}}=(S1 y) => throw null; + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? s11 = new S1(); + S1 s12 = new S1(); + _ = s11 {{{op}}}= s12; + _ = s12 {{{op}}}= s11; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (18,13): error CS0019: Operator '+=' cannot be applied to operands of type 'S1?' and 'S1' + // _ = s11 += s12; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s11 " + op + "= s12").WithArguments(op + "=", "S1?", "S1").WithLocation(18, 13), + // (19,13): error CS0019: Operator '+=' cannot be applied to operands of type 'S1' and 'S1?' + // _ = s12 += s11; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s12 " + op + "= s11").WithArguments(op + "=", "S1", "S1?").WithLocation(19, 13) + ); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_032_Consumption_Lifted([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op}}}(S1 x, S2 y) + { + System.Console.Write("operator1:"); + System.Console.Write(x.F); + System.Console.Write(":"); + System.Console.Write(y.F); + return new S1 { F = x.F * 1000 + y.F }; + } + public static S2 operator {{{op}}}(S2 x, S1 y) + { + System.Console.Write("operator2:"); + System.Console.Write(x.F); + System.Console.Write(":"); + System.Console.Write(y.F); + return new S2 { F = x.F * 1000 + y.F }; + } + } +} + +public struct S1 +{ + public int F; +} + +public struct S2 +{ + public int F; +} + +class Program +{ + static void Main() + { + S1?[] s1 = [new S1() { F = 101 }, null]; + S2?[] s2 = [new S2() { F = 202 }, null]; + + foreach (var s11 in s1) + { + foreach (var s12 in s2) + { + var s21 = s11; + var s22 = s12; + + Print(s21 {{{op}}}= s22, s21, s22); + System.Console.WriteLine(); + + s21 = s11; + s22 = s12; + + Print(s22 {{{op}}}= s21, s22, s21); + System.Console.WriteLine(); + } + } + } + + static void Print(S1? x, S1? y, S2? z) + { + System.Console.Write(":"); + System.Console.Write(x?.F.ToString() ?? "null"); + System.Console.Write(":"); + System.Console.Write(y?.F.ToString() ?? "null"); + System.Console.Write(":"); + System.Console.Write(z?.F.ToString() ?? "null"); + } + + static void Print(S2? x, S2? y, S1? z) + { + System.Console.Write(":"); + System.Console.Write(x?.F.ToString() ?? "null"); + System.Console.Write(":"); + System.Console.Write(y?.F.ToString() ?? "null"); + System.Console.Write(":"); + System.Console.Write(z?.F.ToString() ?? "null"); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: +@" +operator1:101:202:101202:101202:202 +operator2:202:101:202101:202101:101 +:null:null:null +:null:null:101 +:null:null:202 +:null:null:null +:null:null:null +:null:null:null +").VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_033_Consumption_Lifted_Shift([CombinatorialValues("<<", ">>", ">>>")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator {{{op}}}(S1 x, S2 y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} + +public struct S2 +{} + +class Program +{ + static void Main() + { + S1? s1 = new S1(); + S2? s2 = new S2(); + _ = s1 {{{op}}}= s2; + System.Console.Write(":"); + s1 = null; + _ = s1 {{{op}}}= s2; + s1 = new S1(); + s2 = null; + _ = s1 {{{op}}}= s2; + s1 = null; + _ = s1 {{{op}}}= s2; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1:").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_034_Consumption_LiftedIsWorse() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator +(S1 x, S1 y) => throw null; + } + extension(S1?) + { + public static S1? operator +(S1? x, S1? y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? s1 = new S1(); + _ = s1 += s1; + System.Console.Write(":"); + s1 = null; + _ = s1 += s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1:operator1").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_035_Consumption_ExtendedTypeIsNullable() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1?) + { + public static S1? operator +(S1? x, S1? y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1 s1 = new S1(); + _ = s1 += s1; + Extensions1.op_Addition(s1, s1); + + S1? s2 = new S1(); + _ = s2 += s2; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (21,13): error CS0019: Operator '+=' cannot be applied to operands of type 'S1' and 'S1' + // _ = s1 += s1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 += s1").WithArguments("+=", "S1", "S1").WithLocation(21, 13) + ); + } + + [Fact] + public void CompoundAssignment_036_Consumption_ExtendedTypeIsNullable() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S1? x) + { + public void operator +=(S1? y) {} + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1 s1 = new S1(); + _ = s1 += s1; + Extensions1.op_AdditionAssignment(s1, s1); + Extensions1.op_AdditionAssignment(ref s1, s1); + + S1? s2 = new S1(); + _ = s2 += s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (17,13): error CS0019: Operator '+=' cannot be applied to operands of type 'S1' and 'S1' + // _ = s1 += s1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 += s1").WithArguments("+=", "S1", "S1").WithLocation(17, 13), + // (18,43): error CS1620: Argument 1 must be passed with the 'ref' keyword + // Extensions1.op_AdditionAssignment(s1, s1); + Diagnostic(ErrorCode.ERR_BadArgRef, "s1").WithArguments("1", "ref").WithLocation(18, 43), + // (19,47): error CS1503: Argument 1: cannot convert from 'ref S1' to 'ref S1?' + // Extensions1.op_AdditionAssignment(ref s1, s1); + Diagnostic(ErrorCode.ERR_BadArgType, "s1").WithArguments("1", "ref S1", "ref S1?").WithLocation(19, 47) + ); + } + + [Fact] + public void CompoundAssignment_037_Consumption_ReceiverTypeMismatch() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator +(S2 x, S2 y) => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{ + public static implicit operator S2(S1 x) => default; +} + +class Program +{ + static void Main() + { + S1 s1 = new S1(); + S2 s2 = new S2(); + _ = s1 += s2; + _ = s2 += s1; + _ = s1 += s1; + Extensions1.op_Addition(s1, s1); + + S1? s3 = new S1(); + _ = s3 += s3; + Extensions1.op_Addition(s3, s3); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (23,13): error CS0029: Cannot implicitly convert type 'S2' to 'S1' + // _ = s1 += s2; + Diagnostic(ErrorCode.ERR_NoImplicitConv, "s1 += s2").WithArguments("S2", "S1").WithLocation(23, 13), + // (25,13): error CS0019: Operator '+=' cannot be applied to operands of type 'S1' and 'S1' + // _ = s1 += s1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 += s1").WithArguments("+=", "S1", "S1").WithLocation(25, 13), + // (29,13): error CS0019: Operator '+=' cannot be applied to operands of type 'S1?' and 'S1?' + // _ = s3 += s3; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s3 += s3").WithArguments("+=", "S1?", "S1?").WithLocation(29, 13), + // (30,33): error CS1503: Argument 1: cannot convert from 'S1?' to 'S2' + // Extensions1.op_Addition(s3, s3); + Diagnostic(ErrorCode.ERR_BadArgType, "s3").WithArguments("1", "S1?", "S2").WithLocation(30, 33), + // (30,37): error CS1503: Argument 2: cannot convert from 'S1?' to 'S2' + // Extensions1.op_Addition(s3, s3); + Diagnostic(ErrorCode.ERR_BadArgType, "s3").WithArguments("2", "S1?", "S2").WithLocation(30, 37) + ); + + var src1 = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator +(S2 x, S1 y) => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{ + public static implicit operator S2(S1 x) => default; + public static implicit operator S1(S2 x) => default; +} + +class Program +{ + static void Main() + { + S1 s1 = new S1(); + S2 s2 = new S2(); + _ = s1 += s1; + _ = s1 += s2; + _ = s2 += s1; + _ = s2 += s2; + Extensions1.op_Addition(s1, s1); + Extensions1.op_Addition(s1, s2); + } +} +"""; + + var comp1 = CreateCompilation(src1, options: TestOptions.DebugExe); + comp1.VerifyEmitDiagnostics( + // (24,13): error CS0019: Operator '+=' cannot be applied to operands of type 'S1' and 'S1' + // _ = s1 += s1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 += s1").WithArguments("+=", "S1", "S1").WithLocation(24, 13), + // (25,13): error CS0019: Operator '+=' cannot be applied to operands of type 'S1' and 'S2' + // _ = s1 += s2; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 += s2").WithArguments("+=", "S1", "S2").WithLocation(25, 13) + ); + + var src2 = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator +(S1 x, S2 y) => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{ + public static implicit operator S2(S1 x) => default; + public static implicit operator S1(S2 x) => default; +} + +class Program +{ + static void Main() + { + S1 s1 = new S1(); + S2 s2 = new S2(); + _ = s1 += s1; + _ = s1 += s2; + _ = s2 += s1; + _ = s2 += s2; + Extensions1.op_Addition(s1, s1); + Extensions1.op_Addition(s2, s1); + } +} +"""; + + var comp2 = CreateCompilation(src2, options: TestOptions.DebugExe); + comp2.VerifyEmitDiagnostics( + // (24,13): error CS0019: Operator '+=' cannot be applied to operands of type 'S1' and 'S1' + // _ = s1 += s1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 += s1").WithArguments("+=", "S1", "S1").WithLocation(24, 13), + // (26,13): error CS0019: Operator '+=' cannot be applied to operands of type 'S2' and 'S1' + // _ = s2 += s1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s2 += s1").WithArguments("+=", "S2", "S1").WithLocation(26, 13) + ); + } + + [Fact] + public void CompoundAssignment_038_Consumption_ReceiverTypeMismatch() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S2 x) + { + public void operator +=(S2 y) => throw null; + } +} + +public struct S1 +{} + +public struct S2 +{ + public static implicit operator S2(S1 x) => default; +} + +class Program +{ + static void Main() + { + S1 s1 = new S1(); + S2 s2 = new S2(); + _ = s1 += s2; + _ = s2 += s1; + _ = s1 += s1; + Extensions1.op_AdditionAssignment(ref s1, s1); + + S1? s3 = new S1(); + _ = s3 += s3; + Extensions1.op_AdditionAssignment(ref s3, s3); + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (23,13): error CS0019: Operator '+=' cannot be applied to operands of type 'S1' and 'S2' + // _ = s1 += s2; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 += s2").WithArguments("+=", "S1", "S2").WithLocation(23, 13), + // (25,13): error CS0019: Operator '+=' cannot be applied to operands of type 'S1' and 'S1' + // _ = s1 += s1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 += s1").WithArguments("+=", "S1", "S1").WithLocation(25, 13), + // (26,47): error CS1503: Argument 1: cannot convert from 'ref S1' to 'ref S2' + // Extensions1.op_AdditionAssignment(ref s1, s1); + Diagnostic(ErrorCode.ERR_BadArgType, "s1").WithArguments("1", "ref S1", "ref S2").WithLocation(26, 47), + // (29,13): error CS0019: Operator '+=' cannot be applied to operands of type 'S1?' and 'S1?' + // _ = s3 += s3; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s3 += s3").WithArguments("+=", "S1?", "S1?").WithLocation(29, 13), + // (30,47): error CS1503: Argument 1: cannot convert from 'ref S1?' to 'ref S2' + // Extensions1.op_AdditionAssignment(ref s3, s3); + Diagnostic(ErrorCode.ERR_BadArgType, "s3").WithArguments("1", "ref S1?", "ref S2").WithLocation(30, 47), + // (30,51): error CS1503: Argument 2: cannot convert from 'S1?' to 'S2' + // Extensions1.op_AdditionAssignment(ref s3, s3); + Diagnostic(ErrorCode.ERR_BadArgType, "s3").WithArguments("2", "S1?", "S2").WithLocation(30, 51) + ); + } + + [Fact] + public void CompoundAssignment_039_Consumption_ReceiverTypeMismatch() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object) + { + public static S1 operator +(object x, int y) + { + System.Console.Write("operator1"); + return default; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1 s1 = new S1(); + s1 += 1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_040_Consumption_ReceiverTypeMismatch() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object x) + { + public void operator +=(int y) => throw null; + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1 s1 = new S1(); + s1 += 1; + Extensions1.op_AdditionAssignment(s1, 1); + + S1? s2 = new S1(); + s2 += 1; + Extensions1.op_AdditionAssignment(s2, 1); + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (17,9): error CS0019: Operator '+=' cannot be applied to operands of type 'S1' and 'int' + // s1 += 1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 += 1").WithArguments("+=", "S1", "int").WithLocation(17, 9), + // (21,9): error CS0019: Operator '+=' cannot be applied to operands of type 'S1?' and 'int' + // s2 += 1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s2 += 1").WithArguments("+=", "S1?", "int").WithLocation(21, 9) + ); + } + + [Fact] + public void CompoundAssignment_041_Consumption_ReceiverTypeMismatch() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object) + { + public static C1 operator +(object x, int y) + { + System.Console.Write("operator1"); + return null; + } + } +} + +public class C1 +{} + +class Program +{ + static void Main() + { + var c1 = new C1(); + c1 = c1 += 1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_042_Consumption_ReceiverTypeMismatch() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1Base x) + { + public void operator +=(int y) + { + System.Console.Write("operator1:"); + System.Console.Write(x.F); + System.Console.Write(":"); + System.Console.Write(y); + x.F += y; + } + } +} + +public class C1Base +{ + public int F; +} + +public class C1 : C1Base +{} + +class Program +{ + static void Main() + { + var c11 = new C1() { F = 101 }; + var c1 = c11; + var c12 = 202; + + c11 += c12; + System.Console.Write(":"); + System.Console.Write(c11.F); + System.Console.Write(":"); + System.Console.Write(c12); + System.Console.Write(":"); + System.Console.Write(ReferenceEquals(c11, c1) ? "True" : "False"); + System.Console.Write(":"); + + var c2 = c11 += c12; + System.Console.Write(":"); + System.Console.Write(c11.F); + System.Console.Write(":"); + System.Console.Write(c12); + System.Console.Write(":"); + System.Console.Write(ReferenceEquals(c11, c1) ? "True" : "False"); + System.Console.Write(":"); + System.Console.Write(ReferenceEquals(c11, c2) ? "True" : "False"); + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1:101:202:303:202:True:operator1:303:202:505:202:True:True").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_043_Consumption_ReceiverTypeMismatch() + { + var src = $$$""" +public static class Extensions1 +{ + extension(dynamic x) + { + public void operator +=(int y) + { + System.Console.Write("operator1"); + } + } +} + +public class C1 +{} + +class Program +{ + static void Main() + { + var c1 = new C1(); + c1 += 1; + c1 = c1 += 1; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (3,15): error CS1103: The receiver parameter of an extension cannot be of type 'dynamic' + // extension(dynamic x) + Diagnostic(ErrorCode.ERR_BadTypeforThis, "dynamic").WithArguments("dynamic").WithLocation(3, 15) + ); + } + + [Fact] + public void CompoundAssignment_044_Consumption_ReceiverTypeMismatch() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object x) + { + public void operator +=(int y) + { + System.Console.Write("operator1"); + } + } +} + +public class C1 +{} + +class Program +{ + static void Main() + { + Test(new C1()); + } + + static void Test(T c1) where T : class + { + c1 += 1; + c1 = c1 += 1; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1operator1").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_045_Consumption_ReceiverTypeMismatch() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref System.Span x) + { + public void operator +=(int y) => throw null; + } +} + +class Program +{ + static void Main() + { + int[] a1 = null; +#line 17 + _ = a1 += 1; + Extensions1.op_AdditionAssignment(ref a1, 1); + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (17,13): error CS0019: Operator '+=' cannot be applied to operands of type 'int[]' and 'int' + // _ = a1 += 1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "a1 += 1").WithArguments("+=", "int[]", "int").WithLocation(17, 13), + // (18,47): error CS1503: Argument 1: cannot convert from 'ref int[]' to 'ref System.Span' + // Extensions1.op_AdditionAssignment(ref a1, 1); + Diagnostic(ErrorCode.ERR_BadArgType, "a1").WithArguments("1", "ref int[]", "ref System.Span").WithLocation(18, 47) + ); + } + + [Fact] + public void CompoundAssignment_046_Consumption_Generic() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) where T : struct + { + public static S1 operator +(S1 x, S1 y) + { + System.Console.Write(typeof(T).ToString()); + return x; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + var s1 = new S1(); + s1 = s1 += s1; + Extensions1.op_Addition(s1, s1); + + S1? s2 = new S1(); + _ = (s2 += s2).GetValueOrDefault(); + s2 = null; + System.Console.Write(":"); + _ = (s2 += s2).GetValueOrDefault(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "System.Int32System.Int32System.Int32:").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_047_Consumption_Generic() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S1 x) where T : struct + { + public void operator +=(S1 y) + { + System.Console.Write(typeof(T).ToString()); + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + var s1 = new S1(); + s1 = s1 += s1; + Extensions1.op_AdditionAssignment(ref s1, s1); + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "System.Int32System.Int32").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_048_Consumption_Generic_Worse() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator +(S1 x, S1 y) + { + System.Console.Write("[S1]"); + return x; + } + } + + extension(S1?) + { + public static S1? operator +(S1? x, S1? y) + { + System.Console.Write("[S1?]"); + return x; + } + } + + extension(S1) + { + public static S1 operator +(S1 x, S1 y) + { + System.Console.Write("[S1]"); + return x; + } + } + + extension(S2) + { + public static S2 operator +(in S2 x, S2 y) => throw null; + + public static S2 operator +(S2 x, S2 y) + { + System.Console.Write("[S2]"); + return x; + } + } + + extension(S2) + { + public static S2 operator +(in S2 x, S2 y) + { + System.Console.Write("[in S2]"); + return x; + } + } +} + +public struct S1 +{} + +public struct S2 +{} + +class Program +{ + static void Main() + { + var s11 = new S1(); + s11 = s11 += s11; + Extensions1.op_Addition(s11, s11); + + System.Console.WriteLine(); + + var s12 = new S1(); + s12 = s12 += s12; + Extensions1.op_Addition(s12, s12); + + System.Console.WriteLine(); + + var s21 = new S2(); + s21 = s21 += s21; + Extensions1.op_Addition(s21, s21); + + System.Console.WriteLine(); + + var s22 = new S2(); + s22 = s22 += s22; + Extensions1.op_Addition(s22, s22); + + System.Console.WriteLine(); + + S1? s13 = new S1(); + s13 = s13 += s13; + s13 = null; + s13 = s13 += s13; + + System.Console.WriteLine(); + + S1? s14 = new S1(); + s14 = s14 += s14; + s14 = null; + s14 = s14 += s14; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: @" +[S1][S1] +[S1][S1] +[in S2][in S2] +[S2][S2] +[S1] +[S1?][S1?] +").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_049_Consumption_Generic_Worse() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S1 x) + { + public void operator +=(int y) + { + System.Console.Write("[S1]"); + } + } + + extension(ref S1? x) + { + public void operator +=(int y) + { + System.Console.Write("[S1?]"); + } + } + + extension(ref S1 x) + { + public void operator +=(int y) + { + System.Console.Write("[S1]"); + } + } + + extension(ref S1? x) + { + public void operator +=(int y) + { + System.Console.Write("[S1?]"); + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + var s11 = new S1(); + s11 = s11 += 1; + Extensions1.op_AdditionAssignment(ref s11, 1); + + System.Console.WriteLine(); + + var s12 = new S1(); + s12 = s12 += 1; + Extensions1.op_AdditionAssignment(ref s12, 1); + + System.Console.WriteLine(); + + S1? s13 = new S1(); + s13 = s13 += 1; + s13 = null; + s13 = s13 += 1; + + System.Console.WriteLine(); + + S1? s14 = new S1(); + s14 = s14 += 1; + s14 = null; + s14 = s14 += 1; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: @" +[S1][S1] +[S1][S1] +[S1?][S1?] +[S1?][S1?] +").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_050_Consumption_Generic_ConstraintsViolation() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) where T : class + { + public static S1 operator +(S1 x, S1 y) => throw null; + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + var s1 = new S1(); + _ = s1 += s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (17,13): error CS0019: Operator '+=' cannot be applied to operands of type 'S1' and 'S1' + // _ = s1 += s1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 += s1").WithArguments("+=", "S1", "S1").WithLocation(17, 13) + ); + } + + [Fact] + public void CompoundAssignment_051_Consumption_Generic_ConstraintsViolation() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S1 x) where T : class + { + public void operator +=(int i) => throw null; + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + var s1 = new S1(); + _ = s1 += 1; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (17,13): error CS0019: Operator '+=' cannot be applied to operands of type 'S1' and 'int' + // _ = s1 += 1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 += 1").WithArguments("+=", "S1", "int").WithLocation(17, 13) + ); + } + + [Fact] + public void CompoundAssignment_052_Consumption_OverloadResolutionPriority() + { + var src = $$$""" +using System.Runtime.CompilerServices; + +public static class Extensions1 +{ + extension(C1) + { + [OverloadResolutionPriority(1)] + public static C2 operator +(C1 x, C1 y) + { + System.Console.Write("C1"); + return null; + } + } + extension(C2) + { + public static C2 operator +(C2 x, C2 y) + { + System.Console.Write("C2"); + return x; + } + } + extension(C3) + { + public static C4 operator +(C3 x, C3 y) + { + System.Console.Write("C3"); + return null; + } + } + extension(C4) + { + public static C4 operator +(C4 x, C4 y) + { + System.Console.Write("C4"); + return x; + } + } +} + +public class C1; +public class C2 : C1; + +public class C3; +public class C4 : C3; + +class Program +{ + static void Main() + { + var c2 = new C2(); + _ = c2 += c2; + var c4 = new C4(); + _ = c4 += c4; + } +} +"""; + + var comp = CreateCompilation([src, OverloadResolutionPriorityAttributeDefinition], options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "C1C4").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_053_Consumption_OverloadResolutionPriority() + { + var src = $$$""" +using System.Runtime.CompilerServices; + +public static class Extensions1 +{ + extension(C1 x) + { + [OverloadResolutionPriority(1)] + public void operator +=(int y) + { + System.Console.Write("C1"); + } + } + extension(C2 x) + { + public void operator +=(int y) + { + System.Console.Write("C2"); + } + } + extension(C3 x) + { + public void operator +=(int y) + { + System.Console.Write("C3"); + } + } + extension(C4 x) + { + public void operator +=(int y) + { + System.Console.Write("C4"); + } + } +} + +public class C1; +public class C2 : C1; + +public class C3; +public class C4 : C3; + +class Program +{ + static void Main() + { + var c2 = new C2(); + _ = c2 += 1; + var c4 = new C4(); + _ = c4 += 1; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation([src, OverloadResolutionPriorityAttributeDefinition], options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "C1C4").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_054_Consumption_Checked() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator -(C1 x, C1 y) + { + System.Console.Write("regular"); + return x; + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = c1 -= c1; + + checked + { + _ = c1 -= c1; + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "regularregular").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_055_Consumption_Checked() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1 x) + { + public void operator -=(C1 y) + { + System.Console.Write("regular"); + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = c1 -= c1; + + checked + { + _ = c1 -= c1; + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "regularregular").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_056_Consumption_Checked_CheckedFormNotSupported() + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator |(C1 x, C1 y) => throw null; + public static C1 operator checked |(C1 x, C1 y) => throw null; + } +} + +public class C1; +"""; + + var comp1 = CreateCompilation(src1); + comp1.VerifyEmitDiagnostics( + // (6,35): error CS9023: User-defined operator '|' cannot be declared checked + // public static C1 operator checked |(C1 x, C1 y) => throw null; + Diagnostic(ErrorCode.ERR_OperatorCantBeChecked, "checked").WithArguments("|").WithLocation(6, 35), + // (6,43): error CS0111: Type 'Extensions1' already defines a member called 'op_BitwiseOr' with the same parameter types + // public static C1 operator checked |(C1 x, C1 y) => throw null; + Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "|").WithArguments("op_BitwiseOr", "Extensions1").WithLocation(6, 43) + ); + + var src2 = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator |(C1 x, C1 y) + { + System.Console.Write("regular"); + return x; + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = c1 |= c1; + + checked + { + _ = c1 |= c1; + } + } +} +"""; + + var comp2 = CreateCompilation(src2, options: TestOptions.DebugExe); + CompileAndVerify(comp2, expectedOutput: "regularregular").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_057_Consumption_Checked_CheckedFormNotSupported() + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator |(C1 x, C1 y) => throw null; + public static C1 operator checked |(C1 x, C1 y) => throw null; + } +} + +public class C1; +"""; + + var comp1 = CreateCompilation(src1); + comp1.VerifyEmitDiagnostics( + // (6,35): error CS9023: User-defined operator '|' cannot be declared checked + // public static C1 operator checked |(C1 x, C1 y) => throw null; + Diagnostic(ErrorCode.ERR_OperatorCantBeChecked, "checked").WithArguments("|").WithLocation(6, 35), + // (6,43): error CS0111: Type 'Extensions1' already defines a member called 'op_BitwiseOr' with the same parameter types + // public static C1 operator checked |(C1 x, C1 y) => throw null; + Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "|").WithArguments("op_BitwiseOr", "Extensions1").WithLocation(6, 43) + ); + + var src2 = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator |(C1 x, C1 y) + { + System.Console.Write("regular"); + return x; + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = c1 |= c1; + + checked + { + _ = c1 |= c1; + } + } +} +"""; + + var comp2 = CreateCompilation(src2, options: TestOptions.DebugExe); + CompileAndVerify(comp2, expectedOutput: "regularregular").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_058_Consumption_Checked_CheckedFormNotSupported() + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(C1 x) + { + public void operator |=(C1 y) => throw null; + public void operator checked |=(C1 y) => throw null; + } +} + +public class C1; + +""" + CompilerFeatureRequiredAttribute; + + var comp1 = CreateCompilation(src1); + comp1.VerifyEmitDiagnostics( + // (6,30): error CS9023: User-defined operator '|=' cannot be declared checked + // public void operator checked |=(C1 y) => throw null; + Diagnostic(ErrorCode.ERR_OperatorCantBeChecked, "checked").WithArguments("|=").WithLocation(6, 30), + // (6,38): error CS0111: Type 'Extensions1' already defines a member called 'op_BitwiseOrAssignment' with the same parameter types + // public void operator checked |=(C1 y) => throw null; + Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "|=").WithArguments("op_BitwiseOrAssignment", "Extensions1").WithLocation(6, 38) + ); + + var src2 = $$$""" +public static class Extensions1 +{ + extension(C1 x) + { + public void operator |=(C1 y) + { + System.Console.Write("regular"); + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = c1 |= c1; + + checked + { + _ = c1 |= c1; + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp2 = CreateCompilation(src2, options: TestOptions.DebugExe); + CompileAndVerify(comp2, expectedOutput: "regularregular").VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_059_Consumption_Checked([CombinatorialValues("+", "-", "*", "/")] string op, [CombinatorialValues("struct", "class")] string typeKind) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator {{{op}}}(C1 x, C1 y) + { + System.Console.Write("regular"); + return x; + } + public static C1 operator checked {{{op}}}(C1 x, C1 y) + { + System.Console.Write("checked"); + return x; + } + } +} + +public {{{typeKind}}} C1; +"""; + var src2 = $$$""" +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = c1 {{{op}}}= c1; + + checked + { + _ = c1 {{{op}}}= c1; + } + } +} +"""; + + var comp1 = CreateCompilation([src1, src2], options: TestOptions.DebugExe); + CompileAndVerify(comp1, expectedOutput: "regularchecked").VerifyDiagnostics(); + + var comp2 = CreateCompilation([src1, src2], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: "regularchecked").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1.ToMetadataReference()], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (6,13): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = c1 -= c1; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "c1 " + op + "= c1").WithArguments("extensions").WithLocation(6, 13), + // (10,17): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = c1 -= c1; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "c1 " + op + "= c1").WithArguments("extensions").WithLocation(10, 17) + ); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_060_Consumption_Checked([CombinatorialValues("+", "-", "*", "/")] string op, [CombinatorialValues("struct", "class")] string typeKind) + { + var src1 = $$$""" +public static class Extensions1 +{ + extension({{{(typeKind == "struct" ? "ref " : "")}}}C1 x) + { + public void operator {{{op}}}=(C1 y) + { + System.Console.Write("regular"); + } + public void operator checked {{{op}}}=(C1 y) + { + System.Console.Write("checked"); + } + } +} + +public {{{typeKind}}} C1; + +""" + CompilerFeatureRequiredAttribute; + + var src2 = $$$""" +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = c1 {{{op}}}= c1; + + checked + { + _ = c1 {{{op}}}= c1; + } + } +} +"""; + + var comp1 = CreateCompilation([src1, src2], options: TestOptions.DebugExe); + CompileAndVerify(comp1, expectedOutput: "regularchecked").VerifyDiagnostics(); + + var comp2 = CreateCompilation([src1, src2], options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp2, expectedOutput: "regularchecked").VerifyDiagnostics(); + + comp2 = CreateCompilation(src2, references: [comp1.ToMetadataReference()], options: TestOptions.DebugExe, parseOptions: TestOptions.Regular13); + comp2.VerifyEmitDiagnostics( + // (6,13): error CS0019: Operator '-=' cannot be applied to operands of type 'C1' and 'C1' + // _ = c1 -= c1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "c1 " + op + "= c1").WithArguments(op + "=", "C1", "C1").WithLocation(6, 13), + // (10,17): error CS0019: Operator '-=' cannot be applied to operands of type 'C1' and 'C1' + // _ = c1 -= c1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "c1 " + op + "= c1").WithArguments(op + "=", "C1", "C1").WithLocation(10, 17) + ); + } + + [Fact] + public void CompoundAssignment_061_Consumption_Checked() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator -(C1 x, C1 y) + { + System.Console.Write("regular"); + return x; + } + } + extension(C1) + { + public static C1 operator checked -(C1 x, C1 y) + { + System.Console.Write("checked"); + return x; + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = c1 -= c1; + + checked + { + _ = c1 -= c1; + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "regularchecked").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_062_Consumption_Checked() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1 x) + { + public void operator -=(C1 y) + { + System.Console.Write("regular"); + } + } + extension(C1 x) + { + public void operator checked -=(C1 y) + { + System.Console.Write("checked"); + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = c1 -= c1; + + checked + { + _ = c1 -= c1; + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "regularchecked").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_063_Consumption_Checked() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator -(C1 x, C1 y) + { + return x; + } + + public static C1 operator checked -(C1 x, C1 y) + { + return x; + } + } +} + +public static class Extensions2 +{ + extension(C1) + { + public static C1 operator -(C1 x, C1 y) + { + return x; + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = c1 -= c1; + + checked + { + _ = c1 -= c1; + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (35,13): error CS0034: Operator '-=' is ambiguous on operands of type 'C1' and 'C1' + // _ = c1 -= c1; + Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "c1 -= c1").WithArguments("-=", "C1", "C1").WithLocation(35, 13), + // (39,17): error CS0034: Operator '-=' is ambiguous on operands of type 'C1' and 'C1' + // _ = c1 -= c1; + Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "c1 -= c1").WithArguments("-=", "C1", "C1").WithLocation(39, 17) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().Last(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); + Assert.Equal(2, symbolInfo.CandidateSymbols.Length); + AssertEx.Equal("Extensions1.extension(C1).operator checked -(C1, C1)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("Extensions2.extension(C1).operator -(C1, C1)", symbolInfo.CandidateSymbols[1].ToDisplayString()); + } + + [Fact] + [WorkItem("https://github.com/dotnet/roslyn/issues/78968")] + public void CompoundAssignment_064_Consumption_Checked() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1 x) + { + public void operator -=(C1 y) + { + } + + public void operator checked -=(C1 y) + { + } + } +} + +public static class Extensions2 +{ + extension(C1 x) + { + public void operator -=(C1 y) + { + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); +#line 35 + _ = c1 -= c1; + + checked + { + _ = c1 -= c1; + } + } +} +"""; + + var comp = CreateCompilation([src, CompilerFeatureRequiredAttribute], options: TestOptions.DebugExe); + +#if DEBUG // Collection of extension blocks depends on GetTypeMembersUnordered for namespace, which conditionally de-orders types for DEBUG only. + comp.VerifyEmitDiagnostics( + // (35,16): error CS0121: The call is ambiguous between the following methods or properties: 'Extensions2.extension(C1).operator -=(C1)' and 'Extensions1.extension(C1).operator -=(C1)' + // _ = c1 -= c1; + Diagnostic(ErrorCode.ERR_AmbigCall, "-=").WithArguments("Extensions2.extension(C1).operator -=(C1)", "Extensions1.extension(C1).operator -=(C1)").WithLocation(35, 16), + // (39,20): error CS0121: The call is ambiguous between the following methods or properties: 'Extensions1.extension(C1).operator checked -=(C1)' and 'Extensions2.extension(C1).operator -=(C1)' + // _ = c1 -= c1; + Diagnostic(ErrorCode.ERR_AmbigCall, "-=").WithArguments("Extensions1.extension(C1).operator checked -=(C1)", "Extensions2.extension(C1).operator -=(C1)").WithLocation(39, 20) + ); +#else + // https://github.com/dotnet/roslyn/issues/78968: Understand what is causing DEBUG/RELEASE behavior difference + comp.VerifyEmitDiagnostics( + // (35,16): error CS0121: The call is ambiguous between the following methods or properties: 'Extensions1.extension(C1).operator -=(C1)' and 'Extensions2.extension(C1).operator -=(C1)' + // _ = c1 -= c1; + Diagnostic(ErrorCode.ERR_AmbigCall, "-=").WithArguments("Extensions1.extension(C1).operator -=(C1)", "Extensions2.extension(C1).operator -=(C1)").WithLocation(35, 16), + // (39,20): error CS0121: The call is ambiguous between the following methods or properties: 'Extensions1.extension(C1).operator checked -=(C1)' and 'Extensions2.extension(C1).operator -=(C1)' + // _ = c1 -= c1; + Diagnostic(ErrorCode.ERR_AmbigCall, "-=").WithArguments("Extensions1.extension(C1).operator checked -=(C1)", "Extensions2.extension(C1).operator -=(C1)").WithLocation(39, 20) + ); +#endif + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().Last(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); + Assert.Equal(2, symbolInfo.CandidateSymbols.Length); + AssertEx.Equal("Extensions1.extension(C1).operator checked -=(C1)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("Extensions2.extension(C1).operator -=(C1)", symbolInfo.CandidateSymbols[1].ToDisplayString()); + } + + [Fact] + public void CompoundAssignment_065_Consumption_CheckedLiftedIsWorse() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator -(S1 x, S1 y) => throw null; + public static S1 operator checked -(S1 x, S1 y) => throw null; + } + extension(S1?) + { + public static S1? operator -(S1? x, S1? y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? s1 = new S1(); + _ = s1 -= s1; + System.Console.Write(":"); + + checked + { + _ = s1 -= s1; + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1:operator1").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_066_Consumption_CheckedNoLiftedForm() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S1 x) + { + public void operator -=(int i) => throw null; + public void operator checked -=(int i) => throw null; + } + extension(ref S1? x) + { + public void operator -=(int i) + { + System.Console.Write("operator1"); + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? s1 = new S1(); + _ = s1 -= 1; + System.Console.Write(":"); + + checked + { + _ = s1 -= 1; + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1:operator1").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_067_Consumption_OverloadResolutionPlusRegularVsChecked() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C2 operator -(C1 x, C1 y) + { + System.Console.Write("C1"); + return (C2)x; + } + public static C2 operator checked -(C1 x, C1 y) + { + System.Console.Write("checkedC1"); + return (C2)x; + } + } + extension(C2) + { + public static C2 operator -(C2 x, C2 y) + { + System.Console.Write("C2"); + return x; + } + } +} + +public class C1; +public class C2 : C1; + +class Program +{ + static void Main() + { + C1 c1 = new C2(); + _ = c1 -= c1; + + checked + { + _ = c1 -= c1; + } + + var c2 = new C2(); + _ = c2 -= c2; + + checked + { + _ = c2 -= c2; + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "C1checkedC1C2C2").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_068_Consumption_OverloadResolutionPlusRegularVsChecked() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1 x) + { + public void operator -=(C1 y) + { + System.Console.Write("C1"); + } + public void operator checked -=(C1 y) + { + System.Console.Write("checkedC1"); + } + } + extension(C2 x) + { + public void operator -=(C2 y) + { + System.Console.Write("C2"); + } + } +} + +public class C1; +public class C2 : C1; +public class C3 : C1; + +class Program +{ + static void Main() + { + var c3 = new C3(); + _ = c3 -= c3; + + checked + { + _ = c3 -= c3; + } + + var c2 = new C2(); + _ = c2 -= c2; + + checked + { + _ = c2 -= c2; + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "C1checkedC1C2C2").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_069_Consumption_OnObject() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object) + { + public static object operator +(object x, object y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +class Program +{ + static void Main() + { + var s1 = new object(); + _ = s1 += s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_070_Consumption_OnObject() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object x) + { + public void operator +=(object y) + { + System.Console.Write("operator1"); + } + } +} + +class Program +{ + static void Main() + { + var s1 = new object(); + _ = s1 += s1; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_071_Consumption_NotOnDynamic() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object z) + { + public static object operator +(object x, object y) + { + System.Console.Write("operator1"); + return x; + } + + public void operator +=(object y) + { + System.Console.Write("operator2"); + } + } +} + +class Program +{ + static void Main() + { + dynamic s1 = new object(); + var s2 = new object(); + try + { + _ = s1 + s2; + } + catch + { + System.Console.Write("exception1"); + } + + try + { + _ = s2 + s1; + } + catch + { + System.Console.Write("exception2"); + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "exception1exception2").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_072_Consumption_WithLambda() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + public static S1 operator +(S1 x, System.Func y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} + +public class Program +{ + static void Main() + { + S1 s1 = new S1(); + _ = s1 += (() => 1); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_073_Consumption_WithLambda() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S1 x) + { + public void operator +=(System.Func y) + { + System.Console.Write("operator1"); + } + } +} + +public struct S1 +{} + +public class Program +{ + static void Main() + { + S1 s1 = new S1(); + _ = s1 += (() => 1); + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "operator1").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_074_Consumption_BadOperand() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S1 z) + { + public static S1 operator +(S1 x, S2 y) + { + System.Console.Write("operator1"); + return x; + } + public static S1 operator +(S2 y, S1 x) + { + System.Console.Write("operator2"); + return x; + } + public void operator +=(S2 y) + { + System.Console.Write("operator3"); + } + } +} + +public struct S1 +{} +public struct S2 +{} + +public class Program +{ + static void Main() + { + S1 s1 = new S1(); +#line 28 + _ = s1 += new(); + _ = new() += s1; + _ = new() += new(); + _ = s1 += default; + _ = default += s1; + _ = default += default; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (28,13): error CS8310: Operator '+=' cannot be applied to operand 'new()' + // _ = s1 += new(); + Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "s1 += new()").WithArguments("+=", "new()").WithLocation(28, 13), + // (29,13): error CS0131: The left-hand side of an assignment must be a variable, property or indexer + // _ = new() += s1; + Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "new()").WithLocation(29, 13), + // (30,13): error CS0131: The left-hand side of an assignment must be a variable, property or indexer + // _ = new() += new(); + Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "new()").WithLocation(30, 13), + // (31,13): error CS8310: Operator '+=' cannot be applied to operand 'default' + // _ = s1 += default; + Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "s1 += default").WithArguments("+=", "default").WithLocation(31, 13), + // (32,13): error CS0131: The left-hand side of an assignment must be a variable, property or indexer + // _ = default += s1; + Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default").WithLocation(32, 13), + // (33,13): error CS0131: The left-hand side of an assignment must be a variable, property or indexer + // _ = default += default; + Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default").WithLocation(33, 13) + ); + } + + [Fact] + public void CompoundAssignment_075_Consumption_BadOperand() + { + var src = $$$""" +public static class Extensions1 +{ + extension(object y) + { + public void operator +=(int i) + { + System.Console.Write("operator2"); + } + } +} + +class Program +{ + static object P {get; set;} + + static void Main() + { + _ = P += 1; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (18,13): error CS0019: Operator '+=' cannot be applied to operands of type 'object' and 'int' + // _ = P += 1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "P += 1").WithArguments("+=", "object", "int").WithLocation(18, 13) + ); + } + + [Fact] + public void CompoundAssignment_076_Consumption_BadReceiver() + { + var src = $$$""" +public static class Extensions1 +{ + extension(__arglist) + { + public static object operator +(object x, object y) + { + return x; + } + public void operator +=(object y) + { + } + } +} + +class Program +{ + static void Main() + { + var s1 = new object(); + _ = s1 += s1; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (3,15): error CS1669: __arglist is not valid in this context + // extension(__arglist) + Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(3, 15), + // (5,39): error CS9319: One of the parameters of a binary operator must be the extended type. + // public static object operator +(object x, object y) + Diagnostic(ErrorCode.ERR_BadExtensionBinaryOperatorSignature, "+").WithLocation(5, 39), + // (20,13): error CS0019: Operator '+=' cannot be applied to operands of type 'object' and 'object' + // _ = s1 += s1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 += s1").WithArguments("+=", "object", "object").WithLocation(20, 13) + ); + } + + [Fact] + public void CompoundAssignment_077_Consumption_Checked_Generic() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator -(C1 x, C1 y) + { + System.Console.Write("regular"); + return x; + } + } + extension(C1) + { + public static C1 operator checked -(C1 x, C1 y) + { + System.Console.Write("checked"); + return x; + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = c1 -= c1; + + checked + { + _ = c1 -= c1; + } + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "regularchecked").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_078_Consumption_Checked_Generic() + { + var src = $$$""" +public static class Extensions1 +{ + extension(C1 x) + { + public void operator -=(C1 y) + { + System.Console.Write("regular"); + } + } + extension(C1 x) + { + public void operator checked -=(C1 y) + { + System.Console.Write("checked"); + } + } +} + +public class C1; + +class Program +{ + static void Main() + { + var c1 = new C1(); + _ = c1 -= c1; + + checked + { + _ = c1 -= c1; + } + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "regularchecked").VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_079_Consumption_ExpressionTree() + { + var src = $$$""" +using System.Linq.Expressions; + +public static class Extensions1 +{ + extension(S1 s1) + { + public static S1 operator +(S1 x, S1 y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + Expression> ex = (s1) => s1 += s1; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (22,54): error CS0832: An expression tree may not contain an assignment operator + // Expression> ex = (s1) => s1 += s1; + Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "s1 += s1").WithLocation(22, 54) + ); + } + + [Fact] + public void CompoundAssignment_080_Consumption_ExpressionTree() + { + var src = $$$""" +using System.Linq.Expressions; + +public static class Extensions1 +{ + extension(ref S1 s1) + { + public void operator +=(S1 y) + { + System.Console.Write("operator1"); + } + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + Expression> ex = (s1) => s1 += s1; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyEmitDiagnostics( + // (21,54): error CS0832: An expression tree may not contain an assignment operator + // Expression> ex = (s1) => s1 += s1; + Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "s1 += s1").WithLocation(21, 54) + ); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Compound_01 + /// + [Fact] + public void CompoundAssignment_081_RefSafety() + { + var source = """ +public ref struct C +{ + public static C X(C left, C right) => right; + public C M(C c, scoped C c1) + { +#line 7 + c += c1; + c = c + c1; + c = X(c, c1); + return c; + } +} + +static class Extensions +{ + extension(C) + { + public static C operator +(C left, C right) => right; + } +} +"""; + CreateCompilation(source).VerifyDiagnostics( + // (7,9): error CS8347: Cannot use a result of 'Extensions.extension(C).operator +(C, C)' in this context because it may expose variables referenced by parameter 'right' outside of their declaration scope + // c += c1; + Diagnostic(ErrorCode.ERR_EscapeCall, "c += c1").WithArguments("Extensions.extension(C).operator +(C, C)", "right").WithLocation(7, 9), + // (7,14): error CS8352: Cannot use variable 'scoped C c1' in this context because it may expose referenced variables outside of their declaration scope + // c += c1; + Diagnostic(ErrorCode.ERR_EscapeVariable, "c1").WithArguments("scoped C c1").WithLocation(7, 14), + // (8,13): error CS8347: Cannot use a result of 'Extensions.extension(C).operator +(C, C)' in this context because it may expose variables referenced by parameter 'right' outside of their declaration scope + // c = c + c1; + Diagnostic(ErrorCode.ERR_EscapeCall, "c + c1").WithArguments("Extensions.extension(C).operator +(C, C)", "right").WithLocation(8, 13), + // (8,17): error CS8352: Cannot use variable 'scoped C c1' in this context because it may expose referenced variables outside of their declaration scope + // c = c + c1; + Diagnostic(ErrorCode.ERR_EscapeVariable, "c1").WithArguments("scoped C c1").WithLocation(8, 17), + // (9,13): error CS8347: Cannot use a result of 'C.X(C, C)' in this context because it may expose variables referenced by parameter 'right' outside of their declaration scope + // c = X(c, c1); + Diagnostic(ErrorCode.ERR_EscapeCall, "X(c, c1)").WithArguments("C.X(C, C)", "right").WithLocation(9, 13), + // (9,18): error CS8352: Cannot use variable 'scoped C c1' in this context because it may expose referenced variables outside of their declaration scope + // c = X(c, c1); + Diagnostic(ErrorCode.ERR_EscapeVariable, "c1").WithArguments("scoped C c1").WithLocation(9, 18) + ); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Compound_02 + /// + [Fact] + public void CompoundAssignment_082_RefSafety() + { + var source = """ +public ref struct C +{ + public static C X(C left, C right) => right; + public static C Y(C left) => left; + public C M1(C c, scoped C c1) + { +#line 8 + return Y(c += c1); + } + public C M2(C c, scoped C c1) + { + return Y(c = X(c, c1)); + } +} + +static class Extensions +{ + extension(C) + { + public static C operator +(C left, C right) => right; + } +} +"""; + CreateCompilation(source).VerifyDiagnostics( + // (8,16): error CS8347: Cannot use a result of 'C.Y(C)' in this context because it may expose variables referenced by parameter 'left' outside of their declaration scope + // return Y(c += c1); + Diagnostic(ErrorCode.ERR_EscapeCall, "Y(c += c1)").WithArguments("C.Y(C)", "left").WithLocation(8, 16), + // (8,18): error CS8347: Cannot use a result of 'Extensions.extension(C).operator +(C, C)' in this context because it may expose variables referenced by parameter 'right' outside of their declaration scope + // return Y(c += c1); + Diagnostic(ErrorCode.ERR_EscapeCall, "c += c1").WithArguments("Extensions.extension(C).operator +(C, C)", "right").WithLocation(8, 18), + // (8,18): error CS8347: Cannot use a result of 'Extensions.extension(C).operator +(C, C)' in this context because it may expose variables referenced by parameter 'right' outside of their declaration scope + // return Y(c += c1); + Diagnostic(ErrorCode.ERR_EscapeCall, "c += c1").WithArguments("Extensions.extension(C).operator +(C, C)", "right").WithLocation(8, 18), + // (8,23): error CS8352: Cannot use variable 'scoped C c1' in this context because it may expose referenced variables outside of their declaration scope + // return Y(c += c1); + Diagnostic(ErrorCode.ERR_EscapeVariable, "c1").WithArguments("scoped C c1").WithLocation(8, 23), + // (8,23): error CS8352: Cannot use variable 'scoped C c1' in this context because it may expose referenced variables outside of their declaration scope + // return Y(c += c1); + Diagnostic(ErrorCode.ERR_EscapeVariable, "c1").WithArguments("scoped C c1").WithLocation(8, 23), + // (12,22): error CS8347: Cannot use a result of 'C.X(C, C)' in this context because it may expose variables referenced by parameter 'right' outside of their declaration scope + // return Y(c = X(c, c1)); + Diagnostic(ErrorCode.ERR_EscapeCall, "X(c, c1)").WithArguments("C.X(C, C)", "right").WithLocation(12, 22), + // (12,27): error CS8352: Cannot use variable 'scoped C c1' in this context because it may expose referenced variables outside of their declaration scope + // return Y(c = X(c, c1)); + Diagnostic(ErrorCode.ERR_EscapeVariable, "c1").WithArguments("scoped C c1").WithLocation(12, 27) + ); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Compound_Scoped_Left + /// + [Fact] + public void CompoundAssignment_083_RefSafety() + { + var source = """ +public ref struct C +{ + public static C X(scoped C left, C right) => right; + public C M(C c, scoped C c1) + { +#line 7 + c += c1; + c = c + c1; + c = X(c, c1); + return c; + } +} + +static class Extensions +{ + extension(C) + { + public static C operator +(scoped C left, C right) => right; + } +} +"""; + CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( + // (7,9): error CS8347: Cannot use a result of 'Extensions.extension(C).operator +(scoped C, C)' in this context because it may expose variables referenced by parameter 'right' outside of their declaration scope + // c += c1; + Diagnostic(ErrorCode.ERR_EscapeCall, "c += c1").WithArguments("Extensions.extension(C).operator +(scoped C, C)", "right").WithLocation(7, 9), + // (7,14): error CS8352: Cannot use variable 'scoped C c1' in this context because it may expose referenced variables outside of their declaration scope + // c += c1; + Diagnostic(ErrorCode.ERR_EscapeVariable, "c1").WithArguments("scoped C c1").WithLocation(7, 14), + // (8,13): error CS8347: Cannot use a result of 'Extensions.extension(C).operator +(scoped C, C)' in this context because it may expose variables referenced by parameter 'right' outside of their declaration scope + // c = c + c1; + Diagnostic(ErrorCode.ERR_EscapeCall, "c + c1").WithArguments("Extensions.extension(C).operator +(scoped C, C)", "right").WithLocation(8, 13), + // (8,17): error CS8352: Cannot use variable 'scoped C c1' in this context because it may expose referenced variables outside of their declaration scope + // c = c + c1; + Diagnostic(ErrorCode.ERR_EscapeVariable, "c1").WithArguments("scoped C c1").WithLocation(8, 17), + // (9,13): error CS8347: Cannot use a result of 'C.X(scoped C, C)' in this context because it may expose variables referenced by parameter 'right' outside of their declaration scope + // c = X(c, c1); + Diagnostic(ErrorCode.ERR_EscapeCall, "X(c, c1)").WithArguments("C.X(scoped C, C)", "right").WithLocation(9, 13), + // (9,18): error CS8352: Cannot use variable 'scoped C c1' in this context because it may expose referenced variables outside of their declaration scope + // c = X(c, c1); + Diagnostic(ErrorCode.ERR_EscapeVariable, "c1").WithArguments("scoped C c1").WithLocation(9, 18) + ); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Compound_Scoped_Right + /// + [Fact] + public void CompoundAssignment_084_RefSafety() + { + var source = """ +public ref struct C +{ + public static C X(C left, scoped C right) => left; + public C M(C c, scoped C c1) + { + c += c1; + c = c + c1; + c = X(c, c1); + return c; + } +} + +static class Extensions +{ + extension(C) + { + public static C operator +(C left, scoped C right) => left; + } +} +"""; + CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics(); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Compound_Scoped_Both + /// + [Fact] + public void CompoundAssignment_085_RefSafety() + { + var source = """ +static class Extensions +{ + extension(C) + { +#line 3 + public static C operator +(scoped C left, scoped C right) => right; + } +} + +public ref struct C +{ +#line 4 + public static C X(scoped C left, scoped C right) => right; + public C M(C c, scoped C c1) + { + c += c1; + c = c + c1; + c = X(c, c1); + return c; + } +} +"""; + CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( + // (3,70): error CS8352: Cannot use variable 'scoped C right' in this context because it may expose referenced variables outside of their declaration scope + // public static C operator +(scoped C left, scoped C right) => right; + Diagnostic(ErrorCode.ERR_EscapeVariable, "right").WithArguments("scoped C right").WithLocation(3, 70), + // (4,57): error CS8352: Cannot use variable 'scoped C right' in this context because it may expose referenced variables outside of their declaration scope + // public static C X(scoped C left, scoped C right) => right; + Diagnostic(ErrorCode.ERR_EscapeVariable, "right").WithArguments("scoped C right").WithLocation(4, 57) + ); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Compound_ScopedTarget_01 + /// + [Fact] + public void CompoundAssignment_086_RefSafety() + { + var source = """ +public ref struct C +{ + public static C X(C left, C right) => right; + public C M(scoped C c, C c1) + { + c += c1; + c = c + c1; + c = X(c, c1); + return c1; + } +} + +static class Extensions +{ + extension(C) + { + public static C operator +(C left, C right) => right; + } +} +"""; + CreateCompilation(source).VerifyDiagnostics(); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Compound_ScopedTarget_02 + /// + [Fact] + public void CompoundAssignment_087_RefSafety() + { + var source = """ +public ref struct C +{ + public static C X(C left, C right) => right; + public static C Y(C left) => left; + public C M1(scoped C c, C c1) + { +#line 8 + return Y(c += c1); + } + public C M2(scoped C c, C c1) + { + return Y(c = X(c, c1)); + } +} + +static class Extensions +{ + extension(C) + { + public static C operator +(C left, C right) => right; + } +} +"""; + CreateCompilation(source).VerifyDiagnostics( + // (8,16): error CS8347: Cannot use a result of 'C.Y(C)' in this context because it may expose variables referenced by parameter 'left' outside of their declaration scope + // return Y(c += c1); + Diagnostic(ErrorCode.ERR_EscapeCall, "Y(c += c1)").WithArguments("C.Y(C)", "left").WithLocation(8, 16), + // (8,18): error CS8352: Cannot use variable 'scoped C c' in this context because it may expose referenced variables outside of their declaration scope + // return Y(c += c1); + Diagnostic(ErrorCode.ERR_EscapeVariable, "c").WithArguments("scoped C c").WithLocation(8, 18), + // (8,18): error CS8347: Cannot use a result of 'Extensions.extension(C).operator +(C, C)' in this context because it may expose variables referenced by parameter 'left' outside of their declaration scope + // return Y(c += c1); + Diagnostic(ErrorCode.ERR_EscapeCall, "c += c1").WithArguments("Extensions.extension(C).operator +(C, C)", "left").WithLocation(8, 18), + // (12,16): error CS8347: Cannot use a result of 'C.Y(C)' in this context because it may expose variables referenced by parameter 'left' outside of their declaration scope + // return Y(c = X(c, c1)); + Diagnostic(ErrorCode.ERR_EscapeCall, "Y(c = X(c, c1))").WithArguments("C.Y(C)", "left").WithLocation(12, 16), + // (12,18): error CS8352: Cannot use variable 'scoped C c' in this context because it may expose referenced variables outside of their declaration scope + // return Y(c = X(c, c1)); + Diagnostic(ErrorCode.ERR_EscapeVariable, "c = X(c, c1)").WithArguments("scoped C c").WithLocation(12, 18) + ); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Compound_ScopedTarget_03 + /// + [Fact] + public void CompoundAssignment_088_RefSafety() + { + var source = """ +public ref struct C +{ + public static C X(C left, scoped C right) => left; + public static C Y(C left) => left; + public C M1(scoped C c, C c1) + { +#line 8 + return Y(c += c1); + } + public C M2(scoped C c, C c1) + { + return Y(c = X(c, c1)); + } +} + +static class Extensions +{ + extension(C) + { + public static C operator +(C left, scoped C right) => left; + } +} +"""; + CreateCompilation(source).VerifyDiagnostics( + // (8,16): error CS8347: Cannot use a result of 'C.Y(C)' in this context because it may expose variables referenced by parameter 'left' outside of their declaration scope + // return Y(c += c1); + Diagnostic(ErrorCode.ERR_EscapeCall, "Y(c += c1)").WithArguments("C.Y(C)", "left").WithLocation(8, 16), + // (8,18): error CS8352: Cannot use variable 'scoped C c' in this context because it may expose referenced variables outside of their declaration scope + // return Y(c += c1); + Diagnostic(ErrorCode.ERR_EscapeVariable, "c").WithArguments("scoped C c").WithLocation(8, 18), + // (8,18): error CS8347: Cannot use a result of 'Extensions.extension(C).operator +(C, scoped C)' in this context because it may expose variables referenced by parameter 'left' outside of their declaration scope + // return Y(c += c1); + Diagnostic(ErrorCode.ERR_EscapeCall, "c += c1").WithArguments("Extensions.extension(C).operator +(C, scoped C)", "left").WithLocation(8, 18), + // (12,16): error CS8347: Cannot use a result of 'C.Y(C)' in this context because it may expose variables referenced by parameter 'left' outside of their declaration scope + // return Y(c = X(c, c1)); + Diagnostic(ErrorCode.ERR_EscapeCall, "Y(c = X(c, c1))").WithArguments("C.Y(C)", "left").WithLocation(12, 16), + // (12,18): error CS8352: Cannot use variable 'scoped C c' in this context because it may expose referenced variables outside of their declaration scope + // return Y(c = X(c, c1)); + Diagnostic(ErrorCode.ERR_EscapeVariable, "c = X(c, c1)").WithArguments("scoped C c").WithLocation(12, 18) + ); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Compound_ScopedTarget_04 + /// + [Fact] + public void CompoundAssignment_089_RefSafety() + { + var source = """ +public ref struct C +{ + public static C X(scoped C left, C right) => right; + public static C Y(C left) => left; + public C M1(scoped C c, C c1) + { + return Y(c += c1); + } + public C M2(scoped C c, C c1) + { +#line 12 + return Y(c = X(c, c1)); + } +} + +static class Extensions +{ + extension(C) + { + public static C operator +(scoped C left, C right) => right; + } +} +"""; + CreateCompilation(source).VerifyDiagnostics( + // (12,16): error CS8347: Cannot use a result of 'C.Y(C)' in this context because it may expose variables referenced by parameter 'left' outside of their declaration scope + // return Y(c = X(c, c1)); + Diagnostic(ErrorCode.ERR_EscapeCall, "Y(c = X(c, c1))").WithArguments("C.Y(C)", "left").WithLocation(12, 16), + // (12,18): error CS8352: Cannot use variable 'scoped C c' in this context because it may expose referenced variables outside of their declaration scope + // return Y(c = X(c, c1)); + Diagnostic(ErrorCode.ERR_EscapeVariable, "c = X(c, c1)").WithArguments("scoped C c").WithLocation(12, 18) + ); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Compound_Scoped_Left_ScopedTarget + /// + [Fact] + public void CompoundAssignment_090_RefSafety() + { + var source = """ +public ref struct C +{ + public static C X(scoped C left, C right) => right; + public C M(scoped C c, C c1) + { + c += c1; + c = c + c1; + c = X(c, c1); + return c1; + } +} + +static class Extensions +{ + extension(C) + { + public static C operator +(scoped C left, C right) => right; + } +} +"""; + CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics(); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Compound_Scoped_Right_ScopedTarget + /// + [Fact] + public void CompoundAssignment_091_RefSafety() + { + var source = """ +public ref struct C +{ + public static C X(C left, scoped C right) => left; + public C M(scoped C c, C c1) + { + c += c1; + c = c + c1; + c = X(c, c1); + return c1; + } +} + +static class Extensions +{ + extension(C) + { + public static C operator +(C left, scoped C right) => left; + } +} +"""; + CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics(); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Compound_Scoped_Both_ScopedTarget + /// + [Fact] + public void CompoundAssignment_092_RefSafety() + { + var source = """ +public ref struct C +{ + public static C X(scoped C left, scoped C right) => throw null; + public C M(scoped C c, C c1) + { + c += c1; + c = c + c1; + c = X(c, c1); + return c1; + } +} + +static class Extensions +{ + extension(C) + { + public static C operator +(scoped C left, scoped C right) => throw null; + } +} +"""; + CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics(); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Compound_RegressionTest1 + /// + [Fact] + public void CompoundAssignment_093_RefSafety() + { + var source = """ +using System; + +public ref struct S1 +{ + public S1(Span span) { } + + static void Test() + { + S1 stackLocal = new S1(stackalloc int[1]); + S1 heapLocal = new S1(default); + + stackLocal += stackLocal; + stackLocal += heapLocal; + heapLocal += heapLocal; +#line 16 + heapLocal += stackLocal; // 1 + + } +} + +static class Extensions +{ + extension(S1) + { + public static S1 operator +(S1 a, S1 b) => default; + } +} +"""; + var comp = CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp, options: TestOptions.UnsafeDebugDll); + comp.VerifyEmitDiagnostics( + // (16,9): error CS8347: Cannot use a result of 'Extensions.extension(S1).operator +(S1, S1)' in this context because it may expose variables referenced by parameter 'b' outside of their declaration scope + // heapLocal += stackLocal; // 1 + Diagnostic(ErrorCode.ERR_EscapeCall, "heapLocal += stackLocal").WithArguments("Extensions.extension(S1).operator +(S1, S1)", "b").WithLocation(16, 9), + // (16,22): error CS8352: Cannot use variable 'stackLocal' in this context because it may expose referenced variables outside of their declaration scope + // heapLocal += stackLocal; // 1 + Diagnostic(ErrorCode.ERR_EscapeVariable, "stackLocal").WithArguments("stackLocal").WithLocation(16, 22) + ); + } + + /// + /// This is a clone of Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics.RefEscapingTests.UserDefinedBinaryOperator_RefStruct_Compound_RegressionTest2 + /// + [Fact] + public void CompoundAssignment_094_RefSafety() + { + var source = """ +using System; + +public ref struct S1 +{ + public S1(Span span) { } + + static void Test() + { + S1 stackLocal = new(stackalloc int[1]); + S1 heapLocal = new(default); + + stackLocal += stackLocal; + stackLocal += heapLocal; + heapLocal += heapLocal; +#line 16 + heapLocal += stackLocal; // 1 + + } +} + +public ref struct S2 +{ + public S2(Span span) { } + + static void Test() + { + S2 stackLocal = new(stackalloc int[1]); + S2 heapLocal = new(default); + + stackLocal += stackLocal; + stackLocal += heapLocal; + heapLocal += heapLocal; + heapLocal += stackLocal; + } +} + +public ref struct S3 +{ + public S3(Span span) { } + + static void Test() + { + S3 stackLocal = new(stackalloc int[1]); + S3 heapLocal = new(default); + + stackLocal += stackLocal; + stackLocal += heapLocal; +#line 50 + heapLocal += heapLocal; // 2 + heapLocal += stackLocal; // 3 + } +} + +public ref struct S4 +{ + public S4(Span span) { } + + static void Test() + { + S4 stackLocal = new(stackalloc int[1]); + S4 heapLocal = new(default); + + stackLocal += stackLocal; + stackLocal += heapLocal; + heapLocal += heapLocal; +#line 68 + heapLocal += stackLocal; // 4 + } +} + +static class Extensions +{ + extension(S1) + { + public static S1 operator +(S1 a, S1 b) => default; + } + extension(S2) + { + public static S2 operator +(S2 a, scoped S2 b) => default; + } + extension(S3) + { + public static S3 operator +(in S3 a, in S3 b) => default; + } + extension(S4) + { + public static S4 operator +(scoped in S4 a, scoped in S4 b) => default; + } +} +"""; + var comp = CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp, options: TestOptions.UnsafeDebugDll); + comp.VerifyEmitDiagnostics( + // (16,9): error CS8347: Cannot use a result of 'Extensions.extension(S1).operator +(S1, S1)' in this context because it may expose variables referenced by parameter 'b' outside of their declaration scope + // heapLocal += stackLocal; // 1 + Diagnostic(ErrorCode.ERR_EscapeCall, "heapLocal += stackLocal").WithArguments("Extensions.extension(S1).operator +(S1, S1)", "b").WithLocation(16, 9), + // (16,22): error CS8352: Cannot use variable 'stackLocal' in this context because it may expose referenced variables outside of their declaration scope + // heapLocal += stackLocal; // 1 + Diagnostic(ErrorCode.ERR_EscapeVariable, "stackLocal").WithArguments("stackLocal").WithLocation(16, 22), + // (50,9): error CS8168: Cannot return local 'heapLocal' by reference because it is not a ref local + // heapLocal += heapLocal; // 2 + Diagnostic(ErrorCode.ERR_RefReturnLocal, "heapLocal").WithArguments("heapLocal").WithLocation(50, 9), + // (50,9): error CS8347: Cannot use a result of 'Extensions.extension(S3).operator +(in S3, in S3)' in this context because it may expose variables referenced by parameter 'a' outside of their declaration scope + // heapLocal += heapLocal; // 2 + Diagnostic(ErrorCode.ERR_EscapeCall, "heapLocal += heapLocal").WithArguments("Extensions.extension(S3).operator +(in S3, in S3)", "a").WithLocation(50, 9), + // (51,9): error CS8168: Cannot return local 'heapLocal' by reference because it is not a ref local + // heapLocal += stackLocal; // 3 + Diagnostic(ErrorCode.ERR_RefReturnLocal, "heapLocal").WithArguments("heapLocal").WithLocation(51, 9), + // (51,9): error CS8347: Cannot use a result of 'Extensions.extension(S3).operator +(in S3, in S3)' in this context because it may expose variables referenced by parameter 'a' outside of their declaration scope + // heapLocal += stackLocal; // 3 + Diagnostic(ErrorCode.ERR_EscapeCall, "heapLocal += stackLocal").WithArguments("Extensions.extension(S3).operator +(in S3, in S3)", "a").WithLocation(51, 9), + // (68,9): error CS8347: Cannot use a result of 'Extensions.extension(S4).operator +(scoped in S4, scoped in S4)' in this context because it may expose variables referenced by parameter 'b' outside of their declaration scope + // heapLocal += stackLocal; // 4 + Diagnostic(ErrorCode.ERR_EscapeCall, "heapLocal += stackLocal").WithArguments("Extensions.extension(S4).operator +(scoped in S4, scoped in S4)", "b").WithLocation(68, 9), + // (68,22): error CS8352: Cannot use variable 'stackLocal' in this context because it may expose referenced variables outside of their declaration scope + // heapLocal += stackLocal; // 4 + Diagnostic(ErrorCode.ERR_EscapeVariable, "stackLocal").WithArguments("stackLocal").WithLocation(68, 22) + ); + } + + [Fact] + public void CompoundAssignment_095_RefSafety() + { + var source = """ +public ref struct C +{ + public void X(C right) {} + public C M1(C c, C c1) + { + c += c1; + return c; + } + public C M2(C c, C c1) + { + c.X(c1); + return c; + } +} + +static class Extensions +{ + extension(scoped ref C left) + { + public void operator +=(C right) {} + } +} +"""; + CreateCompilation([source, CompilerFeatureRequiredAttribute]).VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_096_RefSafety() + { + var source = """ +public ref struct C +{ + public void X(C right) {} + public C M1(C c, scoped C c1) + { +#line 7 + c += c1; + return c; + } + public C M2(C c, scoped C c1) + { + c.X(c1); + return c; + } +} + +static class Extensions +{ + extension(scoped ref C left) + { + public void operator +=(C right) {} + } +} +"""; + CreateCompilation([source, CompilerFeatureRequiredAttribute]).VerifyDiagnostics( + // (7,9): error CS8350: This combination of arguments to 'Extensions.extension(scoped ref C).operator +=(C)' is disallowed because it may expose variables referenced by parameter 'right' outside of their declaration scope + // c += c1; + Diagnostic(ErrorCode.ERR_CallArgMixing, "c += c1").WithArguments("Extensions.extension(scoped ref C).operator +=(C)", "right").WithLocation(7, 9), + // (7,14): error CS8352: Cannot use variable 'scoped C c1' in this context because it may expose referenced variables outside of their declaration scope + // c += c1; + Diagnostic(ErrorCode.ERR_EscapeVariable, "c1").WithArguments("scoped C c1").WithLocation(7, 14), + // (12,9): error CS8350: This combination of arguments to 'C.X(C)' is disallowed because it may expose variables referenced by parameter 'right' outside of their declaration scope + // c.X(c1); + Diagnostic(ErrorCode.ERR_CallArgMixing, "c.X(c1)").WithArguments("C.X(C)", "right").WithLocation(12, 9), + // (12,13): error CS8352: Cannot use variable 'scoped C c1' in this context because it may expose referenced variables outside of their declaration scope + // c.X(c1); + Diagnostic(ErrorCode.ERR_EscapeVariable, "c1").WithArguments("scoped C c1").WithLocation(12, 13) + ); + } + + [Fact] + public void CompoundAssignment_097_RefSafety() + { + var source = """ +public ref struct C +{ + public void X(C right) {} + public C M1(scoped C c, C c1) + { + c += c1; +#line 8 + return c; + } + public C M2(scoped C c, C c1) + { + c.X(c1); + return c; + } +} + +static class Extensions +{ + extension(scoped ref C left) + { + public void operator +=(C right) {} + } +} +"""; + CreateCompilation([source, CompilerFeatureRequiredAttribute]).VerifyDiagnostics( + // (8,16): error CS8352: Cannot use variable 'scoped C c' in this context because it may expose referenced variables outside of their declaration scope + // return c; + Diagnostic(ErrorCode.ERR_EscapeVariable, "c").WithArguments("scoped C c").WithLocation(8, 16), + // (13,16): error CS8352: Cannot use variable 'scoped C c' in this context because it may expose referenced variables outside of their declaration scope + // return c; + Diagnostic(ErrorCode.ERR_EscapeVariable, "c").WithArguments("scoped C c").WithLocation(13, 16) + ); + } + + [Fact] + public void CompoundAssignment_098_RefSafety() + { + var source = """ +public ref struct C +{ + public void X(C right) {} + public C M1(scoped C c, scoped C c1) + { + c += c1; +#line 8 + return c; + } + public C M2(scoped C c, scoped C c1) + { + c.X(c1); + return c; + } +} + +static class Extensions +{ + extension(scoped ref C left) + { + public void operator +=(C right) {} + } +} +"""; + CreateCompilation([source, CompilerFeatureRequiredAttribute]).VerifyDiagnostics( + // (8,16): error CS8352: Cannot use variable 'scoped C c' in this context because it may expose referenced variables outside of their declaration scope + // return c; + Diagnostic(ErrorCode.ERR_EscapeVariable, "c").WithArguments("scoped C c").WithLocation(8, 16), + // (13,16): error CS8352: Cannot use variable 'scoped C c' in this context because it may expose referenced variables outside of their declaration scope + // return c; + Diagnostic(ErrorCode.ERR_EscapeVariable, "c").WithArguments("scoped C c").WithLocation(13, 16) + ); + } + + [Fact] + public void CompoundAssignment_099_RefSafety() + { + var source = """ +public ref struct C +{ + public void X(scoped C right) {} + public C M1(C c, scoped C c1) + { + c += c1; + return c; + } + public C M2(C c, scoped C c1) + { + c.X(c1); + return c; + } +} + +static class Extensions +{ + extension(scoped ref C left) + { + public void operator +=(scoped C right) {} + } +} +"""; + CreateCompilation([source, CompilerFeatureRequiredAttribute]).VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_100_RefSafety() + { + var source = """ +public ref struct C +{ + public C M1(C c, C c1) + { + return c += c1; + } +} + +static class Extensions +{ + extension(ref C left) + { + public void operator +=(C right) {} + } +} +"""; + CreateCompilation([source, CompilerFeatureRequiredAttribute]).VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_101_RefSafety() + { + var source = """ +public ref struct C +{ + public C M1(scoped C c, C c1) + { +#line 6 + return c += c1; + } +} + +static class Extensions +{ + extension(ref C left) + { + public void operator +=(C right) {} + } +} +"""; + CreateCompilation([source, CompilerFeatureRequiredAttribute]).VerifyDiagnostics( + // (6,16): error CS8352: Cannot use variable 'scoped C c' in this context because it may expose referenced variables outside of their declaration scope + // return c += c1; + Diagnostic(ErrorCode.ERR_EscapeVariable, "c").WithArguments("scoped C c").WithLocation(6, 16) + ); + } + + [Fact] + public void CompoundAssignment_102_RefSafety() + { + var source = """ +public ref struct C +{ + public C M1(C c, scoped C c1) + { +#line 6 + return c += c1; + } +} + +static class Extensions +{ + extension(ref C left) + { + public void operator +=(C right) {} + } +} +"""; + CreateCompilation([source, CompilerFeatureRequiredAttribute]).VerifyDiagnostics( + // (6,16): error CS8350: This combination of arguments to 'Extensions.extension(ref C).operator +=(C)' is disallowed because it may expose variables referenced by parameter 'right' outside of their declaration scope + // return c += c1; + Diagnostic(ErrorCode.ERR_CallArgMixing, "c += c1").WithArguments("Extensions.extension(ref C).operator +=(C)", "right").WithLocation(6, 16), + // (6,21): error CS8352: Cannot use variable 'scoped C c1' in this context because it may expose referenced variables outside of their declaration scope + // return c += c1; + Diagnostic(ErrorCode.ERR_EscapeVariable, "c1").WithArguments("scoped C c1").WithLocation(6, 21) + ); + } + + [Fact] + public void CompoundAssignment_103_RefSafety() + { + var source = """ +public ref struct C +{ + public C M1(C c, scoped C c1) + { + return c += c1; + } +} + +static class Extensions +{ + extension(ref C left) + { + public void operator +=(scoped C right) {} + } +} +"""; + CreateCompilation([source, CompilerFeatureRequiredAttribute]).VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_104_RefSafety() + { + var source = """ +public ref struct C +{ + public C M1(scoped C c, scoped C c1) + { +#line 6 + return c += c1; + } +} + +static class Extensions +{ + extension(ref C left) + { + public void operator +=(C right) {} + } +} +"""; + CreateCompilation([source, CompilerFeatureRequiredAttribute]).VerifyDiagnostics( + // (6,16): error CS8352: Cannot use variable 'scoped C c' in this context because it may expose referenced variables outside of their declaration scope + // return c += c1; + Diagnostic(ErrorCode.ERR_EscapeVariable, "c").WithArguments("scoped C c").WithLocation(6, 16) + ); + } + + [Fact] + public void CompoundAssignment_105_RefSafety() + { + var source = """ +public ref struct C +{ + static C X(C c) => throw null; + public C M1(scoped C c, scoped C c1) + { +#line 7 + return X(c += c1); + } +} + +static class Extensions +{ + extension(ref C left) + { + public void operator +=(C right) {} + } +} +"""; + CreateCompilation([source, CompilerFeatureRequiredAttribute]).VerifyDiagnostics( + // (7,16): error CS8347: Cannot use a result of 'C.X(C)' in this context because it may expose variables referenced by parameter 'c' outside of their declaration scope + // return X(c += c1); + Diagnostic(ErrorCode.ERR_EscapeCall, "X(c += c1)").WithArguments("C.X(C)", "c").WithLocation(7, 16), + // (7,18): error CS8352: Cannot use variable 'scoped C c' in this context because it may expose referenced variables outside of their declaration scope + // return X(c += c1); + Diagnostic(ErrorCode.ERR_EscapeVariable, "c").WithArguments("scoped C c").WithLocation(7, 18) + ); + } + + [Fact] + public void CompoundAssignment_106_RefSafety() + { + var source = $$$""" +ref struct C +{ + public C M1(C c1) + { +#line 8 + return c1 += 1; + } + public C M2(C c2) + { + return c2 -= 1; + } + public C M3(C c3, in int right) + { + return c3 += right; + } + public C M4(C c4, in int right) + { + return c4 -= right; + } +} + +static class Extensions +{ + extension(ref C x) + { + public void operator +=([System.Diagnostics.CodeAnalysis.UnscopedRef] in int right) {} + public static C operator -(C left, [System.Diagnostics.CodeAnalysis.UnscopedRef] in int right) => throw null; + } +} +"""; + CreateCompilation(source, targetFramework: TargetFramework.Net90).VerifyDiagnostics( + // (8,16): error CS8350: This combination of arguments to 'Extensions.extension(ref C).operator +=(in int)' is disallowed because it may expose variables referenced by parameter 'right' outside of their declaration scope + // return c1 += 1; + Diagnostic(ErrorCode.ERR_CallArgMixing, "c1 += 1").WithArguments("Extensions.extension(ref C).operator +=(in int)", "right").WithLocation(8, 16), + // (8,22): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference + // return c1 += 1; + Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "1").WithLocation(8, 22), + // (12,16): error CS8347: Cannot use a result of 'Extensions.extension(ref C).operator -(C, in int)' in this context because it may expose variables referenced by parameter 'right' outside of their declaration scope + // return c2 -= 1; + Diagnostic(ErrorCode.ERR_EscapeCall, "c2 -= 1").WithArguments("Extensions.extension(ref C).operator -(C, in int)", "right").WithLocation(12, 16), + // (12,16): error CS8347: Cannot use a result of 'Extensions.extension(ref C).operator -(C, in int)' in this context because it may expose variables referenced by parameter 'right' outside of their declaration scope + // return c2 -= 1; + Diagnostic(ErrorCode.ERR_EscapeCall, "c2 -= 1").WithArguments("Extensions.extension(ref C).operator -(C, in int)", "right").WithLocation(12, 16), + // (12,22): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference + // return c2 -= 1; + Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "1").WithLocation(12, 22), + // (12,22): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference + // return c2 -= 1; + Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "1").WithLocation(12, 22), + // (16,16): error CS8350: This combination of arguments to 'Extensions.extension(ref C).operator +=(in int)' is disallowed because it may expose variables referenced by parameter 'right' outside of their declaration scope + // return c3 += right; + Diagnostic(ErrorCode.ERR_CallArgMixing, "c3 += right").WithArguments("Extensions.extension(ref C).operator +=(in int)", "right").WithLocation(16, 16), + // (16,22): error CS9077: Cannot return a parameter by reference 'right' through a ref parameter; it can only be returned in a return statement + // return c3 += right; + Diagnostic(ErrorCode.ERR_RefReturnOnlyParameter, "right").WithArguments("right").WithLocation(16, 22), + // (20,16): error CS8347: Cannot use a result of 'Extensions.extension(ref C).operator -(C, in int)' in this context because it may expose variables referenced by parameter 'right' outside of their declaration scope + // return c4 -= right; + Diagnostic(ErrorCode.ERR_EscapeCall, "c4 -= right").WithArguments("Extensions.extension(ref C).operator -(C, in int)", "right").WithLocation(20, 16), + // (20,22): error CS9077: Cannot return a parameter by reference 'right' through a ref parameter; it can only be returned in a return statement + // return c4 -= right; + Diagnostic(ErrorCode.ERR_RefReturnOnlyParameter, "right").WithArguments("right").WithLocation(20, 22) + ); + } + + [Fact] + public void CompoundAssignment_107_RefSafety() + { + var source = """ +ref struct C +{ + public C M1(C c1) + { + return c1 += 1; + } + public C M2(C c2) + { +#line 12 + return c2 -= 1; + } + public C M3(C c3, in int right) + { + return c3 += right; + } + public C M4(C c4, in int right) + { + return c4 -= right; + } +} + +static class Extensions +{ + extension(ref C x) + { + public void operator +=(in int right) {} + public static C operator -(C left, in int right) => throw null; + } +} +"""; + CreateCompilation(source, targetFramework: TargetFramework.Net90).VerifyDiagnostics( + // (12,16): error CS8347: Cannot use a result of 'Extensions.extension(ref C).operator -(C, in int)' in this context because it may expose variables referenced by parameter 'right' outside of their declaration scope + // return c2 -= 1; + Diagnostic(ErrorCode.ERR_EscapeCall, "c2 -= 1").WithArguments("Extensions.extension(ref C).operator -(C, in int)", "right").WithLocation(12, 16), + // (12,16): error CS8347: Cannot use a result of 'Extensions.extension(ref C).operator -(C, in int)' in this context because it may expose variables referenced by parameter 'right' outside of their declaration scope + // return c2 -= 1; + Diagnostic(ErrorCode.ERR_EscapeCall, "c2 -= 1").WithArguments("Extensions.extension(ref C).operator -(C, in int)", "right").WithLocation(12, 16), + // (12,22): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference + // return c2 -= 1; + Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "1").WithLocation(12, 22), + // (12,22): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference + // return c2 -= 1; + Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "1").WithLocation(12, 22), + // (20,16): error CS8347: Cannot use a result of 'Extensions.extension(ref C).operator -(C, in int)' in this context because it may expose variables referenced by parameter 'right' outside of their declaration scope + // return c4 -= right; + Diagnostic(ErrorCode.ERR_EscapeCall, "c4 -= right").WithArguments("Extensions.extension(ref C).operator -(C, in int)", "right").WithLocation(20, 16), + // (20,22): error CS9077: Cannot return a parameter by reference 'right' through a ref parameter; it can only be returned in a return statement + // return c4 -= right; + Diagnostic(ErrorCode.ERR_RefReturnOnlyParameter, "right").WithArguments("right").WithLocation(20, 22) + ); + } + + [Fact] + public void CompoundAssignment_108_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1) + { + public static C1 operator -(C1 x, C1 y) + { + System.Console.Write("operator1"); + return x; + } + } + + extension(C2) + { + public static C2 operator -(C2? x, C2? y) + { + System.Console.Write("operator2"); + return new C2(); + } + } +} + +public class C1 +{} + +public class C2 +{} + +class Program +{ + static void Main() + { + C1? x1 = null; + C1? x2 = null; + C1 y = new C1(); +#line 25 + _ = x1 -= y; + y = y -= x2; + + C2? z = null; + _ = z -= z; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (25,13): warning CS8604: Possible null reference argument for parameter 'x' in 'C1 extension(C1).operator -(C1 x, C1 y)'. + // _ = x1 -= y; + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "C1 extension(C1).operator -(C1 x, C1 y)").WithLocation(25, 13), + // (26,18): warning CS8604: Possible null reference argument for parameter 'y' in 'C1 extension(C1).operator -(C1 x, C1 y)'. + // y = y -= x2; + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("y", "C1 extension(C1).operator -(C1 x, C1 y)").WithLocation(26, 18) + ); + } + + [Fact] + public void CompoundAssignment_109_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1) + { + public static C1? operator -(C1 x, C1 y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public class C1 +{} + +class Program +{ + static void Main() + { + var x = new C1(); + C1 y = x -= x; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (23,16): warning CS8600: Converting null literal or possible null value to non-nullable type. + // C1 y = x -= x; + Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x -= x").WithLocation(23, 16) + ); + } + + [Fact] + public void CompoundAssignment_110_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(T) + { + public static T operator -(T x, T y) + { + return x; + } + } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + C2? x1 = null; + C2? x2 = null; + var y = new C2(); + (x1 -= y).ToString(); + (y -= x2).ToString(); + y.ToString(); + var z = new C2(); + (z -= z).ToString(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (24,10): warning CS8602: Dereference of a possibly null reference. + // (x1 -= y).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1 -= y").WithLocation(24, 10), + // (25,10): warning CS8602: Dereference of a possibly null reference. + // (y -= x2).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y -= x2").WithLocation(25, 10), + // (26,9): warning CS8602: Dereference of a possibly null reference. + // y.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(26, 9) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNodes = tree.GetRoot().DescendantNodes().OfType().ToArray(); + + Assert.Equal(3, opNodes.Length); + AssertEx.Equal("Extensions1.extension(C2?).operator -(C2?, C2?)", model.GetSymbolInfo(opNodes[0]).Symbol.ToDisplayString()); + AssertEx.Equal("Extensions1.extension(C2?).operator -(C2?, C2?)", model.GetSymbolInfo(opNodes[1]).Symbol.ToDisplayString()); + AssertEx.Equal("Extensions1.extension(C2).operator -(C2, C2)", model.GetSymbolInfo(opNodes[2]).Symbol.ToDisplayString()); + } + + [Fact] + public void CompoundAssignment_111_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(T) + { + public static T operator -(T x, int y) + { + return x; + } + } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + C2? x = null; + var y = new C2(); + (x -= 1).ToString(); + (y -= 1).ToString(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (23,10): warning CS8602: Dereference of a possibly null reference. + // (x -= 1).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x -= 1").WithLocation(23, 10) + ); + } + + [Fact] + public void CompoundAssignment_112_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1) where T : new() where S : new() + { + public static C1 operator -(C1 x, C1 y) + { + return x; + } + } +} + +public class C1 where T : new() +{ + public T F = new T(); +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = Get((C2?)null); + var y = Get(new C2()); + + (x -= y).F.ToString(); + (y -= x).F.ToString(); + } + + static C1 Get(T x) where T : new() + { + return new C1(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (29,9): warning CS8602: Dereference of a possibly null reference. + // (x -= y).F.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(x -= y).F").WithLocation(29, 9) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNodes = tree.GetRoot().DescendantNodes().OfType().ToArray(); + + Assert.Equal(2, opNodes.Length); + AssertEx.Equal("Extensions1.extension(C1).operator -(C1, C1)", model.GetSymbolInfo(opNodes[0]).Symbol.ToDisplayString()); + AssertEx.Equal("Extensions1.extension(C1).operator -(C1, C1)", model.GetSymbolInfo(opNodes[1]).Symbol.ToDisplayString()); + } + + [Fact] + public void CompoundAssignment_113_NullableAnalysis_Lifted() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(S1) where T : new() + { + public static S1 operator -(S1 x, int y) + { + return x; + } + } +} + +public struct S1 where T : new() +{ + public T F; +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = Get((C2?)null) -= 1; + + if (x != null) + x.Value.F.ToString(); + + var y = Get(new C2()) -= 1; + + if (y != null) + y.Value.F.ToString(); + } + + static ref S1? Get(T x) where T : new() + { + throw null!; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (29,13): warning CS8602: Dereference of a possibly null reference. + // x.Value.F.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Value.F").WithLocation(29, 13) + ); + } + + [Fact] + public void CompoundAssignment_114_NullableAnalysis_Constraints() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(T) where T : notnull + { + public static C2 operator -(T x, T y) + { + return (C2)(object)x; + } + } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + C2? x = null; + var y = new C2(); + (x -= y).ToString(); + x = null; +#line 24 + (y -= x).ToString(); + + var z = new C2(); + (z -= z).ToString(); + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (23,10): warning CS8714: The type 'C2?' cannot be used as type parameter 'T' in the generic type or method 'Extensions1.extension(T)'. Nullability of type argument 'C2?' doesn't match 'notnull' constraint. + // (x -= y).ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "x -= y").WithArguments("Extensions1.extension(T)", "T", "C2?").WithLocation(23, 10), + // (24,10): warning CS8714: The type 'C2?' cannot be used as type parameter 'T' in the generic type or method 'Extensions1.extension(T)'. Nullability of type argument 'C2?' doesn't match 'notnull' constraint. + // (y -= x).ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "y -= x").WithArguments("Extensions1.extension(T)", "T", "C2?").WithLocation(24, 10) + ); + } + + [Fact] + public void CompoundAssignment_115_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1 x) + { + public void operator -=(C1 y) {} + } + + extension(C2? x) + { + public void operator -=(C2? y) {} + } +} + +public class C1 +{} + +public class C2 +{} + +class Program +{ + static void Main() + { + C1? x1 = null; + C1? x2 = null; + C1 y = new C1(); +#line 25 + _ = x1 -= y; + y = y -= x2; + + C2? z = null; + _ = z -= z; + + C2 a = new C2(); + C2? b = null; + C2 c = a -= b; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (25,13): warning CS8604: Possible null reference argument for parameter 'x' in 'extension(C1)'. + // _ = x1 -= y; + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "extension(C1)").WithLocation(25, 13), + // (26,18): warning CS8604: Possible null reference argument for parameter 'y' in 'void extension(C1).operator -=(C1 y)'. + // y = y -= x2; + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("y", "void extension(C1).operator -=(C1 y)").WithLocation(26, 18) + ); + } + + [Fact] + public void CompoundAssignment_116_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +using System.Diagnostics.CodeAnalysis; + +public static class Extensions1 +{ + extension([NotNull] ref S1? x) + { + public void operator -=(int y) { throw null!; } + } + + extension([NotNull] C2? x) + { + public void operator -=(int y) { throw null!; } + } +} + +public struct S1 +{} + +public class C2 +{} + +class Program +{ + static void Main() + { + S1? x = null; + var x1 = x -= 1; + _ = x.Value; + _ = x1.Value; + + C2? z = null; + var z1 = z -= 1; + z.ToString(); + z1.ToString(); + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: TestOptions.DebugExe); + comp.VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_117_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(ref S1? x) + { + public void operator -=(int y) {} + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + S1? x = null; + var x1 = x -= 1; + _ = x.Value; + _ = x1.Value; + + S1? y = new S1(); + var y1 = y -= 1; + _ = y.Value; + _ = y1.Value; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (20,13): warning CS8629: Nullable value type may be null. + // _ = x.Value; + Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x").WithLocation(20, 13), + // (21,13): warning CS8629: Nullable value type may be null. + // _ = x1.Value; + Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x1").WithLocation(21, 13), + // (25,13): warning CS8629: Nullable value type may be null. + // _ = y.Value; + Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y").WithLocation(25, 13), + // (26,13): warning CS8629: Nullable value type may be null. + // _ = y1.Value; + Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y1").WithLocation(26, 13) + ); + } + + [Fact] + public void CompoundAssignment_118_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(ref S1? x) + { + public void operator -=(int y) {} + } +} + +public struct S1 +{} + +class Program +{ + static void Main() + { + _ = Get(new S1()).Value; + var y1 = Get(new S1()) -= 1; +#line 26 + _ = y1.Value; + } + + [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull("x")] + static ref S1? Get(S1? x) => throw null!; +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (26,13): warning CS8629: Nullable value type may be null. + // _ = y1.Value; + Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y1").WithLocation(26, 13) + ); + } + + [Fact] + public void CompoundAssignment_119_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1Base x) + { + public void operator -=(int y) {} + } + + extension(C2Base? x) + { + public void operator -=(int y) {} + } +} + +public class C1Base {} +public class C1 : C1Base {} + +public class C2Base {} +public class C2 : C2Base {} + +class Program +{ + static void Main() + { + C1? x = null; + var x1 = x -= 1; + x.ToString(); + x1.ToString(); + + C1 y = new C1(); + var y1 = y -= 1; + y.ToString(); + y1.ToString(); + + C2? z = null; + var z1 = z -= 1; + z.ToString(); + z1.ToString(); + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (27,18): warning CS8604: Possible null reference argument for parameter 'x' in 'extension(C1Base)'. + // var x1 = x -= 1; + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "extension(C1Base)").WithLocation(27, 18), + // (38,9): warning CS8602: Dereference of a possibly null reference. + // z.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(38, 9), + // (39,9): warning CS8602: Dereference of a possibly null reference. + // z1.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z1").WithLocation(39, 9) + ); + } + + [Fact] + public void CompoundAssignment_120_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C2Base x) + { + public void operator -=(int y) {} + } +} + +public class C2Base {} +public class C2 : C2Base {} + +class Program +{ + static void Main() + { + C2 z = new C2(); + var z1 = z -= 1; + z.ToString(); + z1.ToString(); + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (19,18): warning CS8620: Argument of type 'C2' cannot be used for parameter 'x' of type 'C2Base' in 'extension(C2Base)' due to differences in the nullability of reference types. + // var z1 = z -= 1; + Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("C2", "C2Base", "x", "extension(C2Base)").WithLocation(19, 18) + ); + } + + [Fact] + public void CompoundAssignment_121_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +using System.Diagnostics.CodeAnalysis; + +public static class Extensions1 +{ + extension([NotNull] C2Base? x) + { + public void operator -=(int y) { throw null!; } + } +} + +public class C2Base +{} + +public class C2 : C2Base +{} + +class Program +{ + static void Main() + { + C2? z = null; + var z1 = z -= 1; + z.ToString(); + z1.ToString(); + } +} +"""; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: TestOptions.DebugExe); + comp.VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_122_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(T x) where T : class? + { + public void operator -=(int y) {} + } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + C2? x = null; + (x -= 1).ToString(); + var y = new C2(); + (y -= 1).ToString(); + } +} +"""; + + var comp = CreateCompilation([src, CompilerFeatureRequiredAttribute], options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (19,10): warning CS8602: Dereference of a possibly null reference. + // (x -= 1).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x -= 1").WithLocation(19, 10) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNodes = tree.GetRoot().DescendantNodes().OfType().ToArray(); + + Assert.Equal(2, opNodes.Length); + AssertEx.Equal("Extensions1.extension(C2?).operator -=(int)", model.GetSymbolInfo(opNodes[0]).Symbol.ToDisplayString()); + AssertEx.Equal("Extensions1.extension(C2).operator -=(int)", model.GetSymbolInfo(opNodes[1]).Symbol.ToDisplayString()); + } + + [Fact] + public void CompoundAssignment_123_NullableAnalysis() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1 x) where T : new() + { + public void operator -=(int y) {} + } +} + +public class C1 where T : new() +{ + public T F = new T(); +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = Get((C2?)null); + (x -= 1).F.ToString(); + var y = Get(new C2()); + (y -= 1).F.ToString(); + } + + static C1 Get(T x) where T : new() + { + return new C1(); + } +} +"""; + + var comp = CreateCompilation([src, CompilerFeatureRequiredAttribute], options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (24,9): warning CS8602: Dereference of a possibly null reference. + // (x -= 1).F.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(x -= 1).F").WithLocation(24, 9) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNodes = tree.GetRoot().DescendantNodes().OfType().ToArray(); + + Assert.Equal(2, opNodes.Length); + AssertEx.Equal("Extensions1.extension(C1).operator -=(int)", model.GetSymbolInfo(opNodes[0]).Symbol.ToDisplayString()); + AssertEx.Equal("Extensions1.extension(C1).operator -=(int)", model.GetSymbolInfo(opNodes[1]).Symbol.ToDisplayString()); + } + + [Fact] + public void CompoundAssignment_124_NullableAnalysis_Constraints() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(T x) where T : class + { + public void operator -=(int y) {} + } +} + +public class C2 +{} + +class Program +{ + static void Main() + { + C2? x = null; + (x -= 1).ToString(); + var y = new C2(); + (y -= 1).ToString(); + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (19,10): warning CS8634: The type 'C2?' cannot be used as type parameter 'T' in the generic type or method 'Extensions1.extension(T)'. Nullability of type argument 'C2?' doesn't match 'class' constraint. + // (x -= 1).ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "x -= 1").WithArguments("Extensions1.extension(T)", "T", "C2?").WithLocation(19, 10), + // (19,10): warning CS8602: Dereference of a possibly null reference. + // (x -= 1).ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x -= 1").WithLocation(19, 10) + ); + } + + [Fact] + public void CompoundAssignment_125_NullableAnalysis_Constraints() + { + var src = $$$""" +#nullable enable + +public static class Extensions1 +{ + extension(C1 x) where T : notnull, new() + { + public void operator -=(int y) {} + } +} + +public class C1 where T : new() +{ + public T F = new T(); +} + +public class C2 +{} + +class Program +{ + static void Main() + { + var x = Get((C2?)null); + (x -= 1).F.ToString(); + var y = Get(new C2()); + (y -= 1).F.ToString(); + } + + static C1 Get(T x) where T : new() + { + return new C1(); + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (24,9): warning CS8602: Dereference of a possibly null reference. + // (x -= 1).F.ToString(); + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(x -= 1).F").WithLocation(24, 9), + // (24,10): warning CS8714: The type 'C2?' cannot be used as type parameter 'T' in the generic type or method 'Extensions1.extension(C1)'. Nullability of type argument 'C2?' doesn't match 'notnull' constraint. + // (x -= 1).F.ToString(); + Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "x -= 1").WithArguments("Extensions1.extension(C1)", "T", "C2?").WithLocation(24, 10) + ); + } + + [Fact] + public void CompoundAssignment_126_Declaration_Extern() + { + var src = $$$""" +using System.Runtime.InteropServices; + +public static class Extensions1 +{ + extension(C2 x) + { + extern public void operator -=(C2 y) {} + + [DllImport("something.dll")] + public void operator +=(C2 y) {} + } +} + +public class C2 +{} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src); + comp.VerifyDiagnostics( + // (7,37): error CS0179: 'Extensions1.extension(C2).operator -=(C2)' cannot be extern and declare a body + // extern public void operator -=(C2 y) {} + Diagnostic(ErrorCode.ERR_ExternHasBody, "-=").WithArguments("Extensions1.extension(C2).operator -=(C2)").WithLocation(7, 37), + // (9,10): error CS0601: The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member + // [DllImport("something.dll")] + Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(9, 10) + ); + } + + [Fact] + public void CompoundAssignment_127_Declaration_Extern() + { + var source = """ +using System.Runtime.InteropServices; +static class E +{ + extension(C2 x) + { + [DllImport("something.dll")] + extern public void operator -=(C2 y); + } +} + +public class C2 +{} + +""" + CompilerFeatureRequiredAttribute; + + var verifier = CompileAndVerify(source).VerifyDiagnostics(); + + verifier.VerifyTypeIL("E", """ +.class private auto ansi abstract sealed beforefieldinit E + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( + 01 00 00 00 + ) + // Nested Types + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + // Methods + .method private hidebysig specialname static + void '$' ( + class C2 x + ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( + 01 00 00 00 + ) + // Method begins at RVA 0x2097 + // Code size 1 (0x1) + .maxstack 8 + IL_0000: ret + } // end of method '<>E__0'::'$' + .method public hidebysig specialname + instance void op_SubtractionAssignment ( + class C2 y + ) cil managed + { + .custom instance void System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute::.ctor(string) = ( + 01 00 26 55 73 65 72 44 65 66 69 6e 65 64 43 6f + 6d 70 6f 75 6e 64 41 73 73 69 67 6e 6d 65 6e 74 + 4f 70 65 72 61 74 6f 72 73 00 00 + ) + // Method begins at RVA 0x2099 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::op_SubtractionAssignment + } // end of class <>E__0 + // Methods + .method public hidebysig static pinvokeimpl("something.dll" winapi) + void op_SubtractionAssignment ( + class C2 x, + class C2 y + ) cil managed preservesig + { + } // end of method E::op_SubtractionAssignment +} // end of class E +""".Replace("[mscorlib]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[mscorlib]")); + } + + [Fact] + public void CompoundAssignment_128_Declaration_Extern() + { + var source = """ +static class E +{ + extension(C2 x) + { + extern public void operator -=(C2 y); + } +} + +public class C2 +{} + +""" + CompilerFeatureRequiredAttribute; + + var verifier = CompileAndVerify(source, verify: Verification.FailsPEVerify with { PEVerifyMessage = """ + Error: Method marked Abstract, Runtime, InternalCall or Imported must have zero RVA, and vice versa. + Type load failed. + """ }); + + verifier.VerifyDiagnostics( + // (5,37): warning CS0626: Method, operator, or accessor 'E.extension(C2).operator -=(C2)' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. + // extern public void operator -=(C2 y); + Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "-=").WithArguments("E.extension(C2).operator -=(C2)").WithLocation(5, 37) + ); + + verifier.VerifyTypeIL("E", """ +.class private auto ansi abstract sealed beforefieldinit E + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( + 01 00 00 00 + ) + // Nested Types + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + // Methods + .method private hidebysig specialname static + void '$' ( + class C2 x + ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( + 01 00 00 00 + ) + // Method begins at RVA 0x2097 + // Code size 1 (0x1) + .maxstack 8 + IL_0000: ret + } // end of method '<>E__0'::'$' + .method public hidebysig specialname + instance void op_SubtractionAssignment ( + class C2 y + ) cil managed + { + .custom instance void System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute::.ctor(string) = ( + 01 00 26 55 73 65 72 44 65 66 69 6e 65 64 43 6f + 6d 70 6f 75 6e 64 41 73 73 69 67 6e 6d 65 6e 74 + 4f 70 65 72 61 74 6f 72 73 00 00 + ) + // Method begins at RVA 0x2099 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::op_SubtractionAssignment + } // end of class <>E__0 + // Methods + .method public hidebysig static + void op_SubtractionAssignment ( + class C2 x, + class C2 y + ) cil managed + { + } // end of method E::op_SubtractionAssignment +} // end of class E +""".Replace("[mscorlib]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[mscorlib]")); + } + + [Fact] + public void CompoundAssignment_129_Declaration_Extern() + { + var source = """ +static class E +{ + extension(C2 x) + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)] + extern public void operator -=(C2 y); + } +} + +public class C2 +{} + +""" + CompilerFeatureRequiredAttribute; + + var verifier = CompileAndVerify(source).VerifyDiagnostics(); + + verifier.VerifyTypeIL("E", """ +.class private auto ansi abstract sealed beforefieldinit E + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( + 01 00 00 00 + ) + // Nested Types + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + // Methods + .method private hidebysig specialname static + void '$' ( + class C2 x + ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( + 01 00 00 00 + ) + // Method begins at RVA 0x2097 + // Code size 1 (0x1) + .maxstack 8 + IL_0000: ret + } // end of method '<>E__0'::'$' + .method public hidebysig specialname + instance void op_SubtractionAssignment ( + class C2 y + ) cil managed + { + .custom instance void System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute::.ctor(string) = ( + 01 00 26 55 73 65 72 44 65 66 69 6e 65 64 43 6f + 6d 70 6f 75 6e 64 41 73 73 69 67 6e 6d 65 6e 74 + 4f 70 65 72 61 74 6f 72 73 00 00 + ) + // Method begins at RVA 0x2099 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::op_SubtractionAssignment + } // end of class <>E__0 + // Methods + .method public hidebysig static + void op_SubtractionAssignment ( + class C2 x, + class C2 y + ) cil managed internalcall + { + } // end of method E::op_SubtractionAssignment +} // end of class E +""".Replace("[mscorlib]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[mscorlib]")); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_130_Consumption_CRef([CombinatorialValues("+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", ">>>=")] string op) + { + var src = $$$""" +/// +/// +public static class E +{ + /// + extension(S1 x) + { + /// + public void operator {{{op}}}(S1 y) => throw null; + } +} + +/// +public class S1; +"""; + + var comp = CreateCompilation([src, CompilerFeatureRequiredAttribute], parseOptions: TestOptions.RegularPreviewWithDocumentationComments); + comp.VerifyEmitDiagnostics(); + + var opName = CompoundAssignmentOperatorName(op); + + var e = comp.GetMember("E"); + AssertEx.Equal($$$""" + + + + + +""", e.GetDocumentationCommentXml()); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + AssertEx.Equal([ + "(E.extension(S1).operator " + ToCRefOp(op) + ", void E.<>E__0." + opName + "(S1 y))", + "(E.extension(S1).operator " + ToCRefOp(op) + "(S1), void E.<>E__0." + opName + "(S1 y))"], + ExtensionTests.PrintXmlCrefSymbols(tree, model)); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_131_Consumption_CRef_Checked([CombinatorialValues("+=", "-=", "*=", "/=")] string op) + { + var src = $$$""" +/// +/// +public static class E +{ + /// + extension(S1 x) + { + /// + public void operator {{{op}}}(S1 y) => throw null; + /// + public void operator checked {{{op}}}(S1 y) => throw null; + } +} + +/// +public class S1; +"""; + + var comp = CreateCompilation([src, CompilerFeatureRequiredAttribute], parseOptions: TestOptions.RegularPreviewWithDocumentationComments); + comp.VerifyEmitDiagnostics(); + + var opName = CompoundAssignmentOperatorName(op, isChecked: true); + + var e = comp.GetMember("E"); + AssertEx.Equal($$$""" + + + + + +""", e.GetDocumentationCommentXml()); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + AssertEx.Equal([ + "(E.extension(S1).operator checked " + ToCRefOp(op) + ", void E.<>E__0." + opName + "(S1 y))", + "(E.extension(S1).operator checked " + ToCRefOp(op) + "(S1), void E.<>E__0." + opName + "(S1 y))"], + ExtensionTests.PrintXmlCrefSymbols(tree, model)); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_132_Consumption_CRef_Error([CombinatorialValues("+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", ">>>=")] string op) + { + var src = $$$""" +/// +/// +/// +/// +/// +/// +public static class E +{ + /// + extension(S1 x) + { + } +} + +/// +public class S1; +"""; + + var comp = CreateCompilation([src, CompilerFeatureRequiredAttribute], parseOptions: TestOptions.RegularPreviewWithDocumentationComments); + comp.VerifyEmitDiagnostics( + // (1,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator +=' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator " + ToCRefOp(op)).WithArguments("extension(S1).operator " + ToCRefOp(op)).WithLocation(1, 16), + // (2,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator +=()' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator " + ToCRefOp(op) + "()").WithArguments("extension(S1).operator " + ToCRefOp(op) + "()").WithLocation(2, 16), + // (3,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator +=(S1)' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator " + ToCRefOp(op) + "(S1)").WithArguments("extension(S1).operator " + ToCRefOp(op) + "(S1)").WithLocation(3, 16), + // (4,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator checked +=' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator checked " + ToCRefOp(op)).WithArguments("extension(S1).operator checked " + ToCRefOp(op)).WithLocation(4, 16), + // (5,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator checked +=()' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator checked " + ToCRefOp(op) + "()").WithArguments("extension(S1).operator checked " + ToCRefOp(op) + "()").WithLocation(5, 16), + // (6,16): warning CS1574: XML comment has cref attribute 'extension(S1).operator checked +=(S1)' that could not be resolved + // /// + Diagnostic(ErrorCode.WRN_BadXMLRef, "E.extension(S1).operator checked " + ToCRefOp(op) + "(S1)").WithArguments("extension(S1).operator checked " + ToCRefOp(op) + "(S1)").WithLocation(6, 16) + ); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_133_ERR_VoidError([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", ">>>")] string op) + { + var src = $$$""" +unsafe public static class Extensions1 +{ + extension(void*) + { + public static void* operator {{{op}}}(void* x, S1 y) => x; + } +} + +public struct S1; + +class Program +{ + unsafe void Test(void* x, S1 y) => x {{{op}}}= y; +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugDll.WithAllowUnsafe(true)); + comp.VerifyDiagnostics( + // (3,15): error CS1103: The receiver parameter of an extension cannot be of type 'void*' + // extension(void*) + Diagnostic(ErrorCode.ERR_BadTypeforThis, "void*").WithArguments("void*").WithLocation(3, 15) + ); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_134_ERR_VoidError([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^")] string op) + { + var src = $$$""" +unsafe public static class Extensions1 +{ + extension(void*) + { + public static S1 operator {{{op}}}(S1 x, void* y) => x; + } +} + +public struct S1; + +class Program +{ + unsafe void Test(void* x, S1 y) => y {{{op}}}= x; +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugDll.WithAllowUnsafe(true)); + comp.VerifyDiagnostics( + // (3,15): error CS1103: The receiver parameter of an extension cannot be of type 'void*' + // extension(void*) + Diagnostic(ErrorCode.ERR_BadTypeforThis, "void*").WithArguments("void*").WithLocation(3, 15) + ); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_135_ERR_VoidError([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + unsafe public static void* operator {{{op}}}(void* x, S1 y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1; + +class Program +{ + unsafe static void Main() + { + void* s11 = null; + var s12 = new S1(); + s11 {{{op}}}= s12; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe.WithAllowUnsafe(true)); + CompileAndVerify(comp, expectedOutput: "operator1", verify: Verification.Skipped).VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_136_ERR_VoidError([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^")] string op) + { + var src = $$$""" +public struct S1 +{ + unsafe public static void* operator {{{op}}}(void* x, S1 y) + { + System.Console.Write("operator1"); + return x; + } + + public override bool Equals(object other) => throw null; + public override int GetHashCode() => throw null; +} + +class Program +{ + unsafe static void Main() + { + void* s11 = null; + var s12 = new S1(); + s11 {{{op}}}= s12; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe.WithAllowUnsafe(true)); + CompileAndVerify(comp, expectedOutput: "operator1", verify: Verification.Skipped).VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_137_ERR_VoidError([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", ">>>")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(S1) + { + unsafe public static S1 operator {{{op}}}(S1 x, void* y) + { + System.Console.Write("operator1"); + return x; + } + } +} + +public struct S1; + +class Program +{ + unsafe static void Main() + { + void* s11 = null; + var s12 = new S1(); + s12 {{{op}}}= s11; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe.WithAllowUnsafe(true)); + CompileAndVerify(comp, expectedOutput: "operator1", verify: Verification.Skipped).VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_138_ERR_VoidError([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", ">>>")] string op) + { + var src = $$$""" +public struct S1 +{ + unsafe public static S1 operator {{{op}}}(S1 x, void* y) + { + System.Console.Write("operator1"); + return x; + } +} + +class Program +{ + unsafe static void Main() + { + void* s11 = null; + var s12 = new S1(); + s12 {{{op}}}= s11; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe.WithAllowUnsafe(true)); + CompileAndVerify(comp, expectedOutput: "operator1", verify: Verification.Skipped).VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_139_ERR_VoidError([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", ">>>")] string op) + { + var src = $$$""" +unsafe public static class Extensions1 +{ + extension(ref void* x) + { + public void operator {{{op}}}=(S1 y) {} + } +} + +public struct S1; + +class Program +{ + unsafe void Test(void* x, S1 y) => x {{{op}}}= y; +} +"""; + + var comp = CreateCompilation([src, CompilerFeatureRequiredAttribute], options: TestOptions.DebugDll.WithAllowUnsafe(true)); + comp.VerifyDiagnostics( + // (3,19): error CS1103: The receiver parameter of an extension cannot be of type 'void*' + // extension(ref void* x) + Diagnostic(ErrorCode.ERR_BadTypeforThis, "void*").WithArguments("void*").WithLocation(3, 19) + ); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_140_ERR_VoidError([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", ">>>")] string op) + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S1 x) + { + unsafe public void operator {{{op}}}=(void* y) + { + System.Console.Write("operator1"); + } + } +} + +public struct S1; + +class Program +{ + unsafe static void Main() + { + void* s11 = null; + var s12 = new S1(); + s12 {{{op}}}= s11; + } +} +"""; + + var comp = CreateCompilation([src, CompilerFeatureRequiredAttribute], options: TestOptions.DebugExe.WithAllowUnsafe(true)); + CompileAndVerify(comp, expectedOutput: "operator1", verify: Verification.Skipped).VerifyDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void CompoundAssignment_141_ERR_VoidError([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", ">>>")] string op) + { + var src = $$$""" +public struct S1 +{ + unsafe public void operator {{{op}}}=(void* y) + { + System.Console.Write("operator1"); + } +} + +class Program +{ + unsafe static void Main() + { + void* s11 = null; + var s12 = new S1(); + s12 {{{op}}}= s11; + } +} +"""; + + var comp = CreateCompilation([src, CompilerFeatureRequiredAttribute], options: TestOptions.DebugExe.WithAllowUnsafe(true)); + CompileAndVerify(comp, expectedOutput: "operator1", verify: Verification.Skipped).VerifyDiagnostics(); + } + + [Fact] + public void CompoundAssignment_142_Consumption_ErrorScenarioCandidates() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S2 x) + { + public void operator +=(int y) => throw null; + } +} + +public struct S2 +{ + public static S2 operator +(S2 x, int y) + { + return x; + } +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + s2 += s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (22,9): error CS0019: Operator '+=' cannot be applied to operands of type 'S2' and 'S2' + // s2 += s2; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s2 += s2").WithArguments("+=", "S2", "S2").WithLocation(22, 9) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + } + + [Fact] + public void CompoundAssignment_143_Consumption_ErrorScenarioCandidates() + { + var src = $$$""" +public static class Extensions1 +{ + extension(ref S2 x) + { + public void operator +=(C1 y) => throw null; + public void operator +=(C2 y) => throw null; + } +} + +public struct S2 +{ + public static S2 operator +(S2 x, int y) + { + return x; + } + + public static implicit operator C1 (S2 x) => null; + public static implicit operator C2 (S2 x) => null; +} + +public class C1; +public class C2; + +class Program +{ + static void Main() + { + var s2 = new S2(); + s2 += s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (29,12): error CS0121: The call is ambiguous between the following methods or properties: 'Extensions1.extension(ref S2).operator +=(C1)' and 'Extensions1.extension(ref S2).operator +=(C2)' + // s2 += s2; + Diagnostic(ErrorCode.ERR_AmbigCall, "+=").WithArguments("Extensions1.extension(ref S2).operator +=(C1)", "Extensions1.extension(ref S2).operator +=(C2)").WithLocation(29, 12) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); + AssertEx.Equal("Extensions1.extension(ref S2).operator +=(C1)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("Extensions1.extension(ref S2).operator +=(C2)", symbolInfo.CandidateSymbols[1].ToDisplayString()); + } + + [Fact] + public void CompoundAssignment_144_Consumption_ErrorScenarioCandidates() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator +(S2 x, int y) => throw null; + } +} + +public struct S2 +{ + public static S2 operator +(S2 x, int y) + { + return x; + } +} + +class Program +{ + static void Main() + { + var s2 = new S2(); + s2 += s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (22,9): error CS0019: Operator '+=' cannot be applied to operands of type 'S2' and 'S2' + // s2 += s2; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "s2 += s2").WithArguments("+=", "S2", "S2").WithLocation(22, 9) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); + Assert.Empty(symbolInfo.CandidateSymbols); + } + + [Fact] + public void CompoundAssignment_145_Consumption_ErrorScenarioCandidates() + { + var src = $$$""" +public static class Extensions1 +{ + extension(S2) + { + public static S2 operator +(S2 x, C1 y) => throw null; + public static S2 operator +(S2 x, C2 y) => throw null; + } +} + +public struct S2 +{ + public static S2 operator +(S2 x, int y) + { + return x; + } + + public static implicit operator C1 (S2 x) => null; + public static implicit operator C2 (S2 x) => null; +} + +public class C1; +public class C2; + +class Program +{ + static void Main() + { + var s2 = new S2(); + s2 += s2; + } +} + +""" + CompilerFeatureRequiredAttribute; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // (29,9): error CS0034: Operator '+=' is ambiguous on operands of type 'S2' and 'S2' + // s2 += s2; + Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "s2 += s2").WithArguments("+=", "S2", "S2").WithLocation(29, 9) + ); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var opNode = tree.GetRoot().DescendantNodes().OfType().First(); + var symbolInfo = model.GetSymbolInfo(opNode); + + Assert.Null(symbolInfo.Symbol); + Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); + AssertEx.Equal("Extensions1.extension(S2).operator +(S2, C1)", symbolInfo.CandidateSymbols[0].ToDisplayString()); + AssertEx.Equal("Extensions1.extension(S2).operator +(S2, C2)", symbolInfo.CandidateSymbols[1].ToDisplayString()); + } + + [Fact] + public void CompoundAssignment_146_Consumption_BadOperator() + { + var source1 = @" +public static class Extensions1 +{ + extension(C1 p) + { + public void operator +=(int a, int x = 0) {} + } +} + +public class C1; +"; + var source2 = @" +public class Program +{ + static void Main() + { + var x = new C1(); + x += 1; + } +} +"; + + CSharpCompilation comp1 = CreateCompilation([source1, CompilerFeatureRequiredAttribute]); + comp1.VerifyDiagnostics( + // (6,30): error CS1020: Overloadable binary operator expected + // public void operator +=(int a, int x = 0) {} + Diagnostic(ErrorCode.ERR_OvlBinaryOperatorExpected, "+=").WithLocation(6, 30), + // (6,44): warning CS1066: The default value specified for parameter 'x' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments + // public void operator +=(int a, int x = 0) {} + Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "x").WithArguments("x").WithLocation(6, 44) + ); + + var comp2 = CreateCompilation(source2, references: [comp1.ToMetadataReference()], options: TestOptions.DebugExe); + comp2.VerifyDiagnostics( + // (7,9): error CS0019: Operator '+=' cannot be applied to operands of type 'C1' and 'int' + // x += 1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "x += 1").WithArguments("+=", "C1", "int").WithLocation(7, 9) + ); + } + + [Fact] + public void CompoundAssignment_147_Consumption_BadOperator() + { + var source1 = @" +public static class Extensions1 +{ + extension(ref C1 p) + { + public void operator +=(int a) {} + } +} + +public class C1; +"; + var source2 = @" +public class Program +{ + static void Main() + { + var x = new C1(); + x += 1; + } +} +"; + + CSharpCompilation comp1 = CreateCompilation([source1, CompilerFeatureRequiredAttribute]); + comp1.VerifyDiagnostics( + // (4,19): error CS9300: The 'ref' receiver parameter of an extension block must be a value type or a generic type constrained to struct. + // extension(ref C1 p) + Diagnostic(ErrorCode.ERR_RefExtensionParameterMustBeValueTypeOrConstrainedToOne, "C1").WithLocation(4, 19) + ); + + var comp2 = CreateCompilation(source2, references: [comp1.ToMetadataReference()], options: TestOptions.DebugExe); + comp2.VerifyDiagnostics( + // (7,9): error CS0019: Operator '+=' cannot be applied to operands of type 'C1' and 'int' + // x += 1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "x += 1").WithArguments("+=", "C1", "int").WithLocation(7, 9) + ); + } + + [Fact] + public void CompoundAssignment_148_Consumption_BadOperator() + { + var source1 = @" +public static class Extensions1 +{ + extension(C1 p) + { + public void operator +=(int a) {} + } +} + +public struct C1; +"; + var source2 = @" +public class Program +{ + static void Main() + { + var x = new C1(); + x += 1; + } +} +"; + + CSharpCompilation comp1 = CreateCompilation([source1, CompilerFeatureRequiredAttribute]); + comp1.VerifyDiagnostics( + // (6,30): error CS9322: Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter + // public void operator +=(int a) {} + Diagnostic(ErrorCode.ERR_InstanceOperatorStructExtensionWrongReceiverRefKind, "+=").WithLocation(6, 30) + ); + + var comp2 = CreateCompilation(source2, references: [comp1.ToMetadataReference()], options: TestOptions.DebugExe); + comp2.VerifyDiagnostics( + // (7,9): error CS0019: Operator '+=' cannot be applied to operands of type 'C1' and 'int' + // x += 1; + Diagnostic(ErrorCode.ERR_BadBinaryOps, "x += 1").WithArguments("+=", "C1", "int").WithLocation(7, 9) + ); + } + } +} diff --git a/src/Compilers/CSharp/Test/Emit3/Semantics/ExtensionTests.cs b/src/Compilers/CSharp/Test/Emit3/Semantics/ExtensionTests.cs index 5424ae1691dc0..12429fe1f8389 100644 --- a/src/Compilers/CSharp/Test/Emit3/Semantics/ExtensionTests.cs +++ b/src/Compilers/CSharp/Test/Emit3/Semantics/ExtensionTests.cs @@ -1443,10 +1443,10 @@ .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' extends [netstandard]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( int32 '' - ) cil managed + ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -1456,8 +1456,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method public hidebysig static - class [netstandard]System.Action DoSomething () cil managed + .method public hidebysig static + class [netstandard]System.Action DoSomething () cil managed { // Method begins at RVA 0x20bc // Code size 2 (0x2) @@ -1475,8 +1475,8 @@ 01 00 00 00 // Fields .field public int32 b // Methods - .method public hidebysig specialname rtspecialname - instance void .ctor () cil managed + .method public hidebysig specialname rtspecialname + instance void .ctor () cil managed { // Method begins at RVA 0x2073 // Code size 7 (0x7) @@ -1485,8 +1485,8 @@ .maxstack 8 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass1_0'::.ctor - .method assembly hidebysig - instance void 'b__0' () cil managed + .method assembly hidebysig + instance void 'g__Do|0' () cil managed { // Method begins at RVA 0x20c0 // Code size 35 (0x23) @@ -1508,11 +1508,11 @@ [0] int32 IL_0018: ldfld int32 IntExt/'<>c__DisplayClass1_0'::b IL_001d: call void [netstandard]System.Console::WriteLine(int32) IL_0022: ret - } // end of method '<>c__DisplayClass1_0'::'b__0' + } // end of method '<>c__DisplayClass1_0'::'g__Do|0' } // end of class <>c__DisplayClass1_0 // Methods - .method public hidebysig static - class [netstandard]System.Action DoSomething () cil managed + .method public hidebysig static + class [netstandard]System.Action DoSomething () cil managed { // Method begins at RVA 0x207c // Code size 50 (0x32) @@ -1534,7 +1534,7 @@ [0] int32 IL_001f: dup IL_0020: ldloc.0 IL_0021: stfld int32 IntExt/'<>c__DisplayClass1_0'::b - IL_0026: ldftn instance void IntExt/'<>c__DisplayClass1_0'::'b__0'() + IL_0026: ldftn instance void IntExt/'<>c__DisplayClass1_0'::'g__Do|0'() IL_002c: newobj instance void [netstandard]System.Action::.ctor(object, native int) IL_0031: ret } // end of method IntExt::DoSomething @@ -2122,7 +2122,7 @@ public static class Extensions VerifyTypeIL(verifier, "Extensions", """ .class public auto ansi abstract sealed beforefieldinit Extensions -extends [netstandard]System.Object + extends [netstandard]System.Object { .custom instance void [netstandard]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -2132,10 +2132,10 @@ .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' extends [netstandard]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object '' - ) cil managed + ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -2145,8 +2145,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method private hidebysig specialname static - int32 get_Property () cil managed + .method private hidebysig specialname static + int32 get_Property () cil managed { // Method begins at RVA 0x206d // Code size 2 (0x2) @@ -2154,10 +2154,10 @@ .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method '<>E__0'::get_Property - .method private hidebysig specialname static + .method private hidebysig specialname static void set_Property ( int32 'value' - ) cil managed + ) cil managed { // Method begins at RVA 0x206d // Code size 2 (0x2) @@ -2174,7 +2174,7 @@ .property int32 Property() } // end of class <>E__0 // Methods .method private hidebysig static - int32 get_Property () cil managed + int32 get_Property () cil managed { // Method begins at RVA 0x2067 // Code size 3 (0x3) @@ -2185,7 +2185,7 @@ .maxstack 8 .method private hidebysig static void set_Property ( int32 'value' - ) cil managed + ) cil managed { // Method begins at RVA 0x206b // Code size 1 (0x1) @@ -2992,18 +2992,6 @@ public static class E """; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( - // (5,36): error CS0563: One of the parameters of a binary operator must be the containing type - // public static int operator +(int i, T t) => 0; - Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "+").WithLocation(5, 36), - // (5,36): error CS9282: Extension declarations can include only methods or properties - // public static int operator +(int i, T t) => 0; - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "+").WithLocation(5, 36), - // (6,36): error CS0563: One of the parameters of a binary operator must be the containing type - // public static int operator -(int i, int j) => 0; - Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "-").WithLocation(6, 36), - // (6,36): error CS9282: Extension declarations can include only methods or properties - // public static int operator -(int i, int j) => 0; - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "-").WithLocation(6, 36), // (6,36): error CS9295: The type parameter `T` is not referenced by either the extension parameter or a parameter of this member // public static int operator -(int i, int j) => 0; Diagnostic(ErrorCode.ERR_UnderspecifiedExtension, "-").WithArguments("T").WithLocation(6, 36)); @@ -3024,12 +3012,12 @@ public static class E """; var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); comp.VerifyEmitDiagnostics( - // (5,30): error CS9282: Extension declarations can include only methods or properties + // (5,30): error CS9322: Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter // public void operator +=(T t) { } - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "+=").WithLocation(5, 30), - // (6,30): error CS9282: Extension declarations can include only methods or properties + Diagnostic(ErrorCode.ERR_InstanceOperatorStructExtensionWrongReceiverRefKind, "+=").WithLocation(5, 30), + // (6,30): error CS9322: Cannot declare instance operator for a struct unless containing extension block receiver parameter is a 'ref' parameter // public void operator -=(int j) { } - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "-=").WithLocation(6, 30), + Diagnostic(ErrorCode.ERR_InstanceOperatorStructExtensionWrongReceiverRefKind, "-=").WithLocation(6, 30), // (6,30): error CS9295: The type parameter `T` is not referenced by either the extension parameter or a parameter of this member // public void operator -=(int j) { } Diagnostic(ErrorCode.ERR_UnderspecifiedExtension, "-=").WithArguments("T").WithLocation(6, 30)); @@ -5403,10 +5391,10 @@ .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -5416,10 +5404,10 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method public hidebysig + .method public hidebysig instance string M ( string s - ) cil managed + ) cil managed { // Method begins at RVA 0x20ad // Code size 2 (0x2) @@ -5439,11 +5427,11 @@ .field public object o .field public string s } // end of class <>c__DisplayClass1_0 // Methods - .method public hidebysig static + .method public hidebysig static string M ( object o, string s - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -5461,13 +5449,13 @@ [0] valuetype Extensions/'<>c__DisplayClass1_0' IL_000a: ldarg.1 IL_000b: stfld string Extensions/'<>c__DisplayClass1_0'::s IL_0010: ldloca.s 0 - IL_0012: call string Extensions::'b__1_0'(valuetype Extensions/'<>c__DisplayClass1_0'&) + IL_0012: call string Extensions::'g__local|1_0'(valuetype Extensions/'<>c__DisplayClass1_0'&) IL_0017: ret } // end of method Extensions::M - .method assembly hidebysig static - string 'b__1_0' ( + .method assembly hidebysig static + string 'g__local|1_0' ( valuetype Extensions/'<>c__DisplayClass1_0'& '' - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -5487,7 +5475,7 @@ .maxstack 8 IL_0013: ldfld string Extensions/'<>c__DisplayClass1_0'::s IL_0018: call string [mscorlib]System.String::Concat(string, string) IL_001d: ret - } // end of method Extensions::'b__1_0' + } // end of method Extensions::'g__local|1_0' } // end of class Extensions """.Replace("[mscorlib]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[mscorlib]")); @@ -6713,10 +6701,10 @@ .class nested public auto ansi sealed specialname beforefieldinit '<>E__0`1' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( class C`1 o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -6726,11 +6714,11 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0`1'::'$' - .method public hidebysig + .method public hidebysig instance class C`1 M ( !T t1, !!U u1 - ) cil managed + ) cil managed { // Method begins at RVA 0x216f // Code size 2 (0x2) @@ -6751,12 +6739,12 @@ .field public !U u1 .field public !T t1 } // end of class <>c__DisplayClass1_0`2 // Methods - .method public hidebysig static + .method public hidebysig static class C`1 M ( class C`1 o, !!T t1, !!U u1 - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -6786,18 +6774,18 @@ .locals init ( IL_002b: ldloc.0 IL_002c: ldfld !1 valuetype Extensions/'<>c__DisplayClass1_0`2'::u1 IL_0031: ldloca.s 0 - IL_0033: call class C`1 Extensions::'b__1_0'(!!0, !!1, !!2, !!3, !!4, valuetype Extensions/'<>c__DisplayClass1_0`2'&) + IL_0033: call class C`1 Extensions::'g__local|1_0'(!!0, !!1, !!2, !!3, !!4, valuetype Extensions/'<>c__DisplayClass1_0`2'&) IL_0038: ret } // end of method Extensions::M - .method assembly hidebysig static - class C`1 'b__1_0' ( + .method assembly hidebysig static + class C`1 'g__local|1_0' ( !!T t2, !!U u2, !!X x2, !!Y y2, !!Z z2, valuetype Extensions/'<>c__DisplayClass1_0`2'& '' - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -6860,7 +6848,7 @@ .maxstack 4 IL_008f: call string [mscorlib]System.String::Concat(string[]) IL_0094: newobj instance void class C`1::.ctor(string) IL_0099: ret - } // end of method Extensions::'b__1_0' + } // end of method Extensions::'g__local|1_0' } // end of class Extensions """.Replace("[mscorlib]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[mscorlib]")); @@ -8434,10 +8422,10 @@ .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object _ - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -8447,11 +8435,11 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method public hidebysig static + .method public hidebysig static string M ( object o, string s - ) cil managed + ) cil managed { // Method begins at RVA 0x20ad // Code size 2 (0x2) @@ -8471,11 +8459,11 @@ .field public object o .field public string s } // end of class <>c__DisplayClass1_0 // Methods - .method public hidebysig static + .method public hidebysig static string M ( object o, string s - ) cil managed + ) cil managed { // Method begins at RVA 0x2068 // Code size 24 (0x18) @@ -8490,13 +8478,13 @@ [0] valuetype Extensions/'<>c__DisplayClass1_0' IL_000a: ldarg.1 IL_000b: stfld string Extensions/'<>c__DisplayClass1_0'::s IL_0010: ldloca.s 0 - IL_0012: call string Extensions::'b__1_0'(valuetype Extensions/'<>c__DisplayClass1_0'&) + IL_0012: call string Extensions::'g__local|1_0'(valuetype Extensions/'<>c__DisplayClass1_0'&) IL_0017: ret } // end of method Extensions::M - .method assembly hidebysig static - string 'b__1_0' ( + .method assembly hidebysig static + string 'g__local|1_0' ( valuetype Extensions/'<>c__DisplayClass1_0'& '' - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -8516,7 +8504,7 @@ .maxstack 8 IL_0013: ldfld string Extensions/'<>c__DisplayClass1_0'::s IL_0018: call string [mscorlib]System.String::Concat(string, string) IL_001d: ret - } // end of method Extensions::'b__1_0' + } // end of method Extensions::'g__local|1_0' } // end of class Extensions """.Replace("[mscorlib]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[mscorlib]")); @@ -9953,10 +9941,10 @@ .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -9966,8 +9954,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method public hidebysig specialname - instance string get_P () cil managed + .method public hidebysig specialname + instance string get_P () cil managed { // Method begins at RVA 0x2071 // Code size 2 (0x2) @@ -9985,7 +9973,7 @@ .property instance string P() .method public hidebysig static string get_P ( object o - ) cil managed + ) cil managed { // Method begins at RVA 0x2067 // Code size 7 (0x7) @@ -10102,10 +10090,10 @@ .class nested public auto ansi sealed specialname beforefieldinit '<>E__0`1' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( !T o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -10115,8 +10103,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0`1'::'$' - .method public hidebysig - instance void M2 () cil managed + .method public hidebysig + instance void M2 () cil managed { // Method begins at RVA 0x20e9 // Code size 2 (0x2) @@ -10135,10 +10123,10 @@ 01 00 00 00 .field public static class [mscorlib]System.Func`1 '<0>__M1' } // end of class O__1_0`3 // Methods - .method public hidebysig static + .method public hidebysig static void M2 ( !!T o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -10146,13 +10134,13 @@ 01 00 00 00 // Method begins at RVA 0x2078 // Code size 12 (0xc) .maxstack 8 - IL_0000: call class [mscorlib]System.Func`1 Extensions::'b__1_0'() + IL_0000: call class [mscorlib]System.Func`1 Extensions::'g__local|1_0'() IL_0005: callvirt instance !0 class [mscorlib]System.Func`1::Invoke() IL_000a: pop IL_000b: ret } // end of method Extensions::M2 - .method assembly hidebysig static - class [mscorlib]System.Func`1 'b__1_0' () cil managed + .method assembly hidebysig static + class [mscorlib]System.Func`1 'g__local|1_0' () cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -10170,7 +10158,7 @@ .maxstack 8 IL_0015: dup IL_0016: stsfld class [mscorlib]System.Func`1 class Extensions/'O__1_0`3'::'<0>__M1' IL_001b: ret - } // end of method Extensions::'b__1_0' + } // end of method Extensions::'g__local|1_0' } // end of class Extensions """.Replace("[mscorlib]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[mscorlib]")); @@ -10253,10 +10241,10 @@ .class nested public auto ansi sealed specialname beforefieldinit '<>E__0`1' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( !T o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -10266,8 +10254,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0`1'::'$' - .method public hidebysig - instance void M2 () cil managed + .method public hidebysig + instance void M2 () cil managed { // Method begins at RVA 0x20b4 // Code size 2 (0x2) @@ -10286,10 +10274,10 @@ 01 00 00 00 .field public static class [mscorlib]System.Action '<0>__M1' } // end of class <>O__1_0`1 // Methods - .method public hidebysig static + .method public hidebysig static void M2 ( !!T o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -10297,12 +10285,12 @@ 01 00 00 00 // Method begins at RVA 0x2078 // Code size 11 (0xb) .maxstack 8 - IL_0000: call class [mscorlib]System.Action Extensions::'b__1_0'() + IL_0000: call class [mscorlib]System.Action Extensions::'g__local|1_0'() IL_0005: callvirt instance void [mscorlib]System.Action::Invoke() IL_000a: ret } // end of method Extensions::M2 - .method assembly hidebysig static - class [mscorlib]System.Action 'b__1_0' () cil managed + .method assembly hidebysig static + class [mscorlib]System.Action 'g__local|1_0' () cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -10320,7 +10308,7 @@ .maxstack 8 IL_0015: dup IL_0016: stsfld class [mscorlib]System.Action class Extensions/'<>O__1_0`1'::'<0>__M1' IL_001b: ret - } // end of method Extensions::'b__1_0' + } // end of method Extensions::'g__local|1_0' } // end of class Extensions """.Replace("[mscorlib]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[mscorlib]")); @@ -10400,10 +10388,10 @@ .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -10413,8 +10401,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method private hidebysig - instance void M2 () cil managed + .method private hidebysig + instance void M2 () cil managed { // Method begins at RVA 0x208e // Code size 2 (0x2) @@ -10433,10 +10421,10 @@ 01 00 00 00 .field public static class [mscorlib]System.Action '<0>__M1' } // end of class <>O // Methods - .method private hidebysig static + .method private hidebysig static void M2 ( object o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -10446,8 +10434,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method Extensions::M2 - .method assembly hidebysig static - class [mscorlib]System.Action 'b__1_0' () cil managed + .method assembly hidebysig static + class [mscorlib]System.Action 'g__local|1_0' () cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -10465,7 +10453,7 @@ .maxstack 8 IL_0015: dup IL_0016: stsfld class [mscorlib]System.Action Extensions/'<>O'::'<0>__M1' IL_001b: ret - } // end of method Extensions::'b__1_0' + } // end of method Extensions::'g__local|1_0' } // end of class Extensions """.Replace("[mscorlib]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[mscorlib]")); @@ -10540,10 +10528,10 @@ .class nested public auto ansi sealed specialname beforefieldinit '<>E__0`1' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( !T o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -10553,8 +10541,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0`1'::'$' - .method private hidebysig - instance class [mscorlib]System.Action M2 () cil managed + .method private hidebysig + instance class [mscorlib]System.Action M2 () cil managed { // Method begins at RVA 0x2098 // Code size 2 (0x2) @@ -10573,10 +10561,10 @@ 01 00 00 00 .field public static class [mscorlib]System.Action '<0>__local' } // end of class <>O__1_0`1 // Methods - .method private hidebysig static + .method private hidebysig static class [mscorlib]System.Action M2 ( !!T o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -10589,14 +10577,14 @@ .maxstack 8 IL_0006: brtrue.s IL_001b IL_0008: pop IL_0009: ldnull - IL_000a: ldftn void Extensions::'b__1_0'() + IL_000a: ldftn void Extensions::'g__local|1_0'() IL_0010: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0015: dup IL_0016: stsfld class [mscorlib]System.Action class Extensions/'<>O__1_0`1'::'<0>__local' IL_001b: ret } // end of method Extensions::M2 - .method assembly hidebysig static - void 'b__1_0' () cil managed + .method assembly hidebysig static + void 'g__local|1_0' () cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -10609,7 +10597,7 @@ .maxstack 8 IL_000a: callvirt instance string [mscorlib]System.Object::ToString() IL_000f: pop IL_0010: ret - } // end of method Extensions::'b__1_0' + } // end of method Extensions::'g__local|1_0' } // end of class Extensions """.Replace("[mscorlib]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[mscorlib]")); @@ -10682,10 +10670,10 @@ .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -10695,8 +10683,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method private hidebysig - instance class [mscorlib]System.Action M2 () cil managed + .method private hidebysig + instance class [mscorlib]System.Action M2 () cil managed { // Method begins at RVA 0x2098 // Code size 2 (0x2) @@ -10715,10 +10703,10 @@ 01 00 00 00 .field public static class [mscorlib]System.Action '<0>__local' } // end of class <>O // Methods - .method private hidebysig static + .method private hidebysig static class [mscorlib]System.Action M2 ( object o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -10731,14 +10719,14 @@ .maxstack 8 IL_0006: brtrue.s IL_001b IL_0008: pop IL_0009: ldnull - IL_000a: ldftn void Extensions::'b__1_0'() + IL_000a: ldftn void Extensions::'g__local|1_0'() IL_0010: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0015: dup IL_0016: stsfld class [mscorlib]System.Action Extensions/'<>O'::'<0>__local' IL_001b: ret } // end of method Extensions::M2 - .method assembly hidebysig static - void 'b__1_0' () cil managed + .method assembly hidebysig static + void 'g__local|1_0' () cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -10751,7 +10739,7 @@ .maxstack 8 IL_000a: callvirt instance string [mscorlib]System.Object::ToString() IL_000f: pop IL_0010: ret - } // end of method Extensions::'b__1_0' + } // end of method Extensions::'g__local|1_0' } // end of class Extensions """.Replace("[mscorlib]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[mscorlib]")); @@ -10831,10 +10819,10 @@ .class nested public auto ansi sealed specialname beforefieldinit '<>E__0`1' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( !T o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -10844,8 +10832,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0`1'::'$' - .method public hidebysig - instance void M2 () cil managed + .method public hidebysig + instance void M2 () cil managed { // Method begins at RVA 0x2154 // Code size 2 (0x2) @@ -10864,10 +10852,10 @@ 01 00 00 00 .field public static class [System.Core]System.Runtime.CompilerServices.CallSite`1> '<>p__0' } // end of class <>o__0|1`3 // Methods - .method public hidebysig static + .method public hidebysig static void M2 ( !!T o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -10888,16 +10876,16 @@ .locals init ( IL_0016: ldloc.1 IL_0017: ldc.i4.s 42 IL_0019: conv.i8 - IL_001a: call void Extensions::'b__1_0'(object, !!0, !!1, !!2) + IL_001a: call void Extensions::'g__local|1_0'(object, !!0, !!1, !!2) IL_001f: ret } // end of method Extensions::M2 - .method assembly hidebysig static - void 'b__1_0' ( + .method assembly hidebysig static + void 'g__local|1_0' ( object d, !!T t, !!U u, !!V v - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -10954,7 +10942,7 @@ .maxstack 9 IL_006b: ldarg.3 IL_006c: callvirt instance void class [mscorlib]System.Action`5::Invoke(!0, !1, !2, !3, !4) IL_0071: ret - } // end of method Extensions::'b__1_0' + } // end of method Extensions::'g__local|1_0' } // end of class Extensions """.Replace("[mscorlib]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[mscorlib]"). Replace("[System.Core]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[System.Core]")); @@ -11024,10 +11012,10 @@ .class nested public auto ansi sealed specialname beforefieldinit '<>E__0`1' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( !T o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -11037,8 +11025,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0`1'::'$' - .method private hidebysig - instance void M2 () cil managed + .method private hidebysig + instance void M2 () cil managed { // Method begins at RVA 0x20d4 // Code size 2 (0x2) @@ -11057,10 +11045,10 @@ 01 00 00 00 .field public static class [System.Core]System.Runtime.CompilerServices.CallSite`1> '<>p__0' } // end of class <>o__1`1 // Methods - .method private hidebysig static + .method private hidebysig static void M2 ( !!T o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -11070,11 +11058,11 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method Extensions::M2 - .method assembly hidebysig static - void 'b__1_0' ( + .method assembly hidebysig static + void 'g__local|1_0' ( object d, !!T t - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -11117,7 +11105,7 @@ .maxstack 9 IL_0055: ldarg.1 IL_0056: callvirt instance void class [mscorlib]System.Action`3::Invoke(!0, !1, !2) IL_005b: ret - } // end of method Extensions::'b__1_0' + } // end of method Extensions::'g__local|1_0' } // end of class Extensions """.Replace("[mscorlib]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[mscorlib]"). Replace("[System.Core]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[System.Core]")); @@ -11187,10 +11175,10 @@ .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' extends [mscorlib]System.Object { // Methods - .method private hidebysig specialname static + .method private hidebysig specialname static void '$' ( object o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -11200,8 +11188,8 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method '<>E__0'::'$' - .method private hidebysig - instance void M2 () cil managed + .method private hidebysig + instance void M2 () cil managed { // Method begins at RVA 0x20c9 // Code size 2 (0x2) @@ -11220,10 +11208,10 @@ 01 00 00 00 .field public static class [System.Core]System.Runtime.CompilerServices.CallSite`1> '<>p__0' } // end of class <>o__1 // Methods - .method private hidebysig static + .method private hidebysig static void M2 ( object o - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 @@ -11233,10 +11221,10 @@ 01 00 00 00 .maxstack 8 IL_0000: ret } // end of method Extensions::M2 - .method assembly hidebysig static - void 'b__1_0' ( + .method assembly hidebysig static + void 'g__local|1_0' ( object d - ) cil managed + ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 @@ -11272,7 +11260,7 @@ .maxstack 9 IL_004a: ldarg.0 IL_004b: callvirt instance void class [mscorlib]System.Action`2::Invoke(!0, !1) IL_0050: ret - } // end of method Extensions::'b__1_0' + } // end of method Extensions::'g__local|1_0' } // end of class Extensions """.Replace("[mscorlib]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[mscorlib]"). Replace("[System.Core]", ExecutionConditionUtil.IsMonoOrCoreClr ? "[netstandard]" : "[System.Core]")); @@ -11542,11 +11530,11 @@ public static class E var model = comp.GetSemanticModel(tree); var memberAccess = GetSyntax(tree, "object.P"); Assert.Equal("System.Int32 E.<>E__0.P { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); - Assert.Equal([], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : handle GetMemberGroup on a property access + Assert.Equal([], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); // Tracked by https://github.com/dotnet/roslyn/issues/78957 : handle GetMemberGroup on a property access memberAccess = GetSyntax(tree, "int.P"); Assert.Equal("System.Int32 E.<>E__0.P { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); - Assert.Equal([], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : handle GetMemberGroup on a property access + Assert.Equal([], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); // Tracked by https://github.com/dotnet/roslyn/issues/78957 : handle GetMemberGroup on a property access } [Fact] @@ -13869,12 +13857,11 @@ static class E } } """; - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : missing ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver var comp = CreateCompilation(source, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( - //// (5,9): error CS9106: Identifier 'Color' is ambiguous between type 'Color' and parameter 'Color Color' in this context. - //// Color.M1(this); - //Diagnostic(ErrorCode.ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver, "Color").WithArguments("Color", "Color", "Color Color").WithLocation(5, 9) + // (5,9): error CS9106: Identifier 'Color' is ambiguous between type 'Color' and parameter 'Color Color' in this context. + // Color.M1(this); + Diagnostic(ErrorCode.ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver, "Color").WithArguments("Color", "Color", "Color Color").WithLocation(5, 9) ); Assert.NotEmpty(comp.GetTypeByMetadataName("S1").InstanceConstructors.OfType().Single().GetCapturedParameters()); @@ -13912,12 +13899,11 @@ static class E2 } } """; - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : missing ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver var comp = CreateCompilation(source, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( - //// (5,9): error CS9106: Identifier 'Color' is ambiguous between type 'Color' and parameter 'Color Color' in this context. - //// Color.M1(this); - //Diagnostic(ErrorCode.ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver, "Color").WithArguments("Color", "Color", "Color Color").WithLocation(5, 9) + // (5,9): error CS9106: Identifier 'Color' is ambiguous between type 'Color' and parameter 'Color Color' in this context. + // Color.M1(this); + Diagnostic(ErrorCode.ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver, "Color").WithArguments("Color", "Color", "Color Color").WithLocation(5, 9) ); Assert.NotEmpty(comp.GetTypeByMetadataName("S1").InstanceConstructors.OfType().Single().GetCapturedParameters()); @@ -15327,7 +15313,7 @@ public static class Extensions var memberAccess = GetSyntax(tree, "new object().P"); Assert.Equal("System.Action Extensions.<>E__0.P { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); Assert.Equal([], model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); - Assert.Equal([], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : handle GetMemberGroup on a property access + Assert.Equal([], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); // Tracked by https://github.com/dotnet/roslyn/issues/78957 : handle GetMemberGroup on a property access } [Fact] @@ -16032,7 +16018,7 @@ static class E { extension(MyCollection c) { - public void Add(ref int i) { System.Console.Write("ran"); } + public void Add(ref int i) { } } } @@ -16642,7 +16628,7 @@ public class C Diagnostic(ErrorCode.ERR_BadDynamicQuery, "where i is not null").WithLocation(2, 9)); } - [Fact(Skip = "Tracked by https://github.com/dotnet/roslyn/issues/76130 : WasPropertyBackingFieldAccessChecked asserts that we're setting twice")] + [Fact(Skip = "Tracked by https://github.com/dotnet/roslyn/issues/78968 : WasPropertyBackingFieldAccessChecked asserts that we're setting twice")] public void ResolveAll_Query_Cast() { var source = """ @@ -17366,7 +17352,7 @@ static class E var model = comp.GetSemanticModel(tree); var memberAccess = GetSyntax(tree, "object.M"); Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); - Assert.Empty(model.GetMemberGroup(memberAccess)); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : consider handling BoundBadExpression better + Assert.Empty(model.GetMemberGroup(memberAccess)); // Tracked by https://github.com/dotnet/roslyn/issues/78957 : consider handling BoundBadExpression better } [Fact] @@ -17404,7 +17390,7 @@ static class E var model = comp.GetSemanticModel(tree); var memberAccess = GetSyntax(tree, "new object().M"); Assert.Equal("System.Action E.<>E__0.M { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); - Assert.Equal([], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : handle GetMemberGroup on a property access + Assert.Equal([], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); // Tracked by https://github.com/dotnet/roslyn/issues/78957 : handle GetMemberGroup on a property access } [Fact] @@ -17442,7 +17428,7 @@ static class E var model = comp.GetSemanticModel(tree); var memberAccess = GetSyntax(tree, "new object().M"); Assert.Equal("System.Action E.<>E__0.M { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); - Assert.Equal([], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : handle GetMemberGroup on a property access + Assert.Equal([], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); // Tracked by https://github.com/dotnet/roslyn/issues/78957 : handle GetMemberGroup on a property access } [Fact] @@ -17690,7 +17676,7 @@ static class E var model = comp.GetSemanticModel(tree); var memberAccess = GetSyntax(tree, "new object().M"); Assert.Equal("System.Int32 E.<>E__0.M { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); - Assert.Equal([], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : handle GetMemberGroup on a property access + Assert.Equal([], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); // Tracked by https://github.com/dotnet/roslyn/issues/78957 : handle GetMemberGroup on a property access } [Fact] @@ -18866,7 +18852,7 @@ static class E var model = comp.GetSemanticModel(tree); var property = GetSyntax(tree, "C.Property"); Assert.Equal("System.Int32 E.<>E__0.Property { set; }", model.GetSymbolInfo(property).Symbol.ToTestDisplayString()); - Assert.Empty(model.GetMemberGroup(property)); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : handle GetMemberGroup on a property access + Assert.Empty(model.GetMemberGroup(property)); // Tracked by https://github.com/dotnet/roslyn/issues/78957 : handle GetMemberGroup on a property access } [Fact] @@ -18898,7 +18884,7 @@ static class E var model = comp.GetSemanticModel(tree); var property = GetSyntax(tree, "C.Property"); Assert.Equal("System.Int32 E.<>E__0.Property { set; }", model.GetSymbolInfo(property).Symbol.ToTestDisplayString()); - Assert.Empty(model.GetMemberGroup(property)); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : handle GetMemberGroup on a property access + Assert.Empty(model.GetMemberGroup(property)); // Tracked by https://github.com/dotnet/roslyn/issues/78957 : handle GetMemberGroup on a property access } [Fact] @@ -19165,12 +19151,11 @@ public static void M1(T x) where T : unmanaged } } """; - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : missing ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver var comp = CreateCompilation(source, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( - //// (5,9): error CS9106: Identifier 'Color' is ambiguous between type 'Color' and parameter 'Color Color' in this context. - //// Color.M1(this); - //Diagnostic(ErrorCode.ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver, "Color").WithArguments("Color", "Color", "Color Color").WithLocation(5, 9) + // (5,9): error CS9106: Identifier 'Color' is ambiguous between type 'Color' and parameter 'Color Color' in this context. + // Color.M1(this); + Diagnostic(ErrorCode.ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver, "Color").WithArguments("Color", "Color", "Color Color").WithLocation(5, 9) ); Assert.NotEmpty(comp.GetTypeByMetadataName("S1").InstanceConstructors.OfType().Single().GetCapturedParameters()); @@ -19211,9 +19196,11 @@ static class E2 } } """; - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : missing ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver var comp = CreateCompilation(source, options: TestOptions.ReleaseDll); - comp.VerifyEmitDiagnostics(); + comp.VerifyEmitDiagnostics( + // (5,13): error CS9106: Identifier 'Color' is ambiguous between type 'Color' and parameter 'Color Color' in this context. + // _ = Color.P1; + Diagnostic(ErrorCode.ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver, "Color").WithArguments("Color", "Color", "Color Color").WithLocation(5, 13)); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); @@ -19254,12 +19241,11 @@ public static void M1(T x) where T : unmanaged } } """; - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : missing ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver var comp = CreateCompilation(source, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( - //// (5,9): error CS9106: Identifier 'Color' is ambiguous between type 'Color' and parameter 'Color Color' in this context. - //// Color.M1(this); - //Diagnostic(ErrorCode.ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver, "Color").WithArguments("Color", "Color", "Color Color").WithLocation(5, 9) + // (5,9): error CS9106: Identifier 'Color' is ambiguous between type 'Color' and parameter 'Color Color' in this context. + // Color.M1(this); + Diagnostic(ErrorCode.ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver, "Color").WithArguments("Color", "Color", "Color Color").WithLocation(5, 9) ); Assert.NotEmpty(comp.GetTypeByMetadataName("S1").InstanceConstructors.OfType().Single().GetCapturedParameters()); @@ -19271,5655 +19257,6584 @@ public static void M1(T x) where T : unmanaged } [Fact] - public void InstanceMethod_MemberAccess() + public void PrimaryCtorParameterCapturing_01() { - var src = """ -new object().M.ToString(); - -static class E + var source = """ +struct S1(Color Color) { - extension(object o) + public void Test() { - public int M() => 42; + Color.Member(); + M(this); } + + public static void M(T x) where T : unmanaged { } } -"""; - var comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics( - // (1,14): error CS0119: 'E.extension(object).M()' is a method, which is not valid in the given context - // new object().M.ToString(); - Diagnostic(ErrorCode.ERR_BadSKunknown, "M").WithArguments("E.extension(object).M()", "method").WithLocation(1, 14)); - var tree = comp.SyntaxTrees.Single(); - var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "new object().M"); - Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); - Assert.Equal([], model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); - Assert.Equal([], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); +class Color { } - src = """ -new object().M.ToString(); +static class E1 +{ + extension(Color c) + { + public System.Action Member => null; + } +} -static class E +static class E2 { - public static int M(this object o) => 42; + extension(Color) + { + public static int Member => 0; + } } """; - comp = CreateCompilation(src); + var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( - // (1,14): error CS0119: 'E.M(object)' is a method, which is not valid in the given context - // new object().M.ToString(); - Diagnostic(ErrorCode.ERR_BadSKunknown, "M").WithArguments("E.M(object)", "method").WithLocation(1, 14)); + // (6,9): error CS8377: The type 'S1' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'S1.M(T)' + // M(this); + Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("S1.M(T)", "T", "S1").WithLocation(6, 9)); - tree = comp.SyntaxTrees.Single(); - model = comp.GetSemanticModel(tree); - memberAccess = GetSyntax(tree, "new object().M"); - Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); - Assert.Equal([], model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); - Assert.Equal([], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "Color.Member"); + Assert.Equal("System.Action E1.<>E__0.Member { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); } [Fact] - public void InstanceMethod_MemberAccess_Missing() + public void PrimaryCtorParameterCapturing_02() { - var src = """ -new object().M.ToString(); -"""; - var comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics( - // (1,14): error CS1061: 'object' does not contain a definition for 'M' and no accessible extension method 'M' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) - // new object().M.ToString(); - Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M").WithArguments("object", "M").WithLocation(1, 14)); + var source = """ +struct S1(Color Color) +{ + public void Test() + { + Color.Member(); + M(this); } - [Fact] - public void CheckValueKind_AssignToMethodGroup() - { - var src = """ -object.M = null; + public static void M(T x) where T : unmanaged { } +} -static class E +class Color { - extension(object) - { - public static void M() { } - } + public static int Member => 0; +} + +static class E1 +{ + public static void Member(this Color c) { } } """; - var comp = CreateCompilation(src); + var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( - // (1,1): error CS1656: Cannot assign to 'M' because it is a 'method group' - // object.M = null; - Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "object.M").WithArguments("M", "method group").WithLocation(1, 1)); + // (6,9): error CS8377: The type 'S1' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'S1.M(T)' + // M(this); + Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("S1.M(T)", "T", "S1").WithLocation(6, 9)); - var tree = comp.SyntaxTrees.Single(); + var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "object.M"); - Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); - Assert.Equal(["void E.<>E__0.M()"], model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); - Assert.Equal(CandidateReason.NotAVariable, model.GetSymbolInfo(memberAccess).CandidateReason); - Assert.Equal(["void E.<>E__0.M()"], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); + var memberAccess = GetSyntax(tree, "Color.Member"); + Assert.Equal("void Color.Member()", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); } [Fact] - public void AccessOnVoid_Invocation() + public void PrimaryCtorParameterCapturing_03() { - var src = """ -object.M().ToString(); - -static class E + // Non-invocable candidate is out of the picture, so we're left with only the instance candidate + var source = """ +struct S1(Color Color) { - extension(object) + public void Test() { - public static void M() { } + Color.Member(); + M(this); } + + public static void M(T x) where T : unmanaged { } } -"""; - var comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics( - // (1,11): error CS0023: Operator '.' cannot be applied to operand of type 'void' - // object.M().ToString(); - Diagnostic(ErrorCode.ERR_BadUnaryOp, ".").WithArguments(".", "void").WithLocation(1, 11)); - } - [Fact] - public void ExtensionMemberLookup_InaccessibleMembers() +class Color +{ +} + +static class E1 +{ + extension(Color c) { - var src = """ -object.Method(); -_ = object.Property; + public void Member() { } + } +} -static class E +static class E2 { - extension(object o) + extension(Color) { - private static void Method() => throw null; - private static int Property => throw null; + public static int Member => 0; } } """; - var comp = CreateCompilation(src); + var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( - // (1,8): error CS0117: 'object' does not contain a definition for 'Method' - // object.Method(); - Diagnostic(ErrorCode.ERR_NoSuchMember, "Method").WithArguments("object", "Method").WithLocation(1, 8), - // (2,12): error CS0117: 'object' does not contain a definition for 'Property' - // _ = object.Property; - Diagnostic(ErrorCode.ERR_NoSuchMember, "Property").WithArguments("object", "Property").WithLocation(2, 12)); + // (6,9): error CS8377: The type 'S1' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'S1.M(T)' + // M(this); + Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("S1.M(T)", "T", "S1").WithLocation(6, 9)); - var tree = comp.SyntaxTrees.Single(); + var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); - var memberAccess1 = GetSyntax(tree, "object.Method"); - Assert.Equal(["void E.<>E__0.Method()"], model.GetMemberGroup(memberAccess1).ToTestDisplayStrings()); - - var memberAccess2 = GetSyntax(tree, "object.Property"); - Assert.Equal([], model.GetMemberGroup(memberAccess2).ToTestDisplayStrings()); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : handle GetMemberGroup on a property access + var memberAccess = GetSyntax(tree, "Color.Member"); + Assert.Equal("void E1.<>E__0.Member()", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); } [Fact] - public void ExtensionMemberLookup_InterpolationHandler_Simple() + public void PrimaryCtorParameterCapturing_04() { - var src = """ -_ = f($"{(object)1} {f2()}"); + // Non-invocable candidate is out of the picture, so we're left with only the static candidate + var source = """ +struct S1(Color Color) +{ + public void Test() + { + Color.Member(); + M(this); + } -static int f(InterpolationHandler s) => 0; -static string f2() => "hello"; + public static void M(T x) where T : unmanaged { } +} -[System.Runtime.CompilerServices.InterpolatedStringHandler] -public struct InterpolationHandler +class Color { - public InterpolationHandler(int literalLength, int formattedCount) => throw null; - public void AppendLiteral(string value) { } - public void AppendFormatted(T hole, int alignment = 0, string format = null) => throw null; +} + +static class E1 +{ + extension(Color) + { + public static void Member() { } + } +} + +static class E2 +{ + extension(Color c) + { + public int Member => 0; + } } """; + var comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (1,17): warning CS9113: Parameter 'Color' is unread. + // struct S1(Color Color) + Diagnostic(ErrorCode.WRN_UnreadPrimaryConstructorParameter, "Color").WithArguments("Color").WithLocation(1, 17)); - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - comp.VerifyEmitDiagnostics(); + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "Color.Member"); + Assert.Equal("void E1.<>E__0.Member()", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); } [Fact] - public void ExtensionMemberLookup_InterpolationHandler_AppendLiteralExtensionMethod() + public void PrimaryCtorParameterCapturing_05() { - var src = """ -_ = f($"{(object)1} {f2()}"); + var source = """ +struct S1(Color Color) +{ + public void Test() + { + Color.Member(); + M(this); + } -static int f(InterpolationHandler s) => 0; -static string f2() => "hello"; + public static void M(T x) where T : unmanaged { } +} -[System.Runtime.CompilerServices.InterpolatedStringHandler] -public struct InterpolationHandler +class Color { - public InterpolationHandler(int literalLength, int formattedCount) => throw null; - public void AppendFormatted(T hole, int alignment = 0, string format = null) => throw null; } -public static class Extensions +static class E1 { - public static void AppendLiteral(this InterpolationHandler ih, string value) { } + extension(Color c) + { + public void Member() { } + } } -"""; - // Interpolation handlers don't allow extension methods - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); +static class E2 +{ + extension(Color) + { + public static System.Action Member => null; + } +} +"""; + var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( - // (1,20): error CS1061: 'InterpolationHandler' does not contain a definition for 'AppendLiteral' and no accessible extension method 'AppendLiteral' accepting a first argument of type 'InterpolationHandler' could be found (are you missing a using directive or an assembly reference?) - // _ = f($"{(object)1} {f2()}"); - Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, " ").WithArguments("InterpolationHandler", "AppendLiteral").WithLocation(1, 20), - // (1,20): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. - // _ = f($"{(object)1} {f2()}"); - Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, " ").WithArguments("?.()").WithLocation(1, 20)); + // (5,9): error CS9106: Identifier 'Color' is ambiguous between type 'Color' and parameter 'Color Color' in this context. + // Color.Member(); + Diagnostic(ErrorCode.ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver, "Color").WithArguments("Color", "Color", "Color Color").WithLocation(5, 9), + // (6,9): error CS8377: The type 'S1' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'S1.M(T)' + // M(this); + Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("S1.M(T)", "T", "S1").WithLocation(6, 9)); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "Color.Member"); + Assert.Equal("void E1.<>E__0.Member()", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); } [Fact] - public void ExtensionMemberLookup_InterpolationHandler_AppendLiteralExtensionDeclarationMethod() + public void PrimaryCtorParameterCapturing_06() { - var src = """ -_ = f($"{(object)1} {f2()}"); + var source = """ +struct S1(Color Color) +{ + public void Test() + { + Color.Member(); + M(this); + } -static int f(InterpolationHandler s) => 0; -static string f2() => "hello"; + public static void M(T x) where T : unmanaged { } +} -[System.Runtime.CompilerServices.InterpolatedStringHandler] -public struct InterpolationHandler +class Color { - public InterpolationHandler(int literalLength, int formattedCount) => throw null; - public void AppendFormatted(T hole, int alignment = 0, string format = null) => throw null; } -static class E +static class E1 { - extension(InterpolationHandler i) + extension(Color c) { - public void AppendLiteral(string value) { } + public void Member() { } } } -"""; - // Interpolation handlers don't allow extension methods - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); +static class E2 +{ + extension(Color) + { + public static void Member(int i) { } + } +} +"""; + var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( - // (1,20): error CS1061: 'InterpolationHandler' does not contain a definition for 'AppendLiteral' and no accessible extension method 'AppendLiteral' accepting a first argument of type 'InterpolationHandler' could be found (are you missing a using directive or an assembly reference?) - // _ = f($"{(object)1} {f2()}"); - Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, " ").WithArguments("InterpolationHandler", "AppendLiteral").WithLocation(1, 20), - // (1,20): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. - // _ = f($"{(object)1} {f2()}"); - Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, " ").WithArguments("?.()").WithLocation(1, 20)); + // (5,9): error CS9106: Identifier 'Color' is ambiguous between type 'Color' and parameter 'Color Color' in this context. + // Color.Member(); + Diagnostic(ErrorCode.ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver, "Color").WithArguments("Color", "Color", "Color Color").WithLocation(5, 9), + // (6,9): error CS8377: The type 'S1' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'S1.M(T)' + // M(this); + Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("S1.M(T)", "T", "S1").WithLocation(6, 9)); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "Color.Member"); + Assert.Equal("void E1.<>E__0.Member()", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); } [Fact] - public void ExtensionMemberLookup_InterpolationHandler_AppendFormattedExtensionMethod() + public void PrimaryCtorParameterCapturing_07() { - var src = """ -/**/ -_ = f($"{(object)1} {f2()}"); -/**/ + // instance extension method in inner scope, static extension method in outer scope + var source = """ +namespace N +{ + struct S1(Color Color) + { + public void Test() + { + Color.Member(); + M(this); + } -static int f(InterpolationHandler s) => 0; -static string f2() => "hello"; + public static void M(T x) where T : unmanaged { } + } -[System.Runtime.CompilerServices.InterpolatedStringHandler] -public struct InterpolationHandler + static class E1 + { + extension(Color c) + { + public void Member() { } + } + } +} + +class Color { - public InterpolationHandler(int literalLength, int formattedCount) => throw null; - public void AppendLiteral(string value) { } } -public static class Extensions +static class E2 { - public static void AppendFormatted(this InterpolationHandler ih, T hole, int alignment = 0, string format = null) { } + extension(Color) + { + public static void Member() { } + } } """; - - // Interpolation handlers don't allow extension methods - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( - // (2,9): error CS1061: 'InterpolationHandler' does not contain a definition for 'AppendFormatted' and no accessible extension method 'AppendFormatted' accepting a first argument of type 'InterpolationHandler' could be found (are you missing a using directive or an assembly reference?) - // _ = f($"{(object)1} {f2()}"); - Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "{(object)1}").WithArguments("InterpolationHandler", "AppendFormatted").WithLocation(2, 9), - // (2,9): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. - // _ = f($"{(object)1} {f2()}"); - Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{(object)1}").WithArguments("?.()").WithLocation(2, 9), - // (2,21): error CS1061: 'InterpolationHandler' does not contain a definition for 'AppendFormatted' and no accessible extension method 'AppendFormatted' accepting a first argument of type 'InterpolationHandler' could be found (are you missing a using directive or an assembly reference?) - // _ = f($"{(object)1} {f2()}"); - Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "{f2()}").WithArguments("InterpolationHandler", "AppendFormatted").WithLocation(2, 21), - // (2,21): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. - // _ = f($"{(object)1} {f2()}"); - Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{f2()}").WithArguments("?.()").WithLocation(2, 21) - ); + // (7,13): error CS9106: Identifier 'Color' is ambiguous between type 'Color' and parameter 'Color Color' in this context. + // Color.Member(); + Diagnostic(ErrorCode.ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver, "Color").WithArguments("Color", "Color", "Color Color").WithLocation(7, 13), + // (8,13): error CS8377: The type 'S1' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'S1.M(T)' + // M(this); + Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("N.S1.M(T)", "T", "N.S1").WithLocation(8, 13)); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "Color.Member"); + Assert.Equal("void N.E1.<>E__0.Member()", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); } [Fact] - public void ExtensionMemberLookup_InterpolationHandler_AppendFormattedExtensionTypeMethod() + public void PrimaryCtorParameterCapturing_08() { - var src = """ -_ = f($"{(object)1} {f2()}"); + // static extension method in inner scope, instance extension method in outer scope + var source = """ +namespace N +{ + struct S1(Color Color) + { + public void Test() + { + Color.Member(); + M(this); + } -static int f(InterpolationHandler s) => 0; -static string f2() => "hello"; + public static void M(T x) where T : unmanaged { } + } -[System.Runtime.CompilerServices.InterpolatedStringHandler] -public struct InterpolationHandler + static class E1 + { + extension(Color) + { + public static void Member() { } + } + } +} + +class Color { - public InterpolationHandler(int literalLength, int formattedCount) => throw null; - public void AppendLiteral(string value) { } } -static class E +static class E2 { - extension(InterpolationHandler i) + extension(Color c) { - public void AppendFormatted(T hole, int alignment = 0, string format = null) { } + public void Member() { } } } """; - - // Interpolation handlers don't allow extension methods - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( - // (1,9): error CS1061: 'InterpolationHandler' does not contain a definition for 'AppendFormatted' and no accessible extension method 'AppendFormatted' accepting a first argument of type 'InterpolationHandler' could be found (are you missing a using directive or an assembly reference?) - // _ = f($"{(object)1} {f2()}"); - Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "{(object)1}").WithArguments("InterpolationHandler", "AppendFormatted").WithLocation(1, 9), - // (1,9): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. - // _ = f($"{(object)1} {f2()}"); - Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{(object)1}").WithArguments("?.()").WithLocation(1, 9), - // (1,21): error CS1061: 'InterpolationHandler' does not contain a definition for 'AppendFormatted' and no accessible extension method 'AppendFormatted' accepting a first argument of type 'InterpolationHandler' could be found (are you missing a using directive or an assembly reference?) - // _ = f($"{(object)1} {f2()}"); - Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "{f2()}").WithArguments("InterpolationHandler", "AppendFormatted").WithLocation(1, 21), - // (1,21): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. - // _ = f($"{(object)1} {f2()}"); - Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{f2()}").WithArguments("?.()").WithLocation(1, 21)); + // (7,13): error CS9106: Identifier 'Color' is ambiguous between type 'Color' and parameter 'Color Color' in this context. + // Color.Member(); + Diagnostic(ErrorCode.ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver, "Color").WithArguments("Color", "Color", "Color Color").WithLocation(7, 13), + // (8,13): error CS8377: The type 'S1' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'S1.M(T)' + // M(this); + Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("N.S1.M(T)", "T", "N.S1").WithLocation(8, 13)); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "Color.Member"); + Assert.Equal("void E2.<>E__0.Member()", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); } [Fact] - public void LiteralReceiver_Property_Enum_Set() + public void PrimaryCtorParameterCapturing_09() { - var src = """ -Enum.Zero.Property = 1; + // static extension property in inner scope, instance extension method in outer scope + var source = """ +namespace N +{ + struct S1(Color Color) + { + public void Test() + { + Color.Member(); + M(this); + } -enum Enum + public static void M(T x) where T : unmanaged { } + } + + static class E1 + { + extension(Color) + { + public static System.Action Member => throw null; + } + } +} + +class Color { - Zero } -static class E +static class E2 { - extension(Enum e) + extension(Color c) { - public int Property { set => throw null; } + public void Member() { } } } """; - var comp = CreateCompilation(src); - // Consider improving the error message + var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( - // (1,1): error CS0131: The left-hand side of an assignment must be a variable, property or indexer - // Enum.Zero.Property = 1; - Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "Enum.Zero.Property").WithLocation(1, 1)); + // (7,13): error CS9106: Identifier 'Color' is ambiguous between type 'Color' and parameter 'Color Color' in this context. + // Color.Member(); + Diagnostic(ErrorCode.ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver, "Color").WithArguments("Color", "Color", "Color Color").WithLocation(7, 13), + // (8,13): error CS8377: The type 'S1' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'S1.M(T)' + // M(this); + Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("N.S1.M(T)", "T", "N.S1").WithLocation(8, 13)); - var tree = comp.SyntaxTrees.Single(); + var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "Enum.Zero.Property"); - Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); - Assert.Equal(["System.Int32 E.<>E__0.Property { set; }"], model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); - Assert.Equal(CandidateReason.NotAVariable, model.GetSymbolInfo(memberAccess).CandidateReason); - Assert.Equal([], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : handle GetMemberGroup on a property access + var memberAccess = GetSyntax(tree, "Color.Member"); + Assert.Equal("void E2.<>E__0.Member()", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); } [Fact] - public void LiteralReceiver_Property_Integer_ForLong() + public void PrimaryCtorParameterCapturing_10() { - var src = """ -1.Property = 42; -_ = 2.Property; - -static class E + // inapplicable candidate + var source = """ +struct S1(Color Color) { - extension(long l) + public void Test() { - public int Property { get { System.Console.Write("get "); return 42; } set { System.Console.Write("set "); } } + Color.Member(); + M(this); } -} -"""; - var comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics( - // (1,1): error CS9286: 'int' does not contain a definition for 'Property' and no accessible extension member 'Property' for receiver of type 'int' could be found (are you missing a using directive or an assembly reference?) - // 1.Property = 42; - Diagnostic(ErrorCode.ERR_ExtensionResolutionFailed, "1.Property").WithArguments("int", "Property").WithLocation(1, 1), - // (2,5): error CS9286: 'int' does not contain a definition for 'Property' and no accessible extension member 'Property' for receiver of type 'int' could be found (are you missing a using directive or an assembly reference?) - // _ = 2.Property; - Diagnostic(ErrorCode.ERR_ExtensionResolutionFailed, "2.Property").WithArguments("int", "Property").WithLocation(2, 5)); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : review the behavior of the semantic model APIs - var tree = comp.SyntaxTrees.Single(); - var model = comp.GetSemanticModel(tree); - var memberAccess1 = GetSyntax(tree, "1.Property"); - Assert.Equal("System.Int32 E.<>E__0.Property { get; set; }", model.GetSymbolInfo(memberAccess1).Symbol.ToTestDisplayString()); - Assert.Equal([], model.GetSymbolInfo(memberAccess1).CandidateSymbols.ToTestDisplayStrings()); - Assert.Equal(CandidateReason.None, model.GetSymbolInfo(memberAccess1).CandidateReason); + public static void M(T x) where T : unmanaged { } +} - var memberAccess2 = GetSyntax(tree, "2.Property"); - Assert.Equal("System.Int32 E.<>E__0.Property { get; set; }", model.GetSymbolInfo(memberAccess2).Symbol.ToTestDisplayString()); - Assert.Equal([], model.GetSymbolInfo(memberAccess2).CandidateSymbols.ToTestDisplayStrings()); - Assert.Equal(CandidateReason.None, model.GetSymbolInfo(memberAccess2).CandidateReason); - } +class Color +{ +} - [Fact] - public void LiteralReceiver_Property_String() +static class E1 +{ + extension(T t) where T : struct { - var src = """ -"".Property = 42; -_ = "".Property; + public void Member() { } + } +} -static class E +static class E2 { - extension(string s) + extension(Color) { - public int Property { get { System.Console.Write("get "); return 42; } set { System.Console.Write("set "); } } + public static void Member() { } } } """; - var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "set get").VerifyDiagnostics(); + var comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (1,17): warning CS9113: Parameter 'Color' is unread. + // struct S1(Color Color) + Diagnostic(ErrorCode.WRN_UnreadPrimaryConstructorParameter, "Color").WithArguments("Color").WithLocation(1, 17)); - var tree = comp.SyntaxTrees.Single(); + var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); - var memberAccess1 = GetSyntaxes(tree, "\"\".Property").First(); - Assert.Equal("System.Int32 E.<>E__0.Property { get; set; }", model.GetSymbolInfo(memberAccess1).Symbol.ToTestDisplayString()); - - var memberAccess2 = GetSyntaxes(tree, "\"\".Property").Last(); - Assert.Equal("System.Int32 E.<>E__0.Property { get; set; }", model.GetSymbolInfo(memberAccess2).Symbol.ToTestDisplayString()); + var memberAccess = GetSyntax(tree, "Color.Member"); + Assert.Equal("void E2.<>E__0.Member()", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); } [Fact] - public void SwitchReceiver_Property_String() + public void PrimaryCtorParameterCapturing_11() { - var src = """ -bool b = true; -(b switch { true => "", _ => "" }).Property = 42; -_ = (b switch { true => "", _ => "" }).Property; - -static class E + // inapplicable candidate + var source = """ +struct S1(Color Color) { - extension(string s) + public void Test() { - public int Property { get { System.Console.Write("get "); return 42; } set { System.Console.Write("set "); } } + Color.Member(); + M(this); } -} -"""; - var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "set get").VerifyDiagnostics(); - var tree = comp.SyntaxTrees.Single(); - var model = comp.GetSemanticModel(tree); - var memberAccess1 = GetSyntaxes(tree, """(b switch { true => "", _ => "" }).Property""").First(); - Assert.Equal("System.Int32 E.<>E__0.Property { get; set; }", model.GetSymbolInfo(memberAccess1).Symbol.ToTestDisplayString()); + public static void M(T x) where T : unmanaged { } +} - var memberAccess2 = GetSyntaxes(tree, """(b switch { true => "", _ => "" }).Property""").Last(); - Assert.Equal("System.Int32 E.<>E__0.Property { get; set; }", model.GetSymbolInfo(memberAccess2).Symbol.ToTestDisplayString()); - } +class Color +{ +} - [Fact] - public void ConditionalReceiver_Property_String() +static class E1 +{ + extension(T) where T : struct { - var src = """ -bool b = true; -(b ? "" : null).Property = 42; -_ = (b ? "" : null).Property; + public static void Member() { } + } +} -static class E +static class E2 { - extension(string s) + extension(Color c) { - public int Property { get { System.Console.Write("get "); return 42; } set { System.Console.Write("set "); } } + public void Member() { } } } """; - var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "set get").VerifyDiagnostics(); + var comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (6,9): error CS8377: The type 'S1' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'S1.M(T)' + // M(this); + Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("S1.M(T)", "T", "S1").WithLocation(6, 9)); - var tree = comp.SyntaxTrees.Single(); + var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); - var memberAccess1 = GetSyntaxes(tree, """(b ? "" : null).Property""").First(); - Assert.Equal("System.Int32 E.<>E__0.Property { get; set; }", model.GetSymbolInfo(memberAccess1).Symbol.ToTestDisplayString()); - - var memberAccess2 = GetSyntaxes(tree, """(b ? "" : null).Property""").Last(); - Assert.Equal("System.Int32 E.<>E__0.Property { get; set; }", model.GetSymbolInfo(memberAccess2).Symbol.ToTestDisplayString()); + var memberAccess = GetSyntax(tree, "Color.Member"); + Assert.Equal("void E2.<>E__0.Member()", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); } [Fact] - public void LiteralReceiver_Property_Integer_Get() + public void PrimaryCtorParameterCapturing_12() { - var src = """ -_ = 1.Property; - -static class E + // only static candidate method + var source = """ +struct S1(Color Color) { - extension(int i) + public void Test() { - public int Property { get { System.Console.Write("get"); return 42; } } + Color.Member(); + M(this); } -} -"""; - var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "get").VerifyDiagnostics(); - var tree = comp.SyntaxTrees.Single(); - var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "1.Property"); - Assert.Equal("System.Int32 E.<>E__0.Property { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); - } + public static void M(T x) where T : unmanaged { } +} - [Fact] - public void LiteralReceiver_Property_Integer_Set() - { - var src = """ -1.Property = 1; +class Color +{ +} static class E { - extension(int i) + extension(Color) { - public int Property { set => throw null; } + public static void Member() { } } } """; - var comp = CreateCompilation(src); - // Consider improving the error message + var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( - // (1,1): error CS0131: The left-hand side of an assignment must be a variable, property or indexer - // 1.Property = 1; - Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "1.Property").WithLocation(1, 1)); + // (1,17): warning CS9113: Parameter 'Color' is unread. + // struct S1(Color Color) + Diagnostic(ErrorCode.WRN_UnreadPrimaryConstructorParameter, "Color").WithArguments("Color").WithLocation(1, 17)); - var tree = comp.SyntaxTrees.Single(); + var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "1.Property"); - Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); - Assert.Equal(["System.Int32 E.<>E__0.Property { set; }"], model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); - Assert.Equal(CandidateReason.NotAVariable, model.GetSymbolInfo(memberAccess).CandidateReason); + var memberAccess = GetSyntax(tree, "Color.Member"); + Assert.Equal("void E.<>E__0.Member()", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); } [Fact] - public void LiteralReceiver_Property_Null() + public void PrimaryCtorParameterCapturing_13() { - var src = """ -null.Property = 1; -_ = null.Property; + // only static candidate property, invocable + var source = """ +struct S1(Color Color) +{ + public void Test() + { + Color.Member(); + M(this); + } + + public static void M(T x) where T : unmanaged { } +} + +class Color +{ +} static class E { - extension(object o) + extension(Color) { - public int Property { get => throw null; set => throw null; } + public static System.Action Member => throw null; } } """; - var comp = CreateCompilation(src); + var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( - // (1,1): error CS0023: Operator '.' cannot be applied to operand of type '' - // null.Property = 1; - Diagnostic(ErrorCode.ERR_BadUnaryOp, "null.Property").WithArguments(".", "").WithLocation(1, 1), - // (2,5): error CS0023: Operator '.' cannot be applied to operand of type '' - // _ = null.Property; - Diagnostic(ErrorCode.ERR_BadUnaryOp, "null.Property").WithArguments(".", "").WithLocation(2, 5)); + // (1,17): warning CS9113: Parameter 'Color' is unread. + // struct S1(Color Color) + Diagnostic(ErrorCode.WRN_UnreadPrimaryConstructorParameter, "Color").WithArguments("Color").WithLocation(1, 17)); - var tree = comp.SyntaxTrees.Single(); + var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); - var memberAccess1 = GetSyntaxes(tree, "null.Property").First(); - Assert.Null(model.GetSymbolInfo(memberAccess1).Symbol); - Assert.Equal([], model.GetSymbolInfo(memberAccess1).CandidateSymbols.ToTestDisplayStrings()); - Assert.Equal(CandidateReason.None, model.GetSymbolInfo(memberAccess1).CandidateReason); - - var memberAccess2 = GetSyntaxes(tree, "null.Property").Last(); - Assert.Null(model.GetSymbolInfo(memberAccess2).Symbol); - Assert.Equal([], model.GetSymbolInfo(memberAccess2).CandidateSymbols.ToTestDisplayStrings()); - Assert.Equal(CandidateReason.None, model.GetSymbolInfo(memberAccess2).CandidateReason); + var memberAccess = GetSyntax(tree, "Color.Member"); + Assert.Equal("System.Action E.<>E__0.Member { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); } [Fact] - public void LiteralReceiver_Property_Default() + public void PrimaryCtorParameterCapturing_14() { - var src = """ -default.Property = 1; -_ = default.Property; + // only static candidate property, non-invocable + var source = """ +struct S1(Color Color) +{ + public void Test() + { + Color.Member(); + M(this); + } + + public static void M(T x) where T : unmanaged { } +} + +class Color +{ +} static class E { - extension(object o) + extension(Color) { - public int Property { get => throw null; set => throw null; } + public static int Member => 0; } } """; - var comp = CreateCompilation(src); + var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( - // (1,1): error CS8716: There is no target type for the default literal. - // default.Property = 1; - Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(1, 1), - // (2,5): error CS8716: There is no target type for the default literal. - // _ = default.Property; - Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(2, 5)); + // (1,17): warning CS9113: Parameter 'Color' is unread. + // struct S1(Color Color) + Diagnostic(ErrorCode.WRN_UnreadPrimaryConstructorParameter, "Color").WithArguments("Color").WithLocation(1, 17), + // (5,15): error CS1061: 'Color' does not contain a definition for 'Member' and no accessible extension method 'Member' accepting a first argument of type 'Color' could be found (are you missing a using directive or an assembly reference?) + // Color.Member(); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Member").WithArguments("Color", "Member").WithLocation(5, 15)); - var tree = comp.SyntaxTrees.Single(); + var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); - var memberAccess1 = GetSyntaxes(tree, "default.Property").First(); - Assert.Equal("System.Int32 E.<>E__0.Property { get; set; }", model.GetSymbolInfo(memberAccess1).Symbol.ToTestDisplayString()); - Assert.Equal([], model.GetSymbolInfo(memberAccess1).CandidateSymbols.ToTestDisplayStrings()); - Assert.Equal(CandidateReason.None, model.GetSymbolInfo(memberAccess1).CandidateReason); - - var memberAccess2 = GetSyntaxes(tree, "default.Property").Last(); - Assert.Equal("System.Int32 E.<>E__0.Property { get; set; }", model.GetSymbolInfo(memberAccess2).Symbol.ToTestDisplayString()); - Assert.Equal([], model.GetSymbolInfo(memberAccess2).CandidateSymbols.ToTestDisplayStrings()); - Assert.Equal(CandidateReason.None, model.GetSymbolInfo(memberAccess2).CandidateReason); + var memberAccess = GetSyntax(tree, "Color.Member"); + Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); } [Fact] - public void LiteralReceiver_Property_Tuple_Get() + public void PrimaryCtorParameterCapturing_15() { - var src = """ -_ = (1, 2).Property; + // only instance candidate property, invocable + var source = """ +struct S1(Color Color) +{ + public void Test() + { + Color.Member(); + M(this); + } + + public static void M(T x) where T : unmanaged { } +} + +class Color +{ +} static class E { - extension((int, int) t) + extension(Color c) { - public int Property { get { System.Console.Write("get "); return 42; } } + public System.Action Member => throw null; } } """; - var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "get").VerifyDiagnostics(); + var comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (6,9): error CS8377: The type 'S1' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'S1.M(T)' + // M(this); + Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("S1.M(T)", "T", "S1").WithLocation(6, 9)); - var tree = comp.SyntaxTrees.Single(); + var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "(1, 2).Property"); - Assert.Equal("System.Int32 E.<>E__0.Property { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); + var memberAccess = GetSyntax(tree, "Color.Member"); + Assert.Equal("System.Action E.<>E__0.Member { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); } [Fact] - public void LiteralReceiver_Property_Tuple_Set() + public void PrimaryCtorParameterCapturing_16() { - var src = """ -(1, 2).Property = 1; + // only instance candidate property, non-invocable + var source = """ +struct S1(Color Color) +{ + public void Test() + { + Color.Member(); + M(this); + } + + public static void M(T x) where T : unmanaged { } +} + +class Color +{ +} static class E { - extension((int, int) t) + extension(Color c) { - public int Property { set { System.Console.Write($"set(value)"); }} + public int Member => 0; } } """; - var comp = CreateCompilation(src); - // Consider improving the error message + var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( - // (1,1): error CS0131: The left-hand side of an assignment must be a variable, property or indexer - // (1, 2).Property = 1; - Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "(1, 2).Property").WithLocation(1, 1)); + // (1,17): warning CS9113: Parameter 'Color' is unread. + // struct S1(Color Color) + Diagnostic(ErrorCode.WRN_UnreadPrimaryConstructorParameter, "Color").WithArguments("Color").WithLocation(1, 17), + // (5,15): error CS1061: 'Color' does not contain a definition for 'Member' and no accessible extension method 'Member' accepting a first argument of type 'Color' could be found (are you missing a using directive or an assembly reference?) + // Color.Member(); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Member").WithArguments("Color", "Member").WithLocation(5, 15)); - var tree = comp.SyntaxTrees.Single(); + var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "(1, 2).Property"); + var memberAccess = GetSyntax(tree, "Color.Member"); Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); - Assert.Equal(["System.Int32 E.<>E__0.Property { set; }"], model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); - Assert.Equal(CandidateReason.NotAVariable, model.GetSymbolInfo(memberAccess).CandidateReason); } [Fact] - public void LiteralReceiver_Property_Tuple_Default() + public void PrimaryCtorParameterCapturing_17() { - var src = """ -(default, default).Property = 1; -_ = (default, default).Property; + // non-extension method not applicable due to arity + var source = """ +new S1(new Color()).Test(); + +struct S1(Color Color) +{ + public void Test() + { + Color.Member(0); + } +} + +class Color +{ + public static void Member(int x) => throw null; +} static class E { - extension((object, object) t) + extension(Color c) { - public int Property { get => throw null; set => throw null; } + public void Member(T x) { System.Console.WriteLine("extension"); } } } """; - var comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics( - // (1,2): error CS8716: There is no target type for the default literal. - // (default, default).Property = 1; - Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(1, 2), - // (1,11): error CS8716: There is no target type for the default literal. - // (default, default).Property = 1; - Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(1, 11), - // (2,6): error CS8716: There is no target type for the default literal. - // _ = (default, default).Property; - Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(2, 6), - // (2,15): error CS8716: There is no target type for the default literal. - // _ = (default, default).Property; - Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(2, 15)); + var comp = CreateCompilation(source); - var tree = comp.SyntaxTrees.Single(); - var model = comp.GetSemanticModel(tree); - var memberAccess1 = GetSyntaxes(tree, "(default, default).Property").First(); - Assert.Null(model.GetSymbolInfo(memberAccess1).Symbol); - Assert.Equal([], model.GetSymbolInfo(memberAccess1).CandidateSymbols.ToTestDisplayStrings()); - Assert.Equal(CandidateReason.None, model.GetSymbolInfo(memberAccess1).CandidateReason); + CompileAndVerify(comp, expectedOutput: "extension").VerifyDiagnostics(); - var memberAccess2 = GetSyntaxes(tree, "(default, default).Property").Last(); - Assert.Null(model.GetSymbolInfo(memberAccess2).Symbol); - Assert.Equal([], model.GetSymbolInfo(memberAccess2).CandidateSymbols.ToTestDisplayStrings()); - Assert.Equal(CandidateReason.None, model.GetSymbolInfo(memberAccess2).CandidateReason); + Assert.NotEmpty(comp.GetTypeByMetadataName("S1").InstanceConstructors.OfType().Single().GetCapturedParameters()); } [Fact] - public void LiteralReceiver_Property_Tuple_Integer_ForLong() + public void PrimaryCtorParameterCapturing_18() { - var src = """ -(1, 1).Property = 1; -_ = (2, 2).Property; + // non-extension method not applicable due to arity, and non-extension method applicable, and instance extension method + var source = """ +struct S1(Color Color) +{ + public void Test() + { + Color.Member(0); + } +} + +class Color +{ + public static void Member(int x) => throw null; + public static void Member(T x) => throw null; +} static class E { - extension((long, long) t) + extension(Color c) { - public int Property { get => throw null; set => throw null; } + public void Member(T x) { System.Console.WriteLine("extension"); } } } """; - var comp = CreateCompilation(src); + var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( - // (1,1): error CS9286: '(int, int)' does not contain a definition for 'Property' and no accessible extension member 'Property' for receiver of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) - // (1, 1).Property = 1; - Diagnostic(ErrorCode.ERR_ExtensionResolutionFailed, "(1, 1).Property").WithArguments("(int, int)", "Property").WithLocation(1, 1), - // (2,5): error CS9286: '(int, int)' does not contain a definition for 'Property' and no accessible extension member 'Property' for receiver of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) - // _ = (2, 2).Property; - Diagnostic(ErrorCode.ERR_ExtensionResolutionFailed, "(2, 2).Property").WithArguments("(int, int)", "Property").WithLocation(2, 5)); - - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : review the behavior of the semantic model APIs - var tree = comp.SyntaxTrees.Single(); - var model = comp.GetSemanticModel(tree); - var memberAccess1 = GetSyntax(tree, "(1, 1).Property"); - Assert.Equal("System.Int32 E.<>E__0.Property { get; set; }", model.GetSymbolInfo(memberAccess1).Symbol.ToTestDisplayString()); - Assert.Equal([], model.GetSymbolInfo(memberAccess1).CandidateSymbols.ToTestDisplayStrings()); - Assert.Equal(CandidateReason.None, model.GetSymbolInfo(memberAccess1).CandidateReason); - - var memberAccess2 = GetSyntax(tree, "(2, 2).Property"); - Assert.Equal("System.Int32 E.<>E__0.Property { get; set; }", model.GetSymbolInfo(memberAccess2).Symbol.ToTestDisplayString()); - Assert.Equal([], model.GetSymbolInfo(memberAccess2).CandidateSymbols.ToTestDisplayStrings()); - Assert.Equal(CandidateReason.None, model.GetSymbolInfo(memberAccess2).CandidateReason); + // (5,9): error CS9106: Identifier 'Color' is ambiguous between type 'Color' and parameter 'Color Color' in this context. + // Color.Member(0); + Diagnostic(ErrorCode.ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver, "Color").WithArguments("Color", "Color", "Color Color").WithLocation(5, 9)); } [Fact] - public void PreferMoreSpecific_Static_MethodAndProperty() + public void PrimaryCtorParameterCapturing_19() { - var src = """ -System.Console.Write(object.M); + // non-extension method not applicable due to arity, and non-extension method applicable, and static extension method + var source = """ +new S1(new Color()).Test(); -static class E1 +struct S1(Color Color) { - extension(object) + public void Test() { - public static string M() => throw null; + Color.Member(0); } } -static class E2 +class Color { - extension(object) + public static void Member(int x) => throw null; + public static void Member(T x) => throw null; +} + +static class E +{ + extension(Color) { - public static string M => throw null; + public static void Member(T x) { System.Console.WriteLine("extension"); } } } """; - var comp = CreateCompilation(src); + var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( - // (1,22): error CS9286: 'object' does not contain a definition for 'M' and no accessible extension member 'M' for receiver of type 'object' could be found (are you missing a using directive or an assembly reference?) - // System.Console.Write(object.M); - Diagnostic(ErrorCode.ERR_ExtensionResolutionFailed, "object.M").WithArguments("object", "M").WithLocation(1, 22)); - - var tree = comp.SyntaxTrees.Single(); - var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "object.M"); - Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); - Assert.Equal(["System.String E1.<>E__0.M()", "System.String E2.<>E__0.M { get; }"], - model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); - Assert.Empty(model.GetMemberGroup(memberAccess)); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : consider handling BoundBadExpression better + // (3,17): warning CS9113: Parameter 'Color' is unread. + // struct S1(Color Color) + Diagnostic(ErrorCode.WRN_UnreadPrimaryConstructorParameter, "Color").WithArguments("Color").WithLocation(3, 17)); } [Fact] - public void PreferMoreSpecific_Static_MethodAndProperty_Generic() + public void InstanceMethod_MemberAccess() { var src = """ -System.Console.Write(object.M); - -static class E1 -{ - extension(T) - { - public static string M() => throw null; - } -} +new object().M.ToString(); -static class E2 +static class E { - extension(T) + extension(object o) { - public static string M => throw null; + public int M() => 42; } } """; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( - // (1,22): error CS9286: 'object' does not contain a definition for 'M' and no accessible extension member 'M' for receiver of type 'object' could be found (are you missing a using directive or an assembly reference?) - // System.Console.Write(object.M); - Diagnostic(ErrorCode.ERR_ExtensionResolutionFailed, "object.M").WithArguments("object", "M").WithLocation(1, 22)); + // (1,14): error CS0119: 'E.extension(object).M()' is a method, which is not valid in the given context + // new object().M.ToString(); + Diagnostic(ErrorCode.ERR_BadSKunknown, "M").WithArguments("E.extension(object).M()", "method").WithLocation(1, 14)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "object.M"); + var memberAccess = GetSyntax(tree, "new object().M"); Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); + Assert.Equal([], model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); + Assert.Equal([], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : consider handling BoundBadExpression better - Assert.Equal(["System.String E1.<>E__0.M()", "System.String E2.<>E__0.M { get; }"], - model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); - Assert.Empty(model.GetMemberGroup(memberAccess)); + src = """ +new object().M.ToString(); + +static class E +{ + public static int M(this object o) => 42; +} +"""; + comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (1,14): error CS0119: 'E.M(object)' is a method, which is not valid in the given context + // new object().M.ToString(); + Diagnostic(ErrorCode.ERR_BadSKunknown, "M").WithArguments("E.M(object)", "method").WithLocation(1, 14)); + + tree = comp.SyntaxTrees.Single(); + model = comp.GetSemanticModel(tree); + memberAccess = GetSyntax(tree, "new object().M"); + Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); + Assert.Equal([], model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); + Assert.Equal([], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); } [Fact] - public void PreferMoreSpecific_Static_MethodAndProperty_Invocation() + public void InstanceMethod_MemberAccess_Missing() { var src = """ -System.Console.Write(object.M()); +new object().M.ToString(); +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (1,14): error CS1061: 'object' does not contain a definition for 'M' and no accessible extension method 'M' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) + // new object().M.ToString(); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M").WithArguments("object", "M").WithLocation(1, 14)); + } -static class E1 -{ - extension(object) + [Fact] + public void CheckValueKind_AssignToMethodGroup() { - public static string M() => "ran"; - } -} + var src = """ +object.M = null; -static class E2 +static class E { extension(object) { - public static string M => throw null; // not invocable + public static void M() { } } } """; var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "ran").VerifyDiagnostics(); + comp.VerifyEmitDiagnostics( + // (1,1): error CS1656: Cannot assign to 'M' because it is a 'method group' + // object.M = null; + Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "object.M").WithArguments("M", "method group").WithLocation(1, 1)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var memberAccess = GetSyntax(tree, "object.M"); - Assert.Equal("System.String E1.<>E__0.M()", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); - Assert.Equal([], model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); - Assert.Equal(["System.String E1.<>E__0.M()", "System.String E2.<>E__0.M { get; }"], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); + Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); + Assert.Equal(["void E.<>E__0.M()"], model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); + Assert.Equal(CandidateReason.NotAVariable, model.GetSymbolInfo(memberAccess).CandidateReason); + Assert.Equal(["void E.<>E__0.M()"], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); } [Fact] - public void GetCompatibleExtensions_TwoSubstitutions() + public void AccessOnVoid_Invocation() { var src = """ -C.M(); -new C().M2(); - -interface I { } -class C : I, I { } +object.M().ToString(); static class E { - extension(I) + extension(object) { public static void M() { } } - - public static void M2(this I i) { } } """; var comp = CreateCompilation(src); - comp.VerifyDiagnostics( - // (1,3): error CS1061: 'C' does not contain a definition for 'M' and no accessible extension method 'M' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) - // C.M(); - Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M").WithArguments("C", "M").WithLocation(1, 3), - // (2,9): error CS1061: 'C' does not contain a definition for 'M2' and no accessible extension method 'M2' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) - // new C().M2(); - Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M2").WithArguments("C", "M2").WithLocation(2, 9)); - - var tree = comp.SyntaxTrees.Single(); - var model = comp.GetSemanticModel(tree); + comp.VerifyEmitDiagnostics( + // (1,11): error CS0023: Operator '.' cannot be applied to operand of type 'void' + // object.M().ToString(); + Diagnostic(ErrorCode.ERR_BadUnaryOp, ".").WithArguments(".", "void").WithLocation(1, 11)); + } - var memberAccess1 = GetSyntax(tree, "C.M"); - Assert.Null(model.GetSymbolInfo(memberAccess1).Symbol); - Assert.Equal([], model.GetSymbolInfo(memberAccess1).CandidateSymbols.ToTestDisplayStrings()); - Assert.Empty(model.GetMemberGroup(memberAccess1)); - - var memberAccess2 = GetSyntax(tree, "new C().M2"); - Assert.Null(model.GetSymbolInfo(memberAccess2).Symbol); - Assert.Equal([], model.GetSymbolInfo(memberAccess2).CandidateSymbols.ToTestDisplayStrings()); - Assert.Empty(model.GetMemberGroup(memberAccess2)); - } - - [Theory, ClassData(typeof(ThreePermutationGenerator))] - public void PreferMoreSpecific_Static_MethodAndMoreSpecificInvocablePropertyAndMoreSpecificMethod(int first, int second, int third) + [Fact] + public void ExtensionMemberLookup_InaccessibleMembers() { - string[] segments = [ - """ - static class E1 - { - extension(object) - { - public static string M() => throw null; - } - } - """, - """ - static class E2 - { - extension(C) - { - public static System.Func M => null; - } - } - """, - """ - static class E3 - { - extension(C) - { - public static string M() => throw null; - } - } - """]; - - var src = $$""" -System.Console.Write(C.M()); - -class C { } - -{{segments[first]}} - -{{segments[second]}} + var src = """ +object.Method(); +_ = object.Property; -{{segments[third]}} +static class E +{ + extension(object o) + { + private static void Method() => throw null; + private static int Property => throw null; + } +} """; var comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics( - // (1,22): error CS9286: 'C' does not contain a definition for 'M' and no accessible extension member 'M' for receiver of type 'C' could be found (are you missing a using directive or an assembly reference?) - // System.Console.Write(C.M()); - Diagnostic(ErrorCode.ERR_ExtensionResolutionFailed, "C.M").WithArguments("C", "M").WithLocation(1, 22)); + // (1,8): error CS0117: 'object' does not contain a definition for 'Method' + // object.Method(); + Diagnostic(ErrorCode.ERR_NoSuchMember, "Method").WithArguments("object", "Method").WithLocation(1, 8), + // (2,12): error CS0117: 'object' does not contain a definition for 'Property' + // _ = object.Property; + Diagnostic(ErrorCode.ERR_NoSuchMember, "Property").WithArguments("object", "Property").WithLocation(2, 12)); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var memberAccess1 = GetSyntax(tree, "object.Method"); + Assert.Equal(["void E.<>E__0.Method()"], model.GetMemberGroup(memberAccess1).ToTestDisplayStrings()); + + var memberAccess2 = GetSyntax(tree, "object.Property"); + Assert.Equal([], model.GetMemberGroup(memberAccess2).ToTestDisplayStrings()); // Tracked by https://github.com/dotnet/roslyn/issues/78957 : handle GetMemberGroup on a property access } [Fact] - public void AmbiguousCallOnInterface() + public void ExtensionMemberLookup_InterpolationHandler_Simple() { var src = """ -I2.M(); +_ = f($"{(object)1} {f2()}"); -interface I +static int f(InterpolationHandler s) => 0; +static string f2() => "hello"; + +[System.Runtime.CompilerServices.InterpolatedStringHandler] +public struct InterpolationHandler { - public static void M() { } + public InterpolationHandler(int literalLength, int formattedCount) => throw null; + public void AppendLiteral(string value) { } + public void AppendFormatted(T hole, int alignment = 0, string format = null) => throw null; } - -interface I2 : I, I { } """; + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - // Tracked by https://github.com/dotnet/roslyn/issues/78830 : diagnostic quality, consider improving the symbols in this error message - comp.VerifyEmitDiagnostics( - // (1,4): error CS0121: The call is ambiguous between the following methods or properties: 'I.M()' and 'I.M()' - // I2.M(); - Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("I.M()", "I.M()").WithLocation(1, 4)); + comp.VerifyEmitDiagnostics(); } [Fact] - public void AmbiguousCallOnInterface_Generic() + public void ExtensionMemberLookup_InterpolationHandler_AppendLiteralExtensionMethod() { var src = """ -I2.M(); +_ = f($"{(object)1} {f2()}"); -interface I +static int f(InterpolationHandler s) => 0; +static string f2() => "hello"; + +[System.Runtime.CompilerServices.InterpolatedStringHandler] +public struct InterpolationHandler { - public static void M() { } + public InterpolationHandler(int literalLength, int formattedCount) => throw null; + public void AppendFormatted(T hole, int alignment = 0, string format = null) => throw null; } -interface I2 : I, I { } +public static class Extensions +{ + public static void AppendLiteral(this InterpolationHandler ih, string value) { } +} """; + + // Interpolation handlers don't allow extension methods var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); comp.VerifyEmitDiagnostics( - // (1,4): error CS0121: The call is ambiguous between the following methods or properties: 'I.M()' and 'I.M()' - // I2.M(); - Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("I.M()", "I.M()").WithLocation(1, 4)); + // (1,20): error CS1061: 'InterpolationHandler' does not contain a definition for 'AppendLiteral' and no accessible extension method 'AppendLiteral' accepting a first argument of type 'InterpolationHandler' could be found (are you missing a using directive or an assembly reference?) + // _ = f($"{(object)1} {f2()}"); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, " ").WithArguments("InterpolationHandler", "AppendLiteral").WithLocation(1, 20), + // (1,20): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. + // _ = f($"{(object)1} {f2()}"); + Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, " ").WithArguments("?.()").WithLocation(1, 20)); } [Fact] - public void OmittedTypeArguments() + public void ExtensionMemberLookup_InterpolationHandler_AppendLiteralExtensionDeclarationMethod() { var src = """ -object.P; -object.P<>; +_ = f($"{(object)1} {f2()}"); + +static int f(InterpolationHandler s) => 0; +static string f2() => "hello"; + +[System.Runtime.CompilerServices.InterpolatedStringHandler] +public struct InterpolationHandler +{ + public InterpolationHandler(int literalLength, int formattedCount) => throw null; + public void AppendFormatted(T hole, int alignment = 0, string format = null) => throw null; +} static class E { - extension(object) + extension(InterpolationHandler i) { - public static int P => 42; + public void AppendLiteral(string value) { } } } """; + + // Interpolation handlers don't allow extension methods var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); comp.VerifyEmitDiagnostics( - // (1,1): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement - // object.P; - Diagnostic(ErrorCode.ERR_IllegalStatement, "object.P").WithLocation(1, 1), - // (1,8): error CS0117: 'object' does not contain a definition for 'P' - // object.P; - Diagnostic(ErrorCode.ERR_NoSuchMember, "P").WithArguments("object", "P").WithLocation(1, 8), - // (2,1): error CS8389: Omitting the type argument is not allowed in the current context - // object.P<>; - Diagnostic(ErrorCode.ERR_OmittedTypeArgument, "object.P<>").WithLocation(2, 1), - // (2,1): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement - // object.P<>; - Diagnostic(ErrorCode.ERR_IllegalStatement, "object.P<>").WithLocation(2, 1), - // (2,8): error CS0117: 'object' does not contain a definition for 'P' - // object.P<>; - Diagnostic(ErrorCode.ERR_NoSuchMember, "P<>").WithArguments("object", "P").WithLocation(2, 8)); + // (1,20): error CS1061: 'InterpolationHandler' does not contain a definition for 'AppendLiteral' and no accessible extension method 'AppendLiteral' accepting a first argument of type 'InterpolationHandler' could be found (are you missing a using directive or an assembly reference?) + // _ = f($"{(object)1} {f2()}"); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, " ").WithArguments("InterpolationHandler", "AppendLiteral").WithLocation(1, 20), + // (1,20): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. + // _ = f($"{(object)1} {f2()}"); + Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, " ").WithArguments("?.()").WithLocation(1, 20)); } [Fact] - public void ExtensionMemberLookup_PatternBased_ForEach_NoMethod() + public void ExtensionMemberLookup_InterpolationHandler_AppendFormattedExtensionMethod() { var src = """ -foreach (var x in new C()) +/**/ +_ = f($"{(object)1} {f2()}"); +/**/ + +static int f(InterpolationHandler s) => 0; +static string f2() => "hello"; + +[System.Runtime.CompilerServices.InterpolatedStringHandler] +public struct InterpolationHandler { - System.Console.Write(x); - break; + public InterpolationHandler(int literalLength, int formattedCount) => throw null; + public void AppendLiteral(string value) { } } -class C { } -class D { } - -static class E +public static class Extensions { - extension(C c) - { - public D GetEnumerator() => new D(); - } - extension(D d) - { - public bool MoveNext() => true; - public int Current => 42; - } + public static void AppendFormatted(this InterpolationHandler ih, T hole, int alignment = 0, string format = null) { } } """; - var comp = CreateCompilation(src); - comp.VerifyDiagnostics( - // (1,19): error CS0117: 'D' does not contain a definition for 'Current' - // foreach (var x in new C()) - Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("D", "Current").WithLocation(1, 19), - // (1,19): error CS0202: foreach requires that the return type 'D' of 'E.extension(C).GetEnumerator()' must have a suitable public 'MoveNext' method and public 'Current' property - // foreach (var x in new C()) - Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new C()").WithArguments("D", "E.extension(C).GetEnumerator()").WithLocation(1, 19) - ); - var tree = comp.SyntaxTrees.Single(); - var model = comp.GetSemanticModel(tree); - var loop = tree.GetRoot().DescendantNodes().OfType().Single(); - Assert.Null(model.GetForEachStatementInfo(loop).GetEnumeratorMethod); - Assert.Null(model.GetForEachStatementInfo(loop).MoveNextMethod); - Assert.Null(model.GetForEachStatementInfo(loop).CurrentProperty); + // Interpolation handlers don't allow extension methods + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics( + // (2,9): error CS1061: 'InterpolationHandler' does not contain a definition for 'AppendFormatted' and no accessible extension method 'AppendFormatted' accepting a first argument of type 'InterpolationHandler' could be found (are you missing a using directive or an assembly reference?) + // _ = f($"{(object)1} {f2()}"); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "{(object)1}").WithArguments("InterpolationHandler", "AppendFormatted").WithLocation(2, 9), + // (2,9): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. + // _ = f($"{(object)1} {f2()}"); + Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{(object)1}").WithArguments("?.()").WithLocation(2, 9), + // (2,21): error CS1061: 'InterpolationHandler' does not contain a definition for 'AppendFormatted' and no accessible extension method 'AppendFormatted' accepting a first argument of type 'InterpolationHandler' could be found (are you missing a using directive or an assembly reference?) + // _ = f($"{(object)1} {f2()}"); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "{f2()}").WithArguments("InterpolationHandler", "AppendFormatted").WithLocation(2, 21), + // (2,21): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. + // _ = f($"{(object)1} {f2()}"); + Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{f2()}").WithArguments("?.()").WithLocation(2, 21) + ); } [Fact] - public void ExtensionMemberLookup_PatternBased_ForEach_NoApplicableMethod() + public void ExtensionMemberLookup_InterpolationHandler_AppendFormattedExtensionTypeMethod() { var src = """ -foreach (var x in new C()) -{ - System.Console.Write(x); - break; -} +_ = f($"{(object)1} {f2()}"); -class C +static int f(InterpolationHandler s) => 0; +static string f2() => "hello"; + +[System.Runtime.CompilerServices.InterpolatedStringHandler] +public struct InterpolationHandler { - public void GetEnumerator(int notApplicable) { } // not applicable + public InterpolationHandler(int literalLength, int formattedCount) => throw null; + public void AppendLiteral(string value) { } } -class D { } static class E { - extension(C c) - { - public D GetEnumerator() => new D(); - } - extension(D d) + extension(InterpolationHandler i) { - public bool MoveNext() => true; - public int Current => 42; + public void AppendFormatted(T hole, int alignment = 0, string format = null) { } } } """; - var comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics( - // (1,19): error CS0117: 'D' does not contain a definition for 'Current' - // foreach (var x in new C()) - Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("D", "Current").WithLocation(1, 19), - // (1,19): error CS0202: foreach requires that the return type 'D' of 'E.extension(C).GetEnumerator()' must have a suitable public 'MoveNext' method and public 'Current' property - // foreach (var x in new C()) - Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new C()").WithArguments("D", "E.extension(C).GetEnumerator()").WithLocation(1, 19) - ); - var tree = comp.SyntaxTrees.Single(); - var model = comp.GetSemanticModel(tree); - var loop = tree.GetRoot().DescendantNodes().OfType().Single(); - Assert.Null(model.GetForEachStatementInfo(loop).GetEnumeratorMethod); - Assert.Null(model.GetForEachStatementInfo(loop).MoveNextMethod); - Assert.Null(model.GetForEachStatementInfo(loop).CurrentProperty); + // Interpolation handlers don't allow extension methods + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics( + // (1,9): error CS1061: 'InterpolationHandler' does not contain a definition for 'AppendFormatted' and no accessible extension method 'AppendFormatted' accepting a first argument of type 'InterpolationHandler' could be found (are you missing a using directive or an assembly reference?) + // _ = f($"{(object)1} {f2()}"); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "{(object)1}").WithArguments("InterpolationHandler", "AppendFormatted").WithLocation(1, 9), + // (1,9): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. + // _ = f($"{(object)1} {f2()}"); + Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{(object)1}").WithArguments("?.()").WithLocation(1, 9), + // (1,21): error CS1061: 'InterpolationHandler' does not contain a definition for 'AppendFormatted' and no accessible extension method 'AppendFormatted' accepting a first argument of type 'InterpolationHandler' could be found (are you missing a using directive or an assembly reference?) + // _ = f($"{(object)1} {f2()}"); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "{f2()}").WithArguments("InterpolationHandler", "AppendFormatted").WithLocation(1, 21), + // (1,21): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. + // _ = f($"{(object)1} {f2()}"); + Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{f2()}").WithArguments("?.()").WithLocation(1, 21)); } [Fact] - public void ExtensionMemberLookup_PatternBased_ForEach_WrongArity() + public void LiteralReceiver_Property_Enum_Set() { var src = """ -using System.Collections; - -foreach (var x in new C()) { } +Enum.Zero.Property = 1; -class C { } +enum Enum +{ + Zero +} static class E { - extension(C c) + extension(Enum e) { - public IEnumerator GetEnumerator() => throw null; + public int Property { set => throw null; } } } """; var comp = CreateCompilation(src); + // Consider improving the error message comp.VerifyEmitDiagnostics( - // (3,19): error CS0411: The type arguments for method 'E.extension(C).GetEnumerator()' cannot be inferred from the usage. Try specifying the type arguments explicitly. - // foreach (var x in new C()) { } - Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "new C()").WithArguments("E.extension(C).GetEnumerator()").WithLocation(3, 19), - // (3,19): error CS1579: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator' - // foreach (var x in new C()) { } - Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new C()").WithArguments("C", "GetEnumerator").WithLocation(3, 19)); + // (1,1): error CS0131: The left-hand side of an assignment must be a variable, property or indexer + // Enum.Zero.Property = 1; + Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "Enum.Zero.Property").WithLocation(1, 1)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); - var loop = tree.GetRoot().DescendantNodes().OfType().Single(); - Assert.Null(model.GetForEachStatementInfo(loop).GetEnumeratorMethod); + var memberAccess = GetSyntax(tree, "Enum.Zero.Property"); + Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); + Assert.Equal(["System.Int32 E.<>E__0.Property { set; }"], model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); + Assert.Equal(CandidateReason.NotAVariable, model.GetSymbolInfo(memberAccess).CandidateReason); + Assert.Equal([], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); // Tracked by https://github.com/dotnet/roslyn/issues/78957 : handle GetMemberGroup on a property access } [Fact] - public void ExtensionMemberLookup_PatternBased_ForEach_NonInvocable() + public void LiteralReceiver_Property_Integer_ForLong() { var src = """ -using System.Collections; - -foreach (var x in new C()) { } - -class C { } +1.Property = 42; +_ = 2.Property; static class E { - extension(C c) + extension(long l) { - public IEnumerator GetEnumerator => throw null; + public int Property { get { System.Console.Write("get "); return 42; } set { System.Console.Write("set "); } } } } """; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( - // (3,19): error CS1579: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator' - // foreach (var x in new C()) { } - Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new C()").WithArguments("C", "GetEnumerator").WithLocation(3, 19)); + // (1,1): error CS9286: 'int' does not contain a definition for 'Property' and no accessible extension member 'Property' for receiver of type 'int' could be found (are you missing a using directive or an assembly reference?) + // 1.Property = 42; + Diagnostic(ErrorCode.ERR_ExtensionResolutionFailed, "1.Property").WithArguments("int", "Property").WithLocation(1, 1), + // (2,5): error CS9286: 'int' does not contain a definition for 'Property' and no accessible extension member 'Property' for receiver of type 'int' could be found (are you missing a using directive or an assembly reference?) + // _ = 2.Property; + Diagnostic(ErrorCode.ERR_ExtensionResolutionFailed, "2.Property").WithArguments("int", "Property").WithLocation(2, 5)); + // Tracked by https://github.com/dotnet/roslyn/issues/76130 : review the behavior of the semantic model APIs var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); - var loop = tree.GetRoot().DescendantNodes().OfType().Single(); - Assert.Null(model.GetForEachStatementInfo(loop).GetEnumeratorMethod); + var memberAccess1 = GetSyntax(tree, "1.Property"); + Assert.Equal("System.Int32 E.<>E__0.Property { get; set; }", model.GetSymbolInfo(memberAccess1).Symbol.ToTestDisplayString()); + Assert.Equal([], model.GetSymbolInfo(memberAccess1).CandidateSymbols.ToTestDisplayStrings()); + Assert.Equal(CandidateReason.None, model.GetSymbolInfo(memberAccess1).CandidateReason); + + var memberAccess2 = GetSyntax(tree, "2.Property"); + Assert.Equal("System.Int32 E.<>E__0.Property { get; set; }", model.GetSymbolInfo(memberAccess2).Symbol.ToTestDisplayString()); + Assert.Equal([], model.GetSymbolInfo(memberAccess2).CandidateSymbols.ToTestDisplayStrings()); + Assert.Equal(CandidateReason.None, model.GetSymbolInfo(memberAccess2).CandidateReason); } [Fact] - public void ExtensionMemberLookup_PatternBased_ForEach_DelegateTypeProperty() + public void LiteralReceiver_Property_String() { var src = """ -using System.Collections; - -foreach (var x in new C()) { } - -class C { } +"".Property = 42; +_ = "".Property; static class E { - extension(C c) + extension(string s) { - public System.Func GetEnumerator => throw null; + public int Property { get { System.Console.Write("get "); return 42; } set { System.Console.Write("set "); } } } } """; var comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics( - // (3,19): error CS1579: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator' - // foreach (var x in new C()) { } - Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new C()").WithArguments("C", "GetEnumerator").WithLocation(3, 19)); + CompileAndVerify(comp, expectedOutput: "set get").VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); - var loop = tree.GetRoot().DescendantNodes().OfType().Single(); - Assert.Null(model.GetForEachStatementInfo(loop).GetEnumeratorMethod); - - src = """ -using System.Collections; - -foreach (var x in new C()) { } + var memberAccess1 = GetSyntaxes(tree, "\"\".Property").First(); + Assert.Equal("System.Int32 E.<>E__0.Property { get; set; }", model.GetSymbolInfo(memberAccess1).Symbol.ToTestDisplayString()); -class C -{ - public System.Func GetEnumerator => throw null; -} -"""; - comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics( - // (3,19): warning CS0280: 'C' does not implement the 'collection' pattern. 'C.GetEnumerator' has the wrong signature. - // foreach (var x in new C()) { } - Diagnostic(ErrorCode.WRN_PatternBadSignature, "new C()").WithArguments("C", "collection", "C.GetEnumerator").WithLocation(3, 19), - // (3,19): error CS1579: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator' - // foreach (var x in new C()) { } - Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new C()").WithArguments("C", "GetEnumerator").WithLocation(3, 19)); + var memberAccess2 = GetSyntaxes(tree, "\"\".Property").Last(); + Assert.Equal("System.Int32 E.<>E__0.Property { get; set; }", model.GetSymbolInfo(memberAccess2).Symbol.ToTestDisplayString()); } [Fact] - public void ExtensionMemberLookup_PatternBased_ForEach_GetEnumerator_DynamicTypeProperty() + public void SwitchReceiver_Property_String() { var src = """ -using System.Collections; - -foreach (var x in new C()) { } - -class C { } +bool b = true; +(b switch { true => "", _ => "" }).Property = 42; +_ = (b switch { true => "", _ => "" }).Property; static class E { - extension(C c) + extension(string s) { - public dynamic GetEnumerator => throw null; + public int Property { get { System.Console.Write("get "); return 42; } set { System.Console.Write("set "); } } } } """; var comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics( - // (3,19): error CS1579: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator' - // foreach (var x in new C()) { } - Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new C()").WithArguments("C", "GetEnumerator").WithLocation(3, 19)); + CompileAndVerify(comp, expectedOutput: "set get").VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); - var loop = tree.GetRoot().DescendantNodes().OfType().Single(); - Assert.Null(model.GetForEachStatementInfo(loop).GetEnumeratorMethod); - - src = """ -foreach (var x in new C()) { } + var memberAccess1 = GetSyntaxes(tree, """(b switch { true => "", _ => "" }).Property""").First(); + Assert.Equal("System.Int32 E.<>E__0.Property { get; set; }", model.GetSymbolInfo(memberAccess1).Symbol.ToTestDisplayString()); -class C -{ - public dynamic GetEnumerator => throw null; -} -"""; - comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics( - // (1,19): warning CS0280: 'C' does not implement the 'collection' pattern. 'C.GetEnumerator' has the wrong signature. - // foreach (var x in new C()) { } - Diagnostic(ErrorCode.WRN_PatternBadSignature, "new C()").WithArguments("C", "collection", "C.GetEnumerator").WithLocation(1, 19), - // (1,19): error CS1579: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator' - // foreach (var x in new C()) { } - Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new C()").WithArguments("C", "GetEnumerator").WithLocation(1, 19)); + var memberAccess2 = GetSyntaxes(tree, """(b switch { true => "", _ => "" }).Property""").Last(); + Assert.Equal("System.Int32 E.<>E__0.Property { get; set; }", model.GetSymbolInfo(memberAccess2).Symbol.ToTestDisplayString()); } [Fact] - public void ExtensionMemberLookup_PatternBased_ForEach_GetEnumerator_Generic() + public void ConditionalReceiver_Property_String() { var src = """ -using System.Collections.Generic; - -foreach (var x in new C()) { System.Console.Write(x); } - -class C { } +bool b = true; +(b ? "" : null).Property = 42; +_ = (b ? "" : null).Property; static class E { - extension(T t) + extension(string s) { - public IEnumerator GetEnumerator() - { - yield return t; - } + public int Property { get { System.Console.Write("get "); return 42; } set { System.Console.Write("set "); } } } } """; var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "C").VerifyDiagnostics(); + CompileAndVerify(comp, expectedOutput: "set get").VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); - var loop = tree.GetRoot().DescendantNodes().OfType().Single(); - Assert.Equal("System.Collections.Generic.IEnumerator E.<>E__0.GetEnumerator()", - model.GetForEachStatementInfo(loop).GetEnumeratorMethod.ToTestDisplayString()); + var memberAccess1 = GetSyntaxes(tree, """(b ? "" : null).Property""").First(); + Assert.Equal("System.Int32 E.<>E__0.Property { get; set; }", model.GetSymbolInfo(memberAccess1).Symbol.ToTestDisplayString()); + + var memberAccess2 = GetSyntaxes(tree, """(b ? "" : null).Property""").Last(); + Assert.Equal("System.Int32 E.<>E__0.Property { get; set; }", model.GetSymbolInfo(memberAccess2).Symbol.ToTestDisplayString()); } [Fact] - public void ExtensionMemberLookup_PatternBased_AwaitForEach_GetAsyncEnumerator() + public void LiteralReceiver_Property_Integer_Get() { var src = """ -using System.Collections.Generic; - -await foreach (var x in new C()) { System.Console.Write(x); } - -class C { } +_ = 1.Property; static class E { - extension(T t) + extension(int i) { - public async IAsyncEnumerator GetAsyncEnumerator() - { - await System.Threading.Tasks.Task.Yield(); - yield return t; - } + public int Property { get { System.Console.Write("get"); return 42; } } } } """; - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); - CompileAndVerify(comp, expectedOutput: ExpectedOutput("C"), verify: Verification.FailsPEVerify).VerifyDiagnostics(); + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "get").VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); - var loop = tree.GetRoot().DescendantNodes().OfType().Single(); - Assert.Equal("System.Collections.Generic.IAsyncEnumerator E.<>E__0.GetAsyncEnumerator()", - model.GetForEachStatementInfo(loop).GetEnumeratorMethod.ToTestDisplayString()); + var memberAccess = GetSyntax(tree, "1.Property"); + Assert.Equal("System.Int32 E.<>E__0.Property { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); } [Fact] - public void ExtensionMemberLookup_PatternBased_Deconstruct_NoMethod() + public void LiteralReceiver_Property_Integer_Set() { var src = """ -var (x, y) = new C(); -System.Console.Write((x, y)); - -class C { } +1.Property = 1; static class E { - extension(C c) + extension(int i) { - public void Deconstruct(out int i, out int j) { i = 42; j = 43; } + public int Property { set => throw null; } } } """; var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "(42, 43)").VerifyDiagnostics(); + // Consider improving the error message + comp.VerifyEmitDiagnostics( + // (1,1): error CS0131: The left-hand side of an assignment must be a variable, property or indexer + // 1.Property = 1; + Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "1.Property").WithLocation(1, 1)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); - var deconstruction = tree.GetRoot().DescendantNodes().OfType().First(); - - Assert.Equal("void E.<>E__0.Deconstruct(out System.Int32 i, out System.Int32 j)", - model.GetDeconstructionInfo(deconstruction).Method.ToTestDisplayString()); + var memberAccess = GetSyntax(tree, "1.Property"); + Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); + Assert.Equal(["System.Int32 E.<>E__0.Property { set; }"], model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); + Assert.Equal(CandidateReason.NotAVariable, model.GetSymbolInfo(memberAccess).CandidateReason); } [Fact] - public void ExtensionMemberLookup_PatternBased_Deconstruct_Conversion_01() + public void LiteralReceiver_Property_Null() { var src = """ -var (x, y) = new C(); -System.Console.Write((x, y)); - -class C { } +null.Property = 1; +_ = null.Property; static class E { extension(object o) { - public void Deconstruct(out int i, out int j) { i = 42; j = 43; } + public int Property { get => throw null; set => throw null; } } } """; var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "(42, 43)").VerifyDiagnostics(); - } - - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78682")] - public void ExtensionMemberLookup_PatternBased_Deconstruct_Conversion_02() - { - // array to Span - var src = """ -var (x, y) = new int[] { 42 }; -System.Console.Write((x, y)); - -class C { } - -static class E -{ - extension(System.Span s) - { - public void Deconstruct(out int i, out int j) { i = 42; j = 43; } - } -} -"""; + comp.VerifyEmitDiagnostics( + // (1,1): error CS0023: Operator '.' cannot be applied to operand of type '' + // null.Property = 1; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "null.Property").WithArguments(".", "").WithLocation(1, 1), + // (2,5): error CS0023: Operator '.' cannot be applied to operand of type '' + // _ = null.Property; + Diagnostic(ErrorCode.ERR_BadUnaryOp, "null.Property").WithArguments(".", "").WithLocation(2, 5)); - // Tracked by https://github.com/dotnet/roslyn/issues/78682 : ref analysis fails with an implicit span conversion on receiver of a deconstruction - try - { - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); - CompileAndVerify(comp, expectedOutput: ExpectedOutput("(42, 43)"), verify: Verification.Skipped).VerifyDiagnostics(); - } - catch (InvalidOperationException) - { - return; - } + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var memberAccess1 = GetSyntaxes(tree, "null.Property").First(); + Assert.Null(model.GetSymbolInfo(memberAccess1).Symbol); + Assert.Equal([], model.GetSymbolInfo(memberAccess1).CandidateSymbols.ToTestDisplayStrings()); + Assert.Equal(CandidateReason.None, model.GetSymbolInfo(memberAccess1).CandidateReason); - Debug.Assert(false); + var memberAccess2 = GetSyntaxes(tree, "null.Property").Last(); + Assert.Null(model.GetSymbolInfo(memberAccess2).Symbol); + Assert.Equal([], model.GetSymbolInfo(memberAccess2).CandidateSymbols.ToTestDisplayStrings()); + Assert.Equal(CandidateReason.None, model.GetSymbolInfo(memberAccess2).CandidateReason); } - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78682")] - public void ExtensionMemberLookup_PatternBased_Deconstruct_Conversion_03() + [Fact] + public void LiteralReceiver_Property_Default() { - // We check conversion during initial binding var src = """ -var (x, y) = new int[] { 42 }; -System.Console.Write((x, y)); - -class C { } +default.Property = 1; +_ = default.Property; static class E { - extension(System.Span s) - { - public void Deconstruct(out int i, out int j) => throw null; - } -} - -namespace System -{ - public ref struct Span + extension(object o) { + public int Property { get => throw null; set => throw null; } } } """; -#if RELEASE - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( - // (1,1): error CS0656: Missing compiler required member 'Span.op_Implicit' - // var (x, y) = new int[] { 42 }; - Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "var (x, y) = new int[] { 42 }").WithArguments("System.Span", "op_Implicit").WithLocation(1, 1), - // (8,22): warning CS0436: The type 'Span' in '' conflicts with the imported type 'Span' in 'System.Runtime, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Using the type defined in ''. - // extension(System.Span s) - Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Span").WithArguments("", "System.Span", "System.Runtime, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Span").WithLocation(8, 22)); -#endif + // (1,1): error CS8716: There is no target type for the default literal. + // default.Property = 1; + Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(1, 1), + // (2,5): error CS8716: There is no target type for the default literal. + // _ = default.Property; + Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(2, 5)); -#if DEBUG - // Tracked by https://github.com/dotnet/roslyn/issues/78682 : ref analysis fails with an implicit span conversion on receiver of a deconstruction - try - { - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); - comp.VerifyEmitDiagnostics(); - } - catch (InvalidOperationException) - { - return; - } + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var memberAccess1 = GetSyntaxes(tree, "default.Property").First(); + Assert.Equal("System.Int32 E.<>E__0.Property { get; set; }", model.GetSymbolInfo(memberAccess1).Symbol.ToTestDisplayString()); + Assert.Equal([], model.GetSymbolInfo(memberAccess1).CandidateSymbols.ToTestDisplayStrings()); + Assert.Equal(CandidateReason.None, model.GetSymbolInfo(memberAccess1).CandidateReason); - Debug.Assert(false); -#endif + var memberAccess2 = GetSyntaxes(tree, "default.Property").Last(); + Assert.Equal("System.Int32 E.<>E__0.Property { get; set; }", model.GetSymbolInfo(memberAccess2).Symbol.ToTestDisplayString()); + Assert.Equal([], model.GetSymbolInfo(memberAccess2).CandidateSymbols.ToTestDisplayStrings()); + Assert.Equal(CandidateReason.None, model.GetSymbolInfo(memberAccess2).CandidateReason); } [Fact] - public void ExtensionMemberLookup_PatternBased_Deconstruct_Generic() + public void LiteralReceiver_Property_Tuple_Get() { var src = """ -var (x, y) = new C(); -System.Console.Write((x, y)); - -class C { } +_ = (1, 2).Property; static class E { - extension(T t) + extension((int, int) t) { - public void Deconstruct(out int i, out int j) { i = 42; j = 43; } + public int Property { get { System.Console.Write("get "); return 42; } } } } """; var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "(42, 43)").VerifyDiagnostics(); + CompileAndVerify(comp, expectedOutput: "get").VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); - var deconstruction = tree.GetRoot().DescendantNodes().OfType().First(); - - Assert.Equal("void E.<>E__0.Deconstruct(out System.Int32 i, out System.Int32 j)", - model.GetDeconstructionInfo(deconstruction).Method.ToTestDisplayString()); + var memberAccess = GetSyntax(tree, "(1, 2).Property"); + Assert.Equal("System.Int32 E.<>E__0.Property { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); } [Fact] - public void ExtensionMemberLookup_PatternBased_Deconstruct_FallbackToExtensionMethod() + public void LiteralReceiver_Property_Tuple_Set() { - // If the method from the extension type is not applicable, we fall back - // to a Deconstruct extension method var src = """ -var (x, y) = new C(); -System.Console.Write((x, y)); - -public class C { } +(1, 2).Property = 1; static class E { - extension(C c) + extension((int, int) t) { - public void Deconstruct(int inapplicable) => throw null; + public int Property { set { System.Console.Write($"set(value)"); }} } } - -public static class E2 -{ - public static void Deconstruct(this C c, out int i, out int j) { i = 42; j = 43; } -} """; var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "(42, 43)").VerifyDiagnostics(); + // Consider improving the error message + comp.VerifyEmitDiagnostics( + // (1,1): error CS0131: The left-hand side of an assignment must be a variable, property or indexer + // (1, 2).Property = 1; + Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "(1, 2).Property").WithLocation(1, 1)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); - var deconstruction = tree.GetRoot().DescendantNodes().OfType().First(); - - Assert.Equal("void E2.Deconstruct(this C c, out System.Int32 i, out System.Int32 j)", - model.GetDeconstructionInfo(deconstruction).Method.ToTestDisplayString()); + var memberAccess = GetSyntax(tree, "(1, 2).Property"); + Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); + Assert.Equal(["System.Int32 E.<>E__0.Property { set; }"], model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); + Assert.Equal(CandidateReason.NotAVariable, model.GetSymbolInfo(memberAccess).CandidateReason); } [Fact] - public void ExtensionMemberLookup_PatternBased_Deconstruct_DelegateTypeProperty() + public void LiteralReceiver_Property_Tuple_Default() { var src = """ -var (x1, y1) = new C1(); - -var (x2, y2) = new C2(); - -class C1 { } - -class C2 -{ - public D Deconstruct => (out int i, out int j) => { i = 42; j = 43; }; -} - -delegate void D(out int i, out int j); +(default, default).Property = 1; +_ = (default, default).Property; static class E { - extension(C1 c) + extension((object, object) t) { - public D Deconstruct => (out int i, out int j) => { i = 42; j = 43; }; + public int Property { get => throw null; set => throw null; } } } """; var comp = CreateCompilation(src); - comp.VerifyDiagnostics( - // (1,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. - // var (x1, y1) = new C1(); - Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(1, 6), - // (1,10): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y1'. - // var (x1, y1) = new C1(); - Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y1").WithArguments("y1").WithLocation(1, 10), - - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : It looks like the following error is not reported for instance scenario. Noise? - - // (1,16): error CS1061: 'C1' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C1' could be found (are you missing a using directive or an assembly reference?) - // var (x1, y1) = new C1(); - Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "new C1()").WithArguments("C1", "Deconstruct").WithLocation(1, 16), - - // (1,16): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C1', with 2 out parameters and a void return type. - // var (x1, y1) = new C1(); - Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C1()").WithArguments("C1", "2").WithLocation(1, 16), - // (3,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'. - // var (x2, y2) = new C2(); - Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(3, 6), - // (3,10): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. - // var (x2, y2) = new C2(); - Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(3, 10), - // (3,16): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C2', with 2 out parameters and a void return type. - // var (x2, y2) = new C2(); - Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C2()").WithArguments("C2", "2").WithLocation(3, 16) - ); + comp.VerifyEmitDiagnostics( + // (1,2): error CS8716: There is no target type for the default literal. + // (default, default).Property = 1; + Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(1, 2), + // (1,11): error CS8716: There is no target type for the default literal. + // (default, default).Property = 1; + Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(1, 11), + // (2,6): error CS8716: There is no target type for the default literal. + // _ = (default, default).Property; + Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(2, 6), + // (2,15): error CS8716: There is no target type for the default literal. + // _ = (default, default).Property; + Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(2, 15)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); - var deconstruction = tree.GetRoot().DescendantNodes().OfType().First(); + var memberAccess1 = GetSyntaxes(tree, "(default, default).Property").First(); + Assert.Null(model.GetSymbolInfo(memberAccess1).Symbol); + Assert.Equal([], model.GetSymbolInfo(memberAccess1).CandidateSymbols.ToTestDisplayStrings()); + Assert.Equal(CandidateReason.None, model.GetSymbolInfo(memberAccess1).CandidateReason); - Assert.Null(model.GetDeconstructionInfo(deconstruction).Method); + var memberAccess2 = GetSyntaxes(tree, "(default, default).Property").Last(); + Assert.Null(model.GetSymbolInfo(memberAccess2).Symbol); + Assert.Equal([], model.GetSymbolInfo(memberAccess2).CandidateSymbols.ToTestDisplayStrings()); + Assert.Equal(CandidateReason.None, model.GetSymbolInfo(memberAccess2).CandidateReason); } [Fact] - public void ExtensionMemberLookup_PatternBased_Deconstruct_DynamicProperty() + public void LiteralReceiver_Property_Tuple_Integer_ForLong() { var src = """ -var (x, y) = new C(); - -class C { } +(1, 1).Property = 1; +_ = (2, 2).Property; static class E { - extension(C c) + extension((long, long) t) { - public dynamic Deconstruct => throw null; + public int Property { get => throw null; set => throw null; } } } """; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( - // (1,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. - // var (x, y) = new C(); - Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(1, 6), - // (1,9): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. - // var (x, y) = new C(); - Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(1, 9), - // (1,14): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) - // var (x, y) = new C(); - Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "new C()").WithArguments("C", "Deconstruct").WithLocation(1, 14), - // (1,14): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 2 out parameters and a void return type. - // var (x, y) = new C(); - Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(1, 14) - ); + // (1,1): error CS9286: '(int, int)' does not contain a definition for 'Property' and no accessible extension member 'Property' for receiver of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) + // (1, 1).Property = 1; + Diagnostic(ErrorCode.ERR_ExtensionResolutionFailed, "(1, 1).Property").WithArguments("(int, int)", "Property").WithLocation(1, 1), + // (2,5): error CS9286: '(int, int)' does not contain a definition for 'Property' and no accessible extension member 'Property' for receiver of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) + // _ = (2, 2).Property; + Diagnostic(ErrorCode.ERR_ExtensionResolutionFailed, "(2, 2).Property").WithArguments("(int, int)", "Property").WithLocation(2, 5)); + // Tracked by https://github.com/dotnet/roslyn/issues/76130 : review the behavior of the semantic model APIs var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); - var deconstruction = tree.GetRoot().DescendantNodes().OfType().First(); - - Assert.Null(model.GetDeconstructionInfo(deconstruction).Method); - - src = """ -var (x, y) = new C(); + var memberAccess1 = GetSyntax(tree, "(1, 1).Property"); + Assert.Equal("System.Int32 E.<>E__0.Property { get; set; }", model.GetSymbolInfo(memberAccess1).Symbol.ToTestDisplayString()); + Assert.Equal([], model.GetSymbolInfo(memberAccess1).CandidateSymbols.ToTestDisplayStrings()); + Assert.Equal(CandidateReason.None, model.GetSymbolInfo(memberAccess1).CandidateReason); -class C -{ - public dynamic Deconstruct => throw null; -} -"""; - comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics( - // (1,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. - // var (x, y) = new C(); - Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(1, 6), - // (1,9): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. - // var (x, y) = new C(); - Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(1, 9), - // (1,14): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 2 out parameters and a void return type. - // var (x, y) = new C(); - Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(1, 14)); + var memberAccess2 = GetSyntax(tree, "(2, 2).Property"); + Assert.Equal("System.Int32 E.<>E__0.Property { get; set; }", model.GetSymbolInfo(memberAccess2).Symbol.ToTestDisplayString()); + Assert.Equal([], model.GetSymbolInfo(memberAccess2).CandidateSymbols.ToTestDisplayStrings()); + Assert.Equal(CandidateReason.None, model.GetSymbolInfo(memberAccess2).CandidateReason); } [Fact] - public void ExtensionMemberLookup_PatternBased_Deconstruct_NoApplicableMethod() + public void PreferMoreSpecific_Static_MethodAndProperty() { var src = """ -var (x, y) = new C(); -System.Console.Write((x, y)); +System.Console.Write(object.M); -class C +static class E1 { - public void Deconstruct() { } // not applicable + extension(object) + { + public static string M() => throw null; + } } -static class E +static class E2 { - extension(C c) + extension(object) { - public void Deconstruct(out int i, out int j) { i = 42; j = 43; } + public static string M => throw null; } } """; var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "(42, 43)").VerifyDiagnostics(); + comp.VerifyEmitDiagnostics( + // (1,22): error CS9286: 'object' does not contain a definition for 'M' and no accessible extension member 'M' for receiver of type 'object' could be found (are you missing a using directive or an assembly reference?) + // System.Console.Write(object.M); + Diagnostic(ErrorCode.ERR_ExtensionResolutionFailed, "object.M").WithArguments("object", "M").WithLocation(1, 22)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); - var deconstruction = tree.GetRoot().DescendantNodes().OfType().First(); - - Assert.Equal("void E.<>E__0.Deconstruct(out System.Int32 i, out System.Int32 j)", - model.GetDeconstructionInfo(deconstruction).Method.ToTestDisplayString()); + var memberAccess = GetSyntax(tree, "object.M"); + Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); + Assert.Equal(["System.String E1.<>E__0.M()", "System.String E2.<>E__0.M { get; }"], + model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); + Assert.Empty(model.GetMemberGroup(memberAccess)); // Tracked by https://github.com/dotnet/roslyn/issues/78957 : public API, consider handling BoundBadExpression better } [Fact] - public void ExtensionMemberLookup_PatternBased_PositionalPattern() + public void PreferMoreSpecific_Static_MethodAndProperty_Generic() { var src = """ -var c = new C(); -if (c is var (x, y)) - System.Console.Write((x, y)); - -class C { } +System.Console.Write(object.M); -static class E +static class E1 { - extension(T t) + extension(T) { - public void Deconstruct(out int i, out int j) { i = 42; j = 43; } + public static string M() => throw null; } } -"""; - var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "(42, 43)").VerifyDiagnostics(); - } - - [Fact] - public void ExtensionMemberLookup_PatternBased_DisposeAsync_NoMethod() - { - var src = """ -using System.Threading.Tasks; - -/**/ -await using var x1 = new C1(); -/**/ -await using var x2 = new C2(); - -class C1 { } -class C2 { } - -static class E +static class E2 { - extension(C1 c) + extension(T) { - public Task DisposeAsync() => throw null; + public static string M => throw null; } - - public static Task DisposeAsync(this C2 c) => throw null; } """; var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (1,22): error CS9286: 'object' does not contain a definition for 'M' and no accessible extension member 'M' for receiver of type 'object' could be found (are you missing a using directive or an assembly reference?) + // System.Console.Write(object.M); + Diagnostic(ErrorCode.ERR_ExtensionResolutionFailed, "object.M").WithArguments("object", "M").WithLocation(1, 22)); - var expectedDiagnostics = new[] { - // (4,1): error CS8410: 'C1': type used in an asynchronous using statement must implement 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. - // await using var x1 = new C1(); - Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "await using var x1 = new C1();").WithArguments("C1").WithLocation(4, 1), - // (7,1): error CS8410: 'C2': type used in an asynchronous using statement must implement 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. - // await using var x2 = new C2(); - Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "await using var x2 = new C2();").WithArguments("C2").WithLocation(7, 1) - }; - - comp.VerifyDiagnostics(expectedDiagnostics); - - string expectedOperationTree = """ -IUsingDeclarationOperation(IsAsynchronous: True) (OperationKind.UsingDeclaration, Type: null, IsInvalid) (Syntax: 'await using ... = new C1();') - DeclarationGroup: - IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'await using ... = new C1();') - IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var x1 = new C1()') - Declarators: - IVariableDeclaratorOperation (Symbol: C1 x1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x1 = new C1()') - Initializer: - IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new C1()') - IObjectCreationOperation (Constructor: C1..ctor()) (OperationKind.ObjectCreation, Type: C1, IsInvalid) (Syntax: 'new C1()') - Arguments(0) - Initializer: - null - Initializer: - null -"""; + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "object.M"); + Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); - VerifyOperationTreeAndDiagnosticsForTest(src, expectedOperationTree, expectedDiagnostics); + // Tracked by https://github.com/dotnet/roslyn/issues/78957 : public API, consider handling BoundBadExpression better + Assert.Equal(["System.String E1.<>E__0.M()", "System.String E2.<>E__0.M { get; }"], + model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); + Assert.Empty(model.GetMemberGroup(memberAccess)); } [Fact] - public void TestPatternBasedDisposal_ExtensionMethod() - { - string source = @" -public class C -{ - public static async System.Threading.Tasks.Task Main() + public void PreferMoreSpecific_Static_MethodAndProperty_Invocation() { - await using (var x = new C()) - { - } + var src = """ +System.Console.Write(object.M()); - return 1; - } -} -public static class Extensions +static class E1 { - extension (C c) + extension(object) { - public System.Threading.Tasks.ValueTask DisposeAsync() - => throw null; + public static string M() => "ran"; } } -"; - // extension methods do not contribute to pattern-based disposal - var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe); - comp.VerifyDiagnostics( - // 0.cs(6,22): error CS8410: 'C': type used in an asynchronous using statement must implement 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. - // await using (var x = new C()) - Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "var x = new C()").WithArguments("C").WithLocation(6, 22) - ); - } - - [Fact] - public void PatternBased_Dispose_Async_DelegateTypeProperty() - { - var src = """ -using System.Threading.Tasks; - -await using var x = new C(); -class C +static class E2 { - public System.Func DisposeAsync => async () => { System.Console.Write("ran2"); await Task.Yield(); }; + extension(object) + { + public static string M => throw null; // not invocable + } } """; var comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics( - // (3,1): error CS8410: 'C': type used in an asynchronous using statement must implement 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. - // await using var x = new C(); - Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "await using var x = new C();").WithArguments("C").WithLocation(3, 1) - ); + CompileAndVerify(comp, expectedOutput: "ran").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "object.M"); + Assert.Equal("System.String E1.<>E__0.M()", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); + Assert.Equal([], model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); + Assert.Equal(["System.String E1.<>E__0.M()", "System.String E2.<>E__0.M { get; }"], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); } [Fact] - public void ExtensionMemberLookup_PatternBased_Dispose_Async_DelegateTypeProperty() + public void GetCompatibleExtensions_TwoSubstitutions() { var src = """ -using System.Threading.Tasks; - -await using var x = new C(); +C.M(); +new C().M2(); -class C { } +interface I { } +class C : I, I { } static class E { - extension(C c) + extension(I) { - public System.Func DisposeAsync => async () => { await Task.Yield(); }; + public static void M() { } } + + public static void M2(this I i) { } } """; var comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics( - // (3,1): error CS8410: 'C': type used in an asynchronous using statement must implement 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. - // await using var x = new C(); - Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "await using var x = new C();").WithArguments("C").WithLocation(3, 1) - ); - } + comp.VerifyDiagnostics( + // (1,3): error CS1061: 'C' does not contain a definition for 'M' and no accessible extension method 'M' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) + // C.M(); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M").WithArguments("C", "M").WithLocation(1, 3), + // (2,9): error CS1061: 'C' does not contain a definition for 'M2' and no accessible extension method 'M2' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) + // new C().M2(); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M2").WithArguments("C", "M2").WithLocation(2, 9)); - [Fact] - public void ExtensionMemberLookup_PatternBased_Dispose_Async_NoApplicableMethod() - { - var src = """ -using System.Threading.Tasks; + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); -/**/ -await using var x = new C(); -/**/ + var memberAccess1 = GetSyntax(tree, "C.M"); + Assert.Null(model.GetSymbolInfo(memberAccess1).Symbol); + Assert.Equal([], model.GetSymbolInfo(memberAccess1).CandidateSymbols.ToTestDisplayStrings()); + Assert.Empty(model.GetMemberGroup(memberAccess1)); -class C -{ - public Task DisposeAsync(int notApplicable) => throw null; // not applicable -} + var memberAccess2 = GetSyntax(tree, "new C().M2"); + Assert.Null(model.GetSymbolInfo(memberAccess2).Symbol); + Assert.Equal([], model.GetSymbolInfo(memberAccess2).CandidateSymbols.ToTestDisplayStrings()); + Assert.Empty(model.GetMemberGroup(memberAccess2)); + } -static class E -{ - extension(C c) + [Theory, ClassData(typeof(ThreePermutationGenerator))] + public void PreferMoreSpecific_Static_MethodAndMoreSpecificInvocablePropertyAndMoreSpecificMethod(int first, int second, int third) { - public async Task DisposeAsync() - { - System.Console.Write("RAN"); - await Task.Yield(); - } - } -} + string[] segments = [ + """ + static class E1 + { + extension(object) + { + public static string M() => throw null; + } + } + """, + """ + static class E2 + { + extension(C) + { + public static System.Func M => null; + } + } + """, + """ + static class E3 + { + extension(C) + { + public static string M() => throw null; + } + } + """]; + + var src = $$""" +System.Console.Write(C.M()); + +class C { } + +{{segments[first]}} + +{{segments[second]}} + +{{segments[third]}} """; var comp = CreateCompilation(src); - comp.VerifyDiagnostics( - // (4,1): error CS8410: 'C': type used in an asynchronous using statement must implement 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. - // await using var x = new C(); - Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "await using var x = new C();").WithArguments("C").WithLocation(4, 1) - ); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : verify IOperation + comp.VerifyEmitDiagnostics( + // (1,22): error CS9286: 'C' does not contain a definition for 'M' and no accessible extension member 'M' for receiver of type 'C' could be found (are you missing a using directive or an assembly reference?) + // System.Console.Write(C.M()); + Diagnostic(ErrorCode.ERR_ExtensionResolutionFailed, "C.M").WithArguments("C", "M").WithLocation(1, 22)); } [Fact] - public void ExtensionMemberLookup_PatternBased_Dispose_RefStruct() + public void AmbiguousCallOnInterface() { var src = """ -using var x1 = new S1(); -using var x2 = new S2(); - -ref struct S1 { } +I2.M(); -ref struct S2 +interface I { + public static void M() { } } -static class E -{ - extension(S1 s) - { - public void Dispose() { } +interface I2 : I, I { } +"""; + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + // Tracked by https://github.com/dotnet/roslyn/issues/78830 : diagnostic quality, consider improving the symbols in this error message + comp.VerifyEmitDiagnostics( + // (1,4): error CS0121: The call is ambiguous between the following methods or properties: 'I.M()' and 'I.M()' + // I2.M(); + Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("I.M()", "I.M()").WithLocation(1, 4)); } - public static void Dispose(this S2 s) { } + [Fact] + public void AmbiguousCallOnInterface_Generic() + { + var src = """ +I2.M(); + +interface I +{ + public static void M() { } } + +interface I2 : I, I { } """; - var comp = CreateCompilation(src); - comp.VerifyDiagnostics( - // (1,1): error CS1674: 'S1': type used in a using statement must implement 'System.IDisposable'. - // using var x1 = new S1(); - Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var x1 = new S1();").WithArguments("S1").WithLocation(1, 1), - // (2,1): error CS1674: 'S2': type used in a using statement must implement 'System.IDisposable'. - // using var x2 = new S2(); - Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var x2 = new S2();").WithArguments("S2").WithLocation(2, 1) - ); + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics( + // (1,4): error CS0121: The call is ambiguous between the following methods or properties: 'I.M()' and 'I.M()' + // I2.M(); + Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("I.M()", "I.M()").WithLocation(1, 4)); } [Fact] - public void ExtensionMemberLookup_PatternBased_Dispose_RefStruct_DelegateTypeProperty() + public void OmittedTypeArguments() { var src = """ -using var x1 = new S1(); - -ref struct S1 { } +object.P; +object.P<>; static class E { - extension(S1 s) + extension(object) { - public System.Action Dispose => throw null; + public static int P => 42; } } """; - var comp = CreateCompilation(src); - comp.VerifyDiagnostics( - // (1,1): error CS1674: 'S1': type used in a using statement must implement 'System.IDisposable'. - // using var x1 = new S1(); - Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var x1 = new S1();").WithArguments("S1").WithLocation(1, 1)); - - src = """ -using var x1 = new S1(); - -ref struct S1 -{ - public System.Action Dispose => throw null; -} -"""; - comp = CreateCompilation(src); - comp.VerifyDiagnostics( - // (1,1): error CS1674: 'S1': type used in a using statement must implement 'System.IDisposable'. - // using var x1 = new S1(); - Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var x1 = new S1();").WithArguments("S1").WithLocation(1, 1)); + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics( + // (1,1): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement + // object.P; + Diagnostic(ErrorCode.ERR_IllegalStatement, "object.P").WithLocation(1, 1), + // (1,8): error CS0117: 'object' does not contain a definition for 'P' + // object.P; + Diagnostic(ErrorCode.ERR_NoSuchMember, "P").WithArguments("object", "P").WithLocation(1, 8), + // (2,1): error CS8389: Omitting the type argument is not allowed in the current context + // object.P<>; + Diagnostic(ErrorCode.ERR_OmittedTypeArgument, "object.P<>").WithLocation(2, 1), + // (2,1): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement + // object.P<>; + Diagnostic(ErrorCode.ERR_IllegalStatement, "object.P<>").WithLocation(2, 1), + // (2,8): error CS0117: 'object' does not contain a definition for 'P' + // object.P<>; + Diagnostic(ErrorCode.ERR_NoSuchMember, "P<>").WithArguments("object", "P").WithLocation(2, 8)); } [Fact] - public void ExtensionMemberLookup_PatternBased_Fixed_01() + public void ExtensionMemberLookup_PatternBased_ForEach_NoMethod() { - var text = """ -unsafe class C + var src = """ +foreach (var x in new C()) { - public static void Main() - { - fixed (int* p = new Fixable()) - { - System.Console.WriteLine(p[1]); - } - } + System.Console.Write(x); + break; } -class Fixable { } +class C { } +class D { } static class E { - extension(Fixable f) + extension(C c) { - public ref int GetPinnableReference() { System.Console.Write("pin "); return ref (new int[] { 1, 2, 3 })[0]; } + public D GetEnumerator() => new D(); + } + extension(D d) + { + public bool MoveNext() => true; + public int Current => 42; } } """; - var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe); - CompileAndVerify(comp, expectedOutput: "pin 2", verify: Verification.Skipped).VerifyDiagnostics(); + var comp = CreateCompilation(src); + comp.VerifyDiagnostics( + // (1,19): error CS0117: 'D' does not contain a definition for 'Current' + // foreach (var x in new C()) + Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("D", "Current").WithLocation(1, 19), + // (1,19): error CS0202: foreach requires that the return type 'D' of 'E.extension(C).GetEnumerator()' must have a suitable public 'MoveNext' method and public 'Current' property + // foreach (var x in new C()) + Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new C()").WithArguments("D", "E.extension(C).GetEnumerator()").WithLocation(1, 19) + ); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var loop = tree.GetRoot().DescendantNodes().OfType().Single(); + Assert.Null(model.GetForEachStatementInfo(loop).GetEnumeratorMethod); + Assert.Null(model.GetForEachStatementInfo(loop).MoveNextMethod); + Assert.Null(model.GetForEachStatementInfo(loop).CurrentProperty); } [Fact] - public void ExtensionMemberLookup_PatternBased_Fixed_Conversion_01() + public void ExtensionMemberLookup_PatternBased_ForEach_NoApplicableMethod() { - var text = """ -unsafe class C + var src = """ +foreach (var x in new C()) { - public static void Main() - { - fixed (int* p = new Fixable()) - { - System.Console.WriteLine(p[1]); - } - } + System.Console.Write(x); + break; } -class Fixable { } +class C +{ + public void GetEnumerator(int notApplicable) { } // not applicable +} +class D { } static class E { - extension(object o) + extension(C c) { - public ref int GetPinnableReference() { System.Console.Write("pin "); return ref (new int[] { 1, 2, 3 })[0]; } + public D GetEnumerator() => new D(); + } + extension(D d) + { + public bool MoveNext() => true; + public int Current => 42; } } """; - var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe); - CompileAndVerify(comp, expectedOutput: "pin 2", verify: Verification.Skipped).VerifyDiagnostics(); + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (1,19): error CS0117: 'D' does not contain a definition for 'Current' + // foreach (var x in new C()) + Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("D", "Current").WithLocation(1, 19), + // (1,19): error CS0202: foreach requires that the return type 'D' of 'E.extension(C).GetEnumerator()' must have a suitable public 'MoveNext' method and public 'Current' property + // foreach (var x in new C()) + Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new C()").WithArguments("D", "E.extension(C).GetEnumerator()").WithLocation(1, 19) + ); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var loop = tree.GetRoot().DescendantNodes().OfType().Single(); + Assert.Null(model.GetForEachStatementInfo(loop).GetEnumeratorMethod); + Assert.Null(model.GetForEachStatementInfo(loop).MoveNextMethod); + Assert.Null(model.GetForEachStatementInfo(loop).CurrentProperty); } [Fact] - public void ExtensionMemberLookup_PatternBased_Fixed_Conversion_02() - { - var text = """ -unsafe class C -{ - public static void Main() + public void ExtensionMemberLookup_PatternBased_ForEach_WrongArity() { - fixed (int* p = (0, "")) - { - System.Console.WriteLine(p[1]); - } - } -} + var src = """ +using System.Collections; + +foreach (var x in new C()) { } + +class C { } static class E { - extension((object, object) t) + extension(C c) { - public ref int GetPinnableReference() { System.Console.Write("pin "); return ref (new int[] { 1, 2, 3 })[0]; } + public IEnumerator GetEnumerator() => throw null; } } """; - var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe, targetFramework: TargetFramework.Net90); - CompileAndVerify(comp, expectedOutput: ExpectedOutput("pin 2"), verify: Verification.Skipped).VerifyDiagnostics(); + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (3,19): error CS0411: The type arguments for method 'E.extension(C).GetEnumerator()' cannot be inferred from the usage. Try specifying the type arguments explicitly. + // foreach (var x in new C()) { } + Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "new C()").WithArguments("E.extension(C).GetEnumerator()").WithLocation(3, 19), + // (3,19): error CS1579: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator' + // foreach (var x in new C()) { } + Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new C()").WithArguments("C", "GetEnumerator").WithLocation(3, 19)); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var loop = tree.GetRoot().DescendantNodes().OfType().Single(); + Assert.Null(model.GetForEachStatementInfo(loop).GetEnumeratorMethod); } [Fact] - public void ExtensionMemberLookup_PatternBased_Fixed_Conversion_03() - { - // We check conversion during initial binding - var text = """ -unsafe class C -{ - public static void M() + public void ExtensionMemberLookup_PatternBased_ForEach_NonInvocable() { - System.ReadOnlySpan x = default; - fixed (long* p = x) - { - } - } -} + var src = """ +using System.Collections; -static class E -{ - extension(System.ReadOnlySpan s) - { - public ref long GetPinnableReference() => throw null; - } -} +foreach (var x in new C()) { } -namespace System +class C { } + +static class E { - public ref struct ReadOnlySpan + extension(C c) { + public IEnumerator GetEnumerator => throw null; } } """; - var comp = CreateCompilation(text, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90); - comp.VerifyDiagnostics( - // (5,16): warning CS0436: The type 'ReadOnlySpan' in '' conflicts with the imported type 'ReadOnlySpan' in 'System.Runtime, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Using the type defined in ''. - // System.ReadOnlySpan x = default; - Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "ReadOnlySpan").WithArguments("", "System.ReadOnlySpan", "System.Runtime, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.ReadOnlySpan").WithLocation(5, 16), - // (6,26): error CS0656: Missing compiler required member 'ReadOnlySpan.CastUp' - // fixed (long* p = x) - Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x").WithArguments("System.ReadOnlySpan", "CastUp").WithLocation(6, 26), - // (14,22): warning CS0436: The type 'ReadOnlySpan' in '' conflicts with the imported type 'ReadOnlySpan' in 'System.Runtime, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Using the type defined in ''. - // extension(System.ReadOnlySpan s) - Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "ReadOnlySpan").WithArguments("", "System.ReadOnlySpan", "System.Runtime, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.ReadOnlySpan").WithLocation(14, 22)); + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (3,19): error CS1579: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator' + // foreach (var x in new C()) { } + Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new C()").WithArguments("C", "GetEnumerator").WithLocation(3, 19)); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var loop = tree.GetRoot().DescendantNodes().OfType().Single(); + Assert.Null(model.GetForEachStatementInfo(loop).GetEnumeratorMethod); } [Fact] - public void ExtensionMemberLookup_PatternBased_Fixed_03_DelegateTypeProperty() + public void ExtensionMemberLookup_PatternBased_ForEach_DelegateTypeProperty() { - var text = @" -unsafe class C + var src = """ +using System.Collections; + +foreach (var x in new C()) { } + +class C { } + +static class E { - public static void Main() + extension(C c) { - fixed (int* p = new Fixable1()) - { - System.Console.WriteLine(p[1]); - } - - fixed (int* p = new Fixable2()) - { - System.Console.WriteLine(p[1]); - } + public System.Func GetEnumerator => throw null; } } +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (3,19): error CS1579: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator' + // foreach (var x in new C()) { } + Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new C()").WithArguments("C", "GetEnumerator").WithLocation(3, 19)); -class Fixable1 { } + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var loop = tree.GetRoot().DescendantNodes().OfType().Single(); + Assert.Null(model.GetForEachStatementInfo(loop).GetEnumeratorMethod); -class Fixable2 -{ - public MyDelegate GetPinnableReference => throw null; -} + src = """ +using System.Collections; -delegate ref int MyDelegate(); +foreach (var x in new C()) { } -static class E +class C { - extension(Fixable1 f) - { - public MyDelegate GetPinnableReference => throw null; - } + public System.Func GetEnumerator => throw null; } -"; - var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe); +"""; + comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( - // (6,25): error CS8385: The given expression cannot be used in a fixed statement - // fixed (int* p = new Fixable1()) - Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable1()").WithLocation(6, 25), - // (11,25): error CS8385: The given expression cannot be used in a fixed statement - // fixed (int* p = new Fixable2()) - Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable2()").WithLocation(11, 25) - ); + // (3,19): warning CS0280: 'C' does not implement the 'collection' pattern. 'C.GetEnumerator' has the wrong signature. + // foreach (var x in new C()) { } + Diagnostic(ErrorCode.WRN_PatternBadSignature, "new C()").WithArguments("C", "collection", "C.GetEnumerator").WithLocation(3, 19), + // (3,19): error CS1579: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator' + // foreach (var x in new C()) { } + Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new C()").WithArguments("C", "GetEnumerator").WithLocation(3, 19)); } [Fact] - public void ExtensionMemberLookup_PatternBased_Fixed_04_DynamicTypeProperty() - { - var text = @" -unsafe class C -{ - public static void Main() + public void ExtensionMemberLookup_PatternBased_ForEach_GetEnumerator_DynamicTypeProperty() { - fixed (int* p = new Fixable1()) - { - } - } -} + var src = """ +using System.Collections; -class Fixable1 { } +foreach (var x in new C()) { } -delegate ref int MyDelegate(); +class C { } static class E { - extension(Fixable1 f) + extension(C c) { - public dynamic GetPinnableReference => throw null; + public dynamic GetEnumerator => throw null; } } -"; - var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe); +"""; + var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( - // (6,25): error CS8385: The given expression cannot be used in a fixed statement - // fixed (int* p = new Fixable1()) - Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable1()").WithLocation(6, 25)); + // (3,19): error CS1579: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator' + // foreach (var x in new C()) { } + Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new C()").WithArguments("C", "GetEnumerator").WithLocation(3, 19)); - text = @" -unsafe class C -{ - public static void Main() - { - fixed (int* p = new Fixable1()) - { - } - } -} + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var loop = tree.GetRoot().DescendantNodes().OfType().Single(); + Assert.Null(model.GetForEachStatementInfo(loop).GetEnumeratorMethod); -class Fixable1 + src = """ +foreach (var x in new C()) { } + +class C { - public dynamic GetPinnableReference => throw null; + public dynamic GetEnumerator => throw null; } - -delegate ref int MyDelegate(); -"; - comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe); +"""; + comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( - // (6,25): error CS8385: The given expression cannot be used in a fixed statement - // fixed (int* p = new Fixable1()) - Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable1()").WithLocation(6, 25)); + // (1,19): warning CS0280: 'C' does not implement the 'collection' pattern. 'C.GetEnumerator' has the wrong signature. + // foreach (var x in new C()) { } + Diagnostic(ErrorCode.WRN_PatternBadSignature, "new C()").WithArguments("C", "collection", "C.GetEnumerator").WithLocation(1, 19), + // (1,19): error CS1579: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator' + // foreach (var x in new C()) { } + Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new C()").WithArguments("C", "GetEnumerator").WithLocation(1, 19)); } [Fact] - public void ExtensionMemberLookup_PatternBased_Fixed_05() + public void ExtensionMemberLookup_PatternBased_ForEach_GetEnumerator_Generic() { var src = """ -unsafe class C +using System.Collections.Generic; + +foreach (var x in new C()) { System.Console.Write(x); } + +class C { } + +static class E { - public static void Main() + extension(T t) { - /**/ - fixed (int* p = new Fixable()) + public IEnumerator GetEnumerator() { - System.Console.WriteLine(p[1]); + yield return t; } - /**/ } } +"""; + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "C").VerifyDiagnostics(); -class Fixable -{ - public ref int GetPinnableReference(int notApplicable) => throw null; // not applicable -} + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var loop = tree.GetRoot().DescendantNodes().OfType().Single(); + Assert.Equal("System.Collections.Generic.IEnumerator E.<>E__0.GetEnumerator()", + model.GetForEachStatementInfo(loop).GetEnumeratorMethod.ToTestDisplayString()); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_AwaitForEach_GetAsyncEnumerator() + { + var src = """ +using System.Collections.Generic; + +await foreach (var x in new C()) { System.Console.Write(x); } + +class C { } static class E { - extension(Fixable f) + extension(T t) { - public ref int GetPinnableReference() { return ref (new int[] { 1, 2, 3 })[0]; } + public async IAsyncEnumerator GetAsyncEnumerator() + { + await System.Threading.Tasks.Task.Yield(); + yield return t; + } } } """; + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + CompileAndVerify(comp, expectedOutput: ExpectedOutput("C"), verify: Verification.FailsPEVerify).VerifyDiagnostics(); - var comp = CreateCompilation(src, options: TestOptions.UnsafeReleaseExe); - CompileAndVerify(comp, expectedOutput: "2", verify: Verification.Skipped).VerifyDiagnostics(); - - string expectedOperationTree = """ -IFixedOperation (OperationKind.None, Type: null) (Syntax: 'fixed (int* ... }') - Locals: Local_1: System.Int32* p - Declaration: - IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int* p = new Fixable()') - IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int* p = new Fixable()') - Declarators: - IVariableDeclaratorOperation (Symbol: System.Int32* p) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p = new Fixable()') - Initializer: - IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new Fixable()') - IOperation: (OperationKind.None, Type: System.Int32*, IsImplicit) (Syntax: 'new Fixable()') - Children(1): - IObjectCreationOperation (Constructor: Fixable..ctor()) (OperationKind.ObjectCreation, Type: Fixable) (Syntax: 'new Fixable()') - Arguments(0) - Initializer: - null - Initializer: - null - Body: - IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') - IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... Line(p[1]);') - Expression: - IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... eLine(p[1])') - Instance Receiver: - null - Arguments(1): - IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'p[1]') - IOperation: (OperationKind.None, Type: System.Int32) (Syntax: 'p[1]') - Children(2): - ILocalReferenceOperation: p (OperationKind.LocalReference, Type: System.Int32*) (Syntax: 'p') - ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') - InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) - OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) -"""; - - VerifyOperationTreeAndDiagnosticsForTest(src, expectedOperationTree, [], targetFramework: TargetFramework.Net70, compilationOptions: TestOptions.UnsafeReleaseExe); + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var loop = tree.GetRoot().DescendantNodes().OfType().Single(); + Assert.Equal("System.Collections.Generic.IAsyncEnumerator E.<>E__0.GetAsyncEnumerator()", + model.GetForEachStatementInfo(loop).GetEnumeratorMethod.ToTestDisplayString()); } [Fact] - public void ExtensionMemberLookup_PatternBased_Fixed_06() - { - var text = @" -unsafe class C -{ - public static void Main() + public void ExtensionMemberLookup_PatternBased_Deconstruct_NoMethod() { - fixed (int* p = new Fixable()) - { - } - } -} + var src = """ +var (x, y) = new C(); +System.Console.Write((x, y)); -class Fixable { } +class C { } static class E { - extension(Fixable f) + extension(C c) { - public static ref int GetPinnableReference() => throw null; + public void Deconstruct(out int i, out int j) { i = 42; j = 43; } } } -"; +"""; + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "(42, 43)").VerifyDiagnostics(); - var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe); - comp.VerifyEmitDiagnostics( - // (6,25): error CS0176: Member 'E.extension(Fixable).GetPinnableReference()' cannot be accessed with an instance reference; qualify it with a type name instead - // fixed (int* p = new Fixable()) - Diagnostic(ErrorCode.ERR_ObjectProhibited, "new Fixable()").WithArguments("E.extension(Fixable).GetPinnableReference()").WithLocation(6, 25), - // (6,25): error CS8385: The given expression cannot be used in a fixed statement - // fixed (int* p = new Fixable()) - Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable()").WithLocation(6, 25)); + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var deconstruction = tree.GetRoot().DescendantNodes().OfType().First(); + + Assert.Equal("void E.<>E__0.Deconstruct(out System.Int32 i, out System.Int32 j)", + model.GetDeconstructionInfo(deconstruction).Method.ToTestDisplayString()); } [Fact] - public void ExtensionMemberLookup_PatternBased_Await_ExtensionIsCompleted() + public void ExtensionMemberLookup_PatternBased_Deconstruct_Conversion_01() { - var text = @" -using System; -using System.Runtime.CompilerServices; + var src = """ +var (x, y) = new C(); +System.Console.Write((x, y)); -int i = await new C(); -System.Console.Write(i); +class C { } -class C +static class E { - public D GetAwaiter() => new D(); + extension(object o) + { + public void Deconstruct(out int i, out int j) { i = 42; j = 43; } + } } +"""; + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "(42, 43)").VerifyDiagnostics(); + } -class D : INotifyCompletion -{ - public int GetResult() => 42; - public void OnCompleted(Action continuation) => throw null; -} + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78682")] + public void ExtensionMemberLookup_PatternBased_Deconstruct_Conversion_02() + { + // array to Span + var src = """ +var (x, y) = new int[] { 42 }; +System.Console.Write((x, y)); + +class C { } static class E { - extension(D d) + extension(System.Span s) { - public bool IsCompleted => true; + public void Deconstruct(out int i, out int j) { i = 42; j = 43; } } } -"; +"""; - var comp = CreateCompilation(text); - comp.VerifyEmitDiagnostics( - // (5,9): error CS0117: 'D' does not contain a definition for 'IsCompleted' - // int i = await new C(); - Diagnostic(ErrorCode.ERR_NoSuchMember, "await new C()").WithArguments("D", "IsCompleted").WithLocation(5, 9) - ); + // Tracked by https://github.com/dotnet/roslyn/issues/78682 : ref analysis fails with an implicit span conversion on receiver of a deconstruction + try + { + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + CompileAndVerify(comp, expectedOutput: ExpectedOutput("(42, 43)"), verify: Verification.Skipped).VerifyDiagnostics(); + } + catch (InvalidOperationException) + { + return; + } + + Debug.Assert(false); } - [Fact] - public void ExtensionMemberLookup_PatternBased_Await_ExtensionGetAwaiter() + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78682")] + public void ExtensionMemberLookup_PatternBased_Deconstruct_Conversion_03() { - var text = @" -using System; -using System.Runtime.CompilerServices; + // We check conversion during initial binding + var src = """ +var (x, y) = new int[] { 42 }; +System.Console.Write((x, y)); -/**/ -int i = await new C(); -/**/ -System.Console.Write(i); +class C { } -class C +static class E { + extension(System.Span s) + { + public void Deconstruct(out int i, out int j) => throw null; + } } -class D : INotifyCompletion +namespace System { - public int GetResult() => 42; - public void OnCompleted(Action continuation) => throw null; - public bool IsCompleted => true; + public ref struct Span + { + } } +"""; +#if RELEASE + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (1,1): error CS0656: Missing compiler required member 'Span.op_Implicit' + // var (x, y) = new int[] { 42 }; + Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "var (x, y) = new int[] { 42 }").WithArguments("System.Span", "op_Implicit").WithLocation(1, 1), + // (8,22): warning CS0436: The type 'Span' in '' conflicts with the imported type 'Span' in 'System.Runtime, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Using the type defined in ''. + // extension(System.Span s) + Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Span").WithArguments("", "System.Span", "System.Runtime, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Span").WithLocation(8, 22)); +#endif + +#if DEBUG + // Tracked by https://github.com/dotnet/roslyn/issues/78682 : ref analysis fails with an implicit span conversion on receiver of a deconstruction + try + { + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics(); + } + catch (InvalidOperationException) + { + return; + } + + Debug.Assert(false); +#endif + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_Deconstruct_Generic() + { + var src = """ +var (x, y) = new C(); +System.Console.Write((x, y)); + +class C { } static class E { - extension(C c) + extension(T t) { - public D GetAwaiter() => new D(); + public void Deconstruct(out int i, out int j) { i = 42; j = 43; } } } -"; - - var comp = CreateCompilation(text); - CompileAndVerify(comp, expectedOutput: "42").VerifyDiagnostics(); - - string expectedOperationTree = """ -IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i = await new C();') -IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = await new C()') - Declarators: - IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = await new C()') - Initializer: - IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= await new C()') - IAwaitOperation (OperationKind.Await, Type: System.Int32) (Syntax: 'await new C()') - Expression: - IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') - Arguments(0) - Initializer: - null - Initializer: - null """; + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "(42, 43)").VerifyDiagnostics(); - VerifyOperationTreeAndDiagnosticsForTest(text, expectedOperationTree, [], targetFramework: TargetFramework.Net70); + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var deconstruction = tree.GetRoot().DescendantNodes().OfType().First(); + + Assert.Equal("void E.<>E__0.Deconstruct(out System.Int32 i, out System.Int32 j)", + model.GetDeconstructionInfo(deconstruction).Method.ToTestDisplayString()); } [Fact] - public void ExtensionMemberLookup_PatternBased_Await_ExtensionGetAwaiter_Conversion() + public void ExtensionMemberLookup_PatternBased_Deconstruct_FallbackToExtensionMethod() { - var text = @" -using System; -using System.Runtime.CompilerServices; + // If the method from the extension type is not applicable, we fall back + // to a Deconstruct extension method + var src = """ +var (x, y) = new C(); +System.Console.Write((x, y)); -int i = await new C(); -System.Console.Write(i); +public class C { } -class C +static class E { + extension(C c) + { + public void Deconstruct(int inapplicable) => throw null; + } } -class D : INotifyCompletion +public static class E2 { - public int GetResult() => 42; - public void OnCompleted(Action continuation) => throw null; - public bool IsCompleted => true; + public static void Deconstruct(this C c, out int i, out int j) { i = 42; j = 43; } } +"""; + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "(42, 43)").VerifyDiagnostics(); -static class E -{ - extension(object o) - { - public D GetAwaiter() => new D(); - } -} -"; + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var deconstruction = tree.GetRoot().DescendantNodes().OfType().First(); - var comp = CreateCompilation(text); - CompileAndVerify(comp, expectedOutput: "42").VerifyDiagnostics(); + Assert.Equal("void E2.Deconstruct(this C c, out System.Int32 i, out System.Int32 j)", + model.GetDeconstructionInfo(deconstruction).Method.ToTestDisplayString()); } [Fact] - public void ExtensionMemberLookup_PatternBased_Await_ExtensionGetAwaiter_DelegateTypeProperty() + public void ExtensionMemberLookup_PatternBased_Deconstruct_DelegateTypeProperty() { - var text = @" -using System; -using System.Runtime.CompilerServices; + var src = """ +var (x1, y1) = new C1(); -int i = await new C(); -System.Console.Write(i); +var (x2, y2) = new C2(); -class C -{ -} +class C1 { } -class D : INotifyCompletion +class C2 { - public int GetResult() => 42; - public void OnCompleted(Action continuation) => throw null; - public bool IsCompleted => true; + public D Deconstruct => (out int i, out int j) => { i = 42; j = 43; }; } +delegate void D(out int i, out int j); + static class E { - extension(C c) + extension(C1 c) { - public System.Func GetAwaiter => () => new D(); + public D Deconstruct => (out int i, out int j) => { i = 42; j = 43; }; } } -"; - - var comp = CreateCompilation(text); - comp.VerifyEmitDiagnostics( - // (5,9): error CS1061: 'C' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) - // int i = await new C(); - Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "await new C()").WithArguments("C", "GetAwaiter").WithLocation(5, 9)); +"""; + var comp = CreateCompilation(src); + comp.VerifyDiagnostics( + // (1,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. + // var (x1, y1) = new C1(); + Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(1, 6), + // (1,10): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y1'. + // var (x1, y1) = new C1(); + Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y1").WithArguments("y1").WithLocation(1, 10), - text = @" -using System; -using System.Runtime.CompilerServices; + // Tracked by https://github.com/dotnet/roslyn/issues/76130 : It looks like the following error is not reported for instance scenario. Noise? -int i = await new C(); -System.Console.Write(i); + // (1,16): error CS1061: 'C1' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C1' could be found (are you missing a using directive or an assembly reference?) + // var (x1, y1) = new C1(); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "new C1()").WithArguments("C1", "Deconstruct").WithLocation(1, 16), -class C -{ - public System.Func GetAwaiter => () => new D(); -} + // (1,16): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C1', with 2 out parameters and a void return type. + // var (x1, y1) = new C1(); + Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C1()").WithArguments("C1", "2").WithLocation(1, 16), + // (3,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'. + // var (x2, y2) = new C2(); + Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(3, 6), + // (3,10): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. + // var (x2, y2) = new C2(); + Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(3, 10), + // (3,16): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C2', with 2 out parameters and a void return type. + // var (x2, y2) = new C2(); + Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C2()").WithArguments("C2", "2").WithLocation(3, 16) + ); -class D : INotifyCompletion -{ - public int GetResult() => 42; - public void OnCompleted(Action continuation) => throw null; - public bool IsCompleted => true; -} -"; + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var deconstruction = tree.GetRoot().DescendantNodes().OfType().First(); - comp = CreateCompilation(text); - comp.VerifyEmitDiagnostics( - // (5,9): error CS0118: 'GetAwaiter' is a property but is used like a method - // int i = await new C(); - Diagnostic(ErrorCode.ERR_BadSKknown, "await new C()").WithArguments("GetAwaiter", "property", "method").WithLocation(5, 9)); + Assert.Null(model.GetDeconstructionInfo(deconstruction).Method); } [Fact] - public void ExtensionMemberLookup_PatternBased_Await_ExtensionGetAwaiter_DynamicTypeProperty() + public void ExtensionMemberLookup_PatternBased_Deconstruct_DynamicProperty() { - var text = @" -using System; -using System.Runtime.CompilerServices; - -int i = await new C(); -System.Console.Write(i); - -class C -{ -} + var src = """ +var (x, y) = new C(); -class D : INotifyCompletion -{ - public int GetResult() => 42; - public void OnCompleted(Action continuation) => throw null; - public bool IsCompleted => true; -} +class C { } static class E { extension(C c) { - public dynamic GetAwaiter => throw null; + public dynamic Deconstruct => throw null; } } -"; - - var comp = CreateCompilation(text); +"""; + var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( - // (5,9): error CS1061: 'C' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) - // int i = await new C(); - Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "await new C()").WithArguments("C", "GetAwaiter").WithLocation(5, 9)); + // (1,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. + // var (x, y) = new C(); + Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(1, 6), + // (1,9): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. + // var (x, y) = new C(); + Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(1, 9), + // (1,14): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) + // var (x, y) = new C(); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "new C()").WithArguments("C", "Deconstruct").WithLocation(1, 14), + // (1,14): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 2 out parameters and a void return type. + // var (x, y) = new C(); + Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(1, 14) + ); - text = @" -using System; -using System.Runtime.CompilerServices; + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var deconstruction = tree.GetRoot().DescendantNodes().OfType().First(); -int i = await new C(); -System.Console.Write(i); + Assert.Null(model.GetDeconstructionInfo(deconstruction).Method); -class C -{ - public dynamic GetAwaiter => throw null; -} + src = """ +var (x, y) = new C(); -class D : INotifyCompletion +class C { - public int GetResult() => 42; - public void OnCompleted(Action continuation) => throw null; - public bool IsCompleted => true; + public dynamic Deconstruct => throw null; } -"; - - comp = CreateCompilation(text); +"""; + comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( - // (5,9): error CS0118: 'GetAwaiter' is a property but is used like a method - // int i = await new C(); - Diagnostic(ErrorCode.ERR_BadSKknown, "await new C()").WithArguments("GetAwaiter", "property", "method").WithLocation(5, 9)); + // (1,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. + // var (x, y) = new C(); + Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(1, 6), + // (1,9): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. + // var (x, y) = new C(); + Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(1, 9), + // (1,14): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 2 out parameters and a void return type. + // var (x, y) = new C(); + Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(1, 14)); } [Fact] - public void ExtensionMemberLookup_PatternBased_Await_ExtensionGetResult() + public void ExtensionMemberLookup_PatternBased_Deconstruct_NoApplicableMethod() { - var text = @" -using System; -using System.Runtime.CompilerServices; - -int i = await new C(); -System.Console.Write(i); + var src = """ +var (x, y) = new C(); +System.Console.Write((x, y)); class C { - public D GetAwaiter() => new D(); -} - -class D : INotifyCompletion -{ - public void OnCompleted(Action continuation) => throw null; - public bool IsCompleted => true; + public void Deconstruct() { } // not applicable } static class E { - extension(D d) + extension(C c) { - public int GetResult() => 42; + public void Deconstruct(out int i, out int j) { i = 42; j = 43; } } } -"; +"""; + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "(42, 43)").VerifyDiagnostics(); - var comp = CreateCompilation(text); - - // The error is consistent with classic extension methods - comp.VerifyEmitDiagnostics( - // (5,9): error CS0117: 'D' does not contain a definition for 'GetResult' - // int i = await new C(); - Diagnostic(ErrorCode.ERR_NoSuchMember, "await new C()").WithArguments("D", "GetResult").WithLocation(5, 9) - ); - - text = """ -using System; -using System.Runtime.CompilerServices; + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var deconstruction = tree.GetRoot().DescendantNodes().OfType().First(); -int i = await new C(); -System.Console.Write(i); + Assert.Equal("void E.<>E__0.Deconstruct(out System.Int32 i, out System.Int32 j)", + model.GetDeconstructionInfo(deconstruction).Method.ToTestDisplayString()); + } -class C + [Fact] + public void ExtensionMemberLookup_PatternBased_PositionalPattern() + { + var libSrc = """ +public static class E { - public D GetAwaiter() => new D(); + extension(T t) + { + public void Deconstruct(out int i, out int j) { i = 42; j = 43; } + } } +"""; + var libRef = CreateCompilation(libSrc).EmitToImageReference(); -class D : INotifyCompletion -{ - public void OnCompleted(Action continuation) => throw null; - public bool IsCompleted => true; -} + var src = """ +var c = new C(); +if (c is var (x, y)) + System.Console.Write((x, y)); + +class C { } -static class E -{ - public static int GetResult(this D d) => 42; -} """; + var comp = CreateCompilation(src, references: [libRef]); + CompileAndVerify(comp, expectedOutput: "(42, 43)").VerifyDiagnostics(); - comp = CreateCompilation(text); - comp.VerifyEmitDiagnostics( - // (4,9): error CS0117: 'D' does not contain a definition for 'GetResult' - // int i = await new C(); - Diagnostic(ErrorCode.ERR_NoSuchMember, "await new C()").WithArguments("D", "GetResult").WithLocation(4, 9) - ); + comp = CreateCompilation(src, references: [libRef], parseOptions: TestOptions.Regular13); + CompileAndVerify(comp, expectedOutput: "(42, 43)").VerifyDiagnostics(); + + comp = CreateCompilation(src, references: [libRef], parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp, expectedOutput: "(42, 43)").VerifyDiagnostics(); } [Fact] - public void ExtensionMemberLookup_PatternBased_Await_ExtensionGetResult_DelegateTypeProperty() + public void ExtensionMemberLookup_PatternBased_DisposeAsync_NoMethod() { - var text = @" -using System; -using System.Runtime.CompilerServices; + var src = """ +using System.Threading.Tasks; -int i = await new C(); -System.Console.Write(i); +/**/ +await using var x1 = new C1(); +/**/ -class C -{ - public D GetAwaiter() => new D(); -} +await using var x2 = new C2(); -class D : INotifyCompletion -{ - public void OnCompleted(Action continuation) => throw null; - public bool IsCompleted => true; -} +class C1 { } +class C2 { } static class E { - extension(D d) + extension(C1 c) { - public System.Func GetResult => () => 42; + public Task DisposeAsync() => throw null; } -} -"; - var comp = CreateCompilation(text); - comp.VerifyEmitDiagnostics( - // (5,9): error CS0117: 'D' does not contain a definition for 'GetResult' - // int i = await new C(); - Diagnostic(ErrorCode.ERR_NoSuchMember, "await new C()").WithArguments("D", "GetResult").WithLocation(5, 9)); - text = """ -using System; -using System.Runtime.CompilerServices; + public static Task DisposeAsync(this C2 c) => throw null; +} +"""; + var comp = CreateCompilation(src); -int i = await new C(); -System.Console.Write(i); + var expectedDiagnostics = new[] { + // (4,1): error CS8410: 'C1': type used in an asynchronous using statement must implement 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. + // await using var x1 = new C1(); + Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "await using var x1 = new C1();").WithArguments("C1").WithLocation(4, 1), + // (7,1): error CS8410: 'C2': type used in an asynchronous using statement must implement 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. + // await using var x2 = new C2(); + Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "await using var x2 = new C2();").WithArguments("C2").WithLocation(7, 1) + }; -class C -{ - public D GetAwaiter() => new D(); -} + comp.VerifyDiagnostics(expectedDiagnostics); -class D : INotifyCompletion -{ - public void OnCompleted(Action continuation) => throw null; - public bool IsCompleted => true; - public System.Func GetResult => () => 42; -} + string expectedOperationTree = """ +IUsingDeclarationOperation(IsAsynchronous: True) (OperationKind.UsingDeclaration, Type: null, IsInvalid) (Syntax: 'await using ... = new C1();') + DeclarationGroup: + IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'await using ... = new C1();') + IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var x1 = new C1()') + Declarators: + IVariableDeclaratorOperation (Symbol: C1 x1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x1 = new C1()') + Initializer: + IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new C1()') + IObjectCreationOperation (Constructor: C1..ctor()) (OperationKind.ObjectCreation, Type: C1, IsInvalid) (Syntax: 'new C1()') + Arguments(0) + Initializer: + null + Initializer: + null """; - comp = CreateCompilation(text); - comp.VerifyEmitDiagnostics( - // (4,9): error CS0118: 'GetResult' is a property but is used like a method - // int i = await new C(); - Diagnostic(ErrorCode.ERR_BadSKknown, "await new C()").WithArguments("GetResult", "property", "method").WithLocation(4, 9)); + VerifyOperationTreeAndDiagnosticsForTest(src, expectedOperationTree, expectedDiagnostics); } [Fact] - public void ExtensionMemberLookup_PatternBased_Await_ExtensionGetResult_DynamicTypeProperty() + public void TestPatternBasedDisposal_ExtensionMethod() { - var text = @" -using System; -using System.Runtime.CompilerServices; - -int i = await new C(); -System.Console.Write(i); - -class C + string source = @" +public class C { - public D GetAwaiter() => new D(); -} + public static async System.Threading.Tasks.Task Main() + { + await using (var x = new C()) + { + } -class D : INotifyCompletion -{ - public void OnCompleted(Action continuation) => throw null; - public bool IsCompleted => true; + return 1; + } } - -static class E +public static class Extensions { - extension(D d) + extension (C c) { - public dynamic GetResult => throw null; + public System.Threading.Tasks.ValueTask DisposeAsync() + => throw null; } } "; + // extension methods do not contribute to pattern-based disposal + var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe); + comp.VerifyDiagnostics( + // 0.cs(6,22): error CS8410: 'C': type used in an asynchronous using statement must implement 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. + // await using (var x = new C()) + Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "var x = new C()").WithArguments("C").WithLocation(6, 22) + ); + } - var comp = CreateCompilation(text); - comp.VerifyEmitDiagnostics( - // (5,9): error CS0117: 'D' does not contain a definition for 'GetResult' - // int i = await new C(); - Diagnostic(ErrorCode.ERR_NoSuchMember, "await new C()").WithArguments("D", "GetResult").WithLocation(5, 9)); - - text = """ -using System; -using System.Runtime.CompilerServices; + [Fact] + public void PatternBased_Dispose_Async_DelegateTypeProperty() + { + var src = """ +using System.Threading.Tasks; -int i = await new C(); -System.Console.Write(i); +await using var x = new C(); class C { - public D GetAwaiter() => new D(); -} - -class D : INotifyCompletion -{ - public void OnCompleted(Action continuation) => throw null; - public bool IsCompleted => true; - public dynamic GetResult => throw null; + public System.Func DisposeAsync => async () => { System.Console.Write("ran2"); await Task.Yield(); }; } """; - - comp = CreateCompilation(text); + var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( - // (4,9): error CS0118: 'GetResult' is a property but is used like a method - // int i = await new C(); - Diagnostic(ErrorCode.ERR_BadSKknown, "await new C()").WithArguments("GetResult", "property", "method").WithLocation(4, 9)); + // (3,1): error CS8410: 'C': type used in an asynchronous using statement must implement 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. + // await using var x = new C(); + Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "await using var x = new C();").WithArguments("C").WithLocation(3, 1) + ); } [Fact] - public void ExtensionMemberLookup_PatternBased_IndexIndexer_Length() + public void ExtensionMemberLookup_PatternBased_Dispose_Async_DelegateTypeProperty() { var src = """ -var c = new C(); +using System.Threading.Tasks; -/**/ -_ = c[^1]; -/**/ +await using var x = new C(); -class C -{ - public int this[int i] => throw null; -} +class C { } static class E { extension(C c) { - public int Length => throw null; + public System.Func DisposeAsync => async () => { await Task.Yield(); }; } } """; - DiagnosticDescription[] expectedDiagnostics = [ - // (4,7): error CS1503: Argument 1: cannot convert from 'System.Index' to 'int' - // _ = c[^1]; - Diagnostic(ErrorCode.ERR_BadArgType, "^1").WithArguments("1", "System.Index", "int").WithLocation(4, 7)]; - - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - comp.VerifyEmitDiagnostics(expectedDiagnostics); - - string expectedOperationTree = """ -ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: '_ = c[^1]') -Left: - IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: '_') -Right: - IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'c[^1]') - Children(2): - ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') - IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index, IsInvalid) (Syntax: '^1') - Operand: - ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') -"""; - - VerifyOperationTreeAndDiagnosticsForTest(src, expectedOperationTree, expectedDiagnostics, targetFramework: TargetFramework.Net70); - - src = """ -var c = new C(); -_ = c[^1]; - -class C -{ - public int this[int i] => throw null; - public int Length => throw null; -} -"""; - comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - comp.VerifyEmitDiagnostics(); + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (3,1): error CS8410: 'C': type used in an asynchronous using statement must implement 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. + // await using var x = new C(); + Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "await using var x = new C();").WithArguments("C").WithLocation(3, 1) + ); } [Fact] - public void ExtensionMemberLookup_PatternBased_IndexIndexer_Count() + public void ExtensionMemberLookup_PatternBased_Dispose_Async_NoApplicableMethod() { var src = """ -var c = new C(); -_ = c[^1]; +using System.Threading.Tasks; + +/**/ +await using var x = new C(); +/**/ class C { - public int this[int i] => throw null; + public Task DisposeAsync(int notApplicable) => throw null; // not applicable } static class E { extension(C c) { - public int Count => throw null; + public async Task DisposeAsync() + { + System.Console.Write("RAN"); + await Task.Yield(); + } } } """; + var comp = CreateCompilation(src); + comp.VerifyDiagnostics( + // (4,1): error CS8410: 'C': type used in an asynchronous using statement must implement 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. + // await using var x = new C(); + Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "await using var x = new C();").WithArguments("C").WithLocation(4, 1) + ); - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - comp.VerifyEmitDiagnostics( - // (2,7): error CS1503: Argument 1: cannot convert from 'System.Index' to 'int' - // _ = c[^1]; - Diagnostic(ErrorCode.ERR_BadArgType, "^1").WithArguments("1", "System.Index", "int").WithLocation(2, 7)); - - src = """ -var c = new C(); -_ = c[^1]; - -class C -{ - public int this[int i] => throw null; - public int Count => throw null; -} -"""; - comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - comp.VerifyEmitDiagnostics(); + // Tracked by https://github.com/dotnet/roslyn/issues/76130 : verify IOperation } [Fact] - public void ExtensionMemberLookup_PatternBased_IndexIndexer_IntIndexer() + public void ExtensionMemberLookup_PatternBased_Dispose_RefStruct() { var src = """ -var c = new C(); -_ = c[^1]; +using var x1 = new S1(); +using var x2 = new S2(); -class C +ref struct S1 { } + +ref struct S2 { - public int Length => throw null; } static class E { - extension(C c) + extension(S1 s) { - public int this[int i] => throw null; + public void Dispose() { } } + + public static void Dispose(this S2 s) { } } """; - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - comp.VerifyEmitDiagnostics( - // (2,5): error CS0021: Cannot apply indexing with [] to an expression of type 'C' - // _ = c[^1]; - Diagnostic(ErrorCode.ERR_BadIndexLHS, "c[^1]").WithArguments("C").WithLocation(2, 5), - // (13,20): error CS9282: This member is not allowed in an extension block - // public int this[int i] => throw null; - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(13, 20)); + var comp = CreateCompilation(src); + comp.VerifyDiagnostics( + // (1,1): error CS1674: 'S1': type used in a using statement must implement 'System.IDisposable'. + // using var x1 = new S1(); + Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var x1 = new S1();").WithArguments("S1").WithLocation(1, 1), + // (2,1): error CS1674: 'S2': type used in a using statement must implement 'System.IDisposable'. + // using var x2 = new S2(); + Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var x2 = new S2();").WithArguments("S2").WithLocation(2, 1) + ); } [Fact] - public void ExtensionMemberLookup_PatternBased_IndexIndexer_RegularIndexer() + public void ExtensionMemberLookup_PatternBased_Dispose_RefStruct_DelegateTypeProperty() { var src = """ -var c = new C(); -_ = c[^1]; +using var x1 = new S1(); -class C -{ - public int Length => throw null; -} +ref struct S1 { } static class E { - extension(C c) + extension(S1 s) { - public int this[System.Index i] => throw null; + public System.Action Dispose => throw null; } } """; - // Tracked by https://github.com/dotnet/roslyn/issues/78829 : revisit when implementing extension indexers - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - comp.VerifyEmitDiagnostics( - // (2,5): error CS0021: Cannot apply indexing with [] to an expression of type 'C' - // _ = c[^1]; - Diagnostic(ErrorCode.ERR_BadIndexLHS, "c[^1]").WithArguments("C").WithLocation(2, 5), - // (13,20): error CS9282: This member is not allowed in an extension block - // public int this[System.Index i] => throw null; - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(13, 20)); + var comp = CreateCompilation(src); + comp.VerifyDiagnostics( + // (1,1): error CS1674: 'S1': type used in a using statement must implement 'System.IDisposable'. + // using var x1 = new S1(); + Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var x1 = new S1();").WithArguments("S1").WithLocation(1, 1)); src = """ -var c = new C(); -_ = c[^1]; +using var x1 = new S1(); -class C +ref struct S1 { - public int Length => throw null; - public int this[System.Index i] => throw null; + public System.Action Dispose => throw null; } """; - comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - comp.VerifyEmitDiagnostics(); + comp = CreateCompilation(src); + comp.VerifyDiagnostics( + // (1,1): error CS1674: 'S1': type used in a using statement must implement 'System.IDisposable'. + // using var x1 = new S1(); + Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var x1 = new S1();").WithArguments("S1").WithLocation(1, 1)); } [Fact] - public void ExtensionMemberLookup_PatternBased_RangeIndexer_Slice() + public void ExtensionMemberLookup_PatternBased_Fixed_01() { - var src = """ -var c = new C(); - -/**/ -_ = c[1..^1]; -/**/ - -class C + var text = """ +unsafe class C { - public int Length => throw null; + public static void Main() + { + fixed (int* p = new Fixable()) + { + System.Console.WriteLine(p[1]); + } + } } +class Fixable { } + static class E { - extension(C c) + extension(Fixable f) { - public int Slice(int i, int j) => throw null; + public ref int GetPinnableReference() { System.Console.Write("pin "); return ref (new int[] { 1, 2, 3 })[0]; } } } """; + var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe); + CompileAndVerify(comp, expectedOutput: "pin 2", verify: Verification.Skipped).VerifyDiagnostics(); + } - DiagnosticDescription[] expectedDiagnostics = [ - // (4,5): error CS0021: Cannot apply indexing with [] to an expression of type 'C' - // _ = c[1..^1]; - Diagnostic(ErrorCode.ERR_BadIndexLHS, "c[1..^1]").WithArguments("C").WithLocation(4, 5)]; - - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - comp.VerifyEmitDiagnostics(expectedDiagnostics); - - string expectedOperationTree = """ -ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '_ = c[1..^1]') -Left: - IDiscardOperation (Symbol: ? _) (OperationKind.Discard, Type: ?) (Syntax: '_') -Right: - IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'c[1..^1]') - Children(2): - IRangeOperation (OperationKind.Range, Type: System.Range, IsInvalid) (Syntax: '1..^1') - LeftOperand: - IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Index System.Index.op_Implicit(System.Int32 value)) (OperationKind.Conversion, Type: System.Index, IsInvalid, IsImplicit) (Syntax: '1') - Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Index System.Index.op_Implicit(System.Int32 value)) - Operand: - ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') - RightOperand: - IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index, IsInvalid) (Syntax: '^1') - Operand: - ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') - ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c') -"""; - - VerifyOperationTreeAndDiagnosticsForTest(src, expectedOperationTree, expectedDiagnostics, targetFramework: TargetFramework.Net70); + [Fact] + public void ExtensionMemberLookup_PatternBased_Fixed_Conversion_01() + { + var text = """ +unsafe class C +{ + public static void Main() + { + fixed (int* p = new Fixable()) + { + System.Console.WriteLine(p[1]); + } + } +} - src = """ -var c = new C(); -_ = c[1..^1]; +class Fixable { } -class C +static class E { - public int Length => throw null; - public int Slice(int i, int j) => throw null; + extension(object o) + { + public ref int GetPinnableReference() { System.Console.Write("pin "); return ref (new int[] { 1, 2, 3 })[0]; } + } } """; - - comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - comp.VerifyEmitDiagnostics(); + var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe); + CompileAndVerify(comp, expectedOutput: "pin 2", verify: Verification.Skipped).VerifyDiagnostics(); } [Fact] - public void ExtensionMemberLookup_PatternBased_RangeIndexer_Length() + public void ExtensionMemberLookup_PatternBased_Fixed_Conversion_02() { - var src = """ -var c = new C(); -_ = c[1..^1]; - -class C + var text = """ +unsafe class C { - public int Slice(int i, int j) => throw null; + public static void Main() + { + fixed (int* p = (0, "")) + { + System.Console.WriteLine(p[1]); + } + } } static class E { - extension(C c) + extension((object, object) t) { - public int Length => throw null; + public ref int GetPinnableReference() { System.Console.Write("pin "); return ref (new int[] { 1, 2, 3 })[0]; } } } """; - - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - comp.VerifyEmitDiagnostics( - // (2,5): error CS0021: Cannot apply indexing with [] to an expression of type 'C' - // _ = c[1..^1]; - Diagnostic(ErrorCode.ERR_BadIndexLHS, "c[1..^1]").WithArguments("C").WithLocation(2, 5)); + var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe, targetFramework: TargetFramework.Net90); + CompileAndVerify(comp, expectedOutput: ExpectedOutput("pin 2"), verify: Verification.Skipped).VerifyDiagnostics(); } [Fact] - public void ExtensionMemberLookup_PatternBased_RangeIndexer_RegularIndexer() + public void ExtensionMemberLookup_PatternBased_Fixed_Conversion_03() { - var src = """ -var c = new C(); -_ = c[1..^1]; - -class C + // We check conversion during initial binding + var text = """ +unsafe class C { - public int Length => throw null; + public static void M() + { + System.ReadOnlySpan x = default; + fixed (long* p = x) + { + } + } } static class E { - extension(C c) + extension(System.ReadOnlySpan s) { - public int this[System.Range r] => throw null; + public ref long GetPinnableReference() => throw null; } } -"""; - - // Tracked by https://github.com/dotnet/roslyn/issues/78829 : revisit when implementing extension indexers - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - comp.VerifyEmitDiagnostics( - // (2,5): error CS0021: Cannot apply indexing with [] to an expression of type 'C' - // _ = c[1..^1]; - Diagnostic(ErrorCode.ERR_BadIndexLHS, "c[1..^1]").WithArguments("C").WithLocation(2, 5), - // (13,20): error CS9282: This member is not allowed in an extension block - // public int this[System.Range r] => throw null; - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(13, 20)); - - src = """ -var c = new C(); -_ = c[1..^1]; -class C +namespace System { - public int Length => throw null; - public int this[System.Range r] => throw null; + public ref struct ReadOnlySpan + { + } } """; - - comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - comp.VerifyEmitDiagnostics(); + var comp = CreateCompilation(text, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90); + comp.VerifyDiagnostics( + // (5,16): warning CS0436: The type 'ReadOnlySpan' in '' conflicts with the imported type 'ReadOnlySpan' in 'System.Runtime, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Using the type defined in ''. + // System.ReadOnlySpan x = default; + Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "ReadOnlySpan").WithArguments("", "System.ReadOnlySpan", "System.Runtime, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.ReadOnlySpan").WithLocation(5, 16), + // (6,26): error CS0656: Missing compiler required member 'ReadOnlySpan.CastUp' + // fixed (long* p = x) + Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x").WithArguments("System.ReadOnlySpan", "CastUp").WithLocation(6, 26), + // (14,22): warning CS0436: The type 'ReadOnlySpan' in '' conflicts with the imported type 'ReadOnlySpan' in 'System.Runtime, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Using the type defined in ''. + // extension(System.ReadOnlySpan s) + Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "ReadOnlySpan").WithArguments("", "System.ReadOnlySpan", "System.Runtime, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.ReadOnlySpan").WithLocation(14, 22)); } [Fact] - public void ExtensionMemberLookup_PatternBased_ListPattern_Length() + public void ExtensionMemberLookup_PatternBased_Fixed_03_DelegateTypeProperty() { - var src = """ -_ = new C() is [1]; - -class C -{ - public int this[int i] => throw null; -} - -static class E + var text = @" +unsafe class C { - extension(C c) + public static void Main() { - public int Length => throw null; + fixed (int* p = new Fixable1()) + { + System.Console.WriteLine(p[1]); + } + + fixed (int* p = new Fixable2()) + { + System.Console.WriteLine(p[1]); + } } } -"""; - - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - comp.VerifyEmitDiagnostics( - // (1,16): error CS8985: List patterns may not be used for a value of type 'C'. No suitable 'Length' or 'Count' property was found. - // _ = new C() is [1]; - Diagnostic(ErrorCode.ERR_ListPatternRequiresLength, "[1]").WithArguments("C").WithLocation(1, 16), - // (1,16): error CS1503: Argument 1: cannot convert from 'System.Index' to 'int' - // _ = new C() is [1]; - Diagnostic(ErrorCode.ERR_BadArgType, "[1]").WithArguments("1", "System.Index", "int").WithLocation(1, 16)); - src = """ -_ = new C() is [1]; +class Fixable1 { } -class C +class Fixable2 { - public int this[int i] => throw null; - public int Length => throw null; + public MyDelegate GetPinnableReference => throw null; } -"""; - comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - comp.VerifyEmitDiagnostics(); - } - - [Fact] - public void ExtensionMemberLookup_PatternBased_ListPattern_IntIndexer() - { - var src = """ -_ = new C() is [1]; -class C -{ - public int Length => throw null; -} +delegate ref int MyDelegate(); static class E { - extension(C c) + extension(Fixable1 f) { - public int this[int i] => throw null; + public MyDelegate GetPinnableReference => throw null; } } -"""; - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); +"; + var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe); comp.VerifyEmitDiagnostics( - // (1,16): error CS0021: Cannot apply indexing with [] to an expression of type 'C' - // _ = new C() is [1]; - Diagnostic(ErrorCode.ERR_BadIndexLHS, "[1]").WithArguments("C").WithLocation(1, 16), - // (12,20): error CS9282: This member is not allowed in an extension block - // public int this[int i] => throw null; - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(12, 20)); + // (6,25): error CS8385: The given expression cannot be used in a fixed statement + // fixed (int* p = new Fixable1()) + Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable1()").WithLocation(6, 25), + // (11,25): error CS8385: The given expression cannot be used in a fixed statement + // fixed (int* p = new Fixable2()) + Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable2()").WithLocation(11, 25) + ); } [Fact] - public void ExtensionMemberLookup_PatternBased_ListPattern_RegularIndexer() + public void ExtensionMemberLookup_PatternBased_Fixed_04_DynamicTypeProperty() { - var src = """ -_ = new C() is [1]; - -class C + var text = @" +unsafe class C { - public int Length => throw null; + public static void Main() + { + fixed (int* p = new Fixable1()) + { + } + } } +class Fixable1 { } + +delegate ref int MyDelegate(); + static class E { - extension(C c) + extension(Fixable1 f) { - public int this[System.Index i] => throw null; + public dynamic GetPinnableReference => throw null; } } -"""; - - // Tracked by https://github.com/dotnet/roslyn/issues/78829 : revisit when implementing extension indexers - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); +"; + var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe); comp.VerifyEmitDiagnostics( - // (1,16): error CS0021: Cannot apply indexing with [] to an expression of type 'C' - // _ = new C() is [1]; - Diagnostic(ErrorCode.ERR_BadIndexLHS, "[1]").WithArguments("C").WithLocation(1, 16), - // (12,20): error CS9282: This member is not allowed in an extension block - // public int this[System.Index i] => throw null; - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(12, 20)); + // (6,25): error CS8385: The given expression cannot be used in a fixed statement + // fixed (int* p = new Fixable1()) + Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable1()").WithLocation(6, 25)); - src = """ -_ = new C() is [1]; + text = @" +unsafe class C +{ + public static void Main() + { + fixed (int* p = new Fixable1()) + { + } + } +} -class C +class Fixable1 { - public int Length => throw null; - public int this[System.Index i] => throw null; + public dynamic GetPinnableReference => throw null; } -"""; - comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - comp.VerifyEmitDiagnostics(); +delegate ref int MyDelegate(); +"; + comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe); + comp.VerifyEmitDiagnostics( + // (6,25): error CS8385: The given expression cannot be used in a fixed statement + // fixed (int* p = new Fixable1()) + Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable1()").WithLocation(6, 25)); } [Fact] - public void ExtensionMemberLookup_PatternBased_SpreadPattern_Length() + public void ExtensionMemberLookup_PatternBased_Fixed_05() { var src = """ -_ = new C() is [_, .. var x]; +unsafe class C +{ + public static void Main() + { + /**/ + fixed (int* p = new Fixable()) + { + System.Console.WriteLine(p[1]); + } + /**/ + } +} -class C +class Fixable { - public int this[System.Index i] => throw null; - public int Slice(int i, int j) => throw null; + public ref int GetPinnableReference(int notApplicable) => throw null; // not applicable } static class E { - extension(C c) + extension(Fixable f) { - public int Length => throw null; + public ref int GetPinnableReference() { return ref (new int[] { 1, 2, 3 })[0]; } } } """; - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - comp.VerifyEmitDiagnostics( - // (1,16): error CS8985: List patterns may not be used for a value of type 'C'. No suitable 'Length' or 'Count' property was found. - // _ = new C() is [_, .. var x]; - Diagnostic(ErrorCode.ERR_ListPatternRequiresLength, "[_, .. var x]").WithArguments("C").WithLocation(1, 16), - // (1,20): error CS1503: Argument 1: cannot convert from 'System.Range' to 'System.Index' - // _ = new C() is [_, .. var x]; - Diagnostic(ErrorCode.ERR_BadArgType, ".. var x").WithArguments("1", "System.Range", "System.Index").WithLocation(1, 20)); - - src = """ -_ = new C() is [_, .. var x]; + var comp = CreateCompilation(src, options: TestOptions.UnsafeReleaseExe); + CompileAndVerify(comp, expectedOutput: "2", verify: Verification.Skipped).VerifyDiagnostics(); -class C -{ - public int this[System.Index i] => throw null; - public int Slice(int i, int j) => throw null; - public int Length => throw null; -} + string expectedOperationTree = """ +IFixedOperation (OperationKind.None, Type: null) (Syntax: 'fixed (int* ... }') + Locals: Local_1: System.Int32* p + Declaration: + IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int* p = new Fixable()') + IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int* p = new Fixable()') + Declarators: + IVariableDeclaratorOperation (Symbol: System.Int32* p) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p = new Fixable()') + Initializer: + IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new Fixable()') + IOperation: (OperationKind.None, Type: System.Int32*, IsImplicit) (Syntax: 'new Fixable()') + Children(1): + IObjectCreationOperation (Constructor: Fixable..ctor()) (OperationKind.ObjectCreation, Type: Fixable) (Syntax: 'new Fixable()') + Arguments(0) + Initializer: + null + Initializer: + null + Body: + IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') + IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... Line(p[1]);') + Expression: + IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... eLine(p[1])') + Instance Receiver: + null + Arguments(1): + IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'p[1]') + IOperation: (OperationKind.None, Type: System.Int32) (Syntax: 'p[1]') + Children(2): + ILocalReferenceOperation: p (OperationKind.LocalReference, Type: System.Int32*) (Syntax: 'p') + ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') + InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) """; - comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - comp.VerifyEmitDiagnostics(); + + VerifyOperationTreeAndDiagnosticsForTest(src, expectedOperationTree, [], targetFramework: TargetFramework.Net70, compilationOptions: TestOptions.UnsafeReleaseExe); } [Fact] - public void ExtensionMemberLookup_PatternBased_SpreadPattern_Slice() + public void ExtensionMemberLookup_PatternBased_Fixed_06() { - var src = """ -_ = new C() is [_, .. var x]; - -class C + var text = @" +unsafe class C { - public int this[System.Index i] => throw null; - public int Length => throw null; + public static void Main() + { + fixed (int* p = new Fixable()) + { + } + } } +class Fixable { } + static class E { - extension(C c) + extension(Fixable f) { - public int Slice(int i, int j) => throw null; + public static ref int GetPinnableReference() => throw null; } } -"""; +"; - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe); comp.VerifyEmitDiagnostics( - // (1,20): error CS1503: Argument 1: cannot convert from 'System.Range' to 'System.Index' - // _ = new C() is [_, .. var x]; - Diagnostic(ErrorCode.ERR_BadArgType, ".. var x").WithArguments("1", "System.Range", "System.Index").WithLocation(1, 20)); + // (6,25): error CS0176: Member 'E.extension(Fixable).GetPinnableReference()' cannot be accessed with an instance reference; qualify it with a type name instead + // fixed (int* p = new Fixable()) + Diagnostic(ErrorCode.ERR_ObjectProhibited, "new Fixable()").WithArguments("E.extension(Fixable).GetPinnableReference()").WithLocation(6, 25), + // (6,25): error CS8385: The given expression cannot be used in a fixed statement + // fixed (int* p = new Fixable()) + Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable()").WithLocation(6, 25)); } [Fact] - public void ExtensionMemberLookup_PatternBased_SpreadPattern_RegularIndexer() + public void ExtensionMemberLookup_PatternBased_Await_ExtensionIsCompleted() { - var src = """ -_ = new C() is [_, .. var x]; + var text = @" +using System; +using System.Runtime.CompilerServices; + +int i = await new C(); +System.Console.Write(i); class C { - public int this[System.Index i] => throw null; - public int Length => throw null; + public D GetAwaiter() => new D(); +} + +class D : INotifyCompletion +{ + public int GetResult() => 42; + public void OnCompleted(Action continuation) => throw null; } static class E { - extension(C c) + extension(D d) { - public int this[System.Range r] => throw null; + public bool IsCompleted => true; } } -"""; +"; - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + var comp = CreateCompilation(text); comp.VerifyEmitDiagnostics( - // (1,20): error CS1503: Argument 1: cannot convert from 'System.Range' to 'System.Index' - // _ = new C() is [_, .. var x]; - Diagnostic(ErrorCode.ERR_BadArgType, ".. var x").WithArguments("1", "System.Range", "System.Index").WithLocation(1, 20), - // (13,20): error CS9282: This member is not allowed in an extension block - // public int this[System.Range r] => throw null; - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(13, 20)); + // (5,9): error CS0117: 'D' does not contain a definition for 'IsCompleted' + // int i = await new C(); + Diagnostic(ErrorCode.ERR_NoSuchMember, "await new C()").WithArguments("D", "IsCompleted").WithLocation(5, 9) + ); + } - src = """ -_ = new C() is [_, .. var x]; + [Fact] + public void ExtensionMemberLookup_PatternBased_Await_ExtensionGetAwaiter() + { + var text = @" +using System; +using System.Runtime.CompilerServices; + +/**/ +int i = await new C(); +/**/ +System.Console.Write(i); class C { - public int this[System.Index i] => throw null; - public int this[System.Range r] => throw null; - public int Length => throw null; } -"""; - comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - comp.VerifyEmitDiagnostics(); - } - - [Fact] - public void ExtensionMemberLookup_Patterns() - { - var src = """ -var c = new C(); -_ = c is { Property: 42 }; -class C { } +class D : INotifyCompletion +{ + public int GetResult() => 42; + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; +} static class E { extension(C c) { - public int Property - { - get { System.Console.Write("property"); return 42; } - } + public D GetAwaiter() => new D(); } } +"; + + var comp = CreateCompilation(text); + CompileAndVerify(comp, expectedOutput: "42").VerifyDiagnostics(); + + string expectedOperationTree = """ +IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i = await new C();') +IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = await new C()') + Declarators: + IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = await new C()') + Initializer: + IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= await new C()') + IAwaitOperation (OperationKind.Await, Type: System.Int32) (Syntax: 'await new C()') + Expression: + IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') + Arguments(0) + Initializer: + null + Initializer: + null """; - var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "property").VerifyDiagnostics(); - var tree = comp.SyntaxTrees.First(); - var model = comp.GetSemanticModel(tree); - var nameColon = GetSyntax(tree, "Property:"); - Assert.Equal("System.Int32 E.<>E__0.Property { get; }", model.GetSymbolInfo(nameColon.Name).Symbol.ToTestDisplayString()); + VerifyOperationTreeAndDiagnosticsForTest(text, expectedOperationTree, [], targetFramework: TargetFramework.Net70); } [Fact] - public void ExtensionMemberLookup_Patterns_Conversion_01() + public void ExtensionMemberLookup_PatternBased_Await_ExtensionGetAwaiter_Conversion() { - var src = """ -var c = new C(); -_ = c is { Property: 42 }; + var text = @" +using System; +using System.Runtime.CompilerServices; -class C { } +int i = await new C(); +System.Console.Write(i); + +class C +{ +} + +class D : INotifyCompletion +{ + public int GetResult() => 42; + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; +} static class E { extension(object o) { - public int Property - { - get { System.Console.Write("property"); return 42; } - } + public D GetAwaiter() => new D(); } } -"""; - var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "property").VerifyDiagnostics(); +"; + + var comp = CreateCompilation(text); + CompileAndVerify(comp, expectedOutput: "42").VerifyDiagnostics(); } [Fact] - public void ExtensionMemberLookup_Patterns_Conversion_02() + public void ExtensionMemberLookup_PatternBased_Await_ExtensionGetAwaiter_DelegateTypeProperty() { - // implicit span conversion: array to Span - var src = """ -int[] i = [42]; -_ = i is { Property: 42 }; -i.M(); + var text = @" +using System; +using System.Runtime.CompilerServices; -class C { } +int i = await new C(); +System.Console.Write(i); + +class C +{ +} + +class D : INotifyCompletion +{ + public int GetResult() => 42; + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; +} static class E { - extension(System.Span s) + extension(C c) { - public int Property - { - get { System.Console.Write("property "); return 42; } - } + public System.Func GetAwaiter => () => new D(); } - public static void M(this System.Span s) { System.Console.Write("method"); } } -"""; - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); - var verify = CompileAndVerify(comp, expectedOutput: ExpectedOutput("property method"), verify: Verification.Skipped).VerifyDiagnostics(); - verify.VerifyIL("", """ +"; + + var comp = CreateCompilation(text); + comp.VerifyEmitDiagnostics( + // (5,9): error CS1061: 'C' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) + // int i = await new C(); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "await new C()").WithArguments("C", "GetAwaiter").WithLocation(5, 9)); + + text = @" +using System; +using System.Runtime.CompilerServices; + +int i = await new C(); +System.Console.Write(i); + +class C { - // Code size 46 (0x2e) - .maxstack 4 - .locals init (int[] V_0) //i - IL_0000: ldc.i4.1 - IL_0001: newarr "int" - IL_0006: dup - IL_0007: ldc.i4.0 - IL_0008: ldc.i4.s 42 - IL_000a: stelem.i4 - IL_000b: stloc.0 - IL_000c: ldloc.0 - IL_000d: brfalse.s IL_0020 - IL_000f: ldloc.0 - IL_0010: call "System.Span System.Span.op_Implicit(int[])" - IL_0015: call "int E.get_Property(System.Span)" - IL_001a: ldc.i4.s 42 - IL_001c: ceq - IL_001e: br.s IL_0021 - IL_0020: ldc.i4.0 - IL_0021: pop - IL_0022: ldloc.0 - IL_0023: call "System.Span System.Span.op_Implicit(int[])" - IL_0028: call "void E.M(System.Span)" - IL_002d: ret + public System.Func GetAwaiter => () => new D(); } -"""); + +class D : INotifyCompletion +{ + public int GetResult() => 42; + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; +} +"; + + comp = CreateCompilation(text); + comp.VerifyEmitDiagnostics( + // (5,9): error CS0118: 'GetAwaiter' is a property but is used like a method + // int i = await new C(); + Diagnostic(ErrorCode.ERR_BadSKknown, "await new C()").WithArguments("GetAwaiter", "property", "method").WithLocation(5, 9)); } [Fact] - public void ExtensionMemberLookup_Patterns_Conversion_03() + public void ExtensionMemberLookup_PatternBased_Await_ExtensionGetAwaiter_DynamicTypeProperty() { - // implicit span conversion: array to Span - var src = """ -string[] i = [""]; -_ = i is { Property: 42 }; -i.M(); + var text = @" +using System; +using System.Runtime.CompilerServices; -class C { } +int i = await new C(); +System.Console.Write(i); + +class C +{ +} + +class D : INotifyCompletion +{ + public int GetResult() => 42; + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; +} static class E { - extension(System.Span s) + extension(C c) { - public int Property - { - get { System.Console.Write("property "); return 42; } - } + public dynamic GetAwaiter => throw null; } - public static void M(this System.Span s) { System.Console.Write("method"); } } -"""; - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); +"; + + var comp = CreateCompilation(text); comp.VerifyEmitDiagnostics( - // (2,12): error CS9286: 'string[]' does not contain a definition for 'Property' and no accessible extension member 'Property' for receiver of type 'string[]' could be found (are you missing a using directive or an assembly reference?) - // _ = i is { Property: 42 }; - Diagnostic(ErrorCode.ERR_ExtensionResolutionFailed, "Property").WithArguments("string[]", "Property").WithLocation(2, 12), - // (3,1): error CS1929: 'string[]' does not contain a definition for 'M' and the best extension method overload 'E.M(Span)' requires a receiver of type 'System.Span' - // i.M(); - Diagnostic(ErrorCode.ERR_BadInstanceArgType, "i").WithArguments("string[]", "M", "E.M(System.Span)", "System.Span").WithLocation(3, 1)); - } + // (5,9): error CS1061: 'C' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) + // int i = await new C(); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "await new C()").WithArguments("C", "GetAwaiter").WithLocation(5, 9)); - [Fact] - public void ExtensionMemberLookup_Patterns_Conversion_04() - { - // implicit span conversion: Span to ReadOnlySpan - var src = """ -System.Span i = [""]; -_ = i is { Property: 42 }; -i.M(); + text = @" +using System; +using System.Runtime.CompilerServices; -class C { } +int i = await new C(); +System.Console.Write(i); -static class E +class C { - extension(System.ReadOnlySpan s) - { - public int Property - { - get { System.Console.Write("property "); return 42; } - } - } - public static void M(this System.ReadOnlySpan s) { System.Console.Write("method"); } + public dynamic GetAwaiter => throw null; } -"""; - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); - var verify = CompileAndVerify(comp, expectedOutput: ExpectedOutput("property method"), verify: Verification.Skipped).VerifyDiagnostics(); - verify.VerifyIL("", """ + +class D : INotifyCompletion { - // Code size 46 (0x2e) - .maxstack 2 - .locals init (string V_0) - IL_0000: ldstr "" - IL_0005: stloc.0 - IL_0006: ldloca.s V_0 - IL_0008: newobj "System.Span..ctor(ref string)" - IL_000d: dup - IL_000e: call "System.ReadOnlySpan System.Span.op_Implicit(System.Span)" - IL_0013: call "System.ReadOnlySpan System.ReadOnlySpan.CastUp(System.ReadOnlySpan)" - IL_0018: call "int E.get_Property(System.ReadOnlySpan)" - IL_001d: pop - IL_001e: call "System.ReadOnlySpan System.Span.op_Implicit(System.Span)" - IL_0023: call "System.ReadOnlySpan System.ReadOnlySpan.CastUp(System.ReadOnlySpan)" - IL_0028: call "void E.M(System.ReadOnlySpan)" - IL_002d: ret + public int GetResult() => 42; + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; } -"""); +"; + + comp = CreateCompilation(text); + comp.VerifyEmitDiagnostics( + // (5,9): error CS0118: 'GetAwaiter' is a property but is used like a method + // int i = await new C(); + Diagnostic(ErrorCode.ERR_BadSKknown, "await new C()").WithArguments("GetAwaiter", "property", "method").WithLocation(5, 9)); } [Fact] - public void ExtensionMemberLookup_Patterns_Conversion_05() + public void ExtensionMemberLookup_PatternBased_Await_ExtensionGetResult() { - // implicit span conversion: ReadOnlySpan to ReadOnlySpan - var src = """ -System.ReadOnlySpan i = [""]; -_ = i is { Property: 42 }; -i.M(); + var text = @" +using System; +using System.Runtime.CompilerServices; -class C { } +int i = await new C(); +System.Console.Write(i); -static class E +class C { - extension(System.ReadOnlySpan s) - { - public int Property - { - get { System.Console.Write("property "); return 42; } - } - } - public static void M(this System.ReadOnlySpan s) { System.Console.Write("method"); } + public D GetAwaiter() => new D(); } -"""; - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); - var verify = CompileAndVerify(comp, expectedOutput: ExpectedOutput("property method"), verify: Verification.Skipped).VerifyDiagnostics(); - verify.VerifyIL("", """ + +class D : INotifyCompletion { - // Code size 36 (0x24) - .maxstack 2 - .locals init (string V_0) - IL_0000: ldstr "" - IL_0005: stloc.0 - IL_0006: ldloca.s V_0 - IL_0008: newobj "System.ReadOnlySpan..ctor(ref readonly string)" - IL_000d: dup - IL_000e: call "System.ReadOnlySpan System.ReadOnlySpan.CastUp(System.ReadOnlySpan)" - IL_0013: call "int E.get_Property(System.ReadOnlySpan)" - IL_0018: pop - IL_0019: call "System.ReadOnlySpan System.ReadOnlySpan.CastUp(System.ReadOnlySpan)" - IL_001e: call "void E.M(System.ReadOnlySpan)" - IL_0023: ret + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; } -"""); - } - - [Fact] - public void ExtensionMemberLookup_Patterns_Conversion_06() - { - // implicit span conversion: string to ReadOnlySpan - var src = """ -string s = ""; -_ = s is { Property: 42 }; -s.M(); - -class C { } static class E { - extension(System.ReadOnlySpan s) + extension(D d) { - public int Property - { - get { System.Console.Write("property "); return 42; } - } + public int GetResult() => 42; } - public static void M(this System.ReadOnlySpan s) { System.Console.Write("method"); } } -"""; - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); - var verify = CompileAndVerify(comp, expectedOutput: ExpectedOutput("property method"), verify: Verification.Skipped).VerifyDiagnostics(); - verify.VerifyIL("", """ +"; + + var comp = CreateCompilation(text); + + // The error is consistent with classic extension methods + comp.VerifyEmitDiagnostics( + // (5,9): error CS0117: 'D' does not contain a definition for 'GetResult' + // int i = await new C(); + Diagnostic(ErrorCode.ERR_NoSuchMember, "await new C()").WithArguments("D", "GetResult").WithLocation(5, 9) + ); + + text = """ +using System; +using System.Runtime.CompilerServices; + +int i = await new C(); +System.Console.Write(i); + +class C { - // Code size 40 (0x28) - .maxstack 2 - .locals init (string V_0) //s - IL_0000: ldstr "" - IL_0005: stloc.0 - IL_0006: ldloc.0 - IL_0007: brfalse.s IL_001a - IL_0009: ldloc.0 - IL_000a: call "System.ReadOnlySpan System.MemoryExtensions.AsSpan(string)" - IL_000f: call "int E.get_Property(System.ReadOnlySpan)" - IL_0014: ldc.i4.s 42 - IL_0016: ceq - IL_0018: br.s IL_001b - IL_001a: ldc.i4.0 - IL_001b: pop - IL_001c: ldloc.0 - IL_001d: call "System.ReadOnlySpan System.MemoryExtensions.AsSpan(string)" - IL_0022: call "void E.M(System.ReadOnlySpan)" - IL_0027: ret + public D GetAwaiter() => new D(); } -"""); - var spanSrc = """ -namespace System; +class D : INotifyCompletion +{ + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; +} -public readonly ref struct ReadOnlySpan +static class E { + public static int GetResult(this D d) => 42; } """; - comp = CreateCompilation([src, spanSrc]); + + comp = CreateCompilation(text); comp.VerifyEmitDiagnostics( - // (2,12): error CS0656: Missing compiler required member 'System.MemoryExtensions.AsSpan' - // _ = s is { Property: 42 }; - Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "Property").WithArguments("System.MemoryExtensions", "AsSpan").WithLocation(2, 12), - // (3,1): error CS0656: Missing compiler required member 'System.MemoryExtensions.AsSpan' - // s.M(); - Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "s").WithArguments("System.MemoryExtensions", "AsSpan").WithLocation(3, 1)); + // (4,9): error CS0117: 'D' does not contain a definition for 'GetResult' + // int i = await new C(); + Diagnostic(ErrorCode.ERR_NoSuchMember, "await new C()").WithArguments("D", "GetResult").WithLocation(4, 9) + ); } [Fact] - public void ExtensionMemberLookup_Patterns_Conversion_07() + public void ExtensionMemberLookup_PatternBased_Await_ExtensionGetResult_DelegateTypeProperty() { - // boxing - var src = """ -int i = 42; -_ = i is { Property: 42 }; -i.M(); + var text = @" +using System; +using System.Runtime.CompilerServices; -class C { } +int i = await new C(); +System.Console.Write(i); -static class E +class C { - extension(object o) - { - public int Property - { - get { System.Console.Write("property "); return 42; } - } - } - public static void M(this object o) { System.Console.Write("method"); } + public D GetAwaiter() => new D(); } -"""; - var comp = CreateCompilation(src); - var verify = CompileAndVerify(comp, expectedOutput: "property method").VerifyDiagnostics(); - verify.VerifyIL("", """ + +class D : INotifyCompletion { - // Code size 25 (0x19) - .maxstack 2 - IL_0000: ldc.i4.s 42 - IL_0002: dup - IL_0003: box "int" - IL_0008: call "int E.get_Property(object)" - IL_000d: pop - IL_000e: box "int" - IL_0013: call "void E.M(object)" - IL_0018: ret + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; } -"""); - } - - [Fact] - public void ExtensionMemberLookup_Patterns_Conversion_08() - { - // implicit tuple conversion - var src = """ -(int, string) t = (42, ""); -_ = t is { Property: 42 }; -t.M(); - -class C { } static class E { - extension((object, object) t) + extension(D d) { - public int Property - { - get { System.Console.Write("property "); return 42; } - } + public System.Func GetResult => () => 42; } - public static void M(this (object, object) t) { System.Console.Write("method"); } -} -"""; - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); - var verify = CompileAndVerify(comp, expectedOutput: ExpectedOutput("property method"), verify: Verification.Skipped).VerifyDiagnostics(); - verify.VerifyIL("", """ -{ - // Code size 71 (0x47) - .maxstack 3 - .locals init (System.ValueTuple V_0) - IL_0000: ldc.i4.s 42 - IL_0002: ldstr "" - IL_0007: newobj "System.ValueTuple..ctor(int, string)" - IL_000c: dup - IL_000d: stloc.0 - IL_000e: ldloc.0 - IL_000f: ldfld "int System.ValueTuple.Item1" - IL_0014: box "int" - IL_0019: ldloc.0 - IL_001a: ldfld "string System.ValueTuple.Item2" - IL_001f: newobj "System.ValueTuple..ctor(object, object)" - IL_0024: call "int E.get_Property(System.ValueTuple)" - IL_0029: pop - IL_002a: stloc.0 - IL_002b: ldloc.0 - IL_002c: ldfld "int System.ValueTuple.Item1" - IL_0031: box "int" - IL_0036: ldloc.0 - IL_0037: ldfld "string System.ValueTuple.Item2" - IL_003c: newobj "System.ValueTuple..ctor(object, object)" - IL_0041: call "void E.M(System.ValueTuple)" - IL_0046: ret } -"""); - } +"; + var comp = CreateCompilation(text); + comp.VerifyEmitDiagnostics( + // (5,9): error CS0117: 'D' does not contain a definition for 'GetResult' + // int i = await new C(); + Diagnostic(ErrorCode.ERR_NoSuchMember, "await new C()").WithArguments("D", "GetResult").WithLocation(5, 9)); - [Fact] - public void ExtensionMemberLookup_Patterns_Conversion_09() - { - // We check conversion during initial binding - var src = """ -int[] i = []; -_ = i is { Property: 42 }; + text = """ +using System; +using System.Runtime.CompilerServices; -static class E +int i = await new C(); +System.Console.Write(i); + +class C { - extension(System.ReadOnlySpan r) - { - public int Property => throw null; - } + public D GetAwaiter() => new D(); } -namespace System +class D : INotifyCompletion { - public ref struct ReadOnlySpan - { - } + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; + public System.Func GetResult => () => 42; } """; - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + + comp = CreateCompilation(text); comp.VerifyEmitDiagnostics( - // (2,12): error CS0656: Missing compiler required member 'ReadOnlySpan.op_Implicit' - // _ = i is { Property: 42 }; - Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "Property").WithArguments("System.ReadOnlySpan", "op_Implicit").WithLocation(2, 12), - // (6,22): warning CS0436: The type 'ReadOnlySpan' in '' conflicts with the imported type 'ReadOnlySpan' in 'System.Runtime, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Using the type defined in ''. - // extension(System.ReadOnlySpan r) - Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "ReadOnlySpan").WithArguments("", "System.ReadOnlySpan", "System.Runtime, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.ReadOnlySpan").WithLocation(6, 22)); + // (4,9): error CS0118: 'GetResult' is a property but is used like a method + // int i = await new C(); + Diagnostic(ErrorCode.ERR_BadSKknown, "await new C()").WithArguments("GetResult", "property", "method").WithLocation(4, 9)); } [Fact] - public void ExtensionMemberLookup_Patterns_ExtendedPropertyPattern() + public void ExtensionMemberLookup_PatternBased_Await_ExtensionGetResult_DynamicTypeProperty() { - var src = """ -var c = new C(); + var text = @" +using System; +using System.Runtime.CompilerServices; -_ = c is { Property.Property2: 43 }; +int i = await new C(); +System.Console.Write(i); -class C { } +class C +{ + public D GetAwaiter() => new D(); +} -static class E1 +class D : INotifyCompletion { - extension(C c) - { - public int Property { get { System.Console.Write("property "); return 42; } } - } + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; } -static class E2 +static class E { - extension(int i) + extension(D d) { - public int Property2 { get { System.Console.Write("property2"); return 43; } } + public dynamic GetResult => throw null; } } -"""; - var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "property property2").VerifyDiagnostics(); - - var tree = comp.SyntaxTrees.First(); - var model = comp.GetSemanticModel(tree); - var expressionColon = GetSyntax(tree, "Property.Property2:"); - Assert.Equal("System.Int32 E2.<>E__0.Property2 { get; }", model.GetSymbolInfo(expressionColon.Expression).Symbol.ToTestDisplayString()); - } +"; - [Fact] - public void ExtensionMemberLookup_Patterns_ExtendedPropertyPattern_Conversion() - { - var src = """ -var c = new C(); + var comp = CreateCompilation(text); + comp.VerifyEmitDiagnostics( + // (5,9): error CS0117: 'D' does not contain a definition for 'GetResult' + // int i = await new C(); + Diagnostic(ErrorCode.ERR_NoSuchMember, "await new C()").WithArguments("D", "GetResult").WithLocation(5, 9)); -_ = c is { Property.Property2: 43 }; + text = """ +using System; +using System.Runtime.CompilerServices; -class C { } +int i = await new C(); +System.Console.Write(i); -static class E1 +class C { - extension(object o) - { - public int Property { get { System.Console.Write("property "); return 42; } } - } + public D GetAwaiter() => new D(); } -static class E2 +class D : INotifyCompletion { - extension(int i) - { - public int Property2 { get { System.Console.Write("property2"); return 43; } } - } + public void OnCompleted(Action continuation) => throw null; + public bool IsCompleted => true; + public dynamic GetResult => throw null; } """; - var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "property property2").VerifyDiagnostics(); + + comp = CreateCompilation(text); + comp.VerifyEmitDiagnostics( + // (4,9): error CS0118: 'GetResult' is a property but is used like a method + // int i = await new C(); + Diagnostic(ErrorCode.ERR_BadSKknown, "await new C()").WithArguments("GetResult", "property", "method").WithLocation(4, 9)); } [Fact] - public void ExtensionMemberLookup_Patterns_ExtendedPropertyPattern_Conversion_02() + public void ExtensionMemberLookup_PatternBased_IndexIndexer_Length() { var src = """ var c = new C(); -_ = c is { Property.Property2: 43 }; +/**/ +_ = c[^1]; +/**/ -class C { } +class C +{ + public int this[int i] => throw null; +} -static class E1 +static class E { extension(C c) { - public C Property { get { System.Console.Write("property "); return c; } } + public int Length => throw null; } } - -static class E2 +"""; + DiagnosticDescription[] expectedDiagnostics = [ + // (4,7): error CS1503: Argument 1: cannot convert from 'System.Index' to 'int' + // _ = c[^1]; + Diagnostic(ErrorCode.ERR_BadArgType, "^1").WithArguments("1", "System.Index", "int").WithLocation(4, 7)]; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics(expectedDiagnostics); + + string expectedOperationTree = """ +ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: '_ = c[^1]') +Left: + IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: '_') +Right: + IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'c[^1]') + Children(2): + ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') + IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index, IsInvalid) (Syntax: '^1') + Operand: + ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') +"""; + + VerifyOperationTreeAndDiagnosticsForTest(src, expectedOperationTree, expectedDiagnostics, targetFramework: TargetFramework.Net70); + + src = """ +var c = new C(); +_ = c[^1]; + +class C { - extension(object o) - { - public int Property2 { get { System.Console.Write("property2"); return 43; } } - } + public int this[int i] => throw null; + public int Length => throw null; } """; - var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "property property2").VerifyDiagnostics(); + comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics(); } [Fact] - public void ExtensionMemberLookup_Patterns_ListPattern_NoInstanceLength() + public void ExtensionMemberLookup_PatternBased_IndexIndexer_Count() { var src = """ -System.Console.Write(new C() is ["hi"]); +var c = new C(); +_ = c[^1]; class C { - public string this[System.Index i] - { - get { System.Console.Write("indexer "); return "hi"; } - } + public int this[int i] => throw null; } static class E { extension(C c) { - public int Length - { - get { System.Console.Write("length "); return 42; } - } + public int Count => throw null; } } """; var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : confirm whether we want extension Length/Count to contribute to list-patterns comp.VerifyEmitDiagnostics( - // (1,33): error CS8985: List patterns may not be used for a value of type 'C'. No suitable 'Length' or 'Count' property was found. - // System.Console.Write(new C() is ["hi"]); - Diagnostic(ErrorCode.ERR_ListPatternRequiresLength, @"[""hi""]").WithArguments("C").WithLocation(1, 33) - ); + // (2,7): error CS1503: Argument 1: cannot convert from 'System.Index' to 'int' + // _ = c[^1]; + Diagnostic(ErrorCode.ERR_BadArgType, "^1").WithArguments("1", "System.Index", "int").WithLocation(2, 7)); + + src = """ +var c = new C(); +_ = c[^1]; + +class C +{ + public int this[int i] => throw null; + public int Count => throw null; +} +"""; + comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics(); } [Fact] - public void ExtensionMemberLookup_ObjectInitializer() + public void ExtensionMemberLookup_PatternBased_IndexIndexer_IntIndexer() { var src = """ -_ = new C() { Property = 42 }; +var c = new C(); +_ = c[^1]; -class C { } +class C +{ + public int Length => throw null; +} static class E { extension(C c) { - public int Property { set { System.Console.Write("property"); } } + public int this[int i] => throw null; } } """; - - var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "property").VerifyDiagnostics(); - - var tree = comp.SyntaxTrees.First(); - var model = comp.GetSemanticModel(tree); - var assignment = GetSyntax(tree, "Property = 42"); - Assert.Equal("System.Int32 E.<>E__0.Property { set; }", model.GetSymbolInfo(assignment.Left).Symbol.ToTestDisplayString()); + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics( + // (2,5): error CS0021: Cannot apply indexing with [] to an expression of type 'C' + // _ = c[^1]; + Diagnostic(ErrorCode.ERR_BadIndexLHS, "c[^1]").WithArguments("C").WithLocation(2, 5), + // (13,20): error CS9282: This member is not allowed in an extension block + // public int this[int i] => throw null; + Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(13, 20)); } [Fact] - public void ExtensionMemberLookup_ObjectInitializer_Conversion_01() + public void ExtensionMemberLookup_PatternBased_IndexIndexer_RegularIndexer() { var src = """ -_ = new C() { Property = 42 }; +var c = new C(); +_ = c[^1]; -class C { } +class C +{ + public int Length => throw null; +} static class E { - extension(object o) + extension(C c) { - public int Property { set { System.Console.Write("property"); } } + public int this[System.Index i] => throw null; } } """; + // Tracked by https://github.com/dotnet/roslyn/issues/78829 : revisit when implementing extension indexers + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics( + // (2,5): error CS0021: Cannot apply indexing with [] to an expression of type 'C' + // _ = c[^1]; + Diagnostic(ErrorCode.ERR_BadIndexLHS, "c[^1]").WithArguments("C").WithLocation(2, 5), + // (13,20): error CS9282: This member is not allowed in an extension block + // public int this[System.Index i] => throw null; + Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(13, 20)); - var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "property").VerifyDiagnostics(); + src = """ +var c = new C(); +_ = c[^1]; + +class C +{ + public int Length => throw null; + public int this[System.Index i] => throw null; +} +"""; + comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics(); } [Fact] - public void ExtensionMemberLookup_ObjectInitializer_Conversion_02() + public void ExtensionMemberLookup_PatternBased_RangeIndexer_Slice() { var src = """ -_ = new System.ReadOnlySpan() { Property = 42 }; +var c = new C(); -new System.ReadOnlySpan().Property = 43; +/**/ +_ = c[1..^1]; +/**/ -class C { } +class C +{ + public int Length => throw null; +} static class E { - extension(System.ReadOnlySpan s) + extension(C c) { - public int Property { set { } } + public int Slice(int i, int j) => throw null; } } """; - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : consider adjusting receiver requirements for extension members - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); - comp.VerifyEmitDiagnostics( - // (1,41): error CS0131: The left-hand side of an assignment must be a variable, property or indexer - // _ = new System.ReadOnlySpan() { Property = 42 }; - Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "Property").WithLocation(1, 41), - // (3,1): error CS0131: The left-hand side of an assignment must be a variable, property or indexer - // new System.ReadOnlySpan().Property = 43; - Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "new System.ReadOnlySpan().Property").WithLocation(3, 1)); + DiagnosticDescription[] expectedDiagnostics = [ + // (4,5): error CS0021: Cannot apply indexing with [] to an expression of type 'C' + // _ = c[1..^1]; + Diagnostic(ErrorCode.ERR_BadIndexLHS, "c[1..^1]").WithArguments("C").WithLocation(4, 5)]; + + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics(expectedDiagnostics); + + string expectedOperationTree = """ +ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '_ = c[1..^1]') +Left: + IDiscardOperation (Symbol: ? _) (OperationKind.Discard, Type: ?) (Syntax: '_') +Right: + IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'c[1..^1]') + Children(2): + IRangeOperation (OperationKind.Range, Type: System.Range, IsInvalid) (Syntax: '1..^1') + LeftOperand: + IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Index System.Index.op_Implicit(System.Int32 value)) (OperationKind.Conversion, Type: System.Index, IsInvalid, IsImplicit) (Syntax: '1') + Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Index System.Index.op_Implicit(System.Int32 value)) + Operand: + ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') + RightOperand: + IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index, IsInvalid) (Syntax: '^1') + Operand: + ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') + ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c') +"""; + + VerifyOperationTreeAndDiagnosticsForTest(src, expectedOperationTree, expectedDiagnostics, targetFramework: TargetFramework.Net70); src = """ -new S().Property = 42; +var c = new C(); +_ = c[1..^1]; -struct S +class C { - public int Property { set { } } + public int Length => throw null; + public int Slice(int i, int j) => throw null; } """; - comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); - comp.VerifyEmitDiagnostics( - // (1,1): error CS0131: The left-hand side of an assignment must be a variable, property or indexer - // new S().Property = 42; - Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "new S().Property").WithLocation(1, 1)); + comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics(); } [Fact] - public void ExtensionMemberLookup_ObjectInitializer_Conversion_03() + public void ExtensionMemberLookup_PatternBased_RangeIndexer_Length() { - // implicit tuple conversion var src = """ -_ = new System.ValueTuple() { Property = 42 }; +var c = new C(); +_ = c[1..^1]; + +class C +{ + public int Slice(int i, int j) => throw null; +} static class E { - extension((object, object) t) + extension(C c) { - public int Property - { - set { System.Console.Write("property"); } - } + public int Length => throw null; } } """; - var comp = CreateCompilation(src); + + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); comp.VerifyEmitDiagnostics( - // (1,44): error CS0131: The left-hand side of an assignment must be a variable, property or indexer - // _ = new System.ValueTuple() { Property = 42 }; - Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "Property").WithLocation(1, 44)); + // (2,5): error CS0021: Cannot apply indexing with [] to an expression of type 'C' + // _ = c[1..^1]; + Diagnostic(ErrorCode.ERR_BadIndexLHS, "c[1..^1]").WithArguments("C").WithLocation(2, 5)); } [Fact] - public void ExtensionMemberLookup_ObjectInitializer_Conversion_04() + public void ExtensionMemberLookup_PatternBased_RangeIndexer_RegularIndexer() { - // implicit span conversion from string var src = """ -_ = new System.String('a', 10) { Property = 42 }; +var c = new C(); +_ = c[1..^1]; + +class C +{ + public int Length => throw null; +} static class E { - extension(System.ReadOnlySpan s) + extension(C c) { - public int Property - { - set { System.Console.Write(value); } - } + public int this[System.Range r] => throw null; } } """; - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); - comp.VerifyDiagnostics( - // (1,34): error CS0131: The left-hand side of an assignment must be a variable, property or indexer - // _ = new System.String('a', 10) { Property = 42 }; - Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "Property").WithLocation(1, 34)); + + // Tracked by https://github.com/dotnet/roslyn/issues/78829 : revisit when implementing extension indexers + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics( + // (2,5): error CS0021: Cannot apply indexing with [] to an expression of type 'C' + // _ = c[1..^1]; + Diagnostic(ErrorCode.ERR_BadIndexLHS, "c[1..^1]").WithArguments("C").WithLocation(2, 5), + // (13,20): error CS9282: This member is not allowed in an extension block + // public int this[System.Range r] => throw null; + Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(13, 20)); + + src = """ +var c = new C(); +_ = c[1..^1]; + +class C +{ + public int Length => throw null; + public int this[System.Range r] => throw null; +} +"""; + + comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics(); } [Fact] - public void ExtensionMemberLookup_With() + public void ExtensionMemberLookup_PatternBased_ListPattern_Length() { var src = """ -_ = new S() with { Property = 42 }; +_ = new C() is [1]; -struct S { } +class C +{ + public int this[int i] => throw null; +} static class E { - extension(S s) + extension(C c) { - public int Property { set { System.Console.Write("property"); } } + public int Length => throw null; } } """; - var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "property").VerifyDiagnostics(); + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics( + // (1,16): error CS8985: List patterns may not be used for a value of type 'C'. No suitable 'Length' or 'Count' property was found. + // _ = new C() is [1]; + Diagnostic(ErrorCode.ERR_ListPatternRequiresLength, "[1]").WithArguments("C").WithLocation(1, 16), + // (1,16): error CS1503: Argument 1: cannot convert from 'System.Index' to 'int' + // _ = new C() is [1]; + Diagnostic(ErrorCode.ERR_BadArgType, "[1]").WithArguments("1", "System.Index", "int").WithLocation(1, 16)); - var tree = comp.SyntaxTrees.First(); - var model = comp.GetSemanticModel(tree); - var assignment = GetSyntax(tree, "Property = 42"); - Assert.Equal("System.Int32 E.<>E__0.Property { set; }", model.GetSymbolInfo(assignment.Left).Symbol.ToTestDisplayString()); + src = """ +_ = new C() is [1]; + +class C +{ + public int this[int i] => throw null; + public int Length => throw null; +} +"""; + comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics(); } [Fact] - public void ExtensionMemberLookup_CollectionInitializer() + public void ExtensionMemberLookup_PatternBased_ListPattern_IntIndexer() { var src = """ -using System.Collections; -using System.Collections.Generic; - -/**/ -_ = new C() { 42 }; -/**/ +_ = new C() is [1]; -class C : IEnumerable, IEnumerable +class C { - IEnumerator IEnumerable.GetEnumerator() => throw null; - IEnumerator IEnumerable.GetEnumerator() => throw null; + public int Length => throw null; } static class E { extension(C c) { - public void Add(int i) { System.Console.Write("add"); } + public int this[int i] => throw null; } } """; - - var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "add").VerifyDiagnostics(); - - string expectedOperationTree = """ -ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: '_ = new C() { 42 }') -Left: - IDiscardOperation (Symbol: C _) (OperationKind.Discard, Type: C) (Syntax: '_') -Right: - IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C() { 42 }') - Arguments(0) - Initializer: - IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ 42 }') - Initializers(1): - IInvocationOperation ( void E.<>E__0.Add(System.Int32 i)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '42') - Instance Receiver: - IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'C') - Arguments(1): - IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '42') - ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') - InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) - OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) -"""; - var expectedDiagnostics = DiagnosticDescription.None; - - VerifyOperationTreeAndDiagnosticsForTest(src, expectedOperationTree, expectedDiagnostics); + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics( + // (1,16): error CS0021: Cannot apply indexing with [] to an expression of type 'C' + // _ = new C() is [1]; + Diagnostic(ErrorCode.ERR_BadIndexLHS, "[1]").WithArguments("C").WithLocation(1, 16), + // (12,20): error CS9282: This member is not allowed in an extension block + // public int this[int i] => throw null; + Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(12, 20)); } [Fact] - public void ExtensionMemberLookup_CollectionInitializer_Conversion() + public void ExtensionMemberLookup_PatternBased_ListPattern_RegularIndexer() { var src = """ -using System.Collections; -using System.Collections.Generic; - -/**/ -_ = new C() { 42 }; -/**/ +_ = new C() is [1]; -class C : IEnumerable, IEnumerable +class C { - IEnumerator IEnumerable.GetEnumerator() => throw null; - IEnumerator IEnumerable.GetEnumerator() => throw null; + public int Length => throw null; } static class E { - extension(object o) + extension(C c) { - public void Add(int i) { System.Console.Write("add"); } + public int this[System.Index i] => throw null; } } """; - var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "add").VerifyDiagnostics(); + // Tracked by https://github.com/dotnet/roslyn/issues/78829 : revisit when implementing extension indexers + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics( + // (1,16): error CS0021: Cannot apply indexing with [] to an expression of type 'C' + // _ = new C() is [1]; + Diagnostic(ErrorCode.ERR_BadIndexLHS, "[1]").WithArguments("C").WithLocation(1, 16), + // (12,20): error CS9282: This member is not allowed in an extension block + // public int this[System.Index i] => throw null; + Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(12, 20)); - string expectedOperationTree = """ -ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: '_ = new C() { 42 }') -Left: - IDiscardOperation (Symbol: C _) (OperationKind.Discard, Type: C) (Syntax: '_') -Right: - IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C() { 42 }') - Arguments(0) - Initializer: - IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ 42 }') - Initializers(1): - IInvocationOperation ( void E.<>E__0.Add(System.Int32 i)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '42') - Instance Receiver: - IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'C') - Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) - Operand: - IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'C') - Arguments(1): - IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '42') - ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') - InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) - OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + src = """ +_ = new C() is [1]; + +class C +{ + public int Length => throw null; + public int this[System.Index i] => throw null; +} """; - var expectedDiagnostics = DiagnosticDescription.None; - VerifyOperationTreeAndDiagnosticsForTest(src, expectedOperationTree, expectedDiagnostics); + comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics(); } [Fact] - public void ExtensionMemberLookup_CollectionInitializer_NoApplicableMethod() + public void ExtensionMemberLookup_PatternBased_SpreadPattern_Length() { var src = """ -using System.Collections; -using System.Collections.Generic; +_ = new C() is [_, .. var x]; -class Program +class C { - static void Main() + public int this[System.Index i] => throw null; + public int Slice(int i, int j) => throw null; +} + +static class E +{ + extension(C c) { - /**/ - _ = new C() { 42 }; - /**/ + public int Length => throw null; } } +"""; -class C : IEnumerable, IEnumerable + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics( + // (1,16): error CS8985: List patterns may not be used for a value of type 'C'. No suitable 'Length' or 'Count' property was found. + // _ = new C() is [_, .. var x]; + Diagnostic(ErrorCode.ERR_ListPatternRequiresLength, "[_, .. var x]").WithArguments("C").WithLocation(1, 16), + // (1,20): error CS1503: Argument 1: cannot convert from 'System.Range' to 'System.Index' + // _ = new C() is [_, .. var x]; + Diagnostic(ErrorCode.ERR_BadArgType, ".. var x").WithArguments("1", "System.Range", "System.Index").WithLocation(1, 20)); + + src = """ +_ = new C() is [_, .. var x]; + +class C { - IEnumerator IEnumerable.GetEnumerator() => throw null; - IEnumerator IEnumerable.GetEnumerator() => throw null; - public void Add(string notApplicable) => throw null; + public int this[System.Index i] => throw null; + public int Slice(int i, int j) => throw null; + public int Length => throw null; +} +"""; + comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics(); + } + + [Fact] + public void ExtensionMemberLookup_PatternBased_SpreadPattern_Slice() + { + var src = """ +_ = new C() is [_, .. var x]; + +class C +{ + public int this[System.Index i] => throw null; + public int Length => throw null; } static class E { - extension(object o) + extension(C c) { - public void Add(int i) { System.Console.Write("add"); } + public int Slice(int i, int j) => throw null; } } """; - var comp = CreateCompilation(src, options: TestOptions.DebugExe); - CompileAndVerify(comp, expectedOutput: "add").VerifyDiagnostics(); - - string expectedOperationTree = """ -ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: '_ = new C() { 42 }') - Left: - IDiscardOperation (Symbol: C _) (OperationKind.Discard, Type: C) (Syntax: '_') - Right: - IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C() { 42 }') - Arguments(0) - Initializer: - IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ 42 }') - Initializers(1): - IInvocationOperation ( void E.<>E__0.Add(System.Int32 i)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '42') - Instance Receiver: - IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'C') - Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) - Operand: - IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'C') - Arguments(1): - IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '42') - ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') - InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) - OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) -"""; - var expectedDiagnostics = DiagnosticDescription.None; - - VerifyOperationTreeAndDiagnosticsForTest(src, expectedOperationTree, expectedDiagnostics); - - VerifyFlowGraph(comp, comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType().First(), """ -Block[B0] - Entry - Statements (0) - Next (Regular) Block[B1] - Entering: {R1} -.locals {R1} -{ - CaptureIds: [0] - Block[B1] - Block - Predecessors: [B0] - Statements (3) - IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new C() { 42 }') - Value: - IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C() { 42 }') - Arguments(0) - Initializer: - null - IInvocationOperation ( void E.<>E__0.Add(System.Int32 i)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '42') - Instance Receiver: - IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'C') - Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) - (ImplicitReference) - Operand: - IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'new C() { 42 }') - Arguments(1): - IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '42') - ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') - InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) - OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) - IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = new C() { 42 };') - Expression: - ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: '_ = new C() { 42 }') - Left: - IDiscardOperation (Symbol: C _) (OperationKind.Discard, Type: C) (Syntax: '_') - Right: - IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'new C() { 42 }') - Next (Regular) Block[B2] - Leaving: {R1} -} -Block[B2] - Exit - Predecessors: [B1] - Statements (0) -"""); - } + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics( + // (1,20): error CS1503: Argument 1: cannot convert from 'System.Range' to 'System.Index' + // _ = new C() is [_, .. var x]; + Diagnostic(ErrorCode.ERR_BadArgType, ".. var x").WithArguments("1", "System.Range", "System.Index").WithLocation(1, 20)); + } [Fact] - public void ExtensionMemberLookup_CollectionInitializer_NoApplicableMethod_ExpressionTree() + public void ExtensionMemberLookup_PatternBased_SpreadPattern_RegularIndexer() { var src = """ -using System.Collections; -using System.Collections.Generic; - -try -{ - System.Linq.Expressions.Expression> e = () => new C() { 42 }; - System.Console.Write(e); -} -catch (System.ArgumentException ae) -{ - System.Console.Write(ae.Message); -} +_ = new C() is [_, .. var x]; -class C : IEnumerable, IEnumerable +class C { - IEnumerator IEnumerable.GetEnumerator() => throw null; - IEnumerator IEnumerable.GetEnumerator() => throw null; - public void Add(string notApplicable) => throw null; + public int this[System.Index i] => throw null; + public int Length => throw null; } static class E { - extension(object o) + extension(C c) { - public void Add(int i) { System.Console.Write("add"); } + public int this[System.Range r] => throw null; } } """; - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : expression trees - var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); - comp.VerifyEmitDiagnostics( - // (6,76): error CS8075: An extension Add method is not supported for a collection initializer in an expression lambda. - // System.Linq.Expressions.Expression> e = () => new C() { 42 }; - Diagnostic(ErrorCode.ERR_ExtensionCollectionElementInitializerInExpressionTree, "42").WithLocation(6, 76) - ); - } - - [Fact] - public void ResolveAll_CollectionInitializer_DelegateTypeProperty() - { - var source = """ -using System.Collections; -using System.Collections.Generic; - -MyCollection c = new MyCollection() { 42 }; - -static class E -{ - extension(MyCollection c) - { - public System.Action Add => (int i) => { }; - } -} - -public class MyCollection : IEnumerable -{ - IEnumerator IEnumerable.GetEnumerator() => throw null; - IEnumerator IEnumerable.GetEnumerator() => throw null; -} -"""; - var comp = CreateCompilation(source); + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); comp.VerifyEmitDiagnostics( - // (4,39): error CS1061: 'MyCollection' does not contain a definition for 'Add' and no accessible extension method 'Add' accepting a first argument of type 'MyCollection' could be found (are you missing a using directive or an assembly reference?) - // MyCollection c = new MyCollection() { 42 }; - Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "42").WithArguments("MyCollection", "Add").WithLocation(4, 39)); - - source = """ -using System.Collections; -using System.Collections.Generic; + // (1,20): error CS1503: Argument 1: cannot convert from 'System.Range' to 'System.Index' + // _ = new C() is [_, .. var x]; + Diagnostic(ErrorCode.ERR_BadArgType, ".. var x").WithArguments("1", "System.Range", "System.Index").WithLocation(1, 20), + // (13,20): error CS9282: This member is not allowed in an extension block + // public int this[System.Range r] => throw null; + Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(13, 20)); -MyCollection c = new MyCollection() { 42 }; + src = """ +_ = new C() is [_, .. var x]; -public class MyCollection : IEnumerable +class C { - IEnumerator IEnumerable.GetEnumerator() => throw null; - IEnumerator IEnumerable.GetEnumerator() => throw null; - public System.Action Add => (int i) => { }; + public int this[System.Index i] => throw null; + public int this[System.Range r] => throw null; + public int Length => throw null; } """; - comp = CreateCompilation(source); - comp.VerifyEmitDiagnostics( - // (4,39): error CS0118: 'Add' is a property but is used like a method - // MyCollection c = new MyCollection() { 42 }; - Diagnostic(ErrorCode.ERR_BadSKknown, "42").WithArguments("Add", "property", "method").WithLocation(4, 39)); + comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics(); } [Fact] - public void ResolveAll_CollectionInitializer_DynamicTypeProperty() + public void ExtensionMemberLookup_Patterns() { - var source = """ -using System.Collections; -using System.Collections.Generic; - -MyCollection c = new MyCollection() { 42 }; + var libSrc = """ +public class C { } -static class E +public static class E { - extension(MyCollection c) + extension(C c) { - public dynamic Add => throw null; + public int Property + { + get { System.Console.Write("property"); return 42; } + } } } - -public class MyCollection : IEnumerable -{ - IEnumerator IEnumerable.GetEnumerator() => throw null; - IEnumerator IEnumerable.GetEnumerator() => throw null; -} """; - var comp = CreateCompilation(source); - comp.VerifyEmitDiagnostics( - // (4,39): error CS1061: 'MyCollection' does not contain a definition for 'Add' and no accessible extension method 'Add' accepting a first argument of type 'MyCollection' could be found (are you missing a using directive or an assembly reference?) - // MyCollection c = new MyCollection() { 42 }; - Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "42").WithArguments("MyCollection", "Add").WithLocation(4, 39)); + var libRef = CreateCompilation(libSrc).EmitToImageReference(); - source = """ -using System.Collections; -using System.Collections.Generic; + var src = """ +var c = new C(); +_ = c is { Property: 42 }; +"""; + var comp = CreateCompilation(src, references: [libRef]); + CompileAndVerify(comp, expectedOutput: "property").VerifyDiagnostics(); -MyCollection c = new MyCollection() { 42 }; + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var nameColon = GetSyntax(tree, "Property:"); + Assert.Equal("System.Int32 E.<>E__0.Property { get; }", model.GetSymbolInfo(nameColon.Name).Symbol.ToTestDisplayString()); -public class MyCollection : IEnumerable -{ - IEnumerator IEnumerable.GetEnumerator() => throw null; - IEnumerator IEnumerable.GetEnumerator() => throw null; - public dynamic Add => throw null; -} -"""; - comp = CreateCompilation(source); + comp = CreateCompilation(src, references: [libRef], parseOptions: TestOptions.Regular13); comp.VerifyEmitDiagnostics( - // (4,39): error CS0118: 'Add' is a property but is used like a method - // MyCollection c = new MyCollection() { 42 }; - Diagnostic(ErrorCode.ERR_BadSKknown, "42").WithArguments("Add", "property", "method").WithLocation(4, 39)); + // (2,12): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = c is { Property: 42 }; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "Property").WithArguments("extensions").WithLocation(2, 12)); + + comp = CreateCompilation(src, references: [libRef], parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp, expectedOutput: "property").VerifyDiagnostics(); } [Fact] - public void ExtensionMemberLookup_Query_NoMethod() + public void ExtensionMemberLookup_Patterns_Conversion_01() { var src = """ -/**/ -string query = from x in new C() select x; -/**/ - -System.Console.Write(query); +var c = new C(); +_ = c is { Property: 42 }; class C { } static class E { - extension(C c) + extension(object o) { - public string Select(System.Func selector) => "hello"; + public int Property + { + get { System.Console.Write("property"); return 42; } + } } } """; - var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "hello").VerifyDiagnostics(); - - string expectedOperationTree = """ -IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'string quer ... ) select x;') - IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'string quer ... () select x') - Declarators: - IVariableDeclaratorOperation (Symbol: System.String query) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'query = fro ... () select x') - Initializer: - IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= from x in ... () select x') - ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.String) (Syntax: 'from x in n ... () select x') - Expression: - IInvocationOperation ( System.String E.<>E__0.Select(System.Func selector)) (OperationKind.Invocation, Type: System.String, IsImplicit) (Syntax: 'select x') - Instance Receiver: - IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') - Arguments(0) - Initializer: - null - Arguments(1): - IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x') - IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func, IsImplicit) (Syntax: 'x') - Target: - IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x') - IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x') - IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x') - ReturnedValue: - IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C) (Syntax: 'x') - InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) - OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) - Initializer: - null -"""; - - VerifyOperationTreeAndDiagnosticsForTest(src, expectedOperationTree, DiagnosticDescription.None); + CompileAndVerify(comp, expectedOutput: "property").VerifyDiagnostics(); } [Fact] - public void ExtensionMemberLookup_Query_NoApplicableMethod() + public void ExtensionMemberLookup_Patterns_Conversion_02() { + // implicit span conversion: array to Span var src = """ -/**/ -string query = from x in new C() select x; -/**/ - -System.Console.Write(query); +int[] i = [42]; +_ = i is { Property: 42 }; +i.M(); -class C -{ - public string Select(int notApplicable) => throw null; // not applicable -} +class C { } static class E { - extension(C c) + extension(System.Span s) { - public string Select(System.Func selector) => "hello"; + public int Property + { + get { System.Console.Write("property "); return 42; } + } } + public static void M(this System.Span s) { System.Console.Write("method"); } } """; - - var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "hello").VerifyDiagnostics(); - - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : verify IOperation + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + var verify = CompileAndVerify(comp, expectedOutput: ExpectedOutput("property method"), verify: Verification.Skipped).VerifyDiagnostics(); + verify.VerifyIL("", """ +{ + // Code size 46 (0x2e) + .maxstack 4 + .locals init (int[] V_0) //i + IL_0000: ldc.i4.1 + IL_0001: newarr "int" + IL_0006: dup + IL_0007: ldc.i4.0 + IL_0008: ldc.i4.s 42 + IL_000a: stelem.i4 + IL_000b: stloc.0 + IL_000c: ldloc.0 + IL_000d: brfalse.s IL_0020 + IL_000f: ldloc.0 + IL_0010: call "System.Span System.Span.op_Implicit(int[])" + IL_0015: call "int E.get_Property(System.Span)" + IL_001a: ldc.i4.s 42 + IL_001c: ceq + IL_001e: br.s IL_0021 + IL_0020: ldc.i4.0 + IL_0021: pop + IL_0022: ldloc.0 + IL_0023: call "System.Span System.Span.op_Implicit(int[])" + IL_0028: call "void E.M(System.Span)" + IL_002d: ret +} +"""); } [Fact] - public void ExtensionMemberLookup_Invocation_ZeroArityMatchesAny() + public void ExtensionMemberLookup_Patterns_Conversion_03() { - var source = $$""" -object.Method(""); -object.Method(""); + // implicit span conversion: array to Span + var src = """ +string[] i = [""]; +_ = i is { Property: 42 }; +i.M(); + +class C { } static class E { - extension(object) + extension(System.Span s) { - public static void Method(int i) => throw null; - public static void Method(T t) { System.Console.Write("Method "); } - public static void Method(T1 t1, T2 t2) => throw null; + public int Property + { + get { System.Console.Write("property "); return 42; } + } } + public static void M(this System.Span s) { System.Console.Write("method"); } } """; - var comp = CreateCompilation(source); - CompileAndVerify(comp, expectedOutput: "Method Method").VerifyDiagnostics(); - - var tree = comp.SyntaxTrees.First(); - var model = comp.GetSemanticModel(tree); - var invocation = GetSyntax(tree, """object.Method("")"""); - Assert.Equal("void E.<>E__0.Method(System.String t)", model.GetSymbolInfo(invocation).Symbol.ToTestDisplayString()); - Assert.Empty(model.GetMemberGroup(invocation)); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : need to fix the semantic model + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (2,12): error CS9286: 'string[]' does not contain a definition for 'Property' and no accessible extension member 'Property' for receiver of type 'string[]' could be found (are you missing a using directive or an assembly reference?) + // _ = i is { Property: 42 }; + Diagnostic(ErrorCode.ERR_ExtensionResolutionFailed, "Property").WithArguments("string[]", "Property").WithLocation(2, 12), + // (3,1): error CS1929: 'string[]' does not contain a definition for 'M' and the best extension method overload 'E.M(Span)' requires a receiver of type 'System.Span' + // i.M(); + Diagnostic(ErrorCode.ERR_BadInstanceArgType, "i").WithArguments("string[]", "M", "E.M(System.Span)", "System.Span").WithLocation(3, 1)); } [Fact] - public void StaticPropertyAccess_ZeroArityMatchesAny() + public void ExtensionMemberLookup_Patterns_Conversion_04() { - var source = """ -int i = object.P; + // implicit span conversion: Span to ReadOnlySpan + var src = """ +System.Span i = [""]; +_ = i is { Property: 42 }; +i.M(); -static class E1 -{ - extension(object) - { - public static int P => 42; - } -} +class C { } -static class E2 +static class E { - extension(object) + extension(System.ReadOnlySpan s) { - public static void P() => throw null; + public int Property + { + get { System.Console.Write("property "); return 42; } + } } + public static void M(this System.ReadOnlySpan s) { System.Console.Write("method"); } } """; - var comp = CreateCompilation(source); - comp.VerifyEmitDiagnostics( - // (1,9): error CS9286: 'object' does not contain a definition for 'P' and no accessible extension member 'P' for receiver of type 'object' could be found (are you missing a using directive or an assembly reference?) - // int i = object.P; - Diagnostic(ErrorCode.ERR_ExtensionResolutionFailed, "object.P").WithArguments("object", "P").WithLocation(1, 9)); - - var tree = comp.SyntaxTrees.First(); - var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "object.P"); - Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); - Assert.Equal(["System.Int32 E1.<>E__0.P { get; }", "void E2.<>E__0.P()"], model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + var verify = CompileAndVerify(comp, expectedOutput: ExpectedOutput("property method"), verify: Verification.Skipped).VerifyDiagnostics(); + verify.VerifyIL("", """ +{ + // Code size 46 (0x2e) + .maxstack 2 + .locals init (string V_0) + IL_0000: ldstr "" + IL_0005: stloc.0 + IL_0006: ldloca.s V_0 + IL_0008: newobj "System.Span..ctor(ref string)" + IL_000d: dup + IL_000e: call "System.ReadOnlySpan System.Span.op_Implicit(System.Span)" + IL_0013: call "System.ReadOnlySpan System.ReadOnlySpan.CastUp(System.ReadOnlySpan)" + IL_0018: call "int E.get_Property(System.ReadOnlySpan)" + IL_001d: pop + IL_001e: call "System.ReadOnlySpan System.Span.op_Implicit(System.Span)" + IL_0023: call "System.ReadOnlySpan System.ReadOnlySpan.CastUp(System.ReadOnlySpan)" + IL_0028: call "void E.M(System.ReadOnlySpan)" + IL_002d: ret +} +"""); } [Fact] - public void StaticPropertyAccess_NonZeroArity() + public void ExtensionMemberLookup_Patterns_Conversion_05() { - var source = """ -int i = object.P; + // implicit span conversion: ReadOnlySpan to ReadOnlySpan + var src = """ +System.ReadOnlySpan i = [""]; +_ = i is { Property: 42 }; +i.M(); -static class E1 -{ - extension(object) - { - public static int P => 42; - } -} +class C { } -static class E2 +static class E { - extension(object) + extension(System.ReadOnlySpan s) { - public static void P() => throw null; + public int Property + { + get { System.Console.Write("property "); return 42; } + } } + public static void M(this System.ReadOnlySpan s) { System.Console.Write("method"); } } """; - var comp = CreateCompilation(source); - comp.VerifyEmitDiagnostics( - // (1,16): error CS0428: Cannot convert method group 'P' to non-delegate type 'int'. Did you intend to invoke the method? - // int i = object.P; - Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "P").WithArguments("P", "int").WithLocation(1, 16)); - - var tree = comp.SyntaxTrees.First(); - var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "object.P"); - Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); - Assert.Equal(["void E2.<>E__0.P()"], model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + var verify = CompileAndVerify(comp, expectedOutput: ExpectedOutput("property method"), verify: Verification.Skipped).VerifyDiagnostics(); + verify.VerifyIL("", """ +{ + // Code size 36 (0x24) + .maxstack 2 + .locals init (string V_0) + IL_0000: ldstr "" + IL_0005: stloc.0 + IL_0006: ldloca.s V_0 + IL_0008: newobj "System.ReadOnlySpan..ctor(ref readonly string)" + IL_000d: dup + IL_000e: call "System.ReadOnlySpan System.ReadOnlySpan.CastUp(System.ReadOnlySpan)" + IL_0013: call "int E.get_Property(System.ReadOnlySpan)" + IL_0018: pop + IL_0019: call "System.ReadOnlySpan System.ReadOnlySpan.CastUp(System.ReadOnlySpan)" + IL_001e: call "void E.M(System.ReadOnlySpan)" + IL_0023: ret +} +"""); } [Fact] - public void StaticMethodAccess_NonZeroArity() + public void ExtensionMemberLookup_Patterns_Conversion_06() { - var source = """ -object.M(); + // implicit span conversion: string to ReadOnlySpan + var src = """ +string s = ""; +_ = s is { Property: 42 }; +s.M(); -static class E1 +class C { } + +static class E { - extension(object) + extension(System.ReadOnlySpan s) { - public static void M() { } - public static void M() { } + public int Property + { + get { System.Console.Write("property "); return 42; } + } } + public static void M(this System.ReadOnlySpan s) { System.Console.Write("method"); } } """; - var comp = CreateCompilation(source); - comp.VerifyEmitDiagnostics( - // (1,8): error CS0117: 'object' does not contain a definition for 'M' - // object.M(); - Diagnostic(ErrorCode.ERR_NoSuchMember, "M").WithArguments("object", "M").WithLocation(1, 8)); - - var tree = comp.SyntaxTrees.First(); - var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "object.M"); - Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); - Assert.Equal(["void E1.<>E__0.M()", "void E1.<>E__0.M()"], model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); - Assert.Equal(["void E1.<>E__0.M()", "void E1.<>E__0.M()"], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); - } - - [Fact] - public void AddressOf_TypeReceiver() - { - var src = """ -unsafe class C + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + var verify = CompileAndVerify(comp, expectedOutput: ExpectedOutput("property method"), verify: Verification.Skipped).VerifyDiagnostics(); + verify.VerifyIL("", """ +{ + // Code size 40 (0x28) + .maxstack 2 + .locals init (string V_0) //s + IL_0000: ldstr "" + IL_0005: stloc.0 + IL_0006: ldloc.0 + IL_0007: brfalse.s IL_001a + IL_0009: ldloc.0 + IL_000a: call "System.ReadOnlySpan System.MemoryExtensions.AsSpan(string)" + IL_000f: call "int E.get_Property(System.ReadOnlySpan)" + IL_0014: ldc.i4.s 42 + IL_0016: ceq + IL_0018: br.s IL_001b + IL_001a: ldc.i4.0 + IL_001b: pop + IL_001c: ldloc.0 + IL_001d: call "System.ReadOnlySpan System.MemoryExtensions.AsSpan(string)" + IL_0022: call "void E.M(System.ReadOnlySpan)" + IL_0027: ret +} +"""); + + var spanSrc = """ +namespace System; + +public readonly ref struct ReadOnlySpan { - static void Main() - { - delegate* ptr = &C.M; - ptr("ran", null); - } } +"""; + comp = CreateCompilation([src, spanSrc]); + comp.VerifyEmitDiagnostics( + // (2,12): error CS0656: Missing compiler required member 'System.MemoryExtensions.AsSpan' + // _ = s is { Property: 42 }; + Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "Property").WithArguments("System.MemoryExtensions", "AsSpan").WithLocation(2, 12), + // (3,1): error CS0656: Missing compiler required member 'System.MemoryExtensions.AsSpan' + // s.M(); + Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "s").WithArguments("System.MemoryExtensions", "AsSpan").WithLocation(3, 1)); + } + + [Fact] + public void ExtensionMemberLookup_Patterns_Conversion_07() + { + // boxing + var src = """ +int i = 42; +_ = i is { Property: 42 }; +i.M(); + +class C { } static class E { - extension(C) + extension(object o) { - public static void M(string s, object o) { System.Console.Write(s); } + public int Property + { + get { System.Console.Write("property "); return 42; } + } } + public static void M(this object o) { System.Console.Write("method"); } } """; - var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugExe); - comp.VerifyEmitDiagnostics(); - var verifier = CompileAndVerify(comp, expectedOutput: "ran", verify: Verification.Fails with { ILVerifyMessage = "[Main]: ImportCalli not implemented" }); - verifier.VerifyIL("C.Main", """ + var comp = CreateCompilation(src); + var verify = CompileAndVerify(comp, expectedOutput: "property method").VerifyDiagnostics(); + verify.VerifyIL("", """ { - // Code size 24 (0x18) - .maxstack 3 - .locals init (delegate* V_0, //ptr - delegate* V_1) - IL_0000: nop - IL_0001: ldftn "void E.M(string, object)" - IL_0007: stloc.0 - IL_0008: ldloc.0 - IL_0009: stloc.1 - IL_000a: ldstr "ran" - IL_000f: ldnull - IL_0010: ldloc.1 - IL_0011: calli "delegate*" - IL_0016: nop - IL_0017: ret + // Code size 25 (0x19) + .maxstack 2 + IL_0000: ldc.i4.s 42 + IL_0002: dup + IL_0003: box "int" + IL_0008: call "int E.get_Property(object)" + IL_000d: pop + IL_000e: box "int" + IL_0013: call "void E.M(object)" + IL_0018: ret } """); - - var tree = comp.SyntaxTrees.First(); - var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "C.M"); - Assert.Equal("void E.<>E__0.M(System.String s, System.Object o)", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); } [Fact] - public void AddressOf_InstanceReceiver() + public void ExtensionMemberLookup_Patterns_Conversion_08() { + // implicit tuple conversion var src = """ -unsafe class C -{ - static void Main() - { - C c = new C(); - delegate* ptr = &c.M; - ptr("ran", null); +(int, string) t = (42, ""); +_ = t is { Property: 42 }; +t.M(); - delegate* ptr2 = &c.M2; - } -} +class C { } static class E { - extension(C c) + extension((object, object) t) { - public void M(string s, object o) { System.Console.Write(s); } + public int Property + { + get { System.Console.Write("property "); return 42; } + } } - public static void M2(this C c, string s, object o) { System.Console.Write(s); } + public static void M(this (object, object) t) { System.Console.Write("method"); } } """; - var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugExe); - comp.VerifyEmitDiagnostics( - // (6,48): error CS8759: Cannot create a function pointer for 'E.extension(C).M(string, object)' because it is not a static method - // delegate* ptr = &c.M; - Diagnostic(ErrorCode.ERR_FuncPtrMethMustBeStatic, "c.M").WithArguments("E.extension(C).M(string, object)").WithLocation(6, 48), - // (9,48): error CS8788: Cannot use an extension method with a receiver as the target of a '&' operator. - // delegate* ptr2 = &c.M2; - Diagnostic(ErrorCode.ERR_CannotUseReducedExtensionMethodInAddressOf, "&c.M2").WithLocation(9, 48)); - - var tree = comp.SyntaxTrees.First(); - var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "c.M"); - Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + var verify = CompileAndVerify(comp, expectedOutput: ExpectedOutput("property method"), verify: Verification.Skipped).VerifyDiagnostics(); + verify.VerifyIL("", """ +{ + // Code size 71 (0x47) + .maxstack 3 + .locals init (System.ValueTuple V_0) + IL_0000: ldc.i4.s 42 + IL_0002: ldstr "" + IL_0007: newobj "System.ValueTuple..ctor(int, string)" + IL_000c: dup + IL_000d: stloc.0 + IL_000e: ldloc.0 + IL_000f: ldfld "int System.ValueTuple.Item1" + IL_0014: box "int" + IL_0019: ldloc.0 + IL_001a: ldfld "string System.ValueTuple.Item2" + IL_001f: newobj "System.ValueTuple..ctor(object, object)" + IL_0024: call "int E.get_Property(System.ValueTuple)" + IL_0029: pop + IL_002a: stloc.0 + IL_002b: ldloc.0 + IL_002c: ldfld "int System.ValueTuple.Item1" + IL_0031: box "int" + IL_0036: ldloc.0 + IL_0037: ldfld "string System.ValueTuple.Item2" + IL_003c: newobj "System.ValueTuple..ctor(object, object)" + IL_0041: call "void E.M(System.ValueTuple)" + IL_0046: ret +} +"""); } [Fact] - public void AddressOf_AmbiguousBestMethod() + public void ExtensionMemberLookup_Patterns_Conversion_09() { + // We check conversion during initial binding var src = """ -unsafe class C +int[] i = []; +_ = i is { Property: 42 }; + +static class E { - static void M1() + extension(System.ReadOnlySpan r) { - delegate* ptr = &C.M; + public int Property => throw null; } } -static class E +namespace System { - extension(C) + public ref struct ReadOnlySpan { - public static void M(string s, object o) {} - public static void M(object o, string s) {} } } """; - var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll); + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); comp.VerifyEmitDiagnostics( - // (5,48): error CS0121: The call is ambiguous between the following methods or properties: 'E.extension(C).M(string, object)' and 'E.extension(C).M(object, string)' - // delegate* ptr = &C.M; - Diagnostic(ErrorCode.ERR_AmbigCall, "C.M").WithArguments("E.extension(C).M(string, object)", "E.extension(C).M(object, string)").WithLocation(5, 48)); - - var tree = comp.SyntaxTrees.First(); - var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "C.M"); - Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); - Assert.Equal(["void E.<>E__0.M(System.String s, System.Object o)", "void E.<>E__0.M(System.Object o, System.String s)"], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); + // (2,12): error CS0656: Missing compiler required member 'ReadOnlySpan.op_Implicit' + // _ = i is { Property: 42 }; + Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "Property").WithArguments("System.ReadOnlySpan", "op_Implicit").WithLocation(2, 12), + // (6,22): warning CS0436: The type 'ReadOnlySpan' in '' conflicts with the imported type 'ReadOnlySpan' in 'System.Runtime, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Using the type defined in ''. + // extension(System.ReadOnlySpan r) + Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "ReadOnlySpan").WithArguments("", "System.ReadOnlySpan", "System.Runtime, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.ReadOnlySpan").WithLocation(6, 22)); } [Fact] - public void AddressOf_TypeReceiver_UnmanagedCallersOnly_01() + public void ExtensionMemberLookup_Patterns_ExtendedPropertyPattern() { var src = """ -unsafe class C +var c = new C(); + +_ = c is { Property.Property2: 43 }; + +class C { } + +static class E1 { - static void Main() + extension(C c) { - delegate* ptr = &C.M; - delegate* ptr2 = &E.M; + public int Property { get { System.Console.Write("property "); return 42; } } } } -static class E +static class E2 { - extension(C) + extension(int i) { - [System.Runtime.InteropServices.UnmanagedCallersOnly] - public static void M() { } + public int Property2 { get { System.Console.Write("property2"); return 43; } } } } """; - var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugExe, targetFramework: TargetFramework.Net90); - comp.VerifyEmitDiagnostics( - // (5,32): error CS8786: Calling convention of 'E.extension(C).M()' is not compatible with 'Default'. - // delegate* ptr = &C.M; - Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M").WithArguments("E.extension(C).M()", "Default").WithLocation(5, 32), - // (6,33): error CS8786: Calling convention of 'E.M()' is not compatible with 'Default'. - // delegate* ptr2 = &E.M; - Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "E.M").WithArguments("E.M()", "Default").WithLocation(6, 33)); + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "property property2").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var expressionColon = GetSyntax(tree, "Property.Property2:"); + Assert.Equal("System.Int32 E2.<>E__0.Property2 { get; }", model.GetSymbolInfo(expressionColon.Expression).Symbol.ToTestDisplayString()); } [Fact] - public void AddressOf_TypeReceiver_UnmanagedCallersOnly_02() + public void ExtensionMemberLookup_Patterns_ExtendedPropertyPattern_Conversion() { var src = """ -unsafe class C +var c = new C(); + +_ = c is { Property.Property2: 43 }; + +class C { } + +static class E1 { - static void Main() + extension(object o) { - delegate* unmanaged ptr = &C.M; - delegate* unmanaged ptr2 = &E.M; + public int Property { get { System.Console.Write("property "); return 42; } } } } -static class E +static class E2 { - extension(C) + extension(int i) { - [System.Runtime.InteropServices.UnmanagedCallersOnly] - public static void M() { } + public int Property2 { get { System.Console.Write("property2"); return 43; } } } } """; - var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugExe, targetFramework: TargetFramework.Net90); - comp.VerifyEmitDiagnostics(); + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "property property2").VerifyDiagnostics(); } [Fact] - public void TwoExtensions_MethodAndProperty() + public void ExtensionMemberLookup_Patterns_ExtendedPropertyPattern_Conversion_02() { var src = """ -System.Console.Write(object.M()); +var c = new C(); + +_ = c is { Property.Property2: 43 }; + +class C { } static class E1 { - extension(object) + extension(C c) { - public static string M() => throw null; + public C Property { get { System.Console.Write("property "); return c; } } } } static class E2 { - extension(object) + extension(object o) { - public static System.Func M => null; + public int Property2 { get { System.Console.Write("property2"); return 43; } } } } """; var comp = CreateCompilation(src); - - comp.VerifyEmitDiagnostics( - // (1,22): error CS9286: 'object' does not contain a definition for 'M' and no accessible extension member 'M' for receiver of type 'object' could be found (are you missing a using directive or an assembly reference?) - // System.Console.Write(object.M()); - Diagnostic(ErrorCode.ERR_ExtensionResolutionFailed, "object.M").WithArguments("object", "M").WithLocation(1, 22)); - - var tree = comp.SyntaxTrees.Single(); - var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "object.M"); - Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); - - Assert.Equal(["System.String E1.<>E__0.M()", "System.Func E2.<>E__0.M { get; }"], - model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); - - Assert.Empty(model.GetMemberGroup(memberAccess)); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : consider handling BoundBadExpression better + CompileAndVerify(comp, expectedOutput: "property property2").VerifyDiagnostics(); } [Fact] - public void Nameof_Static_Method() + public void ExtensionMemberLookup_Patterns_ListPattern_NoInstanceLength() { var src = """ -System.Console.Write(nameof(C.Method)); +System.Console.Write(new C() is ["hi"]); -class C { } +class C +{ + public string this[System.Index i] + { + get { System.Console.Write("indexer "); return "hi"; } + } +} static class E { - extension(C) + extension(C c) { - public static string Method() => throw null; + public int Length + { + get { System.Console.Write("length "); return 42; } + } } } """; - var comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics( - // (1,29): error CS8093: Extension method groups are not allowed as an argument to 'nameof'. - // System.Console.Write(nameof(C.Method)); - Diagnostic(ErrorCode.ERR_NameofExtensionMethod, "C.Method").WithLocation(1, 29)); - var tree = comp.SyntaxTrees.Single(); - var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "C.Method"); - Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); - Assert.Equal(["System.String E.<>E__0.Method()"], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net70); + comp.VerifyEmitDiagnostics( + // (1,33): error CS8985: List patterns may not be used for a value of type 'C'. No suitable 'Length' or 'Count' property was found. + // System.Console.Write(new C() is ["hi"]); + Diagnostic(ErrorCode.ERR_ListPatternRequiresLength, @"[""hi""]").WithArguments("C").WithLocation(1, 33) + ); } [Fact] - public void Nameof_Instance_Method() + public void ExtensionMemberLookup_ObjectInitializer() { - var src = """ -C c = null; -_ = nameof(c.Method); - -class C { } + var libSrc = """ +public class C { } -static class E +public static class E { extension(C c) { - public string Method() => throw null; + public int Property { set { System.Console.Write("property"); } } } } """; - var comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics( - // (2,12): error CS8093: Extension method groups are not allowed as an argument to 'nameof'. - // _ = nameof(c.Method); - Diagnostic(ErrorCode.ERR_NameofExtensionMethod, "c.Method").WithLocation(2, 12)); + var libRef = CreateCompilation(libSrc).EmitToImageReference(); - var tree = comp.SyntaxTrees.Single(); + var src = """ +_ = new C() { Property = 42 }; +"""; + + var comp = CreateCompilation(src, references: [libRef]); + CompileAndVerify(comp, expectedOutput: "property").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "c.Method"); - Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); + var assignment = GetSyntax(tree, "Property = 42"); + Assert.Equal("System.Int32 E.<>E__0.Property { set; }", model.GetSymbolInfo(assignment.Left).Symbol.ToTestDisplayString()); + + comp = CreateCompilation(src, references: [libRef], parseOptions: TestOptions.Regular13); + comp.VerifyEmitDiagnostics( + // (1,15): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = new C() { Property = 42 }; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "Property").WithArguments("extensions").WithLocation(1, 15)); + + comp = CreateCompilation(src, references: [libRef], parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp, expectedOutput: "property").VerifyDiagnostics(); } [Fact] - public void Nameof_Static_Property() + public void ExtensionMemberLookup_ObjectInitializer_Conversion_01() { var src = """ -System.Console.Write(nameof(C.Property)); +_ = new C() { Property = 42 }; class C { } static class E { - extension(C) + extension(object o) { - public static string Property => throw null; + public int Property { set { System.Console.Write("property"); } } } } """; - var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "Property").VerifyDiagnostics(); - var tree = comp.SyntaxTrees.Single(); - var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "C.Property"); - Assert.Equal("System.String E.<>E__0.Property { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "property").VerifyDiagnostics(); } [Fact] - public void Nameof_Static_WrongArityMethod() + public void ExtensionMemberLookup_ObjectInitializer_Conversion_02() { var src = """ -System.Console.Write(nameof(C.Method)); +_ = new System.ReadOnlySpan() { Property = 42 }; + +new System.ReadOnlySpan().Property = 43; class C { } static class E { - extension(C) + extension(System.ReadOnlySpan s) { - public static string Method() => throw null; + public int Property { set { } } } } """; - var comp = CreateCompilation(src); + + // Tracked by https://github.com/dotnet/roslyn/issues/76130 : consider adjusting receiver requirements for extension members + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); comp.VerifyEmitDiagnostics( - // (1,29): error CS8093: Extension method groups are not allowed as an argument to 'nameof'. - // System.Console.Write(nameof(C.Method)); - Diagnostic(ErrorCode.ERR_NameofExtensionMethod, "C.Method").WithLocation(1, 29)); + // (1,41): error CS0131: The left-hand side of an assignment must be a variable, property or indexer + // _ = new System.ReadOnlySpan() { Property = 42 }; + Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "Property").WithLocation(1, 41), + // (3,1): error CS0131: The left-hand side of an assignment must be a variable, property or indexer + // new System.ReadOnlySpan().Property = 43; + Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "new System.ReadOnlySpan().Property").WithLocation(3, 1)); - var tree = comp.SyntaxTrees.Single(); - var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "C.Method"); - Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); - Assert.Equal(["System.String E.<>E__0.Method()"], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); + src = """ +new S().Property = 42; + +struct S +{ + public int Property { set { } } +} +"""; + + comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (1,1): error CS0131: The left-hand side of an assignment must be a variable, property or indexer + // new S().Property = 42; + Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "new S().Property").WithLocation(1, 1)); } [Fact] - public void Nameof_Instance_Property() + public void ExtensionMemberLookup_ObjectInitializer_Conversion_03() { + // implicit tuple conversion var src = """ -C c = null; -System.Console.Write(nameof(c.Property)); - -class C { } +_ = new System.ValueTuple() { Property = 42 }; static class E { - extension(C c) + extension((object, object) t) { - public string Property => "Property"; + public int Property + { + set { System.Console.Write("property"); } + } } } """; var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "Property").VerifyDiagnostics(); - - var tree = comp.SyntaxTrees.Single(); - var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "c.Property"); - Assert.Equal("System.String E.<>E__0.Property { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); + comp.VerifyEmitDiagnostics( + // (1,44): error CS0131: The left-hand side of an assignment must be a variable, property or indexer + // _ = new System.ValueTuple() { Property = 42 }; + Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "Property").WithLocation(1, 44)); } - [Fact(Skip = "Assertion in NullableWalker.AsMemberOfType")] // Tracked by https://github.com/dotnet/roslyn/issues/78828 : Nullability analysis of properties - public void Nameof_Instance_Property_Generic_01() + [Fact] + public void ExtensionMemberLookup_ObjectInitializer_Conversion_04() { + // implicit span conversion from string var src = """ -I i = null; -System.Console.Write(nameof(i.Property)); - -interface I { } +_ = new System.String('a', 10) { Property = 42 }; static class E { - extension(I i) + extension(System.ReadOnlySpan s) { - public string Property => throw null; + public int Property + { + set { System.Console.Write(value); } + } } } """; - var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "Property").VerifyDiagnostics(); - - var tree = comp.SyntaxTrees.Single(); - var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "i.Property"); - Assert.Equal("System.String E.<>E__0.Property { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyDiagnostics( + // (1,34): error CS0131: The left-hand side of an assignment must be a variable, property or indexer + // _ = new System.String('a', 10) { Property = 42 }; + Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "Property").WithLocation(1, 34)); } [Fact] - public void Nameof_Static_Property_Generic_01() + public void ExtensionMemberLookup_With() { - var src = """ -System.Console.Write(nameof(C.Property)); - -class C : I { } -interface I { } + var libSrc = """ +public struct S { } -static class E +public static class E { - extension(I i) + extension(S s) { - public static string Property => throw null; + public int Property { set { System.Console.Write("property"); } } } } """; - var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "Property").VerifyDiagnostics(); - - var tree = comp.SyntaxTrees.Single(); - var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "C.Property"); - Assert.Equal("System.String E.<>E__0.Property { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); - } + var libRef = CreateCompilation(libSrc).EmitToImageReference(); - [Fact] - public void Nameof_Static_Property_Generic_02() - { var src = """ -System.Console.Write(nameof(C.Property)); +_ = new S() with { Property = 42 }; +"""; -class C : I, I { } -interface I { } + var comp = CreateCompilation(src, references: [libRef]); + CompileAndVerify(comp, expectedOutput: "property").VerifyDiagnostics(); -static class E -{ - extension(I i) - { - public static string Property => throw null; - } -} -"""; - var comp = CreateCompilation(src); + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var assignment = GetSyntax(tree, "Property = 42"); + Assert.Equal("System.Int32 E.<>E__0.Property { set; }", model.GetSymbolInfo(assignment.Left).Symbol.ToTestDisplayString()); + + comp = CreateCompilation(src, references: [libRef], parseOptions: TestOptions.Regular13); comp.VerifyEmitDiagnostics( - // (1,29): error CS9286: 'C' does not contain a definition for 'Property' and no accessible extension member 'Property' for receiver of type 'C' could be found (are you missing a using directive or an assembly reference?) - // System.Console.Write(nameof(C.Property)); - Diagnostic(ErrorCode.ERR_ExtensionResolutionFailed, "C.Property").WithArguments("C", "Property").WithLocation(1, 29)); + // (1,20): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = new S() with { Property = 42 }; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "Property").WithArguments("extensions").WithLocation(1, 20)); - var tree = comp.SyntaxTrees.Single(); - var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "C.Property"); - Assert.Equal("System.String E.<>E__0.Property { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); + comp = CreateCompilation(src, references: [libRef], parseOptions: TestOptions.RegularNext); + CompileAndVerify(comp, expectedOutput: "property").VerifyDiagnostics(); } [Fact] - public void Nameof_Static_Property_Generic_03() + public void ExtensionMemberLookup_CollectionInitializer() { var src = """ -System.Console.Write(nameof(I.Property)); +using System.Collections; +using System.Collections.Generic; -interface I { } +/**/ +_ = new C() { 42 }; +/**/ + +class C : IEnumerable, IEnumerable +{ + IEnumerator IEnumerable.GetEnumerator() => throw null; + IEnumerator IEnumerable.GetEnumerator() => throw null; +} static class E { - extension(I i) + extension(C c) { - public static string Property => throw null; + public void Add(int i) { System.Console.Write("add"); } } } """; + var comp = CreateCompilation(src); - CompileAndVerify(comp, expectedOutput: "Property").VerifyDiagnostics(); + CompileAndVerify(comp, expectedOutput: "add").VerifyDiagnostics(); - var tree = comp.SyntaxTrees.Single(); - var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "I.Property"); - Assert.Equal("System.String E.<>E__0.Property { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); + string expectedOperationTree = """ +ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: '_ = new C() { 42 }') +Left: + IDiscardOperation (Symbol: C _) (OperationKind.Discard, Type: C) (Syntax: '_') +Right: + IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C() { 42 }') + Arguments(0) + Initializer: + IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ 42 }') + Initializers(1): + IInvocationOperation ( void E.<>E__0.Add(System.Int32 i)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '42') + Instance Receiver: + IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'C') + Arguments(1): + IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '42') + ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') + InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) +"""; + var expectedDiagnostics = DiagnosticDescription.None; + + VerifyOperationTreeAndDiagnosticsForTest(src, expectedOperationTree, expectedDiagnostics); } [Fact] - public void Nameof_Overloads_01() + public void ExtensionMemberLookup_CollectionInitializer_Conversion() { var src = """ -System.Console.Write($"{nameof(object.M)} "); +using System.Collections; +using System.Collections.Generic; + +/**/ +_ = new C() { 42 }; +/**/ + +class C : IEnumerable, IEnumerable +{ + IEnumerator IEnumerable.GetEnumerator() => throw null; + IEnumerator IEnumerable.GetEnumerator() => throw null; +} static class E { - extension(object) + extension(object o) { - public static void M() { } - public static void M(int i) { } + public void Add(int i) { System.Console.Write("add"); } } } """; + var comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics( - // (1,32): error CS8093: Extension method groups are not allowed as an argument to 'nameof'. - // System.Console.Write($"{nameof(object.M)} "); - Diagnostic(ErrorCode.ERR_NameofExtensionMethod, "object.M").WithLocation(1, 32)); + CompileAndVerify(comp, expectedOutput: "add").VerifyDiagnostics(); + + string expectedOperationTree = """ +ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: '_ = new C() { 42 }') +Left: + IDiscardOperation (Symbol: C _) (OperationKind.Discard, Type: C) (Syntax: '_') +Right: + IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C() { 42 }') + Arguments(0) + Initializer: + IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ 42 }') + Initializers(1): + IInvocationOperation ( void E.<>E__0.Add(System.Int32 i)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '42') + Instance Receiver: + IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'C') + Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) + Operand: + IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'C') + Arguments(1): + IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '42') + ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') + InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) +"""; + var expectedDiagnostics = DiagnosticDescription.None; + + VerifyOperationTreeAndDiagnosticsForTest(src, expectedOperationTree, expectedDiagnostics); } [Fact] - public void Nameof_Overloads_02() + public void ExtensionMemberLookup_CollectionInitializer_NoApplicableMethod() { var src = """ -System.Console.Write($"{nameof(object.M)} "); +using System.Collections; +using System.Collections.Generic; -static class E1 +class Program { - extension(T) where T : class + static void Main() { - public static void M() { } + /**/ + _ = new C() { 42 }; + /**/ } } -static class E2 +class C : IEnumerable, IEnumerable { - extension(T) where T : struct + IEnumerator IEnumerable.GetEnumerator() => throw null; + IEnumerator IEnumerable.GetEnumerator() => throw null; + public void Add(string notApplicable) => throw null; +} + +static class E +{ + extension(object o) { - public static void M() { } + public void Add(int i) { System.Console.Write("add"); } } } """; - var comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics( - // (1,32): error CS8093: Extension method groups are not allowed as an argument to 'nameof'. - // System.Console.Write($"{nameof(object.M)} "); - Diagnostic(ErrorCode.ERR_NameofExtensionMethod, "object.M").WithLocation(1, 32)); - var tree = comp.SyntaxTrees.Single(); - var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "object.M"); - Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); - Assert.Equal(["void E1.<>E__0.M()"], model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); - Assert.Equal(["void E1.<>E__0.M()"], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "add").VerifyDiagnostics(); + + string expectedOperationTree = """ +ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: '_ = new C() { 42 }') + Left: + IDiscardOperation (Symbol: C _) (OperationKind.Discard, Type: C) (Syntax: '_') + Right: + IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C() { 42 }') + Arguments(0) + Initializer: + IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ 42 }') + Initializers(1): + IInvocationOperation ( void E.<>E__0.Add(System.Int32 i)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '42') + Instance Receiver: + IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'C') + Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) + Operand: + IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'C') + Arguments(1): + IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '42') + ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') + InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) +"""; + var expectedDiagnostics = DiagnosticDescription.None; + + VerifyOperationTreeAndDiagnosticsForTest(src, expectedOperationTree, expectedDiagnostics); + + VerifyFlowGraph(comp, comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType().First(), """ +Block[B0] - Entry + Statements (0) + Next (Regular) Block[B1] + Entering: {R1} +.locals {R1} +{ + CaptureIds: [0] + Block[B1] - Block + Predecessors: [B0] + Statements (3) + IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new C() { 42 }') + Value: + IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C() { 42 }') + Arguments(0) + Initializer: + null + IInvocationOperation ( void E.<>E__0.Add(System.Int32 i)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '42') + Instance Receiver: + IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'C') + Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) + (ImplicitReference) + Operand: + IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'new C() { 42 }') + Arguments(1): + IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '42') + ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') + InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = new C() { 42 };') + Expression: + ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: '_ = new C() { 42 }') + Left: + IDiscardOperation (Symbol: C _) (OperationKind.Discard, Type: C) (Syntax: '_') + Right: + IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'new C() { 42 }') + Next (Regular) Block[B2] + Leaving: {R1} +} +Block[B2] - Exit + Predecessors: [B1] + Statements (0) +"""); } [Fact] - public void Nameof_SimpleName() + public void ExtensionMemberLookup_CollectionInitializer_NoApplicableMethod_ExpressionTree() { var src = """ -class C +using System.Collections; +using System.Collections.Generic; + +try { - void M() + System.Linq.Expressions.Expression> e = () => new C() { 42 }; + System.Console.Write(e); +} +catch (System.ArgumentException ae) +{ + System.Console.Write(ae.Message); +} + +class C : IEnumerable, IEnumerable +{ + IEnumerator IEnumerable.GetEnumerator() => throw null; + IEnumerator IEnumerable.GetEnumerator() => throw null; + public void Add(string notApplicable) => throw null; +} + +static class E +{ + extension(object o) { - _ = nameof(Method); - _ = nameof(Property); + public void Add(int i) { System.Console.Write("add"); } } } +"""; + + // Tracked by https://github.com/dotnet/roslyn/issues/76130 : expression trees + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (6,76): error CS8075: An extension Add method is not supported for a collection initializer in an expression lambda. + // System.Linq.Expressions.Expression> e = () => new C() { 42 }; + Diagnostic(ErrorCode.ERR_ExtensionCollectionElementInitializerInExpressionTree, "42").WithLocation(6, 76) + ); + } + + [Fact] + public void ResolveAll_CollectionInitializer_DelegateTypeProperty() + { + var source = """ +using System.Collections; +using System.Collections.Generic; + +MyCollection c = new MyCollection() { 42 }; static class E { - extension(object) + extension(MyCollection c) { - public static void Method() { } - public static int Property => 0; + public System.Action Add => (int i) => { }; } } + +public class MyCollection : IEnumerable +{ + IEnumerator IEnumerable.GetEnumerator() => throw null; + IEnumerator IEnumerable.GetEnumerator() => throw null; +} """; - var comp = CreateCompilation(src); - comp.VerifyDiagnostics( - // (5,20): error CS0103: The name 'Method' does not exist in the current context - // _ = nameof(Method); - Diagnostic(ErrorCode.ERR_NameNotInContext, "Method").WithArguments("Method").WithLocation(5, 20), - // (6,20): error CS0103: The name 'Property' does not exist in the current context - // _ = nameof(Property); - Diagnostic(ErrorCode.ERR_NameNotInContext, "Property").WithArguments("Property").WithLocation(6, 20)); + var comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (4,39): error CS1061: 'MyCollection' does not contain a definition for 'Add' and no accessible extension method 'Add' accepting a first argument of type 'MyCollection' could be found (are you missing a using directive or an assembly reference?) + // MyCollection c = new MyCollection() { 42 }; + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "42").WithArguments("MyCollection", "Add").WithLocation(4, 39)); + + source = """ +using System.Collections; +using System.Collections.Generic; + +MyCollection c = new MyCollection() { 42 }; + +public class MyCollection : IEnumerable +{ + IEnumerator IEnumerable.GetEnumerator() => throw null; + IEnumerator IEnumerable.GetEnumerator() => throw null; + public System.Action Add => (int i) => { }; +} +"""; + comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (4,39): error CS0118: 'Add' is a property but is used like a method + // MyCollection c = new MyCollection() { 42 }; + Diagnostic(ErrorCode.ERR_BadSKknown, "42").WithArguments("Add", "property", "method").WithLocation(4, 39)); } [Fact] - public void Nameof_NoParameter() + public void ResolveAll_CollectionInitializer_DynamicTypeProperty() { - var src = """ -class C + var source = """ +using System.Collections; +using System.Collections.Generic; + +MyCollection c = new MyCollection() { 42 }; + +static class E { - void M() + extension(MyCollection c) { - System.Console.Write(nameof()); + public dynamic Add => throw null; } } +public class MyCollection : IEnumerable +{ + IEnumerator IEnumerable.GetEnumerator() => throw null; + IEnumerator IEnumerable.GetEnumerator() => throw null; +} +"""; + var comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (4,39): error CS1061: 'MyCollection' does not contain a definition for 'Add' and no accessible extension method 'Add' accepting a first argument of type 'MyCollection' could be found (are you missing a using directive or an assembly reference?) + // MyCollection c = new MyCollection() { 42 }; + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "42").WithArguments("MyCollection", "Add").WithLocation(4, 39)); + + source = """ +using System.Collections; +using System.Collections.Generic; + +MyCollection c = new MyCollection() { 42 }; + +public class MyCollection : IEnumerable +{ + IEnumerator IEnumerable.GetEnumerator() => throw null; + IEnumerator IEnumerable.GetEnumerator() => throw null; + public dynamic Add => throw null; +} +"""; + comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (4,39): error CS0118: 'Add' is a property but is used like a method + // MyCollection c = new MyCollection() { 42 }; + Diagnostic(ErrorCode.ERR_BadSKknown, "42").WithArguments("Add", "property", "method").WithLocation(4, 39)); + } + + [Fact] + public void ExtensionMemberLookup_Query_NoMethod() + { + var src = """ +/**/ +string query = from x in new C() select x; +/**/ + +System.Console.Write(query); + +class C { } + static class E { extension(C c) { - public string nameof() => throw null; + public string Select(System.Func selector) => "hello"; } } """; var comp = CreateCompilation(src); - comp.VerifyDiagnostics( - // (5,30): error CS0103: The name 'nameof' does not exist in the current context - // System.Console.Write(nameof()); - Diagnostic(ErrorCode.ERR_NameNotInContext, "nameof").WithArguments("nameof").WithLocation(5, 30)); + CompileAndVerify(comp, expectedOutput: "hello").VerifyDiagnostics(); + + string expectedOperationTree = """ +IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'string quer ... ) select x;') + IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'string quer ... () select x') + Declarators: + IVariableDeclaratorOperation (Symbol: System.String query) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'query = fro ... () select x') + Initializer: + IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= from x in ... () select x') + ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.String) (Syntax: 'from x in n ... () select x') + Expression: + IInvocationOperation ( System.String E.<>E__0.Select(System.Func selector)) (OperationKind.Invocation, Type: System.String, IsImplicit) (Syntax: 'select x') + Instance Receiver: + IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') + Arguments(0) + Initializer: + null + Arguments(1): + IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x') + IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func, IsImplicit) (Syntax: 'x') + Target: + IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x') + IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x') + IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x') + ReturnedValue: + IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C) (Syntax: 'x') + InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + Initializer: + null +"""; + + VerifyOperationTreeAndDiagnosticsForTest(src, expectedOperationTree, DiagnosticDescription.None); } [Fact] - public void Nameof_SingleParameter() + public void ExtensionMemberLookup_Query_NoApplicableMethod() { var src = """ +/**/ +string query = from x in new C() select x; +/**/ + +System.Console.Write(query); + class C { - public static void Main() - { - string x = ""; - System.Console.Write(nameof(x)); - } + public string Select(int notApplicable) => throw null; // not applicable } static class E { extension(C c) { - public string nameof(string s) => throw null; + public string Select(System.Func selector) => "hello"; } } """; - var comp = CreateCompilation(src, options: TestOptions.DebugExe); - CompileAndVerify(comp, expectedOutput: "x").VerifyDiagnostics(); + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "hello").VerifyDiagnostics(); + + // Tracked by https://github.com/dotnet/roslyn/issues/76130 : verify IOperation } [Fact] - public void StaticMethodInvocation_TypeParameter_InNameof() - { - var source = """ -public static class C -{ - static void M() + public void ExtensionMemberLookup_Invocation_ZeroArityMatchesAny() { - _ = nameof(T.Method); - } + var source = $$""" +object.Method(""); +object.Method(""); - extension(T) +static class E +{ + extension(object) { - public static void Method() { } + public static void Method(int i) => throw null; + public static void Method(T t) { System.Console.Write("Method "); } + public static void Method(T1 t1, T2 t2) => throw null; } } """; var comp = CreateCompilation(source); - comp.VerifyDiagnostics( - // 0.cs(5,20): error CS0704: Cannot do non-virtual member lookup in 'T' because it is a type parameter - // _ = nameof(T.Method); - Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T").WithArguments("T").WithLocation(5, 20)); + CompileAndVerify(comp, expectedOutput: "Method Method").VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "T.Method"); - Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); - Assert.Empty(model.GetMemberGroup(memberAccess)); + var invocation = GetSyntax(tree, """object.Method("")"""); + Assert.Equal("void E.<>E__0.Method(System.String t)", model.GetSymbolInfo(invocation).Symbol.ToTestDisplayString()); + Assert.Empty(model.GetMemberGroup(invocation)); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : need to fix the semantic model } [Fact] - public void SymbolInfoForMethodGroup03() + public void StaticPropertyAccess_ZeroArityMatchesAny() { var source = """ -public class A { } +int i = object.P; -static class E +static class E1 { - extension(A a) + extension(object) { - public string Extension() { return null; } + public static int P => 42; } } -public class Program + +static class E2 { - public static void Main(string[] args) + extension(object) { - A a = null; - _ = nameof(a.Extension); + public static void P() => throw null; } } """; var comp = CreateCompilation(source); - comp.VerifyDiagnostics( - // (15,20): error CS8093: Extension method groups are not allowed as an argument to 'nameof'. - // _ = nameof(a.Extension); - Diagnostic(ErrorCode.ERR_NameofExtensionMethod, "a.Extension").WithLocation(15, 20)); + comp.VerifyEmitDiagnostics( + // (1,9): error CS9286: 'object' does not contain a definition for 'P' and no accessible extension member 'P' for receiver of type 'object' could be found (are you missing a using directive or an assembly reference?) + // int i = object.P; + Diagnostic(ErrorCode.ERR_ExtensionResolutionFailed, "object.P").WithArguments("object", "P").WithLocation(1, 9)); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); - var memberAccess = GetSyntax(tree, "a.Extension"); + var memberAccess = GetSyntax(tree, "object.P"); Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Assert.Empty(model.GetMemberGroup(memberAccess)); + Assert.Equal(["System.Int32 E1.<>E__0.P { get; }", "void E2.<>E__0.P()"], model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); } [Fact] - public void StaticMethodInvocation_PartialStaticClass() + public void StaticPropertyAccess_NonZeroArity() { var source = """ -object.M(); -object.M2(); +int i = object.P; -public static partial class C +static class E1 { extension(object) { - public static void M() { System.Console.Write("ran "); } + public static int P => 42; } } -public static partial class C +static class E2 { extension(object) { - public static void M2() { System.Console.Write("ran2"); } + public static void P() => throw null; } } """; var comp = CreateCompilation(source); - CompileAndVerify(comp, expectedOutput: "ran ran2").VerifyDiagnostics(); + comp.VerifyEmitDiagnostics( + // (1,16): error CS0428: Cannot convert method group 'P' to non-delegate type 'int'. Did you intend to invoke the method? + // int i = object.P; + Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "P").WithArguments("P", "int").WithLocation(1, 16)); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "object.P"); + Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); + Assert.Equal(["void E2.<>E__0.P()"], model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); } [Fact] - public void StaticMethodInvocation_TupleTypeReceiver() + public void StaticMethodAccess_NonZeroArity() { - var src = """ -(string, string).M(); -(int a, int b).M(); -"""; - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : consider parsing this - var comp = CreateCompilation(src); - comp.VerifyDiagnostics( - // (1,2): error CS1525: Invalid expression term 'string' - // (string, string).M(); - Diagnostic(ErrorCode.ERR_InvalidExprTerm, "string").WithArguments("string").WithLocation(1, 2), - // (1,10): error CS1525: Invalid expression term 'string' - // (string, string).M(); - Diagnostic(ErrorCode.ERR_InvalidExprTerm, "string").WithArguments("string").WithLocation(1, 10), - // (2,2): error CS8185: A declaration is not allowed in this context. - // (int a, int b).M(); - Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int a").WithLocation(2, 2), - // (2,2): error CS0165: Use of unassigned local variable 'a' - // (int a, int b).M(); - Diagnostic(ErrorCode.ERR_UseDefViolation, "int a").WithArguments("a").WithLocation(2, 2), - // (2,9): error CS8185: A declaration is not allowed in this context. - // (int a, int b).M(); - Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int b").WithLocation(2, 9), - // (2,9): error CS0165: Use of unassigned local variable 'b' - // (int a, int b).M(); - Diagnostic(ErrorCode.ERR_UseDefViolation, "int b").WithArguments("b").WithLocation(2, 9), - // (2,16): error CS1061: '(int a, int b)' does not contain a definition for 'M' and no accessible extension method 'M' accepting a first argument of type '(int a, int b)' could be found (are you missing a using directive or an assembly reference?) - // (int a, int b).M(); - Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M").WithArguments("(int a, int b)", "M").WithLocation(2, 16)); - } + var source = """ +object.M(); - [Fact] - public void StaticMethodInvocation_TupleTypeReceiver_02() +static class E1 +{ + extension(object) { - var src = """ -((string, string)).M(); -((int a, int b)).M(); + public static void M() { } + public static void M() { } + } +} """; - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : consider parsing this - var comp = CreateCompilation(src); - comp.VerifyDiagnostics( - // (1,3): error CS1525: Invalid expression term 'string' - // ((string, string)).M(); - Diagnostic(ErrorCode.ERR_InvalidExprTerm, "string").WithArguments("string").WithLocation(1, 3), - // (1,11): error CS1525: Invalid expression term 'string' - // ((string, string)).M(); - Diagnostic(ErrorCode.ERR_InvalidExprTerm, "string").WithArguments("string").WithLocation(1, 11), - // (2,3): error CS8185: A declaration is not allowed in this context. - // ((int a, int b)).M(); - Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int a").WithLocation(2, 3), - // (2,3): error CS0165: Use of unassigned local variable 'a' - // ((int a, int b)).M(); - Diagnostic(ErrorCode.ERR_UseDefViolation, "int a").WithArguments("a").WithLocation(2, 3), - // (2,10): error CS8185: A declaration is not allowed in this context. - // ((int a, int b)).M(); - Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int b").WithLocation(2, 10), - // (2,10): error CS0165: Use of unassigned local variable 'b' - // ((int a, int b)).M(); - Diagnostic(ErrorCode.ERR_UseDefViolation, "int b").WithArguments("b").WithLocation(2, 10), - // (2,18): error CS1061: '(int a, int b)' does not contain a definition for 'M' and no accessible extension method 'M' accepting a first argument of type '(int a, int b)' could be found (are you missing a using directive or an assembly reference?) - // ((int a, int b)).M(); - Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M").WithArguments("(int a, int b)", "M").WithLocation(2, 18)); + var comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (1,8): error CS0117: 'object' does not contain a definition for 'M' + // object.M(); + Diagnostic(ErrorCode.ERR_NoSuchMember, "M").WithArguments("object", "M").WithLocation(1, 8)); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "object.M"); + Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); + Assert.Equal(["void E1.<>E__0.M()", "void E1.<>E__0.M()"], model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); + Assert.Equal(["void E1.<>E__0.M()", "void E1.<>E__0.M()"], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); } [Fact] - public void StaticMethodInvocation_PointerTypeReceiver() + public void AddressOf_TypeReceiver() { var src = """ unsafe class C { - void M() + static void Main() { - int*.M(); - delegate*.M(); + delegate* ptr = &C.M; + ptr("ran", null); + } +} + +static class E +{ + extension(C) + { + public static void M(string s, object o) { System.Console.Write(s); } } } """; - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : consider parsing this - var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll); - comp.VerifyDiagnostics( - // (5,13): error CS1001: Identifier expected - // int*.M(); - Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(5, 13), - // (5,13): error CS1003: Syntax error, ',' expected - // int*.M(); - Diagnostic(ErrorCode.ERR_SyntaxError, ".").WithArguments(",").WithLocation(5, 13), - // (5,14): error CS1002: ; expected - // int*.M(); - Diagnostic(ErrorCode.ERR_SemicolonExpected, "M").WithLocation(5, 14), - // (6,17): error CS1514: { expected - // delegate*.M(); - Diagnostic(ErrorCode.ERR_LbraceExpected, "*").WithLocation(6, 17), - // (6,17): warning CS8848: Operator '*' cannot be used here due to precedence. Use parentheses to disambiguate. - // delegate*.M(); - Diagnostic(ErrorCode.WRN_PrecedenceInversion, "*").WithArguments("*").WithLocation(6, 17), - // (6,18): error CS1525: Invalid expression term '<' - // delegate*.M(); - Diagnostic(ErrorCode.ERR_InvalidExprTerm, "<").WithArguments("<").WithLocation(6, 18), - // (6,19): error CS1525: Invalid expression term 'void' - // delegate*.M(); - Diagnostic(ErrorCode.ERR_InvalidExprTerm, "void").WithArguments("void").WithLocation(6, 19), - // (6,24): error CS1525: Invalid expression term '.' - // delegate*.M(); - Diagnostic(ErrorCode.ERR_InvalidExprTerm, ".").WithArguments(".").WithLocation(6, 24)); + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugExe); + comp.VerifyEmitDiagnostics(); + var verifier = CompileAndVerify(comp, expectedOutput: "ran", verify: Verification.Fails with { ILVerifyMessage = "[Main]: ImportCalli not implemented" }); + verifier.VerifyIL("C.Main", """ +{ + // Code size 24 (0x18) + .maxstack 3 + .locals init (delegate* V_0, //ptr + delegate* V_1) + IL_0000: nop + IL_0001: ldftn "void E.M(string, object)" + IL_0007: stloc.0 + IL_0008: ldloc.0 + IL_0009: stloc.1 + IL_000a: ldstr "ran" + IL_000f: ldnull + IL_0010: ldloc.1 + IL_0011: calli "delegate*" + IL_0016: nop + IL_0017: ret +} +"""); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "C.M"); + Assert.Equal("void E.<>E__0.M(System.String s, System.Object o)", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); } [Fact] - public void StaticMethodInvocation_DynamicTypeReceiver() + public void AddressOf_InstanceReceiver() { var src = """ -dynamic.M(); -"""; - var comp = CreateCompilation(src); - comp.VerifyDiagnostics( - // (1,1): error CS0103: The name 'dynamic' does not exist in the current context - // dynamic.M(); - Diagnostic(ErrorCode.ERR_NameNotInContext, "dynamic").WithArguments("dynamic").WithLocation(1, 1)); +unsafe class C +{ + static void Main() + { + C c = new C(); + delegate* ptr = &c.M; + ptr("ran", null); + + delegate* ptr2 = &c.M2; } +} - [Fact] - public void DisplayString_Constraint() - { - var source = """ static class E { - extension(T) where T : struct + extension(C c) { + public void M(string s, object o) { System.Console.Write(s); } } + public static void M2(this C c, string s, object o) { System.Console.Write(s); } } """; - var comp = CreateCompilation(source); - comp.VerifyDiagnostics(); + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugExe); + comp.VerifyEmitDiagnostics( + // (6,48): error CS8759: Cannot create a function pointer for 'E.extension(C).M(string, object)' because it is not a static method + // delegate* ptr = &c.M; + Diagnostic(ErrorCode.ERR_FuncPtrMethMustBeStatic, "c.M").WithArguments("E.extension(C).M(string, object)").WithLocation(6, 48), + // (9,48): error CS8788: Cannot use an extension method with a receiver as the target of a '&' operator. + // delegate* ptr2 = &c.M2; + Diagnostic(ErrorCode.ERR_CannotUseReducedExtensionMethodInAddressOf, "&c.M2").WithLocation(9, 48)); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); - var extension = tree.GetRoot().DescendantNodes().OfType().Single(); - var symbol = model.GetDeclaredSymbol(extension); - - var format = new SymbolDisplayFormat(genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints); - Assert.Equal("extension(T) where T : struct", symbol.ToDisplayString(format)); + var memberAccess = GetSyntax(tree, "c.M"); + Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); } [Fact] - public void DisplayString_Modifier() + public void AddressOf_AmbiguousBestMethod() { - var source = """ + var src = """ +unsafe class C +{ + static void M1() + { + delegate* ptr = &C.M; + } +} + static class E { - extension(ref readonly int i) + extension(C) { + public static void M(string s, object o) {} + public static void M(object o, string s) {} } } """; - var comp = CreateCompilation(source); - comp.VerifyDiagnostics(); + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll); + comp.VerifyEmitDiagnostics( + // (5,48): error CS0121: The call is ambiguous between the following methods or properties: 'E.extension(C).M(string, object)' and 'E.extension(C).M(object, string)' + // delegate* ptr = &C.M; + Diagnostic(ErrorCode.ERR_AmbigCall, "C.M").WithArguments("E.extension(C).M(string, object)", "E.extension(C).M(object, string)").WithLocation(5, 48)); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); - var extension = tree.GetRoot().DescendantNodes().OfType().Single(); - var symbol = model.GetDeclaredSymbol(extension); - - var format = new SymbolDisplayFormat(parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeModifiers); - Assert.Equal("extension(ref readonly Int32)", symbol.ToDisplayString(format)); + var memberAccess = GetSyntax(tree, "C.M"); + Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); + Assert.Equal(["void E.<>E__0.M(System.String s, System.Object o)", "void E.<>E__0.M(System.Object o, System.String s)"], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); } [Fact] - public void NameConflict_01_EnclosingStaticTypeNameWithExtensionTypeParameterName() + public void AddressOf_TypeReceiver_UnmanagedCallersOnly_01() { var src = """ -static class Extensions +unsafe class C { - extension(Extensions) + static void Main() + { + delegate* ptr = &C.M; + delegate* ptr2 = &E.M; + } +} + +static class E +{ + extension(C) { + [System.Runtime.InteropServices.UnmanagedCallersOnly] + public static void M() { } } } """; - var comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics(); + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugExe, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (5,32): error CS8786: Calling convention of 'E.extension(C).M()' is not compatible with 'Default'. + // delegate* ptr = &C.M; + Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M").WithArguments("E.extension(C).M()", "Default").WithLocation(5, 32), + // (6,33): error CS8786: Calling convention of 'E.M()' is not compatible with 'Default'. + // delegate* ptr2 = &E.M; + Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "E.M").WithArguments("E.M()", "Default").WithLocation(6, 33)); } [Fact] - public void NameConflict_02_EnclosingStaticTypeNameWithReceiverParameterName() + public void AddressOf_TypeReceiver_UnmanagedCallersOnly_02() { var src = """ -static class Extensions +unsafe class C { - extension(int Extensions) + static void Main() + { + delegate* unmanaged ptr = &C.M; + delegate* unmanaged ptr2 = &E.M; + } +} + +static class E +{ + extension(C) { + [System.Runtime.InteropServices.UnmanagedCallersOnly] + public static void M() { } } } """; - var comp = CreateCompilation(src); + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugExe, targetFramework: TargetFramework.Net90); comp.VerifyEmitDiagnostics(); } [Fact] - public void NameConflict_03_ExtensionTypeParameterNameWithReceiverParameterName() + public void TwoExtensions_MethodAndProperty() { var src = """ -static class Extensions +System.Console.Write(object.M()); + +static class E1 { -#line 7 - extension(T[] T) + extension(object) { - void M1(){} + public static string M() => throw null; + } +} + +static class E2 +{ + extension(object) + { + public static System.Func M => null; } } """; var comp = CreateCompilation(src); - comp.VerifyDiagnostics( - // (7,22): error CS9287: 'T': a receiver parameter cannot have the same name as an extension container type parameter - // extension(T[] T) - Diagnostic(ErrorCode.ERR_ReceiverParameterSameNameAsTypeParameter, "T").WithArguments("T").WithLocation(7, 22) - ); + comp.VerifyEmitDiagnostics( + // (1,22): error CS9286: 'object' does not contain a definition for 'M' and no accessible extension member 'M' for receiver of type 'object' could be found (are you missing a using directive or an assembly reference?) + // System.Console.Write(object.M()); + Diagnostic(ErrorCode.ERR_ExtensionResolutionFailed, "object.M").WithArguments("object", "M").WithLocation(1, 22)); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "object.M"); + Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); + + Assert.Equal(["System.String E1.<>E__0.M()", "System.Func E2.<>E__0.M { get; }"], + model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); + + Assert.Empty(model.GetMemberGroup(memberAccess)); // Tracked by https://github.com/dotnet/roslyn/issues/78957 : public API, consider handling BoundBadExpression better } [Fact] - public void NameConflict_04_ExtensionTypeParameterNameWithMemberParameterName() + public void Nameof_Static_Method() { var src = """ -static class Extensions +System.Console.Write(nameof(C.Method)); + +class C { } + +static class E { - extension(T[] p) + extension(C) { -#line 14 - void M2(int T){} - static void M3(int T){} - int this[int T] => 0; + public static string Method() => throw null; } } """; var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (1,29): error CS8093: Extension method groups are not allowed as an argument to 'nameof'. + // System.Console.Write(nameof(C.Method)); + Diagnostic(ErrorCode.ERR_NameofExtensionMethod, "C.Method").WithLocation(1, 29)); - comp.VerifyDiagnostics( - // (14,21): error CS9288: 'T': a parameter, local variable, or local function cannot have the same name as an extension container type parameter - // void M2(int T){} - Diagnostic(ErrorCode.ERR_LocalSameNameAsExtensionTypeParameter, "T").WithArguments("T").WithLocation(14, 21), - // (15,28): error CS9288: 'T': a parameter, local variable, or local function cannot have the same name as an extension container type parameter - // static void M3(int T){} - Diagnostic(ErrorCode.ERR_LocalSameNameAsExtensionTypeParameter, "T").WithArguments("T").WithLocation(15, 28), - // (16,13): error CS9282: This member is not allowed in an extension block - // int this[int T] => 0; - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(16, 13), - // (16,22): error CS9288: 'T': a parameter, local variable, or local function cannot have the same name as an extension container type parameter - // int this[int T] => 0; - Diagnostic(ErrorCode.ERR_LocalSameNameAsExtensionTypeParameter, "T").WithArguments("T").WithLocation(16, 22) - ); + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "C.Method"); + Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); + Assert.Equal(["System.String E.<>E__0.Method()"], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); } - [Theory] - [CombinatorialData] - public void NameConflict_05_ExtensionTypeParameterNameWithSetterValueParameter(bool isStatic) + [Fact] + public void Nameof_Instance_Method() { - var src = @" -static class Extensions + var src = """ +C c = null; +_ = nameof(c.Method); + +class C { } + +static class E { - extension(value[] p) + extension(C c) { - " + (isStatic ? "static" : "") + @" - int P11 {set{}} - - " + (isStatic ? "static" : "") + @" - int P12 => 0; + public string Method() => throw null; } } -"; +"""; var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (2,12): error CS8093: Extension method groups are not allowed as an argument to 'nameof'. + // _ = nameof(c.Method); + Diagnostic(ErrorCode.ERR_NameofExtensionMethod, "c.Method").WithLocation(2, 12)); - comp.VerifyDiagnostics( - // (4,15): warning CS8981: The type name 'value' only contains lower-cased ascii characters. Such names may become reserved for the language. - // extension(value[] p) - Diagnostic(ErrorCode.WRN_LowerCaseTypeName, "value").WithArguments("value").WithLocation(4, 15), - // (7,18): error CS9294: 'value': an automatically-generated parameter name conflicts with an extension type parameter name - // int P11 {set{}} - Diagnostic(ErrorCode.ERR_ValueParameterSameNameAsExtensionTypeParameter, "set").WithLocation(7, 18) - ); + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "c.Method"); + Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); } [Fact] - public void NameConflict_06_ExtensionTypeParameterNameWithSetterValueParameter() + public void Nameof_Static_Property() { - var src = @" -static class Extensions + var src = """ +System.Console.Write(nameof(C.Property)); + +class C { } + +static class E { - extension(value[] p) + extension(C) { - int this[int i] {set{}} - int this[long i] => 0; + public static string Property => throw null; } } -"; +"""; var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (1,29): error CS9316: Extension members are not allowed as an argument to 'nameof'. + // System.Console.Write(nameof(C.Property)); + Diagnostic(ErrorCode.ERR_NameofExtensionMember, "C.Property").WithLocation(1, 29)); - comp.VerifyDiagnostics( - // (4,15): warning CS8981: The type name 'value' only contains lower-cased ascii characters. Such names may become reserved for the language. - // extension(value[] p) - Diagnostic(ErrorCode.WRN_LowerCaseTypeName, "value").WithArguments("value").WithLocation(4, 15), - // (6,13): error CS9282: This member is not allowed in an extension block - // int this[int i] {set{}} - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(6, 13), - // (6,26): error CS9294: 'value': an automatically-generated parameter name conflicts with an extension type parameter name - // int this[int i] {set{}} - Diagnostic(ErrorCode.ERR_ValueParameterSameNameAsExtensionTypeParameter, "set").WithLocation(6, 26), - // (7,13): error CS9282: This member is not allowed in an extension block - // int this[long i] => 0; - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(7, 13) - ); + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "C.Property"); + Assert.Equal("System.String E.<>E__0.Property { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); } - [Theory] - [CombinatorialData] - public void NameConflict_07_ExtensionTypeParameterNameWithLocalFunctionParameterName(bool isStatic1, bool isStatic2) + [Fact] + public void Nameof_Static_WrongArityMethod() { - var modifier1 = isStatic1 ? "static " : ""; - var modifier2 = isStatic2 ? "static " : ""; + var src = """ +System.Console.Write(nameof(C.Method)); - var src = @" -#pragma warning disable CS8321 // The local function 'local' is declared but never used +class C { } -static class Extensions +static class E { - extension(T[] p) + extension(C) { - " + modifier1 + @"void M4() - { - " + modifier2 + @"int local(int T) - { - return T; - } - } - " + modifier1 + @"int P7 - { - set - { - " + modifier2 + @"int local(int T) - { - return T; - } - } - } + public static string Method() => throw null; } } -"; +"""; var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (1,29): error CS8093: Extension method groups are not allowed as an argument to 'nameof'. + // System.Console.Write(nameof(C.Method)); + Diagnostic(ErrorCode.ERR_NameofExtensionMethod, "C.Method").WithLocation(1, 29)); - comp.VerifyEmitDiagnostics(); + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "C.Method"); + Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); + Assert.Equal(["System.String E.<>E__0.Method()"], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); } - [Theory] - [CombinatorialData] - public void NameConflict_08_ExtensionTypeParameterNameWithLambdaParameterName(bool isStatic1, bool isStatic2) + [Fact] + public void Nameof_Instance_Property_01() { - var modifier1 = isStatic1 ? "static " : ""; - var modifier2 = isStatic2 ? "static " : ""; + var src = """ +C c = null; +System.Console.Write(nameof(c.Property)); - var src = @" -static class Extensions +class C { } + +static class E { - extension(T[] p) + extension(C c) { - " + modifier1 + @"void M4() - { - System.Func l = " + modifier2 + @"(int T) => - { - return T; - }; - } + public string Property => "Property"; + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (2,29): error CS9316: Extension members are not allowed as an argument to 'nameof'. + // System.Console.Write(nameof(c.Property)); + Diagnostic(ErrorCode.ERR_NameofExtensionMember, "c.Property").WithLocation(2, 29)); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "c.Property"); + Assert.Equal("System.String E.<>E__0.Property { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); + } + + [Fact] + public void Nameof_Instance_Property_02() + { + var src = """ +C c = null; +System.Console.Write(nameof(c.Property.Property)); // 1 +System.Console.Write(nameof(c.Property.ToString)); + +class C { } + +static class E +{ + extension(C c) + { + public C Property => throw null; + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (2,29): error CS9316: Extension members are not allowed as an argument to 'nameof'. + // System.Console.Write(nameof(c.Property.Property)); // 1 + Diagnostic(ErrorCode.ERR_NameofExtensionMember, "c.Property.Property").WithLocation(2, 29)); + } + + [Fact(Skip = "Assertion in NullableWalker.AsMemberOfType")] // Tracked by https://github.com/dotnet/roslyn/issues/78828 : Nullability analysis of properties + public void Nameof_Instance_Property_Generic_01() + { + var src = """ +I i = null; +System.Console.Write(nameof(i.Property)); + +interface I { } + +static class E +{ + extension(I i) + { + public string Property => throw null; + } +} +"""; + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "Property").VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "i.Property"); + Assert.Equal("System.String E.<>E__0.Property { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); + } + + [Fact] + public void Nameof_Static_Property_Generic_01() + { + var src = """ +System.Console.Write(nameof(C.Property)); + +class C : I { } +interface I { } + +static class E +{ + extension(I i) + { + public static string Property => throw null; + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (1,29): error CS9316: Extension members are not allowed as an argument to 'nameof'. + // System.Console.Write(nameof(C.Property)); + Diagnostic(ErrorCode.ERR_NameofExtensionMember, "C.Property").WithLocation(1, 29)); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "C.Property"); + Assert.Equal("System.String E.<>E__0.Property { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); + } + + [Fact] + public void Nameof_Static_Property_Generic_02() + { + var src = """ +System.Console.Write(nameof(C.Property)); + +class C : I, I { } +interface I { } + +static class E +{ + extension(I i) + { + public static string Property => throw null; + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (1,29): error CS9286: 'C' does not contain a definition for 'Property' and no accessible extension member 'Property' for receiver of type 'C' could be found (are you missing a using directive or an assembly reference?) + // System.Console.Write(nameof(C.Property)); + Diagnostic(ErrorCode.ERR_ExtensionResolutionFailed, "C.Property").WithArguments("C", "Property").WithLocation(1, 29)); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "C.Property"); + Assert.Equal("System.String E.<>E__0.Property { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); + } + + [Fact] + public void Nameof_Static_Property_Generic_03() + { + var src = """ +System.Console.Write(nameof(I.Property)); + +interface I { } + +static class E +{ + extension(I i) + { + public static string Property => throw null; + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (1,29): error CS9316: Extension members are not allowed as an argument to 'nameof'. + // System.Console.Write(nameof(I.Property)); + Diagnostic(ErrorCode.ERR_NameofExtensionMember, "I.Property").WithLocation(1, 29)); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "I.Property"); + Assert.Equal("System.String E.<>E__0.Property { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); + } + + [Fact] + public void Nameof_Overloads_01() + { + var src = """ +System.Console.Write($"{nameof(object.M)} "); + +static class E +{ + extension(object) + { + public static void M() { } + public static void M(int i) { } + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (1,32): error CS8093: Extension method groups are not allowed as an argument to 'nameof'. + // System.Console.Write($"{nameof(object.M)} "); + Diagnostic(ErrorCode.ERR_NameofExtensionMethod, "object.M").WithLocation(1, 32)); + } + + [Fact] + public void Nameof_Overloads_02() + { + var src = """ +System.Console.Write($"{nameof(object.M)} "); + +static class E1 +{ + extension(T) where T : class + { + public static void M() { } + } +} + +static class E2 +{ + extension(T) where T : struct + { + public static void M() { } + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (1,32): error CS8093: Extension method groups are not allowed as an argument to 'nameof'. + // System.Console.Write($"{nameof(object.M)} "); + Diagnostic(ErrorCode.ERR_NameofExtensionMethod, "object.M").WithLocation(1, 32)); + + var tree = comp.SyntaxTrees.Single(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "object.M"); + Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); + Assert.Equal(["void E1.<>E__0.M()"], model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); + Assert.Equal(["void E1.<>E__0.M()"], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); + } + + [Fact] + public void Nameof_SimpleName() + { + var src = """ +class C +{ + void M() + { + _ = nameof(Method); + _ = nameof(Property); + } +} + +static class E +{ + extension(object) + { + public static void Method() { } + public static int Property => 0; + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyDiagnostics( + // (5,20): error CS0103: The name 'Method' does not exist in the current context + // _ = nameof(Method); + Diagnostic(ErrorCode.ERR_NameNotInContext, "Method").WithArguments("Method").WithLocation(5, 20), + // (6,20): error CS0103: The name 'Property' does not exist in the current context + // _ = nameof(Property); + Diagnostic(ErrorCode.ERR_NameNotInContext, "Property").WithArguments("Property").WithLocation(6, 20)); + } + + [Fact] + public void Nameof_NoParameter() + { + var src = """ +class C +{ + void M() + { + System.Console.Write(nameof()); + } +} + +static class E +{ + extension(C c) + { + public string nameof() => throw null; + } +} +"""; + + var comp = CreateCompilation(src); + comp.VerifyDiagnostics( + // (5,30): error CS0103: The name 'nameof' does not exist in the current context + // System.Console.Write(nameof()); + Diagnostic(ErrorCode.ERR_NameNotInContext, "nameof").WithArguments("nameof").WithLocation(5, 30)); + } + + [Fact] + public void Nameof_SingleParameter() + { + var src = """ +class C +{ + public static void Main() + { + string x = ""; + System.Console.Write(nameof(x)); + } +} + +static class E +{ + extension(C c) + { + public string nameof(string s) => throw null; + } +} +"""; + + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "x").VerifyDiagnostics(); + } + + [Fact] + public void StaticMethodInvocation_TypeParameter_InNameof() + { + var source = """ +public static class C +{ + static void M() + { + _ = nameof(T.Method); + } + + extension(T) + { + public static void Method() { } + } +} +"""; + var comp = CreateCompilation(source); + comp.VerifyDiagnostics( + // 0.cs(5,20): error CS0704: Cannot do non-virtual member lookup in 'T' because it is a type parameter + // _ = nameof(T.Method); + Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T").WithArguments("T").WithLocation(5, 20)); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "T.Method"); + Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); + Assert.Empty(model.GetMemberGroup(memberAccess)); + } + + [Fact] + public void SymbolInfoForMethodGroup03() + { + var source = """ +public class A { } + +static class E +{ + extension(A a) + { + public string Extension() { return null; } + } +} +public class Program +{ + public static void Main(string[] args) + { + A a = null; + _ = nameof(a.Extension); + } +} +"""; + var comp = CreateCompilation(source); + comp.VerifyDiagnostics( + // (15,20): error CS8093: Extension method groups are not allowed as an argument to 'nameof'. + // _ = nameof(a.Extension); + Diagnostic(ErrorCode.ERR_NameofExtensionMethod, "a.Extension").WithLocation(15, 20)); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var memberAccess = GetSyntax(tree, "a.Extension"); + Assert.Null(model.GetSymbolInfo(memberAccess).Symbol); + // Tracked by https://github.com/dotnet/roslyn/issues/76130 : Assert.Empty(model.GetMemberGroup(memberAccess)); + } + + [Fact] + public void StaticMethodInvocation_PartialStaticClass() + { + var source = """ +object.M(); +object.M2(); + +public static partial class C +{ + extension(object) + { + public static void M() { System.Console.Write("ran "); } + } +} + +public static partial class C +{ + extension(object) + { + public static void M2() { System.Console.Write("ran2"); } + } +} +"""; + var comp = CreateCompilation(source); + CompileAndVerify(comp, expectedOutput: "ran ran2").VerifyDiagnostics(); + } + + [Fact] + public void StaticMethodInvocation_TupleTypeReceiver() + { + var src = """ +(string, string).M(); +(int a, int b).M(); +"""; + // Tracked by https://github.com/dotnet/roslyn/issues/78961 : consider parsing this + var comp = CreateCompilation(src); + comp.VerifyDiagnostics( + // (1,2): error CS1525: Invalid expression term 'string' + // (string, string).M(); + Diagnostic(ErrorCode.ERR_InvalidExprTerm, "string").WithArguments("string").WithLocation(1, 2), + // (1,10): error CS1525: Invalid expression term 'string' + // (string, string).M(); + Diagnostic(ErrorCode.ERR_InvalidExprTerm, "string").WithArguments("string").WithLocation(1, 10), + // (2,2): error CS8185: A declaration is not allowed in this context. + // (int a, int b).M(); + Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int a").WithLocation(2, 2), + // (2,2): error CS0165: Use of unassigned local variable 'a' + // (int a, int b).M(); + Diagnostic(ErrorCode.ERR_UseDefViolation, "int a").WithArguments("a").WithLocation(2, 2), + // (2,9): error CS8185: A declaration is not allowed in this context. + // (int a, int b).M(); + Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int b").WithLocation(2, 9), + // (2,9): error CS0165: Use of unassigned local variable 'b' + // (int a, int b).M(); + Diagnostic(ErrorCode.ERR_UseDefViolation, "int b").WithArguments("b").WithLocation(2, 9), + // (2,16): error CS1061: '(int a, int b)' does not contain a definition for 'M' and no accessible extension method 'M' accepting a first argument of type '(int a, int b)' could be found (are you missing a using directive or an assembly reference?) + // (int a, int b).M(); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M").WithArguments("(int a, int b)", "M").WithLocation(2, 16)); + } + + [Fact] + public void StaticMethodInvocation_TupleTypeReceiver_02() + { + var src = """ +((string, string)).M(); +((int a, int b)).M(); +"""; + // Tracked by https://github.com/dotnet/roslyn/issues/78961 : consider parsing this + var comp = CreateCompilation(src); + comp.VerifyDiagnostics( + // (1,3): error CS1525: Invalid expression term 'string' + // ((string, string)).M(); + Diagnostic(ErrorCode.ERR_InvalidExprTerm, "string").WithArguments("string").WithLocation(1, 3), + // (1,11): error CS1525: Invalid expression term 'string' + // ((string, string)).M(); + Diagnostic(ErrorCode.ERR_InvalidExprTerm, "string").WithArguments("string").WithLocation(1, 11), + // (2,3): error CS8185: A declaration is not allowed in this context. + // ((int a, int b)).M(); + Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int a").WithLocation(2, 3), + // (2,3): error CS0165: Use of unassigned local variable 'a' + // ((int a, int b)).M(); + Diagnostic(ErrorCode.ERR_UseDefViolation, "int a").WithArguments("a").WithLocation(2, 3), + // (2,10): error CS8185: A declaration is not allowed in this context. + // ((int a, int b)).M(); + Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int b").WithLocation(2, 10), + // (2,10): error CS0165: Use of unassigned local variable 'b' + // ((int a, int b)).M(); + Diagnostic(ErrorCode.ERR_UseDefViolation, "int b").WithArguments("b").WithLocation(2, 10), + // (2,18): error CS1061: '(int a, int b)' does not contain a definition for 'M' and no accessible extension method 'M' accepting a first argument of type '(int a, int b)' could be found (are you missing a using directive or an assembly reference?) + // ((int a, int b)).M(); + Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M").WithArguments("(int a, int b)", "M").WithLocation(2, 18)); + } + + [Fact] + public void StaticMethodInvocation_PointerTypeReceiver() + { + var src = """ +unsafe class C +{ + void M() + { + int*.M(); + delegate*.M(); + } +} +"""; + // Tracked by https://github.com/dotnet/roslyn/issues/78961 : consider parsing this + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll); + comp.VerifyDiagnostics( + // (5,13): error CS1001: Identifier expected + // int*.M(); + Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(5, 13), + // (5,13): error CS1003: Syntax error, ',' expected + // int*.M(); + Diagnostic(ErrorCode.ERR_SyntaxError, ".").WithArguments(",").WithLocation(5, 13), + // (5,14): error CS1002: ; expected + // int*.M(); + Diagnostic(ErrorCode.ERR_SemicolonExpected, "M").WithLocation(5, 14), + // (6,17): error CS1514: { expected + // delegate*.M(); + Diagnostic(ErrorCode.ERR_LbraceExpected, "*").WithLocation(6, 17), + // (6,17): warning CS8848: Operator '*' cannot be used here due to precedence. Use parentheses to disambiguate. + // delegate*.M(); + Diagnostic(ErrorCode.WRN_PrecedenceInversion, "*").WithArguments("*").WithLocation(6, 17), + // (6,18): error CS1525: Invalid expression term '<' + // delegate*.M(); + Diagnostic(ErrorCode.ERR_InvalidExprTerm, "<").WithArguments("<").WithLocation(6, 18), + // (6,19): error CS1525: Invalid expression term 'void' + // delegate*.M(); + Diagnostic(ErrorCode.ERR_InvalidExprTerm, "void").WithArguments("void").WithLocation(6, 19), + // (6,24): error CS1525: Invalid expression term '.' + // delegate*.M(); + Diagnostic(ErrorCode.ERR_InvalidExprTerm, ".").WithArguments(".").WithLocation(6, 24)); + } + + [Fact] + public void StaticMethodInvocation_DynamicTypeReceiver() + { + var src = """ +dynamic.M(); +"""; + var comp = CreateCompilation(src); + comp.VerifyDiagnostics( + // (1,1): error CS0103: The name 'dynamic' does not exist in the current context + // dynamic.M(); + Diagnostic(ErrorCode.ERR_NameNotInContext, "dynamic").WithArguments("dynamic").WithLocation(1, 1)); + } + + [Fact] + public void DisplayString_Constraint() + { + var source = """ +static class E +{ + extension(T) where T : struct + { + } +} +"""; + var comp = CreateCompilation(source); + comp.VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var extension = tree.GetRoot().DescendantNodes().OfType().Single(); + var symbol = model.GetDeclaredSymbol(extension); + + var format = new SymbolDisplayFormat(genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints); + Assert.Equal("extension(T) where T : struct", symbol.ToDisplayString(format)); + } + + [Fact] + public void DisplayString_Modifier() + { + var source = """ +static class E +{ + extension(ref readonly int i) + { + } +} +"""; + var comp = CreateCompilation(source); + comp.VerifyDiagnostics(); + + var tree = comp.SyntaxTrees.First(); + var model = comp.GetSemanticModel(tree); + var extension = tree.GetRoot().DescendantNodes().OfType().Single(); + var symbol = model.GetDeclaredSymbol(extension); + + var format = new SymbolDisplayFormat(parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeModifiers); + Assert.Equal("extension(ref readonly Int32)", symbol.ToDisplayString(format)); + } + + [Fact] + public void NameConflict_01_EnclosingStaticTypeNameWithExtensionTypeParameterName() + { + var src = """ +static class Extensions +{ + extension(Extensions) + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + } + + [Fact] + public void NameConflict_02_EnclosingStaticTypeNameWithReceiverParameterName() + { + var src = """ +static class Extensions +{ + extension(int Extensions) + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + } + + [Fact] + public void NameConflict_03_ExtensionTypeParameterNameWithReceiverParameterName() + { + var src = """ +static class Extensions +{ +#line 7 + extension(T[] T) + { + void M1(){} + } +} +"""; + var comp = CreateCompilation(src); + + comp.VerifyDiagnostics( + // (7,22): error CS9287: 'T': a receiver parameter cannot have the same name as an extension container type parameter + // extension(T[] T) + Diagnostic(ErrorCode.ERR_ReceiverParameterSameNameAsTypeParameter, "T").WithArguments("T").WithLocation(7, 22) + ); + } + + [Fact] + public void NameConflict_04_ExtensionTypeParameterNameWithMemberParameterName() + { + var src = """ +static class Extensions +{ + extension(T[] p) + { +#line 14 + void M2(int T){} + static void M3(int T){} + int this[int T] => 0; + } +} +"""; + var comp = CreateCompilation(src); + + comp.VerifyDiagnostics( + // (14,21): error CS9288: 'T': a parameter, local variable, or local function cannot have the same name as an extension container type parameter + // void M2(int T){} + Diagnostic(ErrorCode.ERR_LocalSameNameAsExtensionTypeParameter, "T").WithArguments("T").WithLocation(14, 21), + // (15,28): error CS9288: 'T': a parameter, local variable, or local function cannot have the same name as an extension container type parameter + // static void M3(int T){} + Diagnostic(ErrorCode.ERR_LocalSameNameAsExtensionTypeParameter, "T").WithArguments("T").WithLocation(15, 28), + // (16,13): error CS9282: This member is not allowed in an extension block + // int this[int T] => 0; + Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(16, 13), + // (16,22): error CS9288: 'T': a parameter, local variable, or local function cannot have the same name as an extension container type parameter + // int this[int T] => 0; + Diagnostic(ErrorCode.ERR_LocalSameNameAsExtensionTypeParameter, "T").WithArguments("T").WithLocation(16, 22) + ); + } + + [Theory] + [CombinatorialData] + public void NameConflict_05_ExtensionTypeParameterNameWithSetterValueParameter(bool isStatic) + { + var src = @" +static class Extensions +{ + extension(value[] p) + { + " + (isStatic ? "static" : "") + @" + int P11 {set{}} + + " + (isStatic ? "static" : "") + @" + int P12 => 0; + } +} +"; + var comp = CreateCompilation(src); + + comp.VerifyDiagnostics( + // (4,15): warning CS8981: The type name 'value' only contains lower-cased ascii characters. Such names may become reserved for the language. + // extension(value[] p) + Diagnostic(ErrorCode.WRN_LowerCaseTypeName, "value").WithArguments("value").WithLocation(4, 15), + // (7,18): error CS9294: 'value': an automatically-generated parameter name conflicts with an extension type parameter name + // int P11 {set{}} + Diagnostic(ErrorCode.ERR_ValueParameterSameNameAsExtensionTypeParameter, "set").WithLocation(7, 18) + ); + } + + [Fact] + public void NameConflict_06_ExtensionTypeParameterNameWithSetterValueParameter() + { + var src = @" +static class Extensions +{ + extension(value[] p) + { + int this[int i] {set{}} + int this[long i] => 0; + } +} +"; + var comp = CreateCompilation(src); + + comp.VerifyDiagnostics( + // (4,15): warning CS8981: The type name 'value' only contains lower-cased ascii characters. Such names may become reserved for the language. + // extension(value[] p) + Diagnostic(ErrorCode.WRN_LowerCaseTypeName, "value").WithArguments("value").WithLocation(4, 15), + // (6,13): error CS9282: This member is not allowed in an extension block + // int this[int i] {set{}} + Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(6, 13), + // (6,26): error CS9294: 'value': an automatically-generated parameter name conflicts with an extension type parameter name + // int this[int i] {set{}} + Diagnostic(ErrorCode.ERR_ValueParameterSameNameAsExtensionTypeParameter, "set").WithLocation(6, 26), + // (7,13): error CS9282: This member is not allowed in an extension block + // int this[long i] => 0; + Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(7, 13) + ); + } + + [Theory] + [CombinatorialData] + public void NameConflict_07_ExtensionTypeParameterNameWithLocalFunctionParameterName(bool isStatic1, bool isStatic2) + { + var modifier1 = isStatic1 ? "static " : ""; + var modifier2 = isStatic2 ? "static " : ""; + + var src = @" +#pragma warning disable CS8321 // The local function 'local' is declared but never used + +static class Extensions +{ + extension(T[] p) + { + " + modifier1 + @"void M4() + { + " + modifier2 + @"int local(int T) + { + return T; + } + } + " + modifier1 + @"int P7 + { + set + { + " + modifier2 + @"int local(int T) + { + return T; + } + } + } + } +} +"; + var comp = CreateCompilation(src); + + comp.VerifyEmitDiagnostics(); + } + + [Theory] + [CombinatorialData] + public void NameConflict_08_ExtensionTypeParameterNameWithLambdaParameterName(bool isStatic1, bool isStatic2) + { + var modifier1 = isStatic1 ? "static " : ""; + var modifier2 = isStatic2 ? "static " : ""; + + var src = @" +static class Extensions +{ + extension(T[] p) + { + " + modifier1 + @"void M4() + { + System.Func l = " + modifier2 + @"(int T) => + { + return T; + }; + } " + modifier1 + @"int P7 { set @@ -26414,7 +27329,7 @@ int this[int y] "; var comp = CreateCompilation(src); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : We do not allow complex forms of IndexerName attribute due to a possible binding cycle + // Tracked by https://github.com/dotnet/roslyn/issues/78829 : indexers, We do not allow complex forms of IndexerName attribute due to a possible binding cycle comp.VerifyEmitDiagnostics( // (7,54): error CS8078: An expression is too long or complex to compile // [System.Runtime.CompilerServices.IndexerName(Str)] @@ -31992,7 +32907,7 @@ public static class E Assert.Equal([ "System.Boolean System.Object.Equals(System.Object objA, System.Object objB)", "System.Boolean System.Object.ReferenceEquals(System.Object objA, System.Object objB)"], - model.LookupStaticMembers(position: 0, o, name: null).ToTestDisplayStrings()); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : should we include extension static members? + model.LookupStaticMembers(position: 0, o, name: null).ToTestDisplayStrings()); // Tracked by https://github.com/dotnet/roslyn/issues/78957 : public API, should we include extension static members? Assert.Empty(model.LookupNamespacesAndTypes(position: 0, o, name: null)); } @@ -32458,7 +33373,7 @@ static class E var model = comp.GetSemanticModel(tree); var memberAccess = GetSyntax(tree, "object.P"); - Assert.Equal([], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : handle GetMemberGroup on a property access + Assert.Equal([], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); // Tracked by https://github.com/dotnet/roslyn/issues/78957 : handle GetMemberGroup on a property access } [Fact] @@ -32727,7 +33642,7 @@ static class E2 var memberAccess = GetSyntax(tree, "object.P"); Assert.Equal("System.Int32 E2.<>E__0.P { get; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); Assert.Equal([], model.GetSymbolInfo(memberAccess).CandidateSymbols.ToTestDisplayStrings()); - Assert.Equal([], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); // Tracked by https://github.com/dotnet/roslyn/issues/76130 : handle GetMemberGroup on a property access + Assert.Equal([], model.GetMemberGroup(memberAccess).ToTestDisplayStrings()); // Tracked by https://github.com/dotnet/roslyn/issues/78957 : handle GetMemberGroup on a property access } [Fact] @@ -33005,7 +33920,8 @@ public static class E { public void M() { } public static void M2() { } - public static int P => 0; + public int P => 0; + public static int P2 => 0; } } @@ -33020,8 +33936,10 @@ public static void M2() { } var x = new object().M; E.M(new object()); -E.get_P(); E.M2(); + +E.get_P(new object()); +E.get_P2(); """; var comp = CreateCompilation(srcCompat, references: [libRef], parseOptions: TestOptions.Regular13); comp.VerifyEmitDiagnostics(); @@ -33037,53 +33955,184 @@ public static void M2() { } System.Action a = object.M2; var x = object.M2; -_ = object.P; +_ = object.P2; """; comp = CreateCompilation(src, references: [libRef], parseOptions: TestOptions.Regular13); comp.VerifyEmitDiagnostics( - // (1,8): error CS0117: 'object' does not contain a definition for 'M2' + // (1,1): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // object.M2(); - Diagnostic(ErrorCode.ERR_NoSuchMember, "M2").WithArguments("object", "M2").WithLocation(1, 8), - // (2,26): error CS0117: 'object' does not contain a definition for 'M2' + Diagnostic(ErrorCode.ERR_FeatureInPreview, "object.M2()").WithArguments("extensions").WithLocation(1, 1), + // (2,19): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // System.Action a = object.M2; - Diagnostic(ErrorCode.ERR_NoSuchMember, "M2").WithArguments("object", "M2").WithLocation(2, 26), - // (3,16): error CS0117: 'object' does not contain a definition for 'M2' + Diagnostic(ErrorCode.ERR_FeatureInPreview, "object.M2").WithArguments("extensions").WithLocation(2, 19), + // (3,9): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // var x = object.M2; - Diagnostic(ErrorCode.ERR_NoSuchMember, "M2").WithArguments("object", "M2").WithLocation(3, 16), - // (5,12): error CS0117: 'object' does not contain a definition for 'P' - // _ = object.P; - Diagnostic(ErrorCode.ERR_NoSuchMember, "P").WithArguments("object", "P").WithLocation(5, 12)); - verifySymbolInfo(comp, newLangVer: false); + Diagnostic(ErrorCode.ERR_FeatureInPreview, "object.M2").WithArguments("extensions").WithLocation(3, 9), + // (5,5): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = object.P2; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "object.P2").WithArguments("extensions").WithLocation(5, 5)); + verifySymbolInfo(comp); comp = CreateCompilation(src, references: [libRef], parseOptions: TestOptions.RegularNext); comp.VerifyEmitDiagnostics(); - verifySymbolInfo(comp, newLangVer: true); + verifySymbolInfo(comp); comp = CreateCompilation(src, references: [libRef]); comp.VerifyEmitDiagnostics(); - verifySymbolInfo(comp, newLangVer: true); + verifySymbolInfo(comp); - static void verifySymbolInfo(CSharpCompilation comp, bool newLangVer) + src = """ +_ = new object().P; +"""; + comp = CreateCompilation(src, references: [libRef], parseOptions: TestOptions.Regular13); + comp.VerifyEmitDiagnostics( + // (1,5): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // _ = new object().P; + Diagnostic(ErrorCode.ERR_FeatureInPreview, "new object().P").WithArguments("extensions").WithLocation(1, 5)); + verifySymbolInfo(comp); + + comp = CreateCompilation(src, references: [libRef], parseOptions: TestOptions.RegularNext); + comp.VerifyEmitDiagnostics(); + verifySymbolInfo(comp); + + comp = CreateCompilation(src, references: [libRef]); + comp.VerifyEmitDiagnostics(); + verifySymbolInfo(comp); + + static void verifySymbolInfo(CSharpCompilation comp) { var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var o = ((Compilation)comp).GetSpecialType(SpecialType.System_Object); - if (newLangVer) - { - AssertEqualAndNoDuplicates(["void E.<>E__0.M()"], model.LookupSymbols(position: 0, o, name: "M", includeReducedExtensionMethods: true).ToTestDisplayStrings()); - AssertEqualAndNoDuplicates(["void E.<>E__0.M2()"], model.LookupSymbols(position: 0, o, name: "M2", includeReducedExtensionMethods: true).ToTestDisplayStrings()); - AssertEqualAndNoDuplicates(["System.Int32 E.<>E__0.P { get; }"], model.LookupSymbols(position: 0, o, name: "P", includeReducedExtensionMethods: true).ToTestDisplayStrings()); - } - else - { - AssertEqualAndNoDuplicates(["void System.Object.M()"], model.LookupSymbols(position: 0, o, name: "M", includeReducedExtensionMethods: true).ToTestDisplayStrings()); - AssertEqualAndNoDuplicates([], model.LookupSymbols(position: 0, o, name: "M2", includeReducedExtensionMethods: true).ToTestDisplayStrings()); - AssertEqualAndNoDuplicates([], model.LookupSymbols(position: 0, o, name: "P", includeReducedExtensionMethods: true).ToTestDisplayStrings()); - } + AssertEqualAndNoDuplicates(["void E.<>E__0.M()"], model.LookupSymbols(position: 0, o, name: "M", includeReducedExtensionMethods: true).ToTestDisplayStrings()); + AssertEqualAndNoDuplicates(["void E.<>E__0.M2()"], model.LookupSymbols(position: 0, o, name: "M2", includeReducedExtensionMethods: true).ToTestDisplayStrings()); + AssertEqualAndNoDuplicates(["System.Int32 E.<>E__0.P { get; }"], model.LookupSymbols(position: 0, o, name: "P", includeReducedExtensionMethods: true).ToTestDisplayStrings()); + AssertEqualAndNoDuplicates(["System.Int32 E.<>E__0.P2 { get; }"], model.LookupSymbols(position: 0, o, name: "P2", includeReducedExtensionMethods: true).ToTestDisplayStrings()); } } + [Fact] + public void LangVer_02() + { + var libSrc = """ +public static class E +{ + extension(object o) + { + public System.Collections.IEnumerator GetEnumerator() => throw null; + } +} + +"""; + var libComp = CreateCompilation(libSrc, parseOptions: TestOptions.RegularNext); + libComp.VerifyEmitDiagnostics(); + var libRef = libComp.EmitToImageReference(); + + var src = """ +foreach (var x in new object()) +{ +} +"""; + var comp = CreateCompilation(src, references: [libRef], parseOptions: TestOptions.Regular13); + comp.VerifyEmitDiagnostics(); + + comp = CreateCompilation(src, references: [libRef], parseOptions: TestOptions.RegularNext); + comp.VerifyEmitDiagnostics(); + + comp = CreateCompilation(src, references: [libRef]); + comp.VerifyEmitDiagnostics(); + } + + [Fact] + public void LangVer_03() + { + var libSrc = """ +public static class E +{ + extension(object o) + { + public void Add(object o2) { } + } +} +"""; + var libComp = CreateCompilation(libSrc, parseOptions: TestOptions.RegularNext); + libComp.VerifyEmitDiagnostics(); + var libRef = libComp.EmitToImageReference(); + + var src = """ +using System.Collections; +using System.Collections.Generic; + +MyCollection c = [new object()]; + +public class MyCollection : IEnumerable +{ + IEnumerator IEnumerable.GetEnumerator() => throw null!; + IEnumerator IEnumerable.GetEnumerator() => throw null!; +} +"""; + var comp = CreateCompilation(src, references: [libRef], parseOptions: TestOptions.Regular13); + comp.VerifyEmitDiagnostics(); + + comp = CreateCompilation(src, references: [libRef], parseOptions: TestOptions.RegularNext); + comp.VerifyEmitDiagnostics(); + + comp = CreateCompilation(src, references: [libRef]); + comp.VerifyEmitDiagnostics(); + } + + [Fact] + public void LangVer_04() + { + var libSrc = """ +namespace N; + +public static class E +{ + extension(int i) + { + public System.Action Member => () => System.Console.Write("property"); + } +} +"""; + var libComp = CreateCompilation(libSrc, parseOptions: TestOptions.RegularNext); + libComp.VerifyEmitDiagnostics(); + var libRef = libComp.EmitToImageReference(); + + var src = """ +namespace N +{ + class D + { + public static void Main() + { + 42.Member(); + } + } +} + +static class Classic +{ + public static void Member(this int i) { System.Console.Write("classic"); } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "classic").VerifyDiagnostics(); + + comp = CreateCompilation(src, references: [libRef], options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "property").VerifyDiagnostics(); + + comp = CreateCompilation(src, references: [libRef], parseOptions: TestOptions.RegularNext, options: TestOptions.DebugExe); + CompileAndVerify(comp, expectedOutput: "property").VerifyDiagnostics(); + + comp = CreateCompilation(src, references: [libRef], parseOptions: TestOptions.Regular13); + comp.VerifyEmitDiagnostics( + // (7,13): error CS8652: The feature 'extensions' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + // 42.Member(); + Diagnostic(ErrorCode.ERR_FeatureInPreview, "42.Member").WithArguments("extensions").WithLocation(7, 13)); + } + [Fact] public void This_01() { @@ -33376,7 +34425,7 @@ static class E public partial class RegionAnalysisTests : FlowTestBase { - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : consider removing `this` from the region analysis tests + // Tracked by https://github.com/dotnet/roslyn/issues/78968 : consider removing `this` from the region analysis tests [Fact] public void RegionAnalysis_01() { @@ -35971,518 +37020,1486 @@ .locals init (C.d__1 V_0, IL_00c6: ldloc.0 IL_00c7: ret } -"""); +"""); + } + + [Fact] + public void ReceiverParameterValidation_UnnamedReceiverParameter() + { + string source = """ +static class E +{ + extension(int i) + { + public void M1() { } + public static void M2() { } + public int P1 => 0; + public static int P2 => 0; + } + extension(int) + { + public void M3() { } // 1 + public static void M4() { } + public int P3 => 0; // 2 + public static int P4 => 0; + public int this[int j] => 0; // 3 + } +} +"""; + var comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (12,21): error CS9303: 'M3': cannot declare instance members in an extension block with an unnamed receiver parameter + // public void M3() { } // 1 + Diagnostic(ErrorCode.ERR_InstanceMemberWithUnnamedExtensionsParameter, "M3").WithArguments("M3").WithLocation(12, 21), + // (14,20): error CS9303: 'P3': cannot declare instance members in an extension block with an unnamed receiver parameter + // public int P3 => 0; // 2 + Diagnostic(ErrorCode.ERR_InstanceMemberWithUnnamedExtensionsParameter, "P3").WithArguments("P3").WithLocation(14, 20), + // (16,20): error CS9282: This member is not allowed in an extension block + // public int this[int j] => 0; // 3 + Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(16, 20), + // (16,20): error CS9303: 'this[]': cannot declare instance members in an extension block with an unnamed receiver parameter + // public int this[int j] => 0; // 3 + Diagnostic(ErrorCode.ERR_InstanceMemberWithUnnamedExtensionsParameter, "this").WithArguments("this[]").WithLocation(16, 20)); + } + + [Fact] + public void ReceiverParameterValidation_UnnamedReceiverParameter_Ref() + { + string source = """ +static class E +{ + extension(ref int) + { + } + extension(ref string) + { + } +} +"""; + var comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (3,19): error CS9305: Cannot use modifiers on the unnamed receiver parameter of extension block + // extension(ref int) + Diagnostic(ErrorCode.ERR_ModifierOnUnnamedReceiverParameter, "int").WithLocation(3, 19), + // (6,19): error CS9300: The 'ref' receiver parameter of an extension block must be a value type or a generic type constrained to struct. + // extension(ref string) + Diagnostic(ErrorCode.ERR_RefExtensionParameterMustBeValueTypeOrConstrainedToOne, "string").WithLocation(6, 19), + // (6,19): error CS9305: Cannot use modifiers on the unnamed receiver parameter of extension block + // extension(ref string) + Diagnostic(ErrorCode.ERR_ModifierOnUnnamedReceiverParameter, "string").WithLocation(6, 19)); + } + + [Fact] + public void ReceiverParameterValidation_UnnamedReceiverParameter_Out() + { + string source = """ +static class E +{ + extension(out int) + { + } +} +"""; + var comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (3,15): error CS8328: The parameter modifier 'out' cannot be used with 'extension' + // extension(out int) + Diagnostic(ErrorCode.ERR_BadParameterModifiers, "out").WithArguments("out", "extension").WithLocation(3, 15), + // (3,19): error CS9305: Cannot use modifiers on the unnamed receiver parameter of extension block + // extension(out int) + Diagnostic(ErrorCode.ERR_ModifierOnUnnamedReceiverParameter, "int").WithLocation(3, 19)); + } + + [Fact] + public void ReceiverParameterValidation_UnnamedReceiverParameter_Scoped() + { + // Tracked by https://github.com/dotnet/roslyn/issues/78961 : This should probably parse (but still error) + string source = """ +static class E +{ + extension(scoped RS) + { + } +} +ref struct RS { } +"""; + var comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (3,15): error CS0246: The type or namespace name 'scoped' could not be found (are you missing a using directive or an assembly reference?) + // extension(scoped RS) + Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "scoped").WithArguments("scoped").WithLocation(3, 15)); + } + + [Fact] + public void ReceiverParameterValidation_UnnamedReceiverParameter_FromMetadata() + { + // extension(int) + // { + // public void M3() { } + // public static void M4() { } + // public int P3 => 0; + // public static int P4 => 0; + // } + var ilSrc = """ +.class public auto ansi abstract sealed beforefieldinit E + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + .method private hidebysig specialname static void '$' ( int32 '' ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } + .method public hidebysig instance void M3 () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + .method public hidebysig static void M4 () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + .method public hidebysig specialname instance int32 get_P3 () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + .method public hidebysig specialname static int32 get_P4 () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + .property instance int32 P3() + { + .get instance int32 E/'<>E__0'::get_P3() + } + .property int32 P4() + { + .get int32 E/'<>E__0'::get_P4() + } + } + .method public hidebysig static void M3 ( int32 '' ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } + .method public hidebysig static void M4 () cil managed + { + IL_0000: ret + } + .method public hidebysig static int32 get_P3 ( int32 '' ) cil managed + { + IL_0000: ldc.i4.0 + IL_0001: ret + } + .method public hidebysig static int32 get_P4 () cil managed + { + IL_0000: ldc.i4.0 + IL_0001: ret + } +} +"""; + string source = """ +42.M3(); +int.M4(); +_ = 42.P3; +_ = int.P4; +"""; + var comp = CreateCompilationWithIL(source, ilSrc); + comp.VerifyEmitDiagnostics(); + } + + [Fact] + public void AsyncInSecurityCriticalClass() + { + var source = """ +using System.Security; +using System.Threading.Tasks; + +[SecurityCritical] +public static class C +{ + extension(int i) + { + public async void M() + { + await Task.Factory.StartNew(() => { }); + } + } +} +"""; + CreateCompilation(source).VerifyDiagnostics( + // (9,27): error CS4031: Async methods are not allowed in an Interface, Class, or Structure which has the 'SecurityCritical' or 'SecuritySafeCritical' attribute. + // public async void M() + Diagnostic(ErrorCode.ERR_SecurityCriticalOrSecuritySafeCriticalOnAsyncInClassOrStruct, "M").WithLocation(9, 27)); + } + + [Fact] + public void Validation_Modifiers_Virtual() + { + string source = """ +static class E +{ + extension(int i) + { + public virtual void M() { } + public virtual int P { get => 0; set { } } + } +} +"""; + var comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (5,29): error CS0106: The modifier 'virtual' is not valid for this item + // public virtual void M() { } + Diagnostic(ErrorCode.ERR_BadMemberFlag, "M").WithArguments("virtual").WithLocation(5, 29), + // (6,28): error CS0106: The modifier 'virtual' is not valid for this item + // public virtual int P { get => 0; set { } } + Diagnostic(ErrorCode.ERR_BadMemberFlag, "P").WithArguments("virtual").WithLocation(6, 28)); + } + + [Fact] + public void Validation_Modifiers_Abstract() + { + string source = """ +static class E +{ + extension(int i) + { + public abstract void M(); + public abstract int P { get; } + public abstract int P2 { set; } + public abstract int this[int j] { get; } + } +} +"""; + var comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (5,30): error CS0106: The modifier 'abstract' is not valid for this item + // public abstract void M(); + Diagnostic(ErrorCode.ERR_BadMemberFlag, "M").WithArguments("abstract").WithLocation(5, 30), + // (5,30): error CS0501: 'E.extension(int).M()' must declare a body because it is not marked abstract, extern, or partial + // public abstract void M(); + Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M").WithArguments("E.extension(int).M()").WithLocation(5, 30), + // (6,29): error CS0106: The modifier 'abstract' is not valid for this item + // public abstract int P { get; } + Diagnostic(ErrorCode.ERR_BadMemberFlag, "P").WithArguments("abstract").WithLocation(6, 29), + // (6,29): error CS9282: This member is not allowed in an extension block + // public abstract int P { get; } + Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "P").WithLocation(6, 29), + // (7,29): error CS0106: The modifier 'abstract' is not valid for this item + // public abstract int P2 { set; } + Diagnostic(ErrorCode.ERR_BadMemberFlag, "P2").WithArguments("abstract").WithLocation(7, 29), + // (7,29): error CS9282: This member is not allowed in an extension block + // public abstract int P2 { set; } + Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "P2").WithLocation(7, 29), + // (7,34): error CS8051: Auto-implemented properties must have get accessors. + // public abstract int P2 { set; } + Diagnostic(ErrorCode.ERR_AutoPropertyMustHaveGetAccessor, "set").WithLocation(7, 34), + // (8,29): error CS0106: The modifier 'abstract' is not valid for this item + // public abstract int this[int j] { get; } + Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract").WithLocation(8, 29), + // (8,29): error CS9282: This member is not allowed in an extension block + // public abstract int this[int j] { get; } + Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(8, 29), + // (8,43): error CS0501: 'E.extension(int).this[int].get' must declare a body because it is not marked abstract, extern, or partial + // public abstract int this[int j] { get; } + Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("E.extension(int).this[int].get").WithLocation(8, 43)); + } + + [Fact] + public void Validation_Modifiers_New() + { + string source = """ +static class E +{ + extension(int i) + { + public new string ToString() => ""; + public new int P { get => 0; } + public new int this[int j] { get => 0; } + } +} +"""; + var comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (5,27): error CS0106: The modifier 'new' is not valid for this item + // public new string ToString() => ""; + Diagnostic(ErrorCode.ERR_BadMemberFlag, "ToString").WithArguments("new").WithLocation(5, 27), + // (6,24): error CS0106: The modifier 'new' is not valid for this item + // public new int P { get => 0; } + Diagnostic(ErrorCode.ERR_BadMemberFlag, "P").WithArguments("new").WithLocation(6, 24), + // (7,24): error CS0106: The modifier 'new' is not valid for this item + // public new int this[int j] { get => 0; } + Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("new").WithLocation(7, 24), + // (7,24): error CS9282: This member is not allowed in an extension block + // public new int this[int j] { get => 0; } + Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(7, 24)); } [Fact] - public void ReceiverParameterValidation_UnnamedReceiverParameter() + public void Validation_Modifiers_Override() { string source = """ static class E { extension(int i) { - public void M1() { } - public static void M2() { } - public int P1 => 0; - public static int P2 => 0; + public override string ToString() => ""; + public override int P { get => 0; } + public override int this[int j] { get => 0; } } - extension(int) +} +"""; + var comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (5,32): error CS0106: The modifier 'override' is not valid for this item + // public override string ToString() => ""; + Diagnostic(ErrorCode.ERR_BadMemberFlag, "ToString").WithArguments("override").WithLocation(5, 32), + // (6,29): error CS0106: The modifier 'override' is not valid for this item + // public override int P { get => 0; } + Diagnostic(ErrorCode.ERR_BadMemberFlag, "P").WithArguments("override").WithLocation(6, 29), + // (7,29): error CS0106: The modifier 'override' is not valid for this item + // public override int this[int j] { get => 0; } + Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("override").WithLocation(7, 29), + // (7,29): error CS9282: This member is not allowed in an extension block + // public override int this[int j] { get => 0; } + Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(7, 29)); + } + + [Fact] + public void Validation_Modifiers_Partial() { - public void M3() { } // 1 - public static void M4() { } - public int P3 => 0; // 2 - public static int P4 => 0; - public int this[int j] => 0; // 3 + string source = """ +static class E +{ + extension(int i) + { + partial void M(); + partial void M() { } + partial int P { get; set; } + partial int P { get => 0; set { } } + partial int this[int j] { get; } + partial int this[int j] { get => 0; } } } """; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( - // (12,21): error CS9303: 'M3': cannot declare instance members in an extension block with an unnamed receiver parameter - // public void M3() { } // 1 - Diagnostic(ErrorCode.ERR_InstanceMemberWithUnnamedExtensionsParameter, "M3").WithArguments("M3").WithLocation(12, 21), - // (14,20): error CS9303: 'P3': cannot declare instance members in an extension block with an unnamed receiver parameter - // public int P3 => 0; // 2 - Diagnostic(ErrorCode.ERR_InstanceMemberWithUnnamedExtensionsParameter, "P3").WithArguments("P3").WithLocation(14, 20), - // (16,20): error CS9282: This member is not allowed in an extension block - // public int this[int j] => 0; // 3 - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(16, 20), - // (16,20): error CS9303: 'this[]': cannot declare instance members in an extension block with an unnamed receiver parameter - // public int this[int j] => 0; // 3 - Diagnostic(ErrorCode.ERR_InstanceMemberWithUnnamedExtensionsParameter, "this").WithArguments("this[]").WithLocation(16, 20)); + // (5,22): error CS0751: A partial member must be declared within a partial type + // partial void M(); + Diagnostic(ErrorCode.ERR_PartialMemberOnlyInPartialClass, "M").WithLocation(5, 22), + // (6,22): error CS0751: A partial member must be declared within a partial type + // partial void M() { } + Diagnostic(ErrorCode.ERR_PartialMemberOnlyInPartialClass, "M").WithLocation(6, 22), + // (7,21): error CS0751: A partial member must be declared within a partial type + // partial int P { get; set; } + Diagnostic(ErrorCode.ERR_PartialMemberOnlyInPartialClass, "P").WithLocation(7, 21), + // (9,21): error CS9282: This member is not allowed in an extension block + // partial int this[int j] { get; } + Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(9, 21), + // (9,21): error CS0751: A partial member must be declared within a partial type + // partial int this[int j] { get; } + Diagnostic(ErrorCode.ERR_PartialMemberOnlyInPartialClass, "this").WithLocation(9, 21)); } [Fact] - public void ReceiverParameterValidation_UnnamedReceiverParameter_Ref() + public void Validation_Modifiers_Sealed() { string source = """ static class E { - extension(ref int) + extension(int i) { + sealed void M() { } + sealed int P { get => 0; set { } } + sealed int this[int j] { get => 0; } } - extension(ref string) +} +"""; + var comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics( + // (5,21): error CS0106: The modifier 'sealed' is not valid for this item + // sealed void M() { } + Diagnostic(ErrorCode.ERR_BadMemberFlag, "M").WithArguments("sealed").WithLocation(5, 21), + // (6,20): error CS0106: The modifier 'sealed' is not valid for this item + // sealed int P { get => 0; set { } } + Diagnostic(ErrorCode.ERR_BadMemberFlag, "P").WithArguments("sealed").WithLocation(6, 20), + // (7,20): error CS0106: The modifier 'sealed' is not valid for this item + // sealed int this[int j] { get => 0; } + Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("sealed").WithLocation(7, 20), + // (7,20): error CS9282: This member is not allowed in an extension block + // sealed int this[int j] { get => 0; } + Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(7, 20)); + } + + [Fact] + public void Validation_Modifiers_Readonly() + { + string source = """ +static class E +{ + extension(int i) { + readonly void M() { } + readonly int P { get => 0; set { } } + int P2 { readonly get => 0; readonly set { } } + readonly int this[int j] { get => 0; } } } """; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( - // (3,19): error CS9305: Cannot use modifiers on the unnamed receiver parameter of extension block - // extension(ref int) - Diagnostic(ErrorCode.ERR_ModifierOnUnnamedReceiverParameter, "int").WithLocation(3, 19), - // (6,19): error CS9300: The 'ref' receiver parameter of an extension block must be a value type or a generic type constrained to struct. - // extension(ref string) - Diagnostic(ErrorCode.ERR_RefExtensionParameterMustBeValueTypeOrConstrainedToOne, "string").WithLocation(6, 19), - // (6,19): error CS9305: Cannot use modifiers on the unnamed receiver parameter of extension block - // extension(ref string) - Diagnostic(ErrorCode.ERR_ModifierOnUnnamedReceiverParameter, "string").WithLocation(6, 19)); + // (5,23): error CS0106: The modifier 'readonly' is not valid for this item + // readonly void M() { } + Diagnostic(ErrorCode.ERR_BadMemberFlag, "M").WithArguments("readonly").WithLocation(5, 23), + // (6,22): error CS0106: The modifier 'readonly' is not valid for this item + // readonly int P { get => 0; set { } } + Diagnostic(ErrorCode.ERR_BadMemberFlag, "P").WithArguments("readonly").WithLocation(6, 22), + // (7,27): error CS0106: The modifier 'readonly' is not valid for this item + // int P2 { readonly get => 0; readonly set { } } + Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("readonly").WithLocation(7, 27), + // (7,46): error CS0106: The modifier 'readonly' is not valid for this item + // int P2 { readonly get => 0; readonly set { } } + Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("readonly").WithLocation(7, 46), + // (8,22): error CS0106: The modifier 'readonly' is not valid for this item + // readonly int this[int j] { get => 0; } + Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("readonly").WithLocation(8, 22), + // (8,22): error CS9282: This member is not allowed in an extension block + // readonly int this[int j] { get => 0; } + Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(8, 22)); } [Fact] - public void ReceiverParameterValidation_UnnamedReceiverParameter_Out() + public void Validation_Modifiers_Required() { string source = """ static class E { - extension(out int) + extension(int i) { + required void M() { } + required int P { get => 0; set { } } + required int this[int j] { get => 0; } } } """; - var comp = CreateCompilation(source); + var comp = CreateCompilation(source, targetFramework: TargetFramework.Net90); comp.VerifyEmitDiagnostics( - // (3,15): error CS8328: The parameter modifier 'out' cannot be used with 'extension' - // extension(out int) - Diagnostic(ErrorCode.ERR_BadParameterModifiers, "out").WithArguments("out", "extension").WithLocation(3, 15), - // (3,19): error CS9305: Cannot use modifiers on the unnamed receiver parameter of extension block - // extension(out int) - Diagnostic(ErrorCode.ERR_ModifierOnUnnamedReceiverParameter, "int").WithLocation(3, 19)); + // (5,23): error CS0106: The modifier 'required' is not valid for this item + // required void M() { } + Diagnostic(ErrorCode.ERR_BadMemberFlag, "M").WithArguments("required").WithLocation(5, 23), + // (6,22): error CS0106: The modifier 'required' is not valid for this item + // required int P { get => 0; set { } } + Diagnostic(ErrorCode.ERR_BadMemberFlag, "P").WithArguments("required").WithLocation(6, 22), + // (7,22): error CS0106: The modifier 'required' is not valid for this item + // required int this[int j] { get => 0; } + Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("required").WithLocation(7, 22), + // (7,22): error CS9282: This member is not allowed in an extension block + // required int this[int j] { get => 0; } + Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(7, 22)); } [Fact] - public void ReceiverParameterValidation_UnnamedReceiverParameter_Scoped() + public void Extern_01() { - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : This should probably parse (but still error) string source = """ static class E { - extension(scoped RS) + extension(int i) { + extern void M() { } + extern int P { get => 0; set { } } } } -ref struct RS { } """; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( - // (3,15): error CS0246: The type or namespace name 'scoped' could not be found (are you missing a using directive or an assembly reference?) - // extension(scoped RS) - Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "scoped").WithArguments("scoped").WithLocation(3, 15)); + // (5,21): error CS0179: 'E.extension(int).M()' cannot be extern and declare a body + // extern void M() { } + Diagnostic(ErrorCode.ERR_ExternHasBody, "M").WithArguments("E.extension(int).M()").WithLocation(5, 21), + // (6,24): error CS0179: 'E.extension(int).P.get' cannot be extern and declare a body + // extern int P { get => 0; set { } } + Diagnostic(ErrorCode.ERR_ExternHasBody, "get").WithArguments("E.extension(int).P.get").WithLocation(6, 24), + // (6,34): error CS0179: 'E.extension(int).P.set' cannot be extern and declare a body + // extern int P { get => 0; set { } } + Diagnostic(ErrorCode.ERR_ExternHasBody, "set").WithArguments("E.extension(int).P.set").WithLocation(6, 34)); } [Fact] - public void ReceiverParameterValidation_UnnamedReceiverParameter_FromMetadata() + public void Extern_02() { - // extension(int) - // { - // public void M3() { } - // public static void M4() { } - // public int P3 => 0; - // public static int P4 => 0; - // } - var ilSrc = """ -.class public auto ansi abstract sealed beforefieldinit E - extends [mscorlib]System.Object + var source = """ +using System.Runtime.InteropServices; +static class E { - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + extension(int) + { + [DllImport("something.dll")] + static extern void M(); + static extern int P + { + [DllImport("something.dll")] + get; + [DllImport("something.dll")] + set; + } + } +} +"""; + var verifier = CompileAndVerify(source).VerifyDiagnostics(); + // Note: skeleton methods have "throw" bodies and lack pinvokeimpl/preservesig. Implementation methods have pinvokeimpl/preservesig and no body. + VerifyTypeIL(verifier, "E", """ +.class private auto ansi abstract sealed beforefieldinit E + extends [netstandard]System.Object +{ + .custom instance void [netstandard]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( + 01 00 00 00 + ) + // Nested Types .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' - extends [mscorlib]System.Object + extends [netstandard]System.Object { - .method private hidebysig specialname static void '$' ( int32 '' ) cil managed + // Methods + .method private hidebysig specialname static + void '$' ( + int32 '' + ) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( + 01 00 00 00 + ) + // Method begins at RVA 0x2067 + // Code size 1 (0x1) + .maxstack 8 IL_0000: ret - } - .method public hidebysig instance void M3 () cil managed + } // end of method '<>E__0'::'$' + .method private hidebysig static + void M () cil managed { + // Method begins at RVA 0x2069 + // Code size 2 (0x2) + .maxstack 8 IL_0000: ldnull IL_0001: throw - } - .method public hidebysig static void M4 () cil managed + } // end of method '<>E__0'::M + .method private hidebysig specialname static + int32 get_P () cil managed { + // Method begins at RVA 0x2069 + // Code size 2 (0x2) + .maxstack 8 IL_0000: ldnull IL_0001: throw - } - .method public hidebysig specialname instance int32 get_P3 () cil managed + } // end of method '<>E__0'::get_P + .method private hidebysig specialname static + void set_P ( + int32 'value' + ) cil managed { + // Method begins at RVA 0x2069 + // Code size 2 (0x2) + .maxstack 8 IL_0000: ldnull IL_0001: throw + } // end of method '<>E__0'::set_P + // Properties + .property int32 P() + { + .get int32 E/'<>E__0'::get_P() + .set void E/'<>E__0'::set_P(int32) } - .method public hidebysig specialname static int32 get_P4 () cil managed + } // end of class <>E__0 + // Methods + .method private hidebysig static pinvokeimpl("something.dll" winapi) + void M () cil managed preservesig + { + } // end of method E::M + .method private hidebysig static pinvokeimpl("something.dll" winapi) + int32 get_P () cil managed preservesig + { + } // end of method E::get_P + .method private hidebysig static pinvokeimpl("something.dll" winapi) + void set_P ( + int32 'value' + ) cil managed preservesig + { + } // end of method E::set_P +} // end of class E +"""); + } + + [Fact] + public void Extern_03() + { + var source = """ +using System.Runtime.InteropServices; +static class E +{ + extension(int i) + { + [DllImport("something.dll")] + extern void M(); + + extern int P + { + [DllImport("something.dll")] + get; + [DllImport("something.dll")] + set; + } + } +} +"""; + var comp = CreateCompilation(source); + var verifier = CompileAndVerify(source).VerifyDiagnostics(); + VerifyTypeIL(verifier, "E", """ +.class private auto ansi abstract sealed beforefieldinit E + extends [netstandard]System.Object +{ + .custom instance void [netstandard]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( + 01 00 00 00 + ) + // Nested Types + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [netstandard]System.Object + { + // Methods + .method private hidebysig specialname static + void '$' ( + int32 i + ) cil managed + { + .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( + 01 00 00 00 + ) + // Method begins at RVA 0x2067 + // Code size 1 (0x1) + .maxstack 8 + IL_0000: ret + } // end of method '<>E__0'::'$' + .method private hidebysig + instance void M () cil managed { + // Method begins at RVA 0x2069 + // Code size 2 (0x2) + .maxstack 8 IL_0000: ldnull IL_0001: throw - } - .property instance int32 P3() + } // end of method '<>E__0'::M + .method private hidebysig specialname + instance int32 get_P () cil managed { - .get instance int32 E/'<>E__0'::get_P3() - } - .property int32 P4() + // Method begins at RVA 0x2069 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::get_P + .method private hidebysig specialname + instance void set_P ( + int32 'value' + ) cil managed { - .get int32 E/'<>E__0'::get_P4() + // Method begins at RVA 0x2069 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::set_P + // Properties + .property instance int32 P() + { + .get instance int32 E/'<>E__0'::get_P() + .set instance void E/'<>E__0'::set_P(int32) } - } - .method public hidebysig static void M3 ( int32 '' ) cil managed + } // end of class <>E__0 + // Methods + .method private hidebysig static pinvokeimpl("something.dll" winapi) + void M ( + int32 i + ) cil managed preservesig { - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - IL_0000: ret - } - .method public hidebysig static void M4 () cil managed + .custom instance void [netstandard]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( + 01 00 00 00 + ) + } // end of method E::M + .method private hidebysig static pinvokeimpl("something.dll" winapi) + int32 get_P ( + int32 i + ) cil managed preservesig + { + } // end of method E::get_P + .method private hidebysig static pinvokeimpl("something.dll" winapi) + void set_P ( + int32 i, + int32 'value' + ) cil managed preservesig { - IL_0000: ret + } // end of method E::set_P +} // end of class E +"""); + + source = """ +using System.Runtime.InteropServices; +static class E +{ + [DllImport("something.dll")] + static extern void M(this int i); +} +"""; + comp = CreateCompilation(source); + comp.VerifyEmitDiagnostics(); } - .method public hidebysig static int32 get_P3 ( int32 '' ) cil managed + + [Fact] + public void Extern_04() { - IL_0000: ldc.i4.0 - IL_0001: ret - } - .method public hidebysig static int32 get_P4 () cil managed + var source = """ +using System.Runtime.InteropServices; +static class E +{ + extension(int) { - IL_0000: ldc.i4.0 - IL_0001: ret + [DllImport("something.dll", EntryPoint = "Method1")] + static extern void M(); + + static extern int P + { + [DllImport("something.dll", EntryPoint = "Method2")] + get; + [DllImport("something.dll", EntryPoint = "Method3")] + set; + } } } """; - string source = """ -42.M3(); -int.M4(); -_ = 42.P3; -_ = int.P4; -"""; - var comp = CreateCompilationWithIL(source, ilSrc); - comp.VerifyEmitDiagnostics(); + var verifier = CompileAndVerify(source).VerifyDiagnostics(); + VerifyTypeIL(verifier, "E", """ +.class private auto ansi abstract sealed beforefieldinit E + extends [netstandard]System.Object +{ + .custom instance void [netstandard]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( + 01 00 00 00 + ) + // Nested Types + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [netstandard]System.Object + { + // Methods + .method private hidebysig specialname static + void '$' ( + int32 '' + ) cil managed + { + .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( + 01 00 00 00 + ) + // Method begins at RVA 0x2067 + // Code size 1 (0x1) + .maxstack 8 + IL_0000: ret + } // end of method '<>E__0'::'$' + .method private hidebysig static + void M () cil managed + { + // Method begins at RVA 0x2069 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::M + .method private hidebysig specialname static + int32 get_P () cil managed + { + // Method begins at RVA 0x2069 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::get_P + .method private hidebysig specialname static + void set_P ( + int32 'value' + ) cil managed + { + // Method begins at RVA 0x2069 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::set_P + // Properties + .property int32 P() + { + .get int32 E/'<>E__0'::get_P() + .set void E/'<>E__0'::set_P(int32) + } + } // end of class <>E__0 + // Methods + .method private hidebysig static pinvokeimpl("something.dll" as "Method1" winapi) + void M () cil managed preservesig + { + } // end of method E::M + .method private hidebysig static pinvokeimpl("something.dll" as "Method2" winapi) + int32 get_P () cil managed preservesig + { + } // end of method E::get_P + .method private hidebysig static pinvokeimpl("something.dll" as "Method3" winapi) + void set_P ( + int32 'value' + ) cil managed preservesig + { + } // end of method E::set_P +} // end of class E +"""); } [Fact] - public void AsyncInSecurityCriticalClass() + public void Extern_05() { var source = """ -using System.Security; -using System.Threading.Tasks; - -[SecurityCritical] -public static class C +static class E { extension(int i) { - public async void M() + extern void M(); + extern int P { get; set; } + } +} +"""; + var verifier = CompileAndVerify(source, verify: Verification.FailsPEVerify with { PEVerifyMessage = """ + Error: Method marked Abstract, Runtime, InternalCall or Imported must have zero RVA, and vice versa. + Error: Method marked Abstract, Runtime, InternalCall or Imported must have zero RVA, and vice versa. + Error: Method marked Abstract, Runtime, InternalCall or Imported must have zero RVA, and vice versa. + Type load failed. + """ }); + + verifier.VerifyDiagnostics( + // (5,21): warning CS0626: Method, operator, or accessor 'E.extension(int).M()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. + // extern void M(); + Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M").WithArguments("E.extension(int).M()").WithLocation(5, 21), + // (6,24): warning CS0626: Method, operator, or accessor 'E.extension(int).P.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. + // extern int P { get; set; } + Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("E.extension(int).P.get").WithLocation(6, 24), + // (6,29): warning CS0626: Method, operator, or accessor 'E.extension(int).P.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. + // extern int P { get; set; } + Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("E.extension(int).P.set").WithLocation(6, 29)); + + VerifyTypeIL(verifier, "E", """ +.class private auto ansi abstract sealed beforefieldinit E + extends [netstandard]System.Object +{ + .custom instance void [netstandard]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( + 01 00 00 00 + ) + // Nested Types + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [netstandard]System.Object + { + // Methods + .method private hidebysig specialname static + void '$' ( + int32 i + ) cil managed { - await Task.Factory.StartNew(() => { }); + .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( + 01 00 00 00 + ) + // Method begins at RVA 0x2067 + // Code size 1 (0x1) + .maxstack 8 + IL_0000: ret + } // end of method '<>E__0'::'$' + .method private hidebysig + instance void M () cil managed + { + // Method begins at RVA 0x2069 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::M + .method private hidebysig specialname + instance int32 get_P () cil managed + { + // Method begins at RVA 0x2069 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::get_P + .method private hidebysig specialname + instance void set_P ( + int32 'value' + ) cil managed + { + // Method begins at RVA 0x2069 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::set_P + // Properties + .property instance int32 P() + { + .get instance int32 E/'<>E__0'::get_P() + .set instance void E/'<>E__0'::set_P(int32) } - } + } // end of class <>E__0 + // Methods + .method private hidebysig static + void M ( + int32 i + ) cil managed + { + .custom instance void [netstandard]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( + 01 00 00 00 + ) + } // end of method E::M + .method private hidebysig static + int32 get_P ( + int32 i + ) cil managed + { + } // end of method E::get_P + .method private hidebysig static + void set_P ( + int32 i, + int32 'value' + ) cil managed + { + } // end of method E::set_P +} // end of class E +"""); + + source = """ +class C +{ + extern void M(); } """; - CreateCompilation(source).VerifyDiagnostics( - // (9,27): error CS4031: Async methods are not allowed in an Interface, Class, or Structure which has the 'SecurityCritical' or 'SecuritySafeCritical' attribute. - // public async void M() - Diagnostic(ErrorCode.ERR_SecurityCriticalOrSecuritySafeCriticalOnAsyncInClassOrStruct, "M").WithLocation(9, 27)); + verifier = CompileAndVerify(source, verify: Verification.FailsPEVerify with { PEVerifyMessage = """ + Error: Method marked Abstract, Runtime, InternalCall or Imported must have zero RVA, and vice versa. + Type load failed. + """ }); + + verifier.VerifyDiagnostics( + // (3,17): warning CS0626: Method, operator, or accessor 'C.M()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. + // extern void M(); + Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M").WithArguments("C.M()").WithLocation(3, 17)); + + VerifyTypeIL(verifier, "C", """ +.class private auto ansi beforefieldinit C + extends [netstandard]System.Object +{ + // Methods + .method private hidebysig + instance void M () cil managed + { + } // end of method C::M + .method public hidebysig specialname rtspecialname + instance void .ctor () cil managed + { + // Method begins at RVA 0x2067 + // Code size 7 (0x7) + .maxstack 8 + IL_0000: ldarg.0 + IL_0001: call instance void [netstandard]System.Object::.ctor() + IL_0006: ret + } // end of method C::.ctor +} // end of class C +"""); } [Fact] - public void Validation_Modifiers_Virtual() + public void Extern_06() { - string source = """ + var source = """ static class E { extension(int i) { - public virtual void M() { } - public virtual int P { get => 0; set { } } + static extern void M(); + static extern int P { get; set; } } } """; - var comp = CreateCompilation(source); - comp.VerifyEmitDiagnostics( - // (5,29): error CS0106: The modifier 'virtual' is not valid for this item - // public virtual void M() { } - Diagnostic(ErrorCode.ERR_BadMemberFlag, "M").WithArguments("virtual").WithLocation(5, 29), - // (6,28): error CS0106: The modifier 'virtual' is not valid for this item - // public virtual int P { get => 0; set { } } - Diagnostic(ErrorCode.ERR_BadMemberFlag, "P").WithArguments("virtual").WithLocation(6, 28)); - } + var verifier = CompileAndVerify(source, verify: Verification.FailsPEVerify with { PEVerifyMessage = """ + Error: Method marked Abstract, Runtime, InternalCall or Imported must have zero RVA, and vice versa. + Error: Method marked Abstract, Runtime, InternalCall or Imported must have zero RVA, and vice versa. + Error: Method marked Abstract, Runtime, InternalCall or Imported must have zero RVA, and vice versa. + Type load failed. + """ }); - [Fact] - public void Validation_Modifiers_Abstract() - { - string source = """ -static class E + verifier.VerifyDiagnostics( + // (5,28): warning CS0626: Method, operator, or accessor 'E.extension(int).M()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. + // static extern void M(); + Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M").WithArguments("E.extension(int).M()").WithLocation(5, 28), + // (6,31): warning CS0626: Method, operator, or accessor 'E.extension(int).P.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. + // static extern int P { get; set; } + Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("E.extension(int).P.get").WithLocation(6, 31), + // (6,36): warning CS0626: Method, operator, or accessor 'E.extension(int).P.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. + // static extern int P { get; set; } + Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("E.extension(int).P.set").WithLocation(6, 36)); + + VerifyTypeIL(verifier, "E", """ +.class private auto ansi abstract sealed beforefieldinit E + extends [netstandard]System.Object { - extension(int i) + .custom instance void [netstandard]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( + 01 00 00 00 + ) + // Nested Types + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [netstandard]System.Object { - public abstract void M(); - public abstract int P { get; } - public abstract int P2 { set; } - public abstract int this[int j] { get; } - } -} -"""; - var comp = CreateCompilation(source); - comp.VerifyEmitDiagnostics( - // (5,30): error CS0106: The modifier 'abstract' is not valid for this item - // public abstract void M(); - Diagnostic(ErrorCode.ERR_BadMemberFlag, "M").WithArguments("abstract").WithLocation(5, 30), - // (5,30): error CS0501: 'E.extension(int).M()' must declare a body because it is not marked abstract, extern, or partial - // public abstract void M(); - Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M").WithArguments("E.extension(int).M()").WithLocation(5, 30), - // (6,29): error CS0106: The modifier 'abstract' is not valid for this item - // public abstract int P { get; } - Diagnostic(ErrorCode.ERR_BadMemberFlag, "P").WithArguments("abstract").WithLocation(6, 29), - // (6,29): error CS9282: This member is not allowed in an extension block - // public abstract int P { get; } - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "P").WithLocation(6, 29), - // (7,29): error CS0106: The modifier 'abstract' is not valid for this item - // public abstract int P2 { set; } - Diagnostic(ErrorCode.ERR_BadMemberFlag, "P2").WithArguments("abstract").WithLocation(7, 29), - // (7,29): error CS9282: This member is not allowed in an extension block - // public abstract int P2 { set; } - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "P2").WithLocation(7, 29), - // (7,34): error CS8051: Auto-implemented properties must have get accessors. - // public abstract int P2 { set; } - Diagnostic(ErrorCode.ERR_AutoPropertyMustHaveGetAccessor, "set").WithLocation(7, 34), - // (8,29): error CS0106: The modifier 'abstract' is not valid for this item - // public abstract int this[int j] { get; } - Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract").WithLocation(8, 29), - // (8,29): error CS9282: This member is not allowed in an extension block - // public abstract int this[int j] { get; } - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(8, 29), - // (8,43): error CS0501: 'E.extension(int).this[int].get' must declare a body because it is not marked abstract, extern, or partial - // public abstract int this[int j] { get; } - Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("E.extension(int).this[int].get").WithLocation(8, 43)); + // Methods + .method private hidebysig specialname static + void '$' ( + int32 i + ) cil managed + { + .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( + 01 00 00 00 + ) + // Method begins at RVA 0x2067 + // Code size 1 (0x1) + .maxstack 8 + IL_0000: ret + } // end of method '<>E__0'::'$' + .method private hidebysig static + void M () cil managed + { + // Method begins at RVA 0x2069 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::M + .method private hidebysig specialname static + int32 get_P () cil managed + { + // Method begins at RVA 0x2069 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::get_P + .method private hidebysig specialname static + void set_P ( + int32 'value' + ) cil managed + { + // Method begins at RVA 0x2069 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::set_P + // Properties + .property int32 P() + { + .get int32 E/'<>E__0'::get_P() + .set void E/'<>E__0'::set_P(int32) + } + } // end of class <>E__0 + // Methods + .method private hidebysig static + void M () cil managed + { + } // end of method E::M + .method private hidebysig static + int32 get_P () cil managed + { + } // end of method E::get_P + .method private hidebysig static + void set_P ( + int32 'value' + ) cil managed + { + } // end of method E::set_P +} // end of class E +"""); } [Fact] - public void Validation_Modifiers_New() + public void Extern_07() { - string source = """ + var source = """ static class E { extension(int i) { - public new string ToString() => ""; - public new int P { get => 0; } - public new int this[int j] { get => 0; } + extern int this[int j] { get => 0; } } } """; - var comp = CreateCompilation(source); - comp.VerifyEmitDiagnostics( - // (5,27): error CS0106: The modifier 'new' is not valid for this item - // public new string ToString() => ""; - Diagnostic(ErrorCode.ERR_BadMemberFlag, "ToString").WithArguments("new").WithLocation(5, 27), - // (6,24): error CS0106: The modifier 'new' is not valid for this item - // public new int P { get => 0; } - Diagnostic(ErrorCode.ERR_BadMemberFlag, "P").WithArguments("new").WithLocation(6, 24), - // (7,24): error CS0106: The modifier 'new' is not valid for this item - // public new int this[int j] { get => 0; } - Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("new").WithLocation(7, 24), - // (7,24): error CS9282: This member is not allowed in an extension block - // public new int this[int j] { get => 0; } - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(7, 24)); + CreateCompilation(source).VerifyEmitDiagnostics( + // (5,20): error CS9282: This member is not allowed in an extension block + // extern int this[int j] { get => 0; } + Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(5, 20), + // (5,34): error CS0179: 'E.extension(int).this[int].get' cannot be extern and declare a body + // extern int this[int j] { get => 0; } + Diagnostic(ErrorCode.ERR_ExternHasBody, "get").WithArguments("E.extension(int).this[int].get").WithLocation(5, 34)); } [Fact] - public void Validation_Modifiers_Override() + public void Extern_08() { - string source = """ + var source = """ static class E { extension(int i) { - public override string ToString() => ""; - public override int P { get => 0; } - public override int this[int j] { get => 0; } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)] + static extern void M(); + + static extern int P + { + [method: System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)] + get; + + [method: System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)] + set; + } } } """; var comp = CreateCompilation(source); - comp.VerifyEmitDiagnostics( - // (5,32): error CS0106: The modifier 'override' is not valid for this item - // public override string ToString() => ""; - Diagnostic(ErrorCode.ERR_BadMemberFlag, "ToString").WithArguments("override").WithLocation(5, 32), - // (6,29): error CS0106: The modifier 'override' is not valid for this item - // public override int P { get => 0; } - Diagnostic(ErrorCode.ERR_BadMemberFlag, "P").WithArguments("override").WithLocation(6, 29), - // (7,29): error CS0106: The modifier 'override' is not valid for this item - // public override int this[int j] { get => 0; } - Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("override").WithLocation(7, 29), - // (7,29): error CS9282: This member is not allowed in an extension block - // public override int this[int j] { get => 0; } - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(7, 29)); + + // Note: skeleton methods have "throw" bodies and lack internalcall. Implementation methods have internalcall and no body. + var verifier = CompileAndVerify(comp).VerifyDiagnostics(); + VerifyTypeIL(verifier, "E", """ +.class private auto ansi abstract sealed beforefieldinit E + extends [netstandard]System.Object +{ + .custom instance void [netstandard]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( + 01 00 00 00 + ) + // Nested Types + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [netstandard]System.Object + { + // Methods + .method private hidebysig specialname static + void '$' ( + int32 i + ) cil managed + { + .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( + 01 00 00 00 + ) + // Method begins at RVA 0x2067 + // Code size 1 (0x1) + .maxstack 8 + IL_0000: ret + } // end of method '<>E__0'::'$' + .method private hidebysig static + void M () cil managed + { + // Method begins at RVA 0x2069 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::M + .method private hidebysig specialname static + int32 get_P () cil managed + { + // Method begins at RVA 0x2069 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::get_P + .method private hidebysig specialname static + void set_P ( + int32 'value' + ) cil managed + { + // Method begins at RVA 0x2069 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::set_P + // Properties + .property int32 P() + { + .get int32 E/'<>E__0'::get_P() + .set void E/'<>E__0'::set_P(int32) + } + } // end of class <>E__0 + // Methods + .method private hidebysig static + void M () cil managed internalcall + { + } // end of method E::M + .method private hidebysig static + int32 get_P () cil managed internalcall + { + } // end of method E::get_P + .method private hidebysig static + void set_P ( + int32 'value' + ) cil managed internalcall + { + } // end of method E::set_P +} // end of class E +"""); } [Fact] - public void Validation_Modifiers_Partial() + public void Extern_09() { - string source = """ + var source = """ static class E { extension(int i) { - partial void M(); - partial void M() { } - partial int P { get; set; } - partial int P { get => 0; set { } } - partial int this[int j] { get; } - partial int this[int j] { get => 0; } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)] + extern void M(); + + extern int P + { + [method: System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)] + get; + + [method: System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)] + set; + } } } """; var comp = CreateCompilation(source); - comp.VerifyEmitDiagnostics( - // (5,22): error CS0751: A partial member must be declared within a partial type - // partial void M(); - Diagnostic(ErrorCode.ERR_PartialMemberOnlyInPartialClass, "M").WithLocation(5, 22), - // (6,22): error CS0751: A partial member must be declared within a partial type - // partial void M() { } - Diagnostic(ErrorCode.ERR_PartialMemberOnlyInPartialClass, "M").WithLocation(6, 22), - // (7,21): error CS0751: A partial member must be declared within a partial type - // partial int P { get; set; } - Diagnostic(ErrorCode.ERR_PartialMemberOnlyInPartialClass, "P").WithLocation(7, 21), - // (9,21): error CS9282: This member is not allowed in an extension block - // partial int this[int j] { get; } - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(9, 21), - // (9,21): error CS0751: A partial member must be declared within a partial type - // partial int this[int j] { get; } - Diagnostic(ErrorCode.ERR_PartialMemberOnlyInPartialClass, "this").WithLocation(9, 21)); + + var verifier = CompileAndVerify(comp).VerifyDiagnostics(); + VerifyTypeIL(verifier, "E", """ +.class private auto ansi abstract sealed beforefieldinit E + extends [netstandard]System.Object +{ + .custom instance void [netstandard]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( + 01 00 00 00 + ) + // Nested Types + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [netstandard]System.Object + { + // Methods + .method private hidebysig specialname static + void '$' ( + int32 i + ) cil managed + { + .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( + 01 00 00 00 + ) + // Method begins at RVA 0x2067 + // Code size 1 (0x1) + .maxstack 8 + IL_0000: ret + } // end of method '<>E__0'::'$' + .method private hidebysig + instance void M () cil managed + { + // Method begins at RVA 0x2069 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::M + .method private hidebysig specialname + instance int32 get_P () cil managed + { + // Method begins at RVA 0x2069 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::get_P + .method private hidebysig specialname + instance void set_P ( + int32 'value' + ) cil managed + { + // Method begins at RVA 0x2069 + // Code size 2 (0x2) + .maxstack 8 + IL_0000: ldnull + IL_0001: throw + } // end of method '<>E__0'::set_P + // Properties + .property instance int32 P() + { + .get instance int32 E/'<>E__0'::get_P() + .set instance void E/'<>E__0'::set_P(int32) + } + } // end of class <>E__0 + // Methods + .method private hidebysig static + void M ( + int32 i + ) cil managed internalcall + { + .custom instance void [netstandard]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( + 01 00 00 00 + ) + } // end of method E::M + .method private hidebysig static + int32 get_P ( + int32 i + ) cil managed internalcall + { + } // end of method E::get_P + .method private hidebysig static + void set_P ( + int32 i, + int32 'value' + ) cil managed internalcall + { + } // end of method E::set_P +} // end of class E +"""); } [Fact] - public void Validation_Modifiers_Sealed() + public void Extern_10() { - string source = """ + var source = """ +using System.Runtime.InteropServices; static class E { extension(int i) { - sealed void M() { } - sealed int P { get => 0; set { } } - sealed int this[int j] { get => 0; } + [DllImport("something.dll")] + void M() { } + + int P + { + [DllImport("something.dll")] + get => 0; + [DllImport("something.dll")] + set { } + } } } """; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( - // (5,21): error CS0106: The modifier 'sealed' is not valid for this item - // sealed void M() { } - Diagnostic(ErrorCode.ERR_BadMemberFlag, "M").WithArguments("sealed").WithLocation(5, 21), - // (6,20): error CS0106: The modifier 'sealed' is not valid for this item - // sealed int P { get => 0; set { } } - Diagnostic(ErrorCode.ERR_BadMemberFlag, "P").WithArguments("sealed").WithLocation(6, 20), - // (7,20): error CS0106: The modifier 'sealed' is not valid for this item - // sealed int this[int j] { get => 0; } - Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("sealed").WithLocation(7, 20), - // (7,20): error CS9282: This member is not allowed in an extension block - // sealed int this[int j] { get => 0; } - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(7, 20)); + // (6,10): error CS0601: The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member + // [DllImport("something.dll")] + Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(6, 10), + // (11,14): error CS0601: The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member + // [DllImport("something.dll")] + Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(11, 14), + // (13,14): error CS0601: The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member + // [DllImport("something.dll")] + Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(13, 14)); } [Fact] - public void Validation_Modifiers_Readonly() + public void Extern_11() { - string source = """ + var source = """ +using System.Runtime.InteropServices; static class E { extension(int i) { - readonly void M() { } - readonly int P { get => 0; set { } } - int P2 { readonly get => 0; readonly set { } } - readonly int this[int j] { get => 0; } + [DllImport("something.dll")] + extern void M() { } + + extern int P + { + [DllImport("something.dll")] + get => 0; + [DllImport("something.dll")] + set { } + } } } """; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( - // (5,23): error CS0106: The modifier 'readonly' is not valid for this item - // readonly void M() { } - Diagnostic(ErrorCode.ERR_BadMemberFlag, "M").WithArguments("readonly").WithLocation(5, 23), - // (6,22): error CS0106: The modifier 'readonly' is not valid for this item - // readonly int P { get => 0; set { } } - Diagnostic(ErrorCode.ERR_BadMemberFlag, "P").WithArguments("readonly").WithLocation(6, 22), - // (7,27): error CS0106: The modifier 'readonly' is not valid for this item - // int P2 { readonly get => 0; readonly set { } } - Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("readonly").WithLocation(7, 27), - // (7,46): error CS0106: The modifier 'readonly' is not valid for this item - // int P2 { readonly get => 0; readonly set { } } - Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("readonly").WithLocation(7, 46), - // (8,22): error CS0106: The modifier 'readonly' is not valid for this item - // readonly int this[int j] { get => 0; } - Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("readonly").WithLocation(8, 22), - // (8,22): error CS9282: This member is not allowed in an extension block - // readonly int this[int j] { get => 0; } - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(8, 22)); + // (7,21): error CS0179: 'E.extension(int).M()' cannot be extern and declare a body + // extern void M() { } + Diagnostic(ErrorCode.ERR_ExternHasBody, "M").WithArguments("E.extension(int).M()").WithLocation(7, 21), + // (12,13): error CS0179: 'E.extension(int).P.get' cannot be extern and declare a body + // get => 0; + Diagnostic(ErrorCode.ERR_ExternHasBody, "get").WithArguments("E.extension(int).P.get").WithLocation(12, 13), + // (14,13): error CS0179: 'E.extension(int).P.set' cannot be extern and declare a body + // set { } + Diagnostic(ErrorCode.ERR_ExternHasBody, "set").WithArguments("E.extension(int).P.set").WithLocation(14, 13)); } [Fact] - public void Validation_Modifiers_Required() + public void Extern_12() { - string source = """ + var source = """ +using System.Runtime.InteropServices; static class E { - extension(int i) + extension(int) { - required void M() { } - required int P { get => 0; set { } } - required int this[int j] { get => 0; } + int P + { + [DllImport("something.dll")] + extern get; // 1 + [DllImport("something.dll")] + extern set; // 2 + } } } -"""; - var comp = CreateCompilation(source, targetFramework: TargetFramework.Net90); - comp.VerifyEmitDiagnostics( - // (5,23): error CS0106: The modifier 'required' is not valid for this item - // required void M() { } - Diagnostic(ErrorCode.ERR_BadMemberFlag, "M").WithArguments("required").WithLocation(5, 23), - // (6,22): error CS0106: The modifier 'required' is not valid for this item - // required int P { get => 0; set { } } - Diagnostic(ErrorCode.ERR_BadMemberFlag, "P").WithArguments("required").WithLocation(6, 22), - // (7,22): error CS0106: The modifier 'required' is not valid for this item - // required int this[int j] { get => 0; } - Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("required").WithLocation(7, 22), - // (7,22): error CS9282: This member is not allowed in an extension block - // required int this[int j] { get => 0; } - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(7, 22)); - } - [Fact] - public void Validation_Modifiers_Extern() - { - string source = """ -static class E +static class C { - extension(int i) + static int P { - extern void M() { } - extern int P { get => 0; set { } } - extern int this[int j] { get => 0; } + [DllImport("something.dll")] + extern get; // 3 + [DllImport("something.dll")] + extern set; // 4 } } """; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( - // (5,21): error CS0106: The modifier 'extern' is not valid for this item - // extern void M() { } - Diagnostic(ErrorCode.ERR_BadMemberFlag, "M").WithArguments("extern").WithLocation(5, 21), - // (6,20): error CS0106: The modifier 'extern' is not valid for this item - // extern int P { get => 0; set { } } - Diagnostic(ErrorCode.ERR_BadMemberFlag, "P").WithArguments("extern").WithLocation(6, 20), - // (7,20): error CS0106: The modifier 'extern' is not valid for this item - // extern int this[int j] { get => 0; } - Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("extern").WithLocation(7, 20), - // (7,20): error CS9282: This member is not allowed in an extension block - // extern int this[int j] { get => 0; } - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "this").WithLocation(7, 20)); + // (6,13): error CS9282: This member is not allowed in an extension block + // int P + Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "P").WithLocation(6, 13), + // (6,13): error CS9303: 'P': cannot declare instance members in an extension block with an unnamed receiver parameter + // int P + Diagnostic(ErrorCode.ERR_InstanceMemberWithUnnamedExtensionsParameter, "P").WithArguments("P").WithLocation(6, 13), + // (8,14): error CS0601: The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member + // [DllImport("something.dll")] + Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(8, 14), + // (9,20): error CS0106: The modifier 'extern' is not valid for this item + // extern get; // 1 + Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("extern").WithLocation(9, 20), + // (10,14): error CS0601: The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member + // [DllImport("something.dll")] + Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(10, 14), + // (11,20): error CS0106: The modifier 'extern' is not valid for this item + // extern set; // 2 + Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("extern").WithLocation(11, 20), + // (20,10): error CS0601: The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member + // [DllImport("something.dll")] + Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(20, 10), + // (21,16): error CS0106: The modifier 'extern' is not valid for this item + // extern get; // 3 + Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("extern").WithLocation(21, 16), + // (22,10): error CS0601: The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member + // [DllImport("something.dll")] + Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(22, 10), + // (23,16): error CS0106: The modifier 'extern' is not valid for this item + // extern set; // 4 + Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("extern").WithLocation(23, 16)); } [Fact] @@ -36703,7 +38720,7 @@ static class E Assert.Equal("<>E__0", comp.GetTypeByMetadataName("E").GetTypeMembers().Single().ExtensionName); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : we should find the unspeakable nested type + // Tracked by https://github.com/dotnet/roslyn/issues/78968 : we should find the unspeakable nested type Assert.Null(comp.GetTypeByMetadataName("E+<>E__0")); } @@ -39655,7 +41672,6 @@ class C public object? P => null; } """; - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : we shouldn't care about static/instance mismatch in nameof comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); comp.VerifyEmitDiagnostics( // (5,5): warning CS8602: Dereference of a possibly null reference. @@ -39698,7 +41714,10 @@ static class E Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o.P").WithLocation(7, 5), // (13,73): error CS8082: Sub-expression cannot be used in an argument to nameof. // [System.Diagnostics.CodeAnalysis.MemberNotNullWhen(true, nameof(new object().P))] - Diagnostic(ErrorCode.ERR_SubexpressionNotInNameof, "new object()").WithLocation(13, 73)); + Diagnostic(ErrorCode.ERR_SubexpressionNotInNameof, "new object()").WithLocation(13, 73), + // (13,73): error CS9316: Extension members are not allowed as an argument to 'nameof'. + // [System.Diagnostics.CodeAnalysis.MemberNotNullWhen(true, nameof(new object().P))] + Diagnostic(ErrorCode.ERR_NameofExtensionMember, "new object().P").WithLocation(13, 73)); src = """ class E @@ -39756,7 +41775,10 @@ static class E } """; comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); - comp.VerifyEmitDiagnostics(); + comp.VerifyEmitDiagnostics( + // (7,73): error CS9316: Extension members are not allowed as an argument to 'nameof'. + // [System.Diagnostics.CodeAnalysis.MemberNotNullWhen(true, nameof(object.P))] + Diagnostic(ErrorCode.ERR_NameofExtensionMember, "object.P").WithLocation(7, 73)); } [Fact] @@ -40232,11 +42254,17 @@ public class MyCollection : IEnumerable IEnumerator IEnumerable.GetEnumerator() => throw null!; } """; - // Tracked by https://github.com/dotnet/roslyn/issues/78828 : missing nullability diagnostic var comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics(); + comp.VerifyEmitDiagnostics( + // (7,19): warning CS8604: Possible null reference argument for parameter 'o' in 'void extension(MyCollection).Add(object o)'. + // MyCollection c = [oNull, oNotNull]; + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "oNull").WithArguments("o", "void extension(MyCollection).Add(object o)").WithLocation(7, 19)); + } - src = """ + [Fact] + public void Nullability_CollectionExpression_Add_01_Classic() + { + var src = """ #nullable enable using System.Collections; using System.Collections.Generic; @@ -40256,15 +42284,75 @@ public class MyCollection : IEnumerable IEnumerator IEnumerable.GetEnumerator() => throw null!; } """; - // Tracked by https://github.com/dotnet/roslyn/issues/78452 : assertion hit during nullability analysis - try - { - comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics(); - } - catch (InvalidOperationException) - { - } + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (7,19): warning CS8604: Possible null reference argument for parameter 'o' in 'void E.Add(MyCollection c, object o)'. + // MyCollection c = [oNull, oNotNull]; + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "oNull").WithArguments("o", "void E.Add(MyCollection c, object o)").WithLocation(7, 19)); + } + + [Fact] + public void Nullability_CollectionExpression_Add_02() + { + var src = """ +#nullable enable +using System.Collections; +using System.Collections.Generic; + +object? oNull = null; +object oNotNull = new object(); +MyCollection c = [oNull, oNotNull]; + +static class E +{ + extension(MyCollection c) + { + public void Add(T o) { } + } +} + +public class MyCollection : IEnumerable +{ + IEnumerator IEnumerable.GetEnumerator() => throw null!; + IEnumerator IEnumerable.GetEnumerator() => throw null!; +} +"""; + // https://github.com/dotnet/roslyn/issues/78960 + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (7,26): error CS9215: Collection expression type 'MyCollection' must have an instance or extension method 'Add' that can be called with a single argument. + // MyCollection c = [oNull, oNotNull]; + Diagnostic(ErrorCode.ERR_CollectionExpressionMissingAdd, "[oNull, oNotNull]").WithArguments("MyCollection").WithLocation(7, 26), + // (7,26): error CS1929: 'MyCollection' does not contain a definition for 'Add' and the best extension method overload 'E.extension(MyCollection).Add(T)' requires a receiver of type 'MyCollection' + // MyCollection c = [oNull, oNotNull]; + Diagnostic(ErrorCode.ERR_BadInstanceArgType, "[oNull, oNotNull]").WithArguments("MyCollection", "Add", "E.extension(MyCollection).Add(T)", "MyCollection").WithLocation(7, 26)); + } + + [Fact] + public void Nullability_CollectionExpression_Add_02_Classic() + { + var src = """ +#nullable enable +using System.Collections; +using System.Collections.Generic; + +object? oNull = null; +object oNotNull = new object(); +MyCollection c = [oNull, oNotNull]; + +static class E +{ + public static void Add(this MyCollection c, T o) { } +} + +public class MyCollection : IEnumerable +{ + IEnumerator IEnumerable.GetEnumerator() => throw null!; + IEnumerator IEnumerable.GetEnumerator() => throw null!; +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); } [Fact] @@ -40936,6 +43024,81 @@ .method public hidebysig static void M () cil managed Assert.False(comp.GlobalNamespace.GetTypeMember("E").GetTypeMembers().Single().IsExtension); } + [Fact] + public void SpecialName_04() + { + var src = """ +static class E +{ + extension(int i) + { + [System.Runtime.CompilerServices.SpecialName] + public void M() => throw null!; + + public void M2() => throw null!; + + [System.Runtime.CompilerServices.SpecialName] + public int P => throw null!; + + public int P2 => throw null!; + } + + [System.Runtime.CompilerServices.SpecialName] + public static void M3() => throw null!; +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var extension = comp.GlobalNamespace.GetTypeMember("E").GetTypeMembers().Single(); + Assert.True(extension.GetMember("M").HasSpecialName); + Assert.False(extension.GetMember("M2").HasSpecialName); + + Assert.True(extension.GetMember("P").HasSpecialName); + Assert.True(extension.GetMember("get_P").HasSpecialName); + + Assert.False(extension.GetMember("P2").HasSpecialName); + Assert.True(extension.GetMember("get_P2").HasSpecialName); + + Assert.True(comp.GetMember("E.M").HasSpecialName); + Assert.False(comp.GetMember("E.M2").HasSpecialName); + Assert.True(comp.GetMember("E.M3").HasSpecialName); + + Assert.False(comp.GetMember("E.get_P").HasSpecialName); + + Assert.False(comp.GetMember("E.get_P2").HasSpecialName); + } + + [Fact] + public void SpecialName_05() + { + var src = """ +static class E +{ + extension(int i) + { + public int P + { + [System.Runtime.CompilerServices.SpecialName] + get => 0; + [System.Runtime.CompilerServices.SpecialName] + set { } + } + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var extension = comp.GlobalNamespace.GetTypeMember("E").GetTypeMembers().Single(); + Assert.False(extension.GetMember("P").HasSpecialName); + Assert.True(extension.GetMember("get_P").HasSpecialName); + Assert.True(extension.GetMember("set_P").HasSpecialName); + + Assert.True(comp.GetMember("E.get_P").HasSpecialName); + Assert.True(comp.GetMember("E.set_P").HasSpecialName); + } + [Fact] public void WellKnownAttribute_SkipLocalsInit_01() { @@ -41122,7 +43285,7 @@ string print(XmlNameAttributeSyntax name) } } - private static IEnumerable PrintXmlCrefSymbols(SyntaxTree tree, SemanticModel model) + internal static IEnumerable PrintXmlCrefSymbols(SyntaxTree tree, SemanticModel model) { var docComments = tree.GetCompilationUnitRoot().DescendantTrivia().Select(trivia => trivia.GetStructure()).OfType(); var crefs = docComments.SelectMany(doc => doc.DescendantNodes().OfType()); diff --git a/src/Compilers/CSharp/Test/Emit3/Semantics/ExtensionTests2.cs b/src/Compilers/CSharp/Test/Emit3/Semantics/ExtensionTests2.cs index 3026f4bc56e36..b94373fe522ca 100644 --- a/src/Compilers/CSharp/Test/Emit3/Semantics/ExtensionTests2.cs +++ b/src/Compilers/CSharp/Test/Emit3/Semantics/ExtensionTests2.cs @@ -584,7 +584,7 @@ public void AnonymousType_01() var person = new { Name = "John", Age = 30 }; person.M(); person.M2(); -_ = person.P; +_ = person.Property; public static class E { @@ -597,12 +597,32 @@ public static class E public static void M2(this T t) { System.Console.Write("method2 "); } } """; - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : should work var comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics( - // (4,12): error CS1061: '' does not contain a definition for 'P' and no accessible extension method 'P' accepting a first argument of type '' could be found (are you missing a using directive or an assembly reference?) - // _ = person.P; - Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "P").WithArguments("", "P").WithLocation(4, 12)); + CompileAndVerify(comp, expectedOutput: "method method2 property").VerifyDiagnostics(); + } + + [Fact] + public void AnonymousType_02() + { + // instance members come first + var src = """ +System.Action a = () => { System.Console.Write("method "); }; +var person = new { DoStuff = a, Property = 42 }; + +person.DoStuff(); +System.Console.Write(person.Property); + +public static class E +{ + extension(T t) + { + public void DoStuff() => throw null; + public int Property => throw null; + } +} +"""; + var comp = CreateCompilation(src); + CompileAndVerify(comp, expectedOutput: "method 42").VerifyDiagnostics(); } [Fact] @@ -2388,7 +2408,7 @@ static class E2 """; var comp = CreateCompilation(src); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : the diagnostic should describe what went wrong + // Tracked by https://github.com/dotnet/roslyn/issues/78830 : diagnostic quality, the diagnostic should describe what went wrong comp.VerifyEmitDiagnostics( // (1,9): error CS9286: 'object' does not contain a definition for 'M' and no accessible extension member 'M' for receiver of type 'object' could be found (are you missing a using directive or an assembly reference?) // var x = object.M; // 1 @@ -2645,24 +2665,24 @@ public void PEMethodSymbol_GetUseSiteInfo() // missing implementation method for M var ilSrc = """ .class public auto ansi abstract sealed beforefieldinit E - extends [mscorlib]System.Object + extends [mscorlib]System.Object { - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' - extends [mscorlib]System.Object - { - .method private hidebysig specialname static void '$' ( int32 '' ) cil managed - { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - IL_0000: ret - } + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + .method private hidebysig specialname static void '$' ( int32 '' ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } - .method public hidebysig static void M () cil managed - { - IL_0000: ldnull - IL_0001: throw - } - } + .method public hidebysig static void M () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + } } """; var src = """ @@ -2714,24 +2734,24 @@ public void PENamedTypeSymbol_01(string accessibility) // Accessibility of extension marker is not private var ilSrc = $$""" .class public auto ansi abstract sealed beforefieldinit E - extends [mscorlib]System.Object -{ - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' - extends [mscorlib]System.Object - { - .method {{accessibility}} hidebysig specialname static void '$' ( int32 '' ) cil managed - { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - IL_0000: ret - } - - .method public hidebysig static void M () cil managed - { - IL_0000: ldnull - IL_0001: throw - } - } + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + .method {{accessibility}} hidebysig specialname static void '$' ( int32 '' ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } + + .method public hidebysig static void M () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + } .method public hidebysig static void M () cil managed { @@ -2763,24 +2783,24 @@ public void PENamedTypeSymbol_02() // Accessibility of extension marker is not private, instance extension method var ilSrc = $$""" .class public auto ansi abstract sealed beforefieldinit E - extends [mscorlib]System.Object -{ - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' - extends [mscorlib]System.Object - { - .method public hidebysig specialname static void '$' ( int32 i ) cil managed - { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - IL_0000: ret - } - - .method public hidebysig instance void M () cil managed - { - IL_0000: ldnull - IL_0001: throw - } - } + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + .method public hidebysig specialname static void '$' ( int32 i ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } + + .method public hidebysig instance void M () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + } .method public hidebysig static void M ( int32 i ) cil managed { @@ -2805,24 +2825,24 @@ public void PENamedTypeSymbol_03() // Extension marker method is generic var ilSrc = """ .class public auto ansi abstract sealed beforefieldinit E - extends [mscorlib]System.Object -{ - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' - extends [mscorlib]System.Object - { - .method private hidebysig specialname static void '$' ( int32 '' ) cil managed - { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - IL_0000: ret - } - - .method public hidebysig static void M () cil managed - { - IL_0000: ldnull - IL_0001: throw - } - } + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + .method private hidebysig specialname static void '$' ( int32 '' ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } + + .method public hidebysig static void M () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + } .method public hidebysig static void M () cil managed { @@ -2847,24 +2867,24 @@ public void PENamedTypeSymbol_04() // Extension marker method is not static var ilSrc = """ .class public auto ansi abstract sealed beforefieldinit E - extends [mscorlib]System.Object -{ - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' - extends [mscorlib]System.Object - { - .method private hidebysig specialname void '$' ( int32 '' ) cil managed - { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - IL_0000: ret - } - - .method public hidebysig static void M () cil managed - { - IL_0000: ldnull - IL_0001: throw - } - } + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + .method private hidebysig specialname void '$' ( int32 '' ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } + + .method public hidebysig static void M () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + } .method public hidebysig static void M () cil managed { @@ -2889,25 +2909,25 @@ public void PENamedTypeSymbol_05() // Extension marker doesn't return void var ilSrc = """ .class public auto ansi abstract sealed beforefieldinit E - extends [mscorlib]System.Object -{ - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' - extends [mscorlib]System.Object - { - .method private hidebysig specialname static int32 '$' ( int32 '' ) cil managed - { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + .method private hidebysig specialname static int32 '$' ( int32 '' ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) IL_0000: ldc.i4.0 IL_0001: ret - } + } - .method public hidebysig static void M () cil managed - { - IL_0000: ldnull - IL_0001: throw - } - } + .method public hidebysig static void M () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + } .method public hidebysig static void M () cil managed { @@ -2932,24 +2952,24 @@ public void PENamedTypeSymbol_06() // Extension marker lacks its parameter var ilSrc = """ .class public auto ansi abstract sealed beforefieldinit E - extends [mscorlib]System.Object -{ - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' - extends [mscorlib]System.Object - { - .method private hidebysig specialname static void '$' () cil managed - { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - IL_0000: ret - } - - .method public hidebysig static void M () cil managed - { - IL_0000: ldnull - IL_0001: throw - } - } + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + .method private hidebysig specialname static void '$' () cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } + + .method public hidebysig static void M () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + } .method public hidebysig static void M () cil managed { @@ -2974,24 +2994,24 @@ public void PENamedTypeSymbol_07() // Extension marker has an extra parameter var ilSrc = """ .class public auto ansi abstract sealed beforefieldinit E - extends [mscorlib]System.Object -{ - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' - extends [mscorlib]System.Object - { - .method private hidebysig specialname static void '$' ( int32 '', string s ) cil managed - { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - IL_0000: ret - } - - .method public hidebysig static void M () cil managed - { - IL_0000: ldnull - IL_0001: throw - } - } + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + .method private hidebysig specialname static void '$' ( int32 '', string s ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } + + .method public hidebysig static void M () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + } .method public hidebysig static void M () cil managed { @@ -3050,30 +3070,30 @@ public void PENamedTypeSymbol_09() // Two extension markers var ilSrc = """ .class public auto ansi abstract sealed beforefieldinit E - extends [mscorlib]System.Object -{ - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' - extends [mscorlib]System.Object - { - .method private hidebysig specialname static void '$' ( int32 '' ) cil managed - { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - IL_0000: ret - } - - .method private hidebysig specialname static void '$' ( string '' ) cil managed - { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - IL_0000: ret - } - - .method public hidebysig static void M () cil managed - { - IL_0000: ldnull - IL_0001: throw - } - } + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + .method private hidebysig specialname static void '$' ( int32 '' ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } + + .method private hidebysig specialname static void '$' ( string '' ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } + + .method public hidebysig static void M () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + } .method public hidebysig static void M () cil managed { @@ -3098,24 +3118,24 @@ public void PENamedTypeSymbol_10() // Arity mismatch between skeleton and implementation var ilSrc = """ .class public auto ansi abstract sealed beforefieldinit E - extends [mscorlib]System.Object -{ - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' - extends [mscorlib]System.Object - { - .method private hidebysig specialname static void '$' ( int32 '' ) cil managed - { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - IL_0000: ret - } - - .method public hidebysig static void M () cil managed - { - IL_0000: ldnull - IL_0001: throw - } - } + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + .method private hidebysig specialname static void '$' ( int32 '' ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } + + .method public hidebysig static void M () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + } .method public hidebysig static void M () cil managed { @@ -3140,24 +3160,24 @@ public void PENamedTypeSymbol_11() // Accessibility mismatch between skeleton and implementation var ilSrc = """ .class public auto ansi abstract sealed beforefieldinit E - extends [mscorlib]System.Object -{ - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' - extends [mscorlib]System.Object - { - .method private hidebysig specialname static void '$' ( int32 '' ) cil managed - { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - IL_0000: ret - } - - .method public hidebysig static void M () cil managed - { - IL_0000: ldnull - IL_0001: throw - } - } + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + .method private hidebysig specialname static void '$' ( int32 '' ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } + + .method public hidebysig static void M () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + } .method assembly hidebysig static void M () cil managed { @@ -3182,24 +3202,24 @@ public void PENamedTypeSymbol_12() // parameter count mismatch between skeleton and implementation var ilSrc = """ .class public auto ansi abstract sealed beforefieldinit E - extends [mscorlib]System.Object -{ - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' - extends [mscorlib]System.Object - { - .method private hidebysig specialname static void '$' ( int32 '' ) cil managed - { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - IL_0000: ret - } - - .method public hidebysig static void M () cil managed - { - IL_0000: ldnull - IL_0001: throw - } - } + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + .method private hidebysig specialname static void '$' ( int32 '' ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } + + .method public hidebysig static void M () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + } .method public hidebysig static void M (string s) cil managed { @@ -3224,24 +3244,24 @@ public void PENamedTypeSymbol_13() // return type mismatch between skeleton and implementation var ilSrc = """ .class public auto ansi abstract sealed beforefieldinit E - extends [mscorlib]System.Object -{ - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' - extends [mscorlib]System.Object - { - .method private hidebysig specialname static void '$' ( int32 '' ) cil managed - { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - IL_0000: ret - } - - .method public hidebysig static void M () cil managed - { - IL_0000: ldnull - IL_0001: throw - } - } + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + .method private hidebysig specialname static void '$' ( int32 '' ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } + + .method public hidebysig static void M () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + } .method public hidebysig static int32 M () cil managed { @@ -3266,24 +3286,24 @@ public void PENamedTypeSymbol_14() // parameter type mismatch, instance method var ilSrc = """ .class public auto ansi abstract sealed beforefieldinit E - extends [mscorlib]System.Object -{ - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' - extends [mscorlib]System.Object - { - .method private hidebysig specialname static void '$' ( int32 i ) cil managed - { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - IL_0000: ret - } - - .method public hidebysig instance void M () cil managed - { - IL_0000: ldnull - IL_0001: throw - } - } + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + .method private hidebysig specialname static void '$' ( int32 i ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } + + .method public hidebysig instance void M () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + } .method public hidebysig static void M ( object i ) cil managed { @@ -3308,24 +3328,24 @@ public void PENamedTypeSymbol_15() // parameter type mismatch, instance method var ilSrc = """ .class public auto ansi abstract sealed beforefieldinit E - extends [mscorlib]System.Object -{ - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' - extends [mscorlib]System.Object - { - .method private hidebysig specialname static void '$' ( int32 i ) cil managed - { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - IL_0000: ret - } - - .method public hidebysig instance void M ( string s ) cil managed - { - IL_0000: ldnull - IL_0001: throw - } - } + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + .method private hidebysig specialname static void '$' ( int32 i ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } + + .method public hidebysig instance void M ( string s ) cil managed + { + IL_0000: ldnull + IL_0001: throw + } + } .method public hidebysig static void M ( int32 i, object s ) cil managed { @@ -3350,24 +3370,24 @@ public void PENamedTypeSymbol_16() // constraint mismatch between skeleton and implementation var ilSrc = """ .class public auto ansi abstract sealed beforefieldinit E - extends [mscorlib]System.Object -{ - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' - extends [mscorlib]System.Object - { - .method private hidebysig specialname static void '$' ( int32 '' ) cil managed - { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - IL_0000: ret - } - - .method public hidebysig static void M () cil managed - { - IL_0000: ldnull - IL_0001: throw - } - } + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + .method private hidebysig specialname static void '$' ( int32 '' ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } + + .method public hidebysig static void M () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + } .method public hidebysig static void M () cil managed { @@ -3392,24 +3412,24 @@ public void PENamedTypeSymbol_17() // implementation is not static var ilSrc = """ .class public auto ansi abstract sealed beforefieldinit E - extends [mscorlib]System.Object -{ - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' - extends [mscorlib]System.Object - { - .method private hidebysig specialname static void '$' ( int32 '' ) cil managed - { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - IL_0000: ret - } - - .method public hidebysig static void M () cil managed - { - IL_0000: ldnull - IL_0001: throw - } - } + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + .method private hidebysig specialname static void '$' ( int32 '' ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } + + .method public hidebysig static void M () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + } .method public hidebysig instance void M () cil managed { @@ -3434,24 +3454,24 @@ public void PENamedTypeSymbol_18() // skeleton type is not sealed var ilSrc = """ .class public auto ansi abstract sealed beforefieldinit E - extends [mscorlib]System.Object -{ - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - .class nested public auto ansi specialname beforefieldinit '<>E__0' - extends [mscorlib]System.Object - { - .method private hidebysig specialname static void '$' ( int32 '' ) cil managed - { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - IL_0000: ret - } - - .method public hidebysig static void M () cil managed - { - IL_0000: ldnull - IL_0001: throw - } - } + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + .class nested public auto ansi specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + .method private hidebysig specialname static void '$' ( int32 '' ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } + + .method public hidebysig static void M () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + } .method public hidebysig static void M () cil managed { @@ -3480,24 +3500,24 @@ public void PENamedTypeSymbol_19(string accessibility) // skeleton type is not public var ilSrc = $$""" .class public auto ansi abstract sealed beforefieldinit E - extends [mscorlib]System.Object -{ - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - .class nested {{accessibility}} auto ansi specialname beforefieldinit sealed '<>E__0' - extends [mscorlib]System.Object - { - .method private hidebysig specialname static void '$' ( int32 '' ) cil managed - { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - IL_0000: ret - } - - .method public hidebysig static void M () cil managed - { - IL_0000: ldnull - IL_0001: throw - } - } + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + .class nested {{accessibility}} auto ansi specialname beforefieldinit sealed '<>E__0' + extends [mscorlib]System.Object + { + .method private hidebysig specialname static void '$' ( int32 '' ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } + + .method public hidebysig static void M () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + } .method public hidebysig static void M () cil managed { @@ -3524,24 +3544,24 @@ public void PENamedTypeSymbol_20() // skeleton type not sealed var ilSrc = """ .class public auto ansi abstract sealed beforefieldinit E - extends [mscorlib]System.Object -{ - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - .class nested public auto ansi specialname beforefieldinit '<>E__0' - extends [mscorlib]System.Object - { - .method private hidebysig specialname static void '$' ( int32 '' ) cil managed - { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - IL_0000: ret - } - - .method public hidebysig static void M () cil managed - { - IL_0000: ldnull - IL_0001: throw - } - } + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + .class nested public auto ansi specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + .method private hidebysig specialname static void '$' ( int32 '' ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } + + .method public hidebysig static void M () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + } .method public hidebysig static void M () cil managed { @@ -3568,24 +3588,24 @@ public void PENamedTypeSymbol_21() // skeleton type has a base that's not object var ilSrc = """ .class public auto ansi abstract sealed beforefieldinit E - extends [mscorlib]System.Object -{ - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - .class nested public auto ansi specialname beforefieldinit sealed '<>E__0' - extends [mscorlib]System.String - { - .method private hidebysig specialname static void '$' ( int32 '' ) cil managed - { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - IL_0000: ret - } - - .method public hidebysig static void M () cil managed - { - IL_0000: ldnull - IL_0001: throw - } - } + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + .class nested public auto ansi specialname beforefieldinit sealed '<>E__0' + extends [mscorlib]System.String + { + .method private hidebysig specialname static void '$' ( int32 '' ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } + + .method public hidebysig static void M () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + } .method public hidebysig static void M () cil managed { @@ -3612,25 +3632,25 @@ public void PENamedTypeSymbol_22() // skeleton type implements an interface var ilSrc = """ .class public auto ansi abstract sealed beforefieldinit E - extends [mscorlib]System.Object + extends [mscorlib]System.Object { - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - .class nested public auto ansi specialname beforefieldinit sealed '<>E__0' - extends [mscorlib]System.Object + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + .class nested public auto ansi specialname beforefieldinit sealed '<>E__0' + extends [mscorlib]System.Object implements I - { - .method private hidebysig specialname static void '$' ( int32 '' ) cil managed - { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - IL_0000: ret - } - - .method public hidebysig static void M () cil managed - { - IL_0000: ldnull - IL_0001: throw - } - } + { + .method private hidebysig specialname static void '$' ( int32 '' ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } + + .method public hidebysig static void M () cil managed + { + IL_0000: ldnull + IL_0001: throw + } + } .method public hidebysig static void M () cil managed { @@ -3661,24 +3681,24 @@ public void PENamedTypeSymbol_23() // parameter type mismatch, static method var ilSrc = """ .class public auto ansi abstract sealed beforefieldinit E - extends [mscorlib]System.Object -{ - .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) - .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' - extends [mscorlib]System.Object - { - .method private hidebysig specialname static void '$' ( int32 i ) cil managed - { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - IL_0000: ret - } - - .method public hidebysig static void M ( string s ) cil managed - { - IL_0000: ldnull - IL_0001: throw - } - } + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) + .class nested public auto ansi sealed specialname beforefieldinit '<>E__0' + extends [mscorlib]System.Object + { + .method private hidebysig specialname static void '$' ( int32 i ) cil managed + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + IL_0000: ret + } + + .method public hidebysig static void M ( string s ) cil managed + { + IL_0000: ldnull + IL_0001: throw + } + } .method public hidebysig static void M ( object s ) cil managed { @@ -5392,7 +5412,7 @@ public static void Method() { } public static void M2() { } } """; - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : cref, such unqualified references in CREF should work within context of enclosing static type + // Tracked by https://github.com/dotnet/roslyn/issues/78967 : cref, such unqualified references in CREF should work within context of enclosing static type var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreviewWithDocumentationComments); comp.VerifyEmitDiagnostics( // (1,16): warning CS1574: XML comment has cref attribute 'extension(int).Method' that could not be resolved @@ -5545,5 +5565,1637 @@ static class E // /// Diagnostic(ErrorCode.WRN_BadXMLRef, "E.M(string)").WithArguments("M(string)").WithLocation(1, 16)); } + + [Fact] + public void GroupingTypeRawName_01() + { + var src = """ +static class E +{ + extension(object o) + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var e = comp.GetMember("E"); + var extension = (SourceNamedTypeSymbol)e.GetTypeMembers().Single(); + Assert.Equal("extension(System.Object)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_02() + { + // separator for containing types is slash + var src = """ +static class E +{ + extension(N1.N2.C1.C2.C3) + { + } +} + +namespace N1 +{ + namespace N2 + { + class C1 + { + public class C2 + { + public class C3 { } + } + } + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var e = comp.GetMember("E"); + var extension = (SourceNamedTypeSymbol)e.GetTypeMembers().Single(); + Assert.Equal("extension(N1.N2.C1/C2/C3)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_03() + { + // containing type gets an arity, all type arguments are included + var src = """ +static class E +{ + extension(C1.C2) + { + } +} + +class C1 { public class C2 { } } +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var e = comp.GetMember("E"); + var extension = (SourceNamedTypeSymbol)e.GetTypeMembers().Single(); + AssertEx.Equal("extension(C1`1/C2`1)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_04() + { + // Arity above 10 + var src = """ +static class E +{ + extension(C) + { + } +} + +class C { } +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var e = comp.GetMember("E"); + var extension = (SourceNamedTypeSymbol)e.GetTypeMembers().Single(); + AssertEx.Equal("extension(C`12)", + extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_05() + { + // Nested type arguments + var src = """ +static class E +{ + extension(C>) + { + } +} +class C { } +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var e = comp.GetMember("E"); + var extension = (SourceNamedTypeSymbol)e.GetTypeMembers().Single(); + AssertEx.Equal("extension(C`1>)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_08() + { + // Short tuple + var src = """ +static class E +{ + extension((int alice, string bob)) + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var e = comp.GetMember("E"); + var extension = (SourceNamedTypeSymbol)e.GetTypeMembers().Single(); + AssertEx.Equal("extension(System.ValueTuple`2)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_09() + { + // Long tuple + var src = """ +static class E +{ + extension((int x0, int x1, int x2, int x3, int x4, int x5, int x6, string x7)) + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var e = comp.GetMember("E"); + var extension = (SourceNamedTypeSymbol)e.GetTypeMembers().Single(); + AssertEx.Equal("extension(System.ValueTuple`8>)", + extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_10() + { + // Simple types + var src = """ +static class E +{ + extension(C) + { + } +} +class C { } +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var e = comp.GetMember("E"); + var extension = (SourceNamedTypeSymbol)e.GetTypeMembers().Single(); + AssertEx.Equal("extension(C`13)", + extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_11() + { + // Native ints + var src = """ +static class E +{ + extension((nint, nuint)) + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var e = comp.GetMember("E"); + var extension = (SourceNamedTypeSymbol)e.GetTypeMembers().Single(); + AssertEx.Equal("extension(System.ValueTuple`2)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_12() + { + // System.Nullable + var src = """ +static class E +{ + extension(int?) + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var e = comp.GetMember("E"); + var extension = (SourceNamedTypeSymbol)e.GetTypeMembers().Single(); + AssertEx.Equal("extension(System.Nullable`1)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_13() + { + // Referencing type parameter + var src = """ +static class E +{ + extension(U) + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var e = comp.GetMember("E"); + var extension = (SourceNamedTypeSymbol)e.GetTypeMembers().Single(); + AssertEx.Equal("extension<>(!0)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_14() + { + // Referencing over 10 type parameters as type arguments + var src = """ +static class E +{ + extension(C) + { + } +} +class C { } +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var e = comp.GetMember("E"); + var extension = (SourceNamedTypeSymbol)e.GetTypeMembers().Single(); + AssertEx.Equal("extension<,,,,,,,,,,,,>(C`13)", + extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_15() + { + // Attributes are removed from CLR-level signature + var src = """ +static class E +{ + extension<[My] T>(T) + { + } +} + +class MyAttribute : System.Attribute { } +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var e = comp.GetMember("E"); + var extension = (SourceNamedTypeSymbol)e.GetTypeMembers().Single(); + AssertEx.Equal("extension<>(!0)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_16() + { + // Nullability annotations are removed from CLR-level signature + var src = """ +#nullable enable + +static class E +{ + extension(object?) + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var e = comp.GetMember("E"); + var extension = (SourceNamedTypeSymbol)e.GetTypeMembers().Single(); + AssertEx.Equal("extension(System.Object)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_17() + { + // Array + var src = """ +static class E +{ + extension(object[][,]) + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var e = comp.GetMember("E"); + var extension = (SourceNamedTypeSymbol)e.GetTypeMembers().Single(); + AssertEx.Equal("extension(System.Object[,][])", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_18() + { + // Array with nullability annotations + var src = """ +#nullable enable +static class E +{ + extension(object?[]?[,]) + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(System.Object[][,])", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_19() + { + // Vector / single-dimensional array + var src = """ +#nullable enable +static class E +{ + extension(object[,]) + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(System.Object[,])", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_20() + { + // Pointer type + var src = """ +unsafe static class E +{ + extension(int*[]) + { + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(System.Int32*[])", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_21() + { + // Pointer type + var src = """ +unsafe static class E +{ + extension(int**[]) + { + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(System.Int32**[])", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_22() + { + // Function pointer type + var src = """ +unsafe static class E +{ + extension(delegate*[]) + { + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(method void *(System.Int32, System.String)[])", extension.ComputeExtensionGroupingRawName()); + + var src2 = """ +unsafe struct C +{ + delegate*[] field; +} +"""; + CompileAndVerify(src2, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90, verify: Verification.FailsPEVerify).VerifyTypeIL("C", """ +.class private sequential ansi sealed beforefieldinit C + extends [System.Runtime]System.ValueType +{ + // Fields + .field private method void *(int32, string)[] 'field' +} // end of class C +"""); + } + + [Fact] + public void GroupingTypeRawName_23() + { + // null ExtensionParameter + var src = """ +static class E +{ + extension(__arglist) + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (3,15): error CS1669: __arglist is not valid in this context + // extension(__arglist) + Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(3, 15)); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension()", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_24() + { + // constraints: class + var src = """ +static class E +{ + extension(T) where T : class + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(!0)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_25() + { + // constraints: struct + var src = """ +static class E +{ + extension(T) where T : struct + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(!0)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_26() + { + // constraints + var src = """ +static class E +{ + extension(T) where T : class, new() + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(!0)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_27() + { + // constraints + var src = """ +static class E +{ + extension(T) where T : new(), class + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (3,31): error CS0401: The new() constraint must be the last restrictive constraint specified + // extension(T) where T : new(), class + Diagnostic(ErrorCode.ERR_NewBoundMustBeLast, "new").WithLocation(3, 31), + // (3,38): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. + // extension(T) where T : new(), class + Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(3, 38)); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(!0)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_28() + { + // constraints: unmanaged + var src = """ +static class E +{ + extension(T) where T : unmanaged + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(!0)", extension.ComputeExtensionGroupingRawName()); + + var src2 = """ +unsafe struct C where T : unmanaged +{ +} +"""; + CompileAndVerify(src2, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90, verify: Verification.FailsPEVerify).VerifyTypeIL("C`1", """ +.class private sequential ansi sealed beforefieldinit C`1 + extends [System.Runtime]System.ValueType +{ + .param type T + .custom instance void [System.Runtime]System.Runtime.CompilerServices.IsUnmanagedAttribute::.ctor() = ( + 01 00 00 00 + ) + .pack 0 + .size 1 +} // end of class C`1 +"""); + } + + [Fact] + public void GroupingTypeRawName_29() + { + // constraints + var src = """ +static class E +{ + extension(T) where T : System.ValueType + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (3,31): error CS0702: Constraint cannot be special class 'ValueType' + // extension(T) where T : System.ValueType + Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "System.ValueType").WithArguments("System.ValueType").WithLocation(3, 31)); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension<>(!0)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_30() + { + // constraints + var src = """ +static class E +{ + extension(T) where T : unmanaged, new() + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (3,42): error CS8375: The 'new()' constraint cannot be used with the 'unmanaged' constraint + // extension(T) where T : unmanaged, new() + Diagnostic(ErrorCode.ERR_NewBoundWithUnmanaged, "new").WithLocation(3, 42)); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(!0)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_31() + { + // constraints + var src = """ +static class E +{ + extension(T) where T : unmanaged, I + { + } +} + +interface I { } +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(!0)", + extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_32() + { + // type constraints + var src = """ +static class E +{ + extension(T) where T : I + { + } +} + +interface I { } +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension<(I)>(!0)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_33() + { + // type constraints + var src = """ +static class E +{ + extension(T) where T : I1, I2 + { + } +} + +interface I1 { } +interface I2 { } +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension<(I1, I2)>(!0)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_34() + { + // type constraints + var src = """ +static class E +{ + extension(T) where T : I2, I1 + { + } +} + +interface I1 { } +interface I2 { } +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension<(I1, I2)>(!0)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_35() + { + // type constraints + var src = """ +static class E +{ + extension(T) where T : C, I1, I2 + { + } +} + +interface I1 { } +interface I2 { } +class C { } +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension<(C, I1, I2)>(!0)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_36() + { + // constraints + var src = """ +static class E +{ + extension(T) where T : struct, I + { + } +} + +interface I { } +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(!0)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_37() + { + // constraints: allows ref struct + var src = """ +static class E +{ + extension(T) where T : allows ref struct + { + } +} +"""; + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(!0)", extension.ComputeExtensionGroupingRawName()); + + // Note: IL should have byreflike flag + var src2 = """ +struct C where T : allows ref struct +{ +} +"""; + CompileAndVerify(src2, targetFramework: TargetFramework.Net90, verify: Verification.FailsPEVerify).VerifyTypeIL("C`1", """ +.class private sequential ansi sealed beforefieldinit C`1 + extends [System.Runtime]System.ValueType +{ + .pack 0 + .size 1 +} // end of class C`1 +"""); + } + + [Fact] + public void GroupingTypeRawName_38() + { + // constraints + var src = """ +static class E +{ + extension(T) where T : struct, allows ref struct + { + } +} +"""; + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(!0)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_39() + { + // constraints + var src = """ +static class E +{ + extension(T) where T : new(), allows ref struct + { + } +} +"""; + var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(!0)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_40() + { + // type constraints + var src = """ +static class E +{ + extension(T) where T : U + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension<(!1),>(!0)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_41() + { + var src = """ +unsafe static class E +{ + extension(delegate*[]) + { + } +} + +struct D { } +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(method D *(D)[])", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_42() + { + var src = """ +unsafe static class E +{ + extension(delegate*[]) + { + } +} + +class D { } +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(method D *(D)[])", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_43() + { + var src = """ +unsafe static class E +{ + extension(delegate*[]) + { + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension<>(method !0 *(!0)[])", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_44() + { + var src = """ +static class E +{ + extension(C>) + { + } +} + +struct C { } +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(C`1>)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_45() + { + var src = """ +static class E +{ + extension(C>) + { + } +} + +class C { } +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(C`1>)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_46() + { + var src = """ +static class E +{ + extension(ERROR) + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (3,15): error CS0246: The type or namespace name 'ERROR' could not be found (are you missing a using directive or an assembly reference?) + // extension(ERROR) + Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "ERROR").WithArguments("ERROR").WithLocation(3, 15)); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(ERROR)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_47() + { + // function pointer modifiers + var src = """ +unsafe static class E +{ + extension(delegate* unmanaged[]) + { + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(method unmanaged void *()[])", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_48() + { + // function pointer modifiers + var src = """ +unsafe static class E +{ + extension(delegate* unmanaged[Cdecl][]) + { + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(method unmanaged cdecl void *()[])", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_49() + { + // function pointer modifiers + var src = """ +unsafe static class E +{ + extension(delegate* unmanaged[Stdcall][]) + { + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(method unmanaged stdcall void *()[])", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_50() + { + // function pointer modifiers + var src = """ +unsafe static class E +{ + extension(delegate* unmanaged[Thiscall][]) + { + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(method unmanaged thiscall void *()[])", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_51() + { + // function pointer modifiers + var src = """ +unsafe static class E +{ + extension(delegate* unmanaged[Fastcall][]) + { + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(method unmanaged fastcall void *()[])", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_52() + { + // function pointer modifiers: 1 non-special calling convention + var src = """ +unsafe static class E +{ + extension(delegate* unmanaged[SuppressGCTransition][]) + { + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(method unmanaged void modopt(System.Runtime.CompilerServices.CallConvSuppressGCTransition) *()[])", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_53() + { + // function pointer modifiers: 1 non-special calling convention + var src = """ +unsafe static class E +{ + extension(delegate* unmanaged[Vectorcall][]) + { + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (3,35): error CS8890: Type 'CallConvVectorcall' is not defined. + // extension(delegate* unmanaged[Vectorcall][]) + Diagnostic(ErrorCode.ERR_TypeNotFound, "Vectorcall").WithArguments("CallConvVectorcall").WithLocation(3, 35)); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(method unmanaged void modopt(System.Runtime.CompilerServices.CallConvVectorcall) *()[])", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_54() + { + // function pointer modifiers: more than 1 special calling convention + var src = """ +unsafe static class E +{ + extension(delegate* unmanaged[Stdcall, Thiscall][]) + { + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(method unmanaged void modopt(System.Runtime.CompilerServices.CallConvStdcall) modopt(System.Runtime.CompilerServices.CallConvThiscall) *()[])", + extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_55() + { + // function pointer modifiers: more than 1 special calling convention, reverse order + var src = """ +unsafe static class E +{ + extension(delegate* unmanaged[Thiscall, Stdcall][]) + { + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(method unmanaged void modopt(System.Runtime.CompilerServices.CallConvThiscall) modopt(System.Runtime.CompilerServices.CallConvStdcall) *()[])", + extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_56() + { + // function pointer modifiers + var src = """ +unsafe static class E +{ + extension(delegate* unmanaged[Stdcall, SuppressGCTransition][]) + { + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(method unmanaged void modopt(System.Runtime.CompilerServices.CallConvStdcall) modopt(System.Runtime.CompilerServices.CallConvSuppressGCTransition) *()[])", + extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_57() + { + // function pointer refness: ref + var src = """ +unsafe static class E +{ + extension(delegate* []) + { + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(method System.Int64& *(System.Int32&)[])", extension.ComputeExtensionGroupingRawName()); + + var src2 = """ +unsafe struct C +{ + delegate* [] field; +} +"""; + CompileAndVerify(src2, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90, verify: Verification.FailsPEVerify).VerifyTypeIL("C", """ +.class private sequential ansi sealed beforefieldinit C + extends [System.Runtime]System.ValueType +{ + // Fields + .field private method int64& *(int32&)[] 'field' +} // end of class C +"""); + } + + [Fact] + public void GroupingTypeRawName_58() + { + // function pointer refness: ref readonly + var src = """ +unsafe static class E +{ + extension(delegate* []) + { + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(method System.Int64& modreq(System.Runtime.InteropServices.InAttribute) *(System.Int32& modopt(System.Runtime.CompilerServices.RequiresLocationAttribute))[])", + extension.ComputeExtensionGroupingRawName()); + + var src2 = """ +unsafe struct C +{ + delegate* [] field; +} +"""; + CompileAndVerify(src2, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90, verify: Verification.FailsPEVerify).VerifyTypeIL("C", """ +.class private sequential ansi sealed beforefieldinit C + extends [System.Runtime]System.ValueType +{ + // Fields + .field private method int64& modreq([System.Runtime]System.Runtime.InteropServices.InAttribute) *(int32& modopt([System.Runtime]System.Runtime.CompilerServices.RequiresLocationAttribute))[] 'field' +} // end of class C +"""); + } + + [Fact] + public void GroupingTypeRawName_59() + { + // function pointer refness: in + var src = """ +unsafe static class E +{ + extension(delegate* []) + { + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(method void *(System.Int32& modreq(System.Runtime.InteropServices.InAttribute))[])", + extension.ComputeExtensionGroupingRawName()); + + var src2 = """ +unsafe struct C +{ + delegate* [] field; +} +"""; + CompileAndVerify(src2, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90, verify: Verification.FailsPEVerify).VerifyTypeIL("C", """ +.class private sequential ansi sealed beforefieldinit C + extends [System.Runtime]System.ValueType +{ + // Fields + .field private method void *(int32& modreq([System.Runtime]System.Runtime.InteropServices.InAttribute))[] 'field' +} // end of class C +"""); + } + + [Fact] + public void GroupingTypeRawName_60() + { + // function pointer refness: out + var src = """ +unsafe static class E +{ + extension(delegate* []) + { + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(method void *(System.Int32& modreq(System.Runtime.InteropServices.OutAttribute))[])", + extension.ComputeExtensionGroupingRawName()); + + var src2 = """ +unsafe struct C +{ + delegate* [] field; +} +"""; + CompileAndVerify(src2, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90, verify: Verification.FailsPEVerify).VerifyTypeIL("C", """ +.class private sequential ansi sealed beforefieldinit C + extends [System.Runtime]System.ValueType +{ + // Fields + .field private method void *(int32& modreq([System.Runtime]System.Runtime.InteropServices.OutAttribute))[] 'field' +} // end of class C +"""); + } + + [Fact] + public void GroupingTypeRawName_61() + { + // function pointer nullability + var src = """ +#nullable enable + +unsafe static class E +{ + extension(delegate* []) + { + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(method System.Object *(System.Object)[])", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_62() + { + // function pointer: type alias + var src = """ +using Obj = System.Object; + +unsafe static class E +{ + extension(delegate* []) + { + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(method System.Object *(System.Object)[])", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_63() + { + // function pointer modifiers + var src = """ +unsafe static class E +{ + extension(delegate* unmanaged[Stdcall, SuppressGCTransition][]) + { + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(method unmanaged System.Int32& modopt(System.Runtime.CompilerServices.CallConvStdcall) modopt(System.Runtime.CompilerServices.CallConvSuppressGCTransition) modreq(System.Runtime.InteropServices.InAttribute) *()[])", + extension.ComputeExtensionGroupingRawName()); + + var src2 = """ +unsafe struct C +{ + delegate* unmanaged[Stdcall, SuppressGCTransition][] field; +} +"""; + CompileAndVerify(src2, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90, verify: Verification.FailsPEVerify).VerifyTypeIL("C", """ +.class private sequential ansi sealed beforefieldinit C + extends [System.Runtime]System.ValueType +{ + // Fields + .field private method unmanaged int32& modreq([System.Runtime]System.Runtime.InteropServices.InAttribute) modopt([System.Runtime]System.Runtime.CompilerServices.CallConvSuppressGCTransition) modopt([System.Runtime]System.Runtime.CompilerServices.CallConvStdcall) *()[] 'field' +} // end of class C +"""); + } + + [Fact] + public void GroupingTypeRawName_64() + { + var src = """ +static class E +{ + extension(T) + { + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (3,5): error CS9283: Extensions must be declared in a top-level, non-generic, static class + // extension(T) + Diagnostic(ErrorCode.ERR_BadExtensionContainingType, "extension").WithLocation(3, 5)); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(!T)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_65() + { + var src = """ +static class E +{ + extension(T0) + { + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (3,5): error CS9283: Extensions must be declared in a top-level, non-generic, static class + // extension(T0) + Diagnostic(ErrorCode.ERR_BadExtensionContainingType, "extension").WithLocation(3, 5)); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension<>(!T0)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_66() + { + var src = """ +static class E +{ + extension(U) + { + extension(V) + { + } + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (3,5): error CS9283: Extensions must be declared in a top-level, non-generic, static class + // extension(U) + Diagnostic(ErrorCode.ERR_BadExtensionContainingType, "extension").WithLocation(3, 5), + // (5,9): error CS9282: This member is not allowed in an extension block + // extension(V) + Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "extension").WithLocation(5, 9)); + + var nestedExtension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single().GetTypeMembers().Single(); + AssertEx.Equal("extension<>(!0)", nestedExtension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_67() + { + var src = """ +unsafe static class E +{ + extension(delegate*[]) + { + } +} +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90); + comp.VerifyEmitDiagnostics( + // (3,25): error CS8755: 'scoped' cannot be used as a modifier on a function pointer parameter. + // extension(delegate*[]) + Diagnostic(ErrorCode.ERR_BadFuncPointerParamModifier, "scoped").WithArguments("scoped").WithLocation(3, 25), + // (3,41): error CS8808: 'scoped' is not a valid function pointer return type modifier. Valid modifiers are 'ref' and 'ref readonly'. + // extension(delegate*[]) + Diagnostic(ErrorCode.ERR_InvalidFuncPointerReturnTypeModifier, "scoped").WithArguments("scoped").WithLocation(3, 41)); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(method System.Int32& *(System.Int32&)[])", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_68() + { + var src = """ +static class E +{ + extension((dynamic, dynamic)) + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics(); + + var e = comp.GetMember("E"); + var extension = (SourceNamedTypeSymbol)e.GetTypeMembers().Single(); + AssertEx.Equal("extension(System.ValueTuple`2)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_69() + { + var src = """ +static class E +{ + extension(dynamic) + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (3,15): error CS1103: The receiver parameter of an extension cannot be of type 'dynamic' + // extension(dynamic) + Diagnostic(ErrorCode.ERR_BadTypeforThis, "dynamic").WithArguments("dynamic").WithLocation(3, 15)); + + var e = comp.GetMember("E"); + var extension = (SourceNamedTypeSymbol)e.GetTypeMembers().Single(); + AssertEx.Equal("extension(System.Object)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_70() + { + var src = """ +static class E +{ + extension(T) + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (3,15): error CS1960: Invalid variance modifier. Only interface and delegate type parameters can be specified as variant. + // extension(T) + Diagnostic(ErrorCode.ERR_IllegalVarianceSyntax, "in").WithLocation(3, 15)); + + var e = comp.GetMember("E"); + var extension = (SourceNamedTypeSymbol)e.GetTypeMembers().Single(); + AssertEx.Equal("extension<>(!0)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_71() + { + var src = """ +static class E +{ + extension(T) + { + } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (3,15): error CS1960: Invalid variance modifier. Only interface and delegate type parameters can be specified as variant. + // extension(T) + Diagnostic(ErrorCode.ERR_IllegalVarianceSyntax, "out").WithLocation(3, 15)); + + var e = comp.GetMember("E"); + var extension = (SourceNamedTypeSymbol)e.GetTypeMembers().Single(); + AssertEx.Equal("extension<>(!0)", extension.ComputeExtensionGroupingRawName()); + } + + [Fact] + public void GroupingTypeRawName_72() + { + var src = """ +static class E +{ + extension(T t) + { + public void M() { } + } + extension(T t) + { + public void M() { } + } + + public static void M2(this T t) { } + public static void M2(this T t) { } +} +"""; + var comp = CreateCompilation(src); + comp.VerifyEmitDiagnostics( + // (3,15): error CS1960: Invalid variance modifier. Only interface and delegate type parameters can be specified as variant. + // extension(T t) + Diagnostic(ErrorCode.ERR_IllegalVarianceSyntax, "in").WithLocation(3, 15), + // (9,21): error CS0111: Type 'E' already defines a member called 'M' with the same parameter types + // public void M() { } + Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M").WithArguments("M", "E").WithLocation(9, 21), + // (12,27): error CS1960: Invalid variance modifier. Only interface and delegate type parameters can be specified as variant. + // public static void M2(this T t) { } + Diagnostic(ErrorCode.ERR_IllegalVarianceSyntax, "in").WithLocation(12, 27), + // (13,24): error CS0111: Type 'E' already defines a member called 'M2' with the same parameter types + // public static void M2(this T t) { } + Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M2").WithArguments("M2", "E").WithLocation(13, 24)); + } + + [Fact] + public void GroupingTypeRawName_73() + { + // Function pointer type with type named "void" + var src = """ +unsafe static class E +{ + extension(delegate*<@void, @void>[]) + { + } +} +class @void { } +"""; + var comp = CreateCompilation(src, options: TestOptions.UnsafeDebugDll); + comp.VerifyEmitDiagnostics(); + + var extension = (SourceNamedTypeSymbol)comp.GetMember("E").GetTypeMembers().Single(); + AssertEx.Equal("extension(method 'void' *('void')[])", extension.ComputeExtensionGroupingRawName()); + + var src2 = """ +unsafe struct C +{ + delegate*<@void, @void>[] field; +} +class @void { } +"""; + CompileAndVerify(src2, options: TestOptions.UnsafeDebugDll, targetFramework: TargetFramework.Net90, verify: Verification.FailsPEVerify).VerifyTypeIL("C", """ +.class private sequential ansi sealed beforefieldinit C + extends [System.Runtime]System.ValueType +{ + // Fields + .field private method class 'void' *(class 'void')[] 'field' +} // end of class C +"""); + } } diff --git a/src/Compilers/CSharp/Test/Emit3/Semantics/OutVarTests.cs b/src/Compilers/CSharp/Test/Emit3/Semantics/OutVarTests.cs index 8dfd5cbaacf8a..36a1708cfa72a 100644 --- a/src/Compilers/CSharp/Test/Emit3/Semantics/OutVarTests.cs +++ b/src/Compilers/CSharp/Test/Emit3/Semantics/OutVarTests.cs @@ -8,15 +8,16 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; +using Basic.Reference.Assemblies; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; +using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; -using Xunit; using Roslyn.Test.Utilities; using Roslyn.Utilities; -using Microsoft.CodeAnalysis.Diagnostics; -using Basic.Reference.Assemblies; +using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { diff --git a/src/Compilers/CSharp/Test/Emit3/Symbols/UserDefinedCompoundAssignmentOperatorsTests.cs b/src/Compilers/CSharp/Test/Emit3/Symbols/UserDefinedCompoundAssignmentOperatorsTests.cs index cdba5a8cf8cb7..741b59634a76f 100644 --- a/src/Compilers/CSharp/Test/Emit3/Symbols/UserDefinedCompoundAssignmentOperatorsTests.cs +++ b/src/Compilers/CSharp/Test/Emit3/Symbols/UserDefinedCompoundAssignmentOperatorsTests.cs @@ -7872,7 +7872,72 @@ public void Increment_150_GetOperatorKind([CombinatorialValues("++", "--")] stri Assert.Equal(kind, SyntaxFacts.GetOperatorKind(name)); } - private static string CompoundAssignmentOperatorName(string op, bool isChecked = false) + [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/78964")] + public void Increment_151_RefSafety([CombinatorialValues("++", "--")] string op) + { + // r1 = ++r2; + // is equivalent to + // var tmp = r2; + // tmp.op_IncrementAssignment(); + // r2 = tmp; + // r1 = tmp; + // which is *not* ref safe (scoped tmp cannot be assigned to unscoped r1) + var source = $$""" + ref struct R + { + private ref readonly int _i; + public R(in int i) { _i = ref i; } + public void operator {{op}}() { } + } + class Program + { + static R F1(R r1, scoped R r2) + { + r1 = {{op}}r2; + return r1; + } + } + """; + CreateCompilation(source, targetFramework: TargetFramework.Net70).VerifyDiagnostics( + // (11,14): error CS8352: Cannot use variable 'scoped R r2' in this context because it may expose referenced variables outside of their declaration scope + // r1 = ++r2; + Diagnostic(ErrorCode.ERR_EscapeVariable, $"{op}r2").WithArguments("scoped R r2").WithLocation(11, 14)); + } + + [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/78964")] + public void Increment_152_RefSafety([CombinatorialValues("++", "--")] string op) + { + // F2(out var r1, ++r2); return r1; + // is equivalent to + // var tmp = r2; + // tmp.op_IncrementAssignment(); + // r2 = tmp; + // F2(out var r1, tmp); return r1; + // which is *not* ref safe (r1 is inferred as scoped from tmp but scoped r1 cannot be returned) + var source = $$""" + ref struct R + { + private ref readonly int _i; + public R(in int i) { _i = ref i; } + public void operator {{op}}() { } + } + class Program + { + static R F1(scoped R r2) + { + F2(out var r1, {{op}}r2); + return r1; + } + static void F2(out R r1, R r2) => r1 = r2; + } + """; + CreateCompilation(source, targetFramework: TargetFramework.Net70).VerifyDiagnostics( + // (12,16): error CS8352: Cannot use variable 'r1' in this context because it may expose referenced variables outside of their declaration scope + // return r1; + Diagnostic(ErrorCode.ERR_EscapeVariable, "r1").WithArguments("r1").WithLocation(12, 16)); + } + + internal static string CompoundAssignmentOperatorName(string op, bool isChecked = false) { SyntaxKind kind = CompoundAssignmentOperatorTokenKind(op); @@ -17691,7 +17756,7 @@ public class C1 : C2 comp.VerifyEmitDiagnostics(); } - private static string ToCRefOp(string op) + internal static string ToCRefOp(string op) { return op.Replace("&", "&").Replace("<", "<"); } @@ -20232,5 +20297,81 @@ static async Task GetInt(int x) var comp = CreateCompilation([source, CompilerFeatureRequiredAttribute], options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "+=3+=55nullnull").VerifyDiagnostics(); } + + [Fact] + public void CompoundAssignment_01610_Consumption_RightIsImplicitObjectCreation() + { + var source = @" +struct S1 +{ + public void operator +=(S1 y) {} +} + +struct S2 +{ + public static S2 operator +(S2 x, S2 y) => x; +} + +class Program +{ + static void Main() + { + var s1 = new S1(); + s1 += new(); + + var s2 = new S2(); + s2 += new(); + } +} +"; + + var comp = CreateCompilation([source, CompilerFeatureRequiredAttribute]); + comp.VerifyDiagnostics( + // (17,9): error CS8310: Operator '+=' cannot be applied to operand 'new()' + // s1 += new(); + Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "s1 += new()").WithArguments("+=", "new()").WithLocation(17, 9), + // (20,9): error CS8310: Operator '+=' cannot be applied to operand 'new()' + // s2 += new(); + Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "s2 += new()").WithArguments("+=", "new()").WithLocation(20, 9) + ); + } + + [Fact] + public void CompoundAssignment_01620_Consumption_RightIsDefault() + { + var source = @" +struct S1 +{ + public void operator +=(S1 y) {} +} + +struct S2 +{ + public static S2 operator +(S2 x, S2 y) => x; +} + +class Program +{ + static void Main() + { + var s1 = new S1(); + s1 += default; + + var s2 = new S2(); + s2 += default; + } +} +"; + + var comp = CreateCompilation([source, CompilerFeatureRequiredAttribute]); + comp.VerifyDiagnostics( + // (17,9): error CS8310: Operator '+=' cannot be applied to operand 'default' + // s1 += default; + Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "s1 += default").WithArguments("+=", "default").WithLocation(17, 9), + // (20,9): error CS8310: Operator '+=' cannot be applied to operand 'default' + // s2 += default; + Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "s2 += default").WithArguments("+=", "default").WithLocation(20, 9) + ); + } } } diff --git a/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IBinaryOperatorExpression.cs b/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IBinaryOperatorExpression.cs index 6bc37a561b2a6..01c3f3a5ea609 100644 --- a/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IBinaryOperatorExpression.cs +++ b/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IBinaryOperatorExpression.cs @@ -8280,5 +8280,336 @@ void M(int? start) var operation = (IRangeOperation)VerifyOperationTreeForTest(compilation, expectedOperationTree); Assert.Equal(RangeStartAtSignature, operation.Method.ToTestDisplayString()); } + + [CompilerTrait(CompilerFeature.IOperation)] + [Fact] + public void Extensions_01() + { + var source = @" +struct C +{ + void F(C x, C y) + { + var z = /**/x + y/**/; + } +} + +static class Extensions +{ + extension(C) + { + public static C operator +(C c1, C c2) { } + } +} +"; + + string expectedOperationTree = +@" +IBinaryOperation (BinaryOperatorKind.Add) (OperatorMethod: C Extensions.<>E__0.op_Addition(C c1, C c2)) (OperationKind.Binary, Type: C) (Syntax: 'x + y') + Left: + IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C) (Syntax: 'x') + Right: + IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: C) (Syntax: 'y') +"; + + VerifyOperationTreeForTest(source, expectedOperationTree); + } + + [CompilerTrait(CompilerFeature.IOperation)] + [Fact] + public void Extensions_02_Logical() + { + var source = @" +struct C +{ + void F(C x, C y) + { + var z = /**/x || y/**/; + } +} + +static class Extensions +{ + extension(C) + { + public static C operator &(C x, C y) => throw null; + public static C operator |(C x, C y) => throw null; + public static bool operator true(C c) => throw null; + public static bool operator false(C c) => throw null; + } +} +"; + + string expectedOperationTree = +@" +IBinaryOperation (BinaryOperatorKind.ConditionalOr) (OperatorMethod: C Extensions.<>E__0.op_BitwiseOr(C x, C y)) (OperationKind.Binary, Type: C) (Syntax: 'x || y') + Left: + IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C) (Syntax: 'x') + Right: + IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: C) (Syntax: 'y') +"; + + VerifyOperationTreeForTest(source, expectedOperationTree); + } + + [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] + [Fact] + public void Extensions_03_Flow() + { + string source = @" +using System; +class C +{ + void M(C a, C b) + /**/{ + GetArray()[0] = (a ?? b) + (a ?? b); + }/**/ + + static int[] GetArray() => null; +} + +static class Extensions +{ + extension(C) + { + public static int operator +(C c1, C c2) => 0; + } +} +"; + var expectedDiagnostics = DiagnosticDescription.None; + + string expectedGraph = @" +Block[B0] - Entry + Statements (0) + Next (Regular) Block[B1] + Entering: {R1} + +.locals {R1} +{ + CaptureIds: [0] [2] [4] + Block[B1] - Block + Predecessors: [B0] + Statements (1) + IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetArray()[0]') + Value: + IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'GetArray()[0]') + Array reference: + IInvocationOperation (System.Int32[] C.GetArray()) (OperationKind.Invocation, Type: System.Int32[]) (Syntax: 'GetArray()') + Instance Receiver: + null + Arguments(0) + Indices(1): + ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') + + Next (Regular) Block[B2] + Entering: {R2} + + .locals {R2} + { + CaptureIds: [1] + Block[B2] - Block + Predecessors: [B1] + Statements (1) + IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') + Value: + IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: C) (Syntax: 'a') + + Jump if True (Regular) to Block[B4] + IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a') + Operand: + IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'a') + Leaving: {R2} + + Next (Regular) Block[B3] + Block[B3] - Block + Predecessors: [B2] + Statements (1) + IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') + Value: + IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'a') + + Next (Regular) Block[B5] + Leaving: {R2} + Entering: {R3} + } + + Block[B4] - Block + Predecessors: [B2] + Statements (1) + IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') + Value: + IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: C) (Syntax: 'b') + + Next (Regular) Block[B5] + Entering: {R3} + + .locals {R3} + { + CaptureIds: [3] + Block[B5] - Block + Predecessors: [B3] [B4] + Statements (1) + IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') + Value: + IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: C) (Syntax: 'a') + + Jump if True (Regular) to Block[B7] + IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a') + Operand: + IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'a') + Leaving: {R3} + + Next (Regular) Block[B6] + Block[B6] - Block + Predecessors: [B5] + Statements (1) + IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') + Value: + IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'a') + + Next (Regular) Block[B8] + Leaving: {R3} + } + + Block[B7] - Block + Predecessors: [B5] + Statements (1) + IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') + Value: + IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: C) (Syntax: 'b') + + Next (Regular) Block[B8] + Block[B8] - Block + Predecessors: [B6] [B7] + Statements (1) + IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'GetArray()[ ... + (a ?? b);') + Expression: + ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'GetArray()[ ... + (a ?? b)') + Left: + IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'GetArray()[0]') + Right: + IBinaryOperation (BinaryOperatorKind.Add) (OperatorMethod: System.Int32 Extensions.<>E__0.op_Addition(C c1, C c2)) (OperationKind.Binary, Type: System.Int32) (Syntax: '(a ?? b) + (a ?? b)') + Left: + IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'a ?? b') + Right: + IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'a ?? b') + + Next (Regular) Block[B9] + Leaving: {R1} +} + +Block[B9] - Exit + Predecessors: [B8] + Statements (0) +"; + VerifyFlowGraphAndDiagnosticsForTest(source, expectedGraph, expectedDiagnostics); + } + + [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] + [Fact] + public void Extensions_04_Logical_Flow() + { + string source = @" +class C +{ + void M(C a, C b, C result) +/**/{ + result = a || b; + }/**/ +} + +static class Extensions +{ + extension(C) + { + public static C operator &(C x, C y) => throw null; + public static C operator |(C x, C y) => throw null; + public static bool operator true(C c) => throw null; + public static bool operator false(C c) => throw null; + } +} +"; + string expectedGraph = @" +Block[B0] - Entry + Statements (0) + Next (Regular) Block[B1] + Entering: {R1} + +.locals {R1} +{ + CaptureIds: [0] [2] + Block[B1] - Block + Predecessors: [B0] + Statements (1) + IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') + Value: + IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result') + + Next (Regular) Block[B2] + Entering: {R2} + + .locals {R2} + { + CaptureIds: [1] + Block[B2] - Block + Predecessors: [B1] + Statements (1) + IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') + Value: + IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: C) (Syntax: 'a') + + Jump if False (Regular) to Block[B4] + IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean Extensions.<>E__0.op_True(C c)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'a') + Operand: + IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'a') + + Next (Regular) Block[B3] + Block[B3] - Block + Predecessors: [B2] + Statements (1) + IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a || b') + Value: + IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'a') + + Next (Regular) Block[B5] + Leaving: {R2} + Block[B4] - Block + Predecessors: [B2] + Statements (1) + IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a || b') + Value: + IBinaryOperation (BinaryOperatorKind.Or) (OperatorMethod: C Extensions.<>E__0.op_BitwiseOr(C x, C y)) (OperationKind.Binary, Type: C) (Syntax: 'a || b') + Left: + IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'a') + Right: + IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: C) (Syntax: 'b') + + Next (Regular) Block[B5] + Leaving: {R2} + } + + Block[B5] - Block + Predecessors: [B3] [B4] + Statements (1) + IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = a || b;') + Expression: + ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'result = a || b') + Left: + IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'result') + Right: + IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'a || b') + + Next (Regular) Block[B6] + Leaving: {R1} +} + +Block[B6] - Exit + Predecessors: [B5] + Statements (0) +"; + var expectedDiagnostics = DiagnosticDescription.None; + + VerifyFlowGraphAndDiagnosticsForTest(source, expectedGraph, expectedDiagnostics); + } } } diff --git a/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_ICompoundAssignmentOperation.cs b/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_ICompoundAssignmentOperation.cs index bb8954a57e594..8ca61745c7bc6 100644 --- a/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_ICompoundAssignmentOperation.cs +++ b/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_ICompoundAssignmentOperation.cs @@ -1794,6 +1794,431 @@ struct S1 Next (Regular) Block[B10] Leaving: {R1} } +Block[B10] - Exit + Predecessors: [B9] + Statements (0) +"; + VerifyFlowGraphAndDiagnosticsForTest(source, expectedFlowGraph, expectedDiagnostics); + } + + [CompilerTrait(CompilerFeature.IOperation)] + [Fact] + public void Extensions_01() + { + string source = @" +class A +{ + CustomType Method(CustomType x) + { + return /**/x += 1/**/; + } +} +public struct CustomType +{ +} + +static class Extensions +{ + extension(CustomType) + { + public static CustomType operator +(CustomType x, int y) + { + return x; + } + } +} +"; + string expectedOperationTree = @" +ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperatorMethod: CustomType Extensions.<>E__0.op_Addition(CustomType x, System.Int32 y)) (OperationKind.CompoundAssignment, Type: CustomType) (Syntax: 'x += 1') + InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + Left: + IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: CustomType) (Syntax: 'x') + Right: + ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') +"; + VerifyOperationTreeForTest(source, expectedOperationTree); + } + + [CompilerTrait(CompilerFeature.IOperation)] + [Fact] + public void Extensions_02() + { + string source = @" +class A +{ + CustomType Method(CustomType x) + { + return /**/x += 1/**/; + } +} +public struct CustomType +{ +} + +static class Extensions +{ + extension(ref CustomType x) + { + public void operator +=(int y) + { + return x; + } + } +} + +" + CompilerFeatureRequiredAttribute; + + string expectedOperationTree = @" +ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperatorMethod: void Extensions.<>E__0.op_AdditionAssignment(System.Int32 y)) (OperationKind.CompoundAssignment, Type: CustomType) (Syntax: 'x += 1') + InConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + OutConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + Left: + IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: CustomType) (Syntax: 'x') + Right: + ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') +"; + VerifyOperationTreeForTest(source, expectedOperationTree); + } + + [CompilerTrait(CompilerFeature.IOperation)] + [Fact] + public void Extensions_03() + { + string source = @" +class A +{ + CustomType Method(CustomType x) + { + return /**/x += 1/**/; + } +} +public class CustomType +{ +} + +static class Extensions +{ + extension(object) + { + public void operator +=(int y) + { + return x; + } + } +} + +" + CompilerFeatureRequiredAttribute; + + string expectedOperationTree = @" +ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperatorMethod: void Extensions.<>E__0.op_AdditionAssignment(System.Int32 y)) (OperationKind.CompoundAssignment, Type: CustomType) (Syntax: 'x += 1') + InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) + OutConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + Left: + IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: CustomType) (Syntax: 'x') + Right: + ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') +"; + VerifyOperationTreeForTest(source, expectedOperationTree); + } + + [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] + [Fact] + public void Extensions_04_Flow() + { + string source = @" +using System; +class C +{ + void M(S1[] a, int? x, int y, int? b, int c) + /**/{ + a[x ?? y] += b ?? c; + }/**/ +} + +struct S1 +{ +} + +static class Extensions +{ + extension(S1) + { + public static S1 operator +(S1 x, int i) => throw null; + } +} +"; + + var expectedDiagnostics = DiagnosticDescription.None; + + string expectedFlowGraph = @" +Block[B0] - Entry + Statements (0) + Next (Regular) Block[B1] + Entering: {R1} {R2} +.locals {R1} +{ + CaptureIds: [3] [5] + .locals {R2} + { + CaptureIds: [0] [2] + Block[B1] - Block + Predecessors: [B0] + Statements (1) + IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') + Value: + IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S1[]) (Syntax: 'a') + Next (Regular) Block[B2] + Entering: {R3} + .locals {R3} + { + CaptureIds: [1] + Block[B2] - Block + Predecessors: [B1] + Statements (1) + IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') + Value: + IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') + Jump if True (Regular) to Block[B4] + IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x') + Operand: + IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'x') + Leaving: {R3} + Next (Regular) Block[B3] + Block[B3] - Block + Predecessors: [B2] + Statements (1) + IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') + Value: + IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'x') + Instance Receiver: + IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'x') + Arguments(0) + Next (Regular) Block[B5] + Leaving: {R3} + } + Block[B4] - Block + Predecessors: [B2] + Statements (1) + IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') + Value: + IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') + Next (Regular) Block[B5] + Block[B5] - Block + Predecessors: [B3] [B4] + Statements (1) + IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[x ?? y]') + Value: + IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: S1) (Syntax: 'a[x ?? y]') + Array reference: + IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: S1[], IsImplicit) (Syntax: 'a') + Indices(1): + IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x ?? y') + Next (Regular) Block[B6] + Leaving: {R2} + Entering: {R4} + } + .locals {R4} + { + CaptureIds: [4] + Block[B6] - Block + Predecessors: [B5] + Statements (1) + IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') + Value: + IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') + Jump if True (Regular) to Block[B8] + IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') + Operand: + IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') + Leaving: {R4} + Next (Regular) Block[B7] + Block[B7] - Block + Predecessors: [B6] + Statements (1) + IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') + Value: + IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') + Instance Receiver: + IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') + Arguments(0) + Next (Regular) Block[B9] + Leaving: {R4} + } + Block[B8] - Block + Predecessors: [B6] + Statements (1) + IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') + Value: + IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') + Next (Regular) Block[B9] + Block[B9] - Block + Predecessors: [B7] [B8] + Statements (1) + IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[x ?? y] += b ?? c;') + Expression: + ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperatorMethod: S1 Extensions.<>E__0.op_Addition(S1 x, System.Int32 i)) (OperationKind.CompoundAssignment, Type: S1) (Syntax: 'a[x ?? y] += b ?? c') + InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + Left: + IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: S1, IsImplicit) (Syntax: 'a[x ?? y]') + Right: + IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') + Next (Regular) Block[B10] + Leaving: {R1} +} +Block[B10] - Exit + Predecessors: [B9] + Statements (0) +"; + VerifyFlowGraphAndDiagnosticsForTest(source, expectedFlowGraph, expectedDiagnostics); + } + + [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] + [Fact] + public void Extensions_05_Flow() + { + string source = @" +using System; +class C +{ + void M(S1[] a, int? x, int y, int? b, int c) + /**/{ + a[x ?? y] += b ?? c; + }/**/ +} + +struct S1 +{ +} + +static class Extensions +{ + extension(ref S1 x) + { + public void operator +=(int i) {} + } +} +" + CompilerFeatureRequiredAttribute; + + var expectedDiagnostics = DiagnosticDescription.None; + + string expectedFlowGraph = @" +Block[B0] - Entry + Statements (0) + Next (Regular) Block[B1] + Entering: {R1} {R2} +.locals {R1} +{ + CaptureIds: [3] [5] + .locals {R2} + { + CaptureIds: [0] [2] + Block[B1] - Block + Predecessors: [B0] + Statements (1) + IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') + Value: + IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S1[]) (Syntax: 'a') + Next (Regular) Block[B2] + Entering: {R3} + .locals {R3} + { + CaptureIds: [1] + Block[B2] - Block + Predecessors: [B1] + Statements (1) + IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') + Value: + IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') + Jump if True (Regular) to Block[B4] + IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x') + Operand: + IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'x') + Leaving: {R3} + Next (Regular) Block[B3] + Block[B3] - Block + Predecessors: [B2] + Statements (1) + IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') + Value: + IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'x') + Instance Receiver: + IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'x') + Arguments(0) + Next (Regular) Block[B5] + Leaving: {R3} + } + Block[B4] - Block + Predecessors: [B2] + Statements (1) + IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') + Value: + IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') + Next (Regular) Block[B5] + Block[B5] - Block + Predecessors: [B3] [B4] + Statements (1) + IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[x ?? y]') + Value: + IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: S1) (Syntax: 'a[x ?? y]') + Array reference: + IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: S1[], IsImplicit) (Syntax: 'a') + Indices(1): + IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x ?? y') + Next (Regular) Block[B6] + Leaving: {R2} + Entering: {R4} + } + .locals {R4} + { + CaptureIds: [4] + Block[B6] - Block + Predecessors: [B5] + Statements (1) + IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') + Value: + IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') + Jump if True (Regular) to Block[B8] + IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') + Operand: + IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') + Leaving: {R4} + Next (Regular) Block[B7] + Block[B7] - Block + Predecessors: [B6] + Statements (1) + IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') + Value: + IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') + Instance Receiver: + IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') + Arguments(0) + Next (Regular) Block[B9] + Leaving: {R4} + } + Block[B8] - Block + Predecessors: [B6] + Statements (1) + IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') + Value: + IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') + Next (Regular) Block[B9] + Block[B9] - Block + Predecessors: [B7] [B8] + Statements (1) + IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[x ?? y] += b ?? c;') + Expression: + ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperatorMethod: void Extensions.<>E__0.op_AdditionAssignment(System.Int32 i)) (OperationKind.CompoundAssignment, Type: System.Void) (Syntax: 'a[x ?? y] += b ?? c') + InConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + OutConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) + Left: + IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: S1, IsImplicit) (Syntax: 'a[x ?? y]') + Right: + IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') + Next (Regular) Block[B10] + Leaving: {R1} +} Block[B10] - Exit Predecessors: [B9] Statements (0) diff --git a/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IIncrementOrDecrementOperation.cs b/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IIncrementOrDecrementOperation.cs index 7ba7edff4ca24..236b4a68d3008 100644 --- a/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IIncrementOrDecrementOperation.cs +++ b/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IIncrementOrDecrementOperation.cs @@ -221,5 +221,292 @@ struct S1 VerifyFlowGraphAndDiagnosticsForTest(source, expectedFlowGraph, expectedDiagnostics); } + [CompilerTrait(CompilerFeature.IOperation)] + [Fact] + public void Extensions_01() + { + string source = @" +class A +{ + CustomType Method(CustomType x) + { + return /**/--x/**/; + } +} +public struct CustomType +{ +} + +static class Extensions +{ + extension(CustomType) + { + public static CustomType operator --(CustomType x) + { + return x; + } + } +} +"; + string expectedOperationTree = @" +IIncrementOrDecrementOperation (Prefix) (OperatorMethod: CustomType Extensions.<>E__0.op_Decrement(CustomType x)) (OperationKind.Decrement, Type: CustomType) (Syntax: '--x') + Target: + IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: CustomType) (Syntax: 'x') +"; + VerifyOperationTreeForTest(source, expectedOperationTree); + } + + [CompilerTrait(CompilerFeature.IOperation)] + [Fact] + public void Extensions_02() + { + string source = @" +class A +{ + CustomType Method(CustomType x) + { + return /**/--x/**/; + } +} +public struct CustomType +{ +} + +static class Extensions +{ + extension(ref CustomType x) + { + public void operator --() + { + return x; + } + } +} + +" + CompilerFeatureRequiredAttribute; + + string expectedOperationTree = @" +IIncrementOrDecrementOperation (Prefix) (OperatorMethod: void Extensions.<>E__0.op_DecrementAssignment()) (OperationKind.Decrement, Type: CustomType) (Syntax: '--x') + Target: + IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: CustomType) (Syntax: 'x') +"; + VerifyOperationTreeForTest(source, expectedOperationTree); + } + + [CompilerTrait(CompilerFeature.IOperation)] + [Fact] + public void Extensions_03() + { + string source = @" +class A +{ + CustomType Method(CustomType x) + { + return /**/--x/**/; + } +} +public class CustomType +{ +} + +static class Extensions +{ + extension(object) + { + public void operator --() + { + return x; + } + } +} + +" + CompilerFeatureRequiredAttribute; + + string expectedOperationTree = @" +IIncrementOrDecrementOperation (Prefix) (OperatorMethod: void Extensions.<>E__0.op_DecrementAssignment()) (OperationKind.Decrement, Type: CustomType) (Syntax: '--x') + Target: + IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: CustomType) (Syntax: 'x') +"; + VerifyOperationTreeForTest(source, expectedOperationTree); + } + + [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] + [Fact] + public void Extensions_04_Flow() + { + string source = @" +class C +{ + void M(D x, D y) + /**/{ + (x ?? y).i++; + }/**/ + public class D { public S1 i; } +} + +struct S1 +{ +} + +static class Extensions +{ + extension(S1) + { + public static S1 operator ++(S1 x) + { + return x; + } + } +} +" + CompilerFeatureRequiredAttribute; + + var expectedDiagnostics = DiagnosticDescription.None; + + string expectedFlowGraph = @" +Block[B0] - Entry + Statements (0) + Next (Regular) Block[B1] + Entering: {R1} {R2} +.locals {R1} +{ + CaptureIds: [1] + .locals {R2} + { + CaptureIds: [0] + Block[B1] - Block + Predecessors: [B0] + Statements (1) + IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') + Value: + IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C.D) (Syntax: 'x') + Jump if True (Regular) to Block[B3] + IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x') + Operand: + IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C.D, IsImplicit) (Syntax: 'x') + Leaving: {R2} + Next (Regular) Block[B2] + Block[B2] - Block + Predecessors: [B1] + Statements (1) + IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') + Value: + IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C.D, IsImplicit) (Syntax: 'x') + Next (Regular) Block[B4] + Leaving: {R2} + } + Block[B3] - Block + Predecessors: [B1] + Statements (1) + IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') + Value: + IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: C.D) (Syntax: 'y') + Next (Regular) Block[B4] + Block[B4] - Block + Predecessors: [B2] [B3] + Statements (1) + IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(x ?? y).i++;') + Expression: + IIncrementOrDecrementOperation (Postfix) (OperatorMethod: S1 Extensions.<>E__0.op_Increment(S1 x)) (OperationKind.Increment, Type: S1) (Syntax: '(x ?? y).i++') + Target: + IFieldReferenceOperation: S1 C.D.i (OperationKind.FieldReference, Type: S1) (Syntax: '(x ?? y).i') + Instance Receiver: + IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C.D, IsImplicit) (Syntax: 'x ?? y') + Next (Regular) Block[B5] + Leaving: {R1} +} +Block[B5] - Exit + Predecessors: [B4] + Statements (0) +"; + VerifyFlowGraphAndDiagnosticsForTest(source, expectedFlowGraph, expectedDiagnostics); + } + + [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] + [Fact] + public void Extensions_05_Flow() + { + string source = @" +class C +{ + void M(D x, D y) + /**/{ + (x ?? y).i++; + }/**/ + public class D { public S1 i; } +} + +struct S1 +{ +} + +static class Extensions +{ + extension(ref S1 x) + { + public void operator ++() {} + } +} +" + CompilerFeatureRequiredAttribute; + + var expectedDiagnostics = DiagnosticDescription.None; + + string expectedFlowGraph = @" +Block[B0] - Entry + Statements (0) + Next (Regular) Block[B1] + Entering: {R1} {R2} +.locals {R1} +{ + CaptureIds: [1] + .locals {R2} + { + CaptureIds: [0] + Block[B1] - Block + Predecessors: [B0] + Statements (1) + IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') + Value: + IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C.D) (Syntax: 'x') + Jump if True (Regular) to Block[B3] + IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x') + Operand: + IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C.D, IsImplicit) (Syntax: 'x') + Leaving: {R2} + Next (Regular) Block[B2] + Block[B2] - Block + Predecessors: [B1] + Statements (1) + IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') + Value: + IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C.D, IsImplicit) (Syntax: 'x') + Next (Regular) Block[B4] + Leaving: {R2} + } + Block[B3] - Block + Predecessors: [B1] + Statements (1) + IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') + Value: + IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: C.D) (Syntax: 'y') + Next (Regular) Block[B4] + Block[B4] - Block + Predecessors: [B2] [B3] + Statements (1) + IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(x ?? y).i++;') + Expression: + IIncrementOrDecrementOperation (Postfix) (OperatorMethod: void Extensions.<>E__0.op_IncrementAssignment()) (OperationKind.Increment, Type: System.Void) (Syntax: '(x ?? y).i++') + Target: + IFieldReferenceOperation: S1 C.D.i (OperationKind.FieldReference, Type: S1) (Syntax: '(x ?? y).i') + Instance Receiver: + IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C.D, IsImplicit) (Syntax: 'x ?? y') + Next (Regular) Block[B5] + Leaving: {R1} +} +Block[B5] - Exit + Predecessors: [B4] + Statements (0) +"; + VerifyFlowGraphAndDiagnosticsForTest(source, expectedFlowGraph, expectedDiagnostics); + } } } diff --git a/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IUnaryOperatorExpression.cs b/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IUnaryOperatorExpression.cs index 2d5e09c9624fb..ab285d66c1bb7 100644 --- a/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IUnaryOperatorExpression.cs +++ b/src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IUnaryOperatorExpression.cs @@ -3687,5 +3687,93 @@ void M(byte arg) var operation = (IUnaryOperation)VerifyOperationTreeForTest(compilation, expectedOperationTree); Assert.Null(operation.OperatorMethod); } + + [CompilerTrait(CompilerFeature.IOperation)] + [Fact] + public void Test_UnaryOperatorExpression_Extension() + { + string source = @" +class A +{ + CustomType Method() + { + CustomType i = default(CustomType); + return /**/-Method()/**/; + } +} +public struct CustomType +{ +} + +static class Extensions +{ + extension(CustomType) + { + public static CustomType operator -(CustomType x) + { + return x; + } + } +} +"; + string expectedOperationTree = @" +IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: CustomType Extensions.<>E__0.op_UnaryNegation(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '-Method()') + Operand: + IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()') + Instance Receiver: + IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') + Arguments(0) +"; + VerifyOperationTreeForTest(source, expectedOperationTree); + } + + [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] + [Fact] + public void Test_UnaryOperatorExpression_Extension_Flow() + { + string source = @" +class A +{ + CustomType F(CustomType f) + /**/{ + return !f; + }/**/ + + CustomType Method() => throw null; +} +public struct CustomType +{ +} + +static class Extensions +{ + extension(CustomType) + { + public static CustomType operator !(CustomType x) + { + return x; + } + } +} +"; + string expectedGraph = @" +Block[B0] - Entry + Statements (0) + Next (Regular) Block[B1] +Block[B1] - Block + Predecessors: [B0] + Statements (0) + Next (Return) Block[B2] + IUnaryOperation (UnaryOperatorKind.Not) (OperatorMethod: CustomType Extensions.<>E__0.op_LogicalNot(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '!f') + Operand: + IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: CustomType) (Syntax: 'f') +Block[B2] - Exit + Predecessors: [B1] + Statements (0) +"; + var expectedDiagnostics = DiagnosticDescription.None; + + VerifyFlowGraphAndDiagnosticsForTest(source, expectedGraph, expectedDiagnostics); + } } } diff --git a/src/Compilers/CSharp/Test/Semantic/Semantics/InitOnlyMemberTests.cs b/src/Compilers/CSharp/Test/Semantic/Semantics/InitOnlyMemberTests.cs index 042a87f2469b6..6c4f2017ccc45 100644 --- a/src/Compilers/CSharp/Test/Semantic/Semantics/InitOnlyMemberTests.cs +++ b/src/Compilers/CSharp/Test/Semantic/Semantics/InitOnlyMemberTests.cs @@ -4714,9 +4714,9 @@ public class C var comp = CreateEmptyCompilation(source, references: new[] { corlibWithIsExternalInitRef, libWithIsExternalInitRef, libWithIsExternalInitRef2 }, options: TestOptions.DebugDll.WithTopLevelBinderFlags(BinderFlags.IgnoreCorLibraryDuplicatedTypes)); comp.VerifyEmitDiagnostics( - // (4,32): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported + // (4,32): error CS8356: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is declared in multiple referenced assemblies: 'libWithIsExternalInit, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'libWithIsExternalInit2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // public int Property { get; init; } - Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "init").WithArguments("System.Runtime.CompilerServices.IsExternalInit").WithLocation(4, 32) + Diagnostic(ErrorCode.ERR_PredefinedTypeAmbiguous, "init").WithArguments("System.Runtime.CompilerServices.IsExternalInit", "libWithIsExternalInit, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "libWithIsExternalInit2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(4, 32) ); } @@ -4724,9 +4724,9 @@ public class C // type in two libraries var comp = CreateEmptyCompilation(source, references: new[] { corlibWithoutIsExternalInitRef, libWithIsExternalInitRef, libWithIsExternalInitRef2 }); comp.VerifyEmitDiagnostics( - // (4,32): error CS018: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported + // (4,32): error CS8356: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is declared in multiple referenced assemblies: 'libWithIsExternalInit, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'libWithIsExternalInit2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // public int Property { get; init; } - Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "init").WithArguments("System.Runtime.CompilerServices.IsExternalInit").WithLocation(4, 32) + Diagnostic(ErrorCode.ERR_PredefinedTypeAmbiguous, "init").WithArguments("System.Runtime.CompilerServices.IsExternalInit", "libWithIsExternalInit, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "libWithIsExternalInit2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(4, 32) ); } @@ -4735,9 +4735,9 @@ public class C var comp = CreateEmptyCompilation(source, references: new[] { corlibWithoutIsExternalInitRef, libWithIsExternalInitRef, libWithIsExternalInitRef2 }, options: TestOptions.DebugDll.WithTopLevelBinderFlags(BinderFlags.IgnoreCorLibraryDuplicatedTypes)); comp.VerifyEmitDiagnostics( - // (4,32): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported + // (4,32): error CS8356: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is declared in multiple referenced assemblies: 'libWithIsExternalInit, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'libWithIsExternalInit2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // public int Property { get; init; } - Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "init").WithArguments("System.Runtime.CompilerServices.IsExternalInit").WithLocation(4, 32) + Diagnostic(ErrorCode.ERR_PredefinedTypeAmbiguous, "init").WithArguments("System.Runtime.CompilerServices.IsExternalInit", "libWithIsExternalInit, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "libWithIsExternalInit2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(4, 32) ); } diff --git a/src/Compilers/CSharp/Test/Semantic/Semantics/InterceptorsTests.cs b/src/Compilers/CSharp/Test/Semantic/Semantics/InterceptorsTests.cs index 960e0e7476c0c..212f2d5c75966 100644 --- a/src/Compilers/CSharp/Test/Semantic/Semantics/InterceptorsTests.cs +++ b/src/Compilers/CSharp/Test/Semantic/Semantics/InterceptorsTests.cs @@ -34,6 +34,7 @@ public InterceptsLocationAttribute(int version, string data) { } """, "attributes.cs"); private static readonly CSharpParseOptions RegularWithInterceptors = TestOptions.Regular.WithFeature("InterceptorsNamespaces", "global"); + private static readonly CSharpParseOptions RegularPreviewWithInterceptors = TestOptions.RegularPreview.WithFeature("InterceptorsNamespaces", "global"); private static readonly SyntaxTree s_attributesTree = CSharpTestSource.Parse(s_attributesSource.text, s_attributesSource.path, RegularWithInterceptors); @@ -8481,4 +8482,1094 @@ static class D var method = model.GetInterceptorMethod(node); AssertEx.Equal("System.Span D.M(this ref S s)", method.ToTestDisplayString()); } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_01() + { + // original calls use extensions, interceptors are classic + var source = """ +object.M(); +" ran".M2(); + +static class E +{ + extension(object o) + { + public static void M() => throw null; + public void M2() => throw null; + } +} +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +static class Interceptors +{ + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public static void Method() { System.Console.Write(42); } + + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[1]!)}})] + public static void Method2(this object o) { System.Console.Write(o); } +} +"""; + CompileAndVerify([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors, expectedOutput: "42 ran").VerifyDiagnostics(); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_02() + { + // top-level difference in receiver parameter nullability + var source = """ +#nullable enable + +new object().M(); + +static class E +{ + extension(object o) + { + public void M() => throw null!; + } +} +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +#nullable enable + +static class Interceptors +{ + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public static void Method(this object? o) { System.Console.Write("ran"); } +} +"""; + CompileAndVerify([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors, expectedOutput: "ran").VerifyDiagnostics(); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_03() + { + // nested difference in receiver parameter nullability + var source = """ +#nullable enable + +new C().M(); + +static class E +{ + extension(C o) + { + public void M() => throw null!; + } +} + +class C { } +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +#nullable enable + +static class Interceptors +{ + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public static void Method(this C o) { } +} +"""; + var comp = CreateCompilation([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors); + comp.VerifyEmitDiagnostics( + // (5,6): error CS9148: Interceptor must have a 'this' parameter matching parameter 'C o' on 'E.extension(C).M()'. + // [System.Runtime.CompilerServices.InterceptsLocation(1, "T81R8uSCzQRaZ7VAf0D7uCQAAAA=")] + Diagnostic(ErrorCode.ERR_InterceptorMustHaveMatchingThisParameter, "System.Runtime.CompilerServices.InterceptsLocation").WithArguments("C o", "E.extension(C).M()").WithLocation(5, 6)); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_04() + { + // refness difference in receiver parameter + var source = """ +42.M(); + +static class E +{ + extension(int i) + { + public void M() => throw null!; + } +} +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +static class Interceptors +{ + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public static void Method(ref this int i) { } +} +"""; + var comp = CreateCompilation([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors); + comp.VerifyEmitDiagnostics( + // (3,6): error CS9148: Interceptor must have a 'this' parameter matching parameter 'int i' on 'E.extension(int).M()'. + // [System.Runtime.CompilerServices.InterceptsLocation(1, "JjM6W8JDDhaVDDV4fi7OigMAAAA=")] + Diagnostic(ErrorCode.ERR_InterceptorMustHaveMatchingThisParameter, "System.Runtime.CompilerServices.InterceptsLocation").WithArguments("int i", "E.extension(int).M()").WithLocation(3, 6)); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_05() + { + var source = """ +42.M(); + +static class E +{ + extension(int i) + { + public void M() => throw null!; + } +} +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +static class Interceptors +{ + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public static void Method() { } +} +"""; + var comp = CreateCompilation([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors); + comp.VerifyEmitDiagnostics( + // (3,6): error CS9148: Interceptor must have a 'this' parameter matching parameter 'int i' on 'E.extension(int).M()'. + // [System.Runtime.CompilerServices.InterceptsLocation(1, "JjM6W8JDDhaVDDV4fi7OigMAAAA=")] + Diagnostic(ErrorCode.ERR_InterceptorMustHaveMatchingThisParameter, "System.Runtime.CompilerServices.InterceptsLocation").WithArguments("int i", "E.extension(int).M()").WithLocation(3, 6)); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_06() + { + var source = """ +42.M(); + +static class E +{ + extension(int i) + { + public void M() => throw null!; + } +} +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +static class Interceptors +{ + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public static void Method(int i) { } +} +"""; + var comp = CreateCompilation([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors); + comp.VerifyEmitDiagnostics( + // (3,6): error CS9144: Cannot intercept method 'E.extension(int).M()' with interceptor 'Interceptors.Method(int)' because the signatures do not match. + // [System.Runtime.CompilerServices.InterceptsLocation(1, "JjM6W8JDDhaVDDV4fi7OigMAAAA=")] + Diagnostic(ErrorCode.ERR_InterceptorSignatureMismatch, "System.Runtime.CompilerServices.InterceptsLocation").WithArguments("E.extension(int).M()", "Interceptors.Method(int)").WithLocation(3, 6)); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_07() + { + // original calls use static extension, interceptors with and without `this` + var source = """ +int.M(42); +int.M(43); + +static class E +{ + extension(int) + { + public static void M(int i) => throw null!; + } +} +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +static class Interceptors +{ + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public static void Method(int i) { System.Console.Write(i); } + + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[1]!)}})] + public static void Method2(this int i) { System.Console.Write(i); } +} +"""; + CompileAndVerify([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors, expectedOutput: "4243").VerifyDiagnostics(); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_09() + { + // original calls use non-extension invocations, interceptor is an extension method + var source = """ +C.M(); +new C().M2(); + +class C +{ + public static void M() => throw null!; + public void M2() => throw null!; +} +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +static class Interceptors +{ + extension(C c) + { + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public static void Method() { System.Console.Write("ran "); } + + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[1]!)}})] + public void Method2() { System.Console.Write(c); } + } +} +"""; + CompileAndVerify([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors, expectedOutput: "ran C").VerifyDiagnostics(); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_10() + { + // original call uses non-extension instance invocations, interceptor is a static extension method + var source = """ +new C().M2(); + +class C +{ + public void M2() => throw null!; +} +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +static class Interceptors +{ + extension(C) + { + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public static void Method(C c) { } + } +} +"""; + var comp = CreateCompilation([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors); + comp.VerifyEmitDiagnostics( + // (5,10): error CS9144: Cannot intercept method 'C.M2()' with interceptor 'Interceptors.Method(C)' because the signatures do not match. + // [System.Runtime.CompilerServices.InterceptsLocation(1, "6ii77DXfMpjahn56tJIXdAgAAAA=")] + Diagnostic(ErrorCode.ERR_InterceptorSignatureMismatch, "System.Runtime.CompilerServices.InterceptsLocation").WithArguments("C.M2()", "Interceptors.Method(C)").WithLocation(5, 10)); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_11() + { + // original call uses classic extension invocations, interceptor is a new extension method + var source = """ +new object().M(); + +public static class Extensions +{ + public static void M(this object o) => throw null; +} +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +static class Interceptors +{ + extension(object o) + { + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public void Method() { System.Console.Write("ran"); } + } +} +"""; + CompileAndVerify([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors, expectedOutput: "ran").VerifyDiagnostics(); + + interceptors = $$""" +static class Interceptors +{ + extension(object) + { + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public static void Method(object o) { } + } +} +"""; + var comp = CreateCompilation([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors); + comp.VerifyEmitDiagnostics( + // (5,10): error CS9148: Interceptor must have a 'this' parameter matching parameter 'object o' on 'Extensions.M(object)'. + // [System.Runtime.CompilerServices.InterceptsLocation(1, "rthnOf6S6aLCQ1g5K5pDgA0AAAA=")] + Diagnostic(ErrorCode.ERR_InterceptorMustHaveMatchingThisParameter, "System.Runtime.CompilerServices.InterceptsLocation").WithArguments("object o", "Extensions.M(object)").WithLocation(5, 10)); + + interceptors = $$""" +static class Interceptors +{ + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public static void Method(this object o) { System.Console.Write("ran"); } +} +"""; + CompileAndVerify([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors, expectedOutput: "ran").VerifyDiagnostics(); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_12() + { + // original call uses new extension invocations, interceptors are new extension methods + var source = """ +object.M(); +new object().M2(); + +public static class Extensions +{ + extension(object o) + { + public static void M() => throw null; + public void M2() => throw null; + } +} +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +static class Interceptors +{ + extension(object o) + { + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public static void Method() { System.Console.Write("ran1 "); } + + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[1]!)}})] + public void Method2() { System.Console.Write("ran2"); } + } +} +"""; + CompileAndVerify([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors, expectedOutput: "ran1 ran2").VerifyDiagnostics(); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_13() + { + // interception within extension body + var source = """ +public static class E +{ + extension(int i) + { + public void M() + { + i.ToString(); + } + + public string P => i.ToString(); + + public static void M2() + { + 42.ToString(); + } + + public static string P2 => 43.ToString(); + } +} +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +10.M(); +_ = 11.P; +int.M2(); +_ = int.P2; + +static class Interceptors +{ + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public static string Method1(this ref int o) { System.Console.Write("ran1 "); return ""; } + + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[1]!)}})] + public static string Method2(this ref int i) { System.Console.Write("ran2 "); return ""; } + + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[2]!)}})] + public static string Method3(this ref int i) { System.Console.Write("ran3 "); return ""; } + + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[3]!)}})] + public static string Method4(this ref int i) { System.Console.Write("ran4 "); return ""; } +} +"""; + CompileAndVerify([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors, expectedOutput: "ran1 ran2 ran3 ran4").VerifyDiagnostics(); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_14() + { + // mismatch in return types + var source = """ +public static class E +{ + extension(int i) + { + public void M() + { + i.ToString(); + } + } +} +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +static class Interceptors +{ + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public static void Method1(this ref int o) { } +} +"""; + var comp = CreateCompilation([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors); + // Consider printing the return types as part of the compared signatures with FormattedSymbol + comp.VerifyEmitDiagnostics( + // (3,6): error CS9144: Cannot intercept method 'int.ToString()' with interceptor 'Interceptors.Method1(ref int)' because the signatures do not match. + // [System.Runtime.CompilerServices.InterceptsLocation(1, "24Q46HTnfKKGDA49FINUx2kAAAA=")] + Diagnostic(ErrorCode.ERR_InterceptorSignatureMismatch, "System.Runtime.CompilerServices.InterceptsLocation").WithArguments("int.ToString()", "Interceptors.Method1(ref int)").WithLocation(3, 6)); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_15() + { + var source = """ +object.M(new object()); + +public static class E +{ + extension(object) + { + public static void M(object o) { } + } +} +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +static class Interceptors +{ + extension(object o) + { + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public void Method(object o2) { } + } +} +"""; + var comp = CreateCompilation([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors); + comp.VerifyEmitDiagnostics( + // (5,10): error CS9144: Cannot intercept method 'E.extension(object).M(object)' with interceptor 'Interceptors.Method(object, object)' because the signatures do not match. + // [System.Runtime.CompilerServices.InterceptsLocation(1, "CtYO/tuDG+qIspclOkHaEwcAAAA=")] + Diagnostic(ErrorCode.ERR_InterceptorSignatureMismatch, "System.Runtime.CompilerServices.InterceptsLocation").WithArguments("E.extension(object).M(object)", "Interceptors.Method(object, object)").WithLocation(5, 10)); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_16() + { + // receiver initially isn't converted (would be handled as constrained call) but gets converted for interceptor + var source = """ +new S().ToString(); + +struct S { } +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +static class Interceptors +{ + extension(System.ValueType v) + { + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public string Method() { System.Console.Write("ran"); return ""; } + } +} +"""; + CompileAndVerify([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors, expectedOutput: "ran").VerifyDiagnostics(); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_17() + { + // Implicitly capture receiver to temp in 's.M()' because target method needs a writable reference. + var source = """ +S.M0(new S()); + +public struct S +{ + void M() => System.Console.WriteLine(0); + + public static void M0(in S s) + { + s.M(); + } +} +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +static class Interceptors +{ + extension(ref S s) + { + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[2]!)}})] + public void Method() => System.Console.WriteLine("ran"); + } +} +"""; + var verifier = CompileAndVerify([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors, expectedOutput: "ran").VerifyDiagnostics(); + verifier.VerifyIL("S.M0", """ +{ + // Code size 15 (0xf) + .maxstack 1 + .locals init (S V_0) + IL_0000: ldarg.0 + IL_0001: ldobj "S" + IL_0006: stloc.0 + IL_0007: ldloca.s V_0 + IL_0009: call "void Interceptors.Method(ref S)" + IL_000e: ret +} +"""); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_18() + { + // Nullability difference in return + var source = """ +#nullable enable + +new object().M(); +new object().M(); +new object().M(); + +new object().M2(); +new object().M2(); +new object().M2(); + +new object().M3(); +new object().M3(); +new object().M3(); + +static class E +{ + public static string M(this object o) => throw null!; + public static string? M2(this object o) => throw null!; +#nullable disable + public static string M3(this object o) => throw null!; +} +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +#nullable enable + +static class Interceptors +{ + extension(object o) + { + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public string Method0() { System.Console.Write("ran0 "); return ""; } + + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[1]!)}})] // 1 + public string? Method1() { System.Console.Write("ran1 "); return ""; } + +#nullable disable + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[2]!)}})] + public string Method2() { System.Console.Write("ran2 "); return ""; } + +#nullable enable + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[3]!)}})] + public string Method3() { System.Console.Write("ran3 "); return ""; } + + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[4]!)}})] + public string? Method4() { System.Console.Write("ran4 "); return ""; } + +#nullable disable + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[5]!)}})] + public string Method5() { System.Console.Write("ran5 "); return ""; } + +#nullable enable + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[6]!)}})] + public string Method6() { System.Console.Write("ran6 "); return ""; } + + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[7]!)}})] + public string? Method7() { System.Console.Write("ran7 "); return ""; } + +#nullable disable + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[8]!)}})] + public string Method8() { System.Console.Write("ran8 "); return ""; } + } +} +"""; + var comp = CreateCompilation([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors); + CompileAndVerify(comp, expectedOutput: "ran0 ran1 ran2 ran3 ran4 ran5 ran6 ran7 ran8").VerifyDiagnostics( + // (10,10): warning CS9158: Nullability of reference types in return type doesn't match interceptable method 'E.M(object)'. + // [System.Runtime.CompilerServices.InterceptsLocation(1, "kyzJ78tfBnC7NCAmEETPGDQAAAA=")] // 1 + Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnInterceptor, "System.Runtime.CompilerServices.InterceptsLocation").WithArguments("E.M(object)").WithLocation(10, 10)); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_19() + { + // Nullability difference in parameter + var source = """ +#nullable enable + +new object().M(""); +new object().M(""); +new object().M(""); + +new object().M2(""); +new object().M2(""); +new object().M2(""); + +new object().M3(""); +new object().M3(""); +new object().M3(""); + +static class E +{ + public static void M(this object o, string s) => throw null!; + public static void M2(this object o, string? s) => throw null!; +#nullable disable + public static void M3(this object o, string s) => throw null!; +} +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +#nullable enable + +static class Interceptors +{ + extension(object o) + { + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public void Method0(string s) { System.Console.Write("ran0 "); } + + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[1]!)}})] + public void Method1(string? s) { System.Console.Write("ran1 "); } + +#nullable disable + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[2]!)}})] + public void Method2(string s) { System.Console.Write("ran2 "); } + +#nullable enable + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[3]!)}})] // 1 + public void Method3(string s) { System.Console.Write("ran3 "); } + + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[4]!)}})] + public void Method4(string? s) { System.Console.Write("ran4 "); } + +#nullable disable + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[5]!)}})] + public void Method5(string s) { System.Console.Write("ran5 "); } + +#nullable enable + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[6]!)}})] + public void Method6(string s) { System.Console.Write("ran6 "); } + + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[7]!)}})] + public void Method7(string? s) { System.Console.Write("ran7 "); } + +#nullable disable + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[8]!)}})] + public void Method8(string s) { System.Console.Write("ran8 "); } + } +} +"""; + var comp = CreateCompilation([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors); + + CompileAndVerify(comp, expectedOutput: "ran0 ran1 ran2 ran3 ran4 ran5 ran6 ran7 ran8").VerifyDiagnostics( + // (18,10): warning CS9159: Nullability of reference types in type of parameter 's' doesn't match interceptable method 'E.M2(object, string?)'. + // [System.Runtime.CompilerServices.InterceptsLocation(1, "+VOLrIHFLh9ndZzTPFZ19mIAAAA=")] // 1 + Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnInterceptor, "System.Runtime.CompilerServices.InterceptsLocation").WithArguments("s", "E.M2(object, string?)").WithLocation(18, 10)); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_20() + { + // Nullability of receiver, original is extension method + var source = """ +#nullable enable + +object? oNull = null; +oNull.M(); // 1 + +object? oNull2 = null; +oNull2.M(); + +object? oNotNull = new object(); +oNotNull.M(); +oNotNull.M(); + +static class E +{ + public static void M(this object? o) => throw null!; +} +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +#nullable enable + +static class Interceptors +{ + extension(object o) + { + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] // 1 + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[2]!)}})] // 2 + public void Method0() { System.Console.Write("ran0 "); } + } + + extension(object? o) + { + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[1]!)}})] + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[3]!)}})] + public void Method1() { System.Console.Write("ran1 "); } + } +} +"""; + var comp = CreateCompilation([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors); + + CompileAndVerify(comp, expectedOutput: "ran0 ran1 ran0 ran1").VerifyDiagnostics( + // (7,10): warning CS9159: Nullability of reference types in type of parameter 'o' doesn't match interceptable method 'E.M(object?)'. + // [System.Runtime.CompilerServices.InterceptsLocation(1, "UOx514BZZQx0rQJnlTZlGTEAAAA=")] // 1 + Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnInterceptor, "System.Runtime.CompilerServices.InterceptsLocation").WithArguments("o", "E.M(object?)").WithLocation(7, 10), + // (8,10): warning CS9159: Nullability of reference types in type of parameter 'o' doesn't match interceptable method 'E.M(object?)'. + // [System.Runtime.CompilerServices.InterceptsLocation(1, "UOx514BZZQx0rQJnlTZlGZAAAAA=")] // 2 + Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnInterceptor, "System.Runtime.CompilerServices.InterceptsLocation").WithArguments("o", "E.M(object?)").WithLocation(8, 10)); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_21() + { + // Nullability of receiver, original is instance method + var source = """ +#nullable enable + +object? oNull = null; +oNull.ToString(); // 1 + +object? oNull2 = null; +oNull2.ToString(); // 2 + +object? oNotNull = new object(); +oNotNull.ToString(); +oNotNull.ToString(); + +object? oNull3 = null; +oNull3.ToString(); // 3 +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +#nullable enable + +static class Interceptors +{ + extension(object o) + { + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[2]!)}})] + public string Method0() { System.Console.Write("ran0 "); return ""; } + } + + extension(object? o) + { + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[1]!)}})] + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[3]!)}})] + public string Method1() { System.Console.Write("ran1 "); return ""; } + } + + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[4]!)}})] + public static string Method2(this object o) { System.Console.Write("ran2 "); return ""; } +} +"""; + var comp = CreateCompilation([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors); + + CompileAndVerify(comp, expectedOutput: "ran0 ran1 ran0 ran1 ran2").VerifyDiagnostics( + // (4,1): warning CS8602: Dereference of a possibly null reference. + // oNull.ToString(); // 1 + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "oNull").WithLocation(4, 1), + // (7,1): warning CS8602: Dereference of a possibly null reference. + // oNull2.ToString(); // 2 + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "oNull2").WithLocation(7, 1), + // (14,1): warning CS8602: Dereference of a possibly null reference. + // oNull3.ToString(); // 3 + Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "oNull3").WithLocation(14, 1)); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_22() + { + // Tuple names difference in return + var source = """ +new object().M(); +new object().M(); + +static class E +{ + public static (object a, object b) M(this object o) => throw null!; + public static (object a, object b) M2(this object o) => throw null!; +} +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +static class Interceptors +{ + extension(object o) + { + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public (object a, object b) Method0() { System.Console.Write("ran0 "); return (null!, null!); } + + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[1]!)}})] // 1 + public (object other1, object other2) Method1() { System.Console.Write("ran1 "); return (null!, null!); } + } } +"""; + var comp = CreateCompilation([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors); + + CompileAndVerify(comp, expectedOutput: "ran0 ran1").VerifyDiagnostics( + // (8,10): warning CS9154: Intercepting a call to 'E.M(object)' with interceptor 'Interceptors.Method1(object)', but the signatures do not match. + // [System.Runtime.CompilerServices.InterceptsLocation(1, "ZhBCDQ5cTiMfojQyN7NYNyAAAAA=")] // 1 + Diagnostic(ErrorCode.WRN_InterceptorSignatureMismatch, "System.Runtime.CompilerServices.InterceptsLocation").WithArguments("E.M(object)", "Interceptors.Method1(object)").WithLocation(8, 10)); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_23() + { + // scoped difference in parameter, original is extension method + var source = """ +RS s = new RS(); +new object().M(ref s); +new object().M(ref s); + +new object().M2(ref s); +new object().M2(ref s); + +static class E +{ + public static void M(this object o, scoped ref RS s) => throw null!; + public static void M2(this object o, ref RS s) => throw null!; +} + +public ref struct RS { } +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +static class Interceptors +{ + extension(object o) + { + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[2]!)}})] + public void Method0(scoped ref RS s) => throw null!; + + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[1]!)}})] // 1 + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[3]!)}})] + public void Method1(ref RS s) => throw null!; + } +} +"""; + var comp = CreateCompilation([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors); + comp.VerifyEmitDiagnostics( + // (9,10): error CS9156: Cannot intercept call to 'E.M(object, scoped ref RS)' with 'Interceptors.Method1(object, ref RS)' because of a difference in 'scoped' modifiers or '[UnscopedRef]' attributes. + // [System.Runtime.CompilerServices.InterceptsLocation(1, "FcYsmv49zJYGD+zKGdRnfDcAAAA=")] // 1 + Diagnostic(ErrorCode.ERR_InterceptorScopedMismatch, "System.Runtime.CompilerServices.InterceptsLocation").WithArguments("E.M(object, scoped ref RS)", "Interceptors.Method1(object, ref RS)").WithLocation(9, 10)); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_24() + { + // scoped difference in parameter, original is instance method + var source = """ +RS s = new RS(); +new C().M(ref s); +new C().M(ref s); + +new C().M2(ref s); +new C().M2(ref s); + +public class C +{ + public void M(scoped ref RS s) => throw null!; + public void M2(ref RS s) => throw null!; +} + +public ref struct RS { } +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +static class Interceptors +{ + extension(C c) + { + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[2]!)}})] + public void Method0(scoped ref RS s) => throw null!; + + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[1]!)}})] // 1 + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[3]!)}})] + public void Method1(ref RS s) => throw null!; + } +} +"""; + var comp = CreateCompilation([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors); + comp.VerifyEmitDiagnostics( + // (9,10): error CS9156: Cannot intercept call to 'C.M(scoped ref RS)' with 'C.Method1(ref RS)' because of a difference in 'scoped' modifiers or '[UnscopedRef]' attributes. + // [System.Runtime.CompilerServices.InterceptsLocation(1, "WYzfSbWruDNNkIt11JOTKC0AAAA=")] // 1 + Diagnostic(ErrorCode.ERR_InterceptorScopedMismatch, "System.Runtime.CompilerServices.InterceptsLocation").WithArguments("C.M(scoped ref RS)", "C.Method1(ref RS)").WithLocation(9, 10)); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_25() + { + // scoped difference in receiver + var source = """ +RS s = new RS(); +s.M(); +s.M(); + +public ref struct RS +{ + public void M() => throw null!; +} +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +static class Interceptors +{ + extension(ref RS s) + { + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public void Method0() { System.Console.Write("ran0 "); } + } + + extension(scoped ref RS s) + { + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[1]!)}})] + public void Method1() { System.Console.Write("ran1 "); } + } +} +"""; + CompileAndVerify([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors, expectedOutput: "ran0 ran1").VerifyDiagnostics(); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_26() + { + // original call uses classic extension invocations, interceptor is a new extension method, there is explicit ref argument + var source = """ +int i = 0; +new object().M(ref i); + +public static class Extensions +{ + public static void M(this object o, ref int i) => throw null; +} +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +static class Interceptors +{ + extension(object o) + { + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public void Method(ref int i) { System.Console.Write("ran"); } + } +} +"""; + CompileAndVerify([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors, expectedOutput: "ran").VerifyDiagnostics(); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_27() + { + // original call uses classic extension invocations, interceptor is a new extension method, there is an implicit ref on receiver and explicit ref argument + var source = """ +int i = 0; +int j = 42; +j.M(ref i); + +public static class Extensions +{ + public static void M(this ref int j, ref int i) => throw null; +} +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +static class Interceptors +{ + extension(ref int j) + { + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public void Method(ref int i) { System.Console.Write("ran"); } + } +} +"""; + CompileAndVerify([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors, expectedOutput: "ran").VerifyDiagnostics(); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_28() + { + // original call uses instance method, interceptor is a generic new extension method + var source = """ +new C().M(42); + +public class C +{ + public void M(U u) { } +} +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +static class Interceptors +{ + extension(C t) + { + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public void Method(U u) { System.Console.Write((typeof(T), typeof(U))); } + } +} +"""; + CompileAndVerify([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors, expectedOutput: "(System.Object, System.Int32)").VerifyDiagnostics(); + + var interceptors2 = """ +static class Interceptors +{ + extension(C t) + { + [System.Runtime.CompilerServices.InterceptsLocation("Program.cs", 1, 17)] + public void Method(U u) { System.Console.Write((typeof(T), typeof(U))); } + } +} +"""; + CompileAndVerify([(source, "Program.cs"), interceptors2, s_attributesSource], parseOptions: RegularPreviewWithInterceptors, expectedOutput: "(System.Object, System.Int32)").VerifyDiagnostics( + // (5,10): warning CS9270: 'InterceptsLocationAttribute(string, int, int)' is not supported. Move to 'InterceptableLocation'-based generation of these attributes instead. (https://github.com/dotnet/roslyn/issues/72133) + // [System.Runtime.CompilerServices.InterceptsLocation("Program.cs", 1, 17)] + Diagnostic(ErrorCode.WRN_InterceptsLocationAttributeUnsupportedSignature, @"System.Runtime.CompilerServices.InterceptsLocation(""Program.cs"", 1, 17)").WithLocation(5, 10)); + } + + [Fact, CompilerTrait(CompilerFeature.Extensions)] + public void Extensions_29() + { + // interceptor is a new extension method with no ExtensionParameter and no implementation method + var source = """ +new object().M(); + +public static class Extensions +{ + public static void M(this object o) => throw null; +} +"""; + var locations = GetInterceptableLocations(source); + var interceptors = $$""" +static class Interceptors +{ + extension(__arglist) + { + [System.Runtime.CompilerServices.InterceptsLocation({{GetAttributeArgs(locations[0]!)}})] + public void Method() { } + } +} +"""; + var comp = CreateCompilation([source, interceptors, s_attributesSource], parseOptions: RegularPreviewWithInterceptors); + comp.VerifyDiagnostics( + // (3,15): error CS1669: __arglist is not valid in this context + // extension(__arglist) + Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(3, 15)); + } +} + diff --git a/src/Compilers/CSharp/Test/Semantic/Semantics/LambdaTests.cs b/src/Compilers/CSharp/Test/Semantic/Semantics/LambdaTests.cs index 54d7002e47a40..0f114d167ec52 100644 --- a/src/Compilers/CSharp/Test/Semantic/Semantics/LambdaTests.cs +++ b/src/Compilers/CSharp/Test/Semantic/Semantics/LambdaTests.cs @@ -4147,7 +4147,7 @@ internal class DynamicSecurityMethodAttribute : Attribute { } }"; var comp = CreateCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( - // (8,22): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' + // (8,22): error CS0601: The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member // Action a1 = [DllImport("MyModule.dll")] static () => { }; Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(8, 22)); diff --git a/src/Compilers/CSharp/Test/Semantic/Semantics/LocalFunctionTests.cs b/src/Compilers/CSharp/Test/Semantic/Semantics/LocalFunctionTests.cs index 3f571adf122cc..7706b5b47a3a3 100644 --- a/src/Compilers/CSharp/Test/Semantic/Semantics/LocalFunctionTests.cs +++ b/src/Compilers/CSharp/Test/Semantic/Semantics/LocalFunctionTests.cs @@ -1117,19 +1117,19 @@ static void local5() { } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( - // (10,10): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' + // (10,10): error CS0601: The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member // [DllImport("a")] extern void local1(); // 1, 2 Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(10, 10), // (10,38): error CS8112: Local function 'local1()' must either have a body or be marked 'static extern'. // [DllImport("a")] extern void local1(); // 1, 2 Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local1").WithArguments("local1()").WithLocation(10, 38), - // (11,10): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' + // (11,10): error CS0601: The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member // [DllImport("a")] extern void local2() { } // 3, 4 Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(11, 10), // (11,38): error CS0179: 'local2()' cannot be extern and declare a body // [DllImport("a")] extern void local2() { } // 3, 4 Diagnostic(ErrorCode.ERR_ExternHasBody, "local2").WithArguments("local2()").WithLocation(11, 38), - // (12,10): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' + // (12,10): error CS0601: The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member // [DllImport("a")] extern int local3() => 0; // 5, 6 Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(12, 10), // (12,37): error CS0179: 'local3()' cannot be extern and declare a body diff --git a/src/Compilers/CSharp/Test/Semantic/Semantics/NullableReferenceTypesTests.cs b/src/Compilers/CSharp/Test/Semantic/Semantics/NullableReferenceTypesTests.cs index 723a89d5f9eac..84c46e42f8fd6 100644 --- a/src/Compilers/CSharp/Test/Semantic/Semantics/NullableReferenceTypesTests.cs +++ b/src/Compilers/CSharp/Test/Semantic/Semantics/NullableReferenceTypesTests.cs @@ -147218,11 +147218,24 @@ class Program } }"; var comp = CreateCompilation(source); - // https://github.com/dotnet/roslyn/issues/29605: Missing warnings. + // https://github.com/dotnet/roslyn/issues/29605: Some warnings might still be missing. comp.VerifyDiagnostics( // (20,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = null; // 1 - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(20, 15)); + Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(20, 15), + // (26,20): warning CS8620: Argument of type 'A' cannot be used for parameter 'y' of type 'A' in 'A A.operator &(A x, A y)' due to differences in the nullability of reference types. + // _ = (ax && ay); // 2 + Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "ay").WithArguments("A", "A", "y", "A A.operator &(A x, A y)").WithLocation(26, 20), + // (28,20): warning CS8620: Argument of type 'B' cannot be used for parameter 'y' of type 'A' in 'A A.operator |(A x, A y)' due to differences in the nullability of reference types. + // _ = (ax || by); // 3 + Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "by").WithArguments("B", "A", "y", "A A.operator |(A x, A y)").WithLocation(28, 20), + // (29,20): warning CS8620: Argument of type 'A' cannot be used for parameter 'y' of type 'A' in 'A A.operator &(A x, A y)' due to differences in the nullability of reference types. + // _ = (by && ax); // 4 + Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "ax").WithArguments("A", "A", "y", "A A.operator &(A x, A y)").WithLocation(29, 20), + // (31,20): warning CS8620: Argument of type 'B' cannot be used for parameter 'y' of type 'A' in 'A A.operator |(A x, A y)' due to differences in the nullability of reference types. + // _ = (by || bx); // 5 + Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "bx").WithArguments("B", "A", "y", "A A.operator |(A x, A y)").WithLocation(31, 20) + ); } [Fact] @@ -147261,11 +147274,24 @@ class Program } }"; var comp = CreateCompilation(source); - // https://github.com/dotnet/roslyn/issues/29605: Missing warnings. + // https://github.com/dotnet/roslyn/issues/29605: Some warnings might still be missing. comp.VerifyDiagnostics( // (17,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = null; // 1 - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(17, 15)); + Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(17, 15), + // (23,21): warning CS8620: Argument of type 'S' cannot be used for parameter 'y' of type 'S' in 'S S.operator &(S x, S y)' due to differences in the nullability of reference types. + // _ = (s1x && s1y); // 2 + Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s1y").WithArguments("S", "S", "y", "S S.operator &(S x, S y)").WithLocation(23, 21), + // (25,21): warning CS8620: Argument of type 'S' cannot be used for parameter 'y' of type 'S' in 'S S.operator |(S x, S y)' due to differences in the nullability of reference types. + // _ = (s1x || s2y); // 3 + Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s2y").WithArguments("S", "S", "y", "S S.operator |(S x, S y)").WithLocation(25, 21), + // (26,21): warning CS8620: Argument of type 'S' cannot be used for parameter 'y' of type 'S' in 'S S.operator &(S x, S y)' due to differences in the nullability of reference types. + // _ = (s2y && s1x); // 4 + Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s1x").WithArguments("S", "S", "y", "S S.operator &(S x, S y)").WithLocation(26, 21), + // (28,21): warning CS8620: Argument of type 'S' cannot be used for parameter 'y' of type 'S' in 'S S.operator |(S x, S y)' due to differences in the nullability of reference types. + // _ = (s2y || s2x); // 5 + Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s2x").WithArguments("S", "S", "y", "S S.operator |(S x, S y)").WithLocation(28, 21) + ); } [Fact] diff --git a/src/Compilers/CSharp/Test/Semantic/Semantics/OperatorTests.cs b/src/Compilers/CSharp/Test/Semantic/Semantics/OperatorTests.cs index 6fd4164bf4771..5caef4905938d 100644 --- a/src/Compilers/CSharp/Test/Semantic/Semantics/OperatorTests.cs +++ b/src/Compilers/CSharp/Test/Semantic/Semantics/OperatorTests.cs @@ -7383,7 +7383,8 @@ static BinaryOperatorKind getBinaryOperator(Binder binder, BinaryOperatorKind ki else { var discardedUseSiteInfo = CompoundUseSiteInfo.Discarded; - overloadResolution.BinaryOperatorOverloadResolution_NoEasyOut(kind, isChecked, left, right, result, ref discardedUseSiteInfo); + OverloadResolution.GetStaticUserDefinedBinaryOperatorMethodNames(kind, isChecked, out string name1, out string name2Opt); + overloadResolution.BinaryOperatorOverloadResolution_NoEasyOut(kind, isChecked, name1, name2Opt, left, right, result, ref discardedUseSiteInfo); } var signature = result.Best.Signature.Kind; result.Free(); diff --git a/src/Compilers/CSharp/Test/Semantic/Semantics/OverloadResolutionTests.cs b/src/Compilers/CSharp/Test/Semantic/Semantics/OverloadResolutionTests.cs index 2bb1c84896e73..2b6444eb74a8f 100644 --- a/src/Compilers/CSharp/Test/Semantic/Semantics/OverloadResolutionTests.cs +++ b/src/Compilers/CSharp/Test/Semantic/Semantics/OverloadResolutionTests.cs @@ -3055,7 +3055,7 @@ public static void Goo() } "; CreateCompilation(source).VerifyDiagnostics( - // (12,6): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' + // (12,6): error CS0601: The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member // [DllImport("goo")] Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport"), // (20,19): error CS1503: Argument 1: cannot convert from 'short' to 'sbyte' diff --git a/src/Compilers/CSharp/Test/Semantic/Semantics/RefEscapingTests.cs b/src/Compilers/CSharp/Test/Semantic/Semantics/RefEscapingTests.cs index 977c987f503b7..0b3a373b843a2 100644 --- a/src/Compilers/CSharp/Test/Semantic/Semantics/RefEscapingTests.cs +++ b/src/Compilers/CSharp/Test/Semantic/Semantics/RefEscapingTests.cs @@ -10657,6 +10657,130 @@ static R F() CreateCompilation(source, targetFramework: TargetFramework.Net70).VerifyDiagnostics(); } + [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/71773")] + [WorkItem("https://github.com/dotnet/roslyn/issues/78964")] + public void UserDefinedIncrementOperator_RefStruct_Scoped_Prefix([CombinatorialValues("++", "--")] string op) + { + // r1 = ++r2; + // is equivalent to + // var tmp = R.op_Increment(r2); + // r2 = tmp; + // r1 = tmp; + // which is ref safe + var source = $$""" + ref struct R + { + private ref readonly int _i; + public R(in int i) { _i = ref i; } + public static R operator {{op}}(scoped R r) => default; + } + class Program + { + static R F1(R r1, scoped R r2) + { + r1 = {{op}}r2; + return r1; + } + } + """; + CreateCompilation(source, targetFramework: TargetFramework.Net70).VerifyDiagnostics(); + } + + [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/71773")] + [WorkItem("https://github.com/dotnet/roslyn/issues/78964")] + public void UserDefinedIncrementOperator_RefStruct_Scoped_Prefix_Arg([CombinatorialValues("++", "--")] string op) + { + // F2(out var r1, ++r2); return r1; + // is equivalent to + // var tmp = R.op_Increment(r2); + // r2 = tmp; + // F2(out var r1, tmp); return r1; + // which is ref safe + var source = $$""" + ref struct R + { + private ref readonly int _i; + public R(in int i) { _i = ref i; } + public static R operator {{op}}(scoped R r) => default; + } + class Program + { + static R F1(scoped R r2) + { + F2(out var r1, {{op}}r2); + return r1; + } + static void F2(out R r1, R r2) => r1 = r2; + } + """; + CreateCompilation(source, targetFramework: TargetFramework.Net70).VerifyDiagnostics(); + } + + [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/71773")] + [WorkItem("https://github.com/dotnet/roslyn/issues/78964")] + public void UserDefinedIncrementOperator_RefStruct_Scoped_Postfix([CombinatorialValues("++", "--")] string op) + { + // r1 = r2++; + // is equivalent to + // var tmp = r2; + // r2 = R.op_Increment(r2); + // r1 = tmp; + // which is *not* ref safe (scoped r2 cannot be assigned to unscoped r1) + var source = $$""" + ref struct R + { + private ref readonly int _i; + public R(in int i) { _i = ref i; } + public static R operator {{op}}(scoped R r) => default; + } + class Program + { + static R F1(R r1, scoped R r2) + { + r1 = r2{{op}}; + return r1; + } + } + """; + CreateCompilation(source, targetFramework: TargetFramework.Net70).VerifyDiagnostics( + // (11,14): error CS8352: Cannot use variable 'scoped R r2' in this context because it may expose referenced variables outside of their declaration scope + // r1 = r2++; + Diagnostic(ErrorCode.ERR_EscapeVariable, $"r2{op}").WithArguments("scoped R r2").WithLocation(11, 14)); + } + + [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/71773")] + [WorkItem("https://github.com/dotnet/roslyn/issues/78964")] + public void UserDefinedIncrementOperator_RefStruct_Scoped_Postfix_Arg([CombinatorialValues("++", "--")] string op) + { + // F2(out var r1, r2++); return r1; + // is equivalent to + // var tmp = r2; + // r2 = R.op_Increment(r2); + // F2(out var r1, tmp); return r1; + // which is *not* ref safe (r1 is inferred as scoped from r2 but scoped r1 cannot be returned) + var source = $$""" + ref struct R + { + private ref readonly int _i; + public R(in int i) { _i = ref i; } + public static R operator {{op}}(scoped R r) => default; + } + class Program + { + static R F1(scoped R r2) + { + F2(out var r1, r2{{op}}); + return r1; + } + static void F2(out R r1, R r2) => r1 = r2; + } + """; + CreateCompilation(source, targetFramework: TargetFramework.Net70).VerifyDiagnostics( + // (12,16): error CS8352: Cannot use variable 'r1' in this context because it may expose referenced variables outside of their declaration scope + // return r1; + Diagnostic(ErrorCode.ERR_EscapeVariable, "r1").WithArguments("r1").WithLocation(12, 16)); + } + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71773")] public void UserDefinedLogicalOperator_RefStruct() { diff --git a/src/Compilers/CSharp/Test/Semantic/Semantics/SyntaxTreeRootTests.cs b/src/Compilers/CSharp/Test/Semantic/Semantics/SyntaxTreeRootTests.cs index a5bdfcbdb0f5a..43b0b048eb0f2 100644 --- a/src/Compilers/CSharp/Test/Semantic/Semantics/SyntaxTreeRootTests.cs +++ b/src/Compilers/CSharp/Test/Semantic/Semantics/SyntaxTreeRootTests.cs @@ -4,17 +4,12 @@ #nullable disable -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Text; using System; -using System.Collections.Generic; using System.Linq; using System.Reflection; -using System.Text; -using System.Threading.Tasks; -using Xunit; -using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; +using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.Semantics { @@ -32,7 +27,7 @@ public void SyntaxTreeCreateAcceptsAnySyntaxNode() public void SyntaxTreeCreateWithoutCloneAcceptsAnySyntaxNode() { var node = SyntaxFactory.CatchClause(SyntaxFactory.CatchDeclaration(SyntaxFactory.ParseTypeName(typeof(InvalidOperationException).Name)), null, SyntaxFactory.Block()); - var tree = CSharpSyntaxTree.CreateWithoutClone(node); + var tree = CSharpSyntaxTree.CreateWithoutClone(node, CSharpParseOptions.Default); CheckTree(tree); } diff --git a/src/Compilers/CSharp/Test/Semantic/Semantics/TopLevelStatementsTests.cs b/src/Compilers/CSharp/Test/Semantic/Semantics/TopLevelStatementsTests.cs index 5fe12a777c6e4..b3ed1972ca893 100644 --- a/src/Compilers/CSharp/Test/Semantic/Semantics/TopLevelStatementsTests.cs +++ b/src/Compilers/CSharp/Test/Semantic/Semantics/TopLevelStatementsTests.cs @@ -10,6 +10,7 @@ using System.Runtime.InteropServices; using System.Text; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; diff --git a/src/Compilers/CSharp/Test/Semantic/SourceGeneration/StateTableTests.cs b/src/Compilers/CSharp/Test/Semantic/SourceGeneration/StateTableTests.cs index e075bce56677d..ac470c7f78a24 100644 --- a/src/Compilers/CSharp/Test/Semantic/SourceGeneration/StateTableTests.cs +++ b/src/Compilers/CSharp/Test/Semantic/SourceGeneration/StateTableTests.cs @@ -7,6 +7,7 @@ using System.Collections.Immutable; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; diff --git a/src/Compilers/CSharp/Test/Symbol/Compilation/CompilationAPITests.cs b/src/Compilers/CSharp/Test/Symbol/Compilation/CompilationAPITests.cs index 3fd08e070b8d2..f038790ec3bf1 100644 --- a/src/Compilers/CSharp/Test/Symbol/Compilation/CompilationAPITests.cs +++ b/src/Compilers/CSharp/Test/Symbol/Compilation/CompilationAPITests.cs @@ -27,7 +27,6 @@ using Roslyn.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestHelpers; -using KeyValuePairUtil = Roslyn.Utilities.KeyValuePairUtil; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.CSharp.UnitTests @@ -3357,7 +3356,7 @@ public void ReturnInNestedAnonymousMethod() public void LoadedFileWithWrongReturnType() { var resolver = TestSourceReferenceResolver.Create( - KeyValuePairUtil.Create("a.csx", "return \"Who returns a string?\";")); + KeyValuePair.Create("a.csx", "return \"Who returns a string?\";")); var script = CreateSubmission(@" #load ""a.csx"" 42", returnType: typeof(int), options: TestOptions.DebugDll.WithSourceReferenceResolver(resolver)); diff --git a/src/Compilers/CSharp/Test/Symbol/Compilation/LoadDirectiveTests.cs b/src/Compilers/CSharp/Test/Symbol/Compilation/LoadDirectiveTests.cs index ad8449221c71f..4099ff6d77b6a 100644 --- a/src/Compilers/CSharp/Test/Symbol/Compilation/LoadDirectiveTests.cs +++ b/src/Compilers/CSharp/Test/Symbol/Compilation/LoadDirectiveTests.cs @@ -4,6 +4,7 @@ #nullable disable +using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; @@ -47,7 +48,7 @@ public void FileWithErrors() { var code = "#load \"a.csx\""; var resolver = TestSourceReferenceResolver.Create( - KeyValuePairUtil.Create("a.csx", @" + KeyValuePair.Create("a.csx", @" #load ""b.csx"" asdf();")); var options = TestOptions.DebugDll.WithSourceReferenceResolver(resolver); @@ -73,8 +74,8 @@ public void FileThatCannotBeDecoded() { var code = "#load \"b.csx\""; var resolver = TestSourceReferenceResolver.Create( - KeyValuePairUtil.Create("a.csx", new byte[] { 0xd8, 0x00, 0x00, 0x00 }), - KeyValuePairUtil.Create("b.csx", "#load \"a.csx\"")); + KeyValuePair.Create("a.csx", new byte[] { 0xd8, 0x00, 0x00, 0x00 }), + KeyValuePair.Create("b.csx", "#load \"a.csx\"")); var options = TestOptions.DebugDll.WithSourceReferenceResolver(resolver); var compilation = CreateCompilationWithMscorlib461(code, sourceFileName: "external1.csx", options: options, parseOptions: TestOptions.Script); var external1 = compilation.SyntaxTrees.Last(); @@ -152,7 +153,7 @@ public void ErrorInInactiveRegion() public void Cycles() { var code = "#load \"a.csx\""; - var resolver = TestSourceReferenceResolver.Create(KeyValuePairUtil.Create("a.csx", code)); + var resolver = TestSourceReferenceResolver.Create(KeyValuePair.Create("a.csx", code)); var options = TestOptions.DebugDll.WithSourceReferenceResolver(resolver); var compilation = CreateCompilationWithMscorlib461(code, options: options, parseOptions: TestOptions.Script); @@ -171,8 +172,8 @@ public void Cycles() compilation.VerifyDiagnostics(); resolver = TestSourceReferenceResolver.Create( - KeyValuePairUtil.Create("a.csx", "#load \"b.csx\""), - KeyValuePairUtil.Create("b.csx", code)); + KeyValuePair.Create("a.csx", "#load \"b.csx\""), + KeyValuePair.Create("b.csx", code)); options = TestOptions.DebugDll.WithSourceReferenceResolver(resolver); compilation = CreateCompilationWithMscorlib461(code, options: options, parseOptions: TestOptions.Script); diff --git a/src/Compilers/CSharp/Test/Symbol/Compilation/SemanticModelGetSemanticInfoTests.cs b/src/Compilers/CSharp/Test/Symbol/Compilation/SemanticModelGetSemanticInfoTests.cs index e23a2130fd8f5..ffd9ddaf95b3d 100644 --- a/src/Compilers/CSharp/Test/Symbol/Compilation/SemanticModelGetSemanticInfoTests.cs +++ b/src/Compilers/CSharp/Test/Symbol/Compilation/SemanticModelGetSemanticInfoTests.cs @@ -274,7 +274,7 @@ class K Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : see if we can restore a behavior closer to previous (ie. returning the field as candidate symbol) + // Tracked by https://github.com/dotnet/roslyn/issues/78957 : public API, see if we can restore a behavior closer to previous (ie. returning the field as candidate symbol) Assert.Empty(semanticInfo.CandidateSymbols); Assert.Equal(0, semanticInfo.MethodGroup.Length); diff --git a/src/Compilers/CSharp/Test/Symbol/Symbols/ConversionTests.cs b/src/Compilers/CSharp/Test/Symbol/Symbols/ConversionTests.cs index 9d38781e3e73e..4273699b68d71 100644 --- a/src/Compilers/CSharp/Test/Symbol/Symbols/ConversionTests.cs +++ b/src/Compilers/CSharp/Test/Symbol/Symbols/ConversionTests.cs @@ -7,13 +7,14 @@ using System; using System.Collections.Generic; using System.Linq; +using Basic.Reference.Assemblies; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; +using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; -using Basic.Reference.Assemblies; -using Microsoft.CodeAnalysis.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { diff --git a/src/Compilers/CSharp/Test/Symbol/Symbols/GenericConstraintTests.cs b/src/Compilers/CSharp/Test/Symbol/Symbols/GenericConstraintTests.cs index 6aa2da403f3bc..d7dbe221a7a5d 100644 --- a/src/Compilers/CSharp/Test/Symbol/Symbols/GenericConstraintTests.cs +++ b/src/Compilers/CSharp/Test/Symbol/Symbols/GenericConstraintTests.cs @@ -4546,150 +4546,180 @@ static void Main() compilation.VerifyIL("B.M1(T)", @" { - // Code size 216 (0xd8) + // Code size 274 (0x112) .maxstack 4 - .locals init (int V_0, - T& V_1, - T V_2) + .locals init (T V_0, + T& V_1, + int V_2, + T V_3) IL_0000: ldarga.s V_0 - IL_0002: dup - IL_0003: constrained. ""T"" - IL_0009: callvirt ""int I.P.get"" - IL_000e: stloc.0 - IL_000f: ldloc.0 - IL_0010: ldc.i4.1 - IL_0011: add - IL_0012: constrained. ""T"" - IL_0018: callvirt ""void I.P.set"" - IL_001d: ldarga.s V_0 + IL_0002: stloc.1 + IL_0003: ldloca.s V_3 + IL_0005: initobj ""T"" + IL_000b: ldloc.3 + IL_000c: box ""T"" + IL_0011: brtrue.s IL_001e + IL_0013: ldloc.1 + IL_0014: ldobj ""T"" + IL_0019: stloc.0 + IL_001a: ldloca.s V_0 + IL_001c: br.s IL_001f + IL_001e: ldloc.1 IL_001f: dup - IL_0020: ldc.i4.0 - IL_0021: constrained. ""T"" - IL_0027: callvirt ""int I.this[int].get"" - IL_002c: stloc.0 - IL_002d: ldc.i4.0 - IL_002e: ldloc.0 - IL_002f: ldc.i4.1 - IL_0030: add - IL_0031: constrained. ""T"" - IL_0037: callvirt ""void I.this[int].set"" - IL_003c: ldarga.s V_0 - IL_003e: stloc.1 - IL_003f: ldloc.1 - IL_0040: ldloca.s V_2 - IL_0042: initobj ""T"" - IL_0048: ldloc.2 - IL_0049: box ""T"" - IL_004e: brtrue.s IL_0058 - IL_0050: ldobj ""T"" - IL_0055: stloc.2 - IL_0056: ldloca.s V_2 + IL_0020: constrained. ""T"" + IL_0026: callvirt ""int I.P.get"" + IL_002b: stloc.2 + IL_002c: ldloc.2 + IL_002d: ldc.i4.1 + IL_002e: add + IL_002f: constrained. ""T"" + IL_0035: callvirt ""void I.P.set"" + IL_003a: ldarga.s V_0 + IL_003c: stloc.1 + IL_003d: ldloca.s V_3 + IL_003f: initobj ""T"" + IL_0045: ldloc.3 + IL_0046: box ""T"" + IL_004b: brtrue.s IL_0058 + IL_004d: ldloc.1 + IL_004e: ldobj ""T"" + IL_0053: stloc.0 + IL_0054: ldloca.s V_0 + IL_0056: br.s IL_0059 IL_0058: ldloc.1 - IL_0059: constrained. ""T"" - IL_005f: callvirt ""int I.P.get"" - IL_0064: ldc.i4.2 - IL_0065: add - IL_0066: constrained. ""T"" - IL_006c: callvirt ""void I.P.set"" - IL_0071: ldarga.s V_0 - IL_0073: stloc.1 - IL_0074: ldloc.1 - IL_0075: ldloca.s V_2 - IL_0077: initobj ""T"" - IL_007d: ldloc.2 - IL_007e: box ""T"" - IL_0083: brtrue.s IL_008d - IL_0085: ldobj ""T"" - IL_008a: stloc.2 - IL_008b: ldloca.s V_2 - IL_008d: ldc.i4.0 - IL_008e: ldloc.1 - IL_008f: ldc.i4.0 - IL_0090: constrained. ""T"" - IL_0096: callvirt ""int I.this[int].get"" - IL_009b: ldc.i4.2 - IL_009c: add - IL_009d: constrained. ""T"" - IL_00a3: callvirt ""void I.this[int].set"" - IL_00a8: ldstr ""{0}, {1}"" - IL_00ad: ldarga.s V_0 - IL_00af: constrained. ""T"" - IL_00b5: callvirt ""int I.P.get"" - IL_00ba: box ""int"" - IL_00bf: ldarga.s V_0 - IL_00c1: ldc.i4.0 - IL_00c2: constrained. ""T"" - IL_00c8: callvirt ""int I.this[int].get"" - IL_00cd: box ""int"" - IL_00d2: call ""void System.Console.WriteLine(string, object, object)"" - IL_00d7: ret + IL_0059: dup + IL_005a: ldc.i4.0 + IL_005b: constrained. ""T"" + IL_0061: callvirt ""int I.this[int].get"" + IL_0066: stloc.2 + IL_0067: ldc.i4.0 + IL_0068: ldloc.2 + IL_0069: ldc.i4.1 + IL_006a: add + IL_006b: constrained. ""T"" + IL_0071: callvirt ""void I.this[int].set"" + IL_0076: ldarga.s V_0 + IL_0078: stloc.1 + IL_0079: ldloc.1 + IL_007a: ldloca.s V_0 + IL_007c: initobj ""T"" + IL_0082: ldloc.0 + IL_0083: box ""T"" + IL_0088: brtrue.s IL_0092 + IL_008a: ldobj ""T"" + IL_008f: stloc.0 + IL_0090: ldloca.s V_0 + IL_0092: ldloc.1 + IL_0093: constrained. ""T"" + IL_0099: callvirt ""int I.P.get"" + IL_009e: ldc.i4.2 + IL_009f: add + IL_00a0: constrained. ""T"" + IL_00a6: callvirt ""void I.P.set"" + IL_00ab: ldarga.s V_0 + IL_00ad: stloc.1 + IL_00ae: ldloc.1 + IL_00af: ldloca.s V_0 + IL_00b1: initobj ""T"" + IL_00b7: ldloc.0 + IL_00b8: box ""T"" + IL_00bd: brtrue.s IL_00c7 + IL_00bf: ldobj ""T"" + IL_00c4: stloc.0 + IL_00c5: ldloca.s V_0 + IL_00c7: ldc.i4.0 + IL_00c8: ldloc.1 + IL_00c9: ldc.i4.0 + IL_00ca: constrained. ""T"" + IL_00d0: callvirt ""int I.this[int].get"" + IL_00d5: ldc.i4.2 + IL_00d6: add + IL_00d7: constrained. ""T"" + IL_00dd: callvirt ""void I.this[int].set"" + IL_00e2: ldstr ""{0}, {1}"" + IL_00e7: ldarga.s V_0 + IL_00e9: constrained. ""T"" + IL_00ef: callvirt ""int I.P.get"" + IL_00f4: box ""int"" + IL_00f9: ldarga.s V_0 + IL_00fb: ldc.i4.0 + IL_00fc: constrained. ""T"" + IL_0102: callvirt ""int I.this[int].get"" + IL_0107: box ""int"" + IL_010c: call ""void System.Console.WriteLine(string, object, object)"" + IL_0111: ret } "); compilation.VerifyIL("B.M2(T)", @" { - // Code size 172 (0xac) + // Code size 176 (0xb0) .maxstack 4 - .locals init (int V_0, - T& V_1) - IL_0000: ldarga.s V_0 - IL_0002: dup - IL_0003: constrained. ""T"" - IL_0009: callvirt ""int I.P.get"" - IL_000e: stloc.0 - IL_000f: ldloc.0 - IL_0010: ldc.i4.1 - IL_0011: add - IL_0012: constrained. ""T"" - IL_0018: callvirt ""void I.P.set"" - IL_001d: ldarga.s V_0 - IL_001f: dup - IL_0020: ldc.i4.0 - IL_0021: constrained. ""T"" - IL_0027: callvirt ""int I.this[int].get"" - IL_002c: stloc.0 - IL_002d: ldc.i4.0 - IL_002e: ldloc.0 - IL_002f: ldc.i4.1 - IL_0030: add - IL_0031: constrained. ""T"" - IL_0037: callvirt ""void I.this[int].set"" - IL_003c: ldarga.s V_0 - IL_003e: stloc.1 - IL_003f: ldloc.1 - IL_0040: ldobj ""T"" - IL_0045: box ""T"" - IL_004a: ldloc.1 - IL_004b: constrained. ""T"" - IL_0051: callvirt ""int I.P.get"" - IL_0056: ldc.i4.2 - IL_0057: add - IL_0058: callvirt ""void I.P.set"" - IL_005d: ldarga.s V_0 - IL_005f: stloc.1 - IL_0060: ldloc.1 - IL_0061: ldobj ""T"" - IL_0066: box ""T"" - IL_006b: ldc.i4.0 - IL_006c: ldloc.1 - IL_006d: ldc.i4.0 - IL_006e: constrained. ""T"" - IL_0074: callvirt ""int I.this[int].get"" - IL_0079: ldc.i4.2 - IL_007a: add - IL_007b: callvirt ""void I.this[int].set"" - IL_0080: ldstr ""{0}, {1}"" - IL_0085: ldarg.0 - IL_0086: box ""T"" - IL_008b: callvirt ""int I.P.get"" - IL_0090: box ""int"" - IL_0095: ldarg.0 - IL_0096: box ""T"" - IL_009b: ldc.i4.0 - IL_009c: callvirt ""int I.this[int].get"" - IL_00a1: box ""int"" - IL_00a6: call ""void System.Console.WriteLine(string, object, object)"" - IL_00ab: ret + .locals init (T V_0, + int V_1, + T& V_2) + IL_0000: ldarg.0 + IL_0001: stloc.0 + IL_0002: ldloca.s V_0 + IL_0004: dup + IL_0005: constrained. ""T"" + IL_000b: callvirt ""int I.P.get"" + IL_0010: stloc.1 + IL_0011: ldloc.1 + IL_0012: ldc.i4.1 + IL_0013: add + IL_0014: constrained. ""T"" + IL_001a: callvirt ""void I.P.set"" + IL_001f: ldarg.0 + IL_0020: stloc.0 + IL_0021: ldloca.s V_0 + IL_0023: dup + IL_0024: ldc.i4.0 + IL_0025: constrained. ""T"" + IL_002b: callvirt ""int I.this[int].get"" + IL_0030: stloc.1 + IL_0031: ldc.i4.0 + IL_0032: ldloc.1 + IL_0033: ldc.i4.1 + IL_0034: add + IL_0035: constrained. ""T"" + IL_003b: callvirt ""void I.this[int].set"" + IL_0040: ldarga.s V_0 + IL_0042: stloc.2 + IL_0043: ldloc.2 + IL_0044: ldobj ""T"" + IL_0049: box ""T"" + IL_004e: ldloc.2 + IL_004f: constrained. ""T"" + IL_0055: callvirt ""int I.P.get"" + IL_005a: ldc.i4.2 + IL_005b: add + IL_005c: callvirt ""void I.P.set"" + IL_0061: ldarga.s V_0 + IL_0063: stloc.2 + IL_0064: ldloc.2 + IL_0065: ldobj ""T"" + IL_006a: box ""T"" + IL_006f: ldc.i4.0 + IL_0070: ldloc.2 + IL_0071: ldc.i4.0 + IL_0072: constrained. ""T"" + IL_0078: callvirt ""int I.this[int].get"" + IL_007d: ldc.i4.2 + IL_007e: add + IL_007f: callvirt ""void I.this[int].set"" + IL_0084: ldstr ""{0}, {1}"" + IL_0089: ldarg.0 + IL_008a: box ""T"" + IL_008f: callvirt ""int I.P.get"" + IL_0094: box ""int"" + IL_0099: ldarg.0 + IL_009a: box ""T"" + IL_009f: ldc.i4.0 + IL_00a0: callvirt ""int I.this[int].get"" + IL_00a5: box ""int"" + IL_00aa: call ""void System.Console.WriteLine(string, object, object)"" + IL_00af: ret } "); compilation.VerifyIL("B.M3(T)", diff --git a/src/Compilers/CSharp/Test/Symbol/Symbols/SymbolErrorTests.cs b/src/Compilers/CSharp/Test/Symbol/Symbols/SymbolErrorTests.cs index 2d14058a57436..7397b4e3730e4 100644 --- a/src/Compilers/CSharp/Test/Symbol/Symbols/SymbolErrorTests.cs +++ b/src/Compilers/CSharp/Test/Symbol/Symbols/SymbolErrorTests.cs @@ -8702,6 +8702,59 @@ static int Main() Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test").WithArguments("object", "0")); } + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/79195")] + public void CS0518ERR_PredefinedTypeAmbiguous() + { + string code = """ + var range = 1..2; + """; + + CreateCompilation(code, targetFramework: TargetFramework.NetStandard20).VerifyDiagnostics( + // (1,13): error CS0518: Predefined type 'System.Range' is not defined or imported + // var range = 1..2; + Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "1..2").WithArguments("System.Range").WithLocation(1, 13), + // (1,13): error CS0518: Predefined type 'System.Index' is not defined or imported + // var range = 1..2; + Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "1").WithArguments("System.Index").WithLocation(1, 13), + // (1,16): error CS0518: Predefined type 'System.Index' is not defined or imported + // var range = 1..2; + Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "2").WithArguments("System.Index").WithLocation(1, 16)); + + CreateCompilation(code, [createReference("Ref0")], targetFramework: TargetFramework.NetStandard20).VerifyDiagnostics(); + + CreateCompilation(code, [createReference("Ref1"), createReference("Ref2")], targetFramework: TargetFramework.NetStandard20).VerifyDiagnostics( + // (1,13): error CS8356: Predefined type 'System.Range' is declared in multiple referenced assemblies: 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' + // var range = 1..2; + Diagnostic(ErrorCode.ERR_PredefinedTypeAmbiguous, "1..2").WithArguments("System.Range", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 13), + // (1,13): error CS8356: Predefined type 'System.Index' is declared in multiple referenced assemblies: 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' + // var range = 1..2; + Diagnostic(ErrorCode.ERR_PredefinedTypeAmbiguous, "1").WithArguments("System.Index", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 13), + // (1,16): error CS8356: Predefined type 'System.Index' is declared in multiple referenced assemblies: 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' + // var range = 1..2; + Diagnostic(ErrorCode.ERR_PredefinedTypeAmbiguous, "2").WithArguments("System.Index", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 16)); + + static MetadataReference createReference(string name) + { + string code = """ + namespace System; + public struct Index + { + public int GetOffset(int length) => 0; + public static implicit operator Index(int value) => default; + } + public struct Range + { + public Range(Index start, Index end) { } + public Index Start => default; + public Index End => default; + } + """; + return CreateCompilation(code, assemblyName: name) + .VerifyDiagnostics() + .EmitToPortableExecutableReference(); + } + } + //[Fact(Skip = "Bad test case")] //public void CS0520ERR_PredefinedTypeBadType() //{ @@ -11298,9 +11351,9 @@ static void Bar() { } // CS0601 } "; CreateCompilation(text, options: TestOptions.ReleaseDll).VerifyDiagnostics( - // (6,6): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' + // (6,6): error CS0601: The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport"), - // (9,6): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' + // (9,6): error CS0601: The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport")); } @@ -14052,7 +14105,7 @@ public static int Main() // (27,34): error CS0507: 'C.PartI()': cannot change access modifiers when overriding 'protected' inherited member 'Base.PartI()' // sealed override partial void PartI(); Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "PartI").WithArguments("C.PartI()", "protected", "Base.PartI()").WithLocation(27, 34), - // (28,6): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' + // (28,6): error CS0601: The DllImport attribute must be specified on a method marked 'extern' that is either 'static' or an extension member // [System.Runtime.InteropServices.DllImport("none")] Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "System.Runtime.InteropServices.DllImport").WithLocation(28, 6)); } diff --git a/src/Compilers/CSharp/Test/Syntax/Parsing/ExtensionsParsingTests.cs b/src/Compilers/CSharp/Test/Syntax/Parsing/ExtensionsParsingTests.cs index 8d7bf2990fe4a..040c6da63ec5a 100644 --- a/src/Compilers/CSharp/Test/Syntax/Parsing/ExtensionsParsingTests.cs +++ b/src/Compilers/CSharp/Test/Syntax/Parsing/ExtensionsParsingTests.cs @@ -19,7 +19,7 @@ public ExtensionsParsingTests(ITestOutputHelper output) : base(output) { } [Fact] public void LangVer13() { - // Tracked by https://github.com/dotnet/roslyn/issues/76130 : consider giving a LangVer error to trigger UpgradeProject + // Tracked by https://github.com/dotnet/roslyn/issues/78961 : consider giving a LangVer error to trigger UpgradeProject UsingTree(""" class C { @@ -3019,14 +3019,6 @@ static class C } } """; - var comp = CreateCompilation(src); - comp.VerifyEmitDiagnostics( - // (5,39): error CS0563: One of the parameters of a binary operator must be the containing type - // public static object operator +(object a, object b) => a; - Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "+").WithLocation(5, 39), - // (5,39): error CS9282: This member is not allowed in an extension block - // public static object operator +(object a, object b) => a; - Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "+").WithLocation(5, 39)); UsingTree(src, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); @@ -3118,9 +3110,6 @@ static class C """; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( - // (5,41): error CS0556: User-defined conversion must convert to or from the enclosing type - // public static implicit operator int(object t) => 0; - Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(5, 41), // (5,41): error CS9282: This member is not allowed in an extension block // public static implicit operator int(object t) => 0; Diagnostic(ErrorCode.ERR_ExtensionDisallowsMember, "int").WithLocation(5, 41)); diff --git a/src/Compilers/CSharp/Test/Syntax/Syntax/SyntaxFactoryTests.cs b/src/Compilers/CSharp/Test/Syntax/Syntax/SyntaxFactoryTests.cs index 49178bb9c5a9e..bc2e73ce0a952 100644 --- a/src/Compilers/CSharp/Test/Syntax/Syntax/SyntaxFactoryTests.cs +++ b/src/Compilers/CSharp/Test/Syntax/Syntax/SyntaxFactoryTests.cs @@ -9,11 +9,11 @@ using System.Linq; using System.Text; using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; -using Microsoft.CodeAnalysis.CSharp.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { @@ -678,5 +678,41 @@ public void TestParseNameWithOptions() // unsafe class C { delegate* x; } Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("C.x").WithLocation(1, 34)); } + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78510")] + public void TestParseMethodsKeepParseOptionsInTheTree() + { + var parseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Latest); + + var argList = SyntaxFactory.ParseArgumentList("", options: parseOptions); + Assert.Same(parseOptions, argList.SyntaxTree.Options); + + var attrArgList = SyntaxFactory.ParseAttributeArgumentList("", options: parseOptions); + Assert.Same(parseOptions, attrArgList.SyntaxTree.Options); + + var bracketedArgList = SyntaxFactory.ParseBracketedArgumentList("", options: parseOptions); + Assert.Same(parseOptions, bracketedArgList.SyntaxTree.Options); + + var bracketedParamList = SyntaxFactory.ParseBracketedParameterList("", options: parseOptions); + Assert.Same(parseOptions, bracketedParamList.SyntaxTree.Options); + + var compUnit = SyntaxFactory.ParseCompilationUnit("", options: parseOptions); + Assert.Same(parseOptions, compUnit.SyntaxTree.Options); + + var expr = SyntaxFactory.ParseExpression("", options: parseOptions); + Assert.Same(parseOptions, expr.SyntaxTree.Options); + + var memberDecl = SyntaxFactory.ParseMemberDeclaration("public", options: parseOptions); + Assert.Same(parseOptions, memberDecl.SyntaxTree.Options); + + var paramList = SyntaxFactory.ParseParameterList("", options: parseOptions); + Assert.Same(parseOptions, paramList.SyntaxTree.Options); + + var statement = SyntaxFactory.ParseStatement("", options: parseOptions); + Assert.Same(parseOptions, statement.SyntaxTree.Options); + + var typeName = SyntaxFactory.ParseTypeName("", options: parseOptions); + Assert.Same(parseOptions, typeName.SyntaxTree.Options); + } } } diff --git a/src/Compilers/CSharp/Test/Syntax/Syntax/SyntaxTreeTests.cs b/src/Compilers/CSharp/Test/Syntax/Syntax/SyntaxTreeTests.cs index 46468791e38cc..24a6140e20ad8 100644 --- a/src/Compilers/CSharp/Test/Syntax/Syntax/SyntaxTreeTests.cs +++ b/src/Compilers/CSharp/Test/Syntax/Syntax/SyntaxTreeTests.cs @@ -5,6 +5,7 @@ #nullable disable using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; @@ -18,7 +19,6 @@ using Xunit; using Xunit.Abstractions; using static Roslyn.Test.Utilities.TestHelpers; -using KeyValuePair = Roslyn.Utilities.KeyValuePairUtil; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { diff --git a/src/Compilers/CSharp/csc/CscCommandLine.projitems b/src/Compilers/CSharp/csc/CscCommandLine.projitems index 3aef01cf38e3c..90bc1372064fd 100644 --- a/src/Compilers/CSharp/csc/CscCommandLine.projitems +++ b/src/Compilers/CSharp/csc/CscCommandLine.projitems @@ -18,16 +18,16 @@ CommandLine - - - - - - + - + + + + + + diff --git a/src/Compilers/Core/CodeAnalysisTest/AnalyzerAssemblyLoaderTests.cs b/src/Compilers/Core/CodeAnalysisTest/AnalyzerAssemblyLoaderTests.cs index a21427abe5c62..201ce70c0cc7e 100644 --- a/src/Compilers/Core/CodeAnalysisTest/AnalyzerAssemblyLoaderTests.cs +++ b/src/Compilers/Core/CodeAnalysisTest/AnalyzerAssemblyLoaderTests.cs @@ -1160,7 +1160,7 @@ public void AssemblyLoading_MultipleVersions_MissingVersion(AnalyzerTestKind kin /// Test the case where a utility is loaded by multiple analyzers at different versions. Ensure that no matter /// what order we load the analyzers we correctly resolve the utility version. /// - [Theory] + [ConditionalTheory(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/79352")] [CombinatorialData] public void AssemblyLoading_MultipleVersions_AnalyzerDependency(AnalyzerTestKind kind, bool normalOrder) { diff --git a/src/Compilers/Core/CodeAnalysisTest/Analyzers/AnalyzerConfigTests.cs b/src/Compilers/Core/CodeAnalysisTest/Analyzers/AnalyzerConfigTests.cs index 862e18b9ff69f..6b2824c26cb15 100644 --- a/src/Compilers/Core/CodeAnalysisTest/Analyzers/AnalyzerConfigTests.cs +++ b/src/Compilers/Core/CodeAnalysisTest/Analyzers/AnalyzerConfigTests.cs @@ -14,7 +14,6 @@ using Xunit; using static Microsoft.CodeAnalysis.AnalyzerConfig; using static Roslyn.Test.Utilities.TestHelpers; -using KeyValuePair = Roslyn.Utilities.KeyValuePairUtil; namespace Microsoft.CodeAnalysis.UnitTests { @@ -1229,7 +1228,7 @@ private AnalyzerConfigOptionsResult[] GetAnalyzerConfigOptions(string[] filePath } private static void VerifyAnalyzerOptions( - (string key, string val)[][] expected, + (string key, string value)[][] expected, AnalyzerConfigOptionsResult[] options) { Assert.Equal(expected.Length, options.Length); @@ -1243,7 +1242,7 @@ private static void VerifyAnalyzerOptions( else { AssertEx.SetEqual( - expected[i].Select(KeyValuePair.ToKeyValuePair), + expected[i].Select(t => KeyValuePair.Create(t.key, t.value)), options[i].AnalyzerOptions); } } diff --git a/src/Compilers/Core/CodeAnalysisTest/Collections/EnumerableExtensionsTests.cs b/src/Compilers/Core/CodeAnalysisTest/Collections/EnumerableExtensionsTests.cs deleted file mode 100644 index 34b62435ccfde..0000000000000 --- a/src/Compilers/Core/CodeAnalysisTest/Collections/EnumerableExtensionsTests.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Linq; -using Microsoft.CodeAnalysis.Collections; -using Roslyn.Utilities; -using Xunit; - -namespace Microsoft.CodeAnalysis.UnitTests.Collections -{ - public class EnumerableExtensionsTests - { - [Fact] - public void AsSingleton() - { - Assert.Equal(0, new int[] { }.AsSingleton()); - Assert.Equal(1, new int[] { 1 }.AsSingleton()); - Assert.Equal(0, new int[] { 1, 2 }.AsSingleton()); - - Assert.Equal(0, Enumerable.Range(1, 0).AsSingleton()); - Assert.Equal(1, Enumerable.Range(1, 1).AsSingleton()); - Assert.Equal(0, Enumerable.Range(1, 2).AsSingleton()); - } - - private class ReadOnlyList : IReadOnlyList - { - private readonly T[] _items; - - public ReadOnlyList(params T[] items) - { - _items = items; - } - - public T this[int index] => _items[index]; - public int Count => _items.Length; - public IEnumerator GetEnumerator() => throw new NotImplementedException(); - IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); - } - - private class SignlessEqualityComparer : IEqualityComparer - { - public bool Equals(int x, int y) => Math.Abs(x) == Math.Abs(y); - public int GetHashCode(int obj) => throw new NotImplementedException(); - } - - [Fact] - public void IndexOf() - { - Assert.Equal(-1, Enumerable.Range(1, 5).IndexOf(6)); - Assert.Equal(2, Enumerable.Range(1, 5).IndexOf(3)); - - Assert.Equal(-1, ((IEnumerable)SpecializedCollections.SingletonList(5)).IndexOf(6)); - Assert.Equal(0, ((IEnumerable)SpecializedCollections.SingletonList(5)).IndexOf(5)); - - Assert.Equal(-1, ((IEnumerable)new ReadOnlyList(5)).IndexOf(6)); - Assert.Equal(0, ((IEnumerable)new ReadOnlyList(5)).IndexOf(5)); - } - - [Fact] - public void IndexOf_EqualityComparer() - { - var comparer = new SignlessEqualityComparer(); - - Assert.Equal(-1, Enumerable.Range(1, 5).IndexOf(-6, comparer)); - Assert.Equal(2, Enumerable.Range(1, 5).IndexOf(-3, comparer)); - - Assert.Equal(-1, ((IEnumerable)SpecializedCollections.SingletonList(5)).IndexOf(-6, comparer)); - Assert.Equal(0, ((IEnumerable)SpecializedCollections.SingletonList(5)).IndexOf(-5, comparer)); - - Assert.Equal(-1, ((IEnumerable)new ReadOnlyList(5)).IndexOf(-6, comparer)); - Assert.Equal(0, ((IEnumerable)new ReadOnlyList(5)).IndexOf(-5, comparer)); - } - } -} diff --git a/src/Compilers/Core/CodeAnalysisTest/Collections/Extensions/EnumerableExtensionsTests.cs b/src/Compilers/Core/CodeAnalysisTest/Collections/Extensions/EnumerableExtensionsTests.cs index bb924f0d228e8..03123605671b2 100644 --- a/src/Compilers/Core/CodeAnalysisTest/Collections/Extensions/EnumerableExtensionsTests.cs +++ b/src/Compilers/Core/CodeAnalysisTest/Collections/Extensions/EnumerableExtensionsTests.cs @@ -4,29 +4,201 @@ #nullable disable +using System; +using System.Collections; using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis.Collections; +using Roslyn.Utilities; using Xunit; -namespace Roslyn.Utilities.UnitTests.InternalUtilities +namespace Microsoft.CodeAnalysis.UnitTests; + +public class EnumerableExtensionsTests { - using System.Linq; + private static IEnumerable MakeEnumerable(params T[] values) + { + foreach (var value in values) + { + yield return value; + } + } + + [Fact] + public void SequenceEqual() + { + bool comparer(int x, int y) => x == y; + Assert.True(RoslynEnumerableExtensions.SequenceEqual((IEnumerable)null, null, comparer)); + Assert.False(RoslynEnumerableExtensions.SequenceEqual(new[] { 1 }, null, comparer)); + Assert.False(RoslynEnumerableExtensions.SequenceEqual(null, new[] { 1 }, comparer)); + + Assert.True(RoslynEnumerableExtensions.SequenceEqual(new[] { 1 }, new[] { 1 }, comparer)); + Assert.False(RoslynEnumerableExtensions.SequenceEqual(new int[0], new[] { 1 }, comparer)); + Assert.False(RoslynEnumerableExtensions.SequenceEqual(new[] { 1 }, new int[0], comparer)); + Assert.False(RoslynEnumerableExtensions.SequenceEqual(new[] { 1, 2, 3 }, new[] { 1, 3, 2 }, comparer)); + Assert.True(RoslynEnumerableExtensions.SequenceEqual(new[] { 1, 2, 3 }, new[] { 1, 2, 3 }, comparer)); + } - public class EnumerableExtensionsTests + [Fact] + public void AsSingleton() { - [Fact] - public void SequenceEqual() + Assert.Equal(0, new int[] { }.AsSingleton()); + Assert.Equal(1, new int[] { 1 }.AsSingleton()); + Assert.Equal(0, new int[] { 1, 2 }.AsSingleton()); + + Assert.Equal(0, Enumerable.Range(1, 0).AsSingleton()); + Assert.Equal(1, Enumerable.Range(1, 1).AsSingleton()); + Assert.Equal(0, Enumerable.Range(1, 2).AsSingleton()); + } + + private class ReadOnlyList : IReadOnlyList + { + private readonly T[] _items; + + public ReadOnlyList(params T[] items) { - bool comparer(int x, int y) => x == y; - Assert.True(EnumerableExtensions.SequenceEqual((IEnumerable)null, null, comparer)); - Assert.False(EnumerableExtensions.SequenceEqual(new[] { 1 }, null, comparer)); - Assert.False(EnumerableExtensions.SequenceEqual(null, new[] { 1 }, comparer)); - - Assert.True(EnumerableExtensions.SequenceEqual(new[] { 1 }, new[] { 1 }, comparer)); - Assert.False(EnumerableExtensions.SequenceEqual(new int[0], new[] { 1 }, comparer)); - Assert.False(EnumerableExtensions.SequenceEqual(new[] { 1 }, new int[0], comparer)); - Assert.False(EnumerableExtensions.SequenceEqual(new[] { 1, 2, 3 }, new[] { 1, 3, 2 }, comparer)); - Assert.True(EnumerableExtensions.SequenceEqual(new[] { 1, 2, 3 }, new[] { 1, 2, 3 }, comparer)); + _items = items; } + + public T this[int index] => _items[index]; + public int Count => _items.Length; + public IEnumerator GetEnumerator() => throw new NotImplementedException(); + IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); + } + + private class SignlessEqualityComparer : IEqualityComparer + { + public bool Equals(int x, int y) => Math.Abs(x) == Math.Abs(y); + public int GetHashCode(int obj) => throw new NotImplementedException(); + } + + [Fact] + public void IndexOf() + { + Assert.Equal(-1, SpecializedCollections.SingletonList(5).IndexOf(6)); + Assert.Equal(0, SpecializedCollections.SingletonList(5).IndexOf(5)); + + Assert.Equal(-1, new ReadOnlyList(5).IndexOf(6)); + Assert.Equal(0, new ReadOnlyList(5).IndexOf(5)); + } + + [Fact] + public void IndexOf_EqualityComparer() + { + var comparer = new SignlessEqualityComparer(); + + Assert.Equal(-1, SpecializedCollections.SingletonList(5).IndexOf(-6, comparer)); + Assert.Equal(0, SpecializedCollections.SingletonList(5).IndexOf(-5, comparer)); + + Assert.Equal(-1, new ReadOnlyList(5).IndexOf(-6, comparer)); + Assert.Equal(0, new ReadOnlyList(5).IndexOf(-5, comparer)); + } + + [Fact] + public void TestDo() + { + var elements = MakeEnumerable(1, 2, 3); + var result = new List(); + + elements.Do(a => result.Add(a)); + + Assert.True(elements.SequenceEqual(result)); + } + + [Fact] + public void TestConcat() + { + var elements = MakeEnumerable(1, 2, 3); + Assert.True(MakeEnumerable(1, 2, 3, 4).SequenceEqual(elements.Concat(4))); + } + + [Fact] + public void TestSetEquals() + => Assert.True(MakeEnumerable(1, 2, 3, 4).SetEquals(MakeEnumerable(4, 2, 3, 1))); + + [Fact] + public void TestIsEmpty() + { + Assert.True(MakeEnumerable().IsEmpty()); + Assert.False(MakeEnumerable(0).IsEmpty()); + } + + [Fact] + public void TestJoin() + { + Assert.Equal(string.Empty, MakeEnumerable().Join(", ")); + Assert.Equal("a", MakeEnumerable("a").Join(", ")); + Assert.Equal("a, b", MakeEnumerable("a", "b").Join(", ")); + Assert.Equal("a, b, c", MakeEnumerable("a", "b", "c").Join(", ")); + } + + [Fact] + public void TestFlatten() + { + var sequence = MakeEnumerable(MakeEnumerable("a", "b"), MakeEnumerable("c", "d"), MakeEnumerable("e", "f")); + Assert.True(sequence.Flatten().SequenceEqual(MakeEnumerable("a", "b", "c", "d", "e", "f"))); + } + + [Fact] + public void TestSequenceEqualWithFunction() + { + static bool equality(int a, int b) => a == b; + var seq = new List() { 1, 2, 3 }; + + // same object reference + Assert.True(seq.SequenceEqual(seq, equality)); + + // matching values, matching lengths + Assert.True(seq.SequenceEqual(new int[] { 1, 2, 3 }, equality)); + + // matching values, different lengths + Assert.False(seq.SequenceEqual(new int[] { 1, 2, 3, 4 }, equality)); + Assert.False(seq.SequenceEqual(new int[] { 1, 2 }, equality)); + + // different values, matching lengths + Assert.False(seq.SequenceEqual(new int[] { 1, 2, 6 }, equality)); + } + + public sealed class Comparer(Func equals, Func hashCode) : IEqualityComparer + { + private readonly Func _equals = equals; + private readonly Func _hashCode = hashCode; + + public bool Equals(T x, T y) => _equals(x, y); + public int GetHashCode(T obj) => _hashCode(obj); + } + + [Fact] + public void HasDuplicates() + { + var comparer = new Comparer((x, y) => x % 10 == y % 10, x => (x % 10).GetHashCode()); + + Assert.False(MakeEnumerable().HasDuplicates()); + Assert.False(MakeEnumerable().HasDuplicates(comparer)); + Assert.False(MakeEnumerable().HasDuplicates(i => i + 1)); + + Assert.False(MakeEnumerable(1).HasDuplicates()); + Assert.False(MakeEnumerable(1).HasDuplicates(comparer)); + Assert.False(MakeEnumerable(1).HasDuplicates(i => i + 1)); + + Assert.False(MakeEnumerable(1, 2).HasDuplicates()); + Assert.False(MakeEnumerable(1, 2).HasDuplicates(comparer)); + Assert.False(MakeEnumerable(1, 2).HasDuplicates(i => i + 1)); + + Assert.True(MakeEnumerable(1, 1).HasDuplicates()); + Assert.True(MakeEnumerable(11, 1).HasDuplicates(comparer)); + Assert.True(MakeEnumerable(1, 3).HasDuplicates(i => i % 2)); + Assert.True(MakeEnumerable(11.0, 1.2).HasDuplicates(i => (int)i, comparer)); + + Assert.False(MakeEnumerable(2, 0, 1, 3).HasDuplicates()); + Assert.False(MakeEnumerable(2, 0, 1, 13).HasDuplicates(comparer)); + Assert.False(MakeEnumerable(2, 0, 1, 53).HasDuplicates(i => i % 10)); + Assert.False(MakeEnumerable(2.3, 0.1, 1.3, 53.4).HasDuplicates(i => (int)i, comparer)); + + Assert.True(MakeEnumerable(2, 0, 1, 2).HasDuplicates()); + Assert.True(MakeEnumerable(2, 0, 1, 12).HasDuplicates(comparer)); + Assert.True(MakeEnumerable(2, 0, 1, 52).HasDuplicates(i => i % 10)); + Assert.True(MakeEnumerable(2.3, 0.1, 1.3, 52.4).HasDuplicates(i => (int)i, comparer)); } } diff --git a/src/Compilers/Core/CodeAnalysisTest/Collections/TemporaryArrayTests.cs b/src/Compilers/Core/CodeAnalysisTest/Collections/TemporaryArrayTests.cs index 57069ea7a58d2..5796519e0f913 100644 --- a/src/Compilers/Core/CodeAnalysisTest/Collections/TemporaryArrayTests.cs +++ b/src/Compilers/Core/CodeAnalysisTest/Collections/TemporaryArrayTests.cs @@ -6,7 +6,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; -using Microsoft.CodeAnalysis.Shared.Collections; +using Microsoft.CodeAnalysis.Collections; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections diff --git a/src/Compilers/Core/CodeAnalysisTest/Collections/TopologicalSortTests.cs b/src/Compilers/Core/CodeAnalysisTest/Collections/TopologicalSortTests.cs index f17755162b283..680435f807800 100644 --- a/src/Compilers/Core/CodeAnalysisTest/Collections/TopologicalSortTests.cs +++ b/src/Compilers/Core/CodeAnalysisTest/Collections/TopologicalSortTests.cs @@ -7,7 +7,7 @@ using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Shared.Collections; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Test.Utilities; using Xunit; diff --git a/src/Compilers/Core/CodeAnalysisTest/CompilerResolverTests.cs b/src/Compilers/Core/CodeAnalysisTest/CompilerResolverTests.cs index 546546ba3f649..e47630d984c03 100644 --- a/src/Compilers/Core/CodeAnalysisTest/CompilerResolverTests.cs +++ b/src/Compilers/Core/CodeAnalysisTest/CompilerResolverTests.cs @@ -4,10 +4,12 @@ #if NET using System; +using System.Collections.Immutable; using System.Linq; using System.Reflection; using System.Runtime.Loader; using Microsoft.CodeAnalysis.Test.Utilities; +using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; @@ -16,7 +18,7 @@ namespace Microsoft.CodeAnalysis.UnitTests; public sealed class CompilerResolverTests : IDisposable { public TempRoot TempRoot { get; } - public int DefaultLoadContextCount { get; } + public ImmutableArray DefaultLoadContextAssemblies { get; } public AssemblyLoadContext CompilerContext { get; } public AssemblyLoadContext ScratchContext { get; } public Assembly AssemblyInCompilerContext { get; } @@ -25,7 +27,7 @@ public sealed class CompilerResolverTests : IDisposable public CompilerResolverTests() { TempRoot = new TempRoot(); - DefaultLoadContextCount = AssemblyLoadContext.Default.Assemblies.Count(); + DefaultLoadContextAssemblies = AssemblyLoadContext.Default.Assemblies.SelectAsArray(a => a.FullName); CompilerContext = new AssemblyLoadContext(nameof(CompilerResolverTests), isCollectible: true); AssemblyInCompilerContext = CompilerContext.LoadFromAssemblyPath(typeof(AnalyzerAssemblyLoader).Assembly.Location); ScratchContext = new AssemblyLoadContext("Scratch", isCollectible: true); @@ -35,7 +37,7 @@ public CompilerResolverTests() public void Dispose() { // This test should not pollute the default load context and hence interfere with other tests. - Assert.Equal(DefaultLoadContextCount, AssemblyLoadContext.Default.Assemblies.Count()); + AssertEx.SetEqual(DefaultLoadContextAssemblies, AssemblyLoadContext.Default.Assemblies.SelectAsArray(a => a.FullName)); CompilerContext.Unload(); ScratchContext.Unload(); TempRoot.Dispose(); @@ -49,7 +51,7 @@ public void ResolveReturnsNullForNonHostAssembly() Assert.Null(assembly); } - [Fact] + [ConditionalFact(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/79352")] public void ResolveReturnsForHostAssembly() { var assembly = Loader.CompilerAnalyzerAssemblyResolver.Resolve(Loader, AssemblyInCompilerContext.GetName(), ScratchContext, TempRoot.CreateDirectory().Path); diff --git a/src/Compilers/Core/CodeAnalysisTest/Diagnostics/CompilationWithAnalyzersTests.cs b/src/Compilers/Core/CodeAnalysisTest/Diagnostics/CompilationWithAnalyzersTests.cs index afbec11d10025..0d673079b4b06 100644 --- a/src/Compilers/Core/CodeAnalysisTest/Diagnostics/CompilationWithAnalyzersTests.cs +++ b/src/Compilers/Core/CodeAnalysisTest/Diagnostics/CompilationWithAnalyzersTests.cs @@ -5,6 +5,7 @@ #nullable disable using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CSharp; @@ -12,7 +13,6 @@ using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers; -using KeyValuePairUtil = Roslyn.Utilities.KeyValuePairUtil; namespace Microsoft.CodeAnalysis.UnitTests.Diagnostics { @@ -38,7 +38,7 @@ public void GetEffectiveDiagnostics() { var c = CSharpCompilation.Create("c", options: s_dllWithMaxWarningLevel. WithSpecificDiagnosticOptions( - new[] { KeyValuePairUtil.Create($"CS{(int)ErrorCode.WRN_AlwaysNull:D4}", ReportDiagnostic.Suppress) })); + new[] { KeyValuePair.Create($"CS{(int)ErrorCode.WRN_AlwaysNull:D4}", ReportDiagnostic.Suppress) })); var d1 = SimpleDiagnostic.Create(MessageProvider.Instance, (int)ErrorCode.WRN_AlignmentMagnitude, "1", "2"); var d2 = SimpleDiagnostic.Create(MessageProvider.Instance, (int)ErrorCode.WRN_AlwaysNull, "1"); diff --git a/src/Compilers/Core/CodeAnalysisTest/InternalUtilities/OneOrManyTests.cs b/src/Compilers/Core/CodeAnalysisTest/InternalUtilities/OneOrManyTests.cs index 4d8d76b8cc720..7593eb700eece 100644 --- a/src/Compilers/Core/CodeAnalysisTest/InternalUtilities/OneOrManyTests.cs +++ b/src/Compilers/Core/CodeAnalysisTest/InternalUtilities/OneOrManyTests.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; diff --git a/src/Compilers/Core/CodeAnalysisTest/InvokeUtil.cs b/src/Compilers/Core/CodeAnalysisTest/InvokeUtil.cs index a7879283bce40..408434fc7e3c9 100644 --- a/src/Compilers/Core/CodeAnalysisTest/InvokeUtil.cs +++ b/src/Compilers/Core/CodeAnalysisTest/InvokeUtil.cs @@ -63,7 +63,7 @@ internal void Exec( } var loader = new AnalyzerAssemblyLoader(pathResolvers, assemblyResolvers, compilerLoadContext: null); - var compilerContextAssemblyCount = loader.CompilerLoadContext.Assemblies.Count(); + var compilerContextAssemblies = loader.CompilerLoadContext.Assemblies.SelectAsArray(a => a.FullName); try { Exec(testOutputHelper, fixture, loader, typeName, methodName, state); @@ -72,7 +72,7 @@ internal void Exec( { // When using the actual compiler load context (the one shared by all of our unit tests) the test // did not load any additional assemblies that could interfere with later tests. - Assert.Equal(compilerContextAssemblyCount, loader.CompilerLoadContext.Assemblies.Count()); + AssertEx.SetEqual(compilerContextAssemblies, loader.CompilerLoadContext.Assemblies.SelectAsArray(a => a.FullName)); } } @@ -89,7 +89,7 @@ internal void Exec( // load into the compiler or directory load context. // // Not only is this bad behavior it also pollutes future test results. - var defaultContextCount = AssemblyLoadContext.Default.Assemblies.Count(); + var defaultContextAssemblies = AssemblyLoadContext.Default.Assemblies.SelectAsArray(a => a.FullName); using var tempRoot = new TempRoot(); try @@ -120,7 +120,7 @@ internal void Exec( testOutputHelper.WriteLine($"\t{pair.OriginalAssemblyPath} -> {pair.ResolvedAssemblyPath}"); } - Assert.Equal(defaultContextCount, AssemblyLoadContext.Default.Assemblies.Count()); + AssertEx.SetEqual(defaultContextAssemblies, AssemblyLoadContext.Default.Assemblies.SelectAsArray(a => a.FullName)); } } } diff --git a/src/Compilers/Core/CodeAnalysisTest/SourceFileResolverTest.cs b/src/Compilers/Core/CodeAnalysisTest/SourceFileResolverTest.cs index 326a13c5140dd..7d95f38affb3e 100644 --- a/src/Compilers/Core/CodeAnalysisTest/SourceFileResolverTest.cs +++ b/src/Compilers/Core/CodeAnalysisTest/SourceFileResolverTest.cs @@ -7,6 +7,7 @@ using Roslyn.Test.Utilities; using Roslyn.Utilities; using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using Xunit; @@ -33,7 +34,7 @@ public void IncorrectPathmaps() new SourceFileResolver( ImmutableArray.Create(""), isABaseDirectory, - ImmutableArray.Create(KeyValuePairUtil.Create("key", null))); + ImmutableArray.Create(KeyValuePair.Create("key", null))); AssertEx.Fail("Didn't throw"); } catch (ArgumentException argException) @@ -45,7 +46,7 @@ public void IncorrectPathmaps() new SourceFileResolver( ImmutableArray.Create(""), isABaseDirectory, - ImmutableArray.Create(KeyValuePairUtil.Create("key", ""))); + ImmutableArray.Create(KeyValuePair.Create("key", ""))); } [Fact] @@ -54,9 +55,9 @@ public void BadBaseDirectory() try { new SourceFileResolver( - ImmutableArray.Create(""), + [""], "not_a_root directory", - ImmutableArray.Create(KeyValuePairUtil.Create("key", "value"))); + [KeyValuePair.Create("key", "value")]); AssertEx.Fail("Didn't throw"); } catch (ArgumentException argException) diff --git a/src/Compilers/Core/CodeAnalysisTest/StringTableTests.cs b/src/Compilers/Core/CodeAnalysisTest/StringTableTests.cs index 3645077efb104..f4a2c26a37c14 100644 --- a/src/Compilers/Core/CodeAnalysisTest/StringTableTests.cs +++ b/src/Compilers/Core/CodeAnalysisTest/StringTableTests.cs @@ -48,7 +48,7 @@ public void TestAddSameWithVariousInputsProducesSameStringInstance() var s3 = st.Add(" "); Assert.Same(s2, s3); - var s4 = st.Add(new char[1] { ' ' }, 0, 1); + var s4 = st.Add([' ']); Assert.Same(s3, s4); var s5 = st.Add("ABC DEF", 3, 1); diff --git a/src/Compilers/Core/CodeAnalysisTest/Text/TextChangeTests.cs b/src/Compilers/Core/CodeAnalysisTest/Text/TextChangeTests.cs index ba0f572cbe928..7f8818503f094 100644 --- a/src/Compilers/Core/CodeAnalysisTest/Text/TextChangeTests.cs +++ b/src/Compilers/Core/CodeAnalysisTest/Text/TextChangeTests.cs @@ -58,6 +58,29 @@ public void TestSubTextSpanMid() Assert.Equal("o W", subText.ToString()); } + [Fact] + public void TestSubTextSubTextStart() + { + var text = SourceText.From("Hello World"); + var subText = text.GetSubText(new TextSpan(0, 5)); + var subSubText = subText.GetSubText(new TextSpan(0, 0)); + + Assert.Equal("Hello", subText.ToString()); + Assert.Equal(0, subSubText.Length); + } + + [Fact] + [WorkItem(78989, "https://github.com/dotnet/roslyn/pull/78989")] + public void TestSubTextSubTextEnd() + { + var text = SourceText.From("Hello World"); + var subText = text.GetSubText(6); + var subSubText = subText.GetSubText(subText.Length); + + Assert.Equal("World", subText.ToString()); + Assert.Equal(0, subSubText.Length); + } + [Fact] public void TestChangedText() { diff --git a/src/Compilers/Core/MSBuildTask/Directory.Build.props b/src/Compilers/Core/MSBuildTask/Directory.Build.props index 6c4c27e3282bd..734b20b8f8522 100644 --- a/src/Compilers/Core/MSBuildTask/Directory.Build.props +++ b/src/Compilers/Core/MSBuildTask/Directory.Build.props @@ -23,18 +23,9 @@ - - - - - - - - + - - @@ -68,4 +59,6 @@ contentFiles\any\any + + diff --git a/src/Compilers/Core/Portable/CodeAnalysisEventSource.Common.cs b/src/Compilers/Core/Portable/CodeAnalysisEventSource.Common.cs index 4e3dba61cd567..fd672ecc541ec 100644 --- a/src/Compilers/Core/Portable/CodeAnalysisEventSource.Common.cs +++ b/src/Compilers/Core/Portable/CodeAnalysisEventSource.Common.cs @@ -125,7 +125,7 @@ internal unsafe void NodeTransform(int nodeHashCode, string name, string tableTy [Event(16, Message = "Analyzer reference '{0}' was removed from project '{1}'", Keywords = Keywords.AnalyzerLoading, Level = EventLevel.Informational)] internal void AnalyzerReferenceRemovedFromProject(string path, string projectName) => WriteEvent(16, path, projectName); - [Event(17, Message = "Analyzer reference was redirected by '{0}' from '{1}' to '{2}' for project '{3}'", Keywords = Keywords.AnalyzerLoading, Level = EventLevel.Verbose, Task = Tasks.BuildStateTable)] + [Event(17, Message = "Analyzer reference was redirected by '{0}' from '{1}' to '{2}' for project '{3}'", Keywords = Keywords.AnalyzerLoading, Level = EventLevel.Informational)] internal unsafe void AnanlyzerReferenceRedirected(string redirectorType, string originalPath, string newPath, string project) { if (IsEnabled()) diff --git a/src/Compilers/Core/Portable/Collections/ArrayBuilderExtensions.cs b/src/Compilers/Core/Portable/Collections/ArrayBuilderExtensions.cs index b57f1c519512b..8b8fd054b548f 100644 --- a/src/Compilers/Core/Portable/Collections/ArrayBuilderExtensions.cs +++ b/src/Compilers/Core/Portable/Collections/ArrayBuilderExtensions.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/Compilers/Core/Portable/Collections/StaticCast.cs b/src/Compilers/Core/Portable/Collections/StaticCast.cs index 790e4dbf078e4..ede174a6b395f 100644 --- a/src/Compilers/Core/Portable/Collections/StaticCast.cs +++ b/src/Compilers/Core/Portable/Collections/StaticCast.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis diff --git a/src/Compilers/Core/Portable/Collections/TopologicalSort.cs b/src/Compilers/Core/Portable/Collections/TopologicalSort.cs index 63af270c3a803..403417c1812c9 100644 --- a/src/Compilers/Core/Portable/Collections/TopologicalSort.cs +++ b/src/Compilers/Core/Portable/Collections/TopologicalSort.cs @@ -7,7 +7,6 @@ using System.Diagnostics; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Shared.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis diff --git a/src/Compilers/Core/Portable/CommandLine/CommandLineParser.cs b/src/Compilers/Core/Portable/CommandLine/CommandLineParser.cs index ac05da9bf7f0d..503058344f3c7 100644 --- a/src/Compilers/Core/Portable/CommandLine/CommandLineParser.cs +++ b/src/Compilers/Core/Portable/CommandLine/CommandLineParser.cs @@ -509,22 +509,22 @@ internal void FlattenArgs( bool sourceFileSeen = false; bool optionsEnded = false; - var args = ArrayBuilder.GetInstance(); - args.AddRange(rawArguments); - args.ReverseContents(); - var argsIndex = args.Count - 1; - while (argsIndex >= 0) + foreach (string arg in rawArguments) + { + processArg(arg); + } + + void processArg(string arg) { // EDMAURER trim off whitespace. Otherwise behavioral differences arise // when the strings which represent args are constructed by cmd or users. // cmd won't produce args with whitespace at the end. - string arg = args[argsIndex].TrimEnd(); - argsIndex--; + arg = arg.TrimEnd(); if (parsingScriptArgs) { scriptArgsOpt!.Add(arg); - continue; + return; } if (scriptArgsOpt != null) @@ -541,7 +541,7 @@ internal void FlattenArgs( // csi/vbi: at most one script can be specified on command line, anything else is a script arg: parsingScriptArgs = true; scriptArgsOpt.Add(arg); - continue; + return; } if (!optionsEnded && arg == "--") @@ -549,7 +549,7 @@ internal void FlattenArgs( // csi/vbi: no argument past "--" should be treated as an option/response file optionsEnded = true; processedArgs.Add(arg); - continue; + return; } } @@ -586,7 +586,6 @@ internal void FlattenArgs( sourceFileSeen |= optionsEnded || !IsOption(arg); } } - args.Free(); void parseResponseFile(string fullPath) { @@ -653,21 +652,12 @@ void parseResponseFile(string fullPath) return; } - for (var i = splitList.Count - 1; i >= 0; i--) + foreach (var newArg in splitList) { - var newArg = splitList[i]; // Ignores /noconfig option specified in a response file if (!string.Equals(newArg, "/noconfig", StringComparison.OrdinalIgnoreCase) && !string.Equals(newArg, "-noconfig", StringComparison.OrdinalIgnoreCase)) { - argsIndex++; - if (argsIndex < args.Count) - { - args[argsIndex] = newArg; - } - else - { - args.Add(newArg); - } + processArg(newArg); } else { diff --git a/src/Compilers/Core/Portable/Compilation/Compilation.cs b/src/Compilers/Core/Portable/Compilation/Compilation.cs index 631274bba0a40..e09234674e1c9 100644 --- a/src/Compilers/Core/Portable/Compilation/Compilation.cs +++ b/src/Compilers/Core/Portable/Compilation/Compilation.cs @@ -24,7 +24,6 @@ using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Symbols; using Microsoft.DiaSymReader; using Roslyn.Utilities; diff --git a/src/Compilers/Core/Portable/Compilation/DeterministicKeyBuilder.cs b/src/Compilers/Core/Portable/Compilation/DeterministicKeyBuilder.cs index 210421fe3375f..00bee015c64ad 100644 --- a/src/Compilers/Core/Portable/Compilation/DeterministicKeyBuilder.cs +++ b/src/Compilers/Core/Portable/Compilation/DeterministicKeyBuilder.cs @@ -7,6 +7,7 @@ using System.Collections.Immutable; using System.Globalization; using System.IO; +using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; diff --git a/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalysisResultBuilder.cs b/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalysisResultBuilder.cs index a2673decbda91..d48ff0662983d 100644 --- a/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalysisResultBuilder.cs +++ b/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalysisResultBuilder.cs @@ -8,6 +8,7 @@ using System.Diagnostics; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics.Telemetry; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerDriver.GroupedAnalyzerActions.cs b/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerDriver.GroupedAnalyzerActions.cs index 521c4437f1a98..bb6809f7f3a34 100644 --- a/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerDriver.GroupedAnalyzerActions.cs +++ b/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerDriver.GroupedAnalyzerActions.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Collections; diff --git a/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerDriver.cs b/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerDriver.cs index 86e1a04700331..84e42332b22ee 100644 --- a/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerDriver.cs +++ b/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerDriver.cs @@ -16,7 +16,6 @@ using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/Compilers/Core/Portable/DocumentationComments/DocumentationCommentIncludeCache.cs b/src/Compilers/Core/Portable/DocumentationComments/DocumentationCommentIncludeCache.cs index 04d210aa45b61..f98a9c939f004 100644 --- a/src/Compilers/Core/Portable/DocumentationComments/DocumentationCommentIncludeCache.cs +++ b/src/Compilers/Core/Portable/DocumentationComments/DocumentationCommentIncludeCache.cs @@ -55,7 +55,7 @@ private static KeyValuePair MakeValue(XmlReferenceResolver re using (XmlReader reader = XmlReader.Create(stream, s_xmlSettings)) { var document = XDocument.Load(reader, LoadOptions.PreserveWhitespace | LoadOptions.SetLineInfo); - return KeyValuePairUtil.Create(resolvedPath, document); + return KeyValuePair.Create(resolvedPath, document); } } } diff --git a/src/Compilers/Core/Portable/EmbeddedText.cs b/src/Compilers/Core/Portable/EmbeddedText.cs index 5495de2bf9d6d..b4fc78dff9f2a 100644 --- a/src/Compilers/Core/Portable/EmbeddedText.cs +++ b/src/Compilers/Core/Portable/EmbeddedText.cs @@ -370,7 +370,7 @@ public override void WriteByte(byte value) base.WriteByte(value); // same rationale for checked arithmetic as above. - checked { BytesWritten++; }; + checked { BytesWritten++; } } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) diff --git a/src/Compilers/Core/Portable/InternalUtilities/Debug.cs b/src/Compilers/Core/Portable/InternalUtilities/Debug.cs index ebd3a10bf6250..4468c0ac5266c 100644 --- a/src/Compilers/Core/Portable/InternalUtilities/Debug.cs +++ b/src/Compilers/Core/Portable/InternalUtilities/Debug.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; diff --git a/src/Compilers/Core/Portable/InternalUtilities/Hash.cs b/src/Compilers/Core/Portable/InternalUtilities/Hash.cs index 97efbf24f3730..30007df6f4c2f 100644 --- a/src/Compilers/Core/Portable/InternalUtilities/Hash.cs +++ b/src/Compilers/Core/Portable/InternalUtilities/Hash.cs @@ -286,9 +286,7 @@ internal static int GetFNVHashCode(string text, int start, int length) => GetFNVHashCode(text.AsSpan(start, length)); internal static int GetCaseInsensitiveFNVHashCode(string text) - { - return GetCaseInsensitiveFNVHashCode(text.AsSpan(0, text.Length)); - } + => GetCaseInsensitiveFNVHashCode(text.AsSpan()); internal static int GetCaseInsensitiveFNVHashCode(ReadOnlySpan data) { @@ -302,18 +300,6 @@ internal static int GetCaseInsensitiveFNVHashCode(ReadOnlySpan data) return hashCode; } - /// - /// Compute the hashcode of a sub-string using FNV-1a - /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function - /// - /// The input string - /// The start index of the first character to hash - /// The FNV-1a hash code of the substring beginning at and ending at the end of the string. - internal static int GetFNVHashCode(string text, int start) - { - return GetFNVHashCode(text, start, length: text.Length - start); - } - /// /// Compute the hashcode of a string using FNV-1a /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function @@ -363,17 +349,7 @@ internal static int GetFNVHashCode(System.Text.StringBuilder text) /// The number of characters, beginning with to hash /// The FNV-1a hash code of the substring beginning at and ending after characters. internal static int GetFNVHashCode(char[] text, int start, int length) - { - int hashCode = Hash.FnvOffsetBias; - int end = start + length; - - for (int i = start; i < end; i++) - { - hashCode = unchecked((hashCode ^ text[i]) * Hash.FnvPrime); - } - - return hashCode; - } + => GetFNVHashCode(text.AsSpan(start, length)); /// /// Compute the hashcode of a single character using the FNV-1a algorithm @@ -397,14 +373,7 @@ internal static int GetFNVHashCode(char ch) /// The string to combine /// The result of combining with using the FNV-1a algorithm internal static int CombineFNVHash(int hashCode, string text) - { - foreach (char ch in text) - { - hashCode = unchecked((hashCode ^ ch) * Hash.FnvPrime); - } - - return hashCode; - } + => CombineFNVHash(hashCode, text.AsSpan()); /// /// Combine a char with an existing FNV-1a hash code diff --git a/src/Compilers/Core/Portable/InternalUtilities/KeyValuePairUtil.cs b/src/Compilers/Core/Portable/InternalUtilities/KeyValuePairUtil.cs deleted file mode 100644 index 3c51ea439f62a..0000000000000 --- a/src/Compilers/Core/Portable/InternalUtilities/KeyValuePairUtil.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Generic; - -namespace Roslyn.Utilities -{ - internal static class KeyValuePairUtil - { - public static KeyValuePair Create(K key, V value) - { - return new KeyValuePair(key, value); - } - - public static void Deconstruct(this KeyValuePair keyValuePair, out TKey key, out TValue value) - { - key = keyValuePair.Key; - value = keyValuePair.Value; - } - - public static KeyValuePair ToKeyValuePair(this (TKey, TValue) tuple) => Create(tuple.Item1, tuple.Item2); - } -} diff --git a/src/Compilers/Core/Portable/InternalUtilities/PlatformInformation.cs b/src/Compilers/Core/Portable/InternalUtilities/PlatformInformation.cs index fbf4474699150..559fc24c63aad 100644 --- a/src/Compilers/Core/Portable/InternalUtilities/PlatformInformation.cs +++ b/src/Compilers/Core/Portable/InternalUtilities/PlatformInformation.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.IO; using System.Runtime.Versioning; diff --git a/src/Compilers/Core/Portable/InternalUtilities/StringTable.cs b/src/Compilers/Core/Portable/InternalUtilities/StringTable.cs index 96518a81e3752..32ccbf6d08a89 100644 --- a/src/Compilers/Core/Portable/InternalUtilities/StringTable.cs +++ b/src/Compilers/Core/Portable/InternalUtilities/StringTable.cs @@ -5,12 +5,8 @@ using System; using System.Text; using System.Threading; -using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Collections; - -#if DEBUG -using System.Diagnostics; -#endif +using Microsoft.CodeAnalysis.PooledObjects; namespace Roslyn.Utilities { @@ -111,10 +107,21 @@ public void Free() #endregion // Poolable + /// + /// Legacy entrypoint for VB. + /// + internal string Add(char[] chars) + => Add(chars.AsSpan()); + + /// + /// Legacy entrypoint for VB. + /// internal string Add(char[] chars, int start, int len) + => Add(chars.AsSpan(start, len)); + + internal string Add(ReadOnlySpan chars) { - var span = chars.AsSpan(start, len); - var hashCode = Hash.GetFNVHashCode(chars, start, len); + var hashCode = Hash.GetFNVHashCode(chars); // capture array to avoid extra range checks var arr = _localTable; @@ -125,13 +132,13 @@ internal string Add(char[] chars, int start, int len) if (text != null && arr[idx].HashCode == hashCode) { var result = arr[idx].Text; - if (StringTable.TextEquals(result, span)) + if (TextEquals(result, chars)) { return result; } } - string? shared = FindSharedEntry(chars, start, len, hashCode); + string? shared = FindSharedEntry(chars, hashCode); if (shared != null) { // PERF: the following code does element-wise assignment of a struct @@ -143,76 +150,14 @@ internal string Add(char[] chars, int start, int len) return shared; } - return AddItem(chars, start, len, hashCode); + return AddItem(chars, hashCode); } internal string Add(string chars, int start, int len) - { - var hashCode = Hash.GetFNVHashCode(chars, start, len); - - // capture array to avoid extra range checks - var arr = _localTable; - var idx = LocalIdxFromHash(hashCode); - - var text = arr[idx].Text; - - if (text != null && arr[idx].HashCode == hashCode) - { - var result = arr[idx].Text; - if (StringTable.TextEquals(result, chars, start, len)) - { - return result; - } - } - - string? shared = FindSharedEntry(chars, start, len, hashCode); - if (shared != null) - { - // PERF: the following code does element-wise assignment of a struct - // because current JIT produces better code compared to - // arr[idx] = new Entry(...) - arr[idx].HashCode = hashCode; - arr[idx].Text = shared; - - return shared; - } - - return AddItem(chars, start, len, hashCode); - } + => Add(chars.AsSpan(start, len)); internal string Add(char chars) - { - var hashCode = Hash.GetFNVHashCode(chars); - - // capture array to avoid extra range checks - var arr = _localTable; - var idx = LocalIdxFromHash(hashCode); - - var text = arr[idx].Text; - - if (text != null) - { - var result = arr[idx].Text; - if (text.Length == 1 && text[0] == chars) - { - return result; - } - } - - string? shared = FindSharedEntry(chars, hashCode); - if (shared != null) - { - // PERF: the following code does element-wise assignment of a struct - // because current JIT produces better code compared to - // arr[idx] = new Entry(...) - arr[idx].HashCode = hashCode; - arr[idx].Text = shared; - - return shared; - } - - return AddItem(chars, hashCode); - } + => Add([chars]); internal string Add(StringBuilder chars) { @@ -249,41 +194,9 @@ internal string Add(StringBuilder chars) } internal string Add(string chars) - { - var hashCode = Hash.GetFNVHashCode(chars); - - // capture array to avoid extra range checks - var arr = _localTable; - var idx = LocalIdxFromHash(hashCode); + => Add(chars.AsSpan()); - var text = arr[idx].Text; - - if (text != null && arr[idx].HashCode == hashCode) - { - var result = arr[idx].Text; - if (result == chars) - { - return result; - } - } - - string? shared = FindSharedEntry(chars, hashCode); - if (shared != null) - { - // PERF: the following code does element-wise assignment of a struct - // because current JIT produces better code compared to - // arr[idx] = new Entry(...) - arr[idx].HashCode = hashCode; - arr[idx].Text = shared; - - return shared; - } - - AddCore(chars, hashCode); - return chars; - } - - private static string? FindSharedEntry(char[] chars, int start, int len, int hashCode) + private static string? FindSharedEntry(ReadOnlySpan chars, int hashCode) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); @@ -298,7 +211,7 @@ internal string Add(string chars) if (e != null) { - if (hash == hashCode && TextEquals(e, chars.AsSpan(start, len))) + if (hash == hashCode && TextEquals(e, chars)) { break; } @@ -319,39 +232,7 @@ internal string Add(string chars) } private static string? FindSharedEntry(string chars, int start, int len, int hashCode) - { - var arr = s_sharedTable; - int idx = SharedIdxFromHash(hashCode); - - string? e = null; - // we use quadratic probing here - // bucket positions are (n^2 + n)/2 relative to the masked hashcode - for (int i = 1; i < SharedBucketSize + 1; i++) - { - e = arr[idx].Text; - int hash = arr[idx].HashCode; - - if (e != null) - { - if (hash == hashCode && TextEquals(e, chars, start, len)) - { - break; - } - - // this is not e we are looking for - e = null; - } - else - { - // once we see unfilled entry, the rest of the bucket will be empty - break; - } - - idx = (idx + i) & SharedSizeMask; - } - - return e; - } + => FindSharedEntry(chars.AsSpan(start, len), hashCode); private static string? FindSharedEntryASCII(int hashCode, ReadOnlySpan asciiChars) { @@ -389,38 +270,7 @@ internal string Add(string chars) } private static string? FindSharedEntry(char chars, int hashCode) - { - var arr = s_sharedTable; - int idx = SharedIdxFromHash(hashCode); - - string? e = null; - // we use quadratic probing here - // bucket positions are (n^2 + n)/2 relative to the masked hashcode - for (int i = 1; i < SharedBucketSize + 1; i++) - { - e = arr[idx].Text; - - if (e != null) - { - if (e.Length == 1 && e[0] == chars) - { - break; - } - - // this is not e we are looking for - e = null; - } - else - { - // once we see unfilled entry, the rest of the bucket will be empty - break; - } - - idx = (idx + i) & SharedSizeMask; - } - - return e; - } + => FindSharedEntry([chars], hashCode); private static string? FindSharedEntry(StringBuilder chars, int hashCode) { @@ -458,60 +308,27 @@ internal string Add(string chars) } private static string? FindSharedEntry(string chars, int hashCode) - { - var arr = s_sharedTable; - int idx = SharedIdxFromHash(hashCode); - - string? e = null; - // we use quadratic probing here - // bucket positions are (n^2 + n)/2 relative to the masked hashcode - for (int i = 1; i < SharedBucketSize + 1; i++) - { - e = arr[idx].Text; - int hash = arr[idx].HashCode; - - if (e != null) - { - if (hash == hashCode && e == chars) - { - break; - } - - // this is not e we are looking for - e = null; - } - else - { - // once we see unfilled entry, the rest of the bucket will be empty - break; - } + => FindSharedEntry(chars.AsSpan(), hashCode); - idx = (idx + i) & SharedSizeMask; - } - - return e; - } - - private string AddItem(char[] chars, int start, int len, int hashCode) + private string AddItem(ReadOnlySpan chars, int hashCode) { - var text = new String(chars, start, len); + var text = chars.ToString(); AddCore(text, hashCode); return text; } private string AddItem(string chars, int start, int len, int hashCode) { + // Don't defer to ReadOnlySpan here, as it would cause an extra allocation + // in the case where start/len exactly match the full span of chars. + var text = chars.Substring(start, len); AddCore(text, hashCode); return text; } private string AddItem(char chars, int hashCode) - { - var text = new String(chars, 1); - AddCore(text, hashCode); - return text; - } + => AddItem([chars], hashCode); private string AddItem(StringBuilder chars, int hashCode) { @@ -562,19 +379,6 @@ private void AddSharedEntry(int hashCode, string text) Volatile.Write(ref arr[idx].Text, text); } - internal static string AddShared(StringBuilder chars) - { - var hashCode = Hash.GetFNVHashCode(chars); - - string? shared = FindSharedEntry(chars, hashCode); - if (shared != null) - { - return shared; - } - - return AddSharedSlow(hashCode, chars); - } - private static string AddSharedSlow(int hashCode, StringBuilder builder) { string text = builder.ToString(); diff --git a/src/Compilers/Core/Portable/InternalUtilities/TextKeyedCache.cs b/src/Compilers/Core/Portable/InternalUtilities/TextKeyedCache.cs index b1cafb1babf32..8e402447b060f 100644 --- a/src/Compilers/Core/Portable/InternalUtilities/TextKeyedCache.cs +++ b/src/Compilers/Core/Portable/InternalUtilities/TextKeyedCache.cs @@ -105,7 +105,13 @@ public void Free() #endregion // Poolable + /// + /// Legacy entrypoint for VB. + /// internal T? FindItem(char[] chars, int start, int len, int hashCode) + => FindItem(chars.AsSpan(start, len), hashCode); + + internal T? FindItem(ReadOnlySpan chars, int hashCode) { // get direct element reference to avoid extra range checks ref var localSlot = ref _localTable[LocalIdxFromHash(hashCode)]; @@ -114,13 +120,13 @@ public void Free() if (text != null && localSlot.HashCode == hashCode) { - if (StringTable.TextEquals(text, chars.AsSpan(start, len))) + if (StringTable.TextEquals(text, chars)) { return localSlot.Item; } } - SharedEntryValue? e = FindSharedEntry(chars, start, len, hashCode); + SharedEntryValue? e = FindSharedEntry(chars, hashCode); if (e != null) { localSlot.HashCode = hashCode; @@ -135,7 +141,7 @@ public void Free() return null!; } - private SharedEntryValue? FindSharedEntry(char[] chars, int start, int len, int hashCode) + private SharedEntryValue? FindSharedEntry(ReadOnlySpan chars, int hashCode) { var arr = _sharedTableInst; int idx = SharedIdxFromHash(hashCode); @@ -151,7 +157,7 @@ public void Free() if (e != null) { - if (hash == hashCode && StringTable.TextEquals(e.Text, chars.AsSpan(start, len))) + if (hash == hashCode && StringTable.TextEquals(e.Text, chars)) { break; } @@ -171,9 +177,15 @@ public void Free() return e; } + /// + /// Legacy entrypoint for VB. + /// internal void AddItem(char[] chars, int start, int len, int hashCode, T item) + => AddItem(chars.AsSpan(start, len), hashCode, item); + + internal void AddItem(ReadOnlySpan chars, int hashCode, T item) { - var text = _strings.Add(chars, start, len); + var text = _strings.Add(chars); // add to the shared table first (in case someone looks for same item) var e = new SharedEntryValue(text, item); diff --git a/src/Compilers/Core/Portable/MetadataReader/MetadataDecoder.cs b/src/Compilers/Core/Portable/MetadataReader/MetadataDecoder.cs index 02677ff4ce71d..9b0323753a9f7 100644 --- a/src/Compilers/Core/Portable/MetadataReader/MetadataDecoder.cs +++ b/src/Compilers/Core/Portable/MetadataReader/MetadataDecoder.cs @@ -407,7 +407,7 @@ private TypeSymbol DecodeGenericTypeInstanceOrThrow(ref BlobReader ppSig, out bo bool argumentRefersToNoPia; SignatureTypeCode typeCode; ImmutableArray> modifiers = DecodeModifiersOrThrow(ref ppSig, out typeCode); - argumentsBuilder.Add(KeyValuePairUtil.Create(DecodeTypeOrThrow(ref ppSig, typeCode, out argumentRefersToNoPia), modifiers)); + argumentsBuilder.Add(KeyValuePair.Create(DecodeTypeOrThrow(ref ppSig, typeCode, out argumentRefersToNoPia), modifiers)); argumentRefersToNoPiaLocalTypeBuilder.Add(argumentRefersToNoPia); } diff --git a/src/Compilers/Core/Portable/MetadataReader/MetadataHelpers.cs b/src/Compilers/Core/Portable/MetadataReader/MetadataHelpers.cs index 7fce63b6d05b6..fd1727ca9f717 100644 --- a/src/Compilers/Core/Portable/MetadataReader/MetadataHelpers.cs +++ b/src/Compilers/Core/Portable/MetadataReader/MetadataHelpers.cs @@ -913,7 +913,7 @@ public static void GetInfoForImmediateNamespaceMembers( { Debug.Assert(keyIndex < i); var primaryPair = nestedNamespaces[keyIndex]; - nestedNamespaces[keyIndex] = KeyValuePairUtil.Create(primaryPair.Key, primaryPair.Value.Concat(pair.Value)); + nestedNamespaces[keyIndex] = KeyValuePair.Create(primaryPair.Key, primaryPair.Value.Concat(pair.Value)); nestedNamespaces[i] = default(KeyValuePair>>); } } diff --git a/src/Compilers/Core/Portable/MetadataReader/PEAssembly.cs b/src/Compilers/Core/Portable/MetadataReader/PEAssembly.cs index a3fc6af057ae9..122ed3ae22e35 100644 --- a/src/Compilers/Core/Portable/MetadataReader/PEAssembly.cs +++ b/src/Compilers/Core/Portable/MetadataReader/PEAssembly.cs @@ -8,6 +8,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using System.Linq; using System.Reflection.Metadata; using System.Threading; using Microsoft.CodeAnalysis.Collections; diff --git a/src/Compilers/Core/Portable/MetadataReader/PEModule.cs b/src/Compilers/Core/Portable/MetadataReader/PEModule.cs index afac6f99cded9..4907ad63b37d0 100644 --- a/src/Compilers/Core/Portable/MetadataReader/PEModule.cs +++ b/src/Compilers/Core/Portable/MetadataReader/PEModule.cs @@ -2338,19 +2338,6 @@ private static bool CrackBoolAndStringInAttributeValue(out BoolAndStringData val return false; } - private static bool CrackBoolAndBoolInAttributeValue(out (bool, bool) value, ref BlobReader sig) - { - if (CrackBooleanInAttributeValue(out bool item1, ref sig) && - CrackBooleanInAttributeValue(out bool item2, ref sig)) - { - value = (item1, item2); - return true; - } - - value = default; - return false; - } - private static bool CrackBooleanInAttributeValue(out bool value, ref BlobReader sig) { if (sig.RemainingBytes >= 1) diff --git a/src/Compilers/Core/Portable/MetadataReference/AssemblyIdentityMap.cs b/src/Compilers/Core/Portable/MetadataReference/AssemblyIdentityMap.cs index 2bdf07b561a8d..6a6eac02ff94c 100644 --- a/src/Compilers/Core/Portable/MetadataReference/AssemblyIdentityMap.cs +++ b/src/Compilers/Core/Portable/MetadataReference/AssemblyIdentityMap.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis @@ -97,7 +98,7 @@ public bool TryGetValue(AssemblyIdentity identity, out TValue value, Func> sameName; _map[identity.Name] = _map.TryGetValue(identity.Name, out sameName) ? sameName.Add(pair) : OneOrMany.Create(pair); diff --git a/src/Compilers/Core/Portable/PEWriter/MetadataWriter.cs b/src/Compilers/Core/Portable/PEWriter/MetadataWriter.cs index 9ac8a57318ec9..0b055e9a24e50 100644 --- a/src/Compilers/Core/Portable/PEWriter/MetadataWriter.cs +++ b/src/Compilers/Core/Portable/PEWriter/MetadataWriter.cs @@ -1140,7 +1140,7 @@ private BlobHandle GetMethodSignatureHandleAndBlob(IMethodReference methodRefere signatureBlob = builder.ToImmutableArray(); result = metadata.GetOrAddBlob(signatureBlob); - _signatureIndex.Add(methodReference, KeyValuePairUtil.Create(result, signatureBlob)); + _signatureIndex.Add(methodReference, KeyValuePair.Create(result, signatureBlob)); builder.Free(); return result; } @@ -1286,7 +1286,7 @@ private BlobHandle GetPropertySignatureHandle(IPropertyDefinition propertyDef) var blob = builder.ToImmutableArray(); var result = metadata.GetOrAddBlob(blob); - _signatureIndex.Add(propertyDef, KeyValuePairUtil.Create(result, blob)); + _signatureIndex.Add(propertyDef, KeyValuePair.Create(result, blob)); builder.Free(); return result; } diff --git a/src/Compilers/Core/Portable/PEWriter/NativeResourceWriter.cs b/src/Compilers/Core/Portable/PEWriter/NativeResourceWriter.cs index 386eba4d1157a..8c9f274ffc854 100644 --- a/src/Compilers/Core/Portable/PEWriter/NativeResourceWriter.cs +++ b/src/Compilers/Core/Portable/PEWriter/NativeResourceWriter.cs @@ -8,6 +8,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.IO; +using System.Linq; using System.Reflection.Metadata; using Roslyn.Utilities; diff --git a/src/Compilers/Core/Portable/ReferenceManager/AssemblyDataForAssemblyBeingBuilt.cs b/src/Compilers/Core/Portable/ReferenceManager/AssemblyDataForAssemblyBeingBuilt.cs index 6eaf5a7c65c3a..36735fb34a4af 100644 --- a/src/Compilers/Core/Portable/ReferenceManager/AssemblyDataForAssemblyBeingBuilt.cs +++ b/src/Compilers/Core/Portable/ReferenceManager/AssemblyDataForAssemblyBeingBuilt.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/Compilers/Core/Portable/ReferenceManager/CommonReferenceManager.State.cs b/src/Compilers/Core/Portable/ReferenceManager/CommonReferenceManager.State.cs index 20296b4e08ef8..63132614b1208 100644 --- a/src/Compilers/Core/Portable/ReferenceManager/CommonReferenceManager.State.cs +++ b/src/Compilers/Core/Portable/ReferenceManager/CommonReferenceManager.State.cs @@ -679,7 +679,7 @@ private static void PropagateRecursiveAliases( internal sealed override IEnumerable> GetReferencedAssemblies() { - return ReferencedAssembliesMap.Select(ra => KeyValuePairUtil.Create(ra.Key, (IAssemblySymbolInternal)ReferencedAssemblies[ra.Value])); + return ReferencedAssembliesMap.Select(ra => KeyValuePair.Create(ra.Key, (IAssemblySymbolInternal)ReferencedAssemblies[ra.Value])); } internal TAssemblySymbol? GetReferencedAssemblySymbol(MetadataReference reference) diff --git a/src/Compilers/Core/Portable/SourceGeneration/GlobalAliases.cs b/src/Compilers/Core/Portable/SourceGeneration/GlobalAliases.cs index a6939660c46f0..c6d424a7b9bed 100644 --- a/src/Compilers/Core/Portable/SourceGeneration/GlobalAliases.cs +++ b/src/Compilers/Core/Portable/SourceGeneration/GlobalAliases.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Immutable; +using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/Compilers/Core/Portable/SourceGeneration/Nodes/NodeStateTable.cs b/src/Compilers/Core/Portable/SourceGeneration/Nodes/NodeStateTable.cs index d166d64ec62ff..5acbe3013479b 100644 --- a/src/Compilers/Core/Portable/SourceGeneration/Nodes/NodeStateTable.cs +++ b/src/Compilers/Core/Portable/SourceGeneration/Nodes/NodeStateTable.cs @@ -8,6 +8,7 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/Compilers/Core/Portable/Text/SubText.cs b/src/Compilers/Core/Portable/Text/SubText.cs index e0935e8cebc0d..e59db9880fe04 100644 --- a/src/Compilers/Core/Portable/Text/SubText.cs +++ b/src/Compilers/Core/Portable/Text/SubText.cs @@ -22,9 +22,9 @@ public SubText(SourceText text, TextSpan span) throw new ArgumentNullException(nameof(text)); } + // span.Start and span.End are valid wrt eachother by nature of being passed in as a TextSpan, + // so there is no need to verify span.Start against text.Length or span.End against zero. if (span.Start < 0 - || span.Start >= text.Length - || span.End < 0 || span.End > text.Length) { throw new ArgumentOutOfRangeException(nameof(span)); diff --git a/src/Compilers/Core/RebuildTest/DeterministicKeyBuilderTests.cs b/src/Compilers/Core/RebuildTest/DeterministicKeyBuilderTests.cs index da69156710812..b763900796686 100644 --- a/src/Compilers/Core/RebuildTest/DeterministicKeyBuilderTests.cs +++ b/src/Compilers/Core/RebuildTest/DeterministicKeyBuilderTests.cs @@ -577,7 +577,7 @@ public void EmitOptionsPdbFilePathRespectsPathMap(string filePath, string? pathM var pathMap = (pathMapFrom, pathMapTo) switch { (null, null) => ImmutableArray>.Empty, - (string, string) => ImmutableArray.Create(KeyValuePairUtil.Create(pathMapFrom, pathMapTo)), + (string, string) => ImmutableArray.Create(KeyValuePair.Create(pathMapFrom, pathMapTo)), _ => throw new InvalidOperationException(), }; var emitOptions = EmitOptions.WithPdbFilePath(filePath); @@ -725,7 +725,7 @@ public void PathMapAdditionalFiles(string filePath, string? pathMapFrom, string? var pathMap = (pathMapFrom, pathMapTo) switch { (null, null) => ImmutableArray>.Empty, - (string, string) => ImmutableArray.Create(KeyValuePairUtil.Create(pathMapFrom, pathMapTo)), + (string, string) => ImmutableArray.Create(KeyValuePair.Create(pathMapFrom, pathMapTo)), _ => throw new InvalidOperationException(), }; diff --git a/src/Compilers/Extension/Roslyn.Compilers.Extension.csproj b/src/Compilers/Extension/Roslyn.Compilers.Extension.csproj index 9c84fa22c525f..09977d215bf22 100644 --- a/src/Compilers/Extension/Roslyn.Compilers.Extension.csproj +++ b/src/Compilers/Extension/Roslyn.Compilers.Extension.csproj @@ -14,6 +14,8 @@ true false true + true + - - - - - - + + + + + + diff --git a/src/Compilers/Core/CommandLine/BuildProtocol.cs b/src/Compilers/Shared/BuildProtocol.cs similarity index 99% rename from src/Compilers/Core/CommandLine/BuildProtocol.cs rename to src/Compilers/Shared/BuildProtocol.cs index e315beaf65a28..1bd920af986e0 100644 --- a/src/Compilers/Core/CommandLine/BuildProtocol.cs +++ b/src/Compilers/Shared/BuildProtocol.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable + using Roslyn.Utilities; using System; using System.Collections.Generic; diff --git a/src/Compilers/Shared/BuildServerConnection.cs b/src/Compilers/Shared/BuildServerConnection.cs index 675771e47e064..e3e61d1b46ffd 100644 --- a/src/Compilers/Shared/BuildServerConnection.cs +++ b/src/Compilers/Shared/BuildServerConnection.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Collections.Generic; using System.Diagnostics; @@ -63,7 +65,8 @@ internal static BuildRequest CreateBuildRequest( string workingDirectory, string? tempDirectory, string? keepAlive, - string? libDirectory) + string? libDirectory, + string? compilerHash = null) { Debug.Assert(workingDirectory is object); @@ -72,7 +75,7 @@ internal static BuildRequest CreateBuildRequest( arguments, workingDirectory: workingDirectory, tempDirectory: tempDirectory, - compilerHash: BuildProtocolConstants.GetCommitHash() ?? "", + compilerHash: compilerHash ?? BuildProtocolConstants.GetCommitHash() ?? "", requestId: requestId, keepAlive: keepAlive, libDirectory: libDirectory); @@ -178,12 +181,6 @@ internal static async Task RunServerBuildRequestAsync( { Debug.Assert(pipeName is object); - // early check for the build hash. If we can't find it something is wrong; no point even trying to go to the server - if (string.IsNullOrWhiteSpace(BuildProtocolConstants.GetCommitHash())) - { - return new IncorrectHashBuildResponse(); - } - using var pipe = await tryConnectToServerAsync(pipeName, timeoutOverride, logger, tryCreateServerFunc, cancellationToken).ConfigureAwait(false); if (pipe is null) { diff --git a/src/Compilers/Core/CommandLine/CompilerServerLogger.cs b/src/Compilers/Shared/CompilerServerLogger.cs similarity index 99% rename from src/Compilers/Core/CommandLine/CompilerServerLogger.cs rename to src/Compilers/Shared/CompilerServerLogger.cs index b0f2a0cb0df69..9f1a6a7f3f43d 100644 --- a/src/Compilers/Core/CommandLine/CompilerServerLogger.cs +++ b/src/Compilers/Shared/CompilerServerLogger.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable + using Roslyn.Utilities; using System; using System.Collections.Generic; diff --git a/src/Compilers/Core/CommandLine/ConsoleUtil.cs b/src/Compilers/Shared/ConsoleUtil.cs similarity index 100% rename from src/Compilers/Core/CommandLine/ConsoleUtil.cs rename to src/Compilers/Shared/ConsoleUtil.cs diff --git a/src/Compilers/Shared/NamedPipeUtil.cs b/src/Compilers/Shared/NamedPipeUtil.cs index 0a45e71b27ba1..50c2595610c31 100644 --- a/src/Compilers/Shared/NamedPipeUtil.cs +++ b/src/Compilers/Shared/NamedPipeUtil.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.IO; using System.IO.Pipes; diff --git a/src/Compilers/Core/CommandLine/NativeMethods.cs b/src/Compilers/Shared/NativeMethods.cs similarity index 99% rename from src/Compilers/Core/CommandLine/NativeMethods.cs rename to src/Compilers/Shared/NativeMethods.cs index c5008b95be2dc..647245ea26646 100644 --- a/src/Compilers/Core/CommandLine/NativeMethods.cs +++ b/src/Compilers/Shared/NativeMethods.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Runtime.InteropServices; using System.Runtime.Versioning; diff --git a/src/Compilers/Shared/RuntimeHostInfo.cs b/src/Compilers/Shared/RuntimeHostInfo.cs index 26d11e2d2837e..7ff9b16c7dfab 100644 --- a/src/Compilers/Shared/RuntimeHostInfo.cs +++ b/src/Compilers/Shared/RuntimeHostInfo.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; diff --git a/src/Compilers/Test/Core/CompilationVerifier.cs b/src/Compilers/Test/Core/CompilationVerifier.cs index 47d24f1c728ca..57de433b4023c 100644 --- a/src/Compilers/Test/Core/CompilationVerifier.cs +++ b/src/Compilers/Test/Core/CompilationVerifier.cs @@ -385,7 +385,7 @@ public void EmitAndVerify( output = output.Trim(); } - Assert.Equal(expectedOutput, output); + AssertEx.Equal(expectedOutput, output); Assert.Empty(errorOutput); } } diff --git a/src/Compilers/Test/Core/Diagnostics/DescriptorFactory.cs b/src/Compilers/Test/Core/Diagnostics/DescriptorFactory.cs index ceaa08ef2bebb..ce17c83fe616c 100644 --- a/src/Compilers/Test/Core/Diagnostics/DescriptorFactory.cs +++ b/src/Compilers/Test/Core/Diagnostics/DescriptorFactory.cs @@ -29,10 +29,9 @@ public static class DescriptorFactory /// A with specified . public static DiagnosticDescriptor CreateSimpleDescriptor(string id, params string[] additionalCustomTags) { - var customTags = additionalCustomTags.Concat(WellKnownDiagnosticTags.NotConfigurable).AsArray(); return new DiagnosticDescriptor(id, title: "", messageFormat: id, category: "", defaultSeverity: DiagnosticSeverity.Hidden, isEnabledByDefault: true, - customTags: customTags); + customTags: [.. additionalCustomTags, WellKnownDiagnosticTags.NotConfigurable]); } } } diff --git a/src/Compilers/Test/Core/Microsoft.CodeAnalysis.Test.Utilities.csproj b/src/Compilers/Test/Core/Microsoft.CodeAnalysis.Test.Utilities.csproj index 1cf072b4c5a7e..0aab6667e0f88 100644 --- a/src/Compilers/Test/Core/Microsoft.CodeAnalysis.Test.Utilities.csproj +++ b/src/Compilers/Test/Core/Microsoft.CodeAnalysis.Test.Utilities.csproj @@ -16,7 +16,6 @@ - diff --git a/src/Compilers/Test/Core/TestHelpers.cs b/src/Compilers/Test/Core/TestHelpers.cs index 204bae9fc1819..e221647a181fc 100644 --- a/src/Compilers/Test/Core/TestHelpers.cs +++ b/src/Compilers/Test/Core/TestHelpers.cs @@ -17,7 +17,6 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; -using KeyValuePair = Roslyn.Utilities.KeyValuePairUtil; namespace Roslyn.Test.Utilities { @@ -30,11 +29,11 @@ public static class TestHelpers public static ImmutableDictionary CreateImmutableDictionary( IEqualityComparer comparer, - params (K, V)[] entries) - => ImmutableDictionary.CreateRange(comparer, entries.Select(KeyValuePair.ToKeyValuePair)); + params (K key, V value)[] entries) + => ImmutableDictionary.CreateRange(comparer, entries.Select(t => KeyValuePair.Create(t.key, t.value))); - public static ImmutableDictionary CreateImmutableDictionary(params (K, V)[] entries) - => ImmutableDictionary.CreateRange(entries.Select(KeyValuePair.ToKeyValuePair)); + public static ImmutableDictionary CreateImmutableDictionary(params (K key, V value)[] entries) + => ImmutableDictionary.CreateRange(entries.Select(t => KeyValuePair.Create(t.key, t.value))); public static IEnumerable GetAllTypesWithStaticFieldsImplementingType(Assembly assembly, Type type) { diff --git a/src/Compilers/Test/Core/Traits/Traits.cs b/src/Compilers/Test/Core/Traits/Traits.cs index 8fa34d3fd1978..9be99ab4f2769 100644 --- a/src/Compilers/Test/Core/Traits/Traits.cs +++ b/src/Compilers/Test/Core/Traits/Traits.cs @@ -145,6 +145,7 @@ public static class Features public const string CodeActionsMoveType = "CodeActions.MoveType"; public const string CodeActionsNameTupleElement = "CodeActions.NameTupleElement"; public const string CodeActionsOrderModifiers = "CodeActions.OrderModifiers"; + public const string CodeActionsOrganizeImports = "CodeActions.OrganizeImports"; public const string CodeActionsPopulateSwitch = "CodeActions.PopulateSwitch"; public const string CodeActionsPullMemberUp = "CodeActions.PullMemberUp"; public const string CodeActionsQualifyMemberAccess = "CodeActions.QualifyMemberAccess"; diff --git a/src/Compilers/Test/Utilities/CSharp/CSharpTestBase.cs b/src/Compilers/Test/Utilities/CSharp/CSharpTestBase.cs index 59890f50a9f68..2496d73b57c0a 100644 --- a/src/Compilers/Test/Utilities/CSharp/CSharpTestBase.cs +++ b/src/Compilers/Test/Utilities/CSharp/CSharpTestBase.cs @@ -2914,11 +2914,11 @@ internal static string GetIdForErrorCode(ErrorCode code) internal static ImmutableDictionary ReportStructInitializationWarnings { get; } = ImmutableDictionary.CreateRange( new[] { - KeyValuePairUtil.Create(GetIdForErrorCode(ErrorCode.WRN_UseDefViolationPropertySupportedVersion), ReportDiagnostic.Warn), - KeyValuePairUtil.Create(GetIdForErrorCode(ErrorCode.WRN_UseDefViolationFieldSupportedVersion), ReportDiagnostic.Warn), - KeyValuePairUtil.Create(GetIdForErrorCode(ErrorCode.WRN_UseDefViolationThisSupportedVersion), ReportDiagnostic.Warn), - KeyValuePairUtil.Create(GetIdForErrorCode(ErrorCode.WRN_UnassignedThisAutoPropertySupportedVersion), ReportDiagnostic.Warn), - KeyValuePairUtil.Create(GetIdForErrorCode(ErrorCode.WRN_UnassignedThisSupportedVersion), ReportDiagnostic.Warn), + KeyValuePair.Create(GetIdForErrorCode(ErrorCode.WRN_UseDefViolationPropertySupportedVersion), ReportDiagnostic.Warn), + KeyValuePair.Create(GetIdForErrorCode(ErrorCode.WRN_UseDefViolationFieldSupportedVersion), ReportDiagnostic.Warn), + KeyValuePair.Create(GetIdForErrorCode(ErrorCode.WRN_UseDefViolationThisSupportedVersion), ReportDiagnostic.Warn), + KeyValuePair.Create(GetIdForErrorCode(ErrorCode.WRN_UnassignedThisAutoPropertySupportedVersion), ReportDiagnostic.Warn), + KeyValuePair.Create(GetIdForErrorCode(ErrorCode.WRN_UnassignedThisSupportedVersion), ReportDiagnostic.Warn), }); #endregion diff --git a/src/Compilers/Test/Utilities/VisualBasic/BasicTestSource.vb b/src/Compilers/Test/Utilities/VisualBasic/BasicTestSource.vb index 6fd897b5505f2..a12bf0f178713 100644 --- a/src/Compilers/Test/Utilities/VisualBasic/BasicTestSource.vb +++ b/src/Compilers/Test/Utilities/VisualBasic/BasicTestSource.vb @@ -2,10 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Xml.Linq Imports System.Text Imports Microsoft.CodeAnalysis.Text -Imports System.IO Public Structure BasicTestSource diff --git a/src/Compilers/Test/Utilities/VisualBasic/CompilationTestUtils.vb b/src/Compilers/Test/Utilities/VisualBasic/CompilationTestUtils.vb index 93f4e83be9b84..933dd783189c3 100644 --- a/src/Compilers/Test/Utilities/VisualBasic/CompilationTestUtils.vb +++ b/src/Compilers/Test/Utilities/VisualBasic/CompilationTestUtils.vb @@ -7,9 +7,8 @@ Imports System.IO Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports System.Text -Imports System.Xml.Linq Imports Basic.Reference.Assemblies -Imports Microsoft.CodeAnalysis.PooledObjects +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Roslyn.Test.Utilities diff --git a/src/Compilers/Test/Utilities/VisualBasic/Extensions.vb b/src/Compilers/Test/Utilities/VisualBasic/Extensions.vb index f8fb2e210426a..eb56f35ac507d 100644 --- a/src/Compilers/Test/Utilities/VisualBasic/Extensions.vb +++ b/src/Compilers/Test/Utilities/VisualBasic/Extensions.vb @@ -6,7 +6,6 @@ Imports System.Collections.Immutable Imports System.Reflection Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices -Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.Test.Utilities diff --git a/src/Compilers/Test/Utilities/VisualBasic/MetadataHelpers.vb b/src/Compilers/Test/Utilities/VisualBasic/MetadataHelpers.vb index 20ea2d0f921b8..5b4e0eb9bf650 100644 --- a/src/Compilers/Test/Utilities/VisualBasic/MetadataHelpers.vb +++ b/src/Compilers/Test/Utilities/VisualBasic/MetadataHelpers.vb @@ -4,7 +4,6 @@ Imports System.Collections.Immutable Imports System.Runtime.CompilerServices -Imports Microsoft.CodeAnalysis.Test.Utilities Friend Module MetadataTestHelpers diff --git a/src/Compilers/Test/Utilities/VisualBasic/MockVbi.vb b/src/Compilers/Test/Utilities/VisualBasic/MockVbi.vb index 64369063be1fe..200488d1ee45e 100644 --- a/src/Compilers/Test/Utilities/VisualBasic/MockVbi.vb +++ b/src/Compilers/Test/Utilities/VisualBasic/MockVbi.vb @@ -2,11 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.IO -Imports System.Reflection -Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.VisualBasic Friend Class MockVbi Inherits VisualBasicCompiler diff --git a/src/Compilers/Test/Utilities/VisualBasic/MockVisualBasicCompiler.vb b/src/Compilers/Test/Utilities/VisualBasic/MockVisualBasicCompiler.vb index 8a66be7909764..7115fff3c788d 100644 --- a/src/Compilers/Test/Utilities/VisualBasic/MockVisualBasicCompiler.vb +++ b/src/Compilers/Test/Utilities/VisualBasic/MockVisualBasicCompiler.vb @@ -4,8 +4,6 @@ Imports System.Collections.Immutable Imports System.IO -Imports System.Runtime.CompilerServices -Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Test.Utilities diff --git a/src/Compilers/Test/Utilities/VisualBasic/ParserTestUtilities.vb b/src/Compilers/Test/Utilities/VisualBasic/ParserTestUtilities.vb index 1858d6987c0d7..7644eb75e4100 100644 --- a/src/Compilers/Test/Utilities/VisualBasic/ParserTestUtilities.vb +++ b/src/Compilers/Test/Utilities/VisualBasic/ParserTestUtilities.vb @@ -2,19 +2,16 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Globalization +Imports System.Collections.Immutable Imports System.Runtime.CompilerServices Imports System.Text Imports System.Threading -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts Imports Roslyn.Test.Utilities Imports Xunit -Imports Microsoft.CodeAnalysis.Collections -Imports System.Collections.Immutable Friend Module ParserTestUtilities Friend ReadOnly Property PooledStringBuilderPool As ObjectPool(Of PooledStringBuilder) = PooledStringBuilder.CreatePool(64) diff --git a/src/Compilers/Test/Utilities/VisualBasic/SemanticModelTestBase.vb b/src/Compilers/Test/Utilities/VisualBasic/SemanticModelTestBase.vb index a12c44161eb39..055e6d63d8042 100644 --- a/src/Compilers/Test/Utilities/VisualBasic/SemanticModelTestBase.vb +++ b/src/Compilers/Test/Utilities/VisualBasic/SemanticModelTestBase.vb @@ -2,12 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.Immutable -Imports System.Xml.Linq -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Xunit Public MustInherit Class SemanticModelTestBase : Inherits BasicTestBase diff --git a/src/Compilers/Test/Utilities/VisualBasic/SyntaxTreeExtensions.vb b/src/Compilers/Test/Utilities/VisualBasic/SyntaxTreeExtensions.vb index c1e433fa0e854..f8219cc721ec4 100644 --- a/src/Compilers/Test/Utilities/VisualBasic/SyntaxTreeExtensions.vb +++ b/src/Compilers/Test/Utilities/VisualBasic/SyntaxTreeExtensions.vb @@ -2,14 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System -Imports System.Collections.Generic -Imports System.Linq -Imports System.Text Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Public Module SyntaxTreeExtensions diff --git a/src/Compilers/Test/Utilities/VisualBasic/TestOptions.vb b/src/Compilers/Test/Utilities/VisualBasic/TestOptions.vb index 875f9fd5029a2..9aa8f858eb4c9 100644 --- a/src/Compilers/Test/Utilities/VisualBasic/TestOptions.vb +++ b/src/Compilers/Test/Utilities/VisualBasic/TestOptions.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices -Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/Test/Utilities/VisualBasic/VBParser.vb b/src/Compilers/Test/Utilities/VisualBasic/VBParser.vb index e034b81a69acc..5b19dcc51cf9e 100644 --- a/src/Compilers/Test/Utilities/VisualBasic/VBParser.vb +++ b/src/Compilers/Test/Utilities/VisualBasic/VBParser.vb @@ -2,8 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Text Imports System.Reflection +Imports System.Text Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text diff --git a/src/Compilers/VisualBasic/Portable/Binding/Binder_Invocation.vb b/src/Compilers/VisualBasic/Portable/Binding/Binder_Invocation.vb index a1aa76da2ac0e..e5243c375c3be 100644 --- a/src/Compilers/VisualBasic/Portable/Binding/Binder_Invocation.vb +++ b/src/Compilers/VisualBasic/Portable/Binding/Binder_Invocation.vb @@ -1868,7 +1868,7 @@ ProduceBoundNode: callerInfoOpt:=callerInfoOpt, representCandidateInDiagnosticsOpt:=Nothing) - diagnosticPerSymbol.Add(KeyValuePairUtil.Create(candidates(i).Candidate.UnderlyingSymbol, candidateDiagnostics.ToReadOnlyAndFree())) + diagnosticPerSymbol.Add(KeyValuePair.Create(candidates(i).Candidate.UnderlyingSymbol, candidateDiagnostics.ToReadOnlyAndFree())) Next diff --git a/src/Compilers/VisualBasic/Portable/BoundTree/BoundMethodDefIndex.vb b/src/Compilers/VisualBasic/Portable/BoundTree/BoundMethodDefIndex.vb new file mode 100644 index 0000000000000..2e55a4a962d69 --- /dev/null +++ b/src/Compilers/VisualBasic/Portable/BoundTree/BoundMethodDefIndex.vb @@ -0,0 +1,17 @@ +' Licensed to the .NET Foundation under one or more agreements. +' The .NET Foundation licenses this file to you under the MIT license. +' See the LICENSE file in the project root for more information. + +Imports Microsoft.CodeAnalysis.Text +Imports Microsoft.CodeAnalysis.VisualBasic.Symbols +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax + +Namespace Microsoft.CodeAnalysis.VisualBasic + Partial Friend Class BoundMethodDefIndex +#If DEBUG Then + Private Sub Validate() + Debug.Assert(Method.IsDefinition) + End Sub +#End If + End Class +End Namespace diff --git a/src/Compilers/VisualBasic/Portable/BoundTree/BoundNodes.xml b/src/Compilers/VisualBasic/Portable/BoundTree/BoundNodes.xml index dab1d5a8c4fc7..643c25a97d87a 100644 --- a/src/Compilers/VisualBasic/Portable/BoundTree/BoundNodes.xml +++ b/src/Compilers/VisualBasic/Portable/BoundTree/BoundNodes.xml @@ -256,7 +256,7 @@ - + diff --git a/src/Compilers/VisualBasic/Portable/Compilation/SemanticModel.vb b/src/Compilers/VisualBasic/Portable/Compilation/SemanticModel.vb index 32e09ae72b7f2..5d37ffe97f793 100644 --- a/src/Compilers/VisualBasic/Portable/Compilation/SemanticModel.vb +++ b/src/Compilers/VisualBasic/Portable/Compilation/SemanticModel.vb @@ -981,7 +981,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic If useOfLocalBeforeDeclaration AndAlso Not type.IsErrorType() Then conversion = New Conversion(Conversions.ClassifyConversion(type, convertedType, CompoundUseSiteInfo(Of AssemblySymbol).Discarded)) Else - conversion = New Conversion(KeyValuePairUtil.Create(conversionNode.ConversionKind, + conversion = New Conversion(KeyValuePair.Create(conversionNode.ConversionKind, TryCast(conversionNode.ExpressionSymbol, MethodSymbol))) End If End If diff --git a/src/Compilers/VisualBasic/Portable/Generated/BoundNodes.xml.Generated.vb b/src/Compilers/VisualBasic/Portable/Generated/BoundNodes.xml.Generated.vb index 7438416a2b6a3..b44fee89ee78f 100644 --- a/src/Compilers/VisualBasic/Portable/Generated/BoundNodes.xml.Generated.vb +++ b/src/Compilers/VisualBasic/Portable/Generated/BoundNodes.xml.Generated.vb @@ -1118,6 +1118,11 @@ Namespace Microsoft.CodeAnalysis.VisualBasic Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)") Me._Method = method + + Validate() + End Sub + + Private Partial Sub Validate() End Sub Public Sub New(syntax As SyntaxNode, method As MethodSymbol, type As TypeSymbol) @@ -1127,6 +1132,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)") Me._Method = method + + Validate() End Sub diff --git a/src/Compilers/VisualBasic/Portable/Operations/VisualBasicOperationFactory_Methods.vb b/src/Compilers/VisualBasic/Portable/Operations/VisualBasicOperationFactory_Methods.vb index bb4d1b252584a..b44901eb0a28e 100644 --- a/src/Compilers/VisualBasic/Portable/Operations/VisualBasicOperationFactory_Methods.vb +++ b/src/Compilers/VisualBasic/Portable/Operations/VisualBasicOperationFactory_Methods.vb @@ -578,9 +578,9 @@ Namespace Microsoft.CodeAnalysis.Operations If conversionKind.HasFlag(VisualBasic.ConversionKind.UserDefined) AndAlso conversion.Operand.Kind = BoundKind.UserDefinedConversion Then method = DirectCast(conversion.Operand, BoundUserDefinedConversion).Call.Method End If - Return New Conversion(KeyValuePairUtil.Create(conversionKind, method)) + Return New Conversion(KeyValuePair.Create(conversionKind, method)) ElseIf expression.Kind = BoundKind.TryCast OrElse expression.Kind = BoundKind.DirectCast Then - Return New Conversion(KeyValuePairUtil.Create(Of ConversionKind, MethodSymbol)(DirectCast(expression, BoundConversionOrCast).ConversionKind, Nothing)) + Return New Conversion(KeyValuePair.Create(Of ConversionKind, MethodSymbol)(DirectCast(expression, BoundConversionOrCast).ConversionKind, Nothing)) End If Return New Conversion(Conversions.Identity) End Function diff --git a/src/Compilers/VisualBasic/Portable/Parser/Parser.vb b/src/Compilers/VisualBasic/Portable/Parser/Parser.vb index 2b7dc24d71d1f..7a2a53a2413a0 100644 --- a/src/Compilers/VisualBasic/Portable/Parser/Parser.vb +++ b/src/Compilers/VisualBasic/Portable/Parser/Parser.vb @@ -70,6 +70,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax End If End Sub + Friend ReadOnly Property Options As VisualBasicParseOptions + Get + Return _scanner.Options + End Get + End Property + Friend ReadOnly Property IsScript As Boolean Get Return _scanner.Options.Kind = SourceCodeKind.Script diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Source/CustomEventAccessorSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Source/CustomEventAccessorSymbol.vb index 8f5b8d69d01d6..203bbde20e416 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Source/CustomEventAccessorSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Source/CustomEventAccessorSymbol.vb @@ -4,6 +4,7 @@ Imports System.Collections.Immutable Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceComplexParameterSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceComplexParameterSymbol.vb index ac6b3a6095f6b..3f5fc06b97f53 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceComplexParameterSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceComplexParameterSymbol.vb @@ -4,6 +4,7 @@ Imports System.Collections.Immutable Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Binder Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceDelegateMethodSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceDelegateMethodSymbol.vb index 1b3792c0a2848..7b8ff62142ff0 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceDelegateMethodSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceDelegateMethodSymbol.vb @@ -5,6 +5,7 @@ Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceEnumConstantSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceEnumConstantSymbol.vb index 0bc926ebfe9d9..861bbf1d4cd27 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceEnumConstantSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceEnumConstantSymbol.vb @@ -3,6 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceEventSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceEventSymbol.vb index 6b24aaf8b729a..3ac3dd0f2e21a 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceEventSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceEventSymbol.vb @@ -6,6 +6,7 @@ Imports System.Collections.Immutable Imports System.Globalization Imports System.Runtime.InteropServices Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Emit @@ -367,7 +368,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Dim method As New CustomEventAccessorSymbol( Me._containingType, Me, - binder.GetAccessorName(Me.Name, flags.ToMethodKind(), isWinMd:=False), + Binder.GetAccessorName(Me.Name, flags.ToMethodKind(), isWinMd:=False), flags, binder.GetSyntaxReference(syntax), location) diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceFieldSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceFieldSymbol.vb index d7b8ab2e9a071..32d6fcf60ca26 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceFieldSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceFieldSymbol.vb @@ -7,6 +7,7 @@ Imports System.Collections.Immutable Imports System.Globalization Imports System.Runtime.InteropServices Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Emit diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMemberFieldSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMemberFieldSymbol.vb index 1e034909add1b..8b9df817adda8 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMemberFieldSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMemberFieldSymbol.vb @@ -6,6 +6,7 @@ Imports System.Collections.Generic Imports System.Globalization Imports System.Runtime.InteropServices Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMemberMethodSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMemberMethodSymbol.vb index 34d12ee3d5df0..3fdba7d93ae77 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMemberMethodSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMemberMethodSymbol.vb @@ -5,6 +5,7 @@ Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Emit diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceModuleSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceModuleSymbol.vb index e6c5dc802a024..459606ef0e3ee 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceModuleSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceModuleSymbol.vb @@ -7,6 +7,7 @@ Imports System.Collections.Immutable Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.ErrorReporting Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourcePropertyAccessorSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourcePropertyAccessorSymbol.vb index 8a25ddd38b2a2..411a8df8d7eed 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourcePropertyAccessorSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourcePropertyAccessorSymbol.vb @@ -4,6 +4,7 @@ Imports System.Collections.Immutable Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourcePropertySymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourcePropertySymbol.vb index 163bad7cb3235..a955889e71e65 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourcePropertySymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourcePropertySymbol.vb @@ -9,6 +9,7 @@ Imports System.Diagnostics Imports System.Globalization Imports System.Runtime.InteropServices Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Emit diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Symbol_Attributes.vb b/src/Compilers/VisualBasic/Portable/Symbols/Symbol_Attributes.vb index afd1c8e664d0b..0e8ce54e2f283 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Symbol_Attributes.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Symbol_Attributes.vb @@ -6,8 +6,9 @@ Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading -Imports Microsoft.CodeAnalysis.VisualBasic.Emit +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects +Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind diff --git a/src/Compilers/VisualBasic/Portable/Syntax/SyntaxNodeFactories.vb b/src/Compilers/VisualBasic/Portable/Syntax/SyntaxNodeFactories.vb index 78a47f4eb237c..87034af48384e 100644 --- a/src/Compilers/VisualBasic/Portable/Syntax/SyntaxNodeFactories.vb +++ b/src/Compilers/VisualBasic/Portable/Syntax/SyntaxNodeFactories.vb @@ -7,15 +7,15 @@ ' code-generated into SyntaxNodes.vb, but some are easier to hand-write. '----------------------------------------------------------------------------------------------------------- -Imports System.Threading +Imports System.Collections.Immutable +Imports System.ComponentModel Imports System.Text +Imports System.Threading +Imports Microsoft.CodeAnalysis.Syntax Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts Imports InternalSyntax = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax -Imports Microsoft.CodeAnalysis.Syntax -Imports System.Collections.Immutable -Imports System.ComponentModel Namespace Microsoft.CodeAnalysis.VisualBasic @@ -186,7 +186,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic disallowGenericArgumentsOnLastQualifiedName:=False, allowEmptyGenericArguments:=True, allowedEmptyGenericArguments:=True) - Return DirectCast(If(consumeFullText, p.ConsumeUnexpectedTokens(node), node).CreateRed(Nothing, 0), NameSyntax) + Return CreateRed(Of NameSyntax)(If(consumeFullText, p.ConsumeUnexpectedTokens(node), node), p.Options) End Using End Function @@ -196,10 +196,14 @@ Namespace Microsoft.CodeAnalysis.VisualBasic ''' The input string ''' The starting offset in the string Public Shared Function ParseTypeName(text As String, Optional offset As Integer = 0, Optional options As ParseOptions = Nothing, Optional consumeFullText As Boolean = True) As TypeSyntax - Using p = New InternalSyntax.Parser(MakeSourceText(text, offset), If(DirectCast(options, VisualBasicParseOptions), VisualBasicParseOptions.Default)) + Dim vbOptions As VisualBasicParseOptions = DirectCast(options, VisualBasicParseOptions) + Using p = New InternalSyntax.Parser(MakeSourceText(text, offset), If(vbOptions, VisualBasicParseOptions.Default)) p.GetNextToken() Dim node = p.ParseGeneralType() - Return DirectCast(If(consumeFullText, p.ConsumeUnexpectedTokens(node), node).CreateRed(Nothing, 0), TypeSyntax) + If consumeFullText Then + node = p.ConsumeUnexpectedTokens(node) + End If + Return CreateRed(Of TypeSyntax)(node, p.Options) End Using End Function @@ -223,7 +227,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic Using p = New InternalSyntax.Parser(MakeSourceText(text, offset), VisualBasicParseOptions.Default) p.GetNextToken() Dim node = p.ParseExpression() - Return DirectCast(If(consumeFullText, p.ConsumeUnexpectedTokens(node), node).CreateRed(Nothing, 0), ExpressionSyntax) + Return CreateRed(Of ExpressionSyntax)(If(consumeFullText, p.ConsumeUnexpectedTokens(node), node), p.Options) End Using End Function @@ -235,7 +239,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic Public Shared Function ParseExecutableStatement(text As String, Optional offset As Integer = 0, Optional consumeFullText As Boolean = True) As StatementSyntax Using p = New InternalSyntax.Parser(MakeSourceText(text, offset), VisualBasicParseOptions.Default) Dim node = p.ParseExecutableStatement() - Return DirectCast(If(consumeFullText, p.ConsumeUnexpectedTokens(node), node).CreateRed(Nothing, 0), StatementSyntax) + Return CreateRed(Of StatementSyntax)(If(consumeFullText, p.ConsumeUnexpectedTokens(node), node), p.Options) End Using End Function @@ -246,7 +250,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic ''' The starting offset in the string Public Shared Function ParseCompilationUnit(text As String, Optional offset As Integer = 0, Optional options As VisualBasicParseOptions = Nothing) As CompilationUnitSyntax Using p = New InternalSyntax.Parser(MakeSourceText(text, offset), If(options, VisualBasicParseOptions.Default)) - Return DirectCast(p.ParseCompilationUnit().CreateRed(Nothing, 0), CompilationUnitSyntax) + Dim node = p.ParseCompilationUnit() + Return CreateRed(Of CompilationUnitSyntax)(node, p.Options) End Using End Function @@ -259,7 +264,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic Using p = New InternalSyntax.Parser(MakeSourceText(text, offset), VisualBasicParseOptions.Default) p.GetNextToken() Dim node = p.ParseParameterList() - Return DirectCast(If(consumeFullText, p.ConsumeUnexpectedTokens(node), node).CreateRed(Nothing, 0), ParameterListSyntax) + Return CreateRed(Of ParameterListSyntax)(If(consumeFullText, p.ConsumeUnexpectedTokens(node), node), p.Options) End Using End Function @@ -272,7 +277,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic Using p = New InternalSyntax.Parser(MakeSourceText(text, offset), VisualBasicParseOptions.Default) p.GetNextToken() Dim node = p.ParseParenthesizedArguments() - Return DirectCast(If(consumeFullText, p.ConsumeUnexpectedTokens(node), node).CreateRed(Nothing, 0), ArgumentListSyntax) + Return CreateRed(Of ArgumentListSyntax)(If(consumeFullText, p.ConsumeUnexpectedTokens(node), node), p.Options) End Using End Function @@ -298,15 +303,24 @@ Namespace Microsoft.CodeAnalysis.VisualBasic Dim xmlName = InternalSyntax.SyntaxFactory.XmlName( Nothing, InternalSyntax.SyntaxFactory.XmlNameToken(parentElementName, SyntaxKind.XmlNameToken, Nothing, Nothing)) - Return DirectCast( - parser.ParseXmlAttribute( + Dim xmlAttribute = parser.ParseXmlAttribute( requireLeadingWhitespace:=False, AllowNameAsExpression:=False, - xmlElementName:=xmlName).CreateRed(Nothing, 0), BaseXmlAttributeSyntax) + xmlElementName:=xmlName) + Return CreateRed(Of BaseXmlAttributeSyntax)(xmlAttribute, scanner.Options) End Using End Using End Function + Private Shared Function CreateRed(Of TSyntax As VisualBasicSyntaxNode)(green As InternalSyntax.VisualBasicSyntaxNode, options As VisualBasicParseOptions) As TSyntax + Dim red = DirectCast(green.CreateRed(), TSyntax) + Debug.Assert(red._syntaxTree Is Nothing) +#Disable Warning RS0030 ' Do not use banned APIs (CreateWithoutClone is intended to be used from this call site) + red._syntaxTree = VisualBasicSyntaxTree.CreateWithoutClone(red, options) +#Enable Warning RS0030 + Return red + End Function + #End Region #Region "TokenFactories" diff --git a/src/Compilers/VisualBasic/Portable/Syntax/VisualBasicSyntaxNode.vb b/src/Compilers/VisualBasic/Portable/Syntax/VisualBasicSyntaxNode.vb index ae5c84381bf04..3d8e5229b22de 100644 --- a/src/Compilers/VisualBasic/Portable/Syntax/VisualBasicSyntaxNode.vb +++ b/src/Compilers/VisualBasic/Portable/Syntax/VisualBasicSyntaxNode.vb @@ -2,12 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.Immutable Imports System.Collections.ObjectModel -Imports System.ComponentModel -Imports System.Reflection Imports System.Threading -Imports Microsoft.CodeAnalysis.ErrorReporting Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols @@ -70,8 +66,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic If tree Is Nothing Then Debug.Assert(rootCandidate IsNot Nothing) -#Disable Warning RS0030 ' Do not use banned APIs (CreateWithoutClone is intended to be used from this call site only) - tree = VisualBasicSyntaxTree.CreateWithoutClone(DirectCast(rootCandidate, VisualBasicSyntaxNode)) +#Disable Warning RS0030 ' Do not use banned APIs (CreateWithoutClone is intended to be used from this call site) + tree = VisualBasicSyntaxTree.CreateWithoutClone(DirectCast(rootCandidate, VisualBasicSyntaxNode), VisualBasicParseOptions.Default) #Enable Warning RS0030 End If diff --git a/src/Compilers/VisualBasic/Portable/Syntax/VisualBasicSyntaxTree.vb b/src/Compilers/VisualBasic/Portable/Syntax/VisualBasicSyntaxTree.vb index 04ed895f802ff..2f1d0ef1c6f64 100644 --- a/src/Compilers/VisualBasic/Portable/Syntax/VisualBasicSyntaxTree.vb +++ b/src/Compilers/VisualBasic/Portable/Syntax/VisualBasicSyntaxTree.vb @@ -210,10 +210,10 @@ Namespace Microsoft.CodeAnalysis.VisualBasic ''' Internal helper for class to create a new syntax tree rooted at the given root node. ''' This method does not create a clone of the given root, but instead preserves its reference identity. ''' - ''' NOTE: This method is only intended to be used from property. + ''' NOTE: This method is only intended to be used from property and SyntaxFactory.Parse* methods. ''' NOTE: Do not use this method elsewhere, instead use method for creating a syntax tree. ''' - Friend Shared Function CreateWithoutClone(root As VisualBasicSyntaxNode) As SyntaxTree + Friend Shared Function CreateWithoutClone(root As VisualBasicSyntaxNode, options As VisualBasicParseOptions) As SyntaxTree Debug.Assert(root IsNot Nothing) Return New ParsedSyntaxTree( @@ -221,7 +221,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic path:="", encodingOpt:=Nothing, checksumAlgorithm:=SourceHashAlgorithm.Sha1, - options:=VisualBasicParseOptions.Default, + options:=options, syntaxRoot:=root, isMyTemplate:=False, diagnosticOptions:=Nothing, diff --git a/src/Compilers/VisualBasic/Portable/VisualBasicParseOptions.vb b/src/Compilers/VisualBasic/Portable/VisualBasicParseOptions.vb index c49ae511813c0..7fc561ed23ba1 100644 --- a/src/Compilers/VisualBasic/Portable/VisualBasicParseOptions.vb +++ b/src/Compilers/VisualBasic/Portable/VisualBasicParseOptions.vb @@ -78,7 +78,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic Private Shared ReadOnly Property DefaultPreprocessorSymbols As ImmutableArray(Of KeyValuePair(Of String, Object)) Get If s_defaultPreprocessorSymbols.IsDefaultOrEmpty Then - s_defaultPreprocessorSymbols = ImmutableArray.Create(KeyValuePairUtil.Create("_MYTYPE", CObj("Empty"))) + s_defaultPreprocessorSymbols = ImmutableArray.Create(KeyValuePair.Create("_MYTYPE", CObj("Empty"))) End If Return s_defaultPreprocessorSymbols diff --git a/src/Compilers/VisualBasic/Test/CommandLine/CommandLineArgumentsTests.vb b/src/Compilers/VisualBasic/Test/CommandLine/CommandLineArgumentsTests.vb index 9d606373eeff6..42b98d5eec05b 100644 --- a/src/Compilers/VisualBasic/Test/CommandLine/CommandLineArgumentsTests.vb +++ b/src/Compilers/VisualBasic/Test/CommandLine/CommandLineArgumentsTests.vb @@ -3,6 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Imports Xunit diff --git a/src/Compilers/VisualBasic/Test/CommandLine/CommandLineBreakingChanges.vb b/src/Compilers/VisualBasic/Test/CommandLine/CommandLineBreakingChanges.vb index fbd1f78da018f..5d8b6dac69c31 100644 --- a/src/Compilers/VisualBasic/Test/CommandLine/CommandLineBreakingChanges.vb +++ b/src/Compilers/VisualBasic/Test/CommandLine/CommandLineBreakingChanges.vb @@ -3,8 +3,9 @@ ' See the LICENSE file in the project root for more information. Imports System.Reflection -Imports Roslyn.Test.Utilities.SharedResourceHelpers +Imports Microsoft.CodeAnalysis.Collections Imports Roslyn.Test.Utilities +Imports Roslyn.Test.Utilities.SharedResourceHelpers Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests diff --git a/src/Compilers/VisualBasic/Test/CommandLine/CommandLineTests.vb b/src/Compilers/VisualBasic/Test/CommandLine/CommandLineTests.vb index b2cc251b377d1..0163745a8053b 100644 --- a/src/Compilers/VisualBasic/Test/CommandLine/CommandLineTests.vb +++ b/src/Compilers/VisualBasic/Test/CommandLine/CommandLineTests.vb @@ -15,7 +15,9 @@ Imports System.Security.Cryptography Imports System.Text Imports System.Text.RegularExpressions Imports System.Threading +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Emit @@ -29,7 +31,6 @@ Imports Roslyn.Test.Utilities.SharedResourceHelpers Imports Roslyn.Test.Utilities.TestGenerators Imports Roslyn.Utilities Imports TestResources.Analyzers -Imports Basic.Reference.Assemblies Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests @@ -3445,16 +3446,16 @@ print Goodbye, World" parsedArgs = DefaultParse({"/pathmap:K1=V1", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() - Assert.Equal(KeyValuePairUtil.Create("K1" & s, "V1" & s), parsedArgs.PathMap(0)) + Assert.Equal(KeyValuePair.Create("K1" & s, "V1" & s), parsedArgs.PathMap(0)) parsedArgs = DefaultParse({$"/pathmap:abc{s}=/", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() - Assert.Equal(KeyValuePairUtil.Create("abc" & s, "/"), parsedArgs.PathMap(0)) + Assert.Equal(KeyValuePair.Create("abc" & s, "/"), parsedArgs.PathMap(0)) parsedArgs = DefaultParse({"/pathmap:K1=V1,K2=V2", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() - Assert.Equal(KeyValuePairUtil.Create("K1" & s, "V1" & s), parsedArgs.PathMap(0)) - Assert.Equal(KeyValuePairUtil.Create("K2" & s, "V2" & s), parsedArgs.PathMap(1)) + Assert.Equal(KeyValuePair.Create("K1" & s, "V1" & s), parsedArgs.PathMap(0)) + Assert.Equal(KeyValuePair.Create("K2" & s, "V2" & s), parsedArgs.PathMap(1)) parsedArgs = DefaultParse({"/pathmap:,", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() @@ -3487,28 +3488,28 @@ print Goodbye, World" parsedArgs = DefaultParse({"/pathmap:""supporting spaces=is hard""", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() - Assert.Equal(KeyValuePairUtil.Create("supporting spaces" & s, "is hard" & s), parsedArgs.PathMap(0)) + Assert.Equal(KeyValuePair.Create("supporting spaces" & s, "is hard" & s), parsedArgs.PathMap(0)) parsedArgs = DefaultParse({"/pathmap:""K 1=V 1"",""K 2=V 2""", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() - Assert.Equal(KeyValuePairUtil.Create("K 1" & s, "V 1" & s), parsedArgs.PathMap(0)) - Assert.Equal(KeyValuePairUtil.Create("K 2" & s, "V 2" & s), parsedArgs.PathMap(1)) + Assert.Equal(KeyValuePair.Create("K 1" & s, "V 1" & s), parsedArgs.PathMap(0)) + Assert.Equal(KeyValuePair.Create("K 2" & s, "V 2" & s), parsedArgs.PathMap(1)) parsedArgs = DefaultParse({"/pathmap:""K 1""=""V 1"",""K 2""=""V 2""", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() - Assert.Equal(KeyValuePairUtil.Create("K 1" & s, "V 1" & s), parsedArgs.PathMap(0)) - Assert.Equal(KeyValuePairUtil.Create("K 2" & s, "V 2" & s), parsedArgs.PathMap(1)) + Assert.Equal(KeyValuePair.Create("K 1" & s, "V 1" & s), parsedArgs.PathMap(0)) + Assert.Equal(KeyValuePair.Create("K 2" & s, "V 2" & s), parsedArgs.PathMap(1)) parsedArgs = DefaultParse({"/pathmap:""a ==,,b""=""1,,== 2"",""x ==,,y""=""3 4"",", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() - Assert.Equal(KeyValuePairUtil.Create("a =,b" & s, "1,= 2" & s), parsedArgs.PathMap(0)) - Assert.Equal(KeyValuePairUtil.Create("x =,y" & s, "3 4" & s), parsedArgs.PathMap(1)) + Assert.Equal(KeyValuePair.Create("a =,b" & s, "1,= 2" & s), parsedArgs.PathMap(0)) + Assert.Equal(KeyValuePair.Create("x =,y" & s, "3 4" & s), parsedArgs.PathMap(1)) parsedArgs = DefaultParse({"/pathmap:C:\temp\=/_1/,C:\temp\a\=/_2/,C:\temp\a\b\=/_3/", "a.cs", "a\b.cs", "a\b\c.cs"}, _baseDirectory) parsedArgs.Errors.Verify() - Assert.Equal(KeyValuePairUtil.Create("C:\temp\a\b\", "/_3/"), parsedArgs.PathMap(0)) - Assert.Equal(KeyValuePairUtil.Create("C:\temp\a\", "/_2/"), parsedArgs.PathMap(1)) - Assert.Equal(KeyValuePairUtil.Create("C:\temp\", "/_1/"), parsedArgs.PathMap(2)) + Assert.Equal(KeyValuePair.Create("C:\temp\a\b\", "/_3/"), parsedArgs.PathMap(0)) + Assert.Equal(KeyValuePair.Create("C:\temp\a\", "/_2/"), parsedArgs.PathMap(1)) + Assert.Equal(KeyValuePair.Create("C:\temp\", "/_1/"), parsedArgs.PathMap(2)) End Sub ' PathMapKeepsCrossPlatformRoot and PathMapInconsistentSlashes should be in an diff --git a/src/Compilers/VisualBasic/Test/CommandLine/SarifErrorLoggerTests.vb b/src/Compilers/VisualBasic/Test/CommandLine/SarifErrorLoggerTests.vb index 151d7ff2cc932..6c0f5ce8d92c1 100644 --- a/src/Compilers/VisualBasic/Test/CommandLine/SarifErrorLoggerTests.vb +++ b/src/Compilers/VisualBasic/Test/CommandLine/SarifErrorLoggerTests.vb @@ -4,11 +4,12 @@ Imports System.Globalization Imports System.IO +Imports Microsoft.CodeAnalysis.Collections +Imports Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests -Imports Xunit -Imports Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers Imports Roslyn.Test.Utilities.SharedResourceHelpers +Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/AssemblyAttributes.vb b/src/Compilers/VisualBasic/Test/Emit/AssemblyAttributes.vb deleted file mode 100644 index 02f5a0aabbbfb..0000000000000 --- a/src/Compilers/VisualBasic/Test/Emit/AssemblyAttributes.vb +++ /dev/null @@ -1,6 +0,0 @@ -' Licensed to the .NET Foundation under one or more agreements. -' The .NET Foundation licenses this file to you under the MIT license. -' See the LICENSE file in the project root for more information. - -Imports Xunit - diff --git a/src/Compilers/VisualBasic/Test/Emit/Attributes/AssemblyAttributes.vb b/src/Compilers/VisualBasic/Test/Emit/Attributes/AssemblyAttributes.vb index e1ad88031f7e5..6ffc15af9cd97 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Attributes/AssemblyAttributes.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Attributes/AssemblyAttributes.vb @@ -5,10 +5,8 @@ Imports System.Collections.Immutable Imports System.IO Imports System.Reflection -Imports System.Reflection.Emit Imports System.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 -Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Emit diff --git a/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests.vb b/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests.vb index 0b6f776f7b276..a8bb9bd64473f 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests.vb @@ -5,7 +5,6 @@ Imports System.Collections.Immutable Imports System.IO Imports System.Reflection -Imports System.Resources Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_Conditional.vb b/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_Conditional.vb index d288ac87f0101..a08928a896e0f 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_Conditional.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_Conditional.vb @@ -3,22 +3,11 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.Globalization -Imports System.IO Imports System.Reflection -Imports System.Runtime.CompilerServices -Imports System.Runtime.InteropServices -Imports System.Text -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class AttributeTests_Conditional diff --git a/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_Experimental.vb b/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_Experimental.vb index af0f0b616f251..d4c88480252ea 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_Experimental.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_Experimental.vb @@ -2,10 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Roslyn.Test.Utilities -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_MarshalAs.vb b/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_MarshalAs.vb index a8ea1152b1a6e..a776880a1246d 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_MarshalAs.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_MarshalAs.vb @@ -2,17 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System -Imports System.Collections.Generic Imports System.Runtime.InteropServices Imports System.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Roslyn.Test.Utilities -Imports Roslyn.Utilities -Imports Xunit -Imports TypeKind = Microsoft.CodeAnalysis.TypeKind +Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_ObsoleteAttribute.vb b/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_ObsoleteAttribute.vb index 08b0e544245c3..36d5aa7b3f1dc 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_ObsoleteAttribute.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_ObsoleteAttribute.vb @@ -2,10 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities -Imports Xunit -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_Synthesized.vb b/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_Synthesized.vb index 8486312789ba7..16209963499a7 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_Synthesized.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_Synthesized.vb @@ -3,8 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.IO -Imports System.Linq Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_Tuples.vb b/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_Tuples.vb index 05a55db004fc0..5afb195762443 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_Tuples.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_Tuples.vb @@ -5,13 +5,10 @@ Imports System.Collections.Immutable Imports System.Reflection Imports System.Reflection.Metadata -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_WellKnownAttributes.vb b/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_WellKnownAttributes.vb index aef030c9b44ca..d170494955eae 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_WellKnownAttributes.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_WellKnownAttributes.vb @@ -8,13 +8,13 @@ Imports System.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports System.Runtime.InteropServices Imports System.Text +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies #Disable Warning SYSLIB0050 ' 'TypeAttributes.Serializable' is obsolete diff --git a/src/Compilers/VisualBasic/Test/Emit/Attributes/EmitTestStrongNameProvider.vb b/src/Compilers/VisualBasic/Test/Emit/Attributes/EmitTestStrongNameProvider.vb index 3cbcc27ad8cdd..72117f0033bcd 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Attributes/EmitTestStrongNameProvider.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Attributes/EmitTestStrongNameProvider.vb @@ -3,15 +3,11 @@ ' See the LICENSE file in the project root for more information. Imports System.IO -Imports System.Reflection.Metadata -Imports System.Security.Cryptography -Imports Microsoft.Cci Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities -Imports Roslyn.Test.Utilities.SigningTestHelpers Partial Public Class InternalsVisibleToAndStrongNameTests Inherits BasicTestBase diff --git a/src/Compilers/VisualBasic/Test/Emit/Attributes/InternalsVisibleToAndStrongNameTests.vb b/src/Compilers/VisualBasic/Test/Emit/Attributes/InternalsVisibleToAndStrongNameTests.vb index 4d90278dfd7f4..19fb45d41c66d 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Attributes/InternalsVisibleToAndStrongNameTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Attributes/InternalsVisibleToAndStrongNameTests.vb @@ -2,12 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.IO Imports System.Reflection.Metadata Imports System.Reflection.PortableExecutable -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Emit diff --git a/src/Compilers/VisualBasic/Test/Emit/BreakingChanges.vb b/src/Compilers/VisualBasic/Test/Emit/BreakingChanges.vb index f3d818f6f18cd..80c58367e7fc9 100644 --- a/src/Compilers/VisualBasic/Test/Emit/BreakingChanges.vb +++ b/src/Compilers/VisualBasic/Test/Emit/BreakingChanges.vb @@ -2,11 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/AnonymousTypesCodeGenTests.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/AnonymousTypesCodeGenTests.vb index fbaef717764cf..9f9f42d360f8c 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/AnonymousTypesCodeGenTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/AnonymousTypesCodeGenTests.vb @@ -3,12 +3,8 @@ ' See the LICENSE file in the project root for more information. Imports System.IO -Imports System.Threading.Tasks -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Emit -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenAsyncTests.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenAsyncTests.vb index dcd709905f0e6..e4f41972b79c2 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenAsyncTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenAsyncTests.vb @@ -4,13 +4,13 @@ Imports System.IO Imports System.Text.RegularExpressions +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenCollectionInitializer.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenCollectionInitializer.vb index ab636d99e0a70..1914ebf588d1f 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenCollectionInitializer.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenCollectionInitializer.vb @@ -2,10 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenConstLocal.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenConstLocal.vb index a4d93b28c1eb3..c7afb66829065 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenConstLocal.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenConstLocal.vb @@ -3,12 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenCtorInitializers.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenCtorInitializers.vb index 27f9e2fe18625..bb577f86c7adf 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenCtorInitializers.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenCtorInitializers.vb @@ -2,10 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenForeach.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenForeach.vb index 235e18baa007a..088a1e40c2787 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenForeach.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenForeach.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenGetTypeOperator.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenGetTypeOperator.vb index 0a40f2c623024..63d1148461026 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenGetTypeOperator.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenGetTypeOperator.vb @@ -2,13 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenIfOperator.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenIfOperator.vb index f36aaad845d07..31ddbaa491305 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenIfOperator.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenIfOperator.vb @@ -2,13 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenInterfaceImplementation.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenInterfaceImplementation.vb index d93ac9dca5cde..0e476e73b578e 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenInterfaceImplementation.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenInterfaceImplementation.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenMultiDimensionalArray.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenMultiDimensionalArray.vb index ad886c9af5b7b..23b6f5ddf127c 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenMultiDimensionalArray.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenMultiDimensionalArray.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenNullable.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenNullable.vb index 3a03b3ead8296..38ee2ec014f33 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenNullable.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenNullable.vb @@ -2,15 +2,12 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit -Imports System.Collections.Immutable Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenObjectInitializer.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenObjectInitializer.vb index e617955e0f78e..d43940644a166 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenObjectInitializer.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenObjectInitializer.vb @@ -2,11 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit - Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenObjectInitializer Inherits BasicTestBase diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenOverridingAndHiding.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenOverridingAndHiding.vb index 7e9b61bd64903..7e8a3261345d6 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenOverridingAndHiding.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenOverridingAndHiding.vb @@ -3,12 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenSingleLineIf.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenSingleLineIf.vb index c595940ba613a..2809c725d4a42 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenSingleLineIf.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenSingleLineIf.vb @@ -2,9 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit -Imports Roslyn.Test.Utilities - Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenSingleLineIf diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenStaticLocals.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenStaticLocals.vb index 9e802b0b9e409..0b5ffcc37891d 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenStaticLocals.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenStaticLocals.vb @@ -2,14 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenStopOrEnd.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenStopOrEnd.vb index 31c86f820874e..6f4233781b7ac 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenStopOrEnd.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenStopOrEnd.vb @@ -2,13 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenStringConcat.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenStringConcat.vb index ba9efa2c93845..4441219a248bb 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenStringConcat.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenStringConcat.vb @@ -2,13 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenSyncLock.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenSyncLock.vb index 9661abc6ff75b..e8aa5a26e73b7 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenSyncLock.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenSyncLock.vb @@ -2,12 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit -Imports Roslyn.Test.Utilities Imports Basic.Reference.Assemblies +Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenSyncLock diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenTests.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenTests.vb index 5283e27fcd974..761d40ba97514 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenTests.vb @@ -4,12 +4,12 @@ Imports System.Collections.Immutable Imports System.Reflection +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenTuples.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenTuples.vb index 3a01a511788d1..77dc53ddfbcd4 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenTuples.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenTuples.vb @@ -5,6 +5,7 @@ Imports System.Collections.Immutable Imports System.Text Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic @@ -12,7 +13,6 @@ Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenUsingStatement.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenUsingStatement.vb index aa2ade61f3711..b29c07414fa37 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenUsingStatement.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenUsingStatement.vb @@ -2,10 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenVBCore.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenVBCore.vb index 9af925d90f3c9..d2afc7a964ed6 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenVBCore.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenVBCore.vb @@ -5,7 +5,6 @@ Imports System.IO Imports System.Text Imports System.Text.RegularExpressions -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenVbRuntime.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenVbRuntime.vb index 11ff16df990e9..fb700432b4ec9 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenVbRuntime.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenVbRuntime.vb @@ -2,15 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit -Imports Roslyn.Test.Utilities - Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenVbRuntime Inherits BasicTestBase diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenWinMdDelegates.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenWinMdDelegates.vb index d1e26c621e03a..a62725ce18e81 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenWinMdDelegates.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenWinMdDelegates.vb @@ -6,8 +6,6 @@ Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities -Imports System.Xml.Linq -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenWinMdDelegates diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenWinMdEvents.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenWinMdEvents.vb index 03e8a3f758ce1..b16b12c42b3f9 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenWinMdEvents.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenWinMdEvents.vb @@ -2,10 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Roslyn.Test.Utilities Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic +Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenWinMdEvents diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenWithEvents.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenWithEvents.vb index d72ff6403a90a..3eed68c69a714 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenWithEvents.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenWithEvents.vb @@ -10,7 +10,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenWithEvents Inherits BasicTestBase - + Public Sub SimpleWithEventsTest() Dim compilation1 = CompileAndVerify( @@ -400,7 +400,7 @@ handled1 End Sub - + Public Sub SimpleSharedWithEvents() Dim compilation1 = CompileAndVerify( @@ -2003,7 +2003,7 @@ End Class CompileAndVerify(source) End Sub - + Public Sub MultipleInitializationsWithAsNew_01() Dim source = @@ -2067,7 +2067,7 @@ False ]]>) End Sub - + Public Sub MultipleInitializationsWithAsNew_02() Dim source = diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/WinRTCollectionTests.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/WinRTCollectionTests.vb index 67aa5805fa5a3..ee92fc0fc7459 100644 --- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/WinRTCollectionTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/WinRTCollectionTests.vb @@ -2,10 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.CodeGen Public Class WinRTCollectionTests diff --git a/src/Compilers/VisualBasic/Test/Emit/Emit/DeterministicTests.vb b/src/Compilers/VisualBasic/Test/Emit/Emit/DeterministicTests.vb index 38d01e41d8290..03994d50224b6 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Emit/DeterministicTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Emit/DeterministicTests.vb @@ -2,14 +2,12 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System -Imports System.IO -Imports System.Collections.Generic Imports System.Collections.Immutable +Imports System.IO Imports System.Threading Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Roslyn.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols +Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit diff --git a/src/Compilers/VisualBasic/Test/Emit/Emit/DynamicAnalysis/DynamicAnalysisResourceTests.vb b/src/Compilers/VisualBasic/Test/Emit/Emit/DynamicAnalysis/DynamicAnalysisResourceTests.vb index 6fe225ba6394e..de38d1b725267 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Emit/DynamicAnalysis/DynamicAnalysisResourceTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Emit/DynamicAnalysis/DynamicAnalysisResourceTests.vb @@ -4,7 +4,6 @@ Imports System.Collections.Immutable Imports System.Reflection.PortableExecutable -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Emit/Emit/DynamicAnalysis/DynamicInstrumentationTests.vb b/src/Compilers/VisualBasic/Test/Emit/Emit/DynamicAnalysis/DynamicInstrumentationTests.vb index 84abee98952b3..55916ff84e117 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Emit/DynamicAnalysis/DynamicInstrumentationTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Emit/DynamicAnalysis/DynamicInstrumentationTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Test.Utilities.VBInstrumentationChecker diff --git a/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/AssemblyReferencesTests.vb b/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/AssemblyReferencesTests.vb index bea8476785320..be5eaa39d281c 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/AssemblyReferencesTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/AssemblyReferencesTests.vb @@ -2,19 +2,13 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.Generic Imports System.Collections.Immutable -Imports System.IO -Imports System.Linq -Imports System.Reflection.Metadata -Imports System.Threading -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Symbols +Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.MetadataUtilities Imports Roslyn.Test.Utilities -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue.UnitTests Public Class AssemblyReferencesTests diff --git a/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/EditAndContinueClosureTests.vb b/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/EditAndContinueClosureTests.vb index a2735c380d293..a364f410ad73b 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/EditAndContinueClosureTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/EditAndContinueClosureTests.vb @@ -4,11 +4,8 @@ Imports System.Collections.Immutable Imports System.Reflection.Metadata.Ecma335 -Imports Microsoft.CodeAnalysis.EditAndContinue.UnitTests Imports Microsoft.CodeAnalysis.Emit -Imports Microsoft.CodeAnalysis.Operations Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.EditAndContinue.UnitTests Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/EditAndContinuePdbTests.vb b/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/EditAndContinuePdbTests.vb index 30bc296bea330..a68c30f39240d 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/EditAndContinuePdbTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/EditAndContinuePdbTests.vb @@ -4,10 +4,10 @@ Imports System.Collections.Immutable Imports System.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Symbols +Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/EditAndContinueTest.vb b/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/EditAndContinueTest.vb index 1539a9fec8dd4..60a1f8d665bce 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/EditAndContinueTest.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/EditAndContinueTest.vb @@ -2,11 +2,11 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.EditAndContinue.UnitTests Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Roslyn.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests +Imports Roslyn.Test.Utilities Imports Xunit.Abstractions Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/EditAndContinueTestBase.vb b/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/EditAndContinueTestBase.vb index 60e0335fc194b..21060764f7d1b 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/EditAndContinueTestBase.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/EditAndContinueTestBase.vb @@ -7,7 +7,6 @@ Imports System.IO Imports System.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports System.Runtime.CompilerServices -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.EditAndContinue.UnitTests Imports Microsoft.CodeAnalysis.Emit diff --git a/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/SymbolMatcherTests.vb b/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/SymbolMatcherTests.vb index c6025fbff2194..f6720503c9293 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/SymbolMatcherTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/SymbolMatcherTests.vb @@ -3,15 +3,14 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable +Imports System.Threading Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Emit -Imports Roslyn.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE -Imports System.Threading.Tasks -Imports System.Threading +Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SymbolMatcherTests diff --git a/src/Compilers/VisualBasic/Test/Emit/Emit/EmitCustomModifiers.vb b/src/Compilers/VisualBasic/Test/Emit/Emit/EmitCustomModifiers.vb index fdf70732dae90..42a40e23e42ca 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Emit/EmitCustomModifiers.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Emit/EmitCustomModifiers.vb @@ -2,17 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System -Imports System.Collections.Generic -Imports System.Linq -Imports System.Text -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Xunit -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit diff --git a/src/Compilers/VisualBasic/Test/Emit/Emit/EmitErrorTests.vb b/src/Compilers/VisualBasic/Test/Emit/Emit/EmitErrorTests.vb index 649cc8877b86c..bde18144b1352 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Emit/EmitErrorTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Emit/EmitErrorTests.vb @@ -4,15 +4,9 @@ Imports System.IO Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/Emit/EmitMetadata.vb b/src/Compilers/VisualBasic/Test/Emit/Emit/EmitMetadata.vb index b231a7328648e..5360d27f24b4c 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Emit/EmitMetadata.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Emit/EmitMetadata.vb @@ -9,6 +9,7 @@ Imports System.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports System.Reflection.PortableExecutable Imports Basic.Reference.Assemblies +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols diff --git a/src/Compilers/VisualBasic/Test/Emit/Emit/EntryPointTests.vb b/src/Compilers/VisualBasic/Test/Emit/Emit/EntryPointTests.vb index bb7a31777277b..4b3f94d920179 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Emit/EntryPointTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Emit/EntryPointTests.vb @@ -2,10 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit diff --git a/src/Compilers/VisualBasic/Test/Emit/Emit/FieldInitializerTests.vb b/src/Compilers/VisualBasic/Test/Emit/Emit/FieldInitializerTests.vb index 5d24ce3c807f4..ad23eb4830da2 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Emit/FieldInitializerTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Emit/FieldInitializerTests.vb @@ -2,14 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Linq Imports System.Text -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit diff --git a/src/Compilers/VisualBasic/Test/Emit/Emit/NoPiaEmbedTypes.vb b/src/Compilers/VisualBasic/Test/Emit/Emit/NoPiaEmbedTypes.vb index 615ddc687332a..5b5066064fee3 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Emit/NoPiaEmbedTypes.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Emit/NoPiaEmbedTypes.vb @@ -2,20 +2,18 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports System.Collections.Immutable +Imports System.IO +Imports System.Reflection +Imports System.Reflection.Metadata +Imports Basic.Reference.Assemblies +Imports Microsoft.CodeAnalysis.Collections +Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities -Imports System.IO -Imports System.Reflection -Imports System.Xml.Linq -Imports Xunit -Imports System.Reflection.Metadata -Imports Microsoft.CodeAnalysis.Emit -Imports System.Collections.Immutable -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/Emit/OptionalArgumentsTests.vb b/src/Compilers/VisualBasic/Test/Emit/Emit/OptionalArgumentsTests.vb index 4202e203a8415..35e6a77237f5c 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Emit/OptionalArgumentsTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Emit/OptionalArgumentsTests.vb @@ -2,19 +2,11 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.IO -Imports System.Linq Imports System.Reflection -Imports System.Runtime.CompilerServices -Imports System.Xml.Linq -Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Public Class OptionalArgumentsTests diff --git a/src/Compilers/VisualBasic/Test/Emit/EmitResourceUtil.vb b/src/Compilers/VisualBasic/Test/Emit/EmitResourceUtil.vb index abc8dd54e4cae..6ac95412d19da 100644 --- a/src/Compilers/VisualBasic/Test/Emit/EmitResourceUtil.vb +++ b/src/Compilers/VisualBasic/Test/Emit/EmitResourceUtil.vb @@ -4,8 +4,6 @@ Option Strict On Option Explicit On - -Imports System Imports System.IO Imports System.Reflection diff --git a/src/Compilers/VisualBasic/Test/Emit/ErrorHandling.vb b/src/Compilers/VisualBasic/Test/Emit/ErrorHandling.vb index 8b95fdabae821..a5bf709dec2e2 100644 --- a/src/Compilers/VisualBasic/Test/Emit/ErrorHandling.vb +++ b/src/Compilers/VisualBasic/Test/Emit/ErrorHandling.vb @@ -3,13 +3,8 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/CodeGenExprLambda.vb b/src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/CodeGenExprLambda.vb index d75635d656bb7..dc7e20aff41b6 100644 --- a/src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/CodeGenExprLambda.vb +++ b/src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/CodeGenExprLambda.vb @@ -5,9 +5,9 @@ Imports System.IO Imports System.Text Imports System.Xml.Linq +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests ''' diff --git a/src/Compilers/VisualBasic/Test/Emit/PDB/ChecksumTests.vb b/src/Compilers/VisualBasic/Test/Emit/PDB/ChecksumTests.vb index a4146db28aba5..15206422692d9 100644 --- a/src/Compilers/VisualBasic/Test/Emit/PDB/ChecksumTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/PDB/ChecksumTests.vb @@ -2,13 +2,12 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Text -Imports Roslyn.Test.Utilities Imports System.Collections.Immutable Imports System.IO -Imports System.Xml.Linq -Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Emit +Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.Text +Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB diff --git a/src/Compilers/VisualBasic/Test/Emit/PDB/PDBConstLocalTests.vb b/src/Compilers/VisualBasic/Test/Emit/PDB/PDBConstLocalTests.vb index b462edc7b5e23..5b32b336b6039 100644 --- a/src/Compilers/VisualBasic/Test/Emit/PDB/PDBConstLocalTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/PDB/PDBConstLocalTests.vb @@ -2,9 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Roslyn.Test.Utilities -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB diff --git a/src/Compilers/VisualBasic/Test/Emit/PDB/PDBLambdaTests.vb b/src/Compilers/VisualBasic/Test/Emit/PDB/PDBLambdaTests.vb index 3c7a9d7e3d895..bde8afc1f5cdd 100644 --- a/src/Compilers/VisualBasic/Test/Emit/PDB/PDBLambdaTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/PDB/PDBLambdaTests.vb @@ -5,7 +5,6 @@ Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities -Imports System.Xml.Linq Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB Public Class PDBLambdaTests diff --git a/src/Compilers/VisualBasic/Test/Emit/PDB/PDBTests.vb b/src/Compilers/VisualBasic/Test/Emit/PDB/PDBTests.vb index fca4413f84999..99198d27d49de 100644 --- a/src/Compilers/VisualBasic/Test/Emit/PDB/PDBTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/PDB/PDBTests.vb @@ -249,7 +249,7 @@ End Class Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.ConsoleApplication) - defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("Console"))) + defines = defines.Add(KeyValuePair.Create("_MyType", CObj("Console"))) Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines) @@ -4039,7 +4039,7 @@ End Class Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.ConsoleApplication) - defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("Console"))) + defines = defines.Add(KeyValuePair.Create("_MyType", CObj("Console"))) Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines) @@ -4352,11 +4352,11 @@ End Class Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols( OutputKind.WindowsApplication, - KeyValuePairUtil.Create(Of String, Object)("_MyType", "WindowsForms"), - KeyValuePairUtil.Create(Of String, Object)("Config", "Debug"), - KeyValuePairUtil.Create(Of String, Object)("DEBUG", -1), - KeyValuePairUtil.Create(Of String, Object)("TRACE", -1), - KeyValuePairUtil.Create(Of String, Object)("PLATFORM", "AnyCPU")) + KeyValuePair.Create(Of String, Object)("_MyType", "WindowsForms"), + KeyValuePair.Create(Of String, Object)("Config", "Debug"), + KeyValuePair.Create(Of String, Object)("DEBUG", -1), + KeyValuePair.Create(Of String, Object)("TRACE", -1), + KeyValuePair.Create(Of String, Object)("PLATFORM", "AnyCPU")) Dim parseOptions As VisualBasicParseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines) Dim compOptions As VisualBasicCompilationOptions = New VisualBasicCompilationOptions( diff --git a/src/Compilers/VisualBasic/Test/Emit/PDB/PDBUsingTests.vb b/src/Compilers/VisualBasic/Test/Emit/PDB/PDBUsingTests.vb index 2f9f75228a5ec..fe86e72a530fb 100644 --- a/src/Compilers/VisualBasic/Test/Emit/PDB/PDBUsingTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/PDB/PDBUsingTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.IO Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Emit/PDB/PDBWinMdExpTests.vb b/src/Compilers/VisualBasic/Test/Emit/PDB/PDBWinMdExpTests.vb index 55af00c39e232..9caa2900068b8 100644 --- a/src/Compilers/VisualBasic/Test/Emit/PDB/PDBWinMdExpTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/PDB/PDBWinMdExpTests.vb @@ -2,10 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Roslyn.Test.Utilities Imports System.IO Imports System.Text Imports System.Xml +Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB Public Class PDBWinMdExpTests diff --git a/src/Compilers/VisualBasic/Test/Emit/Perf.vb b/src/Compilers/VisualBasic/Test/Emit/Perf.vb index 6448b2df8e81b..49e3c69389749 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Perf.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Perf.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Roslyn.Test.Utilities Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit diff --git a/src/Compilers/VisualBasic/Test/Emit/XmlLiteralTests.vb b/src/Compilers/VisualBasic/Test/Emit/XmlLiteralTests.vb index d1ed11a266a7c..5f92a3533cc33 100644 --- a/src/Compilers/VisualBasic/Test/Emit/XmlLiteralTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/XmlLiteralTests.vb @@ -2,14 +2,12 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.IO Imports System.Text +Imports Basic.Reference.Assemblies Imports Microsoft.Cci Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IArgument.vb b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IArgument.vb index 77252d11b1b9d..dc38ef132f245 100644 --- a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IArgument.vb +++ b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IArgument.vb @@ -2,9 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Operations +Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IArrayElementReferenceExpression.vb b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IArrayElementReferenceExpression.vb index 6ef31628f24c7..ac7ae3a83d74a 100644 --- a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IArrayElementReferenceExpression.vb +++ b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IArrayElementReferenceExpression.vb @@ -2,8 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IAttributeOperation.vb b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IAttributeOperation.vb index 26f7faa4ea2c8..bbc91b7a766ff 100644 --- a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IAttributeOperation.vb +++ b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IAttributeOperation.vb @@ -2,8 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests diff --git a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IAwaitExpression.vb b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IAwaitExpression.vb index b22483b08f3b6..8a8d975efdb99 100644 --- a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IAwaitExpression.vb +++ b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IAwaitExpression.vb @@ -2,8 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IBinaryOperatorExpression.vb b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IBinaryOperatorExpression.vb index 830d524ac6f56..a2df221427a6e 100644 --- a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IBinaryOperatorExpression.vb +++ b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IBinaryOperatorExpression.vb @@ -2,8 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IBlockStatement_MethodBlocks.vb b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IBlockStatement_MethodBlocks.vb index 060ebcabc95be..3d507bd5a8f31 100644 --- a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IBlockStatement_MethodBlocks.vb +++ b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IBlockStatement_MethodBlocks.vb @@ -2,8 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_ICompoundAssignmentOperation.vb b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_ICompoundAssignmentOperation.vb index 3d68e2ea1eae5..d46b827343d97 100644 --- a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_ICompoundAssignmentOperation.vb +++ b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_ICompoundAssignmentOperation.vb @@ -2,10 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Operations +Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IConversionExpression.vb b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IConversionExpression.vb index 688f44bf519c9..146204eab68e9 100644 --- a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IConversionExpression.vb +++ b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IConversionExpression.vb @@ -2,9 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Operations +Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IDynamicInvocationExpression.vb b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IDynamicInvocationExpression.vb index be06de39b70aa..2569b10c98a1b 100644 --- a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IDynamicInvocationExpression.vb +++ b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IDynamicInvocationExpression.vb @@ -2,8 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IDynamicMemberReferenceExpression.vb b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IDynamicMemberReferenceExpression.vb index 90c8138044c8c..be29c42ce8a83 100644 --- a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IDynamicMemberReferenceExpression.vb +++ b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IDynamicMemberReferenceExpression.vb @@ -2,8 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IIfStatement.vb b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IIfStatement.vb index 7c2f62f75dcc4..d47a6b6c790bc 100644 --- a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IIfStatement.vb +++ b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IIfStatement.vb @@ -2,8 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IInterpolatedStringExpression.vb b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IInterpolatedStringExpression.vb index 30499981353b5..64afdaf55a422 100644 --- a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IInterpolatedStringExpression.vb +++ b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IInterpolatedStringExpression.vb @@ -2,8 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_INoPiaObjectCreationOperation.vb b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_INoPiaObjectCreationOperation.vb index f15b297334dd8..ea35c1977f994 100644 --- a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_INoPiaObjectCreationOperation.vb +++ b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_INoPiaObjectCreationOperation.vb @@ -2,8 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IObjectCreationExpression.vb b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IObjectCreationExpression.vb index dcc3ebe8b8b95..348a1a2dd199e 100644 --- a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IObjectCreationExpression.vb +++ b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IObjectCreationExpression.vb @@ -2,8 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IReturnStatement.vb b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IReturnStatement.vb index 5505de8fdb6ae..0f95a7a717c5e 100644 --- a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IReturnStatement.vb +++ b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IReturnStatement.vb @@ -2,8 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_ITupleExpression.vb b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_ITupleExpression.vb index e661324c7e537..e4baf943e4534 100644 --- a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_ITupleExpression.vb +++ b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_ITupleExpression.vb @@ -2,8 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_ITypeOfExpression.vb b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_ITypeOfExpression.vb index 3d5d23aca2c13..83d8844a5ab28 100644 --- a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_ITypeOfExpression.vb +++ b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_ITypeOfExpression.vb @@ -2,8 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IUnaryOperatorExpression.vb b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IUnaryOperatorExpression.vb index b908a3e194ee2..e00d2957f47b1 100644 --- a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IUnaryOperatorExpression.vb +++ b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IUnaryOperatorExpression.vb @@ -2,8 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IUsingStatement.vb b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IUsingStatement.vb index a03fb4dcb8d46..30eef3708e594 100644 --- a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IUsingStatement.vb +++ b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IUsingStatement.vb @@ -2,10 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax +Imports Microsoft.CodeAnalysis.Operations Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Microsoft.CodeAnalysis.Operations Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests diff --git a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IVariableDeclaration.vb b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IVariableDeclaration.vb index 1b8c659d42e3b..fe946769be5f7 100644 --- a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IVariableDeclaration.vb +++ b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IVariableDeclaration.vb @@ -2,8 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IWithStatement.vb b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IWithStatement.vb index 46bd430dd2c28..97533f46735d3 100644 --- a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IWithStatement.vb +++ b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IWithStatement.vb @@ -2,8 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_TryCatch.vb b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_TryCatch.vb index 7f6450dddaabf..60c92f65c9b62 100644 --- a/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_TryCatch.vb +++ b/src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_TryCatch.vb @@ -2,8 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/AssemblyAttributes.vb b/src/Compilers/VisualBasic/Test/Semantic/AssemblyAttributes.vb deleted file mode 100644 index 02f5a0aabbbfb..0000000000000 --- a/src/Compilers/VisualBasic/Test/Semantic/AssemblyAttributes.vb +++ /dev/null @@ -1,6 +0,0 @@ -' Licensed to the .NET Foundation under one or more agreements. -' The .NET Foundation licenses this file to you under the MIT license. -' See the LICENSE file in the project root for more information. - -Imports Xunit - diff --git a/src/Compilers/VisualBasic/Test/Semantic/Binding/BadSymbolReference.vb b/src/Compilers/VisualBasic/Test/Semantic/Binding/BadSymbolReference.vb index 5e4d88ea263f5..86afbc527063e 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Binding/BadSymbolReference.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Binding/BadSymbolReference.vb @@ -3,12 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit - -Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Binding diff --git a/src/Compilers/VisualBasic/Test/Semantic/Binding/Binder_Expressions_Tests.vb b/src/Compilers/VisualBasic/Test/Semantic/Binding/Binder_Expressions_Tests.vb index 5378874139b6f..ca86e30676e86 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Binding/Binder_Expressions_Tests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Binding/Binder_Expressions_Tests.vb @@ -4,7 +4,6 @@ Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Semantic/Binding/Binder_Statements_Tests.vb b/src/Compilers/VisualBasic/Test/Semantic/Binding/Binder_Statements_Tests.vb index 00510c373036a..e274b31a0186b 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Binding/Binder_Statements_Tests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Binding/Binder_Statements_Tests.vb @@ -5,12 +5,9 @@ Imports System.Reflection Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit +Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/Binding/BindingCollectionInitializerTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Binding/BindingCollectionInitializerTests.vb index 51fac213420f2..7b820ae1d6d27 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Binding/BindingCollectionInitializerTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Binding/BindingCollectionInitializerTests.vb @@ -4,11 +4,8 @@ Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/Binding/BindingErrorTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Binding/BindingErrorTests.vb index 6007a4597119e..67cb2003f8506 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Binding/BindingErrorTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Binding/BindingErrorTests.vb @@ -2,12 +2,12 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/Binding/BindingObjectInitializerTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Binding/BindingObjectInitializerTests.vb index c008d8dd5f120..3ee0936214fce 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Binding/BindingObjectInitializerTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Binding/BindingObjectInitializerTests.vb @@ -2,16 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Linq.Enumerable -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax - -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/Binding/BindingScopeTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Binding/BindingScopeTests.vb index 77490557f8d8c..d25dca3f74f1f 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Binding/BindingScopeTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Binding/BindingScopeTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Xml.Linq Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/Binding/ForEachTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Binding/ForEachTests.vb index f28793c052ada..eeb976fa18e1a 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Binding/ForEachTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Binding/ForEachTests.vb @@ -4,16 +4,13 @@ Imports System.Collections.Immutable Imports System.Linq.Enumerable -Imports System.Xml.Linq +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class ForLoopTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/Binding/GotoTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Binding/GotoTests.vb index 066ae43f25249..f5761921fe0fd 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Binding/GotoTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Binding/GotoTests.vb @@ -2,11 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/Binding/ImplicitVariableTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Binding/ImplicitVariableTests.vb index d79f02e9f782e..63e2c3b0ffc0b 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Binding/ImplicitVariableTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Binding/ImplicitVariableTests.vb @@ -2,18 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System -Imports System.Collections.Generic -Imports System.IO -Imports System.Linq -Imports System.Text -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Public Class ImplicitVariableTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/Binding/LookupTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Binding/LookupTests.vb index 839c36a9d8df2..4c989353fe262 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Binding/LookupTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Binding/LookupTests.vb @@ -3,16 +3,12 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.Globalization -Imports System.Text -Imports System.Xml.Linq +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols +Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class LookupTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/Binding/MethodBodyBindingTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Binding/MethodBodyBindingTests.vb index 6c8e2f95b6cae..8504932fc46b5 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Binding/MethodBodyBindingTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Binding/MethodBodyBindingTests.vb @@ -2,11 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Globalization -Imports System.Text -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Semantic/Binding/SyncLockTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Binding/SyncLockTests.vb index 3a349595a3cac..c89344410e3f8 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Binding/SyncLockTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Binding/SyncLockTests.vb @@ -2,9 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SyncLockTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/Binding/UsingTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Binding/UsingTests.vb index 8e5a441ca3513..1999e2faea20e 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Binding/UsingTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Binding/UsingTests.vb @@ -2,11 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/Compilation/CompilationAPITests.vb b/src/Compilers/VisualBasic/Test/Semantic/Compilation/CompilationAPITests.vb index 7a317369b781d..c7c7ffc4bb8df 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Compilation/CompilationAPITests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Compilation/CompilationAPITests.vb @@ -8,7 +8,9 @@ Imports System.Reflection.PortableExecutable Imports System.Runtime.InteropServices Imports System.Security.Cryptography Imports System.Threading +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text @@ -18,7 +20,6 @@ Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.TestHelpers -Imports Basic.Reference.Assemblies Imports CS = Microsoft.CodeAnalysis.CSharp Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/Compilation/GetImportScopesTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Compilation/GetImportScopesTests.vb index 3b8c725991d22..9b3de523959ab 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Compilation/GetImportScopesTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Compilation/GetImportScopesTests.vb @@ -3,13 +3,8 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.Linq -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/Compilation/GetSemanticInfoBrokenCodeTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Compilation/GetSemanticInfoBrokenCodeTests.vb index 431413f8f0681..a674eb6956797 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Compilation/GetSemanticInfoBrokenCodeTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Compilation/GetSemanticInfoBrokenCodeTests.vb @@ -2,10 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax - Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/Compilation/MyTemplateTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Compilation/MyTemplateTests.vb index 30a335a722c3a..98b8eeafa4e94 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Compilation/MyTemplateTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Compilation/MyTemplateTests.vb @@ -120,7 +120,7 @@ End Module Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.ConsoleApplication) - defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("Console"))) + defines = defines.Add(KeyValuePair.Create("_MyType", CObj("Console"))) Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines) Dim compilationOptions = TestOptions.ReleaseExe.WithParseOptions(parseOptions) @@ -196,7 +196,7 @@ End Class Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.WindowsApplication) - defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("WindowsForms"))) + defines = defines.Add(KeyValuePair.Create("_MyType", CObj("WindowsForms"))) Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines) Dim compilationOptions = TestOptions.ReleaseExe.WithOutputKind(OutputKind.WindowsApplication).WithParseOptions(parseOptions).WithMainTypeName("Form1") @@ -225,7 +225,7 @@ End Module Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.ConsoleApplication) - defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("Console"))) + defines = defines.Add(KeyValuePair.Create("_MyType", CObj("Console"))) Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines) Dim compilationOptions = TestOptions.ReleaseExe.WithParseOptions(parseOptions) @@ -280,7 +280,7 @@ End Namespace Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.ConsoleApplication) - defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("Console"))) + defines = defines.Add(KeyValuePair.Create("_MyType", CObj("Console"))) Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines) Dim compilationOptions = TestOptions.ReleaseExe.WithParseOptions(parseOptions) diff --git a/src/Compilers/VisualBasic/Test/Semantic/Compilation/ReferenceManagerTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Compilation/ReferenceManagerTests.vb index 6772b41a13223..f4c9739532b7d 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Compilation/ReferenceManagerTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Compilation/ReferenceManagerTests.vb @@ -2,11 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.Immutable +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/Compilation/SemanticModelAPITests.vb b/src/Compilers/VisualBasic/Test/Semantic/Compilation/SemanticModelAPITests.vb index 6d68af2976416..63287cde51c13 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Compilation/SemanticModelAPITests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Compilation/SemanticModelAPITests.vb @@ -2,13 +2,13 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Basic.Reference.Assemblies +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/Compilation/SemanticModelGetDeclaredSymbolAPITests.vb b/src/Compilers/VisualBasic/Test/Semantic/Compilation/SemanticModelGetDeclaredSymbolAPITests.vb index 82518b12199b3..7c6900eb4d6b8 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Compilation/SemanticModelGetDeclaredSymbolAPITests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Compilation/SemanticModelGetDeclaredSymbolAPITests.vb @@ -2,17 +2,12 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.IO -Imports System.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax - Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Compilation/SemanticModelLookupSymbolsAPITests.vb b/src/Compilers/VisualBasic/Test/Semantic/Compilation/SemanticModelLookupSymbolsAPITests.vb index 99c206f0edc56..075773d540c6d 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Compilation/SemanticModelLookupSymbolsAPITests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Compilation/SemanticModelLookupSymbolsAPITests.vb @@ -3,11 +3,10 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Basic.Reference.Assemblies Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Compilation/SuppressAccessibilityChecksTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Compilation/SuppressAccessibilityChecksTests.vb index f30411c334f0c..5d730d1a5d7ba 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Compilation/SuppressAccessibilityChecksTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Compilation/SuppressAccessibilityChecksTests.vb @@ -6,9 +6,6 @@ Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests - -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SuppressAccessibilityChecksTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/DeclaringSyntaxNodeTests.vb b/src/Compilers/VisualBasic/Test/Semantic/DeclaringSyntaxNodeTests.vb index 5aa7179a05850..e8ed3fb3a9ad4 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/DeclaringSyntaxNodeTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/DeclaringSyntaxNodeTests.vb @@ -3,11 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.Globalization -Imports System.Text -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Compilers/VisualBasic/Test/Semantic/Diagnostics/CompilationEventTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Diagnostics/CompilationEventTests.vb index d2425e49ea3ac..a8202cf153b03 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Diagnostics/CompilationEventTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Diagnostics/CompilationEventTests.vb @@ -2,13 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.Immutable -Imports System.Globalization -Imports System.Runtime.Serialization Imports System.Threading Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics @@ -200,7 +196,7 @@ End Module Dim q = New AsyncQueue(Of CompilationEvent)() Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.ConsoleApplication) - defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("Console"))) + defines = defines.Add(KeyValuePair.Create("_MyType", CObj("Console"))) Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines) Dim compilationOptions = TestOptions.ReleaseExe.WithParseOptions(parseOptions) Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=compilationOptions).WithEventQueue(q) diff --git a/src/Compilers/VisualBasic/Test/Semantic/Diagnostics/DiagnosticAnalyzerTests.AllInOne.vb b/src/Compilers/VisualBasic/Test/Semantic/Diagnostics/DiagnosticAnalyzerTests.AllInOne.vb index d246cc377540d..906f47cfb8f86 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Diagnostics/DiagnosticAnalyzerTests.AllInOne.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Diagnostics/DiagnosticAnalyzerTests.AllInOne.vb @@ -3,8 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.Text.RegularExpressions -Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Semantic/Diagnostics/DiagnosticAnalyzerTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Diagnostics/DiagnosticAnalyzerTests.vb index b072d3e1fe5c5..5e58b96017a4d 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Diagnostics/DiagnosticAnalyzerTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Diagnostics/DiagnosticAnalyzerTests.vb @@ -4,7 +4,6 @@ Imports System.Collections.Concurrent Imports System.Collections.Immutable -Imports System.Runtime.Serialization Imports System.Threading Imports Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers Imports Microsoft.CodeAnalysis.Diagnostics @@ -1633,7 +1632,7 @@ End Namespace Dim defines = AddPredefinedPreprocessorSymbols(OutputKind.WindowsApplication) - defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("WindowsForms"))) + defines = defines.Add(KeyValuePair.Create("_MyType", CObj("WindowsForms"))) Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines) Dim compilationOptions = TestOptions.ReleaseExe.WithParseOptions(parseOptions) diff --git a/src/Compilers/VisualBasic/Test/Semantic/Diagnostics/DiagnosticTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Diagnostics/DiagnosticTests.vb index 1e797c4ceec51..a44c2e9e59606 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Diagnostics/DiagnosticTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Diagnostics/DiagnosticTests.vb @@ -3,6 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Globalization +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Semantic/Diagnostics/OperationAnalyzerTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Diagnostics/OperationAnalyzerTests.vb index f96e6d6ae2d08..0de3b2dd9685d 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Diagnostics/OperationAnalyzerTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Diagnostics/OperationAnalyzerTests.vb @@ -2,14 +2,11 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers -Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/ExtensionMethods/SemanticModelTests.vb b/src/Compilers/VisualBasic/Test/Semantic/ExtensionMethods/SemanticModelTests.vb index 6bc3a935d1b16..ef399202c74bc 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/ExtensionMethods/SemanticModelTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/ExtensionMethods/SemanticModelTests.vb @@ -2,11 +2,11 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.ExtensionMethods diff --git a/src/Compilers/VisualBasic/Test/Semantic/Extensions.vb b/src/Compilers/VisualBasic/Test/Semantic/Extensions.vb index e38c87230d046..ab9e47f608392 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Extensions.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Extensions.vb @@ -2,12 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System Imports System.Runtime.CompilerServices Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax ' This is deliberately declared in the global namespace so that it will always be discoverable (regardless of Imports). diff --git a/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/FlowDiagnosticTests.vb b/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/FlowDiagnosticTests.vb index d13c853854c84..d324d6d933dfc 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/FlowDiagnosticTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/FlowDiagnosticTests.vb @@ -2,16 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System -Imports System.[Text] -Imports System.Collections.Generic -Imports System.Linq -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Roslyn.Test.Utilities -Imports Xunit Imports Basic.Reference.Assemblies +Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SimpleFlowTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/FlowTestBase.vb b/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/FlowTestBase.vb index 1717b4f1aa6c3..edb40d51f61eb 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/FlowTestBase.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/FlowTestBase.vb @@ -2,18 +2,11 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System -Imports System.Collections.Generic Imports System.Collections.Immutable -Imports System.Linq -Imports System.Text -Imports System.Xml.Linq -Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/IterationJumpYieldStatementTests.vb b/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/IterationJumpYieldStatementTests.vb index 0225ecf29b230..850f9e57a5391 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/IterationJumpYieldStatementTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/IterationJumpYieldStatementTests.vb @@ -2,17 +2,11 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System -Imports System.Linq -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.FlowAnalysis diff --git a/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/RegionAnalysisTests.vb b/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/RegionAnalysisTests.vb index 00673802748a4..d278337773b12 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/RegionAnalysisTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/RegionAnalysisTests.vb @@ -2,9 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax - Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests @@ -935,7 +935,7 @@ End Namespace Dim comp = CompileAndGetModelAndSpan(program, startNodes, endNodes, Nothing, Nothing, parseOptions:= VisualBasicParseOptions.Default.WithPreprocessorSymbols( - KeyValuePairUtil.Create("SQLITE_DEBUG", CObj(True)))) + KeyValuePair.Create("SQLITE_DEBUG", CObj(True)))) Assert.Equal(4, startNodes.Count) Assert.Equal(SyntaxKind.DictionaryAccessExpression, startNodes(2).Kind) diff --git a/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/RegionAnalysisTestsWithStaticLocals.vb b/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/RegionAnalysisTestsWithStaticLocals.vb index 28565d01af01a..ff917361c348c 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/RegionAnalysisTestsWithStaticLocals.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/RegionAnalysisTestsWithStaticLocals.vb @@ -4,7 +4,6 @@ Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax - Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/StructureAnalysisTests.vb b/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/StructureAnalysisTests.vb index 95f0635226154..edbfd9de69c4f 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/StructureAnalysisTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/StructureAnalysisTests.vb @@ -2,15 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System -Imports System.Collections.Generic -Imports System.Linq -Imports System.Xml.Linq -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class StructureAnalysisTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/TryLockUsingStatementTests.vb b/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/TryLockUsingStatementTests.vb index 05b14c53ee850..1c8f34a9013b6 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/TryLockUsingStatementTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/TryLockUsingStatementTests.vb @@ -2,15 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System -Imports System.Collections.Generic -Imports System.Linq -Imports System.Xml.Linq -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Partial Public Class FlowAnalysisTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/SemanticResourceUtil.vb b/src/Compilers/VisualBasic/Test/Semantic/SemanticResourceUtil.vb index 3c922041137b8..f22244083286b 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/SemanticResourceUtil.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/SemanticResourceUtil.vb @@ -4,8 +4,6 @@ Option Strict On Option Explicit On - -Imports System Imports System.IO Imports System.Reflection diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/AccessCheckTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/AccessCheckTests.vb index bc82a2a64ef06..039acd5004f0f 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/AccessCheckTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/AccessCheckTests.vb @@ -3,13 +3,9 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.IO Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/ArrayLiteralTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/ArrayLiteralTests.vb index 54fb2172859a2..be478d3fb07ab 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/ArrayLiteralTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/ArrayLiteralTests.vb @@ -2,18 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.Immutable -Imports System.IO Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit - Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/AsyncAwait.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/AsyncAwait.vb index 221261119f52d..d856216161fc4 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/AsyncAwait.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/AsyncAwait.vb @@ -2,13 +2,11 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports System.Collections.ObjectModel +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports System.Collections.ObjectModel -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/BinaryOperators.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/BinaryOperators.vb index a38f792aa5360..d58f5200411a9 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/BinaryOperators.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/BinaryOperators.vb @@ -2,15 +2,11 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.IO Imports System.Text Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/CompoundAssignment.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/CompoundAssignment.vb index 3d05f566015ab..ef9c6842f4522 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/CompoundAssignment.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/CompoundAssignment.vb @@ -2,16 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.IO Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax - Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/ConditionalAccessTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/ConditionalAccessTests.vb index 5bd85f818a840..a4a9f6216d502 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/ConditionalAccessTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/ConditionalAccessTests.vb @@ -2,11 +2,12 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Basic.Reference.Assemblies +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/ConditionalExpressionsTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/ConditionalExpressionsTests.vb index eb162ae3d798e..78b479d4e9f6d 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/ConditionalExpressionsTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/ConditionalExpressionsTests.vb @@ -2,19 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.IO -Imports System.Xml -Imports System.Xml.Linq -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit - Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/Conversions.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/Conversions.vb index 89998c076ec36..89ae32f1e8095 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/Conversions.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/Conversions.vb @@ -2,19 +2,14 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.IO -Imports System.Xml.Linq +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.SpecialType -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics.ConversionsTests.Parameters Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/Conversions_AnonymousDelegates.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/Conversions_AnonymousDelegates.vb index ad7edc1fb8385..0d8aa29d20448 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/Conversions_AnonymousDelegates.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/Conversions_AnonymousDelegates.vb @@ -5,7 +5,6 @@ Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax - Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/EraseStatementTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/EraseStatementTests.vb index 53c74b67eae91..65a5cf8821d1d 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/EraseStatementTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/EraseStatementTests.vb @@ -4,8 +4,6 @@ Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit -Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/FieldInitializerBindingTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/FieldInitializerBindingTests.vb index 23bebecadbaca..02f3be6045a14 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/FieldInitializerBindingTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/FieldInitializerBindingTests.vb @@ -5,6 +5,7 @@ Imports System.Collections.Immutable Imports System.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/ForLoopTest.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/ForLoopTest.vb index 2e191db0fc744..9ce79c312ac3b 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/ForLoopTest.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/ForLoopTest.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/ForeachTest.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/ForeachTest.vb index 29a41679c1bea..8845a46381f14 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/ForeachTest.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/ForeachTest.vb @@ -2,12 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports VB = Microsoft.CodeAnalysis.VisualBasic Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/GetExtendedSemanticInfoTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/GetExtendedSemanticInfoTests.vb index d00a160156b9b..621776207a898 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/GetExtendedSemanticInfoTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/GetExtendedSemanticInfoTests.vb @@ -3,16 +3,13 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.IO +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Basic.Reference.Assemblies Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/GetSemanticInfoTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/GetSemanticInfoTests.vb index 5f10e173e669a..ba7f61c8d2e1b 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/GetSemanticInfoTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/GetSemanticInfoTests.vb @@ -3,19 +3,15 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.IO -Imports System.Linq Imports System.Runtime.CompilerServices +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.SpecialType +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class SemanticModelTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/GetUnusedImportDirectivesTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/GetUnusedImportDirectivesTests.vb index d2208b6b56607..541d46aad819a 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/GetUnusedImportDirectivesTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/GetUnusedImportDirectivesTests.vb @@ -2,10 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.VisualBasic Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/GotoTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/GotoTests.vb index 446c2937ed103..f7ff757149973 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/GotoTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/GotoTests.vb @@ -3,8 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/IFOperatorTest.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/IFOperatorTest.vb index 469858494b3b4..97cedb777ac27 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/IFOperatorTest.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/IFOperatorTest.vb @@ -2,12 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports VB = Microsoft.CodeAnalysis.VisualBasic Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class IFOperatorTest diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/IReadOnlyListAndCollection.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/IReadOnlyListAndCollection.vb index 3ccdc37940797..0e964d3c877ba 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/IReadOnlyListAndCollection.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/IReadOnlyListAndCollection.vb @@ -3,11 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax - -Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/IsIsNot.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/IsIsNot.vb index 413e9e79ff5b2..756c77e9d5361 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/IsIsNot.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/IsIsNot.vb @@ -2,16 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.IO Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.SpecialType -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/IteratorTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/IteratorTests.vb index 6e5e0876ee2d4..5cf6516cd3c40 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/IteratorTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/IteratorTests.vb @@ -6,7 +6,6 @@ Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/LambdaSemanticInfoTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/LambdaSemanticInfoTests.vb index 69fa3b36e8590..241564ef6bc10 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/LambdaSemanticInfoTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/LambdaSemanticInfoTests.vb @@ -2,13 +2,12 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Basic.Reference.Assemblies Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/Lambda_AnonymousDelegateInference.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/Lambda_AnonymousDelegateInference.vb index 298a334b20973..ecb3de79ba065 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/Lambda_AnonymousDelegateInference.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/Lambda_AnonymousDelegateInference.vb @@ -7,7 +7,6 @@ Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax - Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/Lambda_Relaxation.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/Lambda_Relaxation.vb index 0f29e798f54cb..09e348275be84 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/Lambda_Relaxation.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/Lambda_Relaxation.vb @@ -2,10 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Basic.Reference.Assemblies Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/MeMyBaseMyClassTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/MeMyBaseMyClassTests.vb index 9f6ecbe14b73e..c8664aaf79ff7 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/MeMyBaseMyClassTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/MeMyBaseMyClassTests.vb @@ -2,13 +2,11 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Basic.Reference.Assemblies Imports Roslyn.Test.Utilities -Imports VB = Microsoft.CodeAnalysis.VisualBasic Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/MethodCalls.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/MethodCalls.vb index e728fb5b8dc0d..3b9dee476d40f 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/MethodCalls.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/MethodCalls.vb @@ -2,10 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/MissingRuntimeHelpers.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/MissingRuntimeHelpers.vb index fa7d36ba695a8..a4e3fae6a235e 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/MissingRuntimeHelpers.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/MissingRuntimeHelpers.vb @@ -2,17 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.IO -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.SpecialType -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Roslyn.Test.Utilities - Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class MissingRuntimeHelpers diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/MultiDimensionalTest.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/MultiDimensionalTest.vb index d3e3bc45d6aa5..75678ec816460 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/MultiDimensionalTest.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/MultiDimensionalTest.vb @@ -3,11 +3,9 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports VB = Microsoft.CodeAnalysis.VisualBasic Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class MultiDimensionalTest diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/MyBaseMyClassTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/MyBaseMyClassTests.vb index 09c4b724a6fac..ec0005462c9af 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/MyBaseMyClassTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/MyBaseMyClassTests.vb @@ -5,7 +5,6 @@ Imports System.Reflection Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/NameLengthTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/NameLengthTests.vb index 7e2c51991b8b9..8c802f671750a 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/NameLengthTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/NameLengthTests.vb @@ -3,13 +3,10 @@ ' See the LICENSE file in the project root for more information. Imports System.IO +Imports Microsoft.Cci Imports Microsoft.CodeAnalysis.VisualBasic.Symbols 'Imports Microsoft.CodeAnalysis.VisualBasic.Test.Utilities Imports Roslyn.Test.Utilities -Imports Xunit -Imports Microsoft.Cci -Imports System -Imports System.Xml.Linq Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class NameLengthTests : Inherits BasicTestBase diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/NameOfTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/NameOfTests.vb index be9f7f8d2ba72..d5e494774ec74 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/NameOfTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/NameOfTests.vb @@ -3,16 +3,12 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/NewOnInterfaceTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/NewOnInterfaceTests.vb index 7de4af0779822..ddd81e267b5ea 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/NewOnInterfaceTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/NewOnInterfaceTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/OptionApis.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/OptionApis.vb index 6f6c8ebbe53d2..2a5e11d761039 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/OptionApis.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/OptionApis.vb @@ -2,13 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Linq -Imports System.Xml.Linq -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/OverloadResolution.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/OverloadResolution.vb index 28420b328047d..424ea723c60c8 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/OverloadResolution.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/OverloadResolution.vb @@ -3,18 +3,16 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.IO +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics.OverloadResolutionTestHelpers -Imports Basic.Reference.Assemblies Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/PartialMethodsTest.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/PartialMethodsTest.vb index 9214cf4646f85..7fc7787de6001 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/PartialMethodsTest.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/PartialMethodsTest.vb @@ -3,10 +3,8 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax - Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/QueryExpressions.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/QueryExpressions.vb index 6fe3be8c4c918..c3372456e0007 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/QueryExpressions.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/QueryExpressions.vb @@ -2,11 +2,11 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/QueryExpressions_FlowAnalysis.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/QueryExpressions_FlowAnalysis.vb index 94d4fe5a76f24..00b17523da1bd 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/QueryExpressions_FlowAnalysis.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/QueryExpressions_FlowAnalysis.vb @@ -2,15 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System -Imports System.Collections.Generic -Imports System.Linq -Imports System.Xml.Linq -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Partial Public Class FlowAnalysisTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/QueryExpressions_LookupSymbols.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/QueryExpressions_LookupSymbols.vb index a10d26de80573..fcf622c26664f 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/QueryExpressions_LookupSymbols.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/QueryExpressions_LookupSymbols.vb @@ -3,6 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/QueryExpressions_SemanticModel.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/QueryExpressions_SemanticModel.vb index 138261e789e0d..41870f6cb8506 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/QueryExpressions_SemanticModel.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/QueryExpressions_SemanticModel.vb @@ -2,13 +2,13 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Basic.Reference.Assemblies Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/RedimStatementTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/RedimStatementTests.vb index 92c4abda7b048..1872f0d11f62e 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/RedimStatementTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/RedimStatementTests.vb @@ -2,19 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.IO -Imports System.Xml -Imports System.Xml.Linq -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.SpecialType -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit - Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/RefFieldTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/RefFieldTests.vb index 2fe28bcf1273f..8cfdd5beb6d89 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/RefFieldTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/RefFieldTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/ScriptSemanticsTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/ScriptSemanticsTests.vb index 12c757cc2435f..65edb50b216ab 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/ScriptSemanticsTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/ScriptSemanticsTests.vb @@ -45,31 +45,17 @@ F(Function() Dim semanticModel = compilation.GetSemanticModel(syntaxTree, True) Dim node5 As MemberAccessExpressionSyntax = ErrorTestsGetNode(syntaxTree) Assert.Equal("WriteLine", node5.Name.ToString()) - Assert.Null(semanticModel.GetSymbolInfo(node5.Name).Symbol) + Assert.Equal("Sub System.Console.WriteLine(value As System.Int32)", semanticModel.GetSymbolInfo(node5.Name).Symbol.ToTestDisplayString()) - compilation.AssertTheseDiagnostics( - -BC30420: 'Sub Main' was not found in 'Errors_01'. -BC30001: Statement is not valid in a namespace. -System.Console.WriteLine(1) -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - ) + compilation.AssertTheseDiagnostics() compilation = CreateCompilationWithMscorlib461({syntaxTree}, options:=TestOptions.ReleaseExe.WithScriptClassName("Script"), assemblyName:="Errors_01") semanticModel = compilation.GetSemanticModel(syntaxTree, True) node5 = ErrorTestsGetNode(syntaxTree) Assert.Equal("WriteLine", node5.Name.ToString()) - Assert.Null(semanticModel.GetSymbolInfo(node5.Name).Symbol) + Assert.Equal("Sub System.Console.WriteLine(value As System.Int32)", semanticModel.GetSymbolInfo(node5.Name).Symbol.ToTestDisplayString()) - compilation.AssertTheseDiagnostics( - -BC30420: 'Sub Main' was not found in 'Errors_01'. -BC30001: Statement is not valid in a namespace. -System.Console.WriteLine(1) -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - ) + compilation.AssertTheseDiagnostics() syntaxTree = SyntaxFactory.ParseSyntaxTree(code, options:=New VisualBasicParseOptions(kind:=SourceCodeKind.Script)) compilation = CreateCompilationWithMscorlib461AndVBRuntime({syntaxTree}, options:=TestOptions.ReleaseExe) @@ -129,6 +115,7 @@ BC2014: the value 'Nothing' is invalid for option 'ScriptClassName' + Public Sub Errors_02() Dim compilationUnit = VisualBasic.SyntaxFactory.ParseCompilationUnit("System.Console.WriteLine(1)", options:=New VisualBasicParseOptions(kind:=SourceCodeKind.Script)) Dim syntaxTree1 = compilationUnit.SyntaxTree @@ -138,33 +125,41 @@ BC2014: the value 'Nothing' is invalid for option 'ScriptClassName' Dim node2 As MemberAccessExpressionSyntax = ErrorTestsGetNode(syntaxTree2) Assert.Equal("WriteLine", node2.Name.ToString()) - Dim compilation = CreateCompilationWithMscorlib461({syntaxTree1, syntaxTree2}) - Dim semanticModel1 = compilation.GetSemanticModel(syntaxTree1, True) - Dim semanticModel2 = compilation.GetSemanticModel(syntaxTree2, True) - Assert.Null(semanticModel1.GetSymbolInfo(node1.Name).Symbol) - Assert.Equal("Sub System.Console.WriteLine(value As System.Int32)", semanticModel2.GetSymbolInfo(node2.Name).Symbol.ToTestDisplayString()) + Assert.Throws(Of InvalidOperationException)( + Sub() + Dim compilation = CreateCompilationWithMscorlib461({syntaxTree1, syntaxTree2}) + Dim semanticModel1 = compilation.GetSemanticModel(syntaxTree1, True) + Dim semanticModel2 = compilation.GetSemanticModel(syntaxTree2, True) - compilation.AssertTheseDiagnostics( + Assert.Null(semanticModel1.GetSymbolInfo(node1.Name).Symbol) + Assert.Equal("Sub System.Console.WriteLine(value As System.Int32)", semanticModel2.GetSymbolInfo(node2.Name).Symbol.ToTestDisplayString()) + + Compilation.AssertTheseDiagnostics( BC30001: Statement is not valid in a namespace. System.Console.WriteLine(1) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ) + ) + End Sub) - compilation = CreateCompilationWithMscorlib461({syntaxTree2, syntaxTree1}) - semanticModel1 = compilation.GetSemanticModel(syntaxTree1, True) - semanticModel2 = compilation.GetSemanticModel(syntaxTree2, True) - Assert.Null(semanticModel1.GetSymbolInfo(node1.Name).Symbol) - Assert.Equal("Sub System.Console.WriteLine(value As System.Int32)", semanticModel2.GetSymbolInfo(node2.Name).Symbol.ToTestDisplayString()) + Assert.Throws(Of InvalidOperationException)( + Sub() + Dim compilation = CreateCompilationWithMscorlib461({syntaxTree2, syntaxTree1}) + Dim semanticModel1 = compilation.GetSemanticModel(syntaxTree1, True) + Dim semanticModel2 = compilation.GetSemanticModel(syntaxTree2, True) - compilation.AssertTheseDiagnostics( - + Assert.Null(semanticModel1.GetSymbolInfo(node1.Name).Symbol) + Assert.Equal("Sub System.Console.WriteLine(value As System.Int32)", semanticModel2.GetSymbolInfo(node2.Name).Symbol.ToTestDisplayString()) + + Compilation.AssertTheseDiagnostics( + BC30001: Statement is not valid in a namespace. System.Console.WriteLine(1) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ) + ) + End Sub) End Sub Private Shared Function ErrorTestsGetNode(syntaxTree As SyntaxTree) As MemberAccessExpressionSyntax diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/SyncLockTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/SyncLockTests.vb index e4cd28e142e6d..35ddacc12ef0f 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/SyncLockTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/SyncLockTests.vb @@ -3,8 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/SyntaxTreeRootTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/SyntaxTreeRootTests.vb index 76cdf5c630995..7024c5bc413f6 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/SyntaxTreeRootTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/SyntaxTreeRootTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Reflection -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax @@ -19,7 +18,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Sub SyntaxTreeCreateWithoutCloneAcceptsAnySyntaxNode() Dim node As VisualBasicSyntaxNode = SyntaxFactory.CatchStatement(SyntaxFactory.IdentifierName("Goo"), SyntaxFactory.SimpleAsClause(SyntaxFactory.ParseTypeName(GetType(InvalidOperationException).Name)), Nothing) - Dim tree = VisualBasicSyntaxTree.CreateWithoutClone(node) + Dim tree = VisualBasicSyntaxTree.CreateWithoutClone(node, VisualBasicParseOptions.Default) CheckTree(tree) End Sub diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/TooLongNameTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/TooLongNameTests.vb index 81034904f0467..5ccc6d104b7a4 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/TooLongNameTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/TooLongNameTests.vb @@ -2,15 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.IO -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.SpecialType -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/TypeArgumentInference.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/TypeArgumentInference.vb index d99fd62467c23..2d5ecb893cd0f 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/TypeArgumentInference.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/TypeArgumentInference.vb @@ -2,14 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.IO -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.SpecialType -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/UnaryOperators.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/UnaryOperators.vb index 8e86afaf962dc..742200a0cb8e9 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/UnaryOperators.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/UnaryOperators.vb @@ -2,13 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.IO Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/UnstructuredExceptionHandling.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/UnstructuredExceptionHandling.vb index 4465e54f93784..1c913e2969e16 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/UnstructuredExceptionHandling.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/UnstructuredExceptionHandling.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/UseSiteErrorTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/UseSiteErrorTests.vb index 0ba35cee30ca1..e43e5eac6e72c 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/UseSiteErrorTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/UseSiteErrorTests.vb @@ -2,11 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Xml.Linq +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/UserDefinedBinaryOperators.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/UserDefinedBinaryOperators.vb index ac963587c04ac..27c20a76e79b8 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/UserDefinedBinaryOperators.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/UserDefinedBinaryOperators.vb @@ -2,17 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.IO -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit - Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/UserDefinedConversions.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/UserDefinedConversions.vb index b1ca0bdbd701e..c88b61a4ea52a 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/UserDefinedConversions.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/UserDefinedConversions.vb @@ -2,17 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.IO -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit - Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/UserDefinedForToLoop.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/UserDefinedForToLoop.vb index 66bdbbf15fc80..49a9ba526cb68 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/UserDefinedForToLoop.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/UserDefinedForToLoop.vb @@ -2,17 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.IO -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.SpecialType -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit - Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/UserDefinedUnaryOperators.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/UserDefinedUnaryOperators.vb index 3a365b532dd5e..81b5ed5837498 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/UserDefinedUnaryOperators.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/UserDefinedUnaryOperators.vb @@ -2,17 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.IO -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit - Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/UsingStatementTest.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/UsingStatementTest.vb index bcda5870d0f23..6b6a297f15d20 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/UsingStatementTest.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/UsingStatementTest.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/VariableTypeInference.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/VariableTypeInference.vb index 982c0d2f4d55a..4fcac7c2fe8e9 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/VariableTypeInference.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/VariableTypeInference.vb @@ -2,17 +2,11 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.IO Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit - Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/VarianceConversions.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/VarianceConversions.vb index e09ea35cd5fa3..68846f6f92ee1 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/VarianceConversions.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/VarianceConversions.vb @@ -2,17 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.IO -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.SpecialType -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Basic.Reference.Assemblies +Imports Microsoft.CodeAnalysis.VisualBasic Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/WithBlockErrorTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/WithBlockErrorTests.vb index 4b99c97239cb4..119d28d367229 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/WithBlockErrorTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/WithBlockErrorTests.vb @@ -2,9 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/WithBlockSemanticModelTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/WithBlockSemanticModelTests.vb index 1c3b34604dd1a..f285a1d811b79 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/WithBlockSemanticModelTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/WithBlockSemanticModelTests.vb @@ -2,10 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/XmlLiteralSemanticModelTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/XmlLiteralSemanticModelTests.vb index 0a207e58ee864..5d3c24fc9d1a1 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/XmlLiteralSemanticModelTests.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/XmlLiteralSemanticModelTests.vb @@ -3,10 +3,8 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax - Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Semantic/SourceGeneration/GeneratorDriverTests_Attributes_SimpleName.vb b/src/Compilers/VisualBasic/Test/Semantic/SourceGeneration/GeneratorDriverTests_Attributes_SimpleName.vb index 1188390890653..6233fcfec3309 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/SourceGeneration/GeneratorDriverTests_Attributes_SimpleName.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/SourceGeneration/GeneratorDriverTests_Attributes_SimpleName.vb @@ -4,6 +4,7 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/AssemblyAttributes.vb b/src/Compilers/VisualBasic/Test/Symbol/AssemblyAttributes.vb deleted file mode 100644 index 02f5a0aabbbfb..0000000000000 --- a/src/Compilers/VisualBasic/Test/Symbol/AssemblyAttributes.vb +++ /dev/null @@ -1,6 +0,0 @@ -' Licensed to the .NET Foundation under one or more agreements. -' The .NET Foundation licenses this file to you under the MIT license. -' See the LICENSE file in the project root for more information. - -Imports Xunit - diff --git a/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/ConstructorDocumentationCommentTests.vb b/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/ConstructorDocumentationCommentTests.vb index 630acd8cb0b29..87cb9c56df964 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/ConstructorDocumentationCommentTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/ConstructorDocumentationCommentTests.vb @@ -2,9 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class ConstructorDocumentationCommentTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/DocCommentTests.vb b/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/DocCommentTests.vb index 8d2f0944c2544..ad8505b08ec37 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/DocCommentTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/DocCommentTests.vb @@ -6,6 +6,7 @@ Imports System.Collections.Immutable Imports System.IO Imports System.Text Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE diff --git a/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/EventDocumentationCommentTests.vb b/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/EventDocumentationCommentTests.vb index f190a82f0ce87..5ca7b3e85abc5 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/EventDocumentationCommentTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/EventDocumentationCommentTests.vb @@ -2,9 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/FieldDocumentationCommentTests.vb b/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/FieldDocumentationCommentTests.vb index 17293c24f5725..0ef0f25e43e8d 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/FieldDocumentationCommentTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/FieldDocumentationCommentTests.vb @@ -2,9 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class FieldDocumentationCommentTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/MethodDocumentationCommentTests.vb b/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/MethodDocumentationCommentTests.vb index 9b8cc50b54c4c..91c0713a20c39 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/MethodDocumentationCommentTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/MethodDocumentationCommentTests.vb @@ -2,10 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/PropertyDocumentationCommentTests.vb b/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/PropertyDocumentationCommentTests.vb index bb5678a4a5c1a..19bb797115402 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/PropertyDocumentationCommentTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/PropertyDocumentationCommentTests.vb @@ -2,9 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class PropertyDocumentationCommentTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/TypeDocumentationCommentTests.vb b/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/TypeDocumentationCommentTests.vb index c4e65735c702a..bd4b00916df01 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/TypeDocumentationCommentTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/TypeDocumentationCommentTests.vb @@ -2,9 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class TypeDocumentationCommentTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/StaticLocalDeclarationTests.vb b/src/Compilers/VisualBasic/Test/Symbol/StaticLocalDeclarationTests.vb index 0dcd3aa7a4459..3f6da91f01604 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/StaticLocalDeclarationTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/StaticLocalDeclarationTests.vb @@ -3,12 +3,8 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolDisplay/ObjectDisplayTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolDisplay/ObjectDisplayTests.vb index d4ffd3f83e249..008b21fca5d3e 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolDisplay/ObjectDisplayTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolDisplay/ObjectDisplayTests.vb @@ -5,7 +5,6 @@ Imports System.Globalization Imports System.Threading.Thread Imports Roslyn.Test.Utilities -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolDisplay/SymbolDisplayTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolDisplay/SymbolDisplayTests.vb index 2dd567fc52e14..17bb426aebd2f 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolDisplay/SymbolDisplayTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolDisplay/SymbolDisplayTests.vb @@ -5,15 +5,13 @@ Imports System.Collections.Immutable Imports System.Globalization Imports System.Threading -Imports System.Xml.Linq +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests @@ -6125,7 +6123,7 @@ static class E Dim e = DirectCast(comp.GlobalNamespace.GetMembers("E").Single(), ITypeSymbol) Dim extension = e.GetMembers().OfType(Of ITypeSymbol).Single() - ' Tracked by https://github.com/dotnet/roslyn/issues/76130 : the arity should not be included in the extension type name + ' Tracked by https://github.com/dotnet/roslyn/issues/78957 : public API, the arity should not be included in the extension type name Assert.True(extension.IsExtension) Assert.Equal("E.<>E__0`1(Of T)", SymbolDisplay.ToDisplayString(extension, format)) diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AnonymousDelegates/AnonymousDelegates_CreationAndEmit.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AnonymousDelegates/AnonymousDelegates_CreationAndEmit.vb index 58d1eb502bc6b..0d5bd6e490a59 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AnonymousDelegates/AnonymousDelegates_CreationAndEmit.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AnonymousDelegates/AnonymousDelegates_CreationAndEmit.vb @@ -2,14 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax - -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.AnonymousDelegates diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AnonymousTypes/AnonymousTypesEmittedSymbolsTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AnonymousTypes/AnonymousTypesEmittedSymbolsTests.vb index 81f1a9ee9630c..bed7152e175d8 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AnonymousTypes/AnonymousTypesEmittedSymbolsTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AnonymousTypes/AnonymousTypesEmittedSymbolsTests.vb @@ -3,15 +3,11 @@ ' See the LICENSE file in the project root for more information. Imports System.IO -Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols +Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Syntax - -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.ExtensionMethods diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AnonymousTypes/AnonymousTypesSemanticsTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AnonymousTypes/AnonymousTypesSemanticsTests.vb index e60294355455e..ad801dcd3f6f7 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AnonymousTypes/AnonymousTypesSemanticsTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AnonymousTypes/AnonymousTypesSemanticsTests.vb @@ -4,16 +4,13 @@ Imports System.Collections.Immutable Imports System.Runtime.CompilerServices -Imports System.Xml.Linq +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.ExtensionMethods diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AssemblyAndNamespaceTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AssemblyAndNamespaceTests.vb index 8adfbeb969986..81684af6daf12 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AssemblyAndNamespaceTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AssemblyAndNamespaceTests.vb @@ -2,16 +2,11 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Globalization -Imports System.Text -Imports System.Xml.Linq +Imports System.Collections.Immutable +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities -Imports System.Collections.Immutable Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/CompilationCreationTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/CompilationCreationTests.vb index 6efa81702de30..c9441dd93271a 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/CompilationCreationTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/CompilationCreationTests.vb @@ -4,6 +4,7 @@ Imports System.Collections.Immutable Imports System.Runtime.CompilerServices +Imports Basic.Reference.Assemblies Imports CompilationCreationTestHelpers Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic @@ -11,7 +12,6 @@ Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace CompilationCreationTestHelpers Friend Module Helpers diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/CorLibrary/Choosing.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/CorLibrary/Choosing.vb index 0d1a7a1401345..f1f3f7da92364 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/CorLibrary/Choosing.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/CorLibrary/Choosing.vb @@ -2,18 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Runtime.CompilerServices -Imports CompilationCreationTestHelpers -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata +Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies -Imports VBReferenceManager = Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation.ReferenceManager Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.CorLibrary diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/CustomModifiersTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/CustomModifiersTests.vb index ee0606bec8104..24c1c0b323098 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/CustomModifiersTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/CustomModifiersTests.vb @@ -2,13 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.IO -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/DefaultInterfaceImplementationTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/DefaultInterfaceImplementationTests.vb index 9779ee9c1732d..60d0724294195 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/DefaultInterfaceImplementationTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/DefaultInterfaceImplementationTests.vb @@ -2,14 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.IO -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/ExtensionMethods/AddressOf.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/ExtensionMethods/AddressOf.vb index f327dc0736228..5c02702e851a6 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/ExtensionMethods/AddressOf.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/ExtensionMethods/AddressOf.vb @@ -2,16 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Runtime.CompilerServices -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax - -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols -Imports Roslyn.Test.Utilities - Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.ExtensionMethods Public Class [AddressOf] : Inherits BasicTestBase diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/ExtensionMethods/ExtensionMethodTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/ExtensionMethods/ExtensionMethodTests.vb index 49e5e1a6ca83b..edf43ae8aa6a6 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/ExtensionMethods/ExtensionMethodTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/ExtensionMethods/ExtensionMethodTests.vb @@ -3,13 +3,13 @@ ' See the LICENSE file in the project root for more information. Imports System.IO +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.CSharp Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.ExtensionMethods diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/ExtensionMethods/LookupAndInvocation.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/ExtensionMethods/LookupAndInvocation.vb index 2690cb6ca87d8..f301f0ddf0498 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/ExtensionMethods/LookupAndInvocation.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/ExtensionMethods/LookupAndInvocation.vb @@ -2,14 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Runtime.CompilerServices -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax - -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.ExtensionMethods diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/GenericConstraintTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/GenericConstraintTests.vb index 55c1d3224dc62..242944487d43c 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/GenericConstraintTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/GenericConstraintTests.vb @@ -3,14 +3,10 @@ ' See the LICENSE file in the project root for more information. Imports System.IO -Imports System.Xml.Linq +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/ImplicitClassTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/ImplicitClassTests.vb index 74c051469a34e..5dfd9f2344296 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/ImplicitClassTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/ImplicitClassTests.vb @@ -2,14 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Globalization -Imports System.Text -Imports System.Xml.Linq -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax - Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/InaccessibleOverriding.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/InaccessibleOverriding.vb index ce2f3d2f4998c..473e2bcac8324 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/InaccessibleOverriding.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/InaccessibleOverriding.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities - Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/InstantiatingGenerics.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/InstantiatingGenerics.vb index f9f45a7296ef9..7aa21614c9a73 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/InstantiatingGenerics.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/InstantiatingGenerics.vb @@ -4,11 +4,10 @@ Imports System.Collections.Immutable Imports System.Runtime.CompilerServices +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/InterfaceImplementationTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/InterfaceImplementationTests.vb index 1b2aba8041ca3..3a8da66b63ccd 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/InterfaceImplementationTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/InterfaceImplementationTests.vb @@ -2,8 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/MetadataMemberTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/MetadataMemberTests.vb index 049abad7d07c1..14d36585c2433 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/MetadataMemberTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/MetadataMemberTests.vb @@ -2,10 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports CompilationCreationTestHelpers Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/MetadataTypeTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/MetadataTypeTests.vb index d3c8dd48c4752..a90af00ff2e10 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/MetadataTypeTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/MetadataTypeTests.vb @@ -2,14 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.Immutable -Imports CompilationCreationTestHelpers Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/BaseTypeResolution.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/BaseTypeResolution.vb index f00ec4c76838c..f2df96eb13d55 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/BaseTypeResolution.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/BaseTypeResolution.vb @@ -6,7 +6,6 @@ Imports System.Reflection.Metadata Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Roslyn.Test.Utilities Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/HasUnsupportedMetadata.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/HasUnsupportedMetadata.vb index 3635d0feee84a..1642100ed0123 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/HasUnsupportedMetadata.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/HasUnsupportedMetadata.vb @@ -6,7 +6,6 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadCustomModifiers.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadCustomModifiers.vb index 58edd937fbfc4..aa04917ca16aa 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadCustomModifiers.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadCustomModifiers.vb @@ -2,15 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Runtime.CompilerServices -Imports CompilationCreationTestHelpers Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Roslyn.Test.Utilities Imports Microsoft.CodeAnalysis.CSharp Imports Basic.Reference.Assemblies diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingAttributes.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingAttributes.vb index 9f66c5a2dd717..b8ccf2c4ea73f 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingAttributes.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingAttributes.vb @@ -2,17 +2,11 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Runtime.CompilerServices -Imports CompilationCreationTestHelpers -Imports Microsoft.CodeAnalysis.Collections +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax +Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingEvents.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingEvents.vb index 196ea959d38fb..e42fee50e0629 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingEvents.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingEvents.vb @@ -2,14 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Runtime.CompilerServices -Imports CompilationCreationTestHelpers Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingFields.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingFields.vb index 0f9f4763886ea..1a2675004a296 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingFields.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingFields.vb @@ -2,11 +2,11 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingGenericTypeParameters.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingGenericTypeParameters.vb index b11c05ee6cc3b..246a4bc695279 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingGenericTypeParameters.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingGenericTypeParameters.vb @@ -2,16 +2,11 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Runtime.CompilerServices -Imports CompilationCreationTestHelpers -Imports Microsoft.CodeAnalysis.ImmutableArrayExtensions +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingMethods.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingMethods.vb index c65f740f64d20..bb0e2deb7c1a2 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingMethods.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingMethods.vb @@ -2,17 +2,11 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Runtime.CompilerServices -Imports CompilationCreationTestHelpers -Imports Microsoft.CodeAnalysis.Collections +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingNamespacesAndTypes.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingNamespacesAndTypes.vb index 96d76903989a7..60db37bb9489d 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingNamespacesAndTypes.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingNamespacesAndTypes.vb @@ -4,10 +4,8 @@ Imports System.Collections.Immutable Imports System.IO -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Roslyn.Test.Utilities Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingOperators.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingOperators.vb index 967a5a8928547..747fcf8d52333 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingOperators.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingOperators.vb @@ -3,14 +3,8 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.Globalization -Imports System.Text -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingWithEvents.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingWithEvents.vb index 307bdcc5a00e8..ff88f616e3c8b 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingWithEvents.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingWithEvents.vb @@ -2,15 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Runtime.CompilerServices -Imports CompilationCreationTestHelpers -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/MissingTypeReferences.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/MissingTypeReferences.vb index b1f584f2ccabf..5cc4cc88a1033 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/MissingTypeReferences.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/MissingTypeReferences.vb @@ -3,15 +3,11 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.Runtime.CompilerServices -Imports CompilationCreationTestHelpers +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/NoPia.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/NoPia.vb index 6ca017493d472..c72751f2fc4b0 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/NoPia.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/NoPia.vb @@ -3,11 +3,11 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable +Imports Basic.Reference.Assemblies Imports CompilationCreationTestHelpers -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE Public Class NoPia diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/NoPiaInstantiationOfGenericClassAndStruct.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/NoPiaInstantiationOfGenericClassAndStruct.vb index dc7a529f0b3d8..a1c3499d778c6 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/NoPiaInstantiationOfGenericClassAndStruct.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/NoPiaInstantiationOfGenericClassAndStruct.vb @@ -2,18 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System -Imports System.[Text] -Imports System.Collections.Generic -Imports System.Linq -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Roslyn.Test.Utilities -Imports Xunit -Imports ReferenceManager = Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation.ReferenceManager Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/NoPiaLocalHideAndTypeSubstitutionTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/NoPiaLocalHideAndTypeSubstitutionTests.vb index 499172eeab79f..305e659c9ceb4 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/NoPiaLocalHideAndTypeSubstitutionTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/NoPiaLocalHideAndTypeSubstitutionTests.vb @@ -2,11 +2,12 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports System.Collections.Immutable +Imports System.Runtime.CompilerServices +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities -Imports System.Collections.Immutable -Imports System.Runtime.CompilerServices Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/TypeAccessibility.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/TypeAccessibility.vb index 67e1de062de9c..0388d863c39b8 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/TypeAccessibility.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/TypeAccessibility.vb @@ -2,14 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Runtime.CompilerServices -Imports CompilationCreationTestHelpers -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Roslyn.Test.Utilities Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/TypeKindTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/TypeKindTests.vb index c6d00a5cc13f8..fe74a0140af3c 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/TypeKindTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/TypeKindTests.vb @@ -2,15 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Runtime.CompilerServices -Imports CompilationCreationTestHelpers -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/VisualBasicCompilerFeatureRequiredTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/VisualBasicCompilerFeatureRequiredTests.vb index e375832f5d171..72a2fcb093bee 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/VisualBasicCompilerFeatureRequiredTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/VisualBasicCompilerFeatureRequiredTests.vb @@ -2,12 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeGen -Imports Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.UnitTests -Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/WinMdEventTest.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/WinMdEventTest.vb index af6beadab7886..026e59e5ef634 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/WinMdEventTest.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/WinMdEventTest.vb @@ -2,17 +2,14 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Linq -Imports System.Xml.Linq +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic +Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Basic.Reference.Assemblies Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/WinMdTypeTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/WinMdTypeTests.vb index 134fe73177a93..26d7ba8fcc988 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/WinMdTypeTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/WinMdTypeTests.vb @@ -2,12 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports CompilationCreationTestHelpers -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax +Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/MetadataFileReferenceCompilationTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/MetadataFileReferenceCompilationTests.vb index c24f1fd5344cd..b0cd0cf3eadd2 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/MetadataFileReferenceCompilationTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/MetadataFileReferenceCompilationTests.vb @@ -3,12 +3,12 @@ ' See the LICENSE file in the project root for more information. Imports System.IO +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Public Class MetadataFileReferenceCompilationTests Inherits BasicTestBase diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/MyBaseMyClassSemanticsTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/MyBaseMyClassSemanticsTests.vb index 0632cd6bc32ae..71b4561f86b68 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/MyBaseMyClassSemanticsTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/MyBaseMyClassSemanticsTests.vb @@ -2,18 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Runtime.CompilerServices -Imports System.Xml.Linq -Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols -Imports Roslyn.Test.Utilities - Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.ExtensionMethods Public Class MyBaseMyClassSemanticsTests : Inherits BasicTestBase diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/RelaxedShiftOperatorTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/RelaxedShiftOperatorTests.vb index e6bb4425e4f74..0b4d5d08351b5 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/RelaxedShiftOperatorTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/RelaxedShiftOperatorTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Retargeting/NoPia.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Retargeting/NoPia.vb index 83ac35b4e7814..8a7666dd12d67 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Retargeting/NoPia.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Retargeting/NoPia.vb @@ -3,12 +3,10 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities -Imports System.Xml.Linq -Imports Xunit -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Retargeting Public Class NoPia diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Retargeting/RetargetCustomModifiers.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Retargeting/RetargetCustomModifiers.vb index 7f79ba5106022..480b8f4b930b8 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Retargeting/RetargetCustomModifiers.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Retargeting/RetargetCustomModifiers.vb @@ -2,20 +2,11 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System -Imports System.[Text] -Imports System.Collections.Generic -Imports System.Linq -Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities -Imports Xunit Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Retargeting diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Retargeting/RetargetingCustomAttributes.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Retargeting/RetargetingCustomAttributes.vb index dbc2c52af669e..ee23bedb56f62 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Retargeting/RetargetingCustomAttributes.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Retargeting/RetargetingCustomAttributes.vb @@ -2,22 +2,11 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System -Imports System.[Text] -Imports System.Collections.Generic -Imports System.Linq Imports System.Reflection.Metadata -Imports Microsoft.CodeAnalysis.Collections -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols +Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting Imports Roslyn.Test.Utilities -Imports Xunit -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Retargeting #If Not Retargeting Then diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Retargeting/RetargetingTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Retargeting/RetargetingTests.vb index ff6a4f586de09..daec12f553aa7 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Retargeting/RetargetingTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Retargeting/RetargetingTests.vb @@ -3,13 +3,11 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax +Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols #If Not Retargeting Then @@ -1964,7 +1962,7 @@ MethodOverload(Base) End Sub - + Public Sub Retarget_Events() 'The test involves compilation with/without retargeting and ensuring same behavior at runtime 'same diagnostics (or lack off) as compile time diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/BaseClassTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/BaseClassTests.vb index f5b7afe4c488a..375c0faf175cb 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/BaseClassTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/BaseClassTests.vb @@ -4,8 +4,8 @@ Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols +Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/BindingsTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/BindingsTests.vb index 8c83380829477..f42e625299c36 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/BindingsTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/BindingsTests.vb @@ -3,14 +3,9 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.Globalization -Imports System.Text -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/ComClassTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/ComClassTests.vb index afd619530dfc2..518270c185a1b 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/ComClassTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/ComClassTests.vb @@ -3,10 +3,8 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports System.Text -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/DelegateTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/DelegateTests.vb index 95478e4fc03e0..8d7e580ecb322 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/DelegateTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/DelegateTests.vb @@ -2,10 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/EnumTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/EnumTests.vb index a4482b3c744ee..79e7f64839b26 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/EnumTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/EnumTests.vb @@ -2,15 +2,12 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.Generic Imports System.Text -Imports System.Xml.Linq +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class EnumTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/EventTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/EventTests.vb index 8f8c6fb1c6722..1793afc6c44e0 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/EventTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/EventTests.vb @@ -2,24 +2,13 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Globalization -Imports System.IO Imports System.Reflection -Imports System.Runtime.CompilerServices -Imports System.Runtime.InteropServices -Imports System.Text -Imports System.Xml.Linq +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax - -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata Imports Roslyn.Test.Utilities -Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/FieldTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/FieldTests.vb index 48f0ef7810e97..b4b12ae73682e 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/FieldTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/FieldTests.vb @@ -2,15 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Globalization -Imports System.Text -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/GroupClassTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/GroupClassTests.vb index f14b3515e2b4a..b471113cec16c 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/GroupClassTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/GroupClassTests.vb @@ -2,10 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Roslyn.Test.Utilities Imports Microsoft.CodeAnalysis.Text +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax +Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/ImplementsTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/ImplementsTests.vb index cc212fcd3d323..71e02c1de52e1 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/ImplementsTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/ImplementsTests.vb @@ -2,16 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System -Imports System.Globalization -Imports System.Text -Imports System.Xml.Linq +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax - -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/LocalTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/LocalTests.vb index 06cb6ad8561e8..0d5f470eb2edd 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/LocalTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/LocalTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/MeMyBaseMyClassTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/MeMyBaseMyClassTests.vb index 63b82c5944b97..90bd73361573c 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/MeMyBaseMyClassTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/MeMyBaseMyClassTests.vb @@ -2,8 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Roslyn.Test.Utilities Imports Basic.Reference.Assemblies +Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class MeMyBaseMyClassTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/MethodTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/MethodTests.vb index 8538ef9f98308..e5e9d349cf51a 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/MethodTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/MethodTests.vb @@ -2,17 +2,12 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Globalization -Imports System.Text -Imports System.Xml.Linq +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/NamespaceGlobalTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/NamespaceGlobalTests.vb index 5285ed9761f6e..be385b133839c 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/NamespaceGlobalTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/NamespaceGlobalTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/OperatorsTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/OperatorsTests.vb index 9cfe163bb5f5b..0ac89341326c6 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/OperatorsTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/OperatorsTests.vb @@ -2,14 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Globalization -Imports System.Text -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/OverridesTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/OverridesTests.vb index ea3fecdee78e4..b1857d1f92dce 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/OverridesTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/OverridesTests.vb @@ -2,15 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Globalization -Imports System.Text -Imports System.Xml.Linq +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax - -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/PropertyTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/PropertyTests.vb index f943a8f59ba3b..c96aaa1b58764 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/PropertyTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/PropertyTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/SourceSymbolTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/SourceSymbolTests.vb index d4b5daddb7953..d0c870c5d9593 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/SourceSymbolTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/SourceSymbolTests.vb @@ -2,14 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Globalization -Imports System.Text -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/StaticLocals.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/StaticLocals.vb index 5810924f4835d..e33942ffdfb6b 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/StaticLocals.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/StaticLocals.vb @@ -2,8 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Roslyn.Test.Utilities Imports Basic.Reference.Assemblies +Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/SymbolBindingErrorTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/SymbolBindingErrorTests.vb index 4cdfc422a6d64..3fb56b12acc63 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/SymbolBindingErrorTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/SymbolBindingErrorTests.vb @@ -2,14 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Globalization -Imports System.Text -Imports System.Xml.Linq -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/SyntheticEntryPoint.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/SyntheticEntryPoint.vb index ba8bfbda4e7b8..1fccb2d8d7431 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/SyntheticEntryPoint.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/SyntheticEntryPoint.vb @@ -2,19 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.IO -Imports System.Xml.Linq -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE -Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols -Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/TypeBindingTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/TypeBindingTests.vb index 9a4de505c96a2..ba9e8f651c560 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/TypeBindingTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/TypeBindingTests.vb @@ -2,16 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Globalization -Imports System.Text -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata -Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class TypeBindingTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/TypeSubstitutionTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/TypeSubstitutionTests.vb index fe80cab1a70d3..26c63be5a9997 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/TypeSubstitutionTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/TypeSubstitutionTests.vb @@ -2,14 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Globalization -Imports System.Text -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class TypeSubstitutionTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/TypeTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/TypeTests.vb index 02c20c77f0dfc..30961eee88e0d 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/TypeTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/TypeTests.vb @@ -3,12 +3,11 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/VarianceTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/VarianceTests.vb index 5b16131ae0b63..226c832d25758 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/VarianceTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/VarianceTests.vb @@ -2,16 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Globalization -Imports System.Text -Imports System.Xml.Linq -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols -Imports Roslyn.Test.Utilities - Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class VarianceTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/SymbolErrorTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/SymbolErrorTests.vb index e90975efa3db0..729bd5c0126ec 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/SymbolErrorTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/SymbolErrorTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.Xml.Linq Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/TypedConstantTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/TypedConstantTests.vb index 1d3617bfd1da1..061db9dbf08e5 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/TypedConstantTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/TypedConstantTests.vb @@ -2,13 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System -Imports System.Linq -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/UnboundGenericType.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/UnboundGenericType.vb index 1a31a78a9cfb7..77cdd4517101d 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/UnboundGenericType.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/UnboundGenericType.vb @@ -2,13 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/UnmanagedTypeConstraintTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/UnmanagedTypeConstraintTests.vb index 8730118939182..61b1af56f6f47 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/UnmanagedTypeConstraintTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/UnmanagedTypeConstraintTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.CSharp Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/UnsignedRightShiftTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/UnsignedRightShiftTests.vb index a1fcea40c7585..59cb22fe108b7 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/UnsignedRightShiftTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/UnsignedRightShiftTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/WithStatementSymbolsTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/WithStatementSymbolsTests.vb index 29d9f7aa5570b..463f07b76d9f9 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/WithStatementSymbolsTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/WithStatementSymbolsTests.vb @@ -2,18 +2,12 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Runtime.CompilerServices -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols -Imports Roslyn.Test.Utilities - Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.ExtensionMethods Public Class WithStatementSymbolsTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/XmlLiteralsTests_UseSiteErrors.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/XmlLiteralsTests_UseSiteErrors.vb index 3239b351c3fec..88b90c340c530 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/XmlLiteralsTests_UseSiteErrors.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/XmlLiteralsTests_UseSiteErrors.vb @@ -2,12 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax - -Imports Roslyn.Test.Utilities - Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class XmlLiteralTests diff --git a/src/Compilers/VisualBasic/Test/Symbol/UsedAssembliesTests.vb b/src/Compilers/VisualBasic/Test/Symbol/UsedAssembliesTests.vb index 1672b48ce83ad..8b3ee478fa6d1 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/UsedAssembliesTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/UsedAssembliesTests.vb @@ -3,6 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE @@ -3661,7 +3662,7 @@ public class C3 End Class ", TestOptions.DebugDll.WithGlobalImports(GlobalImport.Parse({"C2.C1"})). - WithSpecificDiagnosticOptions({KeyValuePairUtil.Create("BC40057", ReportDiagnostic.Suppress)}), + WithSpecificDiagnosticOptions({KeyValuePair.Create("BC40057", ReportDiagnostic.Suppress)}), comp0Ref, comp1Ref) Assert.DoesNotContain(comp0Ref, used) Assert.DoesNotContain(comp1Ref, used) @@ -3673,7 +3674,7 @@ public class C3 End Class ", TestOptions.DebugDll.WithGlobalImports(GlobalImport.Parse({"alias1 = C2.C1"})). - WithSpecificDiagnosticOptions({KeyValuePairUtil.Create("BC40057", ReportDiagnostic.Suppress)}), + WithSpecificDiagnosticOptions({KeyValuePair.Create("BC40057", ReportDiagnostic.Suppress)}), comp0Ref, comp1Ref) Assert.DoesNotContain(comp0Ref, used) Assert.DoesNotContain(comp1Ref, used) diff --git a/src/Compilers/VisualBasic/Test/Syntax/IncrementalParser/IPEndBlockStatements.vb b/src/Compilers/VisualBasic/Test/Syntax/IncrementalParser/IPEndBlockStatements.vb index c6c6b64a70a05..aaba2180fc089 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/IncrementalParser/IPEndBlockStatements.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/IncrementalParser/IPEndBlockStatements.vb @@ -2,15 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.ObjectModel -Imports System.Text -Imports System.Xml.Linq -Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Public Class IPEndBlockStatements diff --git a/src/Compilers/VisualBasic/Test/Syntax/IncrementalParser/IncrementalParser.vb b/src/Compilers/VisualBasic/Test/Syntax/IncrementalParser/IncrementalParser.vb index 404ece89d4031..7e75286a4c0ef 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/IncrementalParser/IncrementalParser.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/IncrementalParser/IncrementalParser.vb @@ -2,15 +2,12 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.ObjectModel Imports System.Text -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Syntax/IncrementalParser/SyntaxDifferences.vb b/src/Compilers/VisualBasic/Test/Syntax/IncrementalParser/SyntaxDifferences.vb index 47401b17f121a..c4d239c2984bf 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/IncrementalParser/SyntaxDifferences.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/IncrementalParser/SyntaxDifferences.vb @@ -2,13 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.Generic Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Friend Module SyntaxDifferences diff --git a/src/Compilers/VisualBasic/Test/Syntax/Parser/DeclarationTests.vb b/src/Compilers/VisualBasic/Test/Syntax/Parser/DeclarationTests.vb index a6acc119a024c..ce12d658b7e8d 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Parser/DeclarationTests.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Parser/DeclarationTests.vb @@ -5,10 +5,7 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Xunit Public Class DeclarationTests Private Function ParseFile(text As String) As SyntaxTree diff --git a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseAsyncTests.vb b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseAsyncTests.vb index e20975b714622..81a0f20e7cc0c 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseAsyncTests.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseAsyncTests.vb @@ -2,11 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Roslyn.Test.Utilities Public Class ParseAsyncTests Inherits BasicTestBase diff --git a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseAttributes.vb b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseAttributes.vb index 384438c4062e6..6b1f48e6422b7 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseAttributes.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseAttributes.vb @@ -2,9 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseDirectives.vb b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseDirectives.vb index 0be09606b3f53..be8e2664a809e 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseDirectives.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseDirectives.vb @@ -2,8 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports System.Collections.Generic Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic @@ -1573,7 +1575,7 @@ BC30059: Constant expression is required. Public Sub ParseProjConstsCaseInsensitivity() - Dim psymbols = ImmutableArray.Create({Roslyn.Utilities.KeyValuePairUtil.Create("Blah", CObj(False)), Roslyn.Utilities.KeyValuePairUtil.Create("blah", CObj(True))}) + Dim psymbols = ImmutableArray.Create({KeyValuePair.Create("Blah", CObj(False)), KeyValuePair.Create("blah", CObj(True))}) Dim options As VisualBasicParseOptions = VisualBasicParseOptions.Default.WithPreprocessorSymbols(psymbols) diff --git a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseErrorTests.vb b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseErrorTests.vb index fb5b58ed33284..94b058e218a10 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseErrorTests.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseErrorTests.vb @@ -3,10 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseExpression.vb b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseExpression.vb index 9626ce916a768..6e0e67f4308f1 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseExpression.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseExpression.vb @@ -4,11 +4,9 @@ Imports System.Globalization Imports System.Text -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseImports.vb b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseImports.vb index 040d26e79d113..0a3f0af763ff2 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseImports.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseImports.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseIteratorTests.vb b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseIteratorTests.vb index 878771d650a0e..fb348badc418f 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseIteratorTests.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseIteratorTests.vb @@ -2,11 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Roslyn.Test.Utilities Public Class ParseIteratorTests Inherits BasicTestBase diff --git a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseLanguageVersionTests.vb b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseLanguageVersionTests.vb index cd9b325fa5fcd..5886cf47709b1 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseLanguageVersionTests.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseLanguageVersionTests.vb @@ -2,11 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Roslyn.Test.Utilities - Public Class ParseLanguageVersionTests Inherits BasicTestBase diff --git a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseMethods.vb b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseMethods.vb index 9e8409300f6b4..9e319f4cc85cc 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseMethods.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseMethods.vb @@ -2,9 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseStatements.vb b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseStatements.vb index b7918d81b916f..e0f6bdc8ecf71 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseStatements.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseStatements.vb @@ -3,9 +3,8 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Text +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseVarDecl.vb b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseVarDecl.vb index e92ace2856ac0..71876ebc599d7 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseVarDecl.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParseVarDecl.vb @@ -2,9 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParserRegressionTests.vb b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParserRegressionTests.vb index cb66eb6f17b9a..7712eff4845e5 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParserRegressionTests.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParserRegressionTests.vb @@ -3,11 +3,11 @@ ' See the LICENSE file in the project root for more information. Imports System.IO +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Text Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.Syntax -Imports Basic.Reference.Assemblies Public Class ParserRegressionTests : Inherits BasicTestBase diff --git a/src/Compilers/VisualBasic/Test/Syntax/Parser/VisualBasicParseOptionsTests.vb b/src/Compilers/VisualBasic/Test/Syntax/Parser/VisualBasicParseOptionsTests.vb index 63c4e1c528a9c..1b8d63e45682d 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Parser/VisualBasicParseOptionsTests.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Parser/VisualBasicParseOptionsTests.vb @@ -4,7 +4,6 @@ Imports System.Collections.Immutable Imports System.Globalization -Imports System.Linq Imports Roslyn.Test.Utilities Public Class VisualBasicParseOptionsTests diff --git a/src/Compilers/VisualBasic/Test/Syntax/Parser/XmlDocComments.vb b/src/Compilers/VisualBasic/Test/Syntax/Parser/XmlDocComments.vb index 71f2983de47ef..b8f8f2ac8d20b 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Parser/XmlDocComments.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Parser/XmlDocComments.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Syntax/PreprocessorEETests.vb b/src/Compilers/VisualBasic/Test/Syntax/PreprocessorEETests.vb index 47cdf903ff821..e47bab78a32b8 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/PreprocessorEETests.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/PreprocessorEETests.vb @@ -3,12 +3,8 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.Xml.Linq -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Imports Roslyn.Test.Utilities -Imports ERRID = Microsoft.CodeAnalysis.VisualBasic.ERRID Public Class PreprocessorEETests diff --git a/src/Compilers/VisualBasic/Test/Syntax/QuickTokenTableTests.vb b/src/Compilers/VisualBasic/Test/Syntax/QuickTokenTableTests.vb index 8a6d106993a53..0ad98be58742a 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/QuickTokenTableTests.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/QuickTokenTableTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Text Imports InternalSyntax = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax diff --git a/src/Compilers/VisualBasic/Test/Syntax/Scanner/ScanConditionalTests.vb b/src/Compilers/VisualBasic/Test/Syntax/Scanner/ScanConditionalTests.vb index 8d8ee69774e80..a369392858300 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Scanner/ScanConditionalTests.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Scanner/ScanConditionalTests.vb @@ -2,10 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Public Class ScanConditionalTests diff --git a/src/Compilers/VisualBasic/Test/Syntax/Scanner/ScanErrorTests.vb b/src/Compilers/VisualBasic/Test/Syntax/Scanner/ScanErrorTests.vb index 5c37e49caee0f..34fdcb6ff61f4 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Scanner/ScanErrorTests.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Scanner/ScanErrorTests.vb @@ -3,10 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Syntax/Scanner/ScannerTests.vb b/src/Compilers/VisualBasic/Test/Syntax/Scanner/ScannerTests.vb index 560e9d39a216b..befdbd2e6f8d4 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Scanner/ScannerTests.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Scanner/ScannerTests.vb @@ -5,6 +5,7 @@ Imports System.Runtime.CompilerServices Imports System.Threading.Thread Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Compilers/VisualBasic/Test/Syntax/Scanner/XmlScannerTests.vb b/src/Compilers/VisualBasic/Test/Syntax/Scanner/XmlScannerTests.vb index 71e049920925f..5b9303b406e63 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Scanner/XmlScannerTests.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Scanner/XmlScannerTests.vb @@ -2,10 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Syntax/Syntax/GeneratedTests.vb b/src/Compilers/VisualBasic/Test/Syntax/Syntax/GeneratedTests.vb index cebf4911c7448..baea550498370 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Syntax/GeneratedTests.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Syntax/GeneratedTests.vb @@ -2,12 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Imports Roslyn.Test.Utilities -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Syntax/Syntax/ManualTests.vb b/src/Compilers/VisualBasic/Test/Syntax/Syntax/ManualTests.vb index a008c7148b9e8..16ec359c443e3 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Syntax/ManualTests.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Syntax/ManualTests.vb @@ -3,10 +3,8 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Syntax/Syntax/SeparatedSyntaxListTests.vb b/src/Compilers/VisualBasic/Test/Syntax/Syntax/SeparatedSyntaxListTests.vb index 4283450b7c302..0a189991a39b9 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Syntax/SeparatedSyntaxListTests.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Syntax/SeparatedSyntaxListTests.vb @@ -2,15 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System -Imports System.Collections.Generic -Imports System.Linq -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Roslyn.Test.Utilities -Imports Xunit - Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SeparatedSyntaxListTests diff --git a/src/Compilers/VisualBasic/Test/Syntax/Syntax/StatementSyntaxWalkerTests.vb b/src/Compilers/VisualBasic/Test/Syntax/Syntax/StatementSyntaxWalkerTests.vb index a49116e52d6fe..9e5b79d74a466 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Syntax/StatementSyntaxWalkerTests.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Syntax/StatementSyntaxWalkerTests.vb @@ -3,10 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.IO -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxAnnotationTests.vb b/src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxAnnotationTests.vb index bd5d369403514..0172136cff607 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxAnnotationTests.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxAnnotationTests.vb @@ -2,15 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System -Imports System.Collections.Generic -Imports System.Linq Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Roslyn.Test.Utilities -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SyntaxAnnotationTests diff --git a/src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxFactoryTests.vb b/src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxFactoryTests.vb index 62f091c35ccd5..bb08faf2730a6 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxFactoryTests.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxFactoryTests.vb @@ -123,5 +123,16 @@ Integer Dim type2 = SyntaxFactory.ParseTypeName(code, options:=options) Assert.Equal("Integer", type2.ToString()) End Sub + + + Public Shared Sub TestParseMethodsKeepParseOptionsInTheTree() + Dim parseOptions = VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.Latest) + + Dim compUnit = SyntaxFactory.ParseCompilationUnit("", options:=parseOptions) + Assert.Same(parseOptions, compUnit.SyntaxTree.Options) + + Dim typeName = SyntaxFactory.ParseTypeName("", options:=parseOptions) + Assert.Same(parseOptions, typeName.SyntaxTree.Options) + End Sub End Class End Namespace diff --git a/src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxFactsTest.vb b/src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxFactsTest.vb index 0c1d011590a7e..886200c2d924e 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxFactsTest.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxFactsTest.vb @@ -6,6 +6,7 @@ Imports System.IO Imports System.Reflection Imports System.Text Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxListTests.vb b/src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxListTests.vb index 1b5e8f3d3f983..a852167ed290a 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxListTests.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxListTests.vb @@ -2,6 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities diff --git a/src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxNormalizerTests.vb b/src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxNormalizerTests.vb index 24af54449684d..864cfa958392e 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxNormalizerTests.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxNormalizerTests.vb @@ -2,16 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System -Imports System.Collections.Generic -Imports System.Linq -Imports System.Text Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests diff --git a/src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxTokenFactoryTests.vb b/src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxTokenFactoryTests.vb index 021b50fa09b69..e6460b7a7e511 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxTokenFactoryTests.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxTokenFactoryTests.vb @@ -2,12 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System -Imports System.Xml.Linq -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SyntaxTokenFactoryTests diff --git a/src/Compilers/VisualBasic/Test/Syntax/TestSyntaxNodes.vb b/src/Compilers/VisualBasic/Test/Syntax/TestSyntaxNodes.vb index 48cefb811e57b..e0e13f4e83de2 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/TestSyntaxNodes.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/TestSyntaxNodes.vb @@ -5,6 +5,7 @@ Imports System.Globalization Imports System.Text Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Syntax Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Compilers/VisualBasic/vbc/VbcCommandLine.projitems b/src/Compilers/VisualBasic/vbc/VbcCommandLine.projitems index 0ac1959f91e31..aab4e9fe23999 100644 --- a/src/Compilers/VisualBasic/vbc/VbcCommandLine.projitems +++ b/src/Compilers/VisualBasic/vbc/VbcCommandLine.projitems @@ -18,15 +18,15 @@ CommandLine - - - - - - + + + + + + diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/FixedSizeArrayBuilder.cs b/src/Dependencies/Collections/Extensions/FixedSizeArrayBuilder.cs similarity index 79% rename from src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/FixedSizeArrayBuilder.cs rename to src/Dependencies/Collections/Extensions/FixedSizeArrayBuilder.cs index 7ed172ae159a9..d2275f21a986b 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/FixedSizeArrayBuilder.cs +++ b/src/Dependencies/Collections/Extensions/FixedSizeArrayBuilder.cs @@ -5,6 +5,10 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.PooledObjects; @@ -45,32 +49,46 @@ internal struct FixedSizeArrayBuilder(int capacity) public void Add(T value) => _values[_index++] = value; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ThrowIfTrue([DoesNotReturnIf(parameterValue: true)] bool condition, [CallerLineNumber] int lineNumber = 0, [CallerFilePath] string? filePath = null) + { +#if MICROSOFT_CODEANALYSIS_CONTRACTS_NO_CONTRACT + if (condition) + { + var fileName = filePath is null ? null : Path.GetFileName(filePath); + throw new InvalidOperationException($"Unexpected true - file {fileName} line {lineNumber}"); + } +#else + Contract.ThrowIfTrue(condition, lineNumber, filePath); +#endif + } + #region AddRange overloads. These allow us to add these collections directly, without allocating an enumerator. public void AddRange(ImmutableArray values) { - Contract.ThrowIfTrue(_index + values.Length > _values.Length); + ThrowIfTrue(_index + values.Length > _values.Length); Array.Copy(ImmutableCollectionsMarshal.AsArray(values)!, 0, _values, _index, values.Length); _index += values.Length; } public void AddRange(List values) { - Contract.ThrowIfTrue(_index + values.Count > _values.Length); + ThrowIfTrue(_index + values.Count > _values.Length); foreach (var v in values) Add(v); } public void AddRange(HashSet values) { - Contract.ThrowIfTrue(_index + values.Count > _values.Length); + ThrowIfTrue(_index + values.Count > _values.Length); foreach (var v in values) Add(v); } public void AddRange(ArrayBuilder values) { - Contract.ThrowIfTrue(_index + values.Count > _values.Length); + ThrowIfTrue(_index + values.Count > _values.Length); foreach (var v in values) Add(v); } @@ -104,7 +122,7 @@ public ImmutableArray MoveToImmutable() public T[] MoveToArray() { - Contract.ThrowIfTrue(_index != _values.Length); + ThrowIfTrue(_index != _values.Length); var result = _values; _values = []; _index = 0; diff --git a/src/Dependencies/Collections/Extensions/ICollectionExtensions.cs b/src/Dependencies/Collections/Extensions/ICollectionExtensions.cs index b6fd40d078d78..af742ad87cf0c 100644 --- a/src/Dependencies/Collections/Extensions/ICollectionExtensions.cs +++ b/src/Dependencies/Collections/Extensions/ICollectionExtensions.cs @@ -4,7 +4,6 @@ #nullable enable -using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Dependencies/Collections/Extensions/IEnumerableExtensions.cs b/src/Dependencies/Collections/Extensions/IEnumerableExtensions.cs index 144d037776595..d35fe59339b78 100644 --- a/src/Dependencies/Collections/Extensions/IEnumerableExtensions.cs +++ b/src/Dependencies/Collections/Extensions/IEnumerableExtensions.cs @@ -17,23 +17,15 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; namespace Roslyn.Utilities { + /// + /// Enumerable extensions that are not polyfills or variants of existing APIs defined in System.* namespaces. + /// internal static partial class EnumerableExtensions { - public static int Count(this IEnumerable source, Func predicate, TArg arg) - { - var count = 0; - foreach (var v in source) - { - if (predicate(v, arg)) - count++; - } - - return count; - } - public static IEnumerable Do(this IEnumerable source, Action action) { if (source == null) @@ -110,26 +102,6 @@ public static ReadOnlyCollection ToReadOnlyCollection(this IEnumerable return new ReadOnlyCollection(source.ToList()); } - public static IEnumerable Concat(this IEnumerable source, T value) - { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - - return source.ConcatWorker(value); - } - - private static IEnumerable ConcatWorker(this IEnumerable source, T value) - { - foreach (var v in source) - { - yield return v; - } - - yield return value; - } - public static bool SetEquals(this IEnumerable source1, IEnumerable source2, IEqualityComparer? comparer) { if (source1 == null) @@ -183,90 +155,33 @@ public static ISet ToSet(this IEnumerable source) public static IReadOnlyCollection ToCollection(this IEnumerable sequence) => (sequence is IReadOnlyCollection collection) ? collection : sequence.ToList(); - public static T? FirstOrDefault(this IEnumerable source, Func predicate, TArg arg) - { - foreach (var item in source) - { - if (predicate(item, arg)) - return item; - } - - return default; - } - - public static bool Any(this IEnumerable source, Func predicate, TArg arg) - { - foreach (var item in source) - { - if (predicate(item, arg)) - return true; - } - - return false; - } - public static T? FirstOrNull(this IEnumerable source) where T : struct { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - return source.Cast().FirstOrDefault(); } public static T? FirstOrNull(this IEnumerable source, Func predicate) where T : struct { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - - if (predicate == null) - { - throw new ArgumentNullException(nameof(predicate)); - } - return source.Cast().FirstOrDefault(static (v, predicate) => predicate(v!.Value), predicate); } public static T? FirstOrNull(this IEnumerable source, Func predicate, TArg arg) where T : struct { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - - if (predicate == null) - { - throw new ArgumentNullException(nameof(predicate)); - } - return source.Cast().FirstOrDefault(static (v, arg) => arg.predicate(v!.Value, arg.arg), (predicate, arg)); } public static T? LastOrNull(this IEnumerable source) where T : struct { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - return source.Cast().LastOrDefault(); } public static T? SingleOrNull(this IEnumerable source, Func predicate) where T : struct { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - return source.Cast().SingleOrDefault(v => predicate(v!.Value)); } @@ -621,24 +536,6 @@ public static async ValueTask> SelectManyInParallelAsync selector(item, cancellationToken))).ConfigureAwait(false)).Flatten(); } - public static bool All(this IEnumerable source) - { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - - foreach (var b in source) - { - if (!b) - { - return false; - } - } - - return true; - } - public static int IndexOf(this IEnumerable sequence, T value) { return sequence switch @@ -697,50 +594,6 @@ public static IEnumerable Flatten(this IEnumerable> sequenc return sequence.SelectMany(s => s); } - public static IOrderedEnumerable OrderBy(this IEnumerable source, IComparer? comparer) - { - return source.OrderBy(Functions.Identity, comparer); - } - - public static IOrderedEnumerable OrderByDescending(this IEnumerable source, IComparer? comparer) - { - return source.OrderByDescending(Functions.Identity, comparer); - } - - public static IOrderedEnumerable OrderBy(this IEnumerable source, Comparison compare) - { - return source.OrderBy(Comparer.Create(compare)); - } - - public static IOrderedEnumerable OrderByDescending(this IEnumerable source, Comparison compare) - { - return source.OrderByDescending(Comparer.Create(compare)); - } - -#if NET8_0_OR_GREATER - public static IOrderedEnumerable Order(IEnumerable source) where T : IComparable -#else - public static IOrderedEnumerable Order(this IEnumerable source) where T : IComparable -#endif - { - return source.OrderBy(Comparer.Default); - } - - public static IOrderedEnumerable ThenBy(this IOrderedEnumerable source, IComparer? comparer) - { - return source.ThenBy(Functions.Identity, comparer); - } - - public static IOrderedEnumerable ThenBy(this IOrderedEnumerable source, Comparison compare) - { - return source.ThenBy(Comparer.Create(compare)); - } - - public static IOrderedEnumerable ThenBy(this IOrderedEnumerable source) where T : IComparable - { - return source.ThenBy(Comparer.Default); - } - public static bool IsSorted(this IEnumerable enumerable, IComparer? comparer = null) { using var e = enumerable.GetEnumerator(); @@ -765,29 +618,6 @@ public static bool IsSorted(this IEnumerable enumerable, IComparer? com return true; } - public static bool Contains(this IEnumerable sequence, Func predicate) - { - return sequence.Any(predicate); - } - - public static bool Contains(this IEnumerable sequence, string? s) - { - foreach (var item in sequence) - { - if (item == s) - { - return true; - } - } - - return false; - } - - public static IComparer ToComparer(this Comparison comparison) - { - return Comparer.Create(comparison); - } - public static ImmutableDictionary ToImmutableDictionaryOrEmpty(this IEnumerable>? items) where K : notnull { @@ -932,13 +762,122 @@ internal static class Predicates namespace System.Linq { - /// - /// Declare the following extension methods in System.Linq namespace to avoid accidental boxing of ImmutableArray{T} that implements IEnumerable{T}. - /// The boxing would occur if the methods were defined in Roslyn.Utilities and the file calling these methods has using Roslyn.Utilities - /// but not using System.Linq. - /// - internal static class EnumerableExtensions + /// + /// Defines polyfill methods and overloads or alternative names of existing methods defined in System.Linq. + /// + /// Methods that are available on both and are defined in System.Linq namespace + /// to avoid accidental boxing of . The boxing would occur if the file calling these methods didn't have using System.Linq. + /// + internal static class RoslynEnumerableExtensions { + /// + /// Alias for + /// + public static bool Contains(this IEnumerable sequence, Func predicate) + => sequence.Any(predicate); + + /// + /// Variant of + /// + public static int Count(this IEnumerable source, Func predicate, TArg arg) + { + var count = 0; + foreach (var v in source) + { + if (predicate(v, arg)) + count++; + } + + return count; + } + + /// + /// Variant of + /// + public static T? FirstOrDefault(this IEnumerable source, Func predicate, TArg arg) + { + foreach (var item in source) + { + if (predicate(item, arg)) + return item; + } + + return default; + } + + /// + /// Variant of + /// + public static bool Any(this IEnumerable source, Func predicate, TArg arg) + { + foreach (var item in source) + { + if (predicate(item, arg)) + return true; + } + + return false; + } + + /// + /// Variant of + /// + public static IOrderedEnumerable OrderBy(this IEnumerable source, IComparer? comparer) + => source.OrderBy(Functions.Identity, comparer); + + /// + /// Variant of + /// + public static IOrderedEnumerable OrderByDescending(this IEnumerable source, IComparer? comparer) + => source.OrderByDescending(Functions.Identity, comparer); + + /// + /// Variant of + /// + public static IOrderedEnumerable OrderBy(this IEnumerable source, Comparison compare) + => source.OrderBy(Comparer.Create(compare)); + + /// + /// Variant of + /// + public static IOrderedEnumerable OrderByDescending(this IEnumerable source, Comparison compare) + => source.OrderByDescending(Comparer.Create(compare)); + + /// + /// Variant of + /// + public static IOrderedEnumerable ThenBy(this IOrderedEnumerable source, IComparer? comparer) + => source.ThenBy(Functions.Identity, comparer); + + /// + /// Variant of + /// + public static IOrderedEnumerable ThenBy(this IOrderedEnumerable source, Comparison compare) + => source.ThenBy(Comparer.Create(compare)); + +#if NET8_0_OR_GREATER + public static IOrderedEnumerable Order(IEnumerable source) where T : IComparable +#else + public static IOrderedEnumerable Order(this IEnumerable source) where T : IComparable +#endif + => source.OrderBy(Comparer.Default); + + /// + /// Variant of . + /// + public static IEnumerable Concat(this IEnumerable source, T value) + { + foreach (var v in source) + { + yield return v; + } + + yield return value; + } + + /// + /// Variant of + /// public static bool SequenceEqual(this IEnumerable? first, IEnumerable? second, Func comparer) { if (first == second) @@ -971,6 +910,10 @@ public static bool SequenceEqual(this IEnumerable? first, IEnumerable? return true; } + /// + /// Variant of + /// that does not throw on empty . + /// public static T? AggregateOrDefault(this IEnumerable source, Func func) { using (var e = source.GetEnumerator()) @@ -1089,6 +1032,35 @@ private static IEnumerable EnumerableChunkIterator(IEnumerab } } +#endif + +#if NET9_0_OR_GREATER + public static IEnumerable<(int Index, TSource Item)> Index(IEnumerable source) + => Enumerable.Index(source); +#else + /// Returns an enumerable that incorporates the element's index into a tuple. + /// The type of the elements of . + /// The source enumerable providing the elements. + /// An enumerable that incorporates each element index into a tuple. + /// is . + public static IEnumerable<(int Index, TSource Item)> Index(this IEnumerable source) + { + return source is TSource[] { Length: 0 } ? [] : IndexIterator(source); + + static IEnumerable<(int Index, TSource Item)> IndexIterator(IEnumerable source) + { + int index = -1; + foreach (TSource element in source) + { + checked + { + index++; + } + + yield return (index, element); + } + } + } #endif } } diff --git a/src/Dependencies/Collections/Extensions/ImmutableArrayExtensions.cs b/src/Dependencies/Collections/Extensions/ImmutableArrayExtensions.cs index 21f358a580b0a..7303c2d73f428 100644 --- a/src/Dependencies/Collections/Extensions/ImmutableArrayExtensions.cs +++ b/src/Dependencies/Collections/Extensions/ImmutableArrayExtensions.cs @@ -9,18 +9,14 @@ using System.Collections.Immutable; using System.Diagnostics; using System.IO; +using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Collections; -using Roslyn.Utilities; -using Microsoft.CodeAnalysis.Shared.Collections; - -#if DEBUG -using System.Linq; -#endif +using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { @@ -189,13 +185,13 @@ public static ImmutableArray SelectAsArray(this I return ImmutableArray.Create(map(items[0], 0, arg), map(items[1], 1, arg), map(items[2], 2, arg), map(items[3], 3, arg)); default: - var builder = ArrayBuilder.GetInstance(items.Length); + var builder = new FixedSizeArrayBuilder(items.Length); for (int i = 0; i < items.Length; i++) { builder.Add(map(items[i], i, arg)); } - return builder.ToImmutableAndFree(); + return builder.MoveToImmutable(); } } @@ -522,12 +518,13 @@ public static ImmutableArray ZipAsArray(this Imm return ImmutableArray.Empty; } - var builder = ArrayBuilder.GetInstance(self.Length); + var builder = new FixedSizeArrayBuilder(self.Length); for (int i = 0; i < self.Length; i++) { builder.Add(map(self[i], other[i], i, arg)); } - return builder.ToImmutableAndFree(); + + return builder.MoveToImmutable(); } /// @@ -615,38 +612,6 @@ private static ImmutableArray WhereAsArrayImpl(ImmutableArray arr } } - public static bool Any(this ImmutableArray array, Func predicate, TArg arg) - { - int n = array.Length; - for (int i = 0; i < n; i++) - { - var a = array[i]; - - if (predicate(a, arg)) - { - return true; - } - } - - return false; - } - - public static bool All(this ImmutableArray array, Func predicate, TArg arg) - { - int n = array.Length; - for (int i = 0; i < n; i++) - { - var a = array[i]; - - if (!predicate(a, arg)) - { - return false; - } - } - - return true; - } - public static async Task AnyAsync(this ImmutableArray array, Func> predicateAsync) { int n = array.Length; @@ -695,45 +660,6 @@ public static async Task AnyAsync(this ImmutableArray array, F return default; } - public static TValue? FirstOrDefault(this ImmutableArray array, Func predicate, TArg arg) - { - foreach (var val in array) - { - if (predicate(val, arg)) - { - return val; - } - } - - return default; - } - - public static TValue Single(this ImmutableArray array, Func predicate, TArg arg) - { - var hasValue = false; - TValue? value = default; - foreach (var item in array) - { - if (predicate(item, arg)) - { - if (hasValue) - { - throw ExceptionUtilities.Unreachable(); - } - - value = item; - hasValue = true; - } - } - - if (!hasValue) - { - throw ExceptionUtilities.Unreachable(); - } - - return value!; - } - /// /// Casts the immutable array of a Type to an immutable array of its base type. /// @@ -808,34 +734,6 @@ public static ImmutableArray NullToEmpty(this ImmutableArray? array) { } underlying => underlying }; - /// - /// Returns an array of distinct elements, preserving the order in the original array. - /// If the array has no duplicates, the original array is returned. The original array must not be null. - /// - public static ImmutableArray Distinct(this ImmutableArray array, IEqualityComparer? comparer = null) - { - Debug.Assert(!array.IsDefault); - - if (array.Length < 2) - { - return array; - } - - var set = new HashSet(comparer); - var builder = ArrayBuilder.GetInstance(); - foreach (var a in array) - { - if (set.Add(a)) - { - builder.Add(a); - } - } - - var result = (builder.Count == array.Length) ? array : builder.ToImmutable(); - builder.Free(); - return result; - } - // In DEBUG, swap the first and last elements of a read-only array, yielding a new read only array. // This helps to avoid depending on accidentally sorted arrays. internal static ImmutableArray ConditionallyDeOrder(this ImmutableArray array) @@ -881,138 +779,6 @@ internal static ImmutableArray Flatten( return builder.ToImmutableAndFree(); } - internal static ImmutableArray Concat(this ImmutableArray first, ImmutableArray second) - { - return first.AddRange(second); - } - - internal static ImmutableArray Concat(this ImmutableArray first, ImmutableArray second, ImmutableArray third) - { - var builder = new T[first.Length + second.Length + third.Length]; - var index = 0; - - foreach (var item in first) - { - builder[index++] = item; - } - - foreach (var item in second) - { - builder[index++] = item; - } - - foreach (var item in third) - { - builder[index++] = item; - } - - return ImmutableCollectionsMarshal.AsImmutableArray(builder); - } - - internal static ImmutableArray Concat(this ImmutableArray first, ImmutableArray second, ImmutableArray third, ImmutableArray fourth) - { - var builder = new T[first.Length + second.Length + third.Length + fourth.Length]; - var index = 0; - - foreach (var item in first) - { - builder[index++] = item; - } - - foreach (var item in second) - { - builder[index++] = item; - } - - foreach (var item in third) - { - builder[index++] = item; - } - - foreach (var item in fourth) - { - builder[index++] = item; - } - - return ImmutableCollectionsMarshal.AsImmutableArray(builder); - } - - internal static ImmutableArray Concat(this ImmutableArray first, ImmutableArray second, ImmutableArray third, ImmutableArray fourth, ImmutableArray fifth) - { - var builder = new T[first.Length + second.Length + third.Length + fourth.Length + fifth.Length]; - var index = 0; - - foreach (var item in first) - { - builder[index++] = item; - } - - foreach (var item in second) - { - builder[index++] = item; - } - - foreach (var item in third) - { - builder[index++] = item; - } - - foreach (var item in fourth) - { - builder[index++] = item; - } - - foreach (var item in fifth) - { - builder[index++] = item; - } - - return ImmutableCollectionsMarshal.AsImmutableArray(builder); - } - - internal static ImmutableArray Concat(this ImmutableArray first, ImmutableArray second, ImmutableArray third, ImmutableArray fourth, ImmutableArray fifth, ImmutableArray sixth) - { - var builder = new T[first.Length + second.Length + third.Length + fourth.Length + fifth.Length + sixth.Length]; - var index = 0; - - foreach (var item in first) - { - builder[index++] = item; - } - - foreach (var item in second) - { - builder[index++] = item; - } - - foreach (var item in third) - { - builder[index++] = item; - } - - foreach (var item in fourth) - { - builder[index++] = item; - } - - foreach (var item in fifth) - { - builder[index++] = item; - } - - foreach (var item in sixth) - { - builder[index++] = item; - } - - return ImmutableCollectionsMarshal.AsImmutableArray(builder); - } - - internal static ImmutableArray Concat(this ImmutableArray first, T second) - { - return first.Add(second); - } - internal static ImmutableArray AddRange(this ImmutableArray self, in TemporaryArray items) { if (items.Count == 0) @@ -1088,43 +854,6 @@ internal static bool HasDuplicates(this ImmutableArray arr } } - public static int Count(this ImmutableArray items, Func predicate) - { - if (items.IsEmpty) - { - return 0; - } - - int count = 0; - for (int i = 0; i < items.Length; ++i) - { - if (predicate(items[i])) - { - ++count; - } - } - - return count; - } - - public static int Sum(this ImmutableArray items, Func selector) - { - var sum = 0; - foreach (var item in items) - sum += selector(item); - - return sum; - } - - public static int Sum(this ImmutableArray items, Func selector) - { - var sum = 0; - for (var i = 0; i < items.Length; i++) - sum += selector(items[i], i); - - return sum; - } - internal static void AddToMultiValueDictionaryBuilder(Dictionary accumulator, K key, T item) where K : notnull where T : notnull @@ -1244,28 +973,19 @@ static ImmutableArray getOrCreateNamedTypes(ImmutableArray(this ImmutableArray array1, ImmutableArray array2, TArg arg, Func predicate) - { - // The framework implementation of SequenceEqual forces a NullRef for default array1 and 2, so we - // maintain the same behavior in this extension - if (array1.IsDefault) - { - throw new NullReferenceException(); - } + internal static int IndexOf(this ImmutableArray array, T item, IEqualityComparer comparer) + => array.IndexOf(item, startIndex: 0, comparer); - if (array2.IsDefault) - { - throw new NullReferenceException(); - } + internal static bool IsSorted(this ImmutableArray array, Comparison comparison) + => IsSorted(array, Comparer.Create(comparison)); - if (array1.Length != array2.Length) - { - return false; - } + internal static bool IsSorted(this ImmutableArray array, IComparer? comparer = null) + { + comparer ??= Comparer.Default; - for (int i = 0; i < array1.Length; i++) + for (var i = 1; i < array.Length; i++) { - if (!predicate(array1[i], array2[i], arg)) + if (comparer.Compare(array[i - 1], array[i]) > 0) { return false; } @@ -1274,123 +994,373 @@ internal static bool SequenceEqual(this ImmutableArray return true; } - internal static int IndexOf(this ImmutableArray array, T item, IEqualityComparer comparer) - => array.IndexOf(item, startIndex: 0, comparer); + public static bool IsSubsetOf(this ImmutableArray array, ImmutableArray other) + { + if (other.Length == 0) + { + return array.Length == 0; + } - internal static bool IsSorted(this ImmutableArray array, Comparison comparison) - => IsSorted(array, Comparer.Create(comparison)); + switch (array.Length) + { + case 0: + return true; + case 1: + return other.Contains(array[0]); + case 2: + return other.Contains(array[0]) && other.Contains(array[1]); + case 3: + return other.Contains(array[0]) && other.Contains(array[1]) && other.Contains(array[2]); + } - internal static bool IsSorted(this ImmutableArray array, IComparer? comparer = null) - { - comparer ??= Comparer.Default; + var set = PooledHashSet.GetInstance(); + foreach (var item in other) + { + set.Add(item); + } - for (var i = 1; i < array.Length; i++) + foreach (var item in array) { - if (comparer.Compare(array[i - 1], array[i]) > 0) + if (!set.Contains(item)) { + set.Free(); return false; } } + set.Free(); return true; } - // same as Array.BinarySearch but the ability to pass arbitrary value to the comparer without allocation - internal static int BinarySearch(this ImmutableArray array, TValue value, Func comparer) - => BinarySearch(array.AsSpan(), value, comparer); + #region Binary Compat + + // These helpers should be in System.Linq namespace below. However, they are currently + // used by partners with IVT access to Roslyn, so they have to stay here for now. - internal static int BinarySearch(this ReadOnlySpan array, TValue value, Func comparer) + /// + /// Specialization of for . + /// + public static ImmutableArray Concat(this ImmutableArray first, ImmutableArray second) + => first.AddRange(second); + + /// + /// Variant of . + /// + public static ImmutableArray Concat(this ImmutableArray first, ImmutableArray second, ImmutableArray third) { - int low = 0; - int high = array.Length - 1; + var builder = new T[first.Length + second.Length + third.Length]; - while (low <= high) - { - int middle = low + ((high - low) >> 1); - int comparison = comparer(array[middle], value); + var index = 0; + first.CopyTo(builder, index); + index += first.Length; + second.CopyTo(builder, index); + index += second.Length; + third.CopyTo(builder, index); - if (comparison == 0) - { - return middle; - } + return ImmutableCollectionsMarshal.AsImmutableArray(builder); + } - if (comparison > 0) + /// + /// Variant of . + /// + public static ImmutableArray Concat(this ImmutableArray first, ImmutableArray second, ImmutableArray third, ImmutableArray fourth) + { + var builder = new T[first.Length + second.Length + third.Length + fourth.Length]; + + var index = 0; + first.CopyTo(builder, index); + index += first.Length; + second.CopyTo(builder, index); + index += second.Length; + third.CopyTo(builder, index); + index += third.Length; + fourth.CopyTo(builder, index); + + return ImmutableCollectionsMarshal.AsImmutableArray(builder); + } + + /// + /// Variant of . + /// + public static ImmutableArray Concat(this ImmutableArray first, ImmutableArray second, ImmutableArray third, ImmutableArray fourth, ImmutableArray fifth) + { + var builder = new T[first.Length + second.Length + third.Length + fourth.Length + fifth.Length]; + + var index = 0; + first.CopyTo(builder, index); + index += first.Length; + second.CopyTo(builder, index); + index += second.Length; + third.CopyTo(builder, index); + index += third.Length; + fourth.CopyTo(builder, index); + index += fourth.Length; + fifth.CopyTo(builder, index); + + return ImmutableCollectionsMarshal.AsImmutableArray(builder); + } + + /// + /// Variant of . + /// + public static ImmutableArray Concat(this ImmutableArray first, ImmutableArray second, ImmutableArray third, ImmutableArray fourth, ImmutableArray fifth, ImmutableArray sixth) + { + var builder = new T[first.Length + second.Length + third.Length + fourth.Length + fifth.Length + sixth.Length]; + + var index = 0; + first.CopyTo(builder, index); + index += first.Length; + second.CopyTo(builder, index); + index += second.Length; + third.CopyTo(builder, index); + index += third.Length; + fourth.CopyTo(builder, index); + index += fourth.Length; + fifth.CopyTo(builder, index); + index += fifth.Length; + sixth.CopyTo(builder, index); + + return ImmutableCollectionsMarshal.AsImmutableArray(builder); + } + + #endregion + } +} + +namespace System.Linq +{ + /// + /// Defines polyfill methods and overloads or alternative names of existing methods defined in System.Collections.Immutable. + /// + /// Extension methods that are available on both and in System.Linq namespace + /// are defined in System.Linq namespace to avoid accidental boxing of . + /// The boxing would occur if the file calling these methods didn't have using System.Linq. + /// + internal static class RoslynImmutableArrayExtensions + { + /// + /// Variant of + /// + public static TValue? FirstOrDefault(this ImmutableArray array, Func predicate, TArg arg) + { + foreach (var val in array) + { + if (predicate(val, arg)) { - high = middle - 1; + return val; } - else + } + + return default; + } + + /// + /// Variant of + /// + public static TValue Single(this ImmutableArray array, Func predicate, TArg arg) + { + var hasValue = false; + TValue? value = default; + foreach (var item in array) + { + if (predicate(item, arg)) { - low = middle + 1; + if (hasValue) + { + throw ExceptionUtilities.Unreachable(); + } + + value = item; + hasValue = true; } } - return ~low; + if (!hasValue) + { + throw ExceptionUtilities.Unreachable(); + } + + return value!; } - internal static int BinarySearch(this ImmutableSegmentedList array, TValue value, Func comparer) + /// + /// Variant of . + /// + public static bool SequenceEqual(this ImmutableArray array1, ImmutableArray array2, TArg arg, Func predicate) { - int low = 0; - int high = array.Count - 1; + // The framework implementation of SequenceEqual forces a NullRef for default array1 and 2, so we + // maintain the same behavior in this extension + if (array1.IsDefault) + { + throw new NullReferenceException(); + } - while (low <= high) + if (array2.IsDefault) { - int middle = low + ((high - low) >> 1); - int comparison = comparer(array[middle], value); + throw new NullReferenceException(); + } - if (comparison == 0) - { - return middle; - } + if (array1.Length != array2.Length) + { + return false; + } - if (comparison > 0) + for (int i = 0; i < array1.Length; i++) + { + if (!predicate(array1[i], array2[i], arg)) { - high = middle - 1; + return false; } - else + } + + return true; + } + + /// + /// Specialization of for . + /// + public static int Count(this ImmutableArray items, Func predicate) + { + if (items.IsEmpty) + { + return 0; + } + + int count = 0; + for (int i = 0; i < items.Length; ++i) + { + if (predicate(items[i])) { - low = middle + 1; + ++count; } } - return ~low; + return count; } - public static bool IsSubsetOf(this ImmutableArray array, ImmutableArray other) + /// + /// Specialization of for . + /// + public static int Sum(this ImmutableArray items, Func selector) { - if (other.Length == 0) + var sum = 0; + foreach (var item in items) + sum += selector(item); + + return sum; + } + + /// + /// Variation of for . + /// + public static int Sum(this ImmutableArray items, Func selector) + { + var sum = 0; + for (var i = 0; i < items.Length; i++) + sum += selector(items[i], i); + + return sum; + } + + /// + /// Variant of . + /// + public static ImmutableArray Concat(this ImmutableArray first, T second) + => first.Add(second); + + /// + /// Returns an array of distinct elements, preserving the order in the original array. + /// If the array has no duplicates, the original array is returned. The original array must not be null. + /// + /// Specialization of . + /// + public static ImmutableArray Distinct(this ImmutableArray array, IEqualityComparer? comparer = null) + { + Debug.Assert(!array.IsDefault); + + if (array.Length < 2) { - return array.Length == 0; + return array; } - switch (array.Length) + var set = new HashSet(comparer); + var builder = ArrayBuilder.GetInstance(); + foreach (var a in array) { - case 0: - return true; - case 1: - return other.Contains(array[0]); - case 2: - return other.Contains(array[0]) && other.Contains(array[1]); - case 3: - return other.Contains(array[0]) && other.Contains(array[1]) && other.Contains(array[2]); + if (set.Add(a)) + { + builder.Add(a); + } } - var set = PooledHashSet.GetInstance(); - foreach (var item in other) + var result = (builder.Count == array.Length) ? array : builder.ToImmutable(); + builder.Free(); + return result; + } + + /// + /// Variant of . + /// + public static bool Any(this ImmutableArray array, Func predicate, TArg arg) + { + int n = array.Length; + for (int i = 0; i < n; i++) { - set.Add(item); + var a = array[i]; + + if (predicate(a, arg)) + { + return true; + } } - foreach (var item in array) + return false; + } + + /// + /// Variant of . + /// + public static bool All(this ImmutableArray array, Func predicate, TArg arg) + { + int n = array.Length; + for (int i = 0; i < n; i++) { - if (!set.Contains(item)) + var a = array[i]; + + if (!predicate(a, arg)) { - set.Free(); return false; } } - set.Free(); return true; } + + } +} + +namespace System.Collections.Immutable +{ + /// + /// Defines polyfill methods and overloads or alternative names of existing methods defined in System.Collections.Immutable. + /// + /// Methods that are available on both and in System.Collections.Immutable namespace + /// are defined in System.Collections.Immutable namespace to avoid accidental boxing of . + /// The boxing would occur if the file calling these methods didn't have using System.Collections.Immutable. + /// + internal static class RoslynImmutableArrayExtensions + { + /// + /// Variant of + /// + public static bool Contains(this ImmutableArray array, Func predicate) + => array.Any(predicate); + + /// + /// Variant of + /// with the ability to pass arbitrary value to the comparer without allocation. + /// + public static int BinarySearch(this ImmutableArray array, TValue value, Func comparer) + => array.AsSpan().BinarySearch(value, comparer); } } diff --git a/src/Dependencies/Collections/Extensions/KeyValuePairExtensions.cs b/src/Dependencies/Collections/Extensions/KeyValuePairExtensions.cs new file mode 100644 index 0000000000000..9d4155be2666e --- /dev/null +++ b/src/Dependencies/Collections/Extensions/KeyValuePairExtensions.cs @@ -0,0 +1,22 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +#nullable enable + +namespace System.Collections.Generic; + +internal static class RoslynKeyValuePairExtensions +{ +#if NET + public static void Deconstruct(KeyValuePair keyValuePair, out TKey key, out TValue value) + => keyValuePair.Deconstruct(out key, out value); +#else + public static void Deconstruct(this KeyValuePair keyValuePair, out TKey key, out TValue value) + { + key = keyValuePair.Key; + value = keyValuePair.Value; + } +#endif +} + diff --git a/src/Dependencies/Collections/Extensions/MemoryExtensions.cs b/src/Dependencies/Collections/Extensions/MemoryExtensions.cs new file mode 100644 index 0000000000000..993ebda19ffeb --- /dev/null +++ b/src/Dependencies/Collections/Extensions/MemoryExtensions.cs @@ -0,0 +1,45 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +#nullable enable + +namespace System +{ + /// + /// Defines polyfill methods and overloads or alternative names of existing Span related methods defined in System. + /// + internal static class RoslynMemoryExtensions + { + /// + /// Variant of . + /// + public static int BinarySearch(this ReadOnlySpan span, TValue value, Func comparer) + { + int low = 0; + int high = span.Length - 1; + + while (low <= high) + { + int middle = low + ((high - low) >> 1); + int comparison = comparer(span[middle], value); + + if (comparison == 0) + { + return middle; + } + + if (comparison > 0) + { + high = middle - 1; + } + else + { + low = middle + 1; + } + } + + return ~low; + } + } +} diff --git a/src/Dependencies/Collections/KeyValuePair.cs b/src/Dependencies/Collections/KeyValuePair.cs new file mode 100644 index 0000000000000..e38fc9b25b691 --- /dev/null +++ b/src/Dependencies/Collections/KeyValuePair.cs @@ -0,0 +1,29 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +#nullable enable + +// Copied from: +// https://github.com/dotnet/runtime/blob/9214279d93b8b422495a98eb4edda91e92bd60c3/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/KeyValuePair.cs + +#if NET + +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +#pragma warning disable RS0016 // Add public types and members to the declared API (this is a supporting forwarder for an internal polyfill API) +[assembly: TypeForwardedTo(typeof(KeyValuePair))] +#pragma warning restore RS0016 // Add public types and members to the declared API + +#else + +namespace System.Collections.Generic; + +internal static class KeyValuePair +{ + public static KeyValuePair Create(TKey key, TValue value) => + new KeyValuePair(key, value); +} + +#endif diff --git a/src/Dependencies/Collections/Microsoft.CodeAnalysis.Collections.projitems b/src/Dependencies/Collections/Microsoft.CodeAnalysis.Collections.projitems index 77f4e14de4e80..15de459df470c 100644 --- a/src/Dependencies/Collections/Microsoft.CodeAnalysis.Collections.projitems +++ b/src/Dependencies/Collections/Microsoft.CodeAnalysis.Collections.projitems @@ -10,6 +10,7 @@ Microsoft.CodeAnalysis.Collections + @@ -64,6 +65,7 @@ + @@ -71,6 +73,8 @@ + + @@ -90,4 +94,4 @@ - + \ No newline at end of file diff --git a/src/Dependencies/Collections/OneOrMany.cs b/src/Dependencies/Collections/OneOrMany.cs index eaad4dcf1c13d..01b2ec1d01f04 100644 --- a/src/Dependencies/Collections/OneOrMany.cs +++ b/src/Dependencies/Collections/OneOrMany.cs @@ -13,7 +13,7 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.PooledObjects; -namespace Roslyn.Utilities +namespace Microsoft.CodeAnalysis.Collections { /// /// Represents a single item or many items (including none). @@ -200,7 +200,7 @@ public bool SequenceEqual(OneOrMany other, IEqualityComparer? comparer = n Debug.Assert(HasOneItem == other.HasOneItem); return HasOneItem ? comparer.Equals(_one, other._one!) : - System.Linq.ImmutableArrayExtensions.SequenceEqual(_many, other._many, comparer); + _many.SequenceEqual(other._many, comparer); } public bool SequenceEqual(ImmutableArray other, IEqualityComparer? comparer = null) diff --git a/src/Dependencies/Collections/Segmented/ImmutableSegmentedListExtensions.cs b/src/Dependencies/Collections/Segmented/ImmutableSegmentedListExtensions.cs index a7675a069b7b3..38f0931bd4443 100644 --- a/src/Dependencies/Collections/Segmented/ImmutableSegmentedListExtensions.cs +++ b/src/Dependencies/Collections/Segmented/ImmutableSegmentedListExtensions.cs @@ -116,5 +116,33 @@ public static IEnumerable Select(this ImmutableSegmentedLis return Enumerable.Select(immutableList, selector); } } + + public static int BinarySearch(this ImmutableSegmentedList array, TValue value, Func comparer) + { + int low = 0; + int high = array.Count - 1; + + while (low <= high) + { + int middle = low + ((high - low) >> 1); + int comparison = comparer(array[middle], value); + + if (comparison == 0) + { + return middle; + } + + if (comparison > 0) + { + high = middle - 1; + } + else + { + low = middle + 1; + } + } + + return ~low; + } } } diff --git a/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Set.cs b/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Set.cs index be9f0dd34d941..54e56d30891de 100644 --- a/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Set.cs +++ b/src/Dependencies/Collections/Specialized/SpecializedCollections.Empty.Set.cs @@ -5,8 +5,8 @@ #nullable enable using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; namespace Microsoft.CodeAnalysis.Collections { diff --git a/src/Dependencies/Collections/TemporaryArrayExtensions.cs b/src/Dependencies/Collections/TemporaryArrayExtensions.cs index df57c3f899b6d..b5b5077399b9b 100644 --- a/src/Dependencies/Collections/TemporaryArrayExtensions.cs +++ b/src/Dependencies/Collections/TemporaryArrayExtensions.cs @@ -8,7 +8,7 @@ using System.Linq; using System.Runtime.CompilerServices; -namespace Microsoft.CodeAnalysis.Shared.Collections +namespace Microsoft.CodeAnalysis.Collections { internal static class TemporaryArrayExtensions { diff --git a/src/Dependencies/Collections/TemporaryArray`1.cs b/src/Dependencies/Collections/TemporaryArray`1.cs index 8f1856e4a58b4..eefb7503ab1c4 100644 --- a/src/Dependencies/Collections/TemporaryArray`1.cs +++ b/src/Dependencies/Collections/TemporaryArray`1.cs @@ -12,10 +12,11 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; -namespace Microsoft.CodeAnalysis.Shared.Collections +namespace Microsoft.CodeAnalysis.Collections { /// /// Provides temporary storage for a collection of elements. This type is optimized for handling of small diff --git a/src/Dependencies/Contracts/SetsRequiredMembersAttribute.cs b/src/Dependencies/Contracts/SetsRequiredMembersAttribute.cs index 891d50f2859d8..28c91eee619f1 100644 --- a/src/Dependencies/Contracts/SetsRequiredMembersAttribute.cs +++ b/src/Dependencies/Contracts/SetsRequiredMembersAttribute.cs @@ -9,8 +9,8 @@ #if NET8_0_OR_GREATER -using System.Runtime.CompilerServices; using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; #pragma warning disable RS0016 // Add public types and members to the declared API (this is a supporting forwarder for an internal polyfill API) [assembly: TypeForwardedTo(typeof(SetsRequiredMembersAttribute))] diff --git a/src/Dependencies/Threading/AsyncBatchingWorkQueue`2.cs b/src/Dependencies/Threading/AsyncBatchingWorkQueue`2.cs index dbae13b39be23..8ef43c7aa6293 100644 --- a/src/Dependencies/Threading/AsyncBatchingWorkQueue`2.cs +++ b/src/Dependencies/Threading/AsyncBatchingWorkQueue`2.cs @@ -11,7 +11,6 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.ErrorReporting; -using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.TestHooks; namespace Microsoft.CodeAnalysis.Threading; diff --git a/src/EditorFeatures/CSharp/AutomaticCompletion/AutomaticLineEnderCommandHandler.cs b/src/EditorFeatures/CSharp/AutomaticCompletion/AutomaticLineEnderCommandHandler.cs index 5089f5836e7d0..15ef807165bd8 100644 --- a/src/EditorFeatures/CSharp/AutomaticCompletion/AutomaticLineEnderCommandHandler.cs +++ b/src/EditorFeatures/CSharp/AutomaticCompletion/AutomaticLineEnderCommandHandler.cs @@ -7,14 +7,16 @@ using System.ComponentModel.Composition; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.AutomaticCompletion; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; -using Microsoft.CodeAnalysis.AutomaticCompletion; +using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Formatting; +using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; @@ -27,8 +29,6 @@ using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; -using Microsoft.CodeAnalysis.Host; -using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.Editor.CSharp.AutomaticCompletion; diff --git a/src/EditorFeatures/CSharp/AutomaticCompletion/AutomaticLineEnderCommandHandler_Helpers.cs b/src/EditorFeatures/CSharp/AutomaticCompletion/AutomaticLineEnderCommandHandler_Helpers.cs index ff5ead2f7d417..d6c5147307336 100644 --- a/src/EditorFeatures/CSharp/AutomaticCompletion/AutomaticLineEnderCommandHandler_Helpers.cs +++ b/src/EditorFeatures/CSharp/AutomaticCompletion/AutomaticLineEnderCommandHandler_Helpers.cs @@ -835,9 +835,6 @@ private static bool ShouldRemoveBraceForEventDeclaration(EventDeclarationSyntax #region AddBrace - private static AccessorListSyntax GetAccessorListNode(SyntaxFormattingOptions formattingOptions) - => AccessorList().WithOpenBraceToken(GetOpenBrace(formattingOptions)).WithCloseBraceToken(GetCloseBrace(formattingOptions)); - private static InitializerExpressionSyntax GetInitializerExpressionNode(SyntaxFormattingOptions formattingOptions) => InitializerExpression(SyntaxKind.ObjectInitializerExpression) .WithOpenBraceToken(GetOpenBrace(formattingOptions)); diff --git a/src/EditorFeatures/CSharp/ConvertNamespace/ConvertNamespaceCommandHandler.cs b/src/EditorFeatures/CSharp/ConvertNamespace/ConvertNamespaceCommandHandler.cs index 76e1a337054ad..7329634373bfe 100644 --- a/src/EditorFeatures/CSharp/ConvertNamespace/ConvertNamespaceCommandHandler.cs +++ b/src/EditorFeatures/CSharp/ConvertNamespace/ConvertNamespaceCommandHandler.cs @@ -40,8 +40,7 @@ internal sealed class ConvertNamespaceCommandHandler( ITextUndoHistoryRegistry textUndoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService, EditorOptionsService editorOptionsService, - IGlobalOptionService globalOptions, - IIndentationManagerService indentationManager) : IChainedCommandHandler + IGlobalOptionService globalOptions) : IChainedCommandHandler { /// /// Option setting 'use file scoped'. That way we can call into the helpers @@ -54,7 +53,6 @@ internal sealed class ConvertNamespaceCommandHandler( private readonly ITextUndoHistoryRegistry _textUndoHistoryRegistry = textUndoHistoryRegistry; private readonly IEditorOperationsFactoryService _editorOperationsFactoryService = editorOperationsFactoryService; private readonly EditorOptionsService _editorOptionsService = editorOptionsService; - private readonly IIndentationManagerService _indentationManager = indentationManager; private readonly IGlobalOptionService _globalOptions = globalOptions; public CommandState GetCommandState(TypeCharCommandArgs args, Func nextCommandHandler) diff --git a/src/EditorFeatures/CSharp/EventHookup/EventHookupSessionManager.cs b/src/EditorFeatures/CSharp/EventHookup/EventHookupSessionManager.cs index a82060abedcd2..530cc75bf09ef 100644 --- a/src/EditorFeatures/CSharp/EventHookup/EventHookupSessionManager.cs +++ b/src/EditorFeatures/CSharp/EventHookup/EventHookupSessionManager.cs @@ -32,21 +32,19 @@ internal sealed partial class EventHookupSessionManager( private IToolTipPresenter _toolTipPresenter; - private EventHookupSession _currentSessionDoNotAccessDirectly; - internal EventHookupSession CurrentSession { get { ThreadingContext.ThrowIfNotOnUIThread(); - return _currentSessionDoNotAccessDirectly; + return field; } set { ThreadingContext.ThrowIfNotOnUIThread(); - _currentSessionDoNotAccessDirectly?.CancelBackgroundTasks(); - _currentSessionDoNotAccessDirectly = value; + field?.CancelBackgroundTasks(); + field = value; } } diff --git a/src/EditorFeatures/CSharp/EventHookup/EventHookupSessionManager_EventHookupSession.cs b/src/EditorFeatures/CSharp/EventHookup/EventHookupSessionManager_EventHookupSession.cs index ecaba76aa5d08..99217276e4052 100644 --- a/src/EditorFeatures/CSharp/EventHookup/EventHookupSessionManager_EventHookupSession.cs +++ b/src/EditorFeatures/CSharp/EventHookup/EventHookupSessionManager_EventHookupSession.cs @@ -35,9 +35,6 @@ internal sealed partial class EventHookupSessionManager internal sealed class EventHookupSession { private readonly IThreadingContext _threadingContext; - private readonly ITrackingSpan _trackingSpan; - private readonly ITextView _textView; - private readonly ITextBuffer _subjectBuffer; public event Action Dismissed = () => { }; @@ -52,7 +49,7 @@ public ITrackingSpan TrackingSpan get { _threadingContext.ThrowIfNotOnUIThread(); - return _trackingSpan; + return field; } } @@ -61,7 +58,7 @@ public ITextView TextView get { _threadingContext.ThrowIfNotOnUIThread(); - return _textView; + return field; } } @@ -70,7 +67,7 @@ public ITextBuffer SubjectBuffer get { _threadingContext.ThrowIfNotOnUIThread(); - return _subjectBuffer; + return field; } } @@ -96,13 +93,13 @@ public EventHookupSession( _cancellationTokenSource = new(); var cancellationToken = _cancellationTokenSource.Token; - _textView = textView; - _subjectBuffer = subjectBuffer; + TextView = textView; + SubjectBuffer = subjectBuffer; this.TESTSessionHookupMutex = testSessionHookupMutex; // If the caret is at the end of the document we just create an empty span var length = subjectBuffer.CurrentSnapshot.Length > position + 1 ? 1 : 0; - _trackingSpan = subjectBuffer.CurrentSnapshot.CreateTrackingSpan(new Span(position, length), SpanTrackingMode.EdgeInclusive); + TrackingSpan = subjectBuffer.CurrentSnapshot.CreateTrackingSpan(new Span(position, length), SpanTrackingMode.EdgeInclusive); var asyncToken = asyncListener.BeginAsyncOperation(GetType().Name + ".Start"); @@ -155,7 +152,7 @@ async Task ContinueOnMainThreadAsync( var namingRule = await document.GetApplicableNamingRuleAsync( new SymbolKindOrTypeKind(MethodKind.Ordinary), - new DeclarationModifiers(isStatic: plusEqualsToken.Value.GetRequiredParent().IsInStaticContext()), + new DeclarationModifiers(isStatic: plusEqualsToken.Value.GetRequiredParent().IsInStaticContext()).Modifiers, Accessibility.Private, cancellationToken).ConfigureAwait(false); diff --git a/src/EditorFeatures/CSharp/RawStringLiteral/RawStringLiteralCommandHandler_Return.cs b/src/EditorFeatures/CSharp/RawStringLiteral/RawStringLiteralCommandHandler_Return.cs index 6170f34428627..74cd8b6a3b6ad 100644 --- a/src/EditorFeatures/CSharp/RawStringLiteral/RawStringLiteralCommandHandler_Return.cs +++ b/src/EditorFeatures/CSharp/RawStringLiteral/RawStringLiteralCommandHandler_Return.cs @@ -15,7 +15,6 @@ using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.RawStringLiteral; diff --git a/src/EditorFeatures/CSharp/RawStringLiteral/RawStringLiteralCommandHandler_TypeChar.cs b/src/EditorFeatures/CSharp/RawStringLiteral/RawStringLiteralCommandHandler_TypeChar.cs index 39b6b3ee56903..14b1ae6608e4f 100644 --- a/src/EditorFeatures/CSharp/RawStringLiteral/RawStringLiteralCommandHandler_TypeChar.cs +++ b/src/EditorFeatures/CSharp/RawStringLiteral/RawStringLiteralCommandHandler_TypeChar.cs @@ -14,7 +14,6 @@ using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.RawStringLiteral; diff --git a/src/EditorFeatures/CSharp/StringCopyPaste/KnownSourcePasteProcessor.cs b/src/EditorFeatures/CSharp/StringCopyPaste/KnownSourcePasteProcessor.cs index c4006176b2817..ca6ff2e2cf1d8 100644 --- a/src/EditorFeatures/CSharp/StringCopyPaste/KnownSourcePasteProcessor.cs +++ b/src/EditorFeatures/CSharp/StringCopyPaste/KnownSourcePasteProcessor.cs @@ -11,7 +11,6 @@ using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.StringCopyPaste; diff --git a/src/EditorFeatures/CSharp/StringCopyPaste/StringCopyPasteCommandHandler.cs b/src/EditorFeatures/CSharp/StringCopyPaste/StringCopyPasteCommandHandler.cs index 7b3064865775e..779a2a87004f4 100644 --- a/src/EditorFeatures/CSharp/StringCopyPaste/StringCopyPasteCommandHandler.cs +++ b/src/EditorFeatures/CSharp/StringCopyPaste/StringCopyPasteCommandHandler.cs @@ -55,19 +55,15 @@ internal sealed partial class StringCopyPasteCommandHandler( IEditorOperationsFactoryService editorOperationsFactoryService, IGlobalOptionService globalOptions, ITextBufferFactoryService2 textBufferFactoryService, - EditorOptionsService editorOptionsService, - IIndentationManagerService indentationManager) : + EditorOptionsService editorOptionsService) : IChainedCommandHandler, IChainedCommandHandler, IChainedCommandHandler { - private const string CopyId = "RoslynStringCopyPasteId"; - private readonly IThreadingContext _threadingContext = threadingContext; private readonly ITextUndoHistoryRegistry _undoHistoryRegistry = undoHistoryRegistry; private readonly IEditorOperationsFactoryService _editorOperationsFactoryService = editorOperationsFactoryService; private readonly EditorOptionsService _editorOptionsService = editorOptionsService; - private readonly IIndentationManagerService _indentationManager = indentationManager; private readonly IGlobalOptionService _globalOptions = globalOptions; private readonly ITextBufferFactoryService2 _textBufferFactoryService = textBufferFactoryService; diff --git a/src/EditorFeatures/CSharp/StringCopyPaste/StringCopyPasteContent.cs b/src/EditorFeatures/CSharp/StringCopyPaste/StringCopyPasteContent.cs index 973515b21ca5c..0c89cb96a2d62 100644 --- a/src/EditorFeatures/CSharp/StringCopyPaste/StringCopyPasteContent.cs +++ b/src/EditorFeatures/CSharp/StringCopyPaste/StringCopyPasteContent.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Diagnostics.CodeAnalysis; using System.Text.Json.Serialization; +using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.Editor.CSharp.StringCopyPaste; diff --git a/src/EditorFeatures/CSharp/StringCopyPaste/StringCopyPasteData.cs b/src/EditorFeatures/CSharp/StringCopyPaste/StringCopyPasteData.cs index b9d7a6a0a38a1..5b886d61ef5f2 100644 --- a/src/EditorFeatures/CSharp/StringCopyPaste/StringCopyPasteData.cs +++ b/src/EditorFeatures/CSharp/StringCopyPaste/StringCopyPasteData.cs @@ -4,14 +4,14 @@ using System; using System.Collections.Immutable; -using Microsoft.CodeAnalysis.ErrorReporting; -using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Diagnostics.CodeAnalysis; using System.Text.Json; using System.Text.Json.Serialization; +using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; -using Microsoft.CodeAnalysis.Text; +using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.StringCopyPaste; diff --git a/src/EditorFeatures/CSharp/StringCopyPaste/StringCopyPasteHelpers.cs b/src/EditorFeatures/CSharp/StringCopyPaste/StringCopyPasteHelpers.cs index 6d9460ac71a2f..f2805572e35af 100644 --- a/src/EditorFeatures/CSharp/StringCopyPaste/StringCopyPasteHelpers.cs +++ b/src/EditorFeatures/CSharp/StringCopyPaste/StringCopyPasteHelpers.cs @@ -14,7 +14,6 @@ using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.StringCopyPaste; diff --git a/src/EditorFeatures/CSharp/StringCopyPaste/StringInfo.cs b/src/EditorFeatures/CSharp/StringCopyPaste/StringInfo.cs index b8b9e298e8091..0f8450edcc016 100644 --- a/src/EditorFeatures/CSharp/StringCopyPaste/StringInfo.cs +++ b/src/EditorFeatures/CSharp/StringCopyPaste/StringInfo.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; diff --git a/src/EditorFeatures/CSharp/StringCopyPaste/UnknownSourcePasteProcessor.cs b/src/EditorFeatures/CSharp/StringCopyPaste/UnknownSourcePasteProcessor.cs index 7cbaa57063359..8e5611ff9494e 100644 --- a/src/EditorFeatures/CSharp/StringCopyPaste/UnknownSourcePasteProcessor.cs +++ b/src/EditorFeatures/CSharp/StringCopyPaste/UnknownSourcePasteProcessor.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Immutable; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; @@ -13,7 +14,6 @@ using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.StringCopyPaste; diff --git a/src/EditorFeatures/CSharpTest/AddMissingImports/CSharpAddMissingImportsRefactoringProviderTests.cs b/src/EditorFeatures/CSharpTest/AddMissingImports/CSharpAddMissingImportsRefactoringProviderTests.cs index 9134dfce57138..93ceaedbf5734 100644 --- a/src/EditorFeatures/CSharpTest/AddMissingImports/CSharpAddMissingImportsRefactoringProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/AddMissingImports/CSharpAddMissingImportsRefactoringProviderTests.cs @@ -2,13 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable - using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.AddImport; using Microsoft.CodeAnalysis.CodeRefactorings; +using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.AddMissingImports; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; @@ -26,6 +27,12 @@ public sealed class CSharpAddMissingImportsRefactoringProviderTests : AbstractCS protected override CodeRefactoringProvider CreateCodeRefactoringProvider(EditorTestWorkspace workspace, TestParameters parameters) => new CSharpAddMissingImportsRefactoringProvider(); + private static readonly CodeStyleOption2 InsideNamespaceOption = + new(AddImportPlacement.InsideNamespace, NotificationOption2.Error); + + private static readonly CodeStyleOption2 OutsideNamespaceOption = + new(AddImportPlacement.InsideNamespace, NotificationOption2.Error); + protected override void InitializeWorkspace(EditorTestWorkspace workspace, TestParameters parameters) { // Treat the span being tested as the pasted span @@ -46,21 +53,23 @@ protected override void InitializeWorkspace(EditorTestWorkspace workspace, TestP private Task TestInRegularAndScriptAsync( [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string initialMarkup, [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string expectedMarkup, - bool placeSystemNamespaceFirst, bool separateImportDirectiveGroups) + bool placeSystemNamespaceFirst, + bool separateImportDirectiveGroups, + bool placeInsideNamespace = false) { var options = new OptionsCollection(GetLanguage()) { { GenerationOptions.PlaceSystemNamespaceFirst, placeSystemNamespaceFirst }, { GenerationOptions.SeparateImportDirectiveGroups, separateImportDirectiveGroups }, + { CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, placeInsideNamespace ? InsideNamespaceOption : OutsideNamespaceOption }, }; return TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: options); } [WpfFact] - public async Task AddMissingImports_AddImport_PasteContainsSingleMissingImport() - { - var code = """ + public Task AddMissingImports_AddImport_PasteContainsSingleMissingImport() + => TestInRegularAndScriptAsync(""" class C { public [|D|] Foo { get; } @@ -70,9 +79,7 @@ namespace A { public class D { } } - """; - - var expected = """ + """, """ using A; class C @@ -84,15 +91,11 @@ namespace A { public class D { } } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [WpfFact] - public async Task AddMissingImports_AddImportsBelowSystem_PlaceSystemFirstPasteContainsMultipleMissingImports() - { - var code = """ + public Task AddMissingImports_AddImportsBelowSystem_PlaceSystemFirstPasteContainsMultipleMissingImports() + => TestInRegularAndScriptAsync(""" using System; class C @@ -110,9 +113,7 @@ namespace B { public class E { } } - """; - - var expected = """ + """, """ using System; using A; using B; @@ -132,15 +133,11 @@ namespace B { public class E { } } - """; - - await TestInRegularAndScriptAsync(code, expected, placeSystemNamespaceFirst: true, separateImportDirectiveGroups: false); - } + """, placeSystemNamespaceFirst: true, separateImportDirectiveGroups: false); [WpfFact] - public async Task AddMissingImports_AddImportsAboveSystem_DoNotPlaceSystemFirstPasteContainsMultipleMissingImports() - { - var code = """ + public Task AddMissingImports_AddImportsAboveSystem_DoNotPlaceSystemFirstPasteContainsMultipleMissingImports() + => TestInRegularAndScriptAsync(""" using System; class C @@ -158,9 +155,7 @@ namespace B { public class E { } } - """; - - var expected = """ + """, """ using A; using B; using System; @@ -180,15 +175,11 @@ namespace B { public class E { } } - """; - - await TestInRegularAndScriptAsync(code, expected, placeSystemNamespaceFirst: false, separateImportDirectiveGroups: false); - } + """, placeSystemNamespaceFirst: false, separateImportDirectiveGroups: false); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/pull/42221")] - public async Task AddMissingImports_AddImportsUngrouped_SeparateImportGroupsPasteContainsMultipleMissingImports() - { - var code = """ + public Task AddMissingImports_AddImportsUngrouped_SeparateImportGroupsPasteContainsMultipleMissingImports() + => TestInRegularAndScriptAsync(""" using System; class C @@ -206,9 +197,7 @@ namespace B { public class E { } } - """; - - var expected = """ + """, """ using A; using B; @@ -230,15 +219,11 @@ namespace B { public class E { } } - """; - - await TestInRegularAndScriptAsync(code, expected, placeSystemNamespaceFirst: false, separateImportDirectiveGroups: true); - } + """, placeSystemNamespaceFirst: false, separateImportDirectiveGroups: true); [WpfFact] - public async Task AddMissingImports_PartialFix_PasteContainsFixableAndAmbiguousMissingImports() - { - var code = """ + public Task AddMissingImports_PartialFix_PasteContainsFixableAndAmbiguousMissingImports() + => TestInRegularAndScriptAsync(""" class C { [|public D Foo { get; } @@ -255,9 +240,7 @@ namespace B public class D { } public class E { } } - """; - - var expected = """ + """, """ using B; class C @@ -276,15 +259,11 @@ namespace B public class D { } public class E { } } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [WpfFact] - public async Task AddMissingImports_NoAction_NoPastedSpan() - { - var code = """ + public Task AddMissingImports_NoAction_NoPastedSpan() + => TestMissingInRegularAndScriptAsync(""" class C { public D[||] Foo { get; } @@ -294,15 +273,11 @@ namespace A { public class D { } } - """; - - await TestMissingInRegularAndScriptAsync(code); - } + """); [WpfFact] - public async Task AddMissingImports_NoAction_PasteIsNotMissingImports() - { - var code = """ + public Task AddMissingImports_NoAction_PasteIsNotMissingImports() + => TestMissingInRegularAndScriptAsync(""" class [|C|] { public D Foo { get; } @@ -312,15 +287,11 @@ namespace A { public class D { } } - """; - - await TestMissingInRegularAndScriptAsync(code); - } + """); [WpfFact] - public async Task AddMissingImports_NoAction_PasteContainsAmibiguousMissingImport() - { - var code = """ + public Task AddMissingImports_NoAction_PasteContainsAmibiguousMissingImport() + => TestMissingInRegularAndScriptAsync(""" class C { public [|D|] Foo { get; } @@ -335,15 +306,11 @@ namespace B { public class D { } } - """; - - await TestMissingInRegularAndScriptAsync(code); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/31768")] - public async Task AddMissingImports_AddMultipleImports_NoPreviousImports() - { - var code = """ + public Task AddMissingImports_AddMultipleImports_NoPreviousImports() + => TestInRegularAndScriptAsync(""" class C { [|public D Foo { get; } @@ -359,9 +326,7 @@ namespace B { public class E { } } - """; - - var expected = """ + """, """ using A; using B; @@ -380,22 +345,16 @@ namespace B { public class E { } } - """; - - await TestInRegularAndScriptAsync(code, expected, placeSystemNamespaceFirst: false, separateImportDirectiveGroups: false); - } + """, placeSystemNamespaceFirst: false, separateImportDirectiveGroups: false); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/51844")] - public async Task TestOrdering1() - { - var code = """ + public Task TestOrdering1() + => TestInRegularAndScriptAsync(""" class C { [|List list;|] } - """; - - var expected = """ + """, """ using System; using System.Collections.Generic; @@ -403,8 +362,30 @@ class C { List list; } - """; + """, placeSystemNamespaceFirst: true, separateImportDirectiveGroups: true); - await TestInRegularAndScriptAsync(code, expected, placeSystemNamespaceFirst: true, separateImportDirectiveGroups: true); - } + [WpfTheory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/54842")] + public Task TestWithNamespace(bool placeInsideNamespace) + => TestInRegularAndScriptAsync(""" + namespace N + { + using System; + + class C + { + [|List list;|] + } + } + """, """ + namespace N + { + using System; + using System.Collections.Generic; + + class C + { + List list; + } + } + """, placeSystemNamespaceFirst: true, separateImportDirectiveGroups: true, placeInsideNamespace); } diff --git a/src/EditorFeatures/CSharpTest/AutomaticCompletion/AutomaticBraceCompletionTests.cs b/src/EditorFeatures/CSharpTest/AutomaticCompletion/AutomaticBraceCompletionTests.cs index 5460ab773426a..a7669b703831a 100644 --- a/src/EditorFeatures/CSharpTest/AutomaticCompletion/AutomaticBraceCompletionTests.cs +++ b/src/EditorFeatures/CSharpTest/AutomaticCompletion/AutomaticBraceCompletionTests.cs @@ -32,8 +32,11 @@ void M(C c) } } """; + using var session = CreateSession(code); + Assert.NotNull(session); - var expected = """ + CheckStart(session.Session); + CheckText(session.Session, """ class C { void M(C c) @@ -41,12 +44,7 @@ void M(C c) c = c with { } } } - """; - using var session = CreateSession(code); - Assert.NotNull(session); - - CheckStart(session.Session); - CheckText(session.Session, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/47381")] @@ -61,8 +59,11 @@ void M(C c) } } """; + using var session = CreateSession(code); + Assert.NotNull(session); - var expected = """ + CheckStart(session.Session); + CheckText(session.Session, """ class C { void M(C c) @@ -70,12 +71,7 @@ void M(C c) c = new() { } } } - """; - using var session = CreateSession(code); - Assert.NotNull(session); - - CheckStart(session.Session); - CheckText(session.Session, expected); + """); } [WpfFact] @@ -90,7 +86,9 @@ void M(C c) } } """; - var expected = """ + using var session = CreateSession(code); + CheckStart(session.Session); + CheckReturn(session.Session, 12, """ class C { void M(C c) @@ -101,10 +99,7 @@ void M(C c) } } } - """; - using var session = CreateSession(code); - CheckStart(session.Session); - CheckReturn(session.Session, 12, expected); + """); } [WpfFact] @@ -236,19 +231,16 @@ class C string s = $"{}$$ } """; - - var expected = """ + using var session = CreateSession(code); + Assert.NotNull(session); + CheckStart(session.Session); + CheckReturn(session.Session, 0, """ class C { string s = $"{}{ } } - """; - - using var session = CreateSession(code); - Assert.NotNull(session); - CheckStart(session.Session); - CheckReturn(session.Session, 0, expected); + """); } [WpfFact] @@ -486,8 +478,11 @@ void M() } } """; + using var session = CreateSession(code); + Assert.NotNull(session); - var expectedBeforeReturn = """ + CheckStart(session.Session); + CheckText(session.Session, """ record C { void M() @@ -495,9 +490,8 @@ void M() _ = this with { } } } - """; - - var expectedAfterReturn = """ + """); + CheckReturn(session.Session, 12, """ record C { void M() @@ -508,13 +502,7 @@ void M() } } } - """; - using var session = CreateSession(code); - Assert.NotNull(session); - - CheckStart(session.Session); - CheckText(session.Session, expectedBeforeReturn); - CheckReturn(session.Session, 12, expectedAfterReturn); + """); } [WpfFact] @@ -529,8 +517,11 @@ void M() } } """; + using var session = CreateSession(code); + Assert.NotNull(session); - var expectedBeforeReturn = """ + CheckStart(session.Session); + CheckText(session.Session, """ class C { void M() @@ -538,9 +529,8 @@ void M() _ = this is { } } } - """; - - var expectedAfterReturn = """ + """); + CheckReturn(session.Session, 12, """ class C { void M() @@ -551,13 +541,7 @@ void M() } } } - """; - using var session = CreateSession(code); - Assert.NotNull(session); - - CheckStart(session.Session); - CheckText(session.Session, expectedBeforeReturn); - CheckReturn(session.Session, 12, expectedAfterReturn); + """); } [WpfFact] @@ -572,8 +556,11 @@ void M() } } """; + using var session = CreateSession(code); + Assert.NotNull(session); - var expectedBeforeReturn = """ + CheckStart(session.Session); + CheckText(session.Session, """ class C { void M() @@ -581,9 +568,8 @@ void M() _ = this is { Name: { } } } } - """; - - var expectedAfterReturn = """ + """); + CheckReturn(session.Session, 12, """ class C { void M() @@ -594,13 +580,7 @@ void M() } } } } - """; - using var session = CreateSession(code); - Assert.NotNull(session); - - CheckStart(session.Session); - CheckText(session.Session, expectedBeforeReturn); - CheckReturn(session.Session, 12, expectedAfterReturn); + """); } [WpfFact] @@ -615,7 +595,11 @@ void M() } } """; - var expected = """ + using var session = CreateSession(EditorTestWorkspace.CreateCSharp(code), '(', ')'); + Assert.NotNull(session); + + CheckStart(session.Session); + CheckText(session.Session, """ class C { void M() @@ -623,13 +607,7 @@ void M() _ = this is { Name: () } } } - """; - - using var session = CreateSession(EditorTestWorkspace.CreateCSharp(code), '(', ')'); - Assert.NotNull(session); - - CheckStart(session.Session); - CheckText(session.Session, expected); + """); } [WpfFact] @@ -644,7 +622,11 @@ void M() } } """; - var expected = """ + using var session = CreateSession(EditorTestWorkspace.CreateCSharp(code), '(', ')'); + Assert.NotNull(session); + + CheckStart(session.Session); + CheckText(session.Session, """ class C { void M() @@ -652,13 +634,7 @@ void M() _ = this is { Name: { Length: (> 3) and () } } } } - """; - - using var session = CreateSession(EditorTestWorkspace.CreateCSharp(code), '(', ')'); - Assert.NotNull(session); - - CheckStart(session.Session); - CheckText(session.Session, expected); + """); } [WpfFact] @@ -674,8 +650,11 @@ void M() } } """; + using var session = CreateSession(code); + Assert.NotNull(session); - var expectedBeforeReturn = """ + CheckStart(session.Session); + CheckText(session.Session, """ class C { void M() @@ -684,9 +663,8 @@ void M() M(); } } - """; - - var expectedAfterReturn = """ + """); + CheckReturn(session.Session, 12, """ class C { void M() @@ -698,13 +676,7 @@ void M() M(); } } - """; - using var session = CreateSession(code); - Assert.NotNull(session); - - CheckStart(session.Session); - CheckText(session.Session, expectedBeforeReturn); - CheckReturn(session.Session, 12, expectedAfterReturn); + """); } [WpfFact] @@ -720,8 +692,11 @@ void M() } } """; + using var session = CreateSession(code); + Assert.NotNull(session); - var expectedBeforeReturn = """ + CheckStart(session.Session); + CheckText(session.Session, """ class C { void M() @@ -730,9 +705,8 @@ void M() M(); } } - """; - - var expectedAfterReturn = """ + """); + CheckReturn(session.Session, 12, """ class C { void M() @@ -744,13 +718,7 @@ void M() M(); } } - """; - using var session = CreateSession(code); - Assert.NotNull(session); - - CheckStart(session.Session); - CheckText(session.Session, expectedBeforeReturn); - CheckReturn(session.Session, 12, expectedAfterReturn); + """); } [WpfFact] @@ -765,8 +733,11 @@ void M() } } """; + using var session = CreateSession(code); + Assert.NotNull(session); - var expectedBeforeReturn = """ + CheckStart(session.Session); + CheckText(session.Session, """ class C { void M() @@ -774,9 +745,8 @@ void M() _ = this switch { } } } - """; - - var expectedAfterReturn = """ + """); + CheckReturn(session.Session, 12, """ class C { void M() @@ -787,13 +757,7 @@ void M() } } } - """; - using var session = CreateSession(code); - Assert.NotNull(session); - - CheckStart(session.Session); - CheckText(session.Session, expectedBeforeReturn); - CheckReturn(session.Session, 12, expectedAfterReturn); + """); } [WpfFact] @@ -810,8 +774,11 @@ class C }; } """; + using var session = CreateSession(code); + Assert.NotNull(session); - var expected = """ + CheckStart(session.Session); + CheckReturn(session.Session, 12, """ using System.Collections.Generic; class C @@ -824,12 +791,7 @@ class C } }; } - """; - using var session = CreateSession(code); - Assert.NotNull(session); - - CheckStart(session.Session); - CheckReturn(session.Session, 12, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] @@ -846,8 +808,16 @@ public void man() } } """; + var globalOptions = new OptionsCollection(LanguageNames.CSharp) + { + { CSharpFormattingOptions2.NewLineBeforeOpenBrace, CSharpFormattingOptions2.NewLineBeforeOpenBrace.DefaultValue.WithFlagValue(NewLineBeforeOpenBracePlacement.ObjectCollectionArrayInitializers, false) } + }; + + using var session = CreateSession(code, globalOptions); + Assert.NotNull(session); - var expected = """ + CheckStart(session.Session); + CheckReturn(session.Session, 12, """ using System.Collections.Generic; class C @@ -859,17 +829,7 @@ public void man() } } } - """; - var globalOptions = new OptionsCollection(LanguageNames.CSharp) - { - { CSharpFormattingOptions2.NewLineBeforeOpenBrace, CSharpFormattingOptions2.NewLineBeforeOpenBrace.DefaultValue.WithFlagValue(NewLineBeforeOpenBracePlacement.ObjectCollectionArrayInitializers, false) } - }; - - using var session = CreateSession(code, globalOptions); - Assert.NotNull(session); - - CheckStart(session.Session); - CheckReturn(session.Session, 12, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] @@ -886,8 +846,11 @@ public void man() } } """; + using var session = CreateSession(code); + Assert.NotNull(session); - var expected = """ + CheckStart(session.Session); + CheckReturn(session.Session, 12, """ using System.Collections.Generic; class C @@ -900,12 +863,7 @@ public void man() } } } - """; - using var session = CreateSession(code); - Assert.NotNull(session); - - CheckStart(session.Session); - CheckReturn(session.Session, 12, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] @@ -925,8 +883,16 @@ class Goo public int bar; } """; + var globalOptions = new OptionsCollection(LanguageNames.CSharp) + { + { CSharpFormattingOptions2.NewLineBeforeOpenBrace, CSharpFormattingOptions2.NewLineBeforeOpenBrace.DefaultValue.WithFlagValue(NewLineBeforeOpenBracePlacement.ObjectCollectionArrayInitializers, false) } + }; - var expected = """ + using var session = CreateSession(code, globalOptions); + Assert.NotNull(session); + + CheckStart(session.Session); + CheckReturn(session.Session, 12, """ class C { public void man() @@ -941,17 +907,7 @@ class Goo { public int bar; } - """; - var globalOptions = new OptionsCollection(LanguageNames.CSharp) - { - { CSharpFormattingOptions2.NewLineBeforeOpenBrace, CSharpFormattingOptions2.NewLineBeforeOpenBrace.DefaultValue.WithFlagValue(NewLineBeforeOpenBracePlacement.ObjectCollectionArrayInitializers, false) } - }; - - using var session = CreateSession(code, globalOptions); - Assert.NotNull(session); - - CheckStart(session.Session); - CheckReturn(session.Session, 12, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] @@ -971,8 +927,11 @@ class Goo public int bar; } """; + using var session = CreateSession(code); + Assert.NotNull(session); - var expected = """ + CheckStart(session.Session); + CheckReturn(session.Session, 12, """ class C { public void man() @@ -988,12 +947,7 @@ class Goo { public int bar; } - """; - using var session = CreateSession(code); - Assert.NotNull(session); - - CheckStart(session.Session); - CheckReturn(session.Session, 12, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] @@ -1008,8 +962,16 @@ public void man() } } """; + var globalOptions = new OptionsCollection(LanguageNames.CSharp) + { + { CSharpFormattingOptions2.NewLineBeforeOpenBrace, CSharpFormattingOptions2.NewLineBeforeOpenBrace.DefaultValue.WithFlagValue(NewLineBeforeOpenBracePlacement.ObjectCollectionArrayInitializers, false) } + }; + + using var session = CreateSession(code, globalOptions); + Assert.NotNull(session); - var expected = """ + CheckStart(session.Session); + CheckReturn(session.Session, 12, """ class C { public void man() @@ -1019,17 +981,7 @@ public void man() } } } - """; - var globalOptions = new OptionsCollection(LanguageNames.CSharp) - { - { CSharpFormattingOptions2.NewLineBeforeOpenBrace, CSharpFormattingOptions2.NewLineBeforeOpenBrace.DefaultValue.WithFlagValue(NewLineBeforeOpenBracePlacement.ObjectCollectionArrayInitializers, false) } - }; - - using var session = CreateSession(code, globalOptions); - Assert.NotNull(session); - - CheckStart(session.Session); - CheckReturn(session.Session, 12, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] @@ -1044,8 +996,11 @@ public void man() } } """; + using var session = CreateSession(code); + Assert.NotNull(session); - var expected = """ + CheckStart(session.Session); + CheckReturn(session.Session, 12, """ class C { public void man() @@ -1056,12 +1011,7 @@ public void man() } } } - """; - using var session = CreateSession(code); - Assert.NotNull(session); - - CheckStart(session.Session); - CheckReturn(session.Session, 12, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] @@ -1076,8 +1026,16 @@ public void man() } } """; + var globalOptions = new OptionsCollection(LanguageNames.CSharp) + { + { CSharpFormattingOptions2.NewLineBeforeOpenBrace, CSharpFormattingOptions2.NewLineBeforeOpenBrace.DefaultValue.WithFlagValue(NewLineBeforeOpenBracePlacement.ObjectCollectionArrayInitializers, false) } + }; + + using var session = CreateSession(code, globalOptions); + Assert.NotNull(session); - var expected = """ + CheckStart(session.Session); + CheckReturn(session.Session, 12, """ class C { public void man() @@ -1087,17 +1045,7 @@ public void man() } } } - """; - var globalOptions = new OptionsCollection(LanguageNames.CSharp) - { - { CSharpFormattingOptions2.NewLineBeforeOpenBrace, CSharpFormattingOptions2.NewLineBeforeOpenBrace.DefaultValue.WithFlagValue(NewLineBeforeOpenBracePlacement.ObjectCollectionArrayInitializers, false) } - }; - - using var session = CreateSession(code, globalOptions); - Assert.NotNull(session); - - CheckStart(session.Session); - CheckReturn(session.Session, 12, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] @@ -1112,8 +1060,11 @@ public void man() } } """; + using var session = CreateSession(code); + Assert.NotNull(session); - var expected = """ + CheckStart(session.Session); + CheckReturn(session.Session, 12, """ class C { public void man() @@ -1124,12 +1075,7 @@ public void man() } } } - """; - using var session = CreateSession(code); - Assert.NotNull(session); - - CheckStart(session.Session); - CheckReturn(session.Session, 12, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] @@ -1144,8 +1090,15 @@ public void man() } } """; + var globalOptions = new OptionsCollection(LanguageNames.CSharp) + { + { CSharpFormattingOptions2.NewLineBeforeOpenBrace, CSharpFormattingOptions2.NewLineBeforeOpenBrace.DefaultValue.WithFlagValue(NewLineBeforeOpenBracePlacement.ObjectCollectionArrayInitializers, false) } + }; + using var session = CreateSession(code, globalOptions); + Assert.NotNull(session); - var expected = """ + CheckStart(session.Session); + CheckReturn(session.Session, 12, """ class C { public void man() @@ -1155,16 +1108,7 @@ public void man() } } } - """; - var globalOptions = new OptionsCollection(LanguageNames.CSharp) - { - { CSharpFormattingOptions2.NewLineBeforeOpenBrace, CSharpFormattingOptions2.NewLineBeforeOpenBrace.DefaultValue.WithFlagValue(NewLineBeforeOpenBracePlacement.ObjectCollectionArrayInitializers, false) } - }; - using var session = CreateSession(code, globalOptions); - Assert.NotNull(session); - - CheckStart(session.Session); - CheckReturn(session.Session, 12, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] @@ -1179,8 +1123,11 @@ public void man() } } """; + using var session = CreateSession(code); + Assert.NotNull(session); - var expected = """ + CheckStart(session.Session); + CheckReturn(session.Session, 12, """ class C { public void man() @@ -1191,12 +1138,7 @@ public void man() } } } - """; - using var session = CreateSession(code); - Assert.NotNull(session); - - CheckStart(session.Session); - CheckReturn(session.Session, 12, expected); + """); } [WorkItem("https://github.com/dotnet/roslyn/issues/3447")] @@ -1210,16 +1152,25 @@ public void X() $$ } """; + var globalOptions = new OptionsCollection(LanguageNames.CSharp) + { + { AutoFormattingOptionsStorage.FormatOnCloseBrace, false }, + { FormattingOptions2.SmartIndent, FormattingOptions2.IndentStyle.Block }, + }; + + using var session = CreateSession(code, globalOptions); + Assert.NotNull(session); - var expected = """ + CheckStart(session.Session); + Assert.Equal(""" class C { public void X() {} } - """; + """, session.Session.SubjectBuffer.CurrentSnapshot.GetText()); - var expectedAfterReturn = """ + CheckReturn(session.Session, 4, """ class C { public void X() @@ -1227,20 +1178,7 @@ public void X() } } - """; - var globalOptions = new OptionsCollection(LanguageNames.CSharp) - { - { AutoFormattingOptionsStorage.FormatOnCloseBrace, false }, - { FormattingOptions2.SmartIndent, FormattingOptions2.IndentStyle.Block }, - }; - - using var session = CreateSession(code, globalOptions); - Assert.NotNull(session); - - CheckStart(session.Session); - Assert.Equal(expected, session.Session.SubjectBuffer.CurrentSnapshot.GetText()); - - CheckReturn(session.Session, 4, expectedAfterReturn); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/2224")] @@ -1253,15 +1191,6 @@ public class C1 $$ } """; - - var expected = """ - namespace NS1 - { - public class C1 - { } - } - """; - var globalOptions = new OptionsCollection(LanguageNames.CSharp) { { FormattingOptions2.SmartIndent, FormattingOptions2.IndentStyle.None }, @@ -1271,7 +1200,13 @@ public class C1 Assert.NotNull(session); CheckStart(session.Session); - Assert.Equal(expected, session.Session.SubjectBuffer.CurrentSnapshot.GetText()); + Assert.Equal(""" + namespace NS1 + { + public class C1 + { } + } + """, session.Session.SubjectBuffer.CurrentSnapshot.GetText()); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/2330")] @@ -1284,16 +1219,24 @@ public class C1 $$ } """; + var globalOptions = new OptionsCollection(LanguageNames.CSharp) + { + { FormattingOptions2.SmartIndent, FormattingOptions2.IndentStyle.Block }, + }; + + using var session = CreateSession(code, globalOptions); + Assert.NotNull(session); - var expected = """ + CheckStart(session.Session); + Assert.Equal(""" namespace NS1 { public class C1 { } } - """; + """, session.Session.SubjectBuffer.CurrentSnapshot.GetText()); - var expectedAfterReturn = """ + CheckReturn(session.Session, 8, """ namespace NS1 { public class C1 @@ -1301,20 +1244,7 @@ public class C1 } } - """; - - var globalOptions = new OptionsCollection(LanguageNames.CSharp) - { - { FormattingOptions2.SmartIndent, FormattingOptions2.IndentStyle.Block }, - }; - - using var session = CreateSession(code, globalOptions); - Assert.NotNull(session); - - CheckStart(session.Session); - Assert.Equal(expected, session.Session.SubjectBuffer.CurrentSnapshot.GetText()); - - CheckReturn(session.Session, 8, expectedAfterReturn); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/2330")] @@ -1329,8 +1259,16 @@ public class C1 } } """; + var globalOptions = new OptionsCollection(LanguageNames.CSharp) + { + { FormattingOptions2.SmartIndent, FormattingOptions2.IndentStyle.Block }, + }; + + using var session = CreateSession(code, globalOptions); + Assert.NotNull(session); - var expected = """ + CheckStart(session.Session); + Assert.Equal(""" namespace NS1 { public class C1 @@ -1338,9 +1276,9 @@ public class C1 } } - """; + """, session.Session.SubjectBuffer.CurrentSnapshot.GetText()); - var expectedAfterReturn = """ + CheckReturn(session.Session, 8, """ namespace NS1 { public class C1 @@ -1350,20 +1288,7 @@ public class C1 } } - """; - - var globalOptions = new OptionsCollection(LanguageNames.CSharp) - { - { FormattingOptions2.SmartIndent, FormattingOptions2.IndentStyle.Block }, - }; - - using var session = CreateSession(code, globalOptions); - Assert.NotNull(session); - - CheckStart(session.Session); - Assert.Equal(expected, session.Session.SubjectBuffer.CurrentSnapshot.GetText()); - - CheckReturn(session.Session, 8, expectedAfterReturn); + """); } [WpfFact] @@ -1378,8 +1303,11 @@ void M() } } """; + using var session = CreateSession(code); + Assert.NotNull(session); - var expected = """ + CheckStart(session.Session); + CheckText(session.Session, """ class C { void M() @@ -1387,30 +1315,22 @@ void M() var x = new int[] {} } } - """; - using var session = CreateSession(code); - Assert.NotNull(session); - - CheckStart(session.Session); - CheckText(session.Session, expected); + """); } [WpfFact] public void DoesNotFormatOnReturnWithNonWhitespaceInBetween() { var code = @"class C $$"; - - var expected = """ - class C { dd - } - """; - using var session = CreateSession(code); Assert.NotNull(session); CheckStart(session.Session); Type(session.Session, "dd"); - CheckReturn(session.Session, 0, expected); + CheckReturn(session.Session, 0, """ + class C { dd + } + """); } [WpfFact] @@ -1425,7 +1345,11 @@ void M(string[] args) } } """; - var expectedAfterStart = """ + using var session = CreateSession(code); + Assert.NotNull(session); + + CheckStart(session.Session); + Assert.Equal(""" class C { void M(string[] args) @@ -1433,27 +1357,13 @@ void M(string[] args) var s = $"{ args.Select(a => { })}" } } - """; - - using var session = CreateSession(code); - Assert.NotNull(session); - - CheckStart(session.Session); - Assert.Equal(expectedAfterStart, session.Session.SubjectBuffer.CurrentSnapshot.GetText()); + """, session.Session.SubjectBuffer.CurrentSnapshot.GetText()); } [WpfFact] public void CurlyBraceFormatting_DoesNotAddNewLineWhenAlreadyExists() { var code = @"class C $$"; - - var expected = """ - class C - { - - } - """; - using var session = CreateSession(code); Assert.NotNull(session); @@ -1463,7 +1373,12 @@ class C var buffer = session.Session.SubjectBuffer; buffer.Insert(10, Environment.NewLine); - CheckReturn(session.Session, 4, expected); + CheckReturn(session.Session, 4, """ + class C + { + + } + """); } [WpfFact] @@ -1826,18 +1741,6 @@ namespace NS1 $$ """; - var expected = """ - namespace NS1 - {} - """; - - var expectedAfterReturn = """ - namespace NS1 - { - - } - """; - // Those option ensures no additional formatting would happen around added braces, including indention of added newline var globalOptions = new OptionsCollection(LanguageNames.CSharp) { @@ -1849,9 +1752,17 @@ namespace NS1 Assert.NotNull(session); CheckStart(session.Session); - Assert.Equal(expected, session.Session.SubjectBuffer.CurrentSnapshot.GetText()); + Assert.Equal(""" + namespace NS1 + {} + """, session.Session.SubjectBuffer.CurrentSnapshot.GetText()); + + CheckReturn(session.Session, 0, """ + namespace NS1 + { - CheckReturn(session.Session, 0, expectedAfterReturn); + } + """); } [WpfFact] @@ -1866,8 +1777,11 @@ static class C } } """; + using var session = CreateSession(code, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersionExtensions.CSharpNext)); + Assert.NotNull(session); - var expectedBeforeReturn = """ + CheckStart(session.Session); + CheckText(session.Session, """ namespace N { static class C @@ -1875,9 +1789,8 @@ static class C extension(string s) { } } } - """; - - var expectedAfterReturn = """ + """); + CheckReturn(session.Session, 12, """ namespace N { static class C @@ -1888,13 +1801,7 @@ static class C } } } - """; - using var session = CreateSession(code, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersionExtensions.CSharpNext)); - Assert.NotNull(session); - - CheckStart(session.Session); - CheckText(session.Session, expectedBeforeReturn); - CheckReturn(session.Session, 12, expectedAfterReturn); + """); } internal static Holder CreateSession( diff --git a/src/EditorFeatures/CSharpTest/AutomaticCompletion/AutomaticBracketCompletionTests.cs b/src/EditorFeatures/CSharpTest/AutomaticCompletion/AutomaticBracketCompletionTests.cs index de921405533ce..1926bb4d949a3 100644 --- a/src/EditorFeatures/CSharpTest/AutomaticCompletion/AutomaticBracketCompletionTests.cs +++ b/src/EditorFeatures/CSharpTest/AutomaticCompletion/AutomaticBracketCompletionTests.cs @@ -293,7 +293,9 @@ void M(object o) } } """; - var expectedBeforeReturn = """ + using var session = CreateSession(code); + CheckStart(session.Session); + CheckText(session.Session, """ class C { void M(object o) @@ -301,8 +303,8 @@ void M(object o) _ = o is [] } } - """; - var expected = """ + """); + CheckReturn(session.Session, 12, """ class C { void M(object o) @@ -313,11 +315,7 @@ void M(object o) ] } } - """; - using var session = CreateSession(code); - CheckStart(session.Session); - CheckText(session.Session, expectedBeforeReturn); - CheckReturn(session.Session, 12, expected); + """); } internal static Holder CreateSession(string code) diff --git a/src/EditorFeatures/CSharpTest/AutomaticCompletion/AutomaticLineEnderTests.cs b/src/EditorFeatures/CSharpTest/AutomaticCompletion/AutomaticLineEnderTests.cs index c3b01029400f0..2cc2573ac233a 100644 --- a/src/EditorFeatures/CSharpTest/AutomaticCompletion/AutomaticLineEnderTests.cs +++ b/src/EditorFeatures/CSharpTest/AutomaticCompletion/AutomaticLineEnderTests.cs @@ -1402,29 +1402,28 @@ public class Bar [WpfFact] public void TestGetAccessorOfProperty() { - var initialMarkup = """ + var firstResult = """ public class Bar { public int P { - ge$$t$$ + get + { + $$ + } } } """; - - var firstResult = """ + Test(firstResult, """ public class Bar { public int P { - get - { - $$ - } + ge$$t$$ } } - """; - var secondResult = """ + """); + Test(""" public class Bar { public int P @@ -1433,36 +1432,34 @@ public int P $$ } } - """; - Test(firstResult, initialMarkup); - Test(secondResult, firstResult); + """, firstResult); } [WpfFact] public void TestSetAccessorOfProperty() { - var initialMarkup = """ + var firstResult = """ public class Bar { public int P { - set$$ + set + { + $$ + } } } """; - var firstResult = """ + Test(firstResult, """ public class Bar { public int P { - set - { - $$ - } + set$$ } } - """; - var secondResult = """ + """); + Test(""" public class Bar { public int P @@ -1471,9 +1468,7 @@ public int P $$ } } - """; - Test(firstResult, initialMarkup); - Test(secondResult, firstResult); + """, firstResult); } [WpfFact] @@ -1787,12 +1782,6 @@ public event EventHandler e [WpfFact] public void TestField() { - var initialMarkup = """ - public class Bar - { - p$$ublic i$$nt i$$ii$$ - } - """; var firstResult = """ public class Bar { @@ -1802,16 +1791,19 @@ public int iii } } """; - var secondResult = """ + Test(firstResult, """ + public class Bar + { + p$$ublic i$$nt i$$ii$$ + } + """); + Test(""" public class Bar { public int iii; $$ } - """; - - Test(firstResult, initialMarkup); - Test(secondResult, firstResult); + """, firstResult); } [WpfFact] @@ -1893,13 +1885,6 @@ public class Bar [WpfFact] public void TestEvent() { - var initialMarkup = """ - using System; - public class Bar - { - pu$$blic e$$vent EventHand$$ler c$$c$$ - } - """; var firstResult = """ using System; public class Bar @@ -1910,16 +1895,21 @@ public event EventHandler cc } } """; - var secondResult = """ + Test(firstResult, """ + using System; + public class Bar + { + pu$$blic e$$vent EventHand$$ler c$$c$$ + } + """); + Test(""" using System; public class Bar { public event EventHandler cc; $$ } - """; - Test(firstResult, initialMarkup); - Test(secondResult, firstResult); + """, firstResult); } [WpfFact] @@ -1950,12 +1940,15 @@ public event EventHandler Foo [WpfFact] public void TestObjectCreationExpressionWithParenthesis() { - var initialMarkup = """ + var firstResult = """ public class Bar { public void M() { - var f = n$$ew F$$oo($$)$$ + var f = new Foo() + { + $$ + }; } } public class Foo @@ -1964,16 +1957,12 @@ public class Foo public int PP { get; set; } } """; - - var firstResult = """ + Test(firstResult, """ public class Bar { public void M() { - var f = new Foo() - { - $$ - }; + var f = n$$ew F$$oo($$)$$ } } public class Foo @@ -1981,9 +1970,8 @@ public class Foo public int HH { get; set; } public int PP { get; set; } } - """; - - var secondResult = """ + """); + Test(""" public class Bar { public void M() @@ -1997,21 +1985,21 @@ public class Foo public int HH { get; set; } public int PP { get; set; } } - """; - - Test(firstResult, initialMarkup); - Test(secondResult, firstResult); + """, firstResult); } [WpfFact] public void TestObjectCreationExpressionWithNoParenthesis() { - var initialMarkUp = """ + var firstResult = """ public class Bar { public void M() { - var f = n$$ew F$$oo$$ + var f = new Foo() + { + $$ + }; } } public class Foo @@ -2020,16 +2008,12 @@ public class Foo public int PP { get; set; } } """; - - var firstResult = """ + Test(firstResult, """ public class Bar { public void M() { - var f = new Foo() - { - $$ - }; + var f = n$$ew F$$oo$$ } } public class Foo @@ -2037,9 +2021,8 @@ public class Foo public int HH { get; set; } public int PP { get; set; } } - """; - - var secondResult = """ + """); + Test(""" public class Bar { public void M() @@ -2053,21 +2036,21 @@ public class Foo public int HH { get; set; } public int PP { get; set; } } - """; - - Test(firstResult, initialMarkUp); - Test(secondResult, firstResult); + """, firstResult); } [WpfFact] public void TestObjectCreationExpressionWithCorrectSemicolon() { - var initialMarkUp = """ + var firstResult = """ public class Bar { public void M() { - var f = n$$ew F$$oo$$; + var f = new Foo() + { + $$ + }; } } public class Foo @@ -2076,16 +2059,12 @@ public class Foo public int PP { get; set; } } """; - - var firstResult = """ + Test(firstResult, """ public class Bar { public void M() { - var f = new Foo() - { - $$ - }; + var f = n$$ew F$$oo$$; } } public class Foo @@ -2093,9 +2072,8 @@ public class Foo public int HH { get; set; } public int PP { get; set; } } - """; - - var secondResult = """ + """); + Test(""" public class Bar { public void M() @@ -2109,21 +2087,21 @@ public class Foo public int HH { get; set; } public int PP { get; set; } } - """; - - Test(firstResult, initialMarkUp); - Test(secondResult, firstResult); + """, firstResult); } [WpfFact] public void TestObjectCreationExpressionUsedAsExpression() { - var initialMarkUp = """ + var firstResult = """ public class Bar { public void M() { - N(ne$$w Fo$$o$$); + N(new Foo() + { + $$ + }); } private void N(Foo f) @@ -2136,16 +2114,12 @@ public class Foo public int PP { get; set; } } """; - - var firstResult = """ + Test(firstResult, """ public class Bar { public void M() { - N(new Foo() - { - $$ - }); + N(ne$$w Fo$$o$$); } private void N(Foo f) @@ -2157,9 +2131,8 @@ public class Foo public int HH { get; set; } public int PP { get; set; } } - """; - - var secondResult = """ + """); + Test(""" public class Bar { public void M() @@ -2177,21 +2150,21 @@ public class Foo public int HH { get; set; } public int PP { get; set; } } - """; - - Test(firstResult, initialMarkUp); - Test(secondResult, firstResult); + """, firstResult); } [WpfFact] public void TestObjectCreationExpressionInUsingStatement() { - var initialMarkup = """ + var firstResult = """ public class Bar { public void M() { - using(var a = n$$ew F$$oo($$)$$) + using(var a = new Foo() + { + $$ + }) } } public class Foo @@ -2200,16 +2173,12 @@ public class Foo public int PP { get; set; } } """; - - var firstResult = """ + Test(firstResult, """ public class Bar { public void M() { - using(var a = new Foo() - { - $$ - }) + using(var a = n$$ew F$$oo($$)$$) } } public class Foo @@ -2217,9 +2186,8 @@ public class Foo public int HH { get; set; } public int PP { get; set; } } - """; - - var secondResult = """ + """); + Test(""" public class Bar { public void M() @@ -2233,10 +2201,7 @@ public class Foo public int HH { get; set; } public int PP { get; set; } } - """; - - Test(firstResult, initialMarkup); - Test(secondResult, firstResult); + """, firstResult); } [WpfFact] diff --git a/src/EditorFeatures/CSharpTest/BlockCommentEditing/BlockCommentEditingTests.cs b/src/EditorFeatures/CSharpTest/BlockCommentEditing/BlockCommentEditingTests.cs index 3e326d1c12949..eb7ea406f9f9b 100644 --- a/src/EditorFeatures/CSharpTest/BlockCommentEditing/BlockCommentEditingTests.cs +++ b/src/EditorFeatures/CSharpTest/BlockCommentEditing/BlockCommentEditingTests.cs @@ -22,696 +22,602 @@ public sealed class BlockCommentEditingTests : AbstractTypingCommandHandlerTest< [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/11057")] public void EdgeCase0() { - var code = @" + Verify(@" $$/**/ -"; - var expected = @" +", @" $$/**/ -"; - Verify(code, expected); +"); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/11057")] public void EdgeCase1() { - var code = @" + Verify(@" /**/$$ -"; - var expected = @" +", @" /**/ $$ -"; - Verify(code, expected); +"); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/11056")] public void EdgeCase2() { - var code = @" + Verify(@" $$/* */ -"; - var expected = @" +", @" $$/* */ -"; - Verify(code, expected); +"); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/11056")] public void EdgeCase3() { - var code = @" + Verify(@" /* */$$ -"; - var expected = @" +", @" /* */ $$ -"; - Verify(code, expected); +"); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/16128")] public void EofCase0() { - var code = @" -/* */$$"; - var expected = @" + Verify(@" +/* */$$", @" /* */ -$$"; - Verify(code, expected); +$$"); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/16128")] public void EofCase1() { - var code = @" - /*$$"; - var expected = @" + Verify(@" + /*$$", @" /* - * $$"; - Verify(code, expected); + * $$"); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/16128")] public void EofCase2() { - var code = @" - /***$$"; - var expected = @" + Verify(@" + /***$$", @" /*** - * $$"; - Verify(code, expected); + * $$"); } [WpfFact] public void InsertOnStartLine0() { - var code = @" + Verify(@" /*$$ -"; - var expected = @" +", @" /* * $$ -"; - Verify(code, expected); +"); } [WpfFact] public void InsertOnStartLine1() { - var code = @" + Verify(@" /*$$*/ -"; - var expected = @" +", @" /* $$*/ -"; - Verify(code, expected); +"); } [WpfFact] public void InsertOnStartLine2() { - var code = @" + Verify(@" /*$$ */ -"; - var expected = @" +", @" /* * $$*/ -"; - Verify(code, expected); +"); } [WpfFact] public void InsertOnStartLine3() { - var code = @" + Verify(@" /* $$ 1. */ -"; - var expected = @" +", @" /* * $$1. */ -"; - Verify(code, expected); +"); } [WpfFact] public void InsertOnStartLine4() { - var code = @" + Verify(@" /* 1.$$ */ -"; - var expected = @" +", @" /* 1. * $$ */ -"; - Verify(code, expected); +"); } [WpfFact] public void InsertOnStartLine5() { - var code = @" + Verify(@" /********$$ -"; - var expected = @" +", @" /******** * $$ -"; - Verify(code, expected); +"); } [WpfFact] public void InsertOnStartLine6() { - var code = @" + Verify(@" /**$$ -"; - var expected = @" +", @" /** * $$ -"; - Verify(code, expected); +"); } [WpfFact] public void InsertOnStartLine7() { - var code = @" + Verify(@" /* $$ -"; - var expected = @" +", @" /* * $$ -"; - Verify(code, expected); +"); } [WpfFact] public void NotInsertOnStartLine0() { - var code = @" + Verify(@" /$$* */ -"; - var expected = @" +", @" / $$* */ -"; - Verify(code, expected); +"); } [WpfFact] public void InsertOnMiddleLine0() { - var code = @" + Verify(@" /* *$$ -"; - var expected = @" +", @" /* * *$$ -"; - Verify(code, expected); +"); } [WpfFact] public void InsertOnMiddleLine1() { - var code = @" + Verify(@" /* *$$*/ -"; - var expected = @" +", @" /* * $$*/ -"; - Verify(code, expected); +"); } [WpfFact] public void InsertOnMiddleLine2() { - var code = @" + Verify(@" /* *$$ */ -"; - var expected = @" +", @" /* * *$$*/ -"; - Verify(code, expected); +"); } [WpfFact] public void InsertOnMiddleLine3() { - var code = @" + Verify(@" /* * $$ 1. */ -"; - var expected = @" +", @" /* * * $$1. */ -"; - Verify(code, expected); +"); } [WpfFact] public void InsertOnMiddleLine4() { - var code = @" + Verify(@" /* * 1.$$ */ -"; - var expected = @" +", @" /* * 1. * $$ */ -"; - Verify(code, expected); +"); } [WpfFact] public void InsertOnMiddleLine5() { - var code = @" + Verify(@" /* * 1. * $$ */ -"; - var expected = @" +", @" /* * 1. * * $$ */ -"; - Verify(code, expected); +"); } [WpfFact] public void InsertOnMiddleLine6() { - var code = @" + Verify(@" /* $$ * */ -"; - var expected = @" +", @" /* $$* */ -"; - Verify(code, expected); +"); } [WpfFact] public void InsertOnMiddleLine7() { - var code = @" + Verify(@" /* *************$$ */ -"; - var expected = @" +", @" /* ************* *$$ */ -"; - Verify(code, expected); +"); } [WpfFact] public void InsertOnMiddleLine8() { - var code = @" + Verify(@" /** *$$ */ -"; - var expected = @" +", @" /** * *$$ */ -"; - Verify(code, expected); +"); } [WpfFact] public void InsertOnMiddleLine9() { - var code = @" + Verify(@" /** *$$ -"; - var expected = @" +", @" /** * *$$ -"; - Verify(code, expected); +"); } [WpfFact] public void InsertOnEndLine0() { - var code = @" + Verify(@" /* *$$/ -"; - var expected = @" +", @" /* * *$$/ -"; - Verify(code, expected); +"); } [WpfFact] public void InsertOnEndLine1() { - var code = @" + Verify(@" /** *$$/ -"; - var expected = @" +", @" /** * *$$/ -"; - Verify(code, expected); +"); } [WpfFact] public void InsertOnEndLine2() { - var code = @" + Verify(@" /** * *$$/ -"; - var expected = @" +", @" /** * * *$$/ -"; - Verify(code, expected); +"); } [WpfFact] public void InsertOnEndLine3() { - var code = @" + Verify(@" /* $$ */ -"; - var expected = @" +", @" /* $$*/ -"; - Verify(code, expected); +"); } [WpfFact] public void InsertOnEndLine4() { - var code = @" + Verify(@" /* $$*/ -"; - var expected = @" +", @" /* $$*/ -"; - Verify(code, expected); +"); } [WpfFact] public void NotInsertInVerbatimString0() { - var code = @" + Verify(@" var code = @"" /*$$ ""; -"; - var expected = @" +", @" var code = @"" /* $$ ""; -"; - Verify(code, expected); +"); } [WpfFact] public void NotInsertInVerbatimString1() { - var code = @" + Verify(@" var code = @"" /* *$$ ""; -"; - var expected = @" +", @" var code = @"" /* * $$ ""; -"; - Verify(code, expected); +"); } [WpfFact] public void BoundCheckInsertOnStartLine0() { - var code = @" - /$$*"; - var expected = @" + Verify(@" + /$$*", @" / -$$*"; - Verify(code, expected); +$$*"); } [WpfFact] public void BoundCheckInsertOnStartLine1() { - var code = @" - /*$$ "; - var expected = @" + Verify(@" + /*$$ ", @" /* - * $$"; - Verify(code, expected); + * $$"); } [WpfFact] public void BoundCheckInsertOnMiddleLine() { - var code = @" + Verify(@" /* - *$$ "; - var expected = @" + *$$ ", @" /* * - *$$"; - Verify(code, expected); + *$$"); } [WpfFact] public void BoundCheckInsertOnEndLine() { - var code = @" + Verify(@" /* - *$$/"; - var expected = @" + *$$/", @" /* * - *$$/"; - Verify(code, expected); + *$$/"); } [WpfFact] public void InsertOnStartLine2_Tab() { - var code = @" + VerifyTabs(@" /*$$*/ -"; - var expected = @" +", @" /* * $$*/ -"; - VerifyTabs(code, expected); +"); } [WpfFact] public void InsertOnStartLine3_Tab() { - var code = @" + VerifyTabs(@" /*$$1. */ -"; - var expected = @" +", @" /* *$$1. */ -"; - VerifyTabs(code, expected); +"); } [WpfFact] public void InsertOnStartLine4_Tab() { - var code = @" + VerifyTabs(@" /* 1.$$ */ -"; - var expected = @" +", @" /* 1. * $$ */ -"; - VerifyTabs(code, expected); +"); } [WpfFact] public void InsertOnStartLine6_Tab() { - var code = @" + VerifyTabs(@" /*$$ -"; - var expected = @" +", @" /* *$$ -"; - VerifyTabs(code, expected); +"); } [WpfFact] public void InsertOnMiddleLine2_Tab() { - var code = @" + VerifyTabs(@" /* *$$*/ -"; - var expected = @" +", @" /* * *$$*/ -"; - VerifyTabs(code, expected); +"); } [WpfFact] public void InsertOnMiddleLine3_Tab() { - var code = @" + VerifyTabs(@" /* * $$1. */ -"; - var expected = @" +", @" /* * * $$1. */ -"; - VerifyTabs(code, expected); +"); } [WpfFact] public void InsertOnMiddleLine4_Tab() { - var code = @" + VerifyTabs(@" /* * 1.$$ */ -"; - var expected = @" +", @" /* * 1. * $$ */ -"; - VerifyTabs(code, expected); +"); } [WpfFact] public void InsertOnMiddleLine5_Tab() { - var code = @" + VerifyTabs(@" /* * 1. * $$ */ -"; - var expected = @" +", @" /* * 1. * * $$ */ -"; - VerifyTabs(code, expected); +"); } [WpfFact] public void InLanguageConstructTrailingTrivia() { - var code = @" + Verify(@" class C { int i; /*$$ } -"; - var expected = @" +", @" class C { int i; /* * $$ } -"; - Verify(code, expected); +"); } [WpfFact] public void InLanguageConstructTrailingTrivia_Tabs() { - var code = @" + VerifyTabs(@" class C { int i; /*$$ } -"; - var expected = @" +", @" class C { int i; /* * $$ } -"; - VerifyTabs(code, expected); +"); } protected override EditorTestWorkspace CreateTestWorkspace(string initialMarkup) diff --git a/src/EditorFeatures/CSharpTest/BlockCommentEditing/CloseBlockCommentTests.cs b/src/EditorFeatures/CSharpTest/BlockCommentEditing/CloseBlockCommentTests.cs index b64399895711e..562945aaaefd8 100644 --- a/src/EditorFeatures/CSharpTest/BlockCommentEditing/CloseBlockCommentTests.cs +++ b/src/EditorFeatures/CSharpTest/BlockCommentEditing/CloseBlockCommentTests.cs @@ -23,264 +23,229 @@ public sealed class CloseBlockCommentTests : AbstractTypingCommandHandlerTest* $$ - """; - var expected = """ + """, """ /* * */$$ - """; - VerifyTabs(code, expected); + """); } [WpfFact] public void NotClosedAfterAsteriskSpaceWithOptionOff() { - var code = """ + Verify(""" /* * * $$ - """; - var expected = """ + """, """ /* * * /$$ - """; - Verify(code, expected, workspace => + """, workspace => { var globalOptions = workspace.GetService(); globalOptions.SetGlobalOption(BlockCommentEditingOptionsStorage.AutoInsertBlockCommentStartString, LanguageNames.CSharp, false); @@ -290,80 +255,65 @@ public void NotClosedAfterAsteriskSpaceWithOptionOff() [WpfFact] public void NotClosedAfterAsteriskSpaceOutsideComment() { - var code = """ + Verify(""" / * * * $$ - """; - var expected = """ + """, """ / * * * /$$ - """; - Verify(code, expected); + """); } [WpfFact] public void NotClosedAfterAsteriskSpaceInsideString() { - var code = """ + Verify(""" class C { string s = @" /* * * $$ - """; - var expected = """ + """, """ class C { string s = @" /* * * /$$ - """; - Verify(code, expected); + """); } [WpfFact] public void ClosedAfterAsteriskSpaceEndOfFile() { - var code = """ + Verify(""" /* * $$ - """; - var expected = """ + """, """ /* */$$ - """; - Verify(code, expected); + """); } [WpfFact] public void NotClosedAfterAsteriskSpaceStartOfFile() { - var code = @"* $$"; - var expected = @"* /$$"; - - Verify(code, expected); + Verify(@"* $$", @"* /$$"); } [WpfFact] public void NotClosedAfterSpaceStartOfFile() { - var code = @" $$"; - var expected = @" /$$"; - - Verify(code, expected); + Verify(@" $$", @" /$$"); } [WpfFact] public void NotClosedAtStartOfFile() { - var code = @"$$"; - var expected = @"/$$"; - - Verify(code, expected); + Verify(@"$$", @"/$$"); } protected override EditorTestWorkspace CreateTestWorkspace(string initialMarkup) diff --git a/src/EditorFeatures/CSharpTest/BraceHighlighting/BraceHighlightingTests.cs b/src/EditorFeatures/CSharpTest/BraceHighlighting/BraceHighlightingTests.cs index 82e45e1fd1f4c..e930bb80b375e 100644 --- a/src/EditorFeatures/CSharpTest/BraceHighlighting/BraceHighlightingTests.cs +++ b/src/EditorFeatures/CSharpTest/BraceHighlighting/BraceHighlightingTests.cs @@ -40,10 +40,8 @@ public class C { public class C [|{|] [|}|]$$ """)] - public async Task TestCurlies(string testCase) - { - await TestBraceHighlightingAsync(testCase); - } + public Task TestCurlies(string testCase) + => TestBraceHighlightingAsync(testCase); [WpfTheory] [InlineData(""" @@ -81,10 +79,8 @@ public class C { public void Goo()[|{|][|}|]$$ } """)] - public async Task TestTouchingItems(string testCase) - { - await TestBraceHighlightingAsync(testCase); - } + public Task TestTouchingItems(string testCase) + => TestBraceHighlightingAsync(testCase); [WpfTheory] [InlineData("/// $$Goo")] @@ -105,10 +101,8 @@ public async Task TestTouchingItems(string testCase) [InlineData("unsafe class C { delegate*$$[|<|] int, int[|>|] functionPointer; }")] [InlineData("unsafe class C { delegate*[|<|]int, int[|>$$|] functionPointer; }")] [InlineData("unsafe class C { delegate*|]$$> functionPointer; }")] - public async Task TestAngles(string testCase) - { - await TestBraceHighlightingAsync(testCase); - } + public Task TestAngles(string testCase) + => TestBraceHighlightingAsync(testCase); [WpfFact] public async Task TestNoHighlightingOnOperators() @@ -347,9 +341,8 @@ class C } [WpfFact] - public async Task TestRegexGroupBracket1() - { - var input = """ + public Task TestRegexGroupBracket1() + => TestBraceHighlightingAsync(""" using System.Text.RegularExpressions; class C @@ -359,15 +352,11 @@ void Goo() var r = new Regex(@"$$[|(|]a[|)|]"); } } - """; - - await TestBraceHighlightingAsync(input); - } + """); [WpfFact] - public async Task TestRegexGroupBracket2() - { - var input = """ + public Task TestRegexGroupBracket2() + => TestBraceHighlightingAsync(""" using System.Text.RegularExpressions; class C @@ -377,15 +366,11 @@ void Goo() var r = new Regex(@"[|(|]a[|)|]$$"); } } - """; - - await TestBraceHighlightingAsync(input); - } + """); [WpfFact] - public async Task TestRegexUnclosedGroupBracket1() - { - var input = """ + public Task TestRegexUnclosedGroupBracket1() + => TestBraceHighlightingAsync(""" using System.Text.RegularExpressions; class C @@ -395,15 +380,11 @@ void Goo() var r = new Regex(@"$$(a"); } } - """; - - await TestBraceHighlightingAsync(input); - } + """); [WpfFact] - public async Task TestRegexCommentBracket1() - { - var input = """ + public Task TestRegexCommentBracket1() + => TestBraceHighlightingAsync(""" using System.Text.RegularExpressions; class C @@ -413,15 +394,11 @@ void Goo() var r = new Regex(@"$$[|(|]?#a[|)|]"); } } - """; - - await TestBraceHighlightingAsync(input); - } + """); [WpfFact] - public async Task TestRegexCommentBracket2() - { - var input = """ + public Task TestRegexCommentBracket2() + => TestBraceHighlightingAsync(""" using System.Text.RegularExpressions; class C @@ -431,15 +408,11 @@ void Goo() var r = new Regex(@"[|(|]?#a[|)|]$$"); } } - """; - - await TestBraceHighlightingAsync(input); - } + """); [WpfFact] - public async Task TestRegexUnclosedCommentBracket() - { - var input = """ + public Task TestRegexUnclosedCommentBracket() + => TestBraceHighlightingAsync(""" using System.Text.RegularExpressions; class C @@ -449,15 +422,11 @@ void Goo() var r = new Regex(@"$$(?#a"); } } - """; - - await TestBraceHighlightingAsync(input); - } + """); [WpfFact] - public async Task TestRegexCharacterClassBracket1() - { - var input = """ + public Task TestRegexCharacterClassBracket1() + => TestBraceHighlightingAsync(""" using System.Text.RegularExpressions; class C @@ -467,15 +436,11 @@ void Goo() var r = new Regex(@"$$[|<|]a[|>|]"); } } - """; - - await TestBraceHighlightingAsync(input, swapAnglesWithBrackets: true); - } + """, swapAnglesWithBrackets: true); [WpfFact] - public async Task TestRegexCharacterClassBracket2() - { - var input = """ + public Task TestRegexCharacterClassBracket2() + => TestBraceHighlightingAsync(""" using System.Text.RegularExpressions; class C @@ -485,14 +450,11 @@ void Goo() var r = new Regex(@"[|<|]a[|>|]$$"); } } - """; - await TestBraceHighlightingAsync(input, swapAnglesWithBrackets: true); - } + """, swapAnglesWithBrackets: true); [WpfFact] - public async Task TestRegexUnclosedCharacterClassBracket1() - { - var input = """ + public Task TestRegexUnclosedCharacterClassBracket1() + => TestBraceHighlightingAsync(""" using System.Text.RegularExpressions; class C @@ -502,15 +464,11 @@ void Goo() var r = new Regex(@"$$ TestBraceHighlightingAsync(""" using System.Text.RegularExpressions; class C @@ -520,15 +478,11 @@ void Goo() var r = new Regex(@"$$[|<|]^a[|>|]"); } } - """; - - await TestBraceHighlightingAsync(input, swapAnglesWithBrackets: true); - } + """, swapAnglesWithBrackets: true); [WpfFact] - public async Task TestRegexNegativeCharacterClassBracket2() - { - var input = """ + public Task TestRegexNegativeCharacterClassBracket2() + => TestBraceHighlightingAsync(""" using System.Text.RegularExpressions; class C @@ -538,15 +492,11 @@ void Goo() var r = new Regex(@"[|<|]^a[|>|]$$"); } } - """; - - await TestBraceHighlightingAsync(input, swapAnglesWithBrackets: true); - } + """, swapAnglesWithBrackets: true); [WpfFact] - public async Task TestJsonBracket1() - { - var input = """ + public Task TestJsonBracket1() + => TestBraceHighlightingAsync(""" class C { void Goo() @@ -554,14 +504,11 @@ void Goo() var r = /*lang=json*/ @"new Json[|$$(|]1, 2, 3[|)|]"; } } - """; - await TestBraceHighlightingAsync(input); - } + """); [WpfFact] - public async Task TestJsonBracket2() - { - var input = """ + public Task TestJsonBracket2() + => TestBraceHighlightingAsync(""" class C { void Goo() @@ -569,14 +516,11 @@ void Goo() var r = /*lang=json*/ @"new Json[|(|]1, 2, 3[|)|]$$"; } } - """; - await TestBraceHighlightingAsync(input); - } + """); [WpfFact] - public async Task TestJsonBracket_RawStrings() - { - var input = """" + public Task TestJsonBracket_RawStrings() + => TestBraceHighlightingAsync("""" class C { void Goo() @@ -584,14 +528,11 @@ void Goo() var r = /*lang=json*/ """new Json[|$$(|]1, 2, 3[|)|]"""; } } - """"; - await TestBraceHighlightingAsync(input); - } + """"); [WpfFact] - public async Task TestUnmatchedJsonBracket1() - { - var input = """ + public Task TestUnmatchedJsonBracket1() + => TestBraceHighlightingAsync(""" class C { void Goo() @@ -599,14 +540,11 @@ void Goo() var r = /*lang=json*/ @"new Json$$(1, 2, 3"; } } - """; - await TestBraceHighlightingAsync(input); - } + """); [WpfFact] - public async Task TestJsonBracket_NoComment_NotLikelyJson() - { - var input = """ + public Task TestJsonBracket_NoComment_NotLikelyJson() + => TestBraceHighlightingAsync(""" class C { void Goo() @@ -614,14 +552,11 @@ void Goo() var r = @"$$[ 1, 2, 3 ]"; } } - """; - await TestBraceHighlightingAsync(input); - } + """); [WpfFact] - public async Task TestJsonBracket_NoComment_LikelyJson() - { - var input = """ + public Task TestJsonBracket_NoComment_LikelyJson() + => TestBraceHighlightingAsync(""" class C { void Goo() @@ -629,9 +564,7 @@ void Goo() var r = @"[ { prop: 0 }, new Json[|$$(|]1, 2, 3[|)|], 3 ]"; } } - """; - await TestBraceHighlightingAsync(input); - } + """); [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/32791")] [InlineData(@"$$ /* goo */ public class C { }")] @@ -644,10 +577,8 @@ void Goo() [InlineData(@" [|/*|] goo [|*$$/|] public class C { }")] [InlineData(@" [|/*|] goo [|*/|]$$ public class C { }")] [InlineData(@" /* goo */ $$public class C { }")] - public async Task TestBlockComments(string input) - { - await TestBraceHighlightingAsync(input); - } + public Task TestBlockComments(string input) + => TestBraceHighlightingAsync(input); [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/32791")] [InlineData(@"$$ /** goo */ public class C { }")] @@ -661,8 +592,6 @@ public async Task TestBlockComments(string input) [InlineData(@" [|/**|] goo [|*$$/|] public class C { }")] [InlineData(@" [|/**|] goo [|*/|]$$ public class C { }")] [InlineData(@" /** goo */ $$public class C { }")] - public async Task TestDocCommentBlockComments(string input) - { - await TestBraceHighlightingAsync(input); - } + public Task TestDocCommentBlockComments(string input) + => TestBraceHighlightingAsync(input); } diff --git a/src/EditorFeatures/CSharpTest/BraceMatching/CSharpBraceMatcherTests.cs b/src/EditorFeatures/CSharpTest/BraceMatching/CSharpBraceMatcherTests.cs index 15f3c3c3147d9..002b5c2d49026 100644 --- a/src/EditorFeatures/CSharpTest/BraceMatching/CSharpBraceMatcherTests.cs +++ b/src/EditorFeatures/CSharpTest/BraceMatching/CSharpBraceMatcherTests.cs @@ -18,656 +18,310 @@ protected override EditorTestWorkspace CreateWorkspaceFromCode(string code, Pars => EditorTestWorkspace.CreateCSharp(code, options); [Fact] - public async Task TestEmptyFile() - { - var code = @"$$"; - var expected = @""; - - await TestAsync(code, expected); - } + public Task TestEmptyFile() + => TestAsync(@"$$", @""); [Fact] - public async Task TestAtFirstPositionInFile() - { - var code = @"$$public class C { }"; - var expected = @"public class C { }"; - - await TestAsync(code, expected); - } + public Task TestAtFirstPositionInFile() + => TestAsync(@"$$public class C { }", @"public class C { }"); [Fact] - public async Task TestAtLastPositionInFile() - { - var code = @"public class C { }$$"; - var expected = @"public class C [|{|] }"; - - await TestAsync(code, expected); - } + public Task TestAtLastPositionInFile() + => TestAsync(@"public class C { }$$", @"public class C [|{|] }"); [Fact] - public async Task TestCurlyBrace1() - { - var code = @"public class C $${ }"; - var expected = @"public class C { [|}|]"; - - await TestAsync(code, expected); - } + public Task TestCurlyBrace1() + => TestAsync(@"public class C $${ }", @"public class C { [|}|]"); [Fact] - public async Task TestCurlyBrace2() - { - var code = @"public class C {$$ }"; - var expected = @"public class C { [|}|]"; - - await TestAsync(code, expected); - } + public Task TestCurlyBrace2() + => TestAsync(@"public class C {$$ }", @"public class C { [|}|]"); [Fact] - public async Task TestCurlyBrace3() - { - var code = @"public class C { $$}"; - var expected = @"public class C [|{|] }"; - - await TestAsync(code, expected); - } + public Task TestCurlyBrace3() + => TestAsync(@"public class C { $$}", @"public class C [|{|] }"); [Fact] - public async Task TestCurlyBrace4() - { - var code = @"public class C { }$$"; - var expected = @"public class C [|{|] }"; - - await TestAsync(code, expected); - } + public Task TestCurlyBrace4() + => TestAsync(@"public class C { }$$", @"public class C [|{|] }"); [Fact] - public async Task TestParen1() - { - var code = @"public class C { void Goo$$() { } }"; - var expected = @"public class C { void Goo([|)|] { } }"; - - await TestAsync(code, expected); - } + public Task TestParen1() + => TestAsync(@"public class C { void Goo$$() { } }", @"public class C { void Goo([|)|] { } }"); [Fact] - public async Task TestParen2() - { - var code = @"public class C { void Goo($$) { } }"; - var expected = @"public class C { void Goo([|)|] { } }"; - - await TestAsync(code, expected); - } + public Task TestParen2() + => TestAsync(@"public class C { void Goo($$) { } }", @"public class C { void Goo([|)|] { } }"); [Fact] - public async Task TestParen3() - { - var code = @"public class C { void Goo($$ ) { } }"; - var expected = @"public class C { void Goo( [|)|] { } }"; - - await TestAsync(code, expected); - } + public Task TestParen3() + => TestAsync(@"public class C { void Goo($$ ) { } }", @"public class C { void Goo( [|)|] { } }"); [Fact] - public async Task TestParen4() - { - var code = @"public class C { void Goo( $$) { } }"; - var expected = @"public class C { void Goo[|(|] ) { } }"; - - await TestAsync(code, expected); - } + public Task TestParen4() + => TestAsync(@"public class C { void Goo( $$) { } }", @"public class C { void Goo[|(|] ) { } }"); [Fact] - public async Task TestParen5() - { - var code = @"public class C { void Goo( )$$ { } }"; - var expected = @"public class C { void Goo[|(|] ) { } }"; - - await TestAsync(code, expected); - } + public Task TestParen5() + => TestAsync(@"public class C { void Goo( )$$ { } }", @"public class C { void Goo[|(|] ) { } }"); [Fact] - public async Task TestParen6() - { - var code = @"public class C { void Goo()$$ { } }"; - var expected = @"public class C { void Goo[|(|]) { } }"; - - await TestAsync(code, expected); - } + public Task TestParen6() + => TestAsync(@"public class C { void Goo()$$ { } }", @"public class C { void Goo[|(|]) { } }"); [Fact] - public async Task TestSquareBracket1() - { - var code = @"public class C { int$$[] i; }"; - var expected = @"public class C { int[[|]|] i; }"; - - await TestAsync(code, expected); - } + public Task TestSquareBracket1() + => TestAsync(@"public class C { int$$[] i; }", @"public class C { int[[|]|] i; }"); [Fact] - public async Task TestSquareBracket2() - { - var code = @"public class C { int[$$] i; }"; - var expected = @"public class C { int[[|]|] i; }"; - - await TestAsync(code, expected); - } + public Task TestSquareBracket2() + => TestAsync(@"public class C { int[$$] i; }", @"public class C { int[[|]|] i; }"); [Fact] - public async Task TestSquareBracket3() - { - var code = @"public class C { int[$$ ] i; }"; - var expected = @"public class C { int[ [|]|] i; }"; - - await TestAsync(code, expected); - } + public Task TestSquareBracket3() + => TestAsync(@"public class C { int[$$ ] i; }", @"public class C { int[ [|]|] i; }"); [Fact] - public async Task TestSquareBracket4() - { - var code = @"public class C { int[ $$] i; }"; - var expected = @"public class C { int[|[|] ] i; }"; - - await TestAsync(code, expected); - } + public Task TestSquareBracket4() + => TestAsync(@"public class C { int[ $$] i; }", @"public class C { int[|[|] ] i; }"); [Fact] - public async Task TestSquareBracket5() - { - var code = @"public class C { int[ ]$$ i; }"; - var expected = @"public class C { int[|[|] ] i; }"; - - await TestAsync(code, expected); - } + public Task TestSquareBracket5() + => TestAsync(@"public class C { int[ ]$$ i; }", @"public class C { int[|[|] ] i; }"); [Fact] - public async Task TestSquareBracket6() - { - var code = @"public class C { int[]$$ i; }"; - var expected = @"public class C { int[|[|]] i; }"; - - await TestAsync(code, expected); - } + public Task TestSquareBracket6() + => TestAsync(@"public class C { int[]$$ i; }", @"public class C { int[|[|]] i; }"); [Fact] - public async Task TestAngleBracket1() - { - var code = @"public class C { Goo$$ f; }"; - var expected = @"public class C { Goo|] f; }"; - - await TestAsync(code, expected); - } + public Task TestAngleBracket1() + => TestAsync(@"public class C { Goo$$ f; }", @"public class C { Goo|] f; }"); [Fact] - public async Task TestAngleBracket2() - { - var code = @"public class C { Goo<$$int> f; }"; - var expected = @"public class C { Goo|] f; }"; - - await TestAsync(code, expected); - } + public Task TestAngleBracket2() + => TestAsync(@"public class C { Goo<$$int> f; }", @"public class C { Goo|] f; }"); [Fact] - public async Task TestAngleBracket3() - { - var code = @"public class C { Goo f; }"; - var expected = @"public class C { Goo[|<|]int> f; }"; - - await TestAsync(code, expected); - } + public Task TestAngleBracket3() + => TestAsync(@"public class C { Goo f; }", @"public class C { Goo[|<|]int> f; }"); [Fact] - public async Task TestAngleBracket4() - { - var code = @"public class C { Goo$$ f; }"; - var expected = @"public class C { Goo[|<|]int> f; }"; - - await TestAsync(code, expected); - } + public Task TestAngleBracket4() + => TestAsync(@"public class C { Goo$$ f; }", @"public class C { Goo[|<|]int> f; }"); [Fact] - public async Task TestNestedAngleBracket1() - { - var code = @"public class C { Func$$> f; }"; - var expected = @"public class C { Func[|>|] f; }"; - - await TestAsync(code, expected); - } + public Task TestNestedAngleBracket1() + => TestAsync(@"public class C { Func$$> f; }", @"public class C { Func[|>|] f; }"); [Fact] - public async Task TestNestedAngleBracket2() - { - var code = @"public class C { Func<$$Func> f; }"; - var expected = @"public class C { Func[|>|] f; }"; - - await TestAsync(code, expected); - } + public Task TestNestedAngleBracket2() + => TestAsync(@"public class C { Func<$$Func> f; }", @"public class C { Func[|>|] f; }"); [Fact] - public async Task TestNestedAngleBracket3() - { - var code = @"public class C { Func> f; }"; - var expected = @"public class C { Func|]> f; }"; - - await TestAsync(code, expected); - } + public Task TestNestedAngleBracket3() + => TestAsync(@"public class C { Func> f; }", @"public class C { Func|]> f; }"); [Fact] - public async Task TestNestedAngleBracket4() - { - var code = @"public class C { Func> f; }"; - var expected = @"public class C { Func|]> f; }"; - - await TestAsync(code, expected); - } + public Task TestNestedAngleBracket4() + => TestAsync(@"public class C { Func> f; }", @"public class C { Func|]> f; }"); [Fact] - public async Task TestNestedAngleBracket5() - { - var code = @"public class C { Func> f; }"; - var expected = @"public class C { Func> f; }"; - - await TestAsync(code, expected); - } + public Task TestNestedAngleBracket5() + => TestAsync(@"public class C { Func> f; }", @"public class C { Func> f; }"); [Fact] - public async Task TestNestedAngleBracket6() - { - var code = @"public class C { Func$$> f; }"; - var expected = @"public class C { Func> f; }"; - - await TestAsync(code, expected); - } + public Task TestNestedAngleBracket6() + => TestAsync(@"public class C { Func$$> f; }", @"public class C { Func> f; }"); [Fact] - public async Task TestNestedAngleBracket7() - { - var code = @"public class C { Func $$> f; }"; - var expected = @"public class C { Func[|<|]Func > f; }"; - - await TestAsync(code, expected); - } + public Task TestNestedAngleBracket7() + => TestAsync(@"public class C { Func $$> f; }", @"public class C { Func[|<|]Func > f; }"); [Fact] - public async Task TestNestedAngleBracket8() - { - var code = @"public class C { Func>$$ f; }"; - var expected = @"public class C { Func[|<|]Func> f; }"; - - await TestAsync(code, expected); - } + public Task TestNestedAngleBracket8() + => TestAsync(@"public class C { Func>$$ f; }", @"public class C { Func[|<|]Func> f; }"); [Fact] - public async Task TestString1() - { - var code = @"public class C { string s = $$""Goo""; }"; - var expected = @"public class C { string s = ""Goo[|""|]; }"; - - await TestAsync(code, expected); - } + public Task TestString1() + => TestAsync(@"public class C { string s = $$""Goo""; }", @"public class C { string s = ""Goo[|""|]; }"); [Fact] - public async Task TestString2() - { - var code = @"public class C { string s = ""$$Goo""; }"; - var expected = @"public class C { string s = ""Goo[|""|]; }"; - - await TestAsync(code, expected); - } + public Task TestString2() + => TestAsync(@"public class C { string s = ""$$Goo""; }", @"public class C { string s = ""Goo[|""|]; }"); [Fact] - public async Task TestString3() - { - var code = @"public class C { string s = ""Goo$$""; }"; - var expected = @"public class C { string s = [|""|]Goo""; }"; - - await TestAsync(code, expected); - } + public Task TestString3() + => TestAsync(@"public class C { string s = ""Goo$$""; }", @"public class C { string s = [|""|]Goo""; }"); [Fact] - public async Task TestString4() - { - var code = @"public class C { string s = ""Goo""$$; }"; - var expected = @"public class C { string s = [|""|]Goo""; }"; - - await TestAsync(code, expected); - } + public Task TestString4() + => TestAsync(@"public class C { string s = ""Goo""$$; }", @"public class C { string s = [|""|]Goo""; }"); [Fact] - public async Task TestString5() - { - var code = @"public class C { string s = ""Goo$$ "; - var expected = @"public class C { string s = ""Goo "; - - await TestAsync(code, expected); - } + public Task TestString5() + => TestAsync(@"public class C { string s = ""Goo$$ ", @"public class C { string s = ""Goo "); [Fact] - public async Task TestVerbatimString1() - { - var code = @"public class C { string s = $$@""Goo""; }"; - var expected = @"public class C { string s = @""Goo[|""|]; }"; - - await TestAsync(code, expected); - } + public Task TestVerbatimString1() + => TestAsync(@"public class C { string s = $$@""Goo""; }", @"public class C { string s = @""Goo[|""|]; }"); [Fact] - public async Task TestVerbatimString2() - { - var code = @"public class C { string s = @$$""Goo""; }"; - var expected = @"public class C { string s = @""Goo[|""|]; }"; - - await TestAsync(code, expected); - } + public Task TestVerbatimString2() + => TestAsync(@"public class C { string s = @$$""Goo""; }", @"public class C { string s = @""Goo[|""|]; }"); [Fact] - public async Task TestVerbatimString3() - { - var code = @"public class C { string s = @""$$Goo""; }"; - var expected = @"public class C { string s = @""Goo[|""|]; }"; - - await TestAsync(code, expected); - } + public Task TestVerbatimString3() + => TestAsync(@"public class C { string s = @""$$Goo""; }", @"public class C { string s = @""Goo[|""|]; }"); [Fact] - public async Task TestVerbatimString4() - { - var code = @"public class C { string s = @""Goo$$""; }"; - var expected = @"public class C { string s = [|@""|]Goo""; }"; - - await TestAsync(code, expected); - } + public Task TestVerbatimString4() + => TestAsync(@"public class C { string s = @""Goo$$""; }", @"public class C { string s = [|@""|]Goo""; }"); [Fact] - public async Task TestVerbatimString5() - { - var code = @"public class C { string s = @""Goo""$$; }"; - var expected = @"public class C { string s = [|@""|]Goo""; }"; - - await TestAsync(code, expected); - } + public Task TestVerbatimString5() + => TestAsync(@"public class C { string s = @""Goo""$$; }", @"public class C { string s = [|@""|]Goo""; }"); [Fact] - public async Task TestInterpolatedString1() - { - var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""$${x}, {y}""; }"; - var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x[|}|], {y}""; }"; - - await TestAsync(code, expected); - } + public Task TestInterpolatedString1() + => TestAsync(@"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""$${x}, {y}""; }", @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x[|}|], {y}""; }"); [Fact] - public async Task TestInterpolatedString2() - { - var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{$$x}, {y}""; }"; - var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x[|}|], {y}""; }"; - - await TestAsync(code, expected); - } + public Task TestInterpolatedString2() + => TestAsync(@"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{$$x}, {y}""; }", @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x[|}|], {y}""; }"); [Fact] - public async Task TestInterpolatedString3() - { - var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x$$}, {y}""; }"; - var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""[|{|]x}, {y}""; }"; - - await TestAsync(code, expected); - } + public Task TestInterpolatedString3() + => TestAsync(@"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x$$}, {y}""; }", @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""[|{|]x}, {y}""; }"); [Fact] - public async Task TestInterpolatedString4() - { - var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}$$, {y}""; }"; - var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""[|{|]x}, {y}""; }"; - - await TestAsync(code, expected); - } + public Task TestInterpolatedString4() + => TestAsync(@"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}$$, {y}""; }", @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""[|{|]x}, {y}""; }"); [Fact] - public async Task TestInterpolatedString5() - { - var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, $${y}""; }"; - var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y[|}|]""; }"; - - await TestAsync(code, expected); - } + public Task TestInterpolatedString5() + => TestAsync(@"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, $${y}""; }", @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y[|}|]""; }"); [Fact] - public async Task TestInterpolatedString6() - { - var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {$$y}""; }"; - var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y[|}|]""; }"; - - await TestAsync(code, expected); - } + public Task TestInterpolatedString6() + => TestAsync(@"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {$$y}""; }", @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y[|}|]""; }"); [Fact] - public async Task TestInterpolatedString7() - { - var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y$$}""; }"; - var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, [|{|]y}""; }"; - - await TestAsync(code, expected); - } + public Task TestInterpolatedString7() + => TestAsync(@"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y$$}""; }", @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, [|{|]y}""; }"); [Fact] - public async Task TestInterpolatedString8() - { - var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y}$$""; }"; - var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, [|{|]y}""; }"; - - await TestAsync(code, expected); - } + public Task TestInterpolatedString8() + => TestAsync(@"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y}$$""; }", @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, [|{|]y}""; }"); [Fact] - public async Task TestInterpolatedString9() - { - var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $$[||]$""{x}, {y}""; }"; - var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y}[|""|]; }"; - - await TestAsync(code, expected); - } + public Task TestInterpolatedString9() + => TestAsync(@"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $$[||]$""{x}, {y}""; }", @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y}[|""|]; }"); [Fact] - public async Task TestInterpolatedString10() - { - var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $[||]$$""{x}, {y}""; }"; - var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y}[|""|]; }"; - - await TestAsync(code, expected); - } + public Task TestInterpolatedString10() + => TestAsync(@"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $[||]$$""{x}, {y}""; }", @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y}[|""|]; }"); [Fact] - public async Task TestInterpolatedString11() - { - var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $$[||]$@""{x}, {y}""; }"; - var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@""{x}, {y}[|""|]; }"; - - await TestAsync(code, expected); - } + public Task TestInterpolatedString11() + => TestAsync(@"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $$[||]$@""{x}, {y}""; }", @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@""{x}, {y}[|""|]; }"); [Fact] - public async Task TestInterpolatedString12() - { - var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $[||]$$@""{x}, {y}""; }"; - var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@""{x}, {y}[|""|]; }"; - - await TestAsync(code, expected); - } + public Task TestInterpolatedString12() + => TestAsync(@"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $[||]$$@""{x}, {y}""; }", @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@""{x}, {y}[|""|]; }"); [Fact] - public async Task TestInterpolatedString13() - { - var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@$$""{x}, {y}""; }"; - var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@""{x}, {y}[|""|]; }"; - - await TestAsync(code, expected); - } + public Task TestInterpolatedString13() + => TestAsync(@"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@$$""{x}, {y}""; }", @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@""{x}, {y}[|""|]; }"); [Fact] - public async Task TestUtf8String1() - { - var code = @"public class C { string s = $$""Goo""u8; }"; - var expected = @"public class C { string s = ""Goo[|""u8|]; }"; - - await TestAsync(code, expected); - } + public Task TestUtf8String1() + => TestAsync(@"public class C { string s = $$""Goo""u8; }", @"public class C { string s = ""Goo[|""u8|]; }"); [Fact] - public async Task TestUtf8String2() - { - var code = @"public class C { string s = ""$$Goo""u8; }"; - var expected = @"public class C { string s = ""Goo[|""u8|]; }"; - - await TestAsync(code, expected); - } + public Task TestUtf8String2() + => TestAsync(@"public class C { string s = ""$$Goo""u8; }", @"public class C { string s = ""Goo[|""u8|]; }"); [Fact] - public async Task TestUtf8String3() - { - var code = @"public class C { string s = ""Goo$$""u8; }"; - var expected = @"public class C { string s = [|""|]Goo""u8; }"; - - await TestAsync(code, expected); - } + public Task TestUtf8String3() + => TestAsync(@"public class C { string s = ""Goo$$""u8; }", @"public class C { string s = [|""|]Goo""u8; }"); [Fact] - public async Task TestUtf8String4() - { - var code = @"public class C { string s = ""Goo""$$u8; }"; - var expected = @"public class C { string s = [|""|]Goo""u8; }"; - - await TestAsync(code, expected); - } + public Task TestUtf8String4() + => TestAsync(@"public class C { string s = ""Goo""$$u8; }", @"public class C { string s = [|""|]Goo""u8; }"); [Fact] - public async Task TestUtf8String5() - { - var code = @"public class C { string s = ""Goo""u$$8; }"; - var expected = @"public class C { string s = [|""|]Goo""u8; }"; - - await TestAsync(code, expected); - } + public Task TestUtf8String5() + => TestAsync(@"public class C { string s = ""Goo""u$$8; }", @"public class C { string s = [|""|]Goo""u8; }"); [Fact] - public async Task TestUtf8String6() - { - var code = @"public class C { string s = ""Goo""u8$$; }"; - var expected = @"public class C { string s = [|""|]Goo""u8; }"; - - await TestAsync(code, expected); - } + public Task TestUtf8String6() + => TestAsync(@"public class C { string s = ""Goo""u8$$; }", @"public class C { string s = [|""|]Goo""u8; }"); [Fact] - public async Task TestVerbatimUtf8String1() - { - var code = @"public class C { string s = $$@""Goo""u8; }"; - var expected = @"public class C { string s = @""Goo[|""u8|]; }"; - - await TestAsync(code, expected); - } + public Task TestVerbatimUtf8String1() + => TestAsync(@"public class C { string s = $$@""Goo""u8; }", @"public class C { string s = @""Goo[|""u8|]; }"); [Fact] - public async Task TestVerbatimUtf8String2() - { - var code = @"public class C { string s = @$$""Goo""u8; }"; - var expected = @"public class C { string s = @""Goo[|""u8|]; }"; - - await TestAsync(code, expected); - } + public Task TestVerbatimUtf8String2() + => TestAsync(@"public class C { string s = @$$""Goo""u8; }", @"public class C { string s = @""Goo[|""u8|]; }"); [Fact] - public async Task TestVerbatimUtf8String3() - { - var code = @"public class C { string s = @""$$Goo""u8; }"; - var expected = @"public class C { string s = @""Goo[|""u8|]; }"; - - await TestAsync(code, expected); - } + public Task TestVerbatimUtf8String3() + => TestAsync(@"public class C { string s = @""$$Goo""u8; }", @"public class C { string s = @""Goo[|""u8|]; }"); [Fact] - public async Task TestVerbatimUtf8String4() - { - var code = @"public class C { string s = @""Goo$$""u8; }"; - var expected = @"public class C { string s = [|@""|]Goo""u8; }"; - - await TestAsync(code, expected); - } + public Task TestVerbatimUtf8String4() + => TestAsync(@"public class C { string s = @""Goo$$""u8; }", @"public class C { string s = [|@""|]Goo""u8; }"); [Fact] - public async Task TestVerbatimUtf8String5() - { - var code = @"public class C { string s = @""Goo""$$u8; }"; - var expected = @"public class C { string s = [|@""|]Goo""u8; }"; - - await TestAsync(code, expected); - } + public Task TestVerbatimUtf8String5() + => TestAsync(@"public class C { string s = @""Goo""$$u8; }", @"public class C { string s = [|@""|]Goo""u8; }"); [Fact] - public async Task TestVerbatimUtf8String6() - { - var code = @"public class C { string s = @""Goo""u$$8; }"; - var expected = @"public class C { string s = [|@""|]Goo""u8; }"; - - await TestAsync(code, expected); - } + public Task TestVerbatimUtf8String6() + => TestAsync(@"public class C { string s = @""Goo""u$$8; }", @"public class C { string s = [|@""|]Goo""u8; }"); [Fact] - public async Task TestVerbatimUtf8String7() - { - var code = @"public class C { string s = @""Goo""u8$$; }"; - var expected = @"public class C { string s = [|@""|]Goo""u8; }"; - - await TestAsync(code, expected); - } + public Task TestVerbatimUtf8String7() + => TestAsync(@"public class C { string s = @""Goo""u8$$; }", @"public class C { string s = [|@""|]Goo""u8; }"); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/7120")] - public async Task TestConditionalDirectiveWithSingleMatchingDirective() - { - var code = """ + public Task TestConditionalDirectiveWithSingleMatchingDirective() + => TestAsync(""" public class C { #if$$ CHK #endif } - """; - var expected = """ + """, """ public class C { #if$$ CHK [|#endif|] } - """; - - await TestAsync(code, expected); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/7120")] - public async Task TestConditionalDirectiveWithTwoMatchingDirectives() - { - var code = """ + public Task TestConditionalDirectiveWithTwoMatchingDirectives() + => TestAsync(""" public class C { #if$$ CHK #else #endif } - """; - var expected = """ + """, """ public class C { #if$$ CHK [|#else|] #endif } - """; - - await TestAsync(code, expected); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/7120")] - public async Task TestConditionalDirectiveWithAllMatchingDirectives() - { - var code = """ + public Task TestConditionalDirectiveWithAllMatchingDirectives() + => TestAsync(""" public class C { #if CHK @@ -675,8 +329,7 @@ public class C #else #endif$$ } - """; - var expected = """ + """, """ public class C { [|#if|] CHK @@ -684,36 +337,27 @@ public class C #else #endif } - """; - - await TestAsync(code, expected); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/7120")] - public async Task TestRegionDirective() - { - var code = """ + public Task TestRegionDirective() + => TestAsync(""" public class C { $$#region test #endregion } - """; - var expected = """ + """, """ public class C { #region test [|#endregion|] } - """; - - await TestAsync(code, expected); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/7120")] - public async Task TestInterleavedDirectivesInner() - { - var code = """ + public Task TestInterleavedDirectivesInner() + => TestAsync(""" #define CHK public class C { @@ -728,8 +372,7 @@ void Test() #endif } } - """; - var expected = """ + """, """ #define CHK public class C { @@ -744,15 +387,11 @@ void Test() #endif } } - """; - - await TestAsync(code, expected); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/7120")] - public async Task TestInterleavedDirectivesOuter() - { - var code = """ + public Task TestInterleavedDirectivesOuter() + => TestAsync(""" #define CHK public class C { @@ -767,8 +406,7 @@ void Test() #endif } } - """; - var expected = """ + """, """ #define CHK public class C { @@ -783,53 +421,39 @@ void Test() #endif } } - """; - - await TestAsync(code, expected); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/7120")] - public async Task TestUnmatchedDirective1() - { - var code = """ + public Task TestUnmatchedDirective1() + => TestAsync(""" public class C { $$#region test } - """; - var expected = """ + """, """ public class C { #region test } - """; - - await TestAsync(code, expected); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/7120")] - public async Task TestUnmatchedDirective2() - { - var code = """ + public Task TestUnmatchedDirective2() + => TestAsync(""" #d$$efine CHK public class C { } - """; - var expected = """ + """, """ #define CHK public class C { } - """; - - await TestAsync(code, expected); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/7534")] - public async Task TestUnmatchedConditionalDirective() - { - var code = """ + public Task TestUnmatchedConditionalDirective() + => TestAsync(""" class Program { static void Main(string[] args) @@ -837,8 +461,7 @@ static void Main(string[] args) } } - """; - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -846,15 +469,11 @@ static void Main(string[] args) } } - """; - - await TestAsync(code, expected); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/7534")] - public async Task TestUnmatchedConditionalDirective2() - { - var code = """ + public Task TestUnmatchedConditionalDirective2() + => TestAsync(""" class Program { static void Main(string[] args) @@ -862,8 +481,7 @@ static void Main(string[] args) } } - """; - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -871,89 +489,41 @@ static void Main(string[] args) } } - """; - - await TestAsync(code, expected); - } + """); [Fact] - public async Task StartTupleDeclaration() - { - var code = @"public class C { $$(int, int, int, int, int, int, int, int) x; }"; - var expected = @"public class C { (int, int, int, int, int, int, int, int[|)|] x; }"; - - await TestAsync(code, expected, TestOptions.Regular); - } + public Task StartTupleDeclaration() + => TestAsync(@"public class C { $$(int, int, int, int, int, int, int, int) x; }", @"public class C { (int, int, int, int, int, int, int, int[|)|] x; }", TestOptions.Regular); [Fact] - public async Task EndTupleDeclaration() - { - var code = @"public class C { (int, int, int, int, int, int, int, int)$$ x; }"; - var expected = @"public class C { [|(|]int, int, int, int, int, int, int, int) x; }"; - - await TestAsync(code, expected, TestOptions.Regular); - } + public Task EndTupleDeclaration() + => TestAsync(@"public class C { (int, int, int, int, int, int, int, int)$$ x; }", @"public class C { [|(|]int, int, int, int, int, int, int, int) x; }", TestOptions.Regular); [Fact] - public async Task StartTupleLiteral() - { - var code = @"public class C { var x = $$(1, 2, 3, 4, 5, 6, 7, 8); }"; - var expected = @"public class C { var x = (1, 2, 3, 4, 5, 6, 7, 8[|)|]; }"; - - await TestAsync(code, expected, TestOptions.Regular); - } + public Task StartTupleLiteral() + => TestAsync(@"public class C { var x = $$(1, 2, 3, 4, 5, 6, 7, 8); }", @"public class C { var x = (1, 2, 3, 4, 5, 6, 7, 8[|)|]; }", TestOptions.Regular); [Fact] - public async Task EndTupleLiteral() - { - var code = @"public class C { var x = (1, 2, 3, 4, 5, 6, 7, 8)$$; }"; - var expected = @"public class C { var x = [|(|]1, 2, 3, 4, 5, 6, 7, 8); }"; - - await TestAsync(code, expected, TestOptions.Regular); - } + public Task EndTupleLiteral() + => TestAsync(@"public class C { var x = (1, 2, 3, 4, 5, 6, 7, 8)$$; }", @"public class C { var x = [|(|]1, 2, 3, 4, 5, 6, 7, 8); }", TestOptions.Regular); [Fact] - public async Task StartNestedTupleLiteral() - { - var code = @"public class C { var x = $$((1, 1, 1), 2, 3, 4, 5, 6, 7, 8); }"; - var expected = @"public class C { var x = ((1, 1, 1), 2, 3, 4, 5, 6, 7, 8[|)|]; }"; - - await TestAsync(code, expected, TestOptions.Regular); - } + public Task StartNestedTupleLiteral() + => TestAsync(@"public class C { var x = $$((1, 1, 1), 2, 3, 4, 5, 6, 7, 8); }", @"public class C { var x = ((1, 1, 1), 2, 3, 4, 5, 6, 7, 8[|)|]; }", TestOptions.Regular); [Fact] - public async Task StartInnerNestedTupleLiteral() - { - var code = @"public class C { var x = ($$(1, 1, 1), 2, 3, 4, 5, 6, 7, 8); }"; - var expected = @"public class C { var x = ((1, 1, 1[|)|], 2, 3, 4, 5, 6, 7, 8); }"; - - await TestAsync(code, expected, TestOptions.Regular); - } + public Task StartInnerNestedTupleLiteral() + => TestAsync(@"public class C { var x = ($$(1, 1, 1), 2, 3, 4, 5, 6, 7, 8); }", @"public class C { var x = ((1, 1, 1[|)|], 2, 3, 4, 5, 6, 7, 8); }", TestOptions.Regular); [Fact] - public async Task EndNestedTupleLiteral() - { - var code = @"public class C { var x = (1, 2, 3, 4, 5, 6, 7, (8, 8, 8))$$; }"; - var expected = @"public class C { var x = [|(|]1, 2, 3, 4, 5, 6, 7, (8, 8, 8)); }"; - - await TestAsync(code, expected, TestOptions.Regular); - } + public Task EndNestedTupleLiteral() + => TestAsync(@"public class C { var x = (1, 2, 3, 4, 5, 6, 7, (8, 8, 8))$$; }", @"public class C { var x = [|(|]1, 2, 3, 4, 5, 6, 7, (8, 8, 8)); }", TestOptions.Regular); [Fact] - public async Task EndInnerNestedTupleLiteral() - { - var code = @"public class C { var x = ((1, 1, 1)$$, 2, 3, 4, 5, 6, 7, 8); }"; - var expected = @"public class C { var x = ([|(|]1, 1, 1), 2, 3, 4, 5, 6, 7, 8); }"; - - await TestAsync(code, expected, TestOptions.Regular); - } + public Task EndInnerNestedTupleLiteral() + => TestAsync(@"public class C { var x = ((1, 1, 1)$$, 2, 3, 4, 5, 6, 7, 8); }", @"public class C { var x = ([|(|]1, 1, 1), 2, 3, 4, 5, 6, 7, 8); }", TestOptions.Regular); [Fact] - public async Task TestFunctionPointer() - { - var code = @"public unsafe class C { delegate*<$$int, int> functionPointer; }"; - var expected = @"public unsafe class C { delegate*|] functionPointer; }"; - - await TestAsync(code, expected, TestOptions.Regular); - } + public Task TestFunctionPointer() + => TestAsync(@"public unsafe class C { delegate*<$$int, int> functionPointer; }", @"public unsafe class C { delegate*|] functionPointer; }", TestOptions.Regular); } diff --git a/src/EditorFeatures/CSharpTest/BracePairs/CSharpBracePairsTests.cs b/src/EditorFeatures/CSharpTest/BracePairs/CSharpBracePairsTests.cs index dc1b23d66440c..5242bf4948908 100644 --- a/src/EditorFeatures/CSharpTest/BracePairs/CSharpBracePairsTests.cs +++ b/src/EditorFeatures/CSharpTest/BracePairs/CSharpBracePairsTests.cs @@ -15,9 +15,8 @@ protected override EditorTestWorkspace CreateWorkspace(string input) => EditorTestWorkspace.CreateCSharp(input); [Fact] - public async Task Test1() - { - await Test(""" + public Task Test1() + => Test(""" public class C {|a:{|} void M{|b:(|}int i{|b:)|} @@ -30,5 +29,4 @@ public class C {|g:}|} {|a:}|} """); - } } diff --git a/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.AddImports.cs b/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.AddImports.cs index 2d39e680b0243..13997758101ab 100644 --- a/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.AddImports.cs +++ b/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.AddImports.cs @@ -19,13 +19,6 @@ public sealed partial class ChangeSignatureTests : AbstractChangeSignatureTests [Fact] public async Task AddParameterAddsAllImports() { - var markup = """ - class C - { - void $$M() { } - } - """; - var updatedSignature = new[] { new AddedParameterOrExistingIndex( new AddedParameter( @@ -34,8 +27,12 @@ class C "test", CallSiteKind.Todo), "System.Collections.Generic.Dictionary>")}; - - var updatedCode = """ + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ + class C + { + void $$M() { } + } + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ using System; using System.Collections.Generic; using System.ComponentModel; @@ -45,23 +42,12 @@ class C { void M(Dictionary> test) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddParameterAddsOnlyMissingImports() { - var markup = """ - using System.ComponentModel; - - class C - { - void $$M() { } - } - """; - var updatedSignature = new[] { new AddedParameterOrExistingIndex( new AddedParameter( @@ -70,8 +56,14 @@ class C "test", CallSiteKind.Todo), "System.Collections.Generic.Dictionary>")}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ + using System.ComponentModel; - var updatedCode = """ + class C + { + void $$M() { } + } + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ using System; using System.Collections.Generic; using System.ComponentModel; @@ -81,15 +73,21 @@ class C { void M(Dictionary> test) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddParameterAddsImportsOnCascading() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex( + new AddedParameter( + null, + "Dictionary>", + "test", + CallSiteKind.Todo), + "System.Collections.Generic.Dictionary>")}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using NS1; namespace NS1 @@ -112,18 +110,7 @@ class D : B public override void $$M() { } } } - """; - - var updatedSignature = new[] { - new AddedParameterOrExistingIndex( - new AddedParameter( - null, - "Dictionary>", - "test", - CallSiteKind.Todo), - "System.Collections.Generic.Dictionary>")}; - - var updatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ using System; using System.Collections.Generic; using System.ComponentModel; @@ -150,8 +137,6 @@ class D : B public override void M(Dictionary> test) { } } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } } diff --git a/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.Cascading.cs b/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.Cascading.cs index 16bfd0b29060a..78539608fd9ff 100644 --- a/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.Cascading.cs +++ b/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.Cascading.cs @@ -19,7 +19,12 @@ public sealed partial class ChangeSignatureTests : AbstractChangeSignatureTests [Fact] public async Task AddParameter_Cascade_ToImplementedMethod() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(0) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ interface I { void M(int x, string y); @@ -30,13 +35,7 @@ class C : I $$public void M(int x, string y) { } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(0) - }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ interface I { void M(string y, int newIntegerParameter, int x); @@ -47,15 +46,18 @@ class C : I public void M(string y, int newIntegerParameter, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddParameter_Cascade_ToImplementedMethod_WithTuples() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(0) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ interface I { void M((int, int) x, (string a, string b) y); @@ -66,13 +68,7 @@ class C : I $$public void M((int, int) x, (string a, string b) y) { } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(0) - }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ interface I { void M((string a, string b) y, int newIntegerParameter, (int, int) x); @@ -83,15 +79,18 @@ class C : I public void M((string a, string b) y, int newIntegerParameter, (int, int) x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddParameter_Cascade_ToImplementingMethod() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(0) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ interface I { $$void M(int x, string y); @@ -102,13 +101,7 @@ class C : I public void M(int x, string y) { } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(0) - }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ interface I { void M(string y, int newIntegerParameter, int x); @@ -119,15 +112,18 @@ class C : I public void M(string y, int newIntegerParameter, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddParameter_Cascade_ToOverriddenMethod() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(0) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class B { public virtual void M(int x, string y) @@ -139,13 +135,7 @@ class D : B $$public override void M(int x, string y) { } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(0) - }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ class B { public virtual void M(string y, int newIntegerParameter, int x) @@ -157,15 +147,18 @@ class D : B public override void M(string y, int newIntegerParameter, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddParameter_Cascade_ToOverridingMethod() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(0) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class B { $$public virtual void M(int x, string y) @@ -177,13 +170,7 @@ class D : B public override void M(int x, string y) { } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(0) - }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ class B { public virtual void M(string y, int newIntegerParameter, int x) @@ -195,15 +182,18 @@ class D : B public override void M(string y, int newIntegerParameter, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddParameter_Cascade_ToOverriddenMethod_Transitive() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(0) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class B { public virtual void M(int x, string y) @@ -221,13 +211,7 @@ class D2 : D $$public override void M(int x, string y) { } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(0) - }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ class B { public virtual void M(string y, int newIntegerParameter, int x) @@ -245,15 +229,18 @@ class D2 : D public override void M(string y, int newIntegerParameter, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddParameter_Cascade_ToOverridingMethod_Transitive() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(0) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class B { $$public virtual void M(int x, string y) @@ -271,13 +258,7 @@ class D2 : D public override void M(int x, string y) { } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(0) - }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ class B { public virtual void M(string y, int newIntegerParameter, int x) @@ -295,9 +276,7 @@ class D2 : D public override void M(string y, int newIntegerParameter, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] @@ -309,7 +288,12 @@ public async Task AddParameter_Cascade_ToMethods_Complex() //// / \ \ //// $$D2 D3 C - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(0) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class B { public virtual void M(int x, string y) { } } class D : B, I { public override void M(int x, string y) { } } class D2 : D { public override void $$M(int x, string y) { } } @@ -318,14 +302,7 @@ interface I { void M(int x, string y); } interface I2 { void M(int x, string y); } interface I3 : I, I2 { } class C : I3 { public void M(int x, string y) { } } - """; - - var permutation = new[] { - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(0) - }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ class B { public virtual void M(string y, int newIntegerParameter, int x) { } } class D : B, I { public override void M(string y, int newIntegerParameter, int x) { } } class D2 : D { public override void M(string y, int newIntegerParameter, int x) { } } @@ -334,15 +311,18 @@ interface I { void M(string y, int newIntegerParameter, int x); } interface I2 { void M(string y, int newIntegerParameter, int x); } interface I3 : I, I2 { } class C : I3 { public void M(string y, int newIntegerParameter, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddParameter_Cascade_ToMethods_WithDifferentParameterNames() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(0) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class B { /// @@ -380,13 +360,7 @@ public class D2 : D return 1; } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(0) - }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class B { /// @@ -427,53 +401,46 @@ public override int M(string x, int newIntegerParameter, int y) return 1; } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/53091")] public async Task AddParameter_Cascade_Record() { - var markup = """ - record $$BaseR(int A, int B); - - record DerivedR() : BaseR(0, 1); - """; var permutation = new AddedParameterOrExistingIndex[] { new(1), new(new AddedParameter(null, "int", "C", CallSiteKind.Value, "3"), "int"), new(0) }; - var updatedCode = """ + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ + record $$BaseR(int A, int B); + + record DerivedR() : BaseR(0, 1); + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ record BaseR(int B, int C, int A); record DerivedR() : BaseR(1, 3, 0); - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/53091")] public async Task AddParameter_Cascade_PrimaryConstructor() { - var markup = """ - class $$BaseR(int A, int B); - - class DerivedR() : BaseR(0, 1); - """; var permutation = new AddedParameterOrExistingIndex[] { new(1), new(new AddedParameter(null, "int", "C", CallSiteKind.Value, "3"), "int"), new(0) }; - var updatedCode = """ + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ + class $$BaseR(int A, int B); + + class DerivedR() : BaseR(0, 1); + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ class BaseR(int B, int C, int A); class DerivedR() : BaseR(1, 3, 0); - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } } diff --git a/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.Delegates.cs b/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.Delegates.cs index 62a2768d885b3..8467939123b23 100644 --- a/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.Delegates.cs +++ b/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.Delegates.cs @@ -19,7 +19,12 @@ public sealed partial class ChangeSignatureTests : AbstractChangeSignatureTests [Fact] public async Task AddParameter_Delegates_ImplicitInvokeCalls() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(1) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate void MyDelegate($$int x, string y, bool z); class C @@ -30,13 +35,8 @@ void M() d1(1, "Two", true); } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(1) - }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, + expectedUpdatedInvocationDocumentCode: """ delegate void MyDelegate(bool z, int newIntegerParameter, string y); class C @@ -47,15 +47,18 @@ void M() d1(true, 12345, "Two"); } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, - expectedUpdatedInvocationDocumentCode: expectedUpdatedCode, expectedSelectedIndex: 0); + """, expectedSelectedIndex: 0); } [Fact] public async Task AddParameter_Delegates_ExplicitInvokeCalls() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(1) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate void MyDelegate(int x, string $$y, bool z); class C @@ -66,13 +69,8 @@ void M() d1.Invoke(1, "Two", true); } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(1) - }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, + expectedUpdatedInvocationDocumentCode: """ delegate void MyDelegate(bool z, int newIntegerParameter, string y); class C @@ -83,15 +81,18 @@ void M() d1.Invoke(true, 12345, "Two"); } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, - expectedUpdatedInvocationDocumentCode: expectedUpdatedCode, expectedSelectedIndex: 1); + """, expectedSelectedIndex: 1); } [Fact] public async Task AddParameter_Delegates_BeginInvokeCalls() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(1) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate void MyDelegate(int x, string y, bool z$$); class C @@ -102,13 +103,8 @@ void M() d1.BeginInvoke(1, "Two", true, null, null); } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(1) - }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, + expectedUpdatedInvocationDocumentCode: """ delegate void MyDelegate(bool z, int newIntegerParameter, string y); class C @@ -119,15 +115,18 @@ void M() d1.BeginInvoke(true, 12345, "Two", null, null); } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, - expectedUpdatedInvocationDocumentCode: expectedUpdatedCode, expectedSelectedIndex: 2); + """, expectedSelectedIndex: 2); } [Fact] public async Task AddParameter_Delegates_AnonymousMethods() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(1) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate void $$MyDelegate(int x, string y, bool z); class C @@ -139,13 +138,7 @@ void M() d1 = delegate { }; } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(1) - }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ delegate void MyDelegate(bool z, int newIntegerParameter, string y); class C @@ -157,14 +150,18 @@ void M() d1 = delegate { }; } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task AddParameter_Delegates_Lambdas() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(1) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate void $$MyDelegate(int x, string y, bool z); class C @@ -175,13 +172,7 @@ void M() d1 = (r, s, t) => { var x = s.Length + (t ? 0 : 1); }; } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(1) - }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ delegate void MyDelegate(bool z, int newIntegerParameter, string y); class C @@ -192,14 +183,16 @@ void M() d1 = (t, newIntegerParameter, s) => { var x = s.Length + (t ? 0 : 1); }; } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task AddParameter_Delegates_Lambdas_RemovingOnlyParameterIntroducesParentheses() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate void $$MyDelegate(int x); class C @@ -212,11 +205,7 @@ void M() d1 = r => { System.Console.WriteLine("Test"); }; } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ delegate void MyDelegate(int newIntegerParameter); class C @@ -229,14 +218,18 @@ void M() d1 = (int newIntegerParameter) => { System.Console.WriteLine("Test"); }; } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task AddParameter_Delegates_CascadeThroughMethodGroups_AssignedToVariable() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(1) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate void $$MyDelegate(int x, string y, bool z); class C @@ -252,13 +245,7 @@ void M() void Goo(int a, string b, bool c) { } void Goo(int a, object b, bool c) { } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(1) - }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ delegate void MyDelegate(bool z, int newIntegerParameter, string y); class C @@ -274,14 +261,18 @@ void M() void Goo(bool c, int newIntegerParameter, string b) { } void Goo(int a, object b, bool c) { } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task AddParameter_Delegates_CascadeThroughMethodGroups_DelegateConstructor() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(1) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate void $$MyDelegate(int x, string y, bool z); class C @@ -296,13 +287,7 @@ void M() void Goo(int a, string b, bool c) { } void Goo(int a, object b, bool c) { } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(1) - }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ delegate void MyDelegate(bool z, int newIntegerParameter, string y); class C @@ -317,14 +302,18 @@ void M() void Goo(bool c, int newIntegerParameter, string b) { } void Goo(int a, object b, bool c) { } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task AddParameter_Delegates_CascadeThroughMethodGroups_PassedAsArgument() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(1) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate void $$MyDelegate(int x, string y, bool z); class C @@ -341,13 +330,7 @@ void Target(MyDelegate d) { } void Goo(int a, string b, bool c) { } void Goo(int a, object b, bool c) { } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(1) - }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ delegate void MyDelegate(bool z, int newIntegerParameter, string y); class C @@ -364,14 +347,18 @@ void Target(MyDelegate d) { } void Goo(bool c, int newIntegerParameter, string b) { } void Goo(int a, object b, bool c) { } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task AddParameter_Delegates_CascadeThroughMethodGroups_ReturnValue() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(1) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate void $$MyDelegate(int x, string y, bool z); class C @@ -390,13 +377,7 @@ private MyDelegate Result() void Goo(int a, string b, bool c) { } void Goo(int a, object b, bool c) { } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(1) - }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ delegate void MyDelegate(bool z, int newIntegerParameter, string y); class C @@ -415,14 +396,18 @@ private MyDelegate Result() void Goo(bool c, int newIntegerParameter, string b) { } void Goo(int a, object b, bool c) { } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task AddParameter_Delegates_CascadeThroughMethodGroups_YieldReturnValue() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(1) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System.Collections.Generic; delegate void $$MyDelegate(int x, string y, bool z); @@ -442,13 +427,7 @@ private IEnumerable Result() void Goo(int a, string b, bool c) { } void Goo(int a, object b, bool c) { } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(1) - }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ using System.Collections.Generic; delegate void MyDelegate(bool z, int newIntegerParameter, string y); @@ -468,14 +447,18 @@ private IEnumerable Result() void Goo(bool c, int newIntegerParameter, string b) { } void Goo(int a, object b, bool c) { } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task AddParameter_Delegates_ReferencingLambdas_MethodArgument() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(1) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate void $$MyDelegate(int x, string y, bool z); class C @@ -487,13 +470,7 @@ void M6() void Target(MyDelegate d) { } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(1) - }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ delegate void MyDelegate(bool z, int newIntegerParameter, string y); class C @@ -505,14 +482,18 @@ void M6() void Target(MyDelegate d) { } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task AddParameter_Delegates_ReferencingLambdas_YieldReturn() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(1) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System.Collections.Generic; delegate void $$MyDelegate(int x, string y, bool z); @@ -523,13 +504,7 @@ private IEnumerable Result3() yield return (g, h, i) => { var x = h.Length + (i ? 0 : 1); }; } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(1) - }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ using System.Collections.Generic; delegate void MyDelegate(bool z, int newIntegerParameter, string y); @@ -540,14 +515,18 @@ private IEnumerable Result3() yield return (i, newIntegerParameter, h) => { var x = h.Length + (i ? 0 : 1); }; } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task AddParameter_Delegates_Recursive() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(1) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate RecursiveDelegate $$RecursiveDelegate(int x, string y, bool z); class C @@ -558,13 +537,7 @@ void M() rd(1, "Two", true)(1, "Two", true)(1, "Two", true)(1, "Two", true)(1, "Two", true); } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(1) - }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ delegate RecursiveDelegate RecursiveDelegate(bool z, int newIntegerParameter, string y); class C @@ -575,14 +548,18 @@ void M() rd(true, 12345, "Two")(true, 12345, "Two")(true, 12345, "Two")(true, 12345, "Two")(true, 12345, "Two"); } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task AddParameter_Delegates_DocComments() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(1) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ /// /// This is , which has these methods: /// @@ -608,13 +585,7 @@ void M() /// void Goo(int a, string b, bool c) { } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(1) - }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ /// /// This is , which has these methods: /// @@ -640,14 +611,18 @@ void M() /// void Goo(bool c, int newIntegerParameter, string b) { } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task AddParameter_Delegates_CascadeThroughEventAdd() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(1) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate void $$MyDelegate(int x, string y, bool z); class Program @@ -660,13 +635,7 @@ void M() event MyDelegate MyEvent; void Program_MyEvent(int a, string b, bool c) { } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(1) - }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ delegate void MyDelegate(bool z, int newIntegerParameter, string y); class Program @@ -679,14 +648,16 @@ void M() event MyDelegate MyEvent; void Program_MyEvent(bool c, int newIntegerParameter, string b) { } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task AddParameter_Delegates_Generics1() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class DP16a { public delegate void D($$T t); @@ -704,11 +675,7 @@ void B() E2 -= new D(M3); } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ public class DP16a { public delegate void D(int newIntegerParameter); @@ -726,14 +693,16 @@ void B() E2 -= new D(M3); } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task AddParameter_Delegates_Generics2() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class D17 { public delegate void $$D(T t); @@ -743,11 +712,7 @@ public class D17Test void Test() { var x = new D17.D(M17); } internal void M17(string s) { } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ public class D17 { public delegate void D(int newIntegerParameter); @@ -757,14 +722,16 @@ public class D17Test void Test() { var x = new D17.D(M17); } internal void M17(int newIntegerParameter) { } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task AddParameter_Delegates_GenericParams() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class DA { void M(params int[] i) { } @@ -786,11 +753,7 @@ void B() D d = new D(M1); } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class DA { void M(int newIntegerParameter) { } @@ -812,14 +775,16 @@ void B() D d = new D(M1); } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task AddParameter_Delegates_Generic_RemoveArgumentAtReference() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int") + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class CD { public delegate void D(T t); @@ -831,11 +796,8 @@ public void M() var dele = new CD.$$D((int x) => { }); } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int") - }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, + expectedUpdatedInvocationDocumentCode: """ public class CD { public delegate void D(int newIntegerParameter); @@ -847,15 +809,16 @@ public void M() var dele = new CD.D((int newIntegerParameter) => { }); } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, - expectedUpdatedInvocationDocumentCode: expectedUpdatedCode, expectedSelectedIndex: 0); + """, expectedSelectedIndex: 0); } [Fact] public async Task AddParameter_Delegate_Generics_RemoveStaticArgument() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int") + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C2 { public delegate void D(T t); @@ -872,11 +835,7 @@ void B() $$d(D2.Instance); } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int") - }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ public class C2 { public delegate void D(int newIntegerParameter); @@ -893,14 +852,18 @@ void B() d(12345); } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task TestAddParameter_Delegates_Relaxation_ParameterlessFunctionToFunction() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), + new AddedParameterOrExistingIndex(1) + }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class C0 { delegate int $$MyFunc(int x, string y, bool z); @@ -918,13 +881,7 @@ private MyFunc Test() } } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "int"), - new AddedParameterOrExistingIndex(1) - }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class C0 { delegate int MyFunc(bool z, int newIntegerParameter, string y); @@ -942,7 +899,6 @@ private MyFunc Test() } } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } } diff --git a/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.Formatting.cs b/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.Formatting.cs index 7cbe3440a5533..a5c658eb14555 100644 --- a/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.Formatting.cs +++ b/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.Formatting.cs @@ -21,18 +21,6 @@ public sealed partial class ChangeSignatureTests : AbstractChangeSignatureTests [Fact] public async Task AddParameter_Formatting_KeepCountsPerLine() { - var markup = @" -class C -{ - void $$Method(int a, int b, int c, - int d, int e, - int f) - { - Method(1, - 2, 3, - 4, 5, 6); - } -}"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(5), new AddedParameterOrExistingIndex(4), @@ -41,37 +29,36 @@ class C new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0)}; - var expectedUpdatedCode = @" -class C -{ - void Method(int f, int e, int d, - byte bb, int c, - int b, int a) - { - Method(6, - 5, 4, - 34, 3, 2, 1); - } -}"; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ + class C + { + void $$Method(int a, int b, int c, + int d, int e, + int f) + { + Method(1, + 2, 3, + 4, 5, 6); + } + } + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ + class C + { + void Method(int f, int e, int d, + byte bb, int c, + int b, int a) + { + Method(6, + 5, 4, + 34, 3, 2, 1); + } + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28156")] public async Task AddParameter_Formatting_KeepTrivia() { - var markup = @" -class C -{ - void $$Method( - int a, int b, int c, - int d, int e, - int f) - { - Method( - 1, 2, 3, - 4, 5, 6); - } -}"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(2), @@ -79,38 +66,38 @@ class C new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(4), new AddedParameterOrExistingIndex(5)}; - var expectedUpdatedCode = @" -class C -{ - void Method( - int b, int c, int d, - byte bb, int e, - int f) - { - Method( - 2, 3, 4, - 34, 5, 6); - } -}"; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ + class C + { + void $$Method( + int a, int b, int c, + int d, int e, + int f) + { + Method( + 1, 2, 3, + 4, 5, 6); + } + } + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ + class C + { + void Method( + int b, int c, int d, + byte bb, int e, + int f) + { + Method( + 2, 3, 4, + 34, 5, 6); + } + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28156")] public async Task AddParameter_Formatting_KeepTrivia_WithArgumentNames() { - var markup = @" -class C -{ - void $$Method( - int a, int b, int c, - int d, int e, - int f) - { - Method( - a: 1, b: 2, c: 3, - d: 4, e: 5, f: 6); - } -}"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(2), @@ -118,428 +105,439 @@ class C new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(4), new AddedParameterOrExistingIndex(5)}; - var expectedUpdatedCode = @" -class C -{ - void Method( - int b, int c, int d, - byte bb, int e, - int f) - { - Method( - b: 2, c: 3, d: 4, - bb: 34, e: 5, f: 6); - } -}"; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ + class C + { + void $$Method( + int a, int b, int c, + int d, int e, + int f) + { + Method( + a: 1, b: 2, c: 3, + d: 4, e: 5, f: 6); + } + } + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ + class C + { + void Method( + int b, int c, int d, + byte bb, int e, + int f) + { + Method( + b: 2, c: 3, d: 4, + bb: 34, e: 5, f: 6); + } + } + """); } [Fact] public async Task AddParameter_Formatting_Method() { - var markup = @" -class C -{ - void $$Method(int a, - int b) - { - Method(1, - 2); - } -}"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; - var expectedUpdatedCode = @" -class C -{ - void Method(int b, - byte bb, int a) - { - Method(2, - 34, 1); - } -}"; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ + class C + { + void $$Method(int a, + int b) + { + Method(1, + 2); + } + } + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ + class C + { + void Method(int b, + byte bb, int a) + { + Method(2, + 34, 1); + } + } + """); } [Fact] public async Task AddParameter_Formatting_Constructor() { - var markup = @" -class SomeClass -{ - $$SomeClass(int a, - int b) - { - new SomeClass(1, - 2); - } -}"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; - var expectedUpdatedCode = @" -class SomeClass -{ - SomeClass(int b, - byte bb, int a) - { - new SomeClass(2, - 34, 1); - } -}"; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ + class SomeClass + { + $$SomeClass(int a, + int b) + { + new SomeClass(1, + 2); + } + } + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ + class SomeClass + { + SomeClass(int b, + byte bb, int a) + { + new SomeClass(2, + 34, 1); + } + } + """); } [Fact] public async Task AddParameter_Formatting_Indexer() { - var markup = @" -class SomeClass -{ - public int $$this[int a, - int b] - { - get - { - return new SomeClass()[1, - 2]; - } - } -}"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; - var expectedUpdatedCode = @" -class SomeClass -{ - public int this[int b, - byte bb, int a] - { - get - { - return new SomeClass()[2, - 34, 1]; - } - } -}"; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ + class SomeClass + { + public int $$this[int a, + int b] + { + get + { + return new SomeClass()[1, + 2]; + } + } + } + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ + class SomeClass + { + public int this[int b, + byte bb, int a] + { + get + { + return new SomeClass()[2, + 34, 1]; + } + } + } + """); } [Fact] public async Task AddParameter_Formatting_Delegate() { - var markup = @" -class SomeClass -{ - delegate void $$MyDelegate(int a, - int b); - - void M(int a, - int b) - { - var myDel = new MyDelegate(M); - myDel(1, - 2); - } -}"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; - var expectedUpdatedCode = @" -class SomeClass -{ - delegate void MyDelegate(int b, - byte bb, int a); + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ + class SomeClass + { + delegate void $$MyDelegate(int a, + int b); - void M(int b, - byte bb, int a) - { - var myDel = new MyDelegate(M); - myDel(2, - 34, 1); - } -}"; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + void M(int a, + int b) + { + var myDel = new MyDelegate(M); + myDel(1, + 2); + } + } + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ + class SomeClass + { + delegate void MyDelegate(int b, + byte bb, int a); + + void M(int b, + byte bb, int a) + { + var myDel = new MyDelegate(M); + myDel(2, + 34, 1); + } + } + """); } [Fact] public async Task AddParameter_Formatting_AnonymousMethod() { - var markup = @" -class SomeClass -{ - delegate void $$MyDelegate(int a, - int b); - - void M() - { - MyDelegate myDel = delegate (int x, - int y) - { - // Nothing - }; - } -}"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; - var expectedUpdatedCode = @" -class SomeClass -{ - delegate void MyDelegate(int b, - byte bb, int a); + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ + class SomeClass + { + delegate void $$MyDelegate(int a, + int b); - void M() - { - MyDelegate myDel = delegate (int y, - byte bb, int x) - { - // Nothing - }; - } -}"; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + void M() + { + MyDelegate myDel = delegate (int x, + int y) + { + // Nothing + }; + } + } + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ + class SomeClass + { + delegate void MyDelegate(int b, + byte bb, int a); + + void M() + { + MyDelegate myDel = delegate (int y, + byte bb, int x) + { + // Nothing + }; + } + } + """); } [Fact] public async Task AddParameter_Formatting_ConstructorInitializers() { - var markup = @" -class B -{ - public $$B(int x, int y) { } - public B() : this(1, - 2) - { } -} - -class D : B -{ - public D() : base(1, - 2) - { } -}"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; - var expectedUpdatedCode = @" -class B -{ - public B(int y, byte bb, int x) { } - public B() : this(2, - 34, 1) - { } -} + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ + class B + { + public $$B(int x, int y) { } + public B() : this(1, + 2) + { } + } -class D : B -{ - public D() : base(2, - 34, 1) - { } -}"; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + class D : B + { + public D() : base(1, + 2) + { } + } + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ + class B + { + public B(int y, byte bb, int x) { } + public B() : this(2, + 34, 1) + { } + } + + class D : B + { + public D() : base(2, + 34, 1) + { } + } + """); } [Fact] public async Task AddParameter_Formatting_Attribute() { - var markup = @" -[Custom(1, - 2)] -class CustomAttribute : System.Attribute -{ - public $$CustomAttribute(int x, int y) { } -}"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; - var expectedUpdatedCode = @" -[Custom(2, - 34, 1)] -class CustomAttribute : System.Attribute -{ - public CustomAttribute(int y, byte bb, int x) { } -}"; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ + [Custom(1, + 2)] + class CustomAttribute : System.Attribute + { + public $$CustomAttribute(int x, int y) { } + } + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ + [Custom(2, + 34, 1)] + class CustomAttribute : System.Attribute + { + public CustomAttribute(int y, byte bb, int x) { } + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28156")] public async Task AddParameter_Formatting_Attribute_KeepTrivia() { - var markup = @" -[Custom( - 1, 2)] -class CustomAttribute : System.Attribute -{ - public $$CustomAttribute(int x, int y) { } -}"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte") }; - var expectedUpdatedCode = @" -[Custom( - 2, 34)] -class CustomAttribute : System.Attribute -{ - public CustomAttribute(int y, byte bb) { } -}"; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ + [Custom( + 1, 2)] + class CustomAttribute : System.Attribute + { + public $$CustomAttribute(int x, int y) { } + } + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ + [Custom( + 2, 34)] + class CustomAttribute : System.Attribute + { + public CustomAttribute(int y, byte bb) { } + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28156")] public async Task AddParameter_Formatting_Attribute_KeepTrivia_RemovingSecond() { - var markup = @" -[Custom( - 1, 2)] -class CustomAttribute : System.Attribute -{ - public $$CustomAttribute(int x, int y) { } -}"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(0), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte")}; - var expectedUpdatedCode = @" -[Custom( - 1, 34)] -class CustomAttribute : System.Attribute -{ - public CustomAttribute(int x, byte bb) { } -}"; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ + [Custom( + 1, 2)] + class CustomAttribute : System.Attribute + { + public $$CustomAttribute(int x, int y) { } + } + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ + [Custom( + 1, 34)] + class CustomAttribute : System.Attribute + { + public CustomAttribute(int x, byte bb) { } + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28156")] public async Task AddParameter_Formatting_Attribute_KeepTrivia_RemovingBothAddingNew() { - var markup = @" -[Custom( - 1, 2)] -class CustomAttribute : System.Attribute -{ - public $$CustomAttribute(int x, int y) { } -}"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte")}; - var expectedUpdatedCode = @" -[Custom( - 34)] -class CustomAttribute : System.Attribute -{ - public CustomAttribute(byte bb) { } -}"; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ + [Custom( + 1, 2)] + class CustomAttribute : System.Attribute + { + public $$CustomAttribute(int x, int y) { } + } + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ + [Custom( + 34)] + class CustomAttribute : System.Attribute + { + public CustomAttribute(byte bb) { } + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28156")] public async Task AddParameter_Formatting_Attribute_KeepTrivia_RemovingBeforeNewlineComma() { - var markup = @" -[Custom(1 - , 2, 3)] -class CustomAttribute : System.Attribute -{ - public $$CustomAttribute(int x, int y, int z) { } -}"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(2)}; - var expectedUpdatedCode = @" -[Custom(2, 34, 3)] -class CustomAttribute : System.Attribute -{ - public CustomAttribute(int y, byte bb, int z) { } -}"; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ + [Custom(1 + , 2, 3)] + class CustomAttribute : System.Attribute + { + public $$CustomAttribute(int x, int y, int z) { } + } + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ + [Custom(2, 34, 3)] + class CustomAttribute : System.Attribute + { + public CustomAttribute(int y, byte bb, int z) { } + } + """); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/946220")] public async Task AddParameter_Formatting_LambdaAsArgument() { - var markup = @"class C -{ - void M(System.Action f, int z$$) - { - M((x, y) => System.Console.WriteLine(x + y), 5); - } -}"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(0), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte")}; - var expectedUpdatedCode = @"class C -{ - void M(System.Action f, byte bb) - { - M((x, y) => System.Console.WriteLine(x + y), 34); - } -}"; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ + class C + { + void M(System.Action f, int z$$) + { + M((x, y) => System.Console.WriteLine(x + y), 5); + } + } + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ + class C + { + void M(System.Action f, byte bb) + { + M((x, y) => System.Console.WriteLine(x + y), 34); + } + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46595")] public async Task AddParameter_Formatting_PreserveIndentBraces() { - var markup = -@"public class C - { - public void M$$() - { - } - }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "a", CallSiteKind.Value, "12345"), "int")}; - var expectedUpdatedCode = -@"public class C - { - public void M(int a) - { - } - }"; await TestChangeSignatureViaCommandAsync( - LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode, + LanguageNames.CSharp, """ + public class C + { + public void M$$() + { + } + } + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ + public class C + { + public void M(int a) + { + } + } + """, options: Option(CSharpFormattingOptions2.IndentBraces, true)); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46595")] public async Task AddParameter_Formatting_PreserveIndentBraces_Editorconfig() { - var markup = @" - - - -public class C - { - public void M$$() - { - } - } - - [*.cs] -csharp_indent_braces = true - - -"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "a", CallSiteKind.Value, "12345"), "int")}; - var expectedUpdatedCode = @" -public class C - { - public void M(int a) - { - } - } - "; - - await TestChangeSignatureViaCommandAsync("XML", markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + await TestChangeSignatureViaCommandAsync("XML", """ + + + public class C + { + public void M$$() + { + } + } + [*.cs] + csharp_indent_braces = true + + + + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ + public class C + { + public void M(int a) + { + } + } + """); } } diff --git a/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.OptionalParameter.Infer.cs b/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.OptionalParameter.Infer.cs index 691026c15c110..6f8feeb1654cb 100644 --- a/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.OptionalParameter.Infer.cs +++ b/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.OptionalParameter.Infer.cs @@ -19,7 +19,9 @@ public sealed partial class ChangeSignatureTests : AbstractChangeSignatureTests [Fact] public async Task AddOptionalParameter_CallsiteInferred_NoOptions() { - var markup = """ + var updatedSignature = new[] { + AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class C { void M$$() @@ -27,10 +29,7 @@ class C M(); } } - """; - var updatedSignature = new[] { - AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) }; - var updatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class C { void M(int a) @@ -38,15 +37,15 @@ void M(int a) M(TODO); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddOptionalParameter_CallsiteInferred_SingleLocal() { - var markup = """ + var updatedSignature = new[] { + AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class C { void M$$() @@ -55,10 +54,7 @@ class C M(); } } - """; - var updatedSignature = new[] { - AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) }; - var updatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class C { void M(int a) @@ -67,15 +63,15 @@ void M(int a) M(x); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddOptionalParameter_CallsiteInferred_NotOnInaccessibleLocal() { - var markup = """ + var updatedSignature = new[] { + AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class C { void M$$() @@ -84,10 +80,7 @@ class C int x = 7; } } - """; - var updatedSignature = new[] { - AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) }; - var updatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class C { void M(int a) @@ -96,15 +89,15 @@ void M(int a) int x = 7; } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddOptionalParameter_CallsiteInferred_MultipleLocals() { - var markup = """ + var updatedSignature = new[] { + AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class C { void M$$() @@ -114,10 +107,7 @@ class C M(); } } - """; - var updatedSignature = new[] { - AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) }; - var updatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class C { void M(int a) @@ -127,15 +117,16 @@ void M(int a) M(y); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddOptionalParameter_CallsiteInferred_SingleParameter() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(0), + AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class C { void M$$(int x) @@ -143,11 +134,7 @@ class C M(1); } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(0), - AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) }; - var updatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class C { void M(int x, int a) @@ -155,15 +142,15 @@ void M(int x, int a) M(1, x); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddOptionalParameter_CallsiteInferred_SingleField() { - var markup = """ + var updatedSignature = new[] { + AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class C { int x = 8; @@ -173,10 +160,7 @@ class C M(); } } - """; - var updatedSignature = new[] { - AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) }; - var updatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class C { int x = 8; @@ -186,15 +170,15 @@ void M(int a) M(x); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddOptionalParameter_CallsiteInferred_SingleProperty() { - var markup = """ + var updatedSignature = new[] { + AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class C { int X { get; set; } @@ -204,10 +188,7 @@ class C M(); } } - """; - var updatedSignature = new[] { - AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) }; - var updatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class C { int X { get; set; } @@ -217,15 +198,15 @@ void M(int a) M(X); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddOptionalParameter_CallsiteInferred_ImplicitlyConvertable() { - var markup = """ + var updatedSignature = new[] { + AddedParameterOrExistingIndex.CreateAdded("B", "b", CallSiteKind.Inferred) }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class B { } class D : B { } @@ -237,10 +218,7 @@ class C M(); } } - """; - var updatedSignature = new[] { - AddedParameterOrExistingIndex.CreateAdded("B", "b", CallSiteKind.Inferred) }; - var updatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class B { } class D : B { } @@ -252,8 +230,6 @@ void M(B b) M(d); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } } diff --git a/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.OptionalParameter.Omit.cs b/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.OptionalParameter.Omit.cs index 547d2e2311beb..42111cbad2e04 100644 --- a/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.OptionalParameter.Omit.cs +++ b/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.OptionalParameter.Omit.cs @@ -20,7 +20,9 @@ public sealed partial class ChangeSignatureTests : AbstractChangeSignatureTests [WpfFact] public async Task AddOptionalParameter_ToEmptySignature_CallsiteOmitted() { - var markup = """ + var updatedSignature = new[] { + AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1") }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class C { void M$$() @@ -28,10 +30,7 @@ class C M(); } } - """; - var updatedSignature = new[] { - AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1") }; - var updatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class C { void M(int a = 1) @@ -39,15 +38,16 @@ void M(int a = 1) M(); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [WpfFact] public async Task AddOptionalParameter_AfterRequiredParameter_CallsiteOmitted() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(0), + AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1") }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class C { void M$$(int x) @@ -55,11 +55,7 @@ class C M(1); } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(0), - AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1") }; - var updatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class C { void M(int x, int a = 1) @@ -67,15 +63,16 @@ void M(int x, int a = 1) M(1); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [WpfFact] public async Task AddOptionalParameter_BeforeOptionalParameter_CallsiteOmitted() { - var markup = """ + var updatedSignature = new[] { + AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1"), + new AddedParameterOrExistingIndex(0) }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class C { void M$$(int x = 2) @@ -85,11 +82,7 @@ class C M(x: 2); } } - """; - var updatedSignature = new[] { - AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1"), - new AddedParameterOrExistingIndex(0) }; - var updatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class C { void M(int a = 1, int x = 2) @@ -99,15 +92,16 @@ void M(int a = 1, int x = 2) M(x: 2); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [WpfFact] public async Task AddOptionalParameter_BeforeExpandedParamsArray_CallsiteOmitted() { - var markup = """ + var updatedSignature = new[] { + AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1"), + new AddedParameterOrExistingIndex(0) }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class C { void M$$(params int[] p) @@ -118,11 +112,7 @@ class C M(1, 2, 3); } } - """; - var updatedSignature = new[] { - AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1"), - new AddedParameterOrExistingIndex(0) }; - var updatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class C { void M(int a = 1, params int[] p) @@ -133,15 +123,18 @@ void M(int a = 1, params int[] p) M(p: new int[] { 1, 2, 3 }); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [WpfFact] public async Task AddOptionalParameterWithOmittedCallsiteToAttributeConstructor() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(0), + new AddedParameterOrExistingIndex(1), + AddedParameterOrExistingIndex.CreateAdded("int", "x", CallSiteKind.Omitted, isRequired: false, defaultValue: "3"), + new AddedParameterOrExistingIndex(2)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ [Some(1, 2, 4)] class SomeAttribute : System.Attribute { @@ -149,13 +142,7 @@ class SomeAttribute : System.Attribute { } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(0), - new AddedParameterOrExistingIndex(1), - AddedParameterOrExistingIndex.CreateAdded("int", "x", CallSiteKind.Omitted, isRequired: false, defaultValue: "3"), - new AddedParameterOrExistingIndex(2)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ [Some(1, 2, y: 4)] class SomeAttribute : System.Attribute { @@ -163,8 +150,6 @@ public SomeAttribute(int a, int b, int x = 3, int y = 4) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } } diff --git a/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.OptionalParameter.SymbolKinds.cs b/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.OptionalParameter.SymbolKinds.cs index 6ed299ca80b1a..f37338064fb5b 100644 --- a/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.OptionalParameter.SymbolKinds.cs +++ b/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.OptionalParameter.SymbolKinds.cs @@ -20,7 +20,12 @@ public sealed partial class ChangeSignatureTests : AbstractChangeSignatureTests [WpfFact] public async Task AddOptionalParameter_ToConstructor() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(0), + AddedParameterOrExistingIndex.CreateAdded("System.Int32", "x", CallSiteKind.Value, callSiteValue: "100", isRequired: false, defaultValue: "10"), + AddedParameterOrExistingIndex.CreateAdded("System.Int32", "y", CallSiteKind.Omitted, isRequired: false, defaultValue: "11"), + AddedParameterOrExistingIndex.CreateAdded("System.Int32", "z", CallSiteKind.Value, callSiteValue: "102", isRequired: false, defaultValue: "12")}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class B { public B() : this(1) { } @@ -34,13 +39,7 @@ class D : B { public D() : base(1) { } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(0), - AddedParameterOrExistingIndex.CreateAdded("System.Int32", "x", CallSiteKind.Value, callSiteValue: "100", isRequired: false, defaultValue: "10"), - AddedParameterOrExistingIndex.CreateAdded("System.Int32", "y", CallSiteKind.Omitted, isRequired: false, defaultValue: "11"), - AddedParameterOrExistingIndex.CreateAdded("System.Int32", "z", CallSiteKind.Value, callSiteValue: "102", isRequired: false, defaultValue: "12")}; - var updatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class B { public B() : this(1, 100, z: 102) { } @@ -54,15 +53,18 @@ class D : B { public D() : base(1, 100, z: 102) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/44126")] public async Task AddOptionalParameter_ToConstructor_ImplicitObjectCreation() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(0), + AddedParameterOrExistingIndex.CreateAdded("System.Int32", "x", CallSiteKind.Value, callSiteValue: "100", isRequired: false, defaultValue: "10"), + AddedParameterOrExistingIndex.CreateAdded("System.Int32", "y", CallSiteKind.Omitted, isRequired: false, defaultValue: "11"), + AddedParameterOrExistingIndex.CreateAdded("System.Int32", "z", CallSiteKind.Value, callSiteValue: "102", isRequired: false, defaultValue: "12")}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class B { public B() : this(1) { } @@ -76,13 +78,7 @@ class D : B { public D() : base(1) { } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(0), - AddedParameterOrExistingIndex.CreateAdded("System.Int32", "x", CallSiteKind.Value, callSiteValue: "100", isRequired: false, defaultValue: "10"), - AddedParameterOrExistingIndex.CreateAdded("System.Int32", "y", CallSiteKind.Omitted, isRequired: false, defaultValue: "11"), - AddedParameterOrExistingIndex.CreateAdded("System.Int32", "z", CallSiteKind.Value, callSiteValue: "102", isRequired: false, defaultValue: "12")}; - var updatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class B { public B() : this(1, 100, z: 102) { } @@ -96,15 +92,18 @@ class D : B { public D() : base(1, 100, z: 102) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [WpfFact] public async Task AddOptionalParameter_ToIndexer() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(0), + AddedParameterOrExistingIndex.CreateAdded("System.Int32", "x", CallSiteKind.Value, callSiteValue: "100", isRequired: false, defaultValue: "10"), + AddedParameterOrExistingIndex.CreateAdded("System.Int32", "y", CallSiteKind.Omitted, isRequired: false, defaultValue: "11"), + AddedParameterOrExistingIndex.CreateAdded("System.Int32", "z", CallSiteKind.Value, callSiteValue: "102", isRequired: false, defaultValue: "12")}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class B { public int this$$[int a] { get { return 5; } } @@ -114,13 +113,7 @@ public void M() var d = this[1]; } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(0), - AddedParameterOrExistingIndex.CreateAdded("System.Int32", "x", CallSiteKind.Value, callSiteValue: "100", isRequired: false, defaultValue: "10"), - AddedParameterOrExistingIndex.CreateAdded("System.Int32", "y", CallSiteKind.Omitted, isRequired: false, defaultValue: "11"), - AddedParameterOrExistingIndex.CreateAdded("System.Int32", "z", CallSiteKind.Value, callSiteValue: "102", isRequired: false, defaultValue: "12")}; - var updatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class B { public int this[int a, int x = 10, int y = 11, int z = 12] { get { return 5; } } @@ -130,21 +123,12 @@ public void M() var d = this[1, 100, z: 102]; } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [WpfFact] public async Task AddOptionalParameter_ToAttribute() { - var markup = """ - [My(1)] - class MyAttribute : System.Attribute - { - public MyAttribute($$int a) { } - } - """; var updatedSignature = new[] { new AddedParameterOrExistingIndex(0), AddedParameterOrExistingIndex.CreateAdded("System.Int32", "x", CallSiteKind.Value, callSiteValue: "100", isRequired: false, defaultValue: "10"), @@ -153,14 +137,19 @@ public MyAttribute($$int a) { } // TODO: The = in the attribute is a bug. You cannot specify that the attribute should use : instead in the SyntaxGenerator // https://github.com/dotnet/roslyn/issues/43354 - var updatedCode = """ + + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ + [My(1)] + class MyAttribute : System.Attribute + { + public MyAttribute($$int a) { } + } + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ [My(1, 100, z = 102)] class MyAttribute : System.Attribute { public MyAttribute(int a, int x = 10, int y = 11, int z = 12) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } } diff --git a/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.cs b/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.cs index bbc575b4d35f9..bf74564f31009 100644 --- a/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.cs +++ b/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.cs @@ -20,7 +20,13 @@ public sealed partial class ChangeSignatureTests : AbstractChangeSignatureTests [Fact] public async Task AddParameters() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(0), + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "System.Int32"), + new AddedParameterOrExistingIndex(new AddedParameter(null, "string", "newString", CallSiteKind.Value, ""), "System.String"), + new AddedParameterOrExistingIndex(5)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ static class Ext { /// @@ -61,14 +67,7 @@ static class Ext M(p: new[] { 5 }, y: "four", x: 3, c: true, b: "two", a: 1, o: t); } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(0), - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "System.Int32"), - new AddedParameterOrExistingIndex(new AddedParameter(null, "string", "newString", CallSiteKind.Value, ""), "System.String"), - new AddedParameterOrExistingIndex(5)}; - var updatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ static class Ext { /// @@ -109,15 +108,15 @@ static void M(this object o, string b, int newIntegerParameter, string newString M(y: "four", b: "two", newIntegerParameter: 12345, newString:, o: t); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddParameterToParameterlessMethod() { - var markup = """ + var updatedSignature = new[] { + new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "System.Int32")}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ static class Ext { static void $$M() @@ -125,10 +124,7 @@ static class Ext M(); } } - """; - var updatedSignature = new[] { - new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "System.Int32")}; - var updatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ static class Ext { static void M(int newIntegerParameter) @@ -136,15 +132,17 @@ static void M(int newIntegerParameter) M(12345); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderLocalFunctionParametersAndArguments_OnDeclaration() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(0)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class MyClass { @@ -156,12 +154,7 @@ public void M() } } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(0)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ using System; class MyClass { @@ -173,15 +166,17 @@ void Goo(string y, byte b, int x) } } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderLocalFunctionParametersAndArguments_OnInvocation() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(0)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class MyClass { @@ -193,12 +188,7 @@ void Goo(int x, string y) } } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(0)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ using System; class MyClass { @@ -210,15 +200,17 @@ void Goo(string y, byte b, int x) } } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderMethodParameters() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(0)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class MyClass { @@ -226,12 +218,7 @@ class MyClass { } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(0)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ using System; class MyClass { @@ -239,15 +226,17 @@ public void Goo(string y, byte b, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderMethodParametersAndArguments() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(0)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class MyClass { @@ -256,12 +245,7 @@ class MyClass Goo(3, "hello"); } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(0)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ using System; class MyClass { @@ -270,15 +254,17 @@ public void Goo(string y, byte b, int x) Goo("hello", 34, 3); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderMethodParametersAndArgumentsOfNestedCalls() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(0)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class MyClass { @@ -287,12 +273,7 @@ class MyClass return Goo(Goo(4, "inner"), "outer"); } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(0)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ using System; class MyClass { @@ -301,15 +282,17 @@ public int Goo(string y, byte b, int x) return Goo("outer", 34, Goo("inner", 34, 4)); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderConstructorParametersAndArguments() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(1), + AddedParameterOrExistingIndex.CreateAdded("byte", "b", CallSiteKind.Value, "34"), + new AddedParameterOrExistingIndex(0)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class MyClass2 : MyClass @@ -330,12 +313,7 @@ public MyClass() : this(2, "test") var t = new MyClass(x, y); } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(1), - AddedParameterOrExistingIndex.CreateAdded("byte", "b", CallSiteKind.Value, "34"), - new AddedParameterOrExistingIndex(0)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ using System; class MyClass2 : MyClass @@ -356,15 +334,17 @@ public MyClass(string y, byte b, int x) var t = new MyClass(y, 34, x); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderAttributeConstructorParametersAndArguments() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(0)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ [My("test", 8)] class MyClass { @@ -376,12 +356,7 @@ public MyAttribute(string x, int y)$$ { } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(0)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ [My(8, 34, "test")] class MyClass { @@ -393,15 +368,24 @@ public MyAttribute(int y, byte b, string x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderExtensionMethodParametersAndArguments_StaticCall() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(0), + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(5), + new AddedParameterOrExistingIndex(4), + new AddedParameterOrExistingIndex(3)}; + + // Although the `ParameterConfig` has 0 for the `SelectedIndex`, the UI dialog will make an adjustment + // and select parameter `y` instead because the `this` parameter cannot be moved or removed. + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { static void Main(string[] args) @@ -415,17 +399,8 @@ public static class CExt public static void M(this $$C goo, int x, int y, string a = "test_a", string b = "test_b", string c = "test_c") { } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(0), - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(5), - new AddedParameterOrExistingIndex(4), - new AddedParameterOrExistingIndex(3)}; - - var updatedCode = """ + """, updatedSignature: permutation, + expectedUpdatedInvocationDocumentCode: """ public class C { static void Main(string[] args) @@ -439,18 +414,21 @@ public static class CExt public static void M(this C goo, int y, int x, byte b, string c = "test_c", string b = "test_b", string a = "test_a") { } } - """; - - // Although the `ParameterConfig` has 0 for the `SelectedIndex`, the UI dialog will make an adjustment - // and select parameter `y` instead because the `this` parameter cannot be moved or removed. - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, - expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); + """, expectedSelectedIndex: 0); } [Fact] public async Task AddAndReorderExtensionMethodParametersAndArguments_ExtensionCall() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(0), + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(5), + new AddedParameterOrExistingIndex(4), + new AddedParameterOrExistingIndex(3)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { static void Main(string[] args) @@ -464,16 +442,8 @@ public static class CExt public static void M(this C goo, int x$$, int y, string a = "test_a", string b = "test_b", string c = "test_c") { } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(0), - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(5), - new AddedParameterOrExistingIndex(4), - new AddedParameterOrExistingIndex(3)}; - var updatedCode = """ + """, updatedSignature: permutation, + expectedUpdatedInvocationDocumentCode: """ public class C { static void Main(string[] args) @@ -487,16 +457,18 @@ public static class CExt public static void M(this C goo, int y, int x, byte b, string c = "test_c", string b = "test_b", string a = "test_a") { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, - expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 1); + """, expectedSelectedIndex: 1); } [Fact] public async Task AddParameterWithOmittedArgument_ParamsAsArray() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(0), + new AddedParameterOrExistingIndex(1), + AddedParameterOrExistingIndex.CreateAdded("int", "z", CallSiteKind.Omitted, isRequired: false, defaultValue: "3"), + new AddedParameterOrExistingIndex(2)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { void $$M(int x, int y, params int[] p) @@ -504,13 +476,7 @@ public class C M(x, y, p: p); } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(0), - new AddedParameterOrExistingIndex(1), - AddedParameterOrExistingIndex.CreateAdded("int", "z", CallSiteKind.Omitted, isRequired: false, defaultValue: "3"), - new AddedParameterOrExistingIndex(2)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { void M(int x, int y, int z = 3, params int[] p) @@ -518,15 +484,18 @@ void M(int x, int y, int z = 3, params int[] p) M(x, y, p: p); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderParamsMethodParametersAndArguments_ParamsAsArray() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(0), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(2)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { void $$M(int x, int y, params int[] p) @@ -534,13 +503,7 @@ public class C M(x, y, new[] { 1, 2, 3 }); } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(0), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(2)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { void M(int y, int x, byte b, params int[] p) @@ -548,15 +511,18 @@ void M(int y, int x, byte b, params int[] p) M(y, x, 34, new[] { 1, 2, 3 }); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderParamsMethodParametersAndArguments_ParamsExpanded() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(0), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(2)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { void $$M(int x, int y, params int[] p) @@ -564,14 +530,7 @@ public class C M(x, y, 1, 2, 3); } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(0), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(2)}; - - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { void M(int y, int x, byte b, params int[] p) @@ -579,15 +538,22 @@ void M(int y, int x, byte b, params int[] p) M(y, x, 34, 1, 2, 3); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderExtensionAndParamsMethodParametersAndArguments_VariedCallsites() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(0), + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(5), + new AddedParameterOrExistingIndex(4), + new AddedParameterOrExistingIndex(3), + new AddedParameterOrExistingIndex(6)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { static void Main(string[] args) @@ -604,17 +570,8 @@ public static class CExt public static void $$M(this C goo, int x, int y, string a = "test_a", string b = "test_b", string c = "test_c", params int[] p) { } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(0), - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(5), - new AddedParameterOrExistingIndex(4), - new AddedParameterOrExistingIndex(3), - new AddedParameterOrExistingIndex(6)}; - var updatedCode = """ + """, updatedSignature: permutation, + expectedUpdatedInvocationDocumentCode: """ public class C { static void Main(string[] args) @@ -631,16 +588,17 @@ public static class CExt public static void M(this C goo, int y, int x, byte b, string c = "test_c", string b = "test_b", string a = "test_a", params int[] p) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, - expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); + """, expectedSelectedIndex: 0); } [Fact] public async Task AddAndReorderIndexerParametersAndArguments() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(0)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class Program { void M() @@ -655,12 +613,7 @@ void M() set { } } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(0)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ class Program { void M() @@ -675,15 +628,18 @@ void M() set { } } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderParamTagsInDocComments_SingleLineDocComments_OnIndividualLines() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(0)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { /// @@ -694,13 +650,7 @@ public class C } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(0)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { /// @@ -712,15 +662,18 @@ void Goo(int c, int b, byte bb, int a) } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderParamTagsInDocComments_SingleLineDocComments_OnSameLine() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(0)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { /// a is funb is func is fun @@ -729,13 +682,7 @@ public class C } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(0)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { /// c is funb is fun @@ -745,15 +692,21 @@ void Goo(int c, int b, byte bb, int a) } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderParamTagsInDocComments_SingleLineDocComments_MixedLineDistribution() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(5), + new AddedParameterOrExistingIndex(4), + new AddedParameterOrExistingIndex(3), + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(0)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { /// @@ -767,16 +720,7 @@ public class C } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(5), - new AddedParameterOrExistingIndex(4), - new AddedParameterOrExistingIndex(3), - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(0)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { /// Comments spread @@ -791,15 +735,20 @@ void Goo(int f, int e, int d, int c, byte bb, int b, int a) } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderParamTagsInDocComments_SingleLineDocComments_MixedWithRegularComments() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(4), + new AddedParameterOrExistingIndex(3), + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(0)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { /// @@ -810,15 +759,7 @@ public class C } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(4), - new AddedParameterOrExistingIndex(3), - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(0)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { /// @@ -830,15 +771,18 @@ void Goo(int e, int d, int c, byte b, int b, int a) } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderParamTagsInDocComments_MultiLineDocComments_OnSeparateLines1() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(0)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class Program { /** @@ -850,13 +794,7 @@ class Program { } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(0)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ class Program { /** @@ -869,15 +807,18 @@ static void M(int z, byte b, int y, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderParamTagsInDocComments_MultiLineDocComments_OnSingleLine() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(0)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class Program { /** x!y!z! */ @@ -885,13 +826,7 @@ class Program { } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(0)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ class Program { /** z!y! */ @@ -900,15 +835,18 @@ static void M(int z, byte b, int y, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderParamTagsInDocComments_IncorrectOrder_MaintainsOrder() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(0)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { /// @@ -919,13 +857,7 @@ public class C } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(0)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { /// @@ -936,14 +868,18 @@ void Goo(int c, byte bb, int b, int a) } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderParamTagsInDocComments_WrongNames_MaintainsOrder() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(0)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { /// @@ -954,13 +890,7 @@ public class C } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(0)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { /// @@ -971,14 +901,18 @@ void Goo(int c, byte b, int b, int a) } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderParamTagsInDocComments_InsufficientTags_MaintainsOrder() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(0)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { /// @@ -988,13 +922,7 @@ public class C } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(0)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { /// @@ -1004,14 +932,18 @@ void Goo(int c, byte b, int b, int a) } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderParamTagsInDocComments_ExcessiveTags_MaintainsOrder() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(0)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { /// @@ -1023,13 +955,7 @@ public class C } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(0)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { /// @@ -1041,14 +967,18 @@ void Goo(int c, byte bb, int b, int a) } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderParamTagsInDocComments_OnConstructors() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(0)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { /// @@ -1059,13 +989,7 @@ public class C } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(0)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { /// @@ -1077,14 +1001,18 @@ public C(int c, byte bb, int b, int a) } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderParamTagsInDocComments_OnIndexers() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(2), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(0)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { /// @@ -1096,13 +1024,7 @@ public class C set { } } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(2), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(0)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { /// @@ -1115,14 +1037,17 @@ public class C set { } } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderParametersInCrefs() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(0)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class C { /// @@ -1131,12 +1056,7 @@ class C $$void M(int x, string y) { } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(0)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ class C { /// @@ -1145,15 +1065,17 @@ class C void M(string y, byte b, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderParametersInMethodThatImplementsInterfaceMethodOnlyThroughADerivedType1() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(0)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ interface I { $$void M(int x, string y); @@ -1169,12 +1091,7 @@ public void M(int x, string y) class D : C, I { } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(0)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ interface I { void M(string y, byte b, int x); @@ -1190,15 +1107,17 @@ public void M(string y, byte b, int x) class D : C, I { } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddAndReorderParametersInMethodThatImplementsInterfaceMethodOnlyThroughADerivedType2() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), + new AddedParameterOrExistingIndex(0)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ interface I { void M(int x, string y); @@ -1214,12 +1133,7 @@ class C class D : C, I { } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), - new AddedParameterOrExistingIndex(0)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ interface I { void M(string y, byte b, int x); @@ -1235,15 +1149,16 @@ public void M(string y, byte b, int x) class D : C, I { } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43664")] public async Task AddParameterOnUnparenthesizedLambda() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(0), + AddedParameterOrExistingIndex.CreateAdded("byte", "bb", CallSiteKind.Value, callSiteValue: "34") }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System.Linq; namespace ConsoleApp426 @@ -1261,12 +1176,7 @@ static void M(string[] args) static bool Test() { return true; } } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(0), - AddedParameterOrExistingIndex.CreateAdded("byte", "bb", CallSiteKind.Value, callSiteValue: "34") }; - - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ using System.Linq; namespace ConsoleApp426 @@ -1284,15 +1194,17 @@ static void M(string[] args) static bool Test() { return true; } } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44126")] public async Task AddAndReorderImplicitObjectCreationParameter() { - var markup = """ + var permutation = new[] { + new AddedParameterOrExistingIndex(1), + new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, callSiteValue: "34"), "byte"), + new AddedParameterOrExistingIndex(0)}; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class C { @@ -1305,12 +1217,7 @@ public void M() C _ = new(1, "y"); } } - """; - var permutation = new[] { - new AddedParameterOrExistingIndex(1), - new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, callSiteValue: "34"), "byte"), - new AddedParameterOrExistingIndex(0)}; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ using System; class C { @@ -1323,22 +1230,12 @@ public void M() C _ = new("y", 34, 1); } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44558")] public async Task AddParameters_Record() { - var markup = """ - /// - /// - /// - record $$R(int First, int Second, int Third) - { - static R M() => new R(1, 2, 3); - } - """; var updatedSignature = new AddedParameterOrExistingIndex[] { new(0), @@ -1346,7 +1243,15 @@ record $$R(int First, int Second, int Third) new(1), new(new AddedParameter(null, "int", "Forth", CallSiteKind.Value, "12345"), "System.Int32") }; - var updatedCode = """ + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ + /// + /// + /// + record $$R(int First, int Second, int Third) + { + static R M() => new R(1, 2, 3); + } + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ /// /// /// @@ -1355,23 +1260,12 @@ record R(int First, int Third, int Second, int Forth) { static R M() => new R(1, 3, 2, 12345); } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddParameters_PrimaryConstructor_Class() { - var markup = """ - /// - /// - /// - class $$R(int First, int Second, int Third) - { - static R M() => new R(1, 2, 3); - } - """; var updatedSignature = new AddedParameterOrExistingIndex[] { new(0), @@ -1379,7 +1273,15 @@ class $$R(int First, int Second, int Third) new(1), new(new AddedParameter(null, "int", "Forth", CallSiteKind.Value, "12345"), "System.Int32") }; - var updatedCode = """ + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ + /// + /// + /// + class $$R(int First, int Second, int Third) + { + static R M() => new R(1, 2, 3); + } + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ /// /// /// @@ -1388,23 +1290,12 @@ class R(int First, int Third, int Second, int Forth) { static R M() => new R(1, 3, 2, 12345); } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task AddParameters_PrimaryConstructor_Struct() { - var markup = """ - /// - /// - /// - struct $$R(int First, int Second, int Third) - { - static R M() => new R(1, 2, 3); - } - """; var updatedSignature = new AddedParameterOrExistingIndex[] { new(0), @@ -1412,7 +1303,15 @@ struct $$R(int First, int Second, int Third) new(1), new(new AddedParameter(null, "int", "Forth", CallSiteKind.Value, "12345"), "System.Int32") }; - var updatedCode = """ + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ + /// + /// + /// + struct $$R(int First, int Second, int Third) + { + static R M() => new R(1, 2, 3); + } + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ /// /// /// @@ -1421,8 +1320,6 @@ struct R(int First, int Third, int Second, int Forth) { static R M() => new R(1, 3, 2, 12345); } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } } diff --git a/src/EditorFeatures/CSharpTest/ChangeSignature/ChangeSignatureTests.cs b/src/EditorFeatures/CSharpTest/ChangeSignature/ChangeSignatureTests.cs index b11af1a98632f..64d542b996293 100644 --- a/src/EditorFeatures/CSharpTest/ChangeSignature/ChangeSignatureTests.cs +++ b/src/EditorFeatures/CSharpTest/ChangeSignature/ChangeSignatureTests.cs @@ -16,17 +16,13 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature; public sealed partial class ChangeSignatureTests : AbstractChangeSignatureTests { [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8333")] - public async Task TestNotInExpressionBody() - { - var markup = """ + public Task TestNotInExpressionBody() + => TestChangeSignatureViaCodeActionAsync(""" class Ext { void Goo(int a, int b) => [||]0; } - """; - - await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); - } + """, expectedCodeAction: false); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1905")] public async Task TestAfterSemicolonForInvocationInExpressionStatement_ViaCommand() @@ -45,7 +41,11 @@ static void M1(int x, int y) { } static void M2(int x, int y, int z) { } } """; - var expectedCode = """ + await TestChangeSignatureViaCommandAsync( + LanguageNames.CSharp, + markup: markup, + updatedSignature: [1, 0], + expectedUpdatedInvocationDocumentCode: """ class Program { static void Main(string[] args) @@ -58,13 +58,7 @@ static void M1(int y, int x) { } static void M2(int x, int y, int z) { } } - """; - - await TestChangeSignatureViaCommandAsync( - LanguageNames.CSharp, - markup: markup, - updatedSignature: [1, 0], - expectedUpdatedInvocationDocumentCode: expectedCode); + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75676")] @@ -81,7 +75,11 @@ public class Derived() : Base("Item2", "Item1") { } """; - var expectedCode = """ + await TestChangeSignatureViaCommandAsync( + LanguageNames.CSharp, + markup: markup, + updatedSignature: [1, 0], + expectedUpdatedInvocationDocumentCode: """ public class Base { public Base(string Item1, string Item2) { @@ -91,13 +89,7 @@ public Base(string Item1, string Item2) public class Derived() : Base("Item1", "Item2") { } - """; - - await TestChangeSignatureViaCommandAsync( - LanguageNames.CSharp, - markup: markup, - updatedSignature: [1, 0], - expectedUpdatedInvocationDocumentCode: expectedCode); + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75676")] @@ -115,7 +107,11 @@ public class Derived() : Base("Item2", "Item1", 1, "test", true) { } """; - var expectedCode = """ + await TestChangeSignatureViaCommandAsync( + LanguageNames.CSharp, + markup: markup, + updatedSignature: [1, 0, 2], + expectedUpdatedInvocationDocumentCode: """ public class Base { public Base(string Item1, string Item2, params object[] items) { @@ -126,13 +122,7 @@ public Base(string Item1, string Item2, params object[] items) public class Derived() : Base("Item1", "Item2", 1, "test", true) { } - """; - - await TestChangeSignatureViaCommandAsync( - LanguageNames.CSharp, - markup: markup, - updatedSignature: [1, 0, 2], - expectedUpdatedInvocationDocumentCode: expectedCode); + """); } [Fact] @@ -147,7 +137,11 @@ static void M() } } """; - var expectedCode = """ + await TestChangeSignatureViaCommandAsync( + LanguageNames.CSharp, + markup: markup, + updatedSignature: [1, 0], + expectedUpdatedInvocationDocumentCode: """ class Program { static void M() @@ -155,19 +149,12 @@ static void M() System.Func f = (string _, int _) => 1; } } - """; - - await TestChangeSignatureViaCommandAsync( - LanguageNames.CSharp, - markup: markup, - updatedSignature: [1, 0], - expectedUpdatedInvocationDocumentCode: expectedCode); + """); } [Fact] - public async Task TestOnAnonymousMethodWithTwoParameters_ViaCommand() - { - var markup = """ + public Task TestOnAnonymousMethodWithTwoParameters_ViaCommand() + => TestMissingAsync(""" class Program { static void M() @@ -175,14 +162,11 @@ static void M() System.Func f = [||]delegate(int x, string y) { return 1; }; } } - """; - await TestMissingAsync(markup); - } + """); [Fact] - public async Task TestOnAnonymousMethodWithTwoDiscardParameters_ViaCommand() - { - var markup = """ + public Task TestOnAnonymousMethodWithTwoDiscardParameters_ViaCommand() + => TestMissingAsync(""" class Program { static void M() @@ -190,14 +174,11 @@ static void M() System.Func f = [||]delegate(int _, string _) { return 1; }; } } - """; - await TestMissingAsync(markup); - } + """); [Fact] - public async Task TestAfterSemicolonForInvocationInExpressionStatement_ViaCodeAction() - { - var markup = """ + public Task TestAfterSemicolonForInvocationInExpressionStatement_ViaCodeAction() + => TestMissingAsync(""" class Program { static void Main(string[] args) @@ -210,15 +191,11 @@ static void M1(int x, int y) { } static void M2(int x, int y, int z) { } } - """; - - await TestMissingAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17309")] - public async Task TestNotInLeadingWhitespace() - { - var markup = """ + public Task TestNotInLeadingWhitespace() + => TestChangeSignatureViaCodeActionAsync(""" class Ext { [||] @@ -226,15 +203,11 @@ void Goo(int a, int b) { }; } - """; - - await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); - } + """, expectedCodeAction: false); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17309")] - public async Task TestNotInLeadingTrivia() - { - var markup = """ + public Task TestNotInLeadingTrivia() + => TestChangeSignatureViaCodeActionAsync(""" class Ext { // [||] @@ -242,15 +215,11 @@ void Goo(int a, int b) { }; } - """; - - await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); - } + """, expectedCodeAction: false); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17309")] - public async Task TestNotInLeadingTrivia2() - { - var markup = """ + public Task TestNotInLeadingTrivia2() + => TestChangeSignatureViaCodeActionAsync(""" class Ext { [||]// @@ -258,15 +227,11 @@ void Goo(int a, int b) { }; } - """; - - await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); - } + """, expectedCodeAction: false); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17309")] - public async Task TestNotInLeadingDocComment() - { - var markup = """ + public Task TestNotInLeadingDocComment() + => TestChangeSignatureViaCodeActionAsync(""" class Ext { /// [||] @@ -274,15 +239,11 @@ void Goo(int a, int b) { }; } - """; - - await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); - } + """, expectedCodeAction: false); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17309")] - public async Task TestNotInLeadingDocComment2() - { - var markup = """ + public Task TestNotInLeadingDocComment2() + => TestChangeSignatureViaCodeActionAsync(""" class Ext { [||]/// @@ -290,15 +251,11 @@ void Goo(int a, int b) { }; } - """; - - await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); - } + """, expectedCodeAction: false); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17309")] - public async Task TestNotInLeadingAttributes1() - { - var markup = """ + public Task TestNotInLeadingAttributes1() + => TestChangeSignatureViaCodeActionAsync(""" class Ext { [||][X] @@ -306,15 +263,11 @@ void Goo(int a, int b) { }; } - """; - - await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); - } + """, expectedCodeAction: false); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17309")] - public async Task TestNotInLeadingAttributes2() - { - var markup = """ + public Task TestNotInLeadingAttributes2() + => TestChangeSignatureViaCodeActionAsync(""" class Ext { [[||]X] @@ -322,15 +275,11 @@ void Goo(int a, int b) { }; } - """; - - await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); - } + """, expectedCodeAction: false); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17309")] - public async Task TestNotInLeadingAttributes3() - { - var markup = """ + public Task TestNotInLeadingAttributes3() + => TestChangeSignatureViaCodeActionAsync(""" class Ext { [X][||] @@ -338,23 +287,16 @@ void Goo(int a, int b) { }; } - """; - - await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); - } + """, expectedCodeAction: false); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17309")] - public async Task TestNotInConstraints() - { - var markup = """ + public Task TestNotInConstraints() + => TestChangeSignatureViaCodeActionAsync(""" class Ext { void Goo(int a, int b) where [||]T : class { }; } - """; - - await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); - } + """, expectedCodeAction: false); } diff --git a/src/EditorFeatures/CSharpTest/ChangeSignature/ChangeSignature_CheckAllSignatureChanges.cs b/src/EditorFeatures/CSharpTest/ChangeSignature/ChangeSignature_CheckAllSignatureChanges.cs index c9278a29ea244..fd28066af7ddf 100644 --- a/src/EditorFeatures/CSharpTest/ChangeSignature/ChangeSignature_CheckAllSignatureChanges.cs +++ b/src/EditorFeatures/CSharpTest/ChangeSignature/ChangeSignature_CheckAllSignatureChanges.cs @@ -21,9 +21,10 @@ public sealed partial class ChangeSignatureTests : AbstractChangeSignatureTests // https://github.com/xunit/xunit/issues/1968 [MemberData(nameof(AbstractChangeSignatureTests.GetAllSignatureSpecificationsForTheory), new[] { 1, 3, 2, 1 }, MemberType = typeof(AbstractChangeSignatureTests))] #pragma warning restore xUnit1019 - public async Task TestAllSignatureChanges_1This_3Regular_2Default_1Params(int totalParameters, int[] signature) - { - var markup = """ + public Task TestAllSignatureChanges_1This_3Regular_2Default_1Params(int totalParameters, int[] signature) + => TestChangeSignatureViaCommandAsync( + LanguageNames.CSharp, + """ static class Ext { /// @@ -64,16 +65,11 @@ static class Ext M(p: new[] { 5 }, y: "four", x: 3, c: true, b: "two", a: 1, o: t); } } - """; - - await TestChangeSignatureViaCommandAsync( - LanguageNames.CSharp, - markup, + """, expectedSuccess: true, updatedSignature: signature, totalParameters: totalParameters, verifyNoDiagnostics: true); - } [Theory] #pragma warning disable xUnit1019 @@ -81,9 +77,10 @@ await TestChangeSignatureViaCommandAsync( // https://github.com/xunit/xunit/issues/1968 [MemberData(nameof(AbstractChangeSignatureTests.GetAllSignatureSpecificationsForTheory), new[] { 0, 3, 0, 0 }, MemberType = typeof(AbstractChangeSignatureTests))] #pragma warning restore xUnit1019 - public async Task TestAllSignatureChanges_OnDelegate_3Regular(int totalParameters, int[] signature) - { - var markup = """ + public Task TestAllSignatureChanges_OnDelegate_3Regular(int totalParameters, int[] signature) + => TestChangeSignatureViaCommandAsync( + LanguageNames.CSharp, + """ using System; using System.Collections.Generic; using System.Linq; @@ -170,15 +167,10 @@ void Goo4(int a, string b, bool c) { } /// void Goo5(int a, string b, bool c) { } } - """; - - await TestChangeSignatureViaCommandAsync( - LanguageNames.CSharp, - markup, + """, expectedSuccess: true, updatedSignature: signature, totalParameters: totalParameters, verifyNoDiagnostics: true, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp7)); - } } diff --git a/src/EditorFeatures/CSharpTest/ChangeSignature/ChangeSignature_Delegates.cs b/src/EditorFeatures/CSharpTest/ChangeSignature/ChangeSignature_Delegates.cs index 23bd47545b100..15a7788f15bc2 100644 --- a/src/EditorFeatures/CSharpTest/ChangeSignature/ChangeSignature_Delegates.cs +++ b/src/EditorFeatures/CSharpTest/ChangeSignature/ChangeSignature_Delegates.cs @@ -26,7 +26,8 @@ protected internal override string GetLanguage() [Fact] public async Task ChangeSignature_Delegates_ImplicitInvokeCalls() { - var markup = """ + var updatedSignature = new[] { 2, 1 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate void MyDelegate($$int x, string y, bool z); class C @@ -37,9 +38,8 @@ void M() d1(1, "Two", true); } } - """; - var updatedSignature = new[] { 2, 1 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, + expectedUpdatedInvocationDocumentCode: """ delegate void MyDelegate(bool z, string y); class C @@ -50,15 +50,14 @@ void M() d1(true, "Two"); } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, - expectedUpdatedInvocationDocumentCode: expectedUpdatedCode, expectedSelectedIndex: 0); + """, expectedSelectedIndex: 0); } [Fact] public async Task ChangeSignature_Delegates_ExplicitInvokeCalls() { - var markup = """ + var updatedSignature = new[] { 2, 1 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate void MyDelegate(int x, string $$y, bool z); class C @@ -69,9 +68,8 @@ void M() d1.Invoke(1, "Two", true); } } - """; - var updatedSignature = new[] { 2, 1 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, + expectedUpdatedInvocationDocumentCode: """ delegate void MyDelegate(bool z, string y); class C @@ -82,15 +80,14 @@ void M() d1.Invoke(true, "Two"); } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, - expectedUpdatedInvocationDocumentCode: expectedUpdatedCode, expectedSelectedIndex: 1); + """, expectedSelectedIndex: 1); } [Fact] public async Task ChangeSignature_Delegates_BeginInvokeCalls() { - var markup = """ + var updatedSignature = new[] { 2, 1 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate void MyDelegate(int x, string y, bool z$$); class C @@ -101,9 +98,8 @@ void M() d1.BeginInvoke(1, "Two", true, null, null); } } - """; - var updatedSignature = new[] { 2, 1 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, + expectedUpdatedInvocationDocumentCode: """ delegate void MyDelegate(bool z, string y); class C @@ -114,15 +110,14 @@ void M() d1.BeginInvoke(true, "Two", null, null); } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, - expectedUpdatedInvocationDocumentCode: expectedUpdatedCode, expectedSelectedIndex: 2); + """, expectedSelectedIndex: 2); } [Fact] public async Task ChangeSignature_Delegates_AnonymousMethods() { - var markup = """ + var updatedSignature = new[] { 2, 1 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate void $$MyDelegate(int x, string y, bool z); class C @@ -134,9 +129,7 @@ void M() d1 = delegate { }; } } - """; - var updatedSignature = new[] { 2, 1 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ delegate void MyDelegate(bool z, string y); class C @@ -148,14 +141,14 @@ void M() d1 = delegate { }; } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task ChangeSignature_Delegates_Lambdas() { - var markup = """ + var updatedSignature = new[] { 2, 1 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate void $$MyDelegate(int x, string y, bool z); class C @@ -166,9 +159,7 @@ void M() d1 = (r, s, t) => { var x = s.Length + (t ? 0 : 1); }; } } - """; - var updatedSignature = new[] { 2, 1 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ delegate void MyDelegate(bool z, string y); class C @@ -179,14 +170,14 @@ void M() d1 = (t, s) => { var x = s.Length + (t ? 0 : 1); }; } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task ChangeSignature_Delegates_Lambdas_RemovingOnlyParameterIntroducesParentheses() { - var markup = """ + var updatedSignature = Array.Empty(); + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate void $$MyDelegate(int x); class C @@ -199,9 +190,7 @@ void M() d1 = r => { System.Console.WriteLine("Test"); }; } } - """; - var updatedSignature = Array.Empty(); - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ delegate void MyDelegate(); class C @@ -214,14 +203,14 @@ void M() d1 = () => { System.Console.WriteLine("Test"); }; } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task ChangeSignature_Delegates_CascadeThroughMethodGroups_AssignedToVariable() { - var markup = """ + var updatedSignature = new[] { 2, 1 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate void $$MyDelegate(int x, string y, bool z); class C @@ -237,9 +226,7 @@ void M() void Goo(int a, string b, bool c) { } void Goo(int a, object b, bool c) { } } - """; - var updatedSignature = new[] { 2, 1 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ delegate void MyDelegate(bool z, string y); class C @@ -255,14 +242,14 @@ void M() void Goo(bool c, string b) { } void Goo(int a, object b, bool c) { } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task ChangeSignature_Delegates_CascadeThroughMethodGroups_DelegateConstructor() { - var markup = """ + var updatedSignature = new[] { 2, 1 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate void $$MyDelegate(int x, string y, bool z); class C @@ -277,9 +264,7 @@ void M() void Goo(int a, string b, bool c) { } void Goo(int a, object b, bool c) { } } - """; - var updatedSignature = new[] { 2, 1 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ delegate void MyDelegate(bool z, string y); class C @@ -294,14 +279,14 @@ void M() void Goo(bool c, string b) { } void Goo(int a, object b, bool c) { } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task ChangeSignature_Delegates_CascadeThroughMethodGroups_PassedAsArgument() { - var markup = """ + var updatedSignature = new[] { 2, 1 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate void $$MyDelegate(int x, string y, bool z); class C @@ -318,9 +303,7 @@ void Target(MyDelegate d) { } void Goo(int a, string b, bool c) { } void Goo(int a, object b, bool c) { } } - """; - var updatedSignature = new[] { 2, 1 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ delegate void MyDelegate(bool z, string y); class C @@ -337,14 +320,14 @@ void Target(MyDelegate d) { } void Goo(bool c, string b) { } void Goo(int a, object b, bool c) { } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task ChangeSignature_Delegates_CascadeThroughMethodGroups_ReturnValue() { - var markup = """ + var updatedSignature = new[] { 2, 1 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate void $$MyDelegate(int x, string y, bool z); class C @@ -363,9 +346,7 @@ private MyDelegate Result() void Goo(int a, string b, bool c) { } void Goo(int a, object b, bool c) { } } - """; - var updatedSignature = new[] { 2, 1 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ delegate void MyDelegate(bool z, string y); class C @@ -384,14 +365,14 @@ private MyDelegate Result() void Goo(bool c, string b) { } void Goo(int a, object b, bool c) { } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task ChangeSignature_Delegates_CascadeThroughMethodGroups_YieldReturnValue() { - var markup = """ + var updatedSignature = new[] { 2, 1 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System.Collections.Generic; delegate void $$MyDelegate(int x, string y, bool z); @@ -411,9 +392,7 @@ private IEnumerable Result() void Goo(int a, string b, bool c) { } void Goo(int a, object b, bool c) { } } - """; - var updatedSignature = new[] { 2, 1 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ using System.Collections.Generic; delegate void MyDelegate(bool z, string y); @@ -433,14 +412,14 @@ private IEnumerable Result() void Goo(bool c, string b) { } void Goo(int a, object b, bool c) { } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task ChangeSignature_Delegates_ReferencingLambdas_MethodArgument() { - var markup = """ + var updatedSignature = new[] { 2, 1 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate void $$MyDelegate(int x, string y, bool z); class C @@ -452,9 +431,7 @@ void M6() void Target(MyDelegate d) { } } - """; - var updatedSignature = new[] { 2, 1 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ delegate void MyDelegate(bool z, string y); class C @@ -466,14 +443,14 @@ void M6() void Target(MyDelegate d) { } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task ChangeSignature_Delegates_ReferencingLambdas_YieldReturn() { - var markup = """ + var updatedSignature = new[] { 2, 1 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System.Collections.Generic; delegate void $$MyDelegate(int x, string y, bool z); @@ -484,9 +461,7 @@ private IEnumerable Result3() yield return (g, h, i) => { var x = h.Length + (i ? 0 : 1); }; } } - """; - var updatedSignature = new[] { 2, 1 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ using System.Collections.Generic; delegate void MyDelegate(bool z, string y); @@ -497,14 +472,14 @@ private IEnumerable Result3() yield return (i, h) => { var x = h.Length + (i ? 0 : 1); }; } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task ChangeSignature_Delegates_Recursive() { - var markup = """ + var updatedSignature = new[] { 2, 1 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate RecursiveDelegate $$RecursiveDelegate(int x, string y, bool z); class C @@ -515,9 +490,7 @@ void M() rd(1, "Two", true)(1, "Two", true)(1, "Two", true)(1, "Two", true)(1, "Two", true); } } - """; - var updatedSignature = new[] { 2, 1 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ delegate RecursiveDelegate RecursiveDelegate(bool z, string y); class C @@ -528,14 +501,14 @@ void M() rd(true, "Two")(true, "Two")(true, "Two")(true, "Two")(true, "Two"); } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task ChangeSignature_Delegates_DocComments() { - var markup = """ + var updatedSignature = new[] { 2, 1 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ /// /// This is , which has these methods: /// @@ -561,9 +534,7 @@ void M() /// void Goo(int a, string b, bool c) { } } - """; - var updatedSignature = new[] { 2, 1 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ /// /// This is , which has these methods: /// @@ -589,14 +560,14 @@ void M() /// void Goo(bool c, string b) { } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task ChangeSignature_Delegates_CascadeThroughEventAdd() { - var markup = """ + var updatedSignature = new[] { 2, 1 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ delegate void $$MyDelegate(int x, string y, bool z); class Program @@ -609,9 +580,7 @@ void M() event MyDelegate MyEvent; void Program_MyEvent(int a, string b, bool c) { } } - """; - var updatedSignature = new[] { 2, 1 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ delegate void MyDelegate(bool z, string y); class Program @@ -624,14 +593,14 @@ void M() event MyDelegate MyEvent; void Program_MyEvent(bool c, string b) { } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task ChangeSignature_Delegates_Generics1() { - var markup = """ + var updatedSignature = Array.Empty(); + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class DP16a { public delegate void D($$T t); @@ -649,9 +618,7 @@ void B() E2 -= new D(M3); } } - """; - var updatedSignature = Array.Empty(); - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ public class DP16a { public delegate void D(); @@ -669,14 +636,14 @@ void B() E2 -= new D(M3); } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task ChangeSignature_Delegates_Generics2() { - var markup = """ + var updatedSignature = Array.Empty(); + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class D17 { public delegate void $$D(T t); @@ -686,9 +653,7 @@ public class D17Test void Test() { var x = new D17.D(M17); } internal void M17(string s) { } } - """; - var updatedSignature = Array.Empty(); - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ public class D17 { public delegate void D(); @@ -698,14 +663,14 @@ public class D17Test void Test() { var x = new D17.D(M17); } internal void M17() { } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task ChangeSignature_Delegates_GenericParams() { - var markup = """ + var updatedSignature = Array.Empty(); + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class DA { void M(params int[] i) { } @@ -727,9 +692,7 @@ void B() D d = new D(M1); } } - """; - var updatedSignature = Array.Empty(); - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class DA { void M() { } @@ -751,14 +714,14 @@ void B() D d = new D(M1); } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task ChangeSignature_Delegates_Generic_RemoveArgumentAtReference() { - var markup = """ + var updatedSignature = Array.Empty(); + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class CD { public delegate void D(T t); @@ -770,9 +733,8 @@ public void M() var dele = new CD.$$D((int x) => { }); } } - """; - var updatedSignature = Array.Empty(); - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, + expectedUpdatedInvocationDocumentCode: """ public class CD { public delegate void D(); @@ -784,15 +746,14 @@ public void M() var dele = new CD.D(() => { }); } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, - expectedUpdatedInvocationDocumentCode: expectedUpdatedCode, expectedSelectedIndex: 0); + """, expectedSelectedIndex: 0); } [Fact] public async Task ChangeSignature_Delegate_Generics_RemoveStaticArgument() { - var markup = """ + var updatedSignature = Array.Empty(); + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C2 { public delegate void D(T t); @@ -809,9 +770,7 @@ void B() $$d(D2.Instance); } } - """; - var updatedSignature = Array.Empty(); - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ public class C2 { public delegate void D(); @@ -828,7 +787,6 @@ void B() d(); } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } } diff --git a/src/EditorFeatures/CSharpTest/ChangeSignature/ChangeSignature_Formatting.cs b/src/EditorFeatures/CSharpTest/ChangeSignature/ChangeSignature_Formatting.cs index 64a6a1372de62..76f557ddbdfde 100644 --- a/src/EditorFeatures/CSharpTest/ChangeSignature/ChangeSignature_Formatting.cs +++ b/src/EditorFeatures/CSharpTest/ChangeSignature/ChangeSignature_Formatting.cs @@ -18,7 +18,8 @@ public sealed partial class ChangeSignatureTests : AbstractChangeSignatureTests [Fact] public async Task ChangeSignature_Formatting_KeepCountsPerLine() { - var markup = """ + var updatedSignature = new[] { 5, 4, 3, 2, 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class C { void $$Method(int a, int b, int c, @@ -30,9 +31,7 @@ class C 4, 5, 6); } } - """; - var updatedSignature = new[] { 5, 4, 3, 2, 1, 0 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class C { void Method(int f, int e, int d, @@ -44,14 +43,14 @@ void Method(int f, int e, int d, 3, 2, 1); } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28156")] public async Task ChangeSignature_Formatting_KeepTrivia() { - var markup = """ + var updatedSignature = new[] { 1, 2, 3, 4, 5 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class C { void $$Method( @@ -64,9 +63,7 @@ class C 4, 5, 6); } } - """; - var updatedSignature = new[] { 1, 2, 3, 4, 5 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class C { void Method( @@ -78,14 +75,14 @@ void Method( 5, 6); } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28156")] public async Task ChangeSignature_Formatting_KeepTrivia_WithArgumentNames() { - var markup = """ + var updatedSignature = new[] { 1, 2, 3, 4, 5 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class C { void $$Method( @@ -98,9 +95,7 @@ class C d: 4, e: 5, f: 6); } } - """; - var updatedSignature = new[] { 1, 2, 3, 4, 5 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class C { void Method( @@ -112,14 +107,14 @@ void Method( e: 5, f: 6); } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task ChangeSignature_Formatting_Method() { - var markup = """ + var updatedSignature = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class C { void $$Method(int a, @@ -129,9 +124,7 @@ class C 2); } } - """; - var updatedSignature = new[] { 1, 0 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class C { void Method(int b, @@ -141,14 +134,14 @@ void Method(int b, 1); } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task ChangeSignature_Formatting_Constructor() { - var markup = """ + var updatedSignature = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class SomeClass { $$SomeClass(int a, @@ -158,9 +151,7 @@ class SomeClass 2); } } - """; - var updatedSignature = new[] { 1, 0 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class SomeClass { SomeClass(int b, @@ -170,14 +161,14 @@ class SomeClass 1); } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task ChangeSignature_Formatting_Indexer() { - var markup = """ + var updatedSignature = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class SomeClass { public int $$this[int a, @@ -190,9 +181,7 @@ int b] } } } - """; - var updatedSignature = new[] { 1, 0 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class SomeClass { public int this[int b, @@ -205,14 +194,14 @@ int a] } } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task ChangeSignature_Formatting_Delegate() { - var markup = """ + var updatedSignature = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class SomeClass { delegate void $$MyDelegate(int a, @@ -226,9 +215,7 @@ void M(int a, 2); } } - """; - var updatedSignature = new[] { 1, 0 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class SomeClass { delegate void MyDelegate(int b, @@ -242,14 +229,14 @@ void M(int b, 1); } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task ChangeSignature_Formatting_AnonymousMethod() { - var markup = """ + var updatedSignature = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class SomeClass { delegate void $$MyDelegate(int a, @@ -264,9 +251,7 @@ void M() }; } } - """; - var updatedSignature = new[] { 1, 0 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class SomeClass { delegate void MyDelegate(int b, @@ -281,14 +266,14 @@ void M() }; } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task ChangeSignature_Formatting_ConstructorInitializers() { - var markup = """ + var updatedSignature = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class B { public $$B(int x, int y) { } @@ -303,9 +288,7 @@ public D() : base(1, 2) { } } - """; - var updatedSignature = new[] { 1, 0 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class B { public B(int y, int x) { } @@ -320,128 +303,118 @@ public D() : base(2, 1) { } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact] public async Task ChangeSignature_Formatting_Attribute() { - var markup = """ + var updatedSignature = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ [Custom(1, 2)] class CustomAttribute : System.Attribute { public $$CustomAttribute(int x, int y) { } } - """; - var updatedSignature = new[] { 1, 0 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ [Custom(2, 1)] class CustomAttribute : System.Attribute { public CustomAttribute(int y, int x) { } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28156")] public async Task ChangeSignature_Formatting_Attribute_KeepTrivia() { - var markup = """ + var updatedSignature = new[] { 1 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ [Custom( 1, 2)] class CustomAttribute : System.Attribute { public $$CustomAttribute(int x, int y) { } } - """; - var updatedSignature = new[] { 1 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ [Custom( 2)] class CustomAttribute : System.Attribute { public CustomAttribute(int y) { } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28156")] public async Task ChangeSignature_Formatting_Attribute_KeepTrivia_RemovingSecond() { - var markup = """ + var updatedSignature = new[] { 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ [Custom( 1, 2)] class CustomAttribute : System.Attribute { public $$CustomAttribute(int x, int y) { } } - """; - var updatedSignature = new[] { 0 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ [Custom( 1)] class CustomAttribute : System.Attribute { public CustomAttribute(int x) { } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28156")] public async Task ChangeSignature_Formatting_Attribute_KeepTrivia_RemovingBoth() { - var markup = """ + var updatedSignature = new int[] { }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ [Custom( 1, 2)] class CustomAttribute : System.Attribute { public $$CustomAttribute(int x, int y) { } } - """; - var updatedSignature = new int[] { }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ [Custom( )] class CustomAttribute : System.Attribute { public CustomAttribute() { } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28156")] public async Task ChangeSignature_Formatting_Attribute_KeepTrivia_RemovingBeforeNewlineComma() { - var markup = """ + var updatedSignature = new[] { 1, 2 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ [Custom(1 , 2, 3)] class CustomAttribute : System.Attribute { public $$CustomAttribute(int x, int y, int z) { } } - """; - var updatedSignature = new[] { 1, 2 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ [Custom(2, 3)] class CustomAttribute : System.Attribute { public CustomAttribute(int y, int z) { } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/946220")] public async Task ChangeSignature_Formatting_LambdaAsArgument() { - var markup = """ + var updatedSignature = new[] { 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class C { void M(System.Action f, int z$$) @@ -449,9 +422,7 @@ void M(System.Action f, int z$$) M((x, y) => System.Console.WriteLine(x + y), 5); } } - """; - var updatedSignature = new[] { 0 }; - var expectedUpdatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class C { void M(System.Action f) @@ -459,7 +430,6 @@ void M(System.Action f) M((x, y) => System.Console.WriteLine(x + y)); } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); + """); } } diff --git a/src/EditorFeatures/CSharpTest/ChangeSignature/RemoveParametersTests.cs b/src/EditorFeatures/CSharpTest/ChangeSignature/RemoveParametersTests.cs index 0d22ee322cb97..39aeae062c190 100644 --- a/src/EditorFeatures/CSharpTest/ChangeSignature/RemoveParametersTests.cs +++ b/src/EditorFeatures/CSharpTest/ChangeSignature/RemoveParametersTests.cs @@ -27,7 +27,8 @@ public sealed partial class ChangeSignatureTests : AbstractChangeSignatureTests [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task RemoveParameters1() { - var markup = """ + var updatedSignature = new[] { 0, 2, 5 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ static class Ext { /// @@ -68,9 +69,7 @@ static class Ext M(p: new[] { 5 }, y: "four", x: 3, c: true, b: "two", a: 1, o: t); } } - """; - var updatedSignature = new[] { 0, 2, 5 }; - var updatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ static class Ext { /// @@ -111,15 +110,14 @@ static void M(this object o, string b, string y = "Zero") M(y: "four", b: "two", o: t); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task RemoveParameters_GenericParameterType() { - var markup = """ + var updatedSignature = Array.Empty(); + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class DA { void M(params int[] i) { } @@ -150,9 +148,7 @@ void B() E2 -= new D(M3); } } - """; - var updatedSignature = Array.Empty(); - var updatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ class DA { void M() { } @@ -183,9 +179,7 @@ void B() E2 -= new D(M3); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] @@ -200,17 +194,18 @@ public async Task RemoveParameters_ExtensionMethodInAnotherFile() for (var i = 0; i <= 4; i++) { - workspaceXml += $@" - -class C{i} -{{ - void M() - {{ - C5 c = new C5(); - c.Ext(1, ""two""); - }} -}} -"; + workspaceXml += $$""" + + class C{{i}} + { + void M() + { + C5 c = new C5(); + c.Ext(1, "two"); + } + } + + """; } workspaceXml += """ @@ -230,17 +225,18 @@ public static class C5Ext for (var i = 6; i <= 9; i++) { - workspaceXml += $@" - -class C{i} -{{ - void M() - {{ - C5 c = new C5(); - c.Ext(1, ""two""); - }} -}} -"; + workspaceXml += $$""" + + class C{{i}} + { + void M() + { + C5 c = new C5(); + c.Ext(1, "two"); + } + } + + """; } workspaceXml += """ @@ -284,17 +280,18 @@ public async Task AddRemoveParameters_ExtensionMethodInAnotherFile() for (var i = 0; i <= 4; i++) { - workspaceXml += $@" - -class C{i} -{{ - void M() - {{ - C5 c = new C5(); - c.Ext(1, ""two""); - }} -}} -"; + workspaceXml += $$""" + + class C{{i}} + { + void M() + { + C5 c = new C5(); + c.Ext(1, "two"); + } + } + + """; } workspaceXml += """ @@ -314,17 +311,18 @@ public static class C5Ext for (var i = 6; i <= 9; i++) { - workspaceXml += $@" - -class C{i} -{{ - void M() - {{ - C5 c = new C5(); - c.Ext(1, ""two""); - }} -}} -"; + workspaceXml += $$""" + + class C{{i}} + { + void M() + { + C5 c = new C5(); + c.Ext(1, "two"); + } + } + + """; } workspaceXml += """ @@ -394,7 +392,8 @@ class C [WorkItem("https://github.com/dotnet/roslyn/issues/44126")] public async Task RemoveParameters_ImplicitObjectCreation() { - var markup = """ + var updatedSignature = new[] { 1 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { public $$C(int a, string b) { } @@ -404,9 +403,7 @@ void M() C c = new(1, "b"); } } - """; - var updatedSignature = new[] { 1 }; - var updatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ public class C { public C(string b) { } @@ -416,32 +413,26 @@ void M() C c = new("b"); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] [WorkItem("https://github.com/dotnet/roslyn/issues/66547")] public async Task RemoveParameters_SpecialSymbolNamedParameter() { - var markup = """ + var updatedSignature = new[] { 1 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ void $$m(object? param, bool @new = true) { } m(null, @new: false); - """; - - var updatedSignature = new[] { 1 }; - var updatedCode = """ + """, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: """ void m(bool @new = true) { } m(@new: false); - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } } diff --git a/src/EditorFeatures/CSharpTest/ChangeSignature/ReorderParametersTests.Cascading.cs b/src/EditorFeatures/CSharpTest/ChangeSignature/ReorderParametersTests.Cascading.cs index a11b9c550cc80..3cae66ee396c9 100644 --- a/src/EditorFeatures/CSharpTest/ChangeSignature/ReorderParametersTests.Cascading.cs +++ b/src/EditorFeatures/CSharpTest/ChangeSignature/ReorderParametersTests.Cascading.cs @@ -17,7 +17,8 @@ public sealed partial class ChangeSignatureTests : AbstractChangeSignatureTests [Fact] public async Task ReorderParameters_Cascade_ToImplementedMethod() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ interface I { void M(int x, string y); @@ -28,9 +29,7 @@ class C : I $$public void M(int x, string y) { } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ interface I { void M(string y, int x); @@ -41,15 +40,14 @@ class C : I public void M(string y, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParameters_Cascade_ToImplementedMethod_WithTuples() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ interface I { void M((int, int) x, (string a, string b) y); @@ -60,9 +58,7 @@ class C : I $$public void M((int, int) x, (string a, string b) y) { } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ interface I { void M((string a, string b) y, (int, int) x); @@ -73,15 +69,14 @@ class C : I public void M((string a, string b) y, (int, int) x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParameters_Cascade_ToImplementingMethod() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ interface I { $$void M(int x, string y); @@ -92,9 +87,7 @@ class C : I public void M(int x, string y) { } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ interface I { void M(string y, int x); @@ -105,15 +98,14 @@ class C : I public void M(string y, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParameters_Cascade_ToOverriddenMethod() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class B { public virtual void M(int x, string y) @@ -125,9 +117,7 @@ class D : B $$public override void M(int x, string y) { } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ class B { public virtual void M(string y, int x) @@ -139,15 +129,14 @@ class D : B public override void M(string y, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParameters_Cascade_ToOverridingMethod() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class B { $$public virtual void M(int x, string y) @@ -159,9 +148,7 @@ class D : B public override void M(int x, string y) { } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ class B { public virtual void M(string y, int x) @@ -173,15 +160,14 @@ class D : B public override void M(string y, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParameters_Cascade_ToOverriddenMethod_Transitive() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class B { public virtual void M(int x, string y) @@ -199,9 +185,7 @@ class D2 : D $$public override void M(int x, string y) { } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ class B { public virtual void M(string y, int x) @@ -219,15 +203,14 @@ class D2 : D public override void M(string y, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParameters_Cascade_ToOverridingMethod_Transitive() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class B { $$public virtual void M(int x, string y) @@ -245,9 +228,7 @@ class D2 : D public override void M(int x, string y) { } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ class B { public virtual void M(string y, int x) @@ -265,9 +246,7 @@ class D2 : D public override void M(string y, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] @@ -279,7 +258,8 @@ public async Task ReorderParameters_Cascade_ToMethods_Complex() //// / \ \ //// $$D2 D3 C - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class B { public virtual void M(int x, string y) { } } class D : B, I { public override void M(int x, string y) { } } class D2 : D { public override void $$M(int x, string y) { } } @@ -288,10 +268,7 @@ interface I { void M(int x, string y); } interface I2 { void M(int x, string y); } interface I3 : I, I2 { } class C : I3 { public void M(int x, string y) { } } - """; - - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ class B { public virtual void M(string y, int x) { } } class D : B, I { public override void M(string y, int x) { } } class D2 : D { public override void M(string y, int x) { } } @@ -300,15 +277,14 @@ interface I { void M(string y, int x); } interface I2 { void M(string y, int x); } interface I3 : I, I2 { } class C : I3 { public void M(string y, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParameters_Cascade_ToMethods_WithDifferentParameterNames() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class B { /// @@ -346,9 +322,7 @@ public class D2 : D return 1; } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class B { /// @@ -386,7 +360,6 @@ public override int M(string x, int y) return 1; } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } } diff --git a/src/EditorFeatures/CSharpTest/ChangeSignature/ReorderParametersTests.InvocationErrors.cs b/src/EditorFeatures/CSharpTest/ChangeSignature/ReorderParametersTests.InvocationErrors.cs index 64561fcf61f9a..1ed50d76c06ca 100644 --- a/src/EditorFeatures/CSharpTest/ChangeSignature/ReorderParametersTests.InvocationErrors.cs +++ b/src/EditorFeatures/CSharpTest/ChangeSignature/ReorderParametersTests.InvocationErrors.cs @@ -16,9 +16,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature; public sealed partial class ChangeSignatureTests : AbstractChangeSignatureTests { [Fact] - public async Task ReorderMethodParameters_InvokeOnClassName_ShouldFail() - { - var markup = """ + public Task ReorderMethodParameters_InvokeOnClassName_ShouldFail() + => TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class MyClass$$ { @@ -26,15 +25,11 @@ public void Goo(int x, string y) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind); - } + """, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind); [Fact] - public async Task ReorderMethodParameters_InvokeOnField_ShouldFail() - { - var markup = """ + public Task ReorderMethodParameters_InvokeOnField_ShouldFail() + => TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class MyClass { @@ -44,22 +39,15 @@ public void Goo(int x, string y) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind); - } + """, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind); [Fact] - public async Task ReorderMethodParameters_CanBeStartedEvenWithNoParameters() - { - var markup = @"class C { void $$M() { } }"; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: true); - } + public Task ReorderMethodParameters_CanBeStartedEvenWithNoParameters() + => TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, @"class C { void $$M() { } }", expectedSuccess: true); [Fact] - public async Task ReorderMethodParameters_InvokeOnOverloadedOperator_ShouldFail() - { - var markup = """ + public Task ReorderMethodParameters_InvokeOnOverloadedOperator_ShouldFail() + => TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class C { public static C $$operator +(C a, C b) @@ -67,8 +55,5 @@ class C return null; } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind); - } + """, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind); } diff --git a/src/EditorFeatures/CSharpTest/ChangeSignature/ReorderParametersTests.InvocationLocation.cs b/src/EditorFeatures/CSharpTest/ChangeSignature/ReorderParametersTests.InvocationLocation.cs index 7d3d8378c9b22..939d0e6efc284 100644 --- a/src/EditorFeatures/CSharpTest/ChangeSignature/ReorderParametersTests.InvocationLocation.cs +++ b/src/EditorFeatures/CSharpTest/ChangeSignature/ReorderParametersTests.InvocationLocation.cs @@ -20,7 +20,8 @@ public sealed partial class ChangeSignatureTests : AbstractChangeSignatureTests [Fact] public async Task ReorderMethodParameters_InvokeBeforeMethodName() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class MyClass { @@ -28,9 +29,8 @@ class MyClass { } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, + expectedUpdatedInvocationDocumentCode: """ using System; class MyClass { @@ -38,16 +38,14 @@ public void Goo(string y, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, - expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); + """, expectedSelectedIndex: 0); } [Fact] public async Task ReorderMethodParameters_InvokeInParameterList() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class MyClass { @@ -55,9 +53,8 @@ public void Goo(int x, $$string y) { } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, + expectedUpdatedInvocationDocumentCode: """ using System; class MyClass { @@ -65,16 +62,14 @@ public void Goo(string y, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, - expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 1); + """, expectedSelectedIndex: 1); } [Fact] public async Task ReorderMethodParameters_InvokeAfterParameterList() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class MyClass { @@ -82,9 +77,7 @@ public void Goo(int x, string y)$$ { } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ using System; class MyClass { @@ -92,15 +85,14 @@ public void Goo(string y, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderMethodParameters_InvokeBeforeMethodDeclaration() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class MyClass { @@ -108,9 +100,7 @@ class MyClass { } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ using System; class MyClass { @@ -118,15 +108,12 @@ public void Goo(string y, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] - public async Task ReorderMethodParameters_InvokeOnMetadataReference_InIdentifier_ShouldFail() - { - var markup = """ + public Task ReorderMethodParameters_InvokeOnMetadataReference_InIdentifier_ShouldFail() + => TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class C { static void Main(string[] args) @@ -134,15 +121,11 @@ static void Main(string[] args) ((System.IFormattable)null).ToSt$$ring("test", null); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.DefinedInMetadata); - } + """, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.DefinedInMetadata); [Fact] - public async Task ReorderMethodParameters_InvokeOnMetadataReference_AtBeginningOfInvocation_ShouldFail() - { - var markup = """ + public Task ReorderMethodParameters_InvokeOnMetadataReference_AtBeginningOfInvocation_ShouldFail() + => TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class C { static void Main(string[] args) @@ -150,15 +133,11 @@ static void Main(string[] args) $$((System.IFormattable)null).ToString("test", null); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.DefinedInMetadata); - } + """, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.DefinedInMetadata); [Fact] - public async Task ReorderMethodParameters_InvokeOnMetadataReference_InArgumentsOfInvocation_ShouldFail() - { - var markup = """ + public Task ReorderMethodParameters_InvokeOnMetadataReference_InArgumentsOfInvocation_ShouldFail() + => TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class C { static void Main(string[] args) @@ -166,28 +145,21 @@ static void Main(string[] args) ((System.IFormattable)null).ToString("test",$$ null); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.DefinedInMetadata); - } + """, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.DefinedInMetadata); [Fact] - public async Task ReorderMethodParameters_InvokeOnMetadataReference_AfterInvocation_ShouldFail() - { - var markup = """ + public Task ReorderMethodParameters_InvokeOnMetadataReference_AfterInvocation_ShouldFail() + => TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class C { string s = ((System.IFormattable)null).ToString("test", null)$$; } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind); - } + """, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind); [Fact] - public async Task ReorderMethodParameters_InvokeInMethodBody_ViaCommand() - { - var markup = """ + public Task ReorderMethodParameters_InvokeInMethodBody_ViaCommand() + => TestChangeSignatureViaCommandAsync( + LanguageNames.CSharp, """ using System; class MyClass { @@ -196,16 +168,11 @@ public void Goo(int x, string y) $$ } } - """; - - await TestChangeSignatureViaCommandAsync( - LanguageNames.CSharp, markup, expectedSuccess: false); - } + """, expectedSuccess: false); [Fact] - public async Task ReorderMethodParameters_InvokeInMethodBody_ViaSmartTag() - { - var markup = """ + public Task ReorderMethodParameters_InvokeInMethodBody_ViaSmartTag() + => TestMissingAsync(""" using System; class MyClass { @@ -214,15 +181,13 @@ public void Goo(int x, string y) [||] } } - """; - - await TestMissingAsync(markup); - } + """); [Fact] public async Task ReorderMethodParameters_InvokeOnReference_BeginningOfIdentifier() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class MyClass { @@ -235,9 +200,7 @@ public void Bar(int x, string y) { } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ using System; class MyClass { @@ -250,15 +213,14 @@ public void Bar(string y, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderMethodParameters_InvokeOnReference_ArgumentList() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class MyClass { @@ -271,9 +233,7 @@ public void Bar(int x, string y) { } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ using System; class MyClass { @@ -286,15 +246,14 @@ public void Bar(string y, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderMethodParameters_InvokeOnReference_NestedCalls1() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class MyClass { @@ -312,9 +271,7 @@ public int Baz(int x, string y) return 1; } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ using System; class MyClass { @@ -332,15 +289,14 @@ public int Baz(string y, int x) return 1; } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderMethodParameters_InvokeOnReference_NestedCalls2() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class MyClass { @@ -358,9 +314,7 @@ public int Baz(int x, string y) return 1; } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ using System; class MyClass { @@ -378,15 +332,14 @@ public int Baz(int x, string y) return 1; } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderMethodParameters_InvokeOnReference_NestedCalls3() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class MyClass { @@ -404,9 +357,7 @@ public int Baz(int x, string y) return 1; } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ using System; class MyClass { @@ -424,15 +375,14 @@ public int Baz(int x, string y) return 1; } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderMethodParameters_InvokeOnReference_Attribute() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; [$$My(1, 2)] @@ -442,9 +392,7 @@ public MyAttribute(int x, int y) { } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ using System; [My(2, 1)] @@ -454,39 +402,35 @@ public MyAttribute(int y, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderMethodParameters_InvokeOnReference_OnlyHasCandidateSymbols() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class Test { void M(int x, string y) { } void M(int x, double y) { } void M2() { $$M("s", 1); } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ class Test { void M(string y, int x) { } void M(int x, double y) { } void M2() { M(1, "s"); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderMethodParameters_InvokeOnReference_CallToOtherConstructor() { - var markup = """ + var permutation = new[] { 2, 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class Program { public Program(int x, int y) : this(1, 2, 3)$$ @@ -497,9 +441,7 @@ public Program(int x, int y, int z) { } } - """; - var permutation = new[] { 2, 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ class Program { public Program(int x, int y) : this(3, 2, 1) @@ -510,15 +452,14 @@ public Program(int z, int y, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderMethodParameters_InvokeOnReference_CallToBaseConstructor() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class B { public B(int a, int b) @@ -532,9 +473,7 @@ public D(int x, int y) : base(1, 2)$$ { } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ class B { public B(int b, int a) @@ -548,9 +487,7 @@ public D(int x, int y) : base(2, 1) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } #endregion @@ -560,7 +497,8 @@ public D(int x, int y) : base(2, 1) [Fact] public async Task ReorderIndexerParameters_InvokeAtBeginningOfDeclaration() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class Program { $$int this[int x, string y] @@ -569,9 +507,8 @@ class Program set { } } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, + expectedUpdatedInvocationDocumentCode: """ class Program { int this[string y, int x] @@ -580,16 +517,14 @@ class Program set { } } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, - expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); + """, expectedSelectedIndex: 0); } [Fact] public async Task ReorderIndexerParameters_InParameters() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class Program { int this[int x, $$string y] @@ -598,9 +533,8 @@ class Program set { } } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, + expectedUpdatedInvocationDocumentCode: """ class Program { int this[string y, int x] @@ -609,16 +543,14 @@ class Program set { } } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, - expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 1); + """, expectedSelectedIndex: 1); } [Fact] public async Task ReorderIndexerParameters_InvokeAtEndOfDeclaration() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class Program { int this[int x, string y]$$ @@ -627,9 +559,8 @@ class Program set { } } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, + expectedUpdatedInvocationDocumentCode: """ class Program { int this[string y, int x] @@ -638,16 +569,14 @@ class Program set { } } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, - expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); + """, expectedSelectedIndex: 0); } [Fact] public async Task ReorderIndexerParameters_InvokeInAccessor() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class Program { int this[int x, string y] @@ -656,9 +585,7 @@ class Program set { } } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ class Program { int this[string y, int x] @@ -667,15 +594,14 @@ class Program set { } } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderIndexerParameters_InvokeOnReference_BeforeTarget() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class Program { void M(Program p) @@ -689,9 +615,7 @@ void M(Program p) set { } } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ class Program { void M(Program p) @@ -705,15 +629,14 @@ void M(Program p) set { } } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderIndexerParameters_InvokeOnReference_InArgumentList() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class Program { void M(Program p) @@ -727,9 +650,8 @@ void M(Program p) set { } } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, + expectedUpdatedInvocationDocumentCode: """ class Program { void M(Program p) @@ -743,10 +665,7 @@ void M(Program p) set { } } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, - expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); + """, expectedSelectedIndex: 0); } #endregion @@ -756,7 +675,8 @@ await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSi [Fact] public async Task ReorderDelegateParameters_ObjectCreation1() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { void T() @@ -766,9 +686,8 @@ void T() public delegate void D(int x, int y); } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, + expectedUpdatedInvocationDocumentCode: """ public class C { void T() @@ -778,16 +697,14 @@ void T() public delegate void D(int y, int x); } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, - expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); + """, expectedSelectedIndex: 0); } [Fact] public async Task ReorderDelegateParameters_ObjectCreation2() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class CD { public delegate void D(T t, T u); @@ -799,9 +716,7 @@ public void M() var dele = new CD.$$D((int x, int y) => { }); } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class CD { public delegate void D(T u, T t); @@ -813,9 +728,7 @@ public void M() var dele = new CD.D((int y, int x) => { }); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } #endregion @@ -824,7 +737,8 @@ public void M() [Fact] public async Task ReorderMethodParameters_CodeRefactoring_InvokeBeforeMethodName() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCodeActionAsync(""" using System; class MyClass { @@ -832,9 +746,7 @@ class MyClass { } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, expectedCodeAction: true, updatedSignature: permutation, expectedCode: """ using System; class MyClass { @@ -842,14 +754,12 @@ public void Goo(string y, int x) { } } - """; - await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: true, updatedSignature: permutation, expectedCode: updatedCode); + """); } [Fact] - public async Task ReorderMethodParameters_CodeRefactoring_NotInMethodBody() - { - var markup = """ + public Task ReorderMethodParameters_CodeRefactoring_NotInMethodBody() + => TestChangeSignatureViaCodeActionAsync(""" using System; class MyClass { @@ -858,14 +768,13 @@ public void Goo(int x, string y) [||] } } - """; - await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); - } + """, expectedCodeAction: false); [Fact] public async Task ReorderMethodParameters_CodeRefactoring_InLambda() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCodeActionAsync(""" class Program { void M(int x) @@ -873,9 +782,7 @@ void M(int x) System.Func f = (a, b)[||] => { return a; }; } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, expectedCodeAction: true, updatedSignature: permutation, expectedCode: """ class Program { void M(int x) @@ -883,14 +790,12 @@ void M(int x) System.Func f = (b, a) => { return a; }; } } - """; - await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: true, updatedSignature: permutation, expectedCode: updatedCode); + """); } [Fact] - public async Task ReorderMethodParameters_CodeRefactoring_NotInLambdaBody() - { - var markup = """ + public Task ReorderMethodParameters_CodeRefactoring_NotInLambdaBody() + => TestChangeSignatureViaCodeActionAsync(""" class Program { void M(int x) @@ -898,14 +803,14 @@ void M(int x) System.Func f = (a, b) => { [||]return a; }; } } - """; - await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); - } + """, expectedCodeAction: false); [Fact] public async Task ReorderMethodParameters_CodeRefactoring_AtCallSite_ViaCommand() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync( + LanguageNames.CSharp, """ class Program { void M(int x, int y) @@ -913,9 +818,8 @@ void M(int x, int y) M($$5, 6); } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, + expectedUpdatedInvocationDocumentCode: """ class Program { void M(int y, int x) @@ -923,16 +827,12 @@ void M(int y, int x) M(6, 5); } } - """; - await TestChangeSignatureViaCommandAsync( - LanguageNames.CSharp, markup, updatedSignature: permutation, - expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] - public async Task ReorderMethodParameters_CodeRefactoring_AtCallSite_ViaCodeAction() - { - var markup = """ + public Task ReorderMethodParameters_CodeRefactoring_AtCallSite_ViaCodeAction() + => TestMissingAsync(""" class Program { void M(int x, int y) @@ -940,9 +840,7 @@ void M(int x, int y) M([||]5, 6); } } - """; - await TestMissingAsync(markup); - } + """); #endregion } diff --git a/src/EditorFeatures/CSharpTest/ChangeSignature/ReorderParametersTests.cs b/src/EditorFeatures/CSharpTest/ChangeSignature/ReorderParametersTests.cs index 8309d88cd1725..d48ee0dc38026 100644 --- a/src/EditorFeatures/CSharpTest/ChangeSignature/ReorderParametersTests.cs +++ b/src/EditorFeatures/CSharpTest/ChangeSignature/ReorderParametersTests.cs @@ -18,7 +18,8 @@ public sealed partial class ChangeSignatureTests : AbstractChangeSignatureTests [Fact] public async Task ReorderLocalFunctionParametersAndArguments_OnDeclaration() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class MyClass { @@ -30,9 +31,7 @@ public void M() } } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ using System; class MyClass { @@ -44,15 +43,14 @@ void Goo(string y, int x) } } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderLocalFunctionParametersAndArguments_OnInvocation() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class MyClass { @@ -64,9 +62,7 @@ void Goo(int x, string y) } } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ using System; class MyClass { @@ -78,15 +74,14 @@ void Goo(string y, int x) } } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderMethodParameters() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class MyClass { @@ -94,9 +89,7 @@ class MyClass { } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ using System; class MyClass { @@ -104,15 +97,14 @@ public void Goo(string y, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderMethodParametersAndArguments() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class MyClass { @@ -121,9 +113,7 @@ class MyClass Goo(3, "hello"); } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ using System; class MyClass { @@ -132,15 +122,14 @@ public void Goo(string y, int x) Goo("hello", 3); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderMethodParametersAndArgumentsOfNestedCalls() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class MyClass { @@ -149,9 +138,7 @@ class MyClass return Goo(Goo(4, "inner"), "outer"); } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ using System; class MyClass { @@ -160,15 +147,14 @@ public int Goo(string y, int x) return Goo("outer", Goo("inner", 4)); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderConstructorParametersAndArguments() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class MyClass2 : MyClass @@ -189,9 +175,7 @@ public MyClass() : this(2, "test") var t = new MyClass(x, y); } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ using System; class MyClass2 : MyClass @@ -212,15 +196,14 @@ public MyClass(string y, int x) var t = new MyClass(y, x); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44126")] public async Task ReorderConstructorParametersAndArguments_ImplicitObjectCreation() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ using System; class MyClass2 : MyClass @@ -241,9 +224,7 @@ public MyClass(int x, string y) MyClass t = new$$(x, y); } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ using System; class MyClass2 : MyClass @@ -264,15 +245,14 @@ public MyClass(string y, int x) MyClass t = new(y, x); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderAttributeConstructorParametersAndArguments() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ [My("test", 8)] class MyClass { @@ -284,9 +264,7 @@ public MyAttribute(string x, int y)$$ { } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ [My(8, "test")] class MyClass { @@ -298,15 +276,17 @@ public MyAttribute(int y, string x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderExtensionMethodParametersAndArguments_StaticCall() { - var markup = """ + var permutation = new[] { 0, 2, 1, 5, 4, 3 }; + + // Although the `ParameterConfig` has 0 for the `SelectedIndex`, the UI dialog will make an adjustment + // and select parameter `y` instead because the `this` parameter cannot be moved or removed. + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { static void Main(string[] args) @@ -320,9 +300,8 @@ public static class CExt public static void M(this $$C goo, int x, int y, string a = "test_a", string b = "test_b", string c = "test_c") { } } - """; - var permutation = new[] { 0, 2, 1, 5, 4, 3 }; - var updatedCode = """ + """, updatedSignature: permutation, + expectedUpdatedInvocationDocumentCode: """ public class C { static void Main(string[] args) @@ -336,18 +315,14 @@ public static class CExt public static void M(this C goo, int y, int x, string c = "test_c", string b = "test_b", string a = "test_a") { } } - """; - - // Although the `ParameterConfig` has 0 for the `SelectedIndex`, the UI dialog will make an adjustment - // and select parameter `y` instead because the `this` parameter cannot be moved or removed. - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, - expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); + """, expectedSelectedIndex: 0); } [Fact] public async Task ReorderExtensionMethodParametersAndArguments_ExtensionCall() { - var markup = """ + var permutation = new[] { 0, 2, 1, 5, 4, 3 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { static void Main(string[] args) @@ -361,9 +336,8 @@ public static class CExt public static void M(this C goo, int x$$, int y, string a = "test_a", string b = "test_b", string c = "test_c") { } } - """; - var permutation = new[] { 0, 2, 1, 5, 4, 3 }; - var updatedCode = """ + """, updatedSignature: permutation, + expectedUpdatedInvocationDocumentCode: """ public class C { static void Main(string[] args) @@ -377,16 +351,14 @@ public static class CExt public static void M(this C goo, int y, int x, string c = "test_c", string b = "test_b", string a = "test_a") { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, - expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 1); + """, expectedSelectedIndex: 1); } [Fact] public async Task ReorderParamsMethodParametersAndArguments_ParamsAsArray() { - var markup = """ + var permutation = new[] { 1, 0, 2 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { void $$M(int x, int y, params int[] p) @@ -394,9 +366,7 @@ public class C M(x, y, new[] { 1, 2, 3 }); } } - """; - var permutation = new[] { 1, 0, 2 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { void M(int y, int x, params int[] p) @@ -404,15 +374,14 @@ void M(int y, int x, params int[] p) M(y, x, new[] { 1, 2, 3 }); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParamsMethodParametersAndArguments_ParamsExpanded() { - var markup = """ + var permutation = new[] { 1, 0, 2 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { void $$M(int x, int y, params int[] p) @@ -420,9 +389,7 @@ public class C M(x, y, 1, 2, 3); } } - """; - var permutation = new[] { 1, 0, 2 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { void M(int y, int x, params int[] p) @@ -430,15 +397,14 @@ void M(int y, int x, params int[] p) M(y, x, 1, 2, 3); } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderExtensionAndParamsMethodParametersAndArguments_VariedCallsites() { - var markup = """ + var permutation = new[] { 0, 2, 1, 5, 4, 3, 6 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { static void Main(string[] args) @@ -455,9 +421,8 @@ public static class CExt public static void $$M(this C goo, int x, int y, string a = "test_a", string b = "test_b", string c = "test_c", params int[] p) { } } - """; - var permutation = new[] { 0, 2, 1, 5, 4, 3, 6 }; - var updatedCode = """ + """, updatedSignature: permutation, + expectedUpdatedInvocationDocumentCode: """ public class C { static void Main(string[] args) @@ -474,16 +439,14 @@ public static class CExt public static void M(this C goo, int y, int x, string c = "test_c", string b = "test_b", string a = "test_a", params int[] p) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, - expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); + """, expectedSelectedIndex: 0); } [Fact] public async Task ReorderIndexerParametersAndArguments() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class Program { void M() @@ -498,9 +461,7 @@ void M() set { } } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ class Program { void M() @@ -515,15 +476,14 @@ void M() set { } } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParamTagsInDocComments_SingleLineDocComments_OnIndividualLines() { - var markup = """ + var permutation = new[] { 2, 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { /// @@ -534,9 +494,7 @@ public class C } } - """; - var permutation = new[] { 2, 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { /// @@ -547,15 +505,14 @@ void Goo(int c, int b, int a) } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParamTagsInDocComments_SingleLineDocComments_OnSameLine() { - var markup = """ + var permutation = new[] { 2, 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { /// a is funb is func is fun @@ -564,9 +521,7 @@ public class C } } - """; - var permutation = new[] { 2, 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { /// c is funb is funa is fun @@ -575,15 +530,14 @@ void Goo(int c, int b, int a) } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParamTagsInDocComments_SingleLineDocComments_MixedLineDistribution() { - var markup = """ + var permutation = new[] { 5, 4, 3, 2, 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { /// @@ -597,9 +551,7 @@ public class C } } - """; - var permutation = new[] { 5, 4, 3, 2, 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { /// Comments spread @@ -613,15 +565,14 @@ void Goo(int f, int e, int d, int c, int b, int a) } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParamTagsInDocComments_SingleLineDocComments_MixedWithRegularComments() { - var markup = """ + var permutation = new[] { 4, 3, 2, 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { /// @@ -632,9 +583,7 @@ public class C } } - """; - var permutation = new[] { 4, 3, 2, 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { /// @@ -645,15 +594,14 @@ void Goo(int e, int d, int c, int b, int a) } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParamTagsInDocComments_MultiLineDocComments_OnSeparateLines1() { - var markup = """ + var permutation = new[] { 2, 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class Program { /** @@ -665,9 +613,7 @@ class Program { } } - """; - var permutation = new[] { 2, 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ class Program { /** @@ -679,15 +625,14 @@ static void M(int z, int y, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParamTagsInDocComments_MultiLineDocComments_OnSingleLine() { - var markup = """ + var permutation = new[] { 2, 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class Program { /** x!y!z! */ @@ -695,9 +640,7 @@ class Program { } } - """; - var permutation = new[] { 2, 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ class Program { /** z!y!x! */ @@ -705,15 +648,14 @@ static void M(int z, int y, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParamTagsInDocComments_IncorrectOrder_MaintainsOrder() { - var markup = """ + var permutation = new[] { 2, 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { /// @@ -724,9 +666,7 @@ public class C } } - """; - var permutation = new[] { 2, 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { /// @@ -737,14 +677,14 @@ void Goo(int c, int b, int a) } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParamTagsInDocComments_WrongNames_MaintainsOrder() { - var markup = """ + var permutation = new[] { 2, 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { /// @@ -755,9 +695,7 @@ public class C } } - """; - var permutation = new[] { 2, 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { /// @@ -768,14 +706,14 @@ void Goo(int c, int b, int a) } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParamTagsInDocComments_InsufficientTags_MaintainsOrder() { - var markup = """ + var permutation = new[] { 2, 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { /// @@ -785,9 +723,7 @@ public class C } } - """; - var permutation = new[] { 2, 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { /// @@ -797,14 +733,14 @@ void Goo(int c, int b, int a) } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParamTagsInDocComments_ExcessiveTags_MaintainsOrder() { - var markup = """ + var permutation = new[] { 2, 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { /// @@ -816,9 +752,7 @@ public class C } } - """; - var permutation = new[] { 2, 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { /// @@ -830,14 +764,14 @@ void Goo(int c, int b, int a) } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParamTagsInDocComments_OnConstructors() { - var markup = """ + var permutation = new[] { 2, 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { /// @@ -848,9 +782,7 @@ public class C } } - """; - var permutation = new[] { 2, 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { /// @@ -861,14 +793,14 @@ public C(int c, int b, int a) } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParamTagsInDocComments_OnIndexers() { - var markup = """ + var permutation = new[] { 2, 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ public class C { /// @@ -880,9 +812,7 @@ public class C set { } } } - """; - var permutation = new[] { 2, 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ public class C { /// @@ -894,14 +824,14 @@ public class C set { } } } - """; - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParametersInCrefs() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ class C { /// @@ -910,9 +840,7 @@ class C $$void M(int x, string y) { } } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ class C { /// @@ -921,15 +849,14 @@ class C void M(string y, int x) { } } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParametersInMethodThatImplementsInterfaceMethodOnlyThroughADerivedType1() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ interface I { $$void M(int x, string y); @@ -945,9 +872,7 @@ public void M(int x, string y) class D : C, I { } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ interface I { void M(string y, int x); @@ -963,15 +888,14 @@ public void M(string y, int x) class D : C, I { } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParametersInMethodThatImplementsInterfaceMethodOnlyThroughADerivedType2() { - var markup = """ + var permutation = new[] { 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ interface I { void M(int x, string y); @@ -987,9 +911,7 @@ class C class D : C, I { } - """; - var permutation = new[] { 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ interface I { void M(string y, int x); @@ -1005,15 +927,14 @@ public void M(string y, int x) class D : C, I { } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParamTagsInDocComments_Record() { - var markup = """ + var permutation = new[] { 2, 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ /// /// /// @@ -1021,9 +942,7 @@ record $$R(int A, int B, int C) { public static R Instance = new(0, 1, 2); } - """; - var permutation = new[] { 2, 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ /// /// /// @@ -1031,15 +950,14 @@ record R(int C, int B, int A) { public static R Instance = new(2, 1, 0); } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParamTagsInDocComments_PrimaryConstructor_Class() { - var markup = """ + var permutation = new[] { 2, 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ /// /// /// @@ -1047,9 +965,7 @@ class $$R(int A, int B, int C) { public static R Instance = new(0, 1, 2); } - """; - var permutation = new[] { 2, 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ /// /// /// @@ -1057,15 +973,14 @@ class R(int C, int B, int A) { public static R Instance = new(2, 1, 0); } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } [Fact] public async Task ReorderParamTagsInDocComments_PrimaryConstructor_Struct() { - var markup = """ + var permutation = new[] { 2, 1, 0 }; + await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, """ /// /// /// @@ -1073,9 +988,7 @@ struct $$R(int A, int B, int C) { public static R Instance = new(0, 1, 2); } - """; - var permutation = new[] { 2, 1, 0 }; - var updatedCode = """ + """, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: """ /// /// /// @@ -1083,8 +996,6 @@ struct R(int C, int B, int A) { public static R Instance = new(2, 1, 0); } - """; - - await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); + """); } } diff --git a/src/EditorFeatures/CSharpTest/Classification/SemanticClassifierTests.cs b/src/EditorFeatures/CSharpTest/Classification/SemanticClassifierTests.cs index 2884b7a147c0f..32d91769db568 100644 --- a/src/EditorFeatures/CSharpTest/Classification/SemanticClassifierTests.cs +++ b/src/EditorFeatures/CSharpTest/Classification/SemanticClassifierTests.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; -using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; @@ -11,7 +10,6 @@ using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Editor.UnitTests; -using Microsoft.CodeAnalysis.Editor.UnitTests.Classification; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Shared.Extensions; @@ -22,7 +20,6 @@ using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Threading; using Roslyn.Test.Utilities; -using Roslyn.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications; @@ -41,47 +38,39 @@ protected override async Task> GetClassificationS } [Theory, CombinatorialData] - public async Task GenericClassDeclaration(TestHost testHost) - { - await TestInMethodAsync( + public Task GenericClassDeclaration(TestHost testHost) + => TestInMethodAsync( className: "Class", methodName: "M", @"new Class();", testHost, Class("Class")); - } [Theory, CombinatorialData] - public async Task RefVar(TestHost testHost) - { - await TestInMethodAsync( + public Task RefVar(TestHost testHost) + => TestInMethodAsync( @"int i = 0; ref var x = ref i;", testHost, Classifications(Keyword("var"), Local("i"))); - } [Theory, CombinatorialData] - public async Task UsingAlias1(TestHost testHost) - { - await TestAsync( + public Task UsingAlias1(TestHost testHost) + => TestAsync( @"using M = System.Math;", testHost, Class("M"), Namespace("System"), Class("Math"), Static("Math")); - } [Theory, CombinatorialData] - public async Task DynamicAsTypeArgument(TestHost testHost) - { - await TestInMethodAsync( + public Task DynamicAsTypeArgument(TestHost testHost) + => TestInMethodAsync( className: "Class", methodName: "M", @"new Class();", testHost, Classifications(Class("Class"), Keyword("dynamic"))); - } [Theory, CombinatorialData] public async Task UsingTypeAliases(TestHost testHost) @@ -103,9 +92,8 @@ await TestAsync(code, } [Theory, CombinatorialData] - public async Task DynamicTypeAlias(TestHost testHost) - { - await TestAsync( + public Task DynamicTypeAlias(TestHost testHost) + => TestAsync( """ using dynamic = System.EventArgs; @@ -120,12 +108,10 @@ class C Class("EventArgs"), Class("dynamic"), Class("dynamic")); - } [Theory, CombinatorialData] - public async Task DynamicAsDelegateName(TestHost testHost) - { - await TestAsync( + public Task DynamicAsDelegateName(TestHost testHost) + => TestAsync( """ delegate void dynamic(); @@ -139,12 +125,10 @@ void M() """, testHost, Delegate("dynamic")); - } [Theory, CombinatorialData] - public async Task DynamicAsInterfaceName(TestHost testHost) - { - await TestAsync( + public Task DynamicAsInterfaceName(TestHost testHost) + => TestAsync( """ interface dynamic { @@ -157,12 +141,10 @@ class C """, testHost, Interface("dynamic")); - } [Theory, CombinatorialData] - public async Task DynamicAsEnumName(TestHost testHost) - { - await TestAsync( + public Task DynamicAsEnumName(TestHost testHost) + => TestAsync( """ enum dynamic { @@ -175,12 +157,10 @@ class C """, testHost, Enum("dynamic")); - } [Theory, CombinatorialData] - public async Task DynamicAsClassName(TestHost testHost) - { - await TestAsync( + public Task DynamicAsClassName(TestHost testHost) + => TestAsync( """ class dynamic { @@ -193,13 +173,11 @@ class C """, testHost, Class("dynamic")); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/46985")] - public async Task DynamicAsRecordName(TestHost testHost) - { - await TestAsync( + public Task DynamicAsRecordName(TestHost testHost) + => TestAsync( """ record dynamic { @@ -212,12 +190,10 @@ class C """, testHost, RecordClass("dynamic")); - } [Theory, CombinatorialData] - public async Task DynamicAsClassNameAndLocalVariableName(TestHost testHost) - { - await TestAsync( + public Task DynamicAsClassNameAndLocalVariableName(TestHost testHost) + => TestAsync( """ class dynamic { @@ -229,12 +205,10 @@ class dynamic """, testHost, Class("dynamic")); - } [Theory, CombinatorialData] - public async Task DynamicAsStructName(TestHost testHost) - { - await TestAsync( + public Task DynamicAsStructName(TestHost testHost) + => TestAsync( """ struct dynamic { @@ -247,12 +221,10 @@ class C """, testHost, Struct("dynamic")); - } [Theory, CombinatorialData] - public async Task DynamicAsGenericClassName(TestHost testHost) - { - await TestAsync( + public Task DynamicAsGenericClassName(TestHost testHost) + => TestAsync( """ class dynamic { @@ -265,12 +237,10 @@ class C """, testHost, Class("dynamic")); - } [Theory, CombinatorialData] - public async Task DynamicAsGenericClassNameButOtherArity(TestHost testHost) - { - await TestAsync( + public Task DynamicAsGenericClassNameButOtherArity(TestHost testHost) + => TestAsync( """ class dynamic { @@ -283,12 +253,10 @@ class C """, testHost, Keyword("dynamic")); - } [Theory, CombinatorialData] - public async Task DynamicAsUndefinedGenericType(TestHost testHost) - { - await TestAsync( + public Task DynamicAsUndefinedGenericType(TestHost testHost) + => TestAsync( """ class dynamic { @@ -301,12 +269,10 @@ class C """, testHost, Class("dynamic")); - } [Theory, CombinatorialData] - public async Task DynamicAsExternAlias(TestHost testHost) - { - await TestAsync( + public Task DynamicAsExternAlias(TestHost testHost) + => TestAsync( """ extern alias dynamic; @@ -317,12 +283,10 @@ class C """, testHost, Namespace("dynamic")); - } [Theory, CombinatorialData] - public async Task GenericClassNameButOtherArity(TestHost testHost) - { - await TestAsync( + public Task GenericClassNameButOtherArity(TestHost testHost) + => TestAsync( """ class A { @@ -334,12 +298,10 @@ class C } """, testHost, Class("A")); - } [Theory, CombinatorialData] - public async Task GenericTypeParameter(TestHost testHost) - { - await TestAsync( + public Task GenericTypeParameter(TestHost testHost) + => TestAsync( """ class C { @@ -350,12 +312,10 @@ void M() """, testHost, TypeParameter("T")); - } [Theory, CombinatorialData] - public async Task GenericMethodTypeParameter(TestHost testHost) - { - await TestAsync( + public Task GenericMethodTypeParameter(TestHost testHost) + => TestAsync( """ class C { @@ -369,12 +329,10 @@ T M(T t) TypeParameter("T"), TypeParameter("T"), TypeParameter("T")); - } [Theory, CombinatorialData] - public async Task GenericMethodTypeParameterInLocalVariableDeclaration(TestHost testHost) - { - await TestAsync( + public Task GenericMethodTypeParameterInLocalVariableDeclaration(TestHost testHost) + => TestAsync( """ class C { @@ -386,12 +344,10 @@ void M() """, testHost, TypeParameter("T")); - } [Theory, CombinatorialData] - public async Task ParameterOfLambda1(TestHost testHost) - { - await TestAsync( + public Task ParameterOfLambda1(TestHost testHost) + => TestAsync( """ class C { @@ -404,12 +360,10 @@ class C """, testHost, Class("C")); - } [Theory, CombinatorialData] - public async Task ParameterOfAnonymousMethod(TestHost testHost) - { - await TestAsync( + public Task ParameterOfAnonymousMethod(TestHost testHost) + => TestAsync( """ class C { @@ -422,12 +376,10 @@ class C """, testHost, Class("C")); - } [Theory, CombinatorialData] - public async Task GenericTypeParameterAfterWhere(TestHost testHost) - { - await TestAsync( + public Task GenericTypeParameterAfterWhere(TestHost testHost) + => TestAsync( """ class C where A : B { @@ -436,12 +388,10 @@ class C where A : B testHost, TypeParameter("A"), TypeParameter("B")); - } [Theory, CombinatorialData] - public async Task BaseClass(TestHost testHost) - { - await TestAsync( + public Task BaseClass(TestHost testHost) + => TestAsync( """ class C { @@ -453,12 +403,10 @@ class C2 : C """, testHost, Class("C")); - } [Theory, CombinatorialData] - public async Task BaseInterfaceOnInterface(TestHost testHost) - { - await TestAsync( + public Task BaseInterfaceOnInterface(TestHost testHost) + => TestAsync( """ interface T { @@ -470,12 +418,10 @@ interface T2 : T """, testHost, Interface("T")); - } [Theory, CombinatorialData] - public async Task BaseInterfaceOnClass(TestHost testHost) - { - await TestAsync( + public Task BaseInterfaceOnClass(TestHost testHost) + => TestAsync( """ interface T { @@ -487,12 +433,10 @@ class T2 : T """, testHost, Interface("T")); - } [Theory, CombinatorialData] - public async Task InterfaceColorColor(TestHost testHost) - { - await TestAsync( + public Task InterfaceColorColor(TestHost testHost) + => TestAsync( """ interface T { @@ -506,12 +450,10 @@ class T2 : T testHost, Interface("T"), Interface("T")); - } [Theory, CombinatorialData] - public async Task DelegateColorColor(TestHost testHost) - { - await TestAsync( + public Task DelegateColorColor(TestHost testHost) + => TestAsync( """ delegate void T(); @@ -522,12 +464,10 @@ class T2 """, testHost, Delegate("T")); - } [Theory, CombinatorialData] - public async Task DelegateReturnsItself(TestHost testHost) - { - await TestAsync( + public Task DelegateReturnsItself(TestHost testHost) + => TestAsync( """ delegate T T(); @@ -540,12 +480,10 @@ class C Delegate("T"), Delegate("T"), Delegate("T")); - } [Theory, CombinatorialData] - public async Task StructColorColor(TestHost testHost) - { - await TestAsync( + public Task StructColorColor(TestHost testHost) + => TestAsync( """ struct T { @@ -554,12 +492,10 @@ struct T """, testHost, Struct("T")); - } [Theory, CombinatorialData] - public async Task EnumColorColor(TestHost testHost) - { - await TestAsync( + public Task EnumColorColor(TestHost testHost) + => TestAsync( """ enum T { @@ -574,12 +510,10 @@ class C """, testHost, Enum("T")); - } [Theory, CombinatorialData] - public async Task DynamicAsGenericTypeParameter(TestHost testHost) - { - await TestAsync( + public Task DynamicAsGenericTypeParameter(TestHost testHost) + => TestAsync( """ class C { @@ -588,12 +522,10 @@ class C """, testHost, TypeParameter("dynamic")); - } [Theory, CombinatorialData] - public async Task DynamicAsGenericFieldName(TestHost testHost) - { - await TestAsync( + public Task DynamicAsGenericFieldName(TestHost testHost) + => TestAsync( """ class A { @@ -602,12 +534,10 @@ class A """, testHost, TypeParameter("T")); - } [Theory, CombinatorialData] - public async Task PropertySameNameAsClass(TestHost testHost) - { - await TestAsync( + public Task PropertySameNameAsClass(TestHost testHost) + => TestAsync( """ class N { @@ -629,12 +559,10 @@ void M() Local("n"), Property("N"), Property("N")); - } [Theory, CombinatorialData] - public async Task AttributeWithoutAttributeSuffix(TestHost testHost) - { - await TestAsync( + public Task AttributeWithoutAttributeSuffix(TestHost testHost) + => TestAsync( """ using System; @@ -647,12 +575,10 @@ class C Namespace("System"), Class("Obsolete"), Obsolete("C")); - } [Theory, CombinatorialData] - public async Task AttributeOnNonExistingMember(TestHost testHost) - { - await TestAsync( + public Task AttributeOnNonExistingMember(TestHost testHost) + => TestAsync( """ using System; @@ -664,12 +590,10 @@ class A testHost, Namespace("System"), Class("Obsolete")); - } [Theory, CombinatorialData] - public async Task AttributeWithoutAttributeSuffixOnAssembly(TestHost testHost) - { - await TestAsync( + public Task AttributeWithoutAttributeSuffixOnAssembly(TestHost testHost) + => TestAsync( """ using System; @@ -683,12 +607,10 @@ class MyAttribute : Attribute Namespace("System"), Class("My"), Class("Attribute")); - } [Theory, CombinatorialData] - public async Task AttributeViaNestedClassOrDerivedClass(TestHost testHost) - { - await TestAsync( + public Task AttributeViaNestedClassOrDerivedClass(TestHost testHost) + => TestAsync( """ using System; @@ -713,12 +635,10 @@ class Derived : Base Class("My"), Class("Attribute"), Class("Base")); - } [Theory, CombinatorialData] - public async Task NamedAndOptional(TestHost testHost) - { - await TestAsync( + public Task NamedAndOptional(TestHost testHost) + => TestAsync( """ class C { @@ -736,38 +656,32 @@ void M() Class("C"), Method("B"), Parameter("C")); - } [Theory, CombinatorialData] - public async Task PartiallyWrittenGenericName1(TestHost testHost) - { - await TestInMethodAsync( + public Task PartiallyWrittenGenericName1(TestHost testHost) + => TestInMethodAsync( className: "Class", methodName: "M", @"Class TestInMethodAsync( className: "Class", methodName: "M", @"Class TestAsync( """ class Color { @@ -776,12 +690,10 @@ class Color """, testHost, Class("Color")); - } [Theory, CombinatorialData] - public async Task ColorColor2(TestHost testHost) - { - await TestAsync( + public Task ColorColor2(TestHost testHost) + => TestAsync( """ class T { @@ -798,12 +710,10 @@ class T Class("T"), Field("T"), Class("T")); - } [Theory, CombinatorialData] - public async Task ColorColor3(TestHost testHost) - { - await TestAsync( + public Task ColorColor3(TestHost testHost) + => TestAsync( """ class T { @@ -822,16 +732,14 @@ class T Class("T"), Field("T"), Method("M")); - } /// /// Instance field should be preferred to type /// §7.5.4.1 /// [Theory, CombinatorialData] - public async Task ColorColor4(TestHost testHost) - { - await TestAsync( + public Task ColorColor4(TestHost testHost) + => TestAsync( """ class T { @@ -847,16 +755,14 @@ void M() Class("T"), Field("T"), Field("T")); - } /// /// Type should be preferred to a static field /// §7.5.4.1 /// [Theory, CombinatorialData] - public async Task ColorColor5(TestHost testHost) - { - await TestAsync( + public Task ColorColor5(TestHost testHost) + => TestAsync( """ class T { @@ -873,15 +779,13 @@ void M() Class("T"), Field("T"), Static("T")); - } /// /// Needs to prefer the local /// [Theory, CombinatorialData] - public async Task ColorColor6(TestHost testHost) - { - await TestAsync( + public Task ColorColor6(TestHost testHost) + => TestAsync( """ class T { @@ -899,15 +803,13 @@ void M() Class("T"), Local("T"), Field("field")); - } /// /// Needs to prefer the type /// [Theory, CombinatorialData] - public async Task ColorColor7(TestHost testHost) - { - await TestAsync( + public Task ColorColor7(TestHost testHost) + => TestAsync( """ class T { @@ -926,12 +828,10 @@ void M() Class("T"), Field("field"), Static("field")); - } [Theory, CombinatorialData] - public async Task ColorColor8(TestHost testHost) - { - await TestAsync( + public Task ColorColor8(TestHost testHost) + => TestAsync( """ class T { @@ -952,12 +852,10 @@ void M2() Class("T"), Method("M"), Local("T")); - } [Theory, CombinatorialData] - public async Task ColorColor9(TestHost testHost) - { - await TestAsync( + public Task ColorColor9(TestHost testHost) + => TestAsync( """ class T { @@ -974,13 +872,10 @@ T M(T T) Parameter("T"), Class("T"), Parameter("T")); - } [Theory, CombinatorialData] - public async Task ColorColor10(TestHost testHost) - { - // note: 'var' now binds to the type of the local. - await TestAsync( + public Task ColorColor10(TestHost testHost) + => TestAsync( """ class T { @@ -996,12 +891,10 @@ void M() Class("T"), Local("T"), Class("T")); - } [Theory, CombinatorialData] - public async Task ColorColor11(TestHost testHost) - { - await TestAsync( + public Task ColorColor11(TestHost testHost) + => TestAsync( """ class T { @@ -1016,12 +909,10 @@ void M() Keyword("var"), Local("T"), Class("T")); - } [Theory, CombinatorialData] - public async Task ColorColor12(TestHost testHost) - { - await TestAsync( + public Task ColorColor12(TestHost testHost) + => TestAsync( """ class T { @@ -1037,12 +928,10 @@ void M() Class("T"), Keyword("var"), Class("T")); - } [Theory, CombinatorialData] - public async Task ColorColor13(TestHost testHost) - { - await TestAsync( + public Task ColorColor13(TestHost testHost) + => TestAsync( """ class T { @@ -1058,12 +947,10 @@ void M() Class("T"), Class("T"), Class("T")); - } [Theory, CombinatorialData] - public async Task ColorColor14(TestHost testHost) - { - await TestAsync( + public Task ColorColor14(TestHost testHost) + => TestAsync( """ class T { @@ -1079,12 +966,10 @@ void M() Class("T"), Class("T"), Local("T")); - } [Theory, CombinatorialData] - public async Task NamespaceNameSameAsTypeName1(TestHost testHost) - { - await TestAsync( + public Task NamespaceNameSameAsTypeName1(TestHost testHost) + => TestAsync( """ namespace T { @@ -1101,12 +986,10 @@ void M() Namespace("T"), Class("T"), Class("T")); - } [Theory, CombinatorialData] - public async Task NamespaceNameSameAsTypeNameWithGlobal(TestHost testHost) - { - await TestAsync( + public Task NamespaceNameSameAsTypeNameWithGlobal(TestHost testHost) + => TestAsync( """ namespace T { @@ -1125,12 +1008,10 @@ void M() Class("T"), Namespace("T"), Class("T")); - } [Theory, CombinatorialData] - public async Task AmbiguityTypeAsGenericMethodArgumentVsLocal(TestHost testHost) - { - await TestAsync( + public Task AmbiguityTypeAsGenericMethodArgumentVsLocal(TestHost testHost) + => TestAsync( """ class T { @@ -1145,12 +1026,10 @@ void M() TypeParameter("T"), Method("M"), TypeParameter("T")); - } [Theory, CombinatorialData] - public async Task AmbiguityTypeAsGenericArgumentVsLocal(TestHost testHost) - { - await TestAsync( + public Task AmbiguityTypeAsGenericArgumentVsLocal(TestHost testHost) + => TestAsync( """ class T { @@ -1171,12 +1050,10 @@ void M() Class("T"), Class("G"), Class("T")); - } [Theory, CombinatorialData] - public async Task AmbiguityTypeAsGenericArgumentVsField(TestHost testHost) - { - await TestAsync( + public Task AmbiguityTypeAsGenericArgumentVsField(TestHost testHost) + => TestAsync( """ class T { @@ -1198,15 +1075,13 @@ void M() Class("T"), Field("f"), Static("f")); - } /// /// §7.5.4.2 /// [Theory, CombinatorialData] - public async Task GrammarAmbiguity_7_5_4_2(TestHost testHost) - { - await TestAsync( + public Task GrammarAmbiguity_7_5_4_2(TestHost testHost) + => TestAsync( """ class M { @@ -1240,12 +1115,10 @@ class B Method("G"), Class("A"), Class("B")); - } [Theory, CombinatorialData] - public async Task AnonymousTypePropertyName(TestHost testHost) - { - await TestAsync( + public Task AnonymousTypePropertyName(TestHost testHost) + => TestAsync( """ using System; @@ -1259,12 +1132,10 @@ void M() Namespace("System"), Keyword("var"), Property("String")); - } [Theory, CombinatorialData] - public async Task YieldAsATypeName(TestHost testHost) - { - await TestAsync( + public Task YieldAsATypeName(TestHost testHost) + => TestAsync( """ using System.Collections.Generic; @@ -1286,12 +1157,10 @@ IEnumerable M() Class("yield"), Class("yield"), Local("yield")); - } [Theory, CombinatorialData] - public async Task TypeNameDottedNames(TestHost testHost) - { - await TestAsync( + public Task TypeNameDottedNames(TestHost testHost) + => TestAsync( """ class C { @@ -1305,12 +1174,10 @@ class Nested testHost, Class("C"), Class("Nested")); - } [Theory, CombinatorialData] - public async Task BindingTypeNameFromBCLViaGlobalAlias(TestHost testHost) - { - await TestAsync( + public Task BindingTypeNameFromBCLViaGlobalAlias(TestHost testHost) + => TestAsync( """ using System; @@ -1323,7 +1190,6 @@ class C Namespace("System"), Namespace("System"), Class("String")); - } [Theory, CombinatorialData] public async Task BindingTypeNames(TestHost testHost) @@ -1364,9 +1230,8 @@ await TestAsync(code, } [Theory, CombinatorialData] - public async Task Constructors(TestHost testHost) - { - await TestAsync( + public Task Constructors(TestHost testHost) + => TestAsync( """ struct S { @@ -1394,12 +1259,10 @@ public C() Struct("S"), Keyword("var"), Class("C")); - } [Theory, CombinatorialData] - public async Task TypesOfClassMembers(TestHost testHost) - { - await TestAsync( + public Task TypesOfClassMembers(TestHost testHost) + => TestAsync( """ class Type { @@ -1458,15 +1321,13 @@ static operator Type(int other) Class("Type"), Class("Type"), Class("Type")); - } /// /// NAQ = Namespace Alias Qualifier (?) /// [Theory, CombinatorialData] - public async Task NAQTypeNameCtor(TestHost testHost) - { - await TestInMethodAsync( + public Task NAQTypeNameCtor(TestHost testHost) + => TestInMethodAsync( @"System.IO.BufferedStream b = new global::System.IO.BufferedStream();", testHost, Namespace("System"), @@ -1475,12 +1336,10 @@ await TestInMethodAsync( Namespace("System"), Namespace("IO"), Class("BufferedStream")); - } [Theory, CombinatorialData] - public async Task NAQEnum(TestHost testHost) - { - await TestAsync( + public Task NAQEnum(TestHost testHost) + => TestAsync( """ class C { @@ -1494,12 +1353,10 @@ void M() Namespace("System"), Namespace("IO"), Enum("DriveType")); - } [Theory, CombinatorialData] - public async Task NAQDelegate(TestHost testHost) - { - await TestAsync( + public Task NAQDelegate(TestHost testHost) + => TestAsync( """ class C { @@ -1512,22 +1369,18 @@ void M() testHost, Namespace("System"), Delegate("AssemblyLoadEventHandler")); - } [Theory, CombinatorialData] - public async Task NAQTypeNameMethodCall(TestHost testHost) - { - await TestInMethodAsync(@"global::System.String.Clone("");", + public Task NAQTypeNameMethodCall(TestHost testHost) + => TestInMethodAsync(@"global::System.String.Clone("");", testHost, Namespace("System"), Class("String"), Method("Clone")); - } [Theory, CombinatorialData] - public async Task NAQEventSubscription(TestHost testHost) - { - await TestInMethodAsync( + public Task NAQEventSubscription(TestHost testHost) + => TestInMethodAsync( """ global::System.AppDomain.CurrentDomain.AssemblyLoad += delegate (object sender, System.AssemblyLoadEventArgs args) {}; @@ -1540,12 +1393,10 @@ await TestInMethodAsync( Event("AssemblyLoad"), Namespace("System"), Class("AssemblyLoadEventArgs")); - } [Theory, CombinatorialData] - public async Task AnonymousDelegateParameterType(TestHost testHost) - { - await TestAsync( + public Task AnonymousDelegateParameterType(TestHost testHost) + => TestAsync( """ class C { @@ -1563,12 +1414,10 @@ void M() Class("EventArgs"), Namespace("System"), Class("EventArgs")); - } [Theory, CombinatorialData] - public async Task NAQCtor(TestHost testHost) - { - await TestInMethodAsync( + public Task NAQCtor(TestHost testHost) + => TestInMethodAsync( @"global::System.Collections.DictionaryEntry de = new global::System.Collections.DictionaryEntry();", testHost, Namespace("System"), @@ -1577,39 +1426,29 @@ await TestInMethodAsync( Namespace("System"), Namespace("Collections"), Struct("DictionaryEntry")); - } [Theory, CombinatorialData] - public async Task NAQSameFileClass(TestHost testHost) - { - var code = @"class C { static void M() { global::C.M(); } }"; - - await TestAsync(code, + public Task NAQSameFileClass(TestHost testHost) + => TestAsync(@"class C { static void M() { global::C.M(); } }", testHost, ParseOptions(Options.Regular), Class("C"), Method("M"), Static("M")); - } [Theory, CombinatorialData] - public async Task InteractiveNAQSameFileClass(TestHost testHost) - { - var code = @"class C { static void M() { global::Script.C.M(); } }"; - - await TestAsync(code, + public Task InteractiveNAQSameFileClass(TestHost testHost) + => TestAsync(@"class C { static void M() { global::Script.C.M(); } }", testHost, ParseOptions(Options.Script), Class("Script"), Class("C"), Method("M"), Static("M")); - } [Theory, CombinatorialData] - public async Task NAQSameFileClassWithNamespace(TestHost testHost) - { - await TestAsync( + public Task NAQSameFileClassWithNamespace(TestHost testHost) + => TestAsync( """ using @global = N; @@ -1632,12 +1471,10 @@ static void M() Class("C"), Method("M"), Static("M")); - } [Theory, CombinatorialData] - public async Task NAQSameFileClassWithNamespaceAndEscapedKeyword(TestHost testHost) - { - await TestAsync( + public Task NAQSameFileClassWithNamespaceAndEscapedKeyword(TestHost testHost) + => TestAsync( """ using @global = N; @@ -1660,12 +1497,10 @@ static void M() Class("C"), Method("M"), Static("M")); - } [Theory, CombinatorialData] - public async Task NAQGlobalWarning(TestHost testHost) - { - await TestAsync( + public Task NAQGlobalWarning(TestHost testHost) + => TestAsync( """ using global = N; @@ -1688,12 +1523,10 @@ static void M() Class("C"), Method("M"), Static("M")); - } [Theory, CombinatorialData] - public async Task NAQUserDefinedNAQNamespace(TestHost testHost) - { - await TestAsync( + public Task NAQUserDefinedNAQNamespace(TestHost testHost) + => TestAsync( """ using goo = N; @@ -1716,12 +1549,10 @@ static void M() Class("C"), Method("M"), Static("M")); - } [Theory, CombinatorialData] - public async Task NAQUserDefinedNAQNamespaceDoubleColon(TestHost testHost) - { - await TestAsync( + public Task NAQUserDefinedNAQNamespaceDoubleColon(TestHost testHost) + => TestAsync( """ using goo = N; @@ -1744,12 +1575,10 @@ static void M() Class("C"), Method("M"), Static("M")); - } [Theory, CombinatorialData] - public async Task NAQUserDefinedNamespace1(TestHost testHost) - { - await TestAsync( + public Task NAQUserDefinedNamespace1(TestHost testHost) + => TestAsync( """ class C { @@ -1775,12 +1604,10 @@ class D Class("D"), Namespace("A"), Namespace("B")); - } [Theory, CombinatorialData] - public async Task NAQUserDefinedNamespaceWithGlobal(TestHost testHost) - { - await TestAsync( + public Task NAQUserDefinedNamespaceWithGlobal(TestHost testHost) + => TestAsync( """ class C { @@ -1806,12 +1633,10 @@ class D Class("D"), Namespace("A"), Namespace("B")); - } [Theory, CombinatorialData] - public async Task NAQUserDefinedNAQForClass(TestHost testHost) - { - await TestAsync( + public Task NAQUserDefinedNAQForClass(TestHost testHost) + => TestAsync( """ using IO = global::System.IO; @@ -1829,12 +1654,10 @@ void M() Namespace("IO"), Namespace("IO"), Class("BinaryReader")); - } [Theory, CombinatorialData] - public async Task NAQUserDefinedTypes(TestHost testHost) - { - await TestAsync( + public Task NAQUserDefinedTypes(TestHost testHost) + => TestAsync( """ using rabbit = MyNameSpace; @@ -1919,12 +1742,10 @@ enum MyEnum Namespace("MyNameSpace"), Namespace("OtherNamespace"), Delegate("MyDelegate")); - } [Theory, CombinatorialData] - public async Task PreferPropertyOverNestedClass(TestHost testHost) - { - await TestAsync( + public Task PreferPropertyOverNestedClass(TestHost testHost) + => TestAsync( """ class Outer { @@ -1948,12 +1769,10 @@ void M() Class("A"), Local("a"), Field("B")); - } [Theory, CombinatorialData] - public async Task TypeNameInsideNestedClass(TestHost testHost) - { - await TestAsync( + public Task TypeNameInsideNestedClass(TestHost testHost) + => TestAsync( """ using System; @@ -1979,12 +1798,10 @@ void M() Static("Console"), Method("WriteLine"), Static("WriteLine")); - } [Theory, CombinatorialData] - public async Task StructEnumTypeNames(TestHost testHost) - { - await TestAsync( + public Task StructEnumTypeNames(TestHost testHost) + => TestAsync( """ using System; @@ -2009,12 +1826,10 @@ static void Main() Namespace("System"), Enum("ConsoleColor"), Struct("Int32")); - } [Theory, CombinatorialData] - public async Task PreferFieldOverClassWithSameName(TestHost testHost) - { - await TestAsync( + public Task PreferFieldOverClassWithSameName(TestHost testHost) + => TestAsync( """ class C { @@ -2027,12 +1842,10 @@ void M() } """, testHost, Field("C")); - } [Theory, CombinatorialData] - public async Task AttributeBinding(TestHost testHost) - { - await TestAsync( + public Task AttributeBinding(TestHost testHost) + => TestAsync( """ using System; @@ -2076,12 +1889,10 @@ class ObsoleteAttribute : Attribute Class("Attribute"), Class("ObsoleteAttribute"), Class("Attribute")); - } [Theory, CombinatorialData] - public async Task ShouldNotClassifyNamespacesAsTypes(TestHost testHost) - { - await TestAsync( + public Task ShouldNotClassifyNamespacesAsTypes(TestHost testHost) + => TestAsync( """ using System; @@ -2094,12 +1905,10 @@ namespace Roslyn.Compilers.Internal Namespace("Roslyn"), Namespace("Compilers"), Namespace("Internal")); - } [Theory, CombinatorialData] - public async Task NestedTypeCantHaveSameNameAsParentType(TestHost testHost) - { - await TestAsync( + public Task NestedTypeCantHaveSameNameAsParentType(TestHost testHost) + => TestAsync( """ class Program { @@ -2117,53 +1926,43 @@ static void Main(Program p) testHost, Class("Program"), Class("Program")); - } [Theory, CombinatorialData] - public async Task NestedTypeCantHaveSameNameAsParentTypeWithGlobalNamespaceAlias(TestHost testHost) - { - var code = """ + public Task NestedTypeCantHaveSameNameAsParentTypeWithGlobalNamespaceAlias(TestHost testHost) + => TestAsync(""" class Program { class Program { } static void Main(Program p) { } global::Program.Program p; } - """; - - await TestAsync(code, + """, testHost, ParseOptions(Options.Regular), Class("Program"), Class("Program"), Class("Program")); - } [Theory, CombinatorialData] - public async Task InteractiveNestedTypeCantHaveSameNameAsParentTypeWithGlobalNamespaceAlias(TestHost testHost) - { - var code = """ + public Task InteractiveNestedTypeCantHaveSameNameAsParentTypeWithGlobalNamespaceAlias(TestHost testHost) + => TestAsync(""" class Program { class Program { } static void Main(Program p) { } global::Script.Program.Program p; } - """; - - await TestAsync(code, + """, testHost, ParseOptions(Options.Script), Class("Program"), Class("Script"), Class("Program"), Class("Program")); - } [Theory, CombinatorialData] - public async Task EnumFieldWithSameNameShouldBePreferredToType(TestHost testHost) - { - await TestAsync( + public Task EnumFieldWithSameNameShouldBePreferredToType(TestHost testHost) + => TestAsync( """ enum E { @@ -2172,13 +1971,11 @@ enum E } """, testHost, EnumMember("E")); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541150")] [CombinatorialData] - public async Task TestGenericVarClassification(TestHost testHost) - { - await TestAsync( + public Task TestGenericVarClassification(TestHost testHost) + => TestAsync( """ using System; @@ -2197,13 +1994,11 @@ class var testHost, Namespace("System"), Keyword("var")); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541154")] [CombinatorialData] - public async Task TestInaccessibleVarClassification(TestHost testHost) - { - await TestAsync( + public Task TestInaccessibleVarClassification(TestHost testHost) + => TestAsync( """ using System; @@ -2226,13 +2021,11 @@ static void Main() Namespace("System"), Class("A"), Keyword("var")); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541154")] [CombinatorialData] - public async Task TestVarNamedTypeClassification(TestHost testHost) - { - await TestAsync( + public Task TestVarNamedTypeClassification(TestHost testHost) + => TestAsync( """ class var { @@ -2244,13 +2037,11 @@ static void Main() """, testHost, Keyword("var")); - } [Theory, WorkItem(9513, "DevDiv_Projects/Roslyn")] [CombinatorialData] - public async Task RegressionFor9513(TestHost testHost) - { - await TestAsync( + public Task RegressionFor9513(TestHost testHost) + => TestAsync( """ enum E { @@ -2284,13 +2075,11 @@ void M() EnumMember("B"), Enum("E"), EnumMember("A")); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542368")] [CombinatorialData] - public async Task RegressionFor9572(TestHost testHost) - { - await TestAsync( + public Task RegressionFor9572(TestHost testHost) + => TestAsync( """ class A where T : A.I, A.I { @@ -2309,13 +2098,11 @@ public interface I TypeParameter("T"), TypeParameter("T"), Interface("I")); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542368")] [CombinatorialData] - public async Task RegressionFor9831(TestHost testHost) - { - await TestAsync(@"F : A", + public Task RegressionFor9831(TestHost testHost) + => TestAsync(@"F : A", """ public class B { @@ -2333,13 +2120,11 @@ public class F : A """, testHost, Class("A")); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542432")] [CombinatorialData] - public async Task TestVar(TestHost testHost) - { - await TestAsync( + public Task TestVar(TestHost testHost) + => TestAsync( """ class Program { @@ -2366,13 +2151,11 @@ static void Main() Static("GetVarT"), Keyword("var"), Class("var")); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543123")] [CombinatorialData] - public async Task TestVar2(TestHost testHost) - { - await TestAsync( + public Task TestVar2(TestHost testHost) + => TestAsync( """ class Program { @@ -2387,13 +2170,11 @@ void Main(string[] args) testHost, Keyword("var"), Parameter("args")); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542778")] [CombinatorialData] - public async Task TestDuplicateTypeParamWithConstraint(TestHost testHost) - { - await TestAsync(@"where U : IEnumerable", + public Task TestDuplicateTypeParamWithConstraint(TestHost testHost) + => TestAsync(@"where U : IEnumerable", """ using System.Collections.Generic; @@ -2409,22 +2190,18 @@ public void Goo(U arg) testHost, TypeParameter("U"), Interface("IEnumerable")); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542685")] [CombinatorialData] - public async Task OptimisticallyColorFromInDeclaration(TestHost testHost) - { - await TestInExpressionAsync("from ", + public Task OptimisticallyColorFromInDeclaration(TestHost testHost) + => TestInExpressionAsync("from ", testHost, Keyword("from")); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542685")] [CombinatorialData] - public async Task OptimisticallyColorFromInAssignment(TestHost testHost) - { - await TestInMethodAsync( + public Task OptimisticallyColorFromInAssignment(TestHost testHost) + => TestInMethodAsync( """ var q = 3; @@ -2434,7 +2211,6 @@ await TestInMethodAsync( Keyword("var"), Local("q"), Keyword("from")); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542685")] [CombinatorialData] @@ -2443,9 +2219,8 @@ public async Task DoNotColorThingsOtherThanFromInDeclaration(TestHost testHost) [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542685")] [CombinatorialData] - public async Task DoNotColorThingsOtherThanFromInAssignment(TestHost testHost) - { - await TestInMethodAsync( + public Task DoNotColorThingsOtherThanFromInAssignment(TestHost testHost) + => TestInMethodAsync( """ var q = 3; @@ -2454,13 +2229,11 @@ await TestInMethodAsync( testHost, Keyword("var"), Local("q")); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542685")] [CombinatorialData] - public async Task DoNotColorFromWhenBoundInDeclaration(TestHost testHost) - { - await TestInMethodAsync( + public Task DoNotColorFromWhenBoundInDeclaration(TestHost testHost) + => TestInMethodAsync( """ var from = 3; var q = from @@ -2469,13 +2242,11 @@ await TestInMethodAsync( Keyword("var"), Keyword("var"), Local("from")); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542685")] [CombinatorialData] - public async Task DoNotColorFromWhenBoundInAssignment(TestHost testHost) - { - await TestInMethodAsync( + public Task DoNotColorFromWhenBoundInAssignment(TestHost testHost) + => TestInMethodAsync( """ var q = 3; var from = 3; @@ -2487,13 +2258,11 @@ await TestInMethodAsync( Keyword("var"), Local("q"), Local("from")); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543404")] [CombinatorialData] - public async Task NewOfClassWithOnlyPrivateConstructor(TestHost testHost) - { - await TestAsync( + public Task NewOfClassWithOnlyPrivateConstructor(TestHost testHost) + => TestAsync( """ class X { @@ -2512,13 +2281,11 @@ static void Main(string[] args) """, testHost, Class("X")); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544179")] [CombinatorialData] - public async Task TestNullableVersusConditionalAmbiguity1(TestHost testHost) - { - await TestAsync( + public Task TestNullableVersusConditionalAmbiguity1(TestHost testHost) + => TestAsync( """ class Program { @@ -2534,13 +2301,11 @@ public class C1 """, testHost, Class("C1")); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544179")] [CombinatorialData] - public async Task TestPointerVersusMultiplyAmbiguity1(TestHost testHost) - { - await TestAsync( + public Task TestPointerVersusMultiplyAmbiguity1(TestHost testHost) + => TestAsync( """ class Program { @@ -2556,13 +2321,11 @@ public class C1 """, testHost, Class("C1")); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544302")] [CombinatorialData] - public async Task EnumTypeAssignedToNamedPropertyOfSameNameInAttributeCtor(TestHost testHost) - { - await TestAsync( + public Task EnumTypeAssignedToNamedPropertyOfSameNameInAttributeCtor(TestHost testHost) + => TestAsync( """ using System; using System.Runtime.InteropServices; @@ -2581,13 +2344,11 @@ class C Class("DllImport"), Field("CallingConvention"), Enum("CallingConvention")); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531119")] [CombinatorialData] - public async Task OnlyClassifyGenericNameOnce(TestHost testHost) - { - await TestAsync( + public Task OnlyClassifyGenericNameOnce(TestHost testHost) + => TestAsync( """ enum Type { @@ -2600,12 +2361,10 @@ struct Type """, testHost, Struct("Type")); - } [Theory, CombinatorialData] - public async Task NameOf1(TestHost testHost) - { - await TestAsync( + public Task NameOf1(TestHost testHost) + => TestAsync( """ class C { @@ -2618,12 +2377,10 @@ void goo() testHost, Keyword("var"), Keyword("nameof")); - } [Theory, CombinatorialData] - public async Task NameOf2(TestHost testHost) - { - await TestAsync( + public Task NameOf2(TestHost testHost) + => TestAsync( """ class C { @@ -2637,12 +2394,10 @@ void goo() Keyword("var"), Keyword("nameof"), Class("C")); - } [Theory, CombinatorialData] - public async Task NameOfLocalMethod(TestHost testHost) - { - await TestAsync( + public Task NameOfLocalMethod(TestHost testHost) + => TestAsync( """ class C { @@ -2668,12 +2423,10 @@ void M(string s) Keyword("var"), Keyword("nameof"), Method("M")); - } [Theory, CombinatorialData] - public async Task MethodCalledNameOfInScope(TestHost testHost) - { - await TestAsync( + public Task MethodCalledNameOfInScope(TestHost testHost) + => TestAsync( """ class C { @@ -2691,12 +2444,10 @@ void goo() testHost, Keyword("var"), Method("nameof")); - } [Theory, CombinatorialData] - public async Task Tuples(TestHost testHost) - { - await TestAsync( + public Task Tuples(TestHost testHost) + => TestAsync( """ class C { @@ -2705,28 +2456,22 @@ class C """, testHost, ParseOptions(TestOptions.Regular, Options.Script)); - } [Theory, CombinatorialData] [WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/261049")] - public async Task DevDiv261049RegressionTest(TestHost testHost) - { - var source = """ + public Task DevDiv261049RegressionTest(TestHost testHost) + => TestInMethodAsync( + """ var (a,b) = Get(out int x, out int y); Console.WriteLine($"({a.first}, {a.second})"); - """; - - await TestInMethodAsync( - source, + """, testHost, Keyword("var"), Local("a"), Local("a")); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/633")] - public async Task InXmlDocCref_WhenTypeOnlyIsSpecified_ItIsClassified(TestHost testHost) - { - await TestAsync( + public Task InXmlDocCref_WhenTypeOnlyIsSpecified_ItIsClassified(TestHost testHost) + => TestAsync( """ /// /// @@ -2740,13 +2485,11 @@ public MyClass(int x) """, testHost, Class("MyClass")); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/633")] - public async Task InXmlDocCref_WhenConstructorOnlyIsSpecified_NothingIsClassified(TestHost testHost) - { - await TestAsync( + public Task InXmlDocCref_WhenConstructorOnlyIsSpecified_NothingIsClassified(TestHost testHost) + => TestAsync( """ /// /// @@ -2759,13 +2502,11 @@ public MyClass(int x) } """, testHost, Class("MyClass")); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/633")] - public async Task InXmlDocCref_WhenTypeAndConstructorSpecified_OnlyTypeIsClassified(TestHost testHost) - { - await TestAsync( + public Task InXmlDocCref_WhenTypeAndConstructorSpecified_OnlyTypeIsClassified(TestHost testHost) + => TestAsync( """ /// /// @@ -2780,13 +2521,11 @@ public MyClass(int x) testHost, Class("MyClass"), Class("MyClass")); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/13174")] - public async Task TestMemberBindingThatLooksGeneric(TestHost testHost) - { - await TestAsync( + public Task TestMemberBindingThatLooksGeneric(TestHost testHost) + => TestAsync( """ using System.Diagnostics; using System.Threading.Tasks; @@ -2815,13 +2554,11 @@ static void Main(string[] args) Static("Assert"), Parameter("args"), Property("Length")); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/23940")] - public async Task TestAliasQualifiedClass(TestHost testHost) - { - await TestAsync( + public Task TestAliasQualifiedClass(TestHost testHost) + => TestAsync( """ using System; using Col = System.Collections.Generic; @@ -2847,47 +2584,38 @@ static void Main(string[] args) Keyword("var"), Namespace("Col"), Class("List")); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_InsideMethod(TestHost testHost) - { - // Asserts no Keyword("unmanaged") because it is an identifier. - await TestInMethodAsync(""" + public Task TestUnmanagedConstraint_InsideMethod(TestHost testHost) + => TestInMethodAsync(""" var unmanaged = 0; unmanaged++; """, testHost, Keyword("var"), Local("unmanaged")); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Type_Keyword(TestHost testHost) - { - await TestAsync( + public Task TestUnmanagedConstraint_Type_Keyword(TestHost testHost) + => TestAsync( "class X where T : unmanaged { }", testHost, TypeParameter("T"), Keyword("unmanaged")); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Type_ExistingInterface(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_Type_ExistingInterface(TestHost testHost) + => TestAsync(""" interface unmanaged {} class X where T : unmanaged { } """, testHost, TypeParameter("T"), Keyword("unmanaged")); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) + => TestAsync(""" namespace OtherScope { interface unmanaged {} @@ -2898,12 +2626,10 @@ class X where T : unmanaged { } Namespace("OtherScope"), TypeParameter("T"), Keyword("unmanaged")); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Method_Keyword(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_Method_Keyword(TestHost testHost) + => TestAsync(""" class X { void M() where T : unmanaged { } @@ -2912,12 +2638,10 @@ void M() where T : unmanaged { } testHost, TypeParameter("T"), Keyword("unmanaged")); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Method_ExistingInterface(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_Method_ExistingInterface(TestHost testHost) + => TestAsync(""" interface unmanaged {} class X { @@ -2927,12 +2651,10 @@ void M() where T : unmanaged { } testHost, TypeParameter("T"), Keyword("unmanaged")); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) + => TestAsync(""" namespace OtherScope { interface unmanaged {} @@ -2946,34 +2668,28 @@ void M() where T : unmanaged { } Namespace("OtherScope"), TypeParameter("T"), Keyword("unmanaged")); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Delegate_Keyword(TestHost testHost) - { - await TestAsync( + public Task TestUnmanagedConstraint_Delegate_Keyword(TestHost testHost) + => TestAsync( "delegate void D() where T : unmanaged;", testHost, TypeParameter("T"), Keyword("unmanaged")); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Delegate_ExistingInterface(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_Delegate_ExistingInterface(TestHost testHost) + => TestAsync(""" interface unmanaged {} delegate void D() where T : unmanaged; """, testHost, TypeParameter("T"), Keyword("unmanaged")); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) + => TestAsync(""" namespace OtherScope { interface unmanaged {} @@ -2984,12 +2700,10 @@ interface unmanaged {} Namespace("OtherScope"), TypeParameter("T"), Keyword("unmanaged")); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_LocalFunction_Keyword(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_LocalFunction_Keyword(TestHost testHost) + => TestAsync(""" class X { void N() @@ -3001,12 +2715,10 @@ void M() where T : unmanaged { } testHost, TypeParameter("T"), Keyword("unmanaged")); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_LocalFunction_ExistingInterface(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_LocalFunction_ExistingInterface(TestHost testHost) + => TestAsync(""" interface unmanaged {} class X { @@ -3019,12 +2731,10 @@ void M() where T : unmanaged { } testHost, TypeParameter("T"), Keyword("unmanaged")); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) + => TestAsync(""" namespace OtherScope { interface unmanaged {} @@ -3041,7 +2751,6 @@ void M() where T : unmanaged { } Namespace("OtherScope"), TypeParameter("T"), Keyword("unmanaged")); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/29451")] [CombinatorialData] @@ -3052,20 +2761,17 @@ public async Task TestDirectiveStringLiteral(TestHost testHost) [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/30378")] [CombinatorialData] - public async Task TestFormatSpecifierInInterpolation(TestHost testHost) - { - await TestInMethodAsync(@"var goo = $""goo{{1:0000}}bar"";", + public Task TestFormatSpecifierInInterpolation(TestHost testHost) + => TestInMethodAsync(@"var goo = $""goo{{1:0000}}bar"";", testHost, Keyword("var"), Escape(@"{{"), Escape(@"}}")); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/29492")] [CombinatorialData] - public async Task TestOverloadedOperator_BinaryExpression(TestHost testHost) - { - await TestAsync(""" + public Task TestOverloadedOperator_BinaryExpression(TestHost testHost) + => TestAsync(""" class C { void M() @@ -3092,13 +2798,11 @@ class True Class("True"), Class("True"), Class("True")); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/29492")] [CombinatorialData] - public async Task TestOverloadedOperator_PrefixUnaryExpression(TestHost testHost) - { - await TestAsync(""" + public Task TestOverloadedOperator_PrefixUnaryExpression(TestHost testHost) + => TestAsync(""" class C { void M() @@ -3121,13 +2825,11 @@ class True OverloadedOperators.Exclamation, Class("True"), Class("True")); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/29492")] [CombinatorialData] - public async Task TestOverloadedOperator_PostfixUnaryExpression(TestHost testHost) - { - await TestAsync(""" + public Task TestOverloadedOperator_PostfixUnaryExpression(TestHost testHost) + => TestAsync(""" class C { void M() @@ -3156,13 +2858,11 @@ class True Class("True"), Class("True"), Class("True")); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/29492")] [CombinatorialData] - public async Task TestOverloadedOperator_ConditionalExpression(TestHost testHost) - { - await TestAsync(""" + public Task TestOverloadedOperator_ConditionalExpression(TestHost testHost) + => TestAsync(""" class C { void M() @@ -3187,12 +2887,10 @@ class True Class("True"), Class("True"), Class("True")); - } [Theory, CombinatorialData] - public async Task TestCatchDeclarationVariable(TestHost testHost) - { - await TestInMethodAsync(""" + public Task TestCatchDeclarationVariable(TestHost testHost) + => TestInMethodAsync(""" try { } @@ -3203,47 +2901,38 @@ await TestInMethodAsync(""" """, testHost, Local("ex")); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_InsideMethod(TestHost testHost) - { - // Asserts no Keyword("notnull") because it is an identifier. - await TestInMethodAsync(""" + public Task TestNotNullConstraint_InsideMethod(TestHost testHost) + => TestInMethodAsync(""" var notnull = 0; notnull++; """, testHost, Keyword("var"), Local("notnull")); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Type_Keyword(TestHost testHost) - { - await TestAsync( + public Task TestNotNullConstraint_Type_Keyword(TestHost testHost) + => TestAsync( "class X where T : notnull { }", testHost, TypeParameter("T"), Keyword("notnull")); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Type_ExistingInterface(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_Type_ExistingInterface(TestHost testHost) + => TestAsync(""" interface notnull {} class X where T : notnull { } """, testHost, TypeParameter("T"), Keyword("notnull")); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) + => TestAsync(""" namespace OtherScope { interface notnull {} @@ -3254,12 +2943,10 @@ class X where T : notnull { } Namespace("OtherScope"), TypeParameter("T"), Keyword("notnull")); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Method_Keyword(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_Method_Keyword(TestHost testHost) + => TestAsync(""" class X { void M() where T : notnull { } @@ -3268,12 +2955,10 @@ void M() where T : notnull { } testHost, TypeParameter("T"), Keyword("notnull")); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Method_ExistingInterface(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_Method_ExistingInterface(TestHost testHost) + => TestAsync(""" interface notnull {} class X { @@ -3283,12 +2968,10 @@ void M() where T : notnull { } testHost, TypeParameter("T"), Keyword("notnull")); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) + => TestAsync(""" namespace OtherScope { interface notnull {} @@ -3302,34 +2985,28 @@ void M() where T : notnull { } Namespace("OtherScope"), TypeParameter("T"), Keyword("notnull")); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Delegate_Keyword(TestHost testHost) - { - await TestAsync( + public Task TestNotNullConstraint_Delegate_Keyword(TestHost testHost) + => TestAsync( "delegate void D() where T : notnull;", testHost, TypeParameter("T"), Keyword("notnull")); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Delegate_ExistingInterface(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_Delegate_ExistingInterface(TestHost testHost) + => TestAsync(""" interface notnull {} delegate void D() where T : notnull; """, testHost, TypeParameter("T"), Keyword("notnull")); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) + => TestAsync(""" namespace OtherScope { interface notnull {} @@ -3340,12 +3017,10 @@ interface notnull {} Namespace("OtherScope"), TypeParameter("T"), Keyword("notnull")); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_LocalFunction_Keyword(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_LocalFunction_Keyword(TestHost testHost) + => TestAsync(""" class X { void N() @@ -3357,12 +3032,10 @@ void M() where T : notnull { } testHost, TypeParameter("T"), Keyword("notnull")); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_LocalFunction_ExistingInterface(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_LocalFunction_ExistingInterface(TestHost testHost) + => TestAsync(""" interface notnull {} class X { @@ -3375,12 +3048,10 @@ void M() where T : notnull { } testHost, TypeParameter("T"), Keyword("notnull")); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) + => TestAsync(""" namespace OtherScope { interface notnull {} @@ -3397,12 +3068,10 @@ void M() where T : notnull { } Namespace("OtherScope"), TypeParameter("T"), Keyword("notnull")); - } [Theory, CombinatorialData] - public async Task NonDiscardVariableDeclaration(TestHost testHost) - { - await TestAsync(""" + public Task NonDiscardVariableDeclaration(TestHost testHost) + => TestAsync(""" class X { void N() @@ -3415,12 +3084,10 @@ void N() Keyword("var"), Method("Parse"), Static("Parse")); - } [Theory, CombinatorialData] - public async Task NonDiscardVariableDeclarationMultipleDeclarators(TestHost testHost) - { - await TestAsync(""" + public Task NonDiscardVariableDeclarationMultipleDeclarators(TestHost testHost) + => TestAsync(""" class X { void N() @@ -3430,12 +3097,10 @@ void N() } } """, testHost); - } [Theory, CombinatorialData] - public async Task DiscardAssignment(TestHost testHost) - { - await TestAsync(""" + public Task DiscardAssignment(TestHost testHost) + => TestAsync(""" class X { void N() @@ -3448,12 +3113,10 @@ void N() Keyword("_"), Method("Parse"), Static("Parse")); - } [Theory, CombinatorialData] - public async Task DiscardInOutDeclaration(TestHost testHost) - { - await TestAsync(""" + public Task DiscardInOutDeclaration(TestHost testHost) + => TestAsync(""" class X { void N() @@ -3467,12 +3130,10 @@ void N() Static("TryParse"), Keyword("var"), Keyword("_")); - } [Theory, CombinatorialData] - public async Task DiscardInOutAssignment(TestHost testHost) - { - await TestAsync(""" + public Task DiscardInOutAssignment(TestHost testHost) + => TestAsync(""" class X { void N() @@ -3485,12 +3146,10 @@ void N() Method("TryParse"), Static("TryParse"), Keyword("_")); - } [Theory, CombinatorialData] - public async Task DiscardInDeconstructionAssignment(TestHost testHost) - { - await TestAsync(""" + public Task DiscardInDeconstructionAssignment(TestHost testHost) + => TestAsync(""" class X { void N() @@ -3501,12 +3160,10 @@ void N() """, testHost, Keyword("_")); - } [Theory, CombinatorialData] - public async Task DiscardInDeconstructionDeclaration(TestHost testHost) - { - await TestAsync(""" + public Task DiscardInDeconstructionDeclaration(TestHost testHost) + => TestAsync(""" class X { void N() @@ -3517,12 +3174,10 @@ void N() """, testHost, Keyword("_")); - } [Theory, CombinatorialData] - public async Task DiscardInPatternMatch(TestHost testHost) - { - await TestAsync(""" + public Task DiscardInPatternMatch(TestHost testHost) + => TestAsync(""" class X { bool N(object x) @@ -3534,12 +3189,10 @@ bool N(object x) testHost, Parameter("x"), Keyword("_")); - } [Theory, CombinatorialData] - public async Task DiscardInSwitch(TestHost testHost) - { - await TestAsync(""" + public Task DiscardInSwitch(TestHost testHost) + => TestAsync(""" class X { bool N(object x) @@ -3557,12 +3210,10 @@ bool N(object x) testHost, Parameter("x"), Keyword("_")); - } [Theory, CombinatorialData] - public async Task DiscardInSwitchPatternMatch(TestHost testHost) - { - await TestAsync(""" + public Task DiscardInSwitchPatternMatch(TestHost testHost) + => TestAsync(""" class X { bool N(object x) @@ -3577,12 +3228,10 @@ bool N(object x) testHost, Parameter("x"), Keyword("_")); - } [Theory, CombinatorialData] - public async Task UnusedUnderscoreParameterInLambda(TestHost testHost) - { - await TestAsync(""" + public Task UnusedUnderscoreParameterInLambda(TestHost testHost) + => TestAsync(""" class X { void N() @@ -3594,12 +3243,10 @@ void N() testHost, Namespace("System"), Delegate("Func")); - } [Theory, CombinatorialData] - public async Task UsedUnderscoreParameterInLambda(TestHost testHost) - { - await TestAsync(""" + public Task UsedUnderscoreParameterInLambda(TestHost testHost) + => TestAsync(""" class X { void N() @@ -3612,12 +3259,10 @@ void N() Namespace("System"), Delegate("Func"), Parameter("_")); - } [Theory, CombinatorialData] - public async Task DiscardsInLambda(TestHost testHost) - { - await TestAsync(""" + public Task DiscardsInLambda(TestHost testHost) + => TestAsync(""" class X { void N() @@ -3631,12 +3276,10 @@ void N() Delegate("Func"), Keyword("_"), Keyword("_")); - } [Theory, CombinatorialData] - public async Task DiscardsInLambdaWithInferredType(TestHost testHost) - { - await TestAsync(""" + public Task DiscardsInLambdaWithInferredType(TestHost testHost) + => TestAsync(""" class X { void N() @@ -3650,43 +3293,35 @@ void N() Delegate("Func"), Keyword("_"), Keyword("_")); - } [Theory, CombinatorialData] - public async Task NativeInteger(TestHost testHost) - { - await TestInMethodAsync( + public Task NativeInteger(TestHost testHost) + => TestInMethodAsync( @"nint i = 0; nuint i2 = 0;", testHost, Classifications(Keyword("nint"), Keyword("nuint"))); - } [Theory, CombinatorialData] - public async Task NotNativeInteger(TestHost testHost) - { - await TestInMethodAsync( + public Task NotNativeInteger(TestHost testHost) + => TestInMethodAsync( "nint", "M", "nint i = 0;", testHost, Classifications(Class("nint"))); - } [Theory, CombinatorialData] - public async Task NotNativeUnsignedInteger(TestHost testHost) - { - await TestInMethodAsync( + public Task NotNativeUnsignedInteger(TestHost testHost) + => TestInMethodAsync( "nuint", "M", "nuint i = 0;", testHost, Classifications(Class("nuint"))); - } [Theory, CombinatorialData] - public async Task StaticBoldingMethodName(TestHost testHost) - { - await TestAsync( + public Task StaticBoldingMethodName(TestHost testHost) + => TestAsync( """ class C { @@ -3701,12 +3336,10 @@ public static void Method() Delegate("Action"), Method("Method"), Static("Method")); - } [Theory, CombinatorialData] - public async Task StaticBoldingMethodNameNestedInNameof(TestHost testHost) - { - await TestAsync( + public Task StaticBoldingMethodNameNestedInNameof(TestHost testHost) + => TestAsync( """ class C { @@ -3721,12 +3354,10 @@ public static void Method() Keyword("nameof"), Static("Method"), Method("Method")); - } [Theory, CombinatorialData] - public async Task BoldingMethodNameStaticAndNot(TestHost testHost) - { - await TestAsync( + public Task BoldingMethodNameStaticAndNot(TestHost testHost) + => TestAsync( """ class C { @@ -3750,13 +3381,11 @@ public void Test() { Keyword("nameof"), Static("Method"), Method("Method")); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/46985")] - public async Task BasicRecordClassification(TestHost testHost) - { - await TestAsync( + public Task BasicRecordClassification(TestHost testHost) + => TestAsync( """ record R { @@ -3767,13 +3396,11 @@ record R """, testHost, RecordClass("R")); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/46985")] - public async Task ParameterizedRecordClassification(TestHost testHost) - { - await TestAsync( + public Task ParameterizedRecordClassification(TestHost testHost) + => TestAsync( """ record R(int X, int Y); @@ -3784,12 +3411,10 @@ class C """, testHost, RecordClass("R")); - } [Theory, CombinatorialData] - public async Task BasicRecordClassClassification(TestHost testHost) - { - await TestAsync( + public Task BasicRecordClassClassification(TestHost testHost) + => TestAsync( """ record class R { @@ -3800,12 +3425,10 @@ record class R """, testHost, RecordClass("R")); - } [Theory, CombinatorialData] - public async Task BasicRecordStructClassification(TestHost testHost) - { - await TestAsync( + public Task BasicRecordStructClassification(TestHost testHost) + => TestAsync( """ record struct R { @@ -3814,12 +3437,10 @@ record struct R """, testHost, RecordStruct("R")); - } [Theory, CombinatorialData] - public async Task BasicFileScopedNamespaceClassification(TestHost testHost) - { - await TestAsync( + public Task BasicFileScopedNamespaceClassification(TestHost testHost) + => TestAsync( """ namespace NS; @@ -3827,12 +3448,10 @@ class C { } """, testHost, Namespace("NS")); - } [Theory, CombinatorialData] - public async Task NullCheckedParameterClassification(TestHost testHost) - { - await TestAsync( + public Task NullCheckedParameterClassification(TestHost testHost) + => TestAsync( """ class C { @@ -3840,13 +3459,11 @@ void M(string s!!) { } } """, testHost); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/57184")] - public async Task MethodGroupClassifications(TestHost testHost) - { - await TestAsync( + public Task MethodGroupClassifications(TestHost testHost) + => TestAsync( """ var f = m; Delegate d = m; @@ -3866,14 +3483,12 @@ int m(Delegate d) { } Method("m"), Method("m"), Method("m")); - } /// /// [Theory, CombinatorialData] - public async Task LocalFunctionUse(TestHost testHost) - { - await TestAsync( + public Task LocalFunctionUse(TestHost testHost) + => TestAsync( """ using System; @@ -3902,7 +3517,6 @@ static void staticLocalFunction() { }|] Method("M"), Method("staticLocalFunction"), Static("staticLocalFunction")); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/744813")] public async Task TestCreateWithBufferNotInWorkspace() diff --git a/src/EditorFeatures/CSharpTest/Classification/SemanticClassifierTests_Json.cs b/src/EditorFeatures/CSharpTest/Classification/SemanticClassifierTests_Json.cs index f8e81bb763aca..d0a3f0fa4bac0 100644 --- a/src/EditorFeatures/CSharpTest/Classification/SemanticClassifierTests_Json.cs +++ b/src/EditorFeatures/CSharpTest/Classification/SemanticClassifierTests_Json.cs @@ -15,9 +15,8 @@ public partial class SemanticClassifierTests { [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/68534")] - public async Task TestJson1(TestHost testHost) - { - await TestAsync( + public Task TestJson1(TestHost testHost) + => TestAsync( """ class Program { @@ -59,12 +58,10 @@ void Goo() Json.String("'str'"), Json.Array("]"), Json.Comment("// comment")); - } [Theory, CombinatorialData] - public async Task TestJson_RawString(TestHost testHost) - { - await TestAsync( + public Task TestJson_RawString(TestHost testHost) + => TestAsync( """" class Program { @@ -85,13 +82,11 @@ void Goo() Json.Number("0"), Json.Object("}"), Json.Array("]")); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/68534")] - public async Task TestMultiLineJson1(TestHost testHost) - { - await TestAsync( + public Task TestMultiLineJson1(TestHost testHost) + => TestAsync( """ class Program { @@ -147,12 +142,10 @@ void Goo() Json.String("'str'"), Json.Array("]"), Json.Comment("// comment")); - } [Theory, CombinatorialData] - public async Task TestJson_NoComment_NotLikelyJson(TestHost testHost) - { - var input = """ + public Task TestJson_NoComment_NotLikelyJson(TestHost testHost) + => TestAsync(""" class C { void Goo() @@ -160,16 +153,13 @@ void Goo() var r = @"[1, 2, 3]"; } } - """; - await TestAsync(input, + """, testHost, Keyword("var")); - } [Theory, CombinatorialData] - public async Task TestJson_NoComment_LikelyJson(TestHost testHost) - { - var input = """ + public Task TestJson_NoComment_LikelyJson(TestHost testHost) + => TestAsync(""" class C { void Goo() @@ -177,8 +167,7 @@ void Goo() var r = @"[1, { prop: 0 }, 3]"; } } - """; - await TestAsync(input, + """, testHost, Keyword("var"), Json.Array("["), @@ -192,12 +181,10 @@ await TestAsync(input, Json.Punctuation(","), Json.Number("3"), Json.Array("]")); - } [Theory, CombinatorialData] - public async Task TestJsonOnApiWithStringSyntaxAttribute_Field(TestHost testHost) - { - await TestAsync( + public Task TestJsonOnApiWithStringSyntaxAttribute_Field(TestHost testHost) + => TestAsync( """ using System.Diagnostics.CodeAnalysis; @@ -220,12 +207,10 @@ void Goo() Json.Number("0"), Json.Object("}"), Json.Array("]")); - } [Theory, CombinatorialData] - public async Task TestJsonOnApiWithStringSyntaxAttribute_Field_FromLocal(TestHost testHost) - { - await TestAsync( + public Task TestJsonOnApiWithStringSyntaxAttribute_Field_FromLocal(TestHost testHost) + => TestAsync( """ using System.Diagnostics.CodeAnalysis; @@ -249,13 +234,11 @@ void Goo() Json.Number("0"), Json.Object("}"), Json.Array("]")); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/74020")] - public async Task TestJsonOnApiWithStringSyntaxAttribute_OtherLanguage_Field(TestHost testHost) - { - await TestAsync( + public Task TestJsonOnApiWithStringSyntaxAttribute_OtherLanguage_Field(TestHost testHost) + => TestAsync( """ using System.Diagnostics.CodeAnalysis; @@ -271,12 +254,10 @@ void Goo() """ + EmbeddedLanguagesTestConstants.StringSyntaxAttributeCodeCSharp, testHost, Field("field")); - } [Theory, CombinatorialData] - public async Task TestJsonOnApiWithStringSyntaxAttribute_Property(TestHost testHost) - { - await TestAsync( + public Task TestJsonOnApiWithStringSyntaxAttribute_Property(TestHost testHost) + => TestAsync( """ using System.Diagnostics.CodeAnalysis; @@ -299,12 +280,10 @@ void Goo() Json.Number("0"), Json.Object("}"), Json.Array("]")); - } [Theory, CombinatorialData] - public async Task TestJsonOnApiWithStringSyntaxAttribute_Argument(TestHost testHost) - { - await TestAsync( + public Task TestJsonOnApiWithStringSyntaxAttribute_Argument(TestHost testHost) + => TestAsync( """ using System.Diagnostics.CodeAnalysis; @@ -329,12 +308,10 @@ void Goo() Json.Number("0"), Json.Object("}"), Json.Array("]")); - } [Theory, CombinatorialData] - public async Task TestJsonOnApiWithStringSyntaxAttribute_Argument_FromLocal(TestHost testHost) - { - await TestAsync( + public Task TestJsonOnApiWithStringSyntaxAttribute_Argument_FromLocal(TestHost testHost) + => TestAsync( """ using System.Diagnostics.CodeAnalysis; @@ -360,13 +337,11 @@ void Goo() Json.Number("0"), Json.Object("}"), Json.Array("]")); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/69237")] - public async Task TestJsonOnApiWithStringSyntaxAttribute_PropertyInitializer(TestHost testHost) - { - await TestAsync( + public Task TestJsonOnApiWithStringSyntaxAttribute_PropertyInitializer(TestHost testHost) + => TestAsync( """" using System.Diagnostics.CodeAnalysis; @@ -393,13 +368,11 @@ void Goo() Json.Punctuation(","), Json.Number("3"), Json.Array("]")); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/69237")] - public async Task TestJsonOnApiWithStringSyntaxAttribute_PropertyInitializer_FromLocal(TestHost testHost) - { - await TestAsync( + public Task TestJsonOnApiWithStringSyntaxAttribute_PropertyInitializer_FromLocal(TestHost testHost) + => TestAsync( """" using System.Diagnostics.CodeAnalysis; @@ -427,13 +400,11 @@ void Goo() Json.Punctuation(","), Json.Number("3"), Json.Array("]")); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/69237")] - public async Task TestJsonOnApiWithStringSyntaxAttribute_WithExpression(TestHost testHost) - { - await TestAsync( + public Task TestJsonOnApiWithStringSyntaxAttribute_WithExpression(TestHost testHost) + => TestAsync( """" using System.Diagnostics.CodeAnalysis; @@ -461,13 +432,11 @@ void Goo() Json.Punctuation(","), Json.Number("3"), Json.Array("]")); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/69237")] - public async Task TestJsonOnApiWithStringSyntaxAttribute_WithExpression_FromLocal(TestHost testHost) - { - await TestAsync( + public Task TestJsonOnApiWithStringSyntaxAttribute_WithExpression_FromLocal(TestHost testHost) + => TestAsync( """" using System.Diagnostics.CodeAnalysis; @@ -496,13 +465,11 @@ void Goo() Json.Punctuation(","), Json.Number("3"), Json.Array("]")); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/69237")] - public async Task TestJsonOnApiWithStringSyntaxAttribute_WithExpression_FromLocal2(TestHost testHost) - { - await TestAsync( + public Task TestJsonOnApiWithStringSyntaxAttribute_WithExpression_FromLocal2(TestHost testHost) + => TestAsync( """" using System.Diagnostics.CodeAnalysis; @@ -532,5 +499,4 @@ void Goo() Json.Punctuation(","), Json.Number("3"), Json.Array("]")); - } } diff --git a/src/EditorFeatures/CSharpTest/Classification/SemanticClassifierTests_Regex.cs b/src/EditorFeatures/CSharpTest/Classification/SemanticClassifierTests_Regex.cs index f011511041a70..0234b4b8bb6b8 100644 --- a/src/EditorFeatures/CSharpTest/Classification/SemanticClassifierTests_Regex.cs +++ b/src/EditorFeatures/CSharpTest/Classification/SemanticClassifierTests_Regex.cs @@ -14,9 +14,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Classification; public partial class SemanticClassifierTests { [Theory, CombinatorialData] - public async Task TestRegex1(TestHost testHost) - { - await TestAsync( + public Task TestRegex1(TestHost testHost) + => TestAsync( """ using System.Text.RegularExpressions; @@ -94,12 +93,10 @@ void Goo() Regex.Quantifier("}"), Regex.Quantifier("?"), Regex.Anchor("^")); - } [Theory, CombinatorialData] - public async Task TestRegex2(TestHost testHost) - { - await TestAsync( + public Task TestRegex2(TestHost testHost) + => TestAsync( """ using System.Text.RegularExpressions; @@ -177,12 +174,10 @@ void Goo() Regex.Quantifier("}"), Regex.Quantifier("?"), Regex.Anchor("^")); - } [Theory, CombinatorialData] - public async Task TestRegex3(TestHost testHost) - { - await TestAsync( + public Task TestRegex3(TestHost testHost) + => TestAsync( """ using System.Text.RegularExpressions; @@ -260,12 +255,10 @@ void Goo() Regex.Quantifier("}"), Regex.Quantifier("?"), Regex.Anchor("^")); - } [Theory, CombinatorialData] - public async Task TestRegex4(TestHost testHost) - { - await TestAsync( + public Task TestRegex4(TestHost testHost) + => TestAsync( """ using System.Text.RegularExpressions; @@ -285,12 +278,10 @@ void Goo() Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] - public async Task TestRegex4_utf8_1(TestHost testHost) - { - await TestAsync( + public Task TestRegex4_utf8_1(TestHost testHost) + => TestAsync( """ using System.Text.RegularExpressions; @@ -310,12 +301,10 @@ void Goo() Regex.OtherEscape(@"\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] - public async Task TestRegex4_utf8_2(TestHost testHost) - { - await TestAsync( + public Task TestRegex4_utf8_2(TestHost testHost) + => TestAsync( """ using System.Text.RegularExpressions; @@ -335,12 +324,10 @@ void Goo() Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] - public async Task TestRegex5(TestHost testHost) - { - await TestAsync( + public Task TestRegex5(TestHost testHost) + => TestAsync( """ using System.Text.RegularExpressions; @@ -360,12 +347,10 @@ void Goo() Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] - public async Task TestRegex6(TestHost testHost) - { - await TestAsync( + public Task TestRegex6(TestHost testHost) + => TestAsync( """ using System.Text.RegularExpressions; @@ -386,12 +371,10 @@ void Goo() Regex.OtherEscape("a"), Regex.Comment("(?#comment)"), Regex.Text(" # not end of line comment")); - } [Theory, CombinatorialData] - public async Task TestRegex7(TestHost testHost) - { - await TestAsync( + public Task TestRegex7(TestHost testHost) + => TestAsync( """ using System.Text.RegularExpressions; @@ -412,12 +395,10 @@ void Goo() Regex.OtherEscape("a"), Regex.Comment("(?#comment)"), Regex.Comment("# is end of line comment")); - } [Theory, CombinatorialData] - public async Task TestRegex8(TestHost testHost) - { - await TestAsync( + public Task TestRegex8(TestHost testHost) + => TestAsync( """ using System.Text.RegularExpressions; @@ -438,12 +419,10 @@ void Goo() Regex.OtherEscape("a"), Regex.Comment("(?#comment)"), Regex.Comment("# is end of line comment")); - } [Theory, CombinatorialData] - public async Task TestRegex9(TestHost testHost) - { - await TestAsync( + public Task TestRegex9(TestHost testHost) + => TestAsync( """ using System.Text.RegularExpressions; @@ -467,12 +446,10 @@ void Goo() Regex.Comment("# is end of line comment"), Enum("RegexOptions"), EnumMember("IgnorePatternWhitespace")); - } [Theory, CombinatorialData] - public async Task TestRegex10(TestHost testHost) - { - await TestAsync( + public Task TestRegex10(TestHost testHost) + => TestAsync( """ using System.Text.RegularExpressions; @@ -494,12 +471,10 @@ void Goo() Regex.OtherEscape("a"), Regex.Comment("(?#comment)"), Regex.Text(" # is not end of line comment")); - } [Theory, CombinatorialData] - public async Task TestRegex10_utf8(TestHost testHost) - { - await TestAsync( + public Task TestRegex10_utf8(TestHost testHost) + => TestAsync( """ using System.Text.RegularExpressions; @@ -521,12 +496,10 @@ void Goo() Regex.OtherEscape("a"), Regex.Comment("(?#comment)"), Regex.Text(" # is not end of line comment")); - } [Theory, CombinatorialData] - public async Task TestRegex11(TestHost testHost) - { - await TestAsync( + public Task TestRegex11(TestHost testHost) + => TestAsync( """ using System.Text.RegularExpressions; @@ -549,12 +522,10 @@ class Program Regex.OtherEscape("u"), Regex.OtherEscape("0020"), Regex.Grouping(")")); - } [Theory, CombinatorialData] - public async Task TestRegexSingleLineRawStringLiteral(TestHost testHost) - { - await TestAsync( + public Task TestRegexSingleLineRawStringLiteral(TestHost testHost) + => TestAsync( """" using System.Text.RegularExpressions; @@ -574,12 +545,10 @@ void Goo() Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] - public async Task TestRegexSingleLineRawStringLiteral_utf8(TestHost testHost) - { - await TestAsync( + public Task TestRegexSingleLineRawStringLiteral_utf8(TestHost testHost) + => TestAsync( """" using System.Text.RegularExpressions; @@ -599,12 +568,10 @@ void Goo() Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] - public async Task TestRegexMultiLineRawStringLiteral(TestHost testHost) - { - await TestAsync( + public Task TestRegexMultiLineRawStringLiteral(TestHost testHost) + => TestAsync( """" using System.Text.RegularExpressions; @@ -626,12 +593,10 @@ void Goo() Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] - public async Task TestRegexMultiLineRawStringLiteral_utf8(TestHost testHost) - { - await TestAsync( + public Task TestRegexMultiLineRawStringLiteral_utf8(TestHost testHost) + => TestAsync( """" using System.Text.RegularExpressions; @@ -653,13 +618,11 @@ void Goo() Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/47079")] [CombinatorialData] - public async Task TestRegexWithSpecialCSharpCharLiterals(TestHost testHost) - { - await TestAsync( + public Task TestRegexWithSpecialCSharpCharLiterals(TestHost testHost) + => TestAsync( """ using System.Text.RegularExpressions; @@ -678,13 +641,11 @@ class Program Regex.Anchor("^"), Regex.Text(@" """" "), Regex.Anchor("$")); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/47079")] [CombinatorialData] - public async Task TestRegexWithSpecialCSharpCharLiterals_utf8(TestHost testHost) - { - await TestAsync( + public Task TestRegexWithSpecialCSharpCharLiterals_utf8(TestHost testHost) + => TestAsync( """ using System.Text.RegularExpressions; @@ -701,12 +662,10 @@ class Program Regex.Anchor("^"), Regex.Text(@" """" "), Regex.Anchor("$")); - } [Theory, CombinatorialData] - public async Task TestRegexOnApiWithStringSyntaxAttribute_Field(TestHost testHost) - { - await TestAsync( + public Task TestRegexOnApiWithStringSyntaxAttribute_Field(TestHost testHost) + => TestAsync( """ using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; @@ -728,12 +687,10 @@ void Goo() Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] - public async Task TestRegexOnApiWithStringSyntaxAttribute_Field2(TestHost testHost) - { - await TestAsync( + public Task TestRegexOnApiWithStringSyntaxAttribute_Field2(TestHost testHost) + => TestAsync( """ using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; @@ -749,12 +706,10 @@ class Program Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] - public async Task TestRegexOnApiWithStringSyntaxAttribute_Property(TestHost testHost) - { - await TestAsync( + public Task TestRegexOnApiWithStringSyntaxAttribute_Property(TestHost testHost) + => TestAsync( """ using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; @@ -776,12 +731,10 @@ void Goo() Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] - public async Task TestRegexOnApiWithStringSyntaxAttribute_Property2(TestHost testHost) - { - await TestAsync( + public Task TestRegexOnApiWithStringSyntaxAttribute_Property2(TestHost testHost) + => TestAsync( """ using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; @@ -797,12 +750,10 @@ class Program Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] - public async Task TestRegexOnApiWithStringSyntaxAttribute_Argument(TestHost testHost) - { - await TestAsync( + public Task TestRegexOnApiWithStringSyntaxAttribute_Argument(TestHost testHost) + => TestAsync( """ using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; @@ -825,12 +776,10 @@ void Goo() Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] - public async Task TestRegexOnApiWithStringSyntaxAttribute_ParamsArgument(TestHost testHost) - { - await TestAsync( + public Task TestRegexOnApiWithStringSyntaxAttribute_ParamsArgument(TestHost testHost) + => TestAsync( """ using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; @@ -853,13 +802,11 @@ void Goo() Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/64549")] [CombinatorialData] - public async Task TestRegexOnApiWithStringSyntaxAttribute_ParamsArgument2(TestHost testHost) - { - await TestAsync( + public Task TestRegexOnApiWithStringSyntaxAttribute_ParamsArgument2(TestHost testHost) + => TestAsync( """ using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; @@ -886,12 +833,10 @@ void Goo() Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] - public async Task TestRegexOnApiWithStringSyntaxAttribute_ArrayArgument(TestHost testHost) - { - await TestAsync( + public Task TestRegexOnApiWithStringSyntaxAttribute_ArrayArgument(TestHost testHost) + => TestAsync( """ using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; @@ -914,12 +859,10 @@ void Goo() Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] - public async Task TestRegexOnApiWithStringSyntaxAttribute_ImplicitArrayArgument(TestHost testHost) - { - await TestAsync( + public Task TestRegexOnApiWithStringSyntaxAttribute_ImplicitArrayArgument(TestHost testHost) + => TestAsync( """ using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; @@ -942,12 +885,10 @@ void Goo() Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] - public async Task TestRegexOnApiWithStringSyntaxAttribute_CollectionArgument(TestHost testHost) - { - await TestAsync( + public Task TestRegexOnApiWithStringSyntaxAttribute_CollectionArgument(TestHost testHost) + => TestAsync( """ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -972,12 +913,10 @@ void Goo() Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] - public async Task TestRegexOnApiWithStringSyntaxAttribute_ImplicitCollectionArgument(TestHost testHost) - { - await TestAsync( + public Task TestRegexOnApiWithStringSyntaxAttribute_ImplicitCollectionArgument(TestHost testHost) + => TestAsync( """ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -1001,12 +940,10 @@ void Goo() Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] - public async Task TestRegexOnApiWithStringSyntaxAttribute_Argument_Options(TestHost testHost) - { - await TestAsync( + public Task TestRegexOnApiWithStringSyntaxAttribute_Argument_Options(TestHost testHost) + => TestAsync( """ using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; @@ -1032,12 +969,10 @@ void Goo() Regex.Comment("# is end of line comment"), Enum("RegexOptions"), EnumMember("IgnorePatternWhitespace")); - } [Theory, CombinatorialData] - public async Task TestRegexOnApiWithStringSyntaxAttribute_Attribute(TestHost testHost) - { - await TestAsync( + public Task TestRegexOnApiWithStringSyntaxAttribute_Attribute(TestHost testHost) + => TestAsync( """ using System; using System.Diagnostics.CodeAnalysis; @@ -1061,13 +996,11 @@ class Program Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/61947")] - public async Task TestRegexOnApiWithStringSyntaxAttribute_AttributeField(TestHost testHost) - { - await TestAsync( + public Task TestRegexOnApiWithStringSyntaxAttribute_AttributeField(TestHost testHost) + => TestAsync( """ using System; using System.Diagnostics.CodeAnalysis; @@ -1095,13 +1028,11 @@ class Program Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/61947")] - public async Task TestRegexOnApiWithStringSyntaxAttribute_AttributeProperty(TestHost testHost) - { - await TestAsync( + public Task TestRegexOnApiWithStringSyntaxAttribute_AttributeProperty(TestHost testHost) + => TestAsync( """ using System; using System.Diagnostics.CodeAnalysis; @@ -1129,12 +1060,10 @@ class Program Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] - public async Task TestRegexOnApiWithStringSyntaxAttribute_ParamsAttribute(TestHost testHost) - { - await TestAsync( + public Task TestRegexOnApiWithStringSyntaxAttribute_ParamsAttribute(TestHost testHost) + => TestAsync( """ using System; using System.Diagnostics.CodeAnalysis; @@ -1158,12 +1087,10 @@ class Program Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] - public async Task TestRegexOnApiWithStringSyntaxAttribute_ArrayAttribute(TestHost testHost) - { - await TestAsync( + public Task TestRegexOnApiWithStringSyntaxAttribute_ArrayAttribute(TestHost testHost) + => TestAsync( """ using System; using System.Diagnostics.CodeAnalysis; @@ -1187,12 +1114,10 @@ class Program Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] - public async Task TestRegexOnApiWithStringSyntaxAttribute_ImplicitArrayAttribute(TestHost testHost) - { - await TestAsync( + public Task TestRegexOnApiWithStringSyntaxAttribute_ImplicitArrayAttribute(TestHost testHost) + => TestAsync( """ using System; using System.Diagnostics.CodeAnalysis; @@ -1216,12 +1141,10 @@ class Program Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] - public async Task TestIncompleteRegexLeadingToStringInsideSkippedTokensInsideADirective(TestHost testHost) - { - await TestAsync( + public Task TestIncompleteRegexLeadingToStringInsideSkippedTokensInsideADirective(TestHost testHost) + => TestAsync( """ using System.Text.RegularExpressions; @@ -1246,13 +1169,11 @@ void M() Namespace("RegularExpressions"), Keyword("var"), Class("Regex")); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/61982")] - public async Task TestRegexAmbiguity1(TestHost testHost) - { - await TestAsync( + public Task TestRegexAmbiguity1(TestHost testHost) + => TestAsync( """ using System.Text.RegularExpressions; @@ -1267,13 +1188,11 @@ void Goo() Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/61982")] - public async Task TestRegexAmbiguity2(TestHost testHost) - { - await TestAsync( + public Task TestRegexAmbiguity2(TestHost testHost) + => TestAsync( """ using System.Text.RegularExpressions; @@ -1288,12 +1207,10 @@ void Goo() Regex.OtherEscape("\\"), Regex.OtherEscape("a"), Regex.Comment("(?#comment)")); - } [Theory, CombinatorialData] - public async Task TestRegexNotOnBinaryExpression(TestHost testHost) - { - await TestAsync( + public Task TestRegexNotOnBinaryExpression(TestHost testHost) + => TestAsync( """ using System.Text.RegularExpressions; @@ -1311,15 +1228,13 @@ void Goo() Namespace("Text"), Namespace("RegularExpressions"), Keyword("var")); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/77189")] - public async Task TestStringFieldUsedLater_ProperModifiers( + public Task TestStringFieldUsedLater_ProperModifiers( TestHost testHost, [CombinatorialValues("const", "static readonly")] string modifiers) - { - await TestAsync( + => TestAsync( $$""" using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; @@ -1349,15 +1264,13 @@ void Bar([StringSyntax(StringSyntaxAttribute.Regex)] string p) Regex.OtherEscape("u"), Regex.OtherEscape("0020"), Regex.Grouping(")")); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/77189")] - public async Task TestStringFieldUsedLater_ImproperModifiers( + public Task TestStringFieldUsedLater_ImproperModifiers( TestHost testHost, [CombinatorialValues("", "static", "readonly")] string modifiers) - { - await TestAsync( + => TestAsync( $$""" using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; @@ -1377,5 +1290,4 @@ void Bar([StringSyntax(StringSyntaxAttribute.Regex)] string p) } """ + EmbeddedLanguagesTestConstants.StringSyntaxAttributeCodeCSharp, testHost); - } } diff --git a/src/EditorFeatures/CSharpTest/Classification/SemanticClassifierTests_StringEscapes.cs b/src/EditorFeatures/CSharpTest/Classification/SemanticClassifierTests_StringEscapes.cs index bd4882adde4d7..86a6f249a9cdf 100644 --- a/src/EditorFeatures/CSharpTest/Classification/SemanticClassifierTests_StringEscapes.cs +++ b/src/EditorFeatures/CSharpTest/Classification/SemanticClassifierTests_StringEscapes.cs @@ -13,366 +13,295 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Classification; public partial class SemanticClassifierTests : AbstractCSharpClassifierTests { [Theory, CombinatorialData] - public async Task TestStringEscape1(TestHost testHost) - { - await TestInMethodAsync(@"var goo = ""goo\r\nbar"";", + public Task TestStringEscape1(TestHost testHost) + => TestInMethodAsync(@"var goo = ""goo\r\nbar"";", testHost, Keyword("var"), Escape(@"\r"), Escape(@"\n")); - } [Theory, CombinatorialData] - public async Task TestStringEscape1_utf8(TestHost testHost) - { - await TestInMethodAsync(@"var goo = ""goo\r\nbar""u8;", + public Task TestStringEscape1_utf8(TestHost testHost) + => TestInMethodAsync(@"var goo = ""goo\r\nbar""u8;", testHost, Keyword("var"), Escape(@"\r"), Escape(@"\n")); - } [Theory, CombinatorialData] - public async Task TestStringEscape2(TestHost testHost) - { - await TestInMethodAsync(@"var goo = @""goo\r\nbar"";", + public Task TestStringEscape2(TestHost testHost) + => TestInMethodAsync(@"var goo = @""goo\r\nbar"";", testHost, Keyword("var")); - } [Theory, CombinatorialData] - public async Task TestStringEscape2_utf8(TestHost testHost) - { - await TestInMethodAsync(@"var goo = @""goo\r\nbar""u8;", + public Task TestStringEscape2_utf8(TestHost testHost) + => TestInMethodAsync(@"var goo = @""goo\r\nbar""u8;", testHost, Keyword("var")); - } [Theory, CombinatorialData] - public async Task TestStringEscape3(TestHost testHost) - { - await TestInMethodAsync(@"var goo = $""goo{{1}}bar"";", + public Task TestStringEscape3(TestHost testHost) + => TestInMethodAsync(@"var goo = $""goo{{1}}bar"";", testHost, Keyword("var"), Escape(@"{{"), Escape(@"}}")); - } [Theory, CombinatorialData] - public async Task TestStringEscape3_utf8(TestHost testHost) - { - await TestInMethodAsync(@"var goo = $""goo{{1}}bar""u8;", + public Task TestStringEscape3_utf8(TestHost testHost) + => TestInMethodAsync(@"var goo = $""goo{{1}}bar""u8;", testHost, Keyword("var"), Escape(@"{{"), Escape(@"}}")); - } [Theory, CombinatorialData] - public async Task TestStringEscape4(TestHost testHost) - { - await TestInMethodAsync(@"var goo = $@""goo{{1}}bar"";", + public Task TestStringEscape4(TestHost testHost) + => TestInMethodAsync(@"var goo = $@""goo{{1}}bar"";", testHost, Keyword("var"), Escape(@"{{"), Escape(@"}}")); - } [Theory, CombinatorialData] - public async Task TestStringEscape4_utf8(TestHost testHost) - { - await TestInMethodAsync(@"var goo = $@""goo{{1}}bar""u8;", + public Task TestStringEscape4_utf8(TestHost testHost) + => TestInMethodAsync(@"var goo = $@""goo{{1}}bar""u8;", testHost, Keyword("var"), Escape(@"{{"), Escape(@"}}")); - } [Theory, CombinatorialData] - public async Task TestStringEscape5(TestHost testHost) - { - await TestInMethodAsync(@"var goo = $""goo\r{{1}}\nbar"";", + public Task TestStringEscape5(TestHost testHost) + => TestInMethodAsync(@"var goo = $""goo\r{{1}}\nbar"";", testHost, Keyword("var"), Escape(@"\r"), Escape(@"{{"), Escape(@"}}"), Escape(@"\n")); - } [Theory, CombinatorialData] - public async Task TestStringEscape5_utf8(TestHost testHost) - { - await TestInMethodAsync(@"var goo = $""goo\r{{1}}\nbar""u8;", + public Task TestStringEscape5_utf8(TestHost testHost) + => TestInMethodAsync(@"var goo = $""goo\r{{1}}\nbar""u8;", testHost, Keyword("var"), Escape(@"\r"), Escape(@"{{"), Escape(@"}}"), Escape(@"\n")); - } [Theory, CombinatorialData] - public async Task TestStringEscape6(TestHost testHost) - { - await TestInMethodAsync(@"var goo = $@""goo\r{{1}}\nbar"";", + public Task TestStringEscape6(TestHost testHost) + => TestInMethodAsync(@"var goo = $@""goo\r{{1}}\nbar"";", testHost, Keyword("var"), Escape(@"{{"), Escape(@"}}")); - } [Theory, CombinatorialData] - public async Task TestStringEscape6_utf8(TestHost testHost) - { - await TestInMethodAsync(@"var goo = $@""goo\r{{1}}\nbar""u8;", + public Task TestStringEscape6_utf8(TestHost testHost) + => TestInMethodAsync(@"var goo = $@""goo\r{{1}}\nbar""u8;", testHost, Keyword("var"), Escape(@"{{"), Escape(@"}}")); - } [Theory, CombinatorialData] - public async Task TestStringEscape7(TestHost testHost) - { - await TestInMethodAsync(@"var goo = $""goo\r{1}\nbar"";", + public Task TestStringEscape7(TestHost testHost) + => TestInMethodAsync(@"var goo = $""goo\r{1}\nbar"";", testHost, Keyword("var"), Escape(@"\r"), Escape(@"\n")); - } [Theory, CombinatorialData] - public async Task TestStringEscape7_utf8(TestHost testHost) - { - await TestInMethodAsync(@"var goo = $""goo\r{1}\nbar""u8;", + public Task TestStringEscape7_utf8(TestHost testHost) + => TestInMethodAsync(@"var goo = $""goo\r{1}\nbar""u8;", testHost, Keyword("var"), Escape(@"\r"), Escape(@"\n")); - } [Theory, CombinatorialData] - public async Task TestStringEscape8(TestHost testHost) - { - await TestInMethodAsync(@"var goo = $@""{{goo{1}bar}}"";", + public Task TestStringEscape8(TestHost testHost) + => TestInMethodAsync(@"var goo = $@""{{goo{1}bar}}"";", testHost, Keyword("var"), Escape(@"{{"), Escape(@"}}")); - } [Theory, CombinatorialData] - public async Task TestStringEscape8_utf8(TestHost testHost) - { - await TestInMethodAsync(@"var goo = $@""{{goo{1}bar}}""u8;", + public Task TestStringEscape8_utf8(TestHost testHost) + => TestInMethodAsync(@"var goo = $@""{{goo{1}bar}}""u8;", testHost, Keyword("var"), Escape(@"{{"), Escape(@"}}")); - } [Theory, CombinatorialData] - public async Task TestStringEscape9(TestHost testHost) - { - await TestInMethodAsync(@"var goo = $@""{{{12:X}}}"";", + public Task TestStringEscape9(TestHost testHost) + => TestInMethodAsync(@"var goo = $@""{{{12:X}}}"";", testHost, Keyword("var"), Escape(@"{{"), Escape(@"}}")); - } [Theory, CombinatorialData] - public async Task TestStringEscape9_utf8(TestHost testHost) - { - await TestInMethodAsync(@"var goo = $@""{{{12:X}}}""u8;", + public Task TestStringEscape9_utf8(TestHost testHost) + => TestInMethodAsync(@"var goo = $@""{{{12:X}}}""u8;", testHost, Keyword("var"), Escape(@"{{"), Escape(@"}}")); - } [Theory, CombinatorialData] - public async Task TestNotStringEscapeInRawLiteral1(TestHost testHost) - { - await TestInMethodAsync(@"var goo = """"""goo\r\nbar"""""";", + public Task TestNotStringEscapeInRawLiteral1(TestHost testHost) + => TestInMethodAsync(@"var goo = """"""goo\r\nbar"""""";", testHost, Keyword("var")); - } [Theory, CombinatorialData] - public async Task TestNotStringEscapeInRawLiteral1_utf8(TestHost testHost) - { - await TestInMethodAsync(@"var goo = """"""goo\r\nbar""""""u8;", + public Task TestNotStringEscapeInRawLiteral1_utf8(TestHost testHost) + => TestInMethodAsync(@"var goo = """"""goo\r\nbar""""""u8;", testHost, Keyword("var")); - } [Theory, CombinatorialData] - public async Task TestNotStringEscapeInRawLiteral2(TestHost testHost) - { - await TestInMethodAsync("""" + public Task TestNotStringEscapeInRawLiteral2(TestHost testHost) + => TestInMethodAsync("""" var goo = """ goo\r\nbar """; """", testHost, Keyword("var")); - } [Theory, CombinatorialData] - public async Task TestNotStringEscapeInRawLiteral2_utf8(TestHost testHost) - { - await TestInMethodAsync("""" + public Task TestNotStringEscapeInRawLiteral2_utf8(TestHost testHost) + => TestInMethodAsync("""" var goo = """ goo\r\nbar """u8; """", testHost, Keyword("var")); - } [Theory, CombinatorialData] - public async Task TestNotStringEscapeInRawLiteral3(TestHost testHost) - { - await TestInMethodAsync("""" + public Task TestNotStringEscapeInRawLiteral3(TestHost testHost) + => TestInMethodAsync("""" var goo = $""" goo\r\nbar """; """", testHost, Keyword("var")); - } [Theory, CombinatorialData] - public async Task TestNotStringEscapeInRawLiteral3_utf8(TestHost testHost) - { - await TestInMethodAsync("""" + public Task TestNotStringEscapeInRawLiteral3_utf8(TestHost testHost) + => TestInMethodAsync("""" var goo = $""" goo\r\nbar """u8; """", testHost, Keyword("var")); - } [Theory, CombinatorialData] - public async Task TestNotStringEscapeInRawLiteral4(TestHost testHost) - { - await TestInMethodAsync(@"var goo = """"""\"""""";", + public Task TestNotStringEscapeInRawLiteral4(TestHost testHost) + => TestInMethodAsync(@"var goo = """"""\"""""";", testHost, Keyword("var")); - } [Theory, CombinatorialData] - public async Task TestNotStringEscapeInRawLiteral4_utf8(TestHost testHost) - { - await TestInMethodAsync(@"var goo = """"""\""""""u8;", + public Task TestNotStringEscapeInRawLiteral4_utf8(TestHost testHost) + => TestInMethodAsync(@"var goo = """"""\""""""u8;", testHost, Keyword("var")); - } [Theory, CombinatorialData] - public async Task TestNotStringEscapeInRawLiteral5(TestHost testHost) - { - await TestInMethodAsync("""" + public Task TestNotStringEscapeInRawLiteral5(TestHost testHost) + => TestInMethodAsync("""" var goo = """ \ """; """", testHost, Keyword("var")); - } [Theory, CombinatorialData] - public async Task TestNotStringEscapeInRawLiteral5_utf8(TestHost testHost) - { - await TestInMethodAsync("""" + public Task TestNotStringEscapeInRawLiteral5_utf8(TestHost testHost) + => TestInMethodAsync("""" var goo = """ \ """u8; """", testHost, Keyword("var")); - } [Theory, CombinatorialData] - public async Task TestNotStringEscapeInRawLiteral6(TestHost testHost) - { - await TestInMethodAsync("""" + public Task TestNotStringEscapeInRawLiteral6(TestHost testHost) + => TestInMethodAsync("""" var goo = $""" \ """; """", testHost, Keyword("var")); - } [Theory, CombinatorialData] - public async Task TestNotStringEscapeInRawLiteral6_utf8(TestHost testHost) - { - await TestInMethodAsync("""" + public Task TestNotStringEscapeInRawLiteral6_utf8(TestHost testHost) + => TestInMethodAsync("""" var goo = $""" \ """u8; """", testHost, Keyword("var")); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/31200")] [CombinatorialData] - public async Task TestCharEscape1(TestHost testHost) - { - await TestInMethodAsync(@"var goo = '\n';", + public Task TestCharEscape1(TestHost testHost) + => TestInMethodAsync(@"var goo = '\n';", testHost, Keyword("var"), Escape(@"\n")); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/31200")] [CombinatorialData] - public async Task TestCharEscape2(TestHost testHost) - { - await TestInMethodAsync(@"var goo = '\\';", + public Task TestCharEscape2(TestHost testHost) + => TestInMethodAsync(@"var goo = '\\';", testHost, Keyword("var"), Escape(@"\\")); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/31200")] [CombinatorialData] - public async Task TestCharEscape3(TestHost testHost) - { - await TestInMethodAsync(@"var goo = '\'';", + public Task TestCharEscape3(TestHost testHost) + => TestInMethodAsync(@"var goo = '\'';", testHost, Keyword("var"), Escape(@"\'")); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/31200")] [CombinatorialData] - public async Task TestCharEscape5(TestHost testHost) - { - await TestInMethodAsync(@"var goo = '""';", + public Task TestCharEscape5(TestHost testHost) + => TestInMethodAsync(@"var goo = '""';", testHost, Keyword("var")); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/31200")] [CombinatorialData] - public async Task TestCharEscape4(TestHost testHost) - { - await TestInMethodAsync(@"var goo = '\u000a';", + public Task TestCharEscape4(TestHost testHost) + => TestInMethodAsync(@"var goo = '\u000a';", testHost, Keyword("var"), Escape(@"\u000a")); - } [Theory, CombinatorialData] - public async Task TestEscapeFourBytesCharacter(TestHost testHost) - { - await TestAsync(""" + public Task TestEscapeFourBytesCharacter(TestHost testHost) + => TestAsync(""" class C { void M() @@ -382,12 +311,10 @@ void M() } """, testHost, Keyword("var")); - } [Theory, CombinatorialData] - public async Task TestEscapeCharacter(TestHost testHost) - { - await TestAsync(""""" + public Task TestEscapeCharacter(TestHost testHost) + => TestAsync(""""" class C { string x1 = "\xabcd"; @@ -426,13 +353,11 @@ class C Escape(""" "" """)); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/76709")] - public async Task TestEscapeCharacter2(TestHost testHost) - { - await TestAsync(""""" + public Task TestEscapeCharacter2(TestHost testHost) + => TestAsync(""""" class C { string x1 = "\x0003e"; @@ -443,5 +368,4 @@ class C Escape("\\x0003"), Escape("\\0"), Escape("\\0")); - } } diff --git a/src/EditorFeatures/CSharpTest/Classification/SemanticClassifierTests_TestMarkup.cs b/src/EditorFeatures/CSharpTest/Classification/SemanticClassifierTests_TestMarkup.cs index ad522e9d63473..07216b6570b9d 100644 --- a/src/EditorFeatures/CSharpTest/Classification/SemanticClassifierTests_TestMarkup.cs +++ b/src/EditorFeatures/CSharpTest/Classification/SemanticClassifierTests_TestMarkup.cs @@ -155,9 +155,8 @@ void M2() } [Theory, CombinatorialData] - public async Task TestEmbeddedCSharpMarkup1(TestHost testHost) - { - await TestEmbeddedCSharpAsync(""" + public Task TestEmbeddedCSharpMarkup1(TestHost testHost) + => TestEmbeddedCSharpAsync(""" class D { } @@ -168,12 +167,10 @@ class D Class("D"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestEmbeddedCSharpCaret1(TestHost testHost) - { - await TestEmbeddedCSharpAsync(""" + public Task TestEmbeddedCSharpCaret1(TestHost testHost) + => TestEmbeddedCSharpAsync(""" class D { $$ @@ -187,12 +184,10 @@ class D TestCode(" "), TestCodeMarkdown("$$"), Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestEmbeddedCSharpCaret2(TestHost testHost) - { - await TestEmbeddedCSharpAsync(""" + public Task TestEmbeddedCSharpCaret2(TestHost testHost) + => TestEmbeddedCSharpAsync(""" cla$$ss D { } @@ -205,12 +200,10 @@ await TestEmbeddedCSharpAsync(""" Class("D"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestEmbeddedCSharpSpan1(TestHost testHost) - { - await TestEmbeddedCSharpAsync(""" + public Task TestEmbeddedCSharpSpan1(TestHost testHost) + => TestEmbeddedCSharpAsync(""" class D { [|System.Int32 i;|] @@ -231,12 +224,10 @@ class D Punctuation.Semicolon, TestCodeMarkdown("|]"), Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestEmbeddedCSharpSpan2(TestHost testHost) - { - await TestEmbeddedCSharpAsync(""" + public Task TestEmbeddedCSharpSpan2(TestHost testHost) + => TestEmbeddedCSharpAsync(""" class D { {|Example:System.Int32 i;|} @@ -257,12 +248,10 @@ class D Punctuation.Semicolon, TestCodeMarkdown("|}"), Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestEmbeddedCSharpSpan3(TestHost testHost) - { - await TestEmbeddedCSharpAsync(""" + public Task TestEmbeddedCSharpSpan3(TestHost testHost) + => TestEmbeddedCSharpAsync(""" class D { [|System.Int32 i; @@ -282,12 +271,10 @@ class D Field("i"), Punctuation.Semicolon, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestEmbeddedCSharpSpan4(TestHost testHost) - { - await TestEmbeddedCSharpAsync(""" + public Task TestEmbeddedCSharpSpan4(TestHost testHost) + => TestEmbeddedCSharpAsync(""" class D { System.Int32 i;|] @@ -307,12 +294,10 @@ class D Punctuation.Semicolon, TestCodeMarkdown("|]"), Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestEmbeddedCSharpSpan5(TestHost testHost) - { - await TestEmbeddedCSharpAsync(""" + public Task TestEmbeddedCSharpSpan5(TestHost testHost) + => TestEmbeddedCSharpAsync(""" class D { {|Example:System.Int32 i; @@ -332,12 +317,10 @@ class D Field("i"), Punctuation.Semicolon, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestEmbeddedCSharpSpan6(TestHost testHost) - { - await TestEmbeddedCSharpAsync(""" + public Task TestEmbeddedCSharpSpan6(TestHost testHost) + => TestEmbeddedCSharpAsync(""" class D { System.Int32 i;|} @@ -357,12 +340,10 @@ class D Punctuation.Semicolon, TestCodeMarkdown("|}"), Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestEmbeddedCSharpSpan7(TestHost testHost) - { - await TestEmbeddedCSharpAsync(""" + public Task TestEmbeddedCSharpSpan7(TestHost testHost) + => TestEmbeddedCSharpAsync(""" class D { {|Example System.Int32 i;|} @@ -386,12 +367,10 @@ class D Punctuation.Semicolon, TestCodeMarkdown("|}"), Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestEmbeddedCSharpSpan8(TestHost testHost) - { - await TestEmbeddedCSharpAsync(""" + public Task TestEmbeddedCSharpSpan8(TestHost testHost) + => TestEmbeddedCSharpAsync(""" class D { Sys[|tem.In$$t3|]2 i; @@ -416,12 +395,10 @@ class D Field("i"), Punctuation.Semicolon, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestEmbeddedCSharpString1(TestHost testHost) - { - await TestEmbeddedCSharpAsync(""" + public Task TestEmbeddedCSharpString1(TestHost testHost) + => TestEmbeddedCSharpAsync(""" class D { // Embedded escapes not classified. @@ -442,15 +419,15 @@ class D TestCode(" "), Operators.Equals, TestCode(" "), - String(@"""\r\n"""), + String(""" + "\r\n" + """), Punctuation.Semicolon, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestEmbeddedCSharpString2(TestHost testHost) - { - await TestEmbeddedCSharpAsync("""" + public Task TestEmbeddedCSharpString2(TestHost testHost) + => TestEmbeddedCSharpAsync("""" class D { string s = """ @@ -477,27 +454,22 @@ class D """"), Punctuation.Semicolon, Punctuation.CloseCurly); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/76575")] - public async Task TestOnlyMarkup1(TestHost testHost) - { - await TestEmbeddedCSharpAsync( + public Task TestOnlyMarkup1(TestHost testHost) + => TestEmbeddedCSharpAsync( "[||]", testHost, TestCodeMarkdown("[|"), TestCodeMarkdown("|]")); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/76575")] - public async Task TestOnlyMarkup2(TestHost testHost) - { - await TestSingleLineEmbeddedCSharpAsync( + public Task TestOnlyMarkup2(TestHost testHost) + => TestSingleLineEmbeddedCSharpAsync( "[||]", testHost, TestCodeMarkdown("[|"), TestCodeMarkdown("|]")); - } } diff --git a/src/EditorFeatures/CSharpTest/Classification/SyntacticClassifierTests.cs b/src/EditorFeatures/CSharpTest/Classification/SyntacticClassifierTests.cs index 745d8c0135fb6..30da5d04139e7 100644 --- a/src/EditorFeatures/CSharpTest/Classification/SyntacticClassifierTests.cs +++ b/src/EditorFeatures/CSharpTest/Classification/SyntacticClassifierTests.cs @@ -28,9 +28,8 @@ protected override async Task> GetClassificationS } [Theory, CombinatorialData] - public async Task VarAtTypeMemberLevel(TestHost testHost) - { - await TestAsync( + public Task VarAtTypeMemberLevel(TestHost testHost) + => TestAsync( """ class C { @@ -43,12 +42,10 @@ var goo } Identifier("var"), Field("goo"), Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestNamespace(TestHost testHost) - { - await TestAsync( + public Task TestNamespace(TestHost testHost) + => TestAsync( """ namespace N { @@ -59,12 +56,10 @@ namespace N Namespace("N"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestFileScopedNamespace(TestHost testHost) - { - await TestAsync( + public Task TestFileScopedNamespace(TestHost testHost) + => TestAsync( """ namespace N; @@ -73,39 +68,31 @@ namespace N; Keyword("namespace"), Namespace("N"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task VarAsLocalVariableType(TestHost testHost) - { - await TestInMethodAsync("var goo = 42", + public Task VarAsLocalVariableType(TestHost testHost) + => TestInMethodAsync("var goo = 42", testHost, Keyword("var"), Local("goo"), Operators.Equals, Number("42")); - } [Theory, CombinatorialData] - public async Task VarOptimisticallyColored(TestHost testHost) - { - await TestInMethodAsync("var", + public Task VarOptimisticallyColored(TestHost testHost) + => TestInMethodAsync("var", testHost, Keyword("var")); - } [Theory, CombinatorialData] - public async Task VarNotColoredInClass(TestHost testHost) - { - await TestInClassAsync("var", + public Task VarNotColoredInClass(TestHost testHost) + => TestInClassAsync("var", testHost, Identifier("var")); - } [Theory, CombinatorialData] - public async Task VarInsideLocalAndExpressions(TestHost testHost) - { - await TestInMethodAsync( + public Task VarInsideLocalAndExpressions(TestHost testHost) + => TestInMethodAsync( @"var var = (var)var as var;", testHost, Keyword("var"), @@ -118,12 +105,10 @@ await TestInMethodAsync( Keyword("as"), Identifier("var"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task VarAsMethodParameter(TestHost testHost) - { - await TestAsync( + public Task VarAsMethodParameter(TestHost testHost) + => TestAsync( """ class C { @@ -145,12 +130,10 @@ void M(var v) Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task YieldYield(TestHost testHost) - { - await TestAsync( + public Task YieldYield(TestHost testHost) + => TestAsync( """ using System.Collections.Generic; @@ -196,12 +179,10 @@ IEnumerable M() Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task YieldYieldAsSpans(TestHost testHost) - { - await TestAsync( + public Task YieldYieldAsSpans(TestHost testHost) + => TestAsync( """ using System.Collections.Generic; @@ -227,22 +208,18 @@ IEnumerable M() ControlKeyword("return"), Identifier("yield"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task YieldReturn(TestHost testHost) - { - await TestInMethodAsync("yield return 42", + public Task YieldReturn(TestHost testHost) + => TestInMethodAsync("yield return 42", testHost, ControlKeyword("yield"), ControlKeyword("return"), Number("42")); - } [Theory, CombinatorialData] - public async Task YieldFixed(TestHost testHost) - { - await TestInMethodAsync( + public Task YieldFixed(TestHost testHost) + => TestInMethodAsync( """ yield return this.items[0]; yield break; fixed (int* i = 0) { } @@ -270,13 +247,11 @@ await TestInMethodAsync( Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/40741")] - public async Task TestAwait(TestHost testHost) - { - await TestAsync( + public Task TestAwait(TestHost testHost) + => TestAsync( """ using System.Threading.Tasks; @@ -312,23 +287,19 @@ async Task M() Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task PartialClass(TestHost testHost) - { - await TestAsync("public partial class Goo", + public Task PartialClass(TestHost testHost) + => TestAsync("public partial class Goo", testHost, Keyword("public"), Keyword("partial"), Keyword("class"), Class("Goo")); - } [Theory, CombinatorialData] - public async Task PartialMethod(TestHost testHost) - { - await TestInClassAsync( + public Task PartialMethod(TestHost testHost) + => TestInClassAsync( """ public partial void M() { @@ -343,16 +314,14 @@ public partial void M() Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } /// /// Partial is only valid in a type declaration /// [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536313")] - public async Task PartialAsLocalVariableType(TestHost testHost) - { - await TestInMethodAsync( + public Task PartialAsLocalVariableType(TestHost testHost) + => TestInMethodAsync( @"partial p1 = 42;", testHost, Identifier("partial"), @@ -360,12 +329,10 @@ await TestInMethodAsync( Operators.Equals, Number("42"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task PartialClassStructInterface(TestHost testHost) - { - await TestAsync( + public Task PartialClassStructInterface(TestHost testHost) + => TestAsync( """ partial class T1 { @@ -395,7 +362,6 @@ partial interface T3 Interface("T3"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } private static readonly string[] s_contextualKeywordsOnlyValidInMethods = ["where", "from", "group", "join", "select", "into", "let", "by", "orderby", "on", "equals", "ascending", "descending"]; @@ -415,61 +381,52 @@ await TestInNamespaceAsync(kw + " goo", } [Theory, CombinatorialData] - public async Task VerbatimStringLiterals1(TestHost testHost) - { - await TestInMethodAsync(""" + public Task VerbatimStringLiterals1(TestHost testHost) + => TestInMethodAsync(""" @"goo" """, testHost, Verbatim(""" @"goo" """)); - } [Theory, CombinatorialData] - public async Task VerbatimStringLiteralsUtf8_01(TestHost testHost) - { - await TestInMethodAsync(@"@""goo""u8", + public Task VerbatimStringLiteralsUtf8_01(TestHost testHost) + => TestInMethodAsync(@"@""goo""u8", testHost, Verbatim(""" @"goo" """), Keyword("u8")); - } [Theory, CombinatorialData] - public async Task VerbatimStringLiteralsUtf8_02(TestHost testHost) - { - await TestInMethodAsync(@"@""goo""U8", + public Task VerbatimStringLiteralsUtf8_02(TestHost testHost) + => TestInMethodAsync(@"@""goo""U8", testHost, Verbatim(""" @"goo" """), Keyword("U8")); - } /// /// Should show up as soon as we get the @\" typed out /// [Theory, CombinatorialData] - public async Task VerbatimStringLiterals2(TestHost testHost) - { - await TestAsync(""" + public Task VerbatimStringLiterals2(TestHost testHost) + => TestAsync(""" @" """, testHost, Verbatim(""" @" """)); - } /// /// Parser does not currently support strings of this type /// [Theory, CombinatorialData] - public async Task VerbatimStringLiterals3(TestHost testHost) - { - await TestAsync(""" + public Task VerbatimStringLiterals3(TestHost testHost) + => TestAsync(""" goo @" """, testHost, @@ -477,42 +434,36 @@ goo @" Verbatim(""" @" """)); - } /// /// Uncompleted ones should span new lines /// [Theory, CombinatorialData] - public async Task VerbatimStringLiterals4(TestHost testHost) - { - var code = """ + public Task VerbatimStringLiterals4(TestHost testHost) + => TestAsync(""" @" goo bar - """; - await TestAsync(code, + """, testHost, Verbatim(""" @" goo bar """)); - } [Theory, CombinatorialData] - public async Task VerbatimStringLiterals5(TestHost testHost) - { - var code = """ + public Task VerbatimStringLiterals5(TestHost testHost) + => TestInMethodAsync(""" @" goo bar and on a new line " more stuff - """; - await TestInMethodAsync(code, + """, testHost, Verbatim(""" @" goo bar @@ -521,20 +472,17 @@ await TestInMethodAsync(code, """), Identifier("more"), Local("stuff")); - } [Theory, CombinatorialData] - public async Task VerbatimStringLiteralsUtf8_03(TestHost testHost) - { - var code = """ + public Task VerbatimStringLiteralsUtf8_03(TestHost testHost) + => TestInMethodAsync(""" @" goo bar and on a new line "u8 more stuff - """; - await TestInMethodAsync(code, + """, testHost, Verbatim(""" @" goo bar @@ -544,20 +492,17 @@ await TestInMethodAsync(code, Keyword("u8"), Identifier("more"), Local("stuff")); - } [Theory, CombinatorialData] - public async Task VerbatimStringLiteralsUtf8_04(TestHost testHost) - { - var code = """ + public Task VerbatimStringLiteralsUtf8_04(TestHost testHost) + => TestInMethodAsync(""" @" goo bar and on a new line "U8 more stuff - """; - await TestInMethodAsync(code, + """, testHost, Verbatim(""" @" goo bar @@ -567,7 +512,6 @@ await TestInMethodAsync(code, Keyword("U8"), Identifier("more"), Local("stuff")); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] @@ -636,21 +580,18 @@ await TestAsync( } [Theory, CombinatorialData] - public async Task StringLiteral1(TestHost testHost) - { - await TestAsync(""" + public Task StringLiteral1(TestHost testHost) + => TestAsync(""" "goo" """, testHost, String(""" "goo" """)); - } [Theory, CombinatorialData] - public async Task StringLiteralUtf8_01(TestHost testHost) - { - await TestAsync(""" + public Task StringLiteralUtf8_01(TestHost testHost) + => TestAsync(""" "goo"u8 """, testHost, @@ -658,12 +599,10 @@ await TestAsync(""" "goo" """), Keyword("u8")); - } [Theory, CombinatorialData] - public async Task StringLiteralUtf8_02(TestHost testHost) - { - await TestAsync(""" + public Task StringLiteralUtf8_02(TestHost testHost) + => TestAsync(""" "goo"U8 """, testHost, @@ -671,24 +610,20 @@ await TestAsync(""" "goo" """), Keyword("U8")); - } [Theory, CombinatorialData] - public async Task StringLiteral2(TestHost testHost) - { - await TestAsync(""" + public Task StringLiteral2(TestHost testHost) + => TestAsync(""" "" """, testHost, String(""" "" """)); - } [Theory, CombinatorialData] - public async Task StringLiteralUtf8_03(TestHost testHost) - { - await TestAsync(""" + public Task StringLiteralUtf8_03(TestHost testHost) + => TestAsync(""" ""u8 """, testHost, @@ -696,12 +631,10 @@ await TestAsync(""" "" """), Keyword("u8")); - } [Theory, CombinatorialData] - public async Task StringLiteralUtf8_04(TestHost testHost) - { - await TestAsync(""" + public Task StringLiteralUtf8_04(TestHost testHost) + => TestAsync(""" ""U8 """, testHost, @@ -709,34 +642,25 @@ await TestAsync(""" "" """), Keyword("U8")); - } [Theory, CombinatorialData] - public async Task CharacterLiteral1(TestHost testHost) - { - var code = @"'f'"; - await TestInMethodAsync(code, + public Task CharacterLiteral1(TestHost testHost) + => TestInMethodAsync(@"'f'", testHost, String("'f'")); - } [Theory, CombinatorialData] - public async Task LinqFrom1(TestHost testHost) - { - var code = @"from it in goo"; - await TestInExpressionAsync(code, + public Task LinqFrom1(TestHost testHost) + => TestInExpressionAsync(@"from it in goo", testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo")); - } [Theory, CombinatorialData] - public async Task LinqFrom2(TestHost testHost) - { - var code = @"from it in goo.Bar()"; - await TestInExpressionAsync(code, + public Task LinqFrom2(TestHost testHost) + => TestInExpressionAsync(@"from it in goo.Bar()", testHost, Keyword("from"), Identifier("it"), @@ -746,36 +670,26 @@ await TestInExpressionAsync(code, Identifier("Bar"), Punctuation.OpenParen, Punctuation.CloseParen); - } [Theory, CombinatorialData] - public async Task LinqFrom3(TestHost testHost) - { - // query expression are not statement expressions, but the parser parses them anyways to give better errors - var code = @"from it in "; - await TestInMethodAsync(code, + public Task LinqFrom3(TestHost testHost) + => TestInMethodAsync(@"from it in ", testHost, Keyword("from"), Identifier("it"), Keyword("in")); - } [Theory, CombinatorialData] - public async Task LinqFrom4(TestHost testHost) - { - var code = @"from it in "; - await TestInExpressionAsync(code, + public Task LinqFrom4(TestHost testHost) + => TestInExpressionAsync(@"from it in ", testHost, Keyword("from"), Identifier("it"), Keyword("in")); - } [Theory, CombinatorialData] - public async Task LinqWhere1(TestHost testHost) - { - var code = "from it in goo where it > 42"; - await TestInExpressionAsync(code, + public Task LinqWhere1(TestHost testHost) + => TestInExpressionAsync("from it in goo where it > 42", testHost, Keyword("from"), Identifier("it"), @@ -785,15 +699,12 @@ await TestInExpressionAsync(code, Identifier("it"), Operators.GreaterThan, Number("42")); - } [Theory, CombinatorialData] - public async Task LinqWhere2(TestHost testHost) - { - var code = """ + public Task LinqWhere2(TestHost testHost) + => TestInExpressionAsync(""" from it in goo where it > "bar" - """; - await TestInExpressionAsync(code, + """, testHost, Keyword("from"), Identifier("it"), @@ -805,7 +716,6 @@ await TestInExpressionAsync(code, String(""" "bar" """)); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] @@ -887,9 +797,8 @@ await TestAsync( } [Theory, CombinatorialData] - public async Task ContextualKeywordsAsFieldName(TestHost testHost) - { - await TestAsync( + public Task ContextualKeywordsAsFieldName(TestHost testHost) + => TestAsync( """ class C { @@ -922,12 +831,10 @@ class C Field("alias"), Punctuation.Semicolon, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task LinqKeywordsInFieldInitializer(TestHost testHost) - { - await TestAsync( + public Task LinqKeywordsInFieldInitializer(TestHost testHost) + => TestAsync( """ class C { @@ -981,12 +888,10 @@ where a Identifier("a"), Punctuation.Semicolon, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task LinqKeywordsAsTypeName(TestHost testHost) - { - await TestAsync( + public Task LinqKeywordsAsTypeName(TestHost testHost) + => TestAsync( """ class var { @@ -1098,12 +1003,10 @@ class select Class("select"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task LinqKeywordsAsMethodParameters(TestHost testHost) - { - await TestAsync( + public Task LinqKeywordsAsMethodParameters(TestHost testHost) + => TestAsync( """ class C { @@ -1164,12 +1067,10 @@ orderby M(var goo, from goo, join goo, on goo, equals goo, group goo, by goo, in Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task LinqKeywordsInLocalVariableDeclarations(TestHost testHost) - { - await TestAsync( + public Task LinqKeywordsInLocalVariableDeclarations(TestHost testHost) + => TestAsync( """ class C { @@ -1321,12 +1222,10 @@ void M() Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task LinqKeywordsAsFieldNames(TestHost testHost) - { - await TestAsync( + public Task LinqKeywordsAsFieldNames(TestHost testHost) + => TestAsync( """ class C { @@ -1367,12 +1266,10 @@ class C Field("partial"), Punctuation.Semicolon, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task LinqKeywordsAtFieldLevelInvalid(TestHost testHost) - { - await TestAsync( + public Task LinqKeywordsAtFieldLevelInvalid(TestHost testHost) + => TestAsync( """ class C { @@ -1422,41 +1319,31 @@ class C Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task CommentSingle(TestHost testHost) - { - var code = "// goo"; - - await TestAsync(code, + public Task CommentSingle(TestHost testHost) + => TestAsync("// goo", testHost, Comment("// goo")); - } [Theory, CombinatorialData] - public async Task CommentAsTrailingTrivia1(TestHost testHost) - { - var code = "class Bar { // goo"; - await TestAsync(code, + public Task CommentAsTrailingTrivia1(TestHost testHost) + => TestAsync("class Bar { // goo", testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Comment("// goo")); - } [Theory, CombinatorialData] - public async Task CommentAsLeadingTrivia1(TestHost testHost) - { - var code = """ + public Task CommentAsLeadingTrivia1(TestHost testHost) + => TestAsync(""" class Bar { // goo void Method1() { } } - """; - await TestAsync(code, + """, testHost, Keyword("class"), Class("Bar"), @@ -1469,7 +1356,6 @@ await TestAsync(code, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] public async Task ShebangAsFirstCommentInScript(TestHost testHost) @@ -1544,9 +1430,8 @@ public async Task ShebangNotAsFirstCommentInScript(TestHost testHost) } [Theory, CombinatorialData] - public async Task IgnoredDirective_01(TestHost testHost) - { - await TestAsync(""" + public Task IgnoredDirective_01(TestHost testHost) + => TestAsync(""" #:unknown // comment Console.Write(); """, @@ -1561,12 +1446,10 @@ await TestAsync(""" Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task IgnoredDirective_02(TestHost testHost) - { - await TestAsync(""" + public Task IgnoredDirective_02(TestHost testHost) + => TestAsync(""" #:sdk Test 2.1.0 Console.Write(); """, @@ -1581,12 +1464,10 @@ await TestAsync(""" Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task IgnoredDirective_03(TestHost testHost) - { - await TestAsync(""" + public Task IgnoredDirective_03(TestHost testHost) + => TestAsync(""" #:no-space Console.Write(); """, @@ -1600,12 +1481,10 @@ await TestAsync(""" Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task IgnoredDirective_04(TestHost testHost) - { - await TestAsync($""" + public Task IgnoredDirective_04(TestHost testHost) + => TestAsync($""" #:sdk{'\t'}Test 2.1.0 Console.Write(); """, @@ -1620,20 +1499,17 @@ await TestAsync($""" Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task CommentAsMethodBodyContent(TestHost testHost) - { - var code = """ + public Task CommentAsMethodBodyContent(TestHost testHost) + => TestAsync(""" class Bar { void Method1() { // goo } } - """; - await TestAsync(code, + """, testHost, Keyword("class"), Class("Bar"), @@ -1646,12 +1522,10 @@ await TestAsync(code, Comment("// goo"), Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task CommentMix1(TestHost testHost) - { - await TestAsync( + public Task CommentMix1(TestHost testHost) + => TestAsync( """ // comment1 /* class cl @@ -1666,12 +1540,10 @@ class cl Punctuation.OpenCurly, Punctuation.CloseCurly, Comment("//comment2 */")); - } [Theory, CombinatorialData] - public async Task CommentMix2(TestHost testHost) - { - await TestInMethodAsync( + public Task CommentMix2(TestHost testHost) + => TestInMethodAsync( @"/**/int /**/i = 0;", testHost, Comment("/**/"), @@ -1681,17 +1553,14 @@ await TestInMethodAsync( Operators.Equals, Number("0"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task XmlDocCommentOnClass(TestHost testHost) - { - var code = """ + public Task XmlDocCommentOnClass(TestHost testHost) + => TestAsync(""" /// something class Bar { } - """; - await TestAsync(code, + """, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), @@ -1706,19 +1575,16 @@ await TestAsync(code, Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task XmlDocCommentOnClassWithIndent(TestHost testHost) - { - var code = """ + public Task XmlDocCommentOnClassWithIndent(TestHost testHost) + => TestAsync(""" /// /// something /// class Bar { } - """; - await TestAsync(code, + """, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), @@ -1736,17 +1602,14 @@ await TestAsync(code, Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task XmlDocComment_EntityReference(TestHost testHost) - { - var code = """ + public Task XmlDocComment_EntityReference(TestHost testHost) + => TestAsync(""" /// A class Bar { } - """; - await TestAsync(code, + """, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), @@ -1761,18 +1624,15 @@ await TestAsync(code, Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task XmlDocComment_ExteriorTriviaInsideCloseTag(TestHost testHost) - { - var code = """ + public Task XmlDocComment_ExteriorTriviaInsideCloseTag(TestHost testHost) + => TestAsync(""" /// something class Bar { } - """; - await TestAsync(code, + """, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), @@ -1788,7 +1648,6 @@ await TestAsync(code, Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory] [InlineData(TestHost.InProcess, "true", false)] @@ -1797,9 +1656,8 @@ await TestAsync(code, [InlineData(TestHost.OutOfProcess, "return", true)] [InlineData(TestHost.InProcess, "with", false)] [InlineData(TestHost.OutOfProcess, "with", false)] - public async Task XmlDocComment_LangWordAttribute_Keywords(TestHost testHost, string langword, bool isControlKeyword) - { - await TestAsync( + public Task XmlDocComment_LangWordAttribute_Keywords(TestHost testHost, string langword, bool isControlKeyword) + => TestAsync( $$""" /// /// @@ -1820,9 +1678,13 @@ class MyClass XmlDoc.Name("see"), XmlDoc.AttributeName("langword"), XmlDoc.Delimiter("="), - XmlDoc.AttributeQuotes("\""), + XmlDoc.AttributeQuotes(""" + " + """), isControlKeyword ? ControlKeyword(langword) : Keyword(langword), - XmlDoc.AttributeQuotes("\""), + XmlDoc.AttributeQuotes(""" + " + """), XmlDoc.Delimiter("/>"), XmlDoc.Delimiter("///"), XmlDoc.Text(" "), @@ -1833,12 +1695,10 @@ class MyClass Class("MyClass"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task XmlDocComment_LangWordAttribute_NonKeyword(TestHost testHost) - { - await TestAsync( + public Task XmlDocComment_LangWordAttribute_NonKeyword(TestHost testHost) + => TestAsync( """ /// /// @@ -1858,9 +1718,13 @@ class MyClass XmlDoc.Name("see"), XmlDoc.AttributeName("langword"), XmlDoc.Delimiter("="), - XmlDoc.AttributeQuotes("\""), + XmlDoc.AttributeQuotes(""" + " + """), XmlDoc.AttributeValue("MyWord"), - XmlDoc.AttributeQuotes("\""), + XmlDoc.AttributeQuotes(""" + " + """), XmlDoc.Delimiter("/>"), XmlDoc.Delimiter("///"), XmlDoc.Text(" "), @@ -1871,21 +1735,18 @@ class MyClass Class("MyClass"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531155")] [CombinatorialData] - public async Task XmlDocComment_ExteriorTriviaInsideCRef(TestHost testHost) - { - var code = """ + public Task XmlDocComment_ExteriorTriviaInsideCRef(TestHost testHost) + => TestAsync(""" /// class C { } - """; - await TestAsync(code, + """, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), @@ -1908,19 +1769,16 @@ await TestAsync(code, Class("C"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task XmlDocCommentOnClassWithExteriorTrivia(TestHost testHost) - { - var code = """ + public Task XmlDocCommentOnClassWithExteriorTrivia(TestHost testHost) + => TestAsync(""" /// /// something /// class Bar { } - """; - await TestAsync(code, + """, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), @@ -1938,19 +1796,15 @@ await TestAsync(code, Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task XmlDocComment_ExteriorTriviaNoText(TestHost testHost) - { - var code = - """ + public Task XmlDocComment_ExteriorTriviaNoText(TestHost testHost) + => TestAsync(""" /// ///something /// class Bar { } - """; - await TestAsync(code, + """, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), @@ -1966,17 +1820,14 @@ await TestAsync(code, Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task XmlDocComment_EmptyElement(TestHost testHost) - { - var code = """ + public Task XmlDocComment_EmptyElement(TestHost testHost) + => TestAsync(""" /// class Bar { } - """; - await TestAsync(code, + """, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), @@ -1987,18 +1838,14 @@ await TestAsync(code, Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task XmlDocComment_Attribute(TestHost testHost) - { - var code = """ + public Task XmlDocComment_Attribute(TestHost testHost) + => TestAsync(""" /// something class Bar { } - """; - - await TestAsync(code, + """, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), @@ -2022,17 +1869,14 @@ await TestAsync(code, Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task XmlDocComment_AttributeInEmptyElement(TestHost testHost) - { - var code = """ + public Task XmlDocComment_AttributeInEmptyElement(TestHost testHost) + => TestAsync(""" /// class Bar { } - """; - await TestAsync(code, + """, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), @@ -2052,17 +1896,14 @@ await TestAsync(code, Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task XmlDocComment_ExtraSpaces(TestHost testHost) - { - var code = """ + public Task XmlDocComment_ExtraSpaces(TestHost testHost) + => TestAsync(""" /// < summary attribute = "value" /> class Bar { } - """; - await TestAsync(code, + """, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), @@ -2082,17 +1923,14 @@ await TestAsync(code, Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task XmlDocComment_XmlComment(TestHost testHost) - { - var code = """ + public Task XmlDocComment_XmlComment(TestHost testHost) + => TestAsync(""" /// class Bar { } - """; - await TestAsync(code, + """, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter(" class Bar { } - """; - await TestAsync(code, + """, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter(" class Bar { } - """; - await TestAsync(code, + """, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), @@ -2151,20 +1983,17 @@ await TestAsync(code, Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/pull/31410")] - public async Task XmlDocComment_MalformedXmlDocComment(TestHost testHost) - { - var code = """ + public Task XmlDocComment_MalformedXmlDocComment(TestHost testHost) + => TestAsync(""" /// ///. /// class C { } - """; - await TestAsync(code, + """, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), @@ -2187,19 +2016,15 @@ await TestAsync(code, Class("C"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task MultilineXmlDocComment_ExteriorTrivia(TestHost testHost) - { - var code = - """ + public Task MultilineXmlDocComment_ExteriorTrivia(TestHost testHost) + => TestAsync(""" /** *comment **/ class Bar { } - """; - await TestAsync(code, + """, testHost, XmlDoc.Delimiter("/**"), XmlDoc.Delimiter("<"), @@ -2216,18 +2041,15 @@ await TestAsync(code, Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task XmlDocComment_CDataWithExteriorTrivia(TestHost testHost) - { - var code = """ + public Task XmlDocComment_CDataWithExteriorTrivia(TestHost testHost) + => TestAsync(""" /// class Bar { } - """; - await TestAsync(code, + """, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter(" TestAsync( """ /// @@ -2282,14 +2102,11 @@ static void Main() Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536321")] - public async Task KeywordTypeParameters(TestHost testHost) - { - var code = @"class C { }"; - await TestAsync(code, + public Task KeywordTypeParameters(TestHost testHost) + => TestAsync(@"class C { }", testHost, Keyword("class"), Class("C"), @@ -2298,14 +2115,11 @@ await TestAsync(code, Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536853")] - public async Task TypeParametersWithAttribute(TestHost testHost) - { - var code = @"class C<[Attr] T> { }"; - await TestAsync(code, + public Task TypeParametersWithAttribute(TestHost testHost) + => TestAsync(@"class C<[Attr] T> { }", testHost, Keyword("class"), Class("C"), @@ -2317,74 +2131,56 @@ await TestAsync(code, Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task ClassTypeDeclaration1(TestHost testHost) - { - var code = "class C1 { } "; - await TestAsync(code, + public Task ClassTypeDeclaration1(TestHost testHost) + => TestAsync("class C1 { } ", testHost, Keyword("class"), Class("C1"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task ClassTypeDeclaration2(TestHost testHost) - { - var code = "class ClassName1 { } "; - await TestAsync(code, + public Task ClassTypeDeclaration2(TestHost testHost) + => TestAsync("class ClassName1 { } ", testHost, Keyword("class"), Class("ClassName1"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task StructTypeDeclaration1(TestHost testHost) - { - var code = "struct Struct1 { }"; - await TestAsync(code, + public Task StructTypeDeclaration1(TestHost testHost) + => TestAsync("struct Struct1 { }", testHost, Keyword("struct"), Struct("Struct1"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task InterfaceDeclaration1(TestHost testHost) - { - var code = "interface I1 { }"; - await TestAsync(code, + public Task InterfaceDeclaration1(TestHost testHost) + => TestAsync("interface I1 { }", testHost, Keyword("interface"), Interface("I1"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task EnumDeclaration1(TestHost testHost) - { - var code = "enum Weekday { }"; - await TestAsync(code, + public Task EnumDeclaration1(TestHost testHost) + => TestAsync("enum Weekday { }", testHost, Keyword("enum"), Enum("Weekday"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, WorkItem(4302, "DevDiv_Projects/Roslyn")] [CombinatorialData] - public async Task ClassInEnum(TestHost testHost) - { - var code = "enum E { Min = System.Int32.MinValue }"; - await TestAsync(code, + public Task ClassInEnum(TestHost testHost) + => TestAsync("enum E { Min = System.Int32.MinValue }", testHost, Keyword("enum"), Enum("E"), @@ -2397,13 +2193,10 @@ await TestAsync(code, Operators.Dot, Identifier("MinValue"), Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task DelegateDeclaration1(TestHost testHost) - { - var code = "delegate void Action();"; - await TestAsync(code, + public Task DelegateDeclaration1(TestHost testHost) + => TestAsync("delegate void Action();", testHost, Keyword("delegate"), Keyword("void"), @@ -2411,12 +2204,10 @@ await TestAsync(code, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task GenericTypeArgument(TestHost testHost) - { - await TestInMethodAsync( + public Task GenericTypeArgument(TestHost testHost) + => TestInMethodAsync( "C", "M", "default(T)", @@ -2425,13 +2216,10 @@ await TestInMethodAsync( Punctuation.OpenParen, Identifier("T"), Punctuation.CloseParen); - } [Theory, CombinatorialData] - public async Task GenericParameter(TestHost testHost) - { - var code = "class C1 {}"; - await TestAsync(code, + public Task GenericParameter(TestHost testHost) + => TestAsync("class C1 {}", testHost, Keyword("class"), Class("C1"), @@ -2440,13 +2228,10 @@ await TestAsync(code, Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task GenericParameters(TestHost testHost) - { - var code = "class C1 {}"; - await TestAsync(code, + public Task GenericParameters(TestHost testHost) + => TestAsync("class C1 {}", testHost, Keyword("class"), Class("C1"), @@ -2457,13 +2242,10 @@ await TestAsync(code, Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task GenericParameter_Interface(TestHost testHost) - { - var code = "interface I1 {}"; - await TestAsync(code, + public Task GenericParameter_Interface(TestHost testHost) + => TestAsync("interface I1 {}", testHost, Keyword("interface"), Interface("I1"), @@ -2472,13 +2254,10 @@ await TestAsync(code, Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task GenericParameter_Struct(TestHost testHost) - { - var code = "struct S1 {}"; - await TestAsync(code, + public Task GenericParameter_Struct(TestHost testHost) + => TestAsync("struct S1 {}", testHost, Keyword("struct"), Struct("S1"), @@ -2487,13 +2266,10 @@ await TestAsync(code, Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task GenericParameter_Delegate(TestHost testHost) - { - var code = "delegate void D1 {}"; - await TestAsync(code, + public Task GenericParameter_Delegate(TestHost testHost) + => TestAsync("delegate void D1 {}", testHost, Keyword("delegate"), Keyword("void"), @@ -2503,12 +2279,10 @@ await TestAsync(code, Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task GenericParameter_Method(TestHost testHost) - { - await TestInClassAsync( + public Task GenericParameter_Method(TestHost testHost) + => TestInClassAsync( """ T M(T t) { @@ -2533,24 +2307,20 @@ T M(T t) Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TernaryExpression(TestHost testHost) - { - await TestInExpressionAsync("true ? 1 : 0", + public Task TernaryExpression(TestHost testHost) + => TestInExpressionAsync("true ? 1 : 0", testHost, Keyword("true"), Operators.QuestionMark, Number("1"), Operators.Colon, Number("0")); - } [Theory, CombinatorialData] - public async Task BaseClass(TestHost testHost) - { - await TestAsync( + public Task BaseClass(TestHost testHost) + => TestAsync( """ class C : B { @@ -2563,21 +2333,17 @@ class C : B Identifier("B"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestLabel(TestHost testHost) - { - await TestInMethodAsync("goo:", + public Task TestLabel(TestHost testHost) + => TestInMethodAsync("goo:", testHost, Label("goo"), Punctuation.Colon); - } [Theory, CombinatorialData] - public async Task Attribute(TestHost testHost) - { - await TestAsync( + public Task Attribute(TestHost testHost) + => TestAsync( @"[assembly: Goo]", testHost, Punctuation.OpenBracket, @@ -2585,12 +2351,10 @@ await TestAsync( Punctuation.Colon, Identifier("Goo"), Punctuation.CloseBracket); - } [Theory, CombinatorialData] - public async Task TestAngleBracketsOnGenericConstraints_Bug932262(TestHost testHost) - { - await TestAsync( + public Task TestAngleBracketsOnGenericConstraints_Bug932262(TestHost testHost) + => TestAsync( """ class C where T : A { @@ -2611,58 +2375,48 @@ class C where T : A Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestYieldPositive(TestHost testHost) - { - await TestInMethodAsync( + public Task TestYieldPositive(TestHost testHost) + => TestInMethodAsync( @"yield return goo;", testHost, ControlKeyword("yield"), ControlKeyword("return"), Identifier("goo"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestYieldNegative(TestHost testHost) - { - await TestInMethodAsync( + public Task TestYieldNegative(TestHost testHost) + => TestInMethodAsync( @"int yield;", testHost, Keyword("int"), Local("yield"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestFromPositive(TestHost testHost) - { - await TestInExpressionAsync( + public Task TestFromPositive(TestHost testHost) + => TestInExpressionAsync( @"from x in y", testHost, Keyword("from"), Identifier("x"), Keyword("in"), Identifier("y")); - } [Theory, CombinatorialData] - public async Task TestFromNegative(TestHost testHost) - { - await TestInMethodAsync( + public Task TestFromNegative(TestHost testHost) + => TestInMethodAsync( @"int from;", testHost, Keyword("int"), Local("from"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task AttributeTargetSpecifiersModule(TestHost testHost) - { - await TestAsync( + public Task AttributeTargetSpecifiersModule(TestHost testHost) + => TestAsync( @"[module: Obsolete]", testHost, Punctuation.OpenBracket, @@ -2670,12 +2424,10 @@ await TestAsync( Punctuation.Colon, Identifier("Obsolete"), Punctuation.CloseBracket); - } [Theory, CombinatorialData] - public async Task AttributeTargetSpecifiersAssembly(TestHost testHost) - { - await TestAsync( + public Task AttributeTargetSpecifiersAssembly(TestHost testHost) + => TestAsync( @"[assembly: Obsolete]", testHost, Punctuation.OpenBracket, @@ -2683,12 +2435,10 @@ await TestAsync( Punctuation.Colon, Identifier("Obsolete"), Punctuation.CloseBracket); - } [Theory, CombinatorialData] - public async Task AttributeTargetSpecifiersOnDelegate(TestHost testHost) - { - await TestInClassAsync( + public Task AttributeTargetSpecifiersOnDelegate(TestHost testHost) + => TestInClassAsync( """ [type: A] [return: A] @@ -2711,12 +2461,10 @@ await TestInClassAsync( Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task AttributeTargetSpecifiersOnMethod(TestHost testHost) - { - await TestInClassAsync( + public Task AttributeTargetSpecifiersOnMethod(TestHost testHost) + => TestInClassAsync( """ [return: A] [method: A] @@ -2741,12 +2489,10 @@ void M() Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task AttributeTargetSpecifiersOnCtor(TestHost testHost) - { - await TestAsync( + public Task AttributeTargetSpecifiersOnCtor(TestHost testHost) + => TestAsync( """ class C { @@ -2771,12 +2517,10 @@ class C Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task AttributeTargetSpecifiersOnDtor(TestHost testHost) - { - await TestAsync( + public Task AttributeTargetSpecifiersOnDtor(TestHost testHost) + => TestAsync( """ class C { @@ -2802,12 +2546,10 @@ class C Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task AttributeTargetSpecifiersOnOperator(TestHost testHost) - { - await TestInClassAsync( + public Task AttributeTargetSpecifiersOnOperator(TestHost testHost) + => TestInClassAsync( """ [method: A] [return: A] @@ -2839,12 +2581,10 @@ await TestInClassAsync( Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task AttributeTargetSpecifiersOnEventDeclaration(TestHost testHost) - { - await TestInClassAsync( + public Task AttributeTargetSpecifiersOnEventDeclaration(TestHost testHost) + => TestInClassAsync( """ [event: A] event A E @@ -2899,12 +2639,10 @@ event A E Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task AttributeTargetSpecifiersOnPropertyAccessors(TestHost testHost) - { - await TestInClassAsync( + public Task AttributeTargetSpecifiersOnPropertyAccessors(TestHost testHost) + => TestInClassAsync( """ int P { @@ -2952,12 +2690,10 @@ int P Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task AttributeTargetSpecifiersOnIndexers(TestHost testHost) - { - await TestInClassAsync( + public Task AttributeTargetSpecifiersOnIndexers(TestHost testHost) + => TestInClassAsync( """ [property: A] int this[int i] { get; set; } @@ -2980,12 +2716,10 @@ await TestInClassAsync( Keyword("set"), Punctuation.Semicolon, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task AttributeTargetSpecifiersOnIndexerAccessors(TestHost testHost) - { - await TestInClassAsync( + public Task AttributeTargetSpecifiersOnIndexerAccessors(TestHost testHost) + => TestInClassAsync( """ int this[int i] { @@ -3037,12 +2771,10 @@ int this[int i] Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task AttributeTargetSpecifiersOnField(TestHost testHost) - { - await TestInClassAsync( + public Task AttributeTargetSpecifiersOnField(TestHost testHost) + => TestInClassAsync( """ [field: A] const int a = 0; @@ -3060,12 +2792,10 @@ await TestInClassAsync( Operators.Equals, Number("0"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestAllKeywords(TestHost testHost) - { - await TestAsync( + public Task TestAllKeywords(TestHost testHost) + => TestAsync( """ using System; #region TaoRegion @@ -3778,12 +3508,10 @@ [new CSharpParseOptions(LanguageVersion.CSharp8)], PPKeyword("#"), PPKeyword("endregion"), PPText("TaoRegion")); - } [Theory, CombinatorialData] - public async Task TestAllOperators(TestHost testHost) - { - await TestAsync( + public Task TestAllOperators(TestHost testHost) + => TestAsync( """ using IO = System.IO; @@ -4112,12 +3840,10 @@ public void method() Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestPartialMethodWithNamePartial(TestHost testHost) - { - await TestAsync( + public Task TestPartialMethodWithNamePartial(TestHost testHost) + => TestAsync( """ partial class C { @@ -4177,12 +3903,10 @@ public partial void partial void Field("partial"), Keyword("void"), Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task ValueInSetterAndAnonymousTypePropertyName(TestHost testHost) - { - await TestAsync( + public Task ValueInSetterAndAnonymousTypePropertyName(TestHost testHost) + => TestAsync( """ class C { @@ -4217,13 +3941,11 @@ int P Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538680")] [CombinatorialData] - public async Task TestValueInLabel(TestHost testHost) - { - await TestAsync( + public Task TestValueInLabel(TestHost testHost) + => TestAsync( """ class C { @@ -4252,13 +3974,11 @@ int X Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541150")] [CombinatorialData] - public async Task TestGenericVar(TestHost testHost) - { - await TestAsync( + public Task TestGenericVar(TestHost testHost) + => TestAsync( """ using System; @@ -4304,13 +4024,11 @@ class var Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541154")] [CombinatorialData] - public async Task TestInaccessibleVar(TestHost testHost) - { - await TestAsync( + public Task TestInaccessibleVar(TestHost testHost) + => TestAsync( """ using System; @@ -4361,13 +4079,11 @@ static void Main() Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541613")] [CombinatorialData] - public async Task TestEscapedVar(TestHost testHost) - { - await TestAsync( + public Task TestEscapedVar(TestHost testHost) + => TestAsync( """ class Program { @@ -4399,13 +4115,11 @@ static void Main(string[] args) Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542432")] [CombinatorialData] - public async Task TestVar(TestHost testHost) - { - await TestAsync( + public Task TestVar(TestHost testHost) + => TestAsync( """ class Program { @@ -4477,13 +4191,11 @@ static void Main() Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543123")] [CombinatorialData] - public async Task TestVar2(TestHost testHost) - { - await TestAsync( + public Task TestVar2(TestHost testHost) + => TestAsync( """ class Program { @@ -4519,18 +4231,15 @@ void Main(string[] args) Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task InterpolatedStrings1(TestHost testHost) - { - var code = """ + public Task InterpolatedStrings1(TestHost testHost) + => TestInMethodAsync(""" var x = "World"; var y = $"Hello, {x}"; - """; - await TestInMethodAsync(code, + """, testHost, Keyword("var"), Local("x"), @@ -4553,19 +4262,16 @@ await TestInMethodAsync(code, " """), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task InterpolatedStrings2(TestHost testHost) - { - var code = """ + public Task InterpolatedStrings2(TestHost testHost) + => TestInMethodAsync(""" var a = "Hello"; var b = "World"; var c = $"{a}, {b}"; - """; - await TestInMethodAsync(code, + """, testHost, Keyword("var"), Local("a"), @@ -4598,19 +4304,16 @@ await TestInMethodAsync(code, " """), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task InterpolatedStrings3(TestHost testHost) - { - var code = """ + public Task InterpolatedStrings3(TestHost testHost) + => TestInMethodAsync(""" var a = "Hello"; var b = "World"; var c = $@"{a}, {b}"; - """; - await TestInMethodAsync(code, + """, testHost, Keyword("var"), Local("a"), @@ -4643,12 +4346,10 @@ await TestInMethodAsync(code, " """), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task ExceptionFilter1(TestHost testHost) - { - var code = """ + public Task ExceptionFilter1(TestHost testHost) + => TestInMethodAsync(""" try { @@ -4657,8 +4358,7 @@ public async Task ExceptionFilter1(TestHost testHost) { } - """; - await TestInMethodAsync(code, + """, testHost, ControlKeyword("try"), Punctuation.OpenCurly, @@ -4670,12 +4370,10 @@ await TestInMethodAsync(code, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task ExceptionFilter2(TestHost testHost) - { - var code = """ + public Task ExceptionFilter2(TestHost testHost) + => TestInMethodAsync(""" try { @@ -4684,8 +4382,7 @@ public async Task ExceptionFilter2(TestHost testHost) { } - """; - await TestInMethodAsync(code, + """, testHost, ControlKeyword("try"), Punctuation.OpenCurly, @@ -4702,16 +4399,13 @@ await TestInMethodAsync(code, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task OutVar(TestHost testHost) - { - var code = """ + public Task OutVar(TestHost testHost) + => TestInMethodAsync(""" F(out var); - """; - await TestInMethodAsync(code, + """, testHost, Identifier("F"), Punctuation.OpenParen, @@ -4719,51 +4413,42 @@ await TestInMethodAsync(code, Identifier("var"), Punctuation.CloseParen, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task ReferenceDirective(TestHost testHost) - { - var code = """ + public Task ReferenceDirective(TestHost testHost) + => TestAsync(""" #r "file.dll" - """; - await TestAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("r"), String(""" "file.dll" """)); - } [Theory, CombinatorialData] - public async Task LoadDirective(TestHost testHost) - { - var code = """ + public Task LoadDirective(TestHost testHost) + => TestAsync(""" #load "file.csx" - """; - await TestAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("load"), String(""" "file.csx" """)); - } [Theory, CombinatorialData] - public async Task IncompleteAwaitInNonAsyncContext(TestHost testHost) - { - var code = """ + public Task IncompleteAwaitInNonAsyncContext(TestHost testHost) + => TestInClassAsync(""" void M() { var x = await } - """; - await TestInClassAsync(code, + """, testHost, Keyword("void"), Method("M"), @@ -4775,19 +4460,16 @@ await TestInClassAsync(code, Operators.Equals, Keyword("await"), Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task CompleteAwaitInNonAsyncContext(TestHost testHost) - { - var code = """ + public Task CompleteAwaitInNonAsyncContext(TestHost testHost) + => TestInClassAsync(""" void M() { var x = await; } - """; - await TestInClassAsync(code, + """, testHost, Keyword("void"), Method("M"), @@ -4800,12 +4482,10 @@ await TestInClassAsync(code, Identifier("await"), Punctuation.Semicolon, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TupleDeclaration(TestHost testHost) - { - await TestInMethodAsync("(int, string) x", + public Task TupleDeclaration(TestHost testHost) + => TestInMethodAsync("(int, string) x", testHost, ParseOptions(TestOptions.Regular, Options.Script), Punctuation.OpenParen, @@ -4814,12 +4494,10 @@ await TestInMethodAsync("(int, string) x", Keyword("string"), Punctuation.CloseParen, Local("x")); - } [Theory, CombinatorialData] - public async Task TupleDeclarationWithNames(TestHost testHost) - { - await TestInMethodAsync("(int a, string b) x", + public Task TupleDeclarationWithNames(TestHost testHost) + => TestInMethodAsync("(int a, string b) x", testHost, ParseOptions(TestOptions.Regular, Options.Script), Punctuation.OpenParen, @@ -4830,12 +4508,10 @@ await TestInMethodAsync("(int a, string b) x", Identifier("b"), Punctuation.CloseParen, Local("x")); - } [Theory, CombinatorialData] - public async Task TupleLiteral(TestHost testHost) - { - await TestInMethodAsync("var values = (1, 2)", + public Task TupleLiteral(TestHost testHost) + => TestInMethodAsync("var values = (1, 2)", testHost, ParseOptions(TestOptions.Regular, Options.Script), Keyword("var"), @@ -4846,12 +4522,10 @@ await TestInMethodAsync("var values = (1, 2)", Punctuation.Comma, Number("2"), Punctuation.CloseParen); - } [Theory, CombinatorialData] - public async Task TupleLiteralWithNames(TestHost testHost) - { - await TestInMethodAsync("var values = (a: 1, b: 2)", + public Task TupleLiteralWithNames(TestHost testHost) + => TestInMethodAsync("var values = (a: 1, b: 2)", testHost, ParseOptions(TestOptions.Regular, Options.Script), Keyword("var"), @@ -4866,12 +4540,10 @@ await TestInMethodAsync("var values = (a: 1, b: 2)", Punctuation.Colon, Number("2"), Punctuation.CloseParen); - } [Theory, CombinatorialData] - public async Task TestConflictMarkers1(TestHost testHost) - { - await TestAsync( + public Task TestConflictMarkers1(TestHost testHost) + => TestAsync( """ class C { @@ -4902,12 +4574,10 @@ class C Punctuation.Semicolon, Comment(">>>>>>> End"), Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestConflictMarkers2(TestHost testHost) - { - await TestAsync( + public Task TestConflictMarkers2(TestHost testHost) + => TestAsync( """ class C { @@ -4944,12 +4614,10 @@ class C Punctuation.Semicolon, Comment(">>>>>>> End"), Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_InsideMethod(TestHost testHost) - { - await TestInMethodAsync(""" + public Task TestUnmanagedConstraint_InsideMethod(TestHost testHost) + => TestInMethodAsync(""" var unmanaged = 0; unmanaged++; @@ -4963,12 +4631,10 @@ await TestInMethodAsync(""" Identifier("unmanaged"), Operators.PlusPlus, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Type_Keyword(TestHost testHost) - { - await TestAsync( + public Task TestUnmanagedConstraint_Type_Keyword(TestHost testHost) + => TestAsync( "class X where T : unmanaged { }", testHost, Keyword("class"), @@ -4982,12 +4648,10 @@ await TestAsync( Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Type_ExistingInterface(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_Type_ExistingInterface(TestHost testHost) + => TestAsync(""" interface unmanaged {} class X where T : unmanaged { } @@ -5008,12 +4672,10 @@ class X where T : unmanaged { } Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) + => TestAsync(""" namespace OtherScope { @@ -5041,12 +4703,10 @@ class X where T : unmanaged { } Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Method_Keyword(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_Method_Keyword(TestHost testHost) + => TestAsync(""" class X { @@ -5071,12 +4731,10 @@ void M() where T : unmanaged { } Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Method_ExistingInterface(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_Method_ExistingInterface(TestHost testHost) + => TestAsync(""" interface unmanaged {} class X @@ -5106,12 +4764,10 @@ void M() where T : unmanaged { } Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) + => TestAsync(""" namespace OtherScope { @@ -5148,12 +4804,10 @@ void M() where T : unmanaged { } Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Delegate_Keyword(TestHost testHost) - { - await TestAsync( + public Task TestUnmanagedConstraint_Delegate_Keyword(TestHost testHost) + => TestAsync( "delegate void D() where T : unmanaged;", testHost, Keyword("delegate"), @@ -5169,12 +4823,10 @@ await TestAsync( Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Delegate_ExistingInterface(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_Delegate_ExistingInterface(TestHost testHost) + => TestAsync(""" interface unmanaged {} delegate void D() where T : unmanaged; @@ -5197,12 +4849,10 @@ interface unmanaged {} Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) + => TestAsync(""" namespace OtherScope { @@ -5232,12 +4882,10 @@ interface unmanaged {} Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_LocalFunction_Keyword(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_LocalFunction_Keyword(TestHost testHost) + => TestAsync(""" class X { @@ -5271,12 +4919,10 @@ void M() where T : unmanaged { } Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_LocalFunction_ExistingInterface(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_LocalFunction_ExistingInterface(TestHost testHost) + => TestAsync(""" interface unmanaged {} class X @@ -5315,12 +4961,10 @@ void M() where T : unmanaged { } Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) + => TestAsync(""" namespace OtherScope { @@ -5366,12 +5010,10 @@ void M() where T : unmanaged { } Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestDeclarationIsPattern(TestHost testHost) - { - await TestInMethodAsync(""" + public Task TestDeclarationIsPattern(TestHost testHost) + => TestInMethodAsync(""" object foo; @@ -5392,12 +5034,10 @@ await TestInMethodAsync(""" Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestDeclarationSwitchPattern(TestHost testHost) - { - await TestInMethodAsync(""" + public Task TestDeclarationSwitchPattern(TestHost testHost) + => TestInMethodAsync(""" object y; @@ -5423,12 +5063,10 @@ await TestInMethodAsync(""" ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestDeclarationExpression(TestHost testHost) - { - await TestInMethodAsync(""" + public Task TestDeclarationExpression(TestHost testHost) + => TestInMethodAsync(""" int (foo, bar) = (1, 2); """, @@ -5446,13 +5084,11 @@ await TestInMethodAsync(""" Number("2"), Punctuation.CloseParen, Punctuation.Semicolon); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/18956")] - public async Task TestListPattern(TestHost testHost) - { - await TestInMethodAsync(""" + public Task TestListPattern(TestHost testHost) + => TestInMethodAsync(""" switch (new int[0]) { @@ -5493,13 +5129,11 @@ await TestInMethodAsync(""" ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/18956")] - public async Task TestListPattern2(TestHost testHost) - { - await TestInMethodAsync(""" + public Task TestListPattern2(TestHost testHost) + => TestInMethodAsync(""" _ = x switch { @@ -5523,13 +5157,11 @@ await TestInMethodAsync(""" Operators.EqualsGreaterThan, Number("1"), Punctuation.CloseCurly); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/18956")] - public async Task TestVarPattern(TestHost testHost) - { - await TestInMethodAsync(""" + public Task TestVarPattern(TestHost testHost) + => TestInMethodAsync(""" _ = 1 is var x; @@ -5542,12 +5174,10 @@ await TestInMethodAsync(""" Keyword("var"), Local("x"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestTupleTypeSyntax(TestHost testHost) - { - await TestInClassAsync(""" + public Task TestTupleTypeSyntax(TestHost testHost) + => TestInClassAsync(""" public (int a, int b) Get() => null; """, @@ -5566,12 +5196,10 @@ await TestInClassAsync(""" Operators.EqualsGreaterThan, Keyword("null"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestOutParameter(TestHost testHost) - { - await TestInMethodAsync(""" + public Task TestOutParameter(TestHost testHost) + => TestInMethodAsync(""" if (int.TryParse("1", out int x)) { @@ -5595,12 +5223,10 @@ await TestInMethodAsync(""" Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestOutParameter2(TestHost testHost) - { - await TestInClassAsync(""" + public Task TestOutParameter2(TestHost testHost) + => TestInClassAsync(""" int F = int.TryParse("1", out int x) ? x : -1; @@ -5627,14 +5253,10 @@ await TestInClassAsync(""" Operators.Minus, Number("1"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestUsingDirective(TestHost testHost) - { - var code = @"using System.Collections.Generic;"; - - await TestAsync(code, + public Task TestUsingDirective(TestHost testHost) + => TestAsync(@"using System.Collections.Generic;", testHost, Keyword("using"), Identifier("System"), @@ -5643,14 +5265,10 @@ await TestAsync(code, Operators.Dot, Identifier("Generic"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestUsingAliasDirectiveForIdentifier(TestHost testHost) - { - var code = @"using Col = System.Collections;"; - - await TestAsync(code, + public Task TestUsingAliasDirectiveForIdentifier(TestHost testHost) + => TestAsync(@"using Col = System.Collections;", testHost, Keyword("using"), Identifier("Col"), @@ -5659,14 +5277,10 @@ await TestAsync(code, Operators.Dot, Identifier("Collections"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestUsingAliasDirectiveForClass(TestHost testHost) - { - var code = @"using Con = System.Console;"; - - await TestAsync(code, + public Task TestUsingAliasDirectiveForClass(TestHost testHost) + => TestAsync(@"using Con = System.Console;", testHost, Keyword("using"), Identifier("Con"), @@ -5675,14 +5289,10 @@ await TestAsync(code, Operators.Dot, Identifier("Console"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestUsingStaticDirective(TestHost testHost) - { - var code = @"using static System.Console;"; - - await TestAsync(code, + public Task TestUsingStaticDirective(TestHost testHost) + => TestAsync(@"using static System.Console;", testHost, Keyword("using"), Keyword("static"), @@ -5690,13 +5300,11 @@ await TestAsync(code, Operators.Dot, Identifier("Console"), Punctuation.Semicolon); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/33039")] [CombinatorialData] - public async Task ForEachVariableStatement(TestHost testHost) - { - await TestInMethodAsync(""" + public Task ForEachVariableStatement(TestHost testHost) + => TestInMethodAsync(""" foreach (var (x, y) in new[] { (1, 2) }); @@ -5723,12 +5331,10 @@ await TestInMethodAsync(""" Punctuation.CloseCurly, Punctuation.CloseParen, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task CatchDeclarationStatement(TestHost testHost) - { - await TestInMethodAsync(""" + public Task CatchDeclarationStatement(TestHost testHost) + => TestInMethodAsync(""" try { } catch (Exception ex) { } @@ -5744,12 +5350,10 @@ await TestInMethodAsync(""" Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_InsideMethod(TestHost testHost) - { - await TestInMethodAsync(""" + public Task TestNotNullConstraint_InsideMethod(TestHost testHost) + => TestInMethodAsync(""" var notnull = 0; notnull++; @@ -5763,12 +5367,10 @@ await TestInMethodAsync(""" Identifier("notnull"), Operators.PlusPlus, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Type_Keyword(TestHost testHost) - { - await TestAsync( + public Task TestNotNullConstraint_Type_Keyword(TestHost testHost) + => TestAsync( "class X where T : notnull { }", testHost, Keyword("class"), @@ -5782,12 +5384,10 @@ await TestAsync( Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Type_ExistingInterface(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_Type_ExistingInterface(TestHost testHost) + => TestAsync(""" interface notnull {} class X where T : notnull { } @@ -5808,12 +5408,10 @@ class X where T : notnull { } Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) + => TestAsync(""" namespace OtherScope { @@ -5841,12 +5439,10 @@ class X where T : notnull { } Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Method_Keyword(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_Method_Keyword(TestHost testHost) + => TestAsync(""" class X { @@ -5871,12 +5467,10 @@ void M() where T : notnull { } Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Method_ExistingInterface(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_Method_ExistingInterface(TestHost testHost) + => TestAsync(""" interface notnull {} class X @@ -5906,12 +5500,10 @@ void M() where T : notnull { } Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) + => TestAsync(""" namespace OtherScope { @@ -5948,12 +5540,10 @@ void M() where T : notnull { } Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Delegate_Keyword(TestHost testHost) - { - await TestAsync( + public Task TestNotNullConstraint_Delegate_Keyword(TestHost testHost) + => TestAsync( "delegate void D() where T : notnull;", testHost, Keyword("delegate"), @@ -5969,12 +5559,10 @@ await TestAsync( Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Delegate_ExistingInterface(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_Delegate_ExistingInterface(TestHost testHost) + => TestAsync(""" interface notnull {} delegate void D() where T : notnull; @@ -5997,12 +5585,10 @@ interface notnull {} Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) + => TestAsync(""" namespace OtherScope { @@ -6032,12 +5618,10 @@ interface notnull {} Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_LocalFunction_Keyword(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_LocalFunction_Keyword(TestHost testHost) + => TestAsync(""" class X { @@ -6071,12 +5655,10 @@ void M() where T : notnull { } Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_LocalFunction_ExistingInterface(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_LocalFunction_ExistingInterface(TestHost testHost) + => TestAsync(""" interface notnull {} class X @@ -6115,12 +5697,10 @@ void M() where T : notnull { } Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) + => TestAsync(""" namespace OtherScope { @@ -6166,21 +5746,17 @@ void M() where T : notnull { } Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/45807")] - public async Task FunctionPointer(TestHost testHost) - { - var code = """ + public Task FunctionPointer(TestHost testHost) + => TestAsync(""" class C { delegate* unmanaged[Stdcall, SuppressGCTransition] x; } - """; - - await TestAsync(code, + """, testHost, Keyword("class"), Class("C"), @@ -6201,7 +5777,6 @@ await TestAsync(code, Field("x"), Punctuation.Semicolon, Punctuation.CloseCurly); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48094")] public async Task TestXmlAttributeNameSpan1() @@ -6262,9 +5837,8 @@ public async Task TestXmlAttributeNameSpan2() [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/52290")] [CombinatorialData] - public async Task TestStaticLocalFunction(TestHost testHost) - { - var code = """ + public Task TestStaticLocalFunction(TestHost testHost) + => TestAsync(""" class C { @@ -6273,9 +5847,7 @@ public static void M() static void LocalFunc() { } } } - """; - - await TestAsync(code, + """, testHost, Keyword("class"), Class("C"), @@ -6298,13 +5870,11 @@ await TestAsync(code, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/52290")] [CombinatorialData] - public async Task TestConstantLocalVariable(TestHost testHost) - { - var code = """ + public Task TestConstantLocalVariable(TestHost testHost) + => TestAsync(""" class C { @@ -6313,9 +5883,7 @@ public static void M() const int Zero = 0; } } - """; - - await TestAsync(code, + """, testHost, Keyword("class"), Class("C"), @@ -6337,12 +5905,10 @@ await TestAsync(code, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestRawStringLiteral(TestHost testHost) - { - var code = """" + public Task TestRawStringLiteral(TestHost testHost) + => TestAsync("""" class C { @@ -6351,9 +5917,7 @@ public static void M(int x) var s = """Hello world"""; } } - """"; - - await TestAsync(code, + """", testHost, Keyword("class"), Class("C"), @@ -6377,12 +5941,10 @@ await TestAsync(code, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestRawStringLiteralUtf8_01(TestHost testHost) - { - var code = """" + public Task TestRawStringLiteralUtf8_01(TestHost testHost) + => TestAsync("""" class C { @@ -6391,9 +5953,7 @@ public static void M(int x) var s = """Hello world"""u8; } } - """"; - - await TestAsync(code, + """", testHost, Keyword("class"), Class("C"), @@ -6418,12 +5978,10 @@ await TestAsync(code, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestRawStringLiteralUtf8_02(TestHost testHost) - { - var code = """" + public Task TestRawStringLiteralUtf8_02(TestHost testHost) + => TestAsync("""" class C { @@ -6432,9 +5990,7 @@ public static void M(int x) var s = """Hello world"""U8; } } - """"; - - await TestAsync(code, + """", testHost, Keyword("class"), Class("C"), @@ -6459,12 +6015,10 @@ await TestAsync(code, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestRawStringLiteralMultiline(TestHost testHost) - { - var code = """" + public Task TestRawStringLiteralMultiline(TestHost testHost) + => TestAsync("""" class C { @@ -6475,9 +6029,7 @@ Hello world """; } } - """"; - - await TestAsync(code, + """", testHost, Keyword("class"), Class("C"), @@ -6503,12 +6055,10 @@ Hello world Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestRawStringLiteralMultilineUtf8_01(TestHost testHost) - { - var code = """" + public Task TestRawStringLiteralMultilineUtf8_01(TestHost testHost) + => TestAsync("""" class C { @@ -6519,9 +6069,7 @@ Hello world """u8; } } - """"; - - await TestAsync(code, + """", testHost, Keyword("class"), Class("C"), @@ -6548,12 +6096,10 @@ Hello world Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestRawStringLiteralMultilineUtf8_02(TestHost testHost) - { - var code = """" + public Task TestRawStringLiteralMultilineUtf8_02(TestHost testHost) + => TestAsync("""" class C { @@ -6564,9 +6110,7 @@ Hello world """U8; } } - """"; - - await TestAsync(code, + """", testHost, Keyword("class"), Class("C"), @@ -6593,12 +6137,10 @@ Hello world Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestRawStringLiteralInterpolation1(TestHost testHost) - { - var code = """" + public Task TestRawStringLiteralInterpolation1(TestHost testHost) + => TestAsync("""" class C { @@ -6607,9 +6149,7 @@ public static void M(int x) var s = $"""{x}"""; } } - """"; - - await TestAsync(code, + """", testHost, Keyword("class"), Class("C"), @@ -6639,12 +6179,10 @@ await TestAsync(code, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestRawStringLiteralInterpolation2(TestHost testHost) - { - var code = """" + public Task TestRawStringLiteralInterpolation2(TestHost testHost) + => TestAsync("""" class C { @@ -6653,9 +6191,7 @@ public static void M(int x) var s = $$"""{{x}}"""; } } - """"; - - await TestAsync(code, + """", testHost, Keyword("class"), Class("C"), @@ -6685,12 +6221,10 @@ await TestAsync(code, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestRawStringLiteralInterpolation3(TestHost testHost) - { - var code = """" + public Task TestRawStringLiteralInterpolation3(TestHost testHost) + => TestAsync("""" class C { @@ -6699,9 +6233,7 @@ public static void M(int x) var s = $$"""{{{x}}}"""; } } - """"; - - await TestAsync(code, + """", testHost, Keyword("class"), Class("C"), @@ -6733,12 +6265,10 @@ await TestAsync(code, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task CheckedUserDefinedOperators_01(TestHost testHost) - { - await TestInClassAsync( + public Task CheckedUserDefinedOperators_01(TestHost testHost) + => TestInClassAsync( """ static T operator checked -(T a) @@ -6757,12 +6287,10 @@ await TestInClassAsync( Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task CheckedUserDefinedOperators_02(TestHost testHost) - { - await TestInClassAsync( + public Task CheckedUserDefinedOperators_02(TestHost testHost) + => TestInClassAsync( """ static T operator checked +(T a, T b) @@ -6784,12 +6312,10 @@ await TestInClassAsync( Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task CheckedUserDefinedOperators_03(TestHost testHost) - { - await TestInClassAsync( + public Task CheckedUserDefinedOperators_03(TestHost testHost) + => TestInClassAsync( """ static explicit operator checked T(T a) @@ -6808,12 +6334,10 @@ static explicit operator checked T(T a) Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task CheckedUserDefinedOperators_04(TestHost testHost) - { - await TestInClassAsync( + public Task CheckedUserDefinedOperators_04(TestHost testHost) + => TestInClassAsync( """ static T I1.operator checked -(T a) @@ -6834,12 +6358,10 @@ await TestInClassAsync( Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task CheckedUserDefinedOperators_05(TestHost testHost) - { - await TestInClassAsync( + public Task CheckedUserDefinedOperators_05(TestHost testHost) + => TestInClassAsync( """ static T I1.operator checked +(T a, T b) @@ -6863,12 +6385,10 @@ await TestInClassAsync( Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task CheckedUserDefinedOperators_06(TestHost testHost) - { - await TestInClassAsync( + public Task CheckedUserDefinedOperators_06(TestHost testHost) + => TestInClassAsync( """ static explicit I1.operator checked T(T a) @@ -6889,12 +6409,10 @@ static explicit I1.operator checked T(T a) Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task UnsignedRightShift_01(TestHost testHost) - { - await TestInClassAsync( + public Task UnsignedRightShift_01(TestHost testHost) + => TestInClassAsync( """ static T operator >>>(T a, int b) @@ -6915,12 +6433,10 @@ await TestInClassAsync( Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task UnsignedRightShift_02(TestHost testHost) - { - await TestInClassAsync( + public Task UnsignedRightShift_02(TestHost testHost) + => TestInClassAsync( """ static T I1.operator checked >>>(T a, T b) @@ -6944,12 +6460,10 @@ await TestInClassAsync( Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task InstanceIncrementOperator_01(TestHost testHost, [CombinatorialValues("++", "--")] string op) - { - await TestInClassAsync( + public Task InstanceIncrementOperator_01(TestHost testHost, [CombinatorialValues("++", "--")] string op) + => TestInClassAsync( $$$""" void operator {{{op}}}() @@ -6964,12 +6478,10 @@ await TestInClassAsync( Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task InstanceIncrementOperator_02(TestHost testHost, [CombinatorialValues("++", "--")] string op) - { - await TestInClassAsync( + public Task InstanceIncrementOperator_02(TestHost testHost, [CombinatorialValues("++", "--")] string op) + => TestInClassAsync( $$$""" void I1.operator checked {{{op}}}() @@ -6987,12 +6499,10 @@ await TestInClassAsync( Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task InstanceCompoundAssignmentOperator_01(TestHost testHost, [CombinatorialValues("+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", ">>>=")] string op) - { - await TestInClassAsync( + public Task InstanceCompoundAssignmentOperator_01(TestHost testHost, [CombinatorialValues("+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", ">>>=")] string op) + => TestInClassAsync( $$$""" void operator {{{op}}}(T a) @@ -7009,7 +6519,6 @@ await TestInClassAsync( Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } private static FormattedClassification CompoundAssignmentOperatorClassification(string op) { @@ -7032,9 +6541,8 @@ private static FormattedClassification CompoundAssignmentOperatorClassification( } [Theory, CombinatorialData] - public async Task InstanceCompoundAssignmentOperator_02(TestHost testHost, [CombinatorialValues("+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", ">>>=")] string op) - { - await TestInClassAsync( + public Task InstanceCompoundAssignmentOperator_02(TestHost testHost, [CombinatorialValues("+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", ">>>=")] string op) + => TestInClassAsync( $$$""" void I1.operator checked {{{op}}}(T a) @@ -7054,12 +6562,10 @@ await TestInClassAsync( Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestExclamationExclamation(TestHost testHost) - { - await TestAsync( + public Task TestExclamationExclamation(TestHost testHost) + => TestAsync( """ class C { @@ -7083,14 +6589,12 @@ void M(string v!!) Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } /// /// [Theory, CombinatorialData] - public async Task LocalFunctionDeclaration(TestHost testHost) - { - await TestAsync( + public Task LocalFunctionDeclaration(TestHost testHost) + => TestAsync( """ using System; @@ -7143,12 +6647,10 @@ static void staticLocalFunction() { }|] Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task ScopedParameter(TestHost testHost) - { - await TestInMethodAsync(@"interface I { void F(scoped R r); }", + public Task ScopedParameter(TestHost testHost) + => TestInMethodAsync(@"interface I { void F(scoped R r); }", testHost, Keyword("interface"), Interface("I"), @@ -7162,23 +6664,19 @@ public async Task ScopedParameter(TestHost testHost) Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task ScopedLocalDeclaration(TestHost testHost) - { - await TestInMethodAsync(@"scoped var v;", + public Task ScopedLocalDeclaration(TestHost testHost) + => TestInMethodAsync(@"scoped var v;", testHost, Keyword("scoped"), Identifier("var"), Local("v"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task ScopedOutDeclaration(TestHost testHost) - { - await TestInMethodAsync(@"F(x, out scoped R y);", + public Task ScopedOutDeclaration(TestHost testHost) + => TestInMethodAsync(@"F(x, out scoped R y);", testHost, Identifier("F"), Punctuation.OpenParen, @@ -7190,12 +6688,10 @@ public async Task ScopedOutDeclaration(TestHost testHost) Local("y"), Punctuation.CloseParen, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task LambdaDefaultParameter_01(TestHost testHost) - { - await TestAsync( + public Task LambdaDefaultParameter_01(TestHost testHost) + => TestAsync( """ using System; class Program @@ -7251,12 +6747,10 @@ void M() Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task LambdaDefaultParameter_02(TestHost testHost) - { - await TestAsync( + public Task LambdaDefaultParameter_02(TestHost testHost) + => TestAsync( """ class Program { @@ -7292,12 +6786,10 @@ void M() Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task LambdaParamsArray(TestHost testHost) - { - await TestInMethodAsync("var lam = (params int[] xs) => xs.Length;", + public Task LambdaParamsArray(TestHost testHost) + => TestInMethodAsync("var lam = (params int[] xs) => xs.Length;", testHost, Keyword("var"), Local("lam"), @@ -7314,12 +6806,10 @@ public async Task LambdaParamsArray(TestHost testHost) Operators.Dot, Identifier("Length"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task LambdaParamsArray_Multiple(TestHost testHost) - { - await TestInMethodAsync("var lam = (int a, int b = 1, params int[] xs, params int[] ys.Length) => { };", + public Task LambdaParamsArray_Multiple(TestHost testHost) + => TestInMethodAsync("var lam = (int a, int b = 1, params int[] xs, params int[] ys.Length) => { };", testHost, Keyword("var"), Local("lam"), @@ -7351,12 +6841,10 @@ public async Task LambdaParamsArray_Multiple(TestHost testHost) Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestAllowsRefStructConstraint_01(TestHost testHost) - { - await TestAsync( + public Task TestAllowsRefStructConstraint_01(TestHost testHost) + => TestAsync( "class X where T : allows ref struct { }", testHost, Keyword("class"), @@ -7372,12 +6860,10 @@ await TestAsync( Keyword("struct"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestAllowsRefStructConstraint_02(TestHost testHost) - { - await TestAsync( + public Task TestAllowsRefStructConstraint_02(TestHost testHost) + => TestAsync( "class X { void M() where T : allows ref struct { } }", testHost, Keyword("class"), @@ -7399,5 +6885,4 @@ await TestAsync( Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } } diff --git a/src/EditorFeatures/CSharpTest/Classification/SyntacticClassifierTests_Preprocessor.cs b/src/EditorFeatures/CSharpTest/Classification/SyntacticClassifierTests_Preprocessor.cs index 5c944e8a456c0..55337dc958793 100644 --- a/src/EditorFeatures/CSharpTest/Classification/SyntacticClassifierTests_Preprocessor.cs +++ b/src/EditorFeatures/CSharpTest/Classification/SyntacticClassifierTests_Preprocessor.cs @@ -15,31 +15,24 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Classification; public partial class SyntacticClassifierTests { [Theory, CombinatorialData] - public async Task PP_IfTrue(TestHost testHost) - { - var code = - """ + public Task PP_IfTrue(TestHost testHost) + => TestInMethodAsync(""" #if true #endif - """; - await TestInMethodAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("if"), Keyword("true"), PPKeyword("#"), PPKeyword("endif")); - } [Theory, CombinatorialData] - public async Task PP_IfTrueWithComment(TestHost testHost) - { - var code = - """ + public Task PP_IfTrueWithComment(TestHost testHost) + => TestInMethodAsync(""" #if true //Goo #endif - """; - await TestInMethodAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("if"), @@ -47,51 +40,39 @@ await TestInMethodAsync(code, Comment("//Goo"), PPKeyword("#"), PPKeyword("endif")); - } [Theory, CombinatorialData] - public async Task PP_IfFalse(TestHost testHost) - { - var code = - """ + public Task PP_IfFalse(TestHost testHost) + => TestInMethodAsync(""" #if false #endif - """; - await TestInMethodAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("if"), Keyword("false"), PPKeyword("#"), PPKeyword("endif")); - } [Theory, CombinatorialData] - public async Task PP_IfGOO(TestHost testHost) - { - var code = - """ + public Task PP_IfGOO(TestHost testHost) + => TestInMethodAsync(""" #if GOO #endif - """; - await TestInMethodAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("if"), Identifier("GOO"), PPKeyword("#"), PPKeyword("endif")); - } [Theory, CombinatorialData] - public async Task PP_IfNotTrue(TestHost testHost) - { - var code = - """ + public Task PP_IfNotTrue(TestHost testHost) + => TestInMethodAsync(""" #if !true #endif - """; - await TestInMethodAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("if"), @@ -99,17 +80,13 @@ await TestInMethodAsync(code, Keyword("true"), PPKeyword("#"), PPKeyword("endif")); - } [Theory, CombinatorialData] - public async Task PP_IfNotFalse(TestHost testHost) - { - var code = - """ + public Task PP_IfNotFalse(TestHost testHost) + => TestInMethodAsync(""" #if !false #endif - """; - await TestInMethodAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("if"), @@ -117,17 +94,13 @@ await TestInMethodAsync(code, Keyword("false"), PPKeyword("#"), PPKeyword("endif")); - } [Theory, CombinatorialData] - public async Task PP_IfNotGOO(TestHost testHost) - { - var code = - """ + public Task PP_IfNotGOO(TestHost testHost) + => TestInMethodAsync(""" #if !GOO #endif - """; - await TestInMethodAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("if"), @@ -135,17 +108,13 @@ await TestInMethodAsync(code, Identifier("GOO"), PPKeyword("#"), PPKeyword("endif")); - } [Theory, CombinatorialData] - public async Task PP_IfTrueWithParens(TestHost testHost) - { - var code = - """ + public Task PP_IfTrueWithParens(TestHost testHost) + => TestInMethodAsync(""" #if (true) #endif - """; - await TestInMethodAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("if"), @@ -154,17 +123,13 @@ await TestInMethodAsync(code, Punctuation.CloseParen, PPKeyword("#"), PPKeyword("endif")); - } [Theory, CombinatorialData] - public async Task PP_IfFalseWithParens(TestHost testHost) - { - var code = - """ + public Task PP_IfFalseWithParens(TestHost testHost) + => TestInMethodAsync(""" #if (false) #endif - """; - await TestInMethodAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("if"), @@ -173,17 +138,13 @@ await TestInMethodAsync(code, Punctuation.CloseParen, PPKeyword("#"), PPKeyword("endif")); - } [Theory, CombinatorialData] - public async Task PP_IfGOOWithParens(TestHost testHost) - { - var code = - """ + public Task PP_IfGOOWithParens(TestHost testHost) + => TestInMethodAsync(""" #if (GOO) #endif - """; - await TestInMethodAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("if"), @@ -192,18 +153,13 @@ await TestInMethodAsync(code, Punctuation.CloseParen, PPKeyword("#"), PPKeyword("endif")); - } [Theory, CombinatorialData] - public async Task PP_IfOrExpression(TestHost testHost) - { - var code = - """ + public Task PP_IfOrExpression(TestHost testHost) + => TestInMethodAsync(""" #if GOO || BAR #endif - """; - - await TestInMethodAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("if"), @@ -212,18 +168,13 @@ await TestInMethodAsync(code, Identifier("BAR"), PPKeyword("#"), PPKeyword("endif")); - } [Theory, CombinatorialData] - public async Task PP_IfAndExpression(TestHost testHost) - { - var code = - """ + public Task PP_IfAndExpression(TestHost testHost) + => TestInMethodAsync(""" #if GOO && BAR #endif - """; - - await TestInMethodAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("if"), @@ -232,18 +183,13 @@ await TestInMethodAsync(code, Identifier("BAR"), PPKeyword("#"), PPKeyword("endif")); - } [Theory, CombinatorialData] - public async Task PP_IfOrAndExpression(TestHost testHost) - { - var code = - """ + public Task PP_IfOrAndExpression(TestHost testHost) + => TestInMethodAsync(""" #if GOO || BAR && BAZ #endif - """; - - await TestInMethodAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("if"), @@ -254,18 +200,13 @@ await TestInMethodAsync(code, Identifier("BAZ"), PPKeyword("#"), PPKeyword("endif")); - } [Theory, CombinatorialData] - public async Task PP_IfOrExpressionWithParens(TestHost testHost) - { - var code = - """ + public Task PP_IfOrExpressionWithParens(TestHost testHost) + => TestInMethodAsync(""" #if (GOO || BAR) #endif - """; - - await TestInMethodAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("if"), @@ -276,18 +217,13 @@ await TestInMethodAsync(code, Punctuation.CloseParen, PPKeyword("#"), PPKeyword("endif")); - } [Theory, CombinatorialData] - public async Task PP_IfAndExpressionWithParens(TestHost testHost) - { - var code = - """ + public Task PP_IfAndExpressionWithParens(TestHost testHost) + => TestInMethodAsync(""" #if (GOO && BAR) #endif - """; - - await TestInMethodAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("if"), @@ -298,18 +234,13 @@ await TestInMethodAsync(code, Punctuation.CloseParen, PPKeyword("#"), PPKeyword("endif")); - } [Theory, CombinatorialData] - public async Task PP_IfOrAndExpressionWithParens(TestHost testHost) - { - var code = - """ + public Task PP_IfOrAndExpressionWithParens(TestHost testHost) + => TestInMethodAsync(""" #if GOO || (BAR && BAZ) #endif - """; - - await TestInMethodAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("if"), @@ -322,72 +253,56 @@ await TestInMethodAsync(code, Punctuation.CloseParen, PPKeyword("#"), PPKeyword("endif")); - } [Theory, CombinatorialData] - public async Task PP_If1(TestHost testHost) - { - await TestAsync("#if goo", + public Task PP_If1(TestHost testHost) + => TestAsync("#if goo", testHost, PPKeyword("#"), PPKeyword("if"), Identifier("goo")); - } [Theory, CombinatorialData] - public async Task PP_If2(TestHost testHost) - { - await TestAsync(" #if goo", + public Task PP_If2(TestHost testHost) + => TestAsync(" #if goo", testHost, PPKeyword("#"), PPKeyword("if"), Identifier("goo")); - } [Theory, CombinatorialData] - public async Task PP_If3(TestHost testHost) - { - var code = - """ + public Task PP_If3(TestHost testHost) + => TestAsync(""" #if goo #endif - """; - await TestAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("if"), Identifier("goo"), PPKeyword("#"), PPKeyword("endif")); - } [Theory, CombinatorialData] - public async Task PP_If4(TestHost testHost) - { - var code = - """ + public Task PP_If4(TestHost testHost) + => TestAsync(""" #if #endif - """; - await TestAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("if"), PPKeyword("#"), PPKeyword("endif")); - } [Theory, CombinatorialData] - public async Task PP_If5(TestHost testHost) - { - var code = - """ + public Task PP_If5(TestHost testHost) + => TestAsync(""" #if aoeu aoeu #endif - """; - await TestAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("if"), @@ -398,37 +313,29 @@ await TestAsync(code, """), PPKeyword("#"), PPKeyword("endif")); - } [Theory, CombinatorialData] - public async Task PP_If6(TestHost testHost) - { - var code = - """ + public Task PP_If6(TestHost testHost) + => TestAsync(""" #if #else aeu - """; - await TestAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("if"), PPKeyword("#"), PPKeyword("else"), Identifier("aeu")); - } [Theory, CombinatorialData] - public async Task PP_If7(TestHost testHost) - { - var code = - """ + public Task PP_If7(TestHost testHost) + => TestAsync(""" #if #else #endif aeu - """; - await TestAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("if"), @@ -437,7 +344,6 @@ await TestAsync(code, PPKeyword("#"), PPKeyword("endif"), Identifier("aeu")); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] @@ -511,67 +417,54 @@ await TestAsync( } [Theory, CombinatorialData] - public async Task PP_Region1(TestHost testHost) - { - await TestAsync("#region Goo", + public Task PP_Region1(TestHost testHost) + => TestAsync("#region Goo", testHost, PPKeyword("#"), PPKeyword("region"), PPText("Goo")); - } [Theory, CombinatorialData] - public async Task PP_Region2(TestHost testHost) - { - await TestAsync(" #region goo", + public Task PP_Region2(TestHost testHost) + => TestAsync(" #region goo", testHost, PPKeyword("#"), PPKeyword("region"), PPText("goo")); - } [Theory, CombinatorialData] - public async Task PP_EndRegion1(TestHost testHost) - { - await TestAsync("#endregion", + public Task PP_EndRegion1(TestHost testHost) + => TestAsync("#endregion", testHost, PPKeyword("#"), PPKeyword("endregion")); - } [Theory, CombinatorialData] - public async Task PP_EndRegion2(TestHost testHost) - { - await TestAsync(" #endregion", + public Task PP_EndRegion2(TestHost testHost) + => TestAsync(" #endregion", testHost, PPKeyword("#"), PPKeyword("endregion")); - } [Theory, CombinatorialData] - public async Task PP_EndRegion3(TestHost testHost) - { - await TestAsync("#endregion adsf", + public Task PP_EndRegion3(TestHost testHost) + => TestAsync("#endregion adsf", testHost, PPKeyword("#"), PPKeyword("endregion"), PPText("adsf")); - } [Theory, CombinatorialData] - public async Task PP_EndRegion4(TestHost testHost) - { - await TestAsync(" #endregion adsf", + public Task PP_EndRegion4(TestHost testHost) + => TestAsync(" #endregion adsf", testHost, PPKeyword("#"), PPKeyword("endregion"), PPText("adsf")); - } [Theory, CombinatorialData] - public async Task PP_RegionEndRegion1(TestHost testHost) - { - await TestAsync( + public Task PP_RegionEndRegion1(TestHost testHost) + => TestAsync( """ #region #endregion @@ -581,12 +474,10 @@ await TestAsync( PPKeyword("region"), PPKeyword("#"), PPKeyword("endregion")); - } [Theory, CombinatorialData] - public async Task PP_CommentAfterRegion1(TestHost testHost) - { - await TestAsync( + public Task PP_CommentAfterRegion1(TestHost testHost) + => TestAsync( """ #region adsf //comment #endregion @@ -597,12 +488,10 @@ await TestAsync( PPText("adsf //comment"), PPKeyword("#"), PPKeyword("endregion")); - } [Theory, CombinatorialData] - public async Task PP_CommentAfterRegion2(TestHost testHost) - { - await TestAsync( + public Task PP_CommentAfterRegion2(TestHost testHost) + => TestAsync( """ #region //comment #endregion @@ -613,12 +502,10 @@ await TestAsync( PPText("//comment"), PPKeyword("#"), PPKeyword("endregion")); - } [Theory, CombinatorialData] - public async Task PP_CommentAfterEndRegion1(TestHost testHost) - { - await TestAsync( + public Task PP_CommentAfterEndRegion1(TestHost testHost) + => TestAsync( """ #region #endregion adsf //comment @@ -629,12 +516,10 @@ await TestAsync( PPKeyword("#"), PPKeyword("endregion"), PPText("adsf //comment")); - } [Theory, CombinatorialData] - public async Task PP_CommentAfterEndRegion2(TestHost testHost) - { - await TestAsync( + public Task PP_CommentAfterEndRegion2(TestHost testHost) + => TestAsync( """ #region #endregion //comment @@ -645,12 +530,10 @@ await TestAsync( PPKeyword("#"), PPKeyword("endregion"), Comment("//comment")); - } [Theory, CombinatorialData] - public async Task PP_DeclarationDirectives(TestHost testHost) - { - await TestAsync( + public Task PP_DeclarationDirectives(TestHost testHost) + => TestAsync( """ #define A #undef B @@ -662,19 +545,15 @@ await TestAsync( PPKeyword("#"), PPKeyword("undef"), Identifier("B")); - } [Theory, CombinatorialData] - public async Task PP_IfElseEndIfDirectives(TestHost testHost) - { - var code = - """ + public Task PP_IfElseEndIfDirectives(TestHost testHost) + => TestAsync(""" #if true #elif DEBUG #else #endif - """; - await TestAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("if"), @@ -686,208 +565,145 @@ await TestAsync(code, PPKeyword("else"), PPKeyword("#"), PPKeyword("endif")); - } [Theory, CombinatorialData] - public async Task PP_DefineDirective(TestHost testHost) - { - var code = @"#define GOO"; - await TestAsync(code, + public Task PP_DefineDirective(TestHost testHost) + => TestAsync(@"#define GOO", testHost, PPKeyword("#"), PPKeyword("define"), Identifier("GOO")); - } [Theory, CombinatorialData] - public async Task PP_DefineDirectiveWithCommentAndNoName(TestHost testHost) - { - var code = @"#define //Goo"; - await TestAsync(code, + public Task PP_DefineDirectiveWithCommentAndNoName(TestHost testHost) + => TestAsync(@"#define //Goo", testHost, PPKeyword("#"), PPKeyword("define"), Comment("//Goo")); - } [Theory, CombinatorialData] - public async Task PP_DefineDirectiveWithComment(TestHost testHost) - { - var code = @"#define GOO //Goo"; - await TestAsync(code, + public Task PP_DefineDirectiveWithComment(TestHost testHost) + => TestAsync(@"#define GOO //Goo", testHost, PPKeyword("#"), PPKeyword("define"), Identifier("GOO"), Comment("//Goo")); - } [Theory, CombinatorialData] - public async Task PP_UndefDirectives(TestHost testHost) - { - var code = @"#undef GOO"; - - await TestAsync(code, + public Task PP_UndefDirectives(TestHost testHost) + => TestAsync(@"#undef GOO", testHost, PPKeyword("#"), PPKeyword("undef"), Identifier("GOO")); - } [Theory, CombinatorialData] - public async Task PP_UndefDirectiveWithCommentAndNoName(TestHost testHost) - { - var code = @"#undef //Goo"; - await TestAsync(code, + public Task PP_UndefDirectiveWithCommentAndNoName(TestHost testHost) + => TestAsync(@"#undef //Goo", testHost, PPKeyword("#"), PPKeyword("undef"), Comment("//Goo")); - } [Theory, CombinatorialData] - public async Task PP_UndefDirectiveWithComment(TestHost testHost) - { - var code = @"#undef GOO //Goo"; - await TestAsync(code, + public Task PP_UndefDirectiveWithComment(TestHost testHost) + => TestAsync(@"#undef GOO //Goo", testHost, PPKeyword("#"), PPKeyword("undef"), Identifier("GOO"), Comment("//Goo")); - } [Theory, CombinatorialData] - public async Task PP_ErrorDirective(TestHost testHost) - { - var code = @"#error GOO"; - - await TestAsync(code, + public Task PP_ErrorDirective(TestHost testHost) + => TestAsync(@"#error GOO", testHost, PPKeyword("#"), PPKeyword("error"), PPText("GOO")); - } [Theory, CombinatorialData] - public async Task PP_ErrorDirectiveWithComment(TestHost testHost) - { - var code = @"#error GOO //Goo"; - - await TestAsync(code, + public Task PP_ErrorDirectiveWithComment(TestHost testHost) + => TestAsync(@"#error GOO //Goo", testHost, PPKeyword("#"), PPKeyword("error"), PPText("GOO //Goo")); - } [Theory, CombinatorialData] - public async Task PP_WarningDirective(TestHost testHost) - { - var code = @"#warning GOO"; - - await TestAsync(code, + public Task PP_WarningDirective(TestHost testHost) + => TestAsync(@"#warning GOO", testHost, PPKeyword("#"), PPKeyword("warning"), PPText("GOO")); - } [Theory, CombinatorialData] - public async Task PP_WarningDirectiveWithComment(TestHost testHost) - { - var code = @"#warning GOO //Goo"; - - await TestAsync(code, + public Task PP_WarningDirectiveWithComment(TestHost testHost) + => TestAsync(@"#warning GOO //Goo", testHost, PPKeyword("#"), PPKeyword("warning"), PPText("GOO //Goo")); - } [Theory, CombinatorialData] - public async Task PP_LineHidden(TestHost testHost) - { - var code = @"#line hidden"; - - await TestAsync(code, + public Task PP_LineHidden(TestHost testHost) + => TestAsync(@"#line hidden", testHost, PPKeyword("#"), PPKeyword("line"), PPKeyword("hidden")); - } [Theory, CombinatorialData] - public async Task PP_LineHiddenWithComment(TestHost testHost) - { - var code = @"#line hidden //Goo"; - - await TestAsync(code, + public Task PP_LineHiddenWithComment(TestHost testHost) + => TestAsync(@"#line hidden //Goo", testHost, PPKeyword("#"), PPKeyword("line"), PPKeyword("hidden"), Comment("//Goo")); - } [Theory, CombinatorialData] - public async Task PP_LineDefault(TestHost testHost) - { - var code = @"#line default"; - - await TestAsync(code, + public Task PP_LineDefault(TestHost testHost) + => TestAsync(@"#line default", testHost, PPKeyword("#"), PPKeyword("line"), PPKeyword("default")); - } [Theory, CombinatorialData] - public async Task PP_LineDefaultWithComment(TestHost testHost) - { - var code = @"#line default //Goo"; - - await TestAsync(code, + public Task PP_LineDefaultWithComment(TestHost testHost) + => TestAsync(@"#line default //Goo", testHost, PPKeyword("#"), PPKeyword("line"), PPKeyword("default"), Comment("//Goo")); - } [Theory, CombinatorialData] - public async Task PP_LineNumber(TestHost testHost) - { - var code = @"#line 100"; - - await TestAsync(code, + public Task PP_LineNumber(TestHost testHost) + => TestAsync(@"#line 100", testHost, PPKeyword("#"), PPKeyword("line"), Number("100")); - } [Theory, CombinatorialData] - public async Task PP_LineNumberWithComment(TestHost testHost) - { - var code = @"#line 100 //Goo"; - - await TestAsync(code, + public Task PP_LineNumberWithComment(TestHost testHost) + => TestAsync(@"#line 100 //Goo", testHost, PPKeyword("#"), PPKeyword("line"), Number("100"), Comment("//Goo")); - } [Theory, CombinatorialData] - public async Task PP_LineNumberWithFilename(TestHost testHost) - { - var code = """ + public Task PP_LineNumberWithFilename(TestHost testHost) + => TestAsync(""" #line 100 "C:\Goo" - """; - - await TestAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("line"), @@ -895,14 +711,10 @@ await TestAsync(code, String(""" "C:\Goo" """)); - } [Theory, CombinatorialData] - public async Task PP_LineNumberWithFilenameAndComment(TestHost testHost) - { - var code = @"#line 100 ""C:\Goo"" //Goo"; - - await TestAsync(code, + public Task PP_LineNumberWithFilenameAndComment(TestHost testHost) + => TestAsync(@"#line 100 ""C:\Goo"" //Goo", testHost, PPKeyword("#"), PPKeyword("line"), @@ -911,16 +723,12 @@ await TestAsync(code, "C:\Goo" """), Comment("//Goo")); - } [Theory, CombinatorialData] - public async Task PP_LineSpanWithCharacterOffset(TestHost testHost) - { - var code = """ + public Task PP_LineSpanWithCharacterOffset(TestHost testHost) + => TestAsync(""" #line (1, 2) - (3, 4) 5 "file.txt" - """; - - await TestAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("line"), @@ -939,14 +747,10 @@ await TestAsync(code, String(""" "file.txt" """)); - } [Theory, CombinatorialData] - public async Task PP_LineSpanWithComment(TestHost testHost) - { - var code = @"#line (1, 2) - (3, 4) """" //comment"; - - await TestAsync(code, + public Task PP_LineSpanWithComment(TestHost testHost) + => TestAsync(@"#line (1, 2) - (3, 4) """" //comment", testHost, PPKeyword("#"), PPKeyword("line"), @@ -965,128 +769,92 @@ await TestAsync(code, "" """), Comment("//comment")); - } [Theory, CombinatorialData] - public async Task PP_NullableEnable(TestHost testHost) - { - var code = @"#nullable enable"; - - await TestAsync(code, + public Task PP_NullableEnable(TestHost testHost) + => TestAsync(@"#nullable enable", testHost, PPKeyword("#"), PPKeyword("nullable"), PPKeyword("enable")); - } [Theory, CombinatorialData] - public async Task PP_NullableEnableWithComment(TestHost testHost) - { - var code = @"#nullable enable //Goo"; - - await TestAsync(code, + public Task PP_NullableEnableWithComment(TestHost testHost) + => TestAsync(@"#nullable enable //Goo", testHost, PPKeyword("#"), PPKeyword("nullable"), PPKeyword("enable"), Comment("//Goo")); - } [Theory, CombinatorialData] - public async Task PP_NullableEnableWarnings(TestHost testHost) - { - var code = @"#nullable enable warnings"; - - await TestAsync(code, + public Task PP_NullableEnableWarnings(TestHost testHost) + => TestAsync(@"#nullable enable warnings", testHost, PPKeyword("#"), PPKeyword("nullable"), PPKeyword("enable"), PPKeyword("warnings")); - } [Theory, CombinatorialData] - public async Task PP_NullableEnableWarningsWithComment(TestHost testHost) - { - var code = @"#nullable enable warnings //Goo"; - - await TestAsync(code, + public Task PP_NullableEnableWarningsWithComment(TestHost testHost) + => TestAsync(@"#nullable enable warnings //Goo", testHost, PPKeyword("#"), PPKeyword("nullable"), PPKeyword("enable"), PPKeyword("warnings"), Comment("//Goo")); - } [Theory, CombinatorialData] - public async Task PP_NullableEnableAnnotations(TestHost testHost) - { - var code = @"#nullable enable annotations"; - - await TestAsync(code, + public Task PP_NullableEnableAnnotations(TestHost testHost) + => TestAsync(@"#nullable enable annotations", testHost, PPKeyword("#"), PPKeyword("nullable"), PPKeyword("enable"), PPKeyword("annotations")); - } [Theory, CombinatorialData] - public async Task PP_NullableEnableAnnotationsWithComment(TestHost testHost) - { - var code = @"#nullable enable annotations //Goo"; - - await TestAsync(code, + public Task PP_NullableEnableAnnotationsWithComment(TestHost testHost) + => TestAsync(@"#nullable enable annotations //Goo", testHost, PPKeyword("#"), PPKeyword("nullable"), PPKeyword("enable"), PPKeyword("annotations"), Comment("//Goo")); - } [Theory, CombinatorialData] - public async Task PP_NullableDisable(TestHost testHost) - { - var code = @"#nullable disable"; - - await TestAsync(code, + public Task PP_NullableDisable(TestHost testHost) + => TestAsync(@"#nullable disable", testHost, PPKeyword("#"), PPKeyword("nullable"), PPKeyword("disable")); - } [Theory, CombinatorialData] - public async Task PP_NullableDisableWithComment(TestHost testHost) - { - var code = @"#nullable disable //Goo"; - - await TestAsync(code, + public Task PP_NullableDisableWithComment(TestHost testHost) + => TestAsync(@"#nullable disable //Goo", testHost, PPKeyword("#"), PPKeyword("nullable"), PPKeyword("disable"), Comment("//Goo")); - } [Theory, CombinatorialData] - public async Task PP_PragmaChecksum1(TestHost testHost) - { - await TestAsync( + public Task PP_PragmaChecksum1(TestHost testHost) + => TestAsync( @"#pragma checksum stuff", testHost, PPKeyword("#"), PPKeyword("pragma"), PPKeyword("checksum"), PPText("stuff")); - } [Theory, CombinatorialData] - public async Task PP_PragmaChecksum2(TestHost testHost) - { - await TestAsync( + public Task PP_PragmaChecksum2(TestHost testHost) + => TestAsync( """ #pragma checksum "file.txt" "{00000000-0000-0000-0000-000000000000}" "2453" """, @@ -1103,12 +871,10 @@ await TestAsync( String(""" "2453" """)); - } [Theory, CombinatorialData] - public async Task PP_PragmaChecksum3(TestHost testHost) - { - await TestAsync( + public Task PP_PragmaChecksum3(TestHost testHost) + => TestAsync( @"#pragma checksum ""file.txt"" ""{00000000-0000-0000-0000-000000000000}"" ""2453"" // Goo", testHost, PPKeyword("#"), @@ -1124,28 +890,20 @@ await TestAsync( "2453" """), Comment("// Goo")); - } [Theory, CombinatorialData] - public async Task PP_PragmaWarningDisableOne(TestHost testHost) - { - var code = @"#pragma warning disable 100"; - - await TestAsync(code, + public Task PP_PragmaWarningDisableOne(TestHost testHost) + => TestAsync(@"#pragma warning disable 100", testHost, PPKeyword("#"), PPKeyword("pragma"), PPKeyword("warning"), PPKeyword("disable"), Number("100")); - } [Theory, CombinatorialData] - public async Task PP_PragmaWarningDisableOneWithComment(TestHost testHost) - { - var code = @"#pragma warning disable 100 //Goo"; - - await TestAsync(code, + public Task PP_PragmaWarningDisableOneWithComment(TestHost testHost) + => TestAsync(@"#pragma warning disable 100 //Goo", testHost, PPKeyword("#"), PPKeyword("pragma"), @@ -1153,43 +911,31 @@ await TestAsync(code, PPKeyword("disable"), Number("100"), Comment("//Goo")); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/30783")] - public async Task PP_PragmaWarningDisableAllWithComment(TestHost testHost) - { - var code = @"#pragma warning disable //Goo"; - - await TestAsync(code, + public Task PP_PragmaWarningDisableAllWithComment(TestHost testHost) + => TestAsync(@"#pragma warning disable //Goo", testHost, PPKeyword("#"), PPKeyword("pragma"), PPKeyword("warning"), PPKeyword("disable"), Comment("//Goo")); - } [Theory, CombinatorialData] - public async Task PP_PragmaWarningRestoreOne(TestHost testHost) - { - var code = @"#pragma warning restore 100"; - - await TestAsync(code, + public Task PP_PragmaWarningRestoreOne(TestHost testHost) + => TestAsync(@"#pragma warning restore 100", testHost, PPKeyword("#"), PPKeyword("pragma"), PPKeyword("warning"), PPKeyword("restore"), Number("100")); - } [Theory, CombinatorialData] - public async Task PP_PragmaWarningRestoreOneWithComment(TestHost testHost) - { - var code = @"#pragma warning restore 100 //Goo"; - - await TestAsync(code, + public Task PP_PragmaWarningRestoreOneWithComment(TestHost testHost) + => TestAsync(@"#pragma warning restore 100 //Goo", testHost, PPKeyword("#"), PPKeyword("pragma"), @@ -1197,29 +943,21 @@ await TestAsync(code, PPKeyword("restore"), Number("100"), Comment("//Goo")); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/30783")] - public async Task PP_PragmaWarningRestoreAllWithComment(TestHost testHost) - { - var code = @"#pragma warning restore //Goo"; - - await TestAsync(code, + public Task PP_PragmaWarningRestoreAllWithComment(TestHost testHost) + => TestAsync(@"#pragma warning restore //Goo", testHost, PPKeyword("#"), PPKeyword("pragma"), PPKeyword("warning"), PPKeyword("restore"), Comment("//Goo")); - } [Theory, CombinatorialData] - public async Task PP_PragmaWarningDisableTwo(TestHost testHost) - { - var code = @"#pragma warning disable 100, 101"; - - await TestAsync(code, + public Task PP_PragmaWarningDisableTwo(TestHost testHost) + => TestAsync(@"#pragma warning disable 100, 101", testHost, PPKeyword("#"), PPKeyword("pragma"), @@ -1228,14 +966,10 @@ await TestAsync(code, Number("100"), Punctuation.Comma, Number("101")); - } [Theory, CombinatorialData] - public async Task PP_PragmaWarningRestoreTwo(TestHost testHost) - { - var code = @"#pragma warning restore 100, 101"; - - await TestAsync(code, + public Task PP_PragmaWarningRestoreTwo(TestHost testHost) + => TestAsync(@"#pragma warning restore 100, 101", testHost, PPKeyword("#"), PPKeyword("pragma"), @@ -1244,14 +978,10 @@ await TestAsync(code, Number("100"), Punctuation.Comma, Number("101")); - } [Theory, CombinatorialData] - public async Task PP_PragmaWarningDisableThree(TestHost testHost) - { - var code = @"#pragma warning disable 100, 101, 102"; - - await TestAsync(code, + public Task PP_PragmaWarningDisableThree(TestHost testHost) + => TestAsync(@"#pragma warning disable 100, 101, 102", testHost, PPKeyword("#"), PPKeyword("pragma"), @@ -1262,14 +992,10 @@ await TestAsync(code, Number("101"), Punctuation.Comma, Number("102")); - } [Theory, CombinatorialData] - public async Task PP_PragmaWarningRestoreThree(TestHost testHost) - { - var code = @"#pragma warning restore 100, 101, 102"; - - await TestAsync(code, + public Task PP_PragmaWarningRestoreThree(TestHost testHost) + => TestAsync(@"#pragma warning restore 100, 101, 102", testHost, PPKeyword("#"), PPKeyword("pragma"), @@ -1280,21 +1006,17 @@ await TestAsync(code, Number("101"), Punctuation.Comma, Number("102")); - } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/75583")] - public async Task PP_AfterNonWhiteSpaceOnLine(TestHost testHost) - { - var code = """ + public Task PP_AfterNonWhiteSpaceOnLine(TestHost testHost) + => TestAsync(""" if (#if false true #else false #endif ) { } - """; - - await TestAsync(code, + """, testHost, ControlKeyword("if"), Punctuation.OpenParen, @@ -1307,107 +1029,86 @@ await TestAsync(code, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task DiscardInOutDeclaration(TestHost testHost) - { - await TestInMethodAsync( + public Task DiscardInOutDeclaration(TestHost testHost) + => TestInMethodAsync( code: @"M2(out var _);", testHost: testHost, expected: Classifications(Identifier("M2"), Punctuation.OpenParen, Keyword("out"), Identifier("var"), Keyword("_"), Punctuation.CloseParen, Punctuation.Semicolon)); - } [Theory, CombinatorialData] - public async Task DiscardInCasePattern(TestHost testHost) - { - await TestInMethodAsync( + public Task DiscardInCasePattern(TestHost testHost) + => TestInMethodAsync( code: @"switch (1) { case int _: }", testHost: testHost, expected: Classifications(ControlKeyword("switch"), Punctuation.OpenParen, Number("1"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("case"), Keyword("int"), Keyword("_"), Punctuation.Colon, Punctuation.CloseCurly)); - } [Theory, CombinatorialData] - public async Task DiscardInDeconstruction(TestHost testHost) - { - await TestInMethodAsync( + public Task DiscardInDeconstruction(TestHost testHost) + => TestInMethodAsync( code: @"var (x, _) = (1, 2);", testHost: testHost, expected: Classifications(Identifier("var"), Punctuation.OpenParen, Local("x"), Punctuation.Comma, Keyword("_"), Punctuation.CloseParen, Operators.Equals, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen, Punctuation.Semicolon)); - } [Theory, CombinatorialData] - public async Task DiscardInDeconstruction2(TestHost testHost) - { - await TestInMethodAsync( + public Task DiscardInDeconstruction2(TestHost testHost) + => TestInMethodAsync( code: @"(var _, var _) = (1, 2);", testHost: testHost, expected: Classifications(Punctuation.OpenParen, Identifier("var"), Keyword("_"), Punctuation.Comma, Identifier("var"), Keyword("_"), Punctuation.CloseParen, Operators.Equals, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen, Punctuation.Semicolon)); - } [Theory, CombinatorialData] - public async Task ShortDiscardInDeconstruction(TestHost testHost) - { - await TestInMethodAsync( + public Task ShortDiscardInDeconstruction(TestHost testHost) + => TestInMethodAsync( code: @"int x; (_, x) = (1, 2);", testHost: testHost, expected: Classifications(Keyword("int"), Local("x"), Punctuation.Semicolon, Punctuation.OpenParen, Identifier("_"), Punctuation.Comma, Identifier("x"), Punctuation.CloseParen, Operators.Equals, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen, Punctuation.Semicolon)); - } [Theory, CombinatorialData] - public async Task ShortDiscardInOutDeclaration(TestHost testHost) - { - await TestInMethodAsync( + public Task ShortDiscardInOutDeclaration(TestHost testHost) + => TestInMethodAsync( code: @"M2(out _);", testHost: testHost, expected: Classifications(Identifier("M2"), Punctuation.OpenParen, Keyword("out"), Identifier("_"), Punctuation.CloseParen, Punctuation.Semicolon)); - } [Theory, CombinatorialData] - public async Task ShortDiscardInAssignment(TestHost testHost) - { - await TestInMethodAsync( + public Task ShortDiscardInAssignment(TestHost testHost) + => TestInMethodAsync( code: @"_ = 1;", testHost: testHost, expected: Classifications(Identifier("_"), Operators.Equals, Number("1"), Punctuation.Semicolon)); - } [Theory, CombinatorialData] - public async Task UnderscoreInLambda(TestHost testHost) - { - await TestInMethodAsync( + public Task UnderscoreInLambda(TestHost testHost) + => TestInMethodAsync( code: @"x = (_) => 1;", testHost: testHost, expected: Classifications(Identifier("x"), Operators.Equals, Punctuation.OpenParen, Parameter("_"), Punctuation.CloseParen, Operators.EqualsGreaterThan, Number("1"), Punctuation.Semicolon)); - } [Theory, CombinatorialData] - public async Task DiscardInLambda(TestHost testHost) - { - await TestInMethodAsync( + public Task DiscardInLambda(TestHost testHost) + => TestInMethodAsync( code: @"x = (_, _) => 1;", testHost: testHost, expected: Classifications(Identifier("x"), Operators.Equals, Punctuation.OpenParen, Parameter("_"), Punctuation.Comma, Parameter("_"), Punctuation.CloseParen, Operators.EqualsGreaterThan, Number("1"), Punctuation.Semicolon)); - } [Theory, CombinatorialData] - public async Task UnderscoreInAssignment(TestHost testHost) - { - await TestInMethodAsync(code: @"int _; _ = 1;", + public Task UnderscoreInAssignment(TestHost testHost) + => TestInMethodAsync(code: @"int _; _ = 1;", testHost: testHost, expected: Classifications(Keyword("int"), Local("_"), Punctuation.Semicolon, Identifier("_"), Operators.Equals, Number("1"), Punctuation.Semicolon)); - } } diff --git a/src/EditorFeatures/CSharpTest/Classification/TotalClassifierTests.cs b/src/EditorFeatures/CSharpTest/Classification/TotalClassifierTests.cs index c79d47b0c3460..8eedaa5b4fff6 100644 --- a/src/EditorFeatures/CSharpTest/Classification/TotalClassifierTests.cs +++ b/src/EditorFeatures/CSharpTest/Classification/TotalClassifierTests.cs @@ -40,9 +40,8 @@ protected override async Task> GetClassificationS } [Theory, CombinatorialData] - public async Task VarAsUsingAliasForNamespace(TestHost testHost) - { - await TestAsync( + public Task VarAsUsingAliasForNamespace(TestHost testHost) + => TestAsync( @"using var = System;", testHost, Keyword("using"), @@ -50,13 +49,11 @@ await TestAsync( Operators.Equals, Namespace("System"), Punctuation.Semicolon); - } [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547068")] - public async Task Bug17819(TestHost testHost) - { - await TestAsync( + public Task Bug17819(TestHost testHost) + => TestAsync( """ _ _() { @@ -80,12 +77,10 @@ _ _() XmlDoc.AttributeQuotes("'"), Identifier("_"), Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task VarAsUsingAliasForClass(TestHost testHost) - { - await TestAsync( + public Task VarAsUsingAliasForClass(TestHost testHost) + => TestAsync( @"using var = System.Math;", testHost, Keyword("using"), @@ -96,12 +91,10 @@ await TestAsync( Class("Math"), Static("Math"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task VarAsUsingAliasForDelegate(TestHost testHost) - { - await TestAsync( + public Task VarAsUsingAliasForDelegate(TestHost testHost) + => TestAsync( @"using var = System.Action;", testHost, Keyword("using"), @@ -111,12 +104,10 @@ await TestAsync( Operators.Dot, Delegate("Action"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task VarAsUsingAliasForStruct(TestHost testHost) - { - await TestAsync( + public Task VarAsUsingAliasForStruct(TestHost testHost) + => TestAsync( @"using var = System.DateTime;", testHost, Keyword("using"), @@ -126,12 +117,10 @@ await TestAsync( Operators.Dot, Struct("DateTime"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task VarAsUsingAliasForEnum(TestHost testHost) - { - await TestAsync( + public Task VarAsUsingAliasForEnum(TestHost testHost) + => TestAsync( @"using var = System.DayOfWeek;", testHost, Keyword("using"), @@ -141,12 +130,10 @@ await TestAsync( Operators.Dot, Enum("DayOfWeek"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task VarAsUsingAliasForInterface(TestHost testHost) - { - await TestAsync( + public Task VarAsUsingAliasForInterface(TestHost testHost) + => TestAsync( @"using var = System.IDisposable;", testHost, Keyword("using"), @@ -156,12 +143,10 @@ await TestAsync( Operators.Dot, Interface("IDisposable"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task VarAsConstructorName(TestHost testHost) - { - await TestAsync( + public Task VarAsConstructorName(TestHost testHost) + => TestAsync( """ class var { @@ -180,12 +165,10 @@ class var Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestRecordClass(TestHost testHost) - { - await TestAsync( + public Task TestRecordClass(TestHost testHost) + => TestAsync( """ record class R { @@ -205,12 +188,10 @@ record class R Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestRecordStruct(TestHost testHost) - { - await TestAsync( + public Task TestRecordStruct(TestHost testHost) + => TestAsync( """ record struct R { @@ -232,12 +213,10 @@ record struct R Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task UsingAliasGlobalNamespace(TestHost testHost) - { - await TestAsync( + public Task UsingAliasGlobalNamespace(TestHost testHost) + => TestAsync( @"using IO = global::System.IO;", testHost, Keyword("using"), @@ -249,12 +228,10 @@ await TestAsync( Operators.Dot, Namespace("IO"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task PartialDynamicWhere(TestHost testHost) - { - var code = """ + public Task PartialDynamicWhere(TestHost testHost) + => TestAsync(""" partial class partial where where : partial { static dynamic dynamic() @@ -262,8 +239,7 @@ static dynamic dynamic() return dynamic(); } } - """; - await TestAsync(code, + """, testHost, Keyword("partial"), Keyword("class"), @@ -300,13 +276,11 @@ await TestAsync(code, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543123")] - public async Task VarInForeach(TestHost testHost) - { - await TestInMethodAsync(@"foreach (var v in args) { }", + public Task VarInForeach(TestHost testHost) + => TestInMethodAsync(@"foreach (var v in args) { }", testHost, ControlKeyword("foreach"), Punctuation.OpenParen, @@ -317,12 +291,10 @@ await TestInMethodAsync(@"foreach (var v in args) { }", Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task ValueInSetterAndAnonymousTypePropertyName(TestHost testHost) - { - await TestAsync( + public Task ValueInSetterAndAnonymousTypePropertyName(TestHost testHost) + => TestAsync( """ class C { @@ -357,12 +329,10 @@ int P Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestValueInEvent(TestHost testHost) - { - await TestInClassAsync( + public Task TestValueInEvent(TestHost testHost) + => TestInClassAsync( """ event int Bar { @@ -402,12 +372,10 @@ event int Bar Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestValueInProperty(TestHost testHost) - { - await TestInClassAsync( + public Task TestValueInProperty(TestHost testHost) + => TestInClassAsync( """ int Goo { @@ -446,12 +414,10 @@ int Goo Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task ValueFieldInSetterAccessedThroughThis(TestHost testHost) - { - await TestInClassAsync( + public Task ValueFieldInSetterAccessedThroughThis(TestHost testHost) + => TestInClassAsync( """ int P { @@ -475,12 +441,10 @@ int P Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task NewOfInterface(TestHost testHost) - { - await TestInMethodAsync( + public Task NewOfInterface(TestHost testHost) + => TestInMethodAsync( @"object o = new System.IDisposable();", testHost, Keyword("object"), @@ -493,13 +457,11 @@ await TestInMethodAsync( Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545611")] [CombinatorialData] - public async Task TestVarConstructor(TestHost testHost) - { - await TestAsync( + public Task TestVarConstructor(TestHost testHost) + => TestAsync( """ class var { @@ -525,13 +487,11 @@ void Main() Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545609")] [CombinatorialData] - public async Task TestVarTypeParameter(TestHost testHost) - { - await TestAsync( + public Task TestVarTypeParameter(TestHost testHost) + => TestAsync( """ class X { @@ -558,13 +518,11 @@ void Goo() Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545610")] [CombinatorialData] - public async Task TestVarAttribute1(TestHost testHost) - { - await TestAsync( + public Task TestVarAttribute1(TestHost testHost) + => TestAsync( """ using System; @@ -586,13 +544,11 @@ class var : Attribute Class("Attribute"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545610")] [CombinatorialData] - public async Task TestVarAttribute2(TestHost testHost) - { - await TestAsync( + public Task TestVarAttribute2(TestHost testHost) + => TestAsync( """ using System; @@ -614,13 +570,11 @@ class varAttribute : Attribute Class("Attribute"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546170")] [CombinatorialData] - public async Task TestStandaloneTypeName(TestHost testHost) - { - await TestAsync( + public Task TestStandaloneTypeName(TestHost testHost) + => TestAsync( """ using System; @@ -653,13 +607,11 @@ static void Main() Static("Console"), Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546403")] [CombinatorialData] - public async Task TestNamespaceClassAmbiguities(TestHost testHost) - { - await TestAsync( + public Task TestNamespaceClassAmbiguities(TestHost testHost) + => TestAsync( """ class C { @@ -678,12 +630,10 @@ namespace C Namespace("C"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task NameAttributeValue(TestHost testHost) - { - await TestAsync( + public Task NameAttributeValue(TestHost testHost) + => TestAsync( """ class Program { @@ -723,12 +673,10 @@ void Goo(int x) Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task Cref1(TestHost testHost) - { - await TestAsync( + public Task Cref1(TestHost testHost) + => TestAsync( """ /// class Program @@ -769,12 +717,10 @@ void Goo() Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task CrefNamespaceIsNotClass(TestHost testHost) - { - await TestAsync( + public Task CrefNamespaceIsNotClass(TestHost testHost) + => TestAsync( """ /// namespace N @@ -807,12 +753,10 @@ class Program Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task InterfacePropertyWithSameNameShouldBePreferredToType(TestHost testHost) - { - await TestAsync( + public Task InterfacePropertyWithSameNameShouldBePreferredToType(TestHost testHost) + => TestAsync( """ interface IGoo { @@ -843,13 +787,11 @@ interface IGoo Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/633")] - public async Task XmlDocCref(TestHost testHost) - { - await TestAsync( + public Task XmlDocCref(TestHost testHost) + => TestAsync( """ /// /// @@ -903,12 +845,10 @@ public MyClass(int x) Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestGenericTypeWithNoArity(TestHost testHost) - { - await TestAsync( + public Task TestGenericTypeWithNoArity(TestHost testHost) + => TestAsync( """ using System.Collections.Generic; @@ -930,12 +870,10 @@ class Program : IReadOnlyCollection Interface("IReadOnlyCollection"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestGenericTypeWithWrongArity(TestHost testHost) - { - await TestAsync( + public Task TestGenericTypeWithWrongArity(TestHost testHost) + => TestAsync( """ using System.Collections.Generic; @@ -962,12 +900,10 @@ class Program : IReadOnlyCollection Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestExtensionMethodDeclaration(TestHost testHost) - { - await TestAsync( + public Task TestExtensionMethodDeclaration(TestHost testHost) + => TestAsync( """ static class ExtMethod { @@ -995,12 +931,10 @@ public static void TestMethod(this C c) Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestExtensionMethodUsage(TestHost testHost) - { - await TestAsync( + public Task TestExtensionMethodUsage(TestHost testHost) + => TestAsync( """ static class ExtMethod { @@ -1069,12 +1003,10 @@ void Test() Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestConstLocals(TestHost testHost) - { - await TestInMethodAsync( + public Task TestConstLocals(TestHost testHost) + => TestInMethodAsync( """ const int Number = 42; var x = Number; @@ -1092,12 +1024,10 @@ await TestInMethodAsync( Operators.Equals, Constant("Number"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_InsideMethod(TestHost testHost) - { - await TestInMethodAsync(""" + public Task TestUnmanagedConstraint_InsideMethod(TestHost testHost) + => TestInMethodAsync(""" var unmanaged = 0; unmanaged++; """, @@ -1110,12 +1040,10 @@ await TestInMethodAsync(""" Local("unmanaged"), Operators.PlusPlus, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Type_Keyword(TestHost testHost) - { - await TestAsync( + public Task TestUnmanagedConstraint_Type_Keyword(TestHost testHost) + => TestAsync( "class X where T : unmanaged { }", testHost, Keyword("class"), @@ -1129,12 +1057,10 @@ await TestAsync( Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Type_ExistingInterface(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_Type_ExistingInterface(TestHost testHost) + => TestAsync(""" interface unmanaged {} class X where T : unmanaged { } """, @@ -1154,12 +1080,10 @@ class X where T : unmanaged { } Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) + => TestAsync(""" namespace OtherScope { interface unmanaged {} @@ -1186,12 +1110,10 @@ class X where T : unmanaged { } Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Method_Keyword(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_Method_Keyword(TestHost testHost) + => TestAsync(""" class X { void M() where T : unmanaged { } @@ -1215,12 +1137,10 @@ void M() where T : unmanaged { } Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Method_ExistingInterface(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_Method_ExistingInterface(TestHost testHost) + => TestAsync(""" interface unmanaged {} class X { @@ -1249,12 +1169,10 @@ void M() where T : unmanaged { } Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) + => TestAsync(""" namespace OtherScope { interface unmanaged {} @@ -1290,12 +1208,10 @@ void M() where T : unmanaged { } Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Delegate_Keyword(TestHost testHost) - { - await TestAsync( + public Task TestUnmanagedConstraint_Delegate_Keyword(TestHost testHost) + => TestAsync( "delegate void D() where T : unmanaged;", testHost, Keyword("delegate"), @@ -1311,12 +1227,10 @@ await TestAsync( Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Delegate_ExistingInterface(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_Delegate_ExistingInterface(TestHost testHost) + => TestAsync(""" interface unmanaged {} delegate void D() where T : unmanaged; """, @@ -1338,12 +1252,10 @@ interface unmanaged {} Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) + => TestAsync(""" namespace OtherScope { interface unmanaged {} @@ -1372,12 +1284,10 @@ interface unmanaged {} Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_LocalFunction_Keyword(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_LocalFunction_Keyword(TestHost testHost) + => TestAsync(""" class X { void N() @@ -1410,12 +1320,10 @@ void M() where T : unmanaged { } Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_LocalFunction_ExistingInterface(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_LocalFunction_ExistingInterface(TestHost testHost) + => TestAsync(""" interface unmanaged {} class X { @@ -1453,12 +1361,10 @@ void M() where T : unmanaged { } Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestUnmanagedConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) - { - await TestAsync(""" + public Task TestUnmanagedConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) + => TestAsync(""" namespace OtherScope { interface unmanaged {} @@ -1503,13 +1409,11 @@ void M() where T : unmanaged { } Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/29492")] [CombinatorialData] - public async Task TestOperatorOverloading(TestHost testHost) - { - await TestAsync(""" + public Task TestOperatorOverloading(TestHost testHost) + => TestAsync(""" class C { void M() @@ -1581,12 +1485,10 @@ class True Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_InsideMethod(TestHost testHost) - { - await TestInMethodAsync(""" + public Task TestNotNullConstraint_InsideMethod(TestHost testHost) + => TestInMethodAsync(""" var notnull = 0; notnull++; """, @@ -1599,12 +1501,10 @@ await TestInMethodAsync(""" Local("notnull"), Operators.PlusPlus, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Type_Keyword(TestHost testHost) - { - await TestAsync( + public Task TestNotNullConstraint_Type_Keyword(TestHost testHost) + => TestAsync( "class X where T : notnull { }", testHost, Keyword("class"), @@ -1618,12 +1518,10 @@ await TestAsync( Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Type_ExistingInterface(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_Type_ExistingInterface(TestHost testHost) + => TestAsync(""" interface notnull {} class X where T : notnull { } """, @@ -1643,12 +1541,10 @@ class X where T : notnull { } Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) + => TestAsync(""" namespace OtherScope { interface notnull {} @@ -1675,12 +1571,10 @@ class X where T : notnull { } Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Method_Keyword(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_Method_Keyword(TestHost testHost) + => TestAsync(""" class X { void M() where T : notnull { } @@ -1704,12 +1598,10 @@ void M() where T : notnull { } Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Method_ExistingInterface(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_Method_ExistingInterface(TestHost testHost) + => TestAsync(""" interface notnull {} class X { @@ -1738,12 +1630,10 @@ void M() where T : notnull { } Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) + => TestAsync(""" namespace OtherScope { interface notnull {} @@ -1779,12 +1669,10 @@ void M() where T : notnull { } Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Delegate_Keyword(TestHost testHost) - { - await TestAsync( + public Task TestNotNullConstraint_Delegate_Keyword(TestHost testHost) + => TestAsync( "delegate void D() where T : notnull;", testHost, Keyword("delegate"), @@ -1800,12 +1688,10 @@ await TestAsync( Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Delegate_ExistingInterface(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_Delegate_ExistingInterface(TestHost testHost) + => TestAsync(""" interface notnull {} delegate void D() where T : notnull; """, @@ -1827,12 +1713,10 @@ interface notnull {} Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) + => TestAsync(""" namespace OtherScope { interface notnull {} @@ -1861,12 +1745,10 @@ interface notnull {} Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_LocalFunction_Keyword(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_LocalFunction_Keyword(TestHost testHost) + => TestAsync(""" class X { void N() @@ -1899,12 +1781,10 @@ void M() where T : notnull { } Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_LocalFunction_ExistingInterface(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_LocalFunction_ExistingInterface(TestHost testHost) + => TestAsync(""" interface notnull {} class X { @@ -1942,12 +1822,10 @@ void M() where T : notnull { } Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestNotNullConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) - { - await TestAsync(""" + public Task TestNotNullConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) + => TestAsync(""" namespace OtherScope { interface notnull {} @@ -1992,13 +1870,11 @@ void M() where T : notnull { } Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/10174")] [CombinatorialData] - public async Task VarInPropertyPattern(TestHost testHost) - { - await TestAsync( + public Task VarInPropertyPattern(TestHost testHost) + => TestAsync( """ using System; @@ -2062,13 +1938,11 @@ void Goo(object o) Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] [CombinatorialData] - public async Task NotPattern(TestHost testHost) - { - await TestAsync( + public Task NotPattern(TestHost testHost) + => TestAsync( """ class Person { @@ -2103,13 +1977,11 @@ void Goo(object o) Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] [CombinatorialData] - public async Task OrPattern(TestHost testHost) - { - await TestAsync( + public Task OrPattern(TestHost testHost) + => TestAsync( """ class Person { @@ -2144,13 +2016,11 @@ void Goo(object o) Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/59484")] [CombinatorialData] - public async Task TestPatternVariables(TestHost testHost) - { - await TestAsync( + public Task TestPatternVariables(TestHost testHost) + => TestAsync( """ void M(object o) { _ = o is [var (x, y), {} z] list; @@ -2183,13 +2053,11 @@ void M(object o) { Local("list"), Punctuation.Semicolon, Punctuation.CloseCurly); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] [CombinatorialData] - public async Task RelationalPattern(TestHost testHost) - { - await TestAsync( + public Task RelationalPattern(TestHost testHost) + => TestAsync( """ class Person { @@ -2223,12 +2091,10 @@ void Goo(object o) Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task BasicFileScopedNamespaceClassification(TestHost testHost) - { - await TestAsync( + public Task BasicFileScopedNamespaceClassification(TestHost testHost) + => TestAsync( """ namespace NS; @@ -2242,12 +2108,10 @@ class C { } Class("C"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestStringEscape(TestHost testHost) - { - await TestInMethodAsync(@"var goo = $@""{{{12:X}}}"";", + public Task TestStringEscape(TestHost testHost) + => TestInMethodAsync(@"var goo = $@""{{{12:X}}}"";", testHost, Keyword("var"), Local("goo"), @@ -2266,13 +2130,11 @@ public async Task TestStringEscape(TestHost testHost) " """), Punctuation.Semicolon); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/55313")] - public async Task TestStaticConstructorClass(TestHost testHost) - { - await TestAsync( + public Task TestStaticConstructorClass(TestHost testHost) + => TestAsync( """ class C { @@ -2280,24 +2142,22 @@ static C() { } } """, testHost, -Keyword("class"), -Class("C"), -Punctuation.OpenCurly, -Keyword("static"), -Class("C"), -Static("C"), -Punctuation.OpenParen, -Punctuation.CloseParen, -Punctuation.OpenCurly, -Punctuation.CloseCurly, -Punctuation.CloseCurly); - } + Keyword("class"), + Class("C"), + Punctuation.OpenCurly, + Keyword("static"), + Class("C"), + Static("C"), + Punctuation.OpenParen, + Punctuation.CloseParen, + Punctuation.OpenCurly, + Punctuation.CloseCurly, + Punctuation.CloseCurly); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/55313")] - public async Task TestStaticConstructorInterface(TestHost testHost) - { - await TestAsync( + public Task TestStaticConstructorInterface(TestHost testHost) + => TestAsync( """ interface C { @@ -2305,24 +2165,22 @@ static C() { } } """, testHost, -Keyword("interface"), -Interface("C"), -Punctuation.OpenCurly, -Keyword("static"), -Interface("C"), -Static("C"), -Punctuation.OpenParen, -Punctuation.CloseParen, -Punctuation.OpenCurly, -Punctuation.CloseCurly, -Punctuation.CloseCurly); - } + Keyword("interface"), + Interface("C"), + Punctuation.OpenCurly, + Keyword("static"), + Interface("C"), + Static("C"), + Punctuation.OpenParen, + Punctuation.CloseParen, + Punctuation.OpenCurly, + Punctuation.CloseCurly, + Punctuation.CloseCurly); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/59569")] - public async Task TestArgsInTopLevel(TestHost testHost) - { - await TestAsync( + public Task TestArgsInTopLevel(TestHost testHost) + => TestAsync( """ [|foreach (var arg in args) { @@ -2330,22 +2188,20 @@ await TestAsync( """, testHost, parseOptions: null, -ControlKeyword("foreach"), -Punctuation.OpenParen, -Keyword("var"), -Local("arg"), -ControlKeyword("in"), -Keyword("args"), -Punctuation.CloseParen, -Punctuation.OpenCurly, -Punctuation.CloseCurly); - } + ControlKeyword("foreach"), + Punctuation.OpenParen, + Keyword("var"), + Local("arg"), + ControlKeyword("in"), + Keyword("args"), + Punctuation.CloseParen, + Punctuation.OpenCurly, + Punctuation.CloseCurly); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/59569")] - public async Task TestArgsInNormalProgram(TestHost testHost) - { - await TestAsync( + public Task TestArgsInNormalProgram(TestHost testHost) + => TestAsync( """ class Program { @@ -2359,22 +2215,20 @@ static void Main(string[] args) """, testHost, parseOptions: null, -ControlKeyword("foreach"), -Punctuation.OpenParen, -Keyword("var"), -Local("arg"), -ControlKeyword("in"), -Parameter("args"), -Punctuation.CloseParen, -Punctuation.OpenCurly, -Punctuation.CloseCurly); - } + ControlKeyword("foreach"), + Punctuation.OpenParen, + Keyword("var"), + Local("arg"), + ControlKeyword("in"), + Parameter("args"), + Punctuation.CloseParen, + Punctuation.OpenCurly, + Punctuation.CloseCurly); [Theory, CombinatorialData] [WorkItem(60399, "https://github.com/dotnet/roslyn/issues/60339")] - public async Task TestAsyncInIncompleteMember(TestHost testHost) - { - await TestAsync( + public Task TestAsyncInIncompleteMember(TestHost testHost) + => TestAsync( """ class Test { @@ -2383,19 +2237,17 @@ public async """, testHost, parseOptions: null, -Keyword("class"), -Class("Test"), -Punctuation.OpenCurly, -Keyword("public"), -Keyword("async"), -Punctuation.CloseCurly); - } + Keyword("class"), + Class("Test"), + Punctuation.OpenCurly, + Keyword("public"), + Keyword("async"), + Punctuation.CloseCurly); [Theory, CombinatorialData] [WorkItem(60399, "https://github.com/dotnet/roslyn/issues/60339")] - public async Task TestAsyncInIncompleteMemberWhenAsyncTypeIsDefined(TestHost testHost) - { - await TestAsync( + public Task TestAsyncInIncompleteMemberWhenAsyncTypeIsDefined(TestHost testHost) + => TestAsync( """ [|class Test { @@ -2408,19 +2260,17 @@ class async """, testHost, parseOptions: null, -Keyword("class"), -Class("Test"), -Punctuation.OpenCurly, -Keyword("public"), -Class("async"), -Punctuation.CloseCurly); - } + Keyword("class"), + Class("Test"), + Punctuation.OpenCurly, + Keyword("public"), + Class("async"), + Punctuation.CloseCurly); [Theory, CombinatorialData] [WorkItem(60399, "https://github.com/dotnet/roslyn/issues/60339")] - public async Task TestAsyncInPotentialLocalFunctionDeclaration(TestHost testHost) - { - await TestAsync( + public Task TestAsyncInPotentialLocalFunctionDeclaration(TestHost testHost) + => TestAsync( """ void M() { @@ -2429,20 +2279,18 @@ void M() """, testHost, parseOptions: null, -Keyword("void"), -Method("M"), -Punctuation.OpenParen, -Punctuation.CloseParen, -Punctuation.OpenCurly, -Keyword("async"), -Punctuation.CloseCurly); - } + Keyword("void"), + Method("M"), + Punctuation.OpenParen, + Punctuation.CloseParen, + Punctuation.OpenCurly, + Keyword("async"), + Punctuation.CloseCurly); [Theory, CombinatorialData] [WorkItem(60399, "https://github.com/dotnet/roslyn/issues/60339")] - public async Task TestAsyncInPotentialLocalFunctionDeclarationWhenAsyncTypeIsDefined(TestHost testHost) - { - await TestAsync( + public Task TestAsyncInPotentialLocalFunctionDeclarationWhenAsyncTypeIsDefined(TestHost testHost) + => TestAsync( """ [|void M() { @@ -2455,20 +2303,18 @@ class async """, testHost, parseOptions: null, -Keyword("void"), -Method("M"), -Punctuation.OpenParen, -Punctuation.CloseParen, -Punctuation.OpenCurly, -Class("async"), -Punctuation.CloseCurly); - } + Keyword("void"), + Method("M"), + Punctuation.OpenParen, + Punctuation.CloseParen, + Punctuation.OpenCurly, + Class("async"), + Punctuation.CloseCurly); [Theory, CombinatorialData] [WorkItem(60399, "https://github.com/dotnet/roslyn/issues/60339")] - public async Task TestAsyncAsLocalMemberType_NoAsyncInScope(TestHost testHost) - { - await TestAsync( + public Task TestAsyncAsLocalMemberType_NoAsyncInScope(TestHost testHost) + => TestAsync( """ class Test { @@ -2480,16 +2326,14 @@ void M() """, testHost, parseOptions: null, -Keyword("async"), -Local("a"), -Punctuation.Semicolon); - } + Keyword("async"), + Local("a"), + Punctuation.Semicolon); [Theory, CombinatorialData] [WorkItem(60399, "https://github.com/dotnet/roslyn/issues/60339")] - public async Task TestAsyncAsLocalMemberType_AsyncInScope(TestHost testHost) - { - await TestAsync( + public Task TestAsyncAsLocalMemberType_AsyncInScope(TestHost testHost) + => TestAsync( """ class async { } @@ -2503,16 +2347,14 @@ void M() """, testHost, parseOptions: null, -Class("async"), -Local("a"), -Punctuation.Semicolon); - } + Class("async"), + Local("a"), + Punctuation.Semicolon); [Theory, CombinatorialData] [WorkItem(60399, "https://github.com/dotnet/roslyn/issues/60339")] - public async Task TestAsyncAsPropertyType_NoAsyncInScope(TestHost testHost) - { - await TestAsync( + public Task TestAsyncAsPropertyType_NoAsyncInScope(TestHost testHost) + => TestAsync( """ class Test { @@ -2521,22 +2363,20 @@ class Test """, testHost, parseOptions: null, -Keyword("public"), -Keyword("async"), -Property("Prop"), -Punctuation.OpenCurly, -Keyword("get"), -Punctuation.Semicolon, -Keyword("set"), -Punctuation.Semicolon, -Punctuation.CloseCurly); - } + Keyword("public"), + Keyword("async"), + Property("Prop"), + Punctuation.OpenCurly, + Keyword("get"), + Punctuation.Semicolon, + Keyword("set"), + Punctuation.Semicolon, + Punctuation.CloseCurly); [Theory, CombinatorialData] [WorkItem(60399, "https://github.com/dotnet/roslyn/issues/60339")] - public async Task TestAsyncAsPropertyType_AsyncInScope(TestHost testHost) - { - await TestAsync( + public Task TestAsyncAsPropertyType_AsyncInScope(TestHost testHost) + => TestAsync( """ class async { } @@ -2547,22 +2387,20 @@ class Test """, testHost, parseOptions: null, -Keyword("public"), -Class("async"), -Property("Prop"), -Punctuation.OpenCurly, -Keyword("get"), -Punctuation.Semicolon, -Keyword("set"), -Punctuation.Semicolon, -Punctuation.CloseCurly); - } + Keyword("public"), + Class("async"), + Property("Prop"), + Punctuation.OpenCurly, + Keyword("get"), + Punctuation.Semicolon, + Keyword("set"), + Punctuation.Semicolon, + Punctuation.CloseCurly); [Theory, CombinatorialData] [WorkItem(60399, "https://github.com/dotnet/roslyn/issues/60339")] - public async Task TestAsyncAsMethodReturnType_NoAsyncInScope(TestHost testHost) - { - await TestAsync( + public Task TestAsyncAsMethodReturnType_NoAsyncInScope(TestHost testHost) + => TestAsync( """ class Test { @@ -2571,18 +2409,16 @@ class Test """, testHost, parseOptions: null, -Keyword("public"), -Keyword("async"), -Method("M"), -Punctuation.OpenParen, -Punctuation.CloseParen); - } + Keyword("public"), + Keyword("async"), + Method("M"), + Punctuation.OpenParen, + Punctuation.CloseParen); [Theory, CombinatorialData] [WorkItem(60399, "https://github.com/dotnet/roslyn/issues/60339")] - public async Task TestAsyncAsMethodReturnType_AsyncInScope(TestHost testHost) - { - await TestAsync( + public Task TestAsyncAsMethodReturnType_AsyncInScope(TestHost testHost) + => TestAsync( """ class async { } @@ -2593,18 +2429,16 @@ class Test """, testHost, parseOptions: null, -Keyword("public"), -Class("async"), -Method("M"), -Punctuation.OpenParen, -Punctuation.CloseParen); - } + Keyword("public"), + Class("async"), + Method("M"), + Punctuation.OpenParen, + Punctuation.CloseParen); [Theory, CombinatorialData] [WorkItem(60399, "https://github.com/dotnet/roslyn/issues/60339")] - public async Task TestAsyncAsAccessingName(TestHost testHost) - { - await TestAsync( + public Task TestAsyncAsAccessingName(TestHost testHost) + => TestAsync( """ class Test { @@ -2621,18 +2455,16 @@ class C """, testHost, parseOptions: null, -Class("C"), -Operators.Dot, -Field("async"), -Static("async"), -Punctuation.Semicolon); - } + Class("C"), + Operators.Dot, + Field("async"), + Static("async"), + Punctuation.Semicolon); [Theory, CombinatorialData] [WorkItem(60399, "https://github.com/dotnet/roslyn/issues/60339")] - public async Task TestAsyncInIncompleteDelegateOrLambda(TestHost testHost) - { - await TestAsync( + public Task TestAsyncInIncompleteDelegateOrLambda(TestHost testHost) + => TestAsync( """ using System; class Test @@ -2645,16 +2477,14 @@ void M() """, testHost, parseOptions: null, -Delegate("Action"), -Local("a"), -Operators.Equals, -Keyword("async")); - } + Delegate("Action"), + Local("a"), + Operators.Equals, + Keyword("async")); [Theory, CombinatorialData] - public async Task TestPartialInIncompleteMember1(TestHost testHost) - { - await TestAsync(""" + public Task TestPartialInIncompleteMember1(TestHost testHost) + => TestAsync(""" class C { [|partial|] @@ -2662,12 +2492,10 @@ class C """, testHost, Keyword("partial")); - } [Theory, CombinatorialData] - public async Task TestPartialInIncompleteMember2(TestHost testHost) - { - await TestAsync(""" + public Task TestPartialInIncompleteMember2(TestHost testHost) + => TestAsync(""" class C { [|public partial|] @@ -2676,12 +2504,10 @@ class C testHost, Keyword("public"), Keyword("partial")); - } [Theory, CombinatorialData] - public async Task TestPartialInIncompleteMember1_PartialTypeIsDefined(TestHost testHost) - { - await TestAsync(""" + public Task TestPartialInIncompleteMember1_PartialTypeIsDefined(TestHost testHost) + => TestAsync(""" class partial { } @@ -2693,12 +2519,10 @@ class C """, testHost, Class("partial")); - } [Theory, CombinatorialData] - public async Task TestPartialInIncompleteMember2_PartialTypeIsDefined(TestHost testHost) - { - await TestAsync(""" + public Task TestPartialInIncompleteMember2_PartialTypeIsDefined(TestHost testHost) + => TestAsync(""" class partial { } @@ -2711,33 +2535,27 @@ class C testHost, Keyword("public"), Class("partial")); - } [Theory, CombinatorialData] - public async Task TestTopLevelPartial1(TestHost testHost) - { - await TestAsync(""" + public Task TestTopLevelPartial1(TestHost testHost) + => TestAsync(""" partial """, testHost, Keyword("partial")); - } [Theory, CombinatorialData] - public async Task TestTopLevelPartial2(TestHost testHost) - { - await TestAsync(""" + public Task TestTopLevelPartial2(TestHost testHost) + => TestAsync(""" public partial """, testHost, Keyword("public"), Keyword("partial")); - } [Theory, CombinatorialData] - public async Task TestTopLevelPartial1_PartialTypeIsDefined(TestHost testHost) - { - await TestAsync(""" + public Task TestTopLevelPartial1_PartialTypeIsDefined(TestHost testHost) + => TestAsync(""" class partial { } @@ -2746,12 +2564,10 @@ class partial """, testHost, Class("partial")); - } [Theory, CombinatorialData] - public async Task TestTopLevelPartial2_PartialTypeIsDefined(TestHost testHost) - { - await TestAsync(""" + public Task TestTopLevelPartial2_PartialTypeIsDefined(TestHost testHost) + => TestAsync(""" class partial { } @@ -2761,14 +2577,12 @@ class partial testHost, Keyword("public"), Class("partial")); - } /// /// [Theory, CombinatorialData] - public async Task LocalFunctionDeclarationAndUse(TestHost testHost) - { - await TestAsync( + public Task LocalFunctionDeclarationAndUse(TestHost testHost) + => TestAsync( """ using System; @@ -2823,12 +2637,10 @@ static void staticLocalFunction() { }|] Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task TestScopedVar(TestHost testHost) - { - await TestAsync(""" + public Task TestScopedVar(TestHost testHost) + => TestAsync(""" static void method(scoped in S s) { scoped var rs1 = s; @@ -2861,12 +2673,10 @@ file readonly ref struct S { } Struct("S"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task Lambda_DefaultParameterValue(TestHost testHost) - { - await TestAsync( + public Task Lambda_DefaultParameterValue(TestHost testHost) + => TestAsync( """ class C { @@ -2889,12 +2699,10 @@ void M() Punctuation.CloseParen, Operators.EqualsGreaterThan, Parameter("x")); - } [Theory, CombinatorialData] - public async Task UsingAliasToType1(TestHost testHost) - { - await TestAsync( + public Task UsingAliasToType1(TestHost testHost) + => TestAsync( """ using X = int; """, @@ -2904,12 +2712,10 @@ await TestAsync( Operators.Equals, Keyword("int"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task UsingAliasToType2(TestHost testHost) - { - await TestAsync( + public Task UsingAliasToType2(TestHost testHost) + => TestAsync( """ using X = int[]; """, @@ -2921,12 +2727,10 @@ await TestAsync( Punctuation.OpenBracket, Punctuation.CloseBracket, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task UsingAliasToType3(TestHost testHost) - { - await TestAsync( + public Task UsingAliasToType3(TestHost testHost) + => TestAsync( """ using unsafe X = int*; """, @@ -2938,12 +2742,10 @@ await TestAsync( Keyword("int"), Operators.Asterisk, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task UsingAliasToType4(TestHost testHost) - { - await TestAsync( + public Task UsingAliasToType4(TestHost testHost) + => TestAsync( """ using unsafe X = delegate*; """, @@ -2960,12 +2762,10 @@ await TestAsync( Keyword("int"), Punctuation.CloseAngle, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task UsingAliasToType5(TestHost testHost) - { - await TestAsync( + public Task UsingAliasToType5(TestHost testHost) + => TestAsync( """ using X = (int x, string b); """, @@ -2981,13 +2781,11 @@ await TestAsync( Identifier("b"), Punctuation.CloseParen, Punctuation.Semicolon); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/70107")] - public async Task TestFunctionPointer1(TestHost testHost) - { - await TestAsync( + public Task TestFunctionPointer1(TestHost testHost) + => TestAsync( """ delegate* unmanaged[Fastcall, Stdcall, Thiscall] fp; """, @@ -3008,13 +2806,11 @@ await TestAsync( Punctuation.CloseAngle, Local("fp"), Punctuation.Semicolon); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/70107")] - public async Task TestFunctionPointer2(TestHost testHost) - { - await TestAsync( + public Task TestFunctionPointer2(TestHost testHost) + => TestAsync( """ delegate* unmanaged[Member] fp; """, @@ -3031,7 +2827,6 @@ await TestAsync( Punctuation.CloseAngle, Local("fp"), Punctuation.Semicolon); - } [WpfFact] public async Task TestTotalClassifier() @@ -3097,29 +2892,41 @@ void M() Keyword("new"), Class("Regex"), Punctuation.OpenParen, - String("\""), + String(""" + " + """), Regex.Grouping("("), Regex.Text("a"), Regex.Grouping(")"), - String("\""), + String(""" + " + """), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("var"), Local("s1"), Operators.Equals, - String("\"s1\""), + String(""" + "s1" + """), Punctuation.Semicolon, Keyword("var"), Local("s2"), Operators.Equals, - String("$\""), + String(""" + $" + """), String("s2"), - String("\""), + String(""" + " + """), Punctuation.Semicolon, Keyword("var"), Local("s3"), Operators.Equals, - Verbatim("@\"s3\""), + Verbatim(""" + @"s3" + """), Punctuation.Semicolon, Keyword("var"), Local("s4"), @@ -3198,29 +3005,41 @@ void M() Keyword("new"), Class("Regex"), Punctuation.OpenParen, - String("\""), + String(""" + " + """), Regex.Grouping("("), Regex.Text("a"), Regex.Grouping(")"), - String("\""), + String(""" + " + """), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("var"), Local("s1"), Operators.Equals, - String("\"s1\""), + String(""" + "s1" + """), Punctuation.Semicolon, Keyword("var"), Local("s2"), Operators.Equals, - String("$\""), + String(""" + $" + """), String("s2"), - String("\""), + String(""" + " + """), Punctuation.Semicolon, Keyword("var"), Local("s3"), Operators.Equals, - Verbatim("@\"s3\""), + Verbatim(""" + @"s3" + """), Punctuation.Semicolon, Keyword("var"), Local("s4"), @@ -3237,9 +3056,8 @@ void M() } [Theory, CombinatorialData] - public async Task TestModernExtension1(TestHost testHost) - { - await TestAsync( + public Task TestModernExtension1(TestHost testHost) + => TestAsync( """ static class C { @@ -3294,5 +3112,4 @@ void M(string s) Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); - } } diff --git a/src/EditorFeatures/CSharpTest/Classification/TotalClassifierTests_Dynamic.cs b/src/EditorFeatures/CSharpTest/Classification/TotalClassifierTests_Dynamic.cs index 80ddf500d042d..14c1e69dd939b 100644 --- a/src/EditorFeatures/CSharpTest/Classification/TotalClassifierTests_Dynamic.cs +++ b/src/EditorFeatures/CSharpTest/Classification/TotalClassifierTests_Dynamic.cs @@ -13,9 +13,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Classification; public sealed partial class TotalClassifierTests { [Theory, CombinatorialData] - public async Task DynamicAsParamTypeAndDefault(TestHost testHost) - { - await TestInClassAsync(@"void M(dynamic d = default(dynamic", + public Task DynamicAsParamTypeAndDefault(TestHost testHost) + => TestInClassAsync(@"void M(dynamic d = default(dynamic", testHost, Keyword("void"), Method("M"), @@ -26,12 +25,10 @@ public async Task DynamicAsParamTypeAndDefault(TestHost testHost) Keyword("default"), Punctuation.OpenParen, Keyword("dynamic")); - } [Theory, CombinatorialData] - public async Task DynamicExplicitConversion(TestHost testHost) - { - await TestInMethodAsync( + public Task DynamicExplicitConversion(TestHost testHost) + => TestInMethodAsync( @"dynamic d = (dynamic)a;", testHost, Keyword("dynamic"), @@ -42,12 +39,10 @@ await TestInMethodAsync( Punctuation.CloseParen, Identifier("a"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task DynamicMethodCall(TestHost testHost) - { - await TestInMethodAsync(@"dynamic.Equals(1, 1);", + public Task DynamicMethodCall(TestHost testHost) + => TestInMethodAsync(@"dynamic.Equals(1, 1);", testHost, Identifier("dynamic"), Operators.Dot, @@ -58,22 +53,18 @@ public async Task DynamicMethodCall(TestHost testHost) Number("1"), Punctuation.CloseParen, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task DynamicNullable(TestHost testHost) - { - await TestInMethodAsync(@"dynamic? a", + public Task DynamicNullable(TestHost testHost) + => TestInMethodAsync(@"dynamic? a", testHost, Keyword("dynamic"), Operators.QuestionMark, Local("a")); - } [Theory, CombinatorialData] - public async Task DynamicAsUsingAliasForClass(TestHost testHost) - { - await TestAsync( + public Task DynamicAsUsingAliasForClass(TestHost testHost) + => TestAsync( @"using dynamic = System.EventArgs;", testHost, Keyword("using"), @@ -83,12 +74,10 @@ await TestAsync( Operators.Dot, Class("EventArgs"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task DynamicAsUsingAliasForDelegate(TestHost testHost) - { - await TestAsync( + public Task DynamicAsUsingAliasForDelegate(TestHost testHost) + => TestAsync( @"using dynamic = System.Action;", testHost, Keyword("using"), @@ -98,12 +87,10 @@ await TestAsync( Operators.Dot, Delegate("Action"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task DynamicAsUsingAliasForStruct(TestHost testHost) - { - await TestAsync( + public Task DynamicAsUsingAliasForStruct(TestHost testHost) + => TestAsync( @"using dynamic = System.DateTime;", testHost, Keyword("using"), @@ -113,12 +100,10 @@ await TestAsync( Operators.Dot, Struct("DateTime"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task DynamicAsUsingAliasForEnum(TestHost testHost) - { - await TestAsync( + public Task DynamicAsUsingAliasForEnum(TestHost testHost) + => TestAsync( @"using dynamic = System.DayOfWeek;", testHost, Keyword("using"), @@ -128,12 +113,10 @@ await TestAsync( Operators.Dot, Enum("DayOfWeek"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task DynamicAsUsingAliasForInterface(TestHost testHost) - { - await TestAsync( + public Task DynamicAsUsingAliasForInterface(TestHost testHost) + => TestAsync( @"using dynamic = System.IDisposable;", testHost, Keyword("using"), @@ -143,12 +126,10 @@ await TestAsync( Operators.Dot, Interface("IDisposable"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task DynamicAsExternAlias(TestHost testHost) - { - await TestAsync( + public Task DynamicAsExternAlias(TestHost testHost) + => TestAsync( """ extern alias dynamic; @@ -171,24 +152,20 @@ class C Field("a"), Punctuation.Semicolon, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task DynamicAsDelegateType(TestHost testHost) - { - await TestAsync(@"delegate void dynamic()", + public Task DynamicAsDelegateType(TestHost testHost) + => TestAsync(@"delegate void dynamic()", testHost, Keyword("delegate"), Keyword("void"), Delegate("dynamic"), Punctuation.OpenParen, Punctuation.CloseParen); - } [Theory, CombinatorialData] - public async Task DynamicAsDelegateReturnTypeAndParam(TestHost testHost) - { - await TestAsync(@"delegate dynamic MyDelegate (dynamic d)", + public Task DynamicAsDelegateReturnTypeAndParam(TestHost testHost) + => TestAsync(@"delegate dynamic MyDelegate (dynamic d)", testHost, Keyword("delegate"), Keyword("dynamic"), @@ -197,12 +174,10 @@ await TestAsync(@"delegate dynamic MyDelegate (dynamic d)", Keyword("dynamic"), Parameter("d"), Punctuation.CloseParen); - } [Theory, CombinatorialData] - public async Task DynamicAsDelegateLocalVariable(TestHost testHost) - { - await TestInMethodAsync( + public Task DynamicAsDelegateLocalVariable(TestHost testHost) + => TestInMethodAsync( """ Func f = delegate { @@ -233,12 +208,10 @@ await TestInMethodAsync( Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task DynamicAsGenericTypeName(TestHost testHost) - { - await TestAsync( + public Task DynamicAsGenericTypeName(TestHost testHost) + => TestAsync( """ partial class dynamic { @@ -268,12 +241,10 @@ class C Field("d"), Punctuation.Semicolon, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task DynamicAsGenericField(TestHost testHost) - { - await TestAsync( + public Task DynamicAsGenericField(TestHost testHost) + => TestAsync( """ class A { @@ -291,12 +262,10 @@ class A Field("dynamic"), Punctuation.Semicolon, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task DynamicAsIndexerTypeAndParameter(TestHost testHost) - { - await TestInClassAsync(@"dynamic this[dynamic i]", + public Task DynamicAsIndexerTypeAndParameter(TestHost testHost) + => TestInClassAsync(@"dynamic this[dynamic i]", testHost, Keyword("dynamic"), Keyword("this"), @@ -304,12 +273,10 @@ await TestInClassAsync(@"dynamic this[dynamic i]", Keyword("dynamic"), Parameter("i"), Punctuation.CloseBracket); - } [Theory, CombinatorialData] - public async Task DynamicAsOperatorTypeAndParameter(TestHost testHost) - { - await TestInClassAsync(@"static dynamic operator +(dynamic d1)", + public Task DynamicAsOperatorTypeAndParameter(TestHost testHost) + => TestInClassAsync(@"static dynamic operator +(dynamic d1)", testHost, Keyword("static"), Keyword("dynamic"), @@ -319,12 +286,10 @@ await TestInClassAsync(@"static dynamic operator +(dynamic d1)", Keyword("dynamic"), Parameter("d1"), Punctuation.CloseParen); - } [Theory, CombinatorialData] - public async Task DynamicAsOperatorName(TestHost testHost) - { - await TestInClassAsync(@"static explicit operator dynamic(dynamic s)", + public Task DynamicAsOperatorName(TestHost testHost) + => TestInClassAsync(@"static explicit operator dynamic(dynamic s)", testHost, Keyword("static"), Keyword("explicit"), @@ -334,12 +299,10 @@ await TestInClassAsync(@"static explicit operator dynamic(dynamic s)", Keyword("dynamic"), Parameter("s"), Punctuation.CloseParen); - } [Theory, CombinatorialData] - public async Task DynamicAsPropertyTypeAndName(TestHost testHost) - { - await TestInClassAsync(@"dynamic dynamic { get; set; }", + public Task DynamicAsPropertyTypeAndName(TestHost testHost) + => TestInClassAsync(@"dynamic dynamic { get; set; }", testHost, Keyword("dynamic"), Property("dynamic"), @@ -349,22 +312,18 @@ public async Task DynamicAsPropertyTypeAndName(TestHost testHost) Keyword("set"), Punctuation.Semicolon, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task DynamicAsEventName(TestHost testHost) - { - await TestInClassAsync(@"event Action dynamic", + public Task DynamicAsEventName(TestHost testHost) + => TestInClassAsync(@"event Action dynamic", testHost, Keyword("event"), Identifier("Action"), Event("dynamic")); - } [Theory, CombinatorialData] - public async Task DynamicAsLinqLocalVariable(TestHost testHost) - { - await TestInMethodAsync(@"var v = from dynamic in names", + public Task DynamicAsLinqLocalVariable(TestHost testHost) + => TestInMethodAsync(@"var v = from dynamic in names", testHost, Keyword("var"), Local("v"), @@ -373,12 +332,10 @@ await TestInMethodAsync(@"var v = from dynamic in names", Identifier("dynamic"), Keyword("in"), Identifier("names")); - } [Theory, CombinatorialData] - public async Task DynamicAsAnonymousTypePropertyName(TestHost testHost) - { - await TestInMethodAsync( + public Task DynamicAsAnonymousTypePropertyName(TestHost testHost) + => TestInMethodAsync( """ var v = from dynamic in names select new { dynamic = dynamic }; @@ -399,12 +356,10 @@ await TestInMethodAsync( Identifier("dynamic"), Punctuation.CloseCurly, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task DynamicAsArgumentToLambdaExpression(TestHost testHost) - { - await TestInMethodAsync( + public Task DynamicAsArgumentToLambdaExpression(TestHost testHost) + => TestInMethodAsync( @"var p = names.Select(dynamic => dynamic.Length);", testHost, Keyword("var"), @@ -421,12 +376,10 @@ await TestInMethodAsync( Identifier("Length"), Punctuation.CloseParen, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task DynamicAsAnonymousMethodLocalVariable(TestHost testHost) - { - await TestInMethodAsync( + public Task DynamicAsAnonymousMethodLocalVariable(TestHost testHost) + => TestInMethodAsync( """ D f = delegate { @@ -454,12 +407,10 @@ await TestInMethodAsync( Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task DynamicAsMethodName(TestHost testHost) - { - await TestInClassAsync( + public Task DynamicAsMethodName(TestHost testHost) + => TestInClassAsync( """ dynamic dynamic() { @@ -472,12 +423,10 @@ dynamic dynamic() Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task DynamicAsStaticMethodTypeAndParams(TestHost testHost) - { - await TestInClassAsync( + public Task DynamicAsStaticMethodTypeAndParams(TestHost testHost) + => TestInClassAsync( """ static dynamic dynamic(params dynamic[] dynamic) { @@ -497,12 +446,10 @@ static dynamic dynamic(params dynamic[] dynamic) Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task DynamicArraysInMethodSignature(TestHost testHost) - { - await TestInClassAsync( + public Task DynamicArraysInMethodSignature(TestHost testHost) + => TestInClassAsync( """ dynamic[] M(dynamic[] p, params dynamic[] pa) { @@ -527,12 +474,10 @@ dynamic[] M(dynamic[] p, params dynamic[] pa) Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task DynamicInPartialMethods(TestHost testHost) - { - await TestInClassAsync( + public Task DynamicInPartialMethods(TestHost testHost) + => TestInClassAsync( """ partial void F(dynamic d); @@ -558,12 +503,10 @@ partial void F(dynamic d) Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task DynamicRefAndOutParameters(TestHost testHost) - { - await TestInClassAsync( + public Task DynamicRefAndOutParameters(TestHost testHost) + => TestInClassAsync( """ void F(ref dynamic r, out dynamic o) { @@ -583,12 +526,10 @@ void F(ref dynamic r, out dynamic o) Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task DynamicInExtensionMethod(TestHost testHost) - { - await TestInClassAsync( + public Task DynamicInExtensionMethod(TestHost testHost) + => TestInClassAsync( """ dynamic F(this dynamic self, dynamic p) { @@ -607,12 +548,10 @@ dynamic F(this dynamic self, dynamic p) Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task DynamicAsBaseClass(TestHost testHost) - { - await TestAsync( + public Task DynamicAsBaseClass(TestHost testHost) + => TestAsync( """ class C : dynamic { @@ -625,12 +564,10 @@ class C : dynamic Keyword("dynamic"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task DynamicAsGenericConstraint(TestHost testHost) - { - await TestAsync( + public Task DynamicAsGenericConstraint(TestHost testHost) + => TestAsync( """ class C where T : dynamic { @@ -648,12 +585,10 @@ class C where T : dynamic Keyword("dynamic"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task DynamicSizeOf(TestHost testHost) - { - await TestInClassAsync( + public Task DynamicSizeOf(TestHost testHost) + => TestInClassAsync( """ unsafe int M() { @@ -674,18 +609,15 @@ unsafe int M() Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task DynamicTypeOf(TestHost testHost) - { - await TestInMethodAsync(@"typeof(dynamic)", + public Task DynamicTypeOf(TestHost testHost) + => TestInMethodAsync(@"typeof(dynamic)", testHost, Keyword("typeof"), Punctuation.OpenParen, Keyword("dynamic"), Punctuation.CloseParen); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] @@ -717,9 +649,8 @@ await TestAsync( } [Theory, CombinatorialData] - public async Task DynamicInForeach(TestHost testHost) - { - await TestInMethodAsync(@"foreach (dynamic dynamic in dynamic", + public Task DynamicInForeach(TestHost testHost) + => TestInMethodAsync(@"foreach (dynamic dynamic in dynamic", testHost, ControlKeyword("foreach"), Punctuation.OpenParen, @@ -727,34 +658,28 @@ await TestInMethodAsync(@"foreach (dynamic dynamic in dynamic", Local("dynamic"), ControlKeyword("in"), Identifier("dynamic")); - } [Theory, CombinatorialData] - public async Task DynamicInUsing(TestHost testHost) - { - await TestInMethodAsync(@"using(dynamic d", + public Task DynamicInUsing(TestHost testHost) + => TestInMethodAsync(@"using(dynamic d", testHost, Keyword("using"), Punctuation.OpenParen, Keyword("dynamic"), Local("d")); - } [Theory, CombinatorialData] - public async Task DynamicAsLocalVariableName(TestHost testHost) - { - await TestInMethodAsync( + public Task DynamicAsLocalVariableName(TestHost testHost) + => TestInMethodAsync( @"dynamic dynamic;", testHost, Keyword("dynamic"), Local("dynamic"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task DynamicAsNamespaceName(TestHost testHost) - { - await TestAsync( + public Task DynamicAsNamespaceName(TestHost testHost) + => TestAsync( """ namespace dynamic { @@ -765,12 +690,10 @@ namespace dynamic Namespace("dynamic"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task DynamicAsClassName(TestHost testHost) - { - await TestAsync( + public Task DynamicAsClassName(TestHost testHost) + => TestAsync( """ class dynamic { @@ -781,12 +704,10 @@ class dynamic Class("dynamic"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task DynamicAsConstructorDeclarationName(TestHost testHost) - { - await TestAsync( + public Task DynamicAsConstructorDeclarationName(TestHost testHost) + => TestAsync( """ class dynamic { @@ -805,12 +726,10 @@ class dynamic Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task DynamicAsNamespaceAlias(TestHost testHost) - { - await TestInMethodAsync( + public Task DynamicAsNamespaceAlias(TestHost testHost) + => TestInMethodAsync( @"dynamic.FileInfo file;", testHost, Identifier("dynamic"), @@ -818,12 +737,10 @@ await TestInMethodAsync( Identifier("FileInfo"), Local("file"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task DynamicAsGotoLabel(TestHost testHost) - { - await TestInMethodAsync( + public Task DynamicAsGotoLabel(TestHost testHost) + => TestInMethodAsync( """ dynamic: int i = 0; goto dynamic; @@ -839,12 +756,10 @@ await TestInMethodAsync( ControlKeyword("goto"), Label("dynamic"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task DynamicAsEnumField(TestHost testHost) - { - await TestInMethodAsync( + public Task DynamicAsEnumField(TestHost testHost) + => TestInMethodAsync( @"A a = A.dynamic;", testHost, Identifier("A"), @@ -854,12 +769,10 @@ await TestInMethodAsync( Operators.Dot, Identifier("dynamic"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task DynamicAsEnumFieldDefinition(TestHost testHost) - { - await TestAsync( + public Task DynamicAsEnumFieldDefinition(TestHost testHost) + => TestAsync( """ enum A { @@ -872,12 +785,10 @@ enum A Punctuation.OpenCurly, EnumMember("dynamic"), Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task DynamicAsEnumType(TestHost testHost) - { - await TestAsync( + public Task DynamicAsEnumType(TestHost testHost) + => TestAsync( """ enum dynamic { @@ -888,12 +799,10 @@ enum dynamic Enum("dynamic"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task DynamicAsGenericTypeParameter(TestHost testHost) - { - await TestAsync( + public Task DynamicAsGenericTypeParameter(TestHost testHost) + => TestAsync( """ class C where dynamic : T { @@ -917,52 +826,42 @@ class C where dynamic : T Field("d"), Punctuation.Semicolon, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task DynamicAsFieldType(TestHost testHost) - { - await TestInClassAsync(@"dynamic d", + public Task DynamicAsFieldType(TestHost testHost) + => TestInClassAsync(@"dynamic d", testHost, Keyword("dynamic"), Field("d")); - } [Theory, CombinatorialData] - public async Task DynamicAsStaticFieldType(TestHost testHost) - { - await TestInClassAsync(@"static dynamic d", + public Task DynamicAsStaticFieldType(TestHost testHost) + => TestInClassAsync(@"static dynamic d", testHost, Keyword("static"), Keyword("dynamic"), Field("d"), Static("d")); - } [Theory, CombinatorialData] - public async Task DynamicAsLocalVariableType(TestHost testHost) - { - await TestInMethodAsync(@"dynamic d", + public Task DynamicAsLocalVariableType(TestHost testHost) + => TestInMethodAsync(@"dynamic d", testHost, Keyword("dynamic"), Local("d")); - } [Theory, CombinatorialData] - public async Task DynamicAsArrayLocalVariableType(TestHost testHost) - { - await TestInMethodAsync(@"dynamic[] d", + public Task DynamicAsArrayLocalVariableType(TestHost testHost) + => TestInMethodAsync(@"dynamic[] d", testHost, Keyword("dynamic"), Punctuation.OpenBracket, Punctuation.CloseBracket, Local("d")); - } [Theory, CombinatorialData] - public async Task DynamicAsLambdaParameterType(TestHost testHost) - { - await TestInMethodAsync( + public Task DynamicAsLambdaParameterType(TestHost testHost) + => TestInMethodAsync( @"var q = a.Where((dynamic d) => d == dynamic);", testHost, Keyword("var"), @@ -982,12 +881,10 @@ await TestInMethodAsync( Identifier("dynamic"), Punctuation.CloseParen, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task DynamicArray(TestHost testHost) - { - await TestInMethodAsync( + public Task DynamicArray(TestHost testHost) + => TestInMethodAsync( @"dynamic d = new dynamic[5];", testHost, Keyword("dynamic"), @@ -999,12 +896,10 @@ await TestInMethodAsync( Number("5"), Punctuation.CloseBracket, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task DynamicConstructor(TestHost testHost) - { - await TestInMethodAsync( + public Task DynamicConstructor(TestHost testHost) + => TestInMethodAsync( @"dynamic d = new dynamic();", testHost, Keyword("dynamic"), @@ -1015,12 +910,10 @@ await TestInMethodAsync( Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task DynamicAfterIs(TestHost testHost) - { - await TestInMethodAsync(@"if (a is dynamic)", + public Task DynamicAfterIs(TestHost testHost) + => TestInMethodAsync(@"if (a is dynamic)", testHost, ControlKeyword("if"), Punctuation.OpenParen, @@ -1028,24 +921,20 @@ await TestInMethodAsync(@"if (a is dynamic)", Keyword("is"), Keyword("dynamic"), Punctuation.CloseParen); - } [Theory, CombinatorialData] - public async Task DynamicAfterAs(TestHost testHost) - { - await TestInMethodAsync(@"a = a as dynamic", + public Task DynamicAfterAs(TestHost testHost) + => TestInMethodAsync(@"a = a as dynamic", testHost, Identifier("a"), Operators.Equals, Identifier("a"), Keyword("as"), Keyword("dynamic")); - } [Theory, CombinatorialData] - public async Task DynamicAsGenericTypeArgument(TestHost testHost) - { - await TestInMethodAsync( + public Task DynamicAsGenericTypeArgument(TestHost testHost) + => TestInMethodAsync( @"List l = new List();", testHost, Identifier("List"), @@ -1062,12 +951,10 @@ await TestInMethodAsync( Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task DynamicAsSecondGenericTypeArgument(TestHost testHost) - { - await TestInMethodAsync( + public Task DynamicAsSecondGenericTypeArgument(TestHost testHost) + => TestInMethodAsync( @"KVP kvp;", testHost, Identifier("KVP"), @@ -1078,29 +965,23 @@ await TestInMethodAsync( Punctuation.CloseAngle, Local("kvp"), Punctuation.Semicolon); - } [Theory, CombinatorialData] - public async Task DynamicAsRegionLabel(TestHost testHost) - { - var code = - """ + public Task DynamicAsRegionLabel(TestHost testHost) + => TestAsync(""" #region dynamic #endregion - """; - await TestAsync(code, + """, testHost, PPKeyword("#"), PPKeyword("region"), PPText("dynamic"), PPKeyword("#"), PPKeyword("endregion")); - } [Theory, CombinatorialData] - public async Task DynamicAsInterfaceType(TestHost testHost) - { - await TestAsync( + public Task DynamicAsInterfaceType(TestHost testHost) + => TestAsync( """ interface dynamic { @@ -1111,12 +992,10 @@ interface dynamic Interface("dynamic"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task DynamicAsStructType(TestHost testHost) - { - await TestAsync( + public Task DynamicAsStructType(TestHost testHost) + => TestAsync( """ struct dynamic { @@ -1127,12 +1006,10 @@ struct dynamic Struct("dynamic"), Punctuation.OpenCurly, Punctuation.CloseCurly); - } [Theory, CombinatorialData] - public async Task DynamicAsUndefinedGenericType(TestHost testHost) - { - await TestInMethodAsync( + public Task DynamicAsUndefinedGenericType(TestHost testHost) + => TestInMethodAsync( @"dynamic d;", testHost, Identifier("dynamic"), @@ -1141,5 +1018,4 @@ await TestInMethodAsync( Punctuation.CloseAngle, Local("d"), Punctuation.Semicolon); - } } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AbstractAddUsingTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AbstractAddUsingTests.cs index 3dd7865eed439..d6cb4ae26b9c0 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AbstractAddUsingTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AbstractAddUsingTests.cs @@ -2,8 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable - +using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; @@ -17,30 +16,24 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddUsing; -public abstract class AbstractAddUsingTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest +public abstract class AbstractAddUsingTests(ITestOutputHelper? logger = null) + : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest(logger) { - protected AbstractAddUsingTests(ITestOutputHelper logger = null) - : base(logger) - { - } - - internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) + internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpAddImportCodeFixProvider()); private protected OptionsCollection SeparateGroups => Option(GenerationOptions.SeparateImportDirectiveGroups, true); - internal async Task TestAsync( - string initialMarkup, - string expectedMarkup, + internal Task TestAsync( + [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string initialMarkup, + [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string expectedMarkup, TestHost testHost, int index = 0, CodeActionPriority? priority = null, - OptionsCollection options = null) - { - await TestInRegularAndScript1Async( + OptionsCollection? options = null) + => TestInRegularAndScript1Async( initialMarkup, expectedMarkup, index, parameters: new TestParameters(options: options, testHost: testHost, priority: priority)); - } } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingTests.cs index 0f7a8a0913cbf..a9f79963b3c59 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingTests.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Threading.Tasks; +using Basic.Reference.Assemblies; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Editing; @@ -14,2033 +15,2137 @@ using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; -using Basic.Reference.Assemblies; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddUsing; [Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)] -public sealed partial class AddUsingTests : AbstractAddUsingTests +public sealed partial class AddUsingTests(ITestOutputHelper logger) : AbstractAddUsingTests(logger) { - public AddUsingTests(ITestOutputHelper logger) - : base(logger) - { - } - [Theory, CombinatorialData] - public async Task TestTypeFromMultipleNamespaces1(TestHost testHost) - { - await TestAsync( -@"class Class -{ - [|IDictionary|] Method() - { - Goo(); - } -}", -@"using System.Collections; + public Task TestTypeFromMultipleNamespaces1(TestHost testHost) + => TestAsync( + """ + class Class + { + [|IDictionary|] Method() + { + Goo(); + } + } + """, + """ + using System.Collections; -class Class -{ - IDictionary Method() - { - Goo(); - } -}", testHost); - } + class Class + { + IDictionary Method() + { + Goo(); + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestTypeFromMultipleNamespaces1_FileScopedNamespace_Outer(TestHost testHost) - { - await TestAsync( -@" -namespace N; + public Task TestTypeFromMultipleNamespaces1_FileScopedNamespace_Outer(TestHost testHost) + => TestAsync( + """ + namespace N; -class Class -{ - [|IDictionary|] Method() - { - Goo(); - } -}", -@" -using System.Collections; + class Class + { + [|IDictionary|] Method() + { + Goo(); + } + } + """, + """ + using System.Collections; -namespace N; + namespace N; -class Class -{ - IDictionary Method() - { - Goo(); - } -}", testHost); - } + class Class + { + IDictionary Method() + { + Goo(); + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestTypeFromMultipleNamespaces1_FileScopedNamespace_Inner(TestHost testHost) - { - await TestAsync( -@" -namespace N; + public Task TestTypeFromMultipleNamespaces1_FileScopedNamespace_Inner(TestHost testHost) + => TestAsync( + """ + namespace N; -using System; + using System; -class Class -{ - [|IDictionary|] Method() - { - Goo(); - } -}", -@" -namespace N; + class Class + { + [|IDictionary|] Method() + { + Goo(); + } + } + """, + """ + namespace N; -using System; -using System.Collections; + using System; + using System.Collections; -class Class -{ - IDictionary Method() - { - Goo(); - } -}", testHost); - } + class Class + { + IDictionary Method() + { + Goo(); + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/11241")] - public async Task TestAddImportWithCaseChange(TestHost testHost) - { - await TestAsync( -@"namespace N1 -{ - public class TextBox - { - } -} + public Task TestAddImportWithCaseChange(TestHost testHost) + => TestAsync( + """ + namespace N1 + { + public class TextBox + { + } + } -class Class1 : [|Textbox|] -{ -}", -@"using N1; + class Class1 : [|Textbox|] + { + } + """, + """ + using N1; -namespace N1 -{ - public class TextBox - { - } -} + namespace N1 + { + public class TextBox + { + } + } -class Class1 : TextBox -{ -}", testHost); - } + class Class1 : TextBox + { + } + """, testHost); [Theory, CombinatorialData] - public async Task TestTypeFromMultipleNamespaces2(TestHost testHost) - { - await TestAsync( -@"class Class -{ - [|IDictionary|] Method() - { - Goo(); - } -}", -@"using System.Collections.Generic; + public Task TestTypeFromMultipleNamespaces2(TestHost testHost) + => TestAsync( + """ + class Class + { + [|IDictionary|] Method() + { + Goo(); + } + } + """, + """ + using System.Collections.Generic; -class Class -{ - IDictionary Method() - { - Goo(); - } -}", + class Class + { + IDictionary Method() + { + Goo(); + } + } + """, testHost, index: 1); - } [Theory, CombinatorialData] - public async Task TestGenericWithNoArgs(TestHost testHost) - { - await TestAsync( -@"class Class -{ - [|List|] Method() - { - Goo(); - } -}", -@"using System.Collections.Generic; + public Task TestGenericWithNoArgs(TestHost testHost) + => TestAsync( + """ + class Class + { + [|List|] Method() + { + Goo(); + } + } + """, + """ + using System.Collections.Generic; -class Class -{ - List Method() - { - Goo(); - } -}", testHost); - } + class Class + { + List Method() + { + Goo(); + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestGenericWithCorrectArgs(TestHost testHost) - { - await TestAsync( -@"class Class -{ - [|List|] Method() - { - Goo(); - } -}", -@"using System.Collections.Generic; + public Task TestGenericWithCorrectArgs(TestHost testHost) + => TestAsync( + """ + class Class + { + [|List|] Method() + { + Goo(); + } + } + """, + """ + using System.Collections.Generic; -class Class -{ - List Method() - { - Goo(); - } -}", testHost); - } + class Class + { + List Method() + { + Goo(); + } + } + """, testHost); [Fact] - public async Task TestGenericWithWrongArgs1() - { - await TestMissingInRegularAndScriptAsync( -@"class Class -{ - [|List|] Method() - { - Goo(); - } -}"); - } + public Task TestGenericWithWrongArgs1() + => TestMissingInRegularAndScriptAsync( + """ + class Class + { + [|List|] Method() + { + Goo(); + } + } + """); [Fact] - public async Task TestGenericWithWrongArgs2() - { - await TestMissingInRegularAndScriptAsync( -@"class Class -{ - [|List|] Method() - { - Goo(); - } -}"); - } + public Task TestGenericWithWrongArgs2() + => TestMissingInRegularAndScriptAsync( + """ + class Class + { + [|List|] Method() + { + Goo(); + } + } + """); [Theory, CombinatorialData] - public async Task TestGenericInLocalDeclaration(TestHost testHost) - { - await TestAsync( -@"class Class -{ - void Goo() - { - [|List|] a = new List(); - } -}", -@"using System.Collections.Generic; + public Task TestGenericInLocalDeclaration(TestHost testHost) + => TestAsync( + """ + class Class + { + void Goo() + { + [|List|] a = new List(); + } + } + """, + """ + using System.Collections.Generic; -class Class -{ - void Goo() - { - List a = new List(); - } -}", testHost); - } + class Class + { + void Goo() + { + List a = new List(); + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestGenericItemType(TestHost testHost) - { - await TestAsync( -@"using System.Collections.Generic; + public Task TestGenericItemType(TestHost testHost) + => TestAsync( + """ + using System.Collections.Generic; -class Class -{ - List<[|Int32|]> l; -}", -@"using System; -using System.Collections.Generic; + class Class + { + List<[|Int32|]> l; + } + """, + """ + using System; + using System.Collections.Generic; -class Class -{ - List l; -}", testHost); - } + class Class + { + List l; + } + """, testHost); [Theory, CombinatorialData] - public async Task TestGenerateWithExistingUsings(TestHost testHost) - { - await TestAsync( -@"using System; - -class Class -{ - [|List|] Method() - { - Goo(); - } -}", -@"using System; -using System.Collections.Generic; + public Task TestGenerateWithExistingUsings(TestHost testHost) + => TestAsync( + """ + using System; -class Class -{ - List Method() - { - Goo(); - } -}", testHost); - } + class Class + { + [|List|] Method() + { + Goo(); + } + } + """, + """ + using System; + using System.Collections.Generic; + + class Class + { + List Method() + { + Goo(); + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestGenerateInNamespace(TestHost testHost) - { - await TestAsync( -@"namespace N -{ - class Class - { - [|List|] Method() - { - Goo(); - } - } -}", -@"using System.Collections.Generic; + public Task TestGenerateInNamespace(TestHost testHost) + => TestAsync( + """ + namespace N + { + class Class + { + [|List|] Method() + { + Goo(); + } + } + } + """, + """ + using System.Collections.Generic; -namespace N -{ - class Class - { - List Method() - { - Goo(); - } - } -}", testHost); - } + namespace N + { + class Class + { + List Method() + { + Goo(); + } + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestGenerateInNamespaceWithUsings(TestHost testHost) - { - await TestAsync( -@"namespace N -{ - using System; + public Task TestGenerateInNamespaceWithUsings(TestHost testHost) + => TestAsync( + """ + namespace N + { + using System; - class Class - { - [|List|] Method() - { - Goo(); - } - } -}", -@"namespace N -{ - using System; - using System.Collections.Generic; + class Class + { + [|List|] Method() + { + Goo(); + } + } + } + """, + """ + namespace N + { + using System; + using System.Collections.Generic; - class Class - { - List Method() - { - Goo(); - } - } -}", testHost); - } + class Class + { + List Method() + { + Goo(); + } + } + } + """, testHost); [Fact] - public async Task TestExistingUsing_ActionCount() - { - await TestActionCountAsync( -@"using System.Collections.Generic; + public Task TestExistingUsing_ActionCount() + => TestActionCountAsync( + """ + using System.Collections.Generic; -class Class -{ - [|IDictionary|] Method() - { - Goo(); - } -}", + class Class + { + [|IDictionary|] Method() + { + Goo(); + } + } + """, count: 1); - } [Theory, CombinatorialData] - public async Task TestExistingUsing(TestHost testHost) - { - await TestAsync( -@"using System.Collections.Generic; + public Task TestExistingUsing(TestHost testHost) + => TestAsync( + """ + using System.Collections.Generic; -class Class -{ - [|IDictionary|] Method() - { - Goo(); - } -}", -@"using System.Collections; -using System.Collections.Generic; + class Class + { + [|IDictionary|] Method() + { + Goo(); + } + } + """, + """ + using System.Collections; + using System.Collections.Generic; -class Class -{ - IDictionary Method() - { - Goo(); - } -}", testHost); - } + class Class + { + IDictionary Method() + { + Goo(); + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")] - public async Task TestAddUsingForGenericExtensionMethod(TestHost testHost) - { - await TestAsync( -@"using System.Collections.Generic; + public Task TestAddUsingForGenericExtensionMethod(TestHost testHost) + => TestAsync( + """ + using System.Collections.Generic; -class Class -{ - void Method(IList args) - { - args.[|Where|]() } -}", -@"using System.Collections.Generic; -using System.Linq; + class Class + { + void Method(IList args) + { + args.[|Where|]() } + } + """, + """ + using System.Collections.Generic; + using System.Linq; -class Class -{ - void Method(IList args) - { - args.Where() } -}", testHost); - } + class Class + { + void Method(IList args) + { + args.Where() } + } + """, testHost); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")] - public async Task TestAddUsingForNormalExtensionMethod() - { - await TestAsync( -@"class Class -{ - void Method(Class args) - { - args.[|Where|]() } -} + public Task TestAddUsingForNormalExtensionMethod() + => TestAsync( + """ + class Class + { + void Method(Class args) + { + args.[|Where|]() } + } -namespace N -{ - static class E - { - public static void Where(this Class c) - { - } - } -}", -@"using N; + namespace N + { + static class E + { + public static void Where(this Class c) + { + } + } + } + """, + """ + using N; -class Class -{ - void Method(Class args) - { - args.Where() } -} + class Class + { + void Method(Class args) + { + args.Where() } + } -namespace N -{ - static class E - { - public static void Where(this Class c) - { - } - } -}", + namespace N + { + static class E + { + public static void Where(this Class c) + { + } + } + } + """, parseOptions: Options.Regular); - } [Theory, CombinatorialData] - public async Task TestOnEnum(TestHost testHost) - { - await TestAsync( -@"class Class -{ - void Goo() - { - var a = [|Colors|].Red; - } -} + public Task TestOnEnum(TestHost testHost) + => TestAsync( + """ + class Class + { + void Goo() + { + var a = [|Colors|].Red; + } + } -namespace A -{ - enum Colors - { - Red, - Green, - Blue - } -}", -@"using A; + namespace A + { + enum Colors + { + Red, + Green, + Blue + } + } + """, + """ + using A; -class Class -{ - void Goo() - { - var a = Colors.Red; - } -} + class Class + { + void Goo() + { + var a = Colors.Red; + } + } -namespace A -{ - enum Colors - { - Red, - Green, - Blue - } -}", testHost); - } + namespace A + { + enum Colors + { + Red, + Green, + Blue + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestOnClassInheritance(TestHost testHost) - { - await TestAsync( -@"class Class : [|Class2|] -{ -} + public Task TestOnClassInheritance(TestHost testHost) + => TestAsync( + """ + class Class : [|Class2|] + { + } -namespace A -{ - class Class2 - { - } -}", -@"using A; + namespace A + { + class Class2 + { + } + } + """, + """ + using A; -class Class : Class2 -{ -} + class Class : Class2 + { + } -namespace A -{ - class Class2 - { - } -}", testHost); - } + namespace A + { + class Class2 + { + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestOnImplementedInterface(TestHost testHost) - { - await TestAsync( -@"class Class : [|IGoo|] -{ -} + public Task TestOnImplementedInterface(TestHost testHost) + => TestAsync( + """ + class Class : [|IGoo|] + { + } -namespace A -{ - interface IGoo - { - } -}", -@"using A; + namespace A + { + interface IGoo + { + } + } + """, + """ + using A; -class Class : IGoo -{ -} + class Class : IGoo + { + } -namespace A -{ - interface IGoo - { - } -}", testHost); - } + namespace A + { + interface IGoo + { + } + } + """, testHost); [Theory, CombinatorialData] public async Task TestAllInBaseList(TestHost testHost) { await TestAsync( -@"class Class : [|IGoo|], Class2 -{ -} + """ + class Class : [|IGoo|], Class2 + { + } -namespace A -{ - class Class2 - { - } -} + namespace A + { + class Class2 + { + } + } -namespace B -{ - interface IGoo - { - } -}", -@"using B; + namespace B + { + interface IGoo + { + } + } + """, + """ + using B; -class Class : IGoo, Class2 -{ -} + class Class : IGoo, Class2 + { + } -namespace A -{ - class Class2 - { - } -} + namespace A + { + class Class2 + { + } + } -namespace B -{ - interface IGoo - { - } -}", testHost); + namespace B + { + interface IGoo + { + } + } + """, testHost); await TestAsync( -@"using B; + """ + using B; -class Class : IGoo, [|Class2|] -{ -} + class Class : IGoo, [|Class2|] + { + } -namespace A -{ - class Class2 - { - } -} + namespace A + { + class Class2 + { + } + } -namespace B -{ - interface IGoo - { - } -}", -@"using A; -using B; + namespace B + { + interface IGoo + { + } + } + """, + """ + using A; + using B; -class Class : IGoo, Class2 -{ -} + class Class : IGoo, Class2 + { + } -namespace A -{ - class Class2 - { - } -} + namespace A + { + class Class2 + { + } + } -namespace B -{ - interface IGoo - { - } -}", testHost); + namespace B + { + interface IGoo + { + } + } + """, testHost); } [Theory, CombinatorialData] - public async Task TestAttributeUnexpanded(TestHost testHost) - { - await TestAsync( -@"[[|Obsolete|]] -class Class -{ -}", -@"using System; + public Task TestAttributeUnexpanded(TestHost testHost) + => TestAsync( + """ + [[|Obsolete|]] + class Class + { + } + """, + """ + using System; -[Obsolete] -class Class -{ -}", testHost); - } + [Obsolete] + class Class + { + } + """, testHost); [Theory, CombinatorialData] - public async Task TestAttributeExpanded(TestHost testHost) - { - await TestAsync( -@"[[|ObsoleteAttribute|]] -class Class -{ -}", -@"using System; + public Task TestAttributeExpanded(TestHost testHost) + => TestAsync( + """ + [[|ObsoleteAttribute|]] + class Class + { + } + """, + """ + using System; -[ObsoleteAttribute] -class Class -{ -}", testHost); - } + [ObsoleteAttribute] + class Class + { + } + """, testHost); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538018")] - public async Task TestAfterNew(TestHost testHost) - { - await TestAsync( -@"class Class -{ - void Goo() - { - List l; - l = new [|List|](); - } -}", -@"using System.Collections.Generic; + public Task TestAfterNew(TestHost testHost) + => TestAsync( + """ + class Class + { + void Goo() + { + List l; + l = new [|List|](); + } + } + """, + """ + using System.Collections.Generic; -class Class -{ - void Goo() - { - List l; - l = new List(); - } -}", testHost); - } + class Class + { + void Goo() + { + List l; + l = new List(); + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestArgumentsInMethodCall(TestHost testHost) - { - await TestAsync( -@"class Class -{ - void Test() - { - Console.WriteLine([|DateTime|].Today); - } -}", -@"using System; + public Task TestArgumentsInMethodCall(TestHost testHost) + => TestAsync( + """ + class Class + { + void Test() + { + Console.WriteLine([|DateTime|].Today); + } + } + """, + """ + using System; -class Class -{ - void Test() - { - Console.WriteLine(DateTime.Today); - } -}", testHost); - } + class Class + { + void Test() + { + Console.WriteLine(DateTime.Today); + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestCallSiteArgs(TestHost testHost) - { - await TestAsync( -@"class Class -{ - void Test([|DateTime|] dt) - { - } -}", -@"using System; + public Task TestCallSiteArgs(TestHost testHost) + => TestAsync( + """ + class Class + { + void Test([|DateTime|] dt) + { + } + } + """, + """ + using System; -class Class -{ - void Test(DateTime dt) - { - } -}", testHost); - } + class Class + { + void Test(DateTime dt) + { + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestUsePartialClass(TestHost testHost) - { - await TestAsync( -@"namespace A -{ - public class Class - { - [|PClass|] c; - } -} + public Task TestUsePartialClass(TestHost testHost) + => TestAsync( + """ + namespace A + { + public class Class + { + [|PClass|] c; + } + } -namespace B -{ - public partial class PClass - { - } -}", -@"using B; + namespace B + { + public partial class PClass + { + } + } + """, + """ + using B; -namespace A -{ - public class Class - { - PClass c; - } -} + namespace A + { + public class Class + { + PClass c; + } + } -namespace B -{ - public partial class PClass - { - } -}", testHost); - } + namespace B + { + public partial class PClass + { + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestGenericClassInNestedNamespace(TestHost testHost) - { - await TestAsync( -@"namespace A -{ - namespace B - { - class GenericClass - { - } - } -} + public Task TestGenericClassInNestedNamespace(TestHost testHost) + => TestAsync( + """ + namespace A + { + namespace B + { + class GenericClass + { + } + } + } -namespace C -{ - class Class - { - [|GenericClass|] c; - } -}", -@"using A.B; + namespace C + { + class Class + { + [|GenericClass|] c; + } + } + """, + """ + using A.B; -namespace A -{ - namespace B - { - class GenericClass - { - } - } -} + namespace A + { + namespace B + { + class GenericClass + { + } + } + } -namespace C -{ - class Class - { - GenericClass c; - } -}", testHost); - } + namespace C + { + class Class + { + GenericClass c; + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")] - public async Task TestExtensionMethods(TestHost testHost) - { - await TestAsync( -@"using System.Collections.Generic; + public Task TestExtensionMethods(TestHost testHost) + => TestAsync( + """ + using System.Collections.Generic; -class Goo -{ - void Bar() - { - var values = new List(); - values.[|Where|](i => i > 1); - } -}", -@"using System.Collections.Generic; -using System.Linq; + class Goo + { + void Bar() + { + var values = new List(); + values.[|Where|](i => i > 1); + } + } + """, + """ + using System.Collections.Generic; + using System.Linq; -class Goo -{ - void Bar() - { - var values = new List(); - values.Where(i => i > 1); - } -}", testHost); - } + class Goo + { + void Bar() + { + var values = new List(); + values.Where(i => i > 1); + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")] - public async Task TestQueryPatterns(TestHost testHost) - { - await TestAsync( -@"using System.Collections.Generic; + public Task TestQueryPatterns(TestHost testHost) + => TestAsync( + """ + using System.Collections.Generic; -class Goo -{ - void Bar() - { - var values = new List(); - var q = [|from v in values - where v > 1 - select v + 10|]; - } -}", -@"using System.Collections.Generic; -using System.Linq; + class Goo + { + void Bar() + { + var values = new List(); + var q = [|from v in values + where v > 1 + select v + 10|]; + } + } + """, + """ + using System.Collections.Generic; + using System.Linq; -class Goo -{ - void Bar() - { - var values = new List(); - var q = from v in values - where v > 1 - select v + 10; - } -}", testHost); - } + class Goo + { + void Bar() + { + var values = new List(); + var q = from v in values + where v > 1 + select v + 10; + } + } + """, testHost); // Tests for Insertion Order [Theory, CombinatorialData] - public async Task TestSimplePresortedUsings1(TestHost testHost) - { - await TestAsync( -@"using B; -using C; + public Task TestSimplePresortedUsings1(TestHost testHost) + => TestAsync( + """ + using B; + using C; -class Class -{ - void Method() - { - [|Goo|].Bar(); - } -} + class Class + { + void Method() + { + [|Goo|].Bar(); + } + } -namespace D -{ - class Goo - { - public static void Bar() - { - } - } -}", -@"using B; -using C; -using D; + namespace D + { + class Goo + { + public static void Bar() + { + } + } + } + """, + """ + using B; + using C; + using D; -class Class -{ - void Method() - { - Goo.Bar(); - } -} + class Class + { + void Method() + { + Goo.Bar(); + } + } -namespace D -{ - class Goo - { - public static void Bar() - { - } - } -}", testHost); - } + namespace D + { + class Goo + { + public static void Bar() + { + } + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestSimplePresortedUsings2(TestHost testHost) - { - await TestAsync( -@"using B; -using C; + public Task TestSimplePresortedUsings2(TestHost testHost) + => TestAsync( + """ + using B; + using C; -class Class -{ - void Method() - { - [|Goo|].Bar(); - } -} + class Class + { + void Method() + { + [|Goo|].Bar(); + } + } -namespace A -{ - class Goo - { - public static void Bar() - { - } - } -}", -@"using A; -using B; -using C; + namespace A + { + class Goo + { + public static void Bar() + { + } + } + } + """, + """ + using A; + using B; + using C; -class Class -{ - void Method() - { - Goo.Bar(); - } -} + class Class + { + void Method() + { + Goo.Bar(); + } + } -namespace A -{ - class Goo - { - public static void Bar() - { - } - } -}", testHost); - } + namespace A + { + class Goo + { + public static void Bar() + { + } + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestSimpleUnsortedUsings1(TestHost testHost) - { - await TestAsync( -@"using C; -using B; + public Task TestSimpleUnsortedUsings1(TestHost testHost) + => TestAsync( + """ + using C; + using B; -class Class -{ - void Method() - { - [|Goo|].Bar(); - } -} + class Class + { + void Method() + { + [|Goo|].Bar(); + } + } -namespace A -{ - class Goo - { - public static void Bar() - { - } - } -}", -@"using C; -using B; -using A; + namespace A + { + class Goo + { + public static void Bar() + { + } + } + } + """, + """ + using C; + using B; + using A; -class Class -{ - void Method() - { - Goo.Bar(); - } -} + class Class + { + void Method() + { + Goo.Bar(); + } + } -namespace A -{ - class Goo - { - public static void Bar() - { - } - } -}", testHost); - } + namespace A + { + class Goo + { + public static void Bar() + { + } + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestSimpleUnsortedUsings2(TestHost testHost) - { - await TestAsync( -@"using D; -using B; + public Task TestSimpleUnsortedUsings2(TestHost testHost) + => TestAsync( + """ + using D; + using B; -class Class -{ - void Method() - { - [|Goo|].Bar(); - } -} + class Class + { + void Method() + { + [|Goo|].Bar(); + } + } -namespace C -{ - class Goo - { - public static void Bar() - { - } - } -}", -@"using D; -using B; -using C; + namespace C + { + class Goo + { + public static void Bar() + { + } + } + } + """, + """ + using D; + using B; + using C; -class Class -{ - void Method() - { - Goo.Bar(); - } -} + class Class + { + void Method() + { + Goo.Bar(); + } + } -namespace C -{ - class Goo - { - public static void Bar() - { - } - } -}", testHost); - } + namespace C + { + class Goo + { + public static void Bar() + { + } + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestMultiplePresortedUsings1(TestHost testHost) - { - await TestAsync( -@"using B.X; -using B.Y; + public Task TestMultiplePresortedUsings1(TestHost testHost) + => TestAsync( + """ + using B.X; + using B.Y; -class Class -{ - void Method() - { - [|Goo|].Bar(); - } -} + class Class + { + void Method() + { + [|Goo|].Bar(); + } + } -namespace B -{ - class Goo - { - public static void Bar() - { - } - } -}", -@"using B; -using B.X; -using B.Y; + namespace B + { + class Goo + { + public static void Bar() + { + } + } + } + """, + """ + using B; + using B.X; + using B.Y; -class Class -{ - void Method() - { - Goo.Bar(); - } -} + class Class + { + void Method() + { + Goo.Bar(); + } + } -namespace B -{ - class Goo - { - public static void Bar() - { - } - } -}", testHost); - } + namespace B + { + class Goo + { + public static void Bar() + { + } + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestMultiplePresortedUsings2(TestHost testHost) - { - await TestAsync( -@"using B.X; -using B.Y; + public Task TestMultiplePresortedUsings2(TestHost testHost) + => TestAsync( + """ + using B.X; + using B.Y; -class Class -{ - void Method() - { - [|Goo|].Bar(); - } -} + class Class + { + void Method() + { + [|Goo|].Bar(); + } + } -namespace B.A -{ - class Goo - { - public static void Bar() - { - } - } -}", -@"using B.A; -using B.X; -using B.Y; + namespace B.A + { + class Goo + { + public static void Bar() + { + } + } + } + """, + """ + using B.A; + using B.X; + using B.Y; -class Class -{ - void Method() - { - Goo.Bar(); - } -} + class Class + { + void Method() + { + Goo.Bar(); + } + } -namespace B.A -{ - class Goo - { - public static void Bar() - { - } - } -}", testHost); - } + namespace B.A + { + class Goo + { + public static void Bar() + { + } + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestMultiplePresortedUsings3(TestHost testHost) - { - await TestAsync( -@"using B.X; -using B.Y; + public Task TestMultiplePresortedUsings3(TestHost testHost) + => TestAsync( + """ + using B.X; + using B.Y; -class Class -{ - void Method() - { - [|Goo|].Bar(); - } -} + class Class + { + void Method() + { + [|Goo|].Bar(); + } + } -namespace B -{ - namespace A - { - class Goo - { - public static void Bar() + namespace B { + namespace A + { + class Goo + { + public static void Bar() + { + } + } + } } - } - } -}", -@"using B.A; -using B.X; -using B.Y; + """, + """ + using B.A; + using B.X; + using B.Y; -class Class -{ - void Method() - { - Goo.Bar(); - } -} + class Class + { + void Method() + { + Goo.Bar(); + } + } -namespace B -{ - namespace A - { - class Goo - { - public static void Bar() + namespace B { + namespace A + { + class Goo + { + public static void Bar() + { + } + } + } } - } - } -}", testHost); - } + """, testHost); [Theory, CombinatorialData] - public async Task TestMultipleUnsortedUsings1(TestHost testHost) - { - await TestAsync( -@"using B.Y; -using B.X; + public Task TestMultipleUnsortedUsings1(TestHost testHost) + => TestAsync( + """ + using B.Y; + using B.X; -class Class -{ - void Method() - { - [|Goo|].Bar(); - } -} + class Class + { + void Method() + { + [|Goo|].Bar(); + } + } -namespace B -{ - namespace A - { - class Goo - { - public static void Bar() + namespace B { + namespace A + { + class Goo + { + public static void Bar() + { + } + } + } } - } - } -}", -@"using B.Y; -using B.X; -using B.A; + """, + """ + using B.Y; + using B.X; + using B.A; -class Class -{ - void Method() - { - Goo.Bar(); - } -} + class Class + { + void Method() + { + Goo.Bar(); + } + } -namespace B -{ - namespace A - { - class Goo - { - public static void Bar() + namespace B { + namespace A + { + class Goo + { + public static void Bar() + { + } + } + } } - } - } -}", testHost); - } + """, testHost); [Theory, CombinatorialData] - public async Task TestMultipleUnsortedUsings2(TestHost testHost) - { - await TestAsync( -@"using B.Y; -using B.X; + public Task TestMultipleUnsortedUsings2(TestHost testHost) + => TestAsync( + """ + using B.Y; + using B.X; -class Class -{ - void Method() - { - [|Goo|].Bar(); - } -} + class Class + { + void Method() + { + [|Goo|].Bar(); + } + } -namespace B -{ - class Goo - { - public static void Bar() - { - } - } -}", -@"using B.Y; -using B.X; -using B; + namespace B + { + class Goo + { + public static void Bar() + { + } + } + } + """, + """ + using B.Y; + using B.X; + using B; -class Class -{ - void Method() - { - Goo.Bar(); - } -} + class Class + { + void Method() + { + Goo.Bar(); + } + } -namespace B -{ - class Goo - { - public static void Bar() - { - } - } -}", testHost); - } + namespace B + { + class Goo + { + public static void Bar() + { + } + } + } + """, testHost); // System on top cases [Theory, CombinatorialData] - public async Task TestSimpleSystemSortedUsings1(TestHost testHost) - { - await TestAsync( -@"using System; -using B; + public Task TestSimpleSystemSortedUsings1(TestHost testHost) + => TestAsync( + """ + using System; + using B; -class Class -{ - void Method() - { - [|Goo|].Bar(); - } -} + class Class + { + void Method() + { + [|Goo|].Bar(); + } + } -namespace A -{ - class Goo - { - public static void Bar() - { - } - } -}", -@"using System; -using A; -using B; + namespace A + { + class Goo + { + public static void Bar() + { + } + } + } + """, + """ + using System; + using A; + using B; -class Class -{ - void Method() - { - Goo.Bar(); - } -} + class Class + { + void Method() + { + Goo.Bar(); + } + } -namespace A -{ - class Goo - { - public static void Bar() - { - } - } -}", + namespace A + { + class Goo + { + public static void Bar() + { + } + } + } + """, testHost); - } [Theory, CombinatorialData] - public async Task TestSimpleSystemSortedUsings2(TestHost testHost) - { - await TestAsync( -@"using System; -using System.Collections.Generic; -using B; + public Task TestSimpleSystemSortedUsings2(TestHost testHost) + => TestAsync( + """ + using System; + using System.Collections.Generic; + using B; -class Class -{ - void Method() - { - [|Goo|].Bar(); - } -} + class Class + { + void Method() + { + [|Goo|].Bar(); + } + } -namespace A -{ - class Goo - { - public static void Bar() - { - } - } -}", -@"using System; -using System.Collections.Generic; -using A; -using B; + namespace A + { + class Goo + { + public static void Bar() + { + } + } + } + """, + """ + using System; + using System.Collections.Generic; + using A; + using B; -class Class -{ - void Method() - { - Goo.Bar(); - } -} + class Class + { + void Method() + { + Goo.Bar(); + } + } -namespace A -{ - class Goo - { - public static void Bar() - { - } - } -}", + namespace A + { + class Goo + { + public static void Bar() + { + } + } + } + """, testHost); - } [Theory, CombinatorialData] - public async Task TestSimpleSystemSortedUsings3(TestHost testHost) - { - await TestAsync( -@"using A; -using B; + public Task TestSimpleSystemSortedUsings3(TestHost testHost) + => TestAsync( + """ + using A; + using B; -class Class -{ - void Method() - { - [|Console|].Write(1); - } -}", -@"using System; -using A; -using B; + class Class + { + void Method() + { + [|Console|].Write(1); + } + } + """, + """ + using System; + using A; + using B; -class Class -{ - void Method() - { - Console.Write(1); - } -}", + class Class + { + void Method() + { + Console.Write(1); + } + } + """, testHost); - } [Theory, CombinatorialData] - public async Task TestSimpleSystemUnsortedUsings1(TestHost testHost) - { - await TestAsync( -@" -using C; -using B; -using System; + public Task TestSimpleSystemUnsortedUsings1(TestHost testHost) + => TestAsync( + """ + using C; + using B; + using System; -class Class -{ - void Method() - { - [|Goo|].Bar(); - } -} + class Class + { + void Method() + { + [|Goo|].Bar(); + } + } -namespace A -{ - class Goo - { - public static void Bar() - { - } - } -}", -@" -using C; -using B; -using System; -using A; - -class Class -{ - void Method() - { - Goo.Bar(); - } -} + namespace A + { + class Goo + { + public static void Bar() + { + } + } + } + """, + """ + using C; + using B; + using System; + using A; -namespace A -{ - class Goo - { - public static void Bar() - { - } - } -}", + class Class + { + void Method() + { + Goo.Bar(); + } + } + + namespace A + { + class Goo + { + public static void Bar() + { + } + } + } + """, testHost); - } [Theory, CombinatorialData] - public async Task TestSimpleSystemUnsortedUsings2(TestHost testHost) - { - await TestAsync( -@"using System.Collections.Generic; -using System; -using B; + public Task TestSimpleSystemUnsortedUsings2(TestHost testHost) + => TestAsync( + """ + using System.Collections.Generic; + using System; + using B; -class Class -{ - void Method() - { - [|Goo|].Bar(); - } -} + class Class + { + void Method() + { + [|Goo|].Bar(); + } + } -namespace A -{ - class Goo - { - public static void Bar() - { - } - } -}", -@"using System.Collections.Generic; -using System; -using B; -using A; + namespace A + { + class Goo + { + public static void Bar() + { + } + } + } + """, + """ + using System.Collections.Generic; + using System; + using B; + using A; -class Class -{ - void Method() - { - Goo.Bar(); - } -} + class Class + { + void Method() + { + Goo.Bar(); + } + } -namespace A -{ - class Goo - { - public static void Bar() - { - } - } -}", + namespace A + { + class Goo + { + public static void Bar() + { + } + } + } + """, testHost); - } [Theory, CombinatorialData] - public async Task TestSimpleSystemUnsortedUsings3(TestHost testHost) - { - await TestAsync( -@"using B; -using A; + public Task TestSimpleSystemUnsortedUsings3(TestHost testHost) + => TestAsync( + """ + using B; + using A; -class Class -{ - void Method() - { - [|Console|].Write(1); - } -}", -@"using B; -using A; -using System; + class Class + { + void Method() + { + [|Console|].Write(1); + } + } + """, + """ + using B; + using A; + using System; -class Class -{ - void Method() - { - Console.Write(1); - } -}", + class Class + { + void Method() + { + Console.Write(1); + } + } + """, testHost); - } [Theory, CombinatorialData] - public async Task TestSimpleBogusSystemUsings1(TestHost testHost) - { - await TestAsync( -@"using A.System; + public Task TestSimpleBogusSystemUsings1(TestHost testHost) + => TestAsync( + """ + using A.System; -class Class -{ - void Method() - { - [|Console|].Write(1); - } -}", -@"using System; -using A.System; + class Class + { + void Method() + { + [|Console|].Write(1); + } + } + """, + """ + using System; + using A.System; -class Class -{ - void Method() - { - Console.Write(1); - } -}", + class Class + { + void Method() + { + Console.Write(1); + } + } + """, testHost); - } [Theory, CombinatorialData] - public async Task TestSimpleBogusSystemUsings2(TestHost testHost) - { - await TestAsync( -@"using System.System; + public Task TestSimpleBogusSystemUsings2(TestHost testHost) + => TestAsync( + """ + using System.System; -class Class -{ - void Method() - { - [|Console|].Write(1); - } -}", -@"using System; -using System.System; + class Class + { + void Method() + { + [|Console|].Write(1); + } + } + """, + """ + using System; + using System.System; -class Class -{ - void Method() - { - Console.Write(1); - } -}", + class Class + { + void Method() + { + Console.Write(1); + } + } + """, testHost); - } [Theory, CombinatorialData] - public async Task TestUsingsWithComments(TestHost testHost) - { - await TestAsync( -@"using System./*...*/.Collections.Generic; + public Task TestUsingsWithComments(TestHost testHost) + => TestAsync( + """ + using System./*...*/.Collections.Generic; -class Class -{ - void Method() - { - [|Console|].Write(1); - } -}", -@"using System; -using System./*...*/.Collections.Generic; + class Class + { + void Method() + { + [|Console|].Write(1); + } + } + """, + """ + using System; + using System./*...*/.Collections.Generic; -class Class -{ - void Method() - { - Console.Write(1); - } -}", + class Class + { + void Method() + { + Console.Write(1); + } + } + """, testHost); - } // System Not on top cases [Theory, CombinatorialData] - public async Task TestSimpleSystemUnsortedUsings4(TestHost testHost) - { - await TestAsync( -@" -using C; -using System; -using B; + public Task TestSimpleSystemUnsortedUsings4(TestHost testHost) + => TestAsync( + """ + using C; + using System; + using B; -class Class -{ - void Method() - { - [|Goo|].Bar(); - } -} + class Class + { + void Method() + { + [|Goo|].Bar(); + } + } -namespace A -{ - class Goo - { - public static void Bar() - { - } - } -}", -@" -using C; -using System; -using B; -using A; - -class Class -{ - void Method() - { - Goo.Bar(); - } -} + namespace A + { + class Goo + { + public static void Bar() + { + } + } + } + """, + """ + using C; + using System; + using B; + using A; -namespace A -{ - class Goo - { - public static void Bar() - { - } - } -}", + class Class + { + void Method() + { + Goo.Bar(); + } + } + + namespace A + { + class Goo + { + public static void Bar() + { + } + } + } + """, testHost); - } [Theory, CombinatorialData] - public async Task TestSimpleSystemSortedUsings5(TestHost testHost) - { - await TestAsync( -@"using B; -using System; + public Task TestSimpleSystemSortedUsings5(TestHost testHost) + => TestAsync( + """ + using B; + using System; -class Class -{ - void Method() - { - [|Goo|].Bar(); - } -} + class Class + { + void Method() + { + [|Goo|].Bar(); + } + } -namespace A -{ - class Goo - { - public static void Bar() - { - } - } -}", -@"using A; -using B; -using System; + namespace A + { + class Goo + { + public static void Bar() + { + } + } + } + """, + """ + using A; + using B; + using System; -class Class -{ - void Method() - { - Goo.Bar(); - } -} + class Class + { + void Method() + { + Goo.Bar(); + } + } -namespace A -{ - class Goo - { - public static void Bar() - { - } - } -}", + namespace A + { + class Goo + { + public static void Bar() + { + } + } + } + """, testHost); - } [Theory, CombinatorialData] - public async Task TestSimpleSystemSortedUsings4(TestHost testHost) - { - await TestAsync( -@"using A; -using B; + public Task TestSimpleSystemSortedUsings4(TestHost testHost) + => TestAsync( + """ + using A; + using B; -class Class -{ - void Method() - { - [|Console|].Write(1); - } -}", -@"using A; -using B; -using System; + class Class + { + void Method() + { + [|Console|].Write(1); + } + } + """, + """ + using A; + using B; + using System; -class Class -{ - void Method() - { - Console.Write(1); - } -}", + class Class + { + void Method() + { + Console.Write(1); + } + } + """, testHost, options: Option(GenerationOptions.PlaceSystemNamespaceFirst, false)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538136")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538763")] - public async Task TestAddUsingForNamespace() - { - await TestMissingInRegularAndScriptAsync( -@"namespace A -{ - class Class - { - [|C|].Test t; - } -} + public Task TestAddUsingForNamespace() + => TestMissingInRegularAndScriptAsync( + """ + namespace A + { + class Class + { + [|C|].Test t; + } + } -namespace B -{ - namespace C - { - class Test - { - } - } -}"); - } + namespace B + { + namespace C + { + class Test + { + } + } + } + """); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538220")] - public async Task TestAddUsingForFieldWithFormatting(TestHost testHost) - { - await TestAsync( -@"class C { [|DateTime|] t; }", -@"using System; + public Task TestAddUsingForFieldWithFormatting(TestHost testHost) + => TestAsync( + @"class C { [|DateTime|] t; }", + """ + using System; -class C { DateTime t; }", testHost); - } + class C { DateTime t; } + """, testHost); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539657")] - public async Task BugFix5688(TestHost testHost) - { - await TestAsync( -@"class Program { static void Main ( string [ ] args ) { [|Console|] . Out . NewLine = ""\r\n\r\n"" ; } } ", -@"using System; + public Task BugFix5688(TestHost testHost) + => TestAsync( + @"class Program { static void Main ( string [ ] args ) { [|Console|] . Out . NewLine = ""\r\n\r\n"" ; } }", + """ + using System; -class Program { static void Main ( string [ ] args ) { Console . Out . NewLine = ""\r\n\r\n"" ; } } ", testHost); - } + class Program { static void Main ( string [ ] args ) { Console . Out . NewLine = "\r\n\r\n" ; } } + """, testHost); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539853")] - public async Task BugFix5950() - { - await TestAsync( + public Task BugFix5950() + => TestAsync( @"using System.Console; WriteLine([|Expression|].Constant(123));", -@"using System.Console; +""" +using System.Console; using System.Linq.Expressions; -WriteLine(Expression.Constant(123));", +WriteLine(Expression.Constant(123)); +""", parseOptions: GetScriptOptions()); - } [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540339")] - public async Task TestAddAfterDefineDirective1(TestHost testHost) - { - await TestAsync( -@"#define goo + public Task TestAddAfterDefineDirective1(TestHost testHost) + => TestAsync( + """ + #define goo -using System.Collections.Generic; -using System.Linq; + using System.Collections.Generic; + using System.Linq; -class Program -{ - static void Main(string[] args) - { - [|Console|].WriteLine(); - } -}", -@"#define goo + class Program + { + static void Main(string[] args) + { + [|Console|].WriteLine(); + } + } + """, + """ + #define goo -using System; -using System.Collections.Generic; -using System.Linq; + using System; + using System.Collections.Generic; + using System.Linq; -class Program -{ - static void Main(string[] args) - { - Console.WriteLine(); - } -}", testHost); - } + class Program + { + static void Main(string[] args) + { + Console.WriteLine(); + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540339")] - public async Task TestAddAfterDefineDirective2(TestHost testHost) - { - await TestAsync( -@"#define goo + public Task TestAddAfterDefineDirective2(TestHost testHost) + => TestAsync( + """ + #define goo -class Program -{ - static void Main(string[] args) - { - [|Console|].WriteLine(); - } -}", -@"#define goo + class Program + { + static void Main(string[] args) + { + [|Console|].WriteLine(); + } + } + """, + """ + #define goo -using System; + using System; -class Program -{ - static void Main(string[] args) - { - Console.WriteLine(); - } -}", testHost); - } + class Program + { + static void Main(string[] args) + { + Console.WriteLine(); + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestAddAfterDefineDirective3(TestHost testHost) - { - await TestAsync( -@"#define goo + public Task TestAddAfterDefineDirective3(TestHost testHost) + => TestAsync( + """ + #define goo -/// Goo -class Program -{ - static void Main(string[] args) - { - [|Console|].WriteLine(); - } -}", -@"#define goo + /// Goo + class Program + { + static void Main(string[] args) + { + [|Console|].WriteLine(); + } + } + """, + """ + #define goo -using System; + using System; -/// Goo -class Program -{ - static void Main(string[] args) - { - Console.WriteLine(); - } -}", testHost); - } + /// Goo + class Program + { + static void Main(string[] args) + { + Console.WriteLine(); + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestAddAfterDefineDirective4(TestHost testHost) - { - await TestAsync( -@"#define goo + public Task TestAddAfterDefineDirective4(TestHost testHost) + => TestAsync( + """ + #define goo -// Goo -class Program -{ - static void Main(string[] args) - { - [|Console|].WriteLine(); - } -}", -@"#define goo + // Goo + class Program + { + static void Main(string[] args) + { + [|Console|].WriteLine(); + } + } + """, + """ + #define goo -// Goo -using System; + // Goo + using System; -class Program -{ - static void Main(string[] args) - { - Console.WriteLine(); - } -}", testHost); - } + class Program + { + static void Main(string[] args) + { + Console.WriteLine(); + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestAddAfterExistingBanner(TestHost testHost) - { - await TestAsync( -@"// Banner -// Banner + public Task TestAddAfterExistingBanner(TestHost testHost) + => TestAsync( + """ + // Banner + // Banner -class Program -{ - static void Main(string[] args) - { - [|Console|].WriteLine(); - } -}", -@"// Banner -// Banner + class Program + { + static void Main(string[] args) + { + [|Console|].WriteLine(); + } + } + """, + """ + // Banner + // Banner -using System; + using System; -class Program -{ - static void Main(string[] args) - { - Console.WriteLine(); - } -}", testHost); - } + class Program + { + static void Main(string[] args) + { + Console.WriteLine(); + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestAddAfterExternAlias1(TestHost testHost) - { - await TestAsync( -@"#define goo + public Task TestAddAfterExternAlias1(TestHost testHost) + => TestAsync( + """ + #define goo -extern alias Goo; + extern alias Goo; -class Program -{ - static void Main(string[] args) - { - [|Console|].WriteLine(); - } -}", -@"#define goo + class Program + { + static void Main(string[] args) + { + [|Console|].WriteLine(); + } + } + """, + """ + #define goo -extern alias Goo; + extern alias Goo; -using System; + using System; -class Program -{ - static void Main(string[] args) - { - Console.WriteLine(); - } -}", testHost); - } + class Program + { + static void Main(string[] args) + { + Console.WriteLine(); + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestAddAfterExternAlias2(TestHost testHost) - { - await TestAsync( -@"#define goo + public Task TestAddAfterExternAlias2(TestHost testHost) + => TestAsync( + """ + #define goo -extern alias Goo; + extern alias Goo; -using System.Collections; + using System.Collections; -class Program -{ - static void Main(string[] args) - { - [|Console|].WriteLine(); - } -}", -@"#define goo + class Program + { + static void Main(string[] args) + { + [|Console|].WriteLine(); + } + } + """, + """ + #define goo -extern alias Goo; + extern alias Goo; -using System; -using System.Collections; + using System; + using System.Collections; -class Program -{ - static void Main(string[] args) - { - Console.WriteLine(); - } -}", testHost); - } + class Program + { + static void Main(string[] args) + { + Console.WriteLine(); + } + } + """, testHost); [Fact] public async Task TestWithReferenceDirective() @@ -2051,400 +2156,410 @@ public async Task TestWithReferenceDirective() }); await TestAsync( -@"#r ""exprs"" -[|Expression|]", -@"#r ""exprs"" -using System.Linq.Expressions; + """ + #r "exprs" + [|Expression|] + """, + """ + #r "exprs" + using System.Linq.Expressions; -Expression", + Expression + """, GetScriptOptions(), TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); } [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542643")] - public async Task TestAssemblyAttribute(TestHost testHost) - { - await TestAsync( -@"[assembly: [|InternalsVisibleTo|](""Project"")]", -@"using System.Runtime.CompilerServices; + public Task TestAssemblyAttribute(TestHost testHost) + => TestAsync( + @"[assembly: [|InternalsVisibleTo|](""Project"")]", + """ + using System.Runtime.CompilerServices; -[assembly: InternalsVisibleTo(""Project"")]", testHost); - } + [assembly: InternalsVisibleTo("Project")] + """, testHost); [Fact] - public async Task TestDoNotAddIntoHiddenRegion() - { - await TestMissingInRegularAndScriptAsync( -@"#line hidden -using System.Collections.Generic; -#line default + public Task TestDoNotAddIntoHiddenRegion() + => TestMissingInRegularAndScriptAsync( + """ + #line hidden + using System.Collections.Generic; + #line default -class Program -{ - void Main() - { - [|DateTime|] d; - } -}"); - } + class Program + { + void Main() + { + [|DateTime|] d; + } + } + """); [Theory, CombinatorialData] - public async Task TestAddToVisibleRegion(TestHost testHost) - { - await TestAsync( -@"#line default -using System.Collections.Generic; + public Task TestAddToVisibleRegion(TestHost testHost) + => TestAsync( + """ + #line default + using System.Collections.Generic; -#line hidden -class Program -{ - void Main() - { -#line default - [|DateTime|] d; -#line hidden - } -} -#line default", -@"#line default -using System; -using System.Collections.Generic; + #line hidden + class Program + { + void Main() + { + #line default + [|DateTime|] d; + #line hidden + } + } + #line default + """, + """ + #line default + using System; + using System.Collections.Generic; -#line hidden -class Program -{ - void Main() - { -#line default - DateTime d; -#line hidden - } -} -#line default", testHost); - } + #line hidden + class Program + { + void Main() + { + #line default + DateTime d; + #line hidden + } + } + #line default + """, testHost); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545248")] - public async Task TestVenusGeneration1() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void Goo() - { -#line 1 ""Default.aspx"" - using (new [|StreamReader|]()) - { -#line default -#line hidden - } - }"); - } + public Task TestVenusGeneration1() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void Goo() + { + #line 1 "Default.aspx" + using (new [|StreamReader|]()) + { + #line default + #line hidden + } + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")] - public async Task TestAttribute_ActionCount() - { - var input = @"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] "; - await TestActionCountAsync(input, 2); - } + public Task TestAttribute_ActionCount() + => TestActionCountAsync(@"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ", 2); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")] - public async Task TestAttribute(TestHost testHost) - { - var input = @"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] "; - - await TestAsync( -input, -@"using System.Runtime.InteropServices; + public Task TestAttribute(TestHost testHost) + => TestAsync( + @"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ]", + """ + using System.Runtime.InteropServices; -[assembly : Guid ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ", testHost); - } + [assembly : Guid ( "9ed54f84-a89d-4fcd-a854-44251e925f09" ) ] + """, testHost); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546833")] - public async Task TestNotOnOverloadResolutionError() - { - await TestMissingInRegularAndScriptAsync( -@"namespace ConsoleApplication1 -{ - class Program - { - void Main() - { - var test = new [|Test|](""""); - } - } + public Task TestNotOnOverloadResolutionError() + => TestMissingInRegularAndScriptAsync( + """ + namespace ConsoleApplication1 + { + class Program + { + void Main() + { + var test = new [|Test|](""); + } + } - class Test - { - } -}"); - } + class Test + { + } + } + """); [Theory, CombinatorialData] [WorkItem(17020, "DevDiv_Projects/Roslyn")] - public async Task TestAddUsingForGenericArgument(TestHost testHost) - { - await TestAsync( -@"namespace ConsoleApplication10 -{ - class Program - { - static void Main(string[] args) - { - var inArgument = new InArgument<[|IEnumerable|]>(new int[] { 1, 2, 3 }); - } - } + public Task TestAddUsingForGenericArgument(TestHost testHost) + => TestAsync( + """ + namespace ConsoleApplication10 + { + class Program + { + static void Main(string[] args) + { + var inArgument = new InArgument<[|IEnumerable|]>(new int[] { 1, 2, 3 }); + } + } - public class InArgument - { - public InArgument(T constValue) - { - } - } -}", -@"using System.Collections.Generic; + public class InArgument + { + public InArgument(T constValue) + { + } + } + } + """, + """ + using System.Collections.Generic; -namespace ConsoleApplication10 -{ - class Program - { - static void Main(string[] args) - { - var inArgument = new InArgument>(new int[] { 1, 2, 3 }); - } - } + namespace ConsoleApplication10 + { + class Program + { + static void Main(string[] args) + { + var inArgument = new InArgument>(new int[] { 1, 2, 3 }); + } + } - public class InArgument - { - public InArgument(T constValue) - { - } - } -}", testHost); - } + public class InArgument + { + public InArgument(T constValue) + { + } + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775448")] - public async Task ShouldTriggerOnCS0308(TestHost testHost) - { - // CS0308: The non-generic type 'A' cannot be used with type arguments - await TestAsync( -@"using System.Collections; + public Task ShouldTriggerOnCS0308(TestHost testHost) + => TestAsync( + """ + using System.Collections; -class Test -{ - static void Main(string[] args) - { - [|IEnumerable|] f; - } -}", -@"using System.Collections; -using System.Collections.Generic; + class Test + { + static void Main(string[] args) + { + [|IEnumerable|] f; + } + } + """, + """ + using System.Collections; + using System.Collections.Generic; -class Test -{ - static void Main(string[] args) - { - IEnumerable f; - } -}", testHost); - } + class Test + { + static void Main(string[] args) + { + IEnumerable f; + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/838253")] - public async Task TestConflictedInaccessibleType(TestHost testHost) - { - await TestAsync( -@"using System.Diagnostics; + public Task TestConflictedInaccessibleType(TestHost testHost) + => TestAsync( + """ + using System.Diagnostics; -namespace N -{ - public class Log - { - } -} + namespace N + { + public class Log + { + } + } -class C -{ - static void Main(string[] args) - { - [|Log|] } -}", -@"using System.Diagnostics; -using N; + class C + { + static void Main(string[] args) + { + [|Log|] } + } + """, + """ + using System.Diagnostics; + using N; -namespace N -{ - public class Log - { - } -} + namespace N + { + public class Log + { + } + } -class C -{ - static void Main(string[] args) - { - Log } -}", + class C + { + static void Main(string[] args) + { + Log } + } + """, testHost); - } [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858085")] - public async Task TestConflictedAttributeName(TestHost testHost) - { - await TestAsync( -@"[[|Description|]] -class Description -{ -}", -@"using System.ComponentModel; + public Task TestConflictedAttributeName(TestHost testHost) + => TestAsync( + """ + [[|Description|]] + class Description + { + } + """, + """ + using System.ComponentModel; -[Description] -class Description -{ -}", testHost); - } + [Description] + class Description + { + } + """, testHost); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/872908")] - public async Task TestConflictedGenericName(TestHost testHost) - { - await TestAsync( -@"using Task = System.AccessViolationException; + public Task TestConflictedGenericName(TestHost testHost) + => TestAsync( + """ + using Task = System.AccessViolationException; -class X -{ - [|Task x;|] -}", -@"using System.Threading.Tasks; -using Task = System.AccessViolationException; + class X + { + [|Task x;|] + } + """, + """ + using System.Threading.Tasks; + using Task = System.AccessViolationException; -class X -{ - Task x; -}", testHost); - } + class X + { + Task x; + } + """, testHost); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913300")] - public async Task TestNoDuplicateReport_ActionCount() - { - await TestActionCountInAllFixesAsync( -@"class C -{ - void M(P p) - { - [|Console|] - } + public Task TestNoDuplicateReport_ActionCount() + => TestActionCountInAllFixesAsync( + """ + class C + { + void M(P p) + { + [|Console|] + } - static void Main(string[] args) - { - } -}", count: 1); - } + static void Main(string[] args) + { + } + } + """, count: 1); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913300")] - public async Task TestNoDuplicateReport(TestHost testHost) - { - await TestAsync( -@"class C -{ - void M(P p) - { - [|Console|] } + public Task TestNoDuplicateReport(TestHost testHost) + => TestAsync( + """ + class C + { + void M(P p) + { + [|Console|] } - static void Main(string[] args) - { - } -}", -@"using System; + static void Main(string[] args) + { + } + } + """, + """ + using System; -class C -{ - void M(P p) - { - Console } + class C + { + void M(P p) + { + Console } - static void Main(string[] args) - { - } -}", testHost); - } + static void Main(string[] args) + { + } + } + """, testHost); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/938296")] - public async Task TestNullParentInNode() - { - await TestMissingInRegularAndScriptAsync( -@"using System.Collections.Generic; + public Task TestNullParentInNode() + => TestMissingInRegularAndScriptAsync( + """ + using System.Collections.Generic; -class MultiDictionary : Dictionary> -{ - void M() - { - new HashSet([|Comparer|]); - } -}"); - } + class MultiDictionary : Dictionary> + { + void M() + { + new HashSet([|Comparer|]); + } + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968303")] - public async Task TestMalformedUsingSection() - { - await TestMissingInRegularAndScriptAsync( -@"[ class Class -{ - [|List<|] }"); - } + public Task TestMalformedUsingSection() + => TestMissingInRegularAndScriptAsync( + """ + [ class Class + { + [|List<|] } + """); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")] public async Task TestAddUsingsWithExternAlias(TestHost testHost) { - const string InitialWorkspace = @" - - - -namespace ProjectLib -{ - public class Project - { - } -} - - - - lib - -namespace ExternAliases -{ - class Program - { - static void Main(string[] args) - { - Project p = new [|Project()|]; - } - } -} - - -"; + const string InitialWorkspace = """ + + + namespace ProjectLib + { + public class Project + { + } + } + + + lib + namespace ExternAliases + { + class Program + { + static void Main(string[] args) + { + Project p = new [|Project()|]; + } + } + } + + + """; - const string ExpectedDocumentText = @"extern alias P; + const string ExpectedDocumentText = """ + extern alias P; -using P::ProjectLib; + using P::ProjectLib; -namespace ExternAliases -{ - class Program - { - static void Main(string[] args) - { - Project p = new Project(); - } - } -} -"; + namespace ExternAliases + { + class Program + { + static void Main(string[] args) + { + Project p = new Project(); + } + } + } + """; await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost); } @@ -2452,62 +2567,59 @@ static void Main(string[] args) [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")] public async Task TestAddUsingsWithPreExistingExternAlias(TestHost testHost) { - const string InitialWorkspace = @" - - - -namespace ProjectLib -{ - public class Project - { - } -} + const string InitialWorkspace = """ + + + namespace ProjectLib + { + public class Project + { + } + } -namespace AnotherNS -{ - public class AnotherClass - { - } -} - - - - lib - -extern alias P; -using P::ProjectLib; -namespace ExternAliases -{ - class Program - { - static void Main(string[] args) - { - Project p = new Project(); - var x = new [|AnotherClass()|]; - } - } -} - - -"; + namespace AnotherNS + { + public class AnotherClass + { + } + } + + + lib + extern alias P; + using P::ProjectLib; + namespace ExternAliases + { + class Program + { + static void Main(string[] args) + { + Project p = new Project(); + var x = new [|AnotherClass()|]; + } + } + } + + + """; - const string ExpectedDocumentText = @" -extern alias P; + const string ExpectedDocumentText = """ + extern alias P; -using P::AnotherNS; -using P::ProjectLib; -namespace ExternAliases -{ - class Program - { - static void Main(string[] args) - { - Project p = new Project(); - var x = new [|AnotherClass()|]; - } - } -} -"; + using P::AnotherNS; + using P::ProjectLib; + namespace ExternAliases + { + class Program + { + static void Main(string[] args) + { + Project p = new Project(); + var x = new [|AnotherClass()|]; + } + } + } + """; await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost); } @@ -2515,60 +2627,57 @@ static void Main(string[] args) [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")] public async Task TestAddUsingsWithPreExistingExternAlias_FileScopedNamespace(TestHost testHost) { - const string InitialWorkspace = @" - - - -namespace ProjectLib; -{ - public class Project - { - } -} + const string InitialWorkspace = """ + + + namespace ProjectLib; + { + public class Project + { + } + } -namespace AnotherNS -{ - public class AnotherClass - { - } -} - - - - lib - -extern alias P; -using P::ProjectLib; -namespace ExternAliases; - -class Program -{ - static void Main(string[] args) - { - Project p = new Project(); - var x = new [|AnotherClass()|]; - } -} - - -"; + namespace AnotherNS + { + public class AnotherClass + { + } + } + + + lib + extern alias P; + using P::ProjectLib; + namespace ExternAliases; - const string ExpectedDocumentText = @" -extern alias P; + class Program + { + static void Main(string[] args) + { + Project p = new Project(); + var x = new [|AnotherClass()|]; + } + } + + + """; -using P::AnotherNS; -using P::ProjectLib; -namespace ExternAliases; + const string ExpectedDocumentText = """ + extern alias P; -class Program -{ - static void Main(string[] args) - { - Project p = new Project(); - var x = new [|AnotherClass()|]; - } -} -"; + using P::AnotherNS; + using P::ProjectLib; + namespace ExternAliases; + + class Program + { + static void Main(string[] args) + { + Project p = new Project(); + var x = new [|AnotherClass()|]; + } + } + """; await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost); } @@ -2576,50 +2685,48 @@ static void Main(string[] args) [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")] public async Task TestAddUsingsNoExtern(TestHost testHost) { - const string InitialWorkspace = @" - - - -namespace AnotherNS -{ - public class AnotherClass - { - } -} - - - - lib - -using P::AnotherNS; -namespace ExternAliases -{ - class Program - { - static void Main(string[] args) - { - var x = new [|AnotherClass()|]; - } - } -} - - -"; + const string InitialWorkspace = """ + + + namespace AnotherNS + { + public class AnotherClass + { + } + } + + + lib + using P::AnotherNS; + namespace ExternAliases + { + class Program + { + static void Main(string[] args) + { + var x = new [|AnotherClass()|]; + } + } + } + + + """; - const string ExpectedDocumentText = @"extern alias P; + const string ExpectedDocumentText = """ + extern alias P; -using P::AnotherNS; -namespace ExternAliases -{ - class Program - { - static void Main(string[] args) - { - var x = new AnotherClass(); - } - } -} -"; + using P::AnotherNS; + namespace ExternAliases + { + class Program + { + static void Main(string[] args) + { + var x = new AnotherClass(); + } + } + } + """; await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost); } @@ -2627,2171 +2734,2173 @@ static void Main(string[] args) [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")] public async Task TestAddUsingsNoExtern_FileScopedNamespace(TestHost testHost) { - const string InitialWorkspace = @" - - - -namespace AnotherNS; + const string InitialWorkspace = """ + + + namespace AnotherNS; -public class AnotherClass -{ -} - - - - lib - -using P::AnotherNS; -namespace ExternAliases; - -class Program -{ - static void Main(string[] args) - { - var x = new [|AnotherClass()|]; - } -} - - -"; + public class AnotherClass + { + } + + + lib + using P::AnotherNS; + namespace ExternAliases; - const string ExpectedDocumentText = @"extern alias P; + class Program + { + static void Main(string[] args) + { + var x = new [|AnotherClass()|]; + } + } + + + """; -using P::AnotherNS; -namespace ExternAliases; + const string ExpectedDocumentText = """ + extern alias P; -class Program -{ - static void Main(string[] args) - { - var x = new AnotherClass(); - } -} -"; + using P::AnotherNS; + namespace ExternAliases; + + class Program + { + static void Main(string[] args) + { + var x = new AnotherClass(); + } + } + """; await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost); } [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")] - public async Task TestAddUsingsNoExternFilterGlobalAlias(TestHost testHost) - { - await TestAsync( -@"class Program -{ - static void Main(string[] args) - { - [|INotifyPropertyChanged.PropertyChanged|] - } -}", -@"using System.ComponentModel; + public Task TestAddUsingsNoExternFilterGlobalAlias(TestHost testHost) + => TestAsync( + """ + class Program + { + static void Main(string[] args) + { + [|INotifyPropertyChanged.PropertyChanged|] + } + } + """, + """ + using System.ComponentModel; -class Program -{ - static void Main(string[] args) - { - INotifyPropertyChanged.PropertyChanged - } -}", testHost); - } + class Program + { + static void Main(string[] args) + { + INotifyPropertyChanged.PropertyChanged + } + } + """, testHost); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")] public async Task TestAddUsingForCref() { - var initialText = -@"/// -/// This is just like , but this one is mine. -/// -interface MyNotifyPropertyChanged { }"; - - var expectedText = -@"using System.ComponentModel; - -/// -/// This is just like , but this one is mine. -/// -interface MyNotifyPropertyChanged { }"; - var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose); - await TestAsync(initialText, expectedText, parseOptions: options); + await TestAsync(""" + /// + /// This is just like , but this one is mine. + /// + interface MyNotifyPropertyChanged { } + """, """ + using System.ComponentModel; + + /// + /// This is just like , but this one is mine. + /// + interface MyNotifyPropertyChanged { } + """, parseOptions: options); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")] public async Task TestAddUsingForCref2() { - var initialText = -@"/// -/// This is just like , but this one is mine. -/// -interface MyNotifyPropertyChanged { }"; - - var expectedText = -@"using System.ComponentModel; - -/// -/// This is just like , but this one is mine. -/// -interface MyNotifyPropertyChanged { }"; - var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose); - await TestAsync(initialText, expectedText, parseOptions: options); + await TestAsync(""" + /// + /// This is just like , but this one is mine. + /// + interface MyNotifyPropertyChanged { } + """, """ + using System.ComponentModel; + + /// + /// This is just like , but this one is mine. + /// + interface MyNotifyPropertyChanged { } + """, parseOptions: options); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")] public async Task TestAddUsingForCref3() { - var initialText = -@"namespace N1 -{ - public class D { } -} - -public class MyClass -{ - public static explicit operator N1.D (MyClass f) - { - return default(N1.D); - } -} - -/// -public class MyClass2 -{ -}"; + var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose); - var expectedText = -@"using N1; + await TestAsync(""" + namespace N1 + { + public class D { } + } -namespace N1 -{ - public class D { } -} + public class MyClass + { + public static explicit operator N1.D (MyClass f) + { + return default(N1.D); + } + } -public class MyClass -{ - public static explicit operator N1.D (MyClass f) - { - return default(N1.D); - } -} + /// + public class MyClass2 + { + } + """, """ + using N1; -/// -public class MyClass2 -{ -}"; + namespace N1 + { + public class D { } + } - var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose); + public class MyClass + { + public static explicit operator N1.D (MyClass f) + { + return default(N1.D); + } + } - await TestAsync(initialText, expectedText, parseOptions: options); + /// + public class MyClass2 + { + } + """, parseOptions: options); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")] public async Task TestAddUsingForCref4() { - var initialText = -@"namespace N1 -{ - public class D { } -} - -/// -public class MyClass -{ - public void Test(N1.D i) - { - } -}"; - - var expectedText = -@"using N1; + var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose); -namespace N1 -{ - public class D { } -} + await TestAsync(""" + namespace N1 + { + public class D { } + } -/// -public class MyClass -{ - public void Test(N1.D i) - { - } -}"; + /// + public class MyClass + { + public void Test(N1.D i) + { + } + } + """, """ + using N1; - var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose); + namespace N1 + { + public class D { } + } - await TestAsync(initialText, expectedText, parseOptions: options); + /// + public class MyClass + { + public void Test(N1.D i) + { + } + } + """, parseOptions: options); } [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")] - public async Task TestAddStaticType(TestHost testHost) - { - var initialText = -@"using System; - -public static class Outer -{ - [AttributeUsage(AttributeTargets.All)] - public class MyAttribute : Attribute - { - - } -} + public Task TestAddStaticType(TestHost testHost) + => TestAsync(""" + using System; -[[|My|]] -class Test -{}"; + public static class Outer + { + [AttributeUsage(AttributeTargets.All)] + public class MyAttribute : Attribute + { - var expectedText = -@"using System; -using static Outer; + } + } -public static class Outer -{ - [AttributeUsage(AttributeTargets.All)] - public class MyAttribute : Attribute - { + [[|My|]] + class Test + {} + """, """ + using System; + using static Outer; - } -} + public static class Outer + { + [AttributeUsage(AttributeTargets.All)] + public class MyAttribute : Attribute + { -[My] -class Test -{}"; + } + } - await TestAsync(initialText, expectedText, testHost); - } + [My] + class Test + {} + """, testHost); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")] - public async Task TestAddStaticType2(TestHost testHost) - { - var initialText = -@"using System; - -public static class Outer -{ - public static class Inner - { - [AttributeUsage(AttributeTargets.All)] - public class MyAttribute : Attribute - { - } - } -} - -[[|My|]] -class Test -{}"; + public Task TestAddStaticType2(TestHost testHost) + => TestAsync(""" + using System; - var expectedText = -@"using System; -using static Outer.Inner; + public static class Outer + { + public static class Inner + { + [AttributeUsage(AttributeTargets.All)] + public class MyAttribute : Attribute + { + } + } + } -public static class Outer -{ - public static class Inner - { - [AttributeUsage(AttributeTargets.All)] - public class MyAttribute : Attribute - { - } - } -} + [[|My|]] + class Test + {} + """, """ + using System; + using static Outer.Inner; -[My] -class Test -{}"; + public static class Outer + { + public static class Inner + { + [AttributeUsage(AttributeTargets.All)] + public class MyAttribute : Attribute + { + } + } + } - await TestAsync(initialText, expectedText, testHost); - } + [My] + class Test + {} + """, testHost); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")] - public async Task TestAddStaticType3(TestHost testHost) - { - await TestAsync( -@"using System; + public Task TestAddStaticType3(TestHost testHost) + => TestAsync( + """ + using System; -public static class Outer -{ - public class Inner - { - [AttributeUsage(AttributeTargets.All)] - public class MyAttribute : Attribute - { - } - } -} + public static class Outer + { + public class Inner + { + [AttributeUsage(AttributeTargets.All)] + public class MyAttribute : Attribute + { + } + } + } -[[|My|]] -class Test -{ -}", -@"using System; -using static Outer.Inner; + [[|My|]] + class Test + { + } + """, + """ + using System; + using static Outer.Inner; -public static class Outer -{ - public class Inner - { - [AttributeUsage(AttributeTargets.All)] - public class MyAttribute : Attribute - { - } - } -} + public static class Outer + { + public class Inner + { + [AttributeUsage(AttributeTargets.All)] + public class MyAttribute : Attribute + { + } + } + } -[My] -class Test -{ -}", testHost); - } + [My] + class Test + { + } + """, testHost); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")] - public async Task TestAddStaticType4(TestHost testHost) - { - var initialText = -@"using System; -using Outer; - -public static class Outer -{ - public static class Inner - { - [AttributeUsage(AttributeTargets.All)] - public class MyAttribute : Attribute - { - } - } -} - -[[|My|]] -class Test -{}"; + public Task TestAddStaticType4(TestHost testHost) + => TestAsync(""" + using System; + using Outer; - var expectedText = -@"using System; -using Outer; -using static Outer.Inner; + public static class Outer + { + public static class Inner + { + [AttributeUsage(AttributeTargets.All)] + public class MyAttribute : Attribute + { + } + } + } -public static class Outer -{ - public static class Inner - { - [AttributeUsage(AttributeTargets.All)] - public class MyAttribute : Attribute - { - } - } -} + [[|My|]] + class Test + {} + """, """ + using System; + using Outer; + using static Outer.Inner; -[My] -class Test -{}"; + public static class Outer + { + public static class Inner + { + [AttributeUsage(AttributeTargets.All)] + public class MyAttribute : Attribute + { + } + } + } - await TestAsync(initialText, expectedText, testHost); - } + [My] + class Test + {} + """, testHost); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")] - public async Task TestAddInsideUsingDirective1(TestHost testHost) - { - await TestAsync( -@"namespace ns -{ - using B = [|Byte|]; -}", -@"using System; + public Task TestAddInsideUsingDirective1(TestHost testHost) + => TestAsync( + """ + namespace ns + { + using B = [|Byte|]; + } + """, + """ + using System; -namespace ns -{ - using B = Byte; -}", testHost); - } + namespace ns + { + using B = Byte; + } + """, testHost); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")] - public async Task TestAddInsideUsingDirective2(TestHost testHost) - { - await TestAsync( -@"using System.Collections; + public Task TestAddInsideUsingDirective2(TestHost testHost) + => TestAsync( + """ + using System.Collections; -namespace ns -{ - using B = [|Byte|]; -}", -@"using System; -using System.Collections; + namespace ns + { + using B = [|Byte|]; + } + """, + """ + using System; + using System.Collections; -namespace ns -{ - using B = Byte; -}", testHost); - } + namespace ns + { + using B = Byte; + } + """, testHost); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")] - public async Task TestAddInsideUsingDirective3(TestHost testHost) - { - await TestAsync( -@"namespace ns2 -{ - namespace ns3 - { - namespace ns - { - using B = [|Byte|]; - - namespace ns4 + public Task TestAddInsideUsingDirective3(TestHost testHost) + => TestAsync( + """ + namespace ns2 { + namespace ns3 + { + namespace ns + { + using B = [|Byte|]; + + namespace ns4 + { + } + } + } } - } - } -}", -@"using System; - -namespace ns2 -{ - namespace ns3 - { - namespace ns - { - using B = Byte; + """, + """ + using System; - namespace ns4 + namespace ns2 { + namespace ns3 + { + namespace ns + { + using B = Byte; + + namespace ns4 + { + } + } + } } - } - } -}", testHost); - } + """, testHost); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")] - public async Task TestAddInsideUsingDirective4(TestHost testHost) - { - await TestAsync( -@"namespace ns2 -{ - using System.Collections; + public Task TestAddInsideUsingDirective4(TestHost testHost) + => TestAsync( + """ + namespace ns2 + { + using System.Collections; - namespace ns3 - { - namespace ns - { - using System.IO; - using B = [|Byte|]; - } - } -}", -@"namespace ns2 -{ - using System; - using System.Collections; + namespace ns3 + { + namespace ns + { + using System.IO; + using B = [|Byte|]; + } + } + } + """, + """ + namespace ns2 + { + using System; + using System.Collections; - namespace ns3 - { - namespace ns - { - using System.IO; - using B = Byte; - } - } -}", testHost); - } + namespace ns3 + { + namespace ns + { + using System.IO; + using B = Byte; + } + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")] - public async Task TestAddInsideUsingDirective5(TestHost testHost) - { - await TestAsync( -@"using System.IO; + public Task TestAddInsideUsingDirective5(TestHost testHost) + => TestAsync( + """ + using System.IO; -namespace ns2 -{ - using System.Diagnostics; + namespace ns2 + { + using System.Diagnostics; - namespace ns3 - { - using System.Collections; + namespace ns3 + { + using System.Collections; - namespace ns - { - using B = [|Byte|]; - } - } -}", -@"using System.IO; + namespace ns + { + using B = [|Byte|]; + } + } + } + """, + """ + using System.IO; -namespace ns2 -{ - using System.Diagnostics; + namespace ns2 + { + using System.Diagnostics; - namespace ns3 - { - using System; - using System.Collections; + namespace ns3 + { + using System; + using System.Collections; - namespace ns - { - using B = Byte; - } - } -}", testHost); - } + namespace ns + { + using B = Byte; + } + } + } + """, testHost); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")] - public async Task TestAddInsideUsingDirective6() - { - await TestMissingInRegularAndScriptAsync( + public Task TestAddInsideUsingDirective6() + => TestMissingInRegularAndScriptAsync( @"using B = [|Byte|];"); - } [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestAddConditionalAccessExpression(TestHost testHost) - { - var initialText = -@" - - -public class C -{ - void Main(C a) - { - C x = a?[|.B()|]; - } -} - - -namespace Extensions -{ - public static class E - { - public static C B(this C c) { return c; } - } -} - - - "; - - var expectedText = -@" -using Extensions; + public Task TestAddConditionalAccessExpression(TestHost testHost) + => TestAsync(""" + + + public class C + { + void Main(C a) + { + C x = a?[|.B()|]; + } + } + namespace Extensions + { + public static class E + { + public static C B(this C c) { return c; } + } + } + + + """, """ + using Extensions; -public class C -{ - void Main(C a) - { - C x = a?.B(); - } -} - "; - await TestAsync(initialText, expectedText, testHost); - } + public class C + { + void Main(C a) + { + C x = a?.B(); + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestAddConditionalAccessExpression2(TestHost testHost) - { - var initialText = -@" - - -public class C -{ - public E B { get; private set; } - - void Main(C a) - { - int? x = a?.B.[|C()|]; - } + public Task TestAddConditionalAccessExpression2(TestHost testHost) + => TestAsync(""" + + + public class C + { + public E B { get; private set; } - public class E - { - } -} - - -namespace Extensions -{ - public static class D - { - public static C.E C(this C.E c) { return c; } - } -} - - - "; + void Main(C a) + { + int? x = a?.B.[|C()|]; + } - var expectedText = -@" -using Extensions; + public class E + { + } + } + namespace Extensions + { + public static class D + { + public static C.E C(this C.E c) { return c; } + } + } + + + """, """ + using Extensions; -public class C -{ - public E B { get; private set; } + public class C + { + public E B { get; private set; } - void Main(C a) - { - int? x = a?.B.C(); - } + void Main(C a) + { + int? x = a?.B.C(); + } - public class E - { - } -} - "; - await TestAsync(initialText, expectedText, testHost); - } + public class E + { + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1089138")] - public async Task TestAmbiguousUsingName(TestHost testHost) - { - await TestAsync( -@"namespace ClassLibrary1 -{ - using System; + public Task TestAmbiguousUsingName(TestHost testHost) + => TestAsync( + """ + namespace ClassLibrary1 + { + using System; - public class SomeTypeUser - { - [|SomeType|] field; - } -} + public class SomeTypeUser + { + [|SomeType|] field; + } + } -namespace SubNamespaceName -{ - using System; + namespace SubNamespaceName + { + using System; - class SomeType - { - } -} + class SomeType + { + } + } -namespace ClassLibrary1.SubNamespaceName -{ - using System; + namespace ClassLibrary1.SubNamespaceName + { + using System; - class SomeOtherFile - { - } -}", -@"namespace ClassLibrary1 -{ - using System; - using global::SubNamespaceName; + class SomeOtherFile + { + } + } + """, + """ + namespace ClassLibrary1 + { + using System; + using global::SubNamespaceName; - public class SomeTypeUser - { - SomeType field; - } -} + public class SomeTypeUser + { + SomeType field; + } + } -namespace SubNamespaceName -{ - using System; + namespace SubNamespaceName + { + using System; - class SomeType - { - } -} + class SomeType + { + } + } -namespace ClassLibrary1.SubNamespaceName -{ - using System; + namespace ClassLibrary1.SubNamespaceName + { + using System; - class SomeOtherFile - { - } -}", testHost); - } + class SomeOtherFile + { + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestAddUsingInDirective(TestHost testHost) - { - await TestAsync( -@"#define DEBUG -#if DEBUG -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using System.Text; -#endif -class Program -{ - static void Main(string[] args) - { - var a = [|File|].OpenRead(""""); - } -}", -@"#define DEBUG -#if DEBUG -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using System.Text; -using System.IO; -#endif -class Program -{ - static void Main(string[] args) - { - var a = File.OpenRead(""""); - } -}", testHost); - } + public Task TestAddUsingInDirective(TestHost testHost) + => TestAsync( + """ + #define DEBUG + #if DEBUG + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; + using System.Text; + #endif + class Program + { + static void Main(string[] args) + { + var a = [|File|].OpenRead(""); + } + } + """, + """ + #define DEBUG + #if DEBUG + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; + using System.Text; + using System.IO; + #endif + class Program + { + static void Main(string[] args) + { + var a = File.OpenRead(""); + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestAddUsingInDirective2(TestHost testHost) - { - await TestAsync( -@"#define DEBUG -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -#if DEBUG -using System.Text; -#endif -class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ", -@"#define DEBUG -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using System.IO; + public Task TestAddUsingInDirective2(TestHost testHost) + => TestAsync( + """ + #define DEBUG + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; + #if DEBUG + using System.Text; + #endif + class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( "" ) ; } } + """, + """ + #define DEBUG + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; + using System.IO; -#if DEBUG -using System.Text; -#endif -class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ", testHost); - } + #if DEBUG + using System.Text; + #endif + class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( "" ) ; } } + """, testHost); [Theory, CombinatorialData] - public async Task TestAddUsingInDirective3(TestHost testHost) - { - await TestAsync( -@"#define DEBUG -using System; -using System.Collections.Generic; -#if DEBUG -using System.Text; -#endif -using System.Linq; -using System.Threading.Tasks; -class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ", -@"#define DEBUG -using System; -using System.Collections.Generic; -#if DEBUG -using System.Text; -#endif -using System.Linq; -using System.Threading.Tasks; -using System.IO; -class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ", testHost); - } + public Task TestAddUsingInDirective3(TestHost testHost) + => TestAsync( + """ + #define DEBUG + using System; + using System.Collections.Generic; + #if DEBUG + using System.Text; + #endif + using System.Linq; + using System.Threading.Tasks; + class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( "" ) ; } } + """, + """ + #define DEBUG + using System; + using System.Collections.Generic; + #if DEBUG + using System.Text; + #endif + using System.Linq; + using System.Threading.Tasks; + using System.IO; + class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( "" ) ; } } + """, testHost); [Theory, CombinatorialData] - public async Task TestAddUsingInDirective4(TestHost testHost) - { - await TestAsync( -@"#define DEBUG -#if DEBUG -using System; -#endif -using System.Collections.Generic; -using System.Text; -using System.Linq; -using System.Threading.Tasks; -class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ", -@"#define DEBUG -#if DEBUG -using System; -#endif -using System.Collections.Generic; -using System.Text; -using System.Linq; -using System.Threading.Tasks; -using System.IO; -class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ", testHost); - } + public Task TestAddUsingInDirective4(TestHost testHost) + => TestAsync( + """ + #define DEBUG + #if DEBUG + using System; + #endif + using System.Collections.Generic; + using System.Text; + using System.Linq; + using System.Threading.Tasks; + class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( "" ) ; } } + """, + """ + #define DEBUG + #if DEBUG + using System; + #endif + using System.Collections.Generic; + using System.Text; + using System.Linq; + using System.Threading.Tasks; + using System.IO; + class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( "" ) ; } } + """, testHost); [Fact] public async Task TestInaccessibleExtensionMethod() { - const string initial = @" -namespace N1 -{ - public static class C - { - private static bool ExtMethod1(this string arg1) - { - return true; - } - } -} + const string initial = """ + namespace N1 + { + public static class C + { + private static bool ExtMethod1(this string arg1) + { + return true; + } + } + } -namespace N2 -{ - class Program - { - static void Main(string[] args) - { - var x = ""str1"".[|ExtMethod1()|]; - } - } -}"; + namespace N2 + { + class Program + { + static void Main(string[] args) + { + var x = "str1".[|ExtMethod1()|]; + } + } + } + """; await TestMissingInRegularAndScriptAsync(initial); } [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116011")] - public async Task TestAddUsingForProperty(TestHost testHost) - { - await TestAsync( -@"using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; + public Task TestAddUsingForProperty(TestHost testHost) + => TestAsync( + """ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; -class Program -{ - public BindingFlags BindingFlags - { - get - { - return BindingFlags.[|Instance|]; - } - } -}", -@"using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Threading.Tasks; + class Program + { + public BindingFlags BindingFlags + { + get + { + return BindingFlags.[|Instance|]; + } + } + } + """, + """ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using System.Threading.Tasks; -class Program -{ - public BindingFlags BindingFlags - { - get - { - return BindingFlags.Instance; - } - } -}", testHost); - } + class Program + { + public BindingFlags BindingFlags + { + get + { + return BindingFlags.Instance; + } + } + } + """, testHost); - [Theory, CombinatorialData] - [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116011")] - public async Task TestAddUsingForField(TestHost testHost) - { - await TestAsync( -@"using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; + [Theory, CombinatorialData] + [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116011")] + public Task TestAddUsingForField(TestHost testHost) + => TestAsync( + """ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; -class Program -{ - public B B - { - get - { - return B.[|Instance|]; - } - } -} + class Program + { + public B B + { + get + { + return B.[|Instance|]; + } + } + } -namespace A -{ - public class B - { - public static readonly B Instance; - } -}", -@"using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using A; + namespace A + { + public class B + { + public static readonly B Instance; + } + } + """, + """ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; + using A; -class Program -{ - public B B - { - get - { - return B.Instance; - } - } -} + class Program + { + public B B + { + get + { + return B.Instance; + } + } + } -namespace A -{ - public class B - { - public static readonly B Instance; - } -}", testHost); - } + namespace A + { + public class B + { + public static readonly B Instance; + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/1893")] - public async Task TestNameSimplification(TestHost testHost) - { - // Generated using directive must be simplified from "using A.B;" to "using B;" below. - await TestAsync( -@"namespace A.B -{ - class T1 - { - } -} + public Task TestNameSimplification(TestHost testHost) + => TestAsync( + """ + namespace A.B + { + class T1 + { + } + } -namespace A.C -{ - using System; + namespace A.C + { + using System; - class T2 - { - void Test() - { - Console.WriteLine(); - [|T1|] t1; - } - } -}", -@"namespace A.B -{ - class T1 - { - } -} + class T2 + { + void Test() + { + Console.WriteLine(); + [|T1|] t1; + } + } + } + """, + """ + namespace A.B + { + class T1 + { + } + } -namespace A.C -{ - using System; - using A.B; + namespace A.C + { + using System; + using A.B; - class T2 - { - void Test() - { - Console.WriteLine(); - T1 t1; - } - } -}", testHost); - } + class T2 + { + void Test() + { + Console.WriteLine(); + T1 t1; + } + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/935")] - public async Task TestAddUsingWithOtherExtensionsInScope(TestHost testHost) - { - await TestAsync( -@"using System.Linq; -using System.Collections; -using X; + public Task TestAddUsingWithOtherExtensionsInScope(TestHost testHost) + => TestAsync( + """ + using System.Linq; + using System.Collections; + using X; -namespace X -{ - public static class Ext - { - public static void ExtMethod(this int a) - { - } - } -} + namespace X + { + public static class Ext + { + public static void ExtMethod(this int a) + { + } + } + } -namespace Y -{ - public static class Ext - { - public static void ExtMethod(this int a, int v) - { - } - } -} + namespace Y + { + public static class Ext + { + public static void ExtMethod(this int a, int v) + { + } + } + } -public class B -{ - static void Main() - { - var b = 0; - b.[|ExtMethod|](0); - } -}", -@"using System.Linq; -using System.Collections; -using X; -using Y; + public class B + { + static void Main() + { + var b = 0; + b.[|ExtMethod|](0); + } + } + """, + """ + using System.Linq; + using System.Collections; + using X; + using Y; -namespace X -{ - public static class Ext - { - public static void ExtMethod(this int a) - { - } - } -} + namespace X + { + public static class Ext + { + public static void ExtMethod(this int a) + { + } + } + } -namespace Y -{ - public static class Ext - { - public static void ExtMethod(this int a, int v) - { - } - } -} + namespace Y + { + public static class Ext + { + public static void ExtMethod(this int a, int v) + { + } + } + } -public class B -{ - static void Main() - { - var b = 0; - b.ExtMethod(0); - } -}", testHost); - } + public class B + { + static void Main() + { + var b = 0; + b.ExtMethod(0); + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/935")] - public async Task TestAddUsingWithOtherExtensionsInScope2(TestHost testHost) - { - await TestAsync( -@"using System.Linq; -using System.Collections; -using X; + public Task TestAddUsingWithOtherExtensionsInScope2(TestHost testHost) + => TestAsync( + """ + using System.Linq; + using System.Collections; + using X; -namespace X -{ - public static class Ext - { - public static void ExtMethod(this int? a) - { - } - } -} + namespace X + { + public static class Ext + { + public static void ExtMethod(this int? a) + { + } + } + } -namespace Y -{ - public static class Ext - { - public static void ExtMethod(this int? a, int v) - { - } - } -} + namespace Y + { + public static class Ext + { + public static void ExtMethod(this int? a, int v) + { + } + } + } -public class B -{ - static void Main() - { - var b = new int?(); - b?[|.ExtMethod|](0); - } -}", -@"using System.Linq; -using System.Collections; -using X; -using Y; + public class B + { + static void Main() + { + var b = new int?(); + b?[|.ExtMethod|](0); + } + } + """, + """ + using System.Linq; + using System.Collections; + using X; + using Y; -namespace X -{ - public static class Ext - { - public static void ExtMethod(this int? a) - { - } - } -} + namespace X + { + public static class Ext + { + public static void ExtMethod(this int? a) + { + } + } + } -namespace Y -{ - public static class Ext - { - public static void ExtMethod(this int? a, int v) - { - } - } -} + namespace Y + { + public static class Ext + { + public static void ExtMethod(this int? a, int v) + { + } + } + } -public class B -{ - static void Main() - { - var b = new int?(); - b?.ExtMethod(0); - } -}", testHost); - } + public class B + { + static void Main() + { + var b = new int?(); + b?.ExtMethod(0); + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/562")] - public async Task TestAddUsingWithOtherExtensionsInScope3(TestHost testHost) - { - await TestAsync( -@"using System.Linq; + public Task TestAddUsingWithOtherExtensionsInScope3(TestHost testHost) + => TestAsync( + """ + using System.Linq; -class C -{ - int i = 0.[|All|](); -} + class C + { + int i = 0.[|All|](); + } -namespace X -{ - static class E - { - public static int All(this int o) => 0; - } -}", -@"using System.Linq; -using X; + namespace X + { + static class E + { + public static int All(this int o) => 0; + } + } + """, + """ + using System.Linq; + using X; -class C -{ - int i = 0.All(); -} + class C + { + int i = 0.All(); + } -namespace X -{ - static class E - { - public static int All(this int o) => 0; - } -}", testHost); - } + namespace X + { + static class E + { + public static int All(this int o) => 0; + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/562")] - public async Task TestAddUsingWithOtherExtensionsInScope4(TestHost testHost) - { - await TestAsync( -@"using System.Linq; + public Task TestAddUsingWithOtherExtensionsInScope4(TestHost testHost) + => TestAsync( + """ + using System.Linq; -class C -{ - static void Main(string[] args) - { - var a = new int?(); - int? i = a?[|.All|](); - } -} + class C + { + static void Main(string[] args) + { + var a = new int?(); + int? i = a?[|.All|](); + } + } -namespace X -{ - static class E - { - public static int? All(this int? o) => 0; - } -}", -@"using System.Linq; -using X; + namespace X + { + static class E + { + public static int? All(this int? o) => 0; + } + } + """, + """ + using System.Linq; + using X; -class C -{ - static void Main(string[] args) - { - var a = new int?(); - int? i = a?.All(); - } -} + class C + { + static void Main(string[] args) + { + var a = new int?(); + int? i = a?.All(); + } + } -namespace X -{ - static class E - { - public static int? All(this int? o) => 0; - } -}", testHost); - } + namespace X + { + static class E + { + public static int? All(this int? o) => 0; + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/3080")] - public async Task TestNestedNamespaceSimplified(TestHost testHost) - { - await TestAsync( -@"namespace Microsoft.MyApp -{ - using Win32; + public Task TestNestedNamespaceSimplified(TestHost testHost) + => TestAsync( + """ + namespace Microsoft.MyApp + { + using Win32; - class Program - { - static void Main(string[] args) - { - [|SafeRegistryHandle|] h; - } - } -}", -@"namespace Microsoft.MyApp -{ - using Microsoft.Win32.SafeHandles; - using Win32; + class Program + { + static void Main(string[] args) + { + [|SafeRegistryHandle|] h; + } + } + } + """, + """ + namespace Microsoft.MyApp + { + using Microsoft.Win32.SafeHandles; + using Win32; - class Program - { - static void Main(string[] args) - { - SafeRegistryHandle h; - } - } -}", testHost); - } + class Program + { + static void Main(string[] args) + { + SafeRegistryHandle h; + } + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/3080")] - public async Task TestNestedNamespaceSimplified2(TestHost testHost) - { - await TestAsync( -@"namespace Microsoft.MyApp -{ - using Zin32; + public Task TestNestedNamespaceSimplified2(TestHost testHost) + => TestAsync( + """ + namespace Microsoft.MyApp + { + using Zin32; - class Program - { - static void Main(string[] args) - { - [|SafeRegistryHandle|] h; - } - } -}", -@"namespace Microsoft.MyApp -{ - using Microsoft.Win32.SafeHandles; - using Zin32; + class Program + { + static void Main(string[] args) + { + [|SafeRegistryHandle|] h; + } + } + } + """, + """ + namespace Microsoft.MyApp + { + using Microsoft.Win32.SafeHandles; + using Zin32; - class Program - { - static void Main(string[] args) - { - SafeRegistryHandle h; - } - } -}", testHost); - } + class Program + { + static void Main(string[] args) + { + SafeRegistryHandle h; + } + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/3080")] - public async Task TestNestedNamespaceSimplified3(TestHost testHost) - { - await TestAsync( -@"namespace Microsoft.MyApp -{ - using System; - using Win32; + public Task TestNestedNamespaceSimplified3(TestHost testHost) + => TestAsync( + """ + namespace Microsoft.MyApp + { + using System; + using Win32; - class Program - { - static void Main(string[] args) - { - [|SafeRegistryHandle|] h; - } - } -}", -@"namespace Microsoft.MyApp -{ - using System; - using Microsoft.Win32.SafeHandles; - using Win32; + class Program + { + static void Main(string[] args) + { + [|SafeRegistryHandle|] h; + } + } + } + """, + """ + namespace Microsoft.MyApp + { + using System; + using Microsoft.Win32.SafeHandles; + using Win32; - class Program - { - static void Main(string[] args) - { - SafeRegistryHandle h; - } - } -}", testHost); - } + class Program + { + static void Main(string[] args) + { + SafeRegistryHandle h; + } + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/3080")] - public async Task TestNestedNamespaceSimplified4(TestHost testHost) - { - await TestAsync( -@"namespace Microsoft.MyApp -{ - using System; - using Zin32; + public Task TestNestedNamespaceSimplified4(TestHost testHost) + => TestAsync( + """ + namespace Microsoft.MyApp + { + using System; + using Zin32; - class Program - { - static void Main(string[] args) - { - [|SafeRegistryHandle|] h; - } - } -}", -@"namespace Microsoft.MyApp -{ - using System; - using Microsoft.Win32.SafeHandles; - using Zin32; + class Program + { + static void Main(string[] args) + { + [|SafeRegistryHandle|] h; + } + } + } + """, + """ + namespace Microsoft.MyApp + { + using System; + using Microsoft.Win32.SafeHandles; + using Zin32; - class Program - { - static void Main(string[] args) - { - SafeRegistryHandle h; - } - } -}", testHost); - } + class Program + { + static void Main(string[] args) + { + SafeRegistryHandle h; + } + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/3080")] - public async Task TestNestedNamespaceSimplified5(TestHost testHost) - { - await TestAsync( -@"namespace Microsoft.MyApp -{ -#if true - using Win32; -#else - using System; -#endif - class Program - { - static void Main(string[] args) - { - [|SafeRegistryHandle|] h; - } - } -}", -@"namespace Microsoft.MyApp -{ - using Microsoft.Win32.SafeHandles; -#if true - using Win32; -#else - using System; -#endif - class Program - { - static void Main(string[] args) - { - SafeRegistryHandle h; - } - } -}", testHost); - } + public Task TestNestedNamespaceSimplified5(TestHost testHost) + => TestAsync( + """ + namespace Microsoft.MyApp + { + #if true + using Win32; + #else + using System; + #endif + class Program + { + static void Main(string[] args) + { + [|SafeRegistryHandle|] h; + } + } + } + """, + """ + namespace Microsoft.MyApp + { + using Microsoft.Win32.SafeHandles; + #if true + using Win32; + #else + using System; + #endif + class Program + { + static void Main(string[] args) + { + SafeRegistryHandle h; + } + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/3080")] - public async Task TestNestedNamespaceSimplified6(TestHost testHost) - { - await TestAsync( -@"namespace Microsoft.MyApp -{ - using System; -#if false - using Win32; -#endif - using Win32; + public Task TestNestedNamespaceSimplified6(TestHost testHost) + => TestAsync( + """ + namespace Microsoft.MyApp + { + using System; + #if false + using Win32; + #endif + using Win32; - class Program - { - static void Main(string[] args) - { - [|SafeRegistryHandle|] h; - } - } -}", -@"namespace Microsoft.MyApp -{ - using System; - using Microsoft.Win32.SafeHandles; -#if false - using Win32; -#endif - using Win32; - - class Program - { - static void Main(string[] args) - { - SafeRegistryHandle h; - } - } -}", testHost); - } + class Program + { + static void Main(string[] args) + { + [|SafeRegistryHandle|] h; + } + } + } + """, + """ + namespace Microsoft.MyApp + { + using System; + using Microsoft.Win32.SafeHandles; + #if false + using Win32; + #endif + using Win32; + + class Program + { + static void Main(string[] args) + { + SafeRegistryHandle h; + } + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestAddUsingOrdinalUppercase(TestHost testHost) - { - await TestAsync( -@"namespace A -{ - class A - { - static void Main(string[] args) - { - var b = new [|B|](); - } - } -} + public Task TestAddUsingOrdinalUppercase(TestHost testHost) + => TestAsync( + """ + namespace A + { + class A + { + static void Main(string[] args) + { + var b = new [|B|](); + } + } + } -namespace lowercase -{ - class b - { - } -} + namespace lowercase + { + class b + { + } + } -namespace Uppercase -{ - class B - { - } -}", -@"using Uppercase; + namespace Uppercase + { + class B + { + } + } + """, + """ + using Uppercase; -namespace A -{ - class A - { - static void Main(string[] args) - { - var b = new B(); - } - } -} + namespace A + { + class A + { + static void Main(string[] args) + { + var b = new B(); + } + } + } -namespace lowercase -{ - class b - { - } -} + namespace lowercase + { + class b + { + } + } -namespace Uppercase -{ - class B - { - } -}", testHost); - } + namespace Uppercase + { + class B + { + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestAddUsingOrdinalLowercase(TestHost testHost) - { - await TestAsync( -@"namespace A -{ - class A - { - static void Main(string[] args) - { - var a = new [|b|](); - } - } -} + public Task TestAddUsingOrdinalLowercase(TestHost testHost) + => TestAsync( + """ + namespace A + { + class A + { + static void Main(string[] args) + { + var a = new [|b|](); + } + } + } -namespace lowercase -{ - class b - { - } -} + namespace lowercase + { + class b + { + } + } -namespace Uppercase -{ - class B - { - } -}", -@"using lowercase; + namespace Uppercase + { + class B + { + } + } + """, + """ + using lowercase; -namespace A -{ - class A - { - static void Main(string[] args) - { - var a = new b(); - } - } -} + namespace A + { + class A + { + static void Main(string[] args) + { + var a = new b(); + } + } + } -namespace lowercase -{ - class b - { - } -} + namespace lowercase + { + class b + { + } + } -namespace Uppercase -{ - class B - { - } -}", testHost); - } + namespace Uppercase + { + class B + { + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/7443")] - public async Task TestWithExistingIncompatibleExtension(TestHost testHost) - { - await TestAsync( -@"using N; + public Task TestWithExistingIncompatibleExtension(TestHost testHost) + => TestAsync( + """ + using N; -class C -{ - int x() - { - System.Collections.Generic.IEnumerable x = null; - return x.[|Any|] - } -} + class C + { + int x() + { + System.Collections.Generic.IEnumerable x = null; + return x.[|Any|] + } + } -namespace N -{ - static class Extensions - { - public static void Any(this string s) - { - } - } -}", -@"using System.Linq; -using N; + namespace N + { + static class Extensions + { + public static void Any(this string s) + { + } + } + } + """, + """ + using System.Linq; + using N; -class C -{ - int x() - { - System.Collections.Generic.IEnumerable x = null; - return x.Any - } -} + class C + { + int x() + { + System.Collections.Generic.IEnumerable x = null; + return x.Any + } + } -namespace N -{ - static class Extensions - { - public static void Any(this string s) - { - } - } -}", testHost); - } + namespace N + { + static class Extensions + { + public static void Any(this string s) + { + } + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem(1744, @"https://github.com/dotnet/roslyn/issues/1744")] - public async Task TestIncompleteCatchBlockInLambda(TestHost testHost) - { - await TestAsync( -@"class A -{ - System.Action a = () => { - try - { - } - catch ([|Exception|]", -@"using System; + public Task TestIncompleteCatchBlockInLambda(TestHost testHost) + => TestAsync( + """ + class A + { + System.Action a = () => { + try + { + } + catch ([|Exception|] + """, + """ + using System; -class A -{ - System.Action a = () => { - try - { - } - catch (Exception", testHost); - } + class A + { + System.Action a = () => { + try + { + } + catch (Exception + """, testHost); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")] - public async Task TestAddInsideLambda(TestHost testHost) - { - var initialText = -@"using System; - -static void Main(string[] args) -{ - Func f = () => { [|List|]. } -}"; + public Task TestAddInsideLambda(TestHost testHost) + => TestAsync(""" + using System; - var expectedText = -@"using System; -using System.Collections.Generic; + static void Main(string[] args) + { + Func f = () => { [|List|]. } + } + """, """ + using System; + using System.Collections.Generic; -static void Main(string[] args) -{ - Func f = () => { List. } -}"; - await TestAsync(initialText, expectedText, testHost); - } + static void Main(string[] args) + { + Func f = () => { List. } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")] - public async Task TestAddInsideLambda2(TestHost testHost) - { - var initialText = -@"using System; - -static void Main(string[] args) -{ - Func f = () => { [|List|] } -}"; + public Task TestAddInsideLambda2(TestHost testHost) + => TestAsync(""" + using System; - var expectedText = -@"using System; -using System.Collections.Generic; + static void Main(string[] args) + { + Func f = () => { [|List|] } + } + """, """ + using System; + using System.Collections.Generic; -static void Main(string[] args) -{ - Func f = () => { List } -}"; - await TestAsync(initialText, expectedText, testHost); - } + static void Main(string[] args) + { + Func f = () => { List } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")] - public async Task TestAddInsideLambda3(TestHost testHost) - { - var initialText = -@"using System; + public Task TestAddInsideLambda3(TestHost testHost) + => TestAsync(""" + using System; -static void Main(string[] args) -{ - Func f = () => { - var a = 3; - [|List|]. - return a; - }; -}"; - - var expectedText = -@"using System; -using System.Collections.Generic; + static void Main(string[] args) + { + Func f = () => { + var a = 3; + [|List|]. + return a; + }; + } + """, """ + using System; + using System.Collections.Generic; -static void Main(string[] args) -{ - Func f = () => { - var a = 3; - List. - return a; - }; -}"; - await TestAsync(initialText, expectedText, testHost); - } + static void Main(string[] args) + { + Func f = () => { + var a = 3; + List. + return a; + }; + } + """, testHost); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")] - public async Task TestAddInsideLambda4(TestHost testHost) - { - var initialText = -@"using System; + public Task TestAddInsideLambda4(TestHost testHost) + => TestAsync(""" + using System; -static void Main(string[] args) -{ - Func f = () => { - var a = 3; - [|List|] - return a; - }; -}"; - - var expectedText = -@"using System; -using System.Collections.Generic; + static void Main(string[] args) + { + Func f = () => { + var a = 3; + [|List|] + return a; + }; + } + """, """ + using System; + using System.Collections.Generic; -static void Main(string[] args) -{ - Func f = () => { - var a = 3; - List - return a; - }; -}"; - await TestAsync(initialText, expectedText, testHost); - } + static void Main(string[] args) + { + Func f = () => { + var a = 3; + List + return a; + }; + } + """, testHost); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860648")] [CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/902014")] - public async Task TestIncompleteParenthesizedLambdaExpression(TestHost testHost) - { - await TestAsync( -@"using System; + public Task TestIncompleteParenthesizedLambdaExpression(TestHost testHost) + => TestAsync( + """ + using System; -class Test -{ - void Goo() - { - Action a = () => { - [|IBindCtx|] }; - string a; - } -}", -@"using System; -using System.Runtime.InteropServices.ComTypes; + class Test + { + void Goo() + { + Action a = () => { + [|IBindCtx|] }; + string a; + } + } + """, + """ + using System; + using System.Runtime.InteropServices.ComTypes; -class Test -{ - void Goo() - { - Action a = () => { - IBindCtx }; - string a; - } -}", testHost); - } + class Test + { + void Goo() + { + Action a = () => { + IBindCtx }; + string a; + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/7461")] - public async Task TestExtensionWithIncompatibleInstance(TestHost testHost) - { - await TestAsync( -@"using System.IO; + public Task TestExtensionWithIncompatibleInstance(TestHost testHost) + => TestAsync( + """ + using System.IO; -namespace Namespace1 -{ - static class StreamExtensions - { - public static void Write(this Stream stream, byte[] bytes) - { - } - } -} + namespace Namespace1 + { + static class StreamExtensions + { + public static void Write(this Stream stream, byte[] bytes) + { + } + } + } -namespace Namespace2 -{ - class Goo - { - void Bar() - { - Stream stream = null; - stream.[|Write|](new byte[] { 1, 2, 3 }); - } - } -}", -@"using System.IO; -using Namespace1; + namespace Namespace2 + { + class Goo + { + void Bar() + { + Stream stream = null; + stream.[|Write|](new byte[] { 1, 2, 3 }); + } + } + } + """, + """ + using System.IO; + using Namespace1; -namespace Namespace1 -{ - static class StreamExtensions - { - public static void Write(this Stream stream, byte[] bytes) - { - } - } -} + namespace Namespace1 + { + static class StreamExtensions + { + public static void Write(this Stream stream, byte[] bytes) + { + } + } + } -namespace Namespace2 -{ - class Goo - { - void Bar() - { - Stream stream = null; - stream.Write(new byte[] { 1, 2, 3 }); - } - } -}", testHost); - } + namespace Namespace2 + { + class Goo + { + void Bar() + { + Stream stream = null; + stream.Write(new byte[] { 1, 2, 3 }); + } + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/5499")] - public async Task TestFormattingForNamespaceUsings(TestHost testHost) - { - await TestAsync( -@"namespace N -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Text; + public Task TestFormattingForNamespaceUsings(TestHost testHost) + => TestAsync( + """ + namespace N + { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; - class Program - { - void Main() - { - [|Task|] - } - } -}", -@"namespace N -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Text; - using System.Threading.Tasks; + class Program + { + void Main() + { + [|Task|] + } + } + } + """, + """ + namespace N + { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading.Tasks; - class Program - { - void Main() - { - Task - } - } -}", testHost); - } + class Program + { + void Main() + { + Task + } + } + } + """, testHost); [Fact] - public async Task TestGenericAmbiguityInSameNamespace() - { - await TestMissingInRegularAndScriptAsync( -@"namespace NS -{ - class C where T : [|C|].N - { - public class N - { - } - } -}"); - } + public Task TestGenericAmbiguityInSameNamespace() + => TestMissingInRegularAndScriptAsync( + """ + namespace NS + { + class C where T : [|C|].N + { + public class N + { + } + } + } + """); [Fact] - public async Task TestNotOnVar1() - { - await TestMissingInRegularAndScriptAsync( -@"namespace N -{ - class var { } -} + public Task TestNotOnVar1() + => TestMissingInRegularAndScriptAsync( + """ + namespace N + { + class var { } + } -class C -{ - void M() - { - [|var|] - } -} -"); - } + class C + { + void M() + { + [|var|] + } + } + """); [Fact] - public async Task TestNotOnVar2() - { - await TestMissingInRegularAndScriptAsync( -@"namespace N -{ - class Bar { } -} + public Task TestNotOnVar2() + => TestMissingInRegularAndScriptAsync( + """ + namespace N + { + class Bar { } + } -class C -{ - void M() - { - [|var|] - } -} -"); - } + class C + { + void M() + { + [|var|] + } + } + """); [Theory, CombinatorialData] [WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=226826")] - public async Task TestAddUsingWithLeadingDocCommentInFrontOfUsing1(TestHost testHost) - { - await TestAsync( -@" -/// Copyright 2016 - MyCompany -/// All Rights Reserved + public Task TestAddUsingWithLeadingDocCommentInFrontOfUsing1(TestHost testHost) + => TestAsync( + """ + /// Copyright 2016 - MyCompany + /// All Rights Reserved -using System; + using System; -class C : [|IEnumerable|] -{ -} -", -@" -/// Copyright 2016 - MyCompany -/// All Rights Reserved + class C : [|IEnumerable|] + { + } + """, + """ + /// Copyright 2016 - MyCompany + /// All Rights Reserved -using System; -using System.Collections.Generic; + using System; + using System.Collections.Generic; -class C : IEnumerable -{ -} -", testHost); - } + class C : IEnumerable + { + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=226826")] - public async Task TestAddUsingWithLeadingDocCommentInFrontOfUsing2(TestHost testHost) - { - await TestAsync( -@" -/// Copyright 2016 - MyCompany -/// All Rights Reserved + public Task TestAddUsingWithLeadingDocCommentInFrontOfUsing2(TestHost testHost) + => TestAsync( + """ + /// Copyright 2016 - MyCompany + /// All Rights Reserved -using System.Collections; + using System.Collections; -class C -{ - [|DateTime|] d; -} -", -@" -/// Copyright 2016 - MyCompany -/// All Rights Reserved + class C + { + [|DateTime|] d; + } + """, + """ + /// Copyright 2016 - MyCompany + /// All Rights Reserved -using System; -using System.Collections; + using System; + using System.Collections; -class C -{ - DateTime d; -} -", testHost); - } + class C + { + DateTime d; + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=226826")] - public async Task TestAddUsingWithLeadingDocCommentInFrontOfClass1(TestHost testHost) - { - await TestAsync( -@" -/// Copyright 2016 - MyCompany -/// All Rights Reserved -class C -{ - [|DateTime|] d; -} -", -@" -using System; + public Task TestAddUsingWithLeadingDocCommentInFrontOfClass1(TestHost testHost) + => TestAsync( + """ + /// Copyright 2016 - MyCompany + /// All Rights Reserved + class C + { + [|DateTime|] d; + } + """, + """ + using System; -/// Copyright 2016 - MyCompany -/// All Rights Reserved -class C -{ - DateTime d; -} -", testHost); - } + /// Copyright 2016 - MyCompany + /// All Rights Reserved + class C + { + DateTime d; + } + """, testHost); [Theory, CombinatorialData] - public async Task TestPlaceUsingWithUsings_NotWithAliases(TestHost testHost) - { - await TestAsync( -@" -using System; + public Task TestPlaceUsingWithUsings_NotWithAliases(TestHost testHost) + => TestAsync( + """ + using System; -namespace N -{ - using C = System.Collections; + namespace N + { + using C = System.Collections; - class Class - { - [|List|] Method() - { - Goo(); - } - } -}", -@" -using System; -using System.Collections.Generic; + class Class + { + [|List|] Method() + { + Goo(); + } + } + } + """, + """ + using System; + using System.Collections.Generic; -namespace N -{ - using C = System.Collections; + namespace N + { + using C = System.Collections; - class Class - { - List Method() - { - Goo(); - } - } -}", testHost); - } + class Class + { + List Method() + { + Goo(); + } + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/15025")] - public async Task TestPreferSystemNamespaceFirst(TestHost testHost) - { - await TestAsync( -@" -namespace Microsoft -{ - public class SomeClass { } -} + public Task TestPreferSystemNamespaceFirst(TestHost testHost) + => TestAsync( + """ + namespace Microsoft + { + public class SomeClass { } + } -namespace System -{ - public class SomeClass { } -} + namespace System + { + public class SomeClass { } + } -namespace N -{ - class Class - { - [|SomeClass|] c; - } -}", -@" -using System; + namespace N + { + class Class + { + [|SomeClass|] c; + } + } + """, + """ + using System; -namespace Microsoft -{ - public class SomeClass { } -} + namespace Microsoft + { + public class SomeClass { } + } -namespace System -{ - public class SomeClass { } -} + namespace System + { + public class SomeClass { } + } -namespace N -{ - class Class - { - SomeClass c; - } -}", testHost); - } + namespace N + { + class Class + { + SomeClass c; + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/15025")] - public async Task TestPreferSystemNamespaceFirst2(TestHost testHost) - { - await TestAsync( -@" -namespace Microsoft -{ - public class SomeClass { } -} + public Task TestPreferSystemNamespaceFirst2(TestHost testHost) + => TestAsync( + """ + namespace Microsoft + { + public class SomeClass { } + } -namespace System -{ - public class SomeClass { } -} + namespace System + { + public class SomeClass { } + } -namespace N -{ - class Class - { - [|SomeClass|] c; - } -}", -@" -using Microsoft; + namespace N + { + class Class + { + [|SomeClass|] c; + } + } + """, + """ + using Microsoft; -namespace Microsoft -{ - public class SomeClass { } -} + namespace Microsoft + { + public class SomeClass { } + } -namespace System -{ - public class SomeClass { } -} + namespace System + { + public class SomeClass { } + } -namespace N -{ - class Class - { - SomeClass c; - } -}", testHost, index: 1); - } + namespace N + { + class Class + { + SomeClass c; + } + } + """, testHost, index: 1); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18275")] - public async Task TestContextualKeyword1() - { - await TestMissingInRegularAndScriptAsync( -@" -namespace N -{ - class nameof - { - } -} + public Task TestContextualKeyword1() + => TestMissingInRegularAndScriptAsync( + """ + namespace N + { + class nameof + { + } + } -class C -{ - void M() - { - [|nameof|] - } -}"); - } + class C + { + void M() + { + [|nameof|] + } + } + """); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/19218")] - public async Task TestChangeCaseWithUsingsInNestedNamespace(TestHost testHost) - { - await TestAsync( -@"namespace VS -{ - interface IVsStatusbar - { - } -} + public Task TestChangeCaseWithUsingsInNestedNamespace(TestHost testHost) + => TestAsync( + """ + namespace VS + { + interface IVsStatusbar + { + } + } -namespace Outer -{ - using System; + namespace Outer + { + using System; - class C - { - void M() - { - // Note: IVsStatusBar is cased incorrectly. - [|IVsStatusBar|] b; - } - } -} -", -@"namespace VS -{ - interface IVsStatusbar - { - } -} + class C + { + void M() + { + // Note: IVsStatusBar is cased incorrectly. + [|IVsStatusBar|] b; + } + } + } + """, + """ + namespace VS + { + interface IVsStatusbar + { + } + } -namespace Outer -{ - using System; - using VS; + namespace Outer + { + using System; + using VS; - class C - { - void M() - { - // Note: IVsStatusBar is cased incorrectly. - IVsStatusbar b; - } - } -} -", testHost); - } + class C + { + void M() + { + // Note: IVsStatusBar is cased incorrectly. + IVsStatusbar b; + } + } + } + """, testHost); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19575")] public async Task TestNoNonGenericsWithGenericCodeParsedAsExpression() { - var code = @" -class C -{ - private void GetEvaluationRuleNames() - { - [|IEnumerable|] < Int32 > - return ImmutableArray.CreateRange(); - } -}"; + var code = """ + class C + { + private void GetEvaluationRuleNames() + { + [|IEnumerable|] < Int32 > + return ImmutableArray.CreateRange(); + } + } + """; await TestActionCountAsync(code, count: 1); await TestInRegularAndScriptAsync( code, -@" +""" using System.Collections.Generic; class C @@ -4801,1457 +4910,1427 @@ private void GetEvaluationRuleNames() IEnumerable < Int32 > return ImmutableArray.CreateRange(); } -}"); +} +"""); } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/19796")] - public async Task TestWhenInRome1(TestHost testHost) - { - // System is set to be sorted first, but the actual file shows it at the end. - // Keep things sorted, but respect that 'System' is at the end. - await TestAsync( -@" -using B; -using System; + public Task TestWhenInRome1(TestHost testHost) + => TestAsync( + """ + using B; + using System; -class Class -{ - void Method() - { - [|Goo|].Bar(); - } -} + class Class + { + void Method() + { + [|Goo|].Bar(); + } + } -namespace A -{ - class Goo - { - public static void Bar() - { - } - } -}", -@" -using A; -using B; -using System; + namespace A + { + class Goo + { + public static void Bar() + { + } + } + } + """, + """ + using A; + using B; + using System; -class Class -{ - void Method() - { - Goo.Bar(); - } -} + class Class + { + void Method() + { + Goo.Bar(); + } + } -namespace A -{ - class Goo - { - public static void Bar() - { - } - } -}", + namespace A + { + class Goo + { + public static void Bar() + { + } + } + } + """, testHost); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/19796")] - public async Task TestWhenInRome2(TestHost testHost) - { - // System is set to not be sorted first, but the actual file shows it sorted first. - // Keep things sorted, but respect that 'System' is at the beginning. - await TestAsync( -@" -using System; -using B; + public Task TestWhenInRome2(TestHost testHost) + => TestAsync( + """ + using System; + using B; -class Class -{ - void Method() - { - [|Goo|].Bar(); - } -} + class Class + { + void Method() + { + [|Goo|].Bar(); + } + } -namespace A -{ - class Goo - { - public static void Bar() - { - } - } -}", -@" -using System; -using A; -using B; + namespace A + { + class Goo + { + public static void Bar() + { + } + } + } + """, + """ + using System; + using A; + using B; -class Class -{ - void Method() - { - Goo.Bar(); - } -} + class Class + { + void Method() + { + Goo.Bar(); + } + } -namespace A -{ - class Goo - { - public static void Bar() - { - } - } -}", testHost); - } + namespace A + { + class Goo + { + public static void Bar() + { + } + } + } + """, testHost); [Fact] - public async Task TestExactMatchNoGlyph() - { - await TestSmartTagGlyphTagsAsync( -@"namespace VS -{ - interface Other - { - } -} + public Task TestExactMatchNoGlyph() + => TestSmartTagGlyphTagsAsync( + """ + namespace VS + { + interface Other + { + } + } -class C -{ - void M() - { - [|Other|] b; - } -} -", []); - } + class C + { + void M() + { + [|Other|] b; + } + } + """, []); [Fact] - public async Task TestFuzzyMatchGlyph() - { - await TestSmartTagGlyphTagsAsync( -@"namespace VS -{ - interface Other - { - } -} + public Task TestFuzzyMatchGlyph() + => TestSmartTagGlyphTagsAsync( + """ + namespace VS + { + interface Other + { + } + } -class C -{ - void M() - { - [|Otter|] b; - } -} -", WellKnownTagArrays.Namespace); - } + class C + { + void M() + { + [|Otter|] b; + } + } + """, WellKnownTagArrays.Namespace); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/29313")] - public async Task TestGetAwaiterExtensionMethod1(TestHost testHost) - { - await TestAsync( -@" -namespace A -{ - using System; - using System.Runtime.CompilerServices; - using System.Threading.Tasks; + public Task TestGetAwaiterExtensionMethod1(TestHost testHost) + => TestAsync( + """ + namespace A + { + using System; + using System.Runtime.CompilerServices; + using System.Threading.Tasks; - class C - { - async Task M() => await [|Goo|]; + class C + { + async Task M() => await [|Goo|]; - C Goo { get; set; } - } -} + C Goo { get; set; } + } + } -namespace B -{ - using System; - using System.Runtime.CompilerServices; - using System.Threading.Tasks; - using A; + namespace B + { + using System; + using System.Runtime.CompilerServices; + using System.Threading.Tasks; + using A; - static class Extensions - { - public static Awaiter GetAwaiter(this C scheduler) => null; + static class Extensions + { + public static Awaiter GetAwaiter(this C scheduler) => null; - public class Awaiter : INotifyCompletion - { - public object GetResult() => null; + public class Awaiter : INotifyCompletion + { + public object GetResult() => null; - public void OnCompleted(Action continuation) { } + public void OnCompleted(Action continuation) { } - public bool IsCompleted => true; - } - } -}", -@" -namespace A -{ - using System; - using System.Runtime.CompilerServices; - using System.Threading.Tasks; - using B; + public bool IsCompleted => true; + } + } + } + """, + """ + namespace A + { + using System; + using System.Runtime.CompilerServices; + using System.Threading.Tasks; + using B; - class C - { - async Task M() => await Goo; + class C + { + async Task M() => await Goo; - C Goo { get; set; } - } -} + C Goo { get; set; } + } + } -namespace B -{ - using System; - using System.Runtime.CompilerServices; - using System.Threading.Tasks; - using A; + namespace B + { + using System; + using System.Runtime.CompilerServices; + using System.Threading.Tasks; + using A; - static class Extensions - { - public static Awaiter GetAwaiter(this C scheduler) => null; + static class Extensions + { + public static Awaiter GetAwaiter(this C scheduler) => null; - public class Awaiter : INotifyCompletion - { - public object GetResult() => null; + public class Awaiter : INotifyCompletion + { + public object GetResult() => null; - public void OnCompleted(Action continuation) { } + public void OnCompleted(Action continuation) { } - public bool IsCompleted => true; - } - } -}", testHost); - } + public bool IsCompleted => true; + } + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/29313")] - public async Task TestGetAwaiterExtensionMethod2(TestHost testHost) - { - await TestAsync( -@" -namespace A -{ - using System; - using System.Runtime.CompilerServices; - using System.Threading.Tasks; + public Task TestGetAwaiterExtensionMethod2(TestHost testHost) + => TestAsync( + """ + namespace A + { + using System; + using System.Runtime.CompilerServices; + using System.Threading.Tasks; - class C - { - async Task M() => await [|GetC|](); + class C + { + async Task M() => await [|GetC|](); - C GetC() => null; - } -} + C GetC() => null; + } + } -namespace B -{ - using System; - using System.Runtime.CompilerServices; - using System.Threading.Tasks; - using A; + namespace B + { + using System; + using System.Runtime.CompilerServices; + using System.Threading.Tasks; + using A; - static class Extensions - { - public static Awaiter GetAwaiter(this C scheduler) => null; + static class Extensions + { + public static Awaiter GetAwaiter(this C scheduler) => null; - public class Awaiter : INotifyCompletion - { - public object GetResult() => null; + public class Awaiter : INotifyCompletion + { + public object GetResult() => null; - public void OnCompleted(Action continuation) { } + public void OnCompleted(Action continuation) { } - public bool IsCompleted => true; - } - } -}", -@" -namespace A -{ - using System; - using System.Runtime.CompilerServices; - using System.Threading.Tasks; - using B; + public bool IsCompleted => true; + } + } + } + """, + """ + namespace A + { + using System; + using System.Runtime.CompilerServices; + using System.Threading.Tasks; + using B; - class C - { - async Task M() => await GetC(); + class C + { + async Task M() => await GetC(); - C GetC() => null; - } -} + C GetC() => null; + } + } -namespace B -{ - using System; - using System.Runtime.CompilerServices; - using System.Threading.Tasks; - using A; + namespace B + { + using System; + using System.Runtime.CompilerServices; + using System.Threading.Tasks; + using A; - static class Extensions - { - public static Awaiter GetAwaiter(this C scheduler) => null; + static class Extensions + { + public static Awaiter GetAwaiter(this C scheduler) => null; - public class Awaiter : INotifyCompletion - { - public object GetResult() => null; + public class Awaiter : INotifyCompletion + { + public object GetResult() => null; - public void OnCompleted(Action continuation) { } + public void OnCompleted(Action continuation) { } - public bool IsCompleted => true; - } - } -}", testHost); - } + public bool IsCompleted => true; + } + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/745490")] - public async Task TestAddUsingForAwaitableReturningExtensionMethod(TestHost testHost) - { - await TestAsync( -@" -namespace A -{ - using System; - using System.Threading.Tasks; + public Task TestAddUsingForAwaitableReturningExtensionMethod(TestHost testHost) + => TestAsync( + """ + namespace A + { + using System; + using System.Threading.Tasks; - class C - { - C Instance { get; } + class C + { + C Instance { get; } - async Task M() => await Instance.[|Foo|](); - } -} + async Task M() => await Instance.[|Foo|](); + } + } -namespace B -{ - using System; - using System.Threading.Tasks; - using A; + namespace B + { + using System; + using System.Threading.Tasks; + using A; - static class Extensions - { - public static Task Foo(this C instance) => null; - } -}", -@" -namespace A -{ - using System; - using System.Threading.Tasks; - using B; + static class Extensions + { + public static Task Foo(this C instance) => null; + } + } + """, + """ + namespace A + { + using System; + using System.Threading.Tasks; + using B; - class C - { - C Instance { get; } + class C + { + C Instance { get; } - async Task M() => await Instance.Foo(); - } -} + async Task M() => await Instance.Foo(); + } + } -namespace B -{ - using System; - using System.Threading.Tasks; - using A; + namespace B + { + using System; + using System.Threading.Tasks; + using A; - static class Extensions - { - public static Task Foo(this C instance) => null; - } -}", testHost); - } + static class Extensions + { + public static Task Foo(this C instance) => null; + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestAddUsingForExtensionGetEnumeratorReturningIEnumerator(TestHost testHost) - { - await TestAsync( -@" -namespace A -{ - class C - { - C Instance { get; } + public Task TestAddUsingForExtensionGetEnumeratorReturningIEnumerator(TestHost testHost) + => TestAsync( + """ + namespace A + { + class C + { + C Instance { get; } - void M() { foreach (var i in [|Instance|]); } - } -} + void M() { foreach (var i in [|Instance|]); } + } + } -namespace B -{ - using A; - using System.Collections.Generic; + namespace B + { + using A; + using System.Collections.Generic; - static class Extensions - { - public static IEnumerator GetEnumerator(this C instance) => null; - } -}", -@" -using B; + static class Extensions + { + public static IEnumerator GetEnumerator(this C instance) => null; + } + } + """, + """ + using B; -namespace A -{ - class C - { - C Instance { get; } + namespace A + { + class C + { + C Instance { get; } - void M() { foreach (var i in Instance); } - } -} + void M() { foreach (var i in Instance); } + } + } -namespace B -{ - using A; - using System.Collections.Generic; + namespace B + { + using A; + using System.Collections.Generic; - static class Extensions - { - public static IEnumerator GetEnumerator(this C instance) => null; - } -}", testHost); - } + static class Extensions + { + public static IEnumerator GetEnumerator(this C instance) => null; + } + } + """, testHost); [Theory, CombinatorialData] - public async Task TestAddUsingForExtensionGetEnumeratorReturningPatternEnumerator(TestHost testHost) - { - await TestAsync( -@" -namespace A -{ - class C - { - C Instance { get; } - - void M() { foreach (var i in [|Instance|]); } - } -} - -namespace B -{ - using A; - - static class Extensions - { - public static Enumerator GetEnumerator(this C instance) => null; - } - - public class Enumerator - { - public int Current { get; } - public bool MoveNext(); - } -}", -@" -using B; + public Task TestAddUsingForExtensionGetEnumeratorReturningPatternEnumerator(TestHost testHost) + => TestAsync( + """ + namespace A + { + class C + { + C Instance { get; } -namespace A -{ - class C - { - C Instance { get; } + void M() { foreach (var i in [|Instance|]); } + } + } - void M() { foreach (var i in Instance); } - } -} + namespace B + { + using A; -namespace B -{ - using A; + static class Extensions + { + public static Enumerator GetEnumerator(this C instance) => null; + } - static class Extensions - { - public static Enumerator GetEnumerator(this C instance) => null; - } + public class Enumerator + { + public int Current { get; } + public bool MoveNext(); + } + } + """, + """ + using B; - public class Enumerator - { - public int Current { get; } - public bool MoveNext(); - } -}", testHost); - } + namespace A + { + class C + { + C Instance { get; } - [Fact] - public async Task TestMissingForExtensionInvalidGetEnumerator() - { - await TestMissingAsync( -@" -namespace A -{ - class C - { - C Instance { get; } + void M() { foreach (var i in Instance); } + } + } - void M() { foreach (var i in [|Instance|]); } - } -} + namespace B + { + using A; -namespace B -{ - using A; + static class Extensions + { + public static Enumerator GetEnumerator(this C instance) => null; + } - static class Extensions - { - public static bool GetEnumerator(this C instance) => null; - } -}"); - } + public class Enumerator + { + public int Current { get; } + public bool MoveNext(); + } + } + """, testHost); - [Theory, CombinatorialData] - public async Task TestAddUsingForExtensionGetEnumeratorReturningPatternEnumeratorWrongAsync(TestHost testHost) - { - await TestAsync( -@" -namespace A -{ - class C - { - C Instance { get; }; + [Fact] + public Task TestMissingForExtensionInvalidGetEnumerator() + => TestMissingAsync( + """ + namespace A + { + class C + { + C Instance { get; } - void M() { foreach (var i in [|Instance|]); } + void M() { foreach (var i in [|Instance|]); } + } + } - public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) - { - return new Enumerator(); - } - public sealed class Enumerator - { - public async System.Threading.Tasks.Task MoveNextAsync() => throw null; - public int Current => throw null; - } - } -} + namespace B + { + using A; -namespace B -{ - using A; + static class Extensions + { + public static bool GetEnumerator(this C instance) => null; + } + } + """); - static class Extensions - { - public static Enumerator GetEnumerator(this C instance) => null; - } + [Theory, CombinatorialData] + public Task TestAddUsingForExtensionGetEnumeratorReturningPatternEnumeratorWrongAsync(TestHost testHost) + => TestAsync( + """ + namespace A + { + class C + { + C Instance { get; }; + + void M() { foreach (var i in [|Instance|]); } + + public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) + { + return new Enumerator(); + } + public sealed class Enumerator + { + public async System.Threading.Tasks.Task MoveNextAsync() => throw null; + public int Current => throw null; + } + } + } - public class Enumerator - { - public int Current { get; } - public bool MoveNext(); - } -}", -@" -using B; + namespace B + { + using A; -namespace A -{ - class C - { - C Instance { get; }; + static class Extensions + { + public static Enumerator GetEnumerator(this C instance) => null; + } - void M() { foreach (var i in Instance); } + public class Enumerator + { + public int Current { get; } + public bool MoveNext(); + } + } + """, + """ + using B; - public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) - { - return new Enumerator(); - } - public sealed class Enumerator - { - public async System.Threading.Tasks.Task MoveNextAsync() => throw null; - public int Current => throw null; - } - } -} + namespace A + { + class C + { + C Instance { get; }; + + void M() { foreach (var i in Instance); } + + public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) + { + return new Enumerator(); + } + public sealed class Enumerator + { + public async System.Threading.Tasks.Task MoveNextAsync() => throw null; + public int Current => throw null; + } + } + } -namespace B -{ - using A; + namespace B + { + using A; - static class Extensions - { - public static Enumerator GetEnumerator(this C instance) => null; - } + static class Extensions + { + public static Enumerator GetEnumerator(this C instance) => null; + } - public class Enumerator - { - public int Current { get; } - public bool MoveNext(); - } -}", testHost); - } + public class Enumerator + { + public int Current { get; } + public bool MoveNext(); + } + } + """, testHost); [Fact] - public async Task TestMissingForExtensionGetAsyncEnumeratorOnForeach() - { - await TestMissingAsync( -@" -namespace A -{ - class C - { - C Instance { get; } + public Task TestMissingForExtensionGetAsyncEnumeratorOnForeach() + => TestMissingAsync( + """ + namespace A + { + class C + { + C Instance { get; } - void M() { foreach (var i in [|Instance|]); } - } -} + void M() { foreach (var i in [|Instance|]); } + } + } -namespace B -{ - using A; - using System.Collections.Generic; + namespace B + { + using A; + using System.Collections.Generic; - static class Extensions - { - public static IAsyncEnumerator GetAsyncEnumerator(this C instance) => null; - } -}" + IAsyncEnumerable); - } + static class Extensions + { + public static IAsyncEnumerator GetAsyncEnumerator(this C instance) => null; + } + } + """ + IAsyncEnumerable); [Theory, CombinatorialData] - public async Task TestAddUsingForExtensionGetAsyncEnumeratorReturningIAsyncEnumerator(TestHost testHost) - { - await TestAsync( -@" -using System.Threading.Tasks; -namespace A -{ - class C - { - C Instance { get; } + public Task TestAddUsingForExtensionGetAsyncEnumeratorReturningIAsyncEnumerator(TestHost testHost) + => TestAsync( + """ + using System.Threading.Tasks; + namespace A + { + class C + { + C Instance { get; } - async Task M() { await foreach (var i in [|Instance|]); } - } -} + async Task M() { await foreach (var i in [|Instance|]); } + } + } -namespace B -{ - using A; - using System.Collections.Generic; + namespace B + { + using A; + using System.Collections.Generic; - static class Extensions - { - public static IAsyncEnumerator GetAsyncEnumerator(this C instance) => null; - } -}" + IAsyncEnumerable, -@" -using System.Threading.Tasks; -using B; -namespace A -{ - class C - { - C Instance { get; } + static class Extensions + { + public static IAsyncEnumerator GetAsyncEnumerator(this C instance) => null; + } + } + """ + IAsyncEnumerable, + """ + using System.Threading.Tasks; + using B; + namespace A + { + class C + { + C Instance { get; } - async Task M() { await foreach (var i in Instance); } - } -} + async Task M() { await foreach (var i in Instance); } + } + } -namespace B -{ - using A; - using System.Collections.Generic; + namespace B + { + using A; + using System.Collections.Generic; - static class Extensions - { - public static IAsyncEnumerator GetAsyncEnumerator(this C instance) => null; - } -}" + IAsyncEnumerable, testHost); - } + static class Extensions + { + public static IAsyncEnumerator GetAsyncEnumerator(this C instance) => null; + } + } + """ + IAsyncEnumerable, testHost); [Theory, CombinatorialData] - public async Task TestAddUsingForExtensionGetAsyncEnumeratorReturningPatternEnumerator(TestHost testHost) - { - await TestAsync( -@" -using System.Threading.Tasks; -namespace A -{ - class C - { - C Instance { get; } + public Task TestAddUsingForExtensionGetAsyncEnumeratorReturningPatternEnumerator(TestHost testHost) + => TestAsync( + """ + using System.Threading.Tasks; + namespace A + { + class C + { + C Instance { get; } - async Task M() { await foreach (var i in [|Instance|]); } - } -} + async Task M() { await foreach (var i in [|Instance|]); } + } + } -namespace B -{ - using A; + namespace B + { + using A; - static class Extensions - { - public static Enumerator GetAsyncEnumerator(this C instance) => null; - } + static class Extensions + { + public static Enumerator GetAsyncEnumerator(this C instance) => null; + } - public class Enumerator - { - public int Current { get; } - public Task MoveNextAsync(); - } -}", -@" -using System.Threading.Tasks; -using B; -namespace A -{ - class C - { - C Instance { get; } + public class Enumerator + { + public int Current { get; } + public Task MoveNextAsync(); + } + } + """, + """ + using System.Threading.Tasks; + using B; + namespace A + { + class C + { + C Instance { get; } - async Task M() { await foreach (var i in Instance); } - } -} + async Task M() { await foreach (var i in Instance); } + } + } -namespace B -{ - using A; + namespace B + { + using A; - static class Extensions - { - public static Enumerator GetAsyncEnumerator(this C instance) => null; - } + static class Extensions + { + public static Enumerator GetAsyncEnumerator(this C instance) => null; + } - public class Enumerator - { - public int Current { get; } - public Task MoveNextAsync(); - } -}", testHost); - } + public class Enumerator + { + public int Current { get; } + public Task MoveNextAsync(); + } + } + """, testHost); [Fact] - public async Task TestMissingForExtensionInvalidGetAsyncEnumerator() - { - await TestMissingAsync( -@" -using System.Threading.Tasks; + public Task TestMissingForExtensionInvalidGetAsyncEnumerator() + => TestMissingAsync( + """ + using System.Threading.Tasks; -namespace A -{ - class C - { - C Instance { get; } + namespace A + { + class C + { + C Instance { get; } - async Task M() { await foreach (var i in [|Instance|]); } - } -} + async Task M() { await foreach (var i in [|Instance|]); } + } + } -namespace B -{ - using A; + namespace B + { + using A; - static class Extensions - { - public static bool GetAsyncEnumerator(this C instance) => null; - } -}"); - } + static class Extensions + { + public static bool GetAsyncEnumerator(this C instance) => null; + } + } + """); [Theory, CombinatorialData] - public async Task TestAddUsingForExtensionGetAsyncEnumeratorReturningPatternEnumeratorWrongAsync(TestHost testHost) - { - await TestAsync( -@" -using System.Threading.Tasks; -namespace A -{ - class C - { - C Instance { get; } + public Task TestAddUsingForExtensionGetAsyncEnumeratorReturningPatternEnumeratorWrongAsync(TestHost testHost) + => TestAsync( + """ + using System.Threading.Tasks; + namespace A + { + class C + { + C Instance { get; } - Task M() { await foreach (var i in [|Instance|]); } + Task M() { await foreach (var i in [|Instance|]); } - public Enumerator GetEnumerator() - { - return new Enumerator(); - } + public Enumerator GetEnumerator() + { + return new Enumerator(); + } - public class Enumerator - { - public int Current { get; } - public bool MoveNext(); - } - } -} + public class Enumerator + { + public int Current { get; } + public bool MoveNext(); + } + } + } -namespace B -{ - using A; + namespace B + { + using A; - static class Extensions - { - public static Enumerator GetAsyncEnumerator(this C instance) => null; - } + static class Extensions + { + public static Enumerator GetAsyncEnumerator(this C instance) => null; + } - public sealed class Enumerator - { - public async System.Threading.Tasks.Task MoveNextAsync() => throw null; - public int Current => throw null; - } -}", -@" -using System.Threading.Tasks; -using B; -namespace A -{ - class C - { - C Instance { get; } + public sealed class Enumerator + { + public async System.Threading.Tasks.Task MoveNextAsync() => throw null; + public int Current => throw null; + } + } + """, + """ + using System.Threading.Tasks; + using B; + namespace A + { + class C + { + C Instance { get; } - Task M() { await foreach (var i in Instance); } + Task M() { await foreach (var i in Instance); } - public Enumerator GetEnumerator() - { - return new Enumerator(); - } + public Enumerator GetEnumerator() + { + return new Enumerator(); + } - public class Enumerator - { - public int Current { get; } - public bool MoveNext(); - } - } -} + public class Enumerator + { + public int Current { get; } + public bool MoveNext(); + } + } + } -namespace B -{ - using A; + namespace B + { + using A; - static class Extensions - { - public static Enumerator GetAsyncEnumerator(this C instance) => null; - } + static class Extensions + { + public static Enumerator GetAsyncEnumerator(this C instance) => null; + } - public sealed class Enumerator - { - public async System.Threading.Tasks.Task MoveNextAsync() => throw null; - public int Current => throw null; - } -}", testHost); - } + public sealed class Enumerator + { + public async System.Threading.Tasks.Task MoveNextAsync() => throw null; + public int Current => throw null; + } + } + """, testHost); [Fact] - public async Task TestMissingForExtensionGetEnumeratorOnAsyncForeach() - { - await TestMissingAsync( -@" -using System.Threading.Tasks; + public Task TestMissingForExtensionGetEnumeratorOnAsyncForeach() + => TestMissingAsync( + """ + using System.Threading.Tasks; -namespace A -{ - class C - { - C Instance { get; } + namespace A + { + class C + { + C Instance { get; } - Task M() { await foreach (var i in [|Instance|]); } - } -} + Task M() { await foreach (var i in [|Instance|]); } + } + } -namespace B -{ - using A; - using System.Collections.Generic; + namespace B + { + using A; + using System.Collections.Generic; - static class Extensions - { - public static IEnumerator GetEnumerator(this C instance) => null; - } -}"); - } + static class Extensions + { + public static IEnumerator GetEnumerator(this C instance) => null; + } + } + """); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/30734")] - public async Task UsingPlacedWithStaticUsingInNamespace_WhenNoExistingUsings(TestHost testHost) - { - await TestAsync( -@" -namespace N -{ - using static System.Math; + public Task UsingPlacedWithStaticUsingInNamespace_WhenNoExistingUsings(TestHost testHost) + => TestAsync( + """ + namespace N + { + using static System.Math; - class C - { - public [|List|] F; - } -} -", -@" -namespace N -{ - using System.Collections.Generic; - using static System.Math; + class C + { + public [|List|] F; + } + } + """, + """ + namespace N + { + using System.Collections.Generic; + using static System.Math; - class C - { - public List F; - } -} -", testHost); - } + class C + { + public List F; + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/30734")] - public async Task UsingPlacedWithStaticUsingInInnerNestedNamespace_WhenNoExistingUsings(TestHost testHost) - { - await TestAsync( -@" -namespace N -{ - namespace M - { - using static System.Math; + public Task UsingPlacedWithStaticUsingInInnerNestedNamespace_WhenNoExistingUsings(TestHost testHost) + => TestAsync( + """ + namespace N + { + namespace M + { + using static System.Math; - class C - { - public [|List|] F; - } - } -} -", -@" -namespace N -{ - namespace M - { - using System.Collections.Generic; - using static System.Math; + class C + { + public [|List|] F; + } + } + } + """, + """ + namespace N + { + namespace M + { + using System.Collections.Generic; + using static System.Math; - class C - { - public List F; - } - } -} -", testHost); - } + class C + { + public List F; + } + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/30734")] - public async Task UsingPlacedWithStaticUsingInOuterNestedNamespace_WhenNoExistingUsings(TestHost testHost) - { - await TestAsync( -@" -namespace N -{ - using static System.Math; + public Task UsingPlacedWithStaticUsingInOuterNestedNamespace_WhenNoExistingUsings(TestHost testHost) + => TestAsync( + """ + namespace N + { + using static System.Math; - namespace M - { - class C - { - public [|List|] F; - } - } -} -", -@" -namespace N -{ - using System.Collections.Generic; - using static System.Math; + namespace M + { + class C + { + public [|List|] F; + } + } + } + """, + """ + namespace N + { + using System.Collections.Generic; + using static System.Math; - namespace M - { - class C - { - public List F; - } - } -} -", testHost); - } + namespace M + { + class C + { + public List F; + } + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/30734")] - public async Task UsingPlacedWithExistingUsingInCompilationUnit_WhenStaticUsingInNamespace(TestHost testHost) - { - await TestAsync( -@" -using System; + public Task UsingPlacedWithExistingUsingInCompilationUnit_WhenStaticUsingInNamespace(TestHost testHost) + => TestAsync( + """ + using System; -namespace N -{ - using static System.Math; + namespace N + { + using static System.Math; - class C - { - public [|List|] F; - } -} -", -@" -using System; -using System.Collections.Generic; + class C + { + public [|List|] F; + } + } + """, + """ + using System; + using System.Collections.Generic; -namespace N -{ - using static System.Math; + namespace N + { + using static System.Math; - class C - { - public List F; - } -} -", testHost); - } + class C + { + public List F; + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/30734")] - public async Task UsingPlacedWithExistingUsing_WhenStaticUsingInInnerNestedNamespace(TestHost testHost) - { - await TestAsync( -@" -namespace N -{ - using System; + public Task UsingPlacedWithExistingUsing_WhenStaticUsingInInnerNestedNamespace(TestHost testHost) + => TestAsync( + """ + namespace N + { + using System; - namespace M - { - using static System.Math; + namespace M + { + using static System.Math; - class C - { - public [|List|] F; - } - } -} -", -@" -namespace N -{ - using System; - using System.Collections.Generic; + class C + { + public [|List|] F; + } + } + } + """, + """ + namespace N + { + using System; + using System.Collections.Generic; - namespace M - { - using static System.Math; + namespace M + { + using static System.Math; - class C - { - public List F; - } - } -} -", testHost); - } + class C + { + public List F; + } + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/30734")] - public async Task UsingPlacedWithExistingUsing_WhenStaticUsingInOuterNestedNamespace(TestHost testHost) - { - await TestAsync( -@" -namespace N -{ - using static System.Math; + public Task UsingPlacedWithExistingUsing_WhenStaticUsingInOuterNestedNamespace(TestHost testHost) + => TestAsync( + """ + namespace N + { + using static System.Math; - namespace M - { - using System; + namespace M + { + using System; - class C - { - public [|List|] F; - } - } -} -", -@" -namespace N -{ - using static System.Math; + class C + { + public [|List|] F; + } + } + } + """, + """ + namespace N + { + using static System.Math; - namespace M - { - using System; - using System.Collections.Generic; + namespace M + { + using System; + using System.Collections.Generic; - class C - { - public List F; - } - } -} -", testHost); - } + class C + { + public List F; + } + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/30734")] - public async Task UsingPlacedWithUsingAliasInNamespace_WhenNoExistingUsing(TestHost testHost) - { - await TestAsync( -@" -namespace N -{ - using SAction = System.Action; + public Task UsingPlacedWithUsingAliasInNamespace_WhenNoExistingUsing(TestHost testHost) + => TestAsync( + """ + namespace N + { + using SAction = System.Action; - class C - { - public [|List|] F; - } -} -", -@" -namespace N -{ - using System.Collections.Generic; - using SAction = System.Action; + class C + { + public [|List|] F; + } + } + """, + """ + namespace N + { + using System.Collections.Generic; + using SAction = System.Action; - class C - { - public List F; - } -} -", testHost); - } + class C + { + public List F; + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/30734")] - public async Task UsingPlacedWithUsingAliasInInnerNestedNamespace_WhenNoExistingUsing(TestHost testHost) - { - await TestAsync( -@" -namespace N -{ - namespace M - { - using SAction = System.Action; + public Task UsingPlacedWithUsingAliasInInnerNestedNamespace_WhenNoExistingUsing(TestHost testHost) + => TestAsync( + """ + namespace N + { + namespace M + { + using SAction = System.Action; - class C - { - public [|List|] F; - } - } -} -", -@" -namespace N -{ - namespace M - { - using System.Collections.Generic; - using SAction = System.Action; + class C + { + public [|List|] F; + } + } + } + """, + """ + namespace N + { + namespace M + { + using System.Collections.Generic; + using SAction = System.Action; - class C - { - public List F; - } - } -} -", testHost); - } + class C + { + public List F; + } + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/30734")] - public async Task UsingPlacedWithUsingAliasInOuterNestedNamespace_WhenNoExistingUsing(TestHost testHost) - { - await TestAsync( -@" -namespace N -{ - using SAction = System.Action; - - namespace M - { - class C - { - public [|List|] F; - } - } -} -", -@" -namespace N -{ - using System.Collections.Generic; - using SAction = System.Action; + public Task UsingPlacedWithUsingAliasInOuterNestedNamespace_WhenNoExistingUsing(TestHost testHost) + => TestAsync( + """ + namespace N + { + using SAction = System.Action; - namespace M - { - class C - { - public List F; - } - } -} -", testHost); - } + namespace M + { + class C + { + public [|List|] F; + } + } + } + """, + """ + namespace N + { + using System.Collections.Generic; + using SAction = System.Action; + + namespace M + { + class C + { + public List F; + } + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/30734")] - public async Task UsingPlacedWithExistingUsingInCompilationUnit_WhenUsingAliasInNamespace(TestHost testHost) - { - await TestAsync( -@" -using System; + public Task UsingPlacedWithExistingUsingInCompilationUnit_WhenUsingAliasInNamespace(TestHost testHost) + => TestAsync( + """ + using System; -namespace N -{ - using SAction = System.Action; + namespace N + { + using SAction = System.Action; - class C - { - public [|List|] F; - } -} -", -@" -using System; -using System.Collections.Generic; + class C + { + public [|List|] F; + } + } + """, + """ + using System; + using System.Collections.Generic; -namespace N -{ - using SAction = System.Action; + namespace N + { + using SAction = System.Action; - class C - { - public List F; - } -} -", testHost); - } + class C + { + public List F; + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/30734")] - public async Task UsingPlacedWithExistingUsing_WhenUsingAliasInInnerNestedNamespace(TestHost testHost) - { - await TestAsync( -@" -namespace N -{ - using System; + public Task UsingPlacedWithExistingUsing_WhenUsingAliasInInnerNestedNamespace(TestHost testHost) + => TestAsync( + """ + namespace N + { + using System; - namespace M - { - using SAction = System.Action; + namespace M + { + using SAction = System.Action; - class C - { - public [|List|] F; - } - } -} -", -@" -namespace N -{ - using System; - using System.Collections.Generic; + class C + { + public [|List|] F; + } + } + } + """, + """ + namespace N + { + using System; + using System.Collections.Generic; - namespace M - { - using SAction = System.Action; + namespace M + { + using SAction = System.Action; - class C - { - public [|List|] F; - } - } -} -", testHost); - } + class C + { + public [|List|] F; + } + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/30734")] - public async Task UsingPlacedWithExistingUsing_WhenUsingAliasInOuterNestedNamespace(TestHost testHost) - { - await TestAsync( -@" -namespace N -{ - using SAction = System.Action; + public Task UsingPlacedWithExistingUsing_WhenUsingAliasInOuterNestedNamespace(TestHost testHost) + => TestAsync( + """ + namespace N + { + using SAction = System.Action; - namespace M - { - using System; + namespace M + { + using System; - class C - { - public [|List|] F; - } - } -} -", -@" -namespace N -{ - using SAction = System.Action; + class C + { + public [|List|] F; + } + } + } + """, + """ + namespace N + { + using SAction = System.Action; - namespace M - { - using System; - using System.Collections.Generic; + namespace M + { + using System; + using System.Collections.Generic; - class C - { - public [|List|] F; - } - } -} -", testHost); - } + class C + { + public [|List|] F; + } + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/25003")] - public async Task KeepUsingsGrouped1(TestHost testHost) - { - await TestAsync( -@" -using System; + public Task KeepUsingsGrouped1(TestHost testHost) + => TestAsync( + """ + using System; -class Program -{ - static void Main(string[] args) - { - [|Goo|] - } -} + class Program + { + static void Main(string[] args) + { + [|Goo|] + } + } -namespace Microsoft -{ - public class Goo - { - } -}", -@" -using System; -using Microsoft; + namespace Microsoft + { + public class Goo + { + } + } + """, + """ + using System; + using Microsoft; -class Program -{ - static void Main(string[] args) - { - Goo - } -} + class Program + { + static void Main(string[] args) + { + Goo + } + } -namespace Microsoft -{ - public class Goo - { - } -}", testHost); - } + namespace Microsoft + { + public class Goo + { + } + } + """, testHost); [Fact, WorkItem(1239, @"https://github.com/dotnet/roslyn/issues/1239")] - public async Task TestIncompleteLambda1() - { - await TestInRegularAndScriptAsync( -@"using System.Linq; + public Task TestIncompleteLambda1() + => TestInRegularAndScriptAsync( + """ + using System.Linq; -class C -{ - C() - { - """".Select(() => { - new [|Byte|]", -@"using System; -using System.Linq; + class C + { + C() + { + "".Select(() => { + new [|Byte|] + """, + """ + using System; + using System.Linq; -class C -{ - C() - { - """".Select(() => { - new Byte"); - } + class C + { + C() + { + "".Select(() => { + new Byte + """); [Fact, WorkItem(1239, @"https://github.com/dotnet/roslyn/issues/1239")] - public async Task TestIncompleteLambda2() - { - await TestInRegularAndScriptAsync( -@"using System.Linq; + public Task TestIncompleteLambda2() + => TestInRegularAndScriptAsync( + """ + using System.Linq; -class C -{ - C() - { - """".Select(() => { - new [|Byte|]() }", -@"using System; -using System.Linq; + class C + { + C() + { + "".Select(() => { + new [|Byte|]() } + """, + """ + using System; + using System.Linq; -class C -{ - C() - { - """".Select(() => { - new Byte() }"); - } + class C + { + C() + { + "".Select(() => { + new Byte() } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/902014")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860648")] - public async Task TestIncompleteSimpleLambdaExpression() - { - await TestInRegularAndScriptAsync( -@"using System.Linq; + public Task TestIncompleteSimpleLambdaExpression() + => TestInRegularAndScriptAsync( + """ + using System.Linq; -class Program -{ - static void Main(string[] args) - { - args[0].Any(x => [|IBindCtx|] - string a; - } -}", -@"using System.Linq; -using System.Runtime.InteropServices.ComTypes; + class Program + { + static void Main(string[] args) + { + args[0].Any(x => [|IBindCtx|] + string a; + } + } + """, + """ + using System.Linq; + using System.Runtime.InteropServices.ComTypes; -class Program -{ - static void Main(string[] args) - { - args[0].Any(x => IBindCtx - string a; - } -}"); - } + class Program + { + static void Main(string[] args) + { + args[0].Any(x => IBindCtx + string a; + } + } + """); [Theory, CombinatorialData] [WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")] public async Task TestAddUsingsEditorBrowsableNeverSameProject(TestHost testHost) { - const string InitialWorkspace = @" - - - -using System.ComponentModel; -namespace ProjectLib -{ - [EditorBrowsable(EditorBrowsableState.Never)] - public class Project - { - } -} - - -class Program -{ - static void Main(string[] args) - { - Project p = new [|Project()|]; - } -} - - -"; + const string InitialWorkspace = """ + + + using System.ComponentModel; + namespace ProjectLib + { + [EditorBrowsable(EditorBrowsableState.Never)] + public class Project + { + } + } + class Program + { + static void Main(string[] args) + { + Project p = new [|Project()|]; + } + } + + + """; - const string ExpectedDocumentText = @" -using ProjectLib; + const string ExpectedDocumentText = """ + using ProjectLib; -class Program -{ - static void Main(string[] args) - { - Project p = new [|Project()|]; - } -} -"; + class Program + { + static void Main(string[] args) + { + Project p = new [|Project()|]; + } + } + """; await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost); } @@ -6260,31 +6339,32 @@ static void Main(string[] args) [WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")] public async Task TestAddUsingsEditorBrowsableNeverDifferentProject(TestHost testHost) { - const string InitialWorkspace = @" - - - -imports System.ComponentModel -namespace ProjectLib - <EditorBrowsable(EditorBrowsableState.Never)> - public class Project - end class -end namespace - - - - lib - -class Program -{ - static void Main(string[] args) - { - [|Project|] p = new Project(); - } -} - - -"; + const string InitialWorkspace = """ + + + + imports System.ComponentModel + namespace ProjectLib + <EditorBrowsable(EditorBrowsableState.Never)> + public class Project + end class + end namespace + + + + lib + + class Program + { + static void Main(string[] args) + { + [|Project|] p = new Project(); + } + } + + + + """; await TestMissingAsync(InitialWorkspace, new TestParameters(testHost: testHost)); } @@ -6292,80 +6372,74 @@ static void Main(string[] args) [WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")] public async Task TestAddUsingsEditorBrowsableAdvancedDifferentProjectOptionOn(TestHost testHost) { - const string InitialWorkspace = @" - - - -imports System.ComponentModel -namespace ProjectLib - <EditorBrowsable(EditorBrowsableState.Advanced)> - public class Project - end class -end namespace - - - - lib - -class Program -{ - static void Main(string[] args) - { - [|Project|] p = new Project(); - } -} - - -"; + const string InitialWorkspace = """ + + + imports System.ComponentModel + namespace ProjectLib + <EditorBrowsable(EditorBrowsableState.Advanced)> + public class Project + end class + end namespace + + + lib + class Program + { + static void Main(string[] args) + { + [|Project|] p = new Project(); + } + } + + + """; - const string ExpectedDocumentText = @" -using ProjectLib; + const string ExpectedDocumentText = """ + using ProjectLib; -class Program -{ - static void Main(string[] args) - { - Project p = new [|Project()|]; - } -} -"; + class Program + { + static void Main(string[] args) + { + Project p = new [|Project()|]; + } + } + """; await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost); } [Theory, CombinatorialData] [WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")] - public async Task TestAddUsingsEditorBrowsableAdvancedDifferentProjectOptionOff(TestHost testHost) - { - var initialWorkspace = @" - - - -imports System.ComponentModel -namespace ProjectLib - <EditorBrowsable(EditorBrowsableState.Advanced)> - public class Project - end class -end namespace - - - - lib - -class Program -{ - static void Main(string[] args) - { - [|Project|] p = new Project(); - } -} - - -"; - - await TestMissingAsync(initialWorkspace, new TestParameters( + public Task TestAddUsingsEditorBrowsableAdvancedDifferentProjectOptionOff(TestHost testHost) + => TestMissingAsync(""" + + + + imports System.ComponentModel + namespace ProjectLib + <EditorBrowsable(EditorBrowsableState.Advanced)> + public class Project + end class + end namespace + + + + lib + + class Program + { + static void Main(string[] args) + { + [|Project|] p = new Project(); + } + } + + + + """, new TestParameters( options: Option(MemberDisplayOptionsStorage.HideAdvancedMembers, true), testHost: testHost)); - } /// /// Note that this test verifies the current end of line sequence in using directives is preserved regardless of @@ -6373,9 +6447,8 @@ static void Main(string[] args) /// [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/62976")] - public async Task TestAddUsingPreservesNewlines1(TestHost testHost, [CombinatorialValues("\n", "\r\n")] string sourceNewLine, [CombinatorialValues("\n", "\r\n")] string configuredNewLine) - { - await TestInRegularAndScript1Async( + public Task TestAddUsingPreservesNewlines1(TestHost testHost, [CombinatorialValues("\n", "\r\n")] string sourceNewLine, [CombinatorialValues("\n", "\r\n")] string configuredNewLine) + => TestInRegularAndScript1Async( """ namespace ANamespace { @@ -6408,7 +6481,6 @@ class Class """.ReplaceLineEndings(sourceNewLine), index: 0, parameters: new TestParameters(options: Option(FormattingOptions2.NewLine, configuredNewLine), testHost: testHost)); - } /// /// Note that this test verifies the current end of line sequence in using directives is preserved regardless of @@ -6416,9 +6488,8 @@ class Class /// [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/62976")] - public async Task TestAddUsingPreservesNewlines2(TestHost testHost, [CombinatorialValues("\n", "\r\n")] string sourceNewLine, [CombinatorialValues("\n", "\r\n")] string configuredNewLine) - { - await TestInRegularAndScript1Async( + public Task TestAddUsingPreservesNewlines2(TestHost testHost, [CombinatorialValues("\n", "\r\n")] string sourceNewLine, [CombinatorialValues("\n", "\r\n")] string configuredNewLine) + => TestInRegularAndScript1Async( """ using BNamespace; @@ -6466,13 +6537,11 @@ class Class """.ReplaceLineEndings(sourceNewLine), index: 0, parameters: new TestParameters(options: Option(FormattingOptions2.NewLine, configuredNewLine), testHost: testHost)); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/62976")] - public async Task TestAddUsingPreservesNewlines3(TestHost testHost, [CombinatorialValues("\n", "\r\n")] string sourceNewLine, [CombinatorialValues("\n", "\r\n")] string configuredNewLine) - { - await TestInRegularAndScript1Async( + public Task TestAddUsingPreservesNewlines3(TestHost testHost, [CombinatorialValues("\n", "\r\n")] string sourceNewLine, [CombinatorialValues("\n", "\r\n")] string configuredNewLine) + => TestInRegularAndScript1Async( """ using ANamespace; @@ -6520,13 +6589,11 @@ class Class """.ReplaceLineEndings(sourceNewLine), index: 0, parameters: new TestParameters(options: Option(FormattingOptions2.NewLine, configuredNewLine), testHost: testHost)); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/24642")] - public async Task TestAddUsingWithMalformedGeneric(TestHost testHost) - { - await TestInRegularAndScript1Async( + public Task TestAddUsingWithMalformedGeneric(TestHost testHost) + => TestInRegularAndScript1Async( """ class Class { @@ -6543,12 +6610,10 @@ class Class """, index: 0, parameters: new TestParameters(testHost: testHost)); - } [Theory, CombinatorialData] - public async Task TestOutsideOfMethodWithMalformedGenericParameters(TestHost testHost) - { - await TestInRegularAndScript1Async( + public Task TestOutsideOfMethodWithMalformedGenericParameters(TestHost testHost) + => TestInRegularAndScript1Async( """ using System; @@ -6568,5 +6633,17 @@ class Program """, index: 0, parameters: new TestParameters(testHost: testHost)); - } + + [Theory, CombinatorialData] + [WorkItem("https://github.com/dotnet/roslyn/issues/72022")] + public Task TestAssemblyLevelAttribute(TestHost testHost) + => TestAsync( + """ + [assembly: [|NeutralResourcesLanguage|]("en")] + """, + """ + using System.Resources; + + [assembly: NeutralResourcesLanguage("en")] + """, testHost); } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingTestsWithAddImportDiagnosticProvider.cs b/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingTestsWithAddImportDiagnosticProvider.cs index 31522cad6d291..859fa77e0e082 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingTestsWithAddImportDiagnosticProvider.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingTestsWithAddImportDiagnosticProvider.cs @@ -29,177 +29,201 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider => (new CSharpUnboundIdentifiersDiagnosticAnalyzer(), new CSharpAddImportCodeFixProvider()); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829970")] - public async Task TestUnknownIdentifierGenericName() - { - await TestInRegularAndScriptAsync( -@"class C -{ - private [|List|] -}", -@"using System.Collections.Generic; - -class C -{ - private List -}"); - } + public Task TestUnknownIdentifierGenericName() + => TestInRegularAndScriptAsync( + """ + class C + { + private [|List|] + } + """, + """ + using System.Collections.Generic; + + class C + { + private List + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829970")] - public async Task TestUnknownIdentifierInAttributeSyntaxWithoutTarget() - { - await TestInRegularAndScriptAsync( -@"class C -{ - [[|Extension|]] -}", -@"using System.Runtime.CompilerServices; - -class C -{ - [Extension] -}"); - } + public Task TestUnknownIdentifierInAttributeSyntaxWithoutTarget() + => TestInRegularAndScriptAsync( + """ + class C + { + [[|Extension|]] + } + """, + """ + using System.Runtime.CompilerServices; + + class C + { + [Extension] + } + """); [Fact] - public async Task TestOutsideOfMethodWithMalformedGenericParameters() - { - await TestMissingInRegularAndScriptAsync( -@"using System; -class Program -{ - Func<[|FlowControl|] x }"); - } + public Task TestOutsideOfMethodWithMalformedGenericParameters() + => TestMissingInRegularAndScriptAsync( + """ + using System; + class Program + { + Func<[|FlowControl|] x } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/752640")] - public async Task TestUnknownIdentifierWithSyntaxError() - { - await TestInRegularAndScriptAsync( -@"class C -{ - [|Directory|] private int i; -}", -@"using System.IO; - -class C -{ - Directory private int i; -}"); - } + public Task TestUnknownIdentifierWithSyntaxError() + => TestInRegularAndScriptAsync( + """ + class C + { + [|Directory|] private int i; + } + """, + """ + using System.IO; + + class C + { + Directory private int i; + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/855748")] public async Task TestGenericNameWithBrackets() { await TestInRegularAndScriptAsync( -@"class Class -{ - [|List|] -}", -@"using System.Collections.Generic; - -class Class -{ - List -}"); + """ + class Class + { + [|List|] + } + """, + """ + using System.Collections.Generic; + + class Class + { + List + } + """); await TestInRegularAndScriptAsync( -@"class Class -{ - [|List<>|] -}", -@"using System.Collections.Generic; - -class Class -{ - List<> -}"); + """ + class Class + { + [|List<>|] + } + """, + """ + using System.Collections.Generic; + + class Class + { + List<> + } + """); await TestInRegularAndScriptAsync( -@"class Class -{ - List[|<>|] -}", -@"using System.Collections.Generic; - -class Class -{ - List<> -}"); + """ + class Class + { + List[|<>|] + } + """, + """ + using System.Collections.Generic; + + class Class + { + List<> + } + """); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/867496")] public async Task TestMalformedGenericParameters() { await TestInRegularAndScriptAsync( -@"class Class -{ - [|List<|] }", -@"using System.Collections.Generic; - -class Class -{ - List< }"); + """ + class Class + { + [|List<|] } + """, + """ + using System.Collections.Generic; + + class Class + { + List< } + """); await TestMissingInRegularAndScriptAsync( -@"class Class -{ - [|List> - } -}", -@" -using System.Collections.Generic; -using System.Threading.Tasks; -using X; - -namespace X -{ - class ProjectConfiguration - { - } -} - -namespace ConsoleApp282 -{ - class Program - { - public async Task> - } -}"); - } + public Task TestIncompleteMemberWithAsyncTaskReturnType() + => TestInRegularAndScriptAsync( + """ + using System.Collections.Generic; + using System.Threading.Tasks; + + namespace X + { + class ProjectConfiguration + { + } + } + + namespace ConsoleApp282 + { + class Program + { + public async Task> + } + } + """, + """ + using System.Collections.Generic; + using System.Threading.Tasks; + using X; + + namespace X + { + class ProjectConfiguration + { + } + } + + namespace ConsoleApp282 + { + class Program + { + public async Task> + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23667")] - public async Task TestMissingDiagnosticForNameOf() - { - await TestDiagnosticMissingAsync( -@"using System; - -class C -{ - Action action = () => { - var x = [|nameof|](System); -#warning xxx - }; -}"); - } + public Task TestMissingDiagnosticForNameOf() + => TestDiagnosticMissingAsync( + """ + using System; + + class C + { + Action action = () => { + var x = [|nameof|](System); + #warning xxx + }; + } + """); } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingTests_ExtensionMethods.cs b/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingTests_ExtensionMethods.cs index 3b8ad7ab68b2c..2c27f2d9e0ef1 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingTests_ExtensionMethods.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingTests_ExtensionMethods.cs @@ -14,1492 +14,1499 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddUsing; public sealed partial class AddUsingTests { [Fact] - public async Task TestWhereExtension() - { - await TestInRegularAndScriptAsync( -@"using System; -using System.Collections.Generic; - -class Program -{ - static void Main(string[] args) - { - var q = args.[|Where|] } -}", -@"using System; -using System.Collections.Generic; -using System.Linq; - -class Program -{ - static void Main(string[] args) - { - var q = args.Where } -}"); - } + public Task TestWhereExtension() + => TestInRegularAndScriptAsync( + """ + using System; + using System.Collections.Generic; + + class Program + { + static void Main(string[] args) + { + var q = args.[|Where|] } + } + """, + """ + using System; + using System.Collections.Generic; + using System.Linq; + + class Program + { + static void Main(string[] args) + { + var q = args.Where } + } + """); [Fact] - public async Task TestSelectExtension() - { - await TestInRegularAndScriptAsync( -@"using System; -using System.Collections.Generic; - -class Program -{ - static void Main(string[] args) - { - var q = args.[|Select|] } -}", -@"using System; -using System.Collections.Generic; -using System.Linq; - -class Program -{ - static void Main(string[] args) - { - var q = args.Select } -}"); - } + public Task TestSelectExtension() + => TestInRegularAndScriptAsync( + """ + using System; + using System.Collections.Generic; + + class Program + { + static void Main(string[] args) + { + var q = args.[|Select|] } + } + """, + """ + using System; + using System.Collections.Generic; + using System.Linq; + + class Program + { + static void Main(string[] args) + { + var q = args.Select } + } + """); [Fact] - public async Task TestGroupByExtension() - { - await TestInRegularAndScriptAsync( -@"using System; -using System.Collections.Generic; - -class Program -{ - static void Main(string[] args) - { - var q = args.[|GroupBy|] } -}", -@"using System; -using System.Collections.Generic; -using System.Linq; - -class Program -{ - static void Main(string[] args) - { - var q = args.GroupBy } -}"); - } + public Task TestGroupByExtension() + => TestInRegularAndScriptAsync( + """ + using System; + using System.Collections.Generic; + + class Program + { + static void Main(string[] args) + { + var q = args.[|GroupBy|] } + } + """, + """ + using System; + using System.Collections.Generic; + using System.Linq; + + class Program + { + static void Main(string[] args) + { + var q = args.GroupBy } + } + """); [Fact] - public async Task TestJoinExtension() - { - await TestInRegularAndScriptAsync( -@"using System; -using System.Collections.Generic; - -class Program -{ - static void Main(string[] args) - { - var q = args.[|Join|] } -}", -@"using System; -using System.Collections.Generic; -using System.Linq; - -class Program -{ - static void Main(string[] args) - { - var q = args.Join } -}"); - } + public Task TestJoinExtension() + => TestInRegularAndScriptAsync( + """ + using System; + using System.Collections.Generic; + + class Program + { + static void Main(string[] args) + { + var q = args.[|Join|] } + } + """, + """ + using System; + using System.Collections.Generic; + using System.Linq; + + class Program + { + static void Main(string[] args) + { + var q = args.Join } + } + """); [Fact] - public async Task RegressionFor8455() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M() - { - int dim = (int)Math.[|Min|](); - } -}"); - } + public Task RegressionFor8455() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M() + { + int dim = (int)Math.[|Min|](); + } + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/772321")] - public async Task TestExtensionWithThePresenceOfTheSameNameNonExtensionMethod() - { - await TestInRegularAndScriptAsync( -@"namespace NS1 -{ - class Program - { - void Main() - { - [|new C().Goo(4);|] - } - } - - class C - { - public void Goo(string y) - { - } - } -} - -namespace NS2 -{ - static class CExt - { - public static void Goo(this NS1.C c, int x) - { - } - } -}", -@"using NS2; - -namespace NS1 -{ - class Program - { - void Main() - { - new C().Goo(4); - } - } - - class C - { - public void Goo(string y) - { - } - } -} - -namespace NS2 -{ - static class CExt - { - public static void Goo(this NS1.C c, int x) - { - } - } -}"); - } + public Task TestExtensionWithThePresenceOfTheSameNameNonExtensionMethod() + => TestInRegularAndScriptAsync( + """ + namespace NS1 + { + class Program + { + void Main() + { + [|new C().Goo(4);|] + } + } + + class C + { + public void Goo(string y) + { + } + } + } + + namespace NS2 + { + static class CExt + { + public static void Goo(this NS1.C c, int x) + { + } + } + } + """, + """ + using NS2; + + namespace NS1 + { + class Program + { + void Main() + { + new C().Goo(4); + } + } + + class C + { + public void Goo(string y) + { + } + } + } + + namespace NS2 + { + static class CExt + { + public static void Goo(this NS1.C c, int x) + { + } + } + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/920398")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/772321")] - public async Task TestExtensionWithThePresenceOfTheSameNameNonExtensionPrivateMethod() - { - await TestInRegularAndScriptAsync( -@"namespace NS1 -{ - class Program - { - void Main() - { - [|new C().Goo(4);|] - } - } - - class C - { - private void Goo(int x) - { - } - } -} - -namespace NS2 -{ - static class CExt - { - public static void Goo(this NS1.C c, int x) - { - } - } -}", -@"using NS2; - -namespace NS1 -{ - class Program - { - void Main() - { - new C().Goo(4); - } - } - - class C - { - private void Goo(int x) - { - } - } -} - -namespace NS2 -{ - static class CExt - { - public static void Goo(this NS1.C c, int x) - { - } - } -}"); - } + public Task TestExtensionWithThePresenceOfTheSameNameNonExtensionPrivateMethod() + => TestInRegularAndScriptAsync( + """ + namespace NS1 + { + class Program + { + void Main() + { + [|new C().Goo(4);|] + } + } + + class C + { + private void Goo(int x) + { + } + } + } + + namespace NS2 + { + static class CExt + { + public static void Goo(this NS1.C c, int x) + { + } + } + } + """, + """ + using NS2; + + namespace NS1 + { + class Program + { + void Main() + { + new C().Goo(4); + } + } + + class C + { + private void Goo(int x) + { + } + } + } + + namespace NS2 + { + static class CExt + { + public static void Goo(this NS1.C c, int x) + { + } + } + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/920398")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/772321")] - public async Task TestExtensionWithThePresenceOfTheSameNameExtensionPrivateMethod() - { - await TestInRegularAndScriptAsync( -@"using NS2; - -namespace NS1 -{ - class Program - { - void Main() - { - [|new C().Goo(4);|] - } - } - - class C - { - } -} - -namespace NS2 -{ - static class CExt - { - private static void Goo(this NS1.C c, int x) - { - } - } -} - -namespace NS3 -{ - static class CExt - { - public static void Goo(this NS1.C c, int x) - { - } - } -}", -@"using NS2; -using NS3; - -namespace NS1 -{ - class Program - { - void Main() - { - new C().Goo(4); - } - } - - class C - { - } -} - -namespace NS2 -{ - static class CExt - { - private static void Goo(this NS1.C c, int x) - { - } - } -} - -namespace NS3 -{ - static class CExt - { - public static void Goo(this NS1.C c, int x) - { - } - } -}"); - } + public Task TestExtensionWithThePresenceOfTheSameNameExtensionPrivateMethod() + => TestInRegularAndScriptAsync( + """ + using NS2; + + namespace NS1 + { + class Program + { + void Main() + { + [|new C().Goo(4);|] + } + } + + class C + { + } + } + + namespace NS2 + { + static class CExt + { + private static void Goo(this NS1.C c, int x) + { + } + } + } + + namespace NS3 + { + static class CExt + { + public static void Goo(this NS1.C c, int x) + { + } + } + } + """, + """ + using NS2; + using NS3; + + namespace NS1 + { + class Program + { + void Main() + { + new C().Goo(4); + } + } + + class C + { + } + } + + namespace NS2 + { + static class CExt + { + private static void Goo(this NS1.C c, int x) + { + } + } + } + + namespace NS3 + { + static class CExt + { + public static void Goo(this NS1.C c, int x) + { + } + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/269")] - public async Task TestAddUsingForAddExtensionMethod() - { - await TestAsync( -@"using System; -using System.Collections; - -class X : IEnumerable -{ - public IEnumerator GetEnumerator() - { - new X { [|1|] }; - return null; - } -} - -namespace Ext -{ - static class Extensions - { - public static void Add(this X x, int i) - { - } - } -}", -@"using System; -using System.Collections; -using Ext; - -class X : IEnumerable -{ - public IEnumerator GetEnumerator() - { - new X { 1 }; - return null; - } -} - -namespace Ext -{ - static class Extensions - { - public static void Add(this X x, int i) - { - } - } -}", + public Task TestAddUsingForAddExtensionMethod() + => TestAsync( + """ + using System; + using System.Collections; + + class X : IEnumerable + { + public IEnumerator GetEnumerator() + { + new X { [|1|] }; + return null; + } + } + + namespace Ext + { + static class Extensions + { + public static void Add(this X x, int i) + { + } + } + } + """, + """ + using System; + using System.Collections; + using Ext; + + class X : IEnumerable + { + public IEnumerator GetEnumerator() + { + new X { 1 }; + return null; + } + } + + namespace Ext + { + static class Extensions + { + public static void Add(this X x, int i) + { + } + } + } + """, parseOptions: null); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/269")] - public async Task TestAddUsingForAddExtensionMethod2() - { - await TestAsync( -@"using System; -using System.Collections; - -class X : IEnumerable -{ - public IEnumerator GetEnumerator() - { - new X { 1, 2, [|3|] }; - return null; - } -} - -namespace Ext -{ - static class Extensions - { - public static void Add(this X x, int i) - { - } - } -}", -@"using System; -using System.Collections; -using Ext; - -class X : IEnumerable -{ - public IEnumerator GetEnumerator() - { - new X { 1, 2, 3 }; - return null; - } -} - -namespace Ext -{ - static class Extensions - { - public static void Add(this X x, int i) - { - } - } -}", + public Task TestAddUsingForAddExtensionMethod2() + => TestAsync( + """ + using System; + using System.Collections; + + class X : IEnumerable + { + public IEnumerator GetEnumerator() + { + new X { 1, 2, [|3|] }; + return null; + } + } + + namespace Ext + { + static class Extensions + { + public static void Add(this X x, int i) + { + } + } + } + """, + """ + using System; + using System.Collections; + using Ext; + + class X : IEnumerable + { + public IEnumerator GetEnumerator() + { + new X { 1, 2, 3 }; + return null; + } + } + + namespace Ext + { + static class Extensions + { + public static void Add(this X x, int i) + { + } + } + } + """, parseOptions: null); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/269")] - public async Task TestAddUsingForAddExtensionMethod3() - { - await TestAsync( -@"using System; -using System.Collections; - -class X : IEnumerable -{ - public IEnumerator GetEnumerator() - { - new X { 1, [|2|], 3 }; - return null; - } -} - -namespace Ext -{ - static class Extensions - { - public static void Add(this X x, int i) - { - } - } -}", -@"using System; -using System.Collections; -using Ext; - -class X : IEnumerable -{ - public IEnumerator GetEnumerator() - { - new X { 1, 2, 3 }; - return null; - } -} - -namespace Ext -{ - static class Extensions - { - public static void Add(this X x, int i) - { - } - } -}", + public Task TestAddUsingForAddExtensionMethod3() + => TestAsync( + """ + using System; + using System.Collections; + + class X : IEnumerable + { + public IEnumerator GetEnumerator() + { + new X { 1, [|2|], 3 }; + return null; + } + } + + namespace Ext + { + static class Extensions + { + public static void Add(this X x, int i) + { + } + } + } + """, + """ + using System; + using System.Collections; + using Ext; + + class X : IEnumerable + { + public IEnumerator GetEnumerator() + { + new X { 1, 2, 3 }; + return null; + } + } + + namespace Ext + { + static class Extensions + { + public static void Add(this X x, int i) + { + } + } + } + """, parseOptions: null); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/269")] - public async Task TestAddUsingForAddExtensionMethod4() - { - await TestAsync( -@"using System; -using System.Collections; - -class X : IEnumerable -{ - public IEnumerator GetEnumerator() - { - new X { { 1, 2, 3 }, [|{ 4, 5, 6 }|], { 7, 8, 9 } }; - return null; - } -} - -namespace Ext -{ - static class Extensions - { - public static void Add(this X x, int i) - { - } - } -}", -@"using System; -using System.Collections; -using Ext; - -class X : IEnumerable -{ - public IEnumerator GetEnumerator() - { - new X { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; - return null; - } -} - -namespace Ext -{ - static class Extensions - { - public static void Add(this X x, int i) - { - } - } -}", + public Task TestAddUsingForAddExtensionMethod4() + => TestAsync( + """ + using System; + using System.Collections; + + class X : IEnumerable + { + public IEnumerator GetEnumerator() + { + new X { { 1, 2, 3 }, [|{ 4, 5, 6 }|], { 7, 8, 9 } }; + return null; + } + } + + namespace Ext + { + static class Extensions + { + public static void Add(this X x, int i) + { + } + } + } + """, + """ + using System; + using System.Collections; + using Ext; + + class X : IEnumerable + { + public IEnumerator GetEnumerator() + { + new X { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; + return null; + } + } + + namespace Ext + { + static class Extensions + { + public static void Add(this X x, int i) + { + } + } + } + """, parseOptions: null); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/269")] - public async Task TestAddUsingForAddExtensionMethod5() - { - await TestAsync( -@"using System; -using System.Collections; - -class X : IEnumerable -{ - public IEnumerator GetEnumerator() - { - new X { { 1, 2, 3 }, { 4, 5, 6 }, [|{ 7, 8, 9 }|] }; - return null; - } -} - -namespace Ext -{ - static class Extensions - { - public static void Add(this X x, int i) - { - } - } -}", -@"using System; -using System.Collections; -using Ext; - -class X : IEnumerable -{ - public IEnumerator GetEnumerator() - { - new X { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; - return null; - } -} - -namespace Ext -{ - static class Extensions - { - public static void Add(this X x, int i) - { - } - } -}", + public Task TestAddUsingForAddExtensionMethod5() + => TestAsync( + """ + using System; + using System.Collections; + + class X : IEnumerable + { + public IEnumerator GetEnumerator() + { + new X { { 1, 2, 3 }, { 4, 5, 6 }, [|{ 7, 8, 9 }|] }; + return null; + } + } + + namespace Ext + { + static class Extensions + { + public static void Add(this X x, int i) + { + } + } + } + """, + """ + using System; + using System.Collections; + using Ext; + + class X : IEnumerable + { + public IEnumerator GetEnumerator() + { + new X { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; + return null; + } + } + + namespace Ext + { + static class Extensions + { + public static void Add(this X x, int i) + { + } + } + } + """, parseOptions: null); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/269")] - public async Task TestAddUsingForAddExtensionMethod6() - { - await TestAsync( -@"using System; -using System.Collections; - -class X : IEnumerable -{ - public IEnumerator GetEnumerator() - { - new X { { 1, 2, 3 }, { ""Four"", ""Five"", ""Six"" }, [|{ '7', '8', '9' }|] }; - return null; - } -} - -namespace Ext -{ - static class Extensions - { - public static void Add(this X x, int i) - { - } - } -}", -@"using System; -using System.Collections; -using Ext; - -class X : IEnumerable -{ - public IEnumerator GetEnumerator() - { - new X { { 1, 2, 3 }, { ""Four"", ""Five"", ""Six"" }, { '7', '8', '9' } }; - return null; - } -} - -namespace Ext -{ - static class Extensions - { - public static void Add(this X x, int i) - { - } - } -}", + public Task TestAddUsingForAddExtensionMethod6() + => TestAsync( + """ + using System; + using System.Collections; + + class X : IEnumerable + { + public IEnumerator GetEnumerator() + { + new X { { 1, 2, 3 }, { "Four", "Five", "Six" }, [|{ '7', '8', '9' }|] }; + return null; + } + } + + namespace Ext + { + static class Extensions + { + public static void Add(this X x, int i) + { + } + } + } + """, + """ + using System; + using System.Collections; + using Ext; + + class X : IEnumerable + { + public IEnumerator GetEnumerator() + { + new X { { 1, 2, 3 }, { "Four", "Five", "Six" }, { '7', '8', '9' } }; + return null; + } + } + + namespace Ext + { + static class Extensions + { + public static void Add(this X x, int i) + { + } + } + } + """, parseOptions: null); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/269")] - public async Task TestAddUsingForAddExtensionMethod7() - { - await TestAsync( -@"using System; -using System.Collections; - -class X : IEnumerable -{ - public IEnumerator GetEnumerator() - { - new X { { 1, 2, 3 }, [|{ ""Four"", ""Five"", ""Six"" }|], { '7', '8', '9' } }; - return null; - } -} - -namespace Ext -{ - static class Extensions - { - public static void Add(this X x, int i) - { - } - } -}", -@"using System; -using System.Collections; -using Ext; - -class X : IEnumerable -{ - public IEnumerator GetEnumerator() - { - new X { { 1, 2, 3 }, { ""Four"", ""Five"", ""Six"" }, { '7', '8', '9' } }; - return null; - } -} - -namespace Ext -{ - static class Extensions - { - public static void Add(this X x, int i) - { - } - } -}", + public Task TestAddUsingForAddExtensionMethod7() + => TestAsync( + """ + using System; + using System.Collections; + + class X : IEnumerable + { + public IEnumerator GetEnumerator() + { + new X { { 1, 2, 3 }, [|{ "Four", "Five", "Six" }|], { '7', '8', '9' } }; + return null; + } + } + + namespace Ext + { + static class Extensions + { + public static void Add(this X x, int i) + { + } + } + } + """, + """ + using System; + using System.Collections; + using Ext; + + class X : IEnumerable + { + public IEnumerator GetEnumerator() + { + new X { { 1, 2, 3 }, { "Four", "Five", "Six" }, { '7', '8', '9' } }; + return null; + } + } + + namespace Ext + { + static class Extensions + { + public static void Add(this X x, int i) + { + } + } + } + """, parseOptions: null); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/269")] - public async Task TestAddUsingForAddExtensionMethod8() - { - await TestAsync( -@"using System; -using System.Collections; - -class X : IEnumerable -{ - public IEnumerator GetEnumerator() - { - new X { [|{ 1, 2, 3 }|] }; - return null; - } -} - -namespace Ext -{ - static class Extensions - { - public static void Add(this X x, int i) - { - } - } -}", -@"using System; -using System.Collections; -using Ext; - -class X : IEnumerable -{ - public IEnumerator GetEnumerator() - { - new X { { 1, 2, 3 } }; - return null; - } -} - -namespace Ext -{ - static class Extensions - { - public static void Add(this X x, int i) - { - } - } -}", + public Task TestAddUsingForAddExtensionMethod8() + => TestAsync( + """ + using System; + using System.Collections; + + class X : IEnumerable + { + public IEnumerator GetEnumerator() + { + new X { [|{ 1, 2, 3 }|] }; + return null; + } + } + + namespace Ext + { + static class Extensions + { + public static void Add(this X x, int i) + { + } + } + } + """, + """ + using System; + using System.Collections; + using Ext; + + class X : IEnumerable + { + public IEnumerator GetEnumerator() + { + new X { { 1, 2, 3 } }; + return null; + } + } + + namespace Ext + { + static class Extensions + { + public static void Add(this X x, int i) + { + } + } + } + """, parseOptions: null); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/269")] - public async Task TestAddUsingForAddExtensionMethod9() - { - await TestAsync( -@"using System; -using System.Collections; - -class X : IEnumerable -{ - public IEnumerator GetEnumerator() - { - new X { [|""This""|] }; - return null; - } -} - -namespace Ext -{ - static class Extensions - { - public static void Add(this X x, int i) - { - } - } -}", -@"using System; -using System.Collections; -using Ext; - -class X : IEnumerable -{ - public IEnumerator GetEnumerator() - { - new X { ""This"" }; - return null; - } -} - -namespace Ext -{ - static class Extensions - { - public static void Add(this X x, int i) - { - } - } -}", + public Task TestAddUsingForAddExtensionMethod9() + => TestAsync( + """ + using System; + using System.Collections; + + class X : IEnumerable + { + public IEnumerator GetEnumerator() + { + new X { [|"This"|] }; + return null; + } + } + + namespace Ext + { + static class Extensions + { + public static void Add(this X x, int i) + { + } + } + } + """, + """ + using System; + using System.Collections; + using Ext; + + class X : IEnumerable + { + public IEnumerator GetEnumerator() + { + new X { "This" }; + return null; + } + } + + namespace Ext + { + static class Extensions + { + public static void Add(this X x, int i) + { + } + } + } + """, parseOptions: null); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/269")] - public async Task TestAddUsingForAddExtensionMethod10() - { - await TestAsync( -@"using System; -using System.Collections; - -class X : IEnumerable -{ - public IEnumerator GetEnumerator() - { - new X { [|{ 1, 2, 3 }|], { ""Four"", ""Five"", ""Six"" }, { '7', '8', '9' } }; - return null; - } -} - -namespace Ext -{ - static class Extensions - { - public static void Add(this X x, int i) - { - } - } -} - -namespace Ext2 -{ - static class Extensions - { - public static void Add(this X x, object[] i) - { - } - } -}", -@"using System; -using System.Collections; -using Ext; - -class X : IEnumerable -{ - public IEnumerator GetEnumerator() - { - new X { { 1, 2, 3 }, { ""Four"", ""Five"", ""Six"" }, { '7', '8', '9' } }; - return null; - } -} - -namespace Ext -{ - static class Extensions - { - public static void Add(this X x, int i) - { - } - } -} - -namespace Ext2 -{ - static class Extensions - { - public static void Add(this X x, object[] i) - { - } - } -}", + public Task TestAddUsingForAddExtensionMethod10() + => TestAsync( + """ + using System; + using System.Collections; + + class X : IEnumerable + { + public IEnumerator GetEnumerator() + { + new X { [|{ 1, 2, 3 }|], { "Four", "Five", "Six" }, { '7', '8', '9' } }; + return null; + } + } + + namespace Ext + { + static class Extensions + { + public static void Add(this X x, int i) + { + } + } + } + + namespace Ext2 + { + static class Extensions + { + public static void Add(this X x, object[] i) + { + } + } + } + """, + """ + using System; + using System.Collections; + using Ext; + + class X : IEnumerable + { + public IEnumerator GetEnumerator() + { + new X { { 1, 2, 3 }, { "Four", "Five", "Six" }, { '7', '8', '9' } }; + return null; + } + } + + namespace Ext + { + static class Extensions + { + public static void Add(this X x, int i) + { + } + } + } + + namespace Ext2 + { + static class Extensions + { + public static void Add(this X x, object[] i) + { + } + } + } + """, parseOptions: null); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/269")] - public async Task TestAddUsingForAddExtensionMethod11() - { - await TestAsync( -@"using System; -using System.Collections; - -class X : IEnumerable -{ - public IEnumerator GetEnumerator() - { - new X { [|{ 1, 2, 3 }|], { ""Four"", ""Five"", ""Six"" }, { '7', '8', '9' } }; - return null; - } -} - -namespace Ext -{ - static class Extensions - { - public static void Add(this X x, int i) - { - } - } -} - -namespace Ext2 -{ - static class Extensions - { - public static void Add(this X x, object[] i) - { - } - } -}", -@"using System; -using System.Collections; -using Ext2; - -class X : IEnumerable -{ - public IEnumerator GetEnumerator() - { - new X { { 1, 2, 3 }, { ""Four"", ""Five"", ""Six"" }, { '7', '8', '9' } }; - return null; - } -} - -namespace Ext -{ - static class Extensions - { - public static void Add(this X x, int i) - { - } - } -} - -namespace Ext2 -{ - static class Extensions - { - public static void Add(this X x, object[] i) - { - } - } -}", + public Task TestAddUsingForAddExtensionMethod11() + => TestAsync( + """ + using System; + using System.Collections; + + class X : IEnumerable + { + public IEnumerator GetEnumerator() + { + new X { [|{ 1, 2, 3 }|], { "Four", "Five", "Six" }, { '7', '8', '9' } }; + return null; + } + } + + namespace Ext + { + static class Extensions + { + public static void Add(this X x, int i) + { + } + } + } + + namespace Ext2 + { + static class Extensions + { + public static void Add(this X x, object[] i) + { + } + } + } + """, + """ + using System; + using System.Collections; + using Ext2; + + class X : IEnumerable + { + public IEnumerator GetEnumerator() + { + new X { { 1, 2, 3 }, { "Four", "Five", "Six" }, { '7', '8', '9' } }; + return null; + } + } + + namespace Ext + { + static class Extensions + { + public static void Add(this X x, int i) + { + } + } + } + + namespace Ext2 + { + static class Extensions + { + public static void Add(this X x, object[] i) + { + } + } + } + """, index: 1, parseOptions: null); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/3818")] - public async Task InExtensionMethodUnderConditionalAccessExpression() - { - var initialText = -@" - - -namespace Sample -{ - class Program - { - static void Main(string[] args) - { - string myString = ""Sample""; - var other = myString?[|.StringExtension()|].Substring(0); - } - } -} - - -namespace Sample.Extensions -{ - public static class StringExtensions - { - public static string StringExtension(this string s) - { - return ""Ok""; - } - } -} - - -"; - - var expectedText = -@" -using Sample.Extensions; - -namespace Sample -{ - class Program - { - static void Main(string[] args) - { - string myString = ""Sample""; - var other = myString?.StringExtension().Substring(0); - } - } -} - "; - await TestInRegularAndScriptAsync(initialText, expectedText); - } + public Task InExtensionMethodUnderConditionalAccessExpression() + => TestInRegularAndScriptAsync(""" + + + namespace Sample + { + class Program + { + static void Main(string[] args) + { + string myString = "Sample"; + var other = myString?[|.StringExtension()|].Substring(0); + } + } + } + namespace Sample.Extensions + { + public static class StringExtensions + { + public static string StringExtension(this string s) + { + return "Ok"; + } + } + } + + + """, """ + using Sample.Extensions; + + namespace Sample + { + class Program + { + static void Main(string[] args) + { + string myString = "Sample"; + var other = myString?.StringExtension().Substring(0); + } + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/3818")] - public async Task InExtensionMethodUnderMultipleConditionalAccessExpressions() - { - var initialText = -@" - - -public class C -{ - public T F<T>(T x) - { - return F(new C())?.F(new C())?[|.Extn()|]; - } -} - - -namespace Sample.Extensions -{ - public static class Extensions - { - public static C Extn(this C obj) - { - return obj.F(new C()); - } - } -} - - -"; - - var expectedText = -@" -using Sample.Extensions; - -public class C -{ - public T F(T x) - { - return F(new C())?.F(new C())?.Extn(); - } -} - "; - await TestInRegularAndScriptAsync(initialText, expectedText); - } + public Task InExtensionMethodUnderMultipleConditionalAccessExpressions() + => TestInRegularAndScriptAsync(""" + + + public class C + { + public T F<T>(T x) + { + return F(new C())?.F(new C())?[|.Extn()|]; + } + } + namespace Sample.Extensions + { + public static class Extensions + { + public static C Extn(this C obj) + { + return obj.F(new C()); + } + } + } + + + """, """ + using Sample.Extensions; + + public class C + { + public T F(T x) + { + return F(new C())?.F(new C())?.Extn(); + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/3818")] - public async Task InExtensionMethodUnderMultipleConditionalAccessExpressions2() - { - var initialText = -@" - - -public class C -{ - public T F<T>(T x) - { - return F(new C())?.F(new C())[|.Extn()|]?.F(newC()); - } -} - - -namespace Sample.Extensions -{ - public static class Extensions - { - public static C Extn(this C obj) - { - return obj.F(new C()); - } - } -} - - -"; - - var expectedText = -@" -using Sample.Extensions; - -public class C -{ - public T F(T x) - { - return F(new C())?.F(new C()).Extn()?.F(newC()); - } -} - "; - await TestInRegularAndScriptAsync(initialText, expectedText); - } + public Task InExtensionMethodUnderMultipleConditionalAccessExpressions2() + => TestInRegularAndScriptAsync(""" + + + public class C + { + public T F<T>(T x) + { + return F(new C())?.F(new C())[|.Extn()|]?.F(newC()); + } + } + namespace Sample.Extensions + { + public static class Extensions + { + public static C Extn(this C obj) + { + return obj.F(new C()); + } + } + } + + + """, """ + using Sample.Extensions; + + public class C + { + public T F(T x) + { + return F(new C())?.F(new C()).Extn()?.F(newC()); + } + } + """); [Fact] - public async Task TestDeconstructExtension() - { - await TestAsync( -@" -class Program -{ - void M(Program p) - { - var (x, y) = [|p|]; - } -} - -namespace N -{ - static class E - { - public static void Deconstruct(this Program p, out int x, out int y) { } - } -}", -@" -using N; - -class Program -{ - void M(Program p) - { - var (x, y) = [|p|]; - } -} - -namespace N -{ - static class E - { - public static void Deconstruct(this Program p, out int x, out int y) { } - } -}", + public Task TestDeconstructExtension() + => TestAsync( + """ + class Program + { + void M(Program p) + { + var (x, y) = [|p|]; + } + } + + namespace N + { + static class E + { + public static void Deconstruct(this Program p, out int x, out int y) { } + } + } + """, + """ + using N; + + class Program + { + void M(Program p) + { + var (x, y) = [|p|]; + } + } + + namespace N + { + static class E + { + public static void Deconstruct(this Program p, out int x, out int y) { } + } + } + """, parseOptions: null); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/16547")] - public async Task TestAddUsingForAddExtensionMethodWithSameNameAsProperty(TestHost testHost) - { - await TestAsync( -@" -namespace A -{ - public class Foo - { - public void Bar() - { - var self = this.[|Self()|]; - } - - public Foo Self - { - get { return this; } - } - } -} - -namespace A.Extensions -{ - public static class FooExtensions - { - public static Foo Self(this Foo foo) - { - return foo; - } - } -}", -@" -using A.Extensions; - -namespace A -{ - public class Foo - { - public void Bar() - { - var self = this.Self(); - } - - public Foo Self - { - get { return this; } - } - } -} - -namespace A.Extensions -{ - public static class FooExtensions - { - public static Foo Self(this Foo foo) - { - return foo; - } - } -}", testHost); - } + public Task TestAddUsingForAddExtensionMethodWithSameNameAsProperty(TestHost testHost) + => TestAsync( + """ + namespace A + { + public class Foo + { + public void Bar() + { + var self = this.[|Self()|]; + } + + public Foo Self + { + get { return this; } + } + } + } + + namespace A.Extensions + { + public static class FooExtensions + { + public static Foo Self(this Foo foo) + { + return foo; + } + } + } + """, + """ + using A.Extensions; + + namespace A + { + public class Foo + { + public void Bar() + { + var self = this.Self(); + } + + public Foo Self + { + get { return this; } + } + } + } + + namespace A.Extensions + { + public static class FooExtensions + { + public static Foo Self(this Foo foo) + { + return foo; + } + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/39155")] - public async Task TestExtensionGetAwaiterOverload(TestHost testHost) - { - await TestAsync( -@" -using System; -using System.Runtime.CompilerServices; - -namespace A -{ - public class Foo - { - async void M(Foo foo) - { - [|await foo|]; - } - } - - public static class BarExtensions - { - public static Extension.FooAwaiter GetAwaiter(this string s) => default; - } -} - -namespace A.Extension -{ - public static class FooExtensions - { - public static FooAwaiter GetAwaiter(this Foo foo) => default; - } - - public struct FooAwaiter : INotifyCompletion - { - public bool IsCompleted { get; } - - public void OnCompleted(Action continuation) - { - } - - public void GetResult() - { - } - } -} -", -@" -using System; -using System.Runtime.CompilerServices; -using A.Extension; - -namespace A -{ - public class Foo - { - async void M(Foo foo) - { - await foo; - } - } - - public static class BarExtensions - { - public static Extension.FooAwaiter GetAwaiter(this string s) => default; - } -} - -namespace A.Extension -{ - public static class FooExtensions - { - public static FooAwaiter GetAwaiter(this Foo foo) => default; - } - - public struct FooAwaiter : INotifyCompletion - { - public bool IsCompleted { get; } - - public void OnCompleted(Action continuation) - { - } - - public void GetResult() - { - } - } -} -", testHost); - } + public Task TestExtensionGetAwaiterOverload(TestHost testHost) + => TestAsync( + """ + using System; + using System.Runtime.CompilerServices; + + namespace A + { + public class Foo + { + async void M(Foo foo) + { + [|await foo|]; + } + } + + public static class BarExtensions + { + public static Extension.FooAwaiter GetAwaiter(this string s) => default; + } + } + + namespace A.Extension + { + public static class FooExtensions + { + public static FooAwaiter GetAwaiter(this Foo foo) => default; + } + + public struct FooAwaiter : INotifyCompletion + { + public bool IsCompleted { get; } + + public void OnCompleted(Action continuation) + { + } + + public void GetResult() + { + } + } + } + """, + """ + using System; + using System.Runtime.CompilerServices; + using A.Extension; + + namespace A + { + public class Foo + { + async void M(Foo foo) + { + await foo; + } + } + + public static class BarExtensions + { + public static Extension.FooAwaiter GetAwaiter(this string s) => default; + } + } + + namespace A.Extension + { + public static class FooExtensions + { + public static FooAwaiter GetAwaiter(this Foo foo) => default; + } + + public struct FooAwaiter : INotifyCompletion + { + public bool IsCompleted { get; } + + public void OnCompleted(Action continuation) + { + } + + public void GetResult() + { + } + } + } + """, testHost); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/39155")] - public async Task TestExtensionSelectOverload(TestHost testHost) - { - await TestAsync( -@" -using System; -using System.Collections.Generic; - -namespace A -{ - public class Foo - { - void M(Foo foo) - { - _ = [|from x in foo|] select x; - } - } - - public static class BarExtensions - { - public static IEnumerable Select(this string foo, Func f) => null; - } -} - -namespace A.Extension -{ - public static class FooExtensions - { - public static IEnumerable Select(this Foo foo, Func f) => null; - } -} -", -@" -using System; -using System.Collections.Generic; -using A.Extension; - -namespace A -{ - public class Foo - { - void M(Foo foo) - { - _ = from x in foo select x; - } - } - - public static class BarExtensions - { - public static IEnumerable Select(this string foo, Func f) => null; - } -} - -namespace A.Extension -{ - public static class FooExtensions - { - public static IEnumerable Select(this Foo foo, Func f) => null; - } -} -", testHost); - } + public Task TestExtensionSelectOverload(TestHost testHost) + => TestAsync( + """ + using System; + using System.Collections.Generic; + + namespace A + { + public class Foo + { + void M(Foo foo) + { + _ = [|from x in foo|] select x; + } + } + + public static class BarExtensions + { + public static IEnumerable Select(this string foo, Func f) => null; + } + } + + namespace A.Extension + { + public static class FooExtensions + { + public static IEnumerable Select(this Foo foo, Func f) => null; + } + } + """, + """ + using System; + using System.Collections.Generic; + using A.Extension; + + namespace A + { + public class Foo + { + void M(Foo foo) + { + _ = from x in foo select x; + } + } + + public static class BarExtensions + { + public static IEnumerable Select(this string foo, Func f) => null; + } + } + + namespace A.Extension + { + public static class FooExtensions + { + public static IEnumerable Select(this Foo foo, Func f) => null; + } + } + """, testHost); [Fact] - public async Task TestExtensionDeconstructOverload() - { - await TestAsync( -@" -using System; -using System.Collections.Generic; - -namespace A -{ - public class Foo - { - void M(Foo foo) - { - var (x, y) = [|foo|]; - } - } - - public static class BarExtensions - { - public static void Deconstruct(this string foo, out int a, out int b) => throw null; - } -} - -namespace A.Extension -{ - public static class FooExtensions - { - public static void Deconstruct(this Foo foo, out int a, out int b) => throw null; - } -} -", -@" -using System; -using System.Collections.Generic; -using A.Extension; - -namespace A -{ - public class Foo - { - void M(Foo foo) - { - var (x, y) = foo; - } - } - - public static class BarExtensions - { - public static void Deconstruct(this string foo, out int a, out int b) => throw null; - } -} - -namespace A.Extension -{ - public static class FooExtensions - { - public static void Deconstruct(this Foo foo, out int a, out int b) => throw null; - } -} -", + public Task TestExtensionDeconstructOverload() + => TestAsync( + """ + using System; + using System.Collections.Generic; + + namespace A + { + public class Foo + { + void M(Foo foo) + { + var (x, y) = [|foo|]; + } + } + + public static class BarExtensions + { + public static void Deconstruct(this string foo, out int a, out int b) => throw null; + } + } + + namespace A.Extension + { + public static class FooExtensions + { + public static void Deconstruct(this Foo foo, out int a, out int b) => throw null; + } + } + """, + """ + using System; + using System.Collections.Generic; + using A.Extension; + + namespace A + { + public class Foo + { + void M(Foo foo) + { + var (x, y) = foo; + } + } + + public static class BarExtensions + { + public static void Deconstruct(this string foo, out int a, out int b) => throw null; + } + } + + namespace A.Extension + { + public static class FooExtensions + { + public static void Deconstruct(this Foo foo, out int a, out int b) => throw null; + } + } + """, parseOptions: null); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/55117")] - public async Task TestMethodConflictWithGenericExtension() - { - await TestInRegularAndScriptAsync( -@"namespace A -{ - public abstract class Goo - { - public abstract object Bar( Type type ); - } - - public class Test - { - public void TestMethod(Goo arg) - { - arg.[|Bar()|]; - - } - } -} - -namespace A.Extensions -{ - public static class Extension - { - public static T Bar( this Goo @this ) - => (T)@this.Bar( typeof( T ) ); - } -}", -@"using A.Extensions; - -namespace A -{ - public abstract class Goo - { - public abstract object Bar( Type type ); - } - - public class Test - { - public void TestMethod(Goo arg) - { - arg.Bar(); - - } - } -} - -namespace A.Extensions -{ - public static class Extension - { - public static T Bar( this Goo @this ) - => (T)@this.Bar( typeof( T ) ); - } -}"); - } + public Task TestMethodConflictWithGenericExtension() + => TestInRegularAndScriptAsync( + """ + namespace A + { + public abstract class Goo + { + public abstract object Bar( Type type ); + } + + public class Test + { + public void TestMethod(Goo arg) + { + arg.[|Bar()|]; + + } + } + } + + namespace A.Extensions + { + public static class Extension + { + public static T Bar( this Goo @this ) + => (T)@this.Bar( typeof( T ) ); + } + } + """, + """ + using A.Extensions; + + namespace A + { + public abstract class Goo + { + public abstract object Bar( Type type ); + } + + public class Test + { + public void TestMethod(Goo arg) + { + arg.Bar(); + + } + } + } + + namespace A.Extensions + { + public static class Extension + { + public static T Bar( this Goo @this ) + => (T)@this.Bar( typeof( T ) ); + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/55117")] - public async Task TestMethodConflictWithConditionalGenericExtension() - { - await TestInRegularAndScriptAsync( -@"namespace A -{ - public abstract class Goo - { - public abstract object Bar( Type type ); - } - - public class Test - { - public void TestMethod(Goo arg) - { - arg?.[|Bar()|]; - - } - } -} - -namespace A.Extensions -{ - public static class Extension - { - public static T Bar( this Goo @this ) - => (T)@this.Bar( typeof( T ) ); - } -}", -@"using A.Extensions; - -namespace A -{ - public abstract class Goo - { - public abstract object Bar( Type type ); - } - - public class Test - { - public void TestMethod(Goo arg) - { - arg?.Bar(); - - } - } -} - -namespace A.Extensions -{ - public static class Extension - { - public static T Bar( this Goo @this ) - => (T)@this.Bar( typeof( T ) ); - } -}"); - } + public Task TestMethodConflictWithConditionalGenericExtension() + => TestInRegularAndScriptAsync( + """ + namespace A + { + public abstract class Goo + { + public abstract object Bar( Type type ); + } + + public class Test + { + public void TestMethod(Goo arg) + { + arg?.[|Bar()|]; + + } + } + } + + namespace A.Extensions + { + public static class Extension + { + public static T Bar( this Goo @this ) + => (T)@this.Bar( typeof( T ) ); + } + } + """, + """ + using A.Extensions; + + namespace A + { + public abstract class Goo + { + public abstract object Bar( Type type ); + } + + public class Test + { + public void TestMethod(Goo arg) + { + arg?.Bar(); + + } + } + } + + namespace A.Extensions + { + public static class Extension + { + public static T Bar( this Goo @this ) + => (T)@this.Bar( typeof( T ) ); + } + } + """); } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingTests_Queries.cs b/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingTests_Queries.cs index ea71975ce65f2..6c933747d1de3 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingTests_Queries.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingTests_Queries.cs @@ -14,65 +14,69 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddUsing; public sealed partial class AddUsingTests { [Fact] - public async Task TestSimpleQuery() - { - await TestInRegularAndScriptAsync( -@"using System; -using System.Collections.Generic; + public Task TestSimpleQuery() + => TestInRegularAndScriptAsync( + """ + using System; + using System.Collections.Generic; -class Program -{ - static void Main(string[] args) - { - var q = [|from x in args - select x|]} -}", -@"using System; -using System.Collections.Generic; -using System.Linq; + class Program + { + static void Main(string[] args) + { + var q = [|from x in args + select x|]} + } + """, + """ + using System; + using System.Collections.Generic; + using System.Linq; -class Program -{ - static void Main(string[] args) - { - var q = from x in args - select x} -}"); - } + class Program + { + static void Main(string[] args) + { + var q = from x in args + select x} + } + """); [Fact] - public async Task TestSimpleWhere() - { - await TestInRegularAndScriptAsync( -@"class Test -{ - public void SimpleWhere() - { - int[] numbers = { - 1, - 2, - 3 - }; - var lowNums = [|from n in numbers - where n < 5 - select n|]; - } -}", -@"using System.Linq; + public Task TestSimpleWhere() + => TestInRegularAndScriptAsync( + """ + class Test + { + public void SimpleWhere() + { + int[] numbers = { + 1, + 2, + 3 + }; + var lowNums = [|from n in numbers + where n < 5 + select n|]; + } + } + """, + """ + using System.Linq; -class Test -{ - public void SimpleWhere() - { - int[] numbers = { - 1, - 2, - 3 - }; - var lowNums = from n in numbers - where n < 5 - select n; - } -}"); - } + class Test + { + public void SimpleWhere() + { + int[] numbers = { + 1, + 2, + 3 + }; + var lowNums = from n in numbers + where n < 5 + select n; + } + } + """); } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingTests_Razor.cs b/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingTests_Razor.cs index d91236e0b6dfe..8d9f05ec07213 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingTests_Razor.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingTests_Razor.cs @@ -14,33 +14,35 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddUsing; public sealed partial class AddUsingTests_Razor : AbstractAddUsingTests { [Theory, CombinatorialData] - public async Task TestAddIntoHiddenRegionWithModernSpanMapper(TestHost host) - { - await TestAsync( -@"#line hidden -using System.Collections.Generic; -#line default + public Task TestAddIntoHiddenRegionWithModernSpanMapper(TestHost host) + => TestAsync( + """ + #line hidden + using System.Collections.Generic; + #line default -class Program -{ - void Main() - { - [|DateTime|] d; - } -}", -@"#line hidden -using System; -using System.Collections.Generic; -#line default + class Program + { + void Main() + { + [|DateTime|] d; + } + } + """, + """ + #line hidden + using System; + using System.Collections.Generic; + #line default -class Program -{ - void Main() - { - DateTime d; - } -}", host); - } + class Program + { + void Main() + { + DateTime d; + } + } + """, host); private protected override IDocumentServiceProvider GetDocumentServiceProvider() { diff --git a/src/EditorFeatures/CSharpTest/CodeActions/ApplyChangesOperationTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/ApplyChangesOperationTests.cs index 5d79e86913bb5..db111a0b9322f 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/ApplyChangesOperationTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/ApplyChangesOperationTests.cs @@ -55,25 +55,24 @@ public TestCodeAction(Solution changedSolution) } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_queries/edit/1419139")] - public async Task TestMakeTextChangeWithInterveningEditToDifferentFile() - { - // This should succeed as the code action is trying to edit a file that is not touched by the actual - // workspace edit that already went in. - await TestSuccessfulApplicationAsync( -@" - - -class Program1 -{ -} - - -class Program2 -{ -} - - -", + public Task TestMakeTextChangeWithInterveningEditToDifferentFile() + => TestSuccessfulApplicationAsync( + """ + + + + class Program1 + { + } + + + class Program2 + { + } + + + + """, codeActionTransform: solution => { var document1 = solution.Projects.Single().Documents.Single(d => d.FilePath!.Contains("Program1")); @@ -84,28 +83,26 @@ class Program2 var document2 = solution.Projects.Single().Documents.Single(d => d.FilePath!.Contains("Program2")); return solution.WithDocumentText(document2.Id, SourceText.From("NewProgram2Content")); }); - } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_queries/edit/1419139")] - public async Task TestMakeTextChangeWithInterveningRemovalToDifferentFile() - { - // This should succeed as the code action is trying to edit a file that is not touched by the actual - // workspace edit that already went in. - await TestSuccessfulApplicationAsync( -@" - - -class Program1 -{ -} - - -class Program2 -{ -} - - -", + public Task TestMakeTextChangeWithInterveningRemovalToDifferentFile() + => TestSuccessfulApplicationAsync( + """ + + + + class Program1 + { + } + + + class Program2 + { + } + + + + """, codeActionTransform: solution => { var document1 = solution.Projects.Single().Documents.Single(d => d.FilePath!.Contains("Program1")); @@ -116,28 +113,26 @@ class Program2 var document2 = solution.Projects.Single().Documents.Single(d => d.FilePath!.Contains("Program2")); return solution.RemoveDocument(document2.Id); }); - } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_queries/edit/1419139")] - public async Task TestMakeTextChangeWithInterveningEditToSameFile() - { - // This should fail as the code action is trying to edit a file that is was already edited by the actual - // workspace edit that already went in. - await TestFailureApplicationAsync( -@" - - -class Program1 -{ -} - - -class Program2 -{ -} - - -", + public Task TestMakeTextChangeWithInterveningEditToSameFile() + => TestFailureApplicationAsync( + """ + + + + class Program1 + { + } + + + class Program2 + { + } + + + + """, codeActionTransform: solution => { var document1 = solution.Projects.Single().Documents.Single(d => d.FilePath!.Contains("Program1")); @@ -148,27 +143,26 @@ class Program2 var document1 = solution.Projects.Single().Documents.Single(d => d.FilePath!.Contains("Program1")); return solution.WithDocumentText(document1.Id, SourceText.From("NewProgram1Content2")); }); - } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_queries/edit/1419139")] - public async Task TestMakeTextChangeWithInterveningRemovalOfThatFile() - { - // This should fail as the code action is trying to edit a file that is subsequently removed. - await TestFailureApplicationAsync( -@" - - -class Program1 -{ -} - - -class Program2 -{ -} - - -", + public Task TestMakeTextChangeWithInterveningRemovalOfThatFile() + => TestFailureApplicationAsync( + """ + + + + class Program1 + { + } + + + class Program2 + { + } + + + + """, codeActionTransform: solution => { var document1 = solution.Projects.Single().Documents.Single(d => d.FilePath!.Contains("Program1")); @@ -179,28 +173,26 @@ class Program2 var document1 = solution.Projects.Single().Documents.Single(d => d.FilePath!.Contains("Program1")); return solution.RemoveDocument(document1.Id); }); - } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_queries/edit/1419139")] - public async Task TestMakeProjectChangeWithInterveningTextEdit() - { - // This should fail as we don't want to make non-text changes that may have undesirable results to the solution - // given the intervening edits. - await TestFailureApplicationAsync( -@" - - -class Program1 -{ -} - - -class Program2 -{ -} - - -", + public Task TestMakeProjectChangeWithInterveningTextEdit() + => TestFailureApplicationAsync( + """ + + + + class Program1 + { + } + + + class Program2 + { + } + + + + """, codeActionTransform: solution => { var document1 = solution.Projects.Single().Documents.Single(d => d.FilePath!.Contains("Program1")); @@ -211,23 +203,18 @@ class Program2 var document2 = solution.Projects.Single().Documents.Single(d => d.FilePath!.Contains("Program2")); return solution.WithDocumentText(document2.Id, SourceText.From("NewProgram1Content2")); }); - } - private async Task TestSuccessfulApplicationAsync( + private Task TestSuccessfulApplicationAsync( string workspaceXml, Func codeActionTransform, Func intermediaryTransform) - { - await TestApplicationAsync(workspaceXml, codeActionTransform, intermediaryTransform, success: true); - } + => TestApplicationAsync(workspaceXml, codeActionTransform, intermediaryTransform, success: true); - private async Task TestFailureApplicationAsync( + private Task TestFailureApplicationAsync( string workspaceXml, Func codeActionTransform, Func intermediaryTransform) - { - await TestApplicationAsync(workspaceXml, codeActionTransform, intermediaryTransform, success: false); - } + => TestApplicationAsync(workspaceXml, codeActionTransform, intermediaryTransform, success: false); private async Task TestApplicationAsync( string workspaceXml, diff --git a/src/EditorFeatures/CSharpTest/CodeActions/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.cs index fbda58a3296d7..d9bd2d2acc41a 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.cs @@ -20,11 +20,12 @@ using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; -using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeRefactoringVerifier< - Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers.GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.GenerateEqualsAndGetHashCodeFromMembers; +using VerifyCS = CSharpCodeRefactoringVerifier< + GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider>; + [UseExportProvider] [Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public sealed class GenerateEqualsAndGetHashCodeFromMembersTests @@ -69,26 +70,22 @@ private static OptionsCollection PreferExplicitTypeWithInfo() internal static void EnableOption(ImmutableArray options, string id) { var option = options.FirstOrDefault(o => o.Id == id); - if (option != null) - { - option.Value = true; - } + option?.Value = true; } [Fact] - public async Task TestEqualsSingleField() - { - var code = - """ + public Task TestEqualsSingleField() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Program { [|int a;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Program @@ -102,31 +99,24 @@ public override bool Equals(object obj) a == program.a; } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestEqualsSingleField_CSharp7() - { - var code = - """ + public Task TestEqualsSingleField_CSharp7() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Program { [|int a;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Program @@ -139,31 +129,24 @@ public override bool Equals(object obj) a == program.a; } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp7, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39916")] - public async Task TestEqualsSingleField_PreferExplicitType() - { - var code = - """ + public Task TestEqualsSingleField_PreferExplicitType() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Program { [|int a;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Program @@ -177,22 +160,16 @@ public override bool Equals(object obj) a == program.a; } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferExplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestReferenceIEquatable() - { - var code = - """ + public Task TestReferenceIEquatable() + => new VerifyCS.Test + { + TestCode = """ using System; using System.Collections.Generic; @@ -202,9 +179,8 @@ class Program { [|S a;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System; using System.Collections.Generic; @@ -221,22 +197,16 @@ public override bool Equals(object obj) EqualityComparer.Default.Equals(a, program.a); } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestNullableReferenceIEquatable() - { - var code = - """ + public Task TestNullableReferenceIEquatable() + => new VerifyCS.Test + { + TestCode = """ #nullable enable using System; @@ -248,9 +218,8 @@ class Program { [|S? a;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ #nullable enable using System; @@ -273,22 +242,16 @@ public override int GetHashCode() return -1757793268 + EqualityComparer.Default.GetHashCode(a); } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionIndex = 1, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestValueIEquatable() - { - var code = - """ + public Task TestValueIEquatable() + => new VerifyCS.Test + { + TestCode = """ using System; using System.Collections.Generic; @@ -298,9 +261,8 @@ class Program { [|S a;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System; using System.Collections.Generic; @@ -317,31 +279,24 @@ public override bool Equals(object obj) a.Equals(program.a); } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestEqualsLongName() - { - var code = - """ + public Task TestEqualsLongName() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class ReallyLongName { [|int a;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class ReallyLongName @@ -355,31 +310,24 @@ public override bool Equals(object obj) a == name.a; } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestEqualsKeywordName() - { - var code = - """ + public Task TestEqualsKeywordName() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class ReallyLongLong { [|long a;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class ReallyLongLong @@ -393,22 +341,16 @@ public override bool Equals(object obj) a == @long.a; } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestEqualsProperty() - { - var code = - """ + public Task TestEqualsProperty() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class ReallyLongName @@ -417,9 +359,8 @@ class ReallyLongName string B { get; }|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class ReallyLongName @@ -436,22 +377,16 @@ public override bool Equals(object obj) B == name.B; } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestEqualsBaseTypeWithNoEquals() - { - var code = - """ + public Task TestEqualsBaseTypeWithNoEquals() + => new VerifyCS.Test + { + TestCode = """ class Base { } @@ -460,9 +395,8 @@ class Program : Base { [|int i;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ class Base { } @@ -478,22 +412,16 @@ public override bool Equals(object obj) i == program.i; } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestEqualsBaseWithOverriddenEquals() - { - var code = - """ + public Task TestEqualsBaseWithOverriddenEquals() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Base @@ -510,9 +438,8 @@ class Program : Base string S { get; }|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Base @@ -538,22 +465,16 @@ public override bool Equals(object obj) S == program.S; } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestEqualsOverriddenDeepBase() - { - var code = - """ + public Task TestEqualsOverriddenDeepBase() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Base @@ -574,9 +495,8 @@ class Program : Middle string S { get; }|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Base @@ -606,21 +526,14 @@ public override bool Equals(object obj) S == program.S; } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestEqualsStruct() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestEqualsStruct() + => VerifyCS.VerifyRefactoringAsync( """ using System.Collections.Generic; @@ -663,12 +576,10 @@ public bool Equals(ReallyLongName other) } } """); - } [Fact] - public async Task TestEqualsStructCSharpLatest() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestEqualsStructCSharpLatest() + => VerifyCS.VerifyRefactoringAsync( """ using System.Collections.Generic; @@ -711,12 +622,10 @@ public bool Equals(ReallyLongName other) } } """); - } [Fact] - public async Task TestEqualsStructAlreadyImplementsIEquatable() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestEqualsStructAlreadyImplementsIEquatable() + => VerifyCS.VerifyRefactoringAsync( """ using System; using System.Collections.Generic; @@ -756,12 +665,10 @@ public override bool Equals(object obj) } } """); - } [Fact] - public async Task TestEqualsStructAlreadyHasOperators() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestEqualsStructAlreadyHasOperators() + => VerifyCS.VerifyRefactoringAsync( """ using System; using System.Collections.Generic; @@ -801,12 +708,10 @@ public bool Equals(ReallyLongName other) public static bool operator !=(ReallyLongName left, ReallyLongName right) => false; } """); - } [Fact] - public async Task TestEqualsStructAlreadyImplementsIEquatableAndHasOperators() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestEqualsStructAlreadyImplementsIEquatableAndHasOperators() + => VerifyCS.VerifyRefactoringAsync( """ using System; using System.Collections.Generic; @@ -842,20 +747,19 @@ public override bool Equals(object obj) public static bool operator !=(ReallyLongName left, ReallyLongName right) => false; } """); - } [Fact] - public async Task TestEqualsGenericType() - { - var code = """ + public Task TestEqualsGenericType() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Program { [|int i;|] } - """; - - var expected = """ + """, + FixedCode = """ using System.Collections.Generic; class Program { @@ -868,21 +772,14 @@ public override bool Equals(object obj) i == program.i; } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = expected, + """, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestEqualsNullableContext() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestEqualsNullableContext() + => VerifyCS.VerifyRefactoringAsync( """ #nullable enable @@ -905,22 +802,20 @@ public override bool Equals(object? obj) } } """); - } [Fact] - public async Task TestGetHashCodeSingleField1() - { - var code = - """ + public Task TestGetHashCodeSingleField1() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Program { [|int i;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Program @@ -939,32 +834,25 @@ public override int GetHashCode() return 165851236 + i.GetHashCode(); } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestGetHashCodeSingleField2() - { - var code = - """ + public Task TestGetHashCodeSingleField2() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Program { [|int j;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Program @@ -983,23 +871,17 @@ public override int GetHashCode() return 1424088837 + j.GetHashCode(); } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestGetHashCodeWithBaseHashCode1() - { - var code = - """ + public Task TestGetHashCodeWithBaseHashCode1() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Base { @@ -1010,9 +892,8 @@ class Program : Base { [|int j;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Base { @@ -1038,24 +919,18 @@ public override int GetHashCode() return hashCode; } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestGetHashCodeWithBaseHashCode2() - { - var code = - """ - using System.Collections.Generic; + public Task TestGetHashCodeWithBaseHashCode2() + => new TestWithDialog + { + TestCode = """ + using System.Collections.Generic; class Base { public override int GetHashCode() => 0; @@ -1066,9 +941,8 @@ class Program : Base int j; [||] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Base { @@ -1090,33 +964,26 @@ public override int GetHashCode() return 624022166 + base.GetHashCode(); } } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionIndex = 1, MemberNames = [], LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestGetHashCodeSingleField_CodeStyle1() - { - var code = - """ + public Task TestGetHashCodeSingleField_CodeStyle1() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Program { [|int i;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Program @@ -1132,12 +999,7 @@ public override bool Equals(object obj) public override int GetHashCode() => 165851236 + i.GetHashCode(); } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement }, @@ -1145,22 +1007,20 @@ public override bool Equals(object obj) CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, }.RunAsync(); - } [Fact] - public async Task TestGetHashCodeTypeParameter() - { - var code = - """ + public Task TestGetHashCodeTypeParameter() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Program { [|T i;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Program @@ -1179,32 +1039,25 @@ public override int GetHashCode() return 165851236 + EqualityComparer.Default.GetHashCode(i); } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestGetHashCodeGenericType() - { - var code = - """ + public Task TestGetHashCodeGenericType() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Program { [|Program i;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Program @@ -1223,23 +1076,17 @@ public override int GetHashCode() return 165851236 + EqualityComparer>.Default.GetHashCode(i); } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestGetHashCodeMultipleMembers() - { - var code = - """ + public Task TestGetHashCodeMultipleMembers() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Program @@ -1248,9 +1095,8 @@ class Program string S { get; }|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Program @@ -1275,23 +1121,17 @@ public override int GetHashCode() return hashCode; } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestSmartTagText1() - { - var code = - """ + public Task TestSmartTagText1() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Program @@ -1304,9 +1144,8 @@ public Program(bool b) this.b = b; } } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Program @@ -1326,22 +1165,16 @@ public override bool Equals(object obj) EqualityComparer>.Default.Equals(s, program.s); } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionEquivalenceKey = FeaturesResources.Generate_Equals_object, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Generate_Equals_object, codeAction.Title), }.RunAsync(); - } [Fact] - public async Task TestSmartTagText2() - { - var code = - """ + public Task TestSmartTagText2() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Program @@ -1354,9 +1187,8 @@ public Program(bool b) this.b = b; } } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Program @@ -1384,23 +1216,17 @@ public override int GetHashCode() return hashCode; } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionIndex = 1, CodeActionEquivalenceKey = FeaturesResources.Generate_Equals_and_GetHashCode, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Generate_Equals_and_GetHashCode, codeAction.Title), }.RunAsync(); - } [Fact] - public async Task TestSmartTagText3() - { - var code = - """ + public Task TestSmartTagText3() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Program @@ -1413,9 +1239,8 @@ public Program(bool b) this.b = b; } } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Program @@ -1443,32 +1268,25 @@ public override int GetHashCode() return hashCode; } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionIndex = 1, CodeActionEquivalenceKey = FeaturesResources.Generate_Equals_and_GetHashCode, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Generate_Equals_and_GetHashCode, codeAction.Title), }.RunAsync(); - } [Fact] - public async Task Tuple_Disabled() - { - var code = - """ + public Task Tuple_Disabled() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class C { [|{|CS8059:(int, string)|} a;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class C @@ -1482,31 +1300,24 @@ public override bool Equals(object obj) a.Equals(c.a); } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task Tuples_Equals() - { - var code = - """ + public Task Tuples_Equals() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class C { [|{|CS8059:(int, string)|} a;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class C @@ -1520,31 +1331,24 @@ public override bool Equals(object obj) a.Equals(c.a); } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TupleWithNames_Equals() - { - var code = - """ + public Task TupleWithNames_Equals() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class C { [|{|CS8059:(int x, string y)|} a;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class C @@ -1558,31 +1362,24 @@ public override bool Equals(object obj) a.Equals(c.a); } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task Tuple_HashCode() - { - var code = - """ + public Task Tuple_HashCode() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Program { [|{|CS8059:(int, string)|} i;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Program @@ -1601,32 +1398,25 @@ public override int GetHashCode() return 165851236 + i.GetHashCode(); } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TupleWithNames_HashCode() - { - var code = - """ + public Task TupleWithNames_HashCode() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Program { [|{|CS8059:(int x, string y)|} i;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Program @@ -1645,23 +1435,17 @@ public override int GetHashCode() return 165851236 + i.GetHashCode(); } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task StructWithoutGetHashCodeOverride_ShouldCallGetHashCodeDirectly() - { - var code = - """ + public Task StructWithoutGetHashCodeOverride_ShouldCallGetHashCodeDirectly() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Foo @@ -1672,9 +1456,8 @@ class Foo struct Bar { } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Foo @@ -1697,23 +1480,17 @@ public override int GetHashCode() struct Bar { } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task StructWithGetHashCodeOverride_ShouldCallGetHashCodeDirectly() - { - var code = - """ + public Task StructWithGetHashCodeOverride_ShouldCallGetHashCodeDirectly() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Foo @@ -1725,9 +1502,8 @@ struct Bar { public override int GetHashCode() => 0; } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Foo @@ -1751,23 +1527,17 @@ struct Bar { public override int GetHashCode() => 0; } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task NullableStructWithoutGetHashCodeOverride_ShouldCallGetHashCodeDirectly() - { - var code = - """ + public Task NullableStructWithoutGetHashCodeOverride_ShouldCallGetHashCodeDirectly() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Foo @@ -1778,9 +1548,8 @@ class Foo struct Bar { } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Foo @@ -1803,32 +1572,25 @@ public override int GetHashCode() struct Bar { } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task StructTypeParameter_ShouldCallGetHashCodeDirectly() - { - var code = - """ + public Task StructTypeParameter_ShouldCallGetHashCodeDirectly() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Foo where TBar : struct { [|TBar bar;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Foo where TBar : struct @@ -1847,32 +1609,25 @@ public override int GetHashCode() return 999205674 + bar.GetHashCode(); } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task NullableStructTypeParameter_ShouldCallGetHashCodeDirectly() - { - var code = - """ + public Task NullableStructTypeParameter_ShouldCallGetHashCodeDirectly() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Foo where TBar : struct { [|TBar? bar;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Foo where TBar : struct @@ -1891,23 +1646,17 @@ public override int GetHashCode() return 999205674 + bar.GetHashCode(); } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task Enum_ShouldCallGetHashCodeDirectly() - { - var code = - """ + public Task Enum_ShouldCallGetHashCodeDirectly() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Foo @@ -1918,9 +1667,8 @@ class Foo enum Bar { } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Foo @@ -1943,32 +1691,25 @@ public override int GetHashCode() enum Bar { } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task PrimitiveValueType_ShouldCallGetHashCodeDirectly() - { - var code = - """ + public Task PrimitiveValueType_ShouldCallGetHashCodeDirectly() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Foo { [|ulong bar;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Foo @@ -1987,23 +1728,17 @@ public override int GetHashCode() return 999205674 + bar.GetHashCode(); } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestWithDialog1() - { - var code = - """ + public Task TestWithDialog1() + => new TestWithDialog + { + TestCode = """ using System.Collections.Generic; class Program @@ -2012,9 +1747,8 @@ class Program string b; [||] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Program @@ -2030,23 +1764,17 @@ public override bool Equals(object obj) b == program.b; } } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, MemberNames = ["a", "b"], LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestWithDialog2() - { - var code = - """ + public Task TestWithDialog2() + => new TestWithDialog + { + TestCode = """ using System.Collections.Generic; class Program @@ -2056,9 +1784,8 @@ class Program bool c; [||] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Program @@ -2075,23 +1802,17 @@ public override bool Equals(object obj) b == program.b; } } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, MemberNames = ["c", "b"], LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestWithDialog3() - { - var code = - """ + public Task TestWithDialog3() + => new TestWithDialog + { + TestCode = """ using System.Collections.Generic; class Program @@ -2101,9 +1822,8 @@ class Program bool c; [||] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Program @@ -2118,31 +1838,24 @@ public override bool Equals(object obj) return !ReferenceEquals(program, null); } } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, MemberNames = [], LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17643")] - public async Task TestWithDialogNoBackingField() - { - var code = - """ + public Task TestWithDialogNoBackingField() + => new TestWithDialog + { + TestCode = """ class Program { public int F { get; set; } [||] } - """; - var fixedCode = - """ + """, + FixedCode = """ class Program { public int F { get; set; } @@ -2154,31 +1867,24 @@ public override bool Equals(object obj) F == program.F; } } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25690")] - public async Task TestWithDialogNoIndexer() - { - var code = - """ + public Task TestWithDialogNoIndexer() + => new TestWithDialog + { + TestCode = """ class Program { public int P => 0; public int this[int index] => 0; [||] } - """; - var fixedCode = - """ + """, + FixedCode = """ class Program { public int P => 0; @@ -2190,29 +1896,22 @@ public override bool Equals(object obj) P == program.P; } } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25707")] - public async Task TestWithDialogNoSetterOnlyProperty() - { - var code = - """ + public Task TestWithDialogNoSetterOnlyProperty() + => new TestWithDialog + { + TestCode = """ class Program { public int P => 0; public int S { set { } } [||] } - """; - var fixedCode = - """ + """, + FixedCode = """ class Program { public int P => 0; @@ -2224,20 +1923,14 @@ public override bool Equals(object obj) P == program.P; } } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41958")] - public async Task TestWithDialogInheritedMembers() - { - var code = - """ + public Task TestWithDialogInheritedMembers() + => new TestWithDialog + { + TestCode = """ class Base { public int C { get; set; } @@ -2253,9 +1946,8 @@ class Derived : Middle public int A { get; set; } [||] } - """; - var fixedCode = - """ + """, + FixedCode = """ class Base { public int C { get; set; } @@ -2278,20 +1970,14 @@ public override bool Equals(object obj) A == derived.A; } } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, }.RunAsync(); - } [Fact] - public async Task TestGenerateOperators1() - { - var code = - """ + public Task TestGenerateOperators1() + => new TestWithDialog + { + TestCode = """ using System.Collections.Generic; class Program @@ -2299,9 +1985,8 @@ class Program public string s; [||] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Program @@ -2325,24 +2010,18 @@ public override bool Equals(object obj) return !(left == right); } } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId), LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestGenerateOperators2() - { - var code = - """ + public Task TestGenerateOperators2() + => new TestWithDialog + { + TestCode = """ using System.Collections.Generic; class Program @@ -2350,9 +2029,8 @@ class Program public string s; [||] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Program @@ -2369,12 +2047,7 @@ public override bool Equals(object obj) public static bool operator ==(Program left, Program right) => EqualityComparer.Default.Equals(left, right); public static bool operator !=(Program left, Program right) => !(left == right); } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId), LanguageVersion = LanguageVersion.CSharp6, @@ -2383,13 +2056,12 @@ public override bool Equals(object obj) { CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement }, }, }.RunAsync(); - } [Fact] - public async Task TestGenerateOperators3() - { - var code = - """ + public Task TestGenerateOperators3() + => new TestWithDialog + { + TestCode = """ using System.Collections.Generic; class Program @@ -2399,9 +2071,8 @@ class Program public static bool operator {|CS0216:==|}(Program left, Program right) => true; } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Program @@ -2417,24 +2088,18 @@ public override bool Equals(object obj) public static bool operator {|CS0216:==|}(Program left, Program right) => true; } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, MemberNames = default, OptionsCallback = options => Assert.Null(options.FirstOrDefault(i => i.Id == GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId)), LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestGenerateOperators4() - { - var code = - """ + public Task TestGenerateOperators4() + => new TestWithDialog + { + TestCode = """ using System.Collections.Generic; struct Program @@ -2442,9 +2107,8 @@ struct Program public string s; [||] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; struct Program @@ -2472,24 +2136,18 @@ public override bool Equals(object obj) return !(left == right); } } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId), LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestGenerateLiftedOperators() - { - var code = - """ + public Task TestGenerateLiftedOperators() + => new VerifyCS.Test + { + TestCode = """ using System; using System.Collections.Generic; @@ -2504,9 +2162,8 @@ class Foo enum Bar { } - """; - var fixedCode = - """ + """, + FixedCode = """ using System; using System.Collections.Generic; @@ -2531,22 +2188,16 @@ public override bool Equals(object obj) enum Bar { } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task LiftedOperatorIsNotUsedWhenDirectOperatorWouldNotBeUsed() - { - var code = - """ + public Task LiftedOperatorIsNotUsedWhenDirectOperatorWouldNotBeUsed() + => new VerifyCS.Test + { + TestCode = """ using System; using System.Collections.Generic; @@ -2570,9 +2221,8 @@ struct Bar : IEquatable public static bool operator !=(Bar left, Bar right) => !(left == right); } - """; - var fixedCode = - """ + """, + FixedCode = """ using System; using System.Collections.Generic; @@ -2604,22 +2254,16 @@ struct Bar : IEquatable public static bool operator !=(Bar left, Bar right) => !(left == right); } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestImplementIEquatableOnStruct() - { - var code = - """ + public Task TestImplementIEquatableOnStruct() + => new TestWithDialog + { + TestCode = """ using System.Collections.Generic; struct Program @@ -2627,9 +2271,8 @@ struct Program public string s; [||] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System; using System.Collections.Generic; @@ -2647,32 +2290,25 @@ public bool Equals(Program other) return s == other.s; } } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId), LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25708")] - public async Task TestOverrideEqualsOnRefStructReturnsFalse() - { - var code = - """ + public Task TestOverrideEqualsOnRefStructReturnsFalse() + => new TestWithDialog + { + TestCode = """ ref struct Program { public string s; [||] } - """; - var fixedCode = - """ + """, + FixedCode = """ ref struct Program { public string s; @@ -2682,28 +2318,21 @@ public override bool Equals(object obj) return false; } } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25708")] - public async Task TestImplementIEquatableOnRefStructSkipsIEquatable() - { - var code = - """ + public Task TestImplementIEquatableOnRefStructSkipsIEquatable() + => new TestWithDialog + { + TestCode = """ ref struct Program { public string s; [||] } - """; - var fixedCode = - """ + """, + FixedCode = """ ref struct Program { public string s; @@ -2713,25 +2342,19 @@ public override bool Equals(object obj) return false; } } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, MemberNames = default, // We are forcefully enabling the ImplementIEquatable option, as that is our way // to test that the option does nothing. The VS mode will ensure if the option // is not available it will not be shown. OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId), }.RunAsync(); - } [Fact] - public async Task TestImplementIEquatableOnStructInNullableContextWithUnannotatedMetadata() - { - var code = - """ + public Task TestImplementIEquatableOnStructInNullableContextWithUnannotatedMetadata() + => new TestWithDialog + { + TestCode = """ #nullable enable struct Foo @@ -2739,9 +2362,8 @@ struct Foo public int Bar { get; } [||] } - """; - var fixedCode = - """ + """, + FixedCode = """ #nullable enable using System; @@ -2760,23 +2382,17 @@ public bool Equals(Foo other) return Bar == other.Bar; } } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId), LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] - public async Task TestImplementIEquatableOnStructInNullableContextWithAnnotatedMetadata() - { - var code = - """ + public Task TestImplementIEquatableOnStructInNullableContextWithAnnotatedMetadata() + => new TestWithDialog + { + TestCode = """ #nullable enable using System; @@ -2787,9 +2403,8 @@ struct Foo public bool Bar { get; } [||] } - """; - var fixedCode = - """ + """, + FixedCode = """ #nullable enable using System; @@ -2809,23 +2424,17 @@ public bool Equals(Foo other) return Bar == other.Bar; } } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId), LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] - public async Task TestImplementIEquatableOnClass_CSharp6() - { - var code = - """ + public Task TestImplementIEquatableOnClass_CSharp6() + => new TestWithDialog + { + TestCode = """ using System.Collections.Generic; class Program @@ -2833,9 +2442,8 @@ class Program public string s; [||] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System; using System.Collections.Generic; @@ -2854,24 +2462,18 @@ public bool Equals(Program other) s == other.s; } } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId), LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestImplementIEquatableOnClass_CSharp7() - { - var code = - """ + public Task TestImplementIEquatableOnClass_CSharp7() + => new TestWithDialog + { + TestCode = """ using System.Collections.Generic; class Program @@ -2879,9 +2481,8 @@ class Program public string s; [||] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System; using System.Collections.Generic; @@ -2900,24 +2501,18 @@ public bool Equals(Program other) s == other.s; } } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId), LanguageVersion = LanguageVersion.CSharp7, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestImplementIEquatableOnClass_CSharp8() - { - var code = - """ + public Task TestImplementIEquatableOnClass_CSharp8() + => new TestWithDialog + { + TestCode = """ using System.Collections.Generic; class Program @@ -2925,9 +2520,8 @@ class Program public string s; [||] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System; using System.Collections.Generic; @@ -2946,24 +2540,18 @@ public bool Equals(Program other) s == other.s; } } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId), LanguageVersion = LanguageVersion.CSharp8, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestImplementIEquatableOnClass_CSharp9() - { - var code = - """ + public Task TestImplementIEquatableOnClass_CSharp9() + => new TestWithDialog + { + TestCode = """ using System.Collections.Generic; class Program @@ -2971,9 +2559,8 @@ class Program public string s; [||] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System; using System.Collections.Generic; @@ -2992,24 +2579,18 @@ public bool Equals(Program other) s == other.s; } } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId), LanguageVersion = LanguageVersion.CSharp9, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestImplementIEquatableOnClassInNullableContextWithUnannotatedMetadata() - { - var code = - """ + public Task TestImplementIEquatableOnClassInNullableContextWithUnannotatedMetadata() + => new TestWithDialog + { + TestCode = """ #nullable enable class Foo @@ -3017,9 +2598,8 @@ class Foo public int Bar { get; } [||] } - """; - var fixedCode = - """ + """, + FixedCode = """ #nullable enable using System; @@ -3039,23 +2619,17 @@ public bool Equals(Foo? other) Bar == other.Bar; } } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId), LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] - public async Task TestImplementIEquatableOnClassInNullableContextWithAnnotatedMetadata() - { - var code = - """ + public Task TestImplementIEquatableOnClassInNullableContextWithAnnotatedMetadata() + => new TestWithDialog + { + TestCode = """ #nullable enable using System; @@ -3066,9 +2640,8 @@ class Foo public bool Bar { get; } [||] } - """; - var fixedCode = - """ + """, + FixedCode = """ #nullable enable using System; @@ -3089,23 +2662,17 @@ public bool Equals(Foo? other) Bar == other.Bar; } } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId), LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] - public async Task TestDoNotOfferIEquatableIfTypeAlreadyImplementsIt() - { - var code = - """ + public Task TestDoNotOfferIEquatableIfTypeAlreadyImplementsIt() + => new TestWithDialog + { + TestCode = """ using System.Collections.Generic; class Program : {|CS0535:System.IEquatable|} @@ -3113,9 +2680,8 @@ class Program : {|CS0535:System.IEquatable|} public string s; [||] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Program : {|CS0535:System.IEquatable|} @@ -3129,23 +2695,16 @@ public override bool Equals(object obj) s == program.s; } } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, MemberNames = default, OptionsCallback = options => Assert.Null(options.FirstOrDefault(i => i.Id == GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId)), LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestMissingReferences1() - { - await new VerifyCS.Test + public Task TestMissingReferences1() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp6, CodeActionIndex = 1, @@ -3248,13 +2807,12 @@ public override System.Int32 GetHashCode() }, ReferenceAssemblies = ReferenceAssemblies.Default.WithAssemblies([]), }.RunAsync(); - } [Fact] - public async Task TestGetHashCodeInCheckedContext() - { - var code = - """ + public Task TestGetHashCodeInCheckedContext() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Program @@ -3263,9 +2821,8 @@ class Program string S { get; }|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Program @@ -3293,12 +2850,7 @@ public override int GetHashCode() } } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, SolutionTransforms = @@ -3310,22 +2862,20 @@ public override int GetHashCode() }, }, }.RunAsync(); - } [Fact] - public async Task TestGetHashCodeStruct() - { - var code = - """ + public Task TestGetHashCodeStruct() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; struct S { [|int j;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System; using System.Collections.Generic; @@ -3358,31 +2908,15 @@ public override int GetHashCode() return !(left == right); } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] public async Task TestGetHashCodeSystemHashCodeOneMember() { - var code = - """ - using System.Collections.Generic; - namespace System { public struct HashCode { } } - - struct S - { - [|int j;|] - } - """; var fixedCode = """ using System; @@ -3422,7 +2956,15 @@ public override int GetHashCode() await new VerifyCS.Test { - TestCode = code, + TestCode = """ + using System.Collections.Generic; + namespace System { public struct HashCode { } } + + struct S + { + [|int j;|] + } + """, FixedState = { Sources = { fixedCode }, @@ -3441,11 +2983,6 @@ public override int GetHashCode() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37297")] public async Task TestPublicSystemHashCodeOtherProject() { - var publicHashCode = - """ - using System.Collections.Generic; - namespace System { public struct HashCode { } } - """; var code = """ struct S @@ -3496,7 +3033,10 @@ public override int GetHashCode() { ["P1"] = { - Sources = { ("HashCode.cs", publicHashCode) }, + Sources = { ("HashCode.cs", """ + using System.Collections.Generic; + namespace System { public struct HashCode { } } + """) }, }, }, Sources = { code }, @@ -3520,11 +3060,6 @@ public override int GetHashCode() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37297")] public async Task TestInternalSystemHashCode() { - var internalHashCode = - """ - using System.Collections.Generic; - namespace System { internal struct HashCode { } } - """; var code = """ struct S @@ -3532,8 +3067,24 @@ struct S [|int j;|] } """; - var fixedCode = - """ + await new VerifyCS.Test + { + TestState = + { + AdditionalProjects = + { + ["P1"] = + { + Sources = { ("HashCode.cs", """ + using System.Collections.Generic; + namespace System { internal struct HashCode { } } + """) }, + }, + }, + Sources = { code }, + AdditionalProjectReferences = { "P1" }, + }, + FixedCode = """ using System; struct S : IEquatable @@ -3565,23 +3116,7 @@ public override int GetHashCode() return !(left == right); } } - """; - - await new VerifyCS.Test - { - TestState = - { - AdditionalProjects = - { - ["P1"] = - { - Sources = { ("HashCode.cs", internalHashCode) }, - }, - }, - Sources = { code }, - AdditionalProjectReferences = { "P1" }, - }, - FixedCode = fixedCode, + """, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, @@ -3591,16 +3126,6 @@ public override int GetHashCode() [Fact] public async Task TestGetHashCodeSystemHashCodeEightMembers() { - var code = - """ - using System.Collections.Generic; - namespace System { public struct HashCode { } } - - struct S - { - [|int j, k, l, m, n, o, p, q;|] - } - """; var fixedCode = """ using System; @@ -3647,7 +3172,15 @@ public override int GetHashCode() await new VerifyCS.Test { - TestCode = code, + TestCode = """ + using System.Collections.Generic; + namespace System { public struct HashCode { } } + + struct S + { + [|int j, k, l, m, n, o, p, q;|] + } + """, FixedState = { Sources = { fixedCode }, @@ -3664,10 +3197,10 @@ public override int GetHashCode() } [Fact] - public async Task TestGetHashCodeSystemHashCodeNineMembers() - { - var code = - """ + public Task TestGetHashCodeSystemHashCodeNineMembers() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; namespace System { public struct HashCode { public void Add(T value) { } public int ToHashCode() => 0; } } @@ -3675,9 +3208,8 @@ struct S { [|int j, k, l, m, n, o, p, q, r;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System; using System.Collections.Generic; namespace System { public struct HashCode { public void Add(T value) { } public int ToHashCode() => 0; } } @@ -3729,23 +3261,17 @@ public override int GetHashCode() return !(left == right); } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39916")] - public async Task TestGetHashCodeSystemHashCodeNineMembers_Explicit() - { - var code = - """ + public Task TestGetHashCodeSystemHashCodeNineMembers_Explicit() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; namespace System { public struct HashCode { public void Add(T value) { } public int ToHashCode() => 0; } } @@ -3753,9 +3279,8 @@ struct S { [|int j, k, l, m, n, o, p, q, r;|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System; using System.Collections.Generic; namespace System { public struct HashCode { public void Add(T value) { } public int ToHashCode() => 0; } } @@ -3807,22 +3332,15 @@ public override int GetHashCode() return !(left == right); } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferExplicitTypeWithInfo() }, }.RunAsync(); - } [Fact] - public async Task TestEqualsSingleField_Patterns() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestEqualsSingleField_Patterns() + => VerifyCS.VerifyRefactoringAsync( """ using System.Collections.Generic; @@ -3845,12 +3363,10 @@ public override bool Equals(object obj) } } """); - } [Fact] - public async Task TestEqualsSingleFieldInStruct_Patterns() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestEqualsSingleFieldInStruct_Patterns() + => VerifyCS.VerifyRefactoringAsync( """ using System.Collections.Generic; @@ -3888,13 +3404,12 @@ public bool Equals(Program other) } } """); - } [Fact] - public async Task TestEqualsBaseWithOverriddenEquals_Patterns() - { - var code = - """ + public Task TestEqualsBaseWithOverriddenEquals_Patterns() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Base @@ -3911,9 +3426,8 @@ class Program : Base string S { get; }|] } - """; - var fixedCode = - """ + """, + FixedCode = """ using System.Collections.Generic; class Base @@ -3938,50 +3452,26 @@ public override bool Equals(object obj) S == program.S; } } - """; - - await new VerifyCS.Test - { - TestCode = code, - FixedCode = fixedCode, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33601")] - public async Task TestPartialSelection() - { - var code = - """ + public Task TestPartialSelection() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Generic; class Program { int [|a|]; } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40053")] public async Task TestEqualityOperatorsNullableAnnotationWithReferenceType() { - var code = - """ - #nullable enable - using System; - - namespace N - { - public class C[||] - { - public int X; - } - } - """; var fixedCode = """ #nullable enable @@ -4015,7 +3505,18 @@ public override bool Equals(object? obj) await new TestWithDialog { - TestCode = code, + TestCode = """ + #nullable enable + using System; + + namespace N + { + public class C[||] + { + public int X; + } + } + """, FixedState = { Sources = { fixedCode }, @@ -4035,10 +3536,10 @@ public override bool Equals(object? obj) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40053")] - public async Task TestEqualityOperatorsNullableAnnotationWithValueType() - { - var code = - """ + public Task TestEqualityOperatorsNullableAnnotationWithValueType() + => new TestWithDialog + { + TestCode = """ #nullable enable using System; @@ -4049,9 +3550,8 @@ public struct C[||] public int X; } } - """; - var fixedCode = - """ + """, + FixedCode = """ #nullable enable using System; @@ -4078,23 +3578,16 @@ public override bool Equals(object? obj) } } } - """; - - await new TestWithDialog - { - TestCode = code, - FixedCode = fixedCode, + """, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId), LanguageVersion = LanguageVersion.Default, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42574")] - public async Task TestPartialTypes1() - { - await new TestWithDialog + public Task TestPartialTypes1() + => new TestWithDialog { TestState = { @@ -4149,12 +3642,10 @@ partial class Goo MemberNames = ["bar"], CodeActionIndex = 1, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42574")] - public async Task TestPartialTypes2() - { - await new TestWithDialog + public Task TestPartialTypes2() + => new TestWithDialog { TestState = { @@ -4207,12 +3698,10 @@ public override int GetHashCode() MemberNames = ["bar"], CodeActionIndex = 1, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42574")] - public async Task TestPartialTypes3() - { - await new TestWithDialog + public Task TestPartialTypes3() + => new TestWithDialog { TestState = { @@ -4265,12 +3754,10 @@ partial class Goo MemberNames = ["bar"], CodeActionIndex = 1, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42574")] - public async Task TestPartialTypes4() - { - await new TestWithDialog + public Task TestPartialTypes4() + => new TestWithDialog { TestState = { @@ -4325,28 +3812,10 @@ public override int GetHashCode() MemberNames = ["bar"], CodeActionIndex = 1, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43290")] public async Task TestAbstractBase() { - var code = - """ - #nullable enable - - namespace System { public struct HashCode { } } - - abstract class Base - { - public abstract override bool Equals(object? obj); - public abstract override int GetHashCode(); - } - - class {|CS0534:{|CS0534:Derived|}|} : Base - { - [|public int P { get; }|] - } - """; var fixedCode = """ #nullable enable @@ -4380,7 +3849,22 @@ public override int GetHashCode() await new VerifyCS.Test { - TestCode = code, + TestCode = """ + #nullable enable + + namespace System { public struct HashCode { } } + + abstract class Base + { + public abstract override bool Equals(object? obj); + public abstract override int GetHashCode(); + } + + class {|CS0534:{|CS0534:Derived|}|} : Base + { + [|public int P { get; }|] + } + """, FixedState = { Sources = { fixedCode }, @@ -4396,9 +3880,8 @@ public override int GetHashCode() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76916")] - public async Task TestMissingWithPrimaryConstructorAndNoFields() - { - await new VerifyCS.Test + public Task TestMissingWithPrimaryConstructorAndNoFields() + => new VerifyCS.Test { TestCode = """ class C(int a) @@ -4408,5 +3891,4 @@ class C(int a) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/GenerateType/GenerateTypeTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/GenerateType/GenerateTypeTests.cs index b7dc77d7c9d8c..d42de6fa6e5d1 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/GenerateType/GenerateTypeTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/GenerateType/GenerateTypeTests.cs @@ -41,9 +41,8 @@ protected override TestComposition GetComposition() #region Generics [Fact] - public async Task TestGenerateTypeParameterFromArgumentInferT() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateTypeParameterFromArgumentInferT() + => TestInRegularAndScriptAsync( """ class Program { @@ -67,12 +66,10 @@ internal class Goo } """, index: 1); - } [Fact] - public async Task TestGenerateClassFromTypeParameter() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateClassFromTypeParameter() + => TestInRegularAndScriptAsync( """ class Class { @@ -90,12 +87,10 @@ private class Employee } """, index: 2); - } [Fact] - public async Task TestGenerateInternalClassFromASingleConstraintClause() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInternalClassFromASingleConstraintClause() + => TestInRegularAndScriptAsync( """ class EmployeeList where T : [|Employee|], new() { @@ -111,12 +106,10 @@ internal class Employee } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18240")] - public async Task TestGeneratePublicClassFromASingleConstraintClause() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePublicClassFromASingleConstraintClause() + => TestInRegularAndScriptAsync( """ public class EmployeeList where T : [|Employee|], new() { @@ -132,23 +125,19 @@ public class Employee } """, index: 1); - } [Fact] - public async Task NegativeTestGenerateClassFromConstructorConstraint() - { - await TestMissingInRegularAndScriptAsync( + public Task NegativeTestGenerateClassFromConstructorConstraint() + => TestMissingInRegularAndScriptAsync( """ class EmployeeList where T : Employee, [|new()|] { } """); - } [Fact] - public async Task TestGenerateInternalClassFromMultipleTypeConstraintClauses() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInternalClassFromMultipleTypeConstraintClauses() + => TestInRegularAndScriptAsync( """ class Derived where U : struct @@ -168,12 +157,10 @@ internal class Base } """, index: 1); - } [Fact] - public async Task TestGeneratePublicClassFromMultipleTypeConstraintClauses() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePublicClassFromMultipleTypeConstraintClauses() + => TestInRegularAndScriptAsync( """ public class Derived where U : struct @@ -193,12 +180,10 @@ public class Base } """, index: 1); - } [Fact] - public async Task NegativeTestGenerateClassFromClassOrStructConstraint() - { - await TestMissingInRegularAndScriptAsync( + public Task NegativeTestGenerateClassFromClassOrStructConstraint() + => TestMissingInRegularAndScriptAsync( """ class Derived where U : [|struct|] @@ -206,12 +191,10 @@ class Derived { } """); - } [Fact] - public async Task TestAbsenceOfGenerateIntoInvokingTypeForConstraintList() - { - await TestActionCountAsync( + public Task TestAbsenceOfGenerateIntoInvokingTypeForConstraintList() + => TestActionCountAsync( """ class EmployeeList where T : [|Employee|] { @@ -219,12 +202,10 @@ class EmployeeList where T : [|Employee|] """, count: 3, parameters: new TestParameters(Options.Regular)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18240")] - public async Task TestGenerateInternalClassFromASingleConstraintClauseInterface() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInternalClassFromASingleConstraintClauseInterface() + => TestInRegularAndScriptAsync( """ interface IEmployeeList where T : [|Employee|], new() { @@ -240,12 +221,10 @@ internal class Employee } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18240")] - public async Task TestGeneratePublicClassFromASingleConstraintClausePublicInterface() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePublicClassFromASingleConstraintClausePublicInterface() + => TestInRegularAndScriptAsync( """ public interface IEmployeeList where T : [|Employee|], new() { @@ -261,12 +240,10 @@ public class Employee } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18240")] - public async Task TestGenerateInternalClassFromASingleConstraintClauseInternalDelegate() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInternalClassFromASingleConstraintClauseInternalDelegate() + => TestInRegularAndScriptAsync( """ class Employee { @@ -284,12 +261,10 @@ internal class Command } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18240")] - public async Task TestGenerateInternalClassFromASingleConstraintClausePublicDelegate() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInternalClassFromASingleConstraintClausePublicDelegate() + => TestInRegularAndScriptAsync( """ class Employee { @@ -307,12 +282,10 @@ internal class Command } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18240")] - public async Task TestGenerateInternalClassFromASingleConstraintClauseInternalMethod() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInternalClassFromASingleConstraintClauseInternalMethod() + => TestInRegularAndScriptAsync( """ class Employee { @@ -330,12 +303,10 @@ internal class Command } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18240")] - public async Task TestGenerateInternalClassFromASingleConstraintClausePublicMethod() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInternalClassFromASingleConstraintClausePublicMethod() + => TestInRegularAndScriptAsync( """ class Employee { @@ -353,12 +324,10 @@ internal class Command } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18240")] - public async Task TestGenerateInternalClassFromASingleConstraintClauseMethod() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInternalClassFromASingleConstraintClauseMethod() + => TestInRegularAndScriptAsync( """ class Employee { @@ -376,12 +345,10 @@ internal class Command } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18240")] - public async Task TestGenerateInternalClassFromASingleConstraintClauseMethodInInterface() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInternalClassFromASingleConstraintClauseMethodInInterface() + => TestInRegularAndScriptAsync( """ interface Employee { @@ -399,7 +366,6 @@ internal class Command } """, index: 1); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/18240")] [InlineData("public", "internal", "internal")] @@ -410,9 +376,8 @@ internal class Command [InlineData("protected internal", "protected", "public")] [InlineData("protected", "protected private", "internal")] [InlineData("protected private", "protected", "internal")] - public async Task TestGenerateInternalClassFromASingleConstraintClauseNestedClass(string middleAccessibility, string accessibility, string generatedAccessibility) - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInternalClassFromASingleConstraintClauseNestedClass(string middleAccessibility, string accessibility, string generatedAccessibility) + => TestInRegularAndScriptAsync( $$""" public class A { @@ -442,16 +407,14 @@ public class A } """, index: 1); - } #endregion #region Lambdas [Fact] - public async Task TestGenerateClassFromParenthesizedLambdaExpressionsParameter() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateClassFromParenthesizedLambdaExpressionsParameter() + => TestInRegularAndScriptAsync( """ class Class { @@ -469,12 +432,10 @@ private class Employee } """, index: 2); - } [Fact] - public async Task TestGenerateClassFromParenthesizedLambdaExpressionsBody() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateClassFromParenthesizedLambdaExpressionsBody() + => TestInRegularAndScriptAsync( """ class Class { @@ -496,14 +457,12 @@ private class Wage } """, index: 2); - } #endregion [Fact] - public async Task TestGenerateClassFromFieldDeclarationIntoSameType() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateClassFromFieldDeclarationIntoSameType() + => TestInRegularAndScriptAsync( """ class Class { @@ -521,12 +480,10 @@ private class Goo } """, index: 2); - } [Fact] - public async Task TestGenerateClassFromNullableFieldDeclarationIntoSameType() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateClassFromNullableFieldDeclarationIntoSameType() + => TestInRegularAndScriptAsync( """ #nullable enable class Class @@ -546,12 +503,10 @@ private class Goo } """, index: 2); - } [WpfFact] - public async Task TestGenerateClassFromFieldDeclarationIntoGlobalNamespace() - { - await TestAddDocumentInRegularAndScriptAsync( + public Task TestGenerateClassFromFieldDeclarationIntoGlobalNamespace() + => TestAddDocumentInRegularAndScriptAsync( @"class Program { void Main ( ) { [|Goo|] f ; } } ", """ internal class Goo @@ -560,12 +515,10 @@ internal class Goo """, expectedContainers: [], expectedDocumentName: "Goo.cs"); - } [WpfFact] - public async Task TestGenerateClassFromFieldDeclarationIntoCustomNamespace() - { - await TestAddDocumentInRegularAndScriptAsync( + public Task TestGenerateClassFromFieldDeclarationIntoCustomNamespace() + => TestAddDocumentInRegularAndScriptAsync( @"class Class { [|TestNamespace|].Goo f; }", """ namespace TestNamespace @@ -577,12 +530,10 @@ internal class Goo """, expectedContainers: ["TestNamespace"], expectedDocumentName: "Goo.cs"); - } [Fact] - public async Task TestGenerateClassFromFieldDeclarationIntoSameNamespace() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateClassFromFieldDeclarationIntoSameNamespace() + => TestInRegularAndScriptAsync( """ class Class { @@ -600,12 +551,10 @@ internal class Goo } """, index: 1); - } [Fact] - public async Task TestGenerateClassWithCtorFromObjectCreation() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateClassWithCtorFromObjectCreation() + => TestInRegularAndScriptAsync( """ class Class { @@ -626,12 +575,10 @@ public Goo() } """, index: 2); - } [Fact] - public async Task TestGenerateClassWithCtorFromObjectCreationWithTuple() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateClassWithCtorFromObjectCreationWithTuple() + => TestInRegularAndScriptAsync( """ class Class { @@ -655,12 +602,10 @@ public Generated((int, int) value) } """, index: 2); - } [Fact] - public async Task TestGenerateClassWithCtorFromObjectCreationWithTupleWithNames() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateClassWithCtorFromObjectCreationWithTupleWithNames() + => TestInRegularAndScriptAsync( """ class Class { @@ -684,12 +629,10 @@ public Generated((int a, int b, int) value) } """, index: 2); - } [Fact] - public async Task TestGenerateClassFromBaseList() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateClassFromBaseList() + => TestInRegularAndScriptAsync( """ class Class : [|BaseClass|] { @@ -705,12 +648,10 @@ internal class BaseClass } """, index: 1); - } [Fact] - public async Task TestGenerateClassFromMethodParameters() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateClassFromMethodParameters() + => TestInRegularAndScriptAsync( """ class Class { @@ -732,12 +673,10 @@ private class Goo } """, index: 2); - } [Fact] - public async Task TestGenerateClassFromMethodReturnType() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateClassFromMethodReturnType() + => TestInRegularAndScriptAsync( """ class Class { @@ -759,12 +698,10 @@ private class Goo } """, index: 2); - } [Fact] - public async Task TestGenerateClassFromAttribute() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateClassFromAttribute() + => TestInRegularAndScriptAsync( """ class Class { @@ -790,12 +727,10 @@ private class ObsoleteAttribute : Attribute } """, index: 2); - } [Fact] - public async Task TestGenerateClassFromExpandedAttribute() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateClassFromExpandedAttribute() + => TestInRegularAndScriptAsync( """ class Class { @@ -821,12 +756,10 @@ private class ObsoleteAttribute : Attribute } """, index: 2); - } [Fact] - public async Task TestGenerateClassFromCatchClause() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateClassFromCatchClause() + => TestInRegularAndScriptAsync( """ class Class { @@ -879,12 +812,10 @@ protected ExType(SerializationInfo info, StreamingContext context) : base(info, } """, index: 2); - } [Fact] - public async Task TestGenerateClassFromThrowStatement() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateClassFromThrowStatement() + => TestInRegularAndScriptAsync( """ class Class { @@ -927,12 +858,10 @@ protected ExType(SerializationInfo info, StreamingContext context) : base(info, } """, index: 2); - } [Fact] - public async Task TestGenerateClassFromThrowStatementWithDifferentArg() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateClassFromThrowStatementWithDifferentArg() + => TestInRegularAndScriptAsync( """ class Class { @@ -982,12 +911,10 @@ protected ExType(SerializationInfo info, StreamingContext context) : base(info, } """, index: 2); - } [Fact] - public async Task TestGenerateClassFromThrowStatementWithMatchingArg() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateClassFromThrowStatementWithMatchingArg() + => TestInRegularAndScriptAsync( """ class Class { @@ -1030,7 +957,6 @@ protected ExType(SerializationInfo info, StreamingContext context) : base(info, } """, index: 2); - } [Fact] public async Task TestGenerateClassFromThrowStatementOnModernDotNet_NoObsoleteConstructor() @@ -1081,9 +1007,8 @@ public ExType(string message, Exception innerException) : base(message, innerExc } [Fact] - public async Task TestAbsenceOfGenerateIntoInvokingTypeForBaseList() - { - await TestActionCountAsync( + public Task TestAbsenceOfGenerateIntoInvokingTypeForBaseList() + => TestActionCountAsync( """ class Class : [|BaseClass|] { @@ -1091,12 +1016,10 @@ class Class : [|BaseClass|] """, count: 3, parameters: new TestParameters(Options.Regular)); - } [Fact] - public async Task TestGenerateClassFromUsingStatement() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateClassFromUsingStatement() + => TestInRegularAndScriptAsync( """ class Class { @@ -1124,12 +1047,10 @@ private class Goo } """, index: 2); - } [Fact] - public async Task TestGenerateClassFromForeachStatement() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateClassFromForeachStatement() + => TestInRegularAndScriptAsync( """ class Class { @@ -1157,12 +1078,10 @@ private class Employee } """, index: 2); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538346")] - public async Task TestGenerateClassWhereKeywordBecomesTypeName() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateClassWhereKeywordBecomesTypeName() + => TestInRegularAndScriptAsync( """ class Class { @@ -1180,12 +1099,10 @@ private class @class } """, index: 2); - } [Fact] - public async Task NegativeTestGenerateClassOnContextualKeyword() - { - await TestInRegularAndScriptAsync( + public Task NegativeTestGenerateClassOnContextualKeyword() + => TestInRegularAndScriptAsync( """ class Class { @@ -1203,7 +1120,6 @@ private class Goo } """, index: 2); - } [Fact] public async Task NegativeTestGenerateClassOnFrameworkTypes() @@ -1243,9 +1159,8 @@ void Method() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538409")] - public async Task GenerateIntoRightPart() - { - await TestInRegularAndScriptAsync( + public Task GenerateIntoRightPart() + => TestInRegularAndScriptAsync( """ partial class Class { @@ -1271,12 +1186,10 @@ private class C } """, index: 2); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538408")] - public async Task GenerateTypeIntoCompilationUnit() - { - await TestInRegularAndScriptAsync( + public Task GenerateTypeIntoCompilationUnit() + => TestInRegularAndScriptAsync( """ class Class { @@ -1302,12 +1215,10 @@ internal class C } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538408")] - public async Task GenerateTypeIntoNamespace() - { - await TestInRegularAndScriptAsync( + public Task GenerateTypeIntoNamespace() + => TestInRegularAndScriptAsync( """ namespace N { @@ -1339,12 +1250,10 @@ internal class C } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538115")] - public async Task GenerateTypeWithPreprocessor() - { - await TestInRegularAndScriptAsync( + public Task GenerateTypeWithPreprocessor() + => TestInRegularAndScriptAsync( """ class C { @@ -1368,12 +1277,10 @@ private class A } """, index: 2); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538495")] - public async Task GenerateTypeIntoContainingNamespace() - { - await TestInRegularAndScriptAsync( + public Task GenerateTypeIntoContainingNamespace() + => TestInRegularAndScriptAsync( """ namespace N { @@ -1397,12 +1304,10 @@ internal class C } """, index: 1); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538516")] - public async Task TestGenerateClassFromIntoNewNamespace() - { - await TestAddDocumentInRegularAndScriptAsync( + public Task TestGenerateClassFromIntoNewNamespace() + => TestAddDocumentInRegularAndScriptAsync( @"class Class { static void Main(string[] args) { [|N|].C c; } }", """ namespace N @@ -1414,7 +1319,6 @@ internal class C """, expectedContainers: ["N"], expectedDocumentName: "C.cs"); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538558")] public async Task NegativeTestGlobalAlias() @@ -1443,9 +1347,8 @@ void Method() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538069")] - public async Task GenerateTypeFromArrayCreation1() - { - await TestAsync( + public Task GenerateTypeFromArrayCreation1() + => TestAsync( """ class A { @@ -1470,12 +1373,10 @@ internal class C : A """, index: 1, parseOptions: null); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538069")] - public async Task GenerateTypeFromArrayCreation2() - { - await TestAsync( + public Task GenerateTypeFromArrayCreation2() + => TestAsync( """ class A { @@ -1500,12 +1401,10 @@ internal class C : A """, index: 1, parseOptions: null); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538069")] - public async Task GenerateTypeFromArrayCreation3() - { - await TestAsync( + public Task GenerateTypeFromArrayCreation3() + => TestAsync( """ class A { @@ -1530,7 +1429,6 @@ internal class C """, index: 1, parseOptions: null); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539329")] public async Task NegativeTestNotInUsingDirective() @@ -1552,9 +1450,8 @@ await TestMissingInRegularAndScriptAsync( } [Fact] - public async Task GenerateSimpleConstructor() - { - await TestInRegularAndScriptAsync( + public Task GenerateSimpleConstructor() + => TestInRegularAndScriptAsync( """ class Class { @@ -1581,12 +1478,10 @@ public T() } """, index: 1); - } [Fact] - public async Task GenerateWithValueParameter() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithValueParameter() + => TestInRegularAndScriptAsync( """ class Class { @@ -1616,12 +1511,10 @@ public T(int v) } """, index: 1); - } [Fact] - public async Task GenerateWithTwoValueParameters() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithTwoValueParameters() + => TestInRegularAndScriptAsync( """ class Class { @@ -1653,12 +1546,10 @@ public T(int v1, string v2) } """, index: 1); - } [Fact] - public async Task GenerateWithNullableParameter() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithNullableParameter() + => TestInRegularAndScriptAsync( """ #nullable enable class Class @@ -1692,12 +1583,10 @@ public T(string? s) } """, index: 1); - } [Fact] - public async Task GenerateWithNullableParameterThatIsNotNull() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithNullableParameterThatIsNotNull() + => TestInRegularAndScriptAsync( """ #nullable enable class Class @@ -1731,12 +1620,10 @@ public T(string s) } """, index: 1); - } [Fact] - public async Task GenerateWithNamedParameter() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithNamedParameter() + => TestInRegularAndScriptAsync( """ class Class { @@ -1766,12 +1653,10 @@ public T(int arg) } """, index: 1); - } [Fact] - public async Task GenerateWithRefParameter() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithRefParameter() + => TestInRegularAndScriptAsync( """ class Class { @@ -1801,12 +1686,10 @@ public T(ref int i) } """, index: 1); - } [Fact] - public async Task GenerateWithOutParameter() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithOutParameter() + => TestInRegularAndScriptAsync( """ class Class { @@ -1839,12 +1722,10 @@ public T(out int i, ref bool b, object value) } """, index: 1); - } [Fact] - public async Task GenerateWithOutParameters1() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithOutParameters1() + => TestInRegularAndScriptAsync( """ class Class { @@ -1872,12 +1753,10 @@ public T(out string s) } """, index: 1); - } [Fact] - public async Task GenerateWithOutParameters2_CSharp7() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithOutParameters2_CSharp7() + => TestInRegularAndScriptAsync( """ using System; @@ -1910,12 +1789,10 @@ public T(out DateTime d) """, index: 1, parseOptions: TestOptions.Regular7); - } [Fact] - public async Task GenerateWithOutParameters2() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithOutParameters2() + => TestInRegularAndScriptAsync( """ using System; @@ -1947,12 +1824,10 @@ public T(out DateTime d) } """, index: 1); - } [Fact] - public async Task GenerateWithOutParameters3() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithOutParameters3() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1984,12 +1859,10 @@ public T(out IList d) } """, index: 1); - } [Fact] - public async Task GenerateWithOutParameters4() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithOutParameters4() + => TestInRegularAndScriptAsync( """ class Class { @@ -2017,12 +1890,10 @@ public T(out int? d) } """, index: 1); - } [Fact] - public async Task GenerateWithOutParameters5() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithOutParameters5() + => TestInRegularAndScriptAsync( """ class Class { @@ -2050,12 +1921,10 @@ public T(out object d) } """, index: 1); - } [Fact] - public async Task GenerateWithOutParameters6_CSharp7() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithOutParameters6_CSharp7() + => TestInRegularAndScriptAsync( """ class Class { @@ -2084,12 +1953,10 @@ public T(out X d) """, index: 2, parseOptions: TestOptions.Regular7); - } [Fact] - public async Task GenerateWithOutParameters6() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithOutParameters6() + => TestInRegularAndScriptAsync( """ class Class { @@ -2117,12 +1984,10 @@ public T(out X d) } """, index: 2); - } [Fact] - public async Task GenerateWithOutParameters7() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithOutParameters7() + => TestInRegularAndScriptAsync( """ class Class where X : class { @@ -2150,12 +2015,10 @@ public T(out object d) } """, index: 1); - } [Fact] - public async Task GenerateWithOutParameters8() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithOutParameters8() + => TestInRegularAndScriptAsync( """ class Class where X : class { @@ -2183,12 +2046,10 @@ public T(out X d) } """, index: 2); - } [Fact] - public async Task GenerateWithMethod() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithMethod() + => TestInRegularAndScriptAsync( """ class Class { @@ -2220,12 +2081,10 @@ public T(Func m) } """, index: 1); - } [Fact] - public async Task GenerateWithLambda() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithLambda() + => TestInRegularAndScriptAsync( """ class Class { @@ -2257,12 +2116,10 @@ public T(Func value) } """, index: 1); - } [Fact] - public async Task GenerateWithDelegatingConstructor1() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithDelegatingConstructor1() + => TestInRegularAndScriptAsync( """ class Class { @@ -2303,12 +2160,10 @@ protected Base(int i) } """, index: 1); - } [Fact] - public async Task GenerateWithDelegatingConstructor2() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithDelegatingConstructor2() + => TestInRegularAndScriptAsync( """ class Class { @@ -2349,12 +2204,10 @@ protected Base(object i) } """, index: 1); - } [Fact] - public async Task GenerateWithDelegatingConstructor3() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithDelegatingConstructor3() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -2399,12 +2252,10 @@ protected Base(IEnumerable values) } """, index: 1); - } [Fact] - public async Task GenerateWithDelegatingConstructor4() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithDelegatingConstructor4() + => TestInRegularAndScriptAsync( """ class Class { @@ -2445,12 +2296,10 @@ protected Base(ref int o) } """, index: 1); - } [Fact] - public async Task GenerateWithDelegatingConstructor5() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithDelegatingConstructor5() + => TestInRegularAndScriptAsync( """ class Class { @@ -2493,12 +2342,10 @@ protected Base(System.Func f) } """, index: 1); - } [Fact] - public async Task GenerateWithDelegatingConstructor6() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithDelegatingConstructor6() + => TestInRegularAndScriptAsync( """ class Class { @@ -2539,12 +2386,10 @@ protected Base(out int o) } """, index: 1); - } [Fact] - public async Task GenerateWithDelegatingConstructorAssigningToNullableField() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithDelegatingConstructorAssigningToNullableField() + => TestInRegularAndScriptAsync( """ #nullable enable class Class @@ -2578,12 +2423,10 @@ class Base } """, index: 1); - } [Fact] - public async Task GenerateWithNonDelegatingConstructor1() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithNonDelegatingConstructor1() + => TestInRegularAndScriptAsync( """ class Class { @@ -2627,12 +2470,10 @@ protected Base(string i) } """, index: 1); - } [Fact] - public async Task GenerateWithNonDelegatingConstructor2() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithNonDelegatingConstructor2() + => TestInRegularAndScriptAsync( """ class Class { @@ -2676,12 +2517,10 @@ protected Base(out int o) } """, index: 1); - } [Fact] - public async Task GenerateWithNonDelegatingConstructor3() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithNonDelegatingConstructor3() + => TestInRegularAndScriptAsync( """ class Class { @@ -2724,12 +2563,10 @@ protected Base(ref int o, out bool b) } """, index: 1); - } [Fact] - public async Task GenerateWithNonDelegatingConstructor4() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithNonDelegatingConstructor4() + => TestInRegularAndScriptAsync( """ class Class { @@ -2773,12 +2610,10 @@ private Base(int i) } """, index: 1); - } [Fact] - public async Task GenerateWithCallToField1() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithCallToField1() + => TestInRegularAndScriptAsync( """ class Class { @@ -2816,12 +2651,10 @@ class Base } """, index: 1); - } [Fact] - public async Task GenerateWithCallToField2() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithCallToField2() + => TestInRegularAndScriptAsync( """ class Class { @@ -2859,12 +2692,10 @@ class Base } """, index: 1); - } [Fact] - public async Task GenerateWithCallToField3() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithCallToField3() + => TestInRegularAndScriptAsync( """ class Class { @@ -2904,12 +2735,10 @@ class Base } """, index: 1); - } [Fact] - public async Task GenerateWithCallToField4() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithCallToField4() + => TestInRegularAndScriptAsync( """ class Class { @@ -2949,12 +2778,10 @@ class Base } """, index: 1); - } [Fact] - public async Task GenerateWithCallToField5() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithCallToField5() + => TestInRegularAndScriptAsync( """ class Class { @@ -2994,12 +2821,10 @@ class Base } """, index: 1); - } [Fact] - public async Task GenerateWithCallToField6() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithCallToField6() + => TestInRegularAndScriptAsync( """ class Class { @@ -3039,12 +2864,10 @@ class Base } """, index: 1); - } [Fact] - public async Task GenerateWithCallToField7() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithCallToField7() + => TestInRegularAndScriptAsync( """ class Class { @@ -3082,12 +2905,10 @@ class Base } """, index: 1); - } [Fact] - public async Task GenerateWithCallToField7WithQualification() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithCallToField7WithQualification() + => TestInRegularAndScriptAsync( """ class Class { @@ -3126,12 +2947,10 @@ class Base """, index: 1, options: Option(CodeStyleOptions2.QualifyFieldAccess, true, NotificationOption2.Error)); - } [Fact] - public async Task GenerateWithCallToField8() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithCallToField8() + => TestInRegularAndScriptAsync( """ class Class { @@ -3171,12 +2990,10 @@ class Base } """, index: 1); - } [Fact] - public async Task GenerateWithCallToField9() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithCallToField9() + => TestInRegularAndScriptAsync( """ class Class { @@ -3216,12 +3033,10 @@ class Base } """, index: 1); - } [Fact] - public async Task GenerateWithCallToField10() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithCallToField10() + => TestInRegularAndScriptAsync( """ class Class { @@ -3267,7 +3082,6 @@ class B protected int i } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49924")] public async Task GenerateCorrectFieldNaming() @@ -3307,9 +3121,8 @@ public D(int i) } [Fact] - public async Task GenerateWithCallToProperty1() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithCallToProperty1() + => TestInRegularAndScriptAsync( """ class Class { @@ -3349,12 +3162,10 @@ class Base } """, index: 1); - } [Fact] - public async Task GenerateWithCallToProperty2() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithCallToProperty2() + => TestInRegularAndScriptAsync( """ class Class { @@ -3392,12 +3203,10 @@ class Base } """, index: 1); - } [Fact] - public async Task GenerateWithCallToProperty2WithQualification() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithCallToProperty2WithQualification() + => TestInRegularAndScriptAsync( """ class Class { @@ -3436,12 +3245,10 @@ class Base """, index: 1, options: Option(CodeStyleOptions2.QualifyPropertyAccess, true, NotificationOption2.Error)); - } [Fact] - public async Task GenerateWithCallToProperty3() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithCallToProperty3() + => TestInRegularAndScriptAsync( """ class Class { @@ -3479,12 +3286,10 @@ class Base } """, index: 1); - } [Fact] - public async Task GenerateWithCallToProperty3WithQualification() - { - await TestInRegularAndScriptAsync( + public Task GenerateWithCallToProperty3WithQualification() + => TestInRegularAndScriptAsync( """ class Class { @@ -3523,12 +3328,10 @@ class Base """, index: 1, options: Option(CodeStyleOptions2.QualifyPropertyAccess, true, NotificationOption2.Error)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] - public async Task GenerateTypeWithPreferIntrinsicPredefinedKeywordFalse() - { - await TestInRegularAndScriptAsync( + public Task GenerateTypeWithPreferIntrinsicPredefinedKeywordFalse() + => TestInRegularAndScriptAsync( """ class Class { void M(int i) @@ -3557,16 +3360,14 @@ public T(System.Int32 i) """, index: 1, options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Error)); - } #endregion #region Generate Interface [Fact] - public async Task TestGenerateInterfaceFromTypeConstraint() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInterfaceFromTypeConstraint() + => TestInRegularAndScriptAsync( """ class EmployeeList where T : Employee, [|IEmployee|], new() { @@ -3582,12 +3383,10 @@ internal interface IEmployee } """, index: 1); - } [Fact] - public async Task TestGenerateInterfaceFromTypeConstraints() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInterfaceFromTypeConstraints() + => TestInRegularAndScriptAsync( """ class EmployeeList where T : Employee, IEmployee, [|IComparable|], new() { @@ -3603,12 +3402,10 @@ await TestInRegularAndScriptAsync( } """, index: 1); - } [Fact] - public async Task NegativeTestGenerateInterfaceFromTypeConstraint() - { - await TestMissingInRegularAndScriptAsync( + public Task NegativeTestGenerateInterfaceFromTypeConstraint() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -3616,12 +3413,10 @@ await TestMissingInRegularAndScriptAsync( { } """); - } [Fact] - public async Task TestGenerateInterfaceFromBaseList1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInterfaceFromBaseList1() + => TestInRegularAndScriptAsync( """ interface A : [|B|] { @@ -3637,12 +3432,10 @@ internal interface B } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538519")] - public async Task TestGenerateInterfaceFromBaseList2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInterfaceFromBaseList2() + => TestInRegularAndScriptAsync( """ class Test : [|ITest|] { @@ -3658,12 +3451,10 @@ internal interface ITest } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538519")] - public async Task TestGenerateInterfaceFromTypeConstraints2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInterfaceFromTypeConstraints2() + => TestInRegularAndScriptAsync( """ class Test where T : [|ITest|] { @@ -3679,12 +3470,10 @@ internal interface ITest } """, index: 1); - } [Fact] - public async Task TestGenerateInterfaceFromBaseList3() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInterfaceFromBaseList3() + => TestInRegularAndScriptAsync( """ class A : object, [|B|] { @@ -3700,14 +3489,12 @@ internal interface B } """, index: 1); - } #endregion [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539339")] - public async Task NotInLeftSideOfAssignment() - { - await TestMissingInRegularAndScriptAsync( + public Task NotInLeftSideOfAssignment() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -3717,12 +3504,10 @@ void M(int i) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539339")] - public async Task InLeftSideOfAssignment() - { - await TestInRegularAndScriptAsync( + public Task InLeftSideOfAssignment() + => TestInRegularAndScriptAsync( """ class Class { @@ -3746,12 +3531,10 @@ internal class Goo } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539339")] - public async Task NotInRightSideOfAssignment() - { - await TestMissingInRegularAndScriptAsync( + public Task NotInRightSideOfAssignment() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -3761,12 +3544,10 @@ void M(int i) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539339")] - public async Task InRightSideOfAssignment() - { - await TestInRegularAndScriptAsync( + public Task InRightSideOfAssignment() + => TestInRegularAndScriptAsync( """ class Class { @@ -3790,12 +3571,10 @@ internal class Goo } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] - public async Task TestEscapedName() - { - await TestInRegularAndScriptAsync( + public Task TestEscapedName() + => TestInRegularAndScriptAsync( """ class Class { @@ -3813,12 +3592,10 @@ internal class Goo } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] - public async Task TestEscapedKeyword() - { - await TestInRegularAndScriptAsync( + public Task TestEscapedKeyword() + => TestInRegularAndScriptAsync( """ class Class { @@ -3836,12 +3613,10 @@ internal class @int } """, index: 1); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539535")] - public async Task TestGenerateIntoNewFile() - { - await TestAddDocumentInRegularAndScriptAsync( + public Task TestGenerateIntoNewFile() + => TestAddDocumentInRegularAndScriptAsync( @"class Class { void F() { new [|Goo|].Bar(); } }", """ namespace Goo @@ -3856,12 +3631,10 @@ public Bar() """, expectedContainers: ["Goo"], expectedDocumentName: "Bar.cs"); - } [WpfFact] - public async Task TestGenerateIntoNewFileWithUsings1() - { - await TestAddDocumentInRegularAndScriptAsync( + public Task TestGenerateIntoNewFileWithUsings1() + => TestAddDocumentInRegularAndScriptAsync( @"class Class { void F() { new [|Goo|].Bar(new System.Collections.Generic.List()); } }", """ using System.Collections.Generic; @@ -3881,12 +3654,10 @@ public Bar(List list) """, expectedContainers: ["Goo"], expectedDocumentName: "Bar.cs"); - } [WpfFact] - public async Task TestGenerateIntoNewFileWithUsings2() - { - await TestAddDocumentInRegularAndScriptAsync( + public Task TestGenerateIntoNewFileWithUsings2() + => TestAddDocumentInRegularAndScriptAsync( @"class Class { void F() { new [|Goo|].Bar(new System.Collections.Generic.List()); } }", """ namespace Goo @@ -3907,12 +3678,10 @@ public Bar(List list) expectedContainers: ["Goo"], expectedDocumentName: "Bar.cs", parameters: new TestParameters(options: Option(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, AddImportPlacement.InsideNamespace, NotificationOption2.Error))); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539620")] - public async Task TestDeclarationSpan() - { - await TestSpansAsync( + public Task TestDeclarationSpan() + => TestSpansAsync( """ class Class { @@ -3922,23 +3691,19 @@ void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539674")] - public async Task TestNotInEnumBaseList() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotInEnumBaseList() + => TestMissingInRegularAndScriptAsync( """ enum E : [|A|] { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539681")] - public async Task TestNotInConditional() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotInConditional() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -3950,12 +3715,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestInUsing() - { - await TestInRegularAndScriptAsync( + public Task TestInUsing() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -3991,12 +3754,10 @@ internal class Goo } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/pull/54493")] - public async Task TestInLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestInLocalFunction() + => TestInRegularAndScriptAsync( """ using System; @@ -4024,12 +3785,10 @@ internal class Goo } """, index: 1); - } [Fact] - public async Task TestNotInDelegateConstructor() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotInDelegateConstructor() + => TestMissingInRegularAndScriptAsync( """ delegate void D(int x); @@ -4041,12 +3800,10 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539754")] - public async Task TestMissingOnVar() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnVar() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -4060,12 +3817,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539765")] - public async Task TestElideDefaultConstructor() - { - await TestInRegularAndScriptAsync( + public Task TestElideDefaultConstructor() + => TestInRegularAndScriptAsync( """ class A { @@ -4097,20 +3852,16 @@ internal class C } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539783")] - public async Task RegressionFor5867ErrorToleranceTopLevel() - { - await TestMissingAsync( + public Task RegressionFor5867ErrorToleranceTopLevel() + => TestMissingAsync( @"[|this|] . f = f ; ", new TestParameters(GetScriptOptions())); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539799")] - public async Task TestOnInaccessibleType() - { - await TestMissingInRegularAndScriptAsync( + public Task TestOnInaccessibleType() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -4127,12 +3878,10 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539794")] - public async Task TestDefaultConstructorInTypeDerivingFromInterface() - { - await TestInRegularAndScriptAsync( + public Task TestDefaultConstructorInTypeDerivingFromInterface() + => TestInRegularAndScriptAsync( """ class Program { @@ -4164,12 +3913,10 @@ interface I } """, index: 1); - } [Fact] - public async Task TestGenerateWithThrow() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateWithThrow() + => TestInRegularAndScriptAsync( """ using System; @@ -4214,12 +3961,10 @@ protected NotFoundException(SerializationInfo info, StreamingContext context) : } """, index: 1); - } [Fact] - public async Task TestGenerateInTryCatch() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInTryCatch() + => TestInRegularAndScriptAsync( """ using System; @@ -4274,13 +4019,11 @@ protected NotFoundException(SerializationInfo info, StreamingContext context) : } """, index: 1); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539739")] - public async Task TestNotGenerateInDelegateConstructor() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotGenerateInDelegateConstructor() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4294,12 +4037,10 @@ void M() } } """); - } [Fact] - public async Task TestInStructBaseList() - { - await TestInRegularAndScriptAsync( + public Task TestInStructBaseList() + => TestInRegularAndScriptAsync( """ struct S : [|A|] { @@ -4315,12 +4056,10 @@ internal interface A } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539870")] - public async Task TestGenericWhenNonGenericExists() - { - await TestInRegularAndScriptAsync( + public Task TestGenericWhenNonGenericExists() + => TestInRegularAndScriptAsync( """ class C { @@ -4352,12 +4091,10 @@ class A } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539930")] - public async Task TestInheritedTypeParameters() - { - await TestInRegularAndScriptAsync( + public Task TestInheritedTypeParameters() + => TestInRegularAndScriptAsync( """ class C { @@ -4389,12 +4126,10 @@ interface I } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539971")] - public async Task TestDoNotUseOuterTypeParameters() - { - await TestInRegularAndScriptAsync( + public Task TestDoNotUseOuterTypeParameters() + => TestInRegularAndScriptAsync( """ class C { @@ -4418,12 +4153,10 @@ private class D } """, index: 2); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539970")] - public async Task TestReferencingTypeParameters1() - { - await TestInRegularAndScriptAsync( + public Task TestReferencingTypeParameters1() + => TestInRegularAndScriptAsync( """ class M { @@ -4455,12 +4188,10 @@ interface I } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539970")] - public async Task TestReferencingTypeParameters2() - { - await TestInRegularAndScriptAsync( + public Task TestReferencingTypeParameters2() + => TestInRegularAndScriptAsync( """ class M { @@ -4492,12 +4223,10 @@ interface I } """, index: 2); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539972")] - public async Task TestReferencingTypeParameters3() - { - await TestInRegularAndScriptAsync( + public Task TestReferencingTypeParameters3() + => TestInRegularAndScriptAsync( """ class C { @@ -4529,12 +4258,10 @@ public A(object t1, object t2) } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539972")] - public async Task TestReferencingTypeParameters4() - { - await TestInRegularAndScriptAsync( + public Task TestReferencingTypeParameters4() + => TestInRegularAndScriptAsync( """ class C { @@ -4566,12 +4293,10 @@ public A(T1 t1, T2 t2) } """, index: 2); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539992")] - public async Task TestNotPassingEmptyIssueListToCtor() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotPassingEmptyIssueListToCtor() + => TestMissingInRegularAndScriptAsync( """ using System.Linq; @@ -4582,12 +4307,10 @@ void Main() Enumerable.[|T|] Enumerable . Select(Enumerable.Range(0, 9), i => char.Parse(i.ToString())) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540644")] - public async Task TestGenerateWithVoidArg() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateWithVoidArg() + => TestInRegularAndScriptAsync( """ class Program { @@ -4617,12 +4340,10 @@ public C(object v) } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540989")] - public async Task TestMissingOnInaccessibleType() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnInaccessibleType() + => TestMissingInRegularAndScriptAsync( """ class Outer { @@ -4636,12 +4357,10 @@ class A Outer.[|Inner|] inner; } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540766")] - public async Task TestOnInvalidGlobalCode() - { - await TestInRegularAndScriptAsync( + public Task TestOnInvalidGlobalCode() + => TestInRegularAndScriptAsync( @"[|a|] test ", """ [|a|] test internal class a @@ -4649,12 +4368,10 @@ await TestInRegularAndScriptAsync( } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539985")] - public async Task TestDoNotInferTypeWithWrongArity() - { - await TestInRegularAndScriptAsync( + public Task TestDoNotInferTypeWithWrongArity() + => TestInRegularAndScriptAsync( """ class C { @@ -4681,12 +4398,10 @@ public C() } """, index: 1); - } [Fact] - public async Task TestMissingOnInvalidConstructorToExistingType() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnInvalidConstructorToExistingType() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -4696,12 +4411,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541263")] - public async Task TestAccessibilityConstraint() - { - await TestInRegularAndScriptAsync( + public Task TestAccessibilityConstraint() + => TestInRegularAndScriptAsync( """ public static class MyExtension { @@ -4725,12 +4438,10 @@ public class D } """, index: 1); - } [Fact] - public async Task TestBaseTypeAccessibilityConstraint() - { - await TestInRegularAndScriptAsync( + public Task TestBaseTypeAccessibilityConstraint() + => TestInRegularAndScriptAsync( """ public class C : [|D|] { @@ -4746,12 +4457,10 @@ public class D } """, index: 1); - } [Fact] - public async Task TestBaseInterfaceAccessibilityConstraint1() - { - await TestInRegularAndScriptAsync( + public Task TestBaseInterfaceAccessibilityConstraint1() + => TestInRegularAndScriptAsync( """ public class C : X, [|IGoo|] { @@ -4767,12 +4476,10 @@ internal interface IGoo } """, index: 1); - } [Fact] - public async Task TestAccessibilityConstraint2() - { - await TestInRegularAndScriptAsync( + public Task TestAccessibilityConstraint2() + => TestInRegularAndScriptAsync( """ public interface C : [|IBar|], IGoo { @@ -4788,12 +4495,10 @@ public interface IBar } """, index: 1); - } [Fact] - public async Task TestAccessibilityConstraint3() - { - await TestInRegularAndScriptAsync( + public Task TestAccessibilityConstraint3() + => TestInRegularAndScriptAsync( """ public interface C : IBar, [|IGoo|] { @@ -4809,12 +4514,10 @@ public interface IGoo } """, index: 1); - } [Fact] - public async Task TestDelegateReturnTypeAccessibilityConstraint() - { - await TestInRegularAndScriptAsync( + public Task TestDelegateReturnTypeAccessibilityConstraint() + => TestInRegularAndScriptAsync( @"public delegate [|D|] Goo();", """ public delegate D Goo(); @@ -4824,12 +4527,10 @@ public class D } """, index: 1); - } [Fact] - public async Task TestDelegateParameterAccessibilityConstraint() - { - await TestInRegularAndScriptAsync( + public Task TestDelegateParameterAccessibilityConstraint() + => TestInRegularAndScriptAsync( @"public delegate D Goo([|S|] d);", """ public delegate D Goo(S d); @@ -4839,12 +4540,10 @@ public class S } """, index: 1); - } [Fact] - public async Task TestMethodParameterAccessibilityConstraint() - { - await TestInRegularAndScriptAsync( + public Task TestMethodParameterAccessibilityConstraint() + => TestInRegularAndScriptAsync( """ public class C { @@ -4862,12 +4561,10 @@ public class F } """, index: 1); - } [Fact] - public async Task TestMethodReturnTypeAccessibilityConstraint() - { - await TestInRegularAndScriptAsync( + public Task TestMethodReturnTypeAccessibilityConstraint() + => TestInRegularAndScriptAsync( """ public class C { @@ -4885,12 +4582,10 @@ public class F } """, index: 2); - } [Fact] - public async Task TestPropertyTypeAccessibilityConstraint() - { - await TestInRegularAndScriptAsync( + public Task TestPropertyTypeAccessibilityConstraint() + => TestInRegularAndScriptAsync( """ public class C { @@ -4908,12 +4603,10 @@ public class F } """, index: 2); - } [Fact] - public async Task TestFieldEventTypeAccessibilityConstraint() - { - await TestInRegularAndScriptAsync( + public Task TestFieldEventTypeAccessibilityConstraint() + => TestInRegularAndScriptAsync( """ public class C { @@ -4931,12 +4624,10 @@ public class F } """, index: 2); - } [Fact] - public async Task TestEventTypeAccessibilityConstraint() - { - await TestInRegularAndScriptAsync( + public Task TestEventTypeAccessibilityConstraint() + => TestInRegularAndScriptAsync( """ public class C { @@ -4972,12 +4663,10 @@ public class F } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541654")] - public async Task TestGenerateVarType() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateVarType() + => TestInRegularAndScriptAsync( """ class C { @@ -5001,12 +4690,10 @@ internal class var } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541641")] - public async Task TestOnBadAttribute() - { - await TestInRegularAndScriptAsync( + public Task TestOnBadAttribute() + => TestInRegularAndScriptAsync( """ [[|AttClass|]()] class C @@ -5034,12 +4721,10 @@ internal class AttClassAttribute } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542528")] - public async Task TestGenerateStruct1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateStruct1() + => TestInRegularAndScriptAsync( """ using System; @@ -5075,12 +4760,10 @@ internal struct S } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542480")] - public async Task TestCopyConstraints1() - { - await TestInRegularAndScriptAsync( + public Task TestCopyConstraints1() + => TestInRegularAndScriptAsync( """ class A where T : class { @@ -5112,12 +4795,10 @@ internal class B : A where T : class } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542528")] - public async Task TestGenerateStruct2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateStruct2() + => TestInRegularAndScriptAsync( """ using System; @@ -5152,12 +4833,10 @@ private struct S } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542528")] - public async Task TestGenerateStruct3() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateStruct3() + => TestInRegularAndScriptAsync( """ using System; @@ -5192,12 +4871,10 @@ private struct S } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542761")] - public async Task TestGenerateOpenType1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateOpenType1() + => TestInRegularAndScriptAsync( """ class Program { @@ -5221,12 +4898,10 @@ internal class C } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542766")] - public async Task TestGenerateAttributeInGenericType() - { - await TestActionCountAsync( + public Task TestGenerateAttributeInGenericType() + => TestActionCountAsync( """ using System; @@ -5239,12 +4914,10 @@ void Goo() } """, count: 6); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543061")] - public async Task TestNestedGenericAccessibility() - { - await TestInRegularAndScriptAsync( + public Task TestNestedGenericAccessibility() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -5270,7 +4943,6 @@ public class NewClass } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543493")] public async Task MissingIfNotInTypeStatementOrExpressionContext() @@ -5305,9 +4977,8 @@ a b c [|d|] } } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542641")] - public async Task TestAttributeSuffixOnAttributeSubclasses() - { - await TestInRegularAndScriptAsync( + public Task TestAttributeSuffixOnAttributeSubclasses() + => TestInRegularAndScriptAsync( """ using System.Runtime.CompilerServices; @@ -5335,20 +5006,16 @@ internal class GooAttribute : CustomConstantAttribute } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543853")] - public async Task TestDisplayStringForGlobalNamespace() - { - await TestSmartTagTextAsync( + public Task TestDisplayStringForGlobalNamespace() + => TestSmartTagTextAsync( @"class C : [|Goo|]", string.Format(FeaturesResources.Generate_0_1_in_new_file, "class", "Goo")); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543853")] - public async Task TestAddDocumentForGlobalNamespace() - { - await TestAddDocumentInRegularAndScriptAsync( + public Task TestAddDocumentForGlobalNamespace() + => TestAddDocumentInRegularAndScriptAsync( @"class C : [|Goo|]", """ internal class Goo @@ -5357,12 +5024,10 @@ internal class Goo """, [], "Goo.cs"); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543886")] - public async Task TestVerbatimAttribute() - { - await TestInRegularAndScriptAsync( + public Task TestVerbatimAttribute() + => TestInRegularAndScriptAsync( """ [[|@X|]] class Class3 @@ -5382,12 +5047,10 @@ internal class X : Attribute } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531220")] - public async Task CompareIncompleteMembersToEqual() - { - await TestInRegularAndScriptAsync( + public Task CompareIncompleteMembersToEqual() + => TestInRegularAndScriptAsync( """ class C { @@ -5415,12 +5078,10 @@ X void X TestMissingInRegularAndScriptAsync( """ abstract class Goo { @@ -5434,7 +5095,6 @@ void goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545362")] public async Task TestGenerateInVenus1() @@ -5481,9 +5141,8 @@ private class Goo } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/869506")] - public async Task TestGenerateTypeOutsideCurrentProject() - { - var code = """ + public Task TestGenerateTypeOutsideCurrentProject() + => TestInRegularAndScriptAsync(""" Assembly2 @@ -5509,9 +5168,7 @@ public class B } - """; - - var expected = """ + """, """ namespace A { public class B @@ -5521,15 +5178,11 @@ public class C } } } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932602")] - public async Task TestGenerateTypeInFolderNotDefaultNamespace_0() - { - var code = """ + public Task TestGenerateTypeInFolderNotDefaultNamespace_0() + => TestAddDocumentInRegularAndScriptAsync(""" @@ -5542,27 +5195,21 @@ public class ClassA : [|$$ClassB|] - """; - - var expected = """ + """, + """ namespace Namespace1.Namespace2 { public class ClassB { } } - """; - - await TestAddDocumentInRegularAndScriptAsync(code, - expected, + """, expectedContainers: [], expectedDocumentName: "ClassB.cs"); - } [WpfFact] - public async Task TestGenerateTypeInFolderNotDefaultNamespace_0_FileScopedNamespace() - { - var code = """ + public Task TestGenerateTypeInFolderNotDefaultNamespace_0_FileScopedNamespace() + => TestAddDocumentInRegularAndScriptAsync(""" @@ -5574,29 +5221,23 @@ public class ClassA : [|$$ClassB|] - """; - - var expected = """ + """, + """ namespace Namespace1.Namespace2; public class ClassB { } - """; - - await TestAddDocumentInRegularAndScriptAsync(code, - expected, + """, expectedContainers: [], expectedDocumentName: "ClassB.cs", new TestParameters( parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10), options: Option(CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped, NotificationOption2.Silent))); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932602")] - public async Task TestGenerateTypeInFolderNotDefaultNamespace_1() - { - var code = """ + public Task TestGenerateTypeInFolderNotDefaultNamespace_1() + => TestAddDocumentInRegularAndScriptAsync(""" @@ -5609,42 +5250,30 @@ public class ClassA : [|$$ClassB|] - """; - - var expected = """ + """, + """ namespace Namespace1.Namespace2.Namespace3 { public class ClassB { } } - """; - - await TestAddDocumentInRegularAndScriptAsync(code, - expected, + """, expectedContainers: ["Namespace1", "Namespace2"], expectedDocumentName: "ClassB.cs"); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/612700")] - public async Task TestGenerateTypeWithNoBraces() - { - var code = @"class Test : [|Base|]"; - - var expected = """ + public Task TestGenerateTypeWithNoBraces() + => TestInRegularAndScriptAsync(@"class Test : [|Base|]", """ class Test : Base internal class Base { } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1); - } + """, index: 1); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/940003")] - public async Task TestWithProperties1() - { - var code = """ + public Task TestWithProperties1() + => TestInRegularAndScriptAsync(""" using System; class Program @@ -5654,9 +5283,7 @@ static void Main(string[] args) var c = new [|Customer|](x: 1, y: "Hello") {Name = "John", Age = DateTime.Today}; } } - """; - - var expected = """ + """, """ using System; class Program @@ -5681,15 +5308,11 @@ public Customer(int x, string y) public string Name { get; set; } public DateTime Age { get; set; } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1); - } + """, index: 1); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/940003")] - public async Task TestWithProperties2() - { - var code = """ + public Task TestWithProperties2() + => TestInRegularAndScriptAsync(""" using System; class Program @@ -5699,9 +5322,7 @@ static void Main(string[] args) var c = new [|Customer|](x: 1, y: "Hello") {Name = null, Age = DateTime.Today}; } } - """; - - var expected = """ + """, """ using System; class Program @@ -5726,15 +5347,11 @@ public Customer(int x, string y) public object Name { get; set; } public DateTime Age { get; set; } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1); - } + """, index: 1); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/940003")] - public async Task TestWithProperties3() - { - var code = """ + public Task TestWithProperties3() + => TestInRegularAndScriptAsync(""" using System; class Program @@ -5744,9 +5361,7 @@ static void Main(string[] args) var c = new [|Customer|](x: 1, y: "Hello") {Name = Goo, Age = DateTime.Today}; } } - """; - - var expected = """ + """, """ using System; class Program @@ -5771,15 +5386,11 @@ public Customer(int x, string y) public object Name { get; set; } public DateTime Age { get; set; } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1); - } + """, index: 1); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1082031")] - public async Task TestWithProperties4() - { - var code = """ + public Task TestWithProperties4() + => TestInRegularAndScriptAsync(""" using System; class Program @@ -5789,9 +5400,7 @@ static void Main(string[] args) var c = new [|Customer|] {Name = "John", Age = DateTime.Today}; } } - """; - - var expected = """ + """, """ using System; class Program @@ -5807,15 +5416,11 @@ internal class Customer public string Name { get; set; } public DateTime Age { get; set; } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1); - } + """, index: 1); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073099")] - public async Task TestWithNameOf() - { - var code = """ + public Task TestWithNameOf() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -5823,9 +5428,7 @@ void M() var x = nameof([|Z|]); } } - """; - - var expected = """ + """, """ class C { void M() @@ -5837,15 +5440,11 @@ void M() internal class Z { } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1); - } + """, index: 1); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073099")] - public async Task TestWithNameOf2() - { - var code = """ + public Task TestWithNameOf2() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -5853,9 +5452,7 @@ void M() var x = nameof([|C.Test|]); } } - """; - - var expected = """ + """, """ class C { void M() @@ -5867,15 +5464,11 @@ private class Test { } } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task TestWithUsingStatic() - { - await TestInRegularAndScriptAsync( + public Task TestWithUsingStatic() + => TestInRegularAndScriptAsync( @"using static [|Sample|];", """ using static Sample; @@ -5885,19 +5478,15 @@ internal class Sample } """, index: 1); - } [Fact] - public async Task TestWithUsingStatic2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithUsingStatic2() + => TestMissingInRegularAndScriptAsync( @"using [|Sample|];"); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107929")] - public async Task TestAccessibilityForPublicFields() - { - await TestInRegularAndScriptAsync( + public Task TestAccessibilityForPublicFields() + => TestInRegularAndScriptAsync( """ class A { @@ -5912,12 +5501,10 @@ public B() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107929")] - public async Task TestAccessibilityForPublicFields2() - { - await TestInRegularAndScriptAsync( + public Task TestAccessibilityForPublicFields2() + => TestInRegularAndScriptAsync( """ class A { @@ -5938,12 +5525,10 @@ public B() } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107929")] - public async Task TestAccessibilityForPublicFields3() - { - await TestInRegularAndScriptAsync( + public Task TestAccessibilityForPublicFields3() + => TestInRegularAndScriptAsync( """ class A { @@ -5964,12 +5549,10 @@ public B() } """, index: 2); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107929")] - public async Task TestAccessibilityForPublicFields4() - { - await TestInRegularAndScriptAsync( + public Task TestAccessibilityForPublicFields4() + => TestInRegularAndScriptAsync( """ class A { @@ -5984,12 +5567,10 @@ public B() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107929")] - public async Task TestAccessibilityForPublicFields5() - { - await TestInRegularAndScriptAsync( + public Task TestAccessibilityForPublicFields5() + => TestInRegularAndScriptAsync( """ class A { @@ -6010,12 +5591,10 @@ public B() } """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107929")] - public async Task TestAccessibilityForPublicFields6() - { - await TestInRegularAndScriptAsync( + public Task TestAccessibilityForPublicFields6() + => TestInRegularAndScriptAsync( """ class A { @@ -6036,12 +5615,10 @@ public B() } """, index: 2); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/17361")] - public async Task TestPreserveFileBanner1() - { - await TestAddDocumentInRegularAndScriptAsync( + public Task TestPreserveFileBanner1() + => TestAddDocumentInRegularAndScriptAsync( """ // I am a banner @@ -6062,12 +5639,10 @@ internal class Goo """, expectedContainers: [], expectedDocumentName: "Goo.cs"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/17361")] - public async Task TestPreserveFileBanner2() - { - await TestAddDocumentInRegularAndScriptAsync( + public Task TestPreserveFileBanner2() + => TestAddDocumentInRegularAndScriptAsync( """ /// I am a doc comment class Program @@ -6085,12 +5660,10 @@ internal class Goo """, expectedContainers: [], expectedDocumentName: "Goo.cs"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/17361")] - public async Task TestPreserveFileBanner3() - { - await TestAddDocumentInRegularAndScriptAsync( + public Task TestPreserveFileBanner3() + => TestAddDocumentInRegularAndScriptAsync( """ // I am a banner using System; @@ -6119,12 +5692,10 @@ public Goo(StackOverflowException e) """, expectedContainers: [], expectedDocumentName: "Goo.cs"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/17361")] - public async Task TestPreserveFileBanner4() - { - await TestAddDocumentInRegularAndScriptAsync( + public Task TestPreserveFileBanner4() + => TestAddDocumentInRegularAndScriptAsync( """ class Program { @@ -6144,14 +5715,12 @@ internal class Goo expectedContainers: [], expectedDocumentName: "Goo.cs", new TestParameters(options: Option(CodeStyleOptions2.FileHeaderTemplate, "I am a banner"))); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/22293")] [InlineData("void")] [InlineData("int")] - public async Task TestMethodGroupWithMissingSystemActionAndFunc(string returnType) - { - await TestInRegularAndScriptAsync( + public Task TestMethodGroupWithMissingSystemActionAndFunc(string returnType) + => TestInRegularAndScriptAsync( $$""" @@ -6193,12 +5762,10 @@ public Class(object method) } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/270")] - public async Task TestGenerateInIsExpression() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInIsExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -6243,12 +5810,10 @@ protected SampleType(SerializationInfo info, StreamingContext context) : base(in } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45808")] - public async Task TestGenerateUnsafe() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateUnsafe() + => TestInRegularAndScriptAsync( """ class C { @@ -6277,12 +5842,10 @@ public unsafe D(int* x) } } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40605")] - public async Task DoNoInferArrayBaseType1() - { - await TestInRegularAndScriptAsync( + public Task DoNoInferArrayBaseType1() + => TestInRegularAndScriptAsync( """ using System; @@ -6310,12 +5873,10 @@ internal class MyComparer : IComparer { } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58495")] - public async Task UseImplicitObjectInitializerToPopulateProperties() - { - await TestInRegularAndScriptAsync( + public Task UseImplicitObjectInitializerToPopulateProperties() + => TestInRegularAndScriptAsync( """ class Program { @@ -6340,5 +5901,26 @@ internal class Test public int B { get; set; } } """, index: 1); - } + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49649")] + public Task TestInTopLevelProgram() + => TestInRegularAndScriptAsync( + """ + var student = new [|Student|]("Youssef"); + Console.WriteLine(student.Name); + """, + """ + var student = new Student("Youssef"); + Console.WriteLine(student.Name); + + internal class Student + { + private string v; + + public Student(string v) + { + this.v = v; + } + } + """, index: 1); } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/GenerateType/GenerateTypeTests_Dialog.cs b/src/EditorFeatures/CSharpTest/CodeActions/GenerateType/GenerateTypeTests_Dialog.cs index df6fe69dee917..2cd78337b2069 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/GenerateType/GenerateTypeTests_Dialog.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/GenerateType/GenerateTypeTests_Dialog.cs @@ -16,1062 +16,1132 @@ public partial class GenerateTypeTests : AbstractCSharpDiagnosticProviderBasedUs #region SameProject #region SameProject_SameFile [Fact] - public async Task GenerateTypeDefaultValues() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - void Main() - { - [|Goo$$|] f; - } -}", + public Task GenerateTypeDefaultValues() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + void Main() + { + [|Goo$$|] f; + } + } + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"class Program -{ - void Main() - { - Goo f; - } -} +expected: """ + class Program + { + void Main() + { + Goo f; + } + } -class Goo -{ -}", + class Goo + { + } + """, isNewFile: false); - } [Fact] - public async Task GenerateTypeInsideNamespace() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - void Main() - { - [|A.Goo$$|] f; - } -} + public Task GenerateTypeInsideNamespace() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + void Main() + { + [|A.Goo$$|] f; + } + } -namespace A -{ -}", + namespace A + { + } + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"class Program -{ - void Main() - { - A.Goo f; - } -} +expected: """ + class Program + { + void Main() + { + A.Goo f; + } + } -namespace A -{ - class Goo - { - } -}", + namespace A + { + class Goo + { + } + } + """, isNewFile: false); - } [Fact] - public async Task GenerateTypeInsideFileScopedNamespace1() - { - await TestWithMockedGenerateTypeDialog( -initial: @" -namespace A; + public Task GenerateTypeInsideFileScopedNamespace1() + => TestWithMockedGenerateTypeDialog( +initial: """ -class Program -{ - void Main() - { - [|A.Goo$$|] f; - } -} -", + namespace A; + + class Program + { + void Main() + { + [|A.Goo$$|] f; + } + } + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @" -namespace A; +expected: """ -class Program -{ - void Main() - { - A.Goo f; - } -} + namespace A; -class Goo -{ -}", + class Program + { + void Main() + { + A.Goo f; + } + } + + class Goo + { + } + """, isNewFile: false); - } [Fact] - public async Task GenerateTypeInsideFileScopedNamespace2() - { - await TestWithMockedGenerateTypeDialog( -initial: @" -namespace A; + public Task GenerateTypeInsideFileScopedNamespace2() + => TestWithMockedGenerateTypeDialog( +initial: """ -class Program -{ - void Main() - { - [|Goo$$|] f; - } -} -", + namespace A; + + class Program + { + void Main() + { + [|Goo$$|] f; + } + } + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @" -namespace A; +expected: """ -class Program -{ - void Main() - { - Goo f; - } -} + namespace A; -class Goo -{ -}", + class Program + { + void Main() + { + Goo f; + } + } + + class Goo + { + } + """, isNewFile: false); - } [Fact] - public async Task GenerateTypeInsideQualifiedNamespace() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - void Main() - { - [|A.B.Goo$$|] f; - } -} -namespace A.B -{ -}", + public Task GenerateTypeInsideQualifiedNamespace() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + void Main() + { + [|A.B.Goo$$|] f; + } + } + namespace A.B + { + } + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"class Program -{ - void Main() - { - A.B.Goo f; - } -} -namespace A.B -{ - class Goo - { - } -}", +expected: """ + class Program + { + void Main() + { + A.B.Goo f; + } + } + namespace A.B + { + class Goo + { + } + } + """, isNewFile: false); - } [Fact] - public async Task GenerateTypeWithinQualifiedNestedNamespace() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - void Main() - { - [|A.B.C.Goo$$|] f; - } -} -namespace A.B -{ - namespace C - { - } -}", + public Task GenerateTypeWithinQualifiedNestedNamespace() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + void Main() + { + [|A.B.C.Goo$$|] f; + } + } + namespace A.B + { + namespace C + { + } + } + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"class Program -{ - void Main() - { - A.B.C.Goo f; - } -} -namespace A.B -{ - namespace C - { - class Goo - { - } - } -}", +expected: """ + class Program + { + void Main() + { + A.B.C.Goo f; + } + } + namespace A.B + { + namespace C + { + class Goo + { + } + } + } + """, isNewFile: false); - } [Fact] - public async Task GenerateTypeWithinNestedQualifiedNamespace() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - void Main() - { - [|A.B.C.Goo$$|] f; - } -} -namespace A -{ - namespace B.C - { - } -}", + public Task GenerateTypeWithinNestedQualifiedNamespace() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + void Main() + { + [|A.B.C.Goo$$|] f; + } + } + namespace A + { + namespace B.C + { + } + } + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"class Program -{ - void Main() - { - A.B.C.Goo f; - } -} -namespace A -{ - namespace B.C - { - class Goo - { - } - } -}", +expected: """ + class Program + { + void Main() + { + A.B.C.Goo f; + } + } + namespace A + { + namespace B.C + { + class Goo + { + } + } + } + """, isNewFile: false); - } [Fact] - public async Task GenerateTypeWithConstructorMembers() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - var f = new [|$$Goo|](bar: 1, baz: 2); - } -}", + public Task GenerateTypeWithConstructorMembers() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + var f = new [|$$Goo|](bar: 1, baz: 2); + } + } + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"class Program -{ - static void Main(string[] args) - { - var f = new Goo(bar: 1, baz: 2); - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + var f = new Goo(bar: 1, baz: 2); + } + } -class Goo -{ - private int bar; - private int baz; - - public Goo(int bar, int baz) - { - this.bar = bar; - this.baz = baz; - } -}", + class Goo + { + private int bar; + private int baz; + + public Goo(int bar, int baz) + { + this.bar = bar; + this.baz = baz; + } + } + """, isNewFile: false); - } [Fact] - public async Task GenerateTypeWithBaseTypes() - { - await TestWithMockedGenerateTypeDialog( -initial: @"using System.Collections.Generic; -class Program -{ - static void Main(string[] args) - { - List f = new [|$$Goo|](); - } -}", + public Task GenerateTypeWithBaseTypes() + => TestWithMockedGenerateTypeDialog( +initial: """ + using System.Collections.Generic; + class Program + { + static void Main(string[] args) + { + List f = new [|$$Goo|](); + } + } + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"using System.Collections.Generic; -class Program -{ - static void Main(string[] args) - { - List f = new Goo(); - } -} +expected: """ + using System.Collections.Generic; + class Program + { + static void Main(string[] args) + { + List f = new Goo(); + } + } -class Goo : List -{ -}", + class Goo : List + { + } + """, isNewFile: false); - } [Fact] - public async Task GenerateTypeWithPublicInterface() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - void Main() - { - [|A.B.C.Goo$$|] f; - } -} -namespace A -{ - namespace B.C - { - } -}", + public Task GenerateTypeWithPublicInterface() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + void Main() + { + [|A.B.C.Goo$$|] f; + } + } + namespace A + { + namespace B.C + { + } + } + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"class Program -{ - void Main() - { - A.B.C.Goo f; - } -} -namespace A -{ - namespace B.C - { - public interface Goo - { - } - } -}", +expected: """ + class Program + { + void Main() + { + A.B.C.Goo f; + } + } + namespace A + { + namespace B.C + { + public interface Goo + { + } + } + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false); - } [Fact] - public async Task GenerateTypeWithInternalStruct() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - void Main() - { - [|A.B.C.Goo$$|] f; - } -} -namespace A -{ - namespace B.C - { - } -}", + public Task GenerateTypeWithInternalStruct() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + void Main() + { + [|A.B.C.Goo$$|] f; + } + } + namespace A + { + namespace B.C + { + } + } + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"class Program -{ - void Main() - { - A.B.C.Goo f; - } -} -namespace A -{ - namespace B.C - { - internal struct Goo - { - } - } -}", +expected: """ + class Program + { + void Main() + { + A.B.C.Goo f; + } + } + namespace A + { + namespace B.C + { + internal struct Goo + { + } + } + } + """, accessibility: Accessibility.Internal, typeKind: TypeKind.Struct, isNewFile: false); - } [Fact] - public async Task GenerateTypeWithDefaultEnum() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - void Main() - { - [|A.B.Goo$$|] f; - } -} -namespace A -{ - namespace B - { - } -}", + public Task GenerateTypeWithDefaultEnum() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + void Main() + { + [|A.B.Goo$$|] f; + } + } + namespace A + { + namespace B + { + } + } + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"class Program -{ - void Main() - { - A.B.Goo f; - } -} -namespace A -{ - namespace B - { - enum Goo - { - } - } -}", +expected: """ + class Program + { + void Main() + { + A.B.Goo f; + } + } + namespace A + { + namespace B + { + enum Goo + { + } + } + } + """, accessibility: Accessibility.NotApplicable, typeKind: TypeKind.Enum, isNewFile: false); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateTypeWithDefaultEnum_DefaultNamespace() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - void Main() - { - [|Goo$$|] f; - } -}", + public Task GenerateTypeWithDefaultEnum_DefaultNamespace() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + void Main() + { + [|Goo$$|] f; + } + } + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"using ConsoleApplication; +expected: """ + using ConsoleApplication; -class Program -{ - void Main() - { - Goo f; - } -} + class Program + { + void Main() + { + Goo f; + } + } -namespace ConsoleApplication -{ - enum Goo - { - } -}", + namespace ConsoleApplication + { + enum Goo + { + } + } + """, defaultNamespace: "ConsoleApplication", accessibility: Accessibility.NotApplicable, typeKind: TypeKind.Enum, isNewFile: false); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateTypeWithDefaultEnum_DefaultNamespace_NotSimpleName() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - void Main() - { - [|A.B.Goo$$|] f; - } -} -namespace A -{ - namespace B - { - } -}", + public Task GenerateTypeWithDefaultEnum_DefaultNamespace_NotSimpleName() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + void Main() + { + [|A.B.Goo$$|] f; + } + } + namespace A + { + namespace B + { + } + } + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"class Program -{ - void Main() - { - A.B.Goo f; - } -} -namespace A -{ - namespace B - { - enum Goo - { - } - } -}", +expected: """ + class Program + { + void Main() + { + A.B.Goo f; + } + } + namespace A + { + namespace B + { + enum Goo + { + } + } + } + """, defaultNamespace: "ConsoleApplication", accessibility: Accessibility.NotApplicable, typeKind: TypeKind.Enum, isNewFile: false); - } #endregion // Working is very similar to the adding to the same file #region SameProject_ExistingFile [Fact] - public async Task GenerateTypeInExistingEmptyFile() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|A.B.Goo$$|] f; - } -} -namespace A.B -{ -} - - + public Task GenerateTypeInExistingEmptyFile() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|A.B.Goo$$|] f; + } + } + namespace A.B + { + } + + - - - ", + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"namespace A.B -{ - public interface Goo - { - } -}", +expected: """ + namespace A.B + { + public interface Goo + { + } + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, existingFilename: "Test2.cs"); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateTypeInExistingEmptyFile_Usings_Folders() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|Goo$$|] f; - } -} - - - - - ", + public Task GenerateTypeInExistingEmptyFile_Usings_Folders() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|Goo$$|] f; + } + } + + + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"namespace outer.inner -{ - public interface Goo - { - } -}", +expected: """ + namespace outer.inner + { + public interface Goo + { + } + } + """, checkIfUsingsIncluded: true, -expectedTextWithUsings: @" -using outer.inner; +expectedTextWithUsings: """ -class Program -{ - void Main() - { - Goo f; - } -}", + using outer.inner; + + class Program + { + void Main() + { + Goo f; + } + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, existingFilename: "Test2.cs"); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateTypeInExistingEmptyFile_Usings_DefaultNamespace() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|Goo$$|] f; - } -} - - - - - ", + public Task GenerateTypeInExistingEmptyFile_Usings_DefaultNamespace() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|Goo$$|] f; + } + } + + + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"namespace ConsoleApplication -{ - public interface Goo - { - } -}", +expected: """ + namespace ConsoleApplication + { + public interface Goo + { + } + } + """, defaultNamespace: "ConsoleApplication", checkIfUsingsIncluded: true, -expectedTextWithUsings: @" -using ConsoleApplication; +expectedTextWithUsings: """ -class Program -{ - void Main() - { - Goo f; - } -}", + using ConsoleApplication; + + class Program + { + void Main() + { + Goo f; + } + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, existingFilename: "Test2.cs"); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateTypeInExistingEmptyFile_Usings_Folders_DefaultNamespace() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|Goo$$|] f; - } -} - - - - - ", + public Task GenerateTypeInExistingEmptyFile_Usings_Folders_DefaultNamespace() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|Goo$$|] f; + } + } + + + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"namespace ConsoleApplication.outer.inner -{ - public interface Goo - { - } -}", +expected: """ + namespace ConsoleApplication.outer.inner + { + public interface Goo + { + } + } + """, defaultNamespace: "ConsoleApplication", checkIfUsingsIncluded: true, -expectedTextWithUsings: @" -using ConsoleApplication.outer.inner; +expectedTextWithUsings: """ -class Program -{ - void Main() - { - Goo f; - } -}", + using ConsoleApplication.outer.inner; + + class Program + { + void Main() + { + Goo f; + } + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, existingFilename: "Test2.cs"); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateTypeInExistingEmptyFile_NoUsings_Folders_NotSimpleName() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|A.B.Goo$$|] f; - } -} -namespace A.B -{ -} - - + public Task GenerateTypeInExistingEmptyFile_NoUsings_Folders_NotSimpleName() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|A.B.Goo$$|] f; + } + } + namespace A.B + { + } + + - - - ", + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"namespace A.B -{ - public interface Goo - { - } -}", +expected: """ + namespace A.B + { + public interface Goo + { + } + } + """, checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, existingFilename: "Test2.cs"); - } #endregion #region SameProject_NewFile [WpfFact] - public async Task GenerateTypeInNewFile() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|A.B.Goo$$|] f; - } -} -namespace A.B -{ -} - - - ", + public Task GenerateTypeInNewFile() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|A.B.Goo$$|] f; + } + } + namespace A.B + { + } + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"namespace A.B -{ - public interface Goo - { - } -}", +expected: """ + namespace A.B + { + public interface Goo + { + } + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileFolderContainers: [], newFileName: "Test2.cs"); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateType_UsingsNotNeeded_InNewFile_InFolder() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -namespace outer -{ - namespace inner - { - class Program - { - void Main() + public Task GenerateType_UsingsNotNeeded_InNewFile_InFolder() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + namespace outer { - [|Goo$$|] f; + namespace inner + { + class Program + { + void Main() + { + [|Goo$$|] f; + } + } + } } - } - } -} - - - ", + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"namespace outer.inner -{ - public interface Goo - { - } -}", +expected: """ + namespace outer.inner + { + public interface Goo + { + } + } + """, checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileFolderContainers: ["outer", "inner"], newFileName: "Test2.cs"); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateType_UsingsNeeded_InNewFile_InFolder() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|Goo$$|] f; - } -} - - ", + public Task GenerateType_UsingsNeeded_InNewFile_InFolder() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|Goo$$|] f; + } + } + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"namespace outer.inner -{ - public interface Goo - { - } -}", +expected: """ + namespace outer.inner + { + public interface Goo + { + } + } + """, checkIfUsingsIncluded: true, -expectedTextWithUsings: @" -using outer.inner; +expectedTextWithUsings: """ -class Program -{ - void Main() - { - Goo f; - } -}", + using outer.inner; + + class Program + { + void Main() + { + Goo f; + } + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileFolderContainers: ["outer", "inner"], newFileName: "Test2.cs"); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateType_UsingsNotNeeded_InNewFile_InFolder_NotSimpleName() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|A.B.Goo$$|] f; - } -} -namespace A.B -{ -} - - - ", + public Task GenerateType_UsingsNotNeeded_InNewFile_InFolder_NotSimpleName() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|A.B.Goo$$|] f; + } + } + namespace A.B + { + } + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"namespace A.B -{ - public interface Goo - { - } -}", +expected: """ + namespace A.B + { + public interface Goo + { + } + } + """, checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileFolderContainers: ["outer", "inner"], newFileName: "Test2.cs"); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateType_UsingsNeeded_InNewFile_InFolder_DefaultNamespace() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|Goo$$|] f; - } -} - - ", + public Task GenerateType_UsingsNeeded_InNewFile_InFolder_DefaultNamespace() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|Goo$$|] f; + } + } + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"namespace ConsoleApplication.outer.inner -{ - public interface Goo - { - } -}", +expected: """ + namespace ConsoleApplication.outer.inner + { + public interface Goo + { + } + } + """, defaultNamespace: "ConsoleApplication", checkIfUsingsIncluded: true, -expectedTextWithUsings: @" -using ConsoleApplication.outer.inner; +expectedTextWithUsings: """ -class Program -{ - void Main() - { - Goo f; - } -}", + using ConsoleApplication.outer.inner; + + class Program + { + void Main() + { + Goo f; + } + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileFolderContainers: ["outer", "inner"], newFileName: "Test2.cs"); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateType_UsingsNotNeeded_InNewFile_InFolder_DefaultNamespace() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -namespace ConsoleApplication.outer -{ - class Program - { - void Main() - { - [|Goo$$|] f; - } - } -} - - ", + public Task GenerateType_UsingsNotNeeded_InNewFile_InFolder_DefaultNamespace() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + namespace ConsoleApplication.outer + { + class Program + { + void Main() + { + [|Goo$$|] f; + } + } + } + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"namespace ConsoleApplication.outer -{ - public interface Goo - { - } -}", +expected: """ + namespace ConsoleApplication.outer + { + public interface Goo + { + } + } + """, defaultNamespace: "ConsoleApplication", checkIfUsingsIncluded: true, -expectedTextWithUsings: @" -namespace ConsoleApplication.outer -{ - class Program - { - void Main() - { - Goo f; - } - } -}", +expectedTextWithUsings: """ + + namespace ConsoleApplication.outer + { + class Program + { + void Main() + { + Goo f; + } + } + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileFolderContainers: ["outer"], newFileName: "Test2.cs"); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateType_UsingsNotNeeded_InNewFile_InFolder_DefaultNamespace_NotSimpleName() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|A.B.Goo$$|] f; - } -} + public Task GenerateType_UsingsNotNeeded_InNewFile_InFolder_DefaultNamespace_NotSimpleName() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|A.B.Goo$$|] f; + } + } -namespace A.B -{ -} - - ", + namespace A.B + { + } + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"namespace A.B -{ - public interface Goo - { - } -}", +expected: """ + namespace A.B + { + public interface Goo + { + } + } + """, defaultNamespace: "ConsoleApplication", checkIfUsingsIncluded: true, -expectedTextWithUsings: @" -class Program -{ - void Main() - { - A.B.Goo f; - } -} +expectedTextWithUsings: """ -namespace A.B -{ -}", + class Program + { + void Main() + { + A.B.Goo f; + } + } + + namespace A.B + { + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileFolderContainers: ["outer"], newFileName: "Test2.cs"); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/898452")] - public async Task GenerateType_InValidFolderNameNotMadeNamespace() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -namespace outer -{ - namespace inner - { - class Program - { - void Main() + public Task GenerateType_InValidFolderNameNotMadeNamespace() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + namespace outer { - [|Goo$$|] f; - } - } - } -} - - ", + namespace inner + { + class Program + { + void Main() + { + [|Goo$$|] f; + } + } + } + } + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", defaultNamespace: "ConsoleApplication", -expected: @"namespace ConsoleApplication -{ - public interface Goo - { - } -}", +expected: """ + namespace ConsoleApplication + { + public interface Goo + { + } + } + """, checkIfUsingsIncluded: true, -expectedTextWithUsings: @" -using ConsoleApplication; +expectedTextWithUsings: """ -namespace outer -{ - namespace inner - { - class Program - { - void Main() + using ConsoleApplication; + + namespace outer { - Goo f; + namespace inner + { + class Program + { + void Main() + { + Goo f; + } + } + } } - } - } -}", + """, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, areFoldersValidIdentifiers: false, newFileFolderContainers: ["123", "456"], newFileName: "Test2.cs"); - } #endregion @@ -1079,267 +1149,284 @@ void Main() #region SameLanguageDifferentProject #region SameLanguageDifferentProject_ExistingFile [Fact] - public async Task GenerateTypeIntoSameLanguageDifferentProjectEmptyFile() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|A.B.Goo$$|] f; - } -} -namespace A.B -{ -} - - - - - - - ", + public Task GenerateTypeIntoSameLanguageDifferentProjectEmptyFile() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|A.B.Goo$$|] f; + } + } + namespace A.B + { + } + + + + + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"namespace A.B -{ - public interface Goo - { - } -}", +expected: """ + namespace A.B + { + public interface Goo + { + } + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, existingFilename: "Test2.cs", projectName: "Assembly2"); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateTypeIntoSameLanguageDifferentProjectExistingFile() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|A.B.Goo$$|] f; - } -} -namespace A.B -{ -} - - - - -namespace A -{ - namespace B - { - } -} - - ", + public Task GenerateTypeIntoSameLanguageDifferentProjectExistingFile() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|A.B.Goo$$|] f; + } + } + namespace A.B + { + } + + + + + namespace A + { + namespace B + { + } + } + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @" -namespace A -{ - namespace B - { - public interface Goo - { - } - } -}", +expected: """ + + namespace A + { + namespace B + { + public interface Goo + { + } + } + } + """, checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, existingFilename: "Test2.cs", projectName: "Assembly2"); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateTypeIntoSameLanguageDifferentProjectExistingFile_Usings_Folders() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|Goo$$|] f; - } -} - - - -namespace A -{ - namespace B - { - } -} - - ", + public Task GenerateTypeIntoSameLanguageDifferentProjectExistingFile_Usings_Folders() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|Goo$$|] f; + } + } + + + + namespace A + { + namespace B + { + } + } + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @" -namespace A -{ - namespace B - { - } -} +expected: """ -namespace outer.inner -{ - public interface Goo - { - } -}", + namespace A + { + namespace B + { + } + } + + namespace outer.inner + { + public interface Goo + { + } + } + """, checkIfUsingsIncluded: true, -expectedTextWithUsings: @" -using outer.inner; +expectedTextWithUsings: """ -class Program -{ - void Main() - { - Goo f; - } -}", + using outer.inner; + + class Program + { + void Main() + { + Goo f; + } + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, existingFilename: "Test2.cs", projectName: "Assembly2"); - } #endregion #region SameLanguageDifferentProject_NewFile [WpfFact] - public async Task GenerateTypeIntoSameLanguageDifferentProjectNewFile() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|A.B.Goo$$|] f; - } -} -namespace A.B -{ -} - - - - - ", + public Task GenerateTypeIntoSameLanguageDifferentProjectNewFile() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|A.B.Goo$$|] f; + } + } + namespace A.B + { + } + + + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"namespace A.B -{ - public interface Goo - { - } -}", +expected: """ + namespace A.B + { + public interface Goo + { + } + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileName: "Test2.cs", newFileFolderContainers: [], projectName: "Assembly2"); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_Usings() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|Goo$$|] f; - } -} - - - - ", + public Task GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_Usings() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|Goo$$|] f; + } + } + + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"namespace outer.inner -{ - public interface Goo - { - } -}", +expected: """ + namespace outer.inner + { + public interface Goo + { + } + } + """, checkIfUsingsIncluded: true, -expectedTextWithUsings: @" -using outer.inner; +expectedTextWithUsings: """ -class Program -{ - void Main() - { - Goo f; - } -}", + using outer.inner; + + class Program + { + void Main() + { + Goo f; + } + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileName: "Test2.cs", newFileFolderContainers: ["outer", "inner"], projectName: "Assembly2"); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_NoUsings_NotSimpleName() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|A.B.Goo$$|] f; - } -} -namespace A.B -{ -} - - - - - ", + public Task GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_NoUsings_NotSimpleName() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|A.B.Goo$$|] f; + } + } + namespace A.B + { + } + + + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"namespace A.B -{ - public interface Goo - { - } -}", +expected: """ + namespace A.B + { + public interface Goo + { + } + } + """, checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, @@ -1347,84 +1434,90 @@ public interface Goo newFileName: "Test2.cs", newFileFolderContainers: ["outer", "inner"], projectName: "Assembly2"); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_Usings_DefaultNamespace() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|Goo$$|] f; - } -} - - - - ", + public Task GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_Usings_DefaultNamespace() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|Goo$$|] f; + } + } + + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"namespace ConsoleApplication.outer.inner -{ - public interface Goo - { - } -}", +expected: """ + namespace ConsoleApplication.outer.inner + { + public interface Goo + { + } + } + """, defaultNamespace: "ConsoleApplication", checkIfUsingsIncluded: true, -expectedTextWithUsings: @" -using ConsoleApplication.outer.inner; +expectedTextWithUsings: """ -class Program -{ - void Main() - { - Goo f; - } -}", + using ConsoleApplication.outer.inner; + + class Program + { + void Main() + { + Goo f; + } + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileName: "Test2.cs", newFileFolderContainers: ["outer", "inner"], projectName: "Assembly2"); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_NoUsings_NotSimpleName_DefaultNamespace() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|A.B.Goo$$|] f; - } -} -namespace A.B -{ -} - - - - - ", + public Task GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_NoUsings_NotSimpleName_DefaultNamespace() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|A.B.Goo$$|] f; + } + } + namespace A.B + { + } + + + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"namespace A.B -{ - public interface Goo - { - } -}", +expected: """ + namespace A.B + { + public interface Goo + { + } + } + """, defaultNamespace: "ConsoleApplication", checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, @@ -1433,120 +1526,128 @@ public interface Goo newFileName: "Test2.cs", newFileFolderContainers: ["outer", "inner"], projectName: "Assembly2"); - } #endregion #endregion #region DifferentLanguage [WpfFact] - public async Task GenerateTypeIntoDifferentLanguageNewFile() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|A.B.Goo$$|] f; - } -} -namespace A.B -{ -} - - - - - ", + public Task GenerateTypeIntoDifferentLanguageNewFile() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|A.B.Goo$$|] f; + } + } + namespace A.B + { + } + + + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"Namespace Global.A.B - Public Class Goo - End Class -End Namespace -", +expected: """ + Namespace Global.A.B + Public Class Goo + End Class + End Namespace + + """, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: true, newFileName: "Test2.vb", newFileFolderContainers: [], projectName: "Assembly2"); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateTypeIntoDifferentLanguageNewFile_Folders_Usings() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|Goo$$|] f; - } -} - - - - ", + public Task GenerateTypeIntoDifferentLanguageNewFile_Folders_Usings() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|Goo$$|] f; + } + } + + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"Namespace outer.inner - Public Class Goo - End Class -End Namespace -", +expected: """ + Namespace outer.inner + Public Class Goo + End Class + End Namespace + + """, checkIfUsingsIncluded: true, -expectedTextWithUsings: @" -using outer.inner; +expectedTextWithUsings: """ -class Program -{ - void Main() - { - Goo f; - } -}", + using outer.inner; + + class Program + { + void Main() + { + Goo f; + } + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: true, newFileName: "Test2.vb", newFileFolderContainers: ["outer", "inner"], projectName: "Assembly2"); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateTypeIntoDifferentLanguageNewFile_Folders_NoUsings_NotSimpleName() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|A.B.Goo$$|] f; - } -} -namespace A.B -{ -} - - - - - ", + public Task GenerateTypeIntoDifferentLanguageNewFile_Folders_NoUsings_NotSimpleName() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|A.B.Goo$$|] f; + } + } + namespace A.B + { + } + + + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"Namespace Global.A.B - Public Class Goo - End Class -End Namespace -", +expected: """ + Namespace Global.A.B + Public Class Goo + End Class + End Namespace + + """, checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Class, @@ -1554,83 +1655,89 @@ End Namespace newFileName: "Test2.vb", newFileFolderContainers: ["outer", "inner"], projectName: "Assembly2"); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateTypeIntoDifferentLanguageNewFile_Folders_Usings_RootNamespace() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|Goo$$|] f; - } -} - - - - - ", + public Task GenerateTypeIntoDifferentLanguageNewFile_Folders_Usings_RootNamespace() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|Goo$$|] f; + } + } + + + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"Namespace outer.inner - Public Class Goo - End Class -End Namespace -", +expected: """ + Namespace outer.inner + Public Class Goo + End Class + End Namespace + + """, checkIfUsingsIncluded: true, -expectedTextWithUsings: @" -using BarBaz.outer.inner; +expectedTextWithUsings: """ -class Program -{ - void Main() - { - Goo f; - } -}", + using BarBaz.outer.inner; + + class Program + { + void Main() + { + Goo f; + } + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: true, newFileName: "Test2.vb", newFileFolderContainers: ["outer", "inner"], projectName: "Assembly2"); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateTypeIntoDifferentLanguageNewFile_Folders_NoUsings_NotSimpleName_RootNamespace() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|A.B.Goo$$|] f; - } -} -namespace A.B -{ -} - - - - - - ", + public Task GenerateTypeIntoDifferentLanguageNewFile_Folders_NoUsings_NotSimpleName_RootNamespace() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|A.B.Goo$$|] f; + } + } + namespace A.B + { + } + + + + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"Namespace Global.A.B - Public Class Goo - End Class -End Namespace -", +expected: """ + Namespace Global.A.B + Public Class Goo + End Class + End Namespace + + """, checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Class, @@ -1638,43 +1745,45 @@ End Namespace newFileName: "Test2.vb", newFileFolderContainers: ["outer", "inner"], projectName: "Assembly2"); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateTypeIntoDifferentLanguageNewFile_Folders_NoUsings_NotSimpleName_RootNamespace_ProjectReference() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - - - Namespace A.B - Public Class Goo - End Class - End Namespace - - - - Assembly2 - -using BarBaz.A; - -class Program -{ - void Main() - { - [|BarBaz.A.B.Bar$$|] f; - } -} - - ", + public Task GenerateTypeIntoDifferentLanguageNewFile_Folders_NoUsings_NotSimpleName_RootNamespace_ProjectReference() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + + Namespace A.B + Public Class Goo + End Class + End Namespace + + + + Assembly2 + + using BarBaz.A; + + class Program + { + void Main() + { + [|BarBaz.A.B.Bar$$|] f; + } + } + + + """, languageName: LanguageNames.CSharp, typeName: "Bar", -expected: @"Namespace A.B - Public Class Bar - End Class -End Namespace -", +expected: """ + Namespace A.B + Public Class Bar + End Class + End Namespace + + """, defaultNamespace: "ConsoleApplication", checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, @@ -1683,254 +1792,268 @@ End Namespace newFileName: "Test3.vb", newFileFolderContainers: ["outer", "inner"], projectName: "Assembly2"); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858826")] - public async Task GenerateTypeIntoDifferentLanguageNewFileAdjustFileExtension() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|A.B.Goo$$|] f; - } -} -namespace A.B -{ -} - - - - - ", + public Task GenerateTypeIntoDifferentLanguageNewFileAdjustFileExtension() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|A.B.Goo$$|] f; + } + } + namespace A.B + { + } + + + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"Namespace Global.A.B - Public Class Goo - End Class -End Namespace -", +expected: """ + Namespace Global.A.B + Public Class Goo + End Class + End Namespace + + """, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: true, newFileName: "Test2.vb", newFileFolderContainers: [], projectName: "Assembly2"); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateTypeIntoDifferentLanguageExistingEmptyFile() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|A.B.Goo$$|] f; - } -} -namespace A.B -{ -} - - - - - - - ", + public Task GenerateTypeIntoDifferentLanguageExistingEmptyFile() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|A.B.Goo$$|] f; + } + } + namespace A.B + { + } + + + + + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"Namespace Global.A.B - Public Class Goo - End Class -End Namespace -", +expected: """ + Namespace Global.A.B + Public Class Goo + End Class + End Namespace + + """, checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, existingFilename: "Test2.vb", projectName: "Assembly2"); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] - public async Task GenerateTypeIntoDifferentLanguageExistingEmptyFile_Usings_Folder() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|Goo$$|] f; - } -} - - - - - - ", + public Task GenerateTypeIntoDifferentLanguageExistingEmptyFile_Usings_Folder() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|Goo$$|] f; + } + } + + + + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"Namespace outer.inner - Public Class Goo - End Class -End Namespace -", +expected: """ + Namespace outer.inner + Public Class Goo + End Class + End Namespace + + """, checkIfUsingsIncluded: true, -expectedTextWithUsings: @" -using outer.inner; +expectedTextWithUsings: """ -class Program -{ - void Main() - { - Goo f; - } -}", + using outer.inner; + + class Program + { + void Main() + { + Goo f; + } + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, existingFilename: "Test2.vb", projectName: "Assembly2"); - } [Fact] - public async Task GenerateTypeIntoDifferentLanguageExistingNonEmptyFile() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|A.B.Goo$$|] f; - } -} -namespace A.B -{ -} - - - - -Namespace A -End Namespace - - - ", + public Task GenerateTypeIntoDifferentLanguageExistingNonEmptyFile() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|A.B.Goo$$|] f; + } + } + namespace A.B + { + } + + + + + Namespace A + End Namespace + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @" -Namespace A -End Namespace +expected: """ + + Namespace A + End Namespace -Namespace Global.A.B - Public Class Goo - End Class -End Namespace -", + Namespace Global.A.B + Public Class Goo + End Class + End Namespace + + """, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, existingFilename: "Test2.vb", projectName: "Assembly2"); - } [Fact] - public async Task GenerateTypeIntoDifferentLanguageExistingNonEmptyTargetFile() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|A.B.Goo$$|] f; - } -} -namespace A.B -{ -} - - - - -Namespace Global - Namespace A - Namespace C - End Namespace - Namespace B - End Namespace - End Namespace -End Namespace - - ", + public Task GenerateTypeIntoDifferentLanguageExistingNonEmptyTargetFile() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|A.B.Goo$$|] f; + } + } + namespace A.B + { + } + + + + + Namespace Global + Namespace A + Namespace C + End Namespace + Namespace B + End Namespace + End Namespace + End Namespace + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @" -Namespace Global - Namespace A - Namespace C - End Namespace - Namespace B - Public Class Goo - End Class - End Namespace - End Namespace -End Namespace", +expected: """ + + Namespace Global + Namespace A + Namespace C + End Namespace + Namespace B + Public Class Goo + End Class + End Namespace + End Namespace + End Namespace + """, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, existingFilename: "Test2.vb", projectName: "Assembly2"); - } [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861362")] [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/869593")] - public async Task GenerateModuleFromCSharpToVisualBasicInTypeContext() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - [|A.Goo$$|].Bar f; - } -} -namespace A -{ -} - - - - - ", + public Task GenerateModuleFromCSharpToVisualBasicInTypeContext() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + [|A.Goo$$|].Bar f; + } + } + namespace A + { + } + + + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"Namespace Global.A - Public Module Goo - End Module -End Namespace -", +expected: """ + Namespace Global.A + Public Module Goo + End Module + End Namespace + + """, accessibility: Accessibility.Public, typeKind: TypeKind.Module, isNewFile: true, @@ -1938,1703 +2061,1804 @@ End Namespace newFileFolderContainers: [], projectName: "Assembly2", assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Module)); - } #endregion #region Bugfix [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/873066")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")] - public async Task GenerateTypeWithProperAccessibilityAndTypeKind_1() - { - await TestWithMockedGenerateTypeDialog( -initial: @" -public class C : [|$$D|] -{ -}", + public Task GenerateTypeWithProperAccessibilityAndTypeKind_1() + => TestWithMockedGenerateTypeDialog( +initial: """ + + public class C : [|$$D|] + { + } + """, languageName: LanguageNames.CSharp, typeName: "D", -expected: @" -public class C : D -{ -} +expected: """ -public class D -{ -}", + public class C : D + { + } + + public class D + { + } + """, accessibility: Accessibility.Public, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(true, TypeKindOptions.BaseList, false)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")] - public async Task GenerateTypeWithProperAccessibilityAndTypeKind_2() - { - await TestWithMockedGenerateTypeDialog( -initial: @"public interface CCC : [|$$DDD|] -{ -}", + public Task GenerateTypeWithProperAccessibilityAndTypeKind_2() + => TestWithMockedGenerateTypeDialog( +initial: """ + public interface CCC : [|$$DDD|] + { + } + """, languageName: LanguageNames.CSharp, typeName: "DDD", -expected: @"public interface CCC : DDD -{ -} +expected: """ + public interface CCC : DDD + { + } -public interface DDD -{ -}", + public interface DDD + { + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(true, TypeKindOptions.Interface, false)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")] - public async Task GenerateTypeWithProperAccessibilityAndTypeKind_3() - { - await TestWithMockedGenerateTypeDialog( -initial: @"public struct CCC : [|$$DDD|] -{ -}", + public Task GenerateTypeWithProperAccessibilityAndTypeKind_3() + => TestWithMockedGenerateTypeDialog( +initial: """ + public struct CCC : [|$$DDD|] + { + } + """, languageName: LanguageNames.CSharp, typeName: "DDD", -expected: @"public struct CCC : DDD -{ -} +expected: """ + public struct CCC : DDD + { + } -public interface DDD -{ -}", + public interface DDD + { + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(true, TypeKindOptions.Interface, false)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861362")] - public async Task GenerateTypeInMemberAccessExpression() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - var s = [|$$A.B|]; - } -}", + public Task GenerateTypeInMemberAccessExpression() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + var s = [|$$A.B|]; + } + } + """, languageName: LanguageNames.CSharp, typeName: "A", -expected: @"class Program -{ - static void Main(string[] args) - { - var s = A.B; - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + var s = A.B; + } + } -public class A -{ -}", + public class A + { + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.MemberAccessWithNamespace)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861362")] - public async Task GenerateTypeInMemberAccessExpressionInNamespace() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - var s = [|$$A.B.C|]; - } -} + public Task GenerateTypeInMemberAccessExpressionInNamespace() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + var s = [|$$A.B.C|]; + } + } -namespace A -{ -}", + namespace A + { + } + """, languageName: LanguageNames.CSharp, typeName: "B", -expected: @"class Program -{ - static void Main(string[] args) - { - var s = A.B.C; - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + var s = A.B.C; + } + } -namespace A -{ - public class B - { - } -}", + namespace A + { + public class B + { + } + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.MemberAccessWithNamespace)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")] - public async Task GenerateTypeWithoutEnumForGenericsInMemberAccess() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - var s = [|$$Goo|].D; - } -} + public Task GenerateTypeWithoutEnumForGenericsInMemberAccess() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + var s = [|$$Goo|].D; + } + } -class Bar -{ -}", + class Bar + { + } + """, languageName: LanguageNames.CSharp, -typeName: "Goo", -expected: @"class Program -{ - static void Main(string[] args) - { - var s = Goo.D; - } -} +typeName: "Goo", +expected: """ + class Program + { + static void Main(string[] args) + { + var s = Goo.D; + } + } -class Bar -{ -} + class Bar + { + } -public class Goo -{ -}", + public class Goo + { + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")] - public async Task GenerateTypeWithoutEnumForGenericsInNameContext() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - [|$$Goo|] baz; - } -} + public Task GenerateTypeWithoutEnumForGenericsInNameContext() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + [|$$Goo|] baz; + } + } -internal class Bar -{ -}", + internal class Bar + { + } + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"class Program -{ - static void Main(string[] args) - { - Goo baz; - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + Goo baz; + } + } -internal class Bar -{ -} + internal class Bar + { + } -public class Goo -{ -}", + public class Goo + { + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Interface | TypeKindOptions.Delegate)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")] - public async Task GenerateTypeInMemberAccessWithNSForModule() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - var s = [|Goo.$$Bar|].Baz; - } -} + public Task GenerateTypeInMemberAccessWithNSForModule() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + var s = [|Goo.$$Bar|].Baz; + } + } -namespace Goo -{ -}", + namespace Goo + { + } + """, languageName: LanguageNames.CSharp, typeName: "Bar", -expected: @"class Program -{ - static void Main(string[] args) - { - var s = Goo.Bar.Baz; - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + var s = Goo.Bar.Baz; + } + } -namespace Goo -{ - public class Bar - { - } -}", + namespace Goo + { + public class Bar + { + } + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.MemberAccessWithNamespace)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")] - public async Task GenerateTypeInMemberAccessWithGlobalNSForModule() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - var s = [|$$Bar|].Baz; - } -}", + public Task GenerateTypeInMemberAccessWithGlobalNSForModule() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + var s = [|$$Bar|].Baz; + } + } + """, languageName: LanguageNames.CSharp, typeName: "Bar", -expected: @"class Program -{ - static void Main(string[] args) - { - var s = Bar.Baz; - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + var s = Bar.Baz; + } + } -public class Bar -{ -}", + public class Bar + { + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.MemberAccessWithNamespace)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")] - public async Task GenerateTypeInMemberAccessWithoutNS() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - var s = [|$$Bar|].Baz; - } -} + public Task GenerateTypeInMemberAccessWithoutNS() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + var s = [|$$Bar|].Baz; + } + } -namespace Bar -{ -}", + namespace Bar + { + } + """, languageName: LanguageNames.CSharp, typeName: "Bar", isMissing: true); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/883531")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876202")] - public async Task GenerateType_NoParameterLessConstructorForStruct() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - var s = new [|$$Bar|](); - } -}", + public Task GenerateType_NoParameterLessConstructorForStruct() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + var s = new [|$$Bar|](); + } + } + """, languageName: LanguageNames.CSharp, typeName: "Bar", -expected: @"class Program -{ - static void Main(string[] args) - { - var s = new Bar(); - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + var s = new Bar(); + } + } -public struct Bar -{ -}", + public struct Bar + { + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Structure, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure, false)); - } [Fact, WorkItem(63280, "https://github.com/dotnet/roslyn/issues/63280")] - public async Task GenerateType_GenericBaseList() - { - await TestWithMockedGenerateTypeDialog( -initial: @" -using System.Collections.Generic; + public Task GenerateType_GenericBaseList() + => TestWithMockedGenerateTypeDialog( +initial: """ -struct C : IEnumerable<[|$$NewType|]> -{ -}", + using System.Collections.Generic; + + struct C : IEnumerable<[|$$NewType|]> + { + } + """, languageName: LanguageNames.CSharp, typeName: "NewType", -expected: @" -using System.Collections.Generic; +expected: """ -struct C : IEnumerable -{ -} + using System.Collections.Generic; -public class NewType -{ -}", + struct C : IEnumerable + { + } + + public class NewType + { + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions, false)); - } [Fact] - public async Task GenerateType_QualifiedBaseList() - { - await TestWithMockedGenerateTypeDialog( -initial: @" -using System.Collections.Generic; + public Task GenerateType_QualifiedBaseList() + => TestWithMockedGenerateTypeDialog( +initial: """ -struct C : A.B.[|$$INewType|] -{ -} + using System.Collections.Generic; -namespace A.B -{ -}", + struct C : A.B.[|$$INewType|] + { + } + + namespace A.B + { + } + """, languageName: LanguageNames.CSharp, typeName: "INewType", -expected: @" -using System.Collections.Generic; +expected: """ -struct C : A.B.INewType -{ -} + using System.Collections.Generic; -namespace A.B -{ - public interface INewType - { - } -}", + struct C : A.B.INewType + { + } + + namespace A.B + { + public interface INewType + { + } + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Interface, false)); - } [Fact] - public async Task GenerateType_AliasQualifiedBaseList() - { - await TestWithMockedGenerateTypeDialog( -initial: @" -using System.Collections.Generic; + public Task GenerateType_AliasQualifiedBaseList() + => TestWithMockedGenerateTypeDialog( +initial: """ -struct C : global::A.B.[|$$INewType|] -{ -} + using System.Collections.Generic; -namespace A.B -{ -}", + struct C : global::A.B.[|$$INewType|] + { + } + + namespace A.B + { + } + """, languageName: LanguageNames.CSharp, typeName: "INewType", -expected: @" -using System.Collections.Generic; +expected: """ -struct C : global::A.B.INewType -{ -} + using System.Collections.Generic; -namespace A.B -{ - public interface INewType - { - } -}", + struct C : global::A.B.INewType + { + } + + namespace A.B + { + public interface INewType + { + } + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Interface, false)); - } #endregion #region Delegates [Fact] - public async Task GenerateDelegateType_ObjectCreationExpression_MethodGroup() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - var s2 = new [|$$MyD|](goo); - } - static void goo() - { - } -}", + public Task GenerateDelegateType_ObjectCreationExpression_MethodGroup() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + var s2 = new [|$$MyD|](goo); + } + static void goo() + { + } + } + """, languageName: LanguageNames.CSharp, typeName: "MyD", -expected: @"class Program -{ - static void Main(string[] args) - { - var s2 = new MyD(goo); - } - static void goo() - { - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + var s2 = new MyD(goo); + } + static void goo() + { + } + } -public delegate void MyD(); -", + public delegate void MyD(); + + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Delegate)); - } [Fact] - public async Task GenerateDelegateType_ObjectCreationExpression_MethodGroup_Generics() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - var s2 = new [|$$MyD|](goo); - } - static void goo() - { - } -}", + public Task GenerateDelegateType_ObjectCreationExpression_MethodGroup_Generics() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + var s2 = new [|$$MyD|](goo); + } + static void goo() + { + } + } + """, languageName: LanguageNames.CSharp, typeName: "MyD", -expected: @"class Program -{ - static void Main(string[] args) - { - var s2 = new MyD(goo); - } - static void goo() - { - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + var s2 = new MyD(goo); + } + static void goo() + { + } + } -public delegate void MyD(); -", + public delegate void MyD(); + + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Delegate)); - } [Fact] - public async Task GenerateDelegateType_ObjectCreationExpression_Delegate() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - MyD1 d = null; - var s1 = new [|$$MyD2|](d); - } - public delegate object MyD1(); -}", + public Task GenerateDelegateType_ObjectCreationExpression_Delegate() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + MyD1 d = null; + var s1 = new [|$$MyD2|](d); + } + public delegate object MyD1(); + } + """, languageName: LanguageNames.CSharp, typeName: "MyD", -expected: @"class Program -{ - static void Main(string[] args) - { - MyD1 d = null; - var s1 = new MyD2(d); - } - public delegate object MyD1(); -} +expected: """ + class Program + { + static void Main(string[] args) + { + MyD1 d = null; + var s1 = new MyD2(d); + } + public delegate object MyD1(); + } -public delegate object MyD(); -", + public delegate object MyD(); + + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Delegate)); - } [Fact] - public async Task GenerateDelegateType_ObjectCreationExpression_Action() - { - await TestWithMockedGenerateTypeDialog( -initial: @"using System; -class Program -{ - static void Main(string[] args) - { - Action action1 = null; - var s3 = new [|$$MyD|](action1); - } -}", + public Task GenerateDelegateType_ObjectCreationExpression_Action() + => TestWithMockedGenerateTypeDialog( +initial: """ + using System; + class Program + { + static void Main(string[] args) + { + Action action1 = null; + var s3 = new [|$$MyD|](action1); + } + } + """, languageName: LanguageNames.CSharp, typeName: "MyD", -expected: @"using System; -class Program -{ - static void Main(string[] args) - { - Action action1 = null; - var s3 = new MyD(action1); - } -} +expected: """ + using System; + class Program + { + static void Main(string[] args) + { + Action action1 = null; + var s3 = new MyD(action1); + } + } -public delegate void MyD(int obj); -", + public delegate void MyD(int obj); + + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Delegate)); - } [Fact] - public async Task GenerateDelegateType_ObjectCreationExpression_Func() - { - await TestWithMockedGenerateTypeDialog( -initial: @"using System; -class Program -{ - static void Main(string[] args) - { - Func lambda = () => { return 0; }; - var s4 = new [|$$MyD|](lambda); - } -}", + public Task GenerateDelegateType_ObjectCreationExpression_Func() + => TestWithMockedGenerateTypeDialog( +initial: """ + using System; + class Program + { + static void Main(string[] args) + { + Func lambda = () => { return 0; }; + var s4 = new [|$$MyD|](lambda); + } + } + """, languageName: LanguageNames.CSharp, typeName: "MyD", -expected: @"using System; -class Program -{ - static void Main(string[] args) - { - Func lambda = () => { return 0; }; - var s4 = new MyD(lambda); - } -} +expected: """ + using System; + class Program + { + static void Main(string[] args) + { + Func lambda = () => { return 0; }; + var s4 = new MyD(lambda); + } + } -public delegate int MyD(); -", + public delegate int MyD(); + + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Delegate)); - } [Fact] - public async Task GenerateDelegateType_ObjectCreationExpression_ParenLambda() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - var s5 = new [|$$MyD|]((int n) => { return n; }); - } -}", + public Task GenerateDelegateType_ObjectCreationExpression_ParenLambda() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + var s5 = new [|$$MyD|]((int n) => { return n; }); + } + } + """, languageName: LanguageNames.CSharp, typeName: "MyD", -expected: @"class Program -{ - static void Main(string[] args) - { - var s5 = new MyD((int n) => { return n; }); - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + var s5 = new MyD((int n) => { return n; }); + } + } -public delegate int MyD(int n); -", + public delegate int MyD(int n); + + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Delegate)); - } [Fact] - public async Task GenerateDelegateType_ObjectCreationExpression_SimpleLambda() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - var s6 = new [|$$MyD|](n => { return n; }); - } -}", + public Task GenerateDelegateType_ObjectCreationExpression_SimpleLambda() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + var s6 = new [|$$MyD|](n => { return n; }); + } + } + """, languageName: LanguageNames.CSharp, typeName: "MyD", -expected: @"class Program -{ - static void Main(string[] args) - { - var s6 = new MyD(n => { return n; }); - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + var s6 = new MyD(n => { return n; }); + } + } -public delegate void MyD(object n); -", + public delegate void MyD(object n); + + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Delegate)); - } [Fact(Skip = "872935")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/872935")] - public async Task GenerateDelegateType_ObjectCreationExpression_SimpleLambdaEmpty() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - var s7 = new [|$$MyD3|](() => { }); - } -}", + public Task GenerateDelegateType_ObjectCreationExpression_SimpleLambdaEmpty() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + var s7 = new [|$$MyD3|](() => { }); + } + } + """, languageName: LanguageNames.CSharp, typeName: "MyD", -expected: @"class Program -{ - static void Main(string[] args) - { - var s7 = new MyD3(() => { }); - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + var s7 = new MyD3(() => { }); + } + } -public delegate void MyD(); -", + public delegate void MyD(); + + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); - } [Fact] - public async Task GenerateDelegateType_VarDecl_MethodGroup() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - [|$$MyD|] z1 = goo; - } - static void goo() - { - } -}", + public Task GenerateDelegateType_VarDecl_MethodGroup() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + [|$$MyD|] z1 = goo; + } + static void goo() + { + } + } + """, languageName: LanguageNames.CSharp, typeName: "MyD", -expected: @"class Program -{ - static void Main(string[] args) - { - MyD z1 = goo; - } - static void goo() - { - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + MyD z1 = goo; + } + static void goo() + { + } + } -public delegate void MyD(); -", + public delegate void MyD(); + + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); - } [Fact] - public async Task GenerateDelegateType_VarDecl_Delegate() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - MyD1 temp = null; - [|$$MyD|] z2 = temp; // Still Error - } -} + public Task GenerateDelegateType_VarDecl_Delegate() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + MyD1 temp = null; + [|$$MyD|] z2 = temp; // Still Error + } + } -public delegate object MyD1();", + public delegate object MyD1(); + """, languageName: LanguageNames.CSharp, typeName: "MyD", -expected: @"class Program -{ - static void Main(string[] args) - { - MyD1 temp = null; - MyD z2 = temp; // Still Error - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + MyD1 temp = null; + MyD z2 = temp; // Still Error + } + } + + public delegate object MyD1(); -public delegate object MyD1(); + public delegate object MyD(); -public delegate object MyD(); -", + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); - } [Fact] - public async Task GenerateDelegateType_VarDecl_Action() - { - await TestWithMockedGenerateTypeDialog( -initial: @"using System; -class Program -{ - static void Main(string[] args) - { - Action action2 = null; - [|$$MyD|] z3 = action2; // Still Error - } -}", + public Task GenerateDelegateType_VarDecl_Action() + => TestWithMockedGenerateTypeDialog( +initial: """ + using System; + class Program + { + static void Main(string[] args) + { + Action action2 = null; + [|$$MyD|] z3 = action2; // Still Error + } + } + """, languageName: LanguageNames.CSharp, typeName: "MyD", -expected: @"using System; -class Program -{ - static void Main(string[] args) - { - Action action2 = null; - MyD z3 = action2; // Still Error - } -} +expected: """ + using System; + class Program + { + static void Main(string[] args) + { + Action action2 = null; + MyD z3 = action2; // Still Error + } + } + + public delegate void MyD(int arg1, int arg2, int arg3); -public delegate void MyD(int arg1, int arg2, int arg3); -", + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); - } [Fact] - public async Task GenerateDelegateType_VarDecl_Func() - { - await TestWithMockedGenerateTypeDialog( -initial: @"using System; -class Program -{ - static void Main(string[] args) - { - Func lambda2 = () => { return 0; }; - [|$$MyD|] z4 = lambda2; // Still Error - } -}", + public Task GenerateDelegateType_VarDecl_Func() + => TestWithMockedGenerateTypeDialog( +initial: """ + using System; + class Program + { + static void Main(string[] args) + { + Func lambda2 = () => { return 0; }; + [|$$MyD|] z4 = lambda2; // Still Error + } + } + """, languageName: LanguageNames.CSharp, typeName: "MyD", -expected: @"using System; -class Program -{ - static void Main(string[] args) - { - Func lambda2 = () => { return 0; }; - MyD z4 = lambda2; // Still Error - } -} +expected: """ + using System; + class Program + { + static void Main(string[] args) + { + Func lambda2 = () => { return 0; }; + MyD z4 = lambda2; // Still Error + } + } + + public delegate int MyD(); -public delegate int MyD(); -", + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); - } [Fact] - public async Task GenerateDelegateType_VarDecl_ParenLambda() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - [|$$MyD|] z5 = (int n) => { return n; }; - } -} -", + public Task GenerateDelegateType_VarDecl_ParenLambda() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + [|$$MyD|] z5 = (int n) => { return n; }; + } + } + + """, languageName: LanguageNames.CSharp, typeName: "MyD", -expected: @"class Program -{ - static void Main(string[] args) - { - MyD z5 = (int n) => { return n; }; - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + MyD z5 = (int n) => { return n; }; + } + } + + public delegate int MyD(int n); -public delegate int MyD(int n); -", + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); - } [Fact] - public async Task GenerateDelegateType_VarDecl_SimpleLambda() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - [|$$MyD|] z6 = n => { return n; }; - } -}", + public Task GenerateDelegateType_VarDecl_SimpleLambda() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + [|$$MyD|] z6 = n => { return n; }; + } + } + """, languageName: LanguageNames.CSharp, typeName: "MyD", -expected: @"class Program -{ - static void Main(string[] args) - { - MyD z6 = n => { return n; }; - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + MyD z6 = n => { return n; }; + } + } + + public delegate void MyD(object n); -public delegate void MyD(object n); -", + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); - } [Fact] - public async Task GenerateDelegateType_Cast_MethodGroup() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - var zz1 = ([|$$MyD|])goo; - } - static void goo() - { - } -}", + public Task GenerateDelegateType_Cast_MethodGroup() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + var zz1 = ([|$$MyD|])goo; + } + static void goo() + { + } + } + """, languageName: LanguageNames.CSharp, typeName: "MyD", -expected: @"class Program -{ - static void Main(string[] args) - { - var zz1 = (MyD)goo; - } - static void goo() - { - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + var zz1 = (MyD)goo; + } + static void goo() + { + } + } + + public delegate void MyD(); -public delegate void MyD(); -", + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); - } [Fact] - public async Task GenerateDelegateType_Cast_Delegate() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - MyDDD temp1 = null; - var zz2 = ([|$$MyD|])temp1; // Still Error - } -} + public Task GenerateDelegateType_Cast_Delegate() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + MyDDD temp1 = null; + var zz2 = ([|$$MyD|])temp1; // Still Error + } + } -public delegate object MyDDD();", + public delegate object MyDDD(); + """, languageName: LanguageNames.CSharp, typeName: "MyD", -expected: @"class Program -{ - static void Main(string[] args) - { - MyDDD temp1 = null; - var zz2 = (MyD)temp1; // Still Error - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + MyDDD temp1 = null; + var zz2 = (MyD)temp1; // Still Error + } + } -public delegate object MyDDD(); + public delegate object MyDDD(); -public delegate object MyD(); -", + public delegate object MyD(); + + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); - } [Fact] - public async Task GenerateDelegateType_Cast_Action() - { - await TestWithMockedGenerateTypeDialog( -initial: @"using System; -class Program -{ - static void Main(string[] args) - { - Action action3 = null; - var zz3 = ([|$$MyD|])action3; // Still Error - } -}", + public Task GenerateDelegateType_Cast_Action() + => TestWithMockedGenerateTypeDialog( +initial: """ + using System; + class Program + { + static void Main(string[] args) + { + Action action3 = null; + var zz3 = ([|$$MyD|])action3; // Still Error + } + } + """, languageName: LanguageNames.CSharp, typeName: "MyD", -expected: @"using System; -class Program -{ - static void Main(string[] args) - { - Action action3 = null; - var zz3 = (MyD)action3; // Still Error - } -} +expected: """ + using System; + class Program + { + static void Main(string[] args) + { + Action action3 = null; + var zz3 = (MyD)action3; // Still Error + } + } -public delegate void MyD(int arg1, int arg2, int arg3); -", + public delegate void MyD(int arg1, int arg2, int arg3); + + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); - } [Fact] - public async Task GenerateDelegateType_Cast_Func() - { - await TestWithMockedGenerateTypeDialog( -initial: @"using System; -class Program -{ - static void Main(string[] args) - { - Func lambda3 = () => { return 0; }; - var zz4 = ([|$$MyD|])lambda3; // Still Error - } -}", + public Task GenerateDelegateType_Cast_Func() + => TestWithMockedGenerateTypeDialog( +initial: """ + using System; + class Program + { + static void Main(string[] args) + { + Func lambda3 = () => { return 0; }; + var zz4 = ([|$$MyD|])lambda3; // Still Error + } + } + """, languageName: LanguageNames.CSharp, typeName: "MyD", -expected: @"using System; -class Program -{ - static void Main(string[] args) - { - Func lambda3 = () => { return 0; }; - var zz4 = (MyD)lambda3; // Still Error - } -} +expected: """ + using System; + class Program + { + static void Main(string[] args) + { + Func lambda3 = () => { return 0; }; + var zz4 = (MyD)lambda3; // Still Error + } + } -public delegate int MyD(); -", + public delegate int MyD(); + + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); - } [Fact] - public async Task GenerateDelegateType_Cast_ParenLambda() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - var zz5 = ([|$$MyD|])((int n) => { return n; }); - } -} -", + public Task GenerateDelegateType_Cast_ParenLambda() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + var zz5 = ([|$$MyD|])((int n) => { return n; }); + } + } + + """, languageName: LanguageNames.CSharp, typeName: "MyD", -expected: @"class Program -{ - static void Main(string[] args) - { - var zz5 = (MyD)((int n) => { return n; }); - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + var zz5 = (MyD)((int n) => { return n; }); + } + } -public delegate int MyD(int n); -", + public delegate int MyD(int n); + + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); - } [Fact] - public async Task GenerateDelegateType_Cast_SimpleLambda() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - var zz6 = ([|$$MyD|])(n => { return n; }); - } -}", + public Task GenerateDelegateType_Cast_SimpleLambda() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + var zz6 = ([|$$MyD|])(n => { return n; }); + } + } + """, languageName: LanguageNames.CSharp, typeName: "MyD", -expected: @"class Program -{ - static void Main(string[] args) - { - var zz6 = (MyD)(n => { return n; }); - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + var zz6 = (MyD)(n => { return n; }); + } + } -public delegate void MyD(object n); -", + public delegate void MyD(object n); + + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); - } [WpfFact] - public async Task GenerateDelegateTypeIntoDifferentLanguageNewFile() - { - await TestWithMockedGenerateTypeDialog( -initial: @" - - -class Program -{ - void Main() - { - var f = ([|A.B.Goo$$|])Main; - } -} -namespace A.B -{ -} - - - - - ", + public Task GenerateDelegateTypeIntoDifferentLanguageNewFile() + => TestWithMockedGenerateTypeDialog( +initial: """ + + + + class Program + { + void Main() + { + var f = ([|A.B.Goo$$|])Main; + } + } + namespace A.B + { + } + + + + + + """, languageName: LanguageNames.CSharp, typeName: "Goo", -expected: @"Namespace Global.A.B - Public Delegate Sub Goo() -End Namespace -", +expected: """ + Namespace Global.A.B + Public Delegate Sub Goo() + End Namespace + + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: true, newFileName: "Test2.vb", newFileFolderContainers: [], projectName: "Assembly2"); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860210")] - public async Task GenerateDelegateType_NoInfo() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - [|$$MyD|] d; - } -}", + public Task GenerateDelegateType_NoInfo() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + [|$$MyD|] d; + } + } + """, languageName: LanguageNames.CSharp, typeName: "MyD", -expected: @"class Program -{ - static void Main(string[] args) - { - MyD d; - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + MyD d; + } + } + + public delegate void MyD(); -public delegate void MyD(); -", + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false); - } #endregion #region Dev12Filtering [Fact] - public async Task GenerateDelegateType_NoEnum_InvocationExpression_0() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - var s2 = [|$$B|].C(); - } -}", + public Task GenerateDelegateType_NoEnum_InvocationExpression_0() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + var s2 = [|$$B|].C(); + } + } + """, languageName: LanguageNames.CSharp, typeName: "B", -expected: @"class Program -{ - static void Main(string[] args) - { - var s2 = B.C(); - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + var s2 = B.C(); + } + } -public class B -{ -}", + public class B + { + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertTypeKindAbsent: [TypeKindOptions.Enum]); - } [Fact] - public async Task GenerateDelegateType_NoEnum_InvocationExpression_1() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - var s2 = [|A.$$B|].C(); - } -} + public Task GenerateDelegateType_NoEnum_InvocationExpression_1() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + var s2 = [|A.$$B|].C(); + } + } -namespace A -{ -}", + namespace A + { + } + """, languageName: LanguageNames.CSharp, typeName: "B", -expected: @"class Program -{ - static void Main(string[] args) - { - var s2 = A.B.C(); - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + var s2 = A.B.C(); + } + } -namespace A -{ - public class B - { - } -}", + namespace A + { + public class B + { + } + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertTypeKindAbsent: [TypeKindOptions.Enum]); - } [Fact] - public async Task GenerateType_TypeConstraint_1() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - } -} + public Task GenerateType_TypeConstraint_1() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + } + } -public class F where T : [|$$Bar|] -{ -} -", + public class F where T : [|$$Bar|] + { + } + + """, languageName: LanguageNames.CSharp, typeName: "Bar", -expected: @"class Program -{ - static void Main(string[] args) - { - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + } + } -public class F where T : Bar -{ -} + public class F where T : Bar + { + } -public class Bar -{ -}", + public class Bar + { + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(true, TypeKindOptions.BaseList)); - } [Fact] - public async Task GenerateType_TypeConstraint_2() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - } -} + public Task GenerateType_TypeConstraint_2() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + } + } -class outer -{ - public class F where T : [|$$Bar|] - { - } -} -", + class outer + { + public class F where T : [|$$Bar|] + { + } + } + + """, languageName: LanguageNames.CSharp, typeName: "Bar", -expected: @"class Program -{ - static void Main(string[] args) - { - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + } + } -class outer -{ - public class F where T : Bar - { - } -} + class outer + { + public class F where T : Bar + { + } + } -public class Bar -{ -}", + public class Bar + { + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.BaseList)); - } [Fact] - public async Task GenerateType_TypeConstraint_3() - { - await TestWithMockedGenerateTypeDialog( -initial: @"class Program -{ - static void Main(string[] args) - { - } -} + public Task GenerateType_TypeConstraint_3() + => TestWithMockedGenerateTypeDialog( +initial: """ + class Program + { + static void Main(string[] args) + { + } + } -public class outerOuter -{ - public class outer - { - public class F where T : [|$$Bar|] - { - } - } -} -", + public class outerOuter + { + public class outer + { + public class F where T : [|$$Bar|] + { + } + } + } + + """, languageName: LanguageNames.CSharp, typeName: "Bar", -expected: @"class Program -{ - static void Main(string[] args) - { - } -} +expected: """ + class Program + { + static void Main(string[] args) + { + } + } -public class outerOuter -{ - public class outer - { - public class F where T : Bar - { - } - } -} + public class outerOuter + { + public class outer + { + public class F where T : Bar + { + } + } + } -public class Bar -{ -}", + public class Bar + { + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(true, TypeKindOptions.BaseList)); - } [Fact] - public async Task GenerateTypeWithProperAccessibilityWithNesting_1() - { - await TestWithMockedGenerateTypeDialog( -initial: @" -public class B -{ - public class C : [|$$D|] - { - } -}", + public Task GenerateTypeWithProperAccessibilityWithNesting_1() + => TestWithMockedGenerateTypeDialog( +initial: """ + + public class B + { + public class C : [|$$D|] + { + } + } + """, languageName: LanguageNames.CSharp, typeName: "D", -expected: @" -public class B -{ - public class C : D - { - } -} +expected: """ -public class D -{ -}", + public class B + { + public class C : D + { + } + } + + public class D + { + } + """, accessibility: Accessibility.Public, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(true, TypeKindOptions.BaseList, false)); - } [Fact] - public async Task GenerateTypeWithProperAccessibilityWithNesting_2() - { - await TestWithMockedGenerateTypeDialog( -initial: @" -class B -{ - public class C : [|$$D|] - { - } -}", + public Task GenerateTypeWithProperAccessibilityWithNesting_2() + => TestWithMockedGenerateTypeDialog( +initial: """ + + class B + { + public class C : [|$$D|] + { + } + } + """, languageName: LanguageNames.CSharp, typeName: "D", -expected: @" -class B -{ - public class C : D - { - } -} +expected: """ -public class D -{ -}", + class B + { + public class C : D + { + } + } + + public class D + { + } + """, accessibility: Accessibility.Public, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.BaseList, false)); - } [Fact] - public async Task GenerateTypeWithProperAccessibilityWithNesting_3() - { - await TestWithMockedGenerateTypeDialog( -initial: @" -class A -{ - public class B - { - public class C : [|$$D|] - { - } - } -}", + public Task GenerateTypeWithProperAccessibilityWithNesting_3() + => TestWithMockedGenerateTypeDialog( +initial: """ + + class A + { + public class B + { + public class C : [|$$D|] + { + } + } + } + """, languageName: LanguageNames.CSharp, typeName: "D", -expected: @" -class A -{ - public class B - { - public class C : D - { - } - } -} +expected: """ -public class D -{ -}", + class A + { + public class B + { + public class C : D + { + } + } + } + + public class D + { + } + """, accessibility: Accessibility.Public, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.BaseList, false)); - } [Fact] - public async Task GenerateType_Event_1() - { - await TestWithMockedGenerateTypeDialog( -initial: @" -class A -{ - event [|$$goo|] name1 - { - add { } - remove { } - } -}", + public Task GenerateType_Event_1() + => TestWithMockedGenerateTypeDialog( +initial: """ + + class A + { + event [|$$goo|] name1 + { + add { } + remove { } + } + } + """, languageName: LanguageNames.CSharp, typeName: "goo", -expected: @" -class A -{ - event goo name1 - { - add { } - remove { } - } -} +expected: """ + + class A + { + event goo name1 + { + add { } + remove { } + } + } + + public delegate void goo(); -public delegate void goo(); -", + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Delegate)); - } [Fact] - public async Task GenerateType_Event_2() - { - await TestWithMockedGenerateTypeDialog( -initial: @" -class A -{ - public event [|$$goo|] name2; -}", + public Task GenerateType_Event_2() + => TestWithMockedGenerateTypeDialog( +initial: """ + + class A + { + public event [|$$goo|] name2; + } + """, languageName: LanguageNames.CSharp, typeName: "goo", -expected: @" -class A -{ - public event goo name2; -} +expected: """ -public delegate void goo(); -", + class A + { + public event goo name2; + } + + public delegate void goo(); + + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Delegate)); - } [Fact] - public async Task GenerateType_Event_3() - { - await TestWithMockedGenerateTypeDialog( -initial: @" -class A -{ - event [|NS.goo$$|] name1 - { - add { } - remove { } - } -}", + public Task GenerateType_Event_3() + => TestWithMockedGenerateTypeDialog( +initial: """ + + class A + { + event [|NS.goo$$|] name1 + { + add { } + remove { } + } + } + """, languageName: LanguageNames.CSharp, typeName: "goo", -expected: @" -class A -{ - event NS.goo name1 - { - add { } - remove { } - } -} +expected: """ -namespace NS -{ - public delegate void goo(); -}", + class A + { + event NS.goo name1 + { + add { } + remove { } + } + } + + namespace NS + { + public delegate void goo(); + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Delegate)); - } [Fact] - public async Task GenerateType_Event_4() - { - await TestWithMockedGenerateTypeDialog( -initial: @" -class A -{ - public event [|NS.goo$$|] name2; -}", + public Task GenerateType_Event_4() + => TestWithMockedGenerateTypeDialog( +initial: """ + + class A + { + public event [|NS.goo$$|] name2; + } + """, languageName: LanguageNames.CSharp, typeName: "goo", -expected: @" -class A -{ - public event NS.goo name2; -} +expected: """ -namespace NS -{ - public delegate void goo(); -}", + class A + { + public event NS.goo name2; + } + + namespace NS + { + public delegate void goo(); + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Delegate)); - } [Fact] - public async Task GenerateType_Event_5() - { - await TestWithMockedGenerateTypeDialog( -initial: @" -class A -{ - event [|$$NS.goo.Mydel|] name1 - { - add { } - remove { } - } -} + public Task GenerateType_Event_5() + => TestWithMockedGenerateTypeDialog( +initial: """ -namespace NS -{ -}", + class A + { + event [|$$NS.goo.Mydel|] name1 + { + add { } + remove { } + } + } + + namespace NS + { + } + """, languageName: LanguageNames.CSharp, typeName: "goo", -expected: @" -class A -{ - event NS.goo.Mydel name1 - { - add { } - remove { } - } -} +expected: """ -namespace NS -{ - public class goo - { - } -}", + class A + { + event NS.goo.Mydel name1 + { + add { } + remove { } + } + } + + namespace NS + { + public class goo + { + } + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Module)); - } [Fact] - public async Task GenerateType_Event_6() - { - await TestWithMockedGenerateTypeDialog( -initial: @" -class A -{ - public event [|$$NS.goo.Mydel|] name2; -} + public Task GenerateType_Event_6() + => TestWithMockedGenerateTypeDialog( +initial: """ -namespace NS -{ -}", + class A + { + public event [|$$NS.goo.Mydel|] name2; + } + + namespace NS + { + } + """, languageName: LanguageNames.CSharp, typeName: "goo", -expected: @" -class A -{ - public event NS.goo.Mydel name2; -} +expected: """ -namespace NS -{ - public class goo - { - } -}", + class A + { + public event NS.goo.Mydel name2; + } + + namespace NS + { + public class goo + { + } + } + """, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Module)); - } [Fact] - public async Task GenerateType_Event_7() - { - await TestWithMockedGenerateTypeDialog( -initial: @" -public class A -{ - public event [|$$goo|] name1 - { - add { } - remove { } - } -}", + public Task GenerateType_Event_7() + => TestWithMockedGenerateTypeDialog( +initial: """ + + public class A + { + public event [|$$goo|] name1 + { + add { } + remove { } + } + } + """, languageName: LanguageNames.CSharp, typeName: "goo", -expected: @" -public class A -{ - public event goo name1 - { - add { } - remove { } - } -} +expected: """ + + public class A + { + public event goo name1 + { + add { } + remove { } + } + } + + public delegate void goo(); -public delegate void goo(); -", + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(true, TypeKindOptions.Delegate)); - } [Fact] - public async Task GenerateType_Event_8() - { - await TestWithMockedGenerateTypeDialog( -initial: @" -public class outer -{ - public class A - { - public event [|$$goo|] name1 - { - add { } - remove { } - } - } -}", + public Task GenerateType_Event_8() + => TestWithMockedGenerateTypeDialog( +initial: """ + + public class outer + { + public class A + { + public event [|$$goo|] name1 + { + add { } + remove { } + } + } + } + """, languageName: LanguageNames.CSharp, typeName: "goo", -expected: @" -public class outer -{ - public class A - { - public event goo name1 - { - add { } - remove { } - } - } -} +expected: """ + + public class outer + { + public class A + { + public event goo name1 + { + add { } + remove { } + } + } + } + + public delegate void goo(); -public delegate void goo(); -", + """, accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(true, TypeKindOptions.Delegate)); - } #endregion } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/GenerateType/GenerateTypeWithUnboundAnalyzerTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/GenerateType/GenerateTypeWithUnboundAnalyzerTests.cs index 825c79849b29e..0112fd0ef97db 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/GenerateType/GenerateTypeWithUnboundAnalyzerTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/GenerateType/GenerateTypeWithUnboundAnalyzerTests.cs @@ -33,21 +33,23 @@ protected override ImmutableArray MassageActions(ImmutableArray TestInRegularAndScriptAsync( + """ + class Class + { + public [|Goo|] + } + """, + """ + class Class + { + public Goo + } + + internal class Goo + { + } + """, index: 1); - } } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/ImplementInterface/ImplementExplicitlyTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/ImplementInterface/ImplementExplicitlyTests.cs index fe28f9d4a5301..0b25a32c78fb5 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/ImplementInterface/ImplementExplicitlyTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/ImplementInterface/ImplementExplicitlyTests.cs @@ -28,9 +28,8 @@ protected override ImmutableArray MassageActions(ImmutableArray FlattenActions(actions); [Fact] - public async Task TestSingleMember() - { - await TestInRegularAndScriptAsync( + public Task TestSingleMember() + => TestInRegularAndScriptAsync( """ interface IGoo { void Goo1(); void Goo2(); } interface IBar { void Bar(); } @@ -57,12 +56,10 @@ public void Goo2() { } public void Bar() { } } """, index: SingleMember); - } [Fact] - public async Task TestSameInterface() - { - await TestInRegularAndScriptAsync( + public Task TestSameInterface() + => TestInRegularAndScriptAsync( """ interface IGoo { void Goo1(); void Goo2(); } interface IBar { void Bar(); } @@ -89,12 +86,10 @@ void IGoo.Goo2() { } public void Bar() { } } """, index: SameInterface); - } [Fact] - public async Task TestAllInterfaces() - { - await TestInRegularAndScriptAsync( + public Task TestAllInterfaces() + => TestInRegularAndScriptAsync( """ interface IGoo { void Goo1(); void Goo2(); } interface IBar { void Bar(); } @@ -121,12 +116,10 @@ void IGoo.Goo2() { } void IBar.Bar() { } } """, index: AllInterfaces); - } [Fact] - public async Task TestProperty() - { - await TestInRegularAndScriptAsync( + public Task TestProperty() + => TestInRegularAndScriptAsync( """ interface IGoo { int Goo1 { get; } } @@ -143,12 +136,10 @@ class C : IGoo int IGoo.Goo1 { get { } } } """, index: SingleMember); - } [Fact] - public async Task TestEvent() - { - await TestInRegularAndScriptAsync( + public Task TestEvent() + => TestInRegularAndScriptAsync( """ interface IGoo { event Action E; } @@ -165,12 +156,10 @@ class C : IGoo event Action IGoo.E { add { } remove { } } } """, index: SingleMember); - } [Fact] - public async Task TestNotOnExplicitMember() - { - await TestMissingAsync( + public Task TestNotOnExplicitMember() + => TestMissingAsync( """ interface IGoo { void Goo1(); } @@ -179,12 +168,10 @@ class C : IGoo void IGoo.[||]Goo1() { } } """); - } [Fact] - public async Task TestNotOnUnboundImplicitImpl() - { - await TestMissingAsync( + public Task TestNotOnUnboundImplicitImpl() + => TestMissingAsync( """ interface IGoo { void Goo1(); } @@ -193,12 +180,10 @@ class C public void [||]Goo1() { } } """); - } [Fact] - public async Task TestUpdateReferences_InsideDeclarations_Explicit() - { - await TestInRegularAndScriptAsync( + public Task TestUpdateReferences_InsideDeclarations_Explicit() + => TestInRegularAndScriptAsync( """ using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } @@ -221,12 +206,10 @@ class C : IGoo event Action IGoo.Ev { add { ((IGoo)this).Ev += value; } remove { ((IGoo)this).Ev -= value; } } } """, index: SameInterface); - } [Fact] - public async Task TestUpdateReferences_InsideDeclarations_Implicit() - { - await TestInRegularAndScriptAsync( + public Task TestUpdateReferences_InsideDeclarations_Implicit() + => TestInRegularAndScriptAsync( """ using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } @@ -249,12 +232,10 @@ class C : IGoo event Action IGoo.Ev { add { ((IGoo)this).Ev += value; } remove { ((IGoo)this).Ev -= value; } } } """, index: SameInterface); - } [Fact] - public async Task TestUpdateReferences_InternalImplicit() - { - await TestInRegularAndScriptAsync( + public Task TestUpdateReferences_InternalImplicit() + => TestInRegularAndScriptAsync( """ using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } @@ -307,12 +288,10 @@ void InternalImplicit() } } """, index: SameInterface); - } [Fact] - public async Task TestUpdateReferences_InternalExplicit() - { - await TestInRegularAndScriptAsync( + public Task TestUpdateReferences_InternalExplicit() + => TestInRegularAndScriptAsync( """ using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } @@ -365,12 +344,10 @@ void InternalExplicit() } } """, index: SameInterface); - } [Fact] - public async Task TestUpdateReferences_External() - { - await TestInRegularAndScriptAsync( + public Task TestUpdateReferences_External() + => TestInRegularAndScriptAsync( """ using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } @@ -439,12 +416,10 @@ void External(C c) } } """, index: SameInterface); - } [Fact] - public async Task TestUpdateReferences_CrossLanguage() - { - await TestInRegularAndScriptAsync( + public Task TestUpdateReferences_CrossLanguage() + => TestInRegularAndScriptAsync( """ @@ -519,12 +494,10 @@ end class """, index: SameInterface); - } [Fact] - public async Task TestMemberWhichImplementsMultipleMembers() - { - await TestInRegularAndScriptAsync( + public Task TestMemberWhichImplementsMultipleMembers() + => TestInRegularAndScriptAsync( """ interface IGoo { int M(int i); } interface IBar { int M(int i); } @@ -553,12 +526,10 @@ int IBar.M(int i) } } """, index: SingleMember); - } [Fact] - public async Task TestMemberWhichImplementsMultipleMembers2() - { - await TestInRegularAndScriptAsync( + public Task TestMemberWhichImplementsMultipleMembers2() + => TestInRegularAndScriptAsync( """ interface IGoo { int M(int i); } interface IBar { int M(int i); } @@ -587,12 +558,10 @@ int IBar.M(int i) } } """, index: SingleMember); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52020")] - public async Task TestWithContraints() - { - await TestInRegularAndScriptAsync( + public Task TestWithContraints() + => TestInRegularAndScriptAsync( """ interface IRepro { @@ -619,12 +588,10 @@ void IRepro.A(int value) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52020")] - public async Task TestWithDefaultParameterValues() - { - await TestInRegularAndScriptAsync( + public Task TestWithDefaultParameterValues() + => TestInRegularAndScriptAsync( """ interface IRepro { @@ -651,12 +618,10 @@ void IRepro.A(int value) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52020")] - public async Task TestWithMismatchedDefaultParameterValues() - { - await TestInRegularAndScriptAsync( + public Task TestWithMismatchedDefaultParameterValues() + => TestInRegularAndScriptAsync( """ interface IRepro { @@ -683,12 +648,10 @@ void IRepro.A(int value = 1) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52020")] - public async Task TestWithMismatchedDefault1() - { - await TestInRegularAndScriptAsync( + public Task TestWithMismatchedDefault1() + => TestInRegularAndScriptAsync( """ interface IRepro { @@ -715,12 +678,10 @@ void IRepro.A(int value = 1) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52020")] - public async Task TestWithMismatchedDefault2() - { - await TestInRegularAndScriptAsync( + public Task TestWithMismatchedDefault2() + => TestInRegularAndScriptAsync( """ interface IRepro { @@ -747,12 +708,10 @@ void IRepro.A(int value) } } """); - } [Fact] - public async Task TestPreserveReadOnly() - { - await TestInRegularAndScriptAsync( + public Task TestPreserveReadOnly() + => TestInRegularAndScriptAsync( """ interface IRepro { @@ -779,12 +738,10 @@ readonly void IRepro.A() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72024")] - public async Task TestFieldEvent() - { - await TestInRegularAndScriptAsync( + public Task TestFieldEvent() + => TestInRegularAndScriptAsync( """ using System; @@ -807,12 +764,10 @@ class C : IGoo void IGoo.M() { } } """, index: SameInterface); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72024")] - public async Task TestPropertyEvent() - { - await TestInRegularAndScriptAsync( + public Task TestPropertyEvent() + => TestInRegularAndScriptAsync( """ using System; @@ -833,5 +788,4 @@ class C : IGoo event Action IGoo.E { add { } remove { } }; } """, index: SingleMember); - } } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/ImplementInterface/ImplementImplicitlyTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/ImplementInterface/ImplementImplicitlyTests.cs index 3dfdfaffc2298..5309889e71f78 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/ImplementInterface/ImplementImplicitlyTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/ImplementInterface/ImplementImplicitlyTests.cs @@ -30,9 +30,8 @@ protected override ImmutableArray MassageActions(ImmutableArray FlattenActions(actions); [Fact] - public async Task TestSingleMember() - { - await TestInRegularAndScriptAsync( + public Task TestSingleMember() + => TestInRegularAndScriptAsync( """ interface IGoo { void Goo1(); void Goo2(); } interface IBar { void Bar(); } @@ -59,12 +58,10 @@ void IGoo.Goo2() { } void IBar.Bar() { } } """, index: SingleMember); - } [Fact] - public async Task TestSameInterface() - { - await TestInRegularAndScriptAsync( + public Task TestSameInterface() + => TestInRegularAndScriptAsync( """ interface IGoo { void Goo1(); void Goo2(); } interface IBar { void Bar(); } @@ -91,12 +88,10 @@ public void Goo2() { } void IBar.Bar() { } } """, index: SameInterface); - } [Fact] - public async Task TestAllInterfaces() - { - await TestInRegularAndScriptAsync( + public Task TestAllInterfaces() + => TestInRegularAndScriptAsync( """ interface IGoo { void Goo1(); void Goo2(); } interface IBar { void Bar(); } @@ -123,12 +118,10 @@ public void Goo2() { } public void Bar() { } } """, index: AllInterfaces); - } [Fact] - public async Task TestProperty() - { - await TestInRegularAndScriptAsync( + public Task TestProperty() + => TestInRegularAndScriptAsync( """ interface IGoo { int Goo1 { get; } } @@ -145,12 +138,10 @@ class C : IGoo public int Goo1 { get { } } } """, index: SingleMember); - } [Fact] - public async Task TestEvent() - { - await TestInRegularAndScriptAsync( + public Task TestEvent() + => TestInRegularAndScriptAsync( """ interface IGoo { event Action E; } @@ -167,12 +158,10 @@ class C : IGoo public event Action E { add { } remove { } } } """, index: SingleMember); - } [Fact] - public async Task TestNotOnImplicitMember() - { - await TestMissingAsync( + public Task TestNotOnImplicitMember() + => TestMissingAsync( """ interface IGoo { void Goo1(); } @@ -181,26 +170,20 @@ class C : IGoo public void [||]Goo1() { } } """); - } [Fact] - public async Task TestNotOnUnboundExplicitImpl() - { - await TestMissingAsync( + public Task TestNotOnUnboundExplicitImpl() + => TestMissingAsync( """ class C : IGoo { void IGoo.[||]Goo1() { } } """); - } [Fact] - public async Task TestCollision() - { - // Currently we don't do anything special here. But we just test here to make sure we - // don't blow up here. - await TestInRegularAndScriptAsync( + public Task TestCollision() + => TestInRegularAndScriptAsync( """ interface IGoo { void Goo1(); } @@ -221,12 +204,10 @@ public void Goo1() { } private void Goo1() { } } """, index: SingleMember); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48027")] - public async Task TestSingleMemberAndContainingTypeHasNoInterface() - { - await TestMissingAsync( + public Task TestSingleMemberAndContainingTypeHasNoInterface() + => TestMissingAsync( """ using System; using System.Collections; @@ -239,12 +220,10 @@ class C } } """); - } [Fact] - public async Task TestPreserveReadOnly() - { - await TestInRegularAndScriptAsync( + public Task TestPreserveReadOnly() + => TestInRegularAndScriptAsync( """ interface IGoo { void Goo1(); } @@ -261,12 +240,10 @@ class C : IGoo public readonly void Goo1() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70232")] - public async Task TestMissingWhenAlreadyContainingImpl() - { - await TestInRegularAndScriptAsync(""" + public Task TestMissingWhenAlreadyContainingImpl() + => TestInRegularAndScriptAsync(""" interface I { event System.EventHandler Click; @@ -291,12 +268,10 @@ event System.EventHandler I.Click { add { } remove { } } public event System.EventHandler Click } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72024")] - public async Task TestPropertyEvent() - { - await TestInRegularAndScriptAsync( + public Task TestPropertyEvent() + => TestInRegularAndScriptAsync( """ using System; @@ -317,5 +292,4 @@ class C : IGoo public event Action E { add { } remove { } }; } """, index: SingleMember); - } } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/InitializeParameter/AddParameterCheckTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/InitializeParameter/AddParameterCheckTests.cs index 7ee5e8e533ba7..cabb5f1d92dc2 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/InitializeParameter/AddParameterCheckTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/InitializeParameter/AddParameterCheckTests.cs @@ -30,9 +30,11 @@ public async Task TestEmptyFile() } [Fact] - public async Task TestSimpleReferenceType_AlreadyNullChecked1() - { - var testCode = """ + public Task TestSimpleReferenceType_AlreadyNullChecked1() + => new VerifyCS.Test + { + LanguageVersion = LanguageVersion.CSharp11, + TestCode = """ using System; class C @@ -45,18 +47,12 @@ public C([||]string s) } } } - """; - await new VerifyCS.Test - { - LanguageVersion = LanguageVersion.CSharp11, - TestCode = testCode + """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61181")] - public async Task TestSimpleReferenceType_AlreadyNullChecked2() - { - await new VerifyCS.Test + public Task TestSimpleReferenceType_AlreadyNullChecked2() + => new VerifyCS.Test { TestCode = """ using System; @@ -72,12 +68,10 @@ public C([||]string s) LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact] - public async Task TestSimpleReferenceType() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestSimpleReferenceType() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -102,12 +96,10 @@ public C(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61181")] - public async Task TestSimpleReferenceType_ThrowIfNull() - { - await new VerifyCS.Test + public Task TestSimpleReferenceType_ThrowIfNull() + => new VerifyCS.Test { TestCode = """ using System; @@ -132,12 +124,10 @@ public C(string s) """, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact] - public async Task TestSimpleReferenceType_CSharp6() - { - await new VerifyCS.Test + public Task TestSimpleReferenceType_CSharp6() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp6, TestCode = """ @@ -165,12 +155,10 @@ public C(string s) } """ }.RunAsync(); - } [Fact] - public async Task TestNullable() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestNullable() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -195,7 +183,6 @@ public C(int? i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47030")] public async Task TestNotOnOutParameter() @@ -294,9 +281,11 @@ class C [Theory] [InlineData(LanguageVersion.CSharp11)] [InlineData(LanguageVersion.CSharp8)] - public async Task TestNotOnPartialMethodDefinition1(LanguageVersion languageVersion) - { - var code = """ + public Task TestNotOnPartialMethodDefinition1(LanguageVersion languageVersion) + => new VerifyCS.Test + { + LanguageVersion = languageVersion, + TestCode = """ using System; partial class C @@ -307,18 +296,15 @@ partial void M(string s) { } } - """; - await new VerifyCS.Test - { - LanguageVersion = languageVersion, - TestCode = code + """ }.RunAsync(); - } [Fact] - public async Task TestNotOnExtendedPartialMethodDefinition1() - { - var code = """ + public Task TestNotOnExtendedPartialMethodDefinition1() + => new VerifyCS.Test + { + LanguageVersion = LanguageVersion.CSharp9, + TestCode = """ using System; partial class C @@ -329,20 +315,17 @@ public partial void M(string s) { } } - """; - await new VerifyCS.Test - { - LanguageVersion = LanguageVersion.CSharp9, - TestCode = code + """ }.RunAsync(); - } [Theory] [InlineData(LanguageVersion.CSharp11)] [InlineData(LanguageVersion.CSharp8)] - public async Task TestNotOnPartialMethodDefinition2(LanguageVersion languageVersion) - { - var code = """ + public Task TestNotOnPartialMethodDefinition2(LanguageVersion languageVersion) + => new VerifyCS.Test + { + LanguageVersion = languageVersion, + TestCode = """ using System; partial class C @@ -353,18 +336,15 @@ partial void M(string s) partial void M([||]string s); } - """; - await new VerifyCS.Test - { - LanguageVersion = languageVersion, - TestCode = code + """ }.RunAsync(); - } [Fact] - public async Task TestNotOnExtendedPartialMethodDefinition2() - { - var code = """ + public Task TestNotOnExtendedPartialMethodDefinition2() + => new VerifyCS.Test + { + LanguageVersion = LanguageVersion.CSharp9, + TestCode = """ using System; partial class C @@ -375,18 +355,12 @@ public partial void M(string s) public partial void M([||]string s); } - """; - await new VerifyCS.Test - { - LanguageVersion = LanguageVersion.CSharp9, - TestCode = code + """ }.RunAsync(); - } [Fact] - public async Task TestOnPartialMethodImplementation1() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestOnPartialMethodImplementation1() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -415,12 +389,10 @@ partial void M(string s) } } """); - } [Fact] - public async Task TestOnExtendedPartialMethodImplementation1() - { - await new VerifyCS.Test + public Task TestOnExtendedPartialMethodImplementation1() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp9, TestCode = """ @@ -452,12 +424,10 @@ public partial void M(string s) } """ }.RunAsync(); - } [Fact] - public async Task TestOnPartialMethodImplementation2() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestOnPartialMethodImplementation2() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -486,12 +456,10 @@ partial void M(string s) partial void M(string s); } """); - } [Fact] - public async Task TestOnExtendedPartialMethodImplementation2() - { - await new VerifyCS.Test + public Task TestOnExtendedPartialMethodImplementation2() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp9, TestCode = """ @@ -523,12 +491,10 @@ public partial void M(string s) } """ }.RunAsync(); - } [Fact] - public async Task TestUpdateExistingFieldAssignment() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestUpdateExistingFieldAssignment() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -555,12 +521,10 @@ public C(string s) } } """); - } [Fact] - public async Task TestMultiNullableParameters() - { - await new VerifyCS.Test + public Task TestMultiNullableParameters() + => new VerifyCS.Test { TestCode = """ using System; @@ -611,12 +575,10 @@ public C(string a, string b, string c) CodeActionIndex = 3, CodeActionEquivalenceKey = nameof(FeaturesResources.Add_null_checks_for_all_parameters) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61181")] - public async Task TestMultiNullableParameters_Net7() - { - await new VerifyCS.Test + public Task TestMultiNullableParameters_Net7() + => new VerifyCS.Test { TestCode = """ using System; @@ -645,12 +607,10 @@ public C(string a, string b, string c) CodeActionEquivalenceKey = nameof(FeaturesResources.Add_null_checks_for_all_parameters), ReferenceAssemblies = ReferenceAssemblies.Net.Net70, }.RunAsync(); - } [Fact] - public async Task TestMultiNullableParametersSomeNullableReferenceTypes() - { - await new VerifyCS.Test + public Task TestMultiNullableParametersSomeNullableReferenceTypes() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -696,7 +656,6 @@ public C(string a, string b, string? c) CodeActionIndex = 3, CodeActionEquivalenceKey = nameof(FeaturesResources.Add_null_checks_for_all_parameters) }.RunAsync(); - } [Fact] public async Task TestCursorNotOnParameters() @@ -715,9 +674,8 @@ public C(string a[|,|] string b, string c) } [Fact] - public async Task TestMultiNullableWithCursorOnNonNullable() - { - await new VerifyCS.Test + public Task TestMultiNullableWithCursorOnNonNullable() + => new VerifyCS.Test { TestCode = """ using System; @@ -758,12 +716,10 @@ public C(string a, bool b, string c) """, CodeActionEquivalenceKey = nameof(FeaturesResources.Add_null_checks_for_all_parameters) }.RunAsync(); - } [Fact] - public async Task TestMultiNullableNonNullable() - { - await new VerifyCS.Test + public Task TestMultiNullableNonNullable() + => new VerifyCS.Test { TestCode = """ using System; @@ -805,12 +761,10 @@ public C(string a, bool b, string c) CodeActionIndex = 3, CodeActionEquivalenceKey = nameof(FeaturesResources.Add_null_checks_for_all_parameters) }.RunAsync(); - } [Fact] - public async Task TestMultiNullableStringsAndObjects() - { - await new VerifyCS.Test + public Task TestMultiNullableStringsAndObjects() + => new VerifyCS.Test { TestCode = """ using System; @@ -857,12 +811,10 @@ public C(string a, object b, string c) CodeActionIndex = 3, CodeActionEquivalenceKey = nameof(FeaturesResources.Add_null_checks_for_all_parameters) }.RunAsync(); - } [Fact] - public async Task TestMultiNullableObjects() - { - await new VerifyCS.Test + public Task TestMultiNullableObjects() + => new VerifyCS.Test { TestCode = """ using System; @@ -901,12 +853,10 @@ public C(object a, object b, object c) CodeActionIndex = 1, CodeActionEquivalenceKey = nameof(FeaturesResources.Add_null_checks_for_all_parameters) }.RunAsync(); - } [Fact] - public async Task TestMultiNullableStructs() - { - await new VerifyCS.Test + public Task TestMultiNullableStructs() + => new VerifyCS.Test { TestCode = """ using System; @@ -945,12 +895,10 @@ public C(int ? a, bool ? b, double ? c) CodeActionIndex = 1, CodeActionEquivalenceKey = nameof(FeaturesResources.Add_null_checks_for_all_parameters) }.RunAsync(); - } [Fact] - public async Task TestUpdateExistingPropertyAssignment() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestUpdateExistingPropertyAssignment() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -977,12 +925,10 @@ public C(string s) } } """); - } [Fact] - public async Task DoNotUseThrowExpressionBeforeCSharp7() - { - await new VerifyCS.Test + public Task DoNotUseThrowExpressionBeforeCSharp7() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp6, TestCode = """ @@ -1017,12 +963,10 @@ public C(string s) } """ }.RunAsync(); - } [Fact] - public async Task RespectUseThrowExpressionOption() - { - await new VerifyCS.Test + public Task RespectUseThrowExpressionOption() + => new VerifyCS.Test { TestCode = """ using System; @@ -1060,12 +1004,10 @@ public C(string s) { CSharpCodeStyleOptions.PreferThrowExpression, false, NotificationOption2.Silent } } }.RunAsync(); - } [Fact] - public async Task TestUpdateExpressionBody1() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestUpdateExpressionBody1() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -1088,12 +1030,10 @@ public C(string s) => S = s ?? throw new ArgumentNullException(nameof(s)); } """); - } [Fact] - public async Task TestUpdateExpressionBody2() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestUpdateExpressionBody2() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -1127,12 +1067,10 @@ private void Init() } } """); - } [Fact] - public async Task TestUpdateExpressionBody3() - { - await new VerifyCS.Test + public Task TestUpdateExpressionBody3() + => new VerifyCS.Test { TestCode = """ using System; @@ -1172,12 +1110,10 @@ private void Init() { CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement } } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20983")] - public async Task TestUpdateLocalFunctionExpressionBody_NonVoid() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestUpdateLocalFunctionExpressionBody_NonVoid() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -1212,12 +1148,10 @@ int F(string s) private int Init() => 1; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20983")] - public async Task TestUpdateLocalFunctionExpressionBody_Void() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestUpdateLocalFunctionExpressionBody_Void() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -1252,12 +1186,10 @@ void F(string s) private int Init() => 1; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20983")] - public async Task TestUpdateLambdaExpressionBody_NonVoid() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestUpdateLambdaExpressionBody_NonVoid() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -1292,12 +1224,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20983")] - public async Task TestUpdateLambdaExpressionBody_Void() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestUpdateLambdaExpressionBody_Void() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -1332,12 +1262,10 @@ void NoValue() { } } } """); - } [Fact] - public async Task TestInsertAfterExistingNullCheck1() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestInsertAfterExistingNullCheck1() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -1369,12 +1297,10 @@ public C(string a, string s) } } """); - } [Fact] - public async Task TestInsertBeforeExistingNullCheck1() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestInsertBeforeExistingNullCheck1() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -1406,7 +1332,6 @@ public C(string a, string s) } } """); - } [Fact] public async Task TestMissingWithExistingNullCheck1() @@ -1582,9 +1507,8 @@ public C([||]string{|CS1001:)|} } [Fact] - public async Task TestInMethod() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestInMethod() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -1609,12 +1533,10 @@ void F(string s) } } """); - } [Fact] - public async Task TestInOperator() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestInOperator() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -1642,12 +1564,10 @@ class C } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20983")] - public async Task TestOnSimpleLambdaParameter() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestOnSimpleLambdaParameter() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -1678,12 +1598,10 @@ public C() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20983")] - public async Task TestOnSimpleLambdaParameter_EmptyBlock() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestOnSimpleLambdaParameter_EmptyBlock() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -1712,12 +1630,10 @@ public C() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20983")] - public async Task TestOnParenthesizedLambdaParameter() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestOnParenthesizedLambdaParameter() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -1748,12 +1664,10 @@ public C() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20983")] - public async Task TestOnDiscardLambdaParameter1() - { - await new VerifyCS.Test + public Task TestOnDiscardLambdaParameter1() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp11, TestCode = """ @@ -1787,12 +1701,13 @@ public C() } """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20983")] - public async Task TestOnDiscardLambdaParameter2() - { - var testCode = """ + public Task TestOnDiscardLambdaParameter2() + => new VerifyCS.Test + { + LanguageVersion = LanguageVersion.CSharp11, + TestCode = """ using System; class C @@ -1802,18 +1717,12 @@ public C() Func f = ([||]_, _) => { return 0; }; } } - """; - await new VerifyCS.Test - { - LanguageVersion = LanguageVersion.CSharp11, - TestCode = testCode + """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20983")] - public async Task TestOnAnonymousMethodParameter() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestOnAnonymousMethodParameter() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -1844,12 +1753,10 @@ public C() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20983")] - public async Task TestOnLocalFunctionParameter() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestOnLocalFunctionParameter() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -1880,7 +1787,6 @@ void F(string s) } } """); - } [Fact] public async Task TestNotOnIndexerParameter() @@ -1902,9 +1808,10 @@ int this[[||]string s] } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63307")] - public async Task TestNotOnIndexerParameterInRecordWithParameter() - { - var code = """ + public Task TestNotOnIndexerParameterInRecordWithParameter() + => new VerifyCS.Test + { + TestCode = """ record R(string S) { int this[[||]string s] @@ -1915,14 +1822,10 @@ int this[[||]string s] } } } - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net50, }.RunAsync(); - } [Fact] public async Task TestNotOnIndexerParameters() @@ -1944,9 +1847,8 @@ class C } [Fact] - public async Task TestSpecialStringCheck1() - { - await new VerifyCS.Test + public Task TestSpecialStringCheck1() + => new VerifyCS.Test { TestCode = """ using System; @@ -1979,12 +1881,10 @@ public C(string s) CodeActionIndex = 1, CodeActionEquivalenceKey = "Add_string_IsNullOrEmpty_check" }.RunAsync(); - } [Fact] - public async Task TestSpecialStringCheck2() - { - await new VerifyCS.Test + public Task TestSpecialStringCheck2() + => new VerifyCS.Test { TestCode = """ using System; @@ -2017,12 +1917,10 @@ public C(string s) CodeActionIndex = 2, CodeActionEquivalenceKey = "Add_string_IsNullOrWhiteSpace_check" }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61181")] - public async Task TestSpecialStringCheck2_Net8() - { - await new VerifyCS.Test + public Task TestSpecialStringCheck2_Net8() + => new VerifyCS.Test { TestCode = """ using System; @@ -2049,13 +1947,11 @@ public C(string s) CodeActionEquivalenceKey = "Add_string_IsNullOrWhiteSpace_check", ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51338")] [UseCulture("de-DE", "de-DE")] - public async Task TestSpecialStringCheck3() - { - await new VerifyCS.Test + public Task TestSpecialStringCheck3() + => new VerifyCS.Test { TestCode = """ using System; @@ -2088,7 +1984,6 @@ public C(string s) CodeActionIndex = 1, CodeActionEquivalenceKey = "Add_string_IsNullOrEmpty_check" }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19173")] public async Task TestMissingOnUnboundTypeWithExistingNullCheck() @@ -2109,9 +2004,8 @@ public C(string [||]s) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19174")] - public async Task TestRespectPredefinedTypePreferences() - { - await new VerifyCS.Test + public Task TestRespectPredefinedTypePreferences() + => new VerifyCS.Test { TestCode = """ using System; @@ -2148,14 +2042,12 @@ static void Main(String bar) { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, CodeStyleOption2.FalseWithSuggestionEnforcement } } }.RunAsync(); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/19172")] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] - public async Task TestPreferNoBlock(int preferBraces) - { - await new VerifyCS.Test + public Task TestPreferNoBlock(int preferBraces) + => new VerifyCS.Test { TestCode = """ using System; @@ -2183,12 +2075,10 @@ public C(string s) { CSharpCodeStyleOptions.PreferBraces, new CodeStyleOption2((PreferBracesPreference)preferBraces, NotificationOption2.Silent) }, } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19956")] - public async Task TestNoBlock() - { - await new VerifyCS.Test + public Task TestNoBlock() + => new VerifyCS.Test { TestCode = """ using System; @@ -2223,12 +2113,10 @@ public C(string s) InheritanceMode = StateInheritanceMode.Explicit } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21501")] - public async Task TestInArrowExpression1() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestInArrowExpression1() + => VerifyCS.VerifyRefactoringAsync( """ using System; using System.Linq; @@ -2260,12 +2148,10 @@ public int Foo(int[] array) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21501")] - public async Task TestInArrowExpression2() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestInArrowExpression2() + => VerifyCS.VerifyRefactoringAsync( """ using System; using System.Linq; @@ -2297,7 +2183,6 @@ public int Foo(int[] array) /* Bar */ } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21501")] public async Task TestMissingInArrowExpression1() @@ -2344,9 +2229,8 @@ public int Foo(int[] array[||]) => } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21501")] - public async Task TestInArrowExpression3() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestInArrowExpression3() + => VerifyCS.VerifyRefactoringAsync( """ using System; using System.Linq; @@ -2378,12 +2262,10 @@ public void Foo(int[] array) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29190")] - public async Task TestSimpleReferenceTypeWithParameterNameSelected1() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestSimpleReferenceTypeWithParameterNameSelected1() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -2408,7 +2290,6 @@ public C(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29333")] public async Task TestLambdaWithIncorrectNumberOfParameters() @@ -2457,9 +2338,8 @@ public static void M2([||]__arglist) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52383")] - public async Task TestImportSystem() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestImportSystem() + => VerifyCS.VerifyRefactoringAsync( """ class C { @@ -2482,12 +2362,10 @@ public C(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52385")] - public async Task SingleLineStatement_NullCheck_BracesNone_SameLineFalse() - { - await new VerifyCS.Test + public Task SingleLineStatement_NullCheck_BracesNone_SameLineFalse() + => new VerifyCS.Test { TestCode = """ using System; @@ -2518,12 +2396,10 @@ public C(object o) { CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine, false }, } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52385")] - public async Task SingleLineStatement_NullCheck_BracesWhenMultiline_SameLineFalse() - { - await new VerifyCS.Test + public Task SingleLineStatement_NullCheck_BracesWhenMultiline_SameLineFalse() + => new VerifyCS.Test { TestCode = """ using System; @@ -2554,12 +2430,10 @@ public C(object o) { CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine, false }, } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52385")] - public async Task SingleLineStatement_NullCheck_BracesAlways_SameLineFalse() - { - await new VerifyCS.Test + public Task SingleLineStatement_NullCheck_BracesAlways_SameLineFalse() + => new VerifyCS.Test { TestCode = """ using System; @@ -2592,12 +2466,10 @@ public C(object o) { CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine, false }, } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52385")] - public async Task SingleLineStatement_NullCheck_BracesNone_SameLineTrue() - { - await new VerifyCS.Test + public Task SingleLineStatement_NullCheck_BracesNone_SameLineTrue() + => new VerifyCS.Test { TestCode = """ using System; @@ -2627,12 +2499,10 @@ public C(object o) { CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine, true }, } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52385")] - public async Task SingleLineStatement_NullCheck_BracesWhenMultiline_SameLineTrue() - { - await new VerifyCS.Test + public Task SingleLineStatement_NullCheck_BracesWhenMultiline_SameLineTrue() + => new VerifyCS.Test { TestCode = """ using System; @@ -2662,12 +2532,10 @@ public C(object o) { CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine, true }, } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52385")] - public async Task SingleLineStatement_NullCheck_BracesAlways_SameLineTrue() - { - await new VerifyCS.Test + public Task SingleLineStatement_NullCheck_BracesAlways_SameLineTrue() + => new VerifyCS.Test { TestCode = """ using System; @@ -2700,12 +2568,10 @@ public C(object o) { CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine, true }, } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52385")] - public async Task SingleLineStatement_StringIsNullOrEmpty_BracesNone_SameLineFalse() - { - await new VerifyCS.Test + public Task SingleLineStatement_StringIsNullOrEmpty_BracesNone_SameLineFalse() + => new VerifyCS.Test { TestCode = """ using System; @@ -2742,12 +2608,10 @@ public C(string s) CodeActionIndex = 1, CodeActionEquivalenceKey = "Add_string_IsNullOrEmpty_check" }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52385")] - public async Task SingleLineStatement_StringIsNullOrEmpty_BracesWhenMultiline_SameLineFalse() - { - await new VerifyCS.Test + public Task SingleLineStatement_StringIsNullOrEmpty_BracesWhenMultiline_SameLineFalse() + => new VerifyCS.Test { TestCode = """ using System; @@ -2784,12 +2648,10 @@ public C(string s) CodeActionIndex = 1, CodeActionEquivalenceKey = "Add_string_IsNullOrEmpty_check" }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52385")] - public async Task SingleLineStatement_StringIsNullOrEmpty_BracesAlways_SameLineFalse() - { - await new VerifyCS.Test + public Task SingleLineStatement_StringIsNullOrEmpty_BracesAlways_SameLineFalse() + => new VerifyCS.Test { TestCode = """ using System; @@ -2828,12 +2690,10 @@ public C(string s) CodeActionIndex = 1, CodeActionEquivalenceKey = "Add_string_IsNullOrEmpty_check" }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52385")] - public async Task SingleLineStatement_StringIsNullOrEmpty_BracesNone_SameLineTrue() - { - await new VerifyCS.Test + public Task SingleLineStatement_StringIsNullOrEmpty_BracesNone_SameLineTrue() + => new VerifyCS.Test { TestCode = """ using System; @@ -2869,12 +2729,10 @@ public C(string s) CodeActionIndex = 1, CodeActionEquivalenceKey = "Add_string_IsNullOrEmpty_check" }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52385")] - public async Task SingleLineStatement_StringIsNullOrEmpty_BracesWhenMultiline_SameLineTrue() - { - await new VerifyCS.Test + public Task SingleLineStatement_StringIsNullOrEmpty_BracesWhenMultiline_SameLineTrue() + => new VerifyCS.Test { TestCode = """ using System; @@ -2910,12 +2768,10 @@ public C(string s) CodeActionIndex = 1, CodeActionEquivalenceKey = "Add_string_IsNullOrEmpty_check" }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52385")] - public async Task SingleLineStatement_StringIsNullOrEmpty_BracesAlways_SameLineTrue() - { - await new VerifyCS.Test + public Task SingleLineStatement_StringIsNullOrEmpty_BracesAlways_SameLineTrue() + => new VerifyCS.Test { TestCode = """ using System; @@ -2954,12 +2810,10 @@ public C(string s) CodeActionIndex = 1, CodeActionEquivalenceKey = "Add_string_IsNullOrEmpty_check" }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52385")] - public async Task SingleLineStatement_NullCheck_AllParameters() - { - await new VerifyCS.Test + public Task SingleLineStatement_NullCheck_AllParameters() + => new VerifyCS.Test { TestCode = """ using System; @@ -2993,7 +2847,6 @@ public C(object a, object b, object c) CodeActionIndex = 1, CodeActionEquivalenceKey = nameof(FeaturesResources.Add_null_checks_for_all_parameters) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58811")] public async Task TestMissingParameter1() @@ -3063,48 +2916,38 @@ public C(string s, [||] {|CS1031:{|CS1001:)|}|} [WorkItem("https://github.com/dotnet/roslyn/issues/58779")] [InlineData(LanguageVersion.CSharp10)] [InlineData(LanguageVersion.CSharp11)] - public async Task TestNotInRecord(LanguageVersion version) - { - var code = """ - record C([||]string s) { public string s; } - """; - await new VerifyCS.Test + public Task TestNotInRecord(LanguageVersion version) + => new VerifyCS.Test { LanguageVersion = version, - TestCode = code, + TestCode = """ + record C([||]string s) { public string s; } + """, }.RunAsync(); - } [Fact] - public async Task TestNotInClass() - { - var code = """ - class C([||]string s) { public string s; } - """; - await new VerifyCS.Test + public Task TestNotInClass() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp12, - TestCode = code, + TestCode = """ + class C([||]string s) { public string s; } + """, }.RunAsync(); - } [Fact] - public async Task TestNotInStruct() - { - var code = """ - struct C([||]string s) { public string s; } - """; - await new VerifyCS.Test + public Task TestNotInStruct() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp12, - TestCode = code, + TestCode = """ + struct C([||]string s) { public string s; } + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38093")] - public async Task TestReadBeforeAssignment() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task TestReadBeforeAssignment() + => VerifyCS.VerifyRefactoringAsync(""" using System; using System.IO; @@ -3138,12 +2981,10 @@ public Program([||]Stream output) public Stream OutStream { get; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41140")] - public async Task TestAfterComma1() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task TestAfterComma1() + => VerifyCS.VerifyRefactoringAsync(""" using System; class C @@ -3169,12 +3010,10 @@ void M(string a, string b, string c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41140")] - public async Task TestAfterComma2() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task TestAfterComma2() + => VerifyCS.VerifyRefactoringAsync(""" using System; class C @@ -3202,12 +3041,10 @@ void M(string a, } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66327")] - public async Task TestSimpleEnumIsDefinedCheck_ModernEnumIsDefinedOverload() - { - await new VerifyCS.Test() + public Task TestSimpleEnumIsDefinedCheck_ModernEnumIsDefinedOverload() + => new VerifyCS.Test() { TestCode = """ using System; @@ -3235,12 +3072,10 @@ void M(DayOfWeek dayOfWeek) """, ReferenceAssemblies = ReferenceAssemblies.Net.Net80 }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66327")] - public async Task TestSimpleEnumIsDefinedCheck_OldEnumIsDefinedOverload() - { - await new VerifyCS.Test() + public Task TestSimpleEnumIsDefinedCheck_OldEnumIsDefinedOverload() + => new VerifyCS.Test() { TestCode = """ using System; @@ -3270,12 +3105,10 @@ void M(DayOfWeek dayOfWeek) """, ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard20 }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66327")] - public async Task TestNoEnumIsDefinedCheckForOutEnumParameter() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task TestNoEnumIsDefinedCheckForOutEnumParameter() + => VerifyCS.VerifyRefactoringAsync(""" using System; using System.ComponentModel; @@ -3287,12 +3120,10 @@ void M(out DayOfWeek [|result|]) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66327")] - public async Task TestNoEnumIsDefinedCheckForFlagsEnumParameter() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task TestNoEnumIsDefinedCheckForFlagsEnumParameter() + => VerifyCS.VerifyRefactoringAsync(""" using System; using System.ComponentModel; @@ -3310,7 +3141,6 @@ enum MyFlags B = 2 } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66327")] public async Task TestNoEnumIsDefinedCheckIfAlreadyExist_ModernEnumIsDefinedOverload() @@ -3367,9 +3197,8 @@ void M(DayOfWeek [|dayOfWeek|]) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66327")] - public async Task TestEnumIsDefinedCheckAfterAnotherEnumIsDefinedCheck() - { - await new VerifyCS.Test() + public Task TestEnumIsDefinedCheckAfterAnotherEnumIsDefinedCheck() + => new VerifyCS.Test() { TestCode = """ using System; @@ -3408,12 +3237,10 @@ void M(DayOfWeek dayOfWeek1, DayOfWeek dayOfWeek2) """, ReferenceAssemblies = ReferenceAssemblies.Net.Net80 }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66327")] - public async Task TestEnumIsDefinedCheckBeforeAnotherEnumIsDefinedCheck() - { - await new VerifyCS.Test() + public Task TestEnumIsDefinedCheckBeforeAnotherEnumIsDefinedCheck() + => new VerifyCS.Test() { TestCode = """ using System; @@ -3452,12 +3279,10 @@ void M(DayOfWeek dayOfWeek1, DayOfWeek dayOfWeek2) """, ReferenceAssemblies = ReferenceAssemblies.Net.Net80 }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66327")] - public async Task TestEnumIsDefinedCheckAfterNullCheck() - { - await new VerifyCS.Test() + public Task TestEnumIsDefinedCheckAfterNullCheck() + => new VerifyCS.Test() { TestCode = """ using System; @@ -3489,12 +3314,10 @@ void M(string s, DayOfWeek dayOfWeek) """, ReferenceAssemblies = ReferenceAssemblies.Net.Net80 }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66327")] - public async Task TestEnumIsDefinedCheckBeforeNullCheck() - { - await new VerifyCS.Test() + public Task TestEnumIsDefinedCheckBeforeNullCheck() + => new VerifyCS.Test() { TestCode = """ using System; @@ -3533,12 +3356,10 @@ void M(DayOfWeek dayOfWeek, object o) """, ReferenceAssemblies = ReferenceAssemblies.Net.Net80 }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66327")] - public async Task TestEnumIsDefinedCheckInBetweenChecks() - { - await new VerifyCS.Test() + public Task TestEnumIsDefinedCheckInBetweenChecks() + => new VerifyCS.Test() { TestCode = """ using System; @@ -3581,7 +3402,6 @@ void M(object o, DayOfWeek dayOfWeek, string s) """, ReferenceAssemblies = ReferenceAssemblies.Net.Net80 }.RunAsync(); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/37653")] [InlineData("sbyte")] @@ -3706,9 +3526,8 @@ void M({{validNumericType}} [|num|]) [InlineData("ulong")] [InlineData("float")] [InlineData("double")] - public async Task TestNoNumericChecksForUnsignedAndFloatingPointNumericTypes(string invalidNumericType) - { - await VerifyCS.VerifyRefactoringAsync($$""" + public Task TestNoNumericChecksForUnsignedAndFloatingPointNumericTypes(string invalidNumericType) + => VerifyCS.VerifyRefactoringAsync($$""" using System; class C @@ -3718,12 +3537,10 @@ void M({{invalidNumericType}} [|num|]) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37653")] - public async Task TestNoNumericChecksForOutParameter() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task TestNoNumericChecksForOutParameter() + => VerifyCS.VerifyRefactoringAsync(""" using System; class C @@ -3734,7 +3551,6 @@ void M(out int [|num|]) } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/37653")] [InlineData("ThrowIfNegative(num)")] @@ -3747,9 +3563,8 @@ void M(out int [|num|]) [InlineData("ThrowIfEqual(num, 15)")] [InlineData("ThrowIfNotEqual(num, 10)")] [InlineData("ThrowIfZero(num)")] - public async Task TestNoNumericChecksIfAlreadyExist_ModernOverloads(string methodInvocation) - { - await new VerifyCS.Test() + public Task TestNoNumericChecksIfAlreadyExist_ModernOverloads(string methodInvocation) + => new VerifyCS.Test() { TestCode = $$""" using System; @@ -3764,7 +3579,6 @@ void M(int [|num|]) """, ReferenceAssemblies = ReferenceAssemblies.Net.Net80 }.RunAsync(); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/37653")] [InlineData("num < 0")] @@ -3785,9 +3599,8 @@ void M(int [|num|]) [InlineData("num is <= 18")] [InlineData("num is > 5")] [InlineData("num is >= 3")] - public async Task TestNoNumericChecksIfAlreadyExist_OldStyleCheckStatements(string numericCheck) - { - await new VerifyCS.Test() + public Task TestNoNumericChecksIfAlreadyExist_OldStyleCheckStatements(string numericCheck) + => new VerifyCS.Test() { TestCode = $$""" using System; @@ -3806,12 +3619,10 @@ void M(int [|num|]) LanguageVersion = LanguageVersion.Latest, ReferenceAssemblies = ReferenceAssemblies.Net.Net80 }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37653")] - public async Task TestNumericChecksAfterAnotherNumericCheck() - { - await new VerifyCS.Test() + public Task TestNumericChecksAfterAnotherNumericCheck() + => new VerifyCS.Test() { TestCode = """ using System; @@ -3838,12 +3649,10 @@ void M(sbyte a, short [|b|]) """, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37653")] - public async Task TestNumericChecksBeforeAnotherNumericCheck() - { - await new VerifyCS.Test() + public Task TestNumericChecksBeforeAnotherNumericCheck() + => new VerifyCS.Test() { TestCode = """ using System; @@ -3877,12 +3686,10 @@ void M(long a, int b) ReferenceAssemblies = ReferenceAssemblies.Net.Net80, CodeActionIndex = 1 }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37653")] - public async Task TestNumericChecksInBetweenDifferentChecks() - { - await new VerifyCS.Test() + public Task TestNumericChecksInBetweenDifferentChecks() + => new VerifyCS.Test() { TestCode = """ using System; @@ -3929,5 +3736,4 @@ void M(DayOfWeek day, int i, string s) """, ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard20 }.RunAsync(); - } } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/InitializeParameter/InitializeMemberFromParameterTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/InitializeParameter/InitializeMemberFromParameterTests.cs index 06502fd821b8a..88c95de681123 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/InitializeParameter/InitializeMemberFromParameterTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/InitializeParameter/InitializeMemberFromParameterTests.cs @@ -24,9 +24,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(EditorT private readonly NamingStylesTestOptionSets options = new(LanguageNames.CSharp); [Fact] - public async Task TestInitializeFieldWithSameName() - { - await TestInRegularAndScript1Async( + public Task TestInitializeFieldWithSameName() + => TestInRegularAndScript1Async( """ class C { @@ -48,12 +47,10 @@ public C(string s) } } """); - } [Fact] - public async Task TestEndOfParameter1() - { - await TestInRegularAndScript1Async( + public Task TestEndOfParameter1() + => TestInRegularAndScript1Async( """ class C { @@ -75,12 +72,10 @@ public C(string s) } } """); - } [Fact] - public async Task TestEndOfParameter2() - { - await TestInRegularAndScript1Async( + public Task TestEndOfParameter2() + => TestInRegularAndScript1Async( """ class C { @@ -102,12 +97,10 @@ public C(string s, string t) } } """); - } [Fact] - public async Task TestInitializeFieldWithUnderscoreName() - { - await TestInRegularAndScript1Async( + public Task TestInitializeFieldWithUnderscoreName() + => TestInRegularAndScript1Async( """ class C { @@ -129,12 +122,10 @@ public C(string s) } } """); - } [Fact] - public async Task TestInitializeWritableProperty() - { - await TestInRegularAndScript1Async( + public Task TestInitializeWritableProperty() + => TestInRegularAndScript1Async( """ class C { @@ -156,12 +147,10 @@ public C(string s) } } """); - } [Fact] - public async Task TestInitializeFieldWithDifferentName() - { - await TestInRegularAndScriptAsync( + public Task TestInitializeFieldWithDifferentName() + => TestInRegularAndScriptAsync( """ class C { @@ -185,12 +174,10 @@ public C(string s) public string S { get; } } """); - } [Fact] - public async Task TestInitializeNonWritableProperty() - { - await TestInRegularAndScript1Async( + public Task TestInitializeNonWritableProperty() + => TestInRegularAndScript1Async( """ class C { @@ -214,12 +201,10 @@ public C(string s) } } """); - } [Fact] - public async Task TestInitializeDoesNotUsePropertyWithUnrelatedName() - { - await TestInRegularAndScriptAsync( + public Task TestInitializeDoesNotUsePropertyWithUnrelatedName() + => TestInRegularAndScriptAsync( """ class C { @@ -242,12 +227,10 @@ public C(string s) } } """); - } [Fact] - public async Task TestInitializeFieldWithWrongType1() - { - await TestInRegularAndScript1Async( + public Task TestInitializeFieldWithWrongType1() + => TestInRegularAndScript1Async( """ class C { @@ -271,12 +254,10 @@ public C(string s) public string S { get; } } """); - } [Fact] - public async Task TestInitializeFieldWithWrongType2() - { - await TestInRegularAndScript1Async( + public Task TestInitializeFieldWithWrongType2() + => TestInRegularAndScript1Async( """ class C { @@ -299,12 +280,10 @@ public C(string s) } } """, index: 1); - } [Fact] - public async Task TestInitializeFieldWithConvertibleType() - { - await TestInRegularAndScriptAsync( + public Task TestInitializeFieldWithConvertibleType() + => TestInRegularAndScriptAsync( """ class C { @@ -326,12 +305,10 @@ public C(string s) } } """); - } [Fact] - public async Task TestWhenAlreadyInitialized1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWhenAlreadyInitialized1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -344,12 +321,10 @@ public C([||]string s) } } """); - } [Fact] - public async Task TestWhenAlreadyInitialized2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWhenAlreadyInitialized2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -362,12 +337,10 @@ public C([||]string s) } } """); - } [Fact] - public async Task TestWhenAlreadyInitialized3() - { - await TestInRegularAndScript1Async( + public Task TestWhenAlreadyInitialized3() + => TestInRegularAndScript1Async( """ class C { @@ -394,12 +367,10 @@ public C([||]string s) public string S { get; } } """); - } [Fact] - public async Task TestInsertionLocation1() - { - await TestInRegularAndScript1Async( + public Task TestInsertionLocation1() + => TestInRegularAndScript1Async( """ class C { @@ -425,12 +396,10 @@ public C(string s, string t) } } """); - } [Fact] - public async Task TestInsertionLocation2() - { - await TestInRegularAndScript1Async( + public Task TestInsertionLocation2() + => TestInRegularAndScript1Async( """ class C { @@ -456,12 +425,10 @@ public C(string s, string t) } } """); - } [Fact] - public async Task TestInsertionLocation3() - { - await TestInRegularAndScript1Async( + public Task TestInsertionLocation3() + => TestInRegularAndScript1Async( """ class C { @@ -486,12 +453,10 @@ public C(string s) } } """); - } [Fact] - public async Task TestNotInMethod() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotInMethod() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -502,12 +467,10 @@ public void M([||]string s) } } """); - } [Fact] - public async Task TestInsertionLocation4() - { - await TestInRegularAndScript1Async( + public Task TestInsertionLocation4() + => TestInRegularAndScript1Async( """ class C { @@ -531,12 +494,10 @@ public C(string s, string t) } } """); - } [Fact] - public async Task TestInsertionLocation5() - { - await TestInRegularAndScript1Async( + public Task TestInsertionLocation5() + => TestInRegularAndScript1Async( """ class C { @@ -560,12 +521,10 @@ public C(string s, string t) } } """); - } [Fact] - public async Task TestInsertionLocation6() - { - await TestInRegularAndScript1Async( + public Task TestInsertionLocation6() + => TestInRegularAndScript1Async( """ class C { @@ -590,12 +549,10 @@ public C(string s, string t) public string T { get; } } """); - } [Fact] - public async Task TestInsertionLocation7() - { - await TestInRegularAndScript1Async( + public Task TestInsertionLocation7() + => TestInRegularAndScript1Async( """ class C { @@ -620,12 +577,10 @@ public C(string s, string t) public string T { get; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19956")] - public async Task TestNoBlock() - { - await TestInRegularAndScript1Async( + public Task TestNoBlock() + => TestInRegularAndScript1Async( """ class C { @@ -645,12 +600,10 @@ public C(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29190")] - public async Task TestInitializeFieldWithParameterNameSelected1() - { - await TestInRegularAndScript1Async( + public Task TestInitializeFieldWithParameterNameSelected1() + => TestInRegularAndScript1Async( """ class C { @@ -672,12 +625,10 @@ public C(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29190")] - public async Task TestInitializeField_ParameterNameSelected2() - { - await TestInRegularAndScript1Async( + public Task TestInitializeField_ParameterNameSelected2() + => TestInRegularAndScript1Async( """ class C { @@ -699,12 +650,10 @@ public C(string s, int i) } } """); - } [Fact] - public async Task TestInitializeClassProperty_RequiredAccessibilityOmitIfDefault() - { - await TestInRegularAndScript1Async( + public Task TestInitializeClassProperty_RequiredAccessibilityOmitIfDefault() + => TestInRegularAndScript1Async( """ class C { @@ -728,12 +677,10 @@ public C(int test, int test2) public int Test2 { get; } } """, index: 0, parameters: OmitIfDefault_Warning); - } [Fact] - public async Task TestInitializeClassProperty_RequiredAccessibilityNever() - { - await TestInRegularAndScript1Async( + public Task TestInitializeClassProperty_RequiredAccessibilityNever() + => TestInRegularAndScript1Async( """ class C { @@ -757,12 +704,10 @@ public C(int test, int test2) public int Test2 { get; } } """, index: 0, parameters: Never_Warning); - } [Fact] - public async Task TestInitializeClassProperty_RequiredAccessibilityAlways() - { - await TestInRegularAndScript1Async( + public Task TestInitializeClassProperty_RequiredAccessibilityAlways() + => TestInRegularAndScript1Async( """ class C { @@ -786,12 +731,10 @@ public C(int test, int test2) public int Test2 { get; } } """, index: 0, parameters: Always_Warning); - } [Fact] - public async Task TestInitializeClassField_RequiredAccessibilityOmitIfDefault() - { - await TestInRegularAndScript1Async( + public Task TestInitializeClassField_RequiredAccessibilityOmitIfDefault() + => TestInRegularAndScript1Async( """ class C { @@ -814,12 +757,10 @@ public C(int test, int test2) } } """, index: 1, parameters: OmitIfDefault_Warning); - } [Fact] - public async Task TestInitializeClassField_RequiredAccessibilityNever() - { - await TestInRegularAndScript1Async( + public Task TestInitializeClassField_RequiredAccessibilityNever() + => TestInRegularAndScript1Async( """ class C { @@ -842,12 +783,10 @@ public C(int test, int test2) } } """, index: 1, parameters: Never_Warning); - } [Fact] - public async Task TestInitializeClassField_RequiredAccessibilityAlways() - { - await TestInRegularAndScript1Async( + public Task TestInitializeClassField_RequiredAccessibilityAlways() + => TestInRegularAndScript1Async( """ class C { @@ -870,12 +809,10 @@ public C(int test, int test2) } } """, index: 1, parameters: Always_Warning); - } [Fact] - public async Task TestInitializeStructProperty_RequiredAccessibilityOmitIfDefault() - { - await TestInRegularAndScript1Async( + public Task TestInitializeStructProperty_RequiredAccessibilityOmitIfDefault() + => TestInRegularAndScript1Async( """ struct S { @@ -895,12 +832,10 @@ public Test(int test) public int Test { get; } } """, index: 0, parameters: OmitIfDefault_Warning); - } [Fact] - public async Task TestInitializeStructProperty_RequiredAccessibilityNever() - { - await TestInRegularAndScript1Async( + public Task TestInitializeStructProperty_RequiredAccessibilityNever() + => TestInRegularAndScript1Async( """ struct S { @@ -920,12 +855,10 @@ public Test(int test) public int Test { get; } } """, index: 0, parameters: Never_Warning); - } [Fact] - public async Task TestInitializeStructProperty_RequiredAccessibilityAlways() - { - await TestInRegularAndScript1Async( + public Task TestInitializeStructProperty_RequiredAccessibilityAlways() + => TestInRegularAndScript1Async( """ struct S { @@ -945,12 +878,10 @@ public Test(int test) public int Test { get; } } """, index: 0, parameters: Always_Warning); - } [Fact] - public async Task TestInitializeStructField_RequiredAccessibilityOmitIfDefault() - { - await TestInRegularAndScript1Async( + public Task TestInitializeStructField_RequiredAccessibilityOmitIfDefault() + => TestInRegularAndScript1Async( """ struct S { @@ -970,12 +901,10 @@ public Test(int test) } } """, index: 1, parameters: OmitIfDefault_Warning); - } [Fact] - public async Task TestInitializeStructField_RequiredAccessibilityNever() - { - await TestInRegularAndScript1Async( + public Task TestInitializeStructField_RequiredAccessibilityNever() + => TestInRegularAndScript1Async( """ struct S { @@ -995,12 +924,10 @@ public Test(int test) } } """, index: 1, parameters: Never_Warning); - } [Fact] - public async Task TestInitializeStructField_RequiredAccessibilityAlways() - { - await TestInRegularAndScript1Async( + public Task TestInitializeStructField_RequiredAccessibilityAlways() + => TestInRegularAndScript1Async( """ struct S { @@ -1020,12 +947,10 @@ public Test(int test) } } """, index: 1, parameters: Always_Warning); - } [Fact] - public async Task TestNoParameterNamingStyle_CreateAndInitField() - { - await TestInRegularAndScript1Async( + public Task TestNoParameterNamingStyle_CreateAndInitField() + => TestInRegularAndScript1Async( """ class C { @@ -1045,12 +970,10 @@ public C(string s) } } """, index: 1, parameters: new TestParameters(options: options.FieldNamesAreCamelCaseWithUnderscorePrefix)); - } [Fact] - public async Task TestCommonParameterNamingStyle_CreateAndInitField() - { - await TestInRegularAndScript1Async( + public Task TestCommonParameterNamingStyle_CreateAndInitField() + => TestInRegularAndScript1Async( """ class C { @@ -1070,12 +993,10 @@ public C(string t_s) } } """, index: 1, parameters: new TestParameters(options: options.FieldNamesAreCamelCaseWithUnderscorePrefix)); - } [Fact] - public async Task TestSpecifiedParameterNamingStyle_CreateAndInitField() - { - await TestInRegularAndScript1Async( + public Task TestSpecifiedParameterNamingStyle_CreateAndInitField() + => TestInRegularAndScript1Async( """ class C { @@ -1095,12 +1016,10 @@ public C(string p_s_End) } } """, index: 1, parameters: new TestParameters(options: options.MergeStyles(options.FieldNamesAreCamelCaseWithUnderscorePrefix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestCommonAndSpecifiedParameterNamingStyle_CreateAndInitField() - { - await TestInRegularAndScript1Async( + public Task TestCommonAndSpecifiedParameterNamingStyle_CreateAndInitField() + => TestInRegularAndScript1Async( """ class C { @@ -1120,12 +1039,10 @@ public C(string t_p_s_End) } } """, index: 1, parameters: new TestParameters(options: options.MergeStyles(options.FieldNamesAreCamelCaseWithUnderscorePrefix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestCommonAndSpecifiedParameterNamingStyle2_CreateAndInitField() - { - await TestInRegularAndScript1Async( + public Task TestCommonAndSpecifiedParameterNamingStyle2_CreateAndInitField() + => TestInRegularAndScript1Async( """ class C { @@ -1145,12 +1062,10 @@ public C([||]string p_t_s) } } """, index: 1, parameters: new TestParameters(options: options.MergeStyles(options.FieldNamesAreCamelCaseWithUnderscorePrefix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefix))); - } [Fact] - public async Task TestNoParameterNamingStyle_CreateAndInitProperty() - { - await TestInRegularAndScript1Async( + public Task TestNoParameterNamingStyle_CreateAndInitProperty() + => TestInRegularAndScript1Async( """ class C { @@ -1170,12 +1085,10 @@ public C(string s) public string S { get; } } """, parameters: new TestParameters(options: options.PropertyNamesArePascalCase)); - } [Fact] - public async Task TestCommonParameterNamingStyle_CreateAndInitProperty() - { - await TestInRegularAndScript1Async( + public Task TestCommonParameterNamingStyle_CreateAndInitProperty() + => TestInRegularAndScript1Async( """ class C { @@ -1195,12 +1108,10 @@ public C(string t_s) public string S { get; } } """, parameters: new TestParameters(options: options.PropertyNamesArePascalCase)); - } [Fact] - public async Task TestSpecifiedParameterNamingStyle_CreateAndInitProperty() - { - await TestInRegularAndScript1Async( + public Task TestSpecifiedParameterNamingStyle_CreateAndInitProperty() + => TestInRegularAndScript1Async( """ class C { @@ -1220,12 +1131,10 @@ public C(string p_s_End) public string S { get; } } """, parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestCommonAndSpecifiedParameterNamingStyle_CreateAndInitProperty() - { - await TestInRegularAndScript1Async( + public Task TestCommonAndSpecifiedParameterNamingStyle_CreateAndInitProperty() + => TestInRegularAndScript1Async( """ class C { @@ -1245,12 +1154,10 @@ public C(string t_p_s_End) public string S { get; } } """, parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestCommonAndSpecifiedParameterNamingStyle2_CreateAndInitProperty() - { - await TestInRegularAndScript1Async( + public Task TestCommonAndSpecifiedParameterNamingStyle2_CreateAndInitProperty() + => TestInRegularAndScript1Async( """ class C { @@ -1270,12 +1177,10 @@ public C([||]string p_t_s_End) public string S { get; } } """, parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestNoParameterNamingStyle_InitializeField() - { - await TestInRegularAndScript1Async( + public Task TestNoParameterNamingStyle_InitializeField() + => TestInRegularAndScript1Async( """ class C { @@ -1297,12 +1202,10 @@ public C(string s) } } """, index: 0, parameters: new TestParameters(options: options.FieldNamesAreCamelCaseWithUnderscorePrefix)); - } [Fact] - public async Task TestCommonParameterNamingStyle_InitializeField() - { - await TestInRegularAndScript1Async( + public Task TestCommonParameterNamingStyle_InitializeField() + => TestInRegularAndScript1Async( """ class C { @@ -1324,12 +1227,10 @@ public C(string t_s) } } """, index: 0, parameters: new TestParameters(options: options.FieldNamesAreCamelCaseWithUnderscorePrefix)); - } [Fact] - public async Task TestSpecifiedParameterNamingStyle_InitializeField() - { - await TestInRegularAndScript1Async( + public Task TestSpecifiedParameterNamingStyle_InitializeField() + => TestInRegularAndScript1Async( """ class C { @@ -1351,12 +1252,10 @@ public C(string p_s_End) } } """, index: 0, parameters: new TestParameters(options: options.MergeStyles(options.FieldNamesAreCamelCaseWithUnderscorePrefix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestCommonAndSpecifiedParameterNamingStyle_InitializeField() - { - await TestInRegularAndScript1Async( + public Task TestCommonAndSpecifiedParameterNamingStyle_InitializeField() + => TestInRegularAndScript1Async( """ class C { @@ -1378,12 +1277,10 @@ public C(string t_p_s_End) } } """, index: 0, parameters: new TestParameters(options: options.MergeStyles(options.FieldNamesAreCamelCaseWithUnderscorePrefix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestCommonAndSpecifiedParameterNamingStyle2_InitializeField() - { - await TestInRegularAndScript1Async( + public Task TestCommonAndSpecifiedParameterNamingStyle2_InitializeField() + => TestInRegularAndScript1Async( """ class C { @@ -1405,12 +1302,10 @@ public C([||]string p_t_s_End) } } """, index: 0, parameters: new TestParameters(options: options.MergeStyles(options.FieldNamesAreCamelCaseWithUnderscorePrefix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestNoParameterNamingStyle_InitializeProperty() - { - await TestInRegularAndScript1Async( + public Task TestNoParameterNamingStyle_InitializeProperty() + => TestInRegularAndScript1Async( """ class C { @@ -1432,12 +1327,10 @@ public C(string s) public string S { get; } } """, parameters: new TestParameters(options: options.PropertyNamesArePascalCase)); - } [Fact] - public async Task TestCommonParameterNamingStyle_InitializeProperty() - { - await TestInRegularAndScript1Async( + public Task TestCommonParameterNamingStyle_InitializeProperty() + => TestInRegularAndScript1Async( """ class C { @@ -1459,12 +1352,10 @@ public C(string t_s) public string S { get; } } """, parameters: new TestParameters(options: options.PropertyNamesArePascalCase)); - } [Fact] - public async Task TestSpecifiedParameterNamingStyle_InitializeProperty() - { - await TestInRegularAndScript1Async( + public Task TestSpecifiedParameterNamingStyle_InitializeProperty() + => TestInRegularAndScript1Async( """ class C { @@ -1486,12 +1377,10 @@ public C(string p_s_End) public string S { get; } } """, parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestCommonAndSpecifiedParameterNamingStyle_InitializeProperty() - { - await TestInRegularAndScript1Async( + public Task TestCommonAndSpecifiedParameterNamingStyle_InitializeProperty() + => TestInRegularAndScript1Async( """ class C { @@ -1513,12 +1402,10 @@ public C(string t_p_s_End) public string S { get; } } """, parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestCommonAndSpecifiedParameterNamingStyle2_InitializeProperty() - { - await TestInRegularAndScript1Async( + public Task TestCommonAndSpecifiedParameterNamingStyle2_InitializeProperty() + => TestInRegularAndScript1Async( """ class C { @@ -1540,12 +1427,10 @@ public C([||]string p_t_s_End) public string S { get; } } """, parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestBaseNameEmpty() - { - await TestMissingAsync( + public Task TestBaseNameEmpty() + => TestMissingAsync( """ class C { @@ -1556,15 +1441,10 @@ public C([||]string p__End) public string S { get; } } """, parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestSomeBaseNamesEmpty() - { - // Currently, this case does not offer a refactoring because selecting multiple parameters - // is not supported. If multiple parameters are supported in the future, this case should - // be updated to verify that only the parameter name that does not have an empty base is offered. - await TestMissingAsync( + public Task TestSomeBaseNamesEmpty() + => TestMissingAsync( """ class C { @@ -1573,16 +1453,14 @@ public C([|string p__End, string p_test_t|]) } } """, parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } private TestParameters OmitIfDefault_Warning => new TestParameters(options: Option(CodeStyleOptions2.AccessibilityModifiersRequired, AccessibilityModifiersRequired.OmitIfDefault, NotificationOption2.Warning)); private TestParameters Never_Warning => new TestParameters(options: Option(CodeStyleOptions2.AccessibilityModifiersRequired, AccessibilityModifiersRequired.Never, NotificationOption2.Warning)); private TestParameters Always_Warning => new TestParameters(options: Option(CodeStyleOptions2.AccessibilityModifiersRequired, AccessibilityModifiersRequired.Always, NotificationOption2.Warning)); [Fact] - public async Task TestCreateFieldWithTopLevelNullability() - { - await TestInRegularAndScript1Async( + public Task TestCreateFieldWithTopLevelNullability() + => TestInRegularAndScript1Async( """ #nullable enable class C @@ -1604,12 +1482,10 @@ public C(string? s) } } """, index: 1, parameters: new TestParameters(options: options.FieldNamesAreCamelCaseWithUnderscorePrefix)); - } [Fact] - public async Task TestCreatePropertyWithTopLevelNullability() - { - await TestInRegularAndScript1Async( + public Task TestCreatePropertyWithTopLevelNullability() + => TestInRegularAndScript1Async( """ #nullable enable class C @@ -1631,12 +1507,10 @@ public C(string? s) public string? S { get; } } """, parameters: new TestParameters(options: options.PropertyNamesArePascalCase)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24526")] - public async Task TestSingleLineBlock_BraceOnNextLine() - { - await TestInRegularAndScript1Async( + public Task TestSingleLineBlock_BraceOnNextLine() + => TestInRegularAndScript1Async( """ class C { @@ -1654,12 +1528,10 @@ public C(string s) public string S { get; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24526")] - public async Task TestSingleLineBlock_BraceOnSameLine() - { - await TestInRegularAndScriptAsync( + public Task TestSingleLineBlock_BraceOnSameLine() + => TestInRegularAndScriptAsync( """ class C { @@ -1676,12 +1548,10 @@ public C(string s) { public string S { get; } } """, options: this.Option(CSharpFormattingOptions2.NewLineBeforeOpenBrace, NewLineBeforeOpenBracePlacement.All & ~NewLineBeforeOpenBracePlacement.Methods)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23308")] - public async Task TestGenerateFieldIfParameterFollowsExistingFieldAssignment() - { - await TestInRegularAndScript1Async( + public Task TestGenerateFieldIfParameterFollowsExistingFieldAssignment() + => TestInRegularAndScript1Async( """ class C { @@ -1706,12 +1576,10 @@ public C(string s, int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23308")] - public async Task TestGenerateFieldIfParameterPrecedesExistingFieldAssignment() - { - await TestInRegularAndScript1Async( + public Task TestGenerateFieldIfParameterPrecedesExistingFieldAssignment() + => TestInRegularAndScript1Async( """ class C { @@ -1736,12 +1604,10 @@ public C(int i, string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23308")] - public async Task TestGenerateFieldIfParameterFollowsExistingFieldAssignment_TupleAssignment1() - { - await TestInRegularAndScript1Async( + public Task TestGenerateFieldIfParameterFollowsExistingFieldAssignment_TupleAssignment1() + => TestInRegularAndScript1Async( """ class C { @@ -1767,12 +1633,10 @@ public C(string s, string t, int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23308")] - public async Task TestGenerateFieldIfParameterFollowsExistingFieldAssignment_TupleAssignment2() - { - await TestInRegularAndScript1Async( + public Task TestGenerateFieldIfParameterFollowsExistingFieldAssignment_TupleAssignment2() + => TestInRegularAndScript1Async( """ class C { @@ -1794,12 +1658,10 @@ public C(string s, string t, int i) => (this.s, this.t, this.i) = (s, t, i); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23308")] - public async Task TestGenerateFieldIfParameterFollowsExistingFieldAssignment_TupleAssignment3() - { - await TestInRegularAndScript1Async( + public Task TestGenerateFieldIfParameterFollowsExistingFieldAssignment_TupleAssignment3() + => TestInRegularAndScript1Async( """ class C { @@ -1827,12 +1689,10 @@ public C(string s, string t, int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23308")] - public async Task TestGenerateFieldIfParameterPrecedesExistingFieldAssignment_TupleAssignment1() - { - await TestInRegularAndScript1Async( + public Task TestGenerateFieldIfParameterPrecedesExistingFieldAssignment_TupleAssignment1() + => TestInRegularAndScript1Async( """ class C { @@ -1858,12 +1718,10 @@ public C(int i, string s, string t) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23308")] - public async Task TestGenerateFieldIfParameterPrecedesExistingFieldAssignment_TupleAssignment2() - { - await TestInRegularAndScript1Async( + public Task TestGenerateFieldIfParameterPrecedesExistingFieldAssignment_TupleAssignment2() + => TestInRegularAndScript1Async( """ class C { @@ -1885,12 +1743,10 @@ public C(int i, string s, string t) => (this.i, this.s, this.t) = (i, s, t); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23308")] - public async Task TestGenerateFieldIfParameterInMiddleOfExistingFieldAssignment_TupleAssignment1() - { - await TestInRegularAndScript1Async( + public Task TestGenerateFieldIfParameterInMiddleOfExistingFieldAssignment_TupleAssignment1() + => TestInRegularAndScript1Async( """ class C { @@ -1916,12 +1772,10 @@ public C(string s, int i, string t) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23308")] - public async Task TestGenerateFieldIfParameterInMiddleOfExistingFieldAssignment_TupleAssignment2() - { - await TestInRegularAndScript1Async( + public Task TestGenerateFieldIfParameterInMiddleOfExistingFieldAssignment_TupleAssignment2() + => TestInRegularAndScript1Async( """ class C { @@ -1943,12 +1797,10 @@ public C(string s, int i, string t) => (this.s, this.i, this.t) = (s, i, t); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23308")] - public async Task TestGeneratePropertyIfParameterFollowsExistingPropertyAssignment_TupleAssignment1() - { - await TestInRegularAndScript1Async( + public Task TestGeneratePropertyIfParameterFollowsExistingPropertyAssignment_TupleAssignment1() + => TestInRegularAndScript1Async( """ class C { @@ -1974,12 +1826,10 @@ public C(string s, string t, int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41824")] - public async Task TestMissingInArgList() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingInArgList() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1993,12 +1843,10 @@ public static void M2([||]__arglist) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35665")] - public async Task TestGenerateRemainingFields1() - { - await TestInRegularAndScript1Async( + public Task TestGenerateRemainingFields1() + => TestInRegularAndScript1Async( """ class C { @@ -2022,12 +1870,10 @@ public C(int i, int j, int k) } } """, index: 3); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35665")] - public async Task TestGenerateRemainingFields2() - { - await TestInRegularAndScript1Async( + public Task TestGenerateRemainingFields2() + => TestInRegularAndScript1Async( """ class C { @@ -2054,12 +1900,10 @@ public C(int i, int j, int k) } } """, index: 2); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35665")] - public async Task TestGenerateRemainingFields3() - { - await TestInRegularAndScript1Async( + public Task TestGenerateRemainingFields3() + => TestInRegularAndScript1Async( """ class C { @@ -2086,12 +1930,10 @@ public C(int i, int j, int k) } } """, index: 2); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35665")] - public async Task TestGenerateRemainingFields4() - { - await TestInRegularAndScript1Async( + public Task TestGenerateRemainingFields4() + => TestInRegularAndScript1Async( """ class C { @@ -2118,12 +1960,10 @@ public C(int i, int j, int k) } } """, index: 2); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35665")] - public async Task TestGenerateRemainingProperties1() - { - await TestInRegularAndScript1Async( + public Task TestGenerateRemainingProperties1() + => TestInRegularAndScript1Async( """ class C { @@ -2147,12 +1987,10 @@ public C(int i, int j, int k) public int K { get; } } """, index: 2); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35665")] - public async Task TestGenerateRemainingProperties2() - { - await TestInRegularAndScript1Async( + public Task TestGenerateRemainingProperties2() + => TestInRegularAndScript1Async( """ class C { @@ -2180,12 +2018,10 @@ public C(int i, int j, int k) public int K { get; } } """, index: 3); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35665")] - public async Task TestGenerateRemainingProperties3() - { - await TestInRegularAndScript1Async( + public Task TestGenerateRemainingProperties3() + => TestInRegularAndScript1Async( """ class C { @@ -2213,12 +2049,10 @@ public C(int i, int j, int k) public int K { get; } } """, index: 3); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35665")] - public async Task TestGenerateRemainingProperties4() - { - await TestInRegularAndScript1Async( + public Task TestGenerateRemainingProperties4() + => TestInRegularAndScript1Async( """ class C { @@ -2246,12 +2080,10 @@ public C(int i, int j, int k) public int J { get; } } """, index: 3); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53467")] - public async Task TestMissingWhenTypeNotInCompilation() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWhenTypeNotInCompilation() + => TestMissingInRegularAndScriptAsync( """ @@ -2274,12 +2106,10 @@ public Bar(int prop1, int [||]prop2) : base(prop1) { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36998")] - public async Task TestInitializeThrowingProperty1() - { - await TestInRegularAndScript1Async( + public Task TestInitializeThrowingProperty1() + => TestInRegularAndScript1Async( """ using System; @@ -2305,12 +2135,10 @@ public C(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36998")] - public async Task TestInitializeThrowingProperty2() - { - await TestInRegularAndScript1Async( + public Task TestInitializeThrowingProperty2() + => TestInRegularAndScript1Async( """ using System; @@ -2342,12 +2170,10 @@ public C(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36998")] - public async Task TestInitializeThrowingProperty3() - { - await TestInRegularAndScript1Async( + public Task TestInitializeThrowingProperty3() + => TestInRegularAndScript1Async( """ using System; @@ -2379,12 +2205,10 @@ public C(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36998")] - public async Task TestInitializeThrowingProperty4() - { - await TestInRegularAndScript1Async( + public Task TestInitializeThrowingProperty4() + => TestInRegularAndScript1Async( """ using System; @@ -2418,12 +2242,10 @@ public C(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36998")] - public async Task TestInitializeThrowingProperty5() - { - await TestInRegularAndScript1Async( + public Task TestInitializeThrowingProperty5() + => TestInRegularAndScript1Async( """ using System; @@ -2457,12 +2279,10 @@ public C(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36998")] - public async Task TestInitializeThrowingProperty6() - { - await TestInRegularAndScript1Async( + public Task TestInitializeThrowingProperty6() + => TestInRegularAndScript1Async( """ using System; @@ -2490,12 +2310,10 @@ public C(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36998")] - public async Task TestInitializeThrowingProperty_DifferentFile1() - { - await TestInRegularAndScriptAsync( + public Task TestInitializeThrowingProperty_DifferentFile1() + => TestInRegularAndScriptAsync( """ @@ -2539,5 +2357,4 @@ public partial class Goo """); - } } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/InitializeParameter/InitializeMemberFromPrimaryConstructorParameterTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/InitializeParameter/InitializeMemberFromPrimaryConstructorParameterTests.cs index ff75ae534bfe4..8f3cab891e6c9 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/InitializeParameter/InitializeMemberFromPrimaryConstructorParameterTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/InitializeParameter/InitializeMemberFromPrimaryConstructorParameterTests.cs @@ -28,9 +28,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(EditorT private TestParameters Always_Warning => new TestParameters(options: Option(CodeStyleOptions2.AccessibilityModifiersRequired, AccessibilityModifiersRequired.Always, NotificationOption2.Warning)); [Fact] - public async Task TestInitializeFieldWithSameName() - { - await TestInRegularAndScript1Async( + public Task TestInitializeFieldWithSameName() + => TestInRegularAndScript1Async( """ class C([||]string s) { @@ -43,12 +42,10 @@ class C(string s) private string s = s; } """); - } [Fact] - public async Task TestEndOfParameter1() - { - await TestInRegularAndScript1Async( + public Task TestEndOfParameter1() + => TestInRegularAndScript1Async( """ class C(string s[||]) { @@ -61,12 +58,10 @@ class C(string s) private string s = s; } """); - } [Fact] - public async Task TestEndOfParameter2() - { - await TestInRegularAndScript1Async( + public Task TestEndOfParameter2() + => TestInRegularAndScript1Async( """ class C(string s[||], string t) { @@ -79,12 +74,10 @@ class C(string s, string t) private string s = s; } """); - } [Fact] - public async Task TestInitializeFieldWithUnderscoreName() - { - await TestInRegularAndScript1Async( + public Task TestInitializeFieldWithUnderscoreName() + => TestInRegularAndScript1Async( """ class C([||]string s) { @@ -97,12 +90,10 @@ class C(string s) private string _s = s; } """); - } [Fact] - public async Task TestInitializeWritableProperty() - { - await TestInRegularAndScript1Async( + public Task TestInitializeWritableProperty() + => TestInRegularAndScript1Async( """ class C([||]string s) { @@ -115,12 +106,10 @@ class C(string s) private string S { get; } = s; } """); - } [Fact] - public async Task TestInitializeFieldWithDifferentName() - { - await TestInRegularAndScriptAsync( + public Task TestInitializeFieldWithDifferentName() + => TestInRegularAndScriptAsync( """ class C([||]string s) { @@ -135,12 +124,10 @@ class C(string s) public string S { get; } = s; } """); - } [Fact] - public async Task TestInitializeNonWritableProperty() - { - await TestInRegularAndScript1Async( + public Task TestInitializeNonWritableProperty() + => TestInRegularAndScript1Async( """ class C([||]string s) { @@ -155,12 +142,10 @@ class C(string s) private string S => null; } """); - } [Fact] - public async Task TestInitializeDoesNotUsePropertyWithUnrelatedName() - { - await TestInRegularAndScriptAsync( + public Task TestInitializeDoesNotUsePropertyWithUnrelatedName() + => TestInRegularAndScriptAsync( """ class C([||]string s) { @@ -174,12 +159,10 @@ class C(string s) private string T { get; } } """); - } [Fact] - public async Task TestInitializeFieldWithWrongType1() - { - await TestInRegularAndScript1Async( + public Task TestInitializeFieldWithWrongType1() + => TestInRegularAndScript1Async( """ class C([||]string s) { @@ -194,12 +177,10 @@ class C(string s) public string S { get; } = s; } """); - } [Fact] - public async Task TestInitializeFieldWithWrongType2() - { - await TestInRegularAndScript1Async( + public Task TestInitializeFieldWithWrongType2() + => TestInRegularAndScript1Async( """ class C([||]string s) { @@ -213,12 +194,10 @@ class C(string s) private int s; } """, index: 1); - } [Fact] - public async Task TestInitializeFieldWithConvertibleType() - { - await TestInRegularAndScriptAsync( + public Task TestInitializeFieldWithConvertibleType() + => TestInRegularAndScriptAsync( """ class C([||]string s) { @@ -231,12 +210,10 @@ class C(string s) private object s = s; } """); - } [Fact] - public async Task TestWhenAlreadyInitialized1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWhenAlreadyInitialized1() + => TestMissingInRegularAndScriptAsync( """ class C([||]string s) { @@ -244,12 +221,10 @@ class C([||]string s) private int x = s; } """); - } [Fact] - public async Task TestWhenAlreadyInitialized2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWhenAlreadyInitialized2() + => TestMissingInRegularAndScriptAsync( """ class C([||]string s) { @@ -257,12 +232,10 @@ class C([||]string s) private int x = s ?? throw new Exception(); } """); - } [Fact] - public async Task TestWhenAlreadyInitialized3() - { - await TestInRegularAndScript1Async( + public Task TestWhenAlreadyInitialized3() + => TestInRegularAndScript1Async( """ class C([||]string s) { @@ -278,12 +251,10 @@ class C([||]string s) public string S { get; } = s; } """); - } [Fact] - public async Task TestInsertionLocation1() - { - await TestInRegularAndScript1Async( + public Task TestInsertionLocation1() + => TestInRegularAndScript1Async( """ class C([||]string s, string t) { @@ -298,12 +269,10 @@ class C(string s, string t) private string t = t; } """); - } [Fact] - public async Task TestInsertionLocation2() - { - await TestInRegularAndScript1Async( + public Task TestInsertionLocation2() + => TestInRegularAndScript1Async( """ class C(string s, [||]string t) { @@ -318,12 +287,10 @@ class C(string s, string t) private string t = t; } """); - } [Fact] - public async Task TestNotInMethod() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotInMethod() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -334,12 +301,10 @@ public void M([||]string s) } } """); - } [Fact] - public async Task TestInsertionLocation6() - { - await TestInRegularAndScript1Async( + public Task TestInsertionLocation6() + => TestInRegularAndScript1Async( """ class C(string s, [||]string t) { @@ -353,12 +318,10 @@ class C(string s, string t) public string T { get; } = t; } """); - } [Fact] - public async Task TestInsertionLocation7() - { - await TestInRegularAndScript1Async( + public Task TestInsertionLocation7() + => TestInRegularAndScript1Async( """ class C([||]string s, string t) { @@ -372,12 +335,10 @@ class C(string s, string t) public string T { get; } = t; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19956")] - public async Task TestNoBlock1() - { - await TestInRegularAndScript1Async( + public Task TestNoBlock1() + => TestInRegularAndScript1Async( """ class C(string s[||]) """, @@ -388,12 +349,10 @@ class C(string s) } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19956")] - public async Task TestNoBlock2() - { - await TestInRegularAndScript1Async( + public Task TestNoBlock2() + => TestInRegularAndScript1Async( """ class C(string s[||]) """, @@ -405,12 +364,10 @@ class C(string s) """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29190")] - public async Task TestInitializeFieldWithParameterNameSelected1() - { - await TestInRegularAndScript1Async( + public Task TestInitializeFieldWithParameterNameSelected1() + => TestInRegularAndScript1Async( """ class C(string [|s|]) { @@ -423,12 +380,10 @@ class C(string s) private string s = s; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29190")] - public async Task TestInitializeField_ParameterNameSelected2() - { - await TestInRegularAndScript1Async( + public Task TestInitializeField_ParameterNameSelected2() + => TestInRegularAndScript1Async( """ class C(string [|s|], int i) { @@ -441,12 +396,10 @@ class C(string s, int i) private string s = s; } """); - } [Fact] - public async Task TestInitializeClassProperty_RequiredAccessibilityOmitIfDefault() - { - await TestInRegularAndScript1Async( + public Task TestInitializeClassProperty_RequiredAccessibilityOmitIfDefault() + => TestInRegularAndScript1Async( """ class C(int test, int [|test2|]) { @@ -461,12 +414,10 @@ class C(int test, int test2) public int Test2 { get; } = test2; } """, index: 0, parameters: OmitIfDefault_Warning); - } [Fact] - public async Task TestInitializeClassProperty_RequiredAccessibilityNever() - { - await TestInRegularAndScript1Async( + public Task TestInitializeClassProperty_RequiredAccessibilityNever() + => TestInRegularAndScript1Async( """ class C(int test, int [|test2|]) { @@ -481,12 +432,10 @@ class C(int test, int test2) public int Test2 { get; } = test2; } """, index: 0, parameters: Never_Warning); - } [Fact] - public async Task TestInitializeClassProperty_RequiredAccessibilityAlways() - { - await TestInRegularAndScript1Async( + public Task TestInitializeClassProperty_RequiredAccessibilityAlways() + => TestInRegularAndScript1Async( """ class C(int test, int [|test2|]) { @@ -501,12 +450,10 @@ class C(int test, int test2) public int Test2 { get; } = test2; } """, index: 0, parameters: Always_Warning); - } [Fact] - public async Task TestInitializeClassField_RequiredAccessibilityOmitIfDefault() - { - await TestInRegularAndScript1Async( + public Task TestInitializeClassField_RequiredAccessibilityOmitIfDefault() + => TestInRegularAndScript1Async( """ class C(int test, int [|test2|]) { @@ -520,12 +467,10 @@ class C(int test, int test2) readonly int test2 = test2; } """, index: 1, parameters: OmitIfDefault_Warning); - } [Fact] - public async Task TestInitializeClassField_RequiredAccessibilityNever() - { - await TestInRegularAndScript1Async( + public Task TestInitializeClassField_RequiredAccessibilityNever() + => TestInRegularAndScript1Async( """ class C(int test, int [|test2|]) { @@ -539,12 +484,10 @@ class C(int test, int test2) readonly int test2 = test2; } """, index: 1, parameters: Never_Warning); - } [Fact] - public async Task TestInitializeClassField_RequiredAccessibilityAlways() - { - await TestInRegularAndScript1Async( + public Task TestInitializeClassField_RequiredAccessibilityAlways() + => TestInRegularAndScript1Async( """ class C(int test, int [|test2|]) { @@ -558,12 +501,10 @@ class C(int test, int test2) private readonly int test2 = test2; } """, index: 1, parameters: Always_Warning); - } [Fact] - public async Task TestInitializeStructProperty_RequiredAccessibilityOmitIfDefault() - { - await TestInRegularAndScript1Async( + public Task TestInitializeStructProperty_RequiredAccessibilityOmitIfDefault() + => TestInRegularAndScript1Async( """ struct S(int [|test|]) { @@ -575,12 +516,10 @@ struct S(int test) public int Test { get; } = test; } """, index: 0, parameters: OmitIfDefault_Warning); - } [Fact] - public async Task TestInitializeStructProperty_RequiredAccessibilityNever() - { - await TestInRegularAndScript1Async( + public Task TestInitializeStructProperty_RequiredAccessibilityNever() + => TestInRegularAndScript1Async( """ struct S(int [|test|]) { @@ -592,12 +531,10 @@ struct S(int test) public int Test { get; } = test; } """, index: 0, parameters: Never_Warning); - } [Fact] - public async Task TestInitializeStructProperty_RequiredAccessibilityAlways() - { - await TestInRegularAndScript1Async( + public Task TestInitializeStructProperty_RequiredAccessibilityAlways() + => TestInRegularAndScript1Async( """ struct S(int [|test|]) { @@ -609,12 +546,10 @@ struct S(int test) public int Test { get; } = test; } """, index: 0, parameters: Always_Warning); - } [Fact] - public async Task TestInitializeStructField_RequiredAccessibilityOmitIfDefault() - { - await TestInRegularAndScript1Async( + public Task TestInitializeStructField_RequiredAccessibilityOmitIfDefault() + => TestInRegularAndScript1Async( """ struct S(int [|test|]) { @@ -626,12 +561,10 @@ struct S(int test) readonly int test = test; } """, index: 1, parameters: OmitIfDefault_Warning); - } [Fact] - public async Task TestInitializeStructField_RequiredAccessibilityNever() - { - await TestInRegularAndScript1Async( + public Task TestInitializeStructField_RequiredAccessibilityNever() + => TestInRegularAndScript1Async( """ struct S(int [|test|]) { @@ -643,12 +576,10 @@ struct S(int test) readonly int test = test; } """, index: 1, parameters: Never_Warning); - } [Fact] - public async Task TestInitializeStructField_RequiredAccessibilityAlways() - { - await TestInRegularAndScript1Async( + public Task TestInitializeStructField_RequiredAccessibilityAlways() + => TestInRegularAndScript1Async( """ struct S(int [|test|]) { @@ -660,12 +591,10 @@ struct S(int test) private readonly int test = test; } """, index: 1, parameters: Always_Warning); - } [Fact] - public async Task TestNoParameterNamingStyle_CreateAndInitField() - { - await TestInRegularAndScript1Async( + public Task TestNoParameterNamingStyle_CreateAndInitField() + => TestInRegularAndScript1Async( """ class C([||]string s) { @@ -677,12 +606,10 @@ class C(string s) private readonly string _s = s; } """, index: 1, parameters: new TestParameters(options: _options.FieldNamesAreCamelCaseWithUnderscorePrefix)); - } [Fact] - public async Task TestCommonParameterNamingStyle_CreateAndInitField() - { - await TestInRegularAndScript1Async( + public Task TestCommonParameterNamingStyle_CreateAndInitField() + => TestInRegularAndScript1Async( """ class C([||]string t_s) { @@ -694,12 +621,10 @@ class C(string t_s) private readonly string _s = t_s; } """, index: 1, parameters: new TestParameters(options: _options.FieldNamesAreCamelCaseWithUnderscorePrefix)); - } [Fact] - public async Task TestSpecifiedParameterNamingStyle_CreateAndInitField() - { - await TestInRegularAndScript1Async( + public Task TestSpecifiedParameterNamingStyle_CreateAndInitField() + => TestInRegularAndScript1Async( """ class C([||]string p_s_End) { @@ -711,12 +636,10 @@ class C(string p_s_End) private readonly string _s = p_s_End; } """, index: 1, parameters: new TestParameters(options: _options.MergeStyles(_options.FieldNamesAreCamelCaseWithUnderscorePrefix, _options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestCommonAndSpecifiedParameterNamingStyle_CreateAndInitField() - { - await TestInRegularAndScript1Async( + public Task TestCommonAndSpecifiedParameterNamingStyle_CreateAndInitField() + => TestInRegularAndScript1Async( """ class C([||]string t_p_s_End) { @@ -728,12 +651,10 @@ class C(string t_p_s_End) private readonly string _s = t_p_s_End; } """, index: 1, parameters: new TestParameters(options: _options.MergeStyles(_options.FieldNamesAreCamelCaseWithUnderscorePrefix, _options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestCommonAndSpecifiedParameterNamingStyle2_CreateAndInitField() - { - await TestInRegularAndScript1Async( + public Task TestCommonAndSpecifiedParameterNamingStyle2_CreateAndInitField() + => TestInRegularAndScript1Async( """ class C([||]string p_t_s) { @@ -745,12 +666,10 @@ class C([||]string p_t_s) private readonly string _s = p_t_s; } """, index: 1, parameters: new TestParameters(options: _options.MergeStyles(_options.FieldNamesAreCamelCaseWithUnderscorePrefix, _options.ParameterNamesAreCamelCaseWithPUnderscorePrefix))); - } [Fact] - public async Task TestNoParameterNamingStyle_CreateAndInitProperty() - { - await TestInRegularAndScript1Async( + public Task TestNoParameterNamingStyle_CreateAndInitProperty() + => TestInRegularAndScript1Async( """ class C([||]string s) { @@ -762,12 +681,10 @@ class C(string s) public string S { get; } = s; } """, parameters: new TestParameters(options: _options.PropertyNamesArePascalCase)); - } [Fact] - public async Task TestCommonParameterNamingStyle_CreateAndInitProperty() - { - await TestInRegularAndScript1Async( + public Task TestCommonParameterNamingStyle_CreateAndInitProperty() + => TestInRegularAndScript1Async( """ class C([||]string t_s) { @@ -779,12 +696,10 @@ class C(string t_s) public string S { get; } = t_s; } """, parameters: new TestParameters(options: _options.PropertyNamesArePascalCase)); - } [Fact] - public async Task TestSpecifiedParameterNamingStyle_CreateAndInitProperty() - { - await TestInRegularAndScript1Async( + public Task TestSpecifiedParameterNamingStyle_CreateAndInitProperty() + => TestInRegularAndScript1Async( """ class C([||]string p_s_End) { @@ -796,12 +711,10 @@ class C(string p_s_End) public string S { get; } = p_s_End; } """, parameters: new TestParameters(options: _options.MergeStyles(_options.PropertyNamesArePascalCase, _options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestCommonAndSpecifiedParameterNamingStyle_CreateAndInitProperty() - { - await TestInRegularAndScript1Async( + public Task TestCommonAndSpecifiedParameterNamingStyle_CreateAndInitProperty() + => TestInRegularAndScript1Async( """ class C([||]string t_p_s_End) { @@ -813,12 +726,10 @@ class C(string t_p_s_End) public string S { get; } = t_p_s_End; } """, parameters: new TestParameters(options: _options.MergeStyles(_options.PropertyNamesArePascalCase, _options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestCommonAndSpecifiedParameterNamingStyle2_CreateAndInitProperty() - { - await TestInRegularAndScript1Async( + public Task TestCommonAndSpecifiedParameterNamingStyle2_CreateAndInitProperty() + => TestInRegularAndScript1Async( """ class C([||]string p_t_s_End) { @@ -830,12 +741,10 @@ class C(string p_t_s_End) public string S { get; } = p_t_s_End; } """, parameters: new TestParameters(options: _options.MergeStyles(_options.PropertyNamesArePascalCase, _options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestNoParameterNamingStyle_InitializeField() - { - await TestInRegularAndScript1Async( + public Task TestNoParameterNamingStyle_InitializeField() + => TestInRegularAndScript1Async( """ class C([||]string s) { @@ -848,12 +757,10 @@ class C(string s) private readonly string _s = s; } """, index: 0, parameters: new TestParameters(options: _options.FieldNamesAreCamelCaseWithUnderscorePrefix)); - } [Fact] - public async Task TestCommonParameterNamingStyle_InitializeField() - { - await TestInRegularAndScript1Async( + public Task TestCommonParameterNamingStyle_InitializeField() + => TestInRegularAndScript1Async( """ class C([||]string t_s) { @@ -866,12 +773,10 @@ class C(string t_s) private readonly string _s = t_s; } """, index: 0, parameters: new TestParameters(options: _options.FieldNamesAreCamelCaseWithUnderscorePrefix)); - } [Fact] - public async Task TestSpecifiedParameterNamingStyle_InitializeField() - { - await TestInRegularAndScript1Async( + public Task TestSpecifiedParameterNamingStyle_InitializeField() + => TestInRegularAndScript1Async( """ class C([||]string p_s_End) { @@ -884,12 +789,10 @@ class C(string p_s_End) private readonly string _s = p_s_End; } """, index: 0, parameters: new TestParameters(options: _options.MergeStyles(_options.FieldNamesAreCamelCaseWithUnderscorePrefix, _options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestCommonAndSpecifiedParameterNamingStyle_InitializeField() - { - await TestInRegularAndScript1Async( + public Task TestCommonAndSpecifiedParameterNamingStyle_InitializeField() + => TestInRegularAndScript1Async( """ class C([||]string t_p_s_End) { @@ -902,12 +805,10 @@ class C(string t_p_s_End) private readonly string _s = t_p_s_End; } """, index: 0, parameters: new TestParameters(options: _options.MergeStyles(_options.FieldNamesAreCamelCaseWithUnderscorePrefix, _options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestCommonAndSpecifiedParameterNamingStyle2_InitializeField() - { - await TestInRegularAndScript1Async( + public Task TestCommonAndSpecifiedParameterNamingStyle2_InitializeField() + => TestInRegularAndScript1Async( """ class C([||]string p_t_s_End) { @@ -920,12 +821,10 @@ class C([||]string p_t_s_End) private readonly string _s = p_t_s_End; } """, index: 0, parameters: new TestParameters(options: _options.MergeStyles(_options.FieldNamesAreCamelCaseWithUnderscorePrefix, _options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestNoParameterNamingStyle_InitializeProperty() - { - await TestInRegularAndScript1Async( + public Task TestNoParameterNamingStyle_InitializeProperty() + => TestInRegularAndScript1Async( """ class C([||]string s) { @@ -938,12 +837,10 @@ class C(string s) public string S { get; } = s; } """, parameters: new TestParameters(options: _options.PropertyNamesArePascalCase)); - } [Fact] - public async Task TestCommonParameterNamingStyle_InitializeProperty() - { - await TestInRegularAndScript1Async( + public Task TestCommonParameterNamingStyle_InitializeProperty() + => TestInRegularAndScript1Async( """ class C([||]string t_s) { @@ -956,12 +853,10 @@ class C(string t_s) public string S { get; } = t_s; } """, parameters: new TestParameters(options: _options.PropertyNamesArePascalCase)); - } [Fact] - public async Task TestSpecifiedParameterNamingStyle_InitializeProperty() - { - await TestInRegularAndScript1Async( + public Task TestSpecifiedParameterNamingStyle_InitializeProperty() + => TestInRegularAndScript1Async( """ class C([||]string p_s_End) { @@ -974,12 +869,10 @@ class C(string p_s_End) public string S { get; } = p_s_End; } """, parameters: new TestParameters(options: _options.MergeStyles(_options.PropertyNamesArePascalCase, _options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestCommonAndSpecifiedParameterNamingStyle_InitializeProperty() - { - await TestInRegularAndScript1Async( + public Task TestCommonAndSpecifiedParameterNamingStyle_InitializeProperty() + => TestInRegularAndScript1Async( """ class C([||]string t_p_s_End) { @@ -992,12 +885,10 @@ class C(string t_p_s_End) public string S { get; } = t_p_s_End; } """, parameters: new TestParameters(options: _options.MergeStyles(_options.PropertyNamesArePascalCase, _options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestCommonAndSpecifiedParameterNamingStyle2_InitializeProperty() - { - await TestInRegularAndScript1Async( + public Task TestCommonAndSpecifiedParameterNamingStyle2_InitializeProperty() + => TestInRegularAndScript1Async( """ class C([||]string p_t_s_End) { @@ -1010,38 +901,29 @@ class C([||]string p_t_s_End) public string S { get; } = p_t_s_End; } """, parameters: new TestParameters(options: _options.MergeStyles(_options.PropertyNamesArePascalCase, _options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestBaseNameEmpty() - { - await TestMissingAsync( + public Task TestBaseNameEmpty() + => TestMissingAsync( """ class C([||]string p__End) { public string S { get; } } """, parameters: new TestParameters(options: _options.MergeStyles(_options.PropertyNamesArePascalCase, _options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestSomeBaseNamesEmpty() - { - // Currently, this case does not offer a refactoring because selecting multiple parameters - // is not supported. If multiple parameters are supported in the future, this case should - // be updated to verify that only the parameter name that does not have an empty base is offered. - await TestMissingAsync( + public Task TestSomeBaseNamesEmpty() + => TestMissingAsync( """ class C([|string p__End, string p_test_t|]) { } """, parameters: new TestParameters(options: _options.MergeStyles(_options.PropertyNamesArePascalCase, _options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); - } [Fact] - public async Task TestCreateFieldWithTopLevelNullability() - { - await TestInRegularAndScript1Async( + public Task TestCreateFieldWithTopLevelNullability() + => TestInRegularAndScript1Async( """ #nullable enable class C([||]string? s) @@ -1055,12 +937,10 @@ class C(string? s) private readonly string? _s = s; } """, index: 1, parameters: new TestParameters(options: _options.FieldNamesAreCamelCaseWithUnderscorePrefix)); - } [Fact] - public async Task TestCreatePropertyWithTopLevelNullability() - { - await TestInRegularAndScript1Async( + public Task TestCreatePropertyWithTopLevelNullability() + => TestInRegularAndScript1Async( """ #nullable enable class C([||]string? s) @@ -1074,12 +954,10 @@ class C(string? s) public string? S { get; } = s; } """, parameters: new TestParameters(options: _options.PropertyNamesArePascalCase)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24526")] - public async Task TestSingleLineBlock_BraceOnNextLine() - { - await TestInRegularAndScript1Async( + public Task TestSingleLineBlock_BraceOnNextLine() + => TestInRegularAndScript1Async( """ class C([||]string s) { } """, @@ -1089,12 +967,10 @@ class C(string s) public string S { get; } = s; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24526")] - public async Task TestSingleLineBlock_BraceOnSameLine() - { - await TestInRegularAndScriptAsync( + public Task TestSingleLineBlock_BraceOnSameLine() + => TestInRegularAndScriptAsync( """ class C([||]string s) { } """, @@ -1103,12 +979,10 @@ class C(string s) { public string S { get; } = s; } """, options: this.Option(CSharpFormattingOptions2.NewLineBeforeOpenBrace, NewLineBeforeOpenBracePlacement.All & ~NewLineBeforeOpenBracePlacement.Types)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23308")] - public async Task TestGenerateFieldIfParameterFollowsExistingFieldAssignment() - { - await TestInRegularAndScript1Async( + public Task TestGenerateFieldIfParameterFollowsExistingFieldAssignment() + => TestInRegularAndScript1Async( """ class C(string s, [||]int i) { @@ -1122,12 +996,10 @@ class C(string s, int i) private readonly int i = i; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23308")] - public async Task TestGenerateFieldIfParameterPrecedesExistingFieldAssignment() - { - await TestInRegularAndScript1Async( + public Task TestGenerateFieldIfParameterPrecedesExistingFieldAssignment() + => TestInRegularAndScript1Async( """ class C([||]int i, string s) { @@ -1141,12 +1013,10 @@ class C(int i, string s) private readonly string s = s; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35665")] - public async Task TestGenerateRemainingFields1() - { - await TestInRegularAndScript1Async( + public Task TestGenerateRemainingFields1() + => TestInRegularAndScript1Async( """ class C([||]int i, int j, int k) { @@ -1160,12 +1030,10 @@ class C(int i, int j, int k) private readonly int k = k; } """, index: 3); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35665")] - public async Task TestGenerateRemainingFields2() - { - await TestInRegularAndScript1Async( + public Task TestGenerateRemainingFields2() + => TestInRegularAndScript1Async( """ class C(int i, [||]int j, int k) { @@ -1180,12 +1048,10 @@ class C(int i, int j, int k) private readonly int k = k; } """, index: 2); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35665")] - public async Task TestGenerateRemainingFields3() - { - await TestInRegularAndScript1Async( + public Task TestGenerateRemainingFields3() + => TestInRegularAndScript1Async( """ class C([||]int i, int j, int k) { @@ -1200,12 +1066,10 @@ class C(int i, int j, int k) private readonly int k = k; } """, index: 2); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35665")] - public async Task TestGenerateRemainingFields4() - { - await TestInRegularAndScript1Async( + public Task TestGenerateRemainingFields4() + => TestInRegularAndScript1Async( """ class C([||]int i, int j, int k) { @@ -1220,12 +1084,10 @@ class C(int i, int j, int k) private readonly int k = k; } """, index: 2); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35665")] - public async Task TestGenerateRemainingProperties1() - { - await TestInRegularAndScript1Async( + public Task TestGenerateRemainingProperties1() + => TestInRegularAndScript1Async( """ class C([||]int i, int j, int k) { @@ -1239,12 +1101,10 @@ class C(int i, int j, int k) public int K { get; } = k; } """, index: 2); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35665")] - public async Task TestGenerateRemainingProperties2() - { - await TestInRegularAndScript1Async( + public Task TestGenerateRemainingProperties2() + => TestInRegularAndScript1Async( """ class C(int i, [||]int j, int k) { @@ -1260,12 +1120,10 @@ class C(int i, int j, int k) public int K { get; } = k; } """, index: 3); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35665")] - public async Task TestGenerateRemainingProperties3() - { - await TestInRegularAndScript1Async( + public Task TestGenerateRemainingProperties3() + => TestInRegularAndScript1Async( """ class C([||]int i, int j, int k) { @@ -1281,12 +1139,10 @@ class C(int i, int j, int k) public int K { get; } = k; } """, index: 3); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35665")] - public async Task TestGenerateRemainingProperties4() - { - await TestInRegularAndScript1Async( + public Task TestGenerateRemainingProperties4() + => TestInRegularAndScript1Async( """ class C([||]int i, int j, int k) { @@ -1302,12 +1158,10 @@ class C(int i, int j, int k) public int J { get; } = j; } """, index: 3); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36998")] - public async Task TestInitializeThrowingProperty1() - { - await TestInRegularAndScript1Async( + public Task TestInitializeThrowingProperty1() + => TestInRegularAndScript1Async( """ using System; @@ -1324,12 +1178,10 @@ class C(string s) private string S { get; } = s; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36998")] - public async Task TestInitializeThrowingProperty2() - { - await TestInRegularAndScript1Async( + public Task TestInitializeThrowingProperty2() + => TestInRegularAndScript1Async( """ using System; @@ -1352,12 +1204,10 @@ private string S } = s; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36998")] - public async Task TestInitializeThrowingProperty3() - { - await TestInRegularAndScript1Async( + public Task TestInitializeThrowingProperty3() + => TestInRegularAndScript1Async( """ using System; @@ -1380,12 +1230,10 @@ private string S } = s; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36998")] - public async Task TestInitializeThrowingProperty4() - { - await TestInRegularAndScript1Async( + public Task TestInitializeThrowingProperty4() + => TestInRegularAndScript1Async( """ using System; @@ -1410,12 +1258,10 @@ private string S } = s; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36998")] - public async Task TestInitializeThrowingProperty5() - { - await TestInRegularAndScript1Async( + public Task TestInitializeThrowingProperty5() + => TestInRegularAndScript1Async( """ using System; @@ -1440,12 +1286,10 @@ private string S } = s; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36998")] - public async Task TestInitializeThrowingProperty6() - { - await TestInRegularAndScript1Async( + public Task TestInitializeThrowingProperty6() + => TestInRegularAndScript1Async( """ using System; @@ -1464,12 +1308,10 @@ class C(string s) private string S => throw new InvalidOperationException(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36998")] - public async Task TestInitializeThrowingProperty_DifferentFile1() - { - await TestInRegularAndScriptAsync( + public Task TestInitializeThrowingProperty_DifferentFile1() + => TestInRegularAndScriptAsync( """ @@ -1506,12 +1348,54 @@ public partial class Goo """); - } + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76565")] + public Task TestCouldInitializeThrowingProperty_ButGeneratePropertyInstead() + => TestInRegularAndScript1Async( + """ + using System; + + class C([||]string s) + { + private string S => throw new NotImplementedException(); + } + """, + """ + using System; + + class C(string s) + { + public string S1 { get; } = s; + + private string S => throw new NotImplementedException(); + } + """, index: 1); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76565")] + public Task TestCouldInitializeThrowingProperty_ButGenerateFieldInstead() + => TestInRegularAndScript1Async( + """ + using System; + + class C([||]string s) + { + private string S => throw new NotImplementedException(); + } + """, + """ + using System; + + class C(string s) + { + private readonly string s = s; + + private string S => throw new NotImplementedException(); + } + """, index: 2); [Fact] - public async Task TestUpdateCodeToReferenceExistingField1() - { - await TestInRegularAndScript1Async( + public Task TestUpdateCodeToReferenceExistingField1() + => TestInRegularAndScript1Async( """ using System; @@ -1540,12 +1424,10 @@ private void M() } } """); - } [Fact] - public async Task TestUpdateCodeToReferenceExistingField2() - { - await TestInRegularAndScript1Async( + public Task TestUpdateCodeToReferenceExistingField2() + => TestInRegularAndScript1Async( """ using System; @@ -1574,12 +1456,10 @@ private void M() } } """); - } [Fact] - public async Task TestUpdateCodeToReferenceExistingProperty() - { - await TestInRegularAndScript1Async( + public Task TestUpdateCodeToReferenceExistingProperty() + => TestInRegularAndScript1Async( """ using System; @@ -1608,12 +1488,10 @@ private void M() } } """); - } [Fact] - public async Task TestUpdateCodeToReferenceExistingProperty2() - { - await TestInRegularAndScript1Async( + public Task TestUpdateCodeToReferenceExistingProperty2() + => TestInRegularAndScript1Async( """ using System; @@ -1642,12 +1520,10 @@ private void M() } } """); - } [Fact] - public async Task TestUpdateCodeToReferenceNewProperty1() - { - await TestInRegularAndScript1Async( + public Task TestUpdateCodeToReferenceNewProperty1() + => TestInRegularAndScript1Async( """ using System; @@ -1674,12 +1550,10 @@ private void M() } } """); - } [Fact] - public async Task TestUpdateCodeToReferenceNewField1() - { - await TestInRegularAndScript1Async( + public Task TestUpdateCodeToReferenceNewField1() + => TestInRegularAndScript1Async( """ using System; @@ -1706,12 +1580,10 @@ private void M() } } """, index: 1, parameters: new TestParameters(options: _options.FieldNamesAreCamelCaseWithUnderscorePrefix)); - } [Fact] - public async Task TestInitializeIntoFieldInDifferentPart() - { - await TestInRegularAndScript1Async( + public Task TestInitializeIntoFieldInDifferentPart() + => TestInRegularAndScript1Async( """ partial class C([||]string s) { @@ -1732,12 +1604,10 @@ partial class C private string s = s; } """); - } [Fact] - public async Task TestInitializeIntoPropertyInDifferentPart() - { - await TestInRegularAndScript1Async( + public Task TestInitializeIntoPropertyInDifferentPart() + => TestInRegularAndScript1Async( """ partial class C([||]string s) { @@ -1758,12 +1628,10 @@ partial class C private string S { get; } = s; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36998")] - public async Task TestInitializeProperty_DifferentFile1() - { - await TestInRegularAndScriptAsync( + public Task TestInitializeProperty_DifferentFile1() + => TestInRegularAndScriptAsync( """ @@ -1800,12 +1668,10 @@ public partial class Goo """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36998")] - public async Task TestInitializeProperty_DifferentFile2() - { - await TestInRegularAndScriptAsync( + public Task TestInitializeProperty_DifferentFile2() + => TestInRegularAndScriptAsync( """ @@ -1843,12 +1709,10 @@ public partial class Goo """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36998")] - public async Task TestInitializeProperty_DifferentFile3() - { - await TestInRegularAndScriptAsync( + public Task TestInitializeProperty_DifferentFile3() + => TestInRegularAndScriptAsync( """ @@ -1886,12 +1750,10 @@ public partial class Goo """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36998")] - public async Task TestInitializeProperty_DifferentFile4() - { - await TestInRegularAndScriptAsync( + public Task TestInitializeProperty_DifferentFile4() + => TestInRegularAndScriptAsync( """ @@ -1930,12 +1792,10 @@ public partial class Goo """, index: 2); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36998")] - public async Task TestInitializeField_DifferentFile1() - { - await TestInRegularAndScriptAsync( + public Task TestInitializeField_DifferentFile1() + => TestInRegularAndScriptAsync( """ @@ -1972,12 +1832,10 @@ public partial class Goo """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69459")] - public async Task TestInLinkedFile() - { - await TestInRegularAndScriptAsync( + public Task TestInLinkedFile() + => TestInRegularAndScriptAsync( """ @@ -2024,5 +1882,4 @@ private void M() """); - } } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/InlineMethod/CSharpInlineMethodTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/InlineMethod/CSharpInlineMethodTests.cs index f0accee4ec12c..714fdd50eccb7 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/InlineMethod/CSharpInlineMethodTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/InlineMethod/CSharpInlineMethodTests.cs @@ -5,6 +5,7 @@ #nullable disable using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.InlineMethod; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; @@ -23,10 +24,10 @@ private sealed class TestVerifier : CSharpCodeRefactoringVerifier diagnosticResults = null, bool keepInlinedMethod = true) { @@ -58,8 +59,8 @@ public static async Task TestInRegularScriptsInDifferentFilesAsync( } public static async Task TestInRegularAndScriptInTheSameFileAsync( - string initialMarkUp, - string expectedMarkUp, + [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string initialMarkUp, + [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string expectedMarkUp, List diagnosticResults = null, bool keepInlinedMethod = true) { @@ -83,10 +84,10 @@ public static async Task TestInRegularAndScriptInTheSameFileAsync( } public static async Task TestBothKeepAndRemoveInlinedMethodInDifferentFileAsync( - string initialMarkUpForCaller, - string initialMarkUpForCallee, - string expectedMarkUpForCaller, - string expectedMarkUpForCallee, + [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string initialMarkUpForCaller, + [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string initialMarkUpForCallee, + [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string expectedMarkUpForCaller, + [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string expectedMarkUpForCallee, List diagnosticResultsWhenKeepInlinedMethod = null, List diagnosticResultsWhenRemoveInlinedMethod = null) { @@ -119,8 +120,8 @@ await TestInRegularScriptsInDifferentFilesAsync( } public static async Task TestBothKeepAndRemoveInlinedMethodInSameFileAsync( - string initialMarkUp, - string expectedMarkUp, + [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string initialMarkUp, + [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string expectedMarkUp, List diagnosticResultsWhenKeepInlinedMethod = null, List diagnosticResultsWhenRemoveInlinedMethod = null) { @@ -608,7 +609,8 @@ private void Caller(int m) System.Console.WriteLine(10 + m + ("Hello" ?? "")); } } - """, """ + """, + """ public partial class TestClass {## private void Callee(int i, int j = 100, string k = null) @@ -961,34 +963,34 @@ private void Callee(params int[] x) [Fact] public Task TestInlineMethodWithNoElementInParamsArray() => TestVerifier.TestBothKeepAndRemoveInlinedMethodInSameFileAsync( - """ - public class TestClass + """ + public class TestClass + { + private void Caller() { - private void Caller() - { - Cal[||]lee(); - } + Cal[||]lee(); + } - private void Callee(params int[] x) - { - System.Console.WriteLine(x.Length); - } + private void Callee(params int[] x) + { + System.Console.WriteLine(x.Length); + } + } + """, + """ + public class TestClass + { + private void Caller() + { + System.Console.WriteLine((new int[] { }).Length); } - """, - """ - public class TestClass + ## + private void Callee(params int[] x) { - private void Caller() - { - System.Console.WriteLine((new int[] { }).Length); - } - ## - private void Callee(params int[] x) - { - System.Console.WriteLine(x.Length); - } - ##} - """); + System.Console.WriteLine(x.Length); + } + ##} + """); [Fact] public Task TestInlineMethodWithParamsArray() @@ -1344,7 +1346,8 @@ private int Callee(int i) return i + 1; } } - """, """ + """, + """ public class TestClass { public void Caller(int j) @@ -1414,7 +1417,8 @@ private int Callee(int i) return i + 1; } } - """, """ + """, + """ public class TestClass { public void Caller(int? i) @@ -1441,7 +1445,8 @@ public System.Func Caller() private System.Func Callee() => (i, j) => i + j; } - """, """ + """, + """ public class TestClass { public System.Func Caller() @@ -1917,43 +1922,44 @@ public Task TestAwaitExpresssion5() // Await can't be used in non-async method. DiagnosticResult.CompilerError("CS4032").WithSpan(6, 33, 6, 56).WithArguments("int") }; + return TestVerifier.TestBothKeepAndRemoveInlinedMethodInSameFileAsync( - """ - using System.Threading.Tasks; - public class TestClass - { - public int Caller() - { - var x = Cal[||]lee(); - return 1; - } - - private async Task Callee() - { - return await Task.FromResult(await SomeCalculation()); - } - - private async Task SomeCalculation() => await Task.FromResult(10); - } - """, - """ - using System.Threading.Tasks; - public class TestClass - { - public int Caller() - { - var x = Task.FromResult(await SomeCalculation()); - return 1; - } - ## - private async Task Callee() - { - return await Task.FromResult(await SomeCalculation()); - } - ## - private async Task SomeCalculation() => await Task.FromResult(10); - } - """, diagnosticResultsWhenKeepInlinedMethod: diagnostic, diagnosticResultsWhenRemoveInlinedMethod: diagnostic); + """ + using System.Threading.Tasks; + public class TestClass + { + public int Caller() + { + var x = Cal[||]lee(); + return 1; + } + + private async Task Callee() + { + return await Task.FromResult(await SomeCalculation()); + } + + private async Task SomeCalculation() => await Task.FromResult(10); + } + """, + """ + using System.Threading.Tasks; + public class TestClass + { + public int Caller() + { + var x = Task.FromResult(await SomeCalculation()); + return 1; + } + ## + private async Task Callee() + { + return await Task.FromResult(await SomeCalculation()); + } + ## + private async Task SomeCalculation() => await Task.FromResult(10); + } + """, diagnosticResultsWhenKeepInlinedMethod: diagnostic, diagnosticResultsWhenRemoveInlinedMethod: diagnostic); } [Fact] @@ -2428,24 +2434,24 @@ private void Calller() private int SomeInt() => 10; } """, - """ - public class TestClass + """ + public class TestClass + { + private void Calller() { - private void Calller() + try + { + } + catch (System.Exception e) when (SomeInt() == 1) { - try - { - } - catch (System.Exception e) when (SomeInt() == 1) - { - } } - ## - private bool Callee(System.Exception e, int i) => i == 1; - ## - private int SomeInt() => 10; } - """); + ## + private bool Callee(System.Exception e, int i) => i == 1; + ## + private int SomeInt() => 10; + } + """); [Fact] public Task TestInlineMethodWithinYieldReturnStatement() @@ -3069,7 +3075,8 @@ private Func Callee() return () => 1; } } - """, """ + """, + """ using System; public class TestClass { @@ -3102,7 +3109,8 @@ private Func Callee() return async () => await Task.CompletedTask; } } - """, """ + """, + """ using System; using System.Threading.Tasks; public class TestClass @@ -3136,7 +3144,8 @@ private Func> Callee() return async () => { return await Task.FromResult(100); }; } } - """, """ + """, + """ using System; using System.Threading.Tasks; public class TestClass @@ -3168,7 +3177,8 @@ private long Callee() return 1; } } - """, """ + """, + """ public class TestClass { public void Caller() @@ -3204,7 +3214,8 @@ private string Callee(LinkedList l) return l?.Next?.Next?.Next?.Next?.ToString(); } } - """, """ + """, + """ public class LinkedList { public LinkedList Next { get; } @@ -3246,7 +3257,8 @@ private string Callee(LinkedList l) return l?.ToString(); } } - """, """ + """, + """ public class LinkedList { public LinkedList Next { get; } @@ -3288,7 +3300,8 @@ private string Callee(LinkedList l) return l?.Next.ToString(); } } - """, """ + """, + """ public class LinkedList { public LinkedList Next { get; } @@ -3325,7 +3338,8 @@ private string Callee() throw new Exception(); } } - """, """ + """, + """ using System; public class TestClass { @@ -3354,7 +3368,8 @@ public void Caller() private string Callee() => throw new Exception(); } - """, """ + """, + """ using System; public class TestClass { @@ -3380,7 +3395,8 @@ public void Caller(bool a) private string Callee() => throw new Exception(); } - """, """ + """, + """ using System; public class TestClass { @@ -3403,7 +3419,8 @@ public class TestClass private string Callee() => throw new Exception(); } - """, """ + """, + """ using System; public class TestClass { @@ -3429,7 +3446,8 @@ private string Callee() throw new Exception(); } } - """, """ + """, + """ using System; public class TestClass { @@ -3460,7 +3478,8 @@ private int Callee(int c) return c = 1000; } } - """, """ + """, + """ public class TestClass { public void Caller(bool a) @@ -3491,7 +3510,8 @@ private int Callee(int c, bool a) return a ? c + 1000 : c + 10000; } } - """, """ + """, + """ public class TestClass { public void Caller(bool a) @@ -3521,7 +3541,8 @@ private int Callee(int c, bool a) return a ? c + 1000 : c + 10000; } } - """, """ + """, + """ public class TestClass { public int Caller(bool a) => a ? SomeInt() + 1000 : SomeInt() + 10000; @@ -3550,7 +3571,8 @@ public class TestClass private void Callee(out int i) => i = 1; } - """, """ + """, + """ public class TestClass { public void Caller() => i = 1; @@ -3570,7 +3592,8 @@ public class TestClass private int Callee() => i + 1; } - """, """ + """, + """ public class TestClass { private const int i = 10; @@ -3590,7 +3613,8 @@ public class TestClass private int Callee() => i + 1; } - """, """ + """, + """ public class TestClass { private const int i = 10; @@ -3619,7 +3643,8 @@ public void Caller() private void Callee(out int i) => i = 1; } - """, """ + """, + """ using System; public class TestClass { @@ -3646,7 +3671,8 @@ public void Caller() private void Callee(out int i) => i = 1; } - """, """ + """, + """ using System; public class TestClass { @@ -3672,7 +3698,8 @@ public void Caller() private void Callee(out int i) => i = 1; } - """, """ + """, + """ using System; public class TestClass { @@ -3697,36 +3724,37 @@ void Caller() } } """, - """ - public partial class TestClass - { - partial void Callee(); + """ + public partial class TestClass + { + partial void Callee(); - partial void Callee() - { - System.Console.WriteLine("10"); - } + partial void Callee() + { + System.Console.WriteLine("10"); } - """, - """ - public partial class TestClass + } + """, + """ + public partial class TestClass + { + void Caller() { - void Caller() - { - System.Console.WriteLine("10"); - } + System.Console.WriteLine("10"); } - """, """ - public partial class TestClass + } + """, + """ + public partial class TestClass + { + partial void Callee(); + ## + partial void Callee() { - partial void Callee(); - ## - partial void Callee() - { - System.Console.WriteLine("10"); - } - ##} - """); + System.Console.WriteLine("10"); + } + ##} + """); [Fact] public Task TestForExtendedPartialMethod1() @@ -3740,36 +3768,37 @@ void Caller() } } """, - """ - public partial class TestClass - { - private partial void Callee(); + """ + public partial class TestClass + { + private partial void Callee(); - private partial void Callee() - { - System.Console.WriteLine("10"); - } - } - """, - """ - public partial class TestClass + private partial void Callee() { - void Caller() - { - System.Console.WriteLine("10"); - } + System.Console.WriteLine("10"); } - """, """ - public partial class TestClass + } + """, + """ + public partial class TestClass + { + void Caller() { - private partial void Callee(); + System.Console.WriteLine("10"); + } + } + """, + """ + public partial class TestClass + { + private partial void Callee(); - private partial void Callee() - { - System.Console.WriteLine("10"); - } + private partial void Callee() + { + System.Console.WriteLine("10"); } - """, keepInlinedMethod: true); + } + """, keepInlinedMethod: true); [Fact] public Task TestForPartialMethod2() @@ -3793,25 +3822,25 @@ partial void Callee() } } """, - """ - public partial class TestClass + """ + public partial class TestClass + { + partial void Caller() { - partial void Caller() - { - System.Console.WriteLine("10"); - } + System.Console.WriteLine("10"); } - public partial class TestClass - { - partial void Caller(); - partial void Callee(); + } + public partial class TestClass + { + partial void Caller(); + partial void Callee(); - partial void Callee() - { - System.Console.WriteLine("10"); - } + partial void Callee() + { + System.Console.WriteLine("10"); } - """, keepInlinedMethod: true); + } + """, keepInlinedMethod: true); [Fact] public Task TestForExtendedPartialMethod2() @@ -3835,23 +3864,67 @@ private partial void Callee() } } """, - """ - public partial class TestClass + """ + public partial class TestClass + { + private partial void Caller() { - private partial void Caller() - { - System.Console.WriteLine("10"); - } + System.Console.WriteLine("10"); } - public partial class TestClass - { - private partial void Caller(); - private partial void Callee(); + } + public partial class TestClass + { + private partial void Caller(); + private partial void Callee(); - private partial void Callee() - { - System.Console.WriteLine("10"); - } + private partial void Callee() + { + System.Console.WriteLine("10"); } - """, keepInlinedMethod: true); + } + """, keepInlinedMethod: true); + + [Fact] + public Task TestForMultipleFieldsInFieldDeclaration() + => TestVerifier.TestInRegularAndScriptInTheSameFileAsync( + """ + static class C + { + static readonly object A = [||]M(), + B = M(); + + private static object M() => null!; + } + """, + """ + static class C + { + static readonly object A = null!, + B = M(); + + private static object M() => null!; + } + """, keepInlinedMethod: true); + + [Fact] + public Task TestForMultipleFieldsInFieldDeclaration2() + => TestVerifier.TestInRegularAndScriptInTheSameFileAsync( + """ + static class C + { + static readonly object A = M(), + B = [||]M(); + + private static object M() => null!; + } + """, + """ + static class C + { + static readonly object A = M(), + B = null!; + + private static object M() => null!; + } + """, keepInlinedMethod: true); } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/InlineMethod/CSharpInlineMethodTests_CrossLanguage.cs b/src/EditorFeatures/CSharpTest/CodeActions/InlineMethod/CSharpInlineMethodTests_CrossLanguage.cs index 488f96be39650..297de450584c8 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/InlineMethod/CSharpInlineMethodTests_CrossLanguage.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/InlineMethod/CSharpInlineMethodTests_CrossLanguage.cs @@ -30,34 +30,32 @@ private async Task TestNoActionIsProvided(string initialMarkup) // it is hard to test cross language scenario. // After it is resolved then this test should be merged to the other test class [Fact] - public async Task TestCrossLanguageInline() - { - var input = @" - - - VBAssembly - - using VBAssembly; - public class TestClass - { - public void Caller() - { - var x = new VBClass(); - x.C[||]allee(); - } - } - - - - - Public Class VBClass - Private Sub Callee() - End Sub - End Class - - -"; - await TestNoActionIsProvided(input); - } + public Task TestCrossLanguageInline() + => TestNoActionIsProvided(""" + + + VBAssembly + + using VBAssembly; + public class TestClass + { + public void Caller() + { + var x = new VBClass(); + x.C[||]allee(); + } + } + + + + + Public Class VBClass + Private Sub Callee() + End Sub + End Class + + + + """); } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/MoveStaticMembers/CSharpMoveStaticMembersTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/MoveStaticMembers/CSharpMoveStaticMembersTests.cs index 7619ec377d4a2..d943b9e2b3c7d 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/MoveStaticMembers/CSharpMoveStaticMembersTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/MoveStaticMembers/CSharpMoveStaticMembersTests.cs @@ -4,16 +4,19 @@ using System.Collections.Immutable; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.MoveStaticMembers; +using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.MoveStaticMembers; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities.MoveStaticMembers; using Roslyn.Test.Utilities; using Xunit; -using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeRefactoringVerifier< - Microsoft.CodeAnalysis.CSharp.CodeRefactorings.MoveStaticMembers.CSharpMoveStaticMembersRefactoringProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MoveStaticMembers; +using VerifyCS = CSharpCodeRefactoringVerifier< + CSharpMoveStaticMembersRefactoringProvider>; + [UseExportProvider] [Trait(Traits.Feature, Traits.Features.CodeActionsMoveStaticMembers)] public sealed class CSharpMoveStaticMembersTests @@ -24,662 +27,641 @@ public sealed class CSharpMoveStaticMembersTests [Fact] public async Task TestMoveField() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int Test[||]Field = 1; - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestField"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestField = 1; - } -}"; - - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int Test[||]Field = 1; + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestField = 1; + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveProperty() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int Test[||]Property { get; set; } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestProperty"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestProperty { get; set; } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int Test[||]Property { get; set; } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestProperty { get; set; } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveEvent() { - var initialMarkup = @" -using System; - -namespace TestNs1 -{ - public class Class1 - { - public static event EventHandler Test[||]Event; - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestEvent"); - var expectedResult1 = @" -using System; + await TestMovementNewFileAsync(""" + using System; -namespace TestNs1 -{ - public class Class1 - { - } -}"; - var expectedResult2 = @"using System; + namespace TestNs1 + { + public class Class1 + { + public static event EventHandler Test[||]Event; + } + } + """, """ + using System; -namespace TestNs1 -{ - internal static class Class1Helpers - { - public static event EventHandler TestEvent; - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + namespace TestNs1 + { + public class Class1 + { + } + } + """, """ + using System; + + namespace TestNs1 + { + internal static class Class1Helpers + { + public static event EventHandler TestEvent; + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveMethod() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int Test[||]Method() - { - return 0; - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestMethod() - { - return 0; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int Test[||]Method() + { + return 0; + } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestMethod() + { + return 0; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveExtensionMethod() { - var initialMarkup = @" -namespace TestNs1 -{ - public static class Class1 - { - public static int Test[||]Method(this Other other) - { - return other.OtherInt + 2; - } - } - - public class Other - { - public int OtherInt; - public Other() - { - OtherInt = 5; - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -namespace TestNs1 -{ - public static class Class1 - { - } + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public static class Class1 + { + public static int Test[||]Method(this Other other) + { + return other.OtherInt + 2; + } + } - public class Other - { - public int OtherInt; - public Other() - { - OtherInt = 5; - } - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestMethod(this Other other) - { - return other.OtherInt + 2; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + public class Other + { + public int OtherInt; + public Other() + { + OtherInt = 5; + } + } + } + """, """ + namespace TestNs1 + { + public static class Class1 + { + } + + public class Other + { + public int OtherInt; + public Other() + { + OtherInt = 5; + } + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestMethod(this Other other) + { + return other.OtherInt + 2; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveConstField() { - // const is static so we should work here - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public const int Test[||]Field = 1; - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestField"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public const int TestField = 1; - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public const int Test[||]Field = 1; + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public const int TestField = 1; + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveNothing() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int Test[||]Method() - { - return 0; - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Empty; - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - public static int Test[||]Method() - { - return 0; - } - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int Test[||]Method() + { + return 0; + } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + public static int Test[||]Method() + { + return 0; + } + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveMethodWithTrivia() { - var initialMarkup = @" -namespace TestNs1 -{ - // some comment we don't want to move - public class Class1 - { - // some comment we want to move - public static int Test[||]Method() - { - return 0; - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -namespace TestNs1 -{ - // some comment we don't want to move - public class Class1 - { - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - // some comment we want to move - public static int TestMethod() - { - return 0; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + // some comment we don't want to move + public class Class1 + { + // some comment we want to move + public static int Test[||]Method() + { + return 0; + } + } + } + """, """ + namespace TestNs1 + { + // some comment we don't want to move + public class Class1 + { + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + // some comment we want to move + public static int TestMethod() + { + return 0; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveMultipleMethods() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static bool TestMethodBool() - { - return false; - } - - public static int Test[||]MethodInt() - { - return 0; - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestMethodInt", "TestMethodBool"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static bool TestMethodBool() - { - return false; - } - - public static int TestMethodInt() - { - return 0; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static bool TestMethodBool() + { + return false; + } + + public static int Test[||]MethodInt() + { + return 0; + } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static bool TestMethodBool() + { + return false; + } + + public static int TestMethodInt() + { + return 0; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveSingleMethodFromMultiple() { - // move the method that this was not triggered on - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int Test[||]MethodInt() - { - return 0; - } - - public static bool TestMethodBool() - { - return false; - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestMethodBool"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - public static int TestMethodInt() - { - return 0; - } - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int Test[||]MethodInt() + { + return 0; + } + + public static bool TestMethodBool() + { + return false; + } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + public static int TestMethodInt() + { + return 0; + } + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { - public static bool TestMethodBool() - { - return false; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + public static bool TestMethodBool() + { + return false; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveOneOfEach() { - var initialMarkup = @" -using System; - -namespace TestNs1 -{ - public class Class1 - { - public static int TestField; - - public static bool TestProperty { get; set; } - - public static event EventHandler TestEvent; - - public static int Test[||]Method() - { - return 0; - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create( "TestMethod", "TestField", "TestProperty", "TestEvent"); - var expectedResult1 = @" -using System; + await TestMovementNewFileAsync(""" + using System; -namespace TestNs1 -{ - public class Class1 - { - } -}"; - var expectedResult2 = @"using System; + namespace TestNs1 + { + public class Class1 + { + public static int TestField; -namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestField; + public static bool TestProperty { get; set; } - public static bool TestProperty { get; set; } + public static event EventHandler TestEvent; - public static event EventHandler TestEvent; + public static int Test[||]Method() + { + return 0; + } + } + } + """, """ + using System; - public static int Test[||]Method() - { - return 0; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + namespace TestNs1 + { + public class Class1 + { + } + } + """, """ + using System; + + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestField; + + public static bool TestProperty { get; set; } + + public static event EventHandler TestEvent; + + public static int Test[||]Method() + { + return 0; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestInNestedClass() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public class NestedClass1 - { - public static int Test[||]Field = 1; - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestField"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - public class NestedClass1 - { - } - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestField = 1; - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public class NestedClass1 + { + public static int Test[||]Field = 1; + } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + public class NestedClass1 + { + } + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestField = 1; + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestInNestedNamespace() { - // collapse the namespaces in the new file - var initialMarkup = @" -namespace TestNs1 -{ - namespace InnerNs - { - public class Class1 - { - public static int Test[||]Field = 1; - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestField"); - var expectedResult1 = @" -namespace TestNs1 -{ - namespace InnerNs - { - public class Class1 - { - } - } -}"; - var expectedResult2 = @"namespace TestNs1.InnerNs -{ - internal static class Class1Helpers - { - public static int TestField = 1; - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + namespace InnerNs + { + public class Class1 + { + public static int Test[||]Field = 1; + } + } + } + """, """ + namespace TestNs1 + { + namespace InnerNs + { + public class Class1 + { + } + } + } + """, """ + namespace TestNs1.InnerNs + { + internal static class Class1Helpers + { + public static int TestField = 1; + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveFieldNoNamespace() { - var initialMarkup = @" -public class Class1 -{ - public static int Test[||]Field = 1; -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestField"); - var expectedResult1 = @" -public class Class1 -{ -}"; - var expectedResult2 = @"internal static class Class1Helpers -{ - public static int TestField = 1; -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileAsync(""" + public class Class1 + { + public static int Test[||]Field = 1; + } + """, """ + public class Class1 + { + } + """, """ + internal static class Class1Helpers + { + public static int TestField = 1; + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveFieldNewNamespace() { - var initialMarkup = @" -public class Class1 -{ - public static int Test[||]Field = 1; -}"; - var selectedDestinationName = "NewNs.Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestField"); - var expectedResult1 = @" -public class Class1 -{ -}"; - var expectedResult2 = @"namespace NewNs -{ - internal static class Class1Helpers - { - public static int TestField = 1; - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileAsync(""" + public class Class1 + { + public static int Test[||]Field = 1; + } + """, """ + public class Class1 + { + } + """, """ + namespace NewNs + { + internal static class Class1Helpers + { + public static int TestField = 1; + } + } + """, "Class1Helpers.cs", selectedMembers, "NewNs.Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveMethodWithNamespacedSelectedDestination() { - // in the case that we have an extra namespace in the destination name - // we append it on to the old type's namespace - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int Test[||]Method() - { - return 0; - } - } -}"; - var selectedDestinationName = "ExtraNs.Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } -}"; - var expectedResult2 = @"namespace TestNs1.ExtraNs -{ - internal static class Class1Helpers - { - public static int TestMethod() - { - return 0; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int Test[||]Method() + { + return 0; + } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + } + """, """ + namespace TestNs1.ExtraNs + { + internal static class Class1Helpers + { + public static int TestMethod() + { + return 0; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "ExtraNs.Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveMethodFileScopedNamespace() { // We still keep normal namespacing rules in the new file - var initialMarkup = @" -namespace TestNs1; - -public class Class1 -{ - public static int Test[||]Method() - { - return 0; - } -}"; - var selectedDestinationName = "Class1Helpers"; var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -namespace TestNs1; + var expectedResult1 = """ + namespace TestNs1; -public class Class1 -{ -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestMethod() - { - return 0; - } - } -}"; - await new Test(selectedDestinationName, selectedMembers, newFileName) + public class Class1 + { + } + """; + await new Test("Class1Helpers", selectedMembers, newFileName) { - TestCode = initialMarkup, + TestCode = """ + namespace TestNs1; + + public class Class1 + { + public static int Test[||]Method() + { + return 0; + } + } + """, FixedState = { Sources = { expectedResult1, - (newFileName, expectedResult2) + (newFileName, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestMethod() + { + return 0; + } + } + } + """) } }, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp10 @@ -689,733 +671,713 @@ public static int TestMethod() [Fact] public async Task TestMoveGenericMethod() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static T Test[||]Method(T item) - { - return item; - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static T TestMethod(T item) - { - return item; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static T Test[||]Method(T item) + { + return item; + } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static T TestMethod(T item) + { + return item; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveMethodWithGenericClass() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static T Test[||]Method(T item) - { - return item; - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static T Test[||]Method(T item) - { - return item; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static T Test[||]Method(T item) + { + return item; + } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static T Test[||]Method(T item) + { + return item; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveMethodAndRefactorUsage() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int Test[||]Method() - { - return 0; - } + var selectedMembers = ImmutableArray.Create("TestMethod"); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int Test[||]Method() + { + return 0; + } + } + + public class Class2 + { + public static int TestMethod2() + { + return Class1.TestMethod(); + } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + + public class Class2 + { + public static int TestMethod2() + { + return Class1Helpers.TestMethod(); + } + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestMethod() + { + return 0; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } - public class Class2 + [Fact] + public async Task TestMoveMethodAndRefactorUsageWithTrivia() { - public static int TestMethod2() - { - return Class1.TestMethod(); - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } - - public class Class2 - { - public static int TestMethod2() - { - return Class1Helpers.TestMethod(); - } - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestMethod() - { - return 0; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); - } - - [Fact] - public async Task TestMoveMethodAndRefactorUsageWithTrivia() - { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int Test[||]Method() - { - return 0; - } - } + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int Test[||]Method() + { + return 0; + } + } - public class Class2 - { - public static int TestMethod2() - { - // keep this comment, and the random spaces here - return Class1. TestMethod( ); - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; - var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } + public class Class2 + { + public static int TestMethod2() + { + // keep this comment, and the random spaces here + return Class1. TestMethod( ); + } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } - public class Class2 - { - public static int TestMethod2() - { - // keep this comment, and the random spaces here - return Class1Helpers. TestMethod( ); - } - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestMethod() - { - return 0; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + public class Class2 + { + public static int TestMethod2() + { + // keep this comment, and the random spaces here + return Class1Helpers. TestMethod( ); + } + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestMethod() + { + return 0; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveMethodAndRefactorSourceUsage() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int Test[||]Method() - { - return 0; - } - - public static int TestMethod2() - { - return TestMethod(); - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - public static int TestMethod2() - { - return Class1Helpers.TestMethod(); - } - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestMethod() - { - return 0; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int Test[||]Method() + { + return 0; + } + + public static int TestMethod2() + { + return TestMethod(); + } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + public static int TestMethod2() + { + return Class1Helpers.TestMethod(); + } + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestMethod() + { + return 0; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveFieldAndRefactorSourceUsage() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int Test[||]Field = 0; - - public static int TestMethod2() - { - return TestField; - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestField"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - public static int TestMethod2() - { - return Class1Helpers.TestField; - } - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestField = 0; - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int Test[||]Field = 0; + + public static int TestMethod2() + { + return TestField; + } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + public static int TestMethod2() + { + return Class1Helpers.TestField; + } + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestField = 0; + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMovePropertyAndRefactorSourceUsage() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - private static int _testProperty; - - public static int Test[||]Property - { - get => _testProperty; - set + var selectedMembers = ImmutableArray.Create("TestProperty", "_testProperty"); + await TestMovementNewFileAsync(""" + namespace TestNs1 { - _testProperty = value; + public class Class1 + { + private static int _testProperty; + + public static int Test[||]Property + { + get => _testProperty; + set + { + _testProperty = value; + } + } + + public static int TestMethod2() + { + return TestProperty; + } + } } - } - - public static int TestMethod2() - { - return TestProperty; - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; - var selectedMembers = ImmutableArray.Create("TestProperty", "_testProperty"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - public static int TestMethod2() - { - return Class1Helpers.TestProperty; - } - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - private static int _testProperty; - - public static int Test[||]Property - { - get => _testProperty; - set + """, """ + namespace TestNs1 { - _testProperty = value; + public class Class1 + { + public static int TestMethod2() + { + return Class1Helpers.TestProperty; + } + } } - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + private static int _testProperty; + + public static int Test[||]Property + { + get => _testProperty; + set + { + _testProperty = value; + } + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveGenericMethodAndRefactorImpliedUsage() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static T Test[||]Method(T item) - { - return item; - } - } - - public class Class2 - { - public static int TestMethod2() - { - return Class1.TestMethod(5); - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static T Test[||]Method(T item) + { + return item; + } + } - public class Class2 - { - public static int TestMethod2() - { - return Class1Helpers.TestMethod(5); - } - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static T TestMethod(T item) - { - return item; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + public class Class2 + { + public static int TestMethod2() + { + return Class1.TestMethod(5); + } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + + public class Class2 + { + public static int TestMethod2() + { + return Class1Helpers.TestMethod(5); + } + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static T TestMethod(T item) + { + return item; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveGenericMethodAndRefactorUsage() { - var initialMarkup = @" -using System; + var selectedMembers = ImmutableArray.Create("TestMethod"); + await TestMovementNewFileAsync(""" + using System; -namespace TestNs1 -{ - public class Class1 - { - public static Type Test[||]Method() - { - return typeof(T); - } - } + namespace TestNs1 + { + public class Class1 + { + public static Type Test[||]Method() + { + return typeof(T); + } + } - public class Class2 - { - public static Type TestMethod2() - { - return Class1.TestMethod(); - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; - var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -using System; + public class Class2 + { + public static Type TestMethod2() + { + return Class1.TestMethod(); + } + } + } + """, """ + using System; -namespace TestNs1 -{ - public class Class1 - { - } + namespace TestNs1 + { + public class Class1 + { + } - public class Class2 - { - public static Type TestMethod2() - { - return Class1Helpers.TestMethod(); - } - } -}"; - var expectedResult2 = @"using System; + public class Class2 + { + public static Type TestMethod2() + { + return Class1Helpers.TestMethod(); + } + } + } + """, """ + using System; -namespace TestNs1 -{ - internal static class Class1Helpers - { - public static Type TestMethod() - { - return typeof(T); - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + namespace TestNs1 + { + internal static class Class1Helpers + { + public static Type TestMethod() + { + return typeof(T); + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveMethodFromGenericClassAndRefactorUsage() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static T TestGeneric { get; set; } + var selectedMembers = ImmutableArray.Create("TestMethod", "TestGeneric"); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static T TestGeneric { get; set; } - public static T Test[||]Method() - { - return TestGeneric; - } - } + public static T Test[||]Method() + { + return TestGeneric; + } + } - public class Class2 - { - public static int TestMethod2() - { - return Class1.TestMethod(); - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; - var selectedMembers = ImmutableArray.Create("TestMethod", "TestGeneric"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } + public class Class2 + { + public static int TestMethod2() + { + return Class1.TestMethod(); + } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } - public class Class2 - { - public static int TestMethod2() - { - return Class1Helpers.TestMethod(); - } - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static T TestGeneric { get; set; } + public class Class2 + { + public static int TestMethod2() + { + return Class1Helpers.TestMethod(); + } + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static T TestGeneric { get; set; } - public static T TestMethod() - { - return TestGeneric; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + public static T TestMethod() + { + return TestGeneric; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveMethodFromGenericClassAndRefactorPartialTypeArgUsage() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - where T1 : new() - { - public static T1 Test[||]Method() - { - return new T1(); - } + var selectedMembers = ImmutableArray.Create("TestMethod"); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + where T1 : new() + { + public static T1 Test[||]Method() + { + return new T1(); + } - public static T2 TestGeneric2 { get; set; } + public static T2 TestGeneric2 { get; set; } - public T3 TestGeneric3 { get; set; } - } + public T3 TestGeneric3 { get; set; } + } - public class Class2 - { - public static int TestMethod2() - { - return Class1.TestMethod(); - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; - var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - where T1 : new() - { - public static T2 TestGeneric2 { get; set; } + public class Class2 + { + public static int TestMethod2() + { + return Class1.TestMethod(); + } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + where T1 : new() + { + public static T2 TestGeneric2 { get; set; } - public T3 TestGeneric3 { get; set; } - } + public T3 TestGeneric3 { get; set; } + } - public class Class2 - { - public static int TestMethod2() - { - return Class1Helpers.TestMethod(); - } - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers where T1 : new() - { - public static T1 TestMethod() - { - return new T1(); - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + public class Class2 + { + public static int TestMethod2() + { + return Class1Helpers.TestMethod(); + } + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers where T1 : new() + { + public static T1 TestMethod() + { + return new T1(); + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveMethodAndRefactorUsageDifferentNamespace() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int Test[||]Method() - { - return 0; - } - } -} + var selectedMembers = ImmutableArray.Create("TestMethod"); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int Test[||]Method() + { + return 0; + } + } + } -namespace TestNs2 -{ - using TestNs1; + namespace TestNs2 + { + using TestNs1; - public class Class2 - { - public static int TestMethod2() - { - return Class1.TestMethod(); - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; - var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } -} + public class Class2 + { + public static int TestMethod2() + { + return Class1.TestMethod(); + } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + } -namespace TestNs2 -{ - using TestNs1; + namespace TestNs2 + { + using TestNs1; - public class Class2 - { - public static int TestMethod2() - { - return Class1Helpers.TestMethod(); - } - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestMethod() - { - return 0; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + public class Class2 + { + public static int TestMethod2() + { + return Class1Helpers.TestMethod(); + } + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestMethod() + { + return 0; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveMethodAndRefactorUsageNewNamespace() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int Test[||]Method() - { - return 0; - } - } - - public class Class2 - { - public static int TestMethod2() - { - return Class1.TestMethod(); - } - } -}"; - var selectedDestinationName = "ExtraNs.Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -using TestNs1.ExtraNs; - -namespace TestNs1 -{ - public class Class1 - { - } + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int Test[||]Method() + { + return 0; + } + } - public class Class2 - { - public static int TestMethod2() - { - return Class1Helpers.TestMethod(); - } - } -}"; - var expectedResult2 = @"namespace TestNs1.ExtraNs -{ - internal static class Class1Helpers - { - public static int TestMethod() - { - return 0; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + public class Class2 + { + public static int TestMethod2() + { + return Class1.TestMethod(); + } + } + } + """, """ + using TestNs1.ExtraNs; + + namespace TestNs1 + { + public class Class1 + { + } + + public class Class2 + { + public static int TestMethod2() + { + return Class1Helpers.TestMethod(); + } + } + } + """, """ + namespace TestNs1.ExtraNs + { + internal static class Class1Helpers + { + public static int TestMethod() + { + return 0; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "ExtraNs.Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveMethodAndRefactorUsageSeparateFile() { - var initialMarkup1 = @" -namespace TestNs1 -{ - public class Class1 - { - public static int Test[||]Method() - { - return 0; - } - } -}"; - var initialMarkup2 = @" -using TestNs1; + var initialMarkup1 = """ + namespace TestNs1 + { + public class Class1 + { + public static int Test[||]Method() + { + return 0; + } + } + } + """; + var initialMarkup2 = """ + using TestNs1; -public class Class2 -{ - public static int TestMethod2() - { - return Class1.TestMethod(); - } -}"; - var selectedDestinationName = "Class1Helpers"; + public class Class2 + { + public static int TestMethod2() + { + return Class1.TestMethod(); + } + } + """; var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } -}"; - var expectedResult3 = @" -using TestNs1; + var expectedResult1 = """ + namespace TestNs1 + { + public class Class1 + { + } + } + """; + var expectedResult3 = """ + using TestNs1; -public class Class2 -{ - public static int TestMethod2() - { - return Class1Helpers.TestMethod(); - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestMethod() - { - return 0; - } - } -}"; - await new Test(selectedDestinationName, selectedMembers, newFileName) + public class Class2 + { + public static int TestMethod2() + { + return Class1Helpers.TestMethod(); + } + } + """; + await new Test("Class1Helpers", selectedMembers, newFileName) { TestState = { @@ -1431,7 +1393,18 @@ public static int TestMethod() { expectedResult1, expectedResult3, - (newFileName, expectedResult2) + (newFileName, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestMethod() + { + return 0; + } + } + } + """) } } }.RunAsync().ConfigureAwait(false); @@ -1440,216 +1413,215 @@ public static int TestMethod() [Fact] public async Task TestMoveMethodAndRefactorClassAlias() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int Test[||]Method() - { - return 0; - } - } -} + var selectedMembers = ImmutableArray.Create("TestMethod"); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int Test[||]Method() + { + return 0; + } + } + } -namespace TestNs2 -{ - using C1 = TestNs1.Class1; + namespace TestNs2 + { + using C1 = TestNs1.Class1; - class Class2 - { - public static int TestMethod2() - { - return C1.TestMethod(); - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; - var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } -} + class Class2 + { + public static int TestMethod2() + { + return C1.TestMethod(); + } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + } -namespace TestNs2 -{ - using TestNs1; - using C1 = TestNs1.Class1; + namespace TestNs2 + { + using TestNs1; + using C1 = TestNs1.Class1; - class Class2 - { - public static int TestMethod2() - { - return Class1Helpers.TestMethod(); - } - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestMethod() - { - return 0; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + class Class2 + { + public static int TestMethod2() + { + return Class1Helpers.TestMethod(); + } + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestMethod() + { + return 0; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveMethodAndRefactorNamespaceAlias() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int Test[||]Method() - { - return 0; - } - } -} + var selectedMembers = ImmutableArray.Create("TestMethod"); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int Test[||]Method() + { + return 0; + } + } + } -namespace TestNs2 -{ - using C1 = TestNs1; + namespace TestNs2 + { + using C1 = TestNs1; - class Class2 - { - public static int TestMethod2() - { - return C1.Class1.TestMethod(); - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; - var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } -} + class Class2 + { + public static int TestMethod2() + { + return C1.Class1.TestMethod(); + } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + } -namespace TestNs2 -{ - using TestNs1; - using C1 = TestNs1; + namespace TestNs2 + { + using TestNs1; + using C1 = TestNs1; - class Class2 - { - public static int TestMethod2() - { - return Class1Helpers.TestMethod(); - } - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestMethod() - { - return 0; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + class Class2 + { + public static int TestMethod2() + { + return Class1Helpers.TestMethod(); + } + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestMethod() + { + return 0; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveMethodAndRefactorConflictingName() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int F[||]oo() - { - return 0; - } - } -} + var newFileName = "Class1Helpers.cs"; + var selectedMembers = ImmutableArray.Create("Foo"); + var expectedResult1 = """ + namespace TestNs1 + { + public class Class1 + { + } + } -namespace TestNs2 -{ - using TestNs1; + namespace TestNs2 + { + using TestNs1; - class Class2 - { - class Class1Helpers + class Class2 + { + class Class1Helpers + { + public static int Foo() + { + return 1; + } + } + + public static int TestMethod2() + { + return TestNs1.Class1Helpers.Foo() + Class1Helpers.Foo(); + } + } + } + """; + await new Test("Class1Helpers", selectedMembers, newFileName) { - public static int Foo() + TestCode = """ + namespace TestNs1 { - return 1; + public class Class1 + { + public static int F[||]oo() + { + return 0; + } + } } - } - - public static int TestMethod2() - { - return Class1.Foo() + Class1Helpers.Foo(); - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; - var selectedMembers = ImmutableArray.Create("Foo"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } -} -namespace TestNs2 -{ - using TestNs1; - - class Class2 - { - class Class1Helpers - { - public static int Foo() + namespace TestNs2 { - return 1; + using TestNs1; + + class Class2 + { + class Class1Helpers + { + public static int Foo() + { + return 1; + } + } + + public static int TestMethod2() + { + return Class1.Foo() + Class1Helpers.Foo(); + } + } } - } - - public static int TestMethod2() - { - return TestNs1.Class1Helpers.Foo() + Class1Helpers.Foo(); - } - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int Foo() - { - return 0; - } - } -}"; - await new Test(selectedDestinationName, selectedMembers, newFileName) - { - TestCode = initialMarkup, + """, FixedState = { Sources = { expectedResult1, - (newFileName, expectedResult2) + (newFileName, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int Foo() + { + return 0; + } + } + } + """) } }, // the test parser thinks "TestNs1.Class1Helpers" is a member access expression @@ -1661,536 +1633,530 @@ public static int Foo() [Fact] public async Task TestMoveMethodAndRefactorQualifiedName() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int Test[||]Method() - { - return 0; - } - } -} - -namespace TestNs2 -{ - class Class2 - { - public static int TestMethod2() - { - return TestNs1.Class1.TestMethod(); - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -using TestNs1; + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int Test[||]Method() + { + return 0; + } + } + } -namespace TestNs1 -{ - public class Class1 - { - } -} + namespace TestNs2 + { + class Class2 + { + public static int TestMethod2() + { + return TestNs1.Class1.TestMethod(); + } + } + } + """, """ + using TestNs1; -namespace TestNs2 -{ - class Class2 - { - public static int TestMethod2() - { - return Class1Helpers.TestMethod(); - } - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestMethod() - { - return 0; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); - } + namespace TestNs1 + { + public class Class1 + { + } + } - [Fact] - public async Task TestMoveMethodAndRefactorStaticUsing() - { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int Test[||]Method() - { - return 0; - } + namespace TestNs2 + { + class Class2 + { + public static int TestMethod2() + { + return Class1Helpers.TestMethod(); + } + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestMethod() + { + return 0; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } -} - -namespace TestNs2 -{ - using static TestNs1.Class1; - class Class2 + [Fact] + public async Task TestMoveMethodAndRefactorStaticUsing() { - public static int TestMethod2() - { - return TestMethod(); - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } -} + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int Test[||]Method() + { + return 0; + } + } + } -namespace TestNs2 -{ - using TestNs1; - using static TestNs1.Class1; + namespace TestNs2 + { + using static TestNs1.Class1; - class Class2 - { - public static int TestMethod2() - { - return Class1Helpers.TestMethod(); - } - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestMethod() - { - return 0; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + class Class2 + { + public static int TestMethod2() + { + return TestMethod(); + } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + } + + namespace TestNs2 + { + using TestNs1; + using static TestNs1.Class1; + + class Class2 + { + public static int TestMethod2() + { + return Class1Helpers.TestMethod(); + } + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestMethod() + { + return 0; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveMethodAndRefactorNamespaceAliasWithExtraNamespace() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int Test[||]Method() - { - return 0; - } - } -} + var selectedMembers = ImmutableArray.Create("TestMethod"); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int Test[||]Method() + { + return 0; + } + } + } -namespace TestNs2 -{ - using C1 = TestNs1; + namespace TestNs2 + { + using C1 = TestNs1; - class Class2 - { - public static int TestMethod2() - { - return C1.Class1.TestMethod(); - } - } -}"; - var selectedDestinationName = "ExtraNs.Class1Helpers"; - var newFileName = "Class1Helpers.cs"; - var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } -} + class Class2 + { + public static int TestMethod2() + { + return C1.Class1.TestMethod(); + } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + } -namespace TestNs2 -{ - using TestNs1.ExtraNs; - using C1 = TestNs1; + namespace TestNs2 + { + using TestNs1.ExtraNs; + using C1 = TestNs1; - class Class2 - { - public static int TestMethod2() - { - return Class1Helpers.TestMethod(); - } - } -}"; - var expectedResult2 = @"namespace TestNs1.ExtraNs -{ - internal static class Class1Helpers - { - public static int TestMethod() - { - return 0; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + class Class2 + { + public static int TestMethod2() + { + return Class1Helpers.TestMethod(); + } + } + } + """, """ + namespace TestNs1.ExtraNs + { + internal static class Class1Helpers + { + public static int TestMethod() + { + return 0; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "ExtraNs.Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveExtensionMethodDoNotRefactor() { - var initialMarkup = @" -namespace TestNs1 -{ - public static class Class1 - { - public static int Test[||]Method(this Other other) - { - return other.OtherInt + 2; - } - } + var selectedMembers = ImmutableArray.Create("TestMethod"); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public static class Class1 + { + public static int Test[||]Method(this Other other) + { + return other.OtherInt + 2; + } + } - public class Class2 - { - public int GetOtherInt() - { - var other = new Other(); - return other.TestMethod(); - } - } + public class Class2 + { + public int GetOtherInt() + { + var other = new Other(); + return other.TestMethod(); + } + } - public class Other - { - public int OtherInt; - public Other() - { - OtherInt = 5; - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; - var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -namespace TestNs1 -{ - public static class Class1 - { - } + public class Other + { + public int OtherInt; + public Other() + { + OtherInt = 5; + } + } + } + """, """ + namespace TestNs1 + { + public static class Class1 + { + } - public class Class2 - { - public int GetOtherInt() - { - var other = new Other(); - return other.TestMethod(); - } - } + public class Class2 + { + public int GetOtherInt() + { + var other = new Other(); + return other.TestMethod(); + } + } - public class Other - { - public int OtherInt; - public Other() - { - OtherInt = 5; - } - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestMethod(this Other other) - { - return other.OtherInt + 2; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + public class Other + { + public int OtherInt; + public Other() + { + OtherInt = 5; + } + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestMethod(this Other other) + { + return other.OtherInt + 2; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveExtensionMethodRefactorImports() { - var initialMarkup = @" -namespace TestNs1 -{ - using TestNs2; + var selectedMembers = ImmutableArray.Create("TestMethod"); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + using TestNs2; - public static class Class1 - { - public static int Test[||]Method(this Other other) - { - return other.OtherInt + 2; - } - } -} + public static class Class1 + { + public static int Test[||]Method(this Other other) + { + return other.OtherInt + 2; + } + } + } -namespace TestNs2 -{ - using TestNs1; + namespace TestNs2 + { + using TestNs1; - public class Class2 - { - public int GetOtherInt() - { - var other = new Other(); - return other.TestMethod(); - } - } + public class Class2 + { + public int GetOtherInt() + { + var other = new Other(); + return other.TestMethod(); + } + } - public class Other - { - public int OtherInt; - public Other() - { - OtherInt = 5; - } - } -}"; - var selectedDestinationName = "ExtraNs.Class1Helpers"; - var newFileName = "Class1Helpers.cs"; - var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -namespace TestNs1 -{ - using TestNs2; + public class Other + { + public int OtherInt; + public Other() + { + OtherInt = 5; + } + } + } + """, """ + namespace TestNs1 + { + using TestNs2; - public static class Class1 - { - } -} + public static class Class1 + { + } + } -namespace TestNs2 -{ - using TestNs1; - using TestNs1.ExtraNs; + namespace TestNs2 + { + using TestNs1; + using TestNs1.ExtraNs; - public class Class2 - { - public int GetOtherInt() - { - var other = new Other(); - return other.TestMethod(); - } - } + public class Class2 + { + public int GetOtherInt() + { + var other = new Other(); + return other.TestMethod(); + } + } - public class Other - { - public int OtherInt; - public Other() - { - OtherInt = 5; - } - } -}"; - var expectedResult2 = @"using TestNs2; + public class Other + { + public int OtherInt; + public Other() + { + OtherInt = 5; + } + } + } + """, """ + using TestNs2; -namespace TestNs1.ExtraNs -{ - internal static class Class1Helpers - { - public static int TestMethod(this Other other) - { - return other.OtherInt + 2; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + namespace TestNs1.ExtraNs + { + internal static class Class1Helpers + { + public static int TestMethod(this Other other) + { + return other.OtherInt + 2; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "ExtraNs.Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveExtensionMethodRefactorMultipleImports() { - var initialMarkup = @" -namespace TestNs1 -{ - using TestNs2; - - public static class Class1 - { - public static int Test[||]Method(this Other other) - { - return other.OtherInt + 2; - } - } -} - -namespace TestNs2 -{ - using TestNs1; + var selectedMembers = ImmutableArray.Create("TestMethod"); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + using TestNs2; - public class Class2 - { - public int GetOtherInt() - { - var other = new Other(); - return other.TestMethod(); - } + public static class Class1 + { + public static int Test[||]Method(this Other other) + { + return other.OtherInt + 2; + } + } + } - public int GetOtherInt2() - { - var other = new Other(); - return other.TestMethod(); - } - } + namespace TestNs2 + { + using TestNs1; - public class Other - { - public int OtherInt; - public Other() - { - OtherInt = 5; - } - } -}"; - var selectedDestinationName = "ExtraNs.Class1Helpers"; - var newFileName = "Class1Helpers.cs"; - var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -namespace TestNs1 -{ - using TestNs2; + public class Class2 + { + public int GetOtherInt() + { + var other = new Other(); + return other.TestMethod(); + } + + public int GetOtherInt2() + { + var other = new Other(); + return other.TestMethod(); + } + } - public static class Class1 - { - } -} + public class Other + { + public int OtherInt; + public Other() + { + OtherInt = 5; + } + } + } + """, """ + namespace TestNs1 + { + using TestNs2; -namespace TestNs2 -{ - using TestNs1; - using TestNs1.ExtraNs; + public static class Class1 + { + } + } - public class Class2 - { - public int GetOtherInt() - { - var other = new Other(); - return other.TestMethod(); - } + namespace TestNs2 + { + using TestNs1; + using TestNs1.ExtraNs; - public int GetOtherInt2() - { - var other = new Other(); - return other.TestMethod(); - } - } + public class Class2 + { + public int GetOtherInt() + { + var other = new Other(); + return other.TestMethod(); + } + + public int GetOtherInt2() + { + var other = new Other(); + return other.TestMethod(); + } + } - public class Other - { - public int OtherInt; - public Other() - { - OtherInt = 5; - } - } -}"; - var expectedResult2 = @"using TestNs2; + public class Other + { + public int OtherInt; + public Other() + { + OtherInt = 5; + } + } + } + """, """ + using TestNs2; -namespace TestNs1.ExtraNs -{ - internal static class Class1Helpers - { - public static int TestMethod(this Other other) - { - return other.OtherInt + 2; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + namespace TestNs1.ExtraNs + { + internal static class Class1Helpers + { + public static int TestMethod(this Other other) + { + return other.OtherInt + 2; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "ExtraNs.Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveMethodFromStaticClass() { - var initialMarkup = @" -namespace TestNs1 -{ - public static class Class1 - { - public static int Test[||]Method() - { - return 0; - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -namespace TestNs1 -{ - public static class Class1 - { - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestMethod() - { - return 0; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public static class Class1 + { + public static int Test[||]Method() + { + return 0; + } + } + } + """, """ + namespace TestNs1 + { + public static class Class1 + { + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestMethod() + { + return 0; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveMethodRetainFileBanner() { - var initialMarkup = @"// Here is an example of a license or something -// we would want to keep at the top of a file - -namespace TestNs1 -{ - public static class Class1 - { - public static int Test[||]Method() - { - return 0; - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @"// Here is an example of a license or something -// we would want to keep at the top of a file + await TestMovementNewFileAsync(""" + // Here is an example of a license or something + // we would want to keep at the top of a file -namespace TestNs1 -{ - public static class Class1 - { - } -}"; - var expectedResult2 = @"// Here is an example of a license or something -// we would want to keep at the top of a file + namespace TestNs1 + { + public static class Class1 + { + public static int Test[||]Method() + { + return 0; + } + } + } + """, """ + // Here is an example of a license or something + // we would want to keep at the top of a file -namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestMethod() - { - return 0; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + namespace TestNs1 + { + public static class Class1 + { + } + } + """, """ + // Here is an example of a license or something + // we would want to keep at the top of a file + + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestMethod() + { + return 0; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } #endregion @@ -2198,432 +2164,414 @@ public static int TestMethod() [Fact] public async Task TestMoveFieldToExistingType() { - var initialSourceMarkup = @" -public class Class1 -{ - public static int Test[||]Field = 1; -}"; - var initialDestinationMarkup = @" -public class Class1Helpers -{ -}"; - var selectedDestinationName = "Class1Helpers"; var selectedMembers = ImmutableArray.Create("TestField"); - var fixedSourceMarkup = @" -public class Class1 -{ -}"; - var fixedDestinationMarkup = @" -public class Class1Helpers -{ - public static int TestField = 1; -}"; - await TestMovementExistingFileAsync( - initialSourceMarkup, - initialDestinationMarkup, - fixedSourceMarkup, - fixedDestinationMarkup, + """ + public class Class1 + { + public static int Test[||]Field = 1; + } + """, + """ + public class Class1Helpers + { + } + """, + """ + public class Class1 + { + } + """, + """ + public class Class1Helpers + { + public static int TestField = 1; + } + """, selectedMembers, - selectedDestinationName).ConfigureAwait(false); + "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMovePropertyToExistingType() { - var initialSourceMarkup = @" -public class Class1 -{ - public static int Test[||]Property { get; set; } -}"; - var initialDestinationMarkup = @" -public class Class1Helpers -{ -}"; - var selectedDestinationName = "Class1Helpers"; var selectedMembers = ImmutableArray.Create("TestProperty"); - var fixedSourceMarkup = @" -public class Class1 -{ -}"; - var fixedDestinationMarkup = @" -public class Class1Helpers -{ - public static int TestProperty { get; set; } -}"; - await TestMovementExistingFileAsync( - initialSourceMarkup, - initialDestinationMarkup, - fixedSourceMarkup, - fixedDestinationMarkup, + """ + public class Class1 + { + public static int Test[||]Property { get; set; } + } + """, + """ + public class Class1Helpers + { + } + """, + """ + public class Class1 + { + } + """, + """ + public class Class1Helpers + { + public static int TestProperty { get; set; } + } + """, selectedMembers, - selectedDestinationName).ConfigureAwait(false); + "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveEventToExistingType() { - var initialSourceMarkup = @" -using System; - -public class Class1 -{ - public static event EventHandler Test[||]Event; -}"; - var initialDestinationMarkup = @" -public class Class1Helpers -{ -}"; - var selectedDestinationName = "Class1Helpers"; var selectedMembers = ImmutableArray.Create("TestEvent"); - var fixedSourceMarkup = @" -using System; + await TestMovementExistingFileAsync( + """ + using System; -public class Class1 -{ -}"; - var fixedDestinationMarkup = @" -using System; + public class Class1 + { + public static event EventHandler Test[||]Event; + } + """, + """ + public class Class1Helpers + { + } + """, + """ + using System; -public class Class1Helpers -{ - public static event EventHandler TestEvent; -}"; + public class Class1 + { + } + """, + """ + using System; - await TestMovementExistingFileAsync( - initialSourceMarkup, - initialDestinationMarkup, - fixedSourceMarkup, - fixedDestinationMarkup, + public class Class1Helpers + { + public static event EventHandler TestEvent; + } + """, selectedMembers, - selectedDestinationName).ConfigureAwait(false); + "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveMethodToExistingType() { - var initialSourceMarkup = @" -public class Class1 -{ - public static int Test[||]Method() - { - return 0; - } -}"; - var initialDestinationMarkup = @" -public class Class1Helpers -{ -}"; - var selectedDestinationName = "Class1Helpers"; var selectedMembers = ImmutableArray.Create("TestMethod"); - var fixedSourceMarkup = @" -public class Class1 -{ -}"; - var fixedDestinationMarkup = @" -public class Class1Helpers -{ - public static int TestMethod() - { - return 0; - } -}"; - await TestMovementExistingFileAsync( - initialSourceMarkup, - initialDestinationMarkup, - fixedSourceMarkup, - fixedDestinationMarkup, + """ + public class Class1 + { + public static int Test[||]Method() + { + return 0; + } + } + """, + """ + public class Class1Helpers + { + } + """, + """ + public class Class1 + { + } + """, + """ + public class Class1Helpers + { + public static int TestMethod() + { + return 0; + } + } + """, selectedMembers, - selectedDestinationName).ConfigureAwait(false); + "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveExtensionMethodToExistingType() { - var initialSourceMarkup = @" -public static class Class1 -{ - public static int Test[||]Method(this Other other) - { - return other.OtherInt + 2; - } -} - -public class Other -{ - public int OtherInt; - public Other() - { - OtherInt = 5; - } -}"; - var initialDestinationMarkup = @" -public static class Class1Helpers -{ -}"; - var selectedDestinationName = "Class1Helpers"; var selectedMembers = ImmutableArray.Create("TestMethod"); - var fixedSourceMarkup = @" -public static class Class1 -{ -} + await TestMovementExistingFileAsync( + """ + public static class Class1 + { + public static int Test[||]Method(this Other other) + { + return other.OtherInt + 2; + } + } -public class Other -{ - public int OtherInt; - public Other() - { - OtherInt = 5; - } -}"; - var fixedDestinationMarkup = @" -public static class Class1Helpers -{ - public static int TestMethod(this Other other) - { - return other.OtherInt + 2; - } -}"; + public class Other + { + public int OtherInt; + public Other() + { + OtherInt = 5; + } + } + """, + """ + public static class Class1Helpers + { + } + """, + """ + public static class Class1 + { + } - await TestMovementExistingFileAsync( - initialSourceMarkup, - initialDestinationMarkup, - fixedSourceMarkup, - fixedDestinationMarkup, + public class Other + { + public int OtherInt; + public Other() + { + OtherInt = 5; + } + } + """, + """ + public static class Class1Helpers + { + public static int TestMethod(this Other other) + { + return other.OtherInt + 2; + } + } + """, selectedMembers, - selectedDestinationName).ConfigureAwait(false); + "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveConstFieldToExistingType() { - var initialSourceMarkup = @" -public class Class1 -{ - public const int Test[||]Field = 1; -}"; - var initialDestinationMarkup = @" -public class Class1Helpers -{ -}"; - var selectedDestinationName = "Class1Helpers"; var selectedMembers = ImmutableArray.Create("TestField"); - var fixedSourceMarkup = @" -public class Class1 -{ -}"; - var fixedDestinationMarkup = @" -public class Class1Helpers -{ - public const int TestField = 1; -}"; - await TestMovementExistingFileAsync( - initialSourceMarkup, - initialDestinationMarkup, - fixedSourceMarkup, - fixedDestinationMarkup, + """ + public class Class1 + { + public const int Test[||]Field = 1; + } + """, + """ + public class Class1Helpers + { + } + """, + """ + public class Class1 + { + } + """, + """ + public class Class1Helpers + { + public const int TestField = 1; + } + """, selectedMembers, - selectedDestinationName).ConfigureAwait(false); + "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveMethodToExistingTypeWithNamespace() { - var initialSourceMarkup = @" -namespace TestNs -{ - public class Class1 - { - public static int Test[||]Method() - { - return 0; - } - } -}"; - var initialDestinationMarkup = @" -namespace TestNs -{ - public class Class1Helpers - { - } -}"; - var selectedDestinationName = "TestNs.Class1Helpers"; var selectedMembers = ImmutableArray.Create("TestMethod"); - var fixedSourceMarkup = @" -namespace TestNs -{ - public class Class1 - { - } -}"; - var fixedDestinationMarkup = @" -namespace TestNs -{ - public class Class1Helpers - { - public static int TestMethod() - { - return 0; - } - } -}"; - await TestMovementExistingFileAsync( - initialSourceMarkup, - initialDestinationMarkup, - fixedSourceMarkup, - fixedDestinationMarkup, + """ + namespace TestNs + { + public class Class1 + { + public static int Test[||]Method() + { + return 0; + } + } + } + """, + """ + namespace TestNs + { + public class Class1Helpers + { + } + } + """, + """ + namespace TestNs + { + public class Class1 + { + } + } + """, + """ + namespace TestNs + { + public class Class1Helpers + { + public static int TestMethod() + { + return 0; + } + } + } + """, selectedMembers, - selectedDestinationName).ConfigureAwait(false); + "TestNs.Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveMethodToExistingTypeWithNewNamespace() { - var initialSourceMarkup = @" -public class Class1 -{ - public static int Test[||]Method() - { - return 0; - } -}"; - var initialDestinationMarkup = @" -namespace TestNs -{ - public class Class1Helpers - { - } -}"; - var selectedDestinationName = "TestNs.Class1Helpers"; var selectedMembers = ImmutableArray.Create("TestMethod"); - var fixedSourceMarkup = @" -public class Class1 -{ -}"; - var fixedDestinationMarkup = @" -namespace TestNs -{ - public class Class1Helpers - { - public static int TestMethod() - { - return 0; - } - } -}"; - await TestMovementExistingFileAsync( - initialSourceMarkup, - initialDestinationMarkup, - fixedSourceMarkup, - fixedDestinationMarkup, + """ + public class Class1 + { + public static int Test[||]Method() + { + return 0; + } + } + """, + """ + namespace TestNs + { + public class Class1Helpers + { + } + } + """, + """ + public class Class1 + { + } + """, + """ + namespace TestNs + { + public class Class1Helpers + { + public static int TestMethod() + { + return 0; + } + } + } + """, selectedMembers, - selectedDestinationName).ConfigureAwait(false); + "TestNs.Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveMethodToExistingTypeRefactorSourceUsage() - { - var initialSourceMarkup = @" -public class Class1 -{ - public static int Test[||]Method() - { - return 0; - } - - public static int TestMethod2() - { - return TestMethod(); - } -}"; - var initialDestinationMarkup = @" -public class Class1Helpers -{ -}"; - var selectedDestinationName = "Class1Helpers"; - var selectedMembers = ImmutableArray.Create("TestMethod"); - var fixedSourceMarkup = @" -public class Class1 -{ - public static int TestMethod2() - { - return Class1Helpers.TestMethod(); - } -}"; - var fixedDestinationMarkup = @" -public class Class1Helpers -{ - public static int TestMethod() - { - return 0; - } -}"; - + { + var selectedMembers = ImmutableArray.Create("TestMethod"); await TestMovementExistingFileAsync( - initialSourceMarkup, - initialDestinationMarkup, - fixedSourceMarkup, - fixedDestinationMarkup, + """ + public class Class1 + { + public static int Test[||]Method() + { + return 0; + } + + public static int TestMethod2() + { + return TestMethod(); + } + } + """, + """ + public class Class1Helpers + { + } + """, + """ + public class Class1 + { + public static int TestMethod2() + { + return Class1Helpers.TestMethod(); + } + } + """, + """ + public class Class1Helpers + { + public static int TestMethod() + { + return 0; + } + } + """, selectedMembers, - selectedDestinationName).ConfigureAwait(false); + "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestMoveMethodToExistingTypeRefactorDestinationUsage() { - var initialSourceMarkup = @" -public class Class1 -{ - public static int Test[||]Method() - { - return 0; - } -}"; - var initialDestinationMarkup = @" -public class Class1Helpers -{ - public static int TestMethod2() - { - return Class1.TestMethod(); - } -}"; - var selectedDestinationName = "Class1Helpers"; var selectedMembers = ImmutableArray.Create("TestMethod"); - var fixedSourceMarkup = @" -public class Class1 -{ -}"; - var fixedDestinationMarkup = @" -public class Class1Helpers -{ - public static int TestMethod() - { - return 0; - } - public static int TestMethod2() - { - return Class1Helpers.TestMethod(); - } -}"; - await TestMovementExistingFileAsync( - initialSourceMarkup, - initialDestinationMarkup, - fixedSourceMarkup, - fixedDestinationMarkup, + """ + public class Class1 + { + public static int Test[||]Method() + { + return 0; + } + } + """, + """ + public class Class1Helpers + { + public static int TestMethod2() + { + return Class1.TestMethod(); + } + } + """, + """ + public class Class1 + { + } + """, + """ + public class Class1Helpers + { + public static int TestMethod() + { + return 0; + } + public static int TestMethod2() + { + return Class1Helpers.TestMethod(); + } + } + """, selectedMembers, - selectedDestinationName).ConfigureAwait(false); + "Class1Helpers").ConfigureAwait(false); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66734")] public async Task TestMoveMethodToExistingTypeInSameFile() { - var initialSourceMarkup = """ + var selectedMembers = ImmutableArray.Create("IsValidWorkflowType", "validWorkflowTypes"); + await TestMovementExistingFileAsync( + """ public static class WorkflowTypes { public const string FirstType = "firstType"; @@ -2639,10 +2587,10 @@ public static class WorkflowValidations // Moving this method and above dependency into WorkflowTypes static class public static bool IsValid[||]WorkflowType(this string workflowType) => validWorkflowTypes.Contains(workflowType); } - """; - var selectedDestinationName = "WorkflowTypes"; - var selectedMembers = ImmutableArray.Create("IsValidWorkflowType", "validWorkflowTypes"); - var fixedSourceMarkup = """ + """, + // We're testing a move inside the same file, so just use an empty destination. + initialDestinationMarkup: string.Empty, + """ public static class WorkflowTypes { public const string FirstType = "firstType"; @@ -2658,16 +2606,10 @@ public static class WorkflowTypes public static class WorkflowValidations { } - """; - - await TestMovementExistingFileAsync( - initialSourceMarkup, - // We're testing a move inside the same file, so just use an empty destination. - initialDestinationMarkup: string.Empty, - fixedSourceMarkup, + """, fixedDestinationMarkup: string.Empty, selectedMembers, - selectedDestinationName).ConfigureAwait(false); + "WorkflowTypes").ConfigureAwait(false); } #endregion @@ -2677,713 +2619,689 @@ await TestMovementExistingFileAsync( [Fact] public async Task TestSelectInMethodParens() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int TestMethod([||]) - { - return 0; - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestMethod() - { - return 0; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int TestMethod([||]) + { + return 0; + } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestMethod() + { + return 0; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestSelectWholeFieldDeclaration() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - [|public static int TestField = 1;|] - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestField"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestField = 1; - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + [|public static int TestField = 1;|] + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestField = 1; + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestSelectBeforeKeywordOfDeclaration() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - [||]public static int TestField = 1; - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestField"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestField = 1; - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + [||]public static int TestField = 1; + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestField = 1; + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestSelectInKeyWordOfDeclaration1() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - pub[||]lic static int TestField = 1; - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestField"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestField = 1; - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + pub[||]lic static int TestField = 1; + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestField = 1; + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestSelectInKeyWordOfDeclaration2() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public st[||]atic int TestField = 1; - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestField"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestField = 1; - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public st[||]atic int TestField = 1; + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestField = 1; + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestSelectInTypeIdentifierMethodDeclaration() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static i[||]nt TestMethod() - { - return 0; - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestMethod"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestMethod() - { - return 0; - } - } -}"; - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static i[||]nt TestMethod() + { + return 0; + } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestMethod() + { + return 0; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestSelectInFieldInitializerAfterSemicolon() { - // However, a semicolon after the initializer is still considered a declaration - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int TestField = 1;[||] - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("TestField"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int TestField = 1; - } -}"; - - await TestMovementNewFileAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int TestField = 1;[||] + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int TestField = 1; + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestSelectInMultipleFieldIdentifiers() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - [|public static int Goo = 10, Foo = 9;|] - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("Goo", "Foo"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int Goo = 10; - public static int Foo = 9; - } -}"; - - await TestMovementNewFileWithSelectionAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); - } - - [Fact] - public async Task TestSelectMultipleMembers1() - { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - [|public static int Goo = 10, Foo = 9; - - public static int DoSomething() - { - return 5; - }|] - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; - var selectedMembers = ImmutableArray.Create("Goo", "Foo", "DoSomething"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { + await TestMovementNewFileWithSelectionAsync(""" + namespace TestNs1 + { + public class Class1 + { + [|public static int Goo = 10, Foo = 9;|] + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int Goo = 10; + public static int Foo = 9; + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers + + [Fact] + public async Task TestSelectMultipleMembers1() { - public static int Goo = 10; - public static int Foo = 9; + var selectedMembers = ImmutableArray.Create("Goo", "Foo", "DoSomething"); + await TestMovementNewFileWithSelectionAsync(""" + namespace TestNs1 + { + public class Class1 + { + [|public static int Goo = 10, Foo = 9; - public static int DoSomething() - { - return 5; - } - } -}"; + public static int DoSomething() + { + return 5; + }|] + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int Goo = 10; + public static int Foo = 9; - await TestMovementNewFileWithSelectionAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + public static int DoSomething() + { + return 5; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestSelectMultipleMembers2() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - - public static int DoSomething() - { - return [|5; - } - public static int Goo = 10, Foo = 9;|] - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("Goo", "Foo"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { + await TestMovementNewFileWithSelectionAsync(""" + namespace TestNs1 + { + public class Class1 + { - public static int DoSomething() - { - return 5; - } - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int Goo = 10; - public static int Foo = 9; - } -}"; + public static int DoSomething() + { + return [|5; + } + public static int Goo = 10, Foo = 9;|] + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { - await TestMovementNewFileWithSelectionAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + public static int DoSomething() + { + return 5; + } + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int Goo = 10; + public static int Foo = 9; + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestSelectMultipleMembers3() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int Go[|o = 10, Foo = 9; - - public static int DoSometh|]ing() - { - return 5; - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("Goo", "Foo", "DoSomething"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int Goo = 10; - public static int Foo = 9; + await TestMovementNewFileWithSelectionAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int Go[|o = 10, Foo = 9; - public static int DoSomething() - { - return 5; - } - } -}"; + public static int DoSometh|]ing() + { + return 5; + } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int Goo = 10; + public static int Foo = 9; - await TestMovementNewFileWithSelectionAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + public static int DoSomething() + { + return 5; + } + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestSelectMultipleMembers4() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int Goo = 10, F[|oo = 9; - - public static in|]t DoSomething() - { - return 5; - } - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("Foo"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - public static int Goo = 10; + await TestMovementNewFileWithSelectionAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int Goo = 10, F[|oo = 9; - public static int DoSomething() - { - return 5; - } - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int Foo = 9; - } -}"; + public static in|]t DoSomething() + { + return 5; + } + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + public static int Goo = 10; - await TestMovementNewFileWithSelectionAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + public static int DoSomething() + { + return 5; + } + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int Foo = 9; + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestSelectOneOfMultipleFieldIdentifiers() { - // However, a semicolon after the initializer is still considered a declaration - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int G[||]oo = 10, Foo = 9; - } -}"; - var selectedDestinationName = "Class1Helpers"; - var newFileName = "Class1Helpers.cs"; var selectedMembers = ImmutableArray.Create("Goo"); - var expectedResult1 = @" -namespace TestNs1 -{ - public class Class1 - { - public static int Foo = 9; - } -}"; - var expectedResult2 = @"namespace TestNs1 -{ - internal static class Class1Helpers - { - public static int Goo = 10; - } -}"; - - await TestMovementNewFileWithSelectionAsync(initialMarkup, expectedResult1, expectedResult2, newFileName, selectedMembers, selectedDestinationName).ConfigureAwait(false); + await TestMovementNewFileWithSelectionAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int G[||]oo = 10, Foo = 9; + } + } + """, """ + namespace TestNs1 + { + public class Class1 + { + public static int Foo = 9; + } + } + """, """ + namespace TestNs1 + { + internal static class Class1Helpers + { + public static int Goo = 10; + } + } + """, "Class1Helpers.cs", selectedMembers, "Class1Helpers").ConfigureAwait(false); } [Fact] public async Task TestSelectInTypeIdentifierOfFieldDeclaration_NoAction() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static i[||]nt TestField = 1; - } -}"; - await TestNoRefactoringAsync(initialMarkup).ConfigureAwait(false); + await TestNoRefactoringAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static i[||]nt TestField = 1; + } + } + """).ConfigureAwait(false); } [Fact] public async Task TestSelectInFieldInitializerEquals_NoAction() { // The initializer isn't a member declaration - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int TestField =[||] 1; - } -}"; - await TestNoRefactoringAsync(initialMarkup).ConfigureAwait(false); + await TestNoRefactoringAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int TestField =[||] 1; + } + } + """).ConfigureAwait(false); } [Fact] public async Task TestSelectMethodBody_NoAction() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int TestMethod() - { - retu[||]rn 0; - } - } -}"; - await TestNoRefactoringAsync(initialMarkup).ConfigureAwait(false); + await TestNoRefactoringAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int TestMethod() + { + retu[||]rn 0; + } + } + } + """).ConfigureAwait(false); } [Fact] public async Task TestSelectMethodBracket_NoAction() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int TestMethod() - [|{|] - return 0; - } - } -}"; - await TestNoRefactoringAsync(initialMarkup).ConfigureAwait(false); + await TestNoRefactoringAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int TestMethod() + [|{|] + return 0; + } + } + } + """).ConfigureAwait(false); } [Fact] public async Task TestSelectMalformedMethod_NoAction() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public st[||] {|CS1519:int|} TestMethod() - { - return 0; - } - } -}"; await new Test("", [], "") { - TestCode = initialMarkup, + TestCode = """ + namespace TestNs1 + { + public class Class1 + { + public st[||] {|CS1519:int|} TestMethod() + { + return 0; + } + } + } + """, }.RunAsync().ConfigureAwait(false); } [Fact] public async Task TestSelectMalformedField_NoAction1() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public st[||] {|CS1519:int|} TestField = 0; - } -}"; await new Test("", [], "") { - TestCode = initialMarkup, + TestCode = """ + namespace TestNs1 + { + public class Class1 + { + public st[||] {|CS1519:int|} TestField = 0; + } + } + """, }.RunAsync().ConfigureAwait(false); } [Fact] public async Task TestSelectMalformedField_NoAction2() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public st [|{|CS1519:int|} Test|]Field = 0; - } -}"; await new Test("", [], "") { - TestCode = initialMarkup, + TestCode = """ + namespace TestNs1 + { + public class Class1 + { + public st [|{|CS1519:int|} Test|]Field = 0; + } + } + """, }.RunAsync().ConfigureAwait(false); } [Fact] public async Task TestSelectMalformedField_NoAction3() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - [|public st {|CS1519:int|} TestField = 0;|] - } -}"; await new Test("", [], "") { - TestCode = initialMarkup, + TestCode = """ + namespace TestNs1 + { + public class Class1 + { + [|public st {|CS1519:int|} TestField = 0;|] + } + } + """, }.RunAsync().ConfigureAwait(false); } [Fact] public async Task TestSelectMalformedField_NoAction4() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - [|publicc {|CS1585:static|} int TestField = 0;|] - } -}"; await new Test("", [], "") { - TestCode = initialMarkup, + TestCode = """ + namespace TestNs1 + { + public class Class1 + { + [|publicc {|CS1585:static|} int TestField = 0;|] + } + } + """, }.RunAsync().ConfigureAwait(false); } [Fact] public async Task TestSelectPropertyBody_NoAction() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public static int TestProperty { get; [||]set; } - } -}"; - await TestNoRefactoringAsync(initialMarkup).ConfigureAwait(false); + await TestNoRefactoringAsync(""" + namespace TestNs1 + { + public class Class1 + { + public static int TestProperty { get; [||]set; } + } + } + """).ConfigureAwait(false); } [Fact] public async Task TestSelectNonStaticProperty_NoAction() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - public int Test[||]Property { get; set; } - } -}"; - await TestNoRefactoringAsync(initialMarkup).ConfigureAwait(false); + await TestNoRefactoringAsync(""" + namespace TestNs1 + { + public class Class1 + { + public int Test[||]Property { get; set; } + } + } + """).ConfigureAwait(false); } [Fact] public async Task TestSelectStaticConstructor1_NoAction() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - [|static Class1()|] - { - } - } -}"; - await TestNoRefactoringAsync(initialMarkup).ConfigureAwait(false); + await TestNoRefactoringAsync(""" + namespace TestNs1 + { + public class Class1 + { + [|static Class1()|] + { + } + } + } + """).ConfigureAwait(false); } [Fact] public async Task TestSelectStaticConstructor2_NoAction() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - static Cl[||]ass1() - { - } - } -}"; - await TestNoRefactoringAsync(initialMarkup).ConfigureAwait(false); + await TestNoRefactoringAsync(""" + namespace TestNs1 + { + public class Class1 + { + static Cl[||]ass1() + { + } + } + } + """).ConfigureAwait(false); } [Fact] public async Task TestSelectOperator_NoAction() { - var initialMarkup = @" -namespace TestNs1 -{ - public class Class1 - { - [|public static Class1 operator +(Class1 a, Class1 b)|] - { - return new Class1(); - } - } -}"; - await TestNoRefactoringAsync(initialMarkup).ConfigureAwait(false); + await TestNoRefactoringAsync(""" + namespace TestNs1 + { + public class Class1 + { + [|public static Class1 operator +(Class1 a, Class1 b)|] + { + return new Class1(); + } + } + } + """).ConfigureAwait(false); } [Fact] public async Task TestSelectTopLevelStatement_NoAction1() { - var initialMarkup = @" -using System; - -[||]Console.WriteLine(5); -"; - await new Test("", [], "") { - TestCode = initialMarkup, + TestCode = """ + using System; + + [||]Console.WriteLine(5); + """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp10, TestState = { @@ -3395,15 +3313,13 @@ public async Task TestSelectTopLevelStatement_NoAction1() [Fact] public async Task TestSelectTopLevelStatement_NoAction2() { - var initialMarkup = @" -using System; - -[|Console.WriteLine(5);|] -"; - await new Test("", [], "") { - TestCode = initialMarkup, + TestCode = """ + using System; + + [|Console.WriteLine(5);|] + """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp10, TestState = { @@ -3415,18 +3331,16 @@ public async Task TestSelectTopLevelStatement_NoAction2() [Fact] public async Task TestSelectTopLevelLocalFunction_NoAction() { - var initialMarkup = @" -DoSomething(); - -static int Do[||]Something() -{ - return 5; -} -"; - await new Test("", [], "") { - TestCode = initialMarkup, + TestCode = """ + DoSomething(); + + static int Do[||]Something() + { + return 5; + } + """, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp10, TestState = { diff --git a/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.ActionCountTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.ActionCountTests.cs index 5a53ce37b5845..9f03e773494b2 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.ActionCountTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.ActionCountTests.cs @@ -14,283 +14,240 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.MoveType; public partial class MoveTypeTests : CSharpMoveTypeTestsBase { [Fact] - public async Task MoveType_ActionCounts_RenameOnly() - { - var code = -@"namespace N1 -{ - class Class1[||] - { - } -}"; - // Fixes offered will be rename type to match file, rename file to match type. - await TestActionCountAsync(code, count: 2); - } - - [Fact] - public async Task MoveType_AvailableBeforeHeader() - { - var code = -@"namespace N1 -{ - [||] - class Class1 - { - } -}"; - await TestActionCountAsync(code, count: 2); - } - - [Fact] - public async Task MoveType_AvailableBeforeAttributeOnHeader() - { - var code = -@"namespace N1 -{ - [||][X] - class Class1 - { - } -}"; - await TestActionCountAsync(code, count: 2); - } - - [Fact] - public async Task MoveType_AvailableOnHeaderIncludingWhitespaceAndAttribute() - { - var code = -@"namespace N1 -{[| - [X] - class Class1 - {|] - } -}"; - await TestActionCountAsync(code, count: 2); - } - - [Fact] - public async Task MoveType_AvailableAfterHeader() - { - var code = -@"namespace N1 -{ - class Class1 - [||]{ - } -}"; - await TestActionCountAsync(code, count: 2); - } - - [Fact] - public async Task MoveType_AvailableIncludingDocumentationCommentAndHeader() - { - var code = -@"namespace N1 -{ - [|/// - /// Documentation comment. - /// - class Class1|] - { - } -}"; - await TestActionCountAsync(code, count: 2); - } - - [Fact] - public async Task MoveType_AvailableIncludingDocumentationCommentAndAttributeAndHeader() - { - var code = -@"using System; -namespace N1 -{ - [|/// - /// Documentation comment. - /// - [Obsolete] - class Class1|] - { - } -}"; - await TestActionCountAsync(code, count: 2); - } - - [Fact] - public async Task MoveType_NotAvailableBeforeType() - { - var code = -@"[|namespace N1 -{|] - class Class1 - { - } -}"; - await TestMissingInRegularAndScriptAsync(code); - } - - [Fact] - public async Task MoveType_NotAvailableInsideType() - { - var code = -@"namespace N1 -{ - class Class1 - {[| - void M() - { - }|] - } -}"; - await TestMissingInRegularAndScriptAsync(code); - } - - [Fact] - public async Task MoveType_NotAvailableAfterType() - { - var code = -@"namespace N1 -{ - class Class1 - { - void M() - { - } - } - - [|class test1|] - { - } -}"; - await TestMissingInRegularAndScriptAsync(code); - } - - [Fact] - public async Task MoveType_NotAvailableAroundDocumentationCommentAboveHeader() - { - var code = -@"namespace N1 -{ - [|/// - /// Documentation comment. - /// |] - class Class1 - { - } -}"; - await TestMissingInRegularAndScriptAsync(code); - } - - [Fact] - public async Task MoveType_NotAvailableAroundAttributeAboveHeader() - { - var code = -@"using System; -namespace N1 -{ - [|[Obsolete]|] - class Class1 - { - } -}"; - await TestMissingInRegularAndScriptAsync(code); - } - - [Fact] - public async Task MoveType_NotAvailableAroundDocumentationCommentAndAttributeAboveHeader() - { - var code = -@"using System; -namespace N1 -{ - [|/// - /// Documentation comment. - /// - [Obsolete]|] - class Class1 - { - } -}"; - await TestMissingInRegularAndScriptAsync(code); - } - - [Fact] - public async Task MoveType_NotAvailableInsideDocumentationCommentAndAttributeAboveHeader() - { - var code = -@"using System; -namespace N1 -{ - /// - /// [|Documentation comment. - /// - [Obso|]lete] - class Class1 - { - } -}"; - await TestMissingInRegularAndScriptAsync(code); - } - - [Fact] - public async Task MoveType_ActionCounts_MoveOnly() - { - var code = -@"namespace N1 -{ - class Class1[||] - { - } - - class test1 /* this matches file name assigned by TestWorkspace*/ - { - } -}"; - // Fixes offered will be move type to new file. - await TestActionCountAsync(code, count: 1); - } - - [Fact] - public async Task MoveType_ActionCounts_RenameAndMove() - { - var code = -@"namespace N1 -{ - class Class1[||] - { - } - - class Class2 - { - } -}"; - // Fixes offered will be move type, rename type to match file, rename file to match type. - await TestActionCountAsync(code, count: 3); - } - - [Fact] - public async Task MoveType_ActionCounts_All() - { - var code = -@"namespace N1 -{ - class OuterType - { - class InnerType[||] - { - } - } - - class Class1 - { - } -}"; - // Fixes offered will be - // 1. move type to InnerType.cs - // 2. move type to OuterType.InnerType.cs - // 3. rename file to InnerType.cs - // 4. rename file to OuterType.InnerType.cs - // 5. rename type to test1 (which is the default document name given by TestWorkspace). - await TestActionCountAsync(code, count: 5); - } + public Task MoveType_ActionCounts_RenameOnly() + => TestActionCountAsync(""" + namespace N1 + { + class Class1[||] + { + } + } + """, count: 2); + + [Fact] + public Task MoveType_AvailableBeforeHeader() + => TestActionCountAsync(""" + namespace N1 + { + [||] + class Class1 + { + } + } + """, count: 2); + + [Fact] + public Task MoveType_AvailableBeforeAttributeOnHeader() + => TestActionCountAsync(""" + namespace N1 + { + [||][X] + class Class1 + { + } + } + """, count: 2); + + [Fact] + public Task MoveType_AvailableOnHeaderIncludingWhitespaceAndAttribute() + => TestActionCountAsync(""" + namespace N1 + {[| + [X] + class Class1 + {|] + } + } + """, count: 2); + + [Fact] + public Task MoveType_AvailableAfterHeader() + => TestActionCountAsync(""" + namespace N1 + { + class Class1 + [||]{ + } + } + """, count: 2); + + [Fact] + public Task MoveType_AvailableIncludingDocumentationCommentAndHeader() + => TestActionCountAsync(""" + namespace N1 + { + [|/// + /// Documentation comment. + /// + class Class1|] + { + } + } + """, count: 2); + + [Fact] + public Task MoveType_AvailableIncludingDocumentationCommentAndAttributeAndHeader() + => TestActionCountAsync(""" + using System; + namespace N1 + { + [|/// + /// Documentation comment. + /// + [Obsolete] + class Class1|] + { + } + } + """, count: 2); + + [Fact] + public Task MoveType_NotAvailableBeforeType() + => TestMissingInRegularAndScriptAsync(""" + [|namespace N1 + {|] + class Class1 + { + } + } + """); + + [Fact] + public Task MoveType_NotAvailableInsideType() + => TestMissingInRegularAndScriptAsync(""" + namespace N1 + { + class Class1 + {[| + void M() + { + }|] + } + } + """); + + [Fact] + public Task MoveType_NotAvailableAfterType() + => TestMissingInRegularAndScriptAsync(""" + namespace N1 + { + class Class1 + { + void M() + { + } + } + + [|class test1|] + { + } + } + """); + + [Fact] + public Task MoveType_NotAvailableAroundDocumentationCommentAboveHeader() + => TestMissingInRegularAndScriptAsync(""" + namespace N1 + { + [|/// + /// Documentation comment. + /// |] + class Class1 + { + } + } + """); + + [Fact] + public Task MoveType_NotAvailableAroundAttributeAboveHeader() + => TestMissingInRegularAndScriptAsync(""" + using System; + namespace N1 + { + [|[Obsolete]|] + class Class1 + { + } + } + """); + + [Fact] + public Task MoveType_NotAvailableAroundDocumentationCommentAndAttributeAboveHeader() + => TestMissingInRegularAndScriptAsync(""" + using System; + namespace N1 + { + [|/// + /// Documentation comment. + /// + [Obsolete]|] + class Class1 + { + } + } + """); + + [Fact] + public Task MoveType_NotAvailableInsideDocumentationCommentAndAttributeAboveHeader() + => TestMissingInRegularAndScriptAsync(""" + using System; + namespace N1 + { + /// + /// [|Documentation comment. + /// + [Obso|]lete] + class Class1 + { + } + } + """); + + [Fact] + public Task MoveType_ActionCounts_MoveOnly() + => TestActionCountAsync(""" + namespace N1 + { + class Class1[||] + { + } + + class test1 /* this matches file name assigned by TestWorkspace*/ + { + } + } + """, count: 1); + + [Fact] + public Task MoveType_ActionCounts_RenameAndMove() + => TestActionCountAsync(""" + namespace N1 + { + class Class1[||] + { + } + + class Class2 + { + } + } + """, count: 3); + + [Fact] + public Task MoveType_ActionCounts_All() + => TestActionCountAsync(""" + namespace N1 + { + class OuterType + { + class InnerType[||] + { + } + } + + class Class1 + { + } + } + """, count: 5); } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.MoveScope.cs b/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.MoveScope.cs index 6f6d30a1ece97..0f2d0407493ac 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.MoveScope.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.MoveScope.cs @@ -21,893 +21,859 @@ public partial class MoveTypeTests : CSharpMoveTypeTestsBase [Fact] public Task MoveType_NamespaceScope_SingleItem() { - var code = -@"namespace N1 -{ - class [||]Class1 - { - } -}"; - - var expected = -@"namespace N1 -{ - class Class1 - { - } -}"; - - return TestNamespaceMove(code, expected, expectOperation: false); + return TestNamespaceMove(""" + namespace N1 + { + class [||]Class1 + { + } + } + """, """ + namespace N1 + { + class Class1 + { + } + } + """, expectOperation: false); } [Fact] public Task MoveType_NamespaceScope_SingleItemNamespaceComment() { - var code = -@"// Comment on the namespace -namespace N1 -{ - class [||]Class1 - { - } -}"; - - var expected = -@"// Comment on the namespace -namespace N1 -{ - class Class1 - { - } -}"; - - return TestNamespaceMove(code, expected, expectOperation: false); + return TestNamespaceMove(""" + // Comment on the namespace + namespace N1 + { + class [||]Class1 + { + } + } + """, """ + // Comment on the namespace + namespace N1 + { + class Class1 + { + } + } + """, expectOperation: false); } [Fact] public Task MoveType_NamespaceScope_ItemAtTop() { - var code = -@"namespace N1 -{ - class [||]Class1 - { - } - - class Class2 - { - } -}"; - - var expected = -@"namespace N1 -{ - class Class1 - { - } -} - -namespace N1 -{ - class Class2 - { - } -}"; - - return TestNamespaceMove(code, expected); + return TestNamespaceMove(""" + namespace N1 + { + class [||]Class1 + { + } + + class Class2 + { + } + } + """, """ + namespace N1 + { + class Class1 + { + } + } + + namespace N1 + { + class Class2 + { + } + } + """); } [Fact] public Task MoveType_NamespaceScope_ItemAtTopNamespaceComment() { - var code = -@"// Comment on the namespace -namespace N1 -{ - class [||]Class1 - { - } - - class Class2 - { - } -}"; - - var expected = -@"// Comment on the namespace -namespace N1 -{ - class Class1 - { - } -} - -namespace N1 -{ - class Class2 - { - } -}"; - - return TestNamespaceMove(code, expected); + return TestNamespaceMove(""" + // Comment on the namespace + namespace N1 + { + class [||]Class1 + { + } + + class Class2 + { + } + } + """, """ + // Comment on the namespace + namespace N1 + { + class Class1 + { + } + } + + namespace N1 + { + class Class2 + { + } + } + """); } [Fact] public Task MoveType_NamespaceScope_ItemAtTopWithComments() { - var code = -@"namespace N1 -{ - // Class1 Comment - class [||]Class1 - { - } - - // Class2 Comment - class Class2 - { - } -}"; - - var expected = -@"namespace N1 -{ - // Class1 Comment - class Class1 - { - } -} - -namespace N1 -{ - // Class2 Comment - class Class2 - { - } -}"; - - return TestNamespaceMove(code, expected); + return TestNamespaceMove(""" + namespace N1 + { + // Class1 Comment + class [||]Class1 + { + } + + // Class2 Comment + class Class2 + { + } + } + """, """ + namespace N1 + { + // Class1 Comment + class Class1 + { + } + } + + namespace N1 + { + // Class2 Comment + class Class2 + { + } + } + """); } [Fact] public Task MoveType_NamespaceScope_ItemAtTopWithXmlComments() { - var code = -@"namespace N1 -{ - /// - /// Class1 summary - /// - class [||]Class1 - { - } - - /// - /// Class2 summary - /// - class Class2 - { - } -}"; - - var expected = -@"namespace N1 -{ - /// - /// Class1 summary - /// - class Class1 - { - } -} - -namespace N1 -{ - /// - /// Class2 summary - /// - class Class2 - { - } -}"; - - return TestNamespaceMove(code, expected); + return TestNamespaceMove(""" + namespace N1 + { + /// + /// Class1 summary + /// + class [||]Class1 + { + } + + /// + /// Class2 summary + /// + class Class2 + { + } + } + """, """ + namespace N1 + { + /// + /// Class1 summary + /// + class Class1 + { + } + } + + namespace N1 + { + /// + /// Class2 summary + /// + class Class2 + { + } + } + """); } [Fact] public Task MoveType_NamespaceScope_ItemAtBottom() { - var code = -@"namespace N1 -{ - class Class1 - { - } - - class [||]Class2 - { - } -}"; - - var expected = -@"namespace N1 -{ - class Class1 - { - } -} - -namespace N1 -{ - class Class2 - { - } -}"; - - return TestNamespaceMove(code, expected); + return TestNamespaceMove(""" + namespace N1 + { + class Class1 + { + } + + class [||]Class2 + { + } + } + """, """ + namespace N1 + { + class Class1 + { + } + } + + namespace N1 + { + class Class2 + { + } + } + """); } [Fact] public Task MoveType_NamespaceScope_ItemAtBottomNamespaceComments() { - var code = -@"// Comment on the namespace -namespace N1 -{ - class Class1 - { - } - - class [||]Class2 - { - } -}"; - - var expected = -@"// Comment on the namespace -namespace N1 -{ - class Class1 - { - } -} - -namespace N1 -{ - class Class2 - { - } -}"; - - return TestNamespaceMove(code, expected); + return TestNamespaceMove(""" + // Comment on the namespace + namespace N1 + { + class Class1 + { + } + + class [||]Class2 + { + } + } + """, """ + // Comment on the namespace + namespace N1 + { + class Class1 + { + } + } + + namespace N1 + { + class Class2 + { + } + } + """); } [Fact] public Task MoveType_NamespaceScope_ItemAtBottomWithComments() { - var code = -@"namespace N1 -{ - // Class1 comment - class Class1 - { - } - - // Class2 comment - class [||]Class2 - { - } -}"; - - var expected = -@"namespace N1 -{ - // Class1 comment - class Class1 - { - } -} - -namespace N1 -{ - // Class2 comment - class Class2 - { - } -}"; - - return TestNamespaceMove(code, expected); + return TestNamespaceMove(""" + namespace N1 + { + // Class1 comment + class Class1 + { + } + + // Class2 comment + class [||]Class2 + { + } + } + """, """ + namespace N1 + { + // Class1 comment + class Class1 + { + } + } + + namespace N1 + { + // Class2 comment + class Class2 + { + } + } + """); } [Fact] public Task MoveType_NamespaceScope_ItemAtBottomWithXmlComments() { - var code = -@"namespace N1 -{ - /// - /// Class1 summary - /// - class Class1 - { - } - - /// - /// Class2 summary - /// - class [||]Class2 - { - } -}"; - - var expected = -@"namespace N1 -{ - /// - /// Class1 summary - /// - class Class1 - { - } -} - -namespace N1 -{ - /// - /// Class2 summary - /// - class Class2 - { - } -}"; - - return TestNamespaceMove(code, expected); + return TestNamespaceMove(""" + namespace N1 + { + /// + /// Class1 summary + /// + class Class1 + { + } + + /// + /// Class2 summary + /// + class [||]Class2 + { + } + } + """, """ + namespace N1 + { + /// + /// Class1 summary + /// + class Class1 + { + } + } + + namespace N1 + { + /// + /// Class2 summary + /// + class Class2 + { + } + } + """); } [Fact] public Task MoveType_NamespaceScope_ItemInMiddle() { - var code = -@"namespace N1 -{ - class Class1 - { - } - - class Class2 - { - } - - class [||]Class3 - { - } - - class Class4 - { - } - - class Class5 - { - } -}"; - - var expected = -@"namespace N1 -{ - class Class1 - { - } - - class Class2 - { - } -} - -namespace N1 -{ - class Class3 - { - } -} - -namespace N1 -{ - class Class4 - { - } - - class Class5 - { - } -}"; - - return TestNamespaceMove(code, expected); + return TestNamespaceMove(""" + namespace N1 + { + class Class1 + { + } + + class Class2 + { + } + + class [||]Class3 + { + } + + class Class4 + { + } + + class Class5 + { + } + } + """, """ + namespace N1 + { + class Class1 + { + } + + class Class2 + { + } + } + + namespace N1 + { + class Class3 + { + } + } + + namespace N1 + { + class Class4 + { + } + + class Class5 + { + } + } + """); } [Fact] public Task MoveType_NamespaceScope_ItemInMiddleNamespaceComment() { - var code = -@"// Comment on the namespace -namespace N1 -{ - class Class1 - { - } - - class Class2 - { - } - - class [||]Class3 - { - } - - class Class4 - { - } - - class Class5 - { - } -}"; - - var expected = -@"// Comment on the namespace -namespace N1 -{ - class Class1 - { - } - - class Class2 - { - } -} - -namespace N1 -{ - class Class3 - { - } -} - -namespace N1 -{ - class Class4 - { - } - - class Class5 - { - } -}"; - - return TestNamespaceMove(code, expected); + return TestNamespaceMove(""" + // Comment on the namespace + namespace N1 + { + class Class1 + { + } + + class Class2 + { + } + + class [||]Class3 + { + } + + class Class4 + { + } + + class Class5 + { + } + } + """, """ + // Comment on the namespace + namespace N1 + { + class Class1 + { + } + + class Class2 + { + } + } + + namespace N1 + { + class Class3 + { + } + } + + namespace N1 + { + class Class4 + { + } + + class Class5 + { + } + } + """); } [Fact] public Task MoveType_NamespaceScope_ItemInMiddleWithComments() { - var code = -@"namespace N1 -{ - // Class1 comment - class Class1 - { - } - - // Class2 comment - class Class2 - { - } - - // Class3 comment - class [||]Class3 - { - } - - // Class4 comment - class Class4 - { - } - - // Class5 comment - class Class5 - { - } -}"; - - var expected = -@"namespace N1 -{ - // Class1 comment - class Class1 - { - } - - // Class2 comment - class Class2 - { - } -} - -namespace N1 -{ - // Class3 comment - class Class3 - { - } -} - -namespace N1 -{ - // Class4 comment - class Class4 - { - } - - // Class5 comment - class Class5 - { - } -}"; - - return TestNamespaceMove(code, expected); + return TestNamespaceMove(""" + namespace N1 + { + // Class1 comment + class Class1 + { + } + + // Class2 comment + class Class2 + { + } + + // Class3 comment + class [||]Class3 + { + } + + // Class4 comment + class Class4 + { + } + + // Class5 comment + class Class5 + { + } + } + """, """ + namespace N1 + { + // Class1 comment + class Class1 + { + } + + // Class2 comment + class Class2 + { + } + } + + namespace N1 + { + // Class3 comment + class Class3 + { + } + } + + namespace N1 + { + // Class4 comment + class Class4 + { + } + + // Class5 comment + class Class5 + { + } + } + """); } [Fact] public Task MoveType_NamespaceScope_ItemInMiddleWithXmlComments() { - var code = -@"namespace N1 -{ - /// - /// Class1 summary - /// - class Class1 - { - } - - /// - /// Class2 summary - /// - class Class2 - { - } - - /// - /// Class3 summary - /// - class [||]Class3 - { - } - - /// - /// Class4 summary - /// - class Class4 - { - } - - /// - /// Class5 summary - /// - class Class5 - { - } -}"; - - var expected = -@"namespace N1 -{ - /// - /// Class1 summary - /// - class Class1 - { - } - - /// - /// Class2 summary - /// - class Class2 - { - } -} - -namespace N1 -{ - /// - /// Class3 summary - /// - class Class3 - { - } -} - -namespace N1 -{ - /// - /// Class4 summary - /// - class Class4 - { - } - - /// - /// Class5 summary - /// - class Class5 - { - } -}"; - - return TestNamespaceMove(code, expected); + return TestNamespaceMove(""" + namespace N1 + { + /// + /// Class1 summary + /// + class Class1 + { + } + + /// + /// Class2 summary + /// + class Class2 + { + } + + /// + /// Class3 summary + /// + class [||]Class3 + { + } + + /// + /// Class4 summary + /// + class Class4 + { + } + + /// + /// Class5 summary + /// + class Class5 + { + } + } + """, """ + namespace N1 + { + /// + /// Class1 summary + /// + class Class1 + { + } + + /// + /// Class2 summary + /// + class Class2 + { + } + } + + namespace N1 + { + /// + /// Class3 summary + /// + class Class3 + { + } + } + + namespace N1 + { + /// + /// Class4 summary + /// + class Class4 + { + } + + /// + /// Class5 summary + /// + class Class5 + { + } + } + """); } [Fact] public Task MoveType_NamespaceScope_ItemInMiddleWithInterface() { - var code = -@"namespace N1 -{ - // Class1 comment - class Class1 - { - } - - // IClass3 comment - interface IClass3 - { - void DoStuff(); - } - - // Class3 comment - class [||]Class3 : IClass3 - { - public void DoStuff() { } - } - - // Class4 comment - class Class4 - { - } - - // Class5 comment - class Class5 - { - } -}"; - - var expected = -@"namespace N1 -{ - // Class1 comment - class Class1 - { - } - - // IClass3 comment - interface IClass3 - { - void DoStuff(); - } -} - -namespace N1 -{ - // Class3 comment - class Class3 : IClass3 - { - public void DoStuff() { } - } -} - -namespace N1 -{ - // Class4 comment - class Class4 - { - } - - // Class5 comment - class Class5 - { - } -}"; - - return TestNamespaceMove(code, expected); + return TestNamespaceMove(""" + namespace N1 + { + // Class1 comment + class Class1 + { + } + + // IClass3 comment + interface IClass3 + { + void DoStuff(); + } + + // Class3 comment + class [||]Class3 : IClass3 + { + public void DoStuff() { } + } + + // Class4 comment + class Class4 + { + } + + // Class5 comment + class Class5 + { + } + } + """, """ + namespace N1 + { + // Class1 comment + class Class1 + { + } + + // IClass3 comment + interface IClass3 + { + void DoStuff(); + } + } + + namespace N1 + { + // Class3 comment + class Class3 : IClass3 + { + public void DoStuff() { } + } + } + + namespace N1 + { + // Class4 comment + class Class4 + { + } + + // Class5 comment + class Class5 + { + } + } + """); } [Fact] public Task MoveType_NamespaceScope_TwoItemsInDifferentNamespace() { - var code = -@"namespace N1 -{ - class [||]Class1 - { - } -} - -namespace N2 -{ - class Class2 - { - } -}"; - - var expected = -@"namespace N1 -{ - class Class1 - { - } -} - -namespace N2 -{ - class Class2 - { - } -}"; - - return TestNamespaceMove(code, expected, expectOperation: false); + return TestNamespaceMove(""" + namespace N1 + { + class [||]Class1 + { + } + } + + namespace N2 + { + class Class2 + { + } + } + """, """ + namespace N1 + { + class Class1 + { + } + } + + namespace N2 + { + class Class2 + { + } + } + """, expectOperation: false); } [Fact] public Task MoveType_NamespaceScope_ItemsInDifferentNamespace() { - var code = -@"namespace N1 -{ - interface IClass1 - { - } - - class [||]Class1 : IClass1 - { - } -} - -namespace N2 -{ - class Class2 - { - } -}"; - - var expected = -@"namespace N1 -{ - interface IClass1 - { - } -} - -namespace N1 -{ - class Class1 : IClass1 - { - } -} - -namespace N2 -{ - class Class2 - { - } -}"; - - return TestNamespaceMove(code, expected); + return TestNamespaceMove(""" + namespace N1 + { + interface IClass1 + { + } + + class [||]Class1 : IClass1 + { + } + } + + namespace N2 + { + class Class2 + { + } + } + """, """ + namespace N1 + { + interface IClass1 + { + } + } + + namespace N1 + { + class Class1 : IClass1 + { + } + } + + namespace N2 + { + class Class2 + { + } + } + """); } [Fact] public Task MoveType_NamespaceScope_NestedNamespaces() { - var code = -@"namespace N1 -{ - namespace N2 - { - class [||]C1 - { - } - - class C2 - { - } - } - - class C3 - { - } -}"; - var expected = -@"namespace N1 -{ - namespace N1.N2 - { - class C1 - { - } - } - - namespace N2 - { - class C2 - { - } - } - - class C3 - { - } -}"; - return TestNamespaceMove(code, expected); + return TestNamespaceMove(""" + namespace N1 + { + namespace N2 + { + class [||]C1 + { + } + + class C2 + { + } + } + + class C3 + { + } + } + """, """ + namespace N1 + { + namespace N1.N2 + { + class C1 + { + } + } + + namespace N2 + { + class C2 + { + } + } + + class C3 + { + } + } + """); } [Fact] public Task MoveType_NamespaceScope_NestedNamespaces2() { - var code = -@"namespace N1 -{ - namespace N2 - { - class C1 - { - } - - class C2 - { - } - } - - class [||]C3 - { - } - - namespace N3 - { - class C4 - { - } - } -}"; - var expected = -@"namespace N1 -{ - namespace N2 - { - class C1 - { - } - - class C2 - { - } - } -} - -namespace N1 -{ - class C3 - { - } -} - -namespace N1 -{ - namespace N3 - { - class C4 - { - } - } -}"; - return TestNamespaceMove(code, expected); + return TestNamespaceMove(""" + namespace N1 + { + namespace N2 + { + class C1 + { + } + + class C2 + { + } + } + + class [||]C3 + { + } + + namespace N3 + { + class C4 + { + } + } + } + """, """ + namespace N1 + { + namespace N2 + { + class C1 + { + } + + class C2 + { + } + } + } + + namespace N1 + { + class C3 + { + } + } + + namespace N1 + { + namespace N3 + { + class C4 + { + } + } + } + """); } private async Task TestNamespaceMove(string originalCode, string expectedCode, bool expectOperation = true) diff --git a/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.MoveToNewFile.cs b/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.MoveToNewFile.cs index 1fd02d76caab3..f701949fdf8a4 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.MoveToNewFile.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.MoveToNewFile.cs @@ -14,72 +14,42 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.MoveType; public sealed partial class MoveTypeTests : CSharpMoveTypeTestsBase { [WpfFact] - public async Task TestMissing_OnMatchingFileName() - { - var code = - @"[||]class test1 { }"; - - await TestMissingInRegularAndScriptAsync(code); - } + public Task TestMissing_OnMatchingFileName() + => TestMissingInRegularAndScriptAsync(@"[||]class test1 { }"); [WpfFact] - public async Task TestMissing_Nested_OnMatchingFileName_Simple() - { - var code = - """ + public Task TestMissing_Nested_OnMatchingFileName_Simple() + => TestMissingInRegularAndScriptAsync(""" class outer { [||]class test1 { } } - """; - - await TestMissingInRegularAndScriptAsync(code); - } + """); [WpfFact] - public async Task TestMatchingFileName_CaseSensitive() - { - var code = - @"[||]class Test1 { }"; - - await TestActionCountAsync(code, count: 2); - } + public Task TestMatchingFileName_CaseSensitive() + => TestActionCountAsync(@"[||]class Test1 { }", count: 2); [WpfFact] - public async Task TestForSpans1() - { - var code = - """ + public Task TestForSpans1() + => TestActionCountAsync(""" [|clas|]s Class1 { } class Class2 { } - """; - - await TestActionCountAsync(code, count: 3); - } + """, count: 3); [WpfFact] - public async Task TestForSpans2() - { - var code = - """ + public Task TestForSpans2() + => TestMoveTypeToNewFileAsync(""" [||]class Class1 { } class Class2 { } - """; - var codeAfterMove = @"class Class2 { }"; - - var expectedDocumentName = "Class1.cs"; - var destinationDocumentText = """ + """, @"class Class2 { }", "Class1.cs", """ class Class1 { } - """; - - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/14008")] - public async Task TestMoveToNewFileWithFolders() - { - var code = + public Task TestMoveToNewFileWithFolders() + => TestMoveTypeToNewFileAsync( """ @@ -90,108 +60,63 @@ class Class2 { } - """; - var codeAfterMove = """ + """, """ class Class2 { } - """; - - var expectedDocumentName = "Class1.cs"; - var destinationDocumentText = """ + """, "Class1.cs", + """ class Class1 { } - """; - - await TestMoveTypeToNewFileAsync( - code, codeAfterMove, expectedDocumentName, - destinationDocumentText, destinationDocumentContainers: ["A", "B"]); - } + """, destinationDocumentContainers: ["A", "B"]); [WpfFact] - public async Task TestForSpans3() - { - var code = - """ + public Task TestForSpans3() + => TestActionCountAsync(""" [|class Class1|] { } class Class2 { } - """; - - await TestActionCountAsync(code, count: 3); - } + """, count: 3); [WpfFact] - public async Task TestForSpans4() - { - var code = - """ + public Task TestForSpans4() + => TestMoveTypeToNewFileAsync(""" class Class1[||] { } class Class2 { } - """; - var codeAfterMove = @"class Class2 { }"; - - var expectedDocumentName = "Class1.cs"; - var destinationDocumentText = """ + """, @"class Class2 { }", "Class1.cs", """ class Class1 { } - """; - - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact] - public async Task MoveTypeWithNoContainerNamespace() - { - var code = - """ + public Task MoveTypeWithNoContainerNamespace() + => TestMoveTypeToNewFileAsync(""" [||]class Class1 { } class Class2 { } - """; - var codeAfterMove = @"class Class2 { }"; - - var expectedDocumentName = "Class1.cs"; - var destinationDocumentText = """ + """, @"class Class2 { }", "Class1.cs", """ class Class1 { } - """; - - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact] - public async Task MoveTypeWithWithUsingsAndNoContainerNamespace() - { - var code = - """ + public Task MoveTypeWithWithUsingsAndNoContainerNamespace() + => TestMoveTypeToNewFileAsync(""" // Banner Text using System; [||]class Class1 { } class Class2 { } - """; - - var codeAfterMove = - """ + """, """ // Banner Text using System; class Class2 { } - """; - - var expectedDocumentName = "Class1.cs"; - var destinationDocumentText = - """ + """, "Class1.cs", """ // Banner Text class Class1 { } - """; - - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact] - public async Task MoveTypeWithWithMembers() - { - var code = - """ + public Task MoveTypeWithWithMembers() + => TestMoveTypeToNewFileAsync(""" // Banner Text using System; @@ -203,17 +128,10 @@ void Print(int x) } } class Class2 { } - """; - - var codeAfterMove = - """ + """, """ // Banner Text class Class2 { } - """; - - var expectedDocumentName = "Class1.cs"; - var destinationDocumentText = - """ + """, "Class1.cs", """ // Banner Text using System; @@ -225,16 +143,11 @@ void Print(int x) } } - """; - - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact] - public async Task MoveTypeWithWithMembers2() - { - var code = - """ + public Task MoveTypeWithWithMembers2() + => TestMoveTypeToNewFileAsync(""" // Banner Text using System; @@ -253,10 +166,7 @@ void Print(int x) Console.WriteLine(x); } } - """; - - var codeAfterMove = - """ + """, """ // Banner Text using System; @@ -267,11 +177,7 @@ void Print(int x) Console.WriteLine(x); } } - """; - - var expectedDocumentName = "Class1.cs"; - var destinationDocumentText = - """ + """, "Class1.cs", """ // Banner Text using System; @@ -283,136 +189,80 @@ void Print(int x) } } - """; - - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact] - public async Task MoveAnInterface() - { - var code = - """ + public Task MoveAnInterface() + => TestMoveTypeToNewFileAsync(""" [||]interface IMoveType { } class Class2 { } - """; - var codeAfterMove = @"class Class2 { }"; - - var expectedDocumentName = "IMoveType.cs"; - var destinationDocumentText = """ + """, @"class Class2 { }", "IMoveType.cs", """ interface IMoveType { } - """; - - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact] - public async Task MoveAStruct() - { - var code = - """ + public Task MoveAStruct() + => TestMoveTypeToNewFileAsync(""" [||]struct MyStruct { } class Class2 { } - """; - var codeAfterMove = @"class Class2 { }"; - - var expectedDocumentName = "MyStruct.cs"; - var destinationDocumentText = """ + """, @"class Class2 { }", "MyStruct.cs", """ struct MyStruct { } - """; - - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact] - public async Task MoveAnEnum() - { - var code = - """ + public Task MoveAnEnum() + => TestMoveTypeToNewFileAsync(""" [||]enum MyEnum { } class Class2 { } - """; - var codeAfterMove = @"class Class2 { }"; - - var expectedDocumentName = "MyEnum.cs"; - var destinationDocumentText = """ + """, @"class Class2 { }", "MyEnum.cs", """ enum MyEnum { } - """; - - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact] - public async Task MoveTypeWithWithContainerNamespace() - { - var code = - """ + public Task MoveTypeWithWithContainerNamespace() + => TestMoveTypeToNewFileAsync(""" namespace N1 { [||]class Class1 { } class Class2 { } } - """; - - var codeAfterMove = - """ + """, """ namespace N1 { class Class2 { } } - """; - - var expectedDocumentName = "Class1.cs"; - - var destinationDocumentText = - """ + """, "Class1.cs", """ namespace N1 { class Class1 { } } - """; - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact] - public async Task MoveTypeWithWithFileScopedNamespace() - { - var code = - """ + public Task MoveTypeWithWithFileScopedNamespace() + => TestMoveTypeToNewFileAsync(""" namespace N1; [||]class Class1 { } class Class2 { } - """; - - var codeAfterMove = - """ + """, """ namespace N1; class Class2 { } - """; - - var expectedDocumentName = "Class1.cs"; - - var destinationDocumentText = - """ + """, "Class1.cs", """ namespace N1; class Class1 { } - """; - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact] - public async Task MoveNestedTypeToNewFile_Simple() - { - var code = - """ + public Task MoveNestedTypeToNewFile_Simple() + => TestMoveTypeToNewFileAsync(""" namespace N1 { class Class1 @@ -421,10 +271,7 @@ class Class1 } } - """; - - var codeAfterMove = - """ + """, """ namespace N1 { partial class Class1 @@ -432,12 +279,7 @@ partial class Class1 } } - """; - - var expectedDocumentName = "Class2.cs"; - - var destinationDocumentText = - """ + """, "Class2.cs", """ namespace N1 { partial class Class1 @@ -446,15 +288,11 @@ class Class2 { } } } - """; - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact] - public async Task MoveNestedTypePreserveModifiers() - { - var code = - """ + public Task MoveNestedTypePreserveModifiers() + => TestMoveTypeToNewFileAsync(""" namespace N1 { abstract class Class1 @@ -463,10 +301,7 @@ abstract class Class1 } } - """; - - var codeAfterMove = - """ + """, """ namespace N1 { abstract partial class Class1 @@ -474,12 +309,7 @@ abstract partial class Class1 } } - """; - - var expectedDocumentName = "Class2.cs"; - - var destinationDocumentText = - """ + """, "Class2.cs", """ namespace N1 { abstract partial class Class1 @@ -488,15 +318,11 @@ class Class2 { } } } - """; - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/14004")] - public async Task MoveNestedTypeToNewFile_Attributes1() - { - var code = - """ + public Task MoveNestedTypeToNewFile_Attributes1() + => TestMoveTypeToNewFileAsync(""" namespace N1 { [Outer] @@ -507,10 +333,7 @@ class Class1 } } - """; - - var codeAfterMove = - """ + """, """ namespace N1 { [Outer] @@ -519,12 +342,7 @@ partial class Class1 } } - """; - - var expectedDocumentName = "Class2.cs"; - - var destinationDocumentText = - """ + """, "Class2.cs", """ namespace N1 { partial class Class1 @@ -534,14 +352,11 @@ class Class2 { } } } - """; - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/14484")] - public async Task MoveNestedTypeToNewFile_Comments1() - { - var code = + public Task MoveNestedTypeToNewFile_Comments1() + => TestMoveTypeToNewFileAsync( """ namespace N1 { @@ -554,10 +369,7 @@ class Class1 } } } - """; - - var codeAfterMove = - """ + """, """ namespace N1 { /// Outer doc comment. @@ -565,12 +377,7 @@ partial class Class1 { } } - """; - - var expectedDocumentName = "Class2.cs"; - - var destinationDocumentText = - """ + """, "Class2.cs", """ namespace N1 { partial class Class1 @@ -581,16 +388,11 @@ class Class2 } } } - """; - await TestMoveTypeToNewFileAsync( - code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact] - public async Task MoveNestedTypeToNewFile_Simple_DottedName() - { - var code = - """ + public Task MoveNestedTypeToNewFile_Simple_DottedName() + => TestMoveTypeToNewFileAsync(""" namespace N1 { class Class1 @@ -599,10 +401,7 @@ class Class1 } } - """; - - var codeAfterMove = - """ + """, """ namespace N1 { partial class Class1 @@ -610,12 +409,7 @@ partial class Class1 } } - """; - - var expectedDocumentName = "Class1.Class2.cs"; - - var destinationDocumentText = - """ + """, "Class1.Class2.cs", """ namespace N1 { partial class Class1 @@ -624,49 +418,33 @@ class Class2 { } } } - """; - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText, index: 1); - } + """, index: 1); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/72632")] - public async Task MoveNestedTypeToNewFile_Simple_DottedName_WithPrimaryConstructor() - { - var code = - """ + public Task MoveNestedTypeToNewFile_Simple_DottedName_WithPrimaryConstructor() + => TestMoveTypeToNewFileAsync(""" internal class Outer() { private class Inner[||] { } } - """; - - var codeAfterMove = - """ + """, """ internal partial class Outer() { } - """; - - var expectedDocumentName = "Outer.Inner.cs"; - - var destinationDocumentText = - """ + """, "Outer.Inner.cs", """ internal partial class Outer { private class Inner { } } - """; - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText, index: 1); - } + """, index: 1); [WpfFact] - public async Task MoveNestedTypeToNewFile_ParentHasOtherMembers() - { - var code = - """ + public Task MoveNestedTypeToNewFile_ParentHasOtherMembers() + => TestMoveTypeToNewFileAsync(""" namespace N1 { class Class1 @@ -679,10 +457,7 @@ public void Method1() { } } } - """; - - var codeAfterMove = - """ + """, """ namespace N1 { partial class Class1 @@ -693,12 +468,7 @@ public void Method1() { } } } - """; - - var expectedDocumentName = "Class2.cs"; - - var destinationDocumentText = - """ + """, "Class2.cs", """ namespace N1 { partial class Class1 @@ -707,15 +477,11 @@ class Class2 { } } } - """; - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact] - public async Task MoveNestedTypeToNewFile_HasOtherTopLevelMembers() - { - var code = - """ + public Task MoveNestedTypeToNewFile_HasOtherTopLevelMembers() + => TestMoveTypeToNewFileAsync(""" namespace N1 { class Class1 @@ -732,10 +498,7 @@ internal class Class3 private void Method1() { } } } - """; - - var codeAfterMove = - """ + """, """ namespace N1 { partial class Class1 @@ -750,12 +513,7 @@ internal class Class3 private void Method1() { } } } - """; - - var expectedDocumentName = "Class2.cs"; - - var destinationDocumentText = - """ + """, "Class2.cs", """ namespace N1 { partial class Class1 @@ -763,15 +521,11 @@ partial class Class1 class Class2 { } } } - """; - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact] - public async Task MoveNestedTypeToNewFile_HasMembers() - { - var code = - """ + public Task MoveNestedTypeToNewFile_HasMembers() + => TestMoveTypeToNewFileAsync(""" namespace N1 { class Class1 @@ -787,10 +541,7 @@ public void InnerMethod() { } public void Method1() { } } } - """; - - var codeAfterMove = - """ + """, """ namespace N1 { partial class Class1 @@ -800,12 +551,7 @@ partial class Class1 public void Method1() { } } } - """; - - var expectedDocumentName = "Class2.cs"; - - var destinationDocumentText = - """ + """, "Class2.cs", """ namespace N1 { partial class Class1 @@ -817,15 +563,11 @@ public void InnerMethod() { } } } } - """; - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/13969")] - public async Task MoveTypeInFileWithComplexHierarchy() - { - var code = - """ + public Task MoveTypeInFileWithComplexHierarchy() + => TestMoveTypeToNewFileAsync(""" namespace OuterN1.N1 { namespace InnerN2.N2 @@ -871,10 +613,7 @@ class InnerClass6 { } } - """; - - var codeAfterMove = - """ + """, """ namespace OuterN1.N1 { namespace InnerN2.N2 @@ -914,12 +653,7 @@ class InnerClass6 { } } - """; - - var expectedDocumentName = "InnerClass2.cs"; - - var destinationDocumentText = - """ + """, "InnerClass2.cs", """ namespace OuterN1.N1 { @@ -937,15 +671,11 @@ class InnerClass3 } } - """; - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact] - public async Task MoveTypeUsings1() - { - var code = - """ + public Task MoveTypeUsings1() + => TestMoveTypeToNewFileAsync(""" // Only used by inner type. using System; @@ -958,8 +688,7 @@ class Outer { DateTime d; } } - """; - var codeAfterMove = """ + """, """ // Only used by inner type. @@ -968,11 +697,7 @@ class Outer { partial class Outer { } - """; - - var expectedDocumentName = "Inner.cs"; - var destinationDocumentText = - """ + """, "Inner.cs", """ // Only used by inner type. using System; @@ -984,15 +709,11 @@ class Inner { DateTime d; } } - """; - - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/16283")] - public async Task TestLeadingTrivia1() - { - var code = + public Task TestLeadingTrivia1() + => TestMoveTypeToNewFileAsync( """ class Outer @@ -1005,8 +726,7 @@ class Inner1 { } } - """; - var codeAfterMove = """ + """, """ partial class Outer { @@ -1014,10 +734,7 @@ class Inner1 { } } - """; - - var expectedDocumentName = "Inner2.cs"; - var destinationDocumentText = """ + """, "Inner2.cs", """ partial class Outer { @@ -1025,16 +742,11 @@ class Inner2 { } } - """; - - await TestMoveTypeToNewFileAsync( - code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/17171")] - public async Task TestInsertFinalNewLine() - { - var code = + public Task TestInsertFinalNewLine() + => TestMoveTypeToNewFileAsync( """ class Outer @@ -1047,8 +759,7 @@ class Inner1 { } } - """; - var codeAfterMove = """ + """, """ partial class Outer { @@ -1056,10 +767,7 @@ class Inner1 { } } - """; - - var expectedDocumentName = "Inner2.cs"; - var destinationDocumentText = """ + """, "Inner2.cs", """ partial class Outer { @@ -1068,17 +776,12 @@ class Inner2 } } - """; - - await TestMoveTypeToNewFileAsync( - code, codeAfterMove, expectedDocumentName, destinationDocumentText, + """, options: Option(FormattingOptions2.InsertFinalNewLine, true)); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/17171")] - public async Task TestInsertFinalNewLine2() - { - var code = + public Task TestInsertFinalNewLine2() + => TestMoveTypeToNewFileAsync( """ class Outer @@ -1091,8 +794,7 @@ class Inner1 { } } - """; - var codeAfterMove = """ + """, """ partial class Outer { @@ -1100,10 +802,7 @@ class Inner1 { } } - """; - - var expectedDocumentName = "Inner2.cs"; - var destinationDocumentText = """ + """, "Inner2.cs", """ partial class Outer { @@ -1111,17 +810,12 @@ class Inner2 { } } - """; - - await TestMoveTypeToNewFileAsync( - code, codeAfterMove, expectedDocumentName, destinationDocumentText, + """, options: Option(FormattingOptions2.InsertFinalNewLine, false)); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/16282")] - public async Task MoveTypeRemoveOuterInheritanceTypes() - { - var code = + public Task MoveTypeRemoveOuterInheritanceTypes() + => TestMoveTypeToNewFileAsync( """ class Outer : IComparable { @@ -1129,17 +823,11 @@ class Outer : IComparable { DateTime d; } } - """; - var codeAfterMove = - """ + """, """ partial class Outer : IComparable { } - """; - - var expectedDocumentName = "Inner.cs"; - var destinationDocumentText = - """ + """, "Inner.cs", """ partial class Outer { @@ -1147,16 +835,11 @@ class Inner : IWhatever { DateTime d; } } - """; - - await TestMoveTypeToNewFileAsync( - code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/17930")] - public async Task MoveTypeWithDirectives1() - { - var code = + public Task MoveTypeWithDirectives1() + => TestMoveTypeToNewFileAsync( """ using System; @@ -1176,9 +859,7 @@ public class [||]Inner } #endif - """; - var codeAfterMove = - """ + """, """ using System; namespace N @@ -1193,11 +874,7 @@ static void Main() #if true #endif - """; - - var expectedDocumentName = "Inner.cs"; - var destinationDocumentText = - """ + """, "Inner.cs", """ #if true public class Inner @@ -1205,16 +882,11 @@ public class Inner } #endif - """; - - await TestMoveTypeToNewFileAsync( - code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/17930")] - public async Task MoveTypeWithDirectives2() - { - var code = + public Task MoveTypeWithDirectives2() + => TestMoveTypeToNewFileAsync( """ using System; @@ -1234,9 +906,7 @@ public class [||]Inner #endif } } - """; - var codeAfterMove = - """ + """, """ using System; namespace N @@ -1251,11 +921,7 @@ static void Main() #endif } } - """; - - var expectedDocumentName = "Inner.cs"; - var destinationDocumentText = - """ + """, "Inner.cs", """ namespace N { partial class Program @@ -1268,16 +934,11 @@ public class Inner #endif } } - """; - - await TestMoveTypeToNewFileAsync( - code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/19613")] - public async Task MoveTypeWithDirectives3() - { - var code = + public Task MoveTypeWithDirectives3() + => TestMoveTypeToNewFileAsync( """ public class Goo { @@ -1287,20 +948,14 @@ public class [||]Bar } #endregion } - """; - var codeAfterMove = - """ + """, """ public partial class Goo { #region Region #endregion } - """; - - var expectedDocumentName = "Bar.cs"; - var destinationDocumentText = - """ + """, "Bar.cs", """ public partial class Goo { #region Region @@ -1309,16 +964,11 @@ public class Bar } #endregion } - """; - - await TestMoveTypeToNewFileAsync( - code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/19613")] - public async Task MoveTypeWithDirectives4() - { - var code = + public Task MoveTypeWithDirectives4() + => TestMoveTypeToNewFileAsync( """ public class Goo { @@ -1334,9 +984,7 @@ public class [||]Bar } #endregion } - """; - var codeAfterMove = - """ + """, """ public partial class Goo { #region Region1 @@ -1348,11 +996,7 @@ public class NotBar #region Region2 #endregion } - """; - - var expectedDocumentName = "Bar.cs"; - var destinationDocumentText = - """ + """, "Bar.cs", """ public partial class Goo { #region Region2 @@ -1361,16 +1005,11 @@ public class Bar } #endregion } - """; - - await TestMoveTypeToNewFileAsync( - code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/21456")] - public async Task TestLeadingBlankLines1() - { - var code = + public Task TestLeadingBlankLines1() + => TestMoveTypeToNewFileAsync( """ // Banner Text using System; @@ -1391,8 +1030,7 @@ void Foo() } } - """; - var codeAfterMove = """ + """, """ // Banner Text using System; @@ -1404,10 +1042,7 @@ void Foo() } } - """; - - var expectedDocumentName = "Class1.cs"; - var destinationDocumentText = """ + """, "Class1.cs", """ // Banner Text using System; @@ -1419,16 +1054,11 @@ void Foo() } } - """; - - await TestMoveTypeToNewFileAsync( - code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/21456")] - public async Task TestLeadingBlankLines2() - { - var code = + public Task TestLeadingBlankLines2() + => TestMoveTypeToNewFileAsync( """ // Banner Text using System; @@ -1449,8 +1079,7 @@ void Foo() } } - """; - var codeAfterMove = """ + """, """ // Banner Text using System; @@ -1462,10 +1091,7 @@ void Foo() } } - """; - - var expectedDocumentName = "Class2.cs"; - var destinationDocumentText = """ + """, "Class2.cs", """ // Banner Text using System; @@ -1477,16 +1103,11 @@ void Foo() } } - """; - - await TestMoveTypeToNewFileAsync( - code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/31377")] - public async Task TestLeadingCommentInContainer() - { - var code = + public Task TestLeadingCommentInContainer() + => TestMoveTypeToNewFileAsync( """ // Banner Text using System; @@ -1506,8 +1127,7 @@ void Foo() public int I() => 5; } - """; - var codeAfterMove = """ + """, """ // Banner Text using System; @@ -1523,10 +1143,7 @@ void Foo() public int I() => 5; } - """; - - var expectedDocumentName = "Class2.cs"; - var destinationDocumentText = """ + """, "Class2.cs", """ // Banner Text partial class Class1 { @@ -1535,16 +1152,11 @@ class Class2 } } - """; - - await TestMoveTypeToNewFileAsync( - code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/31377")] - public async Task TestLeadingCommentInContainer2() - { - var code = + public Task TestLeadingCommentInContainer2() + => TestMoveTypeToNewFileAsync( """ // Banner Text using System; @@ -1563,8 +1175,7 @@ void Foo() public int I() => 5; } - """; - var codeAfterMove = """ + """, """ // Banner Text using System; @@ -1579,10 +1190,7 @@ void Foo() public int I() => 5; } - """; - - var expectedDocumentName = "Class2.cs"; - var destinationDocumentText = """ + """, "Class2.cs", """ // Banner Text partial class Class1 { @@ -1591,16 +1199,11 @@ class Class2 } } - """; - - await TestMoveTypeToNewFileAsync( - code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/31377")] - public async Task TestTrailingCommentInContainer() - { - var code = + public Task TestTrailingCommentInContainer() + => TestMoveTypeToNewFileAsync( """ // Banner Text using System; @@ -1620,8 +1223,7 @@ void Foo() // End of class document } - """; - var codeAfterMove = """ + """, """ // Banner Text using System; @@ -1637,10 +1239,7 @@ void Foo() // End of class document } - """; - - var expectedDocumentName = "Class2.cs"; - var destinationDocumentText = """ + """, "Class2.cs", """ // Banner Text partial class Class1 { @@ -1649,16 +1248,11 @@ class Class2 } } - """; - - await TestMoveTypeToNewFileAsync( - code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/31377")] - public async Task TestTrailingCommentInContainer2() - { - var code = + public Task TestTrailingCommentInContainer2() + => TestMoveTypeToNewFileAsync( """ // Banner Text using System; @@ -1677,8 +1271,7 @@ void Foo() public int I() => 5; } // End of class document - """; - var codeAfterMove = """ + """, """ // Banner Text using System; @@ -1693,10 +1286,7 @@ void Foo() public int I() => 5; } // End of class document - """; - - var expectedDocumentName = "Class2.cs"; - var destinationDocumentText = """ + """, "Class2.cs", """ // Banner Text partial class Class1 { @@ -1704,114 +1294,73 @@ class Class2 { } } - """; - - await TestMoveTypeToNewFileAsync( - code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/50329")] - public async Task MoveRecordToNewFilePreserveUsings() - { - var code = - """ + public Task MoveRecordToNewFilePreserveUsings() + => TestMoveTypeToNewFileAsync(""" using System; [||]record CacheContext(String Message); class Program { } - """; - var codeAfterMove = @"class Program { }"; - - var expectedDocumentName = "CacheContext.cs"; - var destinationDocumentText = """ + """, @"class Program { }", "CacheContext.cs", """ using System; record CacheContext(String Message); - """; - - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact] - public async Task MoveClassToNewFilePreserveUsings_PrimaryConstructor() - { - var code = - """ + public Task MoveClassToNewFilePreserveUsings_PrimaryConstructor() + => TestMoveTypeToNewFileAsync(""" using System; [||]class CacheContext(String Message); class Program { } - """; - var codeAfterMove = @"class Program { }"; - - var expectedDocumentName = "CacheContext.cs"; - var destinationDocumentText = """ + """, @"class Program { }", "CacheContext.cs", """ using System; class CacheContext(String Message); - """; - - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact] - public async Task MoveStructToNewFilePreserveUsings_PrimaryConstructor() - { - var code = - """ + public Task MoveStructToNewFilePreserveUsings_PrimaryConstructor() + => TestMoveTypeToNewFileAsync(""" using System; [||]struct CacheContext(String Message); class Program { } - """; - var codeAfterMove = @"class Program { }"; - - var expectedDocumentName = "CacheContext.cs"; - var destinationDocumentText = """ + """, @"class Program { }", "CacheContext.cs", """ using System; struct CacheContext(String Message); - """; - - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact] - public async Task MoveInterfaceToNewFilePreserveUsings_PrimaryConstructor() - { - var code = - """ + public Task MoveInterfaceToNewFilePreserveUsings_PrimaryConstructor() + => TestMoveTypeToNewFileAsync(""" using System; [||]interface CacheContext(String Message); class Program { } - """; - var codeAfterMove = """ + """, """ using System; class Program { } - """; - - var expectedDocumentName = "CacheContext.cs"; - var destinationDocumentText = """ + """, "CacheContext.cs", """ interface CacheContext(String Message); - """; - - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact] - public async Task MoveClassInTopLevelStatements() - { - var code = """ + public Task MoveClassInTopLevelStatements() + => TestMoveTypeToNewFileAsync(""" using ConsoleApp1; using System; @@ -1823,9 +1372,7 @@ class [||]C { public string Hello => "Hello"; } - """; - - var codeAfterMove = """ + """, """ using ConsoleApp1; using System; @@ -1833,23 +1380,16 @@ class [||]C var c = new C(); Console.WriteLine(c.Hello); - """; - - var expectedDocumentName = "C.cs"; - var destinationDocumentText = """ + """, "C.cs", """ class C { public string Hello => "Hello"; } - """; - - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact] - public async Task MissingInTopLevelStatementsOnly() - { - var code = """ + public Task MissingInTopLevelStatementsOnly() + => TestMissingAsync(""" using ConsoleApp1; using System; @@ -1857,15 +1397,11 @@ public async Task MissingInTopLevelStatementsOnly() var c = new object(); [||]Console.WriteLine(c.ToString()); - """; - - await TestMissingAsync(code); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/55544")] - public async Task MoveInNamespace_WithAttributes1() - { - var code = """ + public Task MoveInNamespace_WithAttributes1() + => TestMoveTypeToNewFileAsync(""" using Sytem.Reflection; @@ -1880,9 +1416,7 @@ class [||]B { } } - """; - - var codeAfterMove = """ + """, """ using Sytem.Reflection; @@ -1893,25 +1427,18 @@ class A { } } - """; - - var expectedDocumentName = "B.cs"; - var destinationDocumentText = """ + """, "B.cs", """ namespace N { class B { } } - """; - - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/55544")] - public async Task MoveInNamespace_WithAttributes2() - { - var code = """ + public Task MoveInNamespace_WithAttributes2() + => TestMoveTypeToNewFileAsync(""" using Sytem.Reflection; @@ -1927,9 +1454,7 @@ class [||]B { } } - """; - - var codeAfterMove = """ + """, """ using Sytem.Reflection; @@ -1940,10 +1465,7 @@ class A { } } - """; - - var expectedDocumentName = "B.cs"; - var destinationDocumentText = """ + """, "B.cs", """ namespace N { [Test] @@ -1951,15 +1473,11 @@ class B { } } - """; - - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/55544")] - public async Task MoveInNamespace_WithAttributes3() - { - var code = """ + public Task MoveInNamespace_WithAttributes3() + => TestMoveTypeToNewFileAsync(""" namespace N { @@ -1972,9 +1490,7 @@ class [||]B { } } - """; - - var codeAfterMove = """ + """, """ namespace N { @@ -1982,10 +1498,7 @@ class A { } } - """; - - var expectedDocumentName = "B.cs"; - var destinationDocumentText = """ + """, "B.cs", """ namespace N { @@ -1994,15 +1507,11 @@ class B { } } - """; - - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/55544")] - public async Task MoveTopLevel_WithAttributes1() - { - var code = """ + public Task MoveTopLevel_WithAttributes1() + => TestMoveTypeToNewFileAsync(""" [Test] class [||]A @@ -2012,31 +1521,22 @@ class [||]A class B { } - """; - - var codeAfterMove = """ + """, """ class B { } - """; - - var expectedDocumentName = "A.cs"; - var destinationDocumentText = """ + """, "A.cs", """ [Test] class A { } - """; - - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/55544")] - public async Task MoveTopLevel_WithAttributes2() - { - var code = """ + public Task MoveTopLevel_WithAttributes2() + => TestMoveTypeToNewFileAsync(""" [Test] class [||]A @@ -2047,27 +1547,19 @@ class [||]A class B { } - """; - - var codeAfterMove = """ + """, """ [Test] class B { } - """; - - var expectedDocumentName = "A.cs"; - var destinationDocumentText = """ + """, "A.cs", """ [Test] class A { } - """; - - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/63114")] [InlineData("class")] @@ -2075,9 +1567,8 @@ class A [InlineData("interface")] [InlineData("enum")] [InlineData("record")] - public async Task MoveNestedTypeFromInterface(string memberType) - { - var code = $$""" + public Task MoveNestedTypeFromInterface(string memberType) + => TestMoveTypeToNewFileAsync($$""" interface I { @@ -2085,15 +1576,12 @@ interface I { } } - """; - var codeAfterMove = """ + """, """ partial interface I { } - """; - var expectedDocumentName = "Member.cs"; - var destinationDocumentText = $$""" + """, "Member.cs", $$""" partial interface I { @@ -2101,14 +1589,11 @@ partial interface I { } } - """; - await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/74703")] - public async Task TestUpdateFileName() - { - var code = + public Task TestUpdateFileName() + => TestMoveTypeToNewFileAsync( """ @@ -2119,22 +1604,14 @@ class Class2 { } - """; - var codeAfterMove = """ + """, """ // This is a banner referencing Goo.cs class Class2 { } - """; - - var expectedDocumentName = "Class1.cs"; - var destinationDocumentText = """ + """, "Class1.cs", + """ // This is a banner referencing Class1.cs class Class1 { } - """; - - await TestMoveTypeToNewFileAsync( - code, codeAfterMove, expectedDocumentName, - destinationDocumentText, destinationDocumentContainers: ["A", "B"]); - } + """, destinationDocumentContainers: ["A", "B"]); } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.RenameFile.cs b/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.RenameFile.cs index 49dd16a8d1c70..4eef1c3fa2faa 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.RenameFile.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.RenameFile.cs @@ -15,136 +15,83 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.MoveType; public partial class MoveTypeTests : CSharpMoveTypeTestsBase { [Fact] - public async Task SingleClassInFile_RenameFile() - { - var code = -@"[||]class Class1 { }"; - - var expectedDocumentName = "Class1.cs"; - - await TestRenameFileToMatchTypeAsync(code, expectedDocumentName); - } + public Task SingleClassInFile_RenameFile() + => TestRenameFileToMatchTypeAsync(@"[||]class Class1 { }", "Class1.cs"); [Fact] - public async Task MoreThanOneTypeInFile_RenameFile() - { - var code = -@"[||]class Class1 -{ - class Inner { } -}"; - - var expectedDocumentName = "Class1.cs"; - - await TestRenameFileToMatchTypeAsync(code, expectedDocumentName); - } + public Task MoreThanOneTypeInFile_RenameFile() + => TestRenameFileToMatchTypeAsync(""" + [||]class Class1 + { + class Inner { } + } + """, "Class1.cs"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16284")] - public async Task MoreThanOneTypeInFile_RenameFile_InnerType() - { - var code = -@"class Class1 -{ - [||]class Inner { } -}"; - - var expectedDocumentName = "Class1.Inner.cs"; - - await TestRenameFileToMatchTypeAsync(code, expectedDocumentName); - } + public Task MoreThanOneTypeInFile_RenameFile_InnerType() + => TestRenameFileToMatchTypeAsync(""" + class Class1 + { + [||]class Inner { } + } + """, "Class1.Inner.cs"); [Fact] - public async Task TestRenameFileWithFolders() - { - var code = -@" - - - -[||]class Class1 -{ - class Inner { } -} - - -"; - - var expectedDocumentName = "Class1.cs"; - - await TestRenameFileToMatchTypeAsync(code, expectedDocumentName, + public Task TestRenameFileWithFolders() + => TestRenameFileToMatchTypeAsync(""" + + + + [||]class Class1 + { + class Inner { } + } + + + + """, "Class1.cs", destinationDocumentContainers: ["A", "B"]); - } [Fact] - public async Task TestMissing_TypeNameMatchesFileName_RenameFile() - { - // testworkspace creates files like test1.cs, test2.cs and so on.. - // so type name matches filename here and rename file action should not be offered. - var code = -@"[||]class test1 { }"; - - await TestRenameFileToMatchTypeAsync(code, expectedCodeAction: false); - } + public Task TestMissing_TypeNameMatchesFileName_RenameFile() + => TestRenameFileToMatchTypeAsync(@"[||]class test1 { }", expectedCodeAction: false); [Fact] - public async Task TestMissing_MultipleTopLevelTypesInFileAndAtleastOneMatchesFileName_RenameFile() - { - var code = -@"[||]class Class1 { } -class test1 { }"; - - await TestRenameFileToMatchTypeAsync(code, expectedCodeAction: false); - } + public Task TestMissing_MultipleTopLevelTypesInFileAndAtleastOneMatchesFileName_RenameFile() + => TestRenameFileToMatchTypeAsync(""" + [||]class Class1 { } + class test1 { } + """, expectedCodeAction: false); [Fact] - public async Task MultipleTopLevelTypesInFileAndNoneMatchFileName_RenameFile() - { - var code = -@"[||]class Class1 { } -class Class2 { }"; - - var expectedDocumentName = "Class1.cs"; - - await TestRenameFileToMatchTypeAsync(code, expectedDocumentName); - } + public Task MultipleTopLevelTypesInFileAndNoneMatchFileName_RenameFile() + => TestRenameFileToMatchTypeAsync(""" + [||]class Class1 { } + class Class2 { } + """, "Class1.cs"); [Fact] - public async Task MultipleTopLevelTypesInFileAndNoneMatchFileName2_RenameFile() - { - var code = -@"class Class1 { } -[||]class Class2 { }"; - - var expectedDocumentName = "Class2.cs"; - - await TestRenameFileToMatchTypeAsync(code, expectedDocumentName); - } + public Task MultipleTopLevelTypesInFileAndNoneMatchFileName2_RenameFile() + => TestRenameFileToMatchTypeAsync(""" + class Class1 { } + [||]class Class2 { } + """, "Class2.cs"); [Fact] - public async Task NestedFile_Simple_RenameFile() - { - var code = -@"class OuterType -{ - [||]class InnerType { } -}"; - - var expectedDocumentName = "InnerType.cs"; - - await TestRenameFileToMatchTypeAsync(code, expectedDocumentName); - } + public Task NestedFile_Simple_RenameFile() + => TestRenameFileToMatchTypeAsync(""" + class OuterType + { + [||]class InnerType { } + } + """, "InnerType.cs"); [Fact] - public async Task NestedFile_DottedName_RenameFile() - { - var code = -@"class OuterType -{ - [||]class InnerType { } -}"; - - var expectedDocumentName = "OuterType.InnerType.cs"; - - await TestRenameFileToMatchTypeAsync(code, expectedDocumentName); - } + public Task NestedFile_DottedName_RenameFile() + => TestRenameFileToMatchTypeAsync(""" + class OuterType + { + [||]class InnerType { } + } + """, "OuterType.InnerType.cs"); } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.RenameType.cs b/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.RenameType.cs index 21e842b816b2d..d51284f9ef82f 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.RenameType.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.RenameType.cs @@ -15,102 +15,63 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.MoveType; public partial class MoveTypeTests : CSharpMoveTypeTestsBase { [Fact] - public async Task SingleClassInFile_RenameType() - { - var code = -@"[||]class Class1 { }"; - - var codeWithTypeRenamedToMatchFileName = -@"class [|test1|] { }"; - - await TestRenameTypeToMatchFileAsync(code, codeWithTypeRenamedToMatchFileName); - } + public Task SingleClassInFile_RenameType() + => TestRenameTypeToMatchFileAsync(@"[||]class Class1 { }", @"class [|test1|] { }"); [Fact] - public async Task MoreThanOneTypeInFile_RenameType() - { - var code = -@"[||]class Class1 -{ - class Inner { } -}"; - - var codeWithTypeRenamedToMatchFileName = -@"class [|test1|] -{ - class Inner { } -}"; - - await TestRenameTypeToMatchFileAsync(code, codeWithTypeRenamedToMatchFileName); - } + public Task MoreThanOneTypeInFile_RenameType() + => TestRenameTypeToMatchFileAsync(""" + [||]class Class1 + { + class Inner { } + } + """, """ + class [|test1|] + { + class Inner { } + } + """); [Fact] - public async Task TestMissing_TypeNameMatchesFileName_RenameType() - { - // testworkspace creates files like test1.cs, test2.cs and so on.. - // so type name matches filename here and rename file action should not be offered. - var code = -@"[||]class test1 { }"; - - await TestRenameTypeToMatchFileAsync(code, expectedCodeAction: false); - } + public Task TestMissing_TypeNameMatchesFileName_RenameType() + => TestRenameTypeToMatchFileAsync(@"[||]class test1 { }", expectedCodeAction: false); [Fact] - public async Task TestMissing_MultipleTopLevelTypesInFileAndAtleastOneMatchesFileName_RenameType() - { - var code = -@"[||]class Class1 { } -class test1 { }"; - - await TestRenameTypeToMatchFileAsync(code, expectedCodeAction: false); - } + public Task TestMissing_MultipleTopLevelTypesInFileAndAtleastOneMatchesFileName_RenameType() + => TestRenameTypeToMatchFileAsync(""" + [||]class Class1 { } + class test1 { } + """, expectedCodeAction: false); [Fact] - public async Task MultipleTopLevelTypesInFileAndNoneMatchFileName1_RenameType() - { - var code = -@"[||]class Class1 { } -class Class2 { }"; - - var codeWithTypeRenamedToMatchFileName = -@"class [|test1|] { } -class Class2 { }"; - - await TestRenameTypeToMatchFileAsync(code, codeWithTypeRenamedToMatchFileName); - } + public Task MultipleTopLevelTypesInFileAndNoneMatchFileName1_RenameType() + => TestRenameTypeToMatchFileAsync(""" + [||]class Class1 { } + class Class2 { } + """, """ + class [|test1|] { } + class Class2 { } + """); [Fact] - public async Task MultipleTopLevelTypesInFileAndNoneMatchFileName2_RenameType() - { - var code = -@"class Class1 { } -[||]class Class2 { }"; - - var codeWithTypeRenamedToMatchFileName = -@"class Class1 { } -class [|test1|] { }"; - - await TestRenameTypeToMatchFileAsync(code, codeWithTypeRenamedToMatchFileName); - } + public Task MultipleTopLevelTypesInFileAndNoneMatchFileName2_RenameType() + => TestRenameTypeToMatchFileAsync(""" + class Class1 { } + [||]class Class2 { } + """, """ + class Class1 { } + class [|test1|] { } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40043")] - public async Task NothingOfferedWhenTypeHasNoNameYet1() - { - var code = @"class[||]"; - await TestMissingAsync(code); - } + public Task NothingOfferedWhenTypeHasNoNameYet1() + => TestMissingAsync(@"class[||]"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40043")] - public async Task NothingOfferedWhenTypeHasNoNameYet2() - { - var code = @"class [||]"; - await TestMissingAsync(code); - } + public Task NothingOfferedWhenTypeHasNoNameYet2() + => TestMissingAsync(@"class [||]"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40043")] - public async Task NothingOfferedWhenTypeHasNoNameYet3() - { - var code = @"class [||] { }"; - await TestMissingAsync(code); - } + public Task NothingOfferedWhenTypeHasNoNameYet3() + => TestMissingAsync(@"class [||] { }"); } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/PreviewExceptionTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/PreviewExceptionTests.cs index f16a4d7e68c58..ad5cbb59f472e 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/PreviewExceptionTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/PreviewExceptionTests.cs @@ -16,7 +16,6 @@ using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; -using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; diff --git a/src/EditorFeatures/CSharpTest/CodeActions/PullMemberUp/CSharpPullMemberUpTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/PullMemberUp/CSharpPullMemberUpTests.cs index 35a0324f840e0..7fbbb97bc092a 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/PullMemberUp/CSharpPullMemberUpTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/PullMemberUp/CSharpPullMemberUpTests.cs @@ -4,23 +4,23 @@ #nullable disable +using System.Collections.Generic; +using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddImport; +using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; +using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.PullMemberUp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; +using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; +using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; -using Xunit; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis.CodeActions; -using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog; -using System.Collections.Generic; using Microsoft.CodeAnalysis.Test.Utilities.PullMemberUp; using Roslyn.Test.Utilities; -using Microsoft.CodeAnalysis.Editing; -using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; +using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.PullMemberUp; @@ -59,6168 +59,5750 @@ private async Task TestQuickActionNotProvidedAsync( } [Fact] - public async Task TestNoRefactoringProvidedWhenNoOptionsService() - { - var testText = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - } - - public class TestClass : IInterface - { - public void TestM[||]ethod() - { - System.Console.WriteLine(""Hello World""); - } - } -}"; - await TestActionCountAsync(testText, 0); - } - - [Fact] - public async Task TestNoRefactoringProvidedWhenPullFieldInInterfaceViaQuickAction() - { - var testText = @" -namespace PushUpTest -{ - public interface ITestInterface - { - } + public Task TestNoRefactoringProvidedWhenNoOptionsService() + => TestActionCountAsync(""" + using System; + namespace PushUpTest + { + interface IInterface + { + } - public class TestClass : ITestInterface - { - public int yo[||]u = 10086; - } -}"; - await TestQuickActionNotProvidedAsync(testText); - } + public class TestClass : IInterface + { + public void TestM[||]ethod() + { + System.Console.WriteLine("Hello World"); + } + } + } + """, 0); [Fact] - public async Task TestNoRefactoringProvidedWhenMethodDeclarationAlreadyExistsInInterfaceViaQuickAction() - { - var methodTest = @" -namespace PushUpTest -{ - public interface ITestInterface - { - void TestMethod(); - } + public Task TestNoRefactoringProvidedWhenPullFieldInInterfaceViaQuickAction() + => TestQuickActionNotProvidedAsync(""" + namespace PushUpTest + { + public interface ITestInterface + { + } - public class TestClass : ITestInterface - { - public void TestM[||]ethod() - { - System.Console.WriteLine(""Hello World""); - } - } -}"; - await TestQuickActionNotProvidedAsync(methodTest); - } + public class TestClass : ITestInterface + { + public int yo[||]u = 10086; + } + } + """); [Fact] - public async Task TestNoRefactoringProvidedWhenPropertyDeclarationAlreadyExistsInInterfaceViaQuickAction() - { - var propertyTest1 = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - int TestProperty { get; } - } + public Task TestNoRefactoringProvidedWhenMethodDeclarationAlreadyExistsInInterfaceViaQuickAction() + => TestQuickActionNotProvidedAsync(""" + namespace PushUpTest + { + public interface ITestInterface + { + void TestMethod(); + } - public class TestClass : IInterface - { - public int TestPr[||]operty { get; private set; } - } -}"; - await TestQuickActionNotProvidedAsync(propertyTest1); - } + public class TestClass : ITestInterface + { + public void TestM[||]ethod() + { + System.Console.WriteLine("Hello World"); + } + } + } + """); [Fact] - public async Task TestNoRefactoringProvidedWhenEventDeclarationAlreadyExistsToInterfaceViaQuickAction() - { - var eventTest = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - event EventHandler Event2; - } + public Task TestNoRefactoringProvidedWhenPropertyDeclarationAlreadyExistsInInterfaceViaQuickAction() + => TestQuickActionNotProvidedAsync(""" + using System; + namespace PushUpTest + { + interface IInterface + { + int TestProperty { get; } + } - public class TestClass : IInterface - { - public event EventHandler Event1, Eve[||]nt2, Event3; - } -}"; - await TestQuickActionNotProvidedAsync(eventTest); - } + public class TestClass : IInterface + { + public int TestPr[||]operty { get; private set; } + } + } + """); [Fact] - public async Task TestNoRefactoringProvidedInNestedTypesViaQuickAction() - { - var input = @" -namespace PushUpTest -{ - public interface ITestInterface - { - void Foobar(); - } - - public class TestClass : ITestInterface - { - public class N[||]estedClass - { - } - } -}"; + public Task TestNoRefactoringProvidedWhenEventDeclarationAlreadyExistsToInterfaceViaQuickAction() + => TestQuickActionNotProvidedAsync(""" + using System; + namespace PushUpTest + { + interface IInterface + { + event EventHandler Event2; + } - await TestQuickActionNotProvidedAsync(input); - } + public class TestClass : IInterface + { + public event EventHandler Event1, Eve[||]nt2, Event3; + } + } + """); [Fact] - public async Task TestPullMethodUpToInterfaceViaQuickAction() - { - var testText = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - } - - public class TestClass : IInterface - { - public void TestM[||]ethod() - { - System.Console.WriteLine(""Hello World""); - } - } -}"; - var expected = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - void TestMethod(); - } + public Task TestNoRefactoringProvidedInNestedTypesViaQuickAction() + => TestQuickActionNotProvidedAsync(""" + namespace PushUpTest + { + public interface ITestInterface + { + void Foobar(); + } - public class TestClass : IInterface - { - public void TestMethod() - { - System.Console.WriteLine(""Hello World""); - } - } -}"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class TestClass : ITestInterface + { + public class N[||]estedClass + { + } + } + } + """); [Fact] - public async Task TestPullAbstractMethodToInterfaceViaQuickAction() - { - var testText = @" -namespace PushUpTest -{ - public interface IInterface - { - } - - public abstract class TestClass : IInterface - { - public abstract void TestMeth[||]od(); - } -}"; + public Task TestPullMethodUpToInterfaceViaQuickAction() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest + { + interface IInterface + { + } - var expected = @" -namespace PushUpTest -{ - public interface IInterface - { - void TestMethod(); - } + public class TestClass : IInterface + { + public void TestM[||]ethod() + { + System.Console.WriteLine("Hello World"); + } + } + } + """, """ + using System; + namespace PushUpTest + { + interface IInterface + { + void TestMethod(); + } - public abstract class TestClass : IInterface - { - public abstract void TestMethod(); - } -}"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class TestClass : IInterface + { + public void TestMethod() + { + System.Console.WriteLine("Hello World"); + } + } + } + """); [Fact] - public async Task TestPullGenericsUpToInterfaceViaQuickAction() - { - var testText = @" -using System; -namespace PushUpTest -{ - public interface IInterface - { - } - - public class TestClass : IInterface - { - public void TestMeth[||]od() where T : IDisposable - { - } - } -}"; + public Task TestPullAbstractMethodToInterfaceViaQuickAction() + => TestWithPullMemberDialogAsync(""" + namespace PushUpTest + { + public interface IInterface + { + } - var expected = @" -using System; -namespace PushUpTest -{ - public interface IInterface - { - void TestMethod() where T : IDisposable; - } + public abstract class TestClass : IInterface + { + public abstract void TestMeth[||]od(); + } + } + """, """ + namespace PushUpTest + { + public interface IInterface + { + void TestMethod(); + } - public class TestClass : IInterface - { - public void TestMeth[||]od() where T : IDisposable - { - } - } -}"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public abstract class TestClass : IInterface + { + public abstract void TestMethod(); + } + } + """); [Fact] - public async Task TestPullSingleEventToInterfaceViaQuickAction() - { - var testText = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - } - - public class TestClass : IInterface - { - public event EventHandler Eve[||]nt1 - { - add + public Task TestPullGenericsUpToInterfaceViaQuickAction() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest { - System.Console.Writeline(""This is add""); + public interface IInterface + { + } + + public class TestClass : IInterface + { + public void TestMeth[||]od() where T : IDisposable + { + } + } } - remove + """, """ + using System; + namespace PushUpTest { - System.Console.Writeline(""This is remove""); - } - } - } -}"; + public interface IInterface + { + void TestMethod() where T : IDisposable; + } - var expected = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - event EventHandler Event1; - } + public class TestClass : IInterface + { + public void TestMeth[||]od() where T : IDisposable + { + } + } + } + """); - public class TestClass : IInterface - { - public event EventHandler Event1 - { - add + [Fact] + public Task TestPullSingleEventToInterfaceViaQuickAction() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest { - System.Console.Writeline(""This is add""); + interface IInterface + { + } + + public class TestClass : IInterface + { + public event EventHandler Eve[||]nt1 + { + add + { + System.Console.Writeline("This is add"); + } + remove + { + System.Console.Writeline("This is remove"); + } + } + } } - remove + """, """ + using System; + namespace PushUpTest { - System.Console.Writeline(""This is remove""); + interface IInterface + { + event EventHandler Event1; + } + + public class TestClass : IInterface + { + public event EventHandler Event1 + { + add + { + System.Console.Writeline("This is add"); + } + remove + { + System.Console.Writeline("This is remove"); + } + } + } } - } - } -}"; - await TestWithPullMemberDialogAsync(testText, expected); - } + """); [Fact] - public async Task TestPullOneEventFromMultipleEventsToInterfaceViaQuickAction() - { - var testText = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - } - - public class TestClass : IInterface - { - public event EventHandler Event1, Eve[||]nt2, Event3; - } -}"; + public Task TestPullOneEventFromMultipleEventsToInterfaceViaQuickAction() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest + { + interface IInterface + { + } - var expected = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - event EventHandler Event2; - } + public class TestClass : IInterface + { + public event EventHandler Event1, Eve[||]nt2, Event3; + } + } + """, """ + using System; + namespace PushUpTest + { + interface IInterface + { + event EventHandler Event2; + } - public class TestClass : IInterface - { - public event EventHandler Event1, Event2, Event3; - } -}"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class TestClass : IInterface + { + public event EventHandler Event1, Event2, Event3; + } + } + """); [Fact] - public async Task TestPullPublicEventWithAccessorsToInterfaceViaQuickAction() - { - var testText = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - } - - public class TestClass : IInterface - { - public event EventHandler Eve[||]nt2 - { - add + public Task TestPullPublicEventWithAccessorsToInterfaceViaQuickAction() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest { - System.Console.Writeln(""This is add in event1""); + interface IInterface + { + } + + public class TestClass : IInterface + { + public event EventHandler Eve[||]nt2 + { + add + { + System.Console.Writeln("This is add in event1"); + } + remove + { + System.Console.Writeln("This is remove in event2"); + } + } + } } - remove + """, """ + using System; + namespace PushUpTest { - System.Console.Writeln(""This is remove in event2""); + interface IInterface + { + event EventHandler Event2; + } + + public class TestClass : IInterface + { + public event EventHandler Event2 + { + add + { + System.Console.Writeln("This is add in event1"); + } + remove + { + System.Console.Writeln("This is remove in event2"); + } + } + } } - } - } -}"; + """); - var expected = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - event EventHandler Event2; - } - - public class TestClass : IInterface - { - public event EventHandler Event2 - { - add + [Fact] + public Task TestPullPropertyWithPrivateSetterToInterfaceViaQuickAction() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest { - System.Console.Writeln(""This is add in event1""); + interface IInterface + { + } + + public class TestClass : IInterface + { + public int TestPr[||]operty { get; private set; } + } } - remove + """, """ + using System; + namespace PushUpTest { - System.Console.Writeln(""This is remove in event2""); + interface IInterface + { + int TestProperty { get; } + } + + public class TestClass : IInterface + { + public int TestProperty { get; private set; } + } } - } - } -}"; - await TestWithPullMemberDialogAsync(testText, expected); - } + """); [Fact] - public async Task TestPullPropertyWithPrivateSetterToInterfaceViaQuickAction() - { - var testText = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - } - - public class TestClass : IInterface - { - public int TestPr[||]operty { get; private set; } - } -}"; + public Task TestPullPropertyWithPrivateGetterToInterfaceViaQuickAction() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest + { + interface IInterface + { + } - var expected = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - int TestProperty { get; } - } + public class TestClass : IInterface + { + public int TestProperty[||]{ private get; set; } + } + } + """, """ + using System; + namespace PushUpTest + { + interface IInterface + { + int TestProperty { set; } + } - public class TestClass : IInterface - { - public int TestProperty { get; private set; } - } -}"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class TestClass : IInterface + { + public int TestProperty{ private get; set; } + } + } + """); [Fact] - public async Task TestPullPropertyWithPrivateGetterToInterfaceViaQuickAction() - { - var testText = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - } - - public class TestClass : IInterface - { - public int TestProperty[||]{ private get; set; } - } -}"; + public Task TestPullMemberFromInterfaceToInterfaceViaQuickAction() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest + { + interface IInterface + { + } - var expected = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - int TestProperty { set; } - } + interface FooInterface : IInterface + { + int TestPr[||]operty { set; } + } + } + """, """ + using System; + namespace PushUpTest + { + interface IInterface + { + int TestProperty { set; } + } - public class TestClass : IInterface - { - public int TestProperty{ private get; set; } - } -}"; - await TestWithPullMemberDialogAsync(testText, expected); - } + interface FooInterface : IInterface + { + } + } + """); [Fact] - public async Task TestPullMemberFromInterfaceToInterfaceViaQuickAction() - { - var testText = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - } - - interface FooInterface : IInterface - { - int TestPr[||]operty { set; } - } -}"; + public Task TestPullIndexerWithOnlySetterToInterfaceViaQuickAction() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest + { + interface IInterface + { + } - var expected = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - int TestProperty { set; } - } + public class TestClass : IInterface + { + private int j; + public int th[||]is[int i] + { + set => j = value; + } + } + } + """, """ + using System; + namespace PushUpTest + { + interface IInterface + { + int this[int i] { set; } + } - interface FooInterface : IInterface - { - } -}"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class TestClass : IInterface + { + private int j; + public int this[int i] + { + set => j = value; + } + } + } + """); [Fact] - public async Task TestPullIndexerWithOnlySetterToInterfaceViaQuickAction() - { - var testText = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - } + public Task TestPullIndexerWithOnlyGetterToInterfaceViaQuickAction() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest + { + interface IInterface + { + } - public class TestClass : IInterface - { - private int j; - public int th[||]is[int i] - { - set => j = value; - } - } -}"; - var expected = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - int this[int i] { set; } - } + public class TestClass : IInterface + { + private int j; + public int th[||]is[int i] + { + get => j = value; + } + } + } + """, """ + using System; + namespace PushUpTest + { + interface IInterface + { + int this[int i] { get; } + } - public class TestClass : IInterface - { - private int j; - public int this[int i] - { - set => j = value; - } - } -}"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class TestClass : IInterface + { + private int j; + public int this[int i] + { + get => j = value; + } + } + } + """); - [Fact] - public async Task TestPullIndexerWithOnlyGetterToInterfaceViaQuickAction() - { - var testText = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - } + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] + public Task TestPullPropertyToInterfaceWithAddUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + public interface IBase + { + } + + + using System; - public class TestClass : IInterface - { - private int j; - public int th[||]is[int i] - { - get => j = value; - } - } -}"; - var expected = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - int this[int i] { get; } - } + public class Derived : IBase + { + public Uri En[||]dpoint { get; set; } + } + + + + """, """ + + + + using System; + + public interface IBase + { + Uri Endpoint { get; set; } + } + + + using System; - public class TestClass : IInterface - { - private int j; - public int this[int i] - { - get => j = value; - } - } -}"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Derived : IBase + { + public Uri Endpoint { get; set; } + } + + + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullPropertyToInterfaceWithAddUsingsViaQuickAction() - { - var testText = @" - - - -public interface IBase -{ -} - - -using System; + public Task TestPullMethodToInterfaceWithoutAddUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + public interface IBase + { + } + + + using System; -public class Derived : IBase -{ - public Uri En[||]dpoint { get; set; } -} - - - -"; - var expected = @" - - - -using System; - -public interface IBase -{ - Uri Endpoint { get; set; } -} - - -using System; + public class Derived : IBase + { + public bool Test[||]Method() + { + var endpoint1 = new Uri("http://localhost"); + var endpoint2 = new Uri("http://localhost"); + return endpoint1.Equals(endpoint2); + } + } + + + + """, """ + + + + public interface IBase + { + bool TestMethod(); + } + + + using System; -public class Derived : IBase -{ - public Uri Endpoint { get; set; } -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Derived : IBase + { + public bool Test[||]Method() + { + var endpoint1 = new Uri("http://localhost"); + var endpoint2 = new Uri("http://localhost"); + return endpoint1.Equals(endpoint2); + } + } + + + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodToInterfaceWithoutAddUsingsViaQuickAction() - { - var testText = @" - - - -public interface IBase -{ -} - - -using System; + public Task TestPullMethodWithNewReturnTypeToInterfaceWithAddUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + public interface IBase + { + } + + + using System; -public class Derived : IBase -{ - public bool Test[||]Method() - { - var endpoint1 = new Uri(""http://localhost""); - var endpoint2 = new Uri(""http://localhost""); - return endpoint1.Equals(endpoint2); - } -} - - - -"; - var expected = @" - - - -public interface IBase -{ - bool TestMethod(); -} - - -using System; + public class Derived : IBase + { + public Uri Test[||]Method() + { + return new Uri("http://localhost"); + } + } + + + + """, """ + + + + using System; + + public interface IBase + { + Uri TestMethod(); + } + + + using System; -public class Derived : IBase -{ - public bool Test[||]Method() - { - var endpoint1 = new Uri(""http://localhost""); - var endpoint2 = new Uri(""http://localhost""); - return endpoint1.Equals(endpoint2); - } -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Derived : IBase + { + public Uri TestMethod() + { + return new Uri("http://localhost"); + } + } + + + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodWithNewReturnTypeToInterfaceWithAddUsingsViaQuickAction() - { - var testText = @" - - - -public interface IBase -{ -} - - -using System; + public Task TestPullMethodWithNewParamTypeToInterfaceWithAddUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + public interface IBase + { + } + + + using System; -public class Derived : IBase -{ - public Uri Test[||]Method() - { - return new Uri(""http://localhost""); - } -} - - - -"; - var expected = @" - - - -using System; - -public interface IBase -{ - Uri TestMethod(); -} - - -using System; + public class Derived : IBase + { + public bool Test[||]Method(Uri endpoint) + { + var localHost = new Uri("http://localhost"); + return endpoint.Equals(localhost); + } + } + + + + """, """ + + + + using System; + + public interface IBase + { + bool TestMethod(Uri endpoint); + } + + + using System; -public class Derived : IBase -{ - public Uri TestMethod() - { - return new Uri(""http://localhost""); - } -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Derived : IBase + { + public bool TestMethod(Uri endpoint) + { + var localHost = new Uri("http://localhost"); + return endpoint.Equals(localhost); + } + } + + + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodWithNewParamTypeToInterfaceWithAddUsingsViaQuickAction() - { - var testText = @" - - - -public interface IBase -{ -} - - -using System; + public Task TestPullEventToInterfaceWithAddUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + public interface IBase + { + } + + + using System; -public class Derived : IBase -{ - public bool Test[||]Method(Uri endpoint) - { - var localHost = new Uri(""http://localhost""); - return endpoint.Equals(localhost); - } -} - - - -"; - var expected = @" - - - -using System; - -public interface IBase -{ - bool TestMethod(Uri endpoint); -} - - -using System; + public class Derived : IBase + { + public event EventHandler Test[||]Event + { + add + { + Console.WriteLine("adding event..."); + } + remove + { + Console.WriteLine("removing event..."); + } + } + } + + + + """, """ + + + + using System; + + public interface IBase + { + event EventHandler TestEvent; + } + + + using System; -public class Derived : IBase -{ - public bool TestMethod(Uri endpoint) - { - var localHost = new Uri(""http://localhost""); - return endpoint.Equals(localhost); - } -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Derived : IBase + { + public event EventHandler TestEvent + { + add + { + Console.WriteLine("adding event..."); + } + remove + { + Console.WriteLine("removing event..."); + } + } + } + + + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullEventToInterfaceWithAddUsingsViaQuickAction() - { - var testText = @" - - - -public interface IBase -{ -} - - -using System; + public Task TestPullPropertyToClassWithAddUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + public class Base + { + } + + + using System; -public class Derived : IBase -{ - public event EventHandler Test[||]Event - { - add - { - Console.WriteLine(""adding event...""); - } - remove - { - Console.WriteLine(""removing event...""); - } - } -} - - - -"; - var expected = @" - - - -using System; - -public interface IBase -{ - event EventHandler TestEvent; -} - - -using System; + public class Derived : Base + { + public Uri En[||]dpoint { get; set; } + } + + + + """, """ + + + using System; + + public class Base + { + public Uri Endpoint { get; set; } + } + + + using System; -public class Derived : IBase -{ - public event EventHandler TestEvent - { - add - { - Console.WriteLine(""adding event...""); - } - remove - { - Console.WriteLine(""removing event...""); - } - } -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Derived : Base + { + } + + + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullPropertyToClassWithAddUsingsViaQuickAction() - { - var testText = @" - - - -public class Base -{ -} - - -using System; + public Task TestPullPropertyToClassWithAddUsingsViaQuickAction2() + => TestWithPullMemberDialogAsync(""" + + + public class Base + { + } + + + using System; -public class Derived : Base -{ - public Uri En[||]dpoint { get; set; } -} - - - -"; - var expected = @" - - - using System; - -public class Base -{ - public Uri Endpoint { get; set; } -} - - -using System; + public class Derived : Base + { + public Uri En[||]dpoint { get; set; } + } + + + + """, """ + + + using System; + + public class Base + { + public Uri Endpoint { get; set; } + } + + + using System; -public class Derived : Base -{ -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Derived : Base + { + } + + + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullPropertyToClassWithAddUsingsViaQuickAction2() - { - var testText = @" - - - public class Base -{ -} - - -using System; + public Task TestPullPropertyToClassWithoutDuplicatingUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + using System; + + public class Base + { + } + + + using System; -public class Derived : Base -{ - public Uri En[||]dpoint { get; set; } -} - - - -"; - var expected = @" - - - using System; - -public class Base -{ - public Uri Endpoint { get; set; } -} - - -using System; + public class Derived : Base + { + public Uri En[||]dpoint { get; set; } + } + + + + """, """ + + + + using System; + + public class Base + { + public Uri Endpoint { get; set; } + } + + + using System; -public class Derived : Base -{ -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Derived : Base + { + } + + + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullPropertyToClassWithoutDuplicatingUsingsViaQuickAction() - { - var testText = @" - - - -using System; - -public class Base -{ -} - - -using System; + public Task TestPullPropertyWithNewBodyTypeToClassWithAddUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + public class Base + { + } + + + using System; -public class Derived : Base -{ - public Uri En[||]dpoint { get; set; } -} - - - -"; - var expected = @" - - - -using System; - -public class Base -{ - public Uri Endpoint { get; set; } -} - - -using System; + public class Derived : Base + { + public bool Test[||]Property + { + get + { + var endpoint1 = new Uri("http://localhost"); + var endpoint2 = new Uri("http://localhost"); + return endpoint1.Equals(endpoint2); + } + } + } + + + + """, """ + + + using System; + + public class Base + { + public bool TestProperty + { + get + { + var endpoint1 = new Uri("http://localhost"); + var endpoint2 = new Uri("http://localhost"); + return endpoint1.Equals(endpoint2); + } + } + } + + + using System; -public class Derived : Base -{ -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Derived : Base + { + } + + + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullPropertyWithNewBodyTypeToClassWithAddUsingsViaQuickAction() - { - var testText = @" - - - -public class Base -{ -} - - -using System; + public Task TestPullMethodWithNewNonDeclaredBodyTypeToClassWithAddUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + public class Base + { + } + + + using System.Linq; -public class Derived : Base -{ - public bool Test[||]Property - { - get - { - var endpoint1 = new Uri(""http://localhost""); - var endpoint2 = new Uri(""http://localhost""); - return endpoint1.Equals(endpoint2); - } - } -} - - - -"; - var expected = @" - - - using System; - -public class Base -{ - public bool TestProperty - { - get - { - var endpoint1 = new Uri(""http://localhost""); - var endpoint2 = new Uri(""http://localhost""); - return endpoint1.Equals(endpoint2); - } - } -} - - -using System; + public class Derived : Base + { + public int Test[||]Method() + { + return Enumerable.Range(0, 5).Sum(); + } + } + + + + """, """ + + + using System.Linq; + + public class Base + { + public int Test[||]Method() + { + return Enumerable.Range(0, 5).Sum(); + } + } + + + using System.Linq; -public class Derived : Base -{ -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Derived : Base + { + } + + + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodWithNewNonDeclaredBodyTypeToClassWithAddUsingsViaQuickAction() - { - var testText = @" - - - -public class Base -{ -} - - -using System.Linq; + public Task TestPullMethodToClassWithOverlappingUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + using System; + using System.Threading.Tasks; + + public class Base + { + public Uri Endpoint{ get; set; } -public class Derived : Base -{ - public int Test[||]Method() - { - return Enumerable.Range(0, 5).Sum(); - } -} - - - -"; - var expected = @" - - - using System.Linq; - -public class Base -{ - public int Test[||]Method() - { - return Enumerable.Range(0, 5).Sum(); - } -} - - -using System.Linq; + public async Task<int> Get5Async() + { + return 5; + } + } + + + using System.Linq; + using System.Threading.Tasks; -public class Derived : Base -{ -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Derived : Base + { + public async Task<int> Test[||]Method() + { + return Enumerable.Range(0, 5).Sum(); + } + } + + + + """, """ + + + + using System; + using System.Linq; + using System.Threading.Tasks; + + public class Base + { + public Uri Endpoint{ get; set; } - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodToClassWithOverlappingUsingsViaQuickAction() - { - var testText = @" - - - -using System; -using System.Threading.Tasks; + public async Task<int> Get5Async() + { + return 5; + } + public async Task<int> Test[||]Method() + { + return Enumerable.Range(0, 5).Sum(); + } + } + + + using System.Linq; + using System.Threading.Tasks; -public class Base -{ - public Uri Endpoint{ get; set; } + public class Derived : Base + { + } + + + + """); - public async Task<int> Get5Async() - { - return 5; - } -} - - -using System.Linq; -using System.Threading.Tasks; + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] + public Task TestPullMethodToClassWithUnnecessaryFirstUsingViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + -public class Derived : Base -{ - public async Task<int> Test[||]Method() - { - return Enumerable.Range(0, 5).Sum(); - } -} - - - -"; - var expected = @" - - - -using System; -using System.Linq; -using System.Threading.Tasks; + using System.Threading.Tasks; -public class Base -{ - public Uri Endpoint{ get; set; } + public class Base + { + public async Task<int> Get5Async() + { + return 5; + } + } + + + using System; + using System.Linq; + using System.Threading.Tasks; - public async Task<int> Get5Async() - { - return 5; - } - public async Task<int> Test[||]Method() - { - return Enumerable.Range(0, 5).Sum(); - } -} - - -using System.Linq; -using System.Threading.Tasks; + public class Derived : Base + { + public async Task<int> Test[||]Method() + { + return Enumerable.Range(0, 5).Sum(); + } + } + + + + """, """ + + + using System.Linq; + using System.Threading.Tasks; + + public class Base + { + public async Task<int> Get5Async() + { + return 5; + } + public async Task<int> Test[||]Method() + { + return Enumerable.Range(0, 5).Sum(); + } + } + + + using System; + using System.Linq; + using System.Threading.Tasks; -public class Derived : Base -{ -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Derived : Base + { + } + + + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodToClassWithUnnecessaryFirstUsingViaQuickAction() - { - var testText = @" - - - + public Task TestPullMethodToClassWithUnusedBaseUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + using System; + using System.Threading.Tasks; + + public class Base + { + public Uri Endpoint{ get; set; } + } + + + using System.Linq; -using System.Threading.Tasks; + public class Derived : Base + { + public int Test[||]Method() + { + return Enumerable.Range(0, 5).Sum(); + } + } + + + + """, """ + + + + using System; + using System.Linq; + using System.Threading.Tasks; + + public class Base + { + public Uri Endpoint{ get; set; } + public int TestMethod() + { + return Enumerable.Range(0, 5).Sum(); + } + } + + + using System.Linq; -public class Base -{ - public async Task<int> Get5Async() - { - return 5; - } -} - - -using System; -using System.Linq; -using System.Threading.Tasks; + public class Derived : Base + { + } + + + + """); -public class Derived : Base -{ - public async Task<int> Test[||]Method() - { - return Enumerable.Range(0, 5).Sum(); - } -} - - - -"; - var expected = @" - - - using System.Linq; -using System.Threading.Tasks; + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] + public Task TestPullMethodToClassWithRetainCommentsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + // blah blah + + public class Base + { + } + + + using System.Linq; -public class Base -{ - public async Task<int> Get5Async() - { - return 5; - } - public async Task<int> Test[||]Method() - { - return Enumerable.Range(0, 5).Sum(); - } -} - - -using System; -using System.Linq; -using System.Threading.Tasks; + public class Derived : Base + { + public int Test[||]Method() + { + return 5; + } + } + + + + """, """ + + + + // blah blah + + public class Base + { + public int TestMethod() + { + return 5; + } + } + + + using System.Linq; -public class Derived : Base -{ -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Derived : Base + { + } + + + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodToClassWithUnusedBaseUsingsViaQuickAction() - { - var testText = @" - - - -using System; -using System.Threading.Tasks; + public Task TestPullMethodToClassWithRetainPreImportCommentsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + // blah blah + using System.Linq; + + public class Base + { + } + + + using System; -public class Base -{ - public Uri Endpoint{ get; set; } -} - - -using System.Linq; + public class Derived : Base + { + public Uri End[||]point { get; set; } + } + + + + """, """ + + + + // blah blah + using System; + using System.Linq; + + public class Base + { + public Uri Endpoint { get; set; } + } + + + using System; -public class Derived : Base -{ - public int Test[||]Method() - { - return Enumerable.Range(0, 5).Sum(); - } -} - - - -"; - var expected = @" - - - -using System; -using System.Linq; -using System.Threading.Tasks; + public class Derived : Base + { + } + + + + """); -public class Base -{ - public Uri Endpoint{ get; set; } - public int TestMethod() - { - return Enumerable.Range(0, 5).Sum(); - } -} - - -using System.Linq; + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] + public Task TestPullMethodToClassWithRetainPostImportCommentsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + using System.Linq; + + // blah blah + public class Base + { + } + + + using System; -public class Derived : Base -{ -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Derived : Base + { + public Uri End[||]point { get; set; } + } + + + + """, """ + + + + using System; + using System.Linq; + + // blah blah + public class Base + { + public Uri Endpoint { get; set; } + } + + + using System; - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodToClassWithRetainCommentsViaQuickAction() - { - var testText = @" - - - -// blah blah + public class Derived : Base + { + } + + + + """); -public class Base -{ -} - - -using System.Linq; + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] + public Task TestPullMethodToClassWithLambdaUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + public class Base + { + } + + + using System; + using System.Linq; -public class Derived : Base -{ - public int Test[||]Method() - { - return 5; - } -} - - - -"; - var expected = @" - - - -// blah blah - -public class Base -{ - public int TestMethod() - { - return 5; - } -} - - -using System.Linq; + public class Derived : Base + { + public int Test[||]Method() + { + return Enumerable.Range(0, 5). + Select((n) => new Uri("http://" + n)). + Count((uri) => uri != null); + } + } + + + + """, """ + + + using System; + using System.Linq; + + public class Base + { + public int TestMethod() + { + return Enumerable.Range(0, 5). + Select((n) => new Uri("http://" + n)). + Count((uri) => uri != null); + } + } + + + using System; + using System.Linq; -public class Derived : Base -{ -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Derived : Base + { + } + + + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodToClassWithRetainPreImportCommentsViaQuickAction() - { - var testText = @" - - - -// blah blah -using System.Linq; + public Task TestPullMethodToClassWithUnusedUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + using System; + + public class Base + { + public Uri Endpoint{ get; set; } + } + + + using System.Linq; + using System.Threading.Tasks; -public class Base -{ -} - - -using System; + public class Derived : Base + { + public int Test[||]Method() + { + return Enumerable.Range(0, 5).Sum(); + } + } + + + + """, """ + + + + using System; + using System.Linq; + + public class Base + { + public Uri Endpoint{ get; set; } + public int TestMethod() + { + return Enumerable.Range(0, 5).Sum(); + } + } + + + using System.Linq; + using System.Threading.Tasks; -public class Derived : Base -{ - public Uri End[||]point { get; set; } -} - - - -"; - var expected = @" - - - -// blah blah -using System; -using System.Linq; + public class Derived : Base + { + } + + + + """); -public class Base -{ - public Uri Endpoint { get; set; } -} - - -using System; + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] + public Task TestPullMethodToClassKeepSystemFirstViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + namespace TestNs1 + { + using System; -public class Derived : Base -{ -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Base + { + public Uri Endpoint{ get; set; } + } + } + + + namespace A_TestNs2 + { + using TestNs1; - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodToClassWithRetainPostImportCommentsViaQuickAction() - { - var testText = @" - - - -using System.Linq; + public class Derived : Base + { + public Foo Test[||]Method() + { + return null; + } + } -// blah blah -public class Base -{ -} - - -using System; + public class Foo + { + } + } + + + + """, """ + + + + namespace TestNs1 + { + using System; + using A_TestNs2; -public class Derived : Base -{ - public Uri End[||]point { get; set; } -} - - - -"; - var expected = @" - - - -using System; -using System.Linq; + public class Base + { + public Uri Endpoint{ get; set; } + public Foo TestMethod() + { + return null; + } + } + } + + + namespace A_TestNs2 + { + using TestNs1; -// blah blah -public class Base -{ - public Uri Endpoint { get; set; } -} - - -using System; + public class Derived : Base + { + } -public class Derived : Base -{ -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Foo + { + } + } + + + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodToClassWithLambdaUsingsViaQuickAction() - { - var testText = @" - - - -public class Base -{ -} - - -using System; -using System.Linq; + public Task TestPullMethodToClassKeepSystemFirstViaQuickAction2() + => TestWithPullMemberDialogAsync(""" + + + + namespace TestNs1 + { + public class Base + { + } + } + + + namespace A_TestNs2 + { + using System; + using TestNs1; -public class Derived : Base -{ - public int Test[||]Method() - { - return Enumerable.Range(0, 5). - Select((n) => new Uri(""http://"" + n)). - Count((uri) => uri != null); - } -} - - - -"; - var expected = @" - - - using System; -using System.Linq; + public class Derived : Base + { + public Foo Test[||]Method() + { + var uri = new Uri("http://localhost"); + return null; + } + } -public class Base -{ - public int TestMethod() - { - return Enumerable.Range(0, 5). - Select((n) => new Uri(""http://"" + n)). - Count((uri) => uri != null); - } -} - - -using System; -using System.Linq; + public class Foo + { + } + } + + + + """, """ + + + using System; + using A_TestNs2; + + namespace TestNs1 + { + public class Base + { + public Foo TestMethod() + { + var uri = new Uri("http://localhost"); + return null; + } + } + } + + + namespace A_TestNs2 + { + using System; + using TestNs1; -public class Derived : Base -{ -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Derived : Base + { + } + + public class Foo + { + } + } + + + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodToClassWithUnusedUsingsViaQuickAction() - { - var testText = @" - - - -using System; + public Task TestPullMethodToClassWithExtensionViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + namespace TestNs1 + { + public class Base + { + } -public class Base -{ - public Uri Endpoint{ get; set; } -} - - -using System.Linq; -using System.Threading.Tasks; + public class Foo + { + } + } + + + namespace TestNs2 + { + using TestNs1; -public class Derived : Base -{ - public int Test[||]Method() - { - return Enumerable.Range(0, 5).Sum(); - } -} - - - -"; - var expected = @" - - - -using System; -using System.Linq; + public class Derived : Base + { + public int Test[||]Method() + { + var foo = new Foo(); + return foo.FooBar(); + } + } -public class Base -{ - public Uri Endpoint{ get; set; } - public int TestMethod() - { - return Enumerable.Range(0, 5).Sum(); - } -} - - -using System.Linq; -using System.Threading.Tasks; + public static class FooExtensions + { + public static int FooBar(this Foo foo) + { + return 5; + } + } + } + + + + """, """ + + + using TestNs2; + + namespace TestNs1 + { + public class Base + { + public int TestMethod() + { + var foo = new Foo(); + return foo.FooBar(); + } + } -public class Derived : Base -{ -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Foo + { + } + } + + + namespace TestNs2 + { + using TestNs1; - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodToClassKeepSystemFirstViaQuickAction() - { - var testText = @" - - - -namespace TestNs1 -{ - using System; + public class Derived : Base + { + } - public class Base - { - public Uri Endpoint{ get; set; } - } -} - - -namespace A_TestNs2 -{ - using TestNs1; + public static class FooExtensions + { + public static int FooBar(this Foo foo) + { + return 5; + } + } + } + + + + """); - public class Derived : Base - { - public Foo Test[||]Method() - { - return null; - } - } + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] + public Task TestPullMethodToClassWithExtensionViaQuickAction2() + => TestWithPullMemberDialogAsync(""" + + + + namespace TestNs1 + { + public class Base + { + } + } + + + using TestNs1; + using TestNs3; + using TestNs4; - public class Foo - { - } -} - - - -"; - var expected = @" - - - -namespace TestNs1 -{ - using System; - using A_TestNs2; + namespace TestNs2 + { + public class Derived : Base + { + public int Test[||]Method() + { + var foo = new Foo(); + return foo.FooBar(); + } + } + } + + + namespace TestNs3 + { + public class Foo + { + } + } + + + using TestNs3; - public class Base - { - public Uri Endpoint{ get; set; } - public Foo TestMethod() - { - return null; - } - } -} - - -namespace A_TestNs2 -{ - using TestNs1; + namespace TestNs4 + { + public static class FooExtensions + { + public static int FooBar(this Foo foo) + { + return 5; + } + } + } + + + + """, """ + + + using TestNs3; + using TestNs4; + + namespace TestNs1 + { + public class Base + { + public int TestMethod() + { + var foo = new Foo(); + return foo.FooBar(); + } + } + } + + + using TestNs1; + using TestNs3; + using TestNs4; - public class Derived : Base - { - } + namespace TestNs2 + { + public class Derived : Base + { + } + } + + + namespace TestNs3 + { + public class Foo + { + } + } + + + using TestNs3; - public class Foo - { - } -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + namespace TestNs4 + { + public static class FooExtensions + { + public static int FooBar(this Foo foo) + { + return 5; + } + } + } + + + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodToClassKeepSystemFirstViaQuickAction2() - { - var testText = @" - - - -namespace TestNs1 -{ - public class Base - { - } -} - - -namespace A_TestNs2 -{ - using System; - using TestNs1; + public Task TestPullMethodToClassWithAliasUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + using System; + + public class Base + { + public Uri Endpoint{ get; set; } + } + + + using Enumer = System.Linq.Enumerable; + using Sys = System; - public class Derived : Base - { - public Foo Test[||]Method() - { - var uri = new Uri(""http://localhost""); - return null; - } - } - - public class Foo - { - } -} - - - -"; - var expected = @" - - - using System; -using A_TestNs2; - -namespace TestNs1 -{ - public class Base - { - public Foo TestMethod() - { - var uri = new Uri(""http://localhost""); - return null; - } - } -} - - -namespace A_TestNs2 -{ - using System; - using TestNs1; - - public class Derived : Base - { - } - - public class Foo - { - } -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } - - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodToClassWithExtensionViaQuickAction() - { - var testText = @" - - - -namespace TestNs1 -{ - public class Base - { - } - - public class Foo - { - } -} - - -namespace TestNs2 -{ - using TestNs1; - - public class Derived : Base - { - public int Test[||]Method() - { - var foo = new Foo(); - return foo.FooBar(); - } - } - - public static class FooExtensions - { - public static int FooBar(this Foo foo) - { - return 5; - } - } -} - - - -"; - var expected = @" - - - using TestNs2; - -namespace TestNs1 -{ - public class Base - { - public int TestMethod() - { - var foo = new Foo(); - return foo.FooBar(); - } - } - - public class Foo - { - } -} - - -namespace TestNs2 -{ - using TestNs1; - - public class Derived : Base - { - } - - public static class FooExtensions - { - public static int FooBar(this Foo foo) - { - return 5; - } - } -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } - - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodToClassWithExtensionViaQuickAction2() - { - var testText = @" - - - -namespace TestNs1 -{ - public class Base - { - } -} - - -using TestNs1; -using TestNs3; -using TestNs4; - -namespace TestNs2 -{ - public class Derived : Base - { - public int Test[||]Method() - { - var foo = new Foo(); - return foo.FooBar(); - } - } -} - - -namespace TestNs3 -{ - public class Foo - { - } -} - - -using TestNs3; - -namespace TestNs4 -{ - public static class FooExtensions - { - public static int FooBar(this Foo foo) - { - return 5; - } - } -} - - - -"; - var expected = @" - - - using TestNs3; -using TestNs4; - -namespace TestNs1 -{ - public class Base - { - public int TestMethod() - { - var foo = new Foo(); - return foo.FooBar(); - } - } -} - - -using TestNs1; -using TestNs3; -using TestNs4; - -namespace TestNs2 -{ - public class Derived : Base - { - } -} - - -namespace TestNs3 -{ - public class Foo - { - } -} - - -using TestNs3; - -namespace TestNs4 -{ - public static class FooExtensions - { - public static int FooBar(this Foo foo) - { - return 5; - } - } -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } - - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodToClassWithAliasUsingsViaQuickAction() - { - var testText = @" - - - -using System; - -public class Base -{ - public Uri Endpoint{ get; set; } -} - - -using Enumer = System.Linq.Enumerable; -using Sys = System; - -public class Derived : Base -{ - public void Test[||]Method() - { - Sys.Console.WriteLine(Enumer.Range(0, 5).Sum()); - } -} - - - -"; - var expected = @" - - - -using System; -using Enumer = System.Linq.Enumerable; -using Sys = System; - -public class Base -{ - public Uri Endpoint{ get; set; } - public void TestMethod() - { - Sys.Console.WriteLine(Enumer.Range(0, 5).Sum()); - } -} - - -using Enumer = System.Linq.Enumerable; -using Sys = System; - -public class Derived : Base -{ -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } - - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullPropertyToClassWithBaseAliasUsingsViaQuickAction() - { - var testText = @" - - - -using Enumer = System.Linq.Enumerable; - -public class Base -{ - public void TestMethod() - { - System.Console.WriteLine(Enumer.Range(0, 5).Sum()); - } -} - - -using System; - -public class Derived : Base -{ - public Uri End[||]point{ get; set; } -} - - - -"; - var expected = @" - - - -using System; -using Enumer = System.Linq.Enumerable; - -public class Base -{ - public Uri Endpoint{ get; set; } - public void TestMethod() - { - System.Console.WriteLine(Enumer.Range(0, 5).Sum()); - } -} - - -using System; - -public class Derived : Base -{ -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } - - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodToClassWithMultipleNamespacedUsingsViaQuickAction() - { - var testText = @" -namespace TestNs1 -{ - using System; - - public class Base - { - public Uri Endpoint{ get; set; } - } -} -namespace TestNs2 -{ - using System.Linq; - using TestNs1; - - public class Derived : Base - { - public int Test[||]Method() - { - return Enumerable.Range(0, 5).Sum(); - } - } -} -"; - var expected = @" -namespace TestNs1 -{ - using System; - using System.Linq; - - public class Base - { - public Uri Endpoint{ get; set; } - public int TestMethod() - { - return Enumerable.Range(0, 5).Sum(); - } - } -} -namespace TestNs2 -{ - using System.Linq; - using TestNs1; + public class Derived : Base + { + public void Test[||]Method() + { + Sys.Console.WriteLine(Enumer.Range(0, 5).Sum()); + } + } + + + + """, """ + + + + using System; + using Enumer = System.Linq.Enumerable; + using Sys = System; + + public class Base + { + public Uri Endpoint{ get; set; } + public void TestMethod() + { + Sys.Console.WriteLine(Enumer.Range(0, 5).Sum()); + } + } + + + using Enumer = System.Linq.Enumerable; + using Sys = System; - public class Derived : Base - { - } -} -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Derived : Base + { + } + + + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodToClassWithNestedNamespacedUsingsViaQuickAction() - { - var testText = @" -namespace TestNs1 -{ - namespace InnerNs1 - { - using System; - - public class Base - { - public Uri Endpoint { get; set; } - } - } -} -namespace TestNs2 -{ - namespace InnerNs2 - { - using System.Linq; - using TestNs1.InnerNs1; - - public class Derived : Base - { - public int Test[||]Method() + public Task TestPullPropertyToClassWithBaseAliasUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + using Enumer = System.Linq.Enumerable; + + public class Base { - return Foo.Bar(Enumerable.Range(0, 5).Sum()); + public void TestMethod() + { + System.Console.WriteLine(Enumer.Range(0, 5).Sum()); + } } - } + + + using System; - public class Foo - { - public static int Bar(int num) + public class Derived : Base { - return num + 1; + public Uri End[||]point{ get; set; } } - } - } -} -"; - var expected = @" -namespace TestNs1 -{ - namespace InnerNs1 - { - using System; - using System.Linq; - using TestNs2.InnerNs2; - - public class Base - { - public Uri Endpoint { get; set; } - public int TestMethod() + + + + """, """ + + + + using System; + using Enumer = System.Linq.Enumerable; + + public class Base { - return Foo.Bar(Enumerable.Range(0, 5).Sum()); + public Uri Endpoint{ get; set; } + public void TestMethod() + { + System.Console.WriteLine(Enumer.Range(0, 5).Sum()); + } } - } - } -} -namespace TestNs2 -{ - namespace InnerNs2 - { - using System.Linq; - using TestNs1.InnerNs1; - - public class Derived : Base - { - } + + + using System; - public class Foo - { - public static int Bar(int num) + public class Derived : Base { - return num + 1; } - } - } -} -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + + + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodToClassWithNewNamespaceUsingViaQuickAction() - { - var testText = @" - - - -namespace A.B -{ - class Base - { - } -} - - -namespace X.Y -{ - class Derived : A.B.Base - { - public Other Get[||]Other() => null; - } - - class Other - { - } -} - - - -"; - var expected = @" - - - using X.Y; - -namespace A.B -{ - class Base - { - public Other GetOther() => null; - } -} - - -namespace X.Y -{ - class Derived : A.B.Base - { - } - - class Other - { - } -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public Task TestPullMethodToClassWithMultipleNamespacedUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + namespace TestNs1 + { + using System; - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodToClassWithFileNamespaceUsingViaQuickAction() - { - var testText = @" - - - -namespace A.B; + public class Base + { + public Uri Endpoint{ get; set; } + } + } + namespace TestNs2 + { + using System.Linq; + using TestNs1; -class Base -{ -} - - -namespace X.Y; -class Derived : A.B.Base -{ - public Other Get[||]Other() => null; -} + public class Derived : Base + { + public int Test[||]Method() + { + return Enumerable.Range(0, 5).Sum(); + } + } + } + """, """ + namespace TestNs1 + { + using System; + using System.Linq; -class Other -{ -} - - - -"; - var expected = @" - - - using X.Y; - -namespace A.B; - -class Base -{ - public Other GetOther() => null; -} - - -namespace X.Y; -class Derived : A.B.Base -{ -} + public class Base + { + public Uri Endpoint{ get; set; } + public int TestMethod() + { + return Enumerable.Range(0, 5).Sum(); + } + } + } + namespace TestNs2 + { + using System.Linq; + using TestNs1; -class Other -{ -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Derived : Base + { + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodToClassWithUnusedNamespaceUsingViaQuickAction() - { - var testText = @" - - - -namespace A.B -{ - class Base - { - } -} - - -namespace X.Y -{ - class Derived : A.B.Base - { - public int Get[||]Five() => 5; - } - - class Other - { - } -} - - - -"; - var expected = @" - - - -namespace A.B -{ - class Base - { - public int GetFive() => 5; - } -} - - -namespace X.Y -{ - class Derived : A.B.Base - { - } + public Task TestPullMethodToClassWithNestedNamespacedUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + namespace TestNs1 + { + namespace InnerNs1 + { + using System; - class Other - { - } -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Base + { + public Uri Endpoint { get; set; } + } + } + } + namespace TestNs2 + { + namespace InnerNs2 + { + using System.Linq; + using TestNs1.InnerNs1; + + public class Derived : Base + { + public int Test[||]Method() + { + return Foo.Bar(Enumerable.Range(0, 5).Sum()); + } + } + + public class Foo + { + public static int Bar(int num) + { + return num + 1; + } + } + } + } + """, """ + namespace TestNs1 + { + namespace InnerNs1 + { + using System; + using System.Linq; + using TestNs2.InnerNs2; + + public class Base + { + public Uri Endpoint { get; set; } + public int TestMethod() + { + return Foo.Bar(Enumerable.Range(0, 5).Sum()); + } + } + } + } + namespace TestNs2 + { + namespace InnerNs2 + { + using System.Linq; + using TestNs1.InnerNs1; + + public class Derived : Base + { + } + + public class Foo + { + public static int Bar(int num) + { + return num + 1; + } + } + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodToClassWithMultipleNamespacesAndCommentsViaQuickAction() - { - var testText = @" -// comment 1 - -namespace TestNs1 -{ - // comment 2 - - // comment 3 - public class Base - { - } -} -namespace TestNs2 -{ - // comment 4 - using System.Linq; - using TestNs1; - - public class Derived : Base - { - public int Test[||]Method() - { - return 5; - } - } -} -"; - var expected = @" -// comment 1 - -namespace TestNs1 -{ - // comment 2 + public Task TestPullMethodToClassWithNewNamespaceUsingViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + namespace A.B + { + class Base + { + } + } + + + namespace X.Y + { + class Derived : A.B.Base + { + public Other Get[||]Other() => null; + } - // comment 3 - public class Base - { - public int TestMethod() - { - return 5; - } - } -} -namespace TestNs2 -{ - // comment 4 - using System.Linq; - using TestNs1; + class Other + { + } + } + + + + """, """ + + + using X.Y; + + namespace A.B + { + class Base + { + public Other GetOther() => null; + } + } + + + namespace X.Y + { + class Derived : A.B.Base + { + } - public class Derived : Base - { - } -} -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + class Other + { + } + } + + + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodToClassWithMultipleNamespacedUsingsAndCommentsViaQuickAction() - { - var testText = @" -// comment 1 - -namespace TestNs1 -{ - // comment 2 - using System; - - // comment 3 - public class Base - { - } -} -namespace TestNs2 -{ - // comment 4 - using System.Linq; - using TestNs1; + public Task TestPullMethodToClassWithFileNamespaceUsingViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + namespace A.B; + + class Base + { + } + + + namespace X.Y; + class Derived : A.B.Base + { + public Other Get[||]Other() => null; + } - public class Derived : Base - { - public int Test[||]Method() - { - return Enumerable.Range(0, 5).Sum(); - } - } -} -"; - var expected = @" -// comment 1 + class Other + { + } + + + + """, """ + + + using X.Y; -namespace TestNs1 -{ - // comment 2 - using System; - using System.Linq; + namespace A.B; - // comment 3 - public class Base - { - public int TestMethod() - { - return Enumerable.Range(0, 5).Sum(); - } - } -} -namespace TestNs2 -{ - // comment 4 - using System.Linq; - using TestNs1; + class Base + { + public Other GetOther() => null; + } + + + namespace X.Y; + class Derived : A.B.Base + { + } - public class Derived : Base - { - } -} -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + class Other + { + } + + + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodToClassWithNamespacedUsingsViaQuickAction() - { - var testText = @" - - - -namespace ClassLibrary1 -{ - using System; - - public class Base - { - public Uri Endpoint{ get; set; } - } -} - - -namespace ClassLibrary1 -{ - using System.Linq; - - public class Derived : Base - { - public int Test[||]Method() - { - return Enumerable.Range(0, 5).Sum(); - } - } -} - - - -"; - var expected = @" - - - -namespace ClassLibrary1 -{ - using System; - using System.Linq; + public Task TestPullMethodToClassWithUnusedNamespaceUsingViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + namespace A.B + { + class Base + { + } + } + + + namespace X.Y + { + class Derived : A.B.Base + { + public int Get[||]Five() => 5; + } - public class Base - { - public Uri Endpoint{ get; set; } - public int Test[||]Method() - { - return Enumerable.Range(0, 5).Sum(); - } - } -} - - -namespace ClassLibrary1 -{ - using System.Linq; + class Other + { + } + } + + + + """, """ + + + + namespace A.B + { + class Base + { + public int GetFive() => 5; + } + } + + + namespace X.Y + { + class Derived : A.B.Base + { + } - public class Derived : Base - { - } -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + class Other + { + } + } + + + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodToClassWithDuplicateNamespacedUsingsViaQuickAction() - { - var testText = @" - - - -namespace ClassLibrary1 -{ - using System; - - public class Base - { - public Uri Endpoint{ get; set; } - } -} - - -using System.Linq; -namespace ClassLibrary1 -{ - using System.Linq; - - public class Derived : Base - { - public int Test[||]Method() - { - return Enumerable.Range(0, 5).Sum(); - } - } -} - - - -"; - var expected = @" - - - -namespace ClassLibrary1 -{ - using System; - using System.Linq; - - public class Base - { - public Uri Endpoint{ get; set; } - public int Test[||]Method() - { - return Enumerable.Range(0, 5).Sum(); - } - } -} - - -using System.Linq; -namespace ClassLibrary1 -{ - using System.Linq; - - public class Derived : Base - { - } -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public Task TestPullMethodToClassWithMultipleNamespacesAndCommentsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + // comment 1 - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodWithNewReturnTypeToClassWithAddUsingsViaQuickAction() - { - var testText = @" - - - -public class Base -{ -} - - -using System; + namespace TestNs1 + { + // comment 2 -public class Derived : Base -{ - public Uri En[||]dpoint() - { - return new Uri(""http://localhost""); - } -} - - - -"; - var expected = @" - - - using System; - -public class Base -{ - public Uri Endpoint() - { - return new Uri(""http://localhost""); - } -} - - -using System; + // comment 3 + public class Base + { + } + } + namespace TestNs2 + { + // comment 4 + using System.Linq; + using TestNs1; -public class Derived : Base -{ -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Derived : Base + { + public int Test[||]Method() + { + return 5; + } + } + } + """, """ + // comment 1 - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodWithNewParamTypeToClassWithAddUsingsViaQuickAction() - { - var testText = @" - - - -public class Base -{ -} - - -using System; + namespace TestNs1 + { + // comment 2 -public class Derived : Base -{ - public bool Test[||]Method(Uri endpoint) - { - var localHost = new Uri(""http://localhost""); - return endpoint.Equals(localhost); - } -} - - - -"; - var expected = @" - - - using System; - -public class Base -{ - public bool TestMethod(Uri endpoint) - { - var localHost = new Uri(""http://localhost""); - return endpoint.Equals(localhost); - } -} - - -using System; + // comment 3 + public class Base + { + public int TestMethod() + { + return 5; + } + } + } + namespace TestNs2 + { + // comment 4 + using System.Linq; + using TestNs1; -public class Derived : Base -{ -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Derived : Base + { + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullMethodWithNewBodyTypeToClassWithAddUsingsViaQuickAction() - { - var testText = @" - - - -public class Base -{ -} - - -using System; + public Task TestPullMethodToClassWithMultipleNamespacedUsingsAndCommentsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + // comment 1 -public class Derived : Base -{ - public bool Test[||]Method() - { - var endpoint1 = new Uri(""http://localhost""); - var endpoint2 = new Uri(""http://localhost""); - return endpoint1.Equals(endpoint2); - } -} - - - -"; - var expected = @" - - - using System; - -public class Base -{ - public bool TestMethod() - { - var endpoint1 = new Uri(""http://localhost""); - var endpoint2 = new Uri(""http://localhost""); - return endpoint1.Equals(endpoint2); - } -} - - -using System; + namespace TestNs1 + { + // comment 2 + using System; -public class Derived : Base -{ -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + // comment 3 + public class Base + { + } + } + namespace TestNs2 + { + // comment 4 + using System.Linq; + using TestNs1; - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullEventToClassWithAddUsingsViaQuickAction() - { - var testText = @" - - - -public class Base -{ -} - - -using System; + public class Derived : Base + { + public int Test[||]Method() + { + return Enumerable.Range(0, 5).Sum(); + } + } + } + """, """ + // comment 1 -public class Derived : Base -{ - public event EventHandler Test[||]Event - { - add - { - Console.WriteLine(""adding event...""); - } - remove - { - Console.WriteLine(""removing event...""); - } - } -} - - - -"; - var expected = @" - - - using System; - -public class Base -{ - public event EventHandler Test[||]Event - { - add - { - Console.WriteLine(""adding event...""); - } - remove - { - Console.WriteLine(""removing event...""); - } - } -} - - -using System; + namespace TestNs1 + { + // comment 2 + using System; + using System.Linq; -public class Derived : Base -{ -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + // comment 3 + public class Base + { + public int TestMethod() + { + return Enumerable.Range(0, 5).Sum(); + } + } + } + namespace TestNs2 + { + // comment 4 + using System.Linq; + using TestNs1; + + public class Derived : Base + { + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullFieldToClassWithAddUsingsViaQuickAction() - { - var testText = @" - - - -public class Base -{ -} - - -using System; + public Task TestPullMethodToClassWithNamespacedUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + namespace ClassLibrary1 + { + using System; -public class Derived : Base -{ - public var en[||]dpoint = new Uri(""http://localhost""); -} - - - -"; - var expected = @" - - - using System; - -public class Base -{ - public var endpoint = new Uri(""http://localhost""); -} - - -using System; + public class Base + { + public Uri Endpoint{ get; set; } + } + } + + + namespace ClassLibrary1 + { + using System.Linq; -public class Derived : Base -{ -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Derived : Base + { + public int Test[||]Method() + { + return Enumerable.Range(0, 5).Sum(); + } + } + } + + + + """, """ + + + + namespace ClassLibrary1 + { + using System; + using System.Linq; + + public class Base + { + public Uri Endpoint{ get; set; } + public int Test[||]Method() + { + return Enumerable.Range(0, 5).Sum(); + } + } + } + + + namespace ClassLibrary1 + { + using System.Linq; + + public class Derived : Base + { + } + } + + + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] - public async Task TestPullFieldToClassNoConstructorWithAddUsingsViaQuickAction() - { - var testText = @" - - - -public class Base -{ -} - - -using System.Linq; + public Task TestPullMethodToClassWithDuplicateNamespacedUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + namespace ClassLibrary1 + { + using System; -public class Derived : Base -{ - public var ran[||]ge = Enumerable.Range(0, 5); -} - - - -"; - var expected = @" - - - using System.Linq; - -public class Base -{ - public var range = Enumerable.Range(0, 5); -} - - -using System.Linq; + public class Base + { + public Uri Endpoint{ get; set; } + } + } + + + using System.Linq; + namespace ClassLibrary1 + { + using System.Linq; -public class Derived : Base -{ -} - - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Derived : Base + { + public int Test[||]Method() + { + return Enumerable.Range(0, 5).Sum(); + } + } + } + + + + """, """ + + + + namespace ClassLibrary1 + { + using System; + using System.Linq; - [Fact] - public async Task TestNoRefactoringProvidedWhenPullOverrideMethodUpToClassViaQuickAction() - { - var methodTest = @" -namespace PushUpTest -{ - public class Base - { - public virtual void TestMethod() => System.Console.WriteLine(""foo bar bar foo""); - } + public class Base + { + public Uri Endpoint{ get; set; } + public int Test[||]Method() + { + return Enumerable.Range(0, 5).Sum(); + } + } + } + + + using System.Linq; + namespace ClassLibrary1 + { + using System.Linq; - public class TestClass : Base - { - public override void TestMeth[||]od() - { - System.Console.WriteLine(""Hello World""); - } - } -}"; - await TestQuickActionNotProvidedAsync(methodTest); - } + public class Derived : Base + { + } + } + + + + """); - [Fact] - public async Task TestNoRefactoringProvidedWhenPullOverridePropertyUpToClassViaQuickAction() - { - var propertyTest = @" -using System; -namespace PushUpTest -{ - public class Base - { - public virtual int TestProperty { get => 111; private set; } - } + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] + public Task TestPullMethodWithNewReturnTypeToClassWithAddUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + public class Base + { + } + + + using System; - public class TestClass : Base - { - public override int TestPr[||]operty { get; private set; } - } -}"; + public class Derived : Base + { + public Uri En[||]dpoint() + { + return new Uri("http://localhost"); + } + } + + + + """, """ + + + using System; + + public class Base + { + public Uri Endpoint() + { + return new Uri("http://localhost"); + } + } + + + using System; - await TestQuickActionNotProvidedAsync(propertyTest); - } + public class Derived : Base + { + } + + + + """); - [Fact] - public async Task TestNoRefactoringProvidedWhenPullOverrideEventUpToClassViaQuickAction() - { - var eventTest = @" -using System; + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] + public Task TestPullMethodWithNewParamTypeToClassWithAddUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + public class Base + { + } + + + using System; -namespace PushUpTest -{ - public class Base2 - { - protected virtual event EventHandler Event3 - { - add + public class Derived : Base { - System.Console.WriteLine(""Hello""); + public bool Test[||]Method(Uri endpoint) + { + var localHost = new Uri("http://localhost"); + return endpoint.Equals(localhost); + } } - remove + + + + """, """ + + + using System; + + public class Base { - System.Console.WriteLine(""World""); + public bool TestMethod(Uri endpoint) + { + var localHost = new Uri("http://localhost"); + return endpoint.Equals(localhost); + } } - }; - } + + + using System; - public class TestClass2 : Base2 - { - protected override event EventHandler E[||]vent3 - { - add + public class Derived : Base { - System.Console.WriteLine(""foo""); } - remove + + + + """); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] + public Task TestPullMethodWithNewBodyTypeToClassWithAddUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + public class Base { - System.Console.WriteLine(""bar""); } - }; - } -}"; - await TestQuickActionNotProvidedAsync(eventTest); - } + + + using System; - [Fact] - public async Task TestNoRefactoringProvidedWhenPullSameNameFieldUpToClassViaQuickAction() - { - // Fields share the same name will be thought as 'override', since it will cause error - // if two same name fields exist in one class - var fieldTest = @" -namespace PushUpTest -{ - public class Base - { - public int you = -100000; - } + public class Derived : Base + { + public bool Test[||]Method() + { + var endpoint1 = new Uri("http://localhost"); + var endpoint2 = new Uri("http://localhost"); + return endpoint1.Equals(endpoint2); + } + } + + + + """, """ + + + using System; + + public class Base + { + public bool TestMethod() + { + var endpoint1 = new Uri("http://localhost"); + var endpoint2 = new Uri("http://localhost"); + return endpoint1.Equals(endpoint2); + } + } + + + using System; - public class TestClass : Base - { - public int y[||]ou = 10086; - } -}"; - await TestQuickActionNotProvidedAsync(fieldTest); - } + public class Derived : Base + { + } + + + + """); - [Fact] - public async Task TestPullMethodToOrdinaryClassViaQuickAction() - { - var testText = @" -namespace PushUpTest -{ - public class Base - { - } + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] + public Task TestPullEventToClassWithAddUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + public class Base + { + } + + + using System; - public class TestClass : Base - { - public void TestMeth[||]od() - { - System.Console.WriteLine(""Hello World""); - } - } -}"; + public class Derived : Base + { + public event EventHandler Test[||]Event + { + add + { + Console.WriteLine("adding event..."); + } + remove + { + Console.WriteLine("removing event..."); + } + } + } + + + + """, """ + + + using System; + + public class Base + { + public event EventHandler Test[||]Event + { + add + { + Console.WriteLine("adding event..."); + } + remove + { + Console.WriteLine("removing event..."); + } + } + } + + + using System; - var expected = @" -namespace PushUpTest -{ - public class Base - { - public void TestMethod() - { - System.Console.WriteLine(""Hello World""); - } - } + public class Derived : Base + { + } + + + + """); - public class TestClass : Base - { - } -}"; - await TestWithPullMemberDialogAsync(testText, expected); - } + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] + public Task TestPullFieldToClassWithAddUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + public class Base + { + } + + + using System; - [Fact] - public async Task TestPullOneFieldsToClassViaQuickAction() - { - var testText = @" -namespace PushUpTest -{ - public class Base - { - } + public class Derived : Base + { + public var en[||]dpoint = new Uri("http://localhost"); + } + + + + """, """ + + + using System; + + public class Base + { + public var endpoint = new Uri("http://localhost"); + } + + + using System; - public class TestClass : Base - { - public int you[||]= 10086; - } -}"; + public class Derived : Base + { + } + + + + """); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46010")] + public Task TestPullFieldToClassNoConstructorWithAddUsingsViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + + public class Base + { + } + + + using System.Linq; - var expected = @" -namespace PushUpTest -{ - public class Base - { - public int you = 10086; - } + public class Derived : Base + { + public var ran[||]ge = Enumerable.Range(0, 5); + } + + + + """, """ + + + using System.Linq; + + public class Base + { + public var range = Enumerable.Range(0, 5); + } + + + using System.Linq; - public class TestClass : Base - { - } -}"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Derived : Base + { + } + + + + """); [Fact] - public async Task TestPullGenericsUpToClassViaQuickAction() - { - var testText = @" -using System; -namespace PushUpTest -{ - public class BaseClass - { - } + public Task TestNoRefactoringProvidedWhenPullOverrideMethodUpToClassViaQuickAction() + => TestQuickActionNotProvidedAsync(""" + namespace PushUpTest + { + public class Base + { + public virtual void TestMethod() => System.Console.WriteLine("foo bar bar foo"); + } - public class TestClass : BaseClass - { - public void TestMeth[||]od() where T : IDisposable - { - } - } -}"; + public class TestClass : Base + { + public override void TestMeth[||]od() + { + System.Console.WriteLine("Hello World"); + } + } + } + """); - var expected = @" -using System; -namespace PushUpTest -{ - public class BaseClass - { - public void TestMethod() where T : IDisposable - { - } - } + [Fact] + public Task TestNoRefactoringProvidedWhenPullOverridePropertyUpToClassViaQuickAction() + => TestQuickActionNotProvidedAsync(""" + using System; + namespace PushUpTest + { + public class Base + { + public virtual int TestProperty { get => 111; private set; } + } - public class TestClass : BaseClass - { - } -}"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class TestClass : Base + { + public override int TestPr[||]operty { get; private set; } + } + } + """); [Fact] - public async Task TestPullOneFieldFromMultipleFieldsToClassViaQuickAction() - { - var testText = @" -namespace PushUpTest -{ - public class Base - { - } + public Task TestNoRefactoringProvidedWhenPullOverrideEventUpToClassViaQuickAction() + => TestQuickActionNotProvidedAsync(""" + using System; - public class TestClass : Base - { - public int you, a[||]nd, someone = 10086; - } -}"; + namespace PushUpTest + { + public class Base2 + { + protected virtual event EventHandler Event3 + { + add + { + System.Console.WriteLine("Hello"); + } + remove + { + System.Console.WriteLine("World"); + } + }; + } - var expected = @" -namespace PushUpTest -{ - public class Base - { - public int and; - } + public class TestClass2 : Base2 + { + protected override event EventHandler E[||]vent3 + { + add + { + System.Console.WriteLine("foo"); + } + remove + { + System.Console.WriteLine("bar"); + } + }; + } + } + """); - public class TestClass : Base - { - public int you, someone = 10086; - } -}"; - await TestWithPullMemberDialogAsync(testText, expected); - } + [Fact] + public Task TestNoRefactoringProvidedWhenPullSameNameFieldUpToClassViaQuickAction() + => TestQuickActionNotProvidedAsync(""" + namespace PushUpTest + { + public class Base + { + public int you = -100000; + } + + public class TestClass : Base + { + public int y[||]ou = 10086; + } + } + """); [Fact] - public async Task TestPullMiddleFieldWithValueToClassViaQuickAction() - { - var testText = @" -namespace PushUpTest -{ - public class Base - { - } + public Task TestPullMethodToOrdinaryClassViaQuickAction() + => TestWithPullMemberDialogAsync(""" + namespace PushUpTest + { + public class Base + { + } - public class TestClass : Base - { - public int you, a[||]nd = 4000, someone = 10086; - } -}"; - var expected = @" -namespace PushUpTest -{ - public class Base - { - public int and = 4000; - } + public class TestClass : Base + { + public void TestMeth[||]od() + { + System.Console.WriteLine("Hello World"); + } + } + } + """, """ + namespace PushUpTest + { + public class Base + { + public void TestMethod() + { + System.Console.WriteLine("Hello World"); + } + } - public class TestClass : Base - { - public int you, someone = 10086; - } -}"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class TestClass : Base + { + } + } + """); [Fact] - public async Task TestPullOneEventFromMultipleToClassViaQuickAction() - { - var testText = @" -using System; + public Task TestPullOneFieldsToClassViaQuickAction() + => TestWithPullMemberDialogAsync(""" + namespace PushUpTest + { + public class Base + { + } -namespace PushUpTest -{ - public class Base2 - { - } + public class TestClass : Base + { + public int you[||]= 10086; + } + } + """, """ + namespace PushUpTest + { + public class Base + { + public int you = 10086; + } - public class Testclass2 : Base2 - { - private static event EventHandler Event1, Eve[||]nt3, Event4; - } -}"; - var expected = @" -using System; + public class TestClass : Base + { + } + } + """); -namespace PushUpTest -{ - public class Base2 - { - private static event EventHandler Event3; - } + [Fact] + public Task TestPullGenericsUpToClassViaQuickAction() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest + { + public class BaseClass + { + } - public class Testclass2 : Base2 - { - private static event EventHandler Event1, Event4; - } -}"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class TestClass : BaseClass + { + public void TestMeth[||]od() where T : IDisposable + { + } + } + } + """, """ + using System; + namespace PushUpTest + { + public class BaseClass + { + public void TestMethod() where T : IDisposable + { + } + } + + public class TestClass : BaseClass + { + } + } + """); [Fact] - public async Task TestPullEventToClassViaQuickAction() - { - var testText = @" -using System; + public Task TestPullOneFieldFromMultipleFieldsToClassViaQuickAction() + => TestWithPullMemberDialogAsync(""" + namespace PushUpTest + { + public class Base + { + } -namespace PushUpTest -{ - public class Base2 - { - } + public class TestClass : Base + { + public int you, a[||]nd, someone = 10086; + } + } + """, """ + namespace PushUpTest + { + public class Base + { + public int and; + } - public class TestClass2 : Base2 - { - private static event EventHandler Eve[||]nt3; - } -}"; - var expected = @" -using System; + public class TestClass : Base + { + public int you, someone = 10086; + } + } + """); -namespace PushUpTest -{ - public class Base2 - { - private static event EventHandler Event3; - } + [Fact] + public Task TestPullMiddleFieldWithValueToClassViaQuickAction() + => TestWithPullMemberDialogAsync(""" + namespace PushUpTest + { + public class Base + { + } - public class TestClass2 : Base2 - { - } -}"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class TestClass : Base + { + public int you, a[||]nd = 4000, someone = 10086; + } + } + """, """ + namespace PushUpTest + { + public class Base + { + public int and = 4000; + } - [Fact] - public async Task TestPullEventWithBodyToClassViaQuickAction() - { - var testText = @" -using System; + public class TestClass : Base + { + public int you, someone = 10086; + } + } + """); -namespace PushUpTest -{ - public class Base2 - { - } + [Fact] + public Task TestPullOneEventFromMultipleToClassViaQuickAction() + => TestWithPullMemberDialogAsync(""" + using System; - public class TestClass2 : Base2 - { - private static event EventHandler Eve[||]nt3 - { - add + namespace PushUpTest { - System.Console.Writeln(""Hello""); + public class Base2 + { + } + + public class Testclass2 : Base2 + { + private static event EventHandler Event1, Eve[||]nt3, Event4; + } } - remove + """, """ + using System; + + namespace PushUpTest { - System.Console.Writeln(""World""); + public class Base2 + { + private static event EventHandler Event3; + } + + public class Testclass2 : Base2 + { + private static event EventHandler Event1, Event4; + } } - }; - } -}"; - var expected = @" -using System; + """); -namespace PushUpTest -{ - public class Base2 - { - private static event EventHandler Event3 - { - add + [Fact] + public Task TestPullEventToClassViaQuickAction() + => TestWithPullMemberDialogAsync(""" + using System; + + namespace PushUpTest { - System.Console.Writeln(""Hello""); + public class Base2 + { + } + + public class TestClass2 : Base2 + { + private static event EventHandler Eve[||]nt3; + } } - remove + """, """ + using System; + + namespace PushUpTest { - System.Console.Writeln(""World""); - } - }; - } + public class Base2 + { + private static event EventHandler Event3; + } - public class TestClass2 : Base2 - { - } -}"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class TestClass2 : Base2 + { + } + } + """); [Fact] - public async Task TestPullPropertyToClassViaQuickAction() - { - var testText = @" -using System; -namespace PushUpTest -{ - public class Base - { - } + public Task TestPullEventWithBodyToClassViaQuickAction() + => TestWithPullMemberDialogAsync(""" + using System; - public class TestClass : Base - { - public int TestPr[||]operty { get; private set; } - } -}"; + namespace PushUpTest + { + public class Base2 + { + } - var expected = @" -using System; -namespace PushUpTest -{ - public class Base - { - public int TestProperty { get; private set; } - } + public class TestClass2 : Base2 + { + private static event EventHandler Eve[||]nt3 + { + add + { + System.Console.Writeln("Hello"); + } + remove + { + System.Console.Writeln("World"); + } + }; + } + } + """, """ + using System; - public class TestClass : Base - { - } -}"; - await TestWithPullMemberDialogAsync(testText, expected); - } + namespace PushUpTest + { + public class Base2 + { + private static event EventHandler Event3 + { + add + { + System.Console.Writeln("Hello"); + } + remove + { + System.Console.Writeln("World"); + } + }; + } - [Fact] - public async Task TestPullIndexerToClassViaQuickAction() - { - var testText = @" -namespace PushUpTest -{ - public class Base - { - } + public class TestClass2 : Base2 + { + } + } + """); - public class TestClass : Base - { - private int j; - public int th[||]is[int i] - { - get => j; - set => j = value; - } - } -}"; + [Fact] + public Task TestPullPropertyToClassViaQuickAction() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest + { + public class Base + { + } - var expected = @" -namespace PushUpTest -{ - public class Base - { - public int this[int i] - { - get => j; - set => j = value; - } - } + public class TestClass : Base + { + public int TestPr[||]operty { get; private set; } + } + } + """, """ + using System; + namespace PushUpTest + { + public class Base + { + public int TestProperty { get; private set; } + } - public class TestClass : Base - { - private int j; - } -}"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class TestClass : Base + { + } + } + """); [Fact] - public async Task TestPullMethodUpAcrossProjectViaQuickAction() - { - var testText = @" - - - CSAssembly2 - -using Destination; -public class TestClass : IInterface -{ - public int Bar[||]Bar() - { - return 12345; - } -} - - - - -namespace Destination -{ - public interface IInterface - { - } -} - - -"; - - var expected = @" - - - CSAssembly2 - -using Destination; -public class TestClass : IInterface -{ - public int Bar[||]Bar() - { - return 12345; - } -} - - - - -namespace Destination -{ - public interface IInterface - { - int BarBar(); - } -} - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public Task TestPullIndexerToClassViaQuickAction() + => TestWithPullMemberDialogAsync(""" + namespace PushUpTest + { + public class Base + { + } - [Fact] - public async Task TestPullPropertyUpAcrossProjectViaQuickAction() - { - var testText = @" - - - CSAssembly2 - -using Destination; -public class TestClass : IInterface -{ - public int F[||]oo - { - get; - set; - } -} - - - - -namespace Destination -{ - public interface IInterface - { - } -} - - -"; - - var expected = @" - - - CSAssembly2 - -using Destination; -public class TestClass : IInterface -{ - public int Foo - { - get; - set; - } -} - - - - -namespace Destination -{ - public interface IInterface - { - int Foo { get; set; } - } -} - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class TestClass : Base + { + private int j; + public int th[||]is[int i] + { + get => j; + set => j = value; + } + } + } + """, """ + namespace PushUpTest + { + public class Base + { + public int this[int i] + { + get => j; + set => j = value; + } + } - [Fact] - public async Task TestPullFieldUpAcrossProjectViaQuickAction() - { - var testText = @" - - - CSAssembly2 - -using Destination; -public class TestClass : BaseClass -{ - private int i, j, [||]k = 10; -} - - - - -namespace Destination -{ - public class BaseClass - { - } -} - - -"; - - var expected = @" - - - CSAssembly2 - -using Destination; -public class TestClass : BaseClass -{ - private int i, j; -} - - - - -namespace Destination -{ - public class BaseClass - { - private int k = 10; - } -} - - -"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public class TestClass : Base + { + private int j; + } + } + """); [Fact] - public async Task TestPullMethodUpToVBClassViaQuickAction() - { - // Moving member from C# to Visual Basic is not supported currently since the FindMostRelevantDeclarationAsync method in - // AbstractCodeGenerationService will return null. - var input = @" - - - VBAssembly - - using VBAssembly; - public class TestClass : VBClass + public Task TestPullMethodUpAcrossProjectViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + CSAssembly2 + + using Destination; + public class TestClass : IInterface { - public int Bar[||]bar() + public int Bar[||]Bar() { return 12345; } } - - - - - Public Class VBClass - End Class - - -"; - await TestQuickActionNotProvidedAsync(input); - } + + + + + namespace Destination + { + public interface IInterface + { + } + } + + + + """, """ + + + CSAssembly2 + + using Destination; + public class TestClass : IInterface + { + public int Bar[||]Bar() + { + return 12345; + } + } + + + + + namespace Destination + { + public interface IInterface + { + int BarBar(); + } + } + + + + """); [Fact] - public async Task TestPullMethodUpToVBInterfaceViaQuickAction() - { - var input = @" - - - VBAssembly - - public class TestClass : VBInterface - { - public int Bar[||]bar() + public Task TestPullPropertyUpAcrossProjectViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + CSAssembly2 + + using Destination; + public class TestClass : IInterface { - return 12345; + public int F[||]oo + { + get; + set; + } } - } - - - - - Public Interface VBInterface - End Interface - - - -"; - await TestQuickActionNotProvidedAsync(input); - } + + + + + namespace Destination + { + public interface IInterface + { + } + } + + + + """, """ + + + CSAssembly2 + + using Destination; + public class TestClass : IInterface + { + public int Foo + { + get; + set; + } + } + + + + + namespace Destination + { + public interface IInterface + { + int Foo { get; set; } + } + } + + + + """); [Fact] - public async Task TestPullFieldUpToVBClassViaQuickAction() - { - var input = @" - - - VBAssembly - - using VBAssembly; - public class TestClass : VBClass + public Task TestPullFieldUpAcrossProjectViaQuickAction() + => TestWithPullMemberDialogAsync(""" + + + CSAssembly2 + + using Destination; + public class TestClass : BaseClass + { + private int i, j, [||]k = 10; + } + + + + + namespace Destination { - public int fo[||]obar = 0; + public class BaseClass + { + } + } + + + + """, """ + + + CSAssembly2 + + using Destination; + public class TestClass : BaseClass + { + private int i, j; + } + + + + + namespace Destination + { + public class BaseClass + { + private int k = 10; + } } - - - - - Public Class VBClass - End Class - - -"; + + + + """); - await TestQuickActionNotProvidedAsync(input); - } + [Fact] + public Task TestPullMethodUpToVBClassViaQuickAction() + => TestQuickActionNotProvidedAsync(""" + + + VBAssembly + + using VBAssembly; + public class TestClass : VBClass + { + public int Bar[||]bar() + { + return 12345; + } + } + + + + + Public Class VBClass + End Class + + + + """); [Fact] - public async Task TestPullPropertyUpToVBClassViaQuickAction() - { - var input = @" - - - VBAssembly - -using VBAssembly; -public class TestClass : VBClass -{ - public int foo[||]bar - { - get; - set; - } -} - - - - Public Class VBClass - End Class - - - -"; - await TestQuickActionNotProvidedAsync(input); - } + public Task TestPullMethodUpToVBInterfaceViaQuickAction() + => TestQuickActionNotProvidedAsync(""" + + + VBAssembly + + public class TestClass : VBInterface + { + public int Bar[||]bar() + { + return 12345; + } + } + + + + + Public Interface VBInterface + End Interface + + + + """); [Fact] - public async Task TestPullPropertyUpToVBInterfaceViaQuickAction() - { - var input = @" - - VBAssembly - -using VBAssembly; -public class TestClass : VBInterface - { - public int foo[||]bar - { - get; - set; - } - } - - - - - Public Interface VBInterface - End Interface - - -"; - await TestQuickActionNotProvidedAsync(input); - } + public Task TestPullFieldUpToVBClassViaQuickAction() + => TestQuickActionNotProvidedAsync(""" + + + VBAssembly + + using VBAssembly; + public class TestClass : VBClass + { + public int fo[||]obar = 0; + } + + + + + Public Class VBClass + End Class + + + + """); [Fact] - public async Task TestPullEventUpToVBClassViaQuickAction() - { - var input = @" - - - VBAssembly - + public Task TestPullPropertyUpToVBClassViaQuickAction() + => TestQuickActionNotProvidedAsync(""" + + + VBAssembly + using VBAssembly; public class TestClass : VBClass { - public event EventHandler BarEve[||]nt; - } - - - - - Public Class VBClass - End Class - - -"; - await TestQuickActionNotProvidedAsync(input); - } + public int foo[||]bar + { + get; + set; + } + } + + + + Public Class VBClass + End Class + + + + """); [Fact] - public async Task TestPullEventUpToVBInterfaceViaQuickAction() - { - var input = @" - - - VBAssembly - - using VBAssembly; - public class TestClass : VBInterface - { - public event EventHandler BarEve[||]nt; - } - - - - - Public Interface VBInterface - End Interface - - -"; - await TestQuickActionNotProvidedAsync(input); - } + public Task TestPullPropertyUpToVBInterfaceViaQuickAction() + => TestQuickActionNotProvidedAsync(""" + + + VBAssembly + + using VBAssembly; + public class TestClass : VBInterface + { + public int foo[||]bar + { + get; + set; + } + } + + + + + Public Interface VBInterface + End Interface + + + + """); + + [Fact] + public Task TestPullEventUpToVBClassViaQuickAction() + => TestQuickActionNotProvidedAsync(""" + + + VBAssembly + + using VBAssembly; + public class TestClass : VBClass + { + public event EventHandler BarEve[||]nt; + } + + + + + Public Class VBClass + End Class + + + + """); + + [Fact] + public Task TestPullEventUpToVBInterfaceViaQuickAction() + => TestQuickActionNotProvidedAsync(""" + + + VBAssembly + + using VBAssembly; + public class TestClass : VBInterface + { + public event EventHandler BarEve[||]nt; + } + + + + + Public Interface VBInterface + End Interface + + + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/55746")] - public async Task TestPullMethodWithToClassWithAddUsingsInsideNamespaceViaQuickAction() - { - var testText = @" - - - -namespace N -{ - public class Base - { - } -} - - -using System; + public Task TestPullMethodWithToClassWithAddUsingsInsideNamespaceViaQuickAction() + => TestWithPullMemberDialogAsync( + """ + + + + namespace N + { + public class Base + { + } + } + + + using System; -namespace N -{ - public class Derived : Base - { - public Uri En[||]dpoint() - { - return new Uri(""http://localhost""); - } - } -} - - - -"; - var expected = @" - - - -namespace N -{ - using System; + namespace N + { + public class Derived : Base + { + public Uri En[||]dpoint() + { + return new Uri("http://localhost"); + } + } + } + + + + """, + """ + + + + namespace N + { + using System; - public class Base - { - public Uri Endpoint() - { - return new Uri(""http://localhost""); - } - } -} - - -using System; + public class Base + { + public Uri Endpoint() + { + return new Uri("http://localhost"); + } + } + } + + + using System; -namespace N -{ - public class Derived : Base - { - } -} - - - -"; - await TestWithPullMemberDialogAsync( - testText, - expected, + namespace N + { + public class Derived : Base + { + } + } + + + + """, options: Option(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, AddImportPlacement.InsideNamespace, CodeStyle.NotificationOption2.Silent)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/55746")] - public async Task TestPullMethodWithToClassWithAddUsingsSystemUsingsLastViaQuickAction() - { - var testText = @" - - - -namespace N1 -{ - public class Base - { - } -} - - -using System; -using N2; + public Task TestPullMethodWithToClassWithAddUsingsSystemUsingsLastViaQuickAction() + => TestWithPullMemberDialogAsync( + """ + + + + namespace N1 + { + public class Base + { + } + } + + + using System; + using N2; -namespace N1 -{ - public class Derived : Base - { - public Goo Ge[||]tGoo() - { - return new Goo(String.Empty); - } - } -} + namespace N1 + { + public class Derived : Base + { + public Goo Ge[||]tGoo() + { + return new Goo(String.Empty); + } + } + } -namespace N2 -{ - public class Goo - { - public Goo(String s) - { - } - } -} - - - -"; - var expected = @" - - - using N2; -using System; - -namespace N1 -{ - public class Base - { - public Goo GetGoo() - { - return new Goo(String.Empty); - } - } -} - - -using System; -using N2; + namespace N2 + { + public class Goo + { + public Goo(String s) + { + } + } + } + + + + """, + """ + + + using N2; + using System; + + namespace N1 + { + public class Base + { + public Goo GetGoo() + { + return new Goo(String.Empty); + } + } + } + + + using System; + using N2; -namespace N1 -{ - public class Derived : Base - { - } -} + namespace N1 + { + public class Derived : Base + { + } + } -namespace N2 -{ - public class Goo - { - public Goo(String s) - { - } - } -} - - - -"; - await TestWithPullMemberDialogAsync( - testText, - expected, + namespace N2 + { + public class Goo + { + public Goo(String s) + { + } + } + } + + + + """, options: new(GetLanguage()) { { GenerationOptions.PlaceSystemNamespaceFirst, false }, }); - } [Fact, WorkItem(55746, "https://github.com/dotnet/roslyn/issues/51531")] public Task TestPullMethodToClassWithDirective() { - var text = @" -public class BaseClass -{ -} + return TestWithPullMemberDialogAsync(""" + public class BaseClass + { + } -public class Bar : BaseClass -{ - #region Hello - public void G[||]oo() { } - #endregion -}"; - var expected = @" -public class BaseClass -{ - public void Goo() { } -} + public class Bar : BaseClass + { + #region Hello + public void G[||]oo() { } + #endregion + } + """, """ + public class BaseClass + { + public void Goo() { } + } -public class Bar : BaseClass -{ + public class Bar : BaseClass + { - #region Hello - #endregion -}"; - return TestWithPullMemberDialogAsync(text, expected); + #region Hello + #endregion + } + """); } [Fact, WorkItem(55746, "https://github.com/dotnet/roslyn/issues/51531")] public Task TestPullMethodToClassBeforeDirective() { - var text = @" -public class BaseClass -{ -} + return TestWithPullMemberDialogAsync(""" + public class BaseClass + { + } -public class Bar : BaseClass -{ - public void H[||]ello() { } - #region Hello - public void Goo() { } - #endregion -}"; - var expected = @" -public class BaseClass -{ - public void Hello() { } -} + public class Bar : BaseClass + { + public void H[||]ello() { } + #region Hello + public void Goo() { } + #endregion + } + """, """ + public class BaseClass + { + public void Hello() { } + } -public class Bar : BaseClass -{ - #region Hello - public void Goo() { } - #endregion -}"; - return TestWithPullMemberDialogAsync(text, expected); + public class Bar : BaseClass + { + #region Hello + public void Goo() { } + #endregion + } + """); } [Fact, WorkItem(55746, "https://github.com/dotnet/roslyn/issues/51531")] public Task TestPullMethodToClassBeforeDirective2() { - var text = @" -public class BaseClass -{ -} + return TestWithPullMemberDialogAsync(""" + public class BaseClass + { + } -public class Bar : BaseClass -{ - public void Hello() { } + public class Bar : BaseClass + { + public void Hello() { } - #region Hello - public void G[||]oo() { } - #endregion -}"; - var expected = @" -public class BaseClass -{ + #region Hello + public void G[||]oo() { } + #endregion + } + """, """ + public class BaseClass + { - public void Goo() { } -} + public void Goo() { } + } -public class Bar : BaseClass -{ - public void Hello() { } + public class Bar : BaseClass + { + public void Hello() { } - #region Hello - #endregion -}"; - return TestWithPullMemberDialogAsync(text, expected); + #region Hello + #endregion + } + """); } [Fact, WorkItem(55746, "https://github.com/dotnet/roslyn/issues/51531")] public Task TestPullFieldToClassBeforeDirective1() { - var text = @" -public class BaseClass -{ -} + return TestWithPullMemberDialogAsync(""" + public class BaseClass + { + } -public class Bar : BaseClass -{ - public int ba[||]r = 10; - #region Hello - public int Goo = 10; - #endregion -}"; - var expected = @" -public class BaseClass -{ - public int bar = 10; -} + public class Bar : BaseClass + { + public int ba[||]r = 10; + #region Hello + public int Goo = 10; + #endregion + } + """, """ + public class BaseClass + { + public int bar = 10; + } -public class Bar : BaseClass -{ - #region Hello - public int Goo = 10; - #endregion -}"; - return TestWithPullMemberDialogAsync(text, expected); + public class Bar : BaseClass + { + #region Hello + public int Goo = 10; + #endregion + } + """); } [Fact, WorkItem(55746, "https://github.com/dotnet/roslyn/issues/51531")] public Task TestPullFieldToClassBeforeDirective2() { - var text = @" -public class BaseClass -{ -} + return TestWithPullMemberDialogAsync(""" + public class BaseClass + { + } -public class Bar : BaseClass -{ - public int bar = 10; - #region Hello - public int Go[||]o = 10; - #endregion -}"; - var expected = @" -public class BaseClass -{ - public int Goo = 10; -} + public class Bar : BaseClass + { + public int bar = 10; + #region Hello + public int Go[||]o = 10; + #endregion + } + """, """ + public class BaseClass + { + public int Goo = 10; + } -public class Bar : BaseClass -{ - public int bar = 10; + public class Bar : BaseClass + { + public int bar = 10; - #region Hello - #endregion -}"; - return TestWithPullMemberDialogAsync(text, expected); + #region Hello + #endregion + } + """); } [Fact, WorkItem(55746, "https://github.com/dotnet/roslyn/issues/51531")] public Task TestPullFieldToClassBeforeDirective() { - var text = @" -public class BaseClass -{ -} + return TestWithPullMemberDialogAsync(""" + public class BaseClass + { + } -public class Bar : BaseClass -{ - #region Hello - public int G[||]oo = 100, Hoo; - #endregion -}"; - var expected = @" -public class BaseClass -{ - public int Goo = 100; -} + public class Bar : BaseClass + { + #region Hello + public int G[||]oo = 100, Hoo; + #endregion + } + """, """ + public class BaseClass + { + public int Goo = 100; + } -public class Bar : BaseClass -{ - #region Hello - public int Hoo; - #endregion -}"; - return TestWithPullMemberDialogAsync(text, expected); + public class Bar : BaseClass + { + #region Hello + public int Hoo; + #endregion + } + """); } [Fact, WorkItem(55746, "https://github.com/dotnet/roslyn/issues/51531")] public Task TestPullEventToClassBeforeDirective() { - var text = @" -using System; -public class BaseClass -{ -} + return TestWithPullMemberDialogAsync(""" + using System; + public class BaseClass + { + } -public class Bar : BaseClass -{ - #region Hello - public event EventHandler e[||]1; - #endregion -}"; - var expected = @" -using System; -public class BaseClass -{ - public event EventHandler e1; -} + public class Bar : BaseClass + { + #region Hello + public event EventHandler e[||]1; + #endregion + } + """, """ + using System; + public class BaseClass + { + public event EventHandler e1; + } -public class Bar : BaseClass -{ + public class Bar : BaseClass + { - #region Hello - #endregion -}"; - return TestWithPullMemberDialogAsync(text, expected); + #region Hello + #endregion + } + """); } [Fact, WorkItem(55746, "https://github.com/dotnet/roslyn/issues/51531")] public Task TestPullPropertyToClassBeforeDirective() { - var text = @" -public class BaseClass -{ -} - -public class Bar : BaseClass -{ - #region Hello - public int Go[||]o => 1; - #endregion -}"; - var expected = @" -public class BaseClass -{ - public int Goo => 1; -} - -public class Bar : BaseClass -{ - - #region Hello - #endregion -}"; - return TestWithPullMemberDialogAsync(text, expected); - } - - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/55402")] - public Task TestPullPropertyToClassOnKeyword() - { - var text = """ + return TestWithPullMemberDialogAsync(""" public class BaseClass { } - public class Derived : BaseClass + public class Bar : BaseClass { - $$public int I => 1; + #region Hello + public int Go[||]o => 1; + #endregion } - """; - - var expected = """ + """, """ public class BaseClass { - $$public int I => 1; - } - - public class Derived : BaseClass - { + public int Goo => 1; } - """; - - return TestWithPullMemberDialogAsync(text, expected); - } - - #endregion Quick Action - - #region Dialog - - internal Task TestWithPullMemberDialogAsync( - string initialMarkUp, - string expectedResult, - IEnumerable<(string name, bool makeAbstract)> selection = null, - string destinationName = null, - int index = 0, - TestParameters parameters = null, - OptionsCollection options = null) - { - var service = new TestPullMemberUpService(selection, destinationName); - - return TestInRegularAndScript1Async( - initialMarkUp, expectedResult, - (parameters ?? TestParameters.Default).WithFixProviderData(service).WithOptions(options).WithIndex(index)); - } - - [Fact] - public async Task PullPartialMethodUpToInterfaceViaDialog() - { - var testText = @" -using System; -namespace PushUpTest -{ - partial interface IInterface - { - } - - public partial class TestClass : IInterface - { - partial void Bar[||]Bar() - } - - public partial class TestClass - { - partial void BarBar() - {} - } - - partial interface IInterface - { - } -}"; - var expected = @" -using System; -namespace PushUpTest -{ - partial interface IInterface - { - void BarBar(); - } - - public partial class TestClass : IInterface - { - void BarBar() - } - - public partial class TestClass - { - partial void BarBar() - {} - } - - partial interface IInterface - { - } -}"; - - await TestWithPullMemberDialogAsync(testText, expected); - } - - [Fact] - public async Task PullExtendedPartialMethodUpToInterfaceViaDialog() - { - var testText = @" -using System; -namespace PushUpTest -{ - partial interface IInterface - { - } - - public partial class TestClass : IInterface - { - public partial void Bar[||]Bar() - } - - public partial class TestClass - { - public partial void BarBar() - {} - } - - partial interface IInterface - { - } -}"; - var expected = @" -using System; -namespace PushUpTest -{ - partial interface IInterface - { - void BarBar(); - } - - public partial class TestClass : IInterface - { - public partial void BarBar() - } - - public partial class TestClass - { - public partial void BarBar() - {} - } - - partial interface IInterface - { - } -}"; - - await TestWithPullMemberDialogAsync(testText, expected); - } - - [Fact] - public async Task PullMultipleNonPublicMethodsToInterfaceViaDialog() - { - var testText = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - } - - public class TestClass : IInterface - { - public void TestMethod() - { - System.Console.WriteLine(""Hello World""); - } - - protected void F[||]oo(int i) - { - // do awesome things - } - - private static string Bar(string x) - {} - } -}"; - var expected = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - string Bar(string x); - void Foo(int i); - void TestMethod(); - } - - public class TestClass : IInterface - { - public void TestMethod() - { - System.Console.WriteLine(""Hello World""); - } - - public void Foo(int i) - { - // do awesome things - } - - public string Bar(string x) - {} - } -}"; - await TestWithPullMemberDialogAsync(testText, expected); - } - - [Fact] - public async Task PullMultipleNonPublicEventsToInterface() - { - var testText = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - } - public class TestClass : IInterface - { - private event EventHandler Event1, Eve[||]nt2, Event3; - } -}"; + public class Bar : BaseClass + { - var expected = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - event EventHandler Event1; - event EventHandler Event2; - event EventHandler Event3; + #region Hello + #endregion + } + """); } - public class TestClass : IInterface + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/55402")] + public Task TestPullPropertyToClassOnKeyword() { - public event EventHandler Event1; - public event EventHandler Event2; - public event EventHandler Event3; - } -}"; - await TestWithPullMemberDialogAsync(testText, expected); - } + return TestWithPullMemberDialogAsync(""" + public class BaseClass + { + } - [Fact] - public async Task PullMethodToInnerInterfaceViaDialog() - { - var testText = @" -using System; -namespace PushUpTest -{ - public class TestClass : TestClass.IInterface - { - private void Bar[||]Bar() - { - } - interface IInterface - { - } + public class Derived : BaseClass + { + $$public int I => 1; + } + """, """ + public class BaseClass + { + $$public int I => 1; + } + + public class Derived : BaseClass + { + } + """); } -}"; - var expected = @" -using System; -namespace PushUpTest -{ - public class TestClass : TestClass.IInterface + + #endregion Quick Action + + #region Dialog + + internal Task TestWithPullMemberDialogAsync( + string initialMarkUp, + string expectedResult, + IEnumerable<(string name, bool makeAbstract)> selection = null, + string destinationName = null, + int index = 0, + TestParameters parameters = null, + OptionsCollection options = null) { - public void BarBar() - { - } - interface IInterface - { - void BarBar(); - } - } -}"; + var service = new TestPullMemberUpService(selection, destinationName); - await TestWithPullMemberDialogAsync(testText, expected); + return TestInRegularAndScript1Async( + initialMarkUp, expectedResult, + (parameters ?? TestParameters.Default).WithFixProviderData(service).WithOptions(options).WithIndex(index)); } [Fact] - public async Task PullDifferentMembersFromClassToPartialInterfaceViaDialog() - { - var testText = @" -using System; -namespace PushUpTest -{ - partial interface IInterface - { - } + public Task PullPartialMethodUpToInterfaceViaDialog() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest + { + partial interface IInterface + { + } - public class TestClass : IInterface - { - public int th[||]is[int i] - { - get => j = value; - } + public partial class TestClass : IInterface + { + partial void Bar[||]Bar() + } - private static void BarBar() - {} - - protected static event EventHandler event1, event2; + public partial class TestClass + { + partial void BarBar() + {} + } - internal static int Foo - { - get; set; - } - } - partial interface IInterface - { - } -}"; + partial interface IInterface + { + } + } + """, """ + using System; + namespace PushUpTest + { + partial interface IInterface + { + void BarBar(); + } - var expected = @" -using System; -namespace PushUpTest -{ - partial interface IInterface - { - int this[int i] { get; } + public partial class TestClass : IInterface + { + void BarBar() + } - int Foo { get; set; } + public partial class TestClass + { + partial void BarBar() + {} + } - event EventHandler event1; - event EventHandler event2; + partial interface IInterface + { + } + } + """); - void BarBar(); - } + [Fact] + public Task PullExtendedPartialMethodUpToInterfaceViaDialog() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest + { + partial interface IInterface + { + } - public class TestClass : IInterface - { - public int this[int i] - { - get => j = value; - } + public partial class TestClass : IInterface + { + public partial void Bar[||]Bar() + } - public void BarBar() - {} + public partial class TestClass + { + public partial void BarBar() + {} + } - public event EventHandler event1; - public event EventHandler event2; + partial interface IInterface + { + } + } + """, """ + using System; + namespace PushUpTest + { + partial interface IInterface + { + void BarBar(); + } - public int Foo - { - get; set; - } - } - partial interface IInterface - { - } -}"; - await TestWithPullMemberDialogAsync(testText, expected, index: 1); - } + public partial class TestClass : IInterface + { + public partial void BarBar() + } - [Fact] - public async Task TestPullAsyncMethod() - { - var testText = @" -using System.Threading.Tasks; + public partial class TestClass + { + public partial void BarBar() + {} + } -internal interface IPullUp { } + partial interface IInterface + { + } + } + """); -internal class PullUp : IPullUp -{ - internal async Task PullU[||]pAsync() - { - await Task.Delay(1000); - } -}"; - var expectedText = @" -using System.Threading.Tasks; + [Fact] + public Task PullMultipleNonPublicMethodsToInterfaceViaDialog() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest + { + interface IInterface + { + } -internal interface IPullUp -{ - Task PullUpAsync(); -} + public class TestClass : IInterface + { + public void TestMethod() + { + System.Console.WriteLine("Hello World"); + } + + protected void F[||]oo(int i) + { + // do awesome things + } + + private static string Bar(string x) + {} + } + } + """, """ + using System; + namespace PushUpTest + { + interface IInterface + { + string Bar(string x); + void Foo(int i); + void TestMethod(); + } -internal class PullUp : IPullUp -{ - public async Task PullUpAsync() - { - await Task.Delay(1000); - } -}"; - await TestWithPullMemberDialogAsync(testText, expectedText); - } + public class TestClass : IInterface + { + public void TestMethod() + { + System.Console.WriteLine("Hello World"); + } + + public void Foo(int i) + { + // do awesome things + } + + public string Bar(string x) + {} + } + } + """); [Fact] - public async Task PullMethodWithAbstractOptionToClassViaDialog() - { - var testText = @" -namespace PushUpTest -{ - public class Base - { - } + public Task PullMultipleNonPublicEventsToInterface() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest + { + interface IInterface + { + } - public class TestClass : Base - { - public void TestMeth[||]od() - { - System.Console.WriteLine(""Hello World""); - } - } -}"; + public class TestClass : IInterface + { + private event EventHandler Event1, Eve[||]nt2, Event3; + } + } + """, """ + using System; + namespace PushUpTest + { + interface IInterface + { + event EventHandler Event1; + event EventHandler Event2; + event EventHandler Event3; + } - var expected = @" -namespace PushUpTest -{ - public abstract class Base - { - public abstract void TestMethod(); - } + public class TestClass : IInterface + { + public event EventHandler Event1; + public event EventHandler Event2; + public event EventHandler Event3; + } + } + """); - public class TestClass : Base - { - public override void TestMeth[||]od() - { - System.Console.WriteLine(""Hello World""); - } - } -}"; - await TestWithPullMemberDialogAsync(testText, expected, [("TestMethod", true)], index: 1); - } + [Fact] + public Task PullMethodToInnerInterfaceViaDialog() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest + { + public class TestClass : TestClass.IInterface + { + private void Bar[||]Bar() + { + } + interface IInterface + { + } + } + } + """, """ + using System; + namespace PushUpTest + { + public class TestClass : TestClass.IInterface + { + public void BarBar() + { + } + interface IInterface + { + void BarBar(); + } + } + } + """); [Fact] - public async Task PullAbstractMethodToClassViaDialog() - { - var testText = @" -namespace PushUpTest -{ - public class Base - { - } + public Task PullDifferentMembersFromClassToPartialInterfaceViaDialog() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest + { + partial interface IInterface + { + } - public abstract class TestClass : Base - { - public abstract void TestMeth[||]od(); - } -}"; + public class TestClass : IInterface + { + public int th[||]is[int i] + { + get => j = value; + } - var expected = @" -namespace PushUpTest -{ - public abstract class Base - { - public abstract void TestMethod(); - } + private static void BarBar() + {} - public abstract class TestClass : Base - { - } -}"; - await TestWithPullMemberDialogAsync(testText, expected, [("TestMethod", true)], index: 0); - } + protected static event EventHandler event1, event2; - [Fact] - public async Task PullMultipleEventsToClassViaDialog() - { - var testText = @" -using System; -namespace PushUpTest -{ - public class Base2 - { - } + internal static int Foo + { + get; set; + } + } + partial interface IInterface + { + } + } + """, """ + using System; + namespace PushUpTest + { + partial interface IInterface + { + int this[int i] { get; } - public class Testclass2 : Base2 - { - private static event EventHandler Event1, Eve[||]nt3, Event4; - } -}"; - var expected = @" -using System; -namespace PushUpTest -{ - public class Base2 - { - private static event EventHandler Event1; - private static event EventHandler Event3; - private static event EventHandler Event4; - } + int Foo { get; set; } - public class Testclass2 : Base2 - { - } -}"; - await TestWithPullMemberDialogAsync(testText, expected, index: 1); - } + event EventHandler event1; + event EventHandler event2; - [Fact] - public async Task PullMultipleAbstractEventsToInterfaceViaDialog() - { - var testText = @" -using System; -namespace PushUpTest -{ - public interface ITest - { - } + void BarBar(); + } - public abstract class Testclass2 : ITest - { - protected abstract event EventHandler Event1, Eve[||]nt3, Event4; - } -}"; - var expected = @" -using System; -namespace PushUpTest -{ - public interface ITest - { - event EventHandler Event1; - event EventHandler Event3; - event EventHandler Event4; - } + public class TestClass : IInterface + { + public int this[int i] + { + get => j = value; + } - public abstract class Testclass2 : ITest - { - public abstract event EventHandler Event1; - public abstract event EventHandler Event3; - public abstract event EventHandler Event4; - } -}"; - await TestWithPullMemberDialogAsync(testText, expected); - } + public void BarBar() + {} + + public event EventHandler event1; + public event EventHandler event2; + + public int Foo + { + get; set; + } + } + partial interface IInterface + { + } + } + """, index: 1); [Fact] - public async Task PullAbstractEventToClassViaDialog() - { - var testText = @" -using System; -namespace PushUpTest -{ - public class Base2 - { - } + public Task TestPullAsyncMethod() + => TestWithPullMemberDialogAsync(""" + using System.Threading.Tasks; - public abstract class Testclass2 : Base2 - { - private static abstract event EventHandler Event1, Eve[||]nt3, Event4; - } -}"; - var expected = @" -using System; -namespace PushUpTest -{ - public class Base2 - { - private static event EventHandler Event3; - } + internal interface IPullUp { } - public abstract class Testclass2 : Base2 - { - private static abstract event EventHandler Event1, Event4; - } -}"; + internal class PullUp : IPullUp + { + internal async Task PullU[||]pAsync() + { + await Task.Delay(1000); + } + } + """, """ + using System.Threading.Tasks; - await TestWithPullMemberDialogAsync(testText, expected, [("Event3", false)]); - } + internal interface IPullUp + { + Task PullUpAsync(); + } + + internal class PullUp : IPullUp + { + public async Task PullUpAsync() + { + await Task.Delay(1000); + } + } + """); [Fact] - public async Task PullNonPublicEventToInterfaceViaDialog() - { - var testText = @" -using System; -namespace PushUpTest -{ - public interface ITest - { - } - - public class Testclass2 : ITest - { - private event EventHandler Eve[||]nt3; - } -}"; - var expected = @" -using System; -namespace PushUpTest -{ - public interface ITest - { - event EventHandler Event3; - } + public Task PullMethodWithAbstractOptionToClassViaDialog() + => TestWithPullMemberDialogAsync(""" + namespace PushUpTest + { + public class Base + { + } - public class Testclass2 : ITest - { - public event EventHandler Event3; - } -}"; + public class TestClass : Base + { + public void TestMeth[||]od() + { + System.Console.WriteLine("Hello World"); + } + } + } + """, """ + namespace PushUpTest + { + public abstract class Base + { + public abstract void TestMethod(); + } - await TestWithPullMemberDialogAsync(testText, expected, [("Event3", false)]); - } + public class TestClass : Base + { + public override void TestMeth[||]od() + { + System.Console.WriteLine("Hello World"); + } + } + } + """, [("TestMethod", true)], index: 1); [Fact] - public async Task PullSingleNonPublicEventToInterfaceViaDialog() - { - var testText = @" -using System; -namespace PushUpTest -{ - public interface ITest - { - } - - public abstract class TestClass2 : ITest - { - protected event EventHandler Eve[||]nt3; - } -}"; - var expected = @" -using System; -namespace PushUpTest -{ - public interface ITest - { - event EventHandler Event3; - } + public Task PullAbstractMethodToClassViaDialog() + => TestWithPullMemberDialogAsync(""" + namespace PushUpTest + { + public class Base + { + } - public abstract class TestClass2 : ITest - { - public event EventHandler Event3; - } -}"; + public abstract class TestClass : Base + { + public abstract void TestMeth[||]od(); + } + } + """, """ + namespace PushUpTest + { + public abstract class Base + { + public abstract void TestMethod(); + } - await TestWithPullMemberDialogAsync(testText, expected, [("Event3", false)]); - } + public abstract class TestClass : Base + { + } + } + """, [("TestMethod", true)], index: 0); [Fact] - public async Task TestPullNonPublicEventWithAddAndRemoveMethodToInterfaceViaDialog() - { - var testText = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - } - - public class TestClass : IInterface - { - private event EventHandler Eve[||]nt1 - { - add + public Task PullMultipleEventsToClassViaDialog() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest { - System.Console.Writeline(""This is add""); + public class Base2 + { + } + + public class Testclass2 : Base2 + { + private static event EventHandler Event1, Eve[||]nt3, Event4; + } } - remove + """, """ + using System; + namespace PushUpTest { - System.Console.Writeline(""This is remove""); + public class Base2 + { + private static event EventHandler Event1; + private static event EventHandler Event3; + private static event EventHandler Event4; + } + + public class Testclass2 : Base2 + { + } } - } - } -}"; + """, index: 1); - var expected = @" -using System; -namespace PushUpTest -{ - interface IInterface - { - event EventHandler Event1; - } + [Fact] + public Task PullMultipleAbstractEventsToInterfaceViaDialog() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest + { + public interface ITest + { + } - public class TestClass : IInterface - { - public event EventHandler Event1 - { - add + public abstract class Testclass2 : ITest + { + protected abstract event EventHandler Event1, Eve[||]nt3, Event4; + } + } + """, """ + using System; + namespace PushUpTest { - System.Console.Writeline(""This is add""); + public interface ITest + { + event EventHandler Event1; + event EventHandler Event3; + event EventHandler Event4; + } + + public abstract class Testclass2 : ITest + { + public abstract event EventHandler Event1; + public abstract event EventHandler Event3; + public abstract event EventHandler Event4; + } } - remove + """); + + [Fact] + public Task PullAbstractEventToClassViaDialog() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest { - System.Console.Writeline(""This is remove""); + public class Base2 + { + } + + public abstract class Testclass2 : Base2 + { + private static abstract event EventHandler Event1, Eve[||]nt3, Event4; + } } - } - } -}"; + """, """ + using System; + namespace PushUpTest + { + public class Base2 + { + private static event EventHandler Event3; + } - await TestWithPullMemberDialogAsync(testText, expected, [("Event1", false)]); - } + public abstract class Testclass2 : Base2 + { + private static abstract event EventHandler Event1, Event4; + } + } + """, [("Event3", false)]); [Fact] - public async Task PullFieldsToClassViaDialog() - { - var testText = @" -using System; -namespace PushUpTest -{ - public class Base2 - { - } - - public class Testclass2 : Base2 - { - public int i, [||]j = 10, k = 100; - } -}"; - var expected = @" -using System; -namespace PushUpTest -{ - public class Base2 - { - public int i; - public int j = 10; - public int k = 100; - } + public Task PullNonPublicEventToInterfaceViaDialog() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest + { + public interface ITest + { + } - public class Testclass2 : Base2 - { - } -}"; + public class Testclass2 : ITest + { + private event EventHandler Eve[||]nt3; + } + } + """, """ + using System; + namespace PushUpTest + { + public interface ITest + { + event EventHandler Event3; + } - await TestWithPullMemberDialogAsync(testText, expected, index: 1); - } + public class Testclass2 : ITest + { + public event EventHandler Event3; + } + } + """, [("Event3", false)]); [Fact] - public async Task PullNonPublicPropertyWithArrowToInterfaceViaDialog() - { - var testText = @" -using System; -namespace PushUpTest -{ - public interface ITest - { - } - - public class Testclass2 : ITest - { - private double Test[||]Property => 2.717; - } -}"; - var expected = @" -using System; -namespace PushUpTest -{ - public interface ITest - { - double TestProperty { get; } - } + public Task PullSingleNonPublicEventToInterfaceViaDialog() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest + { + public interface ITest + { + } - public class Testclass2 : ITest - { - public readonly double TestProperty => 2.717; - } -}"; + public abstract class TestClass2 : ITest + { + protected event EventHandler Eve[||]nt3; + } + } + """, """ + using System; + namespace PushUpTest + { + public interface ITest + { + event EventHandler Event3; + } - await TestWithPullMemberDialogAsync(testText, expected); - } + public abstract class TestClass2 : ITest + { + public event EventHandler Event3; + } + } + """, [("Event3", false)]); [Fact] - public async Task PullNonPublicPropertyToInterfaceViaDialog() - { - var testText = @" -using System; -namespace PushUpTest -{ - public interface ITest - { - } - - public class Testclass2 : ITest - { - private double Test[||]Property - { - get; - set; - } - } -}"; - var expected = @" -using System; -namespace PushUpTest -{ - public interface ITest - { - double TestProperty { get; set; } - } + public Task TestPullNonPublicEventWithAddAndRemoveMethodToInterfaceViaDialog() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest + { + interface IInterface + { + } - public class Testclass2 : ITest - { - public double TestProperty - { - get; - set; - } - } -}"; + public class TestClass : IInterface + { + private event EventHandler Eve[||]nt1 + { + add + { + System.Console.Writeline("This is add"); + } + remove + { + System.Console.Writeline("This is remove"); + } + } + } + } + """, """ + using System; + namespace PushUpTest + { + interface IInterface + { + event EventHandler Event1; + } - await TestWithPullMemberDialogAsync(testText, expected); - } + public class TestClass : IInterface + { + public event EventHandler Event1 + { + add + { + System.Console.Writeline("This is add"); + } + remove + { + System.Console.Writeline("This is remove"); + } + } + } + } + """, [("Event1", false)]); [Fact] - public async Task PullNonPublicPropertyWithSingleAccessorToInterfaceViaDialog() - { - var testText = @" -using System; -namespace PushUpTest -{ - public interface ITest - { - } - - public class Testclass2 : ITest - { - private static double Test[||]Property - { - set; - } - } -}"; - var expected = @" -using System; -namespace PushUpTest -{ - public interface ITest - { - double TestProperty { set; } - } + public Task PullFieldsToClassViaDialog() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest + { + public class Base2 + { + } - public class Testclass2 : ITest - { - public double Test[||]Property - { - set; - } - } -}"; + public class Testclass2 : Base2 + { + public int i, [||]j = 10, k = 100; + } + } + """, """ + using System; + namespace PushUpTest + { + public class Base2 + { + public int i; + public int j = 10; + public int k = 100; + } - await TestWithPullMemberDialogAsync(testText, expected); - } + public class Testclass2 : Base2 + { + } + } + """, index: 1); - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34268")] - public async Task TestPullPropertyToAbstractClassViaDialogWithMakeAbstractOption() - { - var testText = @" -abstract class B -{ -} + [Fact] + public Task PullNonPublicPropertyWithArrowToInterfaceViaDialog() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest + { + public interface ITest + { + } -class D : B -{ - int [||]X => 7; -}"; - var expected = @" -abstract class B -{ - private abstract int X { get; } -} + public class Testclass2 : ITest + { + private double Test[||]Property => 2.717; + } + } + """, """ + using System; + namespace PushUpTest + { + public interface ITest + { + double TestProperty { get; } + } -class D : B -{ - override int X => 7; -}"; - await TestWithPullMemberDialogAsync(testText, expected, selection: [("X", true)], index: 1); - } + public class Testclass2 : ITest + { + public readonly double TestProperty => 2.717; + } + } + """); [Fact] - public async Task PullEventUpToAbstractClassViaDialogWithMakeAbstractOption() - { - var testText = @" -using System; -namespace PushUpTest -{ - public class Base2 - { - } + public Task PullNonPublicPropertyToInterfaceViaDialog() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest + { + public interface ITest + { + } - public class Testclass2 : Base2 - { - private event EventHandler Event1, Eve[||]nt3, Event4; - } -}"; - var expected = @" -using System; -namespace PushUpTest -{ - public abstract class Base2 - { - private abstract event EventHandler Event3; - } + public class Testclass2 : ITest + { + private double Test[||]Property + { + get; + set; + } + } + } + """, """ + using System; + namespace PushUpTest + { + public interface ITest + { + double TestProperty { get; set; } + } - public class Testclass2 : Base2 - { - private event EventHandler Event1; - private override event EventHandler Eve[||]nt3; - private event EventHandler Event4; - } -}"; - await TestWithPullMemberDialogAsync(testText, expected, selection: [("Event3", true)], index: 1); - } + public class Testclass2 : ITest + { + public double TestProperty + { + get; + set; + } + } + } + """); [Fact] - public async Task TestPullEventWithAddAndRemoveMethodToClassViaDialogWithMakeAbstractOption() - { - var testText = @" -using System; -namespace PushUpTest -{ - public class BaseClass - { - } - - public class TestClass : BaseClass - { - public event EventHandler Eve[||]nt1 - { - add + public Task PullNonPublicPropertyWithSingleAccessorToInterfaceViaDialog() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest { - System.Console.Writeline(""This is add""); + public interface ITest + { + } + + public class Testclass2 : ITest + { + private static double Test[||]Property + { + set; + } + } } - remove + """, """ + using System; + namespace PushUpTest { - System.Console.Writeline(""This is remove""); + public interface ITest + { + double TestProperty { set; } + } + + public class Testclass2 : ITest + { + public double Test[||]Property + { + set; + } + } } - } - } -}"; + """); - var expected = @" -using System; -namespace PushUpTest -{ - public abstract class BaseClass - { - public abstract event EventHandler Event1; - } + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34268")] + public Task TestPullPropertyToAbstractClassViaDialogWithMakeAbstractOption() + => TestWithPullMemberDialogAsync(""" + abstract class B + { + } - public class TestClass : BaseClass - { - public override event EventHandler Event1 - { - add + class D : B { - System.Console.Writeline(""This is add""); + int [||]X => 7; } - remove + """, """ + abstract class B { - System.Console.Writeline(""This is remove""); + private abstract int X { get; } } - } - } -}"; - await TestWithPullMemberDialogAsync(testText, expected, [("Event1", true)], index: 1); - } + class D : B + { + override int X => 7; + } + """, selection: [("X", true)], index: 1); - #endregion Dialog + [Fact] + public Task PullEventUpToAbstractClassViaDialogWithMakeAbstractOption() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest + { + public class Base2 + { + } - #region Selections and caret position - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestArgsIsPartOfHeader() - { - var testText = @" -using System; + public class Testclass2 : Base2 + { + private event EventHandler Event1, Eve[||]nt3, Event4; + } + } + """, """ + using System; + namespace PushUpTest + { + public abstract class Base2 + { + private abstract event EventHandler Event3; + } -namespace PushUpTest -{ - class TestAttribute : Attribute { } - class Test2Attribute : Attribute { } - public class A - { - } + public class Testclass2 : Base2 + { + private event EventHandler Event1; + private override event EventHandler Eve[||]nt3; + private event EventHandler Event4; + } + } + """, selection: [("Event3", true)], index: 1); - public class B : A - { - [Test] - [Test2] - void C([||]) - { - } - } -}"; - var expected = @" -using System; + [Fact] + public Task TestPullEventWithAddAndRemoveMethodToClassViaDialogWithMakeAbstractOption() + => TestWithPullMemberDialogAsync(""" + using System; + namespace PushUpTest + { + public class BaseClass + { + } -namespace PushUpTest -{ - class TestAttribute : Attribute { } - class Test2Attribute : Attribute { } - public class A - { - [Test] - [Test2] - void C() - { - } - } + public class TestClass : BaseClass + { + public event EventHandler Eve[||]nt1 + { + add + { + System.Console.Writeline("This is add"); + } + remove + { + System.Console.Writeline("This is remove"); + } + } + } + } + """, """ + using System; + namespace PushUpTest + { + public abstract class BaseClass + { + public abstract event EventHandler Event1; + } - public class B : A - { - } -}"; + public class TestClass : BaseClass + { + public override event EventHandler Event1 + { + add + { + System.Console.Writeline("This is add"); + } + remove + { + System.Console.Writeline("This is remove"); + } + } + } + } + """, [("Event1", true)], index: 1); - await TestWithPullMemberDialogAsync(testText, expected); - } + #endregion Dialog + #region Selections and caret position [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestRefactoringCaretBeforeAttributes() - { - var testText = @" -using System; - -namespace PushUpTest -{ - class TestAttribute : Attribute { } - class Test2Attribute : Attribute { } - public class A - { - } + public Task TestArgsIsPartOfHeader() + => TestWithPullMemberDialogAsync(""" + using System; - public class B : A - { - [||][Test] - [Test2] - void C() - { - } - } -}"; - var expected = @" -using System; + namespace PushUpTest + { + class TestAttribute : Attribute { } + class Test2Attribute : Attribute { } + public class A + { + } -namespace PushUpTest -{ - class TestAttribute : Attribute { } - class Test2Attribute : Attribute { } - public class A - { - [Test] - [Test2] - void C() - { - } - } + public class B : A + { + [Test] + [Test2] + void C([||]) + { + } + } + } + """, """ + using System; - public class B : A - { - } -}"; + namespace PushUpTest + { + class TestAttribute : Attribute { } + class Test2Attribute : Attribute { } + public class A + { + [Test] + [Test2] + void C() + { + } + } - await TestWithPullMemberDialogAsync(testText, expected); - } + public class B : A + { + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestMissingRefactoringCaretBetweenAttributes() - { - var testText = @" -using System; - -namespace PushUpTest -{ - class TestAttribute : Attribute { } - class Test2Attribute : Attribute { } - public class A - { - } + public Task TestRefactoringCaretBeforeAttributes() + => TestWithPullMemberDialogAsync(""" + using System; - public class B : A - { - [Test] - [||][Test2] - void C() - { - } - } -}"; - await TestQuickActionNotProvidedAsync(testText); - } + namespace PushUpTest + { + class TestAttribute : Attribute { } + class Test2Attribute : Attribute { } + public class A + { + } - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestRefactoringSelectionWithAttributes1() - { - var testText = @" -using System; + public class B : A + { + [||][Test] + [Test2] + void C() + { + } + } + } + """, """ + using System; -namespace PushUpTest -{ - class TestAttribute : Attribute { } - public class A - { - } + namespace PushUpTest + { + class TestAttribute : Attribute { } + class Test2Attribute : Attribute { } + public class A + { + [Test] + [Test2] + void C() + { + } + } - public class B : A - { - [Test] - [|void C() - { - }|] - } -}"; - var expected = @" -using System; + public class B : A + { + } + } + """); -namespace PushUpTest -{ - class TestAttribute : Attribute { } - public class A - { - [Test] - void C() - { - } - } + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] + public Task TestMissingRefactoringCaretBetweenAttributes() + => TestQuickActionNotProvidedAsync(""" + using System; - public class B : A - { - } -}"; + namespace PushUpTest + { + class TestAttribute : Attribute { } + class Test2Attribute : Attribute { } + public class A + { + } - await TestWithPullMemberDialogAsync(testText, expected); - } + public class B : A + { + [Test] + [||][Test2] + void C() + { + } + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestRefactoringSelectionWithAttributes2() - { - var testText = @" -using System; - -namespace PushUpTest -{ - class TestAttribute : Attribute { } - public class A - { - } + public Task TestRefactoringSelectionWithAttributes1() + => TestWithPullMemberDialogAsync(""" + using System; - public class B : A - { - [|[Test] - void C() - { - }|] - } -}"; - var expected = @" -using System; + namespace PushUpTest + { + class TestAttribute : Attribute { } + public class A + { + } -namespace PushUpTest -{ - class TestAttribute : Attribute { } - public class A - { - [Test] - void C() - { - } - } + public class B : A + { + [Test] + [|void C() + { + }|] + } + } + """, """ + using System; - public class B : A - { - } -}"; + namespace PushUpTest + { + class TestAttribute : Attribute { } + public class A + { + [Test] + void C() + { + } + } - await TestWithPullMemberDialogAsync(testText, expected); - } + public class B : A + { + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestRefactoringSelectionWithAttributes3() - { - var testText = @" -using System; - -namespace PushUpTest -{ - class TestAttribute : Attribute { } - public class A - { - } - - public class B : A - { - [Test][| - void C() - { - } - |] - } -}"; - var expected = @" -using System; + public Task TestRefactoringSelectionWithAttributes2() + => TestWithPullMemberDialogAsync(""" + using System; -namespace PushUpTest -{ - class TestAttribute : Attribute { } - public class A - { - [Test] - void C() - { - } - } - - public class B : A - { - } -}"; - - await TestWithPullMemberDialogAsync(testText, expected); - } + namespace PushUpTest + { + class TestAttribute : Attribute { } + public class A + { + } - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestMissingRefactoringInAttributeList() - { - var testText = @" -using System; + public class B : A + { + [|[Test] + void C() + { + }|] + } + } + """, """ + using System; -namespace PushUpTest -{ - class TestAttribute : Attribute { } - public class A - { - } + namespace PushUpTest + { + class TestAttribute : Attribute { } + public class A + { + [Test] + void C() + { + } + } - public class B : A - { - [[||]Test] - void C() - { - } - } -}"; - await TestQuickActionNotProvidedAsync(testText); - } + public class B : A + { + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestMissingRefactoringSelectionAttributeList() - { - var testText = @" -using System; - -namespace PushUpTest -{ - class TestAttribute : Attribute { } - class Test2Attribute : Attribute { } - public class A - { - } + public Task TestRefactoringSelectionWithAttributes3() + => TestWithPullMemberDialogAsync(""" + using System; - public class B : A - { - [|[Test] - [Test2]|] - void C() - { - } - } -}"; - await TestQuickActionNotProvidedAsync(testText); - } + namespace PushUpTest + { + class TestAttribute : Attribute { } + public class A + { + } - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestMissingRefactoringCaretInAttributeList() - { - var testText = @" -using System; + public class B : A + { + [Test][| + void C() + { + } + |] + } + } + """, """ + using System; -namespace PushUpTest -{ - class TestAttribute : Attribute { } - class Test2Attribute : Attribute { } - public class A - { - } + namespace PushUpTest + { + class TestAttribute : Attribute { } + public class A + { + [Test] + void C() + { + } + } - public class B : A - { - [[||]Test] - [Test2] - void C() - { - } - } -}"; - await TestQuickActionNotProvidedAsync(testText); - } + public class B : A + { + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestMissingRefactoringCaretBetweenAttributeLists() - { - var testText = @" -using System; + public Task TestMissingRefactoringInAttributeList() + => TestQuickActionNotProvidedAsync(""" + using System; -namespace PushUpTest -{ - class TestAttribute : Attribute { } - class Test2Attribute : Attribute { } - public class A - { - } + namespace PushUpTest + { + class TestAttribute : Attribute { } + public class A + { + } - public class B : A - { - [Test] - [||][Test2] - void C() - { - } - } -}"; - await TestQuickActionNotProvidedAsync(testText); - } + public class B : A + { + [[||]Test] + void C() + { + } + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestMissingRefactoringSelectionAttributeList2() - { - var testText = @" -using System; + public Task TestMissingRefactoringSelectionAttributeList() + => TestQuickActionNotProvidedAsync(""" + using System; -namespace PushUpTest -{ - class TestAttribute : Attribute { } - class Test2Attribute : Attribute { } - public class A - { - } + namespace PushUpTest + { + class TestAttribute : Attribute { } + class Test2Attribute : Attribute { } + public class A + { + } - public class B : A - { - [|[Test]|] - [Test2] - void C() - { - } - } -}"; - await TestQuickActionNotProvidedAsync(testText); - } + public class B : A + { + [|[Test] + [Test2]|] + void C() + { + } + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestMissingRefactoringSelectAttributeList() - { - var testText = @" -using System; + public Task TestMissingRefactoringCaretInAttributeList() + => TestQuickActionNotProvidedAsync(""" + using System; -namespace PushUpTest -{ - class TestAttribute : Attribute { } - public class A - { - } + namespace PushUpTest + { + class TestAttribute : Attribute { } + class Test2Attribute : Attribute { } + public class A + { + } - public class B : A - { - [|[Test]|] - void C() - { - } - } -}"; - await TestQuickActionNotProvidedAsync(testText); - } + public class B : A + { + [[||]Test] + [Test2] + void C() + { + } + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestRefactoringCaretLocAfterAttributes1() - { - var testText = @" -using System; + public Task TestMissingRefactoringCaretBetweenAttributeLists() + => TestQuickActionNotProvidedAsync(""" + using System; -namespace PushUpTest -{ - class TestAttribute : Attribute { } - public class A - { - } + namespace PushUpTest + { + class TestAttribute : Attribute { } + class Test2Attribute : Attribute { } + public class A + { + } - public class B : A - { - [Test] - [||]void C() - { - } - } -}"; - var expected = @" -using System; + public class B : A + { + [Test] + [||][Test2] + void C() + { + } + } + } + """); -namespace PushUpTest -{ - class TestAttribute : Attribute { } - public class A - { - [Test] - void C() - { - } - } + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] + public Task TestMissingRefactoringSelectionAttributeList2() + => TestQuickActionNotProvidedAsync(""" + using System; - public class B : A - { - } -}"; + namespace PushUpTest + { + class TestAttribute : Attribute { } + class Test2Attribute : Attribute { } + public class A + { + } - await TestWithPullMemberDialogAsync(testText, expected); - } + public class B : A + { + [|[Test]|] + [Test2] + void C() + { + } + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestRefactoringCaretLocAfterAttributes2() - { - var testText = @" -using System; + public Task TestMissingRefactoringSelectAttributeList() + => TestQuickActionNotProvidedAsync(""" + using System; -namespace PushUpTest -{ - class TestAttribute : Attribute { } - class Test2Attribute : Attribute { } - public class A - { - } + namespace PushUpTest + { + class TestAttribute : Attribute { } + public class A + { + } - public class B : A - { - [Test] - // Comment1 - [Test2] - // Comment2 - [||]void C() - { - } - } -}"; - var expected = @" -using System; + public class B : A + { + [|[Test]|] + void C() + { + } + } + } + """); -namespace PushUpTest -{ - class TestAttribute : Attribute { } - class Test2Attribute : Attribute { } - public class A - { - [Test] - // Comment1 - [Test2] - // Comment2 - void C() - { - } - } + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] + public Task TestRefactoringCaretLocAfterAttributes1() + => TestWithPullMemberDialogAsync(""" + using System; - public class B : A - { - } -}"; + namespace PushUpTest + { + class TestAttribute : Attribute { } + public class A + { + } - await TestWithPullMemberDialogAsync(testText, expected); - } + public class B : A + { + [Test] + [||]void C() + { + } + } + } + """, """ + using System; + + namespace PushUpTest + { + class TestAttribute : Attribute { } + public class A + { + [Test] + void C() + { + } + } + + public class B : A + { + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestRefactoringCaretLoc1() - { - var testText = @" -namespace PushUpTest -{ - public class A - { - } + public Task TestRefactoringCaretLocAfterAttributes2() + => TestWithPullMemberDialogAsync(""" + using System; - public class B : A - { - [||]void C() - { - } - } -}"; - var expected = @" -namespace PushUpTest -{ - public class A - { - void C() - { - } - } + namespace PushUpTest + { + class TestAttribute : Attribute { } + class Test2Attribute : Attribute { } + public class A + { + } - public class B : A - { - } -}"; + public class B : A + { + [Test] + // Comment1 + [Test2] + // Comment2 + [||]void C() + { + } + } + } + """, """ + using System; - await TestWithPullMemberDialogAsync(testText, expected); - } + namespace PushUpTest + { + class TestAttribute : Attribute { } + class Test2Attribute : Attribute { } + public class A + { + [Test] + // Comment1 + [Test2] + // Comment2 + void C() + { + } + } - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestRefactoringSelection() - { - var testText = @" -namespace PushUpTest -{ - public class A - { - } + public class B : A + { + } + } + """); - public class B : A - { - [|void C() - { - }|] - } -}"; - var expected = @" -namespace PushUpTest -{ - public class A - { - void C() - { - } - } + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] + public Task TestRefactoringCaretLoc1() + => TestWithPullMemberDialogAsync(""" + namespace PushUpTest + { + public class A + { + } - public class B : A - { - } -}"; + public class B : A + { + [||]void C() + { + } + } + } + """, """ + namespace PushUpTest + { + public class A + { + void C() + { + } + } - await TestWithPullMemberDialogAsync(testText, expected); - } + public class B : A + { + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestRefactoringSelectionComments() - { - var testText = @" -namespace PushUpTest -{ - public class A - { - } - - public class B : A - { [| - // Comment1 - void C() - { - }|] - } -}"; - var expected = @" -namespace PushUpTest -{ - public class A - { - // Comment1 - void C() - { - } - } + public Task TestRefactoringSelection() + => TestWithPullMemberDialogAsync(""" + namespace PushUpTest + { + public class A + { + } - public class B : A - { - } -}"; + public class B : A + { + [|void C() + { + }|] + } + } + """, """ + namespace PushUpTest + { + public class A + { + void C() + { + } + } - await TestWithPullMemberDialogAsync(testText, expected); - } + public class B : A + { + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestRefactoringSelectionComments2() - { - var testText = @" -namespace PushUpTest -{ - public class A - { - } - - public class B : A - { - [|/// - /// Test - /// - void C() - { - }|] - } -}"; - var expected = @" -namespace PushUpTest -{ - public class A - { - /// - /// Test - /// - void C() - { - } - } + public Task TestRefactoringSelectionComments() + => TestWithPullMemberDialogAsync(""" + namespace PushUpTest + { + public class A + { + } - public class B : A - { - } -}"; + public class B : A + { [| + // Comment1 + void C() + { + }|] + } + } + """, """ + namespace PushUpTest + { + public class A + { + // Comment1 + void C() + { + } + } - await TestWithPullMemberDialogAsync(testText, expected); - } + public class B : A + { + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestRefactoringSelectionComments3() - { - var testText = @" -namespace PushUpTest -{ - public class A - { - } + public Task TestRefactoringSelectionComments2() + => TestWithPullMemberDialogAsync(""" + namespace PushUpTest + { + public class A + { + } - public class B : A - { - /// - [|/// Test - /// - void C() - { - }|] - } -}"; - var expected = @" -namespace PushUpTest -{ - public class A - { - /// - /// Test - /// - void C() - { - } - } + public class B : A + { + [|/// + /// Test + /// + void C() + { + }|] + } + } + """, """ + namespace PushUpTest + { + public class A + { + /// + /// Test + /// + void C() + { + } + } - public class B : A - { - } -}"; + public class B : A + { + } + } + """); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] + public Task TestRefactoringSelectionComments3() + => TestWithPullMemberDialogAsync(""" + namespace PushUpTest + { + public class A + { + } + + public class B : A + { + /// + [|/// Test + /// + void C() + { + }|] + } + } + """, """ + namespace PushUpTest + { + public class A + { + /// + /// Test + /// + void C() + { + } + } - await TestWithPullMemberDialogAsync(testText, expected); - } + public class B : A + { + } + } + """); [Fact] - public async Task TestRefactoringSelectionFieldKeyword1_NoAction() - { - var text = @" -public class BaseClass -{ -} + public Task TestRefactoringSelectionFieldKeyword1_NoAction() + => TestQuickActionNotProvidedAsync(""" + public class BaseClass + { + } -public class Bar : BaseClass -{ - pub[|l|]ic int Goo = 10; -}"; - await TestQuickActionNotProvidedAsync(text); - } + public class Bar : BaseClass + { + pub[|l|]ic int Goo = 10; + } + """); [Fact] - public async Task TestRefactoringSelectionFieldKeyword2() - { - var text = @" -public class BaseClass -{ -} + public Task TestRefactoringSelectionFieldKeyword2() + => TestWithPullMemberDialogAsync(""" + public class BaseClass + { + } -public class Bar : BaseClass -{ - pub[||]lic int Goo = 10; -}"; - var expected = @" -public class BaseClass -{ - public int Goo = 10; -} + public class Bar : BaseClass + { + pub[||]lic int Goo = 10; + } + """, """ + public class BaseClass + { + public int Goo = 10; + } -public class Bar : BaseClass -{ -}"; - await TestWithPullMemberDialogAsync(text, expected); - } + public class Bar : BaseClass + { + } + """); [Fact] - public async Task TestRefactoringSelectionFieldAfterSemicolon() - { - var text = @" -public class BaseClass -{ -} + public Task TestRefactoringSelectionFieldAfterSemicolon() + => TestWithPullMemberDialogAsync(""" + public class BaseClass + { + } -public class Bar : BaseClass -{ - public int Goo = 10;[||] -}"; - var expected = @" -public class BaseClass -{ - public int Goo = 10; -} + public class Bar : BaseClass + { + public int Goo = 10;[||] + } + """, """ + public class BaseClass + { + public int Goo = 10; + } -public class Bar : BaseClass -{ -}"; - await TestWithPullMemberDialogAsync(text, expected); - } + public class Bar : BaseClass + { + } + """); [Fact] - public async Task TestRefactoringSelectionFieldEntireDeclaration() - { - var text = @" -public class BaseClass -{ -} + public Task TestRefactoringSelectionFieldEntireDeclaration() + => TestWithPullMemberDialogAsync(""" + public class BaseClass + { + } -public class Bar : BaseClass -{ - [|public int Goo = 10;|] -}"; - var expected = @" -public class BaseClass -{ - public int Goo = 10; -} + public class Bar : BaseClass + { + [|public int Goo = 10;|] + } + """, """ + public class BaseClass + { + public int Goo = 10; + } -public class Bar : BaseClass -{ -}"; - await TestWithPullMemberDialogAsync(text, expected); - } + public class Bar : BaseClass + { + } + """); [Fact] - public async Task TestRefactoringSelectionMultipleFieldsInDeclaration1() - { - var text = @" -public class BaseClass -{ -} + public Task TestRefactoringSelectionMultipleFieldsInDeclaration1() + => TestWithPullMemberDialogAsync(""" + public class BaseClass + { + } -public class Bar : BaseClass -{ - [|public int Goo = 10, Foo = 9;|] -}"; - var expected = @" -public class BaseClass -{ - public int Goo = 10; - public int Foo = 9; -} + public class Bar : BaseClass + { + [|public int Goo = 10, Foo = 9;|] + } + """, """ + public class BaseClass + { + public int Goo = 10; + public int Foo = 9; + } -public class Bar : BaseClass -{ -}"; - await TestWithPullMemberDialogAsync(text, expected); - } + public class Bar : BaseClass + { + } + """); [Fact] - public async Task TestRefactoringSelectionMultipleFieldsInDeclaration2() - { - var text = @" -public class BaseClass -{ -} + public Task TestRefactoringSelectionMultipleFieldsInDeclaration2() + => TestWithPullMemberDialogAsync(""" + public class BaseClass + { + } -public class Bar : BaseClass -{ - public int Go[||]o = 10, Foo = 9; -}"; - var expected = @" -public class BaseClass -{ - public int Goo = 10; -} + public class Bar : BaseClass + { + public int Go[||]o = 10, Foo = 9; + } + """, """ + public class BaseClass + { + public int Goo = 10; + } -public class Bar : BaseClass -{ - public int Foo = 9; -}"; - await TestWithPullMemberDialogAsync(text, expected); - } + public class Bar : BaseClass + { + public int Foo = 9; + } + """); [Fact] - public async Task TestRefactoringSelectionMultipleFieldsInDeclaration3() - { - var text = @" -public class BaseClass -{ -} + public Task TestRefactoringSelectionMultipleFieldsInDeclaration3() + => TestWithPullMemberDialogAsync(""" + public class BaseClass + { + } -public class Bar : BaseClass -{ - public int Goo = 10, [||]Foo = 9; -}"; - var expected = @" -public class BaseClass -{ - public int Foo = 9; -} + public class Bar : BaseClass + { + public int Goo = 10, [||]Foo = 9; + } + """, """ + public class BaseClass + { + public int Foo = 9; + } -public class Bar : BaseClass -{ - public int Goo = 10; -}"; - await TestWithPullMemberDialogAsync(text, expected); - } + public class Bar : BaseClass + { + public int Goo = 10; + } + """); [Fact] - public async Task TestRefactoringSelectionMultipleMembers1() - { - var text = @" -public class BaseClass -{ -} + public Task TestRefactoringSelectionMultipleMembers1() + => TestWithPullMemberDialogAsync(""" + public class BaseClass + { + } -public class Bar : BaseClass -{ - [|public int Goo = 10, Foo = 9; + public class Bar : BaseClass + { + [|public int Goo = 10, Foo = 9; - public int DoSomething() - { - return 5; - }|] -}"; - var expected = @" -public class BaseClass -{ - public int Goo = 10; - public int Foo = 9; + public int DoSomething() + { + return 5; + }|] + } + """, """ + public class BaseClass + { + public int Goo = 10; + public int Foo = 9; - public int DoSomething() - { - return 5; - } -} + public int DoSomething() + { + return 5; + } + } -public class Bar : BaseClass -{ -}"; - await TestWithPullMemberDialogAsync(text, expected); - } + public class Bar : BaseClass + { + } + """); // Some of these have weird whitespace spacing that might suggest a bug [Fact] - public async Task TestRefactoringSelectionMultipleMembers2() - { - var text = @" -public class BaseClass -{ -} + public Task TestRefactoringSelectionMultipleMembers2() + => TestWithPullMemberDialogAsync(""" + public class BaseClass + { + } -public class Bar : BaseClass -{ - public int DoSomething() - { - [|return 5; - } + public class Bar : BaseClass + { + public int DoSomething() + { + [|return 5; + } - public int Goo = 10, Foo = 9;|] -}"; - var expected = @" -public class BaseClass -{ + public int Goo = 10, Foo = 9;|] + } + """, """ + public class BaseClass + { - public int Goo = 10; + public int Goo = 10; - public int Foo = 9; -} + public int Foo = 9; + } -public class Bar : BaseClass -{ - public int DoSomething() - { - return 5; - } -}"; - await TestWithPullMemberDialogAsync(text, expected); - } + public class Bar : BaseClass + { + public int DoSomething() + { + return 5; + } + } + """); [Fact] - public async Task TestRefactoringSelectionMultipleMembers3() - { - var text = @" -public class BaseClass -{ -} + public Task TestRefactoringSelectionMultipleMembers3() + => TestWithPullMemberDialogAsync(""" + public class BaseClass + { + } -public class Bar : BaseClass -{ - public int DoSom[|ething() - { - return 5; - } + public class Bar : BaseClass + { + public int DoSom[|ething() + { + return 5; + } - public int Go|]o = 10, Foo = 9; -}"; - var expected = @" -public class BaseClass -{ + public int Go|]o = 10, Foo = 9; + } + """, """ + public class BaseClass + { - public int Goo = 10; - public int DoSomething() - { - return 5; - } -} + public int Goo = 10; + public int DoSomething() + { + return 5; + } + } -public class Bar : BaseClass -{ - public int Foo = 9; -}"; - await TestWithPullMemberDialogAsync(text, expected); - } + public class Bar : BaseClass + { + public int Foo = 9; + } + """); [Fact] - public async Task TestRefactoringSelectionMultipleMembers4() - { - var text = @" -public class BaseClass -{ -} + public Task TestRefactoringSelectionMultipleMembers4() + => TestWithPullMemberDialogAsync(""" + public class BaseClass + { + } -public class Bar : BaseClass -{ - public int DoSomething()[| - { - return 5; - } + public class Bar : BaseClass + { + public int DoSomething()[| + { + return 5; + } - public int Goo = 10, F|]oo = 9; -}"; - var expected = @" -public class BaseClass -{ + public int Goo = 10, F|]oo = 9; + } + """, """ + public class BaseClass + { - public int Goo = 10; + public int Goo = 10; - public int Foo = 9; -} + public int Foo = 9; + } -public class Bar : BaseClass -{ - public int DoSomething() - { - return 5; - } -}"; - await TestWithPullMemberDialogAsync(text, expected); - } + public class Bar : BaseClass + { + public int DoSomething() + { + return 5; + } + } + """); [Fact] - public async Task TestRefactoringSelectionIncompleteField_NoAction1() - { - var text = @" -public class BaseClass -{ -} + public Task TestRefactoringSelectionIncompleteField_NoAction1() + => TestQuickActionNotProvidedAsync(""" + public class BaseClass + { + } -public class Bar : BaseClass -{ - publ[||] int Goo = 10; -}"; - // we expect a diagnostic/error, but also we shouldn't provide the refactoring - await TestQuickActionNotProvidedAsync(text); - } + public class Bar : BaseClass + { + publ[||] int Goo = 10; + } + """); [Fact] - public async Task TestRefactoringSelectionIncompleteField_NoAction2() - { - var text = @" -public class BaseClass -{ -} + public Task TestRefactoringSelectionIncompleteField_NoAction2() + => TestQuickActionNotProvidedAsync(""" + public class BaseClass + { + } -public class Bar : BaseClass -{ - [|publicc int Goo = 10;|] -}"; - // we expect a diagnostic/error, but also we shouldn't provide the refactoring - await TestQuickActionNotProvidedAsync(text); - } + public class Bar : BaseClass + { + [|publicc int Goo = 10;|] + } + """); [Fact] - public async Task TestRefactoringSelectionIncompleteMethod_NoAction() - { - var text = @" -public class BaseClass -{ -} + public Task TestRefactoringSelectionIncompleteMethod_NoAction() + => TestQuickActionNotProvidedAsync(""" + public class BaseClass + { + } -public class Bar : BaseClass -{ - publ[||] int DoSomething() { - return 5; - } -}"; - // we expect a diagnostic/error, but also we shouldn't provide the refactoring - await TestQuickActionNotProvidedAsync(text); - } + public class Bar : BaseClass + { + publ[||] int DoSomething() { + return 5; + } + } + """); #endregion } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/SyncNamespace/SyncNamespaceTests_ChangeNamespace.cs b/src/EditorFeatures/CSharpTest/CodeActions/SyncNamespace/SyncNamespaceTests_ChangeNamespace.cs index b821b64c58ad0..97a33d9db5983 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/SyncNamespace/SyncNamespaceTests_ChangeNamespace.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/SyncNamespace/SyncNamespaceTests_ChangeNamespace.cs @@ -20,8 +20,7 @@ public async Task ChangeNamespace_InvalidFolderName1() // No change namespace action because the folder name is not valid identifier var (folder, filePath) = CreateDocumentFilePath(["3B", "C"], "File1.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" @@ -34,8 +33,7 @@ class Class1 - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal: null); + """, expectedSourceOriginal: null); } [Fact] @@ -46,8 +44,7 @@ public async Task ChangeNamespace_InvalidFolderName2() // No change namespace action because the folder name is not valid identifier var (folder, filePath) = CreateDocumentFilePath(["B.3C", "D"], "File1.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" @@ -60,8 +57,7 @@ class Class1 - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal: null); + """, expectedSourceOriginal: null); } [Fact] @@ -71,8 +67,7 @@ public async Task ChangeNamespace_SingleDocumentNoReference() var declaredNamespace = "Foo.Bar"; var (folder, filePath) = CreateDocumentFilePath(["B", "C"], "File1.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" @@ -84,18 +79,14 @@ class Class1 } - """; - - var expectedSourceOriginal = - """ + """, """ namespace A.B.C { class Class1 { } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal); + """); } [Fact] @@ -105,8 +96,7 @@ public async Task ChangeNamespace_SingleDocumentNoReference_FileScopedNamespace( var declaredNamespace = "Foo.Bar"; var (folder, filePath) = CreateDocumentFilePath(["B", "C"], "File1.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" namespace [||]{{declaredNamespace}}; @@ -116,17 +106,13 @@ class Class1 } - """; - - var expectedSourceOriginal = - """ + """, """ namespace A.B.C; class Class1 { } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal); + """); } [Fact] @@ -136,8 +122,7 @@ public async Task ChangeNamespace_SingleDocumentLocalReference() var declaredNamespace = "Foo.Bar"; var (folder, filePath) = CreateDocumentFilePath(["B", "C"], "File1.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" @@ -159,10 +144,7 @@ class Class2 : {{declaredNamespace}}.Class1 } - """; - - var expectedSourceOriginal = - """ + """, """ namespace A.B.C { delegate void D1; @@ -179,8 +161,7 @@ class Class2 : Class1 void Class1.M1() { } } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal); + """); } [Fact] @@ -191,8 +172,7 @@ public async Task ChangeNamespace_WithCrefReference() var (folder, filePath) = CreateDocumentFilePath(["B", "C"], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" namespace [||]{{declaredNamespace}} @@ -224,10 +204,7 @@ class RefClass } - """; - - var expectedSourceOriginal = - """ + """, """ namespace A.B.C { /// @@ -241,9 +218,7 @@ public class Class1 public void M1() { } } } - """; - var expectedSourceReference = - """ + """, """ namespace Foo { using A.B.C; @@ -258,8 +233,7 @@ class RefClass { } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact] @@ -269,8 +243,7 @@ public async Task ChangeNamespace_WithCrefReferencesInVB() var declaredNamespace = "A.B.C.D"; var (folder, filePath) = CreateDocumentFilePath([], "File1.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" namespace [||]{{declaredNamespace}} @@ -296,10 +269,7 @@ Public ReadOnly Property C1 As Class1 End Class - """; - - var expectedSourceOriginal = - """ + """, """ namespace A.B.C { /// @@ -310,9 +280,7 @@ public class Class1 { } } - """; - var expectedSourceReference = - """ + """, """ Imports A.B.C ''' @@ -322,8 +290,7 @@ Imports A.B.C Public Class VBClass Public ReadOnly Property C1 As Class1 End Class - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact] @@ -334,8 +301,7 @@ public async Task ChangeNamespace_ReferencingTypesDeclaredInOtherDocument() var (folder, filePath) = CreateDocumentFilePath(["B", "C"], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" @@ -365,10 +331,7 @@ class Class4 {} } - """; - - var expectedSourceOriginal = - """ + """, """ using Foo; using Foo.Bar; using Foo.Bar.Baz; @@ -382,8 +345,7 @@ class Class1 private Class4 c4; } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal); + """); } [Fact] @@ -394,8 +356,7 @@ public async Task ChangeNamespace_ReferencingQualifiedTypesDeclaredInOtherDocume var (folder, filePath) = CreateDocumentFilePath(["B", "C"], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" @@ -425,10 +386,7 @@ class Class4 {} } - """; - - var expectedSourceOriginal = - """ + """, """ using Foo; using Foo.Bar; using Foo.Bar.Baz; @@ -442,8 +400,7 @@ class Class1 private Class4 c4; } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal); + """); } [Fact] @@ -454,8 +411,7 @@ public async Task ChangeNamespace_WithReferencesInOtherDocument() var (folder, filePath) = CreateDocumentFilePath(["B", "C"], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" namespace [||]{{declaredNamespace}} @@ -484,10 +440,7 @@ void M1() } - """; - - var expectedSourceOriginal = - """ + """, """ namespace A.B.C { class Class1 @@ -498,9 +451,7 @@ class Class2 { } } - """; - var expectedSourceReference = - """ + """, """ using A.B.C; namespace Foo @@ -515,8 +466,7 @@ void M1() } } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact] @@ -527,8 +477,7 @@ public async Task ChangeNamespace_WithQualifiedReferencesInOtherDocument() var (folder, filePath) = CreateDocumentFilePath(["B", "C"], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" namespace [||]{{declaredNamespace}} @@ -549,10 +498,7 @@ class RefClass : Interface1 } - """; - - var expectedSourceOriginal = - """ + """, """ namespace A.B.C { interface Interface1 @@ -560,9 +506,7 @@ interface Interface1 void M1(Interface1 c1); } } - """; - var expectedSourceReference = - """ + """, """ namespace Foo { using A.B.C; @@ -572,8 +516,7 @@ class RefClass : Interface1 void Interface1.M1(Interface1 c1){} } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact] @@ -584,8 +527,7 @@ public async Task ChangeNamespace_ChangeUsingsInMultipleContainers() var (folder, filePath) = CreateDocumentFilePath(["B", "C"], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" namespace [||]{{declaredNamespace}} @@ -615,19 +557,14 @@ class Class2 } - """; - - var expectedSourceOriginal = - """ + """, """ namespace A.B.C { class Class1 { } } - """; - var expectedSourceReference = - """ + """, """ namespace NS1 { using A.B.C; @@ -645,8 +582,7 @@ class Class2 } } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact] @@ -657,8 +593,7 @@ public async Task ChangeNamespace_WithAliasReferencesInOtherDocument() var (folder, filePath) = CreateDocumentFilePath(["B", "C"], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" namespace [||]{{declaredNamespace}} @@ -688,10 +623,7 @@ void M1() } - """; - - var expectedSourceOriginal = - """ + """, """ namespace A.B.C { class Class1 @@ -702,9 +634,7 @@ class Class2 { } } - """; - var expectedSourceReference = - """ + """, """ using System; using A.B.C; using Class1Alias = A.B.C.Class1; @@ -721,8 +651,7 @@ void M1() } } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact] @@ -732,8 +661,7 @@ public async Task ChangeToGlobalNamespace_SingleDocumentNoRef() var declaredNamespace = "Foo.Bar"; var (folder, filePath) = CreateDocumentFilePath([], "File1.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" using System; @@ -749,10 +677,7 @@ class Class1 - """; - - var expectedSourceOriginal = - """ + """, """ using System; // Comments before declaration. @@ -763,8 +688,7 @@ class Class1 // Comments before closing brace // Comments after declaration. - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal); + """); } [Fact] @@ -774,8 +698,7 @@ public async Task ChangeToGlobalNamespace_SingleDocumentLocalRef() var declaredNamespace = "Foo.Bar"; var (folder, filePath) = CreateDocumentFilePath([], "File1.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" namespace [||]{{declaredNamespace}} @@ -796,10 +719,7 @@ class Class2 : {{declaredNamespace}}.Class1 } - """; - - var expectedSourceOriginal = - """ + """, """ delegate void D1; interface Class1 @@ -814,8 +734,7 @@ class Class2 : Class1 void Class1.M1() { } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal); + """); } [Fact] @@ -826,8 +745,7 @@ public async Task ChangeToGlobalNamespace_WithReferencesInOtherDocument() var (folder, filePath) = CreateDocumentFilePath([], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" namespace [||]{{declaredNamespace}} @@ -856,10 +774,7 @@ void M1() } - """; - - var expectedSourceOriginal = - """ + """, """ class Class1 { } @@ -868,9 +783,7 @@ class Class2 { } - """; - var expectedSourceReference = - """ + """, """ namespace Foo { class RefClass @@ -883,8 +796,7 @@ void M1() } } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact] @@ -895,8 +807,7 @@ public async Task ChangeToGlobalNamespace_WithQualifiedReferencesInOtherDocument var (folder, filePath) = CreateDocumentFilePath([], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" namespace [||]{{declaredNamespace}} @@ -917,18 +828,13 @@ class RefClass : Interface1 } - """; - - var expectedSourceOriginal = - """ + """, """ interface Interface1 { void M1(Interface1 c1); } - """; - var expectedSourceReference = - """ + """, """ namespace Foo { class RefClass : Interface1 @@ -936,8 +842,7 @@ class RefClass : Interface1 void Interface1.M1(Interface1 c1){} } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact] @@ -948,8 +853,7 @@ public async Task ChangeToGlobalNamespace_WithReferenceAndConflictDeclarationInO var (folder, filePath) = CreateDocumentFilePath([], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" namespace [||]{{declaredNamespace}} @@ -973,17 +877,12 @@ class MyClass } - """; - - var expectedSourceOriginal = - """ + """, """ class MyClass { } - """; - var expectedSourceReference = - """ + """, """ namespace Foo { class RefClass @@ -995,8 +894,7 @@ class MyClass { } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact] @@ -1007,8 +905,7 @@ public async Task ChangeToGlobalNamespace_ReferencingTypesDeclaredInOtherDocumen var (folder, filePath) = CreateDocumentFilePath([], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" namespace [||]{{declaredNamespace}} @@ -1036,10 +933,7 @@ class Class4 {} } - """; - - var expectedSourceOriginal = - """ + """, """ using Foo; using Foo.Bar; using Foo.Bar.Baz; @@ -1051,8 +945,7 @@ class Class1 private Class4 c4; } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal); + """); } [Fact] @@ -1063,8 +956,7 @@ public async Task ChangeToGlobalNamespace_ChangeUsingsInMultipleContainers() var (folder, filePath) = CreateDocumentFilePath([], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" namespace [||]{{declaredNamespace}} @@ -1094,17 +986,12 @@ class Class2 } - """; - - var expectedSourceOriginal = - """ + """, """ class Class1 { } - """; - var expectedSourceReference = - """ + """, """ namespace NS1 { class Class2 @@ -1120,8 +1007,7 @@ class Class2 } } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact] @@ -1132,8 +1018,7 @@ public async Task ChangeToGlobalNamespace_WithAliasReferencesInOtherDocument() var (folder, filePath) = CreateDocumentFilePath([], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" namespace [||]{{declaredNamespace}} @@ -1163,10 +1048,7 @@ void M1() } - """; - - var expectedSourceOriginal = - """ + """, """ class Class1 { } @@ -1175,9 +1057,7 @@ class Class2 { } - """; - var expectedSourceReference = - """ + """, """ using System; using Class1Alias = Class1; @@ -1193,8 +1073,7 @@ void M1() } } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact] @@ -1202,8 +1081,7 @@ public async Task ChangeFromGlobalNamespace_SingleDocumentNoRef() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(["B", "C"], "File1.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" using System; @@ -1214,10 +1092,7 @@ class [||]Class1 - """; - - var expectedSourceOriginal = - """ + """, """ using System; namespace A.B.C @@ -1226,8 +1101,7 @@ class Class1 { } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal); + """); } [Fact] @@ -1235,8 +1109,7 @@ public async Task ChangeFromGlobalNamespace_SingleDocumentLocalRef() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(["B", "C"], "File1.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" @@ -1255,10 +1128,7 @@ void Class1.M1() { } } - """; - - var expectedSourceOriginal = - """ + """, """ namespace A.B.C { delegate void D1; @@ -1275,8 +1145,7 @@ class Class2 : Class1 void Class1.M1() { } } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal); + """); } [Fact] @@ -1286,8 +1155,7 @@ public async Task ChangeFromGlobalNamespace_WithReferencesInOtherDocument() var (folder, filePath) = CreateDocumentFilePath(["B", "C"], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" class [||]Class1 @@ -1311,10 +1179,7 @@ void M1() } - """; - - var expectedSourceOriginal = - """ + """, """ namespace A.B.C { class Class1 @@ -1325,9 +1190,7 @@ class Class2 { } } - """; - var expectedSourceReference = - """ + """, """ using A.B.C; namespace Foo @@ -1342,8 +1205,7 @@ void M1() } } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact] @@ -1352,8 +1214,7 @@ public async Task ChangeFromGlobalNamespace_WithQualifiedReferencesInOtherDocume var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(["B", "C"], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" interface [||]Interface1 @@ -1369,10 +1230,7 @@ void Interface1.M1(Interface1 c1){} } - """; - - var expectedSourceOriginal = - """ + """, """ namespace A.B.C { interface Interface1 @@ -1380,9 +1238,7 @@ interface Interface1 void M1(Interface1 c1); } } - """; - var expectedSourceReference = - """ + """, """ using A.B.C; namespace Foo @@ -1392,8 +1248,7 @@ class RefClass : Interface1 void Interface1.M1(Interface1 c1){} } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact] @@ -1402,8 +1257,7 @@ public async Task ChangeFromGlobalNamespace_ReferencingQualifiedTypesDeclaredInO var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(["B", "C"], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" @@ -1431,10 +1285,7 @@ class Class4 {} } - """; - - var expectedSourceOriginal = - """ + """, """ namespace A.B.C { class Class1 @@ -1444,8 +1295,7 @@ class Class1 private Class4 c4; } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal); + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34707")] @@ -1454,8 +1304,7 @@ public async Task ChangeFromGlobalNamespace_DoNotSimplifyUnrelatedCode() var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(["B", "C"], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" @@ -1490,10 +1339,7 @@ class Class4 {} } - """; - - var expectedSourceOriginal = - """ + """, """ namespace A.B.C { class Class1 @@ -1510,8 +1356,7 @@ void M1() } } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal); + """); } [Fact] @@ -1521,8 +1366,7 @@ public async Task ChangeFromGlobalNamespace_ChangeUsingsInMultipleContainers() var (folder, filePath) = CreateDocumentFilePath(["B", "C"], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" class [||]Class1 @@ -1549,19 +1393,14 @@ class Class2 } - """; - - var expectedSourceOriginal = - """ + """, """ namespace A.B.C { class Class1 { } } - """; - var expectedSourceReference = - """ + """, """ namespace NS1 { using System; @@ -1582,8 +1421,7 @@ class Class2 } } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact] @@ -1593,8 +1431,7 @@ public async Task ChangeFromGlobalNamespace_WithAliasReferencesInOtherDocument() var (folder, filePath) = CreateDocumentFilePath(["B", "C"], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" class [||]Class1 @@ -1622,10 +1459,7 @@ void M1() } - """; - - var expectedSourceOriginal = - """ + """, """ namespace A.B.C { class Class1 @@ -1636,9 +1470,7 @@ class Class2 { } } - """; - var expectedSourceReference = - """ + """, """ using A.B.C; using Class1Alias = Class1; @@ -1656,8 +1488,7 @@ void M1() } } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact] @@ -1667,8 +1498,7 @@ public async Task ChangeNamespace_WithReferencesInVBDocument() var declaredNamespace = "A.B.C.D"; var (folder, filePath) = CreateDocumentFilePath([], "File1.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" namespace [||]{{declaredNamespace}} @@ -1686,26 +1516,20 @@ Public ReadOnly Property C1 As Class1 End Class - """; - - var expectedSourceOriginal = - """ + """, """ namespace A.B.C { public class Class1 { } } - """; - var expectedSourceReference = - """ + """, """ Imports A.B.C Public Class VBClass Public ReadOnly Property C1 As Class1 End Class - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact] @@ -1715,8 +1539,7 @@ public async Task ChangeNamespace_WithQualifiedReferencesInVBDocument() var declaredNamespace = "A.B.C.D"; var (folder, filePath) = CreateDocumentFilePath([], "File1.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" @@ -1734,24 +1557,18 @@ Public ReadOnly Property C1 As A.B.C.D.Class1 End Class - """; - - var expectedSourceOriginal = - """ + """, """ namespace A.B.C { public class Class1 { } } - """; - var expectedSourceReference = - """ + """, """ Public Class VBClass Public ReadOnly Property C1 As A.B.C.Class1 End Class - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact] @@ -1760,8 +1577,7 @@ public async Task ChangeFromGlobalNamespace_WithReferencesInVBDocument() var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(["B", "C"], "File1.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" public class [||]Class1 @@ -1775,26 +1591,20 @@ Public ReadOnly Property C1 As Class1 End Class - """; - - var expectedSourceOriginal = - """ + """, """ namespace A.B.C { public class Class1 { } } - """; - var expectedSourceReference = - """ + """, """ Imports A.B.C Public Class VBClass Public ReadOnly Property C1 As Class1 End Class - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact] @@ -1803,8 +1613,7 @@ public async Task ChangeFromGlobalNamespace_WithCredReferences() var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(["B", "C"], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" /// <summary> @@ -1824,10 +1633,7 @@ class Bar } - """; - - var expectedSourceOriginal = - """ + """, """ namespace A.B.C { @@ -1838,9 +1644,7 @@ class Class1 { } } - """; - var expectedSourceReference = - """ + """, """ using A.B.C; namespace Foo @@ -1852,8 +1656,7 @@ class Bar { } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact] @@ -1863,8 +1666,7 @@ public async Task ChangeToGlobalNamespace_WithReferencesInVBDocument() var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath([], "File1.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" namespace [||]{{declaredNamespace}} @@ -1882,22 +1684,16 @@ Public ReadOnly Property C1 As Class1 End Class - """; - - var expectedSourceOriginal = - """ + """, """ public class Class1 { } - """; - var expectedSourceReference = - """ + """, """ Public Class VBClass Public ReadOnly Property C1 As Class1 End Class - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact] @@ -1907,8 +1703,7 @@ public async Task ChangeToGlobalNamespace_WithReferenceAndConflictDeclarationInV var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath([], "File1.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" namespace [||]{{declaredNamespace}} @@ -1929,17 +1724,12 @@ End Class End Namespace - """; - - var expectedSourceOriginal = - """ + """, """ public class MyClass { } - """; - var expectedSourceReference = - """ + """, """ Namespace Foo Public Class VBClass Public ReadOnly Property C1 As Global.MyClass @@ -1948,8 +1738,7 @@ End Class Public Class MyClass End Class End Namespace - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact] @@ -1960,8 +1749,7 @@ public async Task ChangeToGlobalNamespace_WithCredReferences() var (folder, filePath) = CreateDocumentFilePath([], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" namespace [||]{{declaredNamespace}} @@ -1988,10 +1776,7 @@ class RefClass } - """; - - var expectedSourceOriginal = - """ + """, """ /// /// See /// See @@ -2000,9 +1785,7 @@ public class Class1 { } - """; - var expectedSourceReference = - """ + """, """ namespace Foo { /// @@ -2013,8 +1796,7 @@ class RefClass { } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33890")] @@ -2024,8 +1806,7 @@ public async Task ChangeNamespace_ExtensionMethodInReducedForm() var (folder, filePath) = CreateDocumentFilePath(["B", "C"], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" namespace [||]{{defaultNamespace}} @@ -2046,10 +1827,7 @@ public class Class1 } - """; - - var expectedSourceOriginal = - $$""" + """, $$""" namespace A.B.C { public static class Extensions @@ -2057,9 +1835,7 @@ public static class Extensions public static bool Foo(this Class1 c1) => true; } } - """; - var expectedSourceReference = - $$""" + """, $$""" namespace {{defaultNamespace}} { using System; @@ -2070,8 +1846,7 @@ public class Class1 public bool Bar(Class1 c1) => c1.Foo(); } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33890")] @@ -2081,8 +1856,7 @@ public async Task ChangeNamespace_ExternsionMethodInRegularForm() var (folder, filePath) = CreateDocumentFilePath(["B", "C"], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" namespace [||]A @@ -2103,10 +1877,7 @@ public class Class1 } - """; - - var expectedSourceOriginal = - $$""" + """, $$""" namespace A.B.C { public static class Extensions @@ -2114,9 +1885,7 @@ public static class Extensions public static bool Foo(this Class1 c1) => true; } } - """; - var expectedSourceReference = - $$""" + """, $$""" using System; using A.B.C; @@ -2127,8 +1896,7 @@ public class Class1 public bool Bar(Class1 c1) => Extensions.Foo(c1); } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33890")] @@ -2138,8 +1906,7 @@ public async Task ChangeNamespace_ContainsBothTypeAndExternsionMethod() var (folder, filePath) = CreateDocumentFilePath(["B", "C"], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" namespace [||]A @@ -2163,10 +1930,7 @@ public class Class1 } - """; - - var expectedSourceOriginal = - """ + """, """ namespace A.B.C { public static class Extensions @@ -2177,9 +1941,7 @@ public static class Extensions public class Class2 { } } - """; - var expectedSourceReference = - """ + """, """ using System; using A.B.C; @@ -2190,8 +1952,7 @@ public class Class1 public bool Bar(Class1 c1, Class2 c2) => c2 == null ? c1.Foo() : true; } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33890")] @@ -2201,8 +1962,7 @@ public async Task ChangeNamespace_WithExtensionMethodReferencesInVBDocument() var declaredNamespace = "A.B.C.D"; var (folder, filePath) = CreateDocumentFilePath([], "File1.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" using System; @@ -2225,10 +1985,7 @@ End Function End Class - """; - - var expectedSourceOriginal = - $$""" + """, $$""" using System; namespace {{defaultNamespace}} @@ -2238,9 +1995,7 @@ public static class Extensions public static bool Foo(this String s) => true; } } - """; - var expectedSourceReference = - $""" + """, $""" Imports {defaultNamespace} Public Class VBClass @@ -2248,8 +2003,7 @@ Public Function Foo(s As string) As Boolean Return s.Foo() End Function End Class - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37891")] @@ -2260,8 +2014,7 @@ public async Task ChangeNamespace_WithMemberAccessReferencesInOtherDocument() var documentPath1 = CreateDocumentFilePath(["B", "C"], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" namespace [||]{{declaredNamespace}} @@ -2285,10 +2038,7 @@ Enum1 M1() } - """; - - var expectedSourceOriginal = - """ + """, """ namespace A.B.C { enum Enum1 @@ -2298,9 +2048,7 @@ enum Enum1 C } } - """; - var expectedSourceReference = - """ + """, """ using A.B.C; namespace Foo @@ -2313,8 +2061,7 @@ Enum1 M1() } } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37891")] @@ -2325,8 +2072,7 @@ public async Task ChangeToGlobalNamespace_WithMemberAccessReferencesInOtherDocum var documentPath1 = CreateDocumentFilePath([], "File1.cs"); var documentPath2 = CreateDocumentFilePath([], "File2.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" namespace [||]{{declaredNamespace}} @@ -2350,10 +2096,7 @@ Enum1 M1() } - """; - - var expectedSourceOriginal = - """ + """, """ enum Enum1 { A, @@ -2361,9 +2104,7 @@ enum Enum1 C } - """; - var expectedSourceReference = - """ + """, """ namespace Foo { class RefClass @@ -2374,8 +2115,7 @@ Enum1 M1() } } } - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37891")] @@ -2385,8 +2125,7 @@ public async Task ChangeNamespace_WithMemberAccessReferencesInVBDocument() var declaredNamespace = "A.B.C.D"; var documentPath1 = CreateDocumentFilePath([], "File1.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" @@ -2409,10 +2148,7 @@ End Sub End Class - """; - - var expectedSourceOriginal = - """ + """, """ namespace A.B.C { public enum Enum1 @@ -2422,16 +2158,13 @@ public enum Enum1 C } } - """; - var expectedSourceReference = - """ + """, """ Public Class VBClass Sub M() Dim x = A.B.C.Enum1.A End Sub End Class - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37891")] @@ -2441,8 +2174,7 @@ public async Task ChangeToGlobalNamespace_WithMemberAccessReferencesInVBDocument var declaredNamespace = "A.B.C.D"; var documentPath1 = CreateDocumentFilePath([], "File1.cs"); - var code = - $$""" + await TestChangeNamespaceAsync($$""" namespace [||]{{declaredNamespace}} @@ -2463,10 +2195,7 @@ End Sub End Class - """; - - var expectedSourceOriginal = - """ + """, """ public enum Enum1 { A, @@ -2474,16 +2203,13 @@ public enum Enum1 C } - """; - var expectedSourceReference = - """ + """, """ Public Class VBClass Sub M() Dim x = Enum1.A End Sub End Class - """; - await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); + """); } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1889796")] @@ -2494,9 +2220,7 @@ public async Task ChangeNamespace_DoesNotThrowInDuplicateProgramDeclaration() // No change namespace action because the folder name is not valid identifier var (topLevelProgramFolder, topLevelProgramFilePath) = CreateDocumentFilePath(["3B", "C"], "Program.cs"); var (duplicateProgramFolder, _) = CreateDocumentFilePath([], "Program.cs"); - - var code = -$$""" + await TestChangeNamespaceAsync($$""" @@ -2513,7 +2237,6 @@ private static void Main(string[] args) -"""; - await TestChangeNamespaceAsync(code, expectedSourceOriginal: null); +""", expectedSourceOriginal: null); } } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/SyncNamespace/SyncNamespaceTests_MoveFile.cs b/src/EditorFeatures/CSharpTest/CodeActions/SyncNamespace/SyncNamespaceTests_MoveFile.cs index db6c8231eb3ef..8c5b75939a58c 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/SyncNamespace/SyncNamespaceTests_MoveFile.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/SyncNamespace/SyncNamespaceTests_MoveFile.cs @@ -25,21 +25,20 @@ public async Task MoveFile_DeclarationNotContainedInDefaultNamespace() var expectedFolders = new List(); var (folder, filePath) = CreateDocumentFilePath([], "File1.cs"); - var code = -$@" - - - -namespace [||]{declaredNamespace} -{{ - class Class1 - {{ - }} -}} - - -"; - await TestMoveFileToMatchNamespace(code, expectedFolders); + await TestMoveFileToMatchNamespace($$""" + + + + namespace [||]{{declaredNamespace}} + { + class Class1 + { + } + } + + + + """, expectedFolders); } [Fact] @@ -52,20 +51,19 @@ public async Task MoveFile_DeclarationNotContainedInDefaultNamespace_FileScopedN var expectedFolders = new List(); var (folder, filePath) = CreateDocumentFilePath([], "File1.cs"); - var code = -$@" - - - -namespace [||]{declaredNamespace}; - -class Class1 -{{ -}} - - -"; - await TestMoveFileToMatchNamespace(code, expectedFolders); + await TestMoveFileToMatchNamespace($$""" + + + + namespace [||]{{declaredNamespace}}; + + class Class1 + { + } + + + + """, expectedFolders); } [Fact] @@ -83,21 +81,20 @@ public async Task MoveFile_SingleAction1() }; var (folder, filePath) = CreateDocumentFilePath([]); - var code = -$@" - - - -namespace [||]{declaredNamespace} -{{ - class Class1 - {{ - }} -}} - - -"; - await TestMoveFileToMatchNamespace(code, expectedFolders); + await TestMoveFileToMatchNamespace($$""" + + + + namespace [||]{{declaredNamespace}} + { + class Class1 + { + } + } + + + + """, expectedFolders); } [Fact] @@ -116,29 +113,28 @@ public async Task MoveFile_SingleAction2() var (folder, filePath) = CreateDocumentFilePath([], "File1.cs"); var documentPath2 = CreateDocumentFilePath(["B", "C"], "File2.cs"); // file2 is in \B\C\ - var code = -$@" - - - -namespace [||]{declaredNamespace} -{{ - class Class1 - {{ - }} -}} - - -namespace Foo -{{ - class Class2 - {{ - }} -}} - - -"; - await TestMoveFileToMatchNamespace(code, expectedFolders); + await TestMoveFileToMatchNamespace($$""" + + + + namespace [||]{{declaredNamespace}} + { + class Class1 + { + } + } + + + namespace Foo + { + class Class2 + { + } + } + + + + """, expectedFolders); } [Fact] @@ -155,22 +151,21 @@ public async Task MoveFile_MoveToRoot() }; var (folder, filePath) = CreateDocumentFilePath(["A", "B", "C"]); - var code = -$@" - - - -class [||]Class1 -{{ -}} - -class Class2 -{{ -}} - - -"; - await TestMoveFileToMatchNamespace(code, expectedFolders); + await TestMoveFileToMatchNamespace($$""" + + + + class [||]Class1 + { + } + + class Class2 + { + } + + + + """, expectedFolders); } [Fact] @@ -192,29 +187,28 @@ public async Task MoveFile_MultipleAction1() var (folder, filePath) = CreateDocumentFilePath([], "File1.cs"); var documentPath2 = CreateDocumentFilePath(["B.C"], "File2.cs"); // file2 is in \B.C\ - var code = -$@" - - - -namespace [||]{declaredNamespace} -{{ - class Class1 - {{ - }} -}} - - -namespace Foo -{{ - class Class2 - {{ - }} -}} - - -"; - await TestMoveFileToMatchNamespace(code, expectedFolders); + await TestMoveFileToMatchNamespace($$""" + + + + namespace [||]{{declaredNamespace}} + { + class Class1 + { + } + } + + + namespace Foo + { + class Class2 + { + } + } + + + + """, expectedFolders); } [Fact] @@ -239,37 +233,36 @@ public async Task MoveFile_MultipleAction2() var (folder, filePath) = CreateDocumentFilePath([], "File1.cs"); var documentPath2 = CreateDocumentFilePath(["B", "C.D"], "File2.cs"); // file2 is in \B\C.D\ var documentPath3 = CreateDocumentFilePath(["B.C"], "File3.cs"); // file3 is in \B.C\ - var code = -$@" - - - -namespace [||]{declaredNamespace} -{{ - class Class1 - {{ - }} -}} - - -namespace Foo -{{ - class Class2 - {{ - }} -}} - - -namespace Foo -{{ - class Class2 - {{ - }} -}} - - -"; - await TestMoveFileToMatchNamespace(code, expectedFolders); + await TestMoveFileToMatchNamespace($$""" + + + + namespace [||]{{declaredNamespace}} + { + class Class1 + { + } + } + + + namespace Foo + { + class Class2 + { + } + } + + + namespace Foo + { + class Class2 + { + } + } + + + + """, expectedFolders); } [Fact] @@ -286,30 +279,28 @@ public async Task MoveFile_FromOneFolderToAnother1() var (folder, filePath) = CreateDocumentFilePath(["B.C"], "File1.cs"); // file1 is in \B.C\ var documentPath2 = CreateDocumentFilePath(["B", "Foo"], "File2.cs"); // file2 is in \B\Foo\ - - var code = -$@" - - - -namespace [||]{declaredNamespace} -{{ - class Class1 - {{ - }} -}} - - -namespace Foo -{{ - class Class2 - {{ - }} -}} - - -"; - await TestMoveFileToMatchNamespace(code, expectedFolders); + await TestMoveFileToMatchNamespace($$""" + + + + namespace [||]{{declaredNamespace}} + { + class Class1 + { + } + } + + + namespace Foo + { + class Class2 + { + } + } + + + + """, expectedFolders); } [Fact] @@ -325,30 +316,28 @@ public async Task MoveFile_FromOneFolderToAnother2() var (folder, filePath) = CreateDocumentFilePath(["Foo.Bar", "Baz"], "File1.cs"); // file1 is in \Foo.Bar\Baz\ var documentPath2 = CreateDocumentFilePath(["B", "Foo"], "File2.cs"); // file2 is in \B\Foo\ - - var code = -$@" - - - -namespace [||]{declaredNamespace} -{{ - class Class1 - {{ - }} -}} - - -namespace Foo -{{ - class Class2 - {{ - }} -}} - - -"; - await TestMoveFileToMatchNamespace(code, expectedFolders); + await TestMoveFileToMatchNamespace($$""" + + + + namespace [||]{{declaredNamespace}} + { + class Class1 + { + } + } + + + namespace Foo + { + class Class2 + { + } + } + + + + """, expectedFolders); } [Fact] @@ -364,27 +353,25 @@ public async Task MoveFile_FromOneFolderToAnother2_FileScopedNamespace() var (folder, filePath) = CreateDocumentFilePath(["Foo.Bar", "Baz"], "File1.cs"); // file1 is in \Foo.Bar\Baz\ var documentPath2 = CreateDocumentFilePath(["B", "Foo"], "File2.cs"); // file2 is in \B\Foo\ - - var code = -$@" - - - -namespace [||]{declaredNamespace}; - -class Class1 -{{ -}} - - -namespace Foo; - -class Class2 -{{ -}} - - -"; - await TestMoveFileToMatchNamespace(code, expectedFolders); + await TestMoveFileToMatchNamespace($$""" + + + + namespace [||]{{declaredNamespace}}; + + class Class1 + { + } + + + namespace Foo; + + class Class2 + { + } + + + + """, expectedFolders); } } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/SyncNamespace/SyncNamespaceTests_NoAction.cs b/src/EditorFeatures/CSharpTest/CodeActions/SyncNamespace/SyncNamespaceTests_NoAction.cs index e14a979d00a11..fcfb0ef2c7a6f 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/SyncNamespace/SyncNamespaceTests_NoAction.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/SyncNamespace/SyncNamespaceTests_NoAction.cs @@ -20,45 +20,39 @@ public async Task NoAction_NotOnNamespaceDeclaration() { var folders = new[] { "A", "B" }; var (folder, filePath) = CreateDocumentFilePath(folders); - - var code = -$@" - - - -namespace NS -{{ - class [||]Class1 - {{ - }} -}} - - -"; - - await TestMissingInRegularAndScriptAsync(code); + await TestMissingInRegularAndScriptAsync($$""" + + + + namespace NS + { + class [||]Class1 + { + } + } + + + + """); } [Fact] public async Task NoAction_NotOnNamespaceDeclaration_FileScopedNamespace() { var folders = new[] { "A", "B" }; var (folder, filePath) = CreateDocumentFilePath(folders); - - var code = -$@" - - - -namespace NS; - -class [||]Class1 -{{ -}} - - -"; - - await TestMissingInRegularAndScriptAsync(code); + await TestMissingInRegularAndScriptAsync($$""" + + + + namespace NS; + + class [||]Class1 + { + } + + + + """); } [Fact] @@ -66,24 +60,21 @@ public async Task NoAction_NotOnFirstMemberInGlobal() { var folders = new[] { "A" }; var (folder, filePath) = CreateDocumentFilePath(folders); - - var code = -$@" - - - -class Class1 -{{ -}} - -class [||]Class2 -{{ -}} - - -"; - - await TestMissingInRegularAndScriptAsync(code); + await TestMissingInRegularAndScriptAsync($$""" + + + + class Class1 + { + } + + class [||]Class2 + { + } + + + + """); } [Fact] @@ -91,30 +82,27 @@ public async Task NoAction_MultipleNamespaceDeclarations() { var folders = new[] { "A", "B" }; var (folder, filePath) = CreateDocumentFilePath(folders); - - var code = -$@" - - - -namespace [||]NS1 -{{ - class Class1 - {{ - }} -}} - -namespace NS2 -{{ - class Class1 - {{ - }} -}} - - -"; - - await TestMissingInRegularAndScriptAsync(code); + await TestMissingInRegularAndScriptAsync($$""" + + + + namespace [||]NS1 + { + class Class1 + { + } + } + + namespace NS2 + { + class Class1 + { + } + } + + + + """); } [Fact] @@ -122,27 +110,24 @@ public async Task NoAction_MembersInBothGlobalAndNamespaceDeclaration_CursorOnNa { var folders = new[] { "A", "B" }; var (folder, filePath) = CreateDocumentFilePath(folders); - - var code = -$@" - - - -namespace [||]NS1 -{{ - class Class1 - {{ - }} -}} - -class Class2 -{{ -}} - - -"; - - await TestMissingInRegularAndScriptAsync(code); + await TestMissingInRegularAndScriptAsync($$""" + + + + namespace [||]NS1 + { + class Class1 + { + } + } + + class Class2 + { + } + + + + """); } [Fact] @@ -150,27 +135,24 @@ public async Task NoAction_MembersInBothGlobalAndNamespaceDeclaration_CursorOnFi { var folders = new[] { "A", "B" }; var (folder, filePath) = CreateDocumentFilePath(folders); - - var code = -$@" - - - -class [||]Class1 -{{ -}} - -namespace NS1 -{{ - class Class2 - {{ - }} -}} - - -"; - - await TestMissingInRegularAndScriptAsync(code); + await TestMissingInRegularAndScriptAsync($$""" + + + + class [||]Class1 + { + } + + namespace NS1 + { + class Class2 + { + } + } + + + + """); } [Fact] @@ -178,26 +160,23 @@ public async Task NoAction_NestedNamespaceDeclarations() { var folders = new[] { "A", "B" }; var (folder, filePath) = CreateDocumentFilePath(folders); - - var code = -$@" - - - -namespace [||]NS1 -{{ - namespace NS2 - {{ - class Class1 - {{ - }} - }} -}} - - -"; - - await TestMissingInRegularAndScriptAsync(code); + await TestMissingInRegularAndScriptAsync($$""" + + + + namespace [||]NS1 + { + namespace NS2 + { + class Class1 + { + } + } + } + + + + """); } [Fact] @@ -205,23 +184,20 @@ public async Task NoAction_InvalidNamespaceIdentifier() { var folders = new[] { "A", "B" }; var (folder, filePath) = CreateDocumentFilePath(folders); - - var code = -$@" - - - -namespace [||] -{{ - class Class1 - {{ - }} -}} - - -"; - - await TestMissingInRegularAndScriptAsync(code); + await TestMissingInRegularAndScriptAsync($$""" + + + + namespace [||] + { + class Class1 + { + } + } + + + + """); } [Fact] @@ -229,20 +205,17 @@ public async Task NoAction_MatchingNamespace_InGlobalNamespace() { var folders = Array.Empty(); var (folder, filePath) = CreateDocumentFilePath(folders); - - var code = -$@" - - - -class [||]Class1 -{{ -}} - - -"; - - await TestMissingInRegularAndScriptAsync(code); + await TestMissingInRegularAndScriptAsync($$""" + + + + class [||]Class1 + { + } + + + + """); } [Fact] @@ -250,23 +223,20 @@ public async Task NoAction_MatchingNamespace_DefaultGlobalNamespace() { var folders = new[] { "A", "B", "C" }; var (folder, filePath) = CreateDocumentFilePath(folders); - - var code = -$@" - - - -namespace [||]A.B.C -{{ - class Class1 - {{ - }} -}} - - -"; - - await TestMissingInRegularAndScriptAsync(code); + await TestMissingInRegularAndScriptAsync($$""" + + + + namespace [||]A.B.C + { + class Class1 + { + } + } + + + + """); } [Fact] @@ -274,46 +244,40 @@ public async Task NoAction_MatchingNamespace_InNamespaceDeclaration() { var folders = new[] { "B", "C" }; var (folder, filePath) = CreateDocumentFilePath(folders); - - var code = -$@" - - - -namespace [||]A.B.C -{{ - class Class1 - {{ - }} -}} - - -"; - - await TestMissingInRegularAndScriptAsync(code); + await TestMissingInRegularAndScriptAsync($$""" + + + + namespace [||]A.B.C + { + class Class1 + { + } + } + + + + """); } [Fact] public async Task NoAction_FileNotRooted() { var filePath = PathUtilities.CombineAbsoluteAndRelativePaths(PathUtilities.GetPathRoot(ProjectFilePath), "Foo.cs"); - - var code = -$@" - - - -namespace [||]NS -{{ - class Class1 - {{ - }} -}} - - -"; - - await TestMissingInRegularAndScriptAsync(code); + await TestMissingInRegularAndScriptAsync($$""" + + + + namespace [||]NS + { + class Class1 + { + } + } + + + + """); } [Fact] @@ -321,18 +285,15 @@ public async Task NoAction_NoDeclaration() { var folders = new[] { "A" }; var (folder, filePath) = CreateDocumentFilePath(folders); - - var code = -$@" - - - -using System; -[||] - - -"; - - await TestMissingInRegularAndScriptAsync(code); + await TestMissingInRegularAndScriptAsync($""" + + + + using System; + [||] + + + + """); } } diff --git a/src/EditorFeatures/CSharpTest/CodeLens/CSharpCodeLensTests.cs b/src/EditorFeatures/CSharpTest/CodeLens/CSharpCodeLensTests.cs index 696dae336ca8c..dca07b4e02152 100644 --- a/src/EditorFeatures/CSharpTest/CodeLens/CSharpCodeLensTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeLens/CSharpCodeLensTests.cs @@ -232,40 +232,39 @@ public class A [InlineData("class")] [InlineData("record class")] [InlineData("record struct")] - public async Task TestFullyQualifiedName(string typeKind) - { - var input = $@" - - - - -"; - await RunFullyQualifiedNameTest(input); - } + public Task TestFullyQualifiedName(string typeKind) + => RunFullyQualifiedNameTest($$""" + + + + + + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49636")] public async Task TestExplicitParameterlessConstructor() diff --git a/src/EditorFeatures/CSharpTest/CommentSelection/CSharpCommentSelectionTests.cs b/src/EditorFeatures/CSharpTest/CommentSelection/CSharpCommentSelectionTests.cs index 0e589495649c7..2e4973741f2e3 100644 --- a/src/EditorFeatures/CSharpTest/CommentSelection/CSharpCommentSelectionTests.cs +++ b/src/EditorFeatures/CSharpTest/CommentSelection/CSharpCommentSelectionTests.cs @@ -26,7 +26,7 @@ public sealed class CSharpCommentSelectionTests [WpfFact] public void UncommentAndFormat1() { - var code = """ + UncommentSelection(""" class A { [| // void Method ( ) @@ -34,8 +34,7 @@ class A // // }|] } - """; - var expected = """ + """, """ class A { void Method() @@ -43,14 +42,13 @@ void Method() } } - """; - UncommentSelection(code, expected); + """); } [WpfFact] public void UncommentAndFormat2() { - var code = """ + UncommentSelection(""" class A { [| /* void Method ( ) @@ -58,8 +56,7 @@ class A } */|] } - """; - var expected = """ + """, """ class A { void Method() @@ -67,14 +64,13 @@ void Method() } } - """; - UncommentSelection(code, expected); + """); } [WpfFact] public void UncommentSingleLineCommentInPseudoBlockComment() { - var code = """ + UncommentSelection(""" class C { /// @@ -84,9 +80,7 @@ protected void RtlTranslateAlignment2() } /* Hello world */ } - """; - - var expected = """ + """, """ class C { /// @@ -96,15 +90,13 @@ protected void RtlTranslateAlignment2() } /* Hello world */ } - """; - - UncommentSelection(code, expected); + """); } [WpfFact] public void UncommentAndFormat3() { - var code = """ + UncommentSelection(""" class A { [| // void Method ( ) |] @@ -112,8 +104,7 @@ class A [| // |] [| // } |] } - """; - var expected = """ + """, """ class A { void Method() @@ -121,8 +112,7 @@ void Method() } } - """; - UncommentSelection(code, expected); + """); } private static void UncommentSelection(string markup, string expected) diff --git a/src/EditorFeatures/CSharpTest/CommentSelection/CSharpToggleBlockCommentCommandHandlerTests.cs b/src/EditorFeatures/CSharpTest/CommentSelection/CSharpToggleBlockCommentCommandHandlerTests.cs index 81644333650fd..428a97e701893 100644 --- a/src/EditorFeatures/CSharpTest/CommentSelection/CSharpToggleBlockCommentCommandHandlerTests.cs +++ b/src/EditorFeatures/CSharpTest/CommentSelection/CSharpToggleBlockCommentCommandHandlerTests.cs @@ -23,8 +23,7 @@ public sealed class CSharpToggleBlockCommentCommandHandlerTests : AbstractToggle [WpfFact] public void AddComment_CommentMarkerStringBeforeSelection() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -34,9 +33,7 @@ void M() var k = 3;|] } } - """; - var expected = - """ + """, """ class C { void M() @@ -46,16 +43,13 @@ void M() var k = 3;*/|] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void AddComment_DirectiveWithCommentInsideSelection() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -67,9 +61,7 @@ void M() var k = 3;|] } } - """; - var expected = - """ + """, """ class C { void M() @@ -81,16 +73,13 @@ void M() var k = 3;*/|] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void AddComment_MarkerInsideSelection() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -100,9 +89,7 @@ void M() var k = 3;|] } } - """; - var expected = - """ + """, """ class C { void M() @@ -112,16 +99,13 @@ void M() var k = 3;*/|] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void AddComment_CloseCommentMarkerStringInSelection() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -131,9 +115,7 @@ void M() var k = 3;|] } } - """; - var expected = - """ + """, """ class C { void M() @@ -143,16 +125,13 @@ void M() var k = 3;*/|] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void AddComment_CommentMarkerStringAfterSelection() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -162,9 +141,7 @@ void M() string s = '*/'; } } - """; - var expected = - """ + """, """ class C { void M() @@ -174,16 +151,13 @@ void M() string s = '*/'; } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void RemoveComment_CommentMarkerStringNearSelection() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -194,9 +168,7 @@ void M() var k = 3;*/|] } } - """; - var expected = - """ + """, """ class C { void M() @@ -207,16 +179,13 @@ void M() var k = 3;|] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void RemoveComment_CommentMarkerStringInSelection() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -224,9 +193,7 @@ void M() [|/*string s = '/*';*/|] } } - """; - var expected = - """ + """, """ class C { void M() @@ -234,9 +201,7 @@ void M() [|string s = '/*';|] } } - """; - - ToggleComment(markup, expected); + """); } internal override AbstractCommentSelectionBase GetToggleCommentCommandHandler(EditorTestWorkspace workspace) diff --git a/src/EditorFeatures/CSharpTest/CommentSelection/CSharpToggleLineCommentCommandHandlerTests.cs b/src/EditorFeatures/CSharpTest/CommentSelection/CSharpToggleLineCommentCommandHandlerTests.cs index 230ed171e6a47..8612d90b926bf 100644 --- a/src/EditorFeatures/CSharpTest/CommentSelection/CSharpToggleLineCommentCommandHandlerTests.cs +++ b/src/EditorFeatures/CSharpTest/CommentSelection/CSharpToggleLineCommentCommandHandlerTests.cs @@ -22,26 +22,19 @@ public sealed class CSharpToggleLineCommentCommandHandlerTests : AbstractToggleC [WpfFact] public void AddComment_EmptyCaret() { - var markup = @"$$"; - var expected = @"[||]"; - - ToggleComment(markup, expected); + ToggleComment(@"$$", @"[||]"); } [WpfFact] public void AddComment_EmptySelection() { - var markup = @"[| |]"; - var expected = @"[||]"; - - ToggleComment(markup, expected); + ToggleComment(@"[| |]", @"[||]"); } [WpfFact] public void AddComment_CaretInUncommentedLine() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -49,9 +42,7 @@ void M() var$$ i = 1; } } - """; - var expected = - """ + """, """ class C { void M() @@ -59,16 +50,13 @@ void M() //var[||] i = 1; } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void AddComment_CaretBeforeUncommentedLine() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -76,9 +64,7 @@ void M() $$ var i = 1; } } - """; - var expected = - """ + """, """ class C { void M() @@ -86,16 +72,13 @@ void M() [||] //var i = 1; } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void AddComment_SingleLineSelected() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -103,9 +86,7 @@ void M() [|var i = 1;|] } } - """; - var expected = - """ + """, """ class C { void M() @@ -113,16 +94,13 @@ void M() [|//var i = 1;|] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void AddComment_PartialSingleLineSelected() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -130,9 +108,7 @@ void M() var [|i = 1;|] } } - """; - var expected = - """ + """, """ class C { void M() @@ -140,16 +116,13 @@ void M() //var [|i = 1;|] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void AddComment_SingleLineWithWhitespaceSelected() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -159,9 +132,7 @@ void M() |] } } - """; - var expected = - """ + """, """ class C { void M() @@ -171,16 +142,13 @@ void M() |] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void AddComment_SelectionInsideCommentAtEndOfLine() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -188,9 +156,7 @@ void M() var i = 1; // A [|comment|]. } } - """; - var expected = - """ + """, """ class C { void M() @@ -198,16 +164,13 @@ void M() //var i = 1; // A [|comment|]. } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void AddComment_SelectionAroundCommentAtEndOfLine() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -215,9 +178,7 @@ void M() var i = 1; [|// A comment.|] } } - """; - var expected = - """ + """, """ class C { void M() @@ -225,16 +186,13 @@ void M() //var i = 1; [|// A comment.|] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void AddComment_SelectionOutsideCommentAtEndOfLine() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -242,9 +200,7 @@ void M() [|var i = 1; // A comment.|] } } - """; - var expected = - """ + """, """ class C { void M() @@ -252,16 +208,13 @@ void M() [|//var i = 1; // A comment.|] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void AddComment_CaretOutsideCommentAtEndOfLine() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -269,9 +222,7 @@ void M() var $$i = 1; // A comment. } } - """; - var expected = - """ + """, """ class C { void M() @@ -279,16 +230,13 @@ void M() //var [||]i = 1; // A comment. } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void AddComment_CaretInsideCommentAtEndOfLine() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -296,9 +244,7 @@ void M() var i = 1; // A $$comment. } } - """; - var expected = - """ + """, """ class C { void M() @@ -306,16 +252,13 @@ void M() //var i = 1; // A [||]comment. } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void AddComment_CommentMarkerInString() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -323,9 +266,7 @@ void M() [|string s = '\\';|] } } - """; - var expected = - """ + """, """ class C { void M() @@ -333,16 +274,13 @@ void M() [|//string s = '\\';|] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void AddComment_MultipleLinesSelected() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -351,9 +289,7 @@ void M() var j = 2;|] } } - """; - var expected = - """ + """, """ class C { void M() @@ -362,16 +298,13 @@ void M() //var j = 2;|] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void AddComment_MultipleLinesWithWhitespaceSelected() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -383,9 +316,7 @@ void M() |] } } - """; - var expected = - """ + """, """ class C { void M() @@ -397,16 +328,13 @@ void M() |] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void AddComment_MultipleLinesPartiallyCommentedSelected() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -415,9 +343,7 @@ void M() var j = 2;|] } } - """; - var expected = - """ + """, """ class C { void M() @@ -426,16 +352,13 @@ void M() //var j = 2;|] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void AddComment_MultipleLinesWithCommentsInLineSelected() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -444,9 +367,7 @@ void M() var j = 2;|] } } - """; - var expected = - """ + """, """ class C { void M() @@ -455,16 +376,13 @@ void M() //var j = 2;|] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void AddComment_MultipleLinesWithDifferentIndentationsSelected() { - var markup = - """ + ToggleComment(""" class C { [| void M() @@ -474,9 +392,7 @@ class C var j = 2; }|] } - """; - var expected = - """ + """, """ class C { [| //void M() @@ -486,16 +402,13 @@ class C // var j = 2; //}|] } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void AddComment_MultiCaret() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -504,9 +417,7 @@ void M() var [||]j = 2; } } - """; - var expected = - """ + """, """ class C { void M() @@ -515,16 +426,13 @@ void M() //var [||]j = 2; } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void AddComment_MultiSeletion() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -533,9 +441,7 @@ void M() [|var j = 2;|] } } - """; - var expected = - """ + """, """ class C { void M() @@ -544,16 +450,13 @@ void M() [|//var j = 2;|] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void AddComment_MultiSeletionPartiallyCommented() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -562,9 +465,7 @@ void M() [|var j = 2;|] } } - """; - var expected = - """ + """, """ class C { void M() @@ -573,17 +474,13 @@ void M() [|//var j = 2;|] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void AddComment_WithProjectionBuffer() { - var surfaceMarkup = @"< html >@{|S1:|}"; - var csharpMarkup = - """ + ToggleCommentWithProjectionBuffer(@"< html >@{|S1:|}", """ {|S1:class C { void M() @@ -591,9 +488,7 @@ void M() [|var i = 1;|] } }|} - """; - var expected = - """ + """, """ < html >@class C { void M() @@ -601,16 +496,13 @@ void M() [|//var i = 1;|] } } - """; - - ToggleCommentWithProjectionBuffer(surfaceMarkup, csharpMarkup, expected); + """); } [WpfFact] public void RemoveComment_CaretInCommentedLine() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -618,9 +510,7 @@ void M() //var$$ i = 1; } } - """; - var expected = - """ + """, """ class C { void M() @@ -628,16 +518,13 @@ void M() var[||] i = 1; } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void RemoveComment_CaretBeforeCommentedLine() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -645,9 +532,7 @@ void M() $$ //var i = 1; } } - """; - var expected = - """ + """, """ class C { void M() @@ -655,16 +540,13 @@ void M() [||] var i = 1; } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void RemoveComment_CaretInCommentedLineWithEndComment() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -672,9 +554,7 @@ void M() //var i = 1; // A $$comment. } } - """; - var expected = - """ + """, """ class C { void M() @@ -682,16 +562,13 @@ void M() var i = 1; // A [||]comment. } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void RemoveComment_CaretInDoubleCommentedLine() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -699,9 +576,7 @@ void M() ////var$$ i = 1; } } - """; - var expected = - """ + """, """ class C { void M() @@ -709,16 +584,13 @@ void M() //var[||] i = 1; } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void RemoveComment_CommentedLineSelected() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -726,9 +598,7 @@ void M() [|//var i = 1;|] } } - """; - var expected = - """ + """, """ class C { void M() @@ -736,16 +606,13 @@ void M() [|var i = 1;|] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void RemoveComment_InsideCommentSelected() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -753,9 +620,7 @@ void M() //var [|i = 1;|] } } - """; - var expected = - """ + """, """ class C { void M() @@ -763,16 +628,13 @@ void M() var [|i = 1;|] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void RemoveComment_CommentedLineWithWhitespaceSelected() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -782,9 +644,7 @@ void M() |] } } - """; - var expected = - """ + """, """ class C { void M() @@ -794,16 +654,13 @@ void M() |] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void RemoveComment_CommentMarkerInString() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -811,9 +668,7 @@ void M() [|//string s = '\\';|] } } - """; - var expected = - """ + """, """ class C { void M() @@ -821,16 +676,13 @@ void M() [|string s = '\\';|] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void RemoveComment_MultipleCommentedLinesSelected() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -839,9 +691,7 @@ void M() //var j = 2;|] } } - """; - var expected = - """ + """, """ class C { void M() @@ -850,16 +700,13 @@ void M() var j = 2;|] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void RemoveComment_MultipleCommentedLinesAndWhitespaceSelected() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -871,9 +718,7 @@ void M() |] } } - """; - var expected = - """ + """, """ class C { void M() @@ -885,16 +730,13 @@ void M() |] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void RemoveComment_MultipleCommentedLinesWithEndCommentSelected() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -903,9 +745,7 @@ void M() //var j = 2;|] } } - """; - var expected = - """ + """, """ class C { void M() @@ -914,16 +754,13 @@ void M() var j = 2;|] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void RemoveComment_MultipleLinesWithDifferentIndentationsSelected() { - var markup = - """ + ToggleComment(""" class C { [| //void M() @@ -933,9 +770,7 @@ class C // var j = 2; //}|] } - """; - var expected = - """ + """, """ class C { [| void M() @@ -945,16 +780,13 @@ class C var j = 2; }|] } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void RemoveComment_MultiCaret() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -964,9 +796,7 @@ void M() //var [||]j = 2; } } - """; - var expected = - """ + """, """ class C { void M() @@ -976,16 +806,13 @@ void M() var [||]j = 2; } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void RemoveComment_MultiSeletion() { - var markup = - """ + ToggleComment(""" class C { void M() @@ -995,9 +822,7 @@ void M() [|//var j = 2;|] } } - """; - var expected = - """ + """, """ class C { void M() @@ -1007,17 +832,13 @@ void M() [|var j = 2;|] } } - """; - - ToggleComment(markup, expected); + """); } [WpfFact] public void RemoveComment_WithProjectionBuffer() { - var surfaceMarkup = @"< html >@{|S1:|}"; - var csharpMarkup = - """ + ToggleCommentWithProjectionBuffer(@"< html >@{|S1:|}", """ {|S1:class C { void M() @@ -1025,9 +846,7 @@ void M() [|//var i = 1;|] } }|} - """; - var expected = - """ + """, """ < html >@class C { void M() @@ -1035,26 +854,12 @@ void M() [|var i = 1;|] } } - """; - - ToggleCommentWithProjectionBuffer(surfaceMarkup, csharpMarkup, expected); + """); } [WpfFact] public void ToggleComment_MultipleLinesSelected() { - var markup = - """ - class C - { - void M() - { - [|//var i = 1; - - var j = 2;|] - } - } - """; var expected = new string[] { """ @@ -1081,24 +886,22 @@ void M() """ }; - ToggleCommentMultiple(markup, expected); - } - - [WpfFact] - public void ToggleComment_MultipleSelection() - { - var markup = - """ + ToggleCommentMultiple(""" class C { void M() { - [|//var i = |]1; - [||] - [|var j = 2;|] + [|//var i = 1; + + var j = 2;|] } } - """; + """, expected); + } + + [WpfFact] + public void ToggleComment_MultipleSelection() + { var expected = new string[] { """ @@ -1125,7 +928,17 @@ void M() """ }; - ToggleCommentMultiple(markup, expected); + ToggleCommentMultiple(""" + class C + { + void M() + { + [|//var i = |]1; + [||] + [|var j = 2;|] + } + } + """, expected); } internal override AbstractCommentSelectionBase GetToggleCommentCommandHandler(EditorTestWorkspace workspace) diff --git a/src/EditorFeatures/CSharpTest/CompleteStatement/CSharpCompleteStatementCommandHandlerTests.cs b/src/EditorFeatures/CSharpTest/CompleteStatement/CSharpCompleteStatementCommandHandlerTests.cs index 490b7f558e51f..4f5666a30a46a 100644 --- a/src/EditorFeatures/CSharpTest/CompleteStatement/CSharpCompleteStatementCommandHandlerTests.cs +++ b/src/EditorFeatures/CSharpTest/CompleteStatement/CSharpCompleteStatementCommandHandlerTests.cs @@ -67,41 +67,33 @@ internal static int MethodM(int a, int b) [InlineData("public interface C(int X, int Y$$)", "public interface C(int X, int Y)")] public void ParameterList_CouldBeHandled(string signature, string expectedSignature) { - var code = $$""" + VerifyTypingSemicolon($$""" public class Class1 { {{signature}} } - """; - - var expected = $$""" + """, $$""" public class Class1 { {{expectedSignature}};$$ } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ParameterList_InterfaceMethod() { - var code = """ + VerifyTypingSemicolon(""" public interface I { public void M(object o$$) } - """; - - var expected = """ + """, """ public interface I { public void M(object o);$$ } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfTheory] @@ -112,14 +104,12 @@ public interface I [InlineData("partial void Method($$object o) { }")] public void ParameterList_NotHandled(string signature) { - var code = $$""" + VerifyNoSpecialSemicolonHandling($$""" public class Class1 { {{signature}} } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } #endregion @@ -742,87 +732,66 @@ public void ArgumentList_Array_MissingInner() [WpfFact] public void FieldInitializer_NoParens() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { int i = 4$$ int j = 5; - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void FieldInitializer2() { - var code = - """ + VerifyTypingSemicolon(""" class C { int i = Min(2$$,3) int j = 5; - """; - - var expected = - """ + """, """ class C { int i = Min(2,3);$$ int j = 5; - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void FieldInitializer2b_MissingParen() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { int i = Min(2$$,3 int j = 5; - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void FieldInitializer3() { - var code = - """ + VerifyTypingSemicolon(""" class C { int i = Min(Max(4,5$$),3) int j = 5; - """; - - var expected = - """ + """, """ class C { int i = Min(Max(4,5),3);$$ int j = 5; - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void FieldInitializer3b_MissingInner() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { int i = Min(Max(4,5$$,3) int j = 5; - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } #endregion @@ -832,40 +801,33 @@ class C [WpfFact] public void ForLoopSingleInitializer1() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main() { for (int i = 0$$ ) int j; - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ForLoopSingleInitializer2() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main() { for (int i = 0$$ i < 5; i++) int j; - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ForLoopSingleInitializer3() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main() @@ -877,224 +839,182 @@ static void Main() System.Console.Write("{0}", x); } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ForLoopSingleInitializer_MissingParen() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main() { for (int i = 0$$ int j; - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ForLoopNoStatements() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main() { for ($$ int j; - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ForLoopNoStatements2() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main() { for ( $$ int j; - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ForLoopNoStatements3() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main() { for ( ; $$ int j; - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ForLoopNoStatements4() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main() { for ( ; ;$$ int j; - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ForLoopNoStatements5() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main() { for ( $$ ;) int j; - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ForLoopMultistatementInitializer1() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main() { for ( $$int i = 0, int j = 0) int j; - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ForLoopMultistatementInitializer2() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main() { for ( int$$ i = 0, int j = 0) int j; - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ForLoopMultistatementInitializer3() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main() { for ( int i$$ = 0, int j = 0) int j; - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ForLoopMultistatementInitializer4() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main() { for ( int i = 0, $$int j = 0) int j; - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ForLoopMultistatementInitializer5() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main() { for ( int i = 0, int j =$$ 0) int j; - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ForLoopMultistatementInitializer6() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main() { for ( int i = 0, int j = 0$$) int j; - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ForLoopMultistatementInitializer7() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main() { for ( int i = 0, int j = 0$$) int j; - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ForLoopNewInInitializer1() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) @@ -1110,10 +1030,7 @@ public class C1 return obj; } } - """; - - var expected = - """ + """, """ class C { static void Main(string[] args) @@ -1129,16 +1046,13 @@ public class C1 return obj; } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ForLoopNewInInitializer_MissingOneParen() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main(string[] args) @@ -1154,17 +1068,15 @@ public class C1 return obj; } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ForLoopNewInInitializer2_MissingBothParens() { // only adding one closing paren - var code = - """ + + VerifyNoSpecialSemicolonHandling(""" class C { static void Main(string[] args) @@ -1180,146 +1092,113 @@ public class C1 return obj; } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ForLoopDeclaration() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) { string s = "abcdefghij"; for (int i = s.IndexOf("bcd"$$) i < 10; i++) - """; - - var expected = - """ + """, """ class C { static void Main(string[] args) { string s = "abcdefghij"; for (int i = s.IndexOf("bcd");$$ i < 10; i++) - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ForLoopDeclaration2() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) { string s = "abcdefghij"; for (int i = s.IndexOf("bcd"$$), j=1 i < 10; i++) - """; - - var expected = - """ + """, """ class C { static void Main(string[] args) { string s = "abcdefghij"; for (int i = s.IndexOf("bcd"), j=1;$$ i < 10; i++) - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ForLoopDeclaration3() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) { string s = "abcdefghij"; for (int i = s.IndexOf("bcd"$$); i < 10; i++) - """; - - var expected = - """ + """, """ class C { static void Main(string[] args) { string s = "abcdefghij"; for (int i = s.IndexOf("bcd");$$ i < 10; i++) - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ForLoopDeclaration4() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) { string s = "abcdefghij"; for (int i = s.IndexOf("bcd"$$), j=1; i < 10; i++) - """; - - var expected = - """ + """, """ class C { static void Main(string[] args) { string s = "abcdefghij"; for (int i = s.IndexOf("bcd"), j=1;$$ i < 10; i++) - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ForLoopDeclaration_MissingParen() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) { string s = "abcdefghij"; for (int i = s.IndexOf("bcd"$$ i < 10; i++) - """; - - var expected = - """ + """, """ class C { static void Main(string[] args) { string s = "abcdefghij"; for (int i = s.IndexOf("bcd";$$ i < 10; i++) - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/32250")] public void ForLoopInitializers() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) @@ -1327,10 +1206,7 @@ static void Main(string[] args) string s = "abcdefghij"; int i; for (i = s.IndexOf("bcd"$$) i < 10; i++) - """; - - var expected = - """ + """, """ class C { static void Main(string[] args) @@ -1338,16 +1214,13 @@ static void Main(string[] args) string s = "abcdefghij"; int i; for (i = s.IndexOf("bcd");$$ i < 10; i++) - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/32250")] public void ForLoopInitializers2() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) @@ -1356,10 +1229,7 @@ static void Main(string[] args) int i; int j; for (i = s.IndexOf("bcd"$$), j=1 i < 10; i++) - """; - - var expected = - """ + """, """ class C { static void Main(string[] args) @@ -1368,16 +1238,13 @@ static void Main(string[] args) int i; int j; for (i = s.IndexOf("bcd"), j=1;$$ i < 10; i++) - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ForLoopInitializers3() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) @@ -1385,10 +1252,7 @@ static void Main(string[] args) string s = "abcdefghij"; int i; for (i = s.IndexOf("bcd"$$); i < 10; i++) - """; - - var expected = - """ + """, """ class C { static void Main(string[] args) @@ -1396,16 +1260,13 @@ static void Main(string[] args) string s = "abcdefghij"; int i; for (i = s.IndexOf("bcd");$$ i < 10; i++) - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ForLoopInitializers4() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) @@ -1414,10 +1275,7 @@ static void Main(string[] args) int i; int j; for (i = s.IndexOf("bcd"$$), j=1; i < 10; i++) - """; - - var expected = - """ + """, """ class C { static void Main(string[] args) @@ -1426,15 +1284,12 @@ static void Main(string[] args) int i; int j; for (i = s.IndexOf("bcd"), j=1;$$ i < 10; i++) - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ForLoopInitializers_MissingParen() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) @@ -1442,10 +1297,7 @@ static void Main(string[] args) string s = "abcdefghij"; int i; for (i = s.IndexOf("bcd"$$ i < 10; i++) - """; - - var expected = - """ + """, """ class C { static void Main(string[] args) @@ -1453,42 +1305,33 @@ static void Main(string[] args) string s = "abcdefghij"; int i; for (i = s.IndexOf("bcd";$$ i < 10; i++) - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ForLoopCondition() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) { string s = "abcdefghij"; for (int i = s.IndexOf("bcd"); i < s.IndexOf("x"$$) i++) - """; - - var expected = - """ + """, """ class C { static void Main(string[] args) { string s = "abcdefghij"; for (int i = s.IndexOf("bcd"); i < s.IndexOf("x");$$ i++) - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ForLoopConditionIsNull() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main(string[] args) @@ -1497,16 +1340,13 @@ static void Main(string[] args) { Console.WriteLine("test"); } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ForLoopConditionIsNull2() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) @@ -1515,9 +1355,7 @@ static void Main(string[] args) { Console.WriteLine("test"); } - """; - var expected = - """ + """, """ class C { static void Main(string[] args) @@ -1526,41 +1364,33 @@ static void Main(string[] args) { Console.WriteLine("test"); } - """; - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ForLoopIncrement() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) { string s = "abcdefghij"; for (int i = s.IndexOf("bcd"); i < s.IndexOf("x"); i = i.IndexOf("x"$$)) - """; - - var expected = - """ + """, """ class C { static void Main(string[] args) { string s = "abcdefghij"; for (int i = s.IndexOf("bcd"); i < s.IndexOf("x"); i = i.IndexOf("x";$$)) - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ForLoopBody() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) @@ -1570,10 +1400,7 @@ static void Main(string[] args) { i.ToString($$) } - """; - - var expected = - """ + """, """ class C { static void Main(string[] args) @@ -1583,16 +1410,13 @@ static void Main(string[] args) { i.ToString();$$ } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ForLoopObjectInitializer_MissingParen() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main(string[] args) @@ -1605,16 +1429,13 @@ public class Goo public int i; public string s; } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ForLoopObjectInitializer() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) @@ -1627,9 +1448,7 @@ public class Goo public int i; public string s; } - """; - var expected = - """ + """, """ class C { static void Main(string[] args) @@ -1642,16 +1461,13 @@ public class Goo public int i; public string s; } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ForLoopObjectInitializer_MissingBrace() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main(string[] args) @@ -1664,9 +1480,7 @@ public class Goo public int i; public string s; } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } #endregion @@ -1676,8 +1490,7 @@ public class Goo [WpfFact] public void Indexer() { - var code = - """ + VerifyTypingSemicolon(""" class SampleCollection { private T[] arr = new T[100]; @@ -1688,9 +1501,7 @@ public int Property set { arr[i] = value; } } } - """; - var expected = - """ + """, """ class SampleCollection { private T[] arr = new T[100]; @@ -1701,16 +1512,13 @@ public int Property set { arr[i] = value; } } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void Indexer2() { - var code = - """ + VerifyTypingSemicolon(""" class test { int[] array = { 1, 2, 3 }; @@ -1720,9 +1528,7 @@ void M() var i = array[1$$] } } - """; - var expected = - """ + """, """ class test { int[] array = { 1, 2, 3 }; @@ -1732,16 +1538,13 @@ void M() var i = array[1];$$ } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void Indexer3() { - var code = - """ + VerifyTypingSemicolon(""" class C { int[] array = { 1, 2, 3 }; @@ -1751,9 +1554,7 @@ void M() var i = array[Math.Min(2,3$$)] } } - """; - var expected = - """ + """, """ class C { int[] array = { 1, 2, 3 }; @@ -1763,16 +1564,13 @@ void M() var i = array[Math.Min(2,3)];$$ } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void Indexer4() { - var code = - """ + VerifyTypingSemicolon(""" class C { int[] array = { 1, 2, 3 }; @@ -1782,9 +1580,7 @@ void M() var i = array[Math.Min(2,3$$) } } - """; - var expected = - """ + """, """ class C { int[] array = { 1, 2, 3 }; @@ -1794,9 +1590,7 @@ void M() var i = array[Math.Min(2,3;$$) } } - """; - - VerifyTypingSemicolon(code, expected); + """); } #endregion @@ -1806,8 +1600,7 @@ void M() [WpfFact] public void ArrayInitializer() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main(string[] args) @@ -1816,16 +1609,13 @@ static void Main(string[] args) } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ArrayInitializer2() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) @@ -1834,9 +1624,7 @@ static void Main(string[] args) } } - """; - var expected = - """ + """, """ class C { static void Main(string[] args) @@ -1845,16 +1633,13 @@ static void Main(string[] args) } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ArrayInitializer3() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) @@ -1863,9 +1648,7 @@ static void Main(string[] args) } } - """; - var expected = - """ + """, """ class C { static void Main(string[] args) @@ -1874,16 +1657,13 @@ static void Main(string[] args) } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ArrayInitializer4() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) @@ -1892,9 +1672,7 @@ static void Main(string[] args) } } - """; - var expected = - """ + """, """ class C { static void Main(string[] args) @@ -1903,16 +1681,13 @@ static void Main(string[] args) } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ArrayInitializer_MissingBrace() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main(string[] args) @@ -1921,9 +1696,7 @@ static void Main(string[] args) } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } #endregion @@ -1933,8 +1706,7 @@ static void Main(string[] args) [WpfFact] public void ImplicitTypeArrayInitializer() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main(string[] args) @@ -1943,16 +1715,13 @@ static void Main(string[] args) } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ImplicitTypeArrayInitializer2() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) @@ -1961,9 +1730,7 @@ static void Main(string[] args) } } - """; - var expected = - """ + """, """ class C { static void Main(string[] args) @@ -1972,16 +1739,13 @@ static void Main(string[] args) } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ImplicitTypeArrayInitializer3() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) @@ -1990,9 +1754,7 @@ static void Main(string[] args) } } - """; - var expected = - """ + """, """ class C { static void Main(string[] args) @@ -2001,16 +1763,13 @@ static void Main(string[] args) } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ImplicitTypeArrayInitializer4() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) @@ -2019,9 +1778,7 @@ static void Main(string[] args) } } - """; - var expected = - """ + """, """ class C { static void Main(string[] args) @@ -2030,16 +1787,13 @@ static void Main(string[] args) } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ImplicitTypeArrayInitializer_MissingBrace() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main(string[] args) @@ -2048,9 +1802,7 @@ static void Main(string[] args) } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } #endregion @@ -2060,8 +1812,7 @@ static void Main(string[] args) [WpfFact] public void CollectionExpression() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main(string[] args) @@ -2070,16 +1821,13 @@ static void Main(string[] args) } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void CollectionExpression2() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) @@ -2088,9 +1836,7 @@ static void Main(string[] args) } } - """; - var expected = - """ + """, """ class C { static void Main(string[] args) @@ -2099,16 +1845,13 @@ static void Main(string[] args) } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void CollectionExpression3() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) @@ -2117,9 +1860,7 @@ static void Main(string[] args) } } - """; - var expected = - """ + """, """ class C { static void Main(string[] args) @@ -2128,16 +1869,13 @@ static void Main(string[] args) } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void CollectionExpression4() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) @@ -2146,9 +1884,7 @@ static void Main(string[] args) } } - """; - var expected = - """ + """, """ class C { static void Main(string[] args) @@ -2157,16 +1893,13 @@ static void Main(string[] args) } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void CollectionExpression_MissingBrace() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main(string[] args) @@ -2175,9 +1908,7 @@ static void Main(string[] args) } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } #endregion @@ -2187,8 +1918,7 @@ static void Main(string[] args) [WpfFact] public void CollectionInitializer() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" using System.Collections.Generic; class C { @@ -2198,16 +1928,13 @@ static void Main(string[] args) } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void CollectionInitializer2() { - var code = - """ + VerifyTypingSemicolon(""" using System.Collections.Generic; class C { @@ -2217,9 +1944,7 @@ static void Main(string[] args) } } - """; - var expected = - """ + """, """ using System.Collections.Generic; class C { @@ -2229,16 +1954,13 @@ static void Main(string[] args) } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void CollectionInitializer3() { - var code = - """ + VerifyTypingSemicolon(""" using System.Collections.Generic; class C { @@ -2248,9 +1970,7 @@ static void Main(string[] args) } } - """; - var expected = - """ + """, """ using System.Collections.Generic; class C { @@ -2260,16 +1980,13 @@ static void Main(string[] args) } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void CollectionInitializer4() { - var code = - """ + VerifyTypingSemicolon(""" using System.Collections.Generic; class C { @@ -2279,9 +1996,7 @@ static void Main(string[] args) } } - """; - var expected = - """ + """, """ using System.Collections.Generic; class C { @@ -2291,16 +2006,13 @@ static void Main(string[] args) } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void CollectionInitializer_MissingBrace() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" using System.Collections.Generic; class C { @@ -2310,9 +2022,7 @@ static void Main(string[] args) } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } #endregion @@ -2322,8 +2032,7 @@ static void Main(string[] args) [WpfFact] public void ObjectInitializer() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { static void Main(string[] args) @@ -2337,16 +2046,13 @@ public class Goo public int i; public string s; } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ObjectInitializer2() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) @@ -2360,9 +2066,7 @@ public class Goo public int i; public string s; } - """; - var expected = - """ + """, """ class C { static void Main(string[] args) @@ -2376,16 +2080,13 @@ public class Goo public int i; public string s; } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ObjectInitializer3() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) @@ -2399,9 +2100,7 @@ public class Goo public int i; public string s; } - """; - var expected = - """ + """, """ class C { static void Main(string[] args) @@ -2415,16 +2114,13 @@ public class Goo public int i; public string s; } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ObjectInitializer4() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) @@ -2438,9 +2134,7 @@ public class Goo public int i; public string s; } - """; - var expected = - """ + """, """ class C { static void Main(string[] args) @@ -2454,16 +2148,13 @@ public class Goo public int i; public string s; } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ObjectInitializer_MissingBrace() { - var code = - """ + VerifyTypingSemicolon(""" class C { static void Main(string[] args) @@ -2477,9 +2168,7 @@ public class Goo public int i; public string s; } - """; - var expected = - """ + """, """ class C { static void Main(string[] args) @@ -2493,9 +2182,7 @@ public class Goo public int i; public string s; } - """; - - VerifyTypingSemicolon(code, expected); + """); } #endregion @@ -2505,7 +2192,7 @@ public class Goo [WpfFact] public void PropertyAccessors1() { - var code = """ + VerifyTypingSemicolon(""" public class ClassC { private int xValue = 7; @@ -2517,9 +2204,7 @@ public int XValue } } } - """; - - var expected = """ + """, """ public class ClassC { private int xValue = 7; @@ -2531,15 +2216,13 @@ public int XValue } } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void PropertyAccessors2() { - var code = """ + VerifyTypingSemicolon(""" public class ClassC { private int xValue = 7; @@ -2551,9 +2234,7 @@ public int XValue } } } - """; - - var expected = """ + """, """ public class ClassC { private int xValue = 7; @@ -2565,15 +2246,13 @@ public int XValue } } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void PropertyAccessors3() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" public class Person { private string firstName; @@ -2587,15 +2266,13 @@ public Person(string first, string last) public string Name => $"{firstName} {lastName}"$$ } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void PropertyAccessors4() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" public class SaleItem { string name; @@ -2605,15 +2282,13 @@ public string Name set => name = value$$ } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void PropertyAccessors5() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" public class SaleItem { string name; @@ -2623,15 +2298,13 @@ public string Name set => name = value; } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void PropertyAccessors6() { - var code = """ + VerifyTypingSemicolon(""" public class SaleItem { string name; @@ -2641,8 +2314,7 @@ public string Name set => name = value; } } - """; - var expected = """ + """, """ public class SaleItem { string name; @@ -2652,49 +2324,41 @@ public string Name set => name = value; } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void PropertyAccessors7() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" public class SaleItem { public string Name { get$$ set; } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void PropertyInitializer1() { - var code = """ + VerifyTypingSemicolon(""" public class C { public static C MyProp { get; } = new C($$) } - """; - - var expected = """ + """, """ public class C { public static C MyProp { get; } = new C();$$ } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void PropertyAttribute1() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" public class C { public int P @@ -2706,9 +2370,7 @@ public int P } } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } #endregion @@ -2718,7 +2380,7 @@ public int P [WpfFact] public void ParenthesizedExpression_Assignment1() { - var code = """ + VerifyTypingSemicolon(""" public class Class1 { void M() @@ -2726,9 +2388,7 @@ void M() int i = (6*5$$) } } - """; - - var expected = """ + """, """ public class Class1 { void M() @@ -2736,15 +2396,13 @@ void M() int i = (6*5);$$ } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ParenthesizedExpression_Assignment2() { - var code = """ + VerifyTypingSemicolon(""" public class Class1 { void M() @@ -2752,9 +2410,7 @@ void M() int i = (6*Math.Min(4,5$$)) } } - """; - - var expected = """ + """, """ public class Class1 { void M() @@ -2762,15 +2418,13 @@ void M() int i = (6*Math.Min(4,5));$$ } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ParenthesizedExpression_Assignment3() { - var code = """ + VerifyTypingSemicolon(""" public class Class1 { void M() @@ -2779,9 +2433,7 @@ void M() int i = (6*array[2$$]) } } - """; - - var expected = """ + """, """ public class Class1 { void M() @@ -2790,15 +2442,13 @@ void M() int i = (6*array[2]);$$ } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ParenthesizedExpression_ForLoop() { - var code = """ + VerifyTypingSemicolon(""" public class Class1 { void M() @@ -2809,9 +2459,7 @@ void M() } } } - """; - - var expected = """ + """, """ public class Class1 { void M() @@ -2822,15 +2470,13 @@ void M() } } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ParenthesizedExpression_ForLoop2() { - var code = """ + VerifyTypingSemicolon(""" public class Class1 { void M() @@ -2841,9 +2487,7 @@ void M() } } } - """; - - var expected = """ + """, """ public class Class1 { void M() @@ -2854,15 +2498,13 @@ void M() } } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ParenthesizedExpression_ForLoop3() { - var code = """ + VerifyTypingSemicolon(""" public class Class1 { void M() @@ -2873,9 +2515,7 @@ void M() } } } - """; - - var expected = """ + """, """ public class Class1 { void M() @@ -2886,15 +2526,13 @@ void M() } } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ParenthesizedExpression_ForEach() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" public class Class1 { static void Main(string[] args) @@ -2911,15 +2549,13 @@ private static int[] M(int i) return value; } } - """; - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ParenthesizedExpression_GoTo2() { - var code = - """ + VerifyTypingSemicolon(""" static void Main() { int n = 1; @@ -2933,10 +2569,7 @@ static void Main() break; } } - """; - - var expected = - """ + """, """ static void Main() { int n = 1; @@ -2950,15 +2583,13 @@ static void Main() break; } } - """; - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ParenthesizedExpression_Switch() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class Program { static void Main() @@ -2973,16 +2604,13 @@ static void Main() } } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ParenthesizedExpression_Switch2() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class Program { static void Main() @@ -2997,16 +2625,13 @@ static void Main() } } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ParenthesizedExpression_Switch3() { - var code = - """ + VerifyTypingSemicolon(""" class Program { static void Main() @@ -3022,9 +2647,7 @@ static void Main() } } } - """; - var expected = - """ + """, """ class Program { static void Main() @@ -3040,16 +2663,13 @@ static void Main() } } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void ParenthesizedExpression_While() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" using System; class Program { @@ -3062,16 +2682,13 @@ static void Main() } } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ParenthesizedExpression_While2() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" using System; class Program { @@ -3084,16 +2701,13 @@ static void Main() } } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ParenthesizedExpression_While3() { - var code = - """ + VerifyTypingSemicolon(""" using System; class Program { @@ -3106,9 +2720,7 @@ static void Main() } } } - """; - var expected = - """ + """, """ using System; class Program { @@ -3121,9 +2733,7 @@ static void Main() } } } - """; - - VerifyTypingSemicolon(code, expected); + """); } #endregion @@ -3133,7 +2743,7 @@ static void Main() [InlineData("default($$object)", "default(object)")] public void DefaultExpression_Handled(string expression, string expectedExpression) { - var code = $$""" + VerifyTypingSemicolon($$""" public class Class1 { void M() @@ -3141,9 +2751,7 @@ void M() int i = {{expression}} } } - """; - - var expected = $$""" + """, $$""" public class Class1 { void M() @@ -3151,9 +2759,7 @@ void M() int i = {{expectedExpression}};$$ } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/52137")] @@ -3161,7 +2767,7 @@ void M() [InlineData("typeof($$object)", "typeof(object)")] public void TypeOfExpression_Handled(string expression, string expectedExpression) { - var code = $$""" + VerifyTypingSemicolon($$""" public class Class1 { void M() @@ -3169,9 +2775,7 @@ void M() var x = {{expression}} } } - """; - - var expected = $$""" + """, $$""" public class Class1 { void M() @@ -3179,15 +2783,13 @@ void M() var x = {{expectedExpression}};$$ } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/52365")] public void TupleExpression_Handled() { - var code = """ + VerifyTypingSemicolon(""" public class Class1 { void M() @@ -3195,9 +2797,7 @@ void M() var x = (0, 0$$) } } - """; - - var expected = """ + """, """ public class Class1 { void M() @@ -3205,9 +2805,7 @@ void M() var x = (0, 0);$$ } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfTheory] @@ -3217,7 +2815,7 @@ void M() [InlineData("default($$object")] public void DefaultExpression_NotHandled(string expression) { - var code = $$""" + VerifyNoSpecialSemicolonHandling($$""" public class Class1 { void M() @@ -3225,9 +2823,7 @@ void M() int i = {{expression}} } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfTheory] @@ -3237,7 +2833,7 @@ void M() [InlineData("unchecked($$3 + 3)", "unchecked(3 + 3)")] public void CheckedExpression_Handled(string expression, string expectedExpression) { - var code = $$""" + VerifyTypingSemicolon($$""" public class Class1 { void M() @@ -3245,9 +2841,7 @@ void M() int i = {{expression}} } } - """; - - var expected = $$""" + """, $$""" public class Class1 { void M() @@ -3255,9 +2849,7 @@ void M() int i = {{expectedExpression}};$$ } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfTheory] @@ -3271,7 +2863,7 @@ void M() [InlineData("unchecked($$3 + 3")] public void CheckedExpression_NotHandled(string expression) { - var code = $$""" + VerifyNoSpecialSemicolonHandling($$""" public class Class1 { void M() @@ -3279,15 +2871,13 @@ void M() int i = {{expression}} } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ThrowStatement_MissingBoth() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" public class Class1 { void M() @@ -3297,15 +2887,13 @@ void M() } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void ThrowStatement() { - var code = """ + VerifyTypingSemicolon(""" public class Class1 { void M() @@ -3315,9 +2903,7 @@ void M() } } - """; - - var expected = """ + """, """ public class Class1 { void M() @@ -3327,44 +2913,35 @@ void M() } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void DoNotComplete_SemicolonBeforeClassDeclaration() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" $$ class C { } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoNotCompleteStatment_DocComments() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" /// Testing $$ class C { } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoNotComplete_FormatString() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { void Main() @@ -3372,16 +2949,13 @@ void Main() Console.WriteLine(String.Format("{0:##;(##)$$**Zero**}", 0)); } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoNotComplete_EmptyStatement() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { void Main() @@ -3389,16 +2963,13 @@ void Main() ;$$ } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoNotComplete_EmptyStatement2() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class C { void Main() @@ -3406,16 +2977,13 @@ void Main() ; $$ } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoWhile() { - var code = - """ + VerifyTypingSemicolon(""" public class C { void M() @@ -3428,9 +2996,7 @@ void M() } while (n$$ < 5) } } - """; - var expected = - """ + """, """ public class C { void M() @@ -3443,15 +3009,13 @@ void M() } while (n < 5);$$ } } - """; - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void DoWhile2() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" public class C { void M() @@ -3464,16 +3028,13 @@ void M() } while (n < 5)$$ } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoWhile3() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" public class C { void M() @@ -3486,16 +3047,13 @@ void M() } while $$(n < 5) } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoWhile4() { - var code = - """ + VerifyTypingSemicolon(""" public class C { void M() @@ -3508,10 +3066,7 @@ void M() } while (n < Min(4,$$5)) } } - """; - - var expected = - """ + """, """ public class C { void M() @@ -3524,16 +3079,13 @@ void M() } while (n < Min(4,5));$$ } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/35260")] public void DoWhile5() { - var code = - """ + VerifyTypingSemicolon(""" public class C { void M() @@ -3546,10 +3098,7 @@ void M() } while ($$n < Min(4,5)) } } - """; - - var expected = - """ + """, """ public class C { void M() @@ -3562,16 +3111,13 @@ void M() } while (n < Min(4,5));$$ } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/35260")] public void DoWhile6() { - var code = - """ + VerifyTypingSemicolon(""" public class C { void M() @@ -3584,10 +3130,7 @@ void M() } while (n < Min(4,5)$$) } } - """; - - var expected = - """ + """, """ public class C { void M() @@ -3600,16 +3143,13 @@ void M() } while (n < Min(4,5));$$ } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void DoWhile_MissingParen() { - var code = - """ + VerifyTypingSemicolon(""" public class C { void M() @@ -3622,10 +3162,7 @@ void M() } while (n < Min(4,$$5) } } - """; - - var expected = - """ + """, """ public class C { void M() @@ -3638,16 +3175,13 @@ void M() } while (n < Min(4,;$$5) } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void DoNotComplete_Break() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" public class C { void M() @@ -3661,16 +3195,13 @@ void M() } while (n < 5); } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoNotComplete_Break2() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" public class C { void M() @@ -3684,16 +3215,13 @@ void M() } while (n < 5); } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoNotComplete_Break3() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" public class C { void M() @@ -3707,16 +3235,13 @@ void M() } while (n < 5); } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoNotComplete_Checked() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class Program { static void Main(string[] args) @@ -3739,16 +3264,13 @@ static void Main(string[] args) Console.ReadLine(); } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoNotComplete_Unchecked() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class Program { static void Main(string[] args) @@ -3771,16 +3293,13 @@ static void Main(string[] args) Console.ReadLine(); } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoNotComplete_Fixed() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class Program { static void Main() @@ -3800,17 +3319,14 @@ unsafe static string Transform() return new string(pointer); } } - } - """; - - VerifyNoSpecialSemicolonHandling(code); + } + """); } [WpfFact] public void DoNotComplete_Continue() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class ContinueTest { static void Main() @@ -3825,16 +3341,13 @@ static void Main() } } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoNotComplete_Continue2() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class ContinueTest { static void Main() @@ -3849,16 +3362,13 @@ static void Main() } } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoNotComplete_Continue3() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class ContinueTest { static void Main() @@ -3873,16 +3383,13 @@ static void Main() } } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoNotComplete_GoTo() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" static void Main() { int n = 1; @@ -3897,16 +3404,13 @@ static void Main() break; } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoNotComplete_IfStatement() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class Program { void M() @@ -3918,16 +3422,13 @@ void M() } } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoNotComplete_Labeled() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class Program { static void Main() @@ -3937,16 +3438,13 @@ static void Main() labeled$$: return; } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoNotComplete_IfStatement2() { - var code = - """ + VerifyNoSpecialSemicolonHandling(""" class Program { void M() @@ -3958,9 +3456,7 @@ void M() } } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] @@ -4136,22 +3632,19 @@ public void DoNotComplete_UnterminatedCharLiteral(string literal) [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34176")] public void DoNotComplete_VerbatimStringAsMethodArgument_EndOfLine_NotEndOfString() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" var code = Foo(@"$$ ") ; - """; - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34176")] public void DoNotComplete_VerbatimStringAsMethodArgument_EndOfString_NotEndOfLine() { - - var code = """ + VerifyNoSpecialSemicolonHandling(""" var code = Foo(@" $$" //comments ); - """; - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] @@ -4167,7 +3660,7 @@ public void DoNotComplete_InterpolatedString() [WpfFact] public void DoNotComplete_Attribute() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" using System; class Program @@ -4183,26 +3676,24 @@ static void Test() { } } - """; - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoNotComplete_Attribute2() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" [assembly: System.Reflection.AssemblyVersionAttribute(null$$)] class Program { } - """; - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoNotComplete_Attribute3() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" using System.Runtime.CompilerServices; using System; @@ -4220,14 +3711,13 @@ class A public void MyMethod() { } } - """; - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoNotComplete_Attribute4() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" using System; using System.Reflection; @@ -4249,14 +3739,13 @@ public static void Main() Console.Write($"B.Length={attr.B.Length}, B[0]={attr.B[0]}, B[1]={attr.B[1]}"); } } - """; - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoNotComplete_Attribute5() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" using System; using System.Reflection; @@ -4278,14 +3767,13 @@ public static void Main() Console.Write($"B.Length={attr.B.Length}, B[0]={attr.B[0]}, B[1]={attr.B[1]}"); } } - """; - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoNotComplete_Attribute6() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" using System; class Program @@ -4301,42 +3789,38 @@ static void Test() { } } - """; - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoNotComplete_Using() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" using System.Linq$$ - """; - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoNotComplete_Using2() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" using System.Linq$$; - """; - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact] public void DoNotComplete_Using3() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" using System.$$Linq - """; - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/33851")] public void AtEndOfLineOutsideParens() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" public class Class1 { void M() @@ -4347,14 +3831,13 @@ void M() } } - """; - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/33851")] public void OutsideParensBeforeSpaceDot() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" public class Class1 { void M() @@ -4364,14 +3847,13 @@ void M() } } - """; - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34666")] public void BeforeAttribute() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" public class C { private const string s = @@ -4382,14 +3864,13 @@ public void M() { } } - """; - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34666")] public void ElementBindingExpression() { - var code = """ + VerifyTypingSemicolon(""" class C { void M() @@ -4398,8 +3879,7 @@ void M() var value = data?[0$$] } } - """; - var expected = """ + """, """ class C { void M() @@ -4408,14 +3888,13 @@ void M() var value = data?[0];$$ } } - """; - VerifyTypingSemicolon(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34666")] public void BeforeElementBindingExpression() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" class C { void M() @@ -4424,14 +3903,13 @@ void M() var value = data?$$[0] } } - """; - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34666")] public void AfterElementBindingExpression() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" class C { void M() @@ -4440,15 +3918,14 @@ void M() var value = data?[0]$$ } } - """; - VerifyNoSpecialSemicolonHandling(code); + """); } [WorkItem("https://github.com/dotnet/roslyn/issues/34666")] [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34983")] public void ImplicitElementAccessSyntax() { - var code = """ + VerifyTypingSemicolon(""" class C { void M() @@ -4459,8 +3936,7 @@ void M() } } } - """; - var expected = """ + """, """ class C { void M() @@ -4471,14 +3947,13 @@ void M() };$$ } } - """; - VerifyTypingSemicolon(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34666")] public void BeforeImplicitElementAccessSyntax() { - var code = """ + VerifyTypingSemicolon(""" class C { void M() @@ -4489,8 +3964,7 @@ void M() } } } - """; - var expected = """ + """, """ class C { void M() @@ -4501,14 +3975,13 @@ void M() };$$ } } - """; - VerifyTypingSemicolon(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34666")] public void AfterImplicitElementAccessSyntax() { - var code = """ + VerifyTypingSemicolon(""" class C { void M() @@ -4519,8 +3992,7 @@ void M() } } } - """; - var expected = """ + """, """ class C { void M() @@ -4531,14 +4003,13 @@ void M() };$$ } } - """; - VerifyTypingSemicolon(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34983")] public void AttributeParsedAsElementAccessExpression() { - var code = """ + VerifyTypingSemicolon(""" using System; internal class TestMethodAttribute : Attribute { @@ -4546,8 +4017,7 @@ internal class TestMethodAttribute : Attribute [Test] } - """; - var expected = """ + """, """ using System; internal class TestMethodAttribute : Attribute { @@ -4555,14 +4025,13 @@ internal class TestMethodAttribute : Attribute [Test] } - """; - VerifyTypingSemicolon(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34983")] public void MemberAccessOffOfMethod() { - var code = """ + VerifyTypingSemicolon(""" class Program { static void Main(string[] args) @@ -4571,8 +4040,7 @@ static void Main(string[] args) var t = s.ToLower($$).Substring(1); } } - """; - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -4581,14 +4049,13 @@ static void Main(string[] args) var t = s.ToLower();$$.Substring(1); } } - """; - VerifyTypingSemicolon(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34983")] public void LinqQuery() { - var code = """ + VerifyTypingSemicolon(""" using System.Collections.Generic; using System.Linq; class Query @@ -4602,8 +4069,7 @@ void Main(string[] args) .Select(x2 => x1 + x2)); } } - """; - var expected = """ + """, """ using System.Collections.Generic; using System.Linq; class Query @@ -4617,14 +4083,13 @@ void Main(string[] args) .Select(x2 => x1 + x2));$$ } } - """; - VerifyTypingSemicolon(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34983")] public void LinqQuery2() { - var code = """ + VerifyTypingSemicolon(""" using System.Collections.Generic; using System.Linq; class Query @@ -4637,8 +4102,7 @@ void Main(string[] args) .Select(x => x + x); } } - """; - var expected = """ + """, """ using System.Collections.Generic; using System.Linq; class Query @@ -4651,14 +4115,13 @@ void Main(string[] args) .Select(x => x + x); } } - """; - VerifyTypingSemicolon(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34983")] public void BinaryExpression() { - var code = """ + VerifyTypingSemicolon(""" class D { void M() @@ -4671,8 +4134,7 @@ private int Foo(int v) return v; } } - """; - var expected = """ + """, """ class D { void M() @@ -4685,14 +4147,13 @@ private int Foo(int v) return v; } } - """; - VerifyTypingSemicolon(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34983")] public void BinaryExpression2() { - var code = """ + VerifyTypingSemicolon(""" class D { void M() @@ -4705,8 +4166,7 @@ private int Foo(int v) return v; } } - """; - var expected = """ + """, """ class D { void M() @@ -4719,14 +4179,13 @@ private int Foo(int v) return v; } } - """; - VerifyTypingSemicolon(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34983")] public void AsOperator() { - var code = """ + VerifyTypingSemicolon(""" class D { void M() @@ -4739,8 +4198,7 @@ object Foo(int v) return v.ToString(); } } - """; - var expected = """ + """, """ class D { void M() @@ -4753,14 +4211,13 @@ object Foo(int v) return v.ToString(); } } - """; - VerifyTypingSemicolon(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34983")] public void TernaryOperator() { - var code = """ + VerifyTypingSemicolon(""" class Query { void Main(string[] args) @@ -4774,8 +4231,7 @@ private int Foo(int j) { return j; } - """; - var expected = """ + """, """ class Query { void Main(string[] args) @@ -4789,14 +4245,13 @@ private int Foo(int j) { return j; } - """; - VerifyTypingSemicolon(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34983")] public void SemicolonInCharacterLiteral() { - var code = """ + VerifyTypingSemicolon(""" class D { void Main(string[]args) @@ -4808,8 +4263,7 @@ void M(char c) { } } - """; - var expected = """ + """, """ class D { void Main(string[]args) @@ -4821,14 +4275,13 @@ void M(char c) { } } - """; - VerifyTypingSemicolon(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/35260")] public void IncompleteLambda() { - var code = """ + VerifyTypingSemicolon(""" using System; class C @@ -4843,8 +4296,7 @@ public void Test() private void M(Func p) { } } - """; - var expected = """ + """, """ using System; class C @@ -4859,8 +4311,7 @@ public void Test() private void M(Func p) { } } - """; - VerifyTypingSemicolon(code, expected); + """); } internal override ICommandHandler GetCommandHandler(EditorTestWorkspace workspace) @@ -4877,91 +4328,83 @@ public void ArgumentList_MultipleCharsSelected() [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34051")] public void ParameterList_DelegateDeclaration() { - var code = """ + VerifyTypingSemicolon(""" class C { delegate void Del(string str$$) } - """; - var expected = """ + """, """ class C { delegate void Del(string str);$$ } - """; - VerifyTypingSemicolon(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34051")] public void ParameterList_DelegateDeclaration2() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" class C { public delegate TResult Blah(T arg) } - """; - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34051")] public void ParameterList_DelegateDeclaration3() { - var code = """ + VerifyTypingSemicolon(""" class C { public delegate TResult Blah(T arg$$) } - """; - var expected = """ + """, """ class C { public delegate TResult Blah(T arg);$$ } - """; - VerifyTypingSemicolon(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34051")] public void ParameterList_MultilineDelegateDeclaration() { - var code = """ + VerifyTypingSemicolon(""" class C { delegate void Del(string str$$, int i, string str2) } - """; - var expected = """ + """, """ class C { delegate void Del(string str, int i, string str2);$$ } - """; - VerifyTypingSemicolon(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34051")] public void ParameterList_Constructor() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" class D { public D($$) { } } - """; - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34051")] public void ParameterList_Destructor() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" class D { public D() @@ -4972,28 +4415,26 @@ public D() { } } - """; - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/34051")] public void ParameterList_MethodDeclaration() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" class D { void M($$) { } } - """; - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/54709")] public void YieldReturn() { - var code = """ + VerifyTypingSemicolon(""" class D { private static IEnumerable M() @@ -5001,8 +4442,7 @@ private static IEnumerable M() yield return GetNumber($$) } } - """; - var expected = """ + """, """ class D { private static IEnumerable M() @@ -5010,8 +4450,7 @@ private static IEnumerable M() yield return GetNumber();$$ } } - """; - VerifyTypingSemicolon(code, expected); + """); } [WorkItem("https://github.com/dotnet/roslyn/issues/71933")] @@ -5072,13 +4511,12 @@ public void NearComments(string argument) [WpfFact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/923157")] public void BrokenCode_ReturnIfCaretDoesNotMove() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" class D { public Delegate Task Handles(int num)$$ } - """; - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/pull/37874")] @@ -5110,7 +4548,7 @@ public int XValue [WpfFact] public void TestSwitchExpression() { - var code = """ + VerifyTypingSemicolon(""" public class Bar { public void Test(string myString) @@ -5123,9 +4561,7 @@ public void Test(string myString) } } } - """; - - var expected = """ + """, """ public class Bar { public void Test(string myString) @@ -5138,14 +4574,13 @@ public void Test(string myString) };$$ } } - """; - VerifyTypingSemicolon(code, expected); + """); } [WpfFact] public void TestNotInBracesSwitchExpression() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" public class Bar { public void Test(string myString) @@ -5158,15 +4593,13 @@ public void Test(string myString) } } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/70224")] public void TestNotBeforeKeywordInSwitchExpression() { - var code = """ + VerifyNoSpecialSemicolonHandling(""" public class Bar { public void Test(string myString) @@ -5179,57 +4612,47 @@ public void Test(string myString) } } } - """; - - VerifyNoSpecialSemicolonHandling(code); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/54213")] public void AfterNewInField1() { - var code = """ + VerifyTypingSemicolon(""" public class C { public List list = new$$ } - """; - - var expected = """ + """, """ public class C { public List list = new();$$ } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/54213")] public void AfterNewInField2() { - var code = """ + VerifyTypingSemicolon(""" public class C { List list1 = new$$ List list2; } - """; - - var expected = """ + """, """ public class C { List list1 = new();$$ List list2; } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/54213")] public void AfterNewInLocalDeclaration1() { - var code = """ + VerifyTypingSemicolon(""" public class C { void M() @@ -5237,9 +4660,7 @@ void M() List list = new$$ } } - """; - - var expected = """ + """, """ public class C { void M() @@ -5247,15 +4668,13 @@ void M() List list = new();$$ } } - """; - - VerifyTypingSemicolon(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/54213")] public void AfterNewInLocalDeclaration2() { - var code = """ + VerifyTypingSemicolon(""" public class C { void M() @@ -5264,9 +4683,7 @@ void M() List list2; } } - """; - - var expected = """ + """, """ public class C { void M() @@ -5275,9 +4692,7 @@ void M() List list2; } } - """; - - VerifyTypingSemicolon(code, expected); + """); } protected override EditorTestWorkspace CreateTestWorkspace(string code) diff --git a/src/EditorFeatures/CSharpTest/Completion/ArgumentProviders/ContextVariableArgumentProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/ArgumentProviders/ContextVariableArgumentProviderTests.cs index 6ded50699bb4d..2ec7143f0f0cc 100644 --- a/src/EditorFeatures/CSharpTest/Completion/ArgumentProviders/ContextVariableArgumentProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/ArgumentProviders/ContextVariableArgumentProviderTests.cs @@ -22,20 +22,20 @@ internal override Type GetArgumentProviderType() [InlineData("int?")] public async Task TestLocalVariable(string type) { - var markup = $@" -class C -{{ - void Method() - {{ - {type} arg = default; - this.Target($$); - }} - - void Target({type} arg) - {{ - }} -}} -"; + var markup = $$""" + class C + { + void Method() + { + {{type}} arg = default; + this.Target($$); + } + + void Target({{type}} arg) + { + } + } + """; await VerifyDefaultValueAsync(markup, "arg"); await VerifyDefaultValueAsync(markup, expectedDefaultValue: null, previousDefaultValue: "prior"); @@ -46,20 +46,20 @@ public async Task TestOutVariable( [CombinatorialValues("string", "bool", "int?")] string type, [CombinatorialValues("out", "ref", "in")] string modifier) { - var markup = $@" -class C -{{ - void Method() - {{ - {type} arg; - this.Target($$); - }} - - void Target({modifier} {type} arg) - {{ - }} -}} -"; + var markup = $$""" + class C + { + void Method() + { + {{type}} arg; + this.Target($$); + } + + void Target({{modifier}} {{type}} arg) + { + } + } + """; var generatedModifier = modifier switch { @@ -77,19 +77,19 @@ void Target({modifier} {type} arg) [InlineData("int?")] public async Task TestParameter(string type) { - var markup = $@" -class C -{{ - void Method({type} arg) - {{ - this.Target($$); - }} - - void Target({type} arg) - {{ - }} -}} -"; + var markup = $$""" + class C + { + void Method({{type}} arg) + { + this.Target($$); + } + + void Target({{type}} arg) + { + } + } + """; await VerifyDefaultValueAsync(markup, "arg"); await VerifyDefaultValueAsync(markup, expectedDefaultValue: null, previousDefaultValue: "prior"); @@ -103,22 +103,22 @@ void Target({type} arg) [InlineData("int", "int?")] public async Task TestInstanceVariable(string fieldType, string parameterType) { - var markup = $@" -using System.Collections.Generic; -class C -{{ - {fieldType} arg; - - void Method() - {{ - this.Target($$); - }} - - void Target({parameterType} arg) - {{ - }} -}} -"; + var markup = $$""" + using System.Collections.Generic; + class C + { + {{fieldType}} arg; + + void Method() + { + this.Target($$); + } + + void Target({{parameterType}} arg) + { + } + } + """; await VerifyDefaultValueAsync(markup, "arg"); await VerifyDefaultValueAsync(markup, expectedDefaultValue: null, previousDefaultValue: "prior"); @@ -130,24 +130,24 @@ void Target({parameterType} arg) [InlineData("I")] public async Task TestThisInstance(string parameterType) { - var markup = $@" -using System.Collections.Generic; -interface I {{ }} + var markup = $$""" + using System.Collections.Generic; + interface I { } -class B {{ }} + class B { } -class C : B, I -{{ - void Method() - {{ - this.Target($$); - }} + class C : B, I + { + void Method() + { + this.Target($$); + } - void Target({parameterType} arg) - {{ - }} -}} -"; + void Target({{parameterType}} arg) + { + } + } + """; await VerifyDefaultValueAsync(markup, "this"); await VerifyDefaultValueAsync(markup, expectedDefaultValue: null, previousDefaultValue: "prior"); @@ -156,51 +156,43 @@ void Target({parameterType} arg) [Theory] [InlineData("object")] [InlineData("string")] - public async Task TestThisInstanceNotProvided1(string parameterType) - { - var markup = $@" -using System.Collections.Generic; -interface I {{ }} - -class B {{ }} - -class C : B, I -{{ - void Method() - {{ - this.Target($$); - }} - - void Target({parameterType} arg) - {{ - }} -}} -"; - - await VerifyDefaultValueAsync(markup, null); - } + public Task TestThisInstanceNotProvided1(string parameterType) + => VerifyDefaultValueAsync($$""" + using System.Collections.Generic; + interface I { } + + class B { } + + class C : B, I + { + void Method() + { + this.Target($$); + } + + void Target({{parameterType}} arg) + { + } + } + """, null); [Fact] - public async Task TestThisInstanceNotProvided2() - { - var markup = $@" -using System.Collections.Generic; - -class C -{{ - static void Method() - {{ - Target($$); - }} - - static void Target(C arg) - {{ - }} -}} -"; - - await VerifyDefaultValueAsync(markup, null); - } + public Task TestThisInstanceNotProvided2() + => VerifyDefaultValueAsync($$""" + using System.Collections.Generic; + + class C + { + static void Method() + { + Target($$); + } + + static void Target(C arg) + { + } + } + """, null); // Note: The current implementation checks for exact type match for primitive types. If this changes, some of // these tests may need to be updated to account for the new behavior. @@ -210,22 +202,18 @@ static void Target(C arg) [InlineData("bool", "bool?")] [InlineData("bool", "int")] [InlineData("int", "object")] - public async Task TestMismatchType(string parameterType, string valueType) - { - var markup = $@" -class C -{{ - void Method({valueType} arg) - {{ - this.Target($$); - }} - - void Target({parameterType} arg) - {{ - }} -}} -"; - - await VerifyDefaultValueAsync(markup, null); - } + public Task TestMismatchType(string parameterType, string valueType) + => VerifyDefaultValueAsync($$""" + class C + { + void Method({{valueType}} arg) + { + this.Target($$); + } + + void Target({{parameterType}} arg) + { + } + } + """, null); } diff --git a/src/EditorFeatures/CSharpTest/Completion/ArgumentProviders/DefaultArgumentProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/ArgumentProviders/DefaultArgumentProviderTests.cs index ab4800328e763..926c8751432e4 100644 --- a/src/EditorFeatures/CSharpTest/Completion/ArgumentProviders/DefaultArgumentProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/ArgumentProviders/DefaultArgumentProviderTests.cs @@ -20,19 +20,19 @@ internal override Type GetArgumentProviderType() [InlineData("System.Collections.DictionaryEntry")] public async Task TestDefaultValueIsDefaultLiteral(string type) { - var markup = $@" -class C -{{ - void Method() - {{ - this.Target($$); - }} + var markup = $$""" + class C + { + void Method() + { + this.Target($$); + } - void Target({type} arg) - {{ - }} -}} -"; + void Target({{type}} arg) + { + } + } + """; await VerifyDefaultValueAsync(markup, "default"); await VerifyDefaultValueAsync(markup, expectedDefaultValue: "prior", previousDefaultValue: "prior"); @@ -46,19 +46,19 @@ void Target({type} arg) [InlineData("System.Exception")] public async Task TestDefaultValueIsNullLiteral(string type) { - var markup = $@" -class C -{{ - void Method() - {{ - this.Target($$); - }} + var markup = $$""" + class C + { + void Method() + { + this.Target($$); + } - void Target({type} arg) - {{ - }} -}} -"; + void Target({{type}} arg) + { + } + } + """; await VerifyDefaultValueAsync(markup, "null"); await VerifyDefaultValueAsync(markup, expectedDefaultValue: "prior", previousDefaultValue: "prior"); @@ -93,19 +93,19 @@ void Target({type} arg) [InlineData("System.UInt64", "0UL")] public async Task TestDefaultValueIsZero(string type, string literalZero) { - var markup = $@" -class C -{{ - void Method() - {{ - this.Target($$); - }} + var markup = $$""" + class C + { + void Method() + { + this.Target($$); + } - void Target({type} arg) - {{ - }} -}} -"; + void Target({{type}} arg) + { + } + } + """; await VerifyDefaultValueAsync(markup, literalZero); await VerifyDefaultValueAsync(markup, expectedDefaultValue: "prior", previousDefaultValue: "prior"); diff --git a/src/EditorFeatures/CSharpTest/Completion/ArgumentProviders/OutVariableArgumentProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/ArgumentProviders/OutVariableArgumentProviderTests.cs index 62ce34d750507..3b6339dc6c8c3 100644 --- a/src/EditorFeatures/CSharpTest/Completion/ArgumentProviders/OutVariableArgumentProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/ArgumentProviders/OutVariableArgumentProviderTests.cs @@ -45,35 +45,31 @@ internal override Type GetArgumentProviderType() [InlineData("")] [InlineData("ref")] [InlineData("in")] - public async Task TestUnsupportedModifiers(string modifier) - { - var markup = $@" -class C -{{ - void Method() - {{ - TryParse($$) - }} - - bool TryParse({modifier} int value) => throw null; -}} -"; - - await VerifyDefaultValueAsync(markup, expectedDefaultValue: null); - } + public Task TestUnsupportedModifiers(string modifier) + => VerifyDefaultValueAsync($$""" + class C + { + void Method() + { + TryParse($$) + } + + bool TryParse({{modifier}} int value) => throw null; + } + """, expectedDefaultValue: null); [Fact] public async Task TestDeclareVariable() { - var markup = $@" -class C -{{ - void Method() - {{ - int.TryParse(""x"", $$) - }} -}} -"; + var markup = $$""" + class C + { + void Method() + { + int.TryParse("x", $$) + } + } + """; await VerifyDefaultValueAsync(markup, "out var result"); await VerifyDefaultValueAsync(markup, expectedDefaultValue: null, previousDefaultValue: "prior"); @@ -83,17 +79,6 @@ void Method() [CombinatorialData] public async Task TestDeclareVariableBuiltInType(bool preferVar, bool preferBuiltInType) { - var markup = $@" -using System; -class C -{{ - void Method() - {{ - int.TryParse(""x"", $$) - }} -}} -"; - var expected = (preferVar, preferBuiltInType) switch { (true, _) => "out var result", @@ -108,7 +93,16 @@ void Method() (false, false) => s_useExplicitMetadataTypeOptions, }; - await VerifyDefaultValueAsync(markup, expected, options: options); + await VerifyDefaultValueAsync($$""" + using System; + class C + { + void Method() + { + int.TryParse("x", $$) + } + } + """, expected, options: options); } [Theory] @@ -117,20 +111,20 @@ void Method() [InlineData("int?")] public async Task TestDeclareVariableEscapedIdentifier(string type) { - var markup = $@" -class C -{{ - void Method() - {{ - this.Target($$); - }} - - void Target(out {type} @void) - {{ - @void = default; - }} -}} -"; + var markup = $$""" + class C + { + void Method() + { + this.Target($$); + } + + void Target(out {{type}} @void) + { + @void = default; + } + } + """; await VerifyDefaultValueAsync(markup, "out var @void"); await VerifyDefaultValueAsync(markup, expectedDefaultValue: null, previousDefaultValue: "prior"); diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/AbstractCSharpCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/AbstractCSharpCompletionProviderTests.cs index cbe49be4bcd03..28c4b0d94ae15 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/AbstractCSharpCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/AbstractCSharpCompletionProviderTests.cs @@ -32,15 +32,17 @@ public abstract class AbstractCSharpCompletionProviderTests : protected static string GetMarkup( [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string source, LanguageVersion languageVersion) - => $@" - - - - - -"; + => $""" + + + + + + + + """; protected override EditorTestWorkspace CreateWorkspace([StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string fileContents) => EditorTestWorkspace.CreateCSharp(fileContents, composition: GetComposition()); @@ -119,35 +121,31 @@ await base.VerifyWorkerAsync( options, skipSpeculation: skipSpeculation); } - private async Task VerifyInFrontOfCommentAsync( + private Task VerifyInFrontOfCommentAsync( [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string code, int position, bool usePreviousCharAsTrigger, char? deletedCharTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, Glyph? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit, List matchingFilters, CompletionOptions options, bool skipSpeculation = false) - { - await VerifyInFrontOfCommentAsync( + => VerifyInFrontOfCommentAsync( code, position, string.Empty, usePreviousCharAsTrigger, deletedCharTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, options, skipSpeculation: skipSpeculation); - } - private protected async Task VerifyInFrontOfComment_ItemPartiallyWrittenAsync( + private protected Task VerifyInFrontOfComment_ItemPartiallyWrittenAsync( [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string code, int position, bool usePreviousCharAsTrigger, char? deletedCharTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, Glyph? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit, List matchingFilters, CompletionOptions options, bool skipSpeculation = false) - { - await VerifyInFrontOfCommentAsync( + => VerifyInFrontOfCommentAsync( code, position, ItemPartiallyWritten(expectedItemOrNull), usePreviousCharAsTrigger, deletedCharTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, options, skipSpeculation: skipSpeculation); - } protected static string AddInsideMethod([StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string text) { diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/AttributeNamedParameterCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/AttributeNamedParameterCompletionProviderTests.cs index 1991b35b4a6b9..e335564b79f03 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/AttributeNamedParameterCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/AttributeNamedParameterCompletionProviderTests.cs @@ -68,9 +68,8 @@ public class TestAttribute : Attribute } [Fact] - public async Task SimpleAttributeUsage() - { - var markup = """ + public Task SimpleAttributeUsage() + => VerifyItemExistsAsync(""" using System; class class1 { @@ -84,15 +83,11 @@ public class TestAttribute : Attribute { public ConsoleColor Color { get; set; } } - """; - - await VerifyItemExistsAsync(markup, "Color", displayTextSuffix: " ="); - } + """, "Color", displayTextSuffix: " ="); [Fact] - public async Task AfterComma() - { - var markup = """ + public Task AfterComma() + => VerifyItemExistsAsync(""" using System; class class1 { @@ -107,10 +102,7 @@ public class TestAttribute : Attribute public ConsoleColor Color { get; set; } public string Text { get; set; } } - """; - - await VerifyItemExistsAsync(markup, "Text", displayTextSuffix: " ="); - } + """, "Text", displayTextSuffix: " ="); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544345")] public async Task ExistingItemsAreFiltered() @@ -137,9 +129,8 @@ public class TestAttribute : Attribute } [Fact] - public async Task AttributeConstructor() - { - var markup = """ + public Task AttributeConstructor() + => VerifyItemExistsAsync(""" using System; class TestAttribute : Attribute { @@ -150,15 +141,11 @@ public TestAttribute(int a = 42) [Test($$ class Goo { } - """; - - await VerifyItemExistsAsync(markup, "a", displayTextSuffix: ":"); - } + """, "a", displayTextSuffix: ":"); [Fact] - public async Task AttributeConstructorAfterComma() - { - var markup = """ + public Task AttributeConstructorAfterComma() + => VerifyItemExistsAsync(""" using System; class TestAttribute : Attribute { @@ -169,15 +156,11 @@ public TestAttribute(int a = 42, string s = "") [Test(s:"", $$ class Goo { } - """; - - await VerifyItemExistsAsync(markup, "a", displayTextSuffix: ":"); - } + """, "a", displayTextSuffix: ":"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545426")] - public async Task TestPropertiesInScript() - { - var markup = """ + public Task TestPropertiesInScript() + => VerifyItemExistsAsync(""" using System; class TestAttribute : Attribute @@ -192,15 +175,11 @@ public TestAttribute(int number = 42) class Goo { } - """; - - await VerifyItemExistsAsync(markup, "Text", displayTextSuffix: " ="); - } + """, "Text", displayTextSuffix: " ="); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1075278")] - public async Task NotInComment() - { - var markup = """ + public Task NotInComment() + => VerifyNoItemsExistAsync(""" using System; class class1 { @@ -214,8 +193,5 @@ public class TestAttribute : Attribute { public ConsoleColor Color { get; set; } } - """; - - await VerifyNoItemsExistAsync(markup); - } + """); } diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/AwaitCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/AwaitCompletionProviderTests.cs index 504178d5e2130..44433d40aea12 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/AwaitCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/AwaitCompletionProviderTests.cs @@ -63,20 +63,17 @@ static string GetDescription(string keyword, string tooltip) } [Fact] - public async Task TestNotInTypeContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInTypeContext() + => VerifyAbsenceAsync(""" class Program { $$ } """); - } [Fact] - public async Task TestStatementInMethod() - { - await VerifyKeywordAsync(""" + public Task TestStatementInMethod() + => VerifyKeywordAsync(""" class C { void F() @@ -84,12 +81,10 @@ void F() $$ } } """, LanguageVersion.CSharp9); - } [Fact] - public async Task TestStatementInMethod_Async() - { - await VerifyKeywordAsync(""" + public Task TestStatementInMethod_Async() + => VerifyKeywordAsync(""" class C { async Task F() @@ -97,18 +92,14 @@ async Task F() $$ } } """, LanguageVersion.CSharp9); - } [Fact] - public async Task TestStatementInMethod_TopLevel() - { - await VerifyKeywordAsync("$$", LanguageVersion.CSharp9); - } + public Task TestStatementInMethod_TopLevel() + => VerifyKeywordAsync("$$", LanguageVersion.CSharp9); [Fact] - public async Task TestExpressionInAsyncMethod() - { - await VerifyKeywordAsync(""" + public Task TestExpressionInAsyncMethod() + => VerifyKeywordAsync(""" class C { async Task F() @@ -116,12 +107,10 @@ async Task F() var z = $$ } } """, LanguageVersion.CSharp9); - } [Fact] - public async Task TestExpressionInNonAsyncMethodWithTaskReturn() - { - await VerifyKeywordAsync(""" + public Task TestExpressionInNonAsyncMethodWithTaskReturn() + => VerifyKeywordAsync(""" class C { Task F() @@ -129,18 +118,14 @@ Task F() var z = $$ } } """, LanguageVersion.CSharp9); - } [Fact] - public async Task TestExpressionInAsyncMethod_TopLevel() - { - await VerifyKeywordAsync("var z = $$", LanguageVersion.CSharp9); - } + public Task TestExpressionInAsyncMethod_TopLevel() + => VerifyKeywordAsync("var z = $$", LanguageVersion.CSharp9); [Fact] - public async Task TestUsingStatement() - { - await VerifyAbsenceAsync(""" + public Task TestUsingStatement() + => VerifyAbsenceAsync(""" class C { async Task F() @@ -148,13 +133,10 @@ async Task F() using $$ } } """, LanguageVersion.CSharp9); - } [Fact] - public async Task TestUsingStatement_TopLevel() - { - await VerifyAbsenceAsync("using $$", LanguageVersion.CSharp9); - } + public Task TestUsingStatement_TopLevel() + => VerifyAbsenceAsync("using $$", LanguageVersion.CSharp9); [Fact] public async Task TestUsingDirective() @@ -165,9 +147,8 @@ public async Task TestGlobalUsingDirective() => await VerifyAbsenceAsync("global using $$"); [Fact] - public async Task TestForeachStatement() - { - await VerifyAbsenceAsync(""" + public Task TestForeachStatement() + => VerifyAbsenceAsync(""" class C { async Task F() @@ -175,18 +156,14 @@ async Task F() foreach $$ } } """, LanguageVersion.CSharp9); - } [Fact] - public async Task TestForeachStatement_TopLevel() - { - await VerifyAbsenceAsync("foreach $$", LanguageVersion.CSharp9); - } + public Task TestForeachStatement_TopLevel() + => VerifyAbsenceAsync("foreach $$", LanguageVersion.CSharp9); [Fact] - public async Task TestNotInQuery() - { - await VerifyAbsenceAsync(""" + public Task TestNotInQuery() + => VerifyAbsenceAsync(""" class C { async Task F() @@ -195,22 +172,18 @@ async Task F() select $$ } } """, LanguageVersion.CSharp9); - } [Fact] - public async Task TestNotInQuery_TopLevel() - { - await VerifyAbsenceAsync( + public Task TestNotInQuery_TopLevel() + => VerifyAbsenceAsync( """ var z = from a in "char" select $$ """, LanguageVersion.CSharp9); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907052")] - public async Task TestInFinally() - { - await VerifyKeywordAsync(""" + public Task TestInFinally() + => VerifyKeywordAsync(""" class C { async Task F() @@ -219,22 +192,18 @@ async Task F() finally { $$ } } } """, LanguageVersion.CSharp9); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907052")] - public async Task TestInFinally_TopLevel() - { - await VerifyKeywordAsync( + public Task TestInFinally_TopLevel() + => VerifyKeywordAsync( """ try { } finally { $$ } """, LanguageVersion.CSharp9); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907052")] - public async Task TestInCatch() - { - await VerifyKeywordAsync(""" + public Task TestInCatch() + => VerifyKeywordAsync(""" class C { async Task F() @@ -243,22 +212,18 @@ async Task F() catch { $$ } } } """, LanguageVersion.CSharp9); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907052")] - public async Task TestInCatch_TopLevel() - { - await VerifyKeywordAsync( + public Task TestInCatch_TopLevel() + => VerifyKeywordAsync( """ try { } catch { $$ } """, LanguageVersion.CSharp9); - } [Fact] - public async Task TestNotInLock() - { - await VerifyAbsenceAsync(""" + public Task TestNotInLock() + => VerifyAbsenceAsync(""" class C { async Task F() @@ -266,18 +231,14 @@ async Task F() lock(this) { $$ } } } """, LanguageVersion.CSharp9); - } [Fact] - public async Task TestNotInLock_TopLevel() - { - await VerifyAbsenceAsync("lock (this) { $$ }", LanguageVersion.CSharp9); - } + public Task TestNotInLock_TopLevel() + => VerifyAbsenceAsync("lock (this) { $$ }", LanguageVersion.CSharp9); [Fact] - public async Task TestInAsyncLambdaInCatch() - { - await VerifyKeywordAsync(""" + public Task TestInAsyncLambdaInCatch() + => VerifyKeywordAsync(""" class C { async Task F() @@ -286,22 +247,18 @@ async Task F() catch { var z = async () => $$ } } } """, LanguageVersion.CSharp9); - } [Fact] - public async Task TestInAsyncLambdaInCatch_TopLevel() - { - await VerifyKeywordAsync( + public Task TestInAsyncLambdaInCatch_TopLevel() + => VerifyKeywordAsync( """ try { } catch { var z = async () => $$ } """, LanguageVersion.CSharp9); - } [Fact] - public async Task TestAwaitInLock() - { - await VerifyKeywordAsync(""" + public Task TestAwaitInLock() + => VerifyKeywordAsync(""" class C { async Task F() @@ -309,18 +266,14 @@ async Task F() lock($$ } } """, LanguageVersion.CSharp9); - } [Fact] - public async Task TestAwaitInLock_TopLevel() - { - await VerifyKeywordAsync("lock($$", LanguageVersion.CSharp9); - } + public Task TestAwaitInLock_TopLevel() + => VerifyKeywordAsync("lock($$", LanguageVersion.CSharp9); [Fact] - public async Task TestDotAwaitSuggestAfterDotOnTask() - { - await VerifyKeywordAsync(""" + public Task TestDotAwaitSuggestAfterDotOnTask() + => VerifyKeywordAsync(""" using System.Threading.Tasks; class C @@ -331,12 +284,10 @@ async Task F(Task someTask) } } """, dotAwait: true, dotAwaitf: true); - } [Fact] - public async Task TestDotAwaitSuggestAfterDotOnTaskOfT() - { - await VerifyKeywordAsync(""" + public Task TestDotAwaitSuggestAfterDotOnTaskOfT() + => VerifyKeywordAsync(""" using System.Threading.Tasks; class C @@ -347,7 +298,6 @@ async Task F(Task someTask) } } """, dotAwait: true, dotAwaitf: true); - } [Fact] public async Task TestDotAwaitSuggestAfterDotOnValueTask() @@ -376,9 +326,8 @@ async Task F(ValueTask someTask) } [Fact] - public async Task TestDotAwaitSuggestAfterDotOnCustomAwaitable() - { - await VerifyKeywordAsync(""" + public Task TestDotAwaitSuggestAfterDotOnCustomAwaitable() + => VerifyKeywordAsync(""" using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; @@ -403,12 +352,10 @@ static async Task Main() } } """, dotAwait: true); - } [Fact] - public async Task TestDotAwaitSuggestAfterDotOnCustomAwaitableButNotConfigureAwaitEvenIfPresent() - { - await VerifyKeywordAsync(""" + public Task TestDotAwaitSuggestAfterDotOnCustomAwaitableButNotConfigureAwaitEvenIfPresent() + => VerifyKeywordAsync(""" using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; @@ -434,12 +381,10 @@ static async Task Main() } } """, dotAwait: true, dotAwaitf: false); - } [Fact] - public async Task TestDotAwaitSuggestAfterDotDot() - { - await VerifyKeywordAsync(""" + public Task TestDotAwaitSuggestAfterDotDot() + => VerifyKeywordAsync(""" using System.Threading.Tasks; static class Program @@ -450,12 +395,10 @@ static async Task Main(Task someTask) } } """, dotAwait: true, dotAwaitf: true); - } [Fact] - public async Task TestDotAwaitSuggestAfterDotBeforeType() - { - await VerifyKeywordAsync(""" + public Task TestDotAwaitSuggestAfterDotBeforeType() + => VerifyKeywordAsync(""" using System; using System.Threading.Tasks; @@ -468,12 +411,10 @@ static async Task Main(Task someTask) } } """, dotAwait: true, dotAwaitf: true); - } [Fact] - public async Task TestDotAwaitSuggestAfterDotBeforeAnotherAwait() - { - await VerifyKeywordAsync(""" + public Task TestDotAwaitSuggestAfterDotBeforeAnotherAwait() + => VerifyKeywordAsync(""" using System; using System.Threading.Tasks; @@ -488,7 +429,6 @@ static async Task Main(Task someTask) async Task Test() { } } """, dotAwait: true, dotAwaitf: true); - } [Theory] [InlineData("")] @@ -499,9 +439,8 @@ async Task Test() { } [InlineData("if (true) { }")] [InlineData("System.Int32 Test() => 0;")] [InlineData("async Task Test() => await Task.FromResult(1);")] - public async Task TestDotAwaitSuggestAfterDotBeforeDifferentStatements(string statement) - { - await VerifyKeywordAsync($$""" + public Task TestDotAwaitSuggestAfterDotBeforeDifferentStatements(string statement) + => VerifyKeywordAsync($$""" using System; using System.Threading.Tasks; @@ -514,7 +453,6 @@ static async Task Main(Task someTask) } } """, dotAwait: true, dotAwaitf: true); - } [Theory] // static @@ -547,9 +485,8 @@ static async Task Main(Task someTask) [InlineData("((parameter)).$$")] [InlineData("(true ? parameter : parameter).$$")] [InlineData("(null ?? Task.CompletedTask).$$")] - public async Task TestDotAwaitSuggestAfterDifferentExpressions(string expression) - { - await VerifyKeywordAsync($$""" + public Task TestDotAwaitSuggestAfterDifferentExpressions(string expression) + => VerifyKeywordAsync($$""" using System; using System.Threading.Tasks; @@ -582,19 +519,11 @@ static async Task Main(Task parameter) } } """, dotAwait: true, dotAwaitf: true); - } [Fact(Skip = "Fails because speculative binding can't figure out that local is a Task.")] [WorkItem("https://github.com/dotnet/roslyn/issues/56245")] - public async Task TestDotAwaitSuggestBeforeLocalFunction() - { - // Speculative binding a local as expression finds the local as ILocalSymbol, but the type is ErrorType. - // This is only the case when - // * await is partially written (local.a), - // * only for locals (e.g. IParameterSymbols are fine) which - // * are declared with var - // * The return type of the local function is used as first name in a MemberAccess in the declarator - await VerifyKeywordAsync(""" + public Task TestDotAwaitSuggestBeforeLocalFunction() + => VerifyKeywordAsync(""" using System.Threading.Tasks; static class Program @@ -608,7 +537,6 @@ static async Task Main() } } """); - } [Theory] [InlineData("await Task.Run(async () => Task.CompletedTask.$$")] @@ -620,9 +548,8 @@ static async Task Main() [InlineData("Task.Run(async () => await someTask).$$")] [InlineData("await Task.Run(() => someTask.$$")] - public async Task TestDotAwaitSuggestInLambdas(string lambda) - { - await VerifyKeywordAsync($$""" + public Task TestDotAwaitSuggestInLambdas(string lambda) + => VerifyKeywordAsync($$""" using System.Threading.Tasks; static class Program @@ -634,12 +561,10 @@ static async Task Main() } } """, dotAwait: true, dotAwaitf: true); - } [Fact] - public async Task TestDotAwaitNotAfterDotOnTaskIfAlreadyAwaited() - { - await VerifyAbsenceAsync(""" + public Task TestDotAwaitNotAfterDotOnTaskIfAlreadyAwaited() + => VerifyAbsenceAsync(""" using System.Threading.Tasks; class C @@ -650,12 +575,10 @@ await someTask.$$ } } """); - } [Fact] - public async Task TestDotAwaitNotAfterTaskType() - { - await VerifyAbsenceAsync(""" + public Task TestDotAwaitNotAfterTaskType() + => VerifyAbsenceAsync(""" using System.Threading.Tasks; class C @@ -666,12 +589,10 @@ async Task F() } } """); - } [Fact] - public async Task TestDotAwaitNotInLock() - { - await VerifyAbsenceAsync(""" + public Task TestDotAwaitNotInLock() + => VerifyAbsenceAsync(""" using System.Threading.Tasks; class C @@ -682,22 +603,18 @@ async Task F(Task someTask) } } """); - } [Fact] - public async Task TestDotAwaitNotInLock_TopLevel() - { - await VerifyAbsenceAsync(""" + public Task TestDotAwaitNotInLock_TopLevel() + => VerifyAbsenceAsync(""" using System.Threading.Tasks; lock(this) { Task.CompletedTask.$$ } """); - } [Fact] - public async Task TestDotAwaitQueryNotInSelect() - { - await VerifyAbsenceAsync(""" + public Task TestDotAwaitQueryNotInSelect() + => VerifyAbsenceAsync(""" using System.Linq; using System.Threading.Tasks; @@ -710,12 +627,10 @@ select t.$$ } } """); - } [Fact] - public async Task TestDotAwaitQueryInFirstFromClause() - { - await VerifyKeywordAsync(""" + public Task TestDotAwaitQueryInFirstFromClause() + => VerifyKeywordAsync(""" using System.Linq; using System.Threading.Tasks; @@ -729,12 +644,10 @@ async Task F() } } """, dotAwait: true, dotAwaitf: true); - } [Fact] - public async Task TestDotAwaitQueryNotInSecondFromClause() - { - await VerifyNoItemsExistAsync(""" + public Task TestDotAwaitQueryNotInSecondFromClause() + => VerifyNoItemsExistAsync(""" using System.Linq; using System.Threading.Tasks; @@ -750,12 +663,10 @@ from i2 in arrayTask2.$$ } } """); - } [Fact] - public async Task TestDotAwaitQueryNotInContinuation() - { - await VerifyNoItemsExistAsync(""" + public Task TestDotAwaitQueryNotInContinuation() + => VerifyNoItemsExistAsync(""" using System.Linq; using System.Threading.Tasks; @@ -772,12 +683,10 @@ from i2 in arrayTask2.$$ } } """); - } [Fact] - public async Task TestDotAwaitQueryInJoinClause() - { - await VerifyKeywordAsync(""" + public Task TestDotAwaitQueryInJoinClause() + => VerifyKeywordAsync(""" using System.Linq; using System.Threading.Tasks; @@ -793,12 +702,10 @@ join i2 in arrayTask2.$$ on i1 equals i2 } } """, dotAwait: true, dotAwaitf: true); - } [Fact] - public async Task TestDotAwaitQueryInJoinIntoClause() - { - await VerifyKeywordAsync(""" + public Task TestDotAwaitQueryInJoinIntoClause() + => VerifyKeywordAsync(""" using System.Linq; using System.Threading.Tasks; @@ -814,20 +721,10 @@ join i2 in arrayTask2.$$ on i1 equals i2 into g } } """, dotAwait: true, dotAwaitf: true); - } [Fact] - public async Task TestDotAwaitNotAfterConditionalAccessOfTaskMembers() - { - // The conditional access suggests, that someTask can be null. - // await on null throws at runtime, so the user should do - // if (someTask is not null) await someTask; - // or - // await (someTask ?? Task.CompletedTask) - // Completion should not offer await, because the patterns above would change to much code. - // This decision should be revised after https://github.com/dotnet/csharplang/issues/35 - // is implemented. - await VerifyAbsenceAsync(""" + public Task TestDotAwaitNotAfterConditionalAccessOfTaskMembers() + => VerifyAbsenceAsync(""" using System.Threading.Tasks; class C @@ -838,7 +735,6 @@ async Task F(Task someTask) } } """); - } [Theory] [InlineData("c?.SomeTask.$$")] @@ -857,9 +753,8 @@ async Task F(Task someTask) [InlineData("c.M()?.M().M()?.M().SomeTask.$$")] [InlineData("new C().M()?.Pro.M()?.M().SomeTask.$$")] - public async Task TestDotAwaitNotAfterDotInConditionalAccessChain(string conditionalAccess) - { - await VerifyAbsenceAsync($$""" + public Task TestDotAwaitNotAfterDotInConditionalAccessChain(string conditionalAccess) + => VerifyAbsenceAsync($$""" using System.Threading.Tasks; public class C { @@ -878,7 +773,6 @@ public static async Task Main() } } """); - } [Theory] [InlineData("c!.SomeTask.$$")] @@ -898,9 +792,8 @@ public static async Task Main() [InlineData("c.M()!.M().M()!.M().SomeTask.$$")] [InlineData("new C().M()!.Pro.M()!.M().SomeTask.$$")] - public async Task TestDotAwaitAfterNullForgivingOperatorAccessChain(string nullForgivingAccess) - { - await VerifyKeywordAsync($$""" + public Task TestDotAwaitAfterNullForgivingOperatorAccessChain(string nullForgivingAccess) + => VerifyKeywordAsync($$""" #nullable enable using System.Threading.Tasks; @@ -921,7 +814,6 @@ public static async Task Main(params string[] args) } } """, dotAwait: true, dotAwaitf: true); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/58921")] diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ConversionCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ConversionCompletionProviderTests.cs index b515808efd670..2acfa783ddb1e 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ConversionCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ConversionCompletionProviderTests.cs @@ -69,10 +69,8 @@ public static void Main() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task ExplicitUserDefinedConversionIsNotOfferedAfterNumberLiteral() - { - // User may want to type a floating point literal. - await VerifyNoItemsExistAsync(""" + public Task ExplicitUserDefinedConversionIsNotOfferedAfterNumberLiteral() + => VerifyNoItemsExistAsync(""" public class C { public static explicit operator float(C c) => 0; @@ -86,12 +84,10 @@ public static void Main() } } """, SourceCodeKind.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task ExplicitUserDefinedConversionIsSuggestedAfterDot() - { - await VerifyItemExistsAsync(""" + public Task ExplicitUserDefinedConversionIsSuggestedAfterDot() + => VerifyItemExistsAsync(""" public class C { public static explicit operator float(C c) => 0; @@ -106,12 +102,10 @@ public static void Main() } } """, "float", displayTextPrefix: "(", displayTextSuffix: ")", glyph: Glyph.OperatorPublic, matchingFilters: [FilterSet.OperatorFilter]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task ExplicitUserDefinedConversionIsSuggestedIfMemberNameIsPartiallyWritten() - { - await VerifyItemExistsAsync(""" + public Task ExplicitUserDefinedConversionIsSuggestedIfMemberNameIsPartiallyWritten() + => VerifyItemExistsAsync(""" public class C { public void fly() { } @@ -127,7 +121,6 @@ public static void Main() } } """, "float", displayTextPrefix: "(", displayTextSuffix: ")", glyph: Glyph.OperatorPublic, matchingFilters: [FilterSet.OperatorFilter]); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] [InlineData("c.$$", true)] @@ -149,27 +142,26 @@ public async Task ExplicitUserDefinedConversionDifferentExpressions(string expre ? (markup, expectedItem) => VerifyItemExistsAsync(markup, expectedItem, displayTextPrefix: "(", displayTextSuffix: ")") : (markup, expectedItem) => VerifyItemIsAbsentAsync(markup, expectedItem, displayTextPrefix: "(", displayTextSuffix: ")"); - await verifyFunc(@$" -public class C -{{ - public static explicit operator float(C c) => 0; -}} - -public class Program -{{ - public static void Main() - {{ - var c = new C(); - {expression} - }} -}} -", "float"); + await verifyFunc($$""" + public class C + { + public static explicit operator float(C c) => 0; + } + + public class Program + { + public static void Main() + { + var c = new C(); + {{expression}} + } + } + """, "float"); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task ExplicitUserDefinedConversionIsNotSuggestedOnStaticAccess() - { - await VerifyNoItemsExistAsync(""" + public Task ExplicitUserDefinedConversionIsNotSuggestedOnStaticAccess() + => VerifyNoItemsExistAsync(""" public class C { public static explicit operator float(C c) => 0; @@ -183,12 +175,10 @@ public static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task ExplicitUserDefinedConversionIsNotSuggestedInNameofContext() - { - await VerifyNoItemsExistAsync(""" + public Task ExplicitUserDefinedConversionIsNotSuggestedInNameofContext() + => VerifyNoItemsExistAsync(""" public class C { public static explicit operator float(C c) => 0; @@ -203,7 +193,6 @@ public static void Main() } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] [InlineData("", "Nested1.C", "Nested2.C")] @@ -212,41 +201,41 @@ public static void Main() [InlineData("using N1.Nested1;using N1.Nested2;", "Nested1.C", "Nested2.C")] public async Task ExplicitUserDefinedConversionTypeDisplayStringIsMinimal(string usingDirective, string displayText1, string displayText2) { - var items = await GetCompletionItemsAsync(@$" -namespace N1.Nested1 -{{ - public class C - {{ - }} -}} - -namespace N1.Nested2 -{{ - public class C - {{ - }} -}} -namespace N2 -{{ - public class Conversion - {{ - public static explicit operator N1.Nested1.C(Conversion _) => new N1.Nested1.C(); - public static explicit operator N1.Nested2.C(Conversion _) => new N1.Nested2.C(); - }} -}} -namespace N1 -{{ - {usingDirective} - public class Test - {{ - public void M() - {{ - var conversion = new N2.Conversion(); - conversion.$$ - }} - }} -}} -", SourceCodeKind.Regular); + var items = await GetCompletionItemsAsync($$""" + namespace N1.Nested1 + { + public class C + { + } + } + + namespace N1.Nested2 + { + public class C + { + } + } + namespace N2 + { + public class Conversion + { + public static explicit operator N1.Nested1.C(Conversion _) => new N1.Nested1.C(); + public static explicit operator N1.Nested2.C(Conversion _) => new N1.Nested2.C(); + } + } + namespace N1 + { + {{usingDirective}} + public class Test + { + public void M() + { + var conversion = new N2.Conversion(); + conversion.$$ + } + } + } + """, SourceCodeKind.Regular); Assert.Collection(items, i => Assert.Equal(displayText1, i.DisplayText), i => Assert.Equal(displayText2, i.DisplayText)); @@ -281,9 +270,8 @@ public static void Main() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task ExplicitUserDefinedConversionIgnoresConversionLikeMethods() - { - await VerifyNoItemsExistAsync(""" + public Task ExplicitUserDefinedConversionIgnoresConversionLikeMethods() + => VerifyNoItemsExistAsync(""" public class C { public static bool op_Explicit(C c) => false; @@ -298,12 +286,10 @@ public static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task ExplicitUserDefinedConversionIgnoreMalformedOperators() - { - await VerifyNoItemsExistAsync(""" + public Task ExplicitUserDefinedConversionIgnoreMalformedOperators() + => VerifyNoItemsExistAsync(""" public class C { public static explicit operator int() => 0; @@ -318,12 +304,10 @@ public static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task ExplicitUserDefinedConversionFromOtherTypeToTargetIsNotSuggested() - { - await VerifyNoItemsExistAsync(""" + public Task ExplicitUserDefinedConversionFromOtherTypeToTargetIsNotSuggested() + => VerifyNoItemsExistAsync(""" public class C { public static explicit operator C(D d) => null; @@ -341,13 +325,10 @@ public static void Main() } } """); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task ExplicitConversionOfNullableStructToNullableStructIsOffered() - { - // Lifted conversion https://docs.microsoft.com/hu-hu/dotnet/csharp/language-reference/language-specification/conversions#lifted-conversion-operators - await VerifyItemExistsAsync(""" + public Task ExplicitConversionOfNullableStructToNullableStructIsOffered() + => VerifyItemExistsAsync(""" public struct S { public static explicit operator int(S _) => 0; } @@ -360,7 +341,6 @@ public static void Main() } } """, "int?", displayTextPrefix: "(", displayTextSuffix: ")", glyph: Glyph.OperatorPublic, matchingFilters: [FilterSet.OperatorFilter]); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] public async Task ExplicitConversionDescriptionIsIsGiven() @@ -441,16 +421,16 @@ public async Task ExplicitBuiltInNumericConversionsAreOfferedAcordingToSpec(stri { // built-in numeric conversions: // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/numeric-conversions - var items = await GetCompletionItemsAsync(@$" -public class Program -{{ - public static void Main() - {{ - {fromType} i = default({fromType}); - i.$$ - }} -}} -", SourceCodeKind.Regular); + var items = await GetCompletionItemsAsync($$""" + public class Program + { + public static void Main() + { + {{fromType}} i = default({{fromType}}); + i.$$ + } + } + """, SourceCodeKind.Regular); AssertEx.SetEqual(items.Select(i => i.DisplayText), toTypes); } @@ -471,8 +451,10 @@ await VerifyItemExistsAsync(Markup, "byte", displayTextPrefix: "(", displayTextS glyph: Glyph.OperatorPublic, matchingFilters: [FilterSet.OperatorFilter], expectedDescriptionOrNull: -$@"int.explicit operator byte(int value) -{(FormatExplicitConversionDescription(fromType: "int", toType: "byte"))}"); + $""" + int.explicit operator byte(int value) + {(FormatExplicitConversionDescription(fromType: "int", toType: "byte"))} + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] @@ -492,8 +474,10 @@ await VerifyItemExistsAsync(Markup, "byte?", displayTextPrefix: "(", displayText glyph: Glyph.OperatorPublic, matchingFilters: [FilterSet.OperatorFilter], expectedDescriptionOrNull: -$@"int.explicit operator byte?(int? value) -{(FormatExplicitConversionDescription(fromType: "int", toType: "byte"))}"); + $""" + int.explicit operator byte?(int? value) + {(FormatExplicitConversionDescription(fromType: "int", toType: "byte"))} + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] @@ -534,8 +518,10 @@ await VerifyItemExistsAsync(Markup, "int", displayTextPrefix: "(", displayTextSu glyph: Glyph.OperatorPublic, matchingFilters: [FilterSet.OperatorFilter], expectedDescriptionOrNull: -$@"E.explicit operator int(E value) -{FormatExplicitConversionDescription("E", "int")}"); + $""" + E.explicit operator int(E value) + {FormatExplicitConversionDescription("E", "int")} + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] @@ -556,8 +542,10 @@ await VerifyItemExistsAsync(Markup, "int?", displayTextPrefix: "(", displayTextS glyph: Glyph.OperatorPublic, matchingFilters: [FilterSet.OperatorFilter], expectedDescriptionOrNull: -$@"E.explicit operator int?(E? value) -{(FormatExplicitConversionDescription(fromType: "E", toType: "int"))}"); + $""" + E.explicit operator int?(E? value) + {(FormatExplicitConversionDescription(fromType: "E", toType: "int"))} + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] @@ -584,8 +572,10 @@ await VerifyItemExistsAsync(Markup, "int", displayTextPrefix: "(", displayTextSu glyph: Glyph.OperatorPublic, matchingFilters: [FilterSet.OperatorFilter], expectedDescriptionOrNull: -@$"B.E.explicit operator int(B.E value) -{FormatExplicitConversionDescription("B.E", "int")}"); + $""" + B.E.explicit operator int(B.E value) + {FormatExplicitConversionDescription("B.E", "int")} + """); } [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] @@ -599,24 +589,22 @@ public async Task ExplicitBuiltInEnumConversionToIntAreOffered(string expression Func verifyFunc = conversionIsOffered ? markup => VerifyItemExistsAsync(markup, "int", displayTextPrefix: "(", displayTextSuffix: ")") : markup => VerifyNoItemsExistAsync(markup); - await verifyFunc(@$" -public enum E {{ One }} -public class Program -{{ - public static void Main() - {{ - var e = E.One; - {expression} - }} -}} -"); + await verifyFunc($$""" + public enum E { One } + public class Program + { + public static void Main() + { + var e = E.One; + {{expression}} + } + } + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task ExplicitUserDefinedConversionInheritedConversions() - { - // Base class lookup rule: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/conversions#processing-of-user-defined-explicit-conversions - await VerifyItemExistsAsync(""" + public Task ExplicitUserDefinedConversionInheritedConversions() + => VerifyItemExistsAsync(""" public class Base { public static explicit operator int(Base b) => 0; } @@ -632,25 +620,22 @@ public static void Main() } } """, "int", displayTextPrefix: "(", displayTextSuffix: ")", glyph: Glyph.OperatorPublic, matchingFilters: [FilterSet.OperatorFilter]); - } [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] [InlineData("C", "byte")] [InlineData("byte", "C")] - public async Task ExplicitBuiltinConversionWithAlias(string fromType, string expected) - { - await VerifyItemExistsAsync(@$" -using C = System.Char; -public class Program -{{ - public static void Main() - {{ - var test = new {fromType}(); - var i = test.$$ - }} -}} -", expected, displayTextPrefix: "(", displayTextSuffix: ")", glyph: Glyph.OperatorPublic, matchingFilters: [FilterSet.OperatorFilter]); - } + public Task ExplicitBuiltinConversionWithAlias(string fromType, string expected) + => VerifyItemExistsAsync($$""" + using C = System.Char; + public class Program + { + public static void Main() + { + var test = new {{fromType}}(); + var i = test.$$ + } + } + """, expected, displayTextPrefix: "(", displayTextSuffix: ")", glyph: Glyph.OperatorPublic, matchingFilters: [FilterSet.OperatorFilter]); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] public async Task TestEditorBrowsableOnConversionIsRespected_EditorBrowsableStateNever() @@ -826,9 +811,8 @@ await VerifyItemInEditorBrowsableContextsAsync( } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task ExplicitUserDefinedConversionOfDerefenrencedPointerIsNotOffered() - { - await VerifyNoItemsExistAsync(""" + public Task ExplicitUserDefinedConversionOfDerefenrencedPointerIsNotOffered() + => VerifyNoItemsExistAsync(""" public struct S { public static explicit operator int(S s) => 0; } @@ -844,5 +828,4 @@ public static void Main() } } """); - } } diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/CrefCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/CrefCompletionProviderTests.cs index 22a46e81f0bc6..cc8c3166295af 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/CrefCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/CrefCompletionProviderTests.cs @@ -59,9 +59,8 @@ await VerifyAtEndOfFile_ItemPartiallyWrittenAsync( } [Fact] - public async Task NameCref() - { - var text = """ + public Task NameCref() + => VerifyItemExistsAsync(""" using System; namespace Goo { @@ -70,14 +69,11 @@ class Program { } } - """; - await VerifyItemExistsAsync(text, "AccessViolationException"); - } + """, "AccessViolationException"); [Fact] - public async Task QualifiedCref() - { - var text = """ + public Task QualifiedCref() + => VerifyItemExistsAsync(""" using System; namespace Goo { @@ -88,9 +84,7 @@ class Program void goo() { } } } - """; - await VerifyItemExistsAsync(text, "goo"); - } + """, "goo"); [Fact] public async Task CrefArgumentList() @@ -112,9 +106,8 @@ void goo(int i) { } } [Fact] - public async Task CrefTypeParameterInArgumentList() - { - var text = """ + public Task CrefTypeParameterInArgumentList() + => VerifyItemExistsAsync(""" using System; namespace Goo { @@ -125,14 +118,11 @@ class Program void goo(T i) { } } } - """; - await VerifyItemExistsAsync(text, "Q"); - } + """, "Q"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530887")] - public async Task PrivateMember() - { - var text = """ + public Task PrivateMember() + => VerifyItemExistsAsync(""" using System; namespace Goo { @@ -147,14 +137,11 @@ class C public int Public; } } - """; - await VerifyItemExistsAsync(text, "Private"); - } + """, "Private"); [Fact] - public async Task AfterSingleQuote() - { - var text = """ + public Task AfterSingleQuote() + => VerifyItemExistsAsync(""" using System; namespace Goo { @@ -163,20 +150,15 @@ class Program { } } - """; - await VerifyItemExistsAsync(text, "Exception"); - } + """, "Exception"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531315")] - public async Task EscapePredefinedTypeName() - { - var text = """ + public Task EscapePredefinedTypeName() + => VerifyItemExistsAsync(""" using System; /// class @void { } - """; - await VerifyItemExistsAsync(text, "@void"); - } + """, "@void"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598159")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531345")] @@ -197,9 +179,8 @@ void M(T x) { } } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531345")] - public async Task ShowTypeParameterNames() - { - var text = """ + public Task ShowTypeParameterNames() + => VerifyItemExistsAsync(""" /// class C { @@ -207,9 +188,7 @@ void M(int x) { } void M(long x) { } void M(string x) { } } - """; - await VerifyItemExistsAsync(text, "C{TGoo}"); - } + """, "C{TGoo}"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531156")] public async Task ShowConstructors() @@ -233,9 +212,8 @@ public C(T x) { } } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598679")] - public async Task NoParamsModifier() - { - var text = """ + public Task NoParamsModifier() + => VerifyItemExistsAsync(""" /// /// /// @@ -244,37 +222,27 @@ class C void M(int x) { } void M(params long[] x) { } } - """; - await VerifyItemExistsAsync(text, "M(long[])"); - } + """, "M(long[])"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/607773")] - public async Task UnqualifiedTypes() - { - var text = """ + public Task UnqualifiedTypes() + => VerifyItemExistsAsync(""" using System.Collections.Generic; /// class C { } - """; - await VerifyItemExistsAsync(text, "Enumerator"); - } + """, "Enumerator"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/607773")] - public async Task CommitUnqualifiedTypes() - { - var text = """ + public Task CommitUnqualifiedTypes() + => VerifyProviderCommitAsync(""" using System.Collections.Generic; /// class C { } - """; - - var expected = """ + """, "Enumerator", """ using System.Collections.Generic; /// class C { } - """; - await VerifyProviderCommitAsync(text, "Enumerator", expected, ' '); - } + """, ' '); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/642285")] public async Task SuggestOperators() @@ -308,9 +276,8 @@ public static bool operator false(Test t) } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/641096")] - public async Task SuggestIndexers() - { - var text = """ + public Task SuggestIndexers() + => VerifyItemExistsAsync(""" /// class Program { @@ -321,26 +288,19 @@ public int this[int i] get { return arr[i]; } } } - """; - await VerifyItemExistsAsync(text, "this[int]"); - } + """, "this[int]"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531315")] - public async Task CommitEscapedPredefinedTypeName() - { - var text = """ + public Task CommitEscapedPredefinedTypeName() + => VerifyProviderCommitAsync(""" using System; /// class @void { } - """; - - var expected = """ + """, "@void", """ using System; /// class @void { } - """; - await VerifyProviderCommitAsync(text, "@void", expected, ' '); - } + """, ' '); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598159")] public async Task RefOutModifiers() @@ -391,44 +351,34 @@ static void Main(string[] args) } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730338")] - public async Task PermitTypingTypeParameters() - { - var text = """ + public Task PermitTypingTypeParameters() + => VerifyProviderCommitAsync(""" using System.Collections.Generic; /// class C { } - """; - - var expected = """ + """, "List{T}", """ using System.Collections.Generic; /// class C { } - """; - await VerifyProviderCommitAsync(text, "List{T}", expected, '{'); - } + """, '{'); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730338")] - public async Task PermitTypingParameterTypes() - { - var text = """ + public Task PermitTypingParameterTypes() + => VerifyProviderCommitAsync(""" using System.Collections.Generic; /// class C { public void goo(int x) { } } - """; - - var expected = """ + """, "goo(int)", """ using System.Collections.Generic; /// class C { public void goo(int x) { } } - """; - await VerifyProviderCommitAsync(text, "goo(int)", expected, '('); - } + """, '('); [Fact] public async Task CrefCompletionSpeculatesOutsideTrivia() @@ -479,54 +429,41 @@ public void goo(int x) { } } [Fact] - public async Task NoSuggestionAfterEmptyCref() - { - var text = """ + public Task NoSuggestionAfterEmptyCref() + => VerifyNoItemsExistAsync(""" using System; /// VerifyItemExistsAsync(""" using System; class C { /// VerifyItemExistsAsync($$""" using System; class C { /// VerifyItemExistsAsync(""" class C { /// @@ -534,15 +471,11 @@ class C /// public void M((string, int) stringAndInt) { } } - """; - - await VerifyItemExistsAsync(text, "M(ValueTuple{string, int})"); - } + """, "M(ValueTuple{string, int})"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22626")] - public async Task ValueTuple2() - { - var text = """ + public Task ValueTuple2() + => VerifyItemExistsAsync(""" class C { /// @@ -550,15 +483,11 @@ class C /// public void M((string s, int i) stringAndInt) { } } - """; - - await VerifyItemExistsAsync(text, "M(ValueTuple{string, int})"); - } + """, "M(ValueTuple{string, int})"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43139")] - public async Task TestNonOverload1() - { - var text = """ + public Task TestNonOverload1() + => VerifyItemExistsAsync(""" class C { /// @@ -568,15 +497,11 @@ public void M() { } void Dispose() { } } - """; - - await VerifyItemExistsAsync(text, "Dispose"); - } + """, "Dispose"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43139")] - public async Task TestNonOverload2() - { - var text = """ + public Task TestNonOverload2() + => VerifyItemExistsAsync(""" class C { /// @@ -586,10 +511,7 @@ public void M() { } void Dispose() { } } - """; - - await VerifyItemExistsAsync(text, "Dispose"); - } + """, "Dispose"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43139")] public async Task TestOverload1() diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/DeclarationNameCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/DeclarationNameCompletionProviderTests.cs index e0960c046f70e..e4464bfd1b295 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/DeclarationNameCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/DeclarationNameCompletionProviderTests.cs @@ -335,32 +335,26 @@ internal override Type GetCompletionProviderType() [InlineData("record")] [InlineData("record class")] [InlineData("record struct")] - public async Task TreatRecordPositionalParameterAsProperty(string record) - { - var markup = $$""" + public Task TreatRecordPositionalParameterAsProperty(string record) + => VerifyItemExistsAsync($$""" public class MyClass { } public {{record}} R(MyClass $$ - """; - await VerifyItemExistsAsync(markup, "MyClass", glyph: Glyph.PropertyPublic); - } + """, "MyClass", glyph: Glyph.PropertyPublic); [Theory] [InlineData("class")] [InlineData("struct")] - public async Task DoNotTreatPrimaryConstructorParameterAsProperty(string record) - { - var markup = $$""" + public Task DoNotTreatPrimaryConstructorParameterAsProperty(string record) + => VerifyItemIsAbsentAsync($$""" public class MyClass { } public {{record}} R(MyClass $$ - """; - await VerifyItemIsAbsentAsync(markup, "MyClass"); - } + """, "MyClass"); [Fact] public async Task NameWithOnlyType1() @@ -377,29 +371,23 @@ public class MyClass } [Fact] - public async Task AsyncTaskOfT() - { - var markup = """ + public Task AsyncTaskOfT() + => VerifyItemExistsAsync(""" using System.Threading.Tasks; public class C { async Task $$ } - """; - await VerifyItemExistsAsync(markup, "GetCAsync"); - } + """, "GetCAsync"); [Fact(Skip = "not yet implemented")] - public async Task NonAsyncTaskOfT() - { - var markup = """ + public Task NonAsyncTaskOfT() + => VerifyItemExistsAsync(""" public class C { Task $$ } - """; - await VerifyItemExistsAsync(markup, "GetCAsync"); - } + """, "GetCAsync"); [Fact] public async Task MethodDeclaration1() @@ -431,43 +419,34 @@ public class C } [Fact] - public async Task WordBreaking2() - { - var markup = """ + public Task WordBreaking2() + => VerifyItemExistsAsync(""" interface I {} public class C { I $$ } - """; - await VerifyItemExistsAsync(markup, "GetI"); - } + """, "GetI"); [Fact] - public async Task WordBreaking3() - { - var markup = """ + public Task WordBreaking3() + => VerifyItemExistsAsync(""" interface II {} public class C { II $$ } - """; - await VerifyItemExistsAsync(markup, "GetI"); - } + """, "GetI"); [Fact] - public async Task WordBreaking4() - { - var markup = """ + public Task WordBreaking4() + => VerifyItemExistsAsync(""" interface IGoo {} public class C { IGoo $$ } - """; - await VerifyItemExistsAsync(markup, "Goo"); - } + """, "Goo"); [Fact] public async Task WordBreaking5() @@ -491,121 +470,94 @@ public class C } [Fact] - public async Task Parameter1() - { - var markup = """ + public Task Parameter1() + => VerifyItemExistsAsync(""" using System.Threading; public class C { void Goo(CancellationToken $$ } - """; - await VerifyItemExistsAsync(markup, "cancellationToken", glyph: Glyph.Parameter); - } + """, "cancellationToken", glyph: Glyph.Parameter); [Fact] - public async Task Parameter2() - { - var markup = """ + public Task Parameter2() + => VerifyItemExistsAsync(""" using System.Threading; public class C { void Goo(int x, CancellationToken c$$ } - """; - await VerifyItemExistsAsync(markup, "cancellationToken", glyph: Glyph.Parameter); - } + """, "cancellationToken", glyph: Glyph.Parameter); [Fact] - public async Task Parameter3() - { - var markup = """ + public Task Parameter3() + => VerifyItemExistsAsync(""" using System.Threading; public class C { void Goo(CancellationToken c$$) {} } - """; - await VerifyItemExistsAsync(markup, "cancellationToken", glyph: Glyph.Parameter); - } + """, "cancellationToken", glyph: Glyph.Parameter); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45492")] - public async Task Parameter4() - { - var markup = """ + public Task Parameter4() + => VerifyItemExistsAsync(""" using System.Threading; public class C { void Other(CancellationToken cancellationToken) {} void Goo(CancellationToken c$$) {} } - """; - await VerifyItemExistsAsync(markup, "cancellationToken", glyph: Glyph.Parameter); - } + """, "cancellationToken", glyph: Glyph.Parameter); [Fact] - public async Task Parameter5() - { - var markup = """ + public Task Parameter5() + => VerifyItemExistsAsync(""" using System.Threading; public class C { void Goo(CancellationToken cancellationToken, CancellationToken c$$) {} } - """; - await VerifyItemExistsAsync(markup, "cancellationToken1", glyph: Glyph.Parameter); - } + """, "cancellationToken1", glyph: Glyph.Parameter); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45492")] - public async Task Parameter6() - { - var markup = """ + public Task Parameter6() + => VerifyItemExistsAsync(""" using System.Threading; void Other(CancellationToken cancellationToken) {} void Goo(CancellationToken c$$) {} - """; - await VerifyItemExistsAsync(markup, "cancellationToken", glyph: Glyph.Parameter); - } + """, "cancellationToken", glyph: Glyph.Parameter); [Fact] - public async Task Parameter7() - { - var markup = """ + public Task Parameter7() + => VerifyItemExistsAsync(""" using System.Threading; void Goo(CancellationToken cancellationToken, CancellationToken c$$) {} - """; - await VerifyItemExistsAsync(markup, "cancellationToken1", glyph: Glyph.Parameter); - } + """, "cancellationToken1", glyph: Glyph.Parameter); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45492")] - public async Task Parameter8() - { - var markup = """ + public Task Parameter8() + => VerifyItemExistsAsync(""" using System.Threading; public class C { int this[CancellationToken cancellationToken] => throw null; int this[CancellationToken c$$] => throw null; } - """; - await VerifyItemExistsAsync(markup, "cancellationToken", glyph: Glyph.Parameter); - } + """, "cancellationToken", glyph: Glyph.Parameter); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45492")] - public async Task Parameter9() - { - var markup = """ + public Task Parameter9() + => VerifyItemExistsAsync(""" using System.Threading; public class C { int this[CancellationToken cancellationToken] => throw null; int this[CancellationToken cancellationToken, CancellationToken c$$] => throw null; } - """; - await VerifyItemExistsAsync(markup, "cancellationToken1", glyph: Glyph.Parameter); - } + """, "cancellationToken1", glyph: Glyph.Parameter); [InlineData(LanguageVersion.CSharp7)] [InlineData(LanguageVersion.CSharp8)] @@ -755,16 +707,13 @@ public C(string firstName, string $$) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52534")] - public async Task DoNotSuggestParameterNamesFromTheSameOverload() - { - var markup = """ + public Task DoNotSuggestParameterNamesFromTheSameOverload() + => VerifyItemIsAbsentAsync(""" public class C { void M(string name, string $$) { } } - """; - await VerifyItemIsAbsentAsync(markup, "name"); - } + """, "name"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52534")] public async Task DoNotSuggestParameterNamesFromNonOverloads() @@ -783,9 +732,8 @@ void M2(CancellationToken $$ } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52534")] - public async Task DoNotSuggestInGenericType() - { - var markup = """ + public Task DoNotSuggestInGenericType() + => VerifyNoItemsExistAsync(""" using System.Collections.Generic; public class C { @@ -793,14 +741,11 @@ void M(IEnumerable numbers) { } void M(List<$$>) { } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52534")] - public async Task DoNotSuggestInOptionalParameterDefaultValue() - { - var markup = """ + public Task DoNotSuggestInOptionalParameterDefaultValue() + => VerifyNoItemsExistAsync(""" using System.Collections.Generic; public class C { @@ -809,9 +754,7 @@ void M(int num = ZERO) { } void M(int x, int num = $$) { } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19260")] public async Task EscapeKeywords1() @@ -829,22 +772,18 @@ void Goo(StringBuilder $$) {} } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19260")] - public async Task EscapeKeywords2() - { - var markup = """ + public Task EscapeKeywords2() + => VerifyItemExistsAsync(""" class For { } public class C { void Goo(For $$) {} } - """; - await VerifyItemExistsAsync(markup, "@for", glyph: Glyph.Parameter); - } + """, "@for", glyph: Glyph.Parameter); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19260")] - public async Task EscapeKeywords3() - { - var markup = """ + public Task EscapeKeywords3() + => VerifyItemExistsAsync(""" class For { } public class C { @@ -853,9 +792,7 @@ void goo() For $$ } } - """; - await VerifyItemExistsAsync(markup, "@for"); - } + """, "@for"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19260")] public async Task EscapeKeywords4() @@ -914,172 +851,133 @@ public class Item { } } [Fact] - public async Task NoSuggestionsForInt() - { - var markup = """ + public Task NoSuggestionsForInt() + => VerifyNoItemsExistAsync(""" using System.Threading; public class C { int $$ } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task NoSuggestionsForLong() - { - var markup = """ + public Task NoSuggestionsForLong() + => VerifyNoItemsExistAsync(""" using System.Threading; public class C { long $$ } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task NoSuggestionsForDouble() - { - var markup = """ + public Task NoSuggestionsForDouble() + => VerifyNoItemsExistAsync(""" using System.Threading; public class C { double $$ } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task NoSuggestionsForFloat() - { - var markup = """ + public Task NoSuggestionsForFloat() + => VerifyNoItemsExistAsync(""" using System.Threading; public class C { float $$ } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task NoSuggestionsForSbyte() - { - var markup = """ + public Task NoSuggestionsForSbyte() + => VerifyNoItemsExistAsync(""" using System.Threading; public class C { sbyte $$ } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task NoSuggestionsForShort() - { - var markup = """ + public Task NoSuggestionsForShort() + => VerifyNoItemsExistAsync(""" using System.Threading; public class C { short $$ } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task NoSuggestionsForUint() - { - var markup = """ + public Task NoSuggestionsForUint() + => VerifyNoItemsExistAsync(""" using System.Threading; public class C { uint $$ } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task NoSuggestionsForUlong() - { - var markup = """ + public Task NoSuggestionsForUlong() + => VerifyNoItemsExistAsync(""" using System.Threading; public class C { ulong $$ } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task SuggestionsForUShort() - { - var markup = """ + public Task SuggestionsForUShort() + => VerifyNoItemsExistAsync(""" using System.Threading; public class C { ushort $$ } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task NoSuggestionsForBool() - { - var markup = """ + public Task NoSuggestionsForBool() + => VerifyNoItemsExistAsync(""" using System.Threading; public class C { bool $$ } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task NoSuggestionsForByte() - { - var markup = """ + public Task NoSuggestionsForByte() + => VerifyNoItemsExistAsync(""" using System.Threading; public class C { byte $$ } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task NoSuggestionsForChar() - { - var markup = """ + public Task NoSuggestionsForChar() + => VerifyNoItemsExistAsync(""" using System.Threading; public class C { char $$ } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task NoSuggestionsForString() - { - var markup = """ + public Task NoSuggestionsForString() + => VerifyNoItemsExistAsync(""" public class C { string $$ } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] public async Task NoSingleLetterClassNameSuggested() @@ -1109,45 +1007,35 @@ public class MyClass } [Fact] - public async Task NotTriggeredByVar() - { - var markup = """ + public Task NotTriggeredByVar() + => VerifyNoItemsExistAsync(""" public class C { var $$ } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task NotAfterVoid() - { - var markup = """ + public Task NotAfterVoid() + => VerifyNoItemsExistAsync(""" public class C { void $$ } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task AfterGeneric() - { - var markup = """ + public Task AfterGeneric() + => VerifyItemExistsAsync(""" public class C { System.Collections.Generic.IEnumerable $$ } - """; - await VerifyItemExistsAsync(markup, "GetCs"); - } + """, "GetCs"); [Fact] - public async Task NothingAfterVar() - { - var markup = """ + public Task NothingAfterVar() + => VerifyNoItemsExistAsync(""" public class C { void goo() @@ -1155,9 +1043,7 @@ void goo() var $$ } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] public async Task TestCorrectOrder() @@ -1235,35 +1121,28 @@ public class C } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20016")] - public async Task NotAfterExistingName1() - { - var markup = """ + public Task NotAfterExistingName1() + => VerifyNoItemsExistAsync(""" using IMyType = System.String; public class C { MyType myType $$ } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20016")] - public async Task NotAfterExistingName2() - { - var markup = """ + public Task NotAfterExistingName2() + => VerifyNoItemsExistAsync(""" using IMyType = System.String; public class C { MyType myType, MyType $$ } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19409")] - public async Task OutVarArgument() - { - var markup = """ + public Task OutVarArgument() + => VerifyItemExistsAsync(""" class Test { void Do(out Test goo) @@ -1271,14 +1150,11 @@ void Do(out Test goo) Do(out var $$ } } - """; - await VerifyItemExistsAsync(markup, "test"); - } + """, "test"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19409")] - public async Task OutArgument() - { - var markup = """ + public Task OutArgument() + => VerifyItemExistsAsync(""" class Test { void Do(out Test goo) @@ -1286,14 +1162,11 @@ void Do(out Test goo) Do(out Test $$ } } - """; - await VerifyItemExistsAsync(markup, "test"); - } + """, "test"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19409")] - public async Task OutGenericArgument() - { - var markup = """ + public Task OutGenericArgument() + => VerifyItemExistsAsync(""" class Test { void Do(out T goo) @@ -1301,14 +1174,11 @@ void Do(out T goo) Do(out Test $$ } } - """; - await VerifyItemExistsAsync(markup, "test"); - } + """, "test"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22342")] - public async Task TupleExpressionDeclaration1() - { - var markup = """ + public Task TupleExpressionDeclaration1() + => VerifyItemExistsAsync(""" class Test { void Do() @@ -1316,14 +1186,11 @@ void Do() (System.Array array, System.Action $$ } } - """; - await VerifyItemExistsAsync(markup, "action"); - } + """, "action"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22342")] - public async Task TupleExpressionDeclaration2() - { - var markup = """ + public Task TupleExpressionDeclaration2() + => VerifyItemIsAbsentAsync(""" class Test { void Do() @@ -1331,14 +1198,11 @@ void Do() (array, action $$ } } - """; - await VerifyItemIsAbsentAsync(markup, "action"); - } + """, "action"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22342")] - public async Task TupleExpressionDeclaration_NestedTuples() - { - var markup = """ + public Task TupleExpressionDeclaration_NestedTuples() + => VerifyItemExistsAsync(""" class Test { void Do() @@ -1346,14 +1210,11 @@ void Do() ((int i1, int i2), (System.Array array, System.Action $$ } } - """; - await VerifyItemExistsAsync(markup, "action"); - } + """, "action"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22342")] - public async Task TupleExpressionDeclaration_NestedTuples_CompletionInTheMiddle() - { - var markup = """ + public Task TupleExpressionDeclaration_NestedTuples_CompletionInTheMiddle() + => VerifyItemExistsAsync(""" class Test { void Do() @@ -1361,14 +1222,11 @@ void Do() ((System.Array array, System.Action $$), (int i1, int i2)) } } - """; - await VerifyItemExistsAsync(markup, "action"); - } + """, "action"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22342")] - public async Task TupleElementDefinition1() - { - var markup = """ + public Task TupleElementDefinition1() + => VerifyItemExistsAsync(""" class Test { void Do() @@ -1376,86 +1234,65 @@ void Do() (System.Array $$ } } - """; - await VerifyItemExistsAsync(markup, "array"); - } + """, "array"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22342")] - public async Task TupleElementDefinition2() - { - var markup = """ + public Task TupleElementDefinition2() + => VerifyItemExistsAsync(""" class Test { (System.Array $$) Test() => default; } - """; - await VerifyItemExistsAsync(markup, "array"); - } + """, "array"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22342")] - public async Task TupleElementDefinition3() - { - var markup = """ + public Task TupleElementDefinition3() + => VerifyItemExistsAsync(""" class Test { (System.Array array, System.Action $$) Test() => default; } - """; - await VerifyItemExistsAsync(markup, "action"); - } + """, "action"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22342")] - public async Task TupleElementDefinition4() - { - var markup = """ + public Task TupleElementDefinition4() + => VerifyItemExistsAsync(""" class Test { (System.Array $$ } - """; - await VerifyItemExistsAsync(markup, "array"); - } + """, "array"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22342")] - public async Task TupleElementDefinition5() - { - var markup = """ + public Task TupleElementDefinition5() + => VerifyItemExistsAsync(""" class Test { void M((System.Array $$ } - """; - await VerifyItemExistsAsync(markup, "array"); - } + """, "array"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22342")] - public async Task TupleElementDefinition_NestedTuples() - { - var markup = """ + public Task TupleElementDefinition_NestedTuples() + => VerifyItemExistsAsync(""" class Test { void M(((int, int), (int, System.Array $$ } - """; - await VerifyItemExistsAsync(markup, "array"); - } + """, "array"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22342")] - public async Task TupleElementDefinition_InMiddleOfTuple() - { - var markup = """ + public Task TupleElementDefinition_InMiddleOfTuple() + => VerifyItemExistsAsync(""" class Test { void M((int, System.Array $$),int) } - """; - await VerifyItemExistsAsync(markup, "array"); - } + """, "array"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22342")] - public async Task TupleElementTypeInference() - { - var markup = """ + public Task TupleElementTypeInference() + => VerifyItemIsAbsentAsync(""" class Test { void Do() @@ -1463,19 +1300,12 @@ void Do() (var accessViolationException, var $$) = (new AccessViolationException(), new Action(() => { })); } } - """; - // Currently not supported: - await VerifyItemIsAbsentAsync(markup, "action"); - // see https://github.com/dotnet/roslyn/issues/27138 - // after the issue ist fixed we expect this to work: - // await VerifyItemExistsAsync(markup, "action"); - } + """, "action"); [Fact(Skip = "Not yet supported")] [WorkItem("https://github.com/dotnet/roslyn/issues/22342")] - public async Task TupleElementInGenericTypeArgument() - { - var markup = """ + public Task TupleElementInGenericTypeArgument() + => VerifyItemExistsAsync(""" class Test { void Do() @@ -1483,14 +1313,11 @@ void Do() System.Func<(System.Action $$ } } - """; - await VerifyItemExistsAsync(markup, "action"); - } + """, "action"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22342")] - public async Task TupleElementInvocationInsideTuple() - { - var markup = """ + public Task TupleElementInvocationInsideTuple() + => VerifyNoItemsExistAsync(""" class Test { void Do() @@ -1499,35 +1326,27 @@ void Do() var t=(e1: 1, e2: M(1, $$)); } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17987")] - public async Task Pluralize1() - { - var markup = """ + public Task Pluralize1() + => VerifyItemExistsAsync(""" using System.Collections.Generic; class Index { IEnumerable $$ } - """; - await VerifyItemExistsAsync(markup, "Indices"); - } + """, "Indices"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17987")] - public async Task Pluralize2() - { - var markup = """ + public Task Pluralize2() + => VerifyItemExistsAsync(""" using System.Collections.Generic; class Test { IEnumerable> $$ } - """; - await VerifyItemExistsAsync(markup, "tests"); - } + """, "tests"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17987")] public async Task Pluralize3() @@ -1592,9 +1411,8 @@ void M(Span $$) { } } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37366")] - public async Task PluralizeValidGetEnumerator() - { - var markup = """ + public Task PluralizeValidGetEnumerator() + => VerifyItemExistsAsync(""" class MyClass { public void M(MyOwnCollection $$) { } @@ -1615,14 +1433,11 @@ public class MyEnumerator public bool MoveNext() { return false; } } } - """; - await VerifyItemExistsAsync(markup, "myClasses"); - } + """, "myClasses"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37366")] - public async Task PluralizeValidGetAsyncEnumerator() - { - var markup = """ + public Task PluralizeValidGetAsyncEnumerator() + => VerifyItemExistsAsync(""" using System.Threading.Tasks; class MyClass @@ -1645,14 +1460,11 @@ public class MyEnumerator public Task MoveNextAsync() { return Task.FromResult(false); } } } - """; - await VerifyItemExistsAsync(markup, "myClasses"); - } + """, "myClasses"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37366")] - public async Task PluralizeForUnimplementedIEnumerable() - { - var markup = """ + public Task PluralizeForUnimplementedIEnumerable() + => VerifyItemExistsAsync(""" using System.Collections.Generic; class MyClass @@ -1664,9 +1476,7 @@ public void M(MyOwnCollection $$) { } class MyOwnCollection : IEnumerable { } - """; - await VerifyItemExistsAsync(markup, "myClasses"); - } + """, "myClasses"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37366")] public async Task PluralizeForUnimplementedIAsyncEnumerable() @@ -1811,9 +1621,8 @@ public static void Main() } [Fact] - public async Task InUsingStatement1() - { - var markup = """ + public Task InUsingStatement1() + => VerifyItemExistsAsync(""" using System.IO; class C @@ -1823,14 +1632,11 @@ void M() using (StreamReader s$$ } } - """; - await VerifyItemExistsAsync(markup, "streamReader"); - } + """, "streamReader"); [Fact] - public async Task InUsingStatement2() - { - var markup = """ + public Task InUsingStatement2() + => VerifyItemExistsAsync(""" using System.IO; class C @@ -1840,14 +1646,11 @@ void M() using (StreamReader s1, $$ } } - """; - await VerifyItemExistsAsync(markup, "streamReader"); - } + """, "streamReader"); [Fact] - public async Task InUsingStatement_Var() - { - var markup = """ + public Task InUsingStatement_Var() + => VerifyItemExistsAsync(""" using System.IO; class C @@ -1857,14 +1660,11 @@ void M() using (var m$$ = new MemoryStream()) } } - """; - await VerifyItemExistsAsync(markup, "memoryStream"); - } + """, "memoryStream"); [Fact] - public async Task InForStatement1() - { - var markup = """ + public Task InForStatement1() + => VerifyItemExistsAsync(""" using System.IO; class C @@ -1874,14 +1674,11 @@ void M() for (StreamReader s$$ } } - """; - await VerifyItemExistsAsync(markup, "streamReader"); - } + """, "streamReader"); [Fact] - public async Task InForStatement2() - { - var markup = """ + public Task InForStatement2() + => VerifyItemIsAbsentAsync(""" using System.IO; class C @@ -1891,14 +1688,11 @@ void M() for (StreamReader s1, $$ } } - """; - await VerifyItemIsAbsentAsync(markup, "streamReader"); - } + """, "streamReader"); [Fact] - public async Task InForStatement_Var() - { - var markup = """ + public Task InForStatement_Var() + => VerifyItemExistsAsync(""" using System.IO; class C @@ -1908,14 +1702,11 @@ void M() for (var m$$ = new MemoryStream(); } } - """; - await VerifyItemExistsAsync(markup, "memoryStream"); - } + """, "memoryStream"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26021")] - public async Task InForEachStatement() - { - var markup = """ + public Task InForEachStatement() + => VerifyItemExistsAsync(""" using System.IO; class C @@ -1925,14 +1716,11 @@ void M() foreach (StreamReader $$ } } - """; - await VerifyItemExistsAsync(markup, "streamReader"); - } + """, "streamReader"); [Fact] - public async Task InForEachStatement_Var() - { - var markup = """ + public Task InForEachStatement_Var() + => VerifyItemExistsAsync(""" using System.IO; class C @@ -1942,28 +1730,23 @@ void M() foreach (var m$$ in new[] { new MemoryStream() }) } } - """; - await VerifyItemExistsAsync(markup, "memoryStream"); - } + """, "memoryStream"); [Fact] public async Task DisabledByOption() { ShowNameSuggestions = false; - - var markup = """ + await VerifyNoItemsExistAsync(""" class Test { Test $$ } - """; - await VerifyNoItemsExistAsync(markup); + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23590")] - public async Task TypeImplementsIEnumerableOfType() - { - var markup = """ + public Task TypeImplementsIEnumerableOfType() + => VerifyItemExistsAsync(""" using System.Collections.Generic; public class Class1 @@ -1976,14 +1759,11 @@ public void Method() public class Container : ContainerBase { } public class ContainerBase : IEnumerable { } - """; - await VerifyItemExistsAsync(markup, "container"); - } + """, "container"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23590")] - public async Task TypeImplementsIEnumerableOfType2() - { - var markup = """ + public Task TypeImplementsIEnumerableOfType2() + => VerifyItemExistsAsync(""" using System.Collections.Generic; public class Class1 @@ -1996,14 +1776,11 @@ public void Method() public class ContainerBase : IEnumerable { } public class Container : ContainerBase { } - """; - await VerifyItemExistsAsync(markup, "container"); - } + """, "container"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23590")] - public async Task TypeImplementsIEnumerableOfType3() - { - var markup = """ + public Task TypeImplementsIEnumerableOfType3() + => VerifyItemExistsAsync(""" using System.Collections.Generic; public class Class1 @@ -2015,14 +1792,11 @@ public void Method() } public class Container : IEnumerable { } - """; - await VerifyItemExistsAsync(markup, "container"); - } + """, "container"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23590")] - public async Task TypeImplementsIEnumerableOfType4() - { - var markup = """ + public Task TypeImplementsIEnumerableOfType4() + => VerifyItemExistsAsync(""" using System.Collections.Generic; using System.Threading.Tasks; @@ -2037,14 +1811,11 @@ public void Method() public class ContainerBase : IEnumerable { } public class Container : ContainerBase { } public class TaskType : Task { } - """; - await VerifyItemExistsAsync(markup, "taskType"); - } + """, "taskType"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23590")] - public async Task TypeImplementsTaskOfType() - { - var markup = """ + public Task TypeImplementsTaskOfType() + => VerifyItemExistsAsync(""" using System.Threading.Tasks; public class Class1 @@ -2057,14 +1828,11 @@ public void Method() public class Container : ContainerBase { } public class ContainerBase : Task { } - """; - await VerifyItemExistsAsync(markup, "container"); - } + """, "container"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23590")] - public async Task TypeImplementsTaskOfType2() - { - var markup = """ + public Task TypeImplementsTaskOfType2() + => VerifyItemExistsAsync(""" using System.Threading.Tasks; public class Class1 @@ -2077,14 +1845,11 @@ public void Method() public class Container : Task { } public class ContainerBase : Container { } - """; - await VerifyItemExistsAsync(markup, "container"); - } + """, "container"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23590")] - public async Task TypeImplementsTaskOfType3() - { - var markup = """ + public Task TypeImplementsTaskOfType3() + => VerifyItemExistsAsync(""" using System.Collections.Generic; using System.Threading.Tasks; @@ -2099,14 +1864,11 @@ public void Method() public class TaskType : TaskTypeBase { } public class TaskTypeBase : Task { } public class EnumerableType : IEnumerable { } - """; - await VerifyItemExistsAsync(markup, "taskTypes"); - } + """, "taskTypes"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23590")] - public async Task TypeIsNullableOfNullable() - { - var markup = """ + public Task TypeIsNullableOfNullable() + => VerifyItemExistsAsync(""" using System.Collections.Generic; public class Class1 @@ -2117,15 +1879,12 @@ public void Method() IEnumerable> $$ } } - """; - await VerifyItemExistsAsync(markup, "nullables"); - } + """, "nullables"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36364")] [WorkItem("https://developercommunity2.visualstudio.com/t/Regression-from-1675-Suggested-varia/1220195")] - public async Task TypeIsNullableStructInLocalWithNullableTypeName() - { - var markup = """ + public Task TypeIsNullableStructInLocalWithNullableTypeName() + => VerifyItemExistsAsync(""" using System; public struct ImmutableArray : System.Collections.Generic.IEnumerable { } @@ -2137,15 +1896,12 @@ public void Method() Nullable> $$ } } - """; - await VerifyItemExistsAsync(markup, "ints"); - } + """, "ints"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36364")] [WorkItem("https://developercommunity2.visualstudio.com/t/Regression-from-1675-Suggested-varia/1220195")] - public async Task TypeIsNullableStructInLocalWithQuestionMark() - { - var markup = """ + public Task TypeIsNullableStructInLocalWithQuestionMark() + => VerifyItemExistsAsync(""" using System.Collections.Immutable; public struct ImmutableArray : System.Collections.Generic.IEnumerable { } @@ -2157,15 +1913,12 @@ public void Method() ImmutableArray? $$ } } - """; - await VerifyItemExistsAsync(markup, "ints"); - } + """, "ints"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36364")] [WorkItem("https://developercommunity2.visualstudio.com/t/Regression-from-1675-Suggested-varia/1220195")] - public async Task TypeIsNullableReferenceInLocal() - { - var markup = """ + public Task TypeIsNullableReferenceInLocal() + => VerifyItemExistsAsync(""" #nullable enable using System.Collections.Generic; @@ -2177,15 +1930,12 @@ public void Method() IEnumerable? $$ } } - """; - await VerifyItemExistsAsync(markup, "ints"); - } + """, "ints"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36364")] [WorkItem("https://developercommunity2.visualstudio.com/t/Regression-from-1675-Suggested-varia/1220195")] - public async Task TypeIsNullableStructInParameterWithNullableTypeName() - { - var markup = """ + public Task TypeIsNullableStructInParameterWithNullableTypeName() + => VerifyItemExistsAsync(""" using System; public struct ImmutableArray : System.Collections.Generic.IEnumerable { } @@ -2196,15 +1946,12 @@ public void Method(Nullable> $$) { } } - """; - await VerifyItemExistsAsync(markup, "ints"); - } + """, "ints"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36364")] [WorkItem("https://developercommunity2.visualstudio.com/t/Regression-from-1675-Suggested-varia/1220195")] - public async Task TypeIsNullableStructInParameterWithQuestionMark() - { - var markup = """ + public Task TypeIsNullableStructInParameterWithQuestionMark() + => VerifyItemExistsAsync(""" public struct ImmutableArray : System.Collections.Generic.IEnumerable { } public class Class1 @@ -2213,15 +1960,12 @@ public void Method(ImmutableArray? $$) { } } - """; - await VerifyItemExistsAsync(markup, "ints"); - } + """, "ints"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36364")] [WorkItem("https://developercommunity2.visualstudio.com/t/Regression-from-1675-Suggested-varia/1220195")] - public async Task TypeIsNullableReferenceInParameter() - { - var markup = """ + public Task TypeIsNullableReferenceInParameter() + => VerifyItemExistsAsync(""" #nullable enable using System.Collections.Generic; @@ -2232,14 +1976,11 @@ public void Method(IEnumerable? $$) { } } - """; - await VerifyItemExistsAsync(markup, "ints"); - } + """, "ints"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36364")] - public async Task EnumerableParameterOfUnmanagedType() - { - var markup = """ + public Task EnumerableParameterOfUnmanagedType() + => VerifyItemExistsAsync(""" using System.Collections.Generic; public class Class1 @@ -2248,14 +1989,11 @@ public void Method(IEnumerable $$) { } } - """; - await VerifyItemExistsAsync(markup, "ints"); - } + """, "ints"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36364")] - public async Task EnumerableParameterOfObject() - { - var markup = """ + public Task EnumerableParameterOfObject() + => VerifyItemExistsAsync(""" using System.Collections.Generic; public class Class1 @@ -2264,14 +2002,11 @@ public void Method(IEnumerable $$) { } } - """; - await VerifyItemExistsAsync(markup, "objects"); - } + """, "objects"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36364")] - public async Task EnumerableParameterOfString() - { - var markup = """ + public Task EnumerableParameterOfString() + => VerifyItemExistsAsync(""" using System.Collections.Generic; public class Class1 @@ -2280,14 +2015,11 @@ public void Method(IEnumerable $$) { } } - """; - await VerifyItemExistsAsync(markup, "strings"); - } + """, "strings"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36364")] - public async Task EnumerableGenericTParameter() - { - var markup = """ + public Task EnumerableGenericTParameter() + => VerifyItemExistsAsync(""" using System.Collections.Generic; public class Class1 @@ -2296,14 +2028,11 @@ public void Method(IEnumerable $$) { } } - """; - await VerifyItemExistsAsync(markup, "values"); - } + """, "values"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36364")] - public async Task EnumerableGenericTNameParameter() - { - var markup = """ + public Task EnumerableGenericTNameParameter() + => VerifyItemExistsAsync(""" using System.Collections.Generic; public class Class1 @@ -2312,14 +2041,11 @@ public void Method(IEnumerable $$) { } } - """; - await VerifyItemExistsAsync(markup, "results"); - } + """, "results"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36364")] - public async Task EnumerableGenericUnexpectedlyNamedParameter() - { - var markup = """ + public Task EnumerableGenericUnexpectedlyNamedParameter() + => VerifyItemExistsAsync(""" using System.Collections.Generic; public class Class1 @@ -2328,14 +2054,11 @@ public void Method(IEnumerable $$) { } } - """; - await VerifyItemExistsAsync(markup, "args"); - } + """, "args"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36364")] - public async Task EnumerableGenericUnexpectedlyNamedParameterBeginsWithT() - { - var markup = """ + public Task EnumerableGenericUnexpectedlyNamedParameterBeginsWithT() + => VerifyItemExistsAsync(""" using System.Collections.Generic; public class Class1 @@ -2344,9 +2067,7 @@ public void Method(IEnumerable $$) { } } - """; - await VerifyItemExistsAsync(markup, "types"); - } + """, "types"); [Fact] public async Task CustomNamingStyleInsideClass() @@ -2450,9 +2171,8 @@ await VerifyItemExistsAsync(markup, "classB1", glyph: Glyph.Local, } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31304")] - public async Task TestCompletionCanUsePropertyName() - { - var markup = """ + public Task TestCompletionCanUsePropertyName() + => VerifyItemExistsAsync(""" class ClassA { class ClassB { } @@ -2464,15 +2184,12 @@ void M() ClassB $$ } } - """; - await VerifyItemExistsAsync(markup, "classB", glyph: Glyph.Local, + """, "classB", glyph: Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31304")] - public async Task TestCompletionCanUseFieldName() - { - var markup = """ + public Task TestCompletionCanUseFieldName() + => VerifyItemExistsAsync(""" class ClassA { class ClassB { } @@ -2484,10 +2201,8 @@ void M() ClassB $$ } } - """; - await VerifyItemExistsAsync(markup, "classB", glyph: Glyph.Local, + """, "classB", glyph: Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31304")] public async Task TestCompletionDoesNotUseLocalName() @@ -2555,9 +2270,8 @@ await VerifyItemExistsAsync(markup, "classB1", glyph: Glyph.Local, } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31304")] - public async Task TestCompletionCanUseClassName() - { - var markup = """ + public Task TestCompletionCanUseClassName() + => VerifyItemExistsAsync(""" class classA { void M() @@ -2565,15 +2279,12 @@ void M() classA $$ } } - """; - await VerifyItemExistsAsync(markup, "classA", glyph: Glyph.Local, + """, "classA", glyph: Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31304")] - public async Task TestCompletionCanUseLocalInDifferentScope() - { - var markup = """ + public Task TestCompletionCanUseLocalInDifferentScope() + => VerifyItemExistsAsync(""" class ClassA { class ClassB { } @@ -2588,10 +2299,8 @@ void M2() ClassB $$ } } - """; - await VerifyItemExistsAsync(markup, "classB", glyph: Glyph.Local, + """, "classB", glyph: Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); - } [InlineData(LanguageVersion.CSharp7)] [InlineData(LanguageVersion.CSharp8)] @@ -2650,9 +2359,8 @@ void LocalM1() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35891")] - public async Task TestCompletionDoesNotUseLocalInNestedLocalFunction() - { - var markup = """ + public Task TestCompletionDoesNotUseLocalInNestedLocalFunction() + => VerifyItemIsAbsentAsync(""" class ClassA { class ClassB { } @@ -2668,14 +2376,11 @@ void LocalM2() } } } - """; - await VerifyItemIsAbsentAsync(markup, "classB"); - } + """, "classB"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35891")] - public async Task TestCompletionDoesNotUseLocalFunctionParameterInNestedLocalFunction() - { - var markup = """ + public Task TestCompletionDoesNotUseLocalFunctionParameterInNestedLocalFunction() + => VerifyItemIsAbsentAsync(""" class ClassA { class ClassB { } @@ -2690,14 +2395,11 @@ void LocalM2() } } } - """; - await VerifyItemIsAbsentAsync(markup, "classB"); - } + """, "classB"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35891")] - public async Task TestCompletionCanUseLocalFunctionParameterAsParameter() - { - var markup = """ + public Task TestCompletionCanUseLocalFunctionParameterAsParameter() + => VerifyItemExistsAsync(""" class ClassA { class ClassB { } @@ -2707,15 +2409,12 @@ void LocalM1(ClassB classB) { } void LocalM2(ClassB $$) { } } } - """; - await VerifyItemExistsAsync(markup, "classB", glyph: Glyph.Parameter, + """, "classB", glyph: Glyph.Parameter, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35891")] - public async Task TestCompletionCanUseLocalFunctionVariableAsParameter() - { - var markup = """ + public Task TestCompletionCanUseLocalFunctionVariableAsParameter() + => VerifyItemExistsAsync(""" class ClassA { class ClassB { } @@ -2728,15 +2427,12 @@ ClassB classB void LocalM2(ClassB $$) { } } } - """; - await VerifyItemExistsAsync(markup, "classB", glyph: Glyph.Parameter, + """, "classB", glyph: Glyph.Parameter, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35891")] - public async Task TestCompletionCanUseLocalFunctionParameterAsVariable() - { - var markup = """ + public Task TestCompletionCanUseLocalFunctionParameterAsVariable() + => VerifyItemExistsAsync(""" class ClassA { class ClassB { } @@ -2749,15 +2445,12 @@ void LocalM2() } } } - """; - await VerifyItemExistsAsync(markup, "classB", glyph: Glyph.Local, + """, "classB", glyph: Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35891")] - public async Task TestCompletionCanUseLocalFunctionVariableAsVariable() - { - var markup = """ + public Task TestCompletionCanUseLocalFunctionVariableAsVariable() + => VerifyItemExistsAsync(""" class ClassA { class ClassB { } @@ -2773,10 +2466,8 @@ void LocalM2() } } } - """; - await VerifyItemExistsAsync(markup, "classB", glyph: Glyph.Local, + """, "classB", glyph: Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); - } [Fact] public async Task TestNotForUnboundAsync() @@ -2803,8 +2494,7 @@ public async Task ConflictingLocalVariable() { { NamingStyleOptions.NamingPreferences, MultipleCamelCaseLocalRules() } }); - - var markup = """ + await VerifyItemExistsAsync(""" public class MyClass { void M() @@ -2813,22 +2503,18 @@ void M() MyClass $$ } } - """; - await VerifyItemExistsAsync(markup, "myClass1", glyph: Glyph.Local); + """, "myClass1", glyph: Glyph.Local); } [Fact] - public async Task TestNotForNonTypeSymbol() - { - var markup = """ + public Task TestNotForNonTypeSymbol() + => VerifyItemIsAbsentAsync(""" using System; class C { Console.BackgroundColor $$ } - """; - await VerifyItemIsAbsentAsync(markup, "consoleColor"); - } + """, "consoleColor"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29487")] public async Task TestForOutParam1() @@ -2854,9 +2540,8 @@ void Goo(out CancellationToken interestingName) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43602")] - public async Task TestForOutParam2() - { - var markup = """ + public Task TestForOutParam2() + => VerifyItemExistsAsync(""" class C { void Main() @@ -2864,14 +2549,11 @@ void Main() int.TryParse("", out var $$) } } - """; - await VerifyItemExistsAsync(markup, "result"); - } + """, "result"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49791")] - public async Task TestForErrorType1() - { - var markup = """ + public Task TestForErrorType1() + => VerifyNoItemsExistAsync(""" class C { void Main(string _rootPath) @@ -2880,14 +2562,11 @@ void Main(string _rootPath) _rootPath = null; } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49791")] - public async Task TestForErrorType2() - { - var markup = """ + public Task TestForErrorType2() + => VerifyItemExistsAsync(""" class C { void Main() @@ -2896,14 +2575,11 @@ void Main() Goo = null; } } - """; - await VerifyItemExistsAsync(markup, "goo"); - } + """, "goo"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36352")] - public async Task InferCollectionInErrorCase1() - { - var markup = """ + public Task InferCollectionInErrorCase1() + => VerifyItemExistsAsync(""" class Customer { } class V @@ -2912,14 +2588,11 @@ void M(IEnumerable $$) { } } - """; - await VerifyItemExistsAsync(markup, "customers"); - } + """, "customers"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63943")] - public async Task InferOffOfGenericNameInPattern() - { - var markup = """ + public Task InferOffOfGenericNameInPattern() + => VerifyItemExistsAsync(""" using System.Collections.Generic; class Customer { } @@ -2931,9 +2604,7 @@ void M(object o) if (o is List $$ } } - """; - await VerifyItemExistsAsync(markup, "customers"); - } + """, "customers"); private static NamingStylePreferences MultipleCamelCaseLocalRules() { diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/DeclarationNameCompletionProviderTests_NameDeclarationInfoTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/DeclarationNameCompletionProviderTests_NameDeclarationInfoTests.cs index b0d85e386fdc2..48f3bf6111616 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/DeclarationNameCompletionProviderTests_NameDeclarationInfoTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/DeclarationNameCompletionProviderTests_NameDeclarationInfoTests.cs @@ -367,333 +367,271 @@ await VerifySymbolKinds(markup, } [Fact] - public async Task ClassTypeParameter1() - { - var markup = """ + public Task ClassTypeParameter1() + => VerifySymbolKinds(""" class C<$$ { } - """; - await VerifySymbolKinds(markup, + """, new SymbolKindOrTypeKind(SymbolKind.TypeParameter)); - } [Fact] - public async Task ClassTypeParameter2() - { - var markup = """ + public Task ClassTypeParameter2() + => VerifySymbolKinds(""" class C VerifySymbolKinds(""" class C { readonly int $$ } - """; - await VerifySymbolKinds(markup, + """, new SymbolKindOrTypeKind(SymbolKind.Field)); - } [Fact] - public async Task ModifierExclusion2() - { - var markup = """ + public Task ModifierExclusion2() + => VerifySymbolKinds(""" class C { const int $$ } - """; - await VerifySymbolKinds(markup, + """, new SymbolKindOrTypeKind(SymbolKind.Field)); - } [Fact] - public async Task ModifierExclusion3() - { - var markup = """ + public Task ModifierExclusion3() + => VerifySymbolKinds(""" class C { abstract int $$ } - """; - await VerifySymbolKinds(markup, + """, new SymbolKindOrTypeKind(SymbolKind.Property), new SymbolKindOrTypeKind(MethodKind.Ordinary)); - } [Fact] - public async Task ModifierExclusion4() - { - var markup = """ + public Task ModifierExclusion4() + => VerifySymbolKinds(""" class C { virtual int $$ } - """; - await VerifySymbolKinds(markup, + """, new SymbolKindOrTypeKind(SymbolKind.Property), new SymbolKindOrTypeKind(MethodKind.Ordinary)); - } [Fact] - public async Task ModifierExclusion5() - { - var markup = """ + public Task ModifierExclusion5() + => VerifySymbolKinds(""" class C { sealed int $$ } - """; - await VerifySymbolKinds(markup, + """, new SymbolKindOrTypeKind(SymbolKind.Property), new SymbolKindOrTypeKind(MethodKind.Ordinary)); - } [Fact] - public async Task ModifierExclusion6() - { - var markup = """ + public Task ModifierExclusion6() + => VerifySymbolKinds(""" class C { override int $$ } - """; - await VerifySymbolKinds(markup, + """, new SymbolKindOrTypeKind(SymbolKind.Property), new SymbolKindOrTypeKind(MethodKind.Ordinary)); - } [Fact] - public async Task ModifierExclusion7() - { - var markup = """ + public Task ModifierExclusion7() + => VerifySymbolKinds(""" class C { async int $$ } - """; - await VerifySymbolKinds(markup, + """, new SymbolKindOrTypeKind(MethodKind.Ordinary)); - } [Fact] - public async Task ModifierExclusion8() - { - // Note that the async is not included in the incomplete member syntax - var markup = """ + public Task ModifierExclusion8() + => VerifySymbolKinds(""" class C { partial int $$ } - """; - await VerifySymbolKinds(markup, + """, new SymbolKindOrTypeKind(SymbolKind.Field), new SymbolKindOrTypeKind(SymbolKind.Property), new SymbolKindOrTypeKind(MethodKind.Ordinary)); - } [Theory] [InlineData("int")] [InlineData("C")] [InlineData("List")] - public async Task ModifierExclusionInsideMethod_Const(string type) - { - var markup = $@" -using System.Collections.Generic; -class C -{{ - void M() - {{ - const {type} $$ - }} -}} -"; - await VerifySymbolKinds(markup, + public Task ModifierExclusionInsideMethod_Const(string type) + => VerifySymbolKinds($$""" + using System.Collections.Generic; + class C + { + void M() + { + const {{type}} $$ + } + } + """, new SymbolKindOrTypeKind(SymbolKind.Local)); - } [Theory] [InlineData("int")] [InlineData("C")] [InlineData("List")] - public async Task ModifierExclusionInsideMethod_ConstLocalDeclaration(string type) - { - var markup = $@" -using System.Collections.Generic; -class C -{{ - void M() - {{ - const {type} v$$ = default; - }} -}} -"; - await VerifySymbolKinds(markup, + public Task ModifierExclusionInsideMethod_ConstLocalDeclaration(string type) + => VerifySymbolKinds($$""" + using System.Collections.Generic; + class C + { + void M() + { + const {{type}} v$$ = default; + } + } + """, new SymbolKindOrTypeKind(SymbolKind.Local)); - } [Theory] [InlineData("int")] [InlineData("C")] [InlineData("List")] - public async Task ModifierExclusionInsideMethod_ConstLocalFunction(string type) - { - var markup = $@" -using System.Collections.Generic; -class C -{{ - void M() - {{ - const {type} v$$() - {{ - }} - }} -}} -"; - await VerifySymbolKinds(markup, + public Task ModifierExclusionInsideMethod_ConstLocalFunction(string type) + => VerifySymbolKinds($$""" + using System.Collections.Generic; + class C + { + void M() + { + const {{type}} v$$() + { + } + } + } + """, new SymbolKindOrTypeKind(SymbolKind.Local)); - } [Theory] [InlineData("int")] [InlineData("C")] [InlineData("List")] - public async Task ModifierExclusionInsideMethod_Async(string type) - { - // This only works with a partially written name. - // Because async is not a keyword, the syntax tree when the name is missing is completely broken - // in that there can be multiple statements full of missing and skipped tokens depending on the type syntax. - var markup = $@" -using System.Collections.Generic; -class C -{{ - void M() - {{ - async {type} v$$ - }} -}} -"; - await VerifySymbolKinds(markup, + public Task ModifierExclusionInsideMethod_Async(string type) + => VerifySymbolKinds($$""" + using System.Collections.Generic; + class C + { + void M() + { + async {{type}} v$$ + } + } + """, new SymbolKindOrTypeKind(MethodKind.LocalFunction)); - } [Theory] [InlineData("int")] [InlineData("C")] [InlineData("List")] - public async Task ModifierExclusionInsideMethod_AsyncLocalDeclaration(string type) - { - var markup = $@" -using System.Collections.Generic; -class C -{{ - void M() - {{ - async {type} v$$ = default; - }} -}} -"; - await VerifySymbolKinds(markup, + public Task ModifierExclusionInsideMethod_AsyncLocalDeclaration(string type) + => VerifySymbolKinds($$""" + using System.Collections.Generic; + class C + { + void M() + { + async {{type}} v$$ = default; + } + } + """, new SymbolKindOrTypeKind(MethodKind.LocalFunction)); - } [Theory] [InlineData("int")] [InlineData("C")] [InlineData("List")] - public async Task ModifierExclusionInsideMethod_AsyncLocalFunction(string type) - { - var markup = $@" -using System.Collections.Generic; -class C -{{ - void M() - {{ - async {type} v$$() - {{ - }} - }} -}} -"; - await VerifySymbolKinds(markup, + public Task ModifierExclusionInsideMethod_AsyncLocalFunction(string type) + => VerifySymbolKinds($$""" + using System.Collections.Generic; + class C + { + void M() + { + async {{type}} v$$() + { + } + } + } + """, new SymbolKindOrTypeKind(MethodKind.LocalFunction)); - } [Theory] [InlineData("int")] [InlineData("C")] [InlineData("List")] - public async Task ModifierExclusionInsideMethod_Unsafe(string type) - { - var markup = $@" -using System.Collections.Generic; -class C -{{ - void M() - {{ - unsafe {type} $$ - }} -}} -"; - await VerifySymbolKinds(markup, + public Task ModifierExclusionInsideMethod_Unsafe(string type) + => VerifySymbolKinds($$""" + using System.Collections.Generic; + class C + { + void M() + { + unsafe {{type}} $$ + } + } + """, new SymbolKindOrTypeKind(MethodKind.LocalFunction)); - } [Theory] [InlineData("int")] [InlineData("C")] [InlineData("List")] - public async Task ModifierExclusionInsideMethod_UnsafeLocalDeclaration(string type) - { - var markup = $@" -using System.Collections.Generic; -class C -{{ - void M() - {{ - unsafe {type} v$$ = default; - }} -}} -"; - await VerifySymbolKinds(markup, + public Task ModifierExclusionInsideMethod_UnsafeLocalDeclaration(string type) + => VerifySymbolKinds($$""" + using System.Collections.Generic; + class C + { + void M() + { + unsafe {{type}} v$$ = default; + } + } + """, new SymbolKindOrTypeKind(MethodKind.LocalFunction)); - } [Theory] [InlineData("int")] [InlineData("C")] [InlineData("List")] - public async Task ModifierExclusionInsideMethod_UnsafeLocalFunction(string type) - { - var markup = $@" -using System.Collections.Generic; -class C -{{ - void M() - {{ - unsafe {type} v$$() - {{ - }} - }} -}} -"; - await VerifySymbolKinds(markup, + public Task ModifierExclusionInsideMethod_UnsafeLocalFunction(string type) + => VerifySymbolKinds($$""" + using System.Collections.Generic; + class C + { + void M() + { + unsafe {{type}} v$$() + { + } + } + } + """, new SymbolKindOrTypeKind(MethodKind.LocalFunction)); - } [Fact] - public async Task LocalInsideMethod1() - { - var markup = """ + public Task LocalInsideMethod1() + => VerifySymbolKinds(""" namespace ConsoleApp1 { class ReallyLongClassName { } @@ -704,16 +642,13 @@ static void Main(string[] args) ReallyLongClassName $$ } } - """; - await VerifySymbolKinds(markup, + """, new SymbolKindOrTypeKind(SymbolKind.Local), new SymbolKindOrTypeKind(MethodKind.LocalFunction)); - } [Fact] - public async Task LocalInsideMethod2() - { - var markup = """ + public Task LocalInsideMethod2() + => VerifySymbolKinds(""" namespace ConsoleApp1 { class ReallyLongClassName { } @@ -724,16 +659,13 @@ static void Main(string[] args) ReallyLongClassName $$ } } - """; - await VerifySymbolKinds(markup, + """, new SymbolKindOrTypeKind(SymbolKind.Local), new SymbolKindOrTypeKind(MethodKind.LocalFunction)); - } [Fact] - public async Task LocalInsideMethodAfterPredefinedTypeKeyword() - { - var markup = """ + public Task LocalInsideMethodAfterPredefinedTypeKeyword() + => VerifySymbolKinds(""" namespace ConsoleApp1 { class ReallyLongClassName { } @@ -744,16 +676,13 @@ static void Main(string[] args) string $$ } } - """; - await VerifySymbolKinds(markup, + """, new SymbolKindOrTypeKind(SymbolKind.Local), new SymbolKindOrTypeKind(MethodKind.LocalFunction)); - } [Fact] - public async Task LocalInsideMethodAfterArray() - { - var markup = """ + public Task LocalInsideMethodAfterArray() + => VerifySymbolKinds(""" namespace ConsoleApp1 { class Program @@ -763,11 +692,9 @@ static void Main(string[] args) string[] $$ } } - """; - await VerifySymbolKinds(markup, + """, new SymbolKindOrTypeKind(SymbolKind.Local), new SymbolKindOrTypeKind(MethodKind.LocalFunction)); - } private async Task VerifyTypeName(string markup, string? typeName) { diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/EnumAndCompletionListTagCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/EnumAndCompletionListTagCompletionProviderTests.cs index 4b39e3095fd14..43885e0fbb56e 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/EnumAndCompletionListTagCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/EnumAndCompletionListTagCompletionProviderTests.cs @@ -189,16 +189,18 @@ readonly struct Colors public async Task InYieldReturnInMethod(string typeName) { var markup = -$@"using System; -using System.Collections.Generic; + $$""" + using System; + using System.Collections.Generic; -class Program -{{ - IEnumerable<{typeName}> M() - {{ - yield return $$ - }} -}}"; + class Program + { + IEnumerable<{{typeName}}> M() + { + yield return $$ + } + } + """; if (typeName == nameof(DayOfWeek)) await VerifyItemExistsAsync(markup, typeName); @@ -212,19 +214,21 @@ class Program public async Task InYieldReturnInLocalFunction(string typeName) { var markup = -$@"using System; -using System.Collections.Generic; - -class Program -{{ - void M() - {{ - IEnumerable<{typeName}> F() - {{ - yield return $$ - }} - }} -}}"; + $$""" + using System; + using System.Collections.Generic; + + class Program + { + void M() + { + IEnumerable<{{typeName}}> F() + { + yield return $$ + } + } + } + """; if (typeName == nameof(DayOfWeek)) await VerifyItemExistsAsync(markup, typeName); @@ -238,17 +242,19 @@ void M() public async Task InAsyncMethodReturnStatement(string typeName) { var markup = -$@"using System; -using System.Threading.Tasks; + $$""" + using System; + using System.Threading.Tasks; -class Program -{{ - async Task<{typeName}> M() - {{ - await Task.Delay(1); - return $$ - }} -}}"; + class Program + { + async Task<{{typeName}}> M() + { + await Task.Delay(1); + return $$ + } + } + """; if (typeName == nameof(DayOfWeek)) await VerifyItemExistsAsync(markup, typeName); @@ -262,15 +268,17 @@ class Program public async Task InSimpleLambdaAfterArrow(string typeName) { var markup = -$@"using System; + $$""" + using System; -class Program -{{ - Func M() - {{ - return _ => $$ - }} -}}"; + class Program + { + Func M() + { + return _ => $$ + } + } + """; if (typeName == nameof(DayOfWeek)) await VerifyItemExistsAsync(markup, typeName); @@ -284,15 +292,17 @@ class Program public async Task InParenthesizedLambdaAfterArrow(string typeName) { var markup = -$@"using System; + $$""" + using System; -class Program -{{ - Func<{typeName}> M() - {{ - return () => $$ - }} -}}"; + class Program + { + Func<{{typeName}}> M() + { + return () => $$ + } + } + """; if (typeName == nameof(DayOfWeek)) await VerifyItemExistsAsync(markup, typeName); @@ -303,128 +313,114 @@ class Program [Theory] [InlineData(nameof(DayOfWeek))] [InlineData(nameof(DateTime))] - public async Task NotInAnonymousMethodAfterParameterList(string typeName) - { - var markup = -$@"using System; - -class Program -{{ - Func<{typeName}> M() - {{ - return delegate () $$ - }} -}}"; - await VerifyItemIsAbsentAsync(markup, typeName); - } + public Task NotInAnonymousMethodAfterParameterList(string typeName) + => VerifyItemIsAbsentAsync($$""" + using System; + + class Program + { + Func<{{typeName}}> M() + { + return delegate () $$ + } + } + """, typeName); [Theory] [InlineData(nameof(DayOfWeek))] [InlineData(nameof(DateTime))] - public async Task NotInSimpleLambdaAfterAsync(string typeName) - { - var markup = -$@"using System; - -class Program -{{ - Func M() - {{ - return async $$ _ => - }} -}}"; - await VerifyItemIsAbsentAsync(markup, typeName); - } + public Task NotInSimpleLambdaAfterAsync(string typeName) + => VerifyItemIsAbsentAsync($$""" + using System; + + class Program + { + Func M() + { + return async $$ _ => + } + } + """, typeName); [Theory] [InlineData(nameof(DayOfWeek))] [InlineData(nameof(DateTime))] - public async Task NotInParenthesizedLambdaAfterAsync(string typeName) - { - var markup = -$@"using System; - -class Program -{{ - Func<{typeName}> M() - {{ - return async $$ () => - }} -}}"; - await VerifyItemIsAbsentAsync(markup, typeName); - } + public Task NotInParenthesizedLambdaAfterAsync(string typeName) + => VerifyItemIsAbsentAsync($$""" + using System; + + class Program + { + Func<{{typeName}}> M() + { + return async $$ () => + } + } + """, typeName); [Theory] [InlineData(nameof(DayOfWeek))] [InlineData(nameof(DateTime))] - public async Task NotInAnonymousMethodAfterAsync(string typeName) - { - var markup = -$@"using System; - -class Program -{{ - Func<{typeName}> M() - {{ - return async $$ delegate () - }} -}}"; - await VerifyItemIsAbsentAsync(markup, typeName); - } + public Task NotInAnonymousMethodAfterAsync(string typeName) + => VerifyItemIsAbsentAsync($$""" + using System; + + class Program + { + Func<{{typeName}}> M() + { + return async $$ delegate () + } + } + """, typeName); [Theory] [InlineData(nameof(DayOfWeek))] [InlineData(nameof(DateTime))] - public async Task NotInSimpleLambdaBlock(string typeName) - { - var markup = -$@"using System; - -class Program -{{ - Func M() - {{ - return _ => {{ $$ }} - }} -}}"; - await VerifyItemIsAbsentAsync(markup, typeName); - } + public Task NotInSimpleLambdaBlock(string typeName) + => VerifyItemIsAbsentAsync($$""" + using System; + + class Program + { + Func M() + { + return _ => { $$ } + } + } + """, typeName); [Theory] [InlineData(nameof(DayOfWeek))] [InlineData(nameof(DateTime))] - public async Task NotInParenthesizedLambdaBlock(string typeName) - { - var markup = -$@"using System; - -class Program -{{ - Func<{typeName}> M() - {{ - return () => {{ $$ }} - }} -}}"; - await VerifyItemIsAbsentAsync(markup, typeName); - } + public Task NotInParenthesizedLambdaBlock(string typeName) + => VerifyItemIsAbsentAsync($$""" + using System; + + class Program + { + Func<{{typeName}}> M() + { + return () => { $$ } + } + } + """, typeName); [Theory] [InlineData(nameof(DayOfWeek))] [InlineData(nameof(DateTime))] - public async Task NotInAnonymousMethodBlock(string typeName) - { - var markup = -$@"using System; - -class Program -{{ - Func<{typeName}> M() - {{ - return delegate () {{ $$ }} - }} -}}"; - await VerifyItemIsAbsentAsync(markup, typeName); - } + public Task NotInAnonymousMethodBlock(string typeName) + => VerifyItemIsAbsentAsync($$""" + using System; + + class Program + { + Func<{{typeName}}> M() + { + return delegate () { $$ } + } + } + """, typeName); [Theory] [InlineData(nameof(DayOfWeek))] @@ -432,16 +428,18 @@ class Program public async Task InExpressionTreeSimpleLambdaAfterArrow(string typeName) { var markup = -$@"using System; -using System.Linq.Expressions; + $$""" + using System; + using System.Linq.Expressions; -class Program -{{ - Expression> M() - {{ - return _ => $$ - }} -}}"; + class Program + { + Expression> M() + { + return _ => $$ + } + } + """; if (typeName == nameof(DayOfWeek)) await VerifyItemExistsAsync(markup, typeName); @@ -455,16 +453,18 @@ class Program public async Task InExpressionTreeParenthesizedLambdaAfterArrow(string typeName) { var markup = -$@"using System; -using System.Linq.Expressions; + $$""" + using System; + using System.Linq.Expressions; -class Program -{{ - Expression> M() - {{ - return () => $$ - }} -}}"; + class Program + { + Expression> M() + { + return () => $$ + } + } + """; if (typeName == nameof(DayOfWeek)) await VerifyItemExistsAsync(markup, typeName); @@ -473,10 +473,8 @@ class Program } [Fact] - public async Task NoCompletionListTag() - { - var markup = - """ + public Task NoCompletionListTag() + => VerifyNoItemsExistAsync(""" using System; using System.Threading.Tasks; @@ -492,15 +490,11 @@ void Goo() C c = $$ } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task CompletionList() - { - var markup = - """ + public Task CompletionList() + => VerifyItemExistsAsync(""" using System; using System.Threading.Tasks; @@ -517,15 +511,11 @@ void Goo() C c = $$ } } - """; - await VerifyItemExistsAsync(markup, "C"); - } + """, "C"); [Fact] - public async Task CompletionListCrefToString() - { - var markup = - """ + public Task CompletionListCrefToString() + => VerifyItemExistsAsync(""" using System; using System.Threading.Tasks; @@ -542,15 +532,11 @@ void Goo() C c = $$ } } - """; - await VerifyItemExistsAsync(markup, "string", glyph: Glyph.ClassPublic); - } + """, "string", glyph: Glyph.ClassPublic); [Fact] - public async Task CompletionListEmptyCref() - { - var markup = - """ + public Task CompletionListEmptyCref() + => VerifyNoItemsExistAsync(""" using System; using System.Threading.Tasks; @@ -567,15 +553,11 @@ void Goo() C c = $$ } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task CompletionListInaccessibleType() - { - var markup = - """ + public Task CompletionListInaccessibleType() + => VerifyNoItemsExistAsync(""" using System; using System.Threading.Tasks; @@ -594,15 +576,11 @@ void Goo() C c = $$ } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task CompletionListNotAType() - { - var markup = - """ + public Task CompletionListNotAType() + => VerifyNoItemsExistAsync(""" using System; using System.Threading.Tasks; @@ -621,9 +599,7 @@ void Goo() C c = $$ } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] public async Task CompletionListContainingMembers() @@ -658,15 +634,16 @@ void Goo() [InlineData("System.DateTime")] public async Task SuggestAlias(string fullTypeName) { - var markup = $@" -using D = {fullTypeName}; -class Program -{{ - static void Main(string[] args) - {{ - D d= $$ - }} -}}"; + var markup = $$""" + using D = {{fullTypeName}}; + class Program + { + static void Main(string[] args) + { + D d= $$ + } + } + """; if (fullTypeName == "System.Globalization.DigitShapes") await VerifyItemExistsAsync(markup, "D"); @@ -679,20 +656,20 @@ static void Main(string[] args) [InlineData("System.DateTime")] public async Task SuggestAlias2(string fullTypeName) { - var markup = $@" -namespace N -{{ -using D = {fullTypeName}; - -class Program -{{ - static void Main(string[] args) - {{ - D d= $$ - }} -}} -}} -"; + var markup = $$""" + namespace N + { + using D = {{fullTypeName}}; + + class Program + { + static void Main(string[] args) + { + D d= $$ + } + } + } + """; if (fullTypeName == "System.Globalization.DigitShapes") await VerifyItemExistsAsync(markup, "D"); @@ -705,24 +682,24 @@ static void Main(string[] args) [InlineData("System.DateTime")] public async Task SuggestAlias3(string fullTypeName) { - var markup = $@" -namespace N -{{ -using D = {fullTypeName}; - -class Program -{{ - private void Goo({fullTypeName} shape) - {{ - }} - - static void Main(string[] args) - {{ - Goo($$ - }} -}} -}} -"; + var markup = $$""" + namespace N + { + using D = {{fullTypeName}}; + + class Program + { + private void Goo({{fullTypeName}} shape) + { + } + + static void Main(string[] args) + { + Goo($$ + } + } + } + """; if (fullTypeName == "System.Globalization.DigitShapes") await VerifyItemExistsAsync(markup, "D"); @@ -823,31 +800,23 @@ readonly struct Colors } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] - public async Task NotAfterAsync1() - { - var markup = """ + public Task NotAfterAsync1() + => VerifyNoItemsExistAsync(""" class Test { public async $$ } - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] - public async Task NotAfterAsync2() - { - var markup = """ + public Task NotAfterAsync2() + => VerifyNoItemsExistAsync(""" class Test { public async $$ public void M() {} } - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] public async Task NotAfterDot() @@ -924,10 +893,8 @@ readonly struct E } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/5419")] - public async Task TestInEnumInitializer1() - { - var markup = - """ + public Task TestInEnumInitializer1() + => VerifyItemExistsAsync(""" using System; [Flags] @@ -940,15 +907,11 @@ internal enum ProjectTreeWriterOptions Visibility, AllProperties = FilePath | Visibility | $$ } - """; - await VerifyItemExistsAsync(markup, "ProjectTreeWriterOptions"); - } + """, "ProjectTreeWriterOptions"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/5419")] - public async Task TestInEnumInitializer2() - { - var markup = - """ + public Task TestInEnumInitializer2() + => VerifyItemExistsAsync(""" using System; [Flags] @@ -961,15 +924,11 @@ internal enum ProjectTreeWriterOptions Visibility, AllProperties = FilePath | $$ Visibility } - """; - await VerifyItemExistsAsync(markup, "ProjectTreeWriterOptions"); - } + """, "ProjectTreeWriterOptions"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/5419")] - public async Task TestInEnumInitializer3() - { - var markup = - """ + public Task TestInEnumInitializer3() + => VerifyItemExistsAsync(""" using System; [Flags] @@ -982,15 +941,11 @@ internal enum ProjectTreeWriterOptions Visibility, AllProperties = FilePath | $$ | Visibility } - """; - await VerifyItemExistsAsync(markup, "ProjectTreeWriterOptions"); - } + """, "ProjectTreeWriterOptions"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/5419")] - public async Task TestInEnumInitializer4() - { - var markup = - """ + public Task TestInEnumInitializer4() + => VerifyItemExistsAsync(""" using System; [Flags] @@ -1003,15 +958,11 @@ internal enum ProjectTreeWriterOptions Visibility, AllProperties = FilePath ^ $$ } - """; - await VerifyItemExistsAsync(markup, "ProjectTreeWriterOptions"); - } + """, "ProjectTreeWriterOptions"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/5419")] - public async Task TestInEnumInitializer5() - { - var markup = - """ + public Task TestInEnumInitializer5() + => VerifyItemExistsAsync(""" using System; [Flags] @@ -1024,15 +975,11 @@ internal enum ProjectTreeWriterOptions Visibility, AllProperties = FilePath & $$ } - """; - await VerifyItemExistsAsync(markup, "ProjectTreeWriterOptions"); - } + """, "ProjectTreeWriterOptions"); [Fact] - public async Task TestInEnumHasFlag() - { - var markup = - """ + public Task TestInEnumHasFlag() + => VerifyItemExistsAsync(""" using System.IO; class C @@ -1043,14 +990,11 @@ void M() f.Attributes.HasFlag($$ } } - """; - await VerifyItemExistsAsync(markup, "FileAttributes"); - } + """, "FileAttributes"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39240")] - public async Task TestInSwitchExpression1() - { - var markup = """ + public Task TestInSwitchExpression1() + => VerifyItemIsAbsentAsync(""" using System; class C @@ -1060,14 +1004,11 @@ void M(ConsoleColor color) var number = color switch $$ } } - """; - await VerifyItemIsAbsentAsync(markup, "ConsoleColor"); - } + """, "ConsoleColor"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39240")] - public async Task TestInSwitchExpression2() - { - var markup = """ + public Task TestInSwitchExpression2() + => VerifyItemExistsAsync(""" using System; class C @@ -1077,14 +1018,11 @@ void M(ConsoleColor color) var number = color switch { $$ } } - """; - await VerifyItemExistsAsync(markup, "ConsoleColor"); - } + """, "ConsoleColor"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39240")] - public async Task TestInSwitchExpression3() - { - var markup = """ + public Task TestInSwitchExpression3() + => VerifyItemIsAbsentAsync(""" using System; class C @@ -1094,14 +1032,11 @@ void M(ConsoleColor color) var number = color switch { ConsoleColor.Black $$ } } - """; - await VerifyItemIsAbsentAsync(markup, "ConsoleColor"); - } + """, "ConsoleColor"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39240")] - public async Task TestInSwitchExpression4() - { - var markup = """ + public Task TestInSwitchExpression4() + => VerifyItemIsAbsentAsync(""" using System; class C @@ -1111,14 +1046,11 @@ void M(ConsoleColor color) var number = color switch { ConsoleColor.Black => $$ } } - """; - await VerifyItemIsAbsentAsync(markup, "ConsoleColor"); - } + """, "ConsoleColor"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39240")] - public async Task TestInSwitchExpression5() - { - var markup = """ + public Task TestInSwitchExpression5() + => VerifyItemIsAbsentAsync(""" using System; class C @@ -1128,14 +1060,11 @@ void M(ConsoleColor color) var number = color switch { ConsoleColor.Black => 0 $$ } } - """; - await VerifyItemIsAbsentAsync(markup, "ConsoleColor"); - } + """, "ConsoleColor"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39240")] - public async Task TestInSwitchExpression6() - { - var markup = """ + public Task TestInSwitchExpression6() + => VerifyItemExistsAsync(""" using System; class C @@ -1145,14 +1074,11 @@ void M(ConsoleColor color) var number = color switch { ConsoleColor.Black => 0, $$ } } - """; - await VerifyItemExistsAsync(markup, "ConsoleColor"); - } + """, "ConsoleColor"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39240")] - public async Task TestInSwitchExpression7() - { - var markup = """ + public Task TestInSwitchExpression7() + => VerifyItemIsAbsentAsync(""" using System; class C @@ -1162,14 +1088,11 @@ void M(ConsoleColor color) var number = color switch { ConsoleColor.Black => 0 } $$ } } - """; - await VerifyItemIsAbsentAsync(markup, "ConsoleColor"); - } + """, "ConsoleColor"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68240")] - public async Task TestNotCompilerGeneratedField() - { - var markup = """ + public Task TestNotCompilerGeneratedField() + => VerifyItemIsAbsentAsync(""" class Sample { public static Sample Instance { get; } = new Sample(); @@ -1182,9 +1105,7 @@ Sample A() } } } - """; - await VerifyItemIsAbsentAsync(markup, "Sample.k__BackingField"); - } + """, "Sample.k__BackingField"); #region enum members @@ -1207,14 +1128,6 @@ public enum MyEnum Member } """; - var referencedCode_EnumLike = """ - public readonly struct MyEnum - { - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] - public static readonly MyEnum Member; - } - """; - await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, @@ -1226,7 +1139,13 @@ await VerifyItemInEditorBrowsableContextsAsync( await VerifyItemInEditorBrowsableContextsAsync( markup: markup, - referencedCode: referencedCode_EnumLike, + referencedCode: """ + public readonly struct MyEnum + { + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] + public static readonly MyEnum Member; + } + """, item: "MyEnum.Member", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, @@ -1253,14 +1172,6 @@ public enum MyEnum Member } """; - var referencedCode_EnumLike = """ - public readonly struct MyEnum - { - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public static readonly MyEnum Member; - } - """; - await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, @@ -1272,7 +1183,13 @@ await VerifyItemInEditorBrowsableContextsAsync( await VerifyItemInEditorBrowsableContextsAsync( markup: markup, - referencedCode: referencedCode_EnumLike, + referencedCode: """ + public readonly struct MyEnum + { + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public static readonly MyEnum Member; + } + """, item: "MyEnum.Member", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, @@ -1471,132 +1388,116 @@ readonly struct E [Theory] [InlineData(nameof(DayOfWeek), nameof(DayOfWeek.Friday))] [InlineData(nameof(DateTime), nameof(DateTime.Now))] - public async Task TestInYieldReturn(string typeName, string memberName) - { - var markup = $@" -using System; -using System.Collections.Generic; - -class C -{{ - public IEnumerable<{typeName}> M() - {{ - yield return $$; - }} -}} -"; - - await VerifyItemExistsAsync(markup, $"{typeName}.{memberName}"); - } + public Task TestInYieldReturn(string typeName, string memberName) + => VerifyItemExistsAsync($$""" + using System; + using System.Collections.Generic; + + class C + { + public IEnumerable<{{typeName}}> M() + { + yield return $$; + } + } + """, $"{typeName}.{memberName}"); [Theory] [InlineData(nameof(DayOfWeek), nameof(DayOfWeek.Friday))] [InlineData(nameof(DateTime), nameof(DateTime.Now))] - public async Task TestInAsyncMethodReturnStatement(string typeName, string memberName) - { - var markup = $@" -using System; -using System.Threading.Tasks; + public Task TestInAsyncMethodReturnStatement(string typeName, string memberName) + => VerifyItemExistsAsync($$""" + using System; + using System.Threading.Tasks; -class C -{{ - public async Task<{typeName}> M() - {{ - await Task.Delay(1); - return $$; - }} -}} -"; - - await VerifyItemExistsAsync(markup, $"{typeName}.{memberName}"); - } + class C + { + public async Task<{{typeName}}> M() + { + await Task.Delay(1); + return $$; + } + } + """, $"{typeName}.{memberName}"); [Theory] [InlineData(nameof(DayOfWeek), nameof(DayOfWeek.Friday))] [InlineData(nameof(DateTime), nameof(DateTime.Now))] - public async Task TestInIndexedProperty(string typeName, string memberName) - { - var markup = $@" -using System; -static class Module1 -{{ - public class MyClass1 - {{ - public bool this[{typeName} index] - {{ - set - {{ - }} - }} - }} - - public static void Main() - {{ - var c = new MyClass1(); - c[$${typeName}.{memberName}] = true; - }} -}} -"; - - await VerifyItemExistsAsync(markup, $"{typeName}.{memberName}"); - } + public Task TestInIndexedProperty(string typeName, string memberName) + => VerifyItemExistsAsync($$""" + using System; + static class Module1 + { + public class MyClass1 + { + public bool this[{{typeName}} index] + { + set + { + } + } + } + + public static void Main() + { + var c = new MyClass1(); + c[$${{typeName}}.{{memberName}}] = true; + } + } + """, $"{typeName}.{memberName}"); [Theory] [InlineData(nameof(DayOfWeek), nameof(DayOfWeek.Friday))] [InlineData(nameof(DateTime), nameof(DateTime.Now))] - public async Task TestFullyQualified(string typeName, string memberName) - { - var markup = $@" -class C -{{ - public void M(System.{typeName} day) - {{ - M($$); - }} - - enum DayOfWeek - {{ - A, - B - }} - - struct DateTime - {{ - public static readonly DateTime A; - public static readonly DateTime B; - }} -}} -"; - - await VerifyItemExistsAsync(markup, $"System.{typeName}.{memberName}"); - } + public Task TestFullyQualified(string typeName, string memberName) + => VerifyItemExistsAsync($$""" + class C + { + public void M(System.{{typeName}} day) + { + M($$); + } + + enum DayOfWeek + { + A, + B + } + + struct DateTime + { + public static readonly DateTime A; + public static readonly DateTime B; + } + } + """, $"System.{typeName}.{memberName}"); [Theory] [InlineData(nameof(DayOfWeek))] [InlineData(nameof(DateTime))] public async Task TestTriggeredForNamedArgument(string typeName) { - var markup = $@" -class C -{{ - public void M({typeName} day) - {{ - M(day: $$); - }} - - enum DayOfWeek - {{ - A, - B - }} - - struct DateTime - {{ - public static readonly DateTime A; - public static readonly DateTime B; - }} -}} -"; + var markup = $$""" + class C + { + public void M({{typeName}} day) + { + M(day: $$); + } + + enum DayOfWeek + { + A, + B + } + + struct DateTime + { + public static readonly DateTime A; + public static readonly DateTime B; + } + } + """; if (typeName == nameof(DayOfWeek)) await VerifyItemExistsAsync(markup, $"{typeName}.A", usePreviousCharAsTrigger: true); @@ -1609,32 +1510,28 @@ struct DateTime [Theory] [InlineData(nameof(DayOfWeek))] [InlineData(nameof(DateTime))] - public async Task TestNotTriggeredAfterAssignmentEquals(string typeName) - { - var markup = $@" -class C -{{ - public void M({typeName} day) - {{ - var x = $$; - }} - - enum DayOfWeek - {{ - A, - B - }} - - struct DateTime - {{ - public static readonly DateTime A; - public static readonly DateTime B; - }} -}} -"; - - await VerifyItemIsAbsentAsync(markup, $"{typeName}.A", usePreviousCharAsTrigger: true); - } + public Task TestNotTriggeredAfterAssignmentEquals(string typeName) + => VerifyItemIsAbsentAsync($$""" + class C + { + public void M({{typeName}} day) + { + var x = $$; + } + + enum DayOfWeek + { + A, + B + } + + struct DateTime + { + public static readonly DateTime A; + public static readonly DateTime B; + } + } + """, $"{typeName}.A", usePreviousCharAsTrigger: true); [Fact] public async Task TestCaseStatementWithInt32InferredType() @@ -1688,9 +1585,8 @@ public void M() } [Fact] - public async Task TestIncludeEnumAfterTyping() - { - var markup = """ + public Task TestIncludeEnumAfterTyping() + => VerifyItemExistsAsync(""" enum E { A @@ -1703,15 +1599,11 @@ public void M() const E e = e$$; } } - """; - - await VerifyItemExistsAsync(markup, "E.A"); - } + """, "E.A"); [Fact] - public async Task TestNotInTrivia() - { - var markup = """ + public Task TestNotInTrivia() + => VerifyNoItemsExistAsync(""" class C { public void M(DayOfWeek day) @@ -1731,14 +1623,11 @@ enum DayOfWeek B } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task TestCommitOnComma() - { - var markup = """ + public Task TestCommitOnComma() + => VerifyProviderCommitAsync(""" enum E { A @@ -1751,9 +1640,7 @@ public void M() const E e = $$ } } - """; - - var expected = """ + """, "E.A", """ enum E { A @@ -1766,84 +1653,68 @@ public void M() const E e = E.A; } } - """; - - await VerifyProviderCommitAsync(markup, "E.A", expected, ';'); - } + """, ';'); [Theory] [InlineData(nameof(ConsoleKey))] [InlineData(nameof(DateTime))] - public async Task EnumMember_NotAfterDot(string typeName) - { - var markup = $@" -static class Module1 -{{ - public static void Main({typeName} x) - {{ - while (x == System.{typeName}.$$ - {{ - }} - }} -}} -"; - - await VerifyNoItemsExistAsync(markup); - } + public Task EnumMember_NotAfterDot(string typeName) + => VerifyNoItemsExistAsync($$""" + static class Module1 + { + public static void Main({{typeName}} x) + { + while (x == System.{{typeName}}.$$ + { + } + } + } + """); [Theory] [InlineData(nameof(DayOfWeek), nameof(DayOfWeek.Monday))] [InlineData(nameof(DateTime), nameof(DateTime.Now))] - public async Task TestInCollectionInitializer1(string typeName, string memberName) - { - var markup = $@" -using System; -using System.Collections.Generic; - -class C -{{ - public void Main() - {{ - var y = new List<{typeName}>() - {{ - $$ - }}; - }} -}} -"; - - await VerifyItemExistsAsync(markup, $"{typeName}.{memberName}"); - } + public Task TestInCollectionInitializer1(string typeName, string memberName) + => VerifyItemExistsAsync($$""" + using System; + using System.Collections.Generic; + + class C + { + public void Main() + { + var y = new List<{{typeName}}>() + { + $$ + }; + } + } + """, $"{typeName}.{memberName}"); [Theory] [InlineData(nameof(DayOfWeek), nameof(DayOfWeek.Monday))] [InlineData(nameof(DateTime), nameof(DateTime.Now))] - public async Task TestInCollectionInitializer2(string typeName, string memberName) - { - var markup = $@" -using System; -using System.Collections.Generic; - -class C -{{ - public void Main() - {{ - var y = new List<{typeName}>() - {{ - {typeName}.{memberName}, - $$ - }}; - }} -}} -"; - - await VerifyItemExistsAsync(markup, $"{typeName}.{memberName}"); - } + public Task TestInCollectionInitializer2(string typeName, string memberName) + => VerifyItemExistsAsync($$""" + using System; + using System.Collections.Generic; + + class C + { + public void Main() + { + var y = new List<{{typeName}}>() + { + {{typeName}}.{{memberName}}, + $$ + }; + } + } + """, $"{typeName}.{memberName}"); [Fact] - public async Task EnumMember_TestInEnumHasFlag() - { - var markup = """ + public Task EnumMember_TestInEnumHasFlag() + => VerifyItemExistsAsync(""" using System.IO; class C @@ -1854,10 +1725,7 @@ public void Main() f.Attributes.HasFlag($$ } } - """; - - await VerifyItemExistsAsync(markup, "FileAttributes.Hidden"); - } + """, "FileAttributes.Hidden"); [Fact] public async Task TestMultipleEnumsCausedByOverloads() @@ -1912,45 +1780,40 @@ public void Main() [InlineData(nameof(DayOfWeek), nameof(DayOfWeek.Friday))] [InlineData(nameof(DateTime), nameof(DateTime.Now))] [InlineData(nameof(TimeZoneInfo), nameof(TimeZoneInfo.Local))] - public async Task TestNullableEnum(string typeName, string memberName) - { - var markup = $@" -#nullable enable -using System; -class C -{{ - public void SetValue({typeName}? value) {{ }} - - public void Main() - {{ - SetValue($$ - }} -}} -"; - await VerifyItemExistsAsync(markup, $"{typeName}.{memberName}"); - } + public Task TestNullableEnum(string typeName, string memberName) + => VerifyItemExistsAsync($$""" + #nullable enable + using System; + class C + { + public void SetValue({{typeName}}? value) { } + + public void Main() + { + SetValue($$ + } + } + """, $"{typeName}.{memberName}"); [Theory] [InlineData(nameof(DayOfWeek), nameof(DayOfWeek.Friday))] [InlineData(nameof(DateTime), nameof(DateTime.Now))] [InlineData(nameof(TimeZoneInfo), nameof(TimeZoneInfo.Local))] - public async Task TestTypeAlias(string typeName, string memberName) - { - var markup = $@" -#nullable enable -using AT = System.{typeName}; - -public class Program -{{ - static void M(AT attributeTargets) {{ }} - - public static void Main() - {{ - M($$ - }} -}}"; - await VerifyItemExistsAsync(markup, $"AT.{memberName}"); - } + public Task TestTypeAlias(string typeName, string memberName) + => VerifyItemExistsAsync($$""" + #nullable enable + using AT = System.{{typeName}}; + + public class Program + { + static void M(AT attributeTargets) { } + + public static void Main() + { + M($$ + } + } + """, $"AT.{memberName}"); [Theory] [InlineData("")] @@ -1966,21 +1829,21 @@ public static void Main() [InlineData("not Re")] public async Task TestPatterns_Is_ConstUnaryAndBinaryPattern(string isPattern, bool shouldOfferRed = true) { - var markup = @$" -class C -{{ - public enum Color - {{ - Red, - Green, - }} - - public void M(Color c) - {{ - var isRed = c is {isPattern}$$; - }} -}} -"; + var markup = $$""" + class C + { + public enum Color + { + Red, + Green, + } + + public void M(Color c) + { + var isRed = c is {{isPattern}}$$; + } + } + """; if (shouldOfferRed) { await VerifyItemExistsAsync(markup, "Color.Red"); @@ -1999,55 +1862,48 @@ public void M(Color c) [InlineData("Color.Green or Re")] [InlineData("not ")] [InlineData("not Re")] - public async Task TestPatterns_Is_PropertyPattern(string partialWritten) - { - var markup = @$" -public enum Color -{{ - Red, - Green, -}} - -class C -{{ - public Color Color {{ get; }} - - public void M() - {{ - var isRed = this is {{ Color: {partialWritten}$$ - }} -}} -"; - await VerifyItemExistsAsync(markup, "Color.Red"); - } + public Task TestPatterns_Is_PropertyPattern(string partialWritten) + => VerifyItemExistsAsync($$""" + public enum Color + { + Red, + Green, + } + + class C + { + public Color Color { get; } + + public void M() + { + var isRed = this is { Color: {{partialWritten}}$$ + } + } + """, "Color.Red"); [Fact] - public async Task TestPatterns_Is_PropertyPattern_NotAfterEnumDot() - { - var markup = @$" -public enum Color -{{ - Red, - Green, -}} - -class C -{{ - public Color Color {{ get; }} - - public void M() - {{ - var isRed = this is {{ Color: Color.R$$ - }} -}} -"; - await VerifyItemIsAbsentAsync(markup, "Color.Red"); - } + public Task TestPatterns_Is_PropertyPattern_NotAfterEnumDot() + => VerifyItemIsAbsentAsync($$""" + public enum Color + { + Red, + Green, + } + + class C + { + public Color Color { get; } + + public void M() + { + var isRed = this is { Color: Color.R$$ + } + } + """, "Color.Red"); [Fact] - public async Task TestPatterns_SwitchStatement_PropertyPattern() - { - var markup = """ + public Task TestPatterns_SwitchStatement_PropertyPattern() + => VerifyItemExistsAsync(""" public enum Color { Red, @@ -2065,14 +1921,11 @@ public void M() case { Color: $$ } } - """; - await VerifyItemExistsAsync(markup, "Color.Red"); - } + """, "Color.Red"); [Fact] - public async Task TestPatterns_SwitchExpression_PropertyPattern() - { - var markup = """ + public Task TestPatterns_SwitchExpression_PropertyPattern() + => VerifyItemExistsAsync(""" public enum Color { Red, @@ -2090,9 +1943,7 @@ public void M() { Color: $$ } } - """; - await VerifyItemExistsAsync(markup, "Color.Red"); - } + """, "Color.Red"); [Fact] public async Task TestStaticAndInstanceMembers() @@ -2149,20 +2000,20 @@ public void M(Color color) [InlineData("private")] public async Task TestAccessibilityDifferentType(string modifier) { - var markup = $@" -public class Color -{{ - {modifier} static readonly Color Red; -}} - -class C -{{ - public void M(Color color) - {{ - M($$ - }} -}} -"; + var markup = $$""" + public class Color + { + {{modifier}} static readonly Color Red; + } + + class C + { + public void M(Color color) + { + M($$ + } + } + """; var expected = modifier switch { @@ -2185,46 +2036,38 @@ public void M(Color color) [InlineData("protected")] [InlineData("private protected")] [InlineData("private")] - public async Task TestAccessibilitySameType(string modifier) - { - var markup = $@" -public class Color -{{ - {modifier} static readonly Color Red; - - public void M(Color color) - {{ - M($$ - }} -}} -"; + public Task TestAccessibilitySameType(string modifier) + => VerifyItemExistsAsync($$""" + public class Color + { + {{modifier}} static readonly Color Red; - await VerifyItemExistsAsync(markup, "Color.Red"); - } + public void M(Color color) + { + M($$ + } + } + """, "Color.Red"); [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("record")] - public async Task TestEnumLikeTypeKinds(string typeKeyword) - { - var markup = $@" -public {typeKeyword} Color -{{ - public static readonly Color Red; -}} - -class C -{{ - public void M(Color color) - {{ - M($$ - }} -}} -"; + public Task TestEnumLikeTypeKinds(string typeKeyword) + => VerifyItemExistsAsync($$""" + public {{typeKeyword}} Color + { + public static readonly Color Red; + } - await VerifyItemExistsAsync(markup, "Color.Red"); - } + class C + { + public void M(Color color) + { + M($$ + } + } + """, "Color.Red"); #endregion } diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ExplicitInterfaceMemberCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ExplicitInterfaceMemberCompletionProviderTests.cs index c11c812740f3e..96ef616c64ea7 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ExplicitInterfaceMemberCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ExplicitInterfaceMemberCompletionProviderTests.cs @@ -112,9 +112,8 @@ void IGoo.$$ } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/709988")] - public async Task CommitOnNotParen() - { - var markup = """ + public Task CommitOnNotParen() + => VerifyProviderCommitAsync(""" interface IGoo { void Goo(); @@ -124,9 +123,7 @@ class Bar : IGoo { void IGoo.$$ } - """; - - var expected = """ + """, "Goo()", """ interface IGoo { void Goo(); @@ -139,15 +136,11 @@ void IGoo.Goo() throw new System.NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, "Goo()", expected, null); - } + """, null); [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/709988")] - public async Task CommitOnParen() - { - var markup = """ + public Task CommitOnParen() + => VerifyCustomCommitProviderAsync(""" interface IGoo { void Goo(); @@ -157,9 +150,7 @@ class Bar : IGoo { void IGoo.$$ } - """; - - var expected = """ + """, "Goo", """ interface IGoo { void Goo(); @@ -172,10 +163,7 @@ void IGoo.Goo() [|throw new System.NotImplementedException();|] } } - """; - - await VerifyCustomCommitProviderAsync(markup, "Goo", expected, commitChar: '('); - } + """, commitChar: '('); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19947")] public async Task ExplicitInterfaceMemberCompletionContainsOnlyValidValues() @@ -315,9 +303,8 @@ void IGoo.$$ } [Fact] - public async Task NotNestedType_01() - { - var markup = """ + public Task NotNestedType_01() + => VerifyItemIsAbsentAsync(""" interface IGoo { public abstract class Goo @@ -329,15 +316,11 @@ class Bar : IGoo { void IGoo.$$ } - """; - - await VerifyItemIsAbsentAsync(markup, "Goo"); - } + """, "Goo"); [Fact] - public async Task NotNestedType_02() - { - var markup = """ + public Task NotNestedType_02() + => VerifyItemIsAbsentAsync(""" interface IGoo { public abstract class Goo @@ -349,10 +332,7 @@ interface IBar : IGoo { void IGoo.$$ } - """; - - await VerifyItemIsAbsentAsync(markup, "Goo"); - } + """, "Goo"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34456")] public async Task NotInaccessibleMember_01() @@ -429,9 +409,8 @@ protected void Goo2() {} } [Fact] - public async Task VerifySignatureCommit_Generic_Tab() - { - var markup = """ + public Task VerifySignatureCommit_Generic_Tab() + => VerifyProviderCommitAsync(""" interface IGoo { int Generic(K key, V value); @@ -441,9 +420,7 @@ class Bar : IGoo { void IGoo.$$ } - """; - - var expected = """ + """, "Generic(K key, V value)", """ interface IGoo { int Generic(K key, V value); @@ -456,15 +433,11 @@ int IGoo.Generic(K key, V value) throw new System.NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, "Generic(K key, V value)", expected, '\t'); - } + """, '\t'); [Fact] - public async Task VerifySignatureCommit_Generic_OpenBrace() - { - var markup = """ + public Task VerifySignatureCommit_Generic_OpenBrace() + => VerifyProviderCommitAsync(""" interface IGoo { int Generic(K key, V value); @@ -474,9 +447,7 @@ class Bar : IGoo { void IGoo.$$ } - """; - - var expected = """ + """, "Generic(K key, V value)", """ interface IGoo { int Generic(K key, V value); @@ -486,15 +457,11 @@ class Bar : IGoo { void IGoo.< } - """; - - await VerifyProviderCommitAsync(markup, "Generic(K key, V value)", expected, '<'); - } + """, '<'); [Fact] - public async Task VerifySignatureCommit_Method_Tab() - { - var markup = """ + public Task VerifySignatureCommit_Method_Tab() + => VerifyProviderCommitAsync(""" interface IGoo { int Generic(K key, V value); @@ -504,9 +471,7 @@ class Bar : IGoo { void IGoo.$$ } - """; - - var expected = """ + """, "Generic(K key, V value)", """ interface IGoo { int Generic(K key, V value); @@ -519,15 +484,11 @@ int IGoo.Generic(K key, V value) throw new System.NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, "Generic(K key, V value)", expected, '\t'); - } + """, '\t'); [WpfFact] - public async Task VerifySignatureCommit_Method_OpenBrace() - { - var markup = """ + public Task VerifySignatureCommit_Method_OpenBrace() + => VerifyCustomCommitProviderAsync(""" interface IGoo { int Generic(K key, V value); @@ -537,9 +498,7 @@ class Bar : IGoo { void IGoo.$$ } - """; - - var expected = """ + """, "Generic", """ interface IGoo { int Generic(K key, V value); @@ -552,15 +511,11 @@ int IGoo.Generic(K key, V value) [|throw new System.NotImplementedException();|] } } - """; - - await VerifyCustomCommitProviderAsync(markup, "Generic", expected, commitChar: '('); - } + """, commitChar: '('); [Fact] - public async Task VerifySignatureCommit_Indexer_Tab() - { - var markup = """ + public Task VerifySignatureCommit_Indexer_Tab() + => VerifyProviderCommitAsync(""" interface IGoo { int this[K key, V value] { get; } @@ -570,9 +525,7 @@ class Bar : IGoo { void IGoo.$$ } - """; - - var expected = """ + """, "this[K key, V value]", """ interface IGoo { int this[K key, V value] { get; } @@ -582,15 +535,11 @@ class Bar : IGoo { int IGoo.this[K key, V value] => throw new System.NotImplementedException(); } - """; - - await VerifyProviderCommitAsync(markup, "this[K key, V value]", expected, '\t'); - } + """, '\t'); [Fact] - public async Task VerifySignatureCommit_Indexer_OpenBrace() - { - var markup = """ + public Task VerifySignatureCommit_Indexer_OpenBrace() + => VerifyProviderCommitAsync(""" interface IGoo { int this[K key, V value] { get; } @@ -600,9 +549,7 @@ class Bar : IGoo { void IGoo.$$ } - """; - - var expected = """ + """, "this[K key, V value]", """ interface IGoo { int this[K key, V value] { get; } @@ -612,15 +559,11 @@ class Bar : IGoo { void IGoo.[ } - """; - - await VerifyProviderCommitAsync(markup, "this[K key, V value]", expected, '['); - } + """, '['); [Fact] - public async Task VerifySignatureCommit_IndexerGetSet_Tab() - { - var markup = """ + public Task VerifySignatureCommit_IndexerGetSet_Tab() + => VerifyProviderCommitAsync(""" interface IGoo { int this[K key, V value] { get; set; } @@ -630,9 +573,7 @@ class Bar : IGoo { void IGoo.$$ } - """; - - var expected = """ + """, "this[K key, V value]", """ interface IGoo { int this[K key, V value] { get; set; } @@ -642,15 +583,11 @@ class Bar : IGoo { int IGoo.this[K key, V value] { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, "this[K key, V value]", expected, '\t'); - } + """, '\t'); [Fact] - public async Task VerifySignatureCommit_IndexerGetSet_OpenBrace() - { - var markup = """ + public Task VerifySignatureCommit_IndexerGetSet_OpenBrace() + => VerifyProviderCommitAsync(""" interface IGoo { int this[K key, V value] { get; set; } @@ -660,9 +597,7 @@ class Bar : IGoo { void IGoo.$$ } - """; - - var expected = """ + """, "this[K key, V value]", """ interface IGoo { int this[K key, V value] { get; set; } @@ -672,10 +607,7 @@ class Bar : IGoo { void IGoo.[ } - """; - - await VerifyProviderCommitAsync(markup, "this[K key, V value]", expected, '['); - } + """, '['); [Theory] [InlineData("ref")] @@ -684,9 +616,8 @@ void IGoo.[ [InlineData("ref readonly")] [InlineData("scoped")] [InlineData("scoped ref")] - public async Task TestWithRefKind(string refKind) - { - var markup = $$""" + public Task TestWithRefKind(string refKind) + => VerifyProviderCommitAsync($$""" using System; ref struct S { } @@ -700,9 +631,7 @@ class C : I { void I.$$ } - """; - - var expected = $$""" + """, $"M({refKind} S s)", $$""" using System; ref struct S { } @@ -719,15 +648,11 @@ void I.M({{refKind}} S s) throw new NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, $"M({refKind} S s)", expected, '\t'); - } + """, '\t'); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53924")] - public async Task TestStaticAbstractInterfaceMember() - { - var markup = """ + public Task TestStaticAbstractInterfaceMember() + => VerifyProviderCommitAsync(""" interface I2 where T : I2 { abstract static implicit operator int(T x); @@ -737,9 +662,7 @@ class Test2 : I2 { static implicit I2.$$ } - """; - - var expected = """ + """, "operator int(Test2 x)", """ interface I2 where T : I2 { abstract static implicit operator int(T x); @@ -752,15 +675,11 @@ static implicit I2.operator int(Test2 x) throw new System.NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, "operator int(Test2 x)", expected, '\t'); - } + """, '\t'); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53924")] - public async Task TestStaticAbstractInterfaceMember_TrueOperator() - { - var markup = """ + public Task TestStaticAbstractInterfaceMember_TrueOperator() + => VerifyProviderCommitAsync(""" interface I where T : I { abstract static bool operator true(T x); @@ -771,9 +690,7 @@ class C : I { static bool I.$$ } - """; - - var expected = """ + """, "operator true(C x)", """ interface I where T : I { abstract static bool operator true(T x); @@ -787,15 +704,11 @@ static bool I.operator true(C x) throw new System.NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, "operator true(C x)", expected, '\t'); - } + """, '\t'); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53924")] - public async Task TestStaticAbstractInterfaceMember_UnaryPlusOperator() - { - var markup = """ + public Task TestStaticAbstractInterfaceMember_UnaryPlusOperator() + => VerifyProviderCommitAsync(""" interface I where T : I { abstract static T operator +(T x); @@ -805,9 +718,7 @@ class C : I { static C I.$$ } - """; - - var expected = """ + """, "operator +(C x)", """ interface I where T : I { abstract static T operator +(T x); @@ -820,15 +731,11 @@ class C : I throw new System.NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, "operator +(C x)", expected, '\t'); - } + """, '\t'); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53924")] - public async Task TestStaticAbstractInterfaceMember_BinaryPlusOperator() - { - var markup = """ + public Task TestStaticAbstractInterfaceMember_BinaryPlusOperator() + => VerifyProviderCommitAsync(""" interface I where T : I { abstract static T operator +(T x, T y); @@ -838,9 +745,7 @@ class C : I { static C I.$$ } - """; - - var expected = """ + """, "operator +(C x, C y)", """ interface I where T : I { abstract static T operator +(T x, T y); @@ -853,15 +758,11 @@ class C : I throw new System.NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, "operator +(C x, C y)", expected, '\t'); - } + """, '\t'); [Fact] - public async Task TestWithParamsArrayParameter() - { - var markup = """ + public Task TestWithParamsArrayParameter() + => VerifyProviderCommitAsync(""" interface I { void M(params string[] args); @@ -871,9 +772,7 @@ class C : I { void I.$$ } - """; - - var expected = """ + """, "M(params string[] args)", """ interface I { void M(params string[] args); @@ -886,15 +785,11 @@ void I.M(params string[] args) throw new System.NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, "M(params string[] args)", expected, '\t'); - } + """, '\t'); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72224")] - public async Task TestWithParamsCollectionParameter() - { - var markup = """ + public Task TestWithParamsCollectionParameter() + => VerifyProviderCommitAsync(""" using System.Collections.Generic; interface I @@ -906,9 +801,7 @@ class C : I { void I.$$ } - """; - - var expected = """ + """, "M(params IEnumerable args)", """ using System.Collections.Generic; interface I @@ -923,15 +816,11 @@ void I.M(params IEnumerable args) throw new System.NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, "M(params IEnumerable args)", expected, '\t'); - } + """, '\t'); [Fact] - public async Task TestWithNullable() - { - var markup = """ + public Task TestWithNullable() + => VerifyProviderCommitAsync(""" #nullable enable interface I @@ -943,9 +832,7 @@ class C : I { void I.$$ } - """; - - var expected = """ + """, "M(T? x)", """ #nullable enable interface I @@ -960,15 +847,11 @@ class C : I throw new System.NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, "M(T? x)", expected, '\t'); - } + """, '\t'); [Fact] - public async Task TestEscapeIdentifier() - { - var markup = """ + public Task TestEscapeIdentifier() + => VerifyProviderCommitAsync(""" interface I { void M(string @class); @@ -978,9 +861,7 @@ class C : I { void I.$$ } - """; - - var expected = """ + """, "M(string @class)", """ interface I { void M(string @class); @@ -993,15 +874,11 @@ void I.M(string @class) throw new System.NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, "M(string @class)", expected, '\t'); - } + """, '\t'); [Fact] - public async Task TestEscapeIdentifier2() - { - var markup = """ + public Task TestEscapeIdentifier2() + => VerifyProviderCommitAsync(""" interface I { void M<@class>(); @@ -1011,9 +888,7 @@ class C : I { void I.$$ } - """; - - var expected = """ + """, "M<@class>()", """ interface I { void M<@class>(); @@ -1026,15 +901,11 @@ void I.M<@class>() throw new System.NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, "M<@class>()", expected, '\t'); - } + """, '\t'); [Fact] - public async Task TestParameterWithDefaultValue() - { - var markup = """ + public Task TestParameterWithDefaultValue() + => VerifyProviderCommitAsync(""" interface I { void M(int x = 10); @@ -1044,9 +915,7 @@ class C : I { void I.$$ } - """; - - var expected = """ + """, "M(int x)", """ interface I { void M(int x = 10); @@ -1059,14 +928,11 @@ void I.M(int x) throw new System.NotImplementedException(); } } - """; - await VerifyProviderCommitAsync(markup, "M(int x)", expected, '\t'); - } + """, '\t'); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60215")] - public async Task TestStaticAbstractCheckedUnaryOperator() - { - var markup = """ + public Task TestStaticAbstractCheckedUnaryOperator() + => VerifyProviderCommitAsync(""" interface I1 where T : I1 { abstract static T operator checked -(T x); @@ -1078,9 +944,7 @@ class C : I1 { static C I1.$$ } - """; - - var expected = """ + """, "operator checked -(C x)", """ interface I1 where T : I1 { abstract static T operator checked -(T x); @@ -1095,15 +959,11 @@ class C : I1 throw new System.NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, "operator checked -(C x)", expected, '\t'); - } + """, '\t'); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60215")] - public async Task TestStaticAbstractCheckedBinaryOperator() - { - var markup = """ + public Task TestStaticAbstractCheckedBinaryOperator() + => VerifyProviderCommitAsync(""" interface I1 where T : I1 { abstract static T operator checked +(T x, T y); @@ -1115,9 +975,7 @@ class C : I1 { static C I1.$$ } - """; - - var expected = """ + """, "operator checked +(C x, C y)", """ interface I1 where T : I1 { abstract static T operator checked +(T x, T y); @@ -1132,15 +990,11 @@ class C : I1 throw new System.NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, "operator checked +(C x, C y)", expected, '\t'); - } + """, '\t'); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60215")] - public async Task TestStaticAbstractCheckedCastOperator() - { - var markup = """ + public Task TestStaticAbstractCheckedCastOperator() + => VerifyProviderCommitAsync(""" interface I1 where T : I1 { abstract static explicit operator checked string(T x); @@ -1152,9 +1006,7 @@ class C3 : I1 { static C3 I1.$$ } - """; - - var expected = """ + """, "operator checked string(C3 x)", """ interface I1 where T : I1 { abstract static explicit operator checked string(T x); @@ -1169,15 +1021,11 @@ static explicit I1.operator checked string(C3 x) throw new System.NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, "operator checked string(C3 x)", expected, '\t'); - } + """, '\t'); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/70458")] - public async Task TestExlicitImplementationWithAttributesOnNullableParameters() - { - var markup = """ + public Task TestExlicitImplementationWithAttributesOnNullableParameters() + => VerifyCustomCommitProviderAsync(""" #nullable enable using Example.Namespace; @@ -1198,9 +1046,7 @@ namespace Example.Namespace { public record DecodeError; } - """; - - var expected = """ + """, "TryDecode", """ #nullable enable using Example.Namespace; @@ -1224,10 +1070,7 @@ namespace Example.Namespace { public record DecodeError; } - """; - - await VerifyCustomCommitProviderAsync(markup, "TryDecode", expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75435")] public async Task MissingReturnTypeQualifiedInterface_01() @@ -1250,9 +1093,8 @@ class Bar : IGoo } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75435")] - public async Task MissingReturnTypeQualifiedInterface_02() - { - var markup = """ + public Task MissingReturnTypeQualifiedInterface_02() + => VerifyItemIsAbsentAsync(""" interface IGoo { void Goo(); @@ -1265,10 +1107,7 @@ void Test() IGoo.$$ } } - """; - - await VerifyItemIsAbsentAsync(markup, "Goo"); - } + """, "Goo"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75435")] public async Task MissingReturnTypeQualifiedInterface_03() @@ -1294,9 +1133,8 @@ class Bar : Outer.IGoo } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75435")] - public async Task MissingReturnTypeQualifiedInterface_04() - { - var markup = """ + public Task MissingReturnTypeQualifiedInterface_04() + => VerifyProviderCommitAsync(""" interface IGoo { int Generic(K key, V value); @@ -1306,9 +1144,7 @@ class Bar : IGoo { IGoo.$$ } - """; - - var expected = """ + """, "Generic(K key, V value)", """ interface IGoo { int Generic(K key, V value); @@ -1321,15 +1157,11 @@ int IGoo.Generic(K key, V value) throw new System.NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, "Generic(K key, V value)", expected, '\t'); - } + """, '\t'); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75435")] - public async Task MissingReturnTypeQualifiedInterface_05() - { - var markup = """ + public Task MissingReturnTypeQualifiedInterface_05() + => VerifyProviderCommitAsync(""" interface I where T : I { abstract static bool operator true(T x); @@ -1340,9 +1172,7 @@ class C : I { I.$$ } - """; - - var expected = """ + """, "operator true(C x)", """ interface I where T : I { abstract static bool operator true(T x); @@ -1356,15 +1186,11 @@ static bool I.operator true(C x) throw new System.NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, "operator true(C x)", expected, '\t'); - } + """, '\t'); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75435")] - public async Task MissingReturnTypeQualifiedInterface_06() - { - var markup = """ + public Task MissingReturnTypeQualifiedInterface_06() + => VerifyProviderCommitAsync(""" interface I where T : I { abstract static ref bool Goo(ref int a, out int b); @@ -1374,9 +1200,7 @@ class C : I { I.$$ } - """; - - var expected = """ + """, "Goo(ref int a, out int b)", """ interface I where T : I { abstract static ref bool Goo(ref int a, out int b); @@ -1389,15 +1213,11 @@ static ref bool I.Goo(ref int a, out int b) throw new System.NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, "Goo(ref int a, out int b)", expected, '\t'); - } + """, '\t'); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75435")] - public async Task MissingReturnTypeQualifiedInterface_07() - { - var markup = """ + public Task MissingReturnTypeQualifiedInterface_07() + => VerifyProviderCommitAsync(""" interface I where T : I { abstract static bool Goo { set; } @@ -1407,9 +1227,7 @@ class C : I { I.$$ } - """; - - var expected = """ + """, "Goo", """ interface I where T : I { abstract static bool Goo { set; } @@ -1419,15 +1237,11 @@ class C : I { static bool I.Goo { set => throw new System.NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, "Goo", expected, '\t'); - } + """, '\t'); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75435")] - public async Task MissingReturnTypeQualifiedInterface_08() - { - var markup = """ + public Task MissingReturnTypeQualifiedInterface_08() + => VerifyProviderCommitAsync(""" interface I where T : I { abstract static event System.Action Goo; @@ -1437,9 +1251,7 @@ class C : I { I.$$ } - """; - - var expected = """ + """, "Goo", """ using System; interface I where T : I @@ -1462,15 +1274,11 @@ static event Action I.Goo } } } - """; - - await VerifyProviderCommitAsync(markup, "Goo", expected, '\t'); - } + """, '\t'); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75435")] - public async Task MissingReturnTypeQualifiedInterface_09() - { - var markup = """ + public Task MissingReturnTypeQualifiedInterface_09() + => VerifyProviderCommitAsync(""" interface I where T : I { bool Goo { get; set; } @@ -1480,9 +1288,7 @@ class C : I { I.$$ } - """; - - var expected = """ + """, "Goo", """ interface I where T : I { bool Goo { get; set; } @@ -1492,15 +1298,11 @@ class C : I { bool I.Goo { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, "Goo", expected, '\t'); - } + """, '\t'); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75435")] - public async Task MissingReturnTypeQualifiedInterface_10() - { - var markup = """ + public Task MissingReturnTypeQualifiedInterface_10() + => VerifyProviderCommitAsync(""" interface I where T : I { event System.Action Goo; @@ -1510,9 +1312,7 @@ class C : I { I.$$ } - """; - - var expected = """ + """, "Goo", """ using System; interface I where T : I @@ -1535,15 +1335,11 @@ event Action I.Goo } } } - """; - - await VerifyProviderCommitAsync(markup, "Goo", expected, '\t'); - } + """, '\t'); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75435")] - public async Task MissingReturnTypeQualifiedInterface_11() - { - var markup = """ + public Task MissingReturnTypeQualifiedInterface_11() + => VerifyProviderCommitAsync(""" interface I where T : I { bool this[int a, T b] { get; set; } @@ -1553,9 +1349,7 @@ class C : I { I.$$ } - """; - - var expected = """ + """, "this[int a, C b]", """ interface I where T : I { bool this[int a, T b] { get; set; } @@ -1565,10 +1359,7 @@ class C : I { bool I.this[int a, C b] { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, "this[int a, C b]", expected, '\t'); - } + """, '\t'); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75435")] public async Task MissingReturnTypeQualifiedInterface_12() @@ -1598,9 +1389,8 @@ class C : IOuter } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75435")] - public async Task MissingReturnTypeQualifiedInterface_13() - { - var markup = """ + public Task MissingReturnTypeQualifiedInterface_13() + => VerifyProviderCommitAsync(""" interface IOuter { void Method(); @@ -1616,9 +1406,7 @@ class C : IOuter { IOuter.$$ } - """; - - var expected = """ + """, "Method()", """ interface IOuter { void Method(); @@ -1637,10 +1425,7 @@ void IOuter.Method() throw new System.NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, "Method()", expected, '\t'); - } + """, '\t'); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75435")] public async Task MissingReturnTypeQualifiedInterface_14() @@ -1673,9 +1458,8 @@ class C : IOuter.IInner } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75435")] - public async Task MissingReturnTypeQualifiedInterface_15() - { - var markup = """ + public Task MissingReturnTypeQualifiedInterface_15() + => VerifyProviderCommitAsync(""" interface IOuter { void Method(); @@ -1691,9 +1475,7 @@ class C : IOuter.IInner { IOuter.IInner.$$ } - """; - - var expected = """ + """, "Method1()", """ interface IOuter { void Method(); @@ -1712,15 +1494,11 @@ void IOuter.IInner.Method1() throw new System.NotImplementedException(); } } - """; - - await VerifyProviderCommitAsync(markup, "Method1()", expected, '\t'); - } + """, '\t'); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75435")] - public async Task MissingReturnTypeQualifiedInterface_16() - { - var markup = """ + public Task MissingReturnTypeQualifiedInterface_16() + => VerifyItemIsAbsentAsync(""" interface IOuter { void Method(); @@ -1736,15 +1514,11 @@ class C : IOuter { IOuter.IInner.$$ } - """; - - await VerifyItemIsAbsentAsync(markup, "Method1", displayTextSuffix: "()"); - } + """, "Method1", displayTextSuffix: "()"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75435")] - public async Task MissingReturnTypeQualifiedInterface_17() - { - var markup = """ + public Task MissingReturnTypeQualifiedInterface_17() + => VerifyItemIsAbsentAsync(""" interface IInterface { void Method(); @@ -1754,15 +1528,11 @@ class C { IInterface.$$ } - """; - - await VerifyItemIsAbsentAsync(markup, "Method", displayTextSuffix: "()"); - } + """, "Method", displayTextSuffix: "()"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75435")] - public async Task MissingReturnTypeQualifiedInterface_18() - { - var markup = """ + public Task MissingReturnTypeQualifiedInterface_18() + => VerifyItemIsAbsentAsync(""" interface IOuter { void Method(); @@ -1778,15 +1548,11 @@ class C { IOuter.$$ } - """; - - await VerifyItemIsAbsentAsync(markup, "Method", displayTextSuffix: "()"); - } + """, "Method", displayTextSuffix: "()"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75435")] - public async Task MissingReturnTypeQualifiedInterface_19() - { - var markup = """ + public Task MissingReturnTypeQualifiedInterface_19() + => VerifyItemIsAbsentAsync(""" interface IOuter { void Method(); @@ -1802,15 +1568,11 @@ class C : IOuter.IInner { IOuter.$$ } - """; - - await VerifyItemIsAbsentAsync(markup, "Method", displayTextSuffix: "()"); - } + """, "Method", displayTextSuffix: "()"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75435")] - public async Task MissingReturnTypeQualifiedInterface_20() - { - var markup = """ + public Task MissingReturnTypeQualifiedInterface_20() + => VerifyItemExistsAsync(""" class Outer { public interface IInner @@ -1824,8 +1586,5 @@ class C : Outer.IInner { Outer.IInner.$$ } - """; - - await VerifyItemExistsAsync(markup, "Method1", displayTextSuffix: "()"); - } + """, "Method1", displayTextSuffix: "()"); } diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ExplicitInterfaceTypeCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ExplicitInterfaceTypeCompletionProviderTests.cs index c8e6f4c6a6781..d8284ae2789ac 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ExplicitInterfaceTypeCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ExplicitInterfaceTypeCompletionProviderTests.cs @@ -40,19 +40,20 @@ class C : IList [InlineData("record struct")] public async Task TestAtStartOfRecord(string record) { - var markup = $@" - - - -using System.Collections; - -{record} C : IList -{{ - int $$ -}} - - -"; + var markup = $$""" + + + + using System.Collections; + + {{record}} C : IList + { + int $$ + } + + + + """; await VerifyAnyItemExistsAsync(markup, hasSuggestionModeItem: true); await VerifyItemExistsAsync(markup, "IEnumerable"); @@ -61,16 +62,13 @@ public async Task TestAtStartOfRecord(string record) } [Fact, WorkItem("https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=459044")] - public async Task TestInMisplacedUsing() - { - var markup = """ + public Task TestInMisplacedUsing() + => VerifyNoItemsExistAsync(""" class C { using ($$) } - """; - await VerifyNoItemsExistAsync(markup); // no crash - } + """); // no crash [Fact] public async Task TestAtStartOfStruct() @@ -252,9 +250,8 @@ class C : IList } [Fact] - public async Task NotInMember() - { - var markup = """ + public Task NotInMember() + => VerifyNoItemsExistAsync(""" using System.Collections; class C : IList @@ -264,25 +261,18 @@ void Goo() int $$ } } - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task NotWithAccessibility() - { - var markup = """ + public Task NotWithAccessibility() + => VerifyNoItemsExistAsync(""" using System.Collections; class C : IList { public int $$ } - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] public async Task TestInInterface() @@ -322,9 +312,8 @@ async Task $$ } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70382")] - public async Task TestAfterGenericType() - { - var markup = """ + public Task TestAfterGenericType() + => VerifyItemExistsAsync(""" interface I { I M(); @@ -334,15 +323,11 @@ class C : I { I $$ } - """; - - await VerifyItemExistsAsync(markup, "I", displayTextSuffix: "<>"); - } + """, "I", displayTextSuffix: "<>"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70382")] - public async Task TestAfterNestedGenericType() - { - var markup = """ + public Task TestAfterNestedGenericType() + => VerifyItemExistsAsync(""" interface I { I M(); @@ -352,15 +337,11 @@ class C : I { I> $$ } - """; - - await VerifyItemExistsAsync(markup, "I", displayTextSuffix: "<>"); - } + """, "I", displayTextSuffix: "<>"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/54005")] - public async Task TestWithStaticKeyword() - { - var markup = """ + public Task TestWithStaticKeyword() + => VerifyItemExistsAsync(""" interface I1 { static abstract void M1(); @@ -370,8 +351,5 @@ class C1 : I1 { static void $$ } - """; - - await VerifyItemExistsAsync(markup, "I1", displayTextSuffix: ""); - } + """, "I1", displayTextSuffix: ""); } diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ExtensionMethodImportCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ExtensionMethodImportCompletionProviderTests.cs index 3ab99fbf2377d..7367d4c1b7e8f 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ExtensionMethodImportCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ExtensionMethodImportCompletionProviderTests.cs @@ -1931,9 +1931,8 @@ await VerifyImportItemIsAbsentAsync( [Theory] [InlineData('.')] [InlineData(';')] - public async Task TestCommitWithCustomizedCharForMethod(char commitChar) - { - var markup = """ + public Task TestCommitWithCustomizedCharForMethod(char commitChar) + => VerifyProviderCommitAsync(""" public class C { } @@ -1957,9 +1956,7 @@ public void M() } } } - """; - - var expected = $$""" + """, "ToInt", $$""" using AA; public class C @@ -1985,9 +1982,7 @@ public void M() } } } - """; - await VerifyProviderCommitAsync(markup, "ToInt", expected, commitChar: commitChar, sourceCodeKind: SourceCodeKind.Regular); - } + """, commitChar: commitChar, sourceCodeKind: SourceCodeKind.Regular); [Theory] [InlineData("int", true, "int a")] @@ -2045,9 +2040,8 @@ await VerifyImportItemExistsAsync( } [Fact] - public async Task TestComplexConstraint_NotShownOnObject() - { - await VerifyItemIsAbsentAsync( + public Task TestComplexConstraint_NotShownOnObject() + => VerifyItemIsAbsentAsync( """ interface I { @@ -2072,12 +2066,10 @@ void M(object i) displayTextSuffix: "<>", inlineDescription: "N", sourceCodeKind: SourceCodeKind.Regular); - } [Fact] - public async Task TestComplexConstraint_ShownOnExactInterfaceConstraintMatch() - { - await VerifyItemExistsAsync( + public Task TestComplexConstraint_ShownOnExactInterfaceConstraintMatch() + => VerifyItemExistsAsync( """ interface I { @@ -2102,12 +2094,10 @@ void M(I i) displayTextSuffix: "<>", inlineDescription: "N", sourceCodeKind: SourceCodeKind.Regular); - } [Fact] - public async Task TestComplexConstraint_ShownOnInterfaceMatchThroughChainedTypeParameter() - { - await VerifyItemExistsAsync( + public Task TestComplexConstraint_ShownOnInterfaceMatchThroughChainedTypeParameter() + => VerifyItemExistsAsync( """ interface I { @@ -2132,12 +2122,10 @@ void M(I i) displayTextSuffix: "<>", inlineDescription: "N", sourceCodeKind: SourceCodeKind.Regular); - } [Fact] - public async Task TestComplexConstraint_ShownOnInterfaceMatchThroughChainedTypeParameter_BaseInterface() - { - await VerifyItemExistsAsync( + public Task TestComplexConstraint_ShownOnInterfaceMatchThroughChainedTypeParameter_BaseInterface() + => VerifyItemExistsAsync( """ interface I1 { @@ -2166,12 +2154,10 @@ void M(I2 i) displayTextSuffix: "<>", inlineDescription: "N", sourceCodeKind: SourceCodeKind.Regular); - } [Fact] - public async Task TestComplexConstraint_ShownOnExactBaseTypeConstraintMatch() - { - await VerifyItemExistsAsync( + public Task TestComplexConstraint_ShownOnExactBaseTypeConstraintMatch() + => VerifyItemExistsAsync( """ class C { @@ -2196,12 +2182,10 @@ void M(C i) displayTextSuffix: "<>", inlineDescription: "N", sourceCodeKind: SourceCodeKind.Regular); - } [Fact] - public async Task TestComplexConstraint_ShownOnBaseTypeMatchThroughChainedTypeParameter() - { - await VerifyItemExistsAsync( + public Task TestComplexConstraint_ShownOnBaseTypeMatchThroughChainedTypeParameter() + => VerifyItemExistsAsync( """ class C { @@ -2226,12 +2210,10 @@ void M(C i) displayTextSuffix: "<>", inlineDescription: "N", sourceCodeKind: SourceCodeKind.Regular); - } [Fact] - public async Task TestComplexConstraint_ShownOnBaseTypeMatchThroughChainedTypeParameter_InheritedType() - { - await VerifyItemExistsAsync( + public Task TestComplexConstraint_ShownOnBaseTypeMatchThroughChainedTypeParameter_InheritedType() + => VerifyItemExistsAsync( """ class C1 { @@ -2260,12 +2242,10 @@ void M(C2 i) displayTextSuffix: "<>", inlineDescription: "N", sourceCodeKind: SourceCodeKind.Regular); - } [Fact] - public async Task TestComplexConstraint_ShownOnBaseTypeMatchThroughChainedTypeParameter_InheritedBaseTypeAndInterface() - { - await VerifyItemExistsAsync( + public Task TestComplexConstraint_ShownOnBaseTypeMatchThroughChainedTypeParameter_InheritedBaseTypeAndInterface() + => VerifyItemExistsAsync( """ interface I1 { @@ -2298,7 +2278,6 @@ void M(C1 i) displayTextSuffix: "<>", inlineDescription: "N", sourceCodeKind: SourceCodeKind.Regular); - } private Task VerifyImportItemExistsAsync(string markup, string expectedItem, string inlineDescription, Glyph? glyph = null, string displayTextSuffix = null, string expectedDescriptionOrNull = null, List expectedFilters = null) => VerifyItemExistsAsync(markup, expectedItem, displayTextSuffix: displayTextSuffix, glyph: glyph, inlineDescription: inlineDescription, expectedDescriptionOrNull: expectedDescriptionOrNull, isComplexTextEdit: true, matchingFilters: expectedFilters); diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ExternAliasCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ExternAliasCompletionProviderTests.cs index a316963f66f43..10a68a095e149 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ExternAliasCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ExternAliasCompletionProviderTests.cs @@ -20,59 +20,42 @@ internal override Type GetCompletionProviderType() => typeof(ExternAliasCompletionProvider); [Fact] - public async Task NoAliases() - { - await VerifyNoItemsExistAsync(""" + public Task NoAliases() + => VerifyNoItemsExistAsync(""" extern alias $$ class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44423")] - public async Task ExternAlias() - { - var markup = """ + public Task ExternAlias() + => VerifyItemWithAliasedMetadataReferencesAsync(""" extern alias $$ - """; - await VerifyItemWithAliasedMetadataReferencesAsync(markup, "goo", "goo", 1, "C#", "C#"); - } + """, "goo", "goo", 1, "C#", "C#"); [Fact] - public async Task NotAfterExternAlias() - { - var markup = """ + public Task NotAfterExternAlias() + => VerifyItemWithAliasedMetadataReferencesAsync(""" extern alias goo $$ - """; - await VerifyItemWithAliasedMetadataReferencesAsync(markup, "goo", "goo", 0, "C#", "C#"); - } + """, "goo", "goo", 0, "C#", "C#"); [Fact] - public async Task NotGlobal() - { - var markup = """ + public Task NotGlobal() + => VerifyItemWithAliasedMetadataReferencesAsync(""" extern alias $$ - """; - await VerifyItemWithAliasedMetadataReferencesAsync(markup, "goo", "global", 0, "C#", "C#"); - } + """, "goo", "global", 0, "C#", "C#"); [Fact] - public async Task NotIfAlreadyUsed() - { - var markup = """ + public Task NotIfAlreadyUsed() + => VerifyItemWithAliasedMetadataReferencesAsync(""" extern alias goo; extern alias $$ - """; - await VerifyItemWithAliasedMetadataReferencesAsync(markup, "goo", "goo", 0, "C#", "C#"); - } + """, "goo", "goo", 0, "C#", "C#"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1075278")] - public async Task NotInComment() - { - var markup = """ + public Task NotInComment() + => VerifyNoItemsExistAsync(""" extern alias // $$ - """; - await VerifyNoItemsExistAsync(markup); - } + """); } diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/FunctionPointerUnmanagedCallingConventionCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/FunctionPointerUnmanagedCallingConventionCompletionProviderTests.cs index 4b23996b6254b..d3a7a2c51b04f 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/FunctionPointerUnmanagedCallingConventionCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/FunctionPointerUnmanagedCallingConventionCompletionProviderTests.cs @@ -18,9 +18,8 @@ public sealed class FunctionPointerUnmanagedCallingConventionCompletionProviderT internal override Type GetCompletionProviderType() => typeof(FunctionPointerUnmanagedCallingConventionCompletionProvider); [Fact] - public async Task TypeFound() - { - var markup = """ + public Task TypeFound() + => VerifyItemExistsAsync(""" namespace System.Runtime.CompilerServices { public class CallConvUnitTest { } @@ -30,14 +29,11 @@ class C { delegate* unmanaged[$$] f; } - """; - await VerifyItemExistsAsync(markup, "UnitTest"); - } + """, "UnitTest"); [Fact] - public async Task TypeFoundSecondCallingConvention() - { - var markup = """ + public Task TypeFoundSecondCallingConvention() + => VerifyItemExistsAsync(""" namespace System.Runtime.CompilerServices { public class CallConvUnitTest { } @@ -47,20 +43,15 @@ class C { delegate* unmanaged[Thiscall, $$] f; } - """; - await VerifyItemExistsAsync(markup, "UnitTest"); - } + """, "UnitTest"); [Theory] [InlineData("Cdecl")] [InlineData("Fastcall")] [InlineData("Thiscall")] [InlineData("Stdcall")] - public async Task PredefinedCallingConventionFound(string callingConvention) - { - // We explicitly create a project with no references (not even common references) to ensure we - // get the defaults - var markup = """ + public Task PredefinedCallingConventionFound(string callingConvention) + => VerifyItemExistsAsync(""" @@ -71,7 +62,5 @@ class C - """; - await VerifyItemExistsAsync(markup, callingConvention, glyph: Glyph.Keyword); - } + """, callingConvention, glyph: Glyph.Keyword); } diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/IndexerCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/IndexerCompletionProviderTests.cs index 5c94cda1f28e2..025ddd62965d7 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/IndexerCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/IndexerCompletionProviderTests.cs @@ -19,9 +19,8 @@ internal override Type GetCompletionProviderType() => typeof(UnnamedSymbolCompletionProvider); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task IndexerIsSuggestedAfterDot() - { - await VerifyItemExistsAsync(""" + public Task IndexerIsSuggestedAfterDot() + => VerifyItemExistsAsync(""" public class C { public int this[int i] => i; @@ -36,12 +35,10 @@ public static void Main() } } """, "this", displayTextSuffix: "[]", matchingFilters: [FilterSet.PropertyFilter]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task IndexerIsSuggestedAfterDotForString() - { - await VerifyItemExistsAsync(""" + public Task IndexerIsSuggestedAfterDotForString() + => VerifyItemExistsAsync(""" public class Program { public static void Main(string s) @@ -50,12 +47,10 @@ public static void Main(string s) } } """, "this", displayTextSuffix: "[]", matchingFilters: [FilterSet.PropertyFilter]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task IndexerIsNotSuggestedOnStaticAccess() - { - await VerifyNoItemsExistAsync(""" + public Task IndexerIsNotSuggestedOnStaticAccess() + => VerifyNoItemsExistAsync(""" public class C { public int this[int i] => i; @@ -69,12 +64,10 @@ public static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task IndexerIsNotSuggestedInNameOfContext() - { - await VerifyNoItemsExistAsync(""" + public Task IndexerIsNotSuggestedInNameOfContext() + => VerifyNoItemsExistAsync(""" public class C { public int this[int i] => i; @@ -89,12 +82,10 @@ public static void Main() } } """); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task IndexerSuggestionCommitsOpenAndClosingBraces() - { - await VerifyCustomCommitProviderAsync(""" + public Task IndexerSuggestionCommitsOpenAndClosingBraces() + => VerifyCustomCommitProviderAsync(""" public class C { public int this[int i] => i; @@ -123,12 +114,10 @@ public static void Main() } } """); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task IndexerWithTwoParametersSuggestionCommitsOpenAndClosingBraces() - { - await VerifyCustomCommitProviderAsync(""" + public Task IndexerWithTwoParametersSuggestionCommitsOpenAndClosingBraces() + => VerifyCustomCommitProviderAsync(""" public class C { public int this[int x, int y] => i; @@ -157,7 +146,6 @@ public static void Main() } } """); - } [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] [InlineData("c.$$", @@ -184,38 +172,36 @@ public static void Main() "((C)c)[$$]")] [InlineData("(true ? c : c).$$", "(true ? c : c)[$$]")] - public async Task IndexerCompletionForDifferentExpressions(string expression, string fixedCode) - { - await VerifyCustomCommitProviderAsync($@" -public class C -{{ - public int this[int i] => i; -}} - -public class Program -{{ - public static void Main() - {{ - var c = new C(); - {expression} - }} -}} -", "this", @$" -public class C -{{ - public int this[int i] => i; -}} - -public class Program -{{ - public static void Main() - {{ - var c = new C(); - {fixedCode} - }} -}} -"); - } + public Task IndexerCompletionForDifferentExpressions(string expression, string fixedCode) + => VerifyCustomCommitProviderAsync($$""" + public class C + { + public int this[int i] => i; + } + + public class Program + { + public static void Main() + { + var c = new C(); + {{expression}} + } + } + """, "this", $$""" + public class C + { + public int this[int i] => i; + } + + public class Program + { + public static void Main() + { + var c = new C(); + {{fixedCode}} + } + } + """); [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] [InlineData("/* Leading trivia */c.$$", @@ -224,43 +210,40 @@ public static void Main() "c[$$] /* Trailing trivia */")] [InlineData("c./* Trivia in between */$$", "c[$$]/* Trivia in between */")] - public async Task IndexerCompletionTriviaTest(string expression, string fixedCode) - { - await VerifyCustomCommitProviderAsync($@" -public class C -{{ - public int this[int i] => i; -}} - -public class Program -{{ - public static void Main() - {{ - var c = new C(); - {expression} - }} -}} -", "this", @$" -public class C -{{ - public int this[int i] => i; -}} - -public class Program -{{ - public static void Main() - {{ - var c = new C(); - {fixedCode} - }} -}} -"); - } + public Task IndexerCompletionTriviaTest(string expression, string fixedCode) + => VerifyCustomCommitProviderAsync($$""" + public class C + { + public int this[int i] => i; + } + + public class Program + { + public static void Main() + { + var c = new C(); + {{expression}} + } + } + """, "this", $$""" + public class C + { + public int this[int i] => i; + } + + public class Program + { + public static void Main() + { + var c = new C(); + {{fixedCode}} + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task IndexerDescriptionIncludesDocCommentsAndOverloadsHint() - { - await VerifyItemExistsAsync(""" + public Task IndexerDescriptionIncludesDocCommentsAndOverloadsHint() + => VerifyItemExistsAsync(""" public class C { /// @@ -286,14 +269,14 @@ public static void Main() c.$$ } } - """, "this", displayTextSuffix: "[]", expectedDescriptionOrNull: @$"int C.this[int i] {{ get; }} (+ 1 {FeaturesResources.overload}) -Returns the index i"); - } + """, "this", displayTextSuffix: "[]", expectedDescriptionOrNull: $$""" + int C.this[int i] { get; } (+ 1 {{FeaturesResources.overload}}) + Returns the index i + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task IndexerOfBaseTypeIsSuggestedAfterDot() - { - await VerifyItemExistsAsync(""" + public Task IndexerOfBaseTypeIsSuggestedAfterDot() + => VerifyItemExistsAsync(""" public class Base { public int this[int i] => i; @@ -311,12 +294,10 @@ public static void Main() } } """, "this", displayTextSuffix: "[]"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task IndexerOfBaseTypeIsNotSuggestedIfNotAccessible() - { - await VerifyNoItemsExistAsync(""" + public Task IndexerOfBaseTypeIsNotSuggestedIfNotAccessible() + => VerifyNoItemsExistAsync(""" public class Base { protected int this[int i] => i; @@ -334,12 +315,10 @@ public static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task IndexerIsSuggestedOnString() - { - await VerifyItemExistsAsync(""" + public Task IndexerIsSuggestedOnString() + => VerifyItemExistsAsync(""" public class Program { public static void Main() @@ -349,7 +328,6 @@ public static void Main() } } """, "this", displayTextSuffix: "[]"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] public async Task TestEditorBrowsableOnIndexerIsRespected_EditorBrowsableStateNever() @@ -485,9 +463,8 @@ await VerifyItemInEditorBrowsableContextsAsync( } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task IndexerNullForgivingOperatorHandling() - { - await VerifyCustomCommitProviderAsync(""" + public Task IndexerNullForgivingOperatorHandling() + => VerifyCustomCommitProviderAsync(""" #nullable enable public class C @@ -520,5 +497,4 @@ public static void Main() } } """); - } } diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/KeywordCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/KeywordCompletionProviderTests.cs index 4393d38b050fb..d7208abf6a0c4 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/KeywordCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/KeywordCompletionProviderTests.cs @@ -36,135 +36,95 @@ public async Task SendEnterThroughToEditorTest() } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task InEmptyFile() - { - var markup = "$$"; - - await VerifyAnyItemExistsAsync(markup); - } + public Task InEmptyFile() + => VerifyAnyItemExistsAsync("$$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task NotInInactiveCode() - { - var markup = """ + public Task NotInInactiveCode() + => VerifyNoItemsExistAsync(""" class C { void M() { #if false $$ - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task NotInCharLiteral() - { - var markup = """ + public Task NotInCharLiteral() + => VerifyNoItemsExistAsync(""" class C { void M() { var c = '$$'; - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task NotInUnterminatedCharLiteral() - { - var markup = """ + public Task NotInUnterminatedCharLiteral() + => VerifyNoItemsExistAsync(""" class C { void M() { var c = '$$ - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task NotInUnterminatedCharLiteralAtEndOfFile() - { - var markup = """ + public Task NotInUnterminatedCharLiteralAtEndOfFile() + => VerifyNoItemsExistAsync(""" class C { void M() { var c = '$$ - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task NotInString() - { - var markup = """ + public Task NotInString() + => VerifyNoItemsExistAsync(""" class C { void M() { var s = "$$"; - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task NotInStringInDirective() - { - var markup = """ + public Task NotInStringInDirective() + => VerifyNoItemsExistAsync(""" #r "$$" - """; - - await VerifyNoItemsExistAsync(markup, SourceCodeKind.Script); - } + """, SourceCodeKind.Script); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task NotInUnterminatedString() - { - var markup = """ + public Task NotInUnterminatedString() + => VerifyNoItemsExistAsync(""" class C { void M() { var s = "$$ - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task NotInUnterminatedStringInDirective() - { - var markup = """ + public Task NotInUnterminatedStringInDirective() + => VerifyNoItemsExistAsync(""" #r "$$" - """; - - await VerifyNoItemsExistAsync(markup, SourceCodeKind.Script); - } + """, SourceCodeKind.Script); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task NotInUnterminatedStringAtEndOfFile() - { - var markup = """ + public Task NotInUnterminatedStringAtEndOfFile() + => VerifyNoItemsExistAsync(""" class C { void M() { var s = "$$ - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task NotInVerbatimString() - { - var markup = """ + public Task NotInVerbatimString() + => VerifyNoItemsExistAsync(""" class C { void M() @@ -172,70 +132,50 @@ void M() var s = @" $$ "; - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task NotInUnterminatedVerbatimString() - { - var markup = """ + public Task NotInUnterminatedVerbatimString() + => VerifyNoItemsExistAsync(""" class C { void M() { var s = @" $$ - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task NotInUnterminatedVerbatimStringAtEndOfFile() - { - var markup = """ + public Task NotInUnterminatedVerbatimStringAtEndOfFile() + => VerifyNoItemsExistAsync(""" class C { void M() { var s = @"$$ - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task NotInSingleLineComment() - { - var markup = """ + public Task NotInSingleLineComment() + => VerifyNoItemsExistAsync(""" class C { void M() { // $$ - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task NotInSingleLineCommentAtEndOfFile() - { - var markup = """ + public Task NotInSingleLineCommentAtEndOfFile() + => VerifyNoItemsExistAsync(""" namespace A { }// $$ - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task NotInMutliLineComment() - { - var markup = """ + public Task NotInMutliLineComment() + => VerifyNoItemsExistAsync(""" class C { void M() @@ -243,10 +183,7 @@ void M() /* $$ */ - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968256")] @@ -283,71 +220,56 @@ void goo() { [WorkItem("https://github.com/dotnet/roslyn/issues/7768")] [WorkItem("https://github.com/dotnet/roslyn/issues/8228")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task FormattingAfterCompletionCommit_AfterGetAccessorInSingleLineIncompleteProperty() - { - var markupBeforeCommit = """ + public Task FormattingAfterCompletionCommit_AfterGetAccessorInSingleLineIncompleteProperty() + => VerifyProviderCommitAsync(""" class Program { int P {g$$ void Main() { } } - """; - - var expectedCodeAfterCommit = """ + """, "get", """ class Program { int P {get; void Main() { } } - """; - await VerifyProviderCommitAsync(markupBeforeCommit, "get", expectedCodeAfterCommit, commitChar: ';'); - } + """, commitChar: ';'); [WorkItem("https://github.com/dotnet/roslyn/issues/7768")] [WorkItem("https://github.com/dotnet/roslyn/issues/8228")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task FormattingAfterCompletionCommit_AfterBothAccessorsInSingleLineIncompleteProperty() - { - var markupBeforeCommit = """ + public Task FormattingAfterCompletionCommit_AfterBothAccessorsInSingleLineIncompleteProperty() + => VerifyProviderCommitAsync(""" class Program { int P {get;set$$ void Main() { } } - """; - - var expectedCodeAfterCommit = """ + """, "set", """ class Program { int P {get;set; void Main() { } } - """; - await VerifyProviderCommitAsync(markupBeforeCommit, "set", expectedCodeAfterCommit, commitChar: ';'); - } + """, commitChar: ';'); [WorkItem("https://github.com/dotnet/roslyn/issues/7768")] [WorkItem("https://github.com/dotnet/roslyn/issues/8228")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task FormattingAfterCompletionCommit_InSingleLineMethod() - { - var markupBeforeCommit = """ + public Task FormattingAfterCompletionCommit_InSingleLineMethod() + => VerifyProviderCommitAsync(""" class Program { public static void Test() { return$$ void Main() { } } - """; - - var expectedCodeAfterCommit = """ + """, "return", """ class Program { public static void Test() { return; void Main() { } } - """; - await VerifyProviderCommitAsync(markupBeforeCommit, "return", expectedCodeAfterCommit, commitChar: ';'); - } + """, commitChar: ';'); [WorkItem("https://github.com/dotnet/roslyn/issues/14218")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] @@ -388,69 +310,49 @@ class C } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task PrivateProtectedModifier() - { - var text = """ + public Task PrivateProtectedModifier() + => VerifyItemExistsAsync(""" class C { private $$ } - """; - - await VerifyItemExistsAsync(text, "protected"); - } + """, "protected"); [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task ProtectedPrivateModifier() - { - var text = """ + public Task ProtectedPrivateModifier() + => VerifyItemExistsAsync(""" class C { protected $$ } - """; - - await VerifyItemExistsAsync(text, "private"); - } + """, "private"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("https://github.com/dotnet/roslyn/issues/34774")] - public async Task DoNotSuggestEventAfterReadonlyInClass() - { - var markup = - """ + public Task DoNotSuggestEventAfterReadonlyInClass() + => VerifyItemIsAbsentAsync(""" class C { readonly $$ } - """; - await VerifyItemIsAbsentAsync(markup, "event"); - } + """, "event"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("https://github.com/dotnet/roslyn/issues/34774")] - public async Task DoNotSuggestEventAfterReadonlyInInterface() - { - var markup = - """ + public Task DoNotSuggestEventAfterReadonlyInInterface() + => VerifyItemIsAbsentAsync(""" interface C { readonly $$ } - """; - await VerifyItemIsAbsentAsync(markup, "event"); - } + """, "event"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("https://github.com/dotnet/roslyn/issues/34774")] - public async Task SuggestEventAfterReadonlyInStruct() - { - var markup = - """ + public Task SuggestEventAfterReadonlyInStruct() + => VerifyItemExistsAsync(""" struct C { readonly $$ } - """; - await VerifyItemExistsAsync(markup, "event"); - } + """, "event"); [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("https://github.com/dotnet/roslyn/issues/39265")] @@ -464,12 +366,13 @@ public async Task SuggestReadonlyPropertyAccessor(string declarationType, bool p { var markup = -$@"{declarationType} C {{ - int X {{ - $$ - }} -}} -"; + $$""" + {{declarationType}} C { + int X { + $$ + } + } + """; if (present) { await VerifyItemExistsAsync(markup, "readonly"); @@ -489,12 +392,13 @@ public async Task SuggestReadonlyBeforePropertyAccessor(string declarationType, { var markup = -$@"{declarationType} C {{ - int X {{ - $$ get; - }} -}} -"; + $$""" + {{declarationType}} C { + int X { + $$ get; + } + } + """; if (present) { await VerifyItemExistsAsync(markup, "readonly"); @@ -514,12 +418,13 @@ public async Task SuggestReadonlyIndexerAccessor(string declarationType, bool pr { var markup = -$@"{declarationType} C {{ - int this[int i] {{ - $$ - }} -}} -"; + $$""" + {{declarationType}} C { + int this[int i] { + $$ + } + } + """; if (present) { await VerifyItemExistsAsync(markup, "readonly"); @@ -539,12 +444,13 @@ public async Task SuggestReadonlyEventAccessor(string declarationType, bool pres { var markup = -$@"{declarationType} C {{ - event System.Action E {{ - $$ - }} -}} -"; + $$""" + {{declarationType}} C { + event System.Action E { + $$ + } + } + """; if (present) { await VerifyItemExistsAsync(markup, "readonly"); @@ -574,31 +480,27 @@ int X { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("https://github.com/dotnet/roslyn/issues/39265")] - public async Task SuggestReadonlyMethodInStruct() - { - - var markup = - """ + public Task SuggestReadonlyMethodInStruct() + => VerifyItemExistsAsync(""" struct C { public $$ void M() {} } - """; - await VerifyItemExistsAsync(markup, "readonly"); - } + """, "readonly"); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/58921"), CombinatorialData, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastExpressionThatMightBeParenthesizedExpression1(bool hasNewline) { var markup = -$@" -class C -{{ - void M() - {{ - var data = (n$$) {(hasNewline ? Environment.NewLine : string.Empty)} M(); - }} -}}"; + $$""" + class C + { + void M() + { + var data = (n$$) {{(hasNewline ? Environment.NewLine : string.Empty)}} M(); + } + } + """; if (hasNewline) { @@ -632,11 +534,13 @@ public async Task TestInCastExpressionThatMightBeParenthesizedExpression2(bool h { var markup = -$@"class C -{{ - bool Prop => (t$$) {(hasExpression ? "n" : string.Empty)} - private int n; -}}"; + $$""" + class C + { + bool Prop => (t$$) {{(hasExpression ? "n" : string.Empty)}} + private int n; + } + """; if (hasExpression) { await VerifyItemIsAbsentAsync(markup, "new"); @@ -668,244 +572,165 @@ public async Task TestInCastExpressionThatMightBeParenthesizedExpression2(bool h [InlineData("struct")] [InlineData("record")] [InlineData("record struct")] - public async Task SuggestRequiredInClassOrStructOrRecord(string type) - { - var markup = $$""" + public Task SuggestRequiredInClassOrStructOrRecord(string type) + => VerifyItemExistsAsync($$""" {{type}} C { $$ - """; - - await VerifyItemExistsAsync(markup, "required"); - } + """, "required"); [Fact] - public async Task DoNotSuggestRequiredInInterface() - { - var markup = $$""" + public Task DoNotSuggestRequiredInInterface() + => VerifyItemIsAbsentAsync($$""" interface I { public $$ - """; - - await VerifyItemIsAbsentAsync(markup, "required"); - } + """, "required"); [Theory] [InlineData("static")] [InlineData("const")] [InlineData("readonly")] - public async Task DoNotSuggestRequiredOnFilteredKeywordMembers(string keyword) - { - var markup = $$""" + public Task DoNotSuggestRequiredOnFilteredKeywordMembers(string keyword) + => VerifyItemIsAbsentAsync($$""" class C { {{keyword}} $$ - """; - - await VerifyItemIsAbsentAsync(markup, "required"); - } + """, "required"); [Theory] [InlineData("static")] [InlineData("const")] [InlineData("readonly")] - public async Task DoNotSuggestFilteredKeywordsOnRequiredMembers(string keyword) - { - var markup = $$""" + public Task DoNotSuggestFilteredKeywordsOnRequiredMembers(string keyword) + => VerifyItemIsAbsentAsync($$""" class C { required $$ - """; - - await VerifyItemIsAbsentAsync(markup, keyword); - } + """, keyword); [Fact] - public async Task DoNotSuggestRequiredOnRequiredMembers() - { - var markup = $$""" + public Task DoNotSuggestRequiredOnRequiredMembers() + => VerifyItemIsAbsentAsync($$""" class C { required $$ - """; - - await VerifyItemIsAbsentAsync(markup, "required"); - } + """, "required"); [Fact] - public async Task SuggestFileOnTypes() - { - var markup = $$""" + public Task SuggestFileOnTypes() + => VerifyItemExistsAsync($$""" $$ class C { } - """; - - await VerifyItemExistsAsync(markup, "file"); - } + """, "file"); [Fact] - public async Task DoNotSuggestFileAfterFile() - { - var markup = $$""" + public Task DoNotSuggestFileAfterFile() + => VerifyItemIsAbsentAsync($$""" file $$ - """; - - await VerifyItemIsAbsentAsync(markup, "file"); - } + """, "file"); [Fact] - public async Task SuggestFileAfterReadonly() - { - // e.g. 'readonly file struct X { }' - var markup = $$""" + public Task SuggestFileAfterReadonly() + => VerifyItemExistsAsync($$""" readonly $$ - """; - - await VerifyItemExistsAsync(markup, "file"); - } + """, "file"); [Fact] - public async Task SuggestFileBeforeFileType() - { - var markup = $$""" + public Task SuggestFileBeforeFileType() + => VerifyItemExistsAsync($$""" $$ file class C { } - """; - - // it might seem like we want to prevent 'file file class', - // but it's likely the user is declaring a file-local type above an existing file-local type here. - await VerifyItemExistsAsync(markup, "file"); - } + """, "file"); [Fact] - public async Task SuggestFileBeforeDelegate() - { - var markup = $$""" + public Task SuggestFileBeforeDelegate() + => VerifyItemExistsAsync($$""" $$ delegate - """; - - await VerifyItemExistsAsync(markup, "file"); - } + """, "file"); [Fact] - public async Task DoNotSuggestFileOnNestedTypes() - { - var markup = $$""" + public Task DoNotSuggestFileOnNestedTypes() + => VerifyItemIsAbsentAsync($$""" class Outer { $$ class C { } } - """; - - await VerifyItemIsAbsentAsync(markup, "file"); - } + """, "file"); [Fact] - public async Task DoNotSuggestFileOnNonTypeMembers() - { - var markup = $$""" + public Task DoNotSuggestFileOnNonTypeMembers() + => VerifyItemIsAbsentAsync($$""" class C { $$ } - """; - - await VerifyItemIsAbsentAsync(markup, "file"); - } + """, "file"); [Theory] [InlineData("public")] [InlineData("internal")] [InlineData("protected")] [InlineData("private")] - public async Task DoNotSuggestFileAfterFilteredKeywords(string keyword) - { - var markup = $$""" + public Task DoNotSuggestFileAfterFilteredKeywords(string keyword) + => VerifyItemIsAbsentAsync($$""" {{keyword}} $$ - """; - - await VerifyItemIsAbsentAsync(markup, "file"); - } + """, "file"); [Theory] [InlineData("public")] [InlineData("internal")] [InlineData("protected")] [InlineData("private")] - public async Task DoNotSuggestFilteredKeywordsAfterFile(string keyword) - { - var markup = $$""" + public Task DoNotSuggestFilteredKeywordsAfterFile(string keyword) + => VerifyItemIsAbsentAsync($$""" file $$ - """; - - await VerifyItemIsAbsentAsync(markup, keyword); - } + """, keyword); [Fact] - public async Task SuggestFileInFileScopedNamespace() - { - var markup = $$""" + public Task SuggestFileInFileScopedNamespace() + => VerifyItemExistsAsync($$""" namespace NS; $$ - """; - - await VerifyItemExistsAsync(markup, "file"); - } + """, "file"); [Fact] - public async Task SuggestFileInNamespace() - { - var markup = $$""" + public Task SuggestFileInNamespace() + => VerifyItemExistsAsync($$""" namespace NS { $$ } - """; - - await VerifyItemExistsAsync(markup, "file"); - } + """, "file"); [Fact] - public async Task SuggestFileAfterClass() - { - var markup = $$""" + public Task SuggestFileAfterClass() + => VerifyItemExistsAsync($$""" file class C { } $$ - """; - - await VerifyItemExistsAsync(markup, "file"); - } + """, "file"); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67985")] [MemberData(nameof(TypeDeclarationKeywords))] - public async Task TestTypeDeclarationKeywordsNotAfterUsingUnsafe(string keyword) - { - await VerifyItemIsAbsentAsync("using unsafe $$", keyword); - } + public Task TestTypeDeclarationKeywordsNotAfterUsingUnsafe(string keyword) + => VerifyItemIsAbsentAsync("using unsafe $$", keyword); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67985")] [MemberData(nameof(TypeDeclarationKeywords))] - public async Task TestTypeDeclarationKeywordsNotAfterUsingStaticUnsafe(string keyword) - { - await VerifyItemIsAbsentAsync("using static unsafe $$", keyword); - } + public Task TestTypeDeclarationKeywordsNotAfterUsingStaticUnsafe(string keyword) + => VerifyItemIsAbsentAsync("using static unsafe $$", keyword); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67985")] [MemberData(nameof(TypeDeclarationKeywords))] - public async Task TestTypeDeclarationKeywordsNotAfterGlobalUsingUnsafe(string keyword) - { - await VerifyItemIsAbsentAsync("global using unsafe $$", keyword); - } + public Task TestTypeDeclarationKeywordsNotAfterGlobalUsingUnsafe(string keyword) + => VerifyItemIsAbsentAsync("global using unsafe $$", keyword); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67985")] [MemberData(nameof(TypeDeclarationKeywords))] - public async Task TestTypeDeclarationKeywordsNotAfterGlobalUsingStaticUnsafe(string keyword) - { - await VerifyItemIsAbsentAsync("global using static unsafe $$", keyword); - } + public Task TestTypeDeclarationKeywordsNotAfterGlobalUsingStaticUnsafe(string keyword) + => VerifyItemIsAbsentAsync("global using static unsafe $$", keyword); public static IEnumerable TypeDeclarationKeywords() { diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/NamedParameterCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/NamedParameterCompletionProviderTests.cs index 2c36187ebdc3c..aeeecc6ddd53c 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/NamedParameterCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/NamedParameterCompletionProviderTests.cs @@ -60,9 +60,8 @@ void Bar() } [Fact] - public async Task InObjectCreation() - { - var markup = """ + public Task InObjectCreation() + => VerifyItemExistsAsync(""" class Goo { public Goo(int a = 42) @@ -73,15 +72,11 @@ void Bar() var b = new Goo($$ } } - """; - - await VerifyItemExistsAsync(markup, "a", displayTextSuffix: ":"); - } + """, "a", displayTextSuffix: ":"); [Fact] - public async Task InBaseConstructor() - { - var markup = """ + public Task InBaseConstructor() + => VerifyItemExistsAsync(""" class Goo { public Goo(int a = 42) @@ -92,15 +87,11 @@ class DogBed : Goo { public DogBed(int b) : base($$ } - """; - - await VerifyItemExistsAsync(markup, "a", displayTextSuffix: ":"); - } + """, "a", displayTextSuffix: ":"); [Fact] - public async Task InvocationExpression() - { - var markup = """ + public Task InvocationExpression() + => VerifyItemExistsAsync(""" class Goo { void Bar(int a) @@ -108,15 +99,11 @@ void Bar(int a) Bar($$ } } - """; - - await VerifyItemExistsAsync(markup, "a", displayTextSuffix: ":"); - } + """, "a", displayTextSuffix: ":"); [Fact] - public async Task InvocationExpressionAfterComma() - { - var markup = """ + public Task InvocationExpressionAfterComma() + => VerifyItemExistsAsync(""" class Goo { void Bar(int a, string b) @@ -124,15 +111,11 @@ void Bar(int a, string b) Bar(b:"", $$ } } - """; - - await VerifyItemExistsAsync(markup, "a", displayTextSuffix: ":"); - } + """, "a", displayTextSuffix: ":"); [Fact] - public async Task ElementAccessExpression() - { - var markup = """ + public Task ElementAccessExpression() + => VerifyItemExistsAsync(""" class SampleCollection { private T[] arr = new T[100]; @@ -157,10 +140,7 @@ static void Main(string[] args) stringCollection[$$ } } - """; - - await VerifyItemExistsAsync(markup, "i", displayTextSuffix: ":"); - } + """, "i", displayTextSuffix: ":"); [Fact] public async Task PartialMethods() @@ -205,9 +185,8 @@ static void Caller() } [Fact] - public async Task NotAfterColon() - { - var markup = """ + public Task NotAfterColon() + => VerifyNoItemsExistAsync(""" class Goo { void Bar(int a, string b) @@ -215,15 +194,11 @@ void Bar(int a, string b) Bar(a:$$ } } - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544292")] - public async Task NotInCollectionInitializers() - { - var markup = """ + public Task NotInCollectionInitializers() + => VerifyNoItemsExistAsync(""" using System.Collections.Generic; class Goo { @@ -232,10 +207,7 @@ void Bar(List integers) Bar(integers: new List { 10, 11,$$ 12 }); } } - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544191")] public async Task FilteringOverloadsByCallSite() @@ -377,9 +349,8 @@ void Method(object obj, bool b = false, string str = "") } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529369")] - public async Task VerbatimIdentifierNotAKeyword() - { - var markup = """ + public Task VerbatimIdentifierNotAKeyword() + => VerifyItemExistsAsync(""" class Program { void Goo(int @integer) @@ -387,14 +358,11 @@ void Goo(int @integer) Goo(@i$$ } } - """; - await VerifyItemExistsAsync(markup, "integer", displayTextSuffix: ":"); - } + """, "integer", displayTextSuffix: ":"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544209")] - public async Task DescriptionStringInMethodOverloads() - { - var markup = """ + public Task DescriptionStringInMethodOverloads() + => VerifyItemExistsAsync(""" class Class1 { void Test() @@ -408,15 +376,12 @@ void Goo(string obj = "hello") void Goo(bool boolean = false, Class1 obj = default(Class1)) { } } - """; - await VerifyItemExistsAsync(markup, "obj", displayTextSuffix: ":", + """, "obj", displayTextSuffix: ":", expectedDescriptionOrNull: $"({FeaturesResources.parameter}) Class1 obj = default(Class1)"); - } [Fact] - public async Task InDelegates() - { - var markup = """ + public Task InDelegates() + => VerifyItemExistsAsync(""" public delegate void Del(string message); class Program @@ -432,14 +397,11 @@ static void Main(string[] args) handler($$ } } - """; - await VerifyItemExistsAsync(markup, "message", displayTextSuffix: ":"); - } + """, "message", displayTextSuffix: ":"); [Fact] - public async Task InDelegateInvokeSyntax() - { - var markup = """ + public Task InDelegateInvokeSyntax() + => VerifyItemExistsAsync(""" public delegate void Del(string message); class Program @@ -455,14 +417,11 @@ static void Main(string[] args) handler.Invoke($$ } } - """; - await VerifyItemExistsAsync(markup, "message", displayTextSuffix: ":"); - } + """, "message", displayTextSuffix: ":"); [Fact] - public async Task NotInComment() - { - var markup = """ + public Task NotInComment() + => VerifyNoItemsExistAsync(""" public class Test { static void Main() @@ -472,14 +431,11 @@ static void Main() } static void M(int x, int y) { } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task CommitWithColonWordFullyTyped() - { - var markup = """ + public Task CommitWithColonWordFullyTyped() + => VerifyProviderCommitAsync(""" class Program { static void Main(string[] args) @@ -487,9 +443,7 @@ static void Main(string[] args) Main(args$$) } } - """; - - var expected = """ + """, "args:", """ class Program { static void Main(string[] args) @@ -497,14 +451,11 @@ static void Main(string[] args) Main(args:) } } - """; - await VerifyProviderCommitAsync(markup, "args:", expected, ':'); - } + """, ':'); [Fact] - public async Task CommitWithColonWordPartiallyTyped() - { - var markup = """ + public Task CommitWithColonWordPartiallyTyped() + => VerifyProviderCommitAsync(""" class Program { static void Main(string[] args) @@ -512,9 +463,7 @@ static void Main(string[] args) Main(arg$$) } } - """; - - var expected = """ + """, "args:", """ class Program { static void Main(string[] args) @@ -522,7 +471,5 @@ static void Main(string[] args) Main(args:) } } - """; - await VerifyProviderCommitAsync(markup, "args:", expected, ':'); - } + """, ':'); } diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ObjectCreationCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ObjectCreationCompletionProviderTests.cs index 7849b8d3c1a26..67c4961b78388 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ObjectCreationCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ObjectCreationCompletionProviderTests.cs @@ -21,113 +21,99 @@ internal override Type GetCompletionProviderType() => typeof(ObjectCreationCompletionProvider); [Fact] - public async Task InObjectCreation() - { - var markup = @" -class MyGeneric { } - -void goo() -{ - MyGeneric goo = new $$ -}"; + public Task InObjectCreation() + => VerifyItemExistsAsync(""" + class MyGeneric { } - await VerifyItemExistsAsync(markup, "MyGeneric"); - } + void goo() + { + MyGeneric goo = new $$ + } + """, "MyGeneric"); [Fact] - public async Task NotInAnonymousTypeObjectCreation1() - { - var markup = @" -class C -{ - void M() - { - var x = new[] { new { Goo = ""asdf"", Bar = 1 }, new $$ - } -}"; - - await VerifyItemIsAbsentAsync(markup, ""); - } + public Task NotInAnonymousTypeObjectCreation1() + => VerifyItemIsAbsentAsync(""" + class C + { + void M() + { + var x = new[] { new { Goo = "asdf", Bar = 1 }, new $$ + } + } + """, ""); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854497")] - public async Task NotVoid() - { - var markup = @" -class C -{ - void M() - { - var x = new $$ - } -}"; - - await VerifyItemIsAbsentAsync(markup, "void"); - } + public Task NotVoid() + => VerifyItemIsAbsentAsync(""" + class C + { + void M() + { + var x = new $$ + } + } + """, "void"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827897")] - public async Task InYieldReturn() - { - var markup = -@"using System; -using System.Collections.Generic; + public Task InYieldReturn() + => VerifyItemExistsAsync(""" + using System; + using System.Collections.Generic; -class Program -{ - IEnumerable M() - { - yield return new $$ - } -}"; - await VerifyItemExistsAsync(markup, "FieldAccessException"); - } + class Program + { + IEnumerable M() + { + yield return new $$ + } + } + """, "FieldAccessException"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827897")] - public async Task InAsyncMethodReturnStatement() - { - var markup = -@"using System; -using System.Threading.Tasks; + public Task InAsyncMethodReturnStatement() + => VerifyItemExistsAsync(""" + using System; + using System.Threading.Tasks; -class Program -{ - async Task M() - { - await Task.Delay(1); - return new $$ - } -}"; - await VerifyItemExistsAsync(markup, "FieldAccessException"); - } + class Program + { + async Task M() + { + await Task.Delay(1); + return new $$ + } + } + """, "FieldAccessException"); [Fact] - public async Task InAsyncMethodReturnValueTask() - { - var markup = -@"using System; -using System.Threading.Tasks; + public Task InAsyncMethodReturnValueTask() + => VerifyItemExistsAsync(MakeMarkup(""" + using System; + using System.Threading.Tasks; -class Program -{ - async ValueTask<string> M2Async() - { - return new $$; - } -}"; - await VerifyItemExistsAsync(MakeMarkup(markup), "string"); - } + class Program + { + async ValueTask<string> M2Async() + { + return new $$; + } + } + """), "string"); [Fact] public async Task IsCommitCharacterTest() { - const string markup = @" -using D = System.Globalization.DigitShapes; -class Program -{ - static void Main(string[] args) - { - D d = new $$ - } -}"; + const string markup = """ + using D = System.Globalization.DigitShapes; + class Program + { + static void Main(string[] args) + { + D d = new $$ + } + } + """; await VerifyCommitCharactersAsync(markup, textTypedSoFar: "", validChars: [' ', '(', '{', '['], @@ -147,15 +133,16 @@ public void IsTextualTriggerCharacterTest() [Fact] public async Task SendEnterThroughToEditorTest() { - const string markup = @" -using D = System.Globalization.DigitShapes; -class Program -{ - static void Main(string[] args) - { - D d = new $$ - } -}"; + const string markup = """ + using D = System.Globalization.DigitShapes; + class Program + { + static void Main(string[] args) + { + D d = new $$ + } + } + """; await VerifySendEnterThroughToEnterAsync(markup, "D", sendThroughEnterOption: EnterKeyRule.Never, expected: false); await VerifySendEnterThroughToEnterAsync(markup, "D", sendThroughEnterOption: EnterKeyRule.AfterFullyTypedWord, expected: true); @@ -163,629 +150,543 @@ static void Main(string[] args) } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/828196")] - public async Task SuggestAlias() - { - var markup = @" -using D = System.Globalization.DigitShapes; -class Program -{ - static void Main(string[] args) - { - D d= new $$ - } -}"; - await VerifyItemExistsAsync(markup, "D"); - } + public Task SuggestAlias() + => VerifyItemExistsAsync(""" + using D = System.Globalization.DigitShapes; + class Program + { + static void Main(string[] args) + { + D d= new $$ + } + } + """, "D"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/828196")] - public async Task SuggestAlias2() - { - var markup = @" -namespace N -{ -using D = System.Globalization.DigitShapes; -class Program -{ - static void Main(string[] args) - { - D d= new $$ - } -} -} - -"; - await VerifyItemExistsAsync(markup, "D"); - } + public Task SuggestAlias2() + => VerifyItemExistsAsync(""" + namespace N + { + using D = System.Globalization.DigitShapes; + class Program + { + static void Main(string[] args) + { + D d= new $$ + } + } + } + """, "D"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1075275")] - public async Task CommitAlias() - { - var markup = @" -using D = System.Globalization.DigitShapes; -class Program -{ - static void Main(string[] args) - { - D d= new $$ - } -}"; - - var expected = @" -using D = System.Globalization.DigitShapes; -class Program -{ - static void Main(string[] args) - { - D d= new D( - } -}"; - await VerifyProviderCommitAsync(markup, "D", expected, '('); - } + public Task CommitAlias() + => VerifyProviderCommitAsync(""" + using D = System.Globalization.DigitShapes; + class Program + { + static void Main(string[] args) + { + D d= new $$ + } + } + """, "D", """ + using D = System.Globalization.DigitShapes; + class Program + { + static void Main(string[] args) + { + D d= new D( + } + } + """, '('); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1090377")] - public async Task AfterNewFollowedByAssignment() - { - var markup = @" -class Location {} -enum EAB { A, B } -class Goo -{ - Location Loc {get; set;} - EAB E {get; set;} - - void stuff() - { - var x = new Goo + public Task AfterNewFollowedByAssignment() + => VerifyItemExistsAsync(""" + class Location {} + enum EAB { A, B } + class Goo { - Loc = new $$ - E = EAB.A - }; - } -} - -"; - await VerifyItemExistsAsync(markup, "Location"); - } + Location Loc {get; set;} + EAB E {get; set;} + + void stuff() + { + var x = new Goo + { + Loc = new $$ + E = EAB.A + }; + } + } + """, "Location"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1090377")] - public async Task AfterNewFollowedByAssignment_GrandParentIsSimpleAssignment() - { - var markup = @" -class Program -{ - static void Main(string[] args) - { - Program p = new $$ - bool b = false; - } -}"; - await VerifyItemExistsAsync(markup, "Program"); - } + public Task AfterNewFollowedByAssignment_GrandParentIsSimpleAssignment() + => VerifyItemExistsAsync(""" + class Program + { + static void Main(string[] args) + { + Program p = new $$ + bool b = false; + } + } + """, "Program"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2836")] - public async Task AfterNewFollowedBySimpleAssignment_GrandParentIsEqualsValueClause() - { - var markup = @" -class Program -{ - static void Main(string[] args) - { - bool b; - Program p = new $$ - b = false; - } -}"; - await VerifyItemExistsAsync(markup, "Program"); - } + public Task AfterNewFollowedBySimpleAssignment_GrandParentIsEqualsValueClause() + => VerifyItemExistsAsync(""" + class Program + { + static void Main(string[] args) + { + bool b; + Program p = new $$ + b = false; + } + } + """, "Program"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2836")] - public async Task AfterNewFollowedByCompoundAssignment_GrandParentIsEqualsValueClause() - { - var markup = @" -class Program -{ - static void Main(string[] args) - { - int i; - Program p = new $$ - i += 5; - } -}"; - await VerifyItemExistsAsync(markup, "Program"); - } + public Task AfterNewFollowedByCompoundAssignment_GrandParentIsEqualsValueClause() + => VerifyItemExistsAsync(""" + class Program + { + static void Main(string[] args) + { + int i; + Program p = new $$ + i += 5; + } + } + """, "Program"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2836")] - public async Task AfterNewFollowedByCompoundAssignment_GrandParentIsEqualsValueClause2() - { - var markup = @" -class Program -{ - static void Main(string[] args) - { - int i = 1000; - Program p = new $$ - i <<= 4; - } -}"; - await VerifyItemExistsAsync(markup, "Program"); - } + public Task AfterNewFollowedByCompoundAssignment_GrandParentIsEqualsValueClause2() + => VerifyItemExistsAsync(""" + class Program + { + static void Main(string[] args) + { + int i = 1000; + Program p = new $$ + i <<= 4; + } + } + """, "Program"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4115")] - public async Task CommitObjectWithParenthesis1() - { - var markup = @" -class C -{ - void M1() - { - object o = new $$ - } -}"; - - var expected = @" -class C -{ - void M1() - { - object o = new object( - } -}"; - - await VerifyProviderCommitAsync(markup, "object", expected, '('); - } + public Task CommitObjectWithParenthesis1() + => VerifyProviderCommitAsync(""" + class C + { + void M1() + { + object o = new $$ + } + } + """, "object", """ + class C + { + void M1() + { + object o = new object( + } + } + """, '('); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4115")] - public async Task CommitObjectWithParenthesis2() - { - var markup = @" -class C -{ - void M1() - { - M2(new $$ - } - - void M2(object o) { } -}"; - - var expected = @" -class C -{ - void M1() - { - M2(new object( - } + public Task CommitObjectWithParenthesis2() + => VerifyProviderCommitAsync(""" + class C + { + void M1() + { + M2(new $$ + } + + void M2(object o) { } + } + """, "object", """ + class C + { + void M1() + { + M2(new object( + } - void M2(object o) { } -}"; - - await VerifyProviderCommitAsync(markup, "object", expected, '('); - } + void M2(object o) { } + } + """, '('); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4115")] - public async Task DoNotCommitObjectWithOpenBrace1() - { - var markup = @" -class C -{ - void M1() - { - object o = new $$ - } -}"; - - var expected = @" -class C -{ - void M1() - { - object o = new { - } -}"; - - await VerifyProviderCommitAsync(markup, "object", expected, '{'); - } + public Task DoNotCommitObjectWithOpenBrace1() + => VerifyProviderCommitAsync(""" + class C + { + void M1() + { + object o = new $$ + } + } + """, "object", """ + class C + { + void M1() + { + object o = new { + } + } + """, '{'); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4115")] - public async Task DoNotCommitObjectWithOpenBrace2() - { - var markup = @" -class C -{ - void M1() - { - M2(new $$ - } - - void M2(object o) { } -}"; - - var expected = @" -class C -{ - void M1() - { - M2(new { - } - - void M2(object o) { } -}"; + public Task DoNotCommitObjectWithOpenBrace2() + => VerifyProviderCommitAsync(""" + class C + { + void M1() + { + M2(new $$ + } + + void M2(object o) { } + } + """, "object", """ + class C + { + void M1() + { + M2(new { + } - await VerifyProviderCommitAsync(markup, "object", expected, '{'); - } + void M2(object o) { } + } + """, '{'); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4310")] - public async Task InExpressionBodiedProperty() - { - var markup = -@"class C -{ - object Object => new $$ -} -"; - await VerifyItemExistsAsync(markup, "object"); - } + public Task InExpressionBodiedProperty() + => VerifyItemExistsAsync(""" + class C + { + object Object => new $$ + } + """, "object"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4310")] - public async Task InExpressionBodiedMethod() - { - var markup = -@"class C -{ - object GetObject() => new $$ -} -"; - await VerifyItemExistsAsync(markup, "object"); - } + public Task InExpressionBodiedMethod() + => VerifyItemExistsAsync(""" + class C + { + object GetObject() => new $$ + } + """, "object"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15804")] - public async Task BeforeAttributeParsedAsImplicitArray() - { - var markup = -@"class Program -{ - Program p = new $$ + public Task BeforeAttributeParsedAsImplicitArray() + => VerifyItemExistsAsync(""" + class Program + { + Program p = new $$ - [STAThread] - static void Main() { } -} -"; - await VerifyItemExistsAsync(markup, "Program"); - } + [STAThread] + static void Main() { } + } + """, "Program"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14084")] - public async Task InMethodCallBeforeAssignment1() - { - var markup = -@"namespace ConsoleApplication1 -{ - class Program - { - static void Main(string[] args) - { - object o; - string s; - - Test(new $$ - o = s; - } - static void Test(TimeSpan t, TimeSpan t2) { } - } -} -"; - await VerifyItemExistsAsync(markup, "TimeSpan"); - } + public Task InMethodCallBeforeAssignment1() + => VerifyItemExistsAsync(""" + namespace ConsoleApplication1 + { + class Program + { + static void Main(string[] args) + { + object o; + string s; + + Test(new $$ + o = s; + } + static void Test(TimeSpan t, TimeSpan t2) { } + } + } + """, "TimeSpan"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14084")] - public async Task InMethodCallBeforeAssignment2() - { - var markup = -@"namespace ConsoleApplication1 -{ - class Program - { - static void Main(string[] args) - { - object o; - string s; - - Test(new TimeSpan(), new $$ - o = s; - } - static void Test(TimeSpan t, TimeSpan t2) { } - } -} -"; - await VerifyItemExistsAsync(markup, "TimeSpan"); - } + public Task InMethodCallBeforeAssignment2() + => VerifyItemExistsAsync(""" + namespace ConsoleApplication1 + { + class Program + { + static void Main(string[] args) + { + object o; + string s; + + Test(new TimeSpan(), new $$ + o = s; + } + static void Test(TimeSpan t, TimeSpan t2) { } + } + } + """, "TimeSpan"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2644")] - public async Task InPropertyWithSameNameAsGenericTypeArgument1() - { - var markup = -@"namespace ConsoleApplication1 -{ - class Program - { - public static List Bar { get; set; } - - static void Main(string[] args) - { - Bar = new $$ - } - } - - class Bar - { - } -} -"; - await VerifyItemExistsAsync(markup, "List"); - } + public Task InPropertyWithSameNameAsGenericTypeArgument1() + => VerifyItemExistsAsync(""" + namespace ConsoleApplication1 + { + class Program + { + public static List Bar { get; set; } + + static void Main(string[] args) + { + Bar = new $$ + } + } + + class Bar + { + } + } + """, "List"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2644")] - public async Task InPropertyWithSameNameAsGenericTypeArgument2() - { - var markup = -@"namespace ConsoleApplication1 -{ - class Program - { - public static List Bar { get; set; } = new $$ - } + public Task InPropertyWithSameNameAsGenericTypeArgument2() + => VerifyItemExistsAsync(""" + namespace ConsoleApplication1 + { + class Program + { + public static List Bar { get; set; } = new $$ + } - class Bar - { - } -} -"; - await VerifyItemExistsAsync(markup, "List"); - } + class Bar + { + } + } + """, "List"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2644")] - public async Task InPropertyWithSameNameAsGenericTypeArgument3() - { - var markup = -@"namespace ConsoleApplication1 -{ - class Program - { - public static List Bar { get; set; } => new $$ - } + public Task InPropertyWithSameNameAsGenericTypeArgument3() + => VerifyItemExistsAsync(""" + namespace ConsoleApplication1 + { + class Program + { + public static List Bar { get; set; } => new $$ + } - class Bar - { - } -} -"; - await VerifyItemExistsAsync(markup, "List"); - } + class Bar + { + } + } + """, "List"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2644")] - public async Task InPropertyWithSameNameAsGenericTypeArgument4() - { - var markup = -@"namespace ConsoleApplication1 -{ - class Program - { - static C B { get; set; } - static C A { get; set; } - - static void Main(string[] args) - { - B = new $$ - } - } - class A { } - class B { } - class C { } -} -"; - await VerifyItemExistsAsync(markup, "C"); - } + public Task InPropertyWithSameNameAsGenericTypeArgument4() + => VerifyItemExistsAsync(""" + namespace ConsoleApplication1 + { + class Program + { + static C B { get; set; } + static C A { get; set; } + + static void Main(string[] args) + { + B = new $$ + } + } + class A { } + class B { } + class C { } + } + """, "C"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21674")] - public async Task PropertyWithSameNameAsOtherType() - { - var markup = -@"namespace ConsoleApplication1 -{ - class Program - { - static A B { get; set; } - static B A { get; set; } - - static void Main() - { - B = new $$ - } - } - class A { } - class B { } -} -"; - await VerifyItemExistsAsync(markup, "A"); - } + public Task PropertyWithSameNameAsOtherType() + => VerifyItemExistsAsync(""" + namespace ConsoleApplication1 + { + class Program + { + static A B { get; set; } + static B A { get; set; } + + static void Main() + { + B = new $$ + } + } + class A { } + class B { } + } + """, "A"); [Fact] - public async Task NullableTypeCreation() - { - var markup = -@"#nullable enable -namespace ConsoleApplication1 -{ - class Program - { - void M() - { - object? o; - o = new $$ - } - } -} -"; - await VerifyItemExistsAsync(markup, "object"); - } + public Task NullableTypeCreation() + => VerifyItemExistsAsync(""" + #nullable enable + namespace ConsoleApplication1 + { + class Program + { + void M() + { + object? o; + o = new $$ + } + } + } + """, "object"); [Fact] - public async Task NullableTypeCreation_AssignedNull() - { - var markup = -@"#nullable enable -namespace ConsoleApplication1 -{ - class Program - { - void M() - { - object? o = null; - o = new $$ - } - } -} -"; - await VerifyItemExistsAsync(markup, "object"); - } + public Task NullableTypeCreation_AssignedNull() + => VerifyItemExistsAsync(""" + #nullable enable + namespace ConsoleApplication1 + { + class Program + { + void M() + { + object? o = null; + o = new $$ + } + } + } + """, "object"); [Fact] - public async Task NullableTypeCreation_NestedNull() - { - var markup = -@"#nullable enable + public Task NullableTypeCreation_NestedNull() + => VerifyItemExistsAsync(""" + #nullable enable -using System.Collections.Generic; + using System.Collections.Generic; -namespace ConsoleApplication1 -{ - class Program - { - void M() - { - List l; - l = new $$ - } - } -} -"; - await VerifyItemExistsAsync(markup, "List"); - } + namespace ConsoleApplication1 + { + class Program + { + void M() + { + List l; + l = new $$ + } + } + } + """, "List"); [Theory] [InlineData('.')] [InlineData(';')] - public async Task CreateObjectAndCommitWithCustomizedCommitChar(char commitChar) - { - var markup = @" -class Program -{ - void Bar() - { - object o = new $$ - } -}"; - var expectedMark = $@" -class Program -{{ - void Bar() - {{ - object o = new object(){commitChar} - }} -}}"; - await VerifyProviderCommitAsync(markup, "object", expectedMark, commitChar: commitChar); - } + public Task CreateObjectAndCommitWithCustomizedCommitChar(char commitChar) + => VerifyProviderCommitAsync(""" + class Program + { + void Bar() + { + object o = new $$ + } + } + """, "object", $$""" + class Program + { + void Bar() + { + object o = new object(){{commitChar}} + } + } + """, commitChar: commitChar); [Theory] [InlineData('.')] [InlineData(';')] - public async Task CreateNullableObjectAndCommitWithCustomizedCommitChar(char commitChar) - { - var markup = @" -class Program -{ - void Bar() - { - object? o = new $$ - } -}"; - var expectedMark = $@" -class Program -{{ - void Bar() - {{ - object? o = new object(){commitChar} - }} -}}"; - await VerifyProviderCommitAsync(markup, "object", expectedMark, commitChar: commitChar); - } + public Task CreateNullableObjectAndCommitWithCustomizedCommitChar(char commitChar) + => VerifyProviderCommitAsync(""" + class Program + { + void Bar() + { + object? o = new $$ + } + } + """, "object", $$""" + class Program + { + void Bar() + { + object? o = new object(){{commitChar}} + } + } + """, commitChar: commitChar); [Theory] [InlineData('.')] [InlineData(';')] - public async Task CreateStringAsLocalAndCommitWithCustomizedCommitChar(char commitChar) - { - var markup = @" -class Program -{ - void Bar() - { - string o = new $$ - } -}"; - var expectedMark = $@" -class Program -{{ - void Bar() - {{ - string o = new string(){commitChar} - }} -}}"; - await VerifyProviderCommitAsync(markup, "string", expectedMark, commitChar: commitChar); - } + public Task CreateStringAsLocalAndCommitWithCustomizedCommitChar(char commitChar) + => VerifyProviderCommitAsync(""" + class Program + { + void Bar() + { + string o = new $$ + } + } + """, "string", $$""" + class Program + { + void Bar() + { + string o = new string(){{commitChar}} + } + } + """, commitChar: commitChar); [Theory] [InlineData('.')] [InlineData(';')] - public async Task CreateGenericListAsLocalAndCommitWithCustomizedChar(char commitChar) - { - var markup = @" -using System.Collections.Generic; -class Program -{ - void Bar() - { - List o = new $$ - } -}"; - var expectedMark = $@" -using System.Collections.Generic; -class Program -{{ - void Bar() - {{ - List o = new List(){commitChar} - }} -}}"; - await VerifyProviderCommitAsync(markup, "List", expectedMark, commitChar: commitChar); - } + public Task CreateGenericListAsLocalAndCommitWithCustomizedChar(char commitChar) + => VerifyProviderCommitAsync(""" + using System.Collections.Generic; + class Program + { + void Bar() + { + List o = new $$ + } + } + """, "List", $$""" + using System.Collections.Generic; + class Program + { + void Bar() + { + List o = new List(){{commitChar}} + } + } + """, commitChar: commitChar); [Fact] - public async Task CreateGenericListAsFieldAndCommitWithSemicolon() - { - var markup = @" -using System.Collections.Generic; -class Program -{ - private List o = new $$ -}"; - var expectedMark = @" -using System.Collections.Generic; -class Program -{ - private List o = new List(); -}"; - await VerifyProviderCommitAsync(markup, "List", expectedMark, commitChar: ';'); - } + public Task CreateGenericListAsFieldAndCommitWithSemicolon() + => VerifyProviderCommitAsync(""" + using System.Collections.Generic; + class Program + { + private List o = new $$ + } + """, "List", """ + using System.Collections.Generic; + class Program + { + private List o = new List(); + } + """, commitChar: ';'); private static string MakeMarkup(string source, string languageVersion = "Preview") { diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ObjectInitializerCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ObjectInitializerCompletionProviderTests.cs index 6822640abad79..7d9156b26d153 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ObjectInitializerCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ObjectInitializerCompletionProviderTests.cs @@ -246,9 +246,8 @@ void goo() } [Fact] - public async Task NotInEqualsValue() - { - var markup = """ + public Task NotInEqualsValue() + => VerifyNoItemsExistAsync(""" class C { public int value {set; get; } @@ -262,10 +261,7 @@ void goo() C goo = new C { value = v$$ } } - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] public async Task NothingLeftToShow() @@ -320,9 +316,8 @@ void goo() } [Fact] - public async Task NotExclusive1() - { - var markup = """ + public Task NotExclusive1() + => VerifyExclusiveAsync(""" using System.Collections.Generic; class C : IEnumerable { @@ -338,14 +333,11 @@ void goo() C bar = new C { v$$ } } - """; - await VerifyExclusiveAsync(markup, false); - } + """, false); [Fact] - public async Task NotExclusive2() - { - var markup = """ + public Task NotExclusive2() + => VerifyExclusiveAsync(""" using System.Collections; class C : IEnumerable { @@ -361,14 +353,11 @@ void goo() C bar = new C { v$$ } } - """; - await VerifyExclusiveAsync(markup, false); - } + """, false); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544242")] - public async Task NotInArgumentList() - { - var markup = """ + public Task NotInArgumentList() + => VerifyNoItemsExistAsync(""" class C { void M(int i, int j) @@ -376,14 +365,11 @@ void M(int i, int j) M(i, j$$ } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530075")] - public async Task NotInArgumentList2() - { - var markup = """ + public Task NotInArgumentList2() + => VerifyNoItemsExistAsync(""" class C { public int A; @@ -392,9 +378,7 @@ void M(int i, int j) new C(1, $$ } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544289")] public async Task DerivedMembers() @@ -434,9 +418,8 @@ static void Main(string[] args) } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544242")] - public async Task NotInCollectionInitializer() - { - var markup = """ + public Task NotInCollectionInitializer() + => VerifyNoItemsExistAsync(""" using System.Collections.Generic; class C { @@ -445,14 +428,11 @@ void goo() var a = new List {0, $$ } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task InitializeDerivedType() - { - var markup = """ + public Task InitializeDerivedType() + => VerifyItemExistsAsync(""" using System.Collections.Generic; class B {} @@ -468,9 +448,7 @@ void stuff() B a = new D { $$ } } - """; - await VerifyItemExistsAsync(markup, "goo"); - } + """, "goo"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544550")] public async Task ReadOnlyPropertiesShouldNotBePresent() @@ -530,9 +508,8 @@ void M() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544607")] - public async Task DoNotIncludeStaticMember() - { - var markup = """ + public Task DoNotIncludeStaticMember() + => VerifyItemIsAbsentAsync(""" class Goo { public static int Gibberish { get; set; } @@ -545,10 +522,7 @@ void goo() var c = new Goo { $$ } } - """; - - await VerifyItemIsAbsentAsync(markup, "Gibberish"); - } + """, "Gibberish"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545678")] public async Task EditorBrowsable_PropertyInObjectCreationAlways() @@ -909,9 +883,8 @@ static void Main(string[] args) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4754")] - public async Task ObjectInitializerOfGenericTypeConstructedWithInaccessibleType() - { - var markup = """ + public Task ObjectInitializerOfGenericTypeConstructedWithInaccessibleType() + => VerifyItemExistsAsync(""" class Generic { public string Value { get; set; } @@ -929,10 +902,7 @@ static void Main(string[] args) var g = new Generic { $$ } } } - """; - - await VerifyItemExistsAsync(markup, "Value"); - } + """, "Value"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24612")] public async Task ObjectInitializerOfGenericTypeСonstraint1() @@ -962,9 +932,8 @@ public static T Create() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24612")] - public async Task ObjectInitializerOfGenericTypeСonstraint2() - { - var markup = """ + public Task ObjectInitializerOfGenericTypeСonstraint2() + => VerifyNoItemsExistAsync(""" internal class Example { public static T Create() @@ -976,10 +945,7 @@ public static T Create() }; } } - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24612")] public async Task ObjectInitializerOfGenericTypeСonstraint3() @@ -1003,9 +969,8 @@ public static T Create() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24612")] - public async Task ObjectInitializerOfGenericTypeСonstraint4() - { - var markup = """ + public Task ObjectInitializerOfGenericTypeСonstraint4() + => VerifyNoItemsExistAsync(""" internal class Example { public static T Create() @@ -1017,15 +982,11 @@ public static T Create() }; } } - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/74331")] - public async Task ObjectInitializerOnVariousMembers_01() - { - var markup = """ + public Task ObjectInitializerOnVariousMembers_01() + => VerifyNoItemsExistAsync(""" using System.Collections; using System.Collections.Generic; @@ -1051,15 +1012,11 @@ public static Example Create() }; } } - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/74331")] - public async Task ObjectInitializerOnVariousMembers_02() - { - var markup = """ + public Task ObjectInitializerOnVariousMembers_02() + => VerifyNoItemsExistAsync(""" using System.Collections; using System.Collections.Generic; @@ -1085,10 +1042,7 @@ public static Example Create() }; } } - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26560")] public async Task ObjectInitializerEscapeKeywords() @@ -1144,9 +1098,8 @@ static void Main(string[] args) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15205")] - public async Task NestedPropertyInitializers1() - { - var markup = """ + public Task NestedPropertyInitializers1() + => VerifyItemExistsAsync(""" class A { public B PropB { get; } @@ -1165,15 +1118,11 @@ static void Main(string[] args) var a = new A { $$ } } } - """; - - await VerifyItemExistsAsync(markup, "PropB"); - } + """, "PropB"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15205")] - public async Task NestedPropertyInitializers2() - { - var markup = """ + public Task NestedPropertyInitializers2() + => VerifyItemExistsAsync(""" class A { public B PropB { get; } @@ -1197,15 +1146,11 @@ static void Main(string[] args) var a = new A { $$ } } } - """; - - await VerifyItemExistsAsync(markup, "PropB"); - } + """, "PropB"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15205")] - public async Task NestedPropertyInitializers3() - { - var markup = """ + public Task NestedPropertyInitializers3() + => VerifyItemExistsAsync(""" class A { public B PropB { get; } @@ -1243,15 +1188,11 @@ static void Main(string[] args) var a = new A { $$ } } } - """; - - await VerifyItemExistsAsync(markup, "PropB"); - } + """, "PropB"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15205")] - public async Task NestedPropertyInitializers4() - { - var markup = """ + public Task NestedPropertyInitializers4() + => VerifyItemExistsAsync(""" class A { public B PropB { get; } @@ -1275,15 +1216,11 @@ static void Main(string[] args) var a = new A { $$ } } } - """; - - await VerifyItemExistsAsync(markup, "PropB"); - } + """, "PropB"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15205")] - public async Task NestedPropertyInitializers5() - { - var markup = """ + public Task NestedPropertyInitializers5() + => VerifyItemExistsAsync(""" class A { public B PropB { get; } @@ -1306,15 +1243,11 @@ static void Main(string[] args) var a = new A { $$ } } } - """; - - await VerifyItemExistsAsync(markup, "PropB"); - } + """, "PropB"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36702")] - public async Task NestedPropertyInitializers6() - { - var markup = """ + public Task NestedPropertyInitializers6() + => VerifyItemExistsAsync(""" class A { public B PropB { get; } @@ -1337,10 +1270,7 @@ static void Main(string[] args) var a = new A { PropB = { $$ } } } } - """; - - await VerifyItemExistsAsync(markup, "PropC"); - } + """, "PropC"); private async Task VerifyExclusiveAsync(string markup, bool exclusive) { diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/OperatorCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/OperatorCompletionProviderTests.cs index 405ceaed04efc..1380099562b81 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/OperatorCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/OperatorCompletionProviderTests.cs @@ -69,10 +69,8 @@ public static IEnumerable UnaryOperators() => PostfixOperators().Union(PrefixOperators()); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task OperatorIsNotOfferedAfterNumberLiteral() - { - // User may want to type a floating point literal. - await VerifyNoItemsExistAsync(""" + public Task OperatorIsNotOfferedAfterNumberLiteral() + => VerifyNoItemsExistAsync(""" public class C { public static C operator +(C a, C b) => default; @@ -86,12 +84,10 @@ public static void Main() } } """, SourceCodeKind.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task OperatorIsSuggestedAfterDot() - { - await VerifyItemExistsAsync(""" + public Task OperatorIsSuggestedAfterDot() + => VerifyItemExistsAsync(""" public class C { public static C operator +(C a, C b) => default; @@ -106,7 +102,6 @@ public static void Main() } } """, "+", inlineDescription: "x + y", glyph: Glyph.OperatorPublic, matchingFilters: [FilterSet.OperatorFilter]); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] [InlineData("c.$$", true)] @@ -124,27 +119,26 @@ public async Task OperatorSuggestionOnPartiallyWrittenMember(string expression, var verifyAction = isOffered ? new Func(markup => VerifyItemExistsAsync(markup, "+", inlineDescription: "x + y")) : new Func(markup => VerifyNoItemsExistAsync(markup)); - await verifyAction(@$" -public class C -{{ - public static C operator +(C a, C b) => default; -}} - -public class Program -{{ - public static void Main() - {{ - var c = new C(); - {expression} - }} -}} -"); + await verifyAction($$""" + public class C + { + public static C operator +(C a, C b) => default; + } + + public class Program + { + public static void Main() + { + var c = new C(); + {{expression}} + } + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task OperatorIsNotSuggestedOnStaticAccess() - { - await VerifyNoItemsExistAsync(""" + public Task OperatorIsNotSuggestedOnStaticAccess() + => VerifyNoItemsExistAsync(""" public class C { public static C operator +(C a, C b) => default; @@ -158,12 +152,10 @@ public static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task OperatorIsNotSuggestedInNameoOfContext() - { - await VerifyNoItemsExistAsync(""" + public Task OperatorIsNotSuggestedInNameoOfContext() + => VerifyNoItemsExistAsync(""" public class C { public static C operator +(C a, C b) => default; @@ -178,7 +170,6 @@ public static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] public async Task OperatorsAreSortedByImporttanceAndGroupedByTopic() @@ -338,25 +329,24 @@ public static void Main() [InlineData("System.Guid", 2)] public async Task OperatorSuggestionForSpecialTypes(string specialType, int numberOfSuggestions) { - var completionItems = await GetCompletionItemsAsync(@$" -public class Program -{{ - public static void Main() - {{ - {specialType} i = default({specialType}); - i.$$ - }} -}} -", SourceCodeKind.Regular); + var completionItems = await GetCompletionItemsAsync($$""" + public class Program + { + public static void Main() + { + {{specialType}} i = default({{specialType}}); + i.$$ + } + } + """, SourceCodeKind.Regular); Assert.Equal( numberOfSuggestions, completionItems.Count(c => c.GetProperty(UnnamedSymbolCompletionProvider.KindName) == UnnamedSymbolCompletionProvider.OperatorKindName)); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task OperatorNoSuggestionForTrueAndFalse() - { - await VerifyNoItemsExistAsync(""" + public Task OperatorNoSuggestionForTrueAndFalse() + => VerifyNoItemsExistAsync(""" public class C { public static bool operator true(C _) => true; @@ -372,132 +362,125 @@ public static void Main() } } """); - } [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] [MemberData(nameof(BinaryOperators))] - public async Task OperatorBinaryIsCompleted(string binaryOperator) - { - await VerifyCustomCommitProviderAsync($@" -public class C -{{ - public static C operator {binaryOperator}(C a, C b) => default; -}} - -public class Program -{{ - public static void Main() - {{ - var c = new C(); - c.$$ - }} -}} -", binaryOperator, @$" -public class C -{{ - public static C operator {binaryOperator}(C a, C b) => default; -}} - -public class Program -{{ - public static void Main() - {{ - var c = new C(); - c {binaryOperator} $$ - }} -}} -"); - } + public Task OperatorBinaryIsCompleted(string binaryOperator) + => VerifyCustomCommitProviderAsync($$""" + public class C + { + public static C operator {{binaryOperator}}(C a, C b) => default; + } + + public class Program + { + public static void Main() + { + var c = new C(); + c.$$ + } + } + """, binaryOperator, $$""" + public class C + { + public static C operator {{binaryOperator}}(C a, C b) => default; + } + + public class Program + { + public static void Main() + { + var c = new C(); + c {{binaryOperator}} $$ + } + } + """); [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] [MemberData(nameof(PostfixOperators))] - public async Task OperatorPostfixIsCompleted(string postfixOperator) - { - await VerifyCustomCommitProviderAsync($@" -public class C -{{ - public static C operator {postfixOperator}(C _) => default; -}} - -public class Program -{{ - public static void Main() - {{ - var c = new C(); - c.$$ - }} -}} -", postfixOperator, @$" -public class C -{{ - public static C operator {postfixOperator}(C _) => default; -}} - -public class Program -{{ - public static void Main() - {{ - var c = new C(); - c{postfixOperator} $$ - }} -}} -"); - } + public Task OperatorPostfixIsCompleted(string postfixOperator) + => VerifyCustomCommitProviderAsync($$""" + public class C + { + public static C operator {{postfixOperator}}(C _) => default; + } + + public class Program + { + public static void Main() + { + var c = new C(); + c.$$ + } + } + """, postfixOperator, $$""" + public class C + { + public static C operator {{postfixOperator}}(C _) => default; + } + + public class Program + { + public static void Main() + { + var c = new C(); + c{{postfixOperator}} $$ + } + } + """); [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] [MemberData(nameof(PrefixOperators))] - public async Task OperatorPrefixIsCompleted(string prefixOperator) - { - await VerifyCustomCommitProviderAsync($@" -public class C -{{ - public static C operator {prefixOperator}(C _) => default; -}} - -public class Program -{{ - public static void Main() - {{ - var c = new C(); - c.$$ - }} -}} -", prefixOperator, @$" -public class C -{{ - public static C operator {prefixOperator}(C _) => default; -}} - -public class Program -{{ - public static void Main() - {{ - var c = new C(); - {prefixOperator}c$$ - }} -}} -"); - } + public Task OperatorPrefixIsCompleted(string prefixOperator) + => VerifyCustomCommitProviderAsync($$""" + public class C + { + public static C operator {{prefixOperator}}(C _) => default; + } + + public class Program + { + public static void Main() + { + var c = new C(); + c.$$ + } + } + """, prefixOperator, $$""" + public class C + { + public static C operator {{prefixOperator}}(C _) => default; + } + + public class Program + { + public static void Main() + { + var c = new C(); + {{prefixOperator}}c$$ + } + } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] public async Task OperatorDuplicateOperatorsAreListedBoth() { - var items = await GetCompletionItemsAsync($@" -public class C -{{ - public static C operator +(C a, C b) => default; - public static C operator +(C _) => default; -}} - -public class Program -{{ - public static void Main() - {{ - var c = new C(); - c.$$ - }} -}} -", SourceCodeKind.Regular); + var items = await GetCompletionItemsAsync($$""" + public class C + { + public static C operator +(C a, C b) => default; + public static C operator +(C _) => default; + } + + public class Program + { + public static void Main() + { + var c = new C(); + c.$$ + } + } + """, SourceCodeKind.Regular); Assert.Collection(items, i => { @@ -512,40 +495,38 @@ public static void Main() } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task OperatorDuplicateOperatorsAreCompleted() - { - await VerifyCustomCommitProviderAsync($@" -public class C -{{ - public static C operator +(C a, C b) => default; - public static C operator +(C _) => default; -}} - -public class Program -{{ - public static void Main() - {{ - var c = new C(); - c.$$ - }} -}} -", "+", @$" -public class C -{{ - public static C operator +(C a, C b) => default; - public static C operator +(C _) => default; -}} - -public class Program -{{ - public static void Main() - {{ - var c = new C(); - c + $$ - }} -}} -"); - } + public Task OperatorDuplicateOperatorsAreCompleted() + => VerifyCustomCommitProviderAsync($$""" + public class C + { + public static C operator +(C a, C b) => default; + public static C operator +(C _) => default; + } + + public class Program + { + public static void Main() + { + var c = new C(); + c.$$ + } + } + """, "+", $$""" + public class C + { + public static C operator +(C a, C b) => default; + public static C operator +(C _) => default; + } + + public class Program + { + public static void Main() + { + var c = new C(); + c + $$ + } + } + """); [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] [InlineData("c.$$", @@ -590,42 +571,40 @@ public static void Main() "c?.CProp[0] + $$")] [InlineData("c.CProp[0].CProp?.$$", "c.CProp[0].CProp + $$")] - public async Task OperatorInfixOfferingsAndCompletions(string expression, string completion) - { - await VerifyCustomCommitProviderAsync($@" -public class C -{{ - public static C operator +(C a, C b) => default; - public C CProp {{ get; }} - public C this[int _] => default; -}} - -public class Program -{{ - public static void Main() - {{ - var c = new C(); - {expression} - }} -}} -", "+", @$" -public class C -{{ - public static C operator +(C a, C b) => default; - public C CProp {{ get; }} - public C this[int _] => default; -}} - -public class Program -{{ - public static void Main() - {{ - var c = new C(); - {completion} - }} -}} -"); - } + public Task OperatorInfixOfferingsAndCompletions(string expression, string completion) + => VerifyCustomCommitProviderAsync($$""" + public class C + { + public static C operator +(C a, C b) => default; + public C CProp { get; } + public C this[int _] => default; + } + + public class Program + { + public static void Main() + { + var c = new C(); + {{expression}} + } + } + """, "+", $$""" + public class C + { + public static C operator +(C a, C b) => default; + public C CProp { get; } + public C this[int _] => default; + } + + public class Program + { + public static void Main() + { + var c = new C(); + {{completion}} + } + } + """); [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] [MemberData(nameof(UnaryOperators))] @@ -708,9 +687,8 @@ public static void Main() } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task OperatorLiftingIsApplied() - { - await VerifyCustomCommitProviderAsync(""" + public Task OperatorLiftingIsApplied() + => VerifyCustomCommitProviderAsync(""" public struct S { public static bool operator ==(S a, S b) => default; @@ -739,12 +717,10 @@ public static void Main() } } """); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task OperatorOfBaseTypeIsSuggested() - { - await VerifyItemExistsAsync(""" + public Task OperatorOfBaseTypeIsSuggested() + => VerifyItemExistsAsync(""" public class Base { public static int operator +(Base b, int a)=>0; } @@ -761,12 +737,10 @@ public static void Main() } } """, "+", inlineDescription: "x + y", glyph: Glyph.OperatorPublic, matchingFilters: [FilterSet.OperatorFilter]); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task OperatorForRecordsAreSuggested() - { - await VerifyItemExistsAsync(""" + public Task OperatorForRecordsAreSuggested() + => VerifyItemExistsAsync(""" public record R { } @@ -779,7 +753,6 @@ public static void Main() } } """, "==", inlineDescription: "x == y", glyph: Glyph.OperatorPublic, matchingFilters: [FilterSet.OperatorFilter]); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] public async Task TestEditorBrowsableOnOperatorIsRespected_EditorBrowsableStateNever() @@ -873,9 +846,8 @@ await VerifyItemInEditorBrowsableContextsAsync( } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/47511")] - public async Task OperatorBinaryNullForgivingHandling() - { - await VerifyCustomCommitProviderAsync(""" + public Task OperatorBinaryNullForgivingHandling() + => VerifyCustomCommitProviderAsync(""" #nullable enable public class C @@ -908,5 +880,4 @@ public static void Main() } } """); - } } diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/OverrideCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/OverrideCompletionProviderTests.cs index d59eeb250b8ee..c580f9b00552c 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/OverrideCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/OverrideCompletionProviderTests.cs @@ -39,9 +39,8 @@ internal override OptionsCollection NonCompletionOptions #region "CompletionItem tests" [WpfFact] - public async Task InheritedVirtualPublicMethod() - { - await VerifyItemExistsAsync(""" + public Task InheritedVirtualPublicMethod() + => VerifyItemExistsAsync(""" public class a { public virtual void goo() { } @@ -52,12 +51,10 @@ public class b : a override $$ } """, "goo()"); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543799")] - public async Task InheritedParameterDefaultValue1() - { - await VerifyItemExistsAsync(""" + public Task InheritedParameterDefaultValue1() + => VerifyItemExistsAsync(""" public class a { public virtual void goo(int x = 42) { } @@ -68,12 +65,10 @@ public class b : a override $$ } """, "goo(int x = 42)", "void a.goo([int x = 42])"); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543799")] - public async Task InheritedParameterDefaultValue2() - { - await VerifyItemExistsAsync(""" + public Task InheritedParameterDefaultValue2() + => VerifyItemExistsAsync(""" public class a { public virtual void goo(int x, int y = 42) { } @@ -84,12 +79,10 @@ public class b : a override $$ } """, "goo(int x, int y = 42)", "void a.goo(int x, [int y = 42])"); - } [WpfFact] - public async Task InheritedAbstractPublicMethod() - { - await VerifyItemExistsAsync(""" + public Task InheritedAbstractPublicMethod() + => VerifyItemExistsAsync(""" public class a { public abstract void goo(); @@ -100,12 +93,10 @@ public class b : a override $$ } """, "goo()"); - } [WpfFact] - public async Task NotPrivateInheritedMethod() - { - await VerifyItemIsAbsentAsync(""" + public Task NotPrivateInheritedMethod() + => VerifyItemIsAbsentAsync(""" public class a { private virtual void goo() { } @@ -116,7 +107,6 @@ public class b : a override $$ } """, "goo()"); - } [WpfFact] public async Task MatchReturnType() @@ -160,9 +150,8 @@ override badtype $$ } [WpfFact] - public async Task NotAlreadyImplementedMethods() - { - await VerifyItemIsAbsentAsync(""" + public Task NotAlreadyImplementedMethods() + => VerifyItemIsAbsentAsync(""" public class a { protected virtual void goo() { } @@ -177,12 +166,10 @@ protected override void goo() { } override $$ } """, "goo()"); - } [WpfFact] - public async Task NotSealed() - { - await VerifyItemIsAbsentAsync(""" + public Task NotSealed() + => VerifyItemIsAbsentAsync(""" public class a { protected sealed void goo() { } @@ -193,12 +180,10 @@ public class b : a public override $$ } """, "goo()"); - } [WpfFact] - public async Task ShowEvent() - { - await VerifyItemExistsAsync(""" + public Task ShowEvent() + => VerifyItemExistsAsync(""" using System; public class a { @@ -210,12 +195,10 @@ public class b : a public override $$ } """, "goo"); - } [WpfFact] - public async Task NotIfTokensAfterPosition() - { - await VerifyNoItemsExistAsync(""" + public Task NotIfTokensAfterPosition() + => VerifyNoItemsExistAsync(""" public class a { public virtual void goo() { } @@ -226,12 +209,10 @@ public class b : a public override $$ void } """); - } [WpfFact] - public async Task NotIfNameAfterPosition() - { - await VerifyNoItemsExistAsync(""" + public Task NotIfNameAfterPosition() + => VerifyNoItemsExistAsync(""" public class a { public virtual void goo() { } @@ -242,12 +223,10 @@ public class b : a public override void $$ bar } """); - } [WpfFact] - public async Task NotIfStatic() - { - await VerifyNoItemsExistAsync(""" + public Task NotIfStatic() + => VerifyNoItemsExistAsync(""" public class a { public virtual void goo() { } @@ -258,12 +237,10 @@ public class b : a public static override $$ } """); - } [WpfFact] - public async Task AfterSingleLineMethodDeclaration() - { - await VerifyNoItemsExistAsync(""" + public Task AfterSingleLineMethodDeclaration() + => VerifyNoItemsExistAsync(""" public class a { public virtual void goo() { } @@ -274,12 +251,10 @@ public class b : a void bar() { } override $$ } """); - } [WpfFact] - public async Task SuggestProperty() - { - await VerifyItemExistsAsync(""" + public Task SuggestProperty() + => VerifyItemExistsAsync(""" public class a { public virtual int goo { } @@ -290,12 +265,10 @@ public class b : a override $$ } """, "goo"); - } [WpfFact] - public async Task NotSuggestSealed() - { - await VerifyItemIsAbsentAsync(""" + public Task NotSuggestSealed() + => VerifyItemIsAbsentAsync(""" public class a { public sealed int goo { } @@ -306,12 +279,10 @@ public class b : a override $$ } """, "goo"); - } [WpfFact] - public async Task GatherModifiers() - { - await VerifyItemExistsAsync(""" + public Task GatherModifiers() + => VerifyItemExistsAsync(""" public class a { public abstract extern unsafe int goo { } @@ -322,12 +293,10 @@ public class b : a override $$ } """, "goo"); - } [WpfFact] - public async Task IgnorePartial() - { - await VerifyNoItemsExistAsync(""" + public Task IgnorePartial() + => VerifyNoItemsExistAsync(""" public class a { public virtual partial goo() { } @@ -338,12 +307,10 @@ public class b : a override partial $$ } """); - } [WpfFact] - public async Task IgnoreSealed() - { - await VerifyItemIsAbsentAsync(""" + public Task IgnoreSealed() + => VerifyItemIsAbsentAsync(""" public class a { public virtual sealed int goo() { } @@ -354,12 +321,10 @@ public class b : a override $$ } """, "goo()"); - } [WpfFact] - public async Task IgnoreIfTokenAfter() - { - await VerifyNoItemsExistAsync(""" + public Task IgnoreIfTokenAfter() + => VerifyNoItemsExistAsync(""" public class a { public virtual int goo() { } @@ -370,12 +335,10 @@ public class b : a override $$ int } """); - } [WpfFact] - public async Task SuggestAfterUnsafeAbstractExtern() - { - await VerifyItemExistsAsync(""" + public Task SuggestAfterUnsafeAbstractExtern() + => VerifyItemExistsAsync(""" public class a { public virtual int goo() { } @@ -386,12 +349,10 @@ public class b : a unsafe abstract extern override $$ } """, "goo()"); - } [WpfFact] - public async Task SuggestAfterSealed() - { - await VerifyItemExistsAsync(""" + public Task SuggestAfterSealed() + => VerifyItemExistsAsync(""" public class a { public virtual int goo() { } @@ -402,7 +363,6 @@ public class b : a sealed override $$ } """, "goo()"); - } [WpfFact] public async Task NoAccessibility() @@ -621,22 +581,17 @@ internal protected override $$ } [WpfFact] - public async Task VerifySignatureFormat() - { - var markup = """ + public Task VerifySignatureFormat() + => VerifyItemExistsAsync(""" public class a { override $$ } - """; - - await VerifyItemExistsAsync(markup, "Equals(object obj)"); - } + """, "Equals(object obj)"); [WpfFact] - public async Task PrivateNoFilter() - { - var markup = """ + public Task PrivateNoFilter() + => VerifyNoItemsExistAsync(""" public class c { public virtual void goo() { } @@ -646,31 +601,19 @@ public class a : c { private override $$ } - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [WpfFact] - public async Task NotOfferedOnFirstLine() - { - var markup = @"class c { override $$"; - - await VerifyNoItemsExistAsync(markup); - } + public Task NotOfferedOnFirstLine() + => VerifyNoItemsExistAsync(@"class c { override $$"); [WpfFact] - public async Task NotOfferedOverrideAlone() - { - var markup = @"override $$"; - - await VerifyNoItemsExistAsync(markup); - } + public Task NotOfferedOverrideAlone() + => VerifyNoItemsExistAsync(@"override $$"); [WpfFact] - public async Task IntermediateClassOverriddenMember() - { - var markup = """ + public Task IntermediateClassOverriddenMember() + => VerifyItemExistsAsync(""" abstract class Base { public abstract void Goo(); @@ -685,15 +628,11 @@ class SomeClass : Derived { override $$ } - """; - - await VerifyItemExistsAsync(markup, "Goo()", "void Derived.Goo()"); - } + """, "Goo()", "void Derived.Goo()"); [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543748")] - public async Task NotOfferedBaseClassMember() - { - var markup = """ + public Task NotOfferedBaseClassMember() + => VerifyItemIsAbsentAsync(""" abstract class Base { public abstract void Goo(); @@ -708,15 +647,11 @@ class SomeClass : Derived { override $$ } - """; - - await VerifyItemIsAbsentAsync(markup, "Goo()", "void Base.Goo()"); - } + """, "Goo()", "void Base.Goo()"); [WpfFact] - public async Task NotOfferedOnNonVirtual() - { - var markup = """ + public Task NotOfferedOnNonVirtual() + => VerifyItemIsAbsentAsync(""" class Base { public void Goo(); @@ -726,10 +661,7 @@ class SomeClass : Base { override $$ } - """; - - await VerifyItemIsAbsentAsync(markup, "Goo()", "void Base.Goo()"); - } + """, "Goo()", "void Base.Goo()"); [WpfFact] public async Task GenericTypeNameSubstitutedForGenericInDerivedClass1() @@ -842,9 +774,8 @@ public class SomeClass : Base } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543756")] - public async Task ParameterTypeSimplified() - { - var markup = """ + public Task ParameterTypeSimplified() + => VerifyItemExistsAsync(""" using System; public abstract class Base @@ -856,15 +787,11 @@ public class SomeClass : Base { override $$ } - """; - - await VerifyItemExistsAsync(markup, "Goo(Exception e)"); - } + """, "Goo(Exception e)"); [WpfFact] - public async Task NullableAnnotationsIncluded() - { - var markup = """ + public Task NullableAnnotationsIncluded() + => VerifyItemExistsAsync(""" #nullable enable public abstract class Base @@ -876,14 +803,12 @@ public class SomeClass : Base { override $$ } - """; - await VerifyItemExistsAsync(markup, "Goo(string? s)"); - } + """, "Goo(string? s)"); [WpfFact] public async Task EscapedMethodNameInIntelliSenseList() { - var markup = """ + MarkupTestFile.GetPosition(""" public abstract class Base { public abstract void @class(); @@ -893,8 +818,7 @@ public class SomeClass : Base { override $$ } - """; - MarkupTestFile.GetPosition(markup, out var code, out int position); + """, out var code, out int position); await BaseVerifyWorkerAsync(code, position, "@class()", "void Base.@class()", SourceCodeKind.Regular, false, deletedCharTrigger: null, false, null, null, null, null, null, null); await BaseVerifyWorkerAsync(code, position, "@class()", "void Base.@class()", SourceCodeKind.Script, false, deletedCharTrigger: null, false, null, null, null, null, null, null); @@ -903,7 +827,7 @@ public class SomeClass : Base [WpfFact] public async Task EscapedPropertyNameInIntelliSenseList() { - var markup = """ + MarkupTestFile.GetPosition(""" public abstract class Base { public virtual int @class { get; set; } @@ -913,17 +837,15 @@ public class SomeClass : Base { override $$ } - """; - MarkupTestFile.GetPosition(markup, out var code, out int position); + """, out var code, out int position); await BaseVerifyWorkerAsync(code, position, "@class", "int Base.@class { get; set; }", SourceCodeKind.Regular, false, deletedCharTrigger: null, false, null, null, null, null, null, null); await BaseVerifyWorkerAsync(code, position, "@class", "int Base.@class { get; set; }", SourceCodeKind.Script, false, deletedCharTrigger: null, false, null, null, null, null, null, null); } [WpfFact] - public async Task EscapedParameterNameInIntelliSenseList() - { - var markup = """ + public Task EscapedParameterNameInIntelliSenseList() + => VerifyItemExistsAsync(""" public abstract class Base { public abstract void goo(int @class); @@ -933,15 +855,11 @@ public class SomeClass : Base { override $$ } - """; - - await VerifyItemExistsAsync(markup, "goo(int @class)", "void Base.goo(int @class)"); - } + """, "goo(int @class)", "void Base.goo(int @class)"); [WpfFact] - public async Task RefParameter() - { - var markup = """ + public Task RefParameter() + => VerifyItemExistsAsync(""" public abstract class Base { public abstract void goo(int x, ref string y); @@ -951,15 +869,11 @@ public class SomeClass : Base { override $$ } - """; - - await VerifyItemExistsAsync(markup, "goo(int x, ref string y)", "void Base.goo(int x, ref string y)"); - } + """, "goo(int x, ref string y)", "void Base.goo(int x, ref string y)"); [WpfFact] - public async Task OutParameter() - { - var markup = """ + public Task OutParameter() + => VerifyItemExistsAsync(""" public abstract class Base { public abstract void goo(int x, out string y); @@ -969,15 +883,11 @@ public class SomeClass : Base { override $$ } - """; - - await VerifyItemExistsAsync(markup, "goo(int x, out string y)", "void Base.goo(int x, out string y)"); - } + """, "goo(int x, out string y)", "void Base.goo(int x, out string y)"); [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529714")] - public async Task GenericMethodTypeParametersNotRenamed() - { - var markup = """ + public Task GenericMethodTypeParametersNotRenamed() + => VerifyItemExistsAsync(""" abstract class CGoo { public virtual X Something(X arg) @@ -989,14 +899,11 @@ class Derived : CGoo { override $$ } - """; - await VerifyItemExistsAsync(markup, "Something(X arg)"); - } + """, "Something(X arg)"); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/77193")] - public async Task CommitBeforeAttribute1() - { - var markupBeforeCommit = """ + public Task CommitBeforeAttribute1() + => VerifyCustomCommitProviderAsync(""" namespace InteliSenseIssue { [AttributeUsage(AttributeTargets.All)] @@ -1010,9 +917,7 @@ override Eq$$ public int Disregard = 34; } } - """; - - var expectedCodeAfterCommit = """ + """, "Equals(object obj)", """ namespace InteliSenseIssue { [AttributeUsage(AttributeTargets.All)] @@ -1029,15 +934,11 @@ public override bool Equals(object obj) public int Disregard = 34; } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Equals(object obj)", expectedCodeAfterCommit); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/77193")] - public async Task CommitBeforeAttribute2() - { - var markupBeforeCommit = """ + public Task CommitBeforeAttribute2() + => VerifyCustomCommitProviderAsync(""" namespace InteliSenseIssue { [AttributeUsage(AttributeTargets.All)] @@ -1052,9 +953,7 @@ override Eq$$ public int Disregard = 34; } } - """; - - var expectedCodeAfterCommit = """ + """, "Equals(object obj)", """ namespace InteliSenseIssue { [AttributeUsage(AttributeTargets.All)] @@ -1072,15 +971,11 @@ public override bool Equals(object obj) public int Disregard = 34; } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Equals(object obj)", expectedCodeAfterCommit); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/77193")] - public async Task CommitBeforeAttribute3() - { - var markupBeforeCommit = """ + public Task CommitBeforeAttribute3() + => VerifyCustomCommitProviderAsync(""" namespace InteliSenseIssue { [AttributeUsage(AttributeTargets.All)] @@ -1093,9 +988,7 @@ override Eq$$ [That] public int Disregard = 34; } } - """; - - var expectedCodeAfterCommit = """ + """, "Equals(object obj)", """ namespace InteliSenseIssue { [AttributeUsage(AttributeTargets.All)] @@ -1111,15 +1004,11 @@ public override bool Equals(object obj) [That] public int Disregard = 34; } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Equals(object obj)", expectedCodeAfterCommit); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/77193")] - public async Task CommitBeforeAttribute4() - { - var markupBeforeCommit = """ + public Task CommitBeforeAttribute4() + => VerifyCustomCommitProviderAsync(""" namespace InteliSenseIssue { [AttributeUsage(AttributeTargets.All)] @@ -1134,9 +1023,7 @@ override Eq$$ public int Disregard = 34; } } - """; - - var expectedCodeAfterCommit = """ + """, "Equals(object obj)", """ namespace InteliSenseIssue { [AttributeUsage(AttributeTargets.All)] @@ -1154,15 +1041,11 @@ public override bool Equals(object obj) public int Disregard = 34; } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Equals(object obj)", expectedCodeAfterCommit); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/77193")] - public async Task CommitBeforeAttribute5() - { - var markupBeforeCommit = """ + public Task CommitBeforeAttribute5() + => VerifyCustomCommitProviderAsync(""" namespace InteliSenseIssue { [AttributeUsage(AttributeTargets.All)] @@ -1176,9 +1059,7 @@ override Eq$$ public int Disregard = 34; } } - """; - - var expectedCodeAfterCommit = """ + """, "Equals(object obj)", """ namespace InteliSenseIssue { [AttributeUsage(AttributeTargets.All)] @@ -1195,15 +1076,11 @@ public override bool Equals(object obj) public int Disregard = 34; } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Equals(object obj)", expectedCodeAfterCommit); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/77193")] - public async Task CommitBeforeAttribute6() - { - var markupBeforeCommit = """ + public Task CommitBeforeAttribute6() + => VerifyCustomCommitProviderAsync(""" namespace InteliSenseIssue { [AttributeUsage(AttributeTargets.All)] @@ -1219,9 +1096,7 @@ override Eq$$ public int Disregard = 34; } } - """; - - var expectedCodeAfterCommit = """ + """, "Equals(object obj)", """ namespace InteliSenseIssue { [AttributeUsage(AttributeTargets.All)] @@ -1240,15 +1115,11 @@ public override bool Equals(object obj) public int Disregard = 34; } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Equals(object obj)", expectedCodeAfterCommit); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/77193")] - public async Task CommitBeforeAttribute7() - { - var markupBeforeCommit = """ + public Task CommitBeforeAttribute7() + => VerifyCustomCommitProviderAsync(""" namespace InteliSenseIssue { [AttributeUsage(AttributeTargets.All)] @@ -1261,9 +1132,7 @@ override Eq$$ [That] /* inline comment */ public int Disregard = 34; } } - """; - - var expectedCodeAfterCommit = """ + """, "Equals(object obj)", """ namespace InteliSenseIssue { [AttributeUsage(AttributeTargets.All)] @@ -1279,25 +1148,19 @@ public override bool Equals(object obj) [That] /* inline comment */ public int Disregard = 34; } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Equals(object obj)", expectedCodeAfterCommit); - } + """); #endregion #region "Commit tests" [WpfFact] - public async Task CommitInEmptyClass() - { - var markupBeforeCommit = """ + public Task CommitInEmptyClass() + => VerifyCustomCommitProviderAsync(""" class c { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "Equals(object obj)", """ class c { public override bool Equals(object obj) @@ -1305,15 +1168,11 @@ public override bool Equals(object obj) return base.Equals(obj);$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Equals(object obj)", expectedCodeAfterCommit); - } + """); [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529714")] - public async Task CommitGenericMethodTypeParametersNotRenamed() - { - var markupBeforeCommit = """ + public Task CommitGenericMethodTypeParametersNotRenamed() + => VerifyCustomCommitProviderAsync(""" abstract class CGoo { public virtual X Something(X arg) @@ -1325,9 +1184,7 @@ class Derived : CGoo { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "Something(X arg)", """ abstract class CGoo { public virtual X Something(X arg) @@ -1342,23 +1199,18 @@ public override X Something(X arg) return base.Something(arg);$$ } } - """; - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Something(X arg)", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitMethodBeforeMethod() - { - var markupBeforeCommit = """ + public Task CommitMethodBeforeMethod() + => VerifyCustomCommitProviderAsync(""" class c { override $$ public void goo() { } } - """; - - var expectedCodeAfterCommit = """ + """, "Equals(object obj)", """ class c { public override bool Equals(object obj) @@ -1368,24 +1220,18 @@ public override bool Equals(object obj) public void goo() { } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Equals(object obj)", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitMethodAfterMethod() - { - var markupBeforeCommit = """ + public Task CommitMethodAfterMethod() + => VerifyCustomCommitProviderAsync(""" class c { public void goo() { } override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "Equals(object obj)", """ class c { public void goo() { } @@ -1395,15 +1241,11 @@ public override bool Equals(object obj) return base.Equals(obj);$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Equals(object obj)", expectedCodeAfterCommit); - } + """); [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543798")] - public async Task CommitOptionalParameterValuesAreGenerated() - { - var markupBeforeCommit = """ + public Task CommitOptionalParameterValuesAreGenerated() + => VerifyCustomCommitProviderAsync(""" using System; abstract public class Base @@ -1415,9 +1257,7 @@ public class Derived : Base { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo(int x = 42)", """ using System; abstract public class Base @@ -1432,15 +1272,11 @@ public override void goo(int x = 42) throw new NotImplementedException();$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(int x = 42)", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitAttributesAreNotGenerated() - { - var markupBeforeCommit = """ + public Task CommitAttributesAreNotGenerated() + => VerifyCustomCommitProviderAsync(""" using System; public class Base @@ -1455,9 +1291,7 @@ public class Derived : Base { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ using System; public class Base @@ -1475,15 +1309,11 @@ public override void goo() base.goo();$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitInaccessibleParameterAttributesAreNotGenerated() - { - var markupBeforeCommit = """ + public Task CommitInaccessibleParameterAttributesAreNotGenerated() + => VerifyCustomCommitProviderAsync(""" using System; public class Class1 @@ -1497,9 +1327,7 @@ public class Class2 : Class1 { public override void $$ } - """; - - var expectedCodeAfterCommit = """ + """, "M(int i)", """ using System; public class Class1 @@ -1516,15 +1344,11 @@ public override void M([MyPublic] int i) base.M(i);$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "M(int i)", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitVoidMethod() - { - var markupBeforeCommit = """ + public Task CommitVoidMethod() + => VerifyCustomCommitProviderAsync(""" class c { public virtual void goo() { } @@ -1534,9 +1358,7 @@ class d : c { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ class c { public virtual void goo() { } @@ -1549,15 +1371,11 @@ public override void goo() base.goo();$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitVoidMethodWithParams() - { - var markupBeforeCommit = """ + public Task CommitVoidMethodWithParams() + => VerifyCustomCommitProviderAsync(""" class c { public virtual void goo(int bar, int quux) { } @@ -1567,9 +1385,7 @@ class d : c { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo(int bar, int quux)", """ class c { public virtual void goo(int bar, int quux) { } @@ -1582,15 +1398,11 @@ public override void goo(int bar, int quux) base.goo(bar, quux);$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(int bar, int quux)", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitNonVoidMethod() - { - var markupBeforeCommit = """ + public Task CommitNonVoidMethod() + => VerifyCustomCommitProviderAsync(""" class c { public virtual int goo() { } @@ -1600,9 +1412,7 @@ class d : c { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ class c { public virtual int goo() { } @@ -1615,15 +1425,11 @@ public override int goo() return base.goo();$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitNonVoidMethodWithParams() - { - var markupBeforeCommit = """ + public Task CommitNonVoidMethodWithParams() + => VerifyCustomCommitProviderAsync(""" class c { public virtual int goo(int bar, int quux) { } @@ -1633,9 +1439,7 @@ class d : c { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo(int bar, int quux)", """ class c { public virtual int goo(int bar, int quux) { } @@ -1648,15 +1452,11 @@ public override int goo(int bar, int quux) return base.goo(bar, quux);$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(int bar, int quux)", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitProtectedMethod() - { - var markupBeforeCommit = """ + public Task CommitProtectedMethod() + => VerifyCustomCommitProviderAsync(""" class c { protected virtual void goo() { } @@ -1666,8 +1466,7 @@ class d : c { override $$ } - """; - var expectedCodeAfterCommit = """ + """, "goo()", """ class c { protected virtual void goo() { } @@ -1680,15 +1479,11 @@ protected override void goo() base.goo();$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitInternalMethod() - { - var markupBeforeCommit = """ + public Task CommitInternalMethod() + => VerifyCustomCommitProviderAsync(""" class c { internal virtual void goo() { } @@ -1698,9 +1493,7 @@ class d : c { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ class c { internal virtual void goo() { } @@ -1713,15 +1506,11 @@ internal override void goo() base.goo();$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitProtectedInternalMethod() - { - var markupBeforeCommit = """ + public Task CommitProtectedInternalMethod() + => VerifyCustomCommitProviderAsync(""" public class c { protected internal virtual void goo() { } @@ -1731,9 +1520,7 @@ class d : c { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ public class c { protected internal virtual void goo() { } @@ -1746,15 +1533,11 @@ protected internal override void goo() base.goo();$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitAbstractMethodThrows() - { - var markupBeforeCommit = """ + public Task CommitAbstractMethodThrows() + => VerifyCustomCommitProviderAsync(""" using System; abstract class c @@ -1766,9 +1549,7 @@ class d : c { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ using System; abstract class c @@ -1783,15 +1564,11 @@ public override void goo() throw new NotImplementedException();$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitOverrideAsAbstract() - { - var markupBeforeCommit = """ + public Task CommitOverrideAsAbstract() + => VerifyCustomCommitProviderAsync(""" class c { public virtual void goo() { }; @@ -1801,9 +1578,7 @@ class d : c { abstract override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ class c { public virtual void goo() { }; @@ -1813,15 +1588,11 @@ class d : c { public abstract override void goo();$$ } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitOverrideAsUnsafeSealed() - { - var markupBeforeCommit = """ + public Task CommitOverrideAsUnsafeSealed() + => VerifyCustomCommitProviderAsync(""" class c { public virtual void goo() { }; @@ -1831,9 +1602,7 @@ class d : c { unsafe sealed override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ class c { public virtual void goo() { }; @@ -1846,15 +1615,11 @@ public sealed override unsafe void goo() base.goo();$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitInsertProperty() - { - var markupBeforeCommit = """ + public Task CommitInsertProperty() + => VerifyCustomCommitProviderAsync(""" public class c { public virtual int goo { get; set; } @@ -1864,9 +1629,7 @@ public class d : c { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo", """ public class c { public virtual int goo { get; set; } @@ -1887,15 +1650,11 @@ public override int goo } } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitInsertPropertyAfterMethod() - { - var markupBeforeCommit = """ + public Task CommitInsertPropertyAfterMethod() + => VerifyCustomCommitProviderAsync(""" public class c { public virtual int goo { get; set; } @@ -1906,9 +1665,7 @@ public class d : c public void a() { } override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo", """ public class c { public virtual int goo { get; set; } @@ -1930,15 +1687,11 @@ public override int goo } } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitInsertPropertyBeforeMethod() - { - var markupBeforeCommit = """ + public Task CommitInsertPropertyBeforeMethod() + => VerifyCustomCommitProviderAsync(""" public class c { public virtual int goo { get; set; } @@ -1949,9 +1702,7 @@ public class d : c override $$ public void a() { } } - """; - - var expectedCodeAfterCommit = """ + """, "goo", """ public class c { public virtual int goo { get; set; } @@ -1973,15 +1724,11 @@ public override int goo } public void a() { } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitPropertyInaccessibleGet() - { - var markupBeforeCommit = """ + public Task CommitPropertyInaccessibleGet() + => VerifyCustomCommitProviderAsync(""" public class c { public virtual int goo { private get; set; } @@ -1991,9 +1738,7 @@ public class d : c { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo", """ public class c { public virtual int goo { private get; set; } @@ -2009,15 +1754,11 @@ public override int goo } } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitPropertyInaccessibleSet() - { - var markupBeforeCommit = """ + public Task CommitPropertyInaccessibleSet() + => VerifyCustomCommitProviderAsync(""" public class c { public virtual int goo { private set; get; } @@ -2027,9 +1768,7 @@ public class d : c { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo", """ public class c { public virtual int goo { private set; get; } @@ -2045,15 +1784,11 @@ public override int goo } } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitInsertPropertyInaccessibleParameterAttributesAreNotGenerated() - { - var markupBeforeCommit = """ + public Task CommitInsertPropertyInaccessibleParameterAttributesAreNotGenerated() + => VerifyCustomCommitProviderAsync(""" using System; namespace ClassLibrary1 @@ -2076,9 +1811,7 @@ public class Class2 : Class1 public override int $$ } } - """; - - var expectedCodeAfterCommit = """ + """, "this[int i]", """ using System; namespace ClassLibrary1 @@ -2112,15 +1845,11 @@ public override int this[[MyPublic] int i] } } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "this[int i]", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitAccessibleEvent() - { - var markupBeforeCommit = """ + public Task CommitAccessibleEvent() + => VerifyCustomCommitProviderAsync(""" using System; public class a { @@ -2131,9 +1860,7 @@ public class b : a { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo", """ using System; public class a { @@ -2144,15 +1871,11 @@ public class b : a { public override event EventHandler goo;$$ } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitEventAfterMethod() - { - var markupBeforeCommit = """ + public Task CommitEventAfterMethod() + => VerifyCustomCommitProviderAsync(""" using System; public class a @@ -2165,9 +1888,7 @@ public class b : a void bar() { } override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo", """ using System; public class a @@ -2180,15 +1901,11 @@ public class b : a void bar() { } public override event EventHandler goo;$$ } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitGenericMethod() - { - var markupBeforeCommit = """ + public Task CommitGenericMethod() + => VerifyCustomCommitProviderAsync(""" using System; public class a @@ -2200,9 +1917,7 @@ public class b : a { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ using System; public class a @@ -2217,15 +1932,11 @@ public override void goo() base.goo();$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitMethodWithNullableAttributes() - { - var markupBeforeCommit = """ + public Task CommitMethodWithNullableAttributes() + => VerifyCustomCommitProviderAsync(""" #nullable enable class C @@ -2237,9 +1948,7 @@ class D : C { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "Goo(string? s)", """ #nullable enable class C @@ -2254,15 +1963,11 @@ class D : C return base.Goo(s);$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Goo(string? s)", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitMethodInNullableDisableContext() - { - var markupBeforeCommit = """ + public Task CommitMethodInNullableDisableContext() + => VerifyCustomCommitProviderAsync(""" #nullable enable class C @@ -2276,9 +1981,7 @@ class D : C { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "Goo(string? s)", """ #nullable enable class C @@ -2295,15 +1998,11 @@ public override string Goo(string s) return base.Goo(s);$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Goo(string? s)", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitToStringIsExplicitlyNonNullReturning() - { - var markupBeforeCommit = """ + public Task CommitToStringIsExplicitlyNonNullReturning() + => VerifyCustomCommitProviderAsync(""" #nullable enable namespace System @@ -2318,9 +2017,7 @@ class D : System.Object { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "ToString()", """ #nullable enable namespace System @@ -2338,15 +2035,11 @@ public override string ToString() return base.ToString();$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "ToString()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitInsertIndexer() - { - var markupBeforeCommit = """ + public Task CommitInsertIndexer() + => VerifyCustomCommitProviderAsync(""" public class MyIndexer { private T[] arr = new T[100]; @@ -2367,9 +2060,7 @@ class d : MyIndexer { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "this[int i]", """ public class MyIndexer { private T[] arr = new T[100]; @@ -2401,15 +2092,11 @@ public override T this[int i] } } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "this[int i]", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitAbstractIndexer() - { - var markupBeforeCommit = """ + public Task CommitAbstractIndexer() + => VerifyCustomCommitProviderAsync(""" public class MyIndexer { private T[] arr = new T[100]; @@ -2420,9 +2107,7 @@ class d : MyIndexer { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "this[int i]", """ public class MyIndexer { private T[] arr = new T[100]; @@ -2444,10 +2129,7 @@ public override T this[int i] } } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "this[int i]", expectedCodeAfterCommit); - } + """); // The following two scenarios are already verified through 'VerifyCommit', // which also tests everything at the end of the file (truncating input markup at $$) @@ -2455,9 +2137,8 @@ public override T this[int i] // public void CommitInsertAtEndOfFileAfterMethod() [WpfFact] - public async Task CommitFormats() - { - var markupBeforeCommit = """ + public Task CommitFormats() + => VerifyCustomCommitProviderAsync(""" class Base { public virtual void goo() { } @@ -2467,9 +2148,7 @@ class Derived : Base { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ class Base { public virtual void goo() { } @@ -2482,15 +2161,11 @@ public override void goo() base.goo();$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitSimplifiesParameterTypes() - { - var markupBeforeCommit = """ + public Task CommitSimplifiesParameterTypes() + => VerifyCustomCommitProviderAsync(""" using System; public abstract class Base @@ -2502,9 +2177,7 @@ public class SomeClass : Base { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo(Exception e)", """ using System; public abstract class Base @@ -2519,15 +2192,11 @@ public override void goo(Exception e) throw new NotImplementedException();$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(Exception e)", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitSimplifiesReturnType() - { - var markupBeforeCommit = """ + public Task CommitSimplifiesReturnType() + => VerifyCustomCommitProviderAsync(""" using System; public abstract class Base @@ -2539,9 +2208,7 @@ public class SomeClass : Base { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo(Exception e)", """ using System; public abstract class Base @@ -2556,15 +2223,11 @@ public override ArgumentException goo(Exception e) throw new NotImplementedException();$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(Exception e)", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitEscapedMethodName() - { - var markupBeforeCommit = """ + public Task CommitEscapedMethodName() + => VerifyCustomCommitProviderAsync(""" using System; public abstract class Base @@ -2576,8 +2239,7 @@ public class SomeClass : Base { override $$ } - """; - var expectedCodeAfterCommit = """ + """, "@class()", """ using System; public abstract class Base @@ -2592,15 +2254,11 @@ public override void @class() throw new NotImplementedException();$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "@class()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitEscapedPropertyName() - { - var markupBeforeCommit = """ + public Task CommitEscapedPropertyName() + => VerifyCustomCommitProviderAsync(""" public abstract class Base { public virtual int @class { get; set; } @@ -2610,9 +2268,7 @@ public class SomeClass : Base { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "@class", """ public abstract class Base { public virtual int @class { get; set; } @@ -2633,15 +2289,11 @@ public override int @class } } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "@class", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitEscapedParameterName() - { - var markupBeforeCommit = """ + public Task CommitEscapedParameterName() + => VerifyCustomCommitProviderAsync(""" using System; public abstract class Base @@ -2653,9 +2305,7 @@ public class SomeClass : Base { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo(int @class)", """ using System; public abstract class Base @@ -2670,15 +2320,11 @@ public override void goo(int @class) throw new NotImplementedException();$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(int @class)", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitRefParameter() - { - var markupBeforeCommit = """ + public Task CommitRefParameter() + => VerifyCustomCommitProviderAsync(""" using System; public abstract class Base @@ -2690,9 +2336,7 @@ public class SomeClass : Base { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo(int x, ref string y)", """ using System; public abstract class Base @@ -2707,15 +2351,11 @@ public override void goo(int x, ref string y) throw new NotImplementedException();$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(int x, ref string y)", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitOutParameter() - { - var markupBeforeCommit = """ + public Task CommitOutParameter() + => VerifyCustomCommitProviderAsync(""" using System; public abstract class Base @@ -2727,9 +2367,7 @@ public class SomeClass : Base { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo(int x, out string y)", """ using System; public abstract class Base @@ -2744,16 +2382,11 @@ public override void goo(int x, out string y) throw new NotImplementedException();$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(int x, out string y)", expectedCodeAfterCommit); - } + """); [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544560")] - public async Task TestUnsafe1() - { - var markupBeforeCommit = - """ + public Task TestUnsafe1() + => VerifyCustomCommitProviderAsync(""" public class A { public unsafe virtual void F() @@ -2765,10 +2398,7 @@ public class B : A { override $$ } - """; - - var expectedCodeAfterCommit = - """ + """, "F()", """ public class A { public unsafe virtual void F() @@ -2783,16 +2413,11 @@ public override void F() base.F();$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "F()", expectedCodeAfterCommit); - } + """); [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544560")] - public async Task TestUnsafe2() - { - var markupBeforeCommit = - """ + public Task TestUnsafe2() + => VerifyCustomCommitProviderAsync(""" public class A { public unsafe virtual void F() @@ -2804,10 +2429,7 @@ public class B : A { override unsafe $$ } - """; - - var expectedCodeAfterCommit = - """ + """, "F()", """ public class A { public unsafe virtual void F() @@ -2822,16 +2444,11 @@ public override unsafe void F() base.F();$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "F()", expectedCodeAfterCommit); - } + """); [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544560")] - public async Task TestUnsafe3() - { - var markupBeforeCommit = - """ + public Task TestUnsafe3() + => VerifyCustomCommitProviderAsync(""" public class A { public unsafe virtual void F() @@ -2843,10 +2460,7 @@ public class B : A { unsafe override $$ } - """; - - var expectedCodeAfterCommit = - """ + """, "F()", """ public class A { public unsafe virtual void F() @@ -2861,16 +2475,11 @@ public override unsafe void F() base.F();$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "F()", expectedCodeAfterCommit); - } + """); [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544560")] - public async Task TestUnsafe4() - { - var markupBeforeCommit = - """ + public Task TestUnsafe4() + => VerifyCustomCommitProviderAsync(""" public class A { public virtual void F(int* i) @@ -2882,10 +2491,7 @@ public class B : A { override $$ } - """; - - var expectedCodeAfterCommit = - """ + """, "F(int* i)", """ public class A { public virtual void F(int* i) @@ -2900,16 +2506,11 @@ public override unsafe void F(int* i) base.F(i);$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "F(int* i)", expectedCodeAfterCommit); - } + """); [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545534")] - public async Task TestPrivateVirtualProperty() - { - var markupBeforeCommit = - """ + public Task TestPrivateVirtualProperty() + => VerifyCustomCommitProviderAsync(""" public class B { public virtual int Goo @@ -2922,10 +2523,7 @@ class C : B override $$ } } - """; - - var expectedCodeAfterCommit = - """ + """, "Goo", """ public class B { public virtual int Goo @@ -2944,10 +2542,7 @@ public override int Goo } } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Goo", expectedCodeAfterCommit); - } + """); [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636706")] public async Task CrossLanguageParameterizedPropertyOverride() @@ -2970,19 +2565,6 @@ class Program : Goo override $$ } """; - var csharpFileAfterCommit = """ - class Program : Goo - { - public override int get_Bar(int bay) - { - return base.get_Bar(bay);$$ - } - public override void set_Bar(int bay, int value) - { - base.set_Bar(bay, value); - } - } - """; var xmlString = string.Format(""" @@ -3018,7 +2600,19 @@ public override void set_Bar(int bay, int value) customCommitCompletionProvider.Commit(completionItem, document, textView, textView.TextBuffer, textView.TextSnapshot, '\t'); var actualCodeAfterCommit = textView.TextBuffer.CurrentSnapshot.AsText().ToString(); var caretPosition = textView.Caret.Position.BufferPosition.Position; - MarkupTestFile.GetPosition(csharpFileAfterCommit, out var actualExpectedCode, out int expectedCaretPosition); + MarkupTestFile.GetPosition(""" + class Program : Goo + { + public override int get_Bar(int bay) + { + return base.get_Bar(bay);$$ + } + public override void set_Bar(int bay, int value) + { + base.set_Bar(bay, value); + } + } + """, out var actualExpectedCode, out int expectedCaretPosition); Assert.Equal(actualExpectedCode, actualCodeAfterCommit); Assert.Equal(expectedCaretPosition, caretPosition); @@ -3030,9 +2624,8 @@ public override void set_Bar(int bay, int value) #region "Commit: With Trivia" [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529199")] - public async Task CommitSurroundingTriviaDirective() - { - var markupBeforeCommit = """ + public Task CommitSurroundingTriviaDirective() + => VerifyCustomCommitProviderAsync(""" class Base { public virtual void goo() { } @@ -3044,9 +2637,7 @@ class Derived : Base override $$ #endif } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ class Base { public virtual void goo() { } @@ -3061,14 +2652,11 @@ public override void goo() } #endif } - """; - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529199")] - public async Task CommitBeforeTriviaDirective() - { - var markupBeforeCommit = """ + public Task CommitBeforeTriviaDirective() + => VerifyCustomCommitProviderAsync(""" class Base { public virtual void goo() { } @@ -3080,9 +2668,7 @@ class Derived : Base #if true #endif } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ class Base { public virtual void goo() { } @@ -3097,14 +2683,11 @@ public override void goo() #if true #endif } - """; - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitAfterTriviaDirective() - { - var markupBeforeCommit = """ + public Task CommitAfterTriviaDirective() + => VerifyCustomCommitProviderAsync(""" class Base { public virtual void goo() { } @@ -3116,9 +2699,7 @@ class Derived : Base #endif override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ class Base { public virtual void goo() { } @@ -3133,14 +2714,11 @@ public override void goo() base.goo();$$ } } - """; - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529199")] - public async Task CommitBeforeComment1() - { - var markupBeforeCommit = """ + public Task CommitBeforeComment1() + => VerifyCustomCommitProviderAsync(""" class Base { public virtual void goo() { } @@ -3151,9 +2729,7 @@ class Derived : Base override $$ /* comment */ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ class Base { public virtual void goo() { } @@ -3167,14 +2743,11 @@ public override void goo() } /* comment */ } - """; - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitBeforeComment2() - { - var markupBeforeCommit = """ + public Task CommitBeforeComment2() + => VerifyCustomCommitProviderAsync(""" class Base { public virtual void goo() { } @@ -3184,9 +2757,7 @@ class Derived : Base { override $$/* comment */ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ class Base { public virtual void goo() { } @@ -3199,14 +2770,11 @@ public override void goo() base.goo();$$ } /* comment */ } - """; - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitBeforeComment3() - { - var markupBeforeCommit = """ + public Task CommitBeforeComment3() + => VerifyCustomCommitProviderAsync(""" class Base { public virtual void goo() { } @@ -3216,9 +2784,7 @@ class Derived : Base { override go$$/* comment */ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ class Base { public virtual void goo() { } @@ -3231,14 +2797,11 @@ public override void goo() base.goo();$$ } /* comment */ } - """; - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitAfterComment1() - { - var markupBeforeCommit = """ + public Task CommitAfterComment1() + => VerifyCustomCommitProviderAsync(""" class Base { public virtual void goo() { } @@ -3249,9 +2812,7 @@ class Derived : Base /* comment */ override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ class Base { public virtual void goo() { } @@ -3265,14 +2826,11 @@ public override void goo() base.goo();$$ } } - """; - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitAfterComment2() - { - var markupBeforeCommit = """ + public Task CommitAfterComment2() + => VerifyCustomCommitProviderAsync(""" class Base { public virtual void goo() { } @@ -3284,9 +2842,7 @@ class Derived : Base // another comment override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ class Base { public virtual void goo() { } @@ -3301,14 +2857,11 @@ public override void goo() base.goo();$$ } } - """; - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitAfterComment3() - { - var markupBeforeCommit = """ + public Task CommitAfterComment3() + => VerifyCustomCommitProviderAsync(""" class Base { public virtual void goo() { } @@ -3318,9 +2871,7 @@ class Derived : Base { /* comment */ override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ class Base { public virtual void goo() { } @@ -3334,14 +2885,11 @@ public override void goo() base.goo();$$ } } - """; - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitAfterComment4() - { - var markupBeforeCommit = """ + public Task CommitAfterComment4() + => VerifyCustomCommitProviderAsync(""" class Base { public virtual void goo() { } @@ -3351,9 +2899,7 @@ class Derived : Base { /* comment */ override go$$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ class Base { public virtual void goo() { } @@ -3367,14 +2913,11 @@ public override void goo() base.goo();$$ } } - """; - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitBeforeAndAfterComment() - { - var markupBeforeCommit = """ + public Task CommitBeforeAndAfterComment() + => VerifyCustomCommitProviderAsync(""" class Base { public virtual void goo() { } @@ -3386,9 +2929,7 @@ class Derived : Base override $$ /* comment */ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ class Base { public virtual void goo() { } @@ -3403,14 +2944,11 @@ public override void goo() } /* comment */ } - """; - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task DoNotFormatFile() - { - var markupBeforeCommit = """ + public Task DoNotFormatFile() + => VerifyCustomCommitProviderAsync(""" class Program { int zip; @@ -3425,9 +2963,7 @@ class C : Program int bar; override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ class Program { int zip; @@ -3445,9 +2981,7 @@ public override void goo() base.goo();$$ } } - """; - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/736742")] public async Task AcrossPartialTypes1() @@ -3463,15 +2997,6 @@ partial class c override $$ } """; - var csharpFileAfterCommit = """ - partial class c - { - public override bool Equals(object obj) - { - return base.Equals(obj);$$ - } - } - """; var xmlString = string.Format(""" @@ -3501,7 +3026,15 @@ public override bool Equals(object obj) customCommitCompletionProvider.Commit(completionItem, document, textView, textView.TextBuffer, textView.TextSnapshot, '\t'); var actualCodeAfterCommit = textView.TextBuffer.CurrentSnapshot.AsText().ToString(); var caretPosition = textView.Caret.Position.BufferPosition.Position; - MarkupTestFile.GetPosition(csharpFileAfterCommit, out var actualExpectedCode, out int expectedCaretPosition); + MarkupTestFile.GetPosition(""" + partial class c + { + public override bool Equals(object obj) + { + return base.Equals(obj);$$ + } + } + """, out var actualExpectedCode, out int expectedCaretPosition); Assert.Equal(actualExpectedCode, actualCodeAfterCommit); Assert.Equal(expectedCaretPosition, caretPosition); @@ -3522,15 +3055,6 @@ partial class c override $$ } """; - var csharpFileAfterCommit = """ - partial class c - { - public override bool Equals(object obj) - { - return base.Equals(obj);$$ - } - } - """; var xmlString = string.Format(""" @@ -3560,7 +3084,15 @@ public override bool Equals(object obj) customCommitCompletionProvider.Commit(completionItem, document, textView, textView.TextBuffer, textView.TextSnapshot, '\t'); var actualCodeAfterCommit = textView.TextBuffer.CurrentSnapshot.AsText().ToString(); var caretPosition = textView.Caret.Position.BufferPosition.Position; - MarkupTestFile.GetPosition(csharpFileAfterCommit, out var actualExpectedCode, out int expectedCaretPosition); + MarkupTestFile.GetPosition(""" + partial class c + { + public override bool Equals(object obj) + { + return base.Equals(obj);$$ + } + } + """, out var actualExpectedCode, out int expectedCaretPosition); Assert.Equal(actualExpectedCode, actualCodeAfterCommit); Assert.Equal(expectedCaretPosition, caretPosition); @@ -3568,9 +3100,8 @@ public override bool Equals(object obj) } [WpfFact] - public async Task CommitRequiredKeywordAdded() - { - var markupBeforeCommit = """ + public Task CommitRequiredKeywordAdded() + => VerifyCustomCommitProviderAsync(""" class Base { public virtual required int Prop { get; } @@ -3580,9 +3111,7 @@ class Derived : Base { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "Prop", """ class Base { public virtual required int Prop { get; } @@ -3598,16 +3127,13 @@ public override required int Prop } } } - """; - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Prop", expectedCodeAfterCommit); - } + """); [WpfTheory] [InlineData("required override")] [InlineData("override required")] - public async Task CommitRequiredKeywordPreserved(string ordering) - { - var markupBeforeCommit = $$""" + public Task CommitRequiredKeywordPreserved(string ordering) + => VerifyCustomCommitProviderAsync($$""" class Base @@ -3621,9 +3147,7 @@ class Derived : Base } - """; - - var expectedCodeAfterCommit = """ + """, "Prop", """ class Base { public virtual required int Prop { get; } @@ -3639,16 +3163,13 @@ public override required int Prop } } } - """; - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Prop", expectedCodeAfterCommit); - } + """); [WpfTheory] [InlineData("required override")] [InlineData("override required")] - public async Task CommitRequiredKeywordPreservedWhenBaseIsNotRequired(string ordering) - { - var markupBeforeCommit = $$""" + public Task CommitRequiredKeywordPreservedWhenBaseIsNotRequired(string ordering) + => VerifyCustomCommitProviderAsync($$""" class Base @@ -3662,9 +3183,7 @@ class Derived : Base } - """; - - var expectedCodeAfterCommit = """ + """, "Prop", """ class Base { public virtual int Prop { get; } @@ -3680,14 +3199,11 @@ public override required int Prop } } } - """; - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Prop", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitRequiredKeywordRemovedForMethods() - { - var markupBeforeCommit = """ + public Task CommitRequiredKeywordRemovedForMethods() + => VerifyCustomCommitProviderAsync(""" class Base { public virtual void M() { } @@ -3697,9 +3213,7 @@ class Derived : Base { required override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "M()", """ class Base { public virtual void M() { } @@ -3712,14 +3226,11 @@ public override void M() base.M();$$ } } - """; - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "M()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitRequiredKeywordRemovedForIndexers() - { - var markupBeforeCommit = """ + public Task CommitRequiredKeywordRemovedForIndexers() + => VerifyCustomCommitProviderAsync(""" class Base { public virtual int this[int i] { get { } set { } } @@ -3729,9 +3240,7 @@ class Derived : Base { required override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "this[int i]", """ class Base { public virtual int this[int i] { get { } set { } } @@ -3752,9 +3261,7 @@ public override int this[int i] } } } - """; - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "this[int i]", expectedCodeAfterCommit); - } + """); #endregion @@ -3789,9 +3296,8 @@ await VerifyItemInEditorBrowsableContextsAsync( #endregion [WpfFact] - public async Task DuplicateMember() - { - var markupBeforeCommit = """ + public Task DuplicateMember() + => VerifyCustomCommitProviderAsync(""" class Program { public virtual void goo() {} @@ -3802,9 +3308,7 @@ class C : Program { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ class Program { public virtual void goo() {} @@ -3818,9 +3322,7 @@ public override void goo() base.goo();$$ } } - """; - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] public async Task LeaveTrailingTriviaAlone() @@ -3859,9 +3361,8 @@ static void Main(string[] args) } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/8257")] - public async Task NotImplementedQualifiedWhenSystemUsingNotPresent_Property() - { - var markupBeforeCommit = """ + public Task NotImplementedQualifiedWhenSystemUsingNotPresent_Property() + => VerifyCustomCommitProviderAsync(""" abstract class C { public abstract int goo { get; set; }; @@ -3871,9 +3372,7 @@ class Program : C { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo", """ abstract class C { public abstract int goo { get; set; }; @@ -3894,15 +3393,11 @@ public override int goo } } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo", expectedCodeAfterCommit); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/8257")] - public async Task NotImplementedQualifiedWhenSystemUsingNotPresent_Method() - { - var markupBeforeCommit = """ + public Task NotImplementedQualifiedWhenSystemUsingNotPresent_Method() + => VerifyCustomCommitProviderAsync(""" abstract class C { public abstract void goo(); @@ -3912,9 +3407,7 @@ class Program : C { override $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ abstract class C { public abstract void goo(); @@ -3927,10 +3420,7 @@ public override void goo() throw new System.NotImplementedException();$$ } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [Fact] public async Task FilterOutMethodsWithNonRoundTrippableSymbolKeys() @@ -4023,17 +3513,6 @@ public abstract class Base public abstract void M(in int x); } """; - - var after = """ - public class SomeClass : Base - { - public override void M(in int x) - { - throw new System.NotImplementedException(); - } - } - """; - var origComp = await workspace.CurrentSolution.Projects.Single().GetRequiredCompilationAsync(CancellationToken.None); var options = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Latest); var libComp = origComp.RemoveAllSyntaxTrees().AddSyntaxTrees(CSharpSyntaxTree.ParseText(before, options: options)); @@ -4063,13 +3542,20 @@ public override void M(in int x) var textBuffer = workspace.Documents.Single().GetTextBuffer(); var actualCodeAfterCommit = textBuffer.CurrentSnapshot.AsText().ToString(); - Assert.Equal(after, actualCodeAfterCommit); + Assert.Equal(""" + public class SomeClass : Base + { + public override void M(in int x) + { + throw new System.NotImplementedException(); + } + } + """, actualCodeAfterCommit); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/39909")] - public async Task CommitAddsMissingImports() - { - var markupBeforeCommit = """ + public Task CommitAddsMissingImports() + => VerifyCustomCommitProviderAsync(""" namespace NS1 { using NS2; @@ -4094,9 +3580,7 @@ class D : Goo override $$ } } - """; - - var expectedCodeAfterCommit = """ + """, "Bar(NS2.Baz baz)", """ namespace NS1 { using NS2; @@ -4125,26 +3609,20 @@ public override bool Bar(Baz baz) } } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Bar(NS2.Baz baz)", expectedCodeAfterCommit); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/47941")] - public async Task OverrideInRecordWithoutExplicitOverriddenMember() - { - await VerifyItemExistsAsync(""" + public Task OverrideInRecordWithoutExplicitOverriddenMember() + => VerifyItemExistsAsync(""" record Program { override $$ } """, "ToString()"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/47941")] - public async Task OverrideInRecordWithExplicitOverriddenMember() - { - await VerifyItemIsAbsentAsync(""" + public Task OverrideInRecordWithExplicitOverriddenMember() + => VerifyItemIsAbsentAsync(""" record Program { public override string ToString() => "; @@ -4152,7 +3630,6 @@ record Program override $$ } """, "ToString()"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/47973")] public async Task NoCloneInOverriddenRecord() @@ -4175,15 +3652,13 @@ record Program : Base } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/48640")] - public async Task ObjectEqualsInClass() - { - await VerifyItemExistsAsync(""" + public Task ObjectEqualsInClass() + => VerifyItemExistsAsync(""" class Program { override $$ } """, "Equals(object obj)"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/48640")] public async Task NoObjectEqualsInOverriddenRecord1() @@ -4227,9 +3702,8 @@ record Program : Base } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/64887")] - public async Task WithAttribute1() - { - await VerifyItemExistsAsync(""" + public Task WithAttribute1() + => VerifyItemExistsAsync(""" abstract class C { public abstract void M(); @@ -4241,12 +3715,10 @@ class D : C override $$; } """, "M()"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/64887")] - public async Task WithAttribute2() - { - await VerifyItemExistsAsync(""" + public Task WithAttribute2() + => VerifyItemExistsAsync(""" abstract class C { public abstract void M(); @@ -4259,12 +3731,10 @@ class D : C override $$; } """, "M()"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/64887")] - public async Task NotWhenMultilineModifiers() - { - await VerifyItemIsAbsentAsync(""" + public Task NotWhenMultilineModifiers() + => VerifyItemIsAbsentAsync(""" abstract class C { public abstract void M(); @@ -4276,12 +3746,10 @@ class D : C override $$; } """, "M()"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/64887")] - public async Task NotWhenMultilineModifiersAndAttribute() - { - await VerifyItemIsAbsentAsync(""" + public Task NotWhenMultilineModifiersAndAttribute() + => VerifyItemIsAbsentAsync(""" abstract class C { public abstract void M(); @@ -4294,28 +3762,23 @@ class D : C override $$; } """, "M()"); - } [WpfFact, WorkItem("https://github.com/dotnet/vscode-csharp/issues/6308")] - public async Task NoOverrideItemsWhenNotInTypeDeclaration() - { - await VerifyNoItemsExistAsync(""" + public Task NoOverrideItemsWhenNotInTypeDeclaration() + => VerifyNoItemsExistAsync(""" namespace NS { override $$ } """); - } [WpfFact, WorkItem("https://github.com/dotnet/vscode-csharp/issues/6308")] - public async Task NoOverrideItemsAtTopLevel() - { - await VerifyNoItemsExistAsync(""" + public Task NoOverrideItemsAtTopLevel() + => VerifyNoItemsExistAsync(""" System.Console.WriteLine(); override $$ """); - } private Task VerifyItemExistsAsync(string markup, string expectedItem) { diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/OverrideCompletionProviderTests_ExpressionBody.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/OverrideCompletionProviderTests_ExpressionBody.cs index 82c163176c031..e7e7d864c487a 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/OverrideCompletionProviderTests_ExpressionBody.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/OverrideCompletionProviderTests_ExpressionBody.cs @@ -32,9 +32,8 @@ internal override OptionsCollection NonCompletionOptions }; [WpfFact, WorkItem(16331, "https://github.com/dotnet/roslyn/issues/16334")] - public async Task CommitProducesExpressionBodyProperties() - { - var markupBeforeCommit = """ + public Task CommitProducesExpressionBodyProperties() + => VerifyCustomCommitProviderAsync(""" class B { public virtual int A { get; set; } @@ -43,9 +42,7 @@ class C : B override A$$ } } - """; - - var expectedCodeAfterCommit = """ + """, "A", """ class B { public virtual int A { get; set; } @@ -54,15 +51,11 @@ class C : B public override int A { get => [|base.A|]; set => base.A = value; } } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "A", expectedCodeAfterCommit); - } + """); [WpfFact, WorkItem(16331, "https://github.com/dotnet/roslyn/issues/16334")] - public async Task CommitProducesExpressionBodyGetterOnlyProperty() - { - var markupBeforeCommit = """ + public Task CommitProducesExpressionBodyGetterOnlyProperty() + => VerifyCustomCommitProviderAsync(""" class B { public virtual int A { get; } @@ -71,9 +64,7 @@ class C : B override A$$ } } - """; - - var expectedCodeAfterCommit = """ + """, "A", """ class B { public virtual int A { get; } @@ -82,15 +73,11 @@ class C : B public override int A => [|base.A|]; } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "A", expectedCodeAfterCommit); - } + """); [WpfFact, WorkItem(16331, "https://github.com/dotnet/roslyn/issues/16334")] - public async Task CommitProducesExpressionBodyMethod() - { - var markupBeforeCommit = """ + public Task CommitProducesExpressionBodyMethod() + => VerifyCustomCommitProviderAsync(""" class B { public virtual int A() => 2; @@ -99,9 +86,7 @@ class C : B override A$$ } } - """; - - var expectedCodeAfterCommit = """ + """, "A()", """ class B { public virtual int A() => 2; @@ -110,8 +95,5 @@ class C : B public override int A() => [|base.A()|]; } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "A()", expectedCodeAfterCommit); - } + """); } diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/PartialMethodCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/PartialMethodCompletionProviderTests.cs index b8c5f0bb7ca52..996ecc27e042e 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/PartialMethodCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/PartialMethodCompletionProviderTests.cs @@ -23,394 +23,310 @@ internal override Type GetCompletionProviderType() => typeof(PartialMethodCompletionProvider); [Fact] - public async Task NoPartialMethods1() - { - var text = """ + public Task NoPartialMethods1() + => VerifyNoItemsExistAsync(""" class c { $$ } - """; - await VerifyNoItemsExistAsync(text); - } + """); [Fact] - public async Task NoPartialMethods2() - { - var text = """ + public Task NoPartialMethods2() + => VerifyNoItemsExistAsync(""" class c { private void goo() { }; partial void $$ } - """; - await VerifyNoItemsExistAsync(text); - } + """); [Fact] - public async Task NoExtendedPartialMethods2() - { - var text = """ + public Task NoExtendedPartialMethods2() + => VerifyNoItemsExistAsync(""" class c { public void goo() { }; public void $$ } - """; - await VerifyNoItemsExistAsync(text); - } + """); [Fact] - public async Task PartialMethodInPartialClass() - { - var text = """ + public Task PartialMethodInPartialClass() + => VerifyItemExistsAsync(""" partial class c { partial void goo(); partial void $$ } - """; - await VerifyItemExistsAsync(text, "goo()"); - } + """, "goo()"); [Fact] - public async Task ExtendedPartialMethodInPartialClass() - { - var text = """ + public Task ExtendedPartialMethodInPartialClass() + => VerifyItemExistsAsync(""" partial class c { public partial void goo(); public partial void $$ } - """; - await VerifyItemExistsAsync(text, "goo()"); - } + """, "goo()"); [Fact] - public async Task PartialMethodInPartialGenericClass() - { - var text = """ + public Task PartialMethodInPartialGenericClass() + => VerifyItemExistsAsync(""" partial class c { partial void goo(T bar); partial void $$ } - """; - await VerifyItemExistsAsync(text, "goo(T bar)"); - } + """, "goo(T bar)"); [Fact] - public async Task ExtendedPartialMethodInPartialGenericClass() - { - var text = """ + public Task ExtendedPartialMethodInPartialGenericClass() + => VerifyItemExistsAsync(""" partial class c { public partial void goo(T bar); public partial void $$ } - """; - await VerifyItemExistsAsync(text, "goo(T bar)"); - } + """, "goo(T bar)"); [Fact] - public async Task PartialMethodInPartialStruct() - { - var text = """ + public Task PartialMethodInPartialStruct() + => VerifyItemExistsAsync(""" partial struct c { partial void goo(); partial void $$ } - """; - await VerifyItemExistsAsync(text, "goo()"); - } + """, "goo()"); [Fact] - public async Task ExtendedPartialMethodInPartialStruct() - { - var text = """ + public Task ExtendedPartialMethodInPartialStruct() + => VerifyItemExistsAsync(""" partial struct c { public partial void goo(); public partial void $$ } - """; - await VerifyItemExistsAsync(text, "goo()"); - } + """, "goo()"); [Fact] - public async Task CompletionOnPartial1() - { - var text = """ + public Task CompletionOnPartial1() + => VerifyItemExistsAsync(""" partial class c { partial void goo(); partial $$ } - """; - await VerifyItemExistsAsync(text, "goo()"); - } + """, "goo()"); [Fact] - public async Task CompletionOnExtendedPartial1() - { - var text = """ + public Task CompletionOnExtendedPartial1() + => VerifyItemExistsAsync(""" partial class c { public partial void goo(); partial $$ } - """; - await VerifyItemExistsAsync(text, "goo()"); - } + """, "goo()"); [Fact] - public async Task CompletionOnPartial2() - { - var text = """ + public Task CompletionOnPartial2() + => VerifyItemExistsAsync(""" partial class c { partial void goo(); void partial $$ } - """; - await VerifyItemExistsAsync(text, "goo()"); - } + """, "goo()"); [Fact] - public async Task CompletionOnExtendedPartial2() - { - var text = """ + public Task CompletionOnExtendedPartial2() + => VerifyItemExistsAsync(""" partial class c { public partial void goo(); void partial $$ } - """; - await VerifyItemExistsAsync(text, "goo()"); - } + """, "goo()"); [Fact] - public async Task StaticUnsafePartial() - { - var text = """ + public Task StaticUnsafePartial() + => VerifyItemExistsAsync(""" partial class c { partial static unsafe void goo(); void static unsafe partial $$ } - """; - await VerifyItemExistsAsync(text, "goo()"); - } + """, "goo()"); [Fact] - public async Task StaticUnsafeExtendedPartial() - { - var text = """ + public Task StaticUnsafeExtendedPartial() + => VerifyItemExistsAsync(""" partial class c { public partial static unsafe void goo(); void static unsafe partial $$ } - """; - await VerifyItemExistsAsync(text, "goo()"); - } + """, "goo()"); [Fact] - public async Task PartialCompletionWithPrivate() - { - var text = """ + public Task PartialCompletionWithPrivate() + => VerifyItemExistsAsync(""" partial class c { partial static unsafe void goo(); private partial $$ } - """; - await VerifyItemExistsAsync(text, "goo()"); - } + """, "goo()"); [Fact] - public async Task PartialCompletionWithPublic() - { - var text = """ + public Task PartialCompletionWithPublic() + => VerifyItemExistsAsync(""" partial class c { public partial static unsafe void goo(); public partial $$ } - """; - await VerifyItemExistsAsync(text, "goo()"); - } + """, "goo()"); [Fact] - public async Task NotCompletionDespiteValidModifier() - { - var text = """ + public Task NotCompletionDespiteValidModifier() + => VerifyNoItemsExistAsync(""" partial class c { partial void goo(); void partial unsafe $$ } - """; - await VerifyNoItemsExistAsync(text); - } + """); [Fact] - public async Task NoExtendedCompletionDespiteValidModifier() - { - var text = """ + public Task NoExtendedCompletionDespiteValidModifier() + => VerifyNoItemsExistAsync(""" partial class c { public partial void goo(); void partial unsafe $$ } - """; - await VerifyNoItemsExistAsync(text); - } + """); [Fact] - public async Task YesIfPublic() - { - var text = """ + public Task YesIfPublic() + => VerifyItemExistsAsync(""" partial class c { public partial void goo(); void partial $$ } - """; - await VerifyItemExistsAsync(text, "goo()"); - } + """, "goo()"); [Fact] - public async Task YesIfInternal() - { - var text = """ + public Task YesIfInternal() + => VerifyItemExistsAsync(""" partial class c { internal partial void goo(); void partial $$ } - """; - await VerifyItemExistsAsync(text, "goo()"); - } + """, "goo()"); [Fact] - public async Task YesIfProtected() - { - var text = """ + public Task YesIfProtected() + => VerifyItemExistsAsync(""" partial class c { protected partial void goo(); void partial $$ } - """; - await VerifyItemExistsAsync(text, "goo()"); - } + """, "goo()"); [Fact] - public async Task YesIfProtectedInternal() - { - var text = """ + public Task YesIfProtectedInternal() + => VerifyItemExistsAsync(""" partial class c { protected internal partial void goo(); void partial $$ } - """; - await VerifyItemExistsAsync(text, "goo()"); - } + """, "goo()"); [Fact] - public async Task YesIfExtern() - { - var text = """ + public Task YesIfExtern() + => VerifyItemExistsAsync(""" partial class c { partial void goo(); extern void partial $$ } - """; - await VerifyItemExistsAsync(text, "goo()"); - } + """, "goo()"); [Fact] - public async Task YesIfVirtual() - { - var text = """ + public Task YesIfVirtual() + => VerifyItemExistsAsync(""" partial class c { virtual partial void goo(); void partial $$ } - """; - await VerifyItemExistsAsync(text, "goo()"); - } + """, "goo()"); [Fact] - public async Task YesIfNonVoidReturnType() - { - var text = """ + public Task YesIfNonVoidReturnType() + => VerifyItemExistsAsync(""" partial class c { partial int goo(); partial $$ } - """; - await VerifyItemExistsAsync(text, "goo()"); - } + """, "goo()"); [Fact] - public async Task NotInsideInterface() - { - var text = """ + public Task NotInsideInterface() + => VerifyNoItemsExistAsync(""" partial interface i { partial void goo(); partial $$ } - """; - await VerifyNoItemsExistAsync(text); - } + """); [WpfFact] - public async Task CommitInPartialClass() - { - var markupBeforeCommit = """ + public Task CommitInPartialClass() + => VerifyCustomCommitProviderAsync(""" partial class c { partial void goo(); partial $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ partial class c { partial void goo(); @@ -420,24 +336,18 @@ partial void goo() [|throw new System.NotImplementedException();|] } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitInExtendedPartialClass() - { - var markupBeforeCommit = """ + public Task CommitInExtendedPartialClass() + => VerifyCustomCommitProviderAsync(""" partial class c { public partial void goo(); partial $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ partial class c { public partial void goo(); @@ -447,24 +357,18 @@ public partial void goo() [|throw new System.NotImplementedException();|] } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitGenericPartialMethod() - { - var markupBeforeCommit = """ + public Task CommitGenericPartialMethod() + => VerifyCustomCommitProviderAsync(""" partial class c { partial void goo(T bar); partial $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo(T bar)", """ partial class c { partial void goo(T bar); @@ -474,24 +378,18 @@ partial void goo(T bar) [|throw new System.NotImplementedException();|] } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(T bar)", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitGenericExtendedPartialMethod() - { - var markupBeforeCommit = """ + public Task CommitGenericExtendedPartialMethod() + => VerifyCustomCommitProviderAsync(""" partial class c { public partial void goo(T bar); partial $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo(T bar)", """ partial class c { public partial void goo(T bar); @@ -501,24 +399,18 @@ public partial void goo(T bar) [|throw new System.NotImplementedException();|] } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(T bar)", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitMethodErasesPrivate() - { - var markupBeforeCommit = """ + public Task CommitMethodErasesPrivate() + => VerifyCustomCommitProviderAsync(""" partial class c { partial void goo(); private partial $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ partial class c { partial void goo(); @@ -528,24 +420,18 @@ partial void goo() [|throw new System.NotImplementedException();|] } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitMethodKeepsExtendedPrivate() - { - var markupBeforeCommit = """ + public Task CommitMethodKeepsExtendedPrivate() + => VerifyCustomCommitProviderAsync(""" partial class c { private partial void goo(); private partial $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ partial class c { private partial void goo(); @@ -555,15 +441,11 @@ private partial void goo() [|throw new System.NotImplementedException();|] } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitInPartialClassPart() - { - var markupBeforeCommit = """ + public Task CommitInPartialClassPart() + => VerifyCustomCommitProviderAsync(""" partial class c { partial void goo(); @@ -573,9 +455,7 @@ partial class c { partial $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ partial class c { partial void goo(); @@ -588,15 +468,11 @@ partial void goo() [|throw new System.NotImplementedException();|] } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitInExtendedPartialClassPart() - { - var markupBeforeCommit = """ + public Task CommitInExtendedPartialClassPart() + => VerifyCustomCommitProviderAsync(""" partial class c { public partial void goo(); @@ -606,9 +482,7 @@ partial class c { partial $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ partial class c { public partial void goo(); @@ -621,24 +495,18 @@ public partial void goo() [|throw new System.NotImplementedException();|] } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task CommitInPartialStruct() - { - var markupBeforeCommit = """ + public Task CommitInPartialStruct() + => VerifyCustomCommitProviderAsync(""" partial struct c { partial void goo(); partial $$ } - """; - - var expectedCodeAfterCommit = """ + """, "goo()", """ partial struct c { partial void goo(); @@ -648,15 +516,11 @@ partial void goo() [|throw new System.NotImplementedException();|] } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); - } + """); [Fact] - public async Task NotIfNoPartialKeyword() - { - var text = """ + public Task NotIfNoPartialKeyword() + => VerifyNoItemsExistAsync(""" partial class C { partial void Goo(); @@ -666,14 +530,11 @@ partial class C { void $$ } - """; - await VerifyNoItemsExistAsync(text); - } + """); [Fact] - public async Task NotIfNoExtendedPartialKeyword() - { - var text = """ + public Task NotIfNoExtendedPartialKeyword() + => VerifyNoItemsExistAsync(""" partial class C { public partial void Goo(); @@ -683,14 +544,11 @@ partial class C { void $$ } - """; - await VerifyNoItemsExistAsync(text); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578757")] - public async Task DoNotConsiderFollowingDeclarationPartial() - { - var text = """ + public Task DoNotConsiderFollowingDeclarationPartial() + => VerifyNoItemsExistAsync(""" class Program { partial $$ @@ -700,14 +558,11 @@ void Goo() } } - """; - await VerifyNoItemsExistAsync(text); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578757")] - public async Task DoNotConsiderFollowingDeclarationExtendedPartial() - { - var text = """ + public Task DoNotConsiderFollowingDeclarationExtendedPartial() + => VerifyNoItemsExistAsync(""" class Program { public partial $$ @@ -717,14 +572,11 @@ void Goo() } } - """; - await VerifyNoItemsExistAsync(text); - } + """); [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578078")] - public async Task CommitAsync() - { - var markupBeforeCommit = """ + public Task CommitAsync() + => VerifyCustomCommitProviderAsync(""" using System; partial class Bar @@ -733,9 +585,7 @@ partial class Bar async partial $$ } - """; - - var expectedCodeAfterCommit = """ + """, "Goo()", """ using System; partial class Bar @@ -747,15 +597,11 @@ async partial void Goo() [|throw new NotImplementedException();|] } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Goo()", expectedCodeAfterCommit); - } + """); [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578078")] - public async Task CommitAsyncExtended() - { - var markupBeforeCommit = """ + public Task CommitAsyncExtended() + => VerifyCustomCommitProviderAsync(""" using System; partial class Bar @@ -764,9 +610,7 @@ partial class Bar async partial $$ } - """; - - var expectedCodeAfterCommit = """ + """, "Goo()", """ using System; partial class Bar @@ -778,15 +622,11 @@ public async partial void Goo() [|throw new NotImplementedException();|] } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Goo()", expectedCodeAfterCommit); - } + """); [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578078")] - public async Task AmbiguityCommittingWithParen() - { - var markupBeforeCommit = """ + public Task AmbiguityCommittingWithParen() + => VerifyCustomCommitProviderAsync(""" using System; partial class Bar @@ -795,9 +635,7 @@ partial class Bar partial Goo$$ } - """; - - var expectedCodeAfterCommit = """ + """, "Goo()", """ using System; partial class Bar @@ -809,15 +647,11 @@ partial void Goo() [|throw new NotImplementedException();|] } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Goo()", expectedCodeAfterCommit, commitChar: '('); - } + """, commitChar: '('); [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/965677")] - public async Task NoDefaultParameterValues() - { - var text = """ + public Task NoDefaultParameterValues() + => VerifyCustomCommitProviderAsync(""" namespace PartialClass { partial class PClass @@ -827,9 +661,7 @@ partial class PClass partial $$ } } - """; - - var expected = """ + """, "PMethod(int i)", """ namespace PartialClass { partial class PClass @@ -842,14 +674,11 @@ partial void PMethod(int i) } } } - """; - await VerifyCustomCommitProviderAsync(text, "PMethod(int i)", expected); - } + """); [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/965677")] - public async Task NoDefaultParameterValuesExtended() - { - var text = """ + public Task NoDefaultParameterValuesExtended() + => VerifyCustomCommitProviderAsync(""" namespace PartialClass { partial class PClass @@ -859,9 +688,7 @@ partial class PClass partial $$ } } - """; - - var expected = """ + """, "PMethod(int i)", """ namespace PartialClass { partial class PClass @@ -874,9 +701,7 @@ public partial void PMethod(int i) } } } - """; - await VerifyCustomCommitProviderAsync(text, "PMethod(int i)", expected); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/26388")] public async Task ExpressionBodyMethod() @@ -888,26 +713,21 @@ public async Task ExpressionBodyMethod() { { CSharpCodeStyleOptions.PreferExpressionBodiedMethods, new CodeStyleOption2(ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent) } }); - - var text = """ + await VerifyCustomCommitProviderAsync(""" using System; partial class Bar { partial void Foo(); partial $$ } - """; - - var expected = """ + """, "Foo()", """ using System; partial class Bar { partial void Foo(); partial void Foo() => [|throw new NotImplementedException()|]; } - """; - - await VerifyCustomCommitProviderAsync(text, "Foo()", expected); + """); } [WpfFact] @@ -920,28 +740,21 @@ public async Task ExpressionBodyMethodExtended() { { CSharpCodeStyleOptions.PreferExpressionBodiedMethods, new CodeStyleOption2(ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent) } }); - - var text = """ + await VerifyCustomCommitProviderAsync(""" using System; partial class Bar { public partial void Foo(); partial $$ } - """ -; - - var expected = """ + """, "Foo()", """ using System; partial class Bar { public partial void Foo(); public partial void Foo() => [|throw new NotImplementedException()|]; } - """ -; - - await VerifyCustomCommitProviderAsync(text, "Foo()", expected); + """); } private Task VerifyItemExistsAsync(string markup, string expectedItem) diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/PartialTypeCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/PartialTypeCompletionProviderTests.cs index 6fbdd361c57d9..110efef2e7a80 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/PartialTypeCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/PartialTypeCompletionProviderTests.cs @@ -19,169 +19,118 @@ internal override Type GetCompletionProviderType() => typeof(PartialTypeCompletionProvider); [Fact] - public async Task TestRecommendTypesWithoutPartial() - { - var text = """ + public Task TestRecommendTypesWithoutPartial() + => VerifyItemIsAbsentAsync(""" class C { } partial class $$ - """; - - await VerifyItemIsAbsentAsync(text, "C"); - } + """, "C"); [Fact] - public async Task TestPartialClass1() - { - var text = """ + public Task TestPartialClass1() + => VerifyItemExistsAsync(""" partial class C { } partial class $$ - """; - - await VerifyItemExistsAsync(text, "C"); - } + """, "C"); [Fact] - public async Task TestPartialGenericClass1() - { - var text = """ + public Task TestPartialGenericClass1() + => VerifyItemExistsAsync(""" class Bar { } partial class C { } partial class $$ - """; - - await VerifyItemExistsAsync(text, "C"); - } + """, "C"); [Fact] - public async Task TestPartialGenericClassCommitOnParen() - { - var text = """ + public Task TestPartialGenericClassCommitOnParen() + => VerifyProviderCommitAsync(""" class Bar { } partial class C { } partial class $$ - """; - - var expected = """ + """, "C", """ class Bar { } partial class C { } partial class C< - """; - - await VerifyProviderCommitAsync(text, "C", expected, '<'); - } + """, '<'); [Fact] - public async Task TestPartialGenericClassCommitOnTab() - { - var text = """ + public Task TestPartialGenericClassCommitOnTab() + => VerifyProviderCommitAsync(""" class Bar { } partial class C { } partial class $$ - """; - - var expected = """ + """, "C", """ class Bar { } partial class C { } partial class C - """; - - await VerifyProviderCommitAsync(text, "C", expected, null); - } + """, null); [Fact] - public async Task TestPartialGenericClassCommitOnSpace() - { - var text = """ + public Task TestPartialGenericClassCommitOnSpace() + => VerifyProviderCommitAsync(""" partial class C { } partial class $$ - """; - - var expected = """ + """, "C", """ partial class C { } partial class C - """; - - await VerifyProviderCommitAsync(text, "C", expected, ' '); - } + """, ' '); [Fact] - public async Task TestPartialClassWithModifiers() - { - var text = """ + public Task TestPartialClassWithModifiers() + => VerifyItemExistsAsync(""" partial class C { } internal partial class $$ - """; - - await VerifyItemExistsAsync(text, "C"); - } + """, "C"); [Fact] - public async Task TestPartialStruct() - { - var text = """ + public Task TestPartialStruct() + => VerifyItemExistsAsync(""" partial struct S { } partial struct $$ - """; - - await VerifyItemExistsAsync(text, "S"); - } + """, "S"); [Fact] - public async Task TestPartialInterface() - { - var text = """ + public Task TestPartialInterface() + => VerifyItemExistsAsync(""" partial interface I { } partial interface $$ - """; - - await VerifyItemExistsAsync(text, "I"); - } + """, "I"); [Fact] - public async Task TestTypeKindMatches1() - { - var text = """ + public Task TestTypeKindMatches1() + => VerifyNoItemsExistAsync(""" partial struct S { } partial class $$ - """; - - await VerifyNoItemsExistAsync(text); - } + """); [Fact] - public async Task TestTypeKindMatches2() - { - var text = """ + public Task TestTypeKindMatches2() + => VerifyNoItemsExistAsync(""" partial class C { } partial struct $$ - """; - - await VerifyNoItemsExistAsync(text); - } + """); [Fact] - public async Task TestPartialClassesInSameNamespace() - { - var text = """ + public Task TestPartialClassesInSameNamespace() + => VerifyItemExistsAsync(""" namespace N { partial class Goo { } @@ -191,143 +140,96 @@ namespace N { partial class $$ } - """; - - await VerifyItemExistsAsync(text, "Goo"); - } + """, "Goo"); [Fact] - public async Task TestNotPartialClassesAcrossDifferentNamespaces() - { - var text = """ + public Task TestNotPartialClassesAcrossDifferentNamespaces() + => VerifyNoItemsExistAsync(""" namespace N { partial class Goo { } } partial class $$ - """; - - await VerifyNoItemsExistAsync(text); - } + """); [Fact] - public async Task TestNotPartialClassesInOuterNamespaces() - { - var text = """ + public Task TestNotPartialClassesInOuterNamespaces() + => VerifyNoItemsExistAsync(""" partial class C { } namespace N { partial class $$ } - """; - - await VerifyNoItemsExistAsync(text); - } + """); [Fact] - public async Task TestNotPartialClassesInOuterClass() - { - var text = """ + public Task TestNotPartialClassesInOuterClass() + => VerifyNoItemsExistAsync(""" partial class C { partial class $$ } - """; - - await VerifyNoItemsExistAsync(text); - } + """); [Fact] - public async Task TestClassWithConstraint() - { - var text = """ + public Task TestClassWithConstraint() + => VerifyProviderCommitAsync(""" partial class C1 where T : System.Exception { } partial class $$ - """; - - var expected = """ + """, "C1", """ partial class C1 where T : System.Exception { } partial class C1 - """; - - await VerifyProviderCommitAsync(text, "C1", expected, null); - } + """, null); [Fact] - public async Task TestDoNotSuggestCurrentMember() - { - var text = @"partial class F$$"; - - await VerifyNoItemsExistAsync(text); - } + public Task TestDoNotSuggestCurrentMember() + => VerifyNoItemsExistAsync(@"partial class F$$"); [Fact] - public async Task TestNotInTrivia() - { - var text = """ + public Task TestNotInTrivia() + => VerifyNoItemsExistAsync(""" partial class C1 { } partial class //$$ - """; - - await VerifyNoItemsExistAsync(text); - } + """); [Fact] - public async Task TestPartialClassWithReservedName() - { - var text = """ + public Task TestPartialClassWithReservedName() + => VerifyProviderCommitAsync(""" partial class @class { } partial class $$ - """; - - var expected = """ + """, "@class", """ partial class @class { } partial class @class - """; - - await VerifyProviderCommitAsync(text, "@class", expected, null); - } + """, null); [Fact] - public async Task TestPartialGenericClassWithReservedName() - { - var text = """ + public Task TestPartialGenericClassWithReservedName() + => VerifyProviderCommitAsync(""" partial class @class { } partial class $$ - """; - - var expected = """ + """, "@class", """ partial class @class { } partial class @class - """; - - await VerifyProviderCommitAsync(text, "@class", expected, null); - } + """, null); [Fact] - public async Task TestPartialGenericInterfaceWithVariance() - { - var text = """ + public Task TestPartialGenericInterfaceWithVariance() + => VerifyProviderCommitAsync(""" partial interface I { } partial interface $$ - """; - - var expected = """ + """, "I", """ partial interface I { } partial interface I - """; - - await VerifyProviderCommitAsync(text, "I", expected, null); - } + """, null); } diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/PropertySubPatternCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/PropertySubPatternCompletionProviderTests.cs index e5c66c60bef11..bb7d432f53ac1 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/PropertySubPatternCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/PropertySubPatternCompletionProviderTests.cs @@ -103,10 +103,8 @@ void M() } [Fact] - public async Task PropertiesInRecursivePattern_WriteOnlyProperties() - { - var markup = - """ + public Task PropertiesInRecursivePattern_WriteOnlyProperties() + => VerifyNoItemsExistAsync(""" class Program { public int P1 { set => throw null; } @@ -116,9 +114,7 @@ void M() _ = this is Program { $$ } } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] public async Task PropertiesInRecursivePattern_WithDerivedType() @@ -165,10 +161,8 @@ class Other } [Fact] - public async Task PropertiesInRecursivePattern_WithDerivedType_WithInaccessibleMembers() - { - var markup = - """ + public Task PropertiesInRecursivePattern_WithDerivedType_WithInaccessibleMembers() + => VerifyNoItemsExistAsync(""" class Program { void M() @@ -181,15 +175,11 @@ class Derived : Program private int P1 { get; set; } private int P2 { get; set; } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task PropertiesInRecursivePattern_WithDerivedType_WithPrivateMember() - { - var markup = - """ + public Task PropertiesInRecursivePattern_WithDerivedType_WithPrivateMember() + => VerifyItemExistsAsync(""" class Program { private int P1 { get; set; } @@ -202,9 +192,7 @@ class Derived : Program { private int P2 { get; set; } } - """; - await VerifyItemExistsAsync(markup, "P1", displayTextSuffix: ""); - } + """, "P1", displayTextSuffix: ""); [Fact] public async Task PropertiesInRecursivePattern_UseStaticTypeFromIs() @@ -377,10 +365,8 @@ void M() } [Fact] - public async Task PropertiesInRecursivePattern_Nested_WithMissingProperty() - { - var markup = - """ + public Task PropertiesInRecursivePattern_Nested_WithMissingProperty() + => VerifyNoItemsExistAsync(""" public class Nested { public int P3 { get; set; } @@ -396,15 +382,11 @@ void M() _ = this is Program { : { $$ } } } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task PropertiesInRecursivePattern_NoType() - { - var markup = - """ + public Task PropertiesInRecursivePattern_NoType() + => VerifyNoItemsExistAsync(""" class Program { public int P1 { get; set; } @@ -415,15 +397,11 @@ void M() _ = missing is { $$ } } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task PropertiesInRecursivePattern_MissingAfterColon() - { - var markup = - """ + public Task PropertiesInRecursivePattern_MissingAfterColon() + => VerifyNoItemsExistAsync(""" class Program { public int P1 { get; set; } @@ -434,9 +412,7 @@ void M() _ = this is { P1: $$ } } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] public async Task PropertiesInRecursivePattern_SecondProperty() @@ -460,10 +436,8 @@ void M() } [Fact] - public async Task PropertiesInRecursivePattern_PositionalInFirstProperty() - { - var markup = - """ + public Task PropertiesInRecursivePattern_PositionalInFirstProperty() + => VerifyNoItemsExistAsync(""" class Program { public D P1 { get; set; } @@ -477,15 +451,11 @@ class D { public int P2 { get; set; } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task PropertiesInRecursivePattern_PositionalInFirstProperty_AfterComma() - { - var markup = - """ + public Task PropertiesInRecursivePattern_PositionalInFirstProperty_AfterComma() + => VerifyNoItemsExistAsync(""" class Program { public D P1 { get; set; } @@ -499,15 +469,11 @@ class D { public int P2 { get; set; } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task PropertiesInRecursivePattern_PositionalInFirstProperty_AfterCommaAndBeforeParen() - { - var markup = - """ + public Task PropertiesInRecursivePattern_PositionalInFirstProperty_AfterCommaAndBeforeParen() + => VerifyNoItemsExistAsync(""" class Program { public D P1 { get; set; } @@ -521,15 +487,11 @@ class D { public int P2 { get; set; } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task PropertiesInRecursivePattern_InPositional_Incomplete() - { - var markup = - """ + public Task PropertiesInRecursivePattern_InPositional_Incomplete() + => VerifyItemExistsAsync(""" public class Program { public int P1 { get; set; } @@ -541,15 +503,11 @@ void M() public void Deconstruct(out Program x, out Program y) => throw null; } - """; - await VerifyItemExistsAsync(markup, "P1", displayTextSuffix: ""); - } + """, "P1", displayTextSuffix: ""); [Fact] - public async Task PropertiesInRecursivePattern_InPositional_Incomplete_WithoutClosingBrace() - { - var markup = - """ + public Task PropertiesInRecursivePattern_InPositional_Incomplete_WithoutClosingBrace() + => VerifyItemExistsAsync(""" public class Program { public int P1 { get; set; } @@ -561,15 +519,11 @@ void M() public void Deconstruct(out Program x, out Program y) => throw null; } - """; - await VerifyItemExistsAsync(markup, "P1", displayTextSuffix: ""); - } + """, "P1", displayTextSuffix: ""); [Fact] - public async Task PropertiesInRecursivePattern_InPositional_Incomplete_WithTwoTypes() - { - var markup = - """ + public Task PropertiesInRecursivePattern_InPositional_Incomplete_WithTwoTypes() + => VerifyNoItemsExistAsync(""" public class Program { void M() @@ -583,15 +537,11 @@ public class D { public int P2 { get; set; } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task PropertiesInRecursivePattern_InPositional_Complete_BeforeComma() - { - var markup = - """ + public Task PropertiesInRecursivePattern_InPositional_Complete_BeforeComma() + => VerifyItemExistsAsync(""" public class Program { public int P1 { get; set; } @@ -603,15 +553,11 @@ void M() public void Deconstruct(out Program x, out Program y) => throw null; } - """; - await VerifyItemExistsAsync(markup, "P1", displayTextSuffix: ""); - } + """, "P1", displayTextSuffix: ""); [Fact] - public async Task PropertiesInRecursivePattern_InPositional_Complete_AfterComma() - { - var markup = - """ + public Task PropertiesInRecursivePattern_InPositional_Complete_AfterComma() + => VerifyItemExistsAsync(""" public class Program { public int P1 { get; set; } @@ -623,15 +569,11 @@ void M() public void Deconstruct(out Program x, out Program y) => throw null; } - """; - await VerifyItemExistsAsync(markup, "P1", displayTextSuffix: ""); - } + """, "P1", displayTextSuffix: ""); [Fact] - public async Task PropertiesInRecursivePattern_NoPropertyLeft() - { - var markup = - """ + public Task PropertiesInRecursivePattern_NoPropertyLeft() + => VerifyNoItemsExistAsync(""" class Program { public int P1 { get; set; } @@ -642,9 +584,7 @@ void M() _ = this is Program { P2: 1, P1: 2, $$ } } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] public async Task PropertiesInRecursivePattern_NotForEditorUnbrowsable() @@ -670,10 +610,8 @@ void M() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33250")] - public async Task StaticProperties_NotSuggested() - { - var markup = - """ + public Task StaticProperties_NotSuggested() + => VerifyItemIsAbsentAsync(""" class Program { void M() @@ -681,15 +619,11 @@ void M() _ = "" is { $$ } } } - """; - await VerifyItemIsAbsentAsync(markup, "Empty"); - } + """, "Empty"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33250")] - public async Task StaticFields_NotSuggested() - { - var markup = - """ + public Task StaticFields_NotSuggested() + => VerifyItemIsAbsentAsync(""" class Program { static int x = 42; @@ -699,15 +633,11 @@ void M() _ = this is { $$ } } } - """; - await VerifyItemIsAbsentAsync(markup, "x"); - } + """, "x"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33250")] - public async Task ConstFields_NotSuggested() - { - var markup = - """ + public Task ConstFields_NotSuggested() + => VerifyItemIsAbsentAsync(""" class Program { void M() @@ -715,7 +645,5 @@ void M() _ = 5 is { $$ } } } - """; - await VerifyItemIsAbsentAsync(markup, "MaxValue"); - } + """, "MaxValue"); } diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ReferenceDirectiveCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ReferenceDirectiveCompletionProviderTests.cs index a67e716d96093..20d50e59976e7 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ReferenceDirectiveCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ReferenceDirectiveCompletionProviderTests.cs @@ -74,12 +74,10 @@ public async Task GacReference() => await VerifyItemExistsAsync("#r \"$$", "System.Windows.Forms", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); [ConditionalFact(typeof(WindowsOnly))] - public async Task GacReferenceFullyQualified() - { - await VerifyItemExistsAsync( + public Task GacReferenceFullyQualified() + => VerifyItemExistsAsync( "#r \"System.Windows.Forms,$$", "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); - } [ConditionalFact(typeof(WindowsOnly))] public async Task FileSystemReference() diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SemanticSnippetCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SemanticSnippetCompletionProviderTests.cs index 83eb82f956ba1..6ea59d7deee4b 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SemanticSnippetCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SemanticSnippetCompletionProviderTests.cs @@ -23,9 +23,8 @@ internal override Type GetCompletionProviderType() => typeof(CSharpSnippetCompletionProvider); [WpfFact] - public async Task InsertConsoleSnippetWithInvocationBeforeAndAfterCursorTest() - { - var markupBeforeCommit = """ + public Task InsertConsoleSnippetWithInvocationBeforeAndAfterCursorTest() + => VerifyCustomCommitProviderAsync(""" class Program { public void Method() @@ -33,9 +32,7 @@ public void Method() Wr$$Blah } } - """; - - var expectedCodeAfterCommit = """ + """, "cw", """ using System; class Program @@ -45,16 +42,11 @@ public void Method() Console.WriteLine($$); } } - """; - - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "cw", expectedCodeAfterCommit); - } + """); [WpfFact] - public async Task InsertConsoleSnippetWithInvocationUnderscoreBeforeAndAfterCursorTest() - { - var markupBeforeCommit = - """ + public Task InsertConsoleSnippetWithInvocationUnderscoreBeforeAndAfterCursorTest() + => VerifyCustomCommitProviderAsync(""" class Program { public void Method() @@ -62,10 +54,7 @@ public void Method() _Wr$$Blah_ } } - """; - - var expectedCodeAfterCommit = - """ + """, "cw", """ using System; class Program @@ -75,7 +64,5 @@ public void Method() Console.WriteLine($$); } } - """; - await VerifyCustomCommitProviderAsync(markupBeforeCommit, "cw", expectedCodeAfterCommit); - } + """); } diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SnippetCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SnippetCompletionProviderTests.cs index 581ee610808a1..9f407e913fa0a 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SnippetCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SnippetCompletionProviderTests.cs @@ -85,9 +85,8 @@ public async Task SnippetsInLineSpanDirective() => await VerifyItemIsAbsentAsync(@"#line (1, 2) - (3, 4) $$", MockSnippetInfoService.PreProcessorSnippetShortcut, sourceCodeKind: SourceCodeKind.Regular); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968256")] - public async Task ShowSnippetsFromOtherContext() - { - var markup = """ + public Task ShowSnippetsFromOtherContext() + => VerifyItemInLinkedFilesAsync(""" - """; - await VerifyItemInLinkedFilesAsync(markup, MockSnippetInfoService.SnippetShortcut, null); - } + """, MockSnippetInfoService.SnippetShortcut, null); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1140893")] public async Task CommitWithEnterObeysOption() diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SpeculativeTCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SpeculativeTCompletionProviderTests.cs index a37d85f9baf3e..e7632aec4e47e 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SpeculativeTCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SpeculativeTCompletionProviderTests.cs @@ -52,374 +52,273 @@ class C } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task InClass() - { - var markup = """ + public Task InClass() + => VerifyItemExistsAsync(""" class C { $$ } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task InInterface() - { - var markup = """ + public Task InInterface() + => VerifyItemExistsAsync(""" interface I { $$ } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task InStruct() - { - var markup = """ + public Task InStruct() + => VerifyItemExistsAsync(""" struct S { $$ } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task NotInNamespace() - { - var markup = """ + public Task NotInNamespace() + => VerifyItemIsAbsentAsync(""" namespace N { $$ } - """; - - await VerifyItemIsAbsentAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task NotInEnum() - { - var markup = """ + public Task NotInEnum() + => VerifyItemIsAbsentAsync(""" enum E { $$ } - """; - - await VerifyItemIsAbsentAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task AfterDelegate() - { - var markup = """ + public Task AfterDelegate() + => VerifyItemExistsAsync(""" class C { delegate $$ } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task NotAfterVoid() - { - var markup = """ + public Task NotAfterVoid() + => VerifyItemIsAbsentAsync(""" class C { void $$ } - """; - - await VerifyItemIsAbsentAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task NotAfterInt() - { - var markup = """ + public Task NotAfterInt() + => VerifyItemIsAbsentAsync(""" class C { int $$ } - """; - - await VerifyItemIsAbsentAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task InGeneric() - { - var markup = """ + public Task InGeneric() + => VerifyItemExistsAsync(""" using System; class C { Func<$$ } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("https://github.com/dotnet/roslyn/issues/37224")] - public async Task InRef0() - { - var markup = """ + public Task InRef0() + => VerifyItemExistsAsync(""" using System; class C { ref $$ } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("https://github.com/dotnet/roslyn/issues/37224")] - public async Task InRef1() - { - var markup = """ + public Task InRef1() + => VerifyItemExistsAsync(""" using System; class C { ref T$$ } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("https://github.com/dotnet/roslyn/issues/37224")] - public async Task InRefGeneric0() - { - var markup = """ + public Task InRefGeneric0() + => VerifyItemExistsAsync(""" using System; class C { ref Func<$$ } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("https://github.com/dotnet/roslyn/issues/37224")] - public async Task InRefGeneric1() - { - var markup = """ + public Task InRefGeneric1() + => VerifyItemExistsAsync(""" using System; class C { ref Func<$$> } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("https://github.com/dotnet/roslyn/issues/37224")] - public async Task InRefGeneric2() - { - var markup = """ + public Task InRefGeneric2() + => VerifyItemExistsAsync(""" using System; class C { ref Func } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("https://github.com/dotnet/roslyn/issues/37224")] - public async Task InRefGeneric3() - { - var markup = """ + public Task InRefGeneric3() + => VerifyItemExistsAsync(""" using System; class C { ref Func VerifyItemExistsAsync(""" using System; class C { ref readonly Func<$$ } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("https://github.com/dotnet/roslyn/issues/37268")] - public async Task InQualifiedGeneric0() - { - var markup = """ + public Task InQualifiedGeneric0() + => VerifyItemExistsAsync(""" using System; class C { System.Func<$$ } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("https://github.com/dotnet/roslyn/issues/37268")] - public async Task InQualifiedGeneric1() - { - var markup = """ + public Task InQualifiedGeneric1() + => VerifyItemExistsAsync(""" using System; class C { System.Collections.Generic.List<$$ } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("https://github.com/dotnet/roslyn/issues/37224")] [WorkItem("https://github.com/dotnet/roslyn/issues/37268")] - public async Task InRefAndQualifiedGeneric0() - { - var markup = """ + public Task InRefAndQualifiedGeneric0() + => VerifyItemExistsAsync(""" using System; class C { ref System.Func<$$ } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("https://github.com/dotnet/roslyn/issues/37224")] [WorkItem("https://github.com/dotnet/roslyn/issues/37268")] - public async Task InRefAndQualifiedGeneric1() - { - var markup = """ + public Task InRefAndQualifiedGeneric1() + => VerifyItemExistsAsync(""" using System; class C { internal ref System.Func VerifyItemExistsAsync(""" using System; class C { partial ref System.Func VerifyItemExistsAsync(""" using System; class C { private ref Func VerifyItemExistsAsync(""" using System; class C { public ref Func VerifyItemExistsAsync(""" using System; class C { private protected ref Func VerifyItemExistsAsync(""" using System; class C { protected ($$ } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("https://github.com/dotnet/roslyn/issues/37361")] - public async Task TupleInMethod0() - { - var markup = """ + public Task TupleInMethod0() + => VerifyItemExistsAsync(""" using System; class C { @@ -428,16 +327,12 @@ void M() ($$ } } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("https://github.com/dotnet/roslyn/issues/37361")] - public async Task TupleInMethod1() - { - var markup = """ + public Task TupleInMethod1() + => VerifyItemExistsAsync(""" using System; class C { @@ -447,16 +342,12 @@ void M() ($$ } } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("https://github.com/dotnet/roslyn/issues/37361")] - public async Task TupleInMethod2() - { - var markup = """ + public Task TupleInMethod2() + => VerifyItemExistsAsync(""" using System; class C { @@ -465,15 +356,12 @@ void M() ($$) } } - """; - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("https://github.com/dotnet/roslyn/issues/37361")] - public async Task TupleInMethod3() - { - var markup = """ + public Task TupleInMethod3() + => VerifyItemExistsAsync(""" using System; class C { @@ -486,413 +374,293 @@ void M() a = 1; } } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("https://github.com/dotnet/roslyn/issues/37361")] - public async Task InTupleNot0() - { - var markup = """ + public Task InTupleNot0() + => VerifyItemIsAbsentAsync(""" using System; class C { protected sealed (int $$ } - """; - - await VerifyItemIsAbsentAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("https://github.com/dotnet/roslyn/issues/37361")] - public async Task InTuple1() - { - var markup = """ + public Task InTuple1() + => VerifyItemExistsAsync(""" using System; class C { sealed (int, $$ } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("https://github.com/dotnet/roslyn/issues/37361")] - public async Task InTupleNot1() - { - var markup = """ + public Task InTupleNot1() + => VerifyItemIsAbsentAsync(""" using System; class C { virtual (int x, C $$ } - """; - - await VerifyItemIsAbsentAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("https://github.com/dotnet/roslyn/issues/37361")] - public async Task InTupleGeneric0() - { - var markup = """ + public Task InTupleGeneric0() + => VerifyItemExistsAsync(""" using System; class C { (Func<$$ } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("https://github.com/dotnet/roslyn/issues/37361")] - public async Task InTupleGeneric1() - { - var markup = """ + public Task InTupleGeneric1() + => VerifyItemExistsAsync(""" using System; class C { (int, Func<$$ } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("https://github.com/dotnet/roslyn/issues/37361")] - public async Task InTupleGeneric2() - { - var markup = """ + public Task InTupleGeneric2() + => VerifyItemExistsAsync(""" using System; class C { (int, Func VerifyItemExistsAsync(""" using System; class C { Func<($$ } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("https://github.com/dotnet/roslyn/issues/37361")] - public async Task InGenericTuple1() - { - var markup = """ + public Task InGenericTuple1() + => VerifyItemExistsAsync(""" using System; class C { Func VerifyItemIsAbsentAsync(""" using System; class C { Func VerifyItemExistsAsync(""" using System; class C { Func<(int, $$ } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("https://github.com/dotnet/roslyn/issues/37361")] - public async Task InGenericTuple2Not() - { - var markup = """ + public Task InGenericTuple2Not() + => VerifyItemIsAbsentAsync(""" using System; class C { Func<(C c, int $$ } - """; - - await VerifyItemIsAbsentAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("https://github.com/dotnet/roslyn/issues/37361")] - public async Task InGenericTuple3() - { - var markup = """ + public Task InGenericTuple3() + => VerifyItemExistsAsync(""" using System; class C { Func VerifyItemIsAbsentAsync(""" using System; class C { Func VerifyItemExistsAsync(""" using System; class C { ref (Func VerifyItemExistsAsync(""" using System; class C { ref (C c, Func VerifyItemExistsAsync(""" using System; class C { ref (C c, Func VerifyItemExistsAsync(""" using System; class C { ref (C c, System.Func VerifyItemExistsAsync(""" using System; class C { ref (System.Func<(int,C), (Func VerifyItemExistsAsync(""" using System; class C { ref readonly (System.Func<(int, (C, (Func VerifyItemExistsAsync(""" using System; class C { ref readonly (System.Collections.Generic.List<(int, (C, (Func VerifyItemExistsAsync(""" using System; class C { Func VerifyItemExistsAsync(""" using System; class C { Func VerifyItemExistsAsync(@"$$", "T", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task NotAfterVoidInScript() - { - var markup = @"void $$"; - - await VerifyItemIsAbsentAsync(markup, "T", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); - } + public Task NotAfterVoidInScript() + => VerifyItemIsAbsentAsync(@"void $$", "T", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task NotAfterIntInScript() - { - var markup = @"int $$"; - - await VerifyItemIsAbsentAsync(markup, "T", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); - } + public Task NotAfterIntInScript() + => VerifyItemIsAbsentAsync(@"int $$", "T", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task InGenericInScript() - { - var markup = """ + public Task InGenericInScript() + => VerifyItemExistsAsync(""" using System; Func<$$ - """; - - await VerifyItemExistsAsync(markup, "T", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); - } + """, "T", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task InNestedGenericInScript1() - { - var markup = """ + public Task InNestedGenericInScript1() + => VerifyItemExistsAsync(""" using System; Func VerifyItemExistsAsync(""" using System; Func VerifyItemIsAbsentAsync(""" class C { // $$ } - """; - - await VerifyItemIsAbsentAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task NotInXmlDocComment() - { - var markup = """ + public Task NotInXmlDocComment() + => VerifyItemIsAbsentAsync(""" class C { /// @@ -900,44 +668,32 @@ class C /// void Goo() { } } - """; - - await VerifyItemIsAbsentAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task AfterAsyncTask() - { - var markup = """ + public Task AfterAsyncTask() + => VerifyItemExistsAsync(""" using System.Threading.Tasks; class Program { async Task<$$ } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task NotOkAfterAsync() - { - var markup = """ + public Task NotOkAfterAsync() + => VerifyItemIsAbsentAsync(""" using System.Threading.Tasks; class Program { async $$ } - """; - - await VerifyItemIsAbsentAsync(markup, "T"); - } + """, "T"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968256")] - public async Task UnionOfItemsFromBothContexts() - { - var markup = """ + public Task UnionOfItemsFromBothContexts() + => VerifyItemInLinkedFilesAsync(""" - """; - await VerifyItemInLinkedFilesAsync(markup, "T", null); - } + """, "T", null); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020654")] - public async Task AfterAsyncTaskWithBraceCompletion() - { - var markup = """ + public Task AfterAsyncTaskWithBraceCompletion() + => VerifyItemExistsAsync(""" using System.Threading.Tasks; class Program { async Task<$$> } - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/13480")] [CompilerTrait(CompilerFeature.LocalFunctions)] - public async Task LocalFunctionReturnType() - { - var markup = """ + public Task LocalFunctionReturnType() + => VerifyItemExistsAsync(""" class C { public void M() @@ -991,15 +740,12 @@ public void M() $$ } } - """; - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact(Skip = "https://github.com/dotnet/roslyn/issues/14525")] [CompilerTrait(CompilerFeature.LocalFunctions)] - public async Task LocalFunctionAfterAyncTask() - { - var markup = """ + public Task LocalFunctionAfterAyncTask() + => VerifyItemExistsAsync(""" class C { public void M() @@ -1007,15 +753,12 @@ public void M() async Task<$$> } } - """; - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact(Skip = "https://github.com/dotnet/roslyn/issues/14525")] [CompilerTrait(CompilerFeature.LocalFunctions)] - public async Task LocalFunctionAfterAsync() - { - var markup = """ + public Task LocalFunctionAfterAsync() + => VerifyItemExistsAsync(""" class C { public void M() @@ -1023,7 +766,5 @@ public void M() async $$ } } - """; - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); } diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SuggestionModeCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SuggestionModeCompletionProviderTests.cs index eafd50df635d8..f56be4f949711 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SuggestionModeCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SuggestionModeCompletionProviderTests.cs @@ -22,23 +22,16 @@ internal override Type GetCompletionProviderType() => typeof(CSharpSuggestionModeCompletionProvider); [Fact] - public async Task AfterFirstExplicitArgument() - { - // The right-hand-side parses like a possible deconstruction or tuple type - await VerifyBuilderAsync(AddInsideMethod(@"Func f = (int x, i $$")); - } + public Task AfterFirstExplicitArgument() + => VerifyBuilderAsync(AddInsideMethod(@"Func f = (int x, i $$")); [Fact] - public async Task AfterFirstImplicitArgument() - { - // The right-hand-side parses like a possible deconstruction or tuple type - await VerifyBuilderAsync(AddInsideMethod(@"Func f = (x, i $$")); - } + public Task AfterFirstImplicitArgument() + => VerifyBuilderAsync(AddInsideMethod(@"Func f = (x, i $$")); [Fact] - public async Task AfterFirstImplicitArgumentInMethodCall() - { - var markup = """ + public Task AfterFirstImplicitArgumentInMethodCall() + => VerifyBuilderAsync(""" class c { private void bar(Func f) { } @@ -48,15 +41,11 @@ private void goo() bar((x, i $$ } } - """; - // The right-hand-side parses like a possible deconstruction or tuple type - await VerifyBuilderAsync(markup); - } + """); [Fact] - public async Task AfterFirstExplicitArgumentInMethodCall() - { - var markup = """ + public Task AfterFirstExplicitArgumentInMethodCall() + => VerifyBuilderAsync(""" class c { private void bar(Func f) { } @@ -66,15 +55,11 @@ private void goo() bar((int x, i $$ } } - """; - // Could be a deconstruction expression - await VerifyBuilderAsync(markup); - } + """); [Fact] - public async Task DelegateTypeExpected1() - { - var markup = """ + public Task DelegateTypeExpected1() + => VerifyBuilderAsync(""" using System; class c @@ -86,18 +71,15 @@ private void goo() bar($$ } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact] public async Task DelegateTypeExpected2() => await VerifyBuilderAsync(AddUsingDirectives("using System;", AddInsideMethod(@"Func f = $$"))); [Fact] - public async Task ObjectInitializerDelegateType() - { - var markup = """ + public Task ObjectInitializerDelegateType() + => VerifyBuilderAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -114,14 +96,11 @@ void goo() var b = new Program() { myfunc = $$ } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/817145")] - public async Task ExplicitArrayInitializer() - { - var markup = """ + public Task ExplicitArrayInitializer() + => VerifyBuilderAsync(""" using System; class a @@ -131,14 +110,11 @@ void goo() Func[] myfunc = new Func[] { $$; } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact] - public async Task ImplicitArrayInitializerUnknownType() - { - var markup = """ + public Task ImplicitArrayInitializerUnknownType() + => VerifyNotBuilderAsync(""" using System; class a @@ -148,14 +124,11 @@ void goo() var a = new [] { $$; } } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Fact] - public async Task ImplicitArrayInitializerKnownDelegateType() - { - var markup = """ + public Task ImplicitArrayInitializerKnownDelegateType() + => VerifyBuilderAsync(""" using System; class a @@ -165,14 +138,11 @@ void goo() var a = new [] { x => 2 * x, $$ } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact] - public async Task TernaryOperatorUnknownType() - { - var markup = """ + public Task TernaryOperatorUnknownType() + => VerifyNotBuilderAsync(""" using System; class a @@ -182,14 +152,11 @@ void goo() var a = true ? $$ } } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Fact] - public async Task TernaryOperatorKnownDelegateType1() - { - var markup = """ + public Task TernaryOperatorKnownDelegateType1() + => VerifyBuilderAsync(""" using System; class a @@ -199,14 +166,11 @@ void goo() var a = true ? x => x * 2 : $$ } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact] - public async Task TernaryOperatorKnownDelegateType2() - { - var markup = """ + public Task TernaryOperatorKnownDelegateType2() + => VerifyBuilderAsync(""" using System; class a @@ -216,14 +180,11 @@ void goo() Func a = true ? $$ } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact] - public async Task OverloadTakesADelegate1() - { - var markup = """ + public Task OverloadTakesADelegate1() + => VerifyBuilderAsync(""" using System; class a @@ -236,14 +197,11 @@ void bar() this.goo($$ } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact] - public async Task OverloadTakesDelegate2() - { - var markup = """ + public Task OverloadTakesDelegate2() + => VerifyBuilderAsync(""" using System; class a @@ -256,14 +214,11 @@ void bar() this.goo(1, $$ } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact] - public async Task ExplicitCastToDelegate() - { - var markup = """ + public Task ExplicitCastToDelegate() + => VerifyBuilderAsync(""" using System; class a @@ -274,14 +229,11 @@ void bar() (Func) ($$ } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860580")] - public async Task ReturnStatement() - { - var markup = """ + public Task ReturnStatement() + => VerifyBuilderAsync(""" using System; class a @@ -291,14 +243,11 @@ Func bar() return $$ } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact] - public async Task BuilderInAnonymousType1() - { - var markup = """ + public Task BuilderInAnonymousType1() + => VerifyBuilderAsync(""" using System; class a @@ -308,14 +257,11 @@ int bar() var q = new {$$ } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact] - public async Task BuilderInAnonymousType2() - { - var markup = """ + public Task BuilderInAnonymousType2() + => VerifyBuilderAsync(""" using System; class a @@ -325,14 +271,11 @@ int bar() var q = new {$$ 1, 2 }; } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact] - public async Task BuilderInAnonymousType3() - { - var markup = """ + public Task BuilderInAnonymousType3() + => VerifyBuilderAsync(""" using System; class a { @@ -341,9 +284,7 @@ int bar() var q = new {Name = 1, $$ }; } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact] public async Task BuilderInFromClause() @@ -385,9 +326,8 @@ int bar() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544290")] - public async Task ParenthesizedLambdaArgument() - { - var markup = """ + public Task ParenthesizedLambdaArgument() + => VerifyBuilderAsync(""" using System; class Program { @@ -396,14 +336,11 @@ static void Main(string[] args) Console.CancelKeyPress += new ConsoleCancelEventHandler((a$$, e) => { }); } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544379")] - public async Task IncompleteParenthesizedLambdaArgument() - { - var markup = """ + public Task IncompleteParenthesizedLambdaArgument() + => VerifyBuilderAsync(""" using System; class Program { @@ -412,14 +349,11 @@ static void Main(string[] args) Console.CancelKeyPress += new ConsoleCancelEventHandler((a$$ } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544379")] - public async Task IncompleteNestedParenthesizedLambdaArgument() - { - var markup = """ + public Task IncompleteNestedParenthesizedLambdaArgument() + => VerifyNotBuilderAsync(""" using System; class Program { @@ -428,14 +362,11 @@ static void Main(string[] args) Console.CancelKeyPress += new ConsoleCancelEventHandler(((a$$ } } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Fact] - public async Task ParenthesizedExpressionInVarDeclaration() - { - var markup = """ + public Task ParenthesizedExpressionInVarDeclaration() + => VerifyNotBuilderAsync(""" using System; class Program { @@ -444,14 +375,11 @@ static void Main(string[] args) var x = (a$$ } } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24432")] - public async Task TestInObjectCreation() - { - var markup = """ + public Task TestInObjectCreation() + => VerifyNotBuilderAsync(""" using System; class Program { @@ -460,14 +388,11 @@ static void Main() Program x = new P$$ } } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24432")] - public async Task TestInArrayCreation() - { - var markup = """ + public Task TestInArrayCreation() + => VerifyNotBuilderAsync(""" using System; class Program { @@ -476,14 +401,11 @@ static void Main() Program[] x = new $$ } } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24432")] - public async Task TestInArrayCreation2() - { - var markup = """ + public Task TestInArrayCreation2() + => VerifyNotBuilderAsync(""" using System; class Program { @@ -492,14 +414,11 @@ static void Main() Program[] x = new Pr$$ } } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Fact] - public async Task TupleExpressionInVarDeclaration() - { - var markup = """ + public Task TupleExpressionInVarDeclaration() + => VerifyNotBuilderAsync(""" using System; class Program { @@ -508,14 +427,11 @@ static void Main(string[] args) var x = (a$$, b) } } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Fact] - public async Task TupleExpressionInVarDeclaration2() - { - var markup = """ + public Task TupleExpressionInVarDeclaration2() + => VerifyNotBuilderAsync(""" using System; class Program { @@ -524,14 +440,11 @@ static void Main(string[] args) var x = (a, b$$) } } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Fact] - public async Task IncompleteLambdaInActionDeclaration() - { - var markup = """ + public Task IncompleteLambdaInActionDeclaration() + => VerifyBuilderAsync(""" using System; class Program { @@ -540,14 +453,11 @@ static void Main(string[] args) System.Action x = (a$$, b) } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact] - public async Task TupleWithNamesInActionDeclaration() - { - var markup = """ + public Task TupleWithNamesInActionDeclaration() + => VerifyNotBuilderAsync(""" using System; class Program { @@ -556,14 +466,11 @@ static void Main(string[] args) System.Action x = (a$$, b: b) } } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Fact] - public async Task TupleWithNamesInActionDeclaration2() - { - var markup = """ + public Task TupleWithNamesInActionDeclaration2() + => VerifyNotBuilderAsync(""" using System; class Program { @@ -572,14 +479,11 @@ static void Main(string[] args) System.Action x = (a: a, b$$) } } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Fact] - public async Task TupleWithNamesInVarDeclaration() - { - var markup = """ + public Task TupleWithNamesInVarDeclaration() + => VerifyNotBuilderAsync(""" using System; class Program { @@ -588,14 +492,11 @@ static void Main(string[] args) var x = (a: a, b$$) } } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546363")] - public async Task BuilderForLinqExpression() - { - var markup = """ + public Task BuilderForLinqExpression() + => VerifyBuilderAsync(""" using System; using System.Linq.Expressions; @@ -606,14 +507,11 @@ public void Goo(Expression> arg) Goo($$ } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546363")] - public async Task NotInTypeParameter() - { - var markup = """ + public Task NotInTypeParameter() + => VerifyNotBuilderAsync(""" using System; using System.Linq.Expressions; @@ -624,14 +522,11 @@ public void Goo(Expression> arg) Enumerable.Empty<$$ } } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611477")] - public async Task ExtensionMethodFaultTolerance() - { - var markup = """ + public Task ExtensionMethodFaultTolerance() + => VerifyBuilderAsync(""" using System; using System.Collections; using System.Collections.Generic; @@ -671,14 +566,11 @@ static void Main(string[] args) } } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834609")] - public async Task LambdaWithAutomaticBraceCompletion() - { - var markup = """ + public Task LambdaWithAutomaticBraceCompletion() + => VerifyBuilderAsync(""" using System; using System; @@ -689,27 +581,21 @@ public void Goo() EventHandler h = (s$$) } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")] - public async Task ThisConstructorInitializer() - { - var markup = """ + public Task ThisConstructorInitializer() + => VerifyBuilderAsync(""" using System; class X { X(Func x) : this($$) { } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")] - public async Task BaseConstructorInitializer() - { - var markup = """ + public Task BaseConstructorInitializer() + => VerifyBuilderAsync(""" using System; class B { @@ -720,26 +606,20 @@ class D : B { D() : base($$) { } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/887842")] - public async Task PreprocessorExpression() - { - var markup = """ + public Task PreprocessorExpression() + => VerifyBuilderAsync(""" class C { #if $$ } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/967254")] - public async Task ImplicitArrayInitializerAfterNew() - { - var markup = """ + public Task ImplicitArrayInitializerAfterNew() + => VerifyNotBuilderAsync(""" using System; class a @@ -749,77 +629,50 @@ void goo() int[] a = new $$; } } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task NamespaceDeclaration_Unqualified() - { - var markup = @"namespace $$"; - await VerifyBuilderAsync(markup); - } + public Task NamespaceDeclaration_Unqualified() + => VerifyBuilderAsync(@"namespace $$"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task NamespaceDeclaration_Qualified() - { - var markup = @"namespace A.$$"; - await VerifyBuilderAsync(markup); - } + public Task NamespaceDeclaration_Qualified() + => VerifyBuilderAsync(@"namespace A.$$"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task FileScopedNamespaceDeclaration_Unqualified() - { - var markup = @"namespace $$;"; - await VerifyBuilderAsync(markup); - } + public Task FileScopedNamespaceDeclaration_Unqualified() + => VerifyBuilderAsync(@"namespace $$;"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task FileScopedNamespaceDeclaration_Qualified() - { - var markup = @"namespace A.$$;"; - await VerifyBuilderAsync(markup); - } + public Task FileScopedNamespaceDeclaration_Qualified() + => VerifyBuilderAsync(@"namespace A.$$;"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task PartialClassName() - { - var markup = @"partial class $$"; - await VerifyBuilderAsync(markup); - } + public Task PartialClassName() + => VerifyBuilderAsync(@"partial class $$"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task PartialStructName() - { - var markup = @"partial struct $$"; - await VerifyBuilderAsync(markup); - } + public Task PartialStructName() + => VerifyBuilderAsync(@"partial struct $$"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task PartialInterfaceName() - { - var markup = @"partial interface $$"; - await VerifyBuilderAsync(markup); - } + public Task PartialInterfaceName() + => VerifyBuilderAsync(@"partial interface $$"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/12818")] - public async Task UnwrapParamsArray() - { - var markup = """ + public Task UnwrapParamsArray() + => VerifyBuilderAsync(""" using System; class C { C(params Action[] a) { new C($$ } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72225")] - public async Task UnwrapParamsCollection() - { - var markup = """ + public Task UnwrapParamsCollection() + => VerifyBuilderAsync(""" using System; using System.Collections.Generic; @@ -830,53 +683,41 @@ class C new C($$ } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/12818")] - public async Task DoNotUnwrapRegularArray() - { - var markup = """ + public Task DoNotUnwrapRegularArray() + => VerifyNotBuilderAsync(""" using System; class C { C(Action[] a) { new C($$ } } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47662")] - public async Task LambdaExpressionInImplicitObjectCreation() - { - var markup = """ + public Task LambdaExpressionInImplicitObjectCreation() + => VerifyBuilderAsync(""" using System; class C { C(Action a) { C c = new($$ } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15443")] - public async Task NotBuilderWhenDelegateInferredRightOfDotInInvocation() - { - var markup = """ + public Task NotBuilderWhenDelegateInferredRightOfDotInInvocation() + => VerifyNotBuilderAsync(""" class C { Action a = Task.$$ } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15443")] - public async Task NotBuilderInTypeArgument() - { - var markup = """ + public Task NotBuilderInTypeArgument() + => VerifyNotBuilderAsync(""" namespace ConsoleApplication1 { class Program @@ -890,25 +731,19 @@ static void Main(string[] args) static T Load() => default(T); } } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16176")] - public async Task NotBuilderForLambdaAfterNew() - { - var markup = """ + public Task NotBuilderForLambdaAfterNew() + => VerifyNotBuilderAsync(""" class C { Action a = new $$ } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20937")] - public async Task AsyncLambda() - { - var markup = """ + public Task AsyncLambda() + => VerifyBuilderAsync(""" using System; using System.Threading.Tasks; class Program @@ -918,15 +753,11 @@ public void B(Func> f) { } void A() { B(async($$ - """; - - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20937")] - public async Task AsyncLambdaAfterComma() - { - var markup = """ + public Task AsyncLambdaAfterComma() + => VerifyBuilderAsync(""" using System; using System.Threading.Tasks; class Program @@ -936,15 +767,11 @@ public void B(Func> f) { } void A() { B(async(p1, $$ - """; - - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28586")] - public async Task WithExtensionAndInstanceMethod1() - { - var markup = """ + public Task WithExtensionAndInstanceMethod1() + => VerifyBuilderAsync(""" using System; public sealed class Goo @@ -968,14 +795,11 @@ public static void ReproMethod(Goo goo) goo.Bar(a$$ } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28586")] - public async Task WithExtensionAndInstanceMethod2() - { - var markup = """ + public Task WithExtensionAndInstanceMethod2() + => VerifyBuilderAsync(""" using System; public sealed class Goo @@ -999,14 +823,11 @@ public static void ReproMethod(Goo goo) goo.Bar(a$$) } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28586")] - public async Task WithExtensionAndInstanceMethod3() - { - var markup = """ + public Task WithExtensionAndInstanceMethod3() + => VerifyBuilderAsync(""" using System; public sealed class Goo @@ -1030,14 +851,11 @@ public static void ReproMethod(Goo goo) goo.Bar(($$ } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28586")] - public async Task WithExtensionAndInstanceMethod4() - { - var markup = """ + public Task WithExtensionAndInstanceMethod4() + => VerifyBuilderAsync(""" using System; public sealed class Goo @@ -1061,14 +879,11 @@ public static void ReproMethod(Goo goo) goo.Bar(($$) } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28586")] - public async Task WithExtensionAndInstanceMethod5() - { - var markup = """ + public Task WithExtensionAndInstanceMethod5() + => VerifyBuilderAsync(""" using System; public sealed class Goo @@ -1092,14 +907,11 @@ public static void ReproMethod(Goo goo) goo.Bar(($$)) } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28586")] - public async Task WithExtensionAndInstanceMethod6() - { - var markup = """ + public Task WithExtensionAndInstanceMethod6() + => VerifyBuilderAsync(""" using System; public sealed class Goo @@ -1123,14 +935,11 @@ public static void ReproMethod(Goo goo) goo.Bar((a, $$ } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28586")] - public async Task WithExtensionAndInstanceMethod7() - { - var markup = """ + public Task WithExtensionAndInstanceMethod7() + => VerifyBuilderAsync(""" using System; public sealed class Goo @@ -1154,14 +963,11 @@ public static void ReproMethod(Goo goo) goo.Bar(async (a$$ } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28586")] - public async Task WithNonDelegateExtensionAndInstanceMethod1() - { - var markup = """ + public Task WithNonDelegateExtensionAndInstanceMethod1() + => VerifyNotBuilderAsync(""" using System; public sealed class Goo @@ -1185,14 +991,11 @@ public static void ReproMethod(Goo goo) goo.Bar(a$$ } } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task TestInDeclarationPattern() - { - var markup = """ + public Task TestInDeclarationPattern() + => VerifyBuilderAsync(""" class C { void M() @@ -1201,14 +1004,11 @@ void M() if (e is int o$$) } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task TestInDeclarationPattern2() - { - var markup = """ + public Task TestInDeclarationPattern2() + => VerifyBuilderAsync(""" class C { void M() @@ -1217,14 +1017,11 @@ void M() if (e is System.Collections.Generic.List an$$) } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task TestInRecursivePattern() - { - var markup = """ + public Task TestInRecursivePattern() + => VerifyBuilderAsync(""" class C { int P { get; } @@ -1234,14 +1031,11 @@ void M(C test) if (test is { P: 1 } o$$) } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task TestInPropertyPattern() - { - var markup = """ + public Task TestInPropertyPattern() + => VerifyBuilderAsync(""" class C { int P { get; } @@ -1251,14 +1045,11 @@ void M(C test) if (test is { P: int o$$ }) } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task TestInAndPattern() - { - var markup = """ + public Task TestInAndPattern() + => VerifyBuilderAsync(""" class C { void M() @@ -1267,14 +1058,11 @@ void M() if (e is 1 and int a$$) } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task TestInAndOrPattern() - { - var markup = """ + public Task TestInAndOrPattern() + => VerifyBuilderAsync(""" class C { void M() @@ -1283,14 +1071,11 @@ void M() if (e is (int or 1) and int a$$) } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task TestInSwitchStatement() - { - var markup = """ + public Task TestInSwitchStatement() + => VerifyBuilderAsync(""" class C { void M() @@ -1302,14 +1087,11 @@ void M() } } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task TestInSwitchExpression() - { - var markup = """ + public Task TestInSwitchExpression() + => VerifyBuilderAsync(""" class C { void M() @@ -1321,14 +1103,11 @@ int o$$ } } } - """; - await VerifyBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task TestMissingInNotPattern_Declaration() - { - var markup = """ + public Task TestMissingInNotPattern_Declaration() + => VerifyNotBuilderAsync(""" class C { void M() @@ -1337,14 +1116,11 @@ void M() if (e is not int o$$) } } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task TestMissingInNotPattern_Declaration2() - { - var markup = """ + public Task TestMissingInNotPattern_Declaration2() + => VerifyNotBuilderAsync(""" class C { void M() @@ -1353,14 +1129,11 @@ void M() if (e is not (1 and int o$$)) } } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task TestMissingInNotPattern_Recursive() - { - var markup = """ + public Task TestMissingInNotPattern_Recursive() + => VerifyNotBuilderAsync(""" class C { int P { get; } @@ -1370,14 +1143,11 @@ void M(C test) if (test is not { P: 1 } o$$) } } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task TestMissingInOrPattern() - { - var markup = """ + public Task TestMissingInOrPattern() + => VerifyNotBuilderAsync(""" class C { void M() @@ -1386,14 +1156,11 @@ void M() if (e is 1 or int o$$) } } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task TestMissingInAndOrPattern() - { - var markup = """ + public Task TestMissingInAndOrPattern() + => VerifyNotBuilderAsync(""" class C { void M() @@ -1402,14 +1169,11 @@ void M() if (e is 1 or int and int o$$) } } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task TestMissingInRecursiveOrPattern() - { - var markup = """ + public Task TestMissingInRecursiveOrPattern() + => VerifyNotBuilderAsync(""" class C { int P { get; } @@ -1419,28 +1183,24 @@ void M(C test) if (test is null or { P: 1 } o$$) } } - """; - await VerifyNotBuilderAsync(markup); - } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/46927"), CombinatorialData] - public async Task FirstArgumentOfInvocation_NoParameter(bool hasTypedChar) - { - var markup = $@" -using System; -interface Foo -{{ - bool Bar() => true; -}} -class P -{{ - void M(Foo f) - {{ - f.Bar({(hasTypedChar ? "s" : "")}$$ - }} -}}"; - await VerifyNotBuilderAsync(markup); - } + public Task FirstArgumentOfInvocation_NoParameter(bool hasTypedChar) + => VerifyNotBuilderAsync($$""" + using System; + interface Foo + { + bool Bar() => true; + } + class P + { + void M(Foo f) + { + f.Bar({{(hasTypedChar ? "s" : "")}}$$ + } + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/46927"), CombinatorialData] public async Task FirstArgumentOfInvocation_PossibleLambdaExpression(bool isLambda, bool hasTypedChar) @@ -1449,20 +1209,21 @@ public async Task FirstArgumentOfInvocation_PossibleLambdaExpression(bool isLamb ? "bool Bar(Func predicate) => true;" : "bool Bar(int x) => true;"; - var markup = $@" -using System; -interface Foo -{{ - bool Bar() => true; - {overload} -}} -class P -{{ - void M(Foo f) - {{ - f.Bar({(hasTypedChar ? "s" : "")}$$ - }} -}}"; + var markup = $$""" + using System; + interface Foo + { + bool Bar() => true; + {{overload}} + } + class P + { + void M(Foo f) + { + f.Bar({{(hasTypedChar ? "s" : "")}}$$ + } + } + """; if (isLambda) { await VerifyBuilderAsync(markup); @@ -1477,24 +1238,22 @@ void M(Foo f) [InlineData("string x = null, string y = null")] [InlineData("string x = null, string y = null, params string[] z")] [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/49656")] - public async Task FirstArgumentOfInvocation_WithOverloadAcceptEmptyArgumentList(string overloadParameterList) - { - var markup = $@" -using System; -interface Foo -{{ - bool Bar({overloadParameterList}) => true; - bool Bar(Func predicate) => true; -}} -class P -{{ - void M(Foo f) - {{ - f.Bar($$) - }} -}}"; - await VerifyBuilderAsync(markup); - } + public Task FirstArgumentOfInvocation_WithOverloadAcceptEmptyArgumentList(string overloadParameterList) + => VerifyBuilderAsync($$""" + using System; + interface Foo + { + bool Bar({{overloadParameterList}}) => true; + bool Bar(Func predicate) => true; + } + class P + { + void M(Foo f) + { + f.Bar($$) + } + } + """); private async Task VerifyNotBuilderAsync(string markup) => await VerifyWorkerAsync(markup, isBuilder: false); diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SymbolCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SymbolCompletionProviderTests.cs index 077822b7d8a4e..60063fe34c070 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SymbolCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SymbolCompletionProviderTests.cs @@ -10,7 +10,6 @@ using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; -using Microsoft.CodeAnalysis.CSharp.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion; using Microsoft.CodeAnalysis.Test.Utilities; @@ -316,16 +315,13 @@ await VerifyExpectedItemsAsync(code, [ } [Fact] - public async Task OpenStringLiteralInDirective() - { - var code = "#r \"$$"; - await VerifyExpectedItemsAsync( - code, [ + public Task OpenStringLiteralInDirective() + => VerifyExpectedItemsAsync( + "#r \"$$", [ ItemExpectation.Absent("String"), ItemExpectation.Absent("System") ], sourceCodeKind: SourceCodeKind.Script); - } [Fact] public async Task StringLiteral() @@ -338,18 +334,15 @@ await VerifyExpectedItemsAsync(code, [ } [Fact] - public async Task StringLiteralInDirective() - { - var code = """ + public Task StringLiteralInDirective() + => VerifyExpectedItemsAsync( + """ #r "$$" - """; - await VerifyExpectedItemsAsync( - code, [ + """, [ ItemExpectation.Absent("String"), ItemExpectation.Absent("System") ], sourceCodeKind: SourceCodeKind.Script); - } [Fact] public async Task OpenCharLiteral() @@ -362,14 +355,11 @@ await VerifyExpectedItemsAsync(code, [ } [Fact] - public async Task AssemblyAttribute1() - { - var code = @"[assembly: $$]"; - await VerifyExpectedItemsAsync(code, [ + public Task AssemblyAttribute1() + => VerifyExpectedItemsAsync(@"[assembly: $$]", [ ItemExpectation.Absent("String"), ItemExpectation.Exists("System") ]); - } [Fact] public async Task AssemblyAttribute2() @@ -383,15 +373,11 @@ await VerifyExpectedItemsAsync(source, [ } [Fact] - public async Task SystemAttributeIsNotAnAttribute() - { - var content = """ + public Task SystemAttributeIsNotAnAttribute() + => VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", """ [$$] class CL {} - """; - - await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"Attribute"); - } + """), @"Attribute"); [Fact] public async Task TypeAttribute() @@ -462,118 +448,85 @@ await VerifyExpectedItemsAsync(code, [ } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task NamespaceName_EmptyNameSpan_TopLevel() - { - var source = @"namespace $$ { }"; - - await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); - } + public Task NamespaceName_EmptyNameSpan_TopLevel() + => VerifyItemExistsAsync(@"namespace $$ { }", "System", sourceCodeKind: SourceCodeKind.Regular); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task NamespaceName_EmptyNameSpan_Nested() - { - var source = """ + public Task NamespaceName_EmptyNameSpan_Nested() + => VerifyItemExistsAsync(""" ; namespace System { namespace $$ { } } - """; - - await VerifyItemExistsAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular); - } + """, "Runtime", sourceCodeKind: SourceCodeKind.Regular); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task NamespaceName_Unqualified_TopLevelNoPeers() - { - var source = """ + public Task NamespaceName_Unqualified_TopLevelNoPeers() + => VerifyExpectedItemsAsync(""" using System; namespace $$ - """; - - await VerifyExpectedItemsAsync(source, + """, [ ItemExpectation.Exists("System"), ItemExpectation.Absent("String") ], sourceCodeKind: SourceCodeKind.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task NamespaceName_Unqualified_TopLevelNoPeers_FileScopedNamespace() - { - var source = """ + public Task NamespaceName_Unqualified_TopLevelNoPeers_FileScopedNamespace() + => VerifyExpectedItemsAsync(""" using System; namespace $$; - """; - - await VerifyExpectedItemsAsync(source, + """, [ ItemExpectation.Exists("System"), ItemExpectation.Absent("String") ], sourceCodeKind: SourceCodeKind.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task NamespaceName_Unqualified_TopLevelWithPeer() - { - var source = """ + public Task NamespaceName_Unqualified_TopLevelWithPeer() + => VerifyItemExistsAsync(""" namespace A { } namespace $$ - """; - - await VerifyItemExistsAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); - } + """, "A", sourceCodeKind: SourceCodeKind.Regular); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task NamespaceName_Unqualified_NestedWithNoPeers() - { - var source = """ + public Task NamespaceName_Unqualified_NestedWithNoPeers() + => VerifyNoItemsExistAsync(""" namespace A { namespace $$ } - """; - - await VerifyNoItemsExistAsync(source, sourceCodeKind: SourceCodeKind.Regular); - } + """, sourceCodeKind: SourceCodeKind.Regular); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task NamespaceName_Unqualified_NestedWithPeer() - { - var source = """ + public Task NamespaceName_Unqualified_NestedWithPeer() + => VerifyExpectedItemsAsync(""" namespace A { namespace B { } namespace $$ } - """; - - await VerifyExpectedItemsAsync(source, + """, [ ItemExpectation.Absent("A"), ItemExpectation.Exists("B") ], sourceCodeKind: SourceCodeKind.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task NamespaceName_Unqualified_ExcludesCurrentDeclaration() - { - var source = @"namespace N$$S"; - - await VerifyItemIsAbsentAsync(source, "NS", sourceCodeKind: SourceCodeKind.Regular); - } + public Task NamespaceName_Unqualified_ExcludesCurrentDeclaration() + => VerifyItemIsAbsentAsync(@"namespace N$$S", "NS", sourceCodeKind: SourceCodeKind.Regular); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task NamespaceName_Unqualified_WithNested() - { - var source = """ + public Task NamespaceName_Unqualified_WithNested() + => VerifyExpectedItemsAsync(""" namespace A { namespace $$ @@ -581,20 +534,16 @@ namespace $$ namespace B { } } } - """; - - await VerifyExpectedItemsAsync(source, + """, [ ItemExpectation.Absent("A"), ItemExpectation.Absent("B") ], sourceCodeKind: SourceCodeKind.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task NamespaceName_Unqualified_WithNestedAndMatchingPeer() - { - var source = """ + public Task NamespaceName_Unqualified_WithNestedAndMatchingPeer() + => VerifyExpectedItemsAsync(""" namespace A.B { } namespace A @@ -604,33 +553,26 @@ namespace $$ namespace B { } } } - """; - - await VerifyExpectedItemsAsync(source, + """, [ ItemExpectation.Absent("A"), ItemExpectation.Exists("B") ], sourceCodeKind: SourceCodeKind.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task NamespaceName_Unqualified_InnerCompletionPosition() - { - var source = @"namespace Sys$$tem { }"; - - await VerifyExpectedItemsAsync(source, + public Task NamespaceName_Unqualified_InnerCompletionPosition() + => VerifyExpectedItemsAsync(@"namespace Sys$$tem { }", [ ItemExpectation.Exists("System"), ItemExpectation.Absent("Runtime") ], sourceCodeKind: SourceCodeKind.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task NamespaceName_Unqualified_IncompleteDeclaration() - { - var source = """ + public Task NamespaceName_Unqualified_IncompleteDeclaration() + => VerifyExpectedItemsAsync( + """ namespace A { namespace B @@ -642,10 +584,7 @@ namespace B.C2 { } } namespace A.B.C3 { } - """; - - await VerifyExpectedItemsAsync( - source, [ + """, [ // Ideally, all the C* namespaces would be recommended but, because of how the parser // recovers from the missing braces, they end up with the following qualified names... // @@ -664,142 +603,105 @@ await VerifyExpectedItemsAsync( ItemExpectation.Exists("B") ], SourceCodeKind.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task NamespaceName_Qualified_NoPeers() - { - var source = @"namespace A.$$"; - - await VerifyNoItemsExistAsync(source, sourceCodeKind: SourceCodeKind.Regular); - } + public Task NamespaceName_Qualified_NoPeers() + => VerifyNoItemsExistAsync(@"namespace A.$$", sourceCodeKind: SourceCodeKind.Regular); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task NamespaceName_Qualified_TopLevelWithPeer() - { - var source = """ + public Task NamespaceName_Qualified_TopLevelWithPeer() + => VerifyItemExistsAsync(""" namespace A.B { } namespace A.$$ - """; - - await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); - } + """, "B", sourceCodeKind: SourceCodeKind.Regular); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task NamespaceName_Qualified_TopLevelWithPeer_FileScopedNamespace() - { - var source = """ + public Task NamespaceName_Qualified_TopLevelWithPeer_FileScopedNamespace() + => VerifyItemExistsAsync(""" namespace A.B { } namespace A.$$; - """; - - await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); - } + """, "B", sourceCodeKind: SourceCodeKind.Regular); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task NamespaceName_Qualified_NestedWithPeer() - { - var source = """ + public Task NamespaceName_Qualified_NestedWithPeer() + => VerifyExpectedItemsAsync(""" namespace A { namespace B.C { } namespace B.$$ } - """; - - await VerifyExpectedItemsAsync(source, + """, [ ItemExpectation.Absent("A"), ItemExpectation.Absent("B"), ItemExpectation.Exists("C") ], sourceCodeKind: SourceCodeKind.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task NamespaceName_Qualified_WithNested() - { - var source = """ + public Task NamespaceName_Qualified_WithNested() + => VerifyExpectedItemsAsync(""" namespace A.$$ { namespace B { } } - """; - - await VerifyExpectedItemsAsync(source, + """, [ ItemExpectation.Absent("A"), ItemExpectation.Absent("B") ], sourceCodeKind: SourceCodeKind.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task NamespaceName_Qualified_WithNestedAndMatchingPeer() - { - var source = """ + public Task NamespaceName_Qualified_WithNestedAndMatchingPeer() + => VerifyExpectedItemsAsync(""" namespace A.B { } namespace A.$$ { namespace B { } } - """; - - await VerifyExpectedItemsAsync(source, + """, [ ItemExpectation.Absent("A"), ItemExpectation.Exists("B") ], sourceCodeKind: SourceCodeKind.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task NamespaceName_Qualified_InnerCompletionPosition() - { - var source = @"namespace Sys$$tem.Runtime { }"; - - await VerifyExpectedItemsAsync(source, + public Task NamespaceName_Qualified_InnerCompletionPosition() + => VerifyExpectedItemsAsync(@"namespace Sys$$tem.Runtime { }", [ ItemExpectation.Exists("System"), ItemExpectation.Absent("Runtime") ], sourceCodeKind: SourceCodeKind.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task NamespaceName_OnKeyword() - { - var source = @"name$$space System { }"; - - await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); - } + public Task NamespaceName_OnKeyword() + => VerifyItemExistsAsync(@"name$$space System { }", "System", sourceCodeKind: SourceCodeKind.Regular); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task NamespaceName_OnNestedKeyword() - { - var source = """ + public Task NamespaceName_OnNestedKeyword() + => VerifyExpectedItemsAsync(""" namespace System { name$$space Runtime { } } - """; - - await VerifyExpectedItemsAsync(source, + """, [ ItemExpectation.Absent("System"), ItemExpectation.Absent("Runtime") ], sourceCodeKind: SourceCodeKind.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7213")] - public async Task NamespaceName_Qualified_IncompleteDeclaration() - { - var source = """ + public Task NamespaceName_Qualified_IncompleteDeclaration() + => VerifyExpectedItemsAsync( + """ namespace A { namespace B @@ -813,10 +715,7 @@ namespace B.C.D2 { } } namespace A.B.C.D3 { } - """; - - await VerifyExpectedItemsAsync( - source, [ + """, [ ItemExpectation.Absent("A"), ItemExpectation.Absent("B"), ItemExpectation.Absent("C"), @@ -834,31 +733,24 @@ await VerifyExpectedItemsAsync( ItemExpectation.Absent("D3") ], SourceCodeKind.Regular); - } [Fact] - public async Task UnderNamespace() - { - var source = @"namespace NS { $$"; - await VerifyExpectedItemsAsync(source, [ + public Task UnderNamespace() + => VerifyExpectedItemsAsync(@"namespace NS { $$", [ ItemExpectation.Absent("String"), ItemExpectation.Absent("System") ]); - } [Fact] - public async Task OutsideOfType1() - { - var source = """ + public Task OutsideOfType1() + => VerifyExpectedItemsAsync(""" namespace NS { class CL {} $$ - """; - await VerifyExpectedItemsAsync(source, [ + """, [ ItemExpectation.Absent("String"), ItemExpectation.Absent("System") ]); - } [Fact] public async Task OutsideOfType2() @@ -876,9 +768,8 @@ await VerifyExpectedItemsAsync(source, [ } [Fact] - public async Task CompletionInsideProperty() - { - var source = """ + public Task CompletionInsideProperty() + => VerifyExpectedItemsAsync(""" class C { private string name; @@ -887,12 +778,10 @@ public string Name set { name = $$ - """; - await VerifyExpectedItemsAsync(source, [ + """, [ ItemExpectation.Exists("value"), ItemExpectation.Exists("C") ]); - } [Fact] public async Task AfterDot() @@ -1818,21 +1707,16 @@ await VerifyExpectedItemsAsync(source, [ } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TypeParameterConstraintClause() - { - await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL where T : $$"), @"System"); - } + public Task TypeParameterConstraintClause() + => VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL where T : $$"), @"System"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TypeParameterConstraintClause_NotStaticClass() - { - await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL where T : $$"), @"Console"); - } + public Task TypeParameterConstraintClause_NotStaticClass() + => VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL where T : $$"), @"Console"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TypeParameterConstraintClause_StillShowStaticClassWhenHaveInternalType() - { - await VerifyItemExistsAsync( + public Task TypeParameterConstraintClause_StillShowStaticClassWhenHaveInternalType() + => VerifyItemExistsAsync( """ static class Test { @@ -1841,18 +1725,14 @@ public interface IInterface {} class CL where T : $$ """, @"Test"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TypeParameterConstraintClause_NotSealedClass() - { - await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL where T : $$"), @"String"); - } + public Task TypeParameterConstraintClause_NotSealedClass() + => VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL where T : $$"), @"String"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TypeParameterConstraintClause_StillShowSealedClassWhenHaveInternalType() - { - await VerifyItemExistsAsync( + public Task TypeParameterConstraintClause_StillShowSealedClassWhenHaveInternalType() + => VerifyItemExistsAsync( """ sealed class Test { @@ -1861,7 +1741,6 @@ public interface IInterface {} class CL where T : $$ """, @"Test"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] public async Task TypeParameterConstraintClause_StillShowStaticAndSealedTypesNotDirectlyInConstraint() @@ -1875,21 +1754,16 @@ await VerifyExpectedItemsAsync(source, [ } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TypeParameterConstraintClauseList() - { - await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL where T : A, $$"), @"System"); - } + public Task TypeParameterConstraintClauseList() + => VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL where T : A, $$"), @"System"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TypeParameterConstraintClauseList_NotStaticClass() - { - await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL where T : A, $$"), @"Console"); - } + public Task TypeParameterConstraintClauseList_NotStaticClass() + => VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL where T : A, $$"), @"Console"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TypeParameterConstraintClauseList_StillShowStaticClassWhenHaveInternalType() - { - await VerifyItemExistsAsync( + public Task TypeParameterConstraintClauseList_StillShowStaticClassWhenHaveInternalType() + => VerifyItemExistsAsync( """ static class Test { @@ -1898,18 +1772,14 @@ public interface IInterface {} class CL where T : A, $$ """, @"Test"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TypeParameterConstraintClauseList_NotSealedClass() - { - await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL where T : A, $$"), @"String"); - } + public Task TypeParameterConstraintClauseList_NotSealedClass() + => VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL where T : A, $$"), @"String"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TypeParameterConstraintClauseList_StillShowSealedClassWhenHaveInternalType() - { - await VerifyItemExistsAsync( + public Task TypeParameterConstraintClauseList_StillShowSealedClassWhenHaveInternalType() + => VerifyItemExistsAsync( """ sealed class Test { @@ -1918,7 +1788,6 @@ public interface IInterface {} class CL where T : A, $$ """, @"Test"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] public async Task TypeParameterConstraintClauseList_StillShowStaticAndSealedTypesNotDirectlyInConstraint() @@ -2093,70 +1962,58 @@ public async Task Parameters_01() [InlineData("ar")] [InlineData("arg")] [InlineData("args")] - public async Task Parameters_02(string prefix) - { - await VerifyItemExistsAsync(prefix + "$$", "args", sourceCodeKind: SourceCodeKind.Regular); - } + public Task Parameters_02(string prefix) + => VerifyItemExistsAsync(prefix + "$$", "args", sourceCodeKind: SourceCodeKind.Regular); [Theory] [InlineData("a")] [InlineData("ar")] [InlineData("arg")] [InlineData("args")] - public async Task Parameters_03(string prefix) - { - await VerifyItemIsAbsentAsync(prefix + "$$", "args", sourceCodeKind: SourceCodeKind.Script); - } + public Task Parameters_03(string prefix) + => VerifyItemIsAbsentAsync(prefix + "$$", "args", sourceCodeKind: SourceCodeKind.Script); [Theory] [InlineData("a")] [InlineData("ar")] [InlineData("arg")] [InlineData("args")] - public async Task Parameters_04(string prefix) - { - await VerifyItemExistsAsync(prefix + """ + public Task Parameters_04(string prefix) + => VerifyItemExistsAsync(prefix + """ $$ Systen.Console.WriteLine(); """, "args", sourceCodeKind: SourceCodeKind.Regular); - } [Theory] [InlineData("a")] [InlineData("ar")] [InlineData("arg")] [InlineData("args")] - public async Task Parameters_05(string prefix) - { - await VerifyItemExistsAsync(""" + public Task Parameters_05(string prefix) + => VerifyItemExistsAsync(""" Systen.Console.WriteLine(); """ + prefix + "$$", "args", sourceCodeKind: SourceCodeKind.Regular); - } [Theory] [InlineData("a")] [InlineData("ar")] [InlineData("arg")] [InlineData("args")] - public async Task Parameters_06(string prefix) - { - await VerifyItemExistsAsync(""" + public Task Parameters_06(string prefix) + => VerifyItemExistsAsync(""" Systen.Console.WriteLine(); """ + prefix + """ $$ Systen.Console.WriteLine(); """, "args", sourceCodeKind: SourceCodeKind.Regular); - } [Theory] [InlineData("a")] [InlineData("ar")] [InlineData("arg")] [InlineData("args")] - public async Task Parameters_07(string prefix) - { - await VerifyItemExistsAsync("call(" + prefix + "$$)", "args", sourceCodeKind: SourceCodeKind.Regular); - } + public Task Parameters_07(string prefix) + => VerifyItemExistsAsync("call(" + prefix + "$$)", "args", sourceCodeKind: SourceCodeKind.Regular); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/55969")] public async Task Parameters_TopLevelStatement_1() @@ -2240,12 +2097,8 @@ public async Task MembersAfterVerbatimStringLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { @"""".$$"), "Equals"); [Fact] - public async Task MembersAfterNumericLiteral() - { - // NOTE: the Completion command handler will suppress this case if the user types '.', - // but we still need to show members if the user specifically invokes statement completion here. - await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { 2.$$"), "Equals"); - } + public Task MembersAfterNumericLiteral() + => VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { 2.$$"), "Equals"); [Fact] public async Task NoMembersAfterParenthesizedNullLiteral() @@ -2284,9 +2137,8 @@ public async Task InstanceTypesAvailableInUsingAlias() => await VerifyItemExistsAsync(@"using S = System.$$", "String"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] - public async Task InheritedMember1() - { - var markup = """ + public Task InheritedMember1() + => VerifyExpectedItemsAsync(""" class A { private void Hidden() { } @@ -2299,17 +2151,14 @@ void Bar() $$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("Hidden"), ItemExpectation.Exists("Goo") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] - public async Task InheritedMember2() - { - var markup = """ + public Task InheritedMember2() + => VerifyExpectedItemsAsync(""" class A { private void Hidden() { } @@ -2322,17 +2171,14 @@ void Bar() this.$$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("Hidden"), ItemExpectation.Exists("Goo") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] - public async Task InheritedMember3() - { - var markup = """ + public Task InheritedMember3() + => VerifyExpectedItemsAsync(""" class A { private void Hidden() { } @@ -2345,18 +2191,15 @@ void Bar() base.$$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("Hidden"), ItemExpectation.Exists("Goo"), ItemExpectation.Absent("Bar"), ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] - public async Task InheritedStaticMember1() - { - var markup = """ + public Task InheritedStaticMember1() + => VerifyExpectedItemsAsync(""" class A { private static void Hidden() { } @@ -2369,17 +2212,14 @@ void Bar() $$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("Hidden"), ItemExpectation.Exists("Goo") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] - public async Task InheritedStaticMember2() - { - var markup = """ + public Task InheritedStaticMember2() + => VerifyExpectedItemsAsync(""" class A { private static void Hidden() { } @@ -2392,17 +2232,14 @@ void Bar() B.$$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("Hidden"), ItemExpectation.Exists("Goo") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] - public async Task InheritedStaticMember3() - { - var markup = """ + public Task InheritedStaticMember3() + => VerifyExpectedItemsAsync(""" class A { private static void Hidden() { } @@ -2415,17 +2252,14 @@ void Bar() A.$$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("Hidden"), ItemExpectation.Exists("Goo") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] - public async Task InheritedInstanceAndStaticMembers() - { - var markup = """ + public Task InheritedInstanceAndStaticMembers() + => VerifyExpectedItemsAsync(""" class A { private static void HiddenStatic() { } @@ -2441,171 +2275,129 @@ void Bar() $$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("HiddenStatic"), ItemExpectation.Exists("GooStatic"), ItemExpectation.Absent("HiddenInstance"), ItemExpectation.Exists("GooInstance") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540155")] - public async Task ForLoopIndexer1() - { - var markup = """ + public Task ForLoopIndexer1() + => VerifyItemExistsAsync(""" class C { void M() { for (int i = 0; $$ - """; - await VerifyItemExistsAsync(markup, "i"); - } + """, "i"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540155")] - public async Task ForLoopIndexer2() - { - var markup = """ + public Task ForLoopIndexer2() + => VerifyItemExistsAsync(""" class C { void M() { for (int i = 0; i < 10; $$ - """; - await VerifyItemExistsAsync(markup, "i"); - } + """, "i"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] - public async Task NoInstanceMembersAfterType1() - { - var markup = """ + public Task NoInstanceMembersAfterType1() + => VerifyItemIsAbsentAsync(""" class C { void M() { System.IDisposable.$$ - """; - - await VerifyItemIsAbsentAsync(markup, "Dispose"); - } + """, "Dispose"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] - public async Task NoInstanceMembersAfterType2() - { - var markup = """ + public Task NoInstanceMembersAfterType2() + => VerifyItemIsAbsentAsync(""" class C { void M() { (System.IDisposable).$$ - """; - await VerifyItemIsAbsentAsync(markup, "Dispose"); - } + """, "Dispose"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] - public async Task NoInstanceMembersAfterType3() - { - var markup = """ + public Task NoInstanceMembersAfterType3() + => VerifyItemIsAbsentAsync(""" using System; class C { void M() { IDisposable.$$ - """; - - await VerifyItemIsAbsentAsync(markup, "Dispose"); - } + """, "Dispose"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] - public async Task NoInstanceMembersAfterType4() - { - var markup = """ + public Task NoInstanceMembersAfterType4() + => VerifyItemIsAbsentAsync(""" using System; class C { void M() { (IDisposable).$$ - """; - - await VerifyItemIsAbsentAsync(markup, "Dispose"); - } + """, "Dispose"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] - public async Task StaticMembersAfterType1() - { - var markup = """ + public Task StaticMembersAfterType1() + => VerifyItemExistsAsync(""" class C { void M() { System.IDisposable.$$ - """; - - await VerifyItemExistsAsync(markup, "ReferenceEquals"); - } + """, "ReferenceEquals"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] - public async Task StaticMembersAfterType2() - { - var markup = """ + public Task StaticMembersAfterType2() + => VerifyItemIsAbsentAsync(""" class C { void M() { (System.IDisposable).$$ - """; - await VerifyItemIsAbsentAsync(markup, "ReferenceEquals"); - } + """, "ReferenceEquals"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] - public async Task StaticMembersAfterType3() - { - var markup = """ + public Task StaticMembersAfterType3() + => VerifyItemExistsAsync(""" using System; class C { void M() { IDisposable.$$ - """; - - await VerifyItemExistsAsync(markup, "ReferenceEquals"); - } + """, "ReferenceEquals"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] - public async Task StaticMembersAfterType4() - { - var markup = """ + public Task StaticMembersAfterType4() + => VerifyItemIsAbsentAsync(""" using System; class C { void M() { (IDisposable).$$ - """; - - await VerifyItemIsAbsentAsync(markup, "ReferenceEquals"); - } + """, "ReferenceEquals"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540197")] - public async Task TypeParametersInClass() - { - var markup = """ + public Task TypeParametersInClass() + => VerifyItemExistsAsync(""" class C { $$ } - """; - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540212")] - public async Task AfterRefInLambda_TypeOnly() - { - var markup = """ + public Task AfterRefInLambda_TypeOnly() + => VerifyExpectedItemsAsync(""" using System; class C { @@ -2614,17 +2406,14 @@ void M(String parameter) Func f = (ref $$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("String"), ItemExpectation.Absent("parameter") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540212")] - public async Task AfterOutInLambda_TypeOnly() - { - var markup = """ + public Task AfterOutInLambda_TypeOnly() + => VerifyExpectedItemsAsync(""" using System; class C { @@ -2633,17 +2422,14 @@ void M(String parameter) Func f = (out $$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("String"), ItemExpectation.Absent("parameter") ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24326")] - public async Task AfterInInLambda_TypeOnly() - { - var markup = """ + public Task AfterInInLambda_TypeOnly() + => VerifyExpectedItemsAsync(""" using System; class C { @@ -2652,17 +2438,14 @@ void M(String parameter) Func f = (in $$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("String"), ItemExpectation.Absent("parameter") ]); - } [Fact] - public async Task AfterRefInMethodDeclaration_TypeOnly() - { - var markup = """ + public Task AfterRefInMethodDeclaration_TypeOnly() + => VerifyExpectedItemsAsync(""" using System; class C { @@ -2671,17 +2454,14 @@ void M(ref $$) { } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("String"), ItemExpectation.Absent("field") ]); - } [Fact] - public async Task AfterOutInMethodDeclaration_TypeOnly() - { - var markup = """ + public Task AfterOutInMethodDeclaration_TypeOnly() + => VerifyExpectedItemsAsync(""" using System; class C { @@ -2690,17 +2470,14 @@ void M(out $$) { } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("String"), ItemExpectation.Absent("field") ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24326")] - public async Task AfterInInMethodDeclaration_TypeOnly() - { - var markup = """ + public Task AfterInInMethodDeclaration_TypeOnly() + => VerifyExpectedItemsAsync(""" using System; class C { @@ -2709,17 +2486,14 @@ void M(in $$) { } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("String"), ItemExpectation.Absent("field") ]); - } [Fact] - public async Task AfterRefInInvocation_TypeAndVariable() - { - var markup = """ + public Task AfterRefInInvocation_TypeAndVariable() + => VerifyExpectedItemsAsync(""" using System; class C { @@ -2728,17 +2502,14 @@ void M(ref String parameter) M(ref $$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("String"), ItemExpectation.Exists("parameter") ]); - } [Fact] - public async Task AfterOutInInvocation_TypeAndVariable() - { - var markup = """ + public Task AfterOutInInvocation_TypeAndVariable() + => VerifyExpectedItemsAsync(""" using System; class C { @@ -2747,17 +2518,14 @@ void M(out String parameter) M(out $$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("String"), ItemExpectation.Exists("parameter") ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24326")] - public async Task AfterInInInvocation_TypeAndVariable() - { - var markup = """ + public Task AfterInInInvocation_TypeAndVariable() + => VerifyExpectedItemsAsync(""" using System; class C { @@ -2766,17 +2534,14 @@ void M(in String parameter) M(in $$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("String"), ItemExpectation.Exists("parameter") ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25569")] - public async Task AfterRefExpression_TypeAndVariable() - { - var markup = """ + public Task AfterRefExpression_TypeAndVariable() + => VerifyExpectedItemsAsync(""" using System; class C { @@ -2785,17 +2550,14 @@ void M(String parameter) ref var x = ref $$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("String"), ItemExpectation.Exists("parameter") ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25569")] - public async Task AfterRefInStatementContext_TypeOnly() - { - var markup = """ + public Task AfterRefInStatementContext_TypeOnly() + => VerifyExpectedItemsAsync(""" using System; class C { @@ -2804,17 +2566,14 @@ void M(String parameter) ref $$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("String"), ItemExpectation.Absent("parameter") ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25569")] - public async Task AfterRefReadonlyInStatementContext_TypeOnly() - { - var markup = """ + public Task AfterRefReadonlyInStatementContext_TypeOnly() + => VerifyExpectedItemsAsync(""" using System; class C { @@ -2823,17 +2582,14 @@ void M(String parameter) ref readonly $$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("String"), ItemExpectation.Absent("parameter") ]); - } [Fact] - public async Task AfterRefLocalDeclaration_TypeOnly() - { - var markup = """ + public Task AfterRefLocalDeclaration_TypeOnly() + => VerifyExpectedItemsAsync(""" using System; class C { @@ -2842,17 +2598,14 @@ void M(String parameter) ref $$ int local; } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("String"), ItemExpectation.Absent("parameter") ]); - } [Fact] - public async Task AfterRefReadonlyLocalDeclaration_TypeOnly() - { - var markup = """ + public Task AfterRefReadonlyLocalDeclaration_TypeOnly() + => VerifyExpectedItemsAsync(""" using System; class C { @@ -2861,17 +2614,14 @@ void M(String parameter) ref readonly $$ int local; } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("String"), ItemExpectation.Absent("parameter") ]); - } [Fact] - public async Task AfterRefLocalFunction_TypeOnly() - { - var markup = """ + public Task AfterRefLocalFunction_TypeOnly() + => VerifyExpectedItemsAsync(""" using System; class C { @@ -2880,17 +2630,14 @@ void M(String parameter) ref $$ int Function(); } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("String"), ItemExpectation.Absent("parameter") ]); - } [Fact] - public async Task AfterRefReadonlyLocalFunction_TypeOnly() - { - var markup = """ + public Task AfterRefReadonlyLocalFunction_TypeOnly() + => VerifyExpectedItemsAsync(""" using System; class C { @@ -2899,17 +2646,14 @@ void M(String parameter) ref readonly $$ int Function(); } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("String"), ItemExpectation.Absent("parameter") ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35178")] - public async Task RefStructMembersEmptyByDefault() - { - var markup = """ + public Task RefStructMembersEmptyByDefault() + => VerifyNoItemsExistAsync(""" ref struct Test {} class C { @@ -2919,14 +2663,11 @@ void M() test.$$ } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35178")] - public async Task RefStructMembersHasMethodIfItWasOverriden() - { - var markup = """ + public Task RefStructMembersHasMethodIfItWasOverriden() + => VerifyExpectedItemsAsync(""" ref struct Test { public override string ToString() => string.Empty; @@ -2939,19 +2680,16 @@ void M() test.$$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("ToString"), ItemExpectation.Absent("GetType"), ItemExpectation.Absent("Equals"), ItemExpectation.Absent("GetHashCode") ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35178")] - public async Task RefStructMembersHasMethodsForNameof() - { - var markup = """ + public Task RefStructMembersHasMethodsForNameof() + => VerifyExpectedItemsAsync(""" ref struct Test {} class C { @@ -2961,19 +2699,16 @@ void M() _ = nameof(test.$$); } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("ToString"), ItemExpectation.Exists("GetType"), ItemExpectation.Exists("Equals"), ItemExpectation.Exists("GetHashCode") ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53585")] - public async Task AfterStaticLocalFunction_TypeOnly() - { - var markup = """ + public Task AfterStaticLocalFunction_TypeOnly() + => VerifyExpectedItemsAsync(""" using System; class C { @@ -2982,12 +2717,10 @@ void M(String parameter) static $$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("String"), ItemExpectation.Absent("parameter") ]); - } [Theory] [WorkItem("https://github.com/dotnet/roslyn/issues/53585")] @@ -2999,9 +2732,8 @@ await VerifyExpectedItemsAsync(markup, [ [InlineData("unsafe static")] [InlineData("unsafe extern")] [InlineData("extern unsafe")] - public async Task AfterLocalFunction_TypeOnly(string keyword) - { - var markup = $$""" + public Task AfterLocalFunction_TypeOnly(string keyword) + => VerifyExpectedItemsAsync($$""" using System; class C { @@ -3010,12 +2742,10 @@ void M(String parameter) {{keyword}} $$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("String"), ItemExpectation.Absent("parameter") ]); - } [Theory] [WorkItem("https://github.com/dotnet/roslyn/issues/60341")] @@ -3025,9 +2755,8 @@ await VerifyExpectedItemsAsync(markup, [ [InlineData("async unsafe")] [InlineData("unsafe async")] [InlineData("extern unsafe async static")] - public async Task AfterLocalFunction_TypeOnly_Async(string keyword) - { - var markup = $$""" + public Task AfterLocalFunction_TypeOnly_Async(string keyword) + => VerifyExpectedItemsAsync($$""" using System; class C { @@ -3036,17 +2765,14 @@ void M(String parameter) {{keyword}} $$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("String"), ItemExpectation.Absent("parameter") ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] - public async Task AfterAsyncLocalFunctionWithTwoAsyncs() - { - var markup = """ + public Task AfterAsyncLocalFunctionWithTwoAsyncs() + => VerifyExpectedItemsAsync(""" using System; class C { @@ -3055,12 +2781,10 @@ void M(string parameter) async async $$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("String"), ItemExpectation.Absent("parameter") ]); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/53585")] [InlineData("void")] @@ -3070,9 +2794,8 @@ await VerifyExpectedItemsAsync(markup, [ [InlineData("async void")] [InlineData("async System.Threading.Tasks.Task")] [InlineData("int Function")] - public async Task NotAfterReturnTypeInLocalFunction(string returnType) - { - var markup = $$""" + public Task NotAfterReturnTypeInLocalFunction(string returnType) + => VerifyExpectedItemsAsync($$""" using System; class C { @@ -3081,51 +2804,42 @@ void M(String parameter) static {{returnType}} $$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("String"), ItemExpectation.Absent("parameter") ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25569")] - public async Task AfterRefInMemberContext_TypeOnly() - { - var markup = """ + public Task AfterRefInMemberContext_TypeOnly() + => VerifyExpectedItemsAsync(""" using System; class C { String field; ref $$ } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("String"), ItemExpectation.Absent("field") ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25569")] - public async Task AfterRefReadonlyInMemberContext_TypeOnly() - { - var markup = """ + public Task AfterRefReadonlyInMemberContext_TypeOnly() + => VerifyExpectedItemsAsync(""" using System; class C { String field; ref readonly $$ } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("String"), ItemExpectation.Absent("field") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] - public async Task NestedType1() - { - var markup = """ + public Task NestedType1() + => VerifyExpectedItemsAsync(""" class Q { $$ @@ -3134,17 +2848,14 @@ class R } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("Q"), ItemExpectation.Exists("R") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] - public async Task NestedType2() - { - var markup = """ + public Task NestedType2() + => VerifyExpectedItemsAsync(""" class Q { class R @@ -3152,17 +2863,14 @@ class R $$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("Q"), ItemExpectation.Exists("R") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] - public async Task NestedType3() - { - var markup = """ + public Task NestedType3() + => VerifyExpectedItemsAsync(""" class Q { class R @@ -3170,12 +2878,10 @@ class R } $$ } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("Q"), ItemExpectation.Exists("R") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] public async Task NestedType4_Regular() @@ -3217,42 +2923,35 @@ class R } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] - public async Task NestedType5() - { - var markup = """ + public Task NestedType5() + => VerifyExpectedItemsAsync(""" class Q { class R { } $$ - """; // At EOF - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("Q"), ItemExpectation.Exists("R") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] - public async Task NestedType6() - { - var markup = """ + public Task NestedType6() + => VerifyExpectedItemsAsync(""" class Q { class R { $$ - """; // At EOF - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("Q"), ItemExpectation.Exists("R") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540574")] - public async Task AmbiguityBetweenTypeAndLocal() - { - var markup = """ + public Task AmbiguityBetweenTypeAndLocal() + => VerifyItemExistsAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -3265,15 +2964,11 @@ public void goo() { List ml = new List(); } } - """; - - await VerifyItemExistsAsync(markup, "CompareTo"); - } + """, "CompareTo"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21596")] - public async Task AmbiguityBetweenExpressionAndLocalFunctionReturnType() - { - var markup = """ + public Task AmbiguityBetweenExpressionAndLocalFunctionReturnType() + => VerifyItemExistsAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -3307,54 +3002,38 @@ public async Task Test2() return true; } } - """; - - await VerifyItemExistsAsync(markup, "Add"); - } + """, "Add"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540750")] - public async Task CompletionAfterNewInScript() - { - var markup = """ + public Task CompletionAfterNewInScript() + => VerifyItemExistsAsync(""" using System; new $$ - """; - - await VerifyItemExistsAsync(markup, "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); - } + """, "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540933")] - public async Task ExtensionMethodsInScript() - { - var markup = """ + public Task ExtensionMethodsInScript() + => VerifyItemExistsAsync(""" using System.Linq; var a = new int[] { 1, 2 }; a.$$ - """; - - await VerifyItemExistsAsync(markup, "ElementAt", displayTextSuffix: "<>", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); - } + """, "ElementAt", displayTextSuffix: "<>", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541019")] - public async Task ExpressionsInForLoopInitializer() - { - var markup = """ + public Task ExpressionsInForLoopInitializer() + => VerifyItemExistsAsync(""" public class C { public void M() { int count = 0; for ($$ - """; - - await VerifyItemExistsAsync(markup, "count"); - } + """, "count"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541108")] - public async Task AfterLambdaExpression1() - { - var markup = """ + public Task AfterLambdaExpression1() + => VerifyItemIsAbsentAsync(""" public class C { public void M() @@ -3362,15 +3041,11 @@ public void M() System.Func f = arg => { arg = 2; return arg; }.$$ } } - """; - - await VerifyItemIsAbsentAsync(markup, "ToString"); - } + """, "ToString"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541108")] - public async Task AfterLambdaExpression2() - { - var markup = """ + public Task AfterLambdaExpression2() + => VerifyExpectedItemsAsync(""" public class C { public void M() @@ -3378,29 +3053,21 @@ public void M() ((System.Func)(arg => { arg = 2; return arg; })).$$ } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("ToString"), ItemExpectation.Exists("Invoke") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541216")] - public async Task InMultiLineCommentAtEndOfFile() - { - var markup = """ + public Task InMultiLineCommentAtEndOfFile() + => VerifyItemIsAbsentAsync(""" using System; /*$$ - """; - - await VerifyItemIsAbsentAsync(markup, "Console", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); - } + """, "Console", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541218")] - public async Task TypeParametersAtEndOfFile() - { - var markup = """ + public Task TypeParametersAtEndOfFile() + => VerifyItemExistsAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -3416,15 +3083,11 @@ static void F(T t, U u) public static void F(T t) { Outer<$$ - """; - - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")] - public async Task LabelInCaseSwitchAbsentForCase() - { - var markup = """ + public Task LabelInCaseSwitchAbsentForCase() + => VerifyItemIsAbsentAsync(""" class Program { static void Main() @@ -3434,15 +3097,11 @@ static void Main() { case 0: goto $$ - """; - - await VerifyItemIsAbsentAsync(markup, "case 0:"); - } + """, "case 0:"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")] - public async Task LabelInCaseSwitchAbsentForDefaultWhenAbsent() - { - var markup = """ + public Task LabelInCaseSwitchAbsentForDefaultWhenAbsent() + => VerifyItemIsAbsentAsync(""" class Program { static void Main() @@ -3452,15 +3111,11 @@ static void Main() { case 0: goto $$ - """; - - await VerifyItemIsAbsentAsync(markup, "default:"); - } + """, "default:"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")] - public async Task LabelInCaseSwitchPresentForDefault() - { - var markup = """ + public Task LabelInCaseSwitchPresentForDefault() + => VerifyItemExistsAsync(""" class Program { static void Main() @@ -3470,15 +3125,11 @@ static void Main() { default: goto $$ - """; - - await VerifyItemExistsAsync(markup, "default"); - } + """, "default"); [Fact] - public async Task LabelAfterGoto1() - { - var markup = """ + public Task LabelAfterGoto1() + => VerifyItemExistsAsync(""" class Program { static void Main() @@ -3486,15 +3137,11 @@ static void Main() Goo: int Goo; goto $$ - """; - - await VerifyItemExistsAsync(markup, "Goo"); - } + """, "Goo"); [Fact] - public async Task LabelAfterGoto2() - { - var markup = """ + public Task LabelAfterGoto2() + => VerifyItemIsAbsentAsync(""" class Program { static void Main() @@ -3502,176 +3149,129 @@ static void Main() Goo: int Goo; goto Goo $$ - """; - - await VerifyItemIsAbsentAsync(markup, "Goo"); - } + """, "Goo"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] - public async Task AttributeName() - { - var markup = """ + public Task AttributeName() + => VerifyExpectedItemsAsync(""" using System; [$$ - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("CLSCompliant"), ItemExpectation.Absent("CLSCompliantAttribute") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] - public async Task AttributeNameAfterSpecifier() - { - var markup = """ + public Task AttributeNameAfterSpecifier() + => VerifyExpectedItemsAsync(""" using System; [assembly:$$ - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("CLSCompliant"), ItemExpectation.Absent("CLSCompliantAttribute") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] - public async Task AttributeNameInAttributeList() - { - var markup = """ + public Task AttributeNameInAttributeList() + => VerifyExpectedItemsAsync(""" using System; [CLSCompliant, $$ - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("CLSCompliant"), ItemExpectation.Absent("CLSCompliantAttribute") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] - public async Task AttributeNameBeforeClass() - { - var markup = """ + public Task AttributeNameBeforeClass() + => VerifyExpectedItemsAsync(""" using System; [$$ class C { } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("CLSCompliant"), ItemExpectation.Absent("CLSCompliantAttribute") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] - public async Task AttributeNameAfterSpecifierBeforeClass() - { - var markup = """ + public Task AttributeNameAfterSpecifierBeforeClass() + => VerifyExpectedItemsAsync(""" using System; [assembly:$$ class C { } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("CLSCompliant"), ItemExpectation.Absent("CLSCompliantAttribute") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] - public async Task AttributeNameInAttributeArgumentList() - { - var markup = """ + public Task AttributeNameInAttributeArgumentList() + => VerifyExpectedItemsAsync(""" using System; [CLSCompliant($$ class C { } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("CLSCompliantAttribute"), ItemExpectation.Absent("CLSCompliant") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] - public async Task AttributeNameInsideClass() - { - var markup = """ + public Task AttributeNameInsideClass() + => VerifyExpectedItemsAsync(""" using System; class C { $$ } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("CLSCompliantAttribute"), ItemExpectation.Absent("CLSCompliant") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")] - public async Task NamespaceAliasInAttributeName1() - { - var markup = """ + public Task NamespaceAliasInAttributeName1() + => VerifyItemExistsAsync(""" using Alias = System; [$$ class C { } - """; - - await VerifyItemExistsAsync(markup, "Alias"); - } + """, "Alias"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")] - public async Task NamespaceAliasInAttributeName2() - { - var markup = """ + public Task NamespaceAliasInAttributeName2() + => VerifyItemIsAbsentAsync(""" using Alias = Goo; namespace Goo { } [$$ class C { } - """; - - await VerifyItemIsAbsentAsync(markup, "Alias"); - } + """, "Alias"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")] - public async Task NamespaceAliasInAttributeName3() - { - var markup = """ + public Task NamespaceAliasInAttributeName3() + => VerifyItemExistsAsync(""" using Alias = Goo; namespace Goo { class A : System.Attribute { } } [$$ class C { } - """; - - await VerifyItemExistsAsync(markup, "Alias"); - } + """, "Alias"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] - public async Task AttributeNameAfterNamespace() - { - var markup = """ + public Task AttributeNameAfterNamespace() + => VerifyExpectedItemsAsync(""" namespace Test { class MyAttribute : System.Attribute { } [Test.$$ class Program { } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("My"), ItemExpectation.Absent("MyAttribute") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] - public async Task AttributeNameAfterNamespace2() - { - var markup = """ + public Task AttributeNameAfterNamespace2() + => VerifyExpectedItemsAsync(""" namespace Test { namespace Two @@ -3681,53 +3281,44 @@ class MyAttribute : System.Attribute { } class Program { } } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("My"), ItemExpectation.Absent("MyAttribute") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] - public async Task AttributeNameWhenSuffixlessFormIsKeyword() - { - var markup = """ + public Task AttributeNameWhenSuffixlessFormIsKeyword() + => VerifyExpectedItemsAsync(""" namespace Test { class namespaceAttribute : System.Attribute { } [$$ class Program { } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("namespaceAttribute"), ItemExpectation.Absent("namespace"), ItemExpectation.Absent("@namespace") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] - public async Task AttributeNameAfterNamespaceWhenSuffixlessFormIsKeyword() - { - var markup = """ + public Task AttributeNameAfterNamespaceWhenSuffixlessFormIsKeyword() + => VerifyExpectedItemsAsync(""" namespace Test { class namespaceAttribute : System.Attribute { } [Test.$$ class Program { } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("namespaceAttribute"), ItemExpectation.Absent("namespace"), ItemExpectation.Absent("@namespace") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")] - public async Task KeywordsUsedAsLocals() - { - var markup = """ + public Task KeywordsUsedAsLocals() + => VerifyExpectedItemsAsync(""" class C { void M() @@ -3738,9 +3329,7 @@ void M() Console.Write($$ } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ // preprocessor keyword ItemExpectation.Exists("error"), ItemExpectation.Absent("@error"), @@ -3753,12 +3342,10 @@ await VerifyExpectedItemsAsync(markup, [ ItemExpectation.Exists("@int"), ItemExpectation.Absent("int") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")] - public async Task QueryContextualKeywords1() - { - var markup = """ + public Task QueryContextualKeywords1() + => VerifyExpectedItemsAsync(""" class C { void M() @@ -3767,18 +3354,14 @@ void M() var r = from x in $$ } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("@from"), ItemExpectation.Absent("from") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")] - public async Task QueryContextualKeywords2() - { - var markup = """ + public Task QueryContextualKeywords2() + => VerifyExpectedItemsAsync(""" class C { void M() @@ -3789,20 +3372,16 @@ void M() select @from; } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("@from"), ItemExpectation.Absent("from"), ItemExpectation.Exists("@where"), ItemExpectation.Absent("where") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")] - public async Task QueryContextualKeywords3() - { - var markup = """ + public Task QueryContextualKeywords3() + => VerifyExpectedItemsAsync(""" class C { void M() @@ -3813,53 +3392,43 @@ void M() select $$; } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("@from"), ItemExpectation.Absent("from"), ItemExpectation.Exists("@where"), ItemExpectation.Absent("where") ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] - public async Task AttributeNameAfterGlobalAlias() - { - var markup = """ + public Task AttributeNameAfterGlobalAlias() + => VerifyExpectedItemsAsync( + """ class MyAttribute : System.Attribute { } [global::$$ class Program { } - """; - await VerifyExpectedItemsAsync( - markup, [ + """, [ ItemExpectation.Exists("My"), ItemExpectation.Absent("MyAttribute") ], SourceCodeKind.Regular); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] - public async Task AttributeNameAfterGlobalAliasWhenSuffixlessFormIsKeyword() - { - var markup = """ + public Task AttributeNameAfterGlobalAliasWhenSuffixlessFormIsKeyword() + => VerifyExpectedItemsAsync( + """ class namespaceAttribute : System.Attribute { } [global::$$ class Program { } - """; - await VerifyExpectedItemsAsync( - markup, [ + """, [ ItemExpectation.Exists("namespaceAttribute"), ItemExpectation.Absent("namespace"), ItemExpectation.Absent("@namespace") ], SourceCodeKind.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25589")] - public async Task AttributeSearch_NamespaceWithNestedAttribute1() - { - var markup = """ + public Task AttributeSearch_NamespaceWithNestedAttribute1() + => VerifyItemExistsAsync(""" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } @@ -3867,14 +3436,11 @@ namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [$$] - """; - await VerifyItemExistsAsync(markup, "Namespace1"); - } + """, "Namespace1"); [Fact] - public async Task AttributeSearch_NamespaceWithNestedAttribute2() - { - var markup = """ + public Task AttributeSearch_NamespaceWithNestedAttribute2() + => VerifyExpectedItemsAsync(""" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } @@ -3882,17 +3448,14 @@ namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [Namespace1.$$] - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("Namespace2"), ItemExpectation.Exists("Namespace3"), ]); - } [Fact] - public async Task AttributeSearch_NamespaceWithNestedAttribute3() - { - var markup = """ + public Task AttributeSearch_NamespaceWithNestedAttribute3() + => VerifyItemExistsAsync(""" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } @@ -3900,14 +3463,11 @@ namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [Namespace1.Namespace3.$$] - """; - await VerifyItemExistsAsync(markup, "Namespace4"); - } + """, "Namespace4"); [Fact] - public async Task AttributeSearch_NamespaceWithNestedAttribute4() - { - var markup = """ + public Task AttributeSearch_NamespaceWithNestedAttribute4() + => VerifyItemExistsAsync(""" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } @@ -3915,14 +3475,11 @@ namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [Namespace1.Namespace3.Namespace4.$$] - """; - await VerifyItemExistsAsync(markup, "Custom"); - } + """, "Custom"); [Fact] - public async Task AttributeSearch_NamespaceWithNestedAttribute_NamespaceAlias() - { - var markup = """ + public Task AttributeSearch_NamespaceWithNestedAttribute_NamespaceAlias() + => VerifyExpectedItemsAsync(""" using Namespace1Alias = Namespace1; using Namespace2Alias = Namespace1.Namespace2; using Namespace3Alias = Namespace1.Namespace3; @@ -3935,19 +3492,16 @@ namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [$$] - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("Namespace1Alias"), ItemExpectation.Absent("Namespace2Alias"), ItemExpectation.Exists("Namespace3Alias"), ItemExpectation.Exists("Namespace4Alias"), ]); - } [Fact] - public async Task AttributeSearch_NamespaceWithoutNestedAttribute() - { - var markup = """ + public Task AttributeSearch_NamespaceWithoutNestedAttribute() + => VerifyItemIsAbsentAsync(""" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } @@ -3955,14 +3509,11 @@ namespace Namespace3.Namespace4 { class NonAttribute : System.NonAttribute { } } } [$$] - """; - await VerifyItemIsAbsentAsync(markup, "Namespace1"); - } + """, "Namespace1"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542230")] - public async Task RangeVariableInQuerySelect() - { - var markup = """ + public Task RangeVariableInQuerySelect() + => VerifyItemExistsAsync(""" using System.Linq; class P { @@ -3971,15 +3522,11 @@ void M() var src = new string[] { "Goo", "Bar" }; var q = from x in src select x.$$ - """; - - await VerifyItemExistsAsync(markup, "Length"); - } + """, "Length"); [Fact] - public async Task ConstantsInIsExpression() - { - var markup = """ + public Task ConstantsInIsExpression() + => VerifyItemExistsAsync(""" class C { public const int MAX_SIZE = 10; @@ -3987,15 +3534,11 @@ void M() { int i = 10; if (i is $$ int - """; // 'int' to force this to be parsed as an IsExpression rather than IsPatternExpression - - await VerifyItemExistsAsync(markup, "MAX_SIZE"); - } + """, "MAX_SIZE"); [Fact] - public async Task ConstantsInIsPatternExpression() - { - var markup = """ + public Task ConstantsInIsPatternExpression() + => VerifyItemExistsAsync(""" class C { public const int MAX_SIZE = 10; @@ -4003,15 +3546,11 @@ void M() { int i = 10; if (i is $$ 1 - """; - - await VerifyItemExistsAsync(markup, "MAX_SIZE"); - } + """, "MAX_SIZE"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] - public async Task ConstantsInSwitchCase() - { - var markup = """ + public Task ConstantsInSwitchCase() + => VerifyItemExistsAsync(""" class C { public const int MAX_SIZE = 10; @@ -4021,15 +3560,11 @@ void M() switch (i) { case $$ - """; - - await VerifyItemExistsAsync(markup, "MAX_SIZE"); - } + """, "MAX_SIZE"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25084#issuecomment-370148553")] - public async Task ConstantsInSwitchPatternCase() - { - var markup = """ + public Task ConstantsInSwitchPatternCase() + => VerifyItemExistsAsync(""" class C { public const int MAX_SIZE = 10; @@ -4039,15 +3574,11 @@ void M() switch (i) { case $$ when - """; - - await VerifyItemExistsAsync(markup, "MAX_SIZE"); - } + """, "MAX_SIZE"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] - public async Task ConstantsInSwitchGotoCase() - { - var markup = """ + public Task ConstantsInSwitchGotoCase() + => VerifyItemExistsAsync(""" class C { public const int MAX_SIZE = 10; @@ -4060,138 +3591,98 @@ void M() break; case GOO: goto case $$ - """; - - await VerifyItemExistsAsync(markup, "MAX_SIZE"); - } + """, "MAX_SIZE"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] - public async Task ConstantsInEnumMember() - { - var markup = """ + public Task ConstantsInEnumMember() + => VerifyItemExistsAsync(""" class C { public const int GOO = 0; enum E { A = $$ - """; - - await VerifyItemExistsAsync(markup, "GOO"); - } + """, "GOO"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] - public async Task ConstantsInAttribute1() - { - var markup = """ + public Task ConstantsInAttribute1() + => VerifyItemExistsAsync(""" class C { public const int GOO = 0; [System.AttributeUsage($$ - """; - - await VerifyItemExistsAsync(markup, "GOO"); - } + """, "GOO"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] - public async Task ConstantsInAttribute2() - { - var markup = """ + public Task ConstantsInAttribute2() + => VerifyItemExistsAsync(""" class C { public const int GOO = 0; [System.AttributeUsage(GOO, $$ - """; - - await VerifyItemExistsAsync(markup, "GOO"); - } + """, "GOO"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] - public async Task ConstantsInAttribute3() - { - var markup = """ + public Task ConstantsInAttribute3() + => VerifyItemExistsAsync(""" class C { public const int GOO = 0; [System.AttributeUsage(validOn: $$ - """; - - await VerifyItemExistsAsync(markup, "GOO"); - } + """, "GOO"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] - public async Task ConstantsInAttribute4() - { - var markup = """ + public Task ConstantsInAttribute4() + => VerifyItemExistsAsync(""" class C { public const int GOO = 0; [System.AttributeUsage(AllowMultiple = $$ - """; - - await VerifyItemExistsAsync(markup, "GOO"); - } + """, "GOO"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] - public async Task ConstantsInParameterDefaultValue() - { - var markup = """ + public Task ConstantsInParameterDefaultValue() + => VerifyItemExistsAsync(""" class C { public const int GOO = 0; void M(int x = $$ - """; - - await VerifyItemExistsAsync(markup, "GOO"); - } + """, "GOO"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] - public async Task ConstantsInConstField() - { - var markup = """ + public Task ConstantsInConstField() + => VerifyItemExistsAsync(""" class C { public const int GOO = 0; const int BAR = $$ - """; - - await VerifyItemExistsAsync(markup, "GOO"); - } + """, "GOO"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] - public async Task ConstantsInConstLocal() - { - var markup = """ + public Task ConstantsInConstLocal() + => VerifyItemExistsAsync(""" class C { public const int GOO = 0; void M() { const int BAR = $$ - """; - - await VerifyItemExistsAsync(markup, "GOO"); - } + """, "GOO"); [Fact] - public async Task DescriptionWith1Overload() - { - var markup = """ + public Task DescriptionWith1Overload() + => VerifyItemExistsAsync(""" class C { void M(int i) { } void M() { $$ - """; - - await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 1 {FeaturesResources.overload})"); - } + """, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 1 {FeaturesResources.overload})"); [Fact] - public async Task DescriptionWith2Overloads() - { - var markup = """ + public Task DescriptionWith2Overloads() + => VerifyItemExistsAsync(""" class C { void M(int i) { } @@ -4199,30 +3690,22 @@ void M(out int i) { } void M() { $$ - """; - - await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 2 {FeaturesResources.overloads_})"); - } + """, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 2 {FeaturesResources.overloads_})"); [Fact] - public async Task DescriptionWith1GenericOverload() - { - var markup = """ + public Task DescriptionWith1GenericOverload() + => VerifyItemExistsAsync(""" class C { void M(T i) { } void M() { $$ - """; - - await VerifyItemExistsAsync(markup, "M", displayTextSuffix: "<>", expectedDescriptionOrNull: $"void C.M(T i) (+ 1 {FeaturesResources.generic_overload})"); - } + """, "M", displayTextSuffix: "<>", expectedDescriptionOrNull: $"void C.M(T i) (+ 1 {FeaturesResources.generic_overload})"); [Fact] - public async Task DescriptionWith2GenericOverloads() - { - var markup = """ + public Task DescriptionWith2GenericOverloads() + => VerifyItemExistsAsync(""" class C { void M(int i) { } @@ -4230,95 +3713,68 @@ void M(out int i) { } void M() { $$ - """; - - await VerifyItemExistsAsync(markup, "M", displayTextSuffix: "<>", expectedDescriptionOrNull: $"void C.M(int i) (+ 2 {FeaturesResources.generic_overloads})"); - } + """, "M", displayTextSuffix: "<>", expectedDescriptionOrNull: $"void C.M(int i) (+ 2 {FeaturesResources.generic_overloads})"); [Fact] - public async Task DescriptionNamedGenericType() - { - var markup = """ + public Task DescriptionNamedGenericType() + => VerifyItemExistsAsync(""" class C { void M() { $$ - """; - - await VerifyItemExistsAsync(markup, "C", displayTextSuffix: "<>", expectedDescriptionOrNull: "class C"); - } + """, "C", displayTextSuffix: "<>", expectedDescriptionOrNull: "class C"); [Fact] - public async Task DescriptionParameter() - { - var markup = """ + public Task DescriptionParameter() + => VerifyItemExistsAsync(""" class C { void M(T goo) { $$ - """; - - await VerifyItemExistsAsync(markup, "goo", expectedDescriptionOrNull: $"({FeaturesResources.parameter}) T goo"); - } + """, "goo", expectedDescriptionOrNull: $"({FeaturesResources.parameter}) T goo"); [Fact] - public async Task DescriptionGenericTypeParameter() - { - var markup = """ + public Task DescriptionGenericTypeParameter() + => VerifyItemExistsAsync(""" class C { void M() { $$ - """; - - await VerifyItemExistsAsync(markup, "T", expectedDescriptionOrNull: $"T {FeaturesResources.in_} C"); - } + """, "T", expectedDescriptionOrNull: $"T {FeaturesResources.in_} C"); [Fact] - public async Task DescriptionAnonymousType() - { - var markup = """ + public Task DescriptionAnonymousType() + => VerifyItemExistsAsync(""" class C { void M() { var a = new { }; $$ - """; - - var expectedDescription = - $$""" + """, "a", $$""" ({{FeaturesResources.local_variable}}) 'a a {{FeaturesResources.Types_colon}} 'a {{FeaturesResources.is_}} new { } - """; - - await VerifyItemExistsAsync(markup, "a", expectedDescription); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543288")] - public async Task AfterNewInAnonymousType() - { - var markup = """ + public Task AfterNewInAnonymousType() + => VerifyItemExistsAsync(""" class Program { string field = 0; static void Main() { var an = new { new $$ }; } } - """; - - await VerifyItemExistsAsync(markup, "Program"); - } + """, "Program"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")] - public async Task NoInstanceFieldsInStaticMethod() - { - var markup = """ + public Task NoInstanceFieldsInStaticMethod() + => VerifyItemIsAbsentAsync(""" class C { int x = 0; @@ -4327,29 +3783,21 @@ static void M() $$ } } - """; - - await VerifyItemIsAbsentAsync(markup, "x"); - } + """, "x"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")] - public async Task NoInstanceFieldsInStaticFieldInitializer() - { - var markup = """ + public Task NoInstanceFieldsInStaticFieldInitializer() + => VerifyItemIsAbsentAsync(""" class C { int x = 0; static int y = $$ } - """; - - await VerifyItemIsAbsentAsync(markup, "x"); - } + """, "x"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")] - public async Task StaticFieldsInStaticMethod() - { - var markup = """ + public Task StaticFieldsInStaticMethod() + => VerifyItemExistsAsync(""" class C { static int x = 0; @@ -4358,29 +3806,21 @@ static void M() $$ } } - """; - - await VerifyItemExistsAsync(markup, "x"); - } + """, "x"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")] - public async Task StaticFieldsInStaticFieldInitializer() - { - var markup = """ + public Task StaticFieldsInStaticFieldInitializer() + => VerifyItemExistsAsync(""" class C { static int x = 0; static int y = $$ } - """; - - await VerifyItemExistsAsync(markup, "x"); - } + """, "x"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543680")] - public async Task NoInstanceFieldsFromOuterClassInInstanceMethod() - { - var markup = """ + public Task NoInstanceFieldsFromOuterClassInInstanceMethod() + => VerifyItemIsAbsentAsync(""" class outer { int i; @@ -4392,15 +3832,11 @@ void M() } } } - """; - - await VerifyItemIsAbsentAsync(markup, "i"); - } + """, "i"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543680")] - public async Task StaticFieldsFromOuterClassInInstanceMethod() - { - var markup = """ + public Task StaticFieldsFromOuterClassInInstanceMethod() + => VerifyItemExistsAsync(""" class outer { static int i; @@ -4412,15 +3848,11 @@ void M() } } } - """; - - await VerifyItemExistsAsync(markup, "i"); - } + """, "i"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543104")] - public async Task OnlyEnumMembersInEnumMemberAccess() - { - var markup = """ + public Task OnlyEnumMembersInEnumMemberAccess() + => VerifyExpectedItemsAsync(""" class C { enum x {a,b,c} @@ -4429,20 +3861,16 @@ void M() x.$$ } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("a"), ItemExpectation.Exists("b"), ItemExpectation.Exists("c"), ItemExpectation.Absent("Equals"), ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543104")] - public async Task NoEnumMembersInEnumLocalAccess() - { - var markup = """ + public Task NoEnumMembersInEnumLocalAccess() + => VerifyExpectedItemsAsync(""" class C { enum x {a,b,c} @@ -4452,20 +3880,16 @@ void M() y.$$ } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("a"), ItemExpectation.Absent("b"), ItemExpectation.Absent("c"), ItemExpectation.Exists("Equals"), ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529138")] - public async Task AfterLambdaParameterDot() - { - var markup = """ + public Task AfterLambdaParameterDot() + => VerifyItemExistsAsync(""" using System; using System.Linq; class A @@ -4480,10 +3904,7 @@ static void Main(string[] args) new A().E += ss => ss.$$ } } - """; - - await VerifyItemExistsAsync(markup, "Substring"); - } + """, "Substring"); [Fact, WorkItem(61343, "https://github.com/dotnet/roslyn/issues/61343")] public async Task LambdaParameterMemberAccessOverloads() @@ -4509,174 +3930,145 @@ void Test() } [Fact] - public async Task ValueNotAtRoot_Interactive() - { - await VerifyItemIsAbsentAsync( + public Task ValueNotAtRoot_Interactive() + => VerifyItemIsAbsentAsync( @"$$", "value", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); - } [Fact] - public async Task ValueNotAfterClass_Interactive() - { - await VerifyItemIsAbsentAsync( + public Task ValueNotAfterClass_Interactive() + => VerifyItemIsAbsentAsync( """ class C { } $$ """, -"value", -expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); - } + "value", + expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); [Fact] - public async Task ValueNotAfterGlobalStatement_Interactive() - { - await VerifyItemIsAbsentAsync( + public Task ValueNotAfterGlobalStatement_Interactive() + => VerifyItemIsAbsentAsync( """ System.Console.WriteLine(); $$ """, -"value", -expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); - } + "value", + expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); [Fact] - public async Task ValueNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyItemIsAbsentAsync( + public Task ValueNotAfterGlobalVariableDeclaration_Interactive() + => VerifyItemIsAbsentAsync( """ int i = 0; $$ """, -"value", -expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); - } + "value", + expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); [Fact] - public async Task ValueNotInUsingAlias() - { - await VerifyItemIsAbsentAsync( + public Task ValueNotInUsingAlias() + => VerifyItemIsAbsentAsync( @"using Goo = $$", "value"); - } [Fact] - public async Task ValueNotInEmptyStatement() - { - await VerifyItemIsAbsentAsync(AddInsideMethod( + public Task ValueNotInEmptyStatement() + => VerifyItemIsAbsentAsync(AddInsideMethod( @"$$"), "value"); - } [Fact] - public async Task ValueInsideSetter() - { - await VerifyItemExistsAsync( + public Task ValueInsideSetter() + => VerifyItemExistsAsync( """ class C { int Goo { set { $$ """, -"value"); - } + "value"); [Fact] - public async Task ValueInsideAdder() - { - await VerifyItemExistsAsync( + public Task ValueInsideAdder() + => VerifyItemExistsAsync( """ class C { event int Goo { add { $$ """, -"value"); - } + "value"); [Fact] - public async Task ValueInsideRemover() - { - await VerifyItemExistsAsync( + public Task ValueInsideRemover() + => VerifyItemExistsAsync( """ class C { event int Goo { remove { $$ """, -"value"); - } + "value"); [Fact] - public async Task ValueNotAfterDot() - { - await VerifyItemIsAbsentAsync( + public Task ValueNotAfterDot() + => VerifyItemIsAbsentAsync( """ class C { int Goo { set { this.$$ """, -"value"); - } + "value"); [Fact] - public async Task ValueNotAfterArrow() - { - await VerifyItemIsAbsentAsync( + public Task ValueNotAfterArrow() + => VerifyItemIsAbsentAsync( """ class C { int Goo { set { a->$$ """, -"value"); - } + "value"); [Fact] - public async Task ValueNotAfterColonColon() - { - await VerifyItemIsAbsentAsync( + public Task ValueNotAfterColonColon() + => VerifyItemIsAbsentAsync( """ class C { int Goo { set { a::$$ """, -"value"); - } + "value"); [Fact] - public async Task ValueNotInGetter() - { - await VerifyItemIsAbsentAsync( + public Task ValueNotInGetter() + => VerifyItemIsAbsentAsync( """ class C { int Goo { get { $$ """, -"value"); - } + "value"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] - public async Task NotAfterNullableType() - { - await VerifyItemIsAbsentAsync( + public Task NotAfterNullableType() + => VerifyItemIsAbsentAsync( """ class C { void M() { int goo = 0; C? $$ """, -"goo"); - } + "goo"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] - public async Task NotAfterNullableTypeAlias() - { - await VerifyItemIsAbsentAsync( + public Task NotAfterNullableTypeAlias() + => VerifyItemIsAbsentAsync( """ using A = System.Int32; class C { @@ -4684,27 +4076,23 @@ void M() { int goo = 0; A? $$ """, -"goo"); - } + "goo"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] - public async Task NotAfterNullableTypeAndPartialIdentifier() - { - await VerifyItemIsAbsentAsync( + public Task NotAfterNullableTypeAndPartialIdentifier() + => VerifyItemIsAbsentAsync( """ class C { void M() { int goo = 0; C? f$$ """, -"goo"); - } + "goo"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] - public async Task AfterQuestionMarkInConditional() - { - await VerifyItemExistsAsync( + public Task AfterQuestionMarkInConditional() + => VerifyItemExistsAsync( """ class C { void M() { @@ -4712,13 +4100,11 @@ void M() { int goo = 0; b? $$ """, -"goo"); - } + "goo"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] - public async Task AfterQuestionMarkAndPartialIdentifierInConditional() - { - await VerifyItemExistsAsync( + public Task AfterQuestionMarkAndPartialIdentifierInConditional() + => VerifyItemExistsAsync( """ class C { void M() { @@ -4726,26 +4112,22 @@ void M() { int goo = 0; b? f$$ """, -"goo"); - } + "goo"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] - public async Task NotAfterPointerType() - { - await VerifyItemIsAbsentAsync( + public Task NotAfterPointerType() + => VerifyItemIsAbsentAsync( """ class C { void M() { int goo = 0; C* $$ """, -"goo"); - } + "goo"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] - public async Task NotAfterPointerTypeAlias() - { - await VerifyItemIsAbsentAsync( + public Task NotAfterPointerTypeAlias() + => VerifyItemIsAbsentAsync( """ using A = System.Int32; class C { @@ -4753,26 +4135,22 @@ void M() { int goo = 0; A* $$ """, -"goo"); - } + "goo"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] - public async Task NotAfterPointerTypeAndPartialIdentifier() - { - await VerifyItemIsAbsentAsync( + public Task NotAfterPointerTypeAndPartialIdentifier() + => VerifyItemIsAbsentAsync( """ class C { void M() { int goo = 0; C* f$$ """, -"goo"); - } + "goo"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] - public async Task AfterAsteriskInMultiplication() - { - await VerifyItemExistsAsync( + public Task AfterAsteriskInMultiplication() + => VerifyItemExistsAsync( """ class C { void M() { @@ -4780,13 +4158,11 @@ void M() { int goo = 0; i* $$ """, -"goo"); - } + "goo"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] - public async Task AfterAsteriskAndPartialIdentifierInMultiplication() - { - await VerifyItemExistsAsync( + public Task AfterAsteriskAndPartialIdentifierInMultiplication() + => VerifyItemExistsAsync( """ class C { void M() { @@ -4794,52 +4170,44 @@ void M() { int goo = 0; i* f$$ """, -"goo"); - } + "goo"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")] - public async Task AfterEventFieldDeclaredInSameType() - { - await VerifyItemExistsAsync( + public Task AfterEventFieldDeclaredInSameType() + => VerifyItemExistsAsync( """ class C { public event System.EventHandler E; void M() { E.$$ """, -"Invoke"); - } + "Invoke"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")] - public async Task NotAfterFullEventDeclaredInSameType() - { - await VerifyItemIsAbsentAsync( + public Task NotAfterFullEventDeclaredInSameType() + => VerifyItemIsAbsentAsync( """ class C { public event System.EventHandler E { add { } remove { } } void M() { E.$$ """, -"Invoke"); - } + "Invoke"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")] - public async Task NotAfterEventDeclaredInDifferentType() - { - await VerifyItemIsAbsentAsync( + public Task NotAfterEventDeclaredInDifferentType() + => VerifyItemIsAbsentAsync( """ class C { void M() { System.Console.CancelKeyPress.$$ """, -"Invoke"); - } + "Invoke"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task NotInObjectInitializerMemberContext() - { - await VerifyItemIsAbsentAsync(""" + public Task NotInObjectInitializerMemberContext() + => VerifyItemIsAbsentAsync(""" class C { public int x, y; @@ -4848,13 +4216,11 @@ void M() var c = new C { x = 2, y = 3, $$ """, "x"); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task AfterPointerMemberAccess() - { - await VerifyItemExistsAsync(""" + public Task AfterPointerMemberAccess() + => VerifyItemExistsAsync(""" struct MyStruct { public int MyField; @@ -4870,7 +4236,6 @@ static unsafe void Main(string[] args) }} """, "MyField"); - } // After @ both X and XAttribute are legal. We think this is an edge case in the language and // are not fixing the bug 11931. This test captures that XAttribute doesn't show up indeed. @@ -4896,9 +4261,8 @@ class Class3 { } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544928")] - public async Task InForLoopIncrementor1() - { - await VerifyItemExistsAsync(""" + public Task InForLoopIncrementor1() + => VerifyItemExistsAsync(""" using System; class Program @@ -4909,13 +4273,11 @@ static void Main() } } """, "Console"); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544928")] - public async Task InForLoopIncrementor2() - { - await VerifyItemExistsAsync(""" + public Task InForLoopIncrementor2() + => VerifyItemExistsAsync(""" using System; class Program @@ -4926,13 +4288,11 @@ static void Main() } } """, "Console"); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544931")] - public async Task InForLoopInitializer1() - { - await VerifyItemExistsAsync(""" + public Task InForLoopInitializer1() + => VerifyItemExistsAsync(""" using System; class Program @@ -4943,13 +4303,11 @@ static void Main() } } """, "Console"); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544931")] - public async Task InForLoopInitializer2() - { - await VerifyItemExistsAsync(""" + public Task InForLoopInitializer2() + => VerifyItemExistsAsync(""" using System; class Program @@ -4960,13 +4318,10 @@ static void Main() } } """, "Console"); - } [Fact, WorkItem(10572, "DevDiv_Projects/Roslyn")] - public async Task LocalVariableInItsDeclaration() - { - // "int goo = goo = 1" is a legal declaration - await VerifyItemExistsAsync(""" + public Task LocalVariableInItsDeclaration() + => VerifyItemExistsAsync(""" class Program { void M() @@ -4975,13 +4330,10 @@ void M() } } """, "goo"); - } [Fact, WorkItem(10572, "DevDiv_Projects/Roslyn")] - public async Task LocalVariableInItsDeclarator() - { - // "int bar = bar = 1" is legal in a declarator - await VerifyItemExistsAsync(""" + public Task LocalVariableInItsDeclarator() + => VerifyItemExistsAsync(""" class Program { void M() @@ -4990,12 +4342,10 @@ void M() } } """, "bar"); - } [Fact, WorkItem(10572, "DevDiv_Projects/Roslyn")] - public async Task LocalVariableNotBeforeDeclaration() - { - await VerifyItemIsAbsentAsync(""" + public Task LocalVariableNotBeforeDeclaration() + => VerifyItemIsAbsentAsync(""" class Program { void M() @@ -5005,12 +4355,10 @@ void M() } } """, "goo"); - } [Fact, WorkItem(10572, "DevDiv_Projects/Roslyn")] - public async Task LocalVariableNotBeforeDeclarator() - { - await VerifyItemIsAbsentAsync(""" + public Task LocalVariableNotBeforeDeclarator() + => VerifyItemIsAbsentAsync(""" class Program { void M() @@ -5019,12 +4367,10 @@ void M() } } """, "bar"); - } [Fact, WorkItem(10572, "DevDiv_Projects/Roslyn")] - public async Task LocalVariableAfterDeclarator() - { - await VerifyItemExistsAsync(""" + public Task LocalVariableAfterDeclarator() + => VerifyItemExistsAsync(""" class Program { void M() @@ -5033,12 +4379,10 @@ void M() } } """, "goo"); - } [Fact, WorkItem(10572, "DevDiv_Projects/Roslyn")] - public async Task LocalVariableAsOutArgumentInInitializerExpression() - { - await VerifyItemExistsAsync(""" + public Task LocalVariableAsOutArgumentInInitializerExpression() + => VerifyItemExistsAsync(""" class Program { void M() @@ -5052,7 +4396,6 @@ int Bar(out int x) } } """, "goo"); - } [Fact, WorkItem(7336, "DevDiv_Projects/Roslyn")] public async Task EditorBrowsable_Method_BrowsableStateAlways() @@ -7987,9 +7330,8 @@ await VerifyItemInEditorBrowsableContextsAsync( } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545557")] - public async Task TestColorColor1() - { - var markup = """ + public Task TestColorColor1() + => VerifyExpectedItemsAsync(""" class A { static void Goo() { } @@ -8001,17 +7343,14 @@ static void Main() A.$$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("Goo"), ItemExpectation.Exists("Bar"), ]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")] - public async Task TestLaterLocalHidesType1() - { - var markup = """ + public Task TestLaterLocalHidesType1() + => VerifyItemExistsAsync(""" using System; class C { @@ -8021,15 +7360,11 @@ public static void Main() Console.WriteLine(); } } - """; - - await VerifyItemExistsAsync(markup, "Console"); - } + """, "Console"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")] - public async Task TestLaterLocalHidesType2() - { - var markup = """ + public Task TestLaterLocalHidesType2() + => VerifyItemExistsAsync(""" using System; class C { @@ -8039,10 +7374,7 @@ public static void Main() Console.WriteLine(); } } - """; - - await VerifyItemExistsAsync(markup, "Console"); - } + """, "Console"); [Fact] public async Task TestIndexedProperty() @@ -8099,9 +7431,8 @@ await VerifyItemInEditorBrowsableContextsAsync( } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546841")] - public async Task TestDeclarationAmbiguity() - { - var markup = """ + public Task TestDeclarationAmbiguity() + => VerifyItemExistsAsync(""" using System; class Program @@ -8112,28 +7443,20 @@ void Main() var v; } } - """; - - await VerifyItemExistsAsync(markup, "CommandLine"); - } + """, "CommandLine"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/12781")] - public async Task TestFieldDeclarationAmbiguity() - { - var markup = """ + public Task TestFieldDeclarationAmbiguity() + => VerifyItemExistsAsync(""" using System; Environment.$$ var v; } - """; - - await VerifyItemExistsAsync(markup, "CommandLine", sourceCodeKind: SourceCodeKind.Script); - } + """, "CommandLine", sourceCodeKind: SourceCodeKind.Script); [Fact] - public async Task TestCursorOnClassCloseBrace() - { - var markup = """ + public Task TestCursorOnClassCloseBrace() + => VerifyItemExistsAsync(""" using System; class Outer @@ -8141,43 +7464,31 @@ class Outer class Inner { } $$} - """; - - await VerifyItemExistsAsync(markup, "Inner"); - } + """, "Inner"); [Fact] - public async Task AfterAsync1() - { - var markup = """ + public Task AfterAsync1() + => VerifyItemExistsAsync(""" using System.Threading.Tasks; class Program { async $$ } - """; - - await VerifyItemExistsAsync(markup, "Task"); - } + """, "Task"); [Fact] - public async Task AfterAsync2() - { - var markup = """ + public Task AfterAsync2() + => VerifyItemExistsAsync(""" using System.Threading.Tasks; class Program { public async T$$ } - """; - - await VerifyItemExistsAsync(markup, "Task"); - } + """, "Task"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] - public async Task AfterAsync3() - { - var markup = """ + public Task AfterAsync3() + => VerifyItemExistsAsync(""" using System.Threading.Tasks; class Program { @@ -8185,33 +7496,25 @@ public async $$ public void M() {} } - """; - - await VerifyItemExistsAsync(markup, "Task"); - } + """, "Task"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] - public async Task AfterAsync4() - { - var markup = """ + public Task AfterAsync4() + => VerifyExpectedItemsAsync(""" using System; using System.Threading.Tasks; class Program { public async $$ } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("Task"), ItemExpectation.Absent("Console"), ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] - public async Task AfterAsync5() - { - var markup = """ + public Task AfterAsync5() + => VerifyExpectedItemsAsync(""" using System.Threading.Tasks; class Program { @@ -8219,18 +7522,14 @@ public async $$ } class Test {} - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("Task"), ItemExpectation.Absent("Test"), ]); - } [Fact] - public async Task NotAfterAsyncInMethodBody() - { - var markup = """ + public Task NotAfterAsyncInMethodBody() + => VerifyItemIsAbsentAsync(""" using System.Threading.Tasks; class Program { @@ -8239,15 +7538,11 @@ void goo() var x = async $$ } } - """; - - await VerifyItemIsAbsentAsync(markup, "Task"); - } + """, "Task"); [Fact] - public async Task NotAwaitable1() - { - var markup = """ + public Task NotAwaitable1() + => VerifyItemWithMscorlib45Async(""" class Program { void goo() @@ -8255,15 +7550,11 @@ void goo() $$ } } - """; - - await VerifyItemWithMscorlib45Async(markup, "goo", "void Program.goo()", "C#"); - } + """, "goo", "void Program.goo()", "C#"); [Fact] - public async Task NotAwaitable2() - { - var markup = """ + public Task NotAwaitable2() + => VerifyItemWithMscorlib45Async(""" class Program { async void goo() @@ -8271,15 +7562,11 @@ async void goo() $$ } } - """; - - await VerifyItemWithMscorlib45Async(markup, "goo", "void Program.goo()", "C#"); - } + """, "goo", "void Program.goo()", "C#"); [Fact] - public async Task Awaitable1() - { - var markup = """ + public Task Awaitable1() + => VerifyItemWithMscorlib45Async(""" using System.Threading; using System.Threading.Tasks; @@ -8290,17 +7577,11 @@ async Task goo() $$ } } - """; - - var description = $@"({CSharpFeaturesResources.awaitable}) Task Program.goo()"; - - await VerifyItemWithMscorlib45Async(markup, "goo", description, "C#"); - } + """, "goo", $@"({CSharpFeaturesResources.awaitable}) Task Program.goo()", "C#"); [Fact] - public async Task Awaitable2() - { - var markup = """ + public Task Awaitable2() + => VerifyItemWithMscorlib45Async(""" using System.Threading.Tasks; class Program @@ -8310,17 +7591,11 @@ async Task goo() $$ } } - """; - - var description = $@"({CSharpFeaturesResources.awaitable}) Task Program.goo()"; - - await VerifyItemWithMscorlib45Async(markup, "goo", description, "C#"); - } + """, "goo", $@"({CSharpFeaturesResources.awaitable}) Task Program.goo()", "C#"); [Fact] - public async Task AwaitableDotsLikeRangeExpression() - { - var markup = """ + public Task AwaitableDotsLikeRangeExpression() + => VerifyItemExistsAsync(""" using System.IO; using System.Threading.Tasks; @@ -8340,15 +7615,11 @@ class Request public Task ReadAsStreamAsync() => null; } } - """; - - await VerifyItemExistsAsync(markup, "ReadAsStreamAsync"); - } + """, "ReadAsStreamAsync"); [Fact] - public async Task AwaitableDotsLikeRangeExpressionWithParentheses() - { - var markup = """ + public Task AwaitableDotsLikeRangeExpressionWithParentheses() + => VerifyExpectedItemsAsync(""" using System.IO; using System.Threading.Tasks; @@ -8368,18 +7639,14 @@ class Request public Task ReadAsStreamAsync() => null; } } - """; - // Nothing should be found: no awaiter for request. - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("Result"), ItemExpectation.Absent("ReadAsStreamAsync"), ]); - } [Fact] - public async Task AwaitableDotsLikeRangeExpressionWithTaskAndParentheses() - { - var markup = """ + public Task AwaitableDotsLikeRangeExpressionWithTaskAndParentheses() + => VerifyExpectedItemsAsync(""" using System.IO; using System.Threading.Tasks; @@ -8399,18 +7666,14 @@ class Request public Task ReadAsStreamAsync() => null; } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("Result"), ItemExpectation.Exists("ReadAsStreamAsync"), ]); - } [Fact] - public async Task ObsoleteItem() - { - var markup = """ + public Task ObsoleteItem() + => VerifyItemExistsAsync(""" using System; class Program @@ -8421,14 +7684,11 @@ public void goo() $$ } } - """; - await VerifyItemExistsAsync(markup, "goo", $"[{CSharpFeaturesResources.deprecated}] void Program.goo()"); - } + """, "goo", $"[{CSharpFeaturesResources.deprecated}] void Program.goo()"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568986")] - public async Task NoMembersOnDottingIntoUnboundType() - { - var markup = """ + public Task NoMembersOnDottingIntoUnboundType() + => VerifyNoItemsExistAsync(""" class Program { RegistryKey goo; @@ -8438,38 +7698,29 @@ static void Main(string[] args) goo.$$ } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/550717")] - public async Task TypeArgumentsInConstraintAfterBaselist() - { - var markup = """ + public Task TypeArgumentsInConstraintAfterBaselist() + => VerifyItemExistsAsync(""" public class Goo : System.Object where $$ { } - """; - await VerifyItemExistsAsync(markup, "T"); - } + """, "T"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/647175")] - public async Task NoDestructor() - { - var markup = """ + public Task NoDestructor() + => VerifyItemIsAbsentAsync(""" class C { ~C() { $$ - """; - await VerifyItemIsAbsentAsync(markup, "Finalize"); - } + """, "Finalize"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669624")] - public async Task ExtensionMethodOnCovariantInterface() - { - var markup = """ + public Task ExtensionMethodOnCovariantInterface() + => VerifyItemExistsAsync(""" class Schema { } interface ISet { } @@ -8493,49 +7744,36 @@ static void Main(string[] args) var set = new Context().Set(); set.$$ - """; - - await VerifyItemExistsAsync(markup, "ForSchemaSet", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular); - } + """, "ForSchemaSet", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667752")] - public async Task ForEachInsideParentheses() - { - var markup = """ + public Task ForEachInsideParentheses() + => VerifyItemExistsAsync(""" using System; class C { void M() { foreach($$) - """; - - await VerifyItemExistsAsync(markup, "String"); - } + """, "String"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766869")] - public async Task TestFieldInitializerInP2P() - { - var markup = """ + public Task TestFieldInitializerInP2P() + => VerifyItemWithProjectReferenceAsync(""" class Class { int i = Consts.$$; } - """; - - var referencedCode = """ + """, """ public static class Consts { public const int C = 1; } - """; - await VerifyItemWithProjectReferenceAsync(markup, referencedCode, "C", 1, LanguageNames.CSharp, LanguageNames.CSharp); - } + """, "C", 1, LanguageNames.CSharp, LanguageNames.CSharp); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834605")] - public async Task ShowWithEqualsSign() - { - var markup = """ + public Task ShowWithEqualsSign() + => VerifyNoItemsExistAsync(""" class c { public int value {set; get; }} class d @@ -8545,15 +7783,11 @@ void goo() c goo = new c { value$$= } } - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825661")] - public async Task NothingAfterThisDotInStaticContext() - { - var markup = """ + public Task NothingAfterThisDotInStaticContext() + => VerifyNoItemsExistAsync(""" class C { void M1() { } @@ -8563,15 +7797,11 @@ static void M2() this.$$ } } - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825661")] - public async Task NothingAfterBaseDotInStaticContext() - { - var markup = """ + public Task NothingAfterBaseDotInStaticContext() + => VerifyNoItemsExistAsync(""" class C { void M1() { } @@ -8581,19 +7811,15 @@ static void M2() base.$$ } } - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/7648")] public async Task NothingAfterBaseDotInScriptContext() => await VerifyItemIsAbsentAsync(@"base.$$", @"ToString", sourceCodeKind: SourceCodeKind.Script); - [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858086")] - public async Task NoNestedTypeWhenDisplayingInstance() - { - var markup = """ + [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858086")] + public Task NoNestedTypeWhenDisplayingInstance() + => VerifyItemIsAbsentAsync(""" class C { class D @@ -8605,15 +7831,11 @@ void M2() new C().$$ } } - """; - - await VerifyItemIsAbsentAsync(markup, "D"); - } + """, "D"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876031")] - public async Task CatchVariableInExceptionFilter() - { - var markup = """ + public Task CatchVariableInExceptionFilter() + => VerifyItemExistsAsync(""" class C { void M() @@ -8622,15 +7844,11 @@ void M() { } catch (System.Exception myExn) when ($$ - """; - - await VerifyItemExistsAsync(markup, "myExn"); - } + """, "myExn"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849698")] - public async Task CompletionAfterExternAlias() - { - var markup = """ + public Task CompletionAfterExternAlias() + => VerifyItemExistsAsync(""" class C { void goo() @@ -8638,15 +7856,11 @@ void goo() global::$$ } } - """; - - await VerifyItemExistsAsync(markup, "System", usePreviousCharAsTrigger: true); - } + """, "System", usePreviousCharAsTrigger: true); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849698")] - public async Task ExternAliasSuggested() - { - var markup = """ + public Task ExternAliasSuggested() + => VerifyItemWithAliasedMetadataReferencesAsync(""" extern alias Bar; class C { @@ -8655,9 +7869,7 @@ void goo() $$ } } - """; - await VerifyItemWithAliasedMetadataReferencesAsync(markup, "Bar", "Bar", 1, "C#", "C#"); - } + """, "Bar", "Bar", 1, "C#", "C#"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")] public async Task ClassDestructor() @@ -8693,47 +7905,37 @@ class N } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")] - public async Task StructDestructor() - { - var markup = """ + public Task StructDestructor() + => VerifyItemIsAbsentAsync(""" struct C { ~$$ } - """; - await VerifyItemIsAbsentAsync(markup, "C"); - } + """, "C"); [Theory] [InlineData("record")] [InlineData("record class")] - public async Task RecordDestructor(string record) - { - var markup = $$""" + public Task RecordDestructor(string record) + => VerifyItemExistsAsync($$""" {{record}} C { ~$$ } - """; - await VerifyItemExistsAsync(markup, "C"); - } + """, "C"); [Fact] - public async Task RecordStructDestructor() - { - var markup = $$""" + public Task RecordStructDestructor() + => VerifyItemIsAbsentAsync($$""" record struct C { ~$$ } - """; - await VerifyItemIsAbsentAsync(markup, "C"); - } + """, "C"); [Fact] - public async Task FieldAvailableInBothLinkedFiles() - { - var markup = """ + public Task FieldAvailableInBothLinkedFiles() + => VerifyItemInLinkedFilesAsync(""" - """; - - await VerifyItemInLinkedFilesAsync(markup, "x", $"({FeaturesResources.field}) int C.x"); - } + """, "x", $"({FeaturesResources.field}) int C.x"); [Fact] - public async Task FieldUnavailableInOneLinkedFile() - { - var markup = """ + public Task FieldUnavailableInOneLinkedFile() + => VerifyItemInLinkedFilesAsync(""" - """; - var expectedDescription = $""" + """, "x", $""" ({FeaturesResources.field}) int C.x {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} {string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)} {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} - """; - - await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); - } + """); [Fact] - public async Task FieldUnavailableInTwoLinkedFiles() - { - var markup = """ + public Task FieldUnavailableInTwoLinkedFiles() + => VerifyItemInLinkedFilesAsync(""" - """; - var expectedDescription = $""" + """, "x", $""" ({FeaturesResources.field}) int C.x {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} @@ -8830,15 +8022,11 @@ void goo() {string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)} {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} - """; - - await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); - } + """); [Fact] - public async Task ExcludeFilesWithInactiveRegions() - { - var markup = """ + public Task ExcludeFilesWithInactiveRegions() + => VerifyItemInLinkedFilesAsync(""" - """; - var expectedDescription = $""" + """, "x", $""" ({FeaturesResources.field}) int C.x {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} {string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)} {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} - """; - - await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); - } + """); [Fact] - public async Task UnionOfItemsFromBothContexts() - { - var markup = """ + public Task UnionOfItemsFromBothContexts() + => VerifyItemInLinkedFilesAsync(""" - """; - var expectedDescription = $""" + """, "DoGStuff", $""" void G.DoGStuff() {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Not_Available)} @@ -8921,15 +8103,11 @@ void G.DoGStuff() {string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)} {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} - """; - - await VerifyItemInLinkedFilesAsync(markup, "DoGStuff", expectedDescription); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] - public async Task LocalsValidInLinkedDocuments() - { - var markup = """ + public Task LocalsValidInLinkedDocuments() + => VerifyItemInLinkedFilesAsync(""" - """; - var expectedDescription = $"({FeaturesResources.local_variable}) int xyz"; - await VerifyItemInLinkedFilesAsync(markup, "xyz", expectedDescription); - } + """, "xyz", $"({FeaturesResources.local_variable}) int xyz"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] - public async Task LocalWarningInLinkedDocuments() - { - var markup = """ + public Task LocalWarningInLinkedDocuments() + => VerifyItemInLinkedFilesAsync(""" - """; - var expectedDescription = $""" + """, "xyz", $""" ({FeaturesResources.local_variable}) int xyz {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} {string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)} {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} - """; - await VerifyItemInLinkedFilesAsync(markup, "xyz", expectedDescription); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] - public async Task LabelsValidInLinkedDocuments() - { - var markup = """ + public Task LabelsValidInLinkedDocuments() + => VerifyItemInLinkedFilesAsync(""" - """; - var expectedDescription = $"({FeaturesResources.label}) LABEL"; - await VerifyItemInLinkedFilesAsync(markup, "LABEL", expectedDescription); - } + """, "LABEL", $"({FeaturesResources.label}) LABEL"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] - public async Task RangeVariablesValidInLinkedDocuments() - { - var markup = """ + public Task RangeVariablesValidInLinkedDocuments() + => VerifyItemInLinkedFilesAsync(""" - """; - var expectedDescription = $"({FeaturesResources.range_variable}) ? y"; - await VerifyItemInLinkedFilesAsync(markup, "y", expectedDescription); - } + """, "y", $"({FeaturesResources.range_variable}) ? y"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1063403")] - public async Task MethodOverloadDifferencesIgnored() - { - var markup = """ + public Task MethodOverloadDifferencesIgnored() + => VerifyItemInLinkedFilesAsync(""" - """; - - var expectedDescription = $"void C.Do(int x)"; - await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription); - } + """, "Do", $"void C.Do(int x)"); [Fact] - public async Task MethodOverloadDifferencesIgnored_ExtensionMethod() - { - var markup = """ + public Task MethodOverloadDifferencesIgnored_ExtensionMethod() + => VerifyItemInLinkedFilesAsync(""" - """; - - var expectedDescription = $"void C.Do(int x)"; - await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription); - } + """, "Do", $"void C.Do(int x)"); [Fact] - public async Task MethodOverloadDifferencesIgnored_ExtensionMethod2() - { - var markup = """ + public Task MethodOverloadDifferencesIgnored_ExtensionMethod2() + => VerifyItemInLinkedFilesAsync(""" - """; - - var expectedDescription = $"({CSharpFeaturesResources.extension}) void C.Do(string x)"; - await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription); - } + """, "Do", $"({CSharpFeaturesResources.extension}) void C.Do(string x)"); [Fact] - public async Task MethodOverloadDifferencesIgnored_ContainingType() - { - var markup = """ + public Task MethodOverloadDifferencesIgnored_ContainingType() + => VerifyItemInLinkedFilesAsync(""" - """; - - var expectedDescription = $"void Methods1.Do(string x)"; - await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription); - } + """, "Do", $"void Methods1.Do(string x)"); [Fact] - public async Task SharedProjectFieldAndPropertiesTreatedAsIdentical() - { - var markup = """ + public Task SharedProjectFieldAndPropertiesTreatedAsIdentical() + => VerifyItemInLinkedFilesAsync(""" - """; - - var expectedDescription = $"({FeaturesResources.field}) int C.x"; - await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); - } + """, "x", $"({FeaturesResources.field}) int C.x"); [Fact] - public async Task SharedProjectFieldAndPropertiesTreatedAsIdentical2() - { - var markup = """ + public Task SharedProjectFieldAndPropertiesTreatedAsIdentical2() + => VerifyItemInLinkedFilesAsync(""" - """; - - var expectedDescription = "int C.x { get; set; }"; - await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); - } + """, "x", "int C.x { get; set; }"); [Fact] - public async Task ConditionalAccessWalkUp() - { - var markup = """ + public Task ConditionalAccessWalkUp() + => VerifyExpectedItemsAsync(""" public class B { public A BA; @@ -9304,17 +8436,14 @@ public void goo() var q = a?.$$AB.BA.AB.BA; } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("AA"), ItemExpectation.Exists("AB"), ]); - } [Fact] - public async Task ConditionalAccessNullableIsUnwrapped() - { - var markup = """ + public Task ConditionalAccessNullableIsUnwrapped() + => VerifyExpectedItemsAsync(""" public struct S { public int? i; @@ -9330,17 +8459,14 @@ public void goo() var q = a?.s?.$$; } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("i"), ItemExpectation.Absent("Value"), ]); - } [Fact] - public async Task ConditionalAccessNullableIsUnwrapped2() - { - var markup = """ + public Task ConditionalAccessNullableIsUnwrapped2() + => VerifyExpectedItemsAsync(""" public struct S { public int? i; @@ -9355,17 +8481,14 @@ public void goo() var q = s?.$$i?.ToString(); } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("i"), ItemExpectation.Absent("Value"), ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/54361")] - public async Task ConditionalAccessNullableIsUnwrappedOnParameter() - { - var markup = """ + public Task ConditionalAccessNullableIsUnwrappedOnParameter() + => VerifyExpectedItemsAsync(""" class A { void M(System.DateTime? dt) @@ -9373,17 +8496,14 @@ void M(System.DateTime? dt) dt?.$$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("Day"), ItemExpectation.Absent("Value"), ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/54361")] - public async Task NullableIsNotUnwrappedOnParameter() - { - var markup = """ + public Task NullableIsNotUnwrappedOnParameter() + => VerifyExpectedItemsAsync(""" class A { void M(System.DateTime? dt) @@ -9391,17 +8511,14 @@ void M(System.DateTime? dt) dt.$$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("Value"), ItemExpectation.Absent("Day"), ]); - } [Fact] - public async Task CompletionAfterConditionalIndexing() - { - var markup = """ + public Task CompletionAfterConditionalIndexing() + => VerifyItemExistsAsync(""" public struct S { public int? i; @@ -9417,14 +8534,11 @@ public void goo() var q = a?.s?[$$; } } - """; - await VerifyItemExistsAsync(markup, "System"); - } + """, "System"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")] - public async Task WithinChainOfConditionalAccesses1() - { - var markup = """ + public Task WithinChainOfConditionalAccesses1() + => VerifyItemExistsAsync(""" class Program { static void Main(string[] args) @@ -9438,14 +8552,11 @@ class A { public B b; } class B { public C c; } class C { public D d; } class D { public int e; } - """; - await VerifyItemExistsAsync(markup, "b"); - } + """, "b"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")] - public async Task WithinChainOfConditionalAccesses2() - { - var markup = """ + public Task WithinChainOfConditionalAccesses2() + => VerifyItemExistsAsync(""" class Program { static void Main(string[] args) @@ -9459,14 +8570,11 @@ class A { public B b; } class B { public C c; } class C { public D d; } class D { public int e; } - """; - await VerifyItemExistsAsync(markup, "c"); - } + """, "c"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")] - public async Task WithinChainOfConditionalAccesses3() - { - var markup = """ + public Task WithinChainOfConditionalAccesses3() + => VerifyItemExistsAsync(""" class Program { static void Main(string[] args) @@ -9480,14 +8588,11 @@ class A { public B b; } class B { public C c; } class C { public D d; } class D { public int e; } - """; - await VerifyItemExistsAsync(markup, "d"); - } + """, "d"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843466")] - public async Task NestedAttributeAccessibleOnSelf() - { - var markup = """ + public Task NestedAttributeAccessibleOnSelf() + => VerifyItemExistsAsync(""" using System; [My] class X @@ -9498,14 +8603,11 @@ class MyAttribute : Attribute } } - """; - await VerifyItemExistsAsync(markup, "My"); - } + """, "My"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843466")] - public async Task NestedAttributeAccessibleOnOuterType() - { - var markup = """ + public Task NestedAttributeAccessibleOnOuterType() + => VerifyItemExistsAsync(""" using System; [My] @@ -9523,14 +8625,11 @@ class MyAttribute : Attribute } } - """; - await VerifyItemExistsAsync(markup, "My"); - } + """, "My"); [Fact] - public async Task InstanceMembersFromBaseOuterType() - { - var markup = """ + public Task InstanceMembersFromBaseOuterType() + => VerifyItemExistsAsync(""" abstract class Test { private int _field; @@ -9544,14 +8643,11 @@ public void SomeTest() } } } - """; - await VerifyItemExistsAsync(markup, "_field"); - } + """, "_field"); [Fact] - public async Task InstanceMembersFromBaseOuterType2() - { - var markup = """ + public Task InstanceMembersFromBaseOuterType2() + => VerifyItemExistsAsync(""" class C { void M() { } @@ -9571,14 +8667,11 @@ void Test2() } } } - """; - await VerifyItemExistsAsync(markup, "M"); - } + """, "M"); [Fact] - public async Task InstanceMembersFromBaseOuterType3() - { - var markup = """ + public Task InstanceMembersFromBaseOuterType3() + => VerifyItemIsAbsentAsync(""" class C { void M() { } @@ -9598,14 +8691,11 @@ void Test2() } } } - """; - await VerifyItemIsAbsentAsync(markup, "M"); - } + """, "M"); [Fact] - public async Task InstanceMembersFromBaseOuterType4() - { - var markup = """ + public Task InstanceMembersFromBaseOuterType4() + => VerifyItemExistsAsync(""" class C { void M() { } @@ -9625,14 +8715,11 @@ void Test2() } } } - """; - await VerifyItemExistsAsync(markup, "M"); - } + """, "M"); [Fact] - public async Task InstanceMembersFromBaseOuterType5() - { - var markup = """ + public Task InstanceMembersFromBaseOuterType5() + => VerifyItemIsAbsentAsync(""" class D { public void Q() { } @@ -9647,14 +8734,11 @@ void Test() } } } - """; - await VerifyItemIsAbsentAsync(markup, "Q"); - } + """, "Q"); [Fact] - public async Task InstanceMembersFromBaseOuterType6() - { - var markup = """ + public Task InstanceMembersFromBaseOuterType6() + => VerifyItemIsAbsentAsync(""" class Base { public int X; @@ -9670,26 +8754,20 @@ void Test() } } } - """; - await VerifyItemIsAbsentAsync(markup, "X"); - } + """, "X"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/983367")] - public async Task NoTypeParametersDefinedInCrefs() - { - var markup = """ + public Task NoTypeParametersDefinedInCrefs() + => VerifyItemIsAbsentAsync(""" using System; /// class Program { } - """; - await VerifyItemIsAbsentAsync(markup, "T"); - } + """, "T"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/988025")] - public async Task ShowTypesInGenericMethodTypeParameterList1() - { - var markup = """ + public Task ShowTypesInGenericMethodTypeParameterList1() + => VerifyItemExistsAsync(""" class Class1 { public static Class1 Create() { return null; } @@ -9707,14 +8785,11 @@ static void Main(string[] args) Class1.Create().Test<$$ } } - """; - await VerifyItemExistsAsync(markup, "Class1", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular); - } + """, "Class1", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/988025")] - public async Task ShowTypesInGenericMethodTypeParameterList2() - { - var markup = """ + public Task ShowTypesInGenericMethodTypeParameterList2() + => VerifyItemExistsAsync(""" class Class1 { public static Class1 Create() { return null; } @@ -9732,14 +8807,11 @@ static void Main(string[] args) Class1.Create().Test", sourceCodeKind: SourceCodeKind.Regular); - } + """, "Class1", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")] - public async Task DescriptionInAliasedType() - { - var markup = """ + public Task DescriptionInAliasedType() + => VerifyItemExistsAsync(""" using IAlias = IGoo; ///summary for interface IGoo interface IGoo { } @@ -9747,17 +8819,14 @@ class C { I$$ } - """; - await VerifyItemExistsAsync(markup, "IAlias", expectedDescriptionOrNull: """ + """, "IAlias", expectedDescriptionOrNull: """ interface IGoo summary for interface IGoo """); - } [Fact] - public async Task WithinNameOf() - { - var markup = """ + public Task WithinNameOf() + => VerifyAnyItemExistsAsync(""" class C { void goo() @@ -9765,40 +8834,31 @@ void goo() var x = nameof($$) } } - """; - await VerifyAnyItemExistsAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/997410")] - public async Task InstanceMemberInNameOfInStaticContext() - { - var markup = """ + public Task InstanceMemberInNameOfInStaticContext() + => VerifyItemExistsAsync(""" class C { int y1 = 15; static int y2 = 1; static string x = nameof($$ - """; - await VerifyItemExistsAsync(markup, "y1"); - } + """, "y1"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/997410")] - public async Task StaticMemberInNameOfInStaticContext() - { - var markup = """ + public Task StaticMemberInNameOfInStaticContext() + => VerifyItemExistsAsync(""" class C { int y1 = 15; static int y2 = 1; static string x = nameof($$ - """; - await VerifyItemExistsAsync(markup, "y2"); - } + """, "y2"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/883293")] - public async Task IncompleteDeclarationExpressionType() - { - var markup = """ + public Task IncompleteDeclarationExpressionType() + => VerifyItemExistsAsync(""" using System; class C { @@ -9808,14 +8868,11 @@ void goo() var y = 3; } } - """; - await VerifyItemExistsAsync(markup, "WriteLine"); - } + """, "WriteLine"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024380")] - public async Task StaticAndInstanceInNameOf() - { - var markup = """ + public Task StaticAndInstanceInNameOf() + => VerifyExpectedItemsAsync(""" using System; class C { @@ -9830,17 +8887,14 @@ void goo() var z = nameof(C.D.$$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("x"), ItemExpectation.Exists("y"), ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1663")] - public async Task NameOfMembersListedForLocals() - { - var markup = """ + public Task NameOfMembersListedForLocals() + => VerifyItemExistsAsync(""" class C { void M() @@ -9858,14 +8912,11 @@ public class U { public int nope; } - """; - await VerifyItemExistsAsync(markup, "nope"); - } + """, "nope"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")] - public async Task NameOfMembersListedForNamespacesAndTypes2() - { - var markup = """ + public Task NameOfMembersListedForNamespacesAndTypes2() + => VerifyItemExistsAsync(""" class C { void M() @@ -9883,14 +8934,11 @@ public class U { public int nope; } - """; - await VerifyItemExistsAsync(markup, "nope"); - } + """, "nope"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")] - public async Task NameOfMembersListedForNamespacesAndTypes3() - { - var markup = """ + public Task NameOfMembersListedForNamespacesAndTypes3() + => VerifyItemExistsAsync(""" class C { void M() @@ -9906,14 +8954,11 @@ public class U public int nope; } } - """; - await VerifyItemExistsAsync(markup, "U"); - } + """, "U"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")] - public async Task NameOfMembersListedForNamespacesAndTypes4() - { - var markup = """ + public Task NameOfMembersListedForNamespacesAndTypes4() + => VerifyItemExistsAsync(""" using z = System; class C { @@ -9922,14 +8967,11 @@ void M() var x = nameof(z.$$) } } - """; - await VerifyItemExistsAsync(markup, "Console"); - } + """, "Console"); [Fact] - public async Task InterpolatedStrings1() - { - var markup = """ + public Task InterpolatedStrings1() + => VerifyItemExistsAsync(""" class C { void M() @@ -9937,14 +8979,11 @@ void M() var a = "Hello"; var b = "World"; var c = $"{$$ - """; - await VerifyItemExistsAsync(markup, "a"); - } + """, "a"); [Fact] - public async Task InterpolatedStrings2() - { - var markup = """ + public Task InterpolatedStrings2() + => VerifyItemExistsAsync(""" class C { void M() @@ -9954,29 +8993,23 @@ void M() var c = $"{$$}"; } } - """; - await VerifyItemExistsAsync(markup, "a"); - } + """, "a"); [Fact] - public async Task InterpolatedStrings3() - { - var markup = """ + public Task InterpolatedStrings3() + => VerifyItemExistsAsync(""" class C { void M() { var a = "Hello"; var b = "World"; - var c = $"{a}, {$$ - """; - await VerifyItemExistsAsync(markup, "b"); - } + var c = $"{a}, {$$ + """, "b"); [Fact] - public async Task InterpolatedStrings4() - { - var markup = """ + public Task InterpolatedStrings4() + => VerifyItemExistsAsync(""" class C { void M() @@ -9986,14 +9019,11 @@ void M() var c = $"{a}, {$$}"; } } - """; - await VerifyItemExistsAsync(markup, "b"); - } + """, "b"); [Fact] - public async Task InterpolatedStrings5() - { - var markup = """ + public Task InterpolatedStrings5() + => VerifyItemExistsAsync(""" class C { void M() @@ -10001,14 +9031,11 @@ void M() var a = "Hello"; var b = "World"; var c = $@"{a}, {$$ - """; - await VerifyItemExistsAsync(markup, "b"); - } + """, "b"); [Fact] - public async Task InterpolatedStrings6() - { - var markup = """ + public Task InterpolatedStrings6() + => VerifyItemExistsAsync(""" class C { void M() @@ -10018,52 +9045,41 @@ void M() var c = $@"{a}, {$$}"; } } - """; - await VerifyItemExistsAsync(markup, "b"); - } + """, "b"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] - public async Task NotBeforeFirstStringHole() - { - await VerifyNoItemsExistAsync(AddInsideMethod( + public Task NotBeforeFirstStringHole() + => VerifyNoItemsExistAsync(AddInsideMethod( """ var x = "\{0}$$\{1}\{2}" """)); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] - public async Task NotBetweenStringHoles() - { - await VerifyNoItemsExistAsync(AddInsideMethod( + public Task NotBetweenStringHoles() + => VerifyNoItemsExistAsync(AddInsideMethod( """ var x = "\{0}\{1}$$\{2}" """)); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] - public async Task NotAfterStringHoles() - { - await VerifyNoItemsExistAsync(AddInsideMethod( + public Task NotAfterStringHoles() + => VerifyNoItemsExistAsync(AddInsideMethod( """ var x = "\{0}\{1}\{2}$$" """)); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087171")] - public async Task CompletionAfterTypeOfGetType() - { - await VerifyItemExistsAsync(AddInsideMethod( + public Task CompletionAfterTypeOfGetType() + => VerifyItemExistsAsync(AddInsideMethod( "typeof(int).GetType().$$"), "GUID"); - } [Fact] - public async Task UsingDirectives1() - { - var markup = """ + public Task UsingDirectives1() + => VerifyExpectedItemsAsync(""" using $$ class A { } @@ -10076,19 +9092,15 @@ static class D { } namespace M { } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("A"), ItemExpectation.Absent("B"), ItemExpectation.Exists("N"), ]); - } [Fact] - public async Task UsingDirectives2() - { - var markup = """ + public Task UsingDirectives2() + => VerifyExpectedItemsAsync(""" using N.$$ class A { } @@ -10101,19 +9113,15 @@ static class D { } namespace M { } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("C"), ItemExpectation.Absent("D"), ItemExpectation.Exists("M"), ]); - } [Fact] - public async Task UsingDirectives3() - { - var markup = """ + public Task UsingDirectives3() + => VerifyExpectedItemsAsync(""" using G = $$ class A { } @@ -10126,19 +9134,15 @@ static class D { } namespace M { } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("A"), ItemExpectation.Exists("B"), ItemExpectation.Exists("N"), ]); - } [Fact] - public async Task UsingDirectives4() - { - var markup = """ + public Task UsingDirectives4() + => VerifyExpectedItemsAsync(""" using G = N.$$ class A { } @@ -10151,19 +9155,15 @@ static class D { } namespace M { } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("C"), ItemExpectation.Exists("D"), ItemExpectation.Exists("M"), ]); - } [Fact] - public async Task UsingDirectives5() - { - var markup = """ + public Task UsingDirectives5() + => VerifyExpectedItemsAsync(""" using static $$ class A { } @@ -10176,19 +9176,15 @@ static class D { } namespace M { } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("A"), ItemExpectation.Exists("B"), ItemExpectation.Exists("N"), ]); - } [Fact] - public async Task UsingDirectives6() - { - var markup = """ + public Task UsingDirectives6() + => VerifyExpectedItemsAsync(""" using static N.$$ class A { } @@ -10201,19 +9197,15 @@ static class D { } namespace M { } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("C"), ItemExpectation.Exists("D"), ItemExpectation.Exists("M"), ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67985")] - public async Task UsingDirectives7() - { - var markup = """ + public Task UsingDirectives7() + => VerifyExpectedItemsAsync(""" using static unsafe $$ class A { } @@ -10226,19 +9218,15 @@ static class D { } namespace M { } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("A"), ItemExpectation.Exists("B"), ItemExpectation.Exists("N"), ]); - } [Fact] - public async Task UsingStaticDoesNotShowDelegates1() - { - var markup = """ + public Task UsingStaticDoesNotShowDelegates1() + => VerifyExpectedItemsAsync(""" using static $$ class A { } @@ -10251,19 +9239,15 @@ static class D { } namespace M { } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("A"), ItemExpectation.Absent("B"), ItemExpectation.Exists("N"), ]); - } [Fact] - public async Task UsingStaticDoesNotShowDelegates2() - { - var markup = """ + public Task UsingStaticDoesNotShowDelegates2() + => VerifyExpectedItemsAsync(""" using static N.$$ class A { } @@ -10276,19 +9260,15 @@ class C { } namespace M { } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("C"), ItemExpectation.Absent("D"), ItemExpectation.Exists("M"), ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67985")] - public async Task UsingStaticDoesNotShowDelegates3() - { - var markup = """ + public Task UsingStaticDoesNotShowDelegates3() + => VerifyExpectedItemsAsync(""" using static unsafe $$ class A { } @@ -10301,20 +9281,15 @@ static class D { } namespace M { } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("A"), ItemExpectation.Absent("B"), ItemExpectation.Exists("N"), ]); - } [Fact] - public async Task UsingStaticShowInterfaces1() - { - // Interfaces can have implemented static methods - var markup = """ + public Task UsingStaticShowInterfaces1() + => VerifyExpectedItemsAsync(""" using static N.$$ class A { } @@ -10327,20 +9302,15 @@ interface I { } namespace M { } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("C"), ItemExpectation.Exists("I"), ItemExpectation.Exists("M"), ]); - } [Fact] - public async Task UsingStaticShowInterfaces2() - { - // Interfaces can have implemented static methods - var markup = """ + public Task UsingStaticShowInterfaces2() + => VerifyExpectedItemsAsync(""" using static $$ class A { } @@ -10353,20 +9323,15 @@ static class D { } namespace M { } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("A"), ItemExpectation.Exists("I"), ItemExpectation.Exists("N"), ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67985")] - public async Task UsingStaticShowInterfaces3() - { - // Interfaces can have implemented static methods - var markup = """ + public Task UsingStaticShowInterfaces3() + => VerifyExpectedItemsAsync(""" using static unsafe $$ class A { } @@ -10379,19 +9344,15 @@ static class D { } namespace M { } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("A"), ItemExpectation.Exists("I"), ItemExpectation.Exists("N"), ]); - } [Fact] - public async Task UsingStaticAndExtensionMethods1() - { - var markup = """ + public Task UsingStaticAndExtensionMethods1() + => VerifyExpectedItemsAsync(""" using static A; using static B; @@ -10412,18 +9373,14 @@ void M() $$ } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("Goo"), ItemExpectation.Absent("Bar"), ]); - } [Fact] - public async Task UsingStaticAndExtensionMethods2() - { - var markup = """ + public Task UsingStaticAndExtensionMethods2() + => VerifyExpectedItemsAsync(""" using N; namespace N @@ -10446,18 +9403,14 @@ void M() $$ } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("Goo"), ItemExpectation.Absent("Bar"), ]); - } [Fact] - public async Task UsingStaticAndExtensionMethods3() - { - var markup = """ + public Task UsingStaticAndExtensionMethods3() + => VerifyExpectedItemsAsync(""" using N; namespace N @@ -10481,18 +9434,14 @@ void M() s.$$ } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("Goo"), ItemExpectation.Exists("Bar"), ]); - } [Fact] - public async Task UsingStaticAndExtensionMethods4() - { - var markup = """ + public Task UsingStaticAndExtensionMethods4() + => VerifyExpectedItemsAsync(""" using static N.A; using static N.B; @@ -10517,18 +9466,14 @@ void M() s.$$ } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("Goo"), ItemExpectation.Exists("Bar"), ]); - } [Fact] - public async Task UsingStaticAndExtensionMethods5() - { - var markup = """ + public Task UsingStaticAndExtensionMethods5() + => VerifyExpectedItemsAsync(""" using static N.A; namespace N @@ -10552,18 +9497,14 @@ void M() s.$$ } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("Goo"), ItemExpectation.Absent("Bar"), ]); - } [Fact] - public async Task UsingStaticAndExtensionMethods6() - { - var markup = """ + public Task UsingStaticAndExtensionMethods6() + => VerifyExpectedItemsAsync(""" using static N.B; namespace N @@ -10587,18 +9528,14 @@ void M() s.$$ } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("Goo"), ItemExpectation.Exists("Bar"), ]); - } [Fact] - public async Task UsingStaticAndExtensionMethods7() - { - var markup = """ + public Task UsingStaticAndExtensionMethods7() + => VerifyExpectedItemsAsync(""" using N; using static N.B; @@ -10623,18 +9560,14 @@ void M() s.$$; } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("Goo"), ItemExpectation.Exists("Bar"), ]); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/7932")] - public async Task ExtensionMethodWithinSameClassOfferedForCompletion() - { - var markup = """ + public Task ExtensionMethodWithinSameClassOfferedForCompletion() + => VerifyItemExistsAsync(""" public static class Test { static void TestB() @@ -10643,14 +9576,11 @@ static void TestB() } static void TestA(this string s) { } } - """; - await VerifyItemExistsAsync(markup, "TestA"); - } + """, "TestA"); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/7932")] - public async Task ExtensionMethodWithinParentClassOfferedForCompletion() - { - var markup = """ + public Task ExtensionMethodWithinParentClassOfferedForCompletion() + => VerifyItemExistsAsync(""" public static class Parent { static void TestA(this string s) { } @@ -10663,14 +9593,11 @@ static void TestB() } } } - """; - await VerifyItemExistsAsync(markup, "TestA"); - } + """, "TestA"); [Fact] - public async Task ExceptionFilter1() - { - var markup = """ + public Task ExceptionFilter1() + => VerifyItemExistsAsync(""" using System; class C @@ -10681,15 +9608,11 @@ void M(bool x) { } catch when ($$ - """; - - await VerifyItemExistsAsync(markup, "x"); - } + """, "x"); [Fact] - public async Task ExceptionFilter1_NotBeforeOpenParen() - { - var markup = """ + public Task ExceptionFilter1_NotBeforeOpenParen() + => VerifyNoItemsExistAsync(""" using System; class C @@ -10700,15 +9623,11 @@ void M(bool x) { } catch when $$ - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task ExceptionFilter2() - { - var markup = """ + public Task ExceptionFilter2() + => VerifyItemExistsAsync(""" using System; class C @@ -10719,15 +9638,11 @@ void M(bool x) { } catch (Exception ex) when ($$ - """; - - await VerifyItemExistsAsync(markup, "x"); - } + """, "x"); [Fact] - public async Task ExceptionFilter2_NotBeforeOpenParen() - { - var markup = """ + public Task ExceptionFilter2_NotBeforeOpenParen() + => VerifyNoItemsExistAsync(""" using System; class C @@ -10738,15 +9653,11 @@ void M(bool x) { } catch (Exception ex) when $$ - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25084")] - public async Task SwitchCaseWhenClause1() - { - var markup = """ + public Task SwitchCaseWhenClause1() + => VerifyItemExistsAsync(""" class C { void M(bool x) @@ -10754,15 +9665,11 @@ void M(bool x) switch (1) { case 1 when $$ - """; - - await VerifyItemExistsAsync(markup, "x"); - } + """, "x"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25084")] - public async Task SwitchCaseWhenClause2() - { - var markup = """ + public Task SwitchCaseWhenClause2() + => VerifyItemExistsAsync(""" class C { void M(bool x) @@ -10770,15 +9677,11 @@ void M(bool x) switch (1) { case int i when $$ - """; - - await VerifyItemExistsAsync(markup, "x"); - } + """, "x"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/717")] - public async Task ExpressionContextCompletionWithinCast() - { - var markup = """ + public Task ExpressionContextCompletionWithinCast() + => VerifyItemExistsAsync(""" class Program { void M() @@ -10790,119 +9693,89 @@ void M() } } } - """; - await VerifyItemExistsAsync(markup, "i"); - } + """, "i"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1277")] - public async Task NoInstanceMembersInPropertyInitializer() - { - var markup = """ + public Task NoInstanceMembersInPropertyInitializer() + => VerifyItemIsAbsentAsync(""" class A { int abc; int B { get; } = $$ } - """; - await VerifyItemIsAbsentAsync(markup, "abc"); - } + """, "abc"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1277")] - public async Task StaticMembersInPropertyInitializer() - { - var markup = """ + public Task StaticMembersInPropertyInitializer() + => VerifyItemExistsAsync(""" class A { static Action s_abc; event Action B = $$ } - """; - await VerifyItemExistsAsync(markup, "s_abc"); - } + """, "s_abc"); [Fact] - public async Task NoInstanceMembersInFieldLikeEventInitializer() - { - var markup = """ + public Task NoInstanceMembersInFieldLikeEventInitializer() + => VerifyItemIsAbsentAsync(""" class A { Action abc; event Action B = $$ } - """; - await VerifyItemIsAbsentAsync(markup, "abc"); - } + """, "abc"); [Fact] - public async Task StaticMembersInFieldLikeEventInitializer() - { - var markup = """ + public Task StaticMembersInFieldLikeEventInitializer() + => VerifyItemExistsAsync(""" class A { static Action s_abc; event Action B = $$ } - """; - await VerifyItemExistsAsync(markup, "s_abc"); - } + """, "s_abc"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/5069")] - public async Task InstanceMembersInTopLevelFieldInitializer() - { - var markup = """ + public Task InstanceMembersInTopLevelFieldInitializer() + => VerifyItemExistsAsync(""" int aaa = 1; int bbb = $$ - """; - await VerifyItemExistsAsync(markup, "aaa", sourceCodeKind: SourceCodeKind.Script); - } + """, "aaa", sourceCodeKind: SourceCodeKind.Script); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/5069")] - public async Task InstanceMembersInTopLevelFieldLikeEventInitializer() - { - var markup = """ + public Task InstanceMembersInTopLevelFieldLikeEventInitializer() + => VerifyItemExistsAsync(""" Action aaa = null; event Action bbb = $$ - """; - await VerifyItemExistsAsync(markup, "aaa", sourceCodeKind: SourceCodeKind.Script); - } + """, "aaa", sourceCodeKind: SourceCodeKind.Script); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33")] - public async Task NoConditionalAccessCompletionOnTypes1() - { - var markup = """ + public Task NoConditionalAccessCompletionOnTypes1() + => VerifyNoItemsExistAsync(""" using A = System class C { A?.$$ } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33")] - public async Task NoConditionalAccessCompletionOnTypes2() - { - var markup = """ + public Task NoConditionalAccessCompletionOnTypes2() + => VerifyNoItemsExistAsync(""" class C { System?.$$ } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33")] - public async Task NoConditionalAccessCompletionOnTypes3() - { - var markup = """ + public Task NoConditionalAccessCompletionOnTypes3() + => VerifyNoItemsExistAsync(""" class C { System.Console?.$$ } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task CompletionInIncompletePropertyDeclaration() - { - var markup = """ + public Task CompletionInIncompletePropertyDeclaration() + => VerifyItemExistsAsync(""" class Class1 { public string Property1 { get; set; } @@ -10913,9 +9786,7 @@ class Class2 public string Property { get { return this.Source.$$ public Class1 Source { get; set; } } - """; - await VerifyItemExistsAsync(markup, "Property1"); - } + """, "Property1"); [Fact] public async Task NoCompletionInShebangComments() @@ -10925,9 +9796,8 @@ public async Task NoCompletionInShebangComments() } [Fact] - public async Task CompoundNameTargetTypePreselection() - { - var markup = """ + public Task CompoundNameTargetTypePreselection() + => VerifyItemExistsAsync(""" class Class1 { void goo() @@ -10936,14 +9806,11 @@ void goo() string y = x.$$ } } - """; - await VerifyItemExistsAsync(markup, "ToString", matchPriority: SymbolMatchPriority.PreferEventOrMethod); - } + """, "ToString", matchPriority: SymbolMatchPriority.PreferEventOrMethod); [Fact] - public async Task TargetTypeInCollectionInitializer1() - { - var markup = """ + public Task TargetTypeInCollectionInitializer1() + => VerifyItemExistsAsync(""" using System.Collections.Generic; class Program @@ -10955,14 +9822,11 @@ static void Main(string[] args) List x = new List() { $$ } } } - """; - await VerifyItemExistsAsync(markup, "z", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); - } + """, "z", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); [Fact] - public async Task TargetTypeInCollectionInitializer2() - { - var markup = """ + public Task TargetTypeInCollectionInitializer2() + => VerifyItemExistsAsync(""" using System.Collections.Generic; class Program @@ -10974,14 +9838,11 @@ static void Main(string[] args) List x = new List() { 1, $$ } } } - """; - await VerifyItemExistsAsync(markup, "z", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); - } + """, "z", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); [Fact] - public async Task TargeTypeInObjectInitializer1() - { - var markup = """ + public Task TargeTypeInObjectInitializer1() + => VerifyItemExistsAsync(""" class C { public int X { get; set; } @@ -10993,14 +9854,11 @@ void goo() var c = new C() { X = $$ } } } - """; - await VerifyItemExistsAsync(markup, "i", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); - } + """, "i", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); [Fact] - public async Task TargeTypeInObjectInitializer2() - { - var markup = """ + public Task TargeTypeInObjectInitializer2() + => VerifyItemExistsAsync(""" class C { public int X { get; set; } @@ -11012,9 +9870,7 @@ void goo() var c = new C() { X = 1, Y = $$ } } } - """; - await VerifyItemExistsAsync(markup, "i", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); - } + """, "i", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); [Fact] public async Task TupleElements() @@ -11072,84 +9928,67 @@ void goo() [Fact] [CompilerTrait(CompilerFeature.LocalFunctions)] - [WorkItem("https://github.com/dotnet/roslyn/issues/13480")] - public async Task NoCompletionInLocalFuncGenericParamList() - { - var markup = """ + [WorkItem("https://github.com/dotnet/roslyn/issues/13480")] + public Task NoCompletionInLocalFuncGenericParamList() + => VerifyNoItemsExistAsync(""" class C { void M() { int Local<$$ - """; - - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] [CompilerTrait(CompilerFeature.LocalFunctions)] [WorkItem("https://github.com/dotnet/roslyn/issues/13480")] - public async Task CompletionForAwaitWithoutAsync() - { - var markup = """ + public Task CompletionForAwaitWithoutAsync() + => VerifyAnyItemExistsAsync(""" class C { void M() { await Local<$$ - """; - - await VerifyAnyItemExistsAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TupleTypeAtMemberLevel1() - { - await VerifyItemExistsAsync(""" + public Task TupleTypeAtMemberLevel1() + => VerifyItemExistsAsync(""" class C { ($$ } """, "C"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TupleTypeAtMemberLevel2() - { - await VerifyItemExistsAsync(""" + public Task TupleTypeAtMemberLevel2() + => VerifyItemExistsAsync(""" class C { ($$) } """, "C"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TupleTypeAtMemberLevel3() - { - await VerifyItemExistsAsync(""" + public Task TupleTypeAtMemberLevel3() + => VerifyItemExistsAsync(""" class C { (C, $$ } """, "C"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TupleTypeAtMemberLevel4() - { - await VerifyItemExistsAsync(""" + public Task TupleTypeAtMemberLevel4() + => VerifyItemExistsAsync(""" class C { (C, $$) } """, "C"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TupleTypeInForeach() - { - await VerifyItemExistsAsync(""" + public Task TupleTypeInForeach() + => VerifyItemExistsAsync(""" class C { void M() @@ -11158,12 +9997,10 @@ void M() } } """, "C"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TupleTypeInParameterList() - { - await VerifyItemExistsAsync(""" + public Task TupleTypeInParameterList() + => VerifyItemExistsAsync(""" class C { void M((C, $$) @@ -11171,12 +10008,10 @@ void M((C, $$) } } """, "C"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TupleTypeInNameOf() - { - await VerifyItemExistsAsync(""" + public Task TupleTypeInNameOf() + => VerifyItemExistsAsync(""" class C { void M() @@ -11185,13 +10020,11 @@ void M() } } """, "C"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14163")] [CompilerTrait(CompilerFeature.LocalFunctions)] - public async Task LocalFunctionDescription() - { - await VerifyItemExistsAsync(""" + public Task LocalFunctionDescription() + => VerifyItemExistsAsync(""" class C { void M() @@ -11202,13 +10035,11 @@ void Local() { } } } """, "Local", "void Local()"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14163")] [CompilerTrait(CompilerFeature.LocalFunctions)] - public async Task LocalFunctionDescription2() - { - await VerifyItemExistsAsync(""" + public Task LocalFunctionDescription2() + => VerifyItemExistsAsync(""" using System; class C { @@ -11224,7 +10055,6 @@ Action Local(string x, ref var @class, params Func f) } } """, "Local", "Action Local(string x, ref var @class, params Func f)"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18359")] public async Task EnumMemberAfterDot() @@ -11257,10 +10087,8 @@ enum E [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("https://github.com/dotnet/roslyn/issues/8321")] - public async Task NotOnMethodGroup1() - { - var markup = - """ + public Task NotOnMethodGroup1() + => VerifyNoItemsExistAsync(""" namespace ConsoleApp { class Program @@ -11271,76 +10099,50 @@ static void Main(string[] args) } } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("https://github.com/dotnet/roslyn/issues/8321")] - public async Task NotOnMethodGroup2() - { - var markup = - """ + public Task NotOnMethodGroup2() + => VerifyNoItemsExistAsync(""" class C { void M() {M.$$ } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("https://github.com/dotnet/roslyn/issues/8321")] - public async Task NotOnMethodGroup3() - { - var markup = - """ + public Task NotOnMethodGroup3() + => VerifyNoItemsExistAsync(""" class C { void M() {M.$$} } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=420697&_a=edit")] - public async Task DoNotCrashInExtensionMethoWithExpressionBodiedMember() - { - var markup = - """ + public Task DoNotCrashInExtensionMethoWithExpressionBodiedMember() + => VerifyItemExistsAsync(""" public static class Extensions { public static T Get(this object o) => $$} - """; - await VerifyItemExistsAsync(markup, "o"); - } + """, "o"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task EnumConstraint() - { - var markup = - """ + public Task EnumConstraint() + => VerifyItemExistsAsync(""" public class X where T : System.$$ - """; - await VerifyItemExistsAsync(markup, "Enum"); - } + """, "Enum"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task DelegateConstraint() - { - var markup = - """ + public Task DelegateConstraint() + => VerifyItemExistsAsync(""" public class X where T : System.$$ - """; - await VerifyItemExistsAsync(markup, "Delegate"); - } + """, "Delegate"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task MulticastDelegateConstraint() - { - var markup = - """ + public Task MulticastDelegateConstraint() + => VerifyItemExistsAsync(""" public class X where T : System.$$ - """; - await VerifyItemExistsAsync(markup, "MulticastDelegate"); - } + """, "MulticastDelegate"); private static string CreateThenIncludeTestCode(string lambdaExpressionString, string methodDeclarationString) { @@ -11598,9 +10400,8 @@ public static IIncludableQueryable ThenInclude( } [Fact] - public async Task CompletionForLambdaWithOverloads() - { - var markup = """ + public Task CompletionForLambdaWithOverloads() + => VerifyExpectedItemsAsync(""" using System; using System.Collections; using System.Collections.Generic; @@ -11637,14 +10438,11 @@ void M(SomeCollection c) } } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("Substring"), ItemExpectation.Exists("A"), ItemExpectation.Exists("B"), ]); - } [Fact, WorkItem("https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")] public async Task CompletionForLambdaWithOverloads2() @@ -11713,9 +10511,8 @@ void Test() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42997")] - public async Task CompletionForLambdaWithTypeParameters() - { - var markup = """ + public Task CompletionForLambdaWithTypeParameters() + => VerifyItemExistsAsync(""" using System; using System.Collections.Generic; @@ -11730,15 +10527,11 @@ static void Create(List list, Action expression) { } } class Product { public void MyProperty() { } } - """; - - await VerifyItemExistsAsync(markup, "MyProperty"); - } + """, "MyProperty"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42997")] - public async Task CompletionForLambdaWithTypeParametersAndOverloads() - { - var markup = """ + public Task CompletionForLambdaWithTypeParametersAndOverloads() + => VerifyExpectedItemsAsync(""" using System; using System.Collections.Generic; @@ -11755,18 +10548,14 @@ static void Create(Dictionary list, Action expression) { } class Product1 { public void MyProperty1() { } } class Product2 { public void MyProperty2() { } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("MyProperty1"), ItemExpectation.Exists("MyProperty2"), ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42997")] - public async Task CompletionForLambdaWithTypeParametersAndOverloads2() - { - var markup = """ + public Task CompletionForLambdaWithTypeParametersAndOverloads2() + => VerifyExpectedItemsAsync(""" using System; using System.Collections.Generic; @@ -11785,14 +10574,11 @@ static void Create(Dictionary list, Action express class Product1 { public void MyProperty1() { } } class Product2 { public void MyProperty2() { } } class Product3 { public void MyProperty3() { } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("MyProperty1"), ItemExpectation.Exists("MyProperty2"), ItemExpectation.Exists("MyProperty3") ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParametersFromClass() @@ -11864,9 +10650,8 @@ class Product { public void MyProperty() { } } } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40216")] - public async Task CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameter1() - { - var markup = """ + public Task CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameter1() + => VerifyItemExistsAsync(""" using System; class C @@ -11878,15 +10663,11 @@ void Test() void X(int x = 7, Action y = null) { } } - """; - - await VerifyItemExistsAsync(markup, "Length"); - } + """, "Length"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40216")] - public async Task CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameter2() - { - var markup = """ + public Task CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameter2() + => VerifyItemExistsAsync(""" using System; class C @@ -11898,15 +10679,11 @@ void Test() void X(int x, int z, Action y) { } } - """; - - await VerifyItemExistsAsync(markup, "Length"); - } + """, "Length"); [Fact] - public async Task CompletionForLambdaPassedAsArgumentInReducedExtensionMethod_NonInteractive() - { - var markup = """ + public Task CompletionForLambdaPassedAsArgumentInReducedExtensionMethod_NonInteractive() + => VerifyItemExistsAsync(""" using System; static class CExtensions @@ -11921,14 +10698,11 @@ void Test() new C().X(t => Console.WriteLine(t.$$)); } } - """; - await VerifyItemExistsAsync(markup, "Length", sourceCodeKind: SourceCodeKind.Regular); - } + """, "Length", sourceCodeKind: SourceCodeKind.Regular); [Fact] - public async Task CompletionForLambdaPassedAsArgumentInReducedExtensionMethod_Interactive() - { - var markup = """ + public Task CompletionForLambdaPassedAsArgumentInReducedExtensionMethod_Interactive() + => VerifyItemExistsAsync(""" using System; public static void X(this C x, Action y) { } @@ -11940,14 +10714,11 @@ void Test() new C().X(t => Console.WriteLine(t.$$)); } } - """; - await VerifyItemExistsAsync(markup, "Length", sourceCodeKind: SourceCodeKind.Script); - } + """, "Length", sourceCodeKind: SourceCodeKind.Script); [Fact] - public async Task CompletionInsideMethodsWithNonFunctionsAsArguments() - { - var markup = """ + public Task CompletionInsideMethodsWithNonFunctionsAsArguments() + => VerifyExpectedItemsAsync(""" using System; class c { @@ -11969,21 +10740,17 @@ class Builder { public int Something { get; set; } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("Something"), ItemExpectation.Absent("BeginInvoke"), ItemExpectation.Absent("Clone"), ItemExpectation.Absent("Method"), ItemExpectation.Absent("Target") ]); - } [Fact] - public async Task CompletionInsideMethodsWithDelegatesAsArguments() - { - var markup = """ + public Task CompletionInsideMethodsWithDelegatesAsArguments() + => VerifyExpectedItemsAsync(""" using System; class Program @@ -11999,9 +10766,7 @@ public void Test() M(d => d.$$) } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ // Guid ItemExpectation.Exists("ToByteArray"), @@ -12016,12 +10781,10 @@ await VerifyExpectedItemsAsync(markup, [ ItemExpectation.Absent("Method"), ItemExpectation.Absent("Target") ]); - } [Fact] - public async Task CompletionInsideMethodsWithDelegatesAndReversingArguments() - { - var markup = """ + public Task CompletionInsideMethodsWithDelegatesAndReversingArguments() + => VerifyExpectedItemsAsync(""" using System; class Program @@ -12037,8 +10800,7 @@ public void Test() M(d => d.$$) } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ // Guid ItemExpectation.Exists("ToByteArray"), @@ -12053,12 +10815,10 @@ await VerifyExpectedItemsAsync(markup, [ ItemExpectation.Absent("Method"), ItemExpectation.Absent("Target") ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36029")] - public async Task CompletionInsideMethodWithParamsBeforeParams() - { - var markup = """ + public Task CompletionInsideMethodWithParamsBeforeParams() + => VerifyExpectedItemsAsync(""" using System; class C { @@ -12083,19 +10843,15 @@ class AnotherBuilder { public int AnotherSomething { get; set; } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("AnotherSomething"), ItemExpectation.Absent("FirstOrDefault"), ItemExpectation.Exists("Something") ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36029")] - public async Task CompletionInsideMethodWithParamsInParams() - { - var markup = """ + public Task CompletionInsideMethodWithParamsInParams() + => VerifyExpectedItemsAsync(""" using System; class C { @@ -12117,21 +10873,17 @@ class AnotherBuilder { public int AnotherSomething { get; set; } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("Something"), ItemExpectation.Absent("FirstOrDefault"), ItemExpectation.Exists("AnotherSomething") ]); - } [Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)] public async Task TestTargetTypeFilterWithExperimentEnabled() { ShowTargetTypedCompletionFilter = true; - - var markup = + await VerifyItemExistsAsync( """ public class C { @@ -12141,9 +10893,7 @@ void M(int x) M($$); } } - """; - await VerifyItemExistsAsync( - markup, "intField", + """, "intField", matchingFilters: [FilterSet.FieldFilter, FilterSet.TargetTypedFilter]); } @@ -12151,8 +10901,7 @@ await VerifyItemExistsAsync( public async Task TestNoTargetTypeFilterWithExperimentDisabled() { ShowTargetTypedCompletionFilter = false; - - var markup = + await VerifyItemExistsAsync( """ public class C { @@ -12162,9 +10911,7 @@ void M(int x) M($$); } } - """; - await VerifyItemExistsAsync( - markup, "intField", + """, "intField", matchingFilters: [FilterSet.FieldFilter]); } @@ -12172,8 +10919,7 @@ await VerifyItemExistsAsync( public async Task TestTargetTypeFilter_NotOnObjectMembers() { ShowTargetTypedCompletionFilter = true; - - var markup = + await VerifyItemExistsAsync( """ public class C { @@ -12182,9 +10928,7 @@ void M(int x) M($$); } } - """; - await VerifyItemExistsAsync( - markup, "GetHashCode", + """, "GetHashCode", matchingFilters: [FilterSet.MethodFilter]); } @@ -12213,9 +10957,8 @@ await VerifyItemExistsAsync( } [Fact] - public async Task CompletionShouldNotProvideExtensionMethodsIfTypeConstraintDoesNotMatch() - { - var markup = """ + public Task CompletionShouldNotProvideExtensionMethodsIfTypeConstraintDoesNotMatch() + => VerifyExpectedItemsAsync(""" public static class Ext { public static void DoSomething(this T thing, string s) where T : class, I @@ -12234,9 +10977,7 @@ public void M(string s) this.$$ } } - """; - - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("M"), ItemExpectation.Exists("Equals"), ItemExpectation.Absent("DoSomething") with @@ -12244,13 +10985,11 @@ await VerifyExpectedItemsAsync(markup, [ DisplayTextSuffix = "<>" }, ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38074")] [CompilerTrait(CompilerFeature.LocalFunctions)] - public async Task LocalFunctionInStaticMethod() - { - await VerifyItemExistsAsync(""" + public Task LocalFunctionInStaticMethod() + => VerifyItemExistsAsync(""" class C { static void M() @@ -12261,12 +11000,11 @@ void Local() { } } } """, "Local"); - } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1152109")] - public async Task NoItemWithEmptyDisplayName() - { - var markup = """ + public Task NoItemWithEmptyDisplayName() + => VerifyItemIsAbsentAsync( + """ class C { static void M() @@ -12274,18 +11012,14 @@ static void M() int$$ } } - """; - await VerifyItemIsAbsentAsync( - markup, "", + """, "", matchingFilters: [FilterSet.LocalAndParameterFilter]); - } [Theory] [InlineData('.')] [InlineData(';')] - public async Task CompletionWithCustomizedCommitCharForMethod(char commitChar) - { - var markup = """ + public Task CompletionWithCustomizedCommitCharForMethod(char commitChar) + => VerifyProviderCommitAsync(""" class Program { private void Bar() @@ -12301,8 +11035,7 @@ private void Foo(int i, int c) { } } - """; - var expected = $$""" + """, "Foo", $$""" class Program { private void Bar() @@ -12318,16 +11051,13 @@ private void Foo(int i, int c) { } } - """; - await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar); - } + """, commitChar: commitChar); [Theory] [InlineData('.')] [InlineData(';')] - public async Task CompletionWithSemicolonInNestedMethod(char commitChar) - { - var markup = """ + public Task CompletionWithSemicolonInNestedMethod(char commitChar) + => VerifyProviderCommitAsync(""" class Program { private void Bar() @@ -12340,8 +11070,7 @@ private int Foo(int i) return 1; } } - """; - var expected = $$""" + """, "Foo", $$""" class Program { private void Bar() @@ -12354,16 +11083,13 @@ private int Foo(int i) return 1; } } - """; - await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar); - } + """, commitChar: commitChar); [Theory] [InlineData('.')] [InlineData(';')] - public async Task CompletionWithCustomizedCommitCharForDelegateInferredType(char commitChar) - { - var markup = """ + public Task CompletionWithCustomizedCommitCharForDelegateInferredType(char commitChar) + => VerifyProviderCommitAsync(""" using System; class Program { @@ -12378,8 +11104,7 @@ private void Foo() void Bar2(Action t) { } } - """; - var expected = $$""" + """, "Foo", $$""" using System; class Program { @@ -12394,16 +11119,13 @@ private void Foo() void Bar2(Action t) { } } - """; - await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar); - } + """, commitChar: commitChar); [Theory] [InlineData('.')] [InlineData(';')] - public async Task CompletionWithCustomizedCommitCharForConstructor(char commitChar) - { - var markup = """ + public Task CompletionWithCustomizedCommitCharForConstructor(char commitChar) + => VerifyProviderCommitAsync(""" class Program { private static void Bar() @@ -12411,8 +11133,7 @@ private static void Bar() var o = new P$$ } } - """; - var expected = $$""" + """, "Program", $$""" class Program { private static void Bar() @@ -12420,16 +11141,13 @@ private static void Bar() var o = new Program(){{commitChar}} } } - """; - await VerifyProviderCommitAsync(markup, "Program", expected, commitChar: commitChar); - } + """, commitChar: commitChar); [Theory] [InlineData('.')] [InlineData(';')] - public async Task CompletionWithCustomizedCharForTypeUnderNonObjectCreationContext(char commitChar) - { - var markup = """ + public Task CompletionWithCustomizedCharForTypeUnderNonObjectCreationContext(char commitChar) + => VerifyProviderCommitAsync(""" class Program { private static void Bar() @@ -12437,8 +11155,7 @@ private static void Bar() var o = P$$ } } - """; - var expected = $$""" + """, "Program", $$""" class Program { private static void Bar() @@ -12446,16 +11163,13 @@ private static void Bar() var o = Program{{commitChar}} } } - """; - await VerifyProviderCommitAsync(markup, "Program", expected, commitChar: commitChar); - } + """, commitChar: commitChar); [Theory] [InlineData('.')] [InlineData(';')] - public async Task CompletionWithCustomizedCommitCharForAliasConstructor(char commitChar) - { - var markup = """ + public Task CompletionWithCustomizedCommitCharForAliasConstructor(char commitChar) + => VerifyProviderCommitAsync(""" using String2 = System.String; namespace Bar1 { @@ -12467,8 +11181,7 @@ private static void Bar() } } } - """; - var expected = $$""" + """, "String2", $$""" using String2 = System.String; namespace Bar1 { @@ -12480,14 +11193,11 @@ private static void Bar() } } } - """; - await VerifyProviderCommitAsync(markup, "String2", expected, commitChar: commitChar); - } + """, commitChar: commitChar); [Fact] - public async Task CompletionWithSemicolonUnderNameofContext() - { - var markup = """ + public Task CompletionWithSemicolonUnderNameofContext() + => VerifyProviderCommitAsync(""" namespace Bar1 { class Program @@ -12498,8 +11208,7 @@ private static void Bar() } } } - """; - var expected = """ + """, "Bar", """ namespace Bar1 { class Program @@ -12510,15 +11219,11 @@ private static void Bar() } } } - """; - await VerifyProviderCommitAsync(markup, "Bar", expected, commitChar: ';'); - } + """, commitChar: ';'); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49072")] - public async Task EnumMemberAfterPatternMatch() - { - var markup = - """ + public Task EnumMemberAfterPatternMatch() + => VerifyExpectedItemsAsync(""" namespace N { enum RankedMusicians @@ -12535,20 +11240,15 @@ void M(RankedMusicians m) } } } - """; - // VerifyItemExistsAsync also tests with the item typed. - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("BillyJoel"), ItemExpectation.Exists("EveryoneElse"), ItemExpectation.Absent("Equals"), ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49072")] - public async Task EnumMemberAfterPatternMatchWithDeclaration() - { - var markup = - """ + public Task EnumMemberAfterPatternMatchWithDeclaration() + => VerifyExpectedItemsAsync(""" namespace N { enum RankedMusicians @@ -12567,20 +11267,15 @@ void M(RankedMusicians m) } } } - """; - // VerifyItemExistsAsync also tests with the item typed. - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("BillyJoel"), ItemExpectation.Exists("EveryoneElse"), ItemExpectation.Absent("Equals"), ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49072")] - public async Task EnumMemberAfterPropertyPatternMatch() - { - var markup = - """ + public Task EnumMemberAfterPropertyPatternMatch() + => VerifyExpectedItemsAsync(""" namespace N { enum RankedMusicians @@ -12599,14 +11294,11 @@ void M(C m) } } } - """; - // VerifyItemExistsAsync also tests with the item typed. - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("BillyJoel"), ItemExpectation.Exists("EveryoneElse"), ItemExpectation.Absent("Equals"), ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49072")] public async Task ChildClassAfterPatternMatch() @@ -12632,10 +11324,8 @@ void M(object m) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49072")] - public async Task EnumMemberAfterBinaryExpression() - { - var markup = - """ + public Task EnumMemberAfterBinaryExpression() + => VerifyExpectedItemsAsync(""" namespace N { enum RankedMusicians @@ -12652,20 +11342,15 @@ void M(RankedMusicians m) } } } - """; - // VerifyItemExistsAsync also tests with the item typed. - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("BillyJoel"), ItemExpectation.Exists("EveryoneElse"), ItemExpectation.Absent("Equals"), ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49072")] - public async Task EnumMemberAfterBinaryExpressionWithDeclaration() - { - var markup = - """ + public Task EnumMemberAfterBinaryExpressionWithDeclaration() + => VerifyExpectedItemsAsync(""" namespace N { enum RankedMusicians @@ -12684,20 +11369,15 @@ void M(RankedMusicians m) } } } - """; - // VerifyItemExistsAsync also tests with the item typed. - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("BillyJoel"), ItemExpectation.Exists("EveryoneElse"), ItemExpectation.Absent("Equals"), ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49609")] - public async Task ObsoleteOverloadsAreSkippedIfNonObsoleteOverloadIsAvailable() - { - var markup = - """ + public Task ObsoleteOverloadsAreSkippedIfNonObsoleteOverloadIsAvailable() + => VerifyItemExistsAsync(""" public class C { [System.Obsolete] @@ -12709,16 +11389,12 @@ public void Test() { this.$$ } - } - """; - await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 1 {FeaturesResources.overload})"); - } + } + """, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 1 {FeaturesResources.overload})"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49609")] - public async Task FirstObsoleteOverloadIsUsedIfAllOverloadsAreObsolete() - { - var markup = - """ + public Task FirstObsoleteOverloadIsUsedIfAllOverloadsAreObsolete() + => VerifyItemExistsAsync(""" public class C { [System.Obsolete] @@ -12732,15 +11408,11 @@ public void Test() this.$$ } } - """; - await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"[{CSharpFeaturesResources.deprecated}] void C.M() (+ 1 {FeaturesResources.overload})"); - } + """, "M", expectedDescriptionOrNull: $"[{CSharpFeaturesResources.deprecated}] void C.M() (+ 1 {FeaturesResources.overload})"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49609")] - public async Task IgnoreCustomObsoleteAttribute() - { - var markup = - """ + public Task IgnoreCustomObsoleteAttribute() + => VerifyItemExistsAsync(""" public class ObsoleteAttribute: System.Attribute { } @@ -12757,9 +11429,7 @@ public void Test() this.$$ } } - """; - await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M() (+ 1 {FeaturesResources.overload})"); - } + """, "M", expectedDescriptionOrNull: $"void C.M() (+ 1 {FeaturesResources.overload})"); [InlineData("int", "")] [InlineData("int[]", "int a")] @@ -12768,8 +11438,7 @@ public async Task TestTargetTypeCompletionDescription(string targetType, string { // Check the description displayed is based on symbol matches targeted type ShowTargetTypedCompletionFilter = true; - - var markup = + await VerifyItemExistsAsync( $$""" public class C { @@ -12784,9 +11453,7 @@ void M(C c) N(c.$$); } } - """; - await VerifyItemExistsAsync( - markup, "Bar", + """, "Bar", expectedDescriptionOrNull: $"{targetType} C.Bar({expectedParameterList}) (+{NonBreakingSpaceString}2{NonBreakingSpaceString}{FeaturesResources.overloads_})", matchingFilters: [FilterSet.MethodFilter, FilterSet.TargetTypedFilter]); } @@ -12850,9 +11517,8 @@ void M2() } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestTypesNotSuggestedInDeclarationDeconstruction() - { - await VerifyItemIsAbsentAsync(""" + public Task TestTypesNotSuggestedInDeclarationDeconstruction() + => VerifyItemIsAbsentAsync(""" class C { int M() @@ -12861,12 +11527,10 @@ int M() } } """, "C"); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestTypesSuggestedInMixedDeclarationAndAssignmentInDeconstruction() - { - await VerifyItemExistsAsync(""" + public Task TestTypesSuggestedInMixedDeclarationAndAssignmentInDeconstruction() + => VerifyItemExistsAsync(""" class C { int M() @@ -12875,12 +11539,10 @@ int M() } } """, "C"); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestLocalDeclaredBeforeDeconstructionSuggestedInMixedDeclarationAndAssignmentInDeconstruction() - { - await VerifyItemExistsAsync(""" + public Task TestLocalDeclaredBeforeDeconstructionSuggestedInMixedDeclarationAndAssignmentInDeconstruction() + => VerifyItemExistsAsync(""" class C { int M() @@ -12890,14 +11552,12 @@ int M() } } """, "y"); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("https://github.com/dotnet/roslyn/issues/53930")] [WorkItem("https://github.com/dotnet/roslyn/issues/64733")] - public async Task TestTypeParameterConstrainedToInterfaceWithStatics() - { - var source = """ + public Task TestTypeParameterConstrainedToInterfaceWithStatics() + => VerifyExpectedItemsAsync(""" interface I1 { static void M0(); @@ -12919,8 +11579,7 @@ void M(T x) where T : I1, I2 T.$$ } } - """; - await VerifyExpectedItemsAsync(source, [ + """, [ ItemExpectation.Absent("M0"), ItemExpectation.Exists("M1"), @@ -12929,12 +11588,10 @@ await VerifyExpectedItemsAsync(source, [ ItemExpectation.Exists("P1"), ItemExpectation.Exists("E1") ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58081")] - public async Task CompletionOnPointerParameter() - { - var source = """ + public Task CompletionOnPointerParameter() + => VerifyExpectedItemsAsync(""" struct TestStruct { public int X; @@ -12949,19 +11606,16 @@ void TestMethod(TestStruct* a) a->$$ } } - """; - await VerifyExpectedItemsAsync(source, [ + """, [ ItemExpectation.Exists("X"), ItemExpectation.Exists("Y"), ItemExpectation.Exists("Method"), ItemExpectation.Exists("ToString") ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58081")] - public async Task CompletionOnAwaitedPointerParameter() - { - var source = """ + public Task CompletionOnAwaitedPointerParameter() + => VerifyExpectedItemsAsync(""" struct TestStruct { public int X; @@ -12976,19 +11630,16 @@ async void TestMethod(TestStruct* a) await a->$$ } } - """; - await VerifyExpectedItemsAsync(source, [ + """, [ ItemExpectation.Exists("X"), ItemExpectation.Exists("Y"), ItemExpectation.Exists("Method"), ItemExpectation.Exists("ToString") ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58081")] - public async Task CompletionOnLambdaPointerParameter() - { - var source = """ + public Task CompletionOnLambdaPointerParameter() + => VerifyExpectedItemsAsync(""" struct TestStruct { public int X; @@ -13005,20 +11656,16 @@ TestLambda TestMethod() return a => a->$$ } } - """; - await VerifyExpectedItemsAsync(source, [ + """, [ ItemExpectation.Exists("X"), ItemExpectation.Exists("Y"), ItemExpectation.Exists("Method"), ItemExpectation.Exists("ToString") ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58081")] - public async Task CompletionOnOverloadedLambdaPointerParameter() - { - - var source = """ + public Task CompletionOnOverloadedLambdaPointerParameter() + => VerifyExpectedItemsAsync(""" struct TestStruct1 { public int X; @@ -13045,18 +11692,14 @@ void Overloaded(TestLambda2 lambda) void TestMethod() => Overloaded(a => a->$$); } - """; - await VerifyExpectedItemsAsync(source, [ + """, [ ItemExpectation.Exists("X"), ItemExpectation.Exists("Y") ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58081")] - public async Task CompletionOnOverloadedLambdaPointerParameterWithExplicitType() - { - - var source = """ + public Task CompletionOnOverloadedLambdaPointerParameterWithExplicitType() + => VerifyExpectedItemsAsync(""" struct TestStruct1 { public int X; @@ -13083,17 +11726,14 @@ void Overloaded(TestLambda2 lambda) void TestMethod() => Overloaded((TestStruct1* a) => a->$$); } - """; - await VerifyExpectedItemsAsync(source, [ + """, [ ItemExpectation.Exists("X"), ItemExpectation.Absent("Y") ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58081")] - public async Task CompletionOnPointerParameterWithSimpleMemberAccess() - { - var source = """ + public Task CompletionOnPointerParameterWithSimpleMemberAccess() + => VerifyItemIsAbsentAsync(""" struct TestStruct { public int X; @@ -13108,15 +11748,11 @@ void TestMethod(TestStruct* a) a.$$ } } - """; - await VerifyItemIsAbsentAsync(source, "X"); - } + """, "X"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58081")] - public async Task CompletionOnOverloadedLambdaPointerParameterWithSimpleMemberAccess() - { - - var source = """ + public Task CompletionOnOverloadedLambdaPointerParameterWithSimpleMemberAccess() + => VerifyExpectedItemsAsync(""" struct TestStruct1 { public int X; @@ -13143,18 +11779,14 @@ void Overloaded(TestLambda2 lambda) void TestMethod() => Overloaded(a => a.$$); } - """; - await VerifyExpectedItemsAsync(source, [ + """, [ ItemExpectation.Absent("X"), ItemExpectation.Absent("Y") ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58081")] - public async Task CompletionOnOverloadedLambdaPointerParameterWithSimpleMemberAccessAndExplicitType() - { - - var source = """ + public Task CompletionOnOverloadedLambdaPointerParameterWithSimpleMemberAccessAndExplicitType() + => VerifyExpectedItemsAsync(""" struct TestStruct1 { public int X; @@ -13181,21 +11813,18 @@ void Overloaded(TestLambda2 lambda) void TestMethod() => Overloaded((TestStruct1* a) => a.$$); } - """; - await VerifyExpectedItemsAsync(source, [ + """, [ ItemExpectation.Absent("X"), ItemExpectation.Absent("Y") ]); - } [InlineData("m.MyObject?.$$MyValue!!()")] [InlineData("m.MyObject?.$$MyObject!.MyValue!!()")] [InlineData("m.MyObject?.MyObject!.$$MyValue!!()")] [Theory] [WorkItem("https://github.com/dotnet/roslyn/issues/59714")] - public async Task OptionalExclamationsAfterConditionalAccessShouldBeHandled(string conditionalAccessExpression) - { - var source = $$""" + public Task OptionalExclamationsAfterConditionalAccessShouldBeHandled(string conditionalAccessExpression) + => VerifyItemExistsAsync($$""" class MyClass { public MyClass? MyObject { get; set; } @@ -13207,9 +11836,7 @@ public static void F() {{conditionalAccessExpression}}; } } - """; - await VerifyItemExistsAsync(source, "MyValue"); - } + """, "MyValue"); [Fact] public async Task TopLevelSymbolsAvailableAtTopLevel() @@ -13294,22 +11921,18 @@ void M(int parameter) { } } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60812")] - public async Task ParameterNotAvailableInMethodAttributeNameofWithNoArgument() - { - var source = """ + public Task ParameterNotAvailableInMethodAttributeNameofWithNoArgument() + => VerifyItemExistsAsync(MakeMarkup(""" class C { [Some(nameof($$))] void M(int parameter) { } } - """; - await VerifyItemExistsAsync(MakeMarkup(source), "parameter"); - } + """), "parameter"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66982")] - public async Task CapturedParameters1() - { - var source = """ + public Task CapturedParameters1() + => VerifyItemIsAbsentAsync(MakeMarkup(""" class C { void M(string args) @@ -13320,14 +11943,11 @@ static void LocalFunc() } } } - """; - await VerifyItemIsAbsentAsync(MakeMarkup(source), "args"); - } + """), "args"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66982")] - public async Task CapturedParameters2() - { - var source = """ + public Task CapturedParameters2() + => VerifyItemExistsAsync(MakeMarkup(""" class C { void M(string args) @@ -13338,21 +11958,16 @@ static void LocalFunc() } } } - """; - await VerifyItemExistsAsync(MakeMarkup(source), "args"); - } + """), "args"); [Fact] - public async Task ParameterAvailableInMethodParameterAttributeNameof() - { - var source = """ + public Task ParameterAvailableInMethodParameterAttributeNameof() + => VerifyItemExistsAsync(MakeMarkup(""" class C { void M([Some(nameof(p$$))] int parameter) { } } - """; - await VerifyItemExistsAsync(MakeMarkup(source), "parameter"); - } + """), "parameter"); [Fact] public async Task ParameterAvailableInLocalFunctionAttributeNameof() @@ -13447,22 +12062,19 @@ public async Task ParameterAvailableInDelegateParameterAttributeNameof() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64585")] - public async Task AfterRequired() - { - var source = """ + public Task AfterRequired() + => VerifyAnyItemExistsAsync(""" class C { required $$ } - """; - await VerifyAnyItemExistsAsync(source); - } + """); [Theory, CombinatorialData] public async Task AfterScopedInsideMethod(bool useRef) { var refKeyword = useRef ? "ref " : ""; - var source = $$""" + await VerifyItemExistsAsync(MakeMarkup($$""" class C { void M() @@ -13472,67 +12084,60 @@ void M() } ref struct MyRefStruct { } - """; - await VerifyItemExistsAsync(MakeMarkup(source), "MyRefStruct"); + """), "MyRefStruct"); } [Theory, CombinatorialData] public async Task AfterScopedGlobalStatement_FollowedByRefStruct(bool useRef) { var refKeyword = useRef ? "ref " : ""; - var source = $$""" + await VerifyItemExistsAsync(MakeMarkup($$""" scoped {{refKeyword}}$$ ref struct MyRefStruct { } - """; - await VerifyItemExistsAsync(MakeMarkup(source), "MyRefStruct"); + """), "MyRefStruct"); } [Theory, CombinatorialData] public async Task AfterScopedGlobalStatement_FollowedByStruct(bool useRef) { var refKeyword = useRef ? "ref " : ""; - var source = $$""" + await VerifyItemExistsAsync(MakeMarkup($$""" using System; scoped {{refKeyword}}$$ struct S { } - """; - await VerifyItemExistsAsync(MakeMarkup(source), "ReadOnlySpan", displayTextSuffix: "<>"); + """), "ReadOnlySpan", displayTextSuffix: "<>"); } [Theory, CombinatorialData] public async Task AfterScopedGlobalStatement_FollowedByPartialStruct(bool useRef) { var refKeyword = useRef ? "ref " : ""; - var source = $$""" + await VerifyItemExistsAsync(MakeMarkup($$""" using System; scoped {{refKeyword}}$$ partial struct S { } - """; - await VerifyItemExistsAsync(MakeMarkup(source), "ReadOnlySpan", displayTextSuffix: "<>"); + """), "ReadOnlySpan", displayTextSuffix: "<>"); } [Theory, CombinatorialData] public async Task AfterScopedGlobalStatement_NotFollowedByType(bool useRef) { var refKeyword = useRef ? "ref " : ""; - var source = $""" + await VerifyItemExistsAsync(MakeMarkup($""" using System; scoped {refKeyword}$$ - """; - - await VerifyItemExistsAsync(MakeMarkup(source), "ReadOnlySpan", displayTextSuffix: "<>"); + """), "ReadOnlySpan", displayTextSuffix: "<>"); } [Fact] - public async Task AfterScopedInParameter() - { - var source = """ + public Task AfterScopedInParameter() + => VerifyItemExistsAsync(MakeMarkup(""" class C { void M(scoped $$) @@ -13541,14 +12146,11 @@ void M(scoped $$) } ref struct MyRefStruct { } - """; - await VerifyItemExistsAsync(MakeMarkup(source), "MyRefStruct"); - } + """), "MyRefStruct"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65020")] - public async Task DoNotProvideMemberOnSystemVoid() - { - var source = """ + public Task DoNotProvideMemberOnSystemVoid() + => VerifyItemIsAbsentAsync(MakeMarkup(""" class C { void M1(){} @@ -13562,22 +12164,16 @@ public static class Extension { public static bool ExtMethod(this object x) => false; } - """; - await VerifyItemIsAbsentAsync(MakeMarkup(source), "ExtMethod"); - } + """), "ExtMethod"); [Theory, MemberData(nameof(ValidEnumUnderlyingTypeNames))] - public async Task EnumBaseList1(string underlyingType) - { - var source = "enum E : $$"; - - await VerifyExpectedItemsAsync(source, [ + public Task EnumBaseList1(string underlyingType) + => VerifyExpectedItemsAsync("enum E : $$", [ ItemExpectation.Exists("System"), // Not accessible in the given context ItemExpectation.Absent(underlyingType), ]); - } [Theory, MemberData(nameof(ValidEnumUnderlyingTypeNames))] public async Task EnumBaseList2(string underlyingType) @@ -13598,15 +12194,12 @@ class System } [Theory, MemberData(nameof(ValidEnumUnderlyingTypeNames))] - public async Task EnumBaseList3(string underlyingType) - { - var source = """ + public Task EnumBaseList3(string underlyingType) + => VerifyExpectedItemsAsync(""" using System; enum E : $$ - """; - - await VerifyExpectedItemsAsync(source, [ + """, [ ItemExpectation.Exists("System"), ItemExpectation.Exists(underlyingType), @@ -13616,20 +12209,16 @@ await VerifyExpectedItemsAsync(source, [ ItemExpectation.Absent("Action"), ItemExpectation.Absent("DateTime") ]); - } [Theory, MemberData(nameof(ValidEnumUnderlyingTypeNames))] - public async Task EnumBaseList4(string underlyingType) - { - var source = """ + public Task EnumBaseList4(string underlyingType) + => VerifyExpectedItemsAsync(""" namespace MyNamespace { } enum E : global::$$ - """; - - await VerifyExpectedItemsAsync(source, [ + """, [ ItemExpectation.Absent("E"), ItemExpectation.Exists("System"), @@ -13638,14 +12227,10 @@ await VerifyExpectedItemsAsync(source, [ // Not accessible in the given context ItemExpectation.Absent(underlyingType) ]); - } [Theory, MemberData(nameof(ValidEnumUnderlyingTypeNames))] - public async Task EnumBaseList5(string underlyingType) - { - var source = "enum E : System.$$"; - - await VerifyExpectedItemsAsync(source, [ + public Task EnumBaseList5(string underlyingType) + => VerifyExpectedItemsAsync("enum E : System.$$", [ ItemExpectation.Absent("System"), ItemExpectation.Exists(underlyingType), @@ -13655,14 +12240,10 @@ await VerifyExpectedItemsAsync(source, [ ItemExpectation.Absent("Action"), ItemExpectation.Absent("DateTime") ]); - } [Theory, MemberData(nameof(ValidEnumUnderlyingTypeNames))] - public async Task EnumBaseList6(string underlyingType) - { - var source = "enum E : global::System.$$"; - - await VerifyExpectedItemsAsync(source, [ + public Task EnumBaseList6(string underlyingType) + => VerifyExpectedItemsAsync("enum E : global::System.$$", [ ItemExpectation.Absent("System"), ItemExpectation.Exists(underlyingType), @@ -13672,20 +12253,14 @@ await VerifyExpectedItemsAsync(source, [ ItemExpectation.Absent("Action"), ItemExpectation.Absent("DateTime") ]); - } [Fact] - public async Task EnumBaseList7() - { - var source = "enum E : System.Collections.Generic.$$"; - - await VerifyNoItemsExistAsync(source); - } + public Task EnumBaseList7() + => VerifyNoItemsExistAsync("enum E : System.Collections.Generic.$$"); [Fact] - public async Task EnumBaseList8() - { - var source = """ + public Task EnumBaseList8() + => VerifyNoItemsExistAsync(""" namespace MyNamespace { namespace System {} @@ -13700,45 +12275,31 @@ public struct UInt64 {} } enum E : MyNamespace.$$ - """; - - await VerifyNoItemsExistAsync(source); - } + """); [Fact] - public async Task EnumBaseList9() - { - var source = """ + public Task EnumBaseList9() + => VerifyItemExistsAsync(""" using MySystem = System; enum E : $$ - """; - - await VerifyItemExistsAsync(source, "MySystem"); - } + """, "MySystem"); [Fact] - public async Task EnumBaseList10() - { - var source = """ + public Task EnumBaseList10() + => VerifyItemIsAbsentAsync(""" using MySystem = System; enum E : global::$$ - """; - - await VerifyItemIsAbsentAsync(source, "MySystem"); - } + """, "MySystem"); [Theory, MemberData(nameof(ValidEnumUnderlyingTypeNames))] - public async Task EnumBaseList11(string underlyingType) - { - var source = """ + public Task EnumBaseList11(string underlyingType) + => VerifyExpectedItemsAsync(""" using MySystem = System; enum E : MySystem.$$ - """; - - await VerifyExpectedItemsAsync(source, [ + """, [ ItemExpectation.Absent("System"), ItemExpectation.Absent("MySystem"), @@ -13749,74 +12310,51 @@ await VerifyExpectedItemsAsync(source, [ ItemExpectation.Absent("Action"), ItemExpectation.Absent("DateTime") ]); - } [Fact] - public async Task EnumBaseList12() - { - var source = """ + public Task EnumBaseList12() + => VerifyNoItemsExistAsync(""" using MySystem = System; enum E : global::MySystem.$$ - """; - - await VerifyNoItemsExistAsync(source); - } + """); [Theory, MemberData(nameof(ValidEnumUnderlyingTypeNames))] - public async Task EnumBaseList13(string underlyingType) - { - var source = $""" + public Task EnumBaseList13(string underlyingType) + => VerifyItemExistsAsync($""" using My{underlyingType} = System.{underlyingType}; enum E : $$ - """; - - await VerifyItemExistsAsync(source, $"My{underlyingType}"); - } + """, $"My{underlyingType}"); [Theory, MemberData(nameof(ValidEnumUnderlyingTypeNames))] - public async Task EnumBaseList14(string underlyingType) - { - var source = $""" + public Task EnumBaseList14(string underlyingType) + => VerifyItemIsAbsentAsync($""" using My{underlyingType} = System.{underlyingType}; enum E : global::$$ - """; - - await VerifyItemIsAbsentAsync(source, $"My{underlyingType}"); - } + """, $"My{underlyingType}"); [Theory, MemberData(nameof(ValidEnumUnderlyingTypeNames))] - public async Task EnumBaseList15(string underlyingType) - { - var source = $""" + public Task EnumBaseList15(string underlyingType) + => VerifyItemIsAbsentAsync($""" using My{underlyingType} = System.{underlyingType}; enum E : System.$$ - """; - - await VerifyItemIsAbsentAsync(source, $"My{underlyingType}"); - - } + """, $"My{underlyingType}"); [Theory, MemberData(nameof(ValidEnumUnderlyingTypeNames))] - public async Task EnumBaseList16(string underlyingType) - { - var source = $""" + public Task EnumBaseList16(string underlyingType) + => VerifyItemIsAbsentAsync($""" using MySystem = System; using My{underlyingType} = System.{underlyingType}; enum E : MySystem.$$ - """; - - await VerifyItemIsAbsentAsync(source, $"My{underlyingType}"); - } + """, $"My{underlyingType}"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66903")] - public async Task InRangeExpression() - { - var source = """ + public Task InRangeExpression() + => VerifyExpectedItemsAsync(""" class C { const int Test = 1; @@ -13827,19 +12365,15 @@ void M(string s) var substr = s[1..$$]; } } - """; - - await VerifyExpectedItemsAsync(source, [ + """, [ ItemExpectation.Exists("endIndex"), ItemExpectation.Exists("Test"), ItemExpectation.Exists("C"), ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66903")] - public async Task InRangeExpression_WhitespaceAfterDotDotToken() - { - var source = """ + public Task InRangeExpression_WhitespaceAfterDotDotToken() + => VerifyExpectedItemsAsync(""" class C { const int Test = 1; @@ -13850,19 +12384,15 @@ void M(string s) var substr = s[1.. $$]; } } - """; - - await VerifyExpectedItemsAsync(source, [ + """, [ ItemExpectation.Exists("endIndex"), ItemExpectation.Exists("Test"), ItemExpectation.Exists("C"), ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25572")] - public async Task PropertyAndGenericExtensionMethodCandidates() - { - var source = """ + public Task PropertyAndGenericExtensionMethodCandidates() + => VerifyExpectedItemsAsync(""" using System.Collections.Generic; using System.Linq; @@ -13877,20 +12407,16 @@ void M() } } } - """; - - await VerifyExpectedItemsAsync(source, [ + """, [ ItemExpectation.Exists("foo"), ItemExpectation.Exists("M"), ItemExpectation.Exists("System"), ItemExpectation.Absent("Int32"), ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25572")] - public async Task GenericWithNonGenericOverload() - { - var source = """ + public Task GenericWithNonGenericOverload() + => VerifyExpectedItemsAsync(""" class C { void M(C other) @@ -13903,14 +12429,11 @@ void M(C other) void A() { } void A() { } } - """; - - await VerifyExpectedItemsAsync(source, [ + """, [ ItemExpectation.Exists("System"), ItemExpectation.Exists("C"), ItemExpectation.Absent("other"), ]); - } public static readonly IEnumerable PatternMatchingPrecedingPatterns = new object[][] { @@ -14882,9 +13405,8 @@ IEnumerable M() => [string.Empty, .. ($$ [InlineData("struct")] [InlineData("record class")] [InlineData("record struct")] - public async Task RecommendedPrimaryConstructorParameters01(string typeKind) - { - var markup = $$""" + public Task RecommendedPrimaryConstructorParameters01(string typeKind) + => VerifyExpectedItemsAsync($$""" namespace PrimaryConstructor; public {{typeKind}} Point(int X, int Y) @@ -14894,19 +13416,16 @@ public static Point Parse(string line) $$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("X"), ItemExpectation.Absent("Y"), ]); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/74327")] [InlineData("class")] [InlineData("record class")] - public async Task RecommendedPrimaryConstructorParameters02(string typeKind) - { - var markup = $$""" + public Task RecommendedPrimaryConstructorParameters02(string typeKind) + => VerifyExpectedItemsAsync($$""" namespace PrimaryConstructor; public abstract {{typeKind}} BasePoint(int X); @@ -14919,19 +13438,16 @@ public static Point Parse(string line) $$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("X"), ItemExpectation.Absent("Y"), ]); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/74327")] [InlineData("class")] [InlineData("record class")] - public async Task RecommendedPrimaryConstructorParameters03(string typeKind) - { - var markup = $$""" + public Task RecommendedPrimaryConstructorParameters03(string typeKind) + => VerifyExpectedItemsAsync($$""" namespace PrimaryConstructor; public abstract {{typeKind}} BasePoint(int X); @@ -14946,21 +13462,18 @@ public static Point Parse(string line) $$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("X"), ItemExpectation.Absent("Y"), ]); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/74327")] [InlineData("class")] [InlineData("struct")] [InlineData("record class")] [InlineData("record struct")] - public async Task RecommendedPrimaryConstructorParameters04(string typeKind) - { - var markup = $$""" + public Task RecommendedPrimaryConstructorParameters04(string typeKind) + => VerifyExpectedItemsAsync($$""" namespace PrimaryConstructor; public {{typeKind}} Point(int X, int Y) @@ -14970,19 +13483,16 @@ public static Point Parse(string line) var n = nameof($$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("X"), ItemExpectation.Exists("Y"), ]); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/74327")] [InlineData("record class")] [InlineData("class")] - public async Task RecommendedPrimaryConstructorParameters05(string typeKind) - { - var markup = $$""" + public Task RecommendedPrimaryConstructorParameters05(string typeKind) + => VerifyExpectedItemsAsync($$""" namespace PrimaryConstructor; public abstract {{typeKind}} BasePoint(int X); @@ -14995,19 +13505,16 @@ public static Point Parse(string line) var n = nameof($$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("X"), ItemExpectation.Exists("Y"), ]); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/74327")] [InlineData("record")] [InlineData("class")] - public async Task RecommendedPrimaryConstructorParameters06(string typeKind) - { - var markup = $$""" + public Task RecommendedPrimaryConstructorParameters06(string typeKind) + => VerifyExpectedItemsAsync($$""" namespace PrimaryConstructor; public abstract {{typeKind}} BasePoint(int X); @@ -15022,21 +13529,18 @@ public static Point Parse(string line) var n = nameof($$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("X"), ItemExpectation.Exists("Y"), ]); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/74327")] [InlineData("class")] [InlineData("struct")] [InlineData("record class")] [InlineData("record struct")] - public async Task RecommendedPrimaryConstructorParameters07(string typeKind) - { - var markup = $$""" + public Task RecommendedPrimaryConstructorParameters07(string typeKind) + => VerifyExpectedItemsAsync($$""" namespace PrimaryConstructor; public {{typeKind}} Point(int X, int Y) @@ -15048,21 +13552,18 @@ public static Point Parse(string line) $$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Absent("X"), ItemExpectation.Exists("Y"), ]); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/74327")] [InlineData("class")] [InlineData("struct")] [InlineData("record class")] [InlineData("record struct")] - public async Task RecommendedPrimaryConstructorParameters08(string typeKind) - { - var markup = $$""" + public Task RecommendedPrimaryConstructorParameters08(string typeKind) + => VerifyExpectedItemsAsync($$""" namespace PrimaryConstructor; public {{typeKind}} Point(int X, int Y) @@ -15074,33 +13575,28 @@ public static Point Parse(string line) var n = nameof($$ } } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("X"), ItemExpectation.Exists("Y"), ]); - } [Theory, CombinatorialData] - public async Task PartialPropertyOrConstructor( + public Task PartialPropertyOrConstructor( [CombinatorialValues("class", "struct", "record", "record class", "record struct", "interface")] string typeKind, [CombinatorialValues("", "public", "private", "static", "extern")] string modifiers) - { - var markup = $$""" + => VerifyExpectedItemsAsync($$""" partial {{typeKind}} C { {{modifiers}} partial $$ } - """; - await VerifyExpectedItemsAsync(markup, [ + """, [ ItemExpectation.Exists("C"), ]); - } [Fact] - public async Task ModernExtensionMethod1() - { - var source = """ + public Task ModernExtensionMethod1() + => VerifyItemExistsAsync( + MakeMarkup(""" static class C { extension(string s) @@ -15113,13 +13609,10 @@ void M(string s) s.$$ } } - """; - await VerifyItemExistsAsync( - MakeMarkup(source), + """), "IsNullOrEmpty", sourceCodeKind: SourceCodeKind.Regular, glyph: Glyph.ExtensionMethodPublic); - } private static string MakeMarkup( [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string source, diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SymbolCompletionProviderTests_NoInteractive.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SymbolCompletionProviderTests_NoInteractive.cs index 9605f91f3aefb..8b706b935d906 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SymbolCompletionProviderTests_NoInteractive.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SymbolCompletionProviderTests_NoInteractive.cs @@ -70,77 +70,64 @@ public async Task GlobalStatement1() => await VerifyItemExistsAsync(@"System.Console.$$", @"Beep"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44423")] - public async Task GlobalStatement2() - { - await VerifyItemExistsAsync(""" + public Task GlobalStatement2() + => VerifyItemExistsAsync(""" using System; Console.$$ """, @"Beep"); - } [Fact] public async Task InvalidLocation3() => await VerifyItemIsAbsentAsync(@"using System.Console.$$", @"Beep"); [Fact] - public async Task InvalidLocation4() - { - await VerifyItemIsAbsentAsync(""" + public Task InvalidLocation4() + => VerifyItemIsAbsentAsync(""" class C { #if false System.Console.$$ #endif """, @"Beep"); - } [Fact] - public async Task InvalidLocation5() - { - await VerifyItemIsAbsentAsync(""" + public Task InvalidLocation5() + => VerifyItemIsAbsentAsync(""" class C { #if true System.Console.$$ #endif """, @"Beep"); - } [Fact] - public async Task InvalidLocation6() - { - await VerifyItemIsAbsentAsync(""" + public Task InvalidLocation6() + => VerifyItemIsAbsentAsync(""" using System; class C { // Console.$$ """, @"Beep"); - } [Fact] - public async Task InvalidLocation7() - { - await VerifyItemIsAbsentAsync(""" + public Task InvalidLocation7() + => VerifyItemIsAbsentAsync(""" using System; class C { /* Console.$$ */ """, @"Beep"); - } [Fact] - public async Task InvalidLocation8() - { - await VerifyItemIsAbsentAsync(""" + public Task InvalidLocation8() + => VerifyItemIsAbsentAsync(""" using System; class C { /// Console.$$ """, @"Beep"); - } [Fact] - public async Task InvalidLocation9() - { - await VerifyItemIsAbsentAsync(""" + public Task InvalidLocation9() + => VerifyItemIsAbsentAsync(""" using System; class C { @@ -150,12 +137,10 @@ void Method() } } """, @"Beep"); - } [Fact] - public async Task InvalidLocation10() - { - await VerifyItemIsAbsentAsync(""" + public Task InvalidLocation10() + => VerifyItemIsAbsentAsync(""" using System; class C { @@ -163,7 +148,6 @@ void Method() { /** Console.$$ */ """, @"Beep"); - } [Fact] public async Task InvalidLocation11() @@ -174,40 +158,32 @@ public async Task InvalidLocation12() => await VerifyItemIsAbsentAsync(@"[assembly: System.Console.$$]", @"Beep"); [Fact] - public async Task InvalidLocation13() - { - var content = """ + public Task InvalidLocation13() + => VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", """ [Console.$$] class CL {} - """; - - await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"Beep"); - } + """), @"Beep"); [Fact] public async Task InvalidLocation14() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<[Console.$$]T> {}"), @"Beep"); [Fact] - public async Task InvalidLocation15() - { - var content = """ + public Task InvalidLocation15() + => VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", """ class CL { [Console.$$] void Method() {} } - """; - await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"Beep"); - } + """), @"Beep"); [Fact] public async Task InvalidLocation16() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL VerifyItemIsAbsentAsync(""" using System; class Program { @@ -217,12 +193,10 @@ static void Main(string[] args) } } """, @"Main"); - } [Fact] - public async Task InvalidLocation18() - { - await VerifyItemIsAbsentAsync(""" + public Task InvalidLocation18() + => VerifyItemIsAbsentAsync(""" using System; class Program { @@ -233,12 +207,10 @@ static void Main(string[] args) } } """, @"Main"); - } [Fact] - public async Task InvalidLocation19() - { - await VerifyItemIsAbsentAsync(""" + public Task InvalidLocation19() + => VerifyItemIsAbsentAsync(""" using System; class Program { @@ -248,12 +220,10 @@ static void Main(string[] args) } } """, @"SByte"); - } [Fact] - public async Task InsideMethodBody() - { - await VerifyItemExistsAsync(""" + public Task InsideMethodBody() + => VerifyItemExistsAsync(""" using System; class C { @@ -261,16 +231,14 @@ void Method() { Console.$$ """, @"Beep"); - } [Fact] public async Task UsingDirectiveGlobal() => await VerifyItemExistsAsync(@"using global::$$;", @"System"); [Fact] - public async Task InsideAccessor() - { - await VerifyItemExistsAsync(""" + public Task InsideAccessor() + => VerifyItemExistsAsync(""" using System; class C { @@ -280,32 +248,26 @@ string Property { Console.$$ """, @"Beep"); - } [Fact] - public async Task FieldInitializer() - { - await VerifyItemExistsAsync(""" + public Task FieldInitializer() + => VerifyItemExistsAsync(""" using System; class C { int i = Console.$$ """, @"Beep"); - } [Fact] - public async Task FieldInitializer2() - { - await VerifyItemExistsAsync(""" + public Task FieldInitializer2() + => VerifyItemExistsAsync(""" class C { object i = $$ """, @"System"); - } [Fact] - public async Task ImportedProperty() - { - await VerifyItemExistsAsync(""" + public Task ImportedProperty() + => VerifyItemExistsAsync(""" using System.Collections.Generic; class C { @@ -313,22 +275,18 @@ void Method() { new List().$$ """, @"Capacity"); - } [Fact] - public async Task FieldInitializerWithProperty() - { - await VerifyItemExistsAsync(""" + public Task FieldInitializerWithProperty() + => VerifyItemExistsAsync(""" using System.Collections.Generic; class C { int i = new List().$$ """, @"Count"); - } [Fact] - public async Task StaticMethods() - { - await VerifyItemExistsAsync(""" + public Task StaticMethods() + => VerifyItemExistsAsync(""" using System; class C { @@ -336,7 +294,6 @@ private static int Method() {} int i = $$ """, @"Method"); - } [Fact] public async Task EndOfFile() diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/TupleNameCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/TupleNameCompletionProviderTests.cs index d3cabd8fd0a31..41da300682d74 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/TupleNameCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/TupleNameCompletionProviderTests.cs @@ -19,9 +19,8 @@ public sealed class TupleNameCompletionProviderTests : AbstractCSharpCompletionP internal override Type GetCompletionProviderType() => typeof(TupleNameCompletionProvider); [Fact] - public async Task AfterOpenParen() - { - await VerifyItemExistsAsync(""" + public Task AfterOpenParen() + => VerifyItemExistsAsync(""" class Program { static void Main(string[] args) @@ -30,12 +29,10 @@ static void Main(string[] args) } } """, "word", displayTextSuffix: ":"); - } [Fact] - public async Task AfterOpenParenWithBraceCompletion() - { - await VerifyItemExistsAsync(""" + public Task AfterOpenParenWithBraceCompletion() + => VerifyItemExistsAsync(""" class Program { static void Main(string[] args) @@ -44,12 +41,10 @@ static void Main(string[] args) } } """, "word", displayTextSuffix: ":"); - } [Fact] - public async Task AfterOpenParenInTupleExpression() - { - await VerifyItemExistsAsync(""" + public Task AfterOpenParenInTupleExpression() + => VerifyItemExistsAsync(""" class Program { static void Main(string[] args) @@ -58,12 +53,10 @@ static void Main(string[] args) } } """, "word", displayTextSuffix: ":"); - } [Fact] - public async Task AfterOpenParenInTupleExpressionWithBraceCompletion() - { - await VerifyItemExistsAsync(""" + public Task AfterOpenParenInTupleExpressionWithBraceCompletion() + => VerifyItemExistsAsync(""" class Program { static void Main(string[] args) @@ -72,12 +65,10 @@ static void Main(string[] args) } } """, "word", displayTextSuffix: ":"); - } [Fact] - public async Task AfterComma() - { - await VerifyItemExistsAsync(""" + public Task AfterComma() + => VerifyItemExistsAsync(""" class Program { static void Main(string[] args) @@ -86,12 +77,10 @@ static void Main(string[] args) } } """, "zword", displayTextSuffix: ":"); - } [Fact] - public async Task AfterCommaWithBraceCompletion() - { - await VerifyItemExistsAsync(""" + public Task AfterCommaWithBraceCompletion() + => VerifyItemExistsAsync(""" class Program { static void Main(string[] args) @@ -100,12 +89,10 @@ static void Main(string[] args) } } """, "zword", displayTextSuffix: ":"); - } [Fact] - public async Task InTupleAsArgument() - { - await VerifyItemExistsAsync(""" + public Task InTupleAsArgument() + => VerifyItemExistsAsync(""" class Program { static void Main((int word, int zword) args) @@ -114,7 +101,6 @@ static void Main((int word, int zword) args) } } """, "word", displayTextSuffix: ":"); - } [Fact] public async Task MultiplePossibleTuples() @@ -149,9 +135,8 @@ static void Main((string word, int zword) args) { } [Fact] - public async Task AtIndexGreaterThanNumberOfTupleElements() - { - var markup = """ + public Task AtIndexGreaterThanNumberOfTupleElements() + => VerifyNoItemsExistAsync(""" class Program { static void Main(string[] args) @@ -159,14 +144,11 @@ static void Main(string[] args) (int word, int zword) t = (1, 2, 3, 4, $$ } } - """; - await VerifyNoItemsExistAsync(markup); - } + """); [Fact] - public async Task ConvertCastToTupleExpression() - { - var markup = """ + public Task ConvertCastToTupleExpression() + => VerifyItemExistsAsync(""" class C { void goo() @@ -174,7 +156,5 @@ void goo() (int goat, int moat) x = (g$$)1; } } - """; - await VerifyItemExistsAsync(markup, "goat", displayTextSuffix: ":"); - } + """, "goat", displayTextSuffix: ":"); } diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/TypeImportCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/TypeImportCompletionProviderTests.cs index 2362a89450db1..a65ae36deeacf 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/TypeImportCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/TypeImportCompletionProviderTests.cs @@ -37,11 +37,12 @@ public async Task OptionSetToTrue(bool? optionValue) { ShowImportCompletionItemsOptionValue = optionValue; - var markup = @" -class Bar -{ - $$ -}"; + var markup = """ + class Bar + { + $$ + } + """; if (!optionValue.HasValue || optionValue.Value) { @@ -61,28 +62,26 @@ class Bar [InlineData("enum", (int)Glyph.EnumPublic)] [InlineData("interface", (int)Glyph.InterfacePublic)] [Theory] - public async Task Show_TopLevel_NoImport_InProject(string typeKind, int glyph) - { - var file1 = $@" -namespace Foo -{{ - public {typeKind} Bar - {{}} -}}"; - var file2 = @" -namespace Baz -{ - class Bat - { - $$ - } -}"; - await VerifyTypeImportItemExistsAsync( - CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp), + public Task Show_TopLevel_NoImport_InProject(string typeKind, int glyph) + => VerifyTypeImportItemExistsAsync( + CreateMarkupForSingleProject(""" + namespace Baz + { + class Bat + { + $$ + } + } + """, $$""" + namespace Foo + { + public {{typeKind}} Bar + {} + } + """, LanguageNames.CSharp), "Bar", glyph: glyph, inlineDescription: "Foo"); - } [InlineData("class", (int)Glyph.ClassPublic)] [InlineData("record", (int)Glyph.ClassPublic)] @@ -90,23 +89,20 @@ await VerifyTypeImportItemExistsAsync( [InlineData("enum", (int)Glyph.EnumPublic)] [InlineData("interface", (int)Glyph.InterfacePublic)] [Theory] - public async Task Show_TopLevelStatement_NoImport_InProject(string typeKind, int glyph) - { - var file1 = $@" -namespace Foo -{{ - public {typeKind} Bar - {{}} -}}"; - var file2 = @" -$$ -"; - await VerifyTypeImportItemExistsAsync( - CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp), + public Task Show_TopLevelStatement_NoImport_InProject(string typeKind, int glyph) + => VerifyTypeImportItemExistsAsync( + CreateMarkupForSingleProject(""" + $$ + """, $$""" + namespace Foo + { + public {{typeKind}} Bar + {} + } + """, LanguageNames.CSharp), "Bar", glyph: glyph, inlineDescription: "Foo"); - } [InlineData("class")] [InlineData("record")] @@ -114,27 +110,25 @@ await VerifyTypeImportItemExistsAsync( [InlineData("enum")] [InlineData("interface")] [Theory] - public async Task DoNotShow_TopLevel_SameNamespace_InProject(string typeKind) - { - var file1 = $@" -namespace Foo -{{ - public {typeKind} Bar - {{}} -}}"; - var file2 = @" -namespace Foo -{ - class Bat - { - $$ - } -}"; - await VerifyTypeImportItemIsAbsentAsync( - CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp), + public Task DoNotShow_TopLevel_SameNamespace_InProject(string typeKind) + => VerifyTypeImportItemIsAbsentAsync( + CreateMarkupForSingleProject(""" + namespace Foo + { + class Bat + { + $$ + } + } + """, $$""" + namespace Foo + { + public {{typeKind}} Bar + {} + } + """, LanguageNames.CSharp), "Bar", inlineDescription: "Foo"); - } [InlineData("class", (int)Glyph.ClassPublic)] [InlineData("record", (int)Glyph.ClassPublic)] @@ -143,27 +137,29 @@ await VerifyTypeImportItemIsAbsentAsync( [Theory] public async Task Show_TopLevel_MutipleOverrides_NoImport_InProject(string typeKind, int glyph) { - var file1 = $@" -namespace Foo -{{ - public {typeKind} Bar - {{}} + var file1 = $$""" + namespace Foo + { + public {{typeKind}} Bar + {} - public {typeKind} Bar - {{}} + public {{typeKind}} Bar + {} - public {typeKind} Bar - {{}} -}}"; + public {{typeKind}} Bar + {} + } + """; - var file2 = @" -namespace Baz -{ - class Bat - { - $$ - } -}"; + var file2 = """ + namespace Baz + { + class Bat + { + $$ + } + } + """; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: glyph, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: glyph, inlineDescription: "Foo"); @@ -177,23 +173,25 @@ class Bat [Theory] public async Task DoNotShow_NestedType_NoImport_InProject(string typeKind) { - var file1 = $@" -namespace Foo -{{ - public class Bar - {{ - public {typeKind} Faz {{}} - }} -}}"; - - var file2 = @" -namespace Baz -{ - class Bat - { - $$ - } -}"; + var file1 = $$""" + namespace Foo + { + public class Bar + { + public {{typeKind}} Faz {} + } + } + """; + + var file2 = """ + namespace Baz + { + class Bat + { + $$ + } + } + """; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemIsAbsentAsync(markup, "Faz", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Faz", inlineDescription: "Foo.Bar"); @@ -207,23 +205,25 @@ class Bat [Theory] public async Task DoNotShow_TopLevel_WithImport_InProject(string typeKind) { - var file1 = $@" -namespace Foo -{{ - public {typeKind} Bar - {{}} -}}"; - - var file2 = @" -namespace Baz -{ - using Foo; + var file1 = $$""" + namespace Foo + { + public {{typeKind}} Bar + {} + } + """; - class Bat - { - $$ - } -}"; + var file2 = """ + namespace Baz + { + using Foo; + + class Bat + { + $$ + } + } + """; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); } @@ -231,23 +231,25 @@ class Bat [Theory, CombinatorialData] public async Task Show_TopLevel_Public_NoImport_InReference(bool isProjectReference) { - var file1 = $@" -namespace Foo -{{ - public class Bar - {{}} - - public record Bar2 - {{}} -}}"; - var file2 = @" -namespace Baz -{ - class Bat - { - $$ - } -}"; + var file1 = $$""" + namespace Foo + { + public class Bar + {} + + public record Bar2 + {} + } + """; + var file2 = """ + namespace Baz + { + class Bat + { + $$ + } + } + """; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar2", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); @@ -256,24 +258,26 @@ class Bat [Theory, CombinatorialData] public async Task DoNotShow_TopLevel_Public_WithImport_InReference(bool isProjectReference) { - var file1 = $@" -namespace Foo -{{ - public class Bar - {{}} - - public record Bar2 - {{}} -}}"; - var file2 = @" -using Foo; -namespace Baz -{ - class Bat - { - $$ - } -}"; + var file1 = $$""" + namespace Foo + { + public class Bar + {} + + public record Bar2 + {} + } + """; + var file2 = """ + using Foo; + namespace Baz + { + class Bat + { + $$ + } + } + """; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar2", inlineDescription: "Foo"); @@ -282,23 +286,25 @@ class Bat [Theory, CombinatorialData] public async Task DoNotShow_TopLevel_Internal_NoImport_InReference(bool isProjectReference) { - var file1 = $@" -namespace Foo -{{ - internal class Bar - {{}} - - internal record Bar2 - {{}} -}}"; - var file2 = @" -namespace Baz -{ - class Bat - { - $$ - } -}"; + var file1 = $$""" + namespace Foo + { + internal class Bar + {} + + internal record Bar2 + {} + } + """; + var file2 = """ + namespace Baz + { + class Bat + { + $$ + } + } + """; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar2", inlineDescription: "Foo"); @@ -307,23 +313,25 @@ class Bat [Theory, CombinatorialData] public async Task TopLevel_OverloadsWithMixedAccessibility_Internal_NoImport_InReference1(bool isProjectReference) { - var file1 = $@" -namespace Foo -{{ - internal class Bar - {{}} - - public class Bar - {{}} -}}"; - var file2 = @" -namespace Baz -{ - class Bat - { - $$ - } -}"; + var file1 = $$""" + namespace Foo + { + internal class Bar + {} + + public class Bar + {} + } + """; + var file2 = """ + namespace Baz + { + class Bat + { + $$ + } + } + """; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "", inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); @@ -332,24 +340,26 @@ class Bat [Theory, CombinatorialData] public async Task DoNotShow_TopLevel_OverloadsWithMixedAccessibility_Internal_WithImport_InReference1(bool isProjectReference) { - var file1 = $@" -namespace Foo -{{ - internal class Bar - {{}} - - public class Bar - {{}} -}}"; - var file2 = @" -using Foo; -namespace Baz -{ - class Bat - { - $$ - } -}"; + var file1 = $$""" + namespace Foo + { + internal class Bar + {} + + public class Bar + {} + } + """; + var file2 = """ + using Foo; + namespace Baz + { + class Bat + { + $$ + } + } + """; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "<>", inlineDescription: "Foo"); @@ -358,25 +368,27 @@ class Bat [Theory, CombinatorialData] public async Task TopLevel_OverloadsWithMixedAccessibility_InternalWithIVT_NoImport_InReference1(bool isProjectReference) { - var file1 = $@" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project1"")] - -namespace Foo -{{ - internal class Bar - {{}} - - public class Bar - {{}} -}}"; - var file2 = @" -namespace Baz -{ - class Bat - { - $$ - } -}"; + var file1 = $$""" + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Project1")] + + namespace Foo + { + internal class Bar + {} + + public class Bar + {} + } + """; + var file2 = """ + namespace Baz + { + class Bat + { + $$ + } + } + """; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassInternal, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); @@ -385,26 +397,28 @@ class Bat [Theory, CombinatorialData] public async Task DoNotShow_TopLevel_OverloadsWithMixedAccessibility_InternalWithIVT_WithImport_InReference1(bool isProjectReference) { - var file1 = $@" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project1"")] - -namespace Foo -{{ - internal class Bar - {{}} - - public class Bar - {{}} -}}"; - var file2 = @" -using Foo; -namespace Baz -{ - class Bat - { - $$ - } -}"; + var file1 = $$""" + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Project1")] + + namespace Foo + { + internal class Bar + {} + + public class Bar + {} + } + """; + var file2 = """ + using Foo; + namespace Baz + { + class Bat + { + $$ + } + } + """; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "<>", inlineDescription: "Foo"); @@ -413,26 +427,28 @@ class Bat [Theory, CombinatorialData] public async Task TopLevel_OverloadsWithMixedAccessibility_Internal_NoImport_InReference2(bool isProjectReference) { - var file1 = $@" -namespace Foo -{{ - public class Bar - {{}} - - public class Bar - {{}} - - internal class Bar - {{}} -}}"; - var file2 = @" -namespace Baz -{ - class Bat - { - $$ - } -}"; + var file1 = $$""" + namespace Foo + { + public class Bar + {} + + public class Bar + {} + + internal class Bar + {} + } + """; + var file2 = """ + namespace Baz + { + class Bat + { + $$ + } + } + """; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); @@ -441,26 +457,28 @@ class Bat [Theory, CombinatorialData] public async Task DoNotShow_TopLevel_OverloadsWithMixedAccessibility_Internal_SameNamespace_InReference2(bool isProjectReference) { - var file1 = $@" -namespace Foo -{{ - public class Bar - {{}} - - public class Bar - {{}} - - internal class Bar - {{}} -}}"; - var file2 = @" -namespace Foo.Baz -{ - class Bat - { - $$ - } -}"; + var file1 = $$""" + namespace Foo + { + public class Bar + {} + + public class Bar + {} + + internal class Bar + {} + } + """; + var file2 = """ + namespace Foo.Baz + { + class Bat + { + $$ + } + } + """; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "<>", inlineDescription: "Foo"); @@ -469,28 +487,30 @@ class Bat [Theory, CombinatorialData] public async Task TopLevel_OverloadsWithMixedAccessibility_InternalWithIVT_NoImport_InReference2(bool isProjectReference) { - var file1 = $@" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project1"")] - -namespace Foo -{{ - internal class Bar - {{}} - - internal class Bar - {{}} - - internal class Bar - {{}} -}}"; - var file2 = @" -namespace Baz -{ - class Bat - { - $$ - } -}"; + var file1 = $$""" + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Project1")] + + namespace Foo + { + internal class Bar + {} + + internal class Bar + {} + + internal class Bar + {} + } + """; + var file2 = """ + namespace Baz + { + class Bat + { + $$ + } + } + """; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassInternal, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassInternal, inlineDescription: "Foo"); @@ -499,22 +519,24 @@ class Bat [Theory, CombinatorialData] public async Task Show_TopLevel_Internal_WithIVT_NoImport_InReference(bool isProjectReference) { - var file1 = $@" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project1"")] - -namespace Foo -{{ - internal class Bar - {{}} -}}"; - var file2 = @" -namespace Baz -{ - class Bat - { - $$ - } -}"; + var file1 = $$""" + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Project1")] + + namespace Foo + { + internal class Bar + {} + } + """; + var file2 = """ + namespace Baz + { + class Bat + { + $$ + } + } + """; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassInternal, inlineDescription: "Foo"); } @@ -522,19 +544,21 @@ class Bat [Fact] public async Task Show_TopLevel_NoImport_InVBReference() { - var file1 = $@" -Namespace Bar - Public Class Barr - End CLass -End Namespace"; - var file2 = @" -namespace Baz -{ - class Bat - { - $$ - } -}"; + var file1 = $""" + Namespace Bar + Public Class Barr + End CLass + End Namespace + """; + var file2 = """ + namespace Baz + { + class Bat + { + $$ + } + } + """; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Barr", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo.Bar"); } @@ -542,25 +566,26 @@ class Bat [Fact] public async Task VB_MixedCapitalization_Test() { - var file1 = $@" -Namespace Na - Public Class Foo - End Class -End Namespace - -Namespace na - Public Class Bar - End Class -End Namespace -"; - var file2 = @" -namespace Baz -{ - class Bat - { - $$ - } -}"; + var file1 = $""" + Namespace Na + Public Class Foo + End Class + End Namespace + + Namespace na + Public Class Bar + End Class + End Namespace + """; + var file2 = """ + namespace Baz + { + class Bat + { + $$ + } + } + """; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: ""); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Na"); await VerifyTypeImportItemExistsAsync(markup, "Foo", glyph: (int)Glyph.ClassPublic, inlineDescription: "Na"); @@ -571,26 +596,27 @@ class Bat [Fact] public async Task VB_MixedCapitalization_WithImport_Test() { - var file1 = $@" -Namespace Na - Public Class Foo - End Class -End Namespace - -Namespace na - Public Class Bar - End Class -End Namespace -"; - var file2 = @" -using Na; -namespace Baz -{ - class Bat - { - $$ - } -}"; + var file1 = $""" + Namespace Na + Public Class Foo + End Class + End Namespace + + Namespace na + Public Class Bar + End Class + End Namespace + """; + var file2 = """ + using Na; + namespace Baz + { + class Bat + { + $$ + } + } + """; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: ""); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Na"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo", inlineDescription: "Na"); @@ -601,19 +627,21 @@ class Bat [Fact] public async Task DoNotShow_TopLevel_Internal_NoImport_InVBReference() { - var file1 = $@" -Namespace Bar - Friend Class Barr - End CLass -End Namespace"; - var file2 = @" -namespace Baz -{ - class Bat - { - $$ - } -}"; + var file1 = $""" + Namespace Bar + Friend Class Barr + End CLass + End Namespace + """; + var file2 = """ + namespace Baz + { + class Bat + { + $$ + } + } + """; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Barr", inlineDescription: "Foo.Bar"); } @@ -621,20 +649,22 @@ class Bat [Fact] public async Task DoNotShow_TopLevel_WithImport_InVBReference() { - var file1 = $@" -Namespace Bar - Public Class Barr - End CLass -End Namespace"; - var file2 = @" -using Foo.Bar; -namespace Baz -{ - class Bat - { - $$ - } -}"; + var file1 = $""" + Namespace Bar + Public Class Barr + End CLass + End Namespace + """; + var file2 = """ + using Foo.Bar; + namespace Baz + { + class Bat + { + $$ + } + } + """; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Barr", inlineDescription: "Foo.Bar"); } @@ -642,31 +672,33 @@ class Bat [Theory, CombinatorialData] public async Task TypesWithIdenticalNameButDifferentNamespaces(bool isProjectReference) { - var file1 = $@" -namespace Foo -{{ - public class Bar - {{}} - - public class Bar - {{}} -}} -namespace Baz -{{ - public class Bar - {{}} - - public class Bar - {{}} -}}"; - var file2 = @" -namespace NS -{ - class C - { - $$ - } -}"; + var file1 = $$""" + namespace Foo + { + public class Bar + {} + + public class Bar + {} + } + namespace Baz + { + public class Bar + {} + + public class Bar + {} + } + """; + var file2 = """ + namespace NS + { + class C + { + $$ + } + } + """; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); @@ -677,45 +709,47 @@ class C [Theory, CombinatorialData] public async Task TestNoCompletionItemWhenThereIsAlias(bool isProjectReference) { - var file1 = @" -using AliasFoo1 = Foo1.Foo2.Foo3.Foo4; -using AliasFoo2 = Foo1.Foo2.Foo3.Foo4.Foo6; + var file1 = """ + using AliasFoo1 = Foo1.Foo2.Foo3.Foo4; + using AliasFoo2 = Foo1.Foo2.Foo3.Foo4.Foo6; -namespace Bar -{ - using AliasFoo3 = Foo1.Foo2.Foo3.Foo5; - using AliasFoo4 = Foo1.Foo2.Foo3.Foo5.Foo7; - public class CC - { - public static void Main() - { - F$$ - } - } -}"; - var file2 = @" -namespace Foo1 -{ - namespace Foo2 - { - namespace Foo3 - { - public class Foo4 + namespace Bar { - public class Foo6 + using AliasFoo3 = Foo1.Foo2.Foo3.Foo5; + using AliasFoo4 = Foo1.Foo2.Foo3.Foo5.Foo7; + public class CC { + public static void Main() + { + F$$ + } } } - - public class Foo5 + """; + var file2 = """ + namespace Foo1 { - public class Foo7 + namespace Foo2 { + namespace Foo3 + { + public class Foo4 + { + public class Foo6 + { + } + } + + public class Foo5 + { + public class Foo7 + { + } + } + } } } - } - } -}"; + """; var markup = GetMarkupWithReference(file1, file2, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo4", "Foo1.Foo2.Foo3"); @@ -727,29 +761,31 @@ public class Foo7 [Theory, CombinatorialData] public async Task TestAttributesAlias(bool isProjectReference) { - var file1 = @" -using myAlias = Foo.BarAttribute; -using myAlia2 = Foo.BarAttributeDifferentEnding; + var file1 = """ + using myAlias = Foo.BarAttribute; + using myAlia2 = Foo.BarAttributeDifferentEnding; -namespace Foo2 -{ - public class Main - { - $$ - } -}"; + namespace Foo2 + { + public class Main + { + $$ + } + } + """; - var file2 = @" -namespace Foo -{ - public class BarAttribute: System.Attribute - { - } + var file2 = """ + namespace Foo + { + public class BarAttribute: System.Attribute + { + } - public class BarAttributeDifferentEnding: System.Attribute - { - } -}"; + public class BarAttributeDifferentEnding: System.Attribute + { + } + } + """; var markup = GetMarkupWithReference(file1, file2, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", "Foo"); @@ -760,37 +796,39 @@ public class BarAttributeDifferentEnding: System.Attribute [Theory, CombinatorialData] public async Task TestGenericsAliasHasNoEffect(bool isProjectReference) { - var file1 = @" -using AliasFoo1 = Foo1.Foo2.Foo3.Foo4; + var file1 = """ + using AliasFoo1 = Foo1.Foo2.Foo3.Foo4; -namespace Bar -{ - using AliasFoo2 = Foo1.Foo2.Foo3.Foo5; - public class CC - { - public static void Main() - { - F$$ - } - } -}"; - var file2 = @" -namespace Foo1 -{ - namespace Foo2 - { - namespace Foo3 - { - public class Foo4 + namespace Bar { + using AliasFoo2 = Foo1.Foo2.Foo3.Foo5; + public class CC + { + public static void Main() + { + F$$ + } + } } - - public class Foo5 + """; + var file2 = """ + namespace Foo1 { + namespace Foo2 + { + namespace Foo3 + { + public class Foo4 + { + } + + public class Foo5 + { + } + } + } } - } - } -}"; + """; var markup = GetMarkupWithReference(file1, file2, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Foo4", (int)Glyph.ClassPublic, "Foo1.Foo2.Foo3", displayTextSuffix: "<>"); @@ -806,34 +844,36 @@ public class Foo5 [WpfTheory] public async Task Commit_NoImport_InProject(SourceCodeKind kind) { - var file1 = $@" -namespace Foo -{{ - public class Bar - {{ - }} -}}"; - - var file2 = @" -namespace Baz -{ - class Bat - { - $$ - } -}"; - var expectedCodeAfterCommit = @" -using Foo; + var file1 = $$""" + namespace Foo + { + public class Bar + { + } + } + """; -namespace Baz -{ - class Bat - { - Bar$$ - } -}"; + var file2 = """ + namespace Baz + { + class Bat + { + $$ + } + } + """; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); - await VerifyCustomCommitProviderAsync(markup, "Bar", expectedCodeAfterCommit, sourceCodeKind: kind); + await VerifyCustomCommitProviderAsync(markup, "Bar", """ + using Foo; + + namespace Baz + { + class Bat + { + Bar$$ + } + } + """, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] @@ -841,24 +881,24 @@ class Bat [WpfTheory] public async Task Commit_TopLevelStatement_NoImport_InProject(SourceCodeKind kind) { - var file1 = $@" -namespace Foo -{{ - public class Bar - {{ - }} -}}"; - - var file2 = @" -$$ -"; - var expectedCodeAfterCommit = @"using Foo; - - -Bar$$ -"; + var file1 = $$""" + namespace Foo + { + public class Bar + { + } + } + """; + + var file2 = """ + $$ + """; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); - await VerifyCustomCommitProviderAsync(markup, "Bar", expectedCodeAfterCommit, sourceCodeKind: kind); + await VerifyCustomCommitProviderAsync(markup, "Bar", """ + using Foo; + + Bar$$ + """, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] @@ -866,27 +906,27 @@ public class Bar [WpfTheory] public async Task Commit_TopLevelStatement_UnrelatedImport_InProject(SourceCodeKind kind) { - var file1 = $@" -namespace Foo -{{ - public class Bar - {{ - }} -}}"; - - var file2 = @" -using System; + var file1 = $$""" + namespace Foo + { + public class Bar + { + } + } + """; -$$ -"; - var expectedCodeAfterCommit = @" -using System; -using Foo; + var file2 = """ + using System; -Bar$$ -"; + $$ + """; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); - await VerifyCustomCommitProviderAsync(markup, "Bar", expectedCodeAfterCommit, sourceCodeKind: kind); + await VerifyCustomCommitProviderAsync(markup, "Bar", """ + using System; + using Foo; + + Bar$$ + """, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] @@ -894,77 +934,78 @@ public class Bar [WpfTheory] public async Task Commit_NoImport_InVBReference(SourceCodeKind kind) { - var file1 = $@" -Namespace Bar - Public Class Barr - End CLass -End Namespace"; - var file2 = @" -namespace Baz -{ - class Bat - { - $$ - } -}"; - var expectedCodeAfterCommit = @" -using Foo.Bar; - -namespace Baz -{ - class Bat - { - Barr$$ - } -}"; + var file1 = $""" + Namespace Bar + Public Class Barr + End CLass + End Namespace + """; + var file2 = """ + namespace Baz + { + class Bat + { + $$ + } + } + """; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: "Foo"); - await VerifyCustomCommitProviderAsync(markup, "Barr", expectedCodeAfterCommit, sourceCodeKind: kind); + await VerifyCustomCommitProviderAsync(markup, "Barr", """ + using Foo.Bar; + + namespace Baz + { + class Bat + { + Barr$$ + } + } + """, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory] - public async Task Commit_NoImport_InPEReference(SourceCodeKind kind) - { - var markup = $@" - - -class Bar -{{ - $$ -}} - -"; - var expectedCodeAfterCommit = @" -using System; - -class Bar -{ - Console$$ -}"; + public Task Commit_NoImport_InPEReference(SourceCodeKind kind) + => VerifyCustomCommitProviderAsync($$""" + + + class Bar + { + $$ + } + + + """, "Console", """ + using System; - await VerifyCustomCommitProviderAsync(markup, "Console", expectedCodeAfterCommit, sourceCodeKind: kind); - } + class Bar + { + Console$$ + } + """, sourceCodeKind: kind); #endregion [Fact] public async Task DoNotShow_TopLevel_Public_NoImport_InNonGlobalAliasedMetadataReference() { - var file1 = $@" -namespace Foo -{{ - public class Bar - {{}} -}}"; - var file2 = @" -namespace Baz -{ - class Bat - { - $$ - } -}"; + var file1 = $$""" + namespace Foo + { + public class Bar + {} + } + """; + var file2 = """ + namespace Baz + { + class Bat + { + $$ + } + } + """; var markup = CreateMarkupForProjectWithAliasedMetadataReference(file2, "alias1", file1, LanguageNames.CSharp, LanguageNames.CSharp, hasGlobalAlias: false); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); } @@ -972,20 +1013,22 @@ class Bat [Fact] public async Task Show_TopLevel_Public_NoImport_InGlobalAliasedMetadataReference() { - var file1 = $@" -namespace Foo -{{ - public class Bar - {{}} -}}"; - var file2 = @" -namespace Baz -{ - class Bat - { - $$ - } -}"; + var file1 = $$""" + namespace Foo + { + public class Bar + {} + } + """; + var file2 = """ + namespace Baz + { + class Bat + { + $$ + } + } + """; var markup = CreateMarkupForProjectWithAliasedMetadataReference(file2, "alias1", file1, LanguageNames.CSharp, LanguageNames.CSharp, hasGlobalAlias: true); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } @@ -993,20 +1036,22 @@ class Bat [Fact] public async Task DoNotShow_TopLevel_Public_NoImport_InNonGlobalAliasedProjectReference() { - var file1 = $@" -namespace Foo -{{ - public class Bar - {{}} -}}"; - var file2 = @" -namespace Baz -{ - class Bat - { - $$ - } -}"; + var file1 = $$""" + namespace Foo + { + public class Bar + {} + } + """; + var file2 = """ + namespace Baz + { + class Bat + { + $$ + } + } + """; var markup = CreateMarkupForProjectWithAliasedProjectReference(file2, "alias1", file1, LanguageNames.CSharp, LanguageNames.CSharp); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); } @@ -1014,22 +1059,24 @@ class Bat [Fact] public async Task ShorterTypeNameShouldShowBeforeLongerTypeName() { - var file1 = $@" -namespace Foo -{{ - public class SomeType - {{}} - public class SomeTypeWithLongerName - {{}} -}}"; - var file2 = @" -namespace Baz -{ - class Bat - { - $$ - } -}"; + var file1 = $$""" + namespace Foo + { + public class SomeType + {} + public class SomeTypeWithLongerName + {} + } + """; + var file2 = """ + namespace Baz + { + class Bat + { + $$ + } + } + """; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); var completionList = await GetCompletionListAsync(markup).ConfigureAwait(false); AssertRelativeOrder(["SomeType", "SomeTypeWithLongerName"], [.. completionList.ItemsList]); @@ -1038,20 +1085,22 @@ class Bat [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35540")] public async Task AttributeTypeInAttributeNameContext() { - var file1 = @" -namespace Foo -{ - public class MyAttribute : System.Attribute { } - public class MyAttributeWithoutSuffix : System.Attribute { } - public class MyClass { } -}"; + var file1 = """ + namespace Foo + { + public class MyAttribute : System.Attribute { } + public class MyAttributeWithoutSuffix : System.Attribute { } + public class MyClass { } + } + """; - var file2 = @" -namespace Test -{ - [$$ - class Program { } -}"; + var file2 = """ + namespace Test + { + [$$ + class Program { } + } + """; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "My", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.MyAttribute", flags: CompletionItemFlags.Expanded); @@ -1066,51 +1115,53 @@ class Program { } [WorkItem("https://github.com/dotnet/roslyn/issues/35540")] public async Task CommitAttributeTypeInAttributeNameContext(SourceCodeKind kind) { - var file1 = @" -namespace Foo -{ - public class MyAttribute : System.Attribute { } -}"; - - var file2 = @" -namespace Test -{ - [$$ - class Program { } -}"; - - var expectedCodeAfterCommit = @" -using Foo; - -namespace Test -{ - [My$$ - class Program { } -}"; + var file1 = """ + namespace Foo + { + public class MyAttribute : System.Attribute { } + } + """; + var file2 = """ + namespace Test + { + [$$ + class Program { } + } + """; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); - await VerifyCustomCommitProviderAsync(markup, "My", expectedCodeAfterCommit, sourceCodeKind: kind); + await VerifyCustomCommitProviderAsync(markup, "My", """ + using Foo; + + namespace Test + { + [My$$ + class Program { } + } + """, sourceCodeKind: kind); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35540")] public async Task AttributeTypeInNonAttributeNameContext() { - var file1 = @" -namespace Foo -{ - public class MyAttribute : System.Attribute { } - public class MyAttributeWithoutSuffix : System.Attribute { } - public class MyClass { } -}"; + var file1 = """ + namespace Foo + { + public class MyAttribute : System.Attribute { } + public class MyAttributeWithoutSuffix : System.Attribute { } + public class MyClass { } + } + """; - var file2 = @" -namespace Test -{ - class Program - { - $$ - } -}"; + var file2 = """ + namespace Test + { + class Program + { + $$ + } + } + """; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "MyAttribute", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.MyAttribute", flags: CompletionItemFlags.CachedAndExpanded); @@ -1125,52 +1176,55 @@ class Program [WorkItem("https://github.com/dotnet/roslyn/issues/35540")] public async Task CommitAttributeTypeInNonAttributeNameContext(SourceCodeKind kind) { - var file1 = @" -namespace Foo -{ - public class MyAttribute : System.Attribute { } -}"; - - var file2 = @" -namespace Test -{ - class Program - { - $$ - } -}"; - - var expectedCodeAfterCommit = @" -using Foo; + var file1 = """ + namespace Foo + { + public class MyAttribute : System.Attribute { } + } + """; -namespace Test -{ - class Program - { - MyAttribute$$ - } -}"; + var file2 = """ + namespace Test + { + class Program + { + $$ + } + } + """; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); - await VerifyCustomCommitProviderAsync(markup, "MyAttribute", expectedCodeAfterCommit, sourceCodeKind: kind); + await VerifyCustomCommitProviderAsync(markup, "MyAttribute", """ + using Foo; + + namespace Test + { + class Program + { + MyAttribute$$ + } + } + """, sourceCodeKind: kind); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35540")] public async Task AttributeTypeWithoutSuffixInAttributeNameContext() { // attribute suffix isn't capitalized - var file1 = @" -namespace Foo -{ - public class Myattribute : System.Attribute { } - public class MyClass { } -}"; + var file1 = """ + namespace Foo + { + public class Myattribute : System.Attribute { } + public class MyClass { } + } + """; - var file2 = @" -namespace Test -{ - [$$ - class Program { } -}"; + var file2 = """ + namespace Test + { + [$$ + class Program { } + } + """; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "Myattribute", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.Myattribute", flags: CompletionItemFlags.CachedAndExpanded); @@ -1185,51 +1239,53 @@ class Program { } public async Task CommitAttributeTypeWithoutSuffixInAttributeNameContext(SourceCodeKind kind) { // attribute suffix isn't capitalized - var file1 = @" -namespace Foo -{ - public class Myattribute : System.Attribute { } -}"; - - var file2 = @" -namespace Test -{ - [$$ - class Program { } -}"; - - var expectedCodeAfterCommit = @" -using Foo; - -namespace Test -{ - [Myattribute$$ - class Program { } -}"; + var file1 = """ + namespace Foo + { + public class Myattribute : System.Attribute { } + } + """; + var file2 = """ + namespace Test + { + [$$ + class Program { } + } + """; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); - await VerifyCustomCommitProviderAsync(markup, "Myattribute", expectedCodeAfterCommit, sourceCodeKind: kind); + await VerifyCustomCommitProviderAsync(markup, "Myattribute", """ + using Foo; + + namespace Test + { + [Myattribute$$ + class Program { } + } + """, sourceCodeKind: kind); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35540")] public async Task AttributeTypeWithoutSuffixInNonAttributeNameContext() { // attribute suffix isn't capitalized - var file1 = @" -namespace Foo -{ - public class Myattribute : System.Attribute { } - public class MyClass { } -}"; + var file1 = """ + namespace Foo + { + public class Myattribute : System.Attribute { } + public class MyClass { } + } + """; - var file2 = @" -namespace Test -{ - class Program - { - $$ - } -}"; + var file2 = """ + namespace Test + { + class Program + { + $$ + } + } + """; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "Myattribute", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.Myattribute", flags: CompletionItemFlags.Expanded); @@ -1244,55 +1300,58 @@ class Program public async Task CommitAttributeTypeWithoutSuffixInNonAttributeNameContext(SourceCodeKind kind) { // attribute suffix isn't capitalized - var file1 = @" -namespace Foo -{ - public class Myattribute : System.Attribute { } -}"; - - var file2 = @" -namespace Test -{ - class Program - { - $$ - } -}"; - - var expectedCodeAfterCommit = @" -using Foo; + var file1 = """ + namespace Foo + { + public class Myattribute : System.Attribute { } + } + """; -namespace Test -{ - class Program - { - Myattribute$$ - } -}"; + var file2 = """ + namespace Test + { + class Program + { + $$ + } + } + """; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); - await VerifyCustomCommitProviderAsync(markup, "Myattribute", expectedCodeAfterCommit, sourceCodeKind: kind); + await VerifyCustomCommitProviderAsync(markup, "Myattribute", """ + using Foo; + + namespace Test + { + class Program + { + Myattribute$$ + } + } + """, sourceCodeKind: kind); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35540")] public async Task VBAttributeTypeWithoutSuffixInAttributeNameContext() { - var file1 = @" -Namespace Foo - Public Class Myattribute - Inherits System.Attribute - End Class - Public Class MyVBClass - End Class -End Namespace"; - - var file2 = @" -namespace Test -{ - [$$ - class Program - { - } -}"; + var file1 = """ + Namespace Foo + Public Class Myattribute + Inherits System.Attribute + End Class + Public Class MyVBClass + End Class + End Namespace + """; + + var file2 = """ + namespace Test + { + [$$ + class Program + { + } + } + """; var markup = CreateMarkupForProjectWithProjectReference(file2, file1, LanguageNames.CSharp, LanguageNames.VisualBasic); @@ -1307,20 +1366,20 @@ class Program [WorkItem("https://github.com/dotnet/roslyn/issues/37038")] public async Task CommitTypeInUsingStaticContextShouldUseFullyQualifiedName(SourceCodeKind kind) { - var file1 = @" -namespace Foo -{ - public class MyClass { } -}"; - - var file2 = @" -using static $$"; - - var expectedCodeAfterCommit = @" -using static Foo.MyClass$$"; + var file1 = """ + namespace Foo + { + public class MyClass { } + } + """; + var file2 = """ + using static $$ + """; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); - await VerifyCustomCommitProviderAsync(markup, "MyClass", expectedCodeAfterCommit, sourceCodeKind: kind); + await VerifyCustomCommitProviderAsync(markup, "MyClass", """ + using static Foo.MyClass$$ + """, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] @@ -1329,20 +1388,20 @@ public class MyClass { } [WorkItem("https://github.com/dotnet/roslyn/issues/37038")] public async Task CommitGenericTypeParameterInUsingAliasContextShouldUseFullyQualifiedName(SourceCodeKind kind) { - var file1 = @" -namespace Foo -{ - public class MyClass { } -}"; - - var file2 = @" -using CollectionOfStringBuilders = System.Collections.Generic.List<$$>"; - - var expectedCodeAfterCommit = @" -using CollectionOfStringBuilders = System.Collections.Generic.List"; + var file1 = """ + namespace Foo + { + public class MyClass { } + } + """; + var file2 = """ + using CollectionOfStringBuilders = System.Collections.Generic.List<$$> + """; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); - await VerifyCustomCommitProviderAsync(markup, "MyClass", expectedCodeAfterCommit, sourceCodeKind: kind); + await VerifyCustomCommitProviderAsync(markup, "MyClass", """ + using CollectionOfStringBuilders = System.Collections.Generic.List + """, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] @@ -1351,27 +1410,29 @@ public class MyClass { } [WorkItem("https://github.com/dotnet/roslyn/issues/37038")] public async Task CommitGenericTypeParameterInUsingAliasContextShouldUseFullyQualifiedName2(SourceCodeKind kind) { - var file1 = @" -namespace Foo.Bar -{ - public class MyClass { } -}"; + var file1 = """ + namespace Foo.Bar + { + public class MyClass { } + } + """; - var file2 = @" -namespace Foo -{ - using CollectionOfStringBuilders = System.Collections.Generic.List<$$> -}"; + var file2 = """ + namespace Foo + { + using CollectionOfStringBuilders = System.Collections.Generic.List<$$> + } + """; // Completion is not fully qualified - var expectedCodeAfterCommit = @" -namespace Foo -{ - using CollectionOfStringBuilders = System.Collections.Generic.List -}"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); - await VerifyCustomCommitProviderAsync(markup, "MyClass", expectedCodeAfterCommit, sourceCodeKind: kind); + await VerifyCustomCommitProviderAsync(markup, "MyClass", """ + namespace Foo + { + using CollectionOfStringBuilders = System.Collections.Generic.List + } + """, sourceCodeKind: kind); } [Fact] @@ -1379,15 +1440,16 @@ namespace Foo [WorkItem("https://github.com/dotnet/roslyn/issues/39027")] public async Task TriggerCompletionInSubsequentSubmission() { - var markup = @" - - - var x = ""10""; - - - var y = $$ - - "; + var markup = """ + + + var x = "10"; + + + var y = $$ + + + """; var completionList = await GetCompletionListAsync(markup, workspaceKind: WorkspaceKind.Interactive).ConfigureAwait(false); Assert.NotEmpty(completionList.ItemsList); @@ -1396,23 +1458,25 @@ public async Task TriggerCompletionInSubsequentSubmission() [Fact] public async Task ShouldNotTriggerInsideTrivia() { - var file1 = $@" -namespace Foo -{{ - public class Bar - {{}} -}}"; - - var file2 = @" -namespace Baz -{ - /// - /// - /// - class Bat - { - } -}"; + var file1 = $$""" + namespace Foo + { + public class Bar + {} + } + """; + + var file2 = """ + namespace Baz + { + /// + /// + /// + class Bat + { + } + } + """; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); } @@ -1431,23 +1495,25 @@ private static void AssertRelativeOrder(List expectedTypesInRelativeOrde [Theory, CombinatorialData] public async Task TestBrowsableAwaysFromReferences(bool isProjectReference) { - var srcDoc = @" -class Program -{ - void M() - { - $$ - } -}"; + var srcDoc = """ + class Program + { + void M() + { + $$ + } + } + """; - var refDoc = @" -namespace Foo -{ - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] - public class Goo - { - } -}"; + var refDoc = """ + namespace Foo + { + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] + public class Goo + { + } + } + """; var markup = isProjectReference switch { @@ -1465,23 +1531,25 @@ await VerifyTypeImportItemExistsAsync( [Theory, CombinatorialData] public async Task TestBrowsableNeverFromReferences(bool isProjectReference) { - var srcDoc = @" -class Program -{ - void M() - { - $$ - } -}"; + var srcDoc = """ + class Program + { + void M() + { + $$ + } + } + """; - var refDoc = @" -namespace Foo -{ - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - public class Goo - { - } -}"; + var refDoc = """ + namespace Foo + { + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public class Goo + { + } + } + """; var (markup, shouldContainItem) = isProjectReference switch { @@ -1515,23 +1583,25 @@ public async Task TestBrowsableAdvancedFromReferences(bool isProjectReference, b { HideAdvancedMembers = hideAdvancedMembers; - var srcDoc = @" -class Program -{ - void M() - { - $$ - } -}"; + var srcDoc = """ + class Program + { + void M() + { + $$ + } + } + """; - var refDoc = @" -namespace Foo -{ - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public class Goo - { - } -}"; + var refDoc = """ + namespace Foo + { + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + public class Goo + { + } + } + """; var (markup, shouldContainItem) = isProjectReference switch { @@ -1559,156 +1629,147 @@ await VerifyTypeImportItemIsAbsentAsync( [Theory] [InlineData('.')] [InlineData(';')] - public async Task TestCommitWithCustomizedCommitCharForParameterlessConstructor(char commitChar) - { - var markup = @" -namespace AA -{ - public class C - { - } -} + public Task TestCommitWithCustomizedCommitCharForParameterlessConstructor(char commitChar) + => VerifyProviderCommitAsync(""" + namespace AA + { + public class C + { + } + } -namespace BB -{ - public class B - { - public void M() - { - var c = new $$ - } - } -}"; - - var expected = $@" -using AA; - -namespace AA -{{ - public class C - {{ - }} -}} - -namespace BB -{{ - public class B - {{ - public void M() - {{ - var c = new C(){commitChar} - }} - }} -}}"; - await VerifyProviderCommitAsync(markup, "C", expected, commitChar: commitChar, sourceCodeKind: SourceCodeKind.Regular); - } + namespace BB + { + public class B + { + public void M() + { + var c = new $$ + } + } + } + """, "C", $$""" + using AA; + + namespace AA + { + public class C + { + } + } + + namespace BB + { + public class B + { + public void M() + { + var c = new C(){{commitChar}} + } + } + } + """, commitChar: commitChar, sourceCodeKind: SourceCodeKind.Regular); [Theory] [InlineData('.')] [InlineData(';')] - public async Task TestCommitWithCustomizedCommitCharUnderNonObjectCreationContext(char commitChar) - { - var markup = @" -namespace AA -{ - public class C - { - } -} -namespace BB -{ - public class B - { - public void M() - { - $$ - } - } -}"; - - var expected = $@" -using AA; - -namespace AA -{{ - public class C - {{ - }} -}} -namespace BB -{{ - public class B - {{ - public void M() - {{ - C{commitChar} - }} - }} -}}"; - await VerifyProviderCommitAsync(markup, "C", expected, commitChar: commitChar, sourceCodeKind: SourceCodeKind.Regular); - } + public Task TestCommitWithCustomizedCommitCharUnderNonObjectCreationContext(char commitChar) + => VerifyProviderCommitAsync(""" + namespace AA + { + public class C + { + } + } + namespace BB + { + public class B + { + public void M() + { + $$ + } + } + } + """, "C", $$""" + using AA; + + namespace AA + { + public class C + { + } + } + namespace BB + { + public class B + { + public void M() + { + C{{commitChar}} + } + } + } + """, commitChar: commitChar, sourceCodeKind: SourceCodeKind.Regular); [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory] [WorkItem("https://github.com/dotnet/roslyn/issues/54493")] - public async Task CommitInLocalFunctionContext(SourceCodeKind kind) - { - var markup = @" -namespace Foo -{ - public class MyClass { } -} - -namespace Test -{ - class Program - { - public static void Main() - { - static $$ - } - } -}"; - - var expectedCodeAfterCommit = @" -using Foo; + public Task CommitInLocalFunctionContext(SourceCodeKind kind) + => VerifyProviderCommitAsync(""" + namespace Foo + { + public class MyClass { } + } -namespace Foo -{ - public class MyClass { } -} + namespace Test + { + class Program + { + public static void Main() + { + static $$ + } + } + } + """, "MyClass", """ + using Foo; -namespace Test -{ - class Program - { - public static void Main() - { - static MyClass - } - } -}"; + namespace Foo + { + public class MyClass { } + } - await VerifyProviderCommitAsync(markup, "MyClass", expectedCodeAfterCommit, commitChar: null, sourceCodeKind: kind); - } + namespace Test + { + class Program + { + public static void Main() + { + static MyClass + } + } + } + """, commitChar: null, sourceCodeKind: kind); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58473")] public async Task TestGlobalUsingsInSdkAutoGeneratedFile() { - var source = @" -using System; -$$"; - - var globalUsings = @" -global using global::System; -global using global::System.Collections.Generic; -global using global::System.IO; -global using global::System.Linq; -global using global::System.Net.Http; -global using global::System.Threading; -global using global::System.Threading.Tasks; -"; + var source = """ + using System; + $$ + """; + + var globalUsings = """ + global using global::System; + global using global::System.Collections.Generic; + global using global::System.IO; + global using global::System.Linq; + global using global::System.Net.Http; + global using global::System.Threading; + global using global::System.Threading.Tasks; + """; var markup = CreateMarkupForSingleProject(source, globalUsings, LanguageNames.CSharp, referencedFileName: "ProjectName.GlobalUsings.g.cs"); await VerifyTypeImportItemIsAbsentAsync(markup, "Task", inlineDescription: "System.Threading.Tasks"); @@ -1718,11 +1779,12 @@ public async Task TestGlobalUsingsInSdkAutoGeneratedFile() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58473")] public async Task TestGlobalUsingsInSameFile() { - var source = @" -global using global::System; -global using global::System.Threading.Tasks; + var source = """ + global using global::System; + global using global::System.Threading.Tasks; -$$"; + $$ + """; var markup = CreateMarkupForSingleProject(source, "", LanguageNames.CSharp); await VerifyTypeImportItemIsAbsentAsync(markup, "Console", inlineDescription: "System"); @@ -1732,18 +1794,19 @@ public async Task TestGlobalUsingsInSameFile() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58473")] public async Task TestGlobalUsingsInUserDocument() { - var source = @" -$$"; - - var globalUsings = @" -global using global::System; -global using global::System.Collections.Generic; -global using global::System.IO; -global using global::System.Linq; -global using global::System.Net.Http; -global using global::System.Threading; -global using global::System.Threading.Tasks; -"; + var source = """ + $$ + """; + + var globalUsings = """ + global using global::System; + global using global::System.Collections.Generic; + global using global::System.IO; + global using global::System.Linq; + global using global::System.Net.Http; + global using global::System.Threading; + global using global::System.Threading.Tasks; + """; var markup = CreateMarkupForSingleProject(source, globalUsings, LanguageNames.CSharp, referencedFileName: "GlobalUsings.cs"); await VerifyTypeImportItemIsAbsentAsync(markup, "Task", inlineDescription: "System.Threading.Tasks"); @@ -1757,22 +1820,24 @@ public async Task TestGlobalUsingsInUserDocument() [WorkItem("https://github.com/dotnet/roslyn/issues/65339")] public async Task TestFileScopedType(bool? isProjectReference) { - var srcDoc = @" -class Program -{ - void M() - { - $$goo - } -}"; + var srcDoc = """ + class Program + { + void M() + { + $$goo + } + } + """; - var refDoc = @" -namespace Foo -{ - file class Goo - { - } -}"; + var refDoc = """ + namespace Foo + { + file class Goo + { + } + } + """; string markup; if (isProjectReference.HasValue) @@ -1821,17 +1886,12 @@ enum E : $$ } [Fact] - public async Task TestEnumBaseList2() - { - var source = """ + public Task TestEnumBaseList2() + => VerifyNoItemsExistAsync(""" using System; enum E : $$ - """; - - // Everything valid is already in the scope - await VerifyNoItemsExistAsync(source); - } + """); private Task VerifyTypeImportItemExistsAsync(string markup, string expectedItem, int glyph, string inlineDescription, string displayTextSuffix = null, string expectedDescriptionOrNull = null, CompletionItemFlags? flags = null) => VerifyItemExistsAsync(markup, expectedItem, displayTextSuffix: displayTextSuffix, glyph: (Glyph)glyph, inlineDescription: inlineDescription, expectedDescriptionOrNull: expectedDescriptionOrNull, isComplexTextEdit: true, flags: flags); diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/XmlDocumentationCommentCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/XmlDocumentationCommentCompletionProviderTests.cs index 887c9a4dc4163..e7ffc129062aa 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/XmlDocumentationCommentCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/XmlDocumentationCommentCompletionProviderTests.cs @@ -74,105 +74,88 @@ await VerifyAtEndOfFile_ItemPartiallyWrittenAsync( } [Fact] - public async Task AlwaysVisibleAtAnyLevelItems1() - { - await VerifyItemsExistAsync(""" + public Task AlwaysVisibleAtAnyLevelItems1() + => VerifyItemsExistAsync(""" public class goo { /// $$ public void bar() { } } """, "inheritdoc", "see", "seealso", "![CDATA[", "!--"); - } [Fact] - public async Task AlwaysVisibleAtAnyLevelItems2() - { - await VerifyItemsExistAsync(""" + public Task AlwaysVisibleAtAnyLevelItems2() + => VerifyItemsExistAsync(""" public class goo { /// $$ public void bar() { } } """, "inheritdoc", "see", "seealso", "![CDATA[", "!--"); - } [Fact] - public async Task AlwaysVisibleNotTopLevelItems1() - { - await VerifyItemsExistAsync(""" + public Task AlwaysVisibleNotTopLevelItems1() + => VerifyItemsExistAsync(""" public class goo { /// $$ public void bar() { } } """, "c", "code", "list", "para"); - } [Fact] - public async Task AlwaysVisibleNotTopLevelItems2() - { - await VerifyItemsAbsentAsync(""" + public Task AlwaysVisibleNotTopLevelItems2() + => VerifyItemsAbsentAsync(""" public class goo { /// $$ public void bar() { } } """, "c", "code", "list", "para", "paramref", "typeparamref"); - } [Fact] - public async Task AlwaysVisibleTopLevelOnlyItems1() - { - await VerifyItemsExistAsync(""" + public Task AlwaysVisibleTopLevelOnlyItems1() + => VerifyItemsExistAsync(""" public class goo { /// $$ public void bar() { } } """, "exception", "include", "permission"); - } [Fact] - public async Task AlwaysVisibleTopLevelOnlyItems2() - { - await VerifyItemsAbsentAsync(""" + public Task AlwaysVisibleTopLevelOnlyItems2() + => VerifyItemsAbsentAsync(""" public class goo { /// $$ public void bar() { } } """, "exception", "include", "permission"); - } [Fact] - public async Task TopLevelSingleUseItems1() - { - await VerifyItemsExistAsync(""" + public Task TopLevelSingleUseItems1() + => VerifyItemsExistAsync(""" public class goo { /// $$ public void bar() { } } """, "example", "remarks", "summary"); - } [Fact] - public async Task TopLevelSingleUseItems2() - { - await VerifyItemsAbsentAsync(""" + public Task TopLevelSingleUseItems2() + => VerifyItemsAbsentAsync(""" public class goo { /// $$ public void bar() { } } """, "example", "remarks", "summary"); - } [Fact] - public async Task TopLevelSingleUseItems3() - { - await VerifyItemsAbsentAsync(""" + public Task TopLevelSingleUseItems3() + => VerifyItemsAbsentAsync(""" public class goo { /// $$ @@ -182,12 +165,10 @@ public class goo public void bar() { } } """, "example", "remarks", "summary"); - } [Fact] - public async Task OnlyInListItems() - { - await VerifyItemsAbsentAsync(""" + public Task OnlyInListItems() + => VerifyItemsAbsentAsync(""" public class goo { /// $$ @@ -197,12 +178,10 @@ public class goo public void bar() { } } """, "listheader", "item", "term", "description"); - } [Fact] - public async Task OnlyInListItems2() - { - await VerifyItemsAbsentAsync(""" + public Task OnlyInListItems2() + => VerifyItemsAbsentAsync(""" public class goo { /// $$ @@ -210,12 +189,10 @@ public class goo public void bar() { } } """, "listheader", "item", "term", "description"); - } [Fact] - public async Task OnlyInListItems3() - { - await VerifyItemsExistAsync(""" + public Task OnlyInListItems3() + => VerifyItemsExistAsync(""" public class goo { /// $$ @@ -223,12 +200,10 @@ public class goo public void bar() { } } """, "listheader", "item", "term", "description"); - } [Fact] - public async Task OnlyInListItems4() - { - await VerifyItemsExistAsync(""" + public Task OnlyInListItems4() + => VerifyItemsExistAsync(""" public class goo { /// <$$ @@ -236,12 +211,10 @@ public class goo public void bar() { } } """, "listheader", "item", "term", "description"); - } [Fact] - public async Task ListHeaderItems() - { - await VerifyItemsExistAsync(""" + public Task ListHeaderItems() + => VerifyItemsExistAsync(""" public class goo { /// @@ -253,12 +226,10 @@ public class goo public void bar() { } } """, "term", "description"); - } [Fact] - public async Task VoidMethodDeclarationItems() - { - await VerifyItemIsAbsentAsync(""" + public Task VoidMethodDeclarationItems() + => VerifyItemIsAbsentAsync(""" public class goo { @@ -266,12 +237,10 @@ public class goo public void bar() { } } """, "returns"); - } [Fact] - public async Task MethodReturns() - { - await VerifyItemExistsAsync(""" + public Task MethodReturns() + => VerifyItemExistsAsync(""" public class goo { @@ -279,12 +248,10 @@ public class goo public int bar() { } } """, "returns"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8627")] - public async Task ReadWritePropertyNoReturns() - { - await VerifyItemIsAbsentAsync(""" + public Task ReadWritePropertyNoReturns() + => VerifyItemIsAbsentAsync(""" public class goo { @@ -292,12 +259,10 @@ public class goo public int bar { get; set; } } """, "returns"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8627")] - public async Task ReadWritePropertyValue() - { - await VerifyItemExistsAsync(""" + public Task ReadWritePropertyValue() + => VerifyItemExistsAsync(""" public class goo { @@ -305,12 +270,10 @@ public class goo public int bar { get; set; } } """, "value"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8627")] - public async Task ReadOnlyPropertyNoReturns() - { - await VerifyItemIsAbsentAsync(""" + public Task ReadOnlyPropertyNoReturns() + => VerifyItemIsAbsentAsync(""" public class goo { @@ -318,12 +281,10 @@ public class goo public int bar { get; } } """, "returns"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8627")] - public async Task ReadOnlyPropertyValue() - { - await VerifyItemExistsAsync(""" + public Task ReadOnlyPropertyValue() + => VerifyItemExistsAsync(""" public class goo { @@ -331,12 +292,10 @@ public class goo public int bar { get; } } """, "value"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8627")] - public async Task WriteOnlyPropertyNoReturns() - { - await VerifyItemIsAbsentAsync(""" + public Task WriteOnlyPropertyNoReturns() + => VerifyItemIsAbsentAsync(""" public class goo { @@ -344,12 +303,10 @@ public class goo public int bar { set; } } """, "returns"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8627")] - public async Task WriteOnlyPropertyValue() - { - await VerifyItemExistsAsync(""" + public Task WriteOnlyPropertyValue() + => VerifyItemExistsAsync(""" public class goo { @@ -357,7 +314,6 @@ public class goo public int bar { set; } } """, "value"); - } [Fact] public async Task MethodParamTypeParam() @@ -382,9 +338,8 @@ await VerifyItemsAbsentAsync(text, """ } [Fact] - public async Task IndexerParamTypeParam() - { - await VerifyItemsExistAsync(""" + public Task IndexerParamTypeParam() + => VerifyItemsExistAsync(""" public class goo { @@ -394,12 +349,11 @@ public int this[T green] { get { } set { } } """, """ param name="green" """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17872")] - public async Task MethodParamRefName() - { - var text = """ + public Task MethodParamRefName() + => VerifyItemsExistAsync( + """ public class Outer { public class Inner @@ -410,9 +364,7 @@ public class Inner public int Method(T green) { } } } - """; - await VerifyItemsExistAsync( - text, + """, """ typeparamref name="TOuter" """, @@ -425,12 +377,10 @@ await VerifyItemsExistAsync( """ paramref name="green" """); - } [Fact] - public async Task ClassTypeParamRefName() - { - await VerifyItemsExistAsync(""" + public Task ClassTypeParamRefName() + => VerifyItemsExistAsync(""" /// /// $$ /// @@ -441,12 +391,10 @@ public int bar(T green) { } """, """ typeparamref name="T" """); - } [Fact] - public async Task ClassTypeParam() - { - await VerifyItemsExistAsync(""" + public Task ClassTypeParam() + => VerifyItemsExistAsync(""" /// $$ public class goo { @@ -455,25 +403,19 @@ public int bar(T green) { } """, """ typeparam name="T" """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638802")] - public async Task TagsAfterSameLineClosedTag() - { - var text = """ + public Task TagsAfterSameLineClosedTag() + => VerifyItemsExistAsync(""" /// /// $$ /// /// - """; - - await VerifyItemsExistAsync(text, "!--", "![CDATA[", "c", "code", "inheritdoc", "list", "para", "seealso", "see"); - } + """, "!--", "![CDATA[", "c", "code", "inheritdoc", "list", "para", "seealso", "see"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/734825")] - public async Task EnumMember() - { - var text = """ + public Task EnumMember() + => VerifyItemsExistAsync(""" public enum z { /// @@ -482,28 +424,21 @@ public enum z /// <$$ a } - """; - - await VerifyItemsExistAsync(text); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954679")] - public async Task CompletionList() - { - await VerifyItemExistsAsync(""" + public Task CompletionList() + => VerifyItemExistsAsync(""" /// $$ public class goo { } """, "completionlist"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44423")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775091")] - public async Task ParamRefNames() - { - // Local functions do not support documentation comments - await VerifyItemIsAbsentAsync(""" + public Task ParamRefNames() + => VerifyItemIsAbsentAsync(""" /// /// /// @@ -511,13 +446,11 @@ static void Main(string[] args) { } """, "args", sourceCodeKind: SourceCodeKind.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44423")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775091")] - public async Task ParamRefNames_Interactive() - { - await VerifyItemExistsAsync(""" + public Task ParamRefNames_Interactive() + => VerifyItemExistsAsync(""" /// /// /// @@ -525,46 +458,37 @@ static void Main(string[] args) { } """, "args", sourceCodeKind: SourceCodeKind.Script); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44423")] - public async Task ParamNamesInEmptyAttribute() - { - // Local functions do not support documentation comments - await VerifyItemIsAbsentAsync(""" + public Task ParamNamesInEmptyAttribute() + => VerifyItemIsAbsentAsync(""" /// static void Goo(string str) { } """, "str", sourceCodeKind: SourceCodeKind.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44423")] - public async Task ParamNamesInEmptyAttribute_Interactive() - { - await VerifyItemExistsAsync(""" + public Task ParamNamesInEmptyAttribute_Interactive() + => VerifyItemExistsAsync(""" /// static void Goo(string str) { } """, "str", sourceCodeKind: SourceCodeKind.Script); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26713")] - public async Task DelegateParams() - { - await VerifyItemExistsAsync(""" + public Task DelegateParams() + => VerifyItemExistsAsync(""" /// $$ delegate void D(object o); """, """ param name="o" """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17872")] - public async Task TypeParamRefNamesInEmptyAttribute() - { - var text = """ + public Task TypeParamRefNamesInEmptyAttribute() + => VerifyItemsExistAsync(""" public class Outer { public class Inner @@ -575,15 +499,11 @@ public class Inner public int Method(T green) { } } } - """; - - await VerifyItemsExistAsync(text, "TOuter", "TInner", "TMethod"); - } + """, "TOuter", "TInner", "TMethod"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17872")] - public async Task TypeParamRefNamesPartiallyTyped() - { - var text = """ + public Task TypeParamRefNamesPartiallyTyped() + => VerifyItemsExistAsync(""" public class Outer { public class Inner @@ -594,10 +514,7 @@ public class Inner public int Method(T green) { } } } - """; - - await VerifyItemsExistAsync(text, "TOuter", "TInner", "TMethod"); - } + """, "TOuter", "TInner", "TMethod"); [Fact] public async Task TypeParamNamesInEmptyAttribute() @@ -656,21 +573,18 @@ public int Method(T green) { } } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8322")] - public async Task PartialTagCompletion() - { - await VerifyItemsExistAsync(""" + public Task PartialTagCompletion() + => VerifyItemsExistAsync(""" public class goo { /// VerifyItemsExistAsync(""" public class goo { /// @@ -679,12 +593,10 @@ public class goo public void bar() { } } """, "!--", "![CDATA[", "c", "code", "inheritdoc", "list", "para", "see", "seealso"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11487")] - public async Task TypeParamAtTopLevelOnly() - { - await VerifyItemsAbsentAsync(""" + public Task TypeParamAtTopLevelOnly() + => VerifyItemsAbsentAsync(""" /// /// $$ /// @@ -694,12 +606,10 @@ public class Goo """, """ typeparam name="T" """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11487")] - public async Task ParamAtTopLevelOnly() - { - await VerifyItemsAbsentAsync(""" + public Task ParamAtTopLevelOnly() + => VerifyItemsAbsentAsync(""" /// /// $$ /// @@ -709,12 +619,10 @@ static void Goo(string str) """, """ param name="str" """); - } [Fact] - public async Task ListAttributeNames() - { - await VerifyItemsExistAsync(""" + public Task ListAttributeNames() + => VerifyItemsExistAsync(""" class C { /// @@ -725,12 +633,10 @@ static void Goo() } } """, "type"); - } [Fact] - public async Task ListTypeAttributeValue() - { - await VerifyItemsExistAsync(""" + public Task ListTypeAttributeValue() + => VerifyItemsExistAsync(""" class C { /// @@ -741,13 +647,11 @@ static void Goo() } } """, "bullet", "number", "table"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37504")] [WorkItem(11489, "https://github.com/dotnet/roslyn/issues/11490")] - public async Task SeeAttributeNames() - { - await VerifyItemsExistAsync(""" + public Task SeeAttributeNames() + => VerifyItemsExistAsync(""" class C { /// @@ -758,12 +662,10 @@ static void Goo() } } """, "cref", "langword", "href"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72259")] - public async Task SeeAttributeNames2() - { - var text = """ + public Task SeeAttributeNames2() + => VerifyProviderCommitAsync(""" class C { /// @@ -773,8 +675,7 @@ static void Goo() { } } - """; - var expected = """ + """, "langword", """ class C { /// @@ -784,15 +685,11 @@ static void Goo() { } } - """; - - await VerifyProviderCommitAsync(text, "langword", expected, null); - } + """, null); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37504")] - public async Task SeeAlsoAttributeNames() - { - await VerifyItemsExistAsync(""" + public Task SeeAlsoAttributeNames() + => VerifyItemsExistAsync(""" class C { /// @@ -803,12 +700,10 @@ static void Goo() } } """, "cref", "href"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22789")] - public async Task LangwordCompletionInPlainText() - { - await VerifyItemsExistAsync(""" + public Task LangwordCompletionInPlainText() + => VerifyItemsExistAsync(""" class C { /// @@ -819,12 +714,10 @@ static void Goo() } } """, "null", "sealed", "true", "false", "await"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22789")] - public async Task LangwordCompletionAfterAngleBracket1() - { - await VerifyItemsAbsentAsync(""" + public Task LangwordCompletionAfterAngleBracket1() + => VerifyItemsAbsentAsync(""" class C { /// @@ -835,12 +728,10 @@ static void Goo() } } """, "null", "sealed", "true", "false", "await"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22789")] - public async Task LangwordCompletionAfterAngleBracket2() - { - await VerifyItemsAbsentAsync(""" + public Task LangwordCompletionAfterAngleBracket2() + => VerifyItemsAbsentAsync(""" class C { /// @@ -851,12 +742,10 @@ static void Goo() } } """, "null", "sealed", "true", "false", "await"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22789")] - public async Task LangwordCompletionAfterAngleBracket3() - { - await VerifyItemsExistAsync(""" + public Task LangwordCompletionAfterAngleBracket3() + => VerifyItemsExistAsync(""" class C { /// @@ -867,7 +756,6 @@ static void Goo() } } """, "null", "sealed", "true", "false", "await"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11490")] public async Task SeeLangwordAttributeValue() @@ -900,9 +788,8 @@ static void Goo() } [Fact] - public async Task InheritdocAttributes1() - { - await VerifyItemsExistAsync(""" + public Task InheritdocAttributes1() + => VerifyItemsExistAsync(""" class C { /// @@ -913,12 +800,10 @@ static void Goo() } } """, "cref", "path"); - } [Fact] - public async Task InheritdocAttributes2() - { - await VerifyItemsExistAsync(""" + public Task InheritdocAttributes2() + => VerifyItemsExistAsync(""" class C { /// @@ -927,12 +812,10 @@ static void Goo() } } """, "cref", "path"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11489")] - public async Task AttributeNameAfterTagNameInIncompleteTag() - { - var text = """ + public Task AttributeNameAfterTagNameInIncompleteTag() + => VerifyItemExistsAsync(""" class C { /// VerifyItemExistsAsync(""" class C { /// void Goo() { } } - """; - await VerifyItemExistsAsync(text, "cref"); - } + """, "cref"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11489")] - public async Task AttributeNameAfterTagNameInEmptyElement() - { - var text = """ + public Task AttributeNameAfterTagNameInEmptyElement() + => VerifyItemExistsAsync(""" class C { /// void Goo() { } } - """; - await VerifyItemExistsAsync(text, "cref"); - } + """, "cref"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11489")] - public async Task AttributeNameAfterTagNamePartiallyTyped() - { - var text = """ + public Task AttributeNameAfterTagNamePartiallyTyped() + => VerifyItemExistsAsync(""" class C { /// VerifyItemExistsAsync(""" class C { /// @@ -994,14 +865,11 @@ class C /// void Goo() { } } - """; - await VerifyItemExistsAsync(text, "type"); - } + """, "type"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11489")] - public async Task AttributeNameAfterSpecialNameAttribute() - { - var text = """ + public Task AttributeNameAfterSpecialNameAttribute() + => VerifyItemExistsAsync(""" class C { /// @@ -1009,14 +877,11 @@ class C /// void Goo() { } } - """; - await VerifyItemExistsAsync(text, "type"); - } + """, "type"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11489")] - public async Task AttributeNameAfterTextAttribute() - { - var text = """ + public Task AttributeNameAfterTextAttribute() + => VerifyItemExistsAsync(""" class C { /// @@ -1024,14 +889,11 @@ class C /// void Goo() { } } - """; - await VerifyItemExistsAsync(text, "type"); - } + """, "type"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11489")] - public async Task AttributeNameInWrongTagTypeEmptyElement() - { - var text = """ + public Task AttributeNameInWrongTagTypeEmptyElement() + => VerifyItemExistsAsync(""" class C { /// @@ -1039,14 +901,11 @@ class C /// void Goo() { } } - """; - await VerifyItemExistsAsync(text, "type"); - } + """, "type"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11489")] - public async Task AttributeNameInWrongTagTypeElementStartTag() - { - var text = """ + public Task AttributeNameInWrongTagTypeElementStartTag() + => VerifyItemExistsAsync(""" class C { /// @@ -1054,14 +913,11 @@ class C /// void Goo() { } } - """; - await VerifyItemExistsAsync(text, "langword"); - } + """, "langword"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11489")] - public async Task AttributeValueOnQuote() - { - var text = """ + public Task AttributeValueOnQuote() + => VerifyItemExistsAsync(""" class C { /// @@ -1071,9 +927,7 @@ static void Goo() { } } - """; - await VerifyItemExistsAsync(text, "await", usePreviousCharAsTrigger: true); - } + """, "await", usePreviousCharAsTrigger: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/757")] public async Task TermAndDescriptionInsideItem() @@ -1098,9 +952,8 @@ static void Goo() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52738")] - public async Task RecordParam() - { - await VerifyItemsExistAsync(""" + public Task RecordParam() + => VerifyItemsExistAsync(""" /// $$ public record Goo(string MyParameter); """, """ @@ -1108,12 +961,10 @@ public record Goo(string MyParameter); """, """ typeparam name="T" """); - } [Fact] - public async Task PrimaryConstructor_Class_Param() - { - await VerifyItemsExistAsync(""" + public Task PrimaryConstructor_Class_Param() + => VerifyItemsExistAsync(""" /// $$ public class Goo(string MyParameter); """, """ @@ -1121,12 +972,10 @@ public class Goo(string MyParameter); """, """ typeparam name="T" """); - } [Fact] - public async Task PrimaryConstructor_Struct_Param() - { - await VerifyItemsExistAsync(""" + public Task PrimaryConstructor_Struct_Param() + => VerifyItemsExistAsync(""" /// $$ public struct Goo(string MyParameter); """, """ @@ -1134,12 +983,10 @@ public struct Goo(string MyParameter); """, """ typeparam name="T" """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69293")] - public async Task DelegateParamRef() - { - await VerifyItemsExistAsync(""" + public Task DelegateParamRef() + => VerifyItemsExistAsync(""" /// /// $$ /// @@ -1149,12 +996,10 @@ await VerifyItemsExistAsync(""" """, """ typeparamref name="T" """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52738")] - public async Task RecordParamRef() - { - await VerifyItemsExistAsync(""" + public Task RecordParamRef() + => VerifyItemsExistAsync(""" /// /// $$ /// @@ -1164,12 +1009,10 @@ public record Goo(string MyParameter); """, """ typeparamref name="T" """); - } [Fact] - public async Task PrimaryConstructor_Class_ParamRef() - { - await VerifyItemsExistAsync(""" + public Task PrimaryConstructor_Class_ParamRef() + => VerifyItemsExistAsync(""" /// /// $$ /// @@ -1179,12 +1022,10 @@ public class Goo(string MyParameter); """, """ typeparamref name="T" """); - } [Fact] - public async Task PrimaryConstructor_Struct_ParamRef() - { - await VerifyItemsExistAsync(""" + public Task PrimaryConstructor_Struct_ParamRef() + => VerifyItemsExistAsync(""" /// /// $$ /// @@ -1194,7 +1035,6 @@ public struct Goo(string MyParameter); """, """ typeparamref name="T" """); - } [Fact] public async Task TriggerOnDeletion_DeleteInsideAttributeName() diff --git a/src/EditorFeatures/CSharpTest/Debugging/DataTipInfoGetterTests.cs b/src/EditorFeatures/CSharpTest/Debugging/DataTipInfoGetterTests.cs index c69fb7a0ae3ad..a0ee7b7cb12aa 100644 --- a/src/EditorFeatures/CSharpTest/Debugging/DataTipInfoGetterTests.cs +++ b/src/EditorFeatures/CSharpTest/Debugging/DataTipInfoGetterTests.cs @@ -28,9 +28,8 @@ public async Task TestCSharpLanguageDebugInfoGetDataTipSpanAndText() } [Fact] - public async Task Test1() - { - await TestAsync( + public Task Test1() + => TestAsync( """ class C { @@ -40,12 +39,10 @@ void Goo() } } """); - } [Fact] - public async Task Test2() - { - await TestAsync( + public Task Test2() + => TestAsync( """ class C { @@ -55,12 +52,10 @@ void Goo() } } """); - } [Fact] - public async Task Test3() - { - await TestAsync( + public Task Test3() + => TestAsync( """ class C { @@ -70,12 +65,10 @@ void Goo() } } """); - } [Fact] - public async Task Test4() - { - await TestAsync( + public Task Test4() + => TestAsync( """ class C { @@ -85,12 +78,10 @@ void Goo() } } """); - } [Fact] - public async Task Test5() - { - await TestAsync( + public Task Test5() + => TestAsync( """ class C { @@ -100,12 +91,10 @@ void Goo() } } """); - } [Fact] - public async Task Test6() - { - await TestNoDataTipAsync( + public Task Test6() + => TestNoDataTipAsync( """ class C { @@ -115,12 +104,10 @@ void Goo() } } """); - } [Fact] - public async Task Test7() - { - await TestAsync( + public Task Test7() + => TestAsync( """ class C { @@ -130,12 +117,10 @@ void Goo() } } """); - } [Fact] - public async Task Test8() - { - await TestNoDataTipAsync( + public Task Test8() + => TestNoDataTipAsync( """ class C { @@ -145,12 +130,10 @@ void Goo() } } """); - } [Fact] - public async Task TestVar() - { - await TestAsync( + public Task TestVar() + => TestAsync( """ class C { @@ -160,12 +143,10 @@ void Goo() } } """, "int"); - } [Fact] - public async Task TestVariableType() - { - await TestAsync( + public Task TestVariableType() + => TestAsync( """ class C { @@ -175,12 +156,10 @@ void Goo() } } """); - } [Fact] - public async Task TestVariableIdentifier() - { - await TestAsync( + public Task TestVariableIdentifier() + => TestAsync( """ class C { @@ -190,12 +169,10 @@ void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539910")] - public async Task TestLiterals() - { - await TestAsync( + public Task TestLiterals() + => TestAsync( """ class C { @@ -205,12 +182,10 @@ void Goo() } } """, "int"); - } [Fact] - public async Task TestNonExpressions() - { - await TestNoDataTipAsync( + public Task TestNonExpressions() + => TestNoDataTipAsync( """ class C { @@ -220,12 +195,10 @@ void Goo() }$$ } """); - } [Fact] - public async Task TestParameterIdentifier() - { - await TestAsync( + public Task TestParameterIdentifier() + => TestAsync( """ class C { @@ -234,12 +207,10 @@ void Goo(int [|$$i|]) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942699")] - public async Task TestCatchIdentifier() - { - await TestAsync( + public Task TestCatchIdentifier() + => TestAsync( """ class C { @@ -254,7 +225,6 @@ void Goo() } } """); - } [Fact] public async Task TestEvent() @@ -281,16 +251,14 @@ event System.Action [|$$E|] } [Fact] - public async Task TestMethod() - { - await TestAsync( + public Task TestMethod() + => TestAsync( """ class C { int [|$$M|]() { } } """); - } [Fact] public async Task TestTypeParameter() @@ -306,9 +274,8 @@ class C } [Fact] - public async Task UsingAlias() - { - await TestAsync( + public Task UsingAlias() + => TestAsync( """ using [|$$S|] = Static; @@ -316,12 +283,10 @@ static class Static { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540921")] - public async Task TestForEachIdentifier() - { - await TestAsync( + public Task TestForEachIdentifier() + => TestAsync( """ class C { @@ -333,12 +298,10 @@ void Goo(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546328")] - public async Task TestProperty() - { - await TestAsync( + public Task TestProperty() + => TestAsync( """ namespace ConsoleApplication16 { @@ -363,7 +326,6 @@ static void Main(string[] args) } } """); - } [Fact] public async Task TestQueryIdentifier() @@ -452,9 +414,8 @@ object Goo(string[] args) [InlineData("[|Me?.$$B|]?.C?.D")] [InlineData("[|Me?.B?.$$C|]?.D")] [InlineData("[|Me?.B?.C?.$$D|]")] - public async Task TestConditionalAccessExpression(string data) - { - await TestAsync($$""" + public Task TestConditionalAccessExpression(string data) + => TestAsync($$""" class A { B B; @@ -479,15 +440,13 @@ class D { } """); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077843")] [InlineData("/*1*/[|$$Me|]/*2*/?./*3*/B/*4*/?./*5*/C/*6*/")] [InlineData("/*1*/[|Me/*2*/?./*3*/$$B|]/*4*/?./*5*/C/*6*/")] [InlineData("/*1*/[|Me/*2*/?./*3*/B/*4*/?./*5*/$$C|]/*6*/")] - public async Task TestConditionalAccessExpression_Trivia(string data) - { - await TestAsync($$""" + public Task TestConditionalAccessExpression_Trivia(string data) + => TestAsync($$""" class A { B B; @@ -507,60 +466,49 @@ class C { } """); - } [Fact] - public async Task TestLinq1() - { - await TestAsync(""" + public Task TestLinq1() + => TestAsync(""" using System.Linq; int[] args; var v = $$[|args|].Select(a => a.ToString()); """); - } [Fact] - public async Task TestLinq2() - { - await TestAsync(""" + public Task TestLinq2() + => TestAsync(""" using System.Linq; int[] args; var v = {|LinqExpression:[|args.$$Select|](a => a.ToString())|}; """); - } [Fact] - public async Task TestLinq3() - { - await TestAsync(""" + public Task TestLinq3() + => TestAsync(""" using System.Linq; int[] args; var v = $$[|args|].Select(a => a.ToString()).Where(a => a.Length >= 0); """); - } [Fact] - public async Task TestLinq4() - { - await TestAsync(""" + public Task TestLinq4() + => TestAsync(""" using System.Linq; int[] args; var v = {|LinqExpression:[|args.$$Select|](a => a.ToString())|}.Where(a => a.Length >= 0); """); - } [Fact] - public async Task TestLinq5() - { - await TestAsync(""" + public Task TestLinq5() + => TestAsync(""" using System.Linq; int[] args; var v = {|LinqExpression:[|args.Select(a => a.ToString()).$$Where|](a => a.Length >= 0)|}; """); - } } diff --git a/src/EditorFeatures/CSharpTest/Debugging/LocationInfoGetterTests.cs b/src/EditorFeatures/CSharpTest/Debugging/LocationInfoGetterTests.cs index 7a27619a1905f..678faf22dcfd7 100644 --- a/src/EditorFeatures/CSharpTest/Debugging/LocationInfoGetterTests.cs +++ b/src/EditorFeatures/CSharpTest/Debugging/LocationInfoGetterTests.cs @@ -39,9 +39,8 @@ public async Task TestClass() => await TestAsync("class G$$oo { }", "Goo", 0); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538415")] - public async Task TestMethod() - { - await TestAsync( + public Task TestMethod() + => TestAsync( """ class Class { @@ -50,12 +49,10 @@ class Class } } """, "Class.Method()", 0); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] - public async Task TestNamespace() - { - await TestAsync( + public Task TestNamespace() + => TestAsync( """ namespace Namespace { @@ -67,14 +64,10 @@ void Method() } } """, "Namespace.Class.Method()", 2); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49000")] - public async Task TestFileScopedNamespace() - { - // This test behavior is incorrect. This should be Namespace.Class.Method. - // See the associated WorkItem for details. - await TestAsync( + public Task TestFileScopedNamespace() + => TestAsync( """ namespace Namespace; @@ -85,12 +78,10 @@ void Method() }$$ } """, "Namespace.Class.Method()", 2); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] - public async Task TestDottedNamespace() - { - await TestAsync( + public Task TestDottedNamespace() + => TestAsync( """ namespace Namespace.Another { @@ -102,12 +93,10 @@ void Method() } } """, "Namespace.Another.Class.Method()", 2); - } [Fact] - public async Task TestNestedNamespace() - { - await TestAsync( + public Task TestNestedNamespace() + => TestAsync( """ namespace Namespace { @@ -122,12 +111,10 @@ void Method() } } """, "Namespace.Another.Class.Method()", 2); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] - public async Task TestNestedType() - { - await TestAsync( + public Task TestNestedType() + => TestAsync( """ class Outer { @@ -139,12 +126,10 @@ void Quux() } } """, "Outer.Inner.Quux()", 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] - public async Task TestPropertyGetter() - { - await TestAsync( + public Task TestPropertyGetter() + => TestAsync( """ class Class { @@ -157,12 +142,10 @@ string Property } } """, "Class.Property", 4); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] - public async Task TestPropertySetter() - { - await TestAsync( + public Task TestPropertySetter() + => TestAsync( """ class Class { @@ -180,48 +163,40 @@ string Property } } """, "Class.Property", 9); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538415")] - public async Task TestField() - { - await TestAsync( + public Task TestField() + => TestAsync( """ class Class { int fi$$eld; } """, "Class.field", 0); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543494")] - public async Task TestLambdaInFieldInitializer() - { - await TestAsync( + public Task TestLambdaInFieldInitializer() + => TestAsync( """ class Class { Action a = b => { in$$t c; }; } """, "Class.a", 0); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543494")] - public async Task TestMultipleFields() - { - await TestAsync( + public Task TestMultipleFields() + => TestAsync( """ class Class { int a1, a$$2; } """, "Class.a2", 0); - } [Fact] - public async Task TestConstructor() - { - await TestAsync( + public Task TestConstructor() + => TestAsync( """ class C1 { @@ -231,12 +206,10 @@ class C1 $$} } """, "C1.C1()", 3); - } [Fact] - public async Task TestDestructor() - { - await TestAsync( + public Task TestDestructor() + => TestAsync( """ class C1 { @@ -245,12 +218,10 @@ class C1 $$} } """, "C1.~C1()", 2); - } [Fact] - public async Task TestOperator() - { - await TestAsync( + public Task TestOperator() + => TestAsync( """ namespace N1 { @@ -263,12 +234,10 @@ class C1 } } """, "N1.C1.+(C1 x, C1 y)", 2); // Old implementation reports "operator +" (rather than "+")... - } [Fact] - public async Task TestConversionOperator() - { - await TestAsync( + public Task TestConversionOperator() + => TestAsync( """ namespace N1 { @@ -284,12 +253,10 @@ class C2 } } """, "N1.C1.N1.C2(N1.C1 x)", 2); // Old implementation reports "explicit operator N1.C2" (rather than "N1.C2")... - } [Fact] - public async Task TestEvent() - { - await TestAsync( + public Task TestEvent() + => TestAsync( """ class C1 { @@ -297,12 +264,10 @@ class C1 event D1 e1$$; } """, "C1.e1", 0); - } [Fact] - public async Task TextExplicitInterfaceImplementation() - { - await TestAsync( + public Task TextExplicitInterfaceImplementation() + => TestAsync( """ interface I1 { @@ -315,12 +280,10 @@ void I1.M1() $$} } """, "C1.M1()", 2); - } [Fact] - public async Task TextIndexer() - { - await TestAsync( + public Task TextIndexer() + => TestAsync( """ class C1 { @@ -333,36 +296,30 @@ C1 this[int x] } } """, "C1.this[int x]", 4); - } [Fact] - public async Task TestParamsParameter() - { - await TestAsync( + public Task TestParamsParameter() + => TestAsync( """ class C1 { void M1(params int[] x) { $$ } } """, "C1.M1(params int[] x)", 0); - } [Fact] - public async Task TestArglistParameter() - { - await TestAsync( + public Task TestArglistParameter() + => TestAsync( """ class C1 { void M1(__arglist) { $$ } } """, "C1.M1(__arglist)", 0); // Old implementation does not show "__arglist"... - } [Fact] - public async Task TestRefAndOutParameters() - { - await TestAsync( + public Task TestRefAndOutParameters() + => TestAsync( """ class C1 { @@ -372,12 +329,10 @@ void M1( ref int x, out int y ) } } """, "C1.M1( ref int x, out int y )", 2); // Old implementation did not show extra spaces around the parameters... - } [Fact] - public async Task TestOptionalParameters() - { - await TestAsync( + public Task TestOptionalParameters() + => TestAsync( """ class C1 { @@ -387,12 +342,10 @@ void M1(int x =1) } } """, "C1.M1(int x =1)", 2); - } [Fact] - public async Task TestExtensionMethod() - { - await TestAsync( + public Task TestExtensionMethod() + => TestAsync( """ static class C1 { @@ -401,48 +354,40 @@ static void M1(this int x) }$$ } """, "C1.M1(this int x)", 2); - } [Fact] - public async Task TestGenericType() - { - await TestAsync( + public Task TestGenericType() + => TestAsync( """ class C1 { static void M1() { $$ } } """, "C1.M1()", 0); - } [Fact] - public async Task TestGenericMethod() - { - await TestAsync( + public Task TestGenericMethod() + => TestAsync( """ class C1 { static void M1() { $$ } } """, "C1.M1()", 0); - } [Fact] - public async Task TestGenericParameters() - { - await TestAsync( + public Task TestGenericParameters() + => TestAsync( """ class C1 { static void M1(C1 x, V y) { $$ } } """, "C1.M1(C1 x, V y)", 0); - } [Fact] - public async Task TestMissingNamespace() - { - await TestAsync( + public Task TestMissingNamespace() + => TestAsync( """ { class Class @@ -451,12 +396,10 @@ class Class } } """, "Class.a2", 0); - } [Fact] - public async Task TestMissingNamespaceName() - { - await TestAsync( + public Task TestMissingNamespaceName() + => TestAsync( """ namespace { @@ -468,12 +411,10 @@ int M1() } } """, "?.C1.M1()", 1); - } [Fact] - public async Task TestMissingClassName() - { - await TestAsync( + public Task TestMissingClassName() + => TestAsync( """ namespace N1 class @@ -484,12 +425,10 @@ int M1() } } """, "N1.?.M1()", 1); - } [Fact] - public async Task TestMissingMethodName() - { - await TestAsync( + public Task TestMissingMethodName() + => TestAsync( """ namespace N1 { @@ -501,12 +440,10 @@ static void (ref int x) } } """, "N1.C1", 4); - } [Fact] - public async Task TestMissingParameterList() - { - await TestAsync( + public Task TestMissingParameterList() + => TestAsync( """ namespace N1 { @@ -518,34 +455,27 @@ static void M1 } } """, "N1.C1.M1", 2); - } [Fact] - public async Task TopLevelField() - { - await TestAsync( + public Task TopLevelField() + => TestAsync( """ $$int f1; """, "f1", 0, new CSharpParseOptions(kind: SourceCodeKind.Script)); - } [Fact] - public async Task TopLevelMethod() - { - await TestAsync( + public Task TopLevelMethod() + => TestAsync( """ int M1(int x) { $$} """, "M1(int x)", 2, new CSharpParseOptions(kind: SourceCodeKind.Script)); - } [Fact] - public async Task TopLevelStatement() - { - await TestAsync( + public Task TopLevelStatement() + => TestAsync( """ $$System.Console.WriteLine("Hello") """, null, 0, new CSharpParseOptions(kind: SourceCodeKind.Script)); - } } diff --git a/src/EditorFeatures/CSharpTest/Debugging/ProximityExpressionsGetterTests.cs b/src/EditorFeatures/CSharpTest/Debugging/ProximityExpressionsGetterTests.cs index de150a2e46996..824814ca71c05 100644 --- a/src/EditorFeatures/CSharpTest/Debugging/ProximityExpressionsGetterTests.cs +++ b/src/EditorFeatures/CSharpTest/Debugging/ProximityExpressionsGetterTests.cs @@ -44,21 +44,23 @@ private static SyntaxTree GetTreeFromCode(string code) [Fact] public void TestWithinStatement_1() { - var tree = GetTreeFromCode(@"using System; -using System.Collections.Generic; - -namespace ConsoleApplication1 -{ - class Program - { - static void Main(string[] args) - { - var xx = true; - var yy = new List(); - yy.Add(xx?true:false); - } - } -}"); + var tree = GetTreeFromCode(""" + using System; + using System.Collections.Generic; + + namespace ConsoleApplication1 + { + class Program + { + static void Main(string[] args) + { + var xx = true; + var yy = new List(); + yy.Add(xx?true:false); + } + } + } + """); var terms = CSharpProximityExpressionsService.GetProximityExpressions(tree, 245, cancellationToken: default); Assert.NotNull(terms); AssertEx.Equal((string[])["yy", "xx"], terms); @@ -89,36 +91,34 @@ private static async Task TestTryDoInMainAsync(string body, bool topLevelStateme } else { - input = $@"class Program -{{ - static void Main(string[] args) - {{ -{string.Join(Environment.NewLine, body.ReplaceLineEndings("\n").Split('\n').Select(line => line == "" ? line : $" {line}"))} - }} -}}"; + input = $$""" + class Program + { + static void Main(string[] args) + { + {{string.Join(Environment.NewLine, body.ReplaceLineEndings("\n").Split('\n').Select(line => line == "" ? line : $" {line}"))}} + } + } + """; } await TestTryDoAsync(input, expectedTerms); } - private static async Task TestTryDoAsync(string input, params string[] expectedTerms) - { - await TestProximityExpressionGetterAsync(input, async (getter, document, position) => + private static Task TestTryDoAsync(string input, params string[] expectedTerms) + => TestProximityExpressionGetterAsync(input, async (getter, document, position) => { var actualTerms = await getter.GetProximityExpressionsAsync(document, position, CancellationToken.None); Assert.True(actualTerms is null or { Count: > 0 }); AssertEx.Equal(expectedTerms, actualTerms ?? Array.Empty()); }); - } - private static async Task TestIsValidAsync(string input, string expression, bool expectedValid) - { - await TestProximityExpressionGetterAsync(input, async (getter, semanticSnapshot, position) => + private static Task TestIsValidAsync(string input, string expression, bool expectedValid) + => TestProximityExpressionGetterAsync(input, async (getter, semanticSnapshot, position) => { var actualValid = await getter.IsValidAsync(semanticSnapshot, position, expression, CancellationToken.None); Assert.Equal(expectedValid, actualValid); }); - } [Fact] public async Task TestTryDo1() @@ -133,11 +133,8 @@ public async Task TestIsValid1() => await TestIsValidAsync("class Class { void Method() { string local;$$ } }", "local", true); [Fact] - public async Task TestIsValidWithDiagnostics() - { - // local doesn't exist in this context - await TestIsValidAsync("class Class { void Method() { string local; } $$}", "local", false); - } + public Task TestIsValidWithDiagnostics() + => TestIsValidAsync("class Class { void Method() { string local; } $$}", "local", false); [Fact] public async Task TestIsValidReferencingLocalBeforeDeclaration() @@ -156,37 +153,37 @@ public async Task TestIsValidLocalAfterPosition() => await TestIsValidAsync("class Class { void Method() { $$ int i; string local; } }", "local", false); [Fact] - public async Task TestThis() - { - await TestTryDoAsync(@" -class Class -{ - public Class() : this(true) - { - base.ToString(); - this.ToString()$$; - } -}", "this"); - } + public Task TestThis() + => TestTryDoAsync(""" + class Class + { + public Class() : this(true) + { + base.ToString(); + this.ToString()$$; + } + } + """, "this"); [Theory, CombinatorialData] public async Task TestArrayCreationExpression(bool topLevelStatement) { if (!topLevelStatement) { - await TestTryDoAsync(@" -class Class -{ - void Method() - { - int[] i = new int[] { 3 }$$; - } -}", "i", "this"); + await TestTryDoAsync(""" + class Class + { + void Method() + { + int[] i = new int[] { 3 }$$; + } + } + """, "i", "this"); } - await TestTryDoInMainAsync(@" -int[] i = new int[] { 3 }$$; -", topLevelStatement, "i", "args"); + await TestTryDoInMainAsync(""" + int[] i = new int[] { 3 }$$; + """, topLevelStatement, "i", "args"); } [Theory, CombinatorialData] @@ -194,20 +191,22 @@ public async Task TestPostfixUnaryExpressionSyntax(bool topLevelStatement) { if (!topLevelStatement) { - await TestTryDoAsync(@" -class Class -{ - void Method() - { - int i = 3; - i++$$; - } -}", "i", "this"); + await TestTryDoAsync(""" + class Class + { + void Method() + { + int i = 3; + i++$$; + } + } + """, "i", "this"); } - await TestTryDoInMainAsync(@"int i = 3; -i++$$; -", topLevelStatement, "i"); + await TestTryDoInMainAsync(""" + int i = 3; + i++$$; + """, topLevelStatement, "i"); } [Theory, CombinatorialData] @@ -215,154 +214,147 @@ public async Task TestLabeledStatement(bool topLevelStatement) { if (!topLevelStatement) { - await TestTryDoAsync(@" -class Class -{ - void Method() - { - label: int i = 3; - label2$$: i++; - } -}", "i", "this"); + await TestTryDoAsync(""" + class Class + { + void Method() + { + label: int i = 3; + label2$$: i++; + } + } + """, "i", "this"); } - await TestTryDoInMainAsync(@"label: int i = 3; -label2$$: i++; -", topLevelStatement, "i"); + await TestTryDoInMainAsync(""" + label: int i = 3; + label2$$: i++; + """, topLevelStatement, "i"); } [Theory, CombinatorialData] - public async Task TestThrowStatement(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"e = new Exception(); -thr$$ow e; -", topLevelStatement, "e"); - } + public Task TestThrowStatement(bool topLevelStatement) + => TestTryDoInMainAsync(""" + e = new Exception(); + thr$$ow e; + """, topLevelStatement, "e"); [Theory, CombinatorialData] - public async Task TestDoStatement(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"do$$ { } while (true); -", topLevelStatement, "args"); - } + public Task TestDoStatement(bool topLevelStatement) + => TestTryDoInMainAsync(""" + do$$ { } while (true); + """, topLevelStatement, "args"); [Theory, CombinatorialData] - public async Task TestLockStatement(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"lock(typeof(Cl$$ass)) { }; -", topLevelStatement, "args"); - } + public Task TestLockStatement(bool topLevelStatement) + => TestTryDoInMainAsync(""" + lock(typeof(Cl$$ass)) { }; + """, topLevelStatement, "args"); [Theory, CombinatorialData] - public async Task TestWhileStatement(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"while(DateTime.Now <$$ DateTime.Now) { }; -", topLevelStatement, "DateTime", "DateTime.Now", "args"); - } + public Task TestWhileStatement(bool topLevelStatement) + => TestTryDoInMainAsync(""" + while(DateTime.Now <$$ DateTime.Now) { }; + """, topLevelStatement, "DateTime", "DateTime.Now", "args"); [Theory, CombinatorialData] - public async Task TestForStatementWithDeclarators(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"for(int i = 0; i < 10; i$$++) { } -", topLevelStatement, "i", "args"); - } + public Task TestForStatementWithDeclarators(bool topLevelStatement) + => TestTryDoInMainAsync(""" + for(int i = 0; i < 10; i$$++) { } + """, topLevelStatement, "i", "args"); [Theory, CombinatorialData] - public async Task TestForStatementWithInitializers(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"int i = 0; -for(i = 1; i < 10; i$$++) { } -", topLevelStatement, "i"); - } + public Task TestForStatementWithInitializers(bool topLevelStatement) + => TestTryDoInMainAsync(""" + int i = 0; + for(i = 1; i < 10; i$$++) { } + """, topLevelStatement, "i"); [Theory, CombinatorialData] public async Task TestUsingStatement(bool topLevelStatement) { if (!topLevelStatement) { - await TestTryDoAsync(@" -class Class -{ - void Method() - { - using (FileStream fs = new FileStream($$)) { } - } -}", "this"); + await TestTryDoAsync(""" + class Class + { + void Method() + { + using (FileStream fs = new FileStream($$)) { } + } + } + """, "this"); } - await TestTryDoInMainAsync(@"using (FileStream fs = new FileStream($$)) { } -", topLevelStatement, "args"); + await TestTryDoInMainAsync(""" + using (FileStream fs = new FileStream($$)) { } + """, topLevelStatement, "args"); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538879")] - public async Task TestValueInPropertySetter() - { - await TestTryDoAsync(@" -class Class -{ - string Name - { - get { return """"; } - set { $$ } - } -}", "this", "value"); - } + public Task TestValueInPropertySetter() + => TestTryDoAsync(""" + class Class + { + string Name + { + get { return ""; } + set { $$ } + } + } + """, "this", "value"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48504")] - public async Task TestValueInPropertyInit() - { - await TestTryDoAsync(@" -class Class -{ - string Name - { - get { return """"; } - init { $$ } - } -}", "this", "value"); - } + public Task TestValueInPropertyInit() + => TestTryDoAsync(""" + class Class + { + string Name + { + get { return ""; } + init { $$ } + } + } + """, "this", "value"); [Fact] - public async Task TestValueInEventAdd() - { - await TestTryDoAsync(@" -class Class -{ - event Action Event - { - add { $$ } - set { } - } -}", "this", "value"); - } + public Task TestValueInEventAdd() + => TestTryDoAsync(""" + class Class + { + event Action Event + { + add { $$ } + set { } + } + } + """, "this", "value"); [Fact] - public async Task TestValueInEventRemove() - { - await TestTryDoAsync(@" -class Class -{ - event Action Event - { - add { } - remove { $$ } - } -}", "this", "value"); - } + public Task TestValueInEventRemove() + => TestTryDoAsync(""" + class Class + { + event Action Event + { + add { } + remove { $$ } + } + } + """, "this", "value"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538880")] - public async Task TestValueInIndexerSetter() - { - await TestTryDoAsync(@" -class Class -{ - string this[int index] - { - get { return """"; } - set { $$ } - } -}", "index", "this", "value"); - } + public Task TestValueInIndexerSetter() + => TestTryDoAsync(""" + class Class + { + string this[int index] + { + get { return ""; } + set { $$ } + } + } + """, "index", "this", "value"); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538881")] @@ -370,20 +362,22 @@ public async Task TestCatchBlock(bool topLevelStatement) { if (!topLevelStatement) { - await TestTryDoAsync(@" -class Class -{ - void Method() - { - try { } - catch(Exception ex) { int $$ } - } -}", "ex", "this"); + await TestTryDoAsync(""" + class Class + { + void Method() + { + try { } + catch(Exception ex) { int $$ } + } + } + """, "ex", "this"); } - await TestTryDoInMainAsync(@"try { } -catch(Exception ex) { int $$ } -", topLevelStatement, "ex"); + await TestTryDoInMainAsync(""" + try { } + catch(Exception ex) { int $$ } + """, topLevelStatement, "ex"); } [Theory, CombinatorialData] @@ -392,20 +386,22 @@ public async Task TestCatchBlockEmpty_OpenBrace(bool topLevelStatement) { if (!topLevelStatement) { - await TestTryDoAsync(@" -class Class -{ - void Method() - { - try { } - catch(Exception ex) { $$ } - } -}", "ex", "this"); + await TestTryDoAsync(""" + class Class + { + void Method() + { + try { } + catch(Exception ex) { $$ } + } + } + """, "ex", "this"); } - await TestTryDoInMainAsync(@"try { } -catch(Exception ex) { $$ } -", topLevelStatement, "ex"); + await TestTryDoInMainAsync(""" + try { } + catch(Exception ex) { $$ } + """, topLevelStatement, "ex"); } [Theory, CombinatorialData] @@ -413,20 +409,22 @@ public async Task TestCatchBlockEmpty_CloseBrace(bool topLevelStatement) { if (!topLevelStatement) { - await TestTryDoAsync(@" -class Class -{ - void Method() - { - try { } - catch(Exception ex) { } $$ - } -}", "this"); + await TestTryDoAsync(""" + class Class + { + void Method() + { + try { } + catch(Exception ex) { } $$ + } + } + """, "this"); } - await TestTryDoInMainAsync(@"try { } -catch(Exception ex) { } $$ -", topLevelStatement); + await TestTryDoInMainAsync(""" + try { } + catch(Exception ex) { } $$ + """, topLevelStatement); } [Theory, CombinatorialData] @@ -435,409 +433,385 @@ public async Task TestObjectCreation(bool topLevelStatement) { if (!topLevelStatement) { - await TestTryDoAsync(@" -class Class -{ - void Method() - { - $$Goo(new Bar(a).Baz); - } -}", "a", "new Bar(a).Baz", "Goo", "this"); + await TestTryDoAsync(""" + class Class + { + void Method() + { + $$Goo(new Bar(a).Baz); + } + } + """, "a", "new Bar(a).Baz", "Goo", "this"); } - await TestTryDoInMainAsync(@"$$Goo(new Bar(a).Baz); -", topLevelStatement, "a", "new Bar(a).Baz", "Goo", "args"); + await TestTryDoInMainAsync(""" + $$Goo(new Bar(a).Baz); + """, topLevelStatement, "a", "new Bar(a).Baz", "Goo", "args"); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538874")] - public async Task Test2() - { - await TestIsValidAsync(@" -class D -{ - private static int x; -} - -class Class -{ - void Method() - { - $$Goo(D.x); - } -}", "D.x", false); - } + public Task Test2() + => TestIsValidAsync(""" + class D + { + private static int x; + } + + class Class + { + void Method() + { + $$Goo(D.x); + } + } + """, "D.x", false); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538890")] - public async Task TestArrayCreation() - { - await TestTryDoAsync(@" -class Class -{ - int a; - void Method() - { - $$new int[] { a }; - } -}", "this"); - } + public Task TestArrayCreation() + => TestTryDoAsync(""" + class Class + { + int a; + void Method() + { + $$new int[] { a }; + } + } + """, "this"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/751141")] - public async Task Bug751141() - { - await TestTryDoAsync(@" -class Program -{ - double m_double = 1.1; - static void Main(string[] args) - { - new Program().M(); - } - void M() - { - int local_int = (int)m_double; - $$System.Diagnostics.Debugger.Break(); - } -} -", "System.Diagnostics.Debugger", "local_int", "m_double", "(int)m_double", "this"); - } + public Task Bug751141() + => TestTryDoAsync(""" + class Program + { + double m_double = 1.1; + static void Main(string[] args) + { + new Program().M(); + } + void M() + { + int local_int = (int)m_double; + $$System.Diagnostics.Debugger.Break(); + } + } + """, "System.Diagnostics.Debugger", "local_int", "m_double", "(int)m_double", "this"); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161"), CombinatorialData] - public async Task ForLoopExpressionsInFirstStatementOfLoop1(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"for(int i = 0; i < 5; i++) -{ - $$var x = 8; -} -", topLevelStatement, "i", "x"); - } + public Task ForLoopExpressionsInFirstStatementOfLoop1(bool topLevelStatement) + => TestTryDoInMainAsync(""" + for(int i = 0; i < 5; i++) + { + $$var x = 8; + } + """, topLevelStatement, "i", "x"); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161"), CombinatorialData] - public async Task ForLoopExpressionsInFirstStatementOfLoop2(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"int i = 0, j = 0, k = 0, m = 0, n = 0; + public Task ForLoopExpressionsInFirstStatementOfLoop2(bool topLevelStatement) + => TestTryDoInMainAsync(""" + int i = 0, j = 0, k = 0, m = 0, n = 0; -for(i = 0; j < 5; k++) -{ - $$m = 8; - n = 7; -} -", topLevelStatement, "m", "i", "j", "k"); - } + for(i = 0; j < 5; k++) + { + $$m = 8; + n = 7; + } + """, topLevelStatement, "m", "i", "j", "k"); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161"), CombinatorialData] - public async Task ForLoopExpressionsInFirstStatementOfLoop3(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"int i = 0, j = 0, k = 0, m = 0; + public Task ForLoopExpressionsInFirstStatementOfLoop3(bool topLevelStatement) + => TestTryDoInMainAsync(""" + int i = 0, j = 0, k = 0, m = 0; -for(i = 0; j < 5; k++) -{ - var m = 8; - $$var n = 7; -} -", topLevelStatement, "m", "n"); - } + for(i = 0; j < 5; k++) + { + var m = 8; + $$var n = 7; + } + """, topLevelStatement, "m", "n"); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161"), CombinatorialData] - public async Task ForLoopExpressionsInFirstStatementOfLoop4(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"int i = 0, j = 0, k = 0, m = 0; + public Task ForLoopExpressionsInFirstStatementOfLoop4(bool topLevelStatement) + => TestTryDoInMainAsync(""" + int i = 0, j = 0, k = 0, m = 0; -for(i = 0; j < 5; k++) - $$m = 8; -", topLevelStatement, "m", "i", "j", "k"); - } + for(i = 0; j < 5; k++) + $$m = 8; + """, topLevelStatement, "m", "i", "j", "k"); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161"), CombinatorialData] - public async Task ForEachLoopExpressionsInFirstStatementOfLoop1(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"foreach (var x in new int[] { 1, 2, 3 }) -{ - $$var z = 0; -} -", topLevelStatement, "x", "z"); - } + public Task ForEachLoopExpressionsInFirstStatementOfLoop1(bool topLevelStatement) + => TestTryDoInMainAsync(""" + foreach (var x in new int[] { 1, 2, 3 }) + { + $$var z = 0; + } + """, topLevelStatement, "x", "z"); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161"), CombinatorialData] - public async Task ForEachLoopExpressionsInFirstStatementOfLoop2(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"foreach (var x in new int[] { 1, 2, 3 }) - $$var z = 0; -", topLevelStatement, "x", "z"); - } + public Task ForEachLoopExpressionsInFirstStatementOfLoop2(bool topLevelStatement) + => TestTryDoInMainAsync(""" + foreach (var x in new int[] { 1, 2, 3 }) + $$var z = 0; + """, topLevelStatement, "x", "z"); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161"), CombinatorialData] - public async Task ExpressionsAfterForLoop1(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"int a = 0, b = 0, c = 0, d = 0; + public Task ExpressionsAfterForLoop1(bool topLevelStatement) + => TestTryDoInMainAsync(""" + int a = 0, b = 0, c = 0, d = 0; -for (a = 5; b < 1; b++) -{ - c = 8; - d = 9; // included -} - -$$var z = 0; -", topLevelStatement, "a", "b", "d", "z"); - } + for (a = 5; b < 1; b++) + { + c = 8; + d = 9; // included + } - [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161"), CombinatorialData] - public async Task ExpressionsAfterForLoop2(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"int a = 0, b = 0, c = 0; - -for (a = 5; b < 1; b++) -{ - c = 8; - int d = 9; // not included -} - -$$var z = 0; -", topLevelStatement, "a", "b", "z"); - } + $$var z = 0; + """, topLevelStatement, "a", "b", "d", "z"); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161"), CombinatorialData] - public async Task ExpressionsAfterForEachLoop(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"int a = 0, b = 0, c = 0, d = 0; + public Task ExpressionsAfterForLoop2(bool topLevelStatement) + => TestTryDoInMainAsync(""" + int a = 0, b = 0, c = 0; -foreach (var q in new int[] {1, 2, 3}) -{ - c = 8; - d = 9; // included -} - -$$var z = 0; -", topLevelStatement, "q", "d", "z"); - } + for (a = 5; b < 1; b++) + { + c = 8; + int d = 9; // not included + } - [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161"), CombinatorialData] - public async Task ExpressionsAfterNestedForLoop(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; - -for (a = 5; b < 1; b++) -{ - c = 8; - d = 9; - for (a = 7; b < 9; b--) - { - e = 8; - f = 10; // included - } -} - -$$var z = 0; -", topLevelStatement, "a", "b", "f", "z"); - } + $$var z = 0; + """, topLevelStatement, "a", "b", "z"); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161"), CombinatorialData] - public async Task ExpressionsAfterCheckedStatement(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; + public Task ExpressionsAfterForEachLoop(bool topLevelStatement) + => TestTryDoInMainAsync(""" + int a = 0, b = 0, c = 0, d = 0; -checked -{ - a = 7; - b = 0; // included -} - -$$var z = 0; -", topLevelStatement, "b", "z"); - } + foreach (var q in new int[] {1, 2, 3}) + { + c = 8; + d = 9; // included + } - [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161"), CombinatorialData] - public async Task ExpressionsAfterUncheckedStatement(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; + $$var z = 0; + """, topLevelStatement, "q", "d", "z"); -unchecked -{ - a = 7; - b = 0; // included -} - -$$var z = 0; -", topLevelStatement, "b", "z"); - } + [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161"), CombinatorialData] + public Task ExpressionsAfterNestedForLoop(bool topLevelStatement) + => TestTryDoInMainAsync(""" + int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; + + for (a = 5; b < 1; b++) + { + c = 8; + d = 9; + for (a = 7; b < 9; b--) + { + e = 8; + f = 10; // included + } + } + + $$var z = 0; + """, topLevelStatement, "a", "b", "f", "z"); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161"), CombinatorialData] - public async Task ExpressionsAfterIfStatement(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; + public Task ExpressionsAfterCheckedStatement(bool topLevelStatement) + => TestTryDoInMainAsync(""" + int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; -if (a == 0) -{ - c = 8; - d = 9; // included -} + checked + { + a = 7; + b = 0; // included + } -$$var z = 0; -", topLevelStatement, "a", "d", "z"); - } + $$var z = 0; + """, topLevelStatement, "b", "z"); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161"), CombinatorialData] - public async Task ExpressionsAfterIfStatementWithElse(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; + public Task ExpressionsAfterUncheckedStatement(bool topLevelStatement) + => TestTryDoInMainAsync(""" + int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; -if (a == 0) -{ - c = 8; - d = 9; // included -} -else -{ - e = 1; - f = 2; // included -} + unchecked + { + a = 7; + b = 0; // included + } -$$var z = 0; -", topLevelStatement, "a", "d", "f", "z"); - } + $$var z = 0; + """, topLevelStatement, "b", "z"); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161"), CombinatorialData] - public async Task ExpressionsAfterLockStatement(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; + public Task ExpressionsAfterIfStatement(bool topLevelStatement) + => TestTryDoInMainAsync(""" + int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; -lock (new object()) -{ - a = 2; - b = 3; // included -} + if (a == 0) + { + c = 8; + d = 9; // included + } -$$var z = 0; -", topLevelStatement, "b", "z"); - } + $$var z = 0; + """, topLevelStatement, "a", "d", "z"); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161"), CombinatorialData] - public async Task ExpressionsAfterSwitchStatement(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0; - -switch(a) -{ - case 1: - b = 7; - c = 8; // included - break; - case 2: - d = 9; - e = 10; // included - break; - default: - f = 1; - g = 2; // included - break; -} - -$$var z = 0; -", topLevelStatement, "a", "c", "e", "g", "z"); - } + public Task ExpressionsAfterIfStatementWithElse(bool topLevelStatement) + => TestTryDoInMainAsync(""" + int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; + + if (a == 0) + { + c = 8; + d = 9; // included + } + else + { + e = 1; + f = 2; // included + } + + $$var z = 0; + """, topLevelStatement, "a", "d", "f", "z"); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161"), CombinatorialData] - public async Task ExpressionsAfterTryStatement(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0; + public Task ExpressionsAfterLockStatement(bool topLevelStatement) + => TestTryDoInMainAsync(""" + int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; -try -{ - a = 2; - b = 3; // included -} -catch (System.DivideByZeroException) -{ - c = 2; - d = 5; // included -} -catch (System.EntryPointNotFoundException) -{ - e = 8; - f = 9; // included -} + lock (new object()) + { + a = 2; + b = 3; // included + } -$$var z = 0; -", topLevelStatement, "b", "d", "f", "z"); - } + $$var z = 0; + """, topLevelStatement, "b", "z"); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161"), CombinatorialData] - public async Task ExpressionsAfterTryStatementWithFinally(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0; + public Task ExpressionsAfterSwitchStatement(bool topLevelStatement) + => TestTryDoInMainAsync(""" + int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0; + + switch(a) + { + case 1: + b = 7; + c = 8; // included + break; + case 2: + d = 9; + e = 10; // included + break; + default: + f = 1; + g = 2; // included + break; + } + + $$var z = 0; + """, topLevelStatement, "a", "c", "e", "g", "z"); -try -{ - a = 2; - b = 3; -} -catch (System.DivideByZeroException) -{ - c = 2; - d = 5; -} -catch (System.EntryPointNotFoundException) -{ - e = 8; - f = 9; -} -finally -{ - g = 2; // included -} + [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161"), CombinatorialData] + public Task ExpressionsAfterTryStatement(bool topLevelStatement) + => TestTryDoInMainAsync(""" + int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0; + + try + { + a = 2; + b = 3; // included + } + catch (System.DivideByZeroException) + { + c = 2; + d = 5; // included + } + catch (System.EntryPointNotFoundException) + { + e = 8; + f = 9; // included + } + + $$var z = 0; + """, topLevelStatement, "b", "d", "f", "z"); -$$var z = 0; -", topLevelStatement, "g", "z"); - } + [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161"), CombinatorialData] + public Task ExpressionsAfterTryStatementWithFinally(bool topLevelStatement) + => TestTryDoInMainAsync(""" + int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0; + + try + { + a = 2; + b = 3; + } + catch (System.DivideByZeroException) + { + c = 2; + d = 5; + } + catch (System.EntryPointNotFoundException) + { + e = 8; + f = 9; + } + finally + { + g = 2; // included + } + + $$var z = 0; + """, topLevelStatement, "g", "z"); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161"), CombinatorialData] - public async Task ExpressionsAfterUsingStatement(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0; + public Task ExpressionsAfterUsingStatement(bool topLevelStatement) + => TestTryDoInMainAsync(""" + int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0; -using (null as System.IDisposable) -{ - a = 4; - b = 8; // Included -} + using (null as System.IDisposable) + { + a = 4; + b = 8; // Included + } -$$var z = 0; -", topLevelStatement, "b", "z"); - } + $$var z = 0; + """, topLevelStatement, "b", "z"); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161"), CombinatorialData] - public async Task ExpressionsAfterWhileStatement(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0; + public Task ExpressionsAfterWhileStatement(bool topLevelStatement) + => TestTryDoInMainAsync(""" + int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0; -while (a < 5) -{ - a++; - b = 8; // Included -} + while (a < 5) + { + a++; + b = 8; // Included + } -$$var z = 0; -", topLevelStatement, "a", "b", "z"); - } + $$var z = 0; + """, topLevelStatement, "a", "b", "z"); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/778215"), CombinatorialData] - public async Task ExpressionsInParenthesizedExpressions(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"int i = 0, j = 0, k = 0, m = 0; -int flags = 7; + public Task ExpressionsInParenthesizedExpressions(bool topLevelStatement) + => TestTryDoInMainAsync(""" + int i = 0, j = 0, k = 0, m = 0; + int flags = 7; -if((flags & i) == k) -{ - $$ m = 8; -} -", topLevelStatement, "m", "flags", "i", "k"); - } + if((flags & i) == k) + { + $$ m = 8; + } + """, topLevelStatement, "m", "flags", "i", "k"); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/58337"), CombinatorialData] - public async Task ExpressionsInTopLevelStatement(bool topLevelStatement) - { - await TestTryDoInMainAsync(@"int a = 1; -int b = 2; -$$ Console.WriteLine(""Hello, World!""); -", topLevelStatement, "Console", "b"); - } + public Task ExpressionsInTopLevelStatement(bool topLevelStatement) + => TestTryDoInMainAsync(""" + int a = 1; + int b = 2; + $$ Console.WriteLine("Hello, World!"); + """, topLevelStatement, "Console", "b"); } diff --git a/src/EditorFeatures/CSharpTest/DecompiledSource/DecompiledSourceFormattingTests.cs b/src/EditorFeatures/CSharpTest/DecompiledSource/DecompiledSourceFormattingTests.cs index 66c6f486ebf20..233c2e9b52430 100644 --- a/src/EditorFeatures/CSharpTest/DecompiledSource/DecompiledSourceFormattingTests.cs +++ b/src/EditorFeatures/CSharpTest/DecompiledSource/DecompiledSourceFormattingTests.cs @@ -7,8 +7,8 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.CSharp.DecompiledSource; +using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; @@ -20,9 +20,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.DecompiledSource; public sealed class DecompiledSourceFormattingTests { [Fact] - public async Task TestIfFormatting1() - { - await TestAsync( + public Task TestIfFormatting1() + => TestAsync( """ class C { void M() { @@ -42,12 +41,10 @@ void M() } } """); - } [Fact] - public async Task TestIfFormatting2() - { - await TestAsync( + public Task TestIfFormatting2() + => TestAsync( """ class C { void M() { @@ -70,12 +67,10 @@ void M() } } """); - } [Fact] - public async Task TestIfFormatting3() - { - await TestAsync( + public Task TestIfFormatting3() + => TestAsync( """ class C { void M() { @@ -101,12 +96,10 @@ void M() } } """); - } [Fact] - public async Task TestTryCatchFinally() - { - await TestAsync( + public Task TestTryCatchFinally() + => TestAsync( """ class C { void M() { @@ -134,12 +127,10 @@ void M() } } """); - } [Fact] - public async Task TestDoWhile() - { - await TestAsync( + public Task TestDoWhile() + => TestAsync( """ class C { void M() { @@ -159,12 +150,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedIf() - { - await TestAsync( + public Task TestNestedIf() + => TestAsync( """ class C { void M() { @@ -189,12 +178,10 @@ void M() } } """); - } [Fact] - public async Task TestBraces() - { - await TestAsync( + public Task TestBraces() + => TestAsync( """ class C { void M() { @@ -248,7 +235,6 @@ void M() } } """); - } private static async Task TestAsync(string input, string expected) { diff --git a/src/EditorFeatures/CSharpTest/Diagnostics/AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest.cs b/src/EditorFeatures/CSharpTest/Diagnostics/AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest.cs index de315e1a8000d..9ea1e21c7bfcd 100644 --- a/src/EditorFeatures/CSharpTest/Diagnostics/AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest.cs +++ b/src/EditorFeatures/CSharpTest/Diagnostics/AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest.cs @@ -2,21 +2,29 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable +#if CODE_STYLE +extern alias CODESTYLE_UTILITIES; +#endif +using System.Diagnostics.CodeAnalysis; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; +using Microsoft.CodeAnalysis.Remote.Testing; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; -public abstract partial class AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest : AbstractDiagnosticProviderBasedUserDiagnosticTest -{ - protected AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest(ITestOutputHelper logger) - : base(logger) - { - } +#if CODE_STYLE +using OptionsCollectionAlias = CODESTYLE_UTILITIES::Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.OptionsCollection; +#else +using OptionsCollectionAlias = OptionsCollection; +#endif +public abstract partial class AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest(ITestOutputHelper? logger) + : AbstractDiagnosticProviderBasedUserDiagnosticTest(logger) +{ protected override ParseOptions GetScriptOptions() => Options.Script; protected internal override string GetLanguage() => LanguageNames.CSharp; @@ -151,4 +159,29 @@ public interface IAsyncEnumerator : IAsyncDisposable internal OptionsCollection IgnoreAllParentheses => ParenthesesOptionsProvider.IgnoreAllParentheses; internal OptionsCollection RemoveAllUnnecessaryParentheses => ParenthesesOptionsProvider.RemoveAllUnnecessaryParentheses; internal OptionsCollection RequireAllParenthesesForClarity => ParenthesesOptionsProvider.RequireAllParenthesesForClarity; + + internal new Task TestInRegularAndScript1Async( + [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string initialMarkup, + [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string expectedMarkup, + int index = 0, + TestParameters? parameters = null) + { + return base.TestInRegularAndScript1Async(initialMarkup, expectedMarkup, index, parameters); + } + + internal new Task TestInRegularAndScriptAsync( + [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string initialMarkup, + [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string expectedMarkup, + int index = 0, + CodeActionPriority? priority = null, + CompilationOptions? compilationOptions = null, + OptionsCollectionAlias? options = null, + object? fixProviderData = null, + ParseOptions? parseOptions = null, + string? title = null, + TestHost testHost = TestHost.OutOfProcess) + { + return base.TestInRegularAndScriptAsync( + initialMarkup, expectedMarkup, index, priority, compilationOptions, options, fixProviderData, parseOptions, title, testHost); + } } diff --git a/src/EditorFeatures/CSharpTest/Diagnostics/FixAllProvider/BatchFixerTests.cs b/src/EditorFeatures/CSharpTest/Diagnostics/FixAllProvider/BatchFixerTests.cs index 5b2928ab5eb1d..413bd4b1f4caa 100644 --- a/src/EditorFeatures/CSharpTest/Diagnostics/FixAllProvider/BatchFixerTests.cs +++ b/src/EditorFeatures/CSharpTest/Diagnostics/FixAllProvider/BatchFixerTests.cs @@ -100,9 +100,8 @@ public override FixAllProvider GetFixAllProvider() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/320")] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInDocument_QualifyWithThis() - { - var input = """ + public Task TestFixAllInDocument_QualifyWithThis() + => TestInRegularAndScriptAsync(""" @@ -127,9 +126,7 @@ void Goo() - """; - - var expected = """ + """, """ @@ -154,10 +151,7 @@ void Goo() - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); #endregion } diff --git a/src/EditorFeatures/CSharpTest/Diagnostics/MockDiagnosticAnalyzerTests.cs b/src/EditorFeatures/CSharpTest/Diagnostics/MockDiagnosticAnalyzerTests.cs index 509b5e8828a21..d37d975ea987c 100644 --- a/src/EditorFeatures/CSharpTest/Diagnostics/MockDiagnosticAnalyzerTests.cs +++ b/src/EditorFeatures/CSharpTest/Diagnostics/MockDiagnosticAnalyzerTests.cs @@ -59,9 +59,6 @@ private async Task VerifyDiagnosticsAsync( } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/906919")] - public async Task Bug906919() - { - var source = "[|class C { }|]"; - await VerifyDiagnosticsAsync(source); - } + public Task Bug906919() + => VerifyDiagnosticsAsync("[|class C { }|]"); } diff --git a/src/EditorFeatures/CSharpTest/DocumentationComments/DocumentationCommentTests.cs b/src/EditorFeatures/CSharpTest/DocumentationComments/DocumentationCommentTests.cs index 73a6735475ae4..6becc2a439fee 100644 --- a/src/EditorFeatures/CSharpTest/DocumentationComments/DocumentationCommentTests.cs +++ b/src/EditorFeatures/CSharpTest/DocumentationComments/DocumentationCommentTests.cs @@ -20,153 +20,111 @@ public sealed class DocumentationCommentTests : AbstractDocumentationCommentTest [WpfFact] public void TypingCharacter_Class() { - var code = - """ + VerifyTypingCharacter(""" //$$ class C { } - """; - - var expected = - """ + """, """ /// /// $$ /// class C { } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void TypingCharacter_Record() { - var code = - """ + VerifyTypingCharacter(""" //$$ record R; - """; - - var expected = - """ + """, """ /// /// $$ /// record R; - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void TypingCharacter_RecordStruct() { - var code = - """ + VerifyTypingCharacter(""" //$$ record struct R; - """; - - var expected = - """ + """, """ /// /// $$ /// record struct R; - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void TypingCharacter_RecordWithPositionalParameters() { - var code = - """ + VerifyTypingCharacter(""" //$$ record R(string S, int I); - """; - - var expected = - """ + """, """ /// /// $$ /// /// /// record R(string S, int I); - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void TypingCharacter_ClassParameters() { - var code = - """ + VerifyTypingCharacter(""" //$$ class R(string S, int I); - """; - - var expected = - """ + """, """ /// /// $$ /// /// /// class R(string S, int I); - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void TypingCharacter_RecordStructWithPositionalParameters() { - var code = - """ + VerifyTypingCharacter(""" //$$ record struct R(string S, int I); - """; - - var expected = - """ + """, """ /// /// $$ /// /// /// record struct R(string S, int I); - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void TypingCharacter_StructParameters() { - var code = - """ + VerifyTypingCharacter(""" //$$ struct R(string S, int I); - """; - - var expected = - """ + """, """ /// /// $$ /// /// /// struct R(string S, int I); - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] @@ -218,23 +176,17 @@ class C [WpfFact] public void TypingCharacter_Class_AutoGenerateXmlDocCommentsOff() { - var code = - """ + VerifyTypingCharacter(""" //$$ class C { } - """; - - var expected = - """ + """, """ ///$$ class C { } - """; - - VerifyTypingCharacter(code, expected, globalOptions: new OptionsCollection(LanguageNames.CSharp) + """, globalOptions: new OptionsCollection(LanguageNames.CSharp) { { DocumentationCommentOptionsStorage.AutoXmlDocCommentGeneration, false } }); @@ -243,17 +195,13 @@ class C [WpfFact] public void TypingCharacter_Method() { - var code = - """ + VerifyTypingCharacter(""" class C { //$$ int M(int goo) { return 0; } } - """; - - var expected = - """ + """, """ class C { /// @@ -264,16 +212,13 @@ class C /// int M(int goo) { return 0; } } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/54245")] public void TypingCharacter_Method_WithExceptions() { - var code = - """ + VerifyTypingCharacter(""" class C { //$$ @@ -283,10 +228,7 @@ int M(int goo) return 0; } } - """; - - var expected = - """ + """, """ class C { /// @@ -302,16 +244,13 @@ int M(int goo) return 0; } } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/54245")] public void TypingCharacter_Constructor_WithExceptions() { - var code = - """ + VerifyTypingCharacter(""" class C { //$$ @@ -322,10 +261,7 @@ public C(int goo) throw null; } } - """; - - var expected = - """ + """, """ class C { /// @@ -341,16 +277,13 @@ public C(int goo) throw null; } } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/54245")] public void TypingCharacter_Constructor_WithExceptions_Caught() { - // This result is wrong, but we can't do better as long as we only check syntax. - var code = """ + VerifyTypingCharacter(""" using System; @@ -374,9 +307,7 @@ public C(int goo) throw null; } } - """; - - var expected = """ + """, """ using System; @@ -406,25 +337,19 @@ public C(int goo) throw null; } } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void TypingCharacter_Method_WithVerbatimParams() { - var code = - """ + VerifyTypingCharacter(""" class C { //$$ int M<@int>(int @goo) { return 0; } } - """; - - var expected = - """ + """, """ class C { /// @@ -435,25 +360,19 @@ class C /// int M<@int>(int @goo) { return 0; } } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void TypingCharacter_AutoProperty() { - var code = - """ + VerifyTypingCharacter(""" class C { //$$ int P { get; set; } } - """; - - var expected = - """ + """, """ class C { /// @@ -461,16 +380,13 @@ class C /// int P { get; set; } } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void TypingCharacter_Property() { - var code = - """ + VerifyTypingCharacter(""" class C { //$$ @@ -480,10 +396,7 @@ int P set { } } } - """; - - var expected = - """ + """, """ class C { /// @@ -495,16 +408,13 @@ int P set { } } } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void TypingCharacter_Indexer() { - var code = - """ + VerifyTypingCharacter(""" class C { //$$ @@ -514,10 +424,7 @@ int this[int index] set { } } } - """; - - var expected = - """ + """, """ class C { /// @@ -531,25 +438,19 @@ int this[int index] set { } } } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void TypingCharacter_VoidMethod1() { - var code = - """ + VerifyTypingCharacter(""" class C { //$$ void M(int goo) { } } - """; - - var expected = - """ + """, """ class C { /// @@ -559,25 +460,19 @@ class C /// void M(int goo) { } } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void TypingCharacter_VoidMethod_WithVerbatimParams() { - var code = - """ + VerifyTypingCharacter(""" class C { //$$ void M<@T>(int @int) { } } - """; - - var expected = - """ + """, """ class C { /// @@ -587,24 +482,19 @@ class C /// void M<@T>(int @int) { } } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538699")] public void TypingCharacter_VoidMethod2() { - var code = - """ + VerifyTypingCharacter(""" class C { //$$ void Method() { } } - """; - var expected = - """ + """, """ class C { /// @@ -612,38 +502,33 @@ class C /// void Method() { } } - """; - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void TypingCharacter_NotWhenDocCommentExists1() { - var code = """ + VerifyTypingCharacter(""" /// //$$ class C { } - """; - - var expected = """ + """, """ /// ///$$ class C { } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void TypingCharacter_NotWhenDocCommentExists2() { - var code = """ + VerifyTypingCharacter(""" /// @@ -651,9 +536,7 @@ public void TypingCharacter_NotWhenDocCommentExists2() class C { } - """; - - var expected = """ + """, """ /// @@ -661,15 +544,13 @@ class C class C { } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void TypingCharacter_NotWhenDocCommentExists3() { - var code = """ + VerifyTypingCharacter(""" class B { } /// @@ -677,9 +558,7 @@ class B { } /// class C { } - """; - - var expected = """ + """, """ class B { } /// @@ -687,66 +566,51 @@ class B { } /// class C { } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void TypingCharacter_NotWhenDocCommentExists4() { - var code = - """ + VerifyTypingCharacter(""" //$$ /// class C { } - """; - - var expected = - """ + """, """ ///$$ /// class C { } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void TypingCharacter_NotWhenDocCommentExists5() { - var code = - """ + VerifyTypingCharacter(""" class C { //$$ /// int M(int goo) { return 0; } } - """; - - var expected = - """ + """, """ class C { ///$$ /// int M(int goo) { return 0; } } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void TypingCharacter_NotInsideMethodBody1() { - var code = - """ + VerifyTypingCharacter(""" class C { void M(int goo) @@ -754,10 +618,7 @@ void M(int goo) //$$ } } - """; - - var expected = - """ + """, """ class C { void M(int goo) @@ -765,16 +626,13 @@ void M(int goo) ///$$ } } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void TypingCharacter_NotInsideMethodBody2() { - var code = - """ + VerifyTypingCharacter(""" class C { /// @@ -783,10 +641,7 @@ void M(int goo) //$$ } } - """; - - var expected = - """ + """, """ class C { /// @@ -795,78 +650,57 @@ void M(int goo) ///$$ } } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void TypingCharacter_NotAfterClassName() { - var code = - """ + VerifyTypingCharacter(""" class C//$$ { } - """; - - var expected = - """ + """, """ class C///$$ { } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void TypingCharacter_NotAfterOpenBrace() { - var code = - """ + VerifyTypingCharacter(""" class C {//$$ } - """; - - var expected = - """ + """, """ class C {///$$ } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void TypingCharacter_NotAfterCtorName() { - var code = - """ + VerifyTypingCharacter(""" class C { C() //$$ } - """; - - var expected = - """ + """, """ class C { C() ///$$ } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void TypingCharacter_NotInsideCtor() { - var code = - """ + VerifyTypingCharacter(""" class C { C() @@ -874,10 +708,7 @@ class C //$$ } } - """; - - var expected = - """ + """, """ class C { C() @@ -885,104 +716,82 @@ class C ///$$ } } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/59081")] public void TypingCharacter_NotInTopLevel() { - var code = """ + VerifyTypingCharacter(""" using System; //$$ Console.WriteLine(); - """; - - var expected = """ + """, """ using System; ///$$ Console.WriteLine(); - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/59081")] public void TypingCharacter_NotInNamespace() { - var code = """ + VerifyTypingCharacter(""" using System; //$$ namespace NS { } - """; - - var expected = """ + """, """ using System; ///$$ namespace NS { } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void PressingEnter_InsertComment_Class1() { - var code = - """ + VerifyPressingEnter(""" ///$$ class C { } - """; - - var expected = - """ + """, """ /// /// $$ /// class C { } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/4817")] public void PressingEnter_InsertComment_Class1_AutoGenerateXmlDocCommentsOff() { - var code = - """ + VerifyPressingEnter(""" ///$$ class C { } - """; - - var expected = - """ + """, """ /// $$ class C { } - """; - - VerifyPressingEnter(code, expected, globalOptions: new OptionsCollection(LanguageNames.CSharp) + """, globalOptions: new OptionsCollection(LanguageNames.CSharp) { { DocumentationCommentOptionsStorage.AutoXmlDocCommentGeneration, false } }); @@ -991,84 +800,62 @@ class C [WpfFact] public void PressingEnter_InsertComment_Class2() { - var code = - """ + VerifyPressingEnter(""" ///$$class C { } - """; - - var expected = - """ + """, """ /// /// $$ /// class C { } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact] public void PressingEnter_InsertComment_Class3() { - var code = - """ + VerifyPressingEnter(""" ///$$[Goo] class C { } - """; - - var expected = - """ + """, """ /// /// $$ /// [Goo] class C { } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact] public void PressingEnter_InsertComment_NotAfterWhitespace() { - var code = - """ + VerifyPressingEnter(""" /// $$class C { } - """; - - var expected = - """ + """, """ /// /// $$class C { } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact] public void PressingEnter_InsertComment_Method1() { - var code = - """ + VerifyPressingEnter(""" class C { ///$$ int M(int goo) { return 0; } } - """; - - var expected = - """ + """, """ class C { /// @@ -1079,24 +866,18 @@ class C /// int M(int goo) { return 0; } } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact] public void PressingEnter_InsertComment_Method2() { - var code = - """ + VerifyPressingEnter(""" class C { ///$$int M(int goo) { return 0; } } - """; - - var expected = - """ + """, """ class C { /// @@ -1107,16 +888,13 @@ class C /// int M(int goo) { return 0; } } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact] public void PressingEnter_NotInMethodBody1() { - var code = - """ + VerifyPressingEnter(""" class C { void Goo() @@ -1124,10 +902,7 @@ void Goo() ///$$ } } - """; - - var expected = - """ + """, """ class C { void Goo() @@ -1136,145 +911,106 @@ void Goo() $$ } } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537513")] public void PressingEnter_NotInterleavedInClassName1() { - var code = - """ + VerifyPressingEnter(""" class///$$ C { } - """; - - var expected = - """ + """, """ class/// $$ C { } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537513")] public void PressingEnter_NotInterleavedInClassName2() { - var code = - """ + VerifyPressingEnter(""" class ///$$C { } - """; - - var expected = - """ + """, """ class /// $$C { } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537513")] public void PressingEnter_NotInterleavedInClassName3() { - var code = - """ + VerifyPressingEnter(""" class /// $$C { } - """; - - var expected = - """ + """, """ class /// $$C { } - """; - - VerifyPressingEnter(code, expected); + """); } [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537514")] [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537532")] public void PressingEnter_NotAfterClassName1() { - var code = - """ + VerifyPressingEnter(""" class C ///$$ { } - """; - - var expected = - """ + """, """ class C /// $$ { } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537552")] public void PressingEnter_NotAfterClassName2() { - var code = - """ + VerifyPressingEnter(""" class C /** $$ { } - """; - - var expected = - """ + """, """ class C /** $$ { } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537535")] public void PressingEnter_NotAfterCtorName() { - var code = - """ + VerifyPressingEnter(""" class C { C() ///$$ } - """; - - var expected = - """ + """, """ class C { C() /// $$ } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537511")] public void PressingEnter_NotInsideCtor() { - var code = - """ + VerifyPressingEnter(""" class C { C() @@ -1282,10 +1018,7 @@ class C ///$$ } } - """; - - var expected = - """ + """, """ class C { C() @@ -1294,16 +1027,13 @@ class C $$ } } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537550")] public void PressingEnter_NotBeforeDocComment() { - var code = - """ + VerifyPressingEnter(""" class c1 { $$/// @@ -1315,10 +1045,7 @@ public async Task goo() var x = 1; } } - """; - - var expected = - """ + """, """ class c1 { @@ -1331,51 +1058,39 @@ public async Task goo() var x = 1; } } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact] public void PressingEnter_InsertSlashes1() { - var code = - """ + VerifyPressingEnter(""" ///$$ /// class C { } - """; - - var expected = - """ + """, """ /// /// $$ /// class C { } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact] public void PressingEnter_InsertSlashes2() { - var code = - """ + VerifyPressingEnter(""" /// /// $$ /// class C { } - """; - - var expected = - """ + """, """ /// /// /// $$ @@ -1383,26 +1098,20 @@ class C class C { } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact] public void PressingEnter_InsertSlashes3() { - var code = - """ + VerifyPressingEnter(""" /// /// $$ /// class C { } - """; - - var expected = - """ + """, """ /// /// /// $$ @@ -1410,49 +1119,37 @@ class C class C { } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact] public void PressingEnter_InsertSlashes4() { - var code = - """ + VerifyPressingEnter(""" /// $$ class C { } - """; - - var expected = - """ + """, """ /// /// $$ class C { } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact] public void PressingEnter_InsertSlashes5() { - var code = - """ + VerifyPressingEnter(""" /// /// $$ /// class C { } - """; - - var expected = - """ + """, """ /// /// /// $$ @@ -1460,93 +1157,71 @@ class C class C { } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact] public void PressingEnter_InsertSlashes6() { - var code = - """ + VerifyPressingEnter(""" /// $$ class C { } - """; - - var expected = - """ + """, """ /// /// $$ class C { } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact] public void PressingEnter_InsertSlashes7() { - var code = - """ + VerifyPressingEnter(""" /// $$ class C { - } - """; - - var expected = - """ + } + """, """ /// /// $$ class C { } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538702")] public void PressingEnter_InsertSlashes8() { - var code = - """ + VerifyPressingEnter(""" /// /// /// ///$$class C {} - """; - var expected = - """ + """, """ /// /// /// /// /// $$class C {} - """; - VerifyPressingEnter(code, expected); + """); } [WpfFact] public void PressingEnter_InsertSlashes9() { - var code = - """ + VerifyPressingEnter(""" class C { ///$$ /// int M(int goo) { return 0; } } - """; - - var expected = - """ + """, """ class C { /// @@ -1554,38 +1229,30 @@ class C /// int M(int goo) { return 0; } } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact] public void PressingEnter_InsertSlashes10() { - var code = - """ + VerifyPressingEnter(""" /// /// /// ///$$Go ahead and add some slashes - """; - var expected = - """ + """, """ /// /// /// /// /// $$Go ahead and add some slashes - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact] public void PressingEnter_InsertSlashes11() { - var code = - """ + VerifyPressingEnter(""" class C { /// @@ -1596,10 +1263,7 @@ void Goo(int i) { } } - """; - - var expected = - """ + """, """ class C { /// @@ -1611,34 +1275,26 @@ void Goo(int i) { } } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/4817")] public void PressingEnter_InsertSlashes12_AutoGenerateXmlDocCommentsOff() { - var code = - """ + VerifyPressingEnter(""" ///$$ /// class C { } - """; - - var expected = - """ + """, """ /// /// $$ /// class C { } - """; - - VerifyPressingEnter(code, expected, globalOptions: new OptionsCollection(LanguageNames.CSharp) + """, globalOptions: new OptionsCollection(LanguageNames.CSharp) { { DocumentationCommentOptionsStorage.AutoXmlDocCommentGeneration, false } }); @@ -1647,54 +1303,43 @@ class C [WpfFact] public void PressingEnter_DoNotInsertSlashes1() { - var code = - """ + VerifyPressingEnter(""" /// /// $$ class C { } - """; - - var expected = - """ + """, """ /// /// $$ class C { } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538701")] public void PressingEnter_DoNotInsertSlashes2() { - var code = - """ + VerifyPressingEnter(""" /// ///$$ class C{} - """; - var expected = - """ + """, """ /// /// $$ class C{} - """; - VerifyPressingEnter(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/25746")] public void PressingEnter_ExtraSlashesAfterExteriorTrivia() { - var code = - """ + VerifyPressingEnter(""" class C { C() @@ -1702,10 +1347,7 @@ class C //////$$ } } - """; - - var expected = - """ + """, """ class C { C() @@ -1714,25 +1356,20 @@ class C ///$$ } } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542426")] public void PressingEnter_PreserveParams() { - var code = - """ + VerifyPressingEnter(""" /// /// /// /// $$ static void Main(string[] args) { } - """; - var expected = - """ + """, """ /// /// /// @@ -1740,9 +1377,7 @@ static void Main(string[] args) /// $$ static void Main(string[] args) { } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/2091")] @@ -1946,17 +1581,14 @@ void M() [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/5486")] public void PressingEnter_Selection1() { - var code = - """ + VerifyPressingEnter(""" /// /// Hello [|World|]$$! /// class C { } - """; - var expected = - """ + """, """ /// /// Hello /// $$! @@ -1964,25 +1596,20 @@ class C class C { } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/5486")] public void PressingEnter_Selection2() { - var code = - """ + VerifyPressingEnter(""" /// /// Hello $$[|World|]! /// class C { } - """; - var expected = - """ + """, """ /// /// Hello /// $$! @@ -1990,9 +1617,7 @@ class C class C { } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact] @@ -2000,8 +1625,7 @@ class C [WorkItem("https://github.com/dotnet/roslyn/issues/49564")] public void PressingEnter_XmlDocCommentInStringLiteral() { - var code = - """ + VerifyPressingEnter(""" class C { C() @@ -2011,10 +1635,7 @@ class C void M() {}" } } - """; - - var expected = - """ + """, """ class C { C() @@ -2025,159 +1646,115 @@ class C void M() {}" } } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact] public void Command_Class() { - var code = - """ + VerifyInsertCommentCommand(""" class C {$$ } - """; - - var expected = - """ + """, """ /// /// $$ /// class C { } - """; - - VerifyInsertCommentCommand(code, expected); + """); } [WpfFact] public void Command_Record() { - var code = "record R$$;"; - - var expected = - """ + VerifyInsertCommentCommand("record R$$;", """ /// /// $$ /// record R; - """; - - VerifyInsertCommentCommand(code, expected); + """); } [WpfFact] public void Command_RecordStruct() { - var code = "record struct R$$;"; - - var expected = - """ + VerifyInsertCommentCommand("record struct R$$;", """ /// /// $$ /// record struct R; - """; - - VerifyInsertCommentCommand(code, expected); + """); } [WpfFact] public void Command_RecordWithPositionalParameters() { - var code = "record R$$(string S, int I);"; - - var expected = - """ + VerifyInsertCommentCommand("record R$$(string S, int I);", """ /// /// $$ /// /// /// record R(string S, int I); - """; - - VerifyInsertCommentCommand(code, expected); + """); } [WpfFact] public void Command_ClassParameters() { - var code = "class R$$(string S, int I);"; - - var expected = - """ + VerifyInsertCommentCommand("class R$$(string S, int I);", """ /// /// $$ /// /// /// class R(string S, int I); - """; - - VerifyInsertCommentCommand(code, expected); + """); } [WpfFact] public void Command_RecordStructWithPositionalParameters() { - var code = "record struct R$$(string S, int I);"; - - var expected = - """ + VerifyInsertCommentCommand("record struct R$$(string S, int I);", """ /// /// $$ /// /// /// record struct R(string S, int I); - """; - - VerifyInsertCommentCommand(code, expected); + """); } [WpfFact] public void Command_StructParameters() { - var code = "struct R$$(string S, int I);"; - - var expected = - """ + VerifyInsertCommentCommand("struct R$$(string S, int I);", """ /// /// $$ /// /// /// struct R(string S, int I); - """; - - VerifyInsertCommentCommand(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/4817")] public void Command_Class_AutoGenerateXmlDocCommentsOff() { - var code = - """ + VerifyInsertCommentCommand(""" class C {$$ } - """; - - var expected = - """ + """, """ /// /// $$ /// class C { } - """; - - VerifyInsertCommentCommand(code, expected, globalOptions: new OptionsCollection(LanguageNames.CSharp) + """, globalOptions: new OptionsCollection(LanguageNames.CSharp) { { DocumentationCommentOptionsStorage.AutoXmlDocCommentGeneration, false } }); @@ -2186,58 +1763,45 @@ class C [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538714")] public void Command_BeforeClass1() { - var code = - """ + VerifyInsertCommentCommand(""" $$ class C { } - """; - var expected = - """ + """, """ /// /// $$ /// class C { } - """; - - VerifyInsertCommentCommand(code, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538714")] public void Command_BeforeClass2() { - var code = - """ + VerifyInsertCommentCommand(""" class B { } $$ class C { } - """; - var expected = - """ + """, """ class B { } /// /// $$ /// class C { } - """; - - VerifyInsertCommentCommand(code, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538714")] public void Command_BeforeClass3() { - var code = - """ + VerifyInsertCommentCommand(""" class B { $$ class C { } } - """; - var expected = - """ + """, """ class B { @@ -2246,43 +1810,32 @@ class B /// class C { } } - """; - - VerifyInsertCommentCommand(code, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527604")] public void Command_Class_NotIfMultilineDocCommentExists() { - var code = - """ + VerifyInsertCommentCommand(""" /** */ class C { $$ } - """; - - var expected = - """ + """, """ /** */ class C { $$ } - """; - VerifyInsertCommentCommand(code, expected); + """); } [WpfFact] public void Command_Method() { - var code = - """ + VerifyInsertCommentCommand(""" class C { int M(int goo) { $$return 0; } } - """; - - var expected = - """ + """, """ class C { /// @@ -2293,96 +1846,69 @@ class C /// int M(int goo) { return 0; } } - """; - - VerifyInsertCommentCommand(code, expected); + """); } [WpfFact] public void Command_Class_NotIfCommentExists() { - var code = - """ + VerifyInsertCommentCommand(""" /// class C {$$ } - """; - - var expected = - """ + """, """ /// class C {$$ } - """; - - VerifyInsertCommentCommand(code, expected); + """); } [WpfFact] public void Command_Method_NotIfCommentExists() { - var code = - """ + VerifyInsertCommentCommand(""" class C { /// int M(int goo) { $$return 0; } } - """; - - var expected = - """ + """, """ class C { /// int M(int goo) { $$return 0; } } - """; - - VerifyInsertCommentCommand(code, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538482")] public void Command_FirstClassOnLine() { - var code = @"$$class C { } class D { }"; - - var expected = - """ + VerifyInsertCommentCommand(@"$$class C { } class D { }", """ /// /// $$ /// class C { } class D { } - """; - - VerifyInsertCommentCommand(code, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538482")] public void Command_NotOnSecondClassOnLine() { - var code = @"class C { } $$class D { }"; - - var expected = @"class C { } $$class D { }"; - - VerifyInsertCommentCommand(code, expected); + VerifyInsertCommentCommand(@"class C { } $$class D { }", @"class C { } $$class D { }"); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538482")] public void Command_FirstMethodOnLine() { - var code = - """ + VerifyInsertCommentCommand(""" class C { protected abstract void $$Goo(); protected abstract void Bar(); } - """; - - var expected = - """ + """, """ class C { /// @@ -2390,38 +1916,29 @@ class C /// protected abstract void Goo(); protected abstract void Bar(); } - """; - - VerifyInsertCommentCommand(code, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538482")] public void Command_NotOnSecondMethodOnLine() { - var code = - """ + VerifyInsertCommentCommand(""" class C { protected abstract void Goo(); protected abstract void $$Bar(); } - """; - - var expected = - """ + """, """ class C { protected abstract void Goo(); protected abstract void $$Bar(); } - """; - - VerifyInsertCommentCommand(code, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/917904")] public void TestUseTab() { - var code = - """ + VerifyTypingCharacter(""" using System; public class Class1 @@ -2431,10 +1948,7 @@ public Class1() { } } - """; - - var expected = - """ + """, """ using System; public class Class1 @@ -2446,9 +1960,7 @@ public Class1() { } } - """; - - VerifyTypingCharacter(code, expected, useTabs: true); + """, useTabs: true); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/2090")] @@ -2466,9 +1978,7 @@ void M() } } """; - - var expected = - """ + VerifyOpenLineAbove(code, """ class C { /// @@ -2479,9 +1989,7 @@ void M() { } } - """; - - VerifyOpenLineAbove(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/2090")] @@ -2733,78 +2241,59 @@ class C { } [WpfFact] public void TypingCharacter_Class_WithComment() { - var code = - """ + VerifyTypingCharacter(""" //$$ This is my class and it does great things. class C { } - """; - - var expected = - """ + """, """ /// /// $$This is my class and it does great things. /// class C { } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact] public void TypingCharacter_Class_WithComment_NoSpace() { - var code = - """ + VerifyTypingCharacter(""" //$$This is my class and it does great things. class C { } - """; - - var expected = - """ + """, """ /// /// $$This is my class and it does great things. /// class C { } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/75838")] public void TypingCharacter_ExistingText1() { - var code = - """ + VerifyTypingCharacter(""" /// foo$$ class C { } - """; - - var expected = - """ + """, """ /// foo/$$ class C { } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/75838")] public void TypingCharacter_ExistingText2() { - var code = - """ + VerifyTypingCharacter(""" namespace N { /// foo$$ @@ -2812,10 +2301,7 @@ class C { } } - """; - - var expected = - """ + """, """ namespace N { /// foo/$$ @@ -2823,39 +2309,30 @@ class C { } } - """; - - VerifyTypingCharacter(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/75838")] public void PressingEnter_ExistingText1() { - var code = - """ + VerifyPressingEnter(""" /// foo$$ class C { } - """; - - var expected = - """ + """, """ /// foo /// $$ class C { } - """; - - VerifyPressingEnter(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/75838")] public void PressingEnter_ExistingText2() { - var code = - """ + VerifyPressingEnter(""" namespace N { /// foo$$ @@ -2863,10 +2340,7 @@ class C { } } - """; - - var expected = - """ + """, """ namespace N { /// foo @@ -2875,9 +2349,7 @@ class C { } } - """; - - VerifyPressingEnter(code, expected); + """); } protected override char DocumentationCommentCharacter diff --git a/src/EditorFeatures/CSharpTest/DocumentationComments/XmlTagCompletionTests.cs b/src/EditorFeatures/CSharpTest/DocumentationComments/XmlTagCompletionTests.cs index 7f994c75e16e4..fa517fa3e8282 100644 --- a/src/EditorFeatures/CSharpTest/DocumentationComments/XmlTagCompletionTests.cs +++ b/src/EditorFeatures/CSharpTest/DocumentationComments/XmlTagCompletionTests.cs @@ -25,410 +25,318 @@ private protected override EditorTestWorkspace CreateTestWorkspace(string initia [WpfFact] public void SimpleTagCompletion() { - var text = """ + Verify(""" /// $$ class c { } - """; - - Verify(text, expected, '>'); + """, '>'); } [WpfFact] public void NestedTagCompletion() { - var text = """ + Verify(""" /// /// class c { } - """; - - var expected = """ + """, """ /// /// $$ /// class c { } - """; - - Verify(text, expected, '>'); + """, '>'); } [WpfFact] public void CompleteBeforeIncompleteTag() { - var text = """ + Verify(""" /// class c { } - """; - - var expected = """ + """, """ /// $$ /// class c { } - """; - - Verify(text, expected, '>'); + """, '>'); } [WpfFact] public void NotEmptyElement() { - var text = """ + Verify(""" /// <$$ class c { } - """; - - var expected = """ + """, """ /// <>$$ class c { } - """; - - Verify(text, expected, '>'); + """, '>'); } [WpfFact] public void NotAlreadyCompleteTag() { - var text = """ + Verify(""" /// class c { } - """; - - var expected = """ + """, """ /// $$ class c { } - """; - - Verify(text, expected, '>'); + """, '>'); } [WpfFact] public void NotAlreadyCompleteTag2() { - var text = """ + Verify(""" /// class c { } - """; - - var expected = """ + """, """ /// $$ /// /// class c { } - """; - - Verify(text, expected, '>'); + """, '>'); } [WpfFact] public void SimpleSlashCompletion() { - var text = """ + Verify(""" /// <$$ class c { } - """; - - var expected = """ + """, """ /// $$ class c { } - """; - - Verify(text, expected, '/'); + """, '/'); } [WpfFact] public void NestedSlashTagCompletion() { - var text = """ + Verify(""" /// /// <$$ /// class c { } - """; - - var expected = """ + """, """ /// /// $$ /// class c { } - """; - - Verify(text, expected, '/'); + """, '/'); } [WpfFact] public void SlashCompleteBeforeIncompleteTag() { - var text = """ + Verify(""" /// <$$ /// class c { } - """; - - var expected = """ + """, """ /// $$ /// class c { } - """; - - Verify(text, expected, '/'); + """, '/'); } [WpfFact] public void SlashNotEmptyElement() { - var text = """ + Verify(""" /// <><$$ class c { } - """; - - var expected = """ + """, """ /// <><$$goo> class c { } - """; - - var expected = """ + """, """ /// class c { } - """; - - Verify(text, expected, '/'); + """, '/'); } [WpfFact] public void SlashNotAlreadyCompleteTag2() { - var text = """ + Verify(""" /// /// /// <$$goo> class c { } - """; - - var expected = """ + """, """ /// /// /// class c { } - """; - - Verify(text, expected, '/'); + """, '/'); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638800")] public void NestedIdenticalTags() { - var text = """ + Verify(""" /// class c { } - """; - - var expected = """ + """, """ /// $$ class c { } - """; - - Verify(text, expected, '>'); + """, '>'); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638800")] public void MultipleNestedIdenticalTags() { - var text = """ + Verify(""" /// class c { } - """; - - var expected = """ + """, """ /// $$ class c { } - """; - - Verify(text, expected, '>'); + """, '>'); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638235")] public void SlashNotIfCloseTagFollows() { - var text = """ + Verify(""" /// /// <$$ /// class c { } - """; - - var expected = """ + """, """ /// /// class c { } - """; - - Verify(text, expected, '/'); + """, '/'); } [WpfFact] public void TestSimpleTagCompletion() { - var text = """ + Verify(""" /// $$ class C {} - """; - - Verify(text, expected, '>'); + """, '>'); } [WpfFact] public void TestNestedTagCompletion() { - var text = """ + Verify(""" /// /// class C {} - """; - - var expected = """ + """, """ /// /// $$ /// class C {} - """; - - Verify(text, expected, '>'); + """, '>'); } [WpfFact] public void TestCompleteBeforeIncompleteTag() { - var text = """ + Verify(""" /// class C {} - """; - - var expected = """ + """, """ /// $$ /// class C {} - """; - - Verify(text, expected, '>'); + """, '>'); } [WpfFact] public void TestNotEmptyElement() { - var text = """ + Verify(""" /// <$$ class C {} - """; - - var expected = """ + """, """ /// <>$$ class C {} - """; - - Verify(text, expected, '>'); + """, '>'); } [WpfFact] public void TestNotAlreadyCompleteTag() { - var text = """ + Verify(""" /// class C {} - """; - - var expected = """ + """, """ /// $$ class C {} - """; - - Verify(text, expected, '>'); + """, '>'); } [WpfFact] public void TestNotAlreadyCompleteTag2() { - var text = """ + Verify(""" /// class C {} - """; - - var expected = """ + """, """ /// $$ /// /// class C {} - """; - - Verify(text, expected, '>'); + """, '>'); } [WpfFact] public void TestNotOutsideDocComment() { - var text = """ + Verify(""" class C { private int z = $$ } - """; - - Verify(text, expected, '>'); + """, '>'); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638235")] public void TestNotCloseClosedTag() { - var text = """ + Verify(""" /// /// <$$ /// class C {} - """; - - var expected = """ + """, """ /// /// class C {} - """; - - Verify(text, expected, '/'); + """, '/'); } } diff --git a/src/EditorFeatures/CSharpTest/EditAndContinue/ActiveStatementTrackingServiceTests.cs b/src/EditorFeatures/CSharpTest/EditAndContinue/ActiveStatementTrackingServiceTests.cs index 7343e915b24dc..2b633ba855c44 100644 --- a/src/EditorFeatures/CSharpTest/EditAndContinue/ActiveStatementTrackingServiceTests.cs +++ b/src/EditorFeatures/CSharpTest/EditAndContinue/ActiveStatementTrackingServiceTests.cs @@ -7,8 +7,8 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Contracts.EditAndContinue; +using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; diff --git a/src/EditorFeatures/CSharpTest/EditorConfigSettings/Updater/SettingsUpdaterTests.cs b/src/EditorFeatures/CSharpTest/EditorConfigSettings/Updater/SettingsUpdaterTests.cs index 2f0bec6e84304..a76f5c219bfe1 100644 --- a/src/EditorFeatures/CSharpTest/EditorConfigSettings/Updater/SettingsUpdaterTests.cs +++ b/src/EditorFeatures/CSharpTest/EditorConfigSettings/Updater/SettingsUpdaterTests.cs @@ -79,22 +79,18 @@ private static async Task TestAsync(string initialEditorConfig, string updatedEd } [Fact] - public async Task TestAddNewWhitespaceOptionAsync() - { - await TestAsync( + public Task TestAddNewWhitespaceOptionAsync() + => TestAsync( string.Empty, "[*.cs]\r\ncsharp_new_line_before_else = true", (CSharpFormattingOptions2.NewLineForElse, true)); - } [Fact] - public async Task TestAddNewBoolCodeStyleOptionWithSeverityAsync() - { - await TestAsync( + public Task TestAddNewBoolCodeStyleOptionWithSeverityAsync() + => TestAsync( string.Empty, "[*.cs]\r\ncsharp_style_throw_expression = true:suggestion", (CSharpCodeStyleOptions.PreferThrowExpression, CodeStyleOption2.TrueWithSuggestionEnforcement)); - } [Fact] public async Task TestAddNewEnumCodeStyleOptionWithSeverityAsync() @@ -140,188 +136,176 @@ await TestAsync( } [Fact] - public async Task TestUpdateExistingWhitespaceOptionAsync() - { - await TestAsync( + public Task TestUpdateExistingWhitespaceOptionAsync() + => TestAsync( "[*.cs]\r\ncsharp_new_line_before_else = true", "[*.cs]\r\ncsharp_new_line_before_else = false", (CSharpFormattingOptions2.NewLineForElse, false)); - } [Fact] - public async Task TestAddNewWhitespaceOptionToExistingFileAsync() - { - var initialEditorConfig = @" -[*.{cs,vb}] + public Task TestAddNewWhitespaceOptionToExistingFileAsync() + => TestAsync( + """ -# CA1000: Do not declare static members on generic types -dotnet_diagnostic.CA1000.severity = false + [*.{cs,vb}] -"; + # CA1000: Do not declare static members on generic types + dotnet_diagnostic.CA1000.severity = false - var updatedEditorConfig = @" -[*.{cs,vb}] -# CA1000: Do not declare static members on generic types -dotnet_diagnostic.CA1000.severity = false + """, + """ + [*.{cs,vb}] -[*.cs] -csharp_new_line_before_else = true"; - await TestAsync( - initialEditorConfig, - updatedEditorConfig, - (CSharpFormattingOptions2.NewLineForElse, true)); - } + # CA1000: Do not declare static members on generic types + dotnet_diagnostic.CA1000.severity = false - [Fact] - public async Task TestAddNewWhitespaceOptionToWithNonMathcingGroupsAsync() - { - var initialEditorConfig = @" -root = true -# Xml files -[*.xml] -indent_size = 2"; - - var updatedEditorConfig = @" -root = true + [*.cs] + csharp_new_line_before_else = true + """, + (CSharpFormattingOptions2.NewLineForElse, true)); -# Xml files -[*.xml] -indent_size = 2 -[*.cs] -csharp_new_line_before_else = true"; - await TestAsync( - initialEditorConfig, - updatedEditorConfig, + [Fact] + public Task TestAddNewWhitespaceOptionToWithNonMathcingGroupsAsync() + => TestAsync( + """ + + root = true + + # Xml files + [*.xml] + indent_size = 2 + """, + """ + + root = true + + # Xml files + [*.xml] + indent_size = 2 + [*.cs] + csharp_new_line_before_else = true + """, (CSharpFormattingOptions2.NewLineForElse, true)); - } [Fact] - public async Task TestAddNewWhitespaceOptionWithStarGroup() - { - var initialEditorConfig = @" -root = true + public Task TestAddNewWhitespaceOptionWithStarGroup() + => TestAsync( + """ -# Xml files -[*.xml] -indent_size = 2 + root = true -# Dotnet code style settings: -[*.{cs,vb}] + # Xml files + [*.xml] + indent_size = 2 -# CSharp code style settings: -[*.cs]"; + # Dotnet code style settings: + [*.{cs,vb}] - var updatedEditorConfig = @" -root = true + # CSharp code style settings: + [*.cs] + """, + """ -# Xml files -[*.xml] -indent_size = 2 + root = true -# Dotnet code style settings: -[*.{cs,vb}] + # Xml files + [*.xml] + indent_size = 2 -# CSharp code style settings: -[*.cs] -csharp_new_line_before_else = true"; + # Dotnet code style settings: + [*.{cs,vb}] - await TestAsync( - initialEditorConfig, - updatedEditorConfig, + # CSharp code style settings: + [*.cs] + csharp_new_line_before_else = true + """, (CSharpFormattingOptions2.NewLineForElse, true)); - } [Fact] - public async Task TestAddMultimpleNewWhitespaceOptions() - { - await TestAsync( + public Task TestAddMultimpleNewWhitespaceOptions() + => TestAsync( string.Empty, "[*.cs]\r\ncsharp_new_line_before_else = true\r\ncsharp_new_line_before_catch = true\r\ncsharp_new_line_before_finally = true", (CSharpFormattingOptions2.NewLineForElse, true), (CSharpFormattingOptions2.NewLineForCatch, true), (CSharpFormattingOptions2.NewLineForFinally, true)); - } [Fact] - public async Task TestAddOptionThatAppliesToBothLanguages() - { - var initialEditorConfig = @" -root = true + public Task TestAddOptionThatAppliesToBothLanguages() + => TestAsync( + """ -# Xml files -[*.xml] -indent_size = 2 + root = true -# Dotnet code style settings: -[*.{cs,vb}] + # Xml files + [*.xml] + indent_size = 2 -# CSharp code style settings: -[*.cs]"; + # Dotnet code style settings: + [*.{cs,vb}] - var updatedEditorConfig = @" -root = true + # CSharp code style settings: + [*.cs] + """, + """ -# Xml files -[*.xml] -indent_size = 2 + root = true -# Dotnet code style settings: -[*.{cs,vb}] -dotnet_sort_system_directives_first = true + # Xml files + [*.xml] + indent_size = 2 -# CSharp code style settings: -[*.cs]"; + # Dotnet code style settings: + [*.{cs,vb}] + dotnet_sort_system_directives_first = true - await TestAsync( - initialEditorConfig, - updatedEditorConfig, + # CSharp code style settings: + [*.cs] + """, (GenerationOptions.PlaceSystemNamespaceFirst, true)); - } [Fact] - public async Task TestAddOptionWithRelativePathGroupingPresent() - { - var initialEditorConfig = @" -root = true + public Task TestAddOptionWithRelativePathGroupingPresent() + => TestAsync( + """ -# Xml files -[*.xml] -indent_size = 2 + root = true -# Dotnet code style settings: -[*.{cs,vb}] + # Xml files + [*.xml] + indent_size = 2 -# Test CSharp code style settings: -[*Test.cs] + # Dotnet code style settings: + [*.{cs,vb}] -# CSharp code style settings: -[*.cs]"; + # Test CSharp code style settings: + [*Test.cs] - var updatedEditorConfig = @" -root = true + # CSharp code style settings: + [*.cs] + """, + """ -# Xml files -[*.xml] -indent_size = 2 + root = true -# Dotnet code style settings: -[*.{cs,vb}] + # Xml files + [*.xml] + indent_size = 2 -# Test CSharp code style settings: -[*Test.cs] + # Dotnet code style settings: + [*.{cs,vb}] -# CSharp code style settings: -[*.cs] -csharp_new_line_before_else = true"; + # Test CSharp code style settings: + [*Test.cs] - await TestAsync( - initialEditorConfig, - updatedEditorConfig, + # CSharp code style settings: + [*.cs] + csharp_new_line_before_else = true + """, (CSharpFormattingOptions2.NewLineForElse, true)); - } [Fact] public async Task TestAnalyzerSettingsUpdaterService() @@ -435,157 +419,163 @@ public async Task TestNamingStyleSettingsUpdater() } private readonly string ExpectedInitialEditorConfig = -@$" -[*.{{cs,vb}}] -#### {CompilerExtensionsResources.Naming_styles} #### + $$""" + + [*.{cs,vb}] + #### {{CompilerExtensionsResources.Naming_styles}} #### + + # {{CompilerExtensionsResources.Naming_rules}} -# {CompilerExtensionsResources.Naming_rules} + dotnet_naming_rule.{{(CompilerExtensionsResources.Interface + "_should_be_" + CompilerExtensionsResources.Begins_with_I.Replace(' ', '_')).ToLowerInvariant()}}.severity = error + dotnet_naming_rule.{{(CompilerExtensionsResources.Interface + "_should_be_" + CompilerExtensionsResources.Begins_with_I.Replace(' ', '_')).ToLowerInvariant()}}.symbols = {{CompilerExtensionsResources.Interface.ToLowerInvariant()}} + dotnet_naming_rule.{{(CompilerExtensionsResources.Interface + "_should_be_" + CompilerExtensionsResources.Begins_with_I.Replace(' ', '_')).ToLowerInvariant()}}.style = {{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}} -dotnet_naming_rule.{(CompilerExtensionsResources.Interface + "_should_be_" + CompilerExtensionsResources.Begins_with_I.Replace(' ', '_')).ToLowerInvariant()}.severity = error -dotnet_naming_rule.{(CompilerExtensionsResources.Interface + "_should_be_" + CompilerExtensionsResources.Begins_with_I.Replace(' ', '_')).ToLowerInvariant()}.symbols = {CompilerExtensionsResources.Interface.ToLowerInvariant()} -dotnet_naming_rule.{(CompilerExtensionsResources.Interface + "_should_be_" + CompilerExtensionsResources.Begins_with_I.Replace(' ', '_')).ToLowerInvariant()}.style = {CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()} + dotnet_naming_rule.{{(CompilerExtensionsResources.Types + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}}.severity = suggestion + dotnet_naming_rule.{{(CompilerExtensionsResources.Types + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}}.symbols = {{CompilerExtensionsResources.Types.ToLowerInvariant()}} + dotnet_naming_rule.{{(CompilerExtensionsResources.Types + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}}.style = {{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}} -dotnet_naming_rule.{(CompilerExtensionsResources.Types + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}.severity = suggestion -dotnet_naming_rule.{(CompilerExtensionsResources.Types + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}.symbols = {CompilerExtensionsResources.Types.ToLowerInvariant()} -dotnet_naming_rule.{(CompilerExtensionsResources.Types + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}.style = {CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()} + dotnet_naming_rule.{{(CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_') + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}}.severity = suggestion + dotnet_naming_rule.{{(CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_') + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}}.symbols = {{CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_').ToLowerInvariant()}} + dotnet_naming_rule.{{(CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_') + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}}.style = {{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}} -dotnet_naming_rule.{(CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_') + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}.severity = suggestion -dotnet_naming_rule.{(CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_') + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}.symbols = {CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_').ToLowerInvariant()} -dotnet_naming_rule.{(CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_') + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}.style = {CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()} + # {{CompilerExtensionsResources.Symbol_specifications}} -# {CompilerExtensionsResources.Symbol_specifications} + dotnet_naming_symbols.{{CompilerExtensionsResources.Interface.ToLowerInvariant()}}.applicable_kinds = interface + dotnet_naming_symbols.{{CompilerExtensionsResources.Interface.ToLowerInvariant()}}.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected + dotnet_naming_symbols.{{CompilerExtensionsResources.Interface.ToLowerInvariant()}}.required_modifiers = -dotnet_naming_symbols.{CompilerExtensionsResources.Interface.ToLowerInvariant()}.applicable_kinds = interface -dotnet_naming_symbols.{CompilerExtensionsResources.Interface.ToLowerInvariant()}.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.{CompilerExtensionsResources.Interface.ToLowerInvariant()}.required_modifiers = + dotnet_naming_symbols.{{CompilerExtensionsResources.Types.ToLowerInvariant()}}.applicable_kinds = class, struct, interface, enum + dotnet_naming_symbols.{{CompilerExtensionsResources.Types.ToLowerInvariant()}}.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected + dotnet_naming_symbols.{{CompilerExtensionsResources.Types.ToLowerInvariant()}}.required_modifiers = -dotnet_naming_symbols.{CompilerExtensionsResources.Types.ToLowerInvariant()}.applicable_kinds = class, struct, interface, enum -dotnet_naming_symbols.{CompilerExtensionsResources.Types.ToLowerInvariant()}.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.{CompilerExtensionsResources.Types.ToLowerInvariant()}.required_modifiers = + dotnet_naming_symbols.{{CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_').ToLowerInvariant()}}.applicable_kinds = property, event, method + dotnet_naming_symbols.{{CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_').ToLowerInvariant()}}.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected + dotnet_naming_symbols.{{CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_').ToLowerInvariant()}}.required_modifiers = -dotnet_naming_symbols.{CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_').ToLowerInvariant()}.applicable_kinds = property, event, method -dotnet_naming_symbols.{CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_').ToLowerInvariant()}.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.{CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_').ToLowerInvariant()}.required_modifiers = + # {{CompilerExtensionsResources.Naming_styles}} -# {CompilerExtensionsResources.Naming_styles} + dotnet_naming_style.{{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}}.required_prefix = I + dotnet_naming_style.{{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}}.required_suffix = + dotnet_naming_style.{{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}}.word_separator = + dotnet_naming_style.{{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}}.capitalization = pascal_case -dotnet_naming_style.{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}.required_prefix = I -dotnet_naming_style.{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}.required_suffix = -dotnet_naming_style.{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}.word_separator = -dotnet_naming_style.{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}.capitalization = pascal_case + dotnet_naming_style.{{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}}.required_prefix = + dotnet_naming_style.{{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}}.required_suffix = + dotnet_naming_style.{{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}}.word_separator = + dotnet_naming_style.{{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}}.capitalization = pascal_case -dotnet_naming_style.{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}.required_prefix = -dotnet_naming_style.{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}.required_suffix = -dotnet_naming_style.{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}.word_separator = -dotnet_naming_style.{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}.capitalization = pascal_case + dotnet_naming_style.{{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}}.required_prefix = + dotnet_naming_style.{{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}}.required_suffix = + dotnet_naming_style.{{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}}.word_separator = + dotnet_naming_style.{{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}}.capitalization = pascal_case -dotnet_naming_style.{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}.required_prefix = -dotnet_naming_style.{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}.required_suffix = -dotnet_naming_style.{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}.word_separator = -dotnet_naming_style.{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}.capitalization = pascal_case -"; + """; private readonly string ExpectedEditorConfigAfterAllSeveritiesChanged = -@$" -[*.{{cs,vb}}] -#### {CompilerExtensionsResources.Naming_styles} #### + $$""" -# {CompilerExtensionsResources.Naming_rules} + [*.{cs,vb}] + #### {{CompilerExtensionsResources.Naming_styles}} #### -dotnet_naming_rule.{(CompilerExtensionsResources.Interface + "_should_be_" + CompilerExtensionsResources.Begins_with_I.Replace(' ', '_')).ToLowerInvariant()}.severity = error -dotnet_naming_rule.{(CompilerExtensionsResources.Interface + "_should_be_" + CompilerExtensionsResources.Begins_with_I.Replace(' ', '_')).ToLowerInvariant()}.symbols = {CompilerExtensionsResources.Interface.ToLowerInvariant()} -dotnet_naming_rule.{(CompilerExtensionsResources.Interface + "_should_be_" + CompilerExtensionsResources.Begins_with_I.Replace(' ', '_')).ToLowerInvariant()}.style = {CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()} + # {{CompilerExtensionsResources.Naming_rules}} -dotnet_naming_rule.{(CompilerExtensionsResources.Types + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}.severity = error -dotnet_naming_rule.{(CompilerExtensionsResources.Types + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}.symbols = {CompilerExtensionsResources.Types.ToLowerInvariant()} -dotnet_naming_rule.{(CompilerExtensionsResources.Types + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}.style = {CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()} + dotnet_naming_rule.{{(CompilerExtensionsResources.Interface + "_should_be_" + CompilerExtensionsResources.Begins_with_I.Replace(' ', '_')).ToLowerInvariant()}}.severity = error + dotnet_naming_rule.{{(CompilerExtensionsResources.Interface + "_should_be_" + CompilerExtensionsResources.Begins_with_I.Replace(' ', '_')).ToLowerInvariant()}}.symbols = {{CompilerExtensionsResources.Interface.ToLowerInvariant()}} + dotnet_naming_rule.{{(CompilerExtensionsResources.Interface + "_should_be_" + CompilerExtensionsResources.Begins_with_I.Replace(' ', '_')).ToLowerInvariant()}}.style = {{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}} -dotnet_naming_rule.{(CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_') + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}.severity = error -dotnet_naming_rule.{(CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_') + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}.symbols = {CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_').ToLowerInvariant()} -dotnet_naming_rule.{(CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_') + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}.style = {CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()} + dotnet_naming_rule.{{(CompilerExtensionsResources.Types + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}}.severity = error + dotnet_naming_rule.{{(CompilerExtensionsResources.Types + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}}.symbols = {{CompilerExtensionsResources.Types.ToLowerInvariant()}} + dotnet_naming_rule.{{(CompilerExtensionsResources.Types + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}}.style = {{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}} -# {CompilerExtensionsResources.Symbol_specifications} + dotnet_naming_rule.{{(CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_') + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}}.severity = error + dotnet_naming_rule.{{(CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_') + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}}.symbols = {{CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_').ToLowerInvariant()}} + dotnet_naming_rule.{{(CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_') + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}}.style = {{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}} -dotnet_naming_symbols.{CompilerExtensionsResources.Interface.ToLowerInvariant()}.applicable_kinds = interface -dotnet_naming_symbols.{CompilerExtensionsResources.Interface.ToLowerInvariant()}.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.{CompilerExtensionsResources.Interface.ToLowerInvariant()}.required_modifiers = + # {{CompilerExtensionsResources.Symbol_specifications}} -dotnet_naming_symbols.{CompilerExtensionsResources.Types.ToLowerInvariant()}.applicable_kinds = class, struct, interface, enum -dotnet_naming_symbols.{CompilerExtensionsResources.Types.ToLowerInvariant()}.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.{CompilerExtensionsResources.Types.ToLowerInvariant()}.required_modifiers = + dotnet_naming_symbols.{{CompilerExtensionsResources.Interface.ToLowerInvariant()}}.applicable_kinds = interface + dotnet_naming_symbols.{{CompilerExtensionsResources.Interface.ToLowerInvariant()}}.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected + dotnet_naming_symbols.{{CompilerExtensionsResources.Interface.ToLowerInvariant()}}.required_modifiers = -dotnet_naming_symbols.{CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_').ToLowerInvariant()}.applicable_kinds = property, event, method -dotnet_naming_symbols.{CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_').ToLowerInvariant()}.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.{CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_').ToLowerInvariant()}.required_modifiers = + dotnet_naming_symbols.{{CompilerExtensionsResources.Types.ToLowerInvariant()}}.applicable_kinds = class, struct, interface, enum + dotnet_naming_symbols.{{CompilerExtensionsResources.Types.ToLowerInvariant()}}.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected + dotnet_naming_symbols.{{CompilerExtensionsResources.Types.ToLowerInvariant()}}.required_modifiers = -# {CompilerExtensionsResources.Naming_styles} + dotnet_naming_symbols.{{CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_').ToLowerInvariant()}}.applicable_kinds = property, event, method + dotnet_naming_symbols.{{CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_').ToLowerInvariant()}}.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected + dotnet_naming_symbols.{{CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_').ToLowerInvariant()}}.required_modifiers = -dotnet_naming_style.{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}.required_prefix = I -dotnet_naming_style.{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}.required_suffix = -dotnet_naming_style.{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}.word_separator = -dotnet_naming_style.{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}.capitalization = pascal_case + # {{CompilerExtensionsResources.Naming_styles}} -dotnet_naming_style.{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}.required_prefix = -dotnet_naming_style.{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}.required_suffix = -dotnet_naming_style.{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}.word_separator = -dotnet_naming_style.{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}.capitalization = pascal_case + dotnet_naming_style.{{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}}.required_prefix = I + dotnet_naming_style.{{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}}.required_suffix = + dotnet_naming_style.{{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}}.word_separator = + dotnet_naming_style.{{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}}.capitalization = pascal_case -dotnet_naming_style.{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}.required_prefix = -dotnet_naming_style.{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}.required_suffix = -dotnet_naming_style.{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}.word_separator = -dotnet_naming_style.{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}.capitalization = pascal_case -"; + dotnet_naming_style.{{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}}.required_prefix = + dotnet_naming_style.{{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}}.required_suffix = + dotnet_naming_style.{{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}}.word_separator = + dotnet_naming_style.{{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}}.capitalization = pascal_case + + dotnet_naming_style.{{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}}.required_prefix = + dotnet_naming_style.{{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}}.required_suffix = + dotnet_naming_style.{{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}}.word_separator = + dotnet_naming_style.{{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}}.capitalization = pascal_case + + """; private readonly string ExpectedEditorConfigAfterSymbolSpecChange = -@$" -[*.{{cs,vb}}] -#### {CompilerExtensionsResources.Naming_styles} #### + $$""" + + [*.{cs,vb}] + #### {{CompilerExtensionsResources.Naming_styles}} #### + + # {{CompilerExtensionsResources.Naming_rules}} -# {CompilerExtensionsResources.Naming_rules} + dotnet_naming_rule.{{(CompilerExtensionsResources.Interface + "_should_be_" + CompilerExtensionsResources.Begins_with_I.Replace(' ', '_')).ToLowerInvariant()}}.severity = error + dotnet_naming_rule.{{(CompilerExtensionsResources.Interface + "_should_be_" + CompilerExtensionsResources.Begins_with_I.Replace(' ', '_')).ToLowerInvariant()}}.symbols = {{CompilerExtensionsResources.Interface.ToLowerInvariant()}} + dotnet_naming_rule.{{(CompilerExtensionsResources.Interface + "_should_be_" + CompilerExtensionsResources.Begins_with_I.Replace(' ', '_')).ToLowerInvariant()}}.style = {{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}} -dotnet_naming_rule.{(CompilerExtensionsResources.Interface + "_should_be_" + CompilerExtensionsResources.Begins_with_I.Replace(' ', '_')).ToLowerInvariant()}.severity = error -dotnet_naming_rule.{(CompilerExtensionsResources.Interface + "_should_be_" + CompilerExtensionsResources.Begins_with_I.Replace(' ', '_')).ToLowerInvariant()}.symbols = {CompilerExtensionsResources.Interface.ToLowerInvariant()} -dotnet_naming_rule.{(CompilerExtensionsResources.Interface + "_should_be_" + CompilerExtensionsResources.Begins_with_I.Replace(' ', '_')).ToLowerInvariant()}.style = {CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()} + dotnet_naming_rule.{{(CompilerExtensionsResources.Types + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}}.severity = error + dotnet_naming_rule.{{(CompilerExtensionsResources.Types + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}}.symbols = {{CompilerExtensionsResources.Types.ToLowerInvariant()}} + dotnet_naming_rule.{{(CompilerExtensionsResources.Types + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}}.style = {{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}} -dotnet_naming_rule.{(CompilerExtensionsResources.Types + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}.severity = error -dotnet_naming_rule.{(CompilerExtensionsResources.Types + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}.symbols = {CompilerExtensionsResources.Types.ToLowerInvariant()} -dotnet_naming_rule.{(CompilerExtensionsResources.Types + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}.style = {CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()} + dotnet_naming_rule.{{(CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_') + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}}.severity = error + dotnet_naming_rule.{{(CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_') + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}}.symbols = {{CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_').ToLowerInvariant()}} + dotnet_naming_rule.{{(CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_') + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}}.style = {{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}} -dotnet_naming_rule.{(CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_') + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}.severity = error -dotnet_naming_rule.{(CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_') + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}.symbols = {CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_').ToLowerInvariant()} -dotnet_naming_rule.{(CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_') + "_should_be_" + CompilerExtensionsResources.Pascal_Case.Replace(' ', '_')).ToLowerInvariant()}.style = {CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()} + # {{CompilerExtensionsResources.Symbol_specifications}} -# {CompilerExtensionsResources.Symbol_specifications} + dotnet_naming_symbols.{{CompilerExtensionsResources.Interface.ToLowerInvariant()}}.applicable_kinds = interface + dotnet_naming_symbols.{{CompilerExtensionsResources.Interface.ToLowerInvariant()}}.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected + dotnet_naming_symbols.{{CompilerExtensionsResources.Interface.ToLowerInvariant()}}.required_modifiers = -dotnet_naming_symbols.{CompilerExtensionsResources.Interface.ToLowerInvariant()}.applicable_kinds = interface -dotnet_naming_symbols.{CompilerExtensionsResources.Interface.ToLowerInvariant()}.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.{CompilerExtensionsResources.Interface.ToLowerInvariant()}.required_modifiers = + dotnet_naming_symbols.{{CompilerExtensionsResources.Types.ToLowerInvariant()}}.applicable_kinds = class, struct, interface, enum + dotnet_naming_symbols.{{CompilerExtensionsResources.Types.ToLowerInvariant()}}.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected + dotnet_naming_symbols.{{CompilerExtensionsResources.Types.ToLowerInvariant()}}.required_modifiers = -dotnet_naming_symbols.{CompilerExtensionsResources.Types.ToLowerInvariant()}.applicable_kinds = class, struct, interface, enum -dotnet_naming_symbols.{CompilerExtensionsResources.Types.ToLowerInvariant()}.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.{CompilerExtensionsResources.Types.ToLowerInvariant()}.required_modifiers = + dotnet_naming_symbols.{{CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_').ToLowerInvariant()}}.applicable_kinds = property, event, method + dotnet_naming_symbols.{{CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_').ToLowerInvariant()}}.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected + dotnet_naming_symbols.{{CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_').ToLowerInvariant()}}.required_modifiers = -dotnet_naming_symbols.{CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_').ToLowerInvariant()}.applicable_kinds = property, event, method -dotnet_naming_symbols.{CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_').ToLowerInvariant()}.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.{CompilerExtensionsResources.Non_Field_Members.Replace(' ', '_').Replace('-', '_').ToLowerInvariant()}.required_modifiers = + # {{CompilerExtensionsResources.Naming_styles}} -# {CompilerExtensionsResources.Naming_styles} + dotnet_naming_style.{{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}}.required_prefix = I + dotnet_naming_style.{{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}}.required_suffix = + dotnet_naming_style.{{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}}.word_separator = + dotnet_naming_style.{{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}}.capitalization = pascal_case -dotnet_naming_style.{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}.required_prefix = I -dotnet_naming_style.{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}.required_suffix = -dotnet_naming_style.{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}.word_separator = -dotnet_naming_style.{CompilerExtensionsResources.Begins_with_I.Replace(' ', '_').ToLowerInvariant()}.capitalization = pascal_case + dotnet_naming_style.{{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}}.required_prefix = + dotnet_naming_style.{{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}}.required_suffix = + dotnet_naming_style.{{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}}.word_separator = + dotnet_naming_style.{{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}}.capitalization = pascal_case -dotnet_naming_style.{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}.required_prefix = -dotnet_naming_style.{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}.required_suffix = -dotnet_naming_style.{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}.word_separator = -dotnet_naming_style.{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}.capitalization = pascal_case + dotnet_naming_style.{{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}}.required_prefix = + dotnet_naming_style.{{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}}.required_suffix = + dotnet_naming_style.{{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}}.word_separator = + dotnet_naming_style.{{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}}.capitalization = pascal_case -dotnet_naming_style.{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}.required_prefix = -dotnet_naming_style.{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}.required_suffix = -dotnet_naming_style.{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}.word_separator = -dotnet_naming_style.{CompilerExtensionsResources.Pascal_Case.Replace(' ', '_').ToLowerInvariant()}.capitalization = pascal_case -"; + """; private sealed class TestViewModel : ISettingsEditorViewModel { diff --git a/src/EditorFeatures/CSharpTest/EncapsulateField/EncapsulateFieldCommandHandlerTests.cs b/src/EditorFeatures/CSharpTest/EncapsulateField/EncapsulateFieldCommandHandlerTests.cs index c479e98c05e96..05ad5d4945d0d 100644 --- a/src/EditorFeatures/CSharpTest/EncapsulateField/EncapsulateFieldCommandHandlerTests.cs +++ b/src/EditorFeatures/CSharpTest/EncapsulateField/EncapsulateFieldCommandHandlerTests.cs @@ -34,7 +34,8 @@ private void goo() } } """; - var expected = """ + using var state = EncapsulateFieldTestState.Create(text); + await state.AssertEncapsulateAsAsync(""" class C { private int field; @@ -57,10 +58,7 @@ private void goo() Field = 3; } } - """; - - using var state = EncapsulateFieldTestState.Create(text); - await state.AssertEncapsulateAsAsync(expected); + """); } [WpfFact, Trait(Traits.Feature, Traits.Features.EncapsulateField)] @@ -77,7 +75,8 @@ private void goo() } } """; - var expected = """ + using var state = EncapsulateFieldTestState.Create(text); + await state.AssertEncapsulateAsAsync(""" class C { private int field; @@ -100,10 +99,7 @@ private void goo() Field = 3; } } - """; - - using var state = EncapsulateFieldTestState.Create(text); - await state.AssertEncapsulateAsAsync(expected); + """); } [WpfFact, Trait(Traits.Feature, Traits.Features.EncapsulateField)] @@ -142,7 +138,8 @@ static void Main(string[] args) } } """; - var expected = """ + using var state = EncapsulateFieldTestState.Create(text); + await state.AssertEncapsulateAsAsync(""" class Program { static int A = 1; @@ -180,10 +177,7 @@ static void Main(string[] args) System.Console.WriteLine(B1); } } - """; - - using var state = EncapsulateFieldTestState.Create(text); - await state.AssertEncapsulateAsAsync(expected); + """); } [WpfFact] diff --git a/src/EditorFeatures/CSharpTest/EventHookup/EventHookupCommandHandlerTests.cs b/src/EditorFeatures/CSharpTest/EventHookup/EventHookupCommandHandlerTests.cs index a4be459ff08fb..57fd3ab0d8b23 100644 --- a/src/EditorFeatures/CSharpTest/EventHookup/EventHookupCommandHandlerTests.cs +++ b/src/EditorFeatures/CSharpTest/EventHookup/EventHookupCommandHandlerTests.cs @@ -24,15 +24,16 @@ public sealed class EventHookupCommandHandlerTests [WpfFact] public async Task HandlerName_EventInThisClass() { - var markup = @" -class C -{ - event System.Action MyEvent; - void M() - { - MyEvent +$$ - } -}"; + var markup = """ + class C + { + event System.Action MyEvent; + void M() + { + MyEvent +$$ + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); await testState.WaitForAsynchronousOperationsAsync(); @@ -42,15 +43,16 @@ void M() [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/20999")] public async Task HandlerName_EventInThisClass_CamelCaseRule() { - var markup = @" -class C -{ - event System.Action MyEvent; - void M() - { - MyEvent +$$ - } -}"; + var markup = """ + class C + { + event System.Action MyEvent; + void M() + { + MyEvent +$$ + } + } + """; using var testState = new EventHookupTestState( EventHookupTestState.GetWorkspaceXml(markup), _namingOptions.MethodNamesAreCamelCase); @@ -62,21 +64,21 @@ void M() [WpfFact] public async Task HandlerName_EventOnLocal() { - var markup = @" -class C -{ - public event System.Action MyEvent; -} - -class D -{ - void M() - { - C local = new C(); - local.MyEvent +$$ - } -} -"; + var markup = """ + class C + { + public event System.Action MyEvent; + } + + class D + { + void M() + { + C local = new C(); + local.MyEvent +$$ + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); await testState.WaitForAsynchronousOperationsAsync(); @@ -86,26 +88,26 @@ void M() [WpfFact] public async Task HandlerName_EventOnFieldOfObject() { - var markup = @" -class C -{ - public event System.Action MyEvent; -} - -class D -{ - public C cfield = new C(); -} - -class E -{ - void Goo() - { - D local = new D(); - local.cfield.MyEvent +$$ - } -} -"; + var markup = """ + class C + { + public event System.Action MyEvent; + } + + class D + { + public C cfield = new C(); + } + + class E + { + void Goo() + { + D local = new D(); + local.cfield.MyEvent +$$ + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); await testState.WaitForAsynchronousOperationsAsync(); @@ -115,15 +117,16 @@ void Goo() [WpfFact] public async Task NoHookupOnIntegerPlusEquals() { - var markup = @" -class C -{ - void Goo() - { - int x = 7; - x +$$ - } -}"; + var markup = """ + class C + { + void Goo() + { + int x = 7; + x +$$ + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); await testState.WaitForAsynchronousOperationsAsync(); @@ -132,37 +135,36 @@ void Goo() // Make sure that sending the tab works correctly. Note the 4 spaces after the += testState.SendTab(); await testState.WaitForAsynchronousOperationsAsync(); - var expectedCode = @" -class C -{ - void Goo() - { - int x = 7; - x += - } -}"; - - testState.AssertCodeIs(expectedCode); + testState.AssertCodeIs(""" + class C + { + void Goo() + { + int x = 7; + x += + } + } + """); } [WpfFact] public async Task HandlerName_DefaultHandlerNameAlreadyExistsWithSameNonStaticState() { - var markup = @" -class C -{ - public event System.Action MyEvent; - - void Goo() - { - MyEvent +$$ - } - - private void C_MyEvent() - { - } -} -"; + var markup = """ + class C + { + public event System.Action MyEvent; + + void Goo() + { + MyEvent +$$ + } + + private void C_MyEvent() + { + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); await testState.WaitForAsynchronousOperationsAsync(); @@ -172,21 +174,21 @@ private void C_MyEvent() [WpfFact] public async Task HandlerName_DefaultHandlerNameAlreadyExistsWithDifferentStaticState() { - var markup = @" -class C -{ - public event System.Action MyEvent; - - void Goo() - { - MyEvent +$$ - } - - private static void C_MyEvent() - { - } -} -"; + var markup = """ + class C + { + public event System.Action MyEvent; + + void Goo() + { + MyEvent +$$ + } + + private static void C_MyEvent() + { + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); await testState.WaitForAsynchronousOperationsAsync(); @@ -196,17 +198,18 @@ private static void C_MyEvent() [WpfFact] public async Task HandlerName_DefaultHandlerNameAlreadyExistsAsField() { - var markup = @" -class C -{ - event System.Action MyEvent; - int C_MyEvent; - - void M(string[] args) - { - MyEvent +$$ - } -}"; + var markup = """ + class C + { + event System.Action MyEvent; + int C_MyEvent; + + void M(string[] args) + { + MyEvent +$$ + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); await testState.WaitForAsynchronousOperationsAsync(); @@ -216,17 +219,17 @@ void M(string[] args) [WpfFact] public async Task HookupInLambdaInLocalDeclaration() { - var markup = @" -class C -{ - public event System.Action MyEvent; - - void Goo() - { - Action a = () => MyEvent +$$ - } -} -"; + var markup = """ + class C + { + public event System.Action MyEvent; + + void Goo() + { + Action a = () => MyEvent +$$ + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); await testState.WaitForAsynchronousOperationsAsync(); @@ -236,15 +239,16 @@ void Goo() [WpfFact] public async Task TypingSpacesDoesNotDismiss() { - var markup = @" -class C -{ - event System.Action MyEvent; - void M() - { - MyEvent +$$ - } -}"; + var markup = """ + class C + { + event System.Action MyEvent; + void M() + { + MyEvent +$$ + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); await testState.WaitForAsynchronousOperationsAsync(); @@ -258,15 +262,16 @@ void M() [WpfFact] public async Task TypingLettersDismisses() { - var markup = @" -class C -{ - event System.Action MyEvent; - void M() - { - MyEvent +$$ - } -}"; + var markup = """ + class C + { + event System.Action MyEvent; + void M() + { + MyEvent +$$ + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); await testState.WaitForAsynchronousOperationsAsync(); @@ -280,15 +285,16 @@ void M() [WpfFact] public async Task TypingEqualsInSessionDismisses() { - var markup = @" -class C -{ - event System.Action MyEvent; - void M() - { - MyEvent +$$ - } -}"; + var markup = """ + class C + { + event System.Action MyEvent; + void M() + { + MyEvent +$$ + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); await testState.WaitForAsynchronousOperationsAsync(); @@ -302,15 +308,16 @@ void M() [WpfFact] public async Task CancelViaLeftKey() { - var markup = @" -class C -{ - event System.Action MyEvent; - void M() - { - MyEvent +$$ - } -}"; + var markup = """ + class C + { + event System.Action MyEvent; + void M() + { + MyEvent +$$ + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); await testState.WaitForAsynchronousOperationsAsync(); @@ -332,15 +339,16 @@ void M() [WpfFact] public async Task CancelViaBackspace() { - var markup = @" -class C -{ - event System.Action MyEvent; - void M() - { - MyEvent +$$ - } -}"; + var markup = """ + class C + { + event System.Action MyEvent; + void M() + { + MyEvent +$$ + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); @@ -359,249 +367,250 @@ void M() [WpfFact] public async Task EventHookupBeforeEventHookup() { - var markup = @" -class C -{ - event System.Action MyEvent; - void M() - { - MyEvent +$$ - MyEvent += C_MyEvent; - } - - private void C_MyEvent() - { - throw new System.NotImplementedException(); - } -}"; + var markup = """ + class C + { + event System.Action MyEvent; + void M() + { + MyEvent +$$ + MyEvent += C_MyEvent; + } + + private void C_MyEvent() + { + throw new System.NotImplementedException(); + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); testState.SendTab(); await testState.WaitForAsynchronousOperationsAsync(); - - var expectedCode = @" -class C -{ - event System.Action MyEvent; - void M() - { - MyEvent += C_MyEvent1; - MyEvent += C_MyEvent; - } - - private void C_MyEvent1() - { - throw new System.NotImplementedException(); - } - - private void C_MyEvent() - { - throw new System.NotImplementedException(); - } -}"; - testState.AssertCodeIs(expectedCode); + testState.AssertCodeIs(""" + class C + { + event System.Action MyEvent; + void M() + { + MyEvent += C_MyEvent1; + MyEvent += C_MyEvent; + } + + private void C_MyEvent1() + { + throw new System.NotImplementedException(); + } + + private void C_MyEvent() + { + throw new System.NotImplementedException(); + } + } + """); } [WpfFact] public async Task EventHookupBeforeComment() { - var markup = @" -class C -{ - event System.Action MyEvent; - void M() - { - MyEvent +$$ // Awesome Comment! - MyEvent += C_MyEvent; - } - - private void C_MyEvent() - { - throw new System.NotImplementedException(); - } -}"; + var markup = """ + class C + { + event System.Action MyEvent; + void M() + { + MyEvent +$$ // Awesome Comment! + MyEvent += C_MyEvent; + } + + private void C_MyEvent() + { + throw new System.NotImplementedException(); + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); testState.SendTab(); await testState.WaitForAsynchronousOperationsAsync(); - - var expectedCode = @" -class C -{ - event System.Action MyEvent; - void M() - { - MyEvent += C_MyEvent1; // Awesome Comment! - MyEvent += C_MyEvent; - } - - private void C_MyEvent1() - { - throw new System.NotImplementedException(); - } - - private void C_MyEvent() - { - throw new System.NotImplementedException(); - } -}"; - testState.AssertCodeIs(expectedCode); + testState.AssertCodeIs(""" + class C + { + event System.Action MyEvent; + void M() + { + MyEvent += C_MyEvent1; // Awesome Comment! + MyEvent += C_MyEvent; + } + + private void C_MyEvent1() + { + throw new System.NotImplementedException(); + } + + private void C_MyEvent() + { + throw new System.NotImplementedException(); + } + } + """); } [WpfFact] public async Task EventHookupInArgument() { - var markup = @" -class C -{ - event System.Action MyEvent; - void M() - { - Goo(() => MyEvent +$$) - } - - private void Goo(Action a) - { - } -}"; + var markup = """ + class C + { + event System.Action MyEvent; + void M() + { + Goo(() => MyEvent +$$) + } + + private void Goo(Action a) + { + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); testState.SendTab(); await testState.WaitForAsynchronousOperationsAsync(); - - var expectedCode = @" -class C -{ - event System.Action MyEvent; - void M() - { - Goo(() => MyEvent += C_MyEvent;) - } - - private void C_MyEvent() - { - throw new System.NotImplementedException(); - } - - private void Goo(Action a) - { - } -}"; - testState.AssertCodeIs(expectedCode); + testState.AssertCodeIs(""" + class C + { + event System.Action MyEvent; + void M() + { + Goo(() => MyEvent += C_MyEvent;) + } + + private void C_MyEvent() + { + throw new System.NotImplementedException(); + } + + private void Goo(Action a) + { + } + } + """); } [WpfFact] public async Task HookupInFieldDeclarationSingleLineLambda() { - var markup = @" -class C -{ - static event System.Action MyEvent; - System.Action A = () => MyEvent +$$ -}"; + var markup = """ + class C + { + static event System.Action MyEvent; + System.Action A = () => MyEvent +$$ + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); testState.SendTab(); await testState.WaitForAsynchronousOperationsAsync(); + testState.AssertCodeIs(""" + class C + { + static event System.Action MyEvent; + System.Action A = () => MyEvent += C_MyEvent; - var expectedCode = @" -class C -{ - static event System.Action MyEvent; - System.Action A = () => MyEvent += C_MyEvent; - - private static void C_MyEvent() - { - throw new System.NotImplementedException(); - } -}"; - testState.AssertCodeIs(expectedCode); + private static void C_MyEvent() + { + throw new System.NotImplementedException(); + } + } + """); } [WpfFact] public async Task HookupInFieldDeclarationMultiLineLambda() { - var markup = @" -class C -{ - static event System.Action MyEvent; - System.Action A = () => - { - MyEvent +$$ - }; -}"; + var markup = """ + class C + { + static event System.Action MyEvent; + System.Action A = () => + { + MyEvent +$$ + }; + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); testState.SendTab(); await testState.WaitForAsynchronousOperationsAsync(); - - var expectedCode = @" -class C -{ - static event System.Action MyEvent; - System.Action A = () => - { - MyEvent += C_MyEvent; - }; - - private static void C_MyEvent() - { - throw new System.NotImplementedException(); - } -}"; - testState.AssertCodeIs(expectedCode); + testState.AssertCodeIs(""" + class C + { + static event System.Action MyEvent; + System.Action A = () => + { + MyEvent += C_MyEvent; + }; + + private static void C_MyEvent() + { + throw new System.NotImplementedException(); + } + } + """); } [WpfFact] public async Task EventHookupInUnformattedPosition1() { - var markup = @" -class C -{ - event System.Action MyEvent; - void M() - {MyEvent +$$ - } -}"; + var markup = """ + class C + { + event System.Action MyEvent; + void M() + {MyEvent +$$ + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); testState.SendTab(); await testState.WaitForAsynchronousOperationsAsync(); - - var expectedCode = @" -class C -{ - event System.Action MyEvent; - void M() - { - MyEvent += C_MyEvent; - } - - private void C_MyEvent() - { - throw new System.NotImplementedException(); - } -}"; - testState.AssertCodeIs(expectedCode); + testState.AssertCodeIs(""" + class C + { + event System.Action MyEvent; + void M() + { + MyEvent += C_MyEvent; + } + + private void C_MyEvent() + { + throw new System.NotImplementedException(); + } + } + """); } [WpfFact] public async Task EventHookupInUnformattedPosition2() { - var markup = @" -class C -{ - event System.Action MyEvent; - void M() - {MyEvent +$$ - MyEvent += C_MyEvent; - } - - private void C_MyEvent() - { - throw new System.NotImplementedException(); - } -}"; + var markup = """ + class C + { + event System.Action MyEvent; + void M() + {MyEvent +$$ + MyEvent += C_MyEvent; + } + + private void C_MyEvent() + { + throw new System.NotImplementedException(); + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); @@ -612,42 +621,42 @@ private void C_MyEvent() testState.SendTab(); await testState.WaitForAsynchronousOperationsAsync(); - - var expectedCode = @" -class C -{ - event System.Action MyEvent; - void M() - { - MyEvent += C_MyEvent1; - MyEvent += C_MyEvent; - } - - private void C_MyEvent1() - { - throw new System.NotImplementedException(); - } - - private void C_MyEvent() - { - throw new System.NotImplementedException(); - } -}"; - testState.AssertCodeIs(expectedCode); + testState.AssertCodeIs(""" + class C + { + event System.Action MyEvent; + void M() + { + MyEvent += C_MyEvent1; + MyEvent += C_MyEvent; + } + + private void C_MyEvent1() + { + throw new System.NotImplementedException(); + } + + private void C_MyEvent() + { + throw new System.NotImplementedException(); + } + } + """); } [WpfFact] public async Task SessionCancelledByCharacterBeforeEventHookupDeterminationCompleted() { - var markup = @" -class C -{ - event System.Action MyEvent; - void M() - { - MyEvent +$$ - } -}"; + var markup = """ + class C + { + event System.Action MyEvent; + void M() + { + MyEvent +$$ + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SetEventHookupCheckMutex(); @@ -662,15 +671,16 @@ void M() [WpfFact] public async Task TabBeforeEventHookupDeterminationCompleted() { - var markup = @" -class C -{ - event System.Action MyEvent; - void M() - { - MyEvent +$$ - } -}"; + var markup = """ + class C + { + event System.Action MyEvent; + void M() + { + MyEvent +$$ + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SetEventHookupCheckMutex(); @@ -681,37 +691,36 @@ void M() await testState.WaitForAsynchronousOperationsAsync(); testState.AssertNotShowing(); - - var expectedCode = @" -class C -{ - event System.Action MyEvent; - void M() - { - MyEvent += C_MyEvent; - } - - private void C_MyEvent() - { - throw new System.NotImplementedException(); - } -}"; - - testState.AssertCodeIs(expectedCode); + testState.AssertCodeIs(""" + class C + { + event System.Action MyEvent; + void M() + { + MyEvent += C_MyEvent; + } + + private void C_MyEvent() + { + throw new System.NotImplementedException(); + } + } + """); } [WpfFact] public async Task MoveCaretOutOfSpanBeforeEventHookupDeterminationCompleted() { - var markup = @" -class C -{ - event System.Action MyEvent; - void M() - { - MyEvent +$$ - } -}"; + var markup = """ + class C + { + event System.Action MyEvent; + void M() + { + MyEvent +$$ + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SetEventHookupCheckMutex(); @@ -726,23 +735,24 @@ void M() [WpfFact] public async Task EnsureNameUniquenessInPartialClasses() { - var markup = @" -public partial class C -{ - event System.Action MyEvent; - public async Task Test() - { - MyEvent +$$ - } -} - -public partial class C -{ - private void C_MyEvent() - { - throw new System.NotImplementedException(); - } -}"; + var markup = """ + public partial class C + { + event System.Action MyEvent; + public async Task Test() + { + MyEvent +$$ + } + } + + public partial class C + { + private void C_MyEvent() + { + throw new System.NotImplementedException(); + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); await testState.WaitForAsynchronousOperationsAsync(); @@ -752,19 +762,20 @@ private void C_MyEvent() [WpfFact] public async Task EnsureNameUniquenessAgainstBaseClasses() { - var markup = @" -class Base -{ - protected int Console_CancelKeyPress; -} -class Program : Base -{ - void Main(string[] args) - { - var goo = Console_CancelKeyPress + 23; - System.Console.CancelKeyPress +$$ - } -}"; + var markup = """ + class Base + { + protected int Console_CancelKeyPress; + } + class Program : Base + { + void Main(string[] args) + { + var goo = Console_CancelKeyPress + 23; + System.Console.CancelKeyPress +$$ + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); await testState.WaitForAsynchronousOperationsAsync(); @@ -774,16 +785,17 @@ void Main(string[] args) [WpfFact] public async Task EnsureNameUniquenessAgainstParameters() { - var markup = @" -class C -{ - event System.Action MyEvent; - - void M(int C_MyEvent) - { - MyEvent +$$ - } -}"; + var markup = """ + class C + { + event System.Action MyEvent; + + void M(int C_MyEvent) + { + MyEvent +$$ + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); await testState.WaitForAsynchronousOperationsAsync(); @@ -793,52 +805,53 @@ void M(int C_MyEvent) [WpfFact] public async Task DelegateInvokeMethodReturnsNonVoid() { - var markup = @" -class C -{ - delegate int D(double d); - event D MyEvent; - - void M() - { - MyEvent +$$ - } -}"; + var markup = """ + class C + { + delegate int D(double d); + event D MyEvent; + + void M() + { + MyEvent +$$ + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); testState.SendTab(); await testState.WaitForAsynchronousOperationsAsync(); + testState.AssertCodeIs(""" + class C + { + delegate int D(double d); + event D MyEvent; - var expectedCode = @" -class C -{ - delegate int D(double d); - event D MyEvent; - - void M() - { - MyEvent += C_MyEvent; - } + void M() + { + MyEvent += C_MyEvent; + } - private int C_MyEvent(double d) - { - throw new System.NotImplementedException(); - } -}"; - testState.AssertCodeIs(expectedCode); + private int C_MyEvent(double d) + { + throw new System.NotImplementedException(); + } + } + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553660")] public async Task PlusEqualsInsideComment() { - var markup = @" -class C -{ - void M() - { - // +$$ - } -}"; + var markup = """ + class C + { + void M() + { + // +$$ + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); testState.SendTab(); @@ -849,139 +862,136 @@ void M() [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/951664")] public async Task UseInvocationLocationTypeNameWhenEventIsMemberOfBaseType() { - var markup = @" -namespace Scenarios -{ - public class DelegateTest_Generics_NonGenericClass - { - public delegate void D1<T>(); - public event D1<string> E1; - } -} - -class TestClass_T1_S1_4 : Scenarios.DelegateTest_Generics_NonGenericClass -{ - void Method() - { - E1 +$$ - } -}"; + var markup = """ + namespace Scenarios + { + public class DelegateTest_Generics_NonGenericClass + { + public delegate void D1<T>(); + public event D1<string> E1; + } + } + + class TestClass_T1_S1_4 : Scenarios.DelegateTest_Generics_NonGenericClass + { + void Method() + { + E1 +$$ + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); testState.SendTab(); await testState.WaitForAsynchronousOperationsAsync(); - - var expectedCode = @" -namespace Scenarios -{ - public class DelegateTest_Generics_NonGenericClass - { - public delegate void D1(); - public event D1 E1; - } -} - -class TestClass_T1_S1_4 : Scenarios.DelegateTest_Generics_NonGenericClass -{ - void Method() - { - E1 += TestClass_T1_S1_4_E1; - } - - private void TestClass_T1_S1_4_E1() - { - throw new System.NotImplementedException(); - } -}"; - testState.AssertCodeIs(expectedCode); + testState.AssertCodeIs(""" + namespace Scenarios + { + public class DelegateTest_Generics_NonGenericClass + { + public delegate void D1(); + public event D1 E1; + } + } + + class TestClass_T1_S1_4 : Scenarios.DelegateTest_Generics_NonGenericClass + { + void Method() + { + E1 += TestClass_T1_S1_4_E1; + } + + private void TestClass_T1_S1_4_E1() + { + throw new System.NotImplementedException(); + } + } + """); } [WpfFact] public async Task EventHookupWithQualifiedMethodAccess() { - var markup = @" -class C -{ - event System.Action MyEvent; - void M() - { - MyEvent +$$ - } -}"; + var markup = """ + class C + { + event System.Action MyEvent; + void M() + { + MyEvent +$$ + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup, QualifyMethodAccessWithNotification(NotificationOption2.Error)); testState.SendTypeChar('='); testState.SendTab(); await testState.WaitForAsynchronousOperationsAsync(); - - var expectedCode = @" -class C -{ - event System.Action MyEvent; - void M() - { - MyEvent += this.C_MyEvent; - } - - private void C_MyEvent() - { - throw new System.NotImplementedException(); - } -}"; - testState.AssertCodeIs(expectedCode); + testState.AssertCodeIs(""" + class C + { + event System.Action MyEvent; + void M() + { + MyEvent += this.C_MyEvent; + } + + private void C_MyEvent() + { + throw new System.NotImplementedException(); + } + } + """); } [WpfFact] public async Task EventHookupRemovesInaccessibleAttributes() { - var workspaceXml = @" - - - -using System; - -public static class C -{ - public static event DelegateType E; - - public delegate void DelegateType([ShouldBeRemovedInternalAttribute] object o); -} - -internal class ShouldBeRemovedInternalAttribute : Attribute { } - - - - A - -class D -{ - void M() - { - C.E +$$ - } -} - -"; + var workspaceXml = """ + + + using System; + + public static class C + { + public static event DelegateType E; + + public delegate void DelegateType([ShouldBeRemovedInternalAttribute] object o); + } + + internal class ShouldBeRemovedInternalAttribute : Attribute { } + + + A + class D + { + void M() + { + C.E +$$ + } + } + + + """; using var testState = new EventHookupTestState(XElement.Parse(workspaceXml), options: null); testState.SendTypeChar('='); testState.SendTab(); await testState.WaitForAsynchronousOperationsAsync(); - - var expectedCode = @" -class D -{ - void M() - { - C.E += C_E; - } - - private void C_E(object o) - { - throw new System.NotImplementedException(); - } -}"; - testState.AssertCodeIs(expectedCode); + testState.AssertCodeIs(""" + class D + { + void M() + { + C.E += C_E; + } + + private void C_E(object o) + { + throw new System.NotImplementedException(); + } + } + """); } [WpfFact] @@ -990,110 +1000,107 @@ public async Task EventHookupWithQualifiedMethodAccessAndNotificationOptionSilen // This validates the scenario where the user has stated that they prefer `this.` qualification but the // notification level is `Silent`, which means existing violations of the rule won't be flagged but newly // generated code will conform appropriately. - var markup = @" -class C -{ - event System.Action MyEvent; - void M() - { - MyEvent +$$ - } -}"; + var markup = """ + class C + { + event System.Action MyEvent; + void M() + { + MyEvent +$$ + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup, QualifyMethodAccessWithNotification(NotificationOption2.Silent)); testState.SendTypeChar('='); testState.SendTab(); await testState.WaitForAsynchronousOperationsAsync(); - - var expectedCode = @" -class C -{ - event System.Action MyEvent; - void M() - { - MyEvent += this.C_MyEvent; - } - - private void C_MyEvent() - { - throw new System.NotImplementedException(); - } -}"; - testState.AssertCodeIs(expectedCode); + testState.AssertCodeIs(""" + class C + { + event System.Action MyEvent; + void M() + { + MyEvent += this.C_MyEvent; + } + + private void C_MyEvent() + { + throw new System.NotImplementedException(); + } + } + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/58474")] public async Task EventHookupInTopLevelCode() { - var markup = @" - -System.AppDomain.CurrentDomain.UnhandledException +$$ - -"; + var markup = """ + System.AppDomain.CurrentDomain.UnhandledException +$$ + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); testState.SendTab(); await testState.WaitForAsynchronousOperationsAsync(); + testState.AssertCodeIs(""" + System.AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; - var expectedCode = @" - -System.AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; - -void CurrentDomain_UnhandledException(object sender, System.UnhandledExceptionEventArgs e) -{ - throw new System.NotImplementedException(); -}"; - testState.AssertCodeIs(expectedCode); + void CurrentDomain_UnhandledException(object sender, System.UnhandledExceptionEventArgs e) + { + throw new System.NotImplementedException(); + } + """); } [WpfFact] public async Task EventHookupAtEndOfDocument() { - var markup = @" - -System.AppDomain.CurrentDomain.UnhandledException +$$"; + var markup = """ + System.AppDomain.CurrentDomain.UnhandledException +$$ + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); await testState.WaitForAsynchronousOperationsAsync(); testState.AssertShowing("CurrentDomain_UnhandledException"); - var expectedCode = @" - -System.AppDomain.CurrentDomain.UnhandledException +="; + var expectedCode = """ + System.AppDomain.CurrentDomain.UnhandledException += + """; testState.AssertCodeIs(expectedCode); testState.SendTab(); await testState.WaitForAsynchronousOperationsAsync(); - expectedCode = @" + expectedCode = """ + System.AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; -System.AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; - -void CurrentDomain_UnhandledException(object sender, System.UnhandledExceptionEventArgs e) -{ - throw new System.NotImplementedException(); -}"; + void CurrentDomain_UnhandledException(object sender, System.UnhandledExceptionEventArgs e) + { + throw new System.NotImplementedException(); + } + """; testState.AssertCodeIs(expectedCode); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/59935")] public async Task HandlerName_EventInGenericClass() { - var markup = @" -using System; - -class C -{ - void M() - { - Generic<int>.MyEvent +$$ - } -} - -class Generic<T> -{ - public static event EventHandler MyEvent; -}"; + var markup = """ + using System; + + class C + { + void M() + { + Generic<int>.MyEvent +$$ + } + } + + class Generic<T> + { + public static event EventHandler MyEvent; + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); await testState.WaitForAsynchronousOperationsAsync(); @@ -1103,21 +1110,22 @@ class Generic<T> [WpfFact] public async Task HandlerName_GlobalAlias01() { - var markup = @" -using System; - -class C -{ - void M() - { - global::D.MyEvent +$$ - } -} - -class D -{ - public static event EventHandler MyEvent; -}"; + var markup = """ + using System; + + class C + { + void M() + { + global::D.MyEvent +$$ + } + } + + class D + { + public static event EventHandler MyEvent; + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); await testState.WaitForAsynchronousOperationsAsync(); @@ -1127,21 +1135,22 @@ class D [WpfFact] public async Task HandlerName_GlobalAlias02() { - var markup = @" -using System; - -class C -{ - void M() - { - global::Generic<int>.MyEvent +$$ - } -} - -class Generic<T> -{ - public static event EventHandler MyEvent; -}"; + var markup = """ + using System; + + class C + { + void M() + { + global::Generic<int>.MyEvent +$$ + } + } + + class Generic<T> + { + public static event EventHandler MyEvent; + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); await testState.WaitForAsynchronousOperationsAsync(); @@ -1151,14 +1160,15 @@ class Generic<T> [WpfFact] public async Task HandlerName_GlobalAlias03() { - var markup = @" -class Program -{ - void Main(string[] args) - { - global::System.Console.CancelKeyPress +$$ - } -}"; + var markup = """ + class Program + { + void Main(string[] args) + { + global::System.Console.CancelKeyPress +$$ + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); await testState.WaitForAsynchronousOperationsAsync(); @@ -1168,23 +1178,24 @@ void Main(string[] args) [WpfFact] public async Task HandlerName_InvocationExpression() { - var markup = @" -using System; + var markup = """ + using System; -class C -{ - public event EventHandler MyEvent; - - public static C CreateC() - { - return new C(); - } - - public void M2() - { - CreateC().MyEvent +$$ - } -}"; + class C + { + public event EventHandler MyEvent; + + public static C CreateC() + { + return new C(); + } + + public void M2() + { + CreateC().MyEvent +$$ + } + } + """; using var testState = EventHookupTestState.CreateTestState(markup); testState.SendTypeChar('='); await testState.WaitForAsynchronousOperationsAsync(); diff --git a/src/EditorFeatures/CSharpTest/ExtractInterface/ExtractInterfaceTests.cs b/src/EditorFeatures/CSharpTest/ExtractInterface/ExtractInterfaceTests.cs index 903381749b89a..3aa4f4accbca2 100644 --- a/src/EditorFeatures/CSharpTest/ExtractInterface/ExtractInterfaceTests.cs +++ b/src/EditorFeatures/CSharpTest/ExtractInterface/ExtractInterfaceTests.cs @@ -28,9 +28,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ExtractInterface; public sealed class ExtractInterfaceTests : AbstractExtractInterfaceTests { [WpfFact] - public async Task ExtractInterface_Invocation_CaretInMethod() - { - var markup = """ + public Task ExtractInterface_Invocation_CaretInMethod() + => TestExtractInterfaceCommandCSharpAsync(""" using System; class MyClass { @@ -39,15 +38,11 @@ public void Goo() $$ } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true); - } + """, expectedSuccess: true); [WpfFact] - public async Task ExtractInterface_Invocation_CaretAfterClassClosingBrace() - { - var markup = """ + public Task ExtractInterface_Invocation_CaretAfterClassClosingBrace() + => TestExtractInterfaceCommandCSharpAsync(""" using System; class MyClass { @@ -56,15 +51,11 @@ public void Goo() } }$$ - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true); - } + """, expectedSuccess: true); [WpfFact] - public async Task ExtractInterface_Invocation_CaretBeforeClassKeyword() - { - var markup = """ + public Task ExtractInterface_Invocation_CaretBeforeClassKeyword() + => TestExtractInterfaceCommandCSharpAsync(""" using System; $$class MyClass { @@ -73,15 +64,11 @@ public void Goo() } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true); - } + """, expectedSuccess: true); [WpfFact] - public async Task ExtractInterface_Invocation_FromInnerClass1() - { - var markup = """ + public Task ExtractInterface_Invocation_FromInnerClass1() + => TestExtractInterfaceCommandCSharpAsync(""" using System; class MyClass { @@ -97,15 +84,11 @@ class AnotherClass } } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Bar"); - } + """, expectedSuccess: true, expectedMemberName: "Bar"); [WpfFact] - public async Task ExtractInterface_Invocation_FromInnerClass2() - { - var markup = """ + public Task ExtractInterface_Invocation_FromInnerClass2() + => TestExtractInterfaceCommandCSharpAsync(""" using System; class MyClass { @@ -121,15 +104,11 @@ public async Task Bar() } } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Bar"); - } + """, expectedSuccess: true, expectedMemberName: "Bar"); [WpfFact] - public async Task ExtractInterface_Invocation_FromOuterClass() - { - var markup = """ + public Task ExtractInterface_Invocation_FromOuterClass() + => TestExtractInterfaceCommandCSharpAsync(""" using System; class MyClass { @@ -145,57 +124,41 @@ public async Task Bar() } } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Goo"); - } + """, expectedSuccess: true, expectedMemberName: "Goo"); [WpfFact] - public async Task ExtractInterface_Invocation_FromInterface_01() - { - var markup = """ + public Task ExtractInterface_Invocation_FromInterface_01() + => TestExtractInterfaceCommandCSharpAsync(""" using System; interface IMyInterface { $$void Goo(); } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Goo", expectedInterfaceName: "IMyInterface1"); - } + """, expectedSuccess: true, expectedMemberName: "Goo", expectedInterfaceName: "IMyInterface1"); [WpfFact] - public async Task ExtractInterface_Invocation_FromInterface_02() - { - var markup = """ + public Task ExtractInterface_Invocation_FromInterface_02() + => TestExtractInterfaceCommandCSharpAsync(""" using System; interface IMyInterface() { $$void Goo(); } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Goo", expectedInterfaceName: "IMyInterface1"); - } + """, expectedSuccess: true, expectedMemberName: "Goo", expectedInterfaceName: "IMyInterface1"); [WpfFact] - public async Task ExtractInterface_Invocation_FromStruct() - { - var markup = """ + public Task ExtractInterface_Invocation_FromStruct() + => TestExtractInterfaceCommandCSharpAsync(""" using System; struct SomeStruct { $$public void Goo() { } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Goo", expectedInterfaceName: "ISomeStruct"); - } + """, expectedSuccess: true, expectedMemberName: "Goo", expectedInterfaceName: "ISomeStruct"); [WpfFact] - public async Task ExtractInterface_Invocation_FromNamespace() - { - var markup = """ + public Task ExtractInterface_Invocation_FromNamespace() + => TestExtractInterfaceCommandCSharpAsync(""" using System; namespace Ns$$ @@ -205,15 +168,11 @@ class MyClass public async Task Goo() { } } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: false); - } + """, expectedSuccess: false); [WpfFact] - public async Task ExtractInterface_ExtractableMembers_DoesNotIncludeFields() - { - var markup = """ + public Task ExtractInterface_ExtractableMembers_DoesNotIncludeFields() + => TestExtractInterfaceCommandCSharpAsync(""" using System; class MyClass { @@ -223,36 +182,26 @@ public void Goo() { } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Goo"); - } + """, expectedSuccess: true, expectedMemberName: "Goo"); [WpfFact] - public async Task ExtractInterface_ExtractableMembers_IncludesPublicProperty_WithGetAndSet() - { - var markup = """ + public Task ExtractInterface_ExtractableMembers_IncludesPublicProperty_WithGetAndSet() + => TestExtractInterfaceCommandCSharpAsync(""" using System; class MyClass { $$public int Prop { get; set; } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Prop"); - } + """, expectedSuccess: true, expectedMemberName: "Prop"); [WpfFact] - public async Task ExtractInterfaceAction_ExtractableMembers_IncludesPublicProperty_WithGetAndSet() - { - var markup = """ + public Task ExtractInterfaceAction_ExtractableMembers_IncludesPublicProperty_WithGetAndSet() + => TestExtractInterfaceCodeActionCSharpAsync(""" class MyClass$$ { public int Prop { get; set; } } - """; - - var expectedMarkup = """ + """, """ interface IMyClass { int Prop { get; set; } @@ -262,85 +211,61 @@ class MyClass : IMyClass { public int Prop { get; set; } } - """; - - await TestExtractInterfaceCodeActionCSharpAsync(markup, expectedMarkup); - } + """); [WpfFact] - public async Task ExtractInterface_ExtractableMembers_IncludesPublicProperty_WithGetAndPrivateSet() - { - var markup = """ + public Task ExtractInterface_ExtractableMembers_IncludesPublicProperty_WithGetAndPrivateSet() + => TestExtractInterfaceCommandCSharpAsync(""" using System; class MyClass { $$public int Prop { get; private set; } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Prop"); - } + """, expectedSuccess: true, expectedMemberName: "Prop"); [WpfFact] - public async Task ExtractInterface_ExtractableMembers_IncludesPublicProperty_WithGet() - { - var markup = """ + public Task ExtractInterface_ExtractableMembers_IncludesPublicProperty_WithGet() + => TestExtractInterfaceCommandCSharpAsync(""" using System; class MyClass { $$public int Prop { get; } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Prop"); - } + """, expectedSuccess: true, expectedMemberName: "Prop"); [WpfFact] - public async Task ExtractInterface_ExtractableMembers_ExcludesPublicProperty_WithPrivateGetAndPrivateSet() - { - var markup = """ + public Task ExtractInterface_ExtractableMembers_ExcludesPublicProperty_WithPrivateGetAndPrivateSet() + => TestExtractInterfaceCommandCSharpAsync(""" using System; class MyClass { $$public int Prop { private get; private set; } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: false); - } + """, expectedSuccess: false); [WpfFact] - public async Task ExtractInterface_ExtractableMembers_IncludesPublicIndexer() - { - var markup = """ + public Task ExtractInterface_ExtractableMembers_IncludesPublicIndexer() + => TestExtractInterfaceCommandCSharpAsync(""" using System; class MyClass { $$public int this[int x] { get { return 5; } set { } } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "this[]"); - } + """, expectedSuccess: true, expectedMemberName: "this[]"); [WpfFact] - public async Task ExtractInterface_ExtractableMembers_ExcludesInternalIndexer() - { - var markup = """ + public Task ExtractInterface_ExtractableMembers_ExcludesInternalIndexer() + => TestExtractInterfaceCommandCSharpAsync(""" using System; class MyClass { $$internal int this[int x] { get { return 5; } set { } } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: false); - } + """, expectedSuccess: false); [WpfFact] - public async Task ExtractInterface_ExtractableMembers_IncludesPublicMethod() - { - var markup = """ + public Task ExtractInterface_ExtractableMembers_IncludesPublicMethod() + => TestExtractInterfaceCommandCSharpAsync(""" using System; class MyClass { @@ -348,15 +273,11 @@ class MyClass { } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "M"); - } + """, expectedSuccess: true, expectedMemberName: "M"); [WpfFact] - public async Task ExtractInterface_ExtractableMembers_ExcludesInternalMethod() - { - var markup = """ + public Task ExtractInterface_ExtractableMembers_ExcludesInternalMethod() + => TestExtractInterfaceCommandCSharpAsync(""" using System; class MyClass { @@ -364,57 +285,41 @@ class MyClass { } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: false); - } + """, expectedSuccess: false); [WpfFact] - public async Task ExtractInterface_ExtractableMembers_IncludesAbstractMethod() - { - var markup = """ + public Task ExtractInterface_ExtractableMembers_IncludesAbstractMethod() + => TestExtractInterfaceCommandCSharpAsync(""" using System; abstract class MyClass { $$public abstract void M(); } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "M"); - } + """, expectedSuccess: true, expectedMemberName: "M"); [WpfFact] - public async Task ExtractInterface_ExtractableMembers_IncludesPublicEvent() - { - var markup = """ + public Task ExtractInterface_ExtractableMembers_IncludesPublicEvent() + => TestExtractInterfaceCommandCSharpAsync(""" using System; class MyClass { $$public event Action MyEvent; } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "MyEvent"); - } + """, expectedSuccess: true, expectedMemberName: "MyEvent"); [WpfFact] - public async Task ExtractInterface_ExtractableMembers_ExcludesPrivateEvent() - { - var markup = """ + public Task ExtractInterface_ExtractableMembers_ExcludesPrivateEvent() + => TestExtractInterfaceCommandCSharpAsync(""" using System; class MyClass { $$private event Action MyEvent; } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: false); - } + """, expectedSuccess: false); [WpfFact] - public async Task ExtractInterface_DefaultInterfaceName_DoesNotConflictWithOtherTypeNames() - { - var markup = """ + public Task ExtractInterface_DefaultInterfaceName_DoesNotConflictWithOtherTypeNames() + => TestExtractInterfaceCommandCSharpAsync(""" using System; class MyClass { @@ -424,29 +329,21 @@ class MyClass interface IMyClass { } struct IMyClass1 { } class IMyClass2 { } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceName: "IMyClass3"); - } + """, expectedSuccess: true, expectedInterfaceName: "IMyClass3"); [WpfFact] - public async Task ExtractInterface_NamespaceName_NoNamespace() - { - var markup = """ + public Task ExtractInterface_NamespaceName_NoNamespace() + => TestExtractInterfaceCommandCSharpAsync(""" using System; class MyClass { $$public void Goo() { } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedNamespaceName: ""); - } + """, expectedSuccess: true, expectedNamespaceName: ""); [WpfFact] - public async Task ExtractInterface_NamespaceName_SingleNamespace() - { - var markup = """ + public Task ExtractInterface_NamespaceName_SingleNamespace() + => TestExtractInterfaceCommandCSharpAsync(""" using System; namespace MyNamespace { @@ -455,15 +352,11 @@ class MyClass $$public void Goo() { } } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedNamespaceName: "MyNamespace"); - } + """, expectedSuccess: true, expectedNamespaceName: "MyNamespace"); [WpfFact] - public async Task ExtractInterface_NamespaceName_NestedNamespaces() - { - var markup = """ + public Task ExtractInterface_NamespaceName_NestedNamespaces() + => TestExtractInterfaceCommandCSharpAsync(""" using System; namespace OuterNamespace { @@ -475,10 +368,7 @@ class MyClass } } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedNamespaceName: "OuterNamespace.InnerNamespace"); - } + """, expectedSuccess: true, expectedNamespaceName: "OuterNamespace.InnerNamespace"); [WpfFact] public async Task ExtractInterface_NamespaceName_NestedNamespaces_FileScopedNamespace1() @@ -603,94 +493,62 @@ internal interface IMyClass } [WpfFact] - public async Task ExtractInterface_CodeGen_ClassesImplementExtractedInterface() - { - var markup = """ + public Task ExtractInterface_CodeGen_ClassesImplementExtractedInterface() + => TestExtractInterfaceCommandCSharpAsync(""" using System; class MyClass { $$public void Goo() { } } - """; - - var expectedCode = """ + """, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: """ using System; class MyClass : IMyClass { public void Goo() { } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode); - } + """); [WpfFact] - public async Task ExtractInterface_CodeGen_StructsImplementExtractedInterface() - { - var markup = """ + public Task ExtractInterface_CodeGen_StructsImplementExtractedInterface() + => TestExtractInterfaceCommandCSharpAsync(""" using System; struct MyStruct { $$public void Goo() { } } - """; - - var expectedCode = """ + """, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: """ using System; struct MyStruct : IMyStruct { public void Goo() { } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode); - } + """); [WpfFact] - public async Task ExtractInterface_CodeGen_InterfacesDoNotImplementExtractedInterface() - { - var markup = """ + public Task ExtractInterface_CodeGen_InterfacesDoNotImplementExtractedInterface() + => TestExtractInterfaceCommandCSharpAsync(""" using System; interface MyInterface { $$void Goo(); } - """; - - var expectedCode = """ + """, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: """ using System; interface MyInterface { void Goo(); } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode); - } + """); [WpfFact] public async Task ExtractInterface_CodeGen_Methods() { - var markup = """ - using System; - - abstract class MyClass$$ - { - public required int RequiredProperty { get; set; } - public void ExtractableMethod_Normal() { } - public void ExtractableMethod_ParameterTypes(System.Diagnostics.CorrelationManager x, Nullable y = 7, string z = "42") { } - public abstract void ExtractableMethod_Abstract(); - unsafe public void NotActuallyUnsafeMethod(int p) { } - unsafe public void UnsafeMethod(int *p) { } - } - """; - var expectedInterfaceCode = """ using System.Diagnostics; @@ -706,19 +564,24 @@ interface IMyClass } """; - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode); + await TestExtractInterfaceCommandCSharpAsync(""" + using System; + + abstract class MyClass$$ + { + public required int RequiredProperty { get; set; } + public void ExtractableMethod_Normal() { } + public void ExtractableMethod_ParameterTypes(System.Diagnostics.CorrelationManager x, Nullable y = 7, string z = "42") { } + public abstract void ExtractableMethod_Abstract(); + unsafe public void NotActuallyUnsafeMethod(int p) { } + unsafe public void UnsafeMethod(int *p) { } + } + """, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode); } [WpfFact] public async Task ExtractInterface_CodeGen_MethodsInRecord() { - var markup = """ - abstract record R$$ - { - public void M() { } - } - """; - var expectedInterfaceCode = """ interface IR { @@ -730,22 +593,17 @@ interface IR } """; - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode); + await TestExtractInterfaceCommandCSharpAsync(""" + abstract record R$$ + { + public void M() { } + } + """, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode); } [WpfFact] public async Task ExtractInterface_CodeGen_Events() { - var markup = """ - using System; - - abstract internal class MyClass$$ - { - public event Action ExtractableEvent1; - public event Action> ExtractableEvent2; - } - """; - var expectedInterfaceCode = """ using System; @@ -756,13 +614,36 @@ internal interface IMyClass } """; - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode); + await TestExtractInterfaceCommandCSharpAsync(""" + using System; + + abstract internal class MyClass$$ + { + public event Action ExtractableEvent1; + public event Action> ExtractableEvent2; + } + """, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode); } [WpfFact] public async Task ExtractInterface_CodeGen_Properties() { - var markup = """ + var expectedInterfaceCode = """ + interface IMyClass + { + int ExtractableProp { get; set; } + int ExtractableProp_GetOnly { get; } + int ExtractableProp_SetOnly { set; } + int ExtractableProp_SetPrivate { get; } + int ExtractableProp_GetPrivate { set; } + int ExtractableProp_SetInternal { get; } + int ExtractableProp_GetInternal { set; } + int NotActuallyUnsafeProp { get; set; } + unsafe int* UnsafeProp { get; set; } + } + """; + + await TestExtractInterfaceCommandCSharpAsync(""" using System; abstract class MyClass$$ @@ -778,30 +659,23 @@ public int ExtractableProp_SetOnly { set { } } unsafe public int* UnsafeProp { get; set; } } - """; + """, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode); + } + [WpfFact] + public async Task ExtractInterface_CodeGen_Indexers() + { var expectedInterfaceCode = """ interface IMyClass { - int ExtractableProp { get; set; } - int ExtractableProp_GetOnly { get; } - int ExtractableProp_SetOnly { set; } - int ExtractableProp_SetPrivate { get; } - int ExtractableProp_GetPrivate { set; } - int ExtractableProp_SetInternal { get; } - int ExtractableProp_GetInternal { set; } - int NotActuallyUnsafeProp { get; set; } - unsafe int* UnsafeProp { get; set; } + int this[int x] { set; } + int this[string x] { get; } + int this[double x] { get; set; } + int this[int? x, string y = "42"] { get; set; } } """; - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode); - } - - [WpfFact] - public async Task ExtractInterface_CodeGen_Indexers() - { - var markup = """ + await TestExtractInterfaceCommandCSharpAsync(""" using System; abstract class MyClass$$ @@ -811,33 +685,12 @@ public int this[int x] { set { } } public int this[double x] { get { return 1; } set { } } public int this[Nullable x, string y = "42"] { get { return 1; } set { } } } - """; - - var expectedInterfaceCode = """ - interface IMyClass - { - int this[int x] { set; } - int this[string x] { get; } - int this[double x] { get; set; } - int this[int? x, string y = "42"] { get; set; } - } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode); + """, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode); } [WpfFact] public async Task ExtractInterface_CodeGen_Imports() { - var markup = """ - public class Class - { - $$public System.Diagnostics.BooleanSwitch M1(System.Globalization.Calendar x) { return null; } - public void M2(System.Collections.Generic.List x) { } - public void M3() where T : System.Net.WebProxy { } - } - """; - var expectedInterfaceCode = """ using System.Collections.Generic; using System.Diagnostics; @@ -853,7 +706,14 @@ public interface IClass } """; - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode); + await TestExtractInterfaceCommandCSharpAsync(""" + public class Class + { + $$public System.Diagnostics.BooleanSwitch M1(System.Globalization.Calendar x) { return null; } + public void M2(System.Collections.Generic.List x) { } + public void M3() where T : System.Net.WebProxy { } + } + """, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode); } [WpfFact] @@ -870,8 +730,20 @@ public void M3() where T : System.Net.WebProxy { } } } """; + using var testState = ExtractInterfaceTestState.Create( + markup, LanguageNames.CSharp, + parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10), + options: new OptionsCollection(LanguageNames.CSharp) + { + { CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, AddImportPlacement.InsideNamespace } + }); - var expectedInterfaceCode = """ + var result = await testState.ExtractViaCommandAsync(); + + var interfaceDocument = result.UpdatedSolution.GetRequiredDocument(result.NavigationDocumentId); + var interfaceCode = (await interfaceDocument.GetTextAsync()).ToString(); + + Assert.Equal(""" namespace N { using System.Collections.Generic; @@ -887,43 +759,12 @@ public interface IClass void M3() where T : WebProxy; } } - """; - - using var testState = ExtractInterfaceTestState.Create( - markup, LanguageNames.CSharp, - parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10), - options: new OptionsCollection(LanguageNames.CSharp) - { - { CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, AddImportPlacement.InsideNamespace } - }); - - var result = await testState.ExtractViaCommandAsync(); - - var interfaceDocument = result.UpdatedSolution.GetRequiredDocument(result.NavigationDocumentId); - var interfaceCode = (await interfaceDocument.GetTextAsync()).ToString(); - - Assert.Equal(expectedInterfaceCode, interfaceCode); + """, interfaceCode); } [WpfFact] public async Task ExtractInterface_CodeGen_TypeParameters1() { - var markup = """ - public class Class where E : F - { - $$public void Goo1(A a) { } - public B Goo2() { return default(B); } - public void Goo3(List list) { } - - public event Func Goo4; - - public List Prop { set { } } - public List this[List> list] { set { } } - - public void Bar1() { var x = default(NO1); } - } - """; - var expectedInterfaceCode = """ public interface IClass where E : F { @@ -940,22 +781,27 @@ public interface IClass where E : F } """; - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode); + await TestExtractInterfaceCommandCSharpAsync(""" + public class Class where E : F + { + $$public void Goo1(A a) { } + public B Goo2() { return default(B); } + public void Goo3(List list) { } + + public event Func Goo4; + + public List Prop { set { } } + public List this[List> list] { set { } } + + public void Bar1() { var x = default(NO1); } + } + """, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode); } [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/706894")] [WpfFact] public async Task ExtractInterface_CodeGen_TypeParameters2() { - var markup = """ - using System.Collections.Generic; - - class Program where A : List where B : Dictionary, List> - { - $$public void Goo(T t) where T : List { } - } - """; - var expectedInterfaceCode = """ using System.Collections.Generic; @@ -967,13 +813,27 @@ interface IProgram } """; - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode); + await TestExtractInterfaceCommandCSharpAsync(""" + using System.Collections.Generic; + + class Program where A : List where B : Dictionary, List> + { + $$public void Goo(T t) where T : List { } + } + """, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode); } [WpfFact] public async Task ExtractInterface_CodeGen_TypeParameters3() { - var markup = """ + var expectedInterfaceCode = """ + interface IClass1 + { + void method(A P1, Class1.Class2 P2); + } + """; + + await TestExtractInterfaceCommandCSharpAsync(""" class $$Class1 { public void method(A P1, Class2 P2) @@ -983,40 +843,13 @@ public class Class2 { } } - """; - - var expectedInterfaceCode = """ - interface IClass1 - { - void method(A P1, Class1.Class2 P2); - } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode); + """, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode); } [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/706894")] [WpfFact] public async Task ExtractInterface_CodeGen_TypeParameters4() { - var markup = """ - class C1 - { - public class C2 where B : new() - { - public class C3 where C : System.Collections.ICollection - { - public class C4 - {$$ - public A method() { return default(A); } - public B property { set { } } - public C this[int i] { get { return default(C); } } - } - } - } - } - """; - var expectedInterfaceCode = """ using System.Collections; @@ -1032,7 +865,23 @@ public interface IC4 } """; - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode); + await TestExtractInterfaceCommandCSharpAsync(""" + class C1 + { + public class C2 where B : new() + { + public class C3 where C : System.Collections.ICollection + { + public class C4 + {$$ + public A method() { return default(A); } + public B property { set { } } + public C this[int i] { get { return default(C); } } + } + } + } + } + """, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode); } [WpfFact] @@ -1068,117 +917,86 @@ internal interface IMyClass } [WpfFact] - public async Task ExtractInterface_CodeGen_BaseList_NewBaseListNonGeneric() - { - var markup = """ + public Task ExtractInterface_CodeGen_BaseList_NewBaseListNonGeneric() + => TestExtractInterfaceCommandCSharpAsync(""" class Program { $$public void Goo() { } } - """; - - var expectedCode = """ + """, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: """ class Program : IProgram { public void Goo() { } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode); - } + """); [WpfFact] - public async Task ExtractInterface_CodeGen_BaseList_NewBaseListGeneric() - { - var markup = """ + public Task ExtractInterface_CodeGen_BaseList_NewBaseListGeneric() + => TestExtractInterfaceCommandCSharpAsync(""" class Program { $$public void Goo(T t) { } } - """; - - var expectedCode = """ + """, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: """ class Program : IProgram { public void Goo(T t) { } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode); - } + """); [WpfFact] - public async Task ExtractInterface_CodeGen_BaseList_NewBaseListWithWhereClause() - { - var markup = """ + public Task ExtractInterface_CodeGen_BaseList_NewBaseListWithWhereClause() + => TestExtractInterfaceCommandCSharpAsync(""" class Program where T : U { $$public void Goo(T t, U u) { } } - """; - - var expectedCode = """ + """, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: """ class Program : IProgram where T : U { public void Goo(T t, U u) { } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode); - } + """); [WpfFact] - public async Task ExtractInterface_CodeGen_BaseList_LargerBaseList1() - { - var markup = """ + public Task ExtractInterface_CodeGen_BaseList_LargerBaseList1() + => TestExtractInterfaceCommandCSharpAsync(""" class Program : ISomeInterface { $$public void Goo() { } } interface ISomeInterface {} - """; - - var expectedCode = """ + """, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: """ class Program : ISomeInterface, IProgram { public void Goo() { } } interface ISomeInterface {} - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode); - } + """); [WpfFact] - public async Task ExtractInterface_CodeGen_BaseList_LargerBaseList2() - { - var markup = """ + public Task ExtractInterface_CodeGen_BaseList_LargerBaseList2() + => TestExtractInterfaceCommandCSharpAsync(""" class Program : ISomeInterface { $$public void Goo(T t, U u) { } } interface ISomeInterface {} - """; - - var expectedCode = """ + """, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: """ class Program : ISomeInterface, IProgram { public void Goo(T t, U u) { } } interface ISomeInterface {} - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode); - } + """); [WpfFact] - public async Task ExtractInterface_CodeGen_BaseList_LargerBaseList3() - { - var markup = """ + public Task ExtractInterface_CodeGen_BaseList_LargerBaseList3() + => TestExtractInterfaceCommandCSharpAsync(""" class Program : ISomeInterface, ISomeInterface2 { $$public void Goo(T t, U u) { } @@ -1186,9 +1004,7 @@ class Program : ISomeInterface, ISomeInterface2 interface ISomeInterface {} interface ISomeInterface2 {} - """; - - var expectedCode = """ + """, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: """ class Program : ISomeInterface, ISomeInterface2, IProgram { public void Goo(T t, U u) { } @@ -1196,15 +1012,11 @@ public void Goo(T t, U u) { } interface ISomeInterface {} interface ISomeInterface2 {} - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode); - } + """); [WpfFact] - public async Task ExtractInterface_CodeGen_BaseList_LargerBaseList4() - { - var markup = """ + public Task ExtractInterface_CodeGen_BaseList_LargerBaseList4() + => TestExtractInterfaceCommandCSharpAsync(""" class Program : ISomeInterface, ISomeInterface2 where T : U { $$public void Goo(T t, U u) { } @@ -1212,9 +1024,7 @@ class Program : ISomeInterface, ISomeInterface2 where T : U interface ISomeInterface {} interface ISomeInterface2 {} - """; - - var expectedCode = """ + """, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: """ class Program : ISomeInterface, ISomeInterface2, IProgram where T : U { public void Goo(T t, U u) { } @@ -1222,155 +1032,111 @@ public void Goo(T t, U u) { } interface ISomeInterface {} interface ISomeInterface2 {} - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode); - } + """); [WpfFact] - public async Task ExtractInterface_TypeDiscovery_NameOnly1() - { - var markup = """ + public Task ExtractInterface_TypeDiscovery_NameOnly1() + => TestTypeDiscoveryAsync(""" interface ISomeInterface {} class Program : ISomeInterface where T : U { $$public void Goo(T t, U u) { } } - """; - - await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: false); - } + """, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: false); [WpfFact] - public async Task ExtractInterface_TypeDiscovery_NameOnly2() - { - var markup = """ + public Task ExtractInterface_TypeDiscovery_NameOnly2() + => TestTypeDiscoveryAsync(""" interface ISomeInterface {} class Program $$: ISomeInterface where T : U { public void Goo(T t, U u) { } } - """; - - await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true); - } + """, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true); [WpfFact] - public async Task ExtractInterface_TypeDiscovery_NameOnly3() - { - var markup = """ + public Task ExtractInterface_TypeDiscovery_NameOnly3() + => TestTypeDiscoveryAsync(""" interface ISomeInterface {} class$$ Program : ISomeInterface where T : U { public void Goo(T t, U u) { } } - """; - - await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true); - } + """, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true); [WpfFact] - public async Task ExtractInterface_TypeDiscovery_NameOnly4() - { - var markup = """ + public Task ExtractInterface_TypeDiscovery_NameOnly4() + => TestTypeDiscoveryAsync(""" interface ISomeInterface {} class Program$$ : ISomeInterface where T : U { public void Goo(T t, U u) { } } - """; - - await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true); - } + """, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true); [WpfFact] - public async Task ExtractInterface_TypeDiscovery_NameOnly5() - { - var markup = """ + public Task ExtractInterface_TypeDiscovery_NameOnly5() + => TestTypeDiscoveryAsync(""" interface ISomeInterface {} class Program $$ : ISomeInterface where T : U { public void Goo(T t, U u) { } } - """; - - await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true); - } + """, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true); [WpfFact] - public async Task ExtractInterface_TypeDiscovery_NameOnly6() - { - var markup = """ + public Task ExtractInterface_TypeDiscovery_NameOnly6() + => TestTypeDiscoveryAsync(""" interface ISomeInterface {} class $$Program : ISomeInterface where T : U { public void Goo(T t, U u) { } } - """; - - await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true); - } + """, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true); [WpfFact] - public async Task ExtractInterface_TypeDiscovery_NameOnly7() - { - var markup = """ + public Task ExtractInterface_TypeDiscovery_NameOnly7() + => TestTypeDiscoveryAsync(""" interface ISomeInterface {} class $$Program : ISomeInterface { public void Goo() { } } - """; - - await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true); - } + """, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true); [WpfFact] - public async Task ExtractInterface_TypeDiscovery_NameOnly8() - { - var markup = """ + public Task ExtractInterface_TypeDiscovery_NameOnly8() + => TestTypeDiscoveryAsync(""" interface ISomeInterface {} class Program$$ : ISomeInterface { public void Goo() { } } - """; - - await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true); - } + """, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true); [WpfFact] - public async Task ExtractInterface_TypeDiscovery_NameOnly9() - { - var markup = """ + public Task ExtractInterface_TypeDiscovery_NameOnly9() + => TestTypeDiscoveryAsync(""" interface ISomeInterface {} class$$ Program : ISomeInterface { public void Goo() { } } - """; - - await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true); - } + """, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true); [WpfFact] - public async Task ExtractInterface_TypeDiscovery_NameOnly10() - { - var markup = """ + public Task ExtractInterface_TypeDiscovery_NameOnly10() + => TestTypeDiscoveryAsync(""" interface ISomeInterface {} class Program $$: ISomeInterface { public void Goo() { } } - """; - - await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true); - } + """, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true); [WpfFact] - public async Task ExtractInterface_TypeDiscovery_NameOnly11() - { - var markup = """ + public Task ExtractInterface_TypeDiscovery_NameOnly11() + => TestTypeDiscoveryAsync(""" namespace N { $$ class Program @@ -1378,10 +1144,7 @@ namespace N public void Goo() { } } } - """; - - await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true); - } + """, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true); private static async Task TestTypeDiscoveryAsync( string markup, @@ -1396,43 +1159,37 @@ private static async Task TestTypeDiscoveryAsync( [WpfFact] public async Task ExtractInterface_GeneratedNameTypeParameterSuffix1() { - var markup = """ + var expectedTypeParameterSuffix = @""; + await TestExtractInterfaceCommandCSharpAsync(""" class $$Test { public void M(T a) { } } - """; - - var expectedTypeParameterSuffix = @""; - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedTypeParameterSuffix: expectedTypeParameterSuffix); + """, expectedSuccess: true, expectedTypeParameterSuffix: expectedTypeParameterSuffix); } [WpfFact] public async Task ExtractInterface_GeneratedNameTypeParameterSuffix2() { - var markup = """ + var expectedTypeParameterSuffix = @""; + await TestExtractInterfaceCommandCSharpAsync(""" class $$Test { public void M(T a) { } } - """; - - var expectedTypeParameterSuffix = @""; - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedTypeParameterSuffix: expectedTypeParameterSuffix); + """, expectedSuccess: true, expectedTypeParameterSuffix: expectedTypeParameterSuffix); } [WpfFact] public async Task ExtractInterface_GeneratedNameTypeParameterSuffix3() { - var markup = """ + var expectedTypeParameterSuffix = @""; + await TestExtractInterfaceCommandCSharpAsync(""" class $$Test { public void M(T a, U b) { } } - """; - - var expectedTypeParameterSuffix = @""; - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedTypeParameterSuffix: expectedTypeParameterSuffix); + """, expectedSuccess: true, expectedTypeParameterSuffix: expectedTypeParameterSuffix); } [WpfFact, Trait(Traits.Feature, Traits.Features.Interactive)] @@ -1462,9 +1219,8 @@ public void M() { } } [WpfFact] - public async Task TestInWithMethod_Parameters() - { - var markup = """ + public Task TestInWithMethod_Parameters() + => TestExtractInterfaceCommandCSharpAsync(""" using System; class $$TestClass { @@ -1472,178 +1228,153 @@ public void Method(in int p1) { } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: + """, expectedSuccess: true, expectedInterfaceCode: """ interface ITestClass { void Method(in int p1); } """); - } [WpfFact] - public async Task TestRefReadOnlyWithMethod_ReturnType() - { - var markup = """ + public Task TestRefReadOnlyWithMethod_ReturnType() + => TestExtractInterfaceCommandCSharpAsync(""" using System; class $$TestClass { public ref readonly int Method() => throw null; } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: + """, expectedSuccess: true, expectedInterfaceCode: """ interface ITestClass { ref readonly int Method(); } """); - } [WpfFact] - public async Task TestRefReadOnlyWithProperty() - { - var markup = """ + public Task TestRefReadOnlyWithProperty() + => TestExtractInterfaceCommandCSharpAsync(""" using System; class $$TestClass { public ref readonly int Property => throw null; } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: + """, expectedSuccess: true, expectedInterfaceCode: """ interface ITestClass { ref readonly int Property { get; } } """); - } [WpfFact] - public async Task TestInWithIndexer_Parameters() - { - var markup = """ + public Task TestInWithIndexer_Parameters() + => TestExtractInterfaceCommandCSharpAsync(""" using System; class $$TestClass { public int this[in int p1] { set { } } } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: + """, expectedSuccess: true, expectedInterfaceCode: """ interface ITestClass { int this[in int p1] { set; } } """); - } [WpfFact] - public async Task TestRefReadOnlyWithIndexer_ReturnType() - { - var markup = """ + public Task TestRefReadOnlyWithIndexer_ReturnType() + => TestExtractInterfaceCommandCSharpAsync(""" using System; class $$TestClass { public ref readonly int this[int p1] => throw null; } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: + """, expectedSuccess: true, expectedInterfaceCode: """ interface ITestClass { ref readonly int this[int p1] { get; } } """); - } [WpfFact] - public async Task TestUnmanagedConstraint_Type() - { - var markup = """ + public Task TestUnmanagedConstraint_Type() + => TestExtractInterfaceCommandCSharpAsync(""" class $$TestClass where T : unmanaged { public void M(T arg) => throw null; } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: + """, expectedSuccess: true, expectedInterfaceCode: """ interface ITestClass where T : unmanaged { void M(T arg); } """); - } [WpfFact] - public async Task TestUnmanagedConstraint_Method() - { - var markup = """ + public Task TestUnmanagedConstraint_Method() + => TestExtractInterfaceCommandCSharpAsync(""" class $$TestClass { public void M() where T : unmanaged => throw null; } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: + """, expectedSuccess: true, expectedInterfaceCode: """ interface ITestClass { void M() where T : unmanaged; } """); - } [WpfFact] - public async Task TestNotNullConstraint_Type() - { - var markup = """ + public Task TestNotNullConstraint_Type() + => TestExtractInterfaceCommandCSharpAsync(""" class $$TestClass where T : notnull { public void M(T arg) => throw null; } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: + """, expectedSuccess: true, expectedInterfaceCode: """ interface ITestClass where T : notnull { void M(T arg); } """); - } [WpfFact] - public async Task TestNotNullConstraint_Method() - { - var markup = """ + public Task TestNotNullConstraint_Method() + => TestExtractInterfaceCommandCSharpAsync(""" class $$TestClass { public void M() where T : notnull => throw null; } - """; - - await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: + """, expectedSuccess: true, expectedInterfaceCode: """ interface ITestClass { void M() where T : notnull; } """); - } [WorkItem("https://github.com/dotnet/roslyn/issues/23855")] [WpfFact] public async Task TestExtractInterface_WithCopyright1() { - var markup = + var expectedInterfaceCode = + """ + // Copyright + + public interface IGoo + { + void Test(); + } + """; + + await TestExtractInterfaceCommandCSharpAsync( """ // Copyright @@ -1653,10 +1384,9 @@ public void Test() { } } - """; - - var updatedMarkup = - """ + """, + expectedSuccess: true, + expectedUpdatedOriginalDocumentCode: """ // Copyright public class Goo : IGoo @@ -1665,30 +1395,25 @@ public void Test() { } } - """; + """, + expectedInterfaceCode: expectedInterfaceCode); + } + [WorkItem("https://github.com/dotnet/roslyn/issues/23855")] + [WpfFact] + public async Task TestExtractInterface_WithCopyright2() + { var expectedInterfaceCode = """ // Copyright - public interface IGoo + public interface IA { void Test(); } """; await TestExtractInterfaceCommandCSharpAsync( - markup, - expectedSuccess: true, - expectedUpdatedOriginalDocumentCode: updatedMarkup, - expectedInterfaceCode: expectedInterfaceCode); - } - - [WorkItem("https://github.com/dotnet/roslyn/issues/23855")] - [WpfFact] - public async Task TestExtractInterface_WithCopyright2() - { - var markup = """ // Copyright @@ -1701,10 +1426,9 @@ public void Test() } } } - """; - - var updatedMarkup = - """ + """, + expectedSuccess: true, + expectedUpdatedOriginalDocumentCode: """ // Copyright public class Goo @@ -1716,22 +1440,7 @@ public void Test() } } } - """; - - var expectedInterfaceCode = - """ - // Copyright - - public interface IA - { - void Test(); - } - """; - - await TestExtractInterfaceCommandCSharpAsync( - markup, - expectedSuccess: true, - expectedUpdatedOriginalDocumentCode: updatedMarkup, + """, expectedInterfaceCode: expectedInterfaceCode); } @@ -1739,22 +1448,6 @@ await TestExtractInterfaceCommandCSharpAsync( [WpfFact] public async Task TestRecord1() { - var markup = - """ - namespace Test - { - record $$Whatever(int X, string Y); - } - """; - - var updatedMarkup = - """ - namespace Test - { - record Whatever(int X, string Y) : IWhatever; - } - """; - var expectedInterfaceCode = """ namespace Test @@ -1774,64 +1467,48 @@ interface IWhatever """; await TestExtractInterfaceCommandCSharpAsync( - markup, + """ + namespace Test + { + record $$Whatever(int X, string Y); + } + """, expectedSuccess: true, - expectedUpdatedOriginalDocumentCode: updatedMarkup, + expectedUpdatedOriginalDocumentCode: """ + namespace Test + { + record Whatever(int X, string Y) : IWhatever; + } + """, expectedInterfaceCode: expectedInterfaceCode); } [WpfFact] - public async Task TestClass1() - { - var markup = + public Task TestClass1() + => TestExtractInterfaceCommandCSharpAsync( """ namespace Test { class $$Whatever(int X, string Y); } - """; - - await TestExtractInterfaceCommandCSharpAsync( - markup, + """, expectedSuccess: false); - } [WpfFact] - public async Task TestStruct1() - { - var markup = + public Task TestStruct1() + => TestExtractInterfaceCommandCSharpAsync( """ namespace Test { struct $$Whatever(int X, string Y); } - """; - - await TestExtractInterfaceCommandCSharpAsync( - markup, + """, expectedSuccess: false); - } [WorkItem("https://github.com/dotnet/roslyn/issues/49739")] [WpfFact] public async Task TestRecord2() { - var markup = - """ - namespace Test - { - record $$Whatever(int X, string Y) { } - } - """; - - var updatedMarkup = - """ - namespace Test - { - record Whatever(int X, string Y) : IWhatever { } - } - """; - var expectedInterfaceCode = """ namespace Test @@ -1851,66 +1528,48 @@ interface IWhatever """; await TestExtractInterfaceCommandCSharpAsync( - markup, + """ + namespace Test + { + record $$Whatever(int X, string Y) { } + } + """, expectedSuccess: true, - expectedUpdatedOriginalDocumentCode: updatedMarkup, + expectedUpdatedOriginalDocumentCode: """ + namespace Test + { + record Whatever(int X, string Y) : IWhatever { } + } + """, expectedInterfaceCode: expectedInterfaceCode); } [WpfFact] - public async Task TestClass2() - { - var markup = + public Task TestClass2() + => TestExtractInterfaceCommandCSharpAsync( """ namespace Test { class $$Whatever(int X, string Y) { } } - """; - - await TestExtractInterfaceCommandCSharpAsync( - markup, + """, expectedSuccess: false); - } [WpfFact] - public async Task TestStruct2() - { - var markup = + public Task TestStruct2() + => TestExtractInterfaceCommandCSharpAsync( """ namespace Test { struct $$Whatever(int X, string Y) { } } - """; - - await TestExtractInterfaceCommandCSharpAsync( - markup, + """, expectedSuccess: false); - } [WorkItem("https://github.com/dotnet/roslyn/issues/49739")] [WpfFact] public async Task TestRecord3() { - var markup = - """ - namespace Test - { - /// - record $$Whatever(int X, string Y); - } - """; - - var updatedMarkup = - """ - namespace Test - { - /// - record Whatever(int X, string Y) : IWhatever; - } - """; - var expectedInterfaceCode = """ namespace Test @@ -1930,81 +1589,79 @@ interface IWhatever """; await TestExtractInterfaceCommandCSharpAsync( - markup, + """ + namespace Test + { + /// + record $$Whatever(int X, string Y); + } + """, expectedSuccess: true, - expectedUpdatedOriginalDocumentCode: updatedMarkup, + expectedUpdatedOriginalDocumentCode: """ + namespace Test + { + /// + record Whatever(int X, string Y) : IWhatever; + } + """, expectedInterfaceCode: expectedInterfaceCode); } [WpfFact] - public async Task TestClass3() - { - var markup = + public Task TestClass3() + => TestExtractInterfaceCommandCSharpAsync( """ namespace Test { /// class $$Whatever(int X, string Y); } - """; - - await TestExtractInterfaceCommandCSharpAsync( - markup, + """, expectedSuccess: false); - } [WpfFact] - public async Task TestStruct3() - { - var markup = + public Task TestStruct3() + => TestExtractInterfaceCommandCSharpAsync( """ namespace Test { /// struct $$Whatever(int X, string Y); } - """; - - await TestExtractInterfaceCommandCSharpAsync( - markup, + """, expectedSuccess: false); - } [WpfFact] public async Task TestStruct4() { - var markup = + var expectedInterfaceCode = """ namespace Test { - struct $$Whatever + interface IWhatever { - public int I { get; set; } + int I { get; set; } } } """; - var expectedInterfaceCode = + await TestExtractInterfaceCommandCSharpAsync( """ namespace Test { - interface IWhatever + struct $$Whatever { - int I { get; set; } + public int I { get; set; } } } - """; - - await TestExtractInterfaceCommandCSharpAsync( - markup, + """, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/71718")] - public async Task RemoveEnumeratorCancellationAttribute() - { - var markup = """ + public Task RemoveEnumeratorCancellationAttribute() + => TestExtractInterfaceCodeActionCSharpAsync(""" Foo([EnumeratorCancellation] CancellationToke }]]> - """; - - var expectedMarkup = """ + """, """ using System; using System.Collections.Generic; using System.Runtime.CompilerServices; @@ -2047,15 +1702,11 @@ public async IAsyncEnumerable Foo([EnumeratorCancellation] CancellationToke } } } - """; - - await TestExtractInterfaceCodeActionCSharpAsync(markup, expectedMarkup); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/54019")] - public async Task TestStaticMember() - { - var markup = """ + public Task TestStaticMember() + => TestExtractInterfaceCodeActionCSharpAsync(""" using System; class MyClass$$ @@ -2064,9 +1715,7 @@ public static void M() { } public static int Prop { get; set; } public static event Action Event; } - """; - - var expectedMarkup = """ + """, """ using System; interface IMyClass @@ -2084,15 +1733,12 @@ public static void M() { } public static int Prop { get; set; } public static event Action Event; } - """; - - await TestExtractInterfaceCodeActionCSharpAsync(markup, expectedMarkup); - } + """); [WpfFact] - public async Task ExtractInterface_Invocation_FromExtension() - { - var markup = """ + public Task ExtractInterface_Invocation_FromExtension() + => TestExtractInterfaceCommandCSharpAsync( + """ using System; static class C @@ -2102,10 +1748,6 @@ static class C public void Goo() { } } } - """; - - await TestExtractInterfaceCommandCSharpAsync( - markup, expectedSuccess: false, + """, expectedSuccess: false, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersionExtensions.CSharpNext)); - } } diff --git a/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodBase.cs b/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodBase.cs index 46d96e9c754df..2e7ffbc7dd821 100644 --- a/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodBase.cs +++ b/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodBase.cs @@ -5,6 +5,7 @@ #nullable disable using System.Diagnostics.CodeAnalysis; +using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -32,7 +33,7 @@ protected static async Task ExpectExtractMethodToFailAsync( ParseOptions parseOptions = null; if (features != null) { - var featuresMapped = features.Select(x => KeyValuePairUtil.Create(x, string.Empty)); + var featuresMapped = features.Select(x => KeyValuePair.Create(x, string.Empty)); parseOptions = new CSharpParseOptions().WithFeatures(featuresMapped); } diff --git a/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodMiscellaneousTests.cs b/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodMiscellaneousTests.cs index ba33a86b17b1f..873818d5b118b 100644 --- a/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodMiscellaneousTests.cs +++ b/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodMiscellaneousTests.cs @@ -29,7 +29,7 @@ public sealed class ExtractMethodMiscellaneousTests [Fact] public void ServiceTest1() { - var markupCode = """ + MarkupTestFile.GetSpan(""" class A { /* test */ [|public|] void Test(int i, int b, int c) @@ -37,8 +37,7 @@ class A } } - """; - MarkupTestFile.GetSpan(markupCode, out var code, out var span); + """, out var code, out var span); var root = SyntaxFactory.ParseCompilationUnit(code); var result = CSharpSyntaxTriviaService.Instance.SaveTriviaAroundSelection(root, span); @@ -53,8 +52,7 @@ class A // restore trivia around it var rootWithTriviaRestored = result.RestoreTrivia(newRoot); - - var expected = """ + Assert.Equal(""" class A { /* test */ private void Test(int i, int b, int c) @@ -62,15 +60,13 @@ class A } } - """; - - Assert.Equal(expected, rootWithTriviaRestored.ToFullString()); + """, rootWithTriviaRestored.ToFullString()); } [Fact] public void ServiceTest2() { - var markupCode = """ + MarkupTestFile.GetSpan(""" class A { @@ -82,8 +78,7 @@ class A #endif } - """; - MarkupTestFile.GetSpan(markupCode, out var code, out var span); + """, out var code, out var span); var root = SyntaxFactory.ParseCompilationUnit(code); var result = CSharpSyntaxTriviaService.Instance.SaveTriviaAroundSelection(root, span); @@ -98,8 +93,7 @@ class A // restore trivia around it var rootWithTriviaRestored = result.RestoreTrivia(newRoot); - - var expected = """ + Assert.Equal(""" class A { @@ -111,23 +105,17 @@ private void Test(int i, int b, int c) #endif } - """; - - Assert.Equal(expected, rootWithTriviaRestored.ToFullString()); + """, rootWithTriviaRestored.ToFullString()); } [WpfFact] - public async Task TestExtractMethodCommandHandlerErrorMessage() - { - var markupCode = """ + public Task TestExtractMethodCommandHandlerErrorMessage() + => TestCommandHandler(""" class A { [|void Method() {}|] } - """; - - await TestCommandHandler(markupCode, result: null, expectNotification: true); - } + """, result: null, expectNotification: true); private static async Task TestCommandHandler(string markupCode, string? result, bool expectNotification) { @@ -156,13 +144,10 @@ private static async Task TestCommandHandler(string markupCode, string? result, } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/65465")] - public async Task TestExtractLocalFunctionInTopLevelFromCommandHandler() - { - var markupCode = """ + public Task TestExtractLocalFunctionInTopLevelFromCommandHandler() + => TestCommandHandler(""" System.Console.WriteLine([|"string"|]); - """; - - await TestCommandHandler(markupCode, """ + """, """ System.Console.WriteLine(NewMethod()); static string NewMethod() @@ -170,5 +155,4 @@ static string NewMethod() return "string"; } """, expectNotification: false); - } } diff --git a/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodTests.LanguageInteraction.cs b/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodTests.LanguageInteraction.cs index ebc2950154888..b60dc3e1c6aa1 100644 --- a/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodTests.LanguageInteraction.cs +++ b/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodTests.LanguageInteraction.cs @@ -21,9 +21,8 @@ public sealed class LanguageInteraction : ExtractMethodBase #region Generics [Fact] - public async Task SelectTypeParameterWithConstraints() - { - var code = """ + public Task SelectTypeParameterWithConstraints() + => TestExtractMethodAsync(""" using System; class Program @@ -34,8 +33,7 @@ class Program return abcd; } } - """; - var expected = """ + """, """ using System; class Program @@ -51,15 +49,11 @@ class Program return new TT(); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task SelectTypeParameterWithAllowsRefStructAntiConstraint() - { - var code = """ + public Task SelectTypeParameterWithAllowsRefStructAntiConstraint() + => TestExtractMethodAsync(""" using System; class Program @@ -69,8 +63,7 @@ void MyMethod1(TT tt) where TT : IDisposable, allows ref struct [|tt.Dispose();|] } } - """; - var expected = """ + """, """ using System; class Program @@ -85,14 +78,10 @@ private static void NewMethod(TT tt) where TT : IDisposable, allows ref stru tt.Dispose(); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task SelectTypeParameter() - { - var code = """ + public Task SelectTypeParameter() + => TestExtractMethodAsync(""" using System; class Program @@ -107,8 +96,7 @@ public string Method() return s; } } - """; - var expected = """ + """, """ using System; class Program @@ -129,15 +117,11 @@ private static void NewMethod(out T t, out R r, out string s) s = "hello"; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task SelectTypeOfTypeParameter() - { - var code = """ + public Task SelectTypeOfTypeParameter() + => TestExtractMethodAsync(""" using System; class Program @@ -147,8 +131,7 @@ public static Type meth(U u) return [|typeof(U)|]; } } - """; - var expected = """ + """, """ using System; class Program @@ -163,15 +146,11 @@ private static Type NewMethod() return typeof(U); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task SelectTypeParameterDataFlowOut() - { - var code = """ + public Task SelectTypeParameterDataFlowOut() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -192,8 +171,7 @@ public string Method() return t.i.ToString(); } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -220,15 +198,11 @@ private static T NewMethod() return t; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528198")] - public async Task BugFix6794() - { - var code = """ + public Task BugFix6794() + => TestExtractMethodAsync(""" using System; class Program { @@ -247,8 +221,7 @@ public C(ref int v) } } } - """; - var expected = """ + """, """ using System; class Program { @@ -272,15 +245,11 @@ public C(ref int v) } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528198")] - public async Task BugFix6794_1() - { - var code = """ + public Task BugFix6794_1() + => TestExtractMethodAsync(""" using System; class Program { @@ -298,8 +267,7 @@ public C(out int v) } } } - """; - var expected = """ + """, """ using System; class Program { @@ -322,15 +290,11 @@ public C(out int v) } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task SelectDefaultOfT() - { - var code = """ + public Task SelectDefaultOfT() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -343,8 +307,7 @@ T method() return t; } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -362,19 +325,15 @@ private static T GetT() return default(T); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); #endregion #region Operators [Fact] - public async Task SelectPostIncrementOperatorExtractWithRef() - { - var code = """ + public Task SelectPostIncrementOperatorExtractWithRef() + => TestExtractMethodAsync(""" class A { int method(int i) @@ -382,8 +341,7 @@ int method(int i) return [|i++|]; } } - """; - var expected = """ + """, """ class A { int method(int i) @@ -396,14 +354,11 @@ private static int NewMethod(ref int i) return i++; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task SelectPostIncrementOperator() - { - var code = """ + public Task SelectPostIncrementOperator() + => TestExtractMethodAsync(""" class A { int method(int i) @@ -411,8 +366,7 @@ int method(int i) return [|i++|]; } } - """; - var expected = """ + """, """ class A { int method(int i) @@ -425,14 +379,11 @@ private static int NewMethod(ref int i) return i++; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task SelectPreIncrementOperator() - { - var code = """ + public Task SelectPreIncrementOperator() + => TestExtractMethodAsync(""" class A { int method(int i) @@ -440,8 +391,7 @@ int method(int i) return [|++i|]; } } - """; - var expected = """ + """, """ class A { int method(int i) @@ -454,14 +404,11 @@ private static int NewMethod(ref int i) return ++i; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task SelectPostDecrementOperator() - { - var code = """ + public Task SelectPostDecrementOperator() + => TestExtractMethodAsync(""" class A { int method(int i) @@ -469,8 +416,7 @@ int method(int i) return [|i--|]; } } - """; - var expected = """ + """, """ class A { int method(int i) @@ -483,14 +429,11 @@ private static int NewMethod(ref int i) return i--; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task SelectPreDecrementOperator() - { - var code = """ + public Task SelectPreDecrementOperator() + => TestExtractMethodAsync(""" class A { int method(int i) @@ -498,8 +441,7 @@ int method(int i) return [|--i|]; } } - """; - var expected = """ + """, """ class A { int method(int i) @@ -512,26 +454,22 @@ private static int NewMethod(ref int i) return --i; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); #endregion #region ExpressionBodiedMembers [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/528")] - public async Task ExpressionBodiedMethod() - { - var code = """ + public Task ExpressionBodiedMethod() + => TestExtractMethodAsync(""" using System; class T { int m; int M1() => [|1|] + 2 + 3 + m; } - """; - var expected = """ + """, """ using System; class T { @@ -543,14 +481,11 @@ private static int NewMethod() return 1; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/528")] - public async Task ExpressionBodiedOperator() - { - var code = """ + public Task ExpressionBodiedOperator() + => TestExtractMethodAsync(""" using System; class Complex { @@ -562,8 +497,7 @@ private Complex Add(int b) throw new NotImplementedException(); } } - """; - var expected = """ + """, """ using System; class Complex { @@ -580,14 +514,11 @@ private Complex Add(int b) throw new NotImplementedException(); } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/528")] - public async Task ExpressionBodiedConversionOperator() - { - var code = """ + public Task ExpressionBodiedConversionOperator() + => TestExtractMethodAsync(""" using System; public struct DBBool { @@ -601,8 +532,7 @@ public struct DBBool public static implicit operator DBBool(bool x) => x ? new DBBool([|1|]) : dbFalse; } - """; - var expected = """ + """, """ using System; public struct DBBool { @@ -621,21 +551,17 @@ private static int NewMethod() return 1; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/528")] - public async Task ExpressionBodiedProperty() - { - var code = """ + public Task ExpressionBodiedProperty() + => TestExtractMethodAsync(""" using System; class T { int M1 => [|1|] + 2; } - """; - var expected = """ + """, """ using System; class T { @@ -646,22 +572,18 @@ private static int NewMethod() return 1; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/528")] - public async Task ExpressionBodiedIndexer() - { - var code = """ + public Task ExpressionBodiedIndexer() + => TestExtractMethodAsync(""" using System; class SampleCollection { private T[] arr = new T[100]; public T this[int i] => i > 0 ? arr[[|i + 1|]] : arr[i + 2]; } - """; - var expected = """ + """, """ using System; class SampleCollection { @@ -673,22 +595,18 @@ private static int NewMethod(int i) return i + 1; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/528")] - public async Task ExpressionBodiedIndexer2() - { - var code = """ + public Task ExpressionBodiedIndexer2() + => TestExtractMethodAsync(""" using System; class SampleCollection { private T[] arr = new T[100]; public T this[int i] => [|i > 0 ? arr[i + 1]|] : arr[i + 2]; } - """; - var expected = """ + """, """ using System; class SampleCollection { @@ -700,14 +618,11 @@ private T NewMethod(int i) return i > 0 ? arr[i + 1] : arr[i + 2]; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/528")] - public async Task ExpressionBodiedMethodWithBlockBodiedAnonymousMethodExpression() - { - var code = """ + public Task ExpressionBodiedMethodWithBlockBodiedAnonymousMethodExpression() + => TestExtractMethodAsync(""" using System; class TestClass { @@ -716,8 +631,7 @@ Func Y() => delegate (int x) return [|9|]; }; } - """; - var expected = """ + """, """ using System; class TestClass { @@ -731,21 +645,17 @@ private static int NewMethod() return 9; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/528")] - public async Task ExpressionBodiedMethodWithSingleLineBlockBodiedAnonymousMethodExpression() - { - var code = """ + public Task ExpressionBodiedMethodWithSingleLineBlockBodiedAnonymousMethodExpression() + => TestExtractMethodAsync(""" using System; class TestClass { Func Y() => delegate (int x) { return [|9|]; }; } - """; - var expected = """ + """, """ using System; class TestClass { @@ -756,14 +666,11 @@ private static int NewMethod() return 9; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/528")] - public async Task ExpressionBodiedMethodWithBlockBodiedSimpleLambdaExpression() - { - var code = """ + public Task ExpressionBodiedMethodWithBlockBodiedSimpleLambdaExpression() + => TestExtractMethodAsync(""" using System; class TestClass { @@ -772,8 +679,7 @@ Func Y() => f => return f * [|9|]; }; } - """; - var expected = """ + """, """ using System; class TestClass { @@ -787,21 +693,17 @@ private static int NewMethod() return 9; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/528")] - public async Task ExpressionBodiedMethodWithExpressionBodiedSimpleLambdaExpression() - { - var code = """ + public Task ExpressionBodiedMethodWithExpressionBodiedSimpleLambdaExpression() + => TestExtractMethodAsync(""" using System; class TestClass { Func Y() => f => f * [|9|]; } - """; - var expected = """ + """, """ using System; class TestClass { @@ -812,14 +714,11 @@ private static int NewMethod() return 9; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/528")] - public async Task ExpressionBodiedMethodWithBlockBodiedParenthesizedLambdaExpression() - { - var code = """ + public Task ExpressionBodiedMethodWithBlockBodiedParenthesizedLambdaExpression() + => TestExtractMethodAsync(""" using System; class TestClass { @@ -828,8 +727,7 @@ Func Y() => (f) => return f * [|9|]; }; } - """; - var expected = """ + """, """ using System; class TestClass { @@ -843,21 +741,17 @@ private static int NewMethod() return 9; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/528")] - public async Task ExpressionBodiedMethodWithExpressionBodiedParenthesizedLambdaExpression() - { - var code = """ + public Task ExpressionBodiedMethodWithExpressionBodiedParenthesizedLambdaExpression() + => TestExtractMethodAsync(""" using System; class TestClass { Func Y() => (f) => f * [|9|]; } - """; - var expected = """ + """, """ using System; class TestClass { @@ -868,14 +762,11 @@ private static int NewMethod() return 9; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/528")] - public async Task ExpressionBodiedMethodWithBlockBodiedAnonymousMethodExpressionInMethodArgs() - { - var code = """ + public Task ExpressionBodiedMethodWithBlockBodiedAnonymousMethodExpressionInMethodArgs() + => TestExtractMethodAsync(""" using System; class TestClass { @@ -889,8 +780,7 @@ private int Method1(Func p) throw new NotImplementedException(); } } - """; - var expected = """ + """, """ using System; class TestClass { @@ -909,14 +799,11 @@ private int Method1(Func p) throw new NotImplementedException(); } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/528")] - public async Task LeadingAndTrailingTriviaOnExpressionBodiedMethod() - { - var code = """ + public Task LeadingAndTrailingTriviaOnExpressionBodiedMethod() + => TestExtractMethodAsync(""" using System; class TestClass { @@ -924,8 +811,7 @@ class TestClass void Cat() { } } - """; - var expected = """ + """, """ using System; class TestClass { @@ -938,18 +824,15 @@ private static int NewMethod() void Cat() { } } - """; - await TestExtractMethodAsync(code, expected); - } + """); #endregion #region Patterns [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/9244")] - public async Task PatternIsDisabled() - { - var code = """ + public Task PatternIsDisabled() + => ExpectExtractMethodToFailAsync(""" using System; class Program { @@ -962,17 +845,13 @@ static void Main() } } } - """; - - await ExpectExtractMethodToFailAsync(code); - } + """); #endregion [Fact, WorkItem(11155, "DevDiv_Projects/Roslyn")] - public async Task AnonymousTypeMember1() - { - var code = """ + public Task AnonymousTypeMember1() + => ExpectExtractMethodToFailAsync(""" using System; class Program @@ -983,14 +862,11 @@ static void Main(string[] args) Console.Write(an.[|id|]); // here } } - """; - await ExpectExtractMethodToFailAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544259")] - public async Task ExtractMethod_ConstructorInitializer() - { - var code = """ + public Task ExtractMethod_ConstructorInitializer() + => TestExtractMethodAsync(""" class Program { public Program(string a, int b) @@ -998,8 +874,7 @@ public Program(string a, int b) { } } - """; - var expected = """ + """, """ class Program { public Program(string a, int b) @@ -1012,15 +887,11 @@ private static Program NewMethod() return new Program(); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543984")] - public async Task ExtractMethod_UnsafeAddressTaken() - { - var code = """ + public Task ExtractMethod_UnsafeAddressTaken() + => ExpectExtractMethodToFailAsync(""" class C { unsafe void M() @@ -1029,8 +900,7 @@ unsafe void M() int* j = [|&i|]; } } - """; - var expected = """ + """, """ class C { unsafe void M() @@ -1044,15 +914,11 @@ unsafe void M() return &i; } } - """; - - await ExpectExtractMethodToFailAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544387")] - public async Task ExtractMethod_PointerType() - { - var code = """ + public Task ExtractMethod_PointerType() + => TestExtractMethodAsync(""" class Test { static int x = 0; @@ -1064,8 +930,7 @@ unsafe static void Main() } } } - """; - var expected = """ + """, """ class Test { static int x = 0; @@ -1082,15 +947,11 @@ private static unsafe int GetA1(int* p1) return *p1; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544514")] - public async Task ExtractMethod_AnonymousType() - { - var code = """ + public Task ExtractMethod_AnonymousType() + => ExpectExtractMethodToFailAsync(""" public class Test { public static void Main() @@ -1101,8 +962,7 @@ public static void Main() [|p1 = p2;|] } } - """; - var expected = """ + """, """ public class Test { public static void Main() @@ -1118,15 +978,11 @@ public static void Main() return p2; } } - """; - - await ExpectExtractMethodToFailAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544920")] - public async Task ExtractMethod_StackAllocExpression() - { - var code = """ + public Task ExtractMethod_StackAllocExpression() + => TestExtractMethodAsync(""" unsafe class C { static void Main() @@ -1134,8 +990,7 @@ static void Main() void* p = [|stackalloc int[10]|]; } } - """; - var expected = """ + """, """ unsafe class C { static void Main() @@ -1148,15 +1003,11 @@ private static void NewMethod() void* p = stackalloc int[10]; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539310")] - public async Task Readonly_Field_WrittenTo() - { - var code = """ + public Task Readonly_Field_WrittenTo() + => ExpectExtractMethodToFailAsync(""" class C { private readonly int i; @@ -1166,14 +1017,11 @@ class C [|i = 1;|] } } - """; - await ExpectExtractMethodToFailAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539310")] - public async Task Readonly_Field() - { - var code = """ + public Task Readonly_Field() + => TestExtractMethodAsync(""" class C { private readonly int i; @@ -1184,8 +1032,7 @@ class C [|var x = i;|] } } - """; - var expected = """ + """, """ class C { private readonly int i; @@ -1201,14 +1048,11 @@ private void NewMethod() var x = i; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545180")] - public async Task NodeHasSyntacticErrors() - { - var code = """ + public Task NodeHasSyntacticErrors() + => ExpectExtractMethodToFailAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -1223,14 +1067,11 @@ static void Main(string[] args) }; } } - """; - await ExpectExtractMethodToFailAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545292")] - public async Task LocalConst() - { - var code = """ + public Task LocalConst() + => ExpectExtractMethodToFailAsync(""" class Test { public static void Main() @@ -1238,14 +1079,11 @@ public static void Main() const int v = [|3|]; } } - """; - await ExpectExtractMethodToFailAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545315")] - public async Task Nullable() - { - var code = """ + public Task Nullable() + => TestExtractMethodAsync(""" using System; class Program { @@ -1255,8 +1093,7 @@ static void Main() [|Console.WriteLine(q);|] } } - """; - var expected = """ + """, """ using System; class Program { @@ -1271,15 +1108,11 @@ private static void NewMethod(int? q) Console.WriteLine(q); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545263")] - public async Task SyntacticErrorInSelection() - { - var code = """ + public Task SyntacticErrorInSelection() + => ExpectExtractMethodToFailAsync(""" class Program { static void Main(string[] args) @@ -1294,14 +1127,11 @@ private static string NewMethod() return "true"; } } - """; - await ExpectExtractMethodToFailAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544497")] - public async Task StackAllocExpression() - { - var code = """ + public Task StackAllocExpression() + => TestExtractMethodAsync(""" using System; class Test { @@ -1310,8 +1140,7 @@ unsafe static void Main() void* buffer = [|stackalloc char[16]|]; } } - """; - var expected = """ + """, """ using System; class Test { @@ -1325,14 +1154,11 @@ private static unsafe void NewMethod() void* buffer = stackalloc char[16]; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545503")] - public async Task MethodBodyInScript() - { - var code = """ + public Task MethodBodyInScript() + => TestExtractMethodAsync(""" #r "System.Management" using System; using System.Collections.Generic; @@ -1355,8 +1181,7 @@ void CollectInfo(string title, string query, string[,] labelKeys) } output.AppendLine();|] } - """; - var expected = """ + """, """ #r "System.Management" using System; using System.Collections.Generic; @@ -1384,14 +1209,11 @@ void NewMethod(string query, string[,] labelKeys) } output.AppendLine(); } - """; - await TestExtractMethodAsync(code, expected, parseOptions: new CSharpParseOptions(kind: SourceCodeKind.Script)); - } + """, parseOptions: new CSharpParseOptions(kind: SourceCodeKind.Script)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544920")] - public async Task NoSimplificationForStackAlloc() - { - var code = """ + public Task NoSimplificationForStackAlloc() + => TestExtractMethodAsync(""" using System; unsafe class C @@ -1402,8 +1224,7 @@ static void Main() Console.WriteLine((int)p); } } - """; - var expected = """ + """, """ using System; unsafe class C @@ -1420,14 +1241,11 @@ static void Main() return p; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545553")] - public async Task CheckStatementContext1() - { - var code = """ + public Task CheckStatementContext1() + => TestExtractMethodAsync(""" using System; class X @@ -1445,8 +1263,7 @@ static void Main() } } } - """; - var expected = """ + """, """ using System; class X @@ -1472,14 +1289,11 @@ private static void NewMethod() } } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545553")] - public async Task CheckStatementContext2() - { - var code = """ + public Task CheckStatementContext2() + => TestExtractMethodAsync(""" using System; class X @@ -1497,8 +1311,7 @@ static void Main() }|] } } - """; - var expected = """ + """, """ using System; class X @@ -1521,14 +1334,11 @@ private static void NewMethod() } } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545553")] - public async Task CheckStatementContext3() - { - var code = """ + public Task CheckStatementContext3() + => TestExtractMethodAsync(""" using System; class X @@ -1548,8 +1358,7 @@ static void Main() } } } - """; - var expected = """ + """, """ using System; class X @@ -1575,14 +1384,11 @@ private static void NewMethod() } } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545553")] - public async Task CheckExpressionContext1() - { - var code = """ + public Task CheckExpressionContext1() + => TestExtractMethodAsync(""" using System; class X @@ -1597,8 +1403,7 @@ static void Main() var s = unchecked(1 + [|Goo(X => (byte)X.Value, null)|]); } } - """; - var expected = """ + """, """ using System; class X @@ -1618,14 +1423,11 @@ private static int NewMethod() return unchecked(Goo(X => (byte)X.Value, null)); } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task AwaitExpression_Normal_SingleStatement() - { - var code = """ + public Task AwaitExpression_Normal_SingleStatement() + => TestExtractMethodAsync(""" using System; using System.Threading.Tasks; @@ -1636,8 +1438,7 @@ public async void Test() [|await Task.Run(() => { });|] } } - """; - var expected = """ + """, """ using System; using System.Threading.Tasks; @@ -1653,14 +1454,11 @@ private static async Task NewMethod() await Task.Run(() => { }); } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task AwaitExpression_Normal_Expression() - { - var code = """ + public Task AwaitExpression_Normal_Expression() + => TestExtractMethodAsync(""" using System; using System.Threading.Tasks; @@ -1671,8 +1469,7 @@ public async void Test() [|await Task.Run(() => { })|]; } } - """; - var expected = """ + """, """ using System; using System.Threading.Tasks; @@ -1688,14 +1485,11 @@ private static async Task NewMethod() await Task.Run(() => { }); } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task AwaitExpression_Normal_MultipleStatements() - { - var code = """ + public Task AwaitExpression_Normal_MultipleStatements() + => TestExtractMethodAsync(""" using System; using System.Threading.Tasks; @@ -1710,8 +1504,7 @@ public async void Test() return;|] } } - """; - var expected = """ + """, """ using System; using System.Threading.Tasks; @@ -1731,14 +1524,11 @@ private static async Task NewMethod() return; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task AwaitExpression_Normal_ExpressionWithReturn() - { - var code = """ + public Task AwaitExpression_Normal_ExpressionWithReturn() + => TestExtractMethodAsync(""" using System; using System.Threading.Tasks; @@ -1751,8 +1541,7 @@ public async void Test() [|await Task.Run(() => 1)|]; } } - """; - var expected = """ + """, """ using System; using System.Threading.Tasks; @@ -1770,14 +1559,11 @@ private static async Task NewMethod() return await Task.Run(() => 1); } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task AwaitExpression_Normal_ExpressionInAwaitExpression() - { - var code = """ + public Task AwaitExpression_Normal_ExpressionInAwaitExpression() + => TestExtractMethodAsync(""" using System; using System.Threading.Tasks; @@ -1788,8 +1574,7 @@ public async void Test() await [|Task.Run(() => 1)|]; } } - """; - var expected = """ + """, """ using System; using System.Threading.Tasks; @@ -1805,14 +1590,11 @@ private static Task NewMethod() return Task.Run(() => 1); } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task AwaitExpression_Normal_StatementWithAwaitExpressionWithReturn() - { - var code = """ + public Task AwaitExpression_Normal_StatementWithAwaitExpressionWithReturn() + => TestExtractMethodAsync(""" using System; using System.Threading.Tasks; @@ -1823,8 +1605,7 @@ public async void Test() [|await Task.Run(() => 1);|] } } - """; - var expected = """ + """, """ using System; using System.Threading.Tasks; @@ -1840,14 +1621,11 @@ private static async Task NewMethod() await Task.Run(() => 1); } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task AwaitExpression_Normal_AwaitWithReturnParameter() - { - var code = """ + public Task AwaitExpression_Normal_AwaitWithReturnParameter() + => TestExtractMethodAsync(""" using System; using System.Threading.Tasks; @@ -1860,8 +1638,7 @@ public async void Test(int i) Console.WriteLine(i); } } - """; - var expected = """ + """, """ using System; using System.Threading.Tasks; @@ -1880,14 +1657,11 @@ private static async Task NewMethod(int i) return i; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task AwaitExpression_Normal_AwaitWithReturnParameter_Error() - { - var code = """ + public Task AwaitExpression_Normal_AwaitWithReturnParameter_Error() + => ExpectExtractMethodToFailAsync(""" using System; using System.Threading.Tasks; @@ -1900,15 +1674,11 @@ public async void Test(int i) Console.WriteLine(i); } } - """; - await ExpectExtractMethodToFailAsync(code); - } + """); [Fact] - public async Task AwaitExpression_AsyncLambda() - { - // this is an error case. but currently, I didn't blocked this. but we could if we want to. - var code = """ + public Task AwaitExpression_AsyncLambda() + => TestExtractMethodAsync(""" using System; using System.Threading.Tasks; @@ -1919,8 +1689,7 @@ public void Test(Func> a) Test([|async () => await Task.Run(() => 1)|]); } } - """; - var expected = """ + """, """ using System; using System.Threading.Tasks; @@ -1936,15 +1705,11 @@ private static Func> NewMethod() return async () => await Task.Run(() => 1); } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task AwaitExpression_AsyncLambda_Body() - { - // this is an error case. but currently, I didn't blocked this. but we could if we want to. - var code = """ + public Task AwaitExpression_AsyncLambda_Body() + => TestExtractMethodAsync(""" using System; using System.Threading.Tasks; @@ -1955,8 +1720,7 @@ public void Test(Func> a) Test(async () => [|await Task.Run(() => 1)|]); } } - """; - var expected = """ + """, """ using System; using System.Threading.Tasks; @@ -1972,15 +1736,11 @@ private static async Task NewMethod() return await Task.Run(() => 1); } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task AwaitExpression_AsyncLambda_WholeExpression() - { - // this is an error case. but currently, I didn't blocked this. but we could if we want to. - var code = """ + public Task AwaitExpression_AsyncLambda_WholeExpression() + => TestExtractMethodAsync(""" using System; using System.Threading.Tasks; @@ -1991,8 +1751,7 @@ public void Test(Func> a) [|Test(async () => await Task.Run(() => 1));|] } } - """; - var expected = """ + """, """ using System; using System.Threading.Tasks; @@ -2008,14 +1767,11 @@ private void NewMethod() Test(async () => await Task.Run(() => 1)); } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064798")] - public async Task ExpressionInStringInterpolation() - { - var code = """ + public Task ExpressionInStringInterpolation() + => TestExtractMethodAsync(""" using System; class X @@ -2025,8 +1781,7 @@ public void Test() var s = $"Alpha Beta {[|int.Parse("12345")|]} Gamma"; } } - """; - var expected = """ + """, """ using System; class X @@ -2041,14 +1796,11 @@ private static int NewMethod() return int.Parse("12345"); } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/859493")] - public async Task ExpressionInYieldReturnStatement() - { - var code = """ + public Task ExpressionInYieldReturnStatement() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; @@ -2071,8 +1823,7 @@ public IEnumerator GetEnumerator() } } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; @@ -2100,9 +1851,7 @@ private static T GetItem(Node _localCurrent) return _localCurrent._item; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/3147")] @@ -2147,9 +1896,8 @@ private static FormattableString NewMethod() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17971")] - public async Task BrokenForeachLoop() - { - var code = """ + public Task BrokenForeachLoop() + => TestExtractMethodAsync(""" using System; namespace ConsoleApp1 { @@ -2163,8 +1911,7 @@ static void Main(string[] args) } } } - """; - var expected = """ + """, """ using System; namespace ConsoleApp1 { @@ -2183,15 +1930,11 @@ private static void NewMethod() } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22150")] - public async Task ExtractMethod_LocalVariableCrossingLocalFunction() - { - var code = """ + public Task ExtractMethod_LocalVariableCrossingLocalFunction() + => TestExtractMethodAsync(""" using System; class C @@ -2203,8 +1946,7 @@ public void Test() Console.WriteLine(x);|] } } - """; - var expected = """ + """, """ using System; class C @@ -2221,15 +1963,11 @@ void Local() { } Console.WriteLine(x); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61555")] - public async Task Nullable_FlowAnalysisNotNull() - { - var code = """ + public Task Nullable_FlowAnalysisNotNull() + => TestExtractMethodAsync(""" class C { public void M(C? c) @@ -2242,9 +1980,7 @@ public void M(C? c) [|c.ToString();|] } } - """; - - var expected = """ + """, """ class C { public void M(C? c) @@ -2262,15 +1998,12 @@ private static void NewMethod(C c) c.ToString(); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39329")] public Task SimpleUsingStatement() { - var code = """ + return TestExtractMethodAsync(""" public class Goo : IDisposable { void M2() { } @@ -2290,9 +2023,7 @@ public void Dispose() throw new NotImplementedException(); } } - """; - - var expected = """ + """, """ public class Goo : IDisposable { void M2() { } @@ -2317,15 +2048,12 @@ public void Dispose() throw new NotImplementedException(); } } - """; - - return TestExtractMethodAsync(code, expected); + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24136")] - public async Task WhenClause_SwitchStatement() - { - var code = """ + public Task WhenClause_SwitchStatement() + => TestExtractMethodAsync(""" class C { void DisplayMeasurements(int a, int b) @@ -2346,9 +2074,7 @@ void DisplayMeasurements(int a, int b) } } } - """; - - var expected = """ + """, """ class C { void DisplayMeasurements(int a, int b) @@ -2374,15 +2100,11 @@ private static bool NewMethod(int a, int b) return a == b; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24136")] - public async Task WhenClause_SwitchExpression() - { - var code = """ + public Task WhenClause_SwitchExpression() + => TestExtractMethodAsync(""" class C { string GetMeasurements(int a, int b) @@ -2393,9 +2115,7 @@ string GetMeasurements(int a, int b) _ => "One or both measurements are not valid." }; } - """; - - var expected = """ + """, """ class C { string GetMeasurements(int a, int b) @@ -2411,8 +2131,5 @@ private static bool NewMethod(int a, int b) return a == b; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); } diff --git a/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodTests.cs b/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodTests.cs index a3d115d446fac..28d8ed1c1a6aa 100644 --- a/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodTests.cs +++ b/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodTests.cs @@ -24,9 +24,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ExtractMethod; public sealed partial class ExtractMethodTests : ExtractMethodBase { [Fact] - public async Task ExtractMethod1() - { - var code = """ + public Task ExtractMethod1() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -39,8 +38,7 @@ void Test(string[] args) i = 10;|] } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -57,15 +55,11 @@ private static void NewMethod() int i = 10; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod_KeywordName() - { - var code = """ + public Task ExtractMethod_KeywordName() + => TestExtractMethodAsync(""" using System; class Program @@ -79,8 +73,7 @@ void Test(string[] args) Console.WriteLine(@class + @interface); } } - """; - var expected = """ + """, """ using System; class Program @@ -99,15 +92,11 @@ private static void NewMethod(ref int @class, ref int @interface) @interface++; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod2() - { - var code = """ + public Task ExtractMethod2() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -120,8 +109,7 @@ void Test(string[] args) int i2 = 10;|] } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -139,15 +127,11 @@ private static void NewMethod() int i2 = 10; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod3() - { - var code = """ + public Task ExtractMethod3() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -160,8 +144,7 @@ void Test(string[] args) [|int i2 = i;|] } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -179,15 +162,11 @@ private static void NewMethod(int i) int i2 = i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod4() - { - var code = """ + public Task ExtractMethod4() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -202,8 +181,7 @@ void Test(string[] args) [|i2 += i;|] } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -223,16 +201,11 @@ private static int NewMethod(int i, int i2) return i2; } } - """; - - // compoundaction not supported yet. - await TestExtractMethodAsync(code, expected, temporaryFailing: true); - } + """, temporaryFailing: true); [Fact] - public async Task ExtractMethod5() - { - var code = """ + public Task ExtractMethod5() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -247,8 +220,7 @@ void Test(string[] args) [|i2 = i;|] } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -268,15 +240,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod6() - { - var code = """ + public Task ExtractMethod6() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -292,8 +260,7 @@ void Test(string[] args) [|field = i;|] } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -314,15 +281,11 @@ private void NewMethod(int i) field = i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod7() - { - var code = """ + public Task ExtractMethod7() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -336,8 +299,7 @@ void Test(string[] args) [|Test(a);|] } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -356,15 +318,11 @@ private void NewMethod(string[] a) Test(a); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod8() - { - var code = """ + public Task ExtractMethod8() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -378,8 +336,7 @@ static void Test(string[] args) [|Test(a);|] } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -398,15 +355,11 @@ private static void NewMethod(string[] a) Test(a); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod9() - { - var code = """ + public Task ExtractMethod9() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -422,8 +375,7 @@ void Test(string[] args) s = args[0] + i.ToString();|] } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -444,15 +396,11 @@ private static void NewMethod(string[] args, out int i, out string s) s = args[0] + i.ToString(); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod10() - { - var code = """ + public Task ExtractMethod10() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -471,8 +419,7 @@ void Test(string[] args) Console.WriteLine(s); } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -496,15 +443,11 @@ private static string NewMethod(string[] args) return s; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod11() - { - var code = """ + public Task ExtractMethod11() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -518,8 +461,7 @@ void Test(string[] args) i = 10; } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -538,15 +480,11 @@ private static void NewMethod() int i2 = 10; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod11_1() - { - var code = """ + public Task ExtractMethod11_1() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -559,8 +497,7 @@ void Test(string[] args) int i2 = 10;|] } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -578,15 +515,11 @@ private static void NewMethod() int i2 = 10; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod12() - { - var code = """ + public Task ExtractMethod12() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -602,8 +535,7 @@ void Test(string[] args) Console.WriteLine(i); } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -625,15 +557,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ControlVariableInForeachStatement() - { - var code = """ + public Task ControlVariableInForeachStatement() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -648,8 +576,7 @@ void Test(string[] args) } } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -669,15 +596,11 @@ private static void NewMethod(string s) Console.WriteLine(s); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod14() - { - var code = """ + public Task ExtractMethod14() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -692,8 +615,7 @@ void Test(string[] args) } } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -713,16 +635,11 @@ private static void NewMethod(int i) Console.WriteLine(i); } } - """; - - // var in for loop doesn't get bound yet - await TestExtractMethodAsync(code, expected, temporaryFailing: true); - } + """, temporaryFailing: true); [Fact] - public async Task ExtractMethod15() - { - var code = """ + public Task ExtractMethod15() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -738,8 +655,7 @@ void Test(string[] args) System.Console.WriteLine(i); } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -762,15 +678,11 @@ private static void NewMethod(out int s, out int i) int b = s + i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod16() - { - var code = """ + public Task ExtractMethod16() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -784,8 +696,7 @@ void Test(string[] args) System.Console.WriteLine(i); } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -804,15 +715,11 @@ private static int NewMethod() return 1; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538932")] - public async Task ExtractMethod17() - { - var code = """ + public Task ExtractMethod17() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -828,8 +735,7 @@ class Program System.Console.WriteLine(t1.ToString()); } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -850,15 +756,11 @@ class Program t = t1; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod18() - { - var code = """ + public Task ExtractMethod18() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -876,8 +778,7 @@ class Program return t = new T(); } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -901,15 +802,11 @@ class Program return t = new T(); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod19() - { - var code = """ + public Task ExtractMethod19() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -921,8 +818,7 @@ void Test() [|int i = 1;|] } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -939,15 +835,11 @@ private static void NewMethod() int i = 1; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod20() - { - var code = """ + public Task ExtractMethod20() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -959,8 +851,7 @@ unsafe void Test() [|int i = 1;|] } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -977,15 +868,11 @@ private static unsafe void NewMethod() int i = 1; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542677")] - public async Task ExtractMethod21() - { - var code = """ + public Task ExtractMethod21() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -1000,8 +887,7 @@ void Test() } } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -1021,15 +907,11 @@ private static unsafe void NewMethod() int i = 1; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod22() - { - var code = """ + public Task ExtractMethod22() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -1050,8 +932,7 @@ void Test() Console.WriteLine(i); } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -1079,15 +960,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod23() - { - var code = """ + public Task ExtractMethod23() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -1100,8 +977,7 @@ static void Main(string[] args) [|Console.WriteLine(args[0].ToString());|] } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -1119,15 +995,11 @@ private static void NewMethod(string[] args) Console.WriteLine(args[0].ToString()); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod24() - { - var code = """ + public Task ExtractMethod24() + => TestExtractMethodAsync(""" using System; class Program @@ -1137,8 +1009,7 @@ static void Main(string[] args) int y = [|int.Parse(args[0].ToString())|]; } } - """; - var expected = """ + """, """ using System; class Program @@ -1153,14 +1024,11 @@ private static int GetY(string[] args) return int.Parse(args[0].ToString()); } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod25() - { - var code = """ + public Task ExtractMethod25() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -1175,8 +1043,7 @@ static void Main(string[] args) } } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -1196,15 +1063,11 @@ private static int[] NewMethod() return new int[] { 1, 2, 3 }; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod26() - { - var code = """ + public Task ExtractMethod26() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -1219,8 +1082,7 @@ static void Main(string[] args) } } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -1240,15 +1102,11 @@ private static int[] NewMethod() return (new int[] { 1, 2, 3 }); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod27() - { - var code = """ + public Task ExtractMethod27() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -1269,8 +1127,7 @@ void Test() Console.WriteLine(i); } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -1298,15 +1155,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod28() - { - var code = """ + public Task ExtractMethod28() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -1318,8 +1171,7 @@ int Test() [|return 1;|] } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -1336,15 +1188,11 @@ private static int NewMethod() return 1; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod29() - { - var code = """ + public Task ExtractMethod29() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -1365,8 +1213,7 @@ int Test() }|] } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -1392,15 +1239,11 @@ private static int NewMethod(int i) } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod30() - { - var code = """ + public Task ExtractMethod30() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -1412,8 +1255,7 @@ void Test(out int i) [|i = 10;|] } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -1430,15 +1272,11 @@ private static int NewMethod() return 10; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod31() - { - var code = """ + public Task ExtractMethod31() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Text; @@ -1454,8 +1292,7 @@ void Test() return builder.ToString(); } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Text; @@ -1476,15 +1313,11 @@ private static void NewMethod(StringBuilder builder) builder.Append(" Roslyn"); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod32() - { - var code = """ + public Task ExtractMethod32() + => TestExtractMethodAsync(""" using System; class Program @@ -1495,8 +1328,7 @@ void Test() Console.Write([|v|]); } } - """; - var expected = """ + """, """ using System; class Program @@ -1512,15 +1344,11 @@ private static int GetV(int v) return v; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem(3792, "DevDiv_Projects/Roslyn")] - public async Task ExtractMethod33() - { - var code = """ + public Task ExtractMethod33() + => TestExtractMethodAsync(""" using System; class Program @@ -1534,8 +1362,7 @@ void Test() } } } - """; - var expected = """ + """, """ using System; class Program @@ -1554,17 +1381,11 @@ private static int NewMethod(ref int v) return v++; } } - """; - - // this bug has two issues. one is "v" being not in the dataFlowIn and ReadInside collection (hence no method parameter) - // and the other is binding not working for "v++" (hence object as return type) - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod34() - { - var code = """ + public Task ExtractMethod34() + => TestExtractMethodAsync(""" using System; class Program @@ -1576,8 +1397,7 @@ static void Main(string[] args) int z = [|x + y|]; } } - """; - var expected = """ + """, """ using System; class Program @@ -1594,15 +1414,11 @@ private static int GetZ(int x, int y) return x + y; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538239")] - public async Task ExtractMethod35() - { - var code = """ + public Task ExtractMethod35() + => TestExtractMethodAsync(""" using System; class Program @@ -1612,8 +1428,7 @@ static void Main(string[] args) int[] r = [|new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }|]; } } - """; - var expected = """ + """, """ using System; class Program @@ -1628,15 +1443,11 @@ private static int[] GetR() return new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod36() - { - var code = """ + public Task ExtractMethod36() + => TestExtractMethodAsync(""" using System; class Program @@ -1646,8 +1457,7 @@ static void Main(ref int i) [|i = 1;|] } } - """; - var expected = """ + """, """ using System; class Program @@ -1662,15 +1472,11 @@ private static int NewMethod() return 1; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod37() - { - var code = """ + public Task ExtractMethod37() + => TestExtractMethodAsync(""" using System; class Program @@ -1680,8 +1486,7 @@ static void Main(out int i) [|i = 1;|] } } - """; - var expected = """ + """, """ using System; class Program @@ -1696,15 +1501,11 @@ private static int NewMethod() return 1; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538231")] - public async Task ExtractMethod38() - { - var code = """ + public Task ExtractMethod38() + => TestExtractMethodAsync(""" using System; class Program @@ -1730,8 +1531,7 @@ static void Main(string[] args) // unassigned = 0; } } - """; - var expected = """ + """, """ using System; class Program @@ -1763,15 +1563,11 @@ private static int NewMethod(int unassigned) return unassigned; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538231")] - public async Task ExtractMethod39() - { - var code = """ + public Task ExtractMethod39() + => TestExtractMethodAsync(""" using System; class Program @@ -1797,8 +1593,7 @@ static void Main(string[] args) // unassigned = 0; } } - """; - var expected = """ + """, """ using System; class Program @@ -1830,18 +1625,11 @@ private static int NewMethod(int unassigned) return unassigned; } } - """; - - // current bottom-up re-writer makes re-attaching trivia half belongs to previous token - // and half belongs to next token very hard. - // for now, it won't be able to re-associate trivia belongs to next token. - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538303")] - public async Task ExtractMethod40() - { - var code = """ + public Task ExtractMethod40() + => ExpectExtractMethodToFailAsync(""" class Program { static void Main(string[] args) @@ -1849,17 +1637,11 @@ static void Main(string[] args) [|int x;|] } } - """; - await ExpectExtractMethodToFailAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/868414")] - public async Task ExtractMethodWithLeadingTrivia() - { - // ensure that the extraction doesn't result in trivia moving up a line: - // // a //b - // NewMethod(); - await TestExtractMethodAsync( + public Task ExtractMethodWithLeadingTrivia() + => TestExtractMethodAsync( """ class C { @@ -1887,12 +1669,10 @@ private static void NewMethod() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632351")] - public async Task ExtractMethodFailForTypeInFromClause() - { - var code = """ + public Task ExtractMethodFailForTypeInFromClause() + => ExpectExtractMethodToFailAsync(""" class Program { static void Main(string[] args) @@ -1900,14 +1680,11 @@ static void Main(string[] args) var z = from [|T|] x in e; } } - """; - await ExpectExtractMethodToFailAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632351")] - public async Task ExtractMethodFailForTypeInFromClause_1() - { - var code = """ + public Task ExtractMethodFailForTypeInFromClause_1() + => ExpectExtractMethodToFailAsync(""" class Program { static void Main(string[] args) @@ -1915,14 +1692,11 @@ static void Main(string[] args) var z = from [|W.T|] x in e; } } - """; - await ExpectExtractMethodToFailAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538314")] - public async Task ExtractMethod41() - { - var code = """ + public Task ExtractMethod41() + => TestExtractMethodAsync(""" class Program { static void Main(string[] args) @@ -1934,8 +1708,7 @@ static void Main(string[] args) Console.WriteLine(y); } } - """; - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -1953,14 +1726,11 @@ private static int NewMethod(int x) return y; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538327")] - public async Task ExtractMethod42() - { - var code = """ + public Task ExtractMethod42() + => TestExtractMethodAsync(""" using System; class Program @@ -1973,8 +1743,7 @@ static void Main(string[] args) Console.Write(a + b); } } - """; - var expected = """ + """, """ using System; class Program @@ -1992,15 +1761,11 @@ private static void NewMethod(out int a, out int b) b = 7; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538327")] - public async Task ExtractMethod43() - { - var code = """ + public Task ExtractMethod43() + => TestExtractMethodAsync(""" using System; class Program @@ -2020,8 +1785,7 @@ static void Main(string[] args) Console.Write(a + b); } } - """; - var expected = """ + """, """ using System; class Program @@ -2046,15 +1810,11 @@ private static void NewMethod(out int a, out int b) f = 1; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538328")] - public async Task ExtractMethod44() - { - var code = """ + public Task ExtractMethod44() + => TestExtractMethodAsync(""" using System; class Program @@ -2068,8 +1828,7 @@ static void Main(string[] args) Console.Write(a); } } - """; - var expected = """ + """, """ using System; class Program @@ -2088,15 +1847,11 @@ private static int NewMethod() return 1; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538393")] - public async Task ExtractMethod45() - { - var code = """ + public Task ExtractMethod45() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -2107,8 +1862,7 @@ static void Main(string[] args) /**/[|;|]/**/ } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -2125,15 +1879,11 @@ private static void NewMethod() ; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538393")] - public async Task ExtractMethod46() - { - var code = """ + public Task ExtractMethod46() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -2152,8 +1902,7 @@ static void Goo(ref int x) x = x + 1; } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -2178,14 +1927,11 @@ static void Goo(ref int x) x = x + 1; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538399")] - public async Task ExtractMethod47() - { - var code = """ + public Task ExtractMethod47() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -2198,8 +1944,7 @@ static void Main() [|while (true) Console.WriteLine(x);|] } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -2217,15 +1962,11 @@ private static void NewMethod(int x) while (true) Console.WriteLine(x); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538401")] - public async Task ExtractMethod48() - { - var code = """ + public Task ExtractMethod48() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -2237,8 +1978,7 @@ static void Main() int[] x = [|{ 1, 2, 3 }|]; } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -2255,15 +1995,11 @@ private static int[] GetX() return new int[] { 1, 2, 3 }; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538405")] - public async Task ExtractMethod49() - { - var code = """ + public Task ExtractMethod49() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -2274,8 +2010,7 @@ static void Goo(int GetX) int x = [|1|]; } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -2291,15 +2026,11 @@ private static int GetX1() return 1; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethodNormalProperty() - { - var code = """ + public Task ExtractMethodNormalProperty() + => TestExtractMethodAsync(""" class Class { private static string name; @@ -2313,8 +2044,7 @@ static void Goo(int i) string str = [|Class.Names|]; } } - """; - var expected = """ + """, """ class Class { private static string name; @@ -2333,15 +2063,11 @@ private static string GetStr() return Class.Names; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538932")] - public async Task ExtractMethodAutoProperty() - { - var code = """ + public Task ExtractMethodAutoProperty() + => TestExtractMethodAsync(""" class Class { public string Name { get; set; } @@ -2350,12 +2076,7 @@ static void Main() string str = new Class().[|Name|]; } } - """; - - // given span is not an expression - // selection validator should take care of this case - - var expected = """ + """, """ class Class { public string Name { get; set; } @@ -2369,15 +2090,11 @@ private static string GetStr() return new Class().Name; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538402")] - public async Task BugFix3994() - { - var code = """ + public Task BugFix3994() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -2389,8 +2106,7 @@ static void Main() byte x = [|1|]; } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -2407,15 +2123,11 @@ private static byte GetX() return 1; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538404")] - public async Task BugFix3996() - { - var code = """ + public Task BugFix3996() + => TestExtractMethodAsync(""" class A { class D : A { } @@ -2434,9 +2146,7 @@ static void Bar() } } } - """; - - var expected = """ + """, """ class A { class D : A { } @@ -2460,15 +2170,11 @@ private static B GetX() } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task InsertionPoint() - { - var code = """ + public Task InsertionPoint() + => TestExtractMethodAsync(""" class Test { void Method(string i) @@ -2480,9 +2186,7 @@ void Method(int i) { } } - """; - - var expected = """ + """, """ class Test { void Method(string i) @@ -2499,15 +2203,11 @@ void Method(int i) { } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538980")] - public async Task BugFix4757() - { - var code = """ + public Task BugFix4757() + => TestExtractMethodAsync(""" class GenericMethod { void Method(T t) @@ -2516,9 +2216,7 @@ void Method(T t) [|a = t;|] } } - """; - - var expected = """ + """, """ class GenericMethod { void Method(T t) @@ -2532,15 +2230,11 @@ private static T NewMethod(T t) return t; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538980")] - public async Task BugFix4757_2() - { - var code = """ + public Task BugFix4757_2() + => TestExtractMethodAsync(""" class GenericMethod { void Method(T t) @@ -2551,9 +2245,7 @@ void Method(T t) b = default(T1);|] } } - """; - - var expected = """ + """, """ class GenericMethod { void Method(T t) @@ -2569,15 +2261,11 @@ private static void NewMethod(T t, out T a, out T1 b) b = default(T1); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538980")] - public async Task BugFix4757_3() - { - var code = """ + public Task BugFix4757_3() + => TestExtractMethodAsync(""" class GenericMethod { void Method(T t) @@ -2588,9 +2276,7 @@ void Method(T t) a1 = default(T);|] } } - """; - - var expected = """ + """, """ class GenericMethod { void Method(T t) @@ -2606,15 +2292,11 @@ private static void NewMethod(T t, out T1 a1, out T a) a1 = default(T); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538422")] - public async Task BugFix4758() - { - var code = """ + public Task BugFix4758() + => TestExtractMethodAsync(""" using System; class TestOutParameter { @@ -2624,9 +2306,7 @@ void Method(out int x) Console.Write([|x|]); } } - """; - - var expected = """ + """, """ using System; class TestOutParameter { @@ -2641,15 +2321,11 @@ private static int GetX(int x) return x; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538422")] - public async Task BugFix4758_2() - { - var code = """ + public Task BugFix4758_2() + => TestExtractMethodAsync(""" class TestOutParameter { void Method(out int x) @@ -2658,9 +2334,7 @@ void Method(out int x) Console.Write([|x|]); } } - """; - - var expected = """ + """, """ class TestOutParameter { void Method(out int x) @@ -2674,15 +2348,11 @@ private static int GetX(int x) return x; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538984")] - public async Task BugFix4761() - { - var code = """ + public Task BugFix4761() + => TestExtractMethodAsync(""" using System; class A @@ -2692,9 +2362,7 @@ void Method() System.Func a = x => [|x * x|]; } } - """; - - var expected = """ + """, """ using System; class A @@ -2709,15 +2377,11 @@ private static int NewMethod(int x) return x * x; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538997")] - public async Task BugFix4779() - { - var code = """ + public Task BugFix4779() + => TestExtractMethodAsync(""" using System; class Program @@ -2728,9 +2392,7 @@ static void Main() Func f = [|s|].ToString; } } - """; - - var expected = """ + """, """ using System; class Program @@ -2746,15 +2408,11 @@ private static string GetS(string s) return s; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538997")] - public async Task BugFix4779_2() - { - var code = """ + public Task BugFix4779_2() + => TestExtractMethodAsync(""" using System; class Program @@ -2765,9 +2423,7 @@ static void Main() var f = [|s|].ToString(); } } - """; - - var expected = """ + """, """ using System; class Program @@ -2783,15 +2439,11 @@ private static string GetS(string s) return s; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem(4780, "DevDiv_Projects/Roslyn")] - public async Task BugFix4780() - { - var code = """ + public Task BugFix4780() + => TestExtractMethodAsync(""" using System; class Program @@ -2802,9 +2454,7 @@ static void Main() object f = (Func)[|s.ToString|]; } } - """; - - var expected = """ + """, """ using System; class Program @@ -2820,15 +2470,11 @@ private static Func GetToString(string s) return s.ToString; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem(4780, "DevDiv_Projects/Roslyn")] - public async Task BugFix4780_2() - { - var code = """ + public Task BugFix4780_2() + => TestExtractMethodAsync(""" using System; class Program @@ -2839,9 +2485,7 @@ static void Main() object f = (string)[|s.ToString()|]; } } - """; - - var expected = """ + """, """ using System; class Program @@ -2857,15 +2501,11 @@ private static string NewMethod(string s) return s.ToString(); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem(4782, "DevDiv_Projects/Roslyn")] - public async Task BugFix4782() - { - var code = """ + public Task BugFix4782() + => TestExtractMethodAsync(""" class A { class D : A { } @@ -2879,9 +2519,7 @@ static void Goo(T a) } } } - """; - - var expected = """ + """, """ class A { class D : A { } @@ -2900,14 +2538,11 @@ private static T GetT() } } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem(4782, "DevDiv_Projects/Roslyn")] - public async Task BugFix4782_2() - { - var code = """ + public Task BugFix4782_2() + => ExpectExtractMethodToFailAsync(""" class A { class D : A { } @@ -2921,15 +2556,11 @@ static void Goo() } } } - """; - - await ExpectExtractMethodToFailAsync(code); - } + """); [Fact, WorkItem(4791, "DevDiv_Projects/Roslyn")] - public async Task BugFix4791() - { - var code = """ + public Task BugFix4791() + => TestExtractMethodAsync(""" class Program { delegate int Func(int a); @@ -2939,9 +2570,7 @@ static void Main(string[] args) Func v = (int a) => [|a|]; } } - """; - - var expected = """ + """, """ class Program { delegate int Func(int a); @@ -2956,15 +2585,11 @@ private static int GetA(int a) return a; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539019")] - public async Task BugFix4809() - { - var code = """ + public Task BugFix4809() + => TestExtractMethodAsync(""" class Program { public Program() @@ -2972,9 +2597,7 @@ public Program() [|int x = 2;|] } } - """; - - var expected = """ + """, """ class Program { public Program() @@ -2987,15 +2610,11 @@ private static void NewMethod() int x = 2; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539029")] - public async Task BugFix4813() - { - var code = """ + public Task BugFix4813() + => TestExtractMethodAsync(""" using System; class Program @@ -3005,9 +2624,7 @@ public Program() object o = [|new Program()|]; } } - """; - - var expected = """ + """, """ using System; class Program @@ -3022,15 +2639,11 @@ private static Program GetO() return new Program(); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538425")] - public async Task BugFix4031() - { - var code = """ + public Task BugFix4031() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -3045,9 +2658,7 @@ static void Main() [|while (z) { }|] } } - """; - - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -3067,15 +2678,11 @@ private static void NewMethod(bool z) while (z) { } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527499")] - public async Task BugFix3992() - { - var code = """ + public Task BugFix3992() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -3087,9 +2694,7 @@ static void Main() [|while (false) Console.WriteLine(x);|] } } - """; - - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -3106,14 +2711,11 @@ private static void NewMethod(int x) while (false) Console.WriteLine(x); } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539029")] - public async Task BugFix4823() - { - var code = """ + public Task BugFix4823() + => TestExtractMethodAsync(""" class Program { private double area = 1.0; @@ -3129,9 +2731,7 @@ public override string ToString() return string.Format("{0:F2}", [|Area|]); } } - """; - - var expected = """ + """, """ class Program { private double area = 1.0; @@ -3152,15 +2752,11 @@ private double GetArea() return Area; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538985")] - public async Task BugFix4762() - { - var code = """ + public Task BugFix4762() + => TestExtractMethodAsync(""" class Program { static void Main(string[] args) @@ -3169,9 +2765,7 @@ static void Main(string[] args) [|int x = 2;|] } } - """; - - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -3185,15 +2779,11 @@ private static void NewMethod() int x = 2; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538966")] - public async Task BugFix4744() - { - var code = """ + public Task BugFix4744() + => TestExtractMethodAsync(""" class Program { static void Main(string[] args) @@ -3202,9 +2792,7 @@ static void Main(string[] args) //comments|] } } - """; - - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -3218,15 +2806,11 @@ private static void NewMethod() //comments } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoNoNoNoYesNoNo() - { - var code = """ + public Task MatrixCase_NoNoNoNoNoYesNoNo() + => TestExtractMethodAsync(""" using System; class Program @@ -3243,9 +2827,7 @@ void Test1() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -3267,15 +2849,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoNoNoNoYesNoYes() - { - var code = """ + public Task MatrixCase_NoNoNoNoNoYesNoYes() + => TestExtractMethodAsync(""" using System; class Program @@ -3292,9 +2870,7 @@ void Test2() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -3316,15 +2892,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoNoNoNoYesYesNo() - { - var code = """ + public Task MatrixCase_NoNoNoNoNoYesYesNo() + => TestExtractMethodAsync(""" using System; class Program @@ -3343,9 +2915,7 @@ void Test3() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -3369,15 +2939,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoNoNoNoYesYesYes() - { - var code = """ + public Task MatrixCase_NoNoNoNoNoYesYesYes() + => TestExtractMethodAsync(""" using System; class Program @@ -3396,9 +2962,7 @@ void Test4() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -3422,15 +2986,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoNoNoYesYesNoNo() - { - var code = """ + public Task MatrixCase_NoNoNoNoYesYesNoNo() + => TestExtractMethodAsync(""" using System; class Program @@ -3448,9 +3008,7 @@ void Test4_1() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -3474,15 +3032,11 @@ private static int NewMethod() return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoNoNoYesYesNoYes() - { - var code = """ + public Task MatrixCase_NoNoNoNoYesYesNoYes() + => TestExtractMethodAsync(""" using System; class Program @@ -3500,9 +3054,7 @@ void Test4_2() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -3525,15 +3077,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoNoNoYesYesYesNo() - { - var code = """ + public Task MatrixCase_NoNoNoNoYesYesYesNo() + => TestExtractMethodAsync(""" using System; class Program @@ -3553,9 +3101,7 @@ void Test4_3() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -3581,15 +3127,11 @@ private static int NewMethod() return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoNoNoYesYesYesYes() - { - var code = """ + public Task MatrixCase_NoNoNoNoYesYesYesYes() + => TestExtractMethodAsync(""" using System; class Program @@ -3609,9 +3151,7 @@ void Test4_4() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -3636,15 +3176,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoNoYesNoNoNoNo() - { - var code = """ + public Task MatrixCase_NoNoNoYesNoNoNoNo() + => ExpectExtractMethodToFailAsync(""" using System; class Program @@ -3656,15 +3192,11 @@ void Test5() |] } } - """; - - await ExpectExtractMethodToFailAsync(code); - } + """); [Fact] - public async Task MatrixCase_NoNoNoYesNoNoNoYes() - { - var code = """ + public Task MatrixCase_NoNoNoYesNoNoNoYes() + => ExpectExtractMethodToFailAsync(""" using System; class Program @@ -3678,15 +3210,11 @@ void Test6() i = 1; } } - """; - - await ExpectExtractMethodToFailAsync(code); - } + """); [Fact] - public async Task MatrixCase_NoNoNoYesNoYesNoNo() - { - var code = """ + public Task MatrixCase_NoNoNoYesNoYesNoNo() + => TestExtractMethodAsync(""" using System; class Program @@ -3703,9 +3231,7 @@ void Test7() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -3725,15 +3251,11 @@ private static void NewMethod() } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoNoYesNoYesNoYes() - { - var code = """ + public Task MatrixCase_NoNoNoYesNoYesNoYes() + => TestExtractMethodAsync(""" using System; class Program @@ -3752,9 +3274,7 @@ void Test8() i = 2; } } - """; - - var expected = """ + """, """ using System; class Program @@ -3778,15 +3298,11 @@ private static int NewMethod() return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoNoYesYesNoNoNo() - { - var code = """ + public Task MatrixCase_NoNoNoYesYesNoNoNo() + => TestExtractMethodAsync(""" using System; class Program @@ -3800,9 +3316,7 @@ void Test9() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -3819,15 +3333,11 @@ private static void NewMethod() Console.WriteLine(i); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoNoYesYesNoNoYes() - { - var code = """ + public Task MatrixCase_NoNoNoYesYesNoNoYes() + => TestExtractMethodAsync(""" using System; class Program @@ -3843,9 +3353,7 @@ void Test10() i = 10; } } - """; - - var expected = """ + """, """ using System; class Program @@ -3865,15 +3373,11 @@ private static void NewMethod() Console.WriteLine(i); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoNoYesYesYesNoNo() - { - var code = """ + public Task MatrixCase_NoNoNoYesYesYesNoNo() + => TestExtractMethodAsync(""" using System; class Program @@ -3892,9 +3396,7 @@ void Test11() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -3916,15 +3418,11 @@ private static void NewMethod() Console.WriteLine(i); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoNoYesYesYesNoYes() - { - var code = """ + public Task MatrixCase_NoNoNoYesYesYesNoYes() + => TestExtractMethodAsync(""" using System; class Program @@ -3945,9 +3443,7 @@ void Test12() i = 10; } } - """; - - var expected = """ + """, """ using System; class Program @@ -3972,15 +3468,11 @@ private static int NewMethod() return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoYesNoNoYesNoNo() - { - var code = """ + public Task MatrixCase_NoNoYesNoNoYesNoNo() + => TestExtractMethodAsync(""" using System; class Program @@ -3994,9 +3486,7 @@ void Test13() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -4013,15 +3503,11 @@ private static int NewMethod() return 10; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoYesNoNoYesNoYes() - { - var code = """ + public Task MatrixCase_NoNoYesNoNoYesNoYes() + => TestExtractMethodAsync(""" using System; class Program @@ -4037,9 +3523,7 @@ void Test14() i = 1; } } - """; - - var expected = """ + """, """ using System; class Program @@ -4058,15 +3542,11 @@ private static int NewMethod() return 10; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoYesNoNoYesYesNo() - { - var code = """ + public Task MatrixCase_NoNoYesNoNoYesYesNo() + => TestExtractMethodAsync(""" using System; class Program @@ -4082,9 +3562,7 @@ void Test15() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -4103,15 +3581,11 @@ private static int NewMethod() return 10; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoYesNoNoYesYesYes() - { - var code = """ + public Task MatrixCase_NoNoYesNoNoYesYesYes() + => TestExtractMethodAsync(""" using System; class Program @@ -4129,9 +3603,7 @@ void Test16() Console.WriteLine(i); } } - """; - - var expected = """ + """, """ using System; class Program @@ -4152,18 +3624,14 @@ private static int NewMethod() return 10; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); // dataflow in and out can be false for symbols in unreachable code // boolean indicates // dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: false, readOutside: false, writtenOutside: true [Fact] - public async Task MatrixCase_NoNoYesNoYesNoNoYes() - { - var code = """ + public Task MatrixCase_NoNoYesNoYesNoNoYes() + => TestExtractMethodAsync(""" using System.Collections.Generic; using System.Linq; @@ -4179,9 +3647,7 @@ IEnumerable Crash0(IEnumerable enumerable) } } } - """; - - var expected = """ + """, """ using System.Collections.Generic; using System.Linq; @@ -4202,18 +3668,14 @@ private static IEnumerable NewMethod(IEnumerable enumerable) } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); // dataflow in and out can be false for symbols in unreachable code // boolean indicates // dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: false, readOutside: true, writtenOutside: true [Fact] - public async Task MatrixCase_NoNoYesNoYesNoYesYes() - { - var code = """ + public Task MatrixCase_NoNoYesNoYesNoYesYes() + => TestExtractMethodAsync(""" using System.Collections.Generic; using System.Linq; @@ -4229,9 +3691,7 @@ IEnumerable Crash0(IEnumerable enumerable) } } } - """; - - var expected = """ + """, """ using System.Collections.Generic; using System.Linq; @@ -4253,15 +3713,11 @@ private static IEnumerable NewMethod(IEnumerable enumerable) } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoYesNoYesYesNoNo() - { - var code = """ + public Task MatrixCase_NoNoYesNoYesYesNoNo() + => TestExtractMethodAsync(""" using System; class Program @@ -4276,9 +3732,7 @@ void Test16_1() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -4297,15 +3751,11 @@ private static int NewMethod() return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoYesNoYesYesNoYes() - { - var code = """ + public Task MatrixCase_NoNoYesNoYesYesNoYes() + => TestExtractMethodAsync(""" using System; class Program @@ -4320,9 +3770,7 @@ void Test16_2() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -4341,15 +3789,11 @@ private static int NewMethod() return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoYesNoYesYesYesNo() - { - var code = """ + public Task MatrixCase_NoNoYesNoYesYesYesNo() + => TestExtractMethodAsync(""" using System; class Program @@ -4366,9 +3810,7 @@ void Test16_3() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -4389,15 +3831,11 @@ private static int NewMethod() return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoYesNoYesYesYesYes() - { - var code = """ + public Task MatrixCase_NoNoYesNoYesYesYesYes() + => TestExtractMethodAsync(""" using System; class Program @@ -4414,9 +3852,7 @@ void Test16_4() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -4437,15 +3873,11 @@ private static int NewMethod() return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoYesYesNoYesNoNo() - { - var code = """ + public Task MatrixCase_NoNoYesYesNoYesNoNo() + => TestExtractMethodAsync(""" using System; class Program @@ -4457,9 +3889,7 @@ void Test17() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -4474,15 +3904,11 @@ private static void NewMethod() int i = 10; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoYesYesNoYesNoYes() - { - var code = """ + public Task MatrixCase_NoNoYesYesNoYesNoYes() + => TestExtractMethodAsync(""" using System; class Program @@ -4496,9 +3922,7 @@ void Test18() i = 10; } } - """; - - var expected = """ + """, """ using System; class Program @@ -4515,15 +3939,11 @@ private static int NewMethod() return 10; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoYesYesYesYesNoNo() - { - var code = """ + public Task MatrixCase_NoNoYesYesYesYesNoNo() + => TestExtractMethodAsync(""" using System; class Program @@ -4536,9 +3956,7 @@ void Test19() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -4554,15 +3972,11 @@ private static void NewMethod() Console.WriteLine(i); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoNoYesYesYesYesNoYes() - { - var code = """ + public Task MatrixCase_NoNoYesYesYesYesNoYes() + => TestExtractMethodAsync(""" using System; class Program @@ -4577,9 +3991,7 @@ void Test20() i = 10; } } - """; - - var expected = """ + """, """ using System; class Program @@ -4598,15 +4010,11 @@ private static void NewMethod() Console.WriteLine(i); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoYesNoNoNoYesYesNo() - { - var code = """ + public Task MatrixCase_NoYesNoNoNoYesYesNo() + => TestExtractMethodAsync(""" using System; class Program @@ -4625,9 +4033,7 @@ void Test21() Console.WriteLine(i); } } - """; - - var expected = """ + """, """ using System; class Program @@ -4651,15 +4057,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoYesNoNoNoYesYesYes() - { - var code = """ + public Task MatrixCase_NoYesNoNoNoYesYesYes() + => TestExtractMethodAsync(""" using System; class Program @@ -4678,9 +4080,7 @@ void Test22() Console.WriteLine(i); } } - """; - - var expected = """ + """, """ using System; class Program @@ -4704,15 +4104,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoYesNoNoYesYesYesNo() - { - var code = """ + public Task MatrixCase_NoYesNoNoYesYesYesNo() + => TestExtractMethodAsync(""" using System; class Program @@ -4732,9 +4128,7 @@ void Test22_1() Console.WriteLine(i); } } - """; - - var expected = """ + """, """ using System; class Program @@ -4759,15 +4153,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoYesNoNoYesYesYesYes() - { - var code = """ + public Task MatrixCase_NoYesNoNoYesYesYesYes() + => TestExtractMethodAsync(""" using System; class Program @@ -4787,9 +4177,7 @@ void Test22_2() Console.WriteLine(i); } } - """; - - var expected = """ + """, """ using System; class Program @@ -4814,15 +4202,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoYesNoYesNoNoYesNo() - { - var code = """ + public Task MatrixCase_NoYesNoYesNoNoYesNo() + => ExpectExtractMethodToFailAsync(""" using System; class Program @@ -4836,15 +4220,11 @@ void Test23() Console.WriteLine(i); } } - """; - - await ExpectExtractMethodToFailAsync(code); - } + """); [Fact] - public async Task MatrixCase_NoYesNoYesNoNoYesYes() - { - var code = """ + public Task MatrixCase_NoYesNoYesNoNoYesYes() + => ExpectExtractMethodToFailAsync(""" using System; class Program @@ -4860,15 +4240,11 @@ void Test24() i = 10; } } - """; - - await ExpectExtractMethodToFailAsync(code); - } + """); [Fact] - public async Task MatrixCase_NoYesNoYesNoYesYesNo() - { - var code = """ + public Task MatrixCase_NoYesNoYesNoYesYesNo() + => TestExtractMethodAsync(""" using System; class Program @@ -4887,9 +4263,7 @@ void Test25() Console.WriteLine(i); } } - """; - - var expected = """ + """, """ using System; class Program @@ -4913,15 +4287,11 @@ private static int NewMethod() return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoYesNoYesNoYesYesYes() - { - var code = """ + public Task MatrixCase_NoYesNoYesNoYesYesYes() + => TestExtractMethodAsync(""" using System; class Program @@ -4942,9 +4312,7 @@ void Test26() i = 10; } } - """; - - var expected = """ + """, """ using System; class Program @@ -4970,15 +4338,11 @@ private static int NewMethod() return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoYesNoYesYesNoYesNo() - { - var code = """ + public Task MatrixCase_NoYesNoYesYesNoYesNo() + => TestExtractMethodAsync(""" using System; class Program @@ -4994,9 +4358,7 @@ void Test27() Console.WriteLine(i); } } - """; - - var expected = """ + """, """ using System; class Program @@ -5016,15 +4378,11 @@ private static int NewMethod() return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoYesNoYesYesNoYesYes() - { - var code = """ + public Task MatrixCase_NoYesNoYesYesNoYesYes() + => TestExtractMethodAsync(""" using System; class Program @@ -5042,9 +4400,7 @@ void Test28() i = 10; } } - """; - - var expected = """ + """, """ using System; class Program @@ -5066,15 +4422,11 @@ private static int NewMethod() return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoYesNoYesYesYesYesNo() - { - var code = """ + public Task MatrixCase_NoYesNoYesYesYesYesNo() + => TestExtractMethodAsync(""" using System; class Program @@ -5095,9 +4447,7 @@ void Test29() Console.WriteLine(i); } } - """; - - var expected = """ + """, """ using System; class Program @@ -5122,15 +4472,11 @@ private static int NewMethod() return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoYesNoYesYesYesYesYes() - { - var code = """ + public Task MatrixCase_NoYesNoYesYesYesYesYes() + => TestExtractMethodAsync(""" using System; class Program @@ -5153,9 +4499,7 @@ void Test30() i = 10; } } - """; - - var expected = """ + """, """ using System; class Program @@ -5182,15 +4526,11 @@ private static int NewMethod() return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoYesYesNoNoYesYesNo() - { - var code = """ + public Task MatrixCase_NoYesYesNoNoYesYesNo() + => TestExtractMethodAsync(""" using System; class Program @@ -5206,9 +4546,7 @@ void Test31() Console.WriteLine(i); } } - """; - - var expected = """ + """, """ using System; class Program @@ -5227,15 +4565,11 @@ private static int NewMethod() return 10; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoYesYesNoNoYesYesYes() - { - var code = """ + public Task MatrixCase_NoYesYesNoNoYesYesYes() + => TestExtractMethodAsync(""" using System; class Program @@ -5253,9 +4587,7 @@ void Test32() i = 10; } } - """; - - var expected = """ + """, """ using System; class Program @@ -5276,15 +4608,11 @@ private static int NewMethod() return 10; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoYesYesNoYesYesYesNo() - { - var code = """ + public Task MatrixCase_NoYesYesNoYesYesYesNo() + => TestExtractMethodAsync(""" using System; class Program @@ -5301,9 +4629,7 @@ void Test32_1() Console.WriteLine(i); } } - """; - - var expected = """ + """, """ using System; class Program @@ -5324,15 +4650,11 @@ private static int NewMethod() return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoYesYesNoYesYesYesYes() - { - var code = """ + public Task MatrixCase_NoYesYesNoYesYesYesYes() + => TestExtractMethodAsync(""" using System; class Program @@ -5349,9 +4671,7 @@ void Test32_2() Console.WriteLine(i); } } - """; - - var expected = """ + """, """ using System; class Program @@ -5372,15 +4692,11 @@ private static int NewMethod() return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoYesYesYesNoYesYesNo() - { - var code = """ + public Task MatrixCase_NoYesYesYesNoYesYesNo() + => TestExtractMethodAsync(""" using System; class Program @@ -5394,9 +4710,7 @@ void Test33() Console.WriteLine(i); } } - """; - - var expected = """ + """, """ using System; class Program @@ -5413,15 +4727,11 @@ private static int NewMethod() return 10; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoYesYesYesNoYesYesYes() - { - var code = """ + public Task MatrixCase_NoYesYesYesNoYesYesYes() + => TestExtractMethodAsync(""" using System; class Program @@ -5437,9 +4747,7 @@ void Test34() i = 10; } } - """; - - var expected = """ + """, """ using System; class Program @@ -5458,15 +4766,11 @@ private static int NewMethod() return 10; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoYesYesYesYesYesYesNo() - { - var code = """ + public Task MatrixCase_NoYesYesYesYesYesYesNo() + => TestExtractMethodAsync(""" using System; class Program @@ -5482,9 +4786,7 @@ void Test35() Console.WriteLine(i); } } - """; - - var expected = """ + """, """ using System; class Program @@ -5504,15 +4806,11 @@ private static int NewMethod() return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_NoYesYesYesYesYesYesYes() - { - var code = """ + public Task MatrixCase_NoYesYesYesYesYesYesYes() + => TestExtractMethodAsync(""" using System; class Program @@ -5530,9 +4828,7 @@ void Test36() i = 10; } } - """; - - var expected = """ + """, """ using System; class Program @@ -5554,15 +4850,11 @@ private static int NewMethod() return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_YesNoNoNoYesNoNoNo() - { - var code = """ + public Task MatrixCase_YesNoNoNoYesNoNoNo() + => TestExtractMethodAsync(""" using System; class Program @@ -5576,9 +4868,7 @@ void Test37() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -5595,15 +4885,11 @@ private static void NewMethod(int i) Console.WriteLine(i); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_YesNoNoNoYesNoNoYes() - { - var code = """ + public Task MatrixCase_YesNoNoNoYesNoNoYes() + => TestExtractMethodAsync(""" using System; class Program @@ -5617,9 +4903,7 @@ void Test38() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -5636,15 +4920,11 @@ private static void NewMethod(int i) Console.WriteLine(i); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_YesNoNoNoYesNoYesNo() - { - var code = """ + public Task MatrixCase_YesNoNoNoYesNoYesNo() + => TestExtractMethodAsync(""" using System; class Program @@ -5660,9 +4940,7 @@ void Test39() Console.WriteLine(i); } } - """; - - var expected = """ + """, """ using System; class Program @@ -5681,15 +4959,11 @@ private static void NewMethod(int i) Console.WriteLine(i); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_YesNoNoNoYesNoYesYes() - { - var code = """ + public Task MatrixCase_YesNoNoNoYesNoYesYes() + => TestExtractMethodAsync(""" using System; class Program @@ -5705,9 +4979,7 @@ void Test40() Console.WriteLine(i); } } - """; - - var expected = """ + """, """ using System; class Program @@ -5726,15 +4998,11 @@ private static void NewMethod(int i) Console.WriteLine(i); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_YesNoNoNoYesYesNoNo() - { - var code = """ + public Task MatrixCase_YesNoNoNoYesYesNoNo() + => TestExtractMethodAsync(""" using System; class Program @@ -5753,9 +5021,7 @@ void Test41() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -5779,15 +5045,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_YesNoNoNoYesYesNoYes() - { - var code = """ + public Task MatrixCase_YesNoNoNoYesYesNoYes() + => TestExtractMethodAsync(""" using System; class Program @@ -5806,9 +5068,7 @@ void Test42() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -5832,15 +5092,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_YesNoNoNoYesYesYesNo() - { - var code = """ + public Task MatrixCase_YesNoNoNoYesYesYesNo() + => TestExtractMethodAsync(""" using System; class Program @@ -5861,9 +5117,7 @@ void Test43() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -5889,15 +5143,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_YesNoNoNoYesYesYesYes() - { - var code = """ + public Task MatrixCase_YesNoNoNoYesYesYesYes() + => TestExtractMethodAsync(""" using System; class Program @@ -5918,9 +5168,7 @@ void Test44() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -5946,15 +5194,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_YesNoYesNoYesYesNoNo() - { - var code = """ + public Task MatrixCase_YesNoYesNoYesYesNoNo() + => TestExtractMethodAsync(""" using System; class Program @@ -5970,9 +5214,7 @@ void Test45() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -5992,15 +5234,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_YesNoYesNoYesYesNoYes() - { - var code = """ + public Task MatrixCase_YesNoYesNoYesYesNoYes() + => TestExtractMethodAsync(""" using System; class Program @@ -6016,9 +5254,7 @@ void Test46() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -6038,15 +5274,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_YesNoYesNoYesYesYesNo() - { - var code = """ + public Task MatrixCase_YesNoYesNoYesYesYesNo() + => TestExtractMethodAsync(""" using System; class Program @@ -6064,9 +5296,7 @@ void Test47() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -6088,15 +5318,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_YesNoYesNoYesYesYesYes() - { - var code = """ + public Task MatrixCase_YesNoYesNoYesYesYesYes() + => TestExtractMethodAsync(""" using System; class Program @@ -6114,9 +5340,7 @@ void Test48() |] } } - """; - - var expected = """ + """, """ using System; class Program @@ -6138,15 +5362,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_YesYesNoNoYesYesYesNo() - { - var code = """ + public Task MatrixCase_YesYesNoNoYesYesYesNo() + => TestExtractMethodAsync(""" using System; class Program @@ -6167,9 +5387,7 @@ void Test49() Console.WriteLine(i); } } - """; - - var expected = """ + """, """ using System; class Program @@ -6195,15 +5413,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_YesYesNoNoYesYesYesYes() - { - var code = """ + public Task MatrixCase_YesYesNoNoYesYesYesYes() + => TestExtractMethodAsync(""" using System; class Program @@ -6224,9 +5438,7 @@ void Test50() Console.WriteLine(i); } } - """; - - var expected = """ + """, """ using System; class Program @@ -6252,15 +5464,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_YesYesYesNoYesYesYesNo() - { - var code = """ + public Task MatrixCase_YesYesYesNoYesYesYesNo() + => TestExtractMethodAsync(""" using System; class Program @@ -6278,9 +5486,7 @@ void Test51() Console.WriteLine(i); } } - """; - - var expected = """ + """, """ using System; class Program @@ -6302,15 +5508,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task MatrixCase_YesYesYesNoYesYesYesYes() - { - var code = """ + public Task MatrixCase_YesYesYesNoYesYesYesYes() + => TestExtractMethodAsync(""" using System; class Program @@ -6328,9 +5530,7 @@ void Test52() Console.WriteLine(i); } } - """; - - var expected = """ + """, """ using System; class Program @@ -6352,15 +5552,11 @@ private static int NewMethod(int i) return i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539049")] - public async Task ExtractMethodInProperty1() - { - var code = """ + public Task ExtractMethodInProperty1() + => TestExtractMethodAsync(""" class C2 { static public int Area @@ -6379,9 +5575,7 @@ public static int Area } } } - """; - - var expected = """ + """, """ class C2 { static public int Area @@ -6405,15 +5599,11 @@ private static int GetArea() return C2.Area; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539049")] - public async Task ExtractMethodInProperty2() - { - var code = """ + public Task ExtractMethodInProperty2() + => TestExtractMethodAsync(""" class C3 { public static int Area @@ -6425,9 +5615,7 @@ public static int Area } } } - """; - - var expected = """ + """, """ class C3 { public static int Area @@ -6443,15 +5631,11 @@ private static int NewMethod() return 10; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539049")] - public async Task ExtractMethodInProperty3() - { - var code = """ + public Task ExtractMethodInProperty3() + => TestExtractMethodAsync(""" class C3 { public static int Area @@ -6462,9 +5646,7 @@ public static int Area } } } - """; - - var expected = """ + """, """ class C3 { public static int Area @@ -6480,15 +5662,11 @@ private static void NewMethod(int value) int i = value; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539029")] - public async Task ExtractMethodProperty() - { - var code = """ + public Task ExtractMethodProperty() + => TestExtractMethodAsync(""" class Program { private double area = 1.0; @@ -6505,9 +5683,7 @@ public override string ToString() return string.Format("{0:F2}", [|Area|]); } } - """; - - var expected = """ + """, """ class Program { private double area = 1.0; @@ -6529,14 +5705,11 @@ private double GetArea() return Area; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539196")] - public async Task ExtractMethodWithDeclareOneMoreVariablesInSameLineBeUsedAfter() - { - var code = """ + public Task ExtractMethodWithDeclareOneMoreVariablesInSameLineBeUsedAfter() + => TestExtractMethodAsync(""" class C { void M() @@ -6546,8 +5719,7 @@ void M() Console.Write(x + y); } } - """; - var expected = """ + """, """ class C { void M() @@ -6563,14 +5735,11 @@ private static int NewMethod() return 1; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539196")] - public async Task ExtractMethodWithDeclareOneMoreVariablesInSameLineNotBeUsedAfter() - { - var code = """ + public Task ExtractMethodWithDeclareOneMoreVariablesInSameLineNotBeUsedAfter() + => TestExtractMethodAsync(""" class C { void M() @@ -6578,8 +5747,7 @@ void M() [|int x, y = 1;|] } } - """; - var expected = """ + """, """ class C { void M() @@ -6592,14 +5760,11 @@ private static void NewMethod() int x, y = 1; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539214")] - public async Task ExtractMethodForSplitOutStatementWithComments() - { - var code = """ + public Task ExtractMethodForSplitOutStatementWithComments() + => TestExtractMethodAsync(""" class C { void M() @@ -6612,8 +5777,7 @@ void M() Console.Write(x + y); } } - """; - var expected = """ + """, """ class C { void M() @@ -6631,14 +5795,11 @@ private static void NewMethod(out int x, out int y) y = 10; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539225")] - public async Task Bug5098() - { - var code = """ + public Task Bug5098() + => ExpectExtractMethodToFailAsync(""" class Program { static void Main(string[] args) @@ -6647,15 +5808,11 @@ static void Main(string[] args) Console.Write(4); } } - """; - - await ExpectExtractMethodToFailAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539229")] - public async Task Bug5107() - { - var code = """ + public Task Bug5107() + => TestExtractMethodAsync(""" class Program { static void Main(string[] args) @@ -6666,9 +5823,7 @@ static void Main(string[] args) Console.Write(j); } } - """; - - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -6684,15 +5839,11 @@ private static int NewMethod(int i) return j + i; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539500")] - public async Task LambdaLiftedVariable1() - { - var code = """ + public Task LambdaLiftedVariable1() + => TestExtractMethodAsync(""" class Program { delegate void Func(ref int i, int r); @@ -6707,9 +5858,7 @@ static void Main(string[] args) System.Console.WriteLine(temp); } } - """; - - var expected = """ + """, """ class Program { delegate void Func(ref int i, int r); @@ -6729,15 +5878,11 @@ private static void NewMethod(out int arg, int arg2, out int temp) temp = arg = arg2; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539488")] - public async Task LambdaLiftedVariable2() - { - var code = """ + public Task LambdaLiftedVariable2() + => TestExtractMethodAsync(""" class Program { delegate void Action(); @@ -6756,9 +5901,7 @@ static void Main(string[] args) query(); } } - """; - - var expected = """ + """, """ class Program { delegate void Action(); @@ -6782,15 +5925,11 @@ private static int NewMethod() return 3; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539531")] - public async Task Bug5533() - { - var code = """ + public Task Bug5533() + => TestExtractMethodAsync(""" using System; class Program { @@ -6803,9 +5942,7 @@ static void Main(string[] args) Console.WriteLine(p); } } - """; - - var expected = """ + """, """ using System; class Program { @@ -6823,15 +5960,11 @@ private static TestDelegate NewMethod() return (ref int x) => { x = 10; }; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539531")] - public async Task Bug5533_1() - { - var code = """ + public Task Bug5533_1() + => TestExtractMethodAsync(""" using System; class Program { @@ -6844,9 +5977,7 @@ static void Main(string[] args) Console.WriteLine(p); } } - """; - - var expected = """ + """, """ using System; class Program { @@ -6864,15 +5995,11 @@ private static TestDelegate NewMethod() return (ref int x) => { int y = x; x = 10; }; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539531")] - public async Task Bug5533_2() - { - var code = """ + public Task Bug5533_2() + => TestExtractMethodAsync(""" using System; class Program { @@ -6885,9 +6012,7 @@ static void Main(string[] args) Console.WriteLine(p); } } - """; - - var expected = """ + """, """ using System; class Program { @@ -6906,15 +6031,11 @@ private static int NewMethod(int x) return x; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539531")] - public async Task Bug5533_3() - { - var code = """ + public Task Bug5533_3() + => TestExtractMethodAsync(""" using System; class Program { @@ -6927,9 +6048,7 @@ static void Main(string[] args) Console.WriteLine(p); } } - """; - - var expected = """ + """, """ using System; class Program { @@ -6947,15 +6066,11 @@ private static TestDelegate NewMethod() return delegate (ref int x) { x = 10; }; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539859")] - public async Task LambdaLiftedVariable3() - { - var code = """ + public Task LambdaLiftedVariable3() + => TestExtractMethodAsync(""" using System; class Program { @@ -6974,9 +6089,7 @@ static void Main(string[] args) F(args.Length); } } - """; - - var expected = """ + """, """ using System; class Program { @@ -7000,15 +6113,11 @@ private static void NewMethod(string[] args, int x, int x2) Console.WriteLine(args.Length + x2 + x); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539882")] - public async Task Bug5982() - { - var code = """ + public Task Bug5982() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; @@ -7020,9 +6129,7 @@ static void Main(string[] args) Console.WriteLine([|list.Capacity|]); } } - """; - - var expected = """ + """, """ using System; using System.Collections.Generic; @@ -7039,15 +6146,11 @@ private static int GetCapacity(List list) return list.Capacity; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539932")] - public async Task Bug6041() - { - var code = """ + public Task Bug6041() + => TestExtractMethodAsync(""" using System; class Program { @@ -7058,9 +6161,7 @@ public void Goo() [|d(new ArgumentException());|] } } - """; - - var expected = """ + """, """ using System; class Program { @@ -7076,15 +6177,11 @@ private static void NewMethod(Del d) d(new ArgumentException()); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540183")] - public async Task ExtractMethod50() - { - var code = """ + public Task ExtractMethod50() + => TestExtractMethodAsync(""" class C { void Method() @@ -7099,9 +6196,7 @@ void Method() } } } - """; - - var expected = """ + """, """ class C { void Method() @@ -7121,15 +6216,11 @@ private static void NewMethod() } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod51() - { - var code = """ + public Task ExtractMethod51() + => TestExtractMethodAsync(""" class C { void Method() @@ -7148,9 +6239,7 @@ void Method() } } } - """; - - var expected = """ + """, """ class C { void Method() @@ -7174,15 +6263,11 @@ private static void NewMethod() } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethod52() - { - var code = """ + public Task ExtractMethod52() + => TestExtractMethodAsync(""" class C { void Method() @@ -7194,9 +6279,7 @@ void Method() } } } - """; - - var expected = """ + """, """ class C { void Method() @@ -7213,15 +6296,11 @@ private static void NewMethod() } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539963")] - public async Task ExtractMethod53() - { - var code = """ + public Task ExtractMethod53() + => ExpectExtractMethodToFailAsync(""" class Class { void Main() @@ -7230,30 +6309,22 @@ void Main() } } enum Enum { } - """; - - await ExpectExtractMethodToFailAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539964")] - public async Task ExtractMethod54() - { - var code = """ + public Task ExtractMethod54() + => ExpectExtractMethodToFailAsync(""" class Class { void Main([|string|][] args) { } } - """; - - await ExpectExtractMethodToFailAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540072")] - public async Task Bug6220() - { - var code = """ + public Task Bug6220() + => TestExtractMethodAsync(""" class C { void Main() @@ -7262,9 +6333,7 @@ void Main() |] System.Console.WriteLine(); } } - """; - - var expected = """ + """, """ class C { void Main() @@ -7278,14 +6347,11 @@ private static void NewMethod() float f = 1.2f; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540072")] - public async Task Bug6220_1() - { - var code = """ + public Task Bug6220_1() + => TestExtractMethodAsync(""" class C { void Main() @@ -7294,9 +6360,7 @@ void Main() |] System.Console.WriteLine(); } } - """; - - var expected = """ + """, """ class C { void Main() @@ -7310,14 +6374,11 @@ private static void NewMethod() float f = 1.2f; // test } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540071")] - public async Task Bug6219() - { - var code = """ + public Task Bug6219() + => TestExtractMethodAsync(""" class C { void Main() @@ -7326,9 +6387,7 @@ void Main() [|@float = 1.44F;|] } } - """; - - var expected = """ + """, """ class C { void Main() @@ -7342,14 +6401,11 @@ private static float NewMethod() return 1.44F; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540080")] - public async Task Bug6230() - { - var code = """ + public Task Bug6230() + => TestExtractMethodAsync(""" class C { void M() @@ -7358,9 +6414,7 @@ void M() System.Console.WriteLine(); } } - """; - - var expected = """ + """, """ class C { void M() @@ -7374,14 +6428,11 @@ private static int GetV() return /**/1 + 2; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540080")] - public async Task Bug6230_1() - { - var code = """ + public Task Bug6230_1() + => TestExtractMethodAsync(""" class C { void M() @@ -7390,9 +6441,7 @@ void M() System.Console.WriteLine(); } } - """; - - var expected = """ + """, """ class C { void M() @@ -7406,14 +6455,11 @@ private static void NewMethod() int v = /**/1 + 2; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540052")] - public async Task Bug6197() - { - var code = """ + public Task Bug6197() + => TestExtractMethodAsync(""" using System; class Program @@ -7429,9 +6475,7 @@ private static int NewMethod(int x) return x * 2; } } - """; - - var expected = """ + """, """ using System; class Program @@ -7452,14 +6496,11 @@ private static int NewMethod(int x) return x * 2; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem(6277, "DevDiv_Projects/Roslyn")] - public async Task Bug6277() - { - var code = """ + public Task Bug6277() + => TestExtractMethodAsync(""" using System; class Program @@ -7472,9 +6513,7 @@ static void Main(string[] args) int y = x; } } - """; - - var expected = """ + """, """ using System; class Program @@ -7491,14 +6530,11 @@ private static int NewMethod() return 1; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540151")] - public async Task ArgumentlessReturnWithConstIfExpression() - { - var code = """ + public Task ArgumentlessReturnWithConstIfExpression() + => TestExtractMethodAsync(""" using System; class Program @@ -7510,9 +6546,7 @@ void Test() Console.WriteLine(); } } - """; - - var expected = """ + """, """ using System; class Program @@ -7530,14 +6564,11 @@ private static void NewMethod() return; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540151")] - public async Task ArgumentlessReturnWithConstIfExpression_1() - { - var code = """ + public Task ArgumentlessReturnWithConstIfExpression_1() + => TestExtractMethodAsync(""" using System; class Program @@ -7550,9 +6581,7 @@ void Test() Console.WriteLine(); } } - """; - - var expected = """ + """, """ using System; class Program @@ -7573,14 +6602,11 @@ private static void NewMethod() return; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540151")] - public async Task ArgumentlessReturnWithConstIfExpression_2() - { - var code = """ + public Task ArgumentlessReturnWithConstIfExpression_2() + => TestExtractMethodAsync(""" using System; class Program @@ -7591,9 +6617,7 @@ void Test() return;|] } } - """; - - var expected = """ + """, """ using System; class Program @@ -7609,14 +6633,11 @@ private static void NewMethod() return; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540151")] - public async Task ArgumentlessReturnWithConstIfExpression_3() - { - var code = """ + public Task ArgumentlessReturnWithConstIfExpression_3() + => TestExtractMethodAsync(""" using System; class Program @@ -7628,9 +6649,7 @@ void Test() return;|] } } - """; - - var expected = """ + """, """ using System; class Program @@ -7650,14 +6669,11 @@ private static void NewMethod() return; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] - public async Task Bug6313() - { - var code = """ + public Task Bug6313() + => TestExtractMethodAsync(""" using System; class Program @@ -7671,9 +6687,7 @@ void Test(bool b) Console.WriteLine();|] } } - """; - - var expected = """ + """, """ using System; class Program @@ -7697,14 +6711,11 @@ private static bool NewMethod(bool b) return true; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] - public async Task Bug6313_1() - { - await TestExtractMethodAsync(""" + public Task Bug6313_1() + => TestExtractMethodAsync(""" using System; class Program @@ -7745,12 +6756,10 @@ private static bool NewMethod(bool b) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] - public async Task Bug6313_2() - { - await TestExtractMethodAsync(""" + public Task Bug6313_2() + => TestExtractMethodAsync(""" using System; class Program @@ -7789,12 +6798,10 @@ private static (bool flowControl, int value) NewMethod(bool b) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] - public async Task Bug6313_3() - { - var code = """ + public Task Bug6313_3() + => TestExtractMethodAsync(""" using System; class Program @@ -7817,8 +6824,7 @@ void Test() };|] } } - """; - var expected = """ + """, """ using System; class Program @@ -7851,14 +6857,11 @@ private static bool NewMethod() return true; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] - public async Task Bug6313_4() - { - var code = """ + public Task Bug6313_4() + => TestExtractMethodAsync(""" using System; class Program @@ -7888,8 +6891,7 @@ void Test() Console.WriteLine(1); } } - """; - var expected = """ + """, """ using System; class Program @@ -7924,14 +6926,11 @@ private static void NewMethod() }; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] - public async Task Bug6313_5() - { - var code = """ + public Task Bug6313_5() + => TestExtractMethodAsync(""" using System; class Program @@ -7949,8 +6948,7 @@ void Test() }; } } - """; - var expected = """ + """, """ using System; class Program @@ -7978,14 +6976,11 @@ private static bool NewMethod() return true; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] - public async Task Bug6313_6() - { - await TestExtractMethodAsync(""" + public Task Bug6313_6() + => TestExtractMethodAsync(""" using System; class Program @@ -8033,12 +7028,10 @@ private static bool NewMethod() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540170")] - public async Task Bug6333() - { - var code = """ + public Task Bug6333() + => TestExtractMethodAsync(""" using System; class Program @@ -8049,8 +7042,7 @@ void Test() [|p = new Program()|]; } } - """; - var expected = """ + """, """ using System; class Program @@ -8066,15 +7058,11 @@ private static Program NewMethod() return new Program(); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540216")] - public async Task Bug6393() - { - var code = """ + public Task Bug6393() + => TestExtractMethodAsync(""" using System; class Program @@ -8085,8 +7073,7 @@ object Test() return abcd; } } - """; - var expected = """ + """, """ using System; class Program @@ -8102,15 +7089,11 @@ private static T NewMethod() return new T(); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540184")] - public async Task Bug6351() - { - var code = """ + public Task Bug6351() + => TestExtractMethodAsync(""" class Test { void method() @@ -8127,8 +7110,7 @@ void method() } } } - """; - var expected = """ + """, """ class Test { void method() @@ -8150,15 +7132,11 @@ private static void NewMethod() System.Console.WriteLine(); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540184")] - public async Task Bug6351_1() - { - var code = """ + public Task Bug6351_1() + => TestExtractMethodAsync(""" class Test { void method() @@ -8175,8 +7153,7 @@ void method() } } } - """; - var expected = """ + """, """ class Test { void method() @@ -8198,15 +7175,11 @@ private static void NewMethod() /*End*/ } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540184")] - public async Task Bug6351_2() - { - var code = """ + public Task Bug6351_2() + => TestExtractMethodAsync(""" class Test { void method() @@ -8223,8 +7196,7 @@ void method() }|] } } - """; - var expected = """ + """, """ class Test { void method() @@ -8244,15 +7216,11 @@ private static void NewMethod() /*End*/ } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540333")] - public async Task Bug6560() - { - var code = """ + public Task Bug6560() + => TestExtractMethodAsync(""" using System; class Program { @@ -8262,8 +7230,7 @@ static void Main(string[] args) int Y = S.Length; } } - """; - var expected = """ + """, """ using System; class Program { @@ -8278,22 +7245,17 @@ private static string GetS() return null; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540335")] - public async Task Bug6562() - { - var code = """ + public Task Bug6562() + => TestExtractMethodAsync(""" using System; class Program { int y = [|10|]; } - """; - var expected = """ + """, """ using System; class Program { @@ -8304,35 +7266,27 @@ private static int GetY() return 10; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540335")] - public async Task Bug6562_1() - { - var code = """ + public Task Bug6562_1() + => ExpectExtractMethodToFailAsync(""" using System; class Program { const int i = [|10|]; } - """; - await ExpectExtractMethodToFailAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540335")] - public async Task Bug6562_2() - { - var code = """ + public Task Bug6562_2() + => TestExtractMethodAsync(""" using System; class Program { Func f = [|() => "test"|]; } - """; - var expected = """ + """, """ using System; class Program { @@ -8343,22 +7297,17 @@ private static Func GetF() return () => "test"; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540335")] - public async Task Bug6562_3() - { - var code = """ + public Task Bug6562_3() + => TestExtractMethodAsync(""" using System; class Program { Func f = () => [|"test"|]; } - """; - var expected = """ + """, """ using System; class Program { @@ -8369,15 +7318,11 @@ private static string NewMethod() return "test"; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540361")] - public async Task Bug6598() - { - var code = """ + public Task Bug6598() + => ExpectExtractMethodToFailAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -8389,14 +7334,11 @@ static void Main(string[] args) [|Program|] } } - """; - await ExpectExtractMethodToFailAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540372")] - public async Task Bug6613() - { - var code = """ + public Task Bug6613() + => TestExtractMethodAsync(""" #define A using System; @@ -8409,8 +7351,7 @@ static void Main(string[] args) #endif } } - """; - var expected = """ + """, """ #define A using System; @@ -8428,15 +7369,11 @@ private static void NewMethod() Console.Write(5); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540396")] - public async Task InvalidSelection_MethodBody() - { - var code = """ + public Task InvalidSelection_MethodBody() + => ExpectExtractMethodToFailAsync(""" using System; class Program @@ -8455,14 +7392,11 @@ void Method5(bool b1, bool b2) }|] } } - """; - await ExpectExtractMethodToFailAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541586")] - public async Task StructThis() - { - var code = """ + public Task StructThis() + => TestExtractMethodAsync(""" struct S { void Goo() @@ -8470,8 +7404,7 @@ void Goo() [|this = new S();|] } } - """; - var expected = """ + """, """ struct S { void Goo() @@ -8484,14 +7417,11 @@ private void NewMethod() this = new S(); } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541627")] - public async Task DoNotUseConvertedTypeForImplicitNumericConversion() - { - var code = """ + public Task DoNotUseConvertedTypeForImplicitNumericConversion() + => TestExtractMethodAsync(""" class T { void Goo() @@ -8500,8 +7430,7 @@ void Goo() long x2 = [|x1|]; } } - """; - var expected = """ + """, """ class T { void Goo() @@ -8515,14 +7444,11 @@ private static int GetX2(int x1) return x1; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541668")] - public async Task BreakInSelection() - { - await TestExtractMethodAsync( + public Task BreakInSelection() + => TestExtractMethodAsync( """ using System; using System.Collections.Generic; @@ -8600,12 +7526,10 @@ private static int NewMethod(ref string x1) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541671")] - public async Task UnreachableCodeWithReturnStatement() - { - var code = """ + public Task UnreachableCodeWithReturnStatement() + => TestExtractMethodAsync(""" class Program { static void Main(string[] args) @@ -8618,8 +7542,7 @@ static void Main(string[] args) return; } } - """; - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -8637,14 +7560,11 @@ private static void NewMethod() i1 = i1 + 10; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539862")] - public async Task DoNotBlindlyPutCapturedVariable1() - { - var code = """ + public Task DoNotBlindlyPutCapturedVariable1() + => TestExtractMethodAsync(""" using System; class Program { @@ -8668,8 +7588,7 @@ public void F(int s) } } } - """; - var expected = """ + """, """ using System; class Program { @@ -8698,14 +7617,11 @@ public void F(int s) } } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539862")] - public async Task DoNotBlindlyPutCapturedVariable2() - { - var code = """ + public Task DoNotBlindlyPutCapturedVariable2() + => TestExtractMethodAsync(""" using System; class Program { @@ -8719,8 +7635,7 @@ static void Main(string[] args) d(3); } } - """; - var expected = """ + """, """ using System; class Program { @@ -8739,14 +7654,11 @@ private static Program NewMethod() return null; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541889")] - public async Task DoNotCrashOnRangeVariableSymbol() - { - var code = """ + public Task DoNotCrashOnRangeVariableSymbol() + => ExpectExtractMethodToFailAsync(""" class Test { public void Linq1() @@ -8755,14 +7667,11 @@ public void Linq1() var lowNums = [|from|] n in numbers where n < 5 select n; } } - """; - await ExpectExtractMethodToFailAsync(code); - } + """); [Fact] - public async Task ExtractRangeVariable() - { - var code = """ + public Task ExtractRangeVariable() + => TestExtractMethodAsync(""" using System.Linq; class Test { @@ -8772,9 +7681,7 @@ public void Linq1() var q = from string s in array select [|s|]; } } - """; - - var expected = """ + """, """ using System.Linq; class Test { @@ -8789,14 +7696,11 @@ private static string GetS(string s) return s; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542155")] - public async Task GenericWithErrorType() - { - var code = """ + public Task GenericWithErrorType() + => TestExtractMethodAsync(""" using Goo.Utilities; class Goo { @@ -8821,8 +7725,7 @@ public static bool IsEmpty(this Goo source) } } } - """; - var expected = """ + """, """ using Goo.Utilities; class Goo { @@ -8852,15 +7755,11 @@ public static bool IsEmpty(this Goo source) } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542105")] - public async Task NamedArgument() - { - var code = """ + public Task NamedArgument() + => TestExtractMethodAsync(""" using System; class C @@ -8872,8 +7771,7 @@ void Goo() var y = this[[|y|]: 1]; } } - """; - var expected = """ + """, """ using System; class C @@ -8890,15 +7788,11 @@ private int GetY() return this[y: 1]; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542213")] - public async Task QueryExpressionVariable() - { - var code = """ + public Task QueryExpressionVariable() + => TestExtractMethodAsync(""" using System; using System.Linq; using System.Collections.Generic; @@ -8914,8 +7808,7 @@ from b in Enumerable.Range(1, 2) select a; } } - """; - var expected = """ + """, """ using System; using System.Linq; using System.Collections.Generic; @@ -8936,15 +7829,11 @@ private static bool NewMethod(int a, int b) return a == b; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542465")] - public async Task IsExpression() - { - var code = """ + public Task IsExpression() + => TestExtractMethodAsync(""" using System; class Class1 { @@ -8959,8 +7848,7 @@ static void Main() { } } - """; - var expected = """ + """, """ using System; class Class1 { @@ -8981,15 +7869,11 @@ static void Main() { } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542526")] - public async Task TypeParametersInConstraint() - { - var code = """ + public Task TypeParametersInConstraint() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; @@ -9000,8 +7884,7 @@ static void Goo(T x) where T : IList var y = [|x.Count|]; } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; @@ -9017,15 +7900,11 @@ private static int GetY(T x) where T : IList return x.Count; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542619")] - public async Task GlobalNamespaceInReturnType() - { - var code = """ + public Task GlobalNamespaceInReturnType() + => TestExtractMethodAsync(""" class Program { class System @@ -9034,8 +7913,7 @@ class Action { } } static global::System.Action a = () => { global::System.Console.WriteLine(); [|}|]; } - """; - var expected = """ + """, """ class Program { class System @@ -9049,15 +7927,11 @@ class Action { } return () => { global::System.Console.WriteLine(); }; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542582")] - public async Task ExtractMethodExpandSelectionOnFor() - { - var code = """ + public Task ExtractMethodExpandSelectionOnFor() + => TestExtractMethodAsync(""" using System; class Program @@ -9070,9 +7944,7 @@ static void Main(string[] args) } } } - """; - - var expected = """ + """, """ using System; class Program @@ -9088,15 +7960,11 @@ private static void NewMethod(int i) Console.WriteLine(i); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethodNotContainerOnFor() - { - var code = """ + public Task ExtractMethodNotContainerOnFor() + => TestExtractMethodAsync(""" using System; class Program @@ -9106,9 +7974,7 @@ static void Main(string[] args) for (int i = 0; i < [|10|]; i++) ; } } - """; - - var expected = """ + """, """ using System; class Program @@ -9123,15 +7989,11 @@ private static int NewMethod() return 10; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethodExpandSelectionOnForeach() - { - var code = """ + public Task ExtractMethodExpandSelectionOnForeach() + => TestExtractMethodAsync(""" using System; class Program @@ -9144,9 +8006,7 @@ static void Main(string[] args) } } } - """; - - var expected = """ + """, """ using System; class Program @@ -9162,15 +8022,11 @@ private static void NewMethod(char c) Console.Write(c); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethodNotContainerOnForeach() - { - var code = """ + public Task ExtractMethodNotContainerOnForeach() + => TestExtractMethodAsync(""" using System; class Program @@ -9183,9 +8039,7 @@ static void Main(string[] args) } } } - """; - - var expected = """ + """, """ using System; class Program @@ -9203,15 +8057,11 @@ private static string NewMethod() return "123"; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethodNotContainerOnElseClause() - { - var code = """ + public Task ExtractMethodNotContainerOnElseClause() + => TestExtractMethodAsync(""" using System; class Program @@ -9226,9 +8076,7 @@ static void Main(string[] args) } } } - """; - - var expected = """ + """, """ using System; class Program @@ -9248,15 +8096,11 @@ private static bool NewMethod() return true; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethodExpandSelectionOnLabel() - { - var code = """ + public Task ExtractMethodExpandSelectionOnLabel() + => TestExtractMethodAsync(""" using System; class Program @@ -9269,9 +8113,7 @@ static void Main(string[] args) goto repeat; } } - """; - - var expected = """ + """, """ using System; class Program @@ -9289,15 +8131,11 @@ private static void NewMethod() Console.WriteLine("Roslyn"); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethodNotContainerOnLabel() - { - var code = """ + public Task ExtractMethodNotContainerOnLabel() + => TestExtractMethodAsync(""" using System; class Program @@ -9310,9 +8148,7 @@ static void Main(string[] args) goto repeat; } } - """; - - var expected = """ + """, """ using System; class Program @@ -9330,15 +8166,11 @@ private static bool NewMethod() return true; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethodExpandSelectionOnSwitch() - { - var code = """ + public Task ExtractMethodExpandSelectionOnSwitch() + => TestExtractMethodAsync(""" using System; class Program @@ -9352,9 +8184,7 @@ static void Main(string[] args) } } } - """; - - var expected = """ + """, """ using System; class Program @@ -9373,15 +8203,11 @@ private static void NewMethod() Console.WriteLine("one"); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethodNotContainerOnSwitch() - { - var code = """ + public Task ExtractMethodNotContainerOnSwitch() + => TestExtractMethodAsync(""" using System; class Program @@ -9395,9 +8221,7 @@ static void Main(string[] args) } } } - """; - - var expected = """ + """, """ using System; class Program @@ -9416,15 +8240,11 @@ private static string NewMethod(string[] args) return args[0]; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethodExpandSelectionOnDo() - { - var code = """ + public Task ExtractMethodExpandSelectionOnDo() + => TestExtractMethodAsync(""" using System; class Program @@ -9437,9 +8257,7 @@ static void Main(string[] args) } while (DateTime.Now.DayOfWeek == DayOfWeek.Monday); } } - """; - - var expected = """ + """, """ using System; class Program @@ -9455,15 +8273,11 @@ private static void NewMethod() Console.WriteLine("I don't like"); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethodNotContainerOnDo() - { - var code = """ + public Task ExtractMethodNotContainerOnDo() + => TestExtractMethodAsync(""" using System; class Program @@ -9476,9 +8290,7 @@ static void Main(string[] args) } while ([|DateTime.Now.DayOfWeek == DayOfWeek.Monday|]); } } - """; - - var expected = """ + """, """ using System; class Program @@ -9496,15 +8308,11 @@ private static bool NewMethod() return DateTime.Now.DayOfWeek == DayOfWeek.Monday; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethodExpandSelectionOnWhile() - { - var code = """ + public Task ExtractMethodExpandSelectionOnWhile() + => TestExtractMethodAsync(""" using System; class Program @@ -9517,9 +8325,7 @@ static void Main(string[] args) } } } - """; - - var expected = """ + """, """ using System; class Program @@ -9535,24 +8341,18 @@ private static void NewMethod() ; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethodExpandSelectionOnStruct() - { - var code = """ + public Task ExtractMethodExpandSelectionOnStruct() + => TestExtractMethodAsync(""" using System; struct Goo { static Action a = () => { Console.WriteLine(); [|}|]; } - """; - - var expected = """ + """, """ using System; struct Goo @@ -9564,15 +8364,11 @@ private static Action GetA() return () => { Console.WriteLine(); }; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542619")] - public async Task ExtractMethodIncludeGlobal() - { - var code = """ + public Task ExtractMethodIncludeGlobal() + => TestExtractMethodAsync(""" class Program { class System @@ -9584,9 +8380,7 @@ static void Main(string[] args) { } } - """; - - var expected = """ + """, """ class Program { class System @@ -9604,15 +8398,11 @@ static void Main(string[] args) { } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542582")] - public async Task ExtractMethodExpandSelection() - { - var code = """ + public Task ExtractMethodExpandSelection() + => TestExtractMethodAsync(""" class Program { static void Main(string[] args) @@ -9623,9 +8413,7 @@ static void Main(string[] args) } } } - """; - - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -9639,15 +8427,11 @@ private static void NewMethod(int i) System.Console.WriteLine(i); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542594")] - public async Task ExtractMethodRename1() - { - var code = """ + public Task ExtractMethodRename1() + => TestExtractMethodAsync(""" class Program { static void Main() @@ -9658,9 +8442,7 @@ static void Main() private static void NewMethod() { } private static void NewMethod2() { } } - """; - - var expected = """ + """, """ class Program { static void Main() @@ -9677,15 +8459,11 @@ private static void NewMethod1() private static void NewMethod() { } private static void NewMethod2() { } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542594")] - public async Task ExtractMethodRename2() - { - var code = """ + public Task ExtractMethodRename2() + => TestExtractMethodAsync(""" class Program { static void Main() @@ -9702,9 +8480,7 @@ private static void NewMethod1() private static void NewMethod() { } private static void NewMethod2() { } } - """; - - var expected = """ + """, """ class Program { static void Main() @@ -9726,16 +8502,11 @@ private static void NewMethod1() private static void NewMethod() { } private static void NewMethod2() { } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542632")] - public async Task ExtractMethodInInteractive1() - { - var code = @"int i; [|i = 2|]; i = 3;"; - var expected = """ + public Task ExtractMethodInInteractive1() + => TestExtractMethodAsync(@"int i; [|i = 2|]; i = 3;", """ int i; i = NewMethod(); static int NewMethod() @@ -9744,14 +8515,11 @@ static int NewMethod() } i = 3; - """; - await TestExtractMethodAsync(code, expected, parseOptions: Options.Script); - } + """, parseOptions: Options.Script); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542670")] - public async Task TypeParametersInConstraint1() - { - var code = """ + public Task TypeParametersInConstraint1() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; @@ -9762,8 +8530,7 @@ static void Goo(T x) where T : IList where S : IList var y = [|x.Count|]; } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; @@ -9779,16 +8546,12 @@ private static int GetY(T x) where T : IList return x.Count; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/706894")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543012")] - public async Task TypeParametersInConstraint2() - { - var code = """ + public Task TypeParametersInConstraint2() + => TestExtractMethodAsync(""" using System; interface I where T : IComparable @@ -9803,8 +8566,7 @@ static void Goo(S x) where S : I where T : IComparable var y = [|x.Count|]; } } - """; - var expected = """ + """, """ using System; interface I where T : IComparable @@ -9826,16 +8588,12 @@ private static int GetY(S x) return x.Count; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/706894")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543012")] - public async Task TypeParametersInConstraint3() - { - var code = """ + public Task TypeParametersInConstraint3() + => TestExtractMethodAsync(""" using System; interface I where T : class @@ -9850,8 +8608,7 @@ static void Goo(S x) where S : I where T : class var y = [|x.Count|]; } } - """; - var expected = """ + """, """ using System; interface I where T : class @@ -9873,15 +8630,11 @@ private static int GetY(S x) return x.Count; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543012")] - public async Task TypeParametersInConstraint4() - { - var code = """ + public Task TypeParametersInConstraint4() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; @@ -9908,8 +8661,7 @@ public override void Goo(S x) var y = [|x.Count|]; } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; @@ -9943,15 +8695,11 @@ private static int GetY(S x) return x.Count; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task NullabilityTypeParameters() - { - var code = """ + public Task NullabilityTypeParameters() + => TestExtractMethodAsync(""" #nullable enable using System.Collections.Generic; @@ -9963,8 +8711,7 @@ public int M(Dictionary v) [|return v.Count;|] } } - """; - var expected = """ + """, """ #nullable enable using System.Collections.Generic; @@ -9981,15 +8728,11 @@ private static int NewMethod(Dictionary v) return v.Count; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543012")] - public async Task TypeParametersInConstraintBestEffort() - { - var code = """ + public Task TypeParametersInConstraintBestEffort() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -10008,8 +8751,7 @@ public override void Test(S s) var t = [|s.ToString()|]; } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -10033,15 +8775,11 @@ private static string GetT(S s) where S : string return s.ToString(); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542672")] - public async Task ConstructedTypes() - { - var code = """ + public Task ConstructedTypes() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; @@ -10053,8 +8791,7 @@ static void Goo() Action a = () => Console.WriteLine([|x.Count|]); } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; @@ -10071,15 +8808,11 @@ private static int GetCount(List x) return x.Count; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542792")] - public async Task TypeInDefault() - { - var code = """ + public Task TypeInDefault() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -10105,8 +8838,7 @@ public Node() Console.WriteLine(Key); } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -10137,23 +8869,18 @@ private static K NewMethod() return default(K); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542708")] - public async Task Script_ArgumentException() - { - var code = """ + public Task Script_ArgumentException() + => TestExtractMethodAsync(""" using System; public static void GetNonVirtualMethod( Type type, string name) { Type delegateType = typeof(TDelegate); var invoke = [|delegateType|].GetMethod("Invoke"); } - """; - var expected = """ + """, """ using System; public static void GetNonVirtualMethod( Type type, string name) { @@ -10165,15 +8892,11 @@ static Type GetDelegateType(Type delegateType) { return delegateType; } - """; - - await TestExtractMethodAsync(code, expected, parseOptions: Options.Script); - } + """, parseOptions: Options.Script); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529008")] - public async Task ReadOutSideIsUnReachable() - { - var code = """ + public Task ReadOutSideIsUnReachable() + => TestExtractMethodAsync(""" class Test { public static void Main() @@ -10188,8 +8911,7 @@ public static void Main() System.Console.Write(obj); } } - """; - var expected = """ + """, """ class Test { public static void Main() @@ -10210,15 +8932,11 @@ private static void NewMethod(string str, out object obj) } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543186")] - public async Task AnonymousTypePropertyName() - { - var code = """ + public Task AnonymousTypePropertyName() + => TestExtractMethodAsync(""" class C { void M() @@ -10226,8 +8944,7 @@ void M() var x = new { [|String|] = true }; } } - """; - var expected = """ + """, """ class C { void M() @@ -10240,22 +8957,18 @@ private static void NewMethod() var x = new { String = true }; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543662")] - public async Task ArgumentOfBaseConstrInit() - { - var code = """ + public Task ArgumentOfBaseConstrInit() + => TestExtractMethodAsync(""" class O { public O(int t) : base([|t|]) { } } - """; - var expected = """ + """, """ class O { public O(int t) : base(GetT(t)) @@ -10267,15 +8980,11 @@ private static int GetT(int t) return t; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task UnsafeType() - { - var code = """ + public Task UnsafeType() + => TestExtractMethodAsync(""" unsafe class O { unsafe public O(int t) @@ -10283,8 +8992,7 @@ unsafe public O(int t) [|t = 1;|] } } - """; - var expected = """ + """, """ unsafe class O { unsafe public O(int t) @@ -10297,15 +9005,11 @@ private static int NewMethod() return 1; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544144")] - public async Task CastExpressionWithImplicitUserDefinedConversion() - { - var code = """ + public Task CastExpressionWithImplicitUserDefinedConversion() + => TestExtractMethodAsync(""" class C { static public implicit operator long(C i) @@ -10319,8 +9023,7 @@ static void Main() int y1 = [|(int)c|]; } } - """; - var expected = """ + """, """ class C { static public implicit operator long(C i) @@ -10339,15 +9042,11 @@ private static int GetY1(C c) return (int)c; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544387")] - public async Task FixedPointerVariable() - { - var code = """ + public Task FixedPointerVariable() + => TestExtractMethodAsync(""" class Test { static int x = 0; @@ -10359,8 +9058,7 @@ unsafe static void Main() } } } - """; - var expected = """ + """, """ class Test { static int x = 0; @@ -10377,15 +9075,11 @@ private static unsafe int GetA1(int* p1) return *p1; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544444")] - public async Task PointerDeclarationStatement() - { - var code = """ + public Task PointerDeclarationStatement() + => TestExtractMethodAsync(""" class Program { unsafe static void Main() @@ -10394,8 +9088,7 @@ unsafe static void Main() [|int* p2 = p1;|] } } - """; - var expected = """ + """, """ class Program { unsafe static void Main() @@ -10409,15 +9102,11 @@ private static unsafe void NewMethod(int* p1) int* p2 = p1; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544446")] - public async Task PrecededByCastExpr() - { - var code = """ + public Task PrecededByCastExpr() + => TestExtractMethodAsync(""" class Program { static void Main() @@ -10425,8 +9114,7 @@ static void Main() int i1 = (int)[|5L|]; } } - """; - var expected = """ + """, """ class Program { static void Main() @@ -10439,15 +9127,11 @@ private static long NewMethod() return 5L; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542944")] - public async Task ExpressionWithLocalConst() - { - var code = """ + public Task ExpressionWithLocalConst() + => TestExtractMethodAsync(""" class Program { static void Main(string[] args) @@ -10456,8 +9140,7 @@ static void Main(string[] args) [|a = null;|] } } - """; - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -10472,15 +9155,11 @@ private static string NewMethod(string a) return a; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542944")] - public async Task ExpressionWithLocalConst2() - { - var code = """ + public Task ExpressionWithLocalConst2() + => TestExtractMethodAsync(""" class Program { static void Main(string[] args) @@ -10489,8 +9168,7 @@ static void Main(string[] args) [|a = null;|] } } - """; - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -10505,15 +9183,11 @@ private static string NewMethod(string a) return a; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544675")] - public async Task HiddenPosition() - { - var code = """ + public Task HiddenPosition() + => ExpectExtractMethodToFailAsync(""" class Program { static void Main(string[] args) @@ -10524,20 +9198,15 @@ static void Main(string[] args) #line default #line hidden } - """; - - await ExpectExtractMethodToFailAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530609")] - public async Task NoCrashInteractive() - { - var code = """ + public Task NoCrashInteractive() + => TestExtractMethodAsync(""" [|if (true) { }|] - """; - var expected = """ + """, """ NewMethod(); static void NewMethod() @@ -10546,16 +9215,11 @@ static void NewMethod() { } } - """; - - await TestExtractMethodAsync(code, expected, parseOptions: new CSharpParseOptions(kind: SourceCodeKind.Script)); - } + """, parseOptions: new CSharpParseOptions(kind: SourceCodeKind.Script)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530322")] - public async Task ExtractMethodShouldNotBreakFormatting() - { - var code = - """ + public Task ExtractMethodShouldNotBreakFormatting() + => TestExtractMethodAsync(""" class C { void M(int i, int j, int k) @@ -10565,8 +9229,7 @@ void M(int i, int j, int k) 2); } } - """; - var expected = """ + """, """ class C { void M(int i, int j, int k) @@ -10581,16 +9244,11 @@ private static int NewMethod() return 1; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/604389")] - public async Task TestExtractLiteralExpression() - { - var code = - """ + public Task TestExtractLiteralExpression() + => TestExtractMethodAsync(""" class Program { static void Main() @@ -10603,8 +9261,7 @@ class C { public dynamic X; } - """; - var expected = """ + """, """ class Program { static void Main() @@ -10622,16 +9279,11 @@ class C { public dynamic X; } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/604389")] - public async Task TestExtractCollectionInitializer() - { - var code = - """ + public Task TestExtractCollectionInitializer() + => TestExtractMethodAsync(""" class Program { static void Main() @@ -10644,8 +9296,7 @@ class C { public dynamic X; } - """; - var expected = """ + """, """ class Program { static void Main() @@ -10663,16 +9314,11 @@ class C { public dynamic X; } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854662")] - public async Task TestExtractCollectionInitializer2() - { - var code = - """ + public Task TestExtractCollectionInitializer2() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; class Program @@ -10684,8 +9330,7 @@ static int Main(string[] args) return new Program { A = { { [|a + 2|], 0 } } }.A.Count; } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; class Program @@ -10702,16 +9347,11 @@ private static int NewMethod(int a) return a + 2; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530267")] - public async Task TestCoClassImplicitConversion() - { - var code = - """ + public Task TestCoClassImplicitConversion() + => TestExtractMethodAsync(""" using System; using System.Runtime.InteropServices; @@ -10727,8 +9367,7 @@ static void Main() [|new I()|]; // Extract Method } } - """; - var expected = """ + """, """ using System; using System.Runtime.InteropServices; @@ -10749,16 +9388,11 @@ private static I NewMethod() return new I(); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530710")] - public async Task TestOverloadResolution() - { - var code = - """ + public Task TestOverloadResolution() + => TestExtractMethodAsync(""" using System; static class C @@ -10782,8 +9416,7 @@ static class E { public static void Ex(this int x) { } } - """; - var expected = """ + """, """ using System; static class C @@ -10812,16 +9445,11 @@ static class E { public static void Ex(this int x) { } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530710")] - public async Task TestOverloadResolution1() - { - var code = - """ + public Task TestOverloadResolution1() + => TestExtractMethodAsync(""" using System; static class C @@ -10845,8 +9473,7 @@ static class E { public static void Ex(this int x) { } } - """; - var expected = """ + """, """ using System; static class C @@ -10875,16 +9502,11 @@ static class E { public static void Ex(this int x) { } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530710")] - public async Task TestOverloadResolution2() - { - var code = - """ + public Task TestOverloadResolution2() + => TestExtractMethodAsync(""" using System; static class C @@ -10908,8 +9530,7 @@ static class E { public static void Ex(this int x) { } } - """; - var expected = """ + """, """ using System; static class C @@ -10938,16 +9559,11 @@ static class E { public static void Ex(this int x) { } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/731924")] - public async Task TestTreatEnumSpecial() - { - var code = - """ + public Task TestTreatEnumSpecial() + => TestExtractMethodAsync(""" using System; class Program @@ -10965,8 +9581,7 @@ static void Main(string[] args) [|Console.WriteLine(a);|] } } - """; - var expected = """ + """, """ using System; class Program @@ -10989,16 +9604,11 @@ private static void NewMethod(A a) Console.WriteLine(a); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756222")] - public async Task TestReturnStatementInAsyncMethod() - { - var code = - """ + public Task TestReturnStatementInAsyncMethod() + => TestExtractMethodAsync(""" using System.Threading.Tasks; class C @@ -11009,8 +9619,7 @@ async Task M() [|return 3;|] } } - """; - var expected = """ + """, """ using System.Threading.Tasks; class C @@ -11026,15 +9635,11 @@ private static int NewMethod() return 3; } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/574576")] - public async Task TestAsyncMethodWithRefOrOutParameters() - { - await TestExtractMethodAsync( + public Task TestAsyncMethodWithRefOrOutParameters() + => TestExtractMethodAsync( """ using System.Threading.Tasks; @@ -11072,12 +9677,10 @@ public async void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/574576")] - public async Task TestAsyncLocalFunctionWithRefOrOutParameters() - { - await TestExtractMethodAsync( + public Task TestAsyncLocalFunctionWithRefOrOutParameters() + => TestExtractMethodAsync( """ using System.Threading.Tasks; @@ -11115,12 +9718,10 @@ public async void Goo() } } """, localFunction: true); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1025272")] - public async Task TestAsyncMethodWithWellKnownValueType1() - { - await TestExtractMethodAsync( + public Task TestAsyncMethodWithWellKnownValueType1() + => TestExtractMethodAsync( """ using System; using System.Threading; @@ -11174,12 +9775,10 @@ public async Task Hello() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1025272")] - public async Task TestAsyncMethodWithWellKnownValueType2() - { - await TestExtractMethodAsync( + public Task TestAsyncMethodWithWellKnownValueType2() + => TestExtractMethodAsync( """ using System; using System.Threading; @@ -11235,13 +9834,10 @@ public async Task Hello() } } """); - } [Fact] - public async Task TestDoNotPutOutOrRefForStructOn() - { - var code = - """ + public Task TestDoNotPutOutOrRefForStructOn() + => TestExtractMethodAsync(""" using System.Threading.Tasks; namespace ClassLibrary9 @@ -11268,9 +9864,7 @@ private async Task Test() } } } - """; - var expected = - """ + """, """ using System.Threading.Tasks; namespace ClassLibrary9 @@ -11302,20 +9896,14 @@ private async Task NewMethod(S s) } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Theory] [InlineData("add", "remove")] [InlineData("remove", "add")] [WorkItem("https://github.com/dotnet/roslyn/issues/17474")] - public async Task TestExtractMethodEventAccessorUnresolvedName(string testedAccessor, string untestedAccessor) - { - // This code intentionally omits a 'using System;' - var code = - $$""" + public Task TestExtractMethodEventAccessorUnresolvedName(string testedAccessor, string untestedAccessor) + => TestExtractMethodAsync($$""" namespace ClassLibrary9 { public class Class @@ -11327,9 +9915,7 @@ public event EventHandler Event } } } - """; - var expected = - $$""" + """, $$""" namespace ClassLibrary9 { public class Class @@ -11346,16 +9932,11 @@ private static void NewMethod() } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19958")] - public async Task TestExtractMethodRefPassThrough() - { - var code = - """ + public Task TestExtractMethodRefPassThrough() + => TestExtractMethodAsync(""" using System; namespace ClassLibrary9 @@ -11368,9 +9949,7 @@ public static void Method(ref int x) => Console.WriteLine(OtherMethod(ref [|x|])); } } - """; - var expected = - """ + """, """ using System; namespace ClassLibrary9 @@ -11388,16 +9967,11 @@ public static ref int NewMethod(ref int x) } } } - """; - - await TestExtractMethodAsync(code, expected, temporaryFailing: true); - } + """, temporaryFailing: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19958")] - public async Task TestExtractMethodRefPassThroughDuplicateVariable() - { - var code = - """ + public Task TestExtractMethodRefPassThroughDuplicateVariable() + => TestExtractMethodAsync(""" using System; namespace ClassLibrary9 @@ -11425,9 +9999,7 @@ public static void Method(this IClass instance, Guid guid) } } } - """; - var expected = - """ + """, """ using System; namespace ClassLibrary9 @@ -11460,10 +10032,7 @@ public static ref Guid NewMethod(ref Guid guid) } } } - """; - - await TestExtractMethodAsync(code, expected, temporaryFailing: true); - } + """, temporaryFailing: true); [Fact] public async Task ExtractMethod_Argument1() @@ -11517,9 +10086,8 @@ public void ExtractMethodCommandDisabledInSubmission() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18347")] - public async Task ExtractMethodUnreferencedLocalFunction1() - { - var code = """ + public Task ExtractMethodUnreferencedLocalFunction1() + => TestExtractMethodAsync(""" namespace ExtractMethodCrashRepro { public static class SomeClass @@ -11532,8 +10100,7 @@ private static void Repro( int arg ) } } } - """; - var expected = """ + """, """ namespace ExtractMethodCrashRepro { public static class SomeClass @@ -11551,15 +10118,11 @@ private static void NewMethod(int arg) } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18347")] - public async Task ExtractMethodUnreferencedLocalFunction2() - { - var code = """ + public Task ExtractMethodUnreferencedLocalFunction2() + => TestExtractMethodAsync(""" namespace ExtractMethodCrashRepro { public static class SomeClass @@ -11572,8 +10135,7 @@ private static void Repro( int arg ) } } } - """; - var expected = """ + """, """ namespace ExtractMethodCrashRepro { public static class SomeClass @@ -11591,15 +10153,11 @@ private static void NewMethod(int arg) } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18347")] - public async Task ExtractMethodUnreferencedLocalFunction3() - { - var code = """ + public Task ExtractMethodUnreferencedLocalFunction3() + => TestExtractMethodAsync(""" namespace ExtractMethodCrashRepro { public static class SomeClass @@ -11612,8 +10170,7 @@ private static void Repro( int arg ) } } } - """; - var expected = """ + """, """ namespace ExtractMethodCrashRepro { public static class SomeClass @@ -11632,15 +10189,11 @@ private static int NewMethod(int arg) } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18347")] - public async Task ExtractMethodUnreferencedLocalFunction4() - { - var code = """ + public Task ExtractMethodUnreferencedLocalFunction4() + => TestExtractMethodAsync(""" namespace ExtractMethodCrashRepro { public static class SomeClass @@ -11653,8 +10206,7 @@ private static void Repro( int arg ) } } } - """; - var expected = """ + """, """ namespace ExtractMethodCrashRepro { public static class SomeClass @@ -11673,15 +10225,11 @@ private static int NewMethod(int arg) } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18347")] - public async Task ExtractMethodUnreferencedLocalFunction5() - { - var code = """ + public Task ExtractMethodUnreferencedLocalFunction5() + => TestExtractMethodAsync(""" namespace ExtractMethodCrashRepro { public static class SomeClass @@ -11696,8 +10244,7 @@ private static void Repro( int arg ) } } } - """; - var expected = """ + """, """ namespace ExtractMethodCrashRepro { public static class SomeClass @@ -11718,19 +10265,15 @@ private static int NewMethod(int arg) } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Theory] [InlineData("LocalCapture();")] [InlineData("System.Func function = LocalCapture;")] [InlineData("System.Func function = () => LocalCapture();")] [WorkItem("https://github.com/dotnet/roslyn/issues/18347")] - public async Task ExtractMethodFlowsToLocalFunction1(string usageSyntax) - { - var code = $$""" + public Task ExtractMethodFlowsToLocalFunction1(string usageSyntax) + => TestExtractMethodAsync($$""" namespace ExtractMethodCrashRepro { public static class SomeClass @@ -11745,8 +10288,7 @@ private static void Repro( int arg ) } } } - """; - var expected = $$""" + """, $$""" namespace ExtractMethodCrashRepro { public static class SomeClass @@ -11767,19 +10309,15 @@ private static int NewMethod(int arg) } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Theory] [InlineData("LocalCapture();")] [InlineData("System.Func function = LocalCapture;")] [InlineData("System.Func function = () => LocalCapture();")] [WorkItem("https://github.com/dotnet/roslyn/issues/18347")] - public async Task ExtractMethodFlowsToLocalFunction2(string usageSyntax) - { - var code = $$""" + public Task ExtractMethodFlowsToLocalFunction2(string usageSyntax) + => TestExtractMethodAsync($$""" namespace ExtractMethodCrashRepro { public static class SomeClass @@ -11794,8 +10332,7 @@ private static void Repro( int arg ) } } } - """; - var expected = $$""" + """, $$""" namespace ExtractMethodCrashRepro { public static class SomeClass @@ -11816,10 +10353,7 @@ private static int NewMethod(int arg) } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); /// /// This test verifies that Extract Method works properly when the region to extract references a local @@ -11830,9 +10364,8 @@ private static int NewMethod(int arg) [InlineData("System.Func function = LocalCapture;")] [InlineData("System.Func function = () => LocalCapture();")] [WorkItem("https://github.com/dotnet/roslyn/issues/18347")] - public async Task ExtractMethodFlowsToLocalFunctionWithUnassignedLocal(string usageSyntax) - { - var code = $$""" + public Task ExtractMethodFlowsToLocalFunctionWithUnassignedLocal(string usageSyntax) + => TestExtractMethodAsync($$""" namespace ExtractMethodCrashRepro { public static class SomeClass @@ -11848,8 +10381,7 @@ private static void Repro( int arg ) } } } - """; - var expected = $$""" + """, $$""" namespace ExtractMethodCrashRepro { public static class SomeClass @@ -11871,15 +10403,11 @@ private static int NewMethod(int arg) } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18347")] - public async Task ExtractMethodDoesNotFlowToLocalFunction1() - { - var code = """ + public Task ExtractMethodDoesNotFlowToLocalFunction1() + => TestExtractMethodAsync(""" namespace ExtractMethodCrashRepro { public static class SomeClass @@ -11894,8 +10422,7 @@ private static void Repro( int arg ) } } } - """; - var expected = """ + """, """ namespace ExtractMethodCrashRepro { public static class SomeClass @@ -11916,15 +10443,11 @@ private static int NewMethod(int arg) } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task TestUnreachableCodeModifiedInside() - { - var code = """ + public Task TestUnreachableCodeModifiedInside() + => TestExtractMethodAsync(""" using System.Collections.Generic; using System.Linq; @@ -11941,9 +10464,7 @@ IEnumerable Crash0(IEnumerable enumerable) } } } - """; - - var expected = """ + """, """ using System.Collections.Generic; using System.Linq; @@ -11965,18 +10486,11 @@ private static IEnumerable NewMethod(ref IEnumerable enumerable) } } } - """; - - // allowMovingDeclaration: false is default behavior on VS. - // it doesn't affect result mostly but it does affect for symbols in unreachable code since - // data flow in and out for the symbol is always set to false - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task TestUnreachableCodeModifiedOutside() - { - var code = """ + public Task TestUnreachableCodeModifiedOutside() + => TestExtractMethodAsync(""" using System.Collections.Generic; using System.Linq; @@ -11993,9 +10507,7 @@ IEnumerable Crash0(IEnumerable enumerable) } } } - """; - - var expected = """ + """, """ using System.Collections.Generic; using System.Linq; @@ -12017,15 +10529,11 @@ private static void NewMethod(IEnumerable enumerable) } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task TestUnreachableCodeModifiedBoth() - { - var code = """ + public Task TestUnreachableCodeModifiedBoth() + => TestExtractMethodAsync(""" using System.Collections.Generic; using System.Linq; @@ -12043,9 +10551,7 @@ IEnumerable Crash0(IEnumerable enumerable) } } } - """; - - var expected = """ + """, """ using System.Collections.Generic; using System.Linq; @@ -12069,15 +10575,11 @@ private static IEnumerable NewMethod(IEnumerable enumerable) } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task TestLocalFunctionParameters() - { - var code = """ + public Task TestLocalFunctionParameters() + => TestExtractMethodAsync(""" using System.Collections.Generic; using System.Linq; @@ -12094,9 +10596,7 @@ void Local(int value2) } } } - """; - - var expected = """ + """, """ using System.Collections.Generic; using System.Linq; @@ -12118,15 +10618,11 @@ private void NewMethod(int value, int value2) } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task TestDataFlowInButNoReadInside() - { - var code = """ + public Task TestDataFlowInButNoReadInside() + => TestExtractMethodAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -12154,9 +10650,7 @@ void Method(out object test) } } } - """; - - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -12195,15 +10689,11 @@ private static bool NewMethod(ref object test, bool a) } } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task AllowBestEffortForUnknownVariableDataFlow() - { - var code = """ + public Task AllowBestEffortForUnknownVariableDataFlow() + => TestExtractMethodAsync(""" class Program { void Method(out object test) @@ -12220,8 +10710,7 @@ void Method(out object test) }|] } } - """; - var expected = """ + """, """ class Program { void Method(out object test) @@ -12249,14 +10738,11 @@ private static bool NewMethod(ref object test, bool a) return true; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30750")] - public async Task ExtractMethodInInterface() - { - var code = """ + public Task ExtractMethodInInterface() + => TestExtractMethodAsync(""" interface Program { void Goo(); @@ -12266,8 +10752,7 @@ void Test() [|Goo();|] } } - """; - var expected = """ + """, """ interface Program { void Goo(); @@ -12282,22 +10767,18 @@ void NewMethod() Goo(); } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33242")] - public async Task ExtractMethodInExpressionBodiedConstructors() - { - var code = """ + public Task ExtractMethodInExpressionBodiedConstructors() + => TestExtractMethodAsync(""" class Goo { private readonly string _bar; private Goo(string bar) => _bar = [|bar|]; } - """; - var expected = """ + """, """ class Goo { private readonly string _bar; @@ -12309,22 +10790,18 @@ private static string GetBar(string bar) return bar; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33242")] - public async Task ExtractMethodInExpressionBodiedFinalizers() - { - var code = """ + public Task ExtractMethodInExpressionBodiedFinalizers() + => TestExtractMethodAsync(""" class Goo { bool finalized; ~Goo() => finalized = [|true|]; } - """; - var expected = """ + """, """ class Goo { bool finalized; @@ -12336,14 +10813,11 @@ private static bool NewMethod() return true; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethodInvolvingFunctionPointer() - { - var code = """ + public Task ExtractMethodInvolvingFunctionPointer() + => TestExtractMethodAsync(""" class C { void M(delegate*> ptr1) @@ -12352,9 +10826,7 @@ void M(delegate*> ptr1) _ = [|ptr1()|](ref s); } } - """; - - var expected = """ + """, """ class C { void M(delegate*> ptr1) @@ -12368,15 +10840,11 @@ void M(delegate*> ptr1) return ptr1(); } } - """; - - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractMethodInvolvingFunctionPointerWithTypeParameter() - { - var code = """ + public Task ExtractMethodInvolvingFunctionPointerWithTypeParameter() + => TestExtractMethodAsync(""" class C { void M(delegate* ptr1) @@ -12384,9 +10852,7 @@ void M(delegate* ptr1) _ = [|ptr1|](); } } - """; - - var expected = """ + """, """ class C { void M(delegate* ptr1) @@ -12399,18 +10865,14 @@ void M(delegate* ptr1) return ptr1; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44260")] - public async Task TopLevelStatement_ValueInAssignment() - { - var code = """ + public Task TopLevelStatement_ValueInAssignment() + => TestExtractMethodAsync(""" bool local; local = [|true|]; - """; - var expected = """ + """, """ bool local; local = NewMethod(); @@ -12418,38 +10880,28 @@ static bool NewMethod() { return true; } - """; - await TestExtractMethodAsync(code, expected, localFunction: true); - } + """, localFunction: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44260")] - public async Task TopLevelStatement_ArgumentInInvocation() - { - // Note: the cast should be simplified - // https://github.com/dotnet/roslyn/issues/44260 - - var code = """ + public Task TopLevelStatement_ArgumentInInvocation() + => TestExtractMethodAsync(""" System.Console.WriteLine([|"string"|]); - """; - var expected = """ + """, """ System.Console.WriteLine(NewMethod()); static string NewMethod() { return "string"; } - """; - await TestExtractMethodAsync(code, expected, localFunction: true); - } + """, localFunction: true); [Theory] [InlineData("unsafe")] [InlineData("checked")] [InlineData("unchecked")] [WorkItem("https://github.com/dotnet/roslyn/issues/4950")] - public async Task ExtractMethodInvolvingUnsafeBlock(string keyword) - { - var code = $$""" + public Task ExtractMethodInvolvingUnsafeBlock(string keyword) + => TestExtractMethodAsync($$""" using System; class Program { @@ -12469,8 +10921,7 @@ static void Main(string[] args) Console.WriteLine(p); } } - """; - var expected = $$""" + """, $$""" using System; class Program { @@ -12495,14 +10946,11 @@ private static IntPtr NewMethod(object value) return p; } } - """; - await TestExtractMethodAsync(code, expected); - } + """); [Fact] - public async Task ExtractRawStringLiteral_SingleLine() - { - var code = """" + public Task ExtractRawStringLiteral_SingleLine() + => TestExtractMethodAsync("""" class C { void M(int y) @@ -12510,8 +10958,7 @@ void M(int y) var s = [|"""Hello world"""|]; } } - """"; - var expected = """" + """", """" class C { void M(int y) @@ -12524,15 +10971,11 @@ private static string GetS() return """Hello world"""; } } - """"; - - await TestExtractMethodAsync(code, expected); - } + """"); [Fact] - public async Task ExtractRawStringLiteralInterpolation_SingleLine() - { - var code = """" + public Task ExtractRawStringLiteralInterpolation_SingleLine() + => TestExtractMethodAsync("""" class C { void M(int y) @@ -12540,8 +10983,7 @@ void M(int y) var s = [|$"""{y}"""|]; } } - """"; - var expected = """" + """", """" class C { void M(int y) @@ -12554,15 +10996,11 @@ private static string GetS(int y) return $"""{y}"""; } } - """"; - - await TestExtractMethodAsync(code, expected); - } + """"); [Fact] - public async Task ExtractRawStringLiteralInterpolationHole_SingleLine() - { - var code = """" + public Task ExtractRawStringLiteralInterpolationHole_SingleLine() + => TestExtractMethodAsync("""" class C { void M(int y) @@ -12570,8 +11008,7 @@ void M(int y) var s = $"""{[|y|]}"""; } } - """"; - var expected = """" + """", """" class C { void M(int y) @@ -12584,15 +11021,11 @@ private static int GetY(int y) return y; } } - """"; - - await TestExtractMethodAsync(code, expected); - } + """"); [Fact] - public async Task ExtractRawStringLiteral_MultiLine() - { - var code = """" + public Task ExtractRawStringLiteral_MultiLine() + => TestExtractMethodAsync("""" class C { void M(int y) @@ -12602,8 +11035,7 @@ Hello world """|]; } } - """"; - var expected = """" + """", """" class C { void M(int y) @@ -12618,15 +11050,11 @@ Hello world """; } } - """"; - - await TestExtractMethodAsync(code, expected); - } + """"); [Fact] - public async Task ExtractRawStringLiteralInterpolation_MultiLine() - { - var code = """" + public Task ExtractRawStringLiteralInterpolation_MultiLine() + => TestExtractMethodAsync("""" class C { void M(int y) @@ -12636,8 +11064,7 @@ void M(int y) """|]; } } - """"; - var expected = """" + """", """" class C { void M(int y) @@ -12652,15 +11079,11 @@ private static string GetS(int y) """; } } - """"; - - await TestExtractMethodAsync(code, expected); - } + """"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73044")] - public async Task CapturedPrimaryConstructorParameter() - { - var code = """" + public Task CapturedPrimaryConstructorParameter() + => TestExtractMethodAsync("""" public class Test(int value) { public int M() @@ -12668,8 +11091,7 @@ public int M() return [|value + 1|]; } } - """"; - var expected = """" + """", """" public class Test(int value) { public int M() @@ -12682,15 +11104,11 @@ private int NewMethod() return value + 1; } } - """"; - - await TestExtractMethodAsync(code, expected); - } + """"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39329")] - public async Task ExtractUsingLocalDeclaration1() - { - var code = """" + public Task ExtractUsingLocalDeclaration1() + => TestExtractMethodAsync("""" using System; public class Goo : IDisposable @@ -12707,8 +11125,7 @@ public void Dispose() { } } - """"; - var expected = """" + """", """" using System; public class Goo : IDisposable @@ -12730,15 +11147,11 @@ public void Dispose() { } } - """"; - - await TestExtractMethodAsync(code, expected); - } + """"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39329")] - public async Task ExtractUsingLocalDeclaration2() - { - var code = """" + public Task ExtractUsingLocalDeclaration2() + => TestExtractMethodAsync("""" using System; public class Goo : IDisposable @@ -12756,8 +11169,7 @@ public void Dispose() { } } - """"; - var expected = """" + """", """" using System; public class Goo : IDisposable @@ -12781,15 +11193,11 @@ public void Dispose() { } } - """"; - - await TestExtractMethodAsync(code, expected); - } + """"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39329")] - public async Task ExtractUsingLocalDeclaration3() - { - var code = """" + public Task ExtractUsingLocalDeclaration3() + => TestExtractMethodAsync("""" using System; public class Goo @@ -12801,8 +11209,7 @@ void M() using var x3 = new System.IO.MemoryStream();|] } } - """"; - var expected = """" + """", """" using System; public class Goo @@ -12819,15 +11226,11 @@ private static void NewMethod() using var x3 = new System.IO.MemoryStream(); } } - """"; - - await TestExtractMethodAsync(code, expected); - } + """"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39329")] - public async Task ExtractUsingLocalDeclaration4() - { - var code = """" + public Task ExtractUsingLocalDeclaration4() + => TestExtractMethodAsync("""" using System.Collections.Generic; class C @@ -12838,8 +11241,7 @@ bool M(IEnumerable p) return x.MoveNext();|] } } - """"; - var expected = """" + """", """" using System.Collections.Generic; class C @@ -12855,15 +11257,11 @@ private static bool NewMethod(IEnumerable p) return x.MoveNext(); } } - """"; - - await TestExtractMethodAsync(code, expected); - } + """"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18656")] - public async Task TestSelectionMidwayThroughTwoStatements() - { - var code = """" + public Task TestSelectionMidwayThroughTwoStatements() + => TestExtractMethodAsync("""" class C { static void Main(string[] args) @@ -12893,8 +11291,7 @@ class Item { public bool IsSelected { get; set; } } - """"; - var expected = """" + """", """" class C { static void Main(string[] args) @@ -12930,15 +11327,11 @@ class Item { public bool IsSelected { get; set; } } - """"; - - await TestExtractMethodAsync(code, expected); - } + """"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70024")] - public async Task TestAliasedType() - { - var code = """" + public Task TestAliasedType() + => TestExtractMethodAsync("""" using System; using Spec = System.Collections.Specialized; @@ -12954,8 +11347,7 @@ public void Method() } } } - """"; - var expected = """" + """", """" using System; using Spec = System.Collections.Specialized; @@ -12976,8 +11368,5 @@ private static void NewMethod(Spec.ListDictionary value) } } } - """"; - - await TestExtractMethodAsync(code, expected); - } + """"); } diff --git a/src/EditorFeatures/CSharpTest/ExtractMethod/SelectionValidatorTests.cs b/src/EditorFeatures/CSharpTest/ExtractMethod/SelectionValidatorTests.cs index 07a5485eeb6c4..69552336c7ac5 100644 --- a/src/EditorFeatures/CSharpTest/ExtractMethod/SelectionValidatorTests.cs +++ b/src/EditorFeatures/CSharpTest/ExtractMethod/SelectionValidatorTests.cs @@ -14,159 +14,119 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ExtractMethod; public sealed class SelectionValidatorTests : ExtractMethodBase { [Fact] - public async Task SelectionTest1() - { - var code = """ + public Task SelectionTest1() + => TestSelectionAsync(""" {|b:using System;|} - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest2() - { - var code = """ + public Task SelectionTest2() + => TestSelectionAsync(""" {|b:namespace A|} { } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest3() - { - var code = """ + public Task SelectionTest3() + => TestSelectionAsync(""" namespace {|b:A|} { } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest4() - { - var code = """ + public Task SelectionTest4() + => TestSelectionAsync(""" {|b:class|} A { } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest5() - { - var code = """ + public Task SelectionTest5() + => TestSelectionAsync(""" class {|b:A|} { } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest6() - { - var code = """ + public Task SelectionTest6() + => TestSelectionAsync(""" class A : {|b:object|} { } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest7() - { - var code = """ + public Task SelectionTest7() + => TestSelectionAsync(""" class A : object, {|b:IDisposable|} { } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest8() - { - var code = """ + public Task SelectionTest8() + => TestSelectionAsync(""" class A<{|b:T|}> { } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest9() - { - var code = """ + public Task SelectionTest9() + => TestSelectionAsync(""" class A where {|b:T|} : class { } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest10() - { - var code = """ + public Task SelectionTest10() + => TestSelectionAsync(""" class A where T : {|b:IDisposable|} { } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest11() - { - var code = """ + public Task SelectionTest11() + => TestSelectionAsync(""" class A { {|b:A|} Method() { } } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest12() - { - var code = """ + public Task SelectionTest12() + => TestSelectionAsync(""" class A { A Method({|b:A|} a) { } } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest13() - { - var code = """ + public Task SelectionTest13() + => TestSelectionAsync(""" class A { A Method(A {|b:a|}) { } } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest14() - { - var code = """ + public Task SelectionTest14() + => TestSelectionAsync(""" class A { [{|b:Goo|}] @@ -174,14 +134,11 @@ A Method(A a) { } } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest15() - { - var code = """ + public Task SelectionTest15() + => TestSelectionAsync(""" class A { [Goo({|b:A|}=1)] @@ -189,14 +146,11 @@ A Method(A a) { } } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest16() - { - var code = """ + public Task SelectionTest16() + => TestSelectionAsync(""" class A { [Goo(A={|b:1|})] @@ -204,74 +158,56 @@ A Method(A a) { } } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest17() - { - var code = """ + public Task SelectionTest17() + => TestSelectionAsync(""" class A { const int {|b:i|} = 1; } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest18() - { - var code = """ + public Task SelectionTest18() + => TestSelectionAsync(""" class A { const {|b:int|} i = 1; } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest19() - { - var code = """ + public Task SelectionTest19() + => TestSelectionAsync(""" class A { const int i = {|b:1|}; } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest20() - { - var code = """ + public Task SelectionTest20() + => TestSelectionAsync(""" class A { const int i = {|r:{|b:1 + |}2|}; } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest21() - { - var code = """ + public Task SelectionTest21() + => TestSelectionAsync(""" class A { const int {|b:i = 1 + |}2; } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest22() - { - var code = """ + public Task SelectionTest22() + => TestSelectionAsync(""" class A { void Method1() @@ -284,14 +220,11 @@ void Method2() int b = 2;|} } } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest23() - { - var code = """ + public Task SelectionTest23() + => TestSelectionAsync(""" class A { void Method1() @@ -299,14 +232,11 @@ void Method1() {|b:int i = 1; }|} } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest24() - { - var code = """ + public Task SelectionTest24() + => TestSelectionAsync(""" class A { void Method1() @@ -316,14 +246,11 @@ void Method1() #endRegion } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectionTest25() - { - var code = """ + public Task SelectionTest25() + => TestSelectionAsync(""" class A { void Method1() @@ -333,14 +260,11 @@ void Method1() #endRegion } } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest26() - { - var code = """ + public Task SelectionTest26() + => TestSelectionAsync(""" class A { void Method1() @@ -350,14 +274,11 @@ void Method1() #endregion|} } } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest27() - { - var code = """ + public Task SelectionTest27() + => TestSelectionAsync(""" class A { void Method1() @@ -367,14 +288,11 @@ void Method1() int i = 1;|} } } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest28() - { - var code = """ + public Task SelectionTest28() + => TestSelectionAsync(""" class A { void Method1() @@ -384,14 +302,11 @@ void Method1() #endif|} } } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest29() - { - var code = """ + public Task SelectionTest29() + => TestSelectionAsync(""" class A { void Method1() @@ -401,14 +316,11 @@ void Method1() #endif } } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest30() - { - var code = """ + public Task SelectionTest30() + => TestSelectionAsync(""" class A { void Method1() @@ -418,14 +330,11 @@ void Method1() int i = 1;|} } } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest31() - { - var code = """ + public Task SelectionTest31() + => TestSelectionAsync(""" class A { void Method1() @@ -436,14 +345,11 @@ void Method1() #endif } } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest32() - { - var code = """ + public Task SelectionTest32() + => TestSelectionAsync(""" class A { void Method1() @@ -454,14 +360,11 @@ void Method1() #endif } } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest33() - { - var code = """ + public Task SelectionTest33() + => TestSelectionAsync(""" class A { void Method1() @@ -471,14 +374,11 @@ void Method1() #endif|} } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectionTest34() - { - var code = """ + public Task SelectionTest34() + => TestSelectionAsync(""" class A { void Method1() @@ -488,14 +388,11 @@ void Method1() #endregion|} } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectionTest35() - { - var code = """ + public Task SelectionTest35() + => TestSelectionAsync(""" class A { void Method1() @@ -503,14 +400,11 @@ void Method1() {|b:// test|} } } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest36() - { - var code = """ + public Task SelectionTest36() + => TestSelectionAsync(""" class A { IEnumerable Method1() @@ -518,14 +412,11 @@ IEnumerable Method1() {|r:{|b:yield return 1;|}|} } } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest37() - { - var code = """ + public Task SelectionTest37() + => TestSelectionAsync(""" class A { void Method1() @@ -539,14 +430,11 @@ void Method1() } } } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectionTest38() - { - var code = """ + public Task SelectionTest38() + => TestSelectionAsync(""" class A { void Method1() @@ -560,14 +448,11 @@ void Method1() } } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540082")] - public async Task SelectionTest39() - { - var code = """ + public Task SelectionTest39() + => TestSelectionAsync(""" class A { void Method1() @@ -575,14 +460,11 @@ void Method1() {|r:{|b:System|}.Console.WriteLine(1);|} } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540082")] - public async Task SelectionTest40() - { - var code = """ + public Task SelectionTest40() + => TestSelectionAsync(""" class A { void Method1() @@ -590,14 +472,11 @@ void Method1() {|r:{|b:System.Console|}.WriteLine(1);|} } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540082")] - public async Task SelectionTest41() - { - var code = """ + public Task SelectionTest41() + => TestSelectionAsync(""" class A { void Method1() @@ -605,14 +484,11 @@ void Method1() {|r:{|b:System.Console.WriteLine|}(1);|} } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540082")] - public async Task SelectionTest42() - { - var code = """ + public Task SelectionTest42() + => TestSelectionAsync(""" class A { void Method1() @@ -620,14 +496,11 @@ void Method1() {|r: System.{|b:Console|}.WriteLine(1);|} } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540082")] - public async Task SelectionTest43() - { - var code = """ + public Task SelectionTest43() + => TestSelectionAsync(""" class A { void Method1() @@ -635,14 +508,11 @@ void Method1() {|r: System.{|b:Console.WriteLine|}(1);|} } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540082")] - public async Task SelectionTest44() - { - var code = """ + public Task SelectionTest44() + => TestSelectionAsync(""" class A { void Method1() @@ -650,14 +520,11 @@ void Method1() {|r: System.Console.{|b:WriteLine|}(1);|} } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539242")] - public async Task SelectionTest45() - { - var code = """ + public Task SelectionTest45() + => TestSelectionAsync(""" class A { void Method1() @@ -665,14 +532,11 @@ void Method1() short[,] arr = new short[,] { {|r:{|b:{ 19, 19, 19 }|}|}, { 19, 19, 19 } }; } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539242")] - public async Task SelectionTest46() - { - var code = """ + public Task SelectionTest46() + => TestSelectionAsync(""" class A { void Method1() @@ -680,14 +544,11 @@ void Method1() short[,] arr = { {|r:{|b:{ 19, 19, 19 }|}|}s, { 19, 19, 19 } }; } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540338")] - public async Task SelectionTest47() - { - var code = """ + public Task SelectionTest47() + => TestSelectionAsync(""" using System; class C { @@ -697,14 +558,11 @@ void M() {|b:d +=|} } } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact] - public async Task SelectIfWithReturn() - { - await TestExtractMethodAsync(""" + public Task SelectIfWithReturn() + => TestExtractMethodAsync(""" class A { public void Method1() @@ -737,12 +595,10 @@ private static bool NewMethod(bool b) } } """); - } [Fact] - public async Task SelectConstIfWithReturn() - { - var code = """ + public Task SelectConstIfWithReturn() + => TestSelectionAsync(""" class A { public void Method1() @@ -753,14 +609,11 @@ public void Method1() Console.WriteLine(); } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectReturnButNotAllCodePathsContainAReturn() - { - await TestExtractMethodAsync(""" + public Task SelectReturnButNotAllCodePathsContainAReturn() + => TestExtractMethodAsync(""" class A { public void Method1(bool b1, bool b2) @@ -799,12 +652,10 @@ private static bool NewMethod(bool b2) } } """); - } [Fact] - public async Task SelectIfBranchWhereNotAllPathsReturn() - { - await TestExtractMethodAsync(""" + public Task SelectIfBranchWhereNotAllPathsReturn() + => TestExtractMethodAsync(""" class A { int Method8(int i) @@ -856,12 +707,10 @@ private static (bool flowControl, int value) NewMethod(ref int i) } } """); - } [Fact] - public async Task SelectCatchFilterClause() - { - var code = """ + public Task SelectCatchFilterClause() + => TestSelectionAsync(""" class A { int method() @@ -876,14 +725,11 @@ int method() } } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectCatchFilterClause2() - { - var code = """ + public Task SelectCatchFilterClause2() + => TestSelectionAsync(""" class A { int method() @@ -900,14 +746,11 @@ int method() } } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectWithinCatchFilterClause() - { - var code = """ + public Task SelectWithinCatchFilterClause() + => TestSelectionAsync(""" class A { int method() @@ -922,14 +765,11 @@ int method() } } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectWithinCatchFilterClause2() - { - var code = """ + public Task SelectWithinCatchFilterClause2() + => TestSelectionAsync(""" class A { int method() @@ -944,14 +784,11 @@ int method() } } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectLValueOfPlusEqualsOperator() - { - var code = """ + public Task SelectLValueOfPlusEqualsOperator() + => TestSelectionAsync(""" class A { int method() @@ -961,14 +798,11 @@ int method() return i; } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectRValueOfPlusEqualsOperator() - { - var code = """ + public Task SelectRValueOfPlusEqualsOperator() + => TestSelectionAsync(""" class A { int method() @@ -978,14 +812,11 @@ int method() return i; } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectRValueOfPredecrementOperator() - { - var code = """ + public Task SelectRValueOfPredecrementOperator() + => TestSelectionAsync(""" class A { string method(string s, int i) @@ -996,14 +827,11 @@ string method(string s, int i) return myvar[i]; } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectArrayWithDecrementIndex() - { - var code = """ + public Task SelectArrayWithDecrementIndex() + => TestSelectionAsync(""" class A { string method(string s, int i) @@ -1014,14 +842,11 @@ string method(string s, int i) return myvar[i]; } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectCastOperator() - { - var code = """ + public Task SelectCastOperator() + => TestSelectionAsync(""" class A { int method(string goo) @@ -1030,14 +855,11 @@ int method(string goo) return bar.Length; } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectLHSOfPostIncrementOperator() - { - var code = """ + public Task SelectLHSOfPostIncrementOperator() + => TestSelectionAsync(""" class A { int method(int i) @@ -1045,14 +867,11 @@ int method(int i) return {|r:{|b:i|}++|}; } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectPostIncrementOperator() - { - var code = """ + public Task SelectPostIncrementOperator() + => TestSelectionAsync(""" class A { int method(int i) @@ -1060,14 +879,11 @@ int method(int i) return {|r:i{|b:++|}|}; } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectRHSOfPreIncrementOperator() - { - var code = """ + public Task SelectRHSOfPreIncrementOperator() + => TestSelectionAsync(""" class A { int method(int i) @@ -1075,14 +891,11 @@ int method(int i) return {|r:{|b:++|}i|}; } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectPreIncrementOperator() - { - var code = """ + public Task SelectPreIncrementOperator() + => TestSelectionAsync(""" class A { int method(int i) @@ -1090,14 +903,11 @@ int method(int i) return {|r:{|b:++|}i|}; } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectPreDecrementOperator() - { - var code = """ + public Task SelectPreDecrementOperator() + => TestSelectionAsync(""" class A { int method(int i) @@ -1105,14 +915,11 @@ int method(int i) return {|r:{|b:--|}i|}; } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectLHSOfPostDecrementOperator() - { - var code = """ + public Task SelectLHSOfPostDecrementOperator() + => TestSelectionAsync(""" class A { int method(int i) @@ -1120,14 +927,11 @@ int method(int i) return {|r:{|b:i|}--|}; } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectUnaryPlusOperator() - { - var code = """ + public Task SelectUnaryPlusOperator() + => TestSelectionAsync(""" class A { int method(int i) @@ -1136,14 +940,11 @@ int method(int i) return j; } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectUnaryMinusOperator() - { - var code = """ + public Task SelectUnaryMinusOperator() + => TestSelectionAsync(""" class A { int method(int i) @@ -1152,14 +953,11 @@ int method(int i) return j; } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectLogicalNegationOperator() - { - var code = """ + public Task SelectLogicalNegationOperator() + => TestSelectionAsync(""" class A { int method(int i) @@ -1168,14 +966,11 @@ int method(int i) return j; } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectBitwiseNegationOperator() - { - var code = """ + public Task SelectBitwiseNegationOperator() + => TestSelectionAsync(""" class A { int method(int i) @@ -1184,14 +979,11 @@ int method(int i) return j; } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectCastOperator2() - { - var code = """ + public Task SelectCastOperator2() + => TestSelectionAsync(""" class A { int method(double i) @@ -1200,14 +992,11 @@ int method(double i) return j; } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectInvalidSubexpressionToExpand() - { - var code = """ + public Task SelectInvalidSubexpressionToExpand() + => TestSelectionAsync(""" class A { public int method(int a, int b, int c) @@ -1215,14 +1004,11 @@ public int method(int a, int b, int c) return {|r:a + {|b:b + c|}|}; } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectValidSubexpressionAndHenceDoNotExpand() - { - var code = """ + public Task SelectValidSubexpressionAndHenceDoNotExpand() + => TestSelectionAsync(""" class A { public int method(int a, int b, int c) @@ -1230,14 +1016,11 @@ public int method(int a, int b, int c) return {|b:a + b|} + c; } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectLHSOfMinusEqualsOperator() - { - var code = """ + public Task SelectLHSOfMinusEqualsOperator() + => TestSelectionAsync(""" class A { public int method(int a, int b) @@ -1246,14 +1029,11 @@ public int method(int a, int b) return a; } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectInnerBlockPartially() - { - var code = """ + public Task SelectInnerBlockPartially() + => TestSelectionAsync(""" using System; using System.Collections; @@ -1272,14 +1052,11 @@ void method() } } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectInnerBlockWithoutBracesPartially() - { - var code = """ + public Task SelectInnerBlockWithoutBracesPartially() + => TestSelectionAsync(""" using System; using System.Collections; @@ -1296,14 +1073,11 @@ void method() } } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectBeginningBrace() - { - var code = """ + public Task SelectBeginningBrace() + => TestSelectionAsync(""" using System; using System.Collections; @@ -1314,14 +1088,11 @@ void method() if (true) {|r:{|b:{|} }|} } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectAcrossBlocks1() - { - var code = """ + public Task SelectAcrossBlocks1() + => TestSelectionAsync(""" using System; using System.Collections; @@ -1339,14 +1110,11 @@ void method() } } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectMethodParameters() - { - var code = """ + public Task SelectMethodParameters() + => TestSelectionAsync(""" using System; using System.Collections; @@ -1365,14 +1133,11 @@ double sum(ref double x, double y, double z) return x + y + z; } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectChainedInvocations1() - { - var code = """ + public Task SelectChainedInvocations1() + => TestSelectionAsync(""" using System; using System.Collections; @@ -1396,14 +1161,11 @@ void method() {|b:a.b|}.c(); } } - """; - await TestSelectionAsync(code); - } + """); [Fact] - public async Task SelectChainedInvocations2() - { - var code = """ + public Task SelectChainedInvocations2() + => TestSelectionAsync(""" using System; using System.Collections; @@ -1427,14 +1189,11 @@ void method() {|r: a.{|b:b.c()|}|}; } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540474")] - public async Task GotoStatement() - { - var code = """ + public Task GotoStatement() + => TestSelectionAsync(""" using System; using System.Reflection.Emit; @@ -1451,53 +1210,41 @@ static void Main(string[] args) }|}; } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540481")] - public async Task BugFix6750() - { - var code = """ + public Task BugFix6750() + => TestSelectionAsync(""" using System; class Program { int[] array = new int[{|b:1|}]; } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540481")] - public async Task BugFix6750_1() - { - var code = """ + public Task BugFix6750_1() + => TestSelectionAsync(""" using System; class Program { int[] array = new int[{|r:{|b:1|}|}] { 1 }; } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542201")] - public async Task MalformedCode_NoOuterType() - { - var code = """ + public Task MalformedCode_NoOuterType() + => TestSelectionAsync(""" x(a){ {|b:for ();|} } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542210")] - public async Task NoQueryContinuation() - { - var code = """ + public Task NoQueryContinuation() + => TestSelectionAsync(""" using System.Linq; class P @@ -1510,9 +1257,7 @@ select x into y {|b:select y|}|}; } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542722")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540787")] @@ -1520,21 +1265,17 @@ public async Task DoNotCrash() => await IterateAllAsync(TestResource.AllInOneCSharpCode); [Fact, WorkItem(9931, "DevDiv_Projects/Roslyn")] - public async Task ExtractMethodIdentifierAtEndOfInteractiveBuffer() - { - var code = """ + public Task ExtractMethodIdentifierAtEndOfInteractiveBuffer() + => TestSelectionAsync(""" using System.Console; WriteLine(); {|r:{|b:Diagnostic|}|} - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543020")] - public async Task MemberAccessStructAsExpression() - { - var code = """ + public Task MemberAccessStructAsExpression() + => TestSelectionAsync(""" struct S { public float X; @@ -1565,14 +1306,11 @@ private static S GetS() return new S(); } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543140")] - public async Task TypeOfExpression() - { - var code = """ + public Task TypeOfExpression() + => TestSelectionAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -1584,47 +1322,35 @@ static void Main(string[] args) Console.WriteLine({|r:typeof({|b:Dictionary<,>|})|}.IsGenericTypeDefinition); } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543186")] - public async Task AnonymousTypeMember1() - { - var code = """ + public Task AnonymousTypeMember1() + => TestSelectionAsync(""" using System; class C { void M() { {|r:var x = new { {|b:String|} = true };|} } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543186")] - public async Task AnonymousTypeMember2() - { - var code = """ + public Task AnonymousTypeMember2() + => TestSelectionAsync(""" using System; class C { void M() { var String = 1; var x = new { {|r:{|b:String|}|} }; } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543186")] - public async Task AnonymousTypeMember3() - { - var code = """ + public Task AnonymousTypeMember3() + => TestSelectionAsync(""" using System; class C { void M() { var x = new { String = {|b:true|} }; } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543186")] - public async Task AnonymousTypeMember4() - { - var code = """ + public Task AnonymousTypeMember4() + => TestSelectionAsync(""" class Program { static void Main(string[] args) @@ -1642,14 +1368,11 @@ static void Main(string[] args) }|}; } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543984")] - public async Task AddressOfExpr1() - { - var code = """ + public Task AddressOfExpr1() + => TestSelectionAsync(""" class C { unsafe void M() @@ -1658,14 +1381,11 @@ unsafe void M() int* j = {|r:&{|b:i|}|}; } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543984")] - public async Task AddressOfExpr2() - { - var code = """ + public Task AddressOfExpr2() + => TestSelectionAsync(""" class C { unsafe void M() @@ -1674,14 +1394,11 @@ unsafe void M() int* j = {|b:&i|}; } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544627")] - public async Task BaseKeyword() - { - var code = """ + public Task BaseKeyword() + => TestSelectionAsync(""" class C { void Goo() @@ -1689,14 +1406,11 @@ void Goo() {|r:{|b:base|}.ToString();|} } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545057")] - public async Task RefvalueKeyword() - { - var code = """ + public Task RefvalueKeyword() + => TestSelectionAsync(""" using System; class A @@ -1709,14 +1423,11 @@ static void Goo(__arglist) Console.WriteLine({|r:__refvalue(typedReference, {|b:Int32|})|}); } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531286")] - public async Task NoCrashOnThrowWithoutCatchClause() - { - var code = """ + public Task NoCrashOnThrowWithoutCatchClause() + => TestSelectionAsync(""" public class Test { delegate int D(); @@ -1733,14 +1444,11 @@ static void Main() return 1; } } - """; - await TestSelectionAsync(code, expectedFail: true); - } + """, expectedFail: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/751")] - public async Task SimpleConditionalAccessExpressionSelectFirstExpression() - { - var code = """ + public Task SimpleConditionalAccessExpressionSelectFirstExpression() + => TestSelectionAsync(""" using System; class Program { @@ -1754,14 +1462,11 @@ class A { public int Length { get; internal set; } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/751")] - public async Task SimpleConditionalAccessExpressionSelectSecondExpression() - { - var code = """ + public Task SimpleConditionalAccessExpressionSelectSecondExpression() + => TestSelectionAsync(""" using System; class Program { @@ -1775,14 +1480,11 @@ class A { public int Length { get; internal set; } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/751")] - public async Task NestedConditionalAccessExpressionWithMemberBindingExpression() - { - var code = """ + public Task NestedConditionalAccessExpressionWithMemberBindingExpression() + => TestSelectionAsync(""" using System; class Program @@ -1801,14 +1503,11 @@ class B { public int Length { get; set; } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/751")] - public async Task NestedConditionalAccessExpressionWithMemberBindingExpressionSelectSecondExpression() - { - var code = """ + public Task NestedConditionalAccessExpressionWithMemberBindingExpressionSelectSecondExpression() + => TestSelectionAsync(""" using System; class Program @@ -1827,14 +1526,11 @@ class B { public int Length { get; set; } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/751")] - public async Task NestedConditionalAccessExpressionWithInvocationExpression() - { - var code = """ + public Task NestedConditionalAccessExpressionWithInvocationExpression() + => TestSelectionAsync(""" using System; class Program @@ -1856,16 +1552,13 @@ class B { public int Length { get; set; } } - """; - await TestSelectionAsync(code); - } + """); [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1228916")] public async Task DoNotCrashPastEndOfLine() { // 11 1 // 012345678901 2 - var code = "class C { }\r\n"; // Markup parsing doesn't produce the right spans here, so supply one ourselves. // Can be removed when https://github.com/dotnet/roslyn-sdk/issues/637 is fixed @@ -1873,6 +1566,6 @@ public async Task DoNotCrashPastEndOfLine() // This span covers just the "\n" var span = new TextSpan(12, 1); - await TestSelectionAsync(code, expectedFail: true, textSpanOverride: span); + await TestSelectionAsync("class C { }\r\n", expectedFail: true, textSpanOverride: span); } } diff --git a/src/EditorFeatures/CSharpTest/Formatting/CSharpNewDocumentFormattingServiceTests.cs b/src/EditorFeatures/CSharpTest/Formatting/CSharpNewDocumentFormattingServiceTests.cs index f4f05f8370c69..c6ebc3bc02637 100644 --- a/src/EditorFeatures/CSharpTest/Formatting/CSharpNewDocumentFormattingServiceTests.cs +++ b/src/EditorFeatures/CSharpTest/Formatting/CSharpNewDocumentFormattingServiceTests.cs @@ -34,9 +34,8 @@ protected override EditorTestWorkspace CreateTestWorkspace(string testCode, Pars => EditorTestWorkspace.CreateCSharp(testCode, parseOptions); [Fact] - public async Task TestFileScopedNamespaces() - { - await TestAsync(testCode: """ + public Task TestFileScopedNamespaces() + => TestAsync(testCode: """ namespace Goo { internal class C @@ -56,7 +55,6 @@ internal class C { CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error) } }, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp10)); - } [Fact] public async Task TestFileScopedNamespaces_Invalid_MultipleNamespaces() @@ -105,26 +103,26 @@ await TestAsync( [Theory] [MemberData(nameof(EndOfDocumentSequences))] - public async Task TestBlockScopedNamespaces(string endOfDocumentSequence) - { - await TestAsync(testCode: $@" -namespace Goo; - -internal class C -{{ -}}{endOfDocumentSequence}", - expected: $@" -namespace Goo -{{ - internal class C - {{ - }} -}}{endOfDocumentSequence}", + public Task TestBlockScopedNamespaces(string endOfDocumentSequence) + => TestAsync(testCode: $$""" + namespace Goo; + + internal class C + { + }{{endOfDocumentSequence}} + """, + expected: $$""" + namespace Goo + { + internal class C + { + } + }{{endOfDocumentSequence}} + """, options: new OptionsCollection(LanguageNames.CSharp) { { CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2(NamespaceDeclarationPreference.BlockScoped, NotificationOption2.Error) } }); - } [Fact] public async Task TestOrganizeUsingsWithNoUsings() @@ -144,9 +142,8 @@ await TestAsync( } [Fact] - public async Task TestFileBanners() - { - await TestAsync(testCode: """ + public Task TestFileBanners() + => TestAsync(testCode: """ using System; namespace Goo @@ -166,12 +163,10 @@ namespace Goo { { CodeStyleOptions2.FileHeaderTemplate, "This is a banner." } }); - } [Fact] - public async Task TestAccessibilityModifiers() - { - await TestAsync(testCode: """ + public Task TestAccessibilityModifiers() + => TestAsync(testCode: """ using System; namespace Goo @@ -195,12 +190,10 @@ internal class C { { CodeStyleOptions2.AccessibilityModifiersRequired, new CodeStyleOption2(AccessibilityModifiersRequired.Always, NotificationOption2.Error) } }); - } [Fact] - public async Task TestAccessibilityModifiers_FileScopedNamespace() - { - await TestAsync(testCode: """ + public Task TestAccessibilityModifiers_FileScopedNamespace() + => TestAsync(testCode: """ using System; namespace Goo @@ -223,12 +216,10 @@ internal class C { CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error) }, { CodeStyleOptions2.AccessibilityModifiersRequired, new CodeStyleOption2(AccessibilityModifiersRequired.Always, NotificationOption2.Error) } }); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/55703")] - public async Task TestAccessibilityModifiers_IgnoresPartial() - { - await TestAsync( + public Task TestAccessibilityModifiers_IgnoresPartial() + => TestAsync( testCode: """ using System; @@ -269,12 +260,10 @@ internal class D { { CodeStyleOptions2.AccessibilityModifiersRequired, new CodeStyleOption2(AccessibilityModifiersRequired.Always, NotificationOption2.Error) } }); - } [Fact] - public async Task TestUsingDirectivePlacement() - { - await TestAsync(testCode: """ + public Task TestUsingDirectivePlacement() + => TestAsync(testCode: """ using System; namespace Goo @@ -291,12 +280,10 @@ namespace Goo { { CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, new CodeStyleOption2(AddImportPlacement.InsideNamespace, NotificationOption2.Error) } }); - } [Fact] - public async Task TestPreferTopLevelStatements() - { - await TestAsync(testCode: """ + public Task TestPreferTopLevelStatements() + => TestAsync(testCode: """ using System; // See https://aka.ms/new-console-template for more information @@ -312,12 +299,10 @@ await TestAsync(testCode: """ { { CSharpCodeStyleOptions.PreferTopLevelStatements, new CodeStyleOption2(value: true, notification: NotificationOption2.Suggestion) } }); - } [Fact] - public async Task TestPreferProgramMain() - { - await TestAsync(testCode: """ + public Task TestPreferProgramMain() + => TestAsync(testCode: """ using System; // See https://aka.ms/new-console-template for more information @@ -338,5 +323,4 @@ private static void Main(string[] args) { { CSharpCodeStyleOptions.PreferTopLevelStatements, new CodeStyleOption2(value: false, notification: NotificationOption2.Suggestion) } }); - } } diff --git a/src/EditorFeatures/CSharpTest/Formatting/CodeCleanupTests.cs b/src/EditorFeatures/CSharpTest/Formatting/CodeCleanupTests.cs index 205244c113f71..6e0adae5cab77 100644 --- a/src/EditorFeatures/CSharpTest/Formatting/CodeCleanupTests.cs +++ b/src/EditorFeatures/CSharpTest/Formatting/CodeCleanupTests.cs @@ -37,48 +37,32 @@ public sealed partial class CodeCleanupTests [Fact] public Task RemoveUsings() { - var code = """ + return AssertCodeCleanupResult(""" using System; - using System.Collections.Generic; - class Program + internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { Console.WriteLine(); } } - """; - - var expected = """ + """, """ using System; - internal class Program + using System.Collections.Generic; + class Program { - private static void Main(string[] args) + static void Main(string[] args) { Console.WriteLine(); } } - """; - return AssertCodeCleanupResult(expected, code); + """); } [Fact] public Task SortUsings() { - var code = """ - using System.Collections.Generic; - using System; - class Program - { - static void Main(string[] args) - { - var list = new List(); - Console.WriteLine(list.Count); - } - } - """; - - var expected = """ + return AssertCodeCleanupResult(""" using System; using System.Collections.Generic; internal class Program @@ -89,31 +73,24 @@ private static void Main(string[] args) Console.WriteLine(list.Count); } } - """; - return AssertCodeCleanupResult(expected, code); - } - - [Fact] - public Task SortGlobalUsings() - { - var code = """ - using System.Threading.Tasks; - using System.Threading; - global using System.Collections.Generic; - global using System; + """, """ + using System.Collections.Generic; + using System; class Program { - static Task Main(string[] args) + static void Main(string[] args) { - Barrier b = new Barrier(0); var list = new List(); Console.WriteLine(list.Count); - b.Dispose(); } } - """; + """); + } - var expected = """ + [Fact] + public Task SortGlobalUsings() + { + return AssertCodeCleanupResult(""" global using System; global using System.Collections.Generic; using System.Threading; @@ -128,15 +105,30 @@ private static Task Main(string[] args) b.Dispose(); } } - """; - return AssertCodeCleanupResult(expected, code); + """, """ + using System.Threading.Tasks; + using System.Threading; + global using System.Collections.Generic; + global using System; + class Program + { + static Task Main(string[] args) + { + Barrier b = new Barrier(0); + var list = new List(); + Console.WriteLine(list.Count); + b.Dispose(); + } + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36984")] public Task GroupUsings() { - var code = """ + return AssertCodeCleanupResult(""" using M; + using System; internal class Program @@ -145,7 +137,7 @@ private static void Main(string[] args) { Console.WriteLine("Hello World!"); - new Goo(); + _ = new Goo(); } } @@ -153,11 +145,8 @@ namespace M { public class Goo { } } - """; - - var expected = """ + """, """ using M; - using System; internal class Program @@ -166,7 +155,7 @@ private static void Main(string[] args) { Console.WriteLine("Hello World!"); - _ = new Goo(); + new Goo(); } } @@ -174,24 +163,24 @@ namespace M { public class Goo { } } - """; - return AssertCodeCleanupResult(expected, code, systemUsingsFirst: false, separateUsingGroups: true); + """, systemUsingsFirst: false, separateUsingGroups: true); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36984")] public Task SortAndGroupUsings() { - var code = """ - using M; + return AssertCodeCleanupResult(""" using System; + using M; + internal class Program { private static void Main(string[] args) { Console.WriteLine("Hello World!"); - new Goo(); + _ = new Goo(); } } @@ -199,12 +188,9 @@ namespace M { public class Goo { } } - """; - - var expected = """ - using System; - + """, """ using M; + using System; internal class Program { @@ -212,7 +198,7 @@ private static void Main(string[] args) { Console.WriteLine("Hello World!"); - _ = new Goo(); + new Goo(); } } @@ -220,98 +206,91 @@ namespace M { public class Goo { } } - """; - return AssertCodeCleanupResult(expected, code, systemUsingsFirst: true, separateUsingGroups: true); + """, systemUsingsFirst: true, separateUsingGroups: true); } [Fact] public Task FixAddRemoveBraces() { - var code = """ - class Program + return AssertCodeCleanupResult(""" + internal class Program { - int Method() + private int Method() { int a = 0; if (a > 0) - a ++; + { + a++; + } return a; } } - """; - var expected = """ - internal class Program + """, """ + class Program { - private int Method() + int Method() { int a = 0; if (a > 0) - { - a++; - } + a ++; return a; } } - """; - return AssertCodeCleanupResult(expected, code); + """); } [Fact] public Task RemoveUnusedVariable() { - var code = """ - class Program + return AssertCodeCleanupResult(""" + internal class Program { - void Method() + private void Method() { - int a; } } - """; - var expected = """ - internal class Program + """, """ + class Program { - private void Method() + void Method() { + int a; } } - """; - return AssertCodeCleanupResult(expected, code); + """); } [Fact] public Task FixAccessibilityModifiers() { - var code = """ - class Program + return AssertCodeCleanupResult(""" + internal class Program { - void Method() + private void Method() { - int a; } } - """; - var expected = """ - internal class Program + """, """ + class Program { - private void Method() + void Method() { + int a; } } - """; - return AssertCodeCleanupResult(expected, code); + """); } [Fact] public Task FixUsingPlacementPreferOutside() { - var code = """ + return AssertCodeCleanupResult(""" + using System; + namespace A { - using System; - internal class Program { private void Method() @@ -320,13 +299,11 @@ private void Method() } } } - """; - - var expected = """ - using System; - + """, """ namespace A { + using System; + internal class Program { private void Method() @@ -335,19 +312,17 @@ private void Method() } } } - """; - - return AssertCodeCleanupResult(expected, code); + """); } [Fact] public Task FixUsingPlacementPreferInside() { - var code = """ - using System; - + return AssertCodeCleanupResult(""" namespace A { + using System; + internal class Program { private void Method() @@ -356,13 +331,11 @@ private void Method() } } } - """; + """, """ + using System; - var expected = """ namespace A { - using System; - internal class Program { private void Method() @@ -371,9 +344,7 @@ private void Method() } } } - """; - - return AssertCodeCleanupResult(expected, code, InsideNamespaceOption); + """, InsideNamespaceOption); } [Fact] @@ -425,54 +396,49 @@ private void Method() [Fact] public Task FixUsingPlacementMixedPreferOutside() { - var code = """ + return AssertCodeCleanupResult(""" using System; + using System.Collections.Generic; namespace A { - using System.Collections.Generic; - internal class Program { private void Method() { Console.WriteLine(); - List list = new List(); + List list = []; Console.WriteLine(list.Length); } } } - """; - - var expected = """ + """, """ using System; - using System.Collections.Generic; namespace A { + using System.Collections.Generic; + internal class Program { private void Method() { Console.WriteLine(); - List list = []; + List list = new List(); Console.WriteLine(list.Length); } } } - """; - - return AssertCodeCleanupResult(expected, code, OutsideNamespaceOption); + """, OutsideNamespaceOption); } [Fact] public Task FixUsingPlacementMixedPreferInside() { - var code = """ - using System; - + return AssertCodeCleanupResult(""" namespace A { + using System; using System.Collections.Generic; internal class Program @@ -480,17 +446,16 @@ internal class Program private void Method() { Console.WriteLine(); - List list = new(); + List list = []; Console.WriteLine(list.Length); } } } - """; + """, """ + using System; - var expected = """ namespace A { - using System; using System.Collections.Generic; internal class Program @@ -498,14 +463,12 @@ internal class Program private void Method() { Console.WriteLine(); - List list = []; + List list = new(); Console.WriteLine(list.Length); } } } - """; - - return AssertCodeCleanupResult(expected, code, InsideNamespaceOption); + """, InsideNamespaceOption); } [Fact] @@ -724,44 +687,32 @@ public void M1(int x, int y) """; [Fact] - public async Task RunThirdPartyFixer() - { - await TestThirdPartyCodeFixerApplied(_code, _fixed); - } + public Task RunThirdPartyFixer() + => TestThirdPartyCodeFixerApplied(_code, _fixed); [Fact] - public async Task DoNotRunThirdPartyFixerWithNoFixAll() - { - await TestThirdPartyCodeFixerNoChanges(_code); - } + public Task DoNotRunThirdPartyFixerWithNoFixAll() + => TestThirdPartyCodeFixerNoChanges(_code); [Theory] [InlineData(DiagnosticSeverity.Warning)] [InlineData(DiagnosticSeverity.Error)] - public async Task RunThirdPartyFixerWithSeverityOfWarningOrHigher(DiagnosticSeverity severity) - { - await TestThirdPartyCodeFixerApplied(_code, _fixed, severity); - } + public Task RunThirdPartyFixerWithSeverityOfWarningOrHigher(DiagnosticSeverity severity) + => TestThirdPartyCodeFixerApplied(_code, _fixed, severity); [Theory] [InlineData(DiagnosticSeverity.Hidden)] [InlineData(DiagnosticSeverity.Info)] - public async Task DoNotRunThirdPartyFixerWithSeverityLessThanWarning(DiagnosticSeverity severity) - { - await TestThirdPartyCodeFixerNoChanges(_code, severity); - } + public Task DoNotRunThirdPartyFixerWithSeverityLessThanWarning(DiagnosticSeverity severity) + => TestThirdPartyCodeFixerNoChanges(_code, severity); [Fact] - public async Task DoNotRunThirdPartyFixerIfItDoesNotSupportDocumentScope() - { - await TestThirdPartyCodeFixerNoChanges(_code); - } + public Task DoNotRunThirdPartyFixerIfItDoesNotSupportDocumentScope() + => TestThirdPartyCodeFixerNoChanges(_code); [Fact] - public async Task DoNotApplyFixerIfChangesAreMadeOutsideDocument() - { - await TestThirdPartyCodeFixerNoChanges(_code); - } + public Task DoNotApplyFixerIfChangesAreMadeOutsideDocument() + => TestThirdPartyCodeFixerNoChanges(_code); private static Task TestThirdPartyCodeFixerNoChanges(string code, DiagnosticSeverity severity = DiagnosticSeverity.Warning) where TAnalyzer : DiagnosticAnalyzer, new() diff --git a/src/EditorFeatures/CSharpTest/Formatting/FormattingEngineTests.cs b/src/EditorFeatures/CSharpTest/Formatting/FormattingEngineTests.cs index 11cc6744140e3..ee57dfa19d975 100644 --- a/src/EditorFeatures/CSharpTest/Formatting/FormattingEngineTests.cs +++ b/src/EditorFeatures/CSharpTest/Formatting/FormattingEngineTests.cs @@ -38,63 +38,55 @@ private static OptionsCollection SmartIndentButDoNotFormatWhileTyping() [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539682")] public void FormatDocumentCommandHandler() { - var code = """ + AssertFormatWithView(""" class Program { static void Main(string[] args) { int x;$$ - int y; + int y; } } - """; - - var expected = """ + """, """ class Program { static void Main(string[] args) { int x;$$ - int y; + int y; } } - """; - - AssertFormatWithView(expected, code); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539682")] public void FormatDocumentPasteCommandHandler() { - var code = """ + AssertFormatWithPasteOrReturn(""" class Program { static void Main(string[] args) { int x;$$ - int y; + int y; } } - """; - - var expected = """ + """, """ class Program { static void Main(string[] args) { int x;$$ - int y; + int y; } } - """; - - AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: true); + """, allowDocumentChanges: true); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547261")] public void FormatDocumentReadOnlyWorkspacePasteCommandHandler() { - var code = """ + AssertFormatWithPasteOrReturn(""" class Program { static void Main(string[] args) @@ -103,9 +95,7 @@ static void Main(string[] args) int y; } } - """; - - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -114,15 +104,13 @@ static void Main(string[] args) int y; } } - """; - - AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: false); + """, allowDocumentChanges: false); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")] public void DoNotFormatUsingStatementOnReturn() { - var code = """ + AssertFormatWithPasteOrReturn(""" class Program { static void Main(string[] args) @@ -131,9 +119,7 @@ static void Main(string[] args) using (null)$$ } } - """; - - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -142,15 +128,13 @@ static void Main(string[] args) using (null)$$ } } - """; - - AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: true, isPaste: false); + """, allowDocumentChanges: true, isPaste: false); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")] public void FormatUsingStatementWhenTypingCloseParen() { - var code = """ + AssertFormatAfterTypeChar(""" class Program { static void Main(string[] args) @@ -159,9 +143,7 @@ static void Main(string[] args) using (null)$$ } } - """; - - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -170,15 +152,13 @@ static void Main(string[] args) using (null) } } - """; - - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")] public void FormatNotUsingStatementOnReturn() { - var code = """ + AssertFormatWithPasteOrReturn(""" class Program { static void Main(string[] args) @@ -187,9 +167,7 @@ static void Main(string[] args) for (;;)$$ } } - """; - - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -198,15 +176,13 @@ static void Main(string[] args) for (;;)$$ } } - """; - - AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: true, isPaste: false); + """, allowDocumentChanges: true, isPaste: false); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/977133")] public void DoNotFormatRangeOrFormatTokenOnOpenBraceOnSameLine() { - var code = """ + AssertFormatAfterTypeChar(""" class C { public void M() @@ -214,8 +190,7 @@ public void M() if (true) {$$ } } - """; - var expected = """ + """, """ class C { public void M() @@ -223,14 +198,13 @@ public void M() if (true) { } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/pull/14491")] public void DoNotFormatRangeButFormatTokenOnOpenBraceOnNextLine() { - var code = """ + AssertFormatAfterTypeChar(""" class C { public void M() @@ -239,8 +213,7 @@ public void M() {$$ } } - """; - var expected = """ + """, """ class C { public void M() @@ -249,14 +222,13 @@ public void M() { } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1007071")] public void FormatPragmaWarningInbetweenDelegateDeclarationStatement() { - var code = """ + AssertFormatAfterTypeChar(""" using System; class Program @@ -270,8 +242,7 @@ static void Main(string[] args) };$$ } } - """; - var expected = """ + """, """ using System; class Program @@ -285,14 +256,13 @@ static void Main(string[] args) }; } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")] public void FormatHashRegion() { - var code = """ + AssertFormatAfterTypeChar(""" using System; class Program @@ -302,8 +272,7 @@ static void Main(string[] args) #region$$ } } - """; - var expected = """ + """, """ using System; class Program @@ -313,14 +282,13 @@ static void Main(string[] args) #region } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")] public void FormatHashEndRegion() { - var code = """ + AssertFormatAfterTypeChar(""" using System; class Program @@ -331,8 +299,7 @@ static void Main(string[] args) #endregion$$ } } - """; - var expected = """ + """, """ using System; class Program @@ -343,8 +310,7 @@ static void Main(string[] args) #endregion } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/987373")] @@ -391,7 +357,15 @@ public void M() } } """; - var expected = """ + using var workspace = EditorTestWorkspace.CreateCSharp(code); + var subjectDocument = workspace.Documents.Single(); + var spans = subjectDocument.SelectedSpans; + + var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); + var syntaxRoot = await document.GetRequiredSyntaxRootAsync(CancellationToken.None); + var options = CSharpSyntaxFormattingOptions.Default; + var node = Formatter.Format(syntaxRoot, spans, workspace.Services.SolutionServices, options, rules: default, CancellationToken.None); + Assert.Equal(""" class C { public void M() @@ -431,22 +405,13 @@ public void M() if (true) { } } } - """; - using var workspace = EditorTestWorkspace.CreateCSharp(code); - var subjectDocument = workspace.Documents.Single(); - var spans = subjectDocument.SelectedSpans; - - var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); - var syntaxRoot = await document.GetRequiredSyntaxRootAsync(CancellationToken.None); - var options = CSharpSyntaxFormattingOptions.Default; - var node = Formatter.Format(syntaxRoot, spans, workspace.Services.SolutionServices, options, rules: default, CancellationToken.None); - Assert.Equal(expected, node.ToFullString()); + """, node.ToFullString()); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1044118")] public void SemicolonInCommentOnLastLineDoesNotFormat() { - var code = """ + AssertFormatAfterTypeChar(""" using System; class Program @@ -456,9 +421,7 @@ static void Main(string[] args) } } // ;$$ - """; - - var expected = """ + """, """ using System; class Program @@ -468,15 +431,14 @@ static void Main(string[] args) } } // ; - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/449")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] public void NoFormattingInsideSingleLineRegularComment_1() { - var code = """ + AssertFormatAfterTypeChar(""" class Program { // {$$ @@ -485,9 +447,7 @@ static void Main(int a, int b) } } - """; - - var expected = """ + """, """ class Program { // { @@ -496,15 +456,14 @@ static void Main(int a, int b) } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/449")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] public void NoFormattingInsideSingleLineRegularComment_2() { - var code = """ + AssertFormatAfterTypeChar(""" class Program { // {$$ @@ -513,9 +472,7 @@ static void Main(int a, int b) } } - """; - - var expected = """ + """, """ class Program { // { @@ -524,15 +481,14 @@ static void Main(int a, int b) } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/449")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] public void NoFormattingInsideMultiLineRegularComment_1() { - var code = """ + AssertFormatAfterTypeChar(""" class Program { static void Main(int a/* {$$ */, int b) @@ -540,9 +496,7 @@ static void Main(int a/* {$$ */, int b) } } - """; - - var expected = """ + """, """ class Program { static void Main(int a/* { */, int b) @@ -550,15 +504,14 @@ static void Main(int a/* { */, int b) } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/449")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] public void NoFormattingInsideMultiLineRegularComment_2() { - var code = """ + AssertFormatAfterTypeChar(""" class Program { static void Main(int a/* {$$ @@ -567,9 +520,7 @@ static void Main(int a/* {$$ } } - """; - - var expected = """ + """, """ class Program { static void Main(int a/* { @@ -578,15 +529,14 @@ static void Main(int a/* { } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/449")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] public void NoFormattingInsideMultiLineRegularComment_3() { - var code = """ + AssertFormatAfterTypeChar(""" class Program { static void Main(int a/* {$$ @@ -595,9 +545,7 @@ static void Main(int a/* {$$ } } - """; - - var expected = """ + """, """ class Program { static void Main(int a/* { @@ -606,15 +554,14 @@ static void Main(int a/* { } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/449")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] public void NoFormattingInsideSingleLineDocComment_1() { - var code = """ + AssertFormatAfterTypeChar(""" class Program { /// {$$ @@ -623,9 +570,7 @@ static void Main(int a, int b) } } - """; - - var expected = """ + """, """ class Program { /// { @@ -634,15 +579,14 @@ static void Main(int a, int b) } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/449")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] public void NoFormattingInsideSingleLineDocComment_2() { - var code = """ + AssertFormatAfterTypeChar(""" class Program { /// {$$ @@ -651,9 +595,7 @@ static void Main(int a, int b) } } - """; - - var expected = """ + """, """ class Program { /// { @@ -662,15 +604,14 @@ static void Main(int a, int b) } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/449")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] public void NoFormattingInsideMultiLineDocComment_1() { - var code = """ + AssertFormatAfterTypeChar(""" class Program { /** {$$ **/ @@ -679,9 +620,7 @@ static void Main(int a, int b) } } - """; - - var expected = """ + """, """ class Program { /** { **/ @@ -690,15 +629,14 @@ static void Main(int a, int b) } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/449")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] public void NoFormattingInsideMultiLineDocComment_2() { - var code = """ + AssertFormatAfterTypeChar(""" class Program { /** {$$ @@ -708,9 +646,7 @@ static void Main(int a, int b) } } - """; - - var expected = """ + """, """ class Program { /** { @@ -720,15 +656,14 @@ static void Main(int a, int b) } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/449")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] public void NoFormattingInsideMultiLineDocComment_3() { - var code = """ + AssertFormatAfterTypeChar(""" class Program { /** {$$ @@ -738,9 +673,7 @@ static void Main(int a, int b) } } - """; - - var expected = """ + """, """ class Program { /** { @@ -750,15 +683,14 @@ static void Main(int a, int b) } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/449")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] public void NoFormattingInsideInactiveCode() { - var code = """ + AssertFormatAfterTypeChar(""" class Program { #if false @@ -770,9 +702,7 @@ static void Main(string[] args) } } - """; - - var expected = """ + """, """ class Program { #if false @@ -784,15 +714,14 @@ static void Main(string[] args) } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/449")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] public void NoFormattingInsideStringLiteral() { - var code = """ + AssertFormatAfterTypeChar(""" class Program { static void Main(string[] args) @@ -800,9 +729,7 @@ static void Main(string[] args) var asdas = "{$$" ; } } - """; - - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -810,15 +737,14 @@ static void Main(string[] args) var asdas = "{" ; } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/449")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] public void NoFormattingInsideCharLiteral() { - var code = """ + AssertFormatAfterTypeChar(""" class Program { static void Main(string[] args) @@ -826,9 +752,7 @@ static void Main(string[] args) var asdas = '{$$' ; } } - """; - - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -836,15 +760,14 @@ static void Main(string[] args) var asdas = '{' ; } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/449")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] public void NoFormattingInsideCommentsOfPreprocessorDirectives() { - var code = """ + AssertFormatAfterTypeChar(""" class Program { #region @@ -854,9 +777,7 @@ static void Main(string[] args) } } - """; - - var expected = """ + """, """ class Program { #region @@ -866,15 +787,14 @@ static void Main(string[] args) } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/464")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] public void ColonInSwitchCase() { - var code = """ + AssertFormatAfterTypeChar(""" class Program { static void Main(string[] args) @@ -886,9 +806,7 @@ static void Main(string[] args) } } } - """; - - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -900,15 +818,14 @@ static void Main(string[] args) } } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/464")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] public void ColonInDefaultSwitchCase() { - var code = """ + AssertFormatAfterTypeChar(""" class Program { static void Main(string[] args) @@ -921,9 +838,7 @@ static void Main(string[] args) } } } - """; - - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -936,14 +851,13 @@ static void Main(string[] args) } } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/9097")] public void ColonInPatternSwitchCase01() { - var code = """ + AssertFormatAfterTypeChar(""" class Program { static void Main() @@ -954,9 +868,7 @@ static void Main() } } } - """; - - var expected = """ + """, """ class Program { static void Main() @@ -967,15 +879,14 @@ static void Main() } } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/464")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] public void ColonInLabeledStatement() { - var code = """ + AssertFormatAfterTypeChar(""" class Program { static void Main(string[] args) @@ -983,9 +894,7 @@ static void Main(string[] args) label1 :$$ int s = 0; } } - """; - - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -993,55 +902,48 @@ static void Main(string[] args) label1: int s = 0; } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/464")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] public void DoNotFormatColonInTargetAttribute() { - var code = """ + AssertFormatAfterTypeChar(""" using System; [method :$$ C] class C : Attribute { } - """; - - var expected = """ + """, """ using System; [method : C] class C : Attribute { } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/464")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] public void DoNotFormatColonInBaseList() { - var code = """ + AssertFormatAfterTypeChar(""" class C :$$ Attribute { } - """; - - var expected = """ + """, """ class C : Attribute { } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/464")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] public void DoNotFormatColonInThisConstructor() { - var code = """ + AssertFormatAfterTypeChar(""" class Goo { Goo(int s) :$$ this() @@ -1052,9 +954,7 @@ class Goo { } } - """; - - var expected = """ + """, """ class Goo { Goo(int s) : this() @@ -1065,15 +965,14 @@ class Goo { } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/464")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] public void DoNotFormatColonInConditionalOperator() { - var code = """ + AssertFormatAfterTypeChar(""" class Program { static void Main(string[] args) @@ -1081,9 +980,7 @@ static void Main(string[] args) var vari = goo() ? true :$$ false; } } - """; - - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -1091,15 +988,14 @@ static void Main(string[] args) var vari = goo() ? true : false; } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/464")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] public void DoNotFormatColonInArgument() { - var code = """ + AssertFormatAfterTypeChar(""" class Program { static void Main(string[] args) @@ -1107,9 +1003,7 @@ static void Main(string[] args) Main(args :$$ args); } } - """; - - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -1117,15 +1011,14 @@ static void Main(string[] args) Main(args : args); } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/464")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] public void DoNotFormatColonInTypeParameter() { - var code = """ + AssertFormatAfterTypeChar(""" class Program { class C1 @@ -1134,9 +1027,7 @@ class C1 } } - """; - - var expected = """ + """, """ class Program { class C1 @@ -1145,40 +1036,41 @@ class C1 } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/2224")] public void DoNotSmartFormatBracesOnSmartIndentNone() { - var code = """ + var globalOptions = new OptionsCollection(LanguageNames.CSharp) + { + { IndentationOptionsStorage.SmartIndent, FormattingOptions2.IndentStyle.None } + }; + AssertFormatAfterTypeChar(""" class Program { class C1 {$$ } - """; - - var expected = """ + """, """ class Program { class C1 { } - """; - var globalOptions = new OptionsCollection(LanguageNames.CSharp) - { - { IndentationOptionsStorage.SmartIndent, FormattingOptions2.IndentStyle.None } - }; - AssertFormatAfterTypeChar(code, expected, globalOptions); + """, globalOptions); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void StillAutoIndentCloseBraceWhenFormatOnCloseBraceIsOff() { - var code = """ + var globalOptions = new OptionsCollection(LanguageNames.CSharp) + { + { AutoFormattingOptionsStorage.FormatOnCloseBrace, false } + }; + + AssertFormatAfterTypeChar(""" namespace N { class C @@ -1187,9 +1079,7 @@ class C int x = 10; }$$ } - """; - - var expected = """ + """, """ namespace N { class C @@ -1198,21 +1088,19 @@ class C int x = 10; } } - """; - - var globalOptions = new OptionsCollection(LanguageNames.CSharp) - { - { AutoFormattingOptionsStorage.FormatOnCloseBrace, false } - }; - - AssertFormatAfterTypeChar(code, expected, globalOptions); + """, globalOptions); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void AutoIndentCloseBraceWhenFormatOnTypingIsOff() { - var code = """ + var globalOptions = new OptionsCollection(LanguageNames.CSharp) + { + { AutoFormattingOptionsStorage.FormatOnTyping, false } + }; + + AssertFormatAfterTypeChar(""" namespace N { class C @@ -1221,9 +1109,7 @@ class C int x = 10; }$$ } - """; - - var expected = """ + """, """ namespace N { class C @@ -1232,24 +1118,19 @@ class C int x = 10; } } - """; - - var globalOptions = new OptionsCollection(LanguageNames.CSharp) - { - { AutoFormattingOptionsStorage.FormatOnTyping, false } - }; - - AssertFormatAfterTypeChar(code, expected, globalOptions); + """, globalOptions); } [WpfFact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] [WorkItem("https://github.com/dotnet/roslyn/issues/5873")] public void KeepTabsInCommentsWhenFormattingIsOff() { - // There are tabs in this test case. Tools that touch the Roslyn repo should - // not remove these as we are explicitly testing tab behavior. - var code = - """ + var globalOptions = new OptionsCollection(LanguageNames.CSharp) + { + { AutoFormattingOptionsStorage.FormatOnTyping, false } + }; + + AssertFormatAfterTypeChar(""" class Program { static void Main() @@ -1257,10 +1138,7 @@ static void Main() return; /* Comment preceded by tabs */ // This one too }$$ } - """; - - var expected = - """ + """, """ class Program { static void Main() @@ -1268,23 +1146,14 @@ static void Main() return; /* Comment preceded by tabs */ // This one too } } - """; - - var globalOptions = new OptionsCollection(LanguageNames.CSharp) - { - { AutoFormattingOptionsStorage.FormatOnTyping, false } - }; - - AssertFormatAfterTypeChar(code, expected, globalOptions); + """, globalOptions); } [WpfFact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] [WorkItem("https://github.com/dotnet/roslyn/issues/5873")] public void DoNotKeepTabsInCommentsWhenFormattingIsOn() { - // There are tabs in this test case. Tools that touch the Roslyn repo should - // not remove these as we are explicitly testing tab behavior. - var code = """ + AssertFormatAfterTypeChar(""" class Program { static void Main() @@ -1292,10 +1161,7 @@ static void Main() return; /* Comment preceded by tabs */ // This one too }$$ } - """; - - var expected = - """ + """, """ class Program { static void Main() @@ -1303,17 +1169,19 @@ static void Main() return; /* Comment preceded by tabs */ // This one too } } - """; - - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void DoNotFormatStatementIfSemicolonOptionIsOff() { - var code = - """ + var globalOptions = new OptionsCollection(LanguageNames.CSharp) + { + { AutoFormattingOptionsStorage.FormatOnSemicolon, false } + }; + + AssertFormatAfterTypeChar(""" namespace N { class C @@ -1321,10 +1189,7 @@ class C int x = 10 ;$$ } } - """; - - var expected = - """ + """, """ namespace N { class C @@ -1332,22 +1197,19 @@ class C int x = 10 ; } } - """; - - var globalOptions = new OptionsCollection(LanguageNames.CSharp) - { - { AutoFormattingOptionsStorage.FormatOnSemicolon, false } - }; - - AssertFormatAfterTypeChar(code, expected, globalOptions); + """, globalOptions); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void DoNotFormatStatementIfTypingOptionIsOff() { - var code = - """ + var globalOptions = new OptionsCollection(LanguageNames.CSharp) + { + { AutoFormattingOptionsStorage.FormatOnTyping, false } + }; + + AssertFormatAfterTypeChar(""" namespace N { class C @@ -1355,10 +1217,7 @@ class C int x = 10 ;$$ } } - """; - - var expected = - """ + """, """ namespace N { class C @@ -1366,68 +1225,49 @@ class C int x = 10 ; } } - """; - - var globalOptions = new OptionsCollection(LanguageNames.CSharp) - { - { AutoFormattingOptionsStorage.FormatOnTyping, false } - }; - - AssertFormatAfterTypeChar(code, expected, globalOptions); - } + """, globalOptions); + } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/4435")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void OpenCurlyNotFormattedIfNotAtStartOfLine() { - var code = - """ + AssertFormatAfterTypeChar(""" class C { public int P {$$ } - """; - - var expected = - """ + """, """ class C { public int P { } - """; - - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/4435")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void OpenCurlyFormattedIfAtStartOfLine() { - var code = - """ + AssertFormatAfterTypeChar(""" class C { public int P {$$ } - """; - - var expected = - """ + """, """ class C { public int P { } - """; - - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact] public void DoNotFormatIncompleteBlockOnSingleLineIfNotTypingCloseCurly1() { - var code = """ + AssertFormatAfterTypeChar(""" namespace ConsoleApplication1 { class Program @@ -1437,8 +1277,7 @@ static bool Property get { return true;$$ } } - """; - var expected = """ + """, """ namespace ConsoleApplication1 { class Program @@ -1448,14 +1287,13 @@ static bool Property get { return true; } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact] public void DoNotFormatIncompleteBlockOnSingleLineIfNotTypingCloseCurly2() { - var code = """ + AssertFormatAfterTypeChar(""" namespace ConsoleApplication1 { class Program @@ -1463,8 +1301,7 @@ class Program static bool Property { get { return true;$$ } } - """; - var expected = """ + """, """ namespace ConsoleApplication1 { class Program @@ -1472,14 +1309,13 @@ class Program static bool Property { get { return true; } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact] public void DoNotFormatIncompleteBlockOnSingleLineIfNotTypingCloseCurly3() { - var code = """ + AssertFormatAfterTypeChar(""" namespace ConsoleApplication1 { class Program @@ -1487,8 +1323,7 @@ class Program static bool Property { get;$$ } } - """; - var expected = """ + """, """ namespace ConsoleApplication1 { class Program @@ -1496,14 +1331,13 @@ class Program static bool Property { get; } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact] public void DoNotFormatCompleteBlockOnSingleLineIfTypingCloseCurly1() { - var code = """ + AssertFormatAfterTypeChar(""" namespace ConsoleApplication1 { class Program @@ -1512,8 +1346,7 @@ static bool Property { get { return true; }$$ } - """; - var expected = """ + """, """ namespace ConsoleApplication1 { class Program @@ -1522,36 +1355,33 @@ static bool Property { get { return true; } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact] public void DoNotFormatCompleteBlockOnSingleLineIfTypingCloseCurly2() { - var code = """ + AssertFormatAfterTypeChar(""" namespace ConsoleApplication1 { class Program { static bool Property { get { return true; }$$ } - """; - var expected = """ + """, """ namespace ConsoleApplication1 { class Program { static bool Property { get { return true; } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact] public void FormatIncompleteBlockOnMultipleLinesIfTypingCloseCurly1() { - var code = """ + AssertFormatAfterTypeChar(""" namespace ConsoleApplication1 { class Program @@ -1561,8 +1391,7 @@ static bool Property get { return true; }$$ } - """; - var expected = """ + """, """ namespace ConsoleApplication1 { class Program @@ -1574,14 +1403,13 @@ static bool Property return true; } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact] public void FormatIncompleteBlockOnMultipleLinesIfTypingCloseCurly2() { - var code = """ + AssertFormatAfterTypeChar(""" namespace ConsoleApplication1 { class Program @@ -1591,8 +1419,7 @@ static bool Property get { return true; } }$$ - """; - var expected = """ + """, """ namespace ConsoleApplication1 { class Program @@ -1604,15 +1431,13 @@ static bool Property return true; } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact] public void DoNotFormatCompleteBlockOnSingleLineIfTypingSemicolon() { - var code = - """ + AssertFormatAfterTypeChar(""" public class Class1 { void M() @@ -1622,9 +1447,7 @@ void M() x.ToString(); } } - """; - var expected = - """ + """, """ public class Class1 { void M() @@ -1634,15 +1457,13 @@ void M() x.ToString(); } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact] public void FormatCompleteBlockOnSingleLineIfTypingCloseCurlyOnLaterLine() { - var code = - """ + AssertFormatAfterTypeChar(""" public class Class1 { void M() @@ -1653,9 +1474,7 @@ void M() }$$ } } - """; - var expected = - """ + """, """ public class Class1 { void M() @@ -1668,14 +1487,13 @@ void M() } } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/7900")] public void FormatLockStatementWithEmbeddedStatementOnSemicolonDifferentLine() { - var code = """ + AssertFormatAfterTypeChar(""" class C { private object _l = new object(); @@ -1685,8 +1503,7 @@ public void M() Console.WriteLine("d");$$ } } - """; - var expected = """ + """, """ class C { private object _l = new object(); @@ -1696,14 +1513,13 @@ public void M() Console.WriteLine("d"); } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/7900")] public void FormatLockStatementWithEmbeddedStatementOnSemicolonSameLine() { - var code = """ + AssertFormatAfterTypeChar(""" class C { private object _l = new object(); @@ -1712,8 +1528,7 @@ public void M() lock (_l) Console.WriteLine("d");$$ } } - """; - var expected = """ + """, """ class C { private object _l = new object(); @@ -1722,8 +1537,7 @@ public void M() lock (_l) Console.WriteLine("d"); } } - """; - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/11642")] @@ -1733,14 +1547,33 @@ public void FormatArbitraryNodeParenthesizedLambdaExpression() // ParenthesizedExpression(ParenthesizedLambdaExpression(ParameterList(), Block())) var code = @"(()=>{})"; var node = SyntaxFactory.ParseExpression(code); - var expected = @"(() => { })"; - AssertFormatOnArbitraryNode(node, expected); + AssertFormatOnArbitraryNode(node, @"(() => { })"); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/57465")] - public async Task FormatLambdaWithDirective() - { - var code = """ + public Task FormatLambdaWithDirective() + => AssertFormatAsync(""" + namespace N + { + public class C + { + protected void Render() + { + if (outer) + { + M(() => + { + #nullable enable + if (inner) + { + } + } + ); + } + } + } + } + """, """ namespace N { public class C @@ -1761,37 +1594,31 @@ protected void Render() } } } - """; - var expected = """ + """, spans: null); + + [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/57465")] + public Task FormatLambdaWithComment() + => AssertFormatAsync(""" namespace N { public class C { protected void Render() { - if (outer) + if (true) { M(() => + { + if (true) { - #nullable enable - if (inner) - { - } + /* marker */ } - ); + }); } } } } - """; - - await AssertFormatAsync(expected, code, spans: null); - } - - [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/57465")] - public async Task FormatLambdaWithComment() - { - var code = """ + """, """ namespace N { public class C @@ -1811,31 +1638,7 @@ protected void Render() } } } - """; - var expected = """ - namespace N - { - public class C - { - protected void Render() - { - if (true) - { - M(() => - { - if (true) - { - /* marker */ - } - }); - } - } - } - } - """; - - await AssertFormatAsync(expected, code, spans: null); - } + """, spans: null); [WpfTheory] [CombinatorialData] @@ -1843,22 +1646,24 @@ protected void Render() public async Task FormatAttributeAtEndOfFile(bool trailingNewLine) { var endOfFile = trailingNewLine ? Environment.NewLine : ""; - var code = $@"using System.Diagnostics.CodeAnalysis; + var expected = $""" + using System.Diagnostics.CodeAnalysis; -[assembly:SuppressMessage(""Globalization"", ""CA1308: Normalize strings to uppercase"", Justification = ""My reason"", Scope = ""member"", Target = ""~M:Method"") ] {endOfFile}"; - var expected = $@"using System.Diagnostics.CodeAnalysis; + [assembly: SuppressMessage("Globalization", "CA1308: Normalize strings to uppercase", Justification = "My reason", Scope = "member", Target = "~M:Method")]{endOfFile} + """; -[assembly: SuppressMessage(""Globalization"", ""CA1308: Normalize strings to uppercase"", Justification = ""My reason"", Scope = ""member"", Target = ""~M:Method"")]{endOfFile}"; + await AssertFormatAsync(expected, $""" + using System.Diagnostics.CodeAnalysis; - await AssertFormatAsync(expected, code, spans: null); + [assembly:SuppressMessage("Globalization", "CA1308: Normalize strings to uppercase", Justification = "My reason", Scope = "member", Target = "~M:Method") ] {endOfFile} + """, spans: null); await AssertFormatAsync(expected, expected, spans: null); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/30787")] public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff1() { - var code = - """ + AssertFormatAfterTypeChar(""" class Program { void M() @@ -1867,10 +1672,7 @@ void M() {$$ } } - """; - - var expected = - """ + """, """ class Program { void M() @@ -1879,16 +1681,13 @@ void M() { } } - """; - - AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); + """, SmartIndentButDoNotFormatWhileTyping()); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/30787")] public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff2() { - var code = - """ + AssertFormatAfterTypeChar(""" class Program { void M() @@ -1897,10 +1696,7 @@ void M() {}$$ } } - """; - - var expected = - """ + """, """ class Program { void M() @@ -1909,17 +1705,13 @@ void M() { } } } - """; - - AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); + """, SmartIndentButDoNotFormatWhileTyping()); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/30787")] public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff3() { - // We only smart indent the { if it's on it's own line. - var code = - """ + AssertFormatAfterTypeChar(""" class Program { void M() @@ -1927,10 +1719,7 @@ void M() if (true){$$ } } - """; - - var expected = - """ + """, """ class Program { void M() @@ -1938,17 +1727,13 @@ void M() if (true){ } } - """; - - AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); + """, SmartIndentButDoNotFormatWhileTyping()); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/30787")] public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff4() { - // We only smart indent the { if it's on it's own line. - var code = - """ + AssertFormatAfterTypeChar(""" class Program { void M() @@ -1956,10 +1741,7 @@ void M() if (true){}$$ } } - """; - - var expected = - """ + """, """ class Program { void M() @@ -1967,17 +1749,13 @@ void M() if (true){ } } } - """; - - AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); + """, SmartIndentButDoNotFormatWhileTyping()); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/30787")] public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff5() { - // Typing the { should not affect the formating of the preceding tokens. - var code = - """ + AssertFormatAfterTypeChar(""" class Program { void M() @@ -1986,10 +1764,7 @@ void M() {$$ } } - """; - - var expected = - """ + """, """ class Program { void M() @@ -1998,17 +1773,13 @@ void M() { } } - """; - - AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); + """, SmartIndentButDoNotFormatWhileTyping()); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/30787")] public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff6() { - // Typing the { should not affect the formating of the preceding tokens. - var code = - """ + AssertFormatAfterTypeChar(""" class Program { void M() @@ -2016,10 +1787,7 @@ void M() if ( true ){$$ } } - """; - - var expected = - """ + """, """ class Program { void M() @@ -2027,40 +1795,31 @@ void M() if ( true ){ } } - """; - - AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); + """, SmartIndentButDoNotFormatWhileTyping()); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/30787")] public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff7() { - var code = - """ + AssertFormatAfterTypeChar(""" class Program { void M() {$$ } - """; - - var expected = - """ + """, """ class Program { void M() { } - """; - - AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); + """, SmartIndentButDoNotFormatWhileTyping()); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/30787")] public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff1() { - var code = - """ + AssertFormatAfterTypeChar(""" class Program { void M() @@ -2070,10 +1829,7 @@ void M() }$$ } } - """; - - var expected = - """ + """, """ class Program { void M() @@ -2083,17 +1839,13 @@ void M() } } } - """; - - AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); + """, SmartIndentButDoNotFormatWhileTyping()); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/30787")] public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff2() { - // Note that the { is not updated since we are not formatting. - var code = - """ + AssertFormatAfterTypeChar(""" class Program { void M() @@ -2102,10 +1854,7 @@ void M() }$$ } } - """; - - var expected = - """ + """, """ class Program { void M() @@ -2114,90 +1863,70 @@ void M() } } } - """; - - AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); + """, SmartIndentButDoNotFormatWhileTyping()); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/30787")] public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff3() { - var code = - """ + AssertFormatAfterTypeChar(""" class Program { void M() { }$$ } - """; - - var expected = - """ + """, """ class Program { void M() { } } - """; - - AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); + """, SmartIndentButDoNotFormatWhileTyping()); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/30787")] public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff4() { - // Should not affect formatting of open brace - var code = - """ + AssertFormatAfterTypeChar(""" class Program { void M() { }$$ } - """; - - var expected = - """ + """, """ class Program { void M() { } } - """; - - AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); + """, SmartIndentButDoNotFormatWhileTyping()); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/31907")] - public async Task NullableReferenceTypes() - { - var code = """ - [| + public Task NullableReferenceTypes() + => AssertFormatWithBaseIndentAsync(""" + class MyClass { void MyMethod() { - var returnType = (_useMethodSignatureReturnType ? _methodSignatureOpt !: method).ReturnType; + var returnType = (_useMethodSignatureReturnType ? _methodSignatureOpt! : method).ReturnType; } } - |] - """; - var expected = """ + """, """ + [| class MyClass { void MyMethod() { - var returnType = (_useMethodSignatureReturnType ? _methodSignatureOpt! : method).ReturnType; + var returnType = (_useMethodSignatureReturnType ? _methodSignatureOpt !: method).ReturnType; } } - - """; - - await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4); - } + |] + """, baseIndentation: 4); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/30518")] public void FormatGeneratedNodeInInitializer() @@ -2208,63 +1937,64 @@ public void FormatGeneratedNodeInInitializer() true } """; - - var expected = """ - new bool[] { - true, - true == false, true - } - """; - var tree = SyntaxFactory.ParseSyntaxTree(code, options: TestOptions.Script); var root = tree.GetRoot(); var entry = SyntaxFactory.BinaryExpression(SyntaxKind.EqualsExpression, SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression), SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression)); var newRoot = root.InsertNodesBefore(root.DescendantNodes().Last(), [entry]); - AssertFormatOnArbitraryNode(newRoot, expected); + AssertFormatOnArbitraryNode(newRoot, """ + new bool[] { + true, + true == false, true + } + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/27268")] - public async Task PositionalPattern() - { - var code = """ - [| + public Task PositionalPattern() + => AssertFormatWithBaseIndentAsync(""" + class MyClass { void MyMethod() { - var point = new Point (3, 4); - if (point is Point (3, 4) _ - && point is Point{x: 3, y: 4} _) + var point = new Point(3, 4); + if (point is Point(3, 4) _ + && point is Point { x: 3, y: 4 } _) { } } } - |] - """; - var expected = """ + """, """ + [| class MyClass { void MyMethod() { - var point = new Point(3, 4); - if (point is Point(3, 4) _ - && point is Point { x: 3, y: 4 } _) + var point = new Point (3, 4); + if (point is Point (3, 4) _ + && point is Point{x: 3, y: 4} _) { } } } + |] + """, baseIndentation: 4); - """; + [WpfFact] + public Task WithExpression() + => AssertFormatWithBaseIndentAsync(""" - await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4); - } + record C(int Property) + { + void M() + { + _ = this with { Property = 1 }; + } + } - [WpfFact] - public async Task WithExpression() - { - var code = """ + """, """ [| record C(int Property) { @@ -2274,26 +2004,25 @@ void M() } } |] - """; - var expected = """ + """, baseIndentation: 4); - record C(int Property) + [WpfFact] + public Task WithExpression_MultiLine() + => AssertFormatWithBaseIndentAsync(""" + + record C(int Property, int Property2) { void M() { - _ = this with { Property = 1 }; + _ = this with + { + Property = 1, + Property2 = 2 + }; } } - """; - - await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4); - } - - [WpfFact] - public async Task WithExpression_MultiLine() - { - var code = """ + """, """ [| record C(int Property, int Property2) { @@ -2307,8 +2036,11 @@ void M() } } |] - """; - var expected = """ + """, baseIndentation: 4); + + [WpfFact] + public Task WithExpression_MultiLine_UserPositionedBraces() + => AssertFormatWithBaseIndentAsync(""" record C(int Property, int Property2) { @@ -2322,15 +2054,7 @@ void M() } } - """; - - await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4); - } - - [WpfFact] - public async Task WithExpression_MultiLine_UserPositionedBraces() - { - var code = """ + """, """ [| record C(int Property, int Property2) { @@ -2344,30 +2068,12 @@ void M() } } |] - """; - var expected = """ - - record C(int Property, int Property2) - { - void M() - { - _ = this with - { - Property = 1, - Property2 = 2 - }; - } - } - - """; - - await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4); - } + """, baseIndentation: 4); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/25003")] public void SeparateGroups_KeepMultipleLinesBetweenGroups() { - var code = """ + AssertFormatWithView(""" $$ using System.A; using System.B; @@ -2375,9 +2081,7 @@ public void SeparateGroups_KeepMultipleLinesBetweenGroups() using MS.A; using MS.B; - """; - - var expected = """ + """, """ $$ using System.A; using System.B; @@ -2385,15 +2089,13 @@ public void SeparateGroups_KeepMultipleLinesBetweenGroups() using MS.A; using MS.B; - """; - - AssertFormatWithView(expected, code, new OptionsCollection(LanguageNames.CSharp) { { GenerationOptions.SeparateImportDirectiveGroups, true } }); + """, new OptionsCollection(LanguageNames.CSharp) { { GenerationOptions.SeparateImportDirectiveGroups, true } }); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/25003")] public void SeparateGroups_KeepMultipleLinesBetweenGroups_FileScopedNamespace() { - var code = """ + AssertFormatWithView(""" $$ namespace N; @@ -2403,9 +2105,7 @@ namespace N; using MS.A; using MS.B; - """; - - var expected = """ + """, """ $$ namespace N; @@ -2415,83 +2115,69 @@ namespace N; using MS.A; using MS.B; - """; - - AssertFormatWithView(expected, code, new OptionsCollection(LanguageNames.CSharp) { { GenerationOptions.SeparateImportDirectiveGroups, true } }); + """, new OptionsCollection(LanguageNames.CSharp) { { GenerationOptions.SeparateImportDirectiveGroups, true } }); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/25003")] public void SeparateGroups_DoNotGroupIfNotSorted() { - var code = """ + AssertFormatWithView(""" $$ using System.B; using System.A; using MS.B; using MS.A; - """; - - var expected = """ + """, """ $$ using System.B; using System.A; using MS.B; using MS.A; - """; - - AssertFormatWithView(expected, code, new OptionsCollection(LanguageNames.CSharp) { { GenerationOptions.SeparateImportDirectiveGroups, true } }); + """, new OptionsCollection(LanguageNames.CSharp) { { GenerationOptions.SeparateImportDirectiveGroups, true } }); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/25003")] public void SeparateGroups_GroupIfSorted() { - var code = """ + AssertFormatWithView(""" $$ using System.A; using System.B; + using MS.A; using MS.B; - """; - - var expected = """ + """, """ $$ using System.A; using System.B; - using MS.A; using MS.B; - """; - - AssertFormatWithView(expected, code, new OptionsCollection(LanguageNames.CSharp) { { GenerationOptions.SeparateImportDirectiveGroups, true } }); + """, new OptionsCollection(LanguageNames.CSharp) { { GenerationOptions.SeparateImportDirectiveGroups, true } }); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/25003")] public void SeparateGroups_GroupIfSorted_RecognizeSystemNotFirst() { - var code = """ + AssertFormatWithView(""" $$ using MS.A; using MS.B; + using System.A; using System.B; - """; - - var expected = """ + """, """ $$ using MS.A; using MS.B; - using System.A; using System.B; - """; - - AssertFormatWithView(expected, code, new OptionsCollection(LanguageNames.CSharp) { { GenerationOptions.SeparateImportDirectiveGroups, true } }); + """, new OptionsCollection(LanguageNames.CSharp) { { GenerationOptions.SeparateImportDirectiveGroups, true } }); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/58157")] public void FormatImplicitObjectCollection() { - var code = """ + AssertFormatWithView(""" class Program { static void Main(string[] args) @@ -2502,9 +2188,7 @@ static void Main(string[] args) }; } } - """; - - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -2515,9 +2199,7 @@ static void Main(string[] args) }; } } - """; - - AssertFormatWithView(expected, code); + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49492")] @@ -2555,552 +2237,456 @@ class Test [WpfFact] public void FormatUserDefinedOperator() { - var code = """ + AssertFormatWithView(""" $$ class C { - public static C operator + ( C x, C y){ + public static C operator +(C x, C y) + { } } - """; - - var expected = """ + """, """ $$ class C { - public static C operator +(C x, C y) - { + public static C operator + ( C x, C y){ } } - """; - - AssertFormatWithView(expected, code); + """); } [WpfFact] public void FormatUserDefinedUnaryOperator() { - var code = """ + AssertFormatWithView(""" $$ class C { - public static C operator ++ ( C x){ + public static C operator ++(C x) + { } } - """; - - var expected = """ + """, """ $$ class C { - public static C operator ++(C x) - { + public static C operator ++ ( C x){ } } - """; - - AssertFormatWithView(expected, code); + """); } [WpfFact] public void FormatUserDefinedExplicitCastOperator() { - var code = """ + AssertFormatWithView(""" $$ class C { - public static explicit operator C ( int x){ + public static explicit operator C(int x) + { } } - """; - - var expected = """ + """, """ $$ class C { - public static explicit operator C(int x) - { + public static explicit operator C ( int x){ } } - """; - - AssertFormatWithView(expected, code); + """); } [WpfFact] public void FormatUserDefinedOperatorOnType() { - var code = """ + AssertFormatAfterTypeChar(""" interface I1 { abstract static I1 operator + ( I1 x, I1 y);$$ } - """; - - var expected = """ + """, """ interface I1 { abstract static I1 operator +(I1 x, I1 y); } - """; - - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact] public void FormatUserDefinedUnaryOperatorOnType() { - var code = """ + AssertFormatAfterTypeChar(""" interface I1 { abstract static I1 operator ++ ( I1 x);$$ } - """; - - var expected = """ + """, """ interface I1 { abstract static I1 operator ++(I1 x); } - """; - - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact] public void FormatUserDefinedExplicitCastOperatorOnType() { - var code = """ + AssertFormatAfterTypeChar(""" interface I1 where T : I1 { abstract static explicit operator string ( T x);$$ } - """; - - var expected = """ + """, """ interface I1 where T : I1 { abstract static explicit operator string(T x); } - """; - - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact] public void FormatUserDefinedCheckedOperator() { - var code = """ + AssertFormatWithView(""" $$ class C { - public static C operator checked + ( C x, C y){ + public static C operator checked +(C x, C y) + { } } - """; - - var expected = """ + """, """ $$ class C { - public static C operator checked +(C x, C y) - { + public static C operator checked + ( C x, C y){ } } - """; - - AssertFormatWithView(expected, code, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp12)); + """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp12)); } [WpfFact] public void FormatUserDefinedCheckedUnaryOperator() { - var code = """ + AssertFormatWithView(""" $$ class C { - public static C operator checked ++ ( C x){ + public static C operator checked ++(C x) + { } } - """; - - var expected = """ + """, """ $$ class C { - public static C operator checked ++(C x) - { + public static C operator checked ++ ( C x){ } } - """; - - AssertFormatWithView(expected, code, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp12)); + """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp12)); } [WpfFact] public void FormatUserDefinedExplicitCheckedCastOperator() { - var code = """ + AssertFormatWithView(""" $$ class C { - public static explicit operator checked C ( int x){ + public static explicit operator checked C(int x) + { } } - """; - - var expected = """ + """, """ $$ class C { - public static explicit operator checked C(int x) - { + public static explicit operator checked C ( int x){ } } - """; - - AssertFormatWithView(expected, code, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp12)); + """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp12)); } [WpfFact] public void FormatUserDefinedCheckedOperatorOnType() { - var code = """ + AssertFormatAfterTypeChar(""" interface I1 { abstract static I1 operator checked + ( I1 x, I1 y);$$ } - """; - - var expected = """ + """, """ interface I1 { abstract static I1 operator checked +(I1 x, I1 y); } - """; - - AssertFormatAfterTypeChar(code, expected, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp12)); + """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp12)); } [WpfFact] public void FormatUserDefinedCheckedUnaryOperatorOnType() { - var code = """ + AssertFormatAfterTypeChar(""" interface I1 { abstract static I1 operator checked ++ ( I1 x);$$ } - """; - - var expected = """ + """, """ interface I1 { abstract static I1 operator checked ++(I1 x); } - """; - - AssertFormatAfterTypeChar(code, expected, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp12)); + """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp12)); } [WpfFact] public void FormatUserDefinedExplicitCheckedCastOperatorOnType() { - var code = """ + AssertFormatAfterTypeChar(""" interface I1 where T : I1 { abstract static explicit operator checked string ( T x);$$ } - """; - - var expected = """ + """, """ interface I1 where T : I1 { abstract static explicit operator checked string(T x); } - """; - - AssertFormatAfterTypeChar(code, expected, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp12)); + """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp12)); } [WpfFact] public void FormatUnsignedRightShift() { - var code = """ + AssertFormatWithView(""" $$ class C { - public static C operator>>> ( C x, C y){ + public static C operator >>>(C x, C y) + { } } - """; - - var expected = """ + """, """ $$ class C { - public static C operator >>>(C x, C y) - { + public static C operator>>> ( C x, C y){ } } - """; - - AssertFormatWithView(expected, code); + """); } [WpfTheory] [CombinatorialData] public void FormatInstanceIncrementOperator([CombinatorialValues("++", "--")] string op) { - var code = $$$""" + AssertFormatWithView($$$""" $$ class C { - public void operator{{{op}}} ( ){ + public void operator {{{op}}}() + { } } - """; - - var expected = $$$""" + """, $$$""" $$ class C { - public void operator {{{op}}}() - { + public void operator{{{op}}} ( ){ } } - """; - - AssertFormatWithView(expected, code); + """); } [WpfTheory] [CombinatorialData] public void FormatInstanceIncrementOperator_Checked([CombinatorialValues("++", "--")] string op) { - var code = $$$""" + AssertFormatWithView($$$""" $$ class C { - public void operator checked{{{op}}} ( ){ + public void operator checked {{{op}}}() + { } } - """; - - var expected = $$$""" + """, $$$""" $$ class C { - public void operator checked {{{op}}}() - { + public void operator checked{{{op}}} ( ){ } } - """; - - AssertFormatWithView(expected, code); + """); } [WpfTheory] [CombinatorialData] public void FormatInstanceCompoundAssignmentOperator([CombinatorialValues("+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", ">>>=")] string op) { - var code = $$$""" + AssertFormatWithView($$$""" $$ class C { - public void operator{{{op}}} ( C x ){ + public void operator {{{op}}}(C x) + { } } - """; - - var expected = $$$""" + """, $$$""" $$ class C { - public void operator {{{op}}}(C x) - { + public void operator{{{op}}} ( C x ){ } } - """; - - AssertFormatWithView(expected, code); + """); } [WpfTheory] [CombinatorialData] public void FormatInstanceCompoundAssignmentOperator_Checked([CombinatorialValues("+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", ">>>=")] string op) { - var code = $$$""" + AssertFormatWithView($$$""" $$ class C { - public void operator checked{{{op}}} ( C x ){ + public void operator checked {{{op}}}(C x) + { } } - """; - - var expected = $$$""" + """, $$$""" $$ class C { - public void operator checked {{{op}}}(C x) - { + public void operator checked{{{op}}} ( C x ){ } } - """; - - AssertFormatWithView(expected, code); + """); } [WpfFact] public void FormatCollectionExpressionAfterEquals() { - var code = """ - $$ - var v = [ 1 , 2 , 3 ] ; - """; - - var expected = """ + AssertFormatWithView(""" $$ var v = [1, 2, 3]; - """; - - AssertFormatWithView(expected, code); + """, """ + $$ + var v = [ 1 , 2 , 3 ] ; + """); } [WpfFact] public void FormatCollectionExpressionAfterEquals2() { - var code = """ + AssertFormatWithView(""" class C { void M() { - List list = [ ] ;$$ + List list = [];$$ } } - """; - - var expected = """ + """, """ class C { void M() { - List list = [];$$ + List list = [ ] ;$$ } } - """; - - AssertFormatWithView(expected, code); + """); } [WpfFact] public void FormatUnsignedRightShiftOnType() { - var code = """ + AssertFormatAfterTypeChar(""" interface I1 { abstract static I1 operator >>> ( I1 x, I1 y);$$ } - """; - - var expected = """ + """, """ interface I1 { abstract static I1 operator >>>(I1 x, I1 y); } - """; - - AssertFormatAfterTypeChar(code, expected); + """); } [WpfTheory] [CombinatorialData] public void FormatInstanceIncrementOperatorOnType([CombinatorialValues("++", "--")] string op) { - var code = $$$""" + AssertFormatAfterTypeChar($$$""" interface I1 { abstract void operator{{{op}}} ( );$$ } - """; - - var expected = $$$""" + """, $$$""" interface I1 { abstract void operator {{{op}}}(); } - """; - - AssertFormatAfterTypeChar(code, expected); + """); } [WpfTheory] [CombinatorialData] public void FormatInstanceIncrementOperatorOnType_Checked([CombinatorialValues("++", "--")] string op) { - var code = $$$""" + AssertFormatAfterTypeChar($$$""" interface I1 { abstract void operator checked{{{op}}} ( );$$ } - """; - - var expected = $$$""" + """, $$$""" interface I1 { abstract void operator checked {{{op}}}(); } - """; - - AssertFormatAfterTypeChar(code, expected); + """); } [WpfTheory] [CombinatorialData] public void FormatInstanceCompoundAssignmentOperatorOnType([CombinatorialValues("+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", ">>>=")] string op) { - var code = $$$""" + AssertFormatAfterTypeChar($$$""" interface I1 { abstract void operator{{{op}}} ( I1 x );$$ } - """; - - var expected = $$$""" + """, $$$""" interface I1 { abstract void operator {{{op}}}(I1 x); } - """; - - AssertFormatAfterTypeChar(code, expected); + """); } [WpfTheory] [CombinatorialData] public void FormatInstanceCompoundAssignmentOperatorOnType_Checked([CombinatorialValues("+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", ">>>=")] string op) { - var code = $$$""" + AssertFormatAfterTypeChar($$$""" interface I1 { abstract void operator checked{{{op}}} ( I1 x );$$ } - """; - - var expected = $$$""" + """, $$$""" interface I1 { abstract void operator checked {{{op}}}(I1 x); } - """; - - AssertFormatAfterTypeChar(code, expected); + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/13981")] public void FormatLabeledStatementAfterColon() { - var code = """ + AssertFormatAfterTypeChar(""" class C { void M() @@ -3108,9 +2694,7 @@ void M() foo:$$ } } - """; - - var expected = """ + """, """ class C { void M() @@ -3118,9 +2702,7 @@ void M() foo: } } - """; - - AssertFormatAfterTypeChar(code, expected); + """); } private static void AssertFormatAfterTypeChar( diff --git a/src/EditorFeatures/CSharpTest/Formatting/FormattingEngineTests_Venus.cs b/src/EditorFeatures/CSharpTest/Formatting/FormattingEngineTests_Venus.cs index 68b6667b8e788..2d7f62de8b73d 100644 --- a/src/EditorFeatures/CSharpTest/Formatting/FormattingEngineTests_Venus.cs +++ b/src/EditorFeatures/CSharpTest/Formatting/FormattingEngineTests_Venus.cs @@ -17,22 +17,8 @@ public sealed class FormattingEngineTests_Venus : CSharpFormattingEngineTestBase public FormattingEngineTests_Venus(ITestOutputHelper output) : base(output) { } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting), Trait(Traits.Feature, Traits.Features.Venus)] - public async Task SimpleOneLineNugget() - { - var code = """ - public class Default - { - void PreRender() - { - #line "Goo.aspx", 1[| - int x=1 ; - |]#line hidden - #line default - } - } - """; - - var expected = """ + public Task SimpleOneLineNugget() + => AssertFormatWithBaseIndentAsync(""" public class Default { void PreRender() @@ -43,30 +29,22 @@ void PreRender() #line default } } - """; - - await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 7); - } - - [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting), Trait(Traits.Feature, Traits.Features.Venus)] - public async Task SimpleMultiLineNugget() - { - var code = """ + """, """ public class Default { void PreRender() { #line "Goo.aspx", 1[| - if(true) - { - Console.WriteLine(5);} + int x=1 ; |]#line hidden #line default } } - """; + """, baseIndentation: 7); - var expected = """ + [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting), Trait(Traits.Feature, Traits.Features.Venus)] + public Task SimpleMultiLineNugget() + => AssertFormatWithBaseIndentAsync(""" public class Default { void PreRender() @@ -80,31 +58,24 @@ void PreRender() #line default } } - """; - - await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 3); - } - - [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting), Trait(Traits.Feature, Traits.Features.Venus)] - public async Task SimpleQueryWithinNugget() - { - var code = """ + """, """ public class Default { void PreRender() { #line "Goo.aspx", 1[| - int[] numbers = { 5, 4, 1 }; - var even = from n in numbers - where n % 2 == 0 - select n; + if(true) + { + Console.WriteLine(5);} |]#line hidden #line default } } - """; + """, baseIndentation: 3); - var expected = """ + [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting), Trait(Traits.Feature, Traits.Features.Venus)] + public Task SimpleQueryWithinNugget() + => AssertFormatWithBaseIndentAsync(""" public class Default { void PreRender() @@ -118,31 +89,25 @@ void PreRender() #line default } } - """; - - await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 7); - } - - [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting), Trait(Traits.Feature, Traits.Features.Venus)] - public async Task LambdaExpressionInNugget() - { - var code = """ + """, """ public class Default { void PreRender() { #line "Goo.aspx", 1[| - int[] source = new [] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8} ; - - foreach(int i in source.Where(x => x > 5)) - Console.WriteLine(i); + int[] numbers = { 5, 4, 1 }; + var even = from n in numbers + where n % 2 == 0 + select n; |]#line hidden #line default } } - """; + """, baseIndentation: 7); - var expected = """ + [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting), Trait(Traits.Feature, Traits.Features.Venus)] + public Task LambdaExpressionInNugget() + => AssertFormatWithBaseIndentAsync(""" public class Default { void PreRender() @@ -156,41 +121,26 @@ void PreRender() #line default } } - """; - - await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 3); - } - - [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576457")] - [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting), Trait(Traits.Feature, Traits.Features.Venus)] - public async Task StatementLambdaInNugget() - { - var code = """ + """, """ public class Default { void PreRender() { #line "Goo.aspx", 1[| - int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; + int[] source = new [] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8} ; - foreach (int i in source.Where( - x => - { - if (x <= 3) - return true; - else if (x >= 7) - return true; - return false; - } - )) - Console.WriteLine(i); + foreach(int i in source.Where(x => x > 5)) + Console.WriteLine(i); |]#line hidden #line default } } - """; + """, baseIndentation: 3); - var expected = """ + [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576457")] + [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting), Trait(Traits.Feature, Traits.Features.Venus)] + public Task StatementLambdaInNugget() + => AssertFormatWithBaseIndentAsync(""" public class Default { void PreRender() @@ -213,11 +163,28 @@ void PreRender() #line default } } - """; + """, """ + public class Default + { + void PreRender() + { + #line "Goo.aspx", 1[| + int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; - // It is somewhat odd that the 'x' and the ')' maintain their - // position relative to 'foreach', but the block doesn't, but that isn't - // Venus specific, just the way the formatting engine is. - await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 3); - } + foreach (int i in source.Where( + x => + { + if (x <= 3) + return true; + else if (x >= 7) + return true; + return false; + } + )) + Console.WriteLine(i); + |]#line hidden + #line default + } + } + """, baseIndentation: 3); } diff --git a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterEnterOnTokenTests.cs b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterEnterOnTokenTests.cs index 2036506c6bff9..16213bc27bfa7 100644 --- a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterEnterOnTokenTests.cs +++ b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterEnterOnTokenTests.cs @@ -26,1254 +26,1172 @@ public sealed class SmartIndenterEnterOnTokenTests : CSharpFormatterTestsBase public SmartIndenterEnterOnTokenTests(ITestOutputHelper output) : base(output) { } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537808")] - public async Task MethodBody1() - { - var code = @"class Class1 -{ - void method() - { } -} -"; - await AssertIndentUsingSmartTokenFormatterAsync( - code, + public Task MethodBody1() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + class Class1 + { + void method() + { } + } + + """, '{', indentationLine: 3, expectedIndentation: 4); - } [WpfFact] - public async Task Preprocessor1() - { - var code = @"class A -{ - #region T -#endregion -} -"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + public Task Preprocessor1() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + class A + { + #region T + #endregion + } + + """, indentationLine: 3, expectedIndentation: 4); - } [WpfFact] - public async Task Preprocessor2() - { - var code = @"class A -{ -#line 1 -#lien 2 -} -"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + public Task Preprocessor2() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + class A + { + #line 1 + #lien 2 + } + + """, indentationLine: 3, expectedIndentation: 4); - } [WpfFact] - public async Task Preprocessor3() - { - var code = @"#region stuff -#endregion -"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + public Task Preprocessor3() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + #region stuff + #endregion + + """, indentationLine: 2, expectedIndentation: 0); - } [WpfFact] - public async Task Comments() - { - var code = @"using System; + public Task Comments() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + using System; -class Class -{ - // Comments -// Comments -"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + class Class + { + // Comments + // Comments + + """, indentationLine: 5, expectedIndentation: 4); - } [WpfFact] - public async Task UsingDirective() - { - var code = @"using System; -using System.Linq; -"; - await AssertIndentUsingSmartTokenFormatterAsync( - code, + public Task UsingDirective() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + using System; + using System.Linq; + + """, 'u', indentationLine: 1, expectedIndentation: 0); - } [WpfFact] - public async Task AfterTopOfFileComment() - { - var code = @"// comment + public Task AfterTopOfFileComment() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + // comment + + class -class -"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + """, indentationLine: 2, expectedIndentation: 0); - } [WpfFact] - public async Task DottedName() - { - var code = @"using System. -Collection; -"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + public Task DottedName() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + using System. + Collection; + + """, indentationLine: 1, expectedIndentation: 4); - } [WpfFact] - public async Task Namespace() - { - var code = @"using System; + public Task Namespace() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + using System; -namespace NS -{ -"; - await AssertIndentUsingSmartTokenFormatterAsync( - code, + namespace NS + { + + """, '{', indentationLine: 3, expectedIndentation: 0); - } [WpfFact] - public async Task NamespaceDottedName() - { - var code = @"using System; + public Task NamespaceDottedName() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + using System; -namespace NS. -NS2 -"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + namespace NS. + NS2 + + """, indentationLine: 3, expectedIndentation: 4); - } [WpfFact] - public async Task NamespaceBody() - { - var code = @"using System; + public Task NamespaceBody() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + using System; -namespace NS -{ -class -"; - await AssertIndentUsingSmartTokenFormatterAsync( - code, + namespace NS + { + class + + """, 'c', indentationLine: 4, expectedIndentation: 4); - } [WpfFact] - public async Task NamespaceCloseBrace() - { - var code = @"using System; + public Task NamespaceCloseBrace() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + using System; -namespace NS -{ -} -"; - await AssertIndentUsingSmartTokenFormatterAsync( - code, + namespace NS + { + } + + """, '}', indentationLine: 4, expectedIndentation: 0); - } [WpfFact] - public async Task Class() - { - var code = @"using System; + public Task Class() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + using System; -namespace NS -{ - class Class -{ -"; - await AssertIndentUsingSmartTokenFormatterAsync( - code, + namespace NS + { + class Class + { + + """, '{', indentationLine: 5, expectedIndentation: 4); - } [WpfFact] - public async Task ClassBody() - { - var code = @"using System; + public Task ClassBody() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + using System; -namespace NS -{ - class Class - { -int -"; - await AssertIndentUsingSmartTokenFormatterAsync( - code, + namespace NS + { + class Class + { + int + + """, 'i', indentationLine: 6, expectedIndentation: 8); - } [WpfFact] - public async Task ClassCloseBrace() - { - var code = @"using System; + public Task ClassCloseBrace() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + using System; -namespace NS -{ - class Class - { -} -"; - await AssertIndentUsingSmartTokenFormatterAsync( - code, + namespace NS + { + class Class + { + } + + """, '}', indentationLine: 6, expectedIndentation: 4); - } [WpfFact] - public async Task Method() - { - var code = @"using System; + public Task Method() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + using System; -namespace NS -{ - class Class - { - void Method() -{ -"; + namespace NS + { + class Class + { + void Method() + { - await AssertIndentUsingSmartTokenFormatterAsync( - code, + """, '{', indentationLine: 7, expectedIndentation: 8); - } [WpfFact] - public async Task MethodBody() - { - var code = @"using System; + public Task MethodBody() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + using System; -namespace NS -{ - class Class - { - void Method() - { -int -"; + namespace NS + { + class Class + { + void Method() + { + int - await AssertIndentUsingSmartTokenFormatterAsync( - code, + """, 'i', indentationLine: 8, expectedIndentation: 12); - } [WpfFact] - public async Task MethodCloseBrace() - { - var code = @"using System; + public Task MethodCloseBrace() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + using System; -namespace NS -{ - class Class - { - void Method() - { -} -"; + namespace NS + { + class Class + { + void Method() + { + } - await AssertIndentUsingSmartTokenFormatterAsync( - code, + """, '}', indentationLine: 8, expectedIndentation: 8); - } [WpfFact] - public async Task Statement() - { - var code = @"using System; + public Task Statement() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + using System; -namespace NS -{ - class Class - { - void Method() - { - int i = 10; -int -"; + namespace NS + { + class Class + { + void Method() + { + int i = 10; + int - await AssertIndentUsingSmartTokenFormatterAsync( - code, + """, 'i', indentationLine: 9, expectedIndentation: 12); - } [WpfFact] - public async Task MethodCall() - { - var code = @"class c -{ - void Method() - { - M( -a: 1, - b: 1); - } -}"; - - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + public Task MethodCall() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + class c + { + void Method() + { + M( + a: 1, + b: 1); + } + } + """, indentationLine: 5, expectedIndentation: 12); - } [WpfFact] - public async Task Switch() - { - var code = @"using System; + public Task Switch() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + using System; -namespace NS -{ - class Class - { - void Method() - { - switch (10) -{ -"; + namespace NS + { + class Class + { + void Method() + { + switch (10) + { - await AssertIndentUsingSmartTokenFormatterAsync( - code, + """, '{', indentationLine: 9, expectedIndentation: 12); - } [WpfFact] - public async Task SwitchBody() - { - var code = @"using System; + public Task SwitchBody() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + using System; -namespace NS -{ - class Class - { - void Method() - { - switch (10) + namespace NS { -case -"; + class Class + { + void Method() + { + switch (10) + { + case - await AssertIndentUsingSmartTokenFormatterAsync( - code, + """, 'c', indentationLine: 10, expectedIndentation: 16); - } [WpfFact] - public async Task SwitchCase() - { - var code = @"using System; + public Task SwitchCase() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + using System; -namespace NS -{ - class Class - { - void Method() - { - switch (10) + namespace NS { - case 10 : -int -"; - - await AssertIndentUsingSmartTokenFormatterAsync( - code, + class Class + { + void Method() + { + switch (10) + { + case 10 : + int + + """, 'i', indentationLine: 11, expectedIndentation: 20); - } [WpfFact] - public async Task SwitchCaseBlock() - { - var code = @"using System; + public Task SwitchCaseBlock() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + using System; -namespace NS -{ - class Class - { - void Method() - { - switch (10) + namespace NS + { + class Class + { + void Method() + { + switch (10) + { + case 10 : { - case 10 : -{ -"; - await AssertIndentUsingSmartTokenFormatterAsync( - code, + """, '{', indentationLine: 11, expectedIndentation: 20); - } [WpfFact] - public async Task Block() - { - var code = @"using System; + public Task Block() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + using System; -namespace NS -{ - class Class - { - void Method() - { - switch (10) + namespace NS { - case 10 : + class Class { -int -"; - - await AssertIndentUsingSmartTokenFormatterAsync( - code, + void Method() + { + switch (10) + { + case 10 : + { + int + + """, 'i', indentationLine: 12, expectedIndentation: 24); - } [WpfFact] - public async Task MultilineStatement1() - { - var code = @"using System; + public Task MultilineStatement1() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + using System; -namespace NS -{ - class Class - { - void Method() - { - int i = 10 + -1 -"; + namespace NS + { + class Class + { + void Method() + { + int i = 10 + + 1 - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + """, indentationLine: 9, expectedIndentation: 16); - } [WpfFact] - public async Task MultilineStatement2() - { - var code = @"using System; + public Task MultilineStatement2() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + using System; -namespace NS -{ - class Class - { - void Method() - { - int i = 10 + - 20 + -30 -"; + namespace NS + { + class Class + { + void Method() + { + int i = 10 + + 20 + + 30 - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + """, indentationLine: 10, expectedIndentation: 20); - } // Bug number 902477 [WpfFact] - public async Task Comments2() - { - var code = @"class Class -{ - void Method() - { - if (true) // Test -int - } -} -"; - await AssertIndentUsingSmartTokenFormatterAsync( - code, + public Task Comments2() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + class Class + { + void Method() + { + if (true) // Test + int + } + } + + """, 'i', indentationLine: 5, expectedIndentation: 12); - } [WpfFact] - public async Task AfterCompletedBlock() - { - var code = @"class Program -{ - static void Main(string[] args) - { - foreach(var a in x) {} -int - } -} + public Task AfterCompletedBlock() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + class Program + { + static void Main(string[] args) + { + foreach(var a in x) {} + int + } + } -"; - await AssertIndentUsingSmartTokenFormatterAsync( - code, + + """, 'i', indentationLine: 5, expectedIndentation: 8); - } [WpfFact] - public async Task AfterTopLevelAttribute() - { - var code = @"class Program -{ - [Attr] -[ -} + public Task AfterTopLevelAttribute() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + class Program + { + [Attr] + [ + } -"; - await AssertIndentUsingSmartTokenFormatterAsync( - code, + + """, '[', indentationLine: 3, expectedIndentation: 4); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537802")] - public async Task EmbededStatement() - { - var code = @"class Program -{ - static void Main(string[] args) - { - if (true) - Console.WriteLine(1); -int - } -} + public Task EmbededStatement() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + class Program + { + static void Main(string[] args) + { + if (true) + Console.WriteLine(1); + int + } + } -"; - await AssertIndentUsingSmartTokenFormatterAsync( - code, + + """, 'i', indentationLine: 6, expectedIndentation: 8); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537808")] - public async Task MethodBraces1() - { - var code = @"class Class1 -{ - void method() -{ } -} -"; - await AssertIndentUsingSmartTokenFormatterAsync( - code, + public Task MethodBraces1() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + class Class1 + { + void method() + { } + } + + """, '{', indentationLine: 3, expectedIndentation: 4); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537808")] - public async Task MethodBraces2() - { - var code = @"class Class1 -{ - void method() - { -} -} -"; - await AssertIndentUsingSmartTokenFormatterAsync( - code, + public Task MethodBraces2() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + class Class1 + { + void method() + { + } + } + + """, '}', indentationLine: 4, expectedIndentation: 4); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537795")] - public async Task Property1() - { - var code = @"class C -{ - string Name - { - get; - set; -} -} -"; - await AssertIndentUsingSmartTokenFormatterAsync( - code, + public Task Property1() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + class C + { + string Name + { + get; + set; + } + } + + """, '}', indentationLine: 6, expectedIndentation: 4); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537563")] - public async Task Class1() - { - var code = @"class C -{ -} -"; - await AssertIndentUsingSmartTokenFormatterAsync( - code, + public Task Class1() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + class C + { + } + + """, '}', indentationLine: 2, expectedIndentation: 0); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] - public async Task ArrayInitializer1() - { - var code = @"class C -{ - var a = new [] -{ 1, 2, 3 } -} -"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + public Task ArrayInitializer1() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + class C + { + var a = new [] + { 1, 2, 3 } + } + + """, indentationLine: 3, expectedIndentation: 4); - } [WpfFact] - public async Task ArrayInitializer2() - { - var code = @"class C -{ - var a = new [] - { - 1, 2, 3 -} -} -"; - await AssertIndentUsingSmartTokenFormatterAsync( - code, + public Task ArrayInitializer2() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + class C + { + var a = new [] + { + 1, 2, 3 + } + } + + """, '}', indentationLine: 5, expectedIndentation: 4); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] - public async Task ArrayInitializer3() - { - var code = @"namespace NS -{ - class Class - { - void Method(int i) - { - var a = new [] -{ - }"; - - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + public Task ArrayInitializer3() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + namespace NS + { + class Class + { + void Method(int i) + { + var a = new [] + { + } + """, indentationLine: 7, expectedIndentation: 12); - } [WpfFact] - public async Task QueryExpression2() - { - var code = @"class C -{ - void Method() - { - var a = from c in b - where - } -} -"; - await AssertIndentUsingSmartTokenFormatterAsync( - code, + public Task QueryExpression2() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + class C + { + void Method() + { + var a = from c in b + where + } + } + + """, 'w', indentationLine: 5, expectedIndentation: 16); - } [WpfFact] - public async Task QueryExpression3() - { - var code = @"class C -{ - void Method() - { - var a = from c in b - where select - } -} -"; - await AssertIndentUsingSmartTokenFormatterAsync( - code, + public Task QueryExpression3() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + class C + { + void Method() + { + var a = from c in b + where select + } + } + + """, 'w', indentationLine: 5, expectedIndentation: 16); - } [WpfFact] - public async Task QueryExpression4() - { - var code = @"class C -{ - void Method() - { - var a = from c in b where c > 10 - select - } -} -"; - await AssertIndentUsingSmartTokenFormatterAsync( - code, + public Task QueryExpression4() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + class C + { + void Method() + { + var a = from c in b where c > 10 + select + } + } + + """, 's', indentationLine: 5, expectedIndentation: 16); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853748")] - public async Task ArrayInitializer() - { - var code = @"class C -{ - void Method() - { - var l = new int[] { - } - } -} -"; - await AssertIndentUsingSmartTokenFormatterAsync( - code, + public Task ArrayInitializer() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + class C + { + void Method() + { + var l = new int[] { + } + } + } + + """, '}', indentationLine: 5, expectedIndentation: 8); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939305")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] - public async Task ArrayExpression() - { - var code = @"class C -{ - void M(object[] q) - { - M( - q: new object[] -{ }); - } -} -"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + public Task ArrayExpression() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + class C + { + void M(object[] q) + { + M( + q: new object[] + { }); + } + } + + """, indentationLine: 6, expectedIndentation: 14); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] - public async Task CollectionExpression() - { - var code = @"class C -{ - void M(List e) - { - M( - new List -{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); - } -} -"; - await AssertIndentUsingSmartTokenFormatterAsync( - code, + public Task CollectionExpression() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + class C + { + void M(List e) + { + M( + new List + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); + } + } + + """, '{', indentationLine: 6, expectedIndentation: 12); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] - public async Task ObjectInitializer() - { - var code = @"class C -{ - void M(What dd) - { - M( - new What -{ d = 3, dd = "" }); - } -} + public Task ObjectInitializer() + => AssertIndentUsingSmartTokenFormatterAsync( + """ + class C + { + void M(What dd) + { + M( + new What + { d = 3, dd = " }); + } + } -class What -{ - public int d; - public string dd; -}"; - await AssertIndentUsingSmartTokenFormatterAsync( - code, + class What + { + public int d; + public string dd; + } + """, '{', indentationLine: 6, expectedIndentation: 12); - } [WpfFact] - public async Task Preprocessor() - { - var code = @" -#line 1 """"Bar""""class Goo : [|IComparable|]#line default#line hidden"; + public Task Preprocessor() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + #line 1 ""Bar""class Goo : [|IComparable|]#line default#line hidden + """, indentationLine: 1, expectedIndentation: 0); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")] - public async Task InsideInitializerWithTypeBody_Implicit() - { - var code = @"class X { - int[] a = { - 1, - - }; -}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + public Task InsideInitializerWithTypeBody_Implicit() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + class X { + int[] a = { + 1, + + }; + } + """, indentationLine: 3, expectedIndentation: 8); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")] - public async Task InsideInitializerWithTypeBody_ImplicitNew() - { - var code = @"class X { - int[] a = new[] { - 1, - - }; -}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + public Task InsideInitializerWithTypeBody_ImplicitNew() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + class X { + int[] a = new[] { + 1, + + }; + } + """, indentationLine: 3, expectedIndentation: 8); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")] - public async Task InsideInitializerWithTypeBody_Explicit() - { - var code = @"class X { - int[] a = new int[] { - 1, - - }; -}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + public Task InsideInitializerWithTypeBody_Explicit() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + class X { + int[] a = new int[] { + 1, + + }; + } + """, indentationLine: 3, expectedIndentation: 8); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")] - public async Task InsideInitializerWithTypeBody_Collection() - { - var code = @"using System.Collections.Generic; -class X { - private List a = new List() { - 1, - - }; -}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + public Task InsideInitializerWithTypeBody_Collection() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + using System.Collections.Generic; + class X { + private List a = new List() { + 1, + + }; + } + """, indentationLine: 4, expectedIndentation: 8); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")] - public async Task InsideInitializerWithTypeBody_ObjectInitializers() - { - var code = @"class C -{ - private What sdfsd = new What - { - d = 3, + public Task InsideInitializerWithTypeBody_ObjectInitializers() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + class C + { + private What sdfsd = new What + { + d = 3, - } -} + } + } -class What -{ - public int d; - public string dd; -}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + class What + { + public int d; + public string dd; + } + """, indentationLine: 5, expectedIndentation: 8); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/872")] - public async Task InsideInterpolationString_1() - { - var code = @"class Program -{ - static void Main(string[] args) - { - var s = $@"" -{Program.number}""; - } + public Task InsideInterpolationString_1() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + class Program + { + static void Main(string[] args) + { + var s = $@" + {Program.number}"; + } - static int number; -}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + static int number; + } + """, indentationLine: 5, expectedIndentation: 0); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/872")] - public async Task InsideInterpolationString_2() - { - var code = @"class Program -{ - static void Main(string[] args) - { - var s = $@""Comment -{Program.number}""; - } + public Task InsideInterpolationString_2() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + class Program + { + static void Main(string[] args) + { + var s = $@"Comment + {Program.number}"; + } - static int number; -}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + static int number; + } + """, indentationLine: 5, expectedIndentation: 0); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/872")] - public async Task InsideInterpolationString_3() - { - var code = @"class Program -{ - static void Main(string[] args) - { - var s = $@""Comment{Program.number} -""; - } + public Task InsideInterpolationString_3() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + class Program + { + static void Main(string[] args) + { + var s = $@"Comment{Program.number} + "; + } - static int number; -}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + static int number; + } + """, indentationLine: 5, expectedIndentation: 0); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/872")] - public async Task InsideInterpolationString_4() - { - var code = @"class Program -{ - static void Main(string[] args) - { - var s = $@""Comment{Program.number}Comment here -""; - } + public Task InsideInterpolationString_4() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + class Program + { + static void Main(string[] args) + { + var s = $@"Comment{Program.number}Comment here + "; + } - static int number; -}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + static int number; + } + """, indentationLine: 5, expectedIndentation: 0); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/872")] - public async Task OutsideInterpolationString() - { - var code = @"class Program -{ - static void Main(string[] args) - { - var s = $@""Comment{Program.number}Comment here"" -; - } + public Task OutsideInterpolationString() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + class Program + { + static void Main(string[] args) + { + var s = $@"Comment{Program.number}Comment here" + ; + } - static int number; -}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + static int number; + } + """, indentationLine: 5, expectedIndentation: 12); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/872")] - public async Task InsideInterpolationSyntax_1() - { - var code = @"class Program -{ - static void Main(string[] args) - { - var s = $@""{ -Program.number}""; - } + public Task InsideInterpolationSyntax_1() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + class Program + { + static void Main(string[] args) + { + var s = $@"{ + Program.number}"; + } - static int number; -}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + static int number; + } + """, indentationLine: 5, expectedIndentation: 12); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/872")] - public async Task InsideInterpolationSyntax_2() - { - var code = @"class Program -{ - static void Main(string[] args) - { - var s = $@""{ - Program -.number}""; - } - - static int number; -}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + public Task InsideInterpolationSyntax_2() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + class Program + { + static void Main(string[] args) + { + var s = $@"{ + Program + .number}"; + } + + static int number; + } + """, indentationLine: 6, expectedIndentation: 12); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/872")] - public async Task InsideInterpolationSyntax_3() - { - var code = @"class Program -{ - static void Main(string[] args) - { - var s = $@""{ -}""; - } + public Task InsideInterpolationSyntax_3() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + class Program + { + static void Main(string[] args) + { + var s = $@"{ + }"; + } - static int number; -}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + static int number; + } + """, indentationLine: 5, expectedIndentation: 12); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/872")] - public async Task InsideInterpolationSyntax_4() - { - var code = @"class Program -{ - static void Main(string[] args) - { - Console.WriteLine($@""PPP{ -((Func)((int s) => { return number; })).Invoke(3):(408) ###-####}""); - } + public Task InsideInterpolationSyntax_4() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + class Program + { + static void Main(string[] args) + { + Console.WriteLine($@"PPP{ + ((Func)((int s) => { return number; })).Invoke(3):(408) ###-####}"); + } - static int number; -}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + static int number; + } + """, indentationLine: 5, expectedIndentation: 12); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/872")] - public async Task InsideInterpolationSyntax_5() - { - var code = @"class Program -{ - static void Main(string[] args) - { - Console.WriteLine($@""PPP{ ((Func)((int s) -=> { return number; })).Invoke(3):(408) ###-####}""); - } + public Task InsideInterpolationSyntax_5() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + class Program + { + static void Main(string[] args) + { + Console.WriteLine($@"PPP{ ((Func)((int s) + => { return number; })).Invoke(3):(408) ###-####}"); + } - static int number; -}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + static int number; + } + """, indentationLine: 5, expectedIndentation: 12); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/872")] - public async Task InsideInterpolationSyntax_6() - { - var code = @"class Program -{ - static void Main(string[] args) - { - Console.WriteLine($@""PPP{ ((Func)((int s) => { return number; })) -.Invoke(3):(408) ###-####}""); - } + public Task InsideInterpolationSyntax_6() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + class Program + { + static void Main(string[] args) + { + Console.WriteLine($@"PPP{ ((Func)((int s) => { return number; })) + .Invoke(3):(408) ###-####}"); + } - static int number; -}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + static int number; + } + """, indentationLine: 5, expectedIndentation: 12); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/872")] - public async Task InsideInterpolationSyntax_7() - { - var code = @"class Program -{ - static void Main(string[] args) - { - Console.WriteLine($@""PPP{ ((Func)((int s) => -{ return number; })).Invoke(3):(408) ###-####}""); - } + public Task InsideInterpolationSyntax_7() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + class Program + { + static void Main(string[] args) + { + Console.WriteLine($@"PPP{ ((Func)((int s) => + { return number; })).Invoke(3):(408) ###-####}"); + } - static int number; -}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + static int number; + } + """, indentationLine: 5, expectedIndentation: 8); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/872")] - public async Task IndentLambdaBodyOneIndentationToFirstTokenOfTheStatement() - { - var code = @"class Program -{ - static void Main(string[] args) - { - Console.WriteLine(((Func)((int s) => -{ return number; })).Invoke(3)); - } + public Task IndentLambdaBodyOneIndentationToFirstTokenOfTheStatement() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + class Program + { + static void Main(string[] args) + { + Console.WriteLine(((Func)((int s) => + { return number; })).Invoke(3)); + } - static int number; -}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + static int number; + } + """, indentationLine: 5, expectedIndentation: 8); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/1339")] - public async Task IndentAutoPropertyInitializerAsPartOfTheDeclaration() - { - var code = @"class Program -{ - public int d { get; } -= 3; - static void Main(string[] args) - { - } -}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + public Task IndentAutoPropertyInitializerAsPartOfTheDeclaration() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ + class Program + { + public int d { get; } + = 3; + static void Main(string[] args) + { + } + } + """, indentationLine: 3, expectedIndentation: 8); - } [WpfFact] - public async Task IndentPatternPropertyFirst() - { - var code = @" -class C -{ - void Main(object o) - { - var y = o is Point - { + public Task IndentPatternPropertyFirst() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ - } - } -}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + class C + { + void Main(object o) + { + var y = o is Point + { + + } + } + } + """, indentationLine: 7, expectedIndentation: 12); - } [WpfFact] - public async Task IndentPatternPropertySecond() - { - var code = @" -class C -{ - void Main(object o) - { - var y = o is Point - { - X is 13, + public Task IndentPatternPropertySecond() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ - } - } -}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + class C + { + void Main(object o) + { + var y = o is Point + { + X is 13, + + } + } + } + """, indentationLine: 8, expectedIndentation: 12); - } [WpfFact] - public async Task IndentListPattern() - { - var code = @" -class C -{ - void Main(object o) - { - var y = o is - [ + public Task IndentListPattern() + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + """ - ] - } -}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + class C + { + void Main(object o) + { + var y = o is + [ + + ] + } + } + """, indentationLine: 7, expectedIndentation: 12); - } [WpfTheory] [InlineData("x", "is < 7 and (>= 3 or > 50) or not <= 0;", 12)] @@ -1292,23 +1210,22 @@ await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( [InlineData("x is < 7 and (>= 3 or > 50) or not", "<= 0;", 12)] [InlineData("x is < 7 and (>= 3 or > 50) or not <=", "0;", 12)] [InlineData("x is < 7 and (>= 3 or > 50) or not <= 0", ";", 12)] - public async Task IndentPatternsInLocalDeclarationCSharp9(string line1, string line2, int expectedIndentation) - { - var code = @$" -class C -{{ - void M() - {{ - var x = 7; - var y = {line1} -{line2} - }} -}}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + public Task IndentPatternsInLocalDeclarationCSharp9(string line1, string line2, int expectedIndentation) + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + $$""" + + class C + { + void M() + { + var x = 7; + var y = {{line1}} + {{line2}} + } + } + """, indentationLine: 7, expectedIndentation); - } [WpfTheory] [InlineData("x", "is < 7 and (>= 3 or > 50) or not <= 0;", 8)] @@ -1327,20 +1244,19 @@ await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( [InlineData("x is < 7 and (>= 3 or > 50) or not", "<= 0;", 8)] [InlineData("x is < 7 and (>= 3 or > 50) or not <=", "0;", 8)] [InlineData("x is < 7 and (>= 3 or > 50) or not <= 0", ";", 8)] - public async Task IndentPatternsInFieldDeclarationCSharp9(string line1, string line2, int expectedIndentation) - { - var code = @$" -class C -{{ - static int x = 7; - bool y = {line1} -{line2} -}}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + public Task IndentPatternsInFieldDeclarationCSharp9(string line1, string line2, int expectedIndentation) + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + $$""" + + class C + { + static int x = 7; + bool y = {{line1}} + {{line2}} + } + """, indentationLine: 5, expectedIndentation); - } [WpfTheory] [InlineData("<", "7 and (>= 3 or > 50) or not <= 0", 12)] @@ -1356,27 +1272,26 @@ await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( [InlineData("< 7 and (>= 3 or > 50) or", "not <= 0", 12)] [InlineData("< 7 and (>= 3 or > 50) or not", "<= 0", 12)] [InlineData("< 7 and (>= 3 or > 50) or not <=", "0", 12)] - public async Task IndentPatternsInSwitchCSharp9(string line1, string line2, int expectedIndentation) - { - var code = @$" -class C -{{ - void M() - {{ - var x = 7; - var y = x switch - {{ - {line1} -{line2} => true, - _ => false - }}; - }} -}}"; - await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( - code, + public Task IndentPatternsInSwitchCSharp9(string line1, string line2, int expectedIndentation) + => AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( + $$""" + + class C + { + void M() + { + var x = 7; + var y = x switch + { + {{line1}} + {{line2}} => true, + _ => false + }; + } + } + """, indentationLine: 9, expectedIndentation); - } private static async Task AssertIndentUsingSmartTokenFormatterAsync( string code, diff --git a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterTests.cs b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterTests.cs index b6220dcae0eb2..914af60483410 100644 --- a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterTests.cs +++ b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterTests.cs @@ -41,23 +41,24 @@ public void EmptyFile() [WpfFact] public void NoPreviousLine() { - var code = @"#region Test + AssertSmartIndent( + """ + #region Test -#warning 0 -#undef SYMBOL -#define SYMBOL -#if false -#elif true -#else -#endif -#pragma warning disable 99999 -#goo + #warning 0 + #undef SYMBOL + #define SYMBOL + #if false + #elif true + #else + #endif + #pragma warning disable 99999 + #goo -#endregion + #endregion -"; - AssertSmartIndent( - code, + + """, indentationLine: 13, expectedIndentation: 0); } @@ -65,14 +66,15 @@ public void NoPreviousLine() [WpfFact] public void EndOfFileInactive() { - var code = @" - // Line 1 -#if false -#endif - -"; AssertSmartIndent( - code, + """ + + // Line 1 + #if false + #endif + + + """, indentationLine: 4, expectedIndentation: 0); } @@ -80,15 +82,16 @@ public void EndOfFileInactive() [WpfFact] public void EndOfFileInactive2() { - var code = @" - // Line 1 -#if false -#endif -// Line 2 - -"; AssertSmartIndent( - code, + """ + + // Line 1 + #if false + #endif + // Line 2 + + + """, indentationLine: 5, expectedIndentation: 0); } @@ -96,16 +99,17 @@ public void EndOfFileInactive2() [WpfFact] public void Comments() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -class Class -{ - // Comments - /// Xml Comments + class Class + { + // Comments + /// Xml Comments -"; - AssertSmartIndent( - code, + + """, indentationLine: 6, expectedIndentation: 4); } @@ -113,16 +117,17 @@ class Class [WpfFact] public void TestExplicitNoneIndentStyle() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -class Class -{ - // Comments - /// Xml Comments + class Class + { + // Comments + /// Xml Comments -"; - AssertSmartIndent( - code, + + """, indentationLine: 6, expectedIndentation: 0, indentStyle: IndentStyle.None); @@ -131,11 +136,12 @@ class Class [WpfFact] public void UsingDirective() { - var code = @"using System; - -"; AssertSmartIndent( - code, + """ + using System; + + + """, indentationLine: 1, expectedIndentation: 0); } @@ -143,11 +149,12 @@ public void UsingDirective() [WpfFact] public void DottedName() { - var code = @"using System. - -"; AssertSmartIndent( - code, + """ + using System. + + + """, indentationLine: 1, expectedIndentation: 4); } @@ -155,11 +162,13 @@ public void DottedName() [WpfFact] public void Namespace() { - var code = @"using System; + var code = """ + using System; -namespace NS + namespace NS -"; + + """; AssertSmartIndent( code, indentationLine: 3, @@ -174,13 +183,14 @@ namespace NS [WpfFact] public void NamespaceDottedName() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS. + namespace NS. -"; - AssertSmartIndent( - code, + + """, indentationLine: 3, expectedIndentation: 4); } @@ -188,14 +198,15 @@ namespace NS. [WpfFact] public void NamespaceBody() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ + namespace NS + { -"; - AssertSmartIndent( - code, + + """, indentationLine: 4, expectedIndentation: 4); } @@ -203,12 +214,14 @@ namespace NS [WpfFact] public void FileScopedNamespace() { - var code = @"using System; + var code = """ + using System; + + namespace NS; -namespace NS; -"; + """; AssertSmartIndent( code, indentationLine: 1, @@ -228,15 +241,16 @@ namespace NS; [WpfFact] public void Class() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ - class Class + namespace NS + { + class Class -"; - AssertSmartIndent( - code, + + """, indentationLine: 5, expectedIndentation: 8); } @@ -244,16 +258,17 @@ class Class [WpfFact] public void ClassBody() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ - class Class - { + namespace NS + { + class Class + { -"; - AssertSmartIndent( - code, + + """, indentationLine: 6, expectedIndentation: 8); } @@ -261,18 +276,18 @@ class Class [WpfFact] public void Method() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ - class Class - { - void Method() + namespace NS + { + class Class + { + void Method() -"; - AssertSmartIndent( - code, + """, indentationLine: 7, expectedIndentation: 12); } @@ -280,19 +295,19 @@ void Method() [WpfFact] public void MethodBody() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ - class Class - { - void Method() - { + namespace NS + { + class Class + { + void Method() + { -"; - AssertSmartIndent( - code, + """, indentationLine: 8, expectedIndentation: 12); } @@ -300,18 +315,18 @@ void Method() [WpfFact] public void Property() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ - class Class - { - public static string Name + namespace NS + { + class Class + { + public static string Name -"; - AssertSmartIndent( - code, + """, indentationLine: 7, expectedIndentation: 12); } @@ -319,20 +334,21 @@ public static string Name [WpfFact] public void PropertyGetBody() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ - class Class - { - private string name; - public string Names - { - get + namespace NS + { + class Class + { + private string name; + public string Names + { + get -"; - AssertSmartIndent( - code, + + """, indentationLine: 10, expectedIndentation: 16); } @@ -340,21 +356,21 @@ public string Names [WpfFact] public void PropertySetBody() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ - class Class - { - private static string name; - public static string Names - { - set + namespace NS + { + class Class + { + private static string name; + public static string Names + { + set -"; - AssertSmartIndent( - code, + """, indentationLine: 10, expectedIndentation: 16); } @@ -362,20 +378,20 @@ public static string Names [WpfFact] public void Statement() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ - class Class - { - void Method() - { - int i = 10; + namespace NS + { + class Class + { + void Method() + { + int i = 10; -"; - AssertSmartIndent( - code, + """, indentationLine: 9, expectedIndentation: 12); } @@ -383,13 +399,13 @@ void Method() [WpfFact] public void FieldInitializer() { - var code = @"class C -{ - int i = 2; -"; - AssertSmartIndent( - code, + """ + class C + { + int i = 2; + + """, indentationLine: 3, expectedIndentation: 4); } @@ -397,16 +413,16 @@ public void FieldInitializer() [WpfFact] public void FieldInitializerWithNamespace() { - var code = @"namespace NS -{ - class C - { - C c = new C(); + AssertSmartIndent( + """ + namespace NS + { + class C + { + C c = new C(); -"; - AssertSmartIndent( - code, + """, indentationLine: 5, expectedIndentation: 8); } @@ -414,15 +430,17 @@ class C [WpfFact] public void MethodCall() { - var code = @"class c -{ - void Method() - { - M( - a: 1, - b: 1); - } -}"; + var code = """ + class c + { + void Method() + { + M( + a: 1, + b: 1); + } + } + """; AssertSmartIndent( code, @@ -441,20 +459,20 @@ void Method() [WpfFact] public void Switch() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ - class Class - { - void Method() - { - switch (10) + namespace NS + { + class Class + { + void Method() + { + switch (10) -"; - AssertSmartIndent( - code, + """, indentationLine: 9, expectedIndentation: 16); } @@ -462,21 +480,21 @@ void Method() [WpfFact] public void SwitchBody() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ - class Class - { - void Method() - { - switch (10) + namespace NS { + class Class + { + void Method() + { + switch (10) + { -"; - AssertSmartIndent( - code, + """, indentationLine: 10, expectedIndentation: 16); } @@ -484,22 +502,22 @@ void Method() [WpfFact] public void SwitchCase() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ - class Class - { - void Method() - { - switch (10) + namespace NS { - case 10 : + class Class + { + void Method() + { + switch (10) + { + case 10 : -"; - AssertSmartIndent( - code, + """, indentationLine: 11, expectedIndentation: 20); } @@ -507,17 +525,18 @@ void Method() [WpfFact] public void ExtendedPropertyPattern() { - var code = @" -class C -{ - void M() - { - _ = this is - { - -"; AssertSmartIndent( - code, + """ + + class C + { + void M() + { + _ = this is + { + + + """, indentationLine: 7, expectedIndentation: 12); } @@ -525,17 +544,19 @@ void M() [WpfFact] public void ExtendedPropertyPattern_WithPattern() { - var code = @" -class C -{ - void M() - { - _ = this is - { + var code = """ + + class C + { + void M() + { + _ = this is + { + + A.B: 1, - A.B: 1, -"; + """; AssertSmartIndent( code, indentationLine: 7, @@ -549,23 +570,23 @@ void M() [WpfFact] public void Block() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ - class Class - { - void Method() - { - switch (10) + namespace NS { - case 10 : + class Class + { + void Method() { + switch (10) + { + case 10 : + { -"; - AssertSmartIndent( - code, + """, indentationLine: 12, expectedIndentation: 24); } @@ -573,20 +594,20 @@ void Method() [WpfFact] public void MultilineStatement1() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ - class Class - { - void Method() - { - int i = 10 + + namespace NS + { + class Class + { + void Method() + { + int i = 10 + -"; - AssertSmartIndent( - code, + """, indentationLine: 9, expectedIndentation: 16); } @@ -594,21 +615,21 @@ void Method() [WpfFact] public void MultilineStatement2() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ - class Class - { - void Method() - { - int i = 10 + - 20 + + namespace NS + { + class Class + { + void Method() + { + int i = 10 + + 20 + -"; - AssertSmartIndent( - code, + """, indentationLine: 10, expectedIndentation: 20); } @@ -617,17 +638,18 @@ void Method() [WpfFact] public void Comments2() { - var code = @"class Class -{ - void Method() - { - if (true) // Test - - } -} -"; AssertSmartIndent( - code, + """ + class Class + { + void Method() + { + if (true) // Test + + } + } + + """, indentationLine: 5, expectedIndentation: 12); } @@ -635,18 +657,19 @@ void Method() [WpfFact] public void AfterCompletedBlock() { - var code = @"class Program -{ - static void Main(string[] args) - { - foreach(var a in x) {} + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + foreach(var a in x) {} - } -} + } + } -"; - AssertSmartIndent( - code, + + """, indentationLine: 5, expectedIndentation: 8); } @@ -654,19 +677,20 @@ static void Main(string[] args) [WpfFact] public void AfterCompletedBlockNestedInOtherBlock() { - var code = @"class Program -{ - static void Main(string[] args) - { - foreach(var a in x) {{} + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + foreach(var a in x) {{} - } - } -} + } + } + } -"; - AssertSmartIndent( - code, + + """, indentationLine: 5, expectedIndentation: 12); } @@ -674,15 +698,16 @@ static void Main(string[] args) [WpfFact] public void AfterTopLevelAttribute() { - var code = @"class Program -{ - [Attr] + AssertSmartIndent( + """ + class Program + { + [Attr] -} + } -"; - AssertSmartIndent( - code, + + """, indentationLine: 3, expectedIndentation: 4); } @@ -690,19 +715,20 @@ public void AfterTopLevelAttribute() [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537802")] public void EmbeddedStatement() { - var code = @"class Program -{ - static void Main(string[] args) - { - if (true) - Console.WriteLine(1); + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + if (true) + Console.WriteLine(1); - } -} + } + } -"; - AssertSmartIndent( - code, + + """, indentationLine: 6, expectedIndentation: 8); } @@ -716,18 +742,19 @@ static void Main(string[] args) [InlineData("static void localFunction()")] public void EmbeddedStatement2(string statement) { - var code = $@"class Program -{{ - static void Main(string[] args) - {{ -{statement} + AssertSmartIndent( + $$""" + class Program + { + static void Main(string[] args) + { + {{statement}} + + } + } - }} -}} -"; - AssertSmartIndent( - code, + """, indentationLine: 5, expectedIndentation: 4); } @@ -735,18 +762,19 @@ static void Main(string[] args) [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537883")] public void EnterAfterComment() { - var code = @"class Program -{ - static void Main(string[] args) - { - int a; // enter + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + int a; // enter - } -} + } + } -"; - AssertSmartIndent( - code, + + """, indentationLine: 5, expectedIndentation: 8); } @@ -754,18 +782,19 @@ static void Main(string[] args) [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538121")] public void NestedBlock1() { - var code = @"class Program -{ - static void Main(string[] args) - { - { + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + { - } -} + } + } -"; - AssertSmartIndent( - code, + + """, indentationLine: 5, expectedIndentation: 12); } @@ -773,20 +802,21 @@ static void Main(string[] args) [WpfFact] public void NestedEmbeddedStatement1() { - var code = @"class Program -{ - static void Main(string[] args) - { - if (true) - if (true) - if (true) - args = null; - - } -} -"; AssertSmartIndent( - code, + """ + class Program + { + static void Main(string[] args) + { + if (true) + if (true) + if (true) + args = null; + + } + } + + """, indentationLine: 8, expectedIndentation: 8); } @@ -794,21 +824,21 @@ static void Main(string[] args) [WpfFact] public void NestedEmbeddedStatement2() { - var code = @"class Program -{ - static void Main(string[] args) - { - if (true) - if (true) - if (true) - { } + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + if (true) + if (true) + if (true) + { } - } -} -"; + } + } - AssertSmartIndent( - code, + """, indentationLine: 8, expectedIndentation: 8); } @@ -816,21 +846,21 @@ static void Main(string[] args) [WpfFact] public void NestedEmbeddedStatement3() { - var code = @"class Program -{ - static void Main(string[] args) - { - if (true) - if (true) - if (true) - { return; } + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + if (true) + if (true) + if (true) + { return; } - } -} -"; + } + } - AssertSmartIndent( - code, + """, indentationLine: 8, expectedIndentation: 8); } @@ -838,19 +868,19 @@ static void Main(string[] args) [WpfFact] public void NestedEmbeddedStatement4() { - var code = @"class Program -{ - static void Main(string[] args) - { - if (true) - if (true) - if (true) - args = null; + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + if (true) + if (true) + if (true) + args = null; -"; - AssertSmartIndent( - code, + """, indentationLine: 8, expectedIndentation: 8); } @@ -858,19 +888,19 @@ static void Main(string[] args) [WpfFact] public void NestedEmbeddedStatement5() { - var code = @"class Program -{ - static void Main(string[] args) - { - if (true) - if (true) - if (true) - { } + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + if (true) + if (true) + if (true) + { } -"; - AssertSmartIndent( - code, + """, indentationLine: 8, expectedIndentation: 8); } @@ -878,19 +908,19 @@ static void Main(string[] args) [WpfFact] public void NestedEmbeddedStatement6() { - var code = @"class Program -{ - static void Main(string[] args) - { - if (true) - if (true) - if (true) - { return; } + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + if (true) + if (true) + if (true) + { return; } -"; - AssertSmartIndent( - code, + """, indentationLine: 8, expectedIndentation: 8); } @@ -898,21 +928,21 @@ static void Main(string[] args) [WpfFact] public void NestedEmbeddedStatement7() { - var code = @"class Program -{ - static void Main(string[] args) - { - if (true) - if (true) - if (true) - return; - else - return; + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + if (true) + if (true) + if (true) + return; + else + return; -"; - AssertSmartIndent( - code, + """, indentationLine: 10, expectedIndentation: 8); } @@ -920,22 +950,22 @@ static void Main(string[] args) [WpfFact] public void NestedEmbeddedStatement8() { - var code = @"class Program -{ - static void Main(string[] args) - { - if (true) - if (true) - if (true) - return; - else - return; - - } -}"; - AssertSmartIndent( - code, + """ + class Program + { + static void Main(string[] args) + { + if (true) + if (true) + if (true) + return; + else + return; + + } + } + """, indentationLine: 10, expectedIndentation: 8); } @@ -943,20 +973,20 @@ static void Main(string[] args) [WpfFact] public void Label1() { - var code = @"class Program -{ - static void Main(string[] args) - { - Label: - Console.WriteLine(1); + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + Label: + Console.WriteLine(1); - } -} + } + } -"; - AssertSmartIndent( - code, + """, indentationLine: 6, expectedIndentation: 8); } @@ -964,18 +994,19 @@ static void Main(string[] args) [WpfFact] public void Label2() { - var code = @"class Program -{ - static void Main(string[] args) - { - Label: Console.WriteLine(1); + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + Label: Console.WriteLine(1); - } -} + } + } -"; - AssertSmartIndent( - code, + + """, indentationLine: 5, expectedIndentation: 8); } @@ -983,21 +1014,22 @@ static void Main(string[] args) [WpfFact] public void Label3() { - var code = @"class Program -{ - static void Main(string[] args) - { - switch(args.GetType()) - { - case 1: - Console.WriteLine(1); + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + switch(args.GetType()) + { + case 1: + Console.WriteLine(1); - } -} + } + } -"; - AssertSmartIndent( - code, + + """, indentationLine: 8, expectedIndentation: 16); } @@ -1005,20 +1037,21 @@ static void Main(string[] args) [WpfFact] public void Label4() { - var code = @"class Program -{ - static void Main(string[] args) - { - switch(args.GetType()) - { - case 1: Console.WriteLine(1); + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + switch(args.GetType()) + { + case 1: Console.WriteLine(1); - } -} + } + } -"; - AssertSmartIndent( - code, + + """, indentationLine: 7, expectedIndentation: 16); } @@ -1026,20 +1059,21 @@ static void Main(string[] args) [WpfFact] public void Label5() { - var code = @"class Program -{ - static void Main(string[] args) - { - switch(args.GetType()) - { - case 1: + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + switch(args.GetType()) + { + case 1: - } -} + } + } -"; - AssertSmartIndent( - code, + + """, indentationLine: 7, expectedIndentation: 16); } @@ -1047,18 +1081,19 @@ static void Main(string[] args) [WpfFact] public void Label6() { - var code = @"class Program -{ - static void Main(string[] args) - { - Label: + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + Label: - } -} + } + } -"; - AssertSmartIndent( - code, + + """, indentationLine: 5, expectedIndentation: 8); } @@ -1066,18 +1101,19 @@ static void Main(string[] args) [WpfFact] public void QueryExpression1() { - var code = @"class Program -{ - static void Main(string[] args) - { - var a = from c in + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + var a = from c in - } -} + } + } -"; - AssertSmartIndent( - code, + + """, indentationLine: 5, expectedIndentation: 20); } @@ -1085,18 +1121,19 @@ static void Main(string[] args) [WpfFact] public void QueryExpression2() { - var code = @"class Program -{ - static void Main(string[] args) - { - var a = from c in b + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + var a = from c in b - } -} + } + } -"; - AssertSmartIndent( - code, + + """, indentationLine: 5, expectedIndentation: 16); } @@ -1104,18 +1141,19 @@ static void Main(string[] args) [WpfFact] public void QueryExpression3() { - var code = @"class Program -{ - static void Main(string[] args) - { - var a = from c in b. + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + var a = from c in b. - } -} + } + } -"; - AssertSmartIndent( - code, + + """, indentationLine: 5, expectedIndentation: 16); } @@ -1123,18 +1161,19 @@ static void Main(string[] args) [WpfFact] public void QueryExpression4() { - var code = @"class Program -{ - static void Main(string[] args) - { - var a = from c in b where c > 10 + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + var a = from c in b where c > 10 - } -} + } + } -"; - AssertSmartIndent( - code, + + """, indentationLine: 5, expectedIndentation: 16); } @@ -1142,19 +1181,20 @@ static void Main(string[] args) [WpfFact] public void QueryExpression5() { - var code = @"class Program -{ - static void Main(string[] args) - { - var a = from c in - from b in G + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + var a = from c in + from b in G - } -} + } + } -"; - AssertSmartIndent( - code, + + """, indentationLine: 6, expectedIndentation: 20); } @@ -1162,20 +1202,21 @@ from b in G [WpfFact] public void QueryExpression6() { - var code = @"class Program -{ - static void Main(string[] args) - { - var a = from c in - from b in G - select b + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + var a = from c in + from b in G + select b - } -} + } + } -"; - AssertSmartIndent( - code, + + """, indentationLine: 7, expectedIndentation: 20); } @@ -1183,20 +1224,21 @@ select b [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538779")] public void QueryExpression7() { - var code = @"class Program -{ - static void Main(string[] args) - { - var q = from string s in args + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + var q = from string s in args - where s == null - select s; - } -} + where s == null + select s; + } + } -"; - AssertSmartIndent( - code, + + """, indentationLine: 5, expectedIndentation: 16); } @@ -1204,21 +1246,22 @@ static void Main(string[] args) [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538779")] public void QueryExpression8() { - var code = @"class Program -{ - static void Main(string[] args) - { - var q = from string s in args. - b.c. + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + var q = from string s in args. + b.c. - where s == null - select s; - } -} + where s == null + select s; + } + } -"; - AssertSmartIndent( - code, + + """, indentationLine: 6, expectedIndentation: 30); } @@ -1226,20 +1269,21 @@ static void Main(string[] args) [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538780")] public void QueryExpression9() { - var code = @"class Program -{ - static void Main(string[] args) - { - var q = from string s in args - where s == null + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + var q = from string s in args + where s == null - select s; - } -} + select s; + } + } -"; - AssertSmartIndent( - code, + + """, indentationLine: 6, expectedIndentation: 16); } @@ -1247,21 +1291,22 @@ static void Main(string[] args) [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538780")] public void QueryExpression10() { - var code = @"class Program -{ - static void Main(string[] args) - { - var q = from string s in args - where s == null - == 1 + AssertSmartIndent( + """ + class Program + { + static void Main(string[] args) + { + var q = from string s in args + where s == null + == 1 - select s; - } -} + select s; + } + } -"; - AssertSmartIndent( - code, + + """, indentationLine: 7, expectedIndentation: 24); } @@ -1269,13 +1314,14 @@ static void Main(string[] args) [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538333")] public void Statement1() { - var code = @"class Program -{ - void Test() { } - -}"; AssertSmartIndent( - code, + """ + class Program + { + void Test() { } + + } + """, indentationLine: 3, expectedIndentation: 4); } @@ -1283,16 +1329,17 @@ void Test() { } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538933")] public void EndOfFile1() { - var code = @"class Program -{ - void Test() - { - int i; + AssertSmartIndent( + """ + class Program + { + void Test() + { + int i; -"; - AssertSmartIndent( - code, + + """, indentationLine: 6, expectedIndentation: 8); } @@ -1300,15 +1347,16 @@ void Test() [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539059")] public void VerbatimString() { - var code = @"class Program -{ - void Test() - { - var goo = @""Goo - -"; AssertSmartIndent( - code, + """ + class Program + { + void Test() + { + var goo = @"Goo + + + """, indentationLine: 5, expectedIndentation: 0); } @@ -1316,18 +1364,19 @@ void Test() [WpfFact] public void RawString1() { - var code = @"class Program -{ - void Test() - { - var goo = """""" - - """"""; - } -} -"; AssertSmartIndent( - code, + """" + class Program + { + void Test() + { + var goo = """ + + """; + } + } + + """", indentationLine: 5, expectedIndentation: 12); } @@ -1335,18 +1384,19 @@ void Test() [WpfFact] public void RawString2() { - var code = @"class Program -{ - void Test() - { - var goo = """""" - Goo + AssertSmartIndent( + """" + class Program + { + void Test() + { + var goo = """ + Goo - """""" + """ -"; - AssertSmartIndent( - code, + + """", indentationLine: 6, expectedIndentation: 12); } @@ -1354,18 +1404,19 @@ void Test() [WpfFact] public void RawString3() { - var code = @"class Program -{ - void Test() - { - var goo = """""" - Goo + AssertSmartIndent( + """" + class Program + { + void Test() + { + var goo = """ + Goo - """""" + """ -"; - AssertSmartIndent( - code, + + """", indentationLine: 6, expectedIndentation: 12); } @@ -1373,18 +1424,19 @@ void Test() [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/60946")] public void RawString4() { - var code = @"class Program -{ - void Test() - { - var goo = """""" - Goo + AssertSmartIndent( + """" + class Program + { + void Test() + { + var goo = """ + Goo - """""" + """ -"; - AssertSmartIndent( - code, + + """", indentationLine: 6, expectedIndentation: 16); } @@ -1392,19 +1444,20 @@ void Test() [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/60946")] public void RawString5() { - var code = @"class Program -{ - void Test() - { - var goo = """""" - Goo + AssertSmartIndent( + """" + class Program + { + void Test() + { + var goo = """ + Goo - """""" + """ -"; - AssertSmartIndent( - code, + + """", indentationLine: 7, expectedIndentation: 16); } @@ -1412,10 +1465,12 @@ void Test() [WpfFact] public void RawString6() { - var code = @"var goo = """""" + var code = """" + var goo = """ + + """; - """"""; -"; + """"; AssertSmartIndent( code, @@ -1430,7 +1485,8 @@ public void RawString6() [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/66368")] public void UnterminatedRawString1() { - var code = """"""" + AssertSmartIndent( + """"""" var x = """""" 1 2 @@ -1439,10 +1495,7 @@ public void UnterminatedRawString1() 5 """; - """""""; - - AssertSmartIndent( - code, + """"""", indentationLine: 3, expectedIndentation: 4); } @@ -1450,7 +1503,8 @@ public void UnterminatedRawString1() [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/66368")] public void UnterminatedInterpolatedRawString1() { - var code = """"""" + AssertSmartIndent( + """"""" var x = $"""""" 1 2 @@ -1459,10 +1513,7 @@ public void UnterminatedInterpolatedRawString1() 5 """; - """""""; - - AssertSmartIndent( - code, + """"""", indentationLine: 3, expectedIndentation: 4); } @@ -1470,18 +1521,19 @@ public void UnterminatedInterpolatedRawString1() [WpfFact] public void InterpolatedRawString1() { - var code = @"class Program -{ - void Test() - { - var goo = $"""""" - - """"""; - } -} -"; AssertSmartIndent( - code, + """" + class Program + { + void Test() + { + var goo = $""" + + """; + } + } + + """", indentationLine: 5, expectedIndentation: 12); } @@ -1489,18 +1541,19 @@ void Test() [WpfFact] public void InterpolatedRawString2() { - var code = @"class Program -{ - void Test() - { - var goo = $"""""" - Goo + AssertSmartIndent( + """" + class Program + { + void Test() + { + var goo = $""" + Goo - """""" + """ -"; - AssertSmartIndent( - code, + + """", indentationLine: 6, expectedIndentation: 12); } @@ -1508,18 +1561,19 @@ void Test() [WpfFact] public void InterpolatedRawString3() { - var code = @"class Program -{ - void Test() - { - var goo = $"""""" - Goo + AssertSmartIndent( + """" + class Program + { + void Test() + { + var goo = $""" + Goo - """""" + """ -"; - AssertSmartIndent( - code, + + """", indentationLine: 6, expectedIndentation: 12); } @@ -1527,18 +1581,19 @@ void Test() [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/60946")] public void InterpolatedRawString4() { - var code = @"class Program -{ - void Test() - { - var goo = $"""""" - Goo + AssertSmartIndent( + """" + class Program + { + void Test() + { + var goo = $""" + Goo - """""" + """ -"; - AssertSmartIndent( - code, + + """", indentationLine: 6, expectedIndentation: 16); } @@ -1546,19 +1601,20 @@ void Test() [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/60946")] public void InterpolatedRawString5() { - var code = @"class Program -{ - void Test() - { - var goo = $"""""" - Goo + AssertSmartIndent( + """" + class Program + { + void Test() + { + var goo = $""" + Goo - """""" + """ -"; - AssertSmartIndent( - code, + + """", indentationLine: 7, expectedIndentation: 16); } @@ -1566,10 +1622,12 @@ void Test() [WpfFact] public void InterpolatedRawString6() { - var code = @"var goo = $"""""" + var code = """" + var goo = $""" - """"""; -"; + """; + + """"; AssertSmartIndent( code, @@ -1584,17 +1642,19 @@ public void InterpolatedRawString6() [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/60946")] public void InterpolatedRawString7() { - var code = @"class Program -{ - void Test() - { - var goo = $"""""" - Goo{nameof(goo)} + var code = """" + class Program + { + void Test() + { + var goo = $""" + Goo{nameof(goo)} + + """ - """""" -"; + """"; AssertSmartIndent( code, @@ -1609,18 +1669,20 @@ void Test() [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/60946")] public void InterpolatedRawString8() { - var code = @"class Program -{ - void Test() - { - var goo = $"""""" - Goo{ -nameof(goo)} + var code = """" + class Program + { + void Test() + { + var goo = $""" + Goo{ + nameof(goo)} - """""" + """ -"; + + """"; AssertSmartIndent( code, @@ -1635,25 +1697,25 @@ void Test() [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539892")] public void Bug5994() { - var code = @"using System; -using System.Collections.Generic; -using System.Linq; + AssertSmartIndent( + """ + using System; + using System.Collections.Generic; + using System.Linq; -class Program -{ - static void Main(string[] args) - { - var studentQuery = - from student in students - group student by (avg == 0 ? 0 : avg / 10) into g + class Program + { + static void Main(string[] args) + { + var studentQuery = + from student in students + group student by (avg == 0 ? 0 : avg / 10) into g - ; - } -} -"; + ; + } + } - AssertSmartIndent( - code, + """, indentationLine: 11, expectedIndentation: 15); } @@ -1661,24 +1723,24 @@ group student by (avg == 0 ? 0 : avg / 10) into g [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539990")] public void Bug6124() { - var code = @"class Program -{ - void Main() - { - var commandLine = string.Format( - "", - 0, - 42, - string.Format("", - 0, - 0), - - 0); - } -}"; - AssertSmartIndent( - code, + """ + class Program + { + void Main() + { + var commandLine = string.Format( + ", + 0, + 42, + string.Format(", + 0, + 0), + + 0); + } + } + """, indentationLine: 11, expectedIndentation: 12); } @@ -1686,25 +1748,25 @@ void Main() [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539990")] public void Bug6124_1() { - var code = @"class Program -{ - void Main() - { - var commandLine = string.Format( - "", - 0, - 42, - string.Format("", - 0, - 0 - -), - 0); - } -}"; - AssertSmartIndent( - code, + """ + class Program + { + void Main() + { + var commandLine = string.Format( + ", + 0, + 42, + string.Format(", + 0, + 0 + + ), + 0); + } + } + """, indentationLine: 11, expectedIndentation: 16); } @@ -1712,14 +1774,15 @@ void Main() [WpfFact] public void AfterIfWithSingleStatementInTopLevelMethod_Bug7291_1() { - var code = @"int fact(int x) -{ - if (x < 1) - return 1; - -"; AssertSmartIndent( - code, + """ + int fact(int x) + { + if (x < 1) + return 1; + + + """, indentationLine: 4, expectedIndentation: 4, options: TestOptions.Script); @@ -1728,15 +1791,16 @@ public void AfterIfWithSingleStatementInTopLevelMethod_Bug7291_1() [WpfFact] public void AfterIfWithSingleStatementInTopLevelMethod_Bug7291_2() { - var code = @"int fact(int x) -{ - if (x < 1) - return 1; - -} -"; AssertSmartIndent( - code, + """ + int fact(int x) + { + if (x < 1) + return 1; + + } + + """, indentationLine: 4, expectedIndentation: 4, options: TestOptions.Script); @@ -1746,26 +1810,27 @@ public void AfterIfWithSingleStatementInTopLevelMethod_Bug7291_2() [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544268")] public void FirstArgumentInArgumentList() { - var code = @"class Program -{ - public Program( - string a, - int b, - bool c) - : this( - a, - new Program( - - "", - 3, - true), - b, - c) - { - } -}"; AssertSmartIndent( - code, + """ + class Program + { + public Program( + string a, + int b, + bool c) + : this( + a, + new Program( + + ", + 3, + true), + b, + c) + { + } + } + """, indentationLine: 9, expectedIndentation: 16); } @@ -1773,16 +1838,17 @@ public Program( [WpfFact] public void ForLoop() { - var code = @"class Program -{ - static void Main(string[] args) - { - for (; - ;) { } - } -}"; AssertSmartIndent( - code, + """ + class Program + { + static void Main(string[] args) + { + for (; + ;) { } + } + } + """, indentationLine: 5, expectedIndentation: 12); } @@ -1790,14 +1856,14 @@ static void Main(string[] args) [WpfFact] public void CallBaseCtor() { - var code = @"class Program -{ - public Program() : - base() { } -}"; - AssertSmartIndent( - code, + """ + class Program + { + public Program() : + base() { } + } + """, indentationLine: 3, expectedIndentation: 8); } @@ -1805,17 +1871,17 @@ public Program() : [WpfFact] public void MultipleDeclarations() { - var code = @"class Program -{ - static void Main(string[] args) - { - int i, - j = 42; - } -}"; - AssertSmartIndent( - code, + """ + class Program + { + static void Main(string[] args) + { + int i, + j = 42; + } + } + """, indentationLine: 5, expectedIndentation: 12); } @@ -1823,17 +1889,17 @@ static void Main(string[] args) [WpfFact] public void CloseBracket() { - var code = @"class Program -{ - static void Main(string[] args) - { - var i = new int[1] - ; - } -}"; - AssertSmartIndent( - code, + """ + class Program + { + static void Main(string[] args) + { + var i = new int[1] + ; + } + } + """, indentationLine: 5, expectedIndentation: 12); } @@ -1841,21 +1907,22 @@ static void Main(string[] args) [WpfFact] public void SwitchLabel() { - var code = @"class Program -{ - static void Main(string[] args) - { - switch (args[0]) - { - case ""goo"": - - case ""bar"": - break; - } - } -}"; AssertSmartIndent( - code, + """ + class Program + { + static void Main(string[] args) + { + switch (args[0]) + { + case "goo": + + case "bar": + break; + } + } + } + """, indentationLine: 7, expectedIndentation: 16); } @@ -1863,13 +1930,14 @@ static void Main(string[] args) [WpfFact] public void TypeParameters() { - var code = @"class Program -{ - static void Goo() { } -}"; AssertSmartIndent( - code, + """ + class Program + { + static void Goo() { } + } + """, indentationLine: 3, expectedIndentation: 8); } @@ -1877,18 +1945,19 @@ public void TypeParameters() [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542428")] public void TypeArguments() { - var code = @"class Program -{ - static void Goo(T1 t1, T2 t2) { } - - static void Main(string[] args) - { - Goo(4, 2); - } -}"; AssertSmartIndent( - code, + """ + class Program + { + static void Goo(T1 t1, T2 t2) { } + + static void Main(string[] args) + { + Goo(4, 2); + } + } + """, indentationLine: 7, expectedIndentation: 16); } @@ -1896,13 +1965,14 @@ static void Main(string[] args) [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542983")] public void ConstructorInitializer1() { - var code = @"public class Asset -{ - public Asset() : this( - -"; AssertSmartIndent( - code, + """ + public class Asset + { + public Asset() : this( + + + """, indentationLine: 3, expectedIndentation: 8); } @@ -1910,14 +1980,15 @@ public Asset() : this( [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542983")] public void ConstructorInitializer2() { - var code = @"public class Asset -{ - public Asset() - : this( - -"; AssertSmartIndent( - code, + """ + public class Asset + { + public Asset() + : this( + + + """, indentationLine: 4, expectedIndentation: 14); } @@ -1925,14 +1996,15 @@ public Asset() [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542983")] public void ConstructorInitializer3() { - var code = @"public class Asset -{ - public Asset() : - this( - -"; AssertSmartIndent( - code, + """ + public class Asset + { + public Asset() : + this( + + + """, indentationLine: 4, expectedIndentation: 12); } @@ -1940,22 +2012,23 @@ public Asset() : [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543131")] public void LockStatement1() { - var code = @"using System; -class Program -{ - static object lockObj = new object(); - static int Main() - { - int sum = 0; - lock (lockObj) - try - { sum = 0; } - - return sum; - } -}"; AssertSmartIndent( - code, + """ + using System; + class Program + { + static object lockObj = new object(); + static int Main() + { + int sum = 0; + lock (lockObj) + try + { sum = 0; } + + return sum; + } + } + """, indentationLine: 10, expectedIndentation: 12); } @@ -1963,13 +2036,14 @@ static int Main() [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543533")] public void ConstructorInitializer() { - var code = @"public class Asset -{ - public Asset() : - -"; AssertSmartIndent( - code, + """ + public class Asset + { + public Asset() : + + + """, indentationLine: 3, expectedIndentation: 8); } @@ -1977,21 +2051,22 @@ public Asset() : [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/952803")] public void ArrayInitializer() { - var code = @"using System.Collections.ObjectModel; + AssertSmartIndent( + """ + using System.Collections.ObjectModel; -class Program -{ - static void Main(string[] args) - { - new ReadOnlyCollection(new int[] - { + class Program + { + static void Main(string[] args) + { + new ReadOnlyCollection(new int[] + { - }); - } -} -"; - AssertSmartIndent( - code, + }); + } + } + + """, indentationLine: 8, expectedIndentation: 12); } @@ -1999,37 +2074,38 @@ static void Main(string[] args) [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543563")] public void LambdaEmbededInExpression() { - var code = @"using System; -using System.Collections.Generic; -using System.Linq; - -class Program -{ - static void Main(string[] args) - { - using (var var = new GooClass(() => - { - - })) - { - var var2 = var; - } - } -} - -class GooClass : IDisposable -{ - public GooClass(Action a) - { - } - - public void Dispose() - { - throw new NotImplementedException(); - } -}"; AssertSmartIndent( - code, + """ + using System; + using System.Collections.Generic; + using System.Linq; + + class Program + { + static void Main(string[] args) + { + using (var var = new GooClass(() => + { + + })) + { + var var2 = var; + } + } + } + + class GooClass : IDisposable + { + public GooClass(Action a) + { + } + + public void Dispose() + { + throw new NotImplementedException(); + } + } + """, indentationLine: 10, expectedIndentation: 12); } @@ -2037,16 +2113,17 @@ public void Dispose() [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543563")] public void LambdaEmbededInExpression_1() { - var code = @"class Program -{ - static void Main(string[] args) - { - using (var var = new GooClass(() => - - } -}"; AssertSmartIndent( - code, + """ + class Program + { + static void Main(string[] args) + { + using (var var = new GooClass(() => + + } + } + """, indentationLine: 5, expectedIndentation: 16); } @@ -2054,35 +2131,36 @@ static void Main(string[] args) [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543563")] public void LambdaEmbededInExpression_3() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -class Program -{ - static void Main(string[] args) - { - using (var var = new GooClass(() => - { + class Program + { + static void Main(string[] args) + { + using (var var = new GooClass(() => + { - })) - { - var var2 = var; - } - } -} + })) + { + var var2 = var; + } + } + } -class GooClass : IDisposable -{ - public GooClass(Action a) - { - } + class GooClass : IDisposable + { + public GooClass(Action a) + { + } - public void Dispose() - { - throw new NotImplementedException(); - } -}"; - AssertSmartIndent( - code, + public void Dispose() + { + throw new NotImplementedException(); + } + } + """, indentationLine: 8, expectedIndentation: 12); } @@ -2090,17 +2168,18 @@ public void Dispose() [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543563")] public void LambdaEmbededInExpression_2() { - var code = @"class Program -{ - static void Main(string[] args) - { - using (var var = new GooClass( - () => - - } -}"; AssertSmartIndent( - code, + """ + class Program + { + static void Main(string[] args) + { + using (var var = new GooClass( + () => + + } + } + """, indentationLine: 6, expectedIndentation: 16); } @@ -2108,24 +2187,25 @@ static void Main(string[] args) [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543563")] public void LambdaEmbededInExpression_4() { - var code = @"using System; -class Class -{ - public void Method() - { - OtherMethod(() => - { - var aaa = new object(); if (aaa != null) + AssertSmartIndent( + """ + using System; + class Class { - var bbb = new object(); + public void Method() + { + OtherMethod(() => + { + var aaa = new object(); if (aaa != null) + { + var bbb = new object(); + } + }); + } + private void OtherMethod(Action action) { } } - }); - } - private void OtherMethod(Action action) { } -}"; - AssertSmartIndent( - code, + """, indentationLine: 10, expectedIndentation: 16); } @@ -2133,32 +2213,34 @@ private void OtherMethod(Action action) { } [WpfFact] public void LambdaDefaultParameter_EnterAfterParamList() { - var code = @"class Program -{ - public void Main() - { - var lam = (int x = 7) => - - } -}"; AssertSmartIndent( - code, + """ + class Program + { + public void Main() + { + var lam = (int x = 7) => + + } + } + """, indentationLine: 5, expectedIndentation: 8); } [WpfFact] - public void LambdaDefaultParameter_EnterAfterEquals() - { - var code = @"class Program -{ - public void Main() + public void LambdaDefaultParameter_EnterAfterEquals() { - var lam = (int x = - } -}"; AssertSmartIndent( - code, + """ + class Program + { + public void Main() + { + var lam = (int x = + } + } + """, indentationLine: 5, expectedIndentation: 12); } @@ -2166,16 +2248,18 @@ public void Main() [WpfFact] public void LambdaDefaultParameter_EnterBeforeEquals() { - var code = @"class Program -{ - public void Main() - { - var lam = (int x - = 10, - int y - = 20) => x + y; - } -}"; + var code = """ + class Program + { + public void Main() + { + var lam = (int x + = 10, + int y + = 20) => x + y; + } + } + """; AssertSmartIndent( code, indentationLine: 5, @@ -2195,16 +2279,17 @@ int y [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530074")] public void EnterInArgumentList1() { - var code = @"class Program -{ - static void Main(string[] args) - { - Main(args, - - } -}"; AssertSmartIndent( - code, + """ + class Program + { + static void Main(string[] args) + { + Main(args, + + } + } + """, indentationLine: 5, expectedIndentation: 12); } @@ -2212,16 +2297,17 @@ static void Main(string[] args) [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530074")] public void EnterInArgumentList2() { - var code = @"class Program -{ - static void Main(string[] args) - { - Main(args, -) - } -}"; AssertSmartIndent( - code, + """ + class Program + { + static void Main(string[] args) + { + Main(args, + ) + } + } + """, indentationLine: 5, expectedIndentation: 12); } @@ -2229,16 +2315,17 @@ static void Main(string[] args) [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/806266")] public void EnterInArgumentList3() { - var code = @"class Program -{ - static void Main(string[] args) - { - var s = string.Format(1, - - } -}"; AssertSmartIndent( - code, + """ + class Program + { + static void Main(string[] args) + { + var s = string.Format(1, + + } + } + """, indentationLine: 5, expectedIndentation: 12); } @@ -2246,17 +2333,18 @@ static void Main(string[] args) [WpfFact, WorkItem(9216, "DevDiv_Projects/Roslyn")] public void FollowPreviousLineInMultilineStatements() { - var code = @"class Program -{ - static void Main(string[] args) - { - var accessibleConstructors = normalType.InstanceConstructors - .Where(c => c.IsAccessibleWithin(within)) - .Where(s => s.IsEditorBrowsable(document.ShouldHideAdvancedMembers(), semanticModel.Compilation)) -.Sort(symbolDisplayService, invocationExpression.GetLocation(), semanticModel); - } -}"; - AssertSmartIndent(code, indentationLine: 7, expectedIndentation: 39); + AssertSmartIndent(""" + class Program + { + static void Main(string[] args) + { + var accessibleConstructors = normalType.InstanceConstructors + .Where(c => c.IsAccessibleWithin(within)) + .Where(s => s.IsEditorBrowsable(document.ShouldHideAdvancedMembers(), semanticModel.Compilation)) + .Sort(symbolDisplayService, invocationExpression.GetLocation(), semanticModel); + } + } + """, indentationLine: 7, expectedIndentation: 39); } [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/648068")] @@ -2264,121 +2352,114 @@ static void Main(string[] args) [WpfFact, Trait(Traits.Feature, Traits.Features.Venus)] public void AtBeginningOfSpanInNugget() { - var markup = @"class Program -{ - static void Main(string[] args) - { -#line ""Goo.aspx"", 27 - {|S1:[| -$$Console.WriteLine();|]|} -#line default -#line hidden - } -}"; AssertSmartIndentInProjection( - markup, BaseIndentationOfNugget + 4); + """ + class Program + { + static void Main(string[] args) + { + #line "Goo.aspx", 27 + {|S1:[| + $$Console.WriteLine();|]|} + #line default + #line hidden + } + } + """, BaseIndentationOfNugget + 4); } [WpfFact, Trait(Traits.Feature, Traits.Features.Venus)] public void AtEndOfSpanInNugget() { - var markup = @"class Program -{ - static void Main(string[] args) - { -#line ""Goo.aspx"", 27 - {|S1:[|Console.WriteLine(); -$$|]|} -#line default -#line hidden - } -}"; AssertSmartIndentInProjection( - markup, BaseIndentationOfNugget + 4); + """ + class Program + { + static void Main(string[] args) + { + #line "Goo.aspx", 27 + {|S1:[|Console.WriteLine(); + $$|]|} + #line default + #line hidden + } + } + """, BaseIndentationOfNugget + 4); } [WpfFact, Trait(Traits.Feature, Traits.Features.Venus)] public void InMiddleOfSpanAtStartOfNugget() { - var markup = @"class Program -{ - static void Main(string[] args) - { -#line ""Goo.aspx"", 27 - {|S1:[|Console.Wri -$$teLine();|]|} -#line default -#line hidden - } -}"; // Again, it doesn't matter where Console _is_ in this case -we format based on // where we think it _should_ be. So the position is one indent level past the base // for the nugget (where we think the statement should be), plus one more since it is // a continuation AssertSmartIndentInProjection( - markup, BaseIndentationOfNugget + 8); + """ + class Program + { + static void Main(string[] args) + { + #line "Goo.aspx", 27 + {|S1:[|Console.Wri + $$teLine();|]|} + #line default + #line hidden + } + } + """, BaseIndentationOfNugget + 8); } [WpfFact, Trait(Traits.Feature, Traits.Features.Venus)] public void InMiddleOfSpanInsideOfNugget() { - var markup = @"class Program -{ - static void Main(string[] args) - { -#line ""Goo.aspx"", 27 - {|S1:[| - Console.Wri -$$teLine();|]|} -#line default -#line hidden - } -}"; // Again, it doesn't matter where Console _is_ in this case -we format based on // where we think it _should_ be. So the position is one indent level past the base // for the nugget (where we think the statement should be), plus one more since it is // a continuation AssertSmartIndentInProjection( - markup, BaseIndentationOfNugget + 8); + """ + class Program + { + static void Main(string[] args) + { + #line "Goo.aspx", 27 + {|S1:[| + Console.Wri + $$teLine();|]|} + #line default + #line hidden + } + } + """, BaseIndentationOfNugget + 8); } [WpfFact, Trait(Traits.Feature, Traits.Features.Venus)] public void AfterStatementInNugget() { - var markup = @"class Program -{ - static void Main(string[] args) - { -#line ""Goo.aspx"", 27 - {|S1:[| - Console.WriteLine(); -$$ - |]|} -#line default -#line hidden - } -}"; AssertSmartIndentInProjection( - markup, BaseIndentationOfNugget + 4); + """ + class Program + { + static void Main(string[] args) + { + #line "Goo.aspx", 27 + {|S1:[| + Console.WriteLine(); + $$ + |]|} + #line default + #line hidden + } + } + """, BaseIndentationOfNugget + 4); } [WpfFact, Trait(Traits.Feature, Traits.Features.Venus)] public void AfterStatementOnFirstLineOfNugget() { - var markup = @"class Program -{ - static void Main(string[] args) - { -#line ""Goo.aspx"", 27 - {|S1:[|Console.WriteLine(); -$$ -|]|} -#line default -#line hidden - } -}"; // TODO: Fix this to indent relative to the previous statement, // instead of relative to the containing scope. I.e. Format like: @@ -2391,90 +2472,107 @@ static void Main(string[] args) // as Roslyn has. The Roslyn formatting engine currently always formats // each statement independently, so let's not change that just for Venus AssertSmartIndentInProjection( - markup, BaseIndentationOfNugget + 4); + """ + class Program + { + static void Main(string[] args) + { + #line "Goo.aspx", 27 + {|S1:[|Console.WriteLine(); + $$ + |]|} + #line default + #line hidden + } + } + """, BaseIndentationOfNugget + 4); } [WpfFact, Trait(Traits.Feature, Traits.Features.Venus)] public void InQueryOnFistLineOfNugget() { - var markup = @"class Program -{ - static void Main(string[] args) - { -#line ""Goo.aspx"", 27 - {|S1:[|var q = from -$$ -|]|} -#line default -#line hidden - } -}"; AssertSmartIndentInProjection( - markup, BaseIndentationOfNugget + 8); + """ + class Program + { + static void Main(string[] args) + { + #line "Goo.aspx", 27 + {|S1:[|var q = from + $$ + |]|} + #line default + #line hidden + } + } + """, BaseIndentationOfNugget + 8); } [WpfFact, Trait(Traits.Feature, Traits.Features.Venus)] public void InQueryInNugget() { - var markup = @"class Program -{ - static void Main(string[] args) - { -#line ""Goo.aspx"", 27 - {|S1:[| - var q = from -$$ -|]|} -#line default -#line hidden - } -}"; AssertSmartIndentInProjection( - markup, BaseIndentationOfNugget + 8); + """ + class Program + { + static void Main(string[] args) + { + #line "Goo.aspx", 27 + {|S1:[| + var q = from + $$ + |]|} + #line default + #line hidden + } + } + """, BaseIndentationOfNugget + 8); } [WorkItem(9216, "DevDiv_Projects/Roslyn")] [WpfFact, Trait(Traits.Feature, Traits.Features.Venus)] public void InsideBracesInNugget() { - var markup = @"class Program -{ - static void Main(string[] args) - { -#line ""Goo.aspx"", 27 - {|S1:[|if (true) - { -$$ - }|]|} -#line default -#line hidden - } -}"; - AssertSmartIndentInProjection(markup, BaseIndentationOfNugget + 8); + AssertSmartIndentInProjection(""" + class Program + { + static void Main(string[] args) + { + #line "Goo.aspx", 27 + {|S1:[|if (true) + { + $$ + }|]|} + #line default + #line hidden + } + } + """, BaseIndentationOfNugget + 8); } [WorkItem(9216, "DevDiv_Projects/Roslyn")] [WpfFact, Trait(Traits.Feature, Traits.Features.Venus)] public void AfterEmbeddedStatementOnFirstLineOfNugget() { - var markup = @"class Program - { - static void Main(string[] args) - { - #line ""Goo.aspx"", 27 - {|S1:[|if (true) - { - } - $$ -|]|} - #line default - #line hidden - } - }"; // In this case, we align the next statement with the "if" (though we _don't_ // align the braces with it :S) - AssertSmartIndentInProjection(markup, + AssertSmartIndentInProjection(""" + class Program + { + static void Main(string[] args) + { + #line "Goo.aspx", 27 + {|S1:[|if (true) + { + } + $$ + |]|} + #line default + #line hidden + } + } + """, expectedIndentation: BaseIndentationOfNugget + 2); } @@ -2482,24 +2580,25 @@ static void Main(string[] args) [WpfFact, Trait(Traits.Feature, Traits.Features.Venus)] public void AfterEmbeddedStatementInNugget() { - var markup = @"class Program - { - static void Main(string[] args) - { - #line ""Goo.aspx"", 27 - {|S1:[| - if (true) - { - } -$$ -|]|} - #line default - #line hidden - } - }"; // In this case we align with the "if", - the base indentation we pass in doesn't matter. - AssertSmartIndentInProjection(markup, + AssertSmartIndentInProjection(""" + class Program + { + static void Main(string[] args) + { + #line "Goo.aspx", 27 + {|S1:[| + if (true) + { + } + $$ + |]|} + #line default + #line hidden + } + } + """, expectedIndentation: BaseIndentationOfNugget + 4); } @@ -2508,25 +2607,26 @@ static void Main(string[] args) [WpfFact, Trait(Traits.Feature, Traits.Features.Venus)] public void AfterSwitchStatementAtEndOfNugget() { - var markup = @" -class Program -{ - static void Main(string[] args) - { -#line ""Goo.aspx"", 27 - {|S1:[|switch (10) - { - case 10: -$$ - }|]|} -#line default -#line hidden - } -}"; // It's yuck that I saw differences depending on where the end of the nugget is // but I did, so lets add a test. - AssertSmartIndentInProjection(markup, + AssertSmartIndentInProjection(""" + + class Program + { + static void Main(string[] args) + { + #line "Goo.aspx", 27 + {|S1:[|switch (10) + { + case 10: + $$ + }|]|} + #line default + #line hidden + } + } + """, expectedIndentation: BaseIndentationOfNugget + 12); } @@ -2535,43 +2635,43 @@ static void Main(string[] args) [WpfFact, Trait(Traits.Feature, Traits.Features.Venus)] public void AfterSwitchStatementInNugget() { - var markup = @" -class Program -{ - static void Main(string[] args) - { -#line ""Goo.aspx"", 27 - {|S1:[|switch (10) + AssertSmartIndentInProjection(""" + + class Program { - case 10: -$$ + static void Main(string[] args) + { + #line "Goo.aspx", 27 + {|S1:[|switch (10) + { + case 10: + $$ + } + |]|} + #line default + #line hidden + } } -|]|} -#line default -#line hidden - } -}"; - - AssertSmartIndentInProjection(markup, + """, expectedIndentation: BaseIndentationOfNugget + 12); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529876"), Trait(Traits.Feature, Traits.Features.SmartIndent), Trait(Traits.Feature, Traits.Features.Venus)] public void InEmptyNugget() { - var markup = @"class Program - { - static void Main(string[] args) - { - #line ""Goo.aspx"", 27 - {|S1:[| -$$|]|} - #line default - #line hidden - } - }"; - - AssertSmartIndentInProjection(markup, + AssertSmartIndentInProjection(""" + class Program + { + static void Main(string[] args) + { + #line "Goo.aspx", 27 + {|S1:[| + $$|]|} + #line default + #line hidden + } + } + """, expectedIndentation: BaseIndentationOfNugget + 4); } @@ -2579,87 +2679,87 @@ static void Main(string[] args) [WpfFact, Trait(Traits.Feature, Traits.Features.Venus)] public void GetNextTokenForFormattingSpanCalculationIncludesZeroWidthToken_CS() { - var markup = @"//------------------------------------------------------------------------------ -// -// 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 ASP { -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Web; -using System.Web.Helpers; -using System.Web.Security; -using System.Web.UI; -using System.Web.WebPages; -using System.Web.WebPages.Html; -using WebMatrix.Data; -using WebMatrix.WebData; -using Microsoft.Web.WebPages.OAuth; -using DotNetOpenAuth.AspNet; - -public class _Page_Default_cshtml : System.Web.WebPages.WebPage { -#line hidden -public _Page_Default_cshtml() { -} -protected System.Web.HttpApplication ApplicationInstance { -get { -return ((System.Web.HttpApplication)(Context.ApplicationInstance)); -} -} -public override void Execute() { - -#line 1 ""C:\Users\basoundr\Documents\Visual Studio 2015\WebSites\WebSite6\Default.cshtml"" + AssertSmartIndentInProjection(""" + //------------------------------------------------------------------------------ + // + // 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 ASP { + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Net; + using System.Web; + using System.Web.Helpers; + using System.Web.Security; + using System.Web.UI; + using System.Web.WebPages; + using System.Web.WebPages.Html; + using WebMatrix.Data; + using WebMatrix.WebData; + using Microsoft.Web.WebPages.OAuth; + using DotNetOpenAuth.AspNet; + + public class _Page_Default_cshtml : System.Web.WebPages.WebPage { + #line hidden + public _Page_Default_cshtml() { + } + protected System.Web.HttpApplication ApplicationInstance { + get { + return ((System.Web.HttpApplication)(Context.ApplicationInstance)); + } + } + public override void Execute() { - {|S1:[|public class LanguagePreference - { + #line 1 "C:\Users\basoundr\Documents\Visual Studio 2015\WebSites\WebSite6\Default.cshtml" - } + {|S1:[|public class LanguagePreference + { -if (!File.Exists(physicalPath)) -{ - Context.Response.SetStatus(HttpStatusCode.NotFound); - return; -} -$$ - string[] languages = Context.Request.UserLanguages; + } -if(languages == null || languages.Length == 0) -{ + if (!File.Exists(physicalPath)) + { + Context.Response.SetStatus(HttpStatusCode.NotFound); + return; + } + $$ + string[] languages = Context.Request.UserLanguages; - Response.Redirect() - } + if(languages == null || languages.Length == 0) + { -|]|} -#line default -#line hidden -} -} -}"; + Response.Redirect() + } - AssertSmartIndentInProjection(markup, + |]|} + #line default + #line hidden + } + } + } + """, expectedIndentation: 24); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530948"), Trait(Traits.Feature, Traits.Features.SmartIndent)] public void CommaSeparatedListEnumMembers() { - var code = @"enum MyEnum -{ - e1, - -}"; - AssertSmartIndent( - code, + """ + enum MyEnum + { + e1, + + } + """, indentationLine: 3, expectedIndentation: 4); } @@ -2667,20 +2767,20 @@ public void CommaSeparatedListEnumMembers() [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530796"), Trait(Traits.Feature, Traits.Features.SmartIndent)] public void RelativeIndentationForBracesInExpression() { - var code = @"class C -{ - void M(C c) - { - M(new C() - { + AssertSmartIndent( + """ + class C + { + void M(C c) + { + M(new C() + { - }); - } -} -"; + }); + } + } - AssertSmartIndent( - code, + """, indentationLine: 6, expectedIndentation: 12); } @@ -2688,24 +2788,26 @@ void M(C c) [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/584599"), Trait(Traits.Feature, Traits.Features.SmartIndent)] public void SwitchSection() { - var code = @"class C -{ - void Method() - { - switch (i) - { + var code = """ + class C + { + void Method() + { + switch (i) + { - case 1: + case 1: - case 2: + case 2: - int i2 = 10; + int i2 = 10; - case 4: + case 4: - } - } -}"; + } + } + } + """; AssertSmartIndent( code, @@ -2736,29 +2838,31 @@ void Method() [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/584599"), Trait(Traits.Feature, Traits.Features.SmartIndent)] public void SwitchSection2() { - var code = @"class C -{ - void Method() - { - switch (i) - { - // test + var code = """ + class C + { + void Method() + { + switch (i) + { + // test - case 1: - // test + case 1: + // test - case 2: - // test + case 2: + // test - int i2 = 10; - // test + int i2 = 10; + // test - case 4: - // test + case 4: + // test - } - } -}"; + } + } + } + """; AssertSmartIndent( code, @@ -2789,19 +2893,21 @@ void Method() [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/584599"), Trait(Traits.Feature, Traits.Features.SmartIndent)] public void CommentAtTheEndOfLine() { - var code = @"using System; + var code = """ + using System; -class Program -{ - static void Main(string[] args) - { - Console.WriteLine(); /* this is a comment */ - // that I would like to keep + class Program + { + static void Main(string[] args) + { + Console.WriteLine(); /* this is a comment */ + // that I would like to keep - // properly indented - } -}"; + // properly indented + } + } + """; AssertSmartIndent( code, @@ -2817,19 +2923,21 @@ static void Main(string[] args) [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912735"), Trait(Traits.Feature, Traits.Features.SmartIndent)] public void CommentAtTheEndOfLineWithExecutableAfterCaret() { - var code = @"using System; + var code = """ + using System; -class Program -{ - static void Main(string[] args) - { - // A - // B + class Program + { + static void Main(string[] args) + { + // A + // B - return; - } -}"; + return; + } + } + """; AssertSmartIndent( code, @@ -2845,23 +2953,25 @@ static void Main(string[] args) [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912735"), Trait(Traits.Feature, Traits.Features.SmartIndent)] public void CommentAtTheEndOfLineInsideInitializer() { - var code = @"using System; -using System.Collections.Generic; + var code = """ + using System; + using System.Collections.Generic; -class Program -{ - static void Main(string[] args) - { - var s = new List - { - """", - """",/*sdfsdfsdfsdf*/ - // dfsdfsdfsdfsdf + class Program + { + static void Main(string[] args) + { + var s = new List + { + "", + "",/*sdfsdfsdfsdf*/ + // dfsdfsdfsdfsdf - }; - } -}"; + }; + } + } + """; AssertSmartIndent( code, @@ -2877,48 +2987,48 @@ static void Main(string[] args) [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/5495")] public void AfterBadQueryContinuationWithSelectOrGroupClause() { - var code = @"using System.Collections.Generic; -using System.Linq; - -namespace ConsoleApplication1 -{ - class AutomapperConfig - { - public static IEnumerable ConfigureMappings(string name) - { - List anEntireSlewOfItems = new List(); - List viewModels = new List(); - - var items = (from m in anEntireSlewOfItems into man - - join at in viewModels on m.id equals at.id - join c in viewModels on m.name equals c.name - join ct in viewModels on m.phonenumber equals ct.phonenumber - where m.id == 1 && - m.name == name - select new { M = true, I = at, AT = at }).ToList(); - //Mapper.CreateMap() - // .ForMember(t => t.) - } - } + AssertSmartIndent( + """ + using System.Collections.Generic; + using System.Linq; - class User - { - public int id { get; set; } - public string name { get; set; } - public int phonenumber { get; set; } - } + namespace ConsoleApplication1 + { + class AutomapperConfig + { + public static IEnumerable ConfigureMappings(string name) + { + List anEntireSlewOfItems = new List(); + List viewModels = new List(); + + var items = (from m in anEntireSlewOfItems into man + + join at in viewModels on m.id equals at.id + join c in viewModels on m.name equals c.name + join ct in viewModels on m.phonenumber equals ct.phonenumber + where m.id == 1 && + m.name == name + select new { M = true, I = at, AT = at }).ToList(); + //Mapper.CreateMap() + // .ForMember(t => t.) + } + } - class UserViewModel - { - public int id { get; set; } - public string name { get; set; } - public int phonenumber { get; set; } - } -}"; + class User + { + public int id { get; set; } + public string name { get; set; } + public int phonenumber { get; set; } + } - AssertSmartIndent( - code, + class UserViewModel + { + public int id { get; set; } + public string name { get; set; } + public int phonenumber { get; set; } + } + } + """, indentationLine: 13, expectedIndentation: 25); } @@ -2926,20 +3036,21 @@ class UserViewModel [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/5495")] public void AfterPartialFromClause() { - var code = @" -using System.Linq; + AssertSmartIndent( + """ -class C -{ - void M() - { - var q = from x + using System.Linq; - } -} -"; - AssertSmartIndent( - code, + class C + { + void M() + { + var q = from x + + } + } + + """, indentationLine: 8, expectedIndentation: 16); } @@ -2947,17 +3058,17 @@ void M() [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/5635")] public void ConstructorInitializerMissingBaseOrThisKeyword() { - var code = @" -class C -{ - C(string s) - : + AssertSmartIndent( + """ -} -"; + class C + { + C(string s) + : - AssertSmartIndent( - code, + } + + """, indentationLine: 5, expectedIndentation: 8); } @@ -2965,19 +3076,19 @@ class C [WpfFact] public void CreateIndentOperationForBrokenBracketedArgumentList() { - var code = @" -class Program -{ - static void M() - { - string (userInput == ""Y"") + AssertSmartIndent( + """ - } -} -"; + class Program + { + static void M() + { + string (userInput == "Y") - AssertSmartIndent( - code, + } + } + + """, indentationLine: 6, expectedIndentation: 12); } @@ -2985,20 +3096,20 @@ static void M() [WpfFact] public void PatternPropertyIndentFirst() { - var code = @" -class C -{ - void M(object o) - { - var y = o is Point - { + AssertSmartIndent( + """ - } - } -}"; + class C + { + void M(object o) + { + var y = o is Point + { - AssertSmartIndent( - code, + } + } + } + """, indentationLine: 7, expectedIndentation: 12); } @@ -3006,21 +3117,21 @@ void M(object o) [WpfFact] public void PatternPropertyIndentSecond() { - var code = @" -class C -{ - void M(object o) - { - var y = o is Point - { - X is 4, + AssertSmartIndent( + """ - } - } -}"; + class C + { + void M(object o) + { + var y = o is Point + { + X is 4, - AssertSmartIndent( - code, + } + } + } + """, indentationLine: 8, expectedIndentation: 12); } @@ -3028,24 +3139,24 @@ void M(object o) [WpfFact] public void PatternPropertyIndentNestedFirst() { - var code = @" -class C -{ - void M(object o) - { - var y = o is Point - { - X is Widget - { + AssertSmartIndent( + """ - }, + class C + { + void M(object o) + { + var y = o is Point + { + X is Widget + { - } - } -}"; + }, - AssertSmartIndent( - code, + } + } + } + """, indentationLine: 9, expectedIndentation: 16); } @@ -3053,24 +3164,24 @@ X is Widget [WpfFact] public void PatternPropertyIndentNestedSecond() { - var code = @" -class C -{ - void M(object o) - { - var y = o is Point - { - X is Widget - { - Y is 42, + AssertSmartIndent( + """ - }, - } - } -}"; + class C + { + void M(object o) + { + var y = o is Point + { + X is Widget + { + Y is 42, - AssertSmartIndent( - code, + }, + } + } + } + """, indentationLine: 10, expectedIndentation: 16); } @@ -3078,17 +3189,19 @@ X is Widget [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/33253")] public void EnterAfterFluentSequences_1() { - var code = @"public class Test -{ - public void Test() - { - new List() - .Where(d => d.Kind == DateTimeKind.Local || - d.Kind == DateTimeKind.Utc) + var code = """ + public class Test + { + public void Test() + { + new List() + .Where(d => d.Kind == DateTimeKind.Local || + d.Kind == DateTimeKind.Utc) - .ToArray(); - } -}"; + .ToArray(); + } + } + """; AssertSmartIndent( code: code, @@ -3099,17 +3212,19 @@ public void Test() [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/33253")] public void EnterAfterFluentSequences_2() { - var code = @"public class Test -{ - public void Test() - { - new List() - .Where(d => d.Kind == DateTimeKind.Local || - d.Kind == DateTimeKind.Utc) + var code = """ + public class Test + { + public void Test() + { + new List() + .Where(d => d.Kind == DateTimeKind.Local || + d.Kind == DateTimeKind.Utc) - .ToArray(); - } -}"; + .ToArray(); + } + } + """; AssertSmartIndent( code: code, @@ -3120,16 +3235,18 @@ public void Test() [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/33253")] public void EnterAfterFluentSequences_3() { - var code = @"public class Test -{ - public void Test() - { - new List().Where(d => d.Kind == DateTimeKind.Local || - d.Kind == DateTimeKind.Utc) + var code = """ + public class Test + { + public void Test() + { + new List().Where(d => d.Kind == DateTimeKind.Local || + d.Kind == DateTimeKind.Utc) - .ToArray(); - } -}"; + .ToArray(); + } + } + """; AssertSmartIndent( code: code, @@ -3140,15 +3257,17 @@ public void Test() [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/33253")] public void EnterAfterFluentSequences_4() { - var code = @"public class Test -{ - public void Test() - { - new List().Where(d => d.Kind == DateTimeKind.Local || d.Kind == DateTimeKind.Utc) + var code = """ + public class Test + { + public void Test() + { + new List().Where(d => d.Kind == DateTimeKind.Local || d.Kind == DateTimeKind.Utc) - .ToArray(); - } -}"; + .ToArray(); + } + } + """; AssertSmartIndent( code: code, @@ -3159,15 +3278,17 @@ public void Test() [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/28752")] public void EnterAfterBlankLineAfterCommentedOutCode1() { - var code = @"class Test -{ - public void Test() - { - // comment + var code = """ + class Test + { + public void Test() + { + // comment - } -}"; + } + } + """; AssertSmartIndent( code: code, @@ -3183,16 +3304,18 @@ public void Test() [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/28752")] public void EnterAfterBlankLineAfterCommentedOutCode2() { - var code = @" -class T -{ - // comment + var code = """ + + class T + { + // comment - // comment - int i = 1; -}"; + // comment + int i = 1; + } + """; AssertSmartIndent( code: code, @@ -3213,15 +3336,17 @@ class T [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/38819")] public void IndentationOfReturnInFileWithTabs1() { - var code = @" -public class Example -{ - public void Test(object session) - { - if (session == null) -return; - } -}"; + var code = """ + + public class Example + { + public void Test(object session) + { + if (session == null) + return; + } + } + """; // Ensure the test code doesn't get switched to spaces Assert.Contains("\t\tif (session == null)", code); AssertSmartIndent( @@ -3236,18 +3361,18 @@ public void Test(object session) [WpfFact] public void Operator() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ - class Class - { - public static Class operator +(Class x, Class y) + namespace NS + { + class Class + { + public static Class operator +(Class x, Class y) -"; - AssertSmartIndent( - code, + """, indentationLine: 7, expectedIndentation: 12); } @@ -3255,18 +3380,18 @@ class Class [WpfFact] public void CastOperator() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ - class Class - { - public static explicit operator Class(int x) + namespace NS + { + class Class + { + public static explicit operator Class(int x) -"; - AssertSmartIndent( - code, + """, indentationLine: 7, expectedIndentation: 12); } @@ -3274,19 +3399,19 @@ public static explicit operator Class(int x) [WpfFact] public void OperatorBody() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ - class Class - { - public static Class operator +(Class x, Class y) - { + namespace NS + { + class Class + { + public static Class operator +(Class x, Class y) + { -"; - AssertSmartIndent( - code, + """, indentationLine: 8, expectedIndentation: 12); } @@ -3294,19 +3419,19 @@ class Class [WpfFact] public void CastOperatorBody() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ - class Class - { - public static explicit operator Class(int x) - { + namespace NS + { + class Class + { + public static explicit operator Class(int x) + { -"; - AssertSmartIndent( - code, + """, indentationLine: 8, expectedIndentation: 12); } @@ -3314,18 +3439,18 @@ public static explicit operator Class(int x) [WpfFact] public void CheckedOperator() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ - class Class - { - public static Class operator checked +(Class x, Class y) + namespace NS + { + class Class + { + public static Class operator checked +(Class x, Class y) -"; - AssertSmartIndent( - code, + """, indentationLine: 7, expectedIndentation: 12, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp12)); @@ -3334,18 +3459,18 @@ class Class [WpfFact] public void ExplicitCastCheckedOperator() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ - class Class - { - public static explicit operator checked Class(int x) + namespace NS + { + class Class + { + public static explicit operator checked Class(int x) -"; - AssertSmartIndent( - code, + """, indentationLine: 7, expectedIndentation: 12, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp12)); @@ -3354,19 +3479,19 @@ public static explicit operator checked Class(int x) [WpfFact] public void CheckedOperatorBody() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ - class Class - { - public static Class operator checked +(Class x, Class y) - { + namespace NS + { + class Class + { + public static Class operator checked +(Class x, Class y) + { -"; - AssertSmartIndent( - code, + """, indentationLine: 8, expectedIndentation: 12, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp12)); @@ -3375,19 +3500,19 @@ class Class [WpfFact] public void ExplicitCastCheckedOperatorBody() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ - class Class - { - public static explicit operator checked Class(int x) - { + namespace NS + { + class Class + { + public static explicit operator checked Class(int x) + { -"; - AssertSmartIndent( - code, + """, indentationLine: 8, expectedIndentation: 12, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp12)); @@ -3396,18 +3521,18 @@ public static explicit operator checked Class(int x) [WpfFact] public void UnsignedRightShift() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ - class Class - { - public static Class operator >>>(Class x, Class y) + namespace NS + { + class Class + { + public static Class operator >>>(Class x, Class y) -"; - AssertSmartIndent( - code, + """, indentationLine: 7, expectedIndentation: 12); } @@ -3415,19 +3540,19 @@ class Class [WpfFact] public void UnsignedRightShiftBody() { - var code = @"using System; + AssertSmartIndent( + """ + using System; -namespace NS -{ - class Class - { - public static Class operator >>>(Class x, Class y) - { + namespace NS + { + class Class + { + public static Class operator >>>(Class x, Class y) + { -"; - AssertSmartIndent( - code, + """, indentationLine: 8, expectedIndentation: 12); } @@ -3436,15 +3561,19 @@ class Class [CombinatorialData] public void InstanceIncrementOperator([CombinatorialValues("++", "--")] string op, bool isChecked) { - var code = @"using System; + var code = """ + using System; -namespace NS -{ - class Class - { - public void operator " + (isChecked ? "checked " : "") + op + @"() + namespace NS + { + class Class + { + public void operator + """ + (isChecked ? "checked " : "") + op + """ + () -"; + + """; AssertSmartIndent( code, @@ -3456,16 +3585,20 @@ class Class [CombinatorialData] public void InstanceIncrementOperatorBody([CombinatorialValues("++", "--")] string op, bool isChecked) { - var code = @"using System; + var code = """ + using System; + + namespace NS + { + class Class + { + public void operator + """ + (isChecked ? "checked " : "") + op + """ + () + { -namespace NS -{ - class Class - { - public void operator " + (isChecked ? "checked " : "") + op + @"() - { -"; + """; AssertSmartIndent( code, @@ -3477,15 +3610,19 @@ class Class [CombinatorialData] public void InstanceCompoundAssignmentOperator([CombinatorialValues("+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", ">>>=")] string op, bool isChecked) { - var code = @"using System; + var code = """ + using System; -namespace NS -{ - class Class - { - public static Class operator " + (isChecked ? "checked " : "") + op + @"(Class x) + namespace NS + { + class Class + { + public static Class operator + """ + (isChecked ? "checked " : "") + op + """ + (Class x) -"; + + """; AssertSmartIndent( code, @@ -3497,16 +3634,20 @@ class Class [CombinatorialData] public void InstanceCompoundAssignmentOperatorBody([CombinatorialValues("+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", ">>>=")] string op, bool isChecked) { - var code = @"using System; + var code = """ + using System; + + namespace NS + { + class Class + { + public static Class operator + """ + (isChecked ? "checked " : "") + op + """ + (Class x) + { -namespace NS -{ - class Class - { - public static Class operator " + (isChecked ? "checked " : "") + op + @"(Class x) - { -"; + """; AssertSmartIndent( code, diff --git a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterTests_Performance.cs b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterTests_Performance.cs index 64329c6230877..51b82f4d03a33 100644 --- a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterTests_Performance.cs +++ b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterTests_Performance.cs @@ -17,9 +17,12 @@ public sealed partial class SmartIndenterTests [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void RegionPerformance() { - var code = + #region very long sample code -""" + #endregion + + AssertSmartIndent( + """ using System; using System.Collections.Generic; @@ -2208,11 +2211,7 @@ static void Main() { } } - """; - #endregion - - AssertSmartIndent( - code, + """, expectedIndentation: 12); } } diff --git a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatRangeTests.cs b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatRangeTests.cs index 0a846f1b4df70..a11b96c1e83a5 100644 --- a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatRangeTests.cs +++ b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatRangeTests.cs @@ -36,2163 +36,1973 @@ public sealed class SmartTokenFormatterFormatRangeTests [Fact] public async Task BeginningOfFile() { - var code = @" using System;$$"; - var expected = @" using System;"; - - Assert.NotNull(await Record.ExceptionAsync(() => AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.None))); + Assert.NotNull(await Record.ExceptionAsync(() => AutoFormatOnSemicolonAsync(@" using System;$$", @" using System;", SyntaxKind.None))); } [WpfFact] - public async Task Namespace1() - { - var code = @"using System; -namespace NS -{ - - }$$"; - - var expected = @"using System; -namespace NS -{ + public Task Namespace1() + => AutoFormatOnCloseBraceAsync(""" + using System; + namespace NS + { -}"; + }$$ + """, """ + using System; + namespace NS + { - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); - } + } + """, SyntaxKind.SemicolonToken); [WpfFact] - public async Task Namespace2() - { - var code = @"using System; -namespace NS -{ - class Class + public Task Namespace2() + => AutoFormatOnCloseBraceAsync(""" + using System; + namespace NS + { + class Class + { + } + }$$ + """, """ + using System; + namespace NS + { + class Class { - } - }$$"; - - var expected = @"using System; -namespace NS -{ - class Class - { - } -}"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); - } + } + } + """, SyntaxKind.SemicolonToken); [WpfFact] - public async Task Namespace3() - { - var code = @"using System; -namespace NS { }$$"; - - var expected = @"using System; -namespace NS { }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); - } + public Task Namespace3() + => AutoFormatOnCloseBraceAsync(""" + using System; + namespace NS { }$$ + """, """ + using System; + namespace NS { } + """, SyntaxKind.SemicolonToken); [WpfFact] - public async Task Namespace4() - { - var code = @"using System; -namespace NS { -}$$"; - - var expected = @"using System; -namespace NS -{ -}"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); - } + public Task Namespace4() + => AutoFormatOnCloseBraceAsync(""" + using System; + namespace NS { + }$$ + """, """ + using System; + namespace NS + { + } + """, SyntaxKind.SemicolonToken); [WpfFact] - public async Task Namespace5() - { - var code = @"using System; -namespace NS -{ - class Class { } -}$$"; - - var expected = @"using System; -namespace NS -{ - class Class { } -}"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); - } + public Task Namespace5() + => AutoFormatOnCloseBraceAsync(""" + using System; + namespace NS + { + class Class { } + }$$ + """, """ + using System; + namespace NS + { + class Class { } + } + """, SyntaxKind.SemicolonToken); [WpfFact] - public async Task Namespace6() - { - var code = @"using System; -namespace NS -{ - class Class { -} -}$$"; - - var expected = @"using System; -namespace NS -{ - class Class - { - } -}"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); - } + public Task Namespace6() + => AutoFormatOnCloseBraceAsync(""" + using System; + namespace NS + { + class Class { + } + }$$ + """, """ + using System; + namespace NS + { + class Class + { + } + } + """, SyntaxKind.SemicolonToken); [WpfFact] - public async Task Namespace7() - { - var code = @"using System; -namespace NS -{ - class Class { -} - namespace NS2 -{} -}$$"; - - var expected = @"using System; -namespace NS -{ - class Class - { - } - namespace NS2 - { } -}"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); - } + public Task Namespace7() + => AutoFormatOnCloseBraceAsync(""" + using System; + namespace NS + { + class Class { + } + namespace NS2 + {} + }$$ + """, """ + using System; + namespace NS + { + class Class + { + } + namespace NS2 + { } + } + """, SyntaxKind.SemicolonToken); [WpfFact] - public async Task Namespace8() - { - var code = @"using System; -namespace NS { class Class { } namespace NS2 { } }$$"; - - var expected = @"using System; -namespace NS { class Class { } namespace NS2 { } }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); - } + public Task Namespace8() + => AutoFormatOnCloseBraceAsync(""" + using System; + namespace NS { class Class { } namespace NS2 { } }$$ + """, """ + using System; + namespace NS { class Class { } namespace NS2 { } } + """, SyntaxKind.SemicolonToken); [WpfFact] - public async Task Class1() - { - var code = @"using System; - class Class { -}$$"; - - var expected = @"using System; -class Class -{ -}"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); - } + public Task Class1() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class { + }$$ + """, """ + using System; + class Class + { + } + """, SyntaxKind.SemicolonToken); [WpfFact] - public async Task Class2() - { - var code = @"using System; - class Class -{ - void Method(int i) { + public Task Class2() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + void Method(int i) { + } + }$$ + """, """ + using System; + class Class + { + void Method(int i) + { } -}$$"; - - var expected = @"using System; -class Class -{ - void Method(int i) - { - } -}"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); - } + } + """, SyntaxKind.SemicolonToken); [WpfFact] - public async Task Class3() - { - var code = @"using System; - class Class -{ - void Method(int i) { } -}$$"; - - var expected = @"using System; -class Class -{ - void Method(int i) { } -}"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); - } + public Task Class3() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + void Method(int i) { } + }$$ + """, """ + using System; + class Class + { + void Method(int i) { } + } + """, SyntaxKind.SemicolonToken); [WpfFact] - public async Task Class4() - { - var code = @"using System; - class Class -{ - delegate void Test(int i); -}$$"; - - var expected = @"using System; -class Class -{ - delegate void Test(int i); -}"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); - } + public Task Class4() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + delegate void Test(int i); + }$$ + """, """ + using System; + class Class + { + delegate void Test(int i); + } + """, SyntaxKind.SemicolonToken); [WpfFact] - public async Task Class5() - { - var code = @"using System; - class Class -{ - delegate void Test(int i); - void Method() - { + public Task Class5() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + delegate void Test(int i); + void Method() + { + } + }$$ + """, """ + using System; + class Class + { + delegate void Test(int i); + void Method() + { } -}$$"; - - var expected = @"using System; -class Class -{ - delegate void Test(int i); - void Method() - { - } -}"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); - } + } + """, SyntaxKind.SemicolonToken); [WpfFact] - public async Task Interface1() - { - var code = @"using System; - interface II -{ - delegate void Test(int i); -int Prop { get; set; } -}$$"; - - var expected = @"using System; -interface II -{ - delegate void Test(int i); - int Prop { get; set; } -}"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); - } + public Task Interface1() + => AutoFormatOnCloseBraceAsync(""" + using System; + interface II + { + delegate void Test(int i); + int Prop { get; set; } + }$$ + """, """ + using System; + interface II + { + delegate void Test(int i); + int Prop { get; set; } + } + """, SyntaxKind.SemicolonToken); [WpfFact] - public async Task Struct1() - { - var code = @"using System; - struct Struct -{ - Struct(int i) - { + public Task Struct1() + => AutoFormatOnCloseBraceAsync(""" + using System; + struct Struct + { + Struct(int i) + { + } + }$$ + """, """ + using System; + struct Struct + { + Struct(int i) + { } -}$$"; - - var expected = @"using System; -struct Struct -{ - Struct(int i) - { - } -}"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); - } + } + """, SyntaxKind.SemicolonToken); [WpfFact] - public async Task Enum1() - { - var code = @"using System; - enum Enum -{ + public Task Enum1() + => AutoFormatOnCloseBraceAsync(""" + using System; + enum Enum + { + A = 1, B = 2, + C = 3 + }$$ + """, """ + using System; + enum Enum + { A = 1, B = 2, - C = 3 - }$$"; - - var expected = @"using System; -enum Enum -{ - A = 1, B = 2, - C = 3 -}"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); - } + C = 3 + } + """, SyntaxKind.SemicolonToken); [WpfFact] - public async Task AccessorList1() - { - var code = @"using System; -class Class -{ - int Prop { get { return 1; }$$"; - - var expected = @"using System; -class Class -{ - int Prop { get { return 1; }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task AccessorList1() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + int Prop { get { return 1; }$$ + """, """ + using System; + class Class + { + int Prop { get { return 1; } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task AccessorList2() - { - var code = @"using System; -class Class -{ - int Prop { get { return 1; } }$$"; - - var expected = @"using System; -class Class -{ - int Prop { get { return 1; } }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.IntKeyword); - } + public Task AccessorList2() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + int Prop { get { return 1; } }$$ + """, """ + using System; + class Class + { + int Prop { get { return 1; } } + """, SyntaxKind.IntKeyword); [WpfFact] - public async Task AccessorList3() - { - var code = @"using System; -class Class -{ - int Prop { get { return 1; } -}$$"; - - var expected = @"using System; -class Class -{ - int Prop - { - get { return 1; } - }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.IntKeyword); - } + public Task AccessorList3() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + int Prop { get { return 1; } + }$$ + """, """ + using System; + class Class + { + int Prop + { + get { return 1; } + } + """, SyntaxKind.IntKeyword); [WpfFact] - public async Task AccessorList4() - { - var code = @"using System; -class Class -{ - int Prop { get { return 1; -}$$"; - - var expected = @"using System; -class Class -{ - int Prop { get - { - return 1; - }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.GetKeyword); - } + public Task AccessorList4() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + int Prop { get { return 1; + }$$ + """, """ + using System; + class Class + { + int Prop { get + { + return 1; + } + """, SyntaxKind.GetKeyword); [WpfFact] - public async Task AccessorList5() - { - var code = @"using System; -class Class -{ - int Prop { - get { return 1; -}$$"; - - var expected = @"using System; -class Class -{ - int Prop { - get { return 1; - }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task AccessorList5() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + int Prop { + get { return 1; + }$$ + """, """ + using System; + class Class + { + int Prop { + get { return 1; + } + """, SyntaxKind.OpenBraceToken); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/16984")] - public async Task AccessorList5b() - { - var code = @"using System; -class Class -{ - int Prop { - get { return 1; -}$$ -} -}"; - - var expected = @"using System; -class Class -{ - int Prop { - get - { - return 1; - } -} -}"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } - - [WpfFact] - public async Task AccessorList6() - { - var code = @"using System; -class Class -{ - int Prop - { -get { return 1; -} }$$"; - - var expected = @"using System; -class Class -{ - int Prop - { - get - { - return 1; - } - }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.IntKeyword); - } + public Task AccessorList5b() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + int Prop { + get { return 1; + }$$ + } + } + """, """ + using System; + class Class + { + int Prop { + get + { + return 1; + } + } + } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task AccessorList7() - { - var code = @"using System; -class Class -{ - int Prop - { - get - { -return 1;$$ - } - }"; - - var expected = @"using System; -class Class -{ - int Prop - { - get - { - return 1; - } - }"; + public Task AccessorList6() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + int Prop + { + get { return 1; + } }$$ + """, """ + using System; + class Class + { + int Prop + { + get + { + return 1; + } + } + """, SyntaxKind.IntKeyword); - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); - } + [WpfFact] + public Task AccessorList7() + => AutoFormatOnSemicolonAsync(""" + using System; + class Class + { + int Prop + { + get + { + return 1;$$ + } + } + """, """ + using System; + class Class + { + int Prop + { + get + { + return 1; + } + } + """, SyntaxKind.OpenBraceToken); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/16984")] - public async Task AccessorList8() - { - var code = @"class C -{ - int Prop - { -get - { - return 0; - }$$ - } -}"; - - var expected = @"class C -{ - int Prop - { - get - { - return 0; - } - } -}"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task AccessorList8() + => AutoFormatOnCloseBraceAsync(""" + class C + { + int Prop + { + get + { + return 0; + }$$ + } + } + """, """ + class C + { + int Prop + { + get + { + return 0; + } + } + } + """, SyntaxKind.OpenBraceToken); [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/16984")] [InlineData("get")] [InlineData("set")] [InlineData("init")] - public async Task AccessorList9(string accessor) - { - var code = $@"class C -{{ - int Prop - {{ -{accessor} - {{ - ; - }}$$ - }} -}}"; - - var expected = $@"class C -{{ - int Prop - {{ - {accessor} - {{ - ; - }} - }} -}}"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task AccessorList9(string accessor) + => AutoFormatOnCloseBraceAsync($$""" + class C + { + int Prop + { + {{accessor}} + { + ; + }$$ + } + } + """, $$""" + class C + { + int Prop + { + {{accessor}} + { + ; + } + } + } + """, SyntaxKind.OpenBraceToken); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/16984")] - public async Task AccessorList10() - { - var code = @"class C -{ - event EventHandler E - { -add - { - }$$ - remove - { - } - } - -}"; - - var expected = @"class C -{ - event EventHandler E - { - add - { - } - remove - { - } - } + public Task AccessorList10() + => AutoFormatOnCloseBraceAsync(""" + class C + { + event EventHandler E + { + add + { + }$$ + remove + { + } + } -}"; + } + """, """ + class C + { + event EventHandler E + { + add + { + } + remove + { + } + } - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + } + """, SyntaxKind.OpenBraceToken); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/16984")] - public async Task AccessorList11() - { - var code = @"class C -{ - event EventHandler E - { - add - { - } -remove - { - }$$ - } - -}"; - - var expected = @"class C -{ - event EventHandler E - { - add - { - } - remove - { - } - } + public Task AccessorList11() + => AutoFormatOnCloseBraceAsync(""" + class C + { + event EventHandler E + { + add + { + } + remove + { + }$$ + } -}"; + } + """, """ + class C + { + event EventHandler E + { + add + { + } + remove + { + } + } - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.CloseBraceToken); - } + } + """, SyntaxKind.CloseBraceToken); [WpfFact] - public async Task Block1() - { - var code = @"using System; -class Class -{ - public int Method() - { }$$"; - - var expected = @"using System; -class Class -{ - public int Method() - { }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task Block1() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + public int Method() + { }$$ + """, """ + using System; + class Class + { + public int Method() + { } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task Block2() - { - var code = @"using System; -class Class -{ - public int Method() { }$$"; - - var expected = @"using System; -class Class -{ - public int Method() { }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task Block2() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + public int Method() { }$$ + """, """ + using System; + class Class + { + public int Method() { } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task Block3() - { - var code = @"using System; -class Class -{ - public int Method() { -}$$ -}"; + public Task Block3() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + public int Method() { + }$$ + } + """, """ + using System; + class Class + { + public int Method() + { + } + } + """, SyntaxKind.OpenBraceToken); - var expected = @"using System; -class Class -{ - public int Method() - { - } -}"; + [WpfFact] + public Task Block4() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + public static Class operator +(Class c1, Class c2) { + }$$ + } + """, """ + using System; + class Class + { + public static Class operator +(Class c1, Class c2) + { + } + } + """, SyntaxKind.OpenBraceToken); - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + [WpfFact] + public Task Block5() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + void Method() + { + { }$$ + """, """ + using System; + class Class + { + void Method() + { + { } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task Block4() - { - var code = @"using System; -class Class -{ - public static Class operator +(Class c1, Class c2) { + public Task Block6() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + void Method() + { + { }$$ -}"; - - var expected = @"using System; -class Class -{ - public static Class operator +(Class c1, Class c2) - { - } -}"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + """, """ + using System; + class Class + { + void Method() + { + { + } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task Block5() - { - var code = @"using System; -class Class -{ - void Method() - { - { }$$"; - - var expected = @"using System; -class Class -{ - void Method() - { - { }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task Block7() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + void Method() + { + { { }$$ + """, """ + using System; + class Class + { + void Method() + { + { { } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task Block6() - { - var code = @"using System; -class Class -{ - void Method() - { - { -}$$"; - - var expected = @"using System; -class Class -{ - void Method() - { - { - }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task Block8() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + void Method() + { + { { + }$$ + } + """, """ + using System; + class Class + { + void Method() + { + { + { + } + } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task Block7() - { - var code = @"using System; -class Class -{ - void Method() - { - { { }$$"; - - var expected = @"using System; -class Class -{ - void Method() - { - { { }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } - - [WpfFact] - public async Task Block8() - { - var code = @"using System; -class Class -{ - void Method() - { - { { -}$$ - }"; - - var expected = @"using System; -class Class -{ - void Method() - { - { + public Task SwitchStatement1() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class { + void Method() + { + switch (a) { + case 1: + break; + }$$ + } } - }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } - - [WpfFact] - public async Task SwitchStatement1() - { - var code = @"using System; -class Class -{ - void Method() - { - switch (a) { - case 1: - break; -}$$ - } -}"; - - var expected = @"using System; -class Class -{ - void Method() - { - switch (a) - { - case 1: - break; - } - } -}"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } - - [WpfFact] - public async Task SwitchStatement2() - { - var code = @"using System; -class Class -{ - void Method() - { - switch (true) { }$$"; - - var expected = @"using System; -class Class -{ - void Method() - { - switch (true) { }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } - - [WpfFact] - public async Task SwitchStatement3() - { - var code = @"using System; -class Class -{ - void Method() - { - switch (true) - { - case 1: { }$$"; - - var expected = @"using System; -class Class -{ - void Method() - { - switch (true) - { - case 1: { }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.ColonToken); - } - - [WpfFact] - public async Task SwitchStatement4() - { - var code = @"using System; -class Class -{ - void Method() - { - switch (true) - { - case 1: { -}$$"; - - var expected = @"using System; -class Class -{ - void Method() - { - switch (true) - { - case 1: + """, """ + using System; + class Class + { + void Method() { - }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.ColonToken); - } - - [WpfFact] - public async Task Initializer1() - { - var code = @"using System; -class Class -{ - void Method() - { - var arr = new int[] { }$$"; - - var expected = @"using System; -class Class -{ - void Method() - { - var arr = new int[] { }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword); - } + switch (a) + { + case 1: + break; + } + } + } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task Initializer2() - { - var code = @"using System; -class Class -{ - void Method() - { - var arr = new int[] { -}$$"; - - var expected = @"using System; -class Class -{ - void Method() - { - var arr = new int[] { -}"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword); - } + public Task SwitchStatement2() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + void Method() + { + switch (true) { }$$ + """, """ + using System; + class Class + { + void Method() + { + switch (true) { } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task Initializer3() - { - var code = @"using System; -class Class -{ - void Method() - { - var arr = new { A = 1, B = 2 -}$$"; - - var expected = @"using System; -class Class -{ - void Method() - { - var arr = new - { - A = 1, - B = 2 - }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword); - } + public Task SwitchStatement3() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + void Method() + { + switch (true) + { + case 1: { }$$ + """, """ + using System; + class Class + { + void Method() + { + switch (true) + { + case 1: { } + """, SyntaxKind.ColonToken); [WpfFact] - public async Task Initializer4() - { - var code = @"using System; -class Class -{ - void Method() - { - var arr = new { A = 1, B = 2 }$$"; - - var expected = @"using System; -class Class -{ - void Method() - { - var arr = new { A = 1, B = 2 }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword); - } + public Task SwitchStatement4() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + void Method() + { + switch (true) + { + case 1: { + }$$ + """, """ + using System; + class Class + { + void Method() + { + switch (true) + { + case 1: + { + } + """, SyntaxKind.ColonToken); [WpfFact] - public async Task Initializer5() - { - var code = @"using System; -class Class -{ - void Method() - { - var arr = new[] { - 1, 2, 3, 4, - 5 }$$"; - - var expected = @"using System; -class Class -{ - void Method() - { - var arr = new[] { - 1, 2, 3, 4, - 5 }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword); - } + public Task Initializer1() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + void Method() + { + var arr = new int[] { }$$ + """, """ + using System; + class Class + { + void Method() + { + var arr = new int[] { } + """, SyntaxKind.NewKeyword); [WpfFact] - public async Task Initializer6() - { - var code = @"using System; -class Class -{ - void Method() - { - var arr = new int[] { - 1, 2, 3, 4, - 5 }$$"; - - var expected = @"using System; -class Class -{ - void Method() - { - var arr = new int[] { - 1, 2, 3, 4, - 5 }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword); - } + public Task Initializer2() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + void Method() + { + var arr = new int[] { + }$$ + """, """ + using System; + class Class + { + void Method() + { + var arr = new int[] { + } + """, SyntaxKind.NewKeyword); [WpfFact] - public async Task EmbeddedStatement1() - { - var code = @"using System; -class Class -{ - void Method() - { - if (true) { }$$"; - - var expected = @"using System; -class Class -{ - void Method() - { - if (true) { }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task Initializer3() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + void Method() + { + var arr = new { A = 1, B = 2 + }$$ + """, """ + using System; + class Class + { + void Method() + { + var arr = new + { + A = 1, + B = 2 + } + """, SyntaxKind.NewKeyword); [WpfFact] - public async Task EmbeddedStatement2() - { - var code = @"using System; -class Class -{ - void Method() - { - if (true) { - }$$ - }"; - - var expected = @"using System; -class Class -{ - void Method() - { - if (true) - { - } - }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task Initializer4() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + void Method() + { + var arr = new { A = 1, B = 2 }$$ + """, """ + using System; + class Class + { + void Method() + { + var arr = new { A = 1, B = 2 } + """, SyntaxKind.NewKeyword); [WpfFact] - public async Task EmbeddedStatement3() - { - var code = @"using System; -class Class -{ - void Method() - { - if (true) - { }$$"; - - var expected = @"using System; -class Class -{ - void Method() - { - if (true) - { }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task Initializer5() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + void Method() + { + var arr = new[] { + 1, 2, 3, 4, + 5 }$$ + """, """ + using System; + class Class + { + void Method() + { + var arr = new[] { + 1, 2, 3, 4, + 5 } + """, SyntaxKind.NewKeyword); [WpfFact] - public async Task EmbeddedStatement4() - { - var code = @"using System; -class Class -{ - void Method() - { - while (true) { -}$$ - }"; - - var expected = @"using System; -class Class -{ - void Method() - { - while (true) - { - } - }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } - - [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/8413")] - public async Task EmbeddedStatementDoBlockAlone() - { - var code = @"using System; -class Class -{ - void Method() - { - do { -}$$ - } -}"; - - var expected = @"using System; -class Class -{ - void Method() - { - do - { - } - } -}"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task Initializer6() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + void Method() + { + var arr = new int[] { + 1, 2, 3, 4, + 5 }$$ + """, """ + using System; + class Class + { + void Method() + { + var arr = new int[] { + 1, 2, 3, 4, + 5 } + """, SyntaxKind.NewKeyword); [WpfFact] - public async Task EmbeddedStatement5() - { - var code = @"using System; -class Class -{ - void Method() - { - do { -} while(true);$$ - } -}"; - - var expected = @"using System; -class Class -{ - void Method() - { - do - { - } while (true); - } -}"; - - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task EmbeddedStatement1() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + void Method() + { + if (true) { }$$ + """, """ + using System; + class Class + { + void Method() + { + if (true) { } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task EmbeddedStatement6() - { - var code = @"using System; -class Class -{ - void Method() - { - for (int i = 0; i < 10; i++) { -}$$ - }"; - - var expected = @"using System; -class Class -{ - void Method() - { - for (int i = 0; i < 10; i++) - { - } - }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task EmbeddedStatement2() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + void Method() + { + if (true) { + }$$ + } + """, """ + using System; + class Class + { + void Method() + { + if (true) + { + } + } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task EmbeddedStatement7() - { - var code = @"using System; -class Class -{ - void Method() - { - foreach (var i in collection) { -}$$ - }"; - - var expected = @"using System; -class Class -{ - void Method() - { - foreach (var i in collection) - { - } - }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task EmbeddedStatement3() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + void Method() + { + if (true) + { }$$ + """, """ + using System; + class Class + { + void Method() + { + if (true) + { } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task EmbeddedStatement8() - { - var code = @"using System; -class Class -{ - void Method() - { - using (var resource = GetResource()) { -}$$ - }"; - - var expected = @"using System; -class Class -{ - void Method() - { - using (var resource = GetResource()) - { - } - }"; + public Task EmbeddedStatement4() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + void Method() + { + while (true) { + }$$ + } + """, """ + using System; + class Class + { + void Method() + { + while (true) + { + } + } + """, SyntaxKind.OpenBraceToken); - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/8413")] + public Task EmbeddedStatementDoBlockAlone() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + void Method() + { + do { + }$$ + } + } + """, """ + using System; + class Class + { + void Method() + { + do + { + } + } + } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task EmbeddedStatement9() - { - var code = @"using System; -class Class -{ - void Method() - { - if (true) - int i = 10;$$"; - - var expected = @"using System; -class Class -{ - void Method() - { - if (true) - int i = 10;"; - - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task EmbeddedStatement5() + => AutoFormatOnSemicolonAsync(""" + using System; + class Class + { + void Method() + { + do { + } while(true);$$ + } + } + """, """ + using System; + class Class + { + void Method() + { + do + { + } while (true); + } + } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task FieldlInitializer() - { - var code = @"using System; -class Class -{ - string str = Console.Title;$$ -"; - - var expected = @"using System; -class Class -{ - string str = Console.Title; -"; - - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task EmbeddedStatement6() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + void Method() + { + for (int i = 0; i < 10; i++) { + }$$ + } + """, """ + using System; + class Class + { + void Method() + { + for (int i = 0; i < 10; i++) + { + } + } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task ArrayFieldlInitializer() - { - var code = @"using System; -namespace NS -{ - class Class - { - string[] strArr = { ""1"", ""2"" };$$ -"; - - var expected = @"using System; -namespace NS -{ - class Class - { - string[] strArr = { ""1"", ""2"" }; -"; - - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task EmbeddedStatement7() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + void Method() + { + foreach (var i in collection) { + }$$ + } + """, """ + using System; + class Class + { + void Method() + { + foreach (var i in collection) + { + } + } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task ExpressionValuedPropertyInitializer() - { - var code = @"using System; -class Class -{ - public int Three => 1+2;$$ -"; - - var expected = @"using System; -class Class -{ - public int Three => 1 + 2; -"; - - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task EmbeddedStatement8() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class + { + void Method() + { + using (var resource = GetResource()) { + }$$ + } + """, """ + using System; + class Class + { + void Method() + { + using (var resource = GetResource()) + { + } + } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task EmbeddedStatement10() - { - var code = @"using System; -class Class -{ - void Method() - { - if (true) - int i = 10;$$ - }"; - - var expected = @"using System; -class Class -{ - void Method() - { - if (true) - int i = 10; - }"; - - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task EmbeddedStatement9() + => AutoFormatOnSemicolonAsync(""" + using System; + class Class + { + void Method() + { + if (true) + int i = 10;$$ + """, """ + using System; + class Class + { + void Method() + { + if (true) + int i = 10; + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task EmbeddedStatement11() - { - var code = @"using System; -class Class -{ - void Method() - { - using (var resource = GetResource()) resource.Do();$$"; + public Task FieldlInitializer() + => AutoFormatOnSemicolonAsync(""" + using System; + class Class + { + string str = Console.Title;$$ - var expected = @"using System; -class Class -{ - void Method() - { - using (var resource = GetResource()) resource.Do();"; + """, """ + using System; + class Class + { + string str = Console.Title; - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); - } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task EmbeddedStatement12() - { - var code = @"using System; -class Class -{ - void Method() - { - using (var resource = GetResource()) - resource.Do();$$"; + public Task ArrayFieldlInitializer() + => AutoFormatOnSemicolonAsync(""" + using System; + namespace NS + { + class Class + { + string[] strArr = { "1", "2" };$$ - var expected = @"using System; -class Class -{ - void Method() - { - using (var resource = GetResource()) - resource.Do();"; + """, """ + using System; + namespace NS + { + class Class + { + string[] strArr = { "1", "2" }; - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); - } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task EmbeddedStatement13() - { - var code = @"using System; -class Class -{ - void Method() - { - using (var resource = GetResource()) - resource.Do();$$ - }"; + public Task ExpressionValuedPropertyInitializer() + => AutoFormatOnSemicolonAsync(""" + using System; + class Class + { + public int Three => 1+2;$$ - var expected = @"using System; -class Class -{ - void Method() - { - using (var resource = GetResource()) - resource.Do(); - }"; + """, """ + using System; + class Class + { + public int Three => 1 + 2; - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); - } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task EmbeddedStatement14() - { - var code = @"using System; -class Class -{ - void Method() - { - do i = 10;$$"; - - var expected = @"using System; -class Class -{ - void Method() - { - do i = 10;"; - - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task EmbeddedStatement10() + => AutoFormatOnSemicolonAsync(""" + using System; + class Class + { + void Method() + { + if (true) + int i = 10;$$ + } + """, """ + using System; + class Class + { + void Method() + { + if (true) + int i = 10; + } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task EmbeddedStatement15() - { - var code = @"using System; -class Class -{ - void Method() - { - do - i = 10;$$"; - - var expected = @"using System; -class Class -{ - void Method() - { - do - i = 10;"; - - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task EmbeddedStatement11() + => AutoFormatOnSemicolonAsync(""" + using System; + class Class + { + void Method() + { + using (var resource = GetResource()) resource.Do();$$ + """, """ + using System; + class Class + { + void Method() + { + using (var resource = GetResource()) resource.Do(); + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task EmbeddedStatement16() - { - var code = @"using System; -class Class -{ - void Method() - { - do - i = 10;$$ - }"; - - var expected = @"using System; -class Class -{ - void Method() - { - do - i = 10; - }"; - - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task EmbeddedStatement12() + => AutoFormatOnSemicolonAsync(""" + using System; + class Class + { + void Method() + { + using (var resource = GetResource()) + resource.Do();$$ + """, """ + using System; + class Class + { + void Method() + { + using (var resource = GetResource()) + resource.Do(); + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task EmbeddedStatement17() - { - var code = @"using System; -class Class -{ - void Method() - { - do - i = 10; -while (true);$$ - }"; - - var expected = @"using System; -class Class -{ - void Method() - { - do - i = 10; - while (true); - }"; - - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task EmbeddedStatement13() + => AutoFormatOnSemicolonAsync(""" + using System; + class Class + { + void Method() + { + using (var resource = GetResource()) + resource.Do();$$ + } + """, """ + using System; + class Class + { + void Method() + { + using (var resource = GetResource()) + resource.Do(); + } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task FollowPreviousElement1() - { - var code = @"using System; -class Class -{ - int i = 10; - int i2 = 10;$$"; - - var expected = @"using System; -class Class -{ - int i = 10; - int i2 = 10;"; - - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken); - } + public Task EmbeddedStatement14() + => AutoFormatOnSemicolonAsync(""" + using System; + class Class + { + void Method() + { + do i = 10;$$ + """, """ + using System; + class Class + { + void Method() + { + do i = 10; + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task FollowPreviousElement2() - { - var code = @"using System; -class Class -{ - void Method(int i) + public Task EmbeddedStatement15() + => AutoFormatOnSemicolonAsync(""" + using System; + class Class { - } - - void Method2() + void Method() + { + do + i = 10;$$ + """, """ + using System; + class Class { - }$$ -}"; + void Method() + { + do + i = 10; + """, SyntaxKind.OpenBraceToken); - var expected = @"using System; -class Class -{ - void Method(int i) + [WpfFact] + public Task EmbeddedStatement16() + => AutoFormatOnSemicolonAsync(""" + using System; + class Class { - } + void Method() + { + do + i = 10;$$ + } + """, """ + using System; + class Class + { + void Method() + { + do + i = 10; + } + """, SyntaxKind.OpenBraceToken); - void Method2() - { - } -}"; + [WpfFact] + public Task EmbeddedStatement17() + => AutoFormatOnSemicolonAsync(""" + using System; + class Class + { + void Method() + { + do + i = 10; + while (true);$$ + } + """, """ + using System; + class Class + { + void Method() + { + do + i = 10; + while (true); + } + """, SyntaxKind.OpenBraceToken); - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.CloseBraceToken); - } + [WpfFact] + public Task FollowPreviousElement1() + => AutoFormatOnSemicolonAsync(""" + using System; + class Class + { + int i = 10; + int i2 = 10;$$ + """, """ + using System; + class Class + { + int i = 10; + int i2 = 10; + """, SyntaxKind.SemicolonToken); [WpfFact] - public async Task FollowPreviousElement3() - { - var code = @"using System; -class Class -{ - void Method(int i) + public Task FollowPreviousElement2() + => AutoFormatOnCloseBraceAsync(""" + using System; + class Class { - } + void Method(int i) + { + } - A a = new A + void Method2() + { + }$$ + } + """, """ + using System; + class Class { - Prop = 1, - Prop2 = 2 - };$$ -}"; + void Method(int i) + { + } - var expected = @"using System; -class Class -{ - void Method(int i) + void Method2() + { + } + } + """, SyntaxKind.CloseBraceToken); + + [WpfFact] + public Task FollowPreviousElement3() + => AutoFormatOnSemicolonAsync(""" + using System; + class Class { + void Method(int i) + { + } + + A a = new A + { + Prop = 1, + Prop2 = 2 + };$$ } + """, """ + using System; + class Class + { + void Method(int i) + { + } - A a = new A - { - Prop = 1, - Prop2 = 2 - }; -}"; - - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.CloseBraceToken); - } + A a = new A + { + Prop = 1, + Prop2 = 2 + }; + } + """, SyntaxKind.CloseBraceToken); [WpfFact] - public async Task FollowPreviousElement4() - { - var code = @"using System; -class Class -{ - void Method(int i) + public Task FollowPreviousElement4() + => AutoFormatOnSemicolonAsync(""" + using System; + class Class { - int i = 10; - int i2 = 10;$$"; - - var expected = @"using System; -class Class -{ - void Method(int i) + void Method(int i) + { + int i = 10; + int i2 = 10;$$ + """, """ + using System; + class Class { - int i = 10; - int i2 = 10;"; - - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken); - } + void Method(int i) + { + int i = 10; + int i2 = 10; + """, SyntaxKind.SemicolonToken); [WpfFact] - public async Task FollowPreviousElement5() - { - var code = @"using System; -class Class -{ - void Method(int i) + public Task FollowPreviousElement5() + => AutoFormatOnSemicolonAsync(""" + using System; + class Class { - int i = 10; - if (true) -i = 50;$$"; - - var expected = @"using System; -class Class -{ - void Method(int i) + void Method(int i) + { + int i = 10; + if (true) + i = 50;$$ + """, """ + using System; + class Class { - int i = 10; - if (true) - i = 50;"; + void Method(int i) + { + int i = 10; + if (true) + i = 50; + """, SyntaxKind.SemicolonToken); - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken); - } + [WpfFact] + public Task FollowPreviousElement6() + => AutoFormatOnSemicolonAsync(""" + using System; + using System.Linq;$$ + """, """ + using System; + using System.Linq; + """, SyntaxKind.SemicolonToken); [WpfFact] - public async Task FollowPreviousElement6() - { - var code = @" using System; - using System.Linq;$$"; + public Task FollowPreviousElement7() + => AutoFormatOnCloseBraceAsync(""" + using System; - var expected = @" using System; -using System.Linq;"; + namespace NS + { + } - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken); - } + namespace NS2 + { + }$$ + """, """ + using System; - [WpfFact] - public async Task FollowPreviousElement7() - { - var code = @" using System; + namespace NS + { + } - namespace NS + namespace NS2 { } + """, SyntaxKind.CloseBraceToken); - namespace NS2 - { - }$$"; - - var expected = @" using System; + [WpfFact] + public Task FollowPreviousElement8() + => AutoFormatOnCloseBraceAsync(""" + using System; namespace NS { + class Class + { + } + + class Class1 + { + }$$ } + """, """ + using System; -namespace NS2 -{ -}"; + namespace NS + { + class Class + { + } - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.CloseBraceToken); - } + class Class1 + { + } + } + """, SyntaxKind.CloseBraceToken); [WpfFact] - public async Task FollowPreviousElement8() - { - var code = @"using System; + public Task IfStatement1() + => AutoFormatOnCloseBraceAsync(""" + using System; -namespace NS -{ class Class { - } - - class Class1 - { - }$$ -}"; - - var expected = @"using System; + void Method() + { + if (true) + { + }$$ + """, """ + using System; -namespace NS -{ class Class { - } - - class Class1 - { - } -}"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.CloseBraceToken); - } - - [WpfFact] - public async Task IfStatement1() - { - var code = @"using System; - -class Class -{ - void Method() - { - if (true) - { - }$$"; - - var expected = @"using System; - -class Class -{ - void Method() - { - if (true) - { - }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + void Method() + { + if (true) + { + } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task IfStatement2() - { - var code = @"using System; - -class Class -{ - void Method() - { - if (true) - { - } -else - { - }$$"; - - var expected = @"using System; + public Task IfStatement2() + => AutoFormatOnCloseBraceAsync(""" + using System; -class Class -{ - void Method() - { - if (true) - { - } - else - { - }"; + class Class + { + void Method() + { + if (true) + { + } + else + { + }$$ + """, """ + using System; - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + class Class + { + void Method() + { + if (true) + { + } + else + { + } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task IfStatement3() - { - var code = @"using System; - -class Class -{ - void Method() - { - if (true) - { - } -else if (false) - { - }$$"; - - var expected = @"using System; + public Task IfStatement3() + => AutoFormatOnCloseBraceAsync(""" + using System; -class Class -{ - void Method() - { - if (true) - { - } - else if (false) - { - }"; + class Class + { + void Method() + { + if (true) + { + } + else if (false) + { + }$$ + """, """ + using System; - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + class Class + { + void Method() + { + if (true) + { + } + else if (false) + { + } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task IfStatement4() - { - var code = @"using System; - -class Class -{ - void Method() - { - if (true) - return ; -else if (false) - return ;$$"; - - var expected = @"using System; + public Task IfStatement4() + => AutoFormatOnSemicolonAsync(""" + using System; -class Class -{ - void Method() - { - if (true) - return; - else if (false) - return;"; + class Class + { + void Method() + { + if (true) + return ; + else if (false) + return ;$$ + """, """ + using System; - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); - } + class Class + { + void Method() + { + if (true) + return; + else if (false) + return; + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task TryStatement1() - { - var code = @"using System; - -class Class -{ - void Method() - { - try - { - }$$"; - - var expected = @"using System; + public Task TryStatement1() + => AutoFormatOnCloseBraceAsync(""" + using System; -class Class -{ - void Method() - { - try - { - }"; + class Class + { + void Method() + { + try + { + }$$ + """, """ + using System; - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + class Class + { + void Method() + { + try + { + } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task TryStatement2() - { - var code = @"using System; + public Task TryStatement2() + => AutoFormatOnCloseBraceAsync(""" + using System; -class Class -{ - void Method() - { - try - { - } -catch ( Exception ex) + class Class + { + void Method() { - }$$"; - - var expected = @"using System; - -class Class -{ - void Method() - { - try - { - } - catch (Exception ex) - { - }"; + try + { + } + catch ( Exception ex) + { + }$$ + """, """ + using System; - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + class Class + { + void Method() + { + try + { + } + catch (Exception ex) + { + } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task TryStatement3() - { - var code = @"using System; + public Task TryStatement3() + => AutoFormatOnCloseBraceAsync(""" + using System; -class Class -{ - void Method() - { - try - { - } -catch ( Exception ex) + class Class + { + void Method() { - } - catch (Exception ex2) - { - }$$"; - - var expected = @"using System; - -class Class -{ - void Method() - { - try - { - } - catch (Exception ex) - { - } - catch (Exception ex2) - { - }"; + try + { + } + catch ( Exception ex) + { + } + catch (Exception ex2) + { + }$$ + """, """ + using System; - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + class Class + { + void Method() + { + try + { + } + catch (Exception ex) + { + } + catch (Exception ex2) + { + } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task TryStatement4() - { - var code = @"using System; - -class Class -{ - void Method() - { - try - { - } - finally - { - }$$"; - - var expected = @"using System; - -class Class -{ - void Method() - { - try - { - } - finally - { - }"; - - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } - - [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/6645")] - public async Task TryStatement5() - { - var code = @"using System; - -class Class -{ - void Method() - { - try { - }$$ - } -}"; + public Task TryStatement4() + => AutoFormatOnCloseBraceAsync(""" + using System; - var expected = @"using System; + class Class + { + void Method() + { + try + { + } + finally + { + }$$ + """, """ + using System; -class Class -{ - void Method() - { - try - { - } - } -}"; + class Class + { + void Method() + { + try + { + } + finally + { + } + """, SyntaxKind.OpenBraceToken); - await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); - } + [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/6645")] + public Task TryStatement5() + => AutoFormatOnCloseBraceAsync(""" + using System; - [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537555")] - public async Task SingleLine() - { - var code = @"class C { void M() { C.M( );$$ } }"; + class Class + { + void Method() + { + try { + }$$ + } + } + """, """ + using System; - var expected = @"class C { void M() { C.M(); } }"; + class Class + { + void Method() + { + try + { + } + } + } + """, SyntaxKind.OpenBraceToken); - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); - } + [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537555")] + public Task SingleLine() + => AutoFormatOnSemicolonAsync(@"class C { void M() { C.M( );$$ } }", @"class C { void M() { C.M(); } }", SyntaxKind.OpenBraceToken); [Fact] public async Task StringLiterals() { - var code = @"class C { void M() { C.M(""Test {0}$$"; - var expected = string.Empty; - await AutoFormatOnMarkerAsync(code, expected, SyntaxKind.StringLiteralToken, SyntaxKind.None); + await AutoFormatOnMarkerAsync(@"class C { void M() { C.M(""Test {0}$$", expected, SyntaxKind.StringLiteralToken, SyntaxKind.None); } [Fact] public async Task CharLiterals() { - var code = @"class C { void M() { C.M('}$$"; - var expected = string.Empty; - await AutoFormatOnMarkerAsync(code, expected, SyntaxKind.CharacterLiteralToken, SyntaxKind.None); + await AutoFormatOnMarkerAsync(@"class C { void M() { C.M('}$$", expected, SyntaxKind.CharacterLiteralToken, SyntaxKind.None); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44423")] public async Task CharLiterals1() { - var code = @"';$$"; - var expected = string.Empty; - await AutoFormatOnMarkerAsync(code, expected, SyntaxKind.CharacterLiteralToken, SyntaxKind.None); + await AutoFormatOnMarkerAsync(@"';$$", expected, SyntaxKind.CharacterLiteralToken, SyntaxKind.None); } [Fact] public async Task Comments() { - var code = @"class C { void M() { // { }$$"; - var expected = string.Empty; - await AutoFormatOnMarkerAsync(code, expected, SyntaxKind.OpenBraceToken, SyntaxKind.OpenBraceToken); + await AutoFormatOnMarkerAsync(@"class C { void M() { // { }$$", expected, SyntaxKind.OpenBraceToken, SyntaxKind.OpenBraceToken); } [WpfFact] - public async Task FirstLineInFile() - { - var code = @"using System;$$"; - - await AutoFormatOnSemicolonAsync(code, "using System;", SyntaxKind.UsingKeyword); - } + public Task FirstLineInFile() + => AutoFormatOnSemicolonAsync(@"using System;$$", "using System;", SyntaxKind.UsingKeyword); [WpfFact] - public async Task Label1() - { - var code = @"class C -{ - void Method() - { - L : int i = 20;$$ - } -}"; - var expected = @"class C -{ - void Method() - { - L: int i = 20; - } -}"; - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task Label1() + => AutoFormatOnSemicolonAsync(""" + class C + { + void Method() + { + L : int i = 20;$$ + } + } + """, """ + class C + { + void Method() + { + L: int i = 20; + } + } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task Label2() - { - var code = @"class C -{ - void Method() - { - L : -int i = 20;$$ - } -}"; - var expected = @"class C -{ - void Method() - { - L: - int i = 20; - } -}"; - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task Label2() + => AutoFormatOnSemicolonAsync(""" + class C + { + void Method() + { + L : + int i = 20;$$ + } + } + """, """ + class C + { + void Method() + { + L: + int i = 20; + } + } + """, SyntaxKind.OpenBraceToken); [WpfFact] - public async Task Label3() - { - var code = @"class C -{ - void Method() - { - int base = 10; - L : -int i = 20;$$ - } -}"; - var expected = @"class C -{ - void Method() - { - int base = 10; - L: - int i = 20; - } -}"; - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken); - } + public Task Label3() + => AutoFormatOnSemicolonAsync(""" + class C + { + void Method() + { + int base = 10; + L : + int i = 20;$$ + } + } + """, """ + class C + { + void Method() + { + int base = 10; + L: + int i = 20; + } + } + """, SyntaxKind.SemicolonToken); [WpfFact] - public async Task Label4() - { - var code = @"class C -{ - void Method() - { - int base = 10; - L: - int i = 20; -int nextLine = 30 ;$$ - } -}"; - var expected = @"class C -{ - void Method() - { - int base = 10; - L: - int i = 20; - int nextLine = 30; - } -}"; - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken); - } + public Task Label4() + => AutoFormatOnSemicolonAsync(""" + class C + { + void Method() + { + int base = 10; + L: + int i = 20; + int nextLine = 30 ;$$ + } + } + """, """ + class C + { + void Method() + { + int base = 10; + L: + int i = 20; + int nextLine = 30; + } + } + """, SyntaxKind.SemicolonToken); [WpfFact] - public async Task Label6() - { - var code = @"class C -{ - void Method() - { - L: - int i = 20; -int nextLine = 30 ;$$ - } -}"; - var expected = @"class C -{ - void Method() - { - L: - int i = 20; - int nextLine = 30; - } -}"; - await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); - } + public Task Label6() + => AutoFormatOnSemicolonAsync(""" + class C + { + void Method() + { + L: + int i = 20; + int nextLine = 30 ;$$ + } + } + """, """ + class C + { + void Method() + { + L: + int i = 20; + int nextLine = 30; + } + } + """, SyntaxKind.OpenBraceToken); [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537776")] - public async Task DisappearedTokens() - { - var code = @"class Class1 -{ - int goo() - return 0; - }$$ -}"; - - var expected = @"class Class1 -{ - int goo() - return 0; - } -}"; - await AutoFormatOnCloseBraceAsync( - code, - expected, + public Task DisappearedTokens() + => AutoFormatOnCloseBraceAsync( + """ + class Class1 + { + int goo() + return 0; + }$$ + } + """, + """ + class Class1 + { + int goo() + return 0; + } + } + """, SyntaxKind.ClassKeyword); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537779")] - public async Task DisappearedTokens2() - { - var code = """ + public Task DisappearedTokens2() + => AutoFormatOnSemicolonAsync( + """ class Class1 { void Goo() @@ -2200,9 +2010,8 @@ void Goo() Object o=new Object);$$ } } - """; - - var expected = """ + """, + """ class Class1 { void Goo() @@ -2210,269 +2019,242 @@ void Goo() Object o = new Object); } } - """; - - await AutoFormatOnSemicolonAsync( - code, - expected, + """, SyntaxKind.OpenBraceToken); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537793")] - public async Task Delegate1() - { - var code = @"delegate void MyDelegate(int a,int b);$$"; - - var expected = @"delegate void MyDelegate(int a, int b);"; - - await AutoFormatOnSemicolonAsync( - code, - expected, + public Task Delegate1() + => AutoFormatOnSemicolonAsync( + @"delegate void MyDelegate(int a,int b);$$", + @"delegate void MyDelegate(int a, int b);", SyntaxKind.DelegateKeyword); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537827")] - public async Task DoubleInitializer() - { - var code = @"class C -{ - void Method() - { - int[,] a ={{ 1 , 1 }$$ - } -}"; - - var expected = @"class C -{ - void Method() - { - int[,] a ={{ 1 , 1 } - } -}"; - - await AutoFormatOnCloseBraceAsync( - code, - expected, + public Task DoubleInitializer() + => AutoFormatOnCloseBraceAsync( + """ + class C + { + void Method() + { + int[,] a ={{ 1 , 1 }$$ + } + } + """, + """ + class C + { + void Method() + { + int[,] a ={{ 1 , 1 } + } + } + """, SyntaxKind.OpenBraceToken); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537825")] - public async Task MissingToken1() - { - var code = @"public class Class1 -{ - int a = 1}$$; -}"; - - var expected = @"public class Class1 -{ - int a = 1}; -}"; - - await AutoFormatOnCloseBraceAsync( - code, - expected, + public Task MissingToken1() + => AutoFormatOnCloseBraceAsync( + """ + public class Class1 + { + int a = 1}$$; + } + """, + """ + public class Class1 + { + int a = 1}; + } + """, SyntaxKind.PublicKeyword); - } [WpfFact] - public async Task ArrayInitializer1() - { - var code = @"public class Class1 -{ - var a = new [] - { - 1, 2, 3, 4 - }$$ -}"; - - var expected = @"public class Class1 -{ - var a = new[] - { - 1, 2, 3, 4 - } -}"; - - await AutoFormatOnCloseBraceAsync( - code, - expected, + public Task ArrayInitializer1() + => AutoFormatOnCloseBraceAsync( + """ + public class Class1 + { + var a = new [] + { + 1, 2, 3, 4 + }$$ + } + """, + """ + public class Class1 + { + var a = new[] + { + 1, 2, 3, 4 + } + } + """, SyntaxKind.NewKeyword); - } [WpfFact] - public async Task ArrayInitializer2() - { - var code = @"public class Class1 -{ - var a = new [] - { - 1, 2, 3, 4 - } ;$$ -}"; - - var expected = @"public class Class1 -{ - var a = new[] - { - 1, 2, 3, 4 - }; -}"; - - await AutoFormatOnSemicolonAsync( - code, - expected, + public Task ArrayInitializer2() + => AutoFormatOnSemicolonAsync( + """ + public class Class1 + { + var a = new [] + { + 1, 2, 3, 4 + } ;$$ + } + """, + """ + public class Class1 + { + var a = new[] + { + 1, 2, 3, 4 + }; + } + """, SyntaxKind.OpenBraceToken); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537825")] - public async Task MalformedCode() - { - var code = @"namespace ClassLibrary1 -{ - public class Class1 - { - int a}$$; - } -}"; - - var expected = @"namespace ClassLibrary1 -{ - public class Class1 - { - int a}; - } -}"; - - await AutoFormatOnCloseBraceAsync( - code, - expected, + public Task MalformedCode() + => AutoFormatOnCloseBraceAsync( + """ + namespace ClassLibrary1 + { + public class Class1 + { + int a}$$; + } + } + """, + """ + namespace ClassLibrary1 + { + public class Class1 + { + int a}; + } + } + """, SyntaxKind.OpenBraceToken); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537804")] - public async Task Colon_SwitchLabel() - { - var code = @"namespace ClassLibrary1 -{ - public class Class1 - { - void Test() - { - switch(E.Type) + public Task Colon_SwitchLabel() + => AutoFormatOnColonAsync( + """ + namespace ClassLibrary1 { - case 1 :$$ + public class Class1 + { + void Test() + { + switch(E.Type) + { + case 1 :$$ + } + } + } } - } - } -}"; - - var expected = @"namespace ClassLibrary1 -{ - public class Class1 - { - void Test() - { - switch(E.Type) + """, + """ + namespace ClassLibrary1 { - case 1: + public class Class1 + { + void Test() + { + switch(E.Type) + { + case 1: + } + } + } } - } - } -}"; - - await AutoFormatOnColonAsync( - code, - expected, + """, SyntaxKind.OpenBraceToken); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/584599")] - public async Task Colon_SwitchLabel_Comment() - { - var code = @"namespace ClassLibrary1 -{ - public class Class1 - { - void Test() - { - switch(E.Type) + public Task Colon_SwitchLabel_Comment() + => AutoFormatOnColonAsync( + """ + namespace ClassLibrary1 { - // test - case 1 :$$ + public class Class1 + { + void Test() + { + switch(E.Type) + { + // test + case 1 :$$ + } + } + } } - } - } -}"; - - var expected = @"namespace ClassLibrary1 -{ - public class Class1 - { - void Test() - { - switch(E.Type) + """, + """ + namespace ClassLibrary1 { - // test - case 1: + public class Class1 + { + void Test() + { + switch(E.Type) + { + // test + case 1: + } + } + } } - } - } -}"; - - await AutoFormatOnColonAsync( - code, - expected, + """, SyntaxKind.OpenBraceToken); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/584599")] - public async Task Colon_SwitchLabel_Comment2() - { - var code = @"namespace ClassLibrary1 -{ - public class Class1 - { - void Test() - { - switch(E.Type) + public Task Colon_SwitchLabel_Comment2() + => AutoFormatOnColonAsync( + """ + namespace ClassLibrary1 { - case 2: - // test - case 1 :$$ + public class Class1 + { + void Test() + { + switch(E.Type) + { + case 2: + // test + case 1 :$$ + } + } + } } - } - } -}"; - - var expected = @"namespace ClassLibrary1 -{ - public class Class1 - { - void Test() - { - switch(E.Type) + """, + """ + namespace ClassLibrary1 { - case 2: - // test - case 1: + public class Class1 + { + void Test() + { + switch(E.Type) + { + case 2: + // test + case 1: + } + } + } } - } - } -}"; - - await AutoFormatOnColonAsync( - code, - expected, + """, SyntaxKind.ColonToken); - } [Fact] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537804")] [WorkItem("https://github.com/dotnet/roslyn/issues/13981")] - public async Task Colon_Label() - { - var code = """ + public Task Colon_Label() + => AutoFormatOnColonAsync( + """ namespace ClassLibrary1 { public class Class1 @@ -2483,9 +2265,8 @@ void Test() } } } - """; - - var expected = """ + """, + """ namespace ClassLibrary1 { public class Class1 @@ -2496,280 +2277,245 @@ void Test() } } } - """; - - await AutoFormatOnColonAsync( - code, - expected, + """, SyntaxKind.OpenBraceToken); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538793")] - public async Task Colon_Label2() - { - var code = @"namespace ClassLibrary1 -{ - public class Class1 - { - void Test() - { - label : Console.WriteLine(10) ;$$ - } - } -}"; - - var expected = @"namespace ClassLibrary1 -{ - public class Class1 - { - void Test() - { - label: Console.WriteLine(10); - } - } -}"; - - await AutoFormatOnSemicolonAsync( - code, - expected, + public Task Colon_Label2() + => AutoFormatOnSemicolonAsync( + """ + namespace ClassLibrary1 + { + public class Class1 + { + void Test() + { + label : Console.WriteLine(10) ;$$ + } + } + } + """, + """ + namespace ClassLibrary1 + { + public class Class1 + { + void Test() + { + label: Console.WriteLine(10); + } + } + } + """, SyntaxKind.OpenBraceToken); - } [WpfFact, WorkItem(3186, "DevDiv_Projects/Roslyn")] - public async Task SemicolonInElseIfStatement() - { - var code = @"using System; -using System.Collections.Generic; -using System.Linq; - -class Program -{ - static void Main(string[] args) - { - int a = 0; - if (a == 0) - a = 1; - else if (a == 1) - a=2;$$ - else - a = 3; - - } -}"; - - var expected = @"using System; -using System.Collections.Generic; -using System.Linq; + public Task SemicolonInElseIfStatement() + => AutoFormatOnSemicolonAsync( + """ + using System; + using System.Collections.Generic; + using System.Linq; + + class Program + { + static void Main(string[] args) + { + int a = 0; + if (a == 0) + a = 1; + else if (a == 1) + a=2;$$ + else + a = 3; -class Program -{ - static void Main(string[] args) - { - int a = 0; - if (a == 0) - a = 1; - else if (a == 1) - a = 2; - else - a = 3; + } + } + """, + """ + using System; + using System.Collections.Generic; + using System.Linq; - } -}"; + class Program + { + static void Main(string[] args) + { + int a = 0; + if (a == 0) + a = 1; + else if (a == 1) + a = 2; + else + a = 3; - await AutoFormatOnSemicolonAsync( - code, - expected, + } + } + """, SyntaxKind.SemicolonToken); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538391")] - public async Task SemicolonInElseIfStatement2() - { - var code = @"public class Class1 -{ - void Method() - { - int a = 1; - if (a == 0) - a = 8;$$ + public Task SemicolonInElseIfStatement2() + => AutoFormatOnSemicolonAsync( + """ + public class Class1 + { + void Method() + { + int a = 1; + if (a == 0) + a = 8;$$ + else + a = 10; + } + } + """, + """ + public class Class1 + { + void Method() + { + int a = 1; + if (a == 0) + a = 8; else a = 10; - } -}"; - - var expected = @"public class Class1 -{ - void Method() - { - int a = 1; - if (a == 0) - a = 8; - else - a = 10; - } -}"; - - await AutoFormatOnSemicolonAsync( - code, - expected, + } + } + """, SyntaxKind.SemicolonToken); - } [WpfFact, WorkItem(8385, "DevDiv_Projects/Roslyn")] - public async Task NullCoalescingOperator() - { - var code = @"class C -{ - void M() - { - object o2 = null??null;$$ - } -}"; - - var expected = @"class C -{ - void M() - { - object o2 = null ?? null; - } -}"; - - await AutoFormatOnSemicolonAsync( - code, - expected, + public Task NullCoalescingOperator() + => AutoFormatOnSemicolonAsync( + """ + class C + { + void M() + { + object o2 = null??null;$$ + } + } + """, + """ + class C + { + void M() + { + object o2 = null ?? null; + } + } + """, SyntaxKind.OpenBraceToken); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541517")] - public async Task SwitchDefault() - { - var code = @"using System; -class Program -{ - static void Main() - { - switch (DayOfWeek.Monday) - { - case DayOfWeek.Monday: - case DayOfWeek.Tuesday: - break; - case DayOfWeek.Wednesday: - break; - default:$$ - } - } -}"; - - var expected = @"using System; -class Program -{ - static void Main() - { - switch (DayOfWeek.Monday) - { - case DayOfWeek.Monday: - case DayOfWeek.Tuesday: - break; - case DayOfWeek.Wednesday: - break; - default: - } - } -}"; - - await AutoFormatOnColonAsync( - code, - expected, + public Task SwitchDefault() + => AutoFormatOnColonAsync( + """ + using System; + class Program + { + static void Main() + { + switch (DayOfWeek.Monday) + { + case DayOfWeek.Monday: + case DayOfWeek.Tuesday: + break; + case DayOfWeek.Wednesday: + break; + default:$$ + } + } + } + """, + """ + using System; + class Program + { + static void Main() + { + switch (DayOfWeek.Monday) + { + case DayOfWeek.Monday: + case DayOfWeek.Tuesday: + break; + case DayOfWeek.Wednesday: + break; + default: + } + } + } + """, SyntaxKind.SemicolonToken); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542538")] - public async Task MissingTokens1() - { - var code = @"class Program -{ - static void Main(string[] args) - { - gl::$$ - } -}"; - - var expected = @"class Program -{ - static void Main(string[] args) - { - gl:: - } -}"; - - await AutoFormatOnMarkerAsync( - code, - expected, + public Task MissingTokens1() + => AutoFormatOnMarkerAsync( + """ + class Program + { + static void Main(string[] args) + { + gl::$$ + } + } + """, + """ + class Program + { + static void Main(string[] args) + { + gl:: + } + } + """, SyntaxKind.ColonColonToken, SyntaxKind.OpenBraceToken); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542538")] - public async Task MissingTokens2() - { - var code = @"class C { void M() { M(() => { }$$ } }"; - - var expected = @"class C { void M() { M(() => { } } }"; - - await AutoFormatOnCloseBraceAsync( - code, - expected, + public Task MissingTokens2() + => AutoFormatOnCloseBraceAsync( + @"class C { void M() { M(() => { }$$ } }", + @"class C { void M() { M(() => { } } }", SyntaxKind.EqualsGreaterThanToken); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542953")] - public async Task UsingAlias() - { - var code = @"using Alias=System;$$"; - - var expected = @"using Alias = System;"; - - await AutoFormatOnSemicolonAsync( - code, - expected, + public Task UsingAlias() + => AutoFormatOnSemicolonAsync( + @"using Alias=System;$$", + @"using Alias = System;", SyntaxKind.UsingKeyword); - } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542953")] - public async Task NoLineChangeWithSyntaxError() - { - var code = @"struct Goo { public int member; } -class Program{ - void Main() - { - var f = new Goo { member;$$ } - } -}"; - - var expected = @"struct Goo { public int member; } -class Program{ - void Main() - { - var f = new Goo { member; } - } -}"; - - await AutoFormatOnSemicolonAsync( - code, - expected, + public Task NoLineChangeWithSyntaxError() + => AutoFormatOnSemicolonAsync( + """ + struct Goo { public int member; } + class Program{ + void Main() + { + var f = new Goo { member;$$ } + } + } + """, + """ + struct Goo { public int member; } + class Program{ + void Main() + { + var f = new Goo { member; } + } + } + """, SyntaxKind.None); - } [WpfTheory] [CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/620568")] public void SkippedTokens1(bool useTabs) { - var code = @";$$*"; - - var expected = @";*"; - - AutoFormatToken(code, expected, useTabs); + AutoFormatToken(@";$$*", @";*", useTabs); } [WpfTheory] @@ -2777,17 +2523,17 @@ public void SkippedTokens1(bool useTabs) [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530830")] public void AutoPropertyAccessor(bool useTabs) { - var code = @"class C -{ - int Prop { get ;$$ -}"; - - var expected = @"class C -{ - int Prop { get; -}"; - - AutoFormatToken(code, expected, useTabs); + AutoFormatToken(""" + class C + { + int Prop { get ;$$ + } + """, """ + class C + { + int Prop { get; + } + """, useTabs); } [WpfTheory] @@ -2795,17 +2541,17 @@ public void AutoPropertyAccessor(bool useTabs) [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530830")] public void AutoPropertyAccessor2(bool useTabs) { - var code = @"class C -{ - int Prop { get; set ;$$ -}"; - - var expected = @"class C -{ - int Prop { get; set; -}"; - - AutoFormatToken(code, expected, useTabs); + AutoFormatToken(""" + class C + { + int Prop { get; set ;$$ + } + """, """ + class C + { + int Prop { get; set; + } + """, useTabs); } [WpfTheory] @@ -2813,17 +2559,17 @@ public void AutoPropertyAccessor2(bool useTabs) [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530830")] public void AutoPropertyAccessor3(bool useTabs) { - var code = @"class C -{ - int Prop { get; set ; }$$ -}"; - - var expected = @"class C -{ - int Prop { get; set; } -}"; - - AutoFormatToken(code, expected, useTabs); + AutoFormatToken(""" + class C + { + int Prop { get; set ; }$$ + } + """, """ + class C + { + int Prop { get; set; } + } + """, useTabs); } [WpfTheory] @@ -2831,17 +2577,17 @@ public void AutoPropertyAccessor3(bool useTabs) [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/784674")] public void AutoPropertyAccessor4(bool useTabs) { - var code = @"class C -{ - int Prop { get;$$ } -}"; - - var expected = @"class C -{ - int Prop { get; } -}"; - - AutoFormatToken(code, expected, useTabs); + AutoFormatToken(""" + class C + { + int Prop { get;$$ } + } + """, """ + class C + { + int Prop { get; } + } + """, useTabs); } [WpfTheory] @@ -2849,16 +2595,17 @@ public void AutoPropertyAccessor4(bool useTabs) [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924469")] public void AutoPropertyAccessor5(bool useTabs) { - var code = @"class C -{ - int Prop { get; set ;$$ } -}"; - - var expected = @"class C -{ - int Prop { get; set; } -}"; - AutoFormatToken(code, expected, useTabs); + AutoFormatToken(""" + class C + { + int Prop { get; set ;$$ } + } + """, """ + class C + { + int Prop { get; set; } + } + """, useTabs); } [WpfTheory] @@ -2866,17 +2613,17 @@ public void AutoPropertyAccessor5(bool useTabs) [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924469")] public void AutoPropertyAccessor6(bool useTabs) { - var code = @"class C -{ - int Prop { get;set;$$} -}"; - - var expected = @"class C -{ - int Prop { get; set; } -}"; - - AutoFormatToken(code, expected, useTabs); + AutoFormatToken(""" + class C + { + int Prop { get;set;$$} + } + """, """ + class C + { + int Prop { get; set; } + } + """, useTabs); } [WpfTheory] @@ -2884,17 +2631,17 @@ public void AutoPropertyAccessor6(bool useTabs) [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924469")] public void AutoPropertyAccessor7(bool useTabs) { - var code = @"class C -{ - int Prop { get;set;$$} -}"; - - var expected = @"class C -{ - int Prop { get; set; } -}"; - - AutoFormatToken(code, expected, useTabs); + AutoFormatToken(""" + class C + { + int Prop { get;set;$$} + } + """, """ + class C + { + int Prop { get; set; } + } + """, useTabs); } [WpfTheory] @@ -2902,25 +2649,25 @@ public void AutoPropertyAccessor7(bool useTabs) [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")] public void NestedUsingStatement(bool useTabs) { - var code = @"class C -{ - public void M() - { - using (null) - using(null)$$ - } -}"; - - var expected = @"class C -{ - public void M() - { - using (null) - using (null) - } -}"; - - AutoFormatToken(code, expected, useTabs); + AutoFormatToken(""" + class C + { + public void M() + { + using (null) + using(null)$$ + } + } + """, """ + class C + { + public void M() + { + using (null) + using (null) + } + } + """, useTabs); } [WpfTheory] @@ -2928,224 +2675,224 @@ public void M() [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")] public void NestedNotUsingStatement(bool useTabs) { - var code = @"class C -{ - public void M() - { - using (null) - for(;;)$$ - } -}"; - - var expected = @"class C -{ - public void M() - { - using (null) - for(;;) - } -}"; - - AutoFormatToken(code, expected, useTabs); + AutoFormatToken(""" + class C + { + public void M() + { + using (null) + for(;;)$$ + } + } + """, """ + class C + { + public void M() + { + using (null) + for(;;) + } + } + """, useTabs); } [WpfTheory] [CombinatorialData] public void UsingStatementWithNestedFixedStatement(bool useTabs) { - var code = @"class C -{ - public void M() - { - using (null) - fixed (void* ptr = &i) - { - }$$ - } -}"; - - var expected = @"class C -{ - public void M() - { - using (null) - fixed (void* ptr = &i) + AutoFormatToken(""" + class C { + public void M() + { + using (null) + fixed (void* ptr = &i) + { + }$$ + } } - } -}"; - - AutoFormatToken(code, expected, useTabs); + """, """ + class C + { + public void M() + { + using (null) + fixed (void* ptr = &i) + { + } + } + } + """, useTabs); } [WpfTheory] [CombinatorialData] public void UsingStatementWithNestedCheckedStatement(bool useTabs) { - var code = @"class C -{ - public void M() - { - using (null) - checked - { - }$$ - } -}"; - - var expected = @"class C -{ - public void M() - { - using (null) - checked + AutoFormatToken(""" + class C { + public void M() + { + using (null) + checked + { + }$$ + } } - } -}"; - - AutoFormatToken(code, expected, useTabs); + """, """ + class C + { + public void M() + { + using (null) + checked + { + } + } + } + """, useTabs); } [WpfTheory] [CombinatorialData] public void UsingStatementWithNestedUncheckedStatement(bool useTabs) { - var code = @"class C -{ - public void M() - { - using (null) - unchecked - { - }$$ - } -}"; - - var expected = @"class C -{ - public void M() - { - using (null) - unchecked + AutoFormatToken(""" + class C { + public void M() + { + using (null) + unchecked + { + }$$ + } } - } -}"; - - AutoFormatToken(code, expected, useTabs); + """, """ + class C + { + public void M() + { + using (null) + unchecked + { + } + } + } + """, useTabs); } [WpfTheory] [CombinatorialData] public void FixedStatementWithNestedUsingStatement(bool useTabs) { - var code = @"class C -{ - public void M() - { - fixed (void* ptr = &i) - using (null)$$ - } -}"; - - var expected = @"class C -{ - public void M() - { - fixed (void* ptr = &i) - using (null) - } -}"; - - AutoFormatToken(code, expected, useTabs); + AutoFormatToken(""" + class C + { + public void M() + { + fixed (void* ptr = &i) + using (null)$$ + } + } + """, """ + class C + { + public void M() + { + fixed (void* ptr = &i) + using (null) + } + } + """, useTabs); } [WpfTheory] [CombinatorialData] public void FixedStatementWithNestedFixedStatement(bool useTabs) { - var code = @"class C -{ - public void M() - { - fixed (void* ptr1 = &i) - fixed (void* ptr2 = &i) + AutoFormatToken(""" + class C { - }$$ - } -}"; - - var expected = @"class C -{ - public void M() - { - fixed (void* ptr1 = &i) - fixed (void* ptr2 = &i) - { - } - } -}"; - - AutoFormatToken(code, expected, useTabs); + public void M() + { + fixed (void* ptr1 = &i) + fixed (void* ptr2 = &i) + { + }$$ + } + } + """, """ + class C + { + public void M() + { + fixed (void* ptr1 = &i) + fixed (void* ptr2 = &i) + { + } + } + } + """, useTabs); } [WpfTheory] [CombinatorialData] public void FixedStatementWithNestedNotFixedStatement(bool useTabs) { - var code = @"class C -{ - public void M() - { - fixed (void* ptr = &i) - if (false) - { - }$$ - } -}"; - - var expected = @"class C -{ - public void M() - { - fixed (void* ptr = &i) - if (false) + AutoFormatToken(""" + class C + { + public void M() + { + fixed (void* ptr = &i) + if (false) + { + }$$ + } + } + """, """ + class C { + public void M() + { + fixed (void* ptr = &i) + if (false) + { + } + } } - } -}"; - - AutoFormatToken(code, expected, useTabs); + """, useTabs); } [WpfTheory] [CombinatorialData] public void NotFixedStatementWithNestedFixedStatement(bool useTabs) { - var code = @"class C -{ - public void M() - { - if (false) - fixed (void* ptr = &i) - { - }$$ - } -}"; - - var expected = @"class C -{ - public void M() - { - if (false) - fixed (void* ptr = &i) + AutoFormatToken(""" + class C + { + public void M() + { + if (false) + fixed (void* ptr = &i) + { + }$$ + } + } + """, """ + class C { + public void M() + { + if (false) + fixed (void* ptr = &i) + { + } + } } - } -}"; - - AutoFormatToken(code, expected, useTabs); + """, useTabs); } [WpfTheory] @@ -3153,22 +2900,22 @@ public void M() [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954386")] public void FormattingRangeForFirstStatementOfBlock(bool useTabs) { - var code = @"class C -{ - public void M() - {int s;$$ - } -}"; - - var expected = @"class C -{ - public void M() - { - int s; - } -}"; - - AutoFormatToken(code, expected, useTabs); + AutoFormatToken(""" + class C + { + public void M() + {int s;$$ + } + } + """, """ + class C + { + public void M() + { + int s; + } + } + """, useTabs); } [WpfTheory] @@ -3176,22 +2923,22 @@ public void M() [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954386")] public void FormattingRangeForFirstMemberofType(bool useTabs) { - var code = @"class C -{int s;$$ - public void M() - { - } -}"; - - var expected = @"class C -{ - int s; - public void M() - { - } -}"; - - AutoFormatToken(code, expected, useTabs); + AutoFormatToken(""" + class C + {int s;$$ + public void M() + { + } + } + """, """ + class C + { + int s; + public void M() + { + } + } + """, useTabs); } [WpfTheory] @@ -3199,16 +2946,16 @@ public void M() [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954386")] public void FormattingRangeForFirstMethodMemberofType(bool useTabs) { - var code = @"interface C -{void s();$$ -}"; - - var expected = @"interface C -{ - void s(); -}"; - - AutoFormatToken(code, expected, useTabs); + AutoFormatToken(""" + interface C + {void s();$$ + } + """, """ + interface C + { + void s(); + } + """, useTabs); } [WpfTheory] @@ -3216,16 +2963,16 @@ public void FormattingRangeForFirstMethodMemberofType(bool useTabs) [WorkItem("https://github.com/dotnet/roslyn/issues/17257")] public void FormattingRangeForConstructor(bool useTabs) { - var code = @"class C -{public C()=>f=1;$$ -}"; - - var expected = @"class C -{ - public C() => f = 1; -}"; - - AutoFormatToken(code, expected, useTabs); + AutoFormatToken(""" + class C + {public C()=>f=1;$$ + } + """, """ + class C + { + public C() => f = 1; + } + """, useTabs); } [WpfTheory] @@ -3233,16 +2980,16 @@ public void FormattingRangeForConstructor(bool useTabs) [WorkItem("https://github.com/dotnet/roslyn/issues/17257")] public void FormattingRangeForDestructor(bool useTabs) { - var code = @"class C -{~C()=>f=1;$$ -}"; - - var expected = @"class C -{ - ~C() => f = 1; -}"; - - AutoFormatToken(code, expected, useTabs); + AutoFormatToken(""" + class C + {~C()=>f=1;$$ + } + """, """ + class C + { + ~C() => f = 1; + } + """, useTabs); } [WpfTheory] @@ -3250,18 +2997,18 @@ public void FormattingRangeForDestructor(bool useTabs) [WorkItem("https://github.com/dotnet/roslyn/issues/17257")] public void FormattingRangeForOperator(bool useTabs) { - var code = @"class C -{public static C operator +(C left, C right)=>field=1;$$ - static int field; -}"; - - var expected = @"class C -{ - public static C operator +(C left, C right) => field = 1; - static int field; -}"; - - AutoFormatToken(code, expected, useTabs); + AutoFormatToken(""" + class C + {public static C operator +(C left, C right)=>field=1;$$ + static int field; + } + """, """ + class C + { + public static C operator +(C left, C right) => field = 1; + static int field; + } + """, useTabs); } [WpfTheory] @@ -3269,16 +3016,16 @@ public void FormattingRangeForOperator(bool useTabs) [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954386")] public void FormattingRangeForFirstMemberOfNamespace(bool useTabs) { - var code = @"namespace C -{delegate void s();$$ -}"; - - var expected = @"namespace C -{ - delegate void s(); -}"; - - AutoFormatToken(code, expected, useTabs); + AutoFormatToken(""" + namespace C + {delegate void s();$$ + } + """, """ + namespace C + { + delegate void s(); + } + """, useTabs); } [WpfTheory] @@ -3286,27 +3033,27 @@ public void FormattingRangeForFirstMemberOfNamespace(bool useTabs) [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981821")] public void FormatDirectiveTriviaAlwaysToColumnZero(bool useTabs) { - var code = @"class Program -{ - static void Main(string[] args) - { -#if - #$$ - } -} -"; + AutoFormatToken(""" + class Program + { + static void Main(string[] args) + { + #if + #$$ + } + } - var expected = @"class Program -{ - static void Main(string[] args) - { -#if -# - } -} -"; + """, """ + class Program + { + static void Main(string[] args) + { + #if + # + } + } - AutoFormatToken(code, expected, useTabs); + """, useTabs); } [WpfTheory] @@ -3314,29 +3061,29 @@ static void Main(string[] args) [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981821")] public void FormatDirectiveTriviaAlwaysToColumnZeroWithCode(bool useTabs) { - var code = @"class Program -{ - static void Main(string[] args) - { -#if - int s = 10; - #$$ - } -} -"; + AutoFormatToken(""" + class Program + { + static void Main(string[] args) + { + #if + int s = 10; + #$$ + } + } - var expected = @"class Program -{ - static void Main(string[] args) - { -#if - int s = 10; -# - } -} -"; + """, """ + class Program + { + static void Main(string[] args) + { + #if + int s = 10; + # + } + } - AutoFormatToken(code, expected, useTabs); + """, useTabs); } [WpfTheory] @@ -3344,27 +3091,27 @@ static void Main(string[] args) [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981821")] public void FormatDirectiveTriviaAlwaysToColumnZeroWithBrokenElseDirective(bool useTabs) { - var code = @"class Program -{ - static void Main(string[] args) - { -#else - #$$ - } -} -"; + AutoFormatToken(""" + class Program + { + static void Main(string[] args) + { + #else + #$$ + } + } - var expected = @"class Program -{ - static void Main(string[] args) - { -#else -# - } -} -"; + """, """ + class Program + { + static void Main(string[] args) + { + #else + # + } + } - AutoFormatToken(code, expected, useTabs); + """, useTabs); } internal static void AutoFormatToken(string markup, string expected, bool useTabs) diff --git a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatTokenTests.cs b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatTokenTests.cs index 26197a759ad12..1ef4c124ca412 100644 --- a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatTokenTests.cs +++ b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatTokenTests.cs @@ -22,438 +22,386 @@ public SmartTokenFormatterFormatTokenTests(ITestOutputHelper output) : base(outp } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44423")] - public async Task EmptyFile1() - { - var code = @"{"; - - await AssertSmartTokenFormatterOpenBraceAsync( - code, + public Task EmptyFile1() + => AssertSmartTokenFormatterOpenBraceAsync( + @"{", indentationLine: 0, expectedSpace: 0); - } [Fact] - public async Task EmptyFile2() - { - var code = @"}"; - - await ExpectException_SmartTokenFormatterCloseBraceAsync( - code, + public Task EmptyFile2() + => ExpectException_SmartTokenFormatterCloseBraceAsync( + @"}", indentationLine: 0); - } [Fact] - public async Task Namespace1() - { - var code = @"namespace NS -{"; - - await AssertSmartTokenFormatterOpenBraceAsync( - code, + public Task Namespace1() + => AssertSmartTokenFormatterOpenBraceAsync( + """ + namespace NS + { + """, indentationLine: 1, expectedSpace: 0); - } [Fact] - public async Task Namespace2() - { - var code = @"namespace NS -}"; - - await AssertSmartTokenFormatterCloseBraceAsync( - code, + public Task Namespace2() + => AssertSmartTokenFormatterCloseBraceAsync( + """ + namespace NS + } + """, indentationLine: 1, expectedSpace: 0); - } [Fact] - public async Task Namespace3() - { - var code = @"namespace NS -{ - }"; - - await AssertSmartTokenFormatterCloseBraceAsync( - code, + public Task Namespace3() + => AssertSmartTokenFormatterCloseBraceAsync( + """ + namespace NS + { + } + """, indentationLine: 2, expectedSpace: 0); - } [Fact] - public async Task Class1() - { - var code = @"namespace NS -{ - class Class - {"; - - await AssertSmartTokenFormatterOpenBraceAsync( - code, + public Task Class1() + => AssertSmartTokenFormatterOpenBraceAsync( + """ + namespace NS + { + class Class + { + """, indentationLine: 3, expectedSpace: 4); - } [Fact] - public async Task Class2() - { - var code = @"namespace NS -{ - class Class - }"; - - await AssertSmartTokenFormatterCloseBraceAsync( - code, + public Task Class2() + => AssertSmartTokenFormatterCloseBraceAsync( + """ + namespace NS + { + class Class + } + """, indentationLine: 3, expectedSpace: 4); - } [Fact] - public async Task Class3() - { - var code = @"namespace NS -{ - class Class - { - }"; - - await AssertSmartTokenFormatterCloseBraceAsync( - code, + public Task Class3() + => AssertSmartTokenFormatterCloseBraceAsync( + """ + namespace NS + { + class Class + { + } + """, indentationLine: 4, expectedSpace: 4); - } [Fact] - public async Task Method1() - { - var code = @"namespace NS -{ - class Class - { - void Method(int i) - {"; - - await AssertSmartTokenFormatterOpenBraceAsync( - code, + public Task Method1() + => AssertSmartTokenFormatterOpenBraceAsync( + """ + namespace NS + { + class Class + { + void Method(int i) + { + """, indentationLine: 5, expectedSpace: 8); - } [Fact] - public async Task Method2() - { - var code = @"namespace NS -{ - class Class - { - void Method(int i) - }"; - - await AssertSmartTokenFormatterCloseBraceAsync( - code, + public Task Method2() + => AssertSmartTokenFormatterCloseBraceAsync( + """ + namespace NS + { + class Class + { + void Method(int i) + } + """, indentationLine: 5, expectedSpace: 8); - } [Fact] - public async Task Method3() - { - var code = @"namespace NS -{ - class Class - { - void Method(int i) - { - }"; - - await AssertSmartTokenFormatterCloseBraceAsync( - code, + public Task Method3() + => AssertSmartTokenFormatterCloseBraceAsync( + """ + namespace NS + { + class Class + { + void Method(int i) + { + } + """, indentationLine: 6, expectedSpace: 8); - } [Fact] - public async Task Property1() - { - var code = @"namespace NS -{ - class Class - { - int Goo - {"; - - await AssertSmartTokenFormatterOpenBraceAsync( - code, + public Task Property1() + => AssertSmartTokenFormatterOpenBraceAsync( + """ + namespace NS + { + class Class + { + int Goo + { + """, indentationLine: 5, expectedSpace: 8); - } [Fact] - public async Task Property2() - { - var code = @"namespace NS -{ - class Class - { - int Goo - { - }"; - - await AssertSmartTokenFormatterCloseBraceAsync( - code, + public Task Property2() + => AssertSmartTokenFormatterCloseBraceAsync( + """ + namespace NS + { + class Class + { + int Goo + { + } + """, indentationLine: 6, expectedSpace: 8); - } [Fact] - public async Task Event1() - { - var code = @"namespace NS -{ - class Class - { - event EventHandler Goo - {"; - - await AssertSmartTokenFormatterOpenBraceAsync( - code, + public Task Event1() + => AssertSmartTokenFormatterOpenBraceAsync( + """ + namespace NS + { + class Class + { + event EventHandler Goo + { + """, indentationLine: 5, expectedSpace: 8); - } [Fact] - public async Task Event2() - { - var code = @"namespace NS -{ - class Class - { - event EventHandler Goo - { - }"; - - await AssertSmartTokenFormatterCloseBraceAsync( - code, + public Task Event2() + => AssertSmartTokenFormatterCloseBraceAsync( + """ + namespace NS + { + class Class + { + event EventHandler Goo + { + } + """, indentationLine: 6, expectedSpace: 8); - } [Fact] - public async Task Indexer1() - { - var code = @"namespace NS -{ - class Class - { - int this[int index] - {"; - - await AssertSmartTokenFormatterOpenBraceAsync( - code, + public Task Indexer1() + => AssertSmartTokenFormatterOpenBraceAsync( + """ + namespace NS + { + class Class + { + int this[int index] + { + """, indentationLine: 5, expectedSpace: 8); - } [Fact] - public async Task Indexer2() - { - var code = @"namespace NS -{ - class Class - { - int this[int index] - { - }"; - - await AssertSmartTokenFormatterCloseBraceAsync( - code, + public Task Indexer2() + => AssertSmartTokenFormatterCloseBraceAsync( + """ + namespace NS + { + class Class + { + int this[int index] + { + } + """, indentationLine: 6, expectedSpace: 8); - } [Fact] - public async Task Block1() - { - var code = @"namespace NS -{ - class Class - { - void Method(int i) - { - {"; - - await AssertSmartTokenFormatterOpenBraceAsync( - code, + public Task Block1() + => AssertSmartTokenFormatterOpenBraceAsync( + """ + namespace NS + { + class Class + { + void Method(int i) + { + { + """, indentationLine: 6, expectedSpace: 12); - } [Fact] - public async Task Block2() - { - var code = @"namespace NS -{ - class Class - { - void Method(int i) - } - }"; - - await AssertSmartTokenFormatterCloseBraceAsync( - code, + public Task Block2() + => AssertSmartTokenFormatterCloseBraceAsync( + """ + namespace NS + { + class Class + { + void Method(int i) + } + } + """, indentationLine: 6, expectedSpace: 0); - } [Fact] - public async Task Block3() - { - var code = @"namespace NS -{ - class Class - { - void Method(int i) - { + public Task Block3() + => AssertSmartTokenFormatterCloseBraceAsync( + """ + namespace NS { - }"; - - await AssertSmartTokenFormatterCloseBraceAsync( - code, + class Class + { + void Method(int i) + { + { + } + """, indentationLine: 7, expectedSpace: 12); - } [Fact] - public async Task Block4() - { - var code = @"namespace NS -{ - class Class - { - void Method(int i) - { + public Task Block4() + => AssertSmartTokenFormatterCloseBraceAsync( + """ + namespace NS + { + class Class { - }"; - - await AssertSmartTokenFormatterCloseBraceAsync( - code, + void Method(int i) + { + { + } + """, indentationLine: 7, expectedSpace: 12); - } [Fact] - public async Task ArrayInitializer1() - { - var code = @"namespace NS -{ - class Class - { - void Method(int i) - { - var a = new [] { - }"; - - var expected = @"namespace NS -{ - class Class - { - void Method(int i) - { - var a = new [] { - }"; - - await AssertSmartTokenFormatterOpenBraceAsync( - expected, - code, + public Task ArrayInitializer1() + => AssertSmartTokenFormatterOpenBraceAsync( + """ + namespace NS + { + class Class + { + void Method(int i) + { + var a = new [] { + } + """, + """ + namespace NS + { + class Class + { + void Method(int i) + { + var a = new [] { + } + """, indentationLine: 6); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537827")] - public async Task ArrayInitializer3() - { - var code = @"namespace NS -{ - class Class - { - void Method(int i) - { - int[,] arr = + public Task ArrayInitializer3() + => AssertSmartTokenFormatterCloseBraceAsync( + """ + namespace NS { - {1,1}, {2,2} -} - }"; - - await AssertSmartTokenFormatterCloseBraceAsync( - code, + class Class + { + void Method(int i) + { + int[,] arr = + { + {1,1}, {2,2} + } + } + """, indentationLine: 9, expectedSpace: 12); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543142")] - public async Task EnterWithTrailingWhitespace() - { - var code = @"class Class -{ - void Method(int i) - { - var a = new { - }; -"; + public Task EnterWithTrailingWhitespace() + => AssertSmartTokenFormatterCloseBraceAsync( + """ + class Class + { + void Method(int i) + { + var a = new { + }; - await AssertSmartTokenFormatterCloseBraceAsync( - code, + """, indentationLine: 5, expectedSpace: 8); - } [Fact, WorkItem(9216, "DevDiv_Projects/Roslyn")] - public async Task OpenBraceWithBaseIndentation() - { - var markup = @" -class C -{ - void M() - { -[|#line ""Default.aspx"", 273 - if (true) -$${ - } -#line default -#line hidden|] - } -}"; - await AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(markup, baseIndentation: 7, expectedIndentation: 11); - } + public Task OpenBraceWithBaseIndentation() + => AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(""" + + class C + { + void M() + { + [|#line "Default.aspx", 273 + if (true) + $${ + } + #line default + #line hidden|] + } + } + """, baseIndentation: 7, expectedIndentation: 11); [Fact, WorkItem(9216, "DevDiv_Projects/Roslyn")] - public async Task CloseBraceWithBaseIndentation() - { - var markup = @" -class C -{ - void M() - { -[|#line ""Default.aspx"", 273 - if (true) - { -$$} -#line default -#line hidden|] - } -}"; - await AssertSmartTokenFormatterCloseBraceWithBaseIndentation(markup, baseIndentation: 7, expectedIndentation: 11); - } + public Task CloseBraceWithBaseIndentation() + => AssertSmartTokenFormatterCloseBraceWithBaseIndentation(""" + + class C + { + void M() + { + [|#line "Default.aspx", 273 + if (true) + { + $$} + #line default + #line hidden|] + } + } + """, baseIndentation: 7, expectedIndentation: 11); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766159")] public async Task TestPreprocessor() { - var code = @" -class C -{ - void M() - { - # - } -}"; + var code = """ + + class C + { + void M() + { + # + } + } + """; var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 5, ch: '#', useTabs: false); Assert.Equal(0, actualIndentation); @@ -465,14 +413,16 @@ void M() [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766159")] public async Task TestRegion() { - var code = @" -class C -{ - void M() - { -#region - } -}"; + var code = """ + + class C + { + void M() + { + #region + } + } + """; var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 5, ch: 'n', useTabs: false); Assert.Equal(8, actualIndentation); @@ -484,15 +434,17 @@ void M() [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766159")] public async Task TestEndRegion() { - var code = @" -class C -{ - void M() - { - #region -#endregion - } -}"; + var code = """ + + class C + { + void M() + { + #region + #endregion + } + } + """; var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 5, ch: 'n', useTabs: false); Assert.Equal(8, actualIndentation); @@ -504,19 +456,21 @@ void M() [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/777467")] public async Task TestSelect() { - var code = @" -using System; -using System.Linq; + var code = """ -class Program -{ - static IEnumerable Goo() - { - return from a in new[] { 1, 2, 3 } - select - } -} -"; + using System; + using System.Linq; + + class Program + { + static IEnumerable Goo() + { + return from a in new[] { 1, 2, 3 } + select + } + } + + """; var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 9, ch: 't', useTabs: false); Assert.Equal(15, actualIndentation); @@ -528,19 +482,21 @@ static IEnumerable Goo() [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/777467")] public async Task TestWhere() { - var code = @" -using System; -using System.Linq; + var code = """ -class Program -{ - static IEnumerable Goo() - { - return from a in new[] { 1, 2, 3 } - where - } -} -"; + using System; + using System.Linq; + + class Program + { + static IEnumerable Goo() + { + return from a in new[] { 1, 2, 3 } + where + } + } + + """; var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 9, ch: 'e', useTabs: false); Assert.Equal(15, actualIndentation); diff --git a/src/EditorFeatures/CSharpTest/Formatting/RazorLineFormattingOptionsTests.cs b/src/EditorFeatures/CSharpTest/Formatting/RazorLineFormattingOptionsTests.cs index ec67412ba2bf8..e158db11d2bc3 100644 --- a/src/EditorFeatures/CSharpTest/Formatting/RazorLineFormattingOptionsTests.cs +++ b/src/EditorFeatures/CSharpTest/Formatting/RazorLineFormattingOptionsTests.cs @@ -45,12 +45,14 @@ public async Task FormatAsync() var project = workspace.AddProject("Test", LanguageNames.CSharp); - var source = @" -class C - { -void F () {} - } -"; + var source = """ + + class C + { + void F () {} + } + + """; var sourceText = SourceText.From(source, encoding: null, SourceHashAlgorithms.Default); var documentInfo = DocumentInfo.Create( @@ -72,11 +74,15 @@ void F () {} var formattedText = await formattedDocument.GetTextAsync(); // document options override solution options: - AssertEx.Equal(@" -class C -{ -" + "\t" + @"void F() { } -} -", formattedText.ToString()); + AssertEx.Equal(""" + + class C + { + + """ + "\t" + """ + void F() { } + } + + """, formattedText.ToString()); } } diff --git a/src/EditorFeatures/CSharpTest/GenerateConstructors/GenerateConstructorsTests.cs b/src/EditorFeatures/CSharpTest/GenerateConstructors/GenerateConstructorsTests.cs index 6e9802b93932c..2d8b07336a2fa 100644 --- a/src/EditorFeatures/CSharpTest/GenerateConstructors/GenerateConstructorsTests.cs +++ b/src/EditorFeatures/CSharpTest/GenerateConstructors/GenerateConstructorsTests.cs @@ -26,9 +26,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(EditorT private readonly NamingStylesTestOptionSets options = new(LanguageNames.CSharp); [Fact] - public async Task TestSingleField() - { - await TestInRegularAndScriptAsync( + public Task TestSingleField() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -50,12 +49,10 @@ public Z(int a{|Navigation:)|} } } """); - } [Fact] - public async Task TestSingleFieldWithCodeStyle() - { - await TestInRegularAndScriptAsync( + public Task TestSingleFieldWithCodeStyle() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -75,12 +72,10 @@ class Z } """, options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); - } [Fact] - public async Task TestUseExpressionBodyWhenOnSingleLine_AndIsSingleLine() - { - await TestInRegularAndScriptAsync( + public Task TestUseExpressionBodyWhenOnSingleLine_AndIsSingleLine() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -100,12 +95,10 @@ class Z } """, options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement)); - } [Fact] - public async Task TestUseExpressionBodyWhenOnSingleLine_AndIsNotSingleLine() - { - await TestInRegularAndScriptAsync( + public Task TestUseExpressionBodyWhenOnSingleLine_AndIsNotSingleLine() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -131,12 +124,10 @@ public Z(int a, int b{|Navigation:)|} } """, options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement)); - } [Fact] - public async Task TestMultipleFields() - { - await TestInRegularAndScriptAsync( + public Task TestMultipleFields() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -161,12 +152,10 @@ public Z(int a, string b{|Navigation:)|} } } """); - } [Fact] - public async Task TestMultipleFields_VerticalSelection() - { - await TestInRegularAndScriptAsync( + public Task TestMultipleFields_VerticalSelection() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -191,12 +180,10 @@ public Z(int a, string b{|Navigation:)|} } } """); - } [Fact] - public async Task TestMultipleFields_VerticalSelectionUpToExcludedField() - { - await TestInRegularAndScriptAsync( + public Task TestMultipleFields_VerticalSelectionUpToExcludedField() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -223,12 +210,10 @@ public Z(string b, string c{|Navigation:)|} } } """); - } [Fact] - public async Task TestMultipleFields_VerticalSelectionUpToMethod() - { - await TestInRegularAndScriptAsync( + public Task TestMultipleFields_VerticalSelectionUpToMethod() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -255,12 +240,10 @@ public Z(int a, string b{|Navigation:)|} } } """); - } [Fact] - public async Task TestMultipleFields_SelectionIncludingClassOpeningBrace() - { - await TestMissingAsync( + public Task TestMultipleFields_SelectionIncludingClassOpeningBrace() + => TestMissingAsync( """ using System.Collections.Generic; @@ -270,12 +253,10 @@ class Z string b;|] } """); - } [Fact] - public async Task TestSecondField() - { - await TestInRegularAndScriptAsync( + public Task TestSecondField() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -309,12 +290,10 @@ public Z(string b{|Navigation:)|} } } """); - } [Fact] - public async Task TestFieldAssigningConstructor() - { - await TestInRegularAndScriptAsync( + public Task TestFieldAssigningConstructor() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -349,12 +328,10 @@ public Z(int a, string b{|Navigation:)|} } } """); - } [Fact] - public async Task TestFieldAssigningConstructor2() - { - await TestInRegularAndScriptAsync( + public Task TestFieldAssigningConstructor2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -389,12 +366,10 @@ public Z(int a, string b{|Navigation:)|} } } """); - } [Fact] - public async Task TestDelegatingConstructor() - { - await TestInRegularAndScriptAsync( + public Task TestDelegatingConstructor() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -428,16 +403,11 @@ public Z(int a, string b{|Navigation:)|} : this(a) } } """, -index: 1); - } + index: 1); [Fact] - public async Task TestDelegatingConstructorWithNullabilityDifferences() - { - // For this test we have a problem: the existing constructor has different nullability than - // the underlying field. We will still offer to use the delegating constructor even though it has a nullability issue - // the user can then easily fix. If they don't want that, they can also just use the first option. - await TestInRegularAndScriptAsync( + public Task TestDelegatingConstructorWithNullabilityDifferences() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -475,13 +445,11 @@ public Z(string? a, int b{|Navigation:)|} : this(a) } } """, -index: 1); - } + index: 1); [Fact] - public async Task TestMissingWithExistingConstructor() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWithExistingConstructor() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -502,12 +470,10 @@ public Z(int a, string b{|Navigation:)|} } } """); - } [Fact] - public async Task TestMultipleProperties() - { - await TestInRegularAndScriptAsync( + public Task TestMultipleProperties() + => TestInRegularAndScriptAsync( """ class Z { @@ -528,12 +494,10 @@ public Z(int a, string b{|Navigation:)|} public string B { get; private set; } } """); - } [Fact] - public async Task TestMultiplePropertiesWithQualification() - { - await TestInRegularAndScriptAsync( + public Task TestMultiplePropertiesWithQualification() + => TestInRegularAndScriptAsync( """ class Z { @@ -554,12 +518,10 @@ public Z(int a, string b{|Navigation:)|} public string B { get; private set; } } """, options: Option(CodeStyleOptions2.QualifyPropertyAccess, true, NotificationOption2.Error)); - } [Fact] - public async Task TestStruct() - { - await TestInRegularAndScriptAsync( + public Task TestStruct() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -581,12 +543,10 @@ public S(int i{|Navigation:)|} } } """); - } [Fact] - public async Task TestStructInitializingAutoProperty() - { - await TestInRegularAndScriptAsync( + public Task TestStructInitializingAutoProperty() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -608,12 +568,10 @@ public S(int i{|Navigation:)|} int i { get; set; } } """); - } [Fact] - public async Task TestStructNotInitializingAutoProperty() - { - await TestInRegularAndScriptAsync( + public Task TestStructNotInitializingAutoProperty() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -637,12 +595,10 @@ public S(int i{|Navigation:)|} : this() int j { get; set; } } """); - } [Fact] - public async Task TestStruct2() - { - await TestInRegularAndScriptAsync( + public Task TestStruct2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -668,12 +624,10 @@ public S(int y{|Navigation:)|} : this() } } """); - } [Fact] - public async Task TestStruct3() - { - await TestInRegularAndScriptAsync( + public Task TestStruct3() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -699,12 +653,10 @@ public S(int i{|Navigation:)|} : this() } } """); - } [Fact] - public async Task TestGenericType() - { - await TestInRegularAndScriptAsync( + public Task TestGenericType() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -726,12 +678,10 @@ public Program(int i{|Navigation:)|} } } """); - } [Fact] - public async Task TestSmartTagText1() - { - await TestSmartTagTextAsync( + public Task TestSmartTagText1() + => TestSmartTagTextAsync( """ using System.Collections.Generic; @@ -741,13 +691,11 @@ class Program HashSet s;|] } """, -string.Format(CodeFixesResources.Generate_constructor_0_1, "Program", "bool b, HashSet s")); - } + string.Format(CodeFixesResources.Generate_constructor_0_1, "Program", "bool b, HashSet s")); [Fact] - public async Task TestSmartTagText2() - { - await TestSmartTagTextAsync( + public Task TestSmartTagText2() + => TestSmartTagTextAsync( """ using System.Collections.Generic; @@ -762,13 +710,11 @@ public Program(bool b) } } """, -string.Format(CodeFixesResources.Generate_field_assigning_constructor_0_1, "Program", "bool b, HashSet s")); - } + string.Format(CodeFixesResources.Generate_field_assigning_constructor_0_1, "Program", "bool b, HashSet s")); [Fact] - public async Task TestSmartTagText3() - { - await TestSmartTagTextAsync( + public Task TestSmartTagText3() + => TestSmartTagTextAsync( """ using System.Collections.Generic; @@ -783,14 +729,12 @@ public Program(bool b) } } """, -string.Format(FeaturesResources.Generate_delegating_constructor_0_1, "Program", "bool b, HashSet s"), -index: 1); - } + string.Format(FeaturesResources.Generate_delegating_constructor_0_1, "Program", "bool b, HashSet s"), + index: 1); [Fact] - public async Task TestContextualKeywordName() - { - await TestInRegularAndScriptAsync( + public Task TestContextualKeywordName() + => TestInRegularAndScriptAsync( """ class Program { @@ -808,12 +752,10 @@ public Program(int yield{|Navigation:)|} } } """); - } [Fact] - public async Task TestGenerateConstructorNotOfferedForDuplicate() - { - await TestMissingInRegularAndScriptAsync( + public Task TestGenerateConstructorNotOfferedForDuplicate() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -829,12 +771,10 @@ static void Test() } } """); - } [Fact] - public async Task Tuple() - { - await TestInRegularAndScriptAsync( + public Task Tuple() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -856,12 +796,10 @@ public Z((int, string) a{|Navigation:)|} } } """); - } [Fact] - public async Task NullableReferenceType() - { - await TestInRegularAndScriptAsync( + public Task NullableReferenceType() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -883,12 +821,10 @@ public Z(string? a{|Navigation:)|} } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14219")] - public async Task TestUnderscoreInName1() - { - await TestInRegularAndScriptAsync( + public Task TestUnderscoreInName1() + => TestInRegularAndScriptAsync( """ class Program { @@ -906,12 +842,10 @@ public Program(int field{|Navigation:)|} } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/62162")] - public async Task TestUnderscoreInName_KeepIfNameWithoutUnderscoreIsInvalid() - { - await TestInRegularAndScriptAsync( + public Task TestUnderscoreInName_KeepIfNameWithoutUnderscoreIsInvalid() + => TestInRegularAndScriptAsync( """ class Program { @@ -929,34 +863,34 @@ public Program(int _0{|Navigation:)|} } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/62162")] [InlineData('m')] [InlineData('s')] [InlineData('t')] - public async Task TestCommonPatternInName_KeepUnderscoreIfNameWithoutItIsInvalid(char commonPatternChar) - { - await TestInRegularAndScriptAsync( -$@"class Program -{{ - [|int {commonPatternChar}_0;|] -}}", -$@"class Program -{{ - int {commonPatternChar}_0; - - public Program(int _0{{|Navigation:)|}} - {{ - {commonPatternChar}_0 = _0; - }} -}}"); - } + public Task TestCommonPatternInName_KeepUnderscoreIfNameWithoutItIsInvalid(char commonPatternChar) + => TestInRegularAndScriptAsync( + $$""" + class Program + { + [|int {{commonPatternChar}}_0;|] + } + """, + $$""" + class Program + { + int {{commonPatternChar}}_0; + + public Program(int _0{|Navigation:)|} + { + {{commonPatternChar}}_0 = _0; + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14219")] - public async Task TestUnderscoreInName_PreferThis() - { - await TestInRegularAndScriptAsync( + public Task TestUnderscoreInName_PreferThis() + => TestInRegularAndScriptAsync( """ class Program { @@ -975,12 +909,10 @@ public Program(int field{|Navigation:)|} } """, options: Option(CodeStyleOptions2.QualifyFieldAccess, CodeStyleOption2.TrueWithSuggestionEnforcement)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/13944")] - public async Task TestGetter_Only_Auto_Props() - { - await TestInRegularAndScriptAsync( + public Task TestGetter_Only_Auto_Props() + => TestInRegularAndScriptAsync( """ abstract class Contribution { @@ -1002,12 +934,10 @@ protected Contribution(string title, int number{|Navigation:)|} } """, options: Option(CodeStyleOptions2.QualifyFieldAccess, CodeStyleOption2.TrueWithSuggestionEnforcement)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/13944")] - public async Task TestAbstract_Getter_Only_Auto_Props() - { - await TestMissingInRegularAndScriptAsync( + public Task TestAbstract_Getter_Only_Auto_Props() + => TestMissingInRegularAndScriptAsync( """ abstract class Contribution { @@ -1016,12 +946,10 @@ abstract class Contribution } """, new TestParameters(options: Option(CodeStyleOptions2.QualifyFieldAccess, CodeStyleOption2.TrueWithSuggestionEnforcement))); - } [Fact] - public async Task TestSingleFieldWithDialog() - { - await TestWithPickMembersDialogAsync( + public Task TestSingleFieldWithDialog() + => TestWithPickMembersDialogAsync( """ using System.Collections.Generic; @@ -1045,12 +973,10 @@ public Z(int a{|Navigation:)|} } """, chosenSymbols: ["a"]); - } [Fact] - public async Task TestSingleFieldWithDialog2() - { - await TestWithPickMembersDialogAsync( + public Task TestSingleFieldWithDialog2() + => TestWithPickMembersDialogAsync( """ using System.Collections.Generic; @@ -1073,12 +999,10 @@ public Z(int a{|Navigation:)|} } """, chosenSymbols: ["a"]); - } [Fact] - public async Task TestMissingOnClassAttributes() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnClassAttributes() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1088,12 +1012,10 @@ class Z int a; } """); - } [Fact] - public async Task TestPickNoFieldWithDialog() - { - await TestWithPickMembersDialogAsync( + public Task TestPickNoFieldWithDialog() + => TestWithPickMembersDialogAsync( """ using System.Collections.Generic; @@ -1116,12 +1038,10 @@ public Z({|Navigation:)|} } """, chosenSymbols: []); - } [Fact] - public async Task TestReorderFieldsWithDialog() - { - await TestWithPickMembersDialogAsync( + public Task TestReorderFieldsWithDialog() + => TestWithPickMembersDialogAsync( """ using System.Collections.Generic; @@ -1148,12 +1068,10 @@ public Z(string b, int a{|Navigation:)|} } """, chosenSymbols: ["b", "a"]); - } [Fact] - public async Task TestAddNullChecks1() - { - await TestWithPickMembersDialogAsync( + public Task TestAddNullChecks1() + => TestWithPickMembersDialogAsync( """ using System; using System.Collections.Generic; @@ -1183,12 +1101,10 @@ public Z(int a, string b{|Navigation:)|} """, chosenSymbols: ["a", "b"], optionsCallback: options => options[0].Value = true); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41428")] - public async Task TestAddNullChecksWithNullableReferenceType() - { - await TestWithPickMembersDialogAsync( + public Task TestAddNullChecksWithNullableReferenceType() + => TestWithPickMembersDialogAsync( """ using System; using System.Collections.Generic; @@ -1223,12 +1139,10 @@ public Z(int a, string b, string? c{|Navigation:)|} """, chosenSymbols: ["a", "b", "c"], optionsCallback: options => options[0].Value = true); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41428")] - public async Task TestAddNullChecksWithNullableReferenceTypeForGenerics() - { - await TestWithPickMembersDialogAsync( + public Task TestAddNullChecksWithNullableReferenceTypeForGenerics() + => TestWithPickMembersDialogAsync( """ using System; using System.Collections.Generic; @@ -1263,12 +1177,10 @@ public Z(int a, string b, T? c{|Navigation:)|} """, chosenSymbols: ["a", "b", "c"], optionsCallback: options => options[0].Value = true); - } [Fact] - public async Task TestAddNullChecks2() - { - await TestWithPickMembersDialogAsync( + public Task TestAddNullChecks2() + => TestWithPickMembersDialogAsync( """ using System; using System.Collections.Generic; @@ -1305,12 +1217,10 @@ public Z(int a, string b{|Navigation:)|} optionsCallback: options => options[0].Value = true, parameters: new TestParameters(options: Option(CSharpCodeStyleOptions.PreferThrowExpression, CodeStyleOption2.FalseWithSilentEnforcement))); - } [Fact] - public async Task TestAddNullChecks3() - { - await TestWithPickMembersDialogAsync( + public Task TestAddNullChecks3() + => TestWithPickMembersDialogAsync( """ using System; using System.Collections.Generic; @@ -1342,12 +1252,10 @@ public Z(int a, int? b{|Navigation:)|} optionsCallback: options => options[0].Value = true, parameters: new TestParameters(options: Option(CSharpCodeStyleOptions.PreferThrowExpression, CodeStyleOption2.FalseWithSilentEnforcement))); - } [Fact] - public async Task TestAddNullChecks_CSharp6() - { - await TestWithPickMembersDialogAsync( + public Task TestAddNullChecks_CSharp6() + => TestWithPickMembersDialogAsync( """ using System; using System.Collections.Generic; @@ -1385,12 +1293,10 @@ public Z(int a, string b{|Navigation:)|} parameters: new TestParameters( parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6), options: Option(CSharpCodeStyleOptions.PreferThrowExpression, CodeStyleOption2.FalseWithSilentEnforcement))); - } [Fact] - public async Task TestMissingOnMember1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnMember1() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1401,12 +1307,10 @@ class Z [||]public void M() { } } """); - } [Fact] - public async Task TestMissingOnMember2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnMember2() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1421,12 +1325,10 @@ public void M() public void N() { } } """); - } [Fact] - public async Task TestMissingOnMember3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnMember3() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1442,12 +1344,10 @@ public void M() public void N() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/pull/21067")] - public async Task TestFinalCaretPosition() - { - await TestInRegularAndScriptAsync( + public Task TestFinalCaretPosition() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -1469,12 +1369,10 @@ public Z(int a{|Navigation:)|} } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20595")] - public async Task ProtectedConstructorShouldBeGeneratedForAbstractClass() - { - await TestInRegularAndScriptAsync( + public Task ProtectedConstructorShouldBeGeneratedForAbstractClass() + => TestInRegularAndScriptAsync( """ abstract class C { @@ -1493,12 +1391,10 @@ protected C(int prop{|Navigation:)|} } """, options: Option(CodeStyleOptions2.QualifyFieldAccess, CodeStyleOption2.TrueWithSuggestionEnforcement)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17643")] - public async Task TestWithDialogNoBackingField() - { - await TestWithPickMembersDialogAsync( + public Task TestWithDialogNoBackingField() + => TestWithPickMembersDialogAsync( """ class Program { @@ -1518,12 +1414,10 @@ public Program(int f{|Navigation:)|} } """, chosenSymbols: null); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25690")] - public async Task TestWithDialogNoIndexer() - { - await TestWithPickMembersDialogAsync( + public Task TestWithDialogNoIndexer() + => TestWithPickMembersDialogAsync( """ class Program { @@ -1545,12 +1439,10 @@ public Program(int p{|Navigation:)|} } """, chosenSymbols: null); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] - public async Task TestWithDialogSetterOnlyProperty() - { - await TestWithPickMembersDialogAsync( + public Task TestWithDialogSetterOnlyProperty() + => TestWithPickMembersDialogAsync( """ class Program { @@ -1573,12 +1465,10 @@ public Program(int p, int s{|Navigation:)|} } """, chosenSymbols: null); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33601")] - public async Task TestPartialFieldSelection() - { - await TestInRegularAndScriptAsync( + public Task TestPartialFieldSelection() + => TestInRegularAndScriptAsync( """ class Z { @@ -1596,12 +1486,10 @@ public Z(int a{|Navigation:)|} } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33601")] - public async Task TestPartialFieldSelection2() - { - await TestInRegularAndScriptAsync( + public Task TestPartialFieldSelection2() + => TestInRegularAndScriptAsync( """ class Z { @@ -1619,12 +1507,10 @@ public Z(int abcdefg{|Navigation:)|} } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33601")] - public async Task TestPartialFieldSelection3() - { - await TestInRegularAndScriptAsync( + public Task TestPartialFieldSelection3() + => TestInRegularAndScriptAsync( """ class Z { @@ -1642,12 +1528,10 @@ public Z(int abcdefg{|Navigation:)|} } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33601")] - public async Task TestPartialFieldSelectionBeforeIdentifier() - { - await TestInRegularAndScript1Async( + public Task TestPartialFieldSelectionBeforeIdentifier() + => TestInRegularAndScript1Async( """ class Z { @@ -1665,12 +1549,10 @@ public Z(int a{|Navigation:)|} } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33601")] - public async Task TestPartialFieldSelectionAfterIdentifier() - { - await TestInRegularAndScript1Async( + public Task TestPartialFieldSelectionAfterIdentifier() + => TestInRegularAndScript1Async( """ class Z { @@ -1688,36 +1570,30 @@ public Z(int a{|Navigation:)|} } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33601")] - public async Task TestPartialFieldSelectionIdentifierNotSelected() - { - await TestMissingAsync( + public Task TestPartialFieldSelectionIdentifierNotSelected() + => TestMissingAsync( """ class Z { in[|t|] a; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33601")] - public async Task TestPartialFieldSelectionIdentifierNotSelected2() - { - await TestMissingAsync( + public Task TestPartialFieldSelectionIdentifierNotSelected2() + => TestMissingAsync( """ class Z { int a [|= 3|]; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33601")] - public async Task TestMultiplePartialFieldSelection() - { - await TestInRegularAndScriptAsync( + public Task TestMultiplePartialFieldSelection() + => TestInRegularAndScriptAsync( """ class Z { @@ -1738,12 +1614,10 @@ public Z(int a, int b{|Navigation:)|} } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33601")] - public async Task TestMultiplePartialFieldSelection2() - { - await TestInRegularAndScriptAsync( + public Task TestMultiplePartialFieldSelection2() + => TestInRegularAndScriptAsync( """ class Z { @@ -1763,12 +1637,10 @@ public Z(int a{|Navigation:)|} } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33601")] - public async Task TestMultiplePartialFieldSelection3_1() - { - await TestInRegularAndScriptAsync( + public Task TestMultiplePartialFieldSelection3_1() + => TestInRegularAndScriptAsync( """ class Z { @@ -1786,12 +1658,10 @@ public Z(int a{|Navigation:)|} } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33601")] - public async Task TestMultiplePartialFieldSelection3_2() - { - await TestInRegularAndScriptAsync( + public Task TestMultiplePartialFieldSelection3_2() + => TestInRegularAndScriptAsync( """ class Z { @@ -1810,24 +1680,20 @@ public Z(int a, int b{|Navigation:)|} } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33601")] - public async Task TestMultiplePartialFieldSelection4() - { - await TestMissingAsync( + public Task TestMultiplePartialFieldSelection4() + => TestMissingAsync( """ class Z { int a = [|2|], b = 3; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36741")] - public async Task TestNoFieldNamingStyle() - { - await TestInRegularAndScriptAsync( + public Task TestNoFieldNamingStyle() + => TestInRegularAndScriptAsync( """ class Z { @@ -1845,12 +1711,10 @@ public Z(int p_a{|Navigation:)|} } } """, options: options.ParameterNamesAreCamelCaseWithPUnderscorePrefix); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36741")] - public async Task TestCommonFieldNamingStyle() - { - await TestInRegularAndScriptAsync( + public Task TestCommonFieldNamingStyle() + => TestInRegularAndScriptAsync( """ class Z { @@ -1868,12 +1732,10 @@ public Z(int p_a{|Navigation:)|} } } """, options: options.ParameterNamesAreCamelCaseWithPUnderscorePrefix); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36741")] - public async Task TestSpecifiedNamingStyle() - { - await TestInRegularAndScriptAsync( + public Task TestSpecifiedNamingStyle() + => TestInRegularAndScriptAsync( """ class Z { @@ -1891,12 +1753,10 @@ public Z(int p_a_End{|Navigation:)|} } } """, options: options.MergeStyles(options.FieldNamesAreCamelCaseWithFieldUnderscorePrefix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36741")] - public async Task TestSpecifiedAndCommonFieldNamingStyle() - { - await TestInRegularAndScriptAsync( + public Task TestSpecifiedAndCommonFieldNamingStyle() + => TestInRegularAndScriptAsync( """ class Z { @@ -1914,12 +1774,10 @@ public Z(int p_a_End{|Navigation:)|} } } """, options: options.MergeStyles(options.FieldNamesAreCamelCaseWithFieldUnderscorePrefix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36741")] - public async Task TestSpecifiedAndCommonFieldNamingStyle2() - { - await TestInRegularAndScriptAsync( + public Task TestSpecifiedAndCommonFieldNamingStyle2() + => TestInRegularAndScriptAsync( """ class Z { @@ -1937,24 +1795,20 @@ public Z(int p_a_End{|Navigation:)|} } } """, options: options.MergeStyles(options.FieldNamesAreCamelCaseWithFieldUnderscorePrefix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36741")] - public async Task TestBaseNameEmpty() - { - await TestMissingAsync( + public Task TestBaseNameEmpty() + => TestMissingAsync( """ class Z { int [|field__End|] = 2; } """, new TestParameters(options: options.MergeStyles(options.FieldNamesAreCamelCaseWithFieldUnderscorePrefixAndUnderscoreEndSuffix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefix))); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36741")] - public async Task TestSomeBaseNamesEmpty() - { - await TestInRegularAndScriptAsync( + public Task TestSomeBaseNamesEmpty() + => TestInRegularAndScriptAsync( """ class Z { @@ -1974,12 +1828,10 @@ public Z(int p_a{|Navigation:)|} } } """, options: options.MergeStyles(options.FieldNamesAreCamelCaseWithFieldUnderscorePrefixAndUnderscoreEndSuffix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefix)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45808")] - public async Task TestUnsafeField() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafeField() + => TestInRegularAndScriptAsync( """ class Z { @@ -1997,12 +1849,10 @@ public unsafe Z(int* a{|Navigation:)|} } } """, compilationOptions: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45808")] - public async Task TestUnsafeFieldInUnsafeClass() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafeFieldInUnsafeClass() + => TestInRegularAndScriptAsync( """ unsafe class Z { @@ -2020,12 +1870,10 @@ public Z(int* a{|Navigation:)|} } } """, compilationOptions: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53467")] - public async Task TestMissingWhenTypeNotInCompilation() - { - await TestMissingAsync( + public Task TestMissingWhenTypeNotInCompilation() + => TestMissingAsync( """ @@ -2045,12 +1893,10 @@ await TestMissingAsync( """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29198")] - public async Task TestWithSelectedGetPropertyThatReturnsField1() - { - await TestInRegularAndScriptAsync( + public Task TestWithSelectedGetPropertyThatReturnsField1() + => TestInRegularAndScriptAsync( """ class Program { @@ -2078,12 +1924,10 @@ public int Goo } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29198")] - public async Task TestWithSelectedGetPropertyThatReturnsField2() - { - await TestInRegularAndScriptAsync( + public Task TestWithSelectedGetPropertyThatReturnsField2() + => TestInRegularAndScriptAsync( """ class Program { @@ -2111,12 +1955,10 @@ public int Goo } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29198")] - public async Task TestWithSelectedGetPropertyThatReturnsField3() - { - await TestInRegularAndScriptAsync( + public Task TestWithSelectedGetPropertyThatReturnsField3() + => TestInRegularAndScriptAsync( """ class Program { @@ -2144,12 +1986,10 @@ public int Goo } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29198")] - public async Task TestWithSelectedGetPropertyThatReturnsField4() - { - await TestInRegularAndScriptAsync( + public Task TestWithSelectedGetPropertyThatReturnsField4() + => TestInRegularAndScriptAsync( """ class Program { @@ -2171,12 +2011,10 @@ public Program(int value{|Navigation:)|} public int Goo => this._value; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29198")] - public async Task TestWithSelectedGetPropertyThatReturnsField5() - { - await TestInRegularAndScriptAsync( + public Task TestWithSelectedGetPropertyThatReturnsField5() + => TestInRegularAndScriptAsync( """ class Program { @@ -2204,12 +2042,10 @@ public int Goo } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29198")] - public async Task TestWithSelectedGetPropertyThatReturnsField6() - { - await TestInRegularAndScriptAsync( + public Task TestWithSelectedGetPropertyThatReturnsField6() + => TestInRegularAndScriptAsync( """ class Program { @@ -2239,5 +2075,4 @@ public int Goo } } """); - } } diff --git a/src/EditorFeatures/CSharpTest/GoToAdjacentMember/CSharpGoToAdjacentMemberTests.cs b/src/EditorFeatures/CSharpTest/GoToAdjacentMember/CSharpGoToAdjacentMemberTests.cs index 89c5abbeebf12..55ae362cba694 100644 --- a/src/EditorFeatures/CSharpTest/GoToAdjacentMember/CSharpGoToAdjacentMemberTests.cs +++ b/src/EditorFeatures/CSharpTest/GoToAdjacentMember/CSharpGoToAdjacentMemberTests.cs @@ -22,55 +22,44 @@ public sealed class CSharpGoToAdjacentMemberTests : AbstractGoToAdjacentMemberTe [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] public async Task EmptyFile() { - var code = @"$$"; - Assert.Null(await GetTargetPositionAsync(code, next: true)); + Assert.Null(await GetTargetPositionAsync(@"$$", next: true)); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] public async Task ClassWithNoMembers() { - var code = """ + Assert.Null(await GetTargetPositionAsync(""" class C { $$ } - """; - Assert.Null(await GetTargetPositionAsync(code, next: true)); + """, next: true)); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task BeforeClassWithMember() - { - var code = """ + public Task BeforeClassWithMember() + => AssertNavigatedAsync(""" $$ class C { [||]void M() { } } - """; - - await AssertNavigatedAsync(code, next: true); - } + """, next: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task AfterClassWithMember() - { - var code = """ + public Task AfterClassWithMember() + => AssertNavigatedAsync(""" class C { [||]void M() { } } $$ - """; - - await AssertNavigatedAsync(code, next: true); - } + """, next: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task BetweenClasses() - { - var code = """ + public Task BetweenClasses() + => AssertNavigatedAsync(""" class C1 { void M() { } @@ -82,15 +71,11 @@ class C2 { [||]void M() { } } - """; - - await AssertNavigatedAsync(code, next: true); - } + """, next: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task BetweenClassesPrevious() - { - var code = """ + public Task BetweenClassesPrevious() + => AssertNavigatedAsync(""" class C1 { [||]void M() { } @@ -102,71 +87,51 @@ class C2 { void M() { } } - """; - - await AssertNavigatedAsync(code, next: false); - } + """, next: false); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task FromFirstMemberToSecond() - { - var code = """ + public Task FromFirstMemberToSecond() + => AssertNavigatedAsync(""" class C { $$void M1() { } [||]void M2() { } } - """; - - await AssertNavigatedAsync(code, next: true); - } + """, next: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task FromSecondToFirst() - { - var code = """ + public Task FromSecondToFirst() + => AssertNavigatedAsync(""" class C { [||]void M1() { } $$void M2() { } } - """; - - await AssertNavigatedAsync(code, next: false); - } + """, next: false); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task NextWraps() - { - var code = """ + public Task NextWraps() + => AssertNavigatedAsync(""" class C { [||]void M1() { } $$void M2() { } } - """; - - await AssertNavigatedAsync(code, next: true); - } + """, next: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task PreviousWraps() - { - var code = """ + public Task PreviousWraps() + => AssertNavigatedAsync(""" class C { $$void M1() { } [||]void M2() { } } - """; - - await AssertNavigatedAsync(code, next: false); - } + """, next: false); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task DescendsIntoNestedType() - { - var code = """ + public Task DescendsIntoNestedType() + => AssertNavigatedAsync(""" class C { $$void M1() { } @@ -176,92 +141,70 @@ class N [||]void M2() { } } } - """; - - await AssertNavigatedAsync(code, next: true); - } + """, next: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task StopsAtConstructor() - { - var code = """ + public Task StopsAtConstructor() + => AssertNavigatedAsync(""" class C { $$void M1() { } [||]public C() { } } - """; - await AssertNavigatedAsync(code, next: true); - } + """, next: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task StopsAtDestructor() - { - var code = """ + public Task StopsAtDestructor() + => AssertNavigatedAsync(""" class C { $$void M1() { } [||]~C() { } } - """; - await AssertNavigatedAsync(code, next: true); - } + """, next: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task StopsAtOperator() - { - var code = """ + public Task StopsAtOperator() + => AssertNavigatedAsync(""" class C { $$void M1() { } [||]static C operator+(C left, C right) { throw new System.NotImplementedException(); } } - """; - await AssertNavigatedAsync(code, next: true); - } + """, next: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task StopsAtField() - { - var code = """ + public Task StopsAtField() + => AssertNavigatedAsync(""" class C { $$void M1() { } [||]int F; } - """; - await AssertNavigatedAsync(code, next: true); - } + """, next: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task StopsAtFieldlikeEvent() - { - var code = """ + public Task StopsAtFieldlikeEvent() + => AssertNavigatedAsync(""" class C { $$void M1() { } [||]event System.EventHandler E; } - """; - await AssertNavigatedAsync(code, next: true); - } + """, next: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task StopsAtAutoProperty() - { - var code = """ + public Task StopsAtAutoProperty() + => AssertNavigatedAsync(""" class C { $$void M1() { } [||]int P { get; set ; } } - """; - await AssertNavigatedAsync(code, next: true); - } + """, next: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task StopsAtPropertyWithAccessors() - { - var code = """ + public Task StopsAtPropertyWithAccessors() + => AssertNavigatedAsync(""" class C { $$void M1() { } @@ -272,15 +215,11 @@ class C set { } } } - """; - - await AssertNavigatedAsync(code, next: true); - } + """, next: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task SkipsPropertyAccessors() - { - var code = """ + public Task SkipsPropertyAccessors() + => AssertNavigatedAsync(""" class C { void M1() { } @@ -293,15 +232,11 @@ void M1() { } [||]void M2() { } } - """; - - await AssertNavigatedAsync(code, next: true); - } + """, next: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task FromInsideAccessor() - { - var code = """ + public Task FromInsideAccessor() + => AssertNavigatedAsync(""" class C { void M1() { } @@ -314,15 +249,11 @@ int P [||]void M2() { } } - """; - - await AssertNavigatedAsync(code, next: true); - } + """, next: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task StopsAtIndexerWithAccessors() - { - var code = """ + public Task StopsAtIndexerWithAccessors() + => AssertNavigatedAsync(""" class C { $$void M1() { } @@ -333,15 +264,11 @@ class C set { } } } - """; - - await AssertNavigatedAsync(code, next: true); - } + """, next: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task SkipsIndexerAccessors() - { - var code = """ + public Task SkipsIndexerAccessors() + => AssertNavigatedAsync(""" class C { void M1() { } @@ -354,15 +281,11 @@ void M1() { } [||]void M2() { } } - """; - - await AssertNavigatedAsync(code, next: true); - } + """, next: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task StopsAtEventWithAddRemove() - { - var code = """ + public Task StopsAtEventWithAddRemove() + => AssertNavigatedAsync(""" class C { $$void M1() { } @@ -373,15 +296,11 @@ class C remove { } } } - """; - - await AssertNavigatedAsync(code, next: true); - } + """, next: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task SkipsEventAddRemove() - { - var code = """ + public Task SkipsEventAddRemove() + => AssertNavigatedAsync(""" class C { void M1() { } @@ -394,15 +313,11 @@ void M1() { } [||]void M2() { } } - """; - - await AssertNavigatedAsync(code, next: true); - } + """, next: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task FromInsideMethod() - { - var code = """ + public Task FromInsideMethod() + => AssertNavigatedAsync(""" class C { void M1() @@ -412,15 +327,11 @@ void M1() [||]void M2() { } } - """; - - await AssertNavigatedAsync(code, next: true); - } + """, next: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task NextFromBetweenMethods() - { - var code = """ + public Task NextFromBetweenMethods() + => AssertNavigatedAsync(""" class C { void M1() { } @@ -429,15 +340,11 @@ void M1() { } [||]void M2() { } } - """; - - await AssertNavigatedAsync(code, next: true); - } + """, next: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task PreviousFromBetweenMethods() - { - var code = """ + public Task PreviousFromBetweenMethods() + => AssertNavigatedAsync(""" class C { [||]void M1() { } @@ -446,15 +353,11 @@ class C void M2() { } } - """; - - await AssertNavigatedAsync(code, next: false); - } + """, next: false); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task NextFromBetweenMethodsInTrailingTrivia() - { - var code = """ + public Task NextFromBetweenMethodsInTrailingTrivia() + => AssertNavigatedAsync(""" class C { void M1() @@ -463,15 +366,11 @@ void M1() [||]void M2() { } } - """; - - await AssertNavigatedAsync(code, next: true); - } + """, next: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task PreviousFromBetweenMethodsInTrailingTrivia() - { - var code = """ + public Task PreviousFromBetweenMethodsInTrailingTrivia() + => AssertNavigatedAsync(""" class C { [||]void M1() @@ -480,31 +379,23 @@ class C void M2() { } } - """; - - await AssertNavigatedAsync(code, next: false); - } + """, next: false); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task StopsAtExpressionBodiedMember() - { - var code = """ + public Task StopsAtExpressionBodiedMember() + => AssertNavigatedAsync(""" class C { int M1() => $$42; [||]int M2() => 42; } - """; - - await AssertNavigatedAsync(code, next: true); - } + """, next: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] [WorkItem("https://github.com/dotnet/roslyn/issues/10588")] - public async Task PreviousFromInsideCurrent() - { - var code = """ + public Task PreviousFromInsideCurrent() + => AssertNavigatedAsync(""" class C { [||]void M1() @@ -516,32 +407,21 @@ void M2() { } } - """; - - await AssertNavigatedAsync(code, next: false); - } + """, next: false); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task NextInScript() - { - var code = """ + public Task NextInScript() + => AssertNavigatedAsync(""" $$void M1() { } [||]void M2() { } - """; - - await AssertNavigatedAsync(code, next: true, sourceCodeKind: SourceCodeKind.Script); - } + """, next: true, sourceCodeKind: SourceCodeKind.Script); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4311")] - public async Task PrevInScript() - { - var code = """ + public Task PrevInScript() + => AssertNavigatedAsync(""" [||]void M1() { } $$void M2() { } - """; - - await AssertNavigatedAsync(code, next: false, sourceCodeKind: SourceCodeKind.Script); - } + """, next: false, sourceCodeKind: SourceCodeKind.Script); } diff --git a/src/EditorFeatures/CSharpTest/Intents/AddConstructorParameterIntentTests.cs b/src/EditorFeatures/CSharpTest/Intents/AddConstructorParameterIntentTests.cs index cf6160606f439..18776958a0a06 100644 --- a/src/EditorFeatures/CSharpTest/Intents/AddConstructorParameterIntentTests.cs +++ b/src/EditorFeatures/CSharpTest/Intents/AddConstructorParameterIntentTests.cs @@ -17,8 +17,7 @@ public sealed class AddConstructorParameterIntentTests : IntentTestsBase [Fact] public async Task AddConstructorParameterWithField() { - var initialText = - """ + await VerifyExpectedTextAsync(WellKnownIntents.AddConstructorParameter, """ class C { private readonly int _someInt;{|priorSelection:|} @@ -27,10 +26,7 @@ public C() { } } - """; - - var currentText = - """ + """, """ class C { private readonly int _someInt; @@ -39,9 +35,7 @@ public C(int som) { } } - """; - var expectedText = - """ + """, """ class C { private readonly int _someInt; @@ -51,16 +45,13 @@ public C(int someInt) _someInt = someInt; } } - """; - - await VerifyExpectedTextAsync(WellKnownIntents.AddConstructorParameter, initialText, currentText, expectedText).ConfigureAwait(false); + """).ConfigureAwait(false); } [Fact] public async Task AddConstructorParameterWithProperty() { - var initialText = - """ + await VerifyExpectedTextAsync(WellKnownIntents.AddConstructorParameter, """ class C { public int SomeInt { get; }{|priorSelection:|} @@ -69,9 +60,7 @@ public C() { } } - """; - var currentText = - """ + """, """ class C { public int SomeInt { get; } @@ -80,9 +69,7 @@ public C(int som) { } } - """; - var expectedText = - """ + """, """ class C { public int SomeInt { get; } @@ -92,16 +79,13 @@ public C(int someInt) SomeInt = someInt; } } - """; - - await VerifyExpectedTextAsync(WellKnownIntents.AddConstructorParameter, initialText, currentText, expectedText).ConfigureAwait(false); + """).ConfigureAwait(false); } [Fact] public async Task AddMultipleConstructorParameters() { - var initialText = - """ + await VerifyExpectedTextAsync(WellKnownIntents.AddConstructorParameter, """ class C { {|priorSelection:private readonly int _someInt; @@ -111,9 +95,7 @@ public C() { } } - """; - var currentText = - """ + """, """ class C { {|priorSelection:private readonly int _someInt; @@ -123,9 +105,7 @@ public C(int som) { } } - """; - var expectedText = - """ + """, """ class C { private readonly int _someInt; @@ -137,16 +117,13 @@ public C(int someInt, string someString) _someString = someString; } } - """; - - await VerifyExpectedTextAsync(WellKnownIntents.AddConstructorParameter, initialText, currentText, expectedText).ConfigureAwait(false); + """).ConfigureAwait(false); } [Fact] public async Task AddConstructorParameterOnlyAddsSelected() { - var initialText = - """ + await VerifyExpectedTextAsync(WellKnownIntents.AddConstructorParameter, """ class C { private readonly int _someInt;{|priorSelection:|} @@ -156,9 +133,7 @@ public C() { } } - """; - var currentText = - """ + """, """ class C { private readonly int _someInt;{|priorSelection:|} @@ -168,9 +143,7 @@ public C(int som) { } } - """; - var expectedText = - """ + """, """ class C { private readonly int _someInt; @@ -181,16 +154,13 @@ public C(int someInt) _someInt = someInt; } } - """; - - await VerifyExpectedTextAsync(WellKnownIntents.AddConstructorParameter, initialText, currentText, expectedText).ConfigureAwait(false); + """).ConfigureAwait(false); } [Fact] public async Task AddConstructorParameterUsesCodeStyleOption() { - var initialText = - """ + await VerifyExpectedTextAsync(WellKnownIntents.AddConstructorParameter, """ class C { private readonly int _someInt;{|priorSelection:|} @@ -199,9 +169,7 @@ public C() { } } - """; - var currentText = - """ + """, """ class C { private readonly int _someInt;{|priorSelection:|} @@ -210,9 +178,7 @@ public C(int som) { } } - """; - var expectedText = - """ + """, """ class C { private readonly int _someInt; @@ -222,8 +188,7 @@ public C(int someInt) this._someInt = someInt; } } - """; - await VerifyExpectedTextAsync(WellKnownIntents.AddConstructorParameter, initialText, currentText, expectedText, + """, options: new OptionsCollection(LanguageNames.CSharp) { { CodeStyleOptions2.QualifyFieldAccess, true } @@ -233,8 +198,7 @@ await VerifyExpectedTextAsync(WellKnownIntents.AddConstructorParameter, initialT [Fact] public async Task AddConstructorParameterUsesExistingAccessibility() { - var initialText = - """ + await VerifyExpectedTextAsync(WellKnownIntents.AddConstructorParameter, """ class C { private readonly int _someInt;{|priorSelection:|} @@ -243,9 +207,7 @@ protected C() { } } - """; - var currentText = - """ + """, """ class C { private readonly int _someInt;{|priorSelection:|} @@ -254,9 +216,7 @@ protected C(int som) { } } - """; - var expectedText = - """ + """, """ class C { private readonly int _someInt; @@ -266,8 +226,6 @@ protected C(int someInt) _someInt = someInt; } } - """; - - await VerifyExpectedTextAsync(WellKnownIntents.AddConstructorParameter, initialText, currentText, expectedText).ConfigureAwait(false); + """).ConfigureAwait(false); } } diff --git a/src/EditorFeatures/CSharpTest/Intents/DeleteParameterIntentTests.cs b/src/EditorFeatures/CSharpTest/Intents/DeleteParameterIntentTests.cs deleted file mode 100644 index a75ce38942c48..0000000000000 --- a/src/EditorFeatures/CSharpTest/Intents/DeleteParameterIntentTests.cs +++ /dev/null @@ -1,589 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Threading.Tasks; -using Microsoft.CodeAnalysis.Features.Intents; -using Microsoft.CodeAnalysis.Test.Utilities; -using Xunit; - -namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Intents; - -[UseExportProvider] -public sealed class DeleteParameterIntentTests : IntentTestsBase -{ - [Fact] - public async Task TestDeleteParameterIntentAsync() - { - var initialText = - """ - class C - { - void M() - { - Method({|priorSelection:1|}); - } - - void Method(int value) - { - } - } - """; - var currentText = - """ - class C - { - void M() - { - Method(); - } - - void Method(int value) - { - } - } - """; - var expectedText = - """ - class C - { - void M() - { - Method(); - } - - void Method() - { - } - } - """; - - await VerifyExpectedTextAsync(WellKnownIntents.DeleteParameter, initialText, currentText, expectedText).ConfigureAwait(false); - } - - [Fact] - public async Task TestDeleteParameterOnDefinitionIntentAsync() - { - var initialText = - """ - class C - { - void M() - { - Method(1); - } - - void Method(int {|priorSelection:value|}) - { - } - } - """; - var currentText = - """ - class C - { - void M() - { - Method(); - } - - void Method(int value) - { - } - } - """; - var expectedText = - """ - class C - { - void M() - { - Method(); - } - - void Method() - { - } - } - """; - - await VerifyExpectedTextAsync(WellKnownIntents.DeleteParameter, initialText, currentText, expectedText).ConfigureAwait(false); - } - - [Fact] - public async Task TestDeleteSecondParameterIntentAsync() - { - var initialText = """ - class C - { - void M() - { - Method(1, {|priorSelection:2|}, 3); - } - - void Method(int value1, int value2, int value3) - { - } - } - """; - var currentText = - """ - class C - { - void M() - { - Method(1, 3); - } - - void Method(int value1, int value2, int value3) - { - } - } - """; - var expectedText = - """ - class C - { - void M() - { - Method(1, 3); - } - - void Method(int value1, int value3) - { - } - } - """; - - await VerifyExpectedTextAsync(WellKnownIntents.DeleteParameter, initialText, currentText, expectedText).ConfigureAwait(false); - } - - [Fact] - public async Task TestDeleteLastParameterAsync() - { - var initialText = """ - class C - { - void M() - { - Method(1, 2, {|priorSelection:3|}); - } - - void Method(int value1, int value2, int value3) - { - } - } - """; - var currentText = - """ - class C - { - void M() - { - Method(1, 2); - } - - void Method(int value1, int value2, int value3) - { - } - } - """; - var expectedText = - """ - class C - { - void M() - { - Method(1, 2); - } - - void Method(int value1, int value2) - { - } - } - """; - - await VerifyExpectedTextAsync(WellKnownIntents.DeleteParameter, initialText, currentText, expectedText).ConfigureAwait(false); - } - - [Fact] - public async Task TestDeleteThisParameterAsync() - { - var initialText = """ - public class Foo - { - static void Bar() - { - var f = new Foo(); - f.DoFoo(); - } - } - - public static class FooExtensions - { - public static void DoFoo(this {|priorSelection:Foo|} foo) - { - - } - } - """; - var currentText = - """ - public class Foo - { - static void Bar() - { - var f = new Foo(); - f.DoFoo(); - } - } - - public static class FooExtensions - { - public static void DoFoo() - { - - } - } - """; - - await VerifyIntentMissingAsync(WellKnownIntents.DeleteParameter, initialText, currentText).ConfigureAwait(false); - } - - [Fact] - public async Task TestDeleteParameterInExtensionMethodAsync() - { - var initialText = """ - public class Foo - { - static void Bar() - { - var f = new Foo(); - f.DoFoo({|priorSelection:1|}, 2); - } - } - - public static class FooExtensions - { - public static void DoFoo(this Foo foo, int value1, int value2) - { - - } - } - """; - var currentText = - """ - public class Foo - { - static void Bar() - { - var f = new Foo(); - f.DoFoo(2); - } - } - - public static class FooExtensions - { - public static void DoFoo(this Foo foo, int value1, int value2) - { - - } - } - """; - var expectedText = - """ - public class Foo - { - static void Bar() - { - var f = new Foo(); - f.DoFoo(2); - } - } - - public static class FooExtensions - { - public static void DoFoo(this Foo foo, int value2) - { - - } - } - """; - - await VerifyExpectedTextAsync(WellKnownIntents.DeleteParameter, initialText, currentText, expectedText).ConfigureAwait(false); - } - - [Fact] - public async Task TestDeleteParameterOnDefinitionAsync() - { - var initialText = """ - public class Foo - { - static void Bar() - { - var f = new Foo(); - f.DoFoo(1, 2); - } - } - - public static class FooExtensions - { - public static void DoFoo(this Foo foo, int {|priorSelection:value1|}, int value2) - { - - } - } - """; - var currentText = - """ - public class Foo - { - static void Bar() - { - var f = new Foo(); - f.DoFoo(2); - } - } - - public static class FooExtensions - { - public static void DoFoo(this Foo foo, int value1, int value2) - { - - } - } - """; - var expectedText = - """ - public class Foo - { - static void Bar() - { - var f = new Foo(); - f.DoFoo(2); - } - } - - public static class FooExtensions - { - public static void DoFoo(this Foo foo, int value2) - { - - } - } - """; - - await VerifyExpectedTextAsync(WellKnownIntents.DeleteParameter, initialText, currentText, expectedText).ConfigureAwait(false); - } - - [Fact] - public async Task TestDeleteParamsParameterAsync() - { - var initialText = - """ - class C - { - void M() - { - Method(new C(), {|priorSelection:1|}, 2, 3); - } - - void Method(C c, params int[] values) - { - } - } - """; - var currentText = - """ - class C - { - void M() - { - Method(new C(), 2, 3); - } - - void Method(C c, params int[] values) - { - } - } - """; - var expectedText = - """ - class C - { - void M() - { - Method(new C()); - } - - void Method(C c) - { - } - } - """; - - await VerifyExpectedTextAsync(WellKnownIntents.DeleteParameter, initialText, currentText, expectedText).ConfigureAwait(false); - } - - [Fact] - public async Task TestDeleteParameterBeforeParamsAsync() - { - var initialText = - """ - class C - { - void M() - { - Method(1.0f, 1, 2, 3); - } - - void Method(float {|priorSelection:f|}, params int[] values) - { - } - } - """; - var currentText = - """ - class C - { - void M() - { - Method(1, 2, 3); - } - - void Method(float f, params int[] values) - { - } - } - """; - var expectedText = - """ - class C - { - void M() - { - Method(1, 2, 3); - } - - void Method(params int[] values) - { - } - } - """; - - await VerifyExpectedTextAsync(WellKnownIntents.DeleteParameter, initialText, currentText, expectedText).ConfigureAwait(false); - } - - [Fact] - public async Task TestDeleteParameterOnStaticExtensionInvocationAsync() - { - var initialText = - """ - public static class AExtension - { - public static void Method(this A c, int i) - { - - } - } - - public class A - { - void M() - { - AExtension.Method(new A(), {|priorSelection:1|}); - } - } - """; - var currentText = - """ - public static class AExtension - { - public static void Method(this A c, int i) - { - - } - } - - public class A - { - void M() - { - AExtension.Method(new A()); - } - } - """; - var expectedText = - """ - public static class AExtension - { - public static void Method(this A c) - { - - } - } - - public class A - { - void M() - { - AExtension.Method(new A()); - } - } - """; - - await VerifyExpectedTextAsync(WellKnownIntents.DeleteParameter, initialText, currentText, expectedText).ConfigureAwait(false); - } - - [Fact] - public async Task TestDeleteParameterOnConstructorInvocationAsync() - { - var initialText = - """ - public class A - { - public A(int i, string s) - { - - } - - static A M() - { - return new A(1, {|priorSelection:"hello"|}); - } - } - """; - var currentText = - """ - public class A - { - public A(int i, string s) - { - - } - - static A M() - { - return new A(1); - } - } - """; - var expectedText = - """ - public class A - { - public A(int i) - { - - } - - static A M() - { - return new A(1); - } - } - """; - - await VerifyExpectedTextAsync(WellKnownIntents.DeleteParameter, initialText, currentText, expectedText).ConfigureAwait(false); - } -} diff --git a/src/EditorFeatures/CSharpTest/Intents/GenerateConstructorIntentTests.cs b/src/EditorFeatures/CSharpTest/Intents/GenerateConstructorIntentTests.cs index 745a09589f14f..457f87aebd05f 100644 --- a/src/EditorFeatures/CSharpTest/Intents/GenerateConstructorIntentTests.cs +++ b/src/EditorFeatures/CSharpTest/Intents/GenerateConstructorIntentTests.cs @@ -17,26 +17,21 @@ public sealed class GenerateConstructorIntentTests : IntentTestsBase [Fact] public async Task GenerateConstructorSimpleResult() { - var initialText = - """ + await VerifyExpectedTextAsync(WellKnownIntents.GenerateConstructor, """ class C { private readonly int _someInt; {|priorSelection:|} } - """; - var currentText = - """ + """, """ class C { private readonly int _someInt; public C } - """; - var expectedText = - """ + """, """ class C { private readonly int _someInt; @@ -46,34 +41,27 @@ public C(int someInt) _someInt = someInt; } } - """; - - await VerifyExpectedTextAsync(WellKnownIntents.GenerateConstructor, initialText, currentText, expectedText).ConfigureAwait(false); + """).ConfigureAwait(false); } [Fact] public async Task GenerateConstructorTypedPrivateWithoutIntentData() { - var initialText = - """ + await VerifyExpectedTextAsync(WellKnownIntents.GenerateConstructor, """ class C { private readonly int _someInt; {|priorSelection:|} } - """; - var currentText = - """ + """, """ class C { private readonly int _someInt; private C } - """; - var expectedText = - """ + """, """ class C { private readonly int _someInt; @@ -83,34 +71,31 @@ public C(int someInt) _someInt = someInt; } } - """; - - await VerifyExpectedTextAsync(WellKnownIntents.GenerateConstructor, initialText, currentText, expectedText).ConfigureAwait(false); + """).ConfigureAwait(false); } [Fact] public async Task GenerateConstructorTypedPrivateWithIntentData() { - var initialText = - """ + + // lang=json + var intentData = @"{ ""accessibility"": ""Private""}"; + + await VerifyExpectedTextAsync(WellKnownIntents.GenerateConstructor, """ class C { private readonly int _someInt; {|priorSelection:|} } - """; - var currentText = - """ + """, """ class C { private readonly int _someInt; private C } - """; - var expectedText = - """ + """, """ class C { private readonly int _someInt; @@ -120,37 +105,31 @@ private C(int someInt) _someInt = someInt; } } - """; - - // lang=json - var intentData = @"{ ""accessibility"": ""Private""}"; - - await VerifyExpectedTextAsync(WellKnownIntents.GenerateConstructor, initialText, currentText, expectedText, intentData: intentData).ConfigureAwait(false); + """, intentData: intentData).ConfigureAwait(false); } [Fact] public async Task GenerateConstructorTypedPrivateProtectedWithIntentData() { - var initialText = - """ + + // lang=json + var intentData = @"{ ""accessibility"": ""ProtectedAndInternal""}"; + + await VerifyExpectedTextAsync(WellKnownIntents.GenerateConstructor, """ class C { private readonly int _someInt; {|priorSelection:|} } - """; - var currentText = - """ + """, """ class C { private readonly int _someInt; private protected C } - """; - var expectedText = - """ + """, """ class C { private readonly int _someInt; @@ -160,31 +139,12 @@ private protected C(int someInt) _someInt = someInt; } } - """; - - // lang=json - var intentData = @"{ ""accessibility"": ""ProtectedAndInternal""}"; - - await VerifyExpectedTextAsync(WellKnownIntents.GenerateConstructor, initialText, currentText, expectedText, intentData: intentData).ConfigureAwait(false); + """, intentData: intentData).ConfigureAwait(false); } [Fact] public async Task GenerateConstructorWithFieldsInPartial() { - var initialText = - """ - partial class C - { - {|priorSelection:|} - } - """; - var currentText = - """ - partial class C - { - public C - } - """; var additionalDocuments = new string[] { """ @@ -205,32 +165,37 @@ public C(int someInt) } """; - await VerifyExpectedTextAsync(WellKnownIntents.GenerateConstructor, initialText, currentText, additionalDocuments, [expectedText]).ConfigureAwait(false); + await VerifyExpectedTextAsync(WellKnownIntents.GenerateConstructor, """ + partial class C + { + {|priorSelection:|} + } + """, """ + partial class C + { + public C + } + """, additionalDocuments, [expectedText]).ConfigureAwait(false); } [Fact] public async Task GenerateConstructorWithReferenceType() { - var initialText = - """ + await VerifyExpectedTextAsync(WellKnownIntents.GenerateConstructor, """ class C { private readonly object _someObject; {|priorSelection:|} } - """; - var currentText = - """ + """, """ class C { private readonly object _someObject; public C } - """; - var expectedText = - """ + """, """ class C { private readonly object _someObject; @@ -240,43 +205,34 @@ public C(object someObject) _someObject = someObject; } } - """; - - await VerifyExpectedTextAsync(WellKnownIntents.GenerateConstructor, initialText, currentText, expectedText).ConfigureAwait(false); + """).ConfigureAwait(false); } [Fact] public async Task GenerateConstructorWithExpressionBodyOption() { - var initialText = - """ + await VerifyExpectedTextAsync(WellKnownIntents.GenerateConstructor, """ class C { private readonly int _someInt; {|priorSelection:|} } - """; - var currentText = - """ + """, """ class C { private readonly int _someInt; public C } - """; - var expectedText = - """ + """, """ class C { private readonly int _someInt; public C(int someInt) => _someInt = someInt; } - """; - - await VerifyExpectedTextAsync(WellKnownIntents.GenerateConstructor, initialText, currentText, expectedText, + """, options: new OptionsCollection(LanguageNames.CSharp) { { CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement } diff --git a/src/EditorFeatures/CSharpTest/Intents/RenameIntentTests.cs b/src/EditorFeatures/CSharpTest/Intents/RenameIntentTests.cs deleted file mode 100644 index 5f6aa21a67ee8..0000000000000 --- a/src/EditorFeatures/CSharpTest/Intents/RenameIntentTests.cs +++ /dev/null @@ -1,226 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Threading.Tasks; -using Microsoft.CodeAnalysis.Features.Intents; -using Microsoft.CodeAnalysis.Test.Utilities; -using Xunit; - -namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Intents; - -[UseExportProvider] -public sealed class RenameIntentTests : IntentTestsBase -{ - [Fact] - public async Task TestRenameIntentAsync() - { - var initialText = - """ - class C - { - void M() - { - var thing = 1; - {|priorSelection:thing|}.ToString(); - } - } - """; - var currentText = - """ - class C - { - void M() - { - var thing = 1; - something.ToString(); - } - } - """; - var expectedText = - """ - class C - { - void M() - { - var something = 1; - something.ToString(); - } - } - """; - - await VerifyExpectedRenameAsync(initialText, currentText, expectedText, "something").ConfigureAwait(false); - } - - [Fact] - public async Task TestRenameIntentAsync_Insert() - { - var initialText = - """ - class C - { - void M() - { - var thing = 1; - {|priorSelection:|}thing.ToString(); - } - } - """; - var currentText = - """ - class C - { - void M() - { - var thing = 1; - something.ToString(); - } - } - """; - var expectedText = - """ - class C - { - void M() - { - var something = 1; - something.ToString(); - } - } - """; - - await VerifyExpectedRenameAsync(initialText, currentText, expectedText, "something").ConfigureAwait(false); - } - - [Fact] - public async Task TestRenameIntentAsync_Delete() - { - var initialText = - """ - class C - { - void M() - { - var something = 1; - {|priorSelection:some|}thing.ToString(); - } - } - """; - var currentText = - """ - class C - { - void M() - { - var something = 1; - thing.ToString(); - } - } - """; - var expectedText = - """ - class C - { - void M() - { - var thing = 1; - thing.ToString(); - } - } - """; - - await VerifyExpectedRenameAsync(initialText, currentText, expectedText, "thing").ConfigureAwait(false); - } - - [Fact] - public async Task TestRenameIntentAsync_MultipleFiles() - { - var initialText = - """ - namespace M - { - public class C - { - public static string {|priorSelection:SomeString|} = string.Empty; - - void M() - { - var m = SomeString; - } - } - } - """; - var currentText = - """ - namespace M - { - public class C - { - public static string BetterString = string.Empty; - - void M() - { - var m = SomeString; - } - } - } - """; - var additionalDocuments = new string[] - { - """ - namespace M - { - public class D - { - void M() - { - var m = C.SomeString; - } - } - } - """ - }; - - var expectedTexts = new string[] - { - """ - namespace M - { - public class C - { - public static string BetterString = string.Empty; - - void M() - { - var m = BetterString; - } - } - } - """, - """ - namespace M - { - public class D - { - void M() - { - var m = C.BetterString; - } - } - } - """ - }; - - await VerifyExpectedRenameAsync(initialText, currentText, additionalDocuments, expectedTexts, "BetterString").ConfigureAwait(false); - } - - private static Task VerifyExpectedRenameAsync(string initialText, string currentText, string expectedText, string newName) - { - return VerifyExpectedTextAsync(WellKnownIntents.Rename, initialText, currentText, expectedText, intentData: $"{{ \"newName\": \"{newName}\" }}"); - } - - private static Task VerifyExpectedRenameAsync(string initialText, string currentText, string[] additionalText, string[] expectedTexts, string newName) - { - return VerifyExpectedTextAsync(WellKnownIntents.Rename, initialText, currentText, additionalText, expectedTexts, intentData: $"{{ \"newName\": \"{newName}\" }}"); - } -} diff --git a/src/EditorFeatures/CSharpTest/Interactive/BraceMatching/InteractiveBraceHighlightingTests.cs b/src/EditorFeatures/CSharpTest/Interactive/BraceMatching/InteractiveBraceHighlightingTests.cs index 9b6896fec426b..8d9168cdef180 100644 --- a/src/EditorFeatures/CSharpTest/Interactive/BraceMatching/InteractiveBraceHighlightingTests.cs +++ b/src/EditorFeatures/CSharpTest/Interactive/BraceMatching/InteractiveBraceHighlightingTests.cs @@ -151,18 +151,20 @@ async Task assertNoTags(int position, char expectedChar) [WpfFact] public async Task TestSwitch() { - var code = @" -class C -{ - void M(int variable) - { - switch (variable) - { - case 0: - break; - } - } -} "; + var code = """ + + class C + { + void M(int variable) + { + switch (variable) + { + case 0: + break; + } + } + } + """; using var workspace = EditorTestWorkspace.CreateCSharp(code, parseOptions: TestOptions.Script); var buffer = workspace.Documents.First().GetTextBuffer(); diff --git a/src/EditorFeatures/CSharpTest/Interactive/NavigateTo/InteractiveNavigateToTests.cs b/src/EditorFeatures/CSharpTest/Interactive/NavigateTo/InteractiveNavigateToTests.cs index 435d94cb1d066..b1e058cbcc6f7 100644 --- a/src/EditorFeatures/CSharpTest/Interactive/NavigateTo/InteractiveNavigateToTests.cs +++ b/src/EditorFeatures/CSharpTest/Interactive/NavigateTo/InteractiveNavigateToTests.cs @@ -27,19 +27,16 @@ protected override EditorTestWorkspace CreateWorkspace(string content, TestCompo [WpfTheory] [CombinatorialData] - public async Task NoItemsForEmptyFile(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, "", async w => + public Task NoItemsForEmptyFile(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "", async w => { Assert.Empty(await _aggregator.GetItemsAsync("Hello")); }); - } [WpfTheory] [CombinatorialData] - public async Task FindClass(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, + public Task FindClass(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ class Goo { @@ -49,13 +46,11 @@ class Goo var item = (await _aggregator.GetItemsAsync("Goo")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Goo", "[|Goo|]", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassPrivate); }); - } [WpfTheory] [CombinatorialData] - public async Task FindNestedClass(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, + public Task FindNestedClass(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ class Goo { @@ -71,13 +66,11 @@ internal class DogBed var item = (await _aggregator.GetItemsAsync("DogBed")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "DogBed", "[|DogBed|]", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassInternal); }); - } [WpfTheory] [CombinatorialData] - public async Task FindMemberInANestedClass(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, + public Task FindMemberInANestedClass(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ class Goo { @@ -96,13 +89,11 @@ public void Method() var item = (await _aggregator.GetItemsAsync("Method")).Single(); VerifyNavigateToResultItem(item, "Method", "[|Method|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPublic, string.Format(FeaturesResources.in_0_project_1, "Goo.Bar.DogBed", "Test")); }); - } [WpfTheory] [CombinatorialData] - public async Task FindGenericClassWithConstraints(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, + public Task FindGenericClassWithConstraints(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ using System.Collections; @@ -114,13 +105,11 @@ class Goo where T : IEnumerable var item = (await _aggregator.GetItemsAsync("Goo")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Goo", "[|Goo|]", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassPrivate); }); - } [WpfTheory] [CombinatorialData] - public async Task FindGenericMethodWithConstraints(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, + public Task FindGenericMethodWithConstraints(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ using System; @@ -135,13 +124,11 @@ public void Bar(T item) where T : IComparable var item = (await _aggregator.GetItemsAsync("Bar")).Single(); VerifyNavigateToResultItem(item, "Bar", "[|Bar|](T)", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPublic, string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [WpfTheory] [CombinatorialData] - public async Task FindPartialClass(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, + public Task FindPartialClass(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ public partial class Goo { @@ -161,13 +148,11 @@ partial class Goo VerifyNavigateToResultItems(expecteditems, items); }); - } [WpfTheory] [CombinatorialData] - public async Task FindTypesInMetadata(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, + public Task FindTypesInMetadata(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ using System; @@ -177,13 +162,11 @@ await TestAsync(testHost, composition, var items = await _aggregator.GetItemsAsync("FileStyleUriParser"); Assert.Equal(0, items.Count()); }); - } [WpfTheory] [CombinatorialData] - public async Task FindClassInNamespace(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, + public Task FindClassInNamespace(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ namespace Bar { @@ -196,13 +179,11 @@ class Goo var item = (await _aggregator.GetItemsAsync("Goo")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Goo", "[|Goo|]", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassInternal); }); - } [WpfTheory] [CombinatorialData] - public async Task FindStruct(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, + public Task FindStruct(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ struct Bar { @@ -212,13 +193,11 @@ struct Bar var item = (await _aggregator.GetItemsAsync("B")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Bar", "[|B|]ar", PatternMatchKind.Prefix, NavigateToItemKind.Structure, Glyph.StructurePrivate); }); - } [WpfTheory] [CombinatorialData] - public async Task FindEnum(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, + public Task FindEnum(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ enum Colors { @@ -231,13 +210,11 @@ enum Colors var item = (await _aggregator.GetItemsAsync("Colors")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Colors", "[|Colors|]", PatternMatchKind.Exact, NavigateToItemKind.Enum, Glyph.EnumPrivate); }); - } [WpfTheory] [CombinatorialData] - public async Task FindEnumMember(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, + public Task FindEnumMember(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ enum Colors { @@ -250,13 +227,11 @@ enum Colors var item = (await _aggregator.GetItemsAsync("R")).Single(); VerifyNavigateToResultItem(item, "Red", "[|R|]ed", PatternMatchKind.Prefix, NavigateToItemKind.EnumItem, Glyph.EnumMemberPublic); }); - } [WpfTheory] [CombinatorialData] - public async Task FindConstField(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, + public Task FindConstField(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ class Goo { @@ -267,13 +242,11 @@ class Goo var item = (await _aggregator.GetItemsAsync("ba")).Single(); VerifyNavigateToResultItem(item, "bar", "[|ba|]r", PatternMatchKind.Prefix, NavigateToItemKind.Constant, Glyph.ConstantPrivate); }); - } [WpfTheory] [CombinatorialData] - public async Task FindVerbatimIdentifier(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, + public Task FindVerbatimIdentifier(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ class Goo { @@ -284,37 +257,29 @@ class Goo var item = (await _aggregator.GetItemsAsync("string")).Single(); VerifyNavigateToResultItem(item, "string", "[|string|]", PatternMatchKind.Exact, NavigateToItemKind.Field, Glyph.FieldPrivate, additionalInfo: string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [WpfTheory] [CombinatorialData] - public async Task FindIndexer(TestHost testHost, Composition composition) - { - var program = @"class Goo { int[] arr; public int this[int i] { get { return arr[i]; } set { arr[i] = value; } } }"; - await TestAsync(testHost, composition, program, async w => + public Task FindIndexer(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, @"class Goo { int[] arr; public int this[int i] { get { return arr[i]; } set { arr[i] = value; } } }", async w => { var item = (await _aggregator.GetItemsAsync("this")).Single(); VerifyNavigateToResultItem(item, "this", "[|this|][int]", PatternMatchKind.Exact, NavigateToItemKind.Property, Glyph.PropertyPublic, additionalInfo: string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [WpfTheory] [CombinatorialData] - public async Task FindEvent(TestHost testHost, Composition composition) - { - var program = "class Goo { public event EventHandler ChangedEventHandler; }"; - await TestAsync(testHost, composition, program, async w => + public Task FindEvent(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "class Goo { public event EventHandler ChangedEventHandler; }", async w => { var item = (await _aggregator.GetItemsAsync("CEH")).Single(); VerifyNavigateToResultItem(item, "ChangedEventHandler", "[|C|]hanged[|E|]vent[|H|]andler", PatternMatchKind.CamelCaseExact, NavigateToItemKind.Event, Glyph.EventPublic, additionalInfo: string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [WpfTheory] [CombinatorialData] - public async Task FindAutoProperty(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, + public Task FindAutoProperty(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ class Goo { @@ -325,13 +290,11 @@ class Goo var item = (await _aggregator.GetItemsAsync("B")).Single(); VerifyNavigateToResultItem(item, "Bar", "[|B|]ar", PatternMatchKind.Prefix, NavigateToItemKind.Property, Glyph.PropertyPrivate, additionalInfo: string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [WpfTheory] [CombinatorialData] - public async Task FindMethod(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, + public Task FindMethod(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ class Goo { @@ -342,13 +305,11 @@ class Goo var item = (await _aggregator.GetItemsAsync("DS")).Single(); VerifyNavigateToResultItem(item, "DoSomething", "[|D|]o[|S|]omething()", PatternMatchKind.CamelCaseExact, NavigateToItemKind.Method, Glyph.MethodPrivate, string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [WpfTheory] [CombinatorialData] - public async Task FindParameterizedMethod(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, + public Task FindParameterizedMethod(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ class Goo { @@ -361,13 +322,11 @@ void DoSomething(int a, string b) var item = (await _aggregator.GetItemsAsync("DS")).Single(); VerifyNavigateToResultItem(item, "DoSomething", "[|D|]o[|S|]omething(int, string)", PatternMatchKind.CamelCaseExact, NavigateToItemKind.Method, Glyph.MethodPrivate, string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [WpfTheory] [CombinatorialData] - public async Task FindConstructor(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, + public Task FindConstructor(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ class Goo { @@ -380,13 +339,11 @@ public Goo() var item = (await _aggregator.GetItemsAsync("Goo")).Single(t => t.Kind == NavigateToItemKind.Method); VerifyNavigateToResultItem(item, "Goo", "[|Goo|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPublic, string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [WpfTheory] [CombinatorialData] - public async Task FindParameterizedConstructor(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, + public Task FindParameterizedConstructor(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ class Goo { @@ -399,13 +356,11 @@ public Goo(int i) var item = (await _aggregator.GetItemsAsync("Goo")).Single(t => t.Kind == NavigateToItemKind.Method); VerifyNavigateToResultItem(item, "Goo", "[|Goo|](int)", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPublic, string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [WpfTheory] [CombinatorialData] - public async Task FindStaticConstructor(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, + public Task FindStaticConstructor(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ class Goo { @@ -418,13 +373,11 @@ static Goo() var item = (await _aggregator.GetItemsAsync("Goo")).Single(t => t.Kind == NavigateToItemKind.Method && t.Name != ".ctor"); VerifyNavigateToResultItem(item, "Goo", "[|Goo|].static Goo()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPrivate, string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [WpfTheory] [CombinatorialData] - public async Task FindPartialMethods(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, "partial class Goo { partial void Bar(); } partial class Goo { partial void Bar() { Console.Write(\"hello\"); } }", async w => + public Task FindPartialMethods(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "partial class Goo { partial void Bar(); } partial class Goo { partial void Bar() { Console.Write(\"hello\"); } }", async w => { var expecteditem1 = new NavigateToItem("Bar", NavigateToItemKind.Method, "csharp", null, null, s_emptyExactPatternMatch, null); var expecteditems = new List { expecteditem1, expecteditem1 }; @@ -433,13 +386,11 @@ public async Task FindPartialMethods(TestHost testHost, Composition composition) VerifyNavigateToResultItems(expecteditems, items); }); - } [WpfTheory] [CombinatorialData] - public async Task FindPartialMethodDefinitionOnly(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, + public Task FindPartialMethodDefinitionOnly(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ partial class Goo { @@ -450,14 +401,11 @@ partial class Goo var item = (await _aggregator.GetItemsAsync("Bar")).Single(); VerifyNavigateToResultItem(item, "Bar", "[|Bar|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPrivate, string.Format(FeaturesResources.in_0_1_2, "Goo", "test1.cs", "Test")); }); - } [WpfTheory] [CombinatorialData] - public async Task FindOverriddenMembers(TestHost testHost, Composition composition) - { - var program = "class Goo { public virtual string Name { get; set; } } class DogBed : Goo { public override string Name { get { return base.Name; } set {} } }"; - await TestAsync(testHost, composition, program, async w => + public Task FindOverriddenMembers(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "class Goo { public virtual string Name { get; set; } } class DogBed : Goo { public override string Name { get { return base.Name; } set {} } }", async w => { var expecteditem1 = new NavigateToItem("Name", NavigateToItemKind.Property, "csharp", null, null, s_emptyExactPatternMatch, null); var expecteditems = new List { expecteditem1, expecteditem1 }; @@ -480,13 +428,11 @@ await TestAsync(testHost, composition, program, async w => Assert.Equal("Name", itemDisplay.Name); Assert.Equal(string.Format(FeaturesResources.in_0_project_1, "Goo", "Test"), itemDisplay.AdditionalInformation); }); - } [WpfTheory] [CombinatorialData] - public async Task FindInterface(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, + public Task FindInterface(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ public interface IGoo { @@ -496,13 +442,11 @@ public interface IGoo var item = (await _aggregator.GetItemsAsync("IG")).Single(); VerifyNavigateToResultItem(item, "IGoo", "[|IG|]oo", PatternMatchKind.Prefix, NavigateToItemKind.Interface, Glyph.InterfacePublic); }); - } [WpfTheory] [CombinatorialData] - public async Task FindDelegateInNamespace(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, + public Task FindDelegateInNamespace(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ namespace Goo { @@ -513,13 +457,11 @@ namespace Goo var item = (await _aggregator.GetItemsAsync("DoStuff")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "DoStuff", "[|DoStuff|]", PatternMatchKind.Exact, NavigateToItemKind.Delegate, Glyph.DelegateInternal); }); - } [WpfTheory] [CombinatorialData] - public async Task FindLambdaExpression(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, + public Task FindLambdaExpression(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ using System; @@ -532,13 +474,11 @@ class Goo var item = (await _aggregator.GetItemsAsync("sqr")).Single(); VerifyNavigateToResultItem(item, "sqr", "[|sqr|]", PatternMatchKind.Exact, NavigateToItemKind.Field, Glyph.FieldPrivate, string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [WpfTheory] [CombinatorialData] - public async Task OrderingOfConstructorsAndTypes(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, + public Task OrderingOfConstructorsAndTypes(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ class C1 { @@ -571,14 +511,11 @@ static C2() items.Sort(CompareNavigateToItems); VerifyNavigateToResultItems(expecteditems, items); }); - } [WpfTheory] [CombinatorialData] - public async Task StartStopSanity(TestHost testHost, Composition composition) - { - // Verify that multiple calls to start/stop and dispose don't blow up - await TestAsync(testHost, composition, + public Task StartStopSanity(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ public class Goo { @@ -596,19 +533,16 @@ public class Goo // Dispose the provider _provider.Dispose(); }); - } [WpfTheory] [CombinatorialData] - public async Task DescriptionItems(TestHost testHost, Composition composition) - { - var code = """ + public Task DescriptionItems(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ public class Goo { } - """; - await TestAsync(testHost, composition, code, async w => + """, async w => { var item = (await _aggregator.GetItemsAsync("G")).Single(x => x.Kind != "Method"); var itemDisplay = item.DisplayFactory.CreateItemDisplay(item); @@ -625,14 +559,11 @@ void assertDescription(string label, string value) assertDescription("Line:", "3"); // one based line number assertDescription("Project:", "Test"); }); - } [WpfTheory] [CombinatorialData] - public async Task TermSplittingTest1(TestHost testHost, Composition composition) - { - var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; - await TestAsync(testHost, composition, source, async w => + public Task TermSplittingTest1(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}", async w => { var expecteditem1 = new NavigateToItem("get_keyword", NavigateToItemKind.Field, "csharp", null, null, s_emptyCamelCaseNonContiguousPrefixPatternMatch_NotCaseSensitive, null); var expecteditem2 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, s_emptyCamelCaseNonContiguousPrefixPatternMatch_NotCaseSensitive, null); @@ -645,14 +576,11 @@ await TestAsync(testHost, composition, source, async w => VerifyNavigateToResultItems(expecteditems, items); }); - } [WpfTheory] [CombinatorialData] - public async Task TermSplittingTest2(TestHost testHost, Composition composition) - { - var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; - await TestAsync(testHost, composition, source, async w => + public Task TermSplittingTest2(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}", async w => { var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, s_emptyCamelCaseNonContiguousPrefixPatternMatch_NotCaseSensitive, null); var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, s_emptyCamelCaseExactPatternMatch, null); @@ -662,14 +590,11 @@ await TestAsync(testHost, composition, source, async w => VerifyNavigateToResultItems(expecteditems, items); }); - } [WpfTheory] [CombinatorialData] - public async Task TermSplittingTest3(TestHost testHost, Composition composition) - { - var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; - await TestAsync(testHost, composition, source, async w => + public Task TermSplittingTest3(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}", async w => { var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, s_emptyCamelCaseSubstringPatternMatch_NotCaseSensitive, null); var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, s_emptySubstringPatternMatch, null); @@ -679,39 +604,29 @@ await TestAsync(testHost, composition, source, async w => VerifyNavigateToResultItems(expecteditems, items); }); - } [WpfTheory] [CombinatorialData] - public async Task TermSplittingTest4(TestHost testHost, Composition composition) - { - var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; - await TestAsync(testHost, composition, source, async w => + public Task TermSplittingTest4(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}", async w => { var items = await _aggregator.GetItemsAsync("WKG"); Assert.Empty(items); }); - } [WpfTheory] [CombinatorialData] - public async Task TermSplittingTest5(TestHost testHost, Composition composition) - { - var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; - await TestAsync(testHost, composition, source, async w => + public Task TermSplittingTest5(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}", async w => { var item = (await _aggregator.GetItemsAsync("G_K_W")).Single(); VerifyNavigateToResultItem(item, "get_key_word", "[|g|]et[|_k|]ey[|_w|]ord", PatternMatchKind.CamelCaseExact, NavigateToItemKind.Field, Glyph.FieldPrivate); }); - } [WpfTheory] [CombinatorialData] - public async Task TermSplittingTest7(TestHost testHost, Composition composition) - { - ////Diff from dev10 - var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; - await TestAsync(testHost, composition, source, async w => + public Task TermSplittingTest7(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}", async w => { var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, s_emptyCamelCaseSubstringPatternMatch_NotCaseSensitive, null); var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, s_emptySubstringPatternMatch, null); @@ -721,18 +636,13 @@ await TestAsync(testHost, composition, source, async w => VerifyNavigateToResultItems(expecteditems, items); }); - } [WpfTheory] [CombinatorialData] - public async Task TermSplittingTest8(TestHost testHost, Composition composition) - { - ////Diff from dev10 - var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; - await TestAsync(testHost, composition, source, async w => + public Task TermSplittingTest8(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}", async w => { var items = await _aggregator.GetItemsAsync("GTW"); Assert.Empty(items); }); - } } diff --git a/src/EditorFeatures/CSharpTest/KeywordHighlighting/AsyncAnonymousFunctionHighlighterTests.cs b/src/EditorFeatures/CSharpTest/KeywordHighlighting/AsyncAnonymousFunctionHighlighterTests.cs index 3d49c1169bd11..a398019955c9f 100644 --- a/src/EditorFeatures/CSharpTest/KeywordHighlighting/AsyncAnonymousFunctionHighlighterTests.cs +++ b/src/EditorFeatures/CSharpTest/KeywordHighlighting/AsyncAnonymousFunctionHighlighterTests.cs @@ -19,9 +19,8 @@ internal override Type GetHighlighterType() => typeof(AsyncAwaitHighlighter); [Fact] - public async Task TestSimpleLambda() - { - await TestAsync( + public Task TestSimpleLambda() + => TestAsync( """ using System; using System.Threading.Tasks; @@ -47,12 +46,10 @@ async Task UseAsync() } } """); - } [Fact] - public async Task TestParenthesizedLambda() - { - await TestAsync( + public Task TestParenthesizedLambda() + => TestAsync( """ using System; using System.Threading.Tasks; @@ -78,12 +75,10 @@ async Task UseAsync() } } """); - } [Fact] - public async Task TestAnonymousMethod() - { - await TestAsync( + public Task TestAnonymousMethod() + => TestAsync( """ using System; using System.Threading.Tasks; @@ -109,5 +104,4 @@ async Task UseAsync() } } """); - } } diff --git a/src/EditorFeatures/CSharpTest/KeywordHighlighting/AsyncLocalFunctionHighlighterTests.cs b/src/EditorFeatures/CSharpTest/KeywordHighlighting/AsyncLocalFunctionHighlighterTests.cs index 5916be51e8e41..df22e6fb9f88f 100644 --- a/src/EditorFeatures/CSharpTest/KeywordHighlighting/AsyncLocalFunctionHighlighterTests.cs +++ b/src/EditorFeatures/CSharpTest/KeywordHighlighting/AsyncLocalFunctionHighlighterTests.cs @@ -18,9 +18,8 @@ internal override Type GetHighlighterType() => typeof(AsyncAwaitHighlighter); [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] - public async Task TestLocalFunction() - { - await TestAsync( + public Task TestLocalFunction() + => TestAsync( """ using System; using System.Threading.Tasks; @@ -46,5 +45,4 @@ async Task UseAsync() } } """); - } } diff --git a/src/EditorFeatures/CSharpTest/KeywordHighlighting/AsyncMethodHighlighterTests.cs b/src/EditorFeatures/CSharpTest/KeywordHighlighting/AsyncMethodHighlighterTests.cs index 1b1e898edcbc9..e3b87f87b3b7c 100644 --- a/src/EditorFeatures/CSharpTest/KeywordHighlighting/AsyncMethodHighlighterTests.cs +++ b/src/EditorFeatures/CSharpTest/KeywordHighlighting/AsyncMethodHighlighterTests.cs @@ -19,9 +19,8 @@ internal override Type GetHighlighterType() => typeof(AsyncAwaitHighlighter); [Fact] - public async Task TestExample1_1() - { - await TestAsync( + public Task TestExample1_1() + => TestAsync( """ using System; using System.Threading.Tasks; @@ -47,12 +46,10 @@ async Task UseAsync() } } """); - } [Fact] - public async Task TestExample2_1() - { - await TestAsync( + public Task TestExample2_1() + => TestAsync( """ using System; using System.Threading.Tasks; @@ -78,5 +75,4 @@ async Task AsyncMethod() } } """); - } } diff --git a/src/EditorFeatures/CSharpTest/KeywordHighlighting/AwaitHighlighterTests.cs b/src/EditorFeatures/CSharpTest/KeywordHighlighting/AwaitHighlighterTests.cs index d1f8febcf6400..2ac7231c685e2 100644 --- a/src/EditorFeatures/CSharpTest/KeywordHighlighting/AwaitHighlighterTests.cs +++ b/src/EditorFeatures/CSharpTest/KeywordHighlighting/AwaitHighlighterTests.cs @@ -20,9 +20,8 @@ internal override Type GetHighlighterType() => typeof(AsyncAwaitHighlighter); [Fact] - public async Task TestExample2_2() - { - await TestAsync( + public Task TestExample2_2() + => TestAsync( """ using System; using System.Threading.Tasks; @@ -48,12 +47,10 @@ async Task AsyncMethod() } } """); - } [Fact] - public async Task TestExample2_3() - { - await TestAsync( + public Task TestExample2_3() + => TestAsync( """ using System; using System.Threading.Tasks; @@ -79,12 +76,10 @@ async Task AsyncMethod() } } """); - } [Fact] - public async Task TestExample2_4() - { - await TestAsync( + public Task TestExample2_4() + => TestAsync( """ using System; using System.Threading.Tasks; @@ -110,12 +105,10 @@ async Task AsyncMethod() } } """); - } [Fact] - public async Task TestExample3_2() - { - await TestAsync( + public Task TestExample3_2() + => TestAsync( """ using System; using System.Threading.Tasks; @@ -141,12 +134,10 @@ async Task UseAsync() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/573625")] - public async Task TestNestedAwaits1() - { - await TestAsync( + public Task TestNestedAwaits1() + => TestAsync( """ using System; using System.Threading.Tasks; @@ -177,12 +168,10 @@ async Task UseAsync() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/573625")] - public async Task TestNestedAwaits2() - { - await TestAsync( + public Task TestNestedAwaits2() + => TestAsync( """ using System; using System.Threading.Tasks; @@ -213,12 +202,10 @@ private static Task NewMethod() } } """); - } [Fact] - public async Task TestAwaitUsing_OnAsync() - { - await TestAsync( + public Task TestAwaitUsing_OnAsync() + => TestAsync( """ using System.Threading.Tasks; @@ -230,12 +217,10 @@ class C } } """); - } [Fact] - public async Task TestAwaitUsing_OnAwait() - { - await TestAsync( + public Task TestAwaitUsing_OnAwait() + => TestAsync( """ using System.Threading.Tasks; @@ -247,12 +232,10 @@ class C } } """); - } [Fact] - public async Task TestAwaitUsingDeclaration_OnAsync() - { - await TestAsync( + public Task TestAwaitUsingDeclaration_OnAsync() + => TestAsync( """ using System.Threading.Tasks; @@ -264,12 +247,10 @@ class C } } """); - } [Fact] - public async Task TestAwaitUsingDeclaration_OnAwait() - { - await TestAsync( + public Task TestAwaitUsingDeclaration_OnAwait() + => TestAsync( """ using System.Threading.Tasks; @@ -281,12 +262,10 @@ class C } } """); - } [Fact] - public async Task TestAwaitForEach_OnAsync() - { - await TestAsync( + public Task TestAwaitForEach_OnAsync() + => TestAsync( """ using System.Threading.Tasks; @@ -298,12 +277,10 @@ class C } } """); - } [Fact] - public async Task TestAwaitForEach_OnAwait() - { - await TestAsync( + public Task TestAwaitForEach_OnAwait() + => TestAsync( """ using System.Threading.Tasks; @@ -315,12 +292,10 @@ class C } } """); - } [Fact] - public async Task TestForEachVariableAwait_OnAsync() - { - await TestAsync( + public Task TestForEachVariableAwait_OnAsync() + => TestAsync( """ using System.Threading.Tasks; @@ -332,12 +307,10 @@ class C } } """); - } [Fact] - public async Task TestForEachVariableAwait_OnAwait() - { - await TestAsync( + public Task TestForEachVariableAwait_OnAwait() + => TestAsync( """ using System.Threading.Tasks; @@ -349,15 +322,12 @@ class C } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60400")] - public async Task TestTopLevelStatements() - { - await TestAsync( + public Task TestTopLevelStatements() + => TestAsync( """ [|await|] Task.Delay(1000); {|Cursor:[|await|]|} Task.Run(() => { }) """); - } } diff --git a/src/EditorFeatures/CSharpTest/KeywordHighlighting/CheckedExpressionHighlighterTests.cs b/src/EditorFeatures/CSharpTest/KeywordHighlighting/CheckedExpressionHighlighterTests.cs index b463b48ea2349..819d791e8272d 100644 --- a/src/EditorFeatures/CSharpTest/KeywordHighlighting/CheckedExpressionHighlighterTests.cs +++ b/src/EditorFeatures/CSharpTest/KeywordHighlighting/CheckedExpressionHighlighterTests.cs @@ -19,9 +19,8 @@ internal override Type GetHighlighterType() => typeof(CheckedExpressionHighlighter); [Fact] - public async Task TestExample1_1() - { - await TestAsync( + public Task TestExample1_1() + => TestAsync( """ class C { @@ -43,12 +42,10 @@ void M() } } """); - } [Fact] - public async Task TestExample2_1() - { - await TestAsync( + public Task TestExample2_1() + => TestAsync( """ class C { @@ -61,5 +58,4 @@ void M() } } """); - } } diff --git a/src/EditorFeatures/CSharpTest/KeywordHighlighting/CheckedStatementHighlighterTests.cs b/src/EditorFeatures/CSharpTest/KeywordHighlighting/CheckedStatementHighlighterTests.cs index 419df21337ea2..2269aa5c0ff72 100644 --- a/src/EditorFeatures/CSharpTest/KeywordHighlighting/CheckedStatementHighlighterTests.cs +++ b/src/EditorFeatures/CSharpTest/KeywordHighlighting/CheckedStatementHighlighterTests.cs @@ -19,9 +19,8 @@ internal override Type GetHighlighterType() => typeof(CheckedStatementHighlighter); [Fact] - public async Task TestExample1_1() - { - await TestAsync( + public Task TestExample1_1() + => TestAsync( """ class C { @@ -44,12 +43,10 @@ void M() } } """); - } [Fact] - public async Task TestExample1_2() - { - await TestAsync( + public Task TestExample1_2() + => TestAsync( """ class C { @@ -72,5 +69,4 @@ void M() } } """); - } } diff --git a/src/EditorFeatures/CSharpTest/KeywordHighlighting/ConditionalPreprocessorHighlighterTests.cs b/src/EditorFeatures/CSharpTest/KeywordHighlighting/ConditionalPreprocessorHighlighterTests.cs index 11c492d58e27f..f46d317700674 100644 --- a/src/EditorFeatures/CSharpTest/KeywordHighlighting/ConditionalPreprocessorHighlighterTests.cs +++ b/src/EditorFeatures/CSharpTest/KeywordHighlighting/ConditionalPreprocessorHighlighterTests.cs @@ -19,9 +19,8 @@ internal override Type GetHighlighterType() => typeof(ConditionalPreprocessorHighlighter); [Fact] - public async Task TestExample1_1() - { - await TestAsync( + public Task TestExample1_1() + => TestAsync( """ class C { @@ -49,12 +48,10 @@ void Commit() } } """); - } [Fact] - public async Task TestExample1_2() - { - await TestAsync( + public Task TestExample1_2() + => TestAsync( """ class C { @@ -82,12 +79,10 @@ void Commit() } } """); - } [Fact] - public async Task TestExample2_1() - { - await TestAsync( + public Task TestExample2_1() + => TestAsync( """ class C { @@ -115,12 +110,10 @@ void Commit() } } """); - } [Fact] - public async Task TestExample2_2() - { - await TestAsync( + public Task TestExample2_2() + => TestAsync( """ class C { @@ -148,12 +141,10 @@ void Commit() } } """); - } [Fact] - public async Task TestExample2_3() - { - await TestAsync( + public Task TestExample2_3() + => TestAsync( """ class C { @@ -181,12 +172,10 @@ void Commit() } } """); - } [Fact] - public async Task TestExample4_1() - { - await TestAsync( + public Task TestExample4_1() + => TestAsync( """ class C { @@ -205,12 +194,10 @@ void M() } } """); - } [Fact] - public async Task TestExample4_2() - { - await TestAsync( + public Task TestExample4_2() + => TestAsync( """ class C { @@ -229,12 +216,10 @@ void M() } } """); - } [Fact] - public async Task TestExample4_3() - { - await TestAsync( + public Task TestExample4_3() + => TestAsync( """ class C { @@ -253,12 +238,10 @@ void M() } } """); - } [Fact] - public async Task TestExample4_4() - { - await TestAsync( + public Task TestExample4_4() + => TestAsync( """ class C { @@ -277,5 +260,4 @@ void M() } } """); - } } diff --git a/src/EditorFeatures/CSharpTest/KeywordHighlighting/IfStatementHighlighterTests.cs b/src/EditorFeatures/CSharpTest/KeywordHighlighting/IfStatementHighlighterTests.cs index 41a7cb61a1f13..94c97e4864282 100644 --- a/src/EditorFeatures/CSharpTest/KeywordHighlighting/IfStatementHighlighterTests.cs +++ b/src/EditorFeatures/CSharpTest/KeywordHighlighting/IfStatementHighlighterTests.cs @@ -19,9 +19,8 @@ internal override Type GetHighlighterType() => typeof(IfStatementHighlighter); [Fact] - public async Task TestIfStatementWithIfAndSingleElse1() - { - await TestAsync( + public Task TestIfStatementWithIfAndSingleElse1() + => TestAsync( """ public class C { @@ -39,12 +38,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestIfStatementWithIfAndSingleElse2() - { - await TestAsync( + public Task TestIfStatementWithIfAndSingleElse2() + => TestAsync( """ public class C { @@ -62,12 +59,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestIfStatementWithIfAndElseIfAndElse1() - { - await TestAsync( + public Task TestIfStatementWithIfAndElseIfAndElse1() + => TestAsync( """ public class C { @@ -89,12 +84,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestIfStatementWithIfAndElseIfAndElse2() - { - await TestAsync( + public Task TestIfStatementWithIfAndElseIfAndElse2() + => TestAsync( """ public class C { @@ -116,12 +109,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestIfStatementWithIfAndElseIfAndElse3() - { - await TestAsync( + public Task TestIfStatementWithIfAndElseIfAndElse3() + => TestAsync( """ public class C { @@ -143,12 +134,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestIfStatementWithElseIfOnDifferentLines1() - { - await TestAsync( + public Task TestIfStatementWithElseIfOnDifferentLines1() + => TestAsync( """ public class C { @@ -171,12 +160,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestIfStatementWithElseIfOnDifferentLines2() - { - await TestAsync( + public Task TestIfStatementWithElseIfOnDifferentLines2() + => TestAsync( """ public class C { @@ -199,12 +186,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestIfStatementWithElseIfOnDifferentLines3() - { - await TestAsync( + public Task TestIfStatementWithElseIfOnDifferentLines3() + => TestAsync( """ public class C { @@ -227,12 +212,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestIfStatementWithElseIfOnDifferentLines4() - { - await TestAsync( + public Task TestIfStatementWithElseIfOnDifferentLines4() + => TestAsync( """ public class C { @@ -255,12 +238,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestIfStatementWithIfAndElseIfAndElseTouching1() - { - await TestAsync( + public Task TestIfStatementWithIfAndElseIfAndElseTouching1() + => TestAsync( """ public class C { @@ -281,12 +262,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestIfStatementWithIfAndElseIfAndElseTouching2() - { - await TestAsync( + public Task TestIfStatementWithIfAndElseIfAndElseTouching2() + => TestAsync( """ public class C { @@ -307,12 +286,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestIfStatementWithIfAndElseIfAndElseTouching3() - { - await TestAsync( + public Task TestIfStatementWithIfAndElseIfAndElseTouching3() + => TestAsync( """ public class C { @@ -333,12 +310,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestExtraSpacesBetweenElseAndIf1() - { - await TestAsync( + public Task TestExtraSpacesBetweenElseAndIf1() + => TestAsync( """ public class C { @@ -360,12 +335,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestExtraSpacesBetweenElseAndIf2() - { - await TestAsync( + public Task TestExtraSpacesBetweenElseAndIf2() + => TestAsync( """ public class C { @@ -387,12 +360,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestExtraSpacesBetweenElseAndIf3() - { - await TestAsync( + public Task TestExtraSpacesBetweenElseAndIf3() + => TestAsync( """ public class C { @@ -414,12 +385,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestCommentBetweenElseIf1() - { - await TestAsync( + public Task TestCommentBetweenElseIf1() + => TestAsync( """ public class C { @@ -441,12 +410,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestCommentBetweenElseIf2() - { - await TestAsync( + public Task TestCommentBetweenElseIf2() + => TestAsync( """ public class C { @@ -468,12 +435,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestCommentBetweenElseIf3() - { - await TestAsync( + public Task TestCommentBetweenElseIf3() + => TestAsync( """ public class C { @@ -495,12 +460,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestCommentBetweenElseIf4() - { - await TestAsync( + public Task TestCommentBetweenElseIf4() + => TestAsync( """ public class C { @@ -522,12 +485,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestNestedIfDoesNotHighlight1() - { - await TestAsync( + public Task TestNestedIfDoesNotHighlight1() + => TestAsync( """ public class C { @@ -554,12 +515,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestNestedIfDoesNotHighlight2() - { - await TestAsync( + public Task TestNestedIfDoesNotHighlight2() + => TestAsync( """ public class C { @@ -586,12 +545,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestNestedIfDoesNotHighlight3() - { - await TestAsync( + public Task TestNestedIfDoesNotHighlight3() + => TestAsync( """ public class C { @@ -618,12 +575,10 @@ public void Goo() } } """); - } [Fact] - public async Task TestExample1_1() - { - await TestAsync( + public Task TestExample1_1() + => TestAsync( """ class C { @@ -647,12 +602,10 @@ void M() } } """); - } [Fact] - public async Task TestExample2_1() - { - await TestAsync( + public Task TestExample2_1() + => TestAsync( """ class C { @@ -676,12 +629,10 @@ void M() } } """); - } [Fact] - public async Task TestExample2_2() - { - await TestAsync( + public Task TestExample2_2() + => TestAsync( """ class C { @@ -705,12 +656,10 @@ void M() } } """); - } [Fact] - public async Task TestExample2_3() - { - await TestAsync( + public Task TestExample2_3() + => TestAsync( """ class C { @@ -734,5 +683,4 @@ void M() } } """); - } } diff --git a/src/EditorFeatures/CSharpTest/KeywordHighlighting/LockStatementHighlighterTests.cs b/src/EditorFeatures/CSharpTest/KeywordHighlighting/LockStatementHighlighterTests.cs index 02b10598b4335..fd726b888e37b 100644 --- a/src/EditorFeatures/CSharpTest/KeywordHighlighting/LockStatementHighlighterTests.cs +++ b/src/EditorFeatures/CSharpTest/KeywordHighlighting/LockStatementHighlighterTests.cs @@ -18,9 +18,8 @@ internal override Type GetHighlighterType() => typeof(LockStatementHighlighter); [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] - public async Task TestExample1_1() - { - await TestAsync( + public Task TestExample1_1() + => TestAsync( """ class Account { @@ -44,5 +43,4 @@ int Withdraw(int amount) } } """); - } } diff --git a/src/EditorFeatures/CSharpTest/KeywordHighlighting/LoopHighlighterTests.cs b/src/EditorFeatures/CSharpTest/KeywordHighlighting/LoopHighlighterTests.cs index e1ef3c6013dc0..bdb6d2e7788c7 100644 --- a/src/EditorFeatures/CSharpTest/KeywordHighlighting/LoopHighlighterTests.cs +++ b/src/EditorFeatures/CSharpTest/KeywordHighlighting/LoopHighlighterTests.cs @@ -19,9 +19,8 @@ internal override Type GetHighlighterType() => typeof(LoopHighlighter); [Fact] - public async Task TestExample1_1() - { - await TestAsync( + public Task TestExample1_1() + => TestAsync( """ class C { @@ -41,12 +40,10 @@ void M() } } """); - } [Fact] - public async Task TestExample1_2() - { - await TestAsync( + public Task TestExample1_2() + => TestAsync( """ class C { @@ -66,12 +63,10 @@ void M() } } """); - } [Fact] - public async Task TestExample1_3() - { - await TestAsync( + public Task TestExample1_3() + => TestAsync( """ class C { @@ -91,12 +86,10 @@ void M() } } """); - } [Fact] - public async Task TestExample2_1() - { - await TestAsync( + public Task TestExample2_1() + => TestAsync( """ class C { @@ -117,12 +110,10 @@ void M() } } """); - } [Fact] - public async Task TestExample2_2() - { - await TestAsync( + public Task TestExample2_2() + => TestAsync( """ class C { @@ -143,12 +134,10 @@ void M() } } """); - } [Fact] - public async Task TestExample2_3() - { - await TestAsync( + public Task TestExample2_3() + => TestAsync( """ class C { @@ -169,12 +158,10 @@ void M() } } """); - } [Fact] - public async Task TestExample2_4() - { - await TestAsync( + public Task TestExample2_4() + => TestAsync( """ class C { @@ -195,12 +182,10 @@ void M() } } """); - } [Fact] - public async Task TestExample2_5() - { - await TestAsync( + public Task TestExample2_5() + => TestAsync( """ class C { @@ -221,12 +206,10 @@ void M() } } """); - } [Fact] - public async Task TestExample2_6() - { - await TestAsync( + public Task TestExample2_6() + => TestAsync( """ class C { @@ -247,12 +230,10 @@ void M() } } """); - } [Fact] - public async Task TestExample3_1() - { - await TestAsync( + public Task TestExample3_1() + => TestAsync( """ class C { @@ -272,12 +253,10 @@ void M() } } """); - } [Fact] - public async Task TestExample3_2() - { - await TestAsync( + public Task TestExample3_2() + => TestAsync( """ class C { @@ -297,12 +276,10 @@ void M() } } """); - } [Fact] - public async Task TestExample3_3() - { - await TestAsync( + public Task TestExample3_3() + => TestAsync( """ class C { @@ -322,12 +299,10 @@ void M() } } """); - } [Fact] - public async Task TestExample4_1() - { - await TestAsync( + public Task TestExample4_1() + => TestAsync( """ class C { @@ -347,12 +322,10 @@ void M() } } """); - } [Fact] - public async Task TestExample4_2() - { - await TestAsync( + public Task TestExample4_2() + => TestAsync( """ class C { @@ -372,12 +345,10 @@ void M() } } """); - } [Fact] - public async Task TestExample4_3() - { - await TestAsync( + public Task TestExample4_3() + => TestAsync( """ class C { @@ -397,12 +368,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample1_1() - { - await TestAsync( + public Task TestNestedExample1_1() + => TestAsync( """ class C { @@ -441,12 +410,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample1_2() - { - await TestAsync( + public Task TestNestedExample1_2() + => TestAsync( """ class C { @@ -485,12 +452,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample1_3() - { - await TestAsync( + public Task TestNestedExample1_3() + => TestAsync( """ class C { @@ -529,12 +494,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample1_4() - { - await TestAsync( + public Task TestNestedExample1_4() + => TestAsync( """ class C { @@ -573,12 +536,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample1_5() - { - await TestAsync( + public Task TestNestedExample1_5() + => TestAsync( """ class C { @@ -617,12 +578,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample1_6() - { - await TestAsync( + public Task TestNestedExample1_6() + => TestAsync( """ class C { @@ -661,12 +620,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample1_7() - { - await TestAsync( + public Task TestNestedExample1_7() + => TestAsync( """ class C { @@ -705,12 +662,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample1_8() - { - await TestAsync( + public Task TestNestedExample1_8() + => TestAsync( """ class C { @@ -749,14 +704,12 @@ void M() } } """); - } // TestNestedExample1 9-13 are in SwitchStatementHighlighterTests.cs [Fact] - public async Task TestNestedExample1_14() - { - await TestAsync( + public Task TestNestedExample1_14() + => TestAsync( """ class C { @@ -795,12 +748,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample1_15() - { - await TestAsync( + public Task TestNestedExample1_15() + => TestAsync( """ class C { @@ -839,12 +790,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample2_1() - { - await TestAsync( + public Task TestNestedExample2_1() + => TestAsync( """ class C { @@ -877,12 +826,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample2_2() - { - await TestAsync( + public Task TestNestedExample2_2() + => TestAsync( """ class C { @@ -915,12 +862,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample2_3() - { - await TestAsync( + public Task TestNestedExample2_3() + => TestAsync( """ class C { @@ -953,12 +898,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample2_4() - { - await TestAsync( + public Task TestNestedExample2_4() + => TestAsync( """ class C { @@ -991,12 +934,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample2_5() - { - await TestAsync( + public Task TestNestedExample2_5() + => TestAsync( """ class C { @@ -1029,12 +970,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample2_6() - { - await TestAsync( + public Task TestNestedExample2_6() + => TestAsync( """ class C { @@ -1067,12 +1006,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample2_7() - { - await TestAsync( + public Task TestNestedExample2_7() + => TestAsync( """ class C { @@ -1105,12 +1042,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample2_8() - { - await TestAsync( + public Task TestNestedExample2_8() + => TestAsync( """ class C { @@ -1143,12 +1078,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample2_9() - { - await TestAsync( + public Task TestNestedExample2_9() + => TestAsync( """ class C { @@ -1181,12 +1114,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample2_10() - { - await TestAsync( + public Task TestNestedExample2_10() + => TestAsync( """ class C { @@ -1219,12 +1150,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample2_11() - { - await TestAsync( + public Task TestNestedExample2_11() + => TestAsync( """ class C { @@ -1257,5 +1186,4 @@ void M() } } """); - } } diff --git a/src/EditorFeatures/CSharpTest/KeywordHighlighting/RegionHighlighterTests.cs b/src/EditorFeatures/CSharpTest/KeywordHighlighting/RegionHighlighterTests.cs index e3322a6ccbb0f..b53f1a4f87a32 100644 --- a/src/EditorFeatures/CSharpTest/KeywordHighlighting/RegionHighlighterTests.cs +++ b/src/EditorFeatures/CSharpTest/KeywordHighlighting/RegionHighlighterTests.cs @@ -19,9 +19,8 @@ internal override Type GetHighlighterType() => typeof(RegionHighlighter); [Fact] - public async Task TestExample1_1() - { - await TestAsync( + public Task TestExample1_1() + => TestAsync( """ class C { @@ -32,12 +31,10 @@ static void Main() [|#endregion|] } """); - } [Fact] - public async Task TestExample1_2() - { - await TestAsync( + public Task TestExample1_2() + => TestAsync( """ class C { @@ -48,12 +45,10 @@ static void Main() {|Cursor:[|#endregion|]|} } """); - } [Fact] - public async Task TestNestedExample1_1() - { - await TestAsync( + public Task TestNestedExample1_1() + => TestAsync( """ class C { @@ -66,12 +61,10 @@ static void Main() [|#endregion|] } """); - } [Fact] - public async Task TestNestedExample1_2() - { - await TestAsync( + public Task TestNestedExample1_2() + => TestAsync( """ class C { @@ -84,12 +77,10 @@ static void Main() #endregion } """); - } [Fact] - public async Task TestNestedExample1_3() - { - await TestAsync( + public Task TestNestedExample1_3() + => TestAsync( """ class C { @@ -102,12 +93,10 @@ static void Main() #endregion } """); - } [Fact] - public async Task TestNestedExample1_4() - { - await TestAsync( + public Task TestNestedExample1_4() + => TestAsync( """ class C { @@ -120,5 +109,4 @@ static void Main() {|Cursor:[|#endregion|]|} } """); - } } diff --git a/src/EditorFeatures/CSharpTest/KeywordHighlighting/ReturnStatementHighlighterTests.cs b/src/EditorFeatures/CSharpTest/KeywordHighlighting/ReturnStatementHighlighterTests.cs index 4fbde22856747..c71557e1559f7 100644 --- a/src/EditorFeatures/CSharpTest/KeywordHighlighting/ReturnStatementHighlighterTests.cs +++ b/src/EditorFeatures/CSharpTest/KeywordHighlighting/ReturnStatementHighlighterTests.cs @@ -19,9 +19,8 @@ internal override Type GetHighlighterType() => typeof(ReturnStatementHighlighter); [Fact] - public async Task TestInLambda() - { - await TestAsync( + public Task TestInLambda() + => TestAsync( """ static double CalculateArea(double radius) { @@ -38,12 +37,10 @@ static double CalculateArea(double radius) return calcArea(radius); } """); - } [Fact] - public async Task TestInLambda_NotOnReturnValue() - { - await TestAsync( + public Task TestInLambda_NotOnReturnValue() + => TestAsync( """ class C { @@ -63,12 +60,10 @@ static double CalculateArea(double radius) } } """); - } [Fact] - public async Task TestInLambda_OnSemicolon() - { - await TestAsync( + public Task TestInLambda_OnSemicolon() + => TestAsync( """ class C { @@ -88,12 +83,10 @@ static double CalculateArea(double radius) } } """); - } [Fact] - public async Task TestInLambda_SecondOccurence() - { - await TestAsync( + public Task TestInLambda_SecondOccurence() + => TestAsync( """ class C { @@ -113,12 +106,10 @@ static double CalculateArea(double radius) } } """); - } [Fact] - public async Task TestInLambda_SecondOccurence_NotOnReturnValue() - { - await TestAsync( + public Task TestInLambda_SecondOccurence_NotOnReturnValue() + => TestAsync( """ class C { @@ -138,12 +129,10 @@ static double CalculateArea(double radius) } } """); - } [Fact] - public async Task TestInLambda_SecondOccurence_OnSemicolon() - { - await TestAsync( + public Task TestInLambda_SecondOccurence_OnSemicolon() + => TestAsync( """ class C { @@ -163,12 +152,10 @@ static double CalculateArea(double radius) } } """); - } [Fact] - public async Task TestInMethodWithLambda() - { - await TestAsync( + public Task TestInMethodWithLambda() + => TestAsync( """ class C { @@ -188,12 +175,10 @@ static double CalculateArea(double radius) } } """); - } [Fact] - public async Task TestInMethodWithLambda_NotOnReturnValue() - { - await TestAsync( + public Task TestInMethodWithLambda_NotOnReturnValue() + => TestAsync( """ class C { @@ -213,12 +198,10 @@ static double CalculateArea(double radius) } } """); - } [Fact] - public async Task TestInMethodWithLambda_OnSemicolon() - { - await TestAsync( + public Task TestInMethodWithLambda_OnSemicolon() + => TestAsync( """ class C { @@ -238,12 +221,10 @@ static double CalculateArea(double radius) } } """); - } [Fact] - public async Task TestInConstructor() - { - await TestAsync( + public Task TestInConstructor() + => TestAsync( """ class C { @@ -254,12 +235,10 @@ class C } } """); - } [Fact] - public async Task TestInDestructor() - { - await TestAsync( + public Task TestInDestructor() + => TestAsync( """ class C { @@ -270,12 +249,10 @@ class C } } """); - } [Fact] - public async Task TestInOperator() - { - await TestAsync( + public Task TestInOperator() + => TestAsync( """ class C { @@ -286,12 +263,10 @@ class C } } """); - } [Fact] - public async Task TestInConversionOperator() - { - await TestAsync( + public Task TestInConversionOperator() + => TestAsync( """ class C { @@ -302,12 +277,10 @@ public static explicit operator string(C a) } } """); - } [Fact] - public async Task TestInGetter() - { - await TestAsync( + public Task TestInGetter() + => TestAsync( """ class C { @@ -326,12 +299,10 @@ int P } } """); - } [Fact] - public async Task TestInSetter() - { - await TestAsync( + public Task TestInSetter() + => TestAsync( """ class C { @@ -350,12 +321,10 @@ int P } } """); - } [Fact] - public async Task TestInInit() - { - await TestAsync( + public Task TestInInit() + => TestAsync( """ class C { @@ -374,12 +343,10 @@ int P } } """); - } [Fact] - public async Task TestInAdder() - { - await TestAsync( + public Task TestInAdder() + => TestAsync( """ class C { @@ -398,12 +365,10 @@ event EventHandler E } } """); - } [Fact] - public async Task TestInRemover() - { - await TestAsync( + public Task TestInRemover() + => TestAsync( """ class C { @@ -422,12 +387,10 @@ event EventHandler E } } """); - } [Fact] - public async Task TestInLocalFunction() - { - await TestAsync( + public Task TestInLocalFunction() + => TestAsync( """ class C { @@ -443,12 +406,10 @@ void F() } } """); - } [Fact] - public async Task TestInSimpleLambda() - { - await TestAsync( + public Task TestInSimpleLambda() + => TestAsync( """ class C { @@ -464,12 +425,10 @@ void M() } } """); - } [Fact] - public async Task TestInParenthesizedLambda() - { - await TestAsync( + public Task TestInParenthesizedLambda() + => TestAsync( """ class C { @@ -485,12 +444,10 @@ void M() } } """); - } [Fact] - public async Task TestInAnonymousMethod() - { - await TestAsync( + public Task TestInAnonymousMethod() + => TestAsync( """ class C { @@ -506,15 +463,12 @@ void M() } } """); - } [Fact] - public async Task TestInTopLevelStatements() - { - await TestAsync( + public Task TestInTopLevelStatements() + => TestAsync( """ if (args.Length > 0) [|return|] 0; {|Cursor:[|return|]|} 1; """); - } } diff --git a/src/EditorFeatures/CSharpTest/KeywordHighlighting/SwitchStatementHighlighterTests.cs b/src/EditorFeatures/CSharpTest/KeywordHighlighting/SwitchStatementHighlighterTests.cs index b0d35e02013d7..ef30b71286365 100644 --- a/src/EditorFeatures/CSharpTest/KeywordHighlighting/SwitchStatementHighlighterTests.cs +++ b/src/EditorFeatures/CSharpTest/KeywordHighlighting/SwitchStatementHighlighterTests.cs @@ -20,9 +20,8 @@ internal override Type GetHighlighterType() => typeof(SwitchStatementHighlighter); [Fact] - public async Task TestExample1_OnSwitchKeyword() - { - await TestAsync( + public Task TestExample1_OnSwitchKeyword() + => TestAsync( """ class C { @@ -43,12 +42,10 @@ void M() } } """); - } [Fact] - public async Task TestExample1_OnCaseKeyword() - { - await TestAsync( + public Task TestExample1_OnCaseKeyword() + => TestAsync( """ class C { @@ -69,12 +66,10 @@ void M() } } """); - } [Fact] - public async Task TestExample1_AfterCaseColon() - { - await TestAsync( + public Task TestExample1_AfterCaseColon() + => TestAsync( """ class C { @@ -95,12 +90,10 @@ void M() } } """); - } [Fact] - public async Task TestExample1_NotOnCaseValue() - { - await TestAsync( + public Task TestExample1_NotOnCaseValue() + => TestAsync( """ class C { @@ -121,12 +114,10 @@ void M() } } """); - } [Fact] - public async Task TestExample1_OnBreakStatement() - { - await TestAsync( + public Task TestExample1_OnBreakStatement() + => TestAsync( """ class C { @@ -147,12 +138,10 @@ void M() } } """); - } [Fact] - public async Task TestExample1_OnDefaultLabel() - { - await TestAsync( + public Task TestExample1_OnDefaultLabel() + => TestAsync( """ class C { @@ -173,12 +162,10 @@ void M() } } """); - } [Fact] - public async Task TestExample2_OnGotoCaseKeywords() - { - await TestAsync( + public Task TestExample2_OnGotoCaseKeywords() + => TestAsync( """ class C { @@ -199,12 +186,10 @@ void M() } } """); - } [Fact] - public async Task TestExample2_AfterGotoCaseSemicolon() - { - await TestAsync( + public Task TestExample2_AfterGotoCaseSemicolon() + => TestAsync( """ class C { @@ -225,12 +210,10 @@ void M() } } """); - } [Fact] - public async Task TestExample2_NotOnGotoCaseValue() - { - await TestAsync( + public Task TestExample2_NotOnGotoCaseValue() + => TestAsync( """ class C { @@ -251,12 +234,10 @@ void M() } } """); - } [Fact] - public async Task TestExample2_OnGotoDefaultStatement() - { - await TestAsync( + public Task TestExample2_OnGotoDefaultStatement() + => TestAsync( """ class C { @@ -277,12 +258,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample1_OnSwitchKeyword() - { - await TestAsync( + public Task TestNestedExample1_OnSwitchKeyword() + => TestAsync( """ class C { @@ -321,12 +300,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample1_OnCaseKeyword() - { - await TestAsync( + public Task TestNestedExample1_OnCaseKeyword() + => TestAsync( """ class C { @@ -365,12 +342,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample1_NotBeforeCaseValue() - { - await TestAsync( + public Task TestNestedExample1_NotBeforeCaseValue() + => TestAsync( """ class C { @@ -409,12 +384,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample1_AfterCaseColon() - { - await TestAsync( + public Task TestNestedExample1_AfterCaseColon() + => TestAsync( """ class C { @@ -453,12 +426,10 @@ void M() } } """); - } [Fact] - public async Task TestNestedExample1_OnBreakStatement() - { - await TestAsync( + public Task TestNestedExample1_OnBreakStatement() + => TestAsync( """ class C { @@ -497,12 +468,10 @@ void M() } } """); - } [Fact] - public async Task Bug3483() - { - await TestAsync( + public Task Bug3483() + => TestAsync( """ class C { @@ -516,12 +485,10 @@ static void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25039")] - public async Task TestWithUnrelatedGotoStatement_OnGotoCaseGotoKeyword() - { - await TestAsync( + public Task TestWithUnrelatedGotoStatement_OnGotoCaseGotoKeyword() + => TestAsync( """ class C { @@ -543,12 +510,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25039")] - public async Task TestWithUnrelatedGotoStatement_OnGotoDefaultGotoKeyword() - { - await TestAsync( + public Task TestWithUnrelatedGotoStatement_OnGotoDefaultGotoKeyword() + => TestAsync( """ class C { @@ -570,12 +535,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25039")] - public async Task TestWithUnrelatedGotoStatement_NotOnGotoLabelGotoKeyword() - { - await TestAsync( + public Task TestWithUnrelatedGotoStatement_NotOnGotoLabelGotoKeyword() + => TestAsync( """ class C { @@ -597,12 +560,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25039")] - public async Task TestWithNestedStatements_OnSwitchKeyword() - { - await TestAsync( + public Task TestWithNestedStatements_OnSwitchKeyword() + => TestAsync( """ class C { @@ -629,12 +590,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25039")] - public async Task TestWithNestedStatements_OnBreakKeyword() - { - await TestAsync( + public Task TestWithNestedStatements_OnBreakKeyword() + => TestAsync( """ class C { @@ -661,12 +620,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25039")] - public async Task TestWithGotoCaseAndBreakInsideLoop_OnSwitchKeyword() - { - await TestAsync( + public Task TestWithGotoCaseAndBreakInsideLoop_OnSwitchKeyword() + => TestAsync( """ class C { @@ -691,12 +648,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25039")] - public async Task TestWithGotoCaseAndBreakInsideLoop_OnGotoCaseGotoKeyword() - { - await TestAsync( + public Task TestWithGotoCaseAndBreakInsideLoop_OnGotoCaseGotoKeyword() + => TestAsync( """ class C { @@ -721,12 +676,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25039")] - public async Task TestWithGotoCaseAndBreakInsideLoop_NotOnLoopBreakKeyword() - { - await TestAsync( + public Task TestWithGotoCaseAndBreakInsideLoop_NotOnLoopBreakKeyword() + => TestAsync( """ class C { @@ -751,12 +704,10 @@ void M() } } """); - } [Fact] - public async Task TestWithWhenClauseAndPattern_OnSwitchKeyword() - { - await TestAsync( + public Task TestWithWhenClauseAndPattern_OnSwitchKeyword() + => TestAsync( """ class C { @@ -772,12 +723,10 @@ void M() } } """); - } [Fact] - public async Task TestWithWhenClauseAndPattern_NotOnWhenKeyword() - { - await TestAsync( + public Task TestWithWhenClauseAndPattern_NotOnWhenKeyword() + => TestAsync( """ class C { @@ -793,12 +742,10 @@ void M() } } """); - } [Fact] - public async Task TestWithWhenClauseAndPattern_AfterWhenCaseColon() - { - await TestAsync( + public Task TestWithWhenClauseAndPattern_AfterWhenCaseColon() + => TestAsync( """ class C { @@ -814,12 +761,10 @@ void M() } } """); - } [Fact] - public async Task TestWithWhenClauseAndPattern_AfterPatternCaseColon() - { - await TestAsync( + public Task TestWithWhenClauseAndPattern_AfterPatternCaseColon() + => TestAsync( """ class C { @@ -835,12 +780,10 @@ void M() } } """); - } [Fact] - public async Task TestWithWhenClauseAndPattern_NotOnWhenValue() - { - await TestAsync( + public Task TestWithWhenClauseAndPattern_NotOnWhenValue() + => TestAsync( """ class C { @@ -856,12 +799,10 @@ void M() } } """); - } [Fact] - public async Task TestWithWhenClauseAndPattern_NotOnPattern() - { - await TestAsync( + public Task TestWithWhenClauseAndPattern_NotOnPattern() + => TestAsync( """ class C { @@ -877,5 +818,4 @@ void M() } } """); - } } diff --git a/src/EditorFeatures/CSharpTest/KeywordHighlighting/TryStatementHighlighterTests.cs b/src/EditorFeatures/CSharpTest/KeywordHighlighting/TryStatementHighlighterTests.cs index 69a9a91331175..f7462893c1b3f 100644 --- a/src/EditorFeatures/CSharpTest/KeywordHighlighting/TryStatementHighlighterTests.cs +++ b/src/EditorFeatures/CSharpTest/KeywordHighlighting/TryStatementHighlighterTests.cs @@ -19,9 +19,8 @@ internal override Type GetHighlighterType() => typeof(TryStatementHighlighter); [Fact] - public async Task TestExample1_1() - { - await TestAsync( + public Task TestExample1_1() + => TestAsync( """ class C { @@ -42,12 +41,10 @@ void M() } } """); - } [Fact] - public async Task TestExample1_2() - { - await TestAsync( + public Task TestExample1_2() + => TestAsync( """ class C { @@ -68,12 +65,10 @@ void M() } } """); - } [Fact] - public async Task TestExample1_3() - { - await TestAsync( + public Task TestExample1_3() + => TestAsync( """ class C { @@ -94,12 +89,10 @@ void M() } } """); - } [Fact] - public async Task TestExample1_4() - { - await TestAsync( + public Task TestExample1_4() + => TestAsync( """ class C { @@ -120,12 +113,10 @@ void M() } } """); - } [Fact] - public async Task TestExceptionFilter1() - { - await TestAsync( + public Task TestExceptionFilter1() + => TestAsync( """ class C { @@ -146,12 +137,10 @@ void M() } } """); - } [Fact] - public async Task TestExceptionFilter2() - { - await TestAsync( + public Task TestExceptionFilter2() + => TestAsync( """ class C { @@ -172,12 +161,10 @@ void M() } } """); - } [Fact] - public async Task TestExceptionFilter3() - { - await TestAsync( + public Task TestExceptionFilter3() + => TestAsync( """ class C { @@ -198,5 +185,4 @@ void M() } } """); - } } diff --git a/src/EditorFeatures/CSharpTest/KeywordHighlighting/UnsafeStatementHighlighterTests.cs b/src/EditorFeatures/CSharpTest/KeywordHighlighting/UnsafeStatementHighlighterTests.cs index 6e16f0a0dbf04..99e41fbc25e64 100644 --- a/src/EditorFeatures/CSharpTest/KeywordHighlighting/UnsafeStatementHighlighterTests.cs +++ b/src/EditorFeatures/CSharpTest/KeywordHighlighting/UnsafeStatementHighlighterTests.cs @@ -18,9 +18,8 @@ internal override Type GetHighlighterType() => typeof(UnsafeStatementHighlighter); [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] - public async Task TestExample1_1() - { - await TestAsync( + public Task TestExample1_1() + => TestAsync( """ class C { @@ -37,5 +36,4 @@ void M() } } """); - } } diff --git a/src/EditorFeatures/CSharpTest/KeywordHighlighting/UsingStatementHighlighterTests.cs b/src/EditorFeatures/CSharpTest/KeywordHighlighting/UsingStatementHighlighterTests.cs index f99acb3a8c497..83b148532a48e 100644 --- a/src/EditorFeatures/CSharpTest/KeywordHighlighting/UsingStatementHighlighterTests.cs +++ b/src/EditorFeatures/CSharpTest/KeywordHighlighting/UsingStatementHighlighterTests.cs @@ -18,9 +18,8 @@ internal override Type GetHighlighterType() => typeof(UsingStatementHighlighter); [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] - public async Task TestExample1_1() - { - await TestAsync( + public Task TestExample1_1() + => TestAsync( """ class C { @@ -33,5 +32,4 @@ void M() } } """); - } } diff --git a/src/EditorFeatures/CSharpTest/KeywordHighlighting/YieldStatementHighlighterTests.cs b/src/EditorFeatures/CSharpTest/KeywordHighlighting/YieldStatementHighlighterTests.cs index 1567412859b55..80de4fb52b905 100644 --- a/src/EditorFeatures/CSharpTest/KeywordHighlighting/YieldStatementHighlighterTests.cs +++ b/src/EditorFeatures/CSharpTest/KeywordHighlighting/YieldStatementHighlighterTests.cs @@ -19,9 +19,8 @@ internal override Type GetHighlighterType() => typeof(YieldStatementHighlighter); [Fact] - public async Task TestExample1_1() - { - await TestAsync( + public Task TestExample1_1() + => TestAsync( """ class C { @@ -39,12 +38,10 @@ IEnumerable Range(int min, int max) } } """); - } [Fact] - public async Task TestExample1_2() - { - await TestAsync( + public Task TestExample1_2() + => TestAsync( """ class C { @@ -62,12 +59,10 @@ IEnumerable Range(int min, int max) } } """); - } [Fact] - public async Task TestExample1_3() - { - await TestAsync( + public Task TestExample1_3() + => TestAsync( """ class C { @@ -85,12 +80,10 @@ IEnumerable Range(int min, int max) } } """); - } [Fact] - public async Task TestExample1_4() - { - await TestAsync( + public Task TestExample1_4() + => TestAsync( """ class C { @@ -108,5 +101,4 @@ IEnumerable Range(int min, int max) } } """); - } } diff --git a/src/EditorFeatures/CSharpTest/LineSeparators/LineSeparatorTests.cs b/src/EditorFeatures/CSharpTest/LineSeparators/LineSeparatorTests.cs index 4ae9509439dd5..7e7d067060bdf 100644 --- a/src/EditorFeatures/CSharpTest/LineSeparators/LineSeparatorTests.cs +++ b/src/EditorFeatures/CSharpTest/LineSeparators/LineSeparatorTests.cs @@ -24,34 +24,27 @@ public async Task TestEmptyFile() => await AssertTagsOnBracesOrSemicolonsAsync(contents: string.Empty); [Fact] - public async Task TestEmptyClass() - { - var file = """ + public Task TestEmptyClass() + => AssertTagsOnBracesOrSemicolonsAsync(""" class C { } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 0); - } + """, 0); [Fact] - public async Task TestClassWithOneMethod() - { - var file = """ + public Task TestClassWithOneMethod() + => AssertTagsOnBracesOrSemicolonsAsync(""" class C { void M() { } } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 1); - } + """, 1); [Fact] - public async Task TestClassWithTwoMethods() - { - var file = """ + public Task TestClassWithTwoMethods() + => AssertTagsOnBracesOrSemicolonsAsync(""" class C { void M() @@ -62,14 +55,11 @@ void N() { } } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); - } + """, 0, 2); [Fact] - public async Task TestClassWithTwoNonEmptyMethods() - { - var file = """ + public Task TestClassWithTwoNonEmptyMethods() + => AssertTagsOnBracesOrSemicolonsAsync(""" class C { void M() @@ -82,14 +72,11 @@ void N() M(); } } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 1, 4); - } + """, 1, 4); [Fact] - public async Task TestClassWithMethodAndField() - { - var file = """ + public Task TestClassWithMethodAndField() + => AssertTagsOnBracesOrSemicolonsAsync(""" class C { void M() @@ -98,39 +85,30 @@ void M() int field; } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); - } + """, 0, 2); [Fact] - public async Task TestEmptyNamespace() - { - var file = """ + public Task TestEmptyNamespace() + => AssertTagsOnBracesOrSemicolonsAsync(""" namespace N { } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 0); - } + """, 0); [Fact] - public async Task TestNamespaceAndClass() - { - var file = """ + public Task TestNamespaceAndClass() + => AssertTagsOnBracesOrSemicolonsAsync(""" namespace N { class C { } } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 1); - } + """, 1); [Fact] - public async Task TestNamespaceAndTwoClasses() - { - var file = """ + public Task TestNamespaceAndTwoClasses() + => AssertTagsOnBracesOrSemicolonsAsync(""" namespace N { class C @@ -141,14 +119,11 @@ class D { } } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); - } + """, 0, 2); [Fact] - public async Task TestNamespaceAndTwoClassesAndDelegate() - { - var file = """ + public Task TestNamespaceAndTwoClassesAndDelegate() + => AssertTagsOnBracesOrSemicolonsAsync(""" namespace N { class C @@ -161,28 +136,22 @@ class D delegate void Del(); } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 1, 3); - } + """, 0, 1, 3); [Fact] - public async Task TestNestedClass() - { - var file = """ + public Task TestNestedClass() + => AssertTagsOnBracesOrSemicolonsAsync(""" class C { class N { } } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 1); - } + """, 1); [Fact] - public async Task TestTwoNestedClasses() - { - var file = """ + public Task TestTwoNestedClasses() + => AssertTagsOnBracesOrSemicolonsAsync(""" class C { class N @@ -193,47 +162,35 @@ class N2 { } } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); - } + """, 0, 2); [Fact] - public async Task TestStruct() - { - var file = """ + public Task TestStruct() + => AssertTagsOnBracesOrSemicolonsAsync(""" struct S { } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 0); - } + """, 0); [Fact] - public async Task TestInterface() - { - var file = """ + public Task TestInterface() + => AssertTagsOnBracesOrSemicolonsAsync(""" interface I { } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 0); - } + """, 0); [Fact] - public async Task TestEnum() - { - var file = """ + public Task TestEnum() + => AssertTagsOnBracesOrSemicolonsAsync(""" enum E { } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 0); - } + """, 0); [Fact] - public async Task TestProperty() - { - var file = """ + public Task TestProperty() + => AssertTagsOnBracesOrSemicolonsAsync(""" class C { int Prop @@ -247,14 +204,11 @@ int Prop } } } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 4); - } + """, 4); [Fact] - public async Task TestPropertyAndField() - { - var file = """ + public Task TestPropertyAndField() + => AssertTagsOnBracesOrSemicolonsAsync(""" class C { int Prop @@ -270,14 +224,11 @@ int Prop int field; } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 3, 5); - } + """, 3, 5); [Fact] - public async Task TestClassWithFieldAndMethod() - { - var file = """ + public Task TestClassWithFieldAndMethod() + => AssertTagsOnBracesOrSemicolonsAsync(""" class C { int field; @@ -286,27 +237,21 @@ void M() { } } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); - } + """, 0, 2); [Fact] - public async Task UsingDirective() - { - var file = """ + public Task UsingDirective() + => AssertTagsOnBracesOrSemicolonsAsync(""" using System; class C { } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 1); - } + """, 0, 1); [Fact] - public async Task UsingDirectiveInNamespace() - { - var file = """ + public Task UsingDirectiveInNamespace() + => AssertTagsOnBracesOrSemicolonsAsync(""" namespace N { using System; @@ -315,14 +260,11 @@ class C { } } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); - } + """, 0, 2); [Fact] - public async Task UsingDirectiveInFileScopedNamespace() - { - var file = """ + public Task UsingDirectiveInFileScopedNamespace() + => AssertTagsOnBracesOrSemicolonsAsync(""" namespace N; using System; @@ -330,14 +272,11 @@ namespace N; class C { } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 1); - } + """, 1); [Fact] - public async Task PropertyStyleEventDeclaration() - { - var file = """ + public Task PropertyStyleEventDeclaration() + => AssertTagsOnBracesOrSemicolonsAsync(""" class C { event EventHandler E @@ -348,14 +287,11 @@ event EventHandler E int i; } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 2, 4); - } + """, 2, 4); [Fact] - public async Task IndexerDeclaration() - { - var file = """ + public Task IndexerDeclaration() + => AssertTagsOnBracesOrSemicolonsAsync(""" class C { int this[int i] @@ -366,14 +302,11 @@ int this[int i] int i; } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 3, 5); - } + """, 3, 5); [Fact] - public async Task Constructor() - { - var file = """ + public Task Constructor() + => AssertTagsOnBracesOrSemicolonsAsync(""" class C { C() @@ -382,14 +315,11 @@ class C int i; } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); - } + """, 0, 2); [Fact] - public async Task Destructor() - { - var file = """ + public Task Destructor() + => AssertTagsOnBracesOrSemicolonsAsync(""" class C { ~C() @@ -398,14 +328,11 @@ class C int i; } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); - } + """, 0, 2); [Fact] - public async Task Operator() - { - var file = """ + public Task Operator() + => AssertTagsOnBracesOrSemicolonsAsync(""" class C { static C operator +(C lhs, C rhs) @@ -414,14 +341,11 @@ class C int i; } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); - } + """, 0, 2); [Fact] - public async Task ConversionOperator() - { - var file = """ + public Task ConversionOperator() + => AssertTagsOnBracesOrSemicolonsAsync(""" class C { static implicit operator C(int i) @@ -430,14 +354,11 @@ static implicit operator C(int i) int i; } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); - } + """, 0, 2); [Fact] - public async Task Bug930292() - { - var file = """ + public Task Bug930292() + => AssertTagsOnBracesOrSemicolonsAsync(""" class Program { void A() { } @@ -445,14 +366,11 @@ void B() { } void C() { } void D() { } } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 4); - } + """, 4); [Fact] - public async Task Bug930289() - { - var file = """ + public Task Bug930289() + => AssertTagsOnBracesOrSemicolonsAsync(""" namespace Roslyn.Compilers.CSharp { internal struct ArrayElement @@ -462,14 +380,11 @@ internal struct ArrayElement public static implicit operator ArrayElement(T value) { return new ArrayElement(value); } } } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 6); - } + """, 6); [Fact] - public async Task TestConsoleApp() - { - var file = """ + public Task TestConsoleApp() + => AssertTagsOnBracesOrSemicolonsAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -480,14 +395,11 @@ static void Main(string[] args) { } } - """; - await AssertTagsOnBracesOrSemicolonsAsync(file, 2, 4); - } + """, 2, 4); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1297")] - public async Task ExpressionBodiedProperty() - { - await AssertTagsOnBracesOrSemicolonsAsync(""" + public Task ExpressionBodiedProperty() + => AssertTagsOnBracesOrSemicolonsAsync(""" class C { int Prop => 3; @@ -497,12 +409,10 @@ void M() } } """, 0, 2); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1297")] - public async Task ExpressionBodiedIndexer() - { - await AssertTagsOnBracesOrSemicolonsAsync(""" + public Task ExpressionBodiedIndexer() + => AssertTagsOnBracesOrSemicolonsAsync(""" class C { int this[int i] => 3; @@ -512,14 +422,10 @@ void M() } } """, 0, 2); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1297")] - public async Task ExpressionBodiedEvent() - { - // This is not valid code, and parses all wrong, but just in case a user writes it. Note - // the 3 is because there is a skipped } in the event declaration. - await AssertTagsOnBracesOrSemicolonsAsync(""" + public Task ExpressionBodiedEvent() + => AssertTagsOnBracesOrSemicolonsAsync(""" class C { event EventHandler MyEvent => 3; @@ -529,7 +435,6 @@ void M() } } """, 3); - } #region Negative (incomplete) tests @@ -570,11 +475,8 @@ public async Task IncompleteIndexer() } [Fact] - public async Task IncompleteOperator() - { - // top level operators not supported in script code - await AssertTagsOnBracesOrSemicolonsTokensAsync(@"C operator +(C lhs, C rhs) {", [], Options.Regular); - } + public Task IncompleteOperator() + => AssertTagsOnBracesOrSemicolonsTokensAsync(@"C operator +(C lhs, C rhs) {", [], Options.Regular); [Fact] public async Task IncompleteConversionOperator() diff --git a/src/EditorFeatures/CSharpTest/Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests.csproj b/src/EditorFeatures/CSharpTest/Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests.csproj index 772ec6dd70e8c..5032904cc765c 100644 --- a/src/EditorFeatures/CSharpTest/Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests.csproj +++ b/src/EditorFeatures/CSharpTest/Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests.csproj @@ -56,8 +56,5 @@ - - - diff --git a/src/EditorFeatures/CSharpTest/MoveToNamespace/MoveToNamespaceTests.cs b/src/EditorFeatures/CSharpTest/MoveToNamespace/MoveToNamespaceTests.cs index 9bd49914cde6a..6802398386b27 100644 --- a/src/EditorFeatures/CSharpTest/MoveToNamespace/MoveToNamespaceTests.cs +++ b/src/EditorFeatures/CSharpTest/MoveToNamespace/MoveToNamespaceTests.cs @@ -1101,7 +1101,7 @@ class MyClass4 } } """, - targetNamespace: "My.New.Namespace", + targetNamespace: "My.New.Namespace", expectedSymbolChanges: new Dictionary() { {"A.MyClass3", "My.New.Namespace.MyClass3" } @@ -1158,7 +1158,7 @@ class MyClass4 } } """, - targetNamespace: "B", + targetNamespace: "B", expectedSymbolChanges: new Dictionary() { {"A.B.C.MyClass3", "B.MyClass3" } @@ -1175,7 +1175,7 @@ class MyClass } } """, -expectedNamespaceName: "A.Complex.Namespace"); + expectedNamespaceName: "A.Complex.Namespace"); [Fact] public Task MoveToNamespace_Analysis_MoveType_ComplexNamespace() @@ -1311,11 +1311,8 @@ namespace {|Warning:A|} [Theory, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/980758")] [MemberData(nameof(SupportedKeywords))] - public async Task MoveToNamespace_MoveOnlyTypeToGlobalNamespace(string typeKeyword) - { - // We will not get "" as target namespace in VS, but the refactoring should be able - // to handle it w/o crashing. - await TestMoveToNamespaceAsync( + public Task MoveToNamespace_MoveOnlyTypeToGlobalNamespace(string typeKeyword) + => TestMoveToNamespaceAsync( $$""" namespace A { @@ -1333,7 +1330,6 @@ namespace A } """, targetNamespace: ""); - } [Theory, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/980758")] [MemberData(nameof(SupportedKeywords))] @@ -1422,23 +1418,6 @@ public class Class2[||] """; - - var expected = - """ - namespace A - { - public class Class1 - { - } - } - - namespace B - { - public class Class2 - { - } - } - """; using var workspace = EditorTestWorkspace.Create(System.Xml.Linq.XElement.Parse(input), composition: s_composition, openDocuments: false); // Set the target namespace to "B" @@ -1458,7 +1437,21 @@ public class Class2 var changedDocument = result.Item2.GetRequiredDocument(id); var changedRoot = await changedDocument.GetRequiredSyntaxRootAsync(CancellationToken.None); var actualText = changedRoot.ToFullString(); - AssertEx.Equal(expected, actualText); + AssertEx.Equal(""" + namespace A + { + public class Class1 + { + } + } + + namespace B + { + public class Class2 + { + } + } + """, actualText); } } diff --git a/src/EditorFeatures/CSharpTest/NavigateTo/NavigateToTests.cs b/src/EditorFeatures/CSharpTest/NavigateTo/NavigateToTests.cs index 2a757190cb0c6..e865d72f847dc 100644 --- a/src/EditorFeatures/CSharpTest/NavigateTo/NavigateToTests.cs +++ b/src/EditorFeatures/CSharpTest/NavigateTo/NavigateToTests.cs @@ -27,18 +27,15 @@ protected override EditorTestWorkspace CreateWorkspace(string content, TestCompo => EditorTestWorkspace.CreateCSharp(content, composition: composition); [Theory, CombinatorialData] - public async Task NoItemsForEmptyFile(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, "", async w => + public Task NoItemsForEmptyFile(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "", async w => { Assert.Empty(await _aggregator.GetItemsAsync("Hello")); }); - } [Theory, CombinatorialData] - public async Task FindClass(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindClass(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class Goo { @@ -48,12 +45,10 @@ class Goo var item = (await _aggregator.GetItemsAsync("Goo")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Goo", "[|Goo|]", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassInternal); }); - } [Theory, CombinatorialData] - public async Task FindRecord(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindRecord(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ record Goo { @@ -63,12 +58,10 @@ record Goo var item = (await _aggregator.GetItemsAsync("Goo")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Goo", "[|Goo|]", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassInternal); }); - } [Theory, CombinatorialData] - public async Task FindRecordClass(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindRecordClass(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ record class Goo { @@ -78,7 +71,6 @@ record class Goo var item = (await _aggregator.GetItemsAsync("Goo")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Goo", "[|Goo|]", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassInternal); }); - } [Theory, CombinatorialData] public async Task FindRecordStruct(TestHost testHost, Composition composition) @@ -122,9 +114,8 @@ await TestAsync(testHost, composition, content, async w => } [Theory, CombinatorialData] - public async Task FindVerbatimClass(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindVerbatimClass(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class @static { @@ -138,12 +129,10 @@ class @static item = (await _aggregator.GetItemsAsync("@static")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "static", "[|static|]", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassInternal); }); - } [Theory, CombinatorialData] - public async Task FindNestedClass(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindNestedClass(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class Goo { @@ -159,12 +148,10 @@ internal class DogBed var item = (await _aggregator.GetItemsAsync("DogBed")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "DogBed", "[|DogBed|]", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassInternal); }); - } [Theory, CombinatorialData] - public async Task FindMemberInANestedClass(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindMemberInANestedClass(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class Goo { @@ -183,12 +170,10 @@ public void Method() var item = (await _aggregator.GetItemsAsync("Method")).Single(); VerifyNavigateToResultItem(item, "Method", "[|Method|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPublic, string.Format(FeaturesResources.in_0_project_1, "Goo.Bar.DogBed", "Test")); }); - } [Theory, CombinatorialData] - public async Task FindGenericClassWithConstraints(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindGenericClassWithConstraints(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ using System.Collections; @@ -200,12 +185,10 @@ class Goo where T : IEnumerable var item = (await _aggregator.GetItemsAsync("Goo")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Goo", "[|Goo|]", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassInternal); }); - } [Theory, CombinatorialData] - public async Task FindGenericMethodWithConstraints(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindGenericMethodWithConstraints(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ using System; @@ -220,12 +203,10 @@ public void Bar(T item) where T : IComparable var item = (await _aggregator.GetItemsAsync("Bar")).Single(); VerifyNavigateToResultItem(item, "Bar", "[|Bar|](T)", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPublic, string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [Theory, CombinatorialData] - public async Task FindPartialClass(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindPartialClass(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ public partial class Goo { @@ -243,12 +224,10 @@ partial class Goo var expecteditem1 = new NavigateToItem("Goo", NavigateToItemKind.Class, "csharp", null, null, s_emptyExactPatternMatch, null); VerifyNavigateToResultItems([expecteditem1, expecteditem1], items); }); - } [Theory, CombinatorialData] - public async Task FindTypesInMetadata(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindTypesInMetadata(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ using System; @@ -258,12 +237,10 @@ await TestAsync( var items = await _aggregator.GetItemsAsync("FileStyleUriParser"); Assert.Equal(0, items.Count()); }); - } [Theory, CombinatorialData] - public async Task FindClassInNamespace(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindClassInNamespace(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ namespace Bar { @@ -276,12 +253,10 @@ class Goo var item = (await _aggregator.GetItemsAsync("Goo")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Goo", "[|Goo|]", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassInternal); }); - } [Theory, CombinatorialData] - public async Task FindStruct(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindStruct(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ struct Bar { @@ -291,12 +266,10 @@ struct Bar var item = (await _aggregator.GetItemsAsync("B")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Bar", "[|B|]ar", PatternMatchKind.Prefix, NavigateToItemKind.Structure, Glyph.StructureInternal); }); - } [Theory, CombinatorialData] - public async Task FindEnum(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindEnum(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ enum Colors { @@ -309,12 +282,10 @@ enum Colors var item = (await _aggregator.GetItemsAsync("Colors")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Colors", "[|Colors|]", PatternMatchKind.Exact, NavigateToItemKind.Enum, Glyph.EnumInternal); }); - } [Theory, CombinatorialData] - public async Task FindEnumMember(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindEnumMember(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ enum Colors { @@ -327,12 +298,10 @@ enum Colors var item = (await _aggregator.GetItemsAsync("R")).Single(); VerifyNavigateToResultItem(item, "Red", "[|R|]ed", PatternMatchKind.Prefix, NavigateToItemKind.EnumItem, Glyph.EnumMemberPublic); }); - } [Theory, CombinatorialData] - public async Task FindField1(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindField1(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class Goo { @@ -343,12 +312,10 @@ class Goo var item = (await _aggregator.GetItemsAsync("b")).Single(); VerifyNavigateToResultItem(item, "bar", "[|b|]ar", PatternMatchKind.Prefix, NavigateToItemKind.Field, Glyph.FieldPrivate, additionalInfo: string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [Theory, CombinatorialData] - public async Task FindField2(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindField2(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class Goo { @@ -359,12 +326,10 @@ class Goo var item = (await _aggregator.GetItemsAsync("ba")).Single(); VerifyNavigateToResultItem(item, "bar", "[|ba|]r", PatternMatchKind.Prefix, NavigateToItemKind.Field, Glyph.FieldPrivate, additionalInfo: string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [Theory, CombinatorialData] - public async Task FindField3(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindField3(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class Goo { @@ -374,12 +339,10 @@ class Goo { Assert.Empty(await _aggregator.GetItemsAsync("ar")); }); - } [Theory, CombinatorialData] - public async Task FindVerbatimField(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindVerbatimField(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class Goo { @@ -394,12 +357,10 @@ class Goo item = (await _aggregator.GetItemsAsync("@string")).Single(); VerifyNavigateToResultItem(item, "string", "[|string|]", PatternMatchKind.Exact, NavigateToItemKind.Field, Glyph.FieldPrivate, additionalInfo: string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [Theory, CombinatorialData] - public async Task FindPtrField1(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindPtrField1(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class Goo { @@ -409,12 +370,10 @@ class Goo { Assert.Empty(await _aggregator.GetItemsAsync("ar")); }); - } [Theory, CombinatorialData] - public async Task FindPtrField2(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindPtrField2(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class Goo { @@ -425,12 +384,10 @@ class Goo var item = (await _aggregator.GetItemsAsync("b")).Single(); VerifyNavigateToResultItem(item, "bar", "[|b|]ar", PatternMatchKind.Prefix, NavigateToItemKind.Field, Glyph.FieldPrivate); }); - } [Theory, CombinatorialData] - public async Task FindConstField(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindConstField(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class Goo { @@ -441,34 +398,26 @@ class Goo var item = (await _aggregator.GetItemsAsync("ba")).Single(); VerifyNavigateToResultItem(item, "bar", "[|ba|]r", PatternMatchKind.Prefix, NavigateToItemKind.Constant, Glyph.ConstantPrivate); }); - } [Theory, CombinatorialData] - public async Task FindIndexer(TestHost testHost, Composition composition) - { - var program = @"class Goo { int[] arr; public int this[int i] { get { return arr[i]; } set { arr[i] = value; } } }"; - await TestAsync(testHost, composition, program, async w => + public Task FindIndexer(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, @"class Goo { int[] arr; public int this[int i] { get { return arr[i]; } set { arr[i] = value; } } }", async w => { var item = (await _aggregator.GetItemsAsync("this")).Single(); VerifyNavigateToResultItem(item, "this", "[|this|][int]", PatternMatchKind.Exact, NavigateToItemKind.Property, Glyph.PropertyPublic, additionalInfo: string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [Theory, CombinatorialData] - public async Task FindEvent(TestHost testHost, Composition composition) - { - var program = "class Goo { public event EventHandler ChangedEventHandler; }"; - await TestAsync(testHost, composition, program, async w => + public Task FindEvent(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "class Goo { public event EventHandler ChangedEventHandler; }", async w => { var item = (await _aggregator.GetItemsAsync("CEH")).Single(); VerifyNavigateToResultItem(item, "ChangedEventHandler", "[|C|]hanged[|E|]vent[|H|]andler", PatternMatchKind.CamelCaseExact, NavigateToItemKind.Event, Glyph.EventPublic, additionalInfo: string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [Theory, CombinatorialData] - public async Task FindAutoProperty(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindAutoProperty(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class Goo { @@ -479,12 +428,10 @@ class Goo var item = (await _aggregator.GetItemsAsync("B")).Single(); VerifyNavigateToResultItem(item, "Bar", "[|B|]ar", PatternMatchKind.Prefix, NavigateToItemKind.Property, Glyph.PropertyPrivate, additionalInfo: string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [Theory, CombinatorialData] - public async Task FindMethod(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindMethod(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class Goo { @@ -495,12 +442,10 @@ class Goo var item = (await _aggregator.GetItemsAsync("DS")).Single(); VerifyNavigateToResultItem(item, "DoSomething", "[|D|]o[|S|]omething()", PatternMatchKind.CamelCaseExact, NavigateToItemKind.Method, Glyph.MethodPrivate, string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [Theory, CombinatorialData] - public async Task FindVerbatimMethod(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindVerbatimMethod(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class Goo { @@ -515,12 +460,10 @@ class Goo item = (await _aggregator.GetItemsAsync("@static")).Single(); VerifyNavigateToResultItem(item, "static", "[|static|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPrivate, string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [Theory, CombinatorialData] - public async Task FindParameterizedMethod(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindParameterizedMethod(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class Goo { @@ -533,12 +476,10 @@ void DoSomething(int a, string b) var item = (await _aggregator.GetItemsAsync("DS")).Single(); VerifyNavigateToResultItem(item, "DoSomething", "[|D|]o[|S|]omething(int, string)", PatternMatchKind.CamelCaseExact, NavigateToItemKind.Method, Glyph.MethodPrivate, string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [Theory, CombinatorialData] - public async Task FindConstructor(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindConstructor(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class Goo { @@ -551,12 +492,10 @@ public Goo() var item = (await _aggregator.GetItemsAsync("Goo")).Single(t => t.Kind == NavigateToItemKind.Method); VerifyNavigateToResultItem(item, "Goo", "[|Goo|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPublic, string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [Theory, CombinatorialData] - public async Task FindParameterizedConstructor(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindParameterizedConstructor(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class Goo { @@ -569,12 +508,10 @@ public Goo(int i) var item = (await _aggregator.GetItemsAsync("Goo")).Single(t => t.Kind == NavigateToItemKind.Method); VerifyNavigateToResultItem(item, "Goo", "[|Goo|](int)", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPublic, string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [Theory, CombinatorialData] - public async Task FindStaticConstructor(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindStaticConstructor(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class Goo { @@ -587,12 +524,10 @@ static Goo() var item = (await _aggregator.GetItemsAsync("Goo")).Single(t => t.Kind == NavigateToItemKind.Method && t.Name != ".ctor"); VerifyNavigateToResultItem(item, "Goo", "[|Goo|].static Goo()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPrivate, string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [Theory, CombinatorialData] - public async Task FindPartialMethods(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, "partial class Goo { partial void Bar(); } partial class Goo { partial void Bar() { Console.Write(\"hello\"); } }", async w => + public Task FindPartialMethods(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "partial class Goo { partial void Bar(); } partial class Goo { partial void Bar() { Console.Write(\"hello\"); } }", async w => { var expecteditem1 = new NavigateToItem("Bar", NavigateToItemKind.Method, "csharp", null, null, s_emptyExactPatternMatch, null); @@ -600,12 +535,10 @@ public async Task FindPartialMethods(TestHost testHost, Composition composition) VerifyNavigateToResultItems([expecteditem1, expecteditem1], items); }); - } [Theory, CombinatorialData] - public async Task FindPartialProperties(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, "partial class Goo { partial int Prop { get; set; } } partial class Goo { partial int Prop { get => 1; set { } } }", async w => + public Task FindPartialProperties(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "partial class Goo { partial int Prop { get; set; } } partial class Goo { partial int Prop { get => 1; set { } } }", async w => { var expecteditem1 = new NavigateToItem("Prop", NavigateToItemKind.Property, "csharp", null, null, s_emptyExactPatternMatch, null); @@ -613,12 +546,10 @@ public async Task FindPartialProperties(TestHost testHost, Composition compositi VerifyNavigateToResultItems([expecteditem1, expecteditem1], items); }); - } [Theory, CombinatorialData] - public async Task FindPartialEvents(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, """ + public Task FindPartialEvents(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ partial class C { partial event System.Action E; @@ -631,12 +562,10 @@ partial event System.Action E { add { } remove { } } VerifyNavigateToResultItems([expecteditem1, expecteditem1], items); }); - } [Theory, CombinatorialData] - public async Task FindPartialConstructors(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, """ + public Task FindPartialConstructors(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ partial class C { public partial C(); @@ -649,12 +578,10 @@ public partial C() { } VerifyNavigateToResultItems([expecteditem1, expecteditem1], items); }); - } [Theory, CombinatorialData] - public async Task FindPartialMethodDefinitionOnly(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindPartialMethodDefinitionOnly(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ partial class Goo { @@ -665,12 +592,10 @@ partial class Goo var item = (await _aggregator.GetItemsAsync("Bar")).Single(); VerifyNavigateToResultItem(item, "Bar", "[|Bar|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPrivate, string.Format(FeaturesResources.in_0_1_2, "Goo", "test1.cs", "Test")); }); - } [Theory, CombinatorialData] - public async Task FindPartialMethodImplementationOnly(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindPartialMethodImplementationOnly(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ partial class Goo { @@ -683,13 +608,10 @@ partial void Bar() var item = (await _aggregator.GetItemsAsync("Bar")).Single(); VerifyNavigateToResultItem(item, "Bar", "[|Bar|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPrivate, string.Format(FeaturesResources.in_0_1_2, "Goo", "test1.cs", "Test")); }); - } [Theory, CombinatorialData] - public async Task FindOverriddenMembers(TestHost testHost, Composition composition) - { - var program = "class Goo { public virtual string Name { get; set; } } class DogBed : Goo { public override string Name { get { return base.Name; } set {} } }"; - await TestAsync(testHost, composition, program, async w => + public Task FindOverriddenMembers(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "class Goo { public virtual string Name { get; set; } } class DogBed : Goo { public override string Name { get { return base.Name; } set {} } }", async w => { var expecteditem1 = new NavigateToItem("Name", NavigateToItemKind.Property, "csharp", null, null, s_emptyExactPatternMatch, null); @@ -711,12 +633,10 @@ await TestAsync(testHost, composition, program, async w => Assert.Equal("Name", itemDisplay.Name); Assert.Equal(string.Format(FeaturesResources.in_0_project_1, "Goo", "Test"), itemDisplay.AdditionalInformation); }); - } [Theory, CombinatorialData] - public async Task FindInterface(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindInterface(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ public interface IGoo { @@ -726,12 +646,10 @@ public interface IGoo var item = (await _aggregator.GetItemsAsync("IG")).Single(); VerifyNavigateToResultItem(item, "IGoo", "[|IG|]oo", PatternMatchKind.Prefix, NavigateToItemKind.Interface, Glyph.InterfacePublic); }); - } [Theory, CombinatorialData] - public async Task FindTopLevelLocalFunction(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindTopLevelLocalFunction(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ void Goo() { @@ -741,12 +659,10 @@ void Goo() var item = (await _aggregator.GetItemsAsync("Goo")).Single(); VerifyNavigateToResultItem(item, "Goo", "[|Goo|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPrivate); }); - } [Theory, CombinatorialData] - public async Task FindTopLevelLocalFunction_WithParameters(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindTopLevelLocalFunction_WithParameters(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ void Goo(int i) { @@ -756,12 +672,10 @@ void Goo(int i) var item = (await _aggregator.GetItemsAsync("Goo")).Single(); VerifyNavigateToResultItem(item, "Goo", "[|Goo|](int)", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPrivate); }); - } [Theory, CombinatorialData] - public async Task FindTopLevelLocalFunction_WithTypeArgumentsAndParameters(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindTopLevelLocalFunction_WithTypeArgumentsAndParameters(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ void Goo(int i) { @@ -771,12 +685,10 @@ void Goo(int i) var item = (await _aggregator.GetItemsAsync("Goo")).Single(); VerifyNavigateToResultItem(item, "Goo", "[|Goo|](int)", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPrivate); }); - } [Theory, CombinatorialData] - public async Task FindNestedLocalFunctionTopLevelStatements(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindNestedLocalFunctionTopLevelStatements(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ void Goo() { @@ -789,12 +701,10 @@ void Bar() var item = (await _aggregator.GetItemsAsync("Bar")).Single(); VerifyNavigateToResultItem(item, "Bar", "[|Bar|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPrivate); }); - } [Theory, CombinatorialData] - public async Task FindLocalFunctionInMethod(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindLocalFunctionInMethod(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class C { @@ -813,12 +723,10 @@ void Bar() var item = (await _aggregator.GetItemsAsync("Goo")).Single(); VerifyNavigateToResultItem(item, "Goo", "[|Goo|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPrivate); }); - } [Theory, CombinatorialData] - public async Task FindNestedLocalFunctionInMethod(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindNestedLocalFunctionInMethod(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class C { @@ -837,12 +745,10 @@ void Bar() var item = (await _aggregator.GetItemsAsync("Bar")).Single(); VerifyNavigateToResultItem(item, "Bar", "[|Bar|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPrivate); }); - } [Theory, CombinatorialData] - public async Task FindDelegateInNamespace(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindDelegateInNamespace(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ namespace Goo { @@ -853,12 +759,10 @@ namespace Goo var item = (await _aggregator.GetItemsAsync("DoStuff")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "DoStuff", "[|DoStuff|]", PatternMatchKind.Exact, NavigateToItemKind.Delegate, Glyph.DelegateInternal); }); - } [Theory, CombinatorialData] - public async Task FindLambdaExpression(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindLambdaExpression(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ using System; @@ -871,12 +775,10 @@ class Goo var item = (await _aggregator.GetItemsAsync("sqr")).Single(); VerifyNavigateToResultItem(item, "sqr", "[|sqr|]", PatternMatchKind.Exact, NavigateToItemKind.Field, Glyph.FieldPrivate, string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [Theory, CombinatorialData] - public async Task FindArray(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindArray(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class Goo { @@ -887,12 +789,10 @@ class Goo var item = (await _aggregator.GetItemsAsync("itemArray")).Single(); VerifyNavigateToResultItem(item, "itemArray", "[|itemArray|]", PatternMatchKind.Exact, NavigateToItemKind.Field, Glyph.FieldPrivate, string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [Theory, CombinatorialData] - public async Task FindClassAndMethodWithSameName(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindClassAndMethodWithSameName(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class Goo { @@ -911,12 +811,10 @@ void Goo() new("Goo", NavigateToItemKind.Class, "csharp", "Goo", null, s_emptyExactPatternMatch, null), new("Goo", NavigateToItemKind.Method, "csharp", "Goo", null, s_emptyExactPatternMatch, null)], items); }); - } [Theory, CombinatorialData] - public async Task FindMethodNestedInGenericTypes(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindMethodNestedInGenericTypes(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class A { @@ -935,12 +833,10 @@ void M() var item = (await _aggregator.GetItemsAsync("M")).Single(); VerifyNavigateToResultItem(item, "M", "[|M|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPrivate, additionalInfo: string.Format(FeaturesResources.in_0_project_1, "A.B.C", "Test")); }); - } [Theory, CombinatorialData] - public async Task OrderingOfConstructorsAndTypes(TestHost testHost, Composition composition) - { - await TestAsync( + public Task OrderingOfConstructorsAndTypes(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class C1 { @@ -970,12 +866,10 @@ static C2() new("C2", NavigateToItemKind.Method, "csharp", "C2", null, s_emptyPrefixPatternMatch, null), // this is the static ctor new("C2", NavigateToItemKind.Method, "csharp", "C2", null, s_emptyPrefixPatternMatch, null)], items); }); - } [Theory, CombinatorialData] - public async Task NavigateToMethodWithNullableParameter(TestHost testHost, Composition composition) - { - await TestAsync( + public Task NavigateToMethodWithNullableParameter(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class C { @@ -988,13 +882,10 @@ void M(object? o) var item = (await _aggregator.GetItemsAsync("M")).Single(); VerifyNavigateToResultItem(item, "M", "[|M|](object?)", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPrivate); }); - } [Theory, CombinatorialData] - public async Task StartStopSanity(TestHost testHost, Composition composition) - { - // Verify that multiple calls to start/stop and dispose don't blow up - await TestAsync( + public Task StartStopSanity(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ public class Goo { @@ -1012,12 +903,10 @@ public class Goo // Dispose the provider _provider.Dispose(); }); - } [Theory, CombinatorialData] - public async Task DescriptionItems(TestHost testHost, Composition composition) - { - await TestAsync(testHost, composition, """ + public Task DescriptionItems(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ public class Goo @@ -1039,13 +928,10 @@ void assertDescription(string label, string? value) assertDescription("Line:", "3"); // one based line number assertDescription("Project:", "Test"); }); - } [Theory, CombinatorialData] - public async Task TermSplittingTest1(TestHost testHost, Composition composition) - { - var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; - await TestAsync(testHost, composition, source, async w => + public Task TermSplittingTest1(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}", async w => { var expecteditem1 = new NavigateToItem("get_keyword", NavigateToItemKind.Field, "csharp", null, null, s_emptyCamelCaseNonContiguousPrefixPatternMatch_NotCaseSensitive, null); var expecteditem2 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, s_emptyCamelCaseNonContiguousPrefixPatternMatch_NotCaseSensitive, null); @@ -1055,13 +941,10 @@ await TestAsync(testHost, composition, source, async w => VerifyNavigateToResultItems([expecteditem1, expecteditem2, expecteditem3], items); }); - } [Theory, CombinatorialData] - public async Task TermSplittingTest2(TestHost testHost, Composition composition) - { - var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; - await TestAsync(testHost, composition, source, async w => + public Task TermSplittingTest2(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}", async w => { var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, s_emptyCamelCaseNonContiguousPrefixPatternMatch_NotCaseSensitive, null); var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, s_emptyCamelCaseExactPatternMatch, null); @@ -1070,13 +953,10 @@ await TestAsync(testHost, composition, source, async w => VerifyNavigateToResultItems([expecteditem1, expecteditem2], items); }); - } [Theory, CombinatorialData] - public async Task TermSplittingTest3(TestHost testHost, Composition composition) - { - var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; - await TestAsync(testHost, composition, source, async w => + public Task TermSplittingTest3(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}", async w => { var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, s_emptyCamelCaseSubstringPatternMatch_NotCaseSensitive, null); var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, s_emptySubstringPatternMatch, null); @@ -1085,35 +965,26 @@ await TestAsync(testHost, composition, source, async w => VerifyNavigateToResultItems([expecteditem1, expecteditem2], items); }); - } [Theory, CombinatorialData] - public async Task TermSplittingTest4(TestHost testHost, Composition composition) - { - var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; - await TestAsync(testHost, composition, source, async w => + public Task TermSplittingTest4(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}", async w => { var items = await _aggregator.GetItemsAsync("WKG"); Assert.Empty(items); }); - } [Theory, CombinatorialData] - public async Task TermSplittingTest5(TestHost testHost, Composition composition) - { - var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; - await TestAsync(testHost, composition, source, async w => + public Task TermSplittingTest5(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}", async w => { var item = (await _aggregator.GetItemsAsync("G_K_W")).Single(); VerifyNavigateToResultItem(item, "get_key_word", "[|g|]et[|_k|]ey[|_w|]ord", PatternMatchKind.CamelCaseExact, NavigateToItemKind.Field, Glyph.FieldPrivate); }); - } [Theory, CombinatorialData] - public async Task TermSplittingTest6(TestHost testHost, Composition composition) - { - var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; - await TestAsync(testHost, composition, source, async w => + public Task TermSplittingTest6(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}", async w => { var items = await _aggregator.GetItemsAsync("get word"); @@ -1123,24 +994,18 @@ await TestAsync(testHost, composition, source, async w => new("get_key_word", NavigateToItemKind.Field, "csharp", null, null,s_emptySubstringPatternMatch, null), new("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, s_emptySubstringPatternMatch_NotCaseSensitive, null)], items); }); - } [Theory, CombinatorialData] - public async Task TermSplittingTest7(TestHost testHost, Composition composition) - { - var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; - await TestAsync(testHost, composition, source, async w => + public Task TermSplittingTest7(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}", async w => { var items = await _aggregator.GetItemsAsync("GTW"); Assert.Empty(items); }); - } [Theory, CombinatorialData] - public async Task TestIndexer1(TestHost testHost, Composition composition) - { - var source = - """ + public Task TestIndexer1(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, """ class C { public int this[int y] { get { } } @@ -1154,106 +1019,81 @@ void Goo() var b = q[4]; } } - """; - await TestAsync(testHost, composition, source, async w => + """, async w => { var items = await _aggregator.GetItemsAsync("this"); VerifyNavigateToResultItems([new("this", NavigateToItemKind.Property, "csharp", null, null, s_emptyExactPatternMatch, null)], items); }); - } [Theory, CombinatorialData] - public async Task DottedPattern1(TestHost testHost, Composition composition) - { - var source = "namespace Goo { namespace Bar { class Baz { void Quux() { } } } }"; - await TestAsync(testHost, composition, source, async w => + public Task DottedPattern1(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "namespace Goo { namespace Bar { class Baz { void Quux() { } } } }", async w => { var items = await _aggregator.GetItemsAsync("B.Q"); VerifyNavigateToResultItems([new("Quux", NavigateToItemKind.Method, "csharp", null, null, s_emptyPrefixPatternMatch, null)], items); }); - } [Theory, CombinatorialData] - public async Task DottedPattern2(TestHost testHost, Composition composition) - { - var source = "namespace Goo { namespace Bar { class Baz { void Quux() { } } } }"; - await TestAsync(testHost, composition, source, async w => + public Task DottedPattern2(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "namespace Goo { namespace Bar { class Baz { void Quux() { } } } }", async w => { var items = await _aggregator.GetItemsAsync("C.Q"); VerifyNavigateToResultItems([], items); }); - } [Theory, CombinatorialData] - public async Task DottedPattern3(TestHost testHost, Composition composition) - { - var source = "namespace Goo { namespace Bar { class Baz { void Quux() { } } } }"; - await TestAsync(testHost, composition, source, async w => + public Task DottedPattern3(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "namespace Goo { namespace Bar { class Baz { void Quux() { } } } }", async w => { var items = await _aggregator.GetItemsAsync("B.B.Q"); VerifyNavigateToResultItems([new("Quux", NavigateToItemKind.Method, "csharp", null, null, s_emptyPrefixPatternMatch, null)], items); }); - } [Theory, CombinatorialData] - public async Task DottedPattern4(TestHost testHost, Composition composition) - { - var source = "namespace Goo { namespace Bar { class Baz { void Quux() { } } } }"; - await TestAsync(testHost, composition, source, async w => + public Task DottedPattern4(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "namespace Goo { namespace Bar { class Baz { void Quux() { } } } }", async w => { var items = await _aggregator.GetItemsAsync("Baz.Quux"); VerifyNavigateToResultItems([new("Quux", NavigateToItemKind.Method, "csharp", null, null, s_emptyExactPatternMatch, null)], items); }); - } [Theory, CombinatorialData] - public async Task DottedPattern5(TestHost testHost, Composition composition) - { - var source = "namespace Goo { namespace Bar { class Baz { void Quux() { } } } }"; - await TestAsync(testHost, composition, source, async w => + public Task DottedPattern5(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "namespace Goo { namespace Bar { class Baz { void Quux() { } } } }", async w => { var items = await _aggregator.GetItemsAsync("G.B.B.Quux"); VerifyNavigateToResultItems([new("Quux", NavigateToItemKind.Method, "csharp", null, null, s_emptyExactPatternMatch, null)], items); }); - } [Theory, CombinatorialData] - public async Task DottedPattern6(TestHost testHost, Composition composition) - { - var source = "namespace Goo { namespace Bar { class Baz { void Quux() { } } } }"; - await TestAsync(testHost, composition, source, async w => + public Task DottedPattern6(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "namespace Goo { namespace Bar { class Baz { void Quux() { } } } }", async w => { var items = await _aggregator.GetItemsAsync("F.F.B.B.Quux"); VerifyNavigateToResultItems([], items); }); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/Roslyn/issues/7855")] - public async Task DottedPattern7(TestHost testHost, Composition composition) - { - var source = "namespace Goo { namespace Bar { class Baz { void Quux() { } } } }"; - await TestAsync(testHost, composition, source, async w => + public Task DottedPattern7(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "namespace Goo { namespace Bar { class Baz { void Quux() { } } } }", async w => { var items = await _aggregator.GetItemsAsync("Baz.Q"); VerifyNavigateToResultItems([new("Quux", NavigateToItemKind.Method, "csharp", null, null, s_emptyPrefixPatternMatch, null)], items); }); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/46267")] [CombinatorialData] - public async Task DottedPatternMatchKind(TestHost testHost, Composition composition) - { - var source = "namespace System { class Console { void Write(string s) { } void WriteLine(string s) { } } }"; - await TestAsync(testHost, composition, source, async w => + public Task DottedPatternMatchKind(TestHost testHost, Composition composition) + => TestAsync(testHost, composition, "namespace System { class Console { void Write(string s) { } void WriteLine(string s) { } } }", async w => { var items = await _aggregator.GetItemsAsync("Console.Write"); @@ -1261,7 +1101,6 @@ await TestAsync(testHost, composition, source, async w => new("Write", NavigateToItemKind.Method, "csharp", null, null, s_emptyExactPatternMatch, null), new("WriteLine", NavigateToItemKind.Method, "csharp", null, null, s_emptyPrefixPatternMatch, null)], items); }); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174255")] [WorkItem("https://github.com/dotnet/roslyn/issues/8009")] @@ -1306,9 +1145,8 @@ public void VisibleMethod_Generated() { } [Theory, WorkItem("https://github.com/dotnet/roslyn/pull/11474")] [CombinatorialData] - public async Task FindFuzzy1(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindFuzzy1(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class C { @@ -1321,13 +1159,11 @@ public void ToError() var item = (await _aggregator.GetItemsAsync("ToEror")).Single(); VerifyNavigateToResultItem(item, "ToError", "ToError()", PatternMatchKind.Fuzzy, NavigateToItemKind.Method, Glyph.MethodPublic); }); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/18843")] [CombinatorialData] - public async Task Test__arglist(TestHost testHost, Composition composition) - { - await TestAsync( + public Task Test__arglist(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class C { @@ -1340,7 +1176,6 @@ public void ToError(__arglist) var item = (await _aggregator.GetItemsAsync("ToError")).Single(); VerifyNavigateToResultItem(item, "ToError", "[|ToError|](__arglist)", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPublic); }); - } [Fact] public async Task DoNotIncludeTrivialPartialContainer() @@ -1613,9 +1448,8 @@ public partial class C [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/59231")] - public async Task FindMethodWithTuple(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindMethodWithTuple(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ class Goo { @@ -1630,13 +1464,11 @@ public void Method( var item = (await _aggregator.GetItemsAsync("Method")).Single(); VerifyNavigateToResultItem(item, "Method", "[|Method|]((int x, Dictionary y), (bool b, global::System.Int32 c))", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPublic, string.Format(FeaturesResources.in_0_project_1, "Goo", "Test")); }); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/57873")] - public async Task FindRecordMember1(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindRecordMember1(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ record Goo(int Member) { @@ -1646,13 +1478,11 @@ record Goo(int Member) var item = (await _aggregator.GetItemsAsync("Member")).Single(x => x.Kind == NavigateToItemKind.Property); VerifyNavigateToResultItem(item, "Member", "[|Member|]", PatternMatchKind.Exact, NavigateToItemKind.Property, Glyph.PropertyPublic); }); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/57873")] - public async Task FindRecordMember2(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindRecordMember2(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ record Goo(int Member) { @@ -1663,13 +1493,11 @@ record Goo(int Member) var item = (await _aggregator.GetItemsAsync("Member")).Single(x => x.Kind == NavigateToItemKind.Property); VerifyNavigateToResultItem(item, "Member", "[|Member|]", PatternMatchKind.Exact, NavigateToItemKind.Property, Glyph.PropertyPublic); }); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/57873")] - public async Task FindRecordMember3(TestHost testHost, Composition composition) - { - await TestAsync( + public Task FindRecordMember3(TestHost testHost, Composition composition) + => TestAsync( testHost, composition, """ record Goo(int Member) { @@ -1680,7 +1508,6 @@ record Goo(int Member) var item = (await _aggregator.GetItemsAsync("Member")).Single(x => x.Kind == NavigateToItemKind.Field); VerifyNavigateToResultItem(item, "Member", "[|Member|]", PatternMatchKind.Exact, NavigateToItemKind.Field, Glyph.FieldPublic); }); - } private static bool IsFromFile(NavigateToItem item, string fileName) { @@ -1688,9 +1515,8 @@ private static bool IsFromFile(NavigateToItem item, string fileName) } [Theory, CombinatorialData] - public async Task NavigateToPrioritizeResultInCurrentDocument1(TestHost testHost) - { - await TestAsync(testHost, Composition.FirstActiveAndVisible, XElement.Parse(""" + public Task NavigateToPrioritizeResultInCurrentDocument1(TestHost testHost) + => TestAsync(testHost, Composition.FirstActiveAndVisible, XElement.Parse(""" @@ -1727,12 +1553,10 @@ public void VisibleMethod() { } Assert.Single(items, i => i.SecondarySort.StartsWith("0000") && IsFromFile(i, "File1.cs")); Assert.Single(items, i => i.SecondarySort.StartsWith("0001") && IsFromFile(i, "File2.cs")); }); - } [Theory, CombinatorialData] - public async Task NavigateToPrioritizeResultInCurrentDocument2(TestHost testHost) - { - await TestAsync(testHost, Composition.FirstActiveAndVisible, XElement.Parse(""" + public Task NavigateToPrioritizeResultInCurrentDocument2(TestHost testHost) + => TestAsync(testHost, Composition.FirstActiveAndVisible, XElement.Parse(""" @@ -1769,12 +1593,10 @@ public void VisibleMethod() { } Assert.Single(items, i => i.SecondarySort.StartsWith("0000") && IsFromFile(i, "File1.cs")); Assert.Single(items, i => i.SecondarySort.StartsWith("0001") && IsFromFile(i, "File2.cs")); }); - } [Theory, CombinatorialData] - public async Task NavigateToPrioritizeResultInCurrentDocument3(TestHost testHost) - { - await TestAsync(testHost, Composition.FirstActiveAndVisible, XElement.Parse(""" + public Task NavigateToPrioritizeResultInCurrentDocument3(TestHost testHost) + => TestAsync(testHost, Composition.FirstActiveAndVisible, XElement.Parse(""" @@ -1811,12 +1633,10 @@ public void VisibleMethod() { } Assert.Single(items, i => i.SecondarySort.StartsWith("0000") && IsFromFile(i, "File1.cs")); Assert.Single(items, i => i.SecondarySort.StartsWith("0002") && IsFromFile(i, "File2.cs")); }); - } [Theory, CombinatorialData] - public async Task NavigateToPrioritizeResultInCurrentDocument4(TestHost testHost) - { - await TestAsync(testHost, Composition.FirstActiveAndVisible, XElement.Parse(""" + public Task NavigateToPrioritizeResultInCurrentDocument4(TestHost testHost) + => TestAsync(testHost, Composition.FirstActiveAndVisible, XElement.Parse(""" @@ -1853,12 +1673,10 @@ public void VisibleMethod() { } Assert.Single(items, i => i.SecondarySort.StartsWith("0000") && IsFromFile(i, "File1.cs")); Assert.Single(items, i => i.SecondarySort.StartsWith("0002") && IsFromFile(i, "File2.cs")); }); - } [Theory, CombinatorialData] - public async Task NavigateToPrioritizeResultInCurrentDocument5(TestHost testHost) - { - await TestAsync(testHost, Composition.FirstActiveAndVisible, XElement.Parse(""" + public Task NavigateToPrioritizeResultInCurrentDocument5(TestHost testHost) + => TestAsync(testHost, Composition.FirstActiveAndVisible, XElement.Parse(""" @@ -1895,7 +1713,6 @@ public void VisibleMethod() { } Assert.Single(items, i => i.SecondarySort.StartsWith("0000") && IsFromFile(i, "File1.cs")); Assert.Single(items, i => i.SecondarySort.StartsWith("0003") && IsFromFile(i, "File2.cs")); }); - } [Theory, CombinatorialData] public async Task FindModernExtensionMethod1(TestHost testHost, Composition composition) diff --git a/src/EditorFeatures/CSharpTest/ObsoleteSymbol/CSharpObsoleteSymbolTests.cs b/src/EditorFeatures/CSharpTest/ObsoleteSymbol/CSharpObsoleteSymbolTests.cs index c6e9da1f4cfee..c2fc40c102216 100644 --- a/src/EditorFeatures/CSharpTest/ObsoleteSymbol/CSharpObsoleteSymbolTests.cs +++ b/src/EditorFeatures/CSharpTest/ObsoleteSymbol/CSharpObsoleteSymbolTests.cs @@ -22,9 +22,8 @@ protected override EditorTestWorkspace CreateWorkspace(string markup) [InlineData("record struct")] [InlineData("interface")] [InlineData("enum")] - public async Task TestObsoleteTypeDefinition(string keyword) - { - await TestAsync( + public Task TestObsoleteTypeDefinition(string keyword) + => TestAsync( $$""" [System.Obsolete] {{keyword}} [|ObsoleteType|] @@ -35,24 +34,20 @@ await TestAsync( { } """); - } [Fact] - public async Task TestObsoleteDelegateTypeDefinition() - { - await TestAsync( + public Task TestObsoleteDelegateTypeDefinition() + => TestAsync( """ [System.Obsolete] delegate void [|ObsoleteType|](); delegate void NonObsoleteType(); """); - } [Fact] - public async Task TestDeclarationAndUseOfObsoleteAlias() - { - await TestAsync( + public Task TestDeclarationAndUseOfObsoleteAlias() + => TestAsync( """ using [|ObsoleteAlias|] = [|ObsoleteType|]; @@ -66,12 +61,10 @@ class NonObsoleteType [|ObsoleteAlias|] field = new [|ObsoleteType|](); } """); - } [Fact] - public async Task TestParametersAndReturnTypes() - { - await TestAsync( + public Task TestParametersAndReturnTypes() + => TestAsync( """ [System.Obsolete] class [|ObsoleteType|]; @@ -83,12 +76,10 @@ class NonObsoleteType([|ObsoleteType|] field2) System.Func<[|ObsoleteType|], [|ObsoleteType|]> field = [|ObsoleteType|] ([|ObsoleteType|] arg) => [|new|](); } """); - } [Fact] - public async Task TestImplicitType() - { - await TestAsync( + public Task TestImplicitType() + => TestAsync( """ [System.Obsolete] class [|ObsoleteType|] @@ -128,12 +119,10 @@ void Method() } } """); - } [Fact] - public async Task TestExtensionMethods() - { - await TestAsync( + public Task TestExtensionMethods() + => TestAsync( """ [System.Obsolete] static class [|ObsoleteType|] @@ -155,12 +144,10 @@ void Method() } } """); - } [Fact] - public async Task TestGenerics() - { - await TestAsync( + public Task TestGenerics() + => TestAsync( """ [System.Obsolete] class [|ObsoleteType|]; @@ -196,5 +183,4 @@ void Method() } } """); - } } diff --git a/src/EditorFeatures/CSharpTest/Organizing/OrganizeModifiersTests.cs b/src/EditorFeatures/CSharpTest/Organizing/OrganizeModifiersTests.cs index ce76f4c9f213e..922dae524abc1 100644 --- a/src/EditorFeatures/CSharpTest/Organizing/OrganizeModifiersTests.cs +++ b/src/EditorFeatures/CSharpTest/Organizing/OrganizeModifiersTests.cs @@ -16,75 +16,60 @@ public sealed class OrganizeModifiersTests : AbstractOrganizerTests [Theory] [InlineData("class")] [InlineData("record")] - public async Task TestTypes1(string typeKind) - { - var initial = -$@"static public {typeKind} C {{ -}}"; - var final = -$@"public static {typeKind} C {{ -}}"; - - await CheckAsync(initial, final); - } + public Task TestTypes1(string typeKind) + => CheckAsync($$""" + static public {{typeKind}} C { + } + """, $$""" + public static {{typeKind}} C { + } + """); [Theory] [InlineData("class")] [InlineData("record")] - public async Task TestTypes2(string typeKind) - { - var initial = -$@"public static {typeKind} D {{ -}}"; - var final = -$@"public static {typeKind} D {{ -}}"; - - await CheckAsync(initial, final); - } + public Task TestTypes2(string typeKind) + => CheckAsync($$""" + public static {{typeKind}} D { + } + """, $$""" + public static {{typeKind}} D { + } + """); [Theory] [InlineData("class")] [InlineData("record")] - public async Task TestTypes3(string typeKind) - { - var initial = -$@"public static partial {typeKind} E {{ -}}"; - var final = -$@"public static partial {typeKind} E {{ -}}"; - - await CheckAsync(initial, final); - } + public Task TestTypes3(string typeKind) + => CheckAsync($$""" + public static partial {{typeKind}} E { + } + """, $$""" + public static partial {{typeKind}} E { + } + """); [Theory] [InlineData("class")] [InlineData("record")] - public async Task TestTypes4(string typeKind) - { - var initial = -$@"static public partial {typeKind} F {{ -}}"; - var final = -$@"public static partial {typeKind} F {{ -}}"; - - await CheckAsync(initial, final); - } + public Task TestTypes4(string typeKind) + => CheckAsync($$""" + static public partial {{typeKind}} F { + } + """, $$""" + public static partial {{typeKind}} F { + } + """); [Theory] [InlineData("class")] [InlineData("record")] - public async Task TestTypes5(string typeKind) - { - var initial = -$@"unsafe public static {typeKind} F {{ -}}"; - var final = -$@"public static unsafe {typeKind} F {{ -}}"; - - await CheckAsync(initial, final); - } + public Task TestTypes5(string typeKind) + => CheckAsync($$""" + unsafe public static {{typeKind}} F { + } + """, $$""" + public static unsafe {{typeKind}} F { + } + """); } diff --git a/src/EditorFeatures/CSharpTest/Organizing/OrganizeTypeDeclarationTests.cs b/src/EditorFeatures/CSharpTest/Organizing/OrganizeTypeDeclarationTests.cs index 9dee661af6a6b..965ed951c4f2a 100644 --- a/src/EditorFeatures/CSharpTest/Organizing/OrganizeTypeDeclarationTests.cs +++ b/src/EditorFeatures/CSharpTest/Organizing/OrganizeTypeDeclarationTests.cs @@ -25,23 +25,20 @@ public sealed class OrganizeTypeDeclarationTests : AbstractOrganizerTests [InlineData("record")] [InlineData("record class")] [InlineData("record struct")] - public async Task TestFieldsWithoutInitializers1(string typeKind) - { - var initial = -$@"{typeKind} C {{ - int A; - int B; - int C; -}}"; - - var final = -$@"{typeKind} C {{ - int A; - int B; - int C; -}}"; - await CheckAsync(initial, final); - } + public Task TestFieldsWithoutInitializers1(string typeKind) + => CheckAsync($$""" + {{typeKind}} C { + int A; + int B; + int C; + } + """, $$""" + {{typeKind}} C { + int A; + int B; + int C; + } + """); [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] @@ -49,1115 +46,1012 @@ public async Task TestFieldsWithoutInitializers1(string typeKind) [InlineData("record")] [InlineData("record class")] [InlineData("record struct")] - public async Task TestNestedTypes(string typeKind) - { - var initial = -$@"class C {{ - {typeKind} Nested1 {{ }} - {typeKind} Nested2 {{ }} - int A; -}}"; - - var final = -$@"class C {{ - int A; - {typeKind} Nested1 {{ }} - {typeKind} Nested2 {{ }} -}}"; - await CheckAsync(initial, final); - } + public Task TestNestedTypes(string typeKind) + => CheckAsync($$""" + class C { + {{typeKind}} Nested1 { } + {{typeKind}} Nested2 { } + int A; + } + """, $$""" + class C { + int A; + {{typeKind}} Nested1 { } + {{typeKind}} Nested2 { } + } + """); [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] - public async Task TestFieldsWithoutInitializers2(string typeKind) - { - var initial = -$@"{typeKind} C {{ - int C; - int B; - int A; -}}"; - - var final = -$@"{typeKind} C {{ - int A; - int B; - int C; -}}"; - await CheckAsync(initial, final); - } + public Task TestFieldsWithoutInitializers2(string typeKind) + => CheckAsync($$""" + {{typeKind}} C { + int C; + int B; + int A; + } + """, $$""" + {{typeKind}} C { + int A; + int B; + int C; + } + """); [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] [InlineData("record struct")] - public async Task TestFieldsWithInitializers1(string typeKind) - { - var initial = -$@"{typeKind} C {{ - int C = 0; - int B; - int A; -}}"; - - var final = -$@"{typeKind} C {{ - int A; - int B; - int C = 0; -}}"; - await CheckAsync(initial, final); - } + public Task TestFieldsWithInitializers1(string typeKind) + => CheckAsync($$""" + {{typeKind}} C { + int C = 0; + int B; + int A; + } + """, $$""" + {{typeKind}} C { + int A; + int B; + int C = 0; + } + """); [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] - public async Task TestFieldsWithInitializers2(string typeKind) - { - var initial = -$@"{typeKind} C {{ - int C = 0; - int B = 0; - int A; -}}"; - - var final = -$@"{typeKind} C {{ - int A; - int C = 0; - int B = 0; -}}"; - await CheckAsync(initial, final); - } + public Task TestFieldsWithInitializers2(string typeKind) + => CheckAsync($$""" + {{typeKind}} C { + int C = 0; + int B = 0; + int A; + } + """, $$""" + {{typeKind}} C { + int A; + int C = 0; + int B = 0; + } + """); [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] - public async Task TestEventFieldDeclaration(string typeKind) - { - var initial = -$@"{typeKind} C {{ - public void Goo() {{}} - public event EventHandler MyEvent; -}}"; - - var final = -$@"{typeKind} C {{ - public event EventHandler MyEvent; - public void Goo() {{}} -}}"; - await CheckAsync(initial, final); - } + public Task TestEventFieldDeclaration(string typeKind) + => CheckAsync($$""" + {{typeKind}} C { + public void Goo() {} + public event EventHandler MyEvent; + } + """, $$""" + {{typeKind}} C { + public event EventHandler MyEvent; + public void Goo() {} + } + """); [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] - public async Task TestEventDeclaration(string typeKind) - { - var initial = -$@"{typeKind} C {{ - public void Goo() {{}} - public event EventHandler Event - {{ - remove {{ }} - add {{ }} - }} - - public static int Property {{ get; set; }} -}}"; - - var final = -$@"{typeKind} C {{ - public static int Property {{ get; set; }} - public event EventHandler Event - {{ - remove {{ }} - add {{ }} - }} - - public void Goo() {{}} -}}"; - await CheckAsync(initial, final); - } + public Task TestEventDeclaration(string typeKind) + => CheckAsync($$""" + {{typeKind}} C { + public void Goo() {} + public event EventHandler Event + { + remove { } + add { } + } + + public static int Property { get; set; } + } + """, $$""" + {{typeKind}} C { + public static int Property { get; set; } + public event EventHandler Event + { + remove { } + add { } + } + + public void Goo() {} + } + """); [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] - public async Task TestOperator(string typeKind) - { - var initial = -$@"{typeKind} C {{ - public void Goo() {{}} - public static int operator +(Goo a, int b) - {{ - return 1; - }} -}}"; - - var final = -$@"{typeKind} C {{ - public static int operator +(Goo a, int b) - {{ - return 1; - }} - public void Goo() {{}} -}}"; - await CheckAsync(initial, final); - } + public Task TestOperator(string typeKind) + => CheckAsync($$""" + {{typeKind}} C { + public void Goo() {} + public static int operator +(Goo a, int b) + { + return 1; + } + } + """, $$""" + {{typeKind}} C { + public static int operator +(Goo a, int b) + { + return 1; + } + public void Goo() {} + } + """); [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] - public async Task TestIndexer(string typeKind) - { - var initial = -$@"{typeKind} C {{ - public void Goo() {{}} - public T this[int i] - {{ - get - {{ - return default(T); - }} - }} - - C() {{}} -}}"; - - var final = -$@"{typeKind} C {{ - C() {{}} - public T this[int i] - {{ - get - {{ - return default(T); - }} - }} - - public void Goo() {{}} -}}"; - await CheckAsync(initial, final); - } + public Task TestIndexer(string typeKind) + => CheckAsync($$""" + {{typeKind}} C { + public void Goo() {} + public T this[int i] + { + get + { + return default(T); + } + } + + C() {} + } + """, $$""" + {{typeKind}} C { + C() {} + public T this[int i] + { + get + { + return default(T); + } + } + + public void Goo() {} + } + """); [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] - public async Task TestConstructorAndDestructors(string typeKind) - { - var initial = -$@"{typeKind} C {{ - public ~Goo() {{}} - enum Days {{Sat, Sun}}; - public Goo() {{}} -}}"; - - var final = -$@"{typeKind} C {{ - public Goo() {{}} - public ~Goo() {{}} - enum Days {{Sat, Sun}}; -}}"; - await CheckAsync(initial, final); - } + public Task TestConstructorAndDestructors(string typeKind) + => CheckAsync($$""" + {{typeKind}} C { + public ~Goo() {} + enum Days {Sat, Sun}; + public Goo() {} + } + """, $$""" + {{typeKind}} C { + public Goo() {} + public ~Goo() {} + enum Days {Sat, Sun}; + } + """); [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] - public async Task TestInterface(string typeKind) - { - var initial = -$@"{typeKind} C {{}} -interface I -{{ - void Goo(); - int Property {{ get; set; }} - event EventHandler Event; -}}"; - - var final = -$@"{typeKind} C {{}} -interface I -{{ - event EventHandler Event; - int Property {{ get; set; }} - void Goo(); -}}"; - await CheckAsync(initial, final); - } + public Task TestInterface(string typeKind) + => CheckAsync($$""" + {{typeKind}} C {} + interface I + { + void Goo(); + int Property { get; set; } + event EventHandler Event; + } + """, $$""" + {{typeKind}} C {} + interface I + { + event EventHandler Event; + int Property { get; set; } + void Goo(); + } + """); [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] - public async Task TestStaticInstance(string typeKind) - { - var initial = -$@"{typeKind} C {{ - int A; - static int B; - int C; - static int D; -}}"; - - var final = -$@"{typeKind} C {{ - static int B; - static int D; - int A; - int C; -}}"; - await CheckAsync(initial, final); - } + public Task TestStaticInstance(string typeKind) + => CheckAsync($$""" + {{typeKind}} C { + int A; + static int B; + int C; + static int D; + } + """, $$""" + {{typeKind}} C { + static int B; + static int D; + int A; + int C; + } + """); [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] [InlineData("record struct")] - public async Task TestAccessibility(string typeKind) - { - var initial = -$@"{typeKind} C {{ - int A; - private int B; - internal int C; - protected int D; - public int E; - protected internal int F; -}}"; - - var final = -$@"{typeKind} C {{ - public int E; - protected int D; - protected internal int F; - internal int C; - int A; - private int B; -}}"; - await CheckAsync(initial, final); - } + public Task TestAccessibility(string typeKind) + => CheckAsync($$""" + {{typeKind}} C { + int A; + private int B; + internal int C; + protected int D; + public int E; + protected internal int F; + } + """, $$""" + {{typeKind}} C { + public int E; + protected int D; + protected internal int F; + internal int C; + int A; + private int B; + } + """); [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] - public async Task TestStaticAccessibility(string typeKind) - { - var initial = -$@"{typeKind} C {{ - int A1; - private int B1; - internal int C1; - protected int D1; - public int E1; - static int A2; - static private int B2; - static internal int C2; - static protected int D2; - static public int E2; -}}"; - - var final = -$@"{typeKind} C {{ - public static int E2; - protected static int D2; - internal static int C2; - static int A2; - private static int B2; - public int E1; - protected int D1; - internal int C1; - int A1; - private int B1; -}}"; - await CheckAsync(initial, final); - } + public Task TestStaticAccessibility(string typeKind) + => CheckAsync($$""" + {{typeKind}} C { + int A1; + private int B1; + internal int C1; + protected int D1; + public int E1; + static int A2; + static private int B2; + static internal int C2; + static protected int D2; + static public int E2; + } + """, $$""" + {{typeKind}} C { + public static int E2; + protected static int D2; + internal static int C2; + static int A2; + private static int B2; + public int E1; + protected int D1; + internal int C1; + int A1; + private int B1; + } + """); [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] - public async Task TestGenerics(string typeKind) - { - var initial = -$@"{typeKind} C {{ - void B(); - void B(); - void B(); - void A(); - void A(); - void A(); -}}"; - - var final = -$@"{typeKind} C {{ - void A(); - void A(); - void A(); - void B(); - void B(); - void B(); -}}"; - await CheckAsync(initial, final); - } + public Task TestGenerics(string typeKind) + => CheckAsync($$""" + {{typeKind}} C { + void B(); + void B(); + void B(); + void A(); + void A(); + void A(); + } + """, $$""" + {{typeKind}} C { + void A(); + void A(); + void A(); + void B(); + void B(); + void B(); + } + """); [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] - public async Task TestInsidePPRegion(string typeKind) - { - var initial = -$@"{typeKind} C {{ -#if true - int c; - int b; - int a; -#endif -}}"; - - var final = -$@"{typeKind} C {{ -#if true - int a; - int b; - int c; -#endif -}}"; - await CheckAsync(initial, final); - } + public Task TestInsidePPRegion(string typeKind) + => CheckAsync($$""" + {{typeKind}} C { + #if true + int c; + int b; + int a; + #endif + } + """, $$""" + {{typeKind}} C { + #if true + int a; + int b; + int c; + #endif + } + """); [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] - public async Task TestInsidePPRegion2(string typeKind) - { - var initial = -$@"{typeKind} C {{ -#if true - int z; - int y; - int x; -#endif -#if true - int c; - int b; - int a; -#endif -}}"; - - var final = -$@"{typeKind} C {{ -#if true - int x; - int y; - int z; -#endif -#if true - int a; - int b; - int c; -#endif -}}"; - await CheckAsync(initial, final); - } + public Task TestInsidePPRegion2(string typeKind) + => CheckAsync($$""" + {{typeKind}} C { + #if true + int z; + int y; + int x; + #endif + #if true + int c; + int b; + int a; + #endif + } + """, $$""" + {{typeKind}} C { + #if true + int x; + int y; + int z; + #endif + #if true + int a; + int b; + int c; + #endif + } + """); [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] - public async Task TestInsidePPRegion3(string typeKind) - { - var initial = -$@"{typeKind} C {{ - int z; - int y; -#if true - int x; - int c; -#endif - int b; - int a; -}}"; - - var final = -$@"{typeKind} C {{ - int y; - int z; -#if true - int c; - int x; -#endif - int a; - int b; -}}"; - await CheckAsync(initial, final); - } + public Task TestInsidePPRegion3(string typeKind) + => CheckAsync($$""" + {{typeKind}} C { + int z; + int y; + #if true + int x; + int c; + #endif + int b; + int a; + } + """, $$""" + {{typeKind}} C { + int y; + int z; + #if true + int c; + int x; + #endif + int a; + int b; + } + """); [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] - public async Task TestInsidePPRegion4(string typeKind) - { - var initial = -$@"{typeKind} C {{ - int c() {{ - }} - int b {{ - }} - int a {{ -#if true -#endif - }} -}}"; - - var final = -$@"{typeKind} C {{ - int a {{ -#if true -#endif - }} - int b {{ - }} - int c() {{ - }} -}}"; - await CheckAsync(initial, final); - } + public Task TestInsidePPRegion4(string typeKind) + => CheckAsync($$""" + {{typeKind}} C { + int c() { + } + int b { + } + int a { + #if true + #endif + } + } + """, $$""" + {{typeKind}} C { + int a { + #if true + #endif + } + int b { + } + int c() { + } + } + """); [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] - public async Task TestInsidePPRegion5(string typeKind) - { - var initial = -$@"{typeKind} C {{ - int c() {{ - }} - int b {{ - }} - int a {{ -#if true -#else -#endif - }} -}}"; - - var final = -$@"{typeKind} C {{ - int a {{ -#if true -#else -#endif - }} - int b {{ - }} - int c() {{ - }} -}}"; - await CheckAsync(initial, final); - } + public Task TestInsidePPRegion5(string typeKind) + => CheckAsync($$""" + {{typeKind}} C { + int c() { + } + int b { + } + int a { + #if true + #else + #endif + } + } + """, $$""" + {{typeKind}} C { + int a { + #if true + #else + #endif + } + int b { + } + int c() { + } + } + """); [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] - public async Task TestInsidePPRegion6(string typeKind) - { - var initial = -$@"{typeKind} C {{ -#region - int e() {{ - }} - int d() {{ - }} - int c() {{ -#region - }} -#endregion - int b {{ - }} - int a {{ - }} -#endregion -}}"; - - var final = -$@"{typeKind} C {{ -#region - int d() {{ - }} - int e() {{ - }} - int c() {{ -#region - }} -#endregion - int a {{ - }} - int b {{ - }} -#endregion -}}"; - await CheckAsync(initial, final); - } + public Task TestInsidePPRegion6(string typeKind) + => CheckAsync($$""" + {{typeKind}} C { + #region + int e() { + } + int d() { + } + int c() { + #region + } + #endregion + int b { + } + int a { + } + #endregion + } + """, $$""" + {{typeKind}} C { + #region + int d() { + } + int e() { + } + int c() { + #region + } + #endregion + int a { + } + int b { + } + #endregion + } + """); [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] - public async Task TestPinned(string typeKind) - { - var initial = -$@"{typeKind} C {{ - int z() {{ - }} - int y() {{ - }} - int x() {{ -#if true - }} - int n; - int m; - int c() {{ -#endif - }} - int b() {{ - }} - int a() {{ - }} -}}"; - - var final = -$@"{typeKind} C {{ - int y() {{ - }} - int z() {{ - }} - int x() {{ -#if true - }} - int m; - int n; - int c() {{ -#endif - }} - int a() {{ - }} - int b() {{ - }} -}}"; - await CheckAsync(initial, final); - } + public Task TestPinned(string typeKind) + => CheckAsync($$""" + {{typeKind}} C { + int z() { + } + int y() { + } + int x() { + #if true + } + int n; + int m; + int c() { + #endif + } + int b() { + } + int a() { + } + } + """, $$""" + {{typeKind}} C { + int y() { + } + int z() { + } + int x() { + #if true + } + int m; + int n; + int c() { + #endif + } + int a() { + } + int b() { + } + } + """); [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] - public async Task TestSensitivity(string typeKind) - { - var initial = -$@"{typeKind} C {{ - int Bb; - int B; - int bB; - int b; - int Aa; - int a; - int A; - int aa; - int aA; - int AA; - int bb; - int BB; - int bBb; - int bbB; - int あ; - int ア; - int ア; - int ああ; - int あア; - int あア; - int アあ; - int cC; - int Cc; - int アア; - int アア; - int アあ; - int アア; - int アア; - int BBb; - int BbB; - int bBB; - int BBB; - int c; - int C; - int bbb; - int Bbb; - int cc; - int cC; - int CC; -}}"; - - var final = -$@"{typeKind} C {{ - int a; - int A; - int aa; - int aA; - int Aa; - int AA; - int b; - int B; - int bb; - int bB; - int Bb; - int BB; - int bbb; - int bbB; - int bBb; - int bBB; - int Bbb; - int BbB; - int BBb; - int BBB; - int c; - int C; - int cc; - int cC; - int cC; - int Cc; - int CC; - int ア; - int ア; - int あ; - int アア; - int アア; - int アア; - int アア; - int アあ; - int アあ; - int あア; - int あア; - int ああ; -}}"; - - await CheckAsync(initial, final); - } + public Task TestSensitivity(string typeKind) + => CheckAsync($$""" + {{typeKind}} C { + int Bb; + int B; + int bB; + int b; + int Aa; + int a; + int A; + int aa; + int aA; + int AA; + int bb; + int BB; + int bBb; + int bbB; + int あ; + int ア; + int ア; + int ああ; + int あア; + int あア; + int アあ; + int cC; + int Cc; + int アア; + int アア; + int アあ; + int アア; + int アア; + int BBb; + int BbB; + int bBB; + int BBB; + int c; + int C; + int bbb; + int Bbb; + int cc; + int cC; + int CC; + } + """, $$""" + {{typeKind}} C { + int a; + int A; + int aa; + int aA; + int Aa; + int AA; + int b; + int B; + int bb; + int bB; + int Bb; + int BB; + int bbb; + int bbB; + int bBb; + int bBB; + int Bbb; + int BbB; + int BBb; + int BBB; + int c; + int C; + int cc; + int cC; + int cC; + int Cc; + int CC; + int ア; + int ア; + int あ; + int アア; + int アア; + int アア; + int アア; + int アあ; + int アあ; + int あア; + int あア; + int ああ; + } + """); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [InlineData("class")] [InlineData("record")] - public async Task TestWhitespaceBetweenMethods1(string typeKind) - { - var initial = -$@"{typeKind} Program -{{ - void B() - {{ - }} - - void A() - {{ - }} -}}"; - - var final = -$@"{typeKind} Program -{{ - void A() - {{ - }} - - void B() - {{ - }} -}}"; - await CheckAsync(initial, final); - } + public Task TestWhitespaceBetweenMethods1(string typeKind) + => CheckAsync($$""" + {{typeKind}} Program + { + void B() + { + } + + void A() + { + } + } + """, $$""" + {{typeKind}} Program + { + void A() + { + } + + void B() + { + } + } + """); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [InlineData("class")] [InlineData("record")] - public async Task TestWhitespaceBetweenMethods2(string typeKind) - { - var initial = -$@"{typeKind} Program -{{ - void B() - {{ - }} - - - void A() - {{ - }} -}}"; - - var final = -$@"{typeKind} Program -{{ - void A() - {{ - }} - - - void B() - {{ - }} -}}"; - await CheckAsync(initial, final); - } + public Task TestWhitespaceBetweenMethods2(string typeKind) + => CheckAsync($$""" + {{typeKind}} Program + { + void B() + { + } + + + void A() + { + } + } + """, $$""" + {{typeKind}} Program + { + void A() + { + } + + + void B() + { + } + } + """); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [InlineData("class")] [InlineData("record")] - public async Task TestWhitespaceBetweenMethods3(string typeKind) - { - var initial = -$@"{typeKind} Program -{{ - - void B() - {{ - }} - - void A() - {{ - }} -}}"; - - var final = -$@"{typeKind} Program -{{ - - void A() - {{ - }} - - void B() - {{ - }} -}}"; - await CheckAsync(initial, final); - } + public Task TestWhitespaceBetweenMethods3(string typeKind) + => CheckAsync($$""" + {{typeKind}} Program + { + + void B() + { + } + + void A() + { + } + } + """, $$""" + {{typeKind}} Program + { + + void A() + { + } + + void B() + { + } + } + """); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [InlineData("class")] [InlineData("record")] - public async Task TestWhitespaceBetweenMethods4(string typeKind) - { - var initial = -$@"{typeKind} Program -{{ + public Task TestWhitespaceBetweenMethods4(string typeKind) + => CheckAsync($$""" + {{typeKind}} Program + { - void B() - {{ - }} + void B() + { + } - void A() - {{ - }} -}}"; + void A() + { + } + } + """, $$""" + {{typeKind}} Program + { - var final = -$@"{typeKind} Program -{{ + void A() + { + } - void A() - {{ - }} - - void B() - {{ - }} -}}"; - await CheckAsync(initial, final); - } + void B() + { + } + } + """); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [InlineData("class")] [InlineData("record")] - public async Task TestWhitespaceBetweenMethods5(string typeKind) - { - var initial = -$@"{typeKind} Program -{{ + public Task TestWhitespaceBetweenMethods5(string typeKind) + => CheckAsync($$""" + {{typeKind}} Program + { - void B() - {{ - }} + void B() + { + } - void A() - {{ - }} -}}"; + void A() + { + } + } + """, $$""" + {{typeKind}} Program + { - var final = -$@"{typeKind} Program -{{ + void A() + { + } - void A() - {{ - }} - - void B() - {{ - }} -}}"; - await CheckAsync(initial, final); - } + void B() + { + } + } + """); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [InlineData("class")] [InlineData("record")] - public async Task TestWhitespaceBetweenMethods6(string typeKind) - { - var initial = -$@"{typeKind} Program -{{ + public Task TestWhitespaceBetweenMethods6(string typeKind) + => CheckAsync($$""" + {{typeKind}} Program + { - void B() - {{ - }} + void B() + { + } - void A() - {{ - }} -}}"; + void A() + { + } + } + """, $$""" + {{typeKind}} Program + { - var final = -$@"{typeKind} Program -{{ + void A() + { + } - void A() - {{ - }} - - void B() - {{ - }} -}}"; - await CheckAsync(initial, final); - } + void B() + { + } + } + """); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [InlineData("class")] [InlineData("record")] - public async Task TestMoveComments1(string typeKind) - { - var initial = -$@"{typeKind} Program -{{ - // B - void B() - {{ - }} - - void A() - {{ - }} -}}"; - - var final = -$@"{typeKind} Program -{{ - void A() - {{ - }} - - // B - void B() - {{ - }} -}}"; - await CheckAsync(initial, final); - } + public Task TestMoveComments1(string typeKind) + => CheckAsync($$""" + {{typeKind}} Program + { + // B + void B() + { + } + + void A() + { + } + } + """, $$""" + {{typeKind}} Program + { + void A() + { + } + + // B + void B() + { + } + } + """); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [InlineData("class")] [InlineData("record")] - public async Task TestMoveComments2(string typeKind) - { - var initial = -$@"{typeKind} Program -{{ - // B - void B() - {{ - }} - - // A - void A() - {{ - }} -}}"; - - var final = -$@"{typeKind} Program -{{ - // A - void A() - {{ - }} - - // B - void B() - {{ - }} -}}"; - await CheckAsync(initial, final); - } + public Task TestMoveComments2(string typeKind) + => CheckAsync($$""" + {{typeKind}} Program + { + // B + void B() + { + } + + // A + void A() + { + } + } + """, $$""" + {{typeKind}} Program + { + // A + void A() + { + } + + // B + void B() + { + } + } + """); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [InlineData("class")] [InlineData("record")] - public async Task TestMoveDocComments1(string typeKind) - { - var initial = -$@"{typeKind} Program -{{ - /// B - void B() - {{ - }} - - void A() - {{ - }} -}}"; - - var final = -$@"{typeKind} Program -{{ - void A() - {{ - }} - - /// B - void B() - {{ - }} -}}"; - await CheckAsync(initial, final); - } + public Task TestMoveDocComments1(string typeKind) + => CheckAsync($$""" + {{typeKind}} Program + { + /// B + void B() + { + } + + void A() + { + } + } + """, $$""" + {{typeKind}} Program + { + void A() + { + } + + /// B + void B() + { + } + } + """); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [InlineData("class")] [InlineData("record")] - public async Task TestMoveDocComments2(string typeKind) - { - var initial = -$@"{typeKind} Program -{{ - /// B - - void B() - {{ - }} - - void A() - {{ - }} -}}"; - - var final = -$@"{typeKind} Program -{{ - void A() - {{ - }} - - /// B - - void B() - {{ - }} -}}"; - await CheckAsync(initial, final); - } + public Task TestMoveDocComments2(string typeKind) + => CheckAsync($$""" + {{typeKind}} Program + { + /// B + + void B() + { + } + + void A() + { + } + } + """, $$""" + {{typeKind}} Program + { + void A() + { + } + + /// B + + void B() + { + } + } + """); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [InlineData("class")] [InlineData("record")] - public async Task TestDoNotMoveBanner(string typeKind) - { - var initial = -$@"{typeKind} Program -{{ - // Banner - - void B() - {{ - }} - - void A() - {{ - }} -}}"; - - var final = -$@"{typeKind} Program -{{ - // Banner - - void A() - {{ - }} - - void B() - {{ - }} -}}"; - await CheckAsync(initial, final); - } + public Task TestDoNotMoveBanner(string typeKind) + => CheckAsync($$""" + {{typeKind}} Program + { + // Banner + + void B() + { + } + + void A() + { + } + } + """, $$""" + {{typeKind}} Program + { + // Banner + + void A() + { + } + + void B() + { + } + } + """); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [InlineData("class")] [InlineData("record")] - public async Task TestDoNotMoveBanner2(string typeKind) - { - var initial = -$@"{typeKind} Program -{{ - // Banner - - // More banner - // Bannery stuff - - void B() - {{ - }} - - void A() - {{ - }} -}}"; - - var final = -$@"{typeKind} Program -{{ - // Banner - - // More banner - // Bannery stuff - - void A() - {{ - }} - - void B() - {{ - }} -}}"; - await CheckAsync(initial, final); - } + public Task TestDoNotMoveBanner2(string typeKind) + => CheckAsync($$""" + {{typeKind}} Program + { + // Banner + + // More banner + // Bannery stuff + + void B() + { + } + + void A() + { + } + } + """, $$""" + {{typeKind}} Program + { + // Banner + + // More banner + // Bannery stuff + + void A() + { + } + + void B() + { + } + } + """); [WpfFact] [Trait(Traits.Feature, Traits.Features.Organizing)] diff --git a/src/EditorFeatures/CSharpTest/PdbSourceDocument/AbstractPdbSourceDocumentTests.cs b/src/EditorFeatures/CSharpTest/PdbSourceDocument/AbstractPdbSourceDocumentTests.cs index be856e088e40f..4c5a43ef7d606 100644 --- a/src/EditorFeatures/CSharpTest/PdbSourceDocument/AbstractPdbSourceDocumentTests.cs +++ b/src/EditorFeatures/CSharpTest/PdbSourceDocument/AbstractPdbSourceDocumentTests.cs @@ -211,14 +211,17 @@ protected static async Task GenerateFileAndVerifyAsync( Encoding? fallbackEncoding = null) { var preprocessorSymbolsAttribute = preprocessorSymbols?.Length > 0 - ? $"PreprocessorSymbols=\"{string.Join(";", preprocessorSymbols)}\"" + ? $""" + PreprocessorSymbols="{string.Join(";", preprocessorSymbols)}" + """ : ""; - var workspace = EditorTestWorkspace.Create(@$" - - - -", composition: GetTestComposition()); + var workspace = EditorTestWorkspace.Create($""" + + + + + """, composition: GetTestComposition()); var project = workspace.CurrentSolution.Projects.First(); @@ -250,9 +253,7 @@ protected static void CompileTestSource(string path, SourceText source, Project var dllFilePath = GetDllPath(path); var sourceCodePath = GetSourceFilePath(path); var pdbFilePath = GetPdbPath(path); - var assemblyName = "reference"; - - CompileTestSource(dllFilePath, sourceCodePath, pdbFilePath, assemblyName, source, project, pdbLocation, sourceLocation, buildReferenceAssembly, windowsPdb, fallbackEncoding); + CompileTestSource(dllFilePath, sourceCodePath, pdbFilePath, "reference", source, project, pdbLocation, sourceLocation, buildReferenceAssembly, windowsPdb, fallbackEncoding); } protected static void CompileTestSource(string dllFilePath, string sourceCodePath, string? pdbFilePath, string assemblyName, SourceText source, Project project, Location pdbLocation, Location sourceLocation, bool buildReferenceAssembly, bool windowsPdb, Encoding? fallbackEncoding = null) diff --git a/src/EditorFeatures/CSharpTest/PdbSourceDocument/ImplementationAssemblyLookupServiceTests.cs b/src/EditorFeatures/CSharpTest/PdbSourceDocument/ImplementationAssemblyLookupServiceTests.cs index 3afd7da360834..376d2c614bbe0 100644 --- a/src/EditorFeatures/CSharpTest/PdbSourceDocument/ImplementationAssemblyLookupServiceTests.cs +++ b/src/EditorFeatures/CSharpTest/PdbSourceDocument/ImplementationAssemblyLookupServiceTests.cs @@ -13,7 +13,6 @@ using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; -using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.PdbSourceDocument; @@ -21,19 +20,16 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.PdbSourceDocument; public sealed class ImplementationAssemblyLookupServiceTests : AbstractPdbSourceDocumentTests { [Fact] - public async Task Net6SdkLayout_InvalidXml() - { - var source = """ + public Task Net6SdkLayout_InvalidXml() + => RunTestAsync(async path => + { + MarkupTestFile.GetSpan(""" public class C { // A change public event System.EventHandler [|E|] { add { } remove { } } } - """; - - await RunTestAsync(async path => - { - MarkupTestFile.GetSpan(source, out var metadataSource, out var expectedSpan); + """, out var metadataSource, out var expectedSpan); var packDir = Directory.CreateDirectory(Path.Combine(path, "packs", "MyPack.Ref", "1.0", "ref", "net6.0")).FullName; var dataDir = Directory.CreateDirectory(Path.Combine(path, "packs", "MyPack.Ref", "1.0", "data")).FullName; @@ -56,22 +52,18 @@ await RunTestAsync(async path => Assert.False(service.TryFindImplementationAssemblyPath(GetDllPath(packDir), out var implementationDll)); }); - } [Fact] - public async Task Net6SdkLayout() - { - var source = """ + public Task Net6SdkLayout() + => RunTestAsync(async path => + { + MarkupTestFile.GetSpan(""" public class C { // A change public event System.EventHandler [|E|] { add { } remove { } } } - """; - - await RunTestAsync(async path => - { - MarkupTestFile.GetSpan(source, out var metadataSource, out var expectedSpan); + """, out var metadataSource, out var expectedSpan); var packDir = Directory.CreateDirectory(Path.Combine(path, "packs", "MyPack.Ref", "1.0", "ref", "net6.0")).FullName; var dataDir = Directory.CreateDirectory(Path.Combine(path, "packs", "MyPack.Ref", "1.0", "data")).FullName; @@ -96,22 +88,18 @@ await RunTestAsync(async path => Assert.True(service.TryFindImplementationAssemblyPath(GetDllPath(packDir), out var implementationDll)); Assert.Equal(GetDllPath(sharedDir), implementationDll); }); - } [Fact] - public async Task Net6SdkLayout_PacksInPath() - { - var source = """ + public Task Net6SdkLayout_PacksInPath() + => RunTestAsync(async path => + { + MarkupTestFile.GetSpan(""" public class C { // A change public event System.EventHandler [|E|] { add { } remove { } } } - """; - - await RunTestAsync(async path => - { - MarkupTestFile.GetSpan(source, out var metadataSource, out var expectedSpan); + """, out var metadataSource, out var expectedSpan); path = Path.Combine(path, "packs", "installed", "here"); @@ -138,34 +126,28 @@ await RunTestAsync(async path => Assert.True(service.TryFindImplementationAssemblyPath(GetDllPath(packDir), out var implementationDll)); Assert.Equal(GetDllPath(sharedDir), implementationDll); }); - } [Fact] - public async Task FollowTypeForwards() - { - var source = """ + public Task FollowTypeForwards() + => RunTestAsync(async path => + { + MarkupTestFile.GetSpan(""" public class C { // A change public event System.EventHandler [|E|] { add { } remove { } } } - """; - var typeForwardSource = """ - [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))] - """; - - await RunTestAsync(async path => - { - MarkupTestFile.GetSpan(source, out var metadataSource, out var expectedSpan); + """, out var metadataSource, out var expectedSpan); var sourceText = SourceText.From(metadataSource, Encoding.UTF8); var (project, symbol) = await CompileAndFindSymbolAsync(path, Location.Embedded, Location.Embedded, sourceText, c => c.GetMember("C.E"), buildReferenceAssembly: true); - var workspace = EditorTestWorkspace.Create(@$" - - - -", composition: GetTestComposition()); + var workspace = EditorTestWorkspace.Create($""" + + + + + """, composition: GetTestComposition()); var implProject = workspace.CurrentSolution.Projects.First(); @@ -182,19 +164,21 @@ await RunTestAsync(async path => assemblyName = "typeforward"; implProject = implProject.AddMetadataReference(MetadataReference.CreateFromFile(dllFilePath)); - sourceText = SourceText.From(typeForwardSource, Encoding.UTF8); + sourceText = SourceText.From(""" + [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))] + """, Encoding.UTF8); CompileTestSource(typeForwardDllFilePath, sourceCodePath, pdbFilePath, assemblyName, sourceText, implProject, Location.Embedded, Location.Embedded, buildReferenceAssembly: false, windowsPdb: false); var service = workspace.GetService(); Assert.Equal(dllFilePath, service.FollowTypeForwards(symbol, typeForwardDllFilePath, new NoDuplicatesLogger())); }); - } [Fact] - public async Task FollowTypeForwards_Namespace() - { - var source = """ + public Task FollowTypeForwards_Namespace() + => RunTestAsync(async path => + { + MarkupTestFile.GetSpan(""" namespace A { namespace B @@ -209,14 +193,7 @@ public event System.EventHandler [|E|] { add { } remove { } } } } } - """; - var typeForwardSource = """ - [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(A.B.C))] - """; - - await RunTestAsync(async path => - { - MarkupTestFile.GetSpan(source, out var metadataSource, out var expectedSpan); + """, out var metadataSource, out var expectedSpan); // Compile reference assembly var sourceText = SourceText.From(metadataSource, encoding: Encoding.UTF8); @@ -228,11 +205,12 @@ await RunTestAsync(async path => var pdbFilePath = Path.Combine(path, "implementation.pdb"); var assemblyName = "implementation"; - var workspace = EditorTestWorkspace.Create(@$" - - - -", composition: GetTestComposition()); + var workspace = EditorTestWorkspace.Create($""" + + + + + """, composition: GetTestComposition()); var implProject = workspace.CurrentSolution.Projects.First(); CompileTestSource(dllFilePath, sourceCodePath, pdbFilePath, assemblyName, sourceText, implProject, Location.Embedded, Location.Embedded, buildReferenceAssembly: false, windowsPdb: false); @@ -242,7 +220,9 @@ await RunTestAsync(async path => assemblyName = "typeforward"; implProject = implProject.AddMetadataReference(MetadataReference.CreateFromFile(dllFilePath)); - sourceText = SourceText.From(typeForwardSource, Encoding.UTF8); + sourceText = SourceText.From(""" + [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(A.B.C))] + """, Encoding.UTF8); CompileTestSource(typeForwardDllFilePath, sourceCodePath, pdbFilePath, assemblyName, sourceText, implProject, Location.Embedded, Location.Embedded, buildReferenceAssembly: false, windowsPdb: false); var service = workspace.GetService(); @@ -250,12 +230,12 @@ await RunTestAsync(async path => var foundImplementationFilePath = service.FollowTypeForwards(symbol, typeForwardDllFilePath, new NoDuplicatesLogger()); Assert.Equal(dllFilePath, foundImplementationFilePath); }); - } [Fact] - public async Task FollowTypeForwards_Generics() - { - var source = """ + public Task FollowTypeForwards_Generics() + => RunTestAsync(async path => + { + MarkupTestFile.GetSpan(""" namespace A { namespace B @@ -270,14 +250,7 @@ public event System.EventHandler [|E|] { add { } remove { } } } } } - """; - var typeForwardSource = """ - [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(A.B.C<>))] - """; - - await RunTestAsync(async path => - { - MarkupTestFile.GetSpan(source, out var metadataSource, out var expectedSpan); + """, out var metadataSource, out var expectedSpan); // Compile reference assembly var sourceText = SourceText.From(metadataSource, encoding: Encoding.UTF8); @@ -289,11 +262,12 @@ await RunTestAsync(async path => var pdbFilePath = Path.Combine(path, "implementation.pdb"); var assemblyName = "implementation"; - var workspace = EditorTestWorkspace.Create(@$" - - - -", composition: GetTestComposition()); + var workspace = EditorTestWorkspace.Create($""" + + + + + """, composition: GetTestComposition()); var implProject = workspace.CurrentSolution.Projects.First(); CompileTestSource(dllFilePath, sourceCodePath, pdbFilePath, assemblyName, sourceText, implProject, Location.Embedded, Location.Embedded, buildReferenceAssembly: false, windowsPdb: false); @@ -303,7 +277,9 @@ await RunTestAsync(async path => assemblyName = "typeforward"; implProject = implProject.AddMetadataReference(MetadataReference.CreateFromFile(dllFilePath)); - sourceText = SourceText.From(typeForwardSource, Encoding.UTF8); + sourceText = SourceText.From(""" + [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(A.B.C<>))] + """, Encoding.UTF8); CompileTestSource(typeForwardDllFilePath, sourceCodePath, pdbFilePath, assemblyName, sourceText, implProject, Location.Embedded, Location.Embedded, buildReferenceAssembly: false, windowsPdb: false); var service = workspace.GetService(); @@ -311,12 +287,12 @@ await RunTestAsync(async path => var foundImplementationFilePath = service.FollowTypeForwards(symbol, typeForwardDllFilePath, new NoDuplicatesLogger()); Assert.Equal(dllFilePath, foundImplementationFilePath); }); - } [Fact] - public async Task FollowTypeForwards_NestedType() - { - var source = """ + public Task FollowTypeForwards_NestedType() + => RunTestAsync(async path => + { + MarkupTestFile.GetSpan(""" public class C { public class D @@ -325,14 +301,7 @@ public class D public event System.EventHandler [|E|] { add { } remove { } } } } - """; - var typeForwardSource = """ - [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))] - """; - - await RunTestAsync(async path => - { - MarkupTestFile.GetSpan(source, out var metadataSource, out var expectedSpan); + """, out var metadataSource, out var expectedSpan); // Compile reference assembly var sourceText = SourceText.From(metadataSource, encoding: Encoding.UTF8); @@ -344,11 +313,12 @@ await RunTestAsync(async path => var pdbFilePath = Path.Combine(path, "implementation.pdb"); var assemblyName = "implementation"; - var workspace = EditorTestWorkspace.Create(@$" - - - -", composition: GetTestComposition()); + var workspace = EditorTestWorkspace.Create($""" + + + + + """, composition: GetTestComposition()); var implProject = workspace.CurrentSolution.Projects.First(); CompileTestSource(dllFilePath, sourceCodePath, pdbFilePath, assemblyName, sourceText, implProject, Location.Embedded, Location.Embedded, buildReferenceAssembly: false, windowsPdb: false); @@ -358,32 +328,27 @@ await RunTestAsync(async path => assemblyName = "typeforward"; implProject = implProject.AddMetadataReference(MetadataReference.CreateFromFile(dllFilePath)); - sourceText = SourceText.From(typeForwardSource, Encoding.UTF8); + sourceText = SourceText.From(""" + [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))] + """, Encoding.UTF8); CompileTestSource(typeForwardDllFilePath, sourceCodePath, pdbFilePath, assemblyName, sourceText, implProject, Location.Embedded, Location.Embedded, buildReferenceAssembly: false, windowsPdb: false); var service = workspace.GetService(); Assert.Equal(dllFilePath, service.FollowTypeForwards(symbol, typeForwardDllFilePath, new NoDuplicatesLogger())); }); - } [Fact] - public async Task FollowTypeForwards_Cache() - { - var source = """ + public Task FollowTypeForwards_Cache() + => RunTestAsync(async path => + { + MarkupTestFile.GetSpan(""" public class C { // A change public event System.EventHandler [|E|] { add { } remove { } } } - """; - var typeForwardSource = """ - [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))] - """; - - await RunTestAsync(async path => - { - MarkupTestFile.GetSpan(source, out var metadataSource, out var expectedSpan); + """, out var metadataSource, out var expectedSpan); // Compile reference assembly var sourceText = SourceText.From(metadataSource, encoding: Encoding.UTF8); @@ -395,11 +360,12 @@ await RunTestAsync(async path => var pdbFilePath = Path.Combine(path, "implementation.pdb"); var assemblyName = "implementation"; - var workspace = EditorTestWorkspace.Create(@$" - - - -", composition: GetTestComposition()); + var workspace = EditorTestWorkspace.Create($""" + + + + + """, composition: GetTestComposition()); var implProject = workspace.CurrentSolution.Projects.First(); CompileTestSource(dllFilePath, sourceCodePath, pdbFilePath, assemblyName, sourceText, implProject, Location.Embedded, Location.Embedded, buildReferenceAssembly: false, windowsPdb: false); @@ -409,7 +375,9 @@ await RunTestAsync(async path => assemblyName = "typeforward"; implProject = implProject.AddMetadataReference(MetadataReference.CreateFromFile(dllFilePath)); - sourceText = SourceText.From(typeForwardSource, Encoding.UTF8); + sourceText = SourceText.From(""" + [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))] + """, Encoding.UTF8); CompileTestSource(typeForwardDllFilePath, sourceCodePath, pdbFilePath, assemblyName, sourceText, implProject, Location.Embedded, Location.Embedded, buildReferenceAssembly: false, windowsPdb: false); var service = workspace.GetService(); @@ -423,12 +391,12 @@ await RunTestAsync(async path => Assert.Equal(dllFilePath, service.FollowTypeForwards(symbol, typeForwardDllFilePath, new NoDuplicatesLogger())); }); - } [Fact] - public async Task FollowTypeForwards_MultipleTypes_Cache() - { - var source = """ + public Task FollowTypeForwards_MultipleTypes_Cache() + => RunTestAsync(async path => + { + MarkupTestFile.GetSpan(""" public class C { // A change @@ -438,17 +406,7 @@ public event System.EventHandler [|E|] { add { } remove { } } public class D { } public class E { } public class F { } - """; - var typeForwardSource = """ - [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))] - [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(D))] - [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(E))] - [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(F))] - """; - - await RunTestAsync(async path => - { - MarkupTestFile.GetSpan(source, out var metadataSource, out var expectedSpan); + """, out var metadataSource, out var expectedSpan); // Compile reference assembly var sourceText = SourceText.From(metadataSource, encoding: Encoding.UTF8); @@ -460,11 +418,12 @@ await RunTestAsync(async path => var pdbFilePath = Path.Combine(path, "implementation.pdb"); var assemblyName = "implementation"; - var workspace = EditorTestWorkspace.Create(@$" - - - -", composition: GetTestComposition()); + var workspace = EditorTestWorkspace.Create($""" + + + + + """, composition: GetTestComposition()); var implProject = workspace.CurrentSolution.Projects.First(); CompileTestSource(dllFilePath, sourceCodePath, pdbFilePath, assemblyName, sourceText, implProject, Location.Embedded, Location.Embedded, buildReferenceAssembly: false, windowsPdb: false); @@ -474,7 +433,12 @@ await RunTestAsync(async path => assemblyName = "typeforward"; implProject = implProject.AddMetadataReference(MetadataReference.CreateFromFile(dllFilePath)); - sourceText = SourceText.From(typeForwardSource, Encoding.UTF8); + sourceText = SourceText.From(""" + [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))] + [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(D))] + [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(E))] + [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(F))] + """, Encoding.UTF8); CompileTestSource(typeForwardDllFilePath, sourceCodePath, pdbFilePath, assemblyName, sourceText, implProject, Location.Embedded, Location.Embedded, buildReferenceAssembly: false, windowsPdb: false); var service = workspace.GetService(); @@ -488,25 +452,23 @@ await RunTestAsync(async path => Assert.Equal(dllFilePath, service.FollowTypeForwards(symbol, typeForwardDllFilePath, new NoDuplicatesLogger())); }); - } [Fact] public async Task FollowTypeForwards_MultipleHops_Cache() { - var source = """ - public class C - { - // A change - public event System.EventHandler [|E|] { add { } remove { } } - } - """; var typeForwardSource = """ [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))] """; await RunTestAsync(async path => { - MarkupTestFile.GetSpan(source, out var metadataSource, out var expectedSpan); + MarkupTestFile.GetSpan(""" + public class C + { + // A change + public event System.EventHandler [|E|] { add { } remove { } } + } + """, out var metadataSource, out var expectedSpan); // Compile reference assembly var sourceText = SourceText.From(metadataSource, encoding: Encoding.UTF8); @@ -518,11 +480,12 @@ await RunTestAsync(async path => var pdbFilePath = Path.Combine(path, "implementation.pdb"); var assemblyName = "implementation"; - var workspace = EditorTestWorkspace.Create(@$" - - - -", composition: GetTestComposition()); + var workspace = EditorTestWorkspace.Create($""" + + + + + """, composition: GetTestComposition()); var implProject = workspace.CurrentSolution.Projects.First(); CompileTestSource(dllFilePath, sourceCodePath, pdbFilePath, assemblyName, sourceText, implProject, Location.Embedded, Location.Embedded, buildReferenceAssembly: false, windowsPdb: false); diff --git a/src/EditorFeatures/CSharpTest/PdbSourceDocument/PdbFileLocatorServiceTests.cs b/src/EditorFeatures/CSharpTest/PdbSourceDocument/PdbFileLocatorServiceTests.cs index 4b752e96da1a9..3da6eb6de598e 100644 --- a/src/EditorFeatures/CSharpTest/PdbSourceDocument/PdbFileLocatorServiceTests.cs +++ b/src/EditorFeatures/CSharpTest/PdbSourceDocument/PdbFileLocatorServiceTests.cs @@ -16,18 +16,15 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.PdbSourceDocument; public sealed class PdbFileLocatorServiceTests : AbstractPdbSourceDocumentTests { [Fact] - public async Task ReturnsPdbPathFromDebugger() - { - var source = """ + public Task ReturnsPdbPathFromDebugger() + => RunTestAsync(async path => + { + MarkupTestFile.GetSpan(""" public class C { public event System.EventHandler [|E|] { add { } remove { } } } - """; - - await RunTestAsync(async path => - { - MarkupTestFile.GetSpan(source, out var metadataSource, out var expectedSpan); + """, out var metadataSource, out var expectedSpan); var (project, symbol) = await CompileAndFindSymbolAsync(path, Location.OnDisk, Location.OnDisk, metadataSource, c => c.GetMember("C.E")); @@ -42,21 +39,17 @@ await RunTestAsync(async path => Assert.NotNull(result); }); - } [Fact] - public async Task DoesntReadNonPortablePdbs() - { - var source = """ + public Task DoesntReadNonPortablePdbs() + => RunTestAsync(async path => + { + MarkupTestFile.GetSpan(""" public class C { public event System.EventHandler [|E|] { add { } remove { } } } - """; - - await RunTestAsync(async path => - { - MarkupTestFile.GetSpan(source, out var metadataSource, out var expectedSpan); + """, out var metadataSource, out var expectedSpan); // Ideally we don't want to pass in true for windowsPdb here, and this is supposed to test that the service ignores non-portable PDBs when the debugger // tells us they're not portable, but the debugger has a bug at the moment. @@ -73,21 +66,17 @@ await RunTestAsync(async path => Assert.Null(result); }); - } [Fact] - public async Task NoPdbFoundReturnsNull() - { - var source = """ + public Task NoPdbFoundReturnsNull() + => RunTestAsync(async path => + { + MarkupTestFile.GetSpan(""" public class C { public event System.EventHandler [|E|] { add { } remove { } } } - """; - - await RunTestAsync(async path => - { - MarkupTestFile.GetSpan(source, out var metadataSource, out var expectedSpan); + """, out var metadataSource, out var expectedSpan); var (project, symbol) = await CompileAndFindSymbolAsync(path, Location.OnDisk, Location.OnDisk, metadataSource, c => c.GetMember("C.E")); @@ -102,5 +91,4 @@ await RunTestAsync(async path => Assert.Null(result); }); - } } diff --git a/src/EditorFeatures/CSharpTest/PdbSourceDocument/PdbSourceDocumentLoaderServiceTests.cs b/src/EditorFeatures/CSharpTest/PdbSourceDocument/PdbSourceDocumentLoaderServiceTests.cs index 7614934315ffa..eb5380c32e2e7 100644 --- a/src/EditorFeatures/CSharpTest/PdbSourceDocument/PdbSourceDocumentLoaderServiceTests.cs +++ b/src/EditorFeatures/CSharpTest/PdbSourceDocument/PdbSourceDocumentLoaderServiceTests.cs @@ -19,18 +19,15 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.PdbSourceDocument; public sealed class PdbSourceDocumentLoaderServiceTests : AbstractPdbSourceDocumentTests { [Fact] - public async Task ReturnsSourceFileFromSourceLink() - { - var source = """ + public Task ReturnsSourceFileFromSourceLink() + => RunTestAsync(async path => + { + MarkupTestFile.GetSpan(""" public class C { public event System.EventHandler [|E|] { add { } remove { } } } - """; - - await RunTestAsync(async path => - { - MarkupTestFile.GetSpan(source, out var metadataSource, out var expectedSpan); + """, out var metadataSource, out var expectedSpan); var (project, symbol) = await CompileAndFindSymbolAsync(path, Location.OnDisk, Location.OnDisk, metadataSource, c => c.GetMember("C.E")); @@ -51,21 +48,17 @@ await RunTestAsync(async path => Assert.Equal(sourceFilePath, result!.FilePath); Assert.True(result.FromRemoteLocation); }); - } [Fact] - public async Task NoUrlFoundReturnsNull() - { - var source = """ + public Task NoUrlFoundReturnsNull() + => RunTestAsync(async path => + { + MarkupTestFile.GetSpan(""" public class C { public event System.EventHandler [|E|] { add { } remove { } } } - """; - - await RunTestAsync(async path => - { - MarkupTestFile.GetSpan(source, out var metadataSource, out var expectedSpan); + """, out var metadataSource, out var expectedSpan); var (project, symbol) = await CompileAndFindSymbolAsync(path, Location.OnDisk, Location.OnDisk, metadataSource, c => c.GetMember("C.E")); @@ -81,5 +74,4 @@ await RunTestAsync(async path => Assert.Null(result); }); - } } diff --git a/src/EditorFeatures/CSharpTest/PdbSourceDocument/PdbSourceDocumentTests.cs b/src/EditorFeatures/CSharpTest/PdbSourceDocument/PdbSourceDocumentTests.cs index c70a3d56f4764..88727d09b07b4 100644 --- a/src/EditorFeatures/CSharpTest/PdbSourceDocument/PdbSourceDocumentTests.cs +++ b/src/EditorFeatures/CSharpTest/PdbSourceDocument/PdbSourceDocumentTests.cs @@ -13,7 +13,6 @@ using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; -using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.PdbSourceDocument; @@ -21,9 +20,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.PdbSourceDocument; public sealed partial class PdbSourceDocumentTests : AbstractPdbSourceDocumentTests { [Theory, CombinatorialData] - public async Task PreprocessorSymbols1(Location pdbLocation, Location sourceLocation) - { - var source = """ + public Task PreprocessorSymbols1(Location pdbLocation, Location sourceLocation) + => TestAsync(pdbLocation, sourceLocation, """ public class C { #if SOME_DEFINED_CONSTANT @@ -36,14 +34,11 @@ public void M() } #endif } - """; - await TestAsync(pdbLocation, sourceLocation, source, c => c.GetMember("C.M"), preprocessorSymbols: ["SOME_DEFINED_CONSTANT"]); - } + """, c => c.GetMember("C.M"), preprocessorSymbols: ["SOME_DEFINED_CONSTANT"]); [Theory, CombinatorialData] - public async Task PreprocessorSymbols2(Location pdbLocation, Location sourceLocation) - { - var source = """ + public Task PreprocessorSymbols2(Location pdbLocation, Location sourceLocation) + => TestAsync(pdbLocation, sourceLocation, """ public class C { #if SOME_DEFINED_CONSTANT @@ -56,14 +51,11 @@ public void M() } #endif } - """; - await TestAsync(pdbLocation, sourceLocation, source, c => c.GetMember("C.M")); - } + """, c => c.GetMember("C.M")); [Theory, CombinatorialData] - public async Task Method(Location pdbLocation, Location sourceLocation) - { - var source = """ + public Task Method(Location pdbLocation, Location sourceLocation) + => TestAsync(pdbLocation, sourceLocation, """ public class C { public void [|M|]() @@ -71,14 +63,11 @@ public class C // this is a comment that wouldn't appear in decompiled source } } - """; - await TestAsync(pdbLocation, sourceLocation, source, c => c.GetMember("C.M")); - } + """, c => c.GetMember("C.M")); [Theory, CombinatorialData] - public async Task Constructor(Location pdbLocation, Location sourceLocation) - { - var source = """ + public Task Constructor(Location pdbLocation, Location sourceLocation) + => TestAsync(pdbLocation, sourceLocation, """ public class C { public [|C|]() @@ -86,14 +75,11 @@ public class C // this is a comment that wouldn't appear in decompiled source } } - """; - await TestAsync(pdbLocation, sourceLocation, source, c => c.GetMember("C..ctor")); - } + """, c => c.GetMember("C..ctor")); [Theory, CombinatorialData] - public async Task Parameter(Location pdbLocation, Location sourceLocation) - { - var source = """ + public Task Parameter(Location pdbLocation, Location sourceLocation) + => TestAsync(pdbLocation, sourceLocation, """ public class C { public void M(int [|a|]) @@ -101,39 +87,29 @@ public void M(int [|a|]) // this is a comment that wouldn't appear in decompiled source } } - """; - await TestAsync(pdbLocation, sourceLocation, source, c => c.GetMember("C.M").Parameters.First()); - } + """, c => c.GetMember("C.M").Parameters.First()); [Theory, CombinatorialData] - public async Task Class_FromTypeDefinitionDocument(Location pdbLocation, Location sourceLocation) - { - var source = """ + public Task Class_FromTypeDefinitionDocument(Location pdbLocation, Location sourceLocation) + => TestAsync(pdbLocation, sourceLocation, """ public class [|C|] { // this is a comment that wouldn't appear in decompiled source } - """; - - await TestAsync(pdbLocation, sourceLocation, source, c => c.GetMember("C")); - } + """, c => c.GetMember("C")); [Theory, CombinatorialData] - public async Task Constructor_FromTypeDefinitionDocument(Location pdbLocation, Location sourceLocation) - { - var source = """ + public Task Constructor_FromTypeDefinitionDocument(Location pdbLocation, Location sourceLocation) + => TestAsync(pdbLocation, sourceLocation, """ public class [|C|] { // this is a comment that wouldn't appear in decompiled source } - """; - await TestAsync(pdbLocation, sourceLocation, source, c => c.GetMember("C..ctor")); - } + """, c => c.GetMember("C..ctor")); [Theory, CombinatorialData] - public async Task NestedClass_FromTypeDefinitionDocument(Location pdbLocation, Location sourceLocation) - { - var source = """ + public Task NestedClass_FromTypeDefinitionDocument(Location pdbLocation, Location sourceLocation) + => TestAsync(pdbLocation, sourceLocation, """ public class Outer { public class [|C|] @@ -141,14 +117,11 @@ public class [|C|] // this is a comment that wouldn't appear in decompiled source } } - """; - await TestAsync(pdbLocation, sourceLocation, source, c => c.GetMember("Outer.C")); - } + """, c => c.GetMember("Outer.C")); [Theory, CombinatorialData] - public async Task NestedClassConstructor_FromTypeDefinitionDocument(Location pdbLocation, Location sourceLocation) - { - var source = """ + public Task NestedClassConstructor_FromTypeDefinitionDocument(Location pdbLocation, Location sourceLocation) + => TestAsync(pdbLocation, sourceLocation, """ public class Outer { public class [|C|] @@ -156,14 +129,11 @@ public class [|C|] // this is a comment that wouldn't appear in decompiled source } } - """; - await TestAsync(pdbLocation, sourceLocation, source, c => c.GetMember("Outer.C..ctor")); - } + """, c => c.GetMember("Outer.C..ctor")); [Theory, CombinatorialData] - public async Task Class_FromTypeDefinitionDocumentOfNestedClass(Location pdbLocation, Location sourceLocation) - { - var source = """ + public Task Class_FromTypeDefinitionDocumentOfNestedClass(Location pdbLocation, Location sourceLocation) + => TestAsync(pdbLocation, sourceLocation, """ public class [|Outer|] { public class C @@ -171,14 +141,11 @@ public class C // this is a comment that wouldn't appear in decompiled source } } - """; - await TestAsync(pdbLocation, sourceLocation, source, c => c.GetMember("Outer")); - } + """, c => c.GetMember("Outer")); [Theory, CombinatorialData] - public async Task Constructor_FromTypeDefinitionDocumentOfNestedClass(Location pdbLocation, Location sourceLocation) - { - var source = """ + public Task Constructor_FromTypeDefinitionDocumentOfNestedClass(Location pdbLocation, Location sourceLocation) + => TestAsync(pdbLocation, sourceLocation, """ public class [|Outer|] { public class C @@ -186,15 +153,11 @@ public class C // this is a comment that wouldn't appear in decompiled source } } - """; - await TestAsync(pdbLocation, sourceLocation, source, c => c.GetMember("Outer..ctor")); - - } + """, c => c.GetMember("Outer..ctor")); [Theory, CombinatorialData] - public async Task NestedClass_FromMethodDocument(Location pdbLocation, Location sourceLocation) - { - var source = """ + public Task NestedClass_FromMethodDocument(Location pdbLocation, Location sourceLocation) + => TestAsync(pdbLocation, sourceLocation, """ public class Outer { public class [|C|] @@ -205,14 +168,11 @@ public void M() } } } - """; - await TestAsync(pdbLocation, sourceLocation, source, c => c.GetMember("Outer.C")); - } + """, c => c.GetMember("Outer.C")); [Theory, CombinatorialData] - public async Task NestedClassConstructor_FromMethodDocument(Location pdbLocation, Location sourceLocation) - { - var source = """ + public Task NestedClassConstructor_FromMethodDocument(Location pdbLocation, Location sourceLocation) + => TestAsync(pdbLocation, sourceLocation, """ public class Outer { public class [|C|] @@ -223,15 +183,11 @@ public void M() } } } - """; - - await TestAsync(pdbLocation, sourceLocation, source, c => c.GetMember("Outer.C..ctor")); - } + """, c => c.GetMember("Outer.C..ctor")); [Theory, CombinatorialData] - public async Task Class_FromMethodDocumentOfNestedClass(Location pdbLocation, Location sourceLocation) - { - var source = """ + public Task Class_FromMethodDocumentOfNestedClass(Location pdbLocation, Location sourceLocation) + => TestAsync(pdbLocation, sourceLocation, """ public class [|Outer|] { public class C @@ -242,15 +198,11 @@ public void M() } } } - """; - - await TestAsync(pdbLocation, sourceLocation, source, c => c.GetMember("Outer")); - } + """, c => c.GetMember("Outer")); [Theory, CombinatorialData] - public async Task Constructor_FromMethodDocumentOfNestedClass(Location pdbLocation, Location sourceLocation) - { - var source = """ + public Task Constructor_FromMethodDocumentOfNestedClass(Location pdbLocation, Location sourceLocation) + => TestAsync(pdbLocation, sourceLocation, """ public class [|Outer|] { public class C @@ -261,15 +213,11 @@ public void M() } } } - """; - - await TestAsync(pdbLocation, sourceLocation, source, c => c.GetMember("Outer..ctor")); - } + """, c => c.GetMember("Outer..ctor")); [Theory, CombinatorialData] - public async Task Class_FromMethodDocument(Location pdbLocation, Location sourceLocation) - { - var source = """ + public Task Class_FromMethodDocument(Location pdbLocation, Location sourceLocation) + => TestAsync(pdbLocation, sourceLocation, """ public class [|C|] { public void M() @@ -277,14 +225,11 @@ public void M() // this is a comment that wouldn't appear in decompiled source } } - """; - await TestAsync(pdbLocation, sourceLocation, source, c => c.GetMember("C")); - } + """, c => c.GetMember("C")); [Theory, CombinatorialData] - public async Task Constructor_FromMethodDocument(Location pdbLocation, Location sourceLocation) - { - var source = """ + public Task Constructor_FromMethodDocument(Location pdbLocation, Location sourceLocation) + => TestAsync(pdbLocation, sourceLocation, """ public class [|C|] { public void M() @@ -292,62 +237,47 @@ public void M() // this is a comment that wouldn't appear in decompiled source } } - """; - await TestAsync(pdbLocation, sourceLocation, source, c => c.GetMember("C..ctor")); - } + """, c => c.GetMember("C..ctor")); [Theory, CombinatorialData] - public async Task Field(Location pdbLocation, Location sourceLocation) - { - var source = """ + public Task Field(Location pdbLocation, Location sourceLocation) + => TestAsync(pdbLocation, sourceLocation, """ public class C { public int [|f|]; } - """; - await TestAsync(pdbLocation, sourceLocation, source, c => c.GetMember("C.f")); - } + """, c => c.GetMember("C.f")); [Theory, CombinatorialData] - public async Task Property(Location pdbLocation, Location sourceLocation) - { - var source = """ + public Task Property(Location pdbLocation, Location sourceLocation) + => TestAsync(pdbLocation, sourceLocation, """ public class C { public int [|P|] { get; set; } } - """; - await TestAsync(pdbLocation, sourceLocation, source, c => c.GetMember("C.P")); - } + """, c => c.GetMember("C.P")); [Theory, CombinatorialData] - public async Task Property_WithBody(Location pdbLocation, Location sourceLocation) - { - var source = """ + public Task Property_WithBody(Location pdbLocation, Location sourceLocation) + => TestAsync(pdbLocation, sourceLocation, """ public class C { public int [|P|] { get { return 1; } } } - """; - await TestAsync(pdbLocation, sourceLocation, source, c => c.GetMember("C.P")); - } + """, c => c.GetMember("C.P")); [Theory, CombinatorialData] - public async Task EventField(Location pdbLocation, Location sourceLocation) - { - var source = """ + public Task EventField(Location pdbLocation, Location sourceLocation) + => TestAsync(pdbLocation, sourceLocation, """ public class C { public event System.EventHandler [|E|]; } - """; - await TestAsync(pdbLocation, sourceLocation, source, c => c.GetMember("C.E")); - } + """, c => c.GetMember("C.E")); [Theory, CombinatorialData] - public async Task EventField_WithMethod(Location pdbLocation, Location sourceLocation) - { - var source = """ + public Task EventField_WithMethod(Location pdbLocation, Location sourceLocation) + => TestAsync(pdbLocation, sourceLocation, """ public class C { public event System.EventHandler [|E|]; @@ -357,49 +287,37 @@ public void M() // this is a comment that wouldn't appear in decompiled source } } - """; - await TestAsync(pdbLocation, sourceLocation, source, c => c.GetMember("C.E")); - } + """, c => c.GetMember("C.E")); [Theory, CombinatorialData] - public async Task Event(Location pdbLocation, Location sourceLocation) - { - var source = """ + public Task Event(Location pdbLocation, Location sourceLocation) + => TestAsync(pdbLocation, sourceLocation, """ public class C { public event System.EventHandler [|E|] { add { } remove { } } } - """; - await TestAsync(pdbLocation, sourceLocation, source, c => c.GetMember("C.E")); - } + """, c => c.GetMember("C.E")); [Fact] - public async Task ReferenceAssembly_NullResult() - { - var source = """ + public Task ReferenceAssembly_NullResult() + => TestAsync(Location.OnDisk, Location.OnDisk, """ public class C { public event System.EventHandler [|E|] { add { } remove { } } } - """; - // A pdb won't be emitted when building a reference assembly so the first two parameters don't actually matter - await TestAsync(Location.OnDisk, Location.OnDisk, source, c => c.GetMember("C.E"), buildReferenceAssembly: true, expectNullResult: true); - } + """, c => c.GetMember("C.E"), buildReferenceAssembly: true, expectNullResult: true); [Fact] - public async Task NugetPackageLayout() - { - var source = """ + public Task NugetPackageLayout() + => RunTestAsync(async path => + { + MarkupTestFile.GetSpan(""" public class C { // A change public event System.EventHandler [|E|] { add { } remove { } } } - """; - - await RunTestAsync(async path => - { - MarkupTestFile.GetSpan(source, out var metadataSource, out var expectedSpan); + """, out var metadataSource, out var expectedSpan); // Laziest. Nuget package directory layout. Ever. Directory.CreateDirectory(Path.Combine(path, "ref")); @@ -414,22 +332,18 @@ await RunTestAsync(async path => await GenerateFileAndVerifyAsync(project, symbol, Location.Embedded, metadataSource.ToString(), expectedSpan, expectNullResult: false); }); - } [Fact] - public async Task Net6SdkLayout() - { - var source = """ + public Task Net6SdkLayout() + => RunTestAsync(async path => + { + MarkupTestFile.GetSpan(""" public class C { // A change public event System.EventHandler [|E|] { add { } remove { } } } - """; - - await RunTestAsync(async path => - { - MarkupTestFile.GetSpan(source, out var metadataSource, out var expectedSpan); + """, out var metadataSource, out var expectedSpan); var packDir = Directory.CreateDirectory(Path.Combine(path, "packs", "MyPack.Ref", "1.0", "ref", "net6.0")).FullName; var dataDir = Directory.CreateDirectory(Path.Combine(path, "packs", "MyPack.Ref", "1.0", "data")).FullName; @@ -450,23 +364,19 @@ await RunTestAsync(async path => await GenerateFileAndVerifyAsync(project, symbol, Location.Embedded, metadataSource.ToString(), expectedSpan, expectNullResult: false); }); - } [Fact] - public async Task Net6SdkLayout_WithOtherReferences() - { - var source = """ + public Task Net6SdkLayout_WithOtherReferences() + => RunTestAsync(async path => + { + MarkupTestFile.GetSpan(""" public class C { public void [|M|](string d) { } } - """; - - await RunTestAsync(async path => - { - MarkupTestFile.GetSpan(source, out var metadataSource, out var expectedSpan); + """, out var metadataSource, out var expectedSpan); var packDir = Directory.CreateDirectory(Path.Combine(path, "packs", "MyPack.Ref", "1.0", "ref", "net6.0")).FullName; var dataDir = Directory.CreateDirectory(Path.Combine(path, "packs", "MyPack.Ref", "1.0", "data")).FullName; @@ -475,11 +385,12 @@ await RunTestAsync(async path => var sourceText = SourceText.From(metadataSource, Encoding.UTF8); var (project, symbol) = await CompileAndFindSymbolAsync(packDir, Location.Embedded, Location.Embedded, sourceText, c => c.GetMember("C.M"), buildReferenceAssembly: true); - var workspace = EditorTestWorkspace.Create(@$" - - - -", composition: GetTestComposition()); + var workspace = EditorTestWorkspace.Create($""" + + + + + """, composition: GetTestComposition()); var implProject = workspace.CurrentSolution.Projects.First(); @@ -494,26 +405,19 @@ await RunTestAsync(async path => await GenerateFileAndVerifyAsync(project, symbol, Location.Embedded, metadataSource.ToString(), expectedSpan, expectNullResult: false); }); - } [Fact] - public async Task Net6SdkLayout_TypeForward() - { - var source = """ + public Task Net6SdkLayout_TypeForward() + => RunTestAsync(async path => + { + MarkupTestFile.GetSpan(""" public class [|C|] { public void M(string d) { } } - """; - var typeForwardSource = """ - [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))] - """; - - await RunTestAsync(async path => - { - MarkupTestFile.GetSpan(source, out var metadataSource, out var expectedSpan); + """, out var metadataSource, out var expectedSpan); var packDir = Directory.CreateDirectory(Path.Combine(path, "packs", "MyPack.Ref", "1.0", "ref", "net6.0")).FullName; var dataDir = Directory.CreateDirectory(Path.Combine(path, "packs", "MyPack.Ref", "1.0", "data")).FullName; @@ -522,11 +426,12 @@ await RunTestAsync(async path => var sourceText = SourceText.From(metadataSource, Encoding.UTF8); var (project, symbol) = await CompileAndFindSymbolAsync(packDir, Location.Embedded, Location.Embedded, sourceText, c => c.GetMember("C"), buildReferenceAssembly: true); - var workspace = EditorTestWorkspace.Create(@$" - - - -", composition: GetTestComposition()); + var workspace = EditorTestWorkspace.Create($""" + + + + + """, composition: GetTestComposition()); var implProject = workspace.CurrentSolution.Projects.First(); @@ -545,7 +450,9 @@ await RunTestAsync(async path => assemblyName = "reference"; implProject = implProject.AddMetadataReference(MetadataReference.CreateFromFile(implementationDllFilePath)); - sourceText = SourceText.From(typeForwardSource, Encoding.UTF8); + sourceText = SourceText.From(""" + [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))] + """, Encoding.UTF8); CompileTestSource(typeForwardDllFilePath, sourceCodePath, pdbFilePath, assemblyName, sourceText, implProject, Location.Embedded, Location.Embedded, buildReferenceAssembly: false, windowsPdb: false); // Create FrameworkList.xml @@ -556,7 +463,6 @@ await RunTestAsync(async path => await GenerateFileAndVerifyAsync(project, symbol, Location.Embedded, metadataSource.ToString(), expectedSpan, expectNullResult: false); }); - } [Fact] public async Task NoPdb_NullResult() @@ -703,14 +609,6 @@ public class C public event System.EventHandler [|E|] { add { } remove { } } } """; - var source2 = """ - public class C - { - // A change - public event System.EventHandler E { add { } remove { } } - } - """; - await RunTestAsync(async path => { MarkupTestFile.GetSpan(source1, out var metadataSource, out var expectedSpan); @@ -722,7 +620,13 @@ await RunTestAsync(async path => var archivePdbFilePath = pdbFilePath + ".old"; File.Move(pdbFilePath, archivePdbFilePath); - CompileTestSource(path, SourceText.From(source2, Encoding.UTF8), project, Location.OnDisk, Location.OnDisk, buildReferenceAssembly: false, windowsPdb: false); + CompileTestSource(path, SourceText.From(""" + public class C + { + // A change + public event System.EventHandler E { add { } remove { } } + } + """, Encoding.UTF8), project, Location.OnDisk, Location.OnDisk, buildReferenceAssembly: false, windowsPdb: false); // Move the old file back, so the PDB is now old File.Delete(pdbFilePath); @@ -733,33 +637,28 @@ await RunTestAsync(async path => } [Theory, CombinatorialData] - public async Task SourceFileChecksumIncorrect_NullResult(Location pdbLocation) - { - var source1 = """ + public Task SourceFileChecksumIncorrect_NullResult(Location pdbLocation) + => RunTestAsync(async path => + { + MarkupTestFile.GetSpan(""" public class C { public event System.EventHandler [|E|] { add { } remove { } } } - """; - var source2 = """ + """, out var metadataSource, out var expectedSpan); + + var (project, symbol) = await CompileAndFindSymbolAsync(path, pdbLocation, Location.OnDisk, metadataSource, c => c.GetMember("C.E")); + + File.WriteAllText(GetSourceFilePath(path), """ public class C { // A change public event System.EventHandler E { add { } remove { } } } - """; - - await RunTestAsync(async path => - { - MarkupTestFile.GetSpan(source1, out var metadataSource, out var expectedSpan); - - var (project, symbol) = await CompileAndFindSymbolAsync(path, pdbLocation, Location.OnDisk, metadataSource, c => c.GetMember("C.E")); - - File.WriteAllText(GetSourceFilePath(path), source2, Encoding.UTF8); + """, Encoding.UTF8); await GenerateFileAndVerifyAsync(project, symbol, Location.OnDisk, metadataSource, expectedSpan, expectNullResult: true); }); - } [Theory] [InlineData(Location.Embedded, "utf-16")] @@ -927,11 +826,12 @@ await RunTestAsync(async path => var sourceText1 = SourceText.From(source1, Encoding.UTF8); var sourceText2 = SourceText.From(source2, Encoding.UTF8); - var workspace = EditorTestWorkspace.Create(@$" - - - -", composition: GetTestComposition()); + var workspace = EditorTestWorkspace.Create($""" + + + + + """, composition: GetTestComposition()); var project = workspace.CurrentSolution.Projects.First(); @@ -953,18 +853,15 @@ await RunTestAsync(async path => } [Fact, WorkItem("https://github.com/dotnet/vscode-csharp/issues/7532")] - public async Task OpenFileWithDifferentCase() - { - var source = """ + public Task OpenFileWithDifferentCase() + => RunTestAsync(async path => + { + var (project, symbol) = await CompileAndFindSymbolAsync(path, Location.Embedded, Location.Embedded, """ public class C { public int P { get; set; } } - """; - - await RunTestAsync(async path => - { - var (project, symbol) = await CompileAndFindSymbolAsync(path, Location.Embedded, Location.Embedded, source, c => c.GetMember("C.P")); + """, c => c.GetMember("C.P")); using var workspace = (EditorTestWorkspace)project.Solution.Workspace; var service = workspace.GetService(); @@ -975,21 +872,17 @@ await RunTestAsync(async path => var result = service.TryAddDocumentToWorkspace(requestPath, new StaticSourceTextContainer(SourceText.From(string.Empty)), out var documentId); Assert.True(result); }); - } [Fact] - public async Task OpenThenClose() - { - var source = """ + public Task OpenThenClose() + => RunTestAsync(async path => + { + var (project, symbol) = await CompileAndFindSymbolAsync(path, Location.Embedded, Location.Embedded, """ public class C { public int P { get; set; } } - """; - - await RunTestAsync(async path => - { - var (project, symbol) = await CompileAndFindSymbolAsync(path, Location.Embedded, Location.Embedded, source, c => c.GetMember("C.P")); + """, c => c.GetMember("C.P")); using var workspace = (EditorTestWorkspace)project.Solution.Workspace; var service = workspace.GetService(); @@ -1001,21 +894,17 @@ await RunTestAsync(async path => var closeResult = service.TryRemoveDocumentFromWorkspace(file.FilePath); Assert.True(closeResult); }); - } [Fact, WorkItem("https://github.com/dotnet/vscode-csharp/issues/7514")] - public async Task CloseWithoutOpenDoesNotThrow() - { - var source = """ + public Task CloseWithoutOpenDoesNotThrow() + => RunTestAsync(async path => + { + var (project, symbol) = await CompileAndFindSymbolAsync(path, Location.Embedded, Location.Embedded, """ public class C { public int P { get; set; } } - """; - - await RunTestAsync(async path => - { - var (project, symbol) = await CompileAndFindSymbolAsync(path, Location.Embedded, Location.Embedded, source, c => c.GetMember("C.P")); + """, c => c.GetMember("C.P")); using var workspace = (EditorTestWorkspace)project.Solution.Workspace; var service = workspace.GetService(); @@ -1024,23 +913,19 @@ await RunTestAsync(async path => var result = service.TryRemoveDocumentFromWorkspace(file.FilePath); Assert.False(result); }); - } [Fact, WorkItem("https://github.com/dotnet/vscode-csharp/issues/7514")] - public async Task OpenSameDocument() - { - var source = """ + public Task OpenSameDocument() + => RunTestAsync(async path => + { + var (project, symbol) = await CompileAndFindSymbolAsync(path, Location.Embedded, Location.Embedded, """ public class C { public int P1 { get; set; } public int P2 { get; set; } } - """; - - await RunTestAsync(async path => - { - var (project, symbol) = await CompileAndFindSymbolAsync(path, Location.Embedded, Location.Embedded, source, c => c.GetMember("C.P1")); + """, c => c.GetMember("C.P1")); using var workspace = (EditorTestWorkspace)project.Solution.Workspace; var service = workspace.GetService(); @@ -1059,5 +944,4 @@ await RunTestAsync(async path => // opened document in the MAS workspace). Assert.Throws(() => service.TryAddDocumentToWorkspace(fileTwo.FilePath, new StaticSourceTextContainer(SourceText.From(string.Empty)), out var documentIdTwo)); }); - } } diff --git a/src/EditorFeatures/CSharpTest/QuickInfo/DiagnosticAnalyzerQuickInfoSourceTests.cs b/src/EditorFeatures/CSharpTest/QuickInfo/DiagnosticAnalyzerQuickInfoSourceTests.cs index 79f3517c2eead..fe7fd8711e31e 100644 --- a/src/EditorFeatures/CSharpTest/QuickInfo/DiagnosticAnalyzerQuickInfoSourceTests.cs +++ b/src/EditorFeatures/CSharpTest/QuickInfo/DiagnosticAnalyzerQuickInfoSourceTests.cs @@ -28,35 +28,29 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.QuickInfo; public sealed class DiagnosticAnalyzerQuickInfoSourceTests { [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/46604")] - public async Task ErrorTitleIsShownOnDisablePragma() - { - await TestInMethodAsync( + public Task ErrorTitleIsShownOnDisablePragma() + => TestInMethodAsync( """ #pragma warning disable CS0219$$ var i = 0; #pragma warning restore CS0219 """, GetFormattedErrorTitle(ErrorCode.WRN_UnreferencedVarAssg)); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/46604")] - public async Task ErrorTitleIsShownOnRestorePragma() - { - await TestInMethodAsync( + public Task ErrorTitleIsShownOnRestorePragma() + => TestInMethodAsync( """ #pragma warning disable CS0219 var i = 0; #pragma warning restore CS0219$$ """, GetFormattedErrorTitle(ErrorCode.WRN_UnreferencedVarAssg)); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/46604")] - public async Task DisabledWarningNotExistingInCodeIsDisplayedByTitleWithoutCodeDetails() - { - await TestInMethodAsync( + public Task DisabledWarningNotExistingInCodeIsDisplayedByTitleWithoutCodeDetails() + => TestInMethodAsync( """ #pragma warning disable CS0219$$ """, GetFormattedErrorTitle(ErrorCode.WRN_UnreferencedVarAssg)); - } [WorkItem("https://github.com/dotnet/roslyn/issues/49102")] [WpfTheory] @@ -66,15 +60,11 @@ await TestInMethodAsync( [InlineData("CS02$$19")] [InlineData("2$$19")] [InlineData("02$$19")] - public async Task PragmaWarningCompilerWarningSyntaxKinds(string warning) - { - // Reference: https://docs.microsoft.com/en-US/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-pragma-warning - // "A comma-separated list of warning numbers. The "CS" prefix is optional." - await TestInMethodAsync( + public Task PragmaWarningCompilerWarningSyntaxKinds(string warning) + => TestInMethodAsync( @$" #pragma warning disable {warning} ", GetFormattedErrorTitle(ErrorCode.WRN_UnreferencedVarAssg)); - } [WorkItem("https://github.com/dotnet/roslyn/issues/49102")] [WpfTheory] @@ -103,20 +93,17 @@ await TestInMethodAsync( [InlineData("#pragma warning disable CS0162, CS0219$$", (int)ErrorCode.WRN_UnreferencedVarAssg)] [InlineData("#pragma warning $$disable CS0162, CS0219", (int)ErrorCode.WRN_UnreachableCode)] [InlineData("#pragma warning $$disable CS0219, CS0162", (int)ErrorCode.WRN_UnreferencedVarAssg)] - public async Task MultipleWarningsAreDisplayedDependingOnCursorPosition(string pragma, int errorCode) - { - await TestInMethodAsync( + public Task MultipleWarningsAreDisplayedDependingOnCursorPosition(string pragma, int errorCode) + => TestInMethodAsync( @$" {pragma} return; var i = 0; ", GetFormattedErrorTitle((ErrorCode)errorCode)); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/46604")] - public async Task ErrorTitleIsShwonInSupressMessageAttribute() - { - await TestAsync( + public Task ErrorTitleIsShwonInSupressMessageAttribute() + => TestAsync( """ using System.Diagnostics.CodeAnalysis; namespace T @@ -128,7 +115,6 @@ public class C } } """, GetFormattedIDEAnalyzerTitle(51, nameof(AnalyzersResources.Remove_unused_private_members)), []); - } [WorkItem("https://github.com/dotnet/roslyn/issues/46604")] [WpfTheory] diff --git a/src/EditorFeatures/CSharpTest/QuickInfo/SemanticQuickInfoSourceTests.cs b/src/EditorFeatures/CSharpTest/QuickInfo/SemanticQuickInfoSourceTests.cs index 65fcb111faa91..8a2800b3fa02b 100644 --- a/src/EditorFeatures/CSharpTest/QuickInfo/SemanticQuickInfoSourceTests.cs +++ b/src/EditorFeatures/CSharpTest/QuickInfo/SemanticQuickInfoSourceTests.cs @@ -17,7 +17,6 @@ using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; -using Roslyn.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications; @@ -328,81 +327,59 @@ private async Task TestInvalidTypeInClassAsync(string code) } [Fact] - public async Task TestNamespaceInUsingDirective() - { - await TestAsync( + public Task TestNamespaceInUsingDirective() + => TestAsync( @"using $$System;", MainDescription("namespace System")); - } [Fact] - public async Task TestNamespaceInUsingDirective2() - { - await TestAsync( + public Task TestNamespaceInUsingDirective2() + => TestAsync( @"using System.Coll$$ections.Generic;", MainDescription("namespace System.Collections")); - } [Fact] - public async Task TestNamespaceInUsingDirective3() - { - await TestAsync( + public Task TestNamespaceInUsingDirective3() + => TestAsync( @"using System.L$$inq;", MainDescription("namespace System.Linq")); - } [Fact] - public async Task TestNamespaceInUsingDirectiveWithAlias() - { - await TestAsync( + public Task TestNamespaceInUsingDirectiveWithAlias() + => TestAsync( @"using Goo = Sys$$tem.Console;", MainDescription("namespace System")); - } [Fact] - public async Task TestTypeInUsingDirectiveWithAlias() - { - await TestAsync( + public Task TestTypeInUsingDirectiveWithAlias() + => TestAsync( @"using Goo = System.Con$$sole;", MainDescription("class System.Console")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")] - public async Task TestDocumentationInUsingDirectiveWithAlias() - { - var markup = - """ + public Task TestDocumentationInUsingDirectiveWithAlias() + => TestAsync(""" using I$$ = IGoo; ///summary for interface IGoo interface IGoo { } - """; - - await TestAsync(markup, + """, MainDescription("interface IGoo"), Documentation("summary for interface IGoo")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")] - public async Task TestDocumentationInUsingDirectiveWithAlias2() - { - var markup = - """ + public Task TestDocumentationInUsingDirectiveWithAlias2() + => TestAsync(""" using I = IGoo; ///summary for interface IGoo interface IGoo { } class C : I$$ { } - """; - - await TestAsync(markup, + """, MainDescription("interface IGoo"), Documentation("summary for interface IGoo")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")] - public async Task TestDocumentationInUsingDirectiveWithAlias3() - { - var markup = - """ + public Task TestDocumentationInUsingDirectiveWithAlias3() + => TestAsync(""" using I = IGoo; ///summary for interface IGoo interface IGoo @@ -410,42 +387,29 @@ interface IGoo void Goo(); } class C : I$$ { } - """; - - await TestAsync(markup, + """, MainDescription("interface IGoo"), Documentation("summary for interface IGoo")); - } [Fact] - public async Task TestThis() - { - var markup = - """ + public Task TestThis() + => TestWithUsingsAsync(""" ///summary for Class C class C { string M() { return thi$$s.ToString(); } } - """; - - await TestWithUsingsAsync(markup, + """, MainDescription("class C"), Documentation("summary for Class C")); - } [Fact] - public async Task TestClassWithDocComment() - { - var markup = - """ + public Task TestClassWithDocComment() + => TestAsync(""" ///Hello! class C { void M() { $$C obj; } } - """; - - await TestAsync(markup, + """, MainDescription("class C"), Documentation("Hello!")); - } [Fact] public async Task TestSingleLineDocComments() @@ -646,159 +610,120 @@ class C { void M() { $$C obj; } } } [Fact] - public async Task TestMethodWithDocComment() - { - var markup = - """ + public Task TestMethodWithDocComment() + => TestInClassAsync(""" ///Hello! void M() { M$$() } - """; - - await TestInClassAsync(markup, + """, MainDescription("void C.M()"), Documentation("Hello!")); - } [Fact] - public async Task TestInt32() - { - await TestInClassAsync( + public Task TestInt32() + => TestInClassAsync( @"$$Int32 i;", MainDescription("struct System.Int32")); - } [Fact] - public async Task TestBuiltInInt() - { - await TestInClassAsync( + public Task TestBuiltInInt() + => TestInClassAsync( @"$$int i;", MainDescription("struct System.Int32")); - } [Fact] - public async Task TestString() - { - await TestInClassAsync( + public Task TestString() + => TestInClassAsync( @"$$String s;", MainDescription("class System.String")); - } [Fact] - public async Task TestBuiltInString() - { - await TestInClassAsync( + public Task TestBuiltInString() + => TestInClassAsync( @"$$string s;", MainDescription("class System.String")); - } [Fact] - public async Task TestBuiltInStringAtEndOfToken() - { - await TestInClassAsync( + public Task TestBuiltInStringAtEndOfToken() + => TestInClassAsync( @"string$$ s;", MainDescription("class System.String")); - } [Fact] - public async Task TestBoolean() - { - await TestInClassAsync( + public Task TestBoolean() + => TestInClassAsync( @"$$Boolean b;", MainDescription("struct System.Boolean")); - } [Fact] - public async Task TestBuiltInBool() - { - await TestInClassAsync( + public Task TestBuiltInBool() + => TestInClassAsync( @"$$bool b;", MainDescription("struct System.Boolean")); - } [Fact] - public async Task TestSingle() - { - await TestInClassAsync( + public Task TestSingle() + => TestInClassAsync( @"$$Single s;", MainDescription("struct System.Single")); - } [Fact] - public async Task TestBuiltInFloat() - { - await TestInClassAsync( + public Task TestBuiltInFloat() + => TestInClassAsync( @"$$float f;", MainDescription("struct System.Single")); - } [Fact] - public async Task TestVoidIsInvalid() - { - await TestInvalidTypeInClassAsync( + public Task TestVoidIsInvalid() + => TestInvalidTypeInClassAsync( """ $$void M() { } """); - } [Fact] - public async Task TestInvalidPointer1_931958() - { - await TestInvalidTypeInClassAsync( + public Task TestInvalidPointer1_931958() + => TestInvalidTypeInClassAsync( @"$$T* i;"); - } [Fact] - public async Task TestInvalidPointer2_931958() - { - await TestInvalidTypeInClassAsync( + public Task TestInvalidPointer2_931958() + => TestInvalidTypeInClassAsync( @"T$$* i;"); - } [Fact] - public async Task TestInvalidPointer3_931958() - { - await TestInvalidTypeInClassAsync( + public Task TestInvalidPointer3_931958() + => TestInvalidTypeInClassAsync( @"T*$$ i;"); - } [Fact] - public async Task TestListOfString() - { - await TestInClassAsync( + public Task TestListOfString() + => TestInClassAsync( @"$$List l;", MainDescription("class System.Collections.Generic.List"), TypeParameterMap($""" T {FeaturesResources.is_} string """)); - } [Fact] - public async Task TestListOfSomethingFromSource() - { - var markup = - """ + public Task TestListOfSomethingFromSource() + => TestAsync(""" ///Generic List public class GenericList { Generic$$List t; } - """; - - await TestAsync(markup, + """, MainDescription("class GenericList"), Documentation("Generic List"), TypeParameterMap($""" T {FeaturesResources.is_} int """)); - } [Fact] - public async Task TestListOfT() - { - await TestInMethodAsync( + public Task TestListOfT() + => TestInMethodAsync( """ class C { @@ -806,12 +731,10 @@ class C } """, MainDescription("class System.Collections.Generic.List")); - } [Fact] - public async Task TestDictionaryOfIntAndString() - { - await TestInClassAsync( + public Task TestDictionaryOfIntAndString() + => TestInClassAsync( @"$$Dictionary d;", MainDescription("class System.Collections.Generic.Dictionary"), TypeParameterMap( @@ -820,12 +743,10 @@ await TestInClassAsync( TKey {FeaturesResources.is_} int """, $"TValue {FeaturesResources.is_} string"))); - } [Fact] - public async Task TestDictionaryOfTAndU() - { - await TestInMethodAsync( + public Task TestDictionaryOfTAndU() + => TestInMethodAsync( """ class C { @@ -839,12 +760,10 @@ class C TKey {FeaturesResources.is_} T """, $"TValue {FeaturesResources.is_} U"))); - } [Fact] - public async Task TestIEnumerableOfInt() - { - await TestInClassAsync( + public Task TestIEnumerableOfInt() + => TestInClassAsync( """ $$IEnumerable M() { @@ -856,20 +775,16 @@ await TestInClassAsync( T {FeaturesResources.is_} int """)); - } [Fact] - public async Task TestEventHandler() - { - await TestInClassAsync( + public Task TestEventHandler() + => TestInClassAsync( @"event $$EventHandler e;", MainDescription("delegate void System.EventHandler(object sender, System.EventArgs e)")); - } [Fact] - public async Task TestTypeParameter() - { - await TestAsync( + public Task TestTypeParameter() + => TestAsync( """ class C { @@ -877,28 +792,21 @@ class C } """, MainDescription($"T {FeaturesResources.in_} C")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538636")] - public async Task TestTypeParameterWithDocComment() - { - var markup = - """ + public Task TestTypeParameterWithDocComment() + => TestAsync(""" ///Hello! ///T is Type Parameter class C { $$T t; } - """; - - await TestAsync(markup, + """, MainDescription($"T {FeaturesResources.in_} C"), Documentation("T is Type Parameter")); - } [Fact] - public async Task TestTypeParameter1_Bug931949() - { - await TestAsync( + public Task TestTypeParameter1_Bug931949() + => TestAsync( """ class T1 { @@ -906,12 +814,10 @@ class T1 } """, MainDescription($"T11 {FeaturesResources.in_} T1")); - } [Fact] - public async Task TestTypeParameter2_Bug931949() - { - await TestAsync( + public Task TestTypeParameter2_Bug931949() + => TestAsync( """ class T1 { @@ -919,12 +825,10 @@ class T1 } """, MainDescription($"T11 {FeaturesResources.in_} T1")); - } [Fact] - public async Task TestTypeParameter3_Bug931949() - { - await TestAsync( + public Task TestTypeParameter3_Bug931949() + => TestAsync( """ class T1 { @@ -932,12 +836,10 @@ class T1 } """, MainDescription($"T11 {FeaturesResources.in_} T1")); - } [Fact] - public async Task TestTypeParameter4_Bug931949() - { - await TestAsync( + public Task TestTypeParameter4_Bug931949() + => TestAsync( """ class T1 { @@ -945,23 +847,19 @@ class T1 } """, MainDescription($"T11 {FeaturesResources.in_} T1")); - } [Fact] - public async Task TestNullableOfInt() - { - await TestInClassAsync(@"$$Nullable i; }", + public Task TestNullableOfInt() + => TestInClassAsync(@"$$Nullable i; }", MainDescription("struct System.Nullable where T : struct"), TypeParameterMap($""" T {FeaturesResources.is_} int """)); - } [Fact] - public async Task TestGenericTypeDeclaredOnMethod1_Bug1946() - { - await TestAsync( + public Task TestGenericTypeDeclaredOnMethod1_Bug1946() + => TestAsync( """ class C { @@ -972,12 +870,10 @@ static void Meth1($$T1 i) where T1 : struct } """, MainDescription($"T1 {FeaturesResources.in_} C.Meth1 where T1 : struct")); - } [Fact] - public async Task TestGenericTypeDeclaredOnMethod2_Bug1946() - { - await TestAsync( + public Task TestGenericTypeDeclaredOnMethod2_Bug1946() + => TestAsync( """ class C { @@ -988,12 +884,10 @@ static void Meth1(T1 i) where $$T1 : struct } """, MainDescription($"T1 {FeaturesResources.in_} C.Meth1 where T1 : struct")); - } [Fact] - public async Task TestGenericTypeDeclaredOnMethod3_Bug1946() - { - await TestAsync( + public Task TestGenericTypeDeclaredOnMethod3_Bug1946() + => TestAsync( """ class C { @@ -1004,70 +898,56 @@ static void Meth1(T1 i) where T1 : struct } """, MainDescription($"T1 {FeaturesResources.in_} C.Meth1 where T1 : struct")); - } [Fact] - public async Task TestGenericTypeParameterConstraint_Class() - { - await TestAsync( + public Task TestGenericTypeParameterConstraint_Class() + => TestAsync( """ class C where $$T : class { } """, MainDescription($"T {FeaturesResources.in_} C where T : class")); - } [Fact] - public async Task TestGenericTypeParameterConstraint_Struct() - { - await TestAsync( + public Task TestGenericTypeParameterConstraint_Struct() + => TestAsync( """ struct S where $$T : class { } """, MainDescription($"T {FeaturesResources.in_} S where T : class")); - } [Fact] - public async Task TestGenericTypeParameterConstraint_Interface() - { - await TestAsync( + public Task TestGenericTypeParameterConstraint_Interface() + => TestAsync( """ interface I where $$T : class { } """, MainDescription($"T {FeaturesResources.in_} I where T : class")); - } [Fact] - public async Task TestGenericTypeParameterConstraint_Delegate() - { - await TestAsync( + public Task TestGenericTypeParameterConstraint_Delegate() + => TestAsync( @"delegate void D() where $$T : class;", MainDescription($"T {FeaturesResources.in_} D where T : class")); - } [Fact] - public async Task TestMinimallyQualifiedConstraint() - { - await TestAsync(@"class C where $$T : IEnumerable", + public Task TestMinimallyQualifiedConstraint() + => TestAsync(@"class C where $$T : IEnumerable", MainDescription($"T {FeaturesResources.in_} C where T : IEnumerable")); - } [Fact] - public async Task FullyQualifiedConstraint() - { - await TestAsync(@"class C where $$T : System.Collections.Generic.IEnumerable", + public Task FullyQualifiedConstraint() + => TestAsync(@"class C where $$T : System.Collections.Generic.IEnumerable", MainDescription($"T {FeaturesResources.in_} C where T : System.Collections.Generic.IEnumerable")); - } [Fact] - public async Task TestMethodReferenceInSameMethod() - { - await TestAsync( + public Task TestMethodReferenceInSameMethod() + => TestAsync( """ class C { @@ -1078,44 +958,32 @@ void M() } """, MainDescription("void C.M()")); - } [Fact] - public async Task TestMethodReferenceInSameMethodWithDocComment() - { - var markup = - """ + public Task TestMethodReferenceInSameMethodWithDocComment() + => TestInClassAsync(""" ///Hello World void M() { M$$(); } - """; - - await TestInClassAsync(markup, + """, MainDescription("void C.M()"), Documentation("Hello World")); - } [Fact] - public async Task TestFieldInMethodBuiltIn() - { - var markup = - """ + public Task TestFieldInMethodBuiltIn() + => TestInClassAsync(""" int field; void M() { field$$ } - """; - - await TestInClassAsync(markup, + """, MainDescription($"({FeaturesResources.field}) int C.field")); - } [Fact] - public async Task TestFieldInMethodBuiltIn2() - { - await TestInClassAsync( + public Task TestFieldInMethodBuiltIn2() + => TestInClassAsync( """ int field; @@ -1125,12 +993,10 @@ void M() } """, MainDescription($"({FeaturesResources.field}) int C.field")); - } [Fact] - public async Task TestFieldInMethodBuiltInWithFieldInitializer() - { - await TestInClassAsync( + public Task TestFieldInMethodBuiltInWithFieldInitializer() + => TestInClassAsync( """ int field = 1; @@ -1139,581 +1005,430 @@ void M() int f = field $$; } """); - } [Fact] - public async Task TestOperatorBuiltIn() - { - await TestInMethodAsync( + public Task TestOperatorBuiltIn() + => TestInMethodAsync( """ int x; x = x$$+1; """, MainDescription("int int.operator +(int left, int right)")); - } [Fact] - public async Task TestOperatorBuiltIn1() - { - await TestInMethodAsync( + public Task TestOperatorBuiltIn1() + => TestInMethodAsync( """ int x; x = x$$ + 1; """, MainDescription($"({FeaturesResources.local_variable}) int x")); - } [Fact] - public async Task TestOperatorBuiltIn2() - { - await TestInMethodAsync( + public Task TestOperatorBuiltIn2() + => TestInMethodAsync( """ int x; x = x+$$x; """, MainDescription($"({FeaturesResources.local_variable}) int x")); - } [Fact] - public async Task TestOperatorBuiltIn3() - { - await TestInMethodAsync( + public Task TestOperatorBuiltIn3() + => TestInMethodAsync( """ int x; x = x +$$ x; """, MainDescription("int int.operator +(int left, int right)")); - } [Fact] - public async Task TestOperatorBuiltIn4() - { - await TestInMethodAsync( + public Task TestOperatorBuiltIn4() + => TestInMethodAsync( """ int x; x = x + $$x; """, MainDescription($"({FeaturesResources.local_variable}) int x")); - } [Fact] - public async Task TestOperatorBuiltIn5() - { - await TestInMethodAsync( + public Task TestOperatorBuiltIn5() + => TestInMethodAsync( """ int x; x = unchecked (x$$+1); """, MainDescription("int int.operator +(int left, int right)")); - } [Fact] - public async Task TestOperatorBuiltIn6() - { - await TestInMethodAsync( + public Task TestOperatorBuiltIn6() + => TestInMethodAsync( """ int x; x = checked (x$$+1); """, MainDescription("int int.operator checked +(int left, int right)")); - } [Fact] - public async Task TestOperatorBuiltIn7() - { - await TestInMethodAsync( + public Task TestOperatorBuiltIn7() + => TestInMethodAsync( """ int x; x = unchecked (x +$$ x); """, MainDescription("int int.operator +(int left, int right)")); - } [Fact] - public async Task TestOperatorBuiltIn8() - { - await TestInMethodAsync( + public Task TestOperatorBuiltIn8() + => TestInMethodAsync( """ int x; x = checked (x +$$ x); """, MainDescription("int int.operator checked +(int left, int right)")); - } [Fact] - public async Task TestOperatorBuiltIn9() - { - await TestInMethodAsync( + public Task TestOperatorBuiltIn9() + => TestInMethodAsync( """ int x; x = $$-x; """, MainDescription("int int.operator -(int value)")); - } [Fact] - public async Task TestOperatorBuiltIn10() - { - await TestInMethodAsync( + public Task TestOperatorBuiltIn10() + => TestInMethodAsync( """ int x; x = unchecked ($$-x); """, MainDescription("int int.operator -(int value)")); - } [Fact] - public async Task TestOperatorBuiltIn11() - { - await TestInMethodAsync( + public Task TestOperatorBuiltIn11() + => TestInMethodAsync( """ int x; x = checked ($$-x); """, MainDescription("int int.operator checked -(int value)")); - } [Fact] - public async Task TestOperatorBuiltIn12() - { - await TestInMethodAsync( + public Task TestOperatorBuiltIn12() + => TestInMethodAsync( """ int x; x = x >>>$$ x; """, MainDescription("int int.operator >>>(int left, int right)")); - } [Fact] - public async Task TestOperatorBuiltIn13() - { - await TestInMethodAsync( + public Task TestOperatorBuiltIn13() + => TestInMethodAsync( """ int x; x >>>=$$ x; """, MainDescription("int int.operator >>>(int left, int right)")); - } [Fact] - public async Task TestOperatorCustomTypeBuiltIn_01() - { - var markup = - """ + public Task TestOperatorCustomTypeBuiltIn_01() + => TestAsync(""" class C { static void M() { C c; c = c +$$ c; } } - """; - - await TestAsync(markup); - } + """); [Fact] - public async Task TestOperatorCustomTypeBuiltIn_02() - { - var markup = - """ + public Task TestOperatorCustomTypeBuiltIn_02() + => TestAsync(""" class C { static void M() { C c; c = c >>>$$ c; } } - """; - - await TestAsync(markup); - } + """); [Fact] - public async Task TestOperatorCustomTypeOverload_01() - { - var markup = - """ + public Task TestOperatorCustomTypeOverload_01() + => TestAsync(""" class C { static void M() { C c; c = c +$$ c; } static C operator+(C a, C b) { return a; } } - """; - - await TestAsync(markup, + """, MainDescription("C C.operator +(C a, C b)")); - } [Fact] - public async Task TestOperatorCustomTypeOverload_02() - { - var markup = - """ + public Task TestOperatorCustomTypeOverload_02() + => TestAsync(""" class C { static void M() { C c; c = unchecked (c +$$ c); } static C operator+(C a, C b) { return a; } } - """; - - await TestAsync(markup, + """, MainDescription("C C.operator +(C a, C b)")); - } [Fact] - public async Task TestOperatorCustomTypeOverload_03() - { - var markup = - """ + public Task TestOperatorCustomTypeOverload_03() + => TestAsync(""" class C { static void M() { C c; c = unchecked (c +$$ c); } static C operator+(C a, C b) { return a; } static C operator checked +(C a, C b) { return a; } } - """; - - await TestAsync(markup, + """, MainDescription("C C.operator +(C a, C b)")); - } [Fact] - public async Task TestOperatorCustomTypeOverload_04() - { - var markup = - """ + public Task TestOperatorCustomTypeOverload_04() + => TestAsync(""" class C { static void M() { C c; c = checked (c +$$ c); } static C operator+(C a, C b) { return a; } static C operator checked +(C a, C b) { return a; } } - """; - - await TestAsync(markup, + """, MainDescription("C C.operator checked +(C a, C b)")); - } [Fact] - public async Task TestOperatorCustomTypeOverload_05() - { - var markup = - """ + public Task TestOperatorCustomTypeOverload_05() + => TestAsync(""" class C { static void M() { C c; c = $$-c; } static C operator-(C a) { return a; } } - """; - - await TestAsync(markup, + """, MainDescription("C C.operator -(C a)")); - } [Fact] - public async Task TestOperatorCustomTypeOverload_06() - { - var markup = - """ + public Task TestOperatorCustomTypeOverload_06() + => TestAsync(""" class C { static void M() { C c; c = unchecked ($$-c); } static C operator-(C a) { return a; } } - """; - - await TestAsync(markup, + """, MainDescription("C C.operator -(C a)")); - } [Fact] - public async Task TestOperatorCustomTypeOverload_07() - { - var markup = - """ + public Task TestOperatorCustomTypeOverload_07() + => TestAsync(""" class C { static void M() { C c; c = unchecked ($$-c); } static C operator-(C a) { return a; } static C operator checked -(C a) { return a; } } - """; - - await TestAsync(markup, + """, MainDescription("C C.operator -(C a)")); - } [Fact] - public async Task TestOperatorCustomTypeOverload_08() - { - var markup = - """ + public Task TestOperatorCustomTypeOverload_08() + => TestAsync(""" class C { static void M() { C c; c = checked ($$-c); } static C operator-(C a) { return a; } static C operator checked -(C a) { return a; } } - """; - - await TestAsync(markup, + """, MainDescription("C C.operator checked -(C a)")); - } [Fact] - public async Task TestOperatorCustomTypeOverload_09() - { - var markup = - """ + public Task TestOperatorCustomTypeOverload_09() + => TestAsync(""" class C { static void M() { C c; c = c >>>$$ c; } static C operator>>>(C a, C b) { return a; } } - """; - - await TestAsync(markup, + """, MainDescription("C C.operator >>>(C a, C b)")); - } [Fact] - public async Task TestOperatorCustomTypeOverload_10() - { - var markup = - """ + public Task TestOperatorCustomTypeOverload_10() + => TestAsync(""" class C { static void M() { C c; c >>>=$$ c; } static C operator>>>(C a, C b) { return a; } } - """; - - await TestAsync(markup, + """, MainDescription("C C.operator >>>(C a, C b)")); - } [Theory] [CombinatorialData] - public async Task TestInstanceIncrementOperators_Postfix([CombinatorialValues("++", "--")] string op) - { - var markup = + public Task TestInstanceIncrementOperators_Postfix([CombinatorialValues("++", "--")] string op) + => TestWithOptionsAsync( + Options.Regular.WithLanguageVersion(LanguageVersion.Preview), $$$""" class C { static void M() { C c; c{{{op}}}$$; } public void operator {{{op}}}() {} } - """; - - await TestWithOptionsAsync( - Options.Regular.WithLanguageVersion(LanguageVersion.Preview), - markup, + """, MainDescription($"void C.operator {op}()")); - } [Theory] [CombinatorialData] - public async Task TestInstanceIncrementOperators_Postfix_Checked([CombinatorialValues("++", "--")] string op) - { - var markup = + public Task TestInstanceIncrementOperators_Postfix_Checked([CombinatorialValues("++", "--")] string op) + => TestWithOptionsAsync( + Options.Regular.WithLanguageVersion(LanguageVersion.Preview), $$$""" class C { static void M() { checked { C c; c{{{op}}}$$; } } public void operator checked {{{op}}}() {} } - """; - - await TestWithOptionsAsync( - Options.Regular.WithLanguageVersion(LanguageVersion.Preview), - markup, + """, MainDescription($"void C.operator checked {op}()")); - } [Theory] [CombinatorialData] - public async Task TestInstanceIncrementOperators_Prefix([CombinatorialValues("++", "--")] string op) - { - var markup = + public Task TestInstanceIncrementOperators_Prefix([CombinatorialValues("++", "--")] string op) + => TestWithOptionsAsync( + Options.Regular.WithLanguageVersion(LanguageVersion.Preview), $$$""" class C { static void M() { C c; {{{op}}}$$ c; } public void operator {{{op}}}() {} } - """; - - await TestWithOptionsAsync( - Options.Regular.WithLanguageVersion(LanguageVersion.Preview), - markup, + """, MainDescription($"void C.operator {op}()")); - } [Theory] [CombinatorialData] - public async Task TestInstanceIncrementOperators_Prefix_Checked([CombinatorialValues("++", "--")] string op) - { - var markup = + public Task TestInstanceIncrementOperators_Prefix_Checked([CombinatorialValues("++", "--")] string op) + => TestWithOptionsAsync( + Options.Regular.WithLanguageVersion(LanguageVersion.Preview), $$$""" class C { static void M() { checked { C c; {{{op}}}$$ c; } } public void operator checked {{{op}}}() {} } - """; - - await TestWithOptionsAsync( - Options.Regular.WithLanguageVersion(LanguageVersion.Preview), - markup, + """, MainDescription($"void C.operator checked {op}()")); - } [Theory] [CombinatorialData] - public async Task TestInstanceCompoundAssignmentOperators([CombinatorialValues("+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", ">>>=")] string op) - { - var markup = + public Task TestInstanceCompoundAssignmentOperators([CombinatorialValues("+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", ">>>=")] string op) + => TestWithOptionsAsync( + Options.Regular.WithLanguageVersion(LanguageVersion.Preview), $$$""" class C { static void M() { C c; c {{{op}}}$$ 1; } public void operator {{{op}}}(int x) {} } - """; - - await TestWithOptionsAsync( - Options.Regular.WithLanguageVersion(LanguageVersion.Preview), - markup, + """, MainDescription($"void C.operator {op}(int x)")); - } [Theory] [CombinatorialData] - public async Task TestInstanceCompoundAssignmentOperators_Checked([CombinatorialValues("+=", "-=", "*=", "/=")] string op) - { - var markup = + public Task TestInstanceCompoundAssignmentOperators_Checked([CombinatorialValues("+=", "-=", "*=", "/=")] string op) + => TestWithOptionsAsync( + Options.Regular.WithLanguageVersion(LanguageVersion.Preview), $$$""" class C { static void M() { checked { C c; c {{{op}}}$$ 1; } } public void operator checked {{{op}}}(int x) {} } - """; - - await TestWithOptionsAsync( - Options.Regular.WithLanguageVersion(LanguageVersion.Preview), - markup, + """, MainDescription($"void C.operator checked {op}(int x)")); - } [Fact] - public async Task TestFieldInMethodMinimal() - { - var markup = - """ + public Task TestFieldInMethodMinimal() + => TestInClassAsync(""" DateTime field; void M() { field$$ } - """; - - await TestInClassAsync(markup, + """, MainDescription($"({FeaturesResources.field}) DateTime C.field")); - } [Fact] - public async Task TestFieldInMethodQualified() - { - var markup = - """ + public Task TestFieldInMethodQualified() + => TestInClassAsync(""" System.IO.FileInfo file; void M() { file$$ } - """; - - await TestInClassAsync(markup, + """, MainDescription($"({FeaturesResources.field}) System.IO.FileInfo C.file")); - } [Fact] - public async Task TestMemberOfStructFromSource() - { - var markup = - """ + public Task TestMemberOfStructFromSource() + => TestAsync(""" struct MyStruct { public static int SomeField; } static class Test { int a = MyStruct.Some$$Field; } - """; - - await TestAsync(markup, + """, MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")] - public async Task TestMemberOfStructFromSourceWithDocComment() - { - var markup = - """ + public Task TestMemberOfStructFromSourceWithDocComment() + => TestAsync(""" struct MyStruct { ///My Field public static int SomeField; } static class Test { int a = MyStruct.Some$$Field; } - """; - - await TestAsync(markup, + """, MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"), Documentation("My Field")); - } [Fact] - public async Task TestMemberOfStructInsideMethodFromSource() - { - var markup = - """ + public Task TestMemberOfStructInsideMethodFromSource() + => TestAsync(""" struct MyStruct { public static int SomeField; } static class Test { static void Method() { int a = MyStruct.Some$$Field; } } - """; - - await TestAsync(markup, + """, MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")] - public async Task TestMemberOfStructInsideMethodFromSourceWithDocComment() - { - var markup = - """ + public Task TestMemberOfStructInsideMethodFromSourceWithDocComment() + => TestAsync(""" struct MyStruct { ///My Field public static int SomeField; } static class Test { static void Method() { int a = MyStruct.Some$$Field; } } - """; - - await TestAsync(markup, + """, MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"), Documentation("My Field")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")] - public async Task TestPartialMethodDocComment_01() - { - var markup = - """ + public Task TestPartialMethodDocComment_01() + => TestAsync(""" partial class MyClass { ///My Method Definition @@ -1725,18 +1440,13 @@ public partial void MyMethod() } } static class Test { static void Method() { MyClass.My$$Method(); } } - """; - - await TestAsync(markup, + """, MainDescription($"void MyClass.MyMethod()"), Documentation("My Method Implementation")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")] - public async Task TestPartialMethodDocComment_02() - { - var markup = - """ + public Task TestPartialMethodDocComment_02() + => TestAsync(""" partial class MyClass { ///My Method Definition @@ -1747,18 +1457,13 @@ public partial void MyMethod() } } static class Test { static void Method() { MyClass.My$$Method(); } } - """; - - await TestAsync(markup, + """, MainDescription($"void MyClass.MyMethod()"), Documentation("My Method Definition")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")] - public async Task TestPartialMethodDocComment_03() - { - var markup = - """ + public Task TestPartialMethodDocComment_03() + => TestAsync(""" partial class MyClass { public partial void MyMethod(); @@ -1769,54 +1474,39 @@ public partial void MyMethod() } } static class Test { static void Method() { MyClass.My$$Method(); } } - """; - - await TestAsync(markup, + """, MainDescription($"void MyClass.MyMethod()"), Documentation("My Method Implementation")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")] - public async Task TestPartialMethodDocComment_04() - { - var markup = - """ + public Task TestPartialMethodDocComment_04() + => TestAsync(""" partial class MyClass { ///My Method Definition public partial void MyMethod(); } static class Test { static void Method() { MyClass.My$$Method(); } } - """; - - await TestAsync(markup, + """, MainDescription($"void MyClass.MyMethod()"), Documentation("My Method Definition")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")] - public async Task TestPartialMethodDocComment_05() - { - var markup = - """ + public Task TestPartialMethodDocComment_05() + => TestAsync(""" partial class MyClass { ///My Method Implementation public partial void MyMethod() { } } static class Test { static void Method() { MyClass.My$$Method(); } } - """; - - await TestAsync(markup, + """, MainDescription($"void MyClass.MyMethod()"), Documentation("My Method Implementation")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")] - public async Task TestPartialMethodDocComment_06() - { - var markup = - """ + public Task TestPartialMethodDocComment_06() + => TestAsync(""" partial class MyClass { ///My Method Definition @@ -1825,41 +1515,30 @@ partial class MyClass partial void MyMethod() { } } static class Test { static void Method() { MyClass.My$$Method(); } } - """; - - await TestAsync(markup, + """, MainDescription($"void MyClass.MyMethod()"), Documentation("My Method Definition")); - } [Fact] - public async Task TestMetadataFieldMinimal() - { - await TestInMethodAsync(@"DateTime dt = DateTime.MaxValue$$", + public Task TestMetadataFieldMinimal() + => TestInMethodAsync(@"DateTime dt = DateTime.MaxValue$$", MainDescription($"({FeaturesResources.field}) static readonly DateTime DateTime.MaxValue")); - } [Fact] - public async Task TestMetadataFieldQualified1() - { - // NOTE: we qualify the field type, but not the type that contains the field in Dev10 - var markup = - """ + public Task TestMetadataFieldQualified1() + => TestAsync(""" class C { void M() { DateTime dt = System.DateTime.MaxValue$$ } } - """; - await TestAsync(markup, + """, MainDescription($"({FeaturesResources.field}) static readonly System.DateTime System.DateTime.MaxValue")); - } [Fact] - public async Task TestMetadataFieldQualified2() - { - await TestAsync( + public Task TestMetadataFieldQualified2() + => TestAsync( """ class C { @@ -1870,12 +1549,10 @@ void M() } """, MainDescription($"({FeaturesResources.field}) static readonly System.DateTime System.DateTime.MaxValue")); - } [Fact] - public async Task TestMetadataFieldQualified3() - { - await TestAsync( + public Task TestMetadataFieldQualified3() + => TestAsync( """ using System; @@ -1888,12 +1565,10 @@ void M() } """, MainDescription($"({FeaturesResources.field}) static readonly DateTime DateTime.MaxValue")); - } [Fact] - public async Task ConstructedGenericField() - { - await TestAsync( + public Task ConstructedGenericField() + => TestAsync( """ class C { @@ -1909,12 +1584,10 @@ void M() } """, MainDescription($"({FeaturesResources.field}) int C.Field")); - } [Fact] - public async Task UnconstructedGenericField() - { - await TestAsync( + public Task UnconstructedGenericField() + => TestAsync( """ class C { @@ -1927,51 +1600,39 @@ void M() } """, MainDescription($"({FeaturesResources.field}) T C.Field")); - } [Fact] - public async Task TestIntegerLiteral() - { - await TestInMethodAsync(@"int f = 37$$", + public Task TestIntegerLiteral() + => TestInMethodAsync(@"int f = 37$$", MainDescription("struct System.Int32")); - } [Fact] - public async Task TestTrueKeyword() - { - await TestInMethodAsync(@"bool f = true$$", + public Task TestTrueKeyword() + => TestInMethodAsync(@"bool f = true$$", MainDescription("struct System.Boolean")); - } [Fact] - public async Task TestFalseKeyword() - { - await TestInMethodAsync(@"bool f = false$$", + public Task TestFalseKeyword() + => TestInMethodAsync(@"bool f = false$$", MainDescription("struct System.Boolean")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26027")] - public async Task TestNullLiteral() - { - await TestInMethodAsync(@"string f = null$$", + public Task TestNullLiteral() + => TestInMethodAsync(@"string f = null$$", MainDescription("class System.String")); - } [Fact] public async Task TestNullLiteralWithVar() => await TestInMethodAsync(@"var f = null$$"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26027")] - public async Task TestDefaultLiteral() - { - await TestInMethodAsync(@"string f = default$$", + public Task TestDefaultLiteral() + => TestInMethodAsync(@"string f = default$$", MainDescription("class System.String")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")] - public async Task TestAwaitKeywordOnGenericTaskReturningAsync() - { - var markup = """ + public Task TestAwaitKeywordOnGenericTaskReturningAsync() + => TestAsync(""" using System.Threading.Tasks; class C { @@ -1981,14 +1642,11 @@ public async Task Calc() return 5; } } - """; - await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32"))); - } + """, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32"))); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")] - public async Task TestAwaitKeywordInDeclarationStatement() - { - var markup = """ + public Task TestAwaitKeywordInDeclarationStatement() + => TestAsync(""" using System.Threading.Tasks; class C { @@ -1998,14 +1656,11 @@ public async Task Calc() return 5; } } - """; - await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32"))); - } + """, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32"))); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")] - public async Task TestAwaitKeywordOnTaskReturningAsync() - { - var markup = """ + public Task TestAwaitKeywordOnTaskReturningAsync() + => TestAsync(""" using System.Threading.Tasks; class C { @@ -2014,14 +1669,11 @@ public async void Calc() aw$$ait Task.Delay(100); } } - """; - await TestAsync(markup, MainDescription(FeaturesResources.Awaited_task_returns_no_value)); - } + """, MainDescription(FeaturesResources.Awaited_task_returns_no_value)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")] - public async Task TestNestedAwaitKeywords1() - { - var markup = """ + public Task TestNestedAwaitKeywords1() + => TestAsync(""" using System; using System.Threading.Tasks; class AsyncExample2 @@ -2050,18 +1702,15 @@ async Task UseAsync() result = await lambda(); } } - """; - await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, $"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task")), + """, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, $"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task")), TypeParameterMap($""" TResult {FeaturesResources.is_} int """)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")] - public async Task TestNestedAwaitKeywords2() - { - var markup = """ + public Task TestNestedAwaitKeywords2() + => TestAsync(""" using System; using System.Threading.Tasks; class AsyncExample2 @@ -2090,14 +1739,11 @@ async Task UseAsync() result = await lambda(); } } - """; - await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32"))); - } + """, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32"))); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")] - public async Task TestAwaitablePrefixOnCustomAwaiter() - { - var markup = """ + public Task TestAwaitablePrefixOnCustomAwaiter() + => TestAsync(""" using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; @@ -2118,14 +1764,11 @@ public void OnCompleted(Action continuation) public bool IsCompleted { get { throw new NotImplementedException(); } } public void GetResult() { } } - """; - await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class C")); - } + """, MainDescription($"({CSharpFeaturesResources.awaitable}) class C")); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")] - public async Task TestTaskType() - { - var markup = """ + public Task TestTaskType() + => TestAsync(""" using System.Threading.Tasks; class C { @@ -2134,14 +1777,11 @@ public void Calc() Task$$ v1; } } - """; - await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task")); - } + """, MainDescription($"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task")); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")] - public async Task TestTaskOfTType() - { - var markup = """ + public Task TestTaskOfTType() + => TestAsync(""" using System; using System.Threading.Tasks; class C @@ -2151,18 +1791,15 @@ public void Calc() Task$$ v1; } } - """; - await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task"), + """, MainDescription($"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task"), TypeParameterMap($""" TResult {FeaturesResources.is_} int """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7100")] - public async Task TestDynamicIsntAwaitable() - { - var markup = """ + public Task TestDynamicIsntAwaitable() + => TestAsync(""" class C { @@ -2173,118 +1810,95 @@ void M() } } - """; - await TestAsync(markup, MainDescription("dynamic C.D()")); - } + """, MainDescription("dynamic C.D()")); [Fact] - public async Task TestStringLiteral() - { - await TestInMethodAsync(@"string f = ""Goo""$$", + public Task TestStringLiteral() + => TestInMethodAsync(@"string f = ""Goo""$$", MainDescription("class System.String")); - } [Fact] - public async Task TestStringLiteralUtf8_01() - { - await TestInMethodAsync(@"var f = ""Goo""u8$$", + public Task TestStringLiteralUtf8_01() + => TestInMethodAsync(@"var f = ""Goo""u8$$", TestSources.Span, MainDescription("readonly ref struct System.ReadOnlySpan"), TypeParameterMap($""" T {FeaturesResources.is_} byte """)); - } [Fact] - public async Task TestStringLiteralUtf8_02() - { - await TestInMethodAsync(@"var f = ""Goo""U8$$", + public Task TestStringLiteralUtf8_02() + => TestInMethodAsync(@"var f = ""Goo""U8$$", TestSources.Span, MainDescription("readonly ref struct System.ReadOnlySpan"), TypeParameterMap($""" T {FeaturesResources.is_} byte """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1280")] - public async Task TestVerbatimStringLiteral() - { - await TestInMethodAsync(@"string f = @""cat""$$", + public Task TestVerbatimStringLiteral() + => TestInMethodAsync(@"string f = @""cat""$$", MainDescription("class System.String")); - } [Fact] - public async Task TestVerbatimStringLiteralUtf8_01() - { - await TestInMethodAsync(@"string f = @""cat""u8$$", + public Task TestVerbatimStringLiteralUtf8_01() + => TestInMethodAsync(@"string f = @""cat""u8$$", TestSources.Span, MainDescription("readonly ref struct System.ReadOnlySpan"), TypeParameterMap($""" T {FeaturesResources.is_} byte """)); - } [Fact] - public async Task TestVerbatimStringLiteralUtf8_02() - { - await TestInMethodAsync(@"string f = @""cat""U8$$", + public Task TestVerbatimStringLiteralUtf8_02() + => TestInMethodAsync(@"string f = @""cat""U8$$", TestSources.Span, MainDescription("readonly ref struct System.ReadOnlySpan"), TypeParameterMap($""" T {FeaturesResources.is_} byte """)); - } [Fact] - public async Task TestRawStringLiteral() - { - await TestInMethodAsync(@"string f = """"""Goo""""""$$", + public Task TestRawStringLiteral() + => TestInMethodAsync(@"string f = """"""Goo""""""$$", MainDescription("class System.String")); - } [Fact] - public async Task TestRawStringLiteralUtf8_01() - { - await TestInMethodAsync(@"string f = """"""Goo""""""u8$$", + public Task TestRawStringLiteralUtf8_01() + => TestInMethodAsync(@"string f = """"""Goo""""""u8$$", TestSources.Span, MainDescription("readonly ref struct System.ReadOnlySpan"), TypeParameterMap($""" T {FeaturesResources.is_} byte """)); - } [Fact] - public async Task TestRawStringLiteralUtf8_02() - { - await TestInMethodAsync(@"string f = """"""Goo""""""U8$$", + public Task TestRawStringLiteralUtf8_02() + => TestInMethodAsync(@"string f = """"""Goo""""""U8$$", TestSources.Span, MainDescription("readonly ref struct System.ReadOnlySpan"), TypeParameterMap($""" T {FeaturesResources.is_} byte """)); - } [Fact] - public async Task TestRawStringLiteralMultiline() - { - await TestInMethodAsync("""" + public Task TestRawStringLiteralMultiline() + => TestInMethodAsync("""" string f = """ Goo """$$ """", MainDescription("class System.String")); - } [Fact] - public async Task TestRawStringLiteralMultilineUtf8_01() - { - await TestInMethodAsync("""" + public Task TestRawStringLiteralMultilineUtf8_01() + => TestInMethodAsync("""" string f = """ Goo """u8$$ @@ -2295,12 +1909,10 @@ await TestInMethodAsync("""" T {FeaturesResources.is_} byte """)); - } [Fact] - public async Task TestRawStringLiteralMultilineUtf8_02() - { - await TestInMethodAsync("""" + public Task TestRawStringLiteralMultilineUtf8_02() + => TestInMethodAsync("""" string f = """ Goo """U8$$ @@ -2311,7 +1923,6 @@ await TestInMethodAsync("""" T {FeaturesResources.is_} byte """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1280")] public async Task TestInterpolatedStringLiteral() @@ -2344,25 +1955,20 @@ await TestInMethodAsync(""" } [Fact] - public async Task TestCharLiteral() - { - await TestInMethodAsync(@"string f = 'x'$$", + public Task TestCharLiteral() + => TestInMethodAsync(@"string f = 'x'$$", MainDescription("struct System.Char")); - } [Fact] - public async Task DynamicKeyword() - { - await TestInMethodAsync( + public Task DynamicKeyword() + => TestInMethodAsync( @"dyn$$amic dyn;", MainDescription("dynamic"), Documentation(FeaturesResources.Represents_an_object_whose_operations_will_be_resolved_at_runtime)); - } [Fact] - public async Task DynamicField() - { - await TestInClassAsync( + public Task DynamicField() + => TestInClassAsync( """ dynamic dyn; @@ -2372,12 +1978,10 @@ void M() } """, MainDescription($"({FeaturesResources.field}) dynamic C.dyn")); - } [Fact] - public async Task LocalProperty_Minimal() - { - await TestInClassAsync( + public Task LocalProperty_Minimal() + => TestInClassAsync( """ DateTime Prop { get; set; } @@ -2387,12 +1991,10 @@ void M() } """, MainDescription("DateTime C.Prop { get; set; }")); - } [Fact] - public async Task LocalProperty_Minimal_PrivateSet() - { - await TestInClassAsync( + public Task LocalProperty_Minimal_PrivateSet() + => TestInClassAsync( """ public DateTime Prop { get; private set; } @@ -2402,12 +2004,10 @@ void M() } """, MainDescription("DateTime C.Prop { get; private set; }")); - } [Fact] - public async Task LocalProperty_Minimal_PrivateSet1() - { - await TestInClassAsync( + public Task LocalProperty_Minimal_PrivateSet1() + => TestInClassAsync( """ protected internal int Prop { get; private set; } @@ -2417,12 +2017,10 @@ void M() } """, MainDescription("int C.Prop { get; private set; }")); - } [Fact] - public async Task LocalProperty_Qualified() - { - await TestInClassAsync( + public Task LocalProperty_Qualified() + => TestInClassAsync( """ System.IO.FileInfo Prop { get; set; } @@ -2432,31 +2030,25 @@ void M() } """, MainDescription("System.IO.FileInfo C.Prop { get; set; }")); - } [Fact] - public async Task NonLocalProperty_Minimal() - { - await TestInMethodAsync(@"DateTime.No$$w.ToString();", + public Task NonLocalProperty_Minimal() + => TestInMethodAsync(@"DateTime.No$$w.ToString();", MainDescription("DateTime DateTime.Now { get; }")); - } [Fact] - public async Task NonLocalProperty_Qualified() - { - await TestInMethodAsync( + public Task NonLocalProperty_Qualified() + => TestInMethodAsync( """ System.IO.FileInfo f; f.Att$$ributes.ToString(); """, MainDescription("System.IO.FileAttributes System.IO.FileSystemInfo.Attributes { get; set; }")); - } [Fact] - public async Task ConstructedGenericProperty() - { - await TestAsync( + public Task ConstructedGenericProperty() + => TestAsync( """ class C { @@ -2472,12 +2064,10 @@ void M() } """, MainDescription("int C.Property { get; set; }")); - } [Fact] - public async Task UnconstructedGenericProperty() - { - await TestAsync( + public Task UnconstructedGenericProperty() + => TestAsync( """ class C { @@ -2490,12 +2080,10 @@ void M() } """, MainDescription("T C.Property { get; set; }")); - } [Fact] - public async Task ValueInProperty() - { - await TestInClassAsync( + public Task ValueInProperty() + => TestInClassAsync( """ public DateTime Property { @@ -2506,26 +2094,20 @@ public DateTime Property } """, MainDescription($"({FeaturesResources.parameter}) DateTime value")); - } [Fact] - public async Task EnumTypeName() - { - await TestInMethodAsync(@"Consol$$eColor c", + public Task EnumTypeName() + => TestInMethodAsync(@"Consol$$eColor c", MainDescription("enum System.ConsoleColor")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52490")] - public async Task EnumNonDefaultUnderlyingType_Definition() - { - await TestInClassAsync(@"enum E$$ : byte { A, B }", + public Task EnumNonDefaultUnderlyingType_Definition() + => TestInClassAsync(@"enum E$$ : byte { A, B }", MainDescription("enum C.E : byte")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52490")] - public async Task EnumNonDefaultUnderlyingType_AsField() - { - await TestInClassAsync(""" + public Task EnumNonDefaultUnderlyingType_AsField() + => TestInClassAsync(""" enum E : byte { A, B } @@ -2533,12 +2115,10 @@ enum E : byte { A, B } """, MainDescription("enum C.E : byte")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52490")] - public async Task EnumNonDefaultUnderlyingType_AsProperty() - { - await TestInClassAsync(""" + public Task EnumNonDefaultUnderlyingType_AsProperty() + => TestInClassAsync(""" enum E : byte { A, B } @@ -2546,12 +2126,10 @@ enum E : byte { A, B } """, MainDescription("enum C.E : byte")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52490")] - public async Task EnumNonDefaultUnderlyingType_AsParameter() - { - await TestInClassAsync(""" + public Task EnumNonDefaultUnderlyingType_AsParameter() + => TestInClassAsync(""" enum E : byte { A, B } @@ -2559,12 +2137,10 @@ private void M(E$$ e) { } """, MainDescription("enum C.E : byte")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52490")] - public async Task EnumNonDefaultUnderlyingType_AsReturnType() - { - await TestInClassAsync(""" + public Task EnumNonDefaultUnderlyingType_AsReturnType() + => TestInClassAsync(""" enum E : byte { A, B } @@ -2572,12 +2148,10 @@ enum E : byte { A, B } """, MainDescription("enum C.E : byte")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52490")] - public async Task EnumNonDefaultUnderlyingType_AsLocal() - { - await TestInClassAsync(""" + public Task EnumNonDefaultUnderlyingType_AsLocal() + => TestInClassAsync(""" enum E : byte { A, B } @@ -2588,12 +2162,10 @@ private void M() """, MainDescription("enum C.E : byte")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52490")] - public async Task EnumNonDefaultUnderlyingType_OnMemberAccessOnType() - { - await TestInClassAsync(""" + public Task EnumNonDefaultUnderlyingType_OnMemberAccessOnType() + => TestInClassAsync(""" enum EN : byte { A, B } @@ -2604,12 +2176,10 @@ private void M() """, MainDescription("enum C.EN : byte")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52490")] - public async Task EnumNonDefaultUnderlyingType_OnMemberAccessOnType_OnDot() - { - await TestInClassAsync(""" + public Task EnumNonDefaultUnderlyingType_OnMemberAccessOnType_OnDot() + => TestInClassAsync(""" enum E : byte { A, B } @@ -2620,12 +2190,10 @@ private void M() """, MainDescription("E.A = 0")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52490")] - public async Task EnumNonDefaultUnderlyingType_NotOnMemberAccessOnMember() - { - await TestInClassAsync(""" + public Task EnumNonDefaultUnderlyingType_NotOnMemberAccessOnMember() + => TestInClassAsync(""" enum E : byte { A, B } @@ -2636,7 +2204,6 @@ private void M() """, MainDescription("E.A = 0")); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/52490")] [InlineData("byte", "byte")] @@ -2654,9 +2221,8 @@ private void M() [InlineData("long", "System.Int64")] [InlineData("ulong", "ulong")] [InlineData("ulong", "System.UInt64")] - public async Task EnumNonDefaultUnderlyingType_ShowForNonDefaultTypes(string displayTypeName, string underlyingTypeName) - { - await TestInClassAsync($$""" + public Task EnumNonDefaultUnderlyingType_ShowForNonDefaultTypes(string displayTypeName, string underlyingTypeName) + => TestInClassAsync($$""" enum E$$ : {{underlyingTypeName}} { @@ -2664,15 +2230,13 @@ enum E$$ : {{underlyingTypeName}} } """, MainDescription($"enum C.E : {displayTypeName}")); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/52490")] [InlineData("")] [InlineData(": int")] [InlineData(": System.Int32")] - public async Task EnumNonDefaultUnderlyingType_DoNotShowForDefaultType(string defaultType) - { - await TestInClassAsync($$""" + public Task EnumNonDefaultUnderlyingType_DoNotShowForDefaultType(string defaultType) + => TestInClassAsync($$""" enum E$$ {{defaultType}} { @@ -2680,33 +2244,25 @@ enum E$$ {{defaultType}} } """, MainDescription("enum C.E")); - } [Fact] - public async Task EnumMemberNameFromMetadata() - { - await TestInMethodAsync(@"ConsoleColor c = ConsoleColor.Bla$$ck", + public Task EnumMemberNameFromMetadata() + => TestInMethodAsync(@"ConsoleColor c = ConsoleColor.Bla$$ck", MainDescription("ConsoleColor.Black = 0")); - } [Fact] - public async Task FlagsEnumMemberNameFromMetadata1() - { - await TestInMethodAsync(@"AttributeTargets a = AttributeTargets.Cl$$ass", + public Task FlagsEnumMemberNameFromMetadata1() + => TestInMethodAsync(@"AttributeTargets a = AttributeTargets.Cl$$ass", MainDescription("AttributeTargets.Class = 4")); - } [Fact] - public async Task FlagsEnumMemberNameFromMetadata2() - { - await TestInMethodAsync(@"AttributeTargets a = AttributeTargets.A$$ll", + public Task FlagsEnumMemberNameFromMetadata2() + => TestInMethodAsync(@"AttributeTargets a = AttributeTargets.A$$ll", MainDescription("AttributeTargets.All = AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Delegate | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter")); - } [Fact] - public async Task EnumMemberNameFromSource1() - { - await TestAsync( + public Task EnumMemberNameFromSource1() + => TestAsync( """ enum E { @@ -2723,13 +2279,11 @@ void M() } } """, -MainDescription("E.B = 1 << 1")); - } + MainDescription("E.B = 1 << 1")); [Fact] - public async Task EnumMemberNameFromSource2() - { - await TestAsync( + public Task EnumMemberNameFromSource2() + => TestAsync( """ enum E { @@ -2746,46 +2300,36 @@ void M() } } """, -MainDescription("E.B = 1")); - } + MainDescription("E.B = 1")); [Fact] - public async Task Parameter_InMethod_Minimal() - { - await TestInClassAsync( + public Task Parameter_InMethod_Minimal() + => TestInClassAsync( """ void M(DateTime dt) { d$$t.ToString(); """, MainDescription($"({FeaturesResources.parameter}) DateTime dt")); - } [Fact] - public async Task Parameter_InMethod_Qualified() - { - await TestInClassAsync( + public Task Parameter_InMethod_Qualified() + => TestInClassAsync( """ void M(System.IO.FileInfo fileInfo) { file$$Info.ToString(); """, MainDescription($"({FeaturesResources.parameter}) System.IO.FileInfo fileInfo")); - } [Fact] - public async Task Parameter_FromReferenceToNamedParameter() - { - await TestInMethodAsync(@"Console.WriteLine(va$$lue: ""Hi"");", + public Task Parameter_FromReferenceToNamedParameter() + => TestInMethodAsync(@"Console.WriteLine(va$$lue: ""Hi"");", MainDescription($"({FeaturesResources.parameter}) string value")); - } [Fact] - public async Task Parameter_DefaultValue() - { - // NOTE: Dev10 doesn't show the default value, but it would be nice if we did. - // NOTE: The "DefaultValue" property isn't implemented yet. - await TestInClassAsync( + public Task Parameter_DefaultValue() + => TestInClassAsync( """ void M(int param = 42) { @@ -2793,60 +2337,50 @@ void M(int param = 42) } """, MainDescription($"({FeaturesResources.parameter}) int param = 42")); - } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] - public async Task Lambda_Parameter_DefaultValue_01() - { - await TestInMethodAsync( + public Task Lambda_Parameter_DefaultValue_01() + => TestInMethodAsync( """ (int param = 42) => { return para$$m + 1; } """, -MainDescription($"({FeaturesResources.parameter}) int param = 42")); - } + MainDescription($"({FeaturesResources.parameter}) int param = 42")); [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] - public async Task Lambda_Parameter_DefaultValue_02() - { - await TestInMethodAsync( + public Task Lambda_Parameter_DefaultValue_02() + => TestInMethodAsync( """ (int param = $$int.MaxValue) => { return param + 1; } """, -MainDescription($"{FeaturesResources.struct_} System.Int32")); - } + MainDescription($"{FeaturesResources.struct_} System.Int32")); [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] - public async Task Lambda_Parameter_DefaultValue_03() - { - await TestInMethodAsync( + public Task Lambda_Parameter_DefaultValue_03() + => TestInMethodAsync( """ (int param = int.$$MaxValue) => { return param + 1; } """, -MainDescription($"({FeaturesResources.constant}) const int int.MaxValue = 2147483647")); - } + MainDescription($"({FeaturesResources.constant}) const int int.MaxValue = 2147483647")); [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] - public async Task Lambda_Parameter_ParamsArray() - { - await TestInMethodAsync( + public Task Lambda_Parameter_ParamsArray() + => TestInMethodAsync( """ (params int[] xs) => { return x$$s.Length; } """, -MainDescription($"({FeaturesResources.parameter}) params int[] xs")); - } + MainDescription($"({FeaturesResources.parameter}) params int[] xs")); [Fact] - public async Task Parameter_Params() - { - await TestInClassAsync( + public Task Parameter_Params() + => TestInClassAsync( """ void M(params DateTime[] arg) { @@ -2854,12 +2388,10 @@ void M(params DateTime[] arg) } """, MainDescription($"({FeaturesResources.parameter}) params DateTime[] arg")); - } [Fact] - public async Task Parameter_Ref() - { - await TestInClassAsync( + public Task Parameter_Ref() + => TestInClassAsync( """ void M(ref DateTime arg) { @@ -2867,12 +2399,10 @@ void M(ref DateTime arg) } """, MainDescription($"({FeaturesResources.parameter}) ref DateTime arg")); - } [Fact] - public async Task Parameter_Out() - { - await TestInClassAsync( + public Task Parameter_Out() + => TestInClassAsync( """ void M(out DateTime arg) { @@ -2880,43 +2410,35 @@ void M(out DateTime arg) } """, MainDescription($"({FeaturesResources.parameter}) out DateTime arg")); - } [Fact] - public async Task Local_Minimal() - { - await TestInMethodAsync( + public Task Local_Minimal() + => TestInMethodAsync( """ DateTime dt; d$$t.ToString(); """, MainDescription($"({FeaturesResources.local_variable}) DateTime dt")); - } [Fact] - public async Task Local_Qualified() - { - await TestInMethodAsync( + public Task Local_Qualified() + => TestInMethodAsync( """ System.IO.FileInfo fileInfo; file$$Info.ToString(); """, MainDescription($"({FeaturesResources.local_variable}) System.IO.FileInfo fileInfo")); - } [Fact] - public async Task Method_MetadataOverload() - { - await TestInMethodAsync("Console.Write$$Line();", + public Task Method_MetadataOverload() + => TestInMethodAsync("Console.Write$$Line();", MainDescription($"void Console.WriteLine() (+ 18 {FeaturesResources.overloads_})")); - } [Fact] - public async Task Method_SimpleWithOverload() - { - await TestInClassAsync( + public Task Method_SimpleWithOverload() + => TestInClassAsync( """ void Method() { @@ -2928,12 +2450,10 @@ void Method(int i) } """, MainDescription($"void C.Method() (+ 1 {FeaturesResources.overload})")); - } [Fact] - public async Task Method_MoreOverloads() - { - await TestInClassAsync( + public Task Method_MoreOverloads() + => TestInClassAsync( """ void Method() { @@ -2953,12 +2473,10 @@ void Method(System.IO.FileInfo fileInfo) } """, MainDescription($"void C.Method(System.IO.FileInfo fileInfo) (+ 3 {FeaturesResources.overloads_})")); - } [Fact] - public async Task Method_SimpleInSameClass() - { - await TestInClassAsync( + public Task Method_SimpleInSameClass() + => TestInClassAsync( """ DateTime GetDate(System.IO.FileInfo ft) { @@ -2966,12 +2484,10 @@ DateTime GetDate(System.IO.FileInfo ft) } """, MainDescription("DateTime C.GetDate(System.IO.FileInfo ft)")); - } [Fact] - public async Task Method_OptionalParameter() - { - await TestInClassAsync( + public Task Method_OptionalParameter() + => TestInClassAsync( """ void M() { @@ -2983,26 +2499,20 @@ void Method(int i = 0) } """, MainDescription("void C.Method([int i = 0])")); - } [Fact] - public async Task Method_OptionalDecimalParameter() - { - await TestInClassAsync( + public Task Method_OptionalDecimalParameter() + => TestInClassAsync( """ void Goo(decimal x$$yz = 10) { } """, MainDescription($"({FeaturesResources.parameter}) decimal xyz = 10")); - } [Fact] - public async Task Method_Generic() - { - // Generic method don't get the instantiation info yet. NOTE: We don't display - // constraint info in Dev10. Should we? - await TestInClassAsync( + public Task Method_Generic() + => TestInClassAsync( """ TOut Goo(TIn arg) where TIn : IEquatable { @@ -3011,12 +2521,10 @@ TOut Goo(TIn arg) where TIn : IEquatable """, MainDescription("DateTime C.Goo(int arg)")); - } [Fact] - public async Task Method_UnconstructedGeneric() - { - await TestInClassAsync( + public Task Method_UnconstructedGeneric() + => TestInClassAsync( """ TOut Goo(TIn arg) { @@ -3025,12 +2533,10 @@ TOut Goo(TIn arg) """, MainDescription("TOut C.Goo(TIn arg)")); - } [Fact] - public async Task Method_Inferred() - { - await TestInClassAsync( + public Task Method_Inferred() + => TestInClassAsync( """ void Goo(TIn arg) { @@ -3038,12 +2544,10 @@ void Goo(TIn arg) } """, MainDescription("void C.Goo(int arg)")); - } [Fact] - public async Task Method_MultipleParams() - { - await TestInClassAsync( + public Task Method_MultipleParams() + => TestInClassAsync( """ void Goo(DateTime dt, System.IO.FileInfo fi, int number) { @@ -3051,13 +2555,10 @@ void Goo(DateTime dt, System.IO.FileInfo fi, int number) } """, MainDescription("void C.Goo(DateTime dt, System.IO.FileInfo fi, int number)")); - } [Fact] - public async Task Method_OptionalParam() - { - // NOTE - Default values aren't actually returned by symbols yet. - await TestInClassAsync( + public Task Method_OptionalParam() + => TestInClassAsync( """ void Goo(int num = 42) { @@ -3065,13 +2566,10 @@ void Goo(int num = 42) } """, MainDescription("void C.Goo([int num = 42])")); - } [Fact] - public async Task Method_ParameterModifiers() - { - // NOTE - Default values aren't actually returned by symbols yet. - await TestInClassAsync( + public Task Method_ParameterModifiers() + => TestInClassAsync( """ void Goo(ref DateTime dt, out System.IO.FileInfo fi, params int[] numbers) { @@ -3079,12 +2577,10 @@ void Goo(ref DateTime dt, out System.IO.FileInfo fi, params int[] numbers) } """, MainDescription("void C.Goo(ref DateTime dt, out System.IO.FileInfo fi, params int[] numbers)")); - } [Fact] - public async Task Method_RefReadonly() - { - await TestInClassAsync( + public Task Method_RefReadonly() + => TestInClassAsync( """ void Goo(ref readonly DateTime dt, ref readonly System.IO.FileInfo fi, params int[] numbers) { @@ -3092,12 +2588,10 @@ void Goo(ref readonly DateTime dt, ref readonly System.IO.FileInfo fi, params in } """, MainDescription("void C.Goo(ref readonly DateTime dt, ref readonly System.IO.FileInfo fi, params int[] numbers)")); - } [Fact] - public async Task Constructor() - { - await TestInClassAsync( + public Task Constructor() + => TestInClassAsync( """ public C() { @@ -3109,12 +2603,10 @@ void M() } """, MainDescription("C.C()")); - } [Fact] - public async Task Constructor_Overloads() - { - await TestInClassAsync( + public Task Constructor_Overloads() + => TestInClassAsync( """ public C() { @@ -3134,64 +2626,52 @@ void M() } """, MainDescription($"C.C(DateTime dt) (+ 2 {FeaturesResources.overloads_})")); - } /// /// Regression for 3923 /// [Fact] - public async Task Constructor_OverloadFromStringLiteral() - { - await TestInMethodAsync( + public Task Constructor_OverloadFromStringLiteral() + => TestInMethodAsync( @"new InvalidOperatio$$nException("""");", MainDescription($"InvalidOperationException.InvalidOperationException(string message) (+ 2 {FeaturesResources.overloads_})")); - } /// /// Regression for 3923 /// [Fact] - public async Task Constructor_UnknownType() - { - await TestInvalidTypeInClassAsync( + public Task Constructor_UnknownType() + => TestInvalidTypeInClassAsync( """ void M() { new G$$oo(); } """); - } /// /// Regression for 3923 /// [Fact] - public async Task Constructor_OverloadFromProperty() - { - await TestInMethodAsync( + public Task Constructor_OverloadFromProperty() + => TestInMethodAsync( @"new InvalidOperatio$$nException(this.GetType().Name);", MainDescription($"InvalidOperationException.InvalidOperationException(string message) (+ 2 {FeaturesResources.overloads_})")); - } [Fact] - public async Task Constructor_Metadata() - { - await TestInMethodAsync( + public Task Constructor_Metadata() + => TestInMethodAsync( @"new Argument$$NullException();", MainDescription($"ArgumentNullException.ArgumentNullException() (+ 3 {FeaturesResources.overloads_})")); - } [Fact] - public async Task Constructor_MetadataQualified() - { - await TestInMethodAsync(@"new System.IO.File$$Info(null);", + public Task Constructor_MetadataQualified() + => TestInMethodAsync(@"new System.IO.File$$Info(null);", MainDescription("System.IO.FileInfo.FileInfo(string fileName)")); - } [Fact] - public async Task InterfaceProperty() - { - await TestInMethodAsync( + public Task InterfaceProperty() + => TestInMethodAsync( """ interface I { @@ -3199,12 +2679,10 @@ interface I } """, MainDescription("string I.Name { get; set; }")); - } [Fact] - public async Task ExplicitInterfacePropertyImplementation() - { - await TestInMethodAsync( + public Task ExplicitInterfacePropertyImplementation() + => TestInMethodAsync( """ interface I { @@ -3227,12 +2705,10 @@ string IEmployee.Name$$ } """, MainDescription("string C.Name { get; set; }")); - } [Fact] - public async Task Operator() - { - await TestInClassAsync( + public Task Operator() + => TestInClassAsync( """ public static C operator +(C left, C right) { @@ -3245,15 +2721,13 @@ void M(C left, C right) } """, MainDescription("C C.operator +(C left, C right)")); - } #pragma warning disable CA2243 // Attribute string literals should parse correctly [WorkItem(792629, "generic type parameter constraints for methods in quick info")] #pragma warning restore CA2243 // Attribute string literals should parse correctly [Fact] - public async Task GenericMethodWithConstraintsAtDeclaration() - { - await TestInClassAsync( + public Task GenericMethodWithConstraintsAtDeclaration() + => TestInClassAsync( """ TOut G$$oo(TIn arg) where TIn : IEquatable { @@ -3261,15 +2735,13 @@ await TestInClassAsync( """, MainDescription("TOut C.Goo(TIn arg) where TIn : IEquatable")); - } #pragma warning disable CA2243 // Attribute string literals should parse correctly [WorkItem(792629, "generic type parameter constraints for methods in quick info")] #pragma warning restore CA2243 // Attribute string literals should parse correctly [Fact] - public async Task GenericMethodWithMultipleConstraintsAtDeclaration() - { - await TestInClassAsync( + public Task GenericMethodWithMultipleConstraintsAtDeclaration() + => TestInClassAsync( """ TOut Goo(TIn arg) where TIn : Employee, new() { @@ -3278,15 +2750,13 @@ await TestInClassAsync( """, MainDescription("TOut C.Goo(TIn arg) where TIn : Employee, new()")); - } #pragma warning disable CA2243 // Attribute string literals should parse correctly [WorkItem(792629, "generic type parameter constraints for methods in quick info")] #pragma warning restore CA2243 // Attribute string literals should parse correctly [Fact] - public async Task UnConstructedGenericMethodWithConstraintsAtInvocation() - { - await TestInClassAsync( + public Task UnConstructedGenericMethodWithConstraintsAtInvocation() + => TestInClassAsync( """ TOut Goo(TIn arg) where TIn : Employee { @@ -3295,12 +2765,10 @@ TOut Goo(TIn arg) where TIn : Employee """, MainDescription("TOut C.Goo(TIn arg) where TIn : Employee")); - } [Fact] - public async Task GenericTypeWithConstraintsAtDeclaration() - { - await TestAsync( + public Task GenericTypeWithConstraintsAtDeclaration() + => TestAsync( """ public class Employee : IComparable { @@ -3316,12 +2784,10 @@ public int CompareTo(Employee other) """, MainDescription("class EmployeeList where T : Employee, System.IComparable, new()")); - } [Fact] - public async Task GenericType() - { - await TestAsync( + public Task GenericType() + => TestAsync( """ class T1 { @@ -3329,12 +2795,10 @@ class T1 } """, MainDescription($"T11 {FeaturesResources.in_} T1")); - } [Fact] - public async Task GenericMethod() - { - await TestInClassAsync( + public Task GenericMethod() + => TestInClassAsync( """ static void Meth1(T1 i) where T1 : struct { @@ -3342,23 +2806,19 @@ static void Meth1(T1 i) where T1 : struct } """, MainDescription($"T1 {FeaturesResources.in_} C.Meth1 where T1 : struct")); - } [Fact] - public async Task Var() - { - await TestInMethodAsync( + public Task Var() + => TestInMethodAsync( """ var x = new Exception(); var y = $$x; """, MainDescription($"({FeaturesResources.local_variable}) Exception x")); - } [Fact] - public async Task NullableReference() - { - await TestWithOptionsAsync( + public Task NullableReference() + => TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp8), """ class A @@ -3376,12 +2836,12 @@ static void M() """, // https://github.com/dotnet/roslyn/issues/26198 public API should show inferred nullability MainDescription($"({FeaturesResources.local_variable}) A y")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26648")] - public async Task NullableReference_InMethod() - { - var code = """ + public Task NullableReference_InMethod() + => TestWithOptionsAsync( + Options.Regular.WithLanguageVersion(LanguageVersion.CSharp8), + """ class G { @@ -3397,28 +2857,21 @@ public class C { } } - """; - await TestWithOptionsAsync( - Options.Regular.WithLanguageVersion(LanguageVersion.CSharp8), - code, MainDescription("string? C.Goo(IEnumerable arg)")); - } + """, MainDescription("string? C.Goo(IEnumerable arg)")); [Fact] - public async Task NestedInGeneric() - { - await TestInMethodAsync( + public Task NestedInGeneric() + => TestInMethodAsync( @"List.Enu$$merator e;", MainDescription("struct System.Collections.Generic.List.Enumerator"), TypeParameterMap($""" T {FeaturesResources.is_} int """)); - } [Fact] - public async Task NestedGenericInGeneric() - { - await TestAsync( + public Task NestedGenericInGeneric() + => TestAsync( """ class Outer { @@ -3439,12 +2892,10 @@ static void M() T {FeaturesResources.is_} int """, $"U {FeaturesResources.is_} string"))); - } [Fact] - public async Task ObjectInitializer1() - { - await TestInClassAsync( + public Task ObjectInitializer1() + => TestInClassAsync( """ void M() { @@ -3457,12 +2908,10 @@ class test } """, MainDescription($"({FeaturesResources.field}) int test.z")); - } [Fact] - public async Task ObjectInitializer2() - { - await TestInMethodAsync( + public Task ObjectInitializer2() + => TestInMethodAsync( """ class C { @@ -3478,12 +2927,10 @@ class test } """, MainDescription("struct System.Int32")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537880")] - public async Task TypeArgument() - { - await TestAsync( + public Task TypeArgument() + => TestAsync( """ class C { @@ -3495,12 +2942,10 @@ void M() } """, MainDescription($"({FeaturesResources.local_variable}) C variable")); - } [Fact] - public async Task ForEachLoop_1() - { - await TestInMethodAsync( + public Task ForEachLoop_1() + => TestInMethodAsync( """ int bb = 555; @@ -3511,12 +2956,10 @@ await TestInMethodAsync( } """, MainDescription($"({FeaturesResources.local_variable}) int cc")); - } [Fact] - public async Task TryCatchFinally_1() - { - await TestInMethodAsync( + public Task TryCatchFinally_1() + => TestInMethodAsync( """ try { @@ -3532,12 +2975,10 @@ await TestInMethodAsync( } """, MainDescription($"({FeaturesResources.local_variable}) int aa")); - } [Fact] - public async Task TryCatchFinally_2() - { - await TestInMethodAsync( + public Task TryCatchFinally_2() + => TestInMethodAsync( """ try { @@ -3552,12 +2993,10 @@ await TestInMethodAsync( } """, MainDescription($"({FeaturesResources.local_variable}) Exception ex")); - } [Fact] - public async Task TryCatchFinally_3() - { - await TestInMethodAsync( + public Task TryCatchFinally_3() + => TestInMethodAsync( """ try { @@ -3573,12 +3012,10 @@ await TestInMethodAsync( } """, MainDescription($"({FeaturesResources.local_variable}) int aa")); - } [Fact] - public async Task TryCatchFinally_4() - { - await TestInMethodAsync( + public Task TryCatchFinally_4() + => TestInMethodAsync( """ try { @@ -3594,12 +3031,10 @@ await TestInMethodAsync( } """, MainDescription($"({FeaturesResources.local_variable}) int aa")); - } [Fact] - public async Task GenericVariable() - { - await TestAsync( + public Task GenericVariable() + => TestAsync( """ class C { @@ -3611,12 +3046,10 @@ void M() } """, MainDescription($"({FeaturesResources.local_variable}) C variable")); - } [Fact] - public async Task TestInstantiation() - { - await TestAsync( + public Task TestInstantiation() + => TestAsync( """ using System.Collections.Generic; @@ -3629,12 +3062,10 @@ static void Main(string[] args) } """, MainDescription($"Dictionary.Dictionary() (+ 5 {FeaturesResources.overloads_})")); - } [Fact] - public async Task TestUsingAlias_Bug4141() - { - await TestAsync( + public Task TestUsingAlias_Bug4141() + => TestAsync( """ using X = A.C; @@ -3650,28 +3081,22 @@ class D : X$$ } """, MainDescription(@"class A.C")); - } [Fact] - public async Task TestFieldOnDeclaration() - { - await TestInClassAsync( + public Task TestFieldOnDeclaration() + => TestInClassAsync( @"DateTime fie$$ld;", MainDescription($"({FeaturesResources.field}) DateTime C.field")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538767")] - public async Task TestGenericErrorFieldOnDeclaration() - { - await TestInClassAsync( + public Task TestGenericErrorFieldOnDeclaration() + => TestInClassAsync( @"NonExistentType fi$$eld;", MainDescription($"({FeaturesResources.field}) NonExistentType C.field")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538822")] - public async Task TestDelegateType() - { - await TestInClassAsync( + public Task TestDelegateType() + => TestInClassAsync( @"Fun$$c field;", MainDescription("delegate TResult System.Func(T arg)"), TypeParameterMap( @@ -3680,12 +3105,10 @@ await TestInClassAsync( T {FeaturesResources.is_} int """, $"TResult {FeaturesResources.is_} string"))); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538824")] - public async Task TestOnDelegateInvocation() - { - await TestAsync( + public Task TestOnDelegateInvocation() + => TestAsync( """ class Program { @@ -3699,12 +3122,10 @@ static void Main() } """, MainDescription($"({FeaturesResources.local_variable}) D1 d")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539240")] - public async Task TestOnArrayCreation1() - { - await TestAsync( + public Task TestOnArrayCreation1() + => TestAsync( """ class Program { @@ -3714,12 +3135,10 @@ static void Main() } } """, MainDescription("int[]")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539240")] - public async Task TestOnArrayCreation2() - { - await TestAsync( + public Task TestOnArrayCreation2() + => TestAsync( """ class Program { @@ -3730,12 +3149,10 @@ static void Main() } """, MainDescription("struct System.Int32")); - } [Fact] - public async Task Constructor_ImplicitObjectCreation() - { - await TestAsync( + public Task Constructor_ImplicitObjectCreation() + => TestAsync( """ class C { @@ -3747,12 +3164,10 @@ static void Main() """, MainDescription("C.C()")); - } [Fact] - public async Task Constructor_ImplicitObjectCreation_WithParameters() - { - await TestAsync( + public Task Constructor_ImplicitObjectCreation_WithParameters() + => TestAsync( """ class C { @@ -3766,12 +3181,10 @@ static void Main() """, MainDescription($"C.C(int i) (+ 1 {FeaturesResources.overload})")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539841")] - public async Task TestIsNamedTypeAccessibleForErrorTypes() - { - await TestAsync( + public Task TestIsNamedTypeAccessibleForErrorTypes() + => TestAsync( """ sealed class B : A> { @@ -3785,12 +3198,10 @@ internal class A } """, MainDescription("class A")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540075")] - public async Task TestErrorType() - { - await TestAsync( + public Task TestErrorType() + => TestAsync( """ using Goo = Goo; @@ -3803,12 +3214,10 @@ void Main() } """, MainDescription("Goo")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16662")] - public async Task TestShortDiscardInAssignment() - { - await TestAsync( + public Task TestShortDiscardInAssignment() + => TestAsync( """ class C { @@ -3819,12 +3228,10 @@ int M() } """, MainDescription($"({FeaturesResources.discard}) int _")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16662")] - public async Task TestUnderscoreLocalInAssignment() - { - await TestAsync( + public Task TestUnderscoreLocalInAssignment() + => TestAsync( """ class C { @@ -3835,12 +3242,10 @@ int M() } """, MainDescription($"({FeaturesResources.local_variable}) int _")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16662")] - public async Task TestShortDiscardInOutVar() - { - await TestAsync( + public Task TestShortDiscardInOutVar() + => TestAsync( """ class C { @@ -3852,12 +3257,10 @@ void M(out int i) } """, MainDescription($"({FeaturesResources.discard}) int _")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16667")] - public async Task TestDiscardInOutVar() - { - await TestAsync( + public Task TestDiscardInOutVar() + => TestAsync( """ class C { @@ -3868,12 +3271,10 @@ void M(out int i) } } """); // No quick info (see issue #16667) - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16667")] - public async Task TestDiscardInIsPattern() - { - await TestAsync( + public Task TestDiscardInIsPattern() + => TestAsync( """ class C { @@ -3883,12 +3284,10 @@ void M() } } """); // No quick info (see issue #16667) - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16667")] - public async Task TestDiscardInSwitchPattern() - { - await TestAsync( + public Task TestDiscardInSwitchPattern() + => TestAsync( """ class C { @@ -3902,12 +3301,10 @@ void M() } } """); // No quick info (see issue #16667) - } [Fact] - public async Task TestLambdaDiscardParameter_FirstDiscard() - { - await TestAsync( + public Task TestLambdaDiscardParameter_FirstDiscard() + => TestAsync( """ class C { @@ -3918,12 +3315,10 @@ void M() } """, MainDescription($"({FeaturesResources.discard}) string _")); - } [Fact] - public async Task TestLambdaDiscardParameter_SecondDiscard() - { - await TestAsync( + public Task TestLambdaDiscardParameter_SecondDiscard() + => TestAsync( """ class C { @@ -3934,12 +3329,10 @@ void M() } """, MainDescription($"({FeaturesResources.discard}) int _")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540871")] - public async Task TestLiterals() - { - await TestAsync( + public Task TestLiterals() + => TestAsync( """ class MyClass { @@ -3961,12 +3354,10 @@ public static int Main() } """, MainDescription("struct System.Int32")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541444")] - public async Task TestErrorInForeach() - { - await TestAsync( + public Task TestErrorInForeach() + => TestAsync( """ class C { @@ -3980,12 +3371,10 @@ void Main() } """, MainDescription($"({FeaturesResources.local_variable}) int cc")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541678")] - public async Task TestQuickInfoOnEvent() - { - await TestAsync( + public Task TestQuickInfoOnEvent() + => TestAsync( """ using System; @@ -4013,33 +3402,25 @@ protected virtual void RaiseSampleEvent() } """, MainDescription("SampleEventHandler Publisher.SampleEvent")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")] - public async Task TestEvent() - { - await TestInMethodAsync(@"System.Console.CancelKeyPres$$s += null;", + public Task TestEvent() + => TestInMethodAsync(@"System.Console.CancelKeyPres$$s += null;", MainDescription("ConsoleCancelEventHandler Console.CancelKeyPress")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")] - public async Task TestEventPlusEqualsOperator() - { - await TestInMethodAsync(@"System.Console.CancelKeyPress +$$= null;", + public Task TestEventPlusEqualsOperator() + => TestInMethodAsync(@"System.Console.CancelKeyPress +$$= null;", MainDescription("void Console.CancelKeyPress.add")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")] - public async Task TestEventMinusEqualsOperator() - { - await TestInMethodAsync(@"System.Console.CancelKeyPress -$$= null;", + public Task TestEventMinusEqualsOperator() + => TestInMethodAsync(@"System.Console.CancelKeyPress -$$= null;", MainDescription("void Console.CancelKeyPress.remove")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541885")] - public async Task TestQuickInfoOnExtensionMethod() - { - await TestWithOptionsAsync(Options.Regular, + public Task TestQuickInfoOnExtensionMethod() + => TestWithOptionsAsync(Options.Regular, """ using System; using System.Collections.Generic; @@ -4065,12 +3446,10 @@ public static bool In(this T o, IEnumerable items) } """, MainDescription($"({CSharpFeaturesResources.extension}) bool int.In(IEnumerable items)")); - } [Fact] - public async Task TestQuickInfoOnExtensionMethodOverloads() - { - await TestWithOptionsAsync(Options.Regular, + public Task TestQuickInfoOnExtensionMethodOverloads() + => TestWithOptionsAsync(Options.Regular, """ using System; using System.Linq; @@ -4099,12 +3478,10 @@ public static void TestExt(this string ex, int arg) } """, MainDescription($"({CSharpFeaturesResources.extension}) void string.TestExt() (+ 2 {FeaturesResources.overloads_})")); - } [Fact] - public async Task TestQuickInfoOnExtensionMethodOverloads2() - { - await TestWithOptionsAsync(Options.Regular, + public Task TestQuickInfoOnExtensionMethodOverloads2() + => TestWithOptionsAsync(Options.Regular, """ using System; using System.Linq; @@ -4133,12 +3510,10 @@ public static void TestExt(this int ex, int arg) } """, MainDescription($"({CSharpFeaturesResources.extension}) void string.TestExt() (+ 1 {FeaturesResources.overload})")); - } [Fact] - public async Task Query1() - { - await TestAsync( + public Task Query1() + => TestAsync( """ using System.Linq; @@ -4153,12 +3528,10 @@ void M() } """, MainDescription($"({FeaturesResources.range_variable}) int n")); - } [Fact] - public async Task Query2() - { - await TestAsync( + public Task Query2() + => TestAsync( """ using System.Linq; @@ -4173,12 +3546,10 @@ void M() } """, MainDescription($"({FeaturesResources.range_variable}) int n")); - } [Fact] - public async Task Query3() - { - await TestAsync( + public Task Query3() + => TestAsync( """ class C { @@ -4191,12 +3562,10 @@ void M() } """, MainDescription($"({FeaturesResources.range_variable}) ? n")); - } [Fact] - public async Task Query4() - { - await TestAsync( + public Task Query4() + => TestAsync( """ class C { @@ -4209,12 +3578,10 @@ void M() } """, MainDescription($"({FeaturesResources.range_variable}) ? n")); - } [Fact] - public async Task Query5() - { - await TestAsync( + public Task Query5() + => TestAsync( """ using System.Collections.Generic; using System.Linq; @@ -4229,12 +3596,10 @@ void M() } """, MainDescription($"({FeaturesResources.range_variable}) object n")); - } [Fact] - public async Task Query6() - { - await TestAsync( + public Task Query6() + => TestAsync( """ using System.Collections.Generic; using System.Linq; @@ -4249,12 +3614,10 @@ void M() } """, MainDescription($"({FeaturesResources.range_variable}) object n")); - } [Fact] - public async Task Query7() - { - await TestAsync( + public Task Query7() + => TestAsync( """ using System.Collections.Generic; using System.Linq; @@ -4269,12 +3632,10 @@ void M() } """, MainDescription($"({FeaturesResources.range_variable}) int n")); - } [Fact] - public async Task Query8() - { - await TestAsync( + public Task Query8() + => TestAsync( """ using System.Collections.Generic; using System.Linq; @@ -4289,12 +3650,10 @@ void M() } """, MainDescription($"({FeaturesResources.range_variable}) int n")); - } [Fact] - public async Task Query9() - { - await TestAsync( + public Task Query9() + => TestAsync( """ using System.Collections.Generic; using System.Linq; @@ -4310,12 +3669,10 @@ from y in x } """, MainDescription($"({FeaturesResources.range_variable}) List x")); - } [Fact] - public async Task Query10() - { - await TestAsync( + public Task Query10() + => TestAsync( """ using System.Collections.Generic; using System.Linq; @@ -4331,12 +3688,10 @@ from y in $$x } """, MainDescription($"({FeaturesResources.range_variable}) List x")); - } [Fact] - public async Task Query11() - { - await TestAsync( + public Task Query11() + => TestAsync( """ using System.Collections.Generic; using System.Linq; @@ -4352,12 +3707,10 @@ from y$$ in x } """, MainDescription($"({FeaturesResources.range_variable}) int y")); - } [Fact] - public async Task Query12() - { - await TestAsync( + public Task Query12() + => TestAsync( """ using System.Collections.Generic; using System.Linq; @@ -4373,38 +3726,32 @@ from y in x } """, MainDescription($"({FeaturesResources.range_variable}) int y")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoSelectMappedEnumerable() - { - await TestInMethodAsync( + public Task QueryMethodinfoSelectMappedEnumerable() + => TestInMethodAsync( """ var q = from i in new int[0] $$select i; """, - MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable IEnumerable.Select(Func selector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable IEnumerable.Select(Func selector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoSelectMappedQueryable() - { - await TestInMethodAsync( + public Task QueryMethodinfoSelectMappedQueryable() + => TestInMethodAsync( """ var q = from i in new int[0].AsQueryable() $$select i; """, - MainDescription($"({CSharpFeaturesResources.extension}) IQueryable IQueryable.Select(System.Linq.Expressions.Expression> selector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IQueryable IQueryable.Select(System.Linq.Expressions.Expression> selector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoSelectMappedCustom() - { - await TestAsync( + public Task QueryMethodinfoSelectMappedCustom() + => TestAsync( """ using System; @@ -4427,13 +3774,11 @@ public void M() } """, - MainDescription($"({CSharpFeaturesResources.extension}) Lazy Lazy.Select(Func selector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) Lazy Lazy.Select(Func selector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoSelectNotMapped() - { - await TestInMethodAsync( + public Task QueryMethodinfoSelectNotMapped() + => TestInMethodAsync( """ var q = from i in new int[0] @@ -4441,12 +3786,10 @@ where true $$select i; """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoLet() - { - await TestInMethodAsync( + public Task QueryMethodinfoLet() + => TestInMethodAsync( """ var q = from i in new int[0] @@ -4454,18 +3797,16 @@ await TestInMethodAsync( select i; """, - MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<'a> IEnumerable.Select(Func selector)"), + MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<'a> IEnumerable.Select(Func selector)"), AnonymousTypes($$""" {{FeaturesResources.Types_colon}} 'a {{FeaturesResources.is_}} new { int i, bool j } """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoWhere() - { - await TestInMethodAsync( + public Task QueryMethodinfoWhere() + => TestInMethodAsync( """ var q = from i in new int[0] @@ -4473,13 +3814,11 @@ await TestInMethodAsync( select i; """, - MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable IEnumerable.Where(Func predicate)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable IEnumerable.Where(Func predicate)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoOrderByOneProperty() - { - await TestInMethodAsync( + public Task QueryMethodinfoOrderByOneProperty() + => TestInMethodAsync( """ var q = from i in new int[0] @@ -4487,13 +3826,11 @@ await TestInMethodAsync( select i; """, - MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable IEnumerable.OrderBy(Func keySelector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable IEnumerable.OrderBy(Func keySelector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoOrderByOnePropertyWithOrdering1() - { - await TestInMethodAsync( + public Task QueryMethodinfoOrderByOnePropertyWithOrdering1() + => TestInMethodAsync( """ var q = from i in new int[0] @@ -4501,13 +3838,11 @@ orderby i $$ascending select i; """, - MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable IEnumerable.OrderBy(Func keySelector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable IEnumerable.OrderBy(Func keySelector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoOrderByOnePropertyWithOrdering2() - { - await TestInMethodAsync( + public Task QueryMethodinfoOrderByOnePropertyWithOrdering2() + => TestInMethodAsync( """ var q = from i in new int[0] @@ -4515,12 +3850,10 @@ await TestInMethodAsync( select i; """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoOrderByTwoPropertiesWithComma1() - { - await TestInMethodAsync( + public Task QueryMethodinfoOrderByTwoPropertiesWithComma1() + => TestInMethodAsync( """ var q = from i in new int[0] @@ -4528,13 +3861,11 @@ await TestInMethodAsync( select i; """, - MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable IOrderedEnumerable.ThenBy(Func keySelector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable IOrderedEnumerable.ThenBy(Func keySelector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoOrderByTwoPropertiesWithComma2() - { - await TestInMethodAsync( + public Task QueryMethodinfoOrderByTwoPropertiesWithComma2() + => TestInMethodAsync( """ var q = from i in new int[0] @@ -4542,13 +3873,11 @@ await TestInMethodAsync( select i; """, - MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable IEnumerable.OrderBy(Func keySelector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable IEnumerable.OrderBy(Func keySelector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering1() - { - await TestInMethodAsync( + public Task QueryMethodinfoOrderByTwoPropertiesWithOrdering1() + => TestInMethodAsync( """ var q = from i in new int[0] @@ -4556,13 +3885,11 @@ await TestInMethodAsync( select i; """, - MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable IEnumerable.OrderBy(Func keySelector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable IEnumerable.OrderBy(Func keySelector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering2() - { - await TestInMethodAsync( + public Task QueryMethodinfoOrderByTwoPropertiesWithOrdering2() + => TestInMethodAsync( """ var q = from i in new int[0] @@ -4570,12 +3897,10 @@ await TestInMethodAsync( select i; """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering3() - { - await TestInMethodAsync( + public Task QueryMethodinfoOrderByTwoPropertiesWithOrdering3() + => TestInMethodAsync( """ var q = from i in new int[0] @@ -4583,13 +3908,11 @@ await TestInMethodAsync( select i; """, - MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable IOrderedEnumerable.ThenBy(Func keySelector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable IOrderedEnumerable.ThenBy(Func keySelector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach1() - { - await TestInMethodAsync( + public Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach1() + => TestInMethodAsync( """ var q = from i in new int[0] @@ -4597,12 +3920,10 @@ await TestInMethodAsync( select i; """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach2() - { - await TestInMethodAsync( + public Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach2() + => TestInMethodAsync( """ var q = from i in new int[0] @@ -4610,13 +3931,11 @@ await TestInMethodAsync( select i; """, - MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable IEnumerable.OrderBy(Func keySelector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable IEnumerable.OrderBy(Func keySelector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach3() - { - await TestInMethodAsync( + public Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach3() + => TestInMethodAsync( """ var q = from i in new int[0] @@ -4624,12 +3943,10 @@ await TestInMethodAsync( select i; """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach4() - { - await TestInMethodAsync( + public Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach4() + => TestInMethodAsync( """ var q = from i in new int[0] @@ -4637,13 +3954,11 @@ await TestInMethodAsync( select i; """, - MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable IOrderedEnumerable.ThenBy(Func keySelector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable IOrderedEnumerable.ThenBy(Func keySelector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoOrderByIncomplete() - { - await TestInMethodAsync( + public Task QueryMethodinfoOrderByIncomplete() + => TestInMethodAsync( """ var q = from i in new int[0] @@ -4651,13 +3966,11 @@ where i > 0 orderby$$ """, - MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable IEnumerable.OrderBy(Func keySelector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable IEnumerable.OrderBy(Func keySelector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoSelectMany1() - { - await TestInMethodAsync( + public Task QueryMethodinfoSelectMany1() + => TestInMethodAsync( """ var q = from i1 in new int[0] @@ -4665,13 +3978,11 @@ await TestInMethodAsync( select i1; """, - MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable IEnumerable.SelectMany(Func> collectionSelector, Func resultSelector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable IEnumerable.SelectMany(Func> collectionSelector, Func resultSelector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoSelectMany2() - { - await TestInMethodAsync( + public Task QueryMethodinfoSelectMany2() + => TestInMethodAsync( """ var q = from i1 in new int[0] @@ -4679,39 +3990,33 @@ await TestInMethodAsync( select i1; """, - MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable IEnumerable.SelectMany(Func> collectionSelector, Func resultSelector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable IEnumerable.SelectMany(Func> collectionSelector, Func resultSelector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoGroupBy1() - { - await TestInMethodAsync( + public Task QueryMethodinfoGroupBy1() + => TestInMethodAsync( """ var q = from i in new int[0] $$group i by i; """, - MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable> IEnumerable.GroupBy(Func keySelector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable> IEnumerable.GroupBy(Func keySelector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoGroupBy2() - { - await TestInMethodAsync( + public Task QueryMethodinfoGroupBy2() + => TestInMethodAsync( """ var q = from i in new int[0] group i $$by i; """, - MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable> IEnumerable.GroupBy(Func keySelector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable> IEnumerable.GroupBy(Func keySelector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoGroupByInto() - { - await TestInMethodAsync( + public Task QueryMethodinfoGroupByInto() + => TestInMethodAsync( """ var q = from i in new int[0] @@ -4719,13 +4024,11 @@ await TestInMethodAsync( select g; """, - MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable> IEnumerable.GroupBy(Func keySelector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable> IEnumerable.GroupBy(Func keySelector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoJoin1() - { - await TestInMethodAsync( + public Task QueryMethodinfoJoin1() + => TestInMethodAsync( """ var q = from i1 in new int[0] @@ -4733,13 +4036,11 @@ await TestInMethodAsync( select i1; """, - MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable IEnumerable.Join(IEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func resultSelector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable IEnumerable.Join(IEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func resultSelector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoJoin2() - { - await TestInMethodAsync( + public Task QueryMethodinfoJoin2() + => TestInMethodAsync( """ var q = from i1 in new int[0] @@ -4747,13 +4048,11 @@ await TestInMethodAsync( select i1; """, - MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable IEnumerable.Join(IEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func resultSelector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable IEnumerable.Join(IEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func resultSelector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoJoin3() - { - await TestInMethodAsync( + public Task QueryMethodinfoJoin3() + => TestInMethodAsync( """ var q = from i1 in new int[0] @@ -4761,13 +4060,11 @@ await TestInMethodAsync( select i1; """, - MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable IEnumerable.Join(IEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func resultSelector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable IEnumerable.Join(IEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func resultSelector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoJoin4() - { - await TestInMethodAsync( + public Task QueryMethodinfoJoin4() + => TestInMethodAsync( """ var q = from i1 in new int[0] @@ -4775,13 +4072,11 @@ await TestInMethodAsync( select i1; """, - MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable IEnumerable.Join(IEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func resultSelector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable IEnumerable.Join(IEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func resultSelector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoJoinInto1() - { - await TestInMethodAsync( + public Task QueryMethodinfoJoinInto1() + => TestInMethodAsync( """ var q = from i1 in new int[0] @@ -4789,13 +4084,11 @@ await TestInMethodAsync( select g; """, - MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable> IEnumerable.GroupJoin>(IEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func, IEnumerable> resultSelector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable> IEnumerable.GroupJoin>(IEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func, IEnumerable> resultSelector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoJoinInto2() - { - await TestInMethodAsync( + public Task QueryMethodinfoJoinInto2() + => TestInMethodAsync( """ var q = from i1 in new int[0] @@ -4803,50 +4096,42 @@ await TestInMethodAsync( select g; """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoFromMissing() - { - await TestInMethodAsync( + public Task QueryMethodinfoFromMissing() + => TestInMethodAsync( """ var q = $$from i in new int[0] select i; """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoRangeVariableSimple1() - { - await TestInMethodAsync( + public Task QueryMethodinfoRangeVariableSimple1() + => TestInMethodAsync( """ var q = $$from double i in new int[0] select i; """, - MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable System.Collections.IEnumerable.Cast()")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable System.Collections.IEnumerable.Cast()")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoRangeVariableSimple2() - { - await TestInMethodAsync( + public Task QueryMethodinfoRangeVariableSimple2() + => TestInMethodAsync( """ var q = from double i $$in new int[0] select i; """, - MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable System.Collections.IEnumerable.Cast()")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable System.Collections.IEnumerable.Cast()")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoRangeVariableSelectMany1() - { - await TestInMethodAsync( + public Task QueryMethodinfoRangeVariableSelectMany1() + => TestInMethodAsync( """ var q = from i in new int[0] @@ -4854,13 +4139,11 @@ await TestInMethodAsync( select i; """, - MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable IEnumerable.SelectMany(Func> collectionSelector, Func resultSelector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable IEnumerable.SelectMany(Func> collectionSelector, Func resultSelector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoRangeVariableSelectMany2() - { - await TestInMethodAsync( + public Task QueryMethodinfoRangeVariableSelectMany2() + => TestInMethodAsync( """ var q = from i in new int[0] @@ -4868,13 +4151,11 @@ await TestInMethodAsync( select i; """, - MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable System.Collections.IEnumerable.Cast()")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable System.Collections.IEnumerable.Cast()")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoRangeVariableJoin1() - { - await TestInMethodAsync( + public Task QueryMethodinfoRangeVariableJoin1() + => TestInMethodAsync( """ var q = from i1 in new int[0] @@ -4882,13 +4163,11 @@ await TestInMethodAsync( select i1; """, - MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable IEnumerable.Join(IEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func resultSelector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable IEnumerable.Join(IEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func resultSelector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoRangeVariableJoin2() - { - await TestInMethodAsync( + public Task QueryMethodinfoRangeVariableJoin2() + => TestInMethodAsync( """ var q = from i1 in new int[0] @@ -4896,13 +4175,11 @@ await TestInMethodAsync( select i1; """, - MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable System.Collections.IEnumerable.Cast()")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable System.Collections.IEnumerable.Cast()")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoRangeVariableJoin3() - { - await TestInMethodAsync( + public Task QueryMethodinfoRangeVariableJoin3() + => TestInMethodAsync( """ var q = from i1 in new int[0] @@ -4910,13 +4187,11 @@ await TestInMethodAsync( select i1; """, - MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable IEnumerable.Join(IEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func resultSelector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable IEnumerable.Join(IEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func resultSelector)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23394")] - public async Task QueryMethodinfoRangeVariableJoin4() - { - await TestInMethodAsync( + public Task QueryMethodinfoRangeVariableJoin4() + => TestInMethodAsync( """ var q = from i1 in new int[0] @@ -4924,13 +4199,11 @@ await TestInMethodAsync( select i1; """, - MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable IEnumerable.Join(IEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func resultSelector)")); - } + MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable IEnumerable.Join(IEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func resultSelector)")); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543205")] - public async Task TestErrorGlobal() - { - await TestAsync( + public Task TestErrorGlobal() + => TestAsync( """ extern alias global; @@ -4944,12 +4217,10 @@ static int Main() } """, MainDescription("")); - } [Fact] - public async Task DoNotRemoveAttributeSuffixAndProduceInvalidIdentifier1() - { - await TestAsync( + public Task DoNotRemoveAttributeSuffixAndProduceInvalidIdentifier1() + => TestAsync( """ using System; @@ -4959,12 +4230,10 @@ class classAttribute : Attribute } """, MainDescription($"({FeaturesResources.field}) classAttribute classAttribute.x")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544026")] - public async Task DoNotRemoveAttributeSuffix2() - { - await TestAsync( + public Task DoNotRemoveAttributeSuffix2() + => TestAsync( """ using System; @@ -4974,12 +4243,10 @@ class class1Attribute : Attribute } """, MainDescription($"({FeaturesResources.field}) class1Attribute class1Attribute.x")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1696")] - public async Task AttributeQuickInfoBindsToClassTest() - { - await TestAsync( + public Task AttributeQuickInfoBindsToClassTest() + => TestAsync( """ using System; @@ -4998,12 +4265,10 @@ public SomeAttribute() } """, Documentation("class comment")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1696")] - public async Task AttributeConstructorQuickInfo() - { - await TestAsync( + public Task AttributeConstructorQuickInfo() + => TestAsync( """ using System; @@ -5022,12 +4287,10 @@ public SomeAttribute() } """, Documentation("ctor comment")); - } [Fact] - public async Task TestLabel() - { - await TestInClassAsync( + public Task TestLabel() + => TestInClassAsync( """ void M() { @@ -5037,12 +4300,10 @@ void M() } """, MainDescription($"({FeaturesResources.label}) Goo")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542613")] - public async Task TestUnboundGeneric() - { - await TestAsync( + public Task TestUnboundGeneric() + => TestAsync( """ using System; using System.Collections.Generic; @@ -5057,12 +4318,10 @@ void M() """, MainDescription("class System.Collections.Generic.List"), NoTypeParameterMap); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543113")] - public async Task TestAnonymousTypeNew1() - { - await TestAsync( + public Task TestAnonymousTypeNew1() + => TestAsync( """ class C { @@ -5080,7 +4339,6 @@ void M() {{FeaturesResources.Types_colon}} 'a {{FeaturesResources.is_}} new { } """)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543873")] public async Task TestNestedAnonymousType() @@ -5122,9 +4380,8 @@ await TestInMethodAsync( } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543183")] - public async Task TestAssignmentOperatorInAnonymousType() - { - await TestAsync( + public Task TestAssignmentOperatorInAnonymousType() + => TestAsync( """ class C { @@ -5134,12 +4391,10 @@ void M() } } """); - } [Fact, WorkItem(10731, "DevDiv_Projects/Roslyn")] - public async Task TestErrorAnonymousTypeDoesntShow() - { - await TestInMethodAsync( + public Task TestErrorAnonymousTypeDoesntShow() + => TestInMethodAsync( @"var a = new { new { N = 0 }.N, new { } }.$$N;", MainDescription(@"int 'a.N { get; }"), NoTypeParameterMap, @@ -5149,12 +4404,10 @@ await TestInMethodAsync( {{FeaturesResources.Types_colon}} 'a {{FeaturesResources.is_}} new { int N } """)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543553")] - public async Task TestArrayAssignedToVar() - { - await TestAsync( + public Task TestArrayAssignedToVar() + => TestAsync( """ class C { @@ -5165,12 +4418,10 @@ static void M(string[] args) } """, MainDescription("string[]")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529139")] - public async Task ColorColorRangeVariable() - { - await TestAsync( + public Task ColorColorRangeVariable() + => TestAsync( """ using System.Collections.Generic; using System.Linq; @@ -5191,12 +4442,10 @@ public static IEnumerable Bar() } """, MainDescription($"({FeaturesResources.range_variable}) N1.yield yield")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] - public async Task QuickInfoOnOperator() - { - await TestAsync( + public Task QuickInfoOnOperator() + => TestAsync( """ using System.Collections.Generic; @@ -5220,36 +4469,30 @@ public static implicit operator Program(string s) } """, MainDescription("IEnumerable Program.operator +(Program p1, Program p2)")); - } [Fact] - public async Task TestConstantField() - { - await TestAsync( + public Task TestConstantField() + => TestAsync( """ class C { const int $$F = 1; """, MainDescription($"({FeaturesResources.constant}) int C.F = 1")); - } [Fact] - public async Task TestMultipleConstantFields() - { - await TestAsync( + public Task TestMultipleConstantFields() + => TestAsync( """ class C { public const double X = 1.0, Y = 2.0, $$Z = 3.5; """, MainDescription($"({FeaturesResources.constant}) double C.Z = 3.5")); - } [Fact] - public async Task TestConstantDependencies() - { - await TestAsync( + public Task TestConstantDependencies() + => TestAsync( """ class A { @@ -5263,12 +4506,10 @@ class B } """, MainDescription($"({FeaturesResources.constant}) int A.X = B.Z + 1")); - } [Fact] - public async Task TestConstantCircularDependencies() - { - await TestAsync( + public Task TestConstantCircularDependencies() + => TestAsync( """ class A { @@ -5281,12 +4522,10 @@ class B } """, MainDescription($"({FeaturesResources.constant}) int B.Z = A.X + 1")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")] - public async Task TestConstantOverflow() - { - await TestAsync( + public Task TestConstantOverflow() + => TestAsync( """ class B { @@ -5294,12 +4533,10 @@ class B } """, MainDescription($"({FeaturesResources.constant}) int B.Z = int.MaxValue + 1")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")] - public async Task TestConstantOverflowInUncheckedContext() - { - await TestAsync( + public Task TestConstantOverflowInUncheckedContext() + => TestAsync( """ class B { @@ -5307,12 +4544,10 @@ class B } """, MainDescription($"({FeaturesResources.constant}) int B.Z = unchecked(int.MaxValue + 1)")); - } [Fact] - public async Task TestEnumInConstantField() - { - await TestAsync( + public Task TestEnumInConstantField() + => TestAsync( """ public class EnumTest { @@ -5334,12 +4569,10 @@ static void Main() } """, MainDescription($"({FeaturesResources.local_constant}) int x = (int)Days.Sun")); - } [Fact] - public async Task TestConstantInDefaultExpression() - { - await TestAsync( + public Task TestConstantInDefaultExpression() + => TestAsync( """ public class EnumTest { @@ -5361,12 +4594,10 @@ static void Main() } """, MainDescription($"({FeaturesResources.local_constant}) Days x = default(Days)")); - } [Fact] - public async Task TestConstantParameter() - { - await TestAsync( + public Task TestConstantParameter() + => TestAsync( """ class C { @@ -5374,12 +4605,10 @@ class C } """, MainDescription($"({FeaturesResources.parameter}) int b = 1")); - } [Fact] - public async Task TestConstantLocal() - { - await TestAsync( + public Task TestConstantLocal() + => TestAsync( """ class C { @@ -5389,58 +4618,44 @@ void Bar() } """, MainDescription($"({FeaturesResources.local_constant}) int loc = 1")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] - public async Task TestErrorType1() - { - await TestInMethodAsync( + public Task TestErrorType1() + => TestInMethodAsync( @"var $$v1 = new Goo();", MainDescription($"({FeaturesResources.local_variable}) Goo v1")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] - public async Task TestErrorType2() - { - await TestInMethodAsync( + public Task TestErrorType2() + => TestInMethodAsync( @"var $$v1 = v1;", MainDescription($"({FeaturesResources.local_variable}) var v1")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] - public async Task TestErrorType3() - { - await TestInMethodAsync( + public Task TestErrorType3() + => TestInMethodAsync( @"var $$v1 = new Goo();", MainDescription($"({FeaturesResources.local_variable}) Goo v1")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] - public async Task TestErrorType4() - { - await TestInMethodAsync( + public Task TestErrorType4() + => TestInMethodAsync( @"var $$v1 = &(x => x);", MainDescription($"({FeaturesResources.local_variable}) ?* v1")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] - public async Task TestErrorType5() - { - await TestInMethodAsync("var $$v1 = &v1", + public Task TestErrorType5() + => TestInMethodAsync("var $$v1 = &v1", MainDescription($"({FeaturesResources.local_variable}) var* v1")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] - public async Task TestErrorType6() - { - await TestInMethodAsync("var $$v1 = new Goo[1]", + public Task TestErrorType6() + => TestInMethodAsync("var $$v1 = new Goo[1]", MainDescription($"({FeaturesResources.local_variable}) Goo[] v1")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] - public async Task TestErrorType7() - { - await TestInClassAsync( + public Task TestErrorType7() + => TestInClassAsync( """ class C { @@ -5455,27 +4670,21 @@ void Goo() } """, MainDescription($"({FeaturesResources.local_variable}) ? v1")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] - public async Task TestErrorType8() - { - await TestInMethodAsync("var $$v1 = Unknown", + public Task TestErrorType8() + => TestInMethodAsync("var $$v1 = Unknown", MainDescription($"({FeaturesResources.local_variable}) ? v1")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545072")] - public async Task TestDelegateSpecialTypes() - { - await TestAsync( + public Task TestDelegateSpecialTypes() + => TestAsync( @"delegate void $$F(int x);", MainDescription("delegate void F(int x)")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545108")] - public async Task TestNullPointerParameter() - { - await TestAsync( + public Task TestNullPointerParameter() + => TestAsync( """ class C { @@ -5485,19 +4694,15 @@ class C } """, MainDescription("void C.Goo([int* x = null])")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545098")] - public async Task TestLetIdentifier1() - { - await TestInMethodAsync("var q = from e in \"\" let $$y = 1 let a = new { y } select a;", + public Task TestLetIdentifier1() + => TestInMethodAsync("var q = from e in \"\" let $$y = 1 let a = new { y } select a;", MainDescription($"({FeaturesResources.range_variable}) int y")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545295")] - public async Task TestNullableDefaultValue() - { - await TestAsync( + public Task TestNullableDefaultValue() + => TestAsync( """ class Test { @@ -5507,12 +4712,10 @@ class Test } """, MainDescription("void Test.Method([int? t1 = null])")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529586")] - public async Task TestInvalidParameterInitializer() - { - await TestAsync( + public Task TestInvalidParameterInitializer() + => TestAsync( """ class Program { @@ -5526,12 +4729,10 @@ void M1(float $$j1 = "Hello" MainDescription($""" ({FeaturesResources.parameter}) float j1 = "Hello" + "World" """)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545230")] - public async Task TestComplexConstLocal() - { - await TestAsync( + public Task TestComplexConstLocal() + => TestAsync( """ class Program { @@ -5544,12 +4745,10 @@ void Main() } """, MainDescription($@"({FeaturesResources.local_constant}) int MEGABYTE = 1024 * 1024 + true")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545230")] - public async Task TestComplexConstField() - { - await TestAsync( + public Task TestComplexConstField() + => TestAsync( """ class Program { @@ -5564,12 +4763,10 @@ void Main() } """, MainDescription($"({FeaturesResources.constant}) int Program.a = true - false")); - } [Fact] - public async Task TestTypeParameterCrefDoesNotHaveQuickInfo() - { - await TestAsync( + public Task TestTypeParameterCrefDoesNotHaveQuickInfo() + => TestAsync( """ class C { @@ -5579,12 +4776,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestCref1() - { - await TestAsync( + public Task TestCref1() + => TestAsync( """ class Program { @@ -5595,12 +4790,10 @@ static void Main(string[] args) } """, MainDescription(@"void Program.Main(string[] args)")); - } [Fact] - public async Task TestCref2() - { - await TestAsync( + public Task TestCref2() + => TestAsync( """ class Program { @@ -5611,12 +4804,10 @@ static void Main(string[] args) } """, MainDescription(@"void Program.Main(string[] args)")); - } [Fact] - public async Task TestCref3() - { - await TestAsync( + public Task TestCref3() + => TestAsync( """ class Program { @@ -5626,12 +4817,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestCref4() - { - await TestAsync( + public Task TestCref4() + => TestAsync( """ class Program { @@ -5641,12 +4830,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestCref5() - { - await TestAsync( + public Task TestCref5() + => TestAsync( """ class Program { @@ -5656,12 +4843,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78171")] - public async Task TestPreprocessingSymbol() - { - var markup = """ + public Task TestPreprocessingSymbol() + => TestAsync(""" using System.Threading; using System.Threading.Tasks; @@ -5678,24 +4863,11 @@ async Task Process(CancellationToken cancellationToken = default) #endif } } - """; - - await TestAsync(markup, MainDescription("NET")); - } + """, MainDescription("NET")); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546849")] public async Task TestIndexedProperty() { - var markup = """ - class Program - { - void M() - { - CCC c = new CCC(); - c.Index$$Prop[0] = "s"; - } - } - """; // Note that is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types. var referencedCode = """ @@ -5726,7 +4898,16 @@ End Property End Class """; - await TestWithReferenceAsync(sourceCode: markup, + await TestWithReferenceAsync(sourceCode: """ + class Program + { + void M() + { + CCC c = new CCC(); + c.Index$$Prop[0] = "s"; + } + } + """, referencedCode: referencedCode, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.VisualBasic, @@ -5734,9 +4915,8 @@ await TestWithReferenceAsync(sourceCode: markup, } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546918")] - public async Task TestUnconstructedGeneric() - { - await TestAsync( + public Task TestUnconstructedGeneric() + => TestAsync( """ class A { @@ -5754,12 +4934,10 @@ void Goo() } """, MainDescription(@"enum A.SortOrder")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546970")] - public async Task TestUnconstructedGenericInCRef() - { - await TestAsync( + public Task TestUnconstructedGenericInCRef() + => TestAsync( """ /// class C @@ -5767,12 +4945,10 @@ class C } """, MainDescription(@"class C")); - } [Fact] - public async Task TestAwaitableMethod() - { - var markup = """ + public Task TestAwaitableMethod() + => VerifyWithMscorlib45Async(""" using System.Threading.Tasks; class C { @@ -5781,16 +4957,11 @@ async Task Goo() Go$$o(); } } - """; - var description = $"({CSharpFeaturesResources.awaitable}) Task C.Goo()"; - - await VerifyWithMscorlib45Async(markup, MainDescription(description)); - } + """, MainDescription($"({CSharpFeaturesResources.awaitable}) Task C.Goo()")); [Fact] - public async Task ObsoleteItem() - { - var markup = """ + public Task ObsoleteItem() + => TestAsync(""" using System; @@ -5802,14 +4973,11 @@ public void goo() go$$o(); } } - """; - await TestAsync(markup, MainDescription($"[{CSharpFeaturesResources.deprecated}] void Program.goo()")); - } + """, MainDescription($"[{CSharpFeaturesResources.deprecated}] void Program.goo()")); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/751070")] - public async Task DynamicOperator() - { - var markup = """ + public Task DynamicOperator() + => TestAsync(""" public class Test @@ -5824,14 +4992,11 @@ static int Main() return 1; } } - """; - await TestAsync(markup, MainDescription("dynamic dynamic.operator ==(dynamic left, dynamic right)")); - } + """, MainDescription("dynamic dynamic.operator ==(dynamic left, dynamic right)")); [Fact] - public async Task TextOnlyDocComment() - { - await TestAsync( + public Task TextOnlyDocComment() + => TestAsync( """ /// ///goo @@ -5840,12 +5005,10 @@ class C$$ { } """, Documentation("goo")); - } [Fact] - public async Task TestTrimConcatMultiLine() - { - await TestAsync( + public Task TestTrimConcatMultiLine() + => TestAsync( """ /// /// goo @@ -5855,12 +5018,10 @@ class C$$ { } """, Documentation("goo bar")); - } [Fact] - public async Task TestCref() - { - await TestAsync( + public Task TestCref() + => TestAsync( """ /// /// @@ -5870,12 +5031,10 @@ class C$$ { } """, Documentation("C C")); - } [Fact] - public async Task ExcludeTextOutsideSummaryBlock() - { - await TestAsync( + public Task ExcludeTextOutsideSummaryBlock() + => TestAsync( """ /// red /// @@ -5886,12 +5045,10 @@ class C$$ { } """, Documentation("green")); - } [Fact] - public async Task NewlineAfterPara() - { - await TestAsync( + public Task NewlineAfterPara() + => TestAsync( """ /// /// goo @@ -5900,12 +5057,19 @@ class C$$ { } """, Documentation("goo")); - } [Fact] - public async Task TextOnlyDocComment_Metadata() - { - var referenced = """ + public Task TextOnlyDocComment_Metadata() + => TestWithMetadataReferenceHelperAsync(""" + + class G + { + void goo() + { + C$$ c; + } + } + """, """ /// ///goo @@ -5913,9 +5077,11 @@ public async Task TextOnlyDocComment_Metadata() public class C { } - """; + """, "C#", "C#", Documentation("goo")); - var code = """ + [Fact] + public Task TestTrimConcatMultiLine_Metadata() + => TestWithMetadataReferenceHelperAsync(""" class G { @@ -5924,14 +5090,7 @@ void goo() C$$ c; } } - """; - await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("goo")); - } - - [Fact] - public async Task TestTrimConcatMultiLine_Metadata() - { - var referenced = """ + """, """ /// /// goo @@ -5940,25 +5099,11 @@ public async Task TestTrimConcatMultiLine_Metadata() public class C { } - """; - - var code = """ - - class G - { - void goo() - { - C$$ c; - } - } - """; - await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("goo bar")); - } + """, "C#", "C#", Documentation("goo bar")); [Fact] - public async Task TestCref_Metadata() - { - var code = """ + public Task TestCref_Metadata() + => TestWithMetadataReferenceHelperAsync(""" class G { @@ -5967,9 +5112,7 @@ void goo() C$$ c; } } - """; - - var referenced = """ + """, """ /// /// /// @@ -5977,14 +5120,11 @@ void goo() public class C { } - """; - await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("C C")); - } + """, "C#", "C#", Documentation("C C")); [Fact] - public async Task ExcludeTextOutsideSummaryBlock_Metadata() - { - var code = """ + public Task ExcludeTextOutsideSummaryBlock_Metadata() + => TestWithMetadataReferenceHelperAsync(""" class G { @@ -5993,9 +5133,7 @@ void goo() C$$ c; } } - """; - - var referenced = """ + """, """ /// red /// @@ -6005,14 +5143,11 @@ void goo() public class C { } - """; - await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("green")); - } + """, "C#", "C#", Documentation("green")); [Fact] - public async Task Param() - { - await TestAsync( + public Task Param() + => TestAsync( """ /// public class C @@ -6025,12 +5160,10 @@ public void Goo(string[] arg$$s, T otherParam) } } """, Documentation("First parameter of C.Goo(string[], T)")); - } [Fact] - public async Task Param_Metadata() - { - var code = """ + public Task Param_Metadata() + => TestWithMetadataReferenceHelperAsync(""" class G { @@ -6040,8 +5173,7 @@ void goo() c.Goo(arg$$s: new string[] { }, 1); } } - """; - var referenced = """ + """, """ /// public class C @@ -6053,14 +5185,11 @@ public void Goo(string[] args, T otherParam) { } } - """; - await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("First parameter of C.Goo(string[], T)")); - } + """, "C#", "C#", Documentation("First parameter of C.Goo(string[], T)")); [Fact] - public async Task Param2() - { - await TestAsync( + public Task Param2() + => TestAsync( """ /// public class C @@ -6073,12 +5202,10 @@ public void Goo(string[] args, T oth$$erParam) } } """, Documentation("Another parameter of C.Goo(string[], T)")); - } [Fact] - public async Task Param2_Metadata() - { - var code = """ + public Task Param2_Metadata() + => TestWithMetadataReferenceHelperAsync(""" class G { @@ -6088,8 +5215,7 @@ void goo() c.Goo(args: new string[] { }, other$$Param: 1); } } - """; - var referenced = """ + """, """ /// public class C @@ -6101,14 +5227,11 @@ public void Goo(string[] args, T otherParam) { } } - """; - await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("Another parameter of C.Goo(string[], T)")); - } + """, "C#", "C#", Documentation("Another parameter of C.Goo(string[], T)")); [Fact] - public async Task TypeParam() - { - await TestAsync( + public Task TypeParam() + => TestAsync( """ /// public class C @@ -6121,12 +5244,10 @@ public class C } } """, Documentation("A type parameter of C.Goo(string[], T)")); - } [Fact] - public async Task UnboundCref() - { - await TestAsync( + public Task UnboundCref() + => TestAsync( """ /// public class C @@ -6139,12 +5260,10 @@ public class C } } """, Documentation("A type parameter of goo(string[], T)")); - } [Fact] - public async Task CrefInConstructor() - { - await TestAsync( + public Task CrefInConstructor() + => TestAsync( """ public class TestClass { @@ -6156,12 +5275,10 @@ public class TestClass } } """, Documentation("This sample shows how to specify the TestClass constructor as a cref attribute.")); - } [Fact] - public async Task CrefInConstructorOverloaded() - { - await TestAsync( + public Task CrefInConstructorOverloaded() + => TestAsync( """ public class TestClass { @@ -6180,12 +5297,10 @@ public TestClass() } } """, Documentation("This sample shows how to specify the TestClass(int) constructor as a cref attribute.")); - } [Fact] - public async Task CrefInGenericMethod1() - { - await TestAsync( + public Task CrefInGenericMethod1() + => TestAsync( """ public class TestClass { @@ -6203,12 +5318,10 @@ The GetGenericValue method. This sample shows how to specify the TestClass.GetGenericValue(T) method as a cref attribute. """)); - } [Fact] - public async Task CrefInGenericMethod2() - { - await TestAsync( + public Task CrefInGenericMethod2() + => TestAsync( """ public class TestClass { @@ -6226,12 +5339,10 @@ The GetGenericValue method. This sample shows how to specify the TestClass.GetGenericValue(T) method as a cref attribute. """)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813350")] - public async Task CrefInMethodOverloading1() - { - await TestAsync( + public Task CrefInMethodOverloading1() + => TestAsync( """ public class TestClass { @@ -6257,12 +5368,10 @@ public static void GetGenericValue() } } """, Documentation("This sample shows how to specify the TestClass.GetGenericValue() method as a cref attribute.")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813350")] - public async Task CrefInMethodOverloading2() - { - await TestAsync( + public Task CrefInMethodOverloading2() + => TestAsync( """ public class TestClass { @@ -6288,12 +5397,10 @@ public static void GetGenericValue() } } """, Documentation("This sample shows how to call the TestClass.GetGenericValue(T) method")); - } [Fact] - public async Task CrefInGenericType() - { - await TestAsync( + public Task CrefInGenericType() + => TestAsync( """ /// /// This example shows how to specify the cref. @@ -6312,12 +5419,10 @@ class Generic$$Class Punctuation.CloseAngle, WhiteSpace(" "), Text("cref.")))); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/812720")] - public async Task ClassificationOfCrefsFromMetadata() - { - var code = """ + public Task ClassificationOfCrefsFromMetadata() + => TestWithMetadataReferenceHelperAsync(""" class G { @@ -6327,8 +5432,7 @@ void goo() c.Go$$o(); } } - """; - var referenced = """ + """, """ /// public class C @@ -6340,8 +5444,7 @@ public void Goo() { } } - """; - await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", + """, "C#", "C#", Documentation("See C.Goo() method", ExpectedClassifications( Text("See"), @@ -6353,12 +5456,10 @@ await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Punctuation.CloseParen, WhiteSpace(" "), Text("method")))); - } [Fact] - public async Task FieldAvailableInBothLinkedFiles() - { - var markup = """ + public Task FieldAvailableInBothLinkedFiles() + => VerifyWithReferenceWorkerAsync(""" - """; - - await VerifyWithReferenceWorkerAsync(markup, [MainDescription($"({FeaturesResources.field}) int C.x"), Usage("")]); - } + """, [MainDescription($"({FeaturesResources.field}) int C.x"), Usage("")]); [Fact] public async Task FieldUnavailableInOneLinkedFile() { - var markup = """ + var expectedDescription = Usage($""" + + {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} + {string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)} + + {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} + """, expectsWarningGlyph: true); + + await VerifyWithReferenceWorkerAsync(""" - """; + """, [expectedDescription]); + } + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37097")] + public async Task BindSymbolInOtherFile() + { var expectedDescription = Usage($""" - {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} - {string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)} + {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Not_Available)} + {string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Available)} {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} """, expectsWarningGlyph: true); - await VerifyWithReferenceWorkerAsync(markup, [expectedDescription]); - } - - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37097")] - public async Task BindSymbolInOtherFile() - { - var markup = """ + await VerifyWithReferenceWorkerAsync(""" - """; - var expectedDescription = Usage($""" - - {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Not_Available)} - {string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Available)} - - {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} - """, expectsWarningGlyph: true); - - await VerifyWithReferenceWorkerAsync(markup, [expectedDescription]); + """, [expectedDescription]); } [Fact] public async Task FieldUnavailableInTwoLinkedFiles() { - var markup = """ + var expectedDescription = Usage( + $""" + + {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} + {string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)} + {string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)} + + {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} + """, + expectsWarningGlyph: true); + + await VerifyWithReferenceWorkerAsync(""" - """; - var expectedDescription = Usage( - $""" - - {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} - {string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)} - {string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)} - - {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} - """, - expectsWarningGlyph: true); - - await VerifyWithReferenceWorkerAsync(markup, [expectedDescription]); + """, [expectedDescription]); } [Fact] public async Task ExcludeFilesWithInactiveRegions() { - var markup = """ + var expectedDescription = Usage($""" + + {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} + {string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)} + + {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} + """, expectsWarningGlyph: true); + await VerifyWithReferenceWorkerAsync(""" - """; - var expectedDescription = Usage($""" - - {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} - {string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)} - - {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} - """, expectsWarningGlyph: true); - await VerifyWithReferenceWorkerAsync(markup, [expectedDescription]); + """, [expectedDescription]); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962353")] - public async Task NoValidSymbolsInLinkedDocuments() - { - var markup = """ + public Task NoValidSymbolsInLinkedDocuments() + => VerifyWithReferenceWorkerAsync(""" - """; - await VerifyWithReferenceWorkerAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] - public async Task LocalsValidInLinkedDocuments() - { - var markup = """ + public Task LocalsValidInLinkedDocuments() + => VerifyWithReferenceWorkerAsync(""" - """; - - await VerifyWithReferenceWorkerAsync(markup, [MainDescription($"({FeaturesResources.local_variable}) int x"), Usage("")]); - } + """, [MainDescription($"({FeaturesResources.local_variable}) int x"), Usage("")]); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] - public async Task LocalWarningInLinkedDocuments() - { - var markup = """ + public Task LocalWarningInLinkedDocuments() + => VerifyWithReferenceWorkerAsync(""" - """; - - await VerifyWithReferenceWorkerAsync(markup, [MainDescription($"({FeaturesResources.local_variable}) int x"), Usage($""" + """, [MainDescription($"({FeaturesResources.local_variable}) int x"), Usage($""" {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} {string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)} {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} """, expectsWarningGlyph: true)]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] - public async Task LabelsValidInLinkedDocuments() - { - var markup = """ + public Task LabelsValidInLinkedDocuments() + => VerifyWithReferenceWorkerAsync(""" - """; - - await VerifyWithReferenceWorkerAsync(markup, [MainDescription($"({FeaturesResources.label}) LABEL"), Usage("")]); - } + """, [MainDescription($"({FeaturesResources.label}) LABEL"), Usage("")]); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] - public async Task RangeVariablesValidInLinkedDocuments() - { - var markup = """ + public Task RangeVariablesValidInLinkedDocuments() + => VerifyWithReferenceWorkerAsync(""" - """; - - await VerifyWithReferenceWorkerAsync(markup, [MainDescription($"({FeaturesResources.range_variable}) int y"), Usage("")]); - } + """, [MainDescription($"({FeaturesResources.range_variable}) int y"), Usage("")]); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1019766")] - public async Task PointerAccessibility() - { - var markup = """ + public Task PointerAccessibility() + => TestAsync(""" class C { unsafe static void Main() @@ -6695,14 +5769,11 @@ unsafe static void Main() var x = p =$$= q == d; } } - """; - await TestAsync(markup, MainDescription("bool void*.operator ==(void* left, void* right)")); - } + """, MainDescription("bool void*.operator ==(void* left, void* right)")); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114300")] - public async Task AwaitingTaskOfArrayType() - { - var markup = """ + public Task AwaitingTaskOfArrayType() + => TestAsync(""" using System.Threading.Tasks; @@ -6713,14 +5784,11 @@ async Task M() awa$$it M(); } } - """; - await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "int[]"))); - } + """, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "int[]"))); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114300")] - public async Task AwaitingTaskOfDynamic() - { - var markup = """ + public Task AwaitingTaskOfDynamic() + => TestAsync(""" using System.Threading.Tasks; @@ -6731,14 +5799,11 @@ async Task M() awa$$it M(); } } - """; - await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "dynamic"))); - } + """, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "dynamic"))); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task MethodOverloadDifferencesIgnored() - { - var markup = """ + public Task MethodOverloadDifferencesIgnored() + => VerifyWithReferenceWorkerAsync(""" - """; - - var expectedDescription = $"void C.Do(int x)"; - await VerifyWithReferenceWorkerAsync(markup, MainDescription(expectedDescription)); - } + """, MainDescription($"void C.Do(int x)")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task MethodOverloadDifferencesIgnored_ContainingType() - { - var markup = """ + public Task MethodOverloadDifferencesIgnored_ContainingType() + => VerifyWithReferenceWorkerAsync(""" - """; - - var expectedDescription = $"void Methods1.Do(string x)"; - await VerifyWithReferenceWorkerAsync(markup, MainDescription(expectedDescription)); - } + """, MainDescription($"void Methods1.Do(string x)")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4868")] - public async Task QuickInfoExceptions() - { - await TestAsync( + public Task QuickInfoExceptions() + => TestAsync( """ using System; @@ -6862,12 +5917,10 @@ void M() double Not_A_Class_But_Still_Displayed """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23307")] - public async Task QuickInfoCapturesOnLocalFunction() - { - await TestAsync(""" + public Task QuickInfoCapturesOnLocalFunction() + => TestAsync(""" class C { @@ -6884,12 +5937,10 @@ void M() {WorkspacesResources.Variables_captured_colon} this, i """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23307")] - public async Task QuickInfoCapturesOnLocalFunction2() - { - await TestAsync(""" + public Task QuickInfoCapturesOnLocalFunction2() + => TestAsync(""" class C { @@ -6906,12 +5957,10 @@ void M() {WorkspacesResources.Variables_captured_colon} this """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23307")] - public async Task QuickInfoCapturesOnLocalFunction3() - { - await TestAsync(""" + public Task QuickInfoCapturesOnLocalFunction3() + => TestAsync(""" class C { @@ -6933,12 +5982,10 @@ void local() {WorkspacesResources.Variables_captured_colon} this, @this, i """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26101")] - public async Task QuickInfoCapturesOnLocalFunction4() - { - await TestAsync(""" + public Task QuickInfoCapturesOnLocalFunction4() + => TestAsync(""" class C { @@ -6961,12 +6008,10 @@ int InnerLocalFunction() {WorkspacesResources.Variables_captured_colon} this """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26101")] - public async Task QuickInfoCapturesOnLocalFunction5() - { - await TestAsync(""" + public Task QuickInfoCapturesOnLocalFunction5() + => TestAsync(""" class C { @@ -6989,12 +6034,10 @@ void OuterLocalFunction() {WorkspacesResources.Variables_captured_colon} this, local """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26101")] - public async Task QuickInfoCapturesOnLocalFunction6() - { - await TestAsync(""" + public Task QuickInfoCapturesOnLocalFunction6() + => TestAsync(""" class C { @@ -7019,12 +6062,10 @@ void InnerLocalFunction() {WorkspacesResources.Variables_captured_colon} local1, local2 """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26101")] - public async Task QuickInfoCapturesOnLocalFunction7() - { - await TestAsync(""" + public Task QuickInfoCapturesOnLocalFunction7() + => TestAsync(""" class C { @@ -7049,12 +6090,10 @@ void OuterLocalFunction() {WorkspacesResources.Variables_captured_colon} local2 """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23307")] - public async Task QuickInfoCapturesOnLambda() - { - await TestAsync(""" + public Task QuickInfoCapturesOnLambda() + => TestAsync(""" class C { @@ -7069,12 +6108,10 @@ void M() {WorkspacesResources.Variables_captured_colon} this, i """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23307")] - public async Task QuickInfoCapturesOnLambda2() - { - await TestAsync(""" + public Task QuickInfoCapturesOnLambda2() + => TestAsync(""" class C { @@ -7089,12 +6126,10 @@ void M() {WorkspacesResources.Variables_captured_colon} this, i """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23307")] - public async Task QuickInfoCapturesOnLambda2_DifferentOrder() - { - await TestAsync(""" + public Task QuickInfoCapturesOnLambda2_DifferentOrder() + => TestAsync(""" class C { @@ -7109,12 +6144,10 @@ void M(int j) {WorkspacesResources.Variables_captured_colon} this, j, i """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23307")] - public async Task QuickInfoCapturesOnLambda3() - { - await TestAsync(""" + public Task QuickInfoCapturesOnLambda3() + => TestAsync(""" class C { @@ -7131,12 +6164,10 @@ void N(System.Action x, System.Action y) { } {WorkspacesResources.Variables_captured_colon} this, @this """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23307")] - public async Task QuickInfoCapturesOnLambda4() - { - await TestAsync(""" + public Task QuickInfoCapturesOnLambda4() + => TestAsync(""" class C { @@ -7152,12 +6183,10 @@ void N(System.Action x, System.Action y) { } {WorkspacesResources.Variables_captured_colon} i """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26101")] - public async Task QuickInfoCapturesOnLambda5() - { - await TestAsync(""" + public Task QuickInfoCapturesOnLambda5() + => TestAsync(""" class C { @@ -7180,12 +6209,10 @@ void M() {WorkspacesResources.Variables_captured_colon} this """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26101")] - public async Task QuickInfoCapturesOnLambda6() - { - await TestAsync(""" + public Task QuickInfoCapturesOnLambda6() + => TestAsync(""" class C { @@ -7208,12 +6235,10 @@ void M() {WorkspacesResources.Variables_captured_colon} this, local """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26101")] - public async Task QuickInfoCapturesOnLambda7() - { - await TestAsync(""" + public Task QuickInfoCapturesOnLambda7() + => TestAsync(""" class C { @@ -7238,12 +6263,10 @@ void M() {WorkspacesResources.Variables_captured_colon} local1, local2 """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26101")] - public async Task QuickInfoCapturesOnLambda8() - { - await TestAsync(""" + public Task QuickInfoCapturesOnLambda8() + => TestAsync(""" class C { @@ -7268,12 +6291,10 @@ void M() {WorkspacesResources.Variables_captured_colon} local2 """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23307")] - public async Task QuickInfoCapturesOnDelegate() - { - await TestAsync(""" + public Task QuickInfoCapturesOnDelegate() + => TestAsync(""" class C { @@ -7288,12 +6309,10 @@ void M() {WorkspacesResources.Variables_captured_colon} i """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1516")] - public async Task QuickInfoWithNonStandardSeeAttributesAppear() - { - await TestAsync( + public Task QuickInfoWithNonStandardSeeAttributesAppear() + => TestAsync( """ class C { @@ -7310,7 +6329,6 @@ void M() } """, Documentation(@"string http://microsoft.com null cat")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/6657")] public async Task OptionalParameterFromPreviousSubmission() @@ -7332,9 +6350,8 @@ void M(int x = 1) { } } [Fact] - public async Task TupleProperty() - { - await TestInMethodAsync( + public Task TupleProperty() + => TestInMethodAsync( """ interface I { @@ -7357,12 +6374,10 @@ class C : I } """, MainDescription("(int, int) C.Name { get; set; }")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18311")] - public async Task ValueTupleWithArity0VariableName() - { - await TestAsync( + public Task ValueTupleWithArity0VariableName() + => TestAsync( """ using System; @@ -7376,12 +6391,10 @@ void M() """, MainDescription($"({FeaturesResources.local_variable}) ValueTuple y")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18311")] - public async Task ValueTupleWithArity0ImplicitVar() - { - await TestAsync( + public Task ValueTupleWithArity0ImplicitVar() + => TestAsync( """ using System; @@ -7395,12 +6408,10 @@ void M() """, MainDescription("struct System.ValueTuple")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18311")] - public async Task ValueTupleWithArity1VariableName() - { - await TestAsync( + public Task ValueTupleWithArity1VariableName() + => TestAsync( """ using System; @@ -7414,12 +6425,10 @@ void M() """, MainDescription($"({FeaturesResources.local_variable}) ValueTuple y")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18311")] - public async Task ValueTupleWithArity1ImplicitVar() - { - await TestAsync( + public Task ValueTupleWithArity1ImplicitVar() + => TestAsync( """ using System; @@ -7433,12 +6442,10 @@ void M() """, MainDescription("struct System.ValueTuple")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18311")] - public async Task ValueTupleWithArity2VariableName() - { - await TestAsync( + public Task ValueTupleWithArity2VariableName() + => TestAsync( """ using System; @@ -7452,12 +6459,10 @@ void M() """, MainDescription($"({FeaturesResources.local_variable}) (int, int) y")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18311")] - public async Task ValueTupleWithArity2ImplicitVar() - { - await TestAsync( + public Task ValueTupleWithArity2ImplicitVar() + => TestAsync( """ using System; @@ -7471,12 +6476,10 @@ void M() """, MainDescription("(int, int)")); - } [Fact] - public async Task TestRefMethod() - { - await TestInMethodAsync( + public Task TestRefMethod() + => TestInMethodAsync( """ using System; @@ -7494,12 +6497,10 @@ private static ref int goo() } """, MainDescription("ref int Program.goo()")); - } [Fact] - public async Task TestRefLocal() - { - await TestInMethodAsync( + public Task TestRefLocal() + => TestInMethodAsync( """ using System; @@ -7517,12 +6518,10 @@ private static ref int goo() } """, MainDescription($"({FeaturesResources.local_variable}) ref int i")); - } [Fact, WorkItem("https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=410932")] - public async Task TestGenericMethodInDocComment() - { - await TestAsync( + public Task TestGenericMethodInDocComment() + => TestAsync( """ class Test @@ -7540,13 +6539,11 @@ void S() } """, - MainDescription("T Test.F()")); - } + MainDescription("T Test.F()")); [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=403665&_a=edit")] - public async Task TestExceptionWithCrefToConstructorDoesNotCrash() - { - await TestAsync( + public Task TestExceptionWithCrefToConstructorDoesNotCrash() + => TestAsync( """ class Test @@ -7558,73 +6555,53 @@ class Test } """, - MainDescription("Test.Test()")); - } + MainDescription("Test.Test()")); [Fact] - public async Task TestRefStruct() - { - var markup = "ref struct X$$ {}"; - await TestAsync(markup, MainDescription("ref struct X")); - } + public Task TestRefStruct() + => TestAsync("ref struct X$$ {}", MainDescription("ref struct X")); [Fact] - public async Task TestRefStruct_Nested() - { - var markup = """ + public Task TestRefStruct_Nested() + => TestAsync(""" namespace Nested { ref struct X$$ {} } - """; - await TestAsync(markup, MainDescription("ref struct Nested.X")); - } + """, MainDescription("ref struct Nested.X")); [Fact] - public async Task TestReadOnlyStruct() - { - var markup = "readonly struct X$$ {}"; - await TestAsync(markup, MainDescription("readonly struct X")); - } + public Task TestReadOnlyStruct() + => TestAsync("readonly struct X$$ {}", MainDescription("readonly struct X")); [Fact] - public async Task TestReadOnlyStruct_Nested() - { - var markup = """ + public Task TestReadOnlyStruct_Nested() + => TestAsync(""" namespace Nested { readonly struct X$$ {} } - """; - await TestAsync(markup, MainDescription("readonly struct Nested.X")); - } + """, MainDescription("readonly struct Nested.X")); [Fact] - public async Task TestReadOnlyRefStruct() - { - var markup = "readonly ref struct X$$ {}"; - await TestAsync(markup, MainDescription("readonly ref struct X")); - } + public Task TestReadOnlyRefStruct() + => TestAsync("readonly ref struct X$$ {}", MainDescription("readonly ref struct X")); [Fact] - public async Task TestReadOnlyRefStruct_Nested() - { - var markup = """ + public Task TestReadOnlyRefStruct_Nested() + => TestAsync(""" namespace Nested { readonly ref struct X$$ {} } - """; - await TestAsync(markup, MainDescription("readonly ref struct Nested.X")); - } + """, MainDescription("readonly ref struct Nested.X")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22450")] - public async Task TestRefLikeTypesNoDeprecated() - { - var xmlString = """ + public Task TestRefLikeTypesNoDeprecated() + => VerifyWithReferenceWorkerAsync(""" @@ -7643,16 +6620,11 @@ ref struct Test - """; - - // There should be no [deprecated] attribute displayed. - await VerifyWithReferenceWorkerAsync(xmlString, MainDescription($"ref struct TestRef")); - } + """, MainDescription($"ref struct TestRef")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2644")] - public async Task PropertyWithSameNameAsOtherType() - { - await TestAsync( + public Task PropertyWithSameNameAsOtherType() + => TestAsync( """ namespace ConsoleApplication1 { @@ -7673,13 +6645,11 @@ class B } } """, - MainDescription($"ConsoleApplication1.A ConsoleApplication1.B.F()")); - } + MainDescription($"ConsoleApplication1.A ConsoleApplication1.B.F()")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2644")] - public async Task PropertyWithSameNameAsOtherType2() - { - await TestAsync( + public Task PropertyWithSameNameAsOtherType2() + => TestAsync( """ using System.Collections.Generic; @@ -7702,13 +6672,11 @@ class Bar } } """, - MainDescription($"void Program.Test()")); - } + MainDescription($"void Program.Test()")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23883")] - public async Task InMalformedEmbeddedStatement_01() - { - await TestAsync( + public Task InMalformedEmbeddedStatement_01() + => TestAsync( """ class Program @@ -7723,12 +6691,10 @@ void method1() } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23883")] - public async Task InMalformedEmbeddedStatement_02() - { - await TestAsync( + public Task InMalformedEmbeddedStatement_02() + => TestAsync( """ class Program @@ -7743,13 +6709,11 @@ void method1() } """, - MainDescription($"({FeaturesResources.parameter}) ? b")); - } + MainDescription($"({FeaturesResources.parameter}) ? b")); [Fact] - public async Task EnumConstraint() - { - await TestInMethodAsync( + public Task EnumConstraint() + => TestInMethodAsync( """ class X where T : System.Enum @@ -7758,12 +6722,10 @@ class X where T : System.Enum } """, MainDescription($"T {FeaturesResources.in_} X where T : Enum")); - } [Fact] - public async Task DelegateConstraint() - { - await TestInMethodAsync( + public Task DelegateConstraint() + => TestInMethodAsync( """ class X where T : System.Delegate @@ -7772,12 +6734,10 @@ class X where T : System.Delegate } """, MainDescription($"T {FeaturesResources.in_} X where T : Delegate")); - } [Fact] - public async Task MulticastDelegateConstraint() - { - await TestInMethodAsync( + public Task MulticastDelegateConstraint() + => TestInMethodAsync( """ class X where T : System.MulticastDelegate @@ -7786,12 +6746,10 @@ class X where T : System.MulticastDelegate } """, MainDescription($"T {FeaturesResources.in_} X where T : MulticastDelegate")); - } [Fact] - public async Task UnmanagedConstraint_Type() - { - await TestAsync( + public Task UnmanagedConstraint_Type() + => TestAsync( """ class $$X where T : unmanaged @@ -7799,12 +6757,10 @@ class $$X where T : unmanaged } """, MainDescription("class X where T : unmanaged")); - } [Fact] - public async Task UnmanagedConstraint_Method() - { - await TestAsync( + public Task UnmanagedConstraint_Method() + => TestAsync( """ class X @@ -7813,20 +6769,16 @@ class X } """, MainDescription("void X.M() where T : unmanaged")); - } [Fact] - public async Task UnmanagedConstraint_Delegate() - { - await TestAsync( + public Task UnmanagedConstraint_Delegate() + => TestAsync( "delegate void $$D() where T : unmanaged;", MainDescription("delegate void D() where T : unmanaged")); - } [Fact] - public async Task UnmanagedConstraint_LocalFunction() - { - await TestAsync( + public Task UnmanagedConstraint_LocalFunction() + => TestAsync( """ class X @@ -7838,12 +6790,10 @@ void N() } """, MainDescription("void M() where T : unmanaged")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29703")] - public async Task TestGetAccessorDocumentation() - { - await TestAsync( + public Task TestGetAccessorDocumentation() + => TestAsync( """ class X @@ -7853,12 +6803,10 @@ class X } """, Documentation("Summary for property Goo")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29703")] - public async Task TestSetAccessorDocumentation() - { - await TestAsync( + public Task TestSetAccessorDocumentation() + => TestAsync( """ class X @@ -7868,12 +6816,10 @@ class X } """, Documentation("Summary for property Goo")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29703")] - public async Task TestEventAddDocumentation1() - { - await TestAsync( + public Task TestEventAddDocumentation1() + => TestAsync( """ using System; @@ -7889,12 +6835,10 @@ event EventHandler Goo } """, Documentation("Summary for event Goo")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29703")] - public async Task TestEventAddDocumentation2() - { - await TestAsync( + public Task TestEventAddDocumentation2() + => TestAsync( """ using System; @@ -7908,12 +6852,10 @@ class X } """, Documentation("Summary for event Goo")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29703")] - public async Task TestEventRemoveDocumentation1() - { - await TestAsync( + public Task TestEventRemoveDocumentation1() + => TestAsync( """ using System; @@ -7929,12 +6871,10 @@ event EventHandler Goo } """, Documentation("Summary for event Goo")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29703")] - public async Task TestEventRemoveDocumentation2() - { - await TestAsync( + public Task TestEventRemoveDocumentation2() + => TestAsync( """ using System; @@ -7948,12 +6888,10 @@ class X } """, Documentation("Summary for event Goo")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30642")] - public async Task BuiltInOperatorWithUserDefinedEquivalent() - { - await TestAsync( + public Task BuiltInOperatorWithUserDefinedEquivalent() + => TestAsync( """ class X @@ -7966,12 +6904,10 @@ void N(string a, string b) """, MainDescription("bool string.operator ==(string a, string b)"), SymbolGlyph(Glyph.OperatorPublic)); - } [Fact] - public async Task NotNullConstraint_Type() - { - await TestAsync( + public Task NotNullConstraint_Type() + => TestAsync( """ class $$X where T : notnull @@ -7979,12 +6915,10 @@ class $$X where T : notnull } """, MainDescription("class X where T : notnull")); - } [Fact] - public async Task NotNullConstraint_Method() - { - await TestAsync( + public Task NotNullConstraint_Method() + => TestAsync( """ class X @@ -7993,12 +6927,10 @@ class X } """, MainDescription("void X.M() where T : notnull")); - } [Fact] - public async Task MultipleConstraints_Type() - { - await TestAsync( + public Task MultipleConstraints_Type() + => TestAsync( """ class $$X where T : notnull where U : notnull @@ -8010,12 +6942,10 @@ class X where T : notnull where U : notnull """)); - } [Fact] - public async Task MultipleConstraints_Method() - { - await TestAsync( + public Task MultipleConstraints_Method() + => TestAsync( """ class X @@ -8028,20 +6958,16 @@ void X.M() where T : notnull where U : notnull """)); - } [Fact] - public async Task NotNullConstraint_Delegate() - { - await TestAsync( + public Task NotNullConstraint_Delegate() + => TestAsync( "delegate void $$D() where T : notnull;", MainDescription("delegate void D() where T : notnull")); - } [Fact] - public async Task NotNullConstraint_LocalFunction() - { - await TestAsync( + public Task NotNullConstraint_LocalFunction() + => TestAsync( """ class X @@ -8053,12 +6979,10 @@ void N() } """, MainDescription("void M() where T : notnull")); - } [Fact] - public async Task NullableParameterThatIsMaybeNull() - { - await TestWithOptionsAsync(TestOptions.Regular8, + public Task NullableParameterThatIsMaybeNull() + => TestWithOptionsAsync(TestOptions.Regular8, """ #nullable enable @@ -8072,12 +6996,10 @@ void N(string? s) """, MainDescription($"({FeaturesResources.parameter}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s"))); - } [Fact] - public async Task NullableParameterThatIsNotNull() - { - await TestWithOptionsAsync(TestOptions.Regular8, + public Task NullableParameterThatIsNotNull() + => TestWithOptionsAsync(TestOptions.Regular8, """ #nullable enable @@ -8092,12 +7014,43 @@ void N(string? s) """, MainDescription($"({FeaturesResources.parameter}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); - } [Fact] - public async Task NullableFieldThatIsMaybeNull() - { - await TestWithOptionsAsync(TestOptions.Regular8, + public Task NullableParameterThatIsOblivious() + => TestWithOptionsAsync(TestOptions.Regular8, + """ + class X + { + void N(string s) + { + #nullable enable + string s2 = $$s; + } + } + """, + MainDescription($"({FeaturesResources.parameter}) string s"), + NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_nullable_aware, "s"))); + + [Fact] + public Task NullableParameterThatIsOblivious_Propagated() + => TestWithOptionsAsync(TestOptions.Regular8, + """ + class X + { + void N(string s) + { + #nullable enable + string s2 = s; + string s3 = $$s2; + } + } + """, + MainDescription($"({FeaturesResources.local_variable}) string s2"), + NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s2"))); + + [Fact] + public Task NullableFieldThatIsMaybeNull() + => TestWithOptionsAsync(TestOptions.Regular8, """ #nullable enable @@ -8113,12 +7066,10 @@ void N() """, MainDescription($"({FeaturesResources.field}) string? X.s"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s"))); - } [Fact] - public async Task NullableFieldThatIsNotNull() - { - await TestWithOptionsAsync(TestOptions.Regular8, + public Task NullableFieldThatIsNotNull() + => TestWithOptionsAsync(TestOptions.Regular8, """ #nullable enable @@ -8135,12 +7086,29 @@ void N() """, MainDescription($"({FeaturesResources.field}) string? X.s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); - } + + [Fact] + public Task NullableFieldThatIsOblivious() + => TestWithOptionsAsync(TestOptions.Regular8, + """ + class X + { + string s = null; + + void N() + { + s = ""; + #nullable enable + string s2 = $$s; + } + } + """, + MainDescription($"({FeaturesResources.field}) string X.s"), + NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_nullable_aware, "s"))); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/77219")] - public async Task NullableBackingFieldThatIsMaybeNull() - { - await TestWithOptionsAsync(TestOptions.RegularPreview, + public Task NullableBackingFieldThatIsMaybeNull() + => TestWithOptionsAsync(TestOptions.RegularPreview, """ #nullable enable @@ -8154,12 +7122,10 @@ class X """, MainDescription($"({FeaturesResources.field}) string? X.P.field"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "P.field"))); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/77219")] - public async Task NullableBackingFieldThatIsNotNull() - { - await TestWithOptionsAsync(TestOptions.RegularPreview, + public Task NullableBackingFieldThatIsNotNull() + => TestWithOptionsAsync(TestOptions.RegularPreview, """ #nullable enable @@ -8173,12 +7139,26 @@ string P """, MainDescription($"({FeaturesResources.field}) string X.P.field"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "P.field"))); - } + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/77219")] + public Task NullableBackingFieldThatIsOblivious() + => TestWithOptionsAsync(TestOptions.RegularPreview, + """ + class X + { + string P + { + #nullable enable + get => $$field; + } = "a"; + } + """, + MainDescription($"({FeaturesResources.field}) string X.P.field"), + NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_nullable_aware, "P.field"))); [Fact] - public async Task NullablePropertyThatIsMaybeNull() - { - await TestWithOptionsAsync(TestOptions.Regular8, + public Task NullablePropertyThatIsMaybeNull() + => TestWithOptionsAsync(TestOptions.Regular8, """ #nullable enable @@ -8194,12 +7174,10 @@ void N() """, MainDescription("string? X.S { get; set; }"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "S"))); - } [Fact] - public async Task NullablePropertyThatIsNotNull() - { - await TestWithOptionsAsync(TestOptions.Regular8, + public Task NullablePropertyThatIsNotNull() + => TestWithOptionsAsync(TestOptions.Regular8, """ #nullable enable @@ -8216,12 +7194,32 @@ void N() """, MainDescription("string? X.S { get; set; }"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "S"))); - } + + [Theory] + [InlineData("")] + [InlineData("S = null;")] + [InlineData("S = string.Empty;")] + public Task NullablePropertyThatIsOblivious(string code) + => TestWithOptionsAsync(TestOptions.Regular8, + $$""" + class X + { + string S { get; set; } + + void N() + { + {{code}} + #nullable enable + string s2 = $$S; + } + } + """, + MainDescription("string X.S { get; set; }"), + NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_nullable_aware, "S"))); [Fact] - public async Task NullableRangeVariableThatIsMaybeNull() - { - await TestWithOptionsAsync(TestOptions.Regular8, + public Task NullableRangeVariableThatIsMaybeNull() + => TestWithOptionsAsync(TestOptions.Regular8, """ #nullable enable @@ -8242,12 +7240,10 @@ void N() """, MainDescription($"({FeaturesResources.local_variable}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s"))); - } [Fact] - public async Task NullableRangeVariableThatIsNotNull() - { - await TestWithOptionsAsync(TestOptions.Regular8, + public Task NullableRangeVariableThatIsNotNull() + => TestWithOptionsAsync(TestOptions.Regular8, """ #nullable enable @@ -8268,12 +7264,31 @@ void N() """, MainDescription($"({FeaturesResources.local_variable}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); - } [Fact] - public async Task NullableLocalThatIsMaybeNull() - { - await TestWithOptionsAsync(TestOptions.Regular8, + public Task NullableRangeVariableThatIsOblivious() + => TestWithOptionsAsync(TestOptions.Regular8, + """ + using System.Collections.Generic; + class X + { + void N() + { + IEnumerable enumerable; + foreach (string s in enumerable) + { + #nullable enable + string s2 = $$s; + } + } + } + """, + MainDescription($"({FeaturesResources.local_variable}) string s"), + NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_nullable_aware, "s"))); + + [Fact] + public Task NullableLocalThatIsMaybeNull() + => TestWithOptionsAsync(TestOptions.Regular8, """ #nullable enable @@ -8290,12 +7305,10 @@ void N() """, MainDescription($"({FeaturesResources.local_variable}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s"))); - } [Fact] - public async Task NullableLocalThatIsNotNull() - { - await TestWithOptionsAsync(TestOptions.Regular8, + public Task NullableLocalThatIsNotNull() + => TestWithOptionsAsync(TestOptions.Regular8, """ #nullable enable @@ -8312,12 +7325,131 @@ void N() """, MainDescription($"({FeaturesResources.local_variable}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); - } [Fact] - public async Task NullableNotShownPriorToLanguageVersion8() - { - await TestWithOptionsAsync(TestOptions.Regular7_3, + public Task NullableLocalThatIsOblivious() + => TestWithOptionsAsync(TestOptions.Regular8, + """ + class X + { + void N() + { + string s = null; + #nullable enable + string s2 = $$s; + } + } + """, + MainDescription($"({FeaturesResources.local_variable}) string s"), + NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_nullable_aware, "s"))); + + [Theory] + [InlineData("#nullable enable warnings")] + [InlineData("#nullable enable annotations")] + public Task NullableLocalThatIsOblivious_NotFullyNullableEnabled(string directive) + => TestWithOptionsAsync(TestOptions.Regular8, + $$""" + class X + { + void N() + { + string s = null; + {{directive}} + string s2 = $$s; + } + } + """, + MainDescription($"({FeaturesResources.local_variable}) string s"), + NullabilityAnalysis("")); + + [Fact] + public Task NullableMethodThatIsMaybeNull() + => TestWithOptionsAsync(TestOptions.Regular8, + """ + #nullable enable + class X + { + string? M() => null; + void N() + { + string? s = $$M(); + } + } + """, + MainDescription("string? X.M()"), + NullabilityAnalysis("")); + + [Fact] + public Task NullableMethodThatIsNotNull() + => TestWithOptionsAsync(TestOptions.Regular8, + """ + #nullable enable + class X + { + string M() => ""; + void N() + { + string s = $$M(); + } + } + """, + MainDescription("string X.M()"), + NullabilityAnalysis("")); + + [Fact] + public Task NullableMethodThatIsOblivious() + => TestWithOptionsAsync(TestOptions.Regular8, + """ + class X + { + string M() => ""; + void N() + { + #nullable enable + string s = $$M(); + } + } + """, + MainDescription("string X.M()"), + NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_nullable_aware, "M"))); + + [Fact] + public Task NullableMethodThatIsVoid() + => TestWithOptionsAsync(TestOptions.Regular8, + """ + #nullable enable + class X + { + void M() { } + void N() + { + string s = $$M(); + } + } + """, + MainDescription("void X.M()"), + NullabilityAnalysis("")); + + [Fact] + public Task NullableMethodThatIsVoidAndOblivious() + => TestWithOptionsAsync(TestOptions.Regular8, + """ + class X + { + void M() { } + void N() + { + #nullable enable + string s = $$M(); + } + } + """, + MainDescription("void X.M()"), + NullabilityAnalysis("")); + + [Fact] + public Task NullableNotShownPriorToLanguageVersion8() + => TestWithOptionsAsync(TestOptions.Regular7_3, """ #nullable enable @@ -8334,12 +7466,10 @@ void N() """, MainDescription($"({FeaturesResources.local_variable}) string s"), NullabilityAnalysis("")); - } [Fact] - public async Task NullableNotShownInNullableDisable() - { - await TestWithOptionsAsync(TestOptions.Regular8, + public Task NullableNotShownInNullableDisable() + => TestWithOptionsAsync(TestOptions.Regular8, """ #nullable disable @@ -8356,12 +7486,10 @@ void N() """, MainDescription($"({FeaturesResources.local_variable}) string s"), NullabilityAnalysis("")); - } [Fact] - public async Task NullableShownWhenEnabledGlobally() - { - await TestWithOptionsAsync(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable), + public Task NullableShownWhenEnabledGlobally() + => TestWithOptionsAsync(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable), """ using System.Collections.Generic; @@ -8376,12 +7504,10 @@ void N() """, MainDescription($"({FeaturesResources.local_variable}) string s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); - } [Fact] - public async Task NullableNotShownForValueType() - { - await TestWithOptionsAsync(TestOptions.Regular8, + public Task NullableNotShownForValueType() + => TestWithOptionsAsync(TestOptions.Regular8, """ #nullable enable @@ -8398,12 +7524,10 @@ void N() """, MainDescription($"({FeaturesResources.local_variable}) int a"), NullabilityAnalysis("")); - } [Fact] - public async Task NullableNotShownForConst() - { - await TestWithOptionsAsync(TestOptions.Regular8, + public Task NullableNotShownForConst() + => TestWithOptionsAsync(TestOptions.Regular8, """ #nullable enable @@ -8420,13 +7544,10 @@ void N() """, MainDescription($"({FeaturesResources.local_constant}) string? s = null"), NullabilityAnalysis("")); - } [Fact] - public async Task TestInheritdocInlineSummary() - { - var markup = - """ + public Task TestInheritdocInlineSummary() + => TestInClassAsync(""" /// Summary documentation /// Remarks documentation @@ -8434,18 +7555,13 @@ void M(int x) { } /// void $$M(int x, int y) { } - """; - - await TestInClassAsync(markup, + """, MainDescription("void C.M(int x, int y)"), Documentation("Summary documentation")); - } [Fact] - public async Task TestInheritdocTwoLevels1() - { - var markup = - """ + public Task TestInheritdocTwoLevels1() + => TestInClassAsync(""" /// Summary documentation /// Remarks documentation @@ -8456,18 +7572,13 @@ void M(int x) { } /// void $$M(int x, int y) { } - """; - - await TestInClassAsync(markup, + """, MainDescription("void C.M(int x, int y)"), Documentation("Summary documentation")); - } [Fact] - public async Task TestInheritdocTwoLevels2() - { - var markup = - """ + public Task TestInheritdocTwoLevels2() + => TestInClassAsync(""" /// Summary documentation /// Remarks documentation @@ -8478,18 +7589,13 @@ void M(int x) { } /// void $$M(int x, int y) { } - """; - - await TestInClassAsync(markup, + """, MainDescription("void C.M(int x, int y)"), Documentation("Summary documentation")); - } [Fact] - public async Task TestInheritdocWithTypeParamRef() - { - var markup = - """ + public Task TestInheritdocWithTypeParamRef() + => TestInClassAsync(""" public class Program { @@ -8510,17 +7616,13 @@ public interface ICloneable /// A clone of the . public T Clone(); } - """; - - await TestInClassAsync(markup, + """, MainDescription("Test Test.Clone()"), Documentation("Clones a Test.")); - } [Fact] - public async Task TestInheritdocWithTypeParamRef1() - { - var markup = + public Task TestInheritdocWithTypeParamRef1() + => TestWithOptionsAsync(TestOptions.Regular8, """ public interface ITest @@ -8537,70 +7639,49 @@ public class Test : ITest /// public void $$Foo() { } } - """; - - await TestWithOptionsAsync(TestOptions.Regular8, - markup, + """, MainDescription($"void Test.Foo()"), Documentation("A generic method T."), item => Assert.Equal( item.Sections.First(section => section.Kind == QuickInfoSectionKinds.DocumentationComments).TaggedParts.Select(p => p.Tag).ToArray(), ["Text", "Space", "TypeParameter", "Text"])); - } [Fact] - public async Task TestInheritdocCycle1() - { - var markup = - """ + public Task TestInheritdocCycle1() + => TestInClassAsync(""" /// void M(int x) { } /// void $$M(int x, int y) { } - """; - - await TestInClassAsync(markup, + """, MainDescription("void C.M(int x, int y)"), Documentation("")); - } [Fact] - public async Task TestInheritdocCycle2() - { - var markup = - """ + public Task TestInheritdocCycle2() + => TestInClassAsync(""" /// void $$M(int x) { } - """; - - await TestInClassAsync(markup, + """, MainDescription("void C.M(int x)"), Documentation("")); - } [Fact] - public async Task TestInheritdocCycle3() - { - var markup = - """ + public Task TestInheritdocCycle3() + => TestInClassAsync(""" /// void $$M(int x) { } - """; - - await TestInClassAsync(markup, + """, MainDescription("void C.M(int x)"), Documentation("")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38794")] - public async Task TestLinqGroupVariableDeclaration() - { - var code = - """ + public Task TestLinqGroupVariableDeclaration() + => TestInClassAsync(""" void M(string[] a) { @@ -8608,16 +7689,12 @@ void M(string[] a) group x by x.Length into $$g select g; } - """; - - await TestInClassAsync(code, + """, MainDescription($"({FeaturesResources.range_variable}) IGrouping g")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38283")] - public async Task QuickInfoOnIndexerCloseBracket() - { - await TestAsync(""" + public Task QuickInfoOnIndexerCloseBracket() + => TestAsync(""" class C { @@ -8630,12 +7707,10 @@ void M() } """, MainDescription("int C.this[int x] { get; }")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38283")] - public async Task QuickInfoOnIndexerOpenBracket() - { - await TestAsync(""" + public Task QuickInfoOnIndexerOpenBracket() + => TestAsync(""" class C { @@ -8648,12 +7723,10 @@ void M() } """, MainDescription("int C.this[int x] { get; }")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38283")] - public async Task QuickInfoOnIndexer_NotOnArrayAccess() - { - await TestAsync(""" + public Task QuickInfoOnIndexer_NotOnArrayAccess() + => TestAsync(""" class Program { @@ -8665,12 +7738,10 @@ void M() } """, MainDescription("struct System.Int32")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31618")] - public async Task QuickInfoWithRemarksOnMethod() - { - await TestAsync(""" + public Task QuickInfoWithRemarksOnMethod() + => TestAsync(""" class Program { @@ -8692,12 +7763,10 @@ int M() Remarks text """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31618")] - public async Task QuickInfoWithRemarksOnPropertyAccessor() - { - await TestAsync(""" + public Task QuickInfoWithRemarksOnPropertyAccessor() + => TestAsync(""" class Program { @@ -8716,12 +7785,10 @@ class Program Remarks text """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31618")] - public async Task QuickInfoWithReturnsOnMethod() - { - await TestAsync(""" + public Task QuickInfoWithReturnsOnMethod() + => TestAsync(""" class Program { @@ -8744,12 +7811,10 @@ int M() {FeaturesResources.Returns_colon} Returns text """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31618")] - public async Task QuickInfoWithReturnsOnPropertyAccessor() - { - await TestAsync(""" + public Task QuickInfoWithReturnsOnPropertyAccessor() + => TestAsync(""" class Program { @@ -8769,12 +7834,10 @@ class Program {FeaturesResources.Returns_colon} Returns text """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31618")] - public async Task QuickInfoWithValueOnMethod() - { - await TestAsync(""" + public Task QuickInfoWithValueOnMethod() + => TestAsync(""" class Program { @@ -8797,12 +7860,10 @@ int M() {FeaturesResources.Value_colon} Value text """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31618")] - public async Task QuickInfoWithValueOnPropertyAccessor() - { - await TestAsync(""" + public Task QuickInfoWithValueOnPropertyAccessor() + => TestAsync(""" class Program { @@ -8822,12 +7883,10 @@ class Program {FeaturesResources.Value_colon} Value text """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task QuickInfoNotPattern1() - { - await TestAsync(""" + public Task QuickInfoNotPattern1() + => TestAsync(""" class Person { @@ -8840,12 +7899,10 @@ void Goo(object o) } """, MainDescription("class Person")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task QuickInfoNotPattern2() - { - await TestAsync(""" + public Task QuickInfoNotPattern2() + => TestAsync(""" class Person { @@ -8857,12 +7914,10 @@ void Goo(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task QuickInfoOrPattern1() - { - await TestAsync(""" + public Task QuickInfoOrPattern1() + => TestAsync(""" class Person { @@ -8874,12 +7929,10 @@ void Goo(object o) } } """, MainDescription("class Person")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task QuickInfoOrPattern2() - { - await TestAsync(""" + public Task QuickInfoOrPattern2() + => TestAsync(""" class Person { @@ -8891,12 +7944,10 @@ void Goo(object o) } } """, MainDescription("struct System.Int32")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task QuickInfoOrPattern3() - { - await TestAsync(""" + public Task QuickInfoOrPattern3() + => TestAsync(""" class Person { @@ -8908,12 +7959,10 @@ void Goo(object o) } } """); - } [Fact] - public async Task QuickInfoRecord() - { - await TestWithOptionsAsync( + public Task QuickInfoRecord() + => TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), """ record Person(string First, string Last) @@ -8923,12 +7972,10 @@ void M($$Person p) } } """, MainDescription("record Person")); - } [Fact] - public async Task QuickInfoDerivedRecord() - { - await TestWithOptionsAsync( + public Task QuickInfoDerivedRecord() + => TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), """ record Person(string First, string Last) @@ -8942,45 +7989,37 @@ void M($$Student p) } """, MainDescription("record Student")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44904")] - public async Task QuickInfoRecord_BaseTypeList() - { - await TestAsync(""" + public Task QuickInfoRecord_BaseTypeList() + => TestAsync(""" record Person(string First, string Last); record Student(int Id) : $$Person(null, null); """, MainDescription("Person.Person(string First, string Last)")); - } [Fact] - public async Task QuickInfoClass_BaseTypeList() - { - await TestAsync(""" + public Task QuickInfoClass_BaseTypeList() + => TestAsync(""" class Person(string First, string Last); class Student(int Id) : $$Person(null, null); """, MainDescription("Person.Person(string First, string Last)")); - } [Fact] - public async Task QuickInfo_BaseConstructorInitializer() - { - await TestAsync(""" + public Task QuickInfo_BaseConstructorInitializer() + => TestAsync(""" public class Person { public Person(int id) { } } public class Student : Person { public Student() : $$base(0) { } } """, MainDescription("Person.Person(int id)")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57031")] - public async Task QuickInfo_DotInInvocation() - { - await TestAsync(""" + public Task QuickInfo_DotInInvocation() + => TestAsync(""" public class C { @@ -8998,12 +8037,10 @@ static void Main() } """, MainDescription($"void C.M(int a, params int[] b) (+ 1 {FeaturesResources.overload})")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57031")] - public async Task QuickInfo_BeforeMemberNameInInvocation() - { - await TestAsync(""" + public Task QuickInfo_BeforeMemberNameInInvocation() + => TestAsync(""" public class C { @@ -9021,12 +8058,10 @@ static void Main() } """, MainDescription($"void C.M(int a, params int[] b) (+ 1 {FeaturesResources.overload})")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57031")] - public async Task QuickInfo_AfterMemberNameInInvocation() - { - await TestAsync(""" + public Task QuickInfo_AfterMemberNameInInvocation() + => TestAsync(""" public class C { @@ -9044,12 +8079,10 @@ static void Main() } """, MainDescription($"void C.M(int a, params int[] b) (+ 1 {FeaturesResources.overload})")); - } [Fact] - public async Task QuickInfoRecordClass() - { - await TestWithOptionsAsync( + public Task QuickInfoRecordClass() + => TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), """ record class Person(string First, string Last) @@ -9059,12 +8092,10 @@ void M($$Person p) } } """, MainDescription("record Person")); - } [Fact] - public async Task QuickInfoRecordStruct() - { - await TestWithOptionsAsync( + public Task QuickInfoRecordStruct() + => TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), """ record struct Person(string First, string Last) @@ -9074,12 +8105,10 @@ void M($$Person p) } } """, MainDescription("record struct Person")); - } [Fact] - public async Task QuickInfoReadOnlyRecordStruct() - { - await TestWithOptionsAsync( + public Task QuickInfoReadOnlyRecordStruct() + => TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), """ readonly record struct Person(string First, string Last) @@ -9089,12 +8118,10 @@ void M($$Person p) } } """, MainDescription("readonly record struct Person")); - } [Fact] - public async Task QuickInfoRecordProperty() - { - await TestWithOptionsAsync( + public Task QuickInfoRecordProperty() + => TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), """ /// The person's first name. @@ -9106,14 +8133,12 @@ void M(Person p) } } """, -MainDescription("string Person.First { get; init; }"), -Documentation("The person's first name.")); - } + MainDescription("string Person.First { get; init; }"), + Documentation("The person's first name.")); [Fact] - public async Task QuickInfoFieldKeyword() - { - await TestWithOptionsAsync( + public Task QuickInfoFieldKeyword() + => TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.Preview), """ class C @@ -9125,13 +8150,11 @@ int Prop } } """, -MainDescription("(field) int C.Prop.field")); - } + MainDescription("(field) int C.Prop.field")); - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51615")] - public async Task TestVarPatternOnVarKeyword() - { - await TestAsync( + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51615")] + public Task TestVarPatternOnVarKeyword() + => TestAsync( """ class C { @@ -9146,12 +8169,10 @@ void M2() } """, MainDescription("class System.String")); - } [Fact] - public async Task TestVarPatternOnVariableItself() - { - await TestAsync( + public Task TestVarPatternOnVariableItself() + => TestAsync( """ class C { @@ -9166,12 +8187,10 @@ void M2() } """, MainDescription($"({FeaturesResources.local_variable}) string? x")); - } [Fact] - public async Task TestVarPatternOnVarKeyword_InListPattern() - { - await TestAsync( + public Task TestVarPatternOnVarKeyword_InListPattern() + => TestAsync( """ class C { @@ -9184,12 +8203,10 @@ void M(char[] array) } """, MainDescription("struct System.Char")); - } [Fact] - public async Task TestVarPatternOnVariableItself_InListPattern() - { - await TestAsync( + public Task TestVarPatternOnVariableItself_InListPattern() + => TestAsync( """ class C { @@ -9202,12 +8219,10 @@ void M(char[] array) } """, MainDescription($"({FeaturesResources.local_variable}) char one")); - } [Fact] - public async Task TestVarPatternOnVarKeyword_InSlicePattern() - { - await TestAsync( + public Task TestVarPatternOnVarKeyword_InSlicePattern() + => TestAsync( """ class C { @@ -9220,12 +8235,10 @@ void M(char[] array) } """ + TestSources.Index + TestSources.Range, MainDescription("char[]")); - } [Fact] - public async Task TestVarPatternOnVariableItself_InSlicePattern() - { - await TestAsync( + public Task TestVarPatternOnVariableItself_InSlicePattern() + => TestAsync( """ class C { @@ -9238,13 +8251,10 @@ void M(char[] array) } """ + TestSources.Index + TestSources.Range, MainDescription($"({FeaturesResources.local_variable}) char[]? one")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53135")] - public async Task TestDocumentationCData() - { - var markup = - """ + public Task TestDocumentationCData() + => TestAsync(""" using I$$ = IGoo; /// /// summary for interface IGoo @@ -9253,22 +8263,17 @@ public async Task TestDocumentationCData() /// ]]> /// interface IGoo { } - """; - - await TestAsync(markup, + """, MainDescription("interface IGoo"), Documentation(""" summary for interface IGoo List y = null; """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37503")] - public async Task DoNotNormalizeWhitespaceForCode() - { - var markup = - """ + public Task DoNotNormalizeWhitespaceForCode() + => TestAsync(""" using I$$ = IGoo; /// /// Normalize this, and Also this @@ -9278,9 +8283,7 @@ public async Task DoNotNormalizeWhitespaceForCode() /// /// interface IGoo { } - """; - - await TestAsync(markup, + """, MainDescription("interface IGoo"), Documentation(""" Normalize this, and Also this @@ -9288,13 +8291,10 @@ await TestAsync(markup, line 1 line 2 """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57262")] - public async Task DoNotNormalizeLeadingWhitespaceForCode() - { - var markup = - """ + public Task DoNotNormalizeLeadingWhitespaceForCode() + => TestAsync(""" using I$$ = IGoo; /// /// Normalize this, and Also this @@ -9304,9 +8304,7 @@ public async Task DoNotNormalizeLeadingWhitespaceForCode() /// /// interface IGoo { } - """; - - await TestAsync(markup, + """, MainDescription("interface IGoo"), Documentation(""" Normalize this, and Also this @@ -9314,27 +8312,21 @@ await TestAsync(markup, line 1 line 2 """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57262")] - public async Task ParsesEmptySummary() - { - var markup = - """ + public Task ParsesEmptySummary() + => TestAsync(""" using I$$ = IGoo; /// interface IGoo { } - """; - - await TestAsync(markup, + """, MainDescription("interface IGoo"), Documentation("")); - } [Fact] - public async Task TestStaticAbstract_ImplicitImplementation() - { - var code = """ + public Task TestStaticAbstract_ImplicitImplementation() + => TestAsync( + """ interface I1 { @@ -9347,18 +8339,14 @@ class C1_1 : I1 public static void $$M1() { } } - """; - - await TestAsync( - code, + """, MainDescription("void C1_1.M1()"), Documentation("Summary text")); - } [Fact] - public async Task TestStaticAbstract_ImplicitImplementation_FromReference() - { - var code = """ + public Task TestStaticAbstract_ImplicitImplementation_FromReference() + => TestAsync( + """ interface I1 { @@ -9376,18 +8364,14 @@ class R public static void M() { C1_1.$$M1(); } } - """; - - await TestAsync( - code, + """, MainDescription("void C1_1.M1()"), Documentation("Summary text")); - } [Fact] - public async Task TestStaticAbstract_FromTypeParameterReference() - { - var code = """ + public Task TestStaticAbstract_FromTypeParameterReference() + => TestAsync( + """ interface I1 { @@ -9400,18 +8384,14 @@ class R public static void M() where T : I1 { T.$$M1(); } } - """; - - await TestAsync( - code, + """, MainDescription("void I1.M1()"), Documentation("Summary text")); - } [Fact] - public async Task TestStaticAbstract_ExplicitInheritdoc_ImplicitImplementation() - { - var code = """ + public Task TestStaticAbstract_ExplicitInheritdoc_ImplicitImplementation() + => TestAsync( + """ interface I1 { @@ -9425,18 +8405,14 @@ class C1_1 : I1 public static void $$M1() { } } - """; - - await TestAsync( - code, + """, MainDescription("void C1_1.M1()"), Documentation("Summary text")); - } [Fact] - public async Task TestStaticAbstract_ExplicitImplementation() - { - var code = """ + public Task TestStaticAbstract_ExplicitImplementation() + => TestAsync( + """ interface I1 { @@ -9449,18 +8425,14 @@ class C1_1 : I1 static void I1.$$M1() { } } - """; - - await TestAsync( - code, + """, MainDescription("void C1_1.M1()"), Documentation("Summary text")); - } [Fact] - public async Task TestStaticAbstract_ExplicitInheritdoc_ExplicitImplementation() - { - var code = """ + public Task TestStaticAbstract_ExplicitInheritdoc_ExplicitImplementation() + => TestAsync( + """ interface I1 { @@ -9474,18 +8446,13 @@ class C1_1 : I1 static void I1.$$M1() { } } - """; - - await TestAsync( - code, + """, MainDescription("void C1_1.M1()"), Documentation("Summary text")); - } [Fact] - public async Task QuickInfoLambdaReturnType_01() - { - await TestWithOptionsAsync( + public Task QuickInfoLambdaReturnType_01() + => TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), """ class Program @@ -9494,12 +8461,10 @@ class Program } """, MainDescription("struct System.Boolean")); - } [Fact] - public async Task QuickInfoLambdaReturnType_02() - { - await TestWithOptionsAsync( + public Task QuickInfoLambdaReturnType_02() + => TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), """ class A @@ -9509,12 +8474,10 @@ struct B { } } """, MainDescription("struct A.B")); - } [Fact] - public async Task QuickInfoLambdaReturnType_03() - { - await TestWithOptionsAsync( + public Task QuickInfoLambdaReturnType_03() + => TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), """ class A @@ -9526,12 +8489,10 @@ struct B } """, MainDescription("struct B")); - } [Fact] - public async Task TestNormalFuncSynthesizedLambdaType() - { - await TestAsync( + public Task TestNormalFuncSynthesizedLambdaType() + => TestAsync( """ class C { @@ -9547,12 +8508,10 @@ void M() T {FeaturesResources.is_} int TResult {FeaturesResources.is_} string """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58871")] - public async Task TestInferredNonAnonymousDelegateType1() - { - await TestAsync( + public Task TestInferredNonAnonymousDelegateType1() + => TestAsync( """ class C { @@ -9564,12 +8523,10 @@ void M() """, MainDescription("delegate TResult System.Func(T arg)"), AnonymousTypes("")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58871")] - public async Task TestAnonymousSynthesizedLambdaType() - { - await TestAsync( + public Task TestAnonymousSynthesizedLambdaType() + => TestAsync( """ class C { @@ -9581,12 +8538,10 @@ void M() """, MainDescription("delegate string (ref int arg)"), AnonymousTypes("")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58871")] - public async Task TestAnonymousSynthesizedLambdaType2() - { - await TestAsync( + public Task TestAnonymousSynthesizedLambdaType2() + => TestAsync( """ class C { @@ -9603,12 +8558,10 @@ void M() {FeaturesResources.Types_colon} 'a {FeaturesResources.is_} delegate string (ref int arg) """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58871")] - public async Task TestAnonymousSynthesizedLambdaType3() - { - await TestAsync( + public Task TestAnonymousSynthesizedLambdaType3() + => TestAsync( """ class C { @@ -9628,12 +8581,10 @@ void M() {FeaturesResources.Types_colon} 'a {FeaturesResources.is_} delegate string (ref int arg) """)); - } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] - public async Task TestAnonymousSynthesizedLambdaType4() - { - await TestAsync( + public Task TestAnonymousSynthesizedLambdaType4() + => TestAsync( """ class C @@ -9646,19 +8597,17 @@ void M() } """, -MainDescription($"({FeaturesResources.local_variable}) 'a lam"), + MainDescription($"({FeaturesResources.local_variable}) 'a lam"), AnonymousTypes( $""" {FeaturesResources.Types_colon} 'a {FeaturesResources.is_} delegate int (int arg = 42) """)); - } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] - public async Task TestAnonymousSynthesizedLambdaType5() - { - await TestAsync( + public Task TestAnonymousSynthesizedLambdaType5() + => TestAsync( """ class C @@ -9670,12 +8619,10 @@ void M() } """, MainDescription("delegate int (int arg = 42)")); - } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] - public async Task TestAnonymousSynthesizedLambdaType6() - { - await TestAsync( + public Task TestAnonymousSynthesizedLambdaType6() + => TestAsync( """ class C @@ -9687,12 +8634,10 @@ void M() } """, MainDescription("struct System.Int32")); - } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] - public async Task TestAnonymousSynthesizedLambdaType7() - { - await TestAsync( + public Task TestAnonymousSynthesizedLambdaType7() + => TestAsync( """ class C @@ -9704,12 +8649,10 @@ void M() } """, MainDescription($"({FeaturesResources.parameter}) int param = 42")); - } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] - public async Task TestAnonymousSynthesizedLambdaType8() - { - await TestAsync( + public Task TestAnonymousSynthesizedLambdaType8() + => TestAsync( """ class C @@ -9721,12 +8664,10 @@ void M() } """, MainDescription("struct System.Int32")); - } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] - public async Task TestAnonymousSynthesizedLambdaType9() - { - await TestAsync(""" + public Task TestAnonymousSynthesizedLambdaType9() + => TestAsync(""" class C { void M() @@ -9742,12 +8683,10 @@ void M() {FeaturesResources.Types_colon} 'a {FeaturesResources.is_} delegate int (params int[] arg) """)); - } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] - public async Task TestAnonymousSynthesizedLambdaType10() - { - await TestAsync(""" + public Task TestAnonymousSynthesizedLambdaType10() + => TestAsync(""" class C { void M() @@ -9757,12 +8696,10 @@ void M() } """, MainDescription("delegate int (params int[] arg)")); - } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] - public async Task TestAnonymousSynthesizedLambdaType11() - { - await TestAsync(""" + public Task TestAnonymousSynthesizedLambdaType11() + => TestAsync(""" class C { void M() @@ -9772,12 +8709,10 @@ void M() } """, MainDescription("struct System.Int32")); - } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] - public async Task TestAnonymousSynthesizedLambdaType12() - { - await TestAsync(""" + public Task TestAnonymousSynthesizedLambdaType12() + => TestAsync(""" class C { void M() @@ -9787,12 +8722,10 @@ void M() } """, MainDescription($"({FeaturesResources.parameter}) params int[] xs")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61320")] - public async Task TestSingleTupleType() - { - await TestInClassAsync( + public Task TestSingleTupleType() + => TestInClassAsync( """ void M((int x, string y) t) { } void N() @@ -9803,12 +8736,10 @@ void N() MainDescription(@"void C.M((int x, string y) t)"), NoTypeParameterMap, AnonymousTypes(string.Empty)); - } [Fact] - public async Task TestMultipleTupleTypesSameType() - { - await TestInClassAsync( + public Task TestMultipleTupleTypesSameType() + => TestInClassAsync( """ void M((int x, string y) s, (int x, string y) t) { } void N() @@ -9823,12 +8754,10 @@ void N() {FeaturesResources.Types_colon} 'a {FeaturesResources.is_} (int x, string y) """)); - } [Fact] - public async Task TestMultipleTupleTypesDifferentTypes1() - { - await TestInClassAsync( + public Task TestMultipleTupleTypesDifferentTypes1() + => TestInClassAsync( """ void M((int x, string y) s, (int a, string b) u) { } void N() @@ -9838,12 +8767,10 @@ void N() """, MainDescription(@"void C.M((int x, string y) s, (int a, string b) u)"), NoTypeParameterMap); - } [Fact] - public async Task TestMultipleTupleTypesDifferentTypes2() - { - await TestInClassAsync( + public Task TestMultipleTupleTypesDifferentTypes2() + => TestInClassAsync( """ void M((int x, string y) s, (int x, string y) t, (int a, string b) u, (int a, string b) v) { } void N() @@ -9859,12 +8786,10 @@ void N() 'a {FeaturesResources.is_} (int x, string y) 'b {FeaturesResources.is_} (int a, string b) """)); - } [Fact] - public async Task TestMultipleTupleTypesDifferentTypes3() - { - await TestInClassAsync( + public Task TestMultipleTupleTypesDifferentTypes3() + => TestInClassAsync( """ void M((int x, string y) s, (int x, string y) t, (int a, string b) u) { } void N() @@ -9880,12 +8805,10 @@ void N() 'a {FeaturesResources.is_} (int x, string y) 'b {FeaturesResources.is_} (int a, string b) """)); - } [Fact] - public async Task TestMultipleTupleTypesInference() - { - await TestInClassAsync( + public Task TestMultipleTupleTypesInference() + => TestInClassAsync( """ T M(T t) { } void N() @@ -9901,12 +8824,10 @@ void N() {FeaturesResources.Types_colon} 'a {FeaturesResources.is_} (int a, string b) """)); - } [Fact] - public async Task TestAnonymousTypeWithTupleTypesInference1() - { - await TestInClassAsync( + public Task TestAnonymousTypeWithTupleTypesInference1() + => TestInClassAsync( """ T M(T t) { } void N() @@ -9922,12 +8843,10 @@ void N() {{FeaturesResources.Types_colon}} 'a {{FeaturesResources.is_}} new { (int a, string b) x } """)); - } [Fact] - public async Task TestAnonymousTypeWithTupleTypesInference2() - { - await TestInClassAsync( + public Task TestAnonymousTypeWithTupleTypesInference2() + => TestInClassAsync( """ T M(T t) { } void N() @@ -9944,46 +8863,38 @@ void N() 'a {{FeaturesResources.is_}} new { 'b x, 'b y } 'b {{FeaturesResources.is_}} (int a, string b) """)); - } [Fact] - public async Task TestInRawStringInterpolation_SingleLine() - { - await TestInMethodAsync( + public Task TestInRawStringInterpolation_SingleLine() + => TestInMethodAsync( """" var x = 1; var s = $"""Hello world {$$x}""" """", MainDescription($"({FeaturesResources.local_variable}) int x")); - } [Fact] - public async Task TestInRawStringInterpolation_SingleLine_MultiBrace() - { - await TestInMethodAsync( + public Task TestInRawStringInterpolation_SingleLine_MultiBrace() + => TestInMethodAsync( """" var x = 1; var s = ${|#0:|}$"""Hello world {{$$x}}""" """", MainDescription($"({FeaturesResources.local_variable}) int x")); - } [Fact] - public async Task TestInRawStringLiteral_SingleLine_Const() - { - await TestInClassAsync( + public Task TestInRawStringLiteral_SingleLine_Const() + => TestInClassAsync( """" const string $$s = """Hello world""" """", MainDescription($"""" ({FeaturesResources.constant}) string C.s = """Hello world""" """")); - } [Fact] - public async Task TestInRawStringInterpolation_MultiLine() - { - await TestInMethodAsync( + public Task TestInRawStringInterpolation_MultiLine() + => TestInMethodAsync( """" var x = 1; var s = $""" @@ -9991,12 +8902,10 @@ Hello world {$$x} """ """", MainDescription($"({FeaturesResources.local_variable}) int x")); - } [Fact] - public async Task TestInRawStringInterpolation_MultiLine_MultiBrace() - { - await TestInMethodAsync( + public Task TestInRawStringInterpolation_MultiLine_MultiBrace() + => TestInMethodAsync( """" var x = 1; var s = ${|#0:|}$""" @@ -10004,12 +8913,10 @@ Hello world {{$$x}} """ """", MainDescription($"({FeaturesResources.local_variable}) int x")); - } [Fact] - public async Task TestInRawStringLiteral_MultiLine_Const() - { - await TestInClassAsync( + public Task TestInRawStringLiteral_MultiLine_Const() + => TestInClassAsync( """" const string $$s = """ Hello world @@ -10020,30 +8927,22 @@ Hello world Hello world """ """")); - } [Fact] - public async Task TestArgsInTopLevel() - { - var markup = - """ + public Task TestArgsInTopLevel() + => TestWithOptionsAsync( + Options.Regular, """ forach (var arg in $$args) { } - """; - - await TestWithOptionsAsync( - Options.Regular, markup, + """, MainDescription($"({FeaturesResources.parameter}) string[] args")); - } [Fact] - public async Task TestArgsInNormalProgram() - { - var markup = - """ + public Task TestArgsInNormalProgram() + => TestAsync(""" class Program { @@ -10055,16 +8954,12 @@ static void Main(string[] args) } } - """; - - await TestAsync(markup, + """, MainDescription($"({FeaturesResources.parameter}) string[] args")); - } [Fact] - public async Task TestParameterInMethodAttributeNameof() - { - var source = """ + public Task TestParameterInMethodAttributeNameof() + => TestWithOptionsAsync(Options.Regular.WithLanguageVersion(LanguageVersion.CSharp11), """ class Program { @@ -10072,30 +8967,24 @@ class Program void M(string s) { } } - """; - await TestWithOptionsAsync(Options.Regular.WithLanguageVersion(LanguageVersion.CSharp11), source, + """, MainDescription($"({FeaturesResources.parameter}) string s")); - } [Fact] - public async Task TestParameterInMethodParameterAttributeNameof() - { - var source = """ + public Task TestParameterInMethodParameterAttributeNameof() + => TestWithOptionsAsync(Options.Regular.WithLanguageVersion(LanguageVersion.CSharp11), """ class Program { void M([My(nameof($$s))] string s) { } } - """; - await TestWithOptionsAsync(Options.Regular.WithLanguageVersion(LanguageVersion.CSharp11), source, + """, MainDescription($"({FeaturesResources.parameter}) string s")); - } [Fact] - public async Task TestParameterInLocalFunctionAttributeNameof() - { - var source = """ + public Task TestParameterInLocalFunctionAttributeNameof() + => TestWithOptionsAsync(Options.Regular.WithLanguageVersion(LanguageVersion.CSharp11), """ class Program { @@ -10106,16 +8995,12 @@ void local(string s) { } } } - """; - await TestWithOptionsAsync(Options.Regular.WithLanguageVersion(LanguageVersion.CSharp11), source, + """, MainDescription($"({FeaturesResources.parameter}) string s")); - } [Fact] - public async Task TestScopedParameter() - { - var source = - """ + public Task TestScopedParameter() + => TestAsync(""" ref struct R { } class Program { @@ -10130,16 +9015,12 @@ static void Main() $$F(r, r, ref r, ref r, r, r, out r, out r); } } - """; - await TestAsync(source, + """, MainDescription($"void Program.F(R r1, scoped R r2, ref R r3, scoped ref R r4, in R r5, scoped in R r6, out R r7, out R r8)")); - } [Fact] - public async Task TestScopedLocal() - { - var source = - """ + public Task TestScopedLocal() + => TestAsync(""" class Program { static void Main() @@ -10149,15 +9030,12 @@ static void Main() i = $$r; } } - """; - await TestAsync(source, + """, MainDescription($"({FeaturesResources.local_variable}) scoped ref int r")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66854")] - public async Task TestNullableRefTypeVar1() - { - var source = """ + public Task TestNullableRefTypeVar1() + => TestAsync(""" #nullable enable class C @@ -10168,15 +9046,12 @@ void M() $$var s = (string?)o; } } - """; - await TestAsync(source, + """, MainDescription($"class System.String?")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66854")] - public async Task TestNullableRefTypeVar2() - { - var source = """ + public Task TestNullableRefTypeVar2() + => TestAsync(""" #nullable disable class C @@ -10192,138 +9067,80 @@ void M() #nullable restore } - """; - await TestAsync(source, + """, MainDescription($"class System.String")); - } [Fact] - public async Task TestUsingAliasToType1() - { - var source = - @"using X = $$int;"; - await TestAsync(source, + public Task TestUsingAliasToType1() + => TestAsync(@"using X = $$int;", MainDescription($"struct System.Int32")); - } [Fact] - public async Task TestUsingAliasToType1_A() - { - var source = - @"using $$X = int;"; - await TestAsync(source, + public Task TestUsingAliasToType1_A() + => TestAsync(@"using $$X = int;", MainDescription($"struct System.Int32")); - } [Fact] - public async Task TestUsingAliasToType2() - { - var source = - @"using X = ($$int a, int b);"; - await TestAsync(source, + public Task TestUsingAliasToType2() + => TestAsync(@"using X = ($$int a, int b);", MainDescription($"struct System.Int32")); - } [Fact] - public async Task TestUsingAliasToType2_A() - { - var source = - @"using $$X = (int a, int b);"; - await TestAsync(source, + public Task TestUsingAliasToType2_A() + => TestAsync(@"using $$X = (int a, int b);", MainDescription($"(int a, int b)")); - } [Fact] - public async Task TestUsingAliasToType3() - { - var source = - @"using X = $$(int a, int b);"; - await TestAsync(source); - } + public Task TestUsingAliasToType3() + => TestAsync(@"using X = $$(int a, int b);"); [Fact] - public async Task TestUsingAliasToType4() - { - var source = - @"using unsafe X = $$delegate*;"; - await TestAsync(source); - } + public Task TestUsingAliasToType4() + => TestAsync(@"using unsafe X = $$delegate*;"); [Fact] - public async Task TestUsingAliasToType4_A() - { - var source = - @"using unsafe $$X = delegate*;"; - await TestAsync(source, + public Task TestUsingAliasToType4_A() + => TestAsync(@"using unsafe $$X = delegate*;", MainDescription($"delegate*")); - } [Fact] - public async Task TestUsingAliasToType5() - { - var source = - @"using unsafe X = $$int*;"; - await TestAsync(source, + public Task TestUsingAliasToType5() + => TestAsync(@"using unsafe X = $$int*;", MainDescription($"struct System.Int32")); - } [Fact] - public async Task TestUsingAliasToType5_A() - { - var source = - @"using unsafe $$X = int*;"; - await TestAsync(source, + public Task TestUsingAliasToType5_A() + => TestAsync(@"using unsafe $$X = int*;", MainDescription($"int*")); - } [Fact] - public async Task TestCollectionExpression_Start() - { - var source = - "int[] x = $$[1, 2]"; - await TestAsync(source, + public Task TestCollectionExpression_Start() + => TestAsync("int[] x = $$[1, 2]", MainDescription($"int[]")); - } [Fact] - public async Task TestCollectionExpression_Middle() - { - var source = - "int[] x = [1 $$, 2]"; - await TestAsync(source); - } + public Task TestCollectionExpression_Middle() + => TestAsync("int[] x = [1 $$, 2]"); [Fact] - public async Task TestCollectionExpression_End() - { - var source = - "int[] x = [1, 2]$$"; - await TestAsync(source, + public Task TestCollectionExpression_End() + => TestAsync("int[] x = [1, 2]$$", MainDescription($"int[]")); - } [Fact] - public async Task TestCollectionExpression_Start_Typeless() - { - var source = - "var x = $$[1, 2]"; - await TestAsync(source); - } + public Task TestCollectionExpression_Start_Typeless() + => TestAsync("var x = $$[1, 2]"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71638")] - public async Task TestAnonymousType() - { - var markup = """ + public Task TestAnonymousType() + => VerifyWithMscorlib45Async(""" _ = new { @string = "" }.$$@string; - """; - var description = $"string 'a.@string {{ get; }}"; - - await VerifyWithMscorlib45Async(markup, + """, [ - MainDescription(description), + MainDescription($"string 'a.@string {{ get; }}"), AnonymousTypes( $$""" @@ -10331,7 +9148,6 @@ await VerifyWithMscorlib45Async(markup, 'a {{FeaturesResources.is_}} new { string @string } """) ]); - } [Theory, CombinatorialData] public async Task UsingStatement_Class(bool simpleUsing, bool implementsIDisposable) @@ -10561,9 +9377,8 @@ void M() } [Fact] - public async Task UsingStatement_Interface() - { - await TestAsync(""" + public Task UsingStatement_Interface() + => TestAsync(""" using System; interface IMyInterface : IDisposable @@ -10581,7 +9396,6 @@ void M(IMyInterface i) } """, MainDescription("void IDisposable.Dispose()")); - } [Theory, CombinatorialData] public async Task AwaitUsingStatement_Class(bool simpleUsing, bool implementsIAsyncDisposable) @@ -10818,9 +9632,8 @@ void M() } [Fact] - public async Task AwaitUsingStatement_Interface() - { - await VerifyWithNet8Async(""" + public Task AwaitUsingStatement_Interface() + => VerifyWithNet8Async(""" using System; using System.Threading.Tasks; @@ -10839,12 +9652,10 @@ void M(IMyInterface i) } """, MainDescription($"({CSharpFeaturesResources.awaitable}) ValueTask IAsyncDisposable.DisposeAsync()")); - } [Fact] - public async Task NullConditionalAssignment() - { - await VerifyWithNet8Async(""" + public Task NullConditionalAssignment() + => VerifyWithNet8Async(""" class C { string s; @@ -10856,12 +9667,10 @@ void M(C c) } """, MainDescription($"({FeaturesResources.field}) string C.s")); - } [Fact] - public async Task TestModernExtension1() - { - await TestWithOptionsAsync( + public Task TestModernExtension1() + => TestWithOptionsAsync( CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview), """ using System; @@ -10884,12 +9693,10 @@ void M(string s) } """, MainDescription($"void Extensions.extension(string).Goo()")); - } [Fact] - public async Task TestModernExtension2() - { - await TestWithOptionsAsync( + public Task TestModernExtension2() + => TestWithOptionsAsync( CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview), """ using System; @@ -10913,12 +9720,10 @@ void M(string s) } """, MainDescription($"void Extensions.extension(string).Goo() (+ 1 {FeaturesResources.overload})")); - } [Fact] - public async Task TestModernExtension3() - { - await TestWithOptionsAsync( + public Task TestModernExtension3() + => TestWithOptionsAsync( CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview), """ using System; @@ -10942,12 +9747,10 @@ void M(string s) } """, MainDescription($"void Extensions.extension(string).Goo(int i) (+ 1 {FeaturesResources.overload})")); - } [Fact] - public async Task TestModernExtension4() - { - await TestWithOptionsAsync( + public Task TestModernExtension4() + => TestWithOptionsAsync( CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview), """ using System; @@ -10970,12 +9773,10 @@ void M(string s) } """, MainDescription($$"""int Extensions.extension(string).Prop { get; }""")); - } [Fact] - public async Task TestModernExtension5() - { - await TestWithOptionsAsync( + public Task TestModernExtension5() + => TestWithOptionsAsync( CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview), """ using System; @@ -10993,12 +9794,10 @@ public void Goo() } """, MainDescription($"({FeaturesResources.parameter}) string s")); - } [Fact] - public async Task TestModernExtension6() - { - await TestWithOptionsAsync( + public Task TestModernExtension6() + => TestWithOptionsAsync( CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview), """ using System; @@ -11016,5 +9815,4 @@ public void Goo() } """, MainDescription($"Extensions.extension(System.String)")); - } } diff --git a/src/EditorFeatures/CSharpTest/QuickInfo/SyntacticQuickInfoSourceTests.cs b/src/EditorFeatures/CSharpTest/QuickInfo/SyntacticQuickInfoSourceTests.cs index a74a78112c154..26e43ff569ebc 100644 --- a/src/EditorFeatures/CSharpTest/QuickInfo/SyntacticQuickInfoSourceTests.cs +++ b/src/EditorFeatures/CSharpTest/QuickInfo/SyntacticQuickInfoSourceTests.cs @@ -33,17 +33,19 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.QuickInfo; public sealed class SyntacticQuickInfoSourceTests : AbstractQuickInfoSourceTests { [WpfFact] - public async Task Brackets_0() - { - await TestInMethodAndScriptAsync( -@" -switch (true) -{ -}$$ -", -@"switch (true) -{"); - } + public Task Brackets_0() + => TestInMethodAndScriptAsync( + """ + + switch (true) + { + }$$ + + """, + """ + switch (true) + { + """); [WpfFact] public async Task Brackets_1() @@ -58,214 +60,234 @@ public async Task Brackets_3() => await TestInMethodAndScriptAsync("var a = new int[] { }$$ ", "new int[] {"); [WpfFact] - public async Task Brackets_4() - { - await TestInMethodAndScriptAsync( -@" -if (true) -{ -}$$ -", -@"if (true) -{"); - } + public Task Brackets_4() + => TestInMethodAndScriptAsync( + """ - [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/325")] - public async Task ScopeBrackets_0() - { - await TestInMethodAndScriptAsync( -@"if (true) + if (true) { - { - }$$ - }", + }$$ + + """, + """ + if (true) + { + """); + + [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/325")] + public Task ScopeBrackets_0() + => TestInMethodAndScriptAsync( + """ + if (true) + { + { + }$$ + } + """, "{"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/325")] - public async Task ScopeBrackets_1() - { - await TestInMethodAndScriptAsync( -@"while (true) + public Task ScopeBrackets_1() + => TestInMethodAndScriptAsync( + """ + while (true) + { + // some + // comment + { + }$$ + } + """, + """ + // some + // comment + { + """); + + [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/325")] + public Task ScopeBrackets_2() + => TestInMethodAndScriptAsync( + """ + do + { + /* comment */ + { + }$$ + } + while (true); + """, + """ + /* comment */ + { + """); + + [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/325")] + public Task ScopeBrackets_3() + => TestInMethodAndScriptAsync( + """ + if (true) + { + } + else + { + { + // some + // comment + }$$ + } + """, + """ { // some // comment - { - }$$ - }", -@"// some -// comment -{"); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/325")] - public async Task ScopeBrackets_2() - { - await TestInMethodAndScriptAsync( -@"do + public Task ScopeBrackets_4() + => TestInMethodAndScriptAsync( + """ + using (var x = new X()) + { + { + /* comment */ + }$$ + } + """, + """ { /* comment */ - { - }$$ - } - while (true);", -@"/* comment */ -{"); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/325")] - public async Task ScopeBrackets_3() - { - await TestInMethodAndScriptAsync( -@"if (true) - { - } - else + public Task ScopeBrackets_5() + => TestInMethodAndScriptAsync( + """ + foreach (var x in xs) + { + // above + { + /* below */ + }$$ + } + """, + """ + // above { - { - // some - // comment - }$$ - }", -@"{ - // some - // comment"); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/325")] - public async Task ScopeBrackets_4() - { - await TestInMethodAndScriptAsync( -@"using (var x = new X()) + public Task ScopeBrackets_6() + => TestInMethodAndScriptAsync( + """ + for (;;) + { + /*************/ + + // part 1 + + // part 2 + { + }$$ + } + """, + """ + /*************/ + + // part 1 + + // part 2 { - { - /* comment */ - }$$ - }", -@"{ - /* comment */"); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/325")] - public async Task ScopeBrackets_5() - { - await TestInMethodAndScriptAsync( -@"foreach (var x in xs) + public Task ScopeBrackets_7() + => TestInMethodAndScriptAsync( + """ + try + { + /*************/ + + // part 1 + + // part 2 + { + }$$ + } + catch { throw; } + """, + """ + /*************/ + + // part 1 + + // part 2 { - // above - { - /* below */ - }$$ - }", -@"// above -{"); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/325")] - public async Task ScopeBrackets_6() - { - await TestInMethodAndScriptAsync( -@"for (;;) + public Task ScopeBrackets_8() + => TestInMethodAndScriptAsync( + """ + { /*************/ // part 1 // part 2 - { - }$$ - }", -@"/*************/ - -// part 1 - -// part 2 -{"); - } + }$$ - [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/325")] - public async Task ScopeBrackets_7() - { - await TestInMethodAndScriptAsync( -@"try + """, + """ { /*************/ // part 1 // part 2 - { - }$$ - } - catch { throw; }", -@"/*************/ - -// part 1 - -// part 2 -{"); - } - - [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/325")] - public async Task ScopeBrackets_8() - { - await TestInMethodAndScriptAsync( -@" -{ - /*************/ - - // part 1 - - // part 2 -}$$ -", -@"{ - /*************/ - - // part 1 - - // part 2"); - } + """); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/325")] - public async Task ScopeBrackets_9() - { - await TestInClassAsync( -@"int Property -{ - set - { - { - }$$ - } -}", + public Task ScopeBrackets_9() + => TestInClassAsync( + """ + int Property + { + set + { + { + }$$ + } + } + """, "{"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/325")] - public async Task ScopeBrackets_10() - { - await TestInMethodAndScriptAsync( -@"switch (true) + public Task ScopeBrackets_10() + => TestInMethodAndScriptAsync( + """ + switch (true) + { + default: + // comment + { + }$$ + break; + } + """, + """ + // comment { - default: - // comment - { - }$$ - break; - }", -@"// comment -{"); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56507")] - public async Task RegionEndShowsStartRegionMessage() - { - await TestAsync( -@" -#region Start -#end$$region", "#region Start"); - } + public Task RegionEndShowsStartRegionMessage() + => TestAsync( + """ + + #region Start + #end$$region + """, "#region Start"); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/56507")] [InlineData("$$#endregion")] @@ -273,13 +295,13 @@ await TestAsync( [InlineData("#endregion$$ ")] [InlineData("#endregion$$\r\n")] [InlineData("#endregion$$ End")] - public async Task RegionEndShowsStartRegionMessageAtDifferentPositions(string endRegion) - { - await TestAsync( -@$" -#region Start -{endRegion}", "#region Start"); - } + public Task RegionEndShowsStartRegionMessageAtDifferentPositions(string endRegion) + => TestAsync( + $""" + + #region Start + {endRegion} + """, "#region Start"); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/56507")] [InlineData("#endregion$$")] @@ -288,223 +310,221 @@ await TestAsync( [InlineData("#endregion En$$d")] [InlineData("#endregion $$")] [InlineData("#endregion\r\n$$")] - public async Task RegionEndQuickInfoIsNotOfferedAtDifferentPositions(string endRegion) - { - await TestAsync( -@$" -#region Start -{endRegion}", ""); - } + public Task RegionEndQuickInfoIsNotOfferedAtDifferentPositions(string endRegion) + => TestAsync( + $""" + + #region Start + {endRegion} + """, ""); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56507")] - public async Task RegionEndHasNoQuickinfo_MissingRegionStart_1() - { - await TestAsync( + public Task RegionEndHasNoQuickinfo_MissingRegionStart_1() + => TestAsync( @$"#end$$region", ""); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56507")] - public async Task RegionEndHasNoQuickinfo_MissingRegionStart_2() - { - await TestAsync( -@$" -#region Start -#endregion -#end$$region", ""); - } + public Task RegionEndHasNoQuickinfo_MissingRegionStart_2() + => TestAsync( + $""" + + #region Start + #endregion + #end$$region + """, ""); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56507")] - public async Task RegionEndShowsRegionStart_Nesting_1() - { - await TestAsync( -@$" -#region Start1 -#region Start2 -#endregion -#end$$region", "#region Start1"); - } + public Task RegionEndShowsRegionStart_Nesting_1() + => TestAsync( + $""" + + #region Start1 + #region Start2 + #endregion + #end$$region + """, "#region Start1"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56507")] - public async Task RegionEndShowsRegionStart_Nesting_2() - { - await TestAsync( -@$" -#region Start1 -#region Start2 -#end$$region -#endregion", "#region Start2"); - } + public Task RegionEndShowsRegionStart_Nesting_2() + => TestAsync( + $""" + + #region Start1 + #region Start2 + #end$$region + #endregion + """, "#region Start2"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56507")] - public async Task RegionEndShowsRegionStart_Blocks_1() - { - await TestAsync( -@$" -#region Start1 -#end$$region -#region Start2 -#endregion", "#region Start1"); - } + public Task RegionEndShowsRegionStart_Blocks_1() + => TestAsync( + $""" + + #region Start1 + #end$$region + #region Start2 + #endregion + """, "#region Start1"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56507")] - public async Task RegionEndShowsRegionStart_Blocks_2() - { - await TestAsync( -@$" -#region Start1 -#endregion -#region Start2 -#end$$region", "#region Start2"); - } + public Task RegionEndShowsRegionStart_Blocks_2() + => TestAsync( + $""" + + #region Start1 + #endregion + #region Start2 + #end$$region + """, "#region Start2"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56507")] - public async Task EndIfShowsIfCondition_1() - { - await TestAsync( -@$" -#if DEBUG -#end$$if", "#if DEBUG"); - } + public Task EndIfShowsIfCondition_1() + => TestAsync( + $""" + + #if DEBUG + #end$$if + """, "#if DEBUG"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56507")] - public async Task EndIfShowsIfCondition_2() - { - await TestAsync( -@$" -#if DEBUG -#else -#end$$if", "#if DEBUG\r\n#else"); - } + public Task EndIfShowsIfCondition_2() + => TestAsync( + $""" + + #if DEBUG + #else + #end$$if + """, "#if DEBUG\r\n#else"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56507")] - public async Task EndIfShowsElIfCondition() - { - await TestAsync( -@$" -#if DEBUG -#elif RELEASE -#end$$if", "#if DEBUG\r\n#elif RELEASE"); - } + public Task EndIfShowsElIfCondition() + => TestAsync( + $""" + + #if DEBUG + #elif RELEASE + #end$$if + """, "#if DEBUG\r\n#elif RELEASE"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56507")] - public async Task ElseShowsIfCondition() - { - await TestAsync( -@$" -#if DEBUG -#el$$se -#endif", "#if DEBUG"); - } + public Task ElseShowsIfCondition() + => TestAsync( + $""" + + #if DEBUG + #el$$se + #endif + """, "#if DEBUG"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56507")] - public async Task ElseShowsElIfCondition_1() - { - await TestAsync( -@$" -#if DEBUG -#elif RELEASE -#el$$se -#endif", "#if DEBUG\r\n#elif RELEASE"); - } + public Task ElseShowsElIfCondition_1() + => TestAsync( + $""" + + #if DEBUG + #elif RELEASE + #el$$se + #endif + """, "#if DEBUG\r\n#elif RELEASE"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56507")] - public async Task ElseShowsElIfCondition_2() - { - await TestAsync( -@$" -#if DEBUG -#elif RELEASE -#elif DEMO -#el$$se -#endif", "#if DEBUG\r\n#elif RELEASE\r\n#elif DEMO"); - } + public Task ElseShowsElIfCondition_2() + => TestAsync( + $""" + + #if DEBUG + #elif RELEASE + #elif DEMO + #el$$se + #endif + """, "#if DEBUG\r\n#elif RELEASE\r\n#elif DEMO"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56507")] - public async Task ElIfShowsIfCondition() - { - await TestAsync( -@$" -#if DEBUG -#el$$if RELEASE -#endif", "#if DEBUG"); - } + public Task ElIfShowsIfCondition() + => TestAsync( + $""" + + #if DEBUG + #el$$if RELEASE + #endif + """, "#if DEBUG"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56507")] - public async Task EndIfShowsIfNested_1() - { - await TestAsync( -@$" -#if DEBUG -#if RELEASE -#end$$if -#endif", "#if RELEASE"); - } + public Task EndIfShowsIfNested_1() + => TestAsync( + $""" + + #if DEBUG + #if RELEASE + #end$$if + #endif + """, "#if RELEASE"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56507")] - public async Task EndIfShowsIfNested_2() - { - await TestAsync( -@$" -#if DEBUG -#if RELEASE -#endif -#end$$if", "#if DEBUG"); - } + public Task EndIfShowsIfNested_2() + => TestAsync( + $""" + + #if DEBUG + #if RELEASE + #endif + #end$$if + """, "#if DEBUG"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56507")] - public async Task EndIfShowsIfNested_3() - { - await TestAsync( -@$" -#if DEBUG -#elif RELEASE -#if DEMO -#end$$if -#endif", "#if DEMO"); - } + public Task EndIfShowsIfNested_3() + => TestAsync( + $""" + + #if DEBUG + #elif RELEASE + #if DEMO + #end$$if + #endif + """, "#if DEMO"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56507")] - public async Task EndIfShowsIfNested_4() - { - await TestAsync( -@$" -#if DEBUG -#elif RELEASE -#if DEMO -#endif -#end$$if", "#if DEBUG\r\n#elif RELEASE"); - } + public Task EndIfShowsIfNested_4() + => TestAsync( + $""" + + #if DEBUG + #elif RELEASE + #if DEMO + #endif + #end$$if + """, "#if DEBUG\r\n#elif RELEASE"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56507")] - public async Task EndIfHasNoQuickinfo_MissingIf_1() - { - await TestAsync( -@$" -#end$$if", ""); - } + public Task EndIfHasNoQuickinfo_MissingIf_1() + => TestAsync( + $""" + + #end$$if + """, ""); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56507")] - public async Task EndIfHasNoQuickinfo_MissingIf_2() - { - await TestAsync( -@$" -#if DEBUG -#endif -#end$$if", ""); - } + public Task EndIfHasNoQuickinfo_MissingIf_2() + => TestAsync( + $""" + + #if DEBUG + #endif + #end$$if + """, ""); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/56507")] [InlineData("#$$elif RELEASE")] [InlineData("#elif$$ RELEASE")] [InlineData("#elif RELEASE$$")] - public async Task ElifHasQuickinfoAtDifferentPositions(string elif) - { - await TestAsync( -@$" -#if DEBUG -{elif} -#endif", "#if DEBUG"); - } + public Task ElifHasQuickinfoAtDifferentPositions(string elif) + => TestAsync( + $""" + + #if DEBUG + {elif} + #endif + """, "#if DEBUG"); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/56507")] [InlineData("#elif $$RELEASE")] @@ -518,14 +538,14 @@ await TestAsync( [InlineData("#elif RELEASE &$$& DEMO")] [InlineData("#elif ($$ RELEASE && DEMO)")] [InlineData("#elif (RELEASE && DEMO $$)")] - public async Task ElifHasNoQuickinfoAtDifferentPositions(string elif) - { - await TestAsync( -@$" -#if DEBUG -{elif} -#endif", ""); - } + public Task ElifHasNoQuickinfoAtDifferentPositions(string elif) + => TestAsync( + $""" + + #if DEBUG + {elif} + #endif + """, ""); private static QuickInfoProvider CreateProvider() => new CSharpSyntacticQuickInfoProvider(); @@ -578,15 +598,19 @@ protected override async Task AssertContentIsAsync( protected override Task TestInMethodAsync(string code, string expectedContent, string expectedDocumentationComment = null) { return TestInClassAsync( -@"void M() -{" + code + "}", expectedContent, expectedDocumentationComment); + """ + void M() + { + """ + code + "}", expectedContent, expectedDocumentationComment); } protected override Task TestInClassAsync(string code, string expectedContent, string expectedDocumentationComment = null) { return TestAsync( -@"class C -{" + code + "}", expectedContent, expectedDocumentationComment); + """ + class C + { + """ + code + "}", expectedContent, expectedDocumentationComment); } protected override Task TestInScriptAsync(string code, string expectedContent, string expectedDocumentationComment = null) diff --git a/src/EditorFeatures/CSharpTest/ReassignedVariable/CSharpReassignedVariableTests.cs b/src/EditorFeatures/CSharpTest/ReassignedVariable/CSharpReassignedVariableTests.cs index 0fe06e5017fb4..4570c273e37ac 100644 --- a/src/EditorFeatures/CSharpTest/ReassignedVariable/CSharpReassignedVariableTests.cs +++ b/src/EditorFeatures/CSharpTest/ReassignedVariable/CSharpReassignedVariableTests.cs @@ -16,9 +16,8 @@ protected override EditorTestWorkspace CreateWorkspace(string markup) => EditorTestWorkspace.CreateCSharp(markup); [Fact] - public async Task TestNoParameterReassignment() - { - await TestAsync( + public Task TestNoParameterReassignment() + => TestAsync( """ class C { @@ -27,12 +26,10 @@ void M(int p) } } """); - } [Fact] - public async Task TestParameterReassignment() - { - await TestAsync( + public Task TestParameterReassignment() + => TestAsync( """ class C { @@ -42,12 +39,10 @@ void M(int [|p|]) } } """); - } [Fact] - public async Task TestParameterReassignmentWhenReadAfter() - { - await TestAsync( + public Task TestParameterReassignmentWhenReadAfter() + => TestAsync( """ using System; class C @@ -59,12 +54,10 @@ void M(int [|p|]) } } """); - } [Fact] - public async Task TestParameterReassignmentWhenReadBefore() - { - await TestAsync( + public Task TestParameterReassignmentWhenReadBefore() + => TestAsync( """ using System; class C @@ -76,12 +69,10 @@ void M(int [|p|]) } } """); - } [Fact] - public async Task TestParameterReassignmentWhenReadWithDefaultValue() - { - await TestAsync( + public Task TestParameterReassignmentWhenReadWithDefaultValue() + => TestAsync( """ using System; class C @@ -93,12 +84,10 @@ void M(int [|p|] = 1) } } """); - } [Fact] - public async Task TestParameterWithExprBodyWithReassignment() - { - await TestAsync( + public Task TestParameterWithExprBodyWithReassignment() + => TestAsync( """ using System; class C @@ -106,12 +95,10 @@ class C void M(int [|p|]) => Console.WriteLine([|p|]++); } """); - } [Fact] - public async Task TestLocalFunctionWithExprBodyWithReassignment() - { - await TestAsync( + public Task TestLocalFunctionWithExprBodyWithReassignment() + => TestAsync( """ using System; class C @@ -122,12 +109,10 @@ void Local(int [|p|]) => Console.WriteLine([|p|]++); } """); - } [Fact] - public async Task TestIndexerWithWriteInExprBody() - { - await TestAsync( + public Task TestIndexerWithWriteInExprBody() + => TestAsync( """ using System; class C @@ -135,12 +120,10 @@ class C int this[int [|p|]] => [|p|]++; } """); - } [Fact] - public async Task TestIndexerWithWriteInGetter1() - { - await TestAsync( + public Task TestIndexerWithWriteInGetter1() + => TestAsync( """ using System; class C @@ -148,12 +131,10 @@ class C int this[int [|p|]] { get => [|p|]++; } } """); - } [Fact] - public async Task TestIndexerWithWriteInGetter2() - { - await TestAsync( + public Task TestIndexerWithWriteInGetter2() + => TestAsync( """ using System; class C @@ -161,12 +142,10 @@ class C int this[int [|p|]] { get { [|p|]++; } } } """); - } [Fact] - public async Task TestIndexerWithWriteInSetter1() - { - await TestAsync( + public Task TestIndexerWithWriteInSetter1() + => TestAsync( """ using System; class C @@ -174,12 +153,10 @@ class C int this[int [|p|]] { set => [|p|]++; } } """); - } [Fact] - public async Task TestIndexerWithWriteInSetter2() - { - await TestAsync( + public Task TestIndexerWithWriteInSetter2() + => TestAsync( """ using System; class C @@ -187,12 +164,10 @@ class C int this[int [|p|]] { set { [|p|]++; } } } """); - } [Fact] - public async Task TestPropertyWithAssignmentToValue1() - { - await TestAsync( + public Task TestPropertyWithAssignmentToValue1() + => TestAsync( """ using System; class C @@ -200,12 +175,10 @@ class C int Goo { set => [|value|] = [|value|] + 1; } } """); - } [Fact] - public async Task TestPropertyWithAssignmentToValue2() - { - await TestAsync( + public Task TestPropertyWithAssignmentToValue2() + => TestAsync( """ using System; class C @@ -213,12 +186,10 @@ class C int Goo { set { [|value|] = [|value|] + 1; } } } """); - } [Fact] - public async Task TestEventAddWithAssignmentToValue() - { - await TestAsync( + public Task TestEventAddWithAssignmentToValue() + => TestAsync( """ using System; class C @@ -226,12 +197,10 @@ class C event Action Goo { add { [|value|] = null; } remove { } } } """); - } [Fact] - public async Task TestEventRemoveWithAssignmentToValue() - { - await TestAsync( + public Task TestEventRemoveWithAssignmentToValue() + => TestAsync( """ using System; class C @@ -239,12 +208,10 @@ class C event Action Goo { add { } remove { [|value|] = null; } } } """); - } [Fact] - public async Task TestLambdaParameterWithoutReassignment() - { - await TestAsync( + public Task TestLambdaParameterWithoutReassignment() + => TestAsync( """ using System; class C @@ -255,12 +222,10 @@ void M() } } """); - } [Fact] - public async Task TestLambdaParameterWithReassignment() - { - await TestAsync( + public Task TestLambdaParameterWithReassignment() + => TestAsync( """ using System; class C @@ -271,12 +236,10 @@ void M() } } """); - } [Fact] - public async Task TestLambdaParameterWithReassignment2() - { - await TestAsync( + public Task TestLambdaParameterWithReassignment2() + => TestAsync( """ using System; class C @@ -287,12 +250,10 @@ void M() } } """); - } [Fact] - public async Task TestLocalWithoutInitializerWithoutReassignment() - { - await TestAsync( + public Task TestLocalWithoutInitializerWithoutReassignment() + => TestAsync( """ using System; class C @@ -309,12 +270,10 @@ void M(bool b) } } """); - } [Fact] - public async Task TestLocalWithoutInitializerWithReassignment() - { - await TestAsync( + public Task TestLocalWithoutInitializerWithReassignment() + => TestAsync( """ using System; class C @@ -332,12 +291,10 @@ void M(bool b) } } """); - } [Fact] - public async Task TestLocalDeclaredByPattern() - { - await TestAsync( + public Task TestLocalDeclaredByPattern() + => TestAsync( """ using System; class C @@ -349,12 +306,10 @@ void M() } } """); - } [Fact] - public async Task TestLocalDeclaredByPatternButAssignedInFalseBranch() - { - await TestAsync( + public Task TestLocalDeclaredByPatternButAssignedInFalseBranch() + => TestAsync( """ using System; class C @@ -373,12 +328,10 @@ void M() } } """); - } [Fact] - public async Task TestLocalDeclaredByPositionalPattern() - { - await TestAsync( + public Task TestLocalDeclaredByPositionalPattern() + => TestAsync( """ using System; class C @@ -390,12 +343,10 @@ void M() } } """); - } [Fact] - public async Task TestLocalDeclaredByOutVar() - { - await TestAsync( + public Task TestLocalDeclaredByOutVar() + => TestAsync( """ using System; class C @@ -410,12 +361,10 @@ void M() void M2(out int p) => p = 0; } """); - } [Fact] - public async Task TestOutParameterCausingReassignment() - { - await TestAsync( + public Task TestOutParameterCausingReassignment() + => TestAsync( """ using System; class C @@ -430,12 +379,10 @@ void M() void M2(out int p) => p = 0; } """); - } [Fact] - public async Task TestOutParameterWithoutReassignment() - { - await TestAsync( + public Task TestOutParameterWithoutReassignment() + => TestAsync( """ using System; class C @@ -450,12 +397,10 @@ void M() void M2(out int p) => p = 0; } """); - } [Fact] - public async Task AssignmentThroughOutParameter() - { - await TestAsync( + public Task AssignmentThroughOutParameter() + => TestAsync( """ using System; class C @@ -468,12 +413,10 @@ void M(out int [|p|]) } } """); - } [Fact] - public async Task TestOutParameterReassignmentOneWrites() - { - await TestAsync( + public Task TestOutParameterReassignmentOneWrites() + => TestAsync( """ using System; class C @@ -485,12 +428,10 @@ void M(out int p) } } """); - } [Fact] - public async Task AssignmentThroughRefParameter() - { - await TestAsync( + public Task AssignmentThroughRefParameter() + => TestAsync( """ using System; class C @@ -503,12 +444,10 @@ void M(ref int [|p|]) } } """); - } [Fact] - public async Task TestRefParameterReassignment() - { - await TestAsync( + public Task TestRefParameterReassignment() + => TestAsync( """ using System; class C @@ -520,12 +459,10 @@ void M(ref int [|p|]) } } """); - } [Fact] - public async Task AssignmentThroughRefLocal() - { - await TestAsync( + public Task AssignmentThroughRefLocal() + => TestAsync( """ using System; class C @@ -539,12 +476,10 @@ void M(ref int [|p|]) } } """); - } [Fact] - public async Task AssignmentThroughScopedRefLocal() - { - await TestAsync( + public Task AssignmentThroughScopedRefLocal() + => TestAsync( """ using System; class C @@ -558,12 +493,10 @@ void M(ref int [|p|]) } } """); - } [Fact] - public async Task TestRefLocalReassignment() - { - await TestAsync( + public Task TestRefLocalReassignment() + => TestAsync( """ using System; class C @@ -578,12 +511,10 @@ void M(ref int [|p|]) } } """); - } [Fact] - public async Task AssignmentThroughPointerIsNotAssignmentOfTheVariableItself() - { - await TestAsync( + public Task AssignmentThroughPointerIsNotAssignmentOfTheVariableItself() + => TestAsync( """ using System; class C @@ -595,12 +526,10 @@ unsafe void M(int* p) } } """); - } [Fact] - public async Task TestPointerVariableReassignment() - { - await TestAsync( + public Task TestPointerVariableReassignment() + => TestAsync( """ using System; class C @@ -612,12 +541,10 @@ unsafe void M(int* [|p|]) } } """); - } [Fact] - public async Task TestRefParameterCausingPossibleReassignment() - { - await TestAsync( + public Task TestRefParameterCausingPossibleReassignment() + => TestAsync( """ using System; class C @@ -632,12 +559,10 @@ void M() void M2(ref int p) { } } """); - } [Fact] - public async Task TestVolatileRefReadParameterCausingPossibleReassignment() - { - await TestAsync( + public Task TestVolatileRefReadParameterCausingPossibleReassignment() + => TestAsync( """ using System; using System.Threading; @@ -653,12 +578,10 @@ void M() } } """); - } [Fact] - public async Task TestRefParameterWithoutReassignment() - { - await TestAsync( + public Task TestRefParameterWithoutReassignment() + => TestAsync( """ using System; class C @@ -673,12 +596,10 @@ void M() void M2(ref int p) { } } """); - } [Fact] - public async Task TestRefLocalCausingPossibleReassignment() - { - await TestAsync( + public Task TestRefLocalCausingPossibleReassignment() + => TestAsync( """ using System; class C @@ -691,12 +612,10 @@ void M() } } """); - } [Fact] - public async Task TestReadonlyRefLocalWithNoReassignment() - { - await TestAsync( + public Task TestReadonlyRefLocalWithNoReassignment() + => TestAsync( """ using System; class C @@ -709,12 +628,10 @@ void M() } } """); - } [Fact] - public async Task TestScopedReadonlyRefLocalWithNoReassignment() - { - await TestAsync( + public Task TestScopedReadonlyRefLocalWithNoReassignment() + => TestAsync( """ using System; class C @@ -727,12 +644,10 @@ void M() } } """); - } [Fact] - public async Task TestReadonlyRefLocalWithNoReassignment1() - { - await TestAsync( + public Task TestReadonlyRefLocalWithNoReassignment1() + => TestAsync( """ using System; class C @@ -745,12 +660,10 @@ void M() } } """); - } [Fact] - public async Task TestScopedReadonlyRefLocalWithNoReassignment1() - { - await TestAsync( + public Task TestScopedReadonlyRefLocalWithNoReassignment1() + => TestAsync( """ using System; class C @@ -763,12 +676,10 @@ void M1() } } """); - } [Fact] - public async Task TestPointerCausingPossibleReassignment() - { - await TestAsync( + public Task TestPointerCausingPossibleReassignment() + => TestAsync( """ using System; class C @@ -781,12 +692,10 @@ unsafe void M() } } """); - } [Fact] - public async Task TestRefExtensionMethodCausingPossibleReassignment() - { - await TestAsync( + public Task TestRefExtensionMethodCausingPossibleReassignment() + => TestAsync( """ using System; static class C @@ -801,12 +710,10 @@ void M() static void M2(this ref int p) { } } """); - } [Fact] - public async Task TestMutatingStructMethod() - { - await TestAsync( + public Task TestMutatingStructMethod() + => TestAsync( """ using System; struct S @@ -822,12 +729,10 @@ void M(S p) void MutatingMethod() => this = default; } """); - } [Fact] - public async Task TestReassignmentWhenDeclaredWithDeconstruction() - { - await TestAsync( + public Task TestReassignmentWhenDeclaredWithDeconstruction() + => TestAsync( """ using System; class C @@ -842,12 +747,10 @@ void M() (int x, int y) Goo() => default; } """); - } [Fact] - public async Task TestReassignmentThroughDeconstruction() - { - await TestAsync( + public Task TestReassignmentThroughDeconstruction() + => TestAsync( """ using System; class C @@ -862,55 +765,45 @@ void M() (int x, int y) Goo() => default; } """); - } [Fact] - public async Task TestTopLevelNotReassigned() - { - await TestAsync( + public Task TestTopLevelNotReassigned() + => TestAsync( """ int p; p = 0; Console.WriteLine(p); """); - } [Fact] - public async Task TestTopLevelReassigned() - { - await TestAsync( + public Task TestTopLevelReassigned() + => TestAsync( """ int [|p|] = 1; [|p|] = 0; Console.WriteLine([|p|]); """); - } [Fact] - public async Task TestTopLevelArgsParameterNotReassigned() - { - await TestAsync( + public Task TestTopLevelArgsParameterNotReassigned() + => TestAsync( """ Console.WriteLine(args); """); - } [Fact] - public async Task TestTopLevelArgsParameterReassigned() - { - await TestAsync( + public Task TestTopLevelArgsParameterReassigned() + => TestAsync( """ [|args|] = null Console.WriteLine([|args|]); """); - } [Fact] - public async Task TestUsedInThisBase1() - { - await TestAsync( + public Task TestUsedInThisBase1() + => TestAsync( """ class C { @@ -924,12 +817,10 @@ public C(int x, bool b) } } """); - } [Fact] - public async Task TestUsedInThisBase2() - { - await TestAsync( + public Task TestUsedInThisBase2() + => TestAsync( """ class C { @@ -943,12 +834,10 @@ public C(int x, bool b) } } """); - } [Fact] - public async Task TestRecord1() - { - await TestAsync( + public Task TestRecord1() + => TestAsync( """ record X(int [|x|]) : Y([|x|]++) { @@ -958,36 +847,30 @@ record Y(int x) { } """); - } [Fact] - public async Task TestRecord2() - { - await TestAsync( + public Task TestRecord2() + => TestAsync( """ record X(int [|x|]) { int Y = [|x|]++; } """); - } [Fact] - public async Task TestRecord3() - { - await TestAsync( + public Task TestRecord3() + => TestAsync( """ record struct X(int [|x|]) { int Y = [|x|]++; } """); - } [Fact] - public async Task TestClass1() - { - await TestAsync( + public Task TestClass1() + => TestAsync( """ class X(int [|x|]) : Y([|x|]++) { @@ -997,62 +880,50 @@ class Y(int x) { } """); - } [Fact] - public async Task TestClass2() - { - await TestAsync( + public Task TestClass2() + => TestAsync( """ class X(int [|x|]) { int Y = [|x|]++; } """); - } [Fact] - public async Task TestClass3() - { - await TestAsync( + public Task TestClass3() + => TestAsync( """ class X(int [|x|]) { int Y() => [|x|]++; } """); - } [Fact] - public async Task TestStruct2() - { - await TestAsync( + public Task TestStruct2() + => TestAsync( """ struct X(int [|x|]) { int Y = [|x|]++; } """); - } [Fact] - public async Task TestStruct3() - { - await TestAsync( + public Task TestStruct3() + => TestAsync( """ struct X(int [|x|]) { int Y() => [|x|]++; } """); - } [Fact] - public async Task TestExceptionVariableReassignment() - { - // Note: this is a bug. But the test currently tracks the current behavior. Fixing this - // is just not deemed worth it currently. - await TestAsync( + public Task TestExceptionVariableReassignment() + => TestAsync( """ using System; class C @@ -1067,14 +938,10 @@ void M() } } """); - } [Fact] - public async Task TestLocalReassignedInExceptionFilter() - { - // Note: this is a bug. But the test currently tracks the current behavior. Fixing this - // is just not deemed worth it currently. - await TestAsync( + public Task TestLocalReassignedInExceptionFilter() + => TestAsync( """ using System; class C @@ -1086,12 +953,10 @@ void M() } } """); - } [Fact] - public async Task TestLocalReassignedInCaseGuard() - { - await TestAsync( + public Task TestLocalReassignedInCaseGuard() + => TestAsync( """ using System; class C @@ -1105,12 +970,10 @@ void M() } } """); - } [Fact] - public async Task TestLocalWithMultipleDeclarators() - { - await TestAsync( + public Task TestLocalWithMultipleDeclarators() + => TestAsync( """ using System; class C @@ -1123,12 +986,10 @@ void M() } } """); - } [Fact] - public async Task TestForLoop() - { - await TestAsync( + public Task TestForLoop() + => TestAsync( """ using System; class C @@ -1140,12 +1001,10 @@ void M() } } """); - } [Fact] - public async Task TestForeach() - { - await TestAsync( + public Task TestForeach() + => TestAsync( """ using System; class C @@ -1157,12 +1016,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestWriteThroughOneBranch() - { - await TestAsync( + public Task TestWriteThroughOneBranch() + => TestAsync( """ using System; class C @@ -1178,12 +1035,10 @@ void M() } } """); - } [Fact] - public async Task TestDuplicateMethod() - { - await TestAsync( + public Task TestDuplicateMethod() + => TestAsync( """ class C { @@ -1198,12 +1053,10 @@ void M(int [|p|]) } } """); - } [Fact] - public async Task TestDuplicateParameter() - { - await TestAsync( + public Task TestDuplicateParameter() + => TestAsync( """ class C { @@ -1213,12 +1066,10 @@ void M(int p, int p) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58161")] - public async Task TestRefToSuppression1() - { - await TestAsync( + public Task TestRefToSuppression1() + => TestAsync( """ #nullable enable @@ -1231,12 +1082,10 @@ public static T EnsureInitialized([NotNull] ref T? [|target|]) where T : clas => Volatile.Read(ref [|target|]!); } """); - } [Fact] - public async Task TestPrimaryConstructor1() - { - await TestAsync( + public Task TestPrimaryConstructor1() + => TestAsync( """ class C(int [|p|]) { @@ -1246,12 +1095,10 @@ void M() } } """); - } [Fact] - public async Task TestPrimaryConstructor2() - { - await TestAsync( + public Task TestPrimaryConstructor2() + => TestAsync( """ class C(int p) { @@ -1261,12 +1108,10 @@ void M() } } """); - } [Fact] - public async Task TestPrimaryConstructor3() - { - await TestAsync( + public Task TestPrimaryConstructor3() + => TestAsync( """ partial class C(int [|p|]) { @@ -1280,12 +1125,10 @@ void M() } } """); - } [Fact] - public async Task TestPrimaryConstructor4() - { - await TestAsync( + public Task TestPrimaryConstructor4() + => TestAsync( """ class B(int p) { @@ -1295,12 +1138,10 @@ partial class C(int [|p|]) : B([|p|] = 1) { } """); - } [Fact] - public async Task TestPrimaryConstructor5() - { - await TestAsync( + public Task TestPrimaryConstructor5() + => TestAsync( """ @@ -1321,5 +1162,4 @@ void M() """); - } } diff --git a/src/EditorFeatures/CSharpTest/RefactoringHelpers/RefactoringHelpersTests.cs b/src/EditorFeatures/CSharpTest/RefactoringHelpers/RefactoringHelpersTests.cs index 786fc6e2ade5e..bef11e0e05393 100644 --- a/src/EditorFeatures/CSharpTest/RefactoringHelpers/RefactoringHelpersTests.cs +++ b/src/EditorFeatures/CSharpTest/RefactoringHelpers/RefactoringHelpersTests.cs @@ -15,9 +15,8 @@ public sealed partial class RefactoringHelpersTests : RefactoringHelpersTestBase { #region Locations [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestInTokenDirectlyUnderNode() - { - var testText = """ + public Task TestInTokenDirectlyUnderNode() + => TestAsync(""" class C { void M() @@ -28,14 +27,11 @@ void M() }|} } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestBeforeTokenDirectlyUnderNode() - { - var testText = """ + public Task TestBeforeTokenDirectlyUnderNode() + => TestAsync(""" class C { void M() @@ -46,14 +42,11 @@ void M() }|} } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestAfterTokenDirectlyUnderNode() - { - var testText = """ + public Task TestAfterTokenDirectlyUnderNode() + => TestAsync(""" class C { void M() @@ -64,14 +57,11 @@ void M() }|} } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingInTokenUnderDifferentNode() - { - var testText = """ + public Task TestMissingInTokenUnderDifferentNode() + => TestMissingAsync(""" class C { void M() @@ -83,14 +73,11 @@ C LocalFunction(C c) } } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestClimbRightEdge() - { - var testText = """ + public Task TestClimbRightEdge() + => TestAsync(""" class C { void M() @@ -101,14 +88,11 @@ void M() }[||]|} } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestClimbLeftEdge() - { - var testText = """ + public Task TestClimbLeftEdge() + => TestAsync(""" class C { void M() @@ -119,14 +103,11 @@ void M() }|} } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestClimbLeftEdgeComments() - { - var testText = """ + public Task TestClimbLeftEdgeComments() + => TestAsync(""" class C { void M() @@ -140,14 +121,11 @@ void M() }|} } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingInAnotherChildNode() - { - var testText = """ + public Task TestMissingInAnotherChildNode() + => TestMissingAsync(""" class C { void M() @@ -158,14 +136,11 @@ C LocalFunction(C c) } } } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingInTooFarBeforeInWhitespace() - { - var testText = """ + public Task TestMissingInTooFarBeforeInWhitespace() + => TestMissingAsync(""" class C { void M() @@ -179,14 +154,11 @@ C LocalFunction(C c) } } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingInWhiteSpaceOnLineWithDifferentStatement() - { - var testText = """ + public Task TestMissingInWhiteSpaceOnLineWithDifferentStatement() + => TestMissingAsync(""" class C { void M() @@ -200,14 +172,11 @@ C LocalFunction(C c) } } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestNotBeforePrecedingComment() - { - var testText = """ + public Task TestNotBeforePrecedingComment() + => TestMissingAsync(""" class C { void M() @@ -219,14 +188,11 @@ C LocalFunction(C c) } } } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestBeforeInWhitespace1_OnSameLine() - { - var testText = """ + public Task TestBeforeInWhitespace1_OnSameLine() + => TestAsync(""" class C { void M() @@ -237,14 +203,11 @@ void M() }|} } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestBeforeInWhitespace1_OnPreviousLine() - { - var testText = """ + public Task TestBeforeInWhitespace1_OnPreviousLine() + => TestAsync(""" class C { void M() @@ -256,14 +219,11 @@ void M() }|} } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestBeforeInWhitespace1_NotOnMultipleLinesPrior() - { - var testText = """ + public Task TestBeforeInWhitespace1_NotOnMultipleLinesPrior() + => TestMissingAsync(""" class C { void M() @@ -276,14 +236,11 @@ C LocalFunction(C c) } } } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestBeforeInWhitespace2() - { - var testText = """ + public Task TestBeforeInWhitespace2() + => TestAsync(""" class C { void M() @@ -295,14 +252,11 @@ void M() }|} } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingInNextTokensLeadingTrivia() - { - var testText = """ + public Task TestMissingInNextTokensLeadingTrivia() + => TestMissingAsync(""" class C { void M() @@ -315,14 +269,11 @@ C LocalFunction(C c) [||] } } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestInEmptySyntaxNode_AllowEmptyNodesTrue1() - { - var testText = """ + public Task TestInEmptySyntaxNode_AllowEmptyNodesTrue1() + => TestAsync(""" class C { void M() @@ -334,14 +285,11 @@ int N(int a, int b, int c) { } } - """; - await TestAsync(testText, allowEmptyNodes: true); - } + """, allowEmptyNodes: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestInEmptySyntaxNode_AllowEmptyNodesTrue2() - { - var testText = """ + public Task TestInEmptySyntaxNode_AllowEmptyNodesTrue2() + => TestAsync(""" class C { void M() @@ -353,14 +301,11 @@ int N(int a, int b, int c) { } } - """; - await TestAsync(testText, allowEmptyNodes: true); - } + """, allowEmptyNodes: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestInEmptySyntaxNode_AllowEmptyNodesFalse1() - { - var testText = """ + public Task TestInEmptySyntaxNode_AllowEmptyNodesFalse1() + => TestMissingAsync(""" class C { void M() @@ -372,14 +317,11 @@ int N(int a, int b, int c) { } } - """; - await TestMissingAsync(testText, allowEmptyNodes: false); - } + """, allowEmptyNodes: false); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestInEmptySyntaxNode_AllowEmptyNodesFalse2() - { - var testText = """ + public Task TestInEmptySyntaxNode_AllowEmptyNodesFalse2() + => TestAsync(""" class C { void M() @@ -391,17 +333,14 @@ int N(int a, int b, int c) { } } - """; - await TestAsync(testText, allowEmptyNodes: false); - } + """, allowEmptyNodes: false); #endregion #region Selections [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestSelectedTokenDirectlyUnderNode() - { - var testText = """ + public Task TestSelectedTokenDirectlyUnderNode() + => TestAsync(""" class C { void M() @@ -412,14 +351,11 @@ void M() }|} } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestPartiallySelectedTokenDirectlyUnderNode() - { - var testText = """ + public Task TestPartiallySelectedTokenDirectlyUnderNode() + => TestAsync(""" class C { void M() @@ -430,14 +366,11 @@ void M() }|} } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestSelectedMultipleTokensUnderNode() - { - var testText = """ + public Task TestSelectedMultipleTokensUnderNode() + => TestAsync(""" class C { void M() @@ -448,14 +381,11 @@ void M() }|} } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingSelectedMultipleTokensWithLowerCommonAncestor() - { - var testText = """ + public Task TestMissingSelectedMultipleTokensWithLowerCommonAncestor() + => TestMissingAsync(""" class C { void M() @@ -466,14 +396,11 @@ C LocalFunction(C c) }|] } } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingSelectedLowerNode() - { - var testText = """ + public Task TestMissingSelectedLowerNode() + => TestMissingAsync(""" class C { void M() @@ -484,14 +411,11 @@ void M() } } } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingSelectedWhitespace() - { - var testText = """ + public Task TestMissingSelectedWhitespace() + => TestMissingAsync(""" class C { void M() @@ -502,14 +426,11 @@ void M() } } } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingSelectedWhitespace2() - { - var testText = """ + public Task TestMissingSelectedWhitespace2() + => TestMissingAsync(""" class C { void M() @@ -520,14 +441,11 @@ void M() } } } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestCompleteSelection() - { - var testText = """ + public Task TestCompleteSelection() + => TestAsync(""" class C { void M() @@ -538,14 +456,11 @@ void M() }|]|} } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestOverSelection() - { - var testText = """ + public Task TestOverSelection() + => TestAsync(""" class C { void M() @@ -560,14 +475,11 @@ void M() |]var a = new object(); } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestOverSelectionComments() - { - var testText = """ + public Task TestOverSelectionComments() + => TestAsync(""" class C { void M() @@ -580,14 +492,11 @@ void M() }|}|] } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingOverSelection() - { - var testText = """ + public Task TestMissingOverSelection() + => TestMissingAsync(""" class C { void M() @@ -600,14 +509,11 @@ C LocalFunction(C c) v|]ar a = new object(); } } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingSelectionBefore() - { - var testText = """ + public Task TestMissingSelectionBefore() + => TestMissingAsync(""" class C { void M() @@ -620,17 +526,14 @@ void M() var a = new object(); } } - """; - await TestMissingAsync(testText); - } + """); #endregion #region IsUnderselected [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38708")] - public async Task TestUnderselectionOnSemicolon() - { - var testText = """ + public Task TestUnderselectionOnSemicolon() + => TestNotUnderselectedAsync(""" class Program { static void Main() @@ -638,14 +541,11 @@ static void Main() {|result:Main()|}[|;|] } } - """; - await TestNotUnderselectedAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38708")] - public async Task TestUnderselectionBug1() - { - var testText = """ + public Task TestUnderselectionBug1() + => TestNotUnderselectedAsync(""" class Program { public static void Method() @@ -654,14 +554,11 @@ public static void Method() var str = {|result:" <|] aaa"|}; } } - """; - await TestNotUnderselectedAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38708")] - public async Task TestUnderselectionBug2() - { - var testText = """ + public Task TestUnderselectionBug2() + => TestNotUnderselectedAsync(""" class C { public void M() { @@ -669,81 +566,63 @@ public void M() {|result:Console.WriteLine(new |]C())|}; } } - """; - await TestNotUnderselectedAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38708")] - public async Task TestUnderselection() - { - var testText = """ + public Task TestUnderselection() + => TestNotUnderselectedAsync(""" class C { public void M() { bool a = {|result:[|true || false || true|]|}; } - """; - await TestNotUnderselectedAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38708")] - public async Task TestUnderselection2() - { - var testText = """ + public Task TestUnderselection2() + => TestUnderselectedAsync(""" class C { public void M() { bool a = true || [|false || true|] || true; } - """; - await TestUnderselectedAsync(testText); - } + """); #endregion #region Attributes [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37584")] - public async Task TestMissingEmptyMember() - { - var testText = """ + public Task TestMissingEmptyMember() + => TestMissingAsync(""" using System; public class Class1 { [][||] } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38502")] - public async Task TestIncompleteAttribute() - { - var testText = """ + public Task TestIncompleteAttribute() + => TestAsync(""" using System; public class Class1 { {|result:void foo([[||]bar) {}|} } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38502")] - public async Task TestIncompleteAttribute2() - { - var testText = """ + public Task TestIncompleteAttribute2() + => TestAsync(""" using System; public class Class1 { {|result:void foo([[||]Class1 arg1) {}|} } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37837")] - public async Task TestEmptyParameter() - { - var testText = """ + public Task TestEmptyParameter() + => TestAsync(""" using System; public class TestAttribute : Attribute { } public class Class1 @@ -753,42 +632,33 @@ static void foo({|result:[Test][||] } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37584")] - public async Task TestMissingEmptyMember2() - { - var testText = """ + public Task TestMissingEmptyMember2() + => TestMissingAsync(""" using System; public class Class1 { [||]// Comment [] } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37584")] - public async Task TestEmptyAttributeList() - { - var testText = """ + public Task TestEmptyAttributeList() + => TestAsync(""" using System; public class Class1 { {|result:[] [||]void a() {}|} } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestClimbLeftEdgeBeforeAttribute() - { - var testText = """ + public Task TestClimbLeftEdgeBeforeAttribute() + => TestAsync(""" using System; class C { @@ -800,14 +670,11 @@ void M() { }|} } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestClimbLeftEdgeAfterAttribute() - { - var testText = """ + public Task TestClimbLeftEdgeAfterAttribute() + => TestAsync(""" using System; class C { @@ -818,14 +685,11 @@ class TestAttribute : Attribute { } { }|} } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestClimbLeftEdgeAfterAttributeComments() - { - var testText = """ + public Task TestClimbLeftEdgeAfterAttributeComments() + => TestAsync(""" using System; class C { @@ -838,14 +702,11 @@ class TestAttribute : Attribute { } { }|} } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestClimbLeftEdgeAfterAttributes() - { - var testText = """ + public Task TestClimbLeftEdgeAfterAttributes() + => TestAsync(""" using System; class C { @@ -860,14 +721,11 @@ class Test2Attribute : Attribute { } { }|} } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingBetweenAttributes() - { - var testText = """ + public Task TestMissingBetweenAttributes() + => TestMissingAsync(""" using System; class C { @@ -880,14 +738,11 @@ void M() { } } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingBetweenInAttributes() - { - var testText = """ + public Task TestMissingBetweenInAttributes() + => TestMissingAsync(""" using System; class C { @@ -898,14 +753,11 @@ void M() { } } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingSelectedAttributes() - { - var testText = """ + public Task TestMissingSelectedAttributes() + => TestMissingAsync(""" using System; class C { @@ -918,14 +770,11 @@ void M() { } } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingSelectedAttribute() - { - var testText = """ + public Task TestMissingSelectedAttribute() + => TestMissingAsync(""" using System; class C { @@ -936,14 +785,11 @@ void M() { } } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestSelectedWholeNodeAndAttributes() - { - var testText = """ + public Task TestSelectedWholeNodeAndAttributes() + => TestAsync(""" using System; class C { @@ -958,14 +804,11 @@ void M() { }|}|] } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestSelectedWholeNodeWithoutAttributes() - { - var testText = """ + public Task TestSelectedWholeNodeWithoutAttributes() + => TestAsync(""" using System; class C { @@ -980,16 +823,13 @@ class Test2Attribute : Attribute { } { }|]|} } - """; - await TestAsync(testText); - } + """); #endregion #region Extractions general [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestExtractionsClimbing() - { - var testText = """ + public Task TestExtractionsClimbing() + => TestAsync(""" using System; class C { @@ -998,32 +838,24 @@ void M() var a = {|result:new object()|};[||] } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingExtractHeaderForSelection() - { - var testText = """ + public Task TestMissingExtractHeaderForSelection() + => TestMissingAsync(""" using System; class C { class TestAttribute : Attribute { } [Test] public [|int|] a { get; set; } } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMultipleExtractions() { - var localDeclaration = "{|result:string name = \"\", b[||]b = null;|}"; - var localDeclarator = "string name = \"\", {|result:bb[||] = null|};"; - - await TestAsync(GetTestText(localDeclaration)); - await TestAsync(GetTestText(localDeclarator)); + await TestAsync(GetTestText("{|result:string name = \"\", b[||]b = null;|}")); + await TestAsync(GetTestText("string name = \"\", {|result:bb[||] = null|};")); static string GetTestText(string data) { @@ -1048,9 +880,8 @@ C LocalFunction(C c) #region Extractions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestExtractFromDeclaration() - { - var testText = """ + public Task TestExtractFromDeclaration() + => TestAsync(""" using System; class C { @@ -1059,14 +890,11 @@ void M() [|var a = {|result:new object()|};|] } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestExtractFromDeclaration2() - { - var testText = """ + public Task TestExtractFromDeclaration2() + => TestAsync(""" using System; class C { @@ -1075,14 +903,11 @@ void M() var a = [|{|result:new object()|};|] } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestExtractFromAssignment() - { - var testText = """ + public Task TestExtractFromAssignment() + => TestAsync(""" using System; class C { @@ -1092,14 +917,11 @@ void M() a = [|{|result:new object()|};|] } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestExtractFromDeclarator() - { - var testText = """ + public Task TestExtractFromDeclarator() + => TestAsync(""" using System; class C { @@ -1108,14 +930,11 @@ void M() var [|a = {|result:new object()|}|]; } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestExtractFromDeclarator2() - { - var testText = """ + public Task TestExtractFromDeclarator2() + => TestAsync(""" using System; class C { @@ -1124,37 +943,29 @@ void M() {|result:var [|a = new object()|];|} } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestExtractInHeaderOfProperty() - { - var testText = """ + public Task TestExtractInHeaderOfProperty() + => TestAsync(""" using System; class C { class TestAttribute : Attribute { } {|result:[Test] public i[||]nt a { get; set; }|} } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingExtractNotInHeaderOfProperty() - { - var testText = """ + public Task TestMissingExtractNotInHeaderOfProperty() + => TestMissingAsync(""" using System; class C { class TestAttribute : Attribute { } [Test] public int a { [||]get; set; } } - """; - await TestMissingAsync(testText); - } + """); #endregion @@ -1214,9 +1025,8 @@ C LocalFunction(C c) #region TestHidden [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestNextToHidden() - { - var testText = """ + public Task TestNextToHidden() + => TestAsync(""" #line default class C { @@ -1231,14 +1041,11 @@ void M() }|} } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestNextToHidden2() - { - var testText = """ + public Task TestNextToHidden2() + => TestAsync(""" #line default class C { @@ -1256,14 +1063,11 @@ void M() #line default } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingHidden() - { - var testText = """ + public Task TestMissingHidden() + => TestMissingAsync(""" #line default class C { @@ -1277,16 +1081,13 @@ C LocalFunction(C c) }[||] } } - """; - await TestMissingAsync(testText); - } + """); #endregion #region Test predicate [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingPredicate() - { - var testText = """ + public Task TestMissingPredicate() + => TestMissingAsync(""" class C { void M() @@ -1298,14 +1099,11 @@ void N(int a) { } } - """; - await TestMissingAsync(testText, n => n.Parent is TupleExpressionSyntax); - } + """, n => n.Parent is TupleExpressionSyntax); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestArgument() - { - var testText = """ + public Task TestArgument() + => TestAsync(""" class C { void M() @@ -1317,14 +1115,11 @@ void N(int a) { } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestPredicate() - { - var testText = """ + public Task TestPredicate() + => TestAsync(""" class C { void M() @@ -1332,252 +1127,199 @@ void M() var a = ({|result:[||]2 + 3|}, 2 + 3); } } - """; - await TestAsync(testText, n => n.Parent is TupleExpressionSyntax); - } + """, n => n.Parent is TupleExpressionSyntax); #endregion #region Test arguments [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestArgumentsExtractionsInInitializer() - { - var testText = """ + public Task TestArgumentsExtractionsInInitializer() + => TestAsync(""" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test]int a = [||]42|}, int b = 41) {} } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingArgumentsExtractionsSelectInitializer() - { - var testText = """ + public Task TestMissingArgumentsExtractionsSelectInitializer() + => TestMissingAsync(""" using System; class C { class TestAttribute : Attribute { } public C([Test]int a = [|42|], int b = 41) {} } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingArgumentsExtractionsSelectComma() - { - var testText = """ + public Task TestMissingArgumentsExtractionsSelectComma() + => TestMissingAsync(""" using System; class C { class TestAttribute : Attribute { } public C([Test]int a = 42[|,|] int b = 41) {} } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingArgumentsExtractionsInAttributes() - { - var testText = """ + public Task TestMissingArgumentsExtractionsInAttributes() + => TestMissingAsync(""" using System; class C { class TestAttribute : Attribute { } public C([[||]Test]int a = 42, int b = 41) {} } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingArgumentsExtractionsSelectType1() - { - var testText = """ + public Task TestMissingArgumentsExtractionsSelectType1() + => TestMissingAsync(""" using System; class C { class TestAttribute : Attribute { } public C([Test][|int|] a = 42, int b = 41) {} } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingArgumentsExtractionsSelectType2() - { - var testText = """ + public Task TestMissingArgumentsExtractionsSelectType2() + => TestMissingAsync(""" using System; class C { class TestAttribute : Attribute { } public C([Test][|C|] a = null, int b = 41) {} } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestArgumentsExtractionsAtTheEnd() - { - var testText = """ + public Task TestArgumentsExtractionsAtTheEnd() + => TestAsync(""" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test]int a = 42[||]|}, int b = 41) {} } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestArgumentsExtractionsBefore() - { - var testText = """ + public Task TestArgumentsExtractionsBefore() + => TestAsync(""" using System; class C { class TestAttribute : Attribute { } public C([||]{|result:[Test]int a = 42|}, int b = 41) {} } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestArgumentsExtractionsSelectParamName() - { - var testText = """ + public Task TestArgumentsExtractionsSelectParamName() + => TestAsync(""" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test]int [|a|] = 42|}, int b = 41) {} } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestArgumentsExtractionsSelectParam1() - { - var testText = """ + public Task TestArgumentsExtractionsSelectParam1() + => TestAsync(""" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test][|int a|] = 42|}, int b = 41) {} } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestArgumentsExtractionsSelectParam2() - { - var testText = """ + public Task TestArgumentsExtractionsSelectParam2() + => TestAsync(""" using System; class C { class TestAttribute : Attribute { } public C([|{|result:[Test]int a = 42|}|], int b = 41) {} } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestArgumentsExtractionsSelectParam3() - { - var testText = """ + public Task TestArgumentsExtractionsSelectParam3() + => TestAsync(""" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test][|int a = 42|]|}, int b = 41) {} } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestArgumentsExtractionsInHeader() - { - var testText = """ + public Task TestArgumentsExtractionsInHeader() + => TestAsync(""" using System; class CC { class TestAttribute : Attribute { } public CC({|result:[Test]C[||]C a = 42|}, int b = 41) {} } - """; - await TestAsync(testText); - } + """); #endregion #region Test methods [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingMethodExplicitInterfaceSelection() - { - var testText = """ + public Task TestMissingMethodExplicitInterfaceSelection() + => TestMissingAsync(""" using System; class C { class TestAttribute : Attribute { } public void [|I|].A([Test]int a = 42, int b = 41) {} } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMethodCaretBeforeInterfaceSelection() - { - var testText = """ + public Task TestMethodCaretBeforeInterfaceSelection() + => TestAsync(""" using System; class C { class TestAttribute : Attribute { } {|result:public void [||]I.A([Test]int a = 42, int b = 41) {}|} } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMethodNameAndExplicitInterfaceSelection() - { - var testText = """ + public Task TestMethodNameAndExplicitInterfaceSelection() + => TestAsync(""" using System; class C { class TestAttribute : Attribute { } {|result:public void [|I.A|]([Test]int a = 42, int b = 41) {}|} } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMethodInHeader() - { - var testText = """ + public Task TestMethodInHeader() + => TestAsync(""" using System; class CC { class TestAttribute : Attribute { } {|result:public C[||]C I.A([Test]int a = 42, int b = 41) { return null; }|} } - """; - await TestAsync(testText); - } + """); #endregion @@ -1645,9 +1387,8 @@ C LocalFunction(C c) #region Test Ifs [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMultiline_IfElseIfElseSelection1() - { - await TestAsync( + public Task TestMultiline_IfElseIfElseSelection1() + => TestAsync( """ class A { @@ -1668,12 +1409,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMultiline_IfElseIfElseSelection2() - { - await TestAsync( + public Task TestMultiline_IfElseIfElseSelection2() + => TestAsync( """ class A { @@ -1694,12 +1433,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingMultiline_IfElseIfElseSelection() - { - await TestMissingAsync( + public Task TestMissingMultiline_IfElseIfElseSelection() + => TestMissingAsync( """ class A { @@ -1720,12 +1457,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78749")] - public async Task TestMalformedIfBlock1() - { - await TestAsync( + public Task TestMalformedIfBlock1() + => TestAsync( """ { {|result:[||]if (devsBad) @@ -1733,12 +1468,10 @@ await TestAsync( else return;|} } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78749")] - public async Task TestMalformedIfBlock2() - { - await TestAsync( + public Task TestMalformedIfBlock2() + => TestAsync( """ { if (devsBad) @@ -1746,15 +1479,13 @@ await TestAsync( else return;|]|} } """); - } #endregion #region Test Deep in expression [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestDeepIn() - { - var testText = """ + public Task TestDeepIn() + => TestAsync(""" class C { void M() @@ -1766,14 +1497,11 @@ void N(int a) { } } - """; - await TestAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMissingDeepInSecondRow() - { - var testText = """ + public Task TestMissingDeepInSecondRow() + => TestMissingAsync(""" class C { void M() @@ -1786,14 +1514,11 @@ void N(int a) { } } - """; - await TestMissingAsync(testText); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestDeepInExpression() - { - var testText = """ + public Task TestDeepInExpression() + => TestAsync(""" class C { void M() @@ -1806,8 +1531,6 @@ int N(int a) return a; } } - """; - await TestAsync(testText, predicate: n => n.Parent is TupleExpressionSyntax); - } + """, predicate: n => n.Parent is TupleExpressionSyntax); #endregion } diff --git a/src/EditorFeatures/CSharpTest/Rename/CSharpInlineRenameServiceTests.cs b/src/EditorFeatures/CSharpTest/Rename/CSharpInlineRenameServiceTests.cs index 23b76cd2288f8..4b75641469157 100644 --- a/src/EditorFeatures/CSharpTest/Rename/CSharpInlineRenameServiceTests.cs +++ b/src/EditorFeatures/CSharpTest/Rename/CSharpInlineRenameServiceTests.cs @@ -78,16 +78,14 @@ private static async Task VerifyGetRenameContextAsync( [WorkItem("https://github.com/dotnet/roslyn/issues/74545")] public async Task VerifyContextReachEndOfFile() { - var markup = """ - public class Sampl$$eClass() - { - } - """; - var escapedPath = Path.Combine(TestWorkspace.RootDirectory, "test1.cs").Replace("\\", "\\\\"); await VerifyGetRenameContextAsync( - markup, + """ + public class Sampl$$eClass() + { + } + """, $$""" { "definition": [{"Item1":"{{escapedPath}}", "Item2":"public class SampleClass()\r\n{\r\n}"}] diff --git a/src/EditorFeatures/CSharpTest/Rename/CSharpRenamerTests.cs b/src/EditorFeatures/CSharpTest/Rename/CSharpRenamerTests.cs index 0548e52f5c1b5..2dd9c882de1d8 100644 --- a/src/EditorFeatures/CSharpTest/Rename/CSharpRenamerTests.cs +++ b/src/EditorFeatures/CSharpTest/Rename/CSharpRenamerTests.cs @@ -149,8 +149,8 @@ class C } } """, - documentPath: @"Test\Path\Document.cs", - documentName: @"Document.cs"); + documentPath: @"Test\Path\Document.cs", + documentName: @"Document.cs"); [Fact] public Task CSharp_RenameDocument_RenameNamespace() @@ -171,9 +171,9 @@ class C } } """, - documentPath: @"Test\Path\Document.cs", - documentName: @"Document.cs", - newDocumentPath: @"Test\Path\After\Test\Document.cs"); + documentPath: @"Test\Path\Document.cs", + documentName: @"Document.cs", + newDocumentPath: @"Test\Path\After\Test\Document.cs"); [Fact] public Task CSharp_RenameDocument_RenameMultipleNamespaces() @@ -208,9 +208,9 @@ class C2 } } """, - documentPath: @"Test\Path\Document.cs", - documentName: @"Document.cs", - newDocumentPath: @"Test\Path\After\Test\Document.cs"); + documentPath: @"Test\Path\Document.cs", + documentName: @"Document.cs", + newDocumentPath: @"Test\Path\After\Test\Document.cs"); [Fact] public Task CSharp_RenameDocument_RenameMultipleNamespaces2() @@ -259,9 +259,9 @@ class C3 } } """, - documentPath: @"Test\Path\Document.cs", - documentName: @"Document.cs", - newDocumentPath: @"Test\Path\After\Test\Document.cs"); + documentPath: @"Test\Path\Document.cs", + documentName: @"Document.cs", + newDocumentPath: @"Test\Path\After\Test\Document.cs"); [Fact] public Task CSharp_RenameDocument_RenameMultipleNamespaces3() @@ -310,9 +310,9 @@ class C3 } } """, - documentPath: @"Test\Path\Document.cs", - documentName: @"Document.cs", - newDocumentPath: @"Test\Path\After\Test\Document.cs"); + documentPath: @"Test\Path\Document.cs", + documentName: @"Document.cs", + newDocumentPath: @"Test\Path\After\Test\Document.cs"); [Fact] public Task CSharp_RenameDocument_RenameMultipleNamespaces_Nested() @@ -376,9 +376,9 @@ class C } } """, - documentPath: @"Test\Path\Document.cs", - documentName: @"Document.cs", - newDocumentPath: @"Test\Document.cs"); + documentPath: @"Test\Path\Document.cs", + documentName: @"Document.cs", + newDocumentPath: @"Test\Document.cs"); [Fact] public Task CSharp_RenameDocument_RenameNamespaceAndClass() @@ -399,21 +399,17 @@ class C2 } } """, - documentPath: @"Test\Path\C2.cs", - documentName: @"C.cs", - newDocumentName: @"C2", - newDocumentPath: @"Test\C2.cs"); + documentPath: @"Test\Path\C2.cs", + documentName: @"C.cs", + newDocumentName: @"C2", + newDocumentPath: @"Test\C2.cs"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46580")] public Task CSharp_RenameDocument_MappedDocumentHasNoResults() { - var documentName = "Component1.razor"; - var documentText = - """ + return TestRenameMappedFile("""

Component1

@code {} - """; - - return TestRenameMappedFile(documentText, documentName, newDocumentName: "MyComponent.razor"); + """, "Component1.razor", newDocumentName: "MyComponent.razor"); } } diff --git a/src/EditorFeatures/CSharpTest/Semantics/SpeculationAnalyzerTests.cs b/src/EditorFeatures/CSharpTest/Semantics/SpeculationAnalyzerTests.cs index 78840b6e7323e..78ea0aafe17e3 100644 --- a/src/EditorFeatures/CSharpTest/Semantics/SpeculationAnalyzerTests.cs +++ b/src/EditorFeatures/CSharpTest/Semantics/SpeculationAnalyzerTests.cs @@ -4,6 +4,7 @@ #nullable disable +using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; @@ -530,7 +531,7 @@ protected override Compilation CreateCompilation(SyntaxTree tree) CompilationName, [tree], References, - TestOptions.ReleaseDll.WithSpecificDiagnosticOptions([KeyValuePairUtil.Create("CS0219", ReportDiagnostic.Suppress)])); + TestOptions.ReleaseDll.WithSpecificDiagnosticOptions([KeyValuePair.Create("CS0219", ReportDiagnostic.Suppress)])); } protected override bool CompilationSucceeded(Compilation compilation, Stream temporaryStream) diff --git a/src/EditorFeatures/CSharpTest/SignatureHelp/AbstractCSharpSignatureHelpProviderTests.cs b/src/EditorFeatures/CSharpTest/SignatureHelp/AbstractCSharpSignatureHelpProviderTests.cs index 51cef93281d32..0fee9ebb3303b 100644 --- a/src/EditorFeatures/CSharpTest/SignatureHelp/AbstractCSharpSignatureHelpProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/SignatureHelp/AbstractCSharpSignatureHelpProviderTests.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; diff --git a/src/EditorFeatures/CSharpTest/SignatureHelp/AttributeSignatureHelpProviderTests.cs b/src/EditorFeatures/CSharpTest/SignatureHelp/AttributeSignatureHelpProviderTests.cs index d77d2365bd006..38425d1f9813a 100644 --- a/src/EditorFeatures/CSharpTest/SignatureHelp/AttributeSignatureHelpProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/SignatureHelp/AttributeSignatureHelpProviderTests.cs @@ -26,7 +26,12 @@ internal override Type GetSignatureHelpProviderType() [Fact] public async Task TestInvocationWithoutParameters() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0) + }; + + await TestAsync(""" class SomethingAttribute : System.Attribute { } @@ -35,20 +40,18 @@ class SomethingAttribute : System.Attribute class D { } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task TestInvocationWithoutParametersMethodXmlComments() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("SomethingAttribute()", "Summary For Attribute", null, currentParameterIndex: 0) + }; + + await TestAsync(""" class SomethingAttribute : System.Attribute { /// Summary For Attribute @@ -59,20 +62,19 @@ public SomethingAttribute() { } class D { } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("SomethingAttribute()", "Summary For Attribute", null, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25830")] public async Task PickCorrectOverload_PickInt() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("SomethingAttribute(int i)", currentParameterIndex: 0, isSelected: true), + new SignatureHelpTestItem("SomethingAttribute(string i)", currentParameterIndex: 0), + }; + + await TestAsync(""" class SomethingAttribute : System.Attribute { public SomethingAttribute(string i) => throw null; @@ -81,20 +83,19 @@ class SomethingAttribute : System.Attribute } [[|Something(i: 1$$|])] class D { } - """; - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("SomethingAttribute(int i)", currentParameterIndex: 0, isSelected: true), - new SignatureHelpTestItem("SomethingAttribute(string i)", currentParameterIndex: 0), - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25830")] public async Task PickCorrectOverload_PickString() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("SomethingAttribute(int i)", currentParameterIndex: 0), + new SignatureHelpTestItem("SomethingAttribute(string i)", currentParameterIndex: 0, isSelected: true), + }; + + await TestAsync(""" class SomethingAttribute : System.Attribute { public SomethingAttribute(string i) => throw null; @@ -103,20 +104,18 @@ class SomethingAttribute : System.Attribute } [[|Something(i: null$$|])] class D { } - """; - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("SomethingAttribute(int i)", currentParameterIndex: 0), - new SignatureHelpTestItem("SomethingAttribute(string i)", currentParameterIndex: 0, isSelected: true), - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task TestInvocationWithParametersOn1() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("SomethingAttribute(int someInteger, string someString)", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" class SomethingAttribute : System.Attribute { public SomethingAttribute(int someInteger, string someString) { } @@ -126,20 +125,18 @@ public SomethingAttribute(int someInteger, string someString) { } class D { } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("SomethingAttribute(int someInteger, string someString)", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task TestInvocationWithParametersXmlCommentsOn1() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("SomethingAttribute(int someInteger, string someString)", "Summary For Attribute", "Param someInteger", currentParameterIndex: 0) + }; + + await TestAsync(""" class SomethingAttribute : System.Attribute { /// @@ -154,20 +151,18 @@ public SomethingAttribute(int someInteger, string someString) { } |]class D { } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("SomethingAttribute(int someInteger, string someString)", "Summary For Attribute", "Param someInteger", currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task TestInvocationWithParametersOn2() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("SomethingAttribute(int someInteger, string someString)", string.Empty, string.Empty, currentParameterIndex: 1) + }; + + await TestAsync(""" class SomethingAttribute : System.Attribute { public SomethingAttribute(int someInteger, string someString) { } @@ -177,19 +172,18 @@ public SomethingAttribute(int someInteger, string someString) { } class D { } - """; - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("SomethingAttribute(int someInteger, string someString)", string.Empty, string.Empty, currentParameterIndex: 1) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task TestInvocationWithParametersXmlComentsOn2() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("SomethingAttribute(int someInteger, string someString)", "Summary For Attribute", "Param someString", currentParameterIndex: 1) + }; + + await TestAsync(""" class SomethingAttribute : System.Attribute { /// @@ -204,20 +198,18 @@ public SomethingAttribute(int someInteger, string someString) { } |]class D { } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("SomethingAttribute(int someInteger, string someString)", "Summary For Attribute", "Param someString", currentParameterIndex: 1) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task TestInvocationWithClosingParen() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0) + }; + + await TestAsync(""" class SomethingAttribute : System.Attribute { } @@ -225,20 +217,12 @@ class SomethingAttribute : System.Attribute class D { } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] - public async Task TestInvocationSpan1() - { - await TestAsync( + public Task TestInvocationSpan1() + => TestAsync( """ using System; @@ -250,12 +234,10 @@ void Goo() } } """); - } [Fact] - public async Task TestInvocationSpan2() - { - await TestAsync( + public Task TestInvocationSpan2() + => TestAsync( """ using System; @@ -267,12 +249,10 @@ void Goo() } } """); - } [Fact] - public async Task TestInvocationSpan3() - { - await TestAsync( + public Task TestInvocationSpan3() + => TestAsync( """ using System; @@ -286,16 +266,14 @@ void Goo() } } """); - } #endregion #region "Current Parameter Name" [Fact] - public async Task TestCurrentParameterName() - { - var markup = """ + public Task TestCurrentParameterName() + => VerifyCurrentParameterNameAsync(""" using System; class SomethingAttribute : Attribute @@ -307,10 +285,7 @@ public SomethingAttribute(int someParameter, bool somethingElse) { } class C { } - """; - - await VerifyCurrentParameterNameAsync(markup, "someParameter"); - } + """, "someParameter"); #endregion @@ -320,7 +295,12 @@ class C [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545425")] public async Task TestAttributeWithValidField() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem($"SomethingAttribute({FeaturesResources.Properties}: [goo = int])", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" class SomethingAttribute : System.Attribute { public int goo; @@ -330,20 +310,18 @@ class SomethingAttribute : System.Attribute class D { } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem($"SomethingAttribute({FeaturesResources.Properties}: [goo = int])", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false); + """, expectedOrderedItems, usePreviousCharAsTrigger: false); } [Fact] public async Task TestAttributeWithInvalidFieldReadonly() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0) + }; + + await TestAsync(""" class SomethingAttribute : System.Attribute { public readonly int goo; @@ -353,20 +331,18 @@ class SomethingAttribute : System.Attribute class D { } - """; + """, expectedOrderedItems); + } + [Fact] + public async Task TestAttributeWithInvalidFieldStatic() + { var expectedOrderedItems = new List { new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0) }; - await TestAsync(markup, expectedOrderedItems); - } - - [Fact] - public async Task TestAttributeWithInvalidFieldStatic() - { - var markup = """ + await TestAsync(""" class SomethingAttribute : System.Attribute { public static int goo; @@ -376,20 +352,18 @@ class SomethingAttribute : System.Attribute class D { } - """; + """, expectedOrderedItems); + } + [Fact] + public async Task TestAttributeWithInvalidFieldConst() + { var expectedOrderedItems = new List { new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0) }; - await TestAsync(markup, expectedOrderedItems); - } - - [Fact] - public async Task TestAttributeWithInvalidFieldConst() - { - var markup = """ + await TestAsync(""" class SomethingAttribute : System.Attribute { public const int goo = 42; @@ -399,14 +373,7 @@ class SomethingAttribute : System.Attribute class D { } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } #endregion @@ -417,7 +384,13 @@ class D [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545425")] public async Task TestAttributeWithValidProperty() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem($"SomethingAttribute({FeaturesResources.Properties}: [goo = int])", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + // TODO: Bug 12319: Enable tests for script when this is fixed. + await TestAsync(""" class SomethingAttribute : System.Attribute { public int goo { get; set; } @@ -427,21 +400,18 @@ class SomethingAttribute : System.Attribute class D { } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem($"SomethingAttribute({FeaturesResources.Properties}: [goo = int])", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - // TODO: Bug 12319: Enable tests for script when this is fixed. - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false); + """, expectedOrderedItems, usePreviousCharAsTrigger: false); } [Fact] public async Task TestAttributeWithInvalidPropertyStatic() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0) + }; + + await TestAsync(""" class SomethingAttribute : System.Attribute { public static int goo { get; set; } @@ -451,20 +421,18 @@ class SomethingAttribute : System.Attribute class D { } - """; + """, expectedOrderedItems); + } + [Fact] + public async Task TestAttributeWithInvalidPropertyNoSetter() + { var expectedOrderedItems = new List { new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0) }; - await TestAsync(markup, expectedOrderedItems); - } - - [Fact] - public async Task TestAttributeWithInvalidPropertyNoSetter() - { - var markup = """ + await TestAsync(""" class SomethingAttribute : System.Attribute { public int goo { get { return 0; } } @@ -474,20 +442,18 @@ class SomethingAttribute : System.Attribute class D { } - """; + """, expectedOrderedItems); + } + [Fact] + public async Task TestAttributeWithInvalidPropertyNoGetter() + { var expectedOrderedItems = new List { new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0) }; - await TestAsync(markup, expectedOrderedItems); - } - - [Fact] - public async Task TestAttributeWithInvalidPropertyNoGetter() - { - var markup = """ + await TestAsync(""" class SomethingAttribute : System.Attribute { public int goo { set { } } @@ -497,20 +463,18 @@ public int goo { set { } } class D { } - """; + """, expectedOrderedItems); + } + [Fact] + public async Task TestAttributeWithInvalidPropertyPrivateGetter() + { var expectedOrderedItems = new List { new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0) }; - await TestAsync(markup, expectedOrderedItems); - } - - [Fact] - public async Task TestAttributeWithInvalidPropertyPrivateGetter() - { - var markup = """ + await TestAsync(""" class SomethingAttribute : System.Attribute { public int goo { private get; set; } @@ -520,20 +484,18 @@ class SomethingAttribute : System.Attribute class D { } - """; + """, expectedOrderedItems); + } + [Fact] + public async Task TestAttributeWithInvalidPropertyPrivateSetter() + { var expectedOrderedItems = new List { new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0) }; - await TestAsync(markup, expectedOrderedItems); - } - - [Fact] - public async Task TestAttributeWithInvalidPropertyPrivateSetter() - { - var markup = """ + await TestAsync(""" class SomethingAttribute : System.Attribute { public int goo { get; private set; } @@ -543,21 +505,19 @@ class SomethingAttribute : System.Attribute class D { } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23664")] [WorkItem("https://github.com/dotnet/roslyn/issues/12544")] public async Task TestAttributeWithOverriddenProperty() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem($"DerivedAttribute({FeaturesResources.Properties}: [Name = string])", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" cusing System; class BaseAttribute : Attribute @@ -575,14 +535,7 @@ class C { } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem($"DerivedAttribute({FeaturesResources.Properties}: [Name = string])", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false); + """, expectedOrderedItems, usePreviousCharAsTrigger: false); } #endregion @@ -593,7 +546,13 @@ class C [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545425")] public async Task TestAttributeWithArgumentsAndNamedParameters1() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem($"SomethingAttribute([int goo = 0], [string bar = null], {FeaturesResources.Properties}: [fieldbar = string], [fieldfoo = int])", string.Empty, "GooParameter", currentParameterIndex: 0) + }; + + // TODO: Bug 12319: Enable tests for script when this is fixed. + await TestAsync(""" class SomethingAttribute : System.Attribute { /// GooParameter @@ -607,22 +566,20 @@ public SomethingAttribute(int goo = 0, string bar = null) { } class D { } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem($"SomethingAttribute([int goo = 0], [string bar = null], {FeaturesResources.Properties}: [fieldbar = string], [fieldfoo = int])", string.Empty, "GooParameter", currentParameterIndex: 0) - }; - - // TODO: Bug 12319: Enable tests for script when this is fixed. - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false); + """, expectedOrderedItems, usePreviousCharAsTrigger: false); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544139")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545425")] public async Task TestAttributeWithArgumentsAndNamedParameters2() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem($"SomethingAttribute([int goo = 0], [string bar = null], {FeaturesResources.Properties}: [fieldbar = string], [fieldfoo = int])", string.Empty, "BarParameter", currentParameterIndex: 1) + }; + + // TODO: Bug 12319: Enable tests for script when this is fixed. + await TestAsync(""" class SomethingAttribute : System.Attribute { /// GooParameter @@ -636,22 +593,20 @@ public SomethingAttribute(int goo = 0, string bar = null) { } class D { } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem($"SomethingAttribute([int goo = 0], [string bar = null], {FeaturesResources.Properties}: [fieldbar = string], [fieldfoo = int])", string.Empty, "BarParameter", currentParameterIndex: 1) - }; - - // TODO: Bug 12319: Enable tests for script when this is fixed. - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false); + """, expectedOrderedItems, usePreviousCharAsTrigger: false); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544139")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545425")] public async Task TestAttributeWithArgumentsAndNamedParameters3() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem($"SomethingAttribute([int goo = 0], [string bar = null], {FeaturesResources.Properties}: [fieldbar = string], [fieldfoo = int])", string.Empty, string.Empty, currentParameterIndex: 2) + }; + + // TODO: Bug 12319: Enable tests for script when this is fixed. + await TestAsync(""" class SomethingAttribute : System.Attribute { /// GooParameter @@ -665,22 +620,20 @@ public SomethingAttribute(int goo = 0, string bar = null) { } class D { } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem($"SomethingAttribute([int goo = 0], [string bar = null], {FeaturesResources.Properties}: [fieldbar = string], [fieldfoo = int])", string.Empty, string.Empty, currentParameterIndex: 2) - }; - - // TODO: Bug 12319: Enable tests for script when this is fixed. - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false); + """, expectedOrderedItems, usePreviousCharAsTrigger: false); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544139")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545425")] public async Task TestAttributeWithOptionalArgumentAndNamedParameterWithSameName1() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem($"SomethingAttribute([int goo = 0], {FeaturesResources.Properties}: [goo = int])", string.Empty, "GooParameter", currentParameterIndex: 0) + }; + + // TODO: Bug 12319: Enable tests for script when this is fixed. + await TestAsync(""" class SomethingAttribute : System.Attribute { /// GooParameter @@ -692,22 +645,20 @@ public SomethingAttribute(int goo = 0) { } class D { } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem($"SomethingAttribute([int goo = 0], {FeaturesResources.Properties}: [goo = int])", string.Empty, "GooParameter", currentParameterIndex: 0) - }; - - // TODO: Bug 12319: Enable tests for script when this is fixed. - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false); + """, expectedOrderedItems, usePreviousCharAsTrigger: false); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544139")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545425")] public async Task TestAttributeWithOptionalArgumentAndNamedParameterWithSameName2() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem($"SomethingAttribute([int goo = 0], {FeaturesResources.Properties}: [goo = int])", string.Empty, string.Empty, currentParameterIndex: 1) + }; + + // TODO: Bug 12319: Enable tests for script when this is fixed. + await TestAsync(""" class SomethingAttribute : System.Attribute { /// GooParameter @@ -719,15 +670,7 @@ public SomethingAttribute(int goo = 0) { } class D { } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem($"SomethingAttribute([int goo = 0], {FeaturesResources.Properties}: [goo = int])", string.Empty, string.Empty, currentParameterIndex: 1) - }; - - // TODO: Bug 12319: Enable tests for script when this is fixed. - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false); + """, expectedOrderedItems, usePreviousCharAsTrigger: false); } #endregion @@ -737,7 +680,12 @@ class D [Fact] public async Task TestInvocationOnTriggerParens() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("SomethingAttribute(int someParameter, bool somethingElse)", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" using System; class SomethingAttribute : Attribute @@ -749,20 +697,18 @@ public SomethingAttribute(int someParameter, bool somethingElse) { } class C { } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("SomethingAttribute(int someParameter, bool somethingElse)", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); + """, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact] public async Task TestInvocationOnTriggerComma() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("SomethingAttribute(int someParameter, bool somethingElse)", string.Empty, string.Empty, currentParameterIndex: 1) + }; + + await TestAsync(""" using System; class SomethingAttribute : Attribute @@ -774,20 +720,14 @@ public SomethingAttribute(int someParameter, bool somethingElse) { } class C { } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("SomethingAttribute(int someParameter, bool somethingElse)", string.Empty, string.Empty, currentParameterIndex: 1) - }; - - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); + """, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact] public async Task TestNoInvocationOnSpace() { - var markup = """ + var expectedOrderedItems = new List(); + await TestAsync(""" using System; class SomethingAttribute : Attribute @@ -799,10 +739,7 @@ public SomethingAttribute(int someParameter, bool somethingElse) { } class C { } - """; - - var expectedOrderedItems = new List(); - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); + """, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact] @@ -974,7 +911,15 @@ await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, [Fact] public async Task FieldUnavailableInOneLinkedFile() { - var markup = """ + var expectedDescription = new SignatureHelpTestItem($""" + Secret() + + {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} + {string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)} + + {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} + """, currentParameterIndex: 0); + await VerifyItemWithReferenceWorkerAsync(""" - """; + """, [expectedDescription], false); + } + + [Fact] + public async Task ExcludeFilesWithInactiveRegions() + { var expectedDescription = new SignatureHelpTestItem($""" Secret() {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} - {string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)} + {string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)} {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} """, currentParameterIndex: 0); - await VerifyItemWithReferenceWorkerAsync(markup, [expectedDescription], false); - } - - [Fact] - public async Task ExcludeFilesWithInactiveRegions() - { - var markup = """ + await VerifyItemWithReferenceWorkerAsync(""" - """; - - var expectedDescription = new SignatureHelpTestItem($""" - Secret() - - {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} - {string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)} - - {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} - """, currentParameterIndex: 0); - await VerifyItemWithReferenceWorkerAsync(markup, [expectedDescription], false); + """, [expectedDescription], false); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")] - public async Task InvokedWithNoToken() - { - var markup = """ + public Task InvokedWithNoToken() + => TestAsync(""" // [goo($$ - """; - - await TestAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1081535")] public async Task TestInvocationWithBadParameterList() { - var markup = """ + var expectedOrderedItems = new List(); + await TestAsync(""" class SomethingAttribute : System.Attribute { } @@ -1076,9 +1007,6 @@ class SomethingAttribute : System.Attribute class D { } - """; - - var expectedOrderedItems = new List(); - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } } diff --git a/src/EditorFeatures/CSharpTest/SignatureHelp/ConstructorInitializerSignatureHelpProviderTests.cs b/src/EditorFeatures/CSharpTest/SignatureHelp/ConstructorInitializerSignatureHelpProviderTests.cs index b49b86ca81a1e..bff5937f6bf45 100644 --- a/src/EditorFeatures/CSharpTest/SignatureHelp/ConstructorInitializerSignatureHelpProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/SignatureHelp/ConstructorInitializerSignatureHelpProviderTests.cs @@ -26,7 +26,12 @@ internal override Type GetSignatureHelpProviderType() [Fact] public async Task TestInvocationWithoutParameters() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("BaseClass()", string.Empty, null, currentParameterIndex: 0) + }; + + await TestAsync(""" class BaseClass { public BaseClass() { } @@ -37,20 +42,18 @@ class Derived : BaseClass public Derived() [|: base($$|]) { } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("BaseClass()", string.Empty, null, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task TestInvocationWithoutParametersMethodXmlComments() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("BaseClass()", "Summary for BaseClass", null, currentParameterIndex: 0) + }; + + await TestAsync(""" class BaseClass { /// Summary for BaseClass @@ -62,20 +65,18 @@ class Derived : BaseClass public Derived() [|: base($$|]) { } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("BaseClass()", "Summary for BaseClass", null, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task TestInvocationWithParametersOn1() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("BaseClass(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" class BaseClass { public BaseClass(int a, int b) { } @@ -86,20 +87,18 @@ class Derived : BaseClass public Derived() [|: base($$2, 3|]) { } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("BaseClass(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task TestInvocationWithParametersXmlCommentsOn1() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param a", currentParameterIndex: 0) + }; + + await TestAsync(""" class BaseClass { /// Summary for BaseClass @@ -113,20 +112,18 @@ class Derived : BaseClass public Derived() [|: base($$2, 3|]) { } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param a", currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task TestInvocationWithParametersOn2() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param b", currentParameterIndex: 1) + }; + + await TestAsync(""" class BaseClass { /// Summary for BaseClass @@ -141,19 +138,18 @@ class Derived : BaseClass public Derived() [|: base(2, $$3|]) { } } - """; - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param b", currentParameterIndex: 1) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task TestInvocationWithParametersXmlComentsOn2() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param b", currentParameterIndex: 1) + }; + + await TestAsync(""" class BaseClass { /// Summary for BaseClass @@ -167,96 +163,87 @@ class Derived : BaseClass public Derived() [|: base(2, $$3|]) { } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param b", currentParameterIndex: 1) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2579")] public async Task TestThisInvocation() { - var markup = """ - class Goo - { - public Goo(int a, int b) { } - public Goo() [|: this(2, $$3|]) { } - } - """; - var expectedOrderedItems = new List { new SignatureHelpTestItem("Goo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1) }; - await TestAsync(markup, expectedOrderedItems); + await TestAsync(""" + class Goo + { + public Goo(int a, int b) { } + public Goo() [|: this(2, $$3|]) { } + } + """, expectedOrderedItems); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2579")] public async Task TestThisInvocationWithNonEmptyArgumentList() { - var markup = """ - class Foo - { - public Foo(int a, int b) [|: this($$|]) { } - public Foo() { } - } - """; - var expectedOrderedItems = new List { new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 0), }; - await TestAsync(markup, expectedOrderedItems); + await TestAsync(""" + class Foo + { + public Foo(int a, int b) [|: this($$|]) { } + public Foo() { } + } + """, expectedOrderedItems); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2579")] public async Task TestInvocationWithoutClosingParen() { - var markup = """ - class Goo - { - public Goo(int a, int b) { } - public Goo() [|: this(2, $$ - |]} - """; - var expectedOrderedItems = new List { new SignatureHelpTestItem("Goo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1) }; - await TestAsync(markup, expectedOrderedItems); + await TestAsync(""" + class Goo + { + public Goo(int a, int b) { } + public Goo() [|: this(2, $$ + |]} + """, expectedOrderedItems); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2579")] public async Task TestThisInvocationWithoutClosingParenWithNonEmptyArgumentList() { - var markup = """ - class Foo - { - public Foo() { } - public Foo(int a, int b) [|: this($$ - |]} - """; - var expectedOrderedItems = new List { new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 0), }; - await TestAsync(markup, expectedOrderedItems); + await TestAsync(""" + class Foo + { + public Foo() { } + public Foo(int a, int b) [|: this($$ + |]} + """, expectedOrderedItems); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25830")] public async Task PickCorrectOverload_PickInt() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("D(int i)", currentParameterIndex: 0, isSelected: true), + new SignatureHelpTestItem("D(string i)", currentParameterIndex: 0), + }; + + await TestAsync(""" class D { D() [|: this(i: 1$$|]) { } @@ -265,20 +252,19 @@ class D D(string i) => throw null; D(int i) => throw null; } - """; - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("D(int i)", currentParameterIndex: 0, isSelected: true), - new SignatureHelpTestItem("D(string i)", currentParameterIndex: 0), - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25830")] public async Task PickCorrectOverload_PickString() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("D(int i)", currentParameterIndex: 0), + new SignatureHelpTestItem("D(string i)", currentParameterIndex: 0, isSelected: true), + }; + + await TestAsync(""" class D { D() [|: this(i: null$$|]) { } @@ -287,14 +273,7 @@ class D D(string i) => throw null; D(int i) => throw null; } - """; - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("D(int i)", currentParameterIndex: 0), - new SignatureHelpTestItem("D(string i)", currentParameterIndex: 0, isSelected: true), - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } #endregion @@ -302,18 +281,14 @@ class D #region "Current Parameter Name" [Fact] - public async Task TestCurrentParameterName() - { - var markup = """ + public Task TestCurrentParameterName() + => VerifyCurrentParameterNameAsync(""" class Goo { public Goo(int a, int b) { } public Goo() : this(b: 2, a: $$ } - """; - - await VerifyCurrentParameterNameAsync(markup, "a"); - } + """, "a"); #endregion @@ -322,92 +297,82 @@ public Goo() : this(b: 2, a: $$ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2579")] public async Task TestInvocationOnTriggerParens() { - var markup = """ - class Goo - { - public Goo(int a) { } - public Goo() : this($$ - } - """; - var expectedOrderedItems = new List { new SignatureHelpTestItem("Goo(int a)", string.Empty, string.Empty, currentParameterIndex: 0) }; - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); + await TestAsync(""" + class Goo + { + public Goo(int a) { } + public Goo() : this($$ + } + """, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2579")] public async Task TestInvocationOnTriggerParensWithNonEmptyArgumentList() { - var markup = """ - class Foo - { - public Foo(int a) : this($$ - public Foo() { } - } - """; - var expectedOrderedItems = new List { new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 0), }; - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); + await TestAsync(""" + class Foo + { + public Foo(int a) : this($$ + public Foo() { } + } + """, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2579")] public async Task TestInvocationOnTriggerComma() { - var markup = """ - class Goo - { - public Goo(int a, int b) { } - public Goo() : this(2,$$ - } - """; - var expectedOrderedItems = new List { new SignatureHelpTestItem("Goo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1) }; - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); + await TestAsync(""" + class Goo + { + public Goo(int a, int b) { } + public Goo() : this(2,$$ + } + """, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2579")] public async Task TestInvocationOnTriggerCommaWithNonEmptyArgumentList() { - var markup = """ - class Foo - { - public Foo(int a, int b) : this($$ - public Foo() { } - } - """; - var expectedOrderedItems = new List { new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 0), }; - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); + await TestAsync(""" + class Foo + { + public Foo(int a, int b) : this($$ + public Foo() { } + } + """, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact] public async Task TestNoInvocationOnSpace() { - var markup = """ + var expectedOrderedItems = new List(); + await TestAsync(""" class Goo { public Goo(int a, int b) { } public Goo() : this(2, $$ } - """; - - var expectedOrderedItems = new List(); - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); + """, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact] @@ -570,7 +535,15 @@ await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, [Fact] public async Task FieldUnavailableInOneLinkedFile() { - var markup = """ + var expectedDescription = new SignatureHelpTestItem($""" + Secret(int secret) + + {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} + {string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)} + + {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} + """, currentParameterIndex: 0); + await VerifyItemWithReferenceWorkerAsync(""" - """; + """, [expectedDescription], false); + } + + [Fact] + public async Task ExcludeFilesWithInactiveRegions() + { var expectedDescription = new SignatureHelpTestItem($""" Secret(int secret) {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} - {string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)} + {string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)} {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} """, currentParameterIndex: 0); - await VerifyItemWithReferenceWorkerAsync(markup, [expectedDescription], false); - } - - [Fact] - public async Task ExcludeFilesWithInactiveRegions() - { - var markup = """ + await VerifyItemWithReferenceWorkerAsync(""" - """; - - var expectedDescription = new SignatureHelpTestItem($""" - Secret(int secret) - - {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} - {string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)} - - {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} - """, currentParameterIndex: 0); - await VerifyItemWithReferenceWorkerAsync(markup, [expectedDescription], false); + """, [expectedDescription], false); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")] - public async Task InvokedWithNoToken() - { - var markup = """ + public Task InvokedWithNoToken() + => TestAsync(""" // goo($$ - """; - - await TestAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1082601")] public async Task TestInvocationWithBadParameterList() { - var markup = """ + var expectedOrderedItems = new List(); + await TestAsync(""" class BaseClass { public BaseClass() { } @@ -680,88 +639,77 @@ class Derived : BaseClass public Derived() [|: base{$$|]) { } } - """; - - var expectedOrderedItems = new List(); - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task TypingTupleDoesNotDismiss1() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("D(object o)", currentParameterIndex: 0) + }; + + await TestAsync(""" class D { public D(object o) {} } class C : D { public C() [|: base(($$) |]{} } - """; + """, expectedOrderedItems, usePreviousCharAsTrigger: true); + } + [Fact] + public async Task TypingTupleDoesNotDismiss2() + { var expectedOrderedItems = new List { new SignatureHelpTestItem("D(object o)", currentParameterIndex: 0) }; - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); - } - - [Fact] - public async Task TypingTupleDoesNotDismiss2() - { - var markup = """ + await TestAsync(""" class D { public D(object o) {} } class C : D { public C() [|: base((1,$$) |]{} } - """; + """, expectedOrderedItems, usePreviousCharAsTrigger: true); + } + [Fact] + public async Task TypingTupleDoesNotDismiss3() + { var expectedOrderedItems = new List { new SignatureHelpTestItem("D(object o)", currentParameterIndex: 0) }; - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); - } - - [Fact] - public async Task TypingTupleDoesNotDismiss3() - { - var markup = """ + await TestAsync(""" class D { public D(object o) {} } class C : D { public C() [|: base((1, ($$) |]{} } - """; + """, expectedOrderedItems, usePreviousCharAsTrigger: true); + } + [Fact] + public async Task TypingTupleDoesNotDismiss4() + { var expectedOrderedItems = new List { new SignatureHelpTestItem("D(object o)", currentParameterIndex: 0) }; - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); - } - - [Fact] - public async Task TypingTupleDoesNotDismiss4() - { - var markup = """ + await TestAsync(""" class D { public D(object o) {} } class C : D { public C() [|: base((1, (2,$$) |]{} } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("D(object o)", currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); + """, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Theory] @@ -775,21 +723,20 @@ public C() [|: base((1, (2,$$) |]{} [WorkItem("https://github.com/dotnet/roslyn/issues/6713")] public async Task PickCorrectOverload_NamesAndEmptyPositions(string arguments, int expectedParameterIndex) { - var markup = $@" -class Program -{{ - Program() [|: this({arguments}|]) - {{ - }} - Program(int i1, int i2, int i3) {{ }} -}}"; - var expectedOrderedItems = new List { new SignatureHelpTestItem("Program(int i1, int i2, int i3)", currentParameterIndex: expectedParameterIndex, isSelected: true), }; - await TestAsync(markup, expectedOrderedItems); + await TestAsync($$""" + class Program + { + Program() [|: this({{arguments}}|]) + { + } + Program(int i1, int i2, int i3) { } + } + """, expectedOrderedItems); } [Theory] @@ -809,16 +756,6 @@ class Program [WorkItem("https://github.com/dotnet/roslyn/issues/6713")] public async Task PickCorrectOverload_Incomplete(string arguments, int expectedParameterIndex, int expecteSelectedIndex) { - var markup = $@" -class Program -{{ - Program() [|: this({arguments}|]) - {{ - }} - Program(int i, string s) {{ }} - Program(string s, string s2) {{ }} -}}"; - var index = 0; var expectedOrderedItems = new List { @@ -826,6 +763,15 @@ class Program new SignatureHelpTestItem("Program(string s, string s2)", currentParameterIndex: expectedParameterIndex, isSelected: expecteSelectedIndex == index++), }; - await TestAsync(markup, expectedOrderedItems); + await TestAsync($$""" + class Program + { + Program() [|: this({{arguments}}|]) + { + } + Program(int i, string s) { } + Program(string s, string s2) { } + } + """, expectedOrderedItems); } } diff --git a/src/EditorFeatures/CSharpTest/SignatureHelp/ElementAccessExpressionSignatureHelpProviderTests.cs b/src/EditorFeatures/CSharpTest/SignatureHelp/ElementAccessExpressionSignatureHelpProviderTests.cs index b227f52f11fd6..7ab810931f80b 100644 --- a/src/EditorFeatures/CSharpTest/SignatureHelp/ElementAccessExpressionSignatureHelpProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/SignatureHelp/ElementAccessExpressionSignatureHelpProviderTests.cs @@ -26,7 +26,12 @@ internal override Type GetSignatureHelpProviderType() [Fact] public async Task TestInvocationWithParametersOn1() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" class C { public string this[int a] @@ -44,20 +49,18 @@ void Goo() var x = [|c[$$|]]; } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24311")] public async Task TestInvocationWithParametersOn1_WithRefReturn() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("ref int C[int a]", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" class C { public ref int this[int a] @@ -69,20 +72,18 @@ void Goo(C c) [|c[$$]|] } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("ref int C[int a]", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24311")] public async Task TestInvocationWithParametersOn1_WithRefReadonlyReturn() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("ref readonly int C[int a]", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" class C { public ref readonly int this[int a] @@ -94,20 +95,18 @@ void Goo(C c) [|c[$$]|] } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("ref readonly int C[int a]", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636117")] public async Task TestInvocationOnExpression() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" class C { public string this[int a] @@ -125,20 +124,18 @@ void Goo() c[0][$$ } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task TestInvocationWithParametersXmlCommentsOn1() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("string C[int a]", "Summary for this.", "Param a", currentParameterIndex: 0) + }; + + await TestAsync(""" class C { /// @@ -160,20 +157,18 @@ void Goo() var x = [|c[$$|]]; } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("string C[int a]", "Summary for this.", "Param a", currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task TestInvocationWithParametersOn2() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1) + }; + + await TestAsync(""" class C { public string this[int a, bool b] @@ -191,19 +186,18 @@ void Goo() var x = [|c[22, $$|]]; } } - """; - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task TestInvocationWithParametersXmlComentsOn2() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("string C[int a, bool b]", "Summary for this.", "Param b", currentParameterIndex: 1) + }; + + await TestAsync(""" class C { /// @@ -226,21 +220,18 @@ void Goo() var x = [|c[22, $$|]]; } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("string C[int a, bool b]", "Summary for this.", "Param b", currentParameterIndex: 1) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task TestInvocationWithoutClosingBracketWithParameters() { - var markup = - """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" class C { public string this[int a] @@ -258,20 +249,18 @@ void Goo() var x = [|c[$$ |]} } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task TestInvocationWithoutClosingBracketWithParametersOn2() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1) + }; + + await TestAsync(""" class C { public string this[int a, bool b] @@ -289,14 +278,7 @@ void Goo() var x = [|c[22, $$ |]} } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } #endregion @@ -304,9 +286,8 @@ void Goo() #region "Current Parameter Name" [Fact] - public async Task TestCurrentParameterName() - { - var markup = """ + public Task TestCurrentParameterName() + => VerifyCurrentParameterNameAsync(""" class C { public string this[int a, bool b] @@ -324,10 +305,7 @@ void Goo() var x = [|c[b: false, a: $$42|]]; } } - """; - - await VerifyCurrentParameterNameAsync(markup, "a"); - } + """, "a"); #endregion @@ -336,7 +314,12 @@ void Goo() [Fact] public async Task TestInvocationOnTriggerBracket() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" class C { public string this[int a] @@ -354,20 +337,18 @@ void Goo() var x = [|c[$$|]]; } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); + """, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact] public async Task TestInvocationOnTriggerComma() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1) + }; + + await TestAsync(""" class C { public string this[int a, bool b] @@ -385,20 +366,14 @@ void Goo() var x = [|c[42,$$|]]; } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1) - }; - - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); + """, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact] public async Task TestNoInvocationOnSpace() { - var markup = """ + var expectedOrderedItems = new List(); + await TestAsync(""" class C { public string this[int a, bool b] @@ -416,10 +391,7 @@ void Goo() var x = [|c[42, $$|]]; } } - """; - - var expectedOrderedItems = new List(); - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); + """, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact] @@ -788,7 +760,15 @@ await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, [Fact] public async Task FieldUnavailableInOneLinkedFile() { - var markup = """ + var expectedDescription = new SignatureHelpTestItem($""" + int C[int z] + + {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} + {string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)} + + {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} + """, currentParameterIndex: 0); + await VerifyItemWithReferenceWorkerAsync(""" - """; + """, [expectedDescription], false); + } + + [Fact] + public async Task ExcludeFilesWithInactiveRegions() + { var expectedDescription = new SignatureHelpTestItem($""" int C[int z] {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} - {string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)} + {string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)} {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} """, currentParameterIndex: 0); - await VerifyItemWithReferenceWorkerAsync(markup, [expectedDescription], false); - } - - [Fact] - public async Task ExcludeFilesWithInactiveRegions() - { - var markup = """ + await VerifyItemWithReferenceWorkerAsync(""" - """; - - var expectedDescription = new SignatureHelpTestItem($""" - int C[int z] - - {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} - {string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)} - - {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} - """, currentParameterIndex: 0); - await VerifyItemWithReferenceWorkerAsync(markup, [expectedDescription], false); + """, [expectedDescription], false); } [Trait(Traits.Feature, Traits.Features.SignatureHelp)] @@ -885,7 +854,12 @@ internal override Type GetSignatureHelpProviderType() [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636117")] public async Task TestInvocation() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" class C { public string this[int a] @@ -903,20 +877,18 @@ void Goo() c[$$] } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939417")] public async Task ConditionalIndexer() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("int P[int z]", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" public class P { public int this[int z] @@ -933,14 +905,7 @@ public void goo() p?[$$] } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("int P[int z]", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32")] @@ -997,19 +962,14 @@ void M() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")] - public async Task InvokedWithNoToken() - { - var markup = """ + public Task InvokedWithNoToken() + => TestAsync(""" // goo[$$ - """; - - await TestAsync(markup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2482")] - public async Task WhereExpressionLooksLikeArrayTypeSyntaxOfQualifiedName() - { - var markup = """ + public Task WhereExpressionLooksLikeArrayTypeSyntaxOfQualifiedName() + => TestAsync(""" class WithIndexer { public int this[int index] { get { return 0; } } @@ -1025,14 +985,11 @@ public void Method(TestClass tc) tc.Item[$$] } } - """; - await TestAsync(markup, [new SignatureHelpTestItem("int WithIndexer[int index]")], usePreviousCharAsTrigger: true); - } + """, [new SignatureHelpTestItem("int WithIndexer[int index]")], usePreviousCharAsTrigger: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20507")] - public async Task InConditionalIndexingFollowedByMemberAccess() - { - var markup = """ + public Task InConditionalIndexingFollowedByMemberAccess() + => TestAsync(""" class Indexable { public Indexable this[int x] { get => null; } @@ -1045,14 +1002,11 @@ static void Main(string[] args) x?[$$].Count; } } - """; - await TestAsync(markup, [new SignatureHelpTestItem("Indexable Indexable[int x]")], usePreviousCharAsTrigger: false); - } + """, [new SignatureHelpTestItem("Indexable Indexable[int x]")], usePreviousCharAsTrigger: false); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20507")] - public async Task InConditionalIndexingFollowedByConditionalAccess() - { - var markup = """ + public Task InConditionalIndexingFollowedByConditionalAccess() + => TestAsync(""" class Indexable { public Indexable this[int x] { get => null; } @@ -1065,8 +1019,6 @@ static void Main(string[] args) x?[$$].Count?.Count; } } - """; - await TestAsync(markup, [new SignatureHelpTestItem("Indexable Indexable[int x]")], usePreviousCharAsTrigger: false); - } + """, [new SignatureHelpTestItem("Indexable Indexable[int x]")], usePreviousCharAsTrigger: false); } } diff --git a/src/EditorFeatures/CSharpTest/SignatureHelp/GenericNamePartiallyWrittenSignatureHelpProviderTests.cs b/src/EditorFeatures/CSharpTest/SignatureHelp/GenericNamePartiallyWrittenSignatureHelpProviderTests.cs index d1cf46702c2b7..0386807788470 100644 --- a/src/EditorFeatures/CSharpTest/SignatureHelp/GenericNamePartiallyWrittenSignatureHelpProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/SignatureHelp/GenericNamePartiallyWrittenSignatureHelpProviderTests.cs @@ -25,7 +25,12 @@ internal override Type GetSignatureHelpProviderType() [Fact] public async Task NestedGenericUnterminated() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("G", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" class G { }; class C @@ -35,20 +40,18 @@ void Goo() G$$ } } - """; + """, expectedOrderedItems); + } + [Fact] + public async Task NestedGenericUnterminatedWithAmbiguousShift() + { var expectedOrderedItems = new List { new SignatureHelpTestItem("G", string.Empty, string.Empty, currentParameterIndex: 0) }; - await TestAsync(markup, expectedOrderedItems); - } - - [Fact] - public async Task NestedGenericUnterminatedWithAmbiguousShift() - { - var markup = """ + await TestAsync(""" class G { }; class C @@ -60,20 +63,18 @@ void Goo() x = x; } } - """; + """, expectedOrderedItems); + } + [Fact] + public async Task NestedGenericUnterminatedWithAmbiguousUnsignedShift() + { var expectedOrderedItems = new List { new SignatureHelpTestItem("G", string.Empty, string.Empty, currentParameterIndex: 0) }; - await TestAsync(markup, expectedOrderedItems); - } - - [Fact] - public async Task NestedGenericUnterminatedWithAmbiguousUnsignedShift() - { - var markup = """ + await TestAsync(""" class G { }; class C @@ -85,20 +86,18 @@ void Goo() x = x; } } - """; + """, expectedOrderedItems); + } + [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544088")] + public async Task DeclaringGenericTypeWith1ParameterUnterminated() + { var expectedOrderedItems = new List { new SignatureHelpTestItem("G", string.Empty, string.Empty, currentParameterIndex: 0) }; - await TestAsync(markup, expectedOrderedItems); - } - - [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544088")] - public async Task DeclaringGenericTypeWith1ParameterUnterminated() - { - var markup = """ + await TestAsync(""" class G { }; class C @@ -108,20 +107,19 @@ void Goo() [|G<$$ |]} } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("G", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task CallingGenericAsyncMethod() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem($"({CSharpFeaturesResources.awaitable}) Task Program.Goo()", methodDocumentation: string.Empty, string.Empty, currentParameterIndex: 0) + }; + + // TODO: Enable the script case when we have support for extension methods in scripts + await TestAsync(""" using System.Threading.Tasks; class Program { @@ -134,15 +132,7 @@ Task Goo() return Goo(); } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem($"({CSharpFeaturesResources.awaitable}) Task Program.Goo()", methodDocumentation: string.Empty, string.Empty, currentParameterIndex: 0) - }; - - // TODO: Enable the script case when we have support for extension methods in scripts - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false, sourceCodeKind: Microsoft.CodeAnalysis.SourceCodeKind.Regular); + """, expectedOrderedItems, usePreviousCharAsTrigger: false, sourceCodeKind: Microsoft.CodeAnalysis.SourceCodeKind.Regular); } [Fact, WorkItem(7336, "DevDiv_Projects/Roslyn")] @@ -306,7 +296,14 @@ await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, [Fact] public async Task GenericExtensionMethod() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("void IGoo.Bar()", currentParameterIndex: 0), + new SignatureHelpTestItem($"({CSharpFeaturesResources.extension}) void IGoo.Bar()", currentParameterIndex: 0), + }; + + // Extension methods are supported in Interactive/Script (yet). + await TestAsync(""" interface IGoo { void Bar(); @@ -325,22 +322,19 @@ static void Main() f.[|Bar<$$ |]} } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("void IGoo.Bar()", currentParameterIndex: 0), - new SignatureHelpTestItem($"({CSharpFeaturesResources.extension}) void IGoo.Bar()", currentParameterIndex: 0), - }; - - // Extension methods are supported in Interactive/Script (yet). - await TestAsync(markup, expectedOrderedItems, sourceCodeKind: SourceCodeKind.Regular); + """, expectedOrderedItems, sourceCodeKind: SourceCodeKind.Regular); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544088")] public async Task InvokingGenericMethodWith1ParameterUnterminated() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("void C.Goo()", + "Method Goo", "Method type parameter", currentParameterIndex: 0) + }; + + await TestAsync(""" class C { /// @@ -354,21 +348,18 @@ void Bar() [|Goo<$$ |]} } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("void C.Goo()", - "Method Goo", "Method type parameter", currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task TestInvocationOnTriggerBracket() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("G", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" class G { }; class C @@ -378,20 +369,18 @@ void Goo() [|G<$$ |]} } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("G", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); + """, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact] public async Task TestInvocationOnTriggerComma() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("G", string.Empty, string.Empty, currentParameterIndex: 1) + }; + + await TestAsync(""" class G { }; class C @@ -401,23 +390,12 @@ void Goo() [|G - { - new SignatureHelpTestItem("G", string.Empty, string.Empty, currentParameterIndex: 1) - }; - - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); + """, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")] - public async Task InvokedWithNoToken() - { - var markup = """ + public Task InvokedWithNoToken() + => TestAsync(""" // goo<$$ - """; - - await TestAsync(markup); - } + """); } diff --git a/src/EditorFeatures/CSharpTest/SignatureHelp/GenericNameSignatureHelpProviderTests.cs b/src/EditorFeatures/CSharpTest/SignatureHelp/GenericNameSignatureHelpProviderTests.cs index 4f9f75a7fae39..62adec90b36f5 100644 --- a/src/EditorFeatures/CSharpTest/SignatureHelp/GenericNameSignatureHelpProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/SignatureHelp/GenericNameSignatureHelpProviderTests.cs @@ -29,7 +29,12 @@ internal override Type GetSignatureHelpProviderType() [Fact] public async Task NestedGenericTerminated() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("G", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" class G { }; class C @@ -39,20 +44,18 @@ void Goo() G$$> } } - """; + """, expectedOrderedItems); + } + [Fact] + public async Task DeclaringGenericTypeWith1ParameterTerminated() + { var expectedOrderedItems = new List { new SignatureHelpTestItem("G", string.Empty, string.Empty, currentParameterIndex: 0) }; - await TestAsync(markup, expectedOrderedItems); - } - - [Fact] - public async Task DeclaringGenericTypeWith1ParameterTerminated() - { - var markup = """ + await TestAsync(""" class G { }; class C @@ -62,20 +65,18 @@ void Goo() [|G<$$|]> } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("G", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task DeclaringGenericTypeWith2ParametersOn1() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("G", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" class G { }; class C @@ -85,20 +86,18 @@ void Goo() [|G<$$|]> } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("G", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task DeclaringGenericTypeWith2ParametersOn2() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("G", string.Empty, string.Empty, currentParameterIndex: 1) + }; + + await TestAsync(""" class G { }; class C @@ -108,20 +107,21 @@ void Goo() [|G } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("G", string.Empty, string.Empty, currentParameterIndex: 1) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task DeclaringGenericTypeWith2ParametersOn1XmlDoc() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("G", + "Summary for G", + "TypeParamS. Also see T", + currentParameterIndex: 0) + }; + + await TestAsync(""" /// /// Summary for G /// @@ -136,23 +136,18 @@ void Goo() [|G<$$|]> } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("G", - "Summary for G", - "TypeParamS. Also see T", - currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task DeclaringGenericTypeWith2ParametersOn2XmlDoc() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("G", "Summary for G", "TypeParamT. Also see S", currentParameterIndex: 1) + }; + + await TestAsync(""" /// /// Summary for G /// @@ -167,14 +162,7 @@ void Goo() [|G } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("G", "Summary for G", "TypeParamT. Also see S", currentParameterIndex: 1) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } #endregion @@ -184,7 +172,12 @@ void Goo() [Fact] public async Task DeclaringGenericTypeWithConstraintsStruct() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("G where S : struct", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" class G where S : struct { }; @@ -195,20 +188,18 @@ void Goo() [|G<$$|]> } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("G where S : struct", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task DeclaringGenericTypeWithConstraintsClass() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("G where S : class", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" class G where S : class { }; @@ -219,20 +210,18 @@ void Goo() [|G<$$|]> } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("G where S : class", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task DeclaringGenericTypeWithConstraintsNew() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("G where S : new()", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" class G where S : new() { }; @@ -243,20 +232,18 @@ void Goo() [|G<$$|]> } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("G where S : new()", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task DeclaringGenericTypeWithConstraintsBase() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("G where S : Base", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" class Base { } class G where S : Base @@ -269,20 +256,18 @@ void Goo() [|G<$$|]> } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("G where S : Base", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task DeclaringGenericTypeWithConstraintsBaseGenericWithGeneric() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("G where S : Base", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" class Base { } class G where S : Base @@ -295,20 +280,18 @@ void Goo() [|G<$$|]> } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("G where S : Base", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task DeclaringGenericTypeWithConstraintsBaseGenericWithNonGeneric() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("G where S : Base", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" class Base { } class G where S : Base @@ -321,20 +304,18 @@ void Goo() [|G<$$|]> } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("G where S : Base", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task DeclaringGenericTypeWithConstraintsBaseGenericNested() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("G where S : Base>", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" class Base { } class G where S : Base> @@ -347,20 +328,18 @@ void Goo() [|G<$$|]> } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("G where S : Base>", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task DeclaringGenericTypeWithConstraintsDeriveFromAnotherGenericParameter() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("G where S : T", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" class G where S : T { }; @@ -371,20 +350,18 @@ void Goo() [|G<$$|]> } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("G where S : T", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task DeclaringGenericTypeWithConstraintsMixed1() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("G where S : Base, new()", "Summary1", "SummaryS", currentParameterIndex: 0) + }; + + await TestAsync(""" /// /// Summary1 /// @@ -406,20 +383,18 @@ void Goo() [|G<$$|]> } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("G where S : Base, new()", "Summary1", "SummaryS", currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task DeclaringGenericTypeWithConstraintsMixed2() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("G where T : class, S, IGoo, new()", "Summary1", "SummaryT", currentParameterIndex: 1) + }; + + await TestAsync(""" /// /// Summary1 /// @@ -441,20 +416,18 @@ void Goo() [|G } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("G where T : class, S, IGoo, new()", "Summary1", "SummaryT", currentParameterIndex: 1) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task DeclaringGenericTypeWithConstraintsAllowRefStruct() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("G where S : allows ref struct", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" class G where S : allows ref struct { }; @@ -465,14 +438,7 @@ void Goo() [|G<$$|]> } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("G where S : allows ref struct", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } #endregion @@ -482,7 +448,12 @@ void Goo() [Fact] public async Task InvokingGenericMethodWith1ParameterTerminated() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("void C.Goo()", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + await TestAsync(""" class C { void Goo() { } @@ -492,20 +463,19 @@ void Bar() [|Goo<$$|]> } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("void C.Goo()", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544091")] public async Task InvokingGenericMethodWith2ParametersOn1() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("void C.Goo(S s, T t)", + "Method summary", "type param S. see T", currentParameterIndex: 0) + }; + + await TestAsync(""" class C { /// @@ -522,21 +492,18 @@ void Bar() [|Goo<$$|]> } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("void C.Goo(S s, T t)", - "Method summary", "type param S. see T", currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544091")] public async Task InvokingGenericMethodWith2ParametersOn2() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("void C.Goo(S s, T t)", string.Empty, string.Empty, currentParameterIndex: 1) + }; + + await TestAsync(""" class C { void Goo(S s, T t) { } @@ -546,20 +513,18 @@ void Bar() [|Goo } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("void C.Goo(S s, T t)", string.Empty, string.Empty, currentParameterIndex: 1) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544091")] public async Task InvokingGenericMethodWith2ParametersOn1XmlDoc() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("void C.Goo(S s, T t)", "SummaryForGoo", "SummaryForS", currentParameterIndex: 0) + }; + + await TestAsync(""" class C { /// @@ -574,20 +539,18 @@ void Bar() [|Goo<$$|]> } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("void C.Goo(S s, T t)", "SummaryForGoo", "SummaryForS", currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544091")] public async Task InvokingGenericMethodWith2ParametersOn2XmlDoc() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("void C.Goo(S s, T t)", "SummaryForGoo", "SummaryForT", currentParameterIndex: 1) + }; + + await TestAsync(""" class C { /// @@ -602,20 +565,19 @@ void Bar() [|Goo } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("void C.Goo(S s, T t)", "SummaryForGoo", "SummaryForT", currentParameterIndex: 1) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] public async Task CallingGenericExtensionMethod() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem($"({CSharpFeaturesResources.extension}) void G.Goo()", string.Empty, string.Empty, currentParameterIndex: 0) + }; + + // TODO: Enable the script case when we have support for extension methods in scripts + await TestAsync(""" class G { }; @@ -632,15 +594,7 @@ static class GooClass { public static void Goo(this G g) { } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem($"({CSharpFeaturesResources.extension}) void G.Goo()", string.Empty, string.Empty, currentParameterIndex: 0) - }; - - // TODO: Enable the script case when we have support for extension methods in scripts - await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false, sourceCodeKind: Microsoft.CodeAnalysis.SourceCodeKind.Regular); + """, expectedOrderedItems, usePreviousCharAsTrigger: false, sourceCodeKind: Microsoft.CodeAnalysis.SourceCodeKind.Regular); } #endregion @@ -650,7 +604,12 @@ public static void Goo(this G g) { } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544091")] public async Task InvokingGenericMethodWithConstraintsMixed1() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("S C.Goo(S s, T t) where S : Base, new()", "GooSummary", "ParamS", currentParameterIndex: 0) + }; + + await TestAsync(""" class Base { } interface IGoo { } @@ -671,20 +630,18 @@ void Bar() [|Goo<$$|]> } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("S C.Goo(S s, T t) where S : Base, new()", "GooSummary", "ParamS", currentParameterIndex: 0) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544091")] public async Task InvokingGenericMethodWithConstraintsMixed2() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("S C.Goo(S s, T t) where T : class, S, IGoo, new()", "GooSummary", "ParamT", currentParameterIndex: 1) + }; + + await TestAsync(""" class Base { } interface IGoo { } @@ -705,20 +662,12 @@ void Bar() [|Goo } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("S C.Goo(S s, T t) where T : class, S, IGoo, new()", "GooSummary", "ParamT", currentParameterIndex: 1) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact] - public async Task TestUnmanagedConstraint() - { - var markup = """ + public Task TestUnmanagedConstraint() + => TestAsync(""" class C { /// @@ -734,13 +683,10 @@ void Bar() [|M<$$|]> } } - """; - - await TestAsync(markup, + """, [ new SignatureHelpTestItem("void C.M(T arg) where T : unmanaged", "summary headline", "T documentation", currentParameterIndex: 0) ]); - } #endregion @@ -758,7 +704,15 @@ public void TestTriggerCharacters() [Fact] public async Task FieldUnavailableInOneLinkedFile() { - var markup = """ + var expectedDescription = new SignatureHelpTestItem($""" + D + + {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} + {string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)} + + {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} + """, currentParameterIndex: 0); + await VerifyItemWithReferenceWorkerAsync(""" - """; + """, [expectedDescription], false); + } + + [Fact] + public async Task ExcludeFilesWithInactiveRegions() + { var expectedDescription = new SignatureHelpTestItem($""" D {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} - {string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)} + {string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)} {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} """, currentParameterIndex: 0); - await VerifyItemWithReferenceWorkerAsync(markup, [expectedDescription], false); - } - - [Fact] - public async Task ExcludeFilesWithInactiveRegions() - { - var markup = """ + await VerifyItemWithReferenceWorkerAsync(""" - """; - - var expectedDescription = new SignatureHelpTestItem($""" - D - - {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} - {string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)} - - {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} - """, currentParameterIndex: 0); - await VerifyItemWithReferenceWorkerAsync(markup, [expectedDescription], false); + """, [expectedDescription], false); } #endregion @@ -954,7 +897,8 @@ await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1083601")] public async Task DeclaringGenericTypeWithBadTypeArgumentList() { - var markup = """ + var expectedOrderedItems = new List(); + await TestAsync(""" class G { }; class C @@ -964,16 +908,29 @@ void Goo() G{$$> } } - """; - - var expectedOrderedItems = new List(); - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50114")] public async Task DeclaringGenericTypeWithDocCommentList() { - var markup = """ + var expectedOrderedItems = new List + { + new SignatureHelpTestItem("G", """ + List: + + Item 1. + """, + classificationTypeNames: ImmutableArray.Create( + ClassificationTypeNames.Text, + ClassificationTypeNames.WhiteSpace, + ClassificationTypeNames.WhiteSpace, + ClassificationTypeNames.WhiteSpace, + ClassificationTypeNames.Text, + ClassificationTypeNames.WhiteSpace)) + }; + + await TestAsync(""" /// /// List: /// @@ -993,24 +950,6 @@ void Goo() [|G } } - """; - - var expectedOrderedItems = new List - { - new SignatureHelpTestItem("G", """ - List: - - Item 1. - """, - classificationTypeNames: ImmutableArray.Create( - ClassificationTypeNames.Text, - ClassificationTypeNames.WhiteSpace, - ClassificationTypeNames.WhiteSpace, - ClassificationTypeNames.WhiteSpace, - ClassificationTypeNames.Text, - ClassificationTypeNames.WhiteSpace)) - }; - - await TestAsync(markup, expectedOrderedItems); + """, expectedOrderedItems); } } diff --git a/src/EditorFeatures/CSharpTest/SignatureHelp/InitializerExpressionSignatureHelpProviderTests.cs b/src/EditorFeatures/CSharpTest/SignatureHelp/InitializerExpressionSignatureHelpProviderTests.cs index b153378e84216..10a50fa7e9a3c 100644 --- a/src/EditorFeatures/CSharpTest/SignatureHelp/InitializerExpressionSignatureHelpProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/SignatureHelp/InitializerExpressionSignatureHelpProviderTests.cs @@ -18,9 +18,8 @@ internal override Type GetSignatureHelpProviderType() => typeof(InitializerExpressionSignatureHelpProvider); [Fact] - public async Task WithSingleParamAddMethods() - { - var markup = """ + public Task WithSingleParamAddMethods() + => TestAsync(""" using System.Collections.Generic; class C @@ -30,15 +29,11 @@ void Goo() new List { { $$ } } - """; - - await TestAsync(markup, [new("void List.Add(int item)", currentParameterIndex: 0)]); - } + """, [new("void List.Add(int item)", currentParameterIndex: 0)]); [Fact] - public async Task ForMultiParamAddMethods() - { - var markup = """ + public Task ForMultiParamAddMethods() + => TestAsync(""" using System.Collections.Generic; class C @@ -48,15 +43,11 @@ void Goo() new Dictionary { { $$ } } - """; - - await TestAsync(markup, [new("void Dictionary.Add(int key, string value)", currentParameterIndex: 0)]); - } + """, [new("void Dictionary.Add(int key, string value)", currentParameterIndex: 0)]); [Fact] - public async Task ForSecondParam() - { - var markup = """ + public Task ForSecondParam() + => TestAsync(""" using System.Collections.Generic; class C @@ -66,15 +57,11 @@ void Goo() new Dictionary { { 0, $$ } } - """; - - await TestAsync(markup, [new("void Dictionary.Add(int key, string value)", currentParameterIndex: 1)]); - } + """, [new("void Dictionary.Add(int key, string value)", currentParameterIndex: 1)]); [Fact] - public async Task ForNestedCollectionInitializer() - { - var markup = """ + public Task ForNestedCollectionInitializer() + => TestAsync(""" using System.Collections.Generic; class Bar @@ -89,15 +76,11 @@ void Goo() new Bar { D = { { $$ } } - """; - - await TestAsync(markup, [new("void Dictionary.Add(int key, string value)", currentParameterIndex: 0)]); - } + """, [new("void Dictionary.Add(int key, string value)", currentParameterIndex: 0)]); [Fact] - public async Task WithoutClosingBraces() - { - var markup = """ + public Task WithoutClosingBraces() + => TestAsync(""" using System.Collections.Generic; class Bar @@ -110,15 +93,11 @@ class C void Goo() { new Bar { D = { { $$ - """; - - await TestAsync(markup, [new("void Dictionary.Add(int key, string value)", currentParameterIndex: 0)]); - } + """, [new("void Dictionary.Add(int key, string value)", currentParameterIndex: 0)]); [Fact] - public async Task WithMultipleAddMethods() - { - var markup = """ + public Task WithMultipleAddMethods() + => TestAsync(""" using System.Collections; class Bar : IEnumerable @@ -133,18 +112,14 @@ class C void Goo() { new Bar { { $$ - """; - - await TestAsync(markup, [ + """, [ new("void Bar.Add(int i)", currentParameterIndex: 0), new("void Bar.Add(int i, string s)", currentParameterIndex: 0, isSelected: true), new("void Bar.Add(int i, string s, bool b)", currentParameterIndex: 0)]); - } [Fact] - public async Task DoesNotImplementIEnumerable() - { - var markup = """ + public Task DoesNotImplementIEnumerable() + => TestAsync(""" using System.Collections; class Bar @@ -159,15 +134,11 @@ class C void Goo() { new Bar { { $$ - """; - - await TestAsync(markup, expectedOrderedItemsOrNull: []); - } + """, expectedOrderedItemsOrNull: []); [Fact] - public async Task WithExtensionAddMethods() - { - var markup = """ + public Task WithExtensionAddMethods() + => TestAsync(""" using System.Collections; class Bar : IEnumerable @@ -186,11 +157,8 @@ class C void Goo() { new Bar { { $$ - """; - - await TestAsync(markup, [ + """, [ new($"({CSharpFeaturesResources.extension}) void Bar.Add(int i)", currentParameterIndex: 0), new($"({CSharpFeaturesResources.extension}) void Bar.Add(int i, string s)", currentParameterIndex: 0, isSelected: true), new($"({CSharpFeaturesResources.extension}) void Bar.Add(int i, string s, bool b)", currentParameterIndex: 0)], sourceCodeKind: SourceCodeKind.Regular); - } } diff --git a/src/EditorFeatures/CSharpTest/SignatureHelp/InvocationExpressionSignatureHelpProviderTests.cs b/src/EditorFeatures/CSharpTest/SignatureHelp/InvocationExpressionSignatureHelpProviderTests.cs index 2abfcf0a51a76..7b4d9958c9a01 100644 --- a/src/EditorFeatures/CSharpTest/SignatureHelp/InvocationExpressionSignatureHelpProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/SignatureHelp/InvocationExpressionSignatureHelpProviderTests.cs @@ -23,9 +23,8 @@ internal override Type GetSignatureHelpProviderType() #region "Regular tests" [Fact] - public async Task TestInvocationAfterCloseParen() - { - var markup = """ + public Task TestInvocationAfterCloseParen() + => TestAsync(""" class C { int Goo(int x) @@ -33,15 +32,11 @@ int Goo(int x) [|Goo(Goo(x)$$|]); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("int C.Goo(int x)", currentParameterIndex: 0)]); - } + """, [new SignatureHelpTestItem("int C.Goo(int x)", currentParameterIndex: 0)]); [Fact] - public async Task TestInvocationInsideLambda() - { - var markup = """ + public Task TestInvocationInsideLambda() + => TestAsync(""" using System; class C @@ -51,15 +46,11 @@ void Goo(Action f) [|Goo(i => Console.WriteLine(i)$$|]); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void C.Goo(Action f)", currentParameterIndex: 0)]); - } + """, [new SignatureHelpTestItem("void C.Goo(Action f)", currentParameterIndex: 0)]); [Fact] - public async Task TestInvocationInsideLambda2() - { - var markup = """ + public Task TestInvocationInsideLambda2() + => TestAsync(""" using System; class C @@ -69,15 +60,11 @@ void Goo(Action f) [|Goo(i => Con$$sole.WriteLine(i)|]); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void C.Goo(Action f)", currentParameterIndex: 0)]); - } + """, [new SignatureHelpTestItem("void C.Goo(Action f)", currentParameterIndex: 0)]); [Fact] - public async Task TestInvocationWithoutParameters() - { - var markup = """ + public Task TestInvocationWithoutParameters() + => TestAsync(""" class C { void Goo() @@ -85,15 +72,11 @@ void Goo() [|Goo($$|]); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void C.Goo()", string.Empty, null, currentParameterIndex: 0)]); - } + """, [new SignatureHelpTestItem("void C.Goo()", string.Empty, null, currentParameterIndex: 0)]); [Fact] - public async Task TestInvocationWithoutParametersMethodXmlComments() - { - var markup = """ + public Task TestInvocationWithoutParametersMethodXmlComments() + => TestAsync(""" class C { /// @@ -104,15 +87,11 @@ void Goo() [|Goo($$|]); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void C.Goo()", "Summary for goo", null, currentParameterIndex: 0)]); - } + """, [new SignatureHelpTestItem("void C.Goo()", "Summary for goo", null, currentParameterIndex: 0)]); [Fact] - public async Task TestInvocationWithParametersOn1() - { - var markup = """ + public Task TestInvocationWithParametersOn1() + => TestAsync(""" class C { void Goo(int a, int b) @@ -120,15 +99,11 @@ void Goo(int a, int b) [|Goo($$a, b|]); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void C.Goo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)]); - } + """, [new SignatureHelpTestItem("void C.Goo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)]); [Fact] - public async Task TestInvocationWithParametersXmlCommentsOn1() - { - var markup = """ + public Task TestInvocationWithParametersXmlCommentsOn1() + => TestAsync(""" class C { /// @@ -141,15 +116,11 @@ void Goo(int a, int b) [|Goo($$a, b|]); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void C.Goo(int a, int b)", "Summary for Goo", "Param a", currentParameterIndex: 0)]); - } + """, [new SignatureHelpTestItem("void C.Goo(int a, int b)", "Summary for Goo", "Param a", currentParameterIndex: 0)]); [Fact] - public async Task TestInvocationWithParametersOn2() - { - var markup = """ + public Task TestInvocationWithParametersOn2() + => TestAsync(""" class C { void Goo(int a, int b) @@ -157,15 +128,11 @@ void Goo(int a, int b) [|Goo(a, $$b|]); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void C.Goo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)]); - } + """, [new SignatureHelpTestItem("void C.Goo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)]); [Fact] - public async Task TestInvocationWithParametersXmlComentsOn2() - { - var markup = """ + public Task TestInvocationWithParametersXmlComentsOn2() + => TestAsync(""" class C { /// @@ -178,15 +145,11 @@ void Goo(int a, int b) [|Goo(a, $$b|]); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void C.Goo(int a, int b)", "Summary for Goo", "Param b", currentParameterIndex: 1)]); - } + """, [new SignatureHelpTestItem("void C.Goo(int a, int b)", "Summary for Goo", "Param b", currentParameterIndex: 1)]); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26713")] - public async Task TestDelegateParameterWithDocumentation_Invoke() - { - var markup = """ + public Task TestDelegateParameterWithDocumentation_Invoke() + => TestAsync(""" class C { /// Parameter docs @@ -197,15 +160,11 @@ void M(SomeDelegate theDelegate) [|theDelegate($$|]); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void SomeDelegate(int a)", parameterDocumentation: "Parameter docs", currentParameterIndex: 0)]); - } + """, [new SignatureHelpTestItem("void SomeDelegate(int a)", parameterDocumentation: "Parameter docs", currentParameterIndex: 0)]); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26713")] - public async Task TestDelegateParameterWithDocumentation_Invoke2() - { - var markup = """ + public Task TestDelegateParameterWithDocumentation_Invoke2() + => TestAsync(""" class C { /// Parameter docs @@ -216,15 +175,11 @@ void M(SomeDelegate theDelegate) [|theDelegate.Invoke($$|]); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void SomeDelegate.Invoke(int a)", parameterDocumentation: "Parameter docs", currentParameterIndex: 0)]); - } + """, [new SignatureHelpTestItem("void SomeDelegate.Invoke(int a)", parameterDocumentation: "Parameter docs", currentParameterIndex: 0)]); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26713")] - public async Task TestDelegateParameterWithDocumentation_BeginInvoke() - { - var markup = """ + public Task TestDelegateParameterWithDocumentation_BeginInvoke() + => TestAsync(""" class C { /// Parameter docs @@ -235,15 +190,11 @@ void M(SomeDelegate theDelegate) [|theDelegate.BeginInvoke($$|]); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("System.IAsyncResult SomeDelegate.BeginInvoke(int a, System.AsyncCallback callback, object @object)", parameterDocumentation: "Parameter docs", currentParameterIndex: 0)]); - } + """, [new SignatureHelpTestItem("System.IAsyncResult SomeDelegate.BeginInvoke(int a, System.AsyncCallback callback, object @object)", parameterDocumentation: "Parameter docs", currentParameterIndex: 0)]); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26713")] - public async Task TestDelegateParameterWithDocumentation_BeginInvoke2() - { - var markup = """ + public Task TestDelegateParameterWithDocumentation_BeginInvoke2() + => TestAsync(""" class C { /// Parameter docs @@ -255,15 +206,11 @@ void M(SomeDelegate theDelegate) [|theDelegate.BeginInvoke(0, $$|]); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("System.IAsyncResult SomeDelegate.BeginInvoke(int a, System.AsyncCallback callback, object @object)", parameterDocumentation: null, currentParameterIndex: 1)]); - } + """, [new SignatureHelpTestItem("System.IAsyncResult SomeDelegate.BeginInvoke(int a, System.AsyncCallback callback, object @object)", parameterDocumentation: null, currentParameterIndex: 1)]); [Fact] - public async Task TestInvocationWithoutClosingParen() - { - var markup = """ + public Task TestInvocationWithoutClosingParen() + => TestAsync(""" class C { void Goo() @@ -271,16 +218,11 @@ void Goo() [|Goo($$ |]} } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void C.Goo()", string.Empty, null, currentParameterIndex: 0)]); - } + """, [new SignatureHelpTestItem("void C.Goo()", string.Empty, null, currentParameterIndex: 0)]); [Fact] - public async Task TestInvocationWithoutClosingParenWithParameters() - { - var markup = - """ + public Task TestInvocationWithoutClosingParenWithParameters() + => TestAsync(""" class C { void Goo(int a, int b) @@ -288,15 +230,11 @@ void Goo(int a, int b) [|Goo($$a, b |]} } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void C.Goo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)]); - } + """, [new SignatureHelpTestItem("void C.Goo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)]); [Fact] - public async Task TestInvocationWithoutClosingParenWithParametersOn2() - { - var markup = """ + public Task TestInvocationWithoutClosingParenWithParametersOn2() + => TestAsync(""" class C { void Goo(int a, int b) @@ -304,15 +242,11 @@ void Goo(int a, int b) [|Goo(a, $$b |]} } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void C.Goo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)]); - } + """, [new SignatureHelpTestItem("void C.Goo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)]); [Fact] - public async Task TestInvocationOnLambda() - { - var markup = """ + public Task TestInvocationOnLambda() + => TestAsync(""" using System; class C @@ -323,15 +257,11 @@ void Goo() [|f($$ |]} } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void Action(int obj)", string.Empty, string.Empty, currentParameterIndex: 0)]); - } + """, [new SignatureHelpTestItem("void Action(int obj)", string.Empty, string.Empty, currentParameterIndex: 0)]); [Fact] - public async Task TestInvocationOnMemberAccessExpression() - { - var markup = """ + public Task TestInvocationOnMemberAccessExpression() + => TestAsync(""" class C { static void Bar(int a) @@ -343,15 +273,11 @@ void Goo() [|C.Bar($$ |]} } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void C.Bar(int a)", string.Empty, string.Empty, currentParameterIndex: 0)]); - } + """, [new SignatureHelpTestItem("void C.Bar(int a)", string.Empty, string.Empty, currentParameterIndex: 0)]); [Fact] - public async Task TestExtensionMethod1() - { - var markup = """ + public Task TestExtensionMethod1() + => TestAsync(""" using System; class C @@ -370,16 +296,11 @@ public static int ExtensionMethod(this string s, int x) return s.Length; } } - """; - - // TODO: Once we do the work to allow extension methods in nested types, we should change this. - await TestAsync(markup, [new SignatureHelpTestItem($"({CSharpFeaturesResources.extension}) int string.ExtensionMethod(int x)", string.Empty, string.Empty, currentParameterIndex: 0)], sourceCodeKind: SourceCodeKind.Regular); - } + """, [new SignatureHelpTestItem($"({CSharpFeaturesResources.extension}) int string.ExtensionMethod(int x)", string.Empty, string.Empty, currentParameterIndex: 0)], sourceCodeKind: SourceCodeKind.Regular); [Fact] - public async Task TestOptionalParameters() - { - var markup = """ + public Task TestOptionalParameters() + => TestAsync(""" class Class1 { void Test() @@ -391,15 +312,11 @@ void Goo(int a = 42) { } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void Class1.Goo([int a = 42])", string.Empty, string.Empty, currentParameterIndex: 0)]); - } + """, [new SignatureHelpTestItem("void Class1.Goo([int a = 42])", string.Empty, string.Empty, currentParameterIndex: 0)]); [Fact] - public async Task TestNoInvocationOnEventNotInCurrentClass() - { - var markup = """ + public Task TestNoInvocationOnEventNotInCurrentClass() + => TestAsync(""" using System; class C @@ -415,15 +332,11 @@ public class D { public event Action evt; } - """; - - await TestAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539712")] - public async Task TestInvocationOnNamedType() - { - var markup = """ + public Task TestInvocationOnNamedType() + => TestAsync(""" class Program { void Main() @@ -442,15 +355,11 @@ public double Goo(double x, double y) return x + y; } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("double C.Goo(double x)", string.Empty, string.Empty, currentParameterIndex: 0)]); - } + """, [new SignatureHelpTestItem("double C.Goo(double x)", string.Empty, string.Empty, currentParameterIndex: 0)]); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539712")] - public async Task TestInvocationOnInstance() - { - var markup = """ + public Task TestInvocationOnInstance() + => TestAsync(""" class Program { void Main() @@ -469,15 +378,11 @@ public double Goo(double x, double y) return x + y; } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("double C.Goo(double x, double y)", string.Empty, string.Empty, currentParameterIndex: 0)]); - } + """, [new SignatureHelpTestItem("double C.Goo(double x, double y)", string.Empty, string.Empty, currentParameterIndex: 0)]); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545118")] - public async Task TestStatic1() - { - var markup = """ + public Task TestStatic1() + => TestAsync(""" class C { static void Goo() @@ -493,15 +398,11 @@ void Bar(int i) { } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void C.Bar()", currentParameterIndex: 0)]); - } + """, [new SignatureHelpTestItem("void C.Bar()", currentParameterIndex: 0)]); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545118")] - public async Task TestStatic2() - { - var markup = """ + public Task TestStatic2() + => TestAsync(""" class C { void Goo() @@ -517,17 +418,13 @@ void Bar(int i) { } } - """; - - await TestAsync(markup, [ + """, [ new SignatureHelpTestItem("void C.Bar()", currentParameterIndex: 0), new SignatureHelpTestItem("void C.Bar(int i)", currentParameterIndex: 0)]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543117")] - public async Task TestInvocationOnAnonymousType() - { - var markup = """ + public Task TestInvocationOnAnonymousType() + => TestAsync(""" using System.Collections.Generic; class Program @@ -542,9 +439,7 @@ static List Goo(T t) { } } - """; - - await TestAsync(markup, [ + """, [ new SignatureHelpTestItem( $$""" void List<'a>.Add('a item) @@ -561,12 +456,10 @@ await TestAsync(markup, [ {{FeaturesResources.Types_colon}} 'a {{FeaturesResources.is_}} new { string Name, int Age } """)]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")] - public async Task TestInvocationOnBaseExpression_ProtectedAccessibility() - { - var markup = """ + public Task TestInvocationOnBaseExpression_ProtectedAccessibility() + => TestAsync(""" using System; public class Base { @@ -585,20 +478,16 @@ protected override void Goo(int x) throw new NotImplementedException(); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem( + """, [new SignatureHelpTestItem( @"void Base.Goo(int x)", methodDocumentation: string.Empty, parameterDocumentation: string.Empty, currentParameterIndex: 0, description: string.Empty)]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")] - public async Task TestInvocationOnBaseExpression_AbstractBase() - { - var markup = """ + public Task TestInvocationOnBaseExpression_AbstractBase() + => TestAsync(""" using System; public abstract class Base { @@ -617,20 +506,16 @@ protected override void Goo(int x) throw new NotImplementedException(); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem( + """, [new SignatureHelpTestItem( @"void Base.Goo(int x)", methodDocumentation: string.Empty, parameterDocumentation: string.Empty, currentParameterIndex: 0, description: string.Empty)]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")] - public async Task TestInvocationOnThisExpression_ProtectedAccessibility() - { - var markup = """ + public Task TestInvocationOnThisExpression_ProtectedAccessibility() + => TestAsync(""" using System; public class Base { @@ -644,20 +529,16 @@ void Test() this.Goo($$); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem( + """, [new SignatureHelpTestItem( @"void Base.Goo(int x)", methodDocumentation: string.Empty, parameterDocumentation: string.Empty, currentParameterIndex: 0, description: string.Empty)]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")] - public async Task TestInvocationOnThisExpression_ProtectedAccessibility_Overridden() - { - var markup = """ + public Task TestInvocationOnThisExpression_ProtectedAccessibility_Overridden() + => TestAsync(""" using System; public class Base { @@ -676,20 +557,16 @@ protected override void Goo(int x) throw new NotImplementedException(); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem( + """, [new SignatureHelpTestItem( @"void Derived.Goo(int x)", methodDocumentation: string.Empty, parameterDocumentation: string.Empty, currentParameterIndex: 0, description: string.Empty)]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")] - public async Task TestInvocationOnThisExpression_ProtectedAccessibility_AbstractBase() - { - var markup = """ + public Task TestInvocationOnThisExpression_ProtectedAccessibility_AbstractBase() + => TestAsync(""" using System; public abstract class Base { @@ -703,20 +580,16 @@ void Test() this.Goo($$); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem( + """, [new SignatureHelpTestItem( @"void Base.Goo(int x)", methodDocumentation: string.Empty, parameterDocumentation: string.Empty, currentParameterIndex: 0, description: string.Empty)]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")] - public async Task TestInvocationOnThisExpression_ProtectedAccessibility_AbstractBase_Overridden() - { - var markup = """ + public Task TestInvocationOnThisExpression_ProtectedAccessibility_AbstractBase_Overridden() + => TestAsync(""" using System; public abstract class Base { @@ -735,20 +608,16 @@ protected override void Goo(int x) throw new NotImplementedException(); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem( + """, [new SignatureHelpTestItem( @"void Derived.Goo(int x)", methodDocumentation: string.Empty, parameterDocumentation: string.Empty, currentParameterIndex: 0, description: string.Empty)]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")] - public async Task TestInvocationOnBaseExpression_ProtectedInternalAccessibility() - { - var markup = """ + public Task TestInvocationOnBaseExpression_ProtectedInternalAccessibility() + => TestAsync(""" using System; public class Base { @@ -767,20 +636,16 @@ protected override void Goo(int x) throw new NotImplementedException(); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem( + """, [new SignatureHelpTestItem( @"void Base.Goo(int x)", methodDocumentation: string.Empty, parameterDocumentation: string.Empty, currentParameterIndex: 0, description: string.Empty)]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")] - public async Task TestInvocationOnBaseMember_ProtectedAccessibility_ThroughType() - { - var markup = """ + public Task TestInvocationOnBaseMember_ProtectedAccessibility_ThroughType() + => TestAsync(""" using System; public class Base { @@ -799,15 +664,11 @@ protected override void Goo(int x) throw new NotImplementedException(); } } - """; - - await TestAsync(markup, null); - } + """, null); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")] - public async Task TestInvocationOnBaseExpression_PrivateAccessibility() - { - var markup = """ + public Task TestInvocationOnBaseExpression_PrivateAccessibility() + => TestAsync(""" using System; public class Base { @@ -826,19 +687,15 @@ protected override void Goo(int x) throw new NotImplementedException(); } } - """; - - await TestAsync(markup, null); - } + """, null); #endregion #region "Current Parameter Name" [Fact] - public async Task TestCurrentParameterName() - { - var markup = """ + public Task TestCurrentParameterName() + => VerifyCurrentParameterNameAsync(""" class C { void Goo(int someParameter, bool something) @@ -846,19 +703,16 @@ void Goo(int someParameter, bool something) Goo(something: false, someParameter: $$) } } - """; - - await VerifyCurrentParameterNameAsync(markup, "someParameter"); - } + """, "someParameter"); #endregion #region "Trigger tests" [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47364")] - public async Task TestInvocationOnTriggerParens_OptionalDefaultStruct() - { - var markup = """ + public Task TestInvocationOnTriggerParens_OptionalDefaultStruct() + => TestAsync( + """ using System; using System.Threading; @@ -871,16 +725,11 @@ static void Main(string[] args) [|SomeMethod($$|]); } } - """; - - await TestAsync( - markup, [new SignatureHelpTestItem("void Program.SomeMethod([CancellationToken token = default])", string.Empty, null, currentParameterIndex: 0)], usePreviousCharAsTrigger: true); - } + """, [new SignatureHelpTestItem("void Program.SomeMethod([CancellationToken token = default])", string.Empty, null, currentParameterIndex: 0)], usePreviousCharAsTrigger: true); [Fact] - public async Task TestInvocationOnTriggerParens() - { - var markup = """ + public Task TestInvocationOnTriggerParens() + => TestAsync(""" class C { void Goo() @@ -888,15 +737,11 @@ void Goo() [|Goo($$|]); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void C.Goo()", string.Empty, null, currentParameterIndex: 0)], usePreviousCharAsTrigger: true); - } + """, [new SignatureHelpTestItem("void C.Goo()", string.Empty, null, currentParameterIndex: 0)], usePreviousCharAsTrigger: true); [Fact] - public async Task TestInvocationOnTriggerComma() - { - var markup = """ + public Task TestInvocationOnTriggerComma() + => TestAsync(""" class C { void Goo(int a, int b) @@ -904,15 +749,11 @@ void Goo(int a, int b) [|Goo(23,$$|]); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void C.Goo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)], usePreviousCharAsTrigger: true); - } + """, [new SignatureHelpTestItem("void C.Goo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)], usePreviousCharAsTrigger: true); [Fact] - public async Task TestNoInvocationOnSpace() - { - var markup = """ + public Task TestNoInvocationOnSpace() + => TestAsync(""" class C { void Goo(int a, int b) @@ -920,15 +761,11 @@ void Goo(int a, int b) [|Goo(23, $$|]); } } - """; - - await TestAsync(markup, usePreviousCharAsTrigger: true); - } + """, usePreviousCharAsTrigger: true); [Fact] - public async Task TestTriggerCharacterInComment01() - { - var markup = """ + public Task TestTriggerCharacterInComment01() + => TestAsync(""" class C { void Goo(int a) @@ -936,14 +773,11 @@ void Goo(int a) Goo(/*,$$*/); } } - """; - await TestAsync(markup, [], usePreviousCharAsTrigger: true); - } + """, [], usePreviousCharAsTrigger: true); [Fact] - public async Task TestTriggerCharacterInComment02() - { - var markup = """ + public Task TestTriggerCharacterInComment02() + => TestAsync(""" class C { void Goo(int a) @@ -952,14 +786,11 @@ void Goo(int a) ); } } - """; - await TestAsync(markup, [], usePreviousCharAsTrigger: true); - } + """, [], usePreviousCharAsTrigger: true); [Fact] - public async Task TestTriggerCharacterInString01() - { - var markup = """ + public Task TestTriggerCharacterInString01() + => TestAsync(""" class C { void Goo(int a) @@ -967,9 +798,7 @@ void Goo(int a) Goo(",$$"); } } - """; - await TestAsync(markup, [], usePreviousCharAsTrigger: true); - } + """, [], usePreviousCharAsTrigger: true); [Fact] public void TestTriggerCharacters() @@ -1550,9 +1379,8 @@ await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, #region "Awaitable tests" [Fact] - public async Task AwaitableMethod() - { - var markup = """ + public Task AwaitableMethod() + => TestSignatureHelpWithMscorlib45Async(""" using System.Threading.Tasks; class C { @@ -1561,15 +1389,11 @@ async Task Goo() [|Goo($$|]); } } - """; - - await TestSignatureHelpWithMscorlib45Async(markup, [new SignatureHelpTestItem($"({CSharpFeaturesResources.awaitable}) Task C.Goo()", methodDocumentation: string.Empty, currentParameterIndex: 0)], "C#"); - } + """, [new SignatureHelpTestItem($"({CSharpFeaturesResources.awaitable}) Task C.Goo()", methodDocumentation: string.Empty, currentParameterIndex: 0)], "C#"); [Fact] - public async Task AwaitableMethod2() - { - var markup = """ + public Task AwaitableMethod2() + => TestSignatureHelpWithMscorlib45Async(""" using System.Threading.Tasks; class C { @@ -1578,17 +1402,13 @@ async Task> Goo() [|Goo($$|]); } } - """; - - await TestSignatureHelpWithMscorlib45Async(markup, [new SignatureHelpTestItem($"({CSharpFeaturesResources.awaitable}) Task> C.Goo()", methodDocumentation: string.Empty, currentParameterIndex: 0)], "C#"); - } + """, [new SignatureHelpTestItem($"({CSharpFeaturesResources.awaitable}) Task> C.Goo()", methodDocumentation: string.Empty, currentParameterIndex: 0)], "C#"); #endregion [Fact, WorkItem(13849, "DevDiv_Projects/Roslyn")] - public async Task TestSpecificity1() - { - var markup = """ + public Task TestSpecificity1() + => TestAsync(""" class Class1 { static void Main() @@ -1605,15 +1425,11 @@ public void M(T t) { } /// Real t public void M(int t) { } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void C.M(int t)", string.Empty, "Real t", currentParameterIndex: 0)]); - } + """, [new SignatureHelpTestItem("void C.M(int t)", string.Empty, "Real t", currentParameterIndex: 0)]); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530017")] - public async Task LongSignature() - { - var markup = """ + public Task LongSignature() + => TestAsync(""" class C { void Goo(string a, string b, string c, string d, string e, string f, string g, string h, string i, string j, string k, string l, string m, string n, string o, string p, string q, string r, string s, string t, string u, string v, string w, string x, string y, string z) @@ -1621,9 +1437,7 @@ void Goo(string a, string b, string c, string d, string e, string f, string g, s [|Goo($$|]) } } - """; - - await TestAsync(markup, [ + """, [ new SignatureHelpTestItem( signature: "void C.Goo(string a, string b, string c, string d, string e, string f, string g, string h, string i, string j, string k, string l, string m, string n, string o, string p, string q, string r, string s, string t, string u, string v, string w, string x, string y, string z)", prettyPrintedSignature: """ @@ -1632,12 +1446,10 @@ void C.Goo(string a, string b, string c, string d, string e, string f, string g, string v, string w, string x, string y, string z) """, currentParameterIndex: 0)]); - } [Fact] - public async Task GenericExtensionMethod() - { - var markup = """ + public Task GenericExtensionMethod() + => TestAsync(""" interface IGoo { void Bar(); @@ -1656,18 +1468,13 @@ static void Main() [|f.Bar($$ |]} } - """; - - // Extension methods are supported in Interactive/Script (yet). - await TestAsync(markup, [ + """, [ new SignatureHelpTestItem("void IGoo.Bar()", currentParameterIndex: 0), new SignatureHelpTestItem($"({CSharpFeaturesResources.extension}) void IGoo.Bar()", currentParameterIndex: 0)], sourceCodeKind: SourceCodeKind.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25830")] - public async Task PickCorrectOverload_PickInt() - { - var markup = """ + public Task PickCorrectOverload_PickInt() + => TestAsync(""" class Program { static void Main() @@ -1677,17 +1484,13 @@ static void Main() static void M(int i) { } static void M(string s) { } } - """; - - await TestAsync(markup, [ + """, [ new SignatureHelpTestItem("void Program.M(int i)", currentParameterIndex: 0, isSelected: true), new SignatureHelpTestItem($"void Program.M(string s)", currentParameterIndex: 0)]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25830")] - public async Task PickCorrectOverload_PickInt_ReverseOrder() - { - var markup = """ + public Task PickCorrectOverload_PickInt_ReverseOrder() + => TestAsync(""" class Program { static void Main() @@ -1697,17 +1500,13 @@ static void Main() static void M(string s) { } static void M(int i) { } } - """; - - await TestAsync(markup, [ + """, [ new SignatureHelpTestItem("void Program.M(int i)", currentParameterIndex: 0, isSelected: true), new SignatureHelpTestItem($"void Program.M(string s)", currentParameterIndex: 0)]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25830")] - public async Task PickCorrectOverload_PickSecond() - { - var markup = """ + public Task PickCorrectOverload_PickSecond() + => TestAsync(""" class Program { static void Main() @@ -1717,17 +1516,13 @@ static void Main() static void M(int i) { } static void M(string s) { } } - """; - - await TestAsync(markup, [ + """, [ new SignatureHelpTestItem("void Program.M(int i)", currentParameterIndex: 0), new SignatureHelpTestItem($"void Program.M(string s)", currentParameterIndex: 0, isSelected: true)]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25830")] - public async Task PickCorrectOverload_OtherName_PickIntRemaining() - { - var markup = """ + public Task PickCorrectOverload_OtherName_PickIntRemaining() + => TestAsync(""" class D { static void Main() @@ -1738,17 +1533,13 @@ static void M(D filtered) { } static void M(int i) { } static void M(string i) { } } - """; - - await TestAsync(markup, [ + """, [ new SignatureHelpTestItem("void D.M(int i)", currentParameterIndex: 0, isSelected: true), new SignatureHelpTestItem("void D.M(string i)", currentParameterIndex: 0)]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25830")] - public async Task PickCorrectOverload_OtherName_PickIntRemaining_ConversionToD() - { - var markup = """ + public Task PickCorrectOverload_OtherName_PickIntRemaining_ConversionToD() + => TestAsync(""" class D { static void Main() @@ -1760,17 +1551,13 @@ static void M(int i) { } static void M(string i) { } static implicit operator D(int i) => throw null; } - """; - - await TestAsync(markup, [ + """, [ new SignatureHelpTestItem("void D.M(int i)", currentParameterIndex: 0, isSelected: true), new SignatureHelpTestItem("void D.M(string i)", currentParameterIndex: 0)]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25830")] - public async Task PickCorrectOverload_OtherName_PickIntRemaining_ReversedOrder() - { - var markup = """ + public Task PickCorrectOverload_OtherName_PickIntRemaining_ReversedOrder() + => TestAsync(""" class D { static void Main() @@ -1781,17 +1568,13 @@ static void M(string i) { } static void M(int i) { } static void M(D filtered) { } } - """; - - await TestAsync(markup, [ + """, [ new SignatureHelpTestItem("void D.M(int i)", currentParameterIndex: 0, isSelected: true), new SignatureHelpTestItem("void D.M(string i)", currentParameterIndex: 0)]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25830")] - public async Task PickCorrectOverload_OtherName_PickStringRemaining() - { - var markup = """ + public Task PickCorrectOverload_OtherName_PickStringRemaining() + => TestAsync(""" class D { static void Main() @@ -1802,17 +1585,13 @@ static void M(D filtered) { } static void M(int i) { } static void M(string i) { } } - """; - - await TestAsync(markup, [ + """, [ new SignatureHelpTestItem("void D.M(int i)", currentParameterIndex: 0), new SignatureHelpTestItem("void D.M(string i)", currentParameterIndex: 0, isSelected: true)]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25830")] - public async Task PickCorrectOverload_RefKind() - { - var markup = """ + public Task PickCorrectOverload_RefKind() + => TestAsync(""" class D { static void Main() @@ -1823,12 +1602,9 @@ static void Main() static void M(ref int a, int i) { } static void M(out int b, int i) { } } - """; - - await TestAsync(markup, [ + """, [ new SignatureHelpTestItem("void D.M(ref int a, int i)", currentParameterIndex: 0), new SignatureHelpTestItem("void D.M(out int b, int i)", currentParameterIndex: 0, isSelected: true)]); - } [Theory] [InlineData("1$$", 0)] @@ -1975,9 +1751,8 @@ void M(int i1, params int[] i2) { } } [Fact] - public async Task PickCorrectOverload_Params_NonArrayType() - { - var source = """ + public Task PickCorrectOverload_Params_NonArrayType() + => TestAsync(""" class Program { void Main() @@ -1986,15 +1761,11 @@ void Main() } void M(int i1, params int i2) { } } - """; - - await TestAsync(source, [new SignatureHelpTestItem("void Program.M(int i1, params int i2)", currentParameterIndex: 1, isSelected: true)]); - } + """, [new SignatureHelpTestItem("void Program.M(int i1, params int i2)", currentParameterIndex: 1, isSelected: true)]); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/6713")] - public async Task PickCorrectOverload_Incomplete_OutOfPositionArgument() - { - var markup = """ + public Task PickCorrectOverload_Incomplete_OutOfPositionArgument() + => TestAsync(""" class Program { static void Main() @@ -2003,11 +1774,7 @@ static void Main() } static void M(string s1, string s2, string s3) { } } - """; - - // The first unspecified parameter (s2) is selected - await TestAsync(markup, [new SignatureHelpTestItem($"void Program.M(string s1, string s2, string s3)", currentParameterIndex: 1, isSelected: true)]); - } + """, [new SignatureHelpTestItem($"void Program.M(string s1, string s2, string s3)", currentParameterIndex: 1, isSelected: true)]); [Theory] [InlineData("i: 1", 0)] @@ -2031,9 +1798,8 @@ static void M(string s, string s2) { } } [Fact] - public async Task TestInvocationWithCrefXmlComments() - { - var markup = """ + public Task TestInvocationWithCrefXmlComments() + => TestAsync(""" class C { /// @@ -2046,15 +1812,11 @@ void Goo() void Bar() { } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void C.Goo()", "Summary for goo. See method C.Bar()", null, currentParameterIndex: 0)]); - } + """, [new SignatureHelpTestItem("void C.Goo()", "Summary for goo. See method C.Bar()", null, currentParameterIndex: 0)]); [Fact] - public async Task FieldUnavailableInOneLinkedFile() - { - var markup = """ + public Task FieldUnavailableInOneLinkedFile() + => VerifyItemWithReferenceWorkerAsync(""" - """; - - await VerifyItemWithReferenceWorkerAsync(markup, [new SignatureHelpTestItem($""" + """, [new SignatureHelpTestItem($""" void C.bar() {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} @@ -2087,12 +1847,10 @@ void C.bar() {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} """, currentParameterIndex: 0)], hideAdvancedMembers: false); - } [Fact] - public async Task ExcludeFilesWithInactiveRegions() - { - var markup = """ + public Task ExcludeFilesWithInactiveRegions() + => VerifyItemWithReferenceWorkerAsync(""" - """; - - await VerifyItemWithReferenceWorkerAsync(markup, [new SignatureHelpTestItem($""" + """, [new SignatureHelpTestItem($""" void C.bar() {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} @@ -2131,12 +1887,10 @@ void C.bar() {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} """, currentParameterIndex: 0)], hideAdvancedMembers: false); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768697")] - public async Task InstanceAndStaticMethodsShown1() - { - var markup = """ + public Task InstanceAndStaticMethodsShown1() + => TestAsync(""" class C { Goo Goo; @@ -2152,17 +1906,13 @@ class Goo public void Bar(int x) { } public static void Bar(string s) { } } - """; - - await TestAsync(markup, [ + """, [ new SignatureHelpTestItem("void Goo.Bar(int x)", currentParameterIndex: 0), new SignatureHelpTestItem("void Goo.Bar(string s)", currentParameterIndex: 0)]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768697")] - public async Task InstanceAndStaticMethodsShown2() - { - var markup = """ + public Task InstanceAndStaticMethodsShown2() + => TestAsync(""" class C { Goo Goo; @@ -2178,17 +1928,13 @@ class Goo public void Bar(int x) { } public static void Bar(string s) { } } - """; - - await TestAsync(markup, [ + """, [ new SignatureHelpTestItem("void Goo.Bar(int x)", currentParameterIndex: 0), new SignatureHelpTestItem("void Goo.Bar(string s)", currentParameterIndex: 0)]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768697")] - public async Task InstanceAndStaticMethodsShown3() - { - var markup = """ + public Task InstanceAndStaticMethodsShown3() + => TestAsync(""" class C { Goo Goo; @@ -2204,17 +1950,13 @@ class Goo public static void Bar(int x) { } public static void Bar(string s) { } } - """; - - await TestAsync(markup, [ + """, [ new SignatureHelpTestItem("void Goo.Bar(int x)", currentParameterIndex: 0), new SignatureHelpTestItem("void Goo.Bar(string s)", currentParameterIndex: 0)]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768697")] - public async Task InstanceAndStaticMethodsShown4() - { - var markup = """ + public Task InstanceAndStaticMethodsShown4() + => TestAsync(""" class C { void M() @@ -2229,15 +1971,11 @@ class Goo public static void Bar(int x) { } public static void Bar(string s) { } } - """; - - await TestAsync(markup, []); - } + """, []); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768697")] - public async Task InstanceAndStaticMethodsShown5() - { - var markup = """ + public Task InstanceAndStaticMethodsShown5() + => TestAsync(""" class C { void M() @@ -2252,15 +1990,11 @@ class Goo public static void Bar(int x) { } public static void Bar(string s) { } } - """; - - await TestAsync(markup, []); - } + """, []); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33549")] - public async Task ShowOnlyStaticMethodsForBuildInTypes() - { - var markup = """ + public Task ShowOnlyStaticMethodsForBuildInTypes() + => TestAsync(""" class C { void M() @@ -2268,18 +2002,14 @@ void M() string.Equals($$ } } - """; - - await TestAsync(markup, [ + """, [ new SignatureHelpTestItem("bool object.Equals(object objA, object objB)"), new SignatureHelpTestItem("bool string.Equals(string a, string b)"), new SignatureHelpTestItem("bool string.Equals(string a, string b, System.StringComparison comparisonType)")]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23133")] - public async Task ShowOnlyStaticMethodsForNotImportedTypes() - { - var markup = """ + public Task ShowOnlyStaticMethodsForNotImportedTypes() + => TestAsync(""" class C { void M() @@ -2295,25 +2025,17 @@ public void Bar(int x) { } public static void Bar(string s) { } } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void Test.Goo.Bar(string s)")]); - } + """, [new SignatureHelpTestItem("void Test.Goo.Bar(string s)")]); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")] - public async Task InvokedWithNoToken() - { - var markup = """ + public Task InvokedWithNoToken() + => TestAsync(""" // goo($$ - """; - - await TestAsync(markup); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task MethodOverloadDifferencesIgnored() - { - var markup = """ + public Task MethodOverloadDifferencesIgnored() + => VerifyItemWithReferenceWorkerAsync(""" - """; - - await VerifyItemWithReferenceWorkerAsync(markup, [new SignatureHelpTestItem($""" + """, [new SignatureHelpTestItem($""" void C.Do(int x) {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} @@ -2346,13 +2066,11 @@ void C.Do(int x) {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} """, currentParameterIndex: 0)], hideAdvancedMembers: false); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/699")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068424")] - public async Task TestGenericParameters1() - { - var markup = """ + public Task TestGenericParameters1() + => TestAsync(""" class C { void M() @@ -2363,18 +2081,14 @@ void M() void Goo(T a) { } void Goo(T a, U b) { } } - """; - - await TestAsync(markup, [ + """, [ new SignatureHelpTestItem("void C.Goo(string a)", string.Empty, string.Empty, currentParameterIndex: 0), new SignatureHelpTestItem("void C.Goo(T a, U b)", string.Empty)]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/699")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068424")] - public async Task TestGenericParameters2() - { - var markup = """ + public Task TestGenericParameters2() + => TestAsync(""" class C { void M() @@ -2385,17 +2099,13 @@ void M() void Goo(T a) { } void Goo(T a, U b) { } } - """; - - await TestAsync(markup, [ + """, [ new SignatureHelpTestItem("void C.Goo(T a)", string.Empty), new SignatureHelpTestItem("void C.Goo(T a, U b)", string.Empty, string.Empty, currentParameterIndex: 1)]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4144")] - public async Task TestSigHelpIsVisibleOnInaccessibleItem() - { - var markup = """ + public Task TestSigHelpIsVisibleOnInaccessibleItem() + => TestAsync(""" using System.Collections.Generic; class A @@ -2410,15 +2120,11 @@ void M() args.Add($$ } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void List.Add(int item)")]); - } + """, [new SignatureHelpTestItem("void List.Add(int item)")]); [Fact] - public async Task TypingTupleDoesNotDismiss1() - { - var markup = """ + public Task TypingTupleDoesNotDismiss1() + => TestAsync(""" class C { int Goo(object x) @@ -2426,15 +2132,11 @@ int Goo(object x) [|Goo(($$)|]; } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("int C.Goo(object x)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); - } + """, [new SignatureHelpTestItem("int C.Goo(object x)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); [Fact] - public async Task TypingTupleDoesNotDismiss2() - { - var markup = """ + public Task TypingTupleDoesNotDismiss2() + => TestAsync(""" class C { int Goo(object x) @@ -2442,15 +2144,11 @@ int Goo(object x) [|Goo((1,$$)|]; } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("int C.Goo(object x)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); - } + """, [new SignatureHelpTestItem("int C.Goo(object x)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); [Fact] - public async Task TypingTupleDoesNotDismiss3() - { - var markup = """ + public Task TypingTupleDoesNotDismiss3() + => TestAsync(""" class C { int Goo(object x) @@ -2458,15 +2156,11 @@ int Goo(object x) [|Goo((1, ($$)|]; } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("int C.Goo(object x)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); - } + """, [new SignatureHelpTestItem("int C.Goo(object x)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); [Fact] - public async Task TypingTupleDoesNotDismiss4() - { - var markup = """ + public Task TypingTupleDoesNotDismiss4() + => TestAsync(""" class C { int Goo(object x) @@ -2474,15 +2168,11 @@ int Goo(object x) [|Goo((1, (2,$$)|]; } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("int C.Goo(object x)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); - } + """, [new SignatureHelpTestItem("int C.Goo(object x)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); [Fact] - public async Task PickCorrectOverload_WithCorrectSelectionAfterFilteringOutNoApplicableItems() - { - var markup = """ + public Task PickCorrectOverload_WithCorrectSelectionAfterFilteringOutNoApplicableItems() + => TestAsync(""" class Comparer { public static bool Equals(object x, object y) => true; @@ -2498,18 +2188,14 @@ static void Main(string x, string y) comparer.Equals(x, y$$); } } - """; - - await TestAsync(markup, [ + """, [ new SignatureHelpTestItem("bool Comparer.Equals(object x)", currentParameterIndex: 1), new SignatureHelpTestItem("bool Comparer.Equals(string x, string y)", currentParameterIndex: 1, isSelected: true)]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38074")] [CompilerTrait(CompilerFeature.LocalFunctions)] - public async Task TestLocalFunction() - { - var markup = """ + public Task TestLocalFunction() + => TestAsync(""" class C { void M() @@ -2518,16 +2204,12 @@ void Local() { } Local($$); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void Local()")]); - } + """, [new SignatureHelpTestItem("void Local()")]); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38074")] [CompilerTrait(CompilerFeature.LocalFunctions)] - public async Task TestLocalFunctionInStaticMethod() - { - var markup = """ + public Task TestLocalFunctionInStaticMethod() + => TestAsync(""" class C { static void M() @@ -2536,16 +2218,12 @@ void Local() { } Local($$); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("void Local()")]); - } + """, [new SignatureHelpTestItem("void Local()")]); [Fact] [CompilerTrait(CompilerFeature.FunctionPointers)] - public async Task TestFunctionPointer() - { - var markup = """ + public Task TestFunctionPointer() + => TestAsync(""" class C { unsafe static void M() @@ -2554,16 +2232,12 @@ unsafe static void M() functionPointer($$); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("int delegate*(int)", currentParameterIndex: 0)]); - } + """, [new SignatureHelpTestItem("int delegate*(int)", currentParameterIndex: 0)]); [Fact] [CompilerTrait(CompilerFeature.FunctionPointers)] - public async Task TestFunctionPointerMultipleArguments() - { - var markup = """ + public Task TestFunctionPointerMultipleArguments() + => TestAsync(""" class C { unsafe static void M() @@ -2572,39 +2246,11 @@ unsafe static void M() functionPointer("", $$); } } - """; - - await TestAsync(markup, [new SignatureHelpTestItem("int delegate*(string, long)", currentParameterIndex: 1)]); - } + """, [new SignatureHelpTestItem("int delegate*(string, long)", currentParameterIndex: 1)]); [Theory, CombinatorialData] public async Task ShowWarningForOverloadUnavailableInRelatedDocument(bool typeParameterProvided) { - var markup = $$""" - - - false; - #if TFM - public void M(Action arg1, T arg2, bool flag) => false; - #endif - - void goo() - { - M{{(typeParameterProvided ? "" : string.Empty)}}($$ - } - } - ]]> - - - - - - - """; - var expectedItems = new List(); if (typeParameterProvided) @@ -2632,13 +2278,36 @@ void C.M(Action arg1, T arg2, bool flag) """, currentParameterIndex: 0)); } - await VerifyItemWithReferenceWorkerAsync(markup, expectedItems, hideAdvancedMembers: false); + await VerifyItemWithReferenceWorkerAsync($$""" + + + false; + #if TFM + public void M(Action arg1, T arg2, bool flag) => false; + #endif + + void goo() + { + M{{(typeParameterProvided ? "" : string.Empty)}}($$ + } + } + ]]> + + + + + + + """, expectedItems, hideAdvancedMembers: false); } [Fact] - public async Task TestLightweightOverloadResolution1() - { - var markup = """ + public Task TestLightweightOverloadResolution1() + => TestAsync( + """ class C : IResource { } @@ -2666,17 +2335,13 @@ public interface IResource } public interface IResourceBuilder where T : IResource { } - """; - - await TestAsync( - markup, [new SignatureHelpTestItem($"({CSharpFeaturesResources.extension}) IResourceBuilder IResourceBuilder.WithServiceBinding(int containerPort, [int? hostPort = null], [string? scheme = null], [string? name = null], [string? env = null])", currentParameterIndex: 0)], + """, [new SignatureHelpTestItem($"({CSharpFeaturesResources.extension}) IResourceBuilder IResourceBuilder.WithServiceBinding(int containerPort, [int? hostPort = null], [string? scheme = null], [string? name = null], [string? env = null])", currentParameterIndex: 0)], sourceCodeKind: SourceCodeKind.Regular); - } [Fact] - public async Task TestLightweightOverloadResolution2() - { - var markup = """ + public Task TestLightweightOverloadResolution2() + => TestAsync( + """ class C : IResource { } @@ -2705,10 +2370,6 @@ public interface IResource } public interface IResourceBuilder where T : IResource { } - """; - - await TestAsync( - markup, [new SignatureHelpTestItem($"({CSharpFeaturesResources.extension}) IResourceBuilder IResourceBuilder.WithServiceBinding(int containerPort, [int? hostPort = null], [string? scheme = null], [string? name = null], [string? env = null])", currentParameterIndex: 0)], + """, [new SignatureHelpTestItem($"({CSharpFeaturesResources.extension}) IResourceBuilder IResourceBuilder.WithServiceBinding(int containerPort, [int? hostPort = null], [string? scheme = null], [string? name = null], [string? env = null])", currentParameterIndex: 0)], sourceCodeKind: SourceCodeKind.Regular); - } } diff --git a/src/EditorFeatures/CSharpTest/SignatureHelp/ObjectCreationExpressionSignatureHelpProviderTests.cs b/src/EditorFeatures/CSharpTest/SignatureHelp/ObjectCreationExpressionSignatureHelpProviderTests.cs index 45faed92ed894..875112d1290cb 100644 --- a/src/EditorFeatures/CSharpTest/SignatureHelp/ObjectCreationExpressionSignatureHelpProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/SignatureHelp/ObjectCreationExpressionSignatureHelpProviderTests.cs @@ -24,9 +24,8 @@ internal override Type GetSignatureHelpProviderType() #region "Regular tests" [Fact] - public async Task TestInvocationWithoutParameters() - { - var markup = """ + public Task TestInvocationWithoutParameters() + => TestAsync(""" class C { void goo() @@ -34,15 +33,11 @@ void goo() var c = [|new C($$|]); } } - """; - - await TestAsync(markup, [new("C()", string.Empty, null, currentParameterIndex: 0)]); - } + """, [new("C()", string.Empty, null, currentParameterIndex: 0)]); [Fact] - public async Task TestImplicitInvocationWithoutParameters() - { - var markup = """ + public Task TestImplicitInvocationWithoutParameters() + => TestAsync(""" - """; - - await TestAsync(markup, [new("C()", string.Empty, null, currentParameterIndex: 0)]); - } + """, [new("C()", string.Empty, null, currentParameterIndex: 0)]); [Fact] - public async Task TestInvocationWithoutParametersMethodXmlComments() - { - var markup = """ + public Task TestInvocationWithoutParametersMethodXmlComments() + => TestAsync(""" class C { /// @@ -77,15 +68,11 @@ void Goo() C c = [|new C($$|]); } } - """; - - await TestAsync(markup, [new("C()", "Summary for C", null, currentParameterIndex: 0)]); - } + """, [new("C()", "Summary for C", null, currentParameterIndex: 0)]); [Fact] - public async Task TestInvocationWithParametersOn1() - { - var markup = """ + public Task TestInvocationWithParametersOn1() + => TestAsync(""" class C { C(int a, int b) { } @@ -95,15 +82,11 @@ void Goo() C c = [|new C($$2, 3|]); } } - """; - - await TestAsync(markup, [new("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)]); - } + """, [new("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)]); [Fact] - public async Task TestImplicitInvocationWithParametersOn1() - { - var markup = """ + public Task TestImplicitInvocationWithParametersOn1() + => TestAsync(""" class C { C(int a, int b) { } @@ -113,15 +96,11 @@ void M() C c = [|new($$2, 3|]); } } - """; - - await TestAsync(markup, [new("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)]); - } + """, [new("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)]); [Fact] - public async Task TestInvocationWithParametersXmlCommentsOn1() - { - var markup = """ + public Task TestInvocationWithParametersXmlCommentsOn1() + => TestAsync(""" class C { /// @@ -136,15 +115,11 @@ void Goo() C c = [|new C($$2, 3|]); } } - """; - - await TestAsync(markup, [new("C(int a, int b)", "Summary for C", "Param a", currentParameterIndex: 0)]); - } + """, [new("C(int a, int b)", "Summary for C", "Param a", currentParameterIndex: 0)]); [Fact] - public async Task TestInvocationWithParametersOn2() - { - var markup = """ + public Task TestInvocationWithParametersOn2() + => TestAsync(""" class C { C(int a, int b) { } @@ -154,15 +129,11 @@ void Goo() C c = [|new C(2, $$3|]); } } - """; - - await TestAsync(markup, [new("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)]); - } + """, [new("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)]); [Fact] - public async Task TestInvocationWithParametersXmlComentsOn2() - { - var markup = """ + public Task TestInvocationWithParametersXmlComentsOn2() + => TestAsync(""" class C { /// @@ -177,15 +148,11 @@ void Goo() C c = [|new C(2, $$3|]); } } - """; - - await TestAsync(markup, [new("C(int a, int b)", "Summary for C", "Param b", currentParameterIndex: 1)]); - } + """, [new("C(int a, int b)", "Summary for C", "Param b", currentParameterIndex: 1)]); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25830")] - public async Task PickCorrectOverload_PickFirst() - { - var markup = """ + public Task PickCorrectOverload_PickFirst() + => TestAsync(""" class D { void M() @@ -196,17 +163,13 @@ void M() D(string i) => throw null; D(int i) => throw null; } - """; - - await TestAsync(markup, [ + """, [ new("D(int i)", currentParameterIndex: 0, isSelected: true), new("D(string i)", currentParameterIndex: 0),]); - } [Fact] - public async Task PickCorrectOverload_PickFirst_ImplicitObjectCreation() - { - var markup = """ + public Task PickCorrectOverload_PickFirst_ImplicitObjectCreation() + => TestAsync(""" class D { void M() @@ -217,17 +180,13 @@ void M() D(string i) => throw null; D(int i) => throw null; } - """; - - await TestAsync(markup, [ + """, [ new("D(int i)", currentParameterIndex: 0, isSelected: true), new("D(string i)", currentParameterIndex: 0),]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25830")] - public async Task PickCorrectOverload_PickSecond() - { - var markup = """ + public Task PickCorrectOverload_PickSecond() + => TestAsync(""" class D { void M() @@ -238,17 +197,13 @@ void M() D(string i) => throw null; D(int i) => throw null; } - """; - - await TestAsync(markup, [ + """, [ new("D(int i)", currentParameterIndex: 0), new("D(string i)", currentParameterIndex: 0, isSelected: true),]); - } [Fact] - public async Task PickCorrectOverload_PickSecond_ImplicitObjectCreation() - { - var markup = """ + public Task PickCorrectOverload_PickSecond_ImplicitObjectCreation() + => TestAsync(""" class D { void M() @@ -259,17 +214,13 @@ void M() D(string i) => throw null; D(int i) => throw null; } - """; - - await TestAsync(markup, [ + """, [ new("D(int i)", currentParameterIndex: 0), new("D(string i)", currentParameterIndex: 0, isSelected: true),]); - } [Fact] - public async Task TestInvocationWithoutClosingParen() - { - var markup = """ + public Task TestInvocationWithoutClosingParen() + => TestAsync(""" class C { void goo() @@ -277,15 +228,11 @@ void goo() var c = [|new C($$ |]} } - """; - - await TestAsync(markup, [new("C()", string.Empty, null, currentParameterIndex: 0)]); - } + """, [new("C()", string.Empty, null, currentParameterIndex: 0)]); [Fact] - public async Task TestInvocationWithoutClosingParenWithParameters() - { - var markup = """ + public Task TestInvocationWithoutClosingParenWithParameters() + => TestAsync(""" class C { C(int a, int b) { } @@ -295,15 +242,11 @@ void Goo() C c = [|new C($$2, 3 |]} } - """; - - await TestAsync(markup, [new("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)]); - } + """, [new("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)]); [Fact] - public async Task TestInvocationWithoutClosingParenWithParametersOn2() - { - var markup = """ + public Task TestInvocationWithoutClosingParenWithParametersOn2() + => TestAsync(""" class C { C(int a, int b) { } @@ -313,15 +256,11 @@ void Goo() C c = [|new C(2, $$3 |]} } - """; - - await TestAsync(markup, [new("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)]); - } + """, [new("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)]); [Fact] - public async Task TestInvocationOnLambda() - { - var markup = """ + public Task TestInvocationOnLambda() + => TestAsync(""" using System; class C @@ -331,19 +270,15 @@ void goo() var bar = [|new Action($$ |]} } - """; - - await TestAsync(markup, [new("Action(void (int, int) target)", string.Empty, string.Empty, currentParameterIndex: 0, isSelected: true)]); - } + """, [new("Action(void (int, int) target)", string.Empty, string.Empty, currentParameterIndex: 0, isSelected: true)]); #endregion #region "Current Parameter Name" [Fact] - public async Task TestCurrentParameterName() - { - var markup = """ + public Task TestCurrentParameterName() + => VerifyCurrentParameterNameAsync(""" class C { C(int a, string b) @@ -355,19 +290,15 @@ void goo() var c = [|new C(b: string.Empty, $$a: 2|]); } } - """; - - await VerifyCurrentParameterNameAsync(markup, "a"); - } + """, "a"); #endregion #region "Trigger tests" [Fact] - public async Task TestInvocationOnTriggerParens() - { - var markup = """ + public Task TestInvocationOnTriggerParens() + => TestAsync(""" class C { void goo() @@ -375,15 +306,11 @@ void goo() var c = [|new C($$|]); } } - """; - - await TestAsync(markup, [new("C()", string.Empty, null, currentParameterIndex: 0)], usePreviousCharAsTrigger: true); - } + """, [new("C()", string.Empty, null, currentParameterIndex: 0)], usePreviousCharAsTrigger: true); [Fact] - public async Task TestInvocationOnTriggerComma() - { - var markup = """ + public Task TestInvocationOnTriggerComma() + => TestAsync(""" class C { C(int a, string b) @@ -395,15 +322,11 @@ void goo() var c = [|new C(2,$$string.Empty|]); } } - """; - - await TestAsync(markup, [new("C(int a, string b)", string.Empty, string.Empty, currentParameterIndex: 1)], usePreviousCharAsTrigger: true); - } + """, [new("C(int a, string b)", string.Empty, string.Empty, currentParameterIndex: 1)], usePreviousCharAsTrigger: true); [Fact] - public async Task TestNoInvocationOnSpace() - { - var markup = """ + public Task TestNoInvocationOnSpace() + => TestAsync(""" class C { C(int a, string b) @@ -415,10 +338,7 @@ void goo() var c = [|new C(2, $$string.Empty|]); } } - """; - - await TestAsync(markup, expectedOrderedItemsOrNull: [], usePreviousCharAsTrigger: true); - } + """, expectedOrderedItemsOrNull: [], usePreviousCharAsTrigger: true); [Fact] public void TestTriggerCharacters() @@ -587,9 +507,9 @@ await TestSignatureHelpInEditorBrowsableContextsAsync( #endregion [Fact] - public async Task FieldUnavailableInOneLinkedFile() - { - var markup = """ + public Task FieldUnavailableInOneLinkedFile() + => VerifyItemWithReferenceWorkerAsync( + """ - """; - - await VerifyItemWithReferenceWorkerAsync( - markup, [new($""" + """, [new($""" D() {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} @@ -623,12 +540,11 @@ await VerifyItemWithReferenceWorkerAsync( {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} """, currentParameterIndex: 0)], false); - } [Fact] - public async Task ExcludeFilesWithInactiveRegions() - { - var markup = """ + public Task ExcludeFilesWithInactiveRegions() + => VerifyItemWithReferenceWorkerAsync( + """ - """; - - await VerifyItemWithReferenceWorkerAsync( - markup, [new($""" + """, [new($""" D() {string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)} @@ -668,22 +581,16 @@ await VerifyItemWithReferenceWorkerAsync( {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts} """, currentParameterIndex: 0)], false); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")] - public async Task InvokedWithNoToken() - { - var markup = """ + public Task InvokedWithNoToken() + => TestAsync(""" // new goo($$ - """; - - await TestAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078993")] - public async Task TestSigHelpInIncorrectObjectCreationExpression() - { - var markup = """ + public Task TestSigHelpInIncorrectObjectCreationExpression() + => TestAsync(""" class C { void goo(C c) @@ -691,15 +598,11 @@ void goo(C c) goo([|new C{$$|] } } - """; - - await TestAsync(markup); - } + """); [Fact] - public async Task TypingTupleDoesNotDismiss1() - { - var markup = """ + public Task TypingTupleDoesNotDismiss1() + => TestAsync(""" class C { public C(object o) { } @@ -709,15 +612,11 @@ public C M() |]} } - """; - - await TestAsync(markup, [new("C(object o)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); - } + """, [new("C(object o)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); [Fact] - public async Task TypingTupleDoesNotDismiss2() - { - var markup = """ + public Task TypingTupleDoesNotDismiss2() + => TestAsync(""" class C { public C(object o) { } @@ -727,15 +626,11 @@ public C M() |]} } - """; - - await TestAsync(markup, [new("C(object o)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); - } + """, [new("C(object o)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); [Fact] - public async Task TypingTupleDoesNotDismiss3() - { - var markup = """ + public Task TypingTupleDoesNotDismiss3() + => TestAsync(""" class C { public C(object o) { } @@ -745,15 +640,11 @@ public C M() |]} } - """; - - await TestAsync(markup, [new("C(object o)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); - } + """, [new("C(object o)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); [Fact] - public async Task TypingTupleDoesNotDismiss4() - { - var markup = """ + public Task TypingTupleDoesNotDismiss4() + => TestAsync(""" class C { public C(object o) { } @@ -763,10 +654,7 @@ public C M() |]} } - """; - - await TestAsync(markup, [new("C(object o)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); - } + """, [new("C(object o)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); [Theory] [InlineData("1$$", 0, 0)] @@ -829,9 +717,8 @@ await TestAsync(markup.Replace("ARGUMENTS", arguments), } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70235")] - public async Task ProtectedConstructor1() - { - var markup = """ + public Task ProtectedConstructor1() + => TestAsync(""" public class Derived:BaseClass { public void Do() @@ -845,17 +732,13 @@ public class BaseClass public BaseClass(int val) { } protected BaseClass(int val, int val1) { } } - """; - - await TestAsync(markup, + """, [new SignatureHelpTestItem("BaseClass(int val)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70235")] - public async Task ProtectedConstructor2() - { - var markup = """ + public Task ProtectedConstructor2() + => TestAsync(""" public class BaseClass { public BaseClass(int val) { } @@ -869,19 +752,15 @@ public void Do() } } } - """; - - await TestAsync(markup, [ + """, [ new SignatureHelpTestItem("BaseClass(int val)", currentParameterIndex: 0), new SignatureHelpTestItem("BaseClass(int val, int val1)", currentParameterIndex: 0), ], usePreviousCharAsTrigger: true); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70235")] - public async Task ProtectedConstructor3() - { - var markup = """ + public Task ProtectedConstructor3() + => TestAsync(""" public class BaseClass { public BaseClass(int val) { } @@ -892,12 +771,9 @@ public void Do() var baseInstance = new BaseClass($$); } } - """; - - await TestAsync(markup, [ + """, [ new SignatureHelpTestItem("BaseClass(int val)", currentParameterIndex: 0), new SignatureHelpTestItem("BaseClass(int val, int val1)", currentParameterIndex: 0), ], usePreviousCharAsTrigger: true); - } } diff --git a/src/EditorFeatures/CSharpTest/SignatureHelp/PrimaryConstructorBaseTypeSignatureHelpProviderTests.cs b/src/EditorFeatures/CSharpTest/SignatureHelp/PrimaryConstructorBaseTypeSignatureHelpProviderTests.cs index 2a6cebd5a3577..818091b8b8272 100644 --- a/src/EditorFeatures/CSharpTest/SignatureHelp/PrimaryConstructorBaseTypeSignatureHelpProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/SignatureHelp/PrimaryConstructorBaseTypeSignatureHelpProviderTests.cs @@ -5,10 +5,8 @@ #nullable disable using System; -using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.SignatureHelp; -using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; @@ -22,107 +20,82 @@ internal override Type GetSignatureHelpProviderType() => typeof(PrimaryConstructorBaseTypeSignatureHelpProvider); [Fact] - public async Task PrimaryConstructorBaseType_FirstParameter() - { - var markup = """ + public Task PrimaryConstructorBaseType_FirstParameter() + => TestAsync(""" record Base(int Identifier) { private Base(string ignored) : this(1, 2) { } } record Derived(int Other) : [|Base($$1|]); - """; - - await TestAsync(markup, [ + """, [ new("Base(Base original)", string.Empty, null, currentParameterIndex: 0), new("Base(int Identifier)", string.Empty, null, currentParameterIndex: 0, isSelected: true)]); - } [Fact] - public async Task PrimaryConstructorClassBaseType_FirstParameter() - { - var markup = """ + public Task PrimaryConstructorClassBaseType_FirstParameter() + => TestAsync(""" class Base(int Identifier) { private Base(string ignored) : this(1, 2) { } } class Derived(int Other) : [|Base($$1|]); - """; - - await TestAsync(markup, [new("Base(int Identifier)", string.Empty, null, currentParameterIndex: 0, isSelected: true)]); - } + """, [new("Base(int Identifier)", string.Empty, null, currentParameterIndex: 0, isSelected: true)]); [Fact] - public async Task PrimaryConstructorBaseType_SecondParameter() - { - var markup = """ + public Task PrimaryConstructorBaseType_SecondParameter() + => TestAsync(""" record Base(int Identifier1, int Identifier2) { protected Base(string name) : this(1, 2) { } } record Derived(int Other) : [|Base(1, $$2|]); - """; - - await TestAsync(markup, [ + """, [ new("Base(Base original)", string.Empty, null, currentParameterIndex: 1), new("Base(string name)", string.Empty, null, currentParameterIndex: 1), new("Base(int Identifier1, int Identifier2)", string.Empty, null, currentParameterIndex: 1, isSelected: true)]); - } [Fact] - public async Task PrimaryConstructorClassBaseType_SecondParameter() - { - var markup = """ + public Task PrimaryConstructorClassBaseType_SecondParameter() + => TestAsync(""" class Base(int Identifier1, int Identifier2) { protected Base(string name) : this(1, 2) { } } class Derived(int Other) : [|Base(1, $$2|]); - """; - - await TestAsync(markup, [ + """, [ new("Base(string name)", string.Empty, null, currentParameterIndex: 1), new("Base(int Identifier1, int Identifier2)", string.Empty, null, currentParameterIndex: 1, isSelected: true)]); - } [Fact] - public async Task CommentOnBaseConstructor() - { - var markup = """ + public Task CommentOnBaseConstructor() + => TestAsync(""" record Base(int Identifier1, int Identifier2) { /// Summary for constructor protected Base(string name) : this(1, 2) { } } record Derived(int Other) : [|Base(1, $$2|]); - """; - - await TestAsync(markup, [ + """, [ new("Base(Base original)", string.Empty, null, currentParameterIndex: 1), new("Base(string name)", "Summary for constructor", null, currentParameterIndex: 1), new("Base(int Identifier1, int Identifier2)", string.Empty, null, currentParameterIndex: 1, isSelected: true)]); - } [Fact] - public async Task CommentOnClassBaseConstructor() - { - var markup = """ + public Task CommentOnClassBaseConstructor() + => TestAsync(""" class Base(int Identifier1, int Identifier2) { /// Summary for constructor protected Base(string name) : this(1, 2) { } } class Derived(int Other) : [|Base(1, $$2|]); - """; - - await TestAsync(markup, [ + """, [ new("Base(string name)", "Summary for constructor", null, currentParameterIndex: 1), new("Base(int Identifier1, int Identifier2)", string.Empty, null, currentParameterIndex: 1, isSelected: true)]); - } [Fact] - public async Task CommentOnBaseConstructorAndParameters() - { - var markup = """ + public Task CommentOnBaseConstructorAndParameters() + => TestAsync(""" record Base(int Identifier1, int Identifier2) { /// Summary for constructor @@ -130,18 +103,14 @@ record Base(int Identifier1, int Identifier2) protected Base(string name) : this(1, 2) { } } record Derived(int Other) : [|Base($$1, 2|]); - """; - - await TestAsync(markup, [ + """, [ new("Base(Base original)", string.Empty, null, currentParameterIndex: 0), new("Base(string name)", "Summary for constructor", "Param name", currentParameterIndex: 0), new("Base(int Identifier1, int Identifier2)", string.Empty, null, currentParameterIndex: 0, isSelected: true)]); - } [Fact] - public async Task CommentOnClassBaseConstructorAndParameters() - { - var markup = """ + public Task CommentOnClassBaseConstructorAndParameters() + => TestAsync(""" class Base(int Identifier1, int Identifier2) { /// Summary for constructor @@ -149,23 +118,16 @@ class Base(int Identifier1, int Identifier2) protected Base(string name) : this(1, 2) { } } class Derived(int Other) : [|Base($$1, 2|]); - """; - - await TestAsync(markup, [ + """, [ new("Base(string name)", "Summary for constructor", "Param name", currentParameterIndex: 0), new("Base(int Identifier1, int Identifier2)", string.Empty, null, currentParameterIndex: 0, isSelected: true)]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70106")] - public async Task PrimaryConstructorBaseType_AbstractBaseType() - { - var markup = """ + public Task PrimaryConstructorBaseType_AbstractBaseType() + => TestAsync(""" abstract class Base(int Identifier) { } class Derived(int Other) : [|Base($$1|]); - """; - - await TestAsync(markup, [new("Base(int Identifier)", string.Empty, null, currentParameterIndex: 0, isSelected: true)]); - } + """, [new("Base(int Identifier)", string.Empty, null, currentParameterIndex: 0, isSelected: true)]); } diff --git a/src/EditorFeatures/CSharpTest/SignatureHelp/TupleConstructionSignatureHelpProviderTests.cs b/src/EditorFeatures/CSharpTest/SignatureHelp/TupleConstructionSignatureHelpProviderTests.cs index a17595a6e197b..1a798833beef1 100644 --- a/src/EditorFeatures/CSharpTest/SignatureHelp/TupleConstructionSignatureHelpProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/SignatureHelp/TupleConstructionSignatureHelpProviderTests.cs @@ -18,35 +18,26 @@ internal override Type GetSignatureHelpProviderType() => typeof(TupleConstructionSignatureHelpProvider); [Fact] - public async Task InvocationAfterOpenParen() - { - var markup = """ + public Task InvocationAfterOpenParen() + => TestAsync(""" class C { (int, int) y = [|($$ |]} - """; - - await TestAsync(markup, [new("(int, int)", currentParameterIndex: 0, parameterDocumentation: "")], usePreviousCharAsTrigger: true); - } + """, [new("(int, int)", currentParameterIndex: 0, parameterDocumentation: "")], usePreviousCharAsTrigger: true); [Fact] - public async Task InvocationWithNullableReferenceTypes() - { - var markup = """ + public Task InvocationWithNullableReferenceTypes() + => TestAsync(""" class C { (string?, string) y = [|($$ |]} - """; - - await TestAsync(markup, [new("(string?, string)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); - } + """, [new("(string?, string)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/655607")] - public async Task TestMissingTupleElement() - { - var markup = """ + public Task TestMissingTupleElement() + => TestAsync(""" class C { void M() @@ -54,136 +45,96 @@ void M() (a, ) = [|($$ |] } } - """; - - await TestAsync(markup, [new("(object a, object)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); - } + """, [new("(object a, object)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); [Fact] - public async Task InvocationAfterOpenParen2() - { - var markup = """ + public Task InvocationAfterOpenParen2() + => TestAsync(""" class C { (int, int) y = [|($$)|] } - """; - - await TestAsync(markup, [new("(int, int)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); - } + """, [new("(int, int)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); [Fact] - public async Task InvocationAfterComma1() - { - var markup = """ + public Task InvocationAfterComma1() + => TestAsync(""" class C { (int, int) y = [|(1,$$ |]} - """; - - await TestAsync(markup, [new("(int, int)", currentParameterIndex: 1, parameterDocumentation: "")], usePreviousCharAsTrigger: true); - } + """, [new("(int, int)", currentParameterIndex: 1, parameterDocumentation: "")], usePreviousCharAsTrigger: true); [Fact] - public async Task InvocationAfterComma2() - { - var markup = """ + public Task InvocationAfterComma2() + => TestAsync(""" class C { (int, int) y = [|(1,$$)|] } - """; - - await TestAsync(markup, [new("(int, int)", currentParameterIndex: 1)], usePreviousCharAsTrigger: true); - } + """, [new("(int, int)", currentParameterIndex: 1)], usePreviousCharAsTrigger: true); [Fact] - public async Task ParameterIndexWithNameTyped() - { - var markup = """ + public Task ParameterIndexWithNameTyped() + => TestAsync(""" class C { (int a, int b) y = [|(b: $$ |]} - """; - - await TestAsync(markup, [ + """, [ // currentParameterIndex only considers the position in the argument list // and not names, hence passing 0 even though the controller will highlight // "int b" in the actual display new("(int a, int b)", currentParameterIndex: 0)]); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/14277")] - public async Task NestedTuple() - { - var markup = """ + public Task NestedTuple() + => TestAsync(""" class C { (int a, (int b, int c)) y = [|(1, ($$ |]} - """; - - await TestAsync(markup, [new("(int b, int c)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); - } + """, [new("(int b, int c)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); [Fact] - public async Task NestedTupleWhenNotInferred() - { - var markup = """ + public Task NestedTupleWhenNotInferred() + => TestAsync(""" class C { (int, object) y = [|(1, ($$ |]} - """; - - await TestAsync(markup, [new("(int, object)", currentParameterIndex: 1)], usePreviousCharAsTrigger: true); - } + """, [new("(int, object)", currentParameterIndex: 1)], usePreviousCharAsTrigger: true); [Fact] - public async Task NestedTupleWhenNotInferred2() - { - var markup = """ + public Task NestedTupleWhenNotInferred2() + => TestAsync(""" class C { (int, object) y = [|(1, (2,$$ |]} - """; - - await TestAsync(markup, [new("(int, object)", currentParameterIndex: 1)], usePreviousCharAsTrigger: true); - } + """, [new("(int, object)", currentParameterIndex: 1)], usePreviousCharAsTrigger: true); [Fact] - public async Task NestedTupleWhenNotInferred3() - { - var markup = """ + public Task NestedTupleWhenNotInferred3() + => TestAsync(""" class C { (int, object) y = [|(1, ($$ |]} - """; - - await TestAsync(markup, [new("(int, object)", currentParameterIndex: 1)], usePreviousCharAsTrigger: true); - } + """, [new("(int, object)", currentParameterIndex: 1)], usePreviousCharAsTrigger: true); [Fact] - public async Task NestedTupleWhenNotInferred4() - { - var markup = """ + public Task NestedTupleWhenNotInferred4() + => TestAsync(""" class C { (object, object) y = [|(($$ |]} - """; - - await TestAsync(markup, [new("(object, object)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); - } + """, [new("(object, object)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); [Fact] - public async Task MultipleOverloads() - { - var markup = """ + public Task MultipleOverloads() + => TestAsync(""" class Program { static void Main(string[] args) @@ -194,17 +145,14 @@ static void Main(string[] args) static void Do1((int, int) i) { } static void Do1((string, string) s) { } } - """; - - await TestAsync(markup, [ + """, [ new("(int, int)", currentParameterIndex: 0), new("(string, string)", currentParameterIndex: 0)], usePreviousCharAsTrigger: true); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14793")] - public async Task DoNotCrashInLinkedFile() - { - var markup = """ + public Task DoNotCrashInLinkedFile() + => VerifyItemWithReferenceWorkerAsync( + """ - """; - await VerifyItemWithReferenceWorkerAsync( - markup, [new($"(int, string)", currentParameterIndex: 0)], hideAdvancedMembers: false); - } + """, [new($"(int, string)", currentParameterIndex: 0)], hideAdvancedMembers: false); } diff --git a/src/EditorFeatures/CSharpTest/SpellCheck/SpellCheckFixerProviderTests.cs b/src/EditorFeatures/CSharpTest/SpellCheck/SpellCheckFixerProviderTests.cs index c6a3b0f252c5c..8d603d14ed2ee 100644 --- a/src/EditorFeatures/CSharpTest/SpellCheck/SpellCheckFixerProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/SpellCheck/SpellCheckFixerProviderTests.cs @@ -16,9 +16,8 @@ protected override EditorTestWorkspace CreateWorkspace(string content) => EditorTestWorkspace.CreateCSharp(content); [WpfFact] - public async Task TestRenameClassName() - { - await TestSuccessAsync( + public Task TestRenameClassName() + => TestSuccessAsync( """ class {|CorrectlySpelled:CrrectlySpelled|} { @@ -31,13 +30,10 @@ class CorrectlySpelled public CorrectlySpelled() { } } """); - } [WpfFact] - public async Task TestBogusLocation() - { - // Should not be called inside a string. But we should still apply the change. - await TestFailureAsync( + public Task TestBogusLocation() + => TestFailureAsync( """ class C { @@ -58,13 +54,10 @@ void M() } } """); - } [WpfFact] - public async Task TestReplacementThatLanguageDoesNotSupport() - { - // Should not be called inside a string. But we should still apply the change. - await TestFailureAsync( + public Task TestReplacementThatLanguageDoesNotSupport() + => TestFailureAsync( """ class {|Bo()gus:Orginal|} { @@ -77,13 +70,10 @@ class Bo()gus public Orginal() { } } """); - } [WpfFact] - public async Task TestReplacementSpanLargerThanToken() - { - // Replacement span is larger than the lang token to rename. - await TestFailureAsync( + public Task TestReplacementSpanLargerThanToken() + => TestFailureAsync( """ class {|Replacement:Class |} { @@ -96,5 +86,4 @@ class Replacement public Class() { } } """); - } } diff --git a/src/EditorFeatures/CSharpTest/SpellCheck/SpellCheckSpanTests.cs b/src/EditorFeatures/CSharpTest/SpellCheck/SpellCheckSpanTests.cs index a75d77cd8976f..6c95a1fd1dcad 100644 --- a/src/EditorFeatures/CSharpTest/SpellCheck/SpellCheckSpanTests.cs +++ b/src/EditorFeatures/CSharpTest/SpellCheck/SpellCheckSpanTests.cs @@ -17,500 +17,383 @@ protected override EditorTestWorkspace CreateWorkspace(string content) => EditorTestWorkspace.CreateCSharp(content); [Fact] - public async Task TestSingleLineComment1() - { - await TestAsync("{|Comment:// Goo|}"); - } + public Task TestSingleLineComment1() + => TestAsync("{|Comment:// Goo|}"); [Fact] - public async Task TestSingleLineComment2() - { - await TestAsync(""" + public Task TestSingleLineComment2() + => TestAsync(""" {|Comment:// Goo|} """); - } [Fact] - public async Task TestMultiLineComment1() - { - await TestAsync("{|Comment:/* Goo */|}"); - } + public Task TestMultiLineComment1() + => TestAsync("{|Comment:/* Goo */|}"); [Fact] - public async Task TestMultiLineComment2() - { - await TestAsync(""" + public Task TestMultiLineComment2() + => TestAsync(""" {|Comment:/* Goo */|} """); - } [Fact] - public async Task TestMultiLineComment3() - { - await TestAsync(""" + public Task TestMultiLineComment3() + => TestAsync(""" {|Comment:/* Goo |} """); - } [Fact] - public async Task TestMultiLineComment4() - { - await TestAsync(""" + public Task TestMultiLineComment4() + => TestAsync(""" {|Comment:/**/|} """); - } [Fact] - public async Task TestMultiLineComment5() - { - await TestAsync(""" + public Task TestMultiLineComment5() + => TestAsync(""" {|Comment:/*/|} """); - } [Fact] - public async Task TestDocComment1() - { - await TestAsync(""" + public Task TestDocComment1() + => TestAsync(""" ///{|Comment:goo bar baz|} class {|Identifier:C|} { } """); - } [Fact] - public async Task TestDocComment2() - { - await TestAsync(""" + public Task TestDocComment2() + => TestAsync(""" ///{|Comment:goo bar baz|} ///{|Comment:goo bar baz|} class {|Identifier:C|} { } """); - } [Fact] - public async Task TestDocComment3() - { - await TestAsync(""" + public Task TestDocComment3() + => TestAsync(""" ///{|Comment: |}{|Comment: goo bar baz |} class {|Identifier:C|} { } """); - } [Fact] - public async Task TestString1() - { - await TestAsync(@"{|String:"" goo ""|}"); - } + public Task TestString1() + => TestAsync(@"{|String:"" goo ""|}"); [Fact] - public async Task TestString2() - { - await TestAsync(""" + public Task TestString2() + => TestAsync(""" " goo """); - } [Fact] - public async Task TestString3() - { - await TestAsync(""" + public Task TestString3() + => TestAsync(""" {|String:" goo "|} """); - } [Fact] - public async Task TestString4() - { - await TestAsync(""" + public Task TestString4() + => TestAsync(""" " goo """); - } [Fact] - public async Task TestString5() - { - await TestAsync(""" + public Task TestString5() + => TestAsync(""" {|String:@" goo "|} """); - } [Fact] - public async Task TestString6() - { - await TestAsync(""" + public Task TestString6() + => TestAsync(""" @" goo """); - } [Fact] - public async Task TestString7() - { - await TestAsync(@"{|String:"""""" goo """"""|}"); - } + public Task TestString7() + => TestAsync(@"{|String:"""""" goo """"""|}"); [Fact] - public async Task TestString8() - { - await TestAsync("""" + public Task TestString8() + => TestAsync("""" """ goo "" """"); - } [Fact] - public async Task TestString9() - { - await TestAsync("""" + public Task TestString9() + => TestAsync("""" """ goo " """"); - } [Fact] - public async Task TestString10() - { - await TestAsync("""" + public Task TestString10() + => TestAsync("""" """ goo """"); - } [Fact] - public async Task TestString11() - { - await TestAsync("""" + public Task TestString11() + => TestAsync("""" {|String:""" goo """|} """"); - } [Fact] - public async Task TestString12() - { - await TestAsync("""" + public Task TestString12() + => TestAsync("""" """ goo "" """"); - } [Fact] - public async Task TestString13() - { - await TestAsync("""" + public Task TestString13() + => TestAsync("""" """ goo " """"); - } [Fact] - public async Task TestString14() - { - await TestAsync("""" + public Task TestString14() + => TestAsync("""" """ goo """"); - } [Fact] - public async Task TestString15() - { - await TestAsync(""" + public Task TestString15() + => TestAsync(""" $"{|String: goo |}" """); - } [Fact] - public async Task TestString16() - { - await TestAsync(""" + public Task TestString16() + => TestAsync(""" $"{|String: goo |}{0}{|String: bar |}" """); - } [Fact] - public async Task TestString17() - { - await TestAsync("""" + public Task TestString17() + => TestAsync("""" $"""{|String: goo |}{0}{|String: bar |}""" """"); - } [Fact] - public async Task TestString18() - { - await TestAsync("""" + public Task TestString18() + => TestAsync("""" $"""{|String: goo |}{0:abcd}{|String: bar |}""" """"); - } [Fact] - public async Task TestEscapedString1() - { - await TestAsync(""" " {|String:goo|}\r\n{|String:bar |}" """); - } + public Task TestEscapedString1() + => TestAsync(""" " {|String:goo|}\r\n{|String:bar |}" """); [Fact] - public async Task TestEscapedString2() - { - await TestAsync(""" " {|String:goo|}\r\t{|String:bar |}" """); - } + public Task TestEscapedString2() + => TestAsync(""" " {|String:goo|}\r\t{|String:bar |}" """); [Fact] - public async Task TestEscapedString3() - { - await TestAsync(""" " {|String:goo|}\r\u0065bar " """); - } + public Task TestEscapedString3() + => TestAsync(""" " {|String:goo|}\r\u0065bar " """); [Fact] - public async Task TestEscapedString4() - { - await TestAsync(""" " {|String:C|}:\t{|String:ests |}" """); - } + public Task TestEscapedString4() + => TestAsync(""" " {|String:C|}:\t{|String:ests |}" """); [Fact] - public async Task TestEscapedString5() - { - await TestAsync(""" {|String:@" C:\tests "|} """); - } + public Task TestEscapedString5() + => TestAsync(""" {|String:@" C:\tests "|} """); [Fact] - public async Task TestEscapedString6() - { - await TestAsync(""" " {|String:C|}:\\{|String:tests |}" """); - } + public Task TestEscapedString6() + => TestAsync(""" " {|String:C|}:\\{|String:tests |}" """); [Fact] - public async Task TestEscapedString7() - { - await TestAsync(""" " {|String:C|}:\\{|String:tests|}\\{|String:goo |}" """); - } + public Task TestEscapedString7() + => TestAsync(""" " {|String:C|}:\\{|String:tests|}\\{|String:goo |}" """); [Fact] - public async Task TestEscapedString8() - { - await TestAsync(""" {|String:@" C:\tests\goo "|} """); - } + public Task TestEscapedString8() + => TestAsync(""" {|String:@" C:\tests\goo "|} """); [Fact] - public async Task TestEscapedString9() - { - await TestAsync(""" $" {|String:C|}:\\{|String:tests|}\\{|String:goo |}{0} {|String:C|}:\\{|String:tests|}\\{|String:bar |}" """); - } + public Task TestEscapedString9() + => TestAsync(""" $" {|String:C|}:\\{|String:tests|}\\{|String:goo |}{0} {|String:C|}:\\{|String:tests|}\\{|String:bar |}" """); [Fact] - public async Task TestEscapedString10() - { - await TestAsync(""" $@"{|String: C:\tests\goo |}{0}{|String: C:\tests\bar |}" """); - } + public Task TestEscapedString10() + => TestAsync(""" $@"{|String: C:\tests\goo |}{0}{|String: C:\tests\bar |}" """); [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1908466")] - public async Task TestEscapedString11() - { - await TestAsync(""" " {|String:open telemetry for audits |}\n\t {|String:and |}0{|String:Tel table doesn't exist yet |}" """); - } + public Task TestEscapedString11() + => TestAsync(""" " {|String:open telemetry for audits |}\n\t {|String:and |}0{|String:Tel table doesn't exist yet |}" """); [Fact] - public async Task TestIdentifier1() - { - await TestAsync(""" + public Task TestIdentifier1() + => TestAsync(""" class {|Identifier:C|} { } """); - } [Fact] - public async Task TestIdentifier2() - { - await TestAsync(""" + public Task TestIdentifier2() + => TestAsync(""" record {|Identifier:C|} { } """); - } [Fact] - public async Task TestIdentifier3() - { - await TestAsync(""" + public Task TestIdentifier3() + => TestAsync(""" record class {|Identifier:C|} { } """); - } [Fact] - public async Task TestIdentifier4() - { - await TestAsync(""" + public Task TestIdentifier4() + => TestAsync(""" delegate void {|Identifier:C|}(); """); - } [Fact] - public async Task TestIdentifier5() - { - await TestAsync(""" + public Task TestIdentifier5() + => TestAsync(""" enum {|Identifier:C|} { } """); - } [Fact] - public async Task TestIdentifier6() - { - await TestAsync(""" + public Task TestIdentifier6() + => TestAsync(""" enum {|Identifier:C|} { {|Identifier:D|} } """); - } [Fact] - public async Task TestIdentifier7() - { - await TestAsync(""" + public Task TestIdentifier7() + => TestAsync(""" enum {|Identifier:C|} { {|Identifier:D|}, {|Identifier:E|} } """); - } [Fact] - public async Task TestIdentifier8() - { - await TestAsync(""" + public Task TestIdentifier8() + => TestAsync(""" interface {|Identifier:C|} { } """); - } [Fact] - public async Task TestIdentifier9() - { - await TestAsync(""" + public Task TestIdentifier9() + => TestAsync(""" struct {|Identifier:C|} { } """); - } [Fact] - public async Task TestIdentifier10() - { - await TestAsync(""" + public Task TestIdentifier10() + => TestAsync(""" record struct {|Identifier:C|}() { } """); - } [Fact] - public async Task TestIdentifier11() - { - await TestAsync(""" + public Task TestIdentifier11() + => TestAsync(""" class {|Identifier:C|}<{|Identifier:T|}> { } """); - } [Fact] - public async Task TestIdentifier12() - { - await TestAsync(""" + public Task TestIdentifier12() + => TestAsync(""" class {|Identifier:C|} { private int {|Identifier:X|}; } """); - } [Fact] - public async Task TestIdentifier13() - { - await TestAsync(""" + public Task TestIdentifier13() + => TestAsync(""" class {|Identifier:C|} { private int {|Identifier:X|}, {|Identifier:Y|}; } """); - } [Fact] - public async Task TestIdentifier14() - { - await TestAsync(""" + public Task TestIdentifier14() + => TestAsync(""" class {|Identifier:C|} { private const int {|Identifier:X|}; } """); - } [Fact] - public async Task TestIdentifier15() - { - await TestAsync(""" + public Task TestIdentifier15() + => TestAsync(""" class {|Identifier:C|} { private const int {|Identifier:X|}, {|Identifier:Y|}; } """); - } [Fact] - public async Task TestIdentifier16() - { - await TestAsync(""" + public Task TestIdentifier16() + => TestAsync(""" class {|Identifier:C|} { private int {|Identifier:X|} => 0; } """); - } [Fact] - public async Task TestIdentifier17() - { - await TestAsync(""" + public Task TestIdentifier17() + => TestAsync(""" class {|Identifier:C|} { private event Action {|Identifier:X|}; } """); - } [Fact] - public async Task TestIdentifier18() - { - await TestAsync(""" + public Task TestIdentifier18() + => TestAsync(""" class {|Identifier:C|} { private event Action {|Identifier:X|}, {|Identifier:Y|}; } """); - } [Fact] - public async Task TestIdentifier19() - { - await TestAsync(""" + public Task TestIdentifier19() + => TestAsync(""" class {|Identifier:C|} { private event Action {|Identifier:X|} { add { } remove { } } } """); - } [Fact] - public async Task TestIdentifier20() - { - await TestAsync(""" + public Task TestIdentifier20() + => TestAsync(""" class {|Identifier:C|} { void {|Identifier:D|}() @@ -519,12 +402,10 @@ class {|Identifier:C|} } } """); - } [Fact] - public async Task TestIdentifier21() - { - await TestAsync(""" + public Task TestIdentifier21() + => TestAsync(""" class {|Identifier:C|} { void {|Identifier:D|}() @@ -533,12 +414,10 @@ class {|Identifier:C|} } } """); - } [Fact] - public async Task TestIdentifier22() - { - await TestAsync(""" + public Task TestIdentifier22() + => TestAsync(""" class {|Identifier:C|} { void {|Identifier:D|}() @@ -548,12 +427,10 @@ class {|Identifier:C|} } } """); - } [Fact] - public async Task TestIdentifier23() - { - await TestAsync(""" + public Task TestIdentifier23() + => TestAsync(""" class {|Identifier:C|} { void {|Identifier:D|}(int {|Identifier:E|}) @@ -561,12 +438,10 @@ class {|Identifier:C|} } } """); - } [Fact] - public async Task TestIdentifier24() - { - await TestAsync(""" + public Task TestIdentifier24() + => TestAsync(""" class {|Identifier:C|} { void {|Identifier:D|}(int {|Identifier:E|}) @@ -574,12 +449,10 @@ class {|Identifier:C|} } } """); - } [Fact] - public async Task TestIdentifier25() - { - await TestAsync(""" + public Task TestIdentifier25() + => TestAsync(""" class {|Identifier:C|} { void {|Identifier:D|}(int {|Identifier:E|}, int {|Identifier:F|}) @@ -587,12 +460,10 @@ class {|Identifier:C|} } } """); - } [Fact] - public async Task TestIdentifier26() - { - await TestAsync(""" + public Task TestIdentifier26() + => TestAsync(""" static class {|Identifier:C|} { static void {|Identifier:D|}(this int {|Identifier:E|}) @@ -600,32 +471,26 @@ static class {|Identifier:C|} } } """); - } [Fact] - public async Task TestIdentifier27() - { - await TestAsync(""" + public Task TestIdentifier27() + => TestAsync(""" namespace {|Identifier:C|} { } """); - } [Fact] - public async Task TestIdentifier28() - { - await TestAsync(""" + public Task TestIdentifier28() + => TestAsync(""" namespace {|Identifier:C|}.{|Identifier:D|} { } """); - } [Fact] - public async Task TestIdentifier29() - { - await TestAsync(""" + public Task TestIdentifier29() + => TestAsync(""" class {|Identifier:C|} { void {|Identifier:D|}() @@ -636,12 +501,10 @@ class {|Identifier:C|} } } """); - } [Fact] - public async Task TestIdentifier30() - { - await TestAsync(""" + public Task TestIdentifier30() + => TestAsync(""" class {|Identifier:C|} { void {|Identifier:D|}() @@ -650,37 +513,28 @@ class {|Identifier:C|} } } """); - } [Fact] - public async Task TestIdentifier31() - { - await TestAsync(""" + public Task TestIdentifier31() + => TestAsync(""" class {|Identifier:C|}() { } """); - } [Fact] - public async Task TestIdentifier32() - { - await TestAsync(""" + public Task TestIdentifier32() + => TestAsync(""" struct {|Identifier:C|}() { } """); - } [Fact] - public async Task TestIdentifier33() - { - await TestAsync(""" + public Task TestIdentifier33() + => TestAsync(""" class {|Identifier:C|}; """); - } [Fact] - public async Task TestIdentifier34() - { - await TestAsync(""" + public Task TestIdentifier34() + => TestAsync(""" struct {|Identifier:C|}; """); - } } diff --git a/src/EditorFeatures/CSharpTest/SplitComment/SplitCommentCommandHandlerTests.cs b/src/EditorFeatures/CSharpTest/SplitComment/SplitCommentCommandHandlerTests.cs index 0ad570395045b..0d717ad8a3cd9 100644 --- a/src/EditorFeatures/CSharpTest/SplitComment/SplitCommentCommandHandlerTests.cs +++ b/src/EditorFeatures/CSharpTest/SplitComment/SplitCommentCommandHandlerTests.cs @@ -309,13 +309,15 @@ public static void Main(string[] args) public void TestCommentWithMultipleLeadingSpaces(string commentValue) { TestHandled( -@$"public class Program -{{ - public static void Main(string[] args) - {{ - // {commentValue} - }} -}}", + $$""" + public class Program + { + public static void Main(string[] args) + { + // {{commentValue}} + } + } + """, """ public class Program { @@ -338,13 +340,15 @@ public static void Main(string[] args) public void TestQuadCommentWithMultipleLeadingSpaces(string commentValue) { TestHandled( -@$"public class Program -{{ - public static void Main(string[] args) - {{ - //// {commentValue} - }} -}}", + $$""" + public class Program + { + public static void Main(string[] args) + { + //// {{commentValue}} + } + } + """, """ public class Program { diff --git a/src/EditorFeatures/CSharpTest/SplitStringLiteral/SplitStringLiteralCommandHandlerTests.cs b/src/EditorFeatures/CSharpTest/SplitStringLiteral/SplitStringLiteralCommandHandlerTests.cs index 27c4fa45a1673..a719c07fb9f00 100644 --- a/src/EditorFeatures/CSharpTest/SplitStringLiteral/SplitStringLiteralCommandHandlerTests.cs +++ b/src/EditorFeatures/CSharpTest/SplitStringLiteral/SplitStringLiteralCommandHandlerTests.cs @@ -152,247 +152,285 @@ private static void TestNotHandled(string inputMarkup) public void TestMissingBeforeString() { TestNotHandled( -@"class C -{ - void M() - { - var v = [||]""""; - } -}"); + """ + class C + { + void M() + { + var v = [||]""; + } + } + """); } [WpfFact] public void TestMissingBeforeUtf8String() { TestNotHandled( -@"class C -{ - void M() - { - var v = [||]""""u8; - } -}"); + """ + class C + { + void M() + { + var v = [||]""u8; + } + } + """); } [WpfFact] public void TestMissingBeforeInterpolatedString() { TestNotHandled( -@"class C -{ - void M() - { - var v = [||]$""""; - } -}"); + """ + class C + { + void M() + { + var v = [||]$""; + } + } + """); } [WpfFact] public void TestMissingAfterString_1() { TestNotHandled( -@"class C -{ - void M() - { - var v = """"[||]; - } -}"); + """ + class C + { + void M() + { + var v = ""[||]; + } + } + """); } [WpfFact] public void TestMissingAfterString_2() { TestNotHandled( -@"class C -{ - void M() - { - var v = """" [||]; - } -}"); + """ + class C + { + void M() + { + var v = "" [||]; + } + } + """); } [WpfFact] public void TestMissingAfterString_3() { TestNotHandled( -@"class C -{ - void M() - { - var v = """"[||] - } -}"); + """ + class C + { + void M() + { + var v = ""[||] + } + } + """); } [WpfFact] public void TestMissingAfterString_4() { TestNotHandled( -@"class C -{ - void M() - { - var v = """" [||] - } -}"); + """ + class C + { + void M() + { + var v = "" [||] + } + } + """); } [WpfFact] public void TestMissingAfterInterpolatedString_1() { TestNotHandled( -@"class C -{ - void M() - { - var v = $""""[||]; - } -}"); + """ + class C + { + void M() + { + var v = $""[||]; + } + } + """); } [WpfFact] public void TestMissingAfterInterpolatedString_2() { TestNotHandled( -@"class C -{ - void M() - { - var v = $"""" [||]; - } -}"); + """ + class C + { + void M() + { + var v = $"" [||]; + } + } + """); } [WpfFact] public void TestMissingAfterInterpolatedString_3() { TestNotHandled( -@"class C -{ - void M() - { - var v = $""""[||] - } -}"); + """ + class C + { + void M() + { + var v = $""[||] + } + } + """); } [WpfFact] public void TestMissingAfterInterpolatedString_4() { TestNotHandled( -@"class C -{ - void M() - { - var v = $"""" [||] - } -}"); + """ + class C + { + void M() + { + var v = $"" [||] + } + } + """); } [WpfFact] public void TestMissingAfterUtf8String_1() { TestNotHandled( -@"class C -{ - void M() - { - var v = """"[||]u8; - } -}"); + """ + class C + { + void M() + { + var v = ""[||]u8; + } + } + """); } [WpfFact] public void TestMissingAfterUtf8String_2() { TestNotHandled( -@"class C -{ - void M() - { - var v = """"u8[||]; - } -}"); + """ + class C + { + void M() + { + var v = ""u8[||]; + } + } + """); } [WpfFact] public void TestMissingAfterUtf8String_3() { TestNotHandled( -@"class C -{ - void M() - { - var v = """"u8[||] - } -}"); + """ + class C + { + void M() + { + var v = ""u8[||] + } + } + """); } [WpfFact] public void TestMissingAfterUtf8String_4() { TestNotHandled( -@"class C -{ - void M() - { - var v = $""""u8 [||] - } -}"); + """ + class C + { + void M() + { + var v = $""u8 [||] + } + } + """); } [WpfFact] public void TestMissingAfterUtf8String_5() { TestNotHandled( -@"class C -{ - void M() - { - var v = """"u[||]8; - } -}"); + """ + class C + { + void M() + { + var v = ""u[||]8; + } + } + """); } [WpfFact] public void TestMissingInVerbatimString() { TestNotHandled( -@"class C -{ - void M() - { - var v = @""a[||]b""; - } -}"); + """ + class C + { + void M() + { + var v = @"a[||]b"; + } + } + """); } [WpfFact] public void TestMissingInUtf8VerbatimString() { TestNotHandled( -@"class C -{ - void M() - { - var v = @""a[||]b""u8; - } -}"); + """ + class C + { + void M() + { + var v = @"a[||]b"u8; + } + } + """); } [WpfFact] public void TestMissingInInterpolatedVerbatimString() { TestNotHandled( -@"class C -{ - void M() - { - var v = $@""a[||]b""; - } -}"); + """ + class C + { + void M() + { + var v = $@"a[||]b"; + } + } + """); } [WpfFact] @@ -401,21 +439,25 @@ public void TestInEmptyString() // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( -@"class C -{ - void M() - { - var v = ""[||]""; - } -}", -@"class C -{ - void M() - { - var v = """" + - ""[||]""; - } -}", + """ + class C + { + void M() + { + var v = "[||]"; + } + } + """, + """ + class C + { + void M() + { + var v = "" + + "[||]"; + } + } + """, verifyUndo: false); } @@ -437,21 +479,25 @@ public void TestInEmptyString_BlockIndent() // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( -@"class C -{ - void M() - { - var v = ""[||]""; - } -}", -@"class C -{ - void M() - { - var v = """" + - ""[||]""; - } -}", + """ + class C + { + void M() + { + var v = "[||]"; + } + } + """, + """ + class C + { + void M() + { + var v = "" + + "[||]"; + } + } + """, verifyUndo: false, IndentStyle.Block); } @@ -462,21 +508,25 @@ public void TestInEmptyString_NoneIndent() // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( -@"class C -{ - void M() - { - var v = ""[||]""; - } -}", -@"class C -{ - void M() - { - var v = """" + -""[||]""; - } -}", + """ + class C + { + void M() + { + var v = "[||]"; + } + } + """, + """ + class C + { + void M() + { + var v = "" + + "[||]"; + } + } + """, verifyUndo: false, IndentStyle.None); } @@ -485,21 +535,25 @@ void M() public void TestInEmptyInterpolatedString() { TestHandled( -@"class C -{ - void M() - { - var v = $""[||]""; - } -}", -@"class C -{ - void M() - { - var v = $"""" + - $""[||]""; - } -}"); + """ + class C + { + void M() + { + var v = $"[||]"; + } + } + """, + """ + class C + { + void M() + { + var v = $"" + + $"[||]"; + } + } + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/41322")] @@ -515,207 +569,245 @@ public void TestInEmptyInterpolatedString_LF() public void TestInEmptyInterpolatedString_BlockIndent() { TestHandled( -@"class C -{ - void M() - { - var v = $""[||]""; - } -}", -@"class C -{ - void M() - { - var v = $"""" + - $""[||]""; - } -}", indentStyle: IndentStyle.Block); + """ + class C + { + void M() + { + var v = $"[||]"; + } + } + """, + """ + class C + { + void M() + { + var v = $"" + + $"[||]"; + } + } + """, indentStyle: IndentStyle.Block); } [WpfFact] public void TestInEmptyInterpolatedString_NoneIndent() { TestHandled( -@"class C -{ - void M() - { - var v = $""[||]""; - } -}", -@"class C -{ - void M() - { - var v = $"""" + -$""[||]""; - } -}", indentStyle: IndentStyle.None); + """ + class C + { + void M() + { + var v = $"[||]"; + } + } + """, + """ + class C + { + void M() + { + var v = $"" + + $"[||]"; + } + } + """, indentStyle: IndentStyle.None); } [WpfFact] public void TestSimpleString1() { TestHandled( -@"class C -{ - void M() - { - var v = ""now is [||]the time""; - } -}", -@"class C -{ - void M() - { - var v = ""now is "" + - ""[||]the time""; - } -}"); + """ + class C + { + void M() + { + var v = "now is [||]the time"; + } + } + """, + """ + class C + { + void M() + { + var v = "now is " + + "[||]the time"; + } + } + """); } [WpfFact] public void TestUtf8String_1() { TestHandled( -@"class C -{ - void M() - { - var v = ""now is [||]the time""u8; - } -}", -@"class C -{ - void M() - { - var v = ""now is ""u8 + - ""[||]the time""u8; - } -}"); + """ + class C + { + void M() + { + var v = "now is [||]the time"u8; + } + } + """, + """ + class C + { + void M() + { + var v = "now is "u8 + + "[||]the time"u8; + } + } + """); } [WpfFact] public void TestUtf8String_2() { TestHandled( -@"class C -{ - void M() - { - var v = ""now is [||]the time""U8; - } -}", -@"class C -{ - void M() - { - var v = ""now is ""U8 + - ""[||]the time""U8; - } -}"); + """ + class C + { + void M() + { + var v = "now is [||]the time"U8; + } + } + """, + """ + class C + { + void M() + { + var v = "now is "U8 + + "[||]the time"U8; + } + } + """); } [WpfFact] public void TestInterpolatedString1() { TestHandled( -@"class C -{ - void M() - { - var v = $""now is [||]the { 1 + 2 } time for { 3 + 4 } all good men""; - } -}", -@"class C -{ - void M() - { - var v = $""now is "" + - $""[||]the { 1 + 2 } time for { 3 + 4 } all good men""; - } -}"); + """ + class C + { + void M() + { + var v = $"now is [||]the { 1 + 2 } time for { 3 + 4 } all good men"; + } + } + """, + """ + class C + { + void M() + { + var v = $"now is " + + $"[||]the { 1 + 2 } time for { 3 + 4 } all good men"; + } + } + """); } [WpfFact] public void TestInterpolatedString2() { TestHandled( -@"class C -{ - void M() - { - var v = $""now is the [||]{ 1 + 2 } time for { 3 + 4 } all good men""; - } -}", -@"class C -{ - void M() - { - var v = $""now is the "" + - $""[||]{ 1 + 2 } time for { 3 + 4 } all good men""; - } -}"); + """ + class C + { + void M() + { + var v = $"now is the [||]{ 1 + 2 } time for { 3 + 4 } all good men"; + } + } + """, + """ + class C + { + void M() + { + var v = $"now is the " + + $"[||]{ 1 + 2 } time for { 3 + 4 } all good men"; + } + } + """); } [WpfFact] public void TestInterpolatedString3() { TestHandled( -@"class C -{ - void M() - { - var v = $""now is the { 1 + 2 }[||] time for { 3 + 4 } all good men""; - } -}", -@"class C -{ - void M() - { - var v = $""now is the { 1 + 2 }"" + - $""[||] time for { 3 + 4 } all good men""; - } -}"); + """ + class C + { + void M() + { + var v = $"now is the { 1 + 2 }[||] time for { 3 + 4 } all good men"; + } + } + """, + """ + class C + { + void M() + { + var v = $"now is the { 1 + 2 }" + + $"[||] time for { 3 + 4 } all good men"; + } + } + """); } [WpfFact] public void TestMissingInInterpolation1() { TestNotHandled( -@"class C -{ - void M() - { - var v = $""now is the {[||] 1 + 2 } time for { 3 + 4 } all good men""; - } -}"); + """ + class C + { + void M() + { + var v = $"now is the {[||] 1 + 2 } time for { 3 + 4 } all good men"; + } + } + """); } [WpfFact] public void TestMissingInInterpolation2() { TestNotHandled( -@"class C -{ - void M() - { - var v = $""now is the { 1 + 2 [||]} time for { 3 + 4 } all good men""; - } -}"); + """ + class C + { + void M() + { + var v = $"now is the { 1 + 2 [||]} time for { 3 + 4 } all good men"; + } + } + """); } [WpfFact] public void TestSelection() { TestNotHandled( -@"class C -{ - void M() - { - var v = ""now is [|the|] time""; - } -}"); + """ + class C + { + void M() + { + var v = "now is [|the|] time"; + } + } + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/20258")] @@ -724,33 +816,37 @@ public void TestBeforeEndQuote1() // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( -@"class Program -{ - static void Main(string[] args) - { - var str = $""somestring { args[0]}[||]"" + - $""{args[1]}"" + - $""{args[2]}""; - - var str2 = ""string1"" + - ""string2"" + - ""string3""; - } -}", -@"class Program -{ - static void Main(string[] args) - { - var str = $""somestring { args[0]}"" + - $""[||]"" + - $""{args[1]}"" + - $""{args[2]}""; - - var str2 = ""string1"" + - ""string2"" + - ""string3""; - } -}", + """ + class Program + { + static void Main(string[] args) + { + var str = $"somestring { args[0]}[||]" + + $"{args[1]}" + + $"{args[2]}"; + + var str2 = "string1" + + "string2" + + "string3"; + } + } + """, + """ + class Program + { + static void Main(string[] args) + { + var str = $"somestring { args[0]}" + + $"[||]" + + $"{args[1]}" + + $"{args[2]}"; + + var str2 = "string1" + + "string2" + + "string3"; + } + } + """, verifyUndo: false); } @@ -760,33 +856,37 @@ public void TestBeforeEndQuote2() // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( -@"class Program -{ - static void Main(string[] args) - { - var str = $""somestring { args[0]}"" + - $""{args[1]}[||]"" + - $""{args[2]}""; - - var str2 = ""string1"" + - ""string2"" + - ""string3""; - } -}", -@"class Program -{ - static void Main(string[] args) - { - var str = $""somestring { args[0]}"" + - $""{args[1]}"" + - $""[||]"" + - $""{args[2]}""; - - var str2 = ""string1"" + - ""string2"" + - ""string3""; - } -}", + """ + class Program + { + static void Main(string[] args) + { + var str = $"somestring { args[0]}" + + $"{args[1]}[||]" + + $"{args[2]}"; + + var str2 = "string1" + + "string2" + + "string3"; + } + } + """, + """ + class Program + { + static void Main(string[] args) + { + var str = $"somestring { args[0]}" + + $"{args[1]}" + + $"[||]" + + $"{args[2]}"; + + var str2 = "string1" + + "string2" + + "string3"; + } + } + """, verifyUndo: false); } @@ -796,33 +896,37 @@ public void TestBeforeEndQuote3() // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( -@"class Program -{ - static void Main(string[] args) - { - var str = $""somestring { args[0]}"" + - $""{args[1]}"" + - $""{args[2]}[||]""; - - var str2 = ""string1"" + - ""string2"" + - ""string3""; - } -}", -@"class Program -{ - static void Main(string[] args) - { - var str = $""somestring { args[0]}"" + - $""{args[1]}"" + - $""{args[2]}"" + - $""[||]""; - - var str2 = ""string1"" + - ""string2"" + - ""string3""; - } -}", + """ + class Program + { + static void Main(string[] args) + { + var str = $"somestring { args[0]}" + + $"{args[1]}" + + $"{args[2]}[||]"; + + var str2 = "string1" + + "string2" + + "string3"; + } + } + """, + """ + class Program + { + static void Main(string[] args) + { + var str = $"somestring { args[0]}" + + $"{args[1]}" + + $"{args[2]}" + + $"[||]"; + + var str2 = "string1" + + "string2" + + "string3"; + } + } + """, verifyUndo: false); } @@ -832,33 +936,37 @@ public void TestBeforeEndQuote4() // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( -@"class Program -{ - static void Main(string[] args) - { - var str = $""somestring { args[0]}"" + - $""{args[1]}"" + - $""{args[2]}""; - - var str2 = ""string1[||]"" + - ""string2"" + - ""string3""; - } -}", -@"class Program -{ - static void Main(string[] args) - { - var str = $""somestring { args[0]}"" + - $""{args[1]}"" + - $""{args[2]}""; - - var str2 = ""string1"" + - ""[||]"" + - ""string2"" + - ""string3""; - } -}", + """ + class Program + { + static void Main(string[] args) + { + var str = $"somestring { args[0]}" + + $"{args[1]}" + + $"{args[2]}"; + + var str2 = "string1[||]" + + "string2" + + "string3"; + } + } + """, + """ + class Program + { + static void Main(string[] args) + { + var str = $"somestring { args[0]}" + + $"{args[1]}" + + $"{args[2]}"; + + var str2 = "string1" + + "[||]" + + "string2" + + "string3"; + } + } + """, verifyUndo: false); } @@ -868,33 +976,37 @@ public void TestBeforeEndQuote5() // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( -@"class Program -{ - static void Main(string[] args) - { - var str = $""somestring { args[0]}"" + - $""{args[1]}"" + - $""{args[2]}""; - - var str2 = ""string1"" + - ""string2[||]"" + - ""string3""; - } -}", -@"class Program -{ - static void Main(string[] args) - { - var str = $""somestring { args[0]}"" + - $""{args[1]}"" + - $""{args[2]}""; - - var str2 = ""string1"" + - ""string2"" + - ""[||]"" + - ""string3""; - } -}", + """ + class Program + { + static void Main(string[] args) + { + var str = $"somestring { args[0]}" + + $"{args[1]}" + + $"{args[2]}"; + + var str2 = "string1" + + "string2[||]" + + "string3"; + } + } + """, + """ + class Program + { + static void Main(string[] args) + { + var str = $"somestring { args[0]}" + + $"{args[1]}" + + $"{args[2]}"; + + var str2 = "string1" + + "string2" + + "[||]" + + "string3"; + } + } + """, verifyUndo: false); } @@ -904,33 +1016,37 @@ public void TestBeforeEndQuote6() // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( -@"class Program -{ - static void Main(string[] args) - { - var str = $""somestring { args[0]}"" + - $""{args[1]}"" + - $""{args[2]}""; - - var str2 = ""string1"" + - ""string2"" + - ""string3[||]""; - } -}", -@"class Program -{ - static void Main(string[] args) - { - var str = $""somestring { args[0]}"" + - $""{args[1]}"" + - $""{args[2]}""; - - var str2 = ""string1"" + - ""string2"" + - ""string3"" + - ""[||]""; - } -}", + """ + class Program + { + static void Main(string[] args) + { + var str = $"somestring { args[0]}" + + $"{args[1]}" + + $"{args[2]}"; + + var str2 = "string1" + + "string2" + + "string3[||]"; + } + } + """, + """ + class Program + { + static void Main(string[] args) + { + var str = $"somestring { args[0]}" + + $"{args[1]}" + + $"{args[2]}"; + + var str2 = "string1" + + "string2" + + "string3" + + "[||]"; + } + } + """, verifyUndo: false); } @@ -938,98 +1054,114 @@ static void Main(string[] args) public void TestMultiCaretSingleLine() { TestHandled( -@"class C -{ - void M() - { - var v = ""now is [||]the ti[||]me""; - } -}", -@"class C -{ - void M() - { - var v = ""now is "" + - ""[||]the ti"" + - ""[||]me""; - } -}"); + """ + class C + { + void M() + { + var v = "now is [||]the ti[||]me"; + } + } + """, + """ + class C + { + void M() + { + var v = "now is " + + "[||]the ti" + + "[||]me"; + } + } + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/39040")] public void TestMultiCaretMultiLines() { TestHandled( -@"class C -{ - string s = ""hello w[||]orld""; - - void M() - { - var v = ""now is [||]the ti[||]me""; - } -}", -@"class C -{ - string s = ""hello w"" + - ""[||]orld""; + """ + class C + { + string s = "hello w[||]orld"; - void M() - { - var v = ""now is "" + - ""[||]the ti"" + - ""[||]me""; - } -}"); + void M() + { + var v = "now is [||]the ti[||]me"; + } + } + """, + """ + class C + { + string s = "hello w" + + "[||]orld"; + + void M() + { + var v = "now is " + + "[||]the ti" + + "[||]me"; + } + } + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/39040")] public void TestMultiCaretInterpolatedString() { TestHandled( -@"class C -{ - string s = ""hello w[||]orld""; - - void M() - { - var location = ""world""; - var s = $""H[||]ello {location}!""; - } -}", -@"class C -{ - string s = ""hello w"" + - ""[||]orld""; + """ + class C + { + string s = "hello w[||]orld"; - void M() - { - var location = ""world""; - var s = $""H"" + - $""[||]ello {location}!""; - } -}"); + void M() + { + var location = "world"; + var s = $"H[||]ello {location}!"; + } + } + """, + """ + class C + { + string s = "hello w" + + "[||]orld"; + + void M() + { + var location = "world"; + var s = $"H" + + $"[||]ello {location}!"; + } + } + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/40277")] public void TestInStringWithKeepTabsEnabled1() { TestHandled( -@"class C -{ - void M() - { - var s = ""Hello [||]world""; - } -}", -@"class C -{ - void M() - { - var s = ""Hello "" + - ""[||]world""; - } -}", + """ + class C + { + void M() + { + var s = "Hello [||]world"; + } + } + """, + """ + class C + { + void M() + { + var s = "Hello " + + "[||]world"; + } + } + """, useTabs: true); } @@ -1037,23 +1169,27 @@ void M() public void TestInStringWithKeepTabsEnabled2() { TestHandled( -@"class C -{ - void M() - { - var s = ""Hello "" + - ""there [||]world""; - } -}", -@"class C -{ - void M() - { - var s = ""Hello "" + - ""there "" + - ""[||]world""; - } -}", + """ + class C + { + void M() + { + var s = "Hello " + + "there [||]world"; + } + } + """, + """ + class C + { + void M() + { + var s = "Hello " + + "there " + + "[||]world"; + } + } + """, useTabs: true); } @@ -1061,59 +1197,67 @@ void M() public void TestMissingInRawStringLiteral() { TestNotHandled( -@"class C -{ - void M() - { - var v = """"""Hello[||]there -world -""""""; - } -}"); + """" + class C + { + void M() + { + var v = """Hello[||]there + world + """; + } + } + """"); } [WpfFact] public void TestMissingInRawStringLiteralInterpolation() { TestNotHandled( -@"class C -{ - void M() - { - var v = $""""""Hello[||]there -world -""""""; - } -}"); + """" + class C + { + void M() + { + var v = $"""Hello[||]there + world + """; + } + } + """"); } [WpfFact] public void TestMissingInRawStringLiteralInterpolation_MultiBrace() { TestNotHandled( -@"class C -{ - void M() - { - var v = ${|#0:|}$""""""Hello[||]there -world -""""""; - } -}"); + """" + class C + { + void M() + { + var v = ${|#0:|}$"""Hello[||]there + world + """; + } + } + """"); } [WpfFact] public void TestMissingInRawUtf8StringLiteral() { TestNotHandled( -@"class C -{ - void M() - { - var v = """"""Hello[||]there -world -""""""u8; - } -}"); + """" + class C + { + void M() + { + var v = """Hello[||]there + world + """u8; + } + } + """"); } } diff --git a/src/EditorFeatures/CSharpTest/StringCopyPaste/StringCopyPasteCommandHandlerTests.cs b/src/EditorFeatures/CSharpTest/StringCopyPaste/StringCopyPasteCommandHandlerTests.cs index 6e2d7270c8d7d..e9314721b6e09 100644 --- a/src/EditorFeatures/CSharpTest/StringCopyPaste/StringCopyPasteCommandHandlerTests.cs +++ b/src/EditorFeatures/CSharpTest/StringCopyPaste/StringCopyPasteCommandHandlerTests.cs @@ -53,16 +53,17 @@ public static StringCopyPasteTestState CreateTestState(string? copyFileMarkup, s => new(GetWorkspaceXml(copyFileMarkup, pasteFileMarkup), mockCopyPasteService); public static XElement GetWorkspaceXml(string? copyFileMarkup, string pasteFileMarkup) - => XElement.Parse(($@" - - - {pasteFileMarkup} - - {(copyFileMarkup == null ? "" : $@" + => XElement.Parse(($""" + + + {pasteFileMarkup} + + {(copyFileMarkup == null ? "" : $@" {copyFileMarkup} ")} -")); + + """)); internal void AssertCodeIs(string expectedCode) { diff --git a/src/EditorFeatures/CSharpTest/StringIndentation/StringIndentationTests.cs b/src/EditorFeatures/CSharpTest/StringIndentation/StringIndentationTests.cs index a98dcd35c4d1e..569e187e764b5 100644 --- a/src/EditorFeatures/CSharpTest/StringIndentation/StringIndentationTests.cs +++ b/src/EditorFeatures/CSharpTest/StringIndentation/StringIndentationTests.cs @@ -69,259 +69,258 @@ public async Task TestEmptyFile() [Theory] [InlineData("")] [InlineData("u8")] - public async Task TestLiteralError1(string suffix) - { - await TestAsync($@"class C -{{ - void M() - {{ - // not enough lines in literal - var v = """""" - """"""{suffix}; - }} -}}"); - } + public Task TestLiteralError1(string suffix) + => TestAsync($$"""" + class C + { + void M() + { + // not enough lines in literal + var v = """ + """{{suffix}}; + } + } + """"); [Theory] [InlineData("")] [InlineData("u8")] - public async Task TestLiteralError2(string suffix) - { - await TestAsync($@"class C -{{ - void M() - {{ - // invalid literal - var v = """""" - text too early - """"""{suffix}; - }} -}}"); - } + public Task TestLiteralError2(string suffix) + => TestAsync($$"""" + class C + { + void M() + { + // invalid literal + var v = """ + text too early + """{{suffix}}; + } + } + """"); [Theory] [InlineData("")] [InlineData("u8")] - public async Task TestZeroColumn1(string suffix) - { - await TestAsync($@"class C -{{ - void M() - {{ - var v = """""" -goo -""""""{suffix}; - }} -}}"); - } + public Task TestZeroColumn1(string suffix) + => TestAsync($$"""" + class C + { + void M() + { + var v = """ + goo + """{{suffix}}; + } + } + """"); [Theory] [InlineData("")] [InlineData("u8")] - public async Task TestZeroColumn2(string suffix) - { - await TestAsync($@"class C -{{ - void M() - {{ - var v = """""" - goo -""""""{suffix}; - }} -}}"); - } + public Task TestZeroColumn2(string suffix) + => TestAsync($$"""" + class C + { + void M() + { + var v = """ + goo + """{{suffix}}; + } + } + """"); [Theory] [InlineData("")] [InlineData("u8")] - public async Task TestOneColumn1(string suffix) - { - await TestAsync($@"class C -{{ - void M() - {{ - var v = """""" -|goo - """"""{suffix}; - }} -}}"); - } + public Task TestOneColumn1(string suffix) + => TestAsync($$"""" + class C + { + void M() + { + var v = """ + |goo + """{{suffix}}; + } + } + """"); [Theory] [InlineData("")] [InlineData("u8")] - public async Task TestOneColumn2(string suffix) - { - await TestAsync($@"class C -{{ - void M() - {{ - var v = """""" -| goo - """"""{suffix}; - }} -}}"); - } + public Task TestOneColumn2(string suffix) + => TestAsync($$"""" + class C + { + void M() + { + var v = """ + | goo + """{{suffix}}; + } + } + """"); [Theory] [InlineData("")] [InlineData("u8")] - public async Task TestCase1(string suffix) - { - await TestAsync($@"class C -{{ - void M() - {{ - var v = """""" - |goo - """"""{suffix}; - }} -}}"); - } + public Task TestCase1(string suffix) + => TestAsync($$"""" + class C + { + void M() + { + var v = """ + |goo + """{{suffix}}; + } + } + """"); [Theory] [InlineData("")] [InlineData("u8")] - public async Task TestCase2(string suffix) - { - await TestAsync($@"class C -{{ - void M() - {{ - var v = """""" - |goo - |bar - """"""{suffix}; - }} -}}"); - } + public Task TestCase2(string suffix) + => TestAsync($$"""" + class C + { + void M() + { + var v = """ + |goo + |bar + """{{suffix}}; + } + } + """"); [Theory] [InlineData("")] [InlineData("u8")] - public async Task TestCase3(string suffix) - { - await TestAsync($@"class C -{{ - void M() - {{ - var v = """""" - |goo - |bar - |baz - """"""{suffix}; - }} -}}"); - } + public Task TestCase3(string suffix) + => TestAsync($$"""" + class C + { + void M() + { + var v = """ + |goo + |bar + |baz + """{{suffix}}; + } + } + """"); [Theory] [InlineData("")] [InlineData("u8")] - public async Task TestCase4(string suffix) - { - await TestAsync($@"class C -{{ - void M() - {{ - var v = """""" - |goo - | - |baz - """"""{suffix}; - }} -}}"); - } + public Task TestCase4(string suffix) + => TestAsync($$"""" + class C + { + void M() + { + var v = """ + |goo + | + |baz + """{{suffix}}; + } + } + """"); [Theory] [InlineData("")] [InlineData("u8")] - public async Task TestCase5(string suffix) - { - await TestAsync($@"class C -{{ - void M() - {{ - var v = """""" - | goo - | - | baz - """"""{suffix}; - }} -}}"); - } + public Task TestCase5(string suffix) + => TestAsync($$"""" + class C + { + void M() + { + var v = """ + | goo + | + | baz + """{{suffix}}; + } + } + """"); [Theory] [InlineData("")] [InlineData("u8")] - public async Task TestCase6(string suffix) - { - await TestAsync($@"class C -{{ - void M() - {{ - var v = - $"""""" - |goo - """"""{suffix}; - }} -}}"); - } + public Task TestCase6(string suffix) + => TestAsync($$"""" + class C + { + void M() + { + var v = + $""" + |goo + """{{suffix}}; + } + } + """"); [Theory] [InlineData("")] [InlineData("u8")] - public async Task TestCase7(string suffix) - { - await TestAsync($@"class C -{{ - void M() - {{ - var v = - $"""""" - |goo - """"""{suffix}; - }} -}}"); - } + public Task TestCase7(string suffix) + => TestAsync($$"""" + class C + { + void M() + { + var v = + $""" + |goo + """{{suffix}}; + } + } + """"); [Theory] [InlineData("")] [InlineData("u8")] - public async Task TestCase8(string suffix) - { - await TestAsync($@"class C -{{ - void M() - {{ - var v = - $"""""""" - |goo - """"""""{suffix}; - }} -}}"); - } + public Task TestCase8(string suffix) + => TestAsync($$""""" + class C + { + void M() + { + var v = + $"""" + |goo + """"{{suffix}}; + } + } + """""); [Theory] [InlineData("")] [InlineData("u8")] - public async Task TestCase9(string suffix) - { - await TestAsync($@"class C -{{ - void M() - {{ - var v = - """""""" - |goo - """"""""{suffix}; - }} -}}"); - } + public Task TestCase9(string suffix) + => TestAsync($$""""" + class C + { + void M() + { + var v = + """" + |goo + """"{{suffix}}; + } + } + """""); [Fact] - public async Task TestCase10() - { - await TestAsync(""""" + public Task TestCase10() + => TestAsync(""""" class C { void M() @@ -333,12 +332,10 @@ void M() } } """""); - } [Fact] - public async Task TestCase11() - { - await TestAsync(""""" + public Task TestCase11() + => TestAsync(""""" class C { void M() @@ -350,12 +347,10 @@ void M() } } """""); - } [Fact] - public async Task TestCase12() - { - await TestAsync(""""" + public Task TestCase12() + => TestAsync(""""" class C { void M() @@ -367,12 +362,10 @@ void M() } } """""); - } [Fact] - public async Task TestWithHoles1() - { - await TestAsync("""" + public Task TestWithHoles1() + => TestAsync("""" class C { void M() @@ -385,12 +378,10 @@ void M() } } """"); - } [Fact] - public async Task TestWithHoles2() - { - await TestAsync("""" + public Task TestWithHoles2() + => TestAsync("""" class C { void M() @@ -403,12 +394,10 @@ void M() } } """"); - } [Fact] - public async Task TestWithHoles3() - { - await TestAsync("""" + public Task TestWithHoles3() + => TestAsync("""" class C { void M() @@ -421,12 +410,10 @@ void M() } } """"); - } [Fact] - public async Task TestWithHoles4() - { - await TestAsync("""" + public Task TestWithHoles4() + => TestAsync("""" class C { void M() @@ -439,12 +426,10 @@ void M() } } """"); - } [Fact] - public async Task TestWithHoles5() - { - await TestAsync("""" + public Task TestWithHoles5() + => TestAsync("""" class C { void M() @@ -458,12 +443,10 @@ void M() } } """"); - } [Fact] - public async Task TestWithHoles6() - { - await TestAsync("""" + public Task TestWithHoles6() + => TestAsync("""" class C { void M() @@ -477,12 +460,10 @@ void M() } } """"); - } [Fact] - public async Task TestWithHoles7() - { - await TestAsync("""" + public Task TestWithHoles7() + => TestAsync("""" class C { void M() @@ -496,12 +477,10 @@ void M() } } """"); - } [Fact] - public async Task TestWithHoles8() - { - await TestAsync("""" + public Task TestWithHoles8() + => TestAsync("""" class C { void M() @@ -513,12 +492,10 @@ void M() } } """"); - } [Fact] - public async Task TestWithHoles9() - { - await TestAsync("""" + public Task TestWithHoles9() + => TestAsync("""" class C { void M() @@ -532,12 +509,10 @@ void M() } } """"); - } [Fact] - public async Task TestWithHoles10() - { - await TestAsync("""" + public Task TestWithHoles10() + => TestAsync("""" class C { void M() @@ -551,12 +526,10 @@ void M() } } """"); - } [Fact] - public async Task TestWithNestedHoles1() - { - await TestAsync("""" + public Task TestWithNestedHoles1() + => TestAsync("""" class C { void M() @@ -574,12 +547,10 @@ void M() } } """"); - } [Fact] - public async Task TestWithNestedHoles2() - { - await TestAsync("""" + public Task TestWithNestedHoles2() + => TestAsync("""" class C { void M() @@ -600,12 +571,10 @@ void M() } } """"); - } [Fact] - public async Task TestWithNestedHoles3() - { - await TestAsync("""" + public Task TestWithNestedHoles3() + => TestAsync("""" class C { void M() @@ -626,12 +595,10 @@ void M() } } """"); - } [Fact] - public async Task TestWithNestedHoles4() - { - await TestAsync("""" + public Task TestWithNestedHoles4() + => TestAsync("""" class C { void M() @@ -652,12 +619,10 @@ void M() } } """"); - } [Fact] - public async Task TestWithNestedHoles5() - { - await TestAsync("""" + public Task TestWithNestedHoles5() + => TestAsync("""" class C { void M() @@ -675,12 +640,10 @@ void M() } } """"); - } [Fact] - public async Task TestWithNestedHoles6() - { - await TestAsync("""" + public Task TestWithNestedHoles6() + => TestAsync("""" class C { void M() @@ -701,12 +664,10 @@ void M() } } """"); - } [Fact] - public async Task TestWithNestedHoles7() - { - await TestAsync("""" + public Task TestWithNestedHoles7() + => TestAsync("""" class C { void M() @@ -727,7 +688,6 @@ void M() } } """"); - } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1542623")] public async Task TestWithManyConcatenatedStrings() diff --git a/src/EditorFeatures/CSharpTest/Structure/AccessorDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/AccessorDeclarationStructureTests.cs index af609f5b9a3d4..5f609db6c9496 100644 --- a/src/EditorFeatures/CSharpTest/Structure/AccessorDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/AccessorDeclarationStructureTests.cs @@ -17,9 +17,8 @@ public sealed class AccessorDeclarationStructureTests : AbstractCSharpSyntaxNode internal override AbstractSyntaxStructureProvider CreateProvider() => new AccessorDeclarationStructureProvider(); [Fact] - public async Task TestPropertyGetter1() - { - var code = """ + public Task TestPropertyGetter1() + => VerifyBlockSpansAsync(""" class C { public string Text @@ -29,16 +28,12 @@ public string Text }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestPropertyGetterWithSingleLineComments1() - { - var code = """ + public Task TestPropertyGetterWithSingleLineComments1() + => VerifyBlockSpansAsync(""" class C { public string Text @@ -50,17 +45,13 @@ public string Text }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "// My ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestPropertyGetter2() - { - var code = """ + public Task TestPropertyGetter2() + => VerifyBlockSpansAsync(""" class C { public string Text @@ -73,16 +64,12 @@ public string Text } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestPropertyGetterWithSingleLineComments2() - { - var code = """ + public Task TestPropertyGetterWithSingleLineComments2() + => VerifyBlockSpansAsync(""" class C { public string Text @@ -97,17 +84,13 @@ public string Text } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "// My ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestPropertyGetter3() - { - var code = """ + public Task TestPropertyGetter3() + => VerifyBlockSpansAsync(""" class C { public string Text @@ -121,16 +104,12 @@ public string Text } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestPropertyGetterWithSingleLineComments3() - { - var code = """ + public Task TestPropertyGetterWithSingleLineComments3() + => VerifyBlockSpansAsync(""" class C { public string Text @@ -146,17 +125,13 @@ public string Text } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "// My ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestPropertySetter1() - { - var code = """ + public Task TestPropertySetter1() + => VerifyBlockSpansAsync(""" class C { public string Text @@ -166,16 +141,12 @@ public string Text }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestPropertySetterWithSingleLineComments1() - { - var code = """ + public Task TestPropertySetterWithSingleLineComments1() + => VerifyBlockSpansAsync(""" class C { public string Text @@ -187,17 +158,13 @@ public string Text }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "// My ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestPropertySetter2() - { - var code = """ + public Task TestPropertySetter2() + => VerifyBlockSpansAsync(""" class C { public string Text @@ -210,16 +177,12 @@ public string Text }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestPropertySetterWithSingleLineComments2() - { - var code = """ + public Task TestPropertySetterWithSingleLineComments2() + => VerifyBlockSpansAsync(""" class C { public string Text @@ -234,17 +197,13 @@ public string Text }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "// My ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestPropertySetter3() - { - var code = """ + public Task TestPropertySetter3() + => VerifyBlockSpansAsync(""" class C { public string Text @@ -258,16 +217,12 @@ public string Text }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestPropertySetterWithSingleLineComments3() - { - var code = """ + public Task TestPropertySetterWithSingleLineComments3() + => VerifyBlockSpansAsync(""" class C { public string Text @@ -283,10 +238,7 @@ public string Text }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "// My ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/AnonymousMethodExpressionStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/AnonymousMethodExpressionStructureTests.cs index 921686320d4fe..2df6199e575af 100644 --- a/src/EditorFeatures/CSharpTest/Structure/AnonymousMethodExpressionStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/AnonymousMethodExpressionStructureTests.cs @@ -17,9 +17,8 @@ public sealed class AnonymousMethodExpressionStructureTests : AbstractCSharpSynt internal override AbstractSyntaxStructureProvider CreateProvider() => new AnonymousMethodExpressionStructureProvider(); [Fact] - public async Task TestAnonymousMethod() - { - var code = """ + public Task TestAnonymousMethod() + => VerifyBlockSpansAsync(""" class C { void Main() @@ -29,16 +28,12 @@ void Main() };|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestAnonymousMethodInForLoop() - { - var code = """ + public Task TestAnonymousMethodInForLoop() + => VerifyNoBlockSpansAsync(""" class C { void Main() @@ -46,15 +41,11 @@ void Main() for (Action a = $$delegate { }; true; a()) { } } } - """; - - await VerifyNoBlockSpansAsync(code); - } + """); [Fact] - public async Task TestAnonymousMethodInMethodCall1() - { - var code = """ + public Task TestAnonymousMethodInMethodCall1() + => VerifyBlockSpansAsync(""" class C { void Main() @@ -64,16 +55,12 @@ void Main() }|}|}, "other arguments"); } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestAnonymousMethodInMethodCall2() - { - var code = """ + public Task TestAnonymousMethodInMethodCall2() + => VerifyBlockSpansAsync(""" class C { void Main() @@ -83,9 +70,6 @@ void Main() }|}|}); } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/AnonymousObjectCreationExpressionStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/AnonymousObjectCreationExpressionStructureTests.cs index 6343c2ef5ef53..e623213b12ecb 100644 --- a/src/EditorFeatures/CSharpTest/Structure/AnonymousObjectCreationExpressionStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/AnonymousObjectCreationExpressionStructureTests.cs @@ -18,9 +18,8 @@ internal override AbstractSyntaxStructureProvider CreateProvider() => new AnonymousObjectCreationExpressionStructureProvider(); [Fact] - public async Task TestAnonymousObjectCreation() - { - await VerifyBlockSpansAsync( + public Task TestAnonymousObjectCreation() + => VerifyBlockSpansAsync( """ class C { @@ -34,5 +33,4 @@ void M() } """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/ArgumentListSyntaxStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/ArgumentListSyntaxStructureTests.cs index d1844c227f744..df4174a74e022 100644 --- a/src/EditorFeatures/CSharpTest/Structure/ArgumentListSyntaxStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/ArgumentListSyntaxStructureTests.cs @@ -17,38 +17,26 @@ public sealed class ArgumentListSyntaxStructureTests : AbstractCSharpSyntaxNodeS internal override AbstractSyntaxStructureProvider CreateProvider() => new ArgumentListStructureProvider(); [Fact] - public async Task TestInvocationExpressionSingleLine() - { - var code = """ + public Task TestInvocationExpressionSingleLine() + => VerifyBlockSpansAsync(""" var x = M$$(); - """; - - await VerifyBlockSpansAsync(code); - } + """); [Fact] - public async Task TestInvocationExpressionTwoArgumentsInTwoLines() - { - var code = """ + public Task TestInvocationExpressionTwoArgumentsInTwoLines() + => VerifyBlockSpansAsync(""" var x = M$$("Hello", "World"); - """; - - await VerifyBlockSpansAsync(code); - } + """); [Fact] - public async Task TestInvocationExpressionThreeLines() - { - var code = """ + public Task TestInvocationExpressionThreeLines() + => VerifyBlockSpansAsync(""" var x = M$${|span:( "", "")|}; - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] public async Task TestTwoInvocationExpressionsThreeLines() @@ -57,68 +45,48 @@ public async Task TestTwoInvocationExpressionsThreeLines() // While this test shows both as collapsible, they will be deduplicated by AbstractBlockStructureProvider // This test only tests ArgumentListStructureProvider specifically, so it doesn't show the deduplication. // Tests in BlockStructureServiceTests show the overall behavior accurately. - var testInner = """ + + await VerifyBlockSpansAsync(""" var x = M(M$${|span:( "", "")|}); - """; - - await VerifyBlockSpansAsync(testInner, + """, Region("span", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - - var testOuter = """ + await VerifyBlockSpansAsync(""" var x = M$${|span:(M( "", ""))|}; - """; - - await VerifyBlockSpansAsync(testOuter, + """, Region("span", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [Fact] - public async Task TestObjectCreationSingleLine() - { - var code = """ + public Task TestObjectCreationSingleLine() + => VerifyBlockSpansAsync(""" var x = new C$$(); - """; - - await VerifyBlockSpansAsync(code); - } + """); [Fact] - public async Task TestObjectCreationThreeLines() - { - var code = """ + public Task TestObjectCreationThreeLines() + => VerifyBlockSpansAsync(""" var x = new C$${|span:( "", "")|}; - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestImplicitObjectCreationSingleLine() - { - var code = """ + public Task TestImplicitObjectCreationSingleLine() + => VerifyBlockSpansAsync(""" C x = new$$(); - """; - - await VerifyBlockSpansAsync(code); - } + """); [Fact] - public async Task TestImplicitObjectCreationThreeLines() - { - var code = """ + public Task TestImplicitObjectCreationThreeLines() + => VerifyBlockSpansAsync(""" C x = new$${|span:( "", "")|}; - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/ArrowExpressionClauseStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/ArrowExpressionClauseStructureTests.cs index b3d2faa1b6676..9ee29c2e6388e 100644 --- a/src/EditorFeatures/CSharpTest/Structure/ArrowExpressionClauseStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/ArrowExpressionClauseStructureTests.cs @@ -19,9 +19,8 @@ internal override AbstractSyntaxStructureProvider CreateProvider() => new ArrowExpressionClauseStructureProvider(); [Fact] - public async Task TestArrowExpressionClause_Method1() - { - await VerifyBlockSpansAsync( + public Task TestArrowExpressionClause_Method1() + => VerifyBlockSpansAsync( """ class C { @@ -31,12 +30,10 @@ class C } """, Region("textspan", "hintspan", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestArrowExpressionClause_Method2() - { - await VerifyBlockSpansAsync( + public Task TestArrowExpressionClause_Method2() + => VerifyBlockSpansAsync( """ class C { @@ -47,12 +44,10 @@ class C } """, Region("textspan", "hintspan", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestArrowExpressionClause_Method3() - { - await VerifyBlockSpansAsync( + public Task TestArrowExpressionClause_Method3() + => VerifyBlockSpansAsync( """ class C { @@ -64,12 +59,10 @@ class C } """, Region("textspan", "hintspan", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestArrowExpressionClause_Method4() - { - await VerifyBlockSpansAsync( + public Task TestArrowExpressionClause_Method4() + => VerifyBlockSpansAsync( """ class C { @@ -80,12 +73,10 @@ class C } """, Region("textspan", "hintspan", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestArrowExpressionClause_Method5() - { - await VerifyBlockSpansAsync( + public Task TestArrowExpressionClause_Method5() + => VerifyBlockSpansAsync( """ class C { @@ -97,12 +88,10 @@ class C } """, Region("textspan", "hintspan", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestArrowExpressionClause_Property1() - { - await VerifyBlockSpansAsync( + public Task TestArrowExpressionClause_Property1() + => VerifyBlockSpansAsync( """ class C { @@ -112,12 +101,10 @@ class C } """, Region("textspan", "hintspan", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestArrowExpressionClause_Property2() - { - await VerifyBlockSpansAsync( + public Task TestArrowExpressionClause_Property2() + => VerifyBlockSpansAsync( """ class C { @@ -128,12 +115,10 @@ class C } """, Region("textspan", "hintspan", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestArrowExpressionClause_Property3() - { - await VerifyBlockSpansAsync( + public Task TestArrowExpressionClause_Property3() + => VerifyBlockSpansAsync( """ class C { @@ -145,12 +130,10 @@ class C } """, Region("textspan", "hintspan", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestArrowExpressionClause_Property4() - { - await VerifyBlockSpansAsync( + public Task TestArrowExpressionClause_Property4() + => VerifyBlockSpansAsync( """ class C { @@ -161,12 +144,10 @@ class C } """, Region("textspan", "hintspan", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestArrowExpressionClause_Property5() - { - await VerifyBlockSpansAsync( + public Task TestArrowExpressionClause_Property5() + => VerifyBlockSpansAsync( """ class C { @@ -178,12 +159,10 @@ class C } """, Region("textspan", "hintspan", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestArrowExpressionClause_LocalFunction() - { - await VerifyBlockSpansAsync( + public Task TestArrowExpressionClause_LocalFunction() + => VerifyBlockSpansAsync( """ class C { @@ -196,12 +175,10 @@ void M() } """, Region("textspan", "hintspan", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76820")] - public async Task TestArrowExpressionClause_DirectiveOutsideOfArrow() - { - await VerifyBlockSpansAsync( + public Task TestArrowExpressionClause_DirectiveOutsideOfArrow() + => VerifyBlockSpansAsync( """ class C { @@ -215,12 +192,10 @@ int M() => } """, Region("textspan", "hintspan", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76820")] - public async Task TestArrowExpressionClause_DirectiveInsideOfArrow() - { - await VerifyBlockSpansAsync( + public Task TestArrowExpressionClause_DirectiveInsideOfArrow() + => VerifyBlockSpansAsync( """ class C { @@ -233,5 +208,4 @@ class C } """, Region("textspan", "hintspan", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/BlockSyntaxStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/BlockSyntaxStructureTests.cs index 1d4feb02e239b..4ecb086167dc8 100644 --- a/src/EditorFeatures/CSharpTest/Structure/BlockSyntaxStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/BlockSyntaxStructureTests.cs @@ -18,9 +18,8 @@ public sealed class BlockSyntaxStructureTests : AbstractCSharpSyntaxNodeStructur internal override AbstractSyntaxStructureProvider CreateProvider() => new BlockSyntaxStructureProvider(); [Fact] - public async Task TestTryBlock1() - { - var code = """ + public Task TestTryBlock1() + => VerifyBlockSpansAsync(""" class C { void M() @@ -36,16 +35,12 @@ void M() }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestUnsafe1() - { - var code = """ + public Task TestUnsafe1() + => VerifyBlockSpansAsync(""" class C { void M() @@ -55,16 +50,12 @@ void M() }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestFixed1() - { - var code = """ + public Task TestFixed1() + => VerifyBlockSpansAsync(""" class C { void M() @@ -74,16 +65,12 @@ void M() }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestUsing1() - { - var code = """ + public Task TestUsing1() + => VerifyBlockSpansAsync(""" class C { void M() @@ -93,16 +80,12 @@ void M() }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestLock1() - { - var code = """ + public Task TestLock1() + => VerifyBlockSpansAsync(""" class C { void M() @@ -112,16 +95,12 @@ void M() }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestForStatement1() - { - var code = """ + public Task TestForStatement1() + => VerifyBlockSpansAsync(""" class C { void M() @@ -131,16 +110,12 @@ void M() }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestForEachStatement1() - { - var code = """ + public Task TestForEachStatement1() + => VerifyBlockSpansAsync(""" class C { void M() @@ -150,16 +125,12 @@ void M() }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestCompoundForEachStatement1() - { - var code = """ + public Task TestCompoundForEachStatement1() + => VerifyBlockSpansAsync(""" class C { void M() @@ -169,16 +140,12 @@ void M() }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestWhileStatement1() - { - var code = """ + public Task TestWhileStatement1() + => VerifyBlockSpansAsync(""" class C { void M() @@ -188,16 +155,12 @@ void M() }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestDoStatement1() - { - var code = """ + public Task TestDoStatement1() + => VerifyBlockSpansAsync(""" class C { void M() @@ -208,16 +171,12 @@ void M() while (true);|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestIfStatement1() - { - var code = """ + public Task TestIfStatement1() + => VerifyBlockSpansAsync(""" class C { void M() @@ -227,16 +186,12 @@ void M() }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestIfStatement2() - { - var code = """ + public Task TestIfStatement2() + => VerifyBlockSpansAsync(""" class C { void M() @@ -249,16 +204,12 @@ void M() } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestIfStatement3() - { - var code = """ + public Task TestIfStatement3() + => VerifyBlockSpansAsync(""" class C { void M() @@ -270,16 +221,12 @@ void M() return; } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestElseClause1() - { - var code = """ + public Task TestElseClause1() + => VerifyBlockSpansAsync(""" class C { void M() @@ -292,16 +239,12 @@ void M() }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestElseClause2() - { - var code = """ + public Task TestElseClause2() + => VerifyBlockSpansAsync(""" class C { void M() @@ -314,16 +257,12 @@ void M() }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestIfElse1() - { - var code = """ + public Task TestIfElse1() + => VerifyBlockSpansAsync(""" class C { void M() @@ -336,16 +275,12 @@ void M() }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestIfElse2() - { - var code = """ + public Task TestIfElse2() + => VerifyBlockSpansAsync(""" class C { void M() @@ -360,16 +295,12 @@ void M() }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestIfElse3() - { - var code = """ + public Task TestIfElse3() + => VerifyBlockSpansAsync(""" class C { void M() @@ -383,16 +314,12 @@ void M() }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestNestedBlock() - { - var code = """ + public Task TestNestedBlock() + => VerifyBlockSpansAsync(""" class C { void M() @@ -402,16 +329,12 @@ void M() }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestNestedBlockInSwitchSection1() - { - var code = """ + public Task TestNestedBlockInSwitchSection1() + => VerifyBlockSpansAsync(""" class C { void M() @@ -425,16 +348,12 @@ void M() } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestNestedBlockInSwitchSection2() - { - var code = """ + public Task TestNestedBlockInSwitchSection2() + => VerifyBlockSpansAsync(""" class C { void M() @@ -449,16 +368,12 @@ void M() } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact, WorkItem(52493, "https://github.com/dotnet/roslyn/issues/")] - public async Task LocalFunctionInTopLevelStatement_AutoCollapse() - { - var code = """ + public Task LocalFunctionInTopLevelStatement_AutoCollapse() + => VerifyBlockSpansAsync(""" Goo(); Bar(); @@ -466,17 +381,13 @@ public async Task LocalFunctionInTopLevelStatement_AutoCollapse() {$$ {|hint2:{|textspan2:// comment|}|} }|}|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("textspan2", "hint2", "// comment ...", autoCollapse: true)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68513")] - public async Task LocalFunctionInBodyRespectOption1() - { - var code = """ + public Task LocalFunctionInBodyRespectOption1() + => VerifyBlockSpansAsync(""" class C { void M() @@ -487,17 +398,13 @@ void M() }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("textspan2", "hint2", "// comment ...", autoCollapse: true)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68513")] - public async Task LocalFunctionInBodyRespectOption2() - { - var code = """ + public Task LocalFunctionInBodyRespectOption2() + => VerifyBlockSpansAsync(""" class C { void M() @@ -508,12 +415,9 @@ void M() }|}|} } } - """; - - await VerifyBlockSpansAsync(code, GetDefaultOptions() with + """, GetDefaultOptions() with { CollapseLocalFunctionsWhenCollapsingToDefinitions = true, }, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("textspan2", "hint2", "// comment ...", autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/CollectionExpressionStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/CollectionExpressionStructureTests.cs index d88264c1717eb..ecad448eae255 100644 --- a/src/EditorFeatures/CSharpTest/Structure/CollectionExpressionStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/CollectionExpressionStructureTests.cs @@ -20,9 +20,8 @@ internal override AbstractSyntaxStructureProvider CreateProvider() [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/71932")] - public async Task TestOuterCollectionExpression() - { - await VerifyBlockSpansAsync( + public Task TestOuterCollectionExpression() + => VerifyBlockSpansAsync( """ class C { @@ -37,13 +36,11 @@ void M() } """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/71932")] - public async Task TestInnerCollectionExpressionWithoutComma() - { - await VerifyBlockSpansAsync( + public Task TestInnerCollectionExpressionWithoutComma() + => VerifyBlockSpansAsync( """ class C { @@ -61,13 +58,11 @@ void M() } """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/71932")] - public async Task TestInnerCollectionExpressionWithComma() - { - await VerifyBlockSpansAsync( + public Task TestInnerCollectionExpressionWithComma() + => VerifyBlockSpansAsync( """ class C { @@ -85,5 +80,4 @@ void M() } """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/CommentStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/CommentStructureTests.cs index 52b30d230a814..973f5ece09b18 100644 --- a/src/EditorFeatures/CSharpTest/Structure/CommentStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/CommentStructureTests.cs @@ -50,56 +50,43 @@ internal override async Task> GetBlockSpansWorkerAsync } [Fact] - public async Task TestSimpleComment1() - { - var code = """ + public Task TestSimpleComment1() + => VerifyBlockSpansAsync(""" {|span:// Hello // $$C#|} class C { } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "// Hello ...", autoCollapse: true)); - } [Fact] - public async Task TestSimpleComment2() - { - var code = """ + public Task TestSimpleComment2() + => VerifyBlockSpansAsync(""" {|span:// Hello // // $$C#!|} class C { } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "// Hello ...", autoCollapse: true)); - } [Fact] - public async Task TestSimpleComment3() - { - var code = """ + public Task TestSimpleComment3() + => VerifyBlockSpansAsync(""" {|span:// Hello // $$C#!|} class C { } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "// Hello ...", autoCollapse: true)); - } [Fact] - public async Task TestSingleLineCommentGroupFollowedByDocumentationComment() - { - var code = """ + public Task TestSingleLineCommentGroupFollowedByDocumentationComment() + => VerifyBlockSpansAsync(""" {|span:// Hello // $$C#!|} @@ -107,9 +94,6 @@ public async Task TestSingleLineCommentGroupFollowedByDocumentationComment() class C { } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "// Hello ...", autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/CompilationUnitStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/CompilationUnitStructureTests.cs index 0a8f138188eec..574a1cadcce7c 100644 --- a/src/EditorFeatures/CSharpTest/Structure/CompilationUnitStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/CompilationUnitStructureTests.cs @@ -18,61 +18,44 @@ public sealed class CompilationUnitStructureTests : AbstractCSharpSyntaxNodeStru internal override AbstractSyntaxStructureProvider CreateProvider() => new CompilationUnitStructureProvider(); [Fact] - public async Task TestUsings() - { - var code = """ + public Task TestUsings() + => VerifyBlockSpansAsync(""" $${|hint:using {|textspan:System; using System.Core;|}|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestUsingAliases() - { - var code = """ + public Task TestUsingAliases() + => VerifyBlockSpansAsync(""" $${|hint:using {|textspan:System; using System.Core; using text = System.Text; using linq = System.Linq;|}|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestExternAliases() - { - var code = """ + public Task TestExternAliases() + => VerifyBlockSpansAsync(""" $${|hint:extern {|textspan:alias Goo; extern alias Bar;|}|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestExternAliasesAndUsings() - { - var code = """ + public Task TestExternAliasesAndUsings() + => VerifyBlockSpansAsync(""" $${|hint:extern {|textspan:alias Goo; extern alias Bar; using System; using System.Core;|}|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestExternAliasesAndUsingsWithLeadingTrailingAndNestedComments() - { - var code = """ + public Task TestExternAliasesAndUsingsWithLeadingTrailingAndNestedComments() + => VerifyBlockSpansAsync(""" $${|span1:// Goo // Bar|} {|hint2:extern {|textspan2:alias Goo; @@ -83,95 +66,70 @@ public async Task TestExternAliasesAndUsingsWithLeadingTrailingAndNestedComments using System.Core;|}|} {|span3:// Goo // Bar|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("span3", "// Goo ...", autoCollapse: true)); - } [Fact] - public async Task TestUsingsWithComments() - { - var code = """ + public Task TestUsingsWithComments() + => VerifyBlockSpansAsync(""" $${|span1:// Goo // Bar|} {|hint2:using {|textspan2:System; using System.Core;|}|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestExternAliasesWithComments() - { - var code = """ + public Task TestExternAliasesWithComments() + => VerifyBlockSpansAsync(""" $${|span1:// Goo // Bar|} {|hint2:extern {|textspan2:alias Goo; extern alias Bar;|}|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestWithComments() - { - var code = """ + public Task TestWithComments() + => VerifyBlockSpansAsync(""" $${|span1:// Goo // Bar|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "// Goo ...", autoCollapse: true)); - } [Fact] - public async Task TestWithCommentsAtEnd() - { - var code = """ + public Task TestWithCommentsAtEnd() + => VerifyBlockSpansAsync(""" $${|hint1:using {|textspan1:System;|}|} {|span2:// Goo // Bar|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("span2", "// Goo ...", autoCollapse: true)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539359")] - public async Task TestUsingKeywordWithSpace() - { - var code = """ + public Task TestUsingKeywordWithSpace() + => VerifyBlockSpansAsync(""" $${|hint:using|} {|textspan:|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Theory, CombinatorialData] public async Task TestUsingsShouldBeCollapsedByDefault(bool collapseUsingsByDefault) { - var code = """ - $${|hint:using {|textspan:System; - using System.Core;|}|} - """; - var options = GetDefaultOptions() with { CollapseImportsWhenFirstOpened = collapseUsingsByDefault }; - await VerifyBlockSpansAsync(code, options, + await VerifyBlockSpansAsync(""" + $${|hint:using {|textspan:System; + using System.Core;|}|} + """, options, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true, isDefaultCollapsed: collapseUsingsByDefault)); } } diff --git a/src/EditorFeatures/CSharpTest/Structure/ConstructorDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/ConstructorDeclarationStructureTests.cs index f81fd2ed4f3e4..121b017b13d9f 100644 --- a/src/EditorFeatures/CSharpTest/Structure/ConstructorDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/ConstructorDeclarationStructureTests.cs @@ -18,105 +18,80 @@ public sealed class ConstructorDeclarationStructureTests : AbstractCSharpSyntaxN internal override AbstractSyntaxStructureProvider CreateProvider() => new ConstructorDeclarationStructureProvider(); [Fact] - public async Task TestConstructor1() - { - var code = """ + public Task TestConstructor1() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public C(){|textspan: { }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestConstructor2() - { - var code = """ + public Task TestConstructor2() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public C(){|textspan: { } |}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestConstructor3() - { - var code = """ + public Task TestConstructor3() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public C(){|textspan: { }|}|} // .ctor } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestConstructor4() - { - var code = """ + public Task TestConstructor4() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public C(){|textspan: { }|}|} /* .ctor */ } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestConstructor5() - { - var code = """ + public Task TestConstructor5() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public C() // .ctor{|textspan: { }|}|} // .ctor } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestConstructor6() - { - var code = """ + public Task TestConstructor6() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public C() /* .ctor */{|textspan: { }|}|} // .ctor } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68778")] - public async Task TestConstructor7() - { - var code = """ + public Task TestConstructor7() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public C(){|textspan: @@ -124,16 +99,12 @@ class C { }|}|} // .ctor } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68778")] - public async Task TestConstructor8() - { - var code = """ + public Task TestConstructor8() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public C(){|textspan: @@ -141,16 +112,12 @@ class C { }|}|} // .ctor } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestConstructor9() - { - var code = """ + public Task TestConstructor9() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public C(){|textspan: @@ -160,16 +127,12 @@ public C() { } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestConstructor10() - { - var code = """ + public Task TestConstructor10() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public C(){|textspan: @@ -180,16 +143,12 @@ public C(int x) { } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestConstructorWithComments() - { - var code = """ + public Task TestConstructorWithComments() + => VerifyBlockSpansAsync(""" class C { {|span1:// Goo @@ -198,25 +157,17 @@ class C { }|}|} // .ctor } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestConstructorMissingCloseParenAndBody() - { + public Task TestConstructorMissingCloseParenAndBody() // Expected behavior is that the class should be outlined, but the constructor should not. - - var code = """ + => VerifyNoBlockSpansAsync(""" class C { $$C( } - """; - - await VerifyNoBlockSpansAsync(code); - } + """); } diff --git a/src/EditorFeatures/CSharpTest/Structure/ConversionOperatorDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/ConversionOperatorDeclarationStructureTests.cs index ff90c2cd6fa30..1465c63f0aead 100644 --- a/src/EditorFeatures/CSharpTest/Structure/ConversionOperatorDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/ConversionOperatorDeclarationStructureTests.cs @@ -17,25 +17,20 @@ public sealed class ConversionOperatorDeclarationStructureTests : AbstractCSharp internal override AbstractSyntaxStructureProvider CreateProvider() => new ConversionOperatorDeclarationStructureProvider(); [Fact] - public async Task TestOperator1() - { - var code = """ + public Task TestOperator1() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public static explicit operator C(byte i){|textspan: { }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestOperator2() - { - var code = """ + public Task TestOperator2() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public static explicit operator C(byte i){|textspan: @@ -45,16 +40,12 @@ public static explicit operator C(short i) { } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestOperator3() - { - var code = """ + public Task TestOperator3() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public static explicit operator C(byte i){|textspan: @@ -65,16 +56,12 @@ public static explicit operator C(short i) { } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestOperatorWithLeadingComments() - { - var code = """ + public Task TestOperatorWithLeadingComments() + => VerifyBlockSpansAsync(""" class C { {|span1:// Goo @@ -83,10 +70,7 @@ class C { }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/DelegateDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/DelegateDeclarationStructureTests.cs index c8383744b2df3..e7c142fb5a463 100644 --- a/src/EditorFeatures/CSharpTest/Structure/DelegateDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/DelegateDeclarationStructureTests.cs @@ -16,15 +16,11 @@ public sealed class DelegateDeclarationStructureTests : AbstractCSharpSyntaxNode internal override AbstractSyntaxStructureProvider CreateProvider() => new DelegateDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] - public async Task TestDelegateWithComments() - { - var code = """ + public Task TestDelegateWithComments() + => VerifyBlockSpansAsync(""" {|span:// Goo // Bar|} $$public delegate void C(); - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "// Goo ...", autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/DestructorDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/DestructorDeclarationStructureTests.cs index 9075cb03839d0..9959ca9be5be4 100644 --- a/src/EditorFeatures/CSharpTest/Structure/DestructorDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/DestructorDeclarationStructureTests.cs @@ -17,25 +17,20 @@ public sealed class DestructorDeclarationStructureTests : AbstractCSharpSyntaxNo internal override AbstractSyntaxStructureProvider CreateProvider() => new DestructorDeclarationStructureProvider(); [Fact] - public async Task TestDestructor() - { - var code = """ + public Task TestDestructor() + => VerifyBlockSpansAsync(""" class C { {|hint:$$~C(){|textspan: { }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestDestructorWithComments() - { - var code = """ + public Task TestDestructorWithComments() + => VerifyBlockSpansAsync(""" class C { {|span1:// Goo @@ -44,25 +39,17 @@ class C { }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestDestructorMissingCloseParenAndBody() - { + public Task TestDestructorMissingCloseParenAndBody() // Expected behavior is that the class should be outlined, but the destructor should not. - - var code = """ + => VerifyNoBlockSpansAsync(""" class C { $$~C( } - """; - - await VerifyNoBlockSpansAsync(code); - } + """); } diff --git a/src/EditorFeatures/CSharpTest/Structure/DisabledTextStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/DisabledTextStructureTests.cs index e9114a8a75ad4..44c691ea761d8 100644 --- a/src/EditorFeatures/CSharpTest/Structure/DisabledTextStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/DisabledTextStructureTests.cs @@ -17,56 +17,43 @@ public sealed class DisabledTextStructureTests : AbstractCSharpSyntaxTriviaStruc internal override AbstractSyntaxStructureProvider CreateProvider() => new DisabledTextTriviaStructureProvider(); [Fact] - public async Task TestDisabledIf() - { - var code = """ + public Task TestDisabledIf() + => VerifyBlockSpansAsync(""" #if false {|span:$$Blah Blah Blah|} #endif - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestDisabledElse() - { - var code = """ + public Task TestDisabledElse() + => VerifyBlockSpansAsync(""" #if true #else {|span:$$Blah Blah Blah|} #endif - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestDisabledElIf() - { - var code = """ + public Task TestDisabledElIf() + => VerifyBlockSpansAsync(""" #if true #elif false {|span:$$Blah Blah Blah|} #endif - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531360")] - public async Task DisabledCodeWithEmbeddedPreprocessorDirectivesShouldCollapseEntireDisabledRegion() - { - var code = """ + public Task DisabledCodeWithEmbeddedPreprocessorDirectivesShouldCollapseEntireDisabledRegion() + => VerifyBlockSpansAsync(""" class P { #if false {|span: void $$M() @@ -77,16 +64,12 @@ class P { }|} #endif } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531360")] - public async Task DisabledCodeShouldNotCollapseUnlessItFollowsADirective() - { - var code = """ + public Task DisabledCodeShouldNotCollapseUnlessItFollowsADirective() + => VerifyNoBlockSpansAsync(""" class P { #if false {|span: void M() @@ -97,15 +80,11 @@ class P { }|} #endif } - """; - - await VerifyNoBlockSpansAsync(code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070677")] - public async Task NestedDisabledCodePreProcessorDirectivesShouldCollapseEntireDisabledRegion() - { - var code = """ + public Task NestedDisabledCodePreProcessorDirectivesShouldCollapseEntireDisabledRegion() + => VerifyBlockSpansAsync(""" class P { #if Goo {|span: void $$M() @@ -116,16 +95,12 @@ class P { }|} #endif } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=459257")] - public async Task NestedDisabledCodePreProcessorDirectivesWithElseShouldCollapseEntireDisabledRegion() - { - var code = """ + public Task NestedDisabledCodePreProcessorDirectivesWithElseShouldCollapseEntireDisabledRegion() + => VerifyBlockSpansAsync(""" class P { #if Goo {|span: void $$M() @@ -138,16 +113,12 @@ class P { }|} #endif } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=459257")] - public async Task NestedDisabledCodePreProcessorDirectivesWithElifShouldCollapseEntireDisabledRegion() - { - var code = """ + public Task NestedDisabledCodePreProcessorDirectivesWithElifShouldCollapseEntireDisabledRegion() + => VerifyBlockSpansAsync(""" class P { #if Goo {|span: void $$M() @@ -160,16 +131,12 @@ class P { }|} #endif } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=459257")] - public async Task NestedDisabledCodePreProcessorDirectivesWithElseAndElifShouldCollapseEntireDisabledRegion() - { - var code = """ + public Task NestedDisabledCodePreProcessorDirectivesWithElseAndElifShouldCollapseEntireDisabledRegion() + => VerifyBlockSpansAsync(""" class P { #if Goo {|span: void $$M() @@ -184,16 +151,12 @@ class P { }|} #endif } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070677")] - public async Task NestedDisabledCodePreProcessorDirectivesShouldCollapseEntireDisabledRegion2() - { - var code = """ + public Task NestedDisabledCodePreProcessorDirectivesShouldCollapseEntireDisabledRegion2() + => VerifyBlockSpansAsync(""" class P { #if Goo void M() @@ -205,16 +168,12 @@ void M() } #endif } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070677")] - public async Task NestedDisabledCodePreProcessorDirectivesShouldCollapseEntireDisabledRegion3() - { - var code = """ + public Task NestedDisabledCodePreProcessorDirectivesShouldCollapseEntireDisabledRegion3() + => VerifyBlockSpansAsync(""" class P { #if Goo {|span: void $$M() @@ -225,16 +184,12 @@ class P { } #endif } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070677")] - public async Task NestedDisabledCodePreProcessorDirectivesShouldCollapseEntireDisabledRegion4() - { - var code = """ + public Task NestedDisabledCodePreProcessorDirectivesShouldCollapseEntireDisabledRegion4() + => VerifyBlockSpansAsync(""" class P { #if Goo {|span: void $$M() @@ -254,16 +209,12 @@ class P { }|} #endif } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1100600")] - public async Task PreprocessorDirectivesInTrailingTrivia() - { - var code = """ + public Task PreprocessorDirectivesInTrailingTrivia() + => VerifyBlockSpansAsync(""" class P { #if Goo {|span: void $$M() @@ -283,9 +234,6 @@ class P { }|} #endif } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/DocumentationCommentStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/DocumentationCommentStructureTests.cs index f21d0cb3b6dab..d2fd4d3864ce1 100644 --- a/src/EditorFeatures/CSharpTest/Structure/DocumentationCommentStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/DocumentationCommentStructureTests.cs @@ -18,9 +18,8 @@ public sealed class DocumentationCommentStructureTests : AbstractCSharpSyntaxNod internal override AbstractSyntaxStructureProvider CreateProvider() => new DocumentationCommentStructureProvider(); [Fact] - public async Task TestDocumentationCommentWithoutSummaryTag1() - { - var code = """ + public Task TestDocumentationCommentWithoutSummaryTag1() + => VerifyBlockSpansAsync(""" {|span:/// $$XML doc comment /// some description /// of @@ -28,16 +27,12 @@ public async Task TestDocumentationCommentWithoutSummaryTag1() class Class3 { } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "/// XML doc comment ...", autoCollapse: true)); - } [Fact] - public async Task TestDocumentationCommentWithoutSummaryTag2() - { - var code = """ + public Task TestDocumentationCommentWithoutSummaryTag2() + => VerifyBlockSpansAsync(""" {|span:/** $$Block comment * some description * of @@ -46,41 +41,30 @@ public async Task TestDocumentationCommentWithoutSummaryTag2() class Class3 { } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "/** Block comment ...", autoCollapse: true)); - } [Fact] - public async Task TestDocumentationCommentWithoutSummaryTag3() - { - var code = """ + public Task TestDocumentationCommentWithoutSummaryTag3() + => VerifyBlockSpansAsync(""" {|span:/// $$|} class Class3 { } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "/// ...", autoCollapse: true)); - } [Fact] - public async Task TestDocumentationComment() - { - var code = """ + public Task TestDocumentationComment() + => VerifyBlockSpansAsync(""" {|span:/// /// $$Hello C#! /// |} class Class3 { } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "/// Hello C#!", autoCollapse: true)); - } [Fact] public async Task TestDocumentationCommentWithLongBannerText() @@ -100,113 +84,84 @@ await VerifyBlockSpansAsync(code, } [Fact] - public async Task TestMultilineDocumentationComment() - { - var code = """ + public Task TestMultilineDocumentationComment() + => VerifyBlockSpansAsync(""" {|span:/** $$Hello C#! */|} class Class3 { } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "/** Hello C#!", autoCollapse: true)); - } [Fact] - public async Task TestIndentedDocumentationComment() - { - var code = """ + public Task TestIndentedDocumentationComment() + => VerifyBlockSpansAsync(""" {|span:/// /// $$Hello C#! /// |} class Class3 { } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "/// Hello C#!", autoCollapse: true)); - } [Fact] - public async Task TestIndentedMultilineDocumentationComment() - { - var code = """ + public Task TestIndentedMultilineDocumentationComment() + => VerifyBlockSpansAsync(""" {|span:/** $$Hello C#! */|} class Class3 { } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "/** Hello C#!", autoCollapse: true)); - } [Fact] - public async Task TestDocumentationCommentOnASingleLine() - { - var code = """ + public Task TestDocumentationCommentOnASingleLine() + => VerifyBlockSpansAsync(""" {|span:/// $$Hello C#!|} class Class3 { } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "/// Hello C#!", autoCollapse: true)); - } [Fact] - public async Task TestMultilineDocumentationCommentOnASingleLine() - { - var code = """ + public Task TestMultilineDocumentationCommentOnASingleLine() + => VerifyBlockSpansAsync(""" {|span:/** $$Hello C#! */|} class Class3 { } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "/** Hello C#!", autoCollapse: true)); - } [Fact] - public async Task TestIndentedDocumentationCommentOnASingleLine() - { - var code = """ + public Task TestIndentedDocumentationCommentOnASingleLine() + => VerifyBlockSpansAsync(""" {|span:/// $$Hello C#!|} class Class3 { } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "/// Hello C#!", autoCollapse: true)); - } [Fact] - public async Task TestIndentedMultilineDocumentationCommentOnASingleLine() - { - var code = """ + public Task TestIndentedMultilineDocumentationCommentOnASingleLine() + => VerifyBlockSpansAsync(""" {|span:/** $$Hello C#! */|} class Class3 { } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "/** Hello C#!", autoCollapse: true)); - } [Fact] - public async Task TestMultilineSummaryInDocumentationComment1() - { - var code = """ + public Task TestMultilineSummaryInDocumentationComment1() + => VerifyBlockSpansAsync(""" {|span:/// /// $$Hello /// C#! @@ -214,16 +169,12 @@ public async Task TestMultilineSummaryInDocumentationComment1() class Class3 { } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "/// Hello C#!", autoCollapse: true)); - } [Fact] - public async Task TestMultilineSummaryInDocumentationComment2() - { - var code = """ + public Task TestMultilineSummaryInDocumentationComment2() + => VerifyBlockSpansAsync(""" {|span:/// /// $$Hello /// @@ -232,16 +183,12 @@ public async Task TestMultilineSummaryInDocumentationComment2() class Class3 { } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "/// Hello C#!", autoCollapse: true)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2129")] - public async Task CrefInSummary() - { - var code = """ + public Task CrefInSummary() + => VerifyBlockSpansAsync(""" class C { {|span:/// $$ @@ -250,16 +197,12 @@ class C /// |} public void M(T t) { } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "/// Summary with SeeClass, SeeAlsoClass, null, T, t, and not-supported.", autoCollapse: true)); - } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=402822")] - public async Task TestSummaryWithPunctuation() - { - var code = """ + public Task TestSummaryWithPunctuation() + => VerifyBlockSpansAsync(""" class C { {|span:/// $$ @@ -270,16 +213,12 @@ void Main() { } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "/// The main entrypoint for Program.", autoCollapse: true)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20679")] - public async Task TestSummaryWithAdditionalTags() - { - var code = """ + public Task TestSummaryWithAdditionalTags() + => VerifyBlockSpansAsync(""" public class Class1 { {|span:/// $$ @@ -290,9 +229,6 @@ public Class1() } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "/// Initializes a new instance of the Class1 class.", autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/EnumDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/EnumDeclarationStructureTests.cs index 64c987170924c..acc855fe6a684 100644 --- a/src/EditorFeatures/CSharpTest/Structure/EnumDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/EnumDeclarationStructureTests.cs @@ -17,86 +17,68 @@ public sealed class EnumDeclarationStructureTests : AbstractCSharpSyntaxNodeStru internal override AbstractSyntaxStructureProvider CreateProvider() => new EnumDeclarationStructureProvider(); [Fact] - public async Task TestEnum1() - { - var code = """ + public Task TestEnum1() + => VerifyBlockSpansAsync(""" {|hint:$$enum E{|textspan: { }|}|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Theory] [InlineData("enum")] [InlineData("struct")] [InlineData("class")] [InlineData("interface")] - public async Task TestEnum2(string typeKind) - { - var code = $@" -{{|hint:$$enum E{{|textspan: -{{ -}}|}}|}} -{typeKind} Following -{{ -}}"; - - await VerifyBlockSpansAsync(code, + public Task TestEnum2(string typeKind) + => VerifyBlockSpansAsync($$""" + {|hint:$$enum E{|textspan: + { + }|}|} + {{typeKind}} Following + { + } + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Theory] [InlineData("enum")] [InlineData("struct")] [InlineData("class")] [InlineData("interface")] - public async Task TestEnum3(string typeKind) - { - var code = $@" -{{|hint:$$enum E{{|textspan: -{{ -}}|}}|}} - -{typeKind} Following -{{ -}}"; + public Task TestEnum3(string typeKind) + => VerifyBlockSpansAsync($$""" + {|hint:$$enum E{|textspan: + { + }|}|} - await VerifyBlockSpansAsync(code, + {{typeKind}} Following + { + } + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestEnumWithLeadingComments() - { - var code = """ + public Task TestEnumWithLeadingComments() + => VerifyBlockSpansAsync(""" {|span1:// Goo // Bar|} {|hint2:$$enum E{|textspan2: { }|}|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestEnumWithNestedComments() - { - var code = """ + public Task TestEnumWithNestedComments() + => VerifyBlockSpansAsync(""" {|hint1:$$enum E{|textspan1: { {|span2:// Goo // Bar|} }|}|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("span2", "// Goo ...", autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/EventDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/EventDeclarationStructureTests.cs index 21c7f6e4effcc..ae1114af29891 100644 --- a/src/EditorFeatures/CSharpTest/Structure/EventDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/EventDeclarationStructureTests.cs @@ -17,9 +17,8 @@ public sealed class EventDeclarationStructureTests : AbstractCSharpSyntaxNodeStr internal override AbstractSyntaxStructureProvider CreateProvider() => new EventDeclarationStructureProvider(); [Fact] - public async Task TestEvent1() - { - var code = """ + public Task TestEvent1() + => VerifyBlockSpansAsync(""" class C { {|hint:$$event EventHandler E{|textspan: @@ -28,16 +27,12 @@ class C remove { } }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestEvent2() - { - var code = """ + public Task TestEvent2() + => VerifyBlockSpansAsync(""" class C { {|hint:$$event EventHandler E{|textspan: @@ -51,16 +46,12 @@ event EventHandler E2 remove { } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestEvent3() - { - var code = """ + public Task TestEvent3() + => VerifyBlockSpansAsync(""" class C { {|hint:$$event EventHandler E{|textspan: @@ -75,16 +66,12 @@ event EventHandler E2 remove { } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestEvent4() - { - var code = """ + public Task TestEvent4() + => VerifyBlockSpansAsync(""" class C { {|hint:$$event EventHandler E{|textspan: @@ -99,16 +86,12 @@ EventHandler E2 set; } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestEvent5() - { - var code = """ + public Task TestEvent5() + => VerifyBlockSpansAsync(""" class C { {|hint:$$event EventHandler E{|textspan: @@ -123,16 +106,12 @@ EventHandler this[int index] set => throw null; } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestEventWithComments() - { - var code = """ + public Task TestEventWithComments() + => VerifyBlockSpansAsync(""" class C { {|span1:// Goo @@ -143,10 +122,7 @@ class C remove { } }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/EventFieldDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/EventFieldDeclarationStructureTests.cs index 59e7027e56025..b86133e210e37 100644 --- a/src/EditorFeatures/CSharpTest/Structure/EventFieldDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/EventFieldDeclarationStructureTests.cs @@ -16,18 +16,14 @@ public sealed class EventFieldDeclarationStructureTests : AbstractCSharpSyntaxNo internal override AbstractSyntaxStructureProvider CreateProvider() => new EventFieldDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] - public async Task TestEventFieldWithComments() - { - var code = """ + public Task TestEventFieldWithComments() + => VerifyBlockSpansAsync(""" class C { {|span:// Goo // Bar|} $$event EventHandler E; } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "// Goo ...", autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/FieldDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/FieldDeclarationStructureTests.cs index fa84286aef96e..70abcce3947b3 100644 --- a/src/EditorFeatures/CSharpTest/Structure/FieldDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/FieldDeclarationStructureTests.cs @@ -16,18 +16,14 @@ public sealed class FieldDeclarationStructureTests : AbstractCSharpSyntaxNodeStr internal override AbstractSyntaxStructureProvider CreateProvider() => new FieldDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] - public async Task TestFieldWithComments() - { - var code = """ + public Task TestFieldWithComments() + => VerifyBlockSpansAsync(""" class C { {|span:// Goo // Bar|} $$int F; } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "// Goo ...", autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/IfDirectiveTriviaStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/IfDirectiveTriviaStructureTests.cs index 5901e1bc2c5a7..8b7cca2edb183 100644 --- a/src/EditorFeatures/CSharpTest/Structure/IfDirectiveTriviaStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/IfDirectiveTriviaStructureTests.cs @@ -18,9 +18,8 @@ public sealed class IfDirectiveTriviaStructureTests : AbstractCSharpSyntaxNodeSt internal override AbstractSyntaxStructureProvider CreateProvider() => new IfDirectiveTriviaStructureProvider(); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/10426")] - public async Task TestEnabledIfDisabledElifDisabledElse() - { - var code = """ + public Task TestEnabledIfDisabledElifDisabledElse() + => VerifyBlockSpansAsync(""" #$$if true {|span:class C { @@ -34,16 +33,12 @@ class E { } #endif - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/10426")] - public async Task TestDisabledIfEnabledElifDisabledElse() - { - var code = """ + public Task TestDisabledIfEnabledElifDisabledElse() + => VerifyBlockSpansAsync(""" #$$if false class C { @@ -57,16 +52,12 @@ class E { } #endif - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/10426")] - public async Task TestDisabledIfDisabledElifEnabledElse() - { - var code = """ + public Task TestDisabledIfDisabledElifEnabledElse() + => VerifyBlockSpansAsync(""" #$$if false class C { @@ -80,16 +71,12 @@ class D { }|} #endif - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/10426")] - public async Task TestEmptyEnabledRegion() - { - var code = """ + public Task TestEmptyEnabledRegion() + => VerifyBlockSpansAsync(""" #$$if true #elif false class D @@ -100,28 +87,20 @@ class E { } #endif - """; - - await VerifyBlockSpansAsync(code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/10426")] - public async Task TestMissingEndif1() - { - var code = """ + public Task TestMissingEndif1() + => VerifyBlockSpansAsync(""" #$$if true class C { } - """; - - await VerifyBlockSpansAsync(code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/10426")] - public async Task TestMissingEndif2() - { - var code = """ + public Task TestMissingEndif2() + => VerifyBlockSpansAsync(""" #$$if true {|span:class C { @@ -134,16 +113,12 @@ class D class E { } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/10426")] - public async Task TestMissingEndif3() - { - var code = """ + public Task TestMissingEndif3() + => VerifyBlockSpansAsync(""" #$$if false class C { @@ -156,8 +131,5 @@ class D class E { } - """; - - await VerifyBlockSpansAsync(code); - } + """); } diff --git a/src/EditorFeatures/CSharpTest/Structure/IndexerDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/IndexerDeclarationStructureTests.cs index 71ad764c8d775..63efb599c6bc7 100644 --- a/src/EditorFeatures/CSharpTest/Structure/IndexerDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/IndexerDeclarationStructureTests.cs @@ -17,9 +17,8 @@ public sealed class IndexerDeclarationStructureTests : AbstractCSharpSyntaxNodeS internal override AbstractSyntaxStructureProvider CreateProvider() => new IndexerDeclarationStructureProvider(); [Fact] - public async Task TestIndexer1() - { - var code = """ + public Task TestIndexer1() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public string this[int index]{|textspan: @@ -27,16 +26,12 @@ class C get { } }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestIndexer2() - { - var code = """ + public Task TestIndexer2() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public string this[int index]{|textspan: @@ -45,16 +40,12 @@ class C }|}|} int Value => 0; } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestIndexer3() - { - var code = """ + public Task TestIndexer3() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public string this[int index]{|textspan: @@ -64,16 +55,12 @@ class C int Value => 0; } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestIndexerWithComments() - { - var code = """ + public Task TestIndexerWithComments() + => VerifyBlockSpansAsync(""" class C { {|span1:// Goo @@ -83,26 +70,19 @@ class C get { } }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestIndexerWithWithExpressionBodyAndComments() - { - var code = """ + public Task TestIndexerWithWithExpressionBodyAndComments() + => VerifyBlockSpansAsync(""" class C { {|span:// Goo // Bar|} $$public string this[int index] => 0; } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "// Goo ...", autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/InitializerExpressionStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/InitializerExpressionStructureTests.cs index 34a207f866a26..8613d575ab3c1 100644 --- a/src/EditorFeatures/CSharpTest/Structure/InitializerExpressionStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/InitializerExpressionStructureTests.cs @@ -18,9 +18,8 @@ internal override AbstractSyntaxStructureProvider CreateProvider() => new InitializerExpressionStructureProvider(); [Fact] - public async Task TestOuterInitializer() - { - await VerifyBlockSpansAsync( + public Task TestOuterInitializer() + => VerifyBlockSpansAsync( """ class C { @@ -34,12 +33,10 @@ void M() } """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestInnerInitializer() - { - await VerifyBlockSpansAsync( + public Task TestInnerInitializer() + => VerifyBlockSpansAsync( """ class C { @@ -55,5 +52,4 @@ void M() } """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/InterpolatedStringExpressionStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/InterpolatedStringExpressionStructureTests.cs index 11796c9619ce9..808e3da881f56 100644 --- a/src/EditorFeatures/CSharpTest/Structure/InterpolatedStringExpressionStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/InterpolatedStringExpressionStructureTests.cs @@ -18,9 +18,8 @@ internal override AbstractSyntaxStructureProvider CreateProvider() => new InterpolatedStringExpressionStructureProvider(); [Fact] - public async Task TestMultiLineStringLiteral() - { - await VerifyBlockSpansAsync( + public Task TestMultiLineStringLiteral() + => VerifyBlockSpansAsync( """ class C { @@ -34,12 +33,10 @@ void M() } """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestMissingOnIncompleteStringLiteral() - { - await VerifyNoBlockSpansAsync( + public Task TestMissingOnIncompleteStringLiteral() + => VerifyNoBlockSpansAsync( """ class C { @@ -49,5 +46,4 @@ void M() } } """); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/AccessorDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/AccessorDeclarationStructureTests.cs index 339d738a359d5..0629c6676c505 100644 --- a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/AccessorDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/AccessorDeclarationStructureTests.cs @@ -18,9 +18,8 @@ public sealed class AccessorDeclarationStructureTests : AbstractCSharpSyntaxNode internal override AbstractSyntaxStructureProvider CreateProvider() => new AccessorDeclarationStructureProvider(); [Fact] - public async Task TestPropertyGetter3() - { - var code = """ + public Task TestPropertyGetter3() + => VerifyBlockSpansAsync(""" class C { public string Text @@ -34,16 +33,12 @@ public string Text } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestPropertyGetterWithSingleLineComments3() - { - var code = """ + public Task TestPropertyGetterWithSingleLineComments3() + => VerifyBlockSpansAsync(""" class C { public string Text @@ -59,17 +54,13 @@ public string Text } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "// My ...", autoCollapse: true), Region("textspan2", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestPropertyGetterWithMultiLineComments3() - { - var code = """ + public Task TestPropertyGetterWithMultiLineComments3() + => VerifyBlockSpansAsync(""" class C { public string Text @@ -85,9 +76,6 @@ public string Text } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan1", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/ConstructorDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/ConstructorDeclarationStructureTests.cs index 95947f016846f..cd368a87bb308 100644 --- a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/ConstructorDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/ConstructorDeclarationStructureTests.cs @@ -17,37 +17,28 @@ public sealed class ConstructorDeclarationStructureTests : AbstractCSharpSyntaxN internal override AbstractSyntaxStructureProvider CreateProvider() => new ConstructorDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task NoCommentsOrAttributes() - { - var code = """ + public Task NoCommentsOrAttributes() + => VerifyNoBlockSpansAsync(""" class C { $$C(); } - """; - - await VerifyNoBlockSpansAsync(code); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task WithAttributes() - { - var code = """ + public Task WithAttributes() + => VerifyBlockSpansAsync(""" class C { {|hint:{|textspan:[Bar] |}$$C();|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task WithCommentsAndAttributes() - { - var code = """ + public Task WithCommentsAndAttributes() + => VerifyBlockSpansAsync(""" class C { {|hint:{|textspan:// Summary: @@ -55,16 +46,12 @@ class C [Bar] |}$$C();|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task WithCommentsAttributesAndModifiers() - { - var code = """ + public Task WithCommentsAttributesAndModifiers() + => VerifyBlockSpansAsync(""" class C { {|hint:{|textspan:// Summary: @@ -72,16 +59,12 @@ class C [Bar] |}$$public C();|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] - public async Task TestConstructor10() - { - var code = """ + public Task TestConstructor10() + => VerifyBlockSpansAsync(""" class C { $${|#0:public C(){|textspan: @@ -92,9 +75,6 @@ public C(int x) { } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/ConversionOperatorDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/ConversionOperatorDeclarationStructureTests.cs index a0e91bda6ecb3..bdc462465961c 100644 --- a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/ConversionOperatorDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/ConversionOperatorDeclarationStructureTests.cs @@ -17,37 +17,28 @@ public sealed class ConversionOperatorDeclarationStructureTests : AbstractCSharp internal override AbstractSyntaxStructureProvider CreateProvider() => new ConversionOperatorDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task NoCommentsOrAttributes() - { - var code = """ + public Task NoCommentsOrAttributes() + => VerifyNoBlockSpansAsync(""" class C { public static explicit operator $$Goo(byte b); } - """; - - await VerifyNoBlockSpansAsync(code); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task WithAttributes() - { - var code = """ + public Task WithAttributes() + => VerifyBlockSpansAsync(""" class C { {|hint:{|textspan:[Blah] |}public static explicit operator $$Goo(byte b);|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task WithCommentsAndAttributes() - { - var code = """ + public Task WithCommentsAndAttributes() + => VerifyBlockSpansAsync(""" class C { {|hint:{|textspan:// Summary: @@ -55,16 +46,12 @@ class C [Blah] |}public static explicit operator $$Goo(byte b);|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] - public async Task TestOperator3() - { - var code = """ + public Task TestOperator3() + => VerifyBlockSpansAsync(""" class C { $${|#0:public static explicit operator C(byte i){|textspan: @@ -75,9 +62,6 @@ public static explicit operator C(short i) { } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/DelegateDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/DelegateDeclarationStructureTests.cs index 445352e7422d9..6e4f6dd4af9e2 100644 --- a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/DelegateDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/DelegateDeclarationStructureTests.cs @@ -18,52 +18,36 @@ public sealed class DelegateDeclarationStructureTests : AbstractCSharpSyntaxNode internal override AbstractSyntaxStructureProvider CreateProvider() => new DelegateDeclarationStructureProvider(); [Fact] - public async Task NoCommentsOrAttributes() - { - var code = """ + public Task NoCommentsOrAttributes() + => VerifyNoBlockSpansAsync(""" public delegate TResult $$Blah(T arg); - """; - - await VerifyNoBlockSpansAsync(code); - } + """); [Fact] - public async Task WithAttributes() - { - var code = """ + public Task WithAttributes() + => VerifyBlockSpansAsync(""" {|hint:{|textspan:[Goo] |}public delegate TResult $$Blah(T arg);|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task WithCommentsAndAttributes() - { - var code = """ + public Task WithCommentsAndAttributes() + => VerifyBlockSpansAsync(""" {|hint:{|textspan:// Summary: // This is a summary. [Goo] |}delegate TResult $$Blah(T arg);|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task WithCommentsAttributesAndModifiers() - { - var code = """ + public Task WithCommentsAttributesAndModifiers() + => VerifyBlockSpansAsync(""" {|hint:{|textspan:// Summary: // This is a summary. [Goo] |}public delegate TResult $$Blah(T arg);|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/DestructorDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/DestructorDeclarationStructureTests.cs index 08af03d102561..b107c335fe7aa 100644 --- a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/DestructorDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/DestructorDeclarationStructureTests.cs @@ -18,37 +18,28 @@ public sealed class DestructorDeclarationStructureTests : AbstractCSharpSyntaxNo internal override AbstractSyntaxStructureProvider CreateProvider() => new DestructorDeclarationStructureProvider(); [Fact] - public async Task NoCommentsOrAttributes() - { - var code = """ + public Task NoCommentsOrAttributes() + => VerifyNoBlockSpansAsync(""" class Goo { $$~Goo(); } - """; - - await VerifyNoBlockSpansAsync(code); - } + """); [Fact] - public async Task WithAttributes() - { - var code = """ + public Task WithAttributes() + => VerifyBlockSpansAsync(""" class Goo { {|hint:{|textspan:[Bar] |}$$~Goo();|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task WithCommentsAndAttributes() - { - var code = """ + public Task WithCommentsAndAttributes() + => VerifyBlockSpansAsync(""" class Goo { {|hint:{|textspan:// Summary: @@ -56,9 +47,6 @@ class Goo [Bar] |}$$~Goo();|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/EnumDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/EnumDeclarationStructureTests.cs index cf65f429bc222..615f8d250af15 100644 --- a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/EnumDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/EnumDeclarationStructureTests.cs @@ -17,41 +17,32 @@ public sealed class EnumDeclarationStructureTests : AbstractCSharpSyntaxNodeStru internal override AbstractSyntaxStructureProvider CreateProvider() => new EnumDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task NoCommentsOrAttributes() - { - var code = """ + public Task NoCommentsOrAttributes() + => VerifyBlockSpansAsync(""" {|hint:enum $$E{|textspan: { A, B }|}|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task WithAttributes() - { - var code = """ + public Task WithAttributes() + => VerifyBlockSpansAsync(""" {|hint:{|textspan:[Bar] |}{|#0:enum $$E|}{|textspan2: { A, B }|}|#0} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("textspan2", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task WithCommentsAndAttributes() - { - var code = """ + public Task WithCommentsAndAttributes() + => VerifyBlockSpansAsync(""" {|hint:{|textspan:// Summary: // This is a summary. [Bar] @@ -60,17 +51,13 @@ public async Task WithCommentsAndAttributes() A, B }|}|#0} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("textspan2", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task WithCommentsAttributesAndModifiers() - { - var code = """ + public Task WithCommentsAttributesAndModifiers() + => VerifyBlockSpansAsync(""" {|hint:{|textspan:// Summary: // This is a summary. [Bar] @@ -79,30 +66,24 @@ public async Task WithCommentsAttributesAndModifiers() A, B }|}|#0} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("textspan2", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Theory, Trait(Traits.Feature, Traits.Features.Outlining)] [InlineData("enum")] [InlineData("struct")] [InlineData("class")] [InlineData("interface")] - public async Task TestEnum3(string typeKind) - { - var code = $@" -{{|#0:$$enum E{{|textspan: -{{ -}}|#0}} -|}} -{typeKind} Following -{{ -}}"; - - await VerifyBlockSpansAsync(code, + public Task TestEnum3(string typeKind) + => VerifyBlockSpansAsync($$""" + {|#0:$$enum E{|textspan: + { + }|#0} + |} + {{typeKind}} Following + { + } + """, Region("textspan", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/EnumMemberDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/EnumMemberDeclarationStructureTests.cs index 1bfcf02476122..326f75e737ca4 100644 --- a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/EnumMemberDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/EnumMemberDeclarationStructureTests.cs @@ -18,39 +18,30 @@ public sealed class EnumMemberDeclarationStructureTests : AbstractCSharpSyntaxNo internal override AbstractSyntaxStructureProvider CreateProvider() => new EnumMemberDeclarationStructureProvider(); [Fact] - public async Task NoCommentsOrAttributes() - { - var code = """ + public Task NoCommentsOrAttributes() + => VerifyNoBlockSpansAsync(""" enum E { $$Goo, Bar } - """; - - await VerifyNoBlockSpansAsync(code); - } + """); [Fact] - public async Task WithAttributes() - { - var code = """ + public Task WithAttributes() + => VerifyBlockSpansAsync(""" enum E { {|hint:{|textspan:[Blah] |}$$Goo|}, Bar } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task WithCommentsAndAttributes() - { - var code = """ + public Task WithCommentsAndAttributes() + => VerifyBlockSpansAsync(""" enum E { {|hint:{|textspan:// Summary: @@ -59,9 +50,6 @@ enum E |}$$Goo|}, Bar } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/EventDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/EventDeclarationStructureTests.cs index 4b1f93014e1d3..832670b9f8867 100644 --- a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/EventDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/EventDeclarationStructureTests.cs @@ -17,39 +17,30 @@ public sealed class EventDeclarationStructureTests : AbstractCSharpSyntaxNodeStr internal override AbstractSyntaxStructureProvider CreateProvider() => new EventDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task NoCommentsOrAttributes() - { - var code = """ + public Task NoCommentsOrAttributes() + => VerifyBlockSpansAsync(""" class Goo { {|hint:public event EventArgs $$goo {|textspan:{ add; remove; }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task WithAttributes() - { - var code = """ + public Task WithAttributes() + => VerifyBlockSpansAsync(""" class Goo { {|hint1:{|textspan1:[Goo] |}{|hint2:public event EventArgs $$goo {|textspan2:{ add; remove; }|}|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task WithCommentsAndAttributes() - { - var code = """ + public Task WithCommentsAndAttributes() + => VerifyBlockSpansAsync(""" class Goo { {|hint1:{|textspan1:// Summary: @@ -57,17 +48,13 @@ class Goo [Goo] |}{|hint2:event EventArgs $$goo {|textspan2:{ add; remove; }|}|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task WithCommentsAttributesAndModifiers() - { - var code = """ + public Task WithCommentsAttributesAndModifiers() + => VerifyBlockSpansAsync(""" class Goo { {|hint1:{|textspan1:// Summary: @@ -75,17 +62,13 @@ class Goo [Goo] |}{|hint2:public event EventArgs $$goo {|textspan2:{ add; remove; }|}|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] - public async Task TestEvent3() - { - var code = """ + public Task TestEvent3() + => VerifyBlockSpansAsync(""" class C { $${|#0:event EventHandler E{|textspan: @@ -100,9 +83,6 @@ event EventHandler E2 remove { } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/EventFieldDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/EventFieldDeclarationStructureTests.cs index 11fe3342cb817..8a6083381a5a7 100644 --- a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/EventFieldDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/EventFieldDeclarationStructureTests.cs @@ -18,37 +18,28 @@ public sealed class EventFieldDeclarationStructureTests : AbstractCSharpSyntaxNo internal override AbstractSyntaxStructureProvider CreateProvider() => new EventFieldDeclarationStructureProvider(); [Fact] - public async Task NoCommentsOrAttributes() - { - var code = """ + public Task NoCommentsOrAttributes() + => VerifyNoBlockSpansAsync(""" class Goo { public event EventArgs $$goo } - """; - - await VerifyNoBlockSpansAsync(code); - } + """); [Fact] - public async Task WithAttributes() - { - var code = """ + public Task WithAttributes() + => VerifyBlockSpansAsync(""" class Goo { {|hint:{|textspan:[Goo] |}event EventArgs $$goo|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task WithCommentsAndAttributes() - { - var code = """ + public Task WithCommentsAndAttributes() + => VerifyBlockSpansAsync(""" class Goo { {|hint:{|textspan:// Summary: @@ -56,16 +47,12 @@ class Goo [Goo] |}event EventArgs $$goo|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task WithCommentsAttributesAndModifiers() - { - var code = """ + public Task WithCommentsAttributesAndModifiers() + => VerifyBlockSpansAsync(""" class Goo { {|hint:{|textspan:// Summary: @@ -73,9 +60,6 @@ class Goo [Goo] |}public event EventArgs $$goo|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/FieldDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/FieldDeclarationStructureTests.cs index a793b32342e7e..97a20eeb27847 100644 --- a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/FieldDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/FieldDeclarationStructureTests.cs @@ -18,37 +18,28 @@ public sealed class FieldDeclarationStructureTests : AbstractCSharpSyntaxNodeStr internal override AbstractSyntaxStructureProvider CreateProvider() => new FieldDeclarationStructureProvider(); [Fact] - public async Task NoCommentsOrAttributes() - { - var code = """ + public Task NoCommentsOrAttributes() + => VerifyNoBlockSpansAsync(""" class Goo { public int $$goo } - """; - - await VerifyNoBlockSpansAsync(code); - } + """); [Fact] - public async Task WithAttributes() - { - var code = """ + public Task WithAttributes() + => VerifyBlockSpansAsync(""" class Goo { {|hint:{|textspan:[Goo] |}public int $$goo|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task WithCommentsAndAttributes() - { - var code = """ + public Task WithCommentsAndAttributes() + => VerifyBlockSpansAsync(""" class Goo { {|hint:{|textspan:// Summary: @@ -56,16 +47,12 @@ class Goo [Goo] |}int $$goo|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task WithCommentsAttributesAndModifiers() - { - var code = """ + public Task WithCommentsAttributesAndModifiers() + => VerifyBlockSpansAsync(""" class Goo { {|hint:{|textspan:// Summary: @@ -73,9 +60,6 @@ class Goo [Goo] |}public int $$goo|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/IndexerDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/IndexerDeclarationStructureTests.cs index 92f65837c7ac0..0715a35bd1088 100644 --- a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/IndexerDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/IndexerDeclarationStructureTests.cs @@ -17,39 +17,30 @@ public sealed class IndexerDeclarationStructureTests : AbstractCSharpSyntaxNodeS internal override AbstractSyntaxStructureProvider CreateProvider() => new IndexerDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task NoCommentsOrAttributes() - { - var code = """ + public Task NoCommentsOrAttributes() + => VerifyBlockSpansAsync(""" class Goo { {|hint:public string $$this[int x] {|textspan:{ get; set; }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task WithAttributes() - { - var code = """ + public Task WithAttributes() + => VerifyBlockSpansAsync(""" class Goo { {|hint1:{|textspan1:[Goo] |}{|hint2:public string $$this[int x] {|textspan2:{ get; set; }|}|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task WithCommentsAndAttributes() - { - var code = """ + public Task WithCommentsAndAttributes() + => VerifyBlockSpansAsync(""" class Goo { {|hint1:{|textspan1:// Summary: @@ -57,17 +48,13 @@ class Goo [Goo] |}{|hint2:string $$this[int x] {|textspan2:{ get; set; }|}|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task WithCommentsAttributesAndmodifiers() - { - var code = """ + public Task WithCommentsAttributesAndmodifiers() + => VerifyBlockSpansAsync(""" class Goo { {|hint1:{|textspan1:// Summary: @@ -75,17 +62,13 @@ class Goo [Goo] |}{|hint2:public string $$this[int x] {|textspan2:{ get; set; }|}|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] - public async Task TestIndexer3() - { - var code = """ + public Task TestIndexer3() + => VerifyBlockSpansAsync(""" class C { $${|#0:public string this[int index]{|textspan: @@ -95,9 +78,6 @@ class C |} int Value => 0; } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/InvalidIdentifierStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/InvalidIdentifierStructureTests.cs index 23db1b3ec9b89..1607191577de0 100644 --- a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/InvalidIdentifierStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/InvalidIdentifierStructureTests.cs @@ -33,46 +33,34 @@ internal override async Task> GetBlockSpansWorkerAsync } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174405")] - public async Task PrependedDollarSign() - { - var code = """ + public Task PrependedDollarSign() + => VerifyBlockSpansAsync(""" {|hint:$$class C{|textspan: { public void $Invoke(); }|}|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174405")] - public async Task SymbolsAndPunctuation() - { - var code = """ + public Task SymbolsAndPunctuation() + => VerifyBlockSpansAsync(""" {|hint:$$class C{|textspan: { public void !#$%^&*(()_-+=|\}]{["':;?/>.<,~`(); }|}|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174405")] - public async Task IdentifierThatLooksLikeCode() - { - var code = """ + public Task IdentifierThatLooksLikeCode() + => VerifyBlockSpansAsync(""" {|hint1:$$class C{|textspan1: { public void }|}|} } {|hint2:public class CodeInjection{|textspan2:{ }|}|} {|textspan3:/* now everything is commented (); }|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan3", "/* now everything is commented (); ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/MethodDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/MethodDeclarationStructureTests.cs index dcd140b22b1c2..ceb736872b396 100644 --- a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/MethodDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/MethodDeclarationStructureTests.cs @@ -17,37 +17,28 @@ public sealed class MethodDeclarationStructureTests : AbstractCSharpSyntaxNodeSt internal override AbstractSyntaxStructureProvider CreateProvider() => new MethodDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task NoCommentsOrAttributes() - { - var code = """ + public Task NoCommentsOrAttributes() + => VerifyNoBlockSpansAsync(""" class Goo { public string $$Bar(int x); } - """; - - await VerifyNoBlockSpansAsync(code); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task WithAttributes() - { - var code = """ + public Task WithAttributes() + => VerifyBlockSpansAsync(""" class Goo { {|hint:{|textspan:[Goo] |}public string $$Bar(int x);|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task WithCommentsAndAttributes() - { - var code = """ + public Task WithCommentsAndAttributes() + => VerifyBlockSpansAsync(""" class Goo { {|hint:{|textspan:// Summary: @@ -55,16 +46,12 @@ class Goo [Goo] |}string $$Bar(int x);|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task WithCommentsAttributesAndModifiers() - { - var code = """ + public Task WithCommentsAttributesAndModifiers() + => VerifyBlockSpansAsync(""" class Goo { {|hint:{|textspan:// Summary: @@ -72,16 +59,12 @@ class Goo [Goo] |}public string $$Bar(int x);|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] - public async Task TestMethod3() - { - var code = """ + public Task TestMethod3() + => VerifyBlockSpansAsync(""" class C { $${|#0:public string Goo(){|textspan: @@ -92,9 +75,6 @@ public string Goo2() { } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/OperatorDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/OperatorDeclarationStructureTests.cs index 52bad18197863..f915c317ec267 100644 --- a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/OperatorDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/OperatorDeclarationStructureTests.cs @@ -17,37 +17,28 @@ public sealed class OperatorDeclarationStructureTests : AbstractCSharpSyntaxNode internal override AbstractSyntaxStructureProvider CreateProvider() => new OperatorDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task NoCommentsOrAttributes() - { - var code = """ + public Task NoCommentsOrAttributes() + => VerifyNoBlockSpansAsync(""" class Goo { public static bool operator $$==(Goo a, Goo b); } - """; - - await VerifyNoBlockSpansAsync(code); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task WithAttributes() - { - var code = """ + public Task WithAttributes() + => VerifyBlockSpansAsync(""" class Goo { {|hint:{|textspan:[Blah] |}public static bool operator $$==(Goo a, Goo b);|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task WithCommentsAndAttributes() - { - var code = """ + public Task WithCommentsAndAttributes() + => VerifyBlockSpansAsync(""" class Goo { {|hint:{|textspan:// Summary: @@ -55,16 +46,12 @@ class Goo [Blah] |}bool operator $$==(Goo a, Goo b);|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task WithCommentsAttributesAndModifiers() - { - var code = """ + public Task WithCommentsAttributesAndModifiers() + => VerifyBlockSpansAsync(""" class Goo { {|hint:{|textspan:// Summary: @@ -72,16 +59,12 @@ class Goo [Blah] |}public static bool operator $$==(Goo a, Goo b);|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] - public async Task TestOperator3() - { - var code = """ + public Task TestOperator3() + => VerifyBlockSpansAsync(""" class C { $${|#0:public static int operator +(int i){|textspan: @@ -92,9 +75,6 @@ class C { } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/PropertyDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/PropertyDeclarationStructureTests.cs index 95c9fe24af301..37b2dfb39f011 100644 --- a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/PropertyDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/PropertyDeclarationStructureTests.cs @@ -17,39 +17,30 @@ public sealed class PropertyDeclarationStructureTests : AbstractCSharpSyntaxNode internal override AbstractSyntaxStructureProvider CreateProvider() => new PropertyDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task NoCommentsOrAttributes() - { - var code = """ + public Task NoCommentsOrAttributes() + => VerifyBlockSpansAsync(""" class Goo { {|hint:public string $$Prop {|textspan:{ get; set; }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task WithAttributes() - { - var code = """ + public Task WithAttributes() + => VerifyBlockSpansAsync(""" class Goo { {|hint1:{|textspan1:[Goo] |}{|hint2:public string $$Prop {|textspan2:{ get; set; }|}|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task WithCommentsAndAttributes() - { - var code = """ + public Task WithCommentsAndAttributes() + => VerifyBlockSpansAsync(""" class Goo { {|hint1:{|textspan1:// Summary: @@ -57,17 +48,13 @@ class Goo [Goo] |}{|hint2:string $$Prop {|textspan2:{ get; set; }|}|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task WithCommentsAttributesAndModifiers() - { - var code = """ + public Task WithCommentsAttributesAndModifiers() + => VerifyBlockSpansAsync(""" class Goo { {|hint1:{|textspan1:// Summary: @@ -75,17 +62,13 @@ class Goo [Goo] |}{|hint2:public string $$Prop {|textspan2:{ get; set; }|}|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] - public async Task TestProperty3() - { - var code = """ + public Task TestProperty3() + => VerifyBlockSpansAsync(""" class C { $${|#0:public int Goo{|textspan: @@ -100,16 +83,12 @@ public int Goo2 set { } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] - public async Task TestProperty4() - { - var code = """ + public Task TestProperty4() + => VerifyBlockSpansAsync(""" class C { $${|#0:public int Goo{|textspan: @@ -124,9 +103,6 @@ public int this[int value] set { } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/RegionDirectiveStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/RegionDirectiveStructureTests.cs index 1257887d839b8..4c24c7e2a1541 100644 --- a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/RegionDirectiveStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/RegionDirectiveStructureTests.cs @@ -18,28 +18,20 @@ public sealed class RegionDirectiveStructureTests : AbstractCSharpSyntaxNodeStru internal override AbstractSyntaxStructureProvider CreateProvider() => new RegionDirectiveStructureProvider(); [Fact] - public async Task FileHeader() - { - var code = """ + public Task FileHeader() + => VerifyBlockSpansAsync(""" {|span:#re$$gion Assembly mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\mscorlib.dll #endregion|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "Assembly mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", autoCollapse: true, isDefaultCollapsed: true)); - } [Fact] - public async Task EmptyFileHeader() - { - var code = """ + public Task EmptyFileHeader() + => VerifyBlockSpansAsync(""" {|span:#re$$gion // C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\mscorlib.dll #endregion|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "#region", autoCollapse: true, isDefaultCollapsed: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/TypeDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/TypeDeclarationStructureTests.cs index cd61dfe4da8d6..f2efb8b2144ec 100644 --- a/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/TypeDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/TypeDeclarationStructureTests.cs @@ -19,40 +19,31 @@ public sealed class TypeDeclarationStructureTests : AbstractCSharpSyntaxNodeStru internal override AbstractSyntaxStructureProvider CreateProvider() => new TypeDeclarationStructureProvider(); [Fact] - public async Task NoCommentsOrAttributes() - { - var code = """ + public Task NoCommentsOrAttributes() + => VerifyBlockSpansAsync(""" {|hint:class $$C{|textspan: { void M(); }|}|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task WithAttributes() - { - var code = """ + public Task WithAttributes() + => VerifyBlockSpansAsync(""" {|hint:{|textspan:[Bar] [Baz] |}{|#0:public class $$C|}{|textspan2: { void M(); }|}|#0} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("textspan2", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task WithCommentsAndAttributes() - { - var code = """ + public Task WithCommentsAndAttributes() + => VerifyBlockSpansAsync(""" {|hint:{|textspan:// Summary: // This is a doc comment. [Bar, Baz] @@ -60,17 +51,13 @@ public async Task WithCommentsAndAttributes() { void M(); }|}|#0} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("textspan2", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47889")] - public async Task RecordWithCommentsAndAttributes() - { - var code = """ + public Task RecordWithCommentsAndAttributes() + => VerifyBlockSpansAsync(""" {|hint:{|textspan:// Summary: // This is a doc comment. [Bar, Baz] @@ -78,17 +65,13 @@ public async Task RecordWithCommentsAndAttributes() { void M(); }|}|#0} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("textspan2", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task RecordStructWithCommentsAndAttributes() - { - var code = """ + public Task RecordStructWithCommentsAndAttributes() + => VerifyBlockSpansAsync(""" {|hint:{|textspan:// Summary: // This is a doc comment. [Bar, Baz] @@ -96,33 +79,25 @@ public async Task RecordStructWithCommentsAndAttributes() { void M(); }|}|#0} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("textspan2", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task WithDocComments() - { - var code = """ + public Task WithDocComments() + => VerifyBlockSpansAsync(""" {|hint:{|textspan:/// This is a doc comment. |}{|#0:public class $$C|}{|textspan2: { void M(); }|}|#0} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("textspan2", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task WithMultilineDocComments() - { - var code = """ + public Task WithMultilineDocComments() + => VerifyBlockSpansAsync(""" {|hint:{|textspan:/// This is a doc comment. /// /// Comments are cool @@ -131,10 +106,7 @@ public async Task WithMultilineDocComments() { void M(); }|}|#0} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("textspan2", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/MethodDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/MethodDeclarationStructureTests.cs index 13aa4c6228269..261052ff3aa76 100644 --- a/src/EditorFeatures/CSharpTest/Structure/MethodDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/MethodDeclarationStructureTests.cs @@ -18,25 +18,20 @@ public sealed class MethodDeclarationStructureTests : AbstractCSharpSyntaxNodeSt internal override AbstractSyntaxStructureProvider CreateProvider() => new MethodDeclarationStructureProvider(); [Fact] - public async Task TestMethod1() - { - var code = """ + public Task TestMethod1() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public string Goo(){|textspan: { }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestMethod2() - { - var code = """ + public Task TestMethod2() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public string Goo(){|textspan: @@ -46,16 +41,12 @@ public string Goo2() { } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestMethod3() - { - var code = """ + public Task TestMethod3() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public string Goo(){|textspan: @@ -66,16 +57,12 @@ public string Goo2() { } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestMethod4() - { - var code = """ + public Task TestMethod4() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public string Goo(){|textspan: @@ -84,16 +71,12 @@ class C public string Goo2 => null; } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68778")] - public async Task TestMethod5() - { - var code = """ + public Task TestMethod5() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public void Goo(){|textspan: @@ -101,16 +84,12 @@ class C { }|}|} // .ctor } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68778")] - public async Task TestMethod6() - { - var code = """ + public Task TestMethod6() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public void Goo(){|textspan: @@ -118,32 +97,24 @@ class C { }|}|} // .ctor } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestMethodWithTrailingSpaces() - { - var code = """ + public Task TestMethodWithTrailingSpaces() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public string Goo() {|textspan: { }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestMethodWithLeadingComments() - { - var code = """ + public Task TestMethodWithLeadingComments() + => VerifyBlockSpansAsync(""" class C { {|span1:// Goo @@ -152,26 +123,19 @@ class C { }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestMethodWithWithExpressionBodyAndComments() - { - var code = """ + public Task TestMethodWithWithExpressionBodyAndComments() + => VerifyBlockSpansAsync(""" class C { {|span:// Goo // Bar|} $$public string Goo() => "Goo"; } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "// Goo ...", autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/MultilineCommentStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/MultilineCommentStructureTests.cs index ada5afbc9f93f..6db085ba5f952 100644 --- a/src/EditorFeatures/CSharpTest/Structure/MultilineCommentStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/MultilineCommentStructureTests.cs @@ -17,62 +17,45 @@ public sealed class MultilineCommentStructureTests : AbstractCSharpSyntaxTriviaS internal override AbstractSyntaxStructureProvider CreateProvider() => new MultilineCommentBlockStructureProvider(); [Fact] - public async Task TestMultilineComment1() - { - var code = """ + public Task TestMultilineComment1() + => VerifyBlockSpansAsync(""" {|span:/* Hello $$C# */|} class C { } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "/* Hello ...", autoCollapse: true)); - } [Fact] - public async Task TestMultilineCommentOnOneLine() - { - var code = """ + public Task TestMultilineCommentOnOneLine() + => VerifyBlockSpansAsync(""" {|span:/* Hello $$C# */|} class C { } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "/* Hello C# ...", autoCollapse: true)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108049")] [WorkItem("https://github.com/dotnet/roslyn/issues/791")] - public async Task TestIncompleteMultilineCommentZeroSpace() - { - var code = """ + public Task TestIncompleteMultilineCommentZeroSpace() + => VerifyBlockSpansAsync(""" {|span:$$/*|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "/* ...", autoCollapse: true)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108049")] [WorkItem("https://github.com/dotnet/roslyn/issues/791")] - public async Task TestIncompleteMultilineCommentSingleSpace() - { - var code = """ + public Task TestIncompleteMultilineCommentSingleSpace() + => VerifyBlockSpansAsync(""" {|span:$$/* |} - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "/* ...", autoCollapse: true)); - } [Fact] - public async Task TestPropertyGetterWithMultiLineComments1() - { - var code = """ + public Task TestPropertyGetterWithMultiLineComments1() + => VerifyBlockSpansAsync(""" class C { public string Text @@ -84,16 +67,12 @@ public string Text } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "/* My ...", autoCollapse: true)); - } [Fact] - public async Task TestPropertyGetterWithMultiLineComments2() - { - var code = """ + public Task TestPropertyGetterWithMultiLineComments2() + => VerifyBlockSpansAsync(""" class C { public string Text @@ -108,16 +87,12 @@ public string Text } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "/* My ...", autoCollapse: true)); - } [Fact] - public async Task TestPropertyGetterWithMultiLineComments3() - { - var code = """ + public Task TestPropertyGetterWithMultiLineComments3() + => VerifyBlockSpansAsync(""" class C { public string Text @@ -133,16 +108,12 @@ public string Text } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "/* My ...", autoCollapse: true)); - } [Fact] - public async Task TestPropertySetterWithMultiLineComments1() - { - var code = """ + public Task TestPropertySetterWithMultiLineComments1() + => VerifyBlockSpansAsync(""" class C { public string Text @@ -154,16 +125,12 @@ public string Text } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "/* My ...", autoCollapse: true)); - } [Fact] - public async Task TestPropertySetterWithMultiLineComments2() - { - var code = """ + public Task TestPropertySetterWithMultiLineComments2() + => VerifyBlockSpansAsync(""" class C { public string Text @@ -178,16 +145,12 @@ public string Text } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "/* My ...", autoCollapse: true)); - } [Fact] - public async Task TestPropertySetterWithMultiLineComments3() - { - var code = """ + public Task TestPropertySetterWithMultiLineComments3() + => VerifyBlockSpansAsync(""" class C { public string Text @@ -203,46 +166,34 @@ public string Text } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "/* My ...", autoCollapse: true)); - } [Fact] - public async Task TestMultilineCommentInFile() - { - var code = """ + public Task TestMultilineCommentInFile() + => VerifyBlockSpansAsync(""" $${|span1:/* Comment in file */|} namespace M { } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "/* Comment in file ...", autoCollapse: true)); - } [Fact] - public async Task TestMultilineCommentInNamespace() - { - var code = """ + public Task TestMultilineCommentInNamespace() + => VerifyBlockSpansAsync(""" namespace M { $${|span1:/* Comment in namespace */|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "/* Comment in namespace ...", autoCollapse: true)); - } [Fact] - public async Task TestMultilineCommentInClass() - { - var code = """ + public Task TestMultilineCommentInClass() + => VerifyBlockSpansAsync(""" namespace M { class C @@ -252,16 +203,12 @@ class C } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "/* Comment in class ...", autoCollapse: true)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64001")] - public async Task TestMultilineCommentInMethod() - { - var code = """ + public Task TestMultilineCommentInMethod() + => VerifyBlockSpansAsync(""" namespace M { class C @@ -274,16 +221,12 @@ void M() } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "/* Comment in method ...", autoCollapse: true)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64001")] - public async Task TestMultilineCommentInLocalFunction() - { - var code = """ + public Task TestMultilineCommentInLocalFunction() + => VerifyBlockSpansAsync(""" namespace M { class C @@ -299,16 +242,12 @@ void LocalFunc() } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "/* Comment in local function ...", autoCollapse: true)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64001")] - public async Task TestMultilineCommentInConstructor() - { - var code = """ + public Task TestMultilineCommentInConstructor() + => VerifyBlockSpansAsync(""" namespace M { class C @@ -321,11 +260,8 @@ class C } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "/* Comment in constructor ...", autoCollapse: true)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16186")] public async Task TestInvalidComment() diff --git a/src/EditorFeatures/CSharpTest/Structure/NamespaceDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/NamespaceDeclarationStructureTests.cs index b15434f2c44f1..a2b7f0e18eab3 100644 --- a/src/EditorFeatures/CSharpTest/Structure/NamespaceDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/NamespaceDeclarationStructureTests.cs @@ -17,25 +17,20 @@ public sealed class NamespaceDeclarationStructureTests : AbstractCSharpSyntaxNod internal override AbstractSyntaxStructureProvider CreateProvider() => new NamespaceDeclarationStructureProvider(); [Fact] - public async Task TestNamespace() - { - var code = """ + public Task TestNamespace() + => VerifyBlockSpansAsync(""" class C { {|hint:$$namespace N{|textspan: { }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestNamespaceWithLeadingComments() - { - var code = """ + public Task TestNamespaceWithLeadingComments() + => VerifyBlockSpansAsync(""" class C { {|span1:// Goo @@ -44,17 +39,13 @@ class C { }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestNamespaceWithNestedUsings() - { - var code = """ + public Task TestNamespaceWithNestedUsings() + => VerifyBlockSpansAsync(""" class C { {|hint1:$$namespace N{|textspan1: @@ -63,17 +54,13 @@ class C using System.Linq;|}|} }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestNamespaceWithNestedUsingsWithLeadingComments() - { - var code = """ + public Task TestNamespaceWithNestedUsingsWithLeadingComments() + => VerifyBlockSpansAsync(""" class C { {|hint1:$$namespace N{|textspan1: @@ -84,18 +71,14 @@ class C using System.Linq;|}|} }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("span2", "// Goo ...", autoCollapse: true), Region("textspan3", "hint3", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestNamespaceWithNestedComments() - { - var code = """ + public Task TestNamespaceWithNestedComments() + => VerifyBlockSpansAsync(""" class C { {|hint1:$$namespace N{|textspan1: @@ -104,10 +87,7 @@ class C // Bar|} }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("span2", "// Goo ...", autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/OperatorDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/OperatorDeclarationStructureTests.cs index 0d959e0ed0a90..9c7c271b9826b 100644 --- a/src/EditorFeatures/CSharpTest/Structure/OperatorDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/OperatorDeclarationStructureTests.cs @@ -17,25 +17,20 @@ public sealed class OperatorDeclarationStructureTests : AbstractCSharpSyntaxNode internal override AbstractSyntaxStructureProvider CreateProvider() => new OperatorDeclarationStructureProvider(); [Fact] - public async Task TestOperator1() - { - var code = """ + public Task TestOperator1() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public static int operator +(int i){|textspan: { }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestOperator2() - { - var code = """ + public Task TestOperator2() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public static int operator +(int i){|textspan: @@ -45,16 +40,12 @@ class C { } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestOperator3() - { - var code = """ + public Task TestOperator3() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public static int operator +(int i){|textspan: @@ -65,16 +56,12 @@ class C { } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestOperator4() - { - var code = """ + public Task TestOperator4() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public static int operator +(int i){|textspan: @@ -84,16 +71,12 @@ public static explicit operator C(int i) { } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestOperator5() - { - var code = """ + public Task TestOperator5() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public static int operator +(int i){|textspan: @@ -103,16 +86,12 @@ public static explicit operator C(int i) { } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestOperatorWithLeadingComments() - { - var code = """ + public Task TestOperatorWithLeadingComments() + => VerifyBlockSpansAsync(""" class C { {|span1:// Goo @@ -121,10 +100,7 @@ class C { }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/ParenthesizedLambdaStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/ParenthesizedLambdaStructureTests.cs index a6a6245e230d0..643196ccaa47e 100644 --- a/src/EditorFeatures/CSharpTest/Structure/ParenthesizedLambdaStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/ParenthesizedLambdaStructureTests.cs @@ -17,9 +17,8 @@ public sealed class ParenthesizedLambdaStructureTests : AbstractCSharpSyntaxNode internal override AbstractSyntaxStructureProvider CreateProvider() => new ParenthesizedLambdaExpressionStructureProvider(); [Fact] - public async Task TestLambda() - { - var code = """ + public Task TestLambda() + => VerifyBlockSpansAsync(""" class C { void M() @@ -29,16 +28,12 @@ void M() };|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestLambdaInForLoop() - { - var code = """ + public Task TestLambdaInForLoop() + => VerifyNoBlockSpansAsync(""" class C { void M() @@ -46,15 +41,11 @@ void M() for (Action a = $$() => { }; true; a()) { } } } - """; - - await VerifyNoBlockSpansAsync(code); - } + """); [Fact] - public async Task TestLambdaInMethodCall1() - { - var code = """ + public Task TestLambdaInMethodCall1() + => VerifyBlockSpansAsync(""" class C { void M() @@ -64,16 +55,12 @@ void M() }|}|}, "other arguments"); } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestLambdaInMethodCall2() - { - var code = """ + public Task TestLambdaInMethodCall2() + => VerifyBlockSpansAsync(""" class C { void M() @@ -83,9 +70,6 @@ void M() }|}|}); } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/PropertyDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/PropertyDeclarationStructureTests.cs index b704b62ce3a06..37f597d969799 100644 --- a/src/EditorFeatures/CSharpTest/Structure/PropertyDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/PropertyDeclarationStructureTests.cs @@ -17,9 +17,8 @@ public sealed class PropertyDeclarationStructureTests : AbstractCSharpSyntaxNode internal override AbstractSyntaxStructureProvider CreateProvider() => new PropertyDeclarationStructureProvider(); [Fact] - public async Task TestProperty1() - { - var code = """ + public Task TestProperty1() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public int Goo{|textspan: @@ -28,16 +27,12 @@ class C set { } }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestProperty2() - { - var code = """ + public Task TestProperty2() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public int Goo{|textspan: @@ -51,16 +46,12 @@ public int Goo2 set { } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestProperty3() - { - var code = """ + public Task TestProperty3() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public int Goo{|textspan: @@ -75,16 +66,12 @@ public int Goo2 set { } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestProperty4() - { - var code = """ + public Task TestProperty4() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public int Goo{|textspan: @@ -99,16 +86,12 @@ public int this[int value] set { } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestProperty5() - { - var code = """ + public Task TestProperty5() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public int Goo{|textspan: @@ -119,16 +102,12 @@ class C public event EventHandler Event; } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestProperty6() - { - var code = """ + public Task TestProperty6() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public int Goo{|textspan: @@ -143,16 +122,12 @@ public event EventHandler Event remove { } } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestPropertyWithLeadingComments() - { - var code = """ + public Task TestPropertyWithLeadingComments() + => VerifyBlockSpansAsync(""" class C { {|span1:// Goo @@ -163,33 +138,25 @@ class C set { } }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestPropertyWithWithExpressionBodyAndComments() - { - var code = """ + public Task TestPropertyWithWithExpressionBodyAndComments() + => VerifyBlockSpansAsync(""" class C { {|span:// Goo // Bar|} $$public int Goo => 0; } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "// Goo ...", autoCollapse: true)); - } [Fact] - public async Task TestPropertyWithSpaceAfterIdentifier() - { - var code = """ + public Task TestPropertyWithSpaceAfterIdentifier() + => VerifyBlockSpansAsync(""" class C { {|hint:$$public int Goo {|textspan: @@ -198,9 +165,6 @@ class C set { } }|}|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/RegionDirectiveStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/RegionDirectiveStructureTests.cs index baeab2bb157ec..2d5cb76d54c8d 100644 --- a/src/EditorFeatures/CSharpTest/Structure/RegionDirectiveStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/RegionDirectiveStructureTests.cs @@ -18,31 +18,22 @@ public sealed class RegionDirectiveStructureTests : AbstractCSharpSyntaxNodeStru internal override AbstractSyntaxStructureProvider CreateProvider() => new RegionDirectiveStructureProvider(); [Fact] - public async Task BrokenRegion() - { - var code = """ + public Task BrokenRegion() + => VerifyNoBlockSpansAsync(""" $$#region Goo - """; - - await VerifyNoBlockSpansAsync(code); - } + """); [Fact] - public async Task SimpleRegion() - { - var code = """ + public Task SimpleRegion() + => VerifyBlockSpansAsync(""" {|span:$$#region Goo #endregion|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "Goo", autoCollapse: false, isDefaultCollapsed: true)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539361")] - public async Task RegressionFor5284() - { - var code = """ + public Task RegressionFor5284() + => VerifyBlockSpansAsync(""" namespace BasicGenerateFromUsage { class BasicGenerateFromUsage @@ -69,16 +60,18 @@ class Classic { } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "TaoRegion", autoCollapse: false, isDefaultCollapsed: true)); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/953668"), CombinatorialData] public async Task RegionsShouldBeCollapsedByDefault(bool collapseRegionsWhenFirstOpened) { - var code = """ + var options = GetDefaultOptions() with + { + CollapseRegionsWhenFirstOpened = collapseRegionsWhenFirstOpened + }; + + await VerifyBlockSpansAsync(""" class C { {|span:#region Re$$gion @@ -87,21 +80,13 @@ static void Main(string[] args) } #endregion|} } - """; - - var options = GetDefaultOptions() with - { - CollapseRegionsWhenFirstOpened = collapseRegionsWhenFirstOpened - }; - - await VerifyBlockSpansAsync(code, options, + """, options, Region("span", "Region", autoCollapse: false, isDefaultCollapsed: collapseRegionsWhenFirstOpened)); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4105")] - public async Task SpacesBetweenPoundAndRegionShouldNotAffectBanner() - { - var code = """ + public Task SpacesBetweenPoundAndRegionShouldNotAffectBanner() + => VerifyBlockSpansAsync(""" class C { {|span:# region R$$egion @@ -110,23 +95,16 @@ static void Main(string[] args) } # endregion|} } - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "Region", autoCollapse: false, isDefaultCollapsed: true)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75583")] - public async Task Trailing() - { - var code = """ + public Task Trailing() + => VerifyBlockSpansAsync(""" {|span:#region R$$1 /* comment */ #endregion /* comment */ #region R2 #endregion|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("span", "R1", autoCollapse: false, isDefaultCollapsed: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/SimpleLambdaExpressionStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/SimpleLambdaExpressionStructureTests.cs index 3e5d28a1d2d43..840e3621407c9 100644 --- a/src/EditorFeatures/CSharpTest/Structure/SimpleLambdaExpressionStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/SimpleLambdaExpressionStructureTests.cs @@ -17,9 +17,8 @@ public sealed class SimpleLambdaExpressionStructureTests : AbstractCSharpSyntaxN internal override AbstractSyntaxStructureProvider CreateProvider() => new SimpleLambdaExpressionStructureProvider(); [Fact] - public async Task TestLambda() - { - var code = """ + public Task TestLambda() + => VerifyBlockSpansAsync(""" class C { void M() @@ -29,16 +28,12 @@ void M() };|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestLambdaInForLoop() - { - var code = """ + public Task TestLambdaInForLoop() + => VerifyNoBlockSpansAsync(""" class C { void M() @@ -46,15 +41,11 @@ void M() for (Action a = x$$ => { }; true; a()) { } } } - """; - - await VerifyNoBlockSpansAsync(code); - } + """); [Fact] - public async Task TestLambdaInMethodCall1() - { - var code = """ + public Task TestLambdaInMethodCall1() + => VerifyBlockSpansAsync(""" class C { void M() @@ -64,16 +55,12 @@ void M() }|}|}, "other arguments}"); } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestLambdaInMethodCall2() - { - var code = """ + public Task TestLambdaInMethodCall2() + => VerifyBlockSpansAsync(""" class C { void M() @@ -83,9 +70,6 @@ void M() }|}|}); } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/StringLiteralExpressionStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/StringLiteralExpressionStructureTests.cs index 51e532c65c114..35d944fa7610d 100644 --- a/src/EditorFeatures/CSharpTest/Structure/StringLiteralExpressionStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/StringLiteralExpressionStructureTests.cs @@ -18,9 +18,8 @@ internal override AbstractSyntaxStructureProvider CreateProvider() => new StringLiteralExpressionStructureProvider(); [Fact] - public async Task TestMultiLineStringLiteral() - { - await VerifyBlockSpansAsync( + public Task TestMultiLineStringLiteral() + => VerifyBlockSpansAsync( """ class C { @@ -36,12 +35,10 @@ class } """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); - } [Fact] - public async Task TestMissingOnIncompleteStringLiteral() - { - await VerifyNoBlockSpansAsync( + public Task TestMissingOnIncompleteStringLiteral() + => VerifyNoBlockSpansAsync( """ class C { @@ -51,5 +48,4 @@ void M() } } """); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/SwitchExpressionStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/SwitchExpressionStructureTests.cs index 29643c549439b..5ba1f2cece608 100644 --- a/src/EditorFeatures/CSharpTest/Structure/SwitchExpressionStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/SwitchExpressionStructureTests.cs @@ -18,9 +18,8 @@ public sealed class SwitchExpressionStructureTests : AbstractCSharpSyntaxNodeStr internal override AbstractSyntaxStructureProvider CreateProvider() => new SwitchExpressionStructureProvider(); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69357")] - public async Task TestSwitchExpression1() - { - var code = """ + public Task TestSwitchExpression1() + => VerifyBlockSpansAsync(""" class C { void M(int i) @@ -30,9 +29,6 @@ void M(int i) }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/SwitchStatementStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/SwitchStatementStructureTests.cs index d759d315575fb..22f2beb20d272 100644 --- a/src/EditorFeatures/CSharpTest/Structure/SwitchStatementStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/SwitchStatementStructureTests.cs @@ -17,9 +17,8 @@ public sealed class SwitchStatementStructureTests : AbstractCSharpSyntaxNodeStru internal override AbstractSyntaxStructureProvider CreateProvider() => new SwitchStatementStructureProvider(); [Fact] - public async Task TestSwitchStatement1() - { - var code = """ + public Task TestSwitchStatement1() + => VerifyBlockSpansAsync(""" class C { void M() @@ -29,16 +28,12 @@ void M() }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestSwitchStatement2() - { - var code = """ + public Task TestSwitchStatement2() + => VerifyBlockSpansAsync(""" class C { void M() @@ -58,11 +53,8 @@ void M() }|}|} } } - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("textspan3", "hint3", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } } diff --git a/src/EditorFeatures/CSharpTest/Structure/TypeDeclarationStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/TypeDeclarationStructureTests.cs index 2158e20c78be8..4ee2abe28d481 100644 --- a/src/EditorFeatures/CSharpTest/Structure/TypeDeclarationStructureTests.cs +++ b/src/EditorFeatures/CSharpTest/Structure/TypeDeclarationStructureTests.cs @@ -17,17 +17,13 @@ public sealed class TypeDeclarationStructureTests : AbstractCSharpSyntaxNodeStru internal override AbstractSyntaxStructureProvider CreateProvider() => new TypeDeclarationStructureProvider(); [Fact] - public async Task TestClass1() - { - var code = """ + public Task TestClass1() + => VerifyBlockSpansAsync(""" {|hint:$$class C{|textspan: { }|}|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Theory] [InlineData("enum")] @@ -37,19 +33,16 @@ await VerifyBlockSpansAsync(code, [InlineData("record struct")] [InlineData("struct")] [InlineData("interface")] - public async Task TestClass2(string typeKind) - { - var code = $@" -{{|hint:$$class C{{|textspan: -{{ -}}|}}|}} -{typeKind}D -{{ -}}"; - - await VerifyBlockSpansAsync(code, + public Task TestClass2(string typeKind) + => VerifyBlockSpansAsync($$""" + {|hint:$$class C{|textspan: + { + }|}|} + {{typeKind}}D + { + } + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Theory] [InlineData("enum")] @@ -59,65 +52,50 @@ await VerifyBlockSpansAsync(code, [InlineData("record struct")] [InlineData("struct")] [InlineData("interface")] - public async Task TestClass3(string typeKind) - { - var code = $@" -{{|hint:$$class C{{|textspan: -{{ -}}|}}|}} - -{typeKind}D -{{ -}}"; - - await VerifyBlockSpansAsync(code, + public Task TestClass3(string typeKind) + => VerifyBlockSpansAsync($$""" + {|hint:$$class C{|textspan: + { + }|}|} + + {{typeKind}}D + { + } + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestClassWithLeadingComments() - { - var code = """ + public Task TestClassWithLeadingComments() + => VerifyBlockSpansAsync(""" {|span1:// Goo // Bar|} {|hint2:$$class C{|textspan2: { }|}|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestClassWithNestedComments() - { - var code = """ + public Task TestClassWithNestedComments() + => VerifyBlockSpansAsync(""" {|hint1:$$class C{|textspan1: { {|span2:// Goo // Bar|} }|}|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("span2", "// Goo ...", autoCollapse: true)); - } [Fact] - public async Task TestInterface1() - { - var code = """ + public Task TestInterface1() + => VerifyBlockSpansAsync(""" {|hint:$$interface I{|textspan: { }|}|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Theory] [InlineData("enum")] @@ -127,19 +105,16 @@ await VerifyBlockSpansAsync(code, [InlineData("record struct")] [InlineData("struct")] [InlineData("interface")] - public async Task TestInterface2(string typeKind) - { - var code = $@" -{{|hint:$$interface I{{|textspan: -{{ -}}|}}|}} -{typeKind}D -{{ -}}"; - - await VerifyBlockSpansAsync(code, + public Task TestInterface2(string typeKind) + => VerifyBlockSpansAsync($$""" + {|hint:$$interface I{|textspan: + { + }|}|} + {{typeKind}}D + { + } + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Theory] [InlineData("enum")] @@ -149,65 +124,50 @@ await VerifyBlockSpansAsync(code, [InlineData("record struct")] [InlineData("struct")] [InlineData("interface")] - public async Task TestInterface3(string typeKind) - { - var code = $@" -{{|hint:$$interface I{{|textspan: -{{ -}}|}}|}} - -{typeKind}D -{{ -}}"; - - await VerifyBlockSpansAsync(code, + public Task TestInterface3(string typeKind) + => VerifyBlockSpansAsync($$""" + {|hint:$$interface I{|textspan: + { + }|}|} + + {{typeKind}}D + { + } + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestInterfaceWithLeadingComments() - { - var code = """ + public Task TestInterfaceWithLeadingComments() + => VerifyBlockSpansAsync(""" {|span1:// Goo // Bar|} {|hint2:$$interface I{|textspan2: { }|}|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestInterfaceWithNestedComments() - { - var code = """ + public Task TestInterfaceWithNestedComments() + => VerifyBlockSpansAsync(""" {|hint1:$$interface I{|textspan1: { {|span2:// Goo // Bar|} }|}|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("span2", "// Goo ...", autoCollapse: true)); - } [Fact] - public async Task TestStruct1() - { - var code = """ + public Task TestStruct1() + => VerifyBlockSpansAsync(""" {|hint:$$struct S{|textspan: { }|}|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Theory] [InlineData("enum")] @@ -217,19 +177,16 @@ await VerifyBlockSpansAsync(code, [InlineData("record struct")] [InlineData("struct")] [InlineData("interface")] - public async Task TestStruct2(string typeKind) - { - var code = $@" -{{|hint:$$struct C{{|textspan: -{{ -}}|}}|}} -{typeKind}D -{{ -}}"; - - await VerifyBlockSpansAsync(code, + public Task TestStruct2(string typeKind) + => VerifyBlockSpansAsync($$""" + {|hint:$$struct C{|textspan: + { + }|}|} + {{typeKind}}D + { + } + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Theory] [InlineData("enum")] @@ -239,50 +196,39 @@ await VerifyBlockSpansAsync(code, [InlineData("record struct")] [InlineData("struct")] [InlineData("interface")] - public async Task TestStruct3(string typeKind) - { - var code = $@" -{{|hint:$$struct C{{|textspan: -{{ -}}|}}|}} - -{typeKind}D -{{ -}}"; - - await VerifyBlockSpansAsync(code, + public Task TestStruct3(string typeKind) + => VerifyBlockSpansAsync($$""" + {|hint:$$struct C{|textspan: + { + }|}|} + + {{typeKind}}D + { + } + """, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestStructWithLeadingComments() - { - var code = """ + public Task TestStructWithLeadingComments() + => VerifyBlockSpansAsync(""" {|span1:// Goo // Bar|} {|hint2:$$struct S{|textspan2: { }|}|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); - } [Fact] - public async Task TestStructWithNestedComments() - { - var code = """ + public Task TestStructWithNestedComments() + => VerifyBlockSpansAsync(""" {|hint1:$$struct S{|textspan1: { {|span2:// Goo // Bar|} }|}|} - """; - - await VerifyBlockSpansAsync(code, + """, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("span2", "// Goo ...", autoCollapse: true)); - } } diff --git a/src/EditorFeatures/CSharpTest/SymbolKey/SymbolKeyErrorTypeTests.cs b/src/EditorFeatures/CSharpTest/SymbolKey/SymbolKeyErrorTypeTests.cs index 7c14f32cae7fb..4d26e575e3e3f 100644 --- a/src/EditorFeatures/CSharpTest/SymbolKey/SymbolKeyErrorTypeTests.cs +++ b/src/EditorFeatures/CSharpTest/SymbolKey/SymbolKeyErrorTypeTests.cs @@ -16,7 +16,7 @@ public sealed class SymbolKeyErrorTypeTests : SymbolKeyTestBase [Fact] public void GenericType_NotMissingWithMissingTypeArgument() { - var source = """ + VerifyResolution(""" namespace N { public class C @@ -30,15 +30,13 @@ public class D { } } - """; - - VerifyResolution(source, c => c.GetMember("N.C.M")); + """, c => c.GetMember("N.C.M")); } [Fact] public void GenericType_MissingWithNonMissingTypeArgument() { - var source = """ + VerifyResolution(""" using System.Collections.Generic; namespace N @@ -54,15 +52,13 @@ public class D { } } - """; - - VerifyResolution(source, c => c.GetMember("N.C.M")); + """, c => c.GetMember("N.C.M")); } [Fact] public void GenericType_MissingWithMissingTypeArgument() { - var source = """ + VerifyResolution(""" using System.Collections.Generic; namespace N @@ -74,15 +70,13 @@ public void M(List x) } } } - """; - - VerifyResolution(source, c => c.GetMember("N.C.M")); + """, c => c.GetMember("N.C.M")); } [Fact] public void Tuple_MissingTypes() { - var source = """ + VerifyResolution(""" namespace N { public class C @@ -92,15 +86,13 @@ public void M((string, int) x) } } } - """; - - VerifyResolution(source, c => c.GetMember("N.C.M")); + """, c => c.GetMember("N.C.M")); } [Fact] public void Tuple_NonMissingTypes() { - var source = """ + VerifyResolution(""" namespace N { public class C @@ -114,15 +106,13 @@ public class D { } } - """; - - VerifyResolution(source, c => c.GetMember("N.C.M")); + """, c => c.GetMember("N.C.M")); } [Fact] public void Array_MissingElementType() { - var source = """ + VerifyResolution(""" namespace N { public class C @@ -132,15 +122,13 @@ public void M(string[] x) } } } - """; - - VerifyResolution(source, c => c.GetMember("N.C.M")); + """, c => c.GetMember("N.C.M")); } [Fact] public void Array_NonMissingElementType() { - var source = """ + VerifyResolution(""" namespace N { public class C @@ -154,15 +142,13 @@ public class D { } } - """; - - VerifyResolution(source, c => c.GetMember("N.C.M")); + """, c => c.GetMember("N.C.M")); } [Fact] public void Pointer_MissingType() { - var source = """ + VerifyResolution(""" namespace N { public class C @@ -172,15 +158,13 @@ public unsafe void M(int *x) } } } - """; - - VerifyResolution(source, c => c.GetMember("N.C.M")); + """, c => c.GetMember("N.C.M")); } [Fact] public void Pointer_NonMissingType() { - var source = """ + VerifyResolution(""" namespace N { public class C @@ -194,15 +178,13 @@ public struct S { } } - """; - - VerifyResolution(source, c => c.GetMember("N.C.M")); + """, c => c.GetMember("N.C.M")); } [Fact] public void NestedType_MissingInGenericContainer() { - var source = """ + VerifyResolution(""" using System.Collections.Generic; namespace N @@ -214,15 +196,13 @@ public void M(List.Enumerator x) } } } - """; - - VerifyResolution(source, c => c.GetMember("N.C.M")); + """, c => c.GetMember("N.C.M")); } [Fact] public void NestedType_MissingInNonGenericContainer() { - var source = """ + VerifyResolution(""" using System.Diagnostics; namespace N @@ -234,15 +214,13 @@ public void M(DebuggableAttribute.DebuggingModes x) } } } - """; - - VerifyResolution(source, c => c.GetMember("N.C.M")); + """, c => c.GetMember("N.C.M")); } [Fact] public void Method_MissingReturnType() { - var source = """ + VerifyResolution(""" namespace N { public class C @@ -253,15 +231,13 @@ public string Create() } } } - """; - - VerifyResolution(source, c => c.GetMember("N.C.Create")); + """, c => c.GetMember("N.C.Create")); } [Fact] public void Method_MissingParameterType() { - var source = """ + VerifyResolution(""" namespace N { public class C @@ -272,30 +248,26 @@ public C Create(string x) } } } - """; - - VerifyResolution(source, c => c.GetMember("N.C.Create")); + """, c => c.GetMember("N.C.Create")); } [Fact] public void Constructor_MissingParameterType() { - var source = """ + VerifyResolution(""" public class C { public C(string x) { } } - """; - - VerifyResolution(source, c => c.GetMember("C..ctor")); + """, c => c.GetMember("C..ctor")); } [Fact] public void Indexer_MissingParameterType() { - var source = """ + VerifyResolution(""" namespace N { public class C @@ -307,15 +279,13 @@ public C this[string x] } } } - """; - - VerifyResolution(source, c => c.GetMember("N.C.this[]")); + """, c => c.GetMember("N.C.this[]")); } [Fact] public void Indexer_MissingReturnType() { - var source = """ + VerifyResolution(""" namespace N { public class C @@ -327,15 +297,13 @@ public string this[C x] } } } - """; - - VerifyResolution(source, c => c.GetMember("N.C.this[]")); + """, c => c.GetMember("N.C.this[]")); } [Fact] public void Property_MissingReturnType() { - var source = """ + VerifyResolution(""" namespace N { public class C @@ -347,15 +315,13 @@ public string P } } } - """; - - VerifyResolution(source, c => c.GetMember("N.C.P")); + """, c => c.GetMember("N.C.P")); } [Fact] public void EventField_MissingReturnType() { - var source = """ + VerifyResolution(""" namespace N { public class C @@ -363,9 +329,7 @@ public class C public event System.EventHandler E; } } - """; - - VerifyResolution(source, c => c.GetMember("N.C.E")); + """, c => c.GetMember("N.C.E")); } private static void VerifyResolution(string source, Func symbolToResolve) diff --git a/src/EditorFeatures/CSharpTest/SymbolKey/SymbolKeyMetadataVsSourceTests.cs b/src/EditorFeatures/CSharpTest/SymbolKey/SymbolKeyMetadataVsSourceTests.cs index 32fee29c742d1..c6a8f17433894 100644 --- a/src/EditorFeatures/CSharpTest/SymbolKey/SymbolKeyMetadataVsSourceTests.cs +++ b/src/EditorFeatures/CSharpTest/SymbolKey/SymbolKeyMetadataVsSourceTests.cs @@ -5,6 +5,7 @@ #nullable disable using System.Linq; +using Basic.Reference.Assemblies; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -12,7 +13,6 @@ using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; -using Basic.Reference.Assemblies; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SymbolId; diff --git a/src/EditorFeatures/CSharpTest/SymbolKey/SymbolKeyTests.cs b/src/EditorFeatures/CSharpTest/SymbolKey/SymbolKeyTests.cs index 89000177ecf1f..d7a00566f2456 100644 --- a/src/EditorFeatures/CSharpTest/SymbolKey/SymbolKeyTests.cs +++ b/src/EditorFeatures/CSharpTest/SymbolKey/SymbolKeyTests.cs @@ -28,16 +28,16 @@ public static void M() { } } """; - var workspaceXml = @$" - - - - -{typeSource} - - - -"; + var workspaceXml = $""" + + + + + {typeSource} + + + + """; using var workspace = EditorTestWorkspace.Create(workspaceXml); var solution = workspace.CurrentSolution; @@ -148,16 +148,16 @@ public void Clear() { } } """.Replace("<", "<").Replace(">", ">"); - var workspaceXml = @$" - - - - -{typeSource} - - - -"; + var workspaceXml = $""" + + + + + {typeSource} + + + + """; using var workspace = EditorTestWorkspace.Create(workspaceXml); var solution = workspace.CurrentSolution; @@ -233,21 +233,21 @@ void M() // Randomize the order of the projects in the workspace. if (random.Next() % 2 == 0) { - return TestWorkspace.CreateWorkspace(XElement.Parse($@" - - {bodyProject} - {referenceProject} - -")); + return TestWorkspace.CreateWorkspace(XElement.Parse($""" + + {bodyProject} + {referenceProject} + + """)); } else { - return TestWorkspace.CreateWorkspace(XElement.Parse($@" - - {referenceProject} - {bodyProject} - -")); + return TestWorkspace.CreateWorkspace(XElement.Parse($""" + + {referenceProject} + {bodyProject} + + """)); } } diff --git a/src/EditorFeatures/CSharpTest/TaskList/CSharpTaskListTests.cs b/src/EditorFeatures/CSharpTest/TaskList/CSharpTaskListTests.cs index 7c33da8c171a5..f8b811f56f19f 100644 --- a/src/EditorFeatures/CSharpTest/TaskList/CSharpTaskListTests.cs +++ b/src/EditorFeatures/CSharpTest/TaskList/CSharpTaskListTests.cs @@ -17,157 +17,89 @@ protected override EditorTestWorkspace CreateWorkspace(string codeWithMarker, Te => EditorTestWorkspace.CreateCSharp(codeWithMarker, composition: composition); [Theory, CombinatorialData] - public async Task SingleLineTodoComment_Colon(TestHost host) - { - var code = @"// [|TODO:test|]"; - - await TestAsync(code, host); - } + public Task SingleLineTodoComment_Colon(TestHost host) + => TestAsync(@"// [|TODO:test|]", host); [Theory, CombinatorialData] - public async Task SingleLineTodoComment_Space(TestHost host) - { - var code = @"// [|TODO test|]"; - - await TestAsync(code, host); - } + public Task SingleLineTodoComment_Space(TestHost host) + => TestAsync(@"// [|TODO test|]", host); [Theory, CombinatorialData] - public async Task SingleLineTodoComment_Underscore(TestHost host) - { - var code = @"// TODO_test"; - - await TestAsync(code, host); - } + public Task SingleLineTodoComment_Underscore(TestHost host) + => TestAsync(@"// TODO_test", host); [Theory, CombinatorialData] - public async Task SingleLineTodoComment_Number(TestHost host) - { - var code = @"// TODO1 test"; - - await TestAsync(code, host); - } + public Task SingleLineTodoComment_Number(TestHost host) + => TestAsync(@"// TODO1 test", host); [Theory, CombinatorialData] - public async Task SingleLineTodoComment_Quote(TestHost host) - { - var code = """ + public Task SingleLineTodoComment_Quote(TestHost host) + => TestAsync(""" // "TODO test" - """; - - await TestAsync(code, host); - } + """, host); [Theory, CombinatorialData] - public async Task SingleLineTodoComment_Middle(TestHost host) - { - var code = @"// Hello TODO test"; - - await TestAsync(code, host); - } + public Task SingleLineTodoComment_Middle(TestHost host) + => TestAsync(@"// Hello TODO test", host); [Theory, CombinatorialData] - public async Task SingleLineTodoComment_Document(TestHost host) - { - var code = @"/// [|TODO test|]"; - - await TestAsync(code, host); - } + public Task SingleLineTodoComment_Document(TestHost host) + => TestAsync(@"/// [|TODO test|]", host); [Theory, CombinatorialData] - public async Task SingleLineTodoComment_Preprocessor1(TestHost host) - { - var code = @"#if DEBUG // [|TODO test|]"; - - await TestAsync(code, host); - } + public Task SingleLineTodoComment_Preprocessor1(TestHost host) + => TestAsync(@"#if DEBUG // [|TODO test|]", host); [Theory, CombinatorialData] - public async Task SingleLineTodoComment_Preprocessor2(TestHost host) - { - var code = @"#if DEBUG /// [|TODO test|]"; - - await TestAsync(code, host); - } + public Task SingleLineTodoComment_Preprocessor2(TestHost host) + => TestAsync(@"#if DEBUG /// [|TODO test|]", host); [Theory, CombinatorialData] - public async Task SingleLineTodoComment_Region(TestHost host) - { - var code = @"#region // TODO test"; - - await TestAsync(code, host); - } + public Task SingleLineTodoComment_Region(TestHost host) + => TestAsync(@"#region // TODO test", host); [Theory, CombinatorialData] - public async Task SingleLineTodoComment_EndRegion(TestHost host) - { - var code = @"#endregion // [|TODO test|]"; - - await TestAsync(code, host); - } + public Task SingleLineTodoComment_EndRegion(TestHost host) + => TestAsync(@"#endregion // [|TODO test|]", host); [Theory, CombinatorialData] - public async Task SingleLineTodoComment_TrailingSpan(TestHost host) - { - var code = @"// [|TODO test |]"; - - await TestAsync(code, host); - } + public Task SingleLineTodoComment_TrailingSpan(TestHost host) + => TestAsync(@"// [|TODO test |]", host); [Theory, CombinatorialData] - public async Task MultilineTodoComment_Singleline(TestHost host) - { - var code = @"/* [|TODO: hello |]*/"; - - await TestAsync(code, host); - } + public Task MultilineTodoComment_Singleline(TestHost host) + => TestAsync(@"/* [|TODO: hello |]*/", host); [Theory, CombinatorialData] - public async Task MultilineTodoComment_Singleline_Document(TestHost host) - { - var code = @"/** [|TODO: hello |]*/"; - - await TestAsync(code, host); - } + public Task MultilineTodoComment_Singleline_Document(TestHost host) + => TestAsync(@"/** [|TODO: hello |]*/", host); [Theory, CombinatorialData] - public async Task MultilineTodoComment_Multiline(TestHost host) - { - var code = """ + public Task MultilineTodoComment_Multiline(TestHost host) + => TestAsync(""" /* [|TODO: hello |] [|TODO: hello |] [|TODO: hello |] * [|TODO: hello |] [|TODO: hello |]*/ - """; - - await TestAsync(code, host); - } + """, host); [Theory, CombinatorialData] - public async Task MultilineTodoComment_Multiline_DocComment(TestHost host) - { - var code = """ + public Task MultilineTodoComment_Multiline_DocComment(TestHost host) + => TestAsync(""" /** [|TODO: hello |] [|TODO: hello |] [|TODO: hello |] * [|TODO: hello |] [|TODO: hello |]*/ - """; - - await TestAsync(code, host); - } + """, host); [Theory, CombinatorialData] - public async Task SinglelineDocumentComment_Multiline(TestHost host) - { - var code = """ + public Task SinglelineDocumentComment_Multiline(TestHost host) + => TestAsync(""" /// /// [|TODO : test |] /// /// [|UNDONE: test2 |] - """; - - await TestAsync(code, host); - } + """, host); } diff --git a/src/EditorFeatures/CSharpTest/TaskList/NoCompilationTaskListTests.cs b/src/EditorFeatures/CSharpTest/TaskList/NoCompilationTaskListTests.cs index 01683a5e95029..f292c41ea66dc 100644 --- a/src/EditorFeatures/CSharpTest/TaskList/NoCompilationTaskListTests.cs +++ b/src/EditorFeatures/CSharpTest/TaskList/NoCompilationTaskListTests.cs @@ -28,11 +28,13 @@ public sealed class NoCompilationTaskListTests : AbstractTaskListTests protected override EditorTestWorkspace CreateWorkspace(string codeWithMarker, TestComposition composition) { var workspace = EditorTestWorkspace.CreateWorkspace(XElement.Parse( -$@" - - {codeWithMarker} - -"), composition: composition.AddParts( + $""" + + + {codeWithMarker} + + + """), composition: composition.AddParts( typeof(NoCompilationContentTypeDefinitions), typeof(NoCompilationContentTypeLanguageService), typeof(NoCompilationTaskListService))); @@ -41,12 +43,8 @@ protected override EditorTestWorkspace CreateWorkspace(string codeWithMarker, Te } [Theory, CombinatorialData, WorkItem("https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1192024")] - public async Task TodoCommentInNoCompilationProject(TestHost host) - { - var code = @"(* [|Message|] *)"; - - await TestAsync(code, host); - } + public Task TodoCommentInNoCompilationProject(TestHost host) + => TestAsync(@"(* [|Message|] *)", host); } [PartNotDiscoverable] diff --git a/src/EditorFeatures/CSharpTest/TextStructureNavigation/TextStructureNavigatorTests.cs b/src/EditorFeatures/CSharpTest/TextStructureNavigation/TextStructureNavigatorTests.cs index 0d4299d121c1b..a89a6bbb6790b 100644 --- a/src/EditorFeatures/CSharpTest/TextStructureNavigation/TextStructureNavigatorTests.cs +++ b/src/EditorFeatures/CSharpTest/TextStructureNavigation/TextStructureNavigatorTests.cs @@ -565,7 +565,9 @@ public void TestClampStringLiteral(string content) [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/77401")] [InlineData(@"{|Significant:""|}$$")] [InlineData(@"{|Significant:""""""|}$$")] - [InlineData(@"""""""{|Significant:u8|}$$")] + [InlineData("""" + """{|Significant:u8|}$$ + """")] public void TestClampStringLiteral_Invalid(string content) { AssertExtent(content); diff --git a/src/EditorFeatures/CSharpTest/TypeInferrer/TypeInferrerTests.Delegate.cs b/src/EditorFeatures/CSharpTest/TypeInferrer/TypeInferrerTests.Delegate.cs index f7c647357e926..c014e64babd62 100644 --- a/src/EditorFeatures/CSharpTest/TypeInferrer/TypeInferrerTests.Delegate.cs +++ b/src/EditorFeatures/CSharpTest/TypeInferrer/TypeInferrerTests.Delegate.cs @@ -36,10 +36,8 @@ private async Task TestDelegateAsync(string text, string expectedType) } [Fact] - public async Task TestDeclaration1() - { - var text = - """ + public Task TestDeclaration1() + => TestDelegateAsync(""" using System; class C { @@ -48,16 +46,11 @@ void M() Func q = [|here|]; } } - """; - - await TestDelegateAsync(text, "System.Func"); - } + """, "System.Func"); [Fact] - public async Task TestAssignment1() - { - var text = - """ + public Task TestAssignment1() + => TestDelegateAsync(""" using System; class C { @@ -67,16 +60,11 @@ void M() f = [|here|] } } - """; - - await TestDelegateAsync(text, "System.Func"); - } + """, "System.Func"); [Fact] - public async Task TestArgument1() - { - var text = - """ + public Task TestArgument1() + => TestDelegateAsync(""" using System; class C { @@ -87,16 +75,11 @@ void M() void Bar(Func f); } - """; - - await TestDelegateAsync(text, "System.Func"); - } + """, "System.Func"); [Fact] - public async Task TestConstructor1() - { - var text = - """ + public Task TestConstructor1() + => TestDelegateAsync(""" using System; class C { @@ -107,16 +90,11 @@ void M() public C(Func f); } - """; - - await TestDelegateAsync(text, "System.Func"); - } + """, "System.Func"); [Fact] - public async Task TestDelegateConstructor1() - { - var text = - """ + public Task TestDelegateConstructor1() + => TestDelegateAsync(""" using System; class C { @@ -125,16 +103,11 @@ void M() new Func([|here|]); } } - """; - - await TestDelegateAsync(text, "System.Func"); - } + """, "System.Func"); [Fact] - public async Task TestCastExpression1() - { - var text = - """ + public Task TestCastExpression1() + => TestDelegateAsync(""" using System; class C { @@ -143,16 +116,11 @@ void M() (Func)[|here|] } } - """; - - await TestDelegateAsync(text, "System.Func"); - } + """, "System.Func"); [Fact] - public async Task TestCastExpression2() - { - var text = - """ + public Task TestCastExpression2() + => TestDelegateAsync(""" using System; class C { @@ -161,16 +129,11 @@ void M() (Func)([|here|] } } - """; - - await TestDelegateAsync(text, "System.Func"); - } + """, "System.Func"); [Fact] - public async Task TestReturnFromMethod() - { - var text = - """ + public Task TestReturnFromMethod() + => TestDelegateAsync(""" using System; class C { @@ -179,16 +142,11 @@ Func M() return [|here|] } } - """; - - await TestDelegateAsync(text, "System.Func"); - } + """, "System.Func"); [Fact] - public async Task TestInsideLambda1() - { - var text = - """ + public Task TestInsideLambda1() + => TestDelegateAsync(""" using System; class C { @@ -197,8 +155,5 @@ void M() Func> f = i => [|here|] } } - """; - - await TestDelegateAsync(text, "System.Func"); - } + """, "System.Func"); } diff --git a/src/EditorFeatures/CSharpTest/TypeInferrer/TypeInferrerTests.cs b/src/EditorFeatures/CSharpTest/TypeInferrer/TypeInferrerTests.cs index 24133018652af..9d96f4cc80792 100644 --- a/src/EditorFeatures/CSharpTest/TypeInferrer/TypeInferrerTests.cs +++ b/src/EditorFeatures/CSharpTest/TypeInferrer/TypeInferrerTests.cs @@ -87,160 +87,118 @@ private static ExpressionSyntax FindExpressionSyntaxFromSpan(SyntaxNode root, Te } [Fact] - public async Task TestConditional1() - { - // We do not support position inference here as we're before the ? and we only look - // backwards to infer a type here. - await TestInMethodAsync( + public Task TestConditional1() + => TestInMethodAsync( @"var q = [|Goo()|] ? 1 : 2;", "global::System.Boolean", TestMode.Node); - } [Theory, CombinatorialData] - public async Task TestConditional2(TestMode mode) - { - await TestInMethodAsync( + public Task TestConditional2(TestMode mode) + => TestInMethodAsync( @"var q = a ? [|Goo()|] : 2;", "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestConditional3(TestMode mode) - { - await TestInMethodAsync( + public Task TestConditional3(TestMode mode) + => TestInMethodAsync( @"var q = a ? """" : [|Goo()|];", "global::System.String", mode); - } [Theory, CombinatorialData] - public async Task TestVariableDeclarator1(TestMode mode) - { - await TestInMethodAsync( + public Task TestVariableDeclarator1(TestMode mode) + => TestInMethodAsync( @"int q = [|Goo()|];", "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestVariableDeclarator2(TestMode mode) - { - await TestInMethodAsync( + public Task TestVariableDeclarator2(TestMode mode) + => TestInMethodAsync( @"var q = [|Goo()|];", "global::System.Object", mode); - } [Theory, CombinatorialData] - public async Task TestVariableDeclaratorNullableReferenceType(TestMode mode) - { - await TestInMethodAsync( + public Task TestVariableDeclaratorNullableReferenceType(TestMode mode) + => TestInMethodAsync( """ #nullable enable string? q = [|Goo()|]; """, "global::System.String?", mode); - } [Fact] - public async Task TestCoalesce1() - { - await TestInMethodAsync( + public Task TestCoalesce1() + => TestInMethodAsync( @"var q = [|Goo()|] ?? 1;", "global::System.Int32?", TestMode.Node); - } [Theory, CombinatorialData] - public async Task TestCoalesce2(TestMode mode) - { - await TestInMethodAsync( + public Task TestCoalesce2(TestMode mode) + => TestInMethodAsync( """ bool? b; var q = b ?? [|Goo()|]; """, "global::System.Boolean", mode); - } [Theory, CombinatorialData] - public async Task TestCoalesce3(TestMode mode) - { - await TestInMethodAsync( + public Task TestCoalesce3(TestMode mode) + => TestInMethodAsync( """ string s; var q = s ?? [|Goo()|]; """, "global::System.String", mode); - } [Fact] - public async Task TestCoalesce4() - { - await TestInMethodAsync( + public Task TestCoalesce4() + => TestInMethodAsync( @"var q = [|Goo()|] ?? string.Empty;", "global::System.String?", TestMode.Node); - } [Fact] - public async Task TestCoalesceWithErrorType() - { - // We could be smart and infer this as an ErrorType?, but in the #nullable disable case we don't know if this is intended to be - // a struct (where the question mark is legal) or a class (where it isn't). We'll thus avoid sticking question marks in this case. - // https://github.com/dotnet/roslyn/issues/37852 tracks fixing this is a much fancier way. - await TestInMethodAsync( + public Task TestCoalesceWithErrorType() + => TestInMethodAsync( """ ErrorType s; var q = [|Goo()|] ?? s; """, "ErrorType", TestMode.Node); - } [Theory, CombinatorialData] - public async Task TestBinaryExpression1(TestMode mode) - { - await TestInMethodAsync( + public Task TestBinaryExpression1(TestMode mode) + => TestInMethodAsync( """ string s; var q = s + [|Goo()|]; """, "global::System.String", mode); - } [Theory, CombinatorialData] - public async Task TestBinaryExpression2(TestMode mode) - { - await TestInMethodAsync( + public Task TestBinaryExpression2(TestMode mode) + => TestInMethodAsync( """ var s; var q = s || [|Goo()|]; """, "global::System.Boolean", mode); - } [Theory, CombinatorialData] - public async Task TestBinaryOperator1(TestMode mode) - { - await TestInMethodAsync( + public Task TestBinaryOperator1(TestMode mode) + => TestInMethodAsync( @"var q = x << [|Goo()|];", "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestBinaryOperator2(TestMode mode) - { - await TestInMethodAsync( + public Task TestBinaryOperator2(TestMode mode) + => TestInMethodAsync( @"var q = x >> [|Goo()|];", "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestBinaryOperator3(TestMode mode) - { - await TestInMethodAsync( + public Task TestBinaryOperator3(TestMode mode) + => TestInMethodAsync( @"var q = x >>> [|Goo()|];", "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestAssignmentOperator3(TestMode mode) - { - await TestInMethodAsync( + public Task TestAssignmentOperator3(TestMode mode) + => TestInMethodAsync( @"var q <<= [|Goo()|];", "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestAssignmentOperator4(TestMode mode) - { - await TestInMethodAsync( + public Task TestAssignmentOperator4(TestMode mode) + => TestInMethodAsync( @"var q >>= [|Goo()|];", "global::System.Int32", mode); - } [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestOverloadedConditionalLogicalOperatorsInferBool(TestMode mode) - { - await TestAsync( + public Task TestOverloadedConditionalLogicalOperatorsInferBool(TestMode mode) + => TestAsync( """ using System; @@ -267,13 +225,11 @@ static void Main(string[] args) } } """, "global::System.Boolean", mode); - } [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestConditionalLogicalOrOperatorAlwaysInfersBool(TestMode mode) - { - var text = """ + public Task TestConditionalLogicalOrOperatorAlwaysInfersBool(TestMode mode) + => TestAsync(""" using System; class C { @@ -282,15 +238,12 @@ static void Main(string[] args) var x = a || [|7|]; } } - """; - await TestAsync(text, "global::System.Boolean", mode); - } + """, "global::System.Boolean", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestConditionalLogicalAndOperatorAlwaysInfersBool(TestMode mode) - { - var text = """ + public Task TestConditionalLogicalAndOperatorAlwaysInfersBool(TestMode mode) + => TestAsync(""" using System; class C { @@ -299,14 +252,11 @@ static void Main(string[] args) var x = a && [|7|]; } } - """; - await TestAsync(text, "global::System.Boolean", mode); - } + """, "global::System.Boolean", mode); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalOrOperatorInference1() - { - var text = """ + public Task TestLogicalOrOperatorInference1() + => TestAsync(""" using System; class C { @@ -315,14 +265,11 @@ static void Main(string[] args) var x = [|a|] | true; } } - """; - await TestAsync(text, "global::System.Boolean", TestMode.Node); - } + """, "global::System.Boolean", TestMode.Node); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalOrOperatorInference2() - { - var text = """ + public Task TestLogicalOrOperatorInference2() + => TestAsync(""" using System; class C { @@ -331,15 +278,12 @@ static void Main(string[] args) var x = [|a|] | b | c || d; } } - """; - await TestAsync(text, "global::System.Boolean", TestMode.Node); - } + """, "global::System.Boolean", TestMode.Node); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalOrOperatorInference3(TestMode mode) - { - var text = """ + public Task TestLogicalOrOperatorInference3(TestMode mode) + => TestAsync(""" using System; class C { @@ -348,14 +292,11 @@ static void Main(string[] args) var x = a | b | [|c|] || d; } } - """; - await TestAsync(text, "global::System.Boolean", mode); - } + """, "global::System.Boolean", mode); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalOrOperatorInference4() - { - var text = """ + public Task TestLogicalOrOperatorInference4() + => TestAsync(""" using System; class C { @@ -368,15 +309,12 @@ static object Goo(Program p) return p; } } - """; - await TestAsync(text, "Program", TestMode.Node); - } + """, "Program", TestMode.Node); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalOrOperatorInference5(TestMode mode) - { - var text = """ + public Task TestLogicalOrOperatorInference5(TestMode mode) + => TestAsync(""" using System; class C { @@ -389,14 +327,11 @@ static object Goo(bool p) return p; } } - """; - await TestAsync(text, "global::System.Boolean", mode); - } + """, "global::System.Boolean", mode); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalOrOperatorInference6() - { - var text = """ + public Task TestLogicalOrOperatorInference6() + => TestAsync(""" using System; class C { @@ -405,15 +340,12 @@ static void Main(string[] args) if (([|x|] | y) != 0) {} } } - """; - await TestAsync(text, "global::System.Int32", TestMode.Node); - } + """, "global::System.Int32", TestMode.Node); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalOrOperatorInference7(TestMode mode) - { - var text = """ + public Task TestLogicalOrOperatorInference7(TestMode mode) + => TestAsync(""" using System; class C { @@ -422,14 +354,11 @@ static void Main(string[] args) if ([|x|] | y) {} } } - """; - await TestAsync(text, "global::System.Boolean", mode); - } + """, "global::System.Boolean", mode); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalAndOperatorInference1() - { - var text = """ + public Task TestLogicalAndOperatorInference1() + => TestAsync(""" using System; class C { @@ -438,14 +367,11 @@ static void Main(string[] args) var x = [|a|] & true; } } - """; - await TestAsync(text, "global::System.Boolean", TestMode.Node); - } + """, "global::System.Boolean", TestMode.Node); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalAndOperatorInference2() - { - var text = """ + public Task TestLogicalAndOperatorInference2() + => TestAsync(""" using System; class C { @@ -454,15 +380,12 @@ static void Main(string[] args) var x = [|a|] & b & c && d; } } - """; - await TestAsync(text, "global::System.Boolean", TestMode.Node); - } + """, "global::System.Boolean", TestMode.Node); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalAndOperatorInference3(TestMode mode) - { - var text = """ + public Task TestLogicalAndOperatorInference3(TestMode mode) + => TestAsync(""" using System; class C { @@ -471,14 +394,11 @@ static void Main(string[] args) var x = a & b & [|c|] && d; } } - """; - await TestAsync(text, "global::System.Boolean", mode); - } + """, "global::System.Boolean", mode); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalAndOperatorInference4() - { - var text = """ + public Task TestLogicalAndOperatorInference4() + => TestAsync(""" using System; class C { @@ -491,15 +411,12 @@ static object Goo(Program p) return p; } } - """; - await TestAsync(text, "Program", TestMode.Node); - } + """, "Program", TestMode.Node); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalAndOperatorInference5(TestMode mode) - { - var text = """ + public Task TestLogicalAndOperatorInference5(TestMode mode) + => TestAsync(""" using System; class C { @@ -512,14 +429,11 @@ static object Goo(bool p) return p; } } - """; - await TestAsync(text, "global::System.Boolean", mode); - } + """, "global::System.Boolean", mode); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalAndOperatorInference6() - { - var text = """ + public Task TestLogicalAndOperatorInference6() + => TestAsync(""" using System; class C { @@ -528,15 +442,12 @@ static void Main(string[] args) if (([|x|] & y) != 0) {} } } - """; - await TestAsync(text, "global::System.Int32", TestMode.Node); - } + """, "global::System.Int32", TestMode.Node); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalAndOperatorInference7(TestMode mode) - { - var text = """ + public Task TestLogicalAndOperatorInference7(TestMode mode) + => TestAsync(""" using System; class C { @@ -545,14 +456,11 @@ static void Main(string[] args) if ([|x|] & y) {} } } - """; - await TestAsync(text, "global::System.Boolean", mode); - } + """, "global::System.Boolean", mode); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalXorOperatorInference1() - { - var text = """ + public Task TestLogicalXorOperatorInference1() + => TestAsync(""" using System; class C { @@ -561,14 +469,11 @@ static void Main(string[] args) var x = [|a|] ^ true; } } - """; - await TestAsync(text, "global::System.Boolean", TestMode.Node); - } + """, "global::System.Boolean", TestMode.Node); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalXorOperatorInference2() - { - var text = """ + public Task TestLogicalXorOperatorInference2() + => TestAsync(""" using System; class C { @@ -577,15 +482,12 @@ static void Main(string[] args) var x = [|a|] ^ b ^ c && d; } } - """; - await TestAsync(text, "global::System.Boolean", TestMode.Node); - } + """, "global::System.Boolean", TestMode.Node); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalXorOperatorInference3(TestMode mode) - { - var text = """ + public Task TestLogicalXorOperatorInference3(TestMode mode) + => TestAsync(""" using System; class C { @@ -594,14 +496,11 @@ static void Main(string[] args) var x = a ^ b ^ [|c|] && d; } } - """; - await TestAsync(text, "global::System.Boolean", mode); - } + """, "global::System.Boolean", mode); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalXorOperatorInference4() - { - var text = """ + public Task TestLogicalXorOperatorInference4() + => TestAsync(""" using System; class C { @@ -614,15 +513,12 @@ static object Goo(Program p) return p; } } - """; - await TestAsync(text, "Program", TestMode.Node); - } + """, "Program", TestMode.Node); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalXorOperatorInference5(TestMode mode) - { - var text = """ + public Task TestLogicalXorOperatorInference5(TestMode mode) + => TestAsync(""" using System; class C { @@ -635,14 +531,11 @@ static object Goo(bool p) return p; } } - """; - await TestAsync(text, "global::System.Boolean", mode); - } + """, "global::System.Boolean", mode); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalXorOperatorInference6() - { - var text = """ + public Task TestLogicalXorOperatorInference6() + => TestAsync(""" using System; class C { @@ -651,15 +544,12 @@ static void Main(string[] args) if (([|x|] ^ y) != 0) {} } } - """; - await TestAsync(text, "global::System.Int32", TestMode.Node); - } + """, "global::System.Int32", TestMode.Node); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalXorOperatorInference7(TestMode mode) - { - var text = """ + public Task TestLogicalXorOperatorInference7(TestMode mode) + => TestAsync(""" using System; class C { @@ -668,15 +558,12 @@ static void Main(string[] args) if ([|x|] ^ y) {} } } - """; - await TestAsync(text, "global::System.Boolean", mode); - } + """, "global::System.Boolean", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalOrEqualsOperatorInference1(TestMode mode) - { - var text = """ + public Task TestLogicalOrEqualsOperatorInference1(TestMode mode) + => TestAsync(""" using System; class C { @@ -685,15 +572,12 @@ static void Main(string[] args) if ([|x|] |= y) {} } } - """; - await TestAsync(text, "global::System.Boolean", mode); - } + """, "global::System.Boolean", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalOrEqualsOperatorInference2(TestMode mode) - { - var text = """ + public Task TestLogicalOrEqualsOperatorInference2(TestMode mode) + => TestAsync(""" using System; class C { @@ -702,15 +586,12 @@ static void Main(string[] args) int z = [|x|] |= y; } } - """; - await TestAsync(text, "global::System.Int32", mode); - } + """, "global::System.Int32", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalAndEqualsOperatorInference1(TestMode mode) - { - var text = """ + public Task TestLogicalAndEqualsOperatorInference1(TestMode mode) + => TestAsync(""" using System; class C { @@ -719,15 +600,12 @@ static void Main(string[] args) if ([|x|] &= y) {} } } - """; - await TestAsync(text, "global::System.Boolean", mode); - } + """, "global::System.Boolean", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalAndEqualsOperatorInference2(TestMode mode) - { - var text = """ + public Task TestLogicalAndEqualsOperatorInference2(TestMode mode) + => TestAsync(""" using System; class C { @@ -736,15 +614,12 @@ static void Main(string[] args) int z = [|x|] &= y; } } - """; - await TestAsync(text, "global::System.Int32", mode); - } + """, "global::System.Int32", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalXorEqualsOperatorInference1(TestMode mode) - { - var text = """ + public Task TestLogicalXorEqualsOperatorInference1(TestMode mode) + => TestAsync(""" using System; class C { @@ -753,15 +628,12 @@ static void Main(string[] args) if ([|x|] ^= y) {} } } - """; - await TestAsync(text, "global::System.Boolean", mode); - } + """, "global::System.Boolean", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] - public async Task TestLogicalXorEqualsOperatorInference2(TestMode mode) - { - var text = """ + public Task TestLogicalXorEqualsOperatorInference2(TestMode mode) + => TestAsync(""" using System; class C { @@ -770,50 +642,41 @@ static void Main(string[] args) int z = [|x|] ^= y; } } - """; - await TestAsync(text, "global::System.Int32", mode); - } + """, "global::System.Int32", mode); [Theory, CombinatorialData] - public async Task TestReturnInConstructor(TestMode mode) - { - await TestInClassAsync( + public Task TestReturnInConstructor(TestMode mode) + => TestInClassAsync( """ C() { return [|Goo()|]; } """, "void", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInDestructor(TestMode mode) - { - await TestInClassAsync( + public Task TestReturnInDestructor(TestMode mode) + => TestInClassAsync( """ ~C() { return [|Goo()|]; } """, "void", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInMethod(TestMode mode) - { - await TestInClassAsync( + public Task TestReturnInMethod(TestMode mode) + => TestInClassAsync( """ int M() { return [|Goo()|]; } """, "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInMethodNullableReference(TestMode mode) - { - await TestInClassAsync( + public Task TestReturnInMethodNullableReference(TestMode mode) + => TestInClassAsync( """ #nullable enable string? M() @@ -821,96 +684,80 @@ await TestInClassAsync( return [|Goo()|]; } """, "global::System.String?", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInVoidMethod(TestMode mode) - { - await TestInClassAsync( + public Task TestReturnInVoidMethod(TestMode mode) + => TestInClassAsync( """ void M() { return [|Goo()|]; } """, "void", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInAsyncTaskOfTMethod(TestMode mode) - { - await TestInClassAsync( + public Task TestReturnInAsyncTaskOfTMethod(TestMode mode) + => TestInClassAsync( """ async System.Threading.Tasks.Task M() { return [|Goo()|]; } """, "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInAsyncTaskOfTMethodNestedNullability(TestMode mode) - { - await TestInClassAsync( + public Task TestReturnInAsyncTaskOfTMethodNestedNullability(TestMode mode) + => TestInClassAsync( """ async System.Threading.Tasks.Task M() { return [|Goo()|]; } """, "global::System.String?", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInAsyncTaskMethod(TestMode mode) - { - await TestInClassAsync( + public Task TestReturnInAsyncTaskMethod(TestMode mode) + => TestInClassAsync( """ async System.Threading.Tasks.Task M() { return [|Goo()|]; } """, "void", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInAsyncVoidMethod(TestMode mode) - { - await TestInClassAsync( + public Task TestReturnInAsyncVoidMethod(TestMode mode) + => TestInClassAsync( """ async void M() { return [|Goo()|]; } """, "void", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInOperator(TestMode mode) - { - await TestInClassAsync( + public Task TestReturnInOperator(TestMode mode) + => TestInClassAsync( """ public static C operator ++(C c) { return [|Goo()|]; } """, "global::C", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInConversionOperator(TestMode mode) - { - await TestInClassAsync( + public Task TestReturnInConversionOperator(TestMode mode) + => TestInClassAsync( """ public static implicit operator int(C c) { return [|Goo()|]; } """, "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInPropertyGetter(TestMode mode) - { - await TestInClassAsync( + public Task TestReturnInPropertyGetter(TestMode mode) + => TestInClassAsync( """ int P { @@ -920,12 +767,10 @@ int P } } """, "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInPropertyGetterNullableReference(TestMode mode) - { - await TestInClassAsync( + public Task TestReturnInPropertyGetterNullableReference(TestMode mode) + => TestInClassAsync( """ #nullable enable string? P @@ -936,12 +781,10 @@ await TestInClassAsync( } } """, "global::System.String?", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInPropertySetter(TestMode mode) - { - await TestInClassAsync( + public Task TestReturnInPropertySetter(TestMode mode) + => TestInClassAsync( """ int P { @@ -951,12 +794,10 @@ int P } } """, "void", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInIndexerGetter(TestMode mode) - { - await TestInClassAsync( + public Task TestReturnInIndexerGetter(TestMode mode) + => TestInClassAsync( """ int this[int i] { @@ -966,12 +807,10 @@ int this[int i] } } """, "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInIndexerGetterNullableReference(TestMode mode) - { - await TestInClassAsync( + public Task TestReturnInIndexerGetterNullableReference(TestMode mode) + => TestInClassAsync( """ #nullable enable string? this[int i] @@ -982,12 +821,10 @@ await TestInClassAsync( } } """, "global::System.String?", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInIndexerSetter(TestMode mode) - { - await TestInClassAsync( + public Task TestReturnInIndexerSetter(TestMode mode) + => TestInClassAsync( """ int this[int i] { @@ -997,12 +834,10 @@ int this[int i] } } """, "void", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInEventAdder(TestMode mode) - { - await TestInClassAsync( + public Task TestReturnInEventAdder(TestMode mode) + => TestInClassAsync( """ event System.EventHandler E { @@ -1013,12 +848,10 @@ event System.EventHandler E remove { } } """, "void", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInEventRemover(TestMode mode) - { - await TestInClassAsync( + public Task TestReturnInEventRemover(TestMode mode) + => TestInClassAsync( """ event System.EventHandler E { @@ -1029,12 +862,10 @@ event System.EventHandler E } } """, "void", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInLocalFunction(TestMode mode) - { - await TestInClassAsync( + public Task TestReturnInLocalFunction(TestMode mode) + => TestInClassAsync( """ void M() { @@ -1044,12 +875,10 @@ int F() } } """, "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInLocalFunctionNullableReference(TestMode mode) - { - await TestInClassAsync( + public Task TestReturnInLocalFunctionNullableReference(TestMode mode) + => TestInClassAsync( """ #nullable enable void M() @@ -1060,12 +889,10 @@ void M() } } """, "global::System.String?", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInAsyncTaskOfTLocalFunction(TestMode mode) - { - await TestInClassAsync( + public Task TestReturnInAsyncTaskOfTLocalFunction(TestMode mode) + => TestInClassAsync( """ void M() { @@ -1075,12 +902,10 @@ async System.Threading.Tasks.Task F() } } """, "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInAsyncTaskLocalFunction(TestMode mode) - { - await TestInClassAsync( + public Task TestReturnInAsyncTaskLocalFunction(TestMode mode) + => TestInClassAsync( """ void M() { @@ -1090,12 +915,10 @@ async System.Threading.Tasks.Task F() } } """, "void", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInAsyncVoidLocalFunction(TestMode mode) - { - await TestInClassAsync( + public Task TestReturnInAsyncVoidLocalFunction(TestMode mode) + => TestInClassAsync( """ void M() { @@ -1105,257 +928,202 @@ async void F() } } """, "void", mode); - } [Theory, CombinatorialData] - public async Task TestExpressionBodiedConstructor(TestMode mode) - { - await TestInClassAsync( + public Task TestExpressionBodiedConstructor(TestMode mode) + => TestInClassAsync( @"C() => [|Goo()|];", "void", mode); - } [Theory, CombinatorialData] - public async Task TestExpressionBodiedDestructor(TestMode mode) - { - await TestInClassAsync( + public Task TestExpressionBodiedDestructor(TestMode mode) + => TestInClassAsync( @"~C() => [|Goo()|];", "void", mode); - } [Theory, CombinatorialData] - public async Task TestExpressionBodiedMethod(TestMode mode) - { - await TestInClassAsync( + public Task TestExpressionBodiedMethod(TestMode mode) + => TestInClassAsync( @"int M() => [|Goo()|];", "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestExpressionBodiedVoidMethod(TestMode mode) - { - await TestInClassAsync( + public Task TestExpressionBodiedVoidMethod(TestMode mode) + => TestInClassAsync( @"void M() => [|Goo()|];", "void", mode); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/27647"), CombinatorialData] - public async Task TestExpressionBodiedAsyncTaskOfTMethod(TestMode mode) - { - await TestInClassAsync( + public Task TestExpressionBodiedAsyncTaskOfTMethod(TestMode mode) + => TestInClassAsync( @"async System.Threading.Tasks.Task M() => [|Goo()|];", "global::System.Int32", mode); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/27647"), CombinatorialData] - public async Task TestExpressionBodiedAsyncTaskOfTMethodNullableReference(TestMode mode) - { - await TestInClassAsync( + public Task TestExpressionBodiedAsyncTaskOfTMethodNullableReference(TestMode mode) + => TestInClassAsync( """ #nullable enable async System.Threading.Tasks.Task M() => [|Goo()|]; """, "global::System.String?", mode); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/27647"), CombinatorialData] - public async Task TestExpressionBodiedAsyncTaskMethod(TestMode mode) - { - await TestInClassAsync( + public Task TestExpressionBodiedAsyncTaskMethod(TestMode mode) + => TestInClassAsync( @"async System.Threading.Tasks.Task M() => [|Goo()|];", "void", mode); - } [Theory, CombinatorialData] - public async Task TestExpressionBodiedAsyncVoidMethod(TestMode mode) - { - await TestInClassAsync( + public Task TestExpressionBodiedAsyncVoidMethod(TestMode mode) + => TestInClassAsync( @"async void M() => [|Goo()|];", "void", mode); - } [Theory, CombinatorialData] - public async Task TestExpressionBodiedOperator(TestMode mode) - { - await TestInClassAsync( + public Task TestExpressionBodiedOperator(TestMode mode) + => TestInClassAsync( @"public static C operator ++(C c) => [|Goo()|];", "global::C", mode); - } [Theory, CombinatorialData] - public async Task TestExpressionBodiedConversionOperator(TestMode mode) - { - await TestInClassAsync( + public Task TestExpressionBodiedConversionOperator(TestMode mode) + => TestInClassAsync( @"public static implicit operator int(C c) => [|Goo()|];", "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestExpressionBodiedProperty(TestMode mode) - { - await TestInClassAsync( + public Task TestExpressionBodiedProperty(TestMode mode) + => TestInClassAsync( @"int P => [|Goo()|];", "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestExpressionBodiedIndexer(TestMode mode) - { - await TestInClassAsync( + public Task TestExpressionBodiedIndexer(TestMode mode) + => TestInClassAsync( @"int this[int i] => [|Goo()|];", "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestExpressionBodiedPropertyGetter(TestMode mode) - { - await TestInClassAsync( + public Task TestExpressionBodiedPropertyGetter(TestMode mode) + => TestInClassAsync( @"int P { get => [|Goo()|]; }", "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestExpressionBodiedPropertySetter(TestMode mode) - { - await TestInClassAsync( + public Task TestExpressionBodiedPropertySetter(TestMode mode) + => TestInClassAsync( @"int P { set => [|Goo()|]; }", "void", mode); - } [Theory, CombinatorialData] - public async Task TestExpressionBodiedIndexerGetter(TestMode mode) - { - await TestInClassAsync( + public Task TestExpressionBodiedIndexerGetter(TestMode mode) + => TestInClassAsync( @"int this[int i] { get => [|Goo()|]; }", "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestExpressionBodiedIndexerSetter(TestMode mode) - { - await TestInClassAsync( + public Task TestExpressionBodiedIndexerSetter(TestMode mode) + => TestInClassAsync( @"int this[int i] { set => [|Goo()|]; }", "void", mode); - } [Theory, CombinatorialData] - public async Task TestExpressionBodiedEventAdder(TestMode mode) - { - await TestInClassAsync( + public Task TestExpressionBodiedEventAdder(TestMode mode) + => TestInClassAsync( @"event System.EventHandler E { add => [|Goo()|]; remove { } }", "void", mode); - } [Theory, CombinatorialData] - public async Task TestExpressionBodiedEventRemover(TestMode mode) - { - await TestInClassAsync( + public Task TestExpressionBodiedEventRemover(TestMode mode) + => TestInClassAsync( @"event System.EventHandler E { add { } remove => [|Goo()|]; }", "void", mode); - } [Theory, CombinatorialData] - public async Task TestExpressionBodiedLocalFunction(TestMode mode) - { - await TestInClassAsync( + public Task TestExpressionBodiedLocalFunction(TestMode mode) + => TestInClassAsync( """ void M() { int F() => [|Goo()|]; } """, "global::System.Int32", mode); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/27647"), CombinatorialData] - public async Task TestExpressionBodiedAsyncTaskOfTLocalFunction(TestMode mode) - { - await TestInClassAsync( + public Task TestExpressionBodiedAsyncTaskOfTLocalFunction(TestMode mode) + => TestInClassAsync( """ void M() { async System.Threading.Tasks.Task F() => [|Goo()|]; } """, "global::System.Int32", mode); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/27647"), CombinatorialData] - public async Task TestExpressionBodiedAsyncTaskLocalFunction(TestMode mode) - { - await TestInClassAsync( + public Task TestExpressionBodiedAsyncTaskLocalFunction(TestMode mode) + => TestInClassAsync( """ void M() { async System.Threading.Tasks.Task F() => [|Goo()|]; } """, "void", mode); - } [Theory, CombinatorialData] - public async Task TestExpressionBodiedAsyncVoidLocalFunction(TestMode mode) - { - await TestInClassAsync( + public Task TestExpressionBodiedAsyncVoidLocalFunction(TestMode mode) + => TestInClassAsync( """ void M() { async void F() => [|Goo()|]; } """, "void", mode); - } [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827897")] - public async Task TestYieldReturnInMethod([CombinatorialValues("IEnumerable", "IEnumerator", "InvalidGenericType")] string returnTypeName, TestMode mode) - { - var markup = -$@"using System.Collections.Generic; + public Task TestYieldReturnInMethod([CombinatorialValues("IEnumerable", "IEnumerator", "InvalidGenericType")] string returnTypeName, TestMode mode) + => TestAsync($$""" + using System.Collections.Generic; -class C -{{ - {returnTypeName} M() - {{ - yield return [|abc|] - }} -}}"; - await TestAsync(markup, "global::System.Int32", mode); - } + class C + { + {{returnTypeName}} M() + { + yield return [|abc|] + } + } + """, "global::System.Int32", mode); [Theory, CombinatorialData] - public async Task TestYieldReturnInMethodNullableReference([CombinatorialValues("IEnumerable", "IEnumerator", "InvalidGenericType")] string returnTypeName, TestMode mode) - { - var markup = -$@"#nullable enable -using System.Collections.Generic; + public Task TestYieldReturnInMethodNullableReference([CombinatorialValues("IEnumerable", "IEnumerator", "InvalidGenericType")] string returnTypeName, TestMode mode) + => TestAsync($$""" + #nullable enable + using System.Collections.Generic; -class C -{{ - {returnTypeName} M() - {{ - yield return [|abc|] - }} -}}"; - await TestAsync(markup, "global::System.String?", mode); - } + class C + { + {{returnTypeName}} M() + { + yield return [|abc|] + } + } + """, "global::System.String?", mode); [Theory, CombinatorialData] - public async Task TestYieldReturnInAsyncMethod([CombinatorialValues("IAsyncEnumerable", "IAsyncEnumerator", "InvalidGenericType")] string returnTypeName, TestMode mode) - { - var markup = -$@"namespace System.Collections.Generic -{{ - interface {returnTypeName} {{ }} - class C - {{ - async {returnTypeName} M() - {{ - yield return [|abc|] - }} - }} -}}"; - await TestAsync(markup, "global::System.Int32", mode); - } + public Task TestYieldReturnInAsyncMethod([CombinatorialValues("IAsyncEnumerable", "IAsyncEnumerator", "InvalidGenericType")] string returnTypeName, TestMode mode) + => TestAsync($$""" + namespace System.Collections.Generic + { + interface {{returnTypeName}} { } + class C + { + async {{returnTypeName}} M() + { + yield return [|abc|] + } + } + } + """, "global::System.Int32", mode); [Theory, CombinatorialData] - public async Task TestYieldReturnInvalidTypeInMethod([CombinatorialValues("int[]", "InvalidNonGenericType", "InvalidGenericType")] string returnType, TestMode mode) - { - var markup = -$@"class C -{{ - {returnType} M() - {{ - yield return [|abc|] - }} -}}"; - await TestAsync(markup, "global::System.Object", mode); - } + public Task TestYieldReturnInvalidTypeInMethod([CombinatorialValues("int[]", "InvalidNonGenericType", "InvalidGenericType")] string returnType, TestMode mode) + => TestAsync($$""" + class C + { + {{returnType}} M() + { + yield return [|abc|] + } + } + """, "global::System.Object", mode); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/30235")] - public async Task TestYieldReturnInLocalFunction(TestMode mode) - { - var markup = - """ + public Task TestYieldReturnInLocalFunction(TestMode mode) + => TestAsync(""" using System.Collections.Generic; class C @@ -1368,15 +1136,11 @@ IEnumerable F() } } } - """; - await TestAsync(markup, "global::System.Int32", mode); - } + """, "global::System.Int32", mode); [Theory, CombinatorialData] - public async Task TestYieldReturnInPropertyGetter(TestMode mode) - { - var markup = - """ + public Task TestYieldReturnInPropertyGetter(TestMode mode) + => TestAsync(""" using System.Collections.Generic; class C @@ -1389,15 +1153,11 @@ IEnumerable P } } } - """; - await TestAsync(markup, "global::System.Int32", mode); - } + """, "global::System.Int32", mode); [Theory, CombinatorialData] - public async Task TestYieldReturnInPropertySetter(TestMode mode) - { - var markup = - """ + public Task TestYieldReturnInPropertySetter(TestMode mode) + => TestAsync(""" using System.Collections.Generic; class C @@ -1410,45 +1170,36 @@ IEnumerable P } } } - """; - await TestAsync(markup, "global::System.Object", mode); - } + """, "global::System.Object", mode); [Theory, CombinatorialData] - public async Task TestYieldReturnAsGlobalStatement(TestMode mode) - { - await TestAsync( + public Task TestYieldReturnAsGlobalStatement(TestMode mode) + => TestAsync( @"yield return [|abc|]", "global::System.Object", mode, sourceCodeKind: SourceCodeKind.Script); - } [Theory, CombinatorialData] - public async Task TestReturnInSimpleLambda(TestMode mode) - { - await TestInMethodAsync( + public Task TestReturnInSimpleLambda(TestMode mode) + => TestInMethodAsync( """ System.Func f = s => { return [|Goo()|]; }; """, "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInParenthesizedLambda(TestMode mode) - { - await TestInMethodAsync( + public Task TestReturnInParenthesizedLambda(TestMode mode) + => TestInMethodAsync( """ System.Func f = () => { return [|Goo()|]; }; """, "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInLambdaWithNullableReturn(TestMode mode) - { - await TestInMethodAsync( + public Task TestReturnInLambdaWithNullableReturn(TestMode mode) + => TestInMethodAsync( """ #nullable enable System.Func f = s => @@ -1456,24 +1207,20 @@ await TestInMethodAsync( return [|Goo()|]; }; """, "global::System.String?", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInAnonymousMethod(TestMode mode) - { - await TestInMethodAsync( + public Task TestReturnInAnonymousMethod(TestMode mode) + => TestInMethodAsync( """ System.Func f = delegate () { return [|Goo()|]; }; """, "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInAnonymousMethodWithNullableReturn(TestMode mode) - { - await TestInMethodAsync( + public Task TestReturnInAnonymousMethodWithNullableReturn(TestMode mode) + => TestInMethodAsync( """ #nullable enable System.Func f = delegate () @@ -1481,48 +1228,40 @@ await TestInMethodAsync( return [|Goo()|]; }; """, "global::System.String?", mode); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/4486"), CombinatorialData] - public async Task TestReturnInAsyncTaskOfTSimpleLambda(TestMode mode) - { - await TestInMethodAsync( + public Task TestReturnInAsyncTaskOfTSimpleLambda(TestMode mode) + => TestInMethodAsync( """ System.Func> f = async s => { return [|Goo()|]; }; """, "global::System.Int32", mode); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/4486"), CombinatorialData] - public async Task TestReturnInAsyncTaskOfTParenthesizedLambda(TestMode mode) - { - await TestInMethodAsync( + public Task TestReturnInAsyncTaskOfTParenthesizedLambda(TestMode mode) + => TestInMethodAsync( """ System.Func> f = async () => { return [|Goo()|]; }; """, "global::System.Int32", mode); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/4486"), CombinatorialData] - public async Task TestReturnInAsyncTaskOfTAnonymousMethod(TestMode mode) - { - await TestInMethodAsync( + public Task TestReturnInAsyncTaskOfTAnonymousMethod(TestMode mode) + => TestInMethodAsync( """ System.Func> f = async delegate () { return [|Goo()|]; }; """, "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInAsyncTaskOfTAnonymousMethodWithNullableReference(TestMode mode) - { - await TestInMethodAsync( + public Task TestReturnInAsyncTaskOfTAnonymousMethodWithNullableReference(TestMode mode) + => TestInMethodAsync( """ #nullable enable System.Func> f = async delegate () @@ -1530,176 +1269,137 @@ await TestInMethodAsync( return [|Goo()|]; }; """, "global::System.String?", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInAsyncTaskSimpleLambda(TestMode mode) - { - await TestInMethodAsync( + public Task TestReturnInAsyncTaskSimpleLambda(TestMode mode) + => TestInMethodAsync( """ System.Func f = async s => { return [|Goo()|]; }; """, "void", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInAsyncTaskParenthesizedLambda(TestMode mode) - { - await TestInMethodAsync( + public Task TestReturnInAsyncTaskParenthesizedLambda(TestMode mode) + => TestInMethodAsync( """ System.Func f = async () => { return [|Goo()|]; }; """, "void", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInAsyncTaskAnonymousMethod(TestMode mode) - { - await TestInMethodAsync( + public Task TestReturnInAsyncTaskAnonymousMethod(TestMode mode) + => TestInMethodAsync( """ System.Func f = async delegate () { return [|Goo()|]; }; """, "void", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInAsyncVoidSimpleLambda(TestMode mode) - { - await TestInMethodAsync( + public Task TestReturnInAsyncVoidSimpleLambda(TestMode mode) + => TestInMethodAsync( """ System.Action f = async s => { return [|Goo()|]; }; """, "void", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInAsyncVoidParenthesizedLambda(TestMode mode) - { - await TestInMethodAsync( + public Task TestReturnInAsyncVoidParenthesizedLambda(TestMode mode) + => TestInMethodAsync( """ System.Action f = async () => { return [|Goo()|]; }; """, "void", mode); - } [Theory, CombinatorialData] - public async Task TestReturnInAsyncVoidAnonymousMethod(TestMode mode) - { - await TestInMethodAsync( + public Task TestReturnInAsyncVoidAnonymousMethod(TestMode mode) + => TestInMethodAsync( """ System.Action f = async delegate () { return [|Goo()|]; }; """, "void", mode); - } [Theory, CombinatorialData] - public async Task TestReturnAsGlobalStatement(TestMode mode) - { - await TestAsync( + public Task TestReturnAsGlobalStatement(TestMode mode) + => TestAsync( @"return [|Goo()|];", "global::System.Object", mode, sourceCodeKind: SourceCodeKind.Script); - } [Theory, CombinatorialData] - public async Task TestSimpleLambda(TestMode mode) - { - await TestInMethodAsync( + public Task TestSimpleLambda(TestMode mode) + => TestInMethodAsync( @"System.Func f = s => [|Goo()|];", "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestParenthesizedLambda(TestMode mode) - { - await TestInMethodAsync( + public Task TestParenthesizedLambda(TestMode mode) + => TestInMethodAsync( @"System.Func f = () => [|Goo()|];", "global::System.Int32", mode); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/30232")] - public async Task TestAsyncTaskOfTSimpleLambda(TestMode mode) - { - await TestInMethodAsync( + public Task TestAsyncTaskOfTSimpleLambda(TestMode mode) + => TestInMethodAsync( @"System.Func> f = async s => [|Goo()|];", "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestAsyncTaskOfTSimpleLambdaWithNullableReturn(TestMode mode) - { - await TestInMethodAsync( + public Task TestAsyncTaskOfTSimpleLambdaWithNullableReturn(TestMode mode) + => TestInMethodAsync( """ #nullable enable System.Func> f = async s => [|Goo()|]; """, "global::System.String?", mode); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/30232")] - public async Task TestAsyncTaskOfTParenthesizedLambda(TestMode mode) - { - await TestInMethodAsync( + public Task TestAsyncTaskOfTParenthesizedLambda(TestMode mode) + => TestInMethodAsync( @"System.Func> f = async () => [|Goo()|];", "global::System.Int32", mode); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/30232")] - public async Task TestAsyncTaskSimpleLambda(TestMode mode) - { - await TestInMethodAsync( + public Task TestAsyncTaskSimpleLambda(TestMode mode) + => TestInMethodAsync( @"System.Func f = async s => [|Goo()|];", "void", mode); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/30232"), CombinatorialData] - public async Task TestAsyncTaskParenthesizedLambda(TestMode mode) - { - await TestInMethodAsync( + public Task TestAsyncTaskParenthesizedLambda(TestMode mode) + => TestInMethodAsync( @"System.Func f = async () => [|Goo()|];", "void", mode); - } [Theory, CombinatorialData] - public async Task TestAsyncVoidSimpleLambda(TestMode mode) - { - await TestInMethodAsync( + public Task TestAsyncVoidSimpleLambda(TestMode mode) + => TestInMethodAsync( @"System.Action f = async s => [|Goo()|];", "void", mode); - } [Theory, CombinatorialData] - public async Task TestAsyncVoidParenthesizedLambda(TestMode mode) - { - await TestInMethodAsync( + public Task TestAsyncVoidParenthesizedLambda(TestMode mode) + => TestInMethodAsync( @"System.Action f = async () => [|Goo()|];", "void", mode); - } [Theory, CombinatorialData] - public async Task TestExpressionTreeSimpleLambda(TestMode mode) - { - await TestInMethodAsync( + public Task TestExpressionTreeSimpleLambda(TestMode mode) + => TestInMethodAsync( @"System.Linq.Expressions.Expression> f = s => [|Goo()|];", "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestExpressionTreeParenthesizedLambda(TestMode mode) - { - await TestInMethodAsync( + public Task TestExpressionTreeParenthesizedLambda(TestMode mode) + => TestInMethodAsync( @"System.Linq.Expressions.Expression> f = () => [|Goo()|];", "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestThrow(TestMode mode) - { - await TestInMethodAsync( + public Task TestThrow(TestMode mode) + => TestInMethodAsync( @"throw [|Goo()|];", "global::System.Exception", mode); - } [Theory, CombinatorialData] public async Task TestCatch(TestMode mode) @@ -1718,15 +1418,13 @@ public async Task TestDo(TestMode mode) => await TestInMethodAsync(@"do { } while ([|Goo()|])", "global::System.Boolean", mode); [Theory, CombinatorialData] - public async Task TestFor1(TestMode mode) - { - await TestInMethodAsync( + public Task TestFor1(TestMode mode) + => TestInMethodAsync( """ for (int i = 0; [|Goo()|]; i++) { } """, "global::System.Boolean", mode); - } [Theory, CombinatorialData] public async Task TestFor2(TestMode mode) @@ -1737,14 +1435,12 @@ public async Task TestFor3(TestMode mode) => await TestInMethodAsync(@"for (var i = [|Goo()|]; ; ) { }", "global::System.Int32", mode); [Theory, CombinatorialData] - public async Task TestForNullableReference(TestMode mode) - { - await TestInMethodAsync( + public Task TestForNullableReference(TestMode mode) + => TestInMethodAsync( """ #nullable enable for (string? s = [|Goo()|]; ; ) { } """, "global::System.String?", mode); - } [Theory, CombinatorialData] public async Task TestUsing1(TestMode mode) @@ -1763,56 +1459,42 @@ public async Task TestForEach(TestMode mode) => await TestInMethodAsync(@"foreach (int v in [|Goo()|]) { }", "global::System.Collections.Generic.IEnumerable", mode); [Theory(Skip = "https://github.com/dotnet/roslyn/issues/37309"), CombinatorialData] - public async Task TestForEachNullableElements(TestMode mode) - { - await TestInMethodAsync( + public Task TestForEachNullableElements(TestMode mode) + => TestInMethodAsync( """ #nullable enable foreach (string? v in [|Goo()|]) { } """, "global::System.Collections.Generic.IEnumerable", mode); - } [Theory, CombinatorialData] - public async Task TestPrefixExpression1(TestMode mode) - { - await TestInMethodAsync( + public Task TestPrefixExpression1(TestMode mode) + => TestInMethodAsync( @"var q = +[|Goo()|];", "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestPrefixExpression2(TestMode mode) - { - await TestInMethodAsync( + public Task TestPrefixExpression2(TestMode mode) + => TestInMethodAsync( @"var q = -[|Goo()|];", "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestPrefixExpression3(TestMode mode) - { - await TestInMethodAsync( + public Task TestPrefixExpression3(TestMode mode) + => TestInMethodAsync( @"var q = ~[|Goo()|];", "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestPrefixExpression4(TestMode mode) - { - await TestInMethodAsync( + public Task TestPrefixExpression4(TestMode mode) + => TestInMethodAsync( @"var q = ![|Goo()|];", "global::System.Boolean", mode); - } [Theory, CombinatorialData] - public async Task TestPrefixExpression5(TestMode mode) - { - await TestInMethodAsync( + public Task TestPrefixExpression5(TestMode mode) + => TestInMethodAsync( @"var q = System.DayOfWeek.Monday & ~[|Goo()|];", "global::System.DayOfWeek", mode); - } [Theory, CombinatorialData] - public async Task TestArrayRankSpecifier(TestMode mode) - { - await TestInMethodAsync( + public Task TestArrayRankSpecifier(TestMode mode) + => TestInMethodAsync( @"var q = new string[[|Goo()|]];", "global::System.Int32", mode); - } [Theory, CombinatorialData] public async Task TestSwitch1(TestMode mode) @@ -1827,16 +1509,13 @@ public async Task TestSwitch3(TestMode mode) => await TestInMethodAsync(@"switch ([|Goo()|]) { case ""a"": }", "global::System.String", mode); [Theory, CombinatorialData] - public async Task TestMethodCall1(TestMode mode) - { - await TestInMethodAsync( + public Task TestMethodCall1(TestMode mode) + => TestInMethodAsync( @"Bar([|Goo()|]);", "global::System.Object", mode); - } [Theory, CombinatorialData] - public async Task TestMethodCall2(TestMode mode) - { - await TestInClassAsync( + public Task TestMethodCall2(TestMode mode) + => TestInClassAsync( """ void M() { @@ -1845,12 +1524,10 @@ void M() void Bar(int i); """, "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestMethodCall3(TestMode mode) - { - await TestInClassAsync( + public Task TestMethodCall3(TestMode mode) + => TestInClassAsync( """ void M() { @@ -1859,12 +1536,10 @@ void M() void Bar(); """, "global::System.Object", mode); - } [Theory, CombinatorialData] - public async Task TestMethodCall4(TestMode mode) - { - await TestInClassAsync( + public Task TestMethodCall4(TestMode mode) + => TestInClassAsync( """ void M() { @@ -1873,12 +1548,10 @@ void M() void Bar(int i, string s); """, "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestMethodCall5(TestMode mode) - { - await TestInClassAsync( + public Task TestMethodCall5(TestMode mode) + => TestInClassAsync( """ void M() { @@ -1887,12 +1560,10 @@ void M() void Bar(int i, string s); """, "global::System.String", mode); - } [Theory, CombinatorialData] - public async Task TestMethodCallNullableReference(TestMode mode) - { - await TestInClassAsync( + public Task TestMethodCallNullableReference(TestMode mode) + => TestInClassAsync( """ void M() { @@ -1901,19 +1572,15 @@ void M() void Bar(string? s); """, "global::System.String?", mode); - } [Theory, CombinatorialData] - public async Task TestConstructorCall1(TestMode mode) - { - await TestInMethodAsync( + public Task TestConstructorCall1(TestMode mode) + => TestInMethodAsync( @"new C([|Goo()|]);", "global::System.Object", mode); - } [Theory, CombinatorialData] - public async Task TestConstructorCall2(TestMode mode) - { - await TestInClassAsync( + public Task TestConstructorCall2(TestMode mode) + => TestInClassAsync( """ void M() { @@ -1924,12 +1591,10 @@ void M() { } """, "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestConstructorCall3(TestMode mode) - { - await TestInClassAsync( + public Task TestConstructorCall3(TestMode mode) + => TestInClassAsync( """ void M() { @@ -1940,12 +1605,10 @@ void M() { } """, "global::System.Object", mode); - } [Theory, CombinatorialData] - public async Task TestConstructorCall4(TestMode mode) - { - await TestInClassAsync( + public Task TestConstructorCall4(TestMode mode) + => TestInClassAsync( """ void M() { @@ -1956,12 +1619,10 @@ void M() { } """, "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestConstructorCall5(TestMode mode) - { - await TestInClassAsync( + public Task TestConstructorCall5(TestMode mode) + => TestInClassAsync( """ void M() { @@ -1972,12 +1633,10 @@ void M() { } """, "global::System.String", mode); - } [Theory, CombinatorialData] - public async Task TestConstructorCallNullableParameter(TestMode mode) - { - await TestInClassAsync( + public Task TestConstructorCallNullableParameter(TestMode mode) + => TestInClassAsync( """ #nullable enable @@ -1990,12 +1649,10 @@ void M() { } """, "global::System.String?", mode); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112"), CombinatorialData] - public async Task TestThisConstructorInitializer1(TestMode mode) - { - await TestAsync( + public Task TestThisConstructorInitializer1(TestMode mode) + => TestAsync( """ class MyClass { @@ -2004,12 +1661,10 @@ public MyClass(int x) : this([|test|]) } } """, "global::System.Int32", mode); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112"), CombinatorialData] - public async Task TestThisConstructorInitializer2(TestMode mode) - { - await TestAsync( + public Task TestThisConstructorInitializer2(TestMode mode) + => TestAsync( """ class MyClass { @@ -2018,12 +1673,10 @@ public MyClass(int x, string y) : this(5, [|test|]) } } """, "global::System.String", mode); - } [Theory, CombinatorialData] - public async Task TestThisConstructorInitializerNullableParameter(TestMode mode) - { - await TestAsync( + public Task TestThisConstructorInitializerNullableParameter(TestMode mode) + => TestAsync( """ #nullable enable @@ -2034,12 +1687,10 @@ public MyClass(string? y) : this([|test|]) } } """, "global::System.String?", mode); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112"), CombinatorialData] - public async Task TestBaseConstructorInitializer(TestMode mode) - { - await TestAsync( + public Task TestBaseConstructorInitializer(TestMode mode) + => TestAsync( """ class B { @@ -2055,12 +1706,10 @@ public D() : base([|test|]) } } """, "global::System.Int32", mode); - } [Theory, CombinatorialData] - public async Task TestBaseConstructorInitializerNullableParameter(TestMode mode) - { - await TestAsync( + public Task TestBaseConstructorInitializerNullableParameter(TestMode mode) + => TestAsync( """ #nullable enable @@ -2078,27 +1727,23 @@ public D() : base([|test|]) } } """, "global::System.String?", mode); - } [Theory, CombinatorialData] - public async Task TestIndexAccess1(TestMode mode) - { - await TestInMethodAsync( + public Task TestIndexAccess1(TestMode mode) + => TestInMethodAsync( """ string[] i; i[[|Goo()|]]; """, "global::System.Int32", mode); - } [Theory, CombinatorialData] public async Task TestIndexerCall1(TestMode mode) => await TestInMethodAsync(@"this[[|Goo()|]];", "global::System.Int32", mode); [Theory, CombinatorialData] - public async Task TestIndexerCall2(TestMode mode) - { - await TestInClassAsync( + public Task TestIndexerCall2(TestMode mode) + => TestInClassAsync( """ void M() { @@ -2107,12 +1752,10 @@ void M() int this[long i] { get; } """, "global::System.Int64", mode); - } [Theory, CombinatorialData] - public async Task TestIndexerCall3(TestMode mode) - { - await TestInClassAsync( + public Task TestIndexerCall3(TestMode mode) + => TestInClassAsync( """ void M() { @@ -2121,12 +1764,10 @@ void M() int this[int i, string s] { get; } """, "global::System.String", mode); - } [Theory, CombinatorialData] - public async Task TestIndexerCall5(TestMode mode) - { - await TestInClassAsync( + public Task TestIndexerCall5(TestMode mode) + => TestInClassAsync( """ void M() { @@ -2135,13 +1776,10 @@ void M() int this[int i, string s] { get; } """, "global::System.String", mode); - } [Theory, CombinatorialData] - public async Task TestArrayInitializerInImplicitArrayCreationSimple(TestMode mode) - { - var text = - """ + public Task TestArrayInitializerInImplicitArrayCreationSimple(TestMode mode) + => TestAsync(""" using System.Collections.Generic; class C @@ -2151,16 +1789,11 @@ void M() var a = new[] { 1, [|2|] }; } } - """; - - await TestAsync(text, "global::System.Int32", mode); - } + """, "global::System.Int32", mode); [Theory, CombinatorialData] - public async Task TestArrayInitializerInImplicitArrayCreation1(TestMode mode) - { - var text = - """ + public Task TestArrayInitializerInImplicitArrayCreation1(TestMode mode) + => TestAsync(""" using System.Collections.Generic; class C @@ -2173,16 +1806,11 @@ void M() int Bar() { return 1; } int Goo() { return 2; } } - """; - - await TestAsync(text, "global::System.Int32", mode); - } + """, "global::System.Int32", mode); [Theory, CombinatorialData] - public async Task TestArrayInitializerInImplicitArrayCreation2(TestMode mode) - { - var text = - """ + public Task TestArrayInitializerInImplicitArrayCreation2(TestMode mode) + => TestAsync(""" using System.Collections.Generic; class C @@ -2194,16 +1822,11 @@ void M() int Bar() { return 1; } } - """; - - await TestAsync(text, "global::System.Int32", mode); - } + """, "global::System.Int32", mode); [Theory, CombinatorialData] - public async Task TestArrayInitializerInImplicitArrayCreation3(TestMode mode) - { - var text = - """ + public Task TestArrayInitializerInImplicitArrayCreation3(TestMode mode) + => TestAsync(""" using System.Collections.Generic; class C @@ -2213,16 +1836,11 @@ void M() var a = new[] { Bar(), [|Goo()|] }; } } - """; - - await TestAsync(text, "global::System.Object", mode); - } + """, "global::System.Object", mode); [Theory, CombinatorialData] - public async Task TestArrayInitializerInImplicitArrayCreationInferredAsNullable(TestMode mode) - { - var text = - """ + public Task TestArrayInitializerInImplicitArrayCreationInferredAsNullable(TestMode mode) + => TestAsync(""" #nullable enable using System.Collections.Generic; @@ -2236,16 +1854,11 @@ void M() object? Bar() { return null; } } - """; - - await TestAsync(text, "global::System.Object?", mode); - } + """, "global::System.Object?", mode); [Theory, CombinatorialData] - public async Task TestArrayInitializerInEqualsValueClauseSimple(TestMode mode) - { - var text = - """ + public Task TestArrayInitializerInEqualsValueClauseSimple(TestMode mode) + => TestAsync(""" using System.Collections.Generic; class C @@ -2255,16 +1868,11 @@ void M() int[] a = { 1, [|2|] }; } } - """; - - await TestAsync(text, "global::System.Int32", mode); - } + """, "global::System.Int32", mode); [Theory, CombinatorialData] - public async Task TestArrayInitializerInEqualsValueClause(TestMode mode) - { - var text = - """ + public Task TestArrayInitializerInEqualsValueClause(TestMode mode) + => TestAsync(""" using System.Collections.Generic; class C @@ -2276,16 +1884,11 @@ void M() int Bar() { return 1; } } - """; - - await TestAsync(text, "global::System.Int32", mode); - } + """, "global::System.Int32", mode); [Theory, CombinatorialData] - public async Task TestArrayInitializerInEqualsValueClauseNullableElement(TestMode mode) - { - var text = - """ + public Task TestArrayInitializerInEqualsValueClauseNullableElement(TestMode mode) + => TestAsync(""" #nullable enable using System.Collections.Generic; @@ -2297,17 +1900,12 @@ void M() string?[] a = { [|Goo()|] }; } } - """; - - await TestAsync(text, "global::System.String?", mode); - } + """, "global::System.String?", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] - public async Task TestCollectionInitializer1(TestMode mode) - { - var text = - """ + public Task TestCollectionInitializer1(TestMode mode) + => TestAsync(""" using System.Collections.Generic; class C @@ -2317,16 +1915,11 @@ void M() new List() { [|Goo()|] }; } } - """; - - await TestAsync(text, "global::System.Int32", mode); - } + """, "global::System.Int32", mode); [Theory, CombinatorialData] - public async Task TestCollectionInitializerNullableElement(TestMode mode) - { - var text = - """ + public Task TestCollectionInitializerNullableElement(TestMode mode) + => TestAsync(""" #nullable enable using System.Collections.Generic; @@ -2338,17 +1931,12 @@ void M() new List() { [|Goo()|] }; } } - """; - - await TestAsync(text, "global::System.String?", mode); - } + """, "global::System.String?", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] - public async Task TestCollectionInitializer2(TestMode mode) - { - var text = - """ + public Task TestCollectionInitializer2(TestMode mode) + => TestAsync(""" using System.Collections.Generic; class C @@ -2358,17 +1946,12 @@ void M() new Dictionary() { { [|Goo()|], "" } }; } } - """; - - await TestAsync(text, "global::System.Int32", mode); - } + """, "global::System.Int32", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] - public async Task TestCollectionInitializer3(TestMode mode) - { - var text = - """ + public Task TestCollectionInitializer3(TestMode mode) + => TestAsync(""" using System.Collections.Generic; class C @@ -2378,16 +1961,11 @@ void M() new Dictionary() { { 0, [|Goo()|] } }; } } - """; - - await TestAsync(text, "global::System.String", mode); - } + """, "global::System.String", mode); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] - public async Task TestCustomCollectionInitializerAddMethod1() - { - var text = - """ + public Task TestCustomCollectionInitializerAddMethod1() + => TestAsync(""" class C : System.Collections.IEnumerable { void M() @@ -2403,17 +1981,12 @@ public System.Collections.IEnumerator GetEnumerator() throw new System.NotImplementedException(); } } - """; - - await TestAsync(text, "global::System.Int32", TestMode.Node); - } + """, "global::System.Int32", TestMode.Node); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] - public async Task TestCustomCollectionInitializerAddMethod2(TestMode mode) - { - var text = - """ + public Task TestCustomCollectionInitializerAddMethod2(TestMode mode) + => TestAsync(""" class C : System.Collections.IEnumerable { void M() @@ -2429,17 +2002,12 @@ public System.Collections.IEnumerator GetEnumerator() throw new System.NotImplementedException(); } } - """; - - await TestAsync(text, "global::System.Boolean", mode); - } + """, "global::System.Boolean", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] - public async Task TestCustomCollectionInitializerAddMethod3(TestMode mode) - { - var text = - """ + public Task TestCustomCollectionInitializerAddMethod3(TestMode mode) + => TestAsync(""" class C : System.Collections.IEnumerable { void M() @@ -2455,16 +2023,11 @@ public System.Collections.IEnumerator GetEnumerator() throw new System.NotImplementedException(); } } - """; - - await TestAsync(text, "global::System.String", mode); - } + """, "global::System.String", mode); [Theory, CombinatorialData] - public async Task TestCustomCollectionInitializerAddMethodWithNullableParameter(TestMode mode) - { - var text = - """ + public Task TestCustomCollectionInitializerAddMethodWithNullableParameter(TestMode mode) + => TestAsync(""" class C : System.Collections.IEnumerable { void M() @@ -2480,16 +2043,11 @@ public System.Collections.IEnumerator GetEnumerator() throw new System.NotImplementedException(); } } - """; - - await TestAsync(text, "global::System.String?", mode); - } + """, "global::System.String?", mode); [Fact] - public async Task TestArrayInference1() - { - var text = - """ + public Task TestArrayInference1() + => TestAsync(""" class A { void Goo() @@ -2497,16 +2055,11 @@ void Goo() A[] x = new [|C|][] { }; } } - """; - - await TestAsync(text, "global::A", TestMode.Node); - } + """, "global::A", TestMode.Node); [Fact] - public async Task TestArrayInference1_Position() - { - var text = - """ + public Task TestArrayInference1_Position() + => TestAsync(""" class A { void Goo() @@ -2514,16 +2067,11 @@ void Goo() A[] x = new [|C|][] { }; } } - """; - - await TestAsync(text, "global::A[]", TestMode.Position); - } + """, "global::A[]", TestMode.Position); [Fact] - public async Task TestArrayInference2() - { - var text = - """ + public Task TestArrayInference2() + => TestAsync(""" class A { void Goo() @@ -2531,16 +2079,11 @@ void Goo() A[][] x = new [|C|][][] { }; } } - """; - - await TestAsync(text, "global::A", TestMode.Node); - } + """, "global::A", TestMode.Node); [Fact] - public async Task TestArrayInference2_Position() - { - var text = - """ + public Task TestArrayInference2_Position() + => TestAsync(""" class A { void Goo() @@ -2548,16 +2091,11 @@ void Goo() A[][] x = new [|C|][][] { }; } } - """; - - await TestAsync(text, "global::A[][]", TestMode.Position); - } + """, "global::A[][]", TestMode.Position); [Fact] - public async Task TestArrayInference3() - { - var text = - """ + public Task TestArrayInference3() + => TestAsync(""" class A { void Goo() @@ -2565,16 +2103,11 @@ void Goo() A[][] x = new [|C|][] { }; } } - """; - - await TestAsync(text, "global::A[]", TestMode.Node); - } + """, "global::A[]", TestMode.Node); [Fact] - public async Task TestArrayInference3_Position() - { - var text = - """ + public Task TestArrayInference3_Position() + => TestAsync(""" class A { void Goo() @@ -2582,16 +2115,11 @@ void Goo() A[][] x = new [|C|][] { }; } } - """; - - await TestAsync(text, "global::A[][]", TestMode.Position); - } + """, "global::A[][]", TestMode.Position); [Theory, CombinatorialData] - public async Task TestArrayInference4(TestMode mode) - { - var text = - """ + public Task TestArrayInference4(TestMode mode) + => TestAsync(""" using System; class A { @@ -2600,17 +2128,12 @@ void Goo() Func[] x = new Func[] { [|Bar()|] }; } } - """; - - await TestAsync(text, "global::System.Func", mode); - } + """, "global::System.Func", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538993")] - public async Task TestInsideLambda2(TestMode mode) - { - var text = - """ + public Task TestInsideLambda2(TestMode mode) + => TestAsync(""" using System; class C { @@ -2619,16 +2142,11 @@ void M() Func f = i => [|here|] } } - """; - - await TestAsync(text, "global::System.Int32", mode); - } + """, "global::System.Int32", mode); [Theory, CombinatorialData] - public async Task TestInsideLambdaNullableReturn(TestMode mode) - { - var text = - """ + public Task TestInsideLambdaNullableReturn(TestMode mode) + => TestAsync(""" #nullable enable using System; @@ -2639,17 +2157,12 @@ void M() Func f = i => [|here|] } } - """; - - await TestAsync(text, "global::System.String?", mode); - } + """, "global::System.String?", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539813")] - public async Task TestPointer1(TestMode mode) - { - var text = - """ + public Task TestPointer1(TestMode mode) + => TestAsync(""" class C { void M(int* i) @@ -2657,17 +2170,12 @@ void M(int* i) var q = i[[|Goo()|]]; } } - """; - - await TestAsync(text, "global::System.Int32", mode); - } + """, "global::System.Int32", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539813")] - public async Task TestDynamic1(TestMode mode) - { - var text = - """ + public Task TestDynamic1(TestMode mode) + => TestAsync(""" class C { void M(dynamic i) @@ -2675,16 +2183,11 @@ void M(dynamic i) var q = i[[|Goo()|]]; } } - """; - - await TestAsync(text, "global::System.Int32", mode); - } + """, "global::System.Int32", mode); [Theory, CombinatorialData] - public async Task TestChecked1(TestMode mode) - { - var text = - """ + public Task TestChecked1(TestMode mode) + => TestAsync(""" class C { void M() @@ -2692,17 +2195,12 @@ void M() string q = checked([|Goo()|]); } } - """; - - await TestAsync(text, "global::System.String", mode); - } + """, "global::System.String", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553584")] - public async Task TestAwaitTaskOfT(TestMode mode) - { - var text = - """ + public Task TestAwaitTaskOfT(TestMode mode) + => TestAsync(""" using System.Threading.Tasks; class C { @@ -2711,16 +2209,11 @@ void M() int x = await [|Goo()|]; } } - """; - - await TestAsync(text, "global::System.Threading.Tasks.Task", mode); - } + """, "global::System.Threading.Tasks.Task", mode); [Theory, CombinatorialData] - public async Task TestAwaitTaskOfTNullableValue(TestMode mode) - { - var text = - """ + public Task TestAwaitTaskOfTNullableValue(TestMode mode) + => TestAsync(""" #nullable enable using System.Threading.Tasks; @@ -2731,17 +2224,12 @@ void M() string? x = await [|Goo()|]; } } - """; - - await TestAsync(text, "global::System.Threading.Tasks.Task", mode); - } + """, "global::System.Threading.Tasks.Task", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553584")] - public async Task TestAwaitTaskOfTaskOfT(TestMode mode) - { - var text = - """ + public Task TestAwaitTaskOfTaskOfT(TestMode mode) + => TestAsync(""" using System.Threading.Tasks; class C { @@ -2750,17 +2238,12 @@ void M() Task x = await [|Goo()|]; } } - """; - - await TestAsync(text, "global::System.Threading.Tasks.Task>", mode); - } + """, "global::System.Threading.Tasks.Task>", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553584")] - public async Task TestAwaitTask(TestMode mode) - { - var text = - """ + public Task TestAwaitTask(TestMode mode) + => TestAsync(""" using System.Threading.Tasks; class C { @@ -2769,17 +2252,12 @@ void M() await [|Goo()|]; } } - """; - - await TestAsync(text, "global::System.Threading.Tasks.Task", mode); - } + """, "global::System.Threading.Tasks.Task", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617622")] - public async Task TestLockStatement(TestMode mode) - { - var text = - """ + public Task TestLockStatement(TestMode mode) + => TestAsync(""" class C { void M() @@ -2789,17 +2267,12 @@ void M() } } } - """; - - await TestAsync(text, "global::System.Object", mode); - } + """, "global::System.Object", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617622")] - public async Task TestAwaitExpressionInLockStatement(TestMode mode) - { - var text = - """ + public Task TestAwaitExpressionInLockStatement(TestMode mode) + => TestAsync(""" class C { async void M() @@ -2809,17 +2282,12 @@ async void M() } } } - """; - - await TestAsync(text, "global::System.Threading.Tasks.Task", mode); - } + """, "global::System.Threading.Tasks.Task", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827897")] - public async Task TestReturnFromAsyncTaskOfT(TestMode mode) - { - var markup = - """ + public Task TestReturnFromAsyncTaskOfT(TestMode mode) + => TestAsync(""" using System.Threading.Tasks; class Program { @@ -2829,16 +2297,12 @@ async Task M() return [|ab|] } } - """; - await TestAsync(markup, "global::System.Int32", mode); - } + """, "global::System.Int32", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853840")] - public async Task TestAttributeArguments1(TestMode mode) - { - var markup = - """ + public Task TestAttributeArguments1(TestMode mode) + => TestAsync(""" [A([|dd|], ee, Y = ff)] class AAttribute : System.Attribute { @@ -2850,16 +2314,12 @@ public AAttribute(System.DayOfWeek a, double b) } } - """; - await TestAsync(markup, "global::System.DayOfWeek", mode); - } + """, "global::System.DayOfWeek", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853840")] - public async Task TestAttributeArguments2(TestMode mode) - { - var markup = - """ + public Task TestAttributeArguments2(TestMode mode) + => TestAsync(""" [A(dd, [|ee|], Y = ff)] class AAttribute : System.Attribute { @@ -2871,16 +2331,12 @@ public AAttribute(System.DayOfWeek a, double b) } } - """; - await TestAsync(markup, "global::System.Double", mode); - } + """, "global::System.Double", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853840")] - public async Task TestAttributeArguments3(TestMode mode) - { - var markup = - """ + public Task TestAttributeArguments3(TestMode mode) + => TestAsync(""" [A(dd, ee, Y = [|ff|])] class AAttribute : System.Attribute { @@ -2892,16 +2348,12 @@ public AAttribute(System.DayOfWeek a, double b) } } - """; - await TestAsync(markup, "global::System.String", mode); - } + """, "global::System.String", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/757111")] - public async Task TestReturnStatementWithinDelegateWithinAMethodCall(TestMode mode) - { - var text = - """ + public Task TestReturnStatementWithinDelegateWithinAMethodCall(TestMode mode) + => TestAsync(""" using System; class Program @@ -2917,57 +2369,40 @@ private static void B(A a) { } } - """; - - await TestAsync(text, "global::System.String", mode); - } + """, "global::System.String", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994388")] - public async Task TestCatchFilterClause(TestMode mode) - { - var text = - """ + public Task TestCatchFilterClause(TestMode mode) + => TestInMethodAsync(""" try { } catch (Exception) if ([|M()|]) } - """; - await TestInMethodAsync(text, "global::System.Boolean", mode); - } + """, "global::System.Boolean", mode); [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994388")] - public async Task TestCatchFilterClause1(TestMode mode) - { - var text = - """ + public Task TestCatchFilterClause1(TestMode mode) + => TestInMethodAsync(""" try { } catch (Exception) if ([|M|]) } - """; - await TestInMethodAsync(text, "global::System.Boolean", mode); - } + """, "global::System.Boolean", mode); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994388")] - public async Task TestCatchFilterClause2() - { - var text = - """ + public Task TestCatchFilterClause2() + => TestInMethodAsync(""" try { } catch (Exception) if ([|M|].N) } - """; - await TestInMethodAsync(text, "global::System.Object", TestMode.Node); - } + """, "global::System.Object", TestMode.Node); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/643")] - public async Task TestAwaitExpressionWithChainingMethod() - { - var text = - """ + public Task TestAwaitExpressionWithChainingMethod() + => TestAsync(""" using System; using System.Threading.Tasks; @@ -2978,15 +2413,11 @@ static async void T() bool x = await [|M()|].ConfigureAwait(false); } } - """; - await TestAsync(text, "global::System.Threading.Tasks.Task", TestMode.Node); - } + """, "global::System.Threading.Tasks.Task", TestMode.Node); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/643")] - public async Task TestAwaitExpressionWithChainingMethod2() - { - var text = - """ + public Task TestAwaitExpressionWithChainingMethod2() + => TestAsync(""" using System; using System.Threading.Tasks; @@ -2997,15 +2428,11 @@ static async void T() bool x = await [|M|].ContinueWith(a => { return true; }).ContinueWith(a => { return false; }); } } - """; - await TestAsync(text, "global::System.Threading.Tasks.Task", TestMode.Node); - } + """, "global::System.Threading.Tasks.Task", TestMode.Node); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4233")] - public async Task TestAwaitExpressionWithGenericMethod1() - { - var text = - """ + public Task TestAwaitExpressionWithGenericMethod1() + => TestAsync(""" using System.Threading.Tasks; public class C @@ -3017,16 +2444,12 @@ private async void M() private async Task X(T t) { return t; } } - """; - await TestAsync(text, "global::System.Boolean", TestMode.Node); - } + """, "global::System.Boolean", TestMode.Node); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/4233")] - public async Task TestAwaitExpressionWithGenericMethod2(TestMode mode) - { - var text = - """ + public Task TestAwaitExpressionWithGenericMethod2(TestMode mode) + => TestAsync(""" using System.Threading.Tasks; public class C @@ -3038,16 +2461,12 @@ private async void M() private async Task X(T t) { return t; } } - """; - await TestAsync(text, "global::System.Boolean", mode); - } + """, "global::System.Boolean", mode); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/4483")] - public async Task TestNullCoalescingOperator1(TestMode mode) - { - var text = -""" + public Task TestNullCoalescingOperator1(TestMode mode) + => TestAsync(""" class C { void M() @@ -3055,18 +2474,12 @@ void M() object z = [|a|] ?? null; } } -"""; - // In position mode, we are inferring that the thing to the right is an object, because it's being assigned to a local of type object. - // In node mode, we are inferring the node is an object? because it's to the left of the ??. - await TestAsync(text, mode == TestMode.Node ? "global::System.Object?" : "global::System.Object", mode); - } +""", mode == TestMode.Node ? "global::System.Object?" : "global::System.Object", mode); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/4483")] - public async Task TestNullCoalescingOperator2(TestMode mode) - { - var text = -""" + public Task TestNullCoalescingOperator2(TestMode mode) + => TestAsync(""" class C { void M() @@ -3074,18 +2487,12 @@ void M() object z = [|a|] ?? b ?? c; } } -"""; - // In position mode, we are inferring that the thing to the right is an object, because it's being assigned to a local of type object. - // In node mode, we are inferring the node is an object? because it's to the left of the ??. - await TestAsync(text, mode == TestMode.Node ? "global::System.Object?" : "global::System.Object", mode); - } +""", mode == TestMode.Node ? "global::System.Object?" : "global::System.Object", mode); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/4483")] - public async Task TestNullCoalescingOperator3(TestMode mode) - { - var text = -""" + public Task TestNullCoalescingOperator3(TestMode mode) + => TestAsync(""" class C { void M() @@ -3093,18 +2500,11 @@ void M() object z = a ?? [|b|] ?? c; } } -"""; - // In position mode, we are inferring that the thing to the right is an object, because it's to the right of the first ?? - // and thus must be the same type as the object being assigned to. - // In node mode, we are inferring the node is an object? because it's to the left of the ??. - await TestAsync(text, mode == TestMode.Node ? "global::System.Object?" : "global::System.Object", mode); - } +""", mode == TestMode.Node ? "global::System.Object?" : "global::System.Object", mode); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/5126")] - public async Task TestSelectLambda() - { - var text = -""" + public Task TestSelectLambda() + => TestAsync(""" using System.Collections.Generic; using System.Linq; @@ -3115,15 +2515,11 @@ void M(IEnumerable args) args = args.Select(a =>[||]) } } -"""; - await TestAsync(text, "global::System.Object", TestMode.Node); - } +""", "global::System.Object", TestMode.Node); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/5126")] - public async Task TestSelectLambda2() - { - var text = -""" + public Task TestSelectLambda2() + => TestAsync(""" using System.Collections.Generic; using System.Linq; @@ -3134,16 +2530,12 @@ void M(IEnumerable args) args = args.Select(a =>[|b|]) } } -"""; - await TestAsync(text, "global::System.String", TestMode.Node); - } +""", "global::System.String", TestMode.Node); [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/1903")] - public async Task TestSelectLambda3(TestMode mode) - { - var text = - """ + public Task TestSelectLambda3(TestMode mode) + => TestAsync(""" using System.Collections.Generic; using System.Linq; @@ -3156,15 +2548,11 @@ IEnumerable GetB(IEnumerable a) return a.Select(i => [|Goo(i)|]); } } - """; - await TestAsync(text, "global::B", mode); - } + """, "global::B", mode); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/6765")] - public async Task TestDefaultStatement1() - { - var text = -""" + public Task TestDefaultStatement1() + => TestAsync(""" class C { static void Main(string[] args) @@ -3172,15 +2560,11 @@ static void Main(string[] args) System.ConsoleModifiers c = default([||]) } } -"""; - await TestAsync(text, "global::System.ConsoleModifiers", TestMode.Position); - } +""", "global::System.ConsoleModifiers", TestMode.Position); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/6765")] - public async Task TestDefaultStatement2() - { - var text = -""" + public Task TestDefaultStatement2() + => TestAsync(""" class C { static void Goo(System.ConsoleModifiers arg) @@ -3188,15 +2572,11 @@ static void Goo(System.ConsoleModifiers arg) Goo(default([||]) } } -"""; - await TestAsync(text, "global::System.ConsoleModifiers", TestMode.Position); - } +""", "global::System.ConsoleModifiers", TestMode.Position); [Fact] - public async Task TestWhereCall() - { - var text = -""" + public Task TestWhereCall() + => TestAsync(""" using System.Collections.Generic; class C { @@ -3205,15 +2585,11 @@ void Goo() [|ints|].Where(i => i > 10); } } -"""; - await TestAsync(text, "global::System.Collections.Generic.IEnumerable", TestMode.Node); - } +""", "global::System.Collections.Generic.IEnumerable", TestMode.Node); [Fact] - public async Task TestWhereCall2() - { - var text = -""" + public Task TestWhereCall2() + => TestAsync(""" using System.Collections.Generic; class C { @@ -3222,15 +2598,11 @@ void Goo() [|ints|].Where(i => null); } } -"""; - await TestAsync(text, "global::System.Collections.Generic.IEnumerable", TestMode.Node); - } +""", "global::System.Collections.Generic.IEnumerable", TestMode.Node); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/12755")] - public async Task TestObjectCreationBeforeArrayIndexing() - { - var text = - """ + public Task TestObjectCreationBeforeArrayIndexing() + => TestAsync(""" using System; class C { @@ -3241,39 +2613,28 @@ void M() array[4] = 4; } } - """; - - await TestAsync(text, "global::C", TestMode.Position); - } + """, "global::C", TestMode.Position); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25305")] [WorkItem("https://github.com/dotnet/roslyn/issues/15468")] - public async Task TestDeconstruction() - { - await TestInMethodAsync( + public Task TestDeconstruction() + => TestInMethodAsync( @"[|(int i, _)|] =", "(global::System.Int32 i, global::System.Object _)", TestMode.Node); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25305")] [WorkItem("https://github.com/dotnet/roslyn/issues/15468")] - public async Task TestDeconstruction2() - { - await TestInMethodAsync( + public Task TestDeconstruction2() + => TestInMethodAsync( @"(int i, _) = [||]", "(global::System.Int32 i, global::System.Object _)", TestMode.Position); - } [Fact] - public async Task TestDeconstructionWithNullableElement() - { - await TestInMethodAsync( + public Task TestDeconstructionWithNullableElement() + => TestInMethodAsync( @"[|(string? s, _)|] =", "(global::System.String? s, global::System.Object _)", TestMode.Node); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/13402")] - public async Task TestObjectCreationBeforeBlock() - { - var text = - """ + public Task TestObjectCreationBeforeBlock() + => TestAsync(""" class Program { static void Main(string[] args) @@ -3282,16 +2643,11 @@ static void Main(string[] args) { } } } - """; - - await TestAsync(text, "global::Program", TestMode.Position); - } + """, "global::Program", TestMode.Position); [Theory, CombinatorialData] - public async Task TestInferringThroughGenericFunctionWithNullableReturn(TestMode mode) - { - var text = - """ + public Task TestInferringThroughGenericFunctionWithNullableReturn(TestMode mode) + => TestAsync(""" #nullable enable class Program @@ -3303,16 +2659,11 @@ static void Main(string[] args) static T Identity(T value) { return value; } } - """; - - await TestAsync(text, "global::System.String?", mode); - } + """, "global::System.String?", mode); [Fact] - public async Task TestInferringThroughGenericFunctionMissingArgument() - { - var text = - """ + public Task TestInferringThroughGenericFunctionMissingArgument() + => TestAsync(""" class Program { static void Main(string[] args) @@ -3322,16 +2673,11 @@ static void Main(string[] args) static T Identity(T value) { return value; } } - """; - - await TestAsync(text, "global::System.String", TestMode.Position); - } + """, "global::System.String", TestMode.Position); [Theory, CombinatorialData] - public async Task TestInferringThroughGenericFunctionTooManyArguments(TestMode mode) - { - var text = - """ + public Task TestInferringThroughGenericFunctionTooManyArguments(TestMode mode) + => TestAsync(""" class Program { static void Main(string[] args) @@ -3341,37 +2687,26 @@ static void Main(string[] args) static T Identity(T value) { return value; } } - """; - - await TestAsync(text, "global::System.Object", mode); - } + """, "global::System.Object", mode); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/14277"), CombinatorialData] - public async Task TestValueInNestedTuple1(TestMode mode) - { - await TestInMethodAsync( + public Task TestValueInNestedTuple1(TestMode mode) + => TestInMethodAsync( @"(int, (string, bool)) x = ([|Goo()|], ("""", true));", "global::System.Int32", mode); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/14277"), CombinatorialData] - public async Task TestValueInNestedTuple2(TestMode mode) - { - await TestInMethodAsync( + public Task TestValueInNestedTuple2(TestMode mode) + => TestInMethodAsync( @"(int, (string, bool)) x = (1, ("""", [|Goo()|]));", "global::System.Boolean", mode); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14277")] - public async Task TestValueInNestedTuple3() - { - await TestInMethodAsync( + public Task TestValueInNestedTuple3() + => TestInMethodAsync( @"(int, string) x = (1, [||]);", "global::System.String", TestMode.Position); - } [Theory, CombinatorialData] - public async Task TestInferringInEnumHasFlags(TestMode mode) - { - var text = - """ + public Task TestInferringInEnumHasFlags(TestMode mode) + => TestAsync(""" using System.IO; class Program @@ -3382,10 +2717,7 @@ static void Main(string[] args) f.Attributes.HasFlag([|flag|]); } } - """; - - await TestAsync(text, "global::System.IO.FileAttributes", mode); - } + """, "global::System.IO.FileAttributes", mode); [Theory] [InlineData("")] @@ -3401,26 +2733,24 @@ static void Main(string[] args) [InlineData("not Re")] public async Task TestEnumInPatterns_Is_ConstUnaryAndBinaryPattern(string isPattern, bool shouldInferColor = true) { - var markup = @$" -class C -{{ - public enum Color - {{ - Red, - Green, - }} - - public void M(Color c) - {{ - var isRed = c is {isPattern}[||]; - }} -}} -"; - var expectedType = shouldInferColor ? "global::C.Color" : "global::System.Object"; - await TestAsync(markup, expectedType, TestMode.Position); + await TestAsync($$""" + class C + { + public enum Color + { + Red, + Green, + } + + public void M(Color c) + { + var isRed = c is {{isPattern}}[||]; + } + } + """, expectedType, TestMode.Position); } [Theory] @@ -3432,32 +2762,28 @@ public void M(Color c) [InlineData("Color.Green or Re")] [InlineData("not ")] [InlineData("not Re")] - public async Task TestEnumInPatterns_Is_PropertyPattern(string partialWritten) - { - var markup = @$" -public enum Color -{{ - Red, - Green, -}} + public Task TestEnumInPatterns_Is_PropertyPattern(string partialWritten) + => TestAsync($$""" + public enum Color + { + Red, + Green, + } -class C -{{ - public Color Color {{ get; }} - - public void M() - {{ - var isRed = this is {{ Color: {partialWritten}[||] - }} -}} -"; - await TestAsync(markup, "global::Color", TestMode.Position); - } + class C + { + public Color Color { get; } + + public void M() + { + var isRed = this is { Color: {{partialWritten}}[||] + } + } + """, "global::Color", TestMode.Position); [Fact] - public async Task TestEnumInPatterns_SwitchStatement_PropertyPattern() - { - var markup = """ + public Task TestEnumInPatterns_SwitchStatement_PropertyPattern() + => TestAsync(""" public enum Color { Red, @@ -3475,14 +2801,11 @@ public void M() case { Color: [||] } } - """; - await TestAsync(markup, "global::Color", TestMode.Position); - } + """, "global::Color", TestMode.Position); [Fact] - public async Task TestEnumInPatterns_SwitchExpression_PropertyPattern() - { - var markup = """ + public Task TestEnumInPatterns_SwitchExpression_PropertyPattern() + => TestAsync(""" public enum Color { Red, @@ -3500,14 +2823,11 @@ public void M() { Color: [||] } } - """; - await TestAsync(markup, "global::Color", TestMode.Position); - } + """, "global::Color", TestMode.Position); [Fact] - public async Task TestEnumInPatterns_SwitchStatement_ExtendedPropertyPattern() - { - var markup = """ + public Task TestEnumInPatterns_SwitchStatement_ExtendedPropertyPattern() + => TestAsync(""" public enum Color { Red, @@ -3526,14 +2846,11 @@ public void M() case { AnotherC.Color: [||] } } - """; - await TestAsync(markup, "global::Color", TestMode.Position); - } + """, "global::Color", TestMode.Position); [Fact] - public async Task TestEnumInPatterns_SwitchStatement_ExtendedPropertyPattern_Field() - { - var markup = """ + public Task TestEnumInPatterns_SwitchStatement_ExtendedPropertyPattern_Field() + => TestAsync(""" public enum Color { Red, @@ -3552,17 +2869,12 @@ public void M() case { AnotherC.Color: [||] } } - """; - await TestAsync(markup, "global::Color", TestMode.Position); - } + """, "global::Color", TestMode.Position); [Fact(Skip = "https://github.com/dotnet/roslyn/issues/70803")] - public async Task TestArgumentToBaseRecordPrimaryConstructor() - { - var markup = """ + public Task TestArgumentToBaseRecordPrimaryConstructor() + => TestAsync(""" class Base(int Alice, int Bob); class Derived(int Other) : Base([||] - """; - await TestAsync(markup, "global::System.Int32", TestMode.Position); - } + """, "global::System.Int32", TestMode.Position); } diff --git a/src/EditorFeatures/CSharpTest/Workspaces/WorkspaceTests_EditorFeatures.cs b/src/EditorFeatures/CSharpTest/Workspaces/WorkspaceTests_EditorFeatures.cs index 6c3434d5b8171..781bfc8506297 100644 --- a/src/EditorFeatures/CSharpTest/Workspaces/WorkspaceTests_EditorFeatures.cs +++ b/src/EditorFeatures/CSharpTest/Workspaces/WorkspaceTests_EditorFeatures.cs @@ -864,11 +864,13 @@ public async Task TestDocumentEvents() public async Task TestSourceGeneratedDocumentEvents() { var doc1Text = "public class C { }"; - var workspaceElement = $@" - - {new XText(doc1Text)} - -"; + var workspaceElement = $""" + + + {new XText(doc1Text)} + + + """; using var workspace = EditorTestWorkspace.Create(workspaceElement, composition: EditorTestCompositions.EditorFeatures); var document = workspace.Documents.Single(); @@ -1407,15 +1409,16 @@ public async Task TestLinkedFilesStayInSync() var originalText = "class Program1 { }"; var updatedText = "class Program2 { }"; - var input = $@" - - - {originalText} - - - - -"; + var input = $""" + + + {originalText} + + + + + + """; using var workspace = EditorTestWorkspace.Create(input, composition: EditorTestCompositions.EditorFeatures, openDocuments: true); var eventArgs = new List(); diff --git a/src/EditorFeatures/CSharpTest2/EmbeddedLanguages/Json/CSharpJsonParserTests.cs b/src/EditorFeatures/CSharpTest2/EmbeddedLanguages/Json/CSharpJsonParserTests.cs index 1d0f3c6a11f16..5f9dacbe19fb0 100644 --- a/src/EditorFeatures/CSharpTest2/EmbeddedLanguages/Json/CSharpJsonParserTests.cs +++ b/src/EditorFeatures/CSharpTest2/EmbeddedLanguages/Json/CSharpJsonParserTests.cs @@ -70,16 +70,32 @@ private void Test( if (runSubTreeChecks) TryParseSubTrees(stringText, options); - var actualTree = TreeToText(tree).Replace("\"", "\"\""); - AssertEx.Equal(expectedTree!.Replace("\"", "\"\""), actualTree); + var actualTree = TreeToText(tree).Replace(""" + " + """, """ + "" + """); + AssertEx.Equal(expectedTree!.Replace(""" + " + """, """ + "" + """), actualTree); ValidateDiagnostics(expectedDiagnostics, tree); } private protected static void ValidateDiagnostics(string expectedDiagnostics, JsonTree tree) { - var actualDiagnostics = DiagnosticsToText(tree.Diagnostics).Replace("\"", "\"\""); - AssertEx.Equal(RemoveMessagesInNonSupportedLanguage(expectedDiagnostics).Replace("\"", "\"\""), actualDiagnostics); + var actualDiagnostics = DiagnosticsToText(tree.Diagnostics).Replace(""" + " + """, """ + "" + """); + AssertEx.Equal(RemoveMessagesInNonSupportedLanguage(expectedDiagnostics).Replace(""" + " + """, """ + "" + """), actualDiagnostics); } private static string RemoveMessagesInNonSupportedLanguage(string value) @@ -101,19 +117,33 @@ private void TryParseSubTrees(string stringText, JsonOptions options) { // Trim the input from the right and make sure tree invariants hold var current = stringText; - while (current != "@\"\"" && current != "\"\"") + while (current != """ + @"" + """ && current != """ + "" + """) { - current = current[0..^2] + "\""; + current = current[0..^2] + """ + " + """; TryParseTree(current, options, conversionFailureOk: true); } // Trim the input from the left and make sure tree invariants hold current = stringText; - while (current != "@\"\"" && current != "\"\"") + while (current != """ + @"" + """ && current != """ + "" + """) { current = current[0] == '@' - ? "@\"" + current[3..] - : "\"" + current[2..]; + ? """ + @" + """ + current[3..] + : """ + " + """ + current[2..]; TryParseTree(current, options, conversionFailureOk: true); } diff --git a/src/EditorFeatures/CSharpTest2/EmbeddedLanguages/Json/CSharpJsonParserTests_NstTests.cs b/src/EditorFeatures/CSharpTest2/EmbeddedLanguages/Json/CSharpJsonParserTests_NstTests.cs index fd779e446070d..680c428f81801 100644 --- a/src/EditorFeatures/CSharpTest2/EmbeddedLanguages/Json/CSharpJsonParserTests_NstTests.cs +++ b/src/EditorFeatures/CSharpTest2/EmbeddedLanguages/Json/CSharpJsonParserTests_NstTests.cs @@ -17,8 +17,16 @@ private void TestNST( var (_, tree, allChars) = JustParseTree(stringText, JsonOptions.Strict, conversionFailureOk: false); Assert.NotNull(tree); Contract.ThrowIfNull(tree); - var actualTree = TreeToText(tree!).Replace("\"", "\"\""); - Assert.Equal(expected.Replace("\"", "\"\""), actualTree); + var actualTree = TreeToText(tree!).Replace(""" + " + """, """ + "" + """); + Assert.Equal(expected.Replace(""" + " + """, """ + "" + """), actualTree); ValidateDiagnostics(strictDiagnostics, tree); @@ -50,22 +58,26 @@ private void TestNST( [Fact] public void i_number_double_huge_neg_exp_json() { - TestNST(@"@""[123.456e-789]""", @" - - - - [ - - - 123.456e-789 - - - ] - - - - -", + TestNST(""" + @"[123.456e-789]" + """, """ + + + + + [ + + + 123.456e-789 + + + ] + + + + + + """, @"", @""); } @@ -73,147 +85,181 @@ public void i_number_double_huge_neg_exp_json() [Fact] public void i_number_huge_exp_json() { - TestNST(@"@""[0.4e00669999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999969999999006]""", @" - - - - [ - - - 0.4e00669999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999969999999006 - - - ] - - - - -", - @" - -", + TestNST(""" + @"[0.4e00669999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999969999999006]" + """, """ + + + + + [ + + + 0.4e00669999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999969999999006 + + + ] + + + + + + """, + """ + + + + """, @""); } [Fact] public void i_number_neg_int_huge_exp_json() { - TestNST(@"@""[-1e+9999]""", @" - - - - [ - - - -1e+9999 - - - ] - - - - -", - @" - -", + TestNST(""" + @"[-1e+9999]" + """, """ + + + + + [ + + + -1e+9999 + + + ] + + + + + + """, + """ + + + + """, @""); } [Fact] public void i_number_pos_double_huge_exp_json() { - TestNST(@"@""[1.5e+9999]""", @" - - - - [ - - - 1.5e+9999 - - - ] - - - - -", - @" - -", + TestNST(""" + @"[1.5e+9999]" + """, """ + + + + + [ + + + 1.5e+9999 + + + ] + + + + + + """, + """ + + + + """, @""); } [Fact] public void i_number_real_neg_overflow_json() { - TestNST(@"@""[-123123e100000]""", @" - - - - [ - - - -123123e100000 - - - ] - - - - -", - @" - -", + TestNST(""" + @"[-123123e100000]" + """, """ + + + + + [ + + + -123123e100000 + + + ] + + + + + + """, + """ + + + + """, @""); } [Fact] public void i_number_real_pos_overflow_json() { - TestNST(@"@""[123123e100000]""", @" - - - - [ - - - 123123e100000 - - - ] - - - - -", - @" - -", + TestNST(""" + @"[123123e100000]" + """, """ + + + + + [ + + + 123123e100000 + + + ] + + + + + + """, + """ + + + + """, @""); } [Fact] public void i_number_real_underflow_json() { - TestNST(@"@""[123e-10000000]""", @" - - - - [ - - - 123e-10000000 - - - ] - - - - -", + TestNST(""" + @"[123e-10000000]" + """, """ + + + + + [ + + + 123e-10000000 + + + ] + + + + + + """, @"", @""); } @@ -221,22 +267,26 @@ public void i_number_real_underflow_json() [Fact] public void i_number_too_big_neg_int_json() { - TestNST(@"@""[-123123123123123123123123123123]""", @" - - - - [ - - - -123123123123123123123123123123 - - - ] - - - - -", + TestNST(""" + @"[-123123123123123123123123123123]" + """, """ + + + + + [ + + + -123123123123123123123123123123 + + + ] + + + + + + """, @"", @""); } @@ -244,22 +294,26 @@ public void i_number_too_big_neg_int_json() [Fact] public void i_number_too_big_pos_int_json() { - TestNST(@"@""[100000000000000000000]""", @" - - - - [ - - - 100000000000000000000 - - - ] - - - - -", + TestNST(""" + @"[100000000000000000000]" + """, """ + + + + + [ + + + 100000000000000000000 + + + ] + + + + + + """, @"", @""); } @@ -267,22 +321,26 @@ public void i_number_too_big_pos_int_json() [Fact] public void i_number_very_big_negative_int_json() { - TestNST(@"@""[-237462374673276894279832749832423479823246327846]""", @" - - - - [ - - - -237462374673276894279832749832423479823246327846 - - - ] - - - - -", + TestNST(""" + @"[-237462374673276894279832749832423479823246327846]" + """, """ + + + + + [ + + + -237462374673276894279832749832423479823246327846 + + + ] + + + + + + """, @"", @""); } @@ -290,26 +348,30 @@ public void i_number_very_big_negative_int_json() [Fact] public void i_object_key_lone_2nd_surrogate_json() { - TestNST(@"@""{""""\uDFAA"""":0}""", @" - - - - { - - - ""\uDFAA"" - : - - 0 - - - - } - - - - -", + TestNST(""" + @"{""\uDFAA"":0}" + """, """ + + + + + { + + + "\uDFAA" + : + + 0 + + + + } + + + + + + """, @"", @""); } @@ -317,22 +379,26 @@ public void i_object_key_lone_2nd_surrogate_json() [Fact] public void i_string_1st_surrogate_but_2nd_missing_json() { - TestNST(@"@""[""""\uDADA""""]""", @" - - - - [ - - - ""\uDADA"" - - - ] - - - - -", + TestNST(""" + @"[""\uDADA""]" + """, """ + + + + + [ + + + "\uDADA" + + + ] + + + + + + """, @"", @""); } @@ -340,22 +406,26 @@ public void i_string_1st_surrogate_but_2nd_missing_json() [Fact] public void i_string_1st_valid_surrogate_2nd_invalid_json() { - TestNST(@"@""[""""\uD888\u1234""""]""", @" - - - - [ - - - ""\uD888\u1234"" - - - ] - - - - -", + TestNST(""" + @"[""\uD888\u1234""]" + """, """ + + + + + [ + + + "\uD888\u1234" + + + ] + + + + + + """, @"", @""); } @@ -363,22 +433,26 @@ public void i_string_1st_valid_surrogate_2nd_invalid_json() [Fact] public void i_string_incomplete_surrogates_escape_valid_json() { - TestNST(@"@""[""""\uD800\uD800\n""""]""", @" - - - - [ - - - ""\uD800\uD800\n"" - - - ] - - - - -", + TestNST(""" + @"[""\uD800\uD800\n""]" + """, """ + + + + + [ + + + "\uD800\uD800\n" + + + ] + + + + + + """, @"", @""); } @@ -386,22 +460,26 @@ public void i_string_incomplete_surrogates_escape_valid_json() [Fact] public void i_string_incomplete_surrogate_and_escape_valid_json() { - TestNST(@"@""[""""\uD800\n""""]""", @" - - - - [ - - - ""\uD800\n"" - - - ] - - - - -", + TestNST(""" + @"[""\uD800\n""]" + """, """ + + + + + [ + + + "\uD800\n" + + + ] + + + + + + """, @"", @""); } @@ -409,22 +487,26 @@ public void i_string_incomplete_surrogate_and_escape_valid_json() [Fact] public void i_string_incomplete_surrogate_pair_json() { - TestNST(@"@""[""""\uDd1ea""""]""", @" - - - - [ - - - ""\uDd1ea"" - - - ] - - - - -", + TestNST(""" + @"[""\uDd1ea""]" + """, """ + + + + + [ + + + "\uDd1ea" + + + ] + + + + + + """, @"", @""); } @@ -432,22 +514,26 @@ public void i_string_incomplete_surrogate_pair_json() [Fact] public void i_string_invalid_lonely_surrogate_json() { - TestNST(@"@""[""""\ud800""""]""", @" - - - - [ - - - ""\ud800"" - - - ] - - - - -", + TestNST(""" + @"[""\ud800""]" + """, """ + + + + + [ + + + "\ud800" + + + ] + + + + + + """, @"", @""); } @@ -455,22 +541,26 @@ public void i_string_invalid_lonely_surrogate_json() [Fact] public void i_string_invalid_surrogate_json() { - TestNST(@"@""[""""\ud800abc""""]""", @" - - - - [ - - - ""\ud800abc"" - - - ] - - - - -", + TestNST(""" + @"[""\ud800abc""]" + """, """ + + + + + [ + + + "\ud800abc" + + + ] + + + + + + """, @"", @""); } @@ -478,22 +568,26 @@ public void i_string_invalid_surrogate_json() [Fact] public void i_string_invalid_utf_8_json() { - TestNST(@"@""[""""�""""]""", @" - - - - [ - - - ""�"" - - - ] - - - - -", + TestNST(""" + @"[""�""]" + """, """ + + + + + [ + + + "�" + + + ] + + + + + + """, @"", @""); } @@ -501,22 +595,26 @@ public void i_string_invalid_utf_8_json() [Fact] public void i_string_inverted_surrogates_U_1D11E_json() { - TestNST(@"@""[""""\uDd1e\uD834""""]""", @" - - - - [ - - - ""\uDd1e\uD834"" - - - ] - - - - -", + TestNST(""" + @"[""\uDd1e\uD834""]" + """, """ + + + + + [ + + + "\uDd1e\uD834" + + + ] + + + + + + """, @"", @""); } @@ -524,22 +622,26 @@ public void i_string_inverted_surrogates_U_1D11E_json() [Fact] public void i_string_iso_latin_1_json() { - TestNST(@"@""[""""�""""]""", @" - - - - [ - - - ""�"" - - - ] - - - - -", + TestNST(""" + @"[""�""]" + """, """ + + + + + [ + + + "�" + + + ] + + + + + + """, @"", @""); } @@ -547,22 +649,26 @@ public void i_string_iso_latin_1_json() [Fact] public void i_string_lone_second_surrogate_json() { - TestNST(@"@""[""""\uDFAA""""]""", @" - - - - [ - - - ""\uDFAA"" - - - ] - - - - -", + TestNST(""" + @"[""\uDFAA""]" + """, """ + + + + + [ + + + "\uDFAA" + + + ] + + + + + + """, @"", @""); } @@ -570,22 +676,26 @@ public void i_string_lone_second_surrogate_json() [Fact] public void i_string_lone_utf8_continuation_byte_json() { - TestNST(@"@""[""""�""""]""", @" - - - - [ - - - ""�"" - - - ] - - - - -", + TestNST(""" + @"[""�""]" + """, """ + + + + + [ + + + "�" + + + ] + + + + + + """, @"", @""); } @@ -593,22 +703,26 @@ public void i_string_lone_utf8_continuation_byte_json() [Fact] public void i_string_not_in_unicode_range_json() { - TestNST(@"@""[""""���""""]""", @" - - - - [ - - - ""���"" - - - ] - - - - -", + TestNST(""" + @"[""���""]" + """, """ + + + + + [ + + + "���" + + + ] + + + + + + """, @"", @""); } @@ -616,22 +730,26 @@ public void i_string_not_in_unicode_range_json() [Fact] public void i_string_overlong_sequence_2_bytes_json() { - TestNST(@"@""[""""��""""]""", @" - - - - [ - - - ""��"" - - - ] - - - - -", + TestNST(""" + @"[""��""]" + """, """ + + + + + [ + + + "��" + + + ] + + + + + + """, @"", @""); } @@ -639,22 +757,26 @@ public void i_string_overlong_sequence_2_bytes_json() [Fact] public void i_string_overlong_sequence_6_bytes_json() { - TestNST(@"@""[""""������""""]""", @" - - - - [ - - - ""������"" - - - ] - - - - -", + TestNST(""" + @"[""������""]" + """, """ + + + + + [ + + + "������" + + + ] + + + + + + """, @"", @""); } @@ -662,22 +784,26 @@ public void i_string_overlong_sequence_6_bytes_json() [Fact] public void i_string_overlong_sequence_6_bytes_null_json() { - TestNST(@"@""[""""������""""]""", @" - - - - [ - - - ""������"" - - - ] - - - - -", + TestNST(""" + @"[""������""]" + """, """ + + + + + [ + + + "������" + + + ] + + + + + + """, @"", @""); } @@ -685,22 +811,26 @@ public void i_string_overlong_sequence_6_bytes_null_json() [Fact] public void i_string_truncated_utf_8_json() { - TestNST(@"@""[""""��""""]""", @" - - - - [ - - - ""��"" - - - ] - - - - -", + TestNST(""" + @"[""��""]" + """, """ + + + + + [ + + + "��" + + + ] + + + + + + """, @"", @""); } @@ -708,22 +838,26 @@ public void i_string_truncated_utf_8_json() [Fact] public void i_string_UTF_16LE_with_BOM_json() { - TestNST(@"@""[""""é""""]""", @" - - - - [ - - - ""é"" - - - ] - - - - -", + TestNST(""" + @"[""é""]" + """, """ + + + + + [ + + + "é" + + + ] + + + + + + """, @"", @""); } @@ -731,22 +865,26 @@ public void i_string_UTF_16LE_with_BOM_json() [Fact] public void i_string_UTF_8_invalid_sequence_json() { - TestNST(@"@""[""""日ш�""""]""", @" - - - - [ - - - ""日ш�"" - - - ] - - - - -", + TestNST(""" + @"[""日ш�""]" + """, """ + + + + + [ + + + "日ш�" + + + ] + + + + + + """, @"", @""); } @@ -754,22 +892,26 @@ public void i_string_UTF_8_invalid_sequence_json() [Fact] public void i_string_Utf8_surrogate_U_D800_json() { - TestNST(@"@""[""""��""""]""", @" - - - - [ - - - ""��"" - - - ] - - - - -", + TestNST(""" + @"[""��""]" + """, """ + + + + + [ + + + "��" + + + ] + + + + + + """, @"", @""); } @@ -777,18 +919,22 @@ public void i_string_Utf8_surrogate_U_D800_json() [Fact] public void i_structure_UTF_8_BOM_empty_object_json() { - TestNST(@"@""{}""", @" - - - - { - - } - - - - -", + TestNST(""" + @"{}" + """, """ + + + + + { + + } + + + + + + """, @"", @""); } @@ -796,4932 +942,6252 @@ public void i_structure_UTF_8_BOM_empty_object_json() [Fact] public void n_array_1_true_without_comma_json() { - TestNST(@"@""[1 true]""", @" - - - - [ - - - 1 - - - true - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[1 true]" + """, """ + + + + + [ + + + 1 + + + true + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_array_a_invalid_utf8_json() { - TestNST(@"@""[a�]""", @" - - - - [ - - - a� - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[a�]" + """, """ + + + + + [ + + + a� + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_array_colon_instead_of_comma_json() { - TestNST(@"@""["""""""": 1]""", @" - - - - [ - - - """" - : - - 1 - - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""""" + @"["""": 1]" + """"", """ + + + + + [ + + + "" + : + + 1 + + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_array_comma_after_close_json() { - TestNST(@"@""[""""""""],""", @" - - - - [ - - - """" - - - ] - - - , - - - - -", - @" - -", - @" - -"); + TestNST(""""" + @"[""""]," + """"", """ + + + + + [ + + + "" + + + ] + + + , + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_array_comma_and_number_json() { - TestNST(@"@""[,1]""", @" - - - - [ - - - , - - - 1 - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"[,1]" + """, """ + + + + + [ + + + , + + + 1 + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_array_double_comma_json() { - TestNST(@"@""[1,,2]""", @" - - - - [ - - - 1 - - - , - - - , - - - 2 - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"[1,,2]" + """, """ + + + + + [ + + + 1 + + + , + + + , + + + 2 + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_array_double_extra_comma_json() { - TestNST(@"@""[""""x"""",,]""", @" - - - - [ - - - ""x"" - - - , - - - , - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"[""x"",,]" + """, """ + + + + + [ + + + "x" + + + , + + + , + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_array_extra_close_json() { - TestNST(@"@""[""""x""""]]""", @" - - - - [ - - - ""x"" - - - ] - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[""x""]]" + """, """ + + + + + [ + + + "x" + + + ] + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_array_extra_comma_json() { - TestNST(@"@""["""""""",]""", @" - - - - [ - - - """" - - - , - - - ] - - - - -", - @"", - @" - -"); + TestNST(""""" + @"["""",]" + """"", """ + + + + + [ + + + "" + + + , + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_array_incomplete_json() { - TestNST(@"@""[""""x""""""", @" - - - - [ - - - ""x"" - - - - - - - -", - @" - -", - @" - -"); + TestNST("""" + @"[""x""" + """", """ + + + + + [ + + + "x" + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_array_incomplete_invalid_value_json() { - TestNST(@"@""[x""", @" - - - - [ - - - x - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[x" + """, """ + + + + + [ + + + x + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_array_inner_array_no_comma_json() { - TestNST(@"@""[3[4]]""", @" - - - - [ - - - 3 - - - [ - - - 4 - - - ] - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[3[4]]" + """, """ + + + + + [ + + + 3 + + + [ + + + 4 + + + ] + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_array_invalid_utf8_json() { - TestNST(@"@""[�]""", @" - - - - [ - - - - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[�]" + """, """ + + + + + [ + + + + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_array_items_separated_by_semicolon_json() { - TestNST(@"@""[1:2]""", @" - - - - [ - - - 1 - : - - 2 - - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[1:2]" + """, """ + + + + + [ + + + 1 + : + + 2 + + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_array_just_comma_json() { - TestNST(@"@""[,]""", @" - - - - [ - - - , - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"[,]" + """, """ + + + + + [ + + + , + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_array_just_minus_json() { - TestNST(@"@""[-]""", @" - - - - [ - - - - - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[-]" + """, """ + + + + + [ + + + - + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_array_missing_value_json() { - TestNST(@"@""[ , """"""""]""", @" - - - - [ - - - , - - - """" - - - ] - - - - -", - @"", - @" - -"); + TestNST(""""" + @"[ , """"]" + """"", """ + + + + + [ + + + , + + + "" + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_array_newlines_unclosed_json() { - TestNST(@"@""[""""a"""", -4 -,1,""", @" - - - - [ - - - ""a"" - - - , - - - - 4 - - - - , - - - 1 - - - , - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[""a"", + 4 + ,1," + """, """ + + + + + [ + + + "a" + + + , + + + + 4 + + + + , + + + 1 + + + , + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_array_number_and_comma_json() { - TestNST(@"@""[1,]""", @" - - - - [ - - - 1 - - - , - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"[1,]" + """, """ + + + + + [ + + + 1 + + + , + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_array_number_and_several_commas_json() { - TestNST(@"@""[1,,]""", @" - - - - [ - - - 1 - - - , - - - , - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"[1,,]" + """, """ + + + + + [ + + + 1 + + + , + + + , + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_array_star_inside_json() { - TestNST(@"@""[*]""", @" - - - - [ - - - * - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[*]" + """, """ + + + + + [ + + + * + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_array_unclosed_json() { - TestNST(@"@""[""""""""""", @" - - - - [ - - - """" - - - - - - - -", - @" - -", - @" - -"); + TestNST("""""" + @"[""""" + """""", """ + + + + + [ + + + "" + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_array_unclosed_trailing_comma_json() { - TestNST(@"@""[1,""", @" - - - - [ - - - 1 - - - , - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[1," + """, """ + + + + + [ + + + 1 + + + , + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_array_unclosed_with_new_lines_json() { - TestNST(@"@""[1, -1 -,1""", @" - - - - [ - - - 1 - - - , - - - - 1 - - - - , - - - 1 - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[1, + 1 + ,1" + """, """ + + + + + [ + + + 1 + + + , + + + + 1 + + + + , + + + 1 + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_array_unclosed_with_object_inside_json() { - TestNST(@"@""[{}""", @" - - - - [ - - - { - - } - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[{}" + """, """ + + + + + [ + + + { + + } + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_incomplete_false_json() { - TestNST(@"@""[fals]""", @" - - - - [ - - - fals - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[fals]" + """, """ + + + + + [ + + + fals + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_incomplete_null_json() { - TestNST(@"@""[nul]""", @" - - - - [ - - - nul - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[nul]" + """, """ + + + + + [ + + + nul + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_incomplete_true_json() { - TestNST(@"@""[tru]""", @" - - - - [ - - - tru - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[tru]" + """, """ + + + + + [ + + + tru + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number____json() { - TestNST(@"@""[++1234]""", @" - - - - [ - - - ++1234 - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[++1234]" + """, """ + + + + + [ + + + ++1234 + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number__1_json() { - TestNST(@"@""[+1]""", @" - - - - [ - - - +1 - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[+1]" + """, """ + + + + + [ + + + +1 + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number__Inf_json() { - TestNST(@"@""[+Inf]""", @" - - - - [ - - - +Inf - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[+Inf]" + """, """ + + + + + [ + + + +Inf + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number__01_json() { - TestNST(@"@""[-01]""", @" - - - - [ - - - -01 - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"[-01]" + """, """ + + + + + [ + + + -01 + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_number__1_0__json() { - TestNST(@"@""[-1.0.]""", @" - - - - [ - - - -1.0. - - - ] - - - - -", - @" - -", - @" - -"); - } - + TestNST(""" + @"[-1.0.]" + """, """ + + + + + [ + + + -1.0. + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); + } + [Fact] public void n_number__2__json() { - TestNST(@"@""[-2.]""", @" - - - - [ - - - -2. - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"[-2.]" + """, """ + + + + + [ + + + -2. + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_number__NaN_json() { - TestNST(@"@""[-NaN]""", @" - - - - [ - - - -NaN - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[-NaN]" + """, """ + + + + + [ + + + -NaN + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number___1_json() { - TestNST(@"@""[.-1]""", @" - - - - [ - - - .-1 - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[.-1]" + """, """ + + + + + [ + + + .-1 + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number__2e_3_json() { - TestNST(@"@""[.2e-3]""", @" - - - - [ - - - .2e-3 - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"[.2e-3]" + """, """ + + + + + [ + + + .2e-3 + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_number_0_1_2_json() { - TestNST(@"@""[0.1.2]""", @" - - - - [ - - - 0.1.2 - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[0.1.2]" + """, """ + + + + + [ + + + 0.1.2 + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_0_3e__json() { - TestNST(@"@""[0.3e+]""", @" - - - - [ - - - 0.3e+ - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[0.3e+]" + """, """ + + + + + [ + + + 0.3e+ + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_0_3e_json() { - TestNST(@"@""[0.3e]""", @" - - - - [ - - - 0.3e - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[0.3e]" + """, """ + + + + + [ + + + 0.3e + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_0_e1_json() { - TestNST(@"@""[0.e1]""", @" - - - - [ - - - 0.e1 - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"[0.e1]" + """, """ + + + + + [ + + + 0.e1 + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_number_0e__json() { - TestNST(@"@""[0e+]""", @" - - - - [ - - - 0e+ - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[0e+]" + """, """ + + + + + [ + + + 0e+ + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_0e_json() { - TestNST(@"@""[0e]""", @" - - - - [ - - - 0e - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[0e]" + """, """ + + + + + [ + + + 0e + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_0_capital_E__json() { - TestNST(@"@""[0E+]""", @" - - - - [ - - - 0E+ - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[0E+]" + """, """ + + + + + [ + + + 0E+ + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_0_capital_E_json() { - TestNST(@"@""[0E]""", @" - - - - [ - - - 0E - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[0E]" + """, """ + + + + + [ + + + 0E + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_1_0e__json() { - TestNST(@"@""[1.0e+]""", @" - - - - [ - - - 1.0e+ - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[1.0e+]" + """, """ + + + + + [ + + + 1.0e+ + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_1_0e_json() { - TestNST(@"@""[1.0e]""", @" - - - - [ - - - 1.0e - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[1.0e]" + """, """ + + + + + [ + + + 1.0e + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_1eE2_json() { - TestNST(@"@""[1eE2]""", @" - - - - [ - - - 1eE2 - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[1eE2]" + """, """ + + + + + [ + + + 1eE2 + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_1_000_json() { - TestNST(@"@""[1 000.0]""", @" - - - - [ - - - 1 - - - 000.0 - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[1 000.0]" + """, """ + + + + + [ + + + 1 + + + 000.0 + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_2_e_3_json() { - TestNST(@"@""[2.e+3]""", @" - - - - [ - - - 2.e+3 - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"[2.e+3]" + """, """ + + + + + [ + + + 2.e+3 + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_number_2_e3_json() { - TestNST(@"@""[2.e3]""", @" - - - - [ - - - 2.e3 - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"[2.e3]" + """, """ + + + + + [ + + + 2.e3 + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_number_9_e__json() { - TestNST(@"@""[9.e+]""", @" - - - - [ - - - 9.e+ - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[9.e+]" + """, """ + + + + + [ + + + 9.e+ + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_expression_json() { - TestNST(@"@""[1+2]""", @" - - - - [ - - - 1+2 - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[1+2]" + """, """ + + + + + [ + + + 1+2 + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_hex_1_digit_json() { - TestNST(@"@""[0x1]""", @" - - - - [ - - - 0x1 - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"[0x1]" + """, """ + + + + + [ + + + 0x1 + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_number_hex_2_digits_json() { - TestNST(@"@""[0x42]""", @" - - - - [ - - - 0x42 - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"[0x42]" + """, """ + + + + + [ + + + 0x42 + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_number_Inf_json() { - TestNST(@"@""[Inf]""", @" - - - - [ - - - Inf - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[Inf]" + """, """ + + + + + [ + + + Inf + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_infinity_json() { - TestNST(@"@""[Infinity]""", @" - - - - [ - - - Infinity - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"[Infinity]" + """, """ + + + + + [ + + + Infinity + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_number_invalid___json() { - TestNST(@"@""[0e+-1]""", @" - - - - [ - - - 0e+-1 - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[0e+-1]" + """, """ + + + + + [ + + + 0e+-1 + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_invalid_negative_real_json() { - TestNST(@"@""[-123.123foo]""", @" - - - - [ - - - -123.123foo - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[-123.123foo]" + """, """ + + + + + [ + + + -123.123foo + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_invalid_utf_8_in_bigger_int_json() { - TestNST(@"@""[123�]""", @" - - - - [ - - - 123� - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[123�]" + """, """ + + + + + [ + + + 123� + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_invalid_utf_8_in_exponent_json() { - TestNST(@"@""[1e1�]""", @" - - - - [ - - - 1e1� - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[1e1�]" + """, """ + + + + + [ + + + 1e1� + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_invalid_utf_8_in_int_json() { - TestNST(@"@""[0�] -""", @" - - - - [ - - - 0� - - - ] - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[0�] + " + """, """ + + + + + [ + + + 0� + + + ] + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_minus_infinity_json() { - TestNST(@"@""[-Infinity]""", @" - - - - [ - - - - - Infinity - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"[-Infinity]" + """, """ + + + + + [ + + + - + Infinity + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_number_minus_sign_with_trailing_garbage_json() { - TestNST(@"@""[-foo]""", @" - - - - [ - - - -foo - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[-foo]" + """, """ + + + + + [ + + + -foo + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_minus_space_1_json() { - TestNST(@"@""[- 1]""", @" - - - - [ - - - - - - - 1 - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[- 1]" + """, """ + + + + + [ + + + - + + + 1 + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_NaN_json() { - TestNST(@"@""[NaN]""", @" - - - - [ - - - NaN - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"[NaN]" + """, """ + + + + + [ + + + NaN + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_number_neg_int_starting_with_zero_json() { - TestNST(@"@""[-012]""", @" - - - - [ - - - -012 - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"[-012]" + """, """ + + + + + [ + + + -012 + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_number_neg_real_without_int_part_json() { - TestNST(@"@""[-.123]""", @" - - - - [ - - - -.123 - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"[-.123]" + """, """ + + + + + [ + + + -.123 + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_number_neg_with_garbage_at_end_json() { - TestNST(@"@""[-1x]""", @" - - - - [ - - - -1x - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[-1x]" + """, """ + + + + + [ + + + -1x + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_real_garbage_after_e_json() { - TestNST(@"@""[1ea]""", @" - - - - [ - - - 1ea - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[1ea]" + """, """ + + + + + [ + + + 1ea + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_real_without_fractional_part_json() { - TestNST(@"@""[1.]""", @" - - - - [ - - - 1. - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"[1.]" + """, """ + + + + + [ + + + 1. + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_number_real_with_invalid_utf8_after_e_json() { - TestNST(@"@""[1e�]""", @" - - - - [ - - - 1e� - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[1e�]" + """, """ + + + + + [ + + + 1e� + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_starting_with_dot_json() { - TestNST(@"@""[.123]""", @" - - - - [ - - - .123 - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"[.123]" + """, """ + + + + + [ + + + .123 + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_number_U_FF11_fullwidth_digit_one_json() { - TestNST(@"@""[1]""", @" - - - - [ - - - - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[1]" + """, """ + + + + + [ + + + + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_with_alpha_json() { - TestNST(@"@""[1.2a-3]""", @" - - - - [ - - - 1.2a-3 - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[1.2a-3]" + """, """ + + + + + [ + + + 1.2a-3 + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_with_alpha_char_json() { - TestNST(@"@""[1.8011670033376514H-308]""", @" - - - - [ - - - 1.8011670033376514H-308 - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[1.8011670033376514H-308]" + """, """ + + + + + [ + + + 1.8011670033376514H-308 + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_number_with_leading_zero_json() { - TestNST(@"@""[012]""", @" - - - - [ - - - 012 - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"[012]" + """, """ + + + + + [ + + + 012 + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_object_bad_value_json() { - TestNST(@"@""[""""x"""", truth]""", @" - - - - [ - - - ""x"" - - - , - - - truth - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[""x"", truth]" + """, """ + + + + + [ + + + "x" + + + , + + + truth + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_object_bracket_key_json() { - TestNST(@"@""{[: """"x""""} -""", @" - - - - { - - - [ - - - : - - - ""x"" - - - - - - } - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{[: ""x""} + " + """, """ + + + + + { + + + [ + + + : + + + "x" + + + + + + } + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_object_comma_instead_of_colon_json() { - TestNST(@"@""{""""x"""", null}""", @" - - - - { - - - ""x"" - - , - - null - - - } - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{""x"", null}" + """, """ + + + + + { + + + "x" + + , + + null + + + } + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_object_double_colon_json() { - TestNST(@"@""{""""x""""::""""b""""}""", @" - - - - { - - - ""x"" - : - - : - - - - - ""b"" - - - } - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{""x""::""b""}" + """, """ + + + + + { + + + "x" + : + + : + + + + + "b" + + + } + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_object_garbage_at_end_json() { - TestNST(@"@""{""""a"""":""""a"""" 123}""", @" - - - - { - - - ""a"" - : - - ""a"" - - - - - 123 - - - } - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{""a"":""a"" 123}" + """, """ + + + + + { + + + "a" + : + + "a" + + + + + 123 + + + } + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_object_key_with_single_quotes_json() { - TestNST(@"@""{key: 'value'}""", @" - - - - { - - - key - : - - 'value' - - - - } - - - - -", - @"", - @" - -"); + TestNST(""" + @"{key: 'value'}" + """, """ + + + + + { + + + key + : + + 'value' + + + + } + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_object_lone_continuation_byte_in_key_and_trailing_comma_json() { - TestNST(@"@""{""""�"""":""""0"""",}""", @" - - - - { - - - ""�"" - : - - ""0"" - - - , - - } - - - - -", - @"", - @" - -"); + TestNST(""" + @"{""�"":""0"",}" + """, """ + + + + + { + + + "�" + : + + "0" + + + , + + } + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_object_missing_colon_json() { - TestNST(@"@""{""""a"""" b}""", @" - - - - { - - - ""a"" - - - - b - - - } - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{""a"" b}" + """, """ + + + + + { + + + "a" + + + + b + + + } + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_object_missing_key_json() { - TestNST(@"@""{:""""b""""}""", @" - - - - { - - - : - - - - ""b"" - - - } - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{:""b""}" + """, """ + + + + + { + + + : + + + + "b" + + + } + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_object_missing_semicolon_json() { - TestNST(@"@""{""""a"""" """"b""""}""", @" - - - - { - - - ""a"" - - - - ""b"" - - - } - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{""a"" ""b""}" + """, """ + + + + + { + + + "a" + + + + "b" + + + } + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_object_missing_value_json() { - TestNST(@"@""{""""a"""":""", @" - - - - { - - - ""a"" - : - - - - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{""a"":" + """, """ + + + + + { + + + "a" + : + + + + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_object_no_colon_json() { - TestNST(@"@""{""""a""""""", @" - - - - { - - - ""a"" - - - - - - - -", - @" - -", - @" - -"); + TestNST("""" + @"{""a""" + """", """ + + + + + { + + + "a" + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_object_non_string_key_json() { - TestNST(@"@""{1:1}""", @" - - - - { - - - 1 - : - - 1 - - - - } - - - - -", - @"", - @" - -"); + TestNST(""" + @"{1:1}" + """, """ + + + + + { + + + 1 + : + + 1 + + + + } + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_object_non_string_key_but_huge_number_instead_json() { - TestNST(@"@""{9999E9999:1}""", @" - - - - { - - - 9999E9999 - : - - 1 - - - - } - - - - -", - @"", - @" - -"); + TestNST(""" + @"{9999E9999:1}" + """, """ + + + + + { + + + 9999E9999 + : + + 1 + + + + } + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_object_repeated_null_null_json() { - TestNST(@"@""{null:null,null:null}""", @" - - - - { - - - null - : - - null - - - , - - null - : - - null - - - - } - - - - -", - @"", - @" - -"); + TestNST(""" + @"{null:null,null:null}" + """, """ + + + + + { + + + null + : + + null + + + , + + null + : + + null + + + + } + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_object_several_trailing_commas_json() { - TestNST(@"@""{""""id"""":0,,,,,}""", @" - - - - { - - - ""id"" - : - - 0 - - - , - - , - - , - - , - - , - - } - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{""id"":0,,,,,}" + """, """ + + + + + { + + + "id" + : + + 0 + + + , + + , + + , + + , + + , + + } + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_object_single_quote_json() { - TestNST(@"@""{'a':0}""", @" - - - - { - - - 'a' - : - - 0 - - - - } - - - - -", - @"", - @" - -"); + TestNST(""" + @"{'a':0}" + """, """ + + + + + { + + + 'a' + : + + 0 + + + + } + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_object_trailing_comma_json() { - TestNST(@"@""{""""id"""":0,}""", @" - - - - { - - - ""id"" - : - - 0 - - - , - - } - - - - -", - @"", - @" - -"); + TestNST(""" + @"{""id"":0,}" + """, """ + + + + + { + + + "id" + : + + 0 + + + , + + } + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_object_trailing_comment_json() { - TestNST(@"@""{""""a"""":""""b""""}/**/""", @" - - - - { - - - ""a"" - : - - ""b"" - - - - }/**/ - - - - -", - @"", - @" - -"); + TestNST(""" + @"{""a"":""b""}/**/" + """, """ + + + + + { + + + "a" + : + + "b" + + + + }/**/ + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_object_trailing_comment_open_json() { - TestNST(@"@""{""""a"""":""""b""""}/**//""", @" - - - - { - - - ""a"" - : - - ""b"" - - - - }/**// - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{""a"":""b""}/**//" + """, """ + + + + + { + + + "a" + : + + "b" + + + + }/**// + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_object_trailing_comment_slash_open_json() { - TestNST(@"@""{""""a"""":""""b""""}//""", @" - - - - { - - - ""a"" - : - - ""b"" - - - - }// - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{""a"":""b""}//" + """, """ + + + + + { + + + "a" + : + + "b" + + + + }// + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_object_trailing_comment_slash_open_incomplete_json() { - TestNST(@"@""{""""a"""":""""b""""}/""", @" - - - - { - - - ""a"" - : - - ""b"" - - - - }/ - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{""a"":""b""}/" + """, """ + + + + + { + + + "a" + : + + "b" + + + + }/ + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_object_two_commas_in_a_row_json() { - TestNST(@"@""{""""a"""":""""b"""",,""""c"""":""""d""""}""", @" - - - - { - - - ""a"" - : - - ""b"" - - - , - - , - - - - ""c"" - : - - ""d"" - - - - } - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{""a"":""b"",,""c"":""d""}" + """, """ + + + + + { + + + "a" + : + + "b" + + + , + + , + + + + "c" + : + + "d" + + + + } + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_object_unquoted_key_json() { - TestNST(@"@""{a: """"b""""}""", @" - - - - { - - - a - : - - ""b"" - - - - } - - - - -", - @"", - @" - -"); + TestNST(""" + @"{a: ""b""}" + """, """ + + + + + { + + + a + : + + "b" + + + + } + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_object_unterminated_value_json() { - TestNST(@"@""{""""a"""":""""a""", @" - - - - { - - - ""a"" - : - - ""a - - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{""a"":""a" + """, """ + + + + + { + + + "a" + : + + "a + + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_object_with_single_string_json() { - TestNST(@"@""{ """"foo"""" : """"bar"""", """"a"""" }""", @" - - - - { - - - ""foo"" - : - - ""bar"" - - - , - - ""a"" - - - } - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{ ""foo"" : ""bar"", ""a"" }" + """, """ + + + + + { + + + "foo" + : + + "bar" + + + , + + "a" + + + } + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_object_with_trailing_garbage_json() { - TestNST(@"@""{""""a"""":""""b""""}#""", @" - - - - { - - - ""a"" - : - - ""b"" - - - - } - - - # - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{""a"":""b""}#" + """, """ + + + + + { + + + "a" + : + + "b" + + + + } + + + # + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_single_space_json() { - TestNST(@"@"" """, @" - - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @" " + """, """ + + + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_string_1_surrogate_then_escape_json() { - TestNST(@"@""[""""\uD800\""""]""", @" - - - - [ - - - ""\uD800\""] - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[""\uD800\""]" + """, """ + + + + + [ + + + "\uD800\"] + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_string_1_surrogate_then_escape_u_json() { - TestNST(@"@""[""""\uD800\u""""]""", @" - - - - [ - - - ""\uD800\u""] - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[""\uD800\u""]" + """, """ + + + + + [ + + + "\uD800\u"] + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_string_1_surrogate_then_escape_u1_json() { - TestNST(@"@""[""""\uD800\u1""""]""", @" - - - - [ - - - ""\uD800\u1""] - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[""\uD800\u1""]" + """, """ + + + + + [ + + + "\uD800\u1"] + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_string_1_surrogate_then_escape_u1x_json() { - TestNST(@"@""[""""\uD800\u1x""""]""", @" - - - - [ - - - ""\uD800\u1x""] - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[""\uD800\u1x""]" + """, """ + + + + + [ + + + "\uD800\u1x"] + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_string_accentuated_char_no_quotes_json() { - TestNST(@"@""[é]""", @" - - - - [ - - - é - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[é]" + """, """ + + + + + [ + + + é + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_string_escaped_backslash_bad_json() { - TestNST(@"@""[""""\\\""""]""", @" - - - - [ - - - ""\\\""] - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[""\\\""]" + """, """ + + + + + [ + + + "\\\"] + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_string_escaped_ctrl_char_tab_json() { - TestNST(@"@""[""""\ """"]""", @" - - - - [ - - - ""\ "" - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[""\ ""]" + """, """ + + + + + [ + + + "\ " + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_string_escaped_emoji_json() { - TestNST(@"@""[""""\🌀""""]""", @" - - - - [ - - - ""\🌀"" - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[""\🌀""]" + """, """ + + + + + [ + + + "\🌀" + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_string_escape_x_json() { - TestNST(@"@""[""""\x00""""]""", @" - - - - [ - - - ""\x00"" - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[""\x00""]" + """, """ + + + + + [ + + + "\x00" + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_string_incomplete_escape_json() { - TestNST(@"@""[""""\""""]""", @" - - - - [ - - - ""\""] - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[""\""]" + """, """ + + + + + [ + + + "\"] + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_string_incomplete_escaped_character_json() { - TestNST(@"@""[""""\u00A""""]""", @" - - - - [ - - - ""\u00A""] - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[""\u00A""]" + """, """ + + + + + [ + + + "\u00A"] + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_string_incomplete_surrogate_json() { - TestNST(@"@""[""""\uD834\uDd""""]""", @" - - - - [ - - - ""\uD834\uDd""] - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[""\uD834\uDd""]" + """, """ + + + + + [ + + + "\uD834\uDd"] + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_string_incomplete_surrogate_escape_invalid_json() { - TestNST(@"@""[""""\uD800\uD800\x""""]""", @" - - - - [ - - - ""\uD800\uD800\x"" - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[""\uD800\uD800\x""]" + """, """ + + + + + [ + + + "\uD800\uD800\x" + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_string_invalid_utf_8_in_escape_json() { - TestNST(@"@""[""""\u�""""]""", @" - - - - [ - - - ""\u�""] - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[""\u�""]" + """, """ + + + + + [ + + + "\u�"] + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_string_invalid_backslash_esc_json() { - TestNST(@"@""[""""\a""""]""", @" - - - - [ - - - ""\a"" - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[""\a""]" + """, """ + + + + + [ + + + "\a" + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_string_invalid_unicode_escape_json() { - TestNST(@"@""[""""\uqqqq""""]""", @" - - - - [ - - - ""\uqqqq"" - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[""\uqqqq""]" + """, """ + + + + + [ + + + "\uqqqq" + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_string_invalid_utf8_after_escape_json() { - TestNST(@"@""[""""\�""""]""", @" - - - - [ - - - ""\�"" - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[""\�""]" + """, """ + + + + + [ + + + "\�" + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_string_leading_uescaped_thinspace_json() { - TestNST(@"@""[\u0020""""asd""""]""", @" - - - - [ - - - \u0020 - - - ""asd"" - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[\u0020""asd""]" + """, """ + + + + + [ + + + \u0020 + + + "asd" + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_string_no_quotes_with_bad_escape_json() { - TestNST(@"@""[\n]""", @" - - - - [ - - - \n - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[\n]" + """, """ + + + + + [ + + + \n + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_string_single_doublequote_json() { - TestNST(@"@""""""""", @" - - - - "" - - - - -", - @" - -", - @" - -"); + TestNST(""""" + @"""" + """"", """ + + + + + " + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_string_single_quote_json() { - TestNST(@"@""['single quote']""", @" - - - - [ - - - 'single quote' - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"['single quote']" + """, """ + + + + + [ + + + 'single quote' + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_string_single_string_no_double_quotes_json() { - TestNST(@"@""abc""", @" - - - - abc - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"abc" + """, """ + + + + + abc + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_string_start_escape_unclosed_json() { - TestNST(@"@""[""""\""", @" - - - - [ - - - ""\ - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[""\" + """, """ + + + + + [ + + + "\ + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_string_unescaped_newline_json() { - TestNST(@"@""[""""new -line""""]""", @" - - - - [ - - - ""new -line"" - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"[""new + line""]" + """, """ + + + + + [ + + + "new + line" + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_string_unescaped_tab_json() { - TestNST(@"@""["""" """"]""", @" - - - - [ - - - "" "" - - - ] - - - - -", - @"", - @" - -"); + TestNST(""" + @"["" ""]" + """, """ + + + + + [ + + + " " + + + ] + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_string_unicode_CapitalU_json() { - TestNST(@"@""""""\UA66D""""""", @" - - - - ""\UA66D"" - - - - -", - @" - -", - @" - -"); + TestNST("""" + @"""\UA66D""" + """", """ + + + + + "\UA66D" + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_string_with_trailing_garbage_json() { - TestNST(@"@""""""""""x""", @" - - - - """" - - - x - - - - -", - @" - -", - @" - -"); + TestNST("""""" + @"""""x" + """""", """ + + + + + "" + + + x + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_angle_bracket___json() { - TestNST(@"@""<.>""", @" - - - - <.> - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"<.>" + """, """ + + + + + <.> + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_angle_bracket_null_json() { - TestNST(@"@""[]""", @" - - - - [ - - - <null> - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[]" + """, """ + + + + + [ + + + <null> + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_array_trailing_garbage_json() { - TestNST(@"@""[1]x""", @" - - - - [ - - - 1 - - - ] - - - x - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[1]x" + """, """ + + + + + [ + + + 1 + + + ] + + + x + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_array_with_extra_array_close_json() { - TestNST(@"@""[1]]""", @" - - - - [ - - - 1 - - - ] - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[1]]" + """, """ + + + + + [ + + + 1 + + + ] + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_array_with_unclosed_string_json() { - TestNST(@"@""[""""asd]""", @" - - - - [ - - - ""asd] - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[""asd]" + """, """ + + + + + [ + + + "asd] + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_ascii_unicode_identifier_json() { - TestNST(@"@""aå""", @" - - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"aå" + """, """ + + + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_capitalized_True_json() { - TestNST(@"@""[True]""", @" - - - - [ - - - True - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[True]" + """, """ + + + + + [ + + + True + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_close_unopened_array_json() { - TestNST(@"@""1]""", @" - - - - 1 - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"1]" + """, """ + + + + + 1 + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_comma_instead_of_closing_brace_json() { - TestNST(@"@""{""""x"""": true,""", @" - - - - { - - - ""x"" - : - - true - - - , - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{""x"": true," + """, """ + + + + + { + + + "x" + : + + true + + + , + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_double_array_json() { - TestNST(@"@""[][]""", @" - - - - [ - - ] - - - [ - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[][]" + """, """ + + + + + [ + + ] + + + [ + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_end_array_json() { - TestNST(@"@""]""", @" - - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"]" + """, """ + + + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_incomplete_Utf8_BOM_json() { - TestNST(@"@""�{}""", @" - - - - - - - { - - } - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"�{}" + """, """ + + + + + + + + { + + } + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_lone_open_bracket_json() { - TestNST(@"@""[""", @" - - - - [ - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[" + """, """ + + + + + [ + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_number_with_trailing_garbage_json() { - TestNST(@"@""2@""", @" - - - - 2@ - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"2@" + """, """ + + + + + 2@ + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_object_followed_by_closing_object_json() { - TestNST(@"@""{}}""", @" - - - - { - - } - - - } - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{}}" + """, """ + + + + + { + + } + + + } + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_object_unclosed_no_value_json() { - TestNST(@"@""{"""""""":""", @" - - - - { - - - """" - : - - - - - - - - - - -", - @" - -", - @" - -"); + TestNST(""""" + @"{"""":" + """"", """ + + + + + { + + + "" + : + + + + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_object_with_comment_json() { - TestNST(@"@""{""""a"""":/*comment*/""""b""""}""", @" - - - - { - - - ""a"" - :/*comment*/ - - ""b"" - - - - } - - - - -", - @"", - @" - -"); + TestNST(""" + @"{""a"":/*comment*/""b""}" + """, """ + + + + + { + + + "a" + :/*comment*/ + + "b" + + + + } + + + + + + """, + @"", + """ + + + + """); } [Fact] public void n_structure_object_with_trailing_garbage_json() { - TestNST(@"@""{""""a"""": true} """"x""""""", @" - - - - { - - - ""a"" - : - - true - - - - } - - - ""x"" - - - - -", - @" - -", - @" - -"); + TestNST("""" + @"{""a"": true} ""x""" + """", """ + + + + + { + + + "a" + : + + true + + + + } + + + "x" + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_open_array_apostrophe_json() { - TestNST(@"@""['""", @" - - - - [ - - - ' - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"['" + """, """ + + + + + [ + + + ' + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_open_array_comma_json() { - TestNST(@"@""[,""", @" - - - - [ - - - , - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[," + """, """ + + + + + [ + + + , + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_open_array_open_object_json() { - TestNST(@"@""[{""", @" - - - - [ - - - { - - - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[{" + """, """ + + + + + [ + + + { + + + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_open_array_open_string_json() { - TestNST(@"@""[""""a""", @" - - - - [ - - - ""a - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[""a" + """, """ + + + + + [ + + + "a + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_open_array_string_json() { - TestNST(@"@""[""""a""""""", @" - - - - [ - - - ""a"" - - - - - - - -", - @" - -", - @" - -"); + TestNST("""" + @"[""a""" + """", """ + + + + + [ + + + "a" + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_open_object_json() { - TestNST(@"@""{""", @" - - - - { - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{" + """, """ + + + + + { + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_open_object_close_array_json() { - TestNST(@"@""{]""", @" - - - - { - - - ] - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{]" + """, """ + + + + + { + + + ] + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_open_object_comma_json() { - TestNST(@"@""{,""", @" - - - - { - - - , - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{," + """, """ + + + + + { + + + , + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_open_object_open_array_json() { - TestNST(@"@""{[""", @" - - - - { - - - [ - - - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{[" + """, """ + + + + + { + + + [ + + + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_open_object_open_string_json() { - TestNST(@"@""{""""a""", @" - - - - { - - - ""a - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{""a" + """, """ + + + + + { + + + "a + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_open_object_string_with_apostrophes_json() { - TestNST(@"@""{'a'""", @" - - - - { - - - 'a' - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{'a'" + """, """ + + + + + { + + + 'a' + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_open_open_json() { - TestNST(@"@""[""""\{[""""\{[""""\{[""""\{""", @" - - - - [ - - - ""\{["" - - - \ - - - { - - - [ + TestNST(""" + @"[""\{[""\{[""\{[""\{" + """, """ + + - - ""\{["" - - - \ - - - { - - - + + [ + + + "\{[" + + + \ + + + { + + + [ + + + "\{[" + + + \ + + + { + + + + + + + + + + + + - - - - - - - - - - - -", - @" - -", - @" - -"); + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_single_star_json() { - TestNST(@"@""*""", @" - - - - * - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"*" + """, """ + + + + + * + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_trailing___json() { - TestNST(@"@""{""""a"""":""""b""""}#{}""", @" - - - - { - - - ""a"" - : - - ""b"" - - - - } - - - # - - - { - - } - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"{""a"":""b""}#{}" + """, """ + + + + + { + + + "a" + : + + "b" + + + + } + + + # + + + { + + } + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_U_2060_word_joined_json() { - TestNST(@"@""[⁠]""", @" - - - - [ - - - - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[⁠]" + """, """ + + + + + [ + + + + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_uescaped_LF_before_string_json() { - TestNST(@"@""[\u000A""""""""]""", @" - - - - [ - - - \u000A - - - """" - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""""" + @"[\u000A""""]" + """"", """ + + + + + [ + + + \u000A + + + "" + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_unclosed_array_json() { - TestNST(@"@""[1""", @" - - - - [ - - - 1 - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[1" + """, """ + + + + + [ + + + 1 + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_unclosed_array_partial_null_json() { - TestNST(@"@""[ false, nul""", @" - - - - [ - - - false - - - , - - - nul - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[ false, nul" + """, """ + + + + + [ + + + false + + + , + + + nul + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_unclosed_array_unfinished_false_json() { - TestNST(@"@""[ true, fals""", @" - - - - [ - - - true - - - , - - - fals - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[ true, fals" + """, """ + + + + + [ + + + true + + + , + + + fals + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_unclosed_array_unfinished_true_json() { - TestNST(@"@""[ false, tru""", @" - - - - [ - - - false - - - , - - - tru - - - - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[ false, tru" + """, """ + + + + + [ + + + false + + + , + + + tru + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_unclosed_object_json() { - TestNST(@"@""{""""asd"""":""""asd""""""", @" - - - - { - - - ""asd"" - : - - ""asd"" - - - - - - - - -", - @" - -", - @" - -"); + TestNST("""" + @"{""asd"":""asd""" + """", """ + + + + + { + + + "asd" + : + + "asd" + + + + + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_unicode_identifier_json() { - TestNST(@"@""å""", @" - - - - å - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"å" + """, """ + + + + + å + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void n_structure_whitespace_formfeed_json() { - TestNST(@"@""[ ]""", @" - - - - [\f - - ] - - - - -", + TestNST(""" + @"[ ]" + """, """ + + + + + [\f + + ] + + + + + + """, @"", - @" - -"); + """ + + + + """); } [Fact] public void n_structure_whitespace_U_2060_word_joiner_json() { - TestNST(@"@""[⁠]""", @" - - - - [ - - - - - - ] - - - - -", - @" - -", - @" - -"); + TestNST(""" + @"[⁠]" + """, """ + + + + + [ + + + + + + ] + + + + + + """, + """ + + + + """, + """ + + + + """); } [Fact] public void y_array_arraysWithSpaces_json() { - TestNST(@"@""[[] ]""", @" - - - - [ - - - [ - - ] - - - ] - - - - -", + TestNST(""" + @"[[] ]" + """, """ + + + + + [ + + + [ + + ] + + + ] + + + + + + """, @"", @""); } @@ -5729,22 +7195,26 @@ public void y_array_arraysWithSpaces_json() [Fact] public void y_array_empty_string_json() { - TestNST(@"@""[""""""""]""", @" - - - - [ - - - """" - - - ] - - - - -", + TestNST(""""" + @"[""""]" + """"", """ + + + + + [ + + + "" + + + ] + + + + + + """, @"", @""); } @@ -5752,18 +7222,22 @@ public void y_array_empty_string_json() [Fact] public void y_array_empty_json() { - TestNST(@"@""[]""", @" - - - - [ - - ] - - - - -", + TestNST(""" + @"[]" + """, """ + + + + + [ + + ] + + + + + + """, @"", @""); } @@ -5771,22 +7245,26 @@ public void y_array_empty_json() [Fact] public void y_array_ending_with_newline_json() { - TestNST(@"@""[""""a""""]""", @" - - - - [ - - - ""a"" - - - ] - - - - -", + TestNST(""" + @"[""a""]" + """, """ + + + + + [ + + + "a" + + + ] + + + + + + """, @"", @""); } @@ -5794,22 +7272,26 @@ public void y_array_ending_with_newline_json() [Fact] public void y_array_false_json() { - TestNST(@"@""[false]""", @" - - - - [ - - - false - - - ] - - - - -", + TestNST(""" + @"[false]" + """, """ + + + + + [ + + + false + + + ] + + + + + + """, @"", @""); } @@ -5817,42 +7299,46 @@ public void y_array_false_json() [Fact] public void y_array_heterogeneous_json() { - TestNST(@"@""[null, 1, """"1"""", {}]""", @" - - - - [ - - - null - - - , - - - 1 - - - , - - - ""1"" - - - , - - - { - - } - - - ] - - - - -", + TestNST(""" + @"[null, 1, ""1"", {}]" + """, """ + + + + + [ + + + null + + + , + + + 1 + + + , + + + "1" + + + , + + + { + + } + + + ] + + + + + + """, @"", @""); } @@ -5860,22 +7346,26 @@ public void y_array_heterogeneous_json() [Fact] public void y_array_null_json() { - TestNST(@"@""[null]""", @" - - - - [ - - - null - - - ] - - - - -", + TestNST(""" + @"[null]" + """, """ + + + + + [ + + + null + + + ] + + + + + + """, @"", @""); } @@ -5883,24 +7373,28 @@ public void y_array_null_json() [Fact] public void y_array_with_1_and_newline_json() { - TestNST(@"@""[1 -]""", @" - - - - [ - - - 1 - - - - ] - - - - -", + TestNST(""" + @"[1 + ]" + """, """ + + + + + [ + + + 1 + + + + ] + + + + + + """, @"", @""); } @@ -5908,25 +7402,29 @@ public void y_array_with_1_and_newline_json() [Fact] public void y_array_with_leading_space_json() { - TestNST(@"@"" [1]""", @" - - - - - - - [ - - - 1 - - - ] - - - - -", + TestNST(""" + @" [1]" + """, """ + + + + + + + + [ + + + 1 + + + ] + + + + + + """, @"", @""); } @@ -5934,46 +7432,50 @@ public void y_array_with_leading_space_json() [Fact] public void y_array_with_several_null_json() { - TestNST(@"@""[1,null,null,null,2]""", @" - - - - [ - - - 1 - - - , - - - null - - - , - - - null - - - , - - - null - - - , - - - 2 - - - ] - - - - -", + TestNST(""" + @"[1,null,null,null,2]" + """, """ + + + + + [ + + + 1 + + + , + + + null + + + , + + + null + + + , + + + null + + + , + + + 2 + + + ] + + + + + + """, @"", @""); } @@ -5981,22 +7483,26 @@ public void y_array_with_several_null_json() [Fact] public void y_array_with_trailing_space_json() { - TestNST(@"@""[2] """, @" - - - - [ - - - 2 - - - ] - - - - -", + TestNST(""" + @"[2] " + """, """ + + + + + [ + + + 2 + + + ] + + + + + + """, @"", @""); } @@ -6004,22 +7510,26 @@ public void y_array_with_trailing_space_json() [Fact] public void y_number_json() { - TestNST(@"@""[123e65]""", @" - - - - [ - - - 123e65 - - - ] - - - - -", + TestNST(""" + @"[123e65]" + """, """ + + + + + [ + + + 123e65 + + + ] + + + + + + """, @"", @""); } @@ -6027,22 +7537,26 @@ public void y_number_json() [Fact] public void y_number_0e_1_json() { - TestNST(@"@""[0e+1]""", @" - - - - [ - - - 0e+1 - - - ] - - - - -", + TestNST(""" + @"[0e+1]" + """, """ + + + + + [ + + + 0e+1 + + + ] + + + + + + """, @"", @""); } @@ -6050,22 +7564,26 @@ public void y_number_0e_1_json() [Fact] public void y_number_0e1_json() { - TestNST(@"@""[0e1]""", @" - - - - [ - - - 0e1 - - - ] - - - - -", + TestNST(""" + @"[0e1]" + """, """ + + + + + [ + + + 0e1 + + + ] + + + + + + """, @"", @""); } @@ -6073,22 +7591,26 @@ public void y_number_0e1_json() [Fact] public void y_number_after_space_json() { - TestNST(@"@""[ 4]""", @" - - - - [ - - - 4 - - - ] - - - - -", + TestNST(""" + @"[ 4]" + """, """ + + + + + [ + + + 4 + + + ] + + + + + + """, @"", @""); } @@ -6096,24 +7618,28 @@ public void y_number_after_space_json() [Fact] public void y_number_double_close_to_zero_json() { - TestNST(@"@""[-0.000000000000000000000000000000000000000000000000000000000000000000000000000001] -""", @" - - - - [ - - - -0.000000000000000000000000000000000000000000000000000000000000000000000000000001 - - - ] - - - - - -", + TestNST(""" + @"[-0.000000000000000000000000000000000000000000000000000000000000000000000000000001] + " + """, """ + + + + + [ + + + -0.000000000000000000000000000000000000000000000000000000000000000000000000000001 + + + ] + + + + + + + """, @"", @""); } @@ -6121,22 +7647,26 @@ public void y_number_double_close_to_zero_json() [Fact] public void y_number_int_with_exp_json() { - TestNST(@"@""[20e1]""", @" - - - - [ - - - 20e1 - - - ] - - - - -", + TestNST(""" + @"[20e1]" + """, """ + + + + + [ + + + 20e1 + + + ] + + + + + + """, @"", @""); } @@ -6144,22 +7674,26 @@ public void y_number_int_with_exp_json() [Fact] public void y_number_minus_zero_json() { - TestNST(@"@""[-0]""", @" - - - - [ - - - -0 - - - ] - - - - -", + TestNST(""" + @"[-0]" + """, """ + + + + + [ + + + -0 + + + ] + + + + + + """, @"", @""); } @@ -6167,22 +7701,26 @@ public void y_number_minus_zero_json() [Fact] public void y_number_negative_int_json() { - TestNST(@"@""[-123]""", @" - - - - [ - - - -123 - - - ] - - - - -", + TestNST(""" + @"[-123]" + """, """ + + + + + [ + + + -123 + + + ] + + + + + + """, @"", @""); } @@ -6190,22 +7728,26 @@ public void y_number_negative_int_json() [Fact] public void y_number_negative_one_json() { - TestNST(@"@""[-1]""", @" - - - - [ - - - -1 - - - ] - - - - -", + TestNST(""" + @"[-1]" + """, """ + + + + + [ + + + -1 + + + ] + + + + + + """, @"", @""); } @@ -6213,22 +7755,26 @@ public void y_number_negative_one_json() [Fact] public void y_number_negative_zero_json() { - TestNST(@"@""[-0]""", @" - - - - [ - - - -0 - - - ] - - - - -", + TestNST(""" + @"[-0]" + """, """ + + + + + [ + + + -0 + + + ] + + + + + + """, @"", @""); } @@ -6236,22 +7782,26 @@ public void y_number_negative_zero_json() [Fact] public void y_number_real_capital_e_json() { - TestNST(@"@""[1E22]""", @" - - - - [ - - - 1E22 - - - ] - - - - -", + TestNST(""" + @"[1E22]" + """, """ + + + + + [ + + + 1E22 + + + ] + + + + + + """, @"", @""); } @@ -6259,22 +7809,26 @@ public void y_number_real_capital_e_json() [Fact] public void y_number_real_capital_e_neg_exp_json() { - TestNST(@"@""[1E-2]""", @" - - - - [ - - - 1E-2 - - - ] - - - - -", + TestNST(""" + @"[1E-2]" + """, """ + + + + + [ + + + 1E-2 + + + ] + + + + + + """, @"", @""); } @@ -6282,22 +7836,26 @@ public void y_number_real_capital_e_neg_exp_json() [Fact] public void y_number_real_capital_e_pos_exp_json() { - TestNST(@"@""[1E+2]""", @" - - - - [ - - - 1E+2 - - - ] - - - - -", + TestNST(""" + @"[1E+2]" + """, """ + + + + + [ + + + 1E+2 + + + ] + + + + + + """, @"", @""); } @@ -6305,22 +7863,26 @@ public void y_number_real_capital_e_pos_exp_json() [Fact] public void y_number_real_exponent_json() { - TestNST(@"@""[123e45]""", @" - - - - [ - - - 123e45 - - - ] - - - - -", + TestNST(""" + @"[123e45]" + """, """ + + + + + [ + + + 123e45 + + + ] + + + + + + """, @"", @""); } @@ -6328,22 +7890,26 @@ public void y_number_real_exponent_json() [Fact] public void y_number_real_fraction_exponent_json() { - TestNST(@"@""[123.456e78]""", @" - - - - [ - - - 123.456e78 - - - ] - - - - -", + TestNST(""" + @"[123.456e78]" + """, """ + + + + + [ + + + 123.456e78 + + + ] + + + + + + """, @"", @""); } @@ -6351,22 +7917,26 @@ public void y_number_real_fraction_exponent_json() [Fact] public void y_number_real_neg_exp_json() { - TestNST(@"@""[1e-2]""", @" - - - - [ - - - 1e-2 - - - ] - - - - -", + TestNST(""" + @"[1e-2]" + """, """ + + + + + [ + + + 1e-2 + + + ] + + + + + + """, @"", @""); } @@ -6374,22 +7944,26 @@ public void y_number_real_neg_exp_json() [Fact] public void y_number_real_pos_exponent_json() { - TestNST(@"@""[1e+2]""", @" - - - - [ - - - 1e+2 - - - ] - - - - -", + TestNST(""" + @"[1e+2]" + """, """ + + + + + [ + + + 1e+2 + + + ] + + + + + + """, @"", @""); } @@ -6397,22 +7971,26 @@ public void y_number_real_pos_exponent_json() [Fact] public void y_number_simple_int_json() { - TestNST(@"@""[123]""", @" - - - - [ - - - 123 - - - ] - - - - -", + TestNST(""" + @"[123]" + """, """ + + + + + [ + + + 123 + + + ] + + + + + + """, @"", @""); } @@ -6420,22 +7998,26 @@ public void y_number_simple_int_json() [Fact] public void y_number_simple_real_json() { - TestNST(@"@""[123.456789]""", @" - - - - [ - - - 123.456789 - - - ] - - - - -", + TestNST(""" + @"[123.456789]" + """, """ + + + + + [ + + + 123.456789 + + + ] + + + + + + """, @"", @""); } @@ -6443,34 +8025,38 @@ public void y_number_simple_real_json() [Fact] public void y_object_json() { - TestNST(@"@""{""""asd"""":""""sdf"""", """"dfg"""":""""fgh""""}""", @" - - - - { - - - ""asd"" - : - - ""sdf"" - - - , - - ""dfg"" - : - - ""fgh"" - - - - } - - - - -", + TestNST(""" + @"{""asd"":""sdf"", ""dfg"":""fgh""}" + """, """ + + + + + { + + + "asd" + : + + "sdf" + + + , + + "dfg" + : + + "fgh" + + + + } + + + + + + """, @"", @""); } @@ -6478,26 +8064,30 @@ public void y_object_json() [Fact] public void y_object_basic_json() { - TestNST(@"@""{""""asd"""":""""sdf""""}""", @" - - - - { - - - ""asd"" - : - - ""sdf"" - - - - } - - - - -", + TestNST(""" + @"{""asd"":""sdf""}" + """, """ + + + + + { + + + "asd" + : + + "sdf" + + + + } + + + + + + """, @"", @""); } @@ -6505,34 +8095,38 @@ public void y_object_basic_json() [Fact] public void y_object_duplicated_key_json() { - TestNST(@"@""{""""a"""":""""b"""",""""a"""":""""c""""}""", @" - - - - { - - - ""a"" - : - - ""b"" - - - , - - ""a"" - : - - ""c"" - - - - } - - - - -", + TestNST(""" + @"{""a"":""b"",""a"":""c""}" + """, """ + + + + + { + + + "a" + : + + "b" + + + , + + "a" + : + + "c" + + + + } + + + + + + """, @"", @""); } @@ -6540,34 +8134,38 @@ public void y_object_duplicated_key_json() [Fact] public void y_object_duplicated_key_and_value_json() { - TestNST(@"@""{""""a"""":""""b"""",""""a"""":""""b""""}""", @" - - - - { - - - ""a"" - : - - ""b"" - - - , - - ""a"" - : - - ""b"" - - - - } - - - - -", + TestNST(""" + @"{""a"":""b"",""a"":""b""}" + """, """ + + + + + { + + + "a" + : + + "b" + + + , + + "a" + : + + "b" + + + + } + + + + + + """, @"", @""); } @@ -6575,18 +8173,22 @@ public void y_object_duplicated_key_and_value_json() [Fact] public void y_object_empty_json() { - TestNST(@"@""{}""", @" - - - - { - - } - - - - -", + TestNST(""" + @"{}" + """, """ + + + + + { + + } + + + + + + """, @"", @""); } @@ -6594,26 +8196,30 @@ public void y_object_empty_json() [Fact] public void y_object_empty_key_json() { - TestNST(@"@""{"""""""":0}""", @" - - - - { - - - """" - : - - 0 - - - - } - - - - -", + TestNST(""""" + @"{"""":0}" + """"", """ + + + + + { + + + "" + : + + 0 + + + + } + + + + + + """, @"", @""); } @@ -6621,26 +8227,30 @@ public void y_object_empty_key_json() [Fact] public void y_object_escaped_null_in_key_json() { - TestNST(@"@""{""""foo\u0000bar"""": 42}""", @" - - - - { - - - ""foo\u0000bar"" - : - - 42 - - - - } - - - - -", + TestNST(""" + @"{""foo\u0000bar"": 42}" + """, """ + + + + + { + + + "foo\u0000bar" + : + + 42 + + + + } + + + + + + """, @"", @""); } @@ -6648,34 +8258,38 @@ public void y_object_escaped_null_in_key_json() [Fact] public void y_object_extreme_numbers_json() { - TestNST(@"@""{ """"min"""": -1.0e+28, """"max"""": 1.0e+28 }""", @" - - - - { - - - ""min"" - : - - -1.0e+28 - - - , - - ""max"" - : - - 1.0e+28 - - - - } - - - - -", + TestNST(""" + @"{ ""min"": -1.0e+28, ""max"": 1.0e+28 }" + """, """ + + + + + { + + + "min" + : + + -1.0e+28 + + + , + + "max" + : + + 1.0e+28 + + + + } + + + + + + """, @"", @""); } @@ -6683,51 +8297,55 @@ public void y_object_extreme_numbers_json() [Fact] public void y_object_long_strings_json() { - TestNST(@"@""{""""x"""":[{""""id"""": """"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx""""}], """"id"""": """"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx""""}""", - @" - - - - { - - - ""x"" - : - - [ - - - { - - - ""id"" - : - - ""xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"" - - - - } - - - ] - - - , - - ""id"" - : - - ""xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"" - - - - } - - - - -", + TestNST(""" + @"{""x"":[{""id"": ""xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx""}], ""id"": ""xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx""}" + """, + """ + + + + + { + + + "x" + : + + [ + + + { + + + "id" + : + + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + + + + } + + + ] + + + , + + "id" + : + + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + + + + } + + + + + + """, @"", @""); } @@ -6735,28 +8353,32 @@ public void y_object_long_strings_json() [Fact] public void y_object_simple_json() { - TestNST(@"@""{""""a"""":[]}""", @" - - - - { - - - ""a"" - : - - [ - - ] - - - - } - - - - -", + TestNST(""" + @"{""a"":[]}" + """, """ + + + + + { + + + "a" + : + + [ + + ] + + + + } + + + + + + """, @"", @""); } @@ -6764,26 +8386,30 @@ public void y_object_simple_json() [Fact] public void y_object_string_unicode_json() { - TestNST(@"@""{""""title"""":""""\u041f\u043e\u043b\u0442\u043e\u0440\u0430 \u0417\u0435\u043c\u043b\u0435\u043a\u043e\u043f\u0430"""" }""", @" - - - - { - - - ""title"" - : - - ""\u041f\u043e\u043b\u0442\u043e\u0440\u0430 \u0417\u0435\u043c\u043b\u0435\u043a\u043e\u043f\u0430"" - - - - } - - - - -", + TestNST(""" + @"{""title"":""\u041f\u043e\u043b\u0442\u043e\u0440\u0430 \u0417\u0435\u043c\u043b\u0435\u043a\u043e\u043f\u0430"" }" + """, """ + + + + + { + + + "title" + : + + "\u041f\u043e\u043b\u0442\u043e\u0440\u0430 \u0417\u0435\u043c\u043b\u0435\u043a\u043e\u043f\u0430" + + + + } + + + + + + """, @"", @""); } @@ -6791,30 +8417,34 @@ public void y_object_string_unicode_json() [Fact] public void y_object_with_newlines_json() { - TestNST(@"@""{ -""""a"""": """"b"""" -}""", @" - - - - { - - - - ""a"" - : - - ""b"" - - - - - } - - - - -", + TestNST(""" + @"{ + ""a"": ""b"" + }" + """, """ + + + + + { + + + + "a" + : + + "b" + + + + + } + + + + + + """, @"", @""); } @@ -6822,22 +8452,26 @@ public void y_object_with_newlines_json() [Fact] public void y_string_1_2_3_bytes_UTF_8_sequences_json() { - TestNST(@"@""[""""\u0060\u012a\u12AB""""]""", @" - - - - [ - - - ""\u0060\u012a\u12AB"" - - - ] - - - - -", + TestNST(""" + @"[""\u0060\u012a\u12AB""]" + """, """ + + + + + [ + + + "\u0060\u012a\u12AB" + + + ] + + + + + + """, @"", @""); } @@ -6845,22 +8479,26 @@ public void y_string_1_2_3_bytes_UTF_8_sequences_json() [Fact] public void y_string_accepted_surrogate_pair_json() { - TestNST(@"@""[""""\uD801\udc37""""]""", @" - - - - [ - - - ""\uD801\udc37"" - - - ] - - - - -", + TestNST(""" + @"[""\uD801\udc37""]" + """, """ + + + + + [ + + + "\uD801\udc37" + + + ] + + + + + + """, @"", @""); } @@ -6868,22 +8506,26 @@ public void y_string_accepted_surrogate_pair_json() [Fact] public void y_string_accepted_surrogate_pairs_json() { - TestNST(@"@""[""""\ud83d\ude39\ud83d\udc8d""""]""", @" - - - - [ - - - ""\ud83d\ude39\ud83d\udc8d"" - - - ] - - - - -", + TestNST(""" + @"[""\ud83d\ude39\ud83d\udc8d""]" + """, """ + + + + + [ + + + "\ud83d\ude39\ud83d\udc8d" + + + ] + + + + + + """, @"", @""); } @@ -6891,22 +8533,26 @@ public void y_string_accepted_surrogate_pairs_json() [Fact] public void y_string_allowed_escapes_json() { - TestNST(@"@""[""""\""""\\\/\b\f\n\r\t""""]""", @" - - - - [ - - - ""\""\\\/\b\f\n\r\t"" - - - ] - - - - -", + TestNST(""" + @"[""\""\\\/\b\f\n\r\t""]" + """, """ + + + + + [ + + + "\"\\\/\b\f\n\r\t" + + + ] + + + + + + """, @"", @""); } @@ -6914,22 +8560,26 @@ public void y_string_allowed_escapes_json() [Fact] public void y_string_backslash_and_u_escaped_zero_json() { - TestNST(@"@""[""""\\u0000""""]""", @" - - - - [ - - - ""\\u0000"" - - - ] - - - - -", + TestNST(""" + @"[""\\u0000""]" + """, """ + + + + + [ + + + "\\u0000" + + + ] + + + + + + """, @"", @""); } @@ -6937,22 +8587,26 @@ public void y_string_backslash_and_u_escaped_zero_json() [Fact] public void y_string_backslash_doublequotes_json() { - TestNST(@"@""[""""\""""""""]""", @" - - - - [ - - - ""\"""" - - - ] - - - - -", + TestNST(""""" + @"[""\""""]" + """"", """ + + + + + [ + + + "\"" + + + ] + + + + + + """, @"", @""); } @@ -6960,22 +8614,26 @@ public void y_string_backslash_doublequotes_json() [Fact] public void y_string_comments_json() { - TestNST(@"@""[""""a/*b*/c/*d//e""""]""", @" - - - - [ - - - ""a/*b*/c/*d//e"" - - - ] - - - - -", + TestNST(""" + @"[""a/*b*/c/*d//e""]" + """, """ + + + + + [ + + + "a/*b*/c/*d//e" + + + ] + + + + + + """, @"", @""); } @@ -6983,22 +8641,26 @@ public void y_string_comments_json() [Fact] public void y_string_double_escape_a_json() { - TestNST(@"@""[""""\\a""""]""", @" - - - - [ - - - ""\\a"" - - - ] - - - - -", + TestNST(""" + @"[""\\a""]" + """, """ + + + + + [ + + + "\\a" + + + ] + + + + + + """, @"", @""); } @@ -7006,22 +8668,26 @@ public void y_string_double_escape_a_json() [Fact] public void y_string_double_escape_n_json() { - TestNST(@"@""[""""\\n""""]""", @" - - - - [ - - - ""\\n"" - - - ] - - - - -", + TestNST(""" + @"[""\\n""]" + """, """ + + + + + [ + + + "\\n" + + + ] + + + + + + """, @"", @""); } @@ -7029,22 +8695,26 @@ public void y_string_double_escape_n_json() [Fact] public void y_string_escaped_control_character_json() { - TestNST(@"@""[""""\u0012""""]""", @" - - - - [ - - - ""\u0012"" - - - ] - - - - -", + TestNST(""" + @"[""\u0012""]" + """, """ + + + + + [ + + + "\u0012" + + + ] + + + + + + """, @"", @""); } @@ -7052,22 +8722,26 @@ public void y_string_escaped_control_character_json() [Fact] public void y_string_escaped_noncharacter_json() { - TestNST(@"@""[""""\uFFFF""""]""", @" - - - - [ - - - ""\uFFFF"" - - - ] - - - - -", + TestNST(""" + @"[""\uFFFF""]" + """, """ + + + + + [ + + + "\uFFFF" + + + ] + + + + + + """, @"", @""); } @@ -7075,22 +8749,26 @@ public void y_string_escaped_noncharacter_json() [Fact] public void y_string_in_array_json() { - TestNST(@"@""[""""asd""""]""", @" - - - - [ - - - ""asd"" - - - ] - - - - -", + TestNST(""" + @"[""asd""]" + """, """ + + + + + [ + + + "asd" + + + ] + + + + + + """, @"", @""); } @@ -7098,22 +8776,26 @@ public void y_string_in_array_json() [Fact] public void y_string_in_array_with_leading_space_json() { - TestNST(@"@""[ """"asd""""]""", @" - - - - [ - - - ""asd"" - - - ] - - - - -", + TestNST(""" + @"[ ""asd""]" + """, """ + + + + + [ + + + "asd" + + + ] + + + + + + """, @"", @""); } @@ -7121,22 +8803,26 @@ public void y_string_in_array_with_leading_space_json() [Fact] public void y_string_last_surrogates_1_and_2_json() { - TestNST(@"@""[""""\uDBFF\uDFFF""""]""", @" - - - - [ - - - ""\uDBFF\uDFFF"" - - - ] - - - - -", + TestNST(""" + @"[""\uDBFF\uDFFF""]" + """, """ + + + + + [ + + + "\uDBFF\uDFFF" + + + ] + + + + + + """, @"", @""); } @@ -7144,22 +8830,26 @@ public void y_string_last_surrogates_1_and_2_json() [Fact] public void y_string_nbsp_uescaped_json() { - TestNST(@"@""[""""new\u00A0line""""]""", @" - - - - [ - - - ""new\u00A0line"" - - - ] - - - - -", + TestNST(""" + @"[""new\u00A0line""]" + """, """ + + + + + [ + + + "new\u00A0line" + + + ] + + + + + + """, @"", @""); } @@ -7167,22 +8857,26 @@ public void y_string_nbsp_uescaped_json() [Fact] public void y_string_nonCharacterInUTF_8_U_10FFFF_json() { - TestNST(@"@""[""""􏿿""""]""", @" - - - - [ - - - ""􏿿"" - - - ] - - - - -", + TestNST(""" + @"[""􏿿""]" + """, """ + + + + + [ + + + "􏿿" + + + ] + + + + + + """, @"", @""); } @@ -7190,22 +8884,26 @@ public void y_string_nonCharacterInUTF_8_U_10FFFF_json() [Fact] public void y_string_null_escape_json() { - TestNST(@"@""[""""\u0000""""]""", @" - - - - [ - - - ""\u0000"" - - - ] - - - - -", + TestNST(""" + @"[""\u0000""]" + """, """ + + + + + [ + + + "\u0000" + + + ] + + + + + + """, @"", @""); } @@ -7213,22 +8911,26 @@ public void y_string_null_escape_json() [Fact] public void y_string_one_byte_utf_8_json() { - TestNST(@"@""[""""\u002c""""]""", @" - - - - [ - - - ""\u002c"" - - - ] - - - - -", + TestNST(""" + @"[""\u002c""]" + """, """ + + + + + [ + + + "\u002c" + + + ] + + + + + + """, @"", @""); } @@ -7236,22 +8938,26 @@ public void y_string_one_byte_utf_8_json() [Fact] public void y_string_pi_json() { - TestNST(@"@""[""""π""""]""", @" - - - - [ - - - ""π"" - - - ] - - - - -", + TestNST(""" + @"[""π""]" + """, """ + + + + + [ + + + "π" + + + ] + + + + + + """, @"", @""); } @@ -7259,22 +8965,26 @@ public void y_string_pi_json() [Fact] public void y_string_reservedCharacterInUTF_8_U_1BFFF_json() { - TestNST(@"@""[""""𛿿""""]""", @" - - - - [ - - - ""𛿿"" - - - ] - - - - -", + TestNST(""" + @"[""𛿿""]" + """, """ + + + + + [ + + + "𛿿" + + + ] + + + + + + """, @"", @""); } @@ -7282,22 +8992,26 @@ public void y_string_reservedCharacterInUTF_8_U_1BFFF_json() [Fact] public void y_string_simple_ascii_json() { - TestNST(@"@""[""""asd """"]""", @" - - - - [ - - - ""asd "" - - - ] - - - - -", + TestNST(""" + @"[""asd ""]" + """, """ + + + + + [ + + + "asd " + + + ] + + + + + + """, @"", @""); } @@ -7305,16 +9019,20 @@ public void y_string_simple_ascii_json() [Fact] public void y_string_space_json() { - TestNST(@"@"""""" """"""", @" - - - - "" "" - - - - -", + TestNST("""" + @""" """ + """", """ + + + + + " " + + + + + + """, @"", @""); } @@ -7322,22 +9040,26 @@ public void y_string_space_json() [Fact] public void y_string_surrogates_U_1D11E_MUSICAL_SYMBOL_G_CLEF_json() { - TestNST(@"@""[""""\uD834\uDd1e""""]""", @" - - - - [ - - - ""\uD834\uDd1e"" - - - ] - - - - -", + TestNST(""" + @"[""\uD834\uDd1e""]" + """, """ + + + + + [ + + + "\uD834\uDd1e" + + + ] + + + + + + """, @"", @""); } @@ -7345,22 +9067,26 @@ public void y_string_surrogates_U_1D11E_MUSICAL_SYMBOL_G_CLEF_json() [Fact] public void y_string_three_byte_utf_8_json() { - TestNST(@"@""[""""\u0821""""]""", @" - - - - [ - - - ""\u0821"" - - - ] - - - - -", + TestNST(""" + @"[""\u0821""]" + """, """ + + + + + [ + + + "\u0821" + + + ] + + + + + + """, @"", @""); } @@ -7368,22 +9094,26 @@ public void y_string_three_byte_utf_8_json() [Fact] public void y_string_two_byte_utf_8_json() { - TestNST(@"@""[""""\u0123""""]""", @" - - - - [ - - - ""\u0123"" - - - ] - - - - -", + TestNST(""" + @"[""\u0123""]" + """, """ + + + + + [ + + + "\u0123" + + + ] + + + + + + """, @"", @""); } @@ -7391,22 +9121,26 @@ public void y_string_two_byte_utf_8_json() [Fact] public void y_string_u_2028_line_sep_json() { - TestNST(@"@""[""""
""""]""", @" - - - - [ - - - ""
"" - - - ] - - - - -", + TestNST(""" + @"[""
 ""]" + """, """ + + + + + [ + + + "
 " + + + ] + + + + + + """, @"", @""); } @@ -7414,22 +9148,26 @@ public void y_string_u_2028_line_sep_json() [Fact] public void y_string_u_2029_par_sep_json() { - TestNST(@"@""[""""
""""]""", @" - - - - [ - - - ""
"" - - - ] - - - - -", + TestNST(""" + @"[""
 ""]" + """, """ + + + + + [ + + + "
 " + + + ] + + + + + + """, @"", @""); } @@ -7437,22 +9175,26 @@ public void y_string_u_2029_par_sep_json() [Fact] public void y_string_uEscape_json() { - TestNST(@"@""[""""\u0061\u30af\u30EA\u30b9""""]""", @" - - - - [ - - - ""\u0061\u30af\u30EA\u30b9"" - - - ] - - - - -", + TestNST(""" + @"[""\u0061\u30af\u30EA\u30b9""]" + """, """ + + + + + [ + + + "\u0061\u30af\u30EA\u30b9" + + + ] + + + + + + """, @"", @""); } @@ -7460,22 +9202,26 @@ public void y_string_uEscape_json() [Fact] public void y_string_uescaped_newline_json() { - TestNST(@"@""[""""new\u000Aline""""]""", @" - - - - [ - - - ""new\u000Aline"" - - - ] - - - - -", + TestNST(""" + @"[""new\u000Aline""]" + """, """ + + + + + [ + + + "new\u000Aline" + + + ] + + + + + + """, @"", @""); } @@ -7483,22 +9229,26 @@ public void y_string_uescaped_newline_json() [Fact] public void y_string_unescaped_char_delete_json() { - TestNST(@"@""[""""""""]""", @" - - - - [ - - - """" - - - ] - - - - -", + TestNST(""" + @"[""""]" + """, """ + + + + + [ + + + "" + + + ] + + + + + + """, @"", @""); } @@ -7506,22 +9256,26 @@ public void y_string_unescaped_char_delete_json() [Fact] public void y_string_unicode_json() { - TestNST(@"@""[""""\uA66D""""]""", @" - - - - [ - - - ""\uA66D"" - - - ] - - - - -", + TestNST(""" + @"[""\uA66D""]" + """, """ + + + + + [ + + + "\uA66D" + + + ] + + + + + + """, @"", @""); } @@ -7529,22 +9283,26 @@ public void y_string_unicode_json() [Fact] public void y_string_unicodeEscapedBackslash_json() { - TestNST(@"@""[""""\u005C""""]""", @" - - - - [ - - - ""\u005C"" - - - ] - - - - -", + TestNST(""" + @"[""\u005C""]" + """, """ + + + + + [ + + + "\u005C" + + + ] + + + + + + """, @"", @""); } @@ -7552,22 +9310,26 @@ public void y_string_unicodeEscapedBackslash_json() [Fact] public void y_string_unicode_2_json() { - TestNST(@"@""[""""⍂㈴⍂""""]""", @" - - - - [ - - - ""⍂㈴⍂"" - - - ] - - - - -", + TestNST(""" + @"[""⍂㈴⍂""]" + """, """ + + + + + [ + + + "⍂㈴⍂" + + + ] + + + + + + """, @"", @""); } @@ -7575,22 +9337,26 @@ public void y_string_unicode_2_json() [Fact] public void y_string_unicode_escaped_double_quote_json() { - TestNST(@"@""[""""\u0022""""]""", @" - - - - [ - - - ""\u0022"" - - - ] - - - - -", + TestNST(""" + @"[""\u0022""]" + """, """ + + + + + [ + + + "\u0022" + + + ] + + + + + + """, @"", @""); } @@ -7598,22 +9364,26 @@ public void y_string_unicode_escaped_double_quote_json() [Fact] public void y_string_unicode_U_10FFFE_nonchar_json() { - TestNST(@"@""[""""\uDBFF\uDFFE""""]""", @" - - - - [ - - - ""\uDBFF\uDFFE"" - - - ] - - - - -", + TestNST(""" + @"[""\uDBFF\uDFFE""]" + """, """ + + + + + [ + + + "\uDBFF\uDFFE" + + + ] + + + + + + """, @"", @""); } @@ -7621,22 +9391,26 @@ public void y_string_unicode_U_10FFFE_nonchar_json() [Fact] public void y_string_unicode_U_1FFFE_nonchar_json() { - TestNST(@"@""[""""\uD83F\uDFFE""""]""", @" - - - - [ - - - ""\uD83F\uDFFE"" - - - ] - - - - -", + TestNST(""" + @"[""\uD83F\uDFFE""]" + """, """ + + + + + [ + + + "\uD83F\uDFFE" + + + ] + + + + + + """, @"", @""); } @@ -7644,22 +9418,26 @@ public void y_string_unicode_U_1FFFE_nonchar_json() [Fact] public void y_string_unicode_U_200B_ZERO_WIDTH_SPACE_json() { - TestNST(@"@""[""""\u200B""""]""", @" - - - - [ - - - ""\u200B"" - - - ] - - - - -", + TestNST(""" + @"[""\u200B""]" + """, """ + + + + + [ + + + "\u200B" + + + ] + + + + + + """, @"", @""); } @@ -7667,22 +9445,26 @@ public void y_string_unicode_U_200B_ZERO_WIDTH_SPACE_json() [Fact] public void y_string_unicode_U_2064_invisible_plus_json() { - TestNST(@"@""[""""\u2064""""]""", @" - - - - [ - - - ""\u2064"" - - - ] - - - - -", + TestNST(""" + @"[""\u2064""]" + """, """ + + + + + [ + + + "\u2064" + + + ] + + + + + + """, @"", @""); } @@ -7690,22 +9472,26 @@ public void y_string_unicode_U_2064_invisible_plus_json() [Fact] public void y_string_unicode_U_FDD0_nonchar_json() { - TestNST(@"@""[""""\uFDD0""""]""", @" - - - - [ - - - ""\uFDD0"" - - - ] - - - - -", + TestNST(""" + @"[""\uFDD0""]" + """, """ + + + + + [ + + + "\uFDD0" + + + ] + + + + + + """, @"", @""); } @@ -7713,22 +9499,26 @@ public void y_string_unicode_U_FDD0_nonchar_json() [Fact] public void y_string_unicode_U_FFFE_nonchar_json() { - TestNST(@"@""[""""\uFFFE""""]""", @" - - - - [ - - - ""\uFFFE"" - - - ] - - - - -", + TestNST(""" + @"[""\uFFFE""]" + """, """ + + + + + [ + + + "\uFFFE" + + + ] + + + + + + """, @"", @""); } @@ -7736,22 +9526,26 @@ public void y_string_unicode_U_FFFE_nonchar_json() [Fact] public void y_string_utf8_json() { - TestNST(@"@""[""""€𝄞""""]""", @" - - - - [ - - - ""€𝄞"" - - - ] - - - - -", + TestNST(""" + @"[""€𝄞""]" + """, """ + + + + + [ + + + "€𝄞" + + + ] + + + + + + """, @"", @""); } @@ -7759,22 +9553,26 @@ public void y_string_utf8_json() [Fact] public void y_string_with_del_character_json() { - TestNST(@"@""[""""aa""""]""", @" - - - - [ - - - ""aa"" - - - ] - - - - -", + TestNST(""" + @"[""aa""]" + """, """ + + + + + [ + + + "aa" + + + ] + + + + + + """, @"", @""); } @@ -7782,16 +9580,20 @@ public void y_string_with_del_character_json() [Fact] public void y_structure_lonely_false_json() { - TestNST(@"@""false""", @" - - - - false - - - - -", + TestNST(""" + @"false" + """, """ + + + + + false + + + + + + """, @"", @""); } @@ -7799,16 +9601,20 @@ public void y_structure_lonely_false_json() [Fact] public void y_structure_lonely_int_json() { - TestNST(@"@""42""", @" - - - - 42 - - - - -", + TestNST(""" + @"42" + """, """ + + + + + 42 + + + + + + """, @"", @""); } @@ -7816,16 +9622,20 @@ public void y_structure_lonely_int_json() [Fact] public void y_structure_lonely_negative_real_json() { - TestNST(@"@""-0.1""", @" - - - - -0.1 - - - - -", + TestNST(""" + @"-0.1" + """, """ + + + + + -0.1 + + + + + + """, @"", @""); } @@ -7833,16 +9643,20 @@ public void y_structure_lonely_negative_real_json() [Fact] public void y_structure_lonely_null_json() { - TestNST(@"@""null""", @" - - - - null - - - - -", + TestNST(""" + @"null" + """, """ + + + + + null + + + + + + """, @"", @""); } @@ -7850,16 +9664,20 @@ public void y_structure_lonely_null_json() [Fact] public void y_structure_lonely_string_json() { - TestNST(@"@""""""asd""""""", @" - - - - ""asd"" - - - - -", + TestNST("""" + @"""asd""" + """", """ + + + + + "asd" + + + + + + """, @"", @""); } @@ -7867,16 +9685,20 @@ public void y_structure_lonely_string_json() [Fact] public void y_structure_lonely_true_json() { - TestNST(@"@""true""", @" - - - - true - - - - -", + TestNST(""" + @"true" + """, """ + + + + + true + + + + + + """, @"", @""); } @@ -7884,16 +9706,20 @@ public void y_structure_lonely_true_json() [Fact] public void y_structure_string_empty_json() { - TestNST(@"@""""""""""""", @" - - - - """" - - - - -", + TestNST(""""""" + @"""""" + """"""", """ + + + + + "" + + + + + + """, @"", @""); } @@ -7901,24 +9727,28 @@ public void y_structure_string_empty_json() [Fact] public void y_structure_trailing_newline_json() { - TestNST(@"@""[""""a""""] -""", @" - - - - [ - - - ""a"" - - - ] - - - - - -", + TestNST(""" + @"[""a""] + " + """, """ + + + + + [ + + + "a" + + + ] + + + + + + + """, @"", @""); } @@ -7926,22 +9756,26 @@ public void y_structure_trailing_newline_json() [Fact] public void y_structure_true_in_array_json() { - TestNST(@"@""[true]""", @" - - - - [ - - - true - - - ] - - - - -", + TestNST(""" + @"[true]" + """, """ + + + + + [ + + + true + + + ] + + + + + + """, @"", @""); } @@ -7949,21 +9783,25 @@ public void y_structure_true_in_array_json() [Fact] public void y_structure_whitespace_array_json() { - TestNST(@"@"" [] """, @" - - - - - - - [ - - ] - - - - -", + TestNST(""" + @" [] " + """, """ + + + + + + + + [ + + ] + + + + + + """, @"", @""); } diff --git a/src/EditorFeatures/CSharpTest2/EmbeddedLanguages/RegularExpressions/CSharpRegexParserTests.cs b/src/EditorFeatures/CSharpTest2/EmbeddedLanguages/RegularExpressions/CSharpRegexParserTests.cs index d995c4e667147..5a46271899607 100644 --- a/src/EditorFeatures/CSharpTest2/EmbeddedLanguages/RegularExpressions/CSharpRegexParserTests.cs +++ b/src/EditorFeatures/CSharpTest2/EmbeddedLanguages/RegularExpressions/CSharpRegexParserTests.cs @@ -48,7 +48,9 @@ private void Test( TryParseSubTrees(stringText, options); var actual = TreeToText(sourceText, tree) - .Replace(""", "\""); + .Replace(""", """ + " + """); AssertEx.Equal(expected, actual); } @@ -56,23 +58,37 @@ private void TryParseSubTrees(string stringText, RegexOptions options) { // Trim the input from the right and make sure tree invariants hold var current = stringText; - while (current is not "@\"\"" and not "\"\"") + while (current is not """ + @"" + """ and not """ + "" + """) { - current = current[..^2] + "\""; + current = current[..^2] + """ + " + """; TryParseTree(current, options, conversionFailureOk: true); } // Trim the input from the left and make sure tree invariants hold current = stringText; - while (current is not "@\"\"" and not "\"\"") + while (current is not """ + @"" + """ and not """ + "" + """) { if (current[0] == '@') { - current = "@\"" + current[3..]; + current = """ + @" + """ + current[3..]; } else { - current = "\"" + current[2..]; + current = """ + " + """ + current[2..]; } TryParseTree(current, options, conversionFailureOk: true); @@ -142,7 +158,11 @@ private void TryParseSubTrees(string stringText, RegexOptions options) if (!tree.Diagnostics.IsEmpty) { var expectedDiagnostics = CreateDiagnosticsElement(sourceText, tree); - Assert.False(true, "Expected diagnostics: \r\n" + expectedDiagnostics.ToString().Replace(@"""", @"""""")); + Assert.False(true, "Expected diagnostics: \r\n" + expectedDiagnostics.ToString().Replace(""" + " + """, """ + "" + """)); } Assert.True(regex.GetGroupNumbers().OrderBy(v => v).SequenceEqual( @@ -317,18 +337,20 @@ public void TestDeepRecursion() { var (token, tree, chars) = JustParseTree( -@"@""(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( -((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( -((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( -((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( -((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( -((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( -((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( -((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( -((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( -((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( -((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( -(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((""", RegexOptions.None, conversionFailureOk: false); + """ + @"(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( + ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( + ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( + ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( + ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( + ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( + ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( + ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( + ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( + ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( + ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( + (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((" + """, RegexOptions.None, conversionFailureOk: false); Assert.False(token.IsMissing); Assert.False(chars.IsDefaultOrEmpty); Assert.Null(tree); @@ -340,7 +362,9 @@ public void TestNoStackOverflow() for (var i = 1; i < 1200; i++) { var text = new string('(', i); - var (token, _, chars) = JustParseTree($@"@""{text}""", RegexOptions.None, conversionFailureOk: false); + var (token, _, chars) = JustParseTree($""" + @"{text}" + """, RegexOptions.None, conversionFailureOk: false); Assert.False(token.IsMissing); Assert.False(chars.IsDefaultOrEmpty); } diff --git a/src/EditorFeatures/CSharpTest2/EmbeddedLanguages/RegularExpressions/CSharpRegexParserTests_RealWorld.cs b/src/EditorFeatures/CSharpTest2/EmbeddedLanguages/RegularExpressions/CSharpRegexParserTests_RealWorld.cs index d9d7c293a02f1..5876eaba1ebf5 100644 --- a/src/EditorFeatures/CSharpTest2/EmbeddedLanguages/RegularExpressions/CSharpRegexParserTests_RealWorld.cs +++ b/src/EditorFeatures/CSharpTest2/EmbeddedLanguages/RegularExpressions/CSharpRegexParserTests_RealWorld.cs @@ -20,7 +20,9 @@ public void TestDeepAlternation() { // Tree is too large to convert to string and still fit within dll limits. So we just validate that // we were able to parse and get a real tree back. - var (_, tree, _) = JustParseTree(@"@""(((http|ftp|https):\/{2})+(([0-9a-z_-]+\.)+(zw|zuerich|zone|zm|zip|zero|zara|zappos|za|yun|yt|youtube|you|yokohama|yoga|yodobashi|ye|yandex|yamaxun|yahoo|yachts|xyz|xxx|xin|xfinity|xerox|xbox|wta|wtc|ws|wow|world|works|work|woodside|wolterskluwer|wme|winners|wine|windows|win|williamhill|wiki|wien|whoswho|wf|weir|wedding|wed|website|weber|webcam|weatherchannel|weather|watches|watch|wang|walter|walmart|wales|vu|voyage|voting|vote|volvo|volkswagen|vodka|vn|vlaanderen|vivo|viva|vision|visa|virgin|vip|vin|villas|viking|vig|video|vi|vg|vet|verisign|ventures|vegas|ve|vc|vanguard|vana|vacations|va|uz|uy|us|ups|uol|university|unicom|uk|ug|ubs|ubank|ua|tz|tw|tvs|tv|tunes|tui|tube|tt|trv|trust|travelersinsurance|travelers|travelchannel|travel|training|trading|trade|tr|tp|toys|toyota|town|tours|total|toshiba|toray|top|tools|tokyo|today|to|tn|tmall|tm|tl|tkmaxx|tk|tjx|tjmaxx|tj|tirol|tires|tips|tiffany|tickets|tiaa|theatre|theater|thd|th|tg|tf|teva|tennis|temasek|tel|technology|tech|team|tdk|td|tci|tc|taxi|tax|tattoo|tatar|tatamotors|target|taobao|talk|taipei|tab|sz|systems|symantec|sydney|sy|sx|swiss|swiftcover|swatch|sv|suzuki|surgery|surf|support|supply|supplies|sun|su|style|study|studio|stream|store|storage|stockholm|stcgroup|stc|statefarm|statebank|star|staples|stada|st|ss|srl|sr|spreadbetting|spot|sport|space|sony|song|solutions|solar|sohu|software|softbank|social|soccer|so|sncf|sn|smile|smart|sm|sling|sl|skype|sky|skin|ski|sk|sj|site|singles|sina|silk|si|shriram|showtime|show|shopping|shop|shoes|shia|shell|shaw|sharp|shangrila|sh|sg|sfr|sexy|sex|sew|seven|ses|services|sener|select|seek|security|secure|seat|search|se|sd|scot|scor|scjohnson|science|schwarz|school|scholarships|schmidt|schaeffler|scb|sca|sc|sbs|sbi|sb|saxo|save|sas|sap|sanofi|sandvikcoromant|sandvik|samsung|samsclub|salon|sale|sakura|safety|safe|saarland|sa|ryukyu|rwe|rw|run|ruhr|rugby|ru|rs|room|rogers|rodeo|rocks|rocher|ro|rmit|rip|rio|ril|rightathome|ricoh|richardli|rich|rexroth|reviews|review|restaurant|rest|republican|report|repair|rentals|rent|ren|reliance|reit|rehab|redumbrella|redstone|red|recipes|realty|realtor|realestate|read|re|raid|radio|racing|qvc|quest|quebec|qpon|qa|py|pwc|pw|pub|pt|ps|prudential|pru|protection|property|properties|promo|progressive|prof|productions|prod|pro|prime|press|praxi|pramerica|pr|post|porn|politie|poker|pohl|pnc|pn|pm|plus|plumbing|playstation|play|place|pl|pk|pizza|pioneer|pink|ping|pin|pid|pictures|pictet|pics|physio|photos|photography|photo|phone|philips|phd|pharmacy|ph|pg|pfizer|pf|pet|pe|pccw|pay|party|parts|partners|pars|paris|panasonic|page|pa|ovh|ott|otsuka|osaka|origins|orientexpress|organic|org|orange|oracle|open|ooo|onyourside|online|onl|ong|one|omega|om|ollo|oldnavy|olayangroup|olayan|okinawa|office|off|observer|obi|nz|nyc|nu|ntt|nrw|nra|nr|np|nowtv|nowruz|now|norton|northwesternmutual|nokia|no|nl|nissay|nissan|ninja|nikon|nike|nico|ni|nhk|ngo|ng|nfl|nf|nexus|nextdirect|next|news|newholland|new|neustar|network|netflix|netbank|net|nec|ne|nc|nba|navy|natura|nationwide|name|nagoya|nab|na|mz|my|mx|mw|mv|mutuelle|mutual|museum|mu|mtr|mtpc|mtn|mt|msd|ms|mr|mq|mp|movie|mov|motorcycles|moto|moscow|mortgage|mormon|monster|money|monash|mom|moi|mobile|mobi|mo|mn|mma|mm|mls|mlb|ml|mk|mitsubishi|mit|mint|mini|mil|microsoft|miami|mh|mg|metlife|merckmsd|menu|men|memorial|meme|melbourne|meet|media|med|me|md|mckinsey|mc|mba|mattel|maserati|marshalls|marriott|markets|marketing|market|map|mango|management|man|makeup|maif|madrid|macys|ma|ly|lv|luxury|luxe|lupin|lundbeck|lu|ltd|lt|ls|lr|lplfinancial|lpl|love|lotto|lotte|london|lol|loft|locus|locker|loans|loan|llp|llc|lk|lixil|living|live|lipsy|link|linde|lincoln|limo|limited|lilly|like|lighting|lifestyle|lifeinsurance|life|lidl|li|lgbt|lexus|lego|legal|lefrak|leclerc|lease|lds|lc|lb|lawyer|law|latrobe|latino|lat|lasalle|lanxess|landrover|land|lancia|lancaster|lamer|lamborghini|lacaixa|la|kz|kyoto|ky|kw|kuokgroup|kred|krd|kr|kpn|kpmg|kp|kosher|komatsu|koeln|kn|km|kiwi|kitchen|kindle|kim|kia|ki|kh|kg|kfh|kerryproperties|kerrylogistics|kerryhotels|ke|kddi|juniper|jprs|jpmorgan|jp|joy|jot|joburg|jobs|jo|jnj|jmp|jm|jll|jio|jewelry|jeep|je|jcp|jcb|java|jaguar|iveco|itv|itau|it|istanbul|ist|ismaili|is|irish|ir|iq|ipiranga|io|investments|intuit|international|intel|int|insure|insurance|institute|ink|ing|info|infiniti|industries|inc|in|imdb|imamat|im|il|ikano|iinet|ifm|ieee|ie|id|icu|ice|icbc|ibm|ευ|hyundai|hyatt|hughes|hu|ht|hsbc|hr|how|house|hotmail|hotels|hot|hosting|host|hospital|horse|honda|homesense|homes|homegoods|homedepot|holiday|holdings|hockey|hn|hm|hkt|hk|hiv|hitachi|hisamitsu|hiphop|hgtv|hermes|here|helsinki|help|healthcare|health|hdfcbank|hdfc|hbo|hangout|hamburg|hair|gy|gw|guru|guitars|guide|guge|gucci|guardian|gu|gt|gs|group|grocery|gripe|green|graphics|grainger|gr|gq|gp|gov|got|gop|google|goog|goodyear|goo|golf|goldpoint|gold|godaddy|gn|gmx|gmo|gmail|gm|globo|global|gle|glass|glade|gl|giving|gives|gifts|gift|gi|gh|ggee|gg|gf|george|genting|gent|gea|ge|gdn|gd|gbiz|gb|garage|garden|gap|games|game|gallup|gallo|gallery|gal|ga|fyi|furniture|fund|fun|fujixerox|fujitsu|ftr|frontier|frontdoor|frogans|frl|fresenius|free|fr|fox|foundation|forum|forsale|forex|ford|football|foodnetwork|food|foo|fo|fm|fly|flsmidth|flowers|florist|flir|flights|flickr|fk|fj|fitness|fit|fishing|fish|firmdale|firestone|fire|financial|finance|final|film|fido|fidelity|fiat|fi|ferrero|ferrari|feedback|fedex|fast|fashion|farmers|farm|fans|fan|family|faith|fairwinds|fail|fage|extraspace|express|exposed|expert|exchange|events|eus|eurovision|eu|etisalat|et|esurance|estate|esq|es|erni|ericsson|er|equipment|epson|enterprises|engineering|engineer|energy|emerck|email|eg|ee|education|edu|edeka|eco|ec|eat|earth|dz|dvr|dvag|durban|dupont|dunlop|duck|dubai|dtv|drive|download|dot|doosan|domains|dog|doctor|docs|do|dnp|dm|dk|dj|diy|dish|discover|discount|directory|direct|digital|diet|diamonds|dhl|dev|design|dentist|dental|democrat|delta|deloitte|dell|delivery|degree|deals|dealer|deal|de|dds|dclk|day|datsun|dating|date|data|dance|dad|dabur|cz|cyou|cymru|cy|cx|cw|cv|cuisinella|cu|csc|cruises|cruise|crs|crown|cricket|creditunion|creditcard|credit|cr|cpa|courses|coupons|coupon|count|corsica|coop|cool|cookingchannel|cooking|contractors|contact|consulting|construction|condos|comsec|computer|compare|company|community|commbank|comcast|com|cologne|college|coffee|codes|coach|co|cn|cm|clubmed|club|cloud|clothing|clinique|clinic|click|cleaning|claims|cl|ck|cityeats|city|citic|citi|citadel|cisco|circle|cipriani|ci|church|chrome|christmas|chintai|cheap|chat|chase|charity|channel|chanel|ch|cg|cfd|cfa|cf|cern|ceo|center|ceb|cd|cc|cbs|cbre|cbn|cba|catholic|catering|cat|casino|cash|caseih|case|cars|careers|career|care|cards|caravan|car|captainone|captain|capetown|canon|cancerresearch|camp|camera|cam|calvinklein|call|cal|cab|ca|bzh|bz|by|bw|bv|buzz|buy|business|builders|build|bugatti|budapest|bt|bs|brussels|brother|broker|broadway|bridgestone|bradesco|br|box|boutique|bot|boston|bostik|bosch|booking|book|boo|bond|bofa|boehringer|boats|bo|bnpparibas|bn|bmw|bms|bm|blue|bloomberg|blog|blockbuster|blackfriday|black|bj|biz|bio|bingo|bing|bike|bid|bible|bi|bharti|bh|bg|bf|bet|bestbuy|best|berlin|bentley|beer|beauty|beats|be|bd|bcn|bcg|bbva|bbt|bbc|bb|bayern|bauhaus|basketball|baseball|bargains|barefoot|barclays|barclaycard|barcelona|bar|bank|band|bananarepublic|banamex|baidu|baby|ba|azure|az|axa|ax|aws|aw|avianca|autos|auto|author|auspost|audio|audible|audi|auction|au|attorney|athleta|at|associates|asia|asda|as|arte|art|army|archi|aramco|arab|ar|aquarelle|aq|apple|app|apartments|aol|ao|anz|anquan|android|analytics|an|amsterdam|amica|amfam|amex|americanfamily|americanexpress|am|alstom|alsace|ally|allstate|allfinanz|alipay|alibaba|alfaromeo|al|akdn|airtel|airforce|airbus|aigo|aig|ai|agency|agakhan|ag|africa|afl|afamilycompany|af|aetna|aero|aeg|ae|adult|ads|adac|ad|actor|aco|accountants|accountant|accenture|academy|ac|abudhabi|able|abc|abbvie|abbott|abb|abarth|aarp|aaa)(:[0-9]+)?((\/([~0-9a-zA-Z\#\+\%@\.\/_-]+))?(\?[0-9a-zA-Z\+\%@\/&\[\];=_-]+)?)?))""", + var (_, tree, _) = JustParseTree(""" + @"(((http|ftp|https):\/{2})+(([0-9a-z_-]+\.)+(zw|zuerich|zone|zm|zip|zero|zara|zappos|za|yun|yt|youtube|you|yokohama|yoga|yodobashi|ye|yandex|yamaxun|yahoo|yachts|xyz|xxx|xin|xfinity|xerox|xbox|wta|wtc|ws|wow|world|works|work|woodside|wolterskluwer|wme|winners|wine|windows|win|williamhill|wiki|wien|whoswho|wf|weir|wedding|wed|website|weber|webcam|weatherchannel|weather|watches|watch|wang|walter|walmart|wales|vu|voyage|voting|vote|volvo|volkswagen|vodka|vn|vlaanderen|vivo|viva|vision|visa|virgin|vip|vin|villas|viking|vig|video|vi|vg|vet|verisign|ventures|vegas|ve|vc|vanguard|vana|vacations|va|uz|uy|us|ups|uol|university|unicom|uk|ug|ubs|ubank|ua|tz|tw|tvs|tv|tunes|tui|tube|tt|trv|trust|travelersinsurance|travelers|travelchannel|travel|training|trading|trade|tr|tp|toys|toyota|town|tours|total|toshiba|toray|top|tools|tokyo|today|to|tn|tmall|tm|tl|tkmaxx|tk|tjx|tjmaxx|tj|tirol|tires|tips|tiffany|tickets|tiaa|theatre|theater|thd|th|tg|tf|teva|tennis|temasek|tel|technology|tech|team|tdk|td|tci|tc|taxi|tax|tattoo|tatar|tatamotors|target|taobao|talk|taipei|tab|sz|systems|symantec|sydney|sy|sx|swiss|swiftcover|swatch|sv|suzuki|surgery|surf|support|supply|supplies|sun|su|style|study|studio|stream|store|storage|stockholm|stcgroup|stc|statefarm|statebank|star|staples|stada|st|ss|srl|sr|spreadbetting|spot|sport|space|sony|song|solutions|solar|sohu|software|softbank|social|soccer|so|sncf|sn|smile|smart|sm|sling|sl|skype|sky|skin|ski|sk|sj|site|singles|sina|silk|si|shriram|showtime|show|shopping|shop|shoes|shia|shell|shaw|sharp|shangrila|sh|sg|sfr|sexy|sex|sew|seven|ses|services|sener|select|seek|security|secure|seat|search|se|sd|scot|scor|scjohnson|science|schwarz|school|scholarships|schmidt|schaeffler|scb|sca|sc|sbs|sbi|sb|saxo|save|sas|sap|sanofi|sandvikcoromant|sandvik|samsung|samsclub|salon|sale|sakura|safety|safe|saarland|sa|ryukyu|rwe|rw|run|ruhr|rugby|ru|rs|room|rogers|rodeo|rocks|rocher|ro|rmit|rip|rio|ril|rightathome|ricoh|richardli|rich|rexroth|reviews|review|restaurant|rest|republican|report|repair|rentals|rent|ren|reliance|reit|rehab|redumbrella|redstone|red|recipes|realty|realtor|realestate|read|re|raid|radio|racing|qvc|quest|quebec|qpon|qa|py|pwc|pw|pub|pt|ps|prudential|pru|protection|property|properties|promo|progressive|prof|productions|prod|pro|prime|press|praxi|pramerica|pr|post|porn|politie|poker|pohl|pnc|pn|pm|plus|plumbing|playstation|play|place|pl|pk|pizza|pioneer|pink|ping|pin|pid|pictures|pictet|pics|physio|photos|photography|photo|phone|philips|phd|pharmacy|ph|pg|pfizer|pf|pet|pe|pccw|pay|party|parts|partners|pars|paris|panasonic|page|pa|ovh|ott|otsuka|osaka|origins|orientexpress|organic|org|orange|oracle|open|ooo|onyourside|online|onl|ong|one|omega|om|ollo|oldnavy|olayangroup|olayan|okinawa|office|off|observer|obi|nz|nyc|nu|ntt|nrw|nra|nr|np|nowtv|nowruz|now|norton|northwesternmutual|nokia|no|nl|nissay|nissan|ninja|nikon|nike|nico|ni|nhk|ngo|ng|nfl|nf|nexus|nextdirect|next|news|newholland|new|neustar|network|netflix|netbank|net|nec|ne|nc|nba|navy|natura|nationwide|name|nagoya|nab|na|mz|my|mx|mw|mv|mutuelle|mutual|museum|mu|mtr|mtpc|mtn|mt|msd|ms|mr|mq|mp|movie|mov|motorcycles|moto|moscow|mortgage|mormon|monster|money|monash|mom|moi|mobile|mobi|mo|mn|mma|mm|mls|mlb|ml|mk|mitsubishi|mit|mint|mini|mil|microsoft|miami|mh|mg|metlife|merckmsd|menu|men|memorial|meme|melbourne|meet|media|med|me|md|mckinsey|mc|mba|mattel|maserati|marshalls|marriott|markets|marketing|market|map|mango|management|man|makeup|maif|madrid|macys|ma|ly|lv|luxury|luxe|lupin|lundbeck|lu|ltd|lt|ls|lr|lplfinancial|lpl|love|lotto|lotte|london|lol|loft|locus|locker|loans|loan|llp|llc|lk|lixil|living|live|lipsy|link|linde|lincoln|limo|limited|lilly|like|lighting|lifestyle|lifeinsurance|life|lidl|li|lgbt|lexus|lego|legal|lefrak|leclerc|lease|lds|lc|lb|lawyer|law|latrobe|latino|lat|lasalle|lanxess|landrover|land|lancia|lancaster|lamer|lamborghini|lacaixa|la|kz|kyoto|ky|kw|kuokgroup|kred|krd|kr|kpn|kpmg|kp|kosher|komatsu|koeln|kn|km|kiwi|kitchen|kindle|kim|kia|ki|kh|kg|kfh|kerryproperties|kerrylogistics|kerryhotels|ke|kddi|juniper|jprs|jpmorgan|jp|joy|jot|joburg|jobs|jo|jnj|jmp|jm|jll|jio|jewelry|jeep|je|jcp|jcb|java|jaguar|iveco|itv|itau|it|istanbul|ist|ismaili|is|irish|ir|iq|ipiranga|io|investments|intuit|international|intel|int|insure|insurance|institute|ink|ing|info|infiniti|industries|inc|in|imdb|imamat|im|il|ikano|iinet|ifm|ieee|ie|id|icu|ice|icbc|ibm|ευ|hyundai|hyatt|hughes|hu|ht|hsbc|hr|how|house|hotmail|hotels|hot|hosting|host|hospital|horse|honda|homesense|homes|homegoods|homedepot|holiday|holdings|hockey|hn|hm|hkt|hk|hiv|hitachi|hisamitsu|hiphop|hgtv|hermes|here|helsinki|help|healthcare|health|hdfcbank|hdfc|hbo|hangout|hamburg|hair|gy|gw|guru|guitars|guide|guge|gucci|guardian|gu|gt|gs|group|grocery|gripe|green|graphics|grainger|gr|gq|gp|gov|got|gop|google|goog|goodyear|goo|golf|goldpoint|gold|godaddy|gn|gmx|gmo|gmail|gm|globo|global|gle|glass|glade|gl|giving|gives|gifts|gift|gi|gh|ggee|gg|gf|george|genting|gent|gea|ge|gdn|gd|gbiz|gb|garage|garden|gap|games|game|gallup|gallo|gallery|gal|ga|fyi|furniture|fund|fun|fujixerox|fujitsu|ftr|frontier|frontdoor|frogans|frl|fresenius|free|fr|fox|foundation|forum|forsale|forex|ford|football|foodnetwork|food|foo|fo|fm|fly|flsmidth|flowers|florist|flir|flights|flickr|fk|fj|fitness|fit|fishing|fish|firmdale|firestone|fire|financial|finance|final|film|fido|fidelity|fiat|fi|ferrero|ferrari|feedback|fedex|fast|fashion|farmers|farm|fans|fan|family|faith|fairwinds|fail|fage|extraspace|express|exposed|expert|exchange|events|eus|eurovision|eu|etisalat|et|esurance|estate|esq|es|erni|ericsson|er|equipment|epson|enterprises|engineering|engineer|energy|emerck|email|eg|ee|education|edu|edeka|eco|ec|eat|earth|dz|dvr|dvag|durban|dupont|dunlop|duck|dubai|dtv|drive|download|dot|doosan|domains|dog|doctor|docs|do|dnp|dm|dk|dj|diy|dish|discover|discount|directory|direct|digital|diet|diamonds|dhl|dev|design|dentist|dental|democrat|delta|deloitte|dell|delivery|degree|deals|dealer|deal|de|dds|dclk|day|datsun|dating|date|data|dance|dad|dabur|cz|cyou|cymru|cy|cx|cw|cv|cuisinella|cu|csc|cruises|cruise|crs|crown|cricket|creditunion|creditcard|credit|cr|cpa|courses|coupons|coupon|count|corsica|coop|cool|cookingchannel|cooking|contractors|contact|consulting|construction|condos|comsec|computer|compare|company|community|commbank|comcast|com|cologne|college|coffee|codes|coach|co|cn|cm|clubmed|club|cloud|clothing|clinique|clinic|click|cleaning|claims|cl|ck|cityeats|city|citic|citi|citadel|cisco|circle|cipriani|ci|church|chrome|christmas|chintai|cheap|chat|chase|charity|channel|chanel|ch|cg|cfd|cfa|cf|cern|ceo|center|ceb|cd|cc|cbs|cbre|cbn|cba|catholic|catering|cat|casino|cash|caseih|case|cars|careers|career|care|cards|caravan|car|captainone|captain|capetown|canon|cancerresearch|camp|camera|cam|calvinklein|call|cal|cab|ca|bzh|bz|by|bw|bv|buzz|buy|business|builders|build|bugatti|budapest|bt|bs|brussels|brother|broker|broadway|bridgestone|bradesco|br|box|boutique|bot|boston|bostik|bosch|booking|book|boo|bond|bofa|boehringer|boats|bo|bnpparibas|bn|bmw|bms|bm|blue|bloomberg|blog|blockbuster|blackfriday|black|bj|biz|bio|bingo|bing|bike|bid|bible|bi|bharti|bh|bg|bf|bet|bestbuy|best|berlin|bentley|beer|beauty|beats|be|bd|bcn|bcg|bbva|bbt|bbc|bb|bayern|bauhaus|basketball|baseball|bargains|barefoot|barclays|barclaycard|barcelona|bar|bank|band|bananarepublic|banamex|baidu|baby|ba|azure|az|axa|ax|aws|aw|avianca|autos|auto|author|auspost|audio|audible|audi|auction|au|attorney|athleta|at|associates|asia|asda|as|arte|art|army|archi|aramco|arab|ar|aquarelle|aq|apple|app|apartments|aol|ao|anz|anquan|android|analytics|an|amsterdam|amica|amfam|amex|americanfamily|americanexpress|am|alstom|alsace|ally|allstate|allfinanz|alipay|alibaba|alfaromeo|al|akdn|airtel|airforce|airbus|aigo|aig|ai|agency|agakhan|ag|africa|afl|afamilycompany|af|aetna|aero|aeg|ae|adult|ads|adac|ad|actor|aco|accountants|accountant|accenture|academy|ac|abudhabi|able|abc|abbvie|abbott|abb|abarth|aarp|aaa)(:[0-9]+)?((\/([~0-9a-zA-Z\#\+\%@\.\/_-]+))?(\?[0-9a-zA-Z\+\%@\/&\[\];=_-]+)?)?))" + """, RegexOptions.None, conversionFailureOk: false); Assert.NotNull(tree); Assert.Empty(tree.Diagnostics); @@ -29,7 +31,9 @@ public void TestDeepAlternation() [Theory, MemberData(nameof(GetRealWorldCases))] public void TestRealWorldCases(string pattern, int options) { - var (_, tree, _) = JustParseTree($@"@""{pattern}""", (RegexOptions)options, conversionFailureOk: false); + var (_, tree, _) = JustParseTree($""" + @"{pattern}" + """, (RegexOptions)options, conversionFailureOk: false); Assert.NotNull(tree); Assert.Empty(tree.Diagnostics); } @@ -43,7 +47,11 @@ public static IEnumerable GetRealWorldCases() foreach (var obj in JArray.Load(textReader)) { var options = obj.Value("Options"); - var pattern = obj.Value("Pattern")!.Replace(@"""", @""""""); + var pattern = obj.Value("Pattern")!.Replace(""" + " + """, """ + "" + """); yield return new object[] { pattern, options }; } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/AbstractKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/AbstractKeywordRecommenderTests.cs index 91b6db0d049f3..97370453b9624 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/AbstractKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/AbstractKeywordRecommenderTests.cs @@ -13,295 +13,235 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class AbstractKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInCompilationUnit() - { - await VerifyKeywordAsync( + public Task TestInCompilationUnit() + => VerifyKeywordAsync( @"$$"); - } [Fact] - public async Task TestAfterExtern() - { - await VerifyKeywordAsync( + public Task TestAfterExtern() + => VerifyKeywordAsync( """ extern alias Goo; $$ """); - } [Fact] - public async Task TestAfterUsing() - { - await VerifyKeywordAsync( + public Task TestAfterUsing() + => VerifyKeywordAsync( """ using Goo; $$ """); - } [Fact] - public async Task TestAfterGlobalUsing() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalUsing() + => VerifyKeywordAsync( """ global using Goo; $$ """); - } [Fact] - public async Task TestAfterNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterNamespace() + => VerifyKeywordAsync( """ namespace N {} $$ """); - } [Fact] - public async Task TestAfterFileScopedNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterFileScopedNamespace() + => VerifyKeywordAsync( """ namespace N; $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestFileKeywordInsideNamespace() - { - await VerifyKeywordAsync( + public Task TestFileKeywordInsideNamespace() + => VerifyKeywordAsync( """ namespace N { file $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestFileKeywordInsideNamespaceBeforeClass() - { - await VerifyKeywordAsync( + public Task TestFileKeywordInsideNamespaceBeforeClass() + => VerifyKeywordAsync( """ namespace N { file $$ class C {} } """); - } [Fact] - public async Task TestAfterTypeDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterTypeDeclaration() + => VerifyKeywordAsync( """ class C {} $$ """); - } [Fact] - public async Task TestAfterDelegateDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateDeclaration() + => VerifyKeywordAsync( """ delegate void Goo(); $$ """); - } [Fact] - public async Task TestAfterMethodInClass() - { - await VerifyKeywordAsync( + public Task TestAfterMethodInClass() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterFieldInClass() - { - await VerifyKeywordAsync( + public Task TestAfterFieldInClass() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterPropertyInClass() - { - await VerifyKeywordAsync( + public Task TestAfterPropertyInClass() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ global using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeGlobalUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeGlobalUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ global using Goo; """); - } [Fact] - public async Task TestAfterAssemblyAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterAssemblyAttribute() + => VerifyKeywordAsync( """ [assembly: goo] $$ """); - } [Fact] - public async Task TestAfterRootAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterRootAttribute() + => VerifyKeywordAsync( """ [goo] $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync(""" + public Task TestInsideInterface() + => VerifyKeywordAsync(""" interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() @@ -312,30 +252,23 @@ public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact] - public async Task TestAfterInternal() - { - await VerifyKeywordAsync( + public Task TestAfterInternal() + => VerifyKeywordAsync( @"internal $$"); - } [Fact] - public async Task TestAfterPublic() - { - await VerifyKeywordAsync( + public Task TestAfterPublic() + => VerifyKeywordAsync( @"public $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestAfterFile() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterFile() + => VerifyKeywordAsync(SourceCodeKind.Regular, @"file $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestAfterFile2() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterFile2() + => VerifyKeywordAsync(SourceCodeKind.Regular, """ file $$ @@ -343,7 +276,6 @@ class C { } """); - } [Fact] public async Task TestNotAfterStaticInternal() @@ -362,11 +294,9 @@ public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact] - public async Task TestAfterPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterPrivate() + => VerifyKeywordAsync( @"private $$"); - } [Fact] public async Task TestNotAfterSealed() @@ -377,118 +307,95 @@ public async Task TestNotAfterStatic() => await VerifyAbsenceAsync(@"static $$"); [Theory, CombinatorialData] - public async Task TestNotAfterNestedStatic([CombinatorialValues("class", "struct", "record", "record struct", "record class")] string declarationKind) - { - await VerifyAbsenceAsync(declarationKind + """ + public Task TestNotAfterNestedStatic([CombinatorialValues("class", "struct", "record", "record struct", "record class")] string declarationKind) + => VerifyAbsenceAsync(declarationKind + """ C { static $$ """); - } [Fact] - public async Task TestAfterNestedStaticInInterface() - { - await VerifyKeywordAsync(""" + public Task TestAfterNestedStaticInInterface() + => VerifyKeywordAsync(""" interface C { static $$ """); - } [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Theory, CombinatorialData] - public async Task TestNotAfterNestedAbstract([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) - { - await VerifyAbsenceAsync(declarationKind + """ + public Task TestNotAfterNestedAbstract([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) + => VerifyAbsenceAsync(declarationKind + """ C { abstract $$ """); - } [Theory, CombinatorialData] - public async Task TestNotAfterNestedVirtual([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) - { - await VerifyAbsenceAsync(declarationKind + """ + public Task TestNotAfterNestedVirtual([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) + => VerifyAbsenceAsync(declarationKind + """ C { virtual $$ """); - } [Theory, CombinatorialData] - public async Task TestNotAfterNestedSealed([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) - { - await VerifyAbsenceAsync(declarationKind + """ + public Task TestNotAfterNestedSealed([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) + => VerifyAbsenceAsync(declarationKind + """ C { sealed $$ """); - } [Fact] - public async Task TestNotInProperty() - { - await VerifyAbsenceAsync( + public Task TestNotInProperty() + => VerifyAbsenceAsync( """ class C { int Goo { $$ """); - } [Fact] - public async Task TestNotInPropertyAfterAccessor() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAfterAccessor() + => VerifyAbsenceAsync( """ class C { int Goo { get; $$ """); - } [Fact] - public async Task TestNotInPropertyAfterAccessibility() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAfterAccessibility() + => VerifyAbsenceAsync( """ class C { int Goo { get; protected $$ """); - } [Fact] - public async Task TestNotInPropertyAfterInternal() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAfterInternal() + => VerifyAbsenceAsync( """ class C { int Goo { get; internal $$ """); - } [Fact] - public async Task TestAfterOverride() - { - await VerifyKeywordAsync( + public Task TestAfterOverride() + => VerifyKeywordAsync( """ class C { override $$ """); - } [Fact] - public async Task TestWithinExtension() - { - await VerifyAbsenceAsync( + public Task TestWithinExtension() + => VerifyAbsenceAsync( """ static class C { @@ -498,5 +405,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/AddKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/AddKeywordRecommenderTests.cs index b97c705de6c53..602ec6e0cee5c 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/AddKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/AddKeywordRecommenderTests.cs @@ -12,140 +12,110 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class AddKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterEvent() - { - await VerifyKeywordAsync( + public Task TestAfterEvent() + => VerifyKeywordAsync( """ class C { event Goo Bar { $$ """); - } [Fact] - public async Task TestAfterAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterAttribute() + => VerifyKeywordAsync( """ class C { event Goo Bar { [Bar] $$ """); - } [Fact] - public async Task TestAfterRemove() - { - await VerifyKeywordAsync( + public Task TestAfterRemove() + => VerifyKeywordAsync( """ class C { event Goo Bar { remove { } $$ """); - } [Fact] - public async Task TestAfterRemoveAndAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterRemoveAndAttribute() + => VerifyKeywordAsync( """ class C { event Goo Bar { remove { } [Bar] $$ """); - } [Fact] - public async Task TestAfterRemoveBlock() - { - await VerifyKeywordAsync( + public Task TestAfterRemoveBlock() + => VerifyKeywordAsync( """ class C { event Goo Bar { set { } $$ """); - } [Fact] - public async Task TestNotAfterAddKeyword() - { - await VerifyAbsenceAsync( + public Task TestNotAfterAddKeyword() + => VerifyAbsenceAsync( """ class C { event Goo Bar { add $$ """); - } [Fact] - public async Task TestNotAfterAddAccessor() - { - await VerifyAbsenceAsync( + public Task TestNotAfterAddAccessor() + => VerifyAbsenceAsync( """ class C { event Goo Bar { add { } $$ """); - } [Fact] - public async Task TestNotInProperty() - { - await VerifyAbsenceAsync( + public Task TestNotInProperty() + => VerifyAbsenceAsync( """ class C { int Goo { $$ """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/AliasKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/AliasKeywordRecommenderTests.cs index 70846a4e5836b..7f41ab5a62cdd 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/AliasKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/AliasKeywordRecommenderTests.cs @@ -12,100 +12,78 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class AliasKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterExtern() - { - await VerifyKeywordAsync( + public Task TestAfterExtern() + => VerifyKeywordAsync( @"extern $$"); - } [Fact] public async Task TestNotAfterAlias() => await VerifyAbsenceAsync(@"extern alias $$"); [Fact] - public async Task TestAfterExtern_InNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterExtern_InNamespace() + => VerifyKeywordAsync( """ namespace Goo { extern $$ """); - } [Fact] - public async Task TestNotAfterAlias_InNamespace() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterAlias_InNamespace() + => VerifyAbsenceAsync(""" namespace Goo { extern alias $$ """); - } [Fact] - public async Task TestNotAfterExtern_InClass() - { - await VerifyAbsenceAsync( + public Task TestNotAfterExtern_InClass() + => VerifyAbsenceAsync( """ class Goo { extern $$ """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/AllowsKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/AllowsKeywordRecommenderTests.cs index 0291e4611dc91..c9fa136783d51 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/AllowsKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/AllowsKeywordRecommenderTests.cs @@ -12,155 +12,123 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class AllowsKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot() - { - await VerifyAbsenceAsync("$$"); - } + public Task TestNotAtRoot() + => VerifyAbsenceAsync("$$"); [Fact] - public async Task TestNotAfterClassDeclaration() - { - await VerifyAbsenceAsync( + public Task TestNotAfterClassDeclaration() + => VerifyAbsenceAsync( """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGlobalStatement() + => VerifyAbsenceAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGlobalVariableDeclaration() + => VerifyAbsenceAsync( """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( """ using Goo = $$ """); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( """ global using Goo = $$ """); - } [Theory] [CombinatorialData] - public async Task TestNotEmptyStatement(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod("$$", topLevelStatement: topLevelStatement)); - } + public Task TestNotEmptyStatement(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod("$$", topLevelStatement: topLevelStatement)); [Fact] - public async Task TestAfterNewTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterNewTypeParameterConstraint() + => VerifyKeywordAsync( """ class C where T : $$ """); - } [Fact] - public async Task TestAfterTypeParameterConstraint2() - { - await VerifyKeywordAsync( + public Task TestAfterTypeParameterConstraint2() + => VerifyKeywordAsync( """ class C where T : $$ where U : U """); - } [Fact] - public async Task TestAfterMethodTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterMethodTypeParameterConstraint() + => VerifyKeywordAsync( """ class C { void Goo() where T : $$ """); - } [Fact] - public async Task TestAfterMethodTypeParameterConstraint2() - { - await VerifyKeywordAsync( + public Task TestAfterMethodTypeParameterConstraint2() + => VerifyKeywordAsync( """ class C { void Goo() where T : $$ where U : T """); - } [Fact] - public async Task TestNotAfterClassTypeParameterConstraint() - { - await VerifyAbsenceAsync( + public Task TestNotAfterClassTypeParameterConstraint() + => VerifyAbsenceAsync( """ class C where T : class, $$ """); - } [Fact] - public async Task TestAfterStructTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterStructTypeParameterConstraint() + => VerifyKeywordAsync( """ class C where T : struct, $$ """); - } [Fact] - public async Task TestAfterSimpleTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterSimpleTypeParameterConstraint() + => VerifyKeywordAsync( """ class C where T : IGoo, $$ """); - } [Fact] - public async Task TestAfterConstructorTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorTypeParameterConstraint() + => VerifyKeywordAsync( """ class C where T : new(), $$ """); - } [Fact] - public async Task TestNotAfterMethodInClass() - { - await VerifyAbsenceAsync( + public Task TestNotAfterMethodInClass() + => VerifyAbsenceAsync( """ class C { void Goo() {} $$ """); - } [Fact] public async Task TestNotAfterClass() diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/AndKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/AndKeywordRecommenderTests.cs index 96640aa20e45f..7b438b8a94b2f 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/AndKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/AndKeywordRecommenderTests.cs @@ -17,37 +17,28 @@ public sealed class AndKeywordRecommenderTests : KeywordRecommenderTests """; [Fact] - public async Task TestAfterConstant() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAfterConstant() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is 1 $$")); - } [Fact] - public async Task TestAfterMultipleConstants() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAfterMultipleConstants() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is 1 or 2 $$")); - } [Fact] - public async Task TestAfterType() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAfterType() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is int $$")); - } [Fact] - public async Task TestAfterRelationalOperator() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAfterRelationalOperator() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is >= 0 $$")); - } [Fact] - public async Task TestAfterGenericType() - { - await VerifyKeywordAsync( + public Task TestAfterGenericType() + => VerifyKeywordAsync( """ class C { @@ -56,12 +47,10 @@ void M() var e = new object(); if (e is T $$ """); - } [Fact] - public async Task TestAfterArrayType() - { - await VerifyKeywordAsync( + public Task TestAfterArrayType() + => VerifyKeywordAsync( """ class C { @@ -70,12 +59,10 @@ void M() var e = new object(); if (e is int[] $$ """); - } [Fact] - public async Task TestAfterListType() - { - await VerifyKeywordAsync( + public Task TestAfterListType() + => VerifyKeywordAsync( """ using System.Collections.Generic; @@ -86,12 +73,10 @@ void M() var e = new object(); if (e is List $$ """); - } [Fact] - public async Task TestAfterListType_FullyQualified() - { - await VerifyKeywordAsync( + public Task TestAfterListType_FullyQualified() + => VerifyKeywordAsync( """ class C { @@ -100,12 +85,10 @@ void M() var e = new object(); if (e is System.Collections.Generic.List $$ """); - } [Fact] - public async Task TestAfterRecursivePattern() - { - await VerifyKeywordAsync( + public Task TestAfterRecursivePattern() + => VerifyKeywordAsync( """ class C { @@ -115,12 +98,10 @@ void M(C test) { if (test is { P: 1 } $$ """); - } [Fact] - public async Task TestInsideSubpattern() - { - await VerifyKeywordAsync( + public Task TestInsideSubpattern() + => VerifyKeywordAsync( """ class C { @@ -130,12 +111,10 @@ void M(C test) { if (test is { P: 1 $$ """); - } [Fact] - public async Task TestInsideSubpattern_ComplexConstant() - { - await VerifyKeywordAsync( + public Task TestInsideSubpattern_ComplexConstant() + => VerifyKeywordAsync( """ namespace N { @@ -149,12 +128,10 @@ void M(C test) { if (test is { Prop: N.C.P $$ """); - } [Fact] - public async Task TestInsideSubpattern_AfterOpenParen() - { - await VerifyKeywordAsync( + public Task TestInsideSubpattern_AfterOpenParen() + => VerifyKeywordAsync( """ class C { @@ -165,12 +142,10 @@ void M() var C2 = new C(); if (C2 is { P: (1 $$ """); - } [Fact] - public async Task TestInsideSubpattern_AfterOpenParen_ComplexConstant() - { - await VerifyKeywordAsync( + public Task TestInsideSubpattern_AfterOpenParen_ComplexConstant() + => VerifyKeywordAsync( """ namespace N { @@ -184,12 +159,10 @@ void M(C test) { if (test is { Prop: (N.C.P $$ """); - } [Fact] - public async Task TestInsideSubpattern_AfterMultipleOpenParens() - { - await VerifyKeywordAsync( + public Task TestInsideSubpattern_AfterMultipleOpenParens() + => VerifyKeywordAsync( """ class C { @@ -200,12 +173,10 @@ void M() var C2 = new C(); if (C2 is { P: (((1 $$ """); - } [Fact] - public async Task TestInsideSubpattern_AfterMultipleOpenParens_ComplexConstant() - { - await VerifyKeywordAsync( + public Task TestInsideSubpattern_AfterMultipleOpenParens_ComplexConstant() + => VerifyKeywordAsync( """ namespace N { @@ -219,12 +190,10 @@ void M(C test) { if (test is { Prop: (((N.C.P $$ """); - } [Fact] - public async Task TestInsideSubpattern_AfterParenPair() - { - await VerifyKeywordAsync( + public Task TestInsideSubpattern_AfterParenPair() + => VerifyKeywordAsync( """ class C { @@ -235,12 +204,10 @@ void M() var C2 = new C(); if (C2 is { P: (1) $$ """); - } [Fact] - public async Task TestInsideSubpattern_AfterParenPair_ComplexConstant() - { - await VerifyKeywordAsync( + public Task TestInsideSubpattern_AfterParenPair_ComplexConstant() + => VerifyKeywordAsync( """ namespace N { @@ -254,12 +221,10 @@ void M(C test) { if (test is { Prop: (N.C.P + 1) $$ """); - } [Fact] - public async Task TestInsideSubpattern_AfterMultipleParenPairs() - { - await VerifyKeywordAsync( + public Task TestInsideSubpattern_AfterMultipleParenPairs() + => VerifyKeywordAsync( """ class C { @@ -270,12 +235,10 @@ void M() var C2 = new C(); if (C2 is { P: (((1))) $$ """); - } [Fact] - public async Task TestInsideSubpattern_AfterMultipleParenPairs_ComplexConstant() - { - await VerifyKeywordAsync( + public Task TestInsideSubpattern_AfterMultipleParenPairs_ComplexConstant() + => VerifyKeywordAsync( """ namespace N { @@ -289,12 +252,10 @@ void M(C test) { if (test is { Prop: (((N.C.P))) $$ """); - } [Fact] - public async Task TestAfterQualifiedName() - { - await VerifyKeywordAsync( + public Task TestAfterQualifiedName() + => VerifyKeywordAsync( """ class C { @@ -306,12 +267,10 @@ void M() var e = new object(); if (e is C2.P $$ """); - } [Fact] - public async Task TestAfterQualifiedName2() - { - await VerifyKeywordAsync( + public Task TestAfterQualifiedName2() + => VerifyKeywordAsync( """ namespace N { @@ -324,23 +283,19 @@ void M() var e = new object(); if (e is N.C.P $$ """); - } [Fact] - public async Task TestAtBeginningOfSwitchExpression() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAtBeginningOfSwitchExpression() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + """ var result = e switch { 1 $$ """)); - } [Fact] - public async Task TestAtBeginningOfSwitchExpression_Complex() - { - await VerifyKeywordAsync( + public Task TestAtBeginningOfSwitchExpression_Complex() + => VerifyKeywordAsync( """ namespace N { @@ -355,34 +310,28 @@ void M() { N.C.P $$ """); - } [Fact] - public async Task TestAtBeginningOfSwitchStatement() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAtBeginningOfSwitchStatement() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + """ switch (e) { case 1 $$ """)); - } [Fact] - public async Task TestAtBeginningOfSwitchExpression_AfterOpenParen() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAtBeginningOfSwitchExpression_AfterOpenParen() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + """ var result = e switch { (1 $$ """)); - } [Fact] - public async Task TestAtBeginningOfSwitchExpression_AfterOpenParen_Complex() - { - await VerifyKeywordAsync( + public Task TestAtBeginningOfSwitchExpression_AfterOpenParen_Complex() + => VerifyKeywordAsync( """ namespace N { @@ -397,23 +346,19 @@ void M() { (N.C.P $$ """); - } [Fact] - public async Task TestAtBeginningOfSwitchExpression_AfterMultipleOpenParens() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAtBeginningOfSwitchExpression_AfterMultipleOpenParens() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + """ var result = e switch { (((1 $$ """)); - } [Fact] - public async Task TestAtBeginningOfSwitchExpression_AfterMultipleOpenParens_Complex() - { - await VerifyKeywordAsync( + public Task TestAtBeginningOfSwitchExpression_AfterMultipleOpenParens_Complex() + => VerifyKeywordAsync( """ namespace N { @@ -428,34 +373,28 @@ void M() { (((N.C.P $$ """); - } [Fact] - public async Task TestAtBeginningOfSwitchStatement_AfterOpenParen() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAtBeginningOfSwitchStatement_AfterOpenParen() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + """ switch (e) { case (1 $$ """)); - } [Fact] - public async Task TestAtBeginningOfSwitchStatement_AfterMultipleOpenParens() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAtBeginningOfSwitchStatement_AfterMultipleOpenParens() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + """ switch (e) { case (((1 $$ """)); - } [Fact] - public async Task TestAtBeginningOfSwitchStatement_AfterMultipleOpenParens_MemberAccessExpression() - { - await VerifyKeywordAsync( + public Task TestAtBeginningOfSwitchStatement_AfterMultipleOpenParens_MemberAccessExpression() + => VerifyKeywordAsync( """ namespace N { @@ -470,12 +409,10 @@ void M() { case (((N.C.P $$ """); - } [Fact] - public async Task TestAtBeginningOfSwitchStatement_AfterMultipleOpenParens_MemberAccessExpression2() - { - await VerifyKeywordAsync( + public Task TestAtBeginningOfSwitchStatement_AfterMultipleOpenParens_MemberAccessExpression2() + => VerifyKeywordAsync( """ namespace N { @@ -488,116 +425,88 @@ void M() { case (((N.C $$ """); - } [Fact] - public async Task TestMissingAfterIsKeyword() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAfterIsKeyword() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is $$")); - } [Fact] - public async Task TestMissingAfterNotKeyword() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAfterNotKeyword() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is not $$")); - } [Fact] - public async Task TestMissingAfterVarKeyword() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAfterVarKeyword() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is var $$")); - } [Fact] - public async Task TestMissingAfterAndKeyword() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAfterAndKeyword() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is 1 and $$")); - } [Fact] - public async Task TestMissingAfterOrKeyword() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAfterOrKeyword() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is 1 or $$")); - } [Fact] - public async Task TestMissingAfterOpenParen() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAfterOpenParen() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is ($$")); - } [Fact] - public async Task TestMissingAfterOpenBracket() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAfterOpenBracket() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is { $$")); - } [Fact] - public async Task TestMissingAtBeginningOfSwitchExpression() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAtBeginningOfSwitchExpression() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + """ var result = e switch { $$ """)); - } [Fact] - public async Task TestMissingAtBeginningOfSwitchStatement() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAtBeginningOfSwitchStatement() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + """ switch (e) { case $$ """)); - } [Fact] - public async Task TestMissingAfterTypeAndOpenParen() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAfterTypeAndOpenParen() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is int ($$")); - } [Fact] - public async Task TestMissingAfterTypeAndCloseParen() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAfterTypeAndCloseParen() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is int)$$")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44396")] - public async Task TestMissingAfterColonColonPatternSyntax() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAfterColonColonPatternSyntax() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is null or global::$$) { }")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44396")] - public async Task TestMissingAfterColonColonPatternSyntax_SwitchExpression() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAfterColonColonPatternSyntax_SwitchExpression() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + """ var x = false; x = e switch { global::$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51431")] - public async Task TestNotAtIncompleteSwitchPattern() - { - await VerifyAbsenceAsync( + public Task TestNotAtIncompleteSwitchPattern() + => VerifyAbsenceAsync( """ var goo = Goo.First; switch (goo) @@ -611,42 +520,32 @@ public enum Goo Second } """); - } [Fact] - public async Task TestAfterParenthesizedPattern1() - { - await VerifyKeywordAsync( + public Task TestAfterParenthesizedPattern1() + => VerifyKeywordAsync( """ expr is (not []) $$ """); - } [Fact] - public async Task TestAfterParenthesizedPattern2() - { - // expr is (not []) and var x - await VerifyKeywordAsync( + public Task TestAfterParenthesizedPattern2() + => VerifyKeywordAsync( """ expr is (not []) $$ var x """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70045")] - public async Task TestNotInMemberAccessInPattern1() - { - await VerifyAbsenceAsync(""" + public Task TestNotInMemberAccessInPattern1() + => VerifyAbsenceAsync(""" int v = 0; if (v is var a and a.$$) """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70045")] - public async Task TestNotInMemberAccessInPattern2() - { - await VerifyAbsenceAsync(""" + public Task TestNotInMemberAccessInPattern2() + => VerifyAbsenceAsync(""" int* v = null; if (v is var a and a->$$) """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/AnnotationsKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/AnnotationsKeywordRecommenderTests.cs index 8a55bac134786..7a18bf0d9fc8c 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/AnnotationsKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/AnnotationsKeywordRecommenderTests.cs @@ -12,116 +12,86 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class AnnotationsKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterHash() - { - await VerifyAbsenceAsync( + public Task TestAfterHash() + => VerifyAbsenceAsync( @"#$$"); - } [Fact] - public async Task TestAfterHashAndSpace() - { - await VerifyAbsenceAsync( + public Task TestAfterHashAndSpace() + => VerifyAbsenceAsync( @"# $$"); - } [Fact] - public async Task TestAfterPragma() - { - await VerifyAbsenceAsync( + public Task TestAfterPragma() + => VerifyAbsenceAsync( @"#pragma $$"); - } [Fact] - public async Task TestAfterNullable() - { - await VerifyAbsenceAsync( + public Task TestAfterNullable() + => VerifyAbsenceAsync( @"#nullable $$"); - } [Fact] - public async Task TestAfterNullableEnable() - { - await VerifyKeywordAsync( + public Task TestAfterNullableEnable() + => VerifyKeywordAsync( @"#nullable enable $$"); - } [Fact] - public async Task TestAfterNullableDisable() - { - await VerifyKeywordAsync( + public Task TestAfterNullableDisable() + => VerifyKeywordAsync( @"#nullable disable $$"); - } [Fact] - public async Task TestAfterNullableRestore() - { - await VerifyKeywordAsync( + public Task TestAfterNullableRestore() + => VerifyKeywordAsync( @"#nullable restore $$"); - } [Fact] - public async Task TestAfterNullableBadSetting() - { - await VerifyAbsenceAsync( + public Task TestAfterNullableBadSetting() + => VerifyAbsenceAsync( @"#nullable true $$"); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/AsKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/AsKeywordRecommenderTests.cs index aa5d56a756285..ae908498fbac5 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/AsKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/AsKeywordRecommenderTests.cs @@ -13,129 +13,98 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class AsKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterExpr() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterExpr() + => VerifyKeywordAsync(AddInsideMethod( @"var q = goo $$")); - } [Fact] - public async Task TestAfterDottedName() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterDottedName() + => VerifyKeywordAsync(AddInsideMethod( @"var q = goo.Current $$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543041")] - public async Task TestNotAfterVarInForLoop() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterVarInForLoop() + => VerifyAbsenceAsync(AddInsideMethod( @"for (var $$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] - public async Task TestNotBeforeFirstStringHole() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotBeforeFirstStringHole() + => VerifyAbsenceAsync(AddInsideMethod( """ var x = "\{0}$$\{1}\{2}" """)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] - public async Task TestNotBetweenStringHoles() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotBetweenStringHoles() + => VerifyAbsenceAsync(AddInsideMethod( """ var x = "\{0}\{1}$$\{2}" """)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] - public async Task TestNotAfterStringHoles() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterStringHoles() + => VerifyAbsenceAsync(AddInsideMethod( """ var x = "\{0}\{1}\{2}$$" """)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] - public async Task TestAfterLastStringHole() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterLastStringHole() + => VerifyKeywordAsync(AddInsideMethod( @"var x = ""\{0}\{1}\{2}"" $$")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1736")] - public async Task TestNotWithinNumericLiteral() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotWithinNumericLiteral() + => VerifyAbsenceAsync(AddInsideMethod( @"var x = .$$0;")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28586")] - public async Task TestNotAfterAsync() - { - await VerifyAbsenceAsync( + public Task TestNotAfterAsync() + => VerifyAbsenceAsync( """ using System; @@ -151,12 +120,10 @@ void Bar(Func f) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8319")] - public async Task TestNotAfterMethodReference() - { - await VerifyAbsenceAsync( + public Task TestNotAfterMethodReference() + => VerifyAbsenceAsync( """ using System; @@ -164,12 +131,10 @@ class C { void M() { var v = Console.WriteLine $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8319")] - public async Task TestNotAfterAnonymousMethod() - { - await VerifyAbsenceAsync( + public Task TestNotAfterAnonymousMethod() + => VerifyAbsenceAsync( """ using System; @@ -177,12 +142,10 @@ class C { void M() { Action a = delegate { } $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8319")] - public async Task TestNotAfterLambda1() - { - await VerifyAbsenceAsync( + public Task TestNotAfterLambda1() + => VerifyAbsenceAsync( """ using System; @@ -190,12 +153,10 @@ class C { void M() { Action b = (() => 0) $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8319")] - public async Task TestNotAfterLambda2() - { - await VerifyAbsenceAsync( + public Task TestNotAfterLambda2() + => VerifyAbsenceAsync( """ using System; @@ -203,12 +164,10 @@ class C { void M() { Action b = () => {} $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48573")] - public async Task TestMissingAfterNumericLiteral() - { - await VerifyAbsenceAsync( + public Task TestMissingAfterNumericLiteral() + => VerifyAbsenceAsync( """ class C { @@ -218,12 +177,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48573")] - public async Task TestMissingAfterNumericLiteralAndDot() - { - await VerifyAbsenceAsync( + public Task TestMissingAfterNumericLiteralAndDot() + => VerifyAbsenceAsync( """ class C { @@ -233,12 +190,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48573")] - public async Task TestMissingAfterNumericLiteralDotAndSpace() - { - await VerifyAbsenceAsync( + public Task TestMissingAfterNumericLiteralDotAndSpace() + => VerifyAbsenceAsync( """ class C { @@ -248,12 +203,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31367")] - public async Task TestMissingInCaseClause1() - { - await VerifyAbsenceAsync( + public Task TestMissingInCaseClause1() + => VerifyAbsenceAsync( """ class A { @@ -271,12 +224,10 @@ void M(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31367")] - public async Task TestMissingInCaseClause2() - { - await VerifyAbsenceAsync( + public Task TestMissingInCaseClause2() + => VerifyAbsenceAsync( """ namespace N { @@ -297,5 +248,4 @@ void M(object o) } } """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/AscendingKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/AscendingKeywordRecommenderTests.cs index 8dc4ed9167b49..f7c720e3b632c 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/AscendingKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/AscendingKeywordRecommenderTests.cs @@ -12,110 +12,86 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class AscendingKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterOrderByExpr() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterOrderByExpr() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y orderby x $$ """)); - } [Fact] - public async Task TestAfterSecondExpr() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterSecondExpr() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y orderby x, y $$ """)); - } [Fact] - public async Task TestBetweenExprs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBetweenExprs() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y orderby x, y $$, z """)); - } [Fact] - public async Task TestNotAfterDot() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterDot() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y orderby x.$$ """)); - } [Fact] - public async Task TestNotAfterComma() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterComma() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y orderby x, $$ """)); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/AssemblyKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/AssemblyKeywordRecommenderTests.cs index bbb28bcea0cd8..243f6c4f99fd0 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/AssemblyKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/AssemblyKeywordRecommenderTests.cs @@ -13,100 +13,79 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class AssemblyKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestNotInAttributeInsideClass() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeInsideClass() + => VerifyAbsenceAsync( """ class C { [$$ """); - } [Fact] - public async Task TestNotInAttributeAfterAttributeInsideClass() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeAfterAttributeInsideClass() + => VerifyAbsenceAsync( """ class C { [Goo] [$$ """); - } [Fact] - public async Task TestNotInAttributeAfterMethod() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeAfterMethod() + => VerifyAbsenceAsync( """ class C { void Goo() { } [$$ """); - } [Fact] - public async Task TestNotInAttributeAfterProperty() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeAfterProperty() + => VerifyAbsenceAsync( """ class C { int Goo { @@ -114,41 +93,33 @@ int Goo { } [$$ """); - } [Fact] - public async Task TestNotInAttributeAfterField() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeAfterField() + => VerifyAbsenceAsync( """ class C { int Goo; [$$ """); - } [Fact] - public async Task TestNotInAttributeAfterEvent() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeAfterEvent() + => VerifyAbsenceAsync( """ class C { event Action Goo; [$$ """); - } [Fact] - public async Task TestInOuterAttribute() - { - await VerifyKeywordAsync( + public Task TestInOuterAttribute() + => VerifyKeywordAsync( @"[$$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/362")] - public async Task TestNotInAttributeNestClass() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeNestClass() + => VerifyAbsenceAsync( """ class A { @@ -158,152 +129,124 @@ class B } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/362")] - public async Task TestInAttributeBeforeNamespace() - { - await VerifyKeywordAsync( + public Task TestInAttributeBeforeNamespace() + => VerifyKeywordAsync( """ [$$ namespace Goo { """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/362")] - public async Task TestInAttributeBeforeFileScopedNamespace() - { - await VerifyKeywordAsync( + public Task TestInAttributeBeforeFileScopedNamespace() + => VerifyKeywordAsync( """ [$$ namespace Goo; """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/362")] - public async Task TestNotInAttributeBeforeNamespaceWithoutOpenBracket() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeBeforeNamespaceWithoutOpenBracket() + => VerifyAbsenceAsync( """ $$ namespace Goo {} """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/362")] - public async Task TestNotInAttributeBeforeNamespaceAndAfterUsingWithNoOpenBracket() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeBeforeNamespaceAndAfterUsingWithNoOpenBracket() + => VerifyAbsenceAsync( """ using System; $$ namespace Goo {} """); - } [Fact] - public async Task TestNotInAttributeBeforeNamespaceAndAfterGlobalUsingWithNoOpenBracket() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeBeforeNamespaceAndAfterGlobalUsingWithNoOpenBracket() + => VerifyAbsenceAsync( """ global using System; $$ namespace Goo {} """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/362")] - public async Task TestInAttributeBeforeNamespaceAndAfterUsingWithOpenBracket() - { - await VerifyKeywordAsync( + public Task TestInAttributeBeforeNamespaceAndAfterUsingWithOpenBracket() + => VerifyKeywordAsync( """ using System; [$$ namespace Goo {} """); - } [Fact] - public async Task TestInAttributeBeforeNamespaceAndAfterGlobalUsingWithOpenBracket() - { - await VerifyKeywordAsync( + public Task TestInAttributeBeforeNamespaceAndAfterGlobalUsingWithOpenBracket() + => VerifyKeywordAsync( """ global using System; [$$ namespace Goo {} """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/362")] - public async Task TestInAttributeBeforeAssemblyWithOpenBracket() - { - await VerifyKeywordAsync( + public Task TestInAttributeBeforeAssemblyWithOpenBracket() + => VerifyKeywordAsync( """ [$$ [assembly: Whatever] namespace Goo {} """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/362")] - public async Task TestInAttributeBeforeClass() - { - await VerifyKeywordAsync( + public Task TestInAttributeBeforeClass() + => VerifyKeywordAsync( """ [$$ class Goo {} """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/362")] - public async Task TestInAttributeBeforeInterface() - { - await VerifyKeywordAsync( + public Task TestInAttributeBeforeInterface() + => VerifyKeywordAsync( """ [$$ interface IGoo {} """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/362")] - public async Task TestInAttributeBeforeStruct() - { - await VerifyKeywordAsync( + public Task TestInAttributeBeforeStruct() + => VerifyKeywordAsync( """ [$$ struct Goo {} """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/362")] - public async Task TestInAttributeBeforeEnum() - { - await VerifyKeywordAsync( + public Task TestInAttributeBeforeEnum() + => VerifyKeywordAsync( """ [$$ enum Goo {} """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/362")] - public async Task TestNotInAttributeBeforeOtherAttributeWithoutOpenBracket() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeBeforeOtherAttributeWithoutOpenBracket() + => VerifyAbsenceAsync( """ $$ [assembly: Whatever] namespace Goo {} """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/362")] - public async Task TestNotInAttributeBeforeAssemblyAttributeAndAfterUsingWithoutOpenBracket() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeBeforeAssemblyAttributeAndAfterUsingWithoutOpenBracket() + => VerifyAbsenceAsync( """ using System; @@ -311,12 +254,10 @@ await VerifyAbsenceAsync( [assembly: Whatever] namespace Goo {} """); - } [Fact] - public async Task TestNotInAttributeBeforeAssemblyAttributeAndAfterGlobalUsingWithoutOpenBracket() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeBeforeAssemblyAttributeAndAfterGlobalUsingWithoutOpenBracket() + => VerifyAbsenceAsync( """ global using System; @@ -324,12 +265,10 @@ await VerifyAbsenceAsync( [assembly: Whatever] namespace Goo {} """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/362")] - public async Task TestInBeforeAttributeAssemblyAttributeAndAfterUsingWithoutOpenBracket() - { - await VerifyKeywordAsync( + public Task TestInBeforeAttributeAssemblyAttributeAndAfterUsingWithoutOpenBracket() + => VerifyKeywordAsync( """ using System; @@ -337,12 +276,10 @@ await VerifyKeywordAsync( [assembly: Whatever] namespace Goo {} """); - } [Fact] - public async Task TestInBeforeAttributeAssemblyAttributeAndAfterGlobalUsingWithoutOpenBracket() - { - await VerifyKeywordAsync( + public Task TestInBeforeAttributeAssemblyAttributeAndAfterGlobalUsingWithoutOpenBracket() + => VerifyKeywordAsync( """ global using System; @@ -350,120 +287,95 @@ await VerifyKeywordAsync( [assembly: Whatever] namespace Goo {} """); - } [Fact] - public async Task TestNotInOuterAttributeInNamespace() - { - await VerifyAbsenceAsync( + public Task TestNotInOuterAttributeInNamespace() + => VerifyAbsenceAsync( """ namespace Goo { [$$ """); - } [Fact] - public async Task TestNotInParameterAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInParameterAttribute() + => VerifyAbsenceAsync( """ class C { void Goo([$$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/362")] - public async Task TestNotInElementAccess() - { - await VerifyAbsenceAsync( + public Task TestNotInElementAccess() + => VerifyAbsenceAsync( """ class C { void Goo(string[] array) { array[$$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/362")] - public async Task TestNotInIndex() - { - await VerifyAbsenceAsync( + public Task TestNotInIndex() + => VerifyAbsenceAsync( """ class C { public int this[$$ """); - } [Fact] - public async Task TestNotInPropertyAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAttribute() + => VerifyAbsenceAsync( """ class C { int Goo { [$$ """); - } [Fact] - public async Task TestNotInEventAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInEventAttribute() + => VerifyAbsenceAsync( """ class C { event Action Goo { [$$ """); - } [Fact] - public async Task TestNotInClassAssemblyParameters() - { - await VerifyAbsenceAsync( + public Task TestNotInClassAssemblyParameters() + => VerifyAbsenceAsync( @"class C<[$$"); - } [Fact] - public async Task TestNotInDelegateAssemblyParameters() - { - await VerifyAbsenceAsync( + public Task TestNotInDelegateAssemblyParameters() + => VerifyAbsenceAsync( @"delegate void D<[$$"); - } [Fact] - public async Task TestNotInMethodAssemblyParameters() - { - await VerifyAbsenceAsync( + public Task TestNotInMethodAssemblyParameters() + => VerifyAbsenceAsync( """ class C { void M<[$$ """); - } [Fact] - public async Task TestNotInInterface() - { - await VerifyAbsenceAsync( + public Task TestNotInInterface() + => VerifyAbsenceAsync( """ interface I { [$$ """); - } [Fact] - public async Task TestNotInStruct() - { - await VerifyAbsenceAsync( + public Task TestNotInStruct() + => VerifyAbsenceAsync( """ struct S { [$$ """); - } [Fact] - public async Task TestNotInEnum() - { - await VerifyAbsenceAsync( + public Task TestNotInEnum() + => VerifyAbsenceAsync( """ enum E { [$$ """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/AsyncKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/AsyncKeywordRecommenderTests.cs index 18df1ff77d24d..766d13ce45966 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/AsyncKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/AsyncKeywordRecommenderTests.cs @@ -13,59 +13,49 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class AsyncKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestMethodDeclaration1() - { - await VerifyKeywordAsync(""" + public Task TestMethodDeclaration1() + => VerifyKeywordAsync(""" class C { $$ } """); - } [Fact] - public async Task TestMethodDeclaration2() - { - await VerifyKeywordAsync(""" + public Task TestMethodDeclaration2() + => VerifyKeywordAsync(""" class C { public $$ } """); - } [Fact] - public async Task TestMethodDeclaration3() - { - await VerifyKeywordAsync(""" + public Task TestMethodDeclaration3() + => VerifyKeywordAsync(""" class C { $$ public void goo() { } } """); - } [Fact] - public async Task TestMethodDeclarationAsyncAfterCursor() - { - await VerifyKeywordAsync(""" + public Task TestMethodDeclarationAsyncAfterCursor() + => VerifyKeywordAsync(""" class C { public $$ async void goo() { } } """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync(""" + public Task TestInsideInterface() + => VerifyKeywordAsync(""" interface C { $$ } """); - } [Fact] public async Task TestMethodDeclarationInGlobalStatement1() @@ -82,9 +72,8 @@ public async Task TestMethodDeclarationInGlobalStatement2() } [Fact] - public async Task TestExpressionContext() - { - await VerifyKeywordAsync(""" + public Task TestExpressionContext() + => VerifyKeywordAsync(""" class C { void goo() @@ -93,12 +82,10 @@ void goo() } } """); - } [Fact] - public async Task TestNotInParameter() - { - await VerifyAbsenceAsync(""" + public Task TestNotInParameter() + => VerifyAbsenceAsync(""" class C { void goo($$) @@ -106,12 +93,10 @@ void goo($$) } } """); - } [Fact] - public async Task TestBeforeLambda() - { - await VerifyKeywordAsync(""" + public Task TestBeforeLambda() + => VerifyKeywordAsync(""" class Program { static void Main(string[] args) @@ -120,12 +105,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestBeforeStaticLambda() - { - await VerifyKeywordAsync(""" + public Task TestBeforeStaticLambda() + => VerifyKeywordAsync(""" class Program { static void Main(string[] args) @@ -134,12 +117,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestAfterStaticInLambda() - { - await VerifyKeywordAsync(""" + public Task TestAfterStaticInLambda() + => VerifyKeywordAsync(""" class Program { static void Main(string[] args) @@ -148,12 +129,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestAfterStaticInExpression() - { - await VerifyKeywordAsync(""" + public Task TestAfterStaticInExpression() + => VerifyKeywordAsync(""" class Program { static void Main(string[] args) @@ -162,12 +141,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestAfterDuplicateStaticInExpression() - { - await VerifyKeywordAsync(""" + public Task TestAfterDuplicateStaticInExpression() + => VerifyKeywordAsync(""" class Program { static void Main(string[] args) @@ -176,12 +153,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestAfterStaticAsyncInExpression() - { - await VerifyAbsenceAsync(""" + public Task TestAfterStaticAsyncInExpression() + => VerifyAbsenceAsync(""" class Program { static void Main(string[] args) @@ -190,12 +165,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestAfterAsyncStaticInExpression() - { - await VerifyAbsenceAsync(""" + public Task TestAfterAsyncStaticInExpression() + => VerifyAbsenceAsync(""" class Program { static void Main(string[] args) @@ -204,12 +177,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestInAttribute() - { - await VerifyAbsenceAsync(""" + public Task TestInAttribute() + => VerifyAbsenceAsync(""" class C { [$$ @@ -218,12 +189,10 @@ void M() } } """); - } [Fact] - public async Task TestInAttributeArgument() - { - await VerifyAbsenceAsync(""" + public Task TestInAttributeArgument() + => VerifyAbsenceAsync(""" class C { [Attr($$ @@ -232,12 +201,10 @@ void M() } } """); - } [Fact] - public async Task TestBeforeStaticInExpression() - { - await VerifyKeywordAsync(""" + public Task TestBeforeStaticInExpression() + => VerifyKeywordAsync(""" class Program { static void Main(string[] args) @@ -246,12 +213,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestNotIfAlreadyAsyncInLambda() - { - await VerifyAbsenceAsync(""" + public Task TestNotIfAlreadyAsyncInLambda() + => VerifyAbsenceAsync(""" class Program { static void Main(string[] args) @@ -260,12 +225,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60340")] - public async Task TestNotIfAlreadyAsyncBeforeOtherMember() - { - await VerifyAbsenceAsync(""" + public Task TestNotIfAlreadyAsyncBeforeOtherMember() + => VerifyAbsenceAsync(""" class Program { async $$ @@ -273,104 +236,84 @@ class Program public void M() {} } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60340")] - public async Task TestNotIfAlreadyAsyncAsLastMember() - { - await VerifyAbsenceAsync(""" + public Task TestNotIfAlreadyAsyncAsLastMember() + => VerifyAbsenceAsync(""" class Program { async $$ } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578061")] - public async Task TestNotInNamespace() - { - await VerifyAbsenceAsync(""" + public Task TestNotInNamespace() + => VerifyAbsenceAsync(""" namespace Goo { $$ } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578069")] - public async Task TestNotAfterPartialInNamespace() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterPartialInNamespace() + => VerifyAbsenceAsync(""" namespace Goo { partial $$ } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578750")] - public async Task TestNotAfterPartialInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterPartialInClass() + => VerifyAbsenceAsync(""" class Goo { partial $$ } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578750")] - public async Task TestAfterAttribute() - { - await VerifyKeywordAsync(""" + public Task TestAfterAttribute() + => VerifyKeywordAsync(""" class Goo { [Attr] $$ } """); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/8616")] [CompilerTrait(CompilerFeature.LocalFunctions)] - public async Task TestLocalFunction(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestLocalFunction(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/14525")] [CompilerTrait(CompilerFeature.LocalFunctions)] - public async Task TestLocalFunction2(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestLocalFunction2(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"unsafe $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/14525")] [CompilerTrait(CompilerFeature.LocalFunctions)] - public async Task TestLocalFunction3(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestLocalFunction3(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"unsafe $$ void L() { }", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/8616")] [CompilerTrait(CompilerFeature.LocalFunctions)] - public async Task TestLocalFunction4(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestLocalFunction4(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"$$ void L() { }", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8616")] [CompilerTrait(CompilerFeature.LocalFunctions)] - public async Task TestLocalFunction5() - { - await VerifyKeywordAsync(""" + public Task TestLocalFunction5() + => VerifyKeywordAsync(""" class Goo { public void M(Action a) @@ -382,30 +325,24 @@ public void M(Action a) } } """); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/8616")] [CompilerTrait(CompilerFeature.LocalFunctions)] - public async Task TestLocalFunction6(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestLocalFunction6(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( @"int $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/8616")] [CompilerTrait(CompilerFeature.LocalFunctions)] - public async Task TestLocalFunction7(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestLocalFunction7(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"static $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -415,5 +352,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/BaseKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/BaseKeywordRecommenderTests.cs index 09b652972919c..77f2faf51a64f 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/BaseKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/BaseKeywordRecommenderTests.cs @@ -14,143 +14,112 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class BaseKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotInTopLevelMethod() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotInTopLevelMethod() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ void Goo() { $$ } """); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGlobalStatement() + => VerifyAbsenceAsync( """ System.Console.WriteLine(); $$ """, options: CSharp9ParseOptions); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGlobalVariableDeclaration() + => VerifyAbsenceAsync( """ int i = 0; $$ """, options: CSharp9ParseOptions); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestInClassConstructorInitializer() - { - await VerifyKeywordAsync( + public Task TestInClassConstructorInitializer() + => VerifyKeywordAsync( """ class C { public C() : $$ """); - } [Fact] - public async Task TestInRecordConstructorInitializer() - { - // The recommender doesn't work in record in script - // Tracked by https://github.com/dotnet/roslyn/issues/44865 - await VerifyWorkerAsync(""" + public Task TestInRecordConstructorInitializer() + => VerifyWorkerAsync(""" record C { public C() : $$ """, absent: false, options: TestOptions.RegularPreview); - } [Fact] - public async Task TestNotInStaticClassConstructorInitializer() - { - await VerifyAbsenceAsync( + public Task TestNotInStaticClassConstructorInitializer() + => VerifyAbsenceAsync( """ class C { static C() : $$ """); - } [Fact] - public async Task TestNotInStructConstructorInitializer() - { - await VerifyAbsenceAsync( + public Task TestNotInStructConstructorInitializer() + => VerifyAbsenceAsync( """ struct C { public C() : $$ """); - } [Fact] - public async Task TestAfterCast() - { - await VerifyKeywordAsync( + public Task TestAfterCast() + => VerifyKeywordAsync( """ struct C { new internal ErrorCode Code { get { return (ErrorCode)$$ """); - } [Fact] - public async Task TestInEmptyMethod() - { - await VerifyKeywordAsync( + public Task TestInEmptyMethod() + => VerifyKeywordAsync( SourceCodeKind.Regular, AddInsideMethod( @"$$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] - public async Task TestNotInEnumMemberInitializer1() - { - await VerifyAbsenceAsync( + public Task TestNotInEnumMemberInitializer1() + => VerifyAbsenceAsync( """ enum E { a = $$ } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -158,141 +127,116 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/16335")] - public async Task InExpressionBodyAccessor() - { - await VerifyKeywordAsync(""" + public Task InExpressionBodyAccessor() + => VerifyKeywordAsync(""" class B { public virtual int T { get => bas$$ } } """); - } [Fact] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/BoolKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/BoolKeywordRecommenderTests.cs index 4f2c88f30967b..6111a7a6ea449 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/BoolKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/BoolKeywordRecommenderTests.cs @@ -13,715 +13,552 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class BoolKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot() - { - await VerifyKeywordAsync( + public Task TestAtRoot() + => VerifyKeywordAsync( @"$$", options: CSharp9ParseOptions); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """, options: CSharp9ParseOptions); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalVariableDeclaration() + => VerifyKeywordAsync( """ int i = 0; $$ """, options: CSharp9ParseOptions); - } [Fact] - public async Task TestNotInUsing() - { - await VerifyAbsenceAsync( + public Task TestNotInUsing() + => VerifyAbsenceAsync( @"using $$"); - } [Fact] - public async Task TesInUsingAlias() - { - await VerifyKeywordAsync( + public Task TesInUsingAlias() + => VerifyKeywordAsync( @"using Goo = $$"); - } [Fact] - public async Task TestInGlobalUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInGlobalUsingAlias() + => VerifyKeywordAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestAfterStackAlloc() - { - await VerifyKeywordAsync( + public Task TestAfterStackAlloc() + => VerifyKeywordAsync( """ class C { int* goo = stackalloc $$ """); - } [Theory, CombinatorialData] - public async Task TestInFixedStatement(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFixedStatement(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"fixed ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestAfterConstInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterConstInMemberContext() + => VerifyKeywordAsync( """ class C { const $$ """); - } [Fact] - public async Task TestAfterRefInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefInMemberContext() + => VerifyKeywordAsync( """ class C { ref $$ """); - } [Fact] - public async Task TestAfterRefReadonlyInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyInMemberContext() + => VerifyKeywordAsync( """ class C { ref readonly $$ """); - } [Theory, CombinatorialData] - public async Task TestAfterConstInStatementContext(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstInStatementContext(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"const $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterRefInStatementContext(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefInStatementContext(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"ref $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterRefReadonlyInStatementContext(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyInStatementContext(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterConstLocalDeclaration(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstLocalDeclaration(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterRefLocalDeclaration(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalDeclaration(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterRefReadonlyLocalDeclaration(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalDeclaration(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterRefLocalFunction(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalFunction(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterRefReadonlyLocalFunction(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalFunction(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterRefExpression(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInEmptyStatement(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestNotEnumBaseTypes() - { - await VerifyAbsenceAsync( + public Task TestNotEnumBaseTypes() + => VerifyAbsenceAsync( @"enum E : $$"); - } [Theory, CombinatorialData] - public async Task TestInGenericType1(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType1(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"IList<$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInGenericType2(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType2(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList,$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestNotInBaseList() - { - await VerifyAbsenceAsync( + public Task TestNotInBaseList() + => VerifyAbsenceAsync( @"class C : $$"); - } [Fact] - public async Task TestInGenericType_InBaseList() - { - await VerifyKeywordAsync( + public Task TestInGenericType_InBaseList() + => VerifyKeywordAsync( @"class C : IList<$$"); - } [Theory, CombinatorialData] - public async Task TestAfterIs(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIs(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterAs(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterAs(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync( + public Task TestInsideInterface() + => VerifyKeywordAsync( """ interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact] - public async Task TestAfterNestedPartial() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPartial() + => VerifyKeywordAsync( """ class C { partial $$ """); - } [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] - public async Task TestAfterNestedStaticPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticPublic() + => VerifyKeywordAsync( """ class C { static public $$ """); - } [Fact] - public async Task TestAfterNestedPublicStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublicStatic() + => VerifyKeywordAsync( """ class C { public static $$ """); - } [Fact] - public async Task TestAfterVirtualPublic() - { - await VerifyKeywordAsync( + public Task TestAfterVirtualPublic() + => VerifyKeywordAsync( """ class C { virtual public $$ """); - } [Fact] - public async Task TestAfterNestedPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublic() + => VerifyKeywordAsync( """ class C { public $$ """); - } [Fact] - public async Task TestAfterNestedPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPrivate() + => VerifyKeywordAsync( """ class C { private $$ """); - } [Fact] - public async Task TestAfterNestedProtected() - { - await VerifyKeywordAsync( + public Task TestAfterNestedProtected() + => VerifyKeywordAsync( """ class C { protected $$ """); - } [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] - public async Task TestAfterNestedStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStatic() + => VerifyKeywordAsync( """ class C { static $$ """); - } [Fact] - public async Task TestInLocalVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLocalVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Theory, CombinatorialData] - public async Task TestInForVariableDeclaration(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForVariableDeclaration(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"for ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInForeachVariableDeclaration(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForeachVariableDeclaration(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"foreach ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInUsingVariableDeclaration(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInUsingVariableDeclaration(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"using ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInFromVariableDeclaration(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFromVariableDeclaration(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"var q = from $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInJoinVariableDeclaration(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInJoinVariableDeclaration(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ var q = from a in b join $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestAfterMethodOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterMethodOpenParen() + => VerifyKeywordAsync( """ class C { void Goo($$ """); - } [Fact] - public async Task TestAfterMethodComma() - { - await VerifyKeywordAsync( + public Task TestAfterMethodComma() + => VerifyKeywordAsync( """ class C { void Goo(int i, $$ """); - } [Fact] - public async Task TestAfterIndexerBracket() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracket() + => VerifyKeywordAsync( """ class C { int this[$$ """); - } [Fact] - public async Task TestAfterIndexerBracketComma() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracketComma() + => VerifyKeywordAsync( """ class C { int this[int i, $$ """); - } [Fact] - public async Task TestAfterMethodAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterMethodAttribute() + => VerifyKeywordAsync( """ class C { void Goo(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterConstructorOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorOpenParen() + => VerifyKeywordAsync( """ class C { public C($$ """); - } [Fact] - public async Task TestAfterConstructorComma() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorComma() + => VerifyKeywordAsync( """ class C { public C(int i, $$ """); - } [Fact] - public async Task TestAfterConstructorAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorAttribute() + => VerifyKeywordAsync( """ class C { public C(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterDelegateOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateOpenParen() + => VerifyKeywordAsync( @"delegate void D($$"); - } [Fact] - public async Task TestAfterDelegateComma() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateComma() + => VerifyKeywordAsync( @"delegate void D(int i, $$"); - } [Fact] - public async Task TestAfterDelegateAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateAttribute() + => VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); - } [Fact] - public async Task TestAfterThis() - { - await VerifyKeywordAsync( + public Task TestAfterThis() + => VerifyKeywordAsync( """ static class C { public static void Goo(this $$ """); - } [Fact] - public async Task TestAfterRef() - { - await VerifyKeywordAsync( + public Task TestAfterRef() + => VerifyKeywordAsync( """ class C { void Goo(ref $$ """); - } [Fact] - public async Task TestAfterOut() - { - await VerifyKeywordAsync( + public Task TestAfterOut() + => VerifyKeywordAsync( """ class C { void Goo(out $$ """); - } [Fact] - public async Task TestAfterLambdaRef() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaRef() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (ref $$ """); - } [Fact] - public async Task TestAfterLambdaOut() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaOut() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (out $$ """); - } [Fact] - public async Task TestAfterParams() - { - await VerifyKeywordAsync( + public Task TestAfterParams() + => VerifyKeywordAsync( """ class C { void Goo(params $$ """); - } [Fact] - public async Task TestInImplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInImplicitOperator() + => VerifyKeywordAsync( """ class C { public static implicit operator $$ """); - } [Fact] - public async Task TestInExplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInExplicitOperator() + => VerifyKeywordAsync( """ class C { public static explicit operator $$ """); - } [Theory, CombinatorialData] - public async Task TestAfterNewInExpression(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterNewInExpression(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"new $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInCastType(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInCastType2(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType2(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestInDelegateReturnType() - { - await VerifyKeywordAsync( + public Task TestInDelegateReturnType() + => VerifyKeywordAsync( @"public delegate $$"); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [CombinatorialData] - public async Task TestInTypeOf(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInTypeOf(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"typeof($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [CombinatorialData] - public async Task TestInDefault(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDefault(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"default($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [CombinatorialData] - public async Task TestInSizeOf(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInSizeOf(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"sizeof($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -729,12 +566,10 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] - public async Task TestInCrefContext() - { - await VerifyKeywordAsync(""" + public Task TestInCrefContext() + => VerifyKeywordAsync(""" class Program { /// @@ -744,16 +579,13 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] - public async Task TestInCrefContextNotAfterDot() - { - await VerifyAbsenceAsync(""" + public Task TestInCrefContextNotAfterDot() + => VerifyAbsenceAsync(""" /// class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] public async Task TestNotAfterAsync() @@ -764,19 +596,16 @@ public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1468")] - public async Task TestNotInCrefTypeParameter() - { - await VerifyAbsenceAsync(""" + public Task TestNotInCrefTypeParameter() + => VerifyAbsenceAsync(""" using System; /// class C { } """); - } [Fact] - public async Task Preselection() - { - await VerifyKeywordAsync(""" + public Task Preselection() + => VerifyKeywordAsync(""" class Program { static void Main(string[] args) @@ -786,101 +615,81 @@ static void Main(string[] args) static void Helper(bool x) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinType() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinType() + => VerifyKeywordAsync(""" class Program { ($$ } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] [CombinatorialData] - public async Task TestInTupleWithinMember(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInTupleWithinMember(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestInFunctionPointerType() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerType() + => VerifyKeywordAsync(""" class C { delegate*<$$ """); - } [Fact] - public async Task TestInFunctionPointerTypeAfterComma() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerTypeAfterComma() + => VerifyKeywordAsync(""" class C { delegate* VerifyKeywordAsync(""" class C { delegate* VerifyAbsenceAsync(""" class C { delegate*$$ """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/53585")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithoutAsync))] - public async Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) - { - await VerifyKeywordAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) + => VerifyKeywordAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithAsync))] - public async Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) - { - await VerifyAbsenceAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) + => VerifyAbsenceAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64585")] - public async Task TestAfterRequired() - { - await VerifyKeywordAsync(""" + public Task TestAfterRequired() + => VerifyKeywordAsync(""" class C { required $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefAtTopLevel1() + => VerifyKeywordAsync( @"ref $$"); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [CombinatorialData] @@ -901,216 +710,183 @@ await VerifyAbsenceAsync( } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefReadonlyAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyAtTopLevel1() + => VerifyKeywordAsync( @"ref readonly $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { readonly $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref readonly $$ } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref $$ -}}"); - } + public Task TestAfterRefInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - readonly $$ -}}"); - } + public Task TestAfterReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + readonly $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref readonly $$ -}}"); - } + public Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref readonly $$ + } + """); #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -1120,5 +896,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/BreakKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/BreakKeywordRecommenderTests.cs index 2d9f81aebd40b..280d544906ec3 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/BreakKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/BreakKeywordRecommenderTests.cs @@ -12,193 +12,154 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class BreakKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot() - { - await VerifyAbsenceAsync( + public Task TestNotAtRoot() + => VerifyAbsenceAsync( @"$$", options: CSharp9ParseOptions); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGlobalStatement() + => VerifyAbsenceAsync( """ System.Console.WriteLine(); $$ """, options: CSharp9ParseOptions); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGlobalVariableDeclaration() + => VerifyAbsenceAsync( """ int i = 0; $$ """, options: CSharp9ParseOptions); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Theory, CombinatorialData] - public async Task TestEmptyStatement(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestEmptyStatement(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( @"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestBeforeStatement(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestBeforeStatement(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( """ $$ return true; """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterStatement(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestAfterStatement(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( """ return true; $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterBlock(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestAfterBlock(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( """ if (true) { } $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterIf(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestAfterIf(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( """ if (true) $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterDo(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterDo(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ do $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterWhile(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterWhile(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ while (true) $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterFor(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterFor(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ for (int i = 0; i < 10; i++) $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterForeach(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterForeach(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ foreach (var v in bar) $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestNotInsideLambda(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInsideLambda(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( """ foreach (var v in bar) { var d = () => { $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestNotInsideAnonymousMethod(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInsideAnonymousMethod(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( """ foreach (var v in bar) { var d = delegate { $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInsideSwitch(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideSwitch(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ switch (a) { case 0: $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestNotInsideSwitchWithLambda(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInsideSwitchWithLambda(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( """ switch (a) { case 0: var d = () => { $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInsideSwitchOutsideLambda(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideSwitchOutsideLambda(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ switch (a) { case 0: @@ -206,37 +167,29 @@ await VerifyKeywordAsync(AddInsideMethod( }; $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestNotAfterBreak(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterBreak(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( @"break $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestNotInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotInClass() + => VerifyAbsenceAsync(""" class C { $$ } """); - } [Theory, CombinatorialData] - public async Task TestAfterYield(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterYield(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"yield $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterSwitchInSwitch(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterSwitchInSwitch(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { default: @@ -244,12 +197,10 @@ await VerifyKeywordAsync(AddInsideMethod( } $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterBlockInSwitch(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBlockInSwitch(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { default: @@ -257,5 +208,4 @@ await VerifyKeywordAsync(AddInsideMethod( } $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ByKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ByKeywordRecommenderTests.cs index 966767f926bb3..6f5a212a6cf1f 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ByKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ByKeywordRecommenderTests.cs @@ -12,90 +12,70 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ByKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot() - { - await VerifyAbsenceAsync( + public Task TestNotAtRoot() + => VerifyAbsenceAsync( @"$$", options: CSharp9ParseOptions); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGlobalStatement() + => VerifyAbsenceAsync( """ System.Console.WriteLine(); $$ """, options: CSharp9ParseOptions); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGlobalVariableDeclaration() + => VerifyAbsenceAsync( """ int i = 0; $$ """, options: CSharp9ParseOptions); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Theory, CombinatorialData] - public async Task TestNotInEmptyStatement(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( @"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterGroupExpr(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterGroupExpr(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y group a $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestNotAfterGroup(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterGroup(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y group $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestNotAfterBy(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterBy(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y group a by $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ByteKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ByteKeywordRecommenderTests.cs index 6d84c5e1813c8..07be79ac1693f 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ByteKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ByteKeywordRecommenderTests.cs @@ -13,715 +13,552 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ByteKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot() - { - await VerifyKeywordAsync( + public Task TestAtRoot() + => VerifyKeywordAsync( @"$$", options: CSharp9ParseOptions); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """, options: CSharp9ParseOptions); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalVariableDeclaration() + => VerifyKeywordAsync( """ int i = 0; $$ """, options: CSharp9ParseOptions); - } [Fact] - public async Task TestNotInUsing() - { - await VerifyAbsenceAsync( + public Task TestNotInUsing() + => VerifyAbsenceAsync( @"using $$"); - } [Fact] - public async Task TestInUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInUsingAlias() + => VerifyKeywordAsync( @"using Goo = $$"); - } [Fact] - public async Task TestInGlobalUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInGlobalUsingAlias() + => VerifyKeywordAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestAfterStackAlloc() - { - await VerifyKeywordAsync( + public Task TestAfterStackAlloc() + => VerifyKeywordAsync( """ class C { int* goo = stackalloc $$ """); - } [Theory, CombinatorialData] - public async Task TestInFixedStatement(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFixedStatement(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"fixed ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestInDelegateReturnType() - { - await VerifyKeywordAsync( + public Task TestInDelegateReturnType() + => VerifyKeywordAsync( @"public delegate $$"); - } [Theory, CombinatorialData] - public async Task TestInCastType(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInCastType2(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType2(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestAfterConstInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterConstInMemberContext() + => VerifyKeywordAsync( """ class C { const $$ """); - } [Fact] - public async Task TestAfterRefInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefInMemberContext() + => VerifyKeywordAsync( """ class C { ref $$ """); - } [Fact] - public async Task TestAfterRefReadonlyInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyInMemberContext() + => VerifyKeywordAsync( """ class C { ref readonly $$ """); - } [Theory, CombinatorialData] - public async Task TestAfterConstInStatementContext(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstInStatementContext(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"const $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterRefInStatementContext(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefInStatementContext(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"ref $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterRefReadonlyInStatementContext(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyInStatementContext(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterConstLocalDeclaration(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstLocalDeclaration(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterRefLocalDeclaration(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalDeclaration(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterRefReadonlyLocalDeclaration(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalDeclaration(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterRefLocalFunction(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalFunction(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterRefReadonlyLocalFunction(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalFunction(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterRefExpression(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInEmptyStatement(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestEnumBaseTypes() - { - await VerifyKeywordAsync( + public Task TestEnumBaseTypes() + => VerifyKeywordAsync( @"enum E : $$"); - } [Theory, CombinatorialData] - public async Task TestInGenericType1(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType1(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"IList<$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInGenericType2(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType2(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList,$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestNotInBaseList() - { - await VerifyAbsenceAsync( + public Task TestNotInBaseList() + => VerifyAbsenceAsync( @"class C : $$"); - } [Fact] - public async Task TestInGenericType_InBaseList() - { - await VerifyKeywordAsync( + public Task TestInGenericType_InBaseList() + => VerifyKeywordAsync( @"class C : IList<$$"); - } [Theory, CombinatorialData] - public async Task TestAfterIs(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIs(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterAs(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterAs(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync( + public Task TestInsideInterface() + => VerifyKeywordAsync( """ interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact] - public async Task TestAfterNestedPartial() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPartial() + => VerifyKeywordAsync( """ class C { partial $$ """); - } [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] - public async Task TestAfterNestedStaticPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticPublic() + => VerifyKeywordAsync( """ class C { static public $$ """); - } [Fact] - public async Task TestAfterNestedPublicStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublicStatic() + => VerifyKeywordAsync( """ class C { public static $$ """); - } [Fact] - public async Task TestAfterVirtualPublic() - { - await VerifyKeywordAsync( + public Task TestAfterVirtualPublic() + => VerifyKeywordAsync( """ class C { virtual public $$ """); - } [Fact] - public async Task TestAfterNestedPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublic() + => VerifyKeywordAsync( """ class C { public $$ """); - } [Fact] - public async Task TestAfterNestedPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPrivate() + => VerifyKeywordAsync( """ class C { private $$ """); - } [Fact] - public async Task TestAfterNestedProtected() - { - await VerifyKeywordAsync( + public Task TestAfterNestedProtected() + => VerifyKeywordAsync( """ class C { protected $$ """); - } [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] - public async Task TestAfterNestedStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStatic() + => VerifyKeywordAsync( """ class C { static $$ """); - } [Theory, CombinatorialData] - public async Task TestInLocalVariableDeclaration(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLocalVariableDeclaration(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInForVariableDeclaration(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForVariableDeclaration(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"for ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInForeachVariableDeclaration(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForeachVariableDeclaration(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"foreach ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInUsingVariableDeclaration(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInUsingVariableDeclaration(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"using ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInFromVariableDeclaration(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFromVariableDeclaration(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"var q = from $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInJoinVariableDeclaration(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInJoinVariableDeclaration(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ var q = from a in b join $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestAfterMethodOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterMethodOpenParen() + => VerifyKeywordAsync( """ class C { void Goo($$ """); - } [Fact] - public async Task TestAfterMethodComma() - { - await VerifyKeywordAsync( + public Task TestAfterMethodComma() + => VerifyKeywordAsync( """ class C { void Goo(int i, $$ """); - } [Fact] - public async Task TestAfterMethodAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterMethodAttribute() + => VerifyKeywordAsync( """ class C { void Goo(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterConstructorOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorOpenParen() + => VerifyKeywordAsync( """ class C { public C($$ """); - } [Fact] - public async Task TestAfterConstructorComma() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorComma() + => VerifyKeywordAsync( """ class C { public C(int i, $$ """); - } [Fact] - public async Task TestAfterConstructorAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorAttribute() + => VerifyKeywordAsync( """ class C { public C(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterDelegateOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateOpenParen() + => VerifyKeywordAsync( @"delegate void D($$"); - } [Fact] - public async Task TestAfterDelegateComma() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateComma() + => VerifyKeywordAsync( @"delegate void D(int i, $$"); - } [Fact] - public async Task TestAfterDelegateAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateAttribute() + => VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); - } [Fact] - public async Task TestAfterThis() - { - await VerifyKeywordAsync( + public Task TestAfterThis() + => VerifyKeywordAsync( """ static class C { public static void Goo(this $$ """); - } [Fact] - public async Task TestAfterRef() - { - await VerifyKeywordAsync( + public Task TestAfterRef() + => VerifyKeywordAsync( """ class C { void Goo(ref $$ """); - } [Fact] - public async Task TestAfterOut() - { - await VerifyKeywordAsync( + public Task TestAfterOut() + => VerifyKeywordAsync( """ class C { void Goo(out $$ """); - } [Fact] - public async Task TestAfterLambdaRef() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaRef() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (ref $$ """); - } [Fact] - public async Task TestAfterLambdaOut() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaOut() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (out $$ """); - } [Fact] - public async Task TestAfterParams() - { - await VerifyKeywordAsync( + public Task TestAfterParams() + => VerifyKeywordAsync( """ class C { void Goo(params $$ """); - } [Fact] - public async Task TestInImplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInImplicitOperator() + => VerifyKeywordAsync( """ class C { public static implicit operator $$ """); - } [Fact] - public async Task TestInExplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInExplicitOperator() + => VerifyKeywordAsync( """ class C { public static explicit operator $$ """); - } [Fact] - public async Task TestAfterIndexerBracket() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracket() + => VerifyKeywordAsync( """ class C { int this[$$ """); - } [Fact] - public async Task TestAfterIndexerBracketComma() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracketComma() + => VerifyKeywordAsync( """ class C { int this[int i, $$ """); - } [Theory, CombinatorialData] - public async Task TestAfterNewInExpression(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterNewInExpression(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"new $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [CombinatorialData] - public async Task TestInTypeOf(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInTypeOf(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"typeof($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [CombinatorialData] - public async Task TestInDefault(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDefault(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"default($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [CombinatorialData] - public async Task TestInSizeOf(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInSizeOf(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"sizeof($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -729,12 +566,10 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] - public async Task TestInCrefContext() - { - await VerifyKeywordAsync(""" + public Task TestInCrefContext() + => VerifyKeywordAsync(""" class Program { /// @@ -744,16 +579,13 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] - public async Task TestInCrefContextNotAfterDot() - { - await VerifyAbsenceAsync(""" + public Task TestInCrefContextNotAfterDot() + => VerifyAbsenceAsync(""" /// class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] public async Task TestNotAfterAsync() @@ -764,19 +596,16 @@ public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1468")] - public async Task TestNotInCrefTypeParameter() - { - await VerifyAbsenceAsync(""" + public Task TestNotInCrefTypeParameter() + => VerifyAbsenceAsync(""" using System; /// class C { } """); - } [Fact] - public async Task Preselection() - { - await VerifyKeywordAsync(""" + public Task Preselection() + => VerifyKeywordAsync(""" class Program { static void Main(string[] args) @@ -786,101 +615,81 @@ static void Main(string[] args) static void Helper(byte x) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinType() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinType() + => VerifyKeywordAsync(""" class Program { ($$ } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] [CombinatorialData] - public async Task TestInTupleWithinMember(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInTupleWithinMember(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestInFunctionPointerType() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerType() + => VerifyKeywordAsync(""" class C { delegate*<$$ """); - } [Fact] - public async Task TestInFunctionPointerTypeAfterComma() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerTypeAfterComma() + => VerifyKeywordAsync(""" class C { delegate* VerifyKeywordAsync(""" class C { delegate* VerifyAbsenceAsync(""" class C { delegate*$$ """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/53585")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithoutAsync))] - public async Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) - { - await VerifyKeywordAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) + => VerifyKeywordAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithAsync))] - public async Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) - { - await VerifyAbsenceAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) + => VerifyAbsenceAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64585")] - public async Task TestAfterRequired() - { - await VerifyKeywordAsync(""" + public Task TestAfterRequired() + => VerifyKeywordAsync(""" class C { required $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefAtTopLevel1() + => VerifyKeywordAsync( @"ref $$"); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [CombinatorialData] @@ -901,216 +710,183 @@ await VerifyAbsenceAsync( } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefReadonlyAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyAtTopLevel1() + => VerifyKeywordAsync( @"ref readonly $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { readonly $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref readonly $$ } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref $$ -}}"); - } + public Task TestAfterRefInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - readonly $$ -}}"); - } + public Task TestAfterReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + readonly $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref readonly $$ -}}"); - } + public Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref readonly $$ + } + """); #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -1120,5 +896,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/CaseKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/CaseKeywordRecommenderTests.cs index 9f2bef0cd0d83..38e61b4437616 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/CaseKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/CaseKeywordRecommenderTests.cs @@ -12,148 +12,117 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class CaseKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestNotAfterExpr() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterExpr() + => VerifyAbsenceAsync(AddInsideMethod( @"var q = goo $$")); - } [Fact] - public async Task TestNotAfterDottedName() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterDottedName() + => VerifyAbsenceAsync(AddInsideMethod( @"var q = goo.Current $$")); - } [Fact] - public async Task TestAfterSwitch() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterSwitch() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { $$ """)); - } [Fact] - public async Task TestAfterCase() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterCase() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { case 0: $$ """)); - } [Fact] - public async Task TestAfterDefault() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterDefault() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { default: $$ """)); - } [Fact] - public async Task TestAfterPatternCase() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterPatternCase() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { case String s: $$ """)); - } [Fact] - public async Task TestAfterOneStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterOneStatement() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { default: Console.WriteLine(); $$ """)); - } [Fact] - public async Task TestAfterOneStatementPatternCase() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterOneStatementPatternCase() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { case String s: Console.WriteLine(); $$ """)); - } [Fact] - public async Task TestAfterTwoStatements() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterTwoStatements() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { default: @@ -161,36 +130,30 @@ await VerifyKeywordAsync(AddInsideMethod( Console.WriteLine(); $$ """)); - } [Fact] - public async Task TestAfterBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBlock() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { default: { } $$ """)); - } [Fact] - public async Task TestAfterBlockPatternCase() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBlockPatternCase() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { case String s: { } $$ """)); - } [Fact] - public async Task TestAfterIfElse() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIfElse() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { default: @@ -199,35 +162,29 @@ await VerifyKeywordAsync(AddInsideMethod( } $$ """)); - } [Fact] - public async Task TestNotAfterIncompleteStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterIncompleteStatement() + => VerifyAbsenceAsync(AddInsideMethod( """ switch (expr) { default: Console.WriteLine( $$ """)); - } [Fact] - public async Task TestNotInsideBlock() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInsideBlock() + => VerifyAbsenceAsync(AddInsideMethod( """ switch (expr) { default: { $$ """)); - } [Fact] - public async Task TestAfterIf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIf() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { default: @@ -235,24 +192,20 @@ await VerifyKeywordAsync(AddInsideMethod( Console.WriteLine(); $$ """)); - } [Fact] - public async Task TestNotAfterIf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterIf() + => VerifyAbsenceAsync(AddInsideMethod( """ switch (expr) { default: if (goo) $$ """)); - } [Fact] - public async Task TestAfterWhile() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterWhile() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { default: @@ -260,23 +213,18 @@ await VerifyKeywordAsync(AddInsideMethod( } $$ """)); - } [Fact] - public async Task TestAfterGotoInSwitch() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterGotoInSwitch() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { default: goto $$ """)); - } [Fact] - public async Task TestNotAfterGotoOutsideSwitch() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterGotoOutsideSwitch() + => VerifyAbsenceAsync(AddInsideMethod( @"goto $$")); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/CatchKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/CatchKeywordRecommenderTests.cs index 97c545d9e91a7..c01b54e70be1c 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/CatchKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/CatchKeywordRecommenderTests.cs @@ -12,106 +12,83 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class CatchKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterTry() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterTry() + => VerifyKeywordAsync(AddInsideMethod( """ try { } $$ """)); - } [Fact] - public async Task TestAfterTryCatch() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterTryCatch() + => VerifyKeywordAsync(AddInsideMethod( """ try { } catch { } $$ """)); - } [Fact] - public async Task TestNotAfterFinally() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterFinally() + => VerifyAbsenceAsync(AddInsideMethod( """ try { } finally { } $$ """)); - } [Fact] - public async Task TestNotInStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestNotAfterBlock() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterBlock() + => VerifyAbsenceAsync(AddInsideMethod( """ if (true) { @@ -119,25 +96,20 @@ await VerifyAbsenceAsync(AddInsideMethod( } $$ """)); - } [Fact] - public async Task TestNotAfterCatch() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterCatch() + => VerifyAbsenceAsync(AddInsideMethod( """ try { } catch $$ """)); - } [Fact] - public async Task TestNotInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotInClass() + => VerifyAbsenceAsync(""" class C { $$ } """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/CharKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/CharKeywordRecommenderTests.cs index cbfe7b645ee36..bc840ffcbc11d 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/CharKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/CharKeywordRecommenderTests.cs @@ -12,716 +12,553 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class CharKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsing() - { - await VerifyAbsenceAsync( + public Task TestNotInUsing() + => VerifyAbsenceAsync( @"using $$"); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestInUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInUsingAlias() + => VerifyKeywordAsync( @"using Goo = $$"); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestInGlobalUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInGlobalUsingAlias() + => VerifyKeywordAsync( @"global using Goo = $$"); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterStackAlloc() - { - await VerifyKeywordAsync( + public Task TestAfterStackAlloc() + => VerifyKeywordAsync( """ class C { int* goo = stackalloc $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestInFixedStatement() - { - await VerifyKeywordAsync( + public Task TestInFixedStatement() + => VerifyKeywordAsync( @"fixed ($$"); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestInDelegateReturnType() - { - await VerifyKeywordAsync( + public Task TestInDelegateReturnType() + => VerifyKeywordAsync( @"public delegate $$"); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestInCastType() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestInCastType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType2() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterConstInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterConstInMemberContext() + => VerifyKeywordAsync( """ class C { const $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterRefInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefInMemberContext() + => VerifyKeywordAsync( """ class C { ref $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterRefReadonlyInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyInMemberContext() + => VerifyKeywordAsync( """ class C { ref readonly $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterConstInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"const $$")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterRefInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterRefReadonlyInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterConstLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterRefLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterRefReadonlyLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterRefLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterRefReadonlyLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestInEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestNotInEnumBaseTypes() - { - await VerifyAbsenceAsync( + public Task TestNotInEnumBaseTypes() + => VerifyAbsenceAsync( @"enum E : $$"); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestInGenericType1() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType1() + => VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestInGenericType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType2() + => VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList,$$")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestNotInBaseList() - { - await VerifyAbsenceAsync( + public Task TestNotInBaseList() + => VerifyAbsenceAsync( @"class C : $$"); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestInGenericType_InBaseList() - { - await VerifyKeywordAsync( + public Task TestInGenericType_InBaseList() + => VerifyKeywordAsync( @"class C : IList<$$"); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterIs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterAs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterAs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync( + public Task TestInsideInterface() + => VerifyKeywordAsync( """ interface I { $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterNestedPartial() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPartial() + => VerifyKeywordAsync( """ class C { partial $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterNestedStaticPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticPublic() + => VerifyKeywordAsync( """ class C { static public $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterNestedPublicStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublicStatic() + => VerifyKeywordAsync( """ class C { public static $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterVirtualPublic() - { - await VerifyKeywordAsync( + public Task TestAfterVirtualPublic() + => VerifyKeywordAsync( """ class C { virtual public $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterNestedPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublic() + => VerifyKeywordAsync( """ class C { public $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterNestedPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPrivate() + => VerifyKeywordAsync( """ class C { private $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterNestedProtected() - { - await VerifyKeywordAsync( + public Task TestAfterNestedProtected() + => VerifyKeywordAsync( """ class C { protected $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterNestedStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStatic() + => VerifyKeywordAsync( """ class C { static $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestInLocalVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLocalVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestInForVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"for ($$")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestInForeachVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForeachVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestInUsingVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInUsingVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"using ($$")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestInFromVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFromVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestInJoinVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInJoinVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from a in b join $$ """)); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterMethodOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterMethodOpenParen() + => VerifyKeywordAsync( """ class C { void Goo($$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterMethodComma() - { - await VerifyKeywordAsync( + public Task TestAfterMethodComma() + => VerifyKeywordAsync( """ class C { void Goo(int i, $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterMethodAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterMethodAttribute() + => VerifyKeywordAsync( """ class C { void Goo(int i, [Goo]$$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterConstructorOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorOpenParen() + => VerifyKeywordAsync( """ class C { public C($$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterConstructorComma() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorComma() + => VerifyKeywordAsync( """ class C { public C(int i, $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterConstructorAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorAttribute() + => VerifyKeywordAsync( """ class C { public C(int i, [Goo]$$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterDelegateOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateOpenParen() + => VerifyKeywordAsync( @"delegate void D($$"); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterDelegateComma() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateComma() + => VerifyKeywordAsync( @"delegate void D(int i, $$"); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterDelegateAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateAttribute() + => VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterThis() - { - await VerifyKeywordAsync( + public Task TestAfterThis() + => VerifyKeywordAsync( """ static class C { public static void Goo(this $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterRef() - { - await VerifyKeywordAsync( + public Task TestAfterRef() + => VerifyKeywordAsync( """ class C { void Goo(ref $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterOut() - { - await VerifyKeywordAsync( + public Task TestAfterOut() + => VerifyKeywordAsync( """ class C { void Goo(out $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterLambdaRef() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaRef() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (ref $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterLambdaOut() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaOut() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (out $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterParams() - { - await VerifyKeywordAsync( + public Task TestAfterParams() + => VerifyKeywordAsync( """ class C { void Goo(params $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestInImplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInImplicitOperator() + => VerifyKeywordAsync( """ class C { public static implicit operator $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestInExplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInExplicitOperator() + => VerifyKeywordAsync( """ class C { public static explicit operator $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterIndexerBracket() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracket() + => VerifyKeywordAsync( """ class C { int this[$$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterIndexerBracketComma() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracketComma() + => VerifyKeywordAsync( """ class C { int this[int i, $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestAfterNewInExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterNewInExpression() + => VerifyKeywordAsync(AddInsideMethod( @"new $$")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInTypeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInTypeOf() + => VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInDefault() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDefault() + => VerifyKeywordAsync(AddInsideMethod( @"default($$")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInSizeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInSizeOf() + => VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -729,13 +566,11 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] - public async Task TestInCrefContext() - { - await VerifyKeywordAsync(""" + public Task TestInCrefContext() + => VerifyKeywordAsync(""" class Program { /// @@ -745,17 +580,14 @@ static void Main(string[] args) } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] - public async Task TestInCrefContextNotAfterDot() - { - await VerifyAbsenceAsync(""" + public Task TestInCrefContextNotAfterDot() + => VerifyAbsenceAsync(""" /// class C { } """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("https://github.com/dotnet/roslyn/issues/60341")] @@ -769,9 +601,8 @@ public async Task TestNotAfterAsyncAsType() [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/988025")] - public async Task TestInGenericMethodTypeParameterList1() - { - var markup = """ + public Task TestInGenericMethodTypeParameterList1() + => VerifyKeywordAsync(""" class Class1 { public static Class1 Create() { return null; } @@ -789,15 +620,12 @@ static void Main(string[] args) Class1.Create().Test<$$ } } - """; - await VerifyKeywordAsync(markup); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/988025")] - public async Task TestInGenericMethodTypeParameterList2() - { - var markup = """ + public Task TestInGenericMethodTypeParameterList2() + => VerifyKeywordAsync(""" class Class1 { public static Class1 Create() { return null; } @@ -815,25 +643,20 @@ static void Main(string[] args) Class1.Create().Test VerifyAbsenceAsync(""" using System; /// class C { } """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task Preselection() - { - await VerifyKeywordAsync(""" + public Task Preselection() + => VerifyKeywordAsync(""" class Program { static void Main(string[] args) @@ -843,25 +666,21 @@ static void Main(string[] args) static void Helper(char x) { } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinType() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinType() + => VerifyKeywordAsync(""" class Program { ($$ } """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinMember() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinMember() + => VerifyKeywordAsync(""" class Program { void Method() @@ -870,82 +689,66 @@ void Method() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestInFunctionPointerType() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerType() + => VerifyKeywordAsync(""" class C { delegate*<$$ """); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestInFunctionPointerTypeAfterComma() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerTypeAfterComma() + => VerifyKeywordAsync(""" class C { delegate* VerifyKeywordAsync(""" class C { delegate* VerifyAbsenceAsync(""" class C { delegate*$$ """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/53585"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithoutAsync))] - public async Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) - { - await VerifyKeywordAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) + => VerifyKeywordAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/60341"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithAsync))] - public async Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) - { - await VerifyAbsenceAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) + => VerifyAbsenceAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64585")] - public async Task TestAfterRequired() - { - await VerifyKeywordAsync(""" + public Task TestAfterRequired() + => VerifyKeywordAsync(""" class C { required $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefAtTopLevel1() + => VerifyKeywordAsync( @"ref $$"); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [CombinatorialData] @@ -966,216 +769,183 @@ await VerifyAbsenceAsync( } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefReadonlyAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyAtTopLevel1() + => VerifyKeywordAsync( @"ref readonly $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { readonly $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref readonly $$ } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref $$ -}}"); - } + public Task TestAfterRefInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - readonly $$ -}}"); - } + public Task TestAfterReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + readonly $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref readonly $$ -}}"); - } + public Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref readonly $$ + } + """); #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -1185,5 +955,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/CheckedKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/CheckedKeywordRecommenderTests.cs index c906713d6caad..f8919979b2120 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/CheckedKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/CheckedKeywordRecommenderTests.cs @@ -13,102 +13,77 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class CheckedKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInExpression() + => VerifyKeywordAsync(AddInsideMethod( @"var q = $$")); - } [Fact] - public async Task TestNotInPreProcessor() - { - await VerifyAbsenceAsync( + public Task TestNotInPreProcessor() + => VerifyAbsenceAsync( @"#if a || $$"); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInTypeOf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInTypeOf() + => VerifyAbsenceAsync(AddInsideMethod( @"typeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInDefault() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInDefault() + => VerifyAbsenceAsync(AddInsideMethod( @"default($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInSizeOf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInSizeOf() + => VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -116,219 +91,174 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } [Fact] - public async Task TestNotAfterImplicitOperator_01() - { - await VerifyAbsenceAsync( + public Task TestNotAfterImplicitOperator_01() + => VerifyAbsenceAsync( """ class Goo { public static implicit operator $$ """); - } [Fact] - public async Task TestNotAfterImplicitOperator_02() - { - await VerifyAbsenceAsync( + public Task TestNotAfterImplicitOperator_02() + => VerifyAbsenceAsync( """ class Goo { public static implicit operator $$ int (Goo x){} """); - } [Fact] - public async Task TestAfterExplicitOperator_01() - { - await VerifyKeywordAsync( + public Task TestAfterExplicitOperator_01() + => VerifyKeywordAsync( """ class Goo { public static explicit operator $$ """); - } [Fact] - public async Task TestAfterExplicitOperator_02() - { - await VerifyKeywordAsync( + public Task TestAfterExplicitOperator_02() + => VerifyKeywordAsync( """ class Goo { public static explicit /* some comment */ operator $$ """); - } [Fact] - public async Task TestAfterExplicitOperator_03() - { - await VerifyKeywordAsync( + public Task TestAfterExplicitOperator_03() + => VerifyKeywordAsync( """ class Goo { public static explicit operator $$ int (Goo x){} """); - } [Fact] - public async Task TestAfterOperator_01() - { - await VerifyKeywordAsync( + public Task TestAfterOperator_01() + => VerifyKeywordAsync( """ class Goo { public static int operator $$ """); - } [Fact] - public async Task TestAfterOperator_02() - { - await VerifyKeywordAsync( + public Task TestAfterOperator_02() + => VerifyKeywordAsync( """ class Goo { public static int /* some comment */ operator $$ """); - } [Fact] - public async Task TestAfterOperator_03() - { - await VerifyKeywordAsync( + public Task TestAfterOperator_03() + => VerifyKeywordAsync( """ class Goo { public static int operator $$ -(Goo x){} """); - } [Fact] - public async Task TestAfterOperator_04() - { - await VerifyKeywordAsync( + public Task TestAfterOperator_04() + => VerifyKeywordAsync( """ class Goo { public static int operator $$ -(Goo x, Goo y){} """); - } [Fact] - public async Task TestNotAfterOperator() - { - await VerifyAbsenceAsync( + public Task TestNotAfterOperator() + => VerifyAbsenceAsync( @"operator $$"); - } [Fact] - public async Task TestNotAfterImplicitOperator_ExplicitImplementation_01() - { - await VerifyAbsenceAsync( + public Task TestNotAfterImplicitOperator_ExplicitImplementation_01() + => VerifyAbsenceAsync( """ class Goo { public static implicit I1.operator $$ """); - } [Fact] - public async Task TestNotAfterImplicitOperator_ExplicitImplementation_02() - { - await VerifyAbsenceAsync( + public Task TestNotAfterImplicitOperator_ExplicitImplementation_02() + => VerifyAbsenceAsync( """ class Goo { public static implicit I1.operator $$ int (Goo x){} """); - } [Fact] - public async Task TestAfterExplicitOperator_ExplicitImplementation_01() - { - await VerifyKeywordAsync( + public Task TestAfterExplicitOperator_ExplicitImplementation_01() + => VerifyKeywordAsync( """ class Goo { public static explicit I1.operator $$ """); - } [Fact] - public async Task TestAfterExplicitOperator_ExplicitImplementation_02() - { - await VerifyKeywordAsync( + public Task TestAfterExplicitOperator_ExplicitImplementation_02() + => VerifyKeywordAsync( """ class Goo { public static explicit /* some comment */ I1.operator $$ """); - } [Fact] - public async Task TestAfterExplicitOperator_ExplicitImplementation_03() - { - await VerifyKeywordAsync( + public Task TestAfterExplicitOperator_ExplicitImplementation_03() + => VerifyKeywordAsync( """ class Goo { public static explicit I1. /* some comment */ operator $$ """); - } [Fact] - public async Task TestAfterExplicitOperator_ExplicitImplementation_04() - { - await VerifyKeywordAsync( + public Task TestAfterExplicitOperator_ExplicitImplementation_04() + => VerifyKeywordAsync( """ class Goo { public static explicit I1.operator $$ int (Goo x){} """); - } [Fact] - public async Task TestAfterOperator_ExplicitImplementation_01() - { - await VerifyKeywordAsync( + public Task TestAfterOperator_ExplicitImplementation_01() + => VerifyKeywordAsync( """ class Goo { public static int I1.operator $$ """); - } [Fact] - public async Task TestAfterOperator_ExplicitImplementation_02() - { - await VerifyKeywordAsync( + public Task TestAfterOperator_ExplicitImplementation_02() + => VerifyKeywordAsync( """ class Goo { public static int /* some comment */ I1.operator $$ """); - } [Fact] - public async Task TestAfterOperator_ExplicitImplementation_03() - { - await VerifyKeywordAsync( + public Task TestAfterOperator_ExplicitImplementation_03() + => VerifyKeywordAsync( """ class Goo { public static int I1. /* some comment */ operator $$ """); - } [Fact] - public async Task TestAfterOperator_ExplicitImplementation_04() - { - await VerifyKeywordAsync( + public Task TestAfterOperator_ExplicitImplementation_04() + => VerifyKeywordAsync( """ class Goo { public static int I1.operator $$ -(Goo x){} """); - } [Fact] - public async Task TestAfterOperator_ExplicitImplementation_05() - { - await VerifyKeywordAsync( + public Task TestAfterOperator_ExplicitImplementation_05() + => VerifyKeywordAsync( """ class Goo { public static int I1.operator $$ -(Goo x, Goo y){} """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ChecksumKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ChecksumKeywordRecommenderTests.cs index 215bd260733ec..c14ff00ca97ba 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ChecksumKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ChecksumKeywordRecommenderTests.cs @@ -12,81 +12,61 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ChecksumKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterHash() - { - await VerifyAbsenceAsync( + public Task TestAfterHash() + => VerifyAbsenceAsync( @"#$$"); - } [Fact] - public async Task TestAfterHashAndSpace() - { - await VerifyAbsenceAsync( + public Task TestAfterHashAndSpace() + => VerifyAbsenceAsync( @"# $$"); - } [Fact] - public async Task TestAfterPragma() - { - await VerifyKeywordAsync( + public Task TestAfterPragma() + => VerifyKeywordAsync( @"#pragma $$"); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ClassKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ClassKeywordRecommenderTests.cs index 31207bd7c8261..1eb8dae01fd1e 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ClassKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ClassKeywordRecommenderTests.cs @@ -13,541 +13,423 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ClassKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInCompilationUnit() - { - await VerifyKeywordAsync( + public Task TestInCompilationUnit() + => VerifyKeywordAsync( @"$$"); - } [Fact] - public async Task TestAfterExtern() - { - await VerifyKeywordAsync( + public Task TestAfterExtern() + => VerifyKeywordAsync( """ extern alias Goo; $$ """); - } [Fact] - public async Task TestAfterUsing() - { - await VerifyKeywordAsync( + public Task TestAfterUsing() + => VerifyKeywordAsync( """ using Goo; $$ """); - } [Fact] - public async Task TestAfterGlobalUsing() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalUsing() + => VerifyKeywordAsync( """ global using Goo; $$ """); - } [Fact] - public async Task TestAfterNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterNamespace() + => VerifyKeywordAsync( """ namespace N {} $$ """); - } [Fact] - public async Task TestAfterFileScopedNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterFileScopedNamespace() + => VerifyKeywordAsync( """ namespace N; $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestFileKeywordInsideNamespace() - { - await VerifyKeywordAsync( + public Task TestFileKeywordInsideNamespace() + => VerifyKeywordAsync( """ namespace N { file $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestFileKeywordInsideNamespaceBeforeClass() - { - await VerifyKeywordAsync( + public Task TestFileKeywordInsideNamespaceBeforeClass() + => VerifyKeywordAsync( """ namespace N { file $$ class C {} } """); - } [Fact] - public async Task TestAfterTypeDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterTypeDeclaration() + => VerifyKeywordAsync( """ class C {} $$ """); - } [Fact] - public async Task TestAfterDelegateDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateDeclaration() + => VerifyKeywordAsync( """ delegate void Goo(); $$ """); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ global using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeGlobalUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeGlobalUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ global using Goo; """); - } [Fact] - public async Task TestAfterAssemblyAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterAssemblyAttribute() + => VerifyKeywordAsync( """ [assembly: goo] $$ """); - } [Fact] - public async Task TestAfterRootAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterRootAttribute() + => VerifyKeywordAsync( """ [goo] $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync(""" + public Task TestInsideInterface() + => VerifyKeywordAsync(""" interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] - public async Task TestAfterPartial() - { - await VerifyKeywordAsync( + public Task TestAfterPartial() + => VerifyKeywordAsync( @"partial $$"); - } [Fact] - public async Task TestAfterAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterAbstract() + => VerifyKeywordAsync( @"abstract $$"); - } [Fact] - public async Task TestAfterInternal() - { - await VerifyKeywordAsync( + public Task TestAfterInternal() + => VerifyKeywordAsync( @"internal $$"); - } [Fact] - public async Task TestAfterStaticPublic() - { - await VerifyKeywordAsync( + public Task TestAfterStaticPublic() + => VerifyKeywordAsync( @"static public $$"); - } [Fact] - public async Task TestAfterPublicStatic() - { - await VerifyKeywordAsync( + public Task TestAfterPublicStatic() + => VerifyKeywordAsync( @"public static $$"); - } [Fact] public async Task TestNotAfterInvalidPublic() => await VerifyAbsenceAsync(@"virtual public $$"); [Fact] - public async Task TestAfterPublic() - { - await VerifyKeywordAsync( + public Task TestAfterPublic() + => VerifyKeywordAsync( @"public $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestAfterFile() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterFile() + => VerifyKeywordAsync(SourceCodeKind.Regular, @"file $$"); - } [Fact] - public async Task TestAfterPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterPrivate() + => VerifyKeywordAsync( @"private $$"); - } [Fact] - public async Task TestAfterProtected() - { - await VerifyKeywordAsync( + public Task TestAfterProtected() + => VerifyKeywordAsync( @"protected $$"); - } [Fact] - public async Task TestAfterSealed() - { - await VerifyKeywordAsync( + public Task TestAfterSealed() + => VerifyKeywordAsync( @"sealed $$"); - } [Fact] - public async Task TestAfterStatic() - { - await VerifyKeywordAsync( + public Task TestAfterStatic() + => VerifyKeywordAsync( @"static $$"); - } [Fact] - public async Task TestNotAfterStaticInUsingDirective() - { - await VerifyAbsenceAsync( + public Task TestNotAfterStaticInUsingDirective() + => VerifyAbsenceAsync( @"using static $$"); - } [Fact] - public async Task TestNotAfterStaticInGlobalUsingDirective() - { - await VerifyAbsenceAsync( + public Task TestNotAfterStaticInGlobalUsingDirective() + => VerifyAbsenceAsync( @"global using static $$"); - } [Fact] public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32214")] - public async Task TestNotBetweenUsings() - { - // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBetweenUsings() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ using Goo; $$ using Bar; """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32214")] - public async Task TestNotBetweenGlobalUsings_01() - { - // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBetweenGlobalUsings_01() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ global using Goo; $$ using Bar; """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32214")] - public async Task TestNotBetweenGlobalUsings_02() - { - // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBetweenGlobalUsings_02() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ global using Goo; $$ global using Bar; """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TestAfterClassTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterClassTypeParameterConstraint() + => VerifyKeywordAsync( @"class C where T : $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TestNotAfterClassTypeParameterConstraintWhenNotDirectlyInConstraint() - { - await VerifyAbsenceAsync( + public Task TestNotAfterClassTypeParameterConstraintWhenNotDirectlyInConstraint() + => VerifyAbsenceAsync( @"class C where T : IList<$$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TestAfterClassTypeParameterConstraint2() - { - await VerifyKeywordAsync( + public Task TestAfterClassTypeParameterConstraint2() + => VerifyKeywordAsync( """ class C where T : $$ where U : U """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TestNotAfterClassTypeParameterConstraintWhenNotDirectlyInConstraint2() - { - await VerifyAbsenceAsync( + public Task TestNotAfterClassTypeParameterConstraintWhenNotDirectlyInConstraint2() + => VerifyAbsenceAsync( """ class C where T : IList<$$ where U : U """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TestAfterMethodTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterMethodTypeParameterConstraint() + => VerifyKeywordAsync( """ class C { void Goo() where T : $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TestNotAfterMethodTypeParameterConstraintWhenNotDirectlyInConstraint() - { - await VerifyAbsenceAsync( + public Task TestNotAfterMethodTypeParameterConstraintWhenNotDirectlyInConstraint() + => VerifyAbsenceAsync( """ class C { void Goo() where T : IList<$$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TestAfterMethodTypeParameterConstraint2() - { - await VerifyKeywordAsync( + public Task TestAfterMethodTypeParameterConstraint2() + => VerifyKeywordAsync( """ class C { void Goo() where T : $$ where U : T """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TestNotAfterMethodTypeParameterConstraintWhenNotDirectlyInConstraint2() - { - await VerifyAbsenceAsync( + public Task TestNotAfterMethodTypeParameterConstraintWhenNotDirectlyInConstraint2() + => VerifyAbsenceAsync( """ class C { void Goo() where T : IList<$$ where U : T """); - } [Fact] - public async Task TestAfterNew() - { - await VerifyKeywordAsync( + public Task TestAfterNew() + => VerifyKeywordAsync( """ class C { new $$ """); - } [Fact] - public async Task TestAfterRecord() - { - await VerifyKeywordAsync( + public Task TestAfterRecord() + => VerifyKeywordAsync( @"record $$"); - } [Fact] - public async Task TestAfterAttributeFileScopedNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterAttributeFileScopedNamespace() + => VerifyKeywordAsync( @"namespace NS; [Attr] $$"); - } [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -559,5 +441,4 @@ static class C """, CSharpNextParseOptions, CSharpNextScriptParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ConstKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ConstKeywordRecommenderTests.cs index 6a7ebde4d1ef1..ad6594837d2d9 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ConstKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ConstKeywordRecommenderTests.cs @@ -12,240 +12,190 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ConstKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot() - { - await VerifyKeywordAsync( + public Task TestAtRoot() + => VerifyKeywordAsync( @"$$"); - } [Fact] - public async Task TestAfterClass() - { - await VerifyKeywordAsync( + public Task TestAfterClass() + => VerifyKeywordAsync( """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalVariableDeclaration() + => VerifyKeywordAsync( """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Theory, CombinatorialData] - public async Task TestInEmptyStatement(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestAfterExtern() - { - await VerifyKeywordAsync(""" + public Task TestAfterExtern() + => VerifyKeywordAsync(""" extern alias Goo; $$ """); - } [Fact] - public async Task TestAfterUsing() - { - await VerifyKeywordAsync(""" + public Task TestAfterUsing() + => VerifyKeywordAsync(""" using Goo; $$ """); - } [Fact] - public async Task TestAfterGlobalUsing() - { - await VerifyKeywordAsync(""" + public Task TestAfterGlobalUsing() + => VerifyKeywordAsync(""" global using Goo; $$ """); - } [Fact] - public async Task TestAfterNamespace() - { - await VerifyKeywordAsync(""" + public Task TestAfterNamespace() + => VerifyKeywordAsync(""" namespace N {} $$ """); - } [Fact] - public async Task TestAfterDelegateDeclaration() - { - await VerifyKeywordAsync(""" + public Task TestAfterDelegateDeclaration() + => VerifyKeywordAsync(""" delegate void Goo(); $$ """); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Theory] [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script, Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeUsing(SourceCodeKind sourceCodeKind) - { - await VerifyAbsenceAsync(sourceCodeKind, + public Task TestNotBeforeUsing(SourceCodeKind sourceCodeKind) + => VerifyAbsenceAsync(sourceCodeKind, """ $$ using Goo; """); - } [Theory] [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script, Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeGlobalUsing(SourceCodeKind sourceCodeKind) - { - await VerifyAbsenceAsync(sourceCodeKind, + public Task TestNotBeforeGlobalUsing(SourceCodeKind sourceCodeKind) + => VerifyAbsenceAsync(sourceCodeKind, """ $$ global using Goo; """); - } [Fact] - public async Task TestAfterAssemblyAttribute() - { - await VerifyKeywordAsync(""" + public Task TestAfterAssemblyAttribute() + => VerifyKeywordAsync(""" [assembly: goo] $$ """); - } [Fact] - public async Task TestAfterRootAttribute() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, """ + public Task TestAfterRootAttribute() + => VerifyKeywordAsync(SourceCodeKind.Regular, """ [goo] $$ """); - } [Fact] - public async Task TestAfterRootAttribute_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, """ + public Task TestAfterRootAttribute_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ [goo] $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync(""" + public Task TestInsideInterface() + => VerifyKeywordAsync(""" interface I { $$ """); - } [Fact] - public async Task TestNotInsideEnum() - { - await VerifyAbsenceAsync(""" + public Task TestNotInsideEnum() + => VerifyAbsenceAsync(""" enum E { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() @@ -264,14 +214,12 @@ public async Task TestAfterInternal_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"internal $$"); [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] public async Task TestNotAfterPublic() @@ -282,177 +230,144 @@ public async Task TestAfterPublic_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"public $$"); [Fact] - public async Task TestAfterNestedPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublic() + => VerifyKeywordAsync( """ class C { public $$ """); - } [Fact] - public async Task TestNotAfterPrivate() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotAfterPrivate() + => VerifyAbsenceAsync(SourceCodeKind.Regular, @"private $$"); - } [Fact] - public async Task TestAfterPrivate_Script() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterPrivate_Script() + => VerifyKeywordAsync(SourceCodeKind.Script, @"private $$"); - } [Fact] - public async Task TestAfterNestedPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPrivate() + => VerifyKeywordAsync( """ class C { private $$ """); - } [Fact] - public async Task TestNotAfterProtected() - { - await VerifyAbsenceAsync( + public Task TestNotAfterProtected() + => VerifyAbsenceAsync( @"protected $$"); - } [Fact] - public async Task TestAfterNestedProtected() - { - await VerifyKeywordAsync( + public Task TestAfterNestedProtected() + => VerifyKeywordAsync( """ class C { protected $$ """); - } [Fact] public async Task TestNotAfterSealed() => await VerifyAbsenceAsync(@"sealed $$"); [Fact] - public async Task TestNotAfterNestedSealed() - { - await VerifyAbsenceAsync( + public Task TestNotAfterNestedSealed() + => VerifyAbsenceAsync( """ class C { sealed $$ """); - } [Fact] public async Task TestNotAfterStatic() => await VerifyAbsenceAsync(@"static $$"); [Fact] - public async Task TestNotAfterNestedStatic() - { - await VerifyAbsenceAsync( + public Task TestNotAfterNestedStatic() + => VerifyAbsenceAsync( """ class C { static $$ """); - } [Fact] public async Task TestNotAfterStaticPublic() => await VerifyAbsenceAsync(@"static public $$"); [Fact] - public async Task TestNotAfterNestedStaticPublic() - { - await VerifyAbsenceAsync( + public Task TestNotAfterNestedStaticPublic() + => VerifyAbsenceAsync( """ class C { static public $$ """); - } [Fact] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact] - public async Task TestNotAfterEvent() - { - await VerifyAbsenceAsync( + public Task TestNotAfterEvent() + => VerifyAbsenceAsync( """ class C { event $$ """); - } [Fact] - public async Task TestNotAfterConst() - { - await VerifyAbsenceAsync( + public Task TestNotAfterConst() + => VerifyAbsenceAsync( """ class C { const $$ """); - } [Fact] - public async Task TestNotAfterNew() - { - await VerifyAbsenceAsync( + public Task TestNotAfterNew() + => VerifyAbsenceAsync( @"new $$"); - } [Fact] - public async Task TestAfterNestedNew() - { - await VerifyKeywordAsync( + public Task TestAfterNestedNew() + => VerifyKeywordAsync( """ class C { new $$ """); - } [Fact] - public async Task TestInMethod() - { - await VerifyKeywordAsync( + public Task TestInMethod() + => VerifyKeywordAsync( """ class C { void Goo() { $$ """); - } [Fact] - public async Task TestInMethodNotAfterConst() - { - await VerifyAbsenceAsync( + public Task TestInMethodNotAfterConst() + => VerifyAbsenceAsync( """ class C { void Goo() { const $$ """); - } [Fact] - public async Task TestInProperty() - { - await VerifyKeywordAsync( + public Task TestInProperty() + => VerifyKeywordAsync( """ class C { int Goo { get { $$ """); - } [Fact] - public async Task TestWithinExtension() - { - await VerifyAbsenceAsync( + public Task TestWithinExtension() + => VerifyAbsenceAsync( """ static class C { @@ -464,5 +379,4 @@ static class C """, CSharpNextParseOptions, CSharpNextScriptParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ContinueKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ContinueKeywordRecommenderTests.cs index 933f6ba07ddfd..487ded6ebbd52 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ContinueKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ContinueKeywordRecommenderTests.cs @@ -12,204 +12,162 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ContinueKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestBeforeStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestBeforeStatement() + => VerifyAbsenceAsync(AddInsideMethod( """ $$ return true; """)); - } [Fact] - public async Task TestAfterStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestAfterStatement() + => VerifyAbsenceAsync(AddInsideMethod( """ return true; $$ """)); - } [Fact] - public async Task TestAfterBlock() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestAfterBlock() + => VerifyAbsenceAsync(AddInsideMethod( """ if (true) { } $$ """)); - } [Fact] - public async Task TestAfterIf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestAfterIf() + => VerifyAbsenceAsync(AddInsideMethod( """ if (true) $$ """)); - } [Fact] - public async Task TestAfterDo() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterDo() + => VerifyKeywordAsync(AddInsideMethod( """ do $$ """)); - } [Fact] - public async Task TestAfterWhile() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterWhile() + => VerifyKeywordAsync(AddInsideMethod( """ while (true) $$ """)); - } [Fact] - public async Task TestAfterFor() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterFor() + => VerifyKeywordAsync(AddInsideMethod( """ for (int i = 0; i < 10; i++) $$ """)); - } [Fact] - public async Task TestAfterForeach() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterForeach() + => VerifyKeywordAsync(AddInsideMethod( """ foreach (var v in bar) $$ """)); - } [Fact] - public async Task TestNotInsideLambda() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInsideLambda() + => VerifyAbsenceAsync(AddInsideMethod( """ foreach (var v in bar) { var d = () => { $$ """)); - } [Fact] - public async Task TestOutsideLambda() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestOutsideLambda() + => VerifyKeywordAsync(AddInsideMethod( """ foreach (var v in bar) { var d = () => { }; $$ """)); - } [Fact] - public async Task TestNotInsideAnonymousMethod() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInsideAnonymousMethod() + => VerifyAbsenceAsync(AddInsideMethod( """ foreach (var v in bar) { var d = delegate { $$ """)); - } [Fact] - public async Task TestNotInsideSwitch() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInsideSwitch() + => VerifyAbsenceAsync(AddInsideMethod( """ switch (a) { case 0: $$ """)); - } [Fact] - public async Task TestNotAfterContinue() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterContinue() + => VerifyAbsenceAsync(AddInsideMethod( @"continue $$")); - } [Fact] - public async Task TestNotInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotInClass() + => VerifyAbsenceAsync(""" class C { $$ } """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/DecimalKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/DecimalKeywordRecommenderTests.cs index db812f1a43001..723925e52310a 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/DecimalKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/DecimalKeywordRecommenderTests.cs @@ -13,726 +13,559 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class DecimalKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsing() - { - await VerifyAbsenceAsync( + public Task TestNotInUsing() + => VerifyAbsenceAsync( @"using $$"); - } [Fact] - public async Task TestInUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInUsingAlias() + => VerifyKeywordAsync( @"using Goo = $$"); - } [Fact] - public async Task TestInGlobalUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInGlobalUsingAlias() + => VerifyKeywordAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestAfterStackAlloc() - { - await VerifyKeywordAsync( + public Task TestAfterStackAlloc() + => VerifyKeywordAsync( """ class C { int* goo = stackalloc $$ """); - } [Fact] - public async Task TestInFixedStatement() - { - await VerifyKeywordAsync( + public Task TestInFixedStatement() + => VerifyKeywordAsync( @"fixed ($$"); - } [Fact] - public async Task TestInDelegateReturnType() - { - await VerifyKeywordAsync( + public Task TestInDelegateReturnType() + => VerifyKeywordAsync( @"public delegate $$"); - } [Fact] - public async Task TestInCastType() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); - } [Fact] - public async Task TestInCastType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType2() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); - } [Fact] - public async Task TestAfterConstInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterConstInMemberContext() + => VerifyKeywordAsync( """ class C { const $$ """); - } [Fact] - public async Task TestAfterRefInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefInMemberContext() + => VerifyKeywordAsync( """ class C { ref $$ """); - } [Fact] - public async Task TestAfterRefReadonlyInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyInMemberContext() + => VerifyKeywordAsync( """ class C { ref readonly $$ """); - } [Fact] - public async Task TestAfterConstInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"const $$")); - } [Fact] - public async Task TestAfterRefInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$")); - } [Fact] - public async Task TestAfterRefReadonlyInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); - } [Fact] - public async Task TestAfterConstLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); - } [Fact] - public async Task TestAfterRefReadonlyLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); - } [Fact] - public async Task TestAfterRefReadonlyLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); - } [Fact] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } [Fact] - public async Task TestInEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestNotInEnumBaseTypes() - { - await VerifyAbsenceAsync( + public Task TestNotInEnumBaseTypes() + => VerifyAbsenceAsync( @"enum E : $$"); - } [Fact] - public async Task TestInGenericType1() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType1() + => VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); - } [Fact] - public async Task TestInGenericType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType2() + => VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList,$$")); - } [Fact] - public async Task TestNotInBaseList() - { - await VerifyAbsenceAsync( + public Task TestNotInBaseList() + => VerifyAbsenceAsync( @"class C : $$"); - } [Fact] - public async Task TestInGenericType_InBaseList() - { - await VerifyKeywordAsync( + public Task TestInGenericType_InBaseList() + => VerifyKeywordAsync( @"class C : IList<$$"); - } [Fact] - public async Task TestAfterIs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); - } [Fact] - public async Task TestAfterAs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterAs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync( + public Task TestInsideInterface() + => VerifyKeywordAsync( """ interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact] - public async Task TestAfterNestedPartial() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPartial() + => VerifyKeywordAsync( """ class C { partial $$ """); - } [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] - public async Task TestAfterNestedStaticPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticPublic() + => VerifyKeywordAsync( """ class C { static public $$ """); - } [Fact] - public async Task TestAfterNestedPublicStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublicStatic() + => VerifyKeywordAsync( """ class C { public static $$ """); - } [Fact] - public async Task TestAfterVirtualPublic() - { - await VerifyKeywordAsync( + public Task TestAfterVirtualPublic() + => VerifyKeywordAsync( """ class C { virtual public $$ """); - } [Fact] - public async Task TestAfterNestedPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublic() + => VerifyKeywordAsync( """ class C { public $$ """); - } [Fact] - public async Task TestAfterNestedPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPrivate() + => VerifyKeywordAsync( """ class C { private $$ """); - } [Fact] - public async Task TestAfterNestedProtected() - { - await VerifyKeywordAsync( + public Task TestAfterNestedProtected() + => VerifyKeywordAsync( """ class C { protected $$ """); - } [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] - public async Task TestAfterNestedStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStatic() + => VerifyKeywordAsync( """ class C { static $$ """); - } [Fact] - public async Task TestInLocalVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLocalVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInForVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"for ($$")); - } [Fact] - public async Task TestInForeachVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForeachVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); - } [Fact] - public async Task TestInUsingVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInUsingVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"using ($$")); - } [Fact] - public async Task TestInFromVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFromVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); - } [Fact] - public async Task TestInJoinVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInJoinVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from a in b join $$ """)); - } [Fact] - public async Task TestAfterMethodOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterMethodOpenParen() + => VerifyKeywordAsync( """ class C { void Goo($$ """); - } [Fact] - public async Task TestAfterMethodComma() - { - await VerifyKeywordAsync( + public Task TestAfterMethodComma() + => VerifyKeywordAsync( """ class C { void Goo(int i, $$ """); - } [Fact] - public async Task TestAfterMethodAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterMethodAttribute() + => VerifyKeywordAsync( """ class C { void Goo(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterConstructorOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorOpenParen() + => VerifyKeywordAsync( """ class C { public C($$ """); - } [Fact] - public async Task TestAfterConstructorComma() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorComma() + => VerifyKeywordAsync( """ class C { public C(int i, $$ """); - } [Fact] - public async Task TestAfterConstructorAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorAttribute() + => VerifyKeywordAsync( """ class C { public C(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterDelegateOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateOpenParen() + => VerifyKeywordAsync( @"delegate void D($$"); - } [Fact] - public async Task TestAfterDelegateComma() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateComma() + => VerifyKeywordAsync( @"delegate void D(int i, $$"); - } [Fact] - public async Task TestAfterDelegateAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateAttribute() + => VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); - } [Fact] - public async Task TestAfterThis() - { - await VerifyKeywordAsync( + public Task TestAfterThis() + => VerifyKeywordAsync( """ static class C { public static void Goo(this $$ """); - } [Fact] - public async Task TestAfterRef() - { - await VerifyKeywordAsync( + public Task TestAfterRef() + => VerifyKeywordAsync( """ class C { void Goo(ref $$ """); - } [Fact] - public async Task TestAfterOut() - { - await VerifyKeywordAsync( + public Task TestAfterOut() + => VerifyKeywordAsync( """ class C { void Goo(out $$ """); - } [Fact] - public async Task TestAfterLambdaRef() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaRef() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (ref $$ """); - } [Fact] - public async Task TestAfterLambdaOut() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaOut() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (out $$ """); - } [Fact] - public async Task TestAfterParams() - { - await VerifyKeywordAsync( + public Task TestAfterParams() + => VerifyKeywordAsync( """ class C { void Goo(params $$ """); - } [Fact] - public async Task TestInImplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInImplicitOperator() + => VerifyKeywordAsync( """ class C { public static implicit operator $$ """); - } [Fact] - public async Task TestInExplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInExplicitOperator() + => VerifyKeywordAsync( """ class C { public static explicit operator $$ """); - } [Fact] - public async Task TestAfterIndexerBracket() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracket() + => VerifyKeywordAsync( """ class C { int this[$$ """); - } [Fact] - public async Task TestAfterIndexerBracketComma() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracketComma() + => VerifyKeywordAsync( """ class C { int this[int i, $$ """); - } [Fact] - public async Task TestAfterNewInExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterNewInExpression() + => VerifyKeywordAsync(AddInsideMethod( @"new $$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInTypeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInTypeOf() + => VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInDefault() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDefault() + => VerifyKeywordAsync(AddInsideMethod( @"default($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInSizeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInSizeOf() + => VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")] - public async Task TestInChecked() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInChecked() + => VerifyKeywordAsync(AddInsideMethod( @"var a = checked($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")] - public async Task TestInUnchecked() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInUnchecked() + => VerifyKeywordAsync(AddInsideMethod( @"var a = unchecked($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -740,12 +573,10 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] - public async Task TestInCrefContext() - { - await VerifyKeywordAsync(""" + public Task TestInCrefContext() + => VerifyKeywordAsync(""" class Program { /// @@ -755,16 +586,13 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] - public async Task TestInCrefContextNotAfterDot() - { - await VerifyAbsenceAsync(""" + public Task TestInCrefContextNotAfterDot() + => VerifyAbsenceAsync(""" /// class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] public async Task TestNotAfterAsync() @@ -775,19 +603,16 @@ public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1468")] - public async Task TestNotInCrefTypeParameter() - { - await VerifyAbsenceAsync(""" + public Task TestNotInCrefTypeParameter() + => VerifyAbsenceAsync(""" using System; /// class C { } """); - } [Fact] - public async Task Preselection() - { - await VerifyKeywordAsync(""" + public Task Preselection() + => VerifyKeywordAsync(""" class Program { static void Main(string[] args) @@ -797,23 +622,19 @@ static void Main(string[] args) static void Helper(decimal x) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinType() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinType() + => VerifyKeywordAsync(""" class Program { ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinMember() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinMember() + => VerifyKeywordAsync(""" class Program { void Method() @@ -822,82 +643,66 @@ void Method() } } """); - } [Fact] - public async Task TestInFunctionPointerType() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerType() + => VerifyKeywordAsync(""" class C { delegate*<$$ """); - } [Fact] - public async Task TestInFunctionPointerTypeAfterComma() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerTypeAfterComma() + => VerifyKeywordAsync(""" class C { delegate* VerifyKeywordAsync(""" class C { delegate* VerifyAbsenceAsync(""" class C { delegate*$$ """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/53585")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithoutAsync))] - public async Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) - { - await VerifyKeywordAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) + => VerifyKeywordAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithAsync))] - public async Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) - { - await VerifyAbsenceAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) + => VerifyAbsenceAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64585")] - public async Task TestAfterRequired() - { - await VerifyKeywordAsync(""" + public Task TestAfterRequired() + => VerifyKeywordAsync(""" class C { required $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefAtTopLevel1() + => VerifyKeywordAsync( @"ref $$"); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [CombinatorialData] @@ -918,216 +723,183 @@ await VerifyAbsenceAsync( } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefReadonlyAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyAtTopLevel1() + => VerifyKeywordAsync( @"ref readonly $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { readonly $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref readonly $$ } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref $$ -}}"); - } + public Task TestAfterRefInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - readonly $$ -}}"); - } + public Task TestAfterReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + readonly $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref readonly $$ -}}"); - } + public Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref readonly $$ + } + """); #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -1137,5 +909,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/DefaultKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/DefaultKeywordRecommenderTests.cs index 3cb8035bec097..4b2afbb7f5f47 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/DefaultKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/DefaultKeywordRecommenderTests.cs @@ -13,152 +13,119 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class DefaultKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInPreprocessor1() - { - await VerifyAbsenceAsync( + public Task TestNotInPreprocessor1() + => VerifyAbsenceAsync( """ class C { #$$ """); - } [Fact] - public async Task TestNotInPreprocessor2() - { - await VerifyAbsenceAsync( + public Task TestNotInPreprocessor2() + => VerifyAbsenceAsync( """ class C { #if $$ """); - } [Fact] - public async Task TestAfterHash() - { - await VerifyKeywordAsync( + public Task TestAfterHash() + => VerifyKeywordAsync( @"#line $$"); - } [Fact] - public async Task TestAfterHashAndSpace() - { - await VerifyKeywordAsync( + public Task TestAfterHashAndSpace() + => VerifyKeywordAsync( @"# line $$"); - } [Fact] - public async Task TestInEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInExpression() + => VerifyKeywordAsync(AddInsideMethod( @"var q = $$")); - } [Fact] - public async Task TestAfterSwitch() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterSwitch() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { $$ """)); - } [Fact] - public async Task TestAfterCase() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterCase() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { case 0: $$ """)); - } [Fact] - public async Task TestAfterDefault() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterDefault() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { default: $$ """)); - } [Fact] - public async Task TestAfterOneStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterOneStatement() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { default: Console.WriteLine(); $$ """)); - } [Fact] - public async Task TestAfterTwoStatements() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterTwoStatements() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { default: @@ -166,24 +133,20 @@ await VerifyKeywordAsync(AddInsideMethod( Console.WriteLine(); $$ """)); - } [Fact] - public async Task TestAfterBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBlock() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { default: { } $$ """)); - } [Fact] - public async Task TestAfterIfElse() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIfElse() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { default: @@ -192,35 +155,29 @@ await VerifyKeywordAsync(AddInsideMethod( } $$ """)); - } [Fact] - public async Task TestAfterIncompleteStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIncompleteStatement() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { default: Console.WriteLine( $$ """)); - } [Fact] - public async Task TestInsideBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideBlock() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { default: { $$ """)); - } [Fact] - public async Task TestAfterCompleteIf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterCompleteIf() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { default: @@ -228,24 +185,20 @@ await VerifyKeywordAsync(AddInsideMethod( Console.WriteLine(); $$ """)); - } [Fact] - public async Task TestAfterIncompleteIf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIncompleteIf() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { default: if (goo) $$ """)); - } [Fact] - public async Task TestAfterWhile() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterWhile() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { default: @@ -253,51 +206,39 @@ await VerifyKeywordAsync(AddInsideMethod( } $$ """)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")] - public async Task TestNotAfterGotoInSwitch() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterGotoInSwitch() + => VerifyAbsenceAsync(AddInsideMethod( """ switch (expr) { default: goto $$ """)); - } [Fact] - public async Task TestNotAfterGotoOutsideSwitch() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterGotoOutsideSwitch() + => VerifyAbsenceAsync(AddInsideMethod( @"goto $$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInTypeOf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInTypeOf() + => VerifyAbsenceAsync(AddInsideMethod( @"typeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInDefault() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInDefault() + => VerifyAbsenceAsync(AddInsideMethod( @"default($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInSizeOf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInSizeOf() + => VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -305,19 +246,15 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46283")] - public async Task TestInTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestInTypeParameterConstraint() + => VerifyKeywordAsync( """ class C { @@ -326,12 +263,10 @@ void M() where T : $$ } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46283")] - public async Task TestInTypeParameterConstraint_InOverride() - { - await VerifyKeywordAsync( + public Task TestInTypeParameterConstraint_InOverride() + => VerifyKeywordAsync( """ class C : Base { @@ -340,12 +275,10 @@ public override void M() where T : $$ } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46283")] - public async Task TestInTypeParameterConstraint_InExplicitInterfaceImplementation() - { - await VerifyKeywordAsync( + public Task TestInTypeParameterConstraint_InExplicitInterfaceImplementation() + => VerifyKeywordAsync( """ class C : I { @@ -354,33 +287,25 @@ public void I.M() where T : $$ } } """); - } [Fact] - public async Task TestAfterLambdaOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaOpenParen() + => VerifyKeywordAsync( @"var lam = ($$"); - } [Fact] - public async Task TestAfterLambdaComma() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaComma() + => VerifyKeywordAsync( @"var lam = (int i, $$"); - } [Fact] - public async Task TestLambdaDefaultParameterValue() - { - await VerifyKeywordAsync( + public Task TestLambdaDefaultParameterValue() + => VerifyKeywordAsync( @"var lam = (int i = $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36472")] - public async Task InAmbiguousCast1() - { - await VerifyKeywordAsync( + public Task InAmbiguousCast1() + => VerifyKeywordAsync( """ class C { @@ -392,5 +317,4 @@ static void Main(string[] args) } } """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/DefineKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/DefineKeywordRecommenderTests.cs index 3974d2e7f1222..821de074db985 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/DefineKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/DefineKeywordRecommenderTests.cs @@ -12,125 +12,97 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class DefineKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterHash() - { - await VerifyKeywordAsync( + public Task TestAfterHash() + => VerifyKeywordAsync( @"#$$"); - } [Fact] - public async Task TestAfterHashAndSpace() - { - await VerifyKeywordAsync( + public Task TestAfterHashAndSpace() + => VerifyKeywordAsync( @"# $$"); - } [Fact] - public async Task TestNestedPreprocessor() - { - await VerifyKeywordAsync( + public Task TestNestedPreprocessor() + => VerifyKeywordAsync( """ #if true #$$ #endif """); - } [Fact] - public async Task TestBeforeUsing() - { - await VerifyKeywordAsync( + public Task TestBeforeUsing() + => VerifyKeywordAsync( """ #$$ using System; """); - } [Fact] - public async Task TestBeforeGlobalUsing() - { - await VerifyKeywordAsync( + public Task TestBeforeGlobalUsing() + => VerifyKeywordAsync( """ #$$ global using System; """); - } [Fact] - public async Task TestNotAfterUsing() - { - await VerifyAbsenceAsync( + public Task TestNotAfterUsing() + => VerifyAbsenceAsync( """ using System; #$$ """); - } [Fact] - public async Task TestNotAfterGlobalUsing() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGlobalUsing() + => VerifyAbsenceAsync( """ global using System; #$$ """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/DelegateKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/DelegateKeywordRecommenderTests.cs index 3664642f6ee3b..ee00fbebe46e9 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/DelegateKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/DelegateKeywordRecommenderTests.cs @@ -13,48 +13,38 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class DelegateKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsing() - { - await VerifyAbsenceAsync( + public Task TestNotInUsing() + => VerifyAbsenceAsync( @"using $$"); - } [Fact] public async Task TestInUsingAlias() @@ -75,237 +65,187 @@ await VerifyKeywordAsync( } [Fact] - public async Task TestInUsingAliasTypeParameter() - { - // Valid case: using Goo = System.Collections.Generic.IList[]>; - await VerifyKeywordAsync( + public Task TestInUsingAliasTypeParameter() + => VerifyKeywordAsync( @"using Goo = T<$$"); - } [Fact] - public async Task TestInGlobalUsingAliasTypeParameter() - { - // Valid case: global using Goo = System.Collections.Generic.IList[]>; - await VerifyKeywordAsync( + public Task TestInGlobalUsingAliasTypeParameter() + => VerifyKeywordAsync( @"global using Goo = T<$$"); - } [Fact] - public async Task TestInEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInCompilationUnit() - { - await VerifyKeywordAsync( + public Task TestInCompilationUnit() + => VerifyKeywordAsync( @"$$"); - } [Fact] - public async Task TestAfterExtern() - { - await VerifyKeywordAsync( + public Task TestAfterExtern() + => VerifyKeywordAsync( """ extern alias Goo; $$ """); - } [Fact] - public async Task TestAfterUsing() - { - await VerifyKeywordAsync( + public Task TestAfterUsing() + => VerifyKeywordAsync( """ using Goo; $$ """); - } [Fact] - public async Task TestAfterGlobalUsing() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalUsing() + => VerifyKeywordAsync( """ global using Goo; $$ """); - } [Fact] - public async Task TestAfterNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterNamespace() + => VerifyKeywordAsync( """ namespace N {} $$ """); - } [Fact] - public async Task TestAfterFileScopedNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterFileScopedNamespace() + => VerifyKeywordAsync( """ namespace N; $$ """); - } [Fact] - public async Task TestAfterTypeDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterTypeDeclaration() + => VerifyKeywordAsync( """ class C {} $$ """); - } [Fact] - public async Task TestAfterDelegateDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateDeclaration() + => VerifyKeywordAsync( """ delegate void Goo(); $$ """); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ global using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeGlobalUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeGlobalUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ global using Goo; """); - } [Fact] - public async Task TestAfterAssemblyAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterAssemblyAttribute() + => VerifyKeywordAsync( """ [assembly: goo] $$ """); - } [Fact] - public async Task TestAfterRootAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterRootAttribute() + => VerifyKeywordAsync( """ [goo] $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync(""" + public Task TestInsideInterface() + => VerifyKeywordAsync(""" interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() @@ -316,32 +256,24 @@ public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact] - public async Task TestAfterInternal() - { - await VerifyKeywordAsync( + public Task TestAfterInternal() + => VerifyKeywordAsync( @"internal $$"); - } [Fact] - public async Task TestAfterPublic() - { - await VerifyKeywordAsync( + public Task TestAfterPublic() + => VerifyKeywordAsync( @"public $$"); - } [Fact] - public async Task TestAfterPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterPrivate() + => VerifyKeywordAsync( @"private $$"); - } [Fact] - public async Task TestAfterProtected() - { - await VerifyKeywordAsync( + public Task TestAfterProtected() + => VerifyKeywordAsync( @"protected $$"); - } [Fact] public async Task TestNotAfterSealed() @@ -374,38 +306,31 @@ public async Task TestAfterDelegate() => await VerifyKeywordAsync(@"delegate $$"); [Fact] - public async Task TestDelegateAsArgument() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestDelegateAsArgument() + => VerifyKeywordAsync(AddInsideMethod( @"Assert.Throws($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] - public async Task TestNotInConstMemberInitializer1() - { - await VerifyAbsenceAsync( + public Task TestNotInConstMemberInitializer1() + => VerifyAbsenceAsync( """ class E { const int a = $$ } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] - public async Task TestNotInEnumMemberInitializer1() - { - await VerifyAbsenceAsync( + public Task TestNotInEnumMemberInitializer1() + => VerifyAbsenceAsync( """ enum E { a = $$ } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] - public async Task TestNotInConstLocalInitializer1() - { - await VerifyAbsenceAsync( + public Task TestNotInConstLocalInitializer1() + => VerifyAbsenceAsync( """ class E { void Goo() { @@ -413,44 +338,34 @@ void Goo() { } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] - public async Task TestInMemberInitializer1() - { - await VerifyKeywordAsync( + public Task TestInMemberInitializer1() + => VerifyKeywordAsync( """ class E { int a = $$ } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInTypeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInTypeOf() + => VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInDefault() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDefault() + => VerifyKeywordAsync(AddInsideMethod( @"default($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInSizeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInSizeOf() + => VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -458,12 +373,10 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/607197")] - public async Task TestAfterAsyncInMethodBody() - { - await VerifyKeywordAsync(""" + public Task TestAfterAsyncInMethodBody() + => VerifyKeywordAsync(""" using System; class C { @@ -471,40 +384,32 @@ void M() { Action a = async $$ """); - } [Fact] - public async Task TestAfterAsyncInMemberDeclaration() - { - await VerifyKeywordAsync(""" + public Task TestAfterAsyncInMemberDeclaration() + => VerifyKeywordAsync(""" using System; class C { async $$ """); - } [Fact] - public async Task TestInFunctionPointerTypeList() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerTypeList() + => VerifyKeywordAsync(""" using System; class C { delegate*<$$ """); - } [Fact] - public async Task TestNotInEnumBaseList() - { - await VerifyAbsenceAsync("enum E : $$"); - } + public Task TestNotInEnumBaseList() + => VerifyAbsenceAsync("enum E : $$"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70076")] - public async Task TestNotInAttribute() - { - await VerifyAbsenceAsync(""" + public Task TestNotInAttribute() + => VerifyAbsenceAsync(""" class C { [$$] @@ -513,139 +418,115 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68399")] - public async Task TestNotInRecordParameterAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInRecordParameterAttribute() + => VerifyAbsenceAsync( """ record R([$$] int i) { } """); - } #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -655,5 +536,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/DescendingKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/DescendingKeywordRecommenderTests.cs index 5c111ac1f7d7a..1e6999d78d627 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/DescendingKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/DescendingKeywordRecommenderTests.cs @@ -12,130 +12,102 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class DescendingKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterOrderByExpr() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterOrderByExpr() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y orderby x $$ """)); - } [Fact] - public async Task TestAfterSecondExpr() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterSecondExpr() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y orderby x, y $$ """)); - } [Fact] - public async Task TestBetweenExprs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBetweenExprs() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y orderby x, y $$, z """)); - } [Fact] - public async Task TestNotAfterDot() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterDot() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y orderby x.$$ """)); - } [Fact] - public async Task TestNotAfterComma() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterComma() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y orderby x, $$ """)); - } [Fact] - public async Task TestAfterCloseParen() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterCloseParen() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y orderby x.ToString() $$ """)); - } [Fact] - public async Task TestAfterCloseBracket() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterCloseBracket() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y orderby x.ToString()[0] $$ """)); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/DisableKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/DisableKeywordRecommenderTests.cs index c3c600817acb9..037a135e3ab0f 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/DisableKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/DisableKeywordRecommenderTests.cs @@ -17,72 +17,56 @@ public async Task TestAfterNullable() => await VerifyKeywordAsync(@"#nullable $$"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31130")] - public async Task TestNotAfterNullableAndNewline() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNullableAndNewline() + => VerifyAbsenceAsync(""" #nullable $$ """); - } [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] public async Task TestNotAfterHash() @@ -93,9 +77,7 @@ public async Task TestNotAfterPragma() => await VerifyAbsenceAsync(@"#pragma $$"); [Fact] - public async Task TestAfterPragmaWarning() - { - await VerifyKeywordAsync( + public Task TestAfterPragmaWarning() + => VerifyKeywordAsync( @"#pragma warning $$"); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/DoKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/DoKeywordRecommenderTests.cs index 2b12b85d3a8e9..680b7de1d7385 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/DoKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/DoKeywordRecommenderTests.cs @@ -12,133 +12,105 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class DoKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestBeforeStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBeforeStatement() + => VerifyKeywordAsync(AddInsideMethod( """ $$ return true; """)); - } [Fact] - public async Task TestAfterStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterStatement() + => VerifyKeywordAsync(AddInsideMethod( """ return true; $$ """)); - } [Fact] - public async Task TestAfterBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBlock() + => VerifyKeywordAsync(AddInsideMethod( """ if (true) { } $$ """)); - } [Fact] - public async Task TestInsideDo() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideDo() + => VerifyKeywordAsync(AddInsideMethod( """ do $$ """)); - } [Fact] - public async Task TestInsideDoInsideDo() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideDoInsideDo() + => VerifyKeywordAsync(AddInsideMethod( """ do do $$ """)); - } [Fact] - public async Task TestInsideDoBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideDoBlock() + => VerifyKeywordAsync(AddInsideMethod( """ do { $$ """)); - } [Fact] - public async Task TestNotInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotInClass() + => VerifyAbsenceAsync(""" class C { $$ } """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/DoubleKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/DoubleKeywordRecommenderTests.cs index 39222f18e9c24..d4fd5b8a257e5 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/DoubleKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/DoubleKeywordRecommenderTests.cs @@ -13,712 +13,549 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class DoubleKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsing() - { - await VerifyAbsenceAsync( + public Task TestNotInUsing() + => VerifyAbsenceAsync( @"using $$"); - } [Fact] - public async Task TestInUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInUsingAlias() + => VerifyKeywordAsync( @"using Goo = $$"); - } [Fact] - public async Task TestInGlobalUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInGlobalUsingAlias() + => VerifyKeywordAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestAfterStackAlloc() - { - await VerifyKeywordAsync( + public Task TestAfterStackAlloc() + => VerifyKeywordAsync( """ class C { int* goo = stackalloc $$ """); - } [Fact] - public async Task TestInFixedStatement() - { - await VerifyKeywordAsync( + public Task TestInFixedStatement() + => VerifyKeywordAsync( @"fixed ($$"); - } [Fact] - public async Task TestInDelegateReturnType() - { - await VerifyKeywordAsync( + public Task TestInDelegateReturnType() + => VerifyKeywordAsync( @"public delegate $$"); - } [Fact] - public async Task TestInCastType() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); - } [Fact] - public async Task TestInCastType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType2() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); - } [Fact] - public async Task TestAfterConstInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterConstInMemberContext() + => VerifyKeywordAsync( """ class C { const $$ """); - } [Fact] - public async Task TestAfterRefInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefInMemberContext() + => VerifyKeywordAsync( """ class C { ref $$ """); - } [Fact] - public async Task TestAfterRefReadonlyInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyInMemberContext() + => VerifyKeywordAsync( """ class C { ref readonly $$ """); - } [Fact] - public async Task TestAfterConstInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"const $$")); - } [Fact] - public async Task TestAfterRefInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$")); - } [Fact] - public async Task TestAfterRefReadonlyInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); - } [Fact] - public async Task TestAfterConstLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); - } [Fact] - public async Task TestAfterRefReadonlyLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); - } [Fact] - public async Task TestAfterRefReadonlyLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); - } [Fact] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } [Fact] - public async Task TestInEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestNotInEnumBaseTypes() - { - await VerifyAbsenceAsync( + public Task TestNotInEnumBaseTypes() + => VerifyAbsenceAsync( @"enum E : $$"); - } [Fact] - public async Task TestInGenericType1() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType1() + => VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); - } [Fact] - public async Task TestInGenericType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType2() + => VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList,$$")); - } [Fact] - public async Task TestNotInBaseList() - { - await VerifyAbsenceAsync( + public Task TestNotInBaseList() + => VerifyAbsenceAsync( @"class C : $$"); - } [Fact] - public async Task TestInGenericType_InBaseList() - { - await VerifyKeywordAsync( + public Task TestInGenericType_InBaseList() + => VerifyKeywordAsync( @"class C : IList<$$"); - } [Fact] - public async Task TestAfterIs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); - } [Fact] - public async Task TestAfterAs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterAs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync( + public Task TestInsideInterface() + => VerifyKeywordAsync( """ interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact] - public async Task TestAfterNestedPartial() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPartial() + => VerifyKeywordAsync( """ class C { partial $$ """); - } [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] - public async Task TestAfterNestedStaticPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticPublic() + => VerifyKeywordAsync( """ class C { static public $$ """); - } [Fact] - public async Task TestAfterNestedPublicStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublicStatic() + => VerifyKeywordAsync( """ class C { public static $$ """); - } [Fact] - public async Task TestAfterVirtualPublic() - { - await VerifyKeywordAsync( + public Task TestAfterVirtualPublic() + => VerifyKeywordAsync( """ class C { virtual public $$ """); - } [Fact] - public async Task TestAfterNestedPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublic() + => VerifyKeywordAsync( """ class C { public $$ """); - } [Fact] - public async Task TestAfterNestedPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPrivate() + => VerifyKeywordAsync( """ class C { private $$ """); - } [Fact] - public async Task TestAfterNestedProtected() - { - await VerifyKeywordAsync( + public Task TestAfterNestedProtected() + => VerifyKeywordAsync( """ class C { protected $$ """); - } [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] - public async Task TestAfterNestedStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStatic() + => VerifyKeywordAsync( """ class C { static $$ """); - } [Fact] - public async Task TestInLocalVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLocalVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInForVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"for ($$")); - } [Fact] - public async Task TestInForeachVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForeachVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); - } [Fact] - public async Task TestInUsingVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInUsingVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"using ($$")); - } [Fact] - public async Task TestInFromVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFromVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); - } [Fact] - public async Task TestInJoinVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInJoinVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from a in b join $$ """)); - } [Fact] - public async Task TestAfterMethodOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterMethodOpenParen() + => VerifyKeywordAsync( """ class C { void Goo($$ """); - } [Fact] - public async Task TestAfterMethodComma() - { - await VerifyKeywordAsync( + public Task TestAfterMethodComma() + => VerifyKeywordAsync( """ class C { void Goo(int i, $$ """); - } [Fact] - public async Task TestAfterMethodAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterMethodAttribute() + => VerifyKeywordAsync( """ class C { void Goo(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterConstructorOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorOpenParen() + => VerifyKeywordAsync( """ class C { public C($$ """); - } [Fact] - public async Task TestAfterConstructorComma() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorComma() + => VerifyKeywordAsync( """ class C { public C(int i, $$ """); - } [Fact] - public async Task TestAfterConstructorAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorAttribute() + => VerifyKeywordAsync( """ class C { public C(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterDelegateOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateOpenParen() + => VerifyKeywordAsync( @"delegate void D($$"); - } [Fact] - public async Task TestAfterDelegateComma() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateComma() + => VerifyKeywordAsync( @"delegate void D(int i, $$"); - } [Fact] - public async Task TestAfterDelegateAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateAttribute() + => VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); - } [Fact] - public async Task TestAfterThis() - { - await VerifyKeywordAsync( + public Task TestAfterThis() + => VerifyKeywordAsync( """ static class C { public static void Goo(this $$ """); - } [Fact] - public async Task TestAfterRef() - { - await VerifyKeywordAsync( + public Task TestAfterRef() + => VerifyKeywordAsync( """ class C { void Goo(ref $$ """); - } [Fact] - public async Task TestAfterOut() - { - await VerifyKeywordAsync( + public Task TestAfterOut() + => VerifyKeywordAsync( """ class C { void Goo(out $$ """); - } [Fact] - public async Task TestAfterLambdaRef() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaRef() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (ref $$ """); - } [Fact] - public async Task TestAfterLambdaOut() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaOut() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (out $$ """); - } [Fact] - public async Task TestAfterParams() - { - await VerifyKeywordAsync( + public Task TestAfterParams() + => VerifyKeywordAsync( """ class C { void Goo(params $$ """); - } [Fact] - public async Task TestInImplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInImplicitOperator() + => VerifyKeywordAsync( """ class C { public static implicit operator $$ """); - } [Fact] - public async Task TestInExplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInExplicitOperator() + => VerifyKeywordAsync( """ class C { public static explicit operator $$ """); - } [Fact] - public async Task TestAfterIndexerBracket() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracket() + => VerifyKeywordAsync( """ class C { int this[$$ """); - } [Fact] - public async Task TestAfterIndexerBracketComma() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracketComma() + => VerifyKeywordAsync( """ class C { int this[int i, $$ """); - } [Fact] - public async Task TestAfterNewInExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterNewInExpression() + => VerifyKeywordAsync(AddInsideMethod( @"new $$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInTypeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInTypeOf() + => VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInDefault() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDefault() + => VerifyKeywordAsync(AddInsideMethod( @"default($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInSizeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInSizeOf() + => VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -726,12 +563,10 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] - public async Task TestInCrefContext() - { - await VerifyKeywordAsync(""" + public Task TestInCrefContext() + => VerifyKeywordAsync(""" class Program { /// @@ -741,16 +576,13 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] - public async Task TestInCrefContextNotAfterDot() - { - await VerifyAbsenceAsync(""" + public Task TestInCrefContextNotAfterDot() + => VerifyAbsenceAsync(""" /// class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] public async Task TestNotAfterAsync() @@ -761,19 +593,16 @@ public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1468")] - public async Task TestNotInCrefTypeParameter() - { - await VerifyAbsenceAsync(""" + public Task TestNotInCrefTypeParameter() + => VerifyAbsenceAsync(""" using System; /// class C { } """); - } [Fact] - public async Task Preselection() - { - await VerifyKeywordAsync(""" + public Task Preselection() + => VerifyKeywordAsync(""" class Program { static void Main(string[] args) @@ -783,23 +612,19 @@ static void Main(string[] args) static void Helper(double x) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinType() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinType() + => VerifyKeywordAsync(""" class Program { ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinMember() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinMember() + => VerifyKeywordAsync(""" class Program { void Method() @@ -808,82 +633,66 @@ void Method() } } """); - } [Fact] - public async Task TestInFunctionPointerType() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerType() + => VerifyKeywordAsync(""" class Program { delegate*<$$ """); - } [Fact] - public async Task TestInFunctionPointerTypeAfterComma() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerTypeAfterComma() + => VerifyKeywordAsync(""" class C { delegate* VerifyKeywordAsync(""" class C { delegate* VerifyAbsenceAsync(""" class C { delegate*$$ """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/53585")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithoutAsync))] - public async Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) - { - await VerifyKeywordAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) + => VerifyKeywordAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithAsync))] - public async Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) - { - await VerifyAbsenceAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) + => VerifyAbsenceAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64585")] - public async Task TestAfterRequired() - { - await VerifyKeywordAsync(""" + public Task TestAfterRequired() + => VerifyKeywordAsync(""" class C { required $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefAtTopLevel1() + => VerifyKeywordAsync( @"ref $$"); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [CombinatorialData] @@ -904,216 +713,183 @@ await VerifyAbsenceAsync( } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefReadonlyAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyAtTopLevel1() + => VerifyKeywordAsync( @"ref readonly $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { readonly $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref readonly $$ } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref $$ -}}"); - } + public Task TestAfterRefInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - readonly $$ -}}"); - } + public Task TestAfterReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + readonly $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref readonly $$ -}}"); - } + public Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref readonly $$ + } + """); #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -1123,5 +899,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/DynamicKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/DynamicKeywordRecommenderTests.cs index 757eef9343e87..0fa116020e644 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/DynamicKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/DynamicKeywordRecommenderTests.cs @@ -24,705 +24,545 @@ public DynamicKeywordRecommenderTests() } [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsing() - { - await VerifyAbsenceAsync( + public Task TestNotInUsing() + => VerifyAbsenceAsync( @"using $$"); - } [Fact] - public async Task TestInUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInUsingAlias() + => VerifyKeywordAsync( @"using Goo = $$"); - } [Fact] - public async Task TestInUsingAlias_Tuple() - { - await VerifyKeywordAsync( + public Task TestInUsingAlias_Tuple() + => VerifyKeywordAsync( @"using Goo = ($$"); - } [Fact] - public async Task TestNotAfterStackAlloc() - { - await VerifyAbsenceAsync( + public Task TestNotAfterStackAlloc() + => VerifyAbsenceAsync( """ class C { int* goo = stackalloc $$ """); - } [Fact] - public async Task TestNotInFixedStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInFixedStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"fixed ($$")); - } [Fact] - public async Task TestInDelegateReturnType() - { - await VerifyKeywordAsync( + public Task TestInDelegateReturnType() + => VerifyKeywordAsync( @"public delegate $$"); - } [Fact] - public async Task TestInCastType() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); - } [Fact] - public async Task TestInCastType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType2() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); - } [Fact] - public async Task TestAfterConstInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterConstInMemberContext() + => VerifyKeywordAsync( """ class C { const $$ """); - } [Fact] - public async Task TestAfterRefInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefInMemberContext() + => VerifyKeywordAsync( """ class C { ref $$ """); - } [Fact] - public async Task TestAfterRefReadonlyInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyInMemberContext() + => VerifyKeywordAsync( """ class C { ref readonly $$ """); - } [Fact] - public async Task TestAfterConstInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"const $$")); - } [Fact] - public async Task TestAfterRefInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$")); - } [Fact] - public async Task TestAfterRefReadonlyInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); - } [Fact] - public async Task TestAfterConstLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); - } [Fact] - public async Task TestAfterRefReadonlyLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); - } [Fact] - public async Task TestAfterRefReadonlyLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); - } [Fact] - public async Task TestNotAfterRefExpression() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterRefExpression() + => VerifyAbsenceAsync(AddInsideMethod( @"ref int x = ref $$")); - } [Fact] - public async Task TestInEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestNotInEnumBaseTypes() - { - await VerifyAbsenceAsync( + public Task TestNotInEnumBaseTypes() + => VerifyAbsenceAsync( @"enum E : $$"); - } [Fact] - public async Task TestInGenericType1() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType1() + => VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); - } [Fact] - public async Task TestInGenericType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType2() + => VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList,$$")); - } [Fact] - public async Task TestNotInBaseList() - { - await VerifyAbsenceAsync( + public Task TestNotInBaseList() + => VerifyAbsenceAsync( @"class C : $$"); - } [Fact] - public async Task TestInGenericType_InBaseList() - { - await VerifyKeywordAsync( + public Task TestInGenericType_InBaseList() + => VerifyKeywordAsync( @"class C : IList<$$"); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync( + public Task TestInsideInterface() + => VerifyKeywordAsync( """ interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact] - public async Task TestAfterNestedPartial() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPartial() + => VerifyKeywordAsync( """ class C { partial $$ """); - } [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] - public async Task TestAfterNestedStaticPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticPublic() + => VerifyKeywordAsync( """ class C { static public $$ """); - } [Fact] - public async Task TestAfterNestedPublicStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublicStatic() + => VerifyKeywordAsync( """ class C { public static $$ """); - } [Fact] - public async Task TestAfterVirtualPublic() - { - await VerifyKeywordAsync( + public Task TestAfterVirtualPublic() + => VerifyKeywordAsync( """ class C { virtual public $$ """); - } [Fact] - public async Task TestAfterNestedPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublic() + => VerifyKeywordAsync( """ class C { public $$ """); - } [Fact] - public async Task TestAfterNestedPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPrivate() + => VerifyKeywordAsync( """ class C { private $$ """); - } [Fact] - public async Task TestAfterNestedProtected() - { - await VerifyKeywordAsync( + public Task TestAfterNestedProtected() + => VerifyKeywordAsync( """ class C { protected $$ """); - } [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] - public async Task TestAfterNestedStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStatic() + => VerifyKeywordAsync( """ class C { static $$ """); - } [Fact] - public async Task TestInLocalVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLocalVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInForVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"for ($$")); - } [Fact] - public async Task TestInForeachVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForeachVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); - } [Fact] - public async Task TestInUsingVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInUsingVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"using ($$")); - } [Fact] - public async Task TestInFromVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFromVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); - } [Fact] - public async Task TestInJoinVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInJoinVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from a in b join $$ """)); - } [Fact] - public async Task TestAfterMethodOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterMethodOpenParen() + => VerifyKeywordAsync( """ class C { void Goo($$ """); - } [Fact] - public async Task TestAfterMethodComma() - { - await VerifyKeywordAsync( + public Task TestAfterMethodComma() + => VerifyKeywordAsync( """ class C { void Goo(int i, $$ """); - } [Fact] - public async Task TestAfterMethodAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterMethodAttribute() + => VerifyKeywordAsync( """ class C { void Goo(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterConstructorOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorOpenParen() + => VerifyKeywordAsync( """ class C { public C($$ """); - } [Fact] - public async Task TestAfterConstructorComma() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorComma() + => VerifyKeywordAsync( """ class C { public C(int i, $$ """); - } [Fact] - public async Task TestAfterConstructorAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorAttribute() + => VerifyKeywordAsync( """ class C { public C(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterDelegateOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateOpenParen() + => VerifyKeywordAsync( @"delegate void D($$"); - } [Fact] - public async Task TestAfterDelegateComma() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateComma() + => VerifyKeywordAsync( @"delegate void D(int i, $$"); - } [Fact] - public async Task TestAfterDelegateAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateAttribute() + => VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); - } [Fact] - public async Task TestAfterThis() - { - await VerifyKeywordAsync( + public Task TestAfterThis() + => VerifyKeywordAsync( """ static class C { public static void Goo(this $$ """); - } [Fact] - public async Task TestAfterRef() - { - await VerifyKeywordAsync( + public Task TestAfterRef() + => VerifyKeywordAsync( """ class C { void Goo(ref $$ """); - } [Fact] - public async Task TestAfterOut() - { - await VerifyKeywordAsync( + public Task TestAfterOut() + => VerifyKeywordAsync( """ class C { void Goo(out $$ """); - } [Fact] - public async Task TestAfterLambdaRef() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaRef() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (ref $$ """); - } [Fact] - public async Task TestAfterLambdaOut() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaOut() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (out $$ """); - } [Fact] - public async Task TestAfterParams() - { - await VerifyKeywordAsync( + public Task TestAfterParams() + => VerifyKeywordAsync( """ class C { void Goo(params $$ """); - } [Fact] - public async Task TestNotInImplicitOperator() - { - await VerifyAbsenceAsync( + public Task TestNotInImplicitOperator() + => VerifyAbsenceAsync( """ class C { public static implicit operator $$ """); - } [Fact] - public async Task TestNotInExplicitOperator() - { - await VerifyAbsenceAsync( + public Task TestNotInExplicitOperator() + => VerifyAbsenceAsync( """ class C { public static explicit operator $$ """); - } [Fact] - public async Task TestAfterIndexerBracket() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracket() + => VerifyKeywordAsync( """ class C { int this[$$ """); - } [Fact] - public async Task TestAfterIndexerBracketComma() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracketComma() + => VerifyKeywordAsync( """ class C { int this[int i, $$ """); - } [Fact] - public async Task TestAfterNewInExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterNewInExpression() + => VerifyKeywordAsync(AddInsideMethod( @"new $$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInTypeOf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInTypeOf() + => VerifyAbsenceAsync(AddInsideMethod( @"typeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInDefault() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDefault() + => VerifyKeywordAsync(AddInsideMethod( @"default($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInSizeOf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInSizeOf() + => VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545303")] - public async Task TestNotInPreProcessor() - { - await VerifyAbsenceAsync( + public Task TestNotInPreProcessor() + => VerifyAbsenceAsync( """ class Program { #region $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] public async Task TestNotAfterAsync() @@ -733,49 +573,40 @@ public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [Fact] - public async Task TestInFunctionPointerType() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerType() + => VerifyKeywordAsync(""" class C { delegate*<$$ """); - } [Fact] - public async Task TestInFunctionPointerTypeAfterComma() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerTypeAfterComma() + => VerifyKeywordAsync(""" class C { delegate* VerifyKeywordAsync(""" class C { delegate* VerifyAbsenceAsync(""" class C { delegate*$$ """); - } [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -785,5 +616,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ElifKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ElifKeywordRecommenderTests.cs index 89257b92ea741..515e4155dc1c0 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ElifKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ElifKeywordRecommenderTests.cs @@ -12,74 +12,56 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ElifKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterHash() - { - await VerifyKeywordAsync( + public Task TestAfterHash() + => VerifyKeywordAsync( @"#$$"); - } [Fact] - public async Task TestAfterHashAndSpace() - { - await VerifyKeywordAsync( + public Task TestAfterHashAndSpace() + => VerifyKeywordAsync( @"# $$"); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ElseKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ElseKeywordRecommenderTests.cs index f55e475ac5d7a..519dbcfc35270 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ElseKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ElseKeywordRecommenderTests.cs @@ -13,336 +13,312 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ElseKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInPreprocessor1() - { - await VerifyAbsenceAsync( + public Task TestNotInPreprocessor1() + => VerifyAbsenceAsync( """ class C { #if $$ """); - } [Fact] - public async Task TestInPreprocessorFollowedBySkippedTokens() - { - await VerifyKeywordAsync( + public Task TestInPreprocessorFollowedBySkippedTokens() + => VerifyKeywordAsync( """ #if GOO #$$ dasd """); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterHash() - { - await VerifyKeywordAsync( + public Task TestAfterHash() + => VerifyKeywordAsync( @"#$$"); - } [Fact] - public async Task TestAfterHashAndSpace() - { - await VerifyKeywordAsync( + public Task TestAfterHashAndSpace() + => VerifyKeywordAsync( @"# $$"); - } [Fact] - public async Task TestNotAfterIf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterIf() + => VerifyAbsenceAsync(AddInsideMethod( """ if (true) $$ """)); - } [Theory] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] - public async Task TestAfterIfStatement(string statement) - { - await VerifyKeywordAsync(AddInsideMethod( -$@"if (true) - {statement} -$$")); - } + public Task TestAfterIfStatement(string statement) + => VerifyKeywordAsync(AddInsideMethod( + $""" + if (true) + {statement} + $$ + """)); [Theory] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] - public async Task TestAfterIfStatement_BeforeElse(string statement) - { - await VerifyKeywordAsync(AddInsideMethod( -$@"if (true) - {statement} -$$ -else")); - } + public Task TestAfterIfStatement_BeforeElse(string statement) + => VerifyKeywordAsync(AddInsideMethod( + $""" + if (true) + {statement} + $$ + else + """)); [Theory] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] - public async Task TestAfterIfNestedIfStatement(string statement) - { - await VerifyKeywordAsync(AddInsideMethod( -$@"if (true) - if (true) - {statement} - $$")); - } + public Task TestAfterIfNestedIfStatement(string statement) + => VerifyKeywordAsync(AddInsideMethod( + $""" + if (true) + if (true) + {statement} + $$ + """)); [Theory] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] - public async Task TestAfterIfNestedIfStatement_BeforeElse(string statement) - { - await VerifyKeywordAsync(AddInsideMethod( -$@"if (true) - if (true) - {statement} - $$ - else")); - } + public Task TestAfterIfNestedIfStatement_BeforeElse(string statement) + => VerifyKeywordAsync(AddInsideMethod( + $""" + if (true) + if (true) + {statement} + $$ + else + """)); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/25336")] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] - public async Task TestAfterIfNestedIfElseStatement(string statement) - { - await VerifyKeywordAsync(AddInsideMethod( -$@"if (true) - if (true) - Console.WriteLine(); - else - {statement} -$$")); - } + public Task TestAfterIfNestedIfElseStatement(string statement) + => VerifyKeywordAsync(AddInsideMethod( + $""" + if (true) + if (true) + Console.WriteLine(); + else + {statement} + $$ + """)); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/25336")] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] - public async Task TestAfterIfNestedIfElseStatement_BeforeElse(string statement) - { - await VerifyKeywordAsync(AddInsideMethod( -$@"if (true) - if (true) - Console.WriteLine(); - else - {statement} -$$ -else")); - } + public Task TestAfterIfNestedIfElseStatement_BeforeElse(string statement) + => VerifyKeywordAsync(AddInsideMethod( + $""" + if (true) + if (true) + Console.WriteLine(); + else + {statement} + $$ + else + """)); [Theory] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] - public async Task TestNotAfterIfNestedIfElseElseStatement(string statement) - { - await VerifyAbsenceAsync(AddInsideMethod( -$@"if (true) - if (true) - Console.WriteLine(); - else - Console.WriteLine(); -else - {statement} -$$")); - } + public Task TestNotAfterIfNestedIfElseElseStatement(string statement) + => VerifyAbsenceAsync(AddInsideMethod( + $""" + if (true) + if (true) + Console.WriteLine(); + else + Console.WriteLine(); + else + {statement} + $$ + """)); [Theory] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] - public async Task TestNotAfterIfStatementElse(string statement) - { - await VerifyAbsenceAsync(AddInsideMethod( -$@"if (true) - {statement} -else - $$")); - } + public Task TestNotAfterIfStatementElse(string statement) + => VerifyAbsenceAsync(AddInsideMethod( + $""" + if (true) + {statement} + else + $$ + """)); [Theory] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] - public async Task TestNotAfterIfElseStatement(string statement) - { - await VerifyAbsenceAsync(AddInsideMethod( -$@"if (true) - Console.WriteLine(); -else - {statement} -$$")); - } + public Task TestNotAfterIfElseStatement(string statement) + => VerifyAbsenceAsync(AddInsideMethod( + $""" + if (true) + Console.WriteLine(); + else + {statement} + $$ + """)); [Theory] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] - public async Task TestAfterIfElseNestedIfStatement(string statement) - { - await VerifyKeywordAsync(AddInsideMethod( -$@"if (true) - Console.WriteLine(); -else - if (true) - {statement} - $$")); - } + public Task TestAfterIfElseNestedIfStatement(string statement) + => VerifyKeywordAsync(AddInsideMethod( + $""" + if (true) + Console.WriteLine(); + else + if (true) + {statement} + $$ + """)); [Theory] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] - public async Task TestAfterIfElseNestedIfStatement_BeforeElse(string statement) - { - await VerifyKeywordAsync(AddInsideMethod( -$@"if (true) - Console.WriteLine(); -else - if (true) - {statement} - $$ - else")); - } + public Task TestAfterIfElseNestedIfStatement_BeforeElse(string statement) + => VerifyKeywordAsync(AddInsideMethod( + $""" + if (true) + Console.WriteLine(); + else + if (true) + {statement} + $$ + else + """)); [Theory] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] - public async Task TestNotAfterIfElseNestedIfElseStatement(string statement) - { - await VerifyAbsenceAsync(AddInsideMethod( -$@"if (true) - Console.WriteLine(); -else - if (true) - Console.WriteLine(); - else - {statement} -$$")); - } + public Task TestNotAfterIfElseNestedIfElseStatement(string statement) + => VerifyAbsenceAsync(AddInsideMethod( + $""" + if (true) + Console.WriteLine(); + else + if (true) + Console.WriteLine(); + else + {statement} + $$ + """)); [Theory] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] - public async Task TestAfterWhileIfWhileNestedIfElseStatement(string statement) - { - await VerifyKeywordAsync(AddInsideMethod( -$@"while (true) - if (true) - while (true) + public Task TestAfterWhileIfWhileNestedIfElseStatement(string statement) + => VerifyKeywordAsync(AddInsideMethod( + $""" + while (true) if (true) - Console.WriteLine(); - else - {statement} - $$")); - } + while (true) + if (true) + Console.WriteLine(); + else + {statement} + $$ + """)); [Theory] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] - public async Task TestAfterWhileIfWhileNestedIfElseStatement_BeforeElse(string statement) - { - await VerifyKeywordAsync(AddInsideMethod( -$@"while (true) - if (true) - while (true) + public Task TestAfterWhileIfWhileNestedIfElseStatement_BeforeElse(string statement) + => VerifyKeywordAsync(AddInsideMethod( + $""" + while (true) if (true) - Console.WriteLine(); + while (true) + if (true) + Console.WriteLine(); + else + {statement} + $$ else - {statement} - $$ - else")); - } + """)); [Theory] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] - public async Task TestNotAfterWhileIfWhileNestedIfElseElseStatement(string statement) - { - await VerifyAbsenceAsync(AddInsideMethod( -$@"while (true) - if (true) - while (true) - if (true) - Console.WriteLine(); - else - Console.WriteLine(); - else - {statement} -$$")); - } + public Task TestNotAfterWhileIfWhileNestedIfElseElseStatement(string statement) + => VerifyAbsenceAsync(AddInsideMethod( + $""" + while (true) + if (true) + while (true) + if (true) + Console.WriteLine(); + else + Console.WriteLine(); + else + {statement} + $$ + """)); [Theory] [InlineData("Console")] @@ -356,13 +332,13 @@ await VerifyAbsenceAsync(AddInsideMethod( [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] - public async Task TestNotAfterIfIncompleteStatement(string statement) - { - await VerifyAbsenceAsync(AddInsideMethod( -$@"if (true) - {statement} -$$")); - } + public Task TestNotAfterIfIncompleteStatement(string statement) + => VerifyAbsenceAsync(AddInsideMethod( + $""" + if (true) + {statement} + $$ + """)); [Theory] [InlineData("Console")] @@ -376,14 +352,14 @@ await VerifyAbsenceAsync(AddInsideMethod( [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] - public async Task TestNotAfterIfNestedIfIncompleteStatement(string statement) - { - await VerifyAbsenceAsync(AddInsideMethod( -$@"if (true) - if (true) - {statement} - $$")); - } + public Task TestNotAfterIfNestedIfIncompleteStatement(string statement) + => VerifyAbsenceAsync(AddInsideMethod( + $""" + if (true) + if (true) + {statement} + $$ + """)); [Theory] [InlineData("Console")] @@ -397,66 +373,62 @@ await VerifyAbsenceAsync(AddInsideMethod( [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] - public async Task TestNotAfterIfNestedIfElseIncompleteStatement(string statement) - { - await VerifyAbsenceAsync(AddInsideMethod( -$@"if (true) - if (true) - Console.WriteLine(); - else - {statement} -$$")); - } + public Task TestNotAfterIfNestedIfElseIncompleteStatement(string statement) + => VerifyAbsenceAsync(AddInsideMethod( + $""" + if (true) + if (true) + Console.WriteLine(); + else + {statement} + $$ + """)); [Theory] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] - public async Task TestAfterIfNestedIfIncompleteStatementElseStatement(string statement) - { - await VerifyKeywordAsync(AddInsideMethod( -$@"if (true) - if (true) - Console // Incomplete, but that's fine. This is not the if statement we care about. - else - {statement} -$$")); - } + public Task TestAfterIfNestedIfIncompleteStatementElseStatement(string statement) + => VerifyKeywordAsync(AddInsideMethod( + $""" + if (true) + if (true) + Console // Incomplete, but that's fine. This is not the if statement we care about. + else + {statement} + $$ + """)); [Theory] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] - public async Task TestAfterIfNestedIfIncompleteStatementElseStatement_BeforeElse(string statement) - { - await VerifyKeywordAsync(AddInsideMethod( -$@"if (true) - if (true) - Console // Incomplete, but that's fine. This is not the if statement we care about. - else - {statement} -$$ -else")); - } + public Task TestAfterIfNestedIfIncompleteStatementElseStatement_BeforeElse(string statement) + => VerifyKeywordAsync(AddInsideMethod( + $""" + if (true) + if (true) + Console // Incomplete, but that's fine. This is not the if statement we care about. + else + {statement} + $$ + else + """)); [Fact] - public async Task TestNotInsideStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInsideStatement() + => VerifyAbsenceAsync(AddInsideMethod( """ if (true) Console.WriteLine()$$; // Complete statement, but we're not at the end of it. """)); - } [Fact] - public async Task TestNotAfterSkippedToken() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterSkippedToken() + => VerifyAbsenceAsync(AddInsideMethod( """ if (true) Console.WriteLine();, $$ """)); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/EnableKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/EnableKeywordRecommenderTests.cs index 4df35490b6fea..e29b5196072ed 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/EnableKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/EnableKeywordRecommenderTests.cs @@ -17,14 +17,12 @@ public async Task TestAfterNullable() => await VerifyKeywordAsync(@"#nullable $$"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31130")] - public async Task TestNotAfterNullableAndNewline() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNullableAndNewline() + => VerifyAbsenceAsync(""" #nullable $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31130")] public async Task TestNotAfterHash() @@ -35,34 +33,28 @@ public async Task TestNotAtRoot_Interactive() => await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] public async Task TestNotInUsingAlias() diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/EndIfKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/EndIfKeywordRecommenderTests.cs index 71b1802b18075..eef60ba6b856c 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/EndIfKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/EndIfKeywordRecommenderTests.cs @@ -13,84 +13,64 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class EndIfKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterHash() - { - await VerifyKeywordAsync( + public Task TestAfterHash() + => VerifyKeywordAsync( @"#$$"); - } [Fact] - public async Task TestAfterHashAndSpace() - { - await VerifyKeywordAsync( + public Task TestAfterHashAndSpace() + => VerifyKeywordAsync( @"# $$"); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542971")] - public async Task TestAfterIf() - { - await VerifyKeywordAsync( + public Task TestAfterIf() + => VerifyKeywordAsync( """ #if goo #$$ """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/EndRegionKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/EndRegionKeywordRecommenderTests.cs index 42d97f8c52f6e..f076ec1d0ae7f 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/EndRegionKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/EndRegionKeywordRecommenderTests.cs @@ -12,74 +12,56 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class EndRegionKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterHash() - { - await VerifyKeywordAsync( + public Task TestAfterHash() + => VerifyKeywordAsync( @"#$$"); - } [Fact] - public async Task TestAfterHashAndSpace() - { - await VerifyKeywordAsync( + public Task TestAfterHashAndSpace() + => VerifyKeywordAsync( @"# $$"); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/EnumKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/EnumKeywordRecommenderTests.cs index d011f5fcf03ba..377f4a8040e31 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/EnumKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/EnumKeywordRecommenderTests.cs @@ -12,271 +12,215 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class EnumKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInCompilationUnit() - { - await VerifyKeywordAsync( + public Task TestInCompilationUnit() + => VerifyKeywordAsync( @"$$"); - } [Fact] - public async Task TestAfterExtern() - { - await VerifyKeywordAsync( + public Task TestAfterExtern() + => VerifyKeywordAsync( """ extern alias Goo; $$ """); - } [Fact] - public async Task TestAfterUsing() - { - await VerifyKeywordAsync( + public Task TestAfterUsing() + => VerifyKeywordAsync( """ using Goo; $$ """); - } [Fact] - public async Task TestAfterGlobalUsing() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalUsing() + => VerifyKeywordAsync( """ global using Goo; $$ """); - } [Fact] - public async Task TestAfterNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterNamespace() + => VerifyKeywordAsync( """ namespace N {} $$ """); - } [Fact] - public async Task TestAfterTypeDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterTypeDeclaration() + => VerifyKeywordAsync( """ class C {} $$ """); - } [Fact] - public async Task TestAfterDelegateDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateDeclaration() + => VerifyKeywordAsync( """ delegate void Goo(); $$ """); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ global using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeGlobalUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeGlobalUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ global using Goo; """); - } [Fact] - public async Task TestAfterAssemblyAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterAssemblyAttribute() + => VerifyKeywordAsync( """ [assembly: goo] $$ """); - } [Fact] - public async Task TestAfterRootAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterRootAttribute() + => VerifyKeywordAsync( """ [goo] $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestNotInsideEnum() - { - await VerifyAbsenceAsync(""" + public Task TestNotInsideEnum() + => VerifyAbsenceAsync(""" enum E { $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync(""" + public Task TestInsideInterface() + => VerifyKeywordAsync(""" interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() @@ -287,32 +231,24 @@ public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact] - public async Task TestAfterInternal() - { - await VerifyKeywordAsync( + public Task TestAfterInternal() + => VerifyKeywordAsync( @"internal $$"); - } [Fact] - public async Task TestAfterPublic() - { - await VerifyKeywordAsync( + public Task TestAfterPublic() + => VerifyKeywordAsync( @"public $$"); - } [Fact] - public async Task TestAfterPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterPrivate() + => VerifyKeywordAsync( @"private $$"); - } [Fact] - public async Task TestAfterProtected() - { - await VerifyKeywordAsync( + public Task TestAfterProtected() + => VerifyKeywordAsync( @"protected $$"); - } [Fact] public async Task TestNotAfterSealed() @@ -331,9 +267,8 @@ public async Task TestNotAfterEnum() => await VerifyAbsenceAsync(@"enum $$"); [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -345,5 +280,4 @@ static class C """, CSharpNextParseOptions, CSharpNextScriptParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/EqualsKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/EqualsKeywordRecommenderTests.cs index a1cc2d29eda63..6b4416f5ab73b 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/EqualsKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/EqualsKeywordRecommenderTests.cs @@ -12,110 +12,86 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class EqualsKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterJoinLeftExpr() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterJoinLeftExpr() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y join a in e on o1 $$ """)); - } [Fact] - public async Task TestAfterJoinLeftExpr_NotAfterEquals() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestAfterJoinLeftExpr_NotAfterEquals() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y join a.b c in o1 equals $$ """)); - } [Fact] - public async Task TestAfterJoinLeftExpr_NotAfterIn1() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestAfterJoinLeftExpr_NotAfterIn1() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y join a.b c in $$ """)); - } [Fact] - public async Task TestAfterJoinLeftExpr_NotAfterIn2() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestAfterJoinLeftExpr_NotAfterIn2() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y join a.b c in y $$ """)); - } [Fact] - public async Task TestAfterJoinLeftExpr_NotAfterIn3() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestAfterJoinLeftExpr_NotAfterIn3() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y join a.b c in y on $$ """)); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ErrorKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ErrorKeywordRecommenderTests.cs index 49b26086b5295..4ad5b798a6e91 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ErrorKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ErrorKeywordRecommenderTests.cs @@ -12,74 +12,56 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ErrorKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterHash() - { - await VerifyKeywordAsync( + public Task TestAfterHash() + => VerifyKeywordAsync( @"#$$"); - } [Fact] - public async Task TestAfterHashAndSpace() - { - await VerifyKeywordAsync( + public Task TestAfterHashAndSpace() + => VerifyKeywordAsync( @"# $$"); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/EventKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/EventKeywordRecommenderTests.cs index 9c1cd1d91adb4..5e580d7ae5830 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/EventKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/EventKeywordRecommenderTests.cs @@ -14,320 +14,252 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class EventKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalStatement_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] public async Task TestNotInCompilationUnit() => await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$"); [Fact] - public async Task TestNotAfterExtern() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotAfterExtern() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ extern alias Goo; $$ """); - } [Fact] - public async Task TestAfterExtern_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, """ + public Task TestAfterExtern_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ extern alias Goo; $$ """); - } [Fact] - public async Task TestNotAfterUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotAfterUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ using Goo; $$ """); - } [Fact] - public async Task TestAfterUsing_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, """ + public Task TestAfterUsing_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ using Goo; $$ """); - } [Fact] - public async Task TestNotAfterGlobalUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotAfterGlobalUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ global using Goo; $$ """); - } [Fact] - public async Task TestAfterGlobalUsing_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, """ + public Task TestAfterGlobalUsing_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ global using Goo; $$ """); - } [Fact] - public async Task TestNotAfterNamespace() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotAfterNamespace() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ namespace N {} $$ """); - } [Fact] - public async Task TestNotAfterTypeDeclaration() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotAfterTypeDeclaration() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ class C {} $$ """); - } [Fact] - public async Task TestNotAfterDelegateDeclaration() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotAfterDelegateDeclaration() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ delegate void Goo(); $$ """); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterEvent() - { - await VerifyKeywordAsync( + public Task TestAfterEvent() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ global using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeGlobalUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeGlobalUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ global using Goo; """); - } [Fact] - public async Task TestNotAfterAssemblyAttribute() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotAfterAssemblyAttribute() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ [assembly: goo] $$ """); - } [Fact] - public async Task TestAfterAssemblyAttribute_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, """ + public Task TestAfterAssemblyAttribute_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ [assembly: goo] $$ """); - } [Fact] - public async Task TestNotAfterRootAttribute() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotAfterRootAttribute() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ [goo] $$ """); - } [Fact] - public async Task TestAfterRootAttribute_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, """ + public Task TestAfterRootAttribute_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ [goo] $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync( + public Task TestInsideInterface() + => VerifyKeywordAsync( """ interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] - public async Task TestInsideRecord() - { - // The recommender doesn't work in record in script - // Tracked by https://github.com/dotnet/roslyn/issues/44865 - await VerifyWorkerAsync( + public Task TestInsideRecord() + => VerifyWorkerAsync( """ record C(int i, int j) { $$ """, absent: false, options: TestOptions.RegularPreview); - } [Theory, CombinatorialData] - public async Task TestPartialMember( + public Task TestPartialMember( [CombinatorialValues("class", "record", "struct", "interface")] string kind) - { - await VerifyKeywordAsync( + => VerifyKeywordAsync( $$""" {{kind}} C { partial $$ """); - } [Fact] public async Task TestNotAfterPartial() @@ -346,14 +278,12 @@ public async Task TestAfterInternal_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"internal $$"); [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] public async Task TestNotAfterPublic() @@ -364,79 +294,63 @@ public async Task TestAfterPublic_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"public $$"); [Fact] - public async Task TestAfterNestedPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublic() + => VerifyKeywordAsync( """ class C { public $$ """); - } [Fact] - public async Task TestNotAfterPrivate() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotAfterPrivate() + => VerifyAbsenceAsync(SourceCodeKind.Regular, @"private $$"); - } [Fact] - public async Task TestAfterPrivate_Script() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterPrivate_Script() + => VerifyKeywordAsync(SourceCodeKind.Script, @"private $$"); - } [Fact] - public async Task TestAfterNestedPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPrivate() + => VerifyKeywordAsync( """ class C { private $$ """); - } [Fact] - public async Task TestNotAfterProtected() - { - await VerifyAbsenceAsync( + public Task TestNotAfterProtected() + => VerifyAbsenceAsync( @"protected $$"); - } [Fact] - public async Task TestAfterNestedProtected() - { - await VerifyKeywordAsync( + public Task TestAfterNestedProtected() + => VerifyKeywordAsync( """ class C { protected $$ """); - } [Fact] public async Task TestNotAfterSealed() => await VerifyAbsenceAsync(@"sealed $$"); [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543975")] - public async Task TestAfterUnsafe() - { - await VerifyKeywordAsync( + public Task TestAfterUnsafe() + => VerifyKeywordAsync( """ class C { unsafe $$ """); - } [Fact] public async Task TestNotAfterStatic() @@ -447,14 +361,12 @@ public async Task TestAfterStatic_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"static $$"); [Fact] - public async Task TestAfterStatic() - { - await VerifyKeywordAsync( + public Task TestAfterStatic() + => VerifyKeywordAsync( """ class C { static $$ """); - } [Fact] public async Task TestNotAfterStaticPublic() @@ -465,83 +377,68 @@ public async Task TestAfterStaticPublic_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"static public $$"); [Fact] - public async Task TestAfterNestedStaticPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticPublic() + => VerifyKeywordAsync( """ class C { static public $$ """); - } [Fact] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact] - public async Task TestNotAfterEvent() - { - await VerifyAbsenceAsync( + public Task TestNotAfterEvent() + => VerifyAbsenceAsync( """ class C { event $$ """); - } [Fact] - public async Task TestNotAfterNested() - { - await VerifyAbsenceAsync( + public Task TestNotAfterNested() + => VerifyAbsenceAsync( @"new $$"); - } [Fact] - public async Task TestAfterNestedNew() - { - await VerifyKeywordAsync( + public Task TestAfterNestedNew() + => VerifyKeywordAsync( """ class C { new $$ """); - } [Fact] - public async Task TestInAttributeInsideClass() - { - await VerifyKeywordAsync( + public Task TestInAttributeInsideClass() + => VerifyKeywordAsync( """ class C { [$$ """); - } [Fact] - public async Task TestInAttributeAfterAttributeInsideClass() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterAttributeInsideClass() + => VerifyKeywordAsync( """ class C { [Goo] [$$ """); - } [Fact] - public async Task TestInAttributeAfterMethod() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() { } [$$ """); - } [Fact] - public async Task TestInAttributeAfterProperty() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterProperty() + => VerifyKeywordAsync( """ class C { int Goo { @@ -549,117 +446,93 @@ int Goo { } [$$ """); - } [Fact] - public async Task TestInAttributeAfterField() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterField() + => VerifyKeywordAsync( """ class C { int Goo; [$$ """); - } [Fact] - public async Task TestInAttributeAfterEvent() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterEvent() + => VerifyKeywordAsync( """ class C { event Action Goo; [$$ """); - } [Fact] - public async Task TestNotInOuterAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInOuterAttribute() + => VerifyAbsenceAsync( @"[$$"); - } [Fact] - public async Task TestNotInParameterAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInParameterAttribute() + => VerifyAbsenceAsync( """ class C { void Goo([$$ """); - } [Fact] - public async Task TestNotInPropertyAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAttribute() + => VerifyAbsenceAsync( """ class C { int Goo { [$$ """); - } [Fact] - public async Task TestNotInEventAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInEventAttribute() + => VerifyAbsenceAsync( """ class C { event Action Goo { [$$ """); - } [Fact] - public async Task TestNotInTypeParameters() - { - await VerifyAbsenceAsync( + public Task TestNotInTypeParameters() + => VerifyAbsenceAsync( @"class C<[$$"); - } [Fact] - public async Task TestInInterface() - { - await VerifyKeywordAsync( + public Task TestInInterface() + => VerifyKeywordAsync( """ interface I { [$$ """); - } [Fact] - public async Task TestInStruct() - { - await VerifyKeywordAsync( + public Task TestInStruct() + => VerifyKeywordAsync( """ struct S { [$$ """); - } [Fact] - public async Task TestNotInEnum() - { - await VerifyAbsenceAsync( + public Task TestNotInEnum() + => VerifyAbsenceAsync( """ enum E { [$$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68399")] - public async Task TestNotInRecordParameterAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInRecordParameterAttribute() + => VerifyAbsenceAsync( """ record R([$$] int i) { } """); - } [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -669,7 +542,6 @@ static class C } } """, - CSharpNextParseOptions, - CSharpNextScriptParseOptions); - } + CSharpNextParseOptions, + CSharpNextScriptParseOptions); } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ExplicitKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ExplicitKeywordRecommenderTests.cs index 6b9ce9acf3724..21ff6651e22ab 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ExplicitKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ExplicitKeywordRecommenderTests.cs @@ -13,252 +13,200 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ExplicitKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] public async Task TestNotInCompilationUnit() => await VerifyAbsenceAsync(@"$$"); [Fact] - public async Task TestNotAfterExtern() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterExtern() + => VerifyAbsenceAsync(""" extern alias Goo; $$ """); - } [Fact] - public async Task TestNotAfterUsing() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterUsing() + => VerifyAbsenceAsync(""" using Goo; $$ """); - } [Fact] - public async Task TestNotAfterGlobalUsing() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterGlobalUsing() + => VerifyAbsenceAsync(""" global using Goo; $$ """); - } [Fact] - public async Task TestNotAfterNamespace() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNamespace() + => VerifyAbsenceAsync(""" namespace N {} $$ """); - } [Fact] - public async Task TestNotAfterTypeDeclaration() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterTypeDeclaration() + => VerifyAbsenceAsync(""" class C {} $$ """); - } [Fact] - public async Task TestNotAfterDelegateDeclaration() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterDelegateDeclaration() + => VerifyAbsenceAsync(""" delegate void Goo(); $$ """); - } [Fact] - public async Task TestNotAfterMethod() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterMethod() + => VerifyAbsenceAsync(""" class C { void Goo() {} $$ """); - } [Fact] - public async Task TestNotAfterMethodInPartialType() - { - await VerifyAbsenceAsync( + public Task TestNotAfterMethodInPartialType() + => VerifyAbsenceAsync( """ partial class C { void Goo() {} $$ """); - } [Fact] - public async Task TestNotAfterFieldInPartialClass() - { - await VerifyAbsenceAsync( + public Task TestNotAfterFieldInPartialClass() + => VerifyAbsenceAsync( """ partial class C { int i; $$ """); - } [Fact] - public async Task TestNotAfterPropertyInPartialClass() - { - await VerifyAbsenceAsync( + public Task TestNotAfterPropertyInPartialClass() + => VerifyAbsenceAsync( """ partial class C { int i { get; } $$ """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync( + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync( """ $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync( + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync( """ $$ global using Goo; """); - } [Fact] - public async Task TestNotAfterAssemblyAttribute() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterAssemblyAttribute() + => VerifyAbsenceAsync(""" [assembly: goo] $$ """); - } [Fact] - public async Task TestNotAfterRootAttribute() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterRootAttribute() + => VerifyAbsenceAsync(""" [goo] $$ """); - } [Fact] - public async Task TestNotAfterNestedAttributeInPartialClass() - { - await VerifyAbsenceAsync( + public Task TestNotAfterNestedAttributeInPartialClass() + => VerifyAbsenceAsync( """ partial class C { [goo] $$ """); - } // This will be fixed once we have accessibility for members [Fact] - public async Task TestNotInsideStruct() - { - await VerifyAbsenceAsync(""" + public Task TestNotInsideStruct() + => VerifyAbsenceAsync(""" struct S { $$ """); - } // This will be fixed once we have accessibility for members [Fact] - public async Task TestNotInsidePartialStruct() - { - await VerifyAbsenceAsync( + public Task TestNotInsidePartialStruct() + => VerifyAbsenceAsync( """ partial struct S { $$ """); - } [Fact] - public async Task TestNotInsideInterface() - { - await VerifyAbsenceAsync(""" + public Task TestNotInsideInterface() + => VerifyAbsenceAsync(""" interface I { $$ """); - } [Fact] - public async Task TestNotInsidePartialClass() - { - await VerifyAbsenceAsync( + public Task TestNotInsidePartialClass() + => VerifyAbsenceAsync( """ partial class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() @@ -281,138 +229,112 @@ public async Task TestNotAfterStaticPublic() => await VerifyAbsenceAsync(@"static public $$"); [Fact] - public async Task TestAfterNestedStaticPublicInClass() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticPublicInClass() + => VerifyKeywordAsync( """ class C { static public $$ """); - } [Fact] - public async Task TestNotAfterNestedStaticPublicInInterface() - { - await VerifyAbsenceAsync( + public Task TestNotAfterNestedStaticPublicInInterface() + => VerifyAbsenceAsync( """ interface C { static public $$ """); - } [Fact] - public async Task TestNotAfterNestedAbstractPublicInInterface() - { - await VerifyAbsenceAsync( + public Task TestNotAfterNestedAbstractPublicInInterface() + => VerifyAbsenceAsync( """ interface C { abstract public $$ """); - } [Fact] - public async Task TestAfterNestedStaticAbstractPublicInInterface() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticAbstractPublicInInterface() + => VerifyKeywordAsync( """ interface C { static abstract public $$ """); - } [Fact] - public async Task TestAfterNestedAbstractStaticPublicInInterface() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstractStaticPublicInInterface() + => VerifyKeywordAsync( """ interface C { abstract static public $$ """); - } [Fact] - public async Task TestAfterNestedStaticAbstractInInterface() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticAbstractInInterface() + => VerifyKeywordAsync( """ interface C { static abstract $$ """); - } [Fact] - public async Task TestAfterNestedAbstractStaticInInterface() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstractStaticInInterface() + => VerifyKeywordAsync( """ interface C { abstract static $$ """); - } [Fact] - public async Task TestNotAfterNestedStaticInInterface() - { - await VerifyAbsenceAsync( + public Task TestNotAfterNestedStaticInInterface() + => VerifyAbsenceAsync( """ interface C { static $$ """); - } [Fact] public async Task TestNotAfterPublicStatic() => await VerifyAbsenceAsync(@"public static $$"); [Fact] - public async Task TestAfterNestedPublicStaticInClass() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublicStaticInClass() + => VerifyKeywordAsync( """ class C { public static $$ """); - } [Fact] - public async Task TestNotAfterNestedPublicStaticInInterface() - { - await VerifyAbsenceAsync( + public Task TestNotAfterNestedPublicStaticInInterface() + => VerifyAbsenceAsync( """ interface C { public static $$ """); - } [Fact] - public async Task TestNotAfterNestedPublicAbstractInInterface() - { - await VerifyAbsenceAsync( + public Task TestNotAfterNestedPublicAbstractInInterface() + => VerifyAbsenceAsync( """ interface C { public abstract $$ """); - } [Fact] - public async Task TestAfterNestedPublicStaticAbstractInInterface() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublicStaticAbstractInInterface() + => VerifyKeywordAsync( """ interface C { public static abstract $$ """); - } [Fact] - public async Task TestAfterNestedPublicAbstractStaticInInterface() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublicAbstractStaticInInterface() + => VerifyKeywordAsync( """ interface C { public abstract static $$ """); - } [Fact] public async Task TestNotAfterInvalidPublic() @@ -443,152 +365,120 @@ public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact] - public async Task TestNotBetweenUsings() - { - await VerifyAbsenceAsync( + public Task TestNotBetweenUsings() + => VerifyAbsenceAsync( """ using Goo; $$ using Bar; """); - } [Fact] - public async Task TestNotBetweenGlobalUsings_01() - { - await VerifyAbsenceAsync( + public Task TestNotBetweenGlobalUsings_01() + => VerifyAbsenceAsync( """ global using Goo; $$ using Bar; """); - } [Fact] - public async Task TestNotBetweenGlobalUsings_02() - { - await VerifyAbsenceAsync( + public Task TestNotBetweenGlobalUsings_02() + => VerifyAbsenceAsync( """ global using Goo; $$ global using Bar; """); - } [Fact] - public async Task TestNotAfterNestedAbstractInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedAbstractInClass() + => VerifyAbsenceAsync(""" class C { abstract $$ """); - } [Fact] - public async Task TestNotAfterNestedVirtualInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedVirtualInClass() + => VerifyAbsenceAsync(""" class C { virtual $$ """); - } [Fact] - public async Task TestNotAfterNestedOverrideInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedOverrideInClass() + => VerifyAbsenceAsync(""" class C { override $$ """); - } [Fact] - public async Task TestNotAfterNestedSealedInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedSealedInClass() + => VerifyAbsenceAsync(""" class C { sealed $$ """); - } [Fact] - public async Task TestNotAfterNestedReadOnlyInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedReadOnlyInClass() + => VerifyAbsenceAsync(""" class C { readonly $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544102")] - public async Task TestAfterNestedUnsafeStaticPublicInClass() - { - await VerifyKeywordAsync(""" + public Task TestAfterNestedUnsafeStaticPublicInClass() + => VerifyKeywordAsync(""" class C { unsafe static public $$ """); - } [Fact] - public async Task TestNotAfterNestedAbstractInInterface() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedAbstractInInterface() + => VerifyAbsenceAsync(""" interface C { abstract $$ """); - } [Fact] - public async Task TestNotAfterNestedVirtualInInterface() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedVirtualInInterface() + => VerifyAbsenceAsync(""" interface C { virtual $$ """); - } [Fact] - public async Task TestNotAfterNestedOverrideInInterface() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedOverrideInInterface() + => VerifyAbsenceAsync(""" interface C { override $$ """); - } [Fact] - public async Task TestNotAfterNestedSealedInInterface() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedSealedInInterface() + => VerifyAbsenceAsync(""" interface C { sealed $$ """); - } [Fact] - public async Task TestNotAfterNestedReadOnlyInInterface() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedReadOnlyInInterface() + => VerifyAbsenceAsync(""" interface C { readonly $$ """); - } [Fact] - public async Task TestAfterUnsafeStaticAbstractInInterface() - { - await VerifyKeywordAsync(""" + public Task TestAfterUnsafeStaticAbstractInInterface() + => VerifyKeywordAsync(""" interface C { unsafe static abstract $$ """); - } [Fact] - public async Task TestNotAfterExternStaticAbstractInInterface() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterExternStaticAbstractInInterface() + => VerifyAbsenceAsync(""" interface C { extern static abstract $$ """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ExtensionKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ExtensionKeywordRecommenderTests.cs index c8fe8ee566b3e..74c2c806edd1d 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ExtensionKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ExtensionKeywordRecommenderTests.cs @@ -15,117 +15,96 @@ public sealed class ExtensionKeywordRecommenderTests : KeywordRecommenderTests private static readonly CSharpParseOptions s_options = CSharpNextParseOptions; [Fact] - public async Task NotInRoot() - { - await VerifyAbsenceAsync(@"$$", s_options); - } + public Task NotInRoot() + => VerifyAbsenceAsync(@"$$", s_options); [Fact] - public async Task NotInNormalClass() - { - await VerifyAbsenceAsync(""" + public Task NotInNormalClass() + => VerifyAbsenceAsync(""" class C { $$ } """, s_options); - } [Fact] - public async Task InStaticClass() - { - await VerifyKeywordAsync(""" + public Task InStaticClass() + => VerifyKeywordAsync(""" static class C { $$ } """, s_options); - } [Fact] - public async Task NotAfterAccessibilityInStaticClass() - { - await VerifyAbsenceAsync(""" + public Task NotAfterAccessibilityInStaticClass() + => VerifyAbsenceAsync(""" static class C { public $$ } """, s_options); - } [Fact] - public async Task NotAfterModifierInStaticClass() - { - await VerifyAbsenceAsync(""" + public Task NotAfterModifierInStaticClass() + => VerifyAbsenceAsync(""" static class C { unsafe $$ } """, s_options); - } [Fact] - public async Task NotAfterPartialInStaticClass() - { - await VerifyAbsenceAsync(""" + public Task NotAfterPartialInStaticClass() + => VerifyAbsenceAsync(""" static class C { partial $$ } """, s_options); - } [Fact] - public async Task NotInStaticStructClass() - { - await VerifyAbsenceAsync(""" + public Task NotInStaticStructClass() + => VerifyAbsenceAsync(""" static struct C { $$ } """, s_options); - } [Fact] - public async Task AfterMethodInStaticClass() - { - await VerifyKeywordAsync(""" + public Task AfterMethodInStaticClass() + => VerifyKeywordAsync(""" static class C { void M() { } $$ } """, s_options); - } [Fact] - public async Task AfterClassInStaticClass() - { - await VerifyKeywordAsync(""" + public Task AfterClassInStaticClass() + => VerifyKeywordAsync(""" static class C { class M { } $$ } """, s_options); - } [Fact] - public async Task AfterExtensionInStaticClass() - { - await VerifyKeywordAsync(""" + public Task AfterExtensionInStaticClass() + => VerifyKeywordAsync(""" static class C { extension E() { } $$ } """, s_options); - } [Fact] - public async Task NotInClassInStaticClass() - { - await VerifyAbsenceAsync(""" + public Task NotInClassInStaticClass() + => VerifyAbsenceAsync(""" static class C { class C @@ -134,12 +113,10 @@ class C } } """, s_options); - } [Fact] - public async Task TestWithinExtension() - { - await VerifyAbsenceAsync( + public Task TestWithinExtension() + => VerifyAbsenceAsync( """ static class C { @@ -149,5 +126,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ExternKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ExternKeywordRecommenderTests.cs index 907956dc0e9f1..1fead06ac67e1 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ExternKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ExternKeywordRecommenderTests.cs @@ -12,81 +12,62 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ExternKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot() - { - await VerifyKeywordAsync( + public Task TestAtRoot() + => VerifyKeywordAsync( @"$$"); - } [Fact] - public async Task TestAfterClass() - { - await VerifyKeywordAsync( + public Task TestAfterClass() + => VerifyKeywordAsync( """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalVariableDeclaration() + => VerifyKeywordAsync( """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Theory, CombinatorialData] - public async Task TestInEmptyStatement(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterStaticInStatement(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterStaticInStatement(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"static $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterAttributesInStatement(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterAttributesInStatement(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"[Attr] $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterAttributesInSwitchCase(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterAttributesInSwitchCase(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ switch (c) { @@ -95,262 +76,210 @@ await VerifyKeywordAsync(AddInsideMethod( $$ } """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterAttributesAndStaticInStatement(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterAttributesAndStaticInStatement(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"[Attr] static $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestBetweenAttributesAndReturnStatement(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBetweenAttributesAndReturnStatement(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ [Attr] $$ return x; """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestBetweenAttributesAndLocalDeclarationStatement(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBetweenAttributesAndLocalDeclarationStatement(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ [Attr] $$ x y = bar(); """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestBetweenAttributesAndAwaitExpression(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBetweenAttributesAndAwaitExpression(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ [Attr] $$ await bar; """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestBetweenAttributesAndAssignmentStatement(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBetweenAttributesAndAssignmentStatement(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ [Goo] $$ y = bar(); """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestBetweenAttributesAndCallStatement1(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBetweenAttributesAndCallStatement1(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ [Goo] $$ bar(); """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestBetweenAttributesAndCallStatement2(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBetweenAttributesAndCallStatement2(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ [Goo1] [Goo2] $$ bar(); """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestNotAfterExternInStatement(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterExternInStatement(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( @"extern $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] public async Task TestNotAfterExternKeyword() => await VerifyAbsenceAsync(@"extern $$"); [Fact] - public async Task TestAfterPreviousExternAlias() - { - await VerifyKeywordAsync( + public Task TestAfterPreviousExternAlias() + => VerifyKeywordAsync( """ extern alias Goo; $$ """); - } [Fact] - public async Task TestAfterUsing() - { - await VerifyKeywordAsync(""" + public Task TestAfterUsing() + => VerifyKeywordAsync(""" using Goo; $$ """); - } [Fact] - public async Task TestAfterGlobalUsing() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalUsing() + => VerifyKeywordAsync( """ global using Goo; $$ """); - } [Fact] - public async Task TestAfterNamespace() - { - await VerifyKeywordAsync(""" + public Task TestAfterNamespace() + => VerifyKeywordAsync(""" namespace N {} $$ """); - } [Fact] - public async Task TestInsideNamespace() - { - await VerifyKeywordAsync( + public Task TestInsideNamespace() + => VerifyKeywordAsync( """ namespace N { $$ """); - } [Fact] - public async Task TestInsideFileScopedNamespace() - { - await VerifyKeywordAsync( + public Task TestInsideFileScopedNamespace() + => VerifyKeywordAsync( @"namespace N;$$"); - } [Fact] - public async Task TestNotAfterExternKeyword_InsideNamespace() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterExternKeyword_InsideNamespace() + => VerifyAbsenceAsync(""" namespace N { extern $$ """); - } [Fact] - public async Task TestAfterPreviousExternAlias_InsideNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterPreviousExternAlias_InsideNamespace() + => VerifyKeywordAsync( """ namespace N { extern alias Goo; $$ """); - } [Fact] - public async Task TestNotAfterUsing_InsideNamespace() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterUsing_InsideNamespace() + => VerifyAbsenceAsync(""" namespace N { using Goo; $$ """); - } [Fact] - public async Task TestNotAfterMember_InsideNamespace() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterMember_InsideNamespace() + => VerifyAbsenceAsync(""" namespace N { class C {} $$ """); - } [Fact] - public async Task TestNotAfterNamespace_InsideNamespace() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNamespace_InsideNamespace() + => VerifyAbsenceAsync(""" namespace N { namespace N {} $$ """); - } [Fact] - public async Task TestInClass() - { - await VerifyKeywordAsync( + public Task TestInClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] - public async Task TestInStruct() - { - await VerifyKeywordAsync( + public Task TestInStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInInterface() - { - await VerifyKeywordAsync( + public Task TestInInterface() + => VerifyKeywordAsync( """ interface I { $$ """); - } [Fact] - public async Task TestNotAfterAbstract() - { - await VerifyAbsenceAsync( + public Task TestNotAfterAbstract() + => VerifyAbsenceAsync( """ class C { abstract $$ """); - } [Fact] - public async Task TestNotAfterExtern() - { - await VerifyAbsenceAsync( + public Task TestNotAfterExtern() + => VerifyAbsenceAsync( """ class C { extern $$ """); - } [Fact] - public async Task TestAfterPublic() - { - await VerifyKeywordAsync( + public Task TestAfterPublic() + => VerifyKeywordAsync( """ class C { public $$ """); - } [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -360,5 +289,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/FalseKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/FalseKeywordRecommenderTests.cs index e9504136fa285..675411db3c7d7 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/FalseKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/FalseKeywordRecommenderTests.cs @@ -13,282 +13,217 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class FalseKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInPreprocessor1() - { - await VerifyAbsenceAsync( + public Task TestNotInPreprocessor1() + => VerifyAbsenceAsync( """ class C { #$$ """); - } [Fact] - public async Task TestNotInPreprocessor2() - { - await VerifyAbsenceAsync( + public Task TestNotInPreprocessor2() + => VerifyAbsenceAsync( """ class C { #line $$ """); - } [Fact] - public async Task TestInEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInExpression() + => VerifyKeywordAsync(AddInsideMethod( @"var q = $$")); - } [Fact] - public async Task TestInPPIf() - { - await VerifyKeywordAsync( + public Task TestInPPIf() + => VerifyKeywordAsync( @"#if $$"); - } [Fact] - public async Task TestInPPIf_Or() - { - await VerifyKeywordAsync( + public Task TestInPPIf_Or() + => VerifyKeywordAsync( @"#if a || $$"); - } [Fact] - public async Task TestInPPIf_And() - { - await VerifyKeywordAsync( + public Task TestInPPIf_And() + => VerifyKeywordAsync( @"#if a && $$"); - } [Fact] - public async Task TestInPPIf_Not() - { - await VerifyKeywordAsync( + public Task TestInPPIf_Not() + => VerifyKeywordAsync( @"#if ! $$"); - } [Fact] - public async Task TestInPPIf_Paren() - { - await VerifyKeywordAsync( + public Task TestInPPIf_Paren() + => VerifyKeywordAsync( @"#if ( $$"); - } [Fact] - public async Task TestInPPIf_Equals() - { - await VerifyKeywordAsync( + public Task TestInPPIf_Equals() + => VerifyKeywordAsync( @"#if a == $$"); - } [Fact] - public async Task TestInPPIf_NotEquals() - { - await VerifyKeywordAsync( + public Task TestInPPIf_NotEquals() + => VerifyKeywordAsync( @"#if a != $$"); - } [Fact] - public async Task TestInPPElIf() - { - await VerifyKeywordAsync( + public Task TestInPPElIf() + => VerifyKeywordAsync( """ #if true #elif $$ """); - } [Fact] - public async Task TestInPPelIf_Or() - { - await VerifyKeywordAsync( + public Task TestInPPelIf_Or() + => VerifyKeywordAsync( """ #if true #elif a || $$ """); - } [Fact] - public async Task TestInPPElIf_And() - { - await VerifyKeywordAsync( + public Task TestInPPElIf_And() + => VerifyKeywordAsync( """ #if true #elif a && $$ """); - } [Fact] - public async Task TestInPPElIf_Not() - { - await VerifyKeywordAsync( + public Task TestInPPElIf_Not() + => VerifyKeywordAsync( """ #if true #elif ! $$ """); - } [Fact] - public async Task TestInPPElIf_Paren() - { - await VerifyKeywordAsync( + public Task TestInPPElIf_Paren() + => VerifyKeywordAsync( """ #if true #elif ( $$ """); - } [Fact] - public async Task TestInPPElIf_Equals() - { - await VerifyKeywordAsync( + public Task TestInPPElIf_Equals() + => VerifyKeywordAsync( """ #if true #elif a == $$ """); - } [Fact] - public async Task TestInPPElIf_NotEquals() - { - await VerifyKeywordAsync( + public Task TestInPPElIf_NotEquals() + => VerifyKeywordAsync( """ #if true #elif a != $$ """); - } [Fact] - public async Task TestAfterUnaryOperator() - { - await VerifyKeywordAsync( + public Task TestAfterUnaryOperator() + => VerifyKeywordAsync( """ class C { public static bool operator $$ """); - } [Fact] - public async Task TestNotAfterImplicitOperator() - { - await VerifyAbsenceAsync( + public Task TestNotAfterImplicitOperator() + => VerifyAbsenceAsync( """ class C { public static implicit operator $$ """); - } [Fact] - public async Task TestNotAfterExplicitOperator() - { - await VerifyAbsenceAsync( + public Task TestNotAfterExplicitOperator() + => VerifyAbsenceAsync( """ class C { public static implicit operator $$ """); - } [Fact] - public async Task TestInNamedParameter() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInNamedParameter() + => VerifyKeywordAsync(AddInsideMethod( """ return new SingleDeclaration( kind: GetKind(node.Kind), hasUsings: $$ """)); - } [Fact] - public async Task TestInAttribute() - { - await VerifyKeywordAsync( + public Task TestInAttribute() + => VerifyKeywordAsync( @"[assembly: ComVisible($$"); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInTypeOf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInTypeOf() + => VerifyAbsenceAsync(AddInsideMethod( @"typeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInDefault() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInDefault() + => VerifyAbsenceAsync(AddInsideMethod( @"default($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInSizeOf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInSizeOf() + => VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -296,130 +231,107 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/FieldKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/FieldKeywordRecommenderTests.cs index b727f1250f53b..e81d3e08b8501 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/FieldKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/FieldKeywordRecommenderTests.cs @@ -14,145 +14,114 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class FieldKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """$$"""); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( """using Goo = $$"""); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( """global using Goo = $$"""); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( """$$""")); - } [Fact] - public async Task TestInAttributeInsideClass() - { - await VerifyKeywordAsync( + public Task TestInAttributeInsideClass() + => VerifyKeywordAsync( """ class C { [$$ """); - } [Fact] - public async Task TestNotInAttributeArgumentInsideClass1() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeArgumentInsideClass1() + => VerifyAbsenceAsync( """ class C { [field: $$ """); - } [Fact] - public async Task TestNotInAttributeArgumentInsideClass2() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeArgumentInsideClass2() + => VerifyAbsenceAsync( """ class C { [field: Goo($$)] """); - } [Fact] - public async Task TestNotInAttributeArgumentInsideClass3() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeArgumentInsideClass3() + => VerifyAbsenceAsync( """ class C { [field: Goo($$)] int Prop { get; } """); - } [Theory] [InlineData("record")] [InlineData("record class")] [InlineData("record struct")] - public async Task TestInAttributeInsideRecord(string record) - { - // The recommender doesn't work in record in script - // Tracked by https://github.com/dotnet/roslyn/issues/44865 - await VerifyWorkerAsync( + public Task TestInAttributeInsideRecord(string record) + => VerifyWorkerAsync( $$""" {{record}} C { [$$ """, absent: false, TestOptions.RegularPreview); - } [Fact] - public async Task TestInAttributeAfterAttributeInsideClass() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterAttributeInsideClass() + => VerifyKeywordAsync( """ class C { [Goo] [$$ """); - } [Fact] - public async Task TestInAttributeAfterMethod() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() { } [$$ """); - } [Fact] - public async Task TestInAttributeAfterProperty() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterProperty() + => VerifyKeywordAsync( """ class C { int Goo { @@ -160,228 +129,186 @@ int Goo { } [$$ """); - } [Fact] - public async Task TestInAttributeAfterField() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterField() + => VerifyKeywordAsync( """ class C { int Goo; [$$ """); - } [Fact] - public async Task TestInAttributeAfterEvent() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterEvent() + => VerifyKeywordAsync( """ class C { event Action Goo; [$$ """); - } [Fact] - public async Task TestNotInOuterAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInOuterAttribute() + => VerifyAbsenceAsync( """[$$"""); - } [Fact] - public async Task TestNotInParameterAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInParameterAttribute() + => VerifyAbsenceAsync( """ class C { void Goo([$$ """); - } [Fact] - public async Task TestNotInPropertyAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAttribute() + => VerifyAbsenceAsync( """ class C { int Goo { [$$ """); - } [Fact] - public async Task TestNotInEventAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInEventAttribute() + => VerifyAbsenceAsync( """ class C { event Action Goo { [$$ """); - } [Fact] - public async Task TestNotInTypeParameters() - { - await VerifyAbsenceAsync( + public Task TestNotInTypeParameters() + => VerifyAbsenceAsync( """class C<[$$"""); - } [Fact] - public async Task TestNotInInterface() - { - await VerifyAbsenceAsync( + public Task TestNotInInterface() + => VerifyAbsenceAsync( """ interface I { [$$ """); - } [Fact] - public async Task TestInStruct() - { - await VerifyKeywordAsync( + public Task TestInStruct() + => VerifyKeywordAsync( """ struct S { [$$ """); - } [Fact] - public async Task TestInEnum() - { - await VerifyKeywordAsync( + public Task TestInEnum() + => VerifyKeywordAsync( """ enum E { [$$ """); - } [Fact] - public async Task TestNotInPropertyInitializer() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyInitializer() + => VerifyAbsenceAsync( """ class C { int Goo { get; } = $$ } """); - } [Fact] - public async Task TestInPropertyExpressionBody() - { - await VerifyKeywordAsync( + public Task TestInPropertyExpressionBody() + => VerifyKeywordAsync( """ class C { int Goo => $$ } """); - } [Fact] - public async Task TestNotInPropertyExpressionBody_NotPrimary() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyExpressionBody_NotPrimary() + => VerifyAbsenceAsync( """ class C { int Goo => this.$$ } """); - } [Fact] - public async Task TestInPropertyAccessor1() - { - await VerifyKeywordAsync( + public Task TestInPropertyAccessor1() + => VerifyKeywordAsync( """ class C { int Goo { get => $$ } } """); - } [Fact] - public async Task TestInPropertyAccessor2() - { - await VerifyKeywordAsync( + public Task TestInPropertyAccessor2() + => VerifyKeywordAsync( """ class C { int Goo { get { return $$ } } } """); - } [Fact] - public async Task TestInPropertyStatement() - { - await VerifyKeywordAsync( + public Task TestInPropertyStatement() + => VerifyKeywordAsync( """ class C { int Goo { get { $$ } } } """); - } [Fact] - public async Task TestInPropertyExpressionContext() - { - await VerifyKeywordAsync( + public Task TestInPropertyExpressionContext() + => VerifyKeywordAsync( """ class C { int Goo { get { var v = 1 + $$ } } } """); - } [Fact] - public async Task TestInPropertyArgument1() - { - await VerifyKeywordAsync( + public Task TestInPropertyArgument1() + => VerifyKeywordAsync( """ class C { int Goo { get { Bar($$) } } } """); - } [Fact] - public async Task TestInPropertyArgument2() - { - await VerifyKeywordAsync( + public Task TestInPropertyArgument2() + => VerifyKeywordAsync( """ class C { int Goo { get { Bar(ref $$) } } } """); - } [Fact] - public async Task TestNotInPropertyNameof() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyNameof() + => VerifyAbsenceAsync( """ class C { int Goo { get { Bar(nameof($$)) } } } """); - } [Fact] - public async Task TestInLocalFunctionInProperty() - { - await VerifyKeywordAsync( + public Task TestInLocalFunctionInProperty() + => VerifyKeywordAsync( """ class C { @@ -394,12 +321,10 @@ int Goo } } """); - } [Fact] - public async Task TestInLambdaInProperty() - { - await VerifyKeywordAsync( + public Task TestInLambdaInProperty() + => VerifyKeywordAsync( """ class C { @@ -412,12 +337,10 @@ int Goo } } """); - } [Fact] - public async Task TestNotInAccessorAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInAccessorAttribute() + => VerifyAbsenceAsync( """ class C { @@ -425,60 +348,50 @@ class C int Goo { get; } } """); - } [Fact] - public async Task TestNotInIndexer1() - { - await VerifyAbsenceAsync( + public Task TestNotInIndexer1() + => VerifyAbsenceAsync( """ class C { int this[int index] => $$ } """); - } [Fact] - public async Task TestNotInIndexer2() - { - await VerifyAbsenceAsync( + public Task TestNotInIndexer2() + => VerifyAbsenceAsync( """ class C { int this[int index] { get => $$ } } """); - } [Fact] - public async Task TestNotInIndexer3() - { - await VerifyAbsenceAsync( + public Task TestNotInIndexer3() + => VerifyAbsenceAsync( """ class C { int this[int index] { get { return $$ } } } """); - } [Fact] - public async Task TestNotInEvent1() - { - await VerifyAbsenceAsync( + public Task TestNotInEvent1() + => VerifyAbsenceAsync( """ class C { event Action E { add { $$ } } } """); - } [Fact] - public async Task TestNotInMethodContext() - { - await VerifyAbsenceAsync( + public Task TestNotInMethodContext() + => VerifyAbsenceAsync( """ class C { @@ -488,12 +401,10 @@ void M() } } """); - } [Fact] - public async Task TestNotInMethodExpressionContext() - { - await VerifyAbsenceAsync( + public Task TestNotInMethodExpressionContext() + => VerifyAbsenceAsync( """ class C { @@ -503,23 +414,18 @@ void M() } } """); - } [Fact] - public async Task TestNotInGlobalStatement() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalStatement() + => VerifyAbsenceAsync( """ $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68399")] - public async Task TestInRecordParameterAttribute() - { - await VerifyKeywordAsync( + public Task TestInRecordParameterAttribute() + => VerifyKeywordAsync( """ record R([$$] int i) { } """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/FinallyKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/FinallyKeywordRecommenderTests.cs index 71c2f80cd6778..c2ae9ca397a23 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/FinallyKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/FinallyKeywordRecommenderTests.cs @@ -12,106 +12,83 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class FinallyKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterTry() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterTry() + => VerifyKeywordAsync(AddInsideMethod( """ try { } $$ """)); - } [Fact] - public async Task TestAfterTryCatch() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterTryCatch() + => VerifyKeywordAsync(AddInsideMethod( """ try { } catch { } $$ """)); - } [Fact] - public async Task TestNotAfterFinallyBlock() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterFinallyBlock() + => VerifyAbsenceAsync(AddInsideMethod( """ try { } finally { } $$ """)); - } [Fact] - public async Task TestNotInStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestNotAfterBlock() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterBlock() + => VerifyAbsenceAsync(AddInsideMethod( """ if (true) { @@ -119,25 +96,20 @@ await VerifyAbsenceAsync(AddInsideMethod( } $$ """)); - } [Fact] - public async Task TestNotAfterFinallyKeyword() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterFinallyKeyword() + => VerifyAbsenceAsync(AddInsideMethod( """ try { } finally $$ """)); - } [Fact] - public async Task TestNotInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotInClass() + => VerifyAbsenceAsync(""" class C { $$ } """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/FixedKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/FixedKeywordRecommenderTests.cs index 2945753a4c23e..0704d44352cf0 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/FixedKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/FixedKeywordRecommenderTests.cs @@ -13,172 +13,137 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class FixedKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInsideEmptyMethod() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInsideEmptyMethod() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInsideUnsafeBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideUnsafeBlock() + => VerifyKeywordAsync(AddInsideMethod( """ unsafe { $$ """)); - } [Fact] - public async Task TestAfterFixed() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterFixed() + => VerifyKeywordAsync(AddInsideMethod( """ unsafe { fixed (int* = bar) { } $$ """)); - } [Fact] - public async Task TestNotAfterFixed() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterFixed() + => VerifyAbsenceAsync(AddInsideMethod( """ fixed (int* = bar) { } $$ """)); - } [Fact] - public async Task TestNotInClass() - { - await VerifyAbsenceAsync( + public Task TestNotInClass() + => VerifyAbsenceAsync( """ class C { $$ """); - } [Fact] - public async Task TestNotInStruct() - { - await VerifyAbsenceAsync( + public Task TestNotInStruct() + => VerifyAbsenceAsync( """ struct S { $$ """); - } [Fact] - public async Task TestNotInRecordStruct() - { - await VerifyAbsenceAsync( + public Task TestNotInRecordStruct() + => VerifyAbsenceAsync( """ record struct S { $$ """); - } [Fact] - public async Task TestInUnsafeStruct() - { - await VerifyKeywordAsync( + public Task TestInUnsafeStruct() + => VerifyKeywordAsync( """ unsafe struct S { $$ """); - } [Fact] - public async Task TestInUnsafeNestedStruct1() - { - await VerifyKeywordAsync( + public Task TestInUnsafeNestedStruct1() + => VerifyKeywordAsync( """ unsafe struct S { struct T { $$ """); - } [Fact] - public async Task TestInUnsafeNestedStruct2() - { - await VerifyKeywordAsync( + public Task TestInUnsafeNestedStruct2() + => VerifyKeywordAsync( """ struct S { unsafe struct T { $$ """); - } [Fact] - public async Task TestNotAfterStatic() - { - await VerifyAbsenceAsync( + public Task TestNotAfterStatic() + => VerifyAbsenceAsync( """ unsafe struct S { static $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52296")] - public async Task TestInUnsafeLocalFunction() - { - await VerifyKeywordAsync( + public Task TestInUnsafeLocalFunction() + => VerifyKeywordAsync( """ public class C { @@ -191,12 +156,10 @@ unsafe void Local() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52296")] - public async Task TestNotInOrdinaryLocalFunction() - { - await VerifyAbsenceAsync( + public Task TestNotInOrdinaryLocalFunction() + => VerifyAbsenceAsync( """ public class C { @@ -209,5 +172,4 @@ void Local() } } """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/FloatKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/FloatKeywordRecommenderTests.cs index 1855b622ed448..d27393be69b31 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/FloatKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/FloatKeywordRecommenderTests.cs @@ -13,687 +13,532 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class FloatKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsing() - { - await VerifyAbsenceAsync( + public Task TestNotInUsing() + => VerifyAbsenceAsync( @"using $$"); - } [Fact] - public async Task TestInUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInUsingAlias() + => VerifyKeywordAsync( @"using Goo = $$"); - } [Fact] - public async Task TestInGlobalUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInGlobalUsingAlias() + => VerifyKeywordAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestAfterStackAlloc() - { - await VerifyKeywordAsync( + public Task TestAfterStackAlloc() + => VerifyKeywordAsync( """ class C { int* goo = stackalloc $$ """); - } [Fact] - public async Task TestInFixedStatement() - { - await VerifyKeywordAsync( + public Task TestInFixedStatement() + => VerifyKeywordAsync( @"fixed ($$"); - } [Fact] - public async Task TestInDelegateReturnType() - { - await VerifyKeywordAsync( + public Task TestInDelegateReturnType() + => VerifyKeywordAsync( @"public delegate $$"); - } [Fact] - public async Task TestInCastType() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); - } [Fact] - public async Task TestInCastType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType2() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); - } [Fact] - public async Task TestAfterConstInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterConstInMemberContext() + => VerifyKeywordAsync( """ class C { const $$ """); - } [Fact] - public async Task TestAfterRefInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefInMemberContext() + => VerifyKeywordAsync( """ class C { ref $$ """); - } [Fact] - public async Task TestAfterRefReadonlyInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyInMemberContext() + => VerifyKeywordAsync( """ class C { ref readonly $$ """); - } [Fact] - public async Task TestAfterConstInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"const $$")); - } [Fact] - public async Task TestAfterRefInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$")); - } [Fact] - public async Task TestAfterRefReadonlyInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); - } [Fact] - public async Task TestAfterConstLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); - } [Fact] - public async Task TestAfterRefReadonlyLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); - } [Fact] - public async Task TestAfterRefReadonlyLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); - } [Fact] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } [Fact] - public async Task TestInEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestNotInEnumBaseTypes() - { - await VerifyAbsenceAsync( + public Task TestNotInEnumBaseTypes() + => VerifyAbsenceAsync( @"enum E : $$"); - } [Fact] - public async Task TestInGenericType1() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType1() + => VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); - } [Fact] - public async Task TestInGenericType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType2() + => VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList,$$")); - } [Fact] - public async Task TestNotInBaseList() - { - await VerifyAbsenceAsync( + public Task TestNotInBaseList() + => VerifyAbsenceAsync( @"class C : $$"); - } [Fact] - public async Task TestInGenericType_InBaseList() - { - await VerifyKeywordAsync( + public Task TestInGenericType_InBaseList() + => VerifyKeywordAsync( @"class C : IList<$$"); - } [Fact] - public async Task TestAfterIs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); - } [Fact] - public async Task TestAfterAs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterAs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync( + public Task TestInsideInterface() + => VerifyKeywordAsync( """ interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact] - public async Task TestAfterNestedPartial() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPartial() + => VerifyKeywordAsync( """ class C { partial $$ """); - } [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] - public async Task TestAfterNestedStaticPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticPublic() + => VerifyKeywordAsync( """ class C { static public $$ """); - } [Fact] - public async Task TestAfterNestedPublicStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublicStatic() + => VerifyKeywordAsync( """ class C { public static $$ """); - } [Fact] - public async Task TestAfterVirtualPublic() - { - await VerifyKeywordAsync( + public Task TestAfterVirtualPublic() + => VerifyKeywordAsync( """ class C { virtual public $$ """); - } [Fact] - public async Task TestAfterNestedPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublic() + => VerifyKeywordAsync( """ class C { public $$ """); - } [Fact] - public async Task TestAfterNestedPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPrivate() + => VerifyKeywordAsync( """ class C { private $$ """); - } [Fact] - public async Task TestAfterNestedProtected() - { - await VerifyKeywordAsync( + public Task TestAfterNestedProtected() + => VerifyKeywordAsync( """ class C { protected $$ """); - } [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] - public async Task TestAfterNestedStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStatic() + => VerifyKeywordAsync( """ class C { static $$ """); - } [Fact] - public async Task TestAfterMethodOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterMethodOpenParen() + => VerifyKeywordAsync( """ class C { void Goo($$ """); - } [Fact] - public async Task TestAfterMethodComma() - { - await VerifyKeywordAsync( + public Task TestAfterMethodComma() + => VerifyKeywordAsync( """ class C { void Goo(int i, $$ """); - } [Fact] - public async Task TestAfterMethodAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterMethodAttribute() + => VerifyKeywordAsync( """ class C { void Goo(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterConstructorOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorOpenParen() + => VerifyKeywordAsync( """ class C { public C($$ """); - } [Fact] - public async Task TestAfterConstructorComma() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorComma() + => VerifyKeywordAsync( """ class C { public C(int i, $$ """); - } [Fact] - public async Task TestAfterConstructorAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorAttribute() + => VerifyKeywordAsync( """ class C { public C(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterDelegateOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateOpenParen() + => VerifyKeywordAsync( @"delegate void D($$"); - } [Fact] - public async Task TestAfterDelegateComma() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateComma() + => VerifyKeywordAsync( @"delegate void D(int i, $$"); - } [Fact] - public async Task TestAfterDelegateAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateAttribute() + => VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); - } [Fact] - public async Task TestAfterThis() - { - await VerifyKeywordAsync( + public Task TestAfterThis() + => VerifyKeywordAsync( """ static class C { public static void Goo(this $$ """); - } [Fact] - public async Task TestAfterRef() - { - await VerifyKeywordAsync( + public Task TestAfterRef() + => VerifyKeywordAsync( """ class C { void Goo(ref $$ """); - } [Fact] - public async Task TestAfterOut() - { - await VerifyKeywordAsync( + public Task TestAfterOut() + => VerifyKeywordAsync( """ class C { void Goo(out $$ """); - } [Fact] - public async Task TestAfterLambdaRef() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaRef() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (ref $$ """); - } [Fact] - public async Task TestAfterLambdaOut() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaOut() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (out $$ """); - } [Fact] - public async Task TestAfterParams() - { - await VerifyKeywordAsync( + public Task TestAfterParams() + => VerifyKeywordAsync( """ class C { void Goo(params $$ """); - } [Fact] - public async Task TestInImplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInImplicitOperator() + => VerifyKeywordAsync( """ class C { public static implicit operator $$ """); - } [Fact] - public async Task TestInExplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInExplicitOperator() + => VerifyKeywordAsync( """ class C { public static explicit operator $$ """); - } [Fact] - public async Task TestAfterIndexerBracket() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracket() + => VerifyKeywordAsync( """ class C { int this[$$ """); - } [Fact] - public async Task TestAfterIndexerBracketComma() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracketComma() + => VerifyKeywordAsync( """ class C { int this[int i, $$ """); - } [Fact] - public async Task TestAfterNewInExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterNewInExpression() + => VerifyKeywordAsync(AddInsideMethod( @"new $$")); - } [Fact] - public async Task TestAfterOut2() - { - await VerifyKeywordAsync( + public Task TestAfterOut2() + => VerifyKeywordAsync( """ class C { private static void RoundToFloat(double d, out $$ """); - } [Fact] - public async Task TestAfterOut3() - { - await VerifyKeywordAsync( + public Task TestAfterOut3() + => VerifyKeywordAsync( """ class C { private static void RoundToFloat(double d, out $$ float f) """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInTypeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInTypeOf() + => VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInDefault() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDefault() + => VerifyKeywordAsync(AddInsideMethod( @"default($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInSizeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInSizeOf() + => VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -701,12 +546,10 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] - public async Task TestInCrefContext() - { - await VerifyKeywordAsync(""" + public Task TestInCrefContext() + => VerifyKeywordAsync(""" class Program { /// @@ -716,16 +559,13 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] - public async Task TestInCrefContextNotAfterDot() - { - await VerifyAbsenceAsync(""" + public Task TestInCrefContextNotAfterDot() + => VerifyAbsenceAsync(""" /// class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] public async Task TestNotAfterAsync() @@ -736,19 +576,16 @@ public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1468")] - public async Task TestNotInCrefTypeParameter() - { - await VerifyAbsenceAsync(""" + public Task TestNotInCrefTypeParameter() + => VerifyAbsenceAsync(""" using System; /// class C { } """); - } [Fact] - public async Task Preselection() - { - await VerifyKeywordAsync(""" + public Task Preselection() + => VerifyKeywordAsync(""" class Program { static void Main(string[] args) @@ -758,23 +595,19 @@ static void Main(string[] args) static void Helper(float x) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinType() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinType() + => VerifyKeywordAsync(""" class Program { ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinMember() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinMember() + => VerifyKeywordAsync(""" class Program { void Method() @@ -783,82 +616,66 @@ void Method() } } """); - } [Fact] - public async Task TestInFunctionPointerType() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerType() + => VerifyKeywordAsync(""" class C { delegate*<$$ """); - } [Fact] - public async Task TestInFunctionPointerTypeAfterComma() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerTypeAfterComma() + => VerifyKeywordAsync(""" class C { delegate* VerifyKeywordAsync(""" class C { delegate* VerifyAbsenceAsync(""" class C { delegate*$$ """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/53585")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithoutAsync))] - public async Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) - { - await VerifyKeywordAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) + => VerifyKeywordAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithAsync))] - public async Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) - { - await VerifyAbsenceAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) + => VerifyAbsenceAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64585")] - public async Task TestAfterRequired() - { - await VerifyKeywordAsync(""" + public Task TestAfterRequired() + => VerifyKeywordAsync(""" class C { required $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefAtTopLevel1() + => VerifyKeywordAsync( @"ref $$"); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [CombinatorialData] @@ -879,98 +696,85 @@ await VerifyAbsenceAsync( } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefReadonlyAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyAtTopLevel1() + => VerifyKeywordAsync( @"ref readonly $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { readonly $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref readonly $$ } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref $$ -}}"); - } + public Task TestAfterRefInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - readonly $$ -}}"); - } + public Task TestAfterReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + readonly $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref readonly $$ -}}"); - } + public Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref readonly $$ + } + """); [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -980,5 +784,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ForEachKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ForEachKeywordRecommenderTests.cs index a3f3b7afb82b4..a46a463329eab 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ForEachKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ForEachKeywordRecommenderTests.cs @@ -12,209 +12,161 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ForEachKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAtRoot_TopLevelStatement() - { - await VerifyKeywordAsync( + public Task TestAtRoot_TopLevelStatement() + => VerifyKeywordAsync( @"$$", options: CSharp9ParseOptions); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterStatement_TopLevelStatement() - { - await VerifyKeywordAsync( + public Task TestAfterStatement_TopLevelStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """, options: CSharp9ParseOptions); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestAfterVariableDeclaration_TopLevelStatement() - { - await VerifyKeywordAsync( + public Task TestAfterVariableDeclaration_TopLevelStatement() + => VerifyKeywordAsync( """ int i = 0; $$ """, options: CSharp9ParseOptions); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Theory, CombinatorialData] - public async Task TestEmptyStatement(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestEmptyStatement(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterAwait(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterAwait(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"await $$", isAsync: true, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestBeforeStatement(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBeforeStatement(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ $$ return 0; """, returnType: "int", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterStatement(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterStatement(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ return true; $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterBlock(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBlock(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ if (true) { } $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInsideForEach(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideForEach(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ foreach (var v in c) $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInsideForEachInsideForEach(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideForEachInsideForEach(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ foreach (var v in c) foreach (var v in c) $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInsideForEachBlock(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideForEachBlock(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ foreach (var v in c) { $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestNotAfterForEach1(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterForEach1(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( @"foreach $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestNotAfterForEach2(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterForEach2(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( @"foreach ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestNotAfterForEach3(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterForEach3(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( @"foreach (var $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestNotAfterForEach4(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterForEach4(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( @"foreach (var v $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestNotAfterForEach5(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterForEach5(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( @"foreach (var v in $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestNotAfterForEach6(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterForEach6(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( @"foreach (var v in c $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestNotInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotInClass() + => VerifyAbsenceAsync(""" class C { $$ } """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ForKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ForKeywordRecommenderTests.cs index 0b9a150366684..da46257bbbd71 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ForKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ForKeywordRecommenderTests.cs @@ -12,161 +12,125 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ForKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestBeforeStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBeforeStatement() + => VerifyKeywordAsync(AddInsideMethod( """ $$ return true; """)); - } [Fact] - public async Task TestAfterStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterStatement() + => VerifyKeywordAsync(AddInsideMethod( """ return true; $$ """)); - } [Fact] - public async Task TestAfterBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBlock() + => VerifyKeywordAsync(AddInsideMethod( """ if (true) { } $$ """)); - } [Fact] - public async Task TestInsideFor() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideFor() + => VerifyKeywordAsync(AddInsideMethod( """ for (;;) $$ """)); - } [Fact] - public async Task TestInsideForInsideFor() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideForInsideFor() + => VerifyKeywordAsync(AddInsideMethod( """ for (;;) for (;;) $$ """)); - } [Fact] - public async Task TestInsideForBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideForBlock() + => VerifyKeywordAsync(AddInsideMethod( """ for (;;) { $$ """)); - } [Fact] - public async Task TestNotAfterFor1() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterFor1() + => VerifyAbsenceAsync(AddInsideMethod( @"for $$")); - } [Fact] - public async Task TestNotAfterFor2() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterFor2() + => VerifyAbsenceAsync(AddInsideMethod( @"for ($$")); - } [Fact] - public async Task TestNotAfterFor3() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterFor3() + => VerifyAbsenceAsync(AddInsideMethod( @"for (;$$")); - } [Fact] - public async Task TestNotAfterFor4() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterFor4() + => VerifyAbsenceAsync(AddInsideMethod( @"for (;;$$")); - } [Fact] - public async Task TestNotInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotInClass() + => VerifyAbsenceAsync(""" class C { $$ } """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/FromKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/FromKeywordRecommenderTests.cs index e0a6084e5a1ee..93e84552f0fd4 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/FromKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/FromKeywordRecommenderTests.cs @@ -13,226 +13,175 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class FromKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInEmptySpace() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptySpace() + => VerifyKeywordAsync(AddInsideMethod( @"var v = $$")); - } [Fact] - public async Task TestAfterIdentifier() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIdentifier() + => VerifyKeywordAsync(AddInsideMethod( @"var v = a$$")); - } [Fact] - public async Task TestNestedInQueryExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestNestedInQueryExpression() + => VerifyKeywordAsync(AddInsideMethod( @"var q = from x in $$")); - } [Fact] - public async Task TestAfterFrom() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterFrom() + => VerifyKeywordAsync(AddInsideMethod( """ var v = from x in y $$ """)); - } [Fact] - public async Task TestAfterPreviousClause() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterPreviousClause() + => VerifyKeywordAsync(AddInsideMethod( """ var v = from x in y where x > y $$ """)); - } [Fact] - public async Task TestAfterPreviousContinuationClause() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterPreviousContinuationClause() + => VerifyKeywordAsync(AddInsideMethod( """ var v = from x in y group x by y into g $$ """)); - } [Fact] - public async Task TestNotAfterFrom1() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterFrom1() + => VerifyAbsenceAsync(AddInsideMethod( @"var v = from $$")); - } [Fact] - public async Task TestNotAfterFrom2() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterFrom2() + => VerifyAbsenceAsync(AddInsideMethod( """ var v = from a in y from $$ """)); - } [Fact] - public async Task TestBetweenClauses() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBetweenClauses() + => VerifyKeywordAsync(AddInsideMethod( """ var v = from x in y $$ from z in w """)); - } [Fact] - public async Task TestContinueInSelect() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestContinueInSelect() + => VerifyKeywordAsync(AddInsideMethod( """ var v = from x in y select $$ """)); - } [Fact] - public async Task TestBetweenTokens() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBetweenTokens() + => VerifyKeywordAsync(AddInsideMethod( @"var v =$$;")); - } [Fact] - public async Task TestNotInDeclaration() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInDeclaration() + => VerifyAbsenceAsync(AddInsideMethod( @"int $$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] - public async Task TestNotInEnumMemberInitializer1() - { - await VerifyAbsenceAsync( + public Task TestNotInEnumMemberInitializer1() + => VerifyAbsenceAsync( """ enum E { a = $$ } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] - public async Task TestNotInConstMemberInitializer1() - { - await VerifyAbsenceAsync( + public Task TestNotInConstMemberInitializer1() + => VerifyAbsenceAsync( """ class E { const int a = $$ } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] - public async Task TestInMemberInitializer1() - { - await VerifyKeywordAsync( + public Task TestInMemberInitializer1() + => VerifyKeywordAsync( """ class E { int a = $$ } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInTypeOf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInTypeOf() + => VerifyAbsenceAsync(AddInsideMethod( @"typeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInDefault() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInDefault() + => VerifyAbsenceAsync(AddInsideMethod( @"default($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInSizeOf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInSizeOf() + => VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -240,7 +189,6 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact] public async Task TestNotAfterOutInArgument() @@ -260,118 +208,98 @@ void N() #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/GetKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/GetKeywordRecommenderTests.cs index 5311f80d07470..4a0ea36f13986 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/GetKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/GetKeywordRecommenderTests.cs @@ -12,380 +12,302 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class GetKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int Goo { $$ """); - } [Fact] - public async Task TestAfterPropertyPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterPropertyPrivate() + => VerifyKeywordAsync( """ class C { int Goo { private $$ """); - } [Fact] - public async Task TestAfterPropertyAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterPropertyAttribute() + => VerifyKeywordAsync( """ class C { int Goo { [Bar] $$ """); - } [Fact] - public async Task TestAfterPropertyAttributeAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterPropertyAttributeAndPrivate() + => VerifyKeywordAsync( """ class C { int Goo { [Bar] private $$ """); - } [Fact] - public async Task TestAfterPropertySet() - { - await VerifyKeywordAsync( + public Task TestAfterPropertySet() + => VerifyKeywordAsync( """ class C { int Goo { set; $$ """); - } [Fact] - public async Task TestAfterPropertySetAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterPropertySetAndPrivate() + => VerifyKeywordAsync( """ class C { int Goo { set; private $$ """); - } [Fact] - public async Task TestAfterPropertySetAndAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterPropertySetAndAttribute() + => VerifyKeywordAsync( """ class C { int Goo { set; [Bar] $$ """); - } [Fact] - public async Task TestAfterPropertySetAndAttributeAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterPropertySetAndAttributeAndPrivate() + => VerifyKeywordAsync( """ class C { int Goo { set; [Bar] private $$ """); - } [Fact] - public async Task TestAfterSetAccessorBlock() - { - await VerifyKeywordAsync( + public Task TestAfterSetAccessorBlock() + => VerifyKeywordAsync( """ class C { int Goo { set { } $$ """); - } [Fact] - public async Task TestAfterSetAccessorBlockAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterSetAccessorBlockAndPrivate() + => VerifyKeywordAsync( """ class C { int Goo { set { } private $$ """); - } [Fact] - public async Task TestAfterSetAccessorBlockAndAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterSetAccessorBlockAndAttribute() + => VerifyKeywordAsync( """ class C { int Goo { set { } [Bar] $$ """); - } [Fact] - public async Task TestAfterSetAccessorBlockAndAttributeAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterSetAccessorBlockAndAttributeAndPrivate() + => VerifyKeywordAsync( """ class C { int Goo { set { } [Bar] private $$ """); - } [Fact] - public async Task TestNotAfterPropertyGetKeyword() - { - await VerifyAbsenceAsync( + public Task TestNotAfterPropertyGetKeyword() + => VerifyAbsenceAsync( """ class C { int Goo { get $$ """); - } [Fact] - public async Task TestNotAfterPropertyGetAccessor() - { - await VerifyAbsenceAsync( + public Task TestNotAfterPropertyGetAccessor() + => VerifyAbsenceAsync( """ class C { int Goo { get; $$ """); - } [Fact] - public async Task TestNotInEvent() - { - await VerifyAbsenceAsync( + public Task TestNotInEvent() + => VerifyAbsenceAsync( """ class C { event Goo E { $$ """); - } [Fact] - public async Task TestAfterIndexer() - { - await VerifyKeywordAsync( + public Task TestAfterIndexer() + => VerifyKeywordAsync( """ class C { int this[int i] { $$ """); - } [Fact] - public async Task TestAfterIndexerPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerPrivate() + => VerifyKeywordAsync( """ class C { int this[int i] { private $$ """); - } [Fact] - public async Task TestAfterIndexerAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerAttribute() + => VerifyKeywordAsync( """ class C { int this[int i] { [Bar] $$ """); - } [Fact] - public async Task TestAfterIndexerAttributeAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerAttributeAndPrivate() + => VerifyKeywordAsync( """ class C { int this[int i] { [Bar] private $$ """); - } [Fact] - public async Task TestAfterIndexerSet() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerSet() + => VerifyKeywordAsync( """ class C { int this[int i] { set; $$ """); - } [Fact] - public async Task TestAfterIndexerSetAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerSetAndPrivate() + => VerifyKeywordAsync( """ class C { int this[int i] { set; private $$ """); - } [Fact] - public async Task TestAfterIndexerSetAndAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerSetAndAttribute() + => VerifyKeywordAsync( """ class C { int this[int i] { set; [Bar] $$ """); - } [Fact] - public async Task TestAfterIndexerSetAndAttributeAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerSetAndAttributeAndPrivate() + => VerifyKeywordAsync( """ class C { int this[int i] { set; [Bar] private $$ """); - } [Fact] - public async Task TestAfterIndexerSetBlock() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerSetBlock() + => VerifyKeywordAsync( """ class C { int this[int i] { set { } $$ """); - } [Fact] - public async Task TestAfterIndexerSetBlockAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerSetBlockAndPrivate() + => VerifyKeywordAsync( """ class C { int this[int i] { set { } private $$ """); - } [Fact] - public async Task TestAfterIndexerSetBlockAndAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerSetBlockAndAttribute() + => VerifyKeywordAsync( """ class C { int this[int i] { set { } [Bar] $$ """); - } [Fact] - public async Task TestAfterIndexerSetBlockAndAttributeAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerSetBlockAndAttributeAndPrivate() + => VerifyKeywordAsync( """ class C { int this[int i] { set { } [Bar] private $$ """); - } [Fact] - public async Task TestNotAfterIndexerGetKeyword() - { - await VerifyAbsenceAsync( + public Task TestNotAfterIndexerGetKeyword() + => VerifyAbsenceAsync( """ class C { int this[int i] { get $$ """); - } [Fact] - public async Task TestNotAfterIndexerGetAccessor() - { - await VerifyAbsenceAsync( + public Task TestNotAfterIndexerGetAccessor() + => VerifyAbsenceAsync( """ class C { int this[int i] { get; $$ """); - } [Fact] - public async Task TestBeforeSemicolon() - { - await VerifyKeywordAsync( + public Task TestBeforeSemicolon() + => VerifyKeywordAsync( """ class C { int this[int i] { $$; } """); - } [Fact] - public async Task TestAfterProtectedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterProtectedInternal() + => VerifyKeywordAsync( """ class C { int this[int i] { protected internal $$ } """); - } [Fact] - public async Task TestAfterInternalProtected() - { - await VerifyKeywordAsync( + public Task TestAfterInternalProtected() + => VerifyKeywordAsync( """ class C { int this[int i] { internal protected $$ } """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/GlobalKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/GlobalKeywordRecommenderTests.cs index bcdb71ed9dcd7..abec65ecf113c 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/GlobalKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/GlobalKeywordRecommenderTests.cs @@ -17,9 +17,8 @@ public async Task TestInMethodBody() => await VerifyKeywordAsync(AddInsideMethod(@"$$")); [Fact] - public async Task TestInClassDeclaration() - { - await VerifyKeywordAsync(""" + public Task TestInClassDeclaration() + => VerifyKeywordAsync(""" namespace goo { class bar @@ -27,16 +26,14 @@ class bar $$ } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543628")] public async Task TestNotInEnumDeclaration() => await VerifyAbsenceAsync(@"enum Goo { $$ }"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -44,358 +41,281 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact] - public async Task TestAfterConstInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterConstInMemberContext() + => VerifyKeywordAsync( """ class C { const $$ """); - } [Fact] - public async Task TestAfterRefInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefInMemberContext() + => VerifyKeywordAsync( """ class C { ref $$ """); - } [Fact] - public async Task TestAfterRefReadonlyInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyInMemberContext() + => VerifyKeywordAsync( """ class C { ref readonly $$ """); - } [Fact] - public async Task TestAfterConstInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"const $$")); - } [Fact] - public async Task TestAfterRefInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$")); - } [Fact] - public async Task TestAfterRefReadonlyInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); - } [Fact] - public async Task TestAfterConstLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); - } [Fact] - public async Task TestAfterRefReadonlyLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); - } [Fact] - public async Task TestAfterRefReadonlyLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); - } [Fact] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } [Fact] - public async Task TestInFunctionPointerType() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerType() + => VerifyKeywordAsync(""" class C { delegate*<$$ """); - } [Fact] - public async Task TestInFunctionPointerTypeAfterComma() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerTypeAfterComma() + => VerifyKeywordAsync(""" class C { delegate* VerifyKeywordAsync(""" class C { delegate* VerifyAbsenceAsync(""" class C { delegate*$$ """); - } [Fact] - public async Task TestInCompilationUnit() - { - await VerifyKeywordAsync(""" + public Task TestInCompilationUnit() + => VerifyKeywordAsync(""" $$ """); - } [Fact] - public async Task TestAfterExtern() - { - await VerifyKeywordAsync( + public Task TestAfterExtern() + => VerifyKeywordAsync( """ extern alias goo; $$ """); - } [Fact] - public async Task TestAfterPreviousUsing() - { - await VerifyKeywordAsync( + public Task TestAfterPreviousUsing() + => VerifyKeywordAsync( """ using Goo; $$ """); - } [Fact] - public async Task TestAfterPreviousGlobalUsing() - { - await VerifyKeywordAsync( + public Task TestAfterPreviousGlobalUsing() + => VerifyKeywordAsync( """ global using Goo; $$ """); - } [Fact] - public async Task TestBeforeUsing() - { - await VerifyKeywordAsync( + public Task TestBeforeUsing() + => VerifyKeywordAsync( """ $$ using Goo; """); - } [Fact] - public async Task TestBeforeGlobalUsing() - { - await VerifyKeywordAsync( + public Task TestBeforeGlobalUsing() + => VerifyKeywordAsync( """ $$ global using Goo; """); - } [Fact] - public async Task TestAfterUsingAlias() - { - await VerifyKeywordAsync( + public Task TestAfterUsingAlias() + => VerifyKeywordAsync( """ using Goo = Bar; $$ """); - } [Fact] - public async Task TestAfterGlobalUsingAlias() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalUsingAlias() + => VerifyKeywordAsync( """ using Goo = Bar; $$ """); - } [Fact] - public async Task TestNotAfterGlobalKeyword() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterGlobalKeyword() + => VerifyAbsenceAsync(""" global $$ """); - } [Fact] - public async Task TestNotAfterUsingKeyword() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterUsingKeyword() + => VerifyAbsenceAsync(""" using $$ """); - } [Fact] - public async Task TestNotAfterGlobalUsingKeyword() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterGlobalUsingKeyword() + => VerifyAbsenceAsync(""" global using $$ """); - } [Fact] - public async Task TestNotBeforeExtern() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeExtern() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ extern alias Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeExtern_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeExtern_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ extern alias Goo; """); - } [Fact] - public async Task TestBetweenGlobalUsings_01() - { - await VerifyKeywordAsync( + public Task TestBetweenGlobalUsings_01() + => VerifyKeywordAsync( """ global using Goo; $$ global using Bar; """); - } [Fact] - public async Task TestBetweenUsings_02() - { - await VerifyKeywordAsync( + public Task TestBetweenUsings_02() + => VerifyKeywordAsync( """ global using Goo; $$ using Bar; """); - } [Fact] - public async Task TestNotAfterGlobalBetweenGlobalUsings_01() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGlobalBetweenGlobalUsings_01() + => VerifyAbsenceAsync( """ global using Goo; global $$ global using Bar; """); - } [Fact] - public async Task TestNotAfterGlobalBetweenUsings_02() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGlobalBetweenUsings_02() + => VerifyAbsenceAsync( """ global using Goo; global $$ using Bar; """); - } [Fact] - public async Task TestBeforeNamespace() - { - await VerifyKeywordAsync( + public Task TestBeforeNamespace() + => VerifyKeywordAsync( """ $$ namespace NS {} """); - } [Fact] - public async Task TestBeforeClass() - { - await VerifyKeywordAsync( + public Task TestBeforeClass() + => VerifyKeywordAsync( """ $$ class C1 {} """); - } [Fact] - public async Task TestBeforeStatement() - { - await VerifyKeywordAsync( + public Task TestBeforeStatement() + => VerifyKeywordAsync( """ $$ Call(); """); - } [Fact] - public async Task TestBeforeAttribute_01() - { - await VerifyKeywordAsync( + public Task TestBeforeAttribute_01() + => VerifyKeywordAsync( """ $$ [Call()] """); - } [Fact] - public async Task TestBeforeAttribute_02() - { - await VerifyKeywordAsync( + public Task TestBeforeAttribute_02() + => VerifyKeywordAsync( """ $$ [assembly: Call()] """); - } [Fact] public async Task TestAfterScoped() @@ -405,133 +325,110 @@ public async Task TestAfterScoped() } [Fact] - public async Task TestInEnumBaseList() - { - await VerifyKeywordAsync("enum E : $$"); - } + public Task TestInEnumBaseList() + => VerifyKeywordAsync("enum E : $$"); #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -541,5 +438,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/GotoKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/GotoKeywordRecommenderTests.cs index ab29a694f3685..5e3b772436855 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/GotoKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/GotoKeywordRecommenderTests.cs @@ -12,117 +12,92 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class GotoKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestBeforeStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBeforeStatement() + => VerifyKeywordAsync(AddInsideMethod( """ $$ return true; """)); - } [Fact] - public async Task TestAfterStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterStatement() + => VerifyKeywordAsync(AddInsideMethod( """ return true; $$ """)); - } [Fact] - public async Task TestAfterBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBlock() + => VerifyKeywordAsync(AddInsideMethod( """ if (true) { } $$ """)); - } [Fact] - public async Task TestNotAfterGoto() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterGoto() + => VerifyAbsenceAsync(AddInsideMethod( @"goto $$")); - } [Fact] - public async Task TestNotInClass() - { - await VerifyAbsenceAsync( + public Task TestNotInClass() + => VerifyAbsenceAsync( """ class C { $$ } """); - } [Fact] - public async Task TestAfterAssignment() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterAssignment() + => VerifyKeywordAsync(AddInsideMethod( """ if (b != 0) { count <<= 2; @@ -133,5 +108,4 @@ await VerifyKeywordAsync(AddInsideMethod( $$ Restart; } """)); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/GroupKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/GroupKeywordRecommenderTests.cs index 4b2d7c00d44da..f7c1acf1695a8 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/GroupKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/GroupKeywordRecommenderTests.cs @@ -12,122 +12,94 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class GroupKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestNotAtEndOfPreviousClause() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAtEndOfPreviousClause() + => VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y$$")); - } [Fact] - public async Task TestNewClause() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestNewClause() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y $$ """)); - } [Fact] - public async Task TestAfterPreviousClause() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterPreviousClause() + => VerifyKeywordAsync(AddInsideMethod( """ var v = from x in y where x > y $$ """)); - } [Fact] - public async Task TestAfterPreviousContinuationClause() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterPreviousContinuationClause() + => VerifyKeywordAsync(AddInsideMethod( """ var v = from x in y group x by y into g $$ """)); - } [Fact] - public async Task TestBetweenClauses() - { - // Technically going to generate invalid code, but we - // shouldn't stop users from doing this. - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBetweenClauses() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y $$ from z in w """)); - } [Fact] - public async Task TestNotAfterGroup() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterGroup() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y group $$ """)); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/HiddenKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/HiddenKeywordRecommenderTests.cs index bdc2e07582023..48fdc15f9eb45 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/HiddenKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/HiddenKeywordRecommenderTests.cs @@ -12,74 +12,56 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class HiddenKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterHash() - { - await VerifyKeywordAsync( + public Task TestAfterHash() + => VerifyKeywordAsync( @"#line $$"); - } [Fact] - public async Task TestAfterHashAndSpace() - { - await VerifyKeywordAsync( + public Task TestAfterHashAndSpace() + => VerifyKeywordAsync( @"# line $$"); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/IfKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/IfKeywordRecommenderTests.cs index 2c5e4ac5245a2..02f4e0716d2d9 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/IfKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/IfKeywordRecommenderTests.cs @@ -12,155 +12,120 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class IfKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInPreprocessor1() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInPreprocessor1() + => VerifyAbsenceAsync(AddInsideMethod( "#if $$")); - } [Fact] - public async Task TestEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterHash() - { - await VerifyKeywordAsync( + public Task TestAfterHash() + => VerifyKeywordAsync( @"#$$"); - } [Fact] - public async Task TestAfterHashFollowedBySkippedTokens() - { - await VerifyKeywordAsync( + public Task TestAfterHashFollowedBySkippedTokens() + => VerifyKeywordAsync( """ #$$ aeu """); - } [Fact] - public async Task TestAfterHashAndSpace() - { - await VerifyKeywordAsync( + public Task TestAfterHashAndSpace() + => VerifyKeywordAsync( @"# $$"); - } [Fact] - public async Task TestInsideMethod() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideMethod() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestBeforeStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBeforeStatement() + => VerifyKeywordAsync(AddInsideMethod( """ $$ return true; """)); - } [Fact] - public async Task TestAfterStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterStatement() + => VerifyKeywordAsync(AddInsideMethod( """ return true; $$ """)); - } [Fact] - public async Task TestAfterBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBlock() + => VerifyKeywordAsync(AddInsideMethod( """ if (true) { } $$ """)); - } [Fact] - public async Task TestNotAfterIf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterIf() + => VerifyAbsenceAsync(AddInsideMethod( @"if $$")); - } [Fact] - public async Task TestInCase() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCase() + => VerifyKeywordAsync(AddInsideMethod( """ switch (true) { case 0: $$ } """)); - } [Fact] - public async Task TestInCaseBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCaseBlock() + => VerifyKeywordAsync(AddInsideMethod( """ switch (true) { case 0: { @@ -168,24 +133,20 @@ await VerifyKeywordAsync(AddInsideMethod( } } """)); - } [Fact] - public async Task TestInDefaultCase() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDefaultCase() + => VerifyKeywordAsync(AddInsideMethod( """ switch (true) { default: $$ } """)); - } [Fact] - public async Task TestInDefaultCaseBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDefaultCaseBlock() + => VerifyKeywordAsync(AddInsideMethod( """ switch (true) { default: { @@ -193,92 +154,71 @@ await VerifyKeywordAsync(AddInsideMethod( } } """)); - } [Fact] - public async Task TestAfterLabel() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterLabel() + => VerifyKeywordAsync(AddInsideMethod( """ label: $$ """)); - } [Fact] - public async Task TestNotAfterDoBlock() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterDoBlock() + => VerifyAbsenceAsync(AddInsideMethod( """ do { } $$ """)); - } [Fact] - public async Task TestInActiveRegion1() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInActiveRegion1() + => VerifyKeywordAsync(AddInsideMethod( """ #if true $$ """)); - } [Fact] - public async Task TestInActiveRegion2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInActiveRegion2() + => VerifyKeywordAsync(AddInsideMethod( """ #if true $$ """)); - } [Fact] - public async Task TestAfterElse() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterElse() + => VerifyKeywordAsync(AddInsideMethod( """ if (goo) { } else $$ """)); - } [Fact] - public async Task TestAfterCatch() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestAfterCatch() + => VerifyAbsenceAsync(AddInsideMethod( @"try {} catch $$")); - } [Fact] - public async Task TestAfterCatchDeclaration1() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestAfterCatchDeclaration1() + => VerifyAbsenceAsync(AddInsideMethod( @"try {} catch (Exception) $$")); - } [Fact] - public async Task TestAfterCatchDeclaration2() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestAfterCatchDeclaration2() + => VerifyAbsenceAsync(AddInsideMethod( @"try {} catch (Exception e) $$")); - } [Fact] - public async Task TestAfterCatchDeclarationEmpty() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestAfterCatchDeclarationEmpty() + => VerifyAbsenceAsync(AddInsideMethod( @"try {} catch () $$")); - } [Fact] - public async Task TestNotAfterTryBlock() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterTryBlock() + => VerifyAbsenceAsync(AddInsideMethod( @"try {} $$")); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ImplicitKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ImplicitKeywordRecommenderTests.cs index df37d0400c3a8..3877ac05eef90 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ImplicitKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ImplicitKeywordRecommenderTests.cs @@ -13,252 +13,200 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ImplicitKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] public async Task TestNotInCompilationUnit() => await VerifyAbsenceAsync(@"$$"); [Fact] - public async Task TestNotAfterExtern() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterExtern() + => VerifyAbsenceAsync(""" extern alias Goo; $$ """); - } [Fact] - public async Task TestNotAfterUsing() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterUsing() + => VerifyAbsenceAsync(""" using Goo; $$ """); - } [Fact] - public async Task TestNotAfterGlobalUsing() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterGlobalUsing() + => VerifyAbsenceAsync(""" global using Goo; $$ """); - } [Fact] - public async Task TestNotAfterNamespace() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNamespace() + => VerifyAbsenceAsync(""" namespace N {} $$ """); - } [Fact] - public async Task TestNotAfterTypeDeclaration() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterTypeDeclaration() + => VerifyAbsenceAsync(""" class C {} $$ """); - } [Fact] - public async Task TestNotAfterDelegateDeclaration() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterDelegateDeclaration() + => VerifyAbsenceAsync(""" delegate void Goo(); $$ """); - } [Fact] - public async Task TestNotAfterMethod() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterMethod() + => VerifyAbsenceAsync(""" class C { void Goo() {} $$ """); - } [Fact] - public async Task TestNotAfterMethodInPartialType() - { - await VerifyAbsenceAsync( + public Task TestNotAfterMethodInPartialType() + => VerifyAbsenceAsync( """ partial class C { void Goo() {} $$ """); - } [Fact] - public async Task TestNotAfterFieldInPartialClass() - { - await VerifyAbsenceAsync( + public Task TestNotAfterFieldInPartialClass() + => VerifyAbsenceAsync( """ partial class C { int i; $$ """); - } [Fact] - public async Task TestNotAfterPropertyInPartialClass() - { - await VerifyAbsenceAsync( + public Task TestNotAfterPropertyInPartialClass() + => VerifyAbsenceAsync( """ partial class C { int i { get; } $$ """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync( + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync( """ $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync( + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync( """ $$ global using Goo; """); - } [Fact] - public async Task TestNotAfterAssemblyAttribute() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterAssemblyAttribute() + => VerifyAbsenceAsync(""" [assembly: goo] $$ """); - } [Fact] - public async Task TestNotAfterRootAttribute() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterRootAttribute() + => VerifyAbsenceAsync(""" [goo] $$ """); - } [Fact] - public async Task TestNotAfterNestedAttributeInPartialClass() - { - await VerifyAbsenceAsync( + public Task TestNotAfterNestedAttributeInPartialClass() + => VerifyAbsenceAsync( """ partial class C { [goo] $$ """); - } // This will be fixed once we have accessibility for members [Fact] - public async Task TestNotInsideStruct() - { - await VerifyAbsenceAsync(""" + public Task TestNotInsideStruct() + => VerifyAbsenceAsync(""" struct S { $$ """); - } // This will be fixed once we have accessibility for members [Fact] - public async Task TestNotInsidePartialStruct() - { - await VerifyAbsenceAsync( + public Task TestNotInsidePartialStruct() + => VerifyAbsenceAsync( """ partial struct S { $$ """); - } [Fact] - public async Task TestNotInsideInterface() - { - await VerifyAbsenceAsync(""" + public Task TestNotInsideInterface() + => VerifyAbsenceAsync(""" interface I { $$ """); - } [Fact] - public async Task TestNotInsidePartialClass() - { - await VerifyAbsenceAsync( + public Task TestNotInsidePartialClass() + => VerifyAbsenceAsync( """ partial class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() @@ -281,138 +229,112 @@ public async Task TestNotAfterStaticPublic() => await VerifyAbsenceAsync(@"static public $$"); [Fact] - public async Task TestAfterNestedStaticPublicInClass() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticPublicInClass() + => VerifyKeywordAsync( """ class C { static public $$ """); - } [Fact] - public async Task TestNotAfterNestedStaticPublicInInterface() - { - await VerifyAbsenceAsync( + public Task TestNotAfterNestedStaticPublicInInterface() + => VerifyAbsenceAsync( """ interface C { static public $$ """); - } [Fact] - public async Task TestNotAfterNestedAbstractPublicInInterface() - { - await VerifyAbsenceAsync( + public Task TestNotAfterNestedAbstractPublicInInterface() + => VerifyAbsenceAsync( """ interface C { abstract public $$ """); - } [Fact] - public async Task TestAfterNestedStaticAbstractPublicInInterface() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticAbstractPublicInInterface() + => VerifyKeywordAsync( """ interface C { static abstract public $$ """); - } [Fact] - public async Task TestAfterNestedAbstractStaticPublicInInterface() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstractStaticPublicInInterface() + => VerifyKeywordAsync( """ interface C { abstract static public $$ """); - } [Fact] - public async Task TestAfterNestedStaticAbstractInInterface() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticAbstractInInterface() + => VerifyKeywordAsync( """ interface C { static abstract $$ """); - } [Fact] - public async Task TestAfterNestedAbstractStaticInInterface() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstractStaticInInterface() + => VerifyKeywordAsync( """ interface C { abstract static $$ """); - } [Fact] - public async Task TestNotAfterNestedStaticInInterface() - { - await VerifyAbsenceAsync( + public Task TestNotAfterNestedStaticInInterface() + => VerifyAbsenceAsync( """ interface C { static $$ """); - } [Fact] public async Task TestNotAfterPublicStatic() => await VerifyAbsenceAsync(@"public static $$"); [Fact] - public async Task TestAfterNestedPublicStaticInClass() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublicStaticInClass() + => VerifyKeywordAsync( """ class C { public static $$ """); - } [Fact] - public async Task TestNotAfterNestedPublicStaticInInterface() - { - await VerifyAbsenceAsync( + public Task TestNotAfterNestedPublicStaticInInterface() + => VerifyAbsenceAsync( """ interface C { public static $$ """); - } [Fact] - public async Task TestNotAfterNestedPublicAbstractInInterface() - { - await VerifyAbsenceAsync( + public Task TestNotAfterNestedPublicAbstractInInterface() + => VerifyAbsenceAsync( """ interface C { public abstract $$ """); - } [Fact] - public async Task TestAfterNestedPublicStaticAbstractInInterface() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublicStaticAbstractInInterface() + => VerifyKeywordAsync( """ interface C { public static abstract $$ """); - } [Fact] - public async Task TestAfterNestedPublicAbstractStaticInInterface() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublicAbstractStaticInInterface() + => VerifyKeywordAsync( """ interface C { public abstract static $$ """); - } [Fact] public async Task TestNotAfterInvalidPublic() @@ -443,152 +365,120 @@ public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact] - public async Task TestNotBetweenUsings() - { - await VerifyAbsenceAsync( + public Task TestNotBetweenUsings() + => VerifyAbsenceAsync( """ using Goo; $$ using Bar; """); - } [Fact] - public async Task TestNotBetweenGlobalUsings_01() - { - await VerifyAbsenceAsync( + public Task TestNotBetweenGlobalUsings_01() + => VerifyAbsenceAsync( """ global using Goo; $$ using Bar; """); - } [Fact] - public async Task TestNotBetweenGlobalUsings_02() - { - await VerifyAbsenceAsync( + public Task TestNotBetweenGlobalUsings_02() + => VerifyAbsenceAsync( """ global using Goo; $$ global using Bar; """); - } [Fact] - public async Task TestNotAfterNestedAbstractInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedAbstractInClass() + => VerifyAbsenceAsync(""" class C { abstract $$ """); - } [Fact] - public async Task TestNotAfterNestedVirtualInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedVirtualInClass() + => VerifyAbsenceAsync(""" class C { virtual $$ """); - } [Fact] - public async Task TestNotAfterNestedOverrideInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedOverrideInClass() + => VerifyAbsenceAsync(""" class C { override $$ """); - } [Fact] - public async Task TestNotAfterNestedSealedInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedSealedInClass() + => VerifyAbsenceAsync(""" class C { sealed $$ """); - } [Fact] - public async Task TestNotAfterNestedReadOnlyInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedReadOnlyInClass() + => VerifyAbsenceAsync(""" class C { readonly $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544103")] - public async Task TestAfterNestedUnsafeStaticPublicInClass() - { - await VerifyKeywordAsync(""" + public Task TestAfterNestedUnsafeStaticPublicInClass() + => VerifyKeywordAsync(""" class C { unsafe static public $$ """); - } [Fact] - public async Task TestNotAfterNestedAbstractInInterface() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedAbstractInInterface() + => VerifyAbsenceAsync(""" interface C { abstract $$ """); - } [Fact] - public async Task TestNotAfterNestedVirtualInInterface() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedVirtualInInterface() + => VerifyAbsenceAsync(""" interface C { virtual $$ """); - } [Fact] - public async Task TestNotAfterNestedOverrideInInterface() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedOverrideInInterface() + => VerifyAbsenceAsync(""" interface C { override $$ """); - } [Fact] - public async Task TestNotAfterNestedSealedInInterface() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedSealedInInterface() + => VerifyAbsenceAsync(""" interface C { sealed $$ """); - } [Fact] - public async Task TestNotAfterNestedReadOnlyInInterface() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedReadOnlyInInterface() + => VerifyAbsenceAsync(""" interface C { readonly $$ """); - } [Fact] - public async Task TestAfterUnsafeStaticAbstractInInterface() - { - await VerifyKeywordAsync(""" + public Task TestAfterUnsafeStaticAbstractInInterface() + => VerifyKeywordAsync(""" interface C { unsafe static abstract $$ """); - } [Fact] - public async Task TestNotAfterExternStaticAbstractInInterface() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterExternStaticAbstractInInterface() + => VerifyAbsenceAsync(""" interface C { extern static abstract $$ """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/InKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/InKeywordRecommenderTests.cs index ed79195d830ea..1f6affbc425aa 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/InKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/InKeywordRecommenderTests.cs @@ -13,128 +13,99 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class InKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestNotAfterFrom() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterFrom() + => VerifyAbsenceAsync(AddInsideMethod( @"var q = from $$")); - } [Fact] - public async Task TestAfterFromIdentifier() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterFromIdentifier() + => VerifyKeywordAsync(AddInsideMethod( @"var q = from x $$")); - } [Fact] - public async Task TestAfterFromAndTypeAndIdentifier() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterFromAndTypeAndIdentifier() + => VerifyKeywordAsync(AddInsideMethod( @"var q = from int x $$")); - } [Fact] - public async Task TestNotAfterJoin() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterJoin() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y join $$ """)); - } [Fact] - public async Task TestAfterJoinIdentifier() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterJoinIdentifier() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y join z $$ """)); - } [Fact] - public async Task TestAfterJoinAndTypeAndIdentifier() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterJoinAndTypeAndIdentifier() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y join int z $$ """)); - } [Fact] - public async Task TestAfterJoinNotAfterIn() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestAfterJoinNotAfterIn() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y join z in $$ """)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544158")] - public async Task TestNotAfterJoinPredefinedType() - { - await VerifyAbsenceAsync( + public Task TestNotAfterJoinPredefinedType() + => VerifyAbsenceAsync( """ using System; using System.Linq; @@ -144,12 +115,10 @@ void M() var q = from x in y join int $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544158")] - public async Task TestNotAfterJoinType() - { - await VerifyAbsenceAsync( + public Task TestNotAfterJoinType() + => VerifyAbsenceAsync( """ using System; using System.Linq; @@ -159,155 +128,113 @@ void M() var q = from x in y join Int32 $$ """); - } [Fact] - public async Task TestInForEach() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForEach() + => VerifyKeywordAsync(AddInsideMethod( @"foreach (var v $$")); - } [Fact] - public async Task TestInForEach1() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForEach1() + => VerifyKeywordAsync(AddInsideMethod( @"foreach (var v $$ c")); - } [Fact] - public async Task TestInForEach2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForEach2() + => VerifyKeywordAsync(AddInsideMethod( @"foreach (var v $$ c")); - } [Fact] - public async Task TestNotInForEach() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInForEach() + => VerifyAbsenceAsync(AddInsideMethod( @"foreach ($$")); - } [Fact] - public async Task TestNotInForEach1() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInForEach1() + => VerifyAbsenceAsync(AddInsideMethod( @"foreach (var $$")); - } [Fact] - public async Task TestNotInForEach2() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInForEach2() + => VerifyAbsenceAsync(AddInsideMethod( @"foreach (var v in $$")); - } [Fact] - public async Task TestNotInForEach3() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInForEach3() + => VerifyAbsenceAsync(AddInsideMethod( @"foreach (var v in c $$")); - } [Fact] - public async Task TestInterfaceTypeVarianceAfterAngle() - { - await VerifyKeywordAsync( + public Task TestInterfaceTypeVarianceAfterAngle() + => VerifyKeywordAsync( @"interface IGoo<$$"); - } [Fact] - public async Task TestInterfaceTypeVarianceNotAfterIn() - { - await VerifyAbsenceAsync( + public Task TestInterfaceTypeVarianceNotAfterIn() + => VerifyAbsenceAsync( @"interface IGoo VerifyKeywordAsync( @"interface IGoo VerifyKeywordAsync( @"interface IGoo<[Goo]$$"); - } [Fact] - public async Task TestDelegateTypeVarianceAfterAngle() - { - await VerifyKeywordAsync( + public Task TestDelegateTypeVarianceAfterAngle() + => VerifyKeywordAsync( @"delegate void D<$$"); - } [Fact] - public async Task TestDelegateTypeVarianceAfterComma() - { - await VerifyKeywordAsync( + public Task TestDelegateTypeVarianceAfterComma() + => VerifyKeywordAsync( @"delegate void D VerifyKeywordAsync( @"delegate void D<[Goo]$$"); - } [Fact] - public async Task TestNotInClassTypeVarianceAfterAngle() - { - await VerifyAbsenceAsync( + public Task TestNotInClassTypeVarianceAfterAngle() + => VerifyAbsenceAsync( @"class IGoo<$$"); - } [Fact] - public async Task TestNotInStructTypeVarianceAfterAngle() - { - await VerifyAbsenceAsync( + public Task TestNotInStructTypeVarianceAfterAngle() + => VerifyAbsenceAsync( @"struct IGoo<$$"); - } [Fact] - public async Task TestNotInBaseListAfterAngle() - { - await VerifyAbsenceAsync( + public Task TestNotInBaseListAfterAngle() + => VerifyAbsenceAsync( @"interface IGoo : Bar<$$"); - } [Fact] - public async Task TestNotInGenericMethod() - { - await VerifyAbsenceAsync( + public Task TestNotInGenericMethod() + => VerifyAbsenceAsync( """ interface IGoo { void Goo<$$ """); - } [Fact] - public async Task TestFrom2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestFrom2() + => VerifyKeywordAsync(AddInsideMethod( @"var q2 = from int x $$ ((IEnumerable)src))")); - } [Fact] - public async Task TestFrom3() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestFrom3() + => VerifyKeywordAsync(AddInsideMethod( @"var q2 = from x $$ ((IEnumerable)src))")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544158")] - public async Task TestNotAfterFromPredefinedType() - { - await VerifyAbsenceAsync( + public Task TestNotAfterFromPredefinedType() + => VerifyAbsenceAsync( """ using System; using System.Linq; @@ -316,12 +243,10 @@ void M() { var q = from int $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544158")] - public async Task TestNotAfterFromType() - { - await VerifyAbsenceAsync( + public Task TestNotAfterFromType() + => VerifyAbsenceAsync( """ using System; using System.Linq; @@ -330,47 +255,39 @@ void M() { var q = from Int32 $$ """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInAsParameterModifierInMethods() - { - await VerifyKeywordAsync(""" + public Task TestInAsParameterModifierInMethods() + => VerifyKeywordAsync(""" class Program { public static void Test($$ p) { } } """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInAsParameterModifierInSecondParameter() - { - await VerifyKeywordAsync(""" + public Task TestInAsParameterModifierInSecondParameter() + => VerifyKeywordAsync(""" class Program { public static void Test(int p1, $$ p2) { } } """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInAsParameterModifierInDelegates() - { - await VerifyKeywordAsync(""" + public Task TestInAsParameterModifierInDelegates() + => VerifyKeywordAsync(""" public delegate int Delegate($$ int p); """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInAsParameterModifierInLocalFunctions() - { - await VerifyKeywordAsync(""" + public Task TestInAsParameterModifierInLocalFunctions() + => VerifyKeywordAsync(""" class Program { public static void Test() @@ -379,13 +296,11 @@ void localFunc($$ int p) { } } } """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInAsParameterModifierInLambdaExpressions() - { - await VerifyKeywordAsync(""" + public Task TestInAsParameterModifierInLambdaExpressions() + => VerifyKeywordAsync(""" public delegate int Delegate(in int p); class Program @@ -396,13 +311,11 @@ public static void Test() } } """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInAsParameterModifierInAnonymousMethods() - { - await VerifyKeywordAsync(""" + public Task TestInAsParameterModifierInAnonymousMethods() + => VerifyKeywordAsync(""" public delegate int Delegate(in int p); class Program @@ -413,13 +326,11 @@ public static void Test() } } """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInAsModifierInMethodReturnTypes() - { - await VerifyAbsenceAsync(""" + public Task TestInAsModifierInMethodReturnTypes() + => VerifyAbsenceAsync(""" class Program { public $$ int Test() @@ -428,403 +339,328 @@ class Program } } """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInAsModifierInGlobalMemberDeclaration() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, """ + public Task TestInAsModifierInGlobalMemberDeclaration() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ public $$ """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInAsModifierInDelegateReturnType() - { - await VerifyAbsenceAsync(""" + public Task TestInAsModifierInDelegateReturnType() + => VerifyAbsenceAsync(""" public delegate $$ int Delegate(); class Program { } """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInAsModifierInMemberDeclaration() - { - await VerifyAbsenceAsync(""" + public Task TestInAsModifierInMemberDeclaration() + => VerifyAbsenceAsync(""" class Program { public $$ int Test { get; set; } } """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInMethodFirstArgumentModifier() - { - await VerifyKeywordAsync(""" + public Task TestInMethodFirstArgumentModifier() + => VerifyKeywordAsync(""" class C { void M() { Call($$ """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInMethodSecondArgumentModifier() - { - await VerifyKeywordAsync(""" + public Task TestInMethodSecondArgumentModifier() + => VerifyKeywordAsync(""" class C { void M(object arg1) { Call(arg1, $$ """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInBaseCallFirstArgumentModifier() - { - await VerifyKeywordAsync(""" + public Task TestInBaseCallFirstArgumentModifier() + => VerifyKeywordAsync(""" class C { public C() : base($$ """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInBaseCallSecondArgumentModifier() - { - await VerifyKeywordAsync(""" + public Task TestInBaseCallSecondArgumentModifier() + => VerifyKeywordAsync(""" class C { public C(object arg1) : base(arg1, $$ """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInThisCallFirstArgumentModifier() - { - await VerifyKeywordAsync(""" + public Task TestInThisCallFirstArgumentModifier() + => VerifyKeywordAsync(""" class C { public C() : this($$ """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInThisCallSecondArgumentModifier() - { - await VerifyKeywordAsync(""" + public Task TestInThisCallSecondArgumentModifier() + => VerifyKeywordAsync(""" class C { public C(object arg1) : this(arg1, $$ """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24079")] - public async Task TestInAsParameterModifierInConversionOperators() - { - await VerifyKeywordAsync(""" + public Task TestInAsParameterModifierInConversionOperators() + => VerifyKeywordAsync(""" class Program { public static explicit operator double($$) { } } """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24079")] - public async Task TestInAsParameterModifierInBinaryOperators() - { - await VerifyKeywordAsync(""" + public Task TestInAsParameterModifierInBinaryOperators() + => VerifyKeywordAsync(""" class Program { public static Program operator +($$) { } } """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInConstructorCallFirstArgumentModifier() - { - await VerifyKeywordAsync(""" + public Task TestInConstructorCallFirstArgumentModifier() + => VerifyKeywordAsync(""" class C { void M() { new MyType($$ """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInConstructorSecondArgumentModifier() - { - await VerifyKeywordAsync(""" + public Task TestInConstructorSecondArgumentModifier() + => VerifyKeywordAsync(""" class C { void M(object arg1) { new MyType(arg1, $$ """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInMethodFirstNamedArgumentModifier() - { - await VerifyKeywordAsync(""" + public Task TestInMethodFirstNamedArgumentModifier() + => VerifyKeywordAsync(""" class C { void M() { Call(a: $$ """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInMethodSecondNamedArgumentModifier() - { - await VerifyKeywordAsync(""" + public Task TestInMethodSecondNamedArgumentModifier() + => VerifyKeywordAsync(""" class C { void M(object arg1) { Call(a: arg1, b: $$ """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInBaseCallFirstNamedArgumentModifier() - { - await VerifyKeywordAsync(""" + public Task TestInBaseCallFirstNamedArgumentModifier() + => VerifyKeywordAsync(""" class C { public C() : base(a: $$ """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInBaseCallSecondNamedArgumentModifier() - { - await VerifyKeywordAsync(""" + public Task TestInBaseCallSecondNamedArgumentModifier() + => VerifyKeywordAsync(""" class C { public C(object arg1) : base(a: arg1, b: $$ """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInThisCallFirstNamedArgumentModifier() - { - await VerifyKeywordAsync(""" + public Task TestInThisCallFirstNamedArgumentModifier() + => VerifyKeywordAsync(""" class C { public C() : this(a: $$ """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInThisCallSecondNamedArgumentModifier() - { - await VerifyKeywordAsync(""" + public Task TestInThisCallSecondNamedArgumentModifier() + => VerifyKeywordAsync(""" class C { public C(object arg1) : this(a: arg1, b: $$ """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInConstructorCallFirstNamedArgumentModifier() - { - await VerifyKeywordAsync(""" + public Task TestInConstructorCallFirstNamedArgumentModifier() + => VerifyKeywordAsync(""" class C { void M() { new MyType(a: $$ """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] - public async Task TestInConstructorSecondNamedArgumentModifier() - { - await VerifyKeywordAsync(""" + public Task TestInConstructorSecondNamedArgumentModifier() + => VerifyKeywordAsync(""" class C { void M(object arg1) { new MyType(a: arg1, b: $$ """); - } [Fact] - public async Task TestExtensionMethods_FirstParameter() - { - await VerifyKeywordAsync( + public Task TestExtensionMethods_FirstParameter() + => VerifyKeywordAsync( """ static class Extensions { static void Extension($$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30339")] - public async Task TestExtensionMethods_FirstParameter_AfterThisKeyword() - { - await VerifyKeywordAsync( + public Task TestExtensionMethods_FirstParameter_AfterThisKeyword() + => VerifyKeywordAsync( """ static class Extensions { static void Extension(this $$ """); - } [Fact] - public async Task TestExtensionMethods_SecondParameter() - { - await VerifyKeywordAsync( + public Task TestExtensionMethods_SecondParameter() + => VerifyKeywordAsync( """ static class Extensions { static void Extension(this int i, $$ """); - } [Fact] - public async Task TestExtensionMethods_SecondParameter_AfterThisKeyword() - { - await VerifyAbsenceAsync( + public Task TestExtensionMethods_SecondParameter_AfterThisKeyword() + => VerifyAbsenceAsync( """ static class Extensions { static void Extension(this int i, this $$ """); - } [Fact] - public async Task TestExtensionMethods_FirstParameter_NonStaticClass() - { - await VerifyKeywordAsync( + public Task TestExtensionMethods_FirstParameter_NonStaticClass() + => VerifyKeywordAsync( """ class Extensions { static void Extension($$ """); - } [Fact] - public async Task TestExtensionMethods_FirstParameter_AfterThisKeyword_NonStaticClass() - { - await VerifyAbsenceAsync( + public Task TestExtensionMethods_FirstParameter_AfterThisKeyword_NonStaticClass() + => VerifyAbsenceAsync( """ class Extensions { static void Extension(this $$ """); - } [Fact] - public async Task TestExtensionMethods_SecondParameter_NonStaticClass() - { - await VerifyKeywordAsync( + public Task TestExtensionMethods_SecondParameter_NonStaticClass() + => VerifyKeywordAsync( """ class Extensions { static void Extension(this int i, $$ """); - } [Fact] - public async Task TestExtensionMethods_SecondParameter_AfterThisKeyword_NonStaticClass() - { - await VerifyAbsenceAsync( + public Task TestExtensionMethods_SecondParameter_AfterThisKeyword_NonStaticClass() + => VerifyAbsenceAsync( """ class Extensions { static void Extension(this int i, this $$ """); - } [Fact] - public async Task TestExtensionMethods_FirstParameter_NonStaticMethod() - { - await VerifyKeywordAsync( + public Task TestExtensionMethods_FirstParameter_NonStaticMethod() + => VerifyKeywordAsync( """ static class Extensions { void Extension($$ """); - } [Fact] - public async Task TestExtensionMethods_FirstParameter_AfterThisKeyword_NonStaticMethod() - { - await VerifyAbsenceAsync( + public Task TestExtensionMethods_FirstParameter_AfterThisKeyword_NonStaticMethod() + => VerifyAbsenceAsync( """ static class Extensions { void Extension(this $$ """); - } [Fact] - public async Task TestExtensionMethods_SecondParameter_NonStaticMethod() - { - await VerifyKeywordAsync( + public Task TestExtensionMethods_SecondParameter_NonStaticMethod() + => VerifyKeywordAsync( """ static class Extensions { void Extension(this int i, $$ """); - } [Fact] - public async Task TestExtensionMethods_SecondParameter_AfterThisKeyword_NonStaticMethod() - { - await VerifyAbsenceAsync( + public Task TestExtensionMethods_SecondParameter_AfterThisKeyword_NonStaticMethod() + => VerifyAbsenceAsync( """ static class Extensions { void Extension(this int i, this $$ """); - } [Fact] - public async Task TestInFunctionPointerTypeNoExistingModifiers() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerTypeNoExistingModifiers() + => VerifyKeywordAsync(""" class C { delegate*<$$ """); - } [Theory] [InlineData("in")] [InlineData("out")] [InlineData("ref")] [InlineData("ref readonly")] - public async Task TestNotInFunctionPointerTypeExistingModifiers(string modifier) - { - await VerifyAbsenceAsync($@" -class C -{{ - delegate*<{modifier} $$"); - } - - [Fact] - public async Task TestInParameterAfterScoped() - { - await VerifyKeywordAsync(""" + public Task TestNotInFunctionPointerTypeExistingModifiers(string modifier) + => VerifyAbsenceAsync($$""" + class C + { + delegate*<{{modifier}} $$ + """); + + [Fact] + public Task TestInParameterAfterScoped() + => VerifyKeywordAsync(""" class C { void M(scoped $$) } """); - } [Fact] - public async Task TestInParameterAfterThisScoped() - { - await VerifyKeywordAsync(""" + public Task TestInParameterAfterThisScoped() + => VerifyKeywordAsync(""" static class C { static void M(this scoped $$) } """); - } [Fact] - public async Task TestInAnonymousMethodParameterAfterScoped() - { - await VerifyKeywordAsync(""" + public Task TestInAnonymousMethodParameterAfterScoped() + => VerifyKeywordAsync(""" class C { void M() @@ -833,5 +669,4 @@ void M() } } """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/InitKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/InitKeywordRecommenderTests.cs index 4123a17633d77..c35ab299ac7c6 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/InitKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/InitKeywordRecommenderTests.cs @@ -12,360 +12,286 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class InitKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int Goo { $$ """); - } [Fact] - public async Task TestAfterPropertyPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterPropertyPrivate() + => VerifyKeywordAsync( """ class C { int Goo { private $$ """); - } [Fact] - public async Task TestAfterPropertyAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterPropertyAttribute() + => VerifyKeywordAsync( """ class C { int Goo { [Bar] $$ """); - } [Fact] - public async Task TestAfterPropertyAttributeAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterPropertyAttributeAndPrivate() + => VerifyKeywordAsync( """ class C { int Goo { [Bar] private $$ """); - } [Fact] - public async Task TestAfterPropertyGet() - { - await VerifyKeywordAsync( + public Task TestAfterPropertyGet() + => VerifyKeywordAsync( """ class C { int Goo { get; $$ """); - } [Fact] - public async Task TestAfterPropertyGetAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterPropertyGetAndPrivate() + => VerifyKeywordAsync( """ class C { int Goo { get; private $$ """); - } [Fact] - public async Task TestAfterPropertyGetAndAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterPropertyGetAndAttribute() + => VerifyKeywordAsync( """ class C { int Goo { get; [Bar] $$ """); - } [Fact] - public async Task TestAfterPropertyGetAndAttributeAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterPropertyGetAndAttributeAndPrivate() + => VerifyKeywordAsync( """ class C { int Goo { get; [Bar] private $$ """); - } [Fact] - public async Task TestAfterGetAccessorBlock() - { - await VerifyKeywordAsync( + public Task TestAfterGetAccessorBlock() + => VerifyKeywordAsync( """ class C { int Goo { get { } $$ """); - } [Fact] - public async Task TestAfterSetAccessorBlock() - { - await VerifyKeywordAsync( + public Task TestAfterSetAccessorBlock() + => VerifyKeywordAsync( """ class C { int Goo { set { } $$ """); - } [Fact] - public async Task TestAfterGetAccessorBlockAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterGetAccessorBlockAndPrivate() + => VerifyKeywordAsync( """ class C { int Goo { get { } private $$ """); - } [Fact] - public async Task TestAfterGetAccessorBlockAndAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterGetAccessorBlockAndAttribute() + => VerifyKeywordAsync( """ class C { int Goo { get { } [Bar] $$ """); - } [Fact] - public async Task TestAfterGetAccessorBlockAndAttributeAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterGetAccessorBlockAndAttributeAndPrivate() + => VerifyKeywordAsync( """ class C { int Goo { get { } [Bar] private $$ """); - } [Fact] - public async Task TestNotAfterPropertySetKeyword() - { - await VerifyAbsenceAsync( + public Task TestNotAfterPropertySetKeyword() + => VerifyAbsenceAsync( """ class C { int Goo { set $$ """); - } [Fact] - public async Task TestAfterPropertySetAccessor() - { - await VerifyKeywordAsync( + public Task TestAfterPropertySetAccessor() + => VerifyKeywordAsync( """ class C { int Goo { set; $$ """); - } [Fact] - public async Task TestNotInEvent() - { - await VerifyAbsenceAsync( + public Task TestNotInEvent() + => VerifyAbsenceAsync( """ class C { event Goo E { $$ """); - } [Fact] - public async Task TestAfterIndexer() - { - await VerifyKeywordAsync( + public Task TestAfterIndexer() + => VerifyKeywordAsync( """ class C { int this[int i] { $$ """); - } [Fact] - public async Task TestAfterIndexerPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerPrivate() + => VerifyKeywordAsync( """ class C { int this[int i] { private $$ """); - } [Fact] - public async Task TestAfterIndexerAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerAttribute() + => VerifyKeywordAsync( """ class C { int this[int i] { [Bar] $$ """); - } [Fact] - public async Task TestAfterIndexerAttributeAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerAttributeAndPrivate() + => VerifyKeywordAsync( """ class C { int this[int i] { [Bar] private $$ """); - } [Fact] - public async Task TestAfterIndexerGet() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerGet() + => VerifyKeywordAsync( """ class C { int this[int i] { get; $$ """); - } [Fact] - public async Task TestAfterIndexerGetAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerGetAndPrivate() + => VerifyKeywordAsync( """ class C { int this[int i] { get; private $$ """); - } [Fact] - public async Task TestAfterIndexerGetAndAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerGetAndAttribute() + => VerifyKeywordAsync( """ class C { int this[int i] { get; [Bar] $$ """); - } [Fact] - public async Task TestAfterIndexerGetAndAttributeAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerGetAndAttributeAndPrivate() + => VerifyKeywordAsync( """ class C { int this[int i] { get; [Bar] private $$ """); - } [Fact] - public async Task TestAfterIndexerGetBlock() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerGetBlock() + => VerifyKeywordAsync( """ class C { int this[int i] { get { } $$ """); - } [Fact] - public async Task TestAfterIndexerGetBlockAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerGetBlockAndPrivate() + => VerifyKeywordAsync( """ class C { int this[int i] { get { } private $$ """); - } [Fact] - public async Task TestAfterIndexerGetBlockAndAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerGetBlockAndAttribute() + => VerifyKeywordAsync( """ class C { int this[int i] { get { } [Bar] $$ """); - } [Fact] - public async Task TestAfterIndexerGetBlockAndAttributeAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerGetBlockAndAttributeAndPrivate() + => VerifyKeywordAsync( """ class C { int this[int i] { get { } [Bar] private $$ """); - } [Fact] - public async Task TestNotAfterIndexerSetKeyword() - { - await VerifyAbsenceAsync( + public Task TestNotAfterIndexerSetKeyword() + => VerifyAbsenceAsync( """ class C { int this[int i] { set $$ """); - } [Fact] - public async Task TestAfterIndexerSetAccessor() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerSetAccessor() + => VerifyKeywordAsync( """ class C { int this[int i] { set; $$ """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/IntKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/IntKeywordRecommenderTests.cs index c07fa8a9c9c96..bbde5547ec24a 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/IntKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/IntKeywordRecommenderTests.cs @@ -13,804 +13,619 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class IntKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestAfterStaticKeyword_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterStaticKeyword_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"static $$"); - } [Fact] - public async Task TestAfterPublicKeyword_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterPublicKeyword_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"public $$"); - } [Fact] - public async Task TestNotInUsing() - { - await VerifyAbsenceAsync( + public Task TestNotInUsing() + => VerifyAbsenceAsync( @"using $$"); - } [Fact] - public async Task TestInUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInUsingAlias() + => VerifyKeywordAsync( @"using Goo = $$"); - } [Fact] - public async Task TestInUsingAlias_Tuple() - { - await VerifyKeywordAsync( + public Task TestInUsingAlias_Tuple() + => VerifyKeywordAsync( @"using Goo = ($$"); - } [Fact] - public async Task TestInUsingAlias_FuncPointer() - { - await VerifyKeywordAsync( + public Task TestInUsingAlias_FuncPointer() + => VerifyKeywordAsync( @"using Goo = delegate*<$$"); - } [Fact] - public async Task TestInGlobalUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInGlobalUsingAlias() + => VerifyKeywordAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInPreprocessor1() - { - await VerifyAbsenceAsync( + public Task TestNotInPreprocessor1() + => VerifyAbsenceAsync( """ class C { #$$ """); - } [Fact] - public async Task TestNotInPreprocessor2() - { - await VerifyAbsenceAsync( + public Task TestNotInPreprocessor2() + => VerifyAbsenceAsync( """ class C { #if $$ """); - } [Fact] - public async Task TestAfterStackAlloc() - { - await VerifyKeywordAsync( + public Task TestAfterStackAlloc() + => VerifyKeywordAsync( """ class C { int* goo = stackalloc $$ """); - } [Fact] - public async Task TestInFixedStatement() - { - await VerifyKeywordAsync( + public Task TestInFixedStatement() + => VerifyKeywordAsync( @"fixed ($$"); - } [Fact] - public async Task TestInDelegateReturnType() - { - await VerifyKeywordAsync( + public Task TestInDelegateReturnType() + => VerifyKeywordAsync( @"public delegate $$"); - } [Fact] - public async Task TestInCastType() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); - } [Fact] - public async Task TestInCastType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType2() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); - } [Fact] - public async Task TestInEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestEnumBaseTypes() - { - await VerifyKeywordAsync( + public Task TestEnumBaseTypes() + => VerifyKeywordAsync( @"enum E : $$"); - } [Fact] - public async Task TestInGenericType1() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType1() + => VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); - } [Fact] - public async Task TestInGenericType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType2() + => VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList,$$")); - } [Fact] - public async Task TestNotInBaseList() - { - await VerifyAbsenceAsync( + public Task TestNotInBaseList() + => VerifyAbsenceAsync( @"class C : $$"); - } [Fact] - public async Task TestInGenericType_InBaseList() - { - await VerifyKeywordAsync( + public Task TestInGenericType_InBaseList() + => VerifyKeywordAsync( @"class C : IList<$$"); - } [Fact] - public async Task TestAfterIs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); - } [Fact] - public async Task TestAfterAs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterAs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync( + public Task TestInsideInterface() + => VerifyKeywordAsync( """ interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact] - public async Task TestAfterNestedPartial() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPartial() + => VerifyKeywordAsync( """ class C { partial $$ """); - } [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] - public async Task TestAfterNestedStaticPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticPublic() + => VerifyKeywordAsync( """ class C { static public $$ """); - } [Fact] - public async Task TestAfterNestedPublicStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublicStatic() + => VerifyKeywordAsync( """ class C { public static $$ """); - } [Fact] - public async Task TestAfterVirtualPublic() - { - await VerifyKeywordAsync( + public Task TestAfterVirtualPublic() + => VerifyKeywordAsync( """ class C { virtual public $$ """); - } [Fact] - public async Task TestAfterNestedPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublic() + => VerifyKeywordAsync( """ class C { public $$ """); - } [Fact] - public async Task TestAfterNestedPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPrivate() + => VerifyKeywordAsync( """ class C { private $$ """); - } [Fact] - public async Task TestAfterNestedProtected() - { - await VerifyKeywordAsync( + public Task TestAfterNestedProtected() + => VerifyKeywordAsync( """ class C { protected $$ """); - } [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] - public async Task TestAfterNestedStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStatic() + => VerifyKeywordAsync( """ class C { static $$ """); - } [Fact] - public async Task TestInLocalVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLocalVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInForVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"for ($$")); - } [Fact] - public async Task TestInForeachVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForeachVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); - } [Fact] - public async Task TestInUsingVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInUsingVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"using ($$")); - } [Fact] - public async Task TestInFromVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFromVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); - } [Fact] - public async Task TestInJoinVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInJoinVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from a in b join $$ """)); - } [Fact] - public async Task TestAfterMethodOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterMethodOpenParen() + => VerifyKeywordAsync( """ class C { void Goo($$ """); - } [Fact] - public async Task TestAfterMethodComma() - { - await VerifyKeywordAsync( + public Task TestAfterMethodComma() + => VerifyKeywordAsync( """ class C { void Goo(int i, $$ """); - } [Fact] - public async Task TestAfterMethodAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterMethodAttribute() + => VerifyKeywordAsync( """ class C { void Goo(int i, [Goo]$$ """); - } [Fact] public async Task TestAfterStatementAttribute() => await VerifyKeywordAsync(AddInsideMethod(@"[Goo] $$")); [Fact] - public async Task TestAfterConstructorOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorOpenParen() + => VerifyKeywordAsync( """ class C { public C($$ """); - } [Fact] - public async Task TestAfterConstructorComma() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorComma() + => VerifyKeywordAsync( """ class C { public C(int i, $$ """); - } [Fact] - public async Task TestAfterConstructorAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorAttribute() + => VerifyKeywordAsync( """ class C { public C(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterDelegateOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateOpenParen() + => VerifyKeywordAsync( @"delegate void D($$"); - } [Fact] - public async Task TestAfterDelegateComma() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateComma() + => VerifyKeywordAsync( @"delegate void D(int i, $$"); - } [Fact] - public async Task TestAfterDelegateAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateAttribute() + => VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); - } [Fact] - public async Task TestAfterThis() - { - await VerifyKeywordAsync( + public Task TestAfterThis() + => VerifyKeywordAsync( """ static class C { public static void Goo(this $$ """); - } [Fact] - public async Task TestAfterRef() - { - await VerifyKeywordAsync( + public Task TestAfterRef() + => VerifyKeywordAsync( """ class C { void Goo(ref $$ """); - } [Fact] - public async Task TestAfterOut() - { - await VerifyKeywordAsync( + public Task TestAfterOut() + => VerifyKeywordAsync( """ class C { void Goo(out $$ """); - } [Fact] - public async Task TestAfterLambdaRef() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaRef() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (ref $$ """); - } [Fact] - public async Task TestAfterLambdaOut() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaOut() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (out $$ """); - } [Fact] - public async Task TestAfterParams() - { - await VerifyKeywordAsync( + public Task TestAfterParams() + => VerifyKeywordAsync( """ class C { void Goo(params $$ """); - } [Fact] - public async Task TestInImplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInImplicitOperator() + => VerifyKeywordAsync( """ class C { public static implicit operator $$ """); - } [Fact] - public async Task TestInExplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInExplicitOperator() + => VerifyKeywordAsync( """ class C { public static explicit operator $$ """); - } [Fact] - public async Task TestAfterIndexerBracket() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracket() + => VerifyKeywordAsync( """ class C { int this[$$ """); - } [Fact] - public async Task TestAfterIndexerBracketComma() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracketComma() + => VerifyKeywordAsync( """ class C { int this[int i, $$ """); - } [Fact] - public async Task TestAfterNewInExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterNewInExpression() + => VerifyKeywordAsync(AddInsideMethod( @"new $$")); - } [Fact] - public async Task TestAfterConstInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterConstInMemberContext() + => VerifyKeywordAsync( """ class C { const $$ """); - } [Fact] - public async Task TestAfterRefInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefInMemberContext() + => VerifyKeywordAsync( """ class C { ref $$ """); - } [Fact] - public async Task TestAfterRefReadonlyInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyInMemberContext() + => VerifyKeywordAsync( """ class C { ref readonly $$ """); - } [Fact] - public async Task TestAfterConstInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"const $$")); - } [Fact] - public async Task TestAfterRefInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$")); - } [Fact] - public async Task TestAfterRefReadonlyInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); - } [Fact] - public async Task TestAfterConstLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); - } [Fact] - public async Task TestAfterRefReadonlyLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); - } [Fact] - public async Task TestAfterRefReadonlyLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); - } [Fact] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } [Fact] - public async Task TestInUncheckedCast() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInUncheckedCast() + => VerifyKeywordAsync(AddInsideMethod( @"return unchecked(($$")); - } [Fact] - public async Task TestNotAfterPointerDecl() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterPointerDecl() + => VerifyAbsenceAsync(AddInsideMethod( @"int* $$")); - } [Fact] - public async Task TestNotAfterNullableDecl() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterNullableDecl() + => VerifyAbsenceAsync(AddInsideMethod( @"int? $$")); - } [Fact] - public async Task TestAfterNew() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterNew() + => VerifyKeywordAsync(AddInsideMethod( @"int[] i = new $$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInTypeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInTypeOf() + => VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInDefault() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDefault() + => VerifyKeywordAsync(AddInsideMethod( @"default($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInSizeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInSizeOf() + => VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); - } [Fact] - public async Task TestAfterTopLevelMemberDeclaration() - { - await VerifyKeywordAsync(SourceCodeKind.Script, """ + public Task TestAfterTopLevelMemberDeclaration() + => VerifyKeywordAsync(SourceCodeKind.Script, """ void Goo() { } $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -818,12 +633,10 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] - public async Task TestInCrefContext() - { - await VerifyKeywordAsync(""" + public Task TestInCrefContext() + => VerifyKeywordAsync(""" class Program { /// @@ -833,16 +646,13 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] - public async Task TestInCrefContextNotAfterDot() - { - await VerifyAbsenceAsync(""" + public Task TestInCrefContextNotAfterDot() + => VerifyAbsenceAsync(""" /// class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] public async Task TestNotAfterAsync() @@ -853,19 +663,16 @@ public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1468")] - public async Task TestNotInCrefTypeParameter() - { - await VerifyAbsenceAsync(""" + public Task TestNotInCrefTypeParameter() + => VerifyAbsenceAsync(""" using System; /// class C { } """); - } [Fact] - public async Task Preselection() - { - await VerifyKeywordAsync(""" + public Task Preselection() + => VerifyKeywordAsync(""" class Program { static void Main(string[] args) @@ -875,23 +682,19 @@ static void Main(string[] args) static void Helper(int x) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinType() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinType() + => VerifyKeywordAsync(""" class Program { ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinMember() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinMember() + => VerifyKeywordAsync(""" class Program { void Method() @@ -900,96 +703,76 @@ void Method() } } """); - } [Fact] - public async Task TestInFunctionPointerType() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerType() + => VerifyKeywordAsync(""" class C { delegate*<$$ """); - } [Fact] - public async Task TestInFunctionPointerTypeAfterComma() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerTypeAfterComma() + => VerifyKeywordAsync(""" class C { delegate* VerifyKeywordAsync(""" class C { delegate* VerifyAbsenceAsync(""" class C { delegate*$$ """); - } [Fact] - public async Task TestNotInDeclarationDeconstruction() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInDeclarationDeconstruction() + => VerifyAbsenceAsync(AddInsideMethod( @"var (x, $$) = (0, 0);")); - } [Fact] - public async Task TestInMixedDeclarationAndAssignmentInDeconstruction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInMixedDeclarationAndAssignmentInDeconstruction() + => VerifyKeywordAsync(AddInsideMethod( @"(x, $$) = (0, 0);")); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/53585")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithoutAsync))] - public async Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) - { - await VerifyKeywordAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) + => VerifyKeywordAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithAsync))] - public async Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) - { - await VerifyAbsenceAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) + => VerifyAbsenceAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64585")] - public async Task TestAfterRequired() - { - await VerifyKeywordAsync(""" + public Task TestAfterRequired() + => VerifyKeywordAsync(""" class C { required $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefAtTopLevel1() + => VerifyKeywordAsync( @"ref $$"); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [CombinatorialData] @@ -1010,216 +793,183 @@ await VerifyAbsenceAsync( } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefReadonlyAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyAtTopLevel1() + => VerifyKeywordAsync( @"ref readonly $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { readonly $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref readonly $$ } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref $$ -}}"); - } + public Task TestAfterRefInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - readonly $$ -}}"); - } + public Task TestAfterReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + readonly $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref readonly $$ -}}"); - } + public Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref readonly $$ + } + """); #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -1229,5 +979,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/InterfaceKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/InterfaceKeywordRecommenderTests.cs index 6dfb2bc102b67..32acf9e0abc67 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/InterfaceKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/InterfaceKeywordRecommenderTests.cs @@ -12,311 +12,245 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class InterfaceKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInCompilationUnit() - { - await VerifyKeywordAsync( + public Task TestInCompilationUnit() + => VerifyKeywordAsync( @"$$"); - } [Fact] - public async Task TestAfterExtern() - { - await VerifyKeywordAsync( + public Task TestAfterExtern() + => VerifyKeywordAsync( """ extern alias Goo; $$ """); - } [Fact] - public async Task TestAfterUsing() - { - await VerifyKeywordAsync( + public Task TestAfterUsing() + => VerifyKeywordAsync( """ using Goo; $$ """); - } [Fact] - public async Task TestAfterGlobalUsing() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalUsing() + => VerifyKeywordAsync( """ global using Goo; $$ """); - } [Fact] - public async Task TestAfterNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterNamespace() + => VerifyKeywordAsync( """ namespace N {} $$ """); - } [Fact] - public async Task TestAfterFileScopedNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterFileScopedNamespace() + => VerifyKeywordAsync( """ namespace N; $$ """); - } [Fact] - public async Task TestAfterTypeDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterTypeDeclaration() + => VerifyKeywordAsync( """ class C {} $$ """); - } [Fact] - public async Task TestAfterDelegateDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateDeclaration() + => VerifyKeywordAsync( """ delegate void Goo(); $$ """); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ global using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeGlobalUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeGlobalUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ global using Goo; """); - } [Fact] - public async Task TestAfterAssemblyAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterAssemblyAttribute() + => VerifyKeywordAsync( """ [assembly: goo] $$ """); - } [Fact] - public async Task TestAfterRootAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterRootAttribute() + => VerifyKeywordAsync( """ [goo] $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync(""" + public Task TestInsideInterface() + => VerifyKeywordAsync(""" interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] - public async Task TestAfterPartial() - { - await VerifyKeywordAsync( + public Task TestAfterPartial() + => VerifyKeywordAsync( @"partial $$"); - } [Fact] public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact] - public async Task TestAfterInternal() - { - await VerifyKeywordAsync( + public Task TestAfterInternal() + => VerifyKeywordAsync( @"internal $$"); - } [Fact] - public async Task TestAfterPublic() - { - await VerifyKeywordAsync( + public Task TestAfterPublic() + => VerifyKeywordAsync( @"public $$"); - } [Fact] - public async Task TestAfterPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterPrivate() + => VerifyKeywordAsync( @"private $$"); - } [Fact] - public async Task TestAfterProtected() - { - await VerifyKeywordAsync( + public Task TestAfterProtected() + => VerifyKeywordAsync( @"protected $$"); - } [Fact] public async Task TestNotAfterSealed() @@ -335,9 +269,8 @@ public async Task TestNotAfterInterface() => await VerifyAbsenceAsync(@"interface $$"); [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -349,5 +282,4 @@ static class C """, CSharpNextParseOptions, CSharpNextScriptParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/InternalKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/InternalKeywordRecommenderTests.cs index b39a119beef17..1cf91b2172757 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/InternalKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/InternalKeywordRecommenderTests.cs @@ -12,283 +12,225 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class InternalKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInCompilationUnit() - { - await VerifyKeywordAsync( + public Task TestInCompilationUnit() + => VerifyKeywordAsync( @"$$"); - } [Fact] - public async Task TestAfterExtern() - { - await VerifyKeywordAsync( + public Task TestAfterExtern() + => VerifyKeywordAsync( """ extern alias Goo; $$ """); - } [Fact] - public async Task TestAfterUsing() - { - await VerifyKeywordAsync( + public Task TestAfterUsing() + => VerifyKeywordAsync( """ using Goo; $$ """); - } [Fact] - public async Task TestAfterGlobalUsing() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalUsing() + => VerifyKeywordAsync( """ global using Goo; $$ """); - } [Fact] - public async Task TestAfterNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterNamespace() + => VerifyKeywordAsync( """ namespace N {} $$ """); - } [Fact] - public async Task TestAfterFileScopedNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterFileScopedNamespace() + => VerifyKeywordAsync( """ namespace N; $$ """); - } [Fact] - public async Task TestAfterTypeDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterTypeDeclaration() + => VerifyKeywordAsync( """ class C {} $$ """); - } [Fact] - public async Task TestAfterDelegateDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateDeclaration() + => VerifyKeywordAsync( """ delegate void Goo(); $$ """); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ global using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeGlobalUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeGlobalUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ global using Goo; """); - } [Fact] - public async Task TestAfterAssemblyAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterAssemblyAttribute() + => VerifyKeywordAsync( """ [assembly: goo] $$ """); - } [Fact] - public async Task TestAfterRootAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterRootAttribute() + => VerifyKeywordAsync( """ [goo] $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync(""" + public Task TestInsideInterface() + => VerifyKeywordAsync(""" interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact] - public async Task TestAfterAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterAbstract() + => VerifyKeywordAsync( @"abstract $$"); - } [Fact] public async Task TestNotAfterInternal() @@ -315,39 +257,29 @@ public async Task TestNotAfterPrivate() => await VerifyAbsenceAsync(@"private $$"); [Fact] - public async Task TestAfterProtected() - { - await VerifyKeywordAsync( + public Task TestAfterProtected() + => VerifyKeywordAsync( @"protected $$"); - } [Fact] - public async Task TestAfterSealed() - { - await VerifyKeywordAsync( + public Task TestAfterSealed() + => VerifyKeywordAsync( @"sealed $$"); - } [Fact] - public async Task TestAfterStatic() - { - await VerifyKeywordAsync( + public Task TestAfterStatic() + => VerifyKeywordAsync( @"static $$"); - } [Fact] - public async Task TestNotAfterStaticInUsingDirective() - { - await VerifyAbsenceAsync( + public Task TestNotAfterStaticInUsingDirective() + => VerifyAbsenceAsync( @"using static $$"); - } [Fact] - public async Task TestNotAfterStaticInGlobalUsingDirective() - { - await VerifyAbsenceAsync( + public Task TestNotAfterStaticInGlobalUsingDirective() + => VerifyAbsenceAsync( @"global using static $$"); - } [Fact] public async Task TestNotAfterClass() @@ -358,129 +290,104 @@ public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] - public async Task TestAfterNestedVirtual() - { - await VerifyKeywordAsync( + public Task TestAfterNestedVirtual() + => VerifyKeywordAsync( """ class C { virtual $$ """); - } [Fact] - public async Task TestAfterNestedOverride() - { - await VerifyKeywordAsync( + public Task TestAfterNestedOverride() + => VerifyKeywordAsync( """ class C { override $$ """); - } [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] - public async Task TestInProperty() - { - await VerifyKeywordAsync( + public Task TestInProperty() + => VerifyKeywordAsync( """ class C { int Goo { $$ """); - } [Fact] - public async Task TestInPropertyAfterAccessor() - { - await VerifyKeywordAsync( + public Task TestInPropertyAfterAccessor() + => VerifyKeywordAsync( """ class C { int Goo { get; $$ """); - } [Fact] - public async Task TestNotInPropertyAfterInternal() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAfterInternal() + => VerifyAbsenceAsync( """ class C { int Goo { get; internal $$ """); - } [Fact] - public async Task TestInPropertyAfterProtected() - { - await VerifyKeywordAsync( + public Task TestInPropertyAfterProtected() + => VerifyKeywordAsync( """ class C { int Goo { get; protected $$ """); - } [Fact] - public async Task TestInIndexer() - { - await VerifyKeywordAsync( + public Task TestInIndexer() + => VerifyKeywordAsync( """ class C { int this[int i] { $$ """); - } [Fact] - public async Task TestInIndexerAfterAccessor() - { - await VerifyKeywordAsync( + public Task TestInIndexerAfterAccessor() + => VerifyKeywordAsync( """ class C { int this[int i] { get { } $$ """); - } [Fact] - public async Task TestNotInIndexerAfterInternal() - { - await VerifyAbsenceAsync( + public Task TestNotInIndexerAfterInternal() + => VerifyAbsenceAsync( """ class C { int this[int i] { get { } internal $$ """); - } [Fact] - public async Task TestInIndexerAfterProtected() - { - await VerifyKeywordAsync( + public Task TestInIndexerAfterProtected() + => VerifyKeywordAsync( """ class C { int this[int i] { get { } protected $$ """); - } [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -492,5 +399,4 @@ static class C """, CSharpNextParseOptions, CSharpNextScriptParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/IntoKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/IntoKeywordRecommenderTests.cs index 797197205f1b5..df7bc1643e450 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/IntoKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/IntoKeywordRecommenderTests.cs @@ -12,196 +12,154 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class IntoKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestNotInSelectMemberExpressionOnlyADot() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInSelectMemberExpressionOnlyADot() + => VerifyAbsenceAsync(AddInsideMethod( @"var y = from x in new [] { 1,2,3 } select x.$$")); - } [Fact] - public async Task TestNotInSelectMemberExpression() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInSelectMemberExpression() + => VerifyAbsenceAsync(AddInsideMethod( @"var y = from x in new [] { 1,2,3 } select x.i$$")); - } [Fact] - public async Task TestAfterJoinRightExpr() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterJoinRightExpr() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y join a in e on o1 equals o2 $$ """)); - } [Fact] - public async Task TestAfterJoinRightExpr_NotAfterInto() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestAfterJoinRightExpr_NotAfterInto() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y join a.b c in o1 equals o2 into $$ """)); - } [Fact] - public async Task TestNotAfterEquals() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterEquals() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y join a.b c in o1 equals $$ """)); - } [Fact] - public async Task TestAfterSelectClause() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterSelectClause() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y select z $$ """)); - } [Fact] - public async Task TestAfterSelectClauseWithMemberExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterSelectClauseWithMemberExpression() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y select z.i $$ """)); - } [Fact] - public async Task TestAfterSelectClause_NotAfterInto() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestAfterSelectClause_NotAfterInto() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y select z into $$ """)); - } [Fact] - public async Task TestAfterGroupClause() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterGroupClause() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y group z by w $$ """)); - } [Fact] - public async Task TestAfterGroupClause_NotAfterInto() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestAfterGroupClause_NotAfterInto() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y group z by w into $$ """)); - } [Fact] - public async Task TestNotAfterSelect() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterSelect() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y select $$ """)); - } [Fact] - public async Task TestNotAfterGroupKeyword() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterGroupKeyword() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y group $$ """)); - } [Fact] - public async Task TestNotAfterGroupExpression() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterGroupExpression() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y group x $$ """)); - } [Fact] - public async Task TestNotAfterGroupBy() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterGroupBy() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y group x by $$ """)); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/IsKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/IsKeywordRecommenderTests.cs index bb5ac829bd6c4..ce21db4353e6f 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/IsKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/IsKeywordRecommenderTests.cs @@ -13,131 +13,99 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class IsKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterExpr() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterExpr() + => VerifyKeywordAsync(AddInsideMethod( @"var q = goo $$")); - } [Fact] - public async Task TestNotAfterVoid() - { - await VerifyAbsenceAsync( + public Task TestNotAfterVoid() + => VerifyAbsenceAsync( """ class C { void $$ """); - } [Fact] - public async Task TestNotInForeach() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInForeach() + => VerifyAbsenceAsync(AddInsideMethod( @"foreach (var v $$")); - } [Fact] - public async Task TestNotInFrom() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInFrom() + => VerifyAbsenceAsync(AddInsideMethod( @"var q = from a $$")); - } [Fact] - public async Task TestNotInJoin() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInJoin() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from a in b join x $$ """)); - } [Fact] - public async Task TestNotAfterType1() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterType1() + => VerifyAbsenceAsync(AddInsideMethod( @"int $$")); - } [Fact] - public async Task TestNotAfterType2() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterType2() + => VerifyAbsenceAsync(AddInsideMethod( @"Goo $$")); - } [Fact] - public async Task TestNotAfterType3() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterType3() + => VerifyAbsenceAsync(AddInsideMethod( @"Goo $$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543041")] - public async Task TestNotAfterVarInForLoop() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterVarInForLoop() + => VerifyAbsenceAsync(AddInsideMethod( @"for (var $$")); - } [Fact] public async Task TestNotAfterVarInOutArgument() @@ -148,61 +116,48 @@ await VerifyAbsenceAsync(AddInsideMethod( } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] - public async Task TestNotBeforeFirstStringHole() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotBeforeFirstStringHole() + => VerifyAbsenceAsync(AddInsideMethod( """ var x = "\{0}$$\{1}\{2}" """)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] - public async Task TestNotBetweenStringHoles() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotBetweenStringHoles() + => VerifyAbsenceAsync(AddInsideMethod( """ var x = "\{0}\{1}$$\{2}" """)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] - public async Task TestNotAfterStringHoles() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterStringHoles() + => VerifyAbsenceAsync(AddInsideMethod( """ var x = "\{0}\{1}\{2}$$" """)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] - public async Task TestAfterLastStringHole() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterLastStringHole() + => VerifyKeywordAsync(AddInsideMethod( @"var x = ""\{0}\{1}\{2}"" $$")); - } [Fact] - public async Task TestAfterExpression_InMethodWithArrowBody() - { - await VerifyKeywordAsync(""" + public Task TestAfterExpression_InMethodWithArrowBody() + => VerifyKeywordAsync(""" class C { bool M() => this $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1736")] - public async Task TestNotWithinNumericLiteral() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotWithinNumericLiteral() + => VerifyAbsenceAsync(AddInsideMethod( @"var x = .$$0;")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28586")] - public async Task TestNotAfterAsync() - { - await VerifyAbsenceAsync( + public Task TestNotAfterAsync() + => VerifyAbsenceAsync( """ using System; @@ -218,12 +173,10 @@ void Bar(Func f) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8319")] - public async Task TestNotAfterMethodReference() - { - await VerifyAbsenceAsync( + public Task TestNotAfterMethodReference() + => VerifyAbsenceAsync( """ using System; @@ -231,12 +184,10 @@ class C { void M() { var v = Console.WriteLine $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8319")] - public async Task TestNotAfterAnonymousMethod() - { - await VerifyAbsenceAsync( + public Task TestNotAfterAnonymousMethod() + => VerifyAbsenceAsync( """ using System; @@ -244,12 +195,10 @@ class C { void M() { Action a = delegate { } $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8319")] - public async Task TestNotAfterLambda1() - { - await VerifyAbsenceAsync( + public Task TestNotAfterLambda1() + => VerifyAbsenceAsync( """ using System; @@ -257,12 +206,10 @@ class C { void M() { Action b = (() => 0) $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8319")] - public async Task TestNotAfterLambda2() - { - await VerifyAbsenceAsync( + public Task TestNotAfterLambda2() + => VerifyAbsenceAsync( """ using System; @@ -270,12 +217,10 @@ class C { void M() { Action b = () => {} $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48573")] - public async Task TestMissingAfterNumericLiteral() - { - await VerifyAbsenceAsync( + public Task TestMissingAfterNumericLiteral() + => VerifyAbsenceAsync( """ class C { @@ -285,12 +230,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48573")] - public async Task TestMissingAfterNumericLiteralAndDot() - { - await VerifyAbsenceAsync( + public Task TestMissingAfterNumericLiteralAndDot() + => VerifyAbsenceAsync( """ class C { @@ -300,12 +243,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48573")] - public async Task TestMissingAfterNumericLiteralDotAndSpace() - { - await VerifyAbsenceAsync( + public Task TestMissingAfterNumericLiteralDotAndSpace() + => VerifyAbsenceAsync( """ class C { @@ -315,12 +256,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31367")] - public async Task TestMissingInCaseClause1() - { - await VerifyAbsenceAsync( + public Task TestMissingInCaseClause1() + => VerifyAbsenceAsync( """ class A { @@ -338,12 +277,10 @@ void M(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31367")] - public async Task TestMissingInCaseClause2() - { - await VerifyAbsenceAsync( + public Task TestMissingInCaseClause2() + => VerifyAbsenceAsync( """ namespace N { @@ -364,5 +301,4 @@ void M(object o) } } """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/JoinKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/JoinKeywordRecommenderTests.cs index 0f810697269da..704309574e37c 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/JoinKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/JoinKeywordRecommenderTests.cs @@ -12,121 +12,95 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class JoinKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestNotAtEndOfPreviousClause() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAtEndOfPreviousClause() + => VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y$$")); - } [Fact] - public async Task TestNewClause() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestNewClause() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y $$ """)); - } [Fact] - public async Task TestAfterPreviousClause() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterPreviousClause() + => VerifyKeywordAsync(AddInsideMethod( """ var v = from x in y where x > y $$ """)); - } [Fact] - public async Task TestAfterPreviousContinuationClause() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterPreviousContinuationClause() + => VerifyKeywordAsync(AddInsideMethod( """ var v = from x in y group x by y into g $$ """)); - } [Fact] - public async Task TestBetweenClauses() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBetweenClauses() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y $$ from z in w """)); - } [Fact] - public async Task TestNotAfterJoin() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterJoin() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y join $$ from z in w """)); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/LetKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/LetKeywordRecommenderTests.cs index 0d60997afc871..3c57b02be3572 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/LetKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/LetKeywordRecommenderTests.cs @@ -12,120 +12,94 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class LetKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestNotAtEndOfPreviousClause() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAtEndOfPreviousClause() + => VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y$$")); - } [Fact] - public async Task TestNewClause() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestNewClause() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y $$ """)); - } [Fact] - public async Task TestAfterPreviousClause() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterPreviousClause() + => VerifyKeywordAsync(AddInsideMethod( """ var v = from x in y where x > y $$ """)); - } [Fact] - public async Task TestAfterPreviousContinuationClause() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterPreviousContinuationClause() + => VerifyKeywordAsync(AddInsideMethod( """ var v = from x in y group x by y into g $$ """)); - } [Fact] - public async Task TestBetweenClauses() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBetweenClauses() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y $$ from z in w """)); - } [Fact] - public async Task TestNotAfterLet() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterLet() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y let $$ """)); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/LineKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/LineKeywordRecommenderTests.cs index 7994cc22c1fbd..c8150f29fc3d4 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/LineKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/LineKeywordRecommenderTests.cs @@ -12,74 +12,56 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class LineKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterHash() - { - await VerifyKeywordAsync( + public Task TestAfterHash() + => VerifyKeywordAsync( @"#$$"); - } [Fact] - public async Task TestAfterHashAndSpace() - { - await VerifyKeywordAsync( + public Task TestAfterHashAndSpace() + => VerifyKeywordAsync( @"# $$"); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/LockKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/LockKeywordRecommenderTests.cs index 227055b457145..f273ac43b22c7 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/LockKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/LockKeywordRecommenderTests.cs @@ -12,134 +12,104 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class LockKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestBeforeStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBeforeStatement() + => VerifyKeywordAsync(AddInsideMethod( """ $$ return true; """)); - } [Fact] - public async Task TestAfterStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterStatement() + => VerifyKeywordAsync(AddInsideMethod( """ return true; $$ """)); - } [Fact] - public async Task TestAfterBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBlock() + => VerifyKeywordAsync(AddInsideMethod( """ if (true) { } $$ """)); - } [Fact] - public async Task TestInsideSwitchBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideSwitchBlock() + => VerifyKeywordAsync(AddInsideMethod( """ switch (E) { case 0: $$ """)); - } [Fact] - public async Task TestNotAfterLock1() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterLock1() + => VerifyAbsenceAsync(AddInsideMethod( @"lock $$")); - } [Fact] - public async Task TestNotAfterLock2() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterLock2() + => VerifyAbsenceAsync(AddInsideMethod( @"lock ($$")); - } [Fact] - public async Task TestNotAfterLock3() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterLock3() + => VerifyAbsenceAsync(AddInsideMethod( @"lock (l$$")); - } [Fact] - public async Task TestNotInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotInClass() + => VerifyAbsenceAsync(""" class C { $$ } """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/LongKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/LongKeywordRecommenderTests.cs index 691af0383ad8c..8c3992d630634 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/LongKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/LongKeywordRecommenderTests.cs @@ -13,712 +13,549 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class LongKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsing() - { - await VerifyAbsenceAsync( + public Task TestNotInUsing() + => VerifyAbsenceAsync( @"using $$"); - } [Fact] - public async Task TestInUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInUsingAlias() + => VerifyKeywordAsync( @"using Goo = $$"); - } [Fact] - public async Task TestInGlobalUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInGlobalUsingAlias() + => VerifyKeywordAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestAfterStackAlloc() - { - await VerifyKeywordAsync( + public Task TestAfterStackAlloc() + => VerifyKeywordAsync( """ class C { int* goo = stackalloc $$ """); - } [Fact] - public async Task TestAfterConstInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterConstInMemberContext() + => VerifyKeywordAsync( """ class C { const $$ """); - } [Fact] - public async Task TestAfterRefInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefInMemberContext() + => VerifyKeywordAsync( """ class C { ref $$ """); - } [Fact] - public async Task TestAfterRefReadonlyInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyInMemberContext() + => VerifyKeywordAsync( """ class C { ref readonly $$ """); - } [Fact] - public async Task TestAfterConstInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"const $$")); - } [Fact] - public async Task TestAfterRefInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$")); - } [Fact] - public async Task TestAfterRefReadonlyInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); - } [Fact] - public async Task TestAfterConstLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); - } [Fact] - public async Task TestAfterRefReadonlyLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); - } [Fact] - public async Task TestAfterRefReadonlyLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); - } [Fact] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } [Fact] - public async Task TestInFixedStatement() - { - await VerifyKeywordAsync( + public Task TestInFixedStatement() + => VerifyKeywordAsync( @"fixed ($$"); - } [Fact] - public async Task TestInDelegateReturnType() - { - await VerifyKeywordAsync( + public Task TestInDelegateReturnType() + => VerifyKeywordAsync( @"public delegate $$"); - } [Fact] - public async Task TestInCastType() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); - } [Fact] - public async Task TestInCastType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType2() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); - } [Fact] - public async Task TestInEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestEnumBaseTypes() - { - await VerifyKeywordAsync( + public Task TestEnumBaseTypes() + => VerifyKeywordAsync( @"enum E : $$"); - } [Fact] - public async Task TestInGenericType1() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType1() + => VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); - } [Fact] - public async Task TestInGenericType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType2() + => VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList,$$")); - } [Fact] - public async Task TestNotInBaseList() - { - await VerifyAbsenceAsync( + public Task TestNotInBaseList() + => VerifyAbsenceAsync( @"class C : $$"); - } [Fact] - public async Task TestInGenericType_InBaseList() - { - await VerifyKeywordAsync( + public Task TestInGenericType_InBaseList() + => VerifyKeywordAsync( @"class C : IList<$$"); - } [Fact] - public async Task TestAfterIs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); - } [Fact] - public async Task TestAfterAs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterAs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync( + public Task TestInsideInterface() + => VerifyKeywordAsync( """ interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact] - public async Task TestAfterNestedPartial() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPartial() + => VerifyKeywordAsync( """ class C { partial $$ """); - } [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] - public async Task TestAfterNestedStaticPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticPublic() + => VerifyKeywordAsync( """ class C { static public $$ """); - } [Fact] - public async Task TestAfterNestedPublicStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublicStatic() + => VerifyKeywordAsync( """ class C { public static $$ """); - } [Fact] - public async Task TestAfterVirtualPublic() - { - await VerifyKeywordAsync( + public Task TestAfterVirtualPublic() + => VerifyKeywordAsync( """ class C { virtual public $$ """); - } [Fact] - public async Task TestAfterNestedPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublic() + => VerifyKeywordAsync( """ class C { public $$ """); - } [Fact] - public async Task TestAfterNestedPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPrivate() + => VerifyKeywordAsync( """ class C { private $$ """); - } [Fact] - public async Task TestAfterNestedProtected() - { - await VerifyKeywordAsync( + public Task TestAfterNestedProtected() + => VerifyKeywordAsync( """ class C { protected $$ """); - } [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] - public async Task TestAfterNestedStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStatic() + => VerifyKeywordAsync( """ class C { static $$ """); - } [Fact] - public async Task TestInLocalVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLocalVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInForVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"for ($$")); - } [Fact] - public async Task TestInForeachVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForeachVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); - } [Fact] - public async Task TestInUsingVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInUsingVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"using ($$")); - } [Fact] - public async Task TestInFromVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFromVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); - } [Fact] - public async Task TestInJoinVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInJoinVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from a in b join $$ """)); - } [Fact] - public async Task TestAfterMethodOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterMethodOpenParen() + => VerifyKeywordAsync( """ class C { void Goo($$ """); - } [Fact] - public async Task TestAfterMethodComma() - { - await VerifyKeywordAsync( + public Task TestAfterMethodComma() + => VerifyKeywordAsync( """ class C { void Goo(int i, $$ """); - } [Fact] - public async Task TestAfterMethodAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterMethodAttribute() + => VerifyKeywordAsync( """ class C { void Goo(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterConstructorOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorOpenParen() + => VerifyKeywordAsync( """ class C { public C($$ """); - } [Fact] - public async Task TestAfterConstructorComma() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorComma() + => VerifyKeywordAsync( """ class C { public C(int i, $$ """); - } [Fact] - public async Task TestAfterConstructorAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorAttribute() + => VerifyKeywordAsync( """ class C { public C(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterDelegateOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateOpenParen() + => VerifyKeywordAsync( @"delegate void D($$"); - } [Fact] - public async Task TestAfterDelegateComma() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateComma() + => VerifyKeywordAsync( @"delegate void D(int i, $$"); - } [Fact] - public async Task TestAfterDelegateAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateAttribute() + => VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); - } [Fact] - public async Task TestAfterThis() - { - await VerifyKeywordAsync( + public Task TestAfterThis() + => VerifyKeywordAsync( """ static class C { public static void Goo(this $$ """); - } [Fact] - public async Task TestAfterRef() - { - await VerifyKeywordAsync( + public Task TestAfterRef() + => VerifyKeywordAsync( """ class C { void Goo(ref $$ """); - } [Fact] - public async Task TestAfterOut() - { - await VerifyKeywordAsync( + public Task TestAfterOut() + => VerifyKeywordAsync( """ class C { void Goo(out $$ """); - } [Fact] - public async Task TestAfterLambdaRef() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaRef() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (ref $$ """); - } [Fact] - public async Task TestAfterLambdaOut() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaOut() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (out $$ """); - } [Fact] - public async Task TestAfterParams() - { - await VerifyKeywordAsync( + public Task TestAfterParams() + => VerifyKeywordAsync( """ class C { void Goo(params $$ """); - } [Fact] - public async Task TestInImplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInImplicitOperator() + => VerifyKeywordAsync( """ class C { public static implicit operator $$ """); - } [Fact] - public async Task TestInExplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInExplicitOperator() + => VerifyKeywordAsync( """ class C { public static explicit operator $$ """); - } [Fact] - public async Task TestAfterIndexerBracket() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracket() + => VerifyKeywordAsync( """ class C { int this[$$ """); - } [Fact] - public async Task TestAfterIndexerBracketComma() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracketComma() + => VerifyKeywordAsync( """ class C { int this[int i, $$ """); - } [Fact] - public async Task TestAfterNewInExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterNewInExpression() + => VerifyKeywordAsync(AddInsideMethod( @"new $$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInTypeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInTypeOf() + => VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInDefault() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDefault() + => VerifyKeywordAsync(AddInsideMethod( @"default($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInSizeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInSizeOf() + => VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -726,12 +563,10 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] - public async Task TestInCrefContext() - { - await VerifyKeywordAsync(""" + public Task TestInCrefContext() + => VerifyKeywordAsync(""" class Program { /// @@ -741,16 +576,13 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] - public async Task TestInCrefContextNotAfterDot() - { - await VerifyAbsenceAsync(""" + public Task TestInCrefContextNotAfterDot() + => VerifyAbsenceAsync(""" /// class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] public async Task TestNotAfterAsync() @@ -761,19 +593,16 @@ public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1468")] - public async Task TestNotInCrefTypeParameter() - { - await VerifyAbsenceAsync(""" + public Task TestNotInCrefTypeParameter() + => VerifyAbsenceAsync(""" using System; /// class C { } """); - } [Fact] - public async Task Preselection() - { - await VerifyKeywordAsync(""" + public Task Preselection() + => VerifyKeywordAsync(""" class Program { static void Main(string[] args) @@ -783,23 +612,19 @@ static void Main(string[] args) static void Helper(int x) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinType() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinType() + => VerifyKeywordAsync(""" class Program { ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinMember() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinMember() + => VerifyKeywordAsync(""" class Program { void Method() @@ -808,82 +633,66 @@ void Method() } } """); - } [Fact] - public async Task TestInFunctionPointerType() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerType() + => VerifyKeywordAsync(""" class C { delegate*<$$ """); - } [Fact] - public async Task TestInFunctionPointerTypeAfterComma() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerTypeAfterComma() + => VerifyKeywordAsync(""" class C { delegate* VerifyKeywordAsync(""" class C { delegate* VerifyAbsenceAsync(""" class C { delegate*$$ """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/53585")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithoutAsync))] - public async Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) - { - await VerifyKeywordAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) + => VerifyKeywordAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithAsync))] - public async Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) - { - await VerifyAbsenceAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) + => VerifyAbsenceAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64585")] - public async Task TestAfterRequired() - { - await VerifyKeywordAsync(""" + public Task TestAfterRequired() + => VerifyKeywordAsync(""" class C { required $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefAtTopLevel1() + => VerifyKeywordAsync( @"ref $$"); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [CombinatorialData] @@ -904,209 +713,177 @@ await VerifyAbsenceAsync( } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefReadonlyAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyAtTopLevel1() + => VerifyKeywordAsync( @"ref readonly $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { readonly $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref readonly $$ } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref $$ -}}"); - } + public Task TestAfterRefInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - readonly $$ -}}"); - } + public Task TestAfterReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + readonly $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref readonly $$ -}}"); - } + public Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref readonly $$ + } + """); #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ManagedKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ManagedKeywordRecommenderTests.cs index 817d75c459531..0144a1d6539a6 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ManagedKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ManagedKeywordRecommenderTests.cs @@ -12,24 +12,20 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ManagedKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestInFunctionPointerDeclaration() - { - await VerifyKeywordAsync( + public Task TestInFunctionPointerDeclaration() + => VerifyKeywordAsync( """ class Test { unsafe void N() { delegate* $$ """); - } [Fact] - public async Task TestInFunctionPointerDeclarationTouchingAsterisk() - { - await VerifyKeywordAsync( + public Task TestInFunctionPointerDeclarationTouchingAsterisk() + => VerifyKeywordAsync( """ class Test { unsafe void N() { delegate*$$ """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/MethodKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/MethodKeywordRecommenderTests.cs index d3564a3544a7e..baf1da186cf60 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/MethodKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/MethodKeywordRecommenderTests.cs @@ -13,100 +13,79 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class MethodKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInAttributeInsideClass() - { - await VerifyKeywordAsync( + public Task TestInAttributeInsideClass() + => VerifyKeywordAsync( """ class C { [$$ """); - } [Fact] - public async Task TestInAttributeAfterAttributeInsideClass() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterAttributeInsideClass() + => VerifyKeywordAsync( """ class C { [Goo] [$$ """); - } [Fact] - public async Task TestInAttributeAfterMethod() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() { } [$$ """); - } [Fact] - public async Task TestInAttributeAfterProperty() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterProperty() + => VerifyKeywordAsync( """ class C { int Goo { @@ -114,150 +93,120 @@ int Goo { } [$$ """); - } [Fact] - public async Task TestInAttributeAfterField() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterField() + => VerifyKeywordAsync( """ class C { int Goo; [$$ """); - } [Fact] - public async Task TestInAttributeAfterEvent() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterEvent() + => VerifyKeywordAsync( """ class C { event Action Goo; [$$ """); - } [Fact] - public async Task TestNotInOuterAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInOuterAttribute() + => VerifyAbsenceAsync( @"[$$"); - } [Fact] - public async Task TestNotInParameterAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInParameterAttribute() + => VerifyAbsenceAsync( """ class C { void Goo([$$ """); - } [Fact] - public async Task TestInPropertyAttribute1() - { - await VerifyKeywordAsync( + public Task TestInPropertyAttribute1() + => VerifyKeywordAsync( """ class C { int Goo { [$$ """); - } [Fact] - public async Task TestInPropertyAttribute2() - { - await VerifyKeywordAsync( + public Task TestInPropertyAttribute2() + => VerifyKeywordAsync( """ class C { int Goo { get { } [$$ """); - } [Fact] - public async Task TestInEventAttribute1() - { - await VerifyKeywordAsync( + public Task TestInEventAttribute1() + => VerifyKeywordAsync( """ class C { event Action Goo { [$$ """); - } [Fact] - public async Task TestInEventAttribute2() - { - await VerifyKeywordAsync( + public Task TestInEventAttribute2() + => VerifyKeywordAsync( """ class C { event Action Goo { add { } [$$ """); - } [Fact] - public async Task TestNotInTypeParameters() - { - await VerifyAbsenceAsync( + public Task TestNotInTypeParameters() + => VerifyAbsenceAsync( @"class C<[$$"); - } [Fact] - public async Task TestInInterface() - { - await VerifyKeywordAsync( + public Task TestInInterface() + => VerifyKeywordAsync( """ interface I { [$$ """); - } [Fact] - public async Task TestInStruct() - { - await VerifyKeywordAsync( + public Task TestInStruct() + => VerifyKeywordAsync( """ struct S { [$$ """); - } [Fact] - public async Task TestNotInEnum() - { - await VerifyAbsenceAsync( + public Task TestNotInEnum() + => VerifyAbsenceAsync( """ enum E { [$$ """); - } [Fact] - public async Task TestPrimaryConstructor1() - { - await VerifyKeywordAsync(""" + public Task TestPrimaryConstructor1() + => VerifyKeywordAsync(""" [$$ class C() { } """); - } [Fact] - public async Task TestPrimaryConstructor2() - { - await VerifyKeywordAsync(""" + public Task TestPrimaryConstructor2() + => VerifyKeywordAsync(""" [$$ struct C() { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70077")] - public async Task TestLocalFunction() - { - await VerifyKeywordAsync(""" + public Task TestLocalFunction() + => VerifyKeywordAsync(""" class C { void M() @@ -269,12 +218,10 @@ void F() } } """); - } [Fact] - public async Task TestWithinExtension1() - { - await VerifyAbsenceAsync( + public Task TestWithinExtension1() + => VerifyAbsenceAsync( """ static class C { @@ -284,12 +231,10 @@ static class C } } """, CSharpNextParseOptions); - } [Fact] - public async Task TestWithinExtension2() - { - await VerifyKeywordAsync( + public Task TestWithinExtension2() + => VerifyKeywordAsync( """ static class C { @@ -299,7 +244,6 @@ static class C } } """, - CSharpNextParseOptions, - CSharpNextScriptParseOptions); - } + CSharpNextParseOptions, + CSharpNextScriptParseOptions); } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ModuleKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ModuleKeywordRecommenderTests.cs index c186f295008c5..f2d6f764a414c 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ModuleKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ModuleKeywordRecommenderTests.cs @@ -12,100 +12,79 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ModuleKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestNotInAttributeInsideClass() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeInsideClass() + => VerifyAbsenceAsync( """ class C { [$$ """); - } [Fact] - public async Task TestNotInAttributeAfterAttributeInsideClass() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeAfterAttributeInsideClass() + => VerifyAbsenceAsync( """ class C { [Goo] [$$ """); - } [Fact] - public async Task TestNotInAttributeAfterMethod() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeAfterMethod() + => VerifyAbsenceAsync( """ class C { void Goo() { } [$$ """); - } [Fact] - public async Task TestNotInAttributeAfterProperty() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeAfterProperty() + => VerifyAbsenceAsync( """ class C { int Goo { @@ -113,128 +92,101 @@ int Goo { } [$$ """); - } [Fact] - public async Task TestNotInAttributeAfterField() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeAfterField() + => VerifyAbsenceAsync( """ class C { int Goo; [$$ """); - } [Fact] - public async Task TestNotInAttributeAfterEvent() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeAfterEvent() + => VerifyAbsenceAsync( """ class C { event Action Goo; [$$ """); - } [Fact] - public async Task TestInOuterAttribute() - { - await VerifyKeywordAsync( + public Task TestInOuterAttribute() + => VerifyKeywordAsync( @"[$$"); - } [Fact] - public async Task TestNotInOuterAttributeInNamespace() - { - await VerifyAbsenceAsync( + public Task TestNotInOuterAttributeInNamespace() + => VerifyAbsenceAsync( """ namespace Goo { [$$ """); - } [Fact] - public async Task TestNotInParameterAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInParameterAttribute() + => VerifyAbsenceAsync( """ class C { void Goo([$$ """); - } [Fact] - public async Task TestNotInPropertyAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAttribute() + => VerifyAbsenceAsync( """ class C { int Goo { [$$ """); - } [Fact] - public async Task TestNotInEventAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInEventAttribute() + => VerifyAbsenceAsync( """ class C { event Action Goo { [$$ """); - } [Fact] - public async Task TestNotInClassModuleParameters() - { - await VerifyAbsenceAsync( + public Task TestNotInClassModuleParameters() + => VerifyAbsenceAsync( @"class C<[$$"); - } [Fact] - public async Task TestNotInDelegateModuleParameters() - { - await VerifyAbsenceAsync( + public Task TestNotInDelegateModuleParameters() + => VerifyAbsenceAsync( @"delegate void D<[$$"); - } [Fact] - public async Task TestNotInMethodModuleParameters() - { - await VerifyAbsenceAsync( + public Task TestNotInMethodModuleParameters() + => VerifyAbsenceAsync( """ class C { void M<[$$ """); - } [Fact] - public async Task TestNotInInterface() - { - await VerifyAbsenceAsync( + public Task TestNotInInterface() + => VerifyAbsenceAsync( """ interface I { [$$ """); - } [Fact] - public async Task TestNotInStruct() - { - await VerifyAbsenceAsync( + public Task TestNotInStruct() + => VerifyAbsenceAsync( """ struct S { [$$ """); - } [Fact] - public async Task TestNotInEnum() - { - await VerifyAbsenceAsync( + public Task TestNotInEnum() + => VerifyAbsenceAsync( """ enum E { [$$ """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/NameOfKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/NameOfKeywordRecommenderTests.cs index b82b2841ef6fd..830c0a535dcea 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/NameOfKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/NameOfKeywordRecommenderTests.cs @@ -17,89 +17,70 @@ public async Task TestOfferedInAttributeConstructorArgumentList() => await VerifyKeywordAsync("using System.ComponentModel; [DefaultValue($$ class C { }"); [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestConstMemberInitializer() - { - await VerifyKeywordAsync( + public Task TestConstMemberInitializer() + => VerifyKeywordAsync( """ class E { const string a = $$ } """); - } [Fact] - public async Task TestInMemberInitializer1() - { - await VerifyKeywordAsync( + public Task TestInMemberInitializer1() + => VerifyKeywordAsync( """ class E { int a = $$ } """); - } [Fact] - public async Task TestNotInTypeOf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInTypeOf() + => VerifyAbsenceAsync(AddInsideMethod( @"typeof($$")); - } [Fact] - public async Task TestNotInDefault() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInDefault() + => VerifyAbsenceAsync(AddInsideMethod( @"default($$")); - } [Fact] - public async Task TestNotInSizeOf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInSizeOf() + => VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); - } [Fact] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -107,130 +88,107 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/NamespaceKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/NamespaceKeywordRecommenderTests.cs index 31db792b909ba..7ca3974948991 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/NamespaceKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/NamespaceKeywordRecommenderTests.cs @@ -12,109 +12,86 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class NamespaceKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAtRoot() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAtRoot() + => VerifyKeywordAsync(SourceCodeKind.Regular, @"$$"); - } [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] public async Task TestNotAfterNamespaceKeyword() => await VerifyAbsenceAsync(@"namespace $$"); [Fact] - public async Task TestAfterPreviousNamespace() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterPreviousNamespace() + => VerifyKeywordAsync(SourceCodeKind.Regular, """ namespace N {} $$ """); - } [Fact] - public async Task TestNotAfterPreviousFileScopedNamespace() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotAfterPreviousFileScopedNamespace() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ namespace N; $$ """); - } [Fact] - public async Task TestNotAfterUsingInFileScopedNamespace() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotAfterUsingInFileScopedNamespace() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ namespace N; using U; $$ """); - } [Fact] - public async Task TestAfterUsingInNamespace() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterUsingInNamespace() + => VerifyKeywordAsync(SourceCodeKind.Regular, """ namespace N { @@ -122,53 +99,43 @@ namespace N $$ } """); - } [Fact] - public async Task TestAfterPreviousNamespace_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestAfterPreviousNamespace_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ namespace N {} $$ """); - } [Fact] - public async Task TestAfterExtern() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterExtern() + => VerifyKeywordAsync(SourceCodeKind.Regular, """ extern alias goo; $$ """); - } [Fact] - public async Task TestAfterExtern_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestAfterExtern_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ extern alias goo; $$ """); - } [Fact] - public async Task TestNotAfterExternInFileScopedNamespace() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotAfterExternInFileScopedNamespace() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ namespace N; extern alias A; $$ """); - } [Fact] - public async Task TestAfterExternInNamespace() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterExternInNamespace() + => VerifyKeywordAsync(SourceCodeKind.Regular, """ namespace N { @@ -176,348 +143,280 @@ namespace N $$ } """); - } [Fact] - public async Task TestAfterUsing() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterUsing() + => VerifyKeywordAsync(SourceCodeKind.Regular, """ using Goo; $$ """); - } [Fact] - public async Task TestAfterGlobalUsing() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterGlobalUsing() + => VerifyKeywordAsync(SourceCodeKind.Regular, """ global using Goo; $$ """); - } [Fact] - public async Task TestAfterUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestAfterUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ using Goo; $$ """); - } [Fact] - public async Task TestAfterGlobalUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestAfterGlobalUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ global using Goo; $$ """); - } [Fact] - public async Task TestAfterUsingAlias() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterUsingAlias() + => VerifyKeywordAsync(SourceCodeKind.Regular, """ using Goo = Bar; $$ """); - } [Fact] - public async Task TestAfterUsingAlias_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestAfterUsingAlias_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ using Goo = Bar; $$ """); - } [Fact] - public async Task TestAfterGlobalUsingAlias() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterGlobalUsingAlias() + => VerifyKeywordAsync(SourceCodeKind.Regular, """ global using Goo = Bar; $$ """); - } [Fact] - public async Task TestAfterGlobalUsingAlias_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestAfterGlobalUsingAlias_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ global using Goo = Bar; $$ """); - } [Fact] - public async Task TestAfterClassDeclaration() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterClassDeclaration() + => VerifyKeywordAsync(SourceCodeKind.Regular, """ class C {} $$ """); - } [Fact] - public async Task TestAfterClassDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestAfterClassDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C {} $$ """); - } [Fact] - public async Task TestAfterDelegateDeclaration() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterDelegateDeclaration() + => VerifyKeywordAsync(SourceCodeKind.Regular, """ delegate void D(); $$ """); - } [Fact] - public async Task TestAfterDelegateDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestAfterDelegateDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ delegate void D(); $$ """); - } [Fact] - public async Task TestNotAfterNestedDelegateDeclaration() - { - await VerifyAbsenceAsync( + public Task TestNotAfterNestedDelegateDeclaration() + => VerifyAbsenceAsync( """ class C { delegate void D(); $$ """); - } [Fact] - public async Task TestNotAfterNestedMember() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedMember() + => VerifyAbsenceAsync(""" class A { class C {} $$ """); - } [Fact] - public async Task TestInsideNamespace() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestInsideNamespace() + => VerifyKeywordAsync(SourceCodeKind.Regular, """ namespace N { $$ """); - } [Fact] - public async Task TestInsideNamespace_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestInsideNamespace_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ namespace N { $$ """); - } [Fact] - public async Task TestNotAfterNamespaceKeyword_InsideNamespace() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNamespaceKeyword_InsideNamespace() + => VerifyAbsenceAsync(""" namespace N { namespace $$ """); - } [Fact] - public async Task TestAfterPreviousNamespace_InsideNamespace() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterPreviousNamespace_InsideNamespace() + => VerifyKeywordAsync(SourceCodeKind.Regular, """ namespace N { namespace N1 {} $$ """); - } [Fact] - public async Task TestAfterPreviousNamespace_InsideNamespace_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestAfterPreviousNamespace_InsideNamespace_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ namespace N { namespace N1 {} $$ """); - } [Fact] - public async Task TestNotBeforeUsing_InsideNamespace() - { - await VerifyAbsenceAsync(""" + public Task TestNotBeforeUsing_InsideNamespace() + => VerifyAbsenceAsync(""" namespace N { $$ using Goo; """); - } [Fact] - public async Task TestAfterMember_InsideNamespace() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterMember_InsideNamespace() + => VerifyKeywordAsync(SourceCodeKind.Regular, """ namespace N { class C {} $$ """); - } [Fact] - public async Task TestAfterMember_InsideNamespace_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestAfterMember_InsideNamespace_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ namespace N { class C {} $$ """); - } [Fact] - public async Task TestNotAfterNestedMember_InsideNamespace() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedMember_InsideNamespace() + => VerifyAbsenceAsync(""" namespace N { class A { class C {} $$ """); - } [Fact] - public async Task TestNotBeforeExtern() - { - await VerifyAbsenceAsync(""" + public Task TestNotBeforeExtern() + => VerifyAbsenceAsync(""" $$ extern alias Goo; """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync(""" + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync(""" $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync(""" + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync(""" $$ global using Goo; """); - } [Fact] - public async Task TestNotBetweenUsings() - { - await VerifyAbsenceAsync( + public Task TestNotBetweenUsings() + => VerifyAbsenceAsync( """ using Goo; $$ using Bar; """); - } [Fact] - public async Task TestNotBetweenGlobalUsings_01() - { - await VerifyAbsenceAsync( + public Task TestNotBetweenGlobalUsings_01() + => VerifyAbsenceAsync( """ global using Goo; $$ using Bar; """); - } [Fact] - public async Task TestNotBetweenGlobalUsings_02() - { - await VerifyAbsenceAsync( + public Task TestNotBetweenGlobalUsings_02() + => VerifyAbsenceAsync( """ global using Goo; $$ global using Bar; """); - } [Fact] - public async Task TestAfterGlobalAttribute() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterGlobalAttribute() + => VerifyKeywordAsync(SourceCodeKind.Regular, """ [assembly: Goo] $$ """); - } [Fact] - public async Task TestAfterGlobalAttribute_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestAfterGlobalAttribute_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ [assembly: Goo] $$ """); - } [Fact] - public async Task TestNotAfterAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotAfterAttribute() + => VerifyAbsenceAsync( """ [Goo] $$ """); - } [Fact] - public async Task TestNotAfterNestedAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotAfterNestedAttribute() + => VerifyAbsenceAsync( """ class C { [Goo] $$ """); - } [Fact] - public async Task TestAfterRegion() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterRegion() + => VerifyKeywordAsync(SourceCodeKind.Regular, """ #region EDM Relationship Metadata @@ -527,12 +426,10 @@ await VerifyKeywordAsync(SourceCodeKind.Regular, $$ """); - } [Fact] - public async Task TestAfterRegion_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestAfterRegion_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ #region EDM Relationship Metadata @@ -542,12 +439,10 @@ await VerifyAbsenceAsync(SourceCodeKind.Script, $$ """); - } [Fact] - public async Task TestWithinExtension() - { - await VerifyAbsenceAsync( + public Task TestWithinExtension() + => VerifyAbsenceAsync( """ static class C { @@ -557,5 +452,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/NativeIntegerKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/NativeIntegerKeywordRecommenderTests.cs index c13f4bee4cbfd..a7bf14de2fbc1 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/NativeIntegerKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/NativeIntegerKeywordRecommenderTests.cs @@ -22,160 +22,125 @@ protected NativeIntegerKeywordRecommenderTests() } [Fact] - public async Task TestInLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInClass() - { - await VerifyKeywordAsync( + public Task TestInClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] - public async Task TestInParameterList() - { - await VerifyKeywordAsync( + public Task TestInParameterList() + => VerifyKeywordAsync( """ class C { void F($$ """); - } [Fact] - public async Task TestInLambdaParameterListFirst() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLambdaParameterListFirst() + => VerifyKeywordAsync(AddInsideMethod( @"F(($$")); - } [Fact] - public async Task TestInLambdaParameterListLater() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLambdaParameterListLater() + => VerifyKeywordAsync(AddInsideMethod( @"F((int x, $$")); - } [Fact] - public async Task TestAfterConst() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConst() + => VerifyKeywordAsync(AddInsideMethod( @"const $$")); - } [Fact] - public async Task TestInFixedStatement() - { - await VerifyKeywordAsync( + public Task TestInFixedStatement() + => VerifyKeywordAsync( @"fixed ($$"); - } [Fact] - public async Task TestInRef() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInRef() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$")); - } [Fact] - public async Task TestInMemberType() - { - await VerifyKeywordAsync( + public Task TestInMemberType() + => VerifyKeywordAsync( """ class C { private $$ """); - } [Fact] - public async Task TestInOperatorType() - { - await VerifyKeywordAsync( + public Task TestInOperatorType() + => VerifyKeywordAsync( """ class C { static implicit operator $$ """); - } [Fact] - public async Task TestInEnumUnderlyingType() - { - await VerifyAbsenceAsync( + public Task TestInEnumUnderlyingType() + => VerifyAbsenceAsync( @"enum E : $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TestNotInTypeParameterConstraint_TypeDeclaration1() - { - await VerifyAbsenceAsync( + public Task TestNotInTypeParameterConstraint_TypeDeclaration1() + => VerifyAbsenceAsync( @"class C where T : $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TestInTypeParameterConstraint_TypeDeclaration_WhenNotDirectlyInConstraint1() - { - await VerifyKeywordAsync( + public Task TestInTypeParameterConstraint_TypeDeclaration_WhenNotDirectlyInConstraint1() + => VerifyKeywordAsync( @"class C where T : IList<$$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TestNotInTypeParameterConstraint_TypeDeclaration2() - { - await VerifyAbsenceAsync( + public Task TestNotInTypeParameterConstraint_TypeDeclaration2() + => VerifyAbsenceAsync( """ class C where T : $$ where U : U """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TestInTypeParameterConstraint_TypeDeclaration_WhenNotDirectlyInConstraint2() - { - await VerifyKeywordAsync( + public Task TestInTypeParameterConstraint_TypeDeclaration_WhenNotDirectlyInConstraint2() + => VerifyKeywordAsync( """ class C where T : IList<$$ where U : U """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TestNotInTypeParameterConstraint_MethodDeclaration1() - { - await VerifyAbsenceAsync( + public Task TestNotInTypeParameterConstraint_MethodDeclaration1() + => VerifyAbsenceAsync( """ class C { public void M() where T : $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TestInTypeParameterConstraint_MethodDeclaration_WhenNotDirectlyInConstraint1() - { - await VerifyKeywordAsync( + public Task TestInTypeParameterConstraint_MethodDeclaration_WhenNotDirectlyInConstraint1() + => VerifyKeywordAsync( """ class C { public void M() where T : IList<$$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TestNotInTypeParameterConstraint_MethodDeclaration2() - { - await VerifyAbsenceAsync( + public Task TestNotInTypeParameterConstraint_MethodDeclaration2() + => VerifyAbsenceAsync( """ class C { @@ -183,12 +148,10 @@ public void M() where T : $$ where U : T """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TestNotInTypeParameterConstraint_MethodDeclaration_WhenNotDirectlyInConstraint2() - { - await VerifyKeywordAsync( + public Task TestNotInTypeParameterConstraint_MethodDeclaration_WhenNotDirectlyInConstraint2() + => VerifyKeywordAsync( """ class C { @@ -196,138 +159,104 @@ public void M() where T : IList<$$ where U : T """); - } [Fact] - public async Task TestInExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInExpression() + => VerifyKeywordAsync(AddInsideMethod( @"var v = 1 + $$")); - } [Fact] - public async Task TestInDefault() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDefault() + => VerifyKeywordAsync(AddInsideMethod( @"_ = default($$")); - } [Fact] - public async Task TestInCastType() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType() + => VerifyKeywordAsync(AddInsideMethod( @"var v = (($$")); - } [Fact] - public async Task TestInNew() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInNew() + => VerifyKeywordAsync(AddInsideMethod( @"_ = new $$")); - } [Fact] - public async Task TestAfterAs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterAs() + => VerifyKeywordAsync(AddInsideMethod( """ object x = null; var y = x as $$ """)); - } [Fact] - public async Task TestAfterIs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIs() + => VerifyKeywordAsync(AddInsideMethod( """ object x = null; if (x is $$ """)); - } [Fact] - public async Task TestAfterStackAlloc() - { - await VerifyKeywordAsync( + public Task TestAfterStackAlloc() + => VerifyKeywordAsync( """ class C { nint* p = stackalloc $$ """); - } [Fact] - public async Task TestNotInUsing() - { - await VerifyAbsenceAsync( + public Task TestNotInUsing() + => VerifyAbsenceAsync( @"using $$"); - } [Fact] - public async Task TestInUsingAliasFirst() - { - await VerifyKeywordAsync( + public Task TestInUsingAliasFirst() + => VerifyKeywordAsync( @"using A = $$"); - } [Fact] - public async Task TestInGlobalUsingAliasFirst() - { - await VerifyKeywordAsync( + public Task TestInGlobalUsingAliasFirst() + => VerifyKeywordAsync( @"global using A = $$"); - } [Fact] - public async Task TestInUsingAliasLater() - { - await VerifyKeywordAsync( + public Task TestInUsingAliasLater() + => VerifyKeywordAsync( @"using A = List<$$"); - } [Fact] - public async Task TestInGlobalUsingAliasLater() - { - await VerifyKeywordAsync( + public Task TestInGlobalUsingAliasLater() + => VerifyKeywordAsync( @"global using A = List<$$"); - } [Fact] - public async Task TestInNameOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInNameOf() + => VerifyKeywordAsync(AddInsideMethod( @"_ = nameof($$")); - } [Fact] - public async Task TestInSizeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInSizeOf() + => VerifyKeywordAsync(AddInsideMethod( @"_ = sizeof($$")); - } [Fact] - public async Task TestInCRef() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestInCRef() + => VerifyAbsenceAsync(AddInsideMethod( @"/// VerifyKeywordAsync(""" class Program { ($$ } """); - } [Fact] - public async Task TestInTupleWithinMember() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinMember() + => VerifyKeywordAsync(""" class Program { void Method() @@ -336,119 +265,97 @@ void Method() } } """); - } [Fact] - public async Task TestPatternInSwitch() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestPatternInSwitch() + => VerifyKeywordAsync(AddInsideMethod( """ switch(o) { case $$ } """)); - } [Fact] - public async Task TestInFunctionPointerType() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerType() + => VerifyKeywordAsync(""" class C { delegate*<$$ """); - } [Fact] - public async Task TestInFunctionPointerTypeAfterComma() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerTypeAfterComma() + => VerifyKeywordAsync(""" class C { delegate* VerifyKeywordAsync(""" class C { delegate* VerifyAbsenceAsync(""" class C { async $$ """); - } [Fact] - public async Task TestNotAfterDelegateAsterisk() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterDelegateAsterisk() + => VerifyAbsenceAsync(""" class C { delegate*$$ """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/53585")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithoutAsync))] - public async Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) - { - await VerifyKeywordAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) + => VerifyKeywordAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithAsync))] - public async Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) - { - await VerifyAbsenceAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) + => VerifyAbsenceAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49743")] - public async Task TestNotInPreprocessorDirective() - { - await VerifyAbsenceAsync( + public Task TestNotInPreprocessorDirective() + => VerifyAbsenceAsync( @"#$$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64585")] - public async Task TestAfterRequired() - { - await VerifyKeywordAsync(""" + public Task TestAfterRequired() + => VerifyKeywordAsync(""" class C { required $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70074")] - public async Task TestNotInAttribute1() - { - await VerifyAbsenceAsync(""" + public Task TestNotInAttribute1() + => VerifyAbsenceAsync(""" [$$ class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70074")] - public async Task TestNotInAttribute2() - { - await VerifyAbsenceAsync(""" + public Task TestNotInAttribute2() + => VerifyAbsenceAsync(""" class C { [$$ @@ -457,12 +364,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70074")] - public async Task TestNotInAttribute3() - { - await VerifyAbsenceAsync(""" + public Task TestNotInAttribute3() + => VerifyAbsenceAsync(""" class C { void M() @@ -474,139 +379,115 @@ void L() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68399")] - public async Task TestNotInRecordParameterAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInRecordParameterAttribute() + => VerifyAbsenceAsync( """ record R([$$] int i) { } """); - } #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -616,7 +497,6 @@ static class C } } """, - CSharpNextParseOptions, - CSharpNextScriptParseOptions); - } + CSharpNextParseOptions, + CSharpNextScriptParseOptions); } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/NewKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/NewKeywordRecommenderTests.cs index 75f4fc0c67b6f..9374e0fd4b158 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/NewKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/NewKeywordRecommenderTests.cs @@ -13,824 +13,621 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class NewKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot() - { - await VerifyKeywordAsync( + public Task TestAtRoot() + => VerifyKeywordAsync( @"$$"); - } [Fact] - public async Task TestAfterClass() - { - await VerifyKeywordAsync( + public Task TestAfterClass() + => VerifyKeywordAsync( """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalVariableDeclaration() + => VerifyKeywordAsync( """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Theory, CombinatorialData] - public async Task TestEmptyStatement(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestEmptyStatement(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestAfterNewTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterNewTypeParameterConstraint() + => VerifyKeywordAsync( @"class C where T : $$"); - } [Fact] - public async Task TestAfterTypeParameterConstraint2() - { - await VerifyKeywordAsync( + public Task TestAfterTypeParameterConstraint2() + => VerifyKeywordAsync( """ class C where T : $$ where U : U """); - } [Fact] - public async Task TestAfterMethodTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterMethodTypeParameterConstraint() + => VerifyKeywordAsync( """ class C { void Goo() where T : $$ """); - } [Fact] - public async Task TestAfterMethodTypeParameterConstraint2() - { - await VerifyKeywordAsync( + public Task TestAfterMethodTypeParameterConstraint2() + => VerifyKeywordAsync( """ class C { void Goo() where T : $$ where U : T """); - } [Fact] - public async Task TestAfterClassTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterClassTypeParameterConstraint() + => VerifyKeywordAsync( @"class C where T : class, $$"); - } [Fact] - public async Task TestNotAfterStructTypeParameterConstraint() - { - await VerifyAbsenceAsync( + public Task TestNotAfterStructTypeParameterConstraint() + => VerifyAbsenceAsync( @"class C where T : struct, $$"); - } [Fact] - public async Task TestAfterSimpleTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterSimpleTypeParameterConstraint() + => VerifyKeywordAsync( @"class C where T : IGoo, $$"); - } [Theory, CombinatorialData] - public async Task TestStartOfExpression(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestStartOfExpression(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"var q = $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/34324")] - public async Task TestAfterNullCoalescingAssignment(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterNullCoalescingAssignment(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"q ??= $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInParenthesizedExpression(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInParenthesizedExpression(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"var q = ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestPlusEquals(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestPlusEquals(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"q += $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestMinusEquals(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestMinusEquals(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"q -= $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestTimesEquals(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestTimesEquals(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"q *= $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestDivideEquals(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestDivideEquals(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"q /= $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestModEquals(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestModEquals(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"q %= $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestXorEquals(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestXorEquals(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"q ^= $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAndEquals(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAndEquals(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"q &= $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestOrEquals(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestOrEquals(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"q |= $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestLeftShiftEquals(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestLeftShiftEquals(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"q <<= $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestRightShiftEquals(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestRightShiftEquals(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"q >>= $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterMinus(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterMinus(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"- $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterPlus(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterPlus(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"+ $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterNot(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterNot(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"! $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterTilde(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterTilde(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"~ $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterBinaryTimes(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBinaryTimes(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"a * $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterBinaryDivide(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBinaryDivide(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"a / $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterBinaryMod(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBinaryMod(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"a % $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterBinaryPlus(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBinaryPlus(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"a + $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterBinaryMinus(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBinaryMinus(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"a - $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterBinaryLeftShift(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBinaryLeftShift(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"a << $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterBinaryRightShift(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBinaryRightShift(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"a >> $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterBinaryLessThan(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBinaryLessThan(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"a < $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterBinaryGreaterThan(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBinaryGreaterThan(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"a > $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterEqualsEquals(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterEqualsEquals(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"a == $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterNotEquals(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterNotEquals(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"a != $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterLessThanEquals(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterLessThanEquals(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"a <= $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterGreaterThanEquals(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterGreaterThanEquals(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"a >= $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterNullable(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterNullable(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"a ?? $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterArrayRankSpecifier1(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterArrayRankSpecifier1(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"new int[ $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterArrayRankSpecifier2(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterArrayRankSpecifier2(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"new int[expr, $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterConditional1(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConditional1(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"a ? $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory] [InlineData(false)] [InlineData(true, Skip = "https://github.com/dotnet/roslyn/issues/44443")] - public async Task TestAfterConditional2(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConditional2(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"a ? expr | $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInArgument1(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInArgument1(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"Goo( $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInArgument2(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInArgument2(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"Goo(expr, $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInArgument3(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInArgument3(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"new Goo( $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInArgument4(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInArgument4(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"new Goo(expr, $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterRef(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRef(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"Goo(ref $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterOut(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterOut(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"Goo(out $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestLambda(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestLambda(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"Action a = i => $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInCollectionInitializer1(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionInitializer1(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"new System.Collections.Generic.List() { $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInCollectionInitializer2(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionInitializer2(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"new System.Collections.Generic.List() { expr, $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInForeachIn(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForeachIn(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"foreach (var v in $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInAwaitForeachIn(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInAwaitForeachIn(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"await foreach (var v in $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInFromIn(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFromIn(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"var q = from x in $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInJoinIn(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInJoinIn(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y join a in $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInJoinOn(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInJoinOn(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y join a in b on $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInJoinEquals(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInJoinEquals(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y join a in b on equals $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestWhere(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestWhere(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y where $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestOrderby1(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestOrderby1(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y orderby $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestOrderby2(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestOrderby2(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y orderby a, $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestOrderby3(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestOrderby3(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y orderby a ascending, $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterSelect(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterSelect(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y select $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterGroup(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterGroup(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y group $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterGroupBy(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterGroupBy(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y group expr by $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterReturn(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterReturn(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"return $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterYieldReturn(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterYieldReturn(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"yield return $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestNotAfterAttributeReturn() - { - await VerifyAbsenceAsync( + public Task TestNotAfterAttributeReturn() + => VerifyAbsenceAsync( @"[return $$"); - } [Theory, CombinatorialData] - public async Task TestAfterThrow(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterThrow(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"throw $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInWhile(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInWhile(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"while ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInUsing(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInUsing(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"using ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInAwaitUsing(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInAwaitUsing(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"await using ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInLock(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLock(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"lock ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInIf(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInIf(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"if ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInSwitch(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInSwitch(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"switch ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestAfterExtern() - { - await VerifyKeywordAsync(""" + public Task TestAfterExtern() + => VerifyKeywordAsync(""" extern alias Goo; $$ """); - } [Fact] - public async Task TestAfterUsing() - { - await VerifyKeywordAsync(""" + public Task TestAfterUsing() + => VerifyKeywordAsync(""" using Goo; $$ """); - } [Fact] - public async Task TestAfterGlobalUsing() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalUsing() + => VerifyKeywordAsync( """ global using Goo; $$ """); - } [Fact] - public async Task TestAfterNamespace() - { - await VerifyKeywordAsync(""" + public Task TestAfterNamespace() + => VerifyKeywordAsync(""" namespace N {} $$ """); - } [Fact] - public async Task TestAfterFileScopedNamespace() - { - await VerifyAbsenceAsync( + public Task TestAfterFileScopedNamespace() + => VerifyAbsenceAsync( """ namespace N; $$ """); - } [Fact] - public async Task TestAfterDelegateDeclaration() - { - await VerifyKeywordAsync(""" + public Task TestAfterDelegateDeclaration() + => VerifyKeywordAsync(""" delegate void Goo(); $$ """); - } [Fact] - public async Task TestAfterMethodInClass() - { - await VerifyKeywordAsync( + public Task TestAfterMethodInClass() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterFieldInClass() - { - await VerifyKeywordAsync( + public Task TestAfterFieldInClass() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterPropertyInClass() - { - await VerifyKeywordAsync( + public Task TestAfterPropertyInClass() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ global using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeGlobalUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeGlobalUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ global using Goo; """); - } [Fact] - public async Task TestAfterAssemblyAttribute() - { - await VerifyKeywordAsync(""" + public Task TestAfterAssemblyAttribute() + => VerifyKeywordAsync(""" [assembly: goo] $$ """); - } [Fact] - public async Task TestAfterRootAttribute() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, """ + public Task TestAfterRootAttribute() + => VerifyKeywordAsync(SourceCodeKind.Regular, """ [goo] $$ """); - } [Fact] - public async Task TestAfterRootAttribute_Interactive() - { - // The global function could be hiding a member inherited from System.Object. - await VerifyKeywordAsync(SourceCodeKind.Script, """ + public Task TestAfterRootAttribute_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ [goo] $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync( + public Task TestInsideInterface() + => VerifyKeywordAsync( """ interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() @@ -881,18 +678,14 @@ public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact] - public async Task TestNotAfterPrivate() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotAfterPrivate() + => VerifyAbsenceAsync(SourceCodeKind.Regular, @"private $$"); - } [Fact] - public async Task TestAfterPrivate_Script() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterPrivate_Script() + => VerifyKeywordAsync(SourceCodeKind.Script, @"private $$"); - } [Fact] public async Task TestNotAfterSealed() @@ -907,165 +700,130 @@ public async Task TestAfterStatic_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"static $$"); [Fact] - public async Task TestAfterNestedStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStatic() + => VerifyKeywordAsync( """ class C { static $$ """); - } [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] - public async Task TestAfterNestedPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPrivate() + => VerifyKeywordAsync( """ class C { private $$ """); - } [Fact] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] - public async Task TestAfterNestedVirtual() - { - await VerifyKeywordAsync( + public Task TestAfterNestedVirtual() + => VerifyKeywordAsync( """ class C { virtual $$ """); - } [Fact] - public async Task TestNotAfterNestedNew() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedNew() + => VerifyAbsenceAsync(""" class C { new $$ """); - } [Fact] - public async Task TestNotAfterNestedOverride() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedOverride() + => VerifyAbsenceAsync(""" class C { override $$ """); - } [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] - public async Task TestNotInProperty() - { - await VerifyAbsenceAsync( + public Task TestNotInProperty() + => VerifyAbsenceAsync( """ class C { int Goo { $$ """); - } [Fact] - public async Task TestNotInPropertyAfterAccessor() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAfterAccessor() + => VerifyAbsenceAsync( """ class C { int Goo { get; $$ """); - } [Fact] - public async Task TestNotInPropertyAfterAccessibility() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAfterAccessibility() + => VerifyAbsenceAsync( """ class C { int Goo { get; protected $$ """); - } [Fact] - public async Task TestNotInPropertyAfterInternal() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAfterInternal() + => VerifyAbsenceAsync( """ class C { int Goo { get; internal $$ """); - } [Fact] - public async Task TestAfterCastType1() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterCastType1() + => VerifyKeywordAsync(AddInsideMethod( @"return (LeafSegment)$$")); - } [Fact] - public async Task TestAfterCastType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterCastType2() + => VerifyKeywordAsync(AddInsideMethod( @"return (LeafSegment)(object)$$")); - } [Fact] - public async Task TestNotAfterParenthesizedExpression() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterParenthesizedExpression() + => VerifyAbsenceAsync(AddInsideMethod( @"return (a + b)$$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] - public async Task TestInConstMemberInitializer1() - { - // User could say "new int()" here. - await VerifyKeywordAsync( + public Task TestInConstMemberInitializer1() + => VerifyKeywordAsync( """ class E { const int a = $$ } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] - public async Task TestInConstLocalInitializer1() - { - // User could say "new int()" here. - await VerifyKeywordAsync( + public Task TestInConstLocalInitializer1() + => VerifyKeywordAsync( """ class E { void Goo() { @@ -1073,44 +831,34 @@ void Goo() { } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] - public async Task TestInMemberInitializer1() - { - await VerifyKeywordAsync( + public Task TestInMemberInitializer1() + => VerifyKeywordAsync( """ class E { int a = $$ } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInTypeOf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInTypeOf() + => VerifyAbsenceAsync(AddInsideMethod( @"typeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInDefault() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInDefault() + => VerifyAbsenceAsync(AddInsideMethod( @"default($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInSizeOf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInSizeOf() + => VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -1118,218 +866,177 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544486")] - public async Task TestInsideInitOfConstFieldDecl() - { - // user could say "new int()" here. - await VerifyKeywordAsync( + public Task TestInsideInitOfConstFieldDecl() + => VerifyKeywordAsync( """ class C { const int value = $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544998")] - public async Task TestInsideStructParameterInitializer() - { - await VerifyKeywordAsync( + public Task TestInsideStructParameterInitializer() + => VerifyKeywordAsync( """ struct C { void M(C c = $$ } """); - } [Fact] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } [Fact] - public async Task TestInRawStringInterpolation_SingleLine() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInRawStringInterpolation_SingleLine() + => VerifyKeywordAsync(AddInsideMethod( """" var x = $"""{$$}""" """")); - } [Fact] - public async Task TestInRawStringInterpolation_SingleLine_MultiBrace() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInRawStringInterpolation_SingleLine_MultiBrace() + => VerifyKeywordAsync(AddInsideMethod( """" var x = ${|#0:|}$"""{{$$}}""" """")); - } [Fact] - public async Task TestInRawStringInterpolation_SingleLineIncomplete() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInRawStringInterpolation_SingleLineIncomplete() + => VerifyKeywordAsync(AddInsideMethod( @"var x = $""""""{$$")); - } [Fact] - public async Task TestInRawStringInterpolation_MultiLine() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInRawStringInterpolation_MultiLine() + => VerifyKeywordAsync(AddInsideMethod( """" var x = $""" {$$} """ """")); - } [Fact] - public async Task TestInRawStringInterpolation_MultiLine_MultiBrace() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInRawStringInterpolation_MultiLine_MultiBrace() + => VerifyKeywordAsync(AddInsideMethod( """" var x = ${|#0:|}$""" {{$$}} """ """")); - } [Fact] - public async Task TestInRawStringInterpolation_MultiLineIncomplete() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInRawStringInterpolation_MultiLineIncomplete() + => VerifyKeywordAsync(AddInsideMethod( """" var x = $""" {$$ """")); - } #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion [Fact] - public async Task TestWithinExtension() - { - await VerifyAbsenceAsync( + public Task TestWithinExtension() + => VerifyAbsenceAsync( """ static class C { @@ -1341,5 +1048,4 @@ static class C """, CSharpNextParseOptions, CSharpNextScriptParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/NotKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/NotKeywordRecommenderTests.cs index 0a34df1d7c64e..84ae0d28a58e1 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/NotKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/NotKeywordRecommenderTests.cs @@ -17,72 +17,53 @@ public sealed class NotKeywordRecommenderTests : KeywordRecommenderTests """; [Fact] - public async Task TestAfterIsKeyword() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAfterIsKeyword() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is $$")); - } [Fact] - public async Task TestAfterNotKeyword() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAfterNotKeyword() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is not $$")); - } [Fact] - public async Task TestAfterNotKeywordAndOpenParen() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAfterNotKeywordAndOpenParen() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is not ($$")); - } [Fact] - public async Task TestAfterAndKeyword_IntExpression() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAfterAndKeyword_IntExpression() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is 1 and $$")); - } [Fact] - public async Task TestAfterAndKeyword_StrExpression() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAfterAndKeyword_StrExpression() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is ""str"" and $$")); - } [Fact] - public async Task TestAfterAndKeyword_RelationalExpression() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAfterAndKeyword_RelationalExpression() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is <= 1 and $$")); - } [Fact] - public async Task TestAfterOpenParen() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAfterOpenParen() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is ($$")); - } [Fact] - public async Task TestAfterMultipleOpenParen() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAfterMultipleOpenParen() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is ((($$")); - } [Fact] - public async Task TestInMiddleofCompletePattern() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestInMiddleofCompletePattern() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is $$ 1 or 2)")); - } [Fact] - public async Task TestInMiddleOfCompleteQualifiedPattern() - { - await VerifyKeywordAsync( + public Task TestInMiddleOfCompleteQualifiedPattern() + => VerifyKeywordAsync( """ namespace N { @@ -97,12 +78,10 @@ void M() } } """); - } [Fact] - public async Task TestInMiddleOfCompleteQualifiedPattern_List() - { - await VerifyKeywordAsync( + public Task TestInMiddleOfCompleteQualifiedPattern_List() + => VerifyKeywordAsync( """ namespace N { @@ -117,128 +96,104 @@ void M() } } """); - } [Fact] - public async Task TestInMiddleofCompletePattern_MultipleParens() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestInMiddleofCompletePattern_MultipleParens() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is ((($$ 1 or 2))))")); - } [Fact] - public async Task TestInMiddleofCompletePattern_EmptyListPattern() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestInMiddleofCompletePattern_EmptyListPattern() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is ($$ []) and var x)")); - } [Fact] - public async Task TestAtBeginningOfSwitchExpression() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAtBeginningOfSwitchExpression() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + """ var result = e switch { $$ """)); - } [Fact] - public async Task TestAtBeginningOfSwitchStatement() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAtBeginningOfSwitchStatement() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + """ switch (e) { case $$ """)); - } [Fact] - public async Task TestInMiddleOfSwitchExpression() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestInMiddleOfSwitchExpression() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + """ var result = e switch { 1 => 2, $$ """)); - } [Fact] - public async Task TestInMiddleOfSwitchStatement() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestInMiddleOfSwitchStatement() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + """ switch (e) { case 1: case $$ """)); - } [Fact] - public async Task TestAtBeginningOfSwitchExpression_AfterOpenParen() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAtBeginningOfSwitchExpression_AfterOpenParen() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + """ var result = e switch { ($$ """)); - } [Fact] - public async Task TestInMiddleOfSwitchExpression_AfterOpenParen() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestInMiddleOfSwitchExpression_AfterOpenParen() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + """ var result = e switch { 1 => 2, ($$ """)); - } [Fact] - public async Task TestInMiddleOfSwitchExpression_ComplexCase() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestInMiddleOfSwitchExpression_ComplexCase() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + """ var result = e switch { 1 and ($$ """)); - } [Fact] - public async Task TestAtBeginningOfSwitchStatement_AfterOpenParen() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAtBeginningOfSwitchStatement_AfterOpenParen() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + """ switch (e) { case ($$ """)); - } [Fact] - public async Task TestAtBeginningOfSwitchStatement_AfterOpenParen_CompleteStatement() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAtBeginningOfSwitchStatement_AfterOpenParen_CompleteStatement() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + """ switch (e) { case ($$ 1) """)); - } [Fact] - public async Task TestInsideSubpattern() - { - await VerifyKeywordAsync( + public Task TestInsideSubpattern() + => VerifyKeywordAsync( """ class C { @@ -248,12 +203,10 @@ void M(C test) { if (test is { P: $$ """); - } [Fact] - public async Task TestInsideSubpattern_ExtendedProperty() - { - await VerifyKeywordAsync( + public Task TestInsideSubpattern_ExtendedProperty() + => VerifyKeywordAsync( """ class C { @@ -264,12 +217,10 @@ void M(C test) { if (test is { P.P2: $$ """); - } [Fact] - public async Task TestInsideSubpattern_AfterOpenParen() - { - await VerifyKeywordAsync( + public Task TestInsideSubpattern_AfterOpenParen() + => VerifyKeywordAsync( """ class C { @@ -279,12 +230,10 @@ void M(C test) { if (test is { P: ($$ """); - } [Fact] - public async Task TestInsideSubpattern_AfterOpenParen_Complex() - { - await VerifyKeywordAsync( + public Task TestInsideSubpattern_AfterOpenParen_Complex() + => VerifyKeywordAsync( """ class C { @@ -294,44 +243,35 @@ void M(C test) { if (test is { P: (1 or $$ """); - } [Fact] - public async Task TestMissingAfterConstant() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAfterConstant() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is 1 $$")); - } [Fact] - public async Task TestMissingAfterMultipleConstants() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAfterMultipleConstants() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is 1 or 2 $$")); - } [Fact] - public async Task TestAfterType() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestAfterType() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is int $$")); - } [Fact] - public async Task TestAfterRelationalOperator() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestAfterRelationalOperator() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is >= 0 $$")); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/61184")] [InlineData("and")] [InlineData("or")] - public async Task TestAfterIdentifierPatternKeyword(string precedingKeyword) - { - await VerifyKeywordAsync(InitializeObjectE + -$@"if (e is Test.TestValue {precedingKeyword} $$) + public Task TestAfterIdentifierPatternKeyword(string precedingKeyword) + => VerifyKeywordAsync(InitializeObjectE + + $$""" + if (e is Test.TestValue {{precedingKeyword}} $$) -enum Test {{ TestValue }}"); - } + enum Test { TestValue } + """); } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/NotnullKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/NotnullKeywordRecommenderTests.cs index 3d41af1bd975e..7ac5283b2d4e3 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/NotnullKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/NotnullKeywordRecommenderTests.cs @@ -23,233 +23,179 @@ public NotNullKeywordRecommenderTests() } [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotAfterName_Type() - { - await VerifyAbsenceAsync( + public Task TestNotAfterName_Type() + => VerifyAbsenceAsync( @"class Test $$"); - } [Fact] - public async Task TestNotAfterWhereClause_Type() - { - await VerifyAbsenceAsync( + public Task TestNotAfterWhereClause_Type() + => VerifyAbsenceAsync( @"class Test where $$"); - } [Fact] - public async Task TestNotAfterWhereClauseType_Type() - { - await VerifyAbsenceAsync( + public Task TestNotAfterWhereClauseType_Type() + => VerifyAbsenceAsync( @"class Test where T $$"); - } [Fact] - public async Task TestAfterWhereClauseColon_Type() - { - await VerifyKeywordAsync( + public Task TestAfterWhereClauseColon_Type() + => VerifyKeywordAsync( @"class Test where T : $$"); - } [Fact] - public async Task TestNotAfterTypeConstraint_Type() - { - await VerifyAbsenceAsync( + public Task TestNotAfterTypeConstraint_Type() + => VerifyAbsenceAsync( @"class Test where T : I $$"); - } [Fact] - public async Task TestAfterTypeConstraintComma_Type() - { - await VerifyKeywordAsync( + public Task TestAfterTypeConstraintComma_Type() + => VerifyKeywordAsync( @"class Test where T : I, $$"); - } [Fact] - public async Task TestNotAfterName_Method() - { - await VerifyAbsenceAsync( + public Task TestNotAfterName_Method() + => VerifyAbsenceAsync( """ class Test { void M $$ """); - } [Fact] - public async Task TestNotAfterWhereClause_Method() - { - await VerifyAbsenceAsync( + public Task TestNotAfterWhereClause_Method() + => VerifyAbsenceAsync( """ class Test { void M where $$ """); - } [Fact] - public async Task TestNotAfterWhereClauseType_Method() - { - await VerifyAbsenceAsync( + public Task TestNotAfterWhereClauseType_Method() + => VerifyAbsenceAsync( """ class Test { void M where T $$ """); - } [Fact] - public async Task TestAfterWhereClauseColon_Method() - { - await VerifyKeywordAsync( + public Task TestAfterWhereClauseColon_Method() + => VerifyKeywordAsync( """ class Test { void M where T : $$ """); - } [Fact] - public async Task TestNotAfterTypeConstraint_Method() - { - await VerifyAbsenceAsync( + public Task TestNotAfterTypeConstraint_Method() + => VerifyAbsenceAsync( """ class Test { void M where T : I $$ """); - } [Fact] - public async Task TestAfterTypeConstraintComma_Method() - { - await VerifyKeywordAsync( + public Task TestAfterTypeConstraintComma_Method() + => VerifyKeywordAsync( """ class Test { void M where T : I, $$ """); - } [Fact] - public async Task TestNotAfterName_Delegate() - { - await VerifyAbsenceAsync( + public Task TestNotAfterName_Delegate() + => VerifyAbsenceAsync( @"delegate void D $$"); - } [Fact] - public async Task TestNotAfterWhereClause_Delegate() - { - await VerifyAbsenceAsync( + public Task TestNotAfterWhereClause_Delegate() + => VerifyAbsenceAsync( @"delegate void D() where $$"); - } [Fact] - public async Task TestNotAfterWhereClauseType_Delegate() - { - await VerifyAbsenceAsync( + public Task TestNotAfterWhereClauseType_Delegate() + => VerifyAbsenceAsync( @"delegate void D() where T $$"); - } [Fact] - public async Task TestAfterWhereClauseColon_Delegate() - { - await VerifyKeywordAsync( + public Task TestAfterWhereClauseColon_Delegate() + => VerifyKeywordAsync( @"delegate void D() where T : $$"); - } [Fact] - public async Task TestNotAfterTypeConstraint_Delegate() - { - await VerifyAbsenceAsync( + public Task TestNotAfterTypeConstraint_Delegate() + => VerifyAbsenceAsync( @"delegate void D() where T : I $$"); - } [Fact] - public async Task TestAfterTypeConstraintComma_Delegate() - { - await VerifyKeywordAsync( + public Task TestAfterTypeConstraintComma_Delegate() + => VerifyKeywordAsync( @"delegate void D() where T : I, $$"); - } [Fact] - public async Task TestNotAfterName_LocalFunction() - { - await VerifyAbsenceAsync( + public Task TestNotAfterName_LocalFunction() + => VerifyAbsenceAsync( """ class Test { void N() { void M $$ """); - } [Fact] - public async Task TestNotAfterWhereClause_LocalFunction() - { - await VerifyAbsenceAsync( + public Task TestNotAfterWhereClause_LocalFunction() + => VerifyAbsenceAsync( """ class Test { void N() { void M where $$ """); - } [Fact] - public async Task TestNotAfterWhereClauseType_LocalFunction() - { - await VerifyAbsenceAsync( + public Task TestNotAfterWhereClauseType_LocalFunction() + => VerifyAbsenceAsync( """ class Test { void N() { void M where T $$ """); - } [Fact] - public async Task TestAfterWhereClauseColon_LocalFunction() - { - await VerifyKeywordAsync( + public Task TestAfterWhereClauseColon_LocalFunction() + => VerifyKeywordAsync( """ class Test { void N() { void M where T : $$ """); - } [Fact] - public async Task TestNotAfterTypeConstraint_LocalFunction() - { - await VerifyAbsenceAsync( + public Task TestNotAfterTypeConstraint_LocalFunction() + => VerifyAbsenceAsync( """ class Test { void N() { void M where T : I $$ """); - } [Fact] - public async Task TestAfterTypeConstraintComma_LocalFunction() - { - await VerifyKeywordAsync( + public Task TestAfterTypeConstraintComma_LocalFunction() + => VerifyKeywordAsync( """ class Test { void N() { void M where T : I, $$ """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/NullKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/NullKeywordRecommenderTests.cs index 9ce863a783ef0..e13351c2befc8 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/NullKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/NullKeywordRecommenderTests.cs @@ -13,290 +13,223 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class NullKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestInEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInExpression() + => VerifyKeywordAsync(AddInsideMethod( @"var q = $$")); - } [Fact] - public async Task TestNotInPPIf() - { - await VerifyAbsenceAsync( + public Task TestNotInPPIf() + => VerifyAbsenceAsync( @"#if $$"); - } [Fact] - public async Task TestNotInPPIf_Or() - { - await VerifyAbsenceAsync( + public Task TestNotInPPIf_Or() + => VerifyAbsenceAsync( @"#if a || $$"); - } [Fact] - public async Task TestNotInPPIf_And() - { - await VerifyAbsenceAsync( + public Task TestNotInPPIf_And() + => VerifyAbsenceAsync( @"#if a && $$"); - } [Fact] - public async Task TestNotInPPIf_Not() - { - await VerifyAbsenceAsync( + public Task TestNotInPPIf_Not() + => VerifyAbsenceAsync( @"#if ! $$"); - } [Fact] - public async Task TestNotInPPIf_Paren() - { - await VerifyAbsenceAsync( + public Task TestNotInPPIf_Paren() + => VerifyAbsenceAsync( @"#if ( $$"); - } [Fact] - public async Task TestNotInPPIf_Equals() - { - await VerifyAbsenceAsync( + public Task TestNotInPPIf_Equals() + => VerifyAbsenceAsync( @"#if a == $$"); - } [Fact] - public async Task TestNotInPPIf_NotEquals() - { - await VerifyAbsenceAsync( + public Task TestNotInPPIf_NotEquals() + => VerifyAbsenceAsync( @"#if a != $$"); - } [Fact] - public async Task TestNotInPPElIf() - { - await VerifyAbsenceAsync( + public Task TestNotInPPElIf() + => VerifyAbsenceAsync( """ #if true #elif $$ """); - } [Fact] - public async Task TestNotInPPelIf_Or() - { - await VerifyAbsenceAsync( + public Task TestNotInPPelIf_Or() + => VerifyAbsenceAsync( """ #if true #elif a || $$ """); - } [Fact] - public async Task TestNotInPPElIf_And() - { - await VerifyAbsenceAsync( + public Task TestNotInPPElIf_And() + => VerifyAbsenceAsync( """ #if true #elif a && $$ """); - } [Fact] - public async Task TestNotInPPElIf_Not() - { - await VerifyAbsenceAsync( + public Task TestNotInPPElIf_Not() + => VerifyAbsenceAsync( """ #if true #elif ! $$ """); - } [Fact] - public async Task TestNotInPPElIf_Paren() - { - await VerifyAbsenceAsync( + public Task TestNotInPPElIf_Paren() + => VerifyAbsenceAsync( """ #if true #elif ( $$ """); - } [Fact] - public async Task TestNotInPPElIf_Equals() - { - await VerifyAbsenceAsync( + public Task TestNotInPPElIf_Equals() + => VerifyAbsenceAsync( """ #if true #elif a == $$ """); - } [Fact] - public async Task TestNotInPPElIf_NotEquals() - { - await VerifyAbsenceAsync( + public Task TestNotInPPElIf_NotEquals() + => VerifyAbsenceAsync( """ #if true #elif a != $$ """); - } [Fact] - public async Task TestNotAfterUnaryOperator() - { - await VerifyAbsenceAsync( + public Task TestNotAfterUnaryOperator() + => VerifyAbsenceAsync( """ class C { public static bool operator $$ """); - } [Fact] - public async Task TestNotAfterImplicitOperator() - { - await VerifyAbsenceAsync( + public Task TestNotAfterImplicitOperator() + => VerifyAbsenceAsync( """ class C { public static implicit operator $$ """); - } [Fact] - public async Task TestNotAfterExplicitOperator() - { - await VerifyAbsenceAsync( + public Task TestNotAfterExplicitOperator() + => VerifyAbsenceAsync( """ class C { public static implicit operator $$ """); - } [Fact] - public async Task TestAfterCastInField() - { - await VerifyKeywordAsync( + public Task TestAfterCastInField() + => VerifyKeywordAsync( """ class C { public static readonly ImmutableList Empty = new ImmutableList((Segment)$$ """); - } [Fact] - public async Task TestInTernary() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInTernary() + => VerifyKeywordAsync(AddInsideMethod( """ SyntaxKind kind = caseOrDefaultKeywordOpt == $$ ? SyntaxKind.GotoStatement : caseOrDefaultKeyword.Kind == SyntaxKind.CaseKeyword ? SyntaxKind.GotoCaseStatement : SyntaxKind.GotoDefaultStatement; """)); - } [Fact] - public async Task TestInForMiddle() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForMiddle() + => VerifyKeywordAsync(AddInsideMethod( @"for (int i = 0; $$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInTypeOf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInTypeOf() + => VerifyAbsenceAsync(AddInsideMethod( @"typeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInDefault() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInDefault() + => VerifyAbsenceAsync(AddInsideMethod( @"default($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInSizeOf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInSizeOf() + => VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541670")] - public async Task TestInReferenceSwitch() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInReferenceSwitch() + => VerifyKeywordAsync(AddInsideMethod( """ switch ("goo") { case $$ } """)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543766")] - public async Task TestNotInDefaultParameterValue() - { - await VerifyKeywordAsync( + public Task TestNotInDefaultParameterValue() + => VerifyKeywordAsync( @"class C { void Goo(string[] args = $$"); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -304,12 +237,10 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] - public async Task TestNotInCrefContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInCrefContext() + => VerifyAbsenceAsync(""" class Program { /// @@ -319,166 +250,135 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] - public async Task TestInCrefContextNotAfterDot() - { - await VerifyAbsenceAsync(""" + public Task TestInCrefContextNotAfterDot() + => VerifyAbsenceAsync(""" /// class C { } """); - } [Fact] public async Task TestAfterIs() => await VerifyKeywordAsync(AddInsideMethod(@"if (x is $$")); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25293")] - public async Task TestAfterIs_BeforeExpression() - { - await VerifyKeywordAsync(AddInsideMethod(""" + public Task TestAfterIs_BeforeExpression() + => VerifyKeywordAsync(AddInsideMethod(""" int x; int y = x is $$ Method(); """)); - } [Fact] - public async Task TestAfterLambdaOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaOpenParen() + => VerifyKeywordAsync( @"var lam = ($$"); - } [Fact] - public async Task TestAfterLambdaComma() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaComma() + => VerifyKeywordAsync( @"var lam = (int i, $$"); - } [Fact] - public async Task TestLambdaDefaultParameterValue() - { - await VerifyKeywordAsync( + public Task TestLambdaDefaultParameterValue() + => VerifyKeywordAsync( @"var lam = (int i = $$"); - } #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/NullableKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/NullableKeywordRecommenderTests.cs index a9d079e6e03db..3f3a0b9d2b4a5 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/NullableKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/NullableKeywordRecommenderTests.cs @@ -13,83 +13,63 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class NullableKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterHash() - { - await VerifyKeywordAsync( + public Task TestAfterHash() + => VerifyKeywordAsync( @"#$$"); - } [Fact] - public async Task TestAfterHashAndSpace() - { - await VerifyKeywordAsync( + public Task TestAfterHashAndSpace() + => VerifyKeywordAsync( @"# $$"); - } [Fact] - public async Task TestNotAfterHashAndNullable() - { - await VerifyAbsenceAsync( + public Task TestNotAfterHashAndNullable() + => VerifyAbsenceAsync( @"#nullable $$"); - } [Fact] public async Task TestNotAfterPragma() diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ObjectKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ObjectKeywordRecommenderTests.cs index 3aeabdd5d6b3d..d77bfb3e286e7 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ObjectKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ObjectKeywordRecommenderTests.cs @@ -13,719 +13,554 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ObjectKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsing() - { - await VerifyAbsenceAsync( + public Task TestNotInUsing() + => VerifyAbsenceAsync( @"using $$"); - } [Fact] - public async Task TestInUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInUsingAlias() + => VerifyKeywordAsync( @"using Goo = $$"); - } [Fact] - public async Task TestInGlobalUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInGlobalUsingAlias() + => VerifyKeywordAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotAfterStackAlloc() - { - await VerifyAbsenceAsync( + public Task TestNotAfterStackAlloc() + => VerifyAbsenceAsync( """ class C { int* goo = stackalloc $$ """); - } [Fact] - public async Task TestNotInFixedStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInFixedStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"fixed ($$")); - } [Fact] - public async Task TestAfterConstInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterConstInMemberContext() + => VerifyKeywordAsync( """ class C { const $$ """); - } [Fact] - public async Task TestAfterRefInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefInMemberContext() + => VerifyKeywordAsync( """ class C { ref $$ """); - } [Fact] - public async Task TestAfterRefReadonlyInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyInMemberContext() + => VerifyKeywordAsync( """ class C { ref readonly $$ """); - } [Fact] - public async Task TestAfterConstInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"const $$")); - } [Fact] - public async Task TestAfterRefInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$")); - } [Fact] - public async Task TestAfterRefReadonlyInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); - } [Fact] - public async Task TestAfterConstLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); - } [Fact] - public async Task TestAfterRefReadonlyLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); - } [Fact] - public async Task TestAfterRefReadonlyLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); - } [Fact] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } [Fact] - public async Task TestInEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestNotInEnumBaseTypes() - { - await VerifyAbsenceAsync( + public Task TestNotInEnumBaseTypes() + => VerifyAbsenceAsync( @"enum E : $$"); - } [Fact] - public async Task TestInGenericType1() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType1() + => VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); - } [Fact] - public async Task TestInGenericType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType2() + => VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList,$$")); - } [Fact] - public async Task TestNotInBaseList() - { - await VerifyAbsenceAsync( + public Task TestNotInBaseList() + => VerifyAbsenceAsync( @"class C : $$"); - } [Fact] - public async Task TestInGenericType_InBaseList() - { - await VerifyKeywordAsync( + public Task TestInGenericType_InBaseList() + => VerifyKeywordAsync( @"class C : IList<$$"); - } [Fact] - public async Task TestAfterIs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); - } [Fact] - public async Task TestAfterAs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterAs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync( + public Task TestInsideInterface() + => VerifyKeywordAsync( """ interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact] - public async Task TestAfterNestedPartial() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPartial() + => VerifyKeywordAsync( """ class C { partial $$ """); - } [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] - public async Task TestAfterNestedStaticPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticPublic() + => VerifyKeywordAsync( """ class C { static public $$ """); - } [Fact] - public async Task TestAfterNestedPublicStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublicStatic() + => VerifyKeywordAsync( """ class C { public static $$ """); - } [Fact] - public async Task TestAfterVirtualPublic() - { - await VerifyKeywordAsync( + public Task TestAfterVirtualPublic() + => VerifyKeywordAsync( """ class C { virtual public $$ """); - } [Fact] - public async Task TestAfterNestedPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublic() + => VerifyKeywordAsync( """ class C { public $$ """); - } [Fact] - public async Task TestAfterNestedPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPrivate() + => VerifyKeywordAsync( """ class C { private $$ """); - } [Fact] - public async Task TestAfterNestedProtected() - { - await VerifyKeywordAsync( + public Task TestAfterNestedProtected() + => VerifyKeywordAsync( """ class C { protected $$ """); - } [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] - public async Task TestAfterNestedStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStatic() + => VerifyKeywordAsync( """ class C { static $$ """); - } [Fact] - public async Task TestInLocalVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLocalVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInForVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"for ($$")); - } [Fact] - public async Task TestInForeachVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForeachVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); - } [Fact] - public async Task TestInUsingVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInUsingVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"using ($$")); - } [Fact] - public async Task TestInFromVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFromVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); - } [Fact] - public async Task TestInJoinVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInJoinVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from a in b join $$ """)); - } [Fact] - public async Task TestAfterMethodOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterMethodOpenParen() + => VerifyKeywordAsync( """ class C { void Goo($$ """); - } [Fact] - public async Task TestAfterMethodComma() - { - await VerifyKeywordAsync( + public Task TestAfterMethodComma() + => VerifyKeywordAsync( """ class C { void Goo(int i, $$ """); - } [Fact] - public async Task TestAfterMethodAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterMethodAttribute() + => VerifyKeywordAsync( """ class C { void Goo(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterConstructorOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorOpenParen() + => VerifyKeywordAsync( """ class C { public C($$ """); - } [Fact] - public async Task TestAfterConstructorComma() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorComma() + => VerifyKeywordAsync( """ class C { public C(int i, $$ """); - } [Fact] - public async Task TestAfterConstructorAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorAttribute() + => VerifyKeywordAsync( """ class C { public C(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterDelegateOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateOpenParen() + => VerifyKeywordAsync( @"delegate void D($$"); - } [Fact] - public async Task TestAfterDelegateComma() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateComma() + => VerifyKeywordAsync( @"delegate void D(int i, $$"); - } [Fact] - public async Task TestAfterDelegateAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateAttribute() + => VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); - } [Fact] - public async Task TestAfterThis() - { - await VerifyKeywordAsync( + public Task TestAfterThis() + => VerifyKeywordAsync( """ static class C { public static void Goo(this $$ """); - } [Fact] - public async Task TestAfterRef() - { - await VerifyKeywordAsync( + public Task TestAfterRef() + => VerifyKeywordAsync( """ class C { void Goo(ref $$ """); - } [Fact] - public async Task TestAfterOut() - { - await VerifyKeywordAsync( + public Task TestAfterOut() + => VerifyKeywordAsync( """ class C { void Goo(out $$ """); - } [Fact] - public async Task TestAfterLambdaRef() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaRef() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (ref $$ """); - } [Fact] - public async Task TestAfterLambdaOut() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaOut() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (out $$ """); - } [Fact] - public async Task TestAfterParams() - { - await VerifyKeywordAsync( + public Task TestAfterParams() + => VerifyKeywordAsync( """ class C { void Goo(params $$ """); - } [Fact] - public async Task TestInImplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInImplicitOperator() + => VerifyKeywordAsync( """ class C { public static implicit operator $$ """); - } [Fact] - public async Task TestInExplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInExplicitOperator() + => VerifyKeywordAsync( """ class C { public static explicit operator $$ """); - } [Fact] - public async Task TestAfterIndexerBracket() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracket() + => VerifyKeywordAsync( """ class C { int this[$$ """); - } [Fact] - public async Task TestAfterIndexerBracketComma() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracketComma() + => VerifyKeywordAsync( """ class C { int this[int i, $$ """); - } [Fact] - public async Task TestAfterNewInExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterNewInExpression() + => VerifyKeywordAsync(AddInsideMethod( @"new $$")); - } [Fact] - public async Task TestInCastType() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); - } [Fact] - public async Task TestInCastType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType2() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); - } [Fact] - public async Task TestInCastType3() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType3() + => VerifyKeywordAsync(AddInsideMethod( @"return (LeafSegment)(object)$$")); - } [Fact] - public async Task TestInDelegateReturnType() - { - await VerifyKeywordAsync( + public Task TestInDelegateReturnType() + => VerifyKeywordAsync( @"public delegate $$"); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInTypeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInTypeOf() + => VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInDefault() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDefault() + => VerifyKeywordAsync(AddInsideMethod( @"default($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInSizeOf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInSizeOf() + => VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -733,12 +568,10 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] - public async Task TestInCrefContext() - { - await VerifyKeywordAsync(""" + public Task TestInCrefContext() + => VerifyKeywordAsync(""" class Program { /// @@ -748,16 +581,13 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] - public async Task TestInCrefContextNotAfterDot() - { - await VerifyAbsenceAsync(""" + public Task TestInCrefContextNotAfterDot() + => VerifyAbsenceAsync(""" /// class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] public async Task TestNotAfterAsync() @@ -768,19 +598,16 @@ public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1468")] - public async Task TestNotInCrefTypeParameter() - { - await VerifyAbsenceAsync(""" + public Task TestNotInCrefTypeParameter() + => VerifyAbsenceAsync(""" using System; /// class C { } """); - } [Fact] - public async Task Preselection() - { - await VerifyKeywordAsync(""" + public Task Preselection() + => VerifyKeywordAsync(""" class Program { static void Main(string[] args) @@ -790,23 +617,19 @@ static void Main(string[] args) static void Helper(object x) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinType() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinType() + => VerifyKeywordAsync(""" class Program { ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinMember() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinMember() + => VerifyKeywordAsync(""" class Program { void Method() @@ -815,96 +638,76 @@ void Method() } } """); - } [Fact] - public async Task TestInFunctionPointerType() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerType() + => VerifyKeywordAsync(""" class C { delegate*<$$ """); - } [Fact] - public async Task TestInFunctionPointerTypeAfterComma() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerTypeAfterComma() + => VerifyKeywordAsync(""" class C { delegate* VerifyKeywordAsync(""" class C { delegate* VerifyAbsenceAsync(""" class C { delegate*$$ """); - } [Fact] - public async Task TestNotInDeclarationDeconstruction() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInDeclarationDeconstruction() + => VerifyAbsenceAsync(AddInsideMethod( @"var (x, $$) = (0, 0);")); - } [Fact] - public async Task TestInMixedDeclarationAndAssignmentInDeconstruction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInMixedDeclarationAndAssignmentInDeconstruction() + => VerifyKeywordAsync(AddInsideMethod( @"(x, $$) = (0, 0);")); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/53585")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithoutAsync))] - public async Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) - { - await VerifyKeywordAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) + => VerifyKeywordAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithAsync))] - public async Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) - { - await VerifyAbsenceAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) + => VerifyAbsenceAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64585")] - public async Task TestAfterRequired() - { - await VerifyKeywordAsync(""" + public Task TestAfterRequired() + => VerifyKeywordAsync(""" class C { required $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefAtTopLevel1() + => VerifyKeywordAsync( @"ref $$"); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [CombinatorialData] @@ -925,216 +728,183 @@ await VerifyAbsenceAsync( } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefReadonlyAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyAtTopLevel1() + => VerifyKeywordAsync( @"ref readonly $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { readonly $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref readonly $$ } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref $$ -}}"); - } + public Task TestAfterRefInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - readonly $$ -}}"); - } + public Task TestAfterReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + readonly $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref readonly $$ -}}"); - } + public Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref readonly $$ + } + """); #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -1144,5 +914,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/OnKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/OnKeywordRecommenderTests.cs index 960a8f96f4800..7bb79c84ee6a9 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/OnKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/OnKeywordRecommenderTests.cs @@ -12,150 +12,118 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class OnKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterJoinInExpr1() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterJoinInExpr1() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y join a in e $$ """)); - } [Fact] - public async Task TestAfterJoinInExpr2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterJoinInExpr2() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y join a.b c in e $$ """)); - } [Fact] - public async Task TestNotAfterOn1() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterOn1() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y join a.b c in e on $$ """)); - } [Fact] - public async Task TestNotAfterOn2() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterOn2() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y join a.b c in e on o$$ """)); - } [Fact] - public async Task TestNotAfterOn3() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterOn3() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y join a.b c in e on o1 $$ """)); - } [Fact] - public async Task TestNotAfterOn4() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterOn4() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y join a.b c in e on o1 e$$ """)); - } [Fact] - public async Task TestNotAfterOn5() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterOn5() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y join a.b c in e on o1 equals $$ """)); - } [Fact] - public async Task TestNotAfterOn6() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterOn6() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y join a.b c in e on o1 equals o$$ """)); - } [Fact] - public async Task TestNotAfterIn() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterIn() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y join a.b c in $$ """)); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/OperatorKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/OperatorKeywordRecommenderTests.cs index f4304ca252ec2..cbe9671de2564 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/OperatorKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/OperatorKeywordRecommenderTests.cs @@ -13,137 +13,108 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class OperatorKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterImplicit() - { - await VerifyKeywordAsync( + public Task TestAfterImplicit() + => VerifyKeywordAsync( """ class Goo { public static implicit $$ """); - } [Fact] - public async Task TestAfterExplicit() - { - await VerifyKeywordAsync( + public Task TestAfterExplicit() + => VerifyKeywordAsync( """ class Goo { public static explicit $$ """); - } [Fact] - public async Task TestNotAfterType() - { - await VerifyAbsenceAsync( + public Task TestNotAfterType() + => VerifyAbsenceAsync( """ class Goo { int $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542271")] - public async Task TestAfterPublicStaticType() - { - await VerifyAbsenceAsync( + public Task TestAfterPublicStaticType() + => VerifyAbsenceAsync( """ class Goo { public static int $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542271")] - public async Task TestAfterPublicStaticExternType() - { - await VerifyAbsenceAsync( + public Task TestAfterPublicStaticExternType() + => VerifyAbsenceAsync( """ class Goo { public static extern int $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542271")] - public async Task TestAfterGenericType() - { - await VerifyAbsenceAsync( + public Task TestAfterGenericType() + => VerifyAbsenceAsync( """ class Goo { public static IList $$ """); - } [Fact] - public async Task TestNotInInterface() - { - await VerifyAbsenceAsync( + public Task TestNotInInterface() + => VerifyAbsenceAsync( """ interface Goo { public static int $$ """); - } [Fact] - public async Task TestWithinExtension1() - { - await VerifyAbsenceAsync( + public Task TestWithinExtension1() + => VerifyAbsenceAsync( """ static class C { @@ -153,12 +124,10 @@ static class C } } """, CSharpNextParseOptions); - } [Fact] - public async Task TestWithinExtension2() - { - await VerifyKeywordAsync( + public Task TestWithinExtension2() + => VerifyKeywordAsync( """ static class C { @@ -170,5 +139,4 @@ public static explicit $$ """, CSharpNextParseOptions, CSharpNextScriptParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/OrKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/OrKeywordRecommenderTests.cs index 3fa6a59a09fda..be16b4d871f1a 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/OrKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/OrKeywordRecommenderTests.cs @@ -17,37 +17,28 @@ public sealed class OrKeywordRecommenderTests : KeywordRecommenderTests """; [Fact] - public async Task TestAfterConstant() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAfterConstant() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is 1 $$")); - } [Fact] - public async Task TestAfterMultipleConstants() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAfterMultipleConstants() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is 1 or 2 $$")); - } [Fact] - public async Task TestAfterType() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAfterType() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is int $$")); - } [Fact] - public async Task TestAfterRelationalOperator() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAfterRelationalOperator() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is >= 0 $$")); - } [Fact] - public async Task TestAfterGenericType() - { - await VerifyKeywordAsync( + public Task TestAfterGenericType() + => VerifyKeywordAsync( """ class C { @@ -56,12 +47,10 @@ void M() var e = new object(); if (e is T $$ """); - } [Fact] - public async Task TestAfterArrayType() - { - await VerifyKeywordAsync( + public Task TestAfterArrayType() + => VerifyKeywordAsync( """ class C { @@ -70,12 +59,10 @@ void M() var e = new object(); if (e is int[] $$ """); - } [Fact] - public async Task TestAfterListType() - { - await VerifyKeywordAsync( + public Task TestAfterListType() + => VerifyKeywordAsync( """ using System.Collections.Generic; @@ -86,12 +73,10 @@ void M() var e = new object(); if (e is List $$ """); - } [Fact] - public async Task TestAfterListType_FullyQualified() - { - await VerifyKeywordAsync( + public Task TestAfterListType_FullyQualified() + => VerifyKeywordAsync( """ class C { @@ -100,12 +85,10 @@ void M() var e = new object(); if (e is System.Collections.Generic.List $$ """); - } [Fact] - public async Task TestAfterRecursivePattern() - { - await VerifyKeywordAsync( + public Task TestAfterRecursivePattern() + => VerifyKeywordAsync( """ class C { @@ -115,12 +98,10 @@ void M(C test) { if (test is { P: 1 } $$ """); - } [Fact] - public async Task TestInsideSubpattern() - { - await VerifyKeywordAsync( + public Task TestInsideSubpattern() + => VerifyKeywordAsync( """ class C { @@ -130,12 +111,10 @@ void M(C test) { if (test is { P: 1 $$ """); - } [Fact] - public async Task TestInsideSubpattern_ComplexConstant() - { - await VerifyKeywordAsync( + public Task TestInsideSubpattern_ComplexConstant() + => VerifyKeywordAsync( """ namespace N { @@ -149,12 +128,10 @@ void M(C test) { if (test is { Prop: N.C.P $$ """); - } [Fact] - public async Task TestInsideSubpattern_AfterOpenParen() - { - await VerifyKeywordAsync( + public Task TestInsideSubpattern_AfterOpenParen() + => VerifyKeywordAsync( """ class C { @@ -165,12 +142,10 @@ void M() var C2 = new C(); if (C2 is { P: (1 $$ """); - } [Fact] - public async Task TestInsideSubpattern_AfterOpenParen_ComplexConstant() - { - await VerifyKeywordAsync( + public Task TestInsideSubpattern_AfterOpenParen_ComplexConstant() + => VerifyKeywordAsync( """ namespace N { @@ -184,12 +159,10 @@ void M(C test) { if (test is { Prop: (N.C.P $$ """); - } [Fact] - public async Task TestInsideSubpattern_AfterMultipleOpenParens() - { - await VerifyKeywordAsync( + public Task TestInsideSubpattern_AfterMultipleOpenParens() + => VerifyKeywordAsync( """ class C { @@ -200,12 +173,10 @@ void M() var C2 = new C(); if (C2 is { P: (((1 $$ """); - } [Fact] - public async Task TestInsideSubpattern_AfterMultipleOpenParens_ComplexConstant() - { - await VerifyKeywordAsync( + public Task TestInsideSubpattern_AfterMultipleOpenParens_ComplexConstant() + => VerifyKeywordAsync( """ namespace N { @@ -219,12 +190,10 @@ void M(C test) { if (test is { Prop: (((N.C.P $$ """); - } [Fact] - public async Task TestAtBeginningOfSwitchStatement_AfterMultipleOpenParens_MemberAccessExpression() - { - await VerifyKeywordAsync( + public Task TestAtBeginningOfSwitchStatement_AfterMultipleOpenParens_MemberAccessExpression() + => VerifyKeywordAsync( """ namespace N { @@ -239,12 +208,10 @@ void M() { case (((N.C.P $$ """); - } [Fact] - public async Task TestAtBeginningOfSwitchStatement_AfterMultipleOpenParens_MemberAccessExpression2() - { - await VerifyKeywordAsync( + public Task TestAtBeginningOfSwitchStatement_AfterMultipleOpenParens_MemberAccessExpression2() + => VerifyKeywordAsync( """ namespace N { @@ -257,12 +224,10 @@ void M() { case (((N.C $$ """); - } [Fact] - public async Task TestInsideSubpattern_AfterParenPair() - { - await VerifyKeywordAsync( + public Task TestInsideSubpattern_AfterParenPair() + => VerifyKeywordAsync( """ class C { @@ -273,12 +238,10 @@ void M() var C2 = new C(); if (C2 is { P: (1) $$ """); - } [Fact] - public async Task TestInsideSubpattern_AfterParenPair_ComplexConstant() - { - await VerifyKeywordAsync( + public Task TestInsideSubpattern_AfterParenPair_ComplexConstant() + => VerifyKeywordAsync( """ namespace N { @@ -292,12 +255,10 @@ void M(C test) { if (test is { Prop: (N.C.P + 1) $$ """); - } [Fact] - public async Task TestInsideSubpattern_AfterMultipleParenPairs() - { - await VerifyKeywordAsync( + public Task TestInsideSubpattern_AfterMultipleParenPairs() + => VerifyKeywordAsync( """ class C { @@ -308,12 +269,10 @@ void M() var C2 = new C(); if (C2 is { P: (((1))) $$ """); - } [Fact] - public async Task TestInsideSubpattern_AfterMultipleParenPairs_ComplexConstant() - { - await VerifyKeywordAsync( + public Task TestInsideSubpattern_AfterMultipleParenPairs_ComplexConstant() + => VerifyKeywordAsync( """ namespace N { @@ -327,12 +286,10 @@ void M(C test) { if (test is { Prop: (((N.C.P))) $$ """); - } [Fact] - public async Task TestAfterQualifiedName() - { - await VerifyKeywordAsync( + public Task TestAfterQualifiedName() + => VerifyKeywordAsync( """ class C { @@ -344,12 +301,10 @@ void M() var e = new object(); if (e is C2.P $$ """); - } [Fact] - public async Task TestAfterQualifiedName2() - { - await VerifyKeywordAsync( + public Task TestAfterQualifiedName2() + => VerifyKeywordAsync( """ namespace N { @@ -362,23 +317,19 @@ void M() var e = new object(); if (e is N.C.P $$ """); - } [Fact] - public async Task TestAtBeginningOfSwitchExpression() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAtBeginningOfSwitchExpression() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + """ var result = e switch { 1 $$ """)); - } [Fact] - public async Task TestAtBeginningOfSwitchExpression_Complex() - { - await VerifyKeywordAsync( + public Task TestAtBeginningOfSwitchExpression_Complex() + => VerifyKeywordAsync( """ namespace N { @@ -393,34 +344,28 @@ void M() { N.C.P $$ """); - } [Fact] - public async Task TestAtBeginningOfSwitchStatement() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAtBeginningOfSwitchStatement() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + """ switch (e) { case 1 $$ """)); - } [Fact] - public async Task TestAtBeginningOfSwitchExpression_AfterOpenParen() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAtBeginningOfSwitchExpression_AfterOpenParen() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + """ var result = e switch { (1 $$ """)); - } [Fact] - public async Task TestAtBeginningOfSwitchExpression_AfterOpenParen_Complex() - { - await VerifyKeywordAsync( + public Task TestAtBeginningOfSwitchExpression_AfterOpenParen_Complex() + => VerifyKeywordAsync( """ namespace N { @@ -435,23 +380,19 @@ void M() { (N.C.P $$ """); - } [Fact] - public async Task TestAtBeginningOfSwitchExpression_AfterMultipleOpenParens() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAtBeginningOfSwitchExpression_AfterMultipleOpenParens() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + """ var result = e switch { (((1 $$ """)); - } [Fact] - public async Task TestAtBeginningOfSwitchExpression_AfterMultipleOpenParens_Complex() - { - await VerifyKeywordAsync( + public Task TestAtBeginningOfSwitchExpression_AfterMultipleOpenParens_Complex() + => VerifyKeywordAsync( """ namespace N { @@ -466,149 +407,114 @@ void M() { (((N.C.P $$ """); - } [Fact] - public async Task TestAtBeginningOfSwitchStatement_AfterOpenParen() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAtBeginningOfSwitchStatement_AfterOpenParen() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + """ switch (e) { case (1 $$ """)); - } [Fact] - public async Task TestAtBeginningOfSwitchStatement_AfterMultipleOpenParens() - { - await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + + public Task TestAtBeginningOfSwitchStatement_AfterMultipleOpenParens() + => VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + """ switch (e) { case (((1 $$ """)); - } [Fact] - public async Task TestMissingAfterIsKeyword() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAfterIsKeyword() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is $$")); - } [Fact] - public async Task TestMissingAfterNotKeyword() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAfterNotKeyword() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is not $$")); - } [Fact] - public async Task TestMissingAfterVarKeyword() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAfterVarKeyword() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is var $$")); - } [Fact] - public async Task TestMissingAfterAndKeyword() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAfterAndKeyword() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is 1 and $$")); - } [Fact] - public async Task TestMissingAfterOrKeyword() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAfterOrKeyword() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is 1 or $$")); - } [Fact] - public async Task TestMissingAfterOpenParen() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAfterOpenParen() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is ($$")); - } [Fact] - public async Task TestMissingAfterOpenBracket() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAfterOpenBracket() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is { $$")); - } [Fact] - public async Task TestMissingAtBeginningOfSwitchExpression() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAtBeginningOfSwitchExpression() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + """ var result = e switch { $$ """)); - } [Fact] - public async Task TestMissingAtBeginningOfSwitchStatement() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAtBeginningOfSwitchStatement() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + """ switch (e) { case $$ """)); - } [Fact] - public async Task TestMissingAfterTypeAndOpenParen() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAfterTypeAndOpenParen() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is int ($$")); - } [Fact] - public async Task TestMissingAfterTypeAndCloseParen() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAfterTypeAndCloseParen() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is int)$$")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44396")] - public async Task TestMissingAfterColonColonPatternSyntax() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAfterColonColonPatternSyntax() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is null or global::$$) { }")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44396")] - public async Task TestMissingAfterColonColonPatternSyntax_SwitchExpression() - { - await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + + public Task TestMissingAfterColonColonPatternSyntax_SwitchExpression() + => VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + """ var x = false; x = e switch { global::$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70045")] - public async Task TestNotInMemberAccessInPattern1() - { - await VerifyAbsenceAsync(""" + public Task TestNotInMemberAccessInPattern1() + => VerifyAbsenceAsync(""" int v = 0; if (v is var a and a.$$) """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70045")] - public async Task TestNotInMemberAccessInPattern2() - { - await VerifyAbsenceAsync(""" + public Task TestNotInMemberAccessInPattern2() + => VerifyAbsenceAsync(""" int* v = null; if (v is var a and a->$$) """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/OrderByKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/OrderByKeywordRecommenderTests.cs index c2c7050e07b78..bbf8e7981678e 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/OrderByKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/OrderByKeywordRecommenderTests.cs @@ -12,120 +12,94 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class OrderByKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestNotAtEndOfPreviousClause() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAtEndOfPreviousClause() + => VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y$$")); - } [Fact] - public async Task TestNewClause() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestNewClause() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y $$ """)); - } [Fact] - public async Task TestAfterPreviousClause() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterPreviousClause() + => VerifyKeywordAsync(AddInsideMethod( """ var v = from x in y where x > y $$ """)); - } [Fact] - public async Task TestAfterPreviousContinuationClause() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterPreviousContinuationClause() + => VerifyKeywordAsync(AddInsideMethod( """ var v = from x in y group x by y into g $$ """)); - } [Fact] - public async Task TestBetweenClauses() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBetweenClauses() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y $$ from z in w """)); - } [Fact] - public async Task TestNotAfterOrderBy() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterOrderBy() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y orderby $$ """)); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/OutKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/OutKeywordRecommenderTests.cs index 4f83772fe01a9..fbb191779b1ed 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/OutKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/OutKeywordRecommenderTests.cs @@ -13,559 +13,437 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class OutKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestInterfaceTypeVarianceAfterAngle() - { - await VerifyKeywordAsync( + public Task TestInterfaceTypeVarianceAfterAngle() + => VerifyKeywordAsync( @"interface IGoo<$$"); - } [Fact] - public async Task TestInterfaceTypeVarianceNotAfterOut() - { - await VerifyAbsenceAsync( + public Task TestInterfaceTypeVarianceNotAfterOut() + => VerifyAbsenceAsync( @"interface IGoo VerifyKeywordAsync( @"interface IGoo VerifyKeywordAsync( @"interface IGoo<[Goo]$$"); - } [Fact] - public async Task TestDelegateTypeVarianceAfterAngle() - { - await VerifyKeywordAsync( + public Task TestDelegateTypeVarianceAfterAngle() + => VerifyKeywordAsync( @"delegate void D<$$"); - } [Fact] - public async Task TestDelegateTypeVarianceAfterComma() - { - await VerifyKeywordAsync( + public Task TestDelegateTypeVarianceAfterComma() + => VerifyKeywordAsync( @"delegate void D VerifyKeywordAsync( @"delegate void D<[Goo]$$"); - } [Fact] - public async Task TestNotOutClassTypeVarianceAfterAngle() - { - await VerifyAbsenceAsync( + public Task TestNotOutClassTypeVarianceAfterAngle() + => VerifyAbsenceAsync( @"class IGoo<$$"); - } [Fact] - public async Task TestNotOutStructTypeVarianceAfterAngle() - { - await VerifyAbsenceAsync( + public Task TestNotOutStructTypeVarianceAfterAngle() + => VerifyAbsenceAsync( @"struct IGoo<$$"); - } [Fact] - public async Task TestNotOutBaseListAfterAngle() - { - await VerifyAbsenceAsync( + public Task TestNotOutBaseListAfterAngle() + => VerifyAbsenceAsync( @"interface IGoo : Bar<$$"); - } [Fact] - public async Task TestNotInGenericMethod() - { - await VerifyAbsenceAsync( + public Task TestNotInGenericMethod() + => VerifyAbsenceAsync( """ interface IGoo { void Goo<$$ """); - } [Fact] - public async Task TestNotAfterOut() - { - await VerifyAbsenceAsync( + public Task TestNotAfterOut() + => VerifyAbsenceAsync( """ class C { void Goo(out $$ """); - } [Fact] - public async Task TestAfterMethodOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterMethodOpenParen() + => VerifyKeywordAsync( """ class C { void Goo($$ """); - } [Fact] - public async Task TestAfterMethodComma() - { - await VerifyKeywordAsync( + public Task TestAfterMethodComma() + => VerifyKeywordAsync( """ class C { void Goo(int i, $$ """); - } [Fact] - public async Task TestAfterMethodAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterMethodAttribute() + => VerifyKeywordAsync( """ class C { void Goo(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterConstructorOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorOpenParen() + => VerifyKeywordAsync( """ class C { public C($$ """); - } [Fact] - public async Task TestAfterConstructorComma() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorComma() + => VerifyKeywordAsync( """ class C { public C(int i, $$ """); - } [Fact] - public async Task TestAfterConstructorAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorAttribute() + => VerifyKeywordAsync( """ class C { public C(int i, [Goo]$$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933972")] - public async Task TestAfterThisConstructorInitializer() - { - await VerifyKeywordAsync( + public Task TestAfterThisConstructorInitializer() + => VerifyKeywordAsync( """ class C { public C():this($$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933972")] - public async Task TestAfterThisConstructorInitializerNamedArgument() - { - await VerifyKeywordAsync( + public Task TestAfterThisConstructorInitializerNamedArgument() + => VerifyKeywordAsync( """ class C { public C():this(Goo:$$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933972")] - public async Task TestAfterBaseConstructorInitializer() - { - await VerifyKeywordAsync( + public Task TestAfterBaseConstructorInitializer() + => VerifyKeywordAsync( """ class C { public C():base($$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933972")] - public async Task TestAfterBaseConstructorInitializerNamedArgument() - { - await VerifyKeywordAsync( + public Task TestAfterBaseConstructorInitializerNamedArgument() + => VerifyKeywordAsync( """ class C { public C():base(5, Goo:$$ """); - } [Fact] - public async Task TestAfterDelegateOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateOpenParen() + => VerifyKeywordAsync( @"delegate void D($$"); - } [Fact] - public async Task TestAfterDelegateComma() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateComma() + => VerifyKeywordAsync( @"delegate void D(int i, $$"); - } [Fact] - public async Task TestAfterDelegateAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateAttribute() + => VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24079")] - public async Task TestNotAfterOperator() - { - await VerifyAbsenceAsync( + public Task TestNotAfterOperator() + => VerifyAbsenceAsync( """ class C { static int operator +($$ """); - } [Fact] - public async Task TestNotAfterDestructor() - { - await VerifyAbsenceAsync( + public Task TestNotAfterDestructor() + => VerifyAbsenceAsync( """ class C { ~C($$ """); - } [Fact] - public async Task TestNotAfterIndexer() - { - await VerifyAbsenceAsync( + public Task TestNotAfterIndexer() + => VerifyAbsenceAsync( """ class C { int this[$$ """); - } [Fact] - public async Task TestInObjectCreationAfterOpenParen() - { - await VerifyKeywordAsync( + public Task TestInObjectCreationAfterOpenParen() + => VerifyKeywordAsync( """ class C { void Goo() { new Bar($$ """); - } [Fact] - public async Task TestNotAfterRef() - { - await VerifyAbsenceAsync( + public Task TestNotAfterRef() + => VerifyAbsenceAsync( """ class C { void Goo() { new Bar(ref $$ """); - } [Fact] - public async Task TestNotAfterOutParam() - { - await VerifyAbsenceAsync( + public Task TestNotAfterOutParam() + => VerifyAbsenceAsync( """ class C { void Goo() { new Bar(out $$ """); - } [Fact] - public async Task TestInObjectCreationAfterComma() - { - await VerifyKeywordAsync( + public Task TestInObjectCreationAfterComma() + => VerifyKeywordAsync( """ class C { void Goo() { new Bar(baz, $$ """); - } [Fact] - public async Task TestInObjectCreationAfterSecondComma() - { - await VerifyKeywordAsync( + public Task TestInObjectCreationAfterSecondComma() + => VerifyKeywordAsync( """ class C { void Goo() { new Bar(baz, quux, $$ """); - } [Fact] - public async Task TestInObjectCreationAfterSecondNamedParam() - { - await VerifyKeywordAsync( + public Task TestInObjectCreationAfterSecondNamedParam() + => VerifyKeywordAsync( """ class C { void Goo() { new Bar(baz: 4, quux: $$ """); - } [Fact] - public async Task TestInInvocationExpression() - { - await VerifyKeywordAsync( + public Task TestInInvocationExpression() + => VerifyKeywordAsync( """ class C { void Goo() { Bar($$ """); - } [Fact] - public async Task TestInInvocationAfterComma() - { - await VerifyKeywordAsync( + public Task TestInInvocationAfterComma() + => VerifyKeywordAsync( """ class C { void Goo() { Bar(baz, $$ """); - } [Fact] - public async Task TestInInvocationAfterSecondComma() - { - await VerifyKeywordAsync( + public Task TestInInvocationAfterSecondComma() + => VerifyKeywordAsync( """ class C { void Goo() { Bar(baz, quux, $$ """); - } [Fact] - public async Task TestInInvocationAfterSecondNamedParam() - { - await VerifyKeywordAsync( + public Task TestInInvocationAfterSecondNamedParam() + => VerifyKeywordAsync( """ class C { void Goo() { Bar(baz: 4, quux: $$ """); - } [Fact] - public async Task TestInLambdaDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLambdaDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"var q = ($$")); - } [Fact] - public async Task TestInLambdaDeclaration2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLambdaDeclaration2() + => VerifyKeywordAsync(AddInsideMethod( @"var q = (ref int a, $$")); - } [Fact] - public async Task TestInLambdaDeclaration3() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLambdaDeclaration3() + => VerifyKeywordAsync(AddInsideMethod( @"var q = (int a, $$")); - } [Fact] - public async Task TestInDelegateDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDelegateDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"var q = delegate ($$")); - } [Fact] - public async Task TestInDelegateDeclaration2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDelegateDeclaration2() + => VerifyKeywordAsync(AddInsideMethod( @"var q = delegate (a, $$")); - } [Fact] - public async Task TestInDelegateDeclaration3() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDelegateDeclaration3() + => VerifyKeywordAsync(AddInsideMethod( @"var q = delegate (int a, $$")); - } [Fact] - public async Task TestInCrefParameterList() - { - var text = """ + public Task TestInCrefParameterList() + => VerifyKeywordAsync(""" Class c { /// void main(out goo) { } } - """; - - await VerifyKeywordAsync(text); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22253")] - public async Task TestInLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"void F(int x, $$")); - } [Fact] - public async Task TestExtensionMethods_FirstParameter() - { - await VerifyKeywordAsync( + public Task TestExtensionMethods_FirstParameter() + => VerifyKeywordAsync( """ static class Extensions { static void Extension($$ """); - } [Fact] - public async Task TestExtensionMethods_FirstParameter_AfterThisKeyword() - { - await VerifyAbsenceAsync( + public Task TestExtensionMethods_FirstParameter_AfterThisKeyword() + => VerifyAbsenceAsync( """ static class Extensions { static void Extension(this $$ """); - } [Fact] - public async Task TestExtensionMethods_SecondParameter() - { - await VerifyKeywordAsync( + public Task TestExtensionMethods_SecondParameter() + => VerifyKeywordAsync( """ static class Extensions { static void Extension(this int i, $$ """); - } [Fact] - public async Task TestExtensionMethods_SecondParameter_AfterThisKeyword() - { - await VerifyAbsenceAsync( + public Task TestExtensionMethods_SecondParameter_AfterThisKeyword() + => VerifyAbsenceAsync( """ static class Extensions { static void Extension(this int i, this $$ """); - } [Fact] - public async Task TestInFunctionPointerTypeNoExistingModifiers() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerTypeNoExistingModifiers() + => VerifyKeywordAsync(""" class C { delegate*<$$ """); - } [Theory] [InlineData("in")] [InlineData("out")] [InlineData("ref")] [InlineData("ref readonly")] - public async Task TestNotInFunctionPointerTypeExistingModifiers(string modifier) - { - await VerifyAbsenceAsync($@" -class C -{{ - delegate*<{modifier} $$"); - } - - [Fact] - public async Task TestInParameterAfterScoped() - { - await VerifyKeywordAsync(""" + public Task TestNotInFunctionPointerTypeExistingModifiers(string modifier) + => VerifyAbsenceAsync($$""" + class C + { + delegate*<{{modifier}} $$ + """); + + [Fact] + public Task TestInParameterAfterScoped() + => VerifyKeywordAsync(""" class C { void M(scoped $$) } """); - } [Fact] - public async Task TestInParameterAfterThisScoped() - { - await VerifyKeywordAsync(""" + public Task TestInParameterAfterThisScoped() + => VerifyKeywordAsync(""" static class C { static void M(this scoped $$) } """); - } [Fact] - public async Task TestInAnonymousMethodParameterAfterScoped() - { - await VerifyKeywordAsync(""" + public Task TestInAnonymousMethodParameterAfterScoped() + => VerifyKeywordAsync(""" class C { void M() @@ -574,5 +452,4 @@ void M() } } """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/OverrideKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/OverrideKeywordRecommenderTests.cs index 449951ccecbb0..4155e2dd20754 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/OverrideKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/OverrideKeywordRecommenderTests.cs @@ -13,262 +13,208 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class OverrideKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] public async Task TestNotInCompilationUnit() => await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$"); [Fact] - public async Task TestNotAfterExtern() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterExtern() + => VerifyAbsenceAsync(""" extern alias Goo; $$ """); - } [Fact] - public async Task TestNotAfterUsing() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterUsing() + => VerifyAbsenceAsync(""" using Goo; $$ """); - } [Fact] - public async Task TestNotAfterGlobalUsing() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterGlobalUsing() + => VerifyAbsenceAsync(""" global using Goo; $$ """); - } [Fact] - public async Task TestNotAfterNamespace() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNamespace() + => VerifyAbsenceAsync(""" namespace N {} $$ """); - } [Fact] - public async Task TestNotAfterTypeDeclaration() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterTypeDeclaration() + => VerifyAbsenceAsync(""" class C {} $$ """); - } [Fact] - public async Task TestNotAfterDelegateDeclaration() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterDelegateDeclaration() + => VerifyAbsenceAsync(""" delegate void Goo(); $$ """); - } [Fact] - public async Task TestAfterMethodInClass() - { - await VerifyKeywordAsync( + public Task TestAfterMethodInClass() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterFieldInClass() - { - await VerifyKeywordAsync( + public Task TestAfterFieldInClass() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterFieldInRecord() - { - await VerifyWorkerAsync( + public Task TestAfterFieldInRecord() + => VerifyWorkerAsync( """ record C { int i; $$ """, absent: false, options: TestOptions.RegularPreview); - } [Fact] - public async Task TestAfterPropertyInClass() - { - await VerifyKeywordAsync( + public Task TestAfterPropertyInClass() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ global using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeGlobalUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeGlobalUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ global using Goo; """); - } [Fact] - public async Task TestNotAfterAssemblyAttribute() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterAssemblyAttribute() + => VerifyAbsenceAsync(""" [assembly: goo] $$ """); - } [Fact] - public async Task TestNotAfterRootAttribute() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterRootAttribute() + => VerifyAbsenceAsync(""" [goo] $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestNotInsideInterface() - { - await VerifyAbsenceAsync(""" + public Task TestNotInsideInterface() + => VerifyAbsenceAsync(""" interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() @@ -315,139 +261,112 @@ public async Task TestNotAfterStatic() => await VerifyAbsenceAsync(@"static $$"); [Fact] - public async Task TestNotAfterNestedStatic() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedStatic() + => VerifyAbsenceAsync(""" class C { static $$ """); - } [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] - public async Task TestNotAfterNestedPrivate() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedPrivate() + => VerifyAbsenceAsync(""" class C { private $$ """); - } [Fact] - public async Task TestNotAfterNestedNew() - { - await VerifyAbsenceAsync( + public Task TestNotAfterNestedNew() + => VerifyAbsenceAsync( """ class C { new $$ """); - } [Fact] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact] - public async Task TestNotAfterNestedVirtual() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedVirtual() + => VerifyAbsenceAsync(""" class C { virtual $$ """); - } [Fact] - public async Task TestNotAfterNestedOverride() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedOverride() + => VerifyAbsenceAsync(""" class C { override $$ """); - } [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] - public async Task TestNotInProperty() - { - await VerifyAbsenceAsync( + public Task TestNotInProperty() + => VerifyAbsenceAsync( """ class C { int Goo { $$ """); - } [Fact] - public async Task TestNotInPropertyAfterAccessor() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAfterAccessor() + => VerifyAbsenceAsync( """ class C { int Goo { get; $$ """); - } [Fact] - public async Task TestNotInPropertyAfterAccessibility() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAfterAccessibility() + => VerifyAbsenceAsync( """ class C { int Goo { get; protected $$ """); - } [Fact] - public async Task TestNotInPropertyAfterInternal() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAfterInternal() + => VerifyAbsenceAsync( """ class C { int Goo { get; internal $$ """); - } [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] - public async Task TestAfterPrivateProtected() - { - await VerifyKeywordAsync( + public Task TestAfterPrivateProtected() + => VerifyKeywordAsync( """ class C { private protected $$ """); - } [Fact] - public async Task TestWithinExtension() - { - await VerifyAbsenceAsync( + public Task TestWithinExtension() + => VerifyAbsenceAsync( """ static class C { @@ -457,5 +376,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ParamKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ParamKeywordRecommenderTests.cs index 69d275ea57978..6cd003e05fbbf 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ParamKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ParamKeywordRecommenderTests.cs @@ -21,100 +21,79 @@ public async Task TestNotOfferedInsideArgumentList2() => await VerifyAbsenceAsync("delegate void M([$$"); [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestNotInAttributeInsideClass() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeInsideClass() + => VerifyAbsenceAsync( """ class C { [$$ """); - } [Fact] - public async Task TestNotInAttributeAfterAttributeInsideClass() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeAfterAttributeInsideClass() + => VerifyAbsenceAsync( """ class C { [Goo] [$$ """); - } [Fact] - public async Task TestNotInAttributeAfterMethod() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeAfterMethod() + => VerifyAbsenceAsync( """ class C { void Goo() { } [$$ """); - } [Fact] - public async Task TestNotInAttributeAfterProperty() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeAfterProperty() + => VerifyAbsenceAsync( """ class C { int Goo { @@ -122,130 +101,103 @@ int Goo { } [$$ """); - } [Fact] - public async Task TestNotInAttributeAfterField() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeAfterField() + => VerifyAbsenceAsync( """ class C { int Goo; [$$ """); - } [Fact] - public async Task TestNotInAttributeAfterEvent() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeAfterEvent() + => VerifyAbsenceAsync( """ class C { event Action Goo; [$$ """); - } [Fact] - public async Task TestNotInOuterAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInOuterAttribute() + => VerifyAbsenceAsync( @"[$$"); - } [Fact] - public async Task TestNotInParameterAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInParameterAttribute() + => VerifyAbsenceAsync( """ class C { void Goo([$$ """); - } [Fact] - public async Task TestInPropertyAttribute1() - { - await VerifyKeywordAsync( + public Task TestInPropertyAttribute1() + => VerifyKeywordAsync( """ class C { int Goo { [$$ """); - } [Fact] - public async Task TestInPropertyAttribute2() - { - await VerifyKeywordAsync( + public Task TestInPropertyAttribute2() + => VerifyKeywordAsync( """ class C { int Goo { get { } [$$ """); - } [Fact] - public async Task TestInEventAttribute1() - { - await VerifyKeywordAsync( + public Task TestInEventAttribute1() + => VerifyKeywordAsync( """ class C { event Action Goo { [$$ """); - } [Fact] - public async Task TestInEventAttribute2() - { - await VerifyKeywordAsync( + public Task TestInEventAttribute2() + => VerifyKeywordAsync( """ class C { event Action Goo { add { } [$$ """); - } [Fact] - public async Task TestNotInTypeParameters() - { - await VerifyAbsenceAsync( + public Task TestNotInTypeParameters() + => VerifyAbsenceAsync( @"class C<[$$"); - } [Fact] - public async Task TestNotInInterface() - { - await VerifyAbsenceAsync( + public Task TestNotInInterface() + => VerifyAbsenceAsync( """ interface I { [$$ """); - } [Fact] - public async Task TestNotInStruct() - { - await VerifyAbsenceAsync( + public Task TestNotInStruct() + => VerifyAbsenceAsync( """ struct S { [$$ """); - } [Fact] - public async Task TestNotInEnum() - { - await VerifyAbsenceAsync( + public Task TestNotInEnum() + => VerifyAbsenceAsync( """ enum E { [$$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68399")] - public async Task TestInRecordParameterAttribute() - { - await VerifyKeywordAsync( + public Task TestInRecordParameterAttribute() + => VerifyKeywordAsync( """ record R([$$] int i) { } """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ParamsKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ParamsKeywordRecommenderTests.cs index 37076a1c379a1..12fab9ef57955 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ParamsKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ParamsKeywordRecommenderTests.cs @@ -12,384 +12,300 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ParamsKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotAfterAngle() - { - await VerifyAbsenceAsync( + public Task TestNotAfterAngle() + => VerifyAbsenceAsync( @"interface IGoo<$$"); - } [Fact] - public async Task TestInterfaceTypeVarianceNotAfterIn() - { - await VerifyAbsenceAsync( + public Task TestInterfaceTypeVarianceNotAfterIn() + => VerifyAbsenceAsync( @"interface IGoo VerifyAbsenceAsync( @"interface IGoo VerifyAbsenceAsync( @"interface IGoo<[Goo]$$"); - } [Fact] - public async Task TestDelegateTypeVarianceNotAfterAngle() - { - await VerifyAbsenceAsync( + public Task TestDelegateTypeVarianceNotAfterAngle() + => VerifyAbsenceAsync( @"delegate void D<$$"); - } [Fact] - public async Task TestDelegateTypeVarianceNotAfterComma() - { - await VerifyAbsenceAsync( + public Task TestDelegateTypeVarianceNotAfterComma() + => VerifyAbsenceAsync( @"delegate void D VerifyAbsenceAsync( @"delegate void D<[Goo]$$"); - } [Fact] - public async Task TestNotParamsBaseListAfterAngle() - { - await VerifyAbsenceAsync( + public Task TestNotParamsBaseListAfterAngle() + => VerifyAbsenceAsync( @"interface IGoo : Bar<$$"); - } [Fact] - public async Task TestNotInGenericMethod() - { - await VerifyAbsenceAsync( + public Task TestNotInGenericMethod() + => VerifyAbsenceAsync( """ interface IGoo { void Goo<$$ """); - } [Fact] - public async Task TestNotAfterParams() - { - await VerifyAbsenceAsync( + public Task TestNotAfterParams() + => VerifyAbsenceAsync( """ class C { void Goo(ref $$ """); - } [Fact] - public async Task TestNotAfterOut() - { - await VerifyAbsenceAsync( + public Task TestNotAfterOut() + => VerifyAbsenceAsync( """ class C { void Goo(out $$ """); - } [Fact] - public async Task TestNotAfterThis() - { - await VerifyAbsenceAsync( + public Task TestNotAfterThis() + => VerifyAbsenceAsync( """ static class C { static void Goo(this $$ """); - } [Fact] - public async Task TestAfterMethodOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterMethodOpenParen() + => VerifyKeywordAsync( """ class C { void Goo($$ """); - } [Fact] - public async Task TestAfterMethodComma() - { - await VerifyKeywordAsync( + public Task TestAfterMethodComma() + => VerifyKeywordAsync( """ class C { void Goo(int i, $$ """); - } [Fact] - public async Task TestAfterMethodAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterMethodAttribute() + => VerifyKeywordAsync( """ class C { void Goo(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterConstructorOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorOpenParen() + => VerifyKeywordAsync( """ class C { public C($$ """); - } [Fact] - public async Task TestAfterConstructorComma() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorComma() + => VerifyKeywordAsync( """ class C { public C(int i, $$ """); - } [Fact] - public async Task TestAfterConstructorAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorAttribute() + => VerifyKeywordAsync( """ class C { public C(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterDelegateOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateOpenParen() + => VerifyKeywordAsync( @"delegate void D($$"); - } [Fact] - public async Task TestAfterDelegateComma() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateComma() + => VerifyKeywordAsync( @"delegate void D(int i, $$"); - } [Fact] - public async Task TestAfterDelegateAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateAttribute() + => VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); - } [Fact] - public async Task TestAfterLambdaOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaOpenParen() + => VerifyKeywordAsync( @"var lam = ($$"); - } [Fact] - public async Task TestAfterLambdaComma() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaComma() + => VerifyKeywordAsync( @"var lam = (int i, $$"); - } [Fact] - public async Task TestNotAfterOperator() - { - await VerifyAbsenceAsync( + public Task TestNotAfterOperator() + => VerifyAbsenceAsync( """ class C { static int operator +($$ """); - } [Fact] - public async Task TestNotAfterDestructor() - { - await VerifyAbsenceAsync( + public Task TestNotAfterDestructor() + => VerifyAbsenceAsync( """ class C { ~C($$ """); - } [Fact] - public async Task TestAfterIndexer() - { - await VerifyKeywordAsync( + public Task TestAfterIndexer() + => VerifyKeywordAsync( """ class C { int this[$$ """); - } [Fact] - public async Task TestNotInObjectCreationAfterOpenParen() - { - await VerifyAbsenceAsync( + public Task TestNotInObjectCreationAfterOpenParen() + => VerifyAbsenceAsync( """ class C { void Goo() { new Bar($$ """); - } [Fact] - public async Task TestNotAfterParamsParam() - { - await VerifyAbsenceAsync( + public Task TestNotAfterParamsParam() + => VerifyAbsenceAsync( """ class C { void Goo() { new Bar(ref $$ """); - } [Fact] - public async Task TestNotAfterOutParam() - { - await VerifyAbsenceAsync( + public Task TestNotAfterOutParam() + => VerifyAbsenceAsync( """ class C { void Goo() { new Bar(out $$ """); - } [Fact] - public async Task TestNotInObjectCreationAfterComma() - { - await VerifyAbsenceAsync( + public Task TestNotInObjectCreationAfterComma() + => VerifyAbsenceAsync( """ class C { void Goo() { new Bar(baz, $$ """); - } [Fact] - public async Task TestNotInObjectCreationAfterSecondComma() - { - await VerifyAbsenceAsync( + public Task TestNotInObjectCreationAfterSecondComma() + => VerifyAbsenceAsync( """ class C { void Goo() { new Bar(baz, quux, $$ """); - } [Fact] - public async Task TestNotInObjectCreationAfterSecondNamedParam() - { - await VerifyAbsenceAsync( + public Task TestNotInObjectCreationAfterSecondNamedParam() + => VerifyAbsenceAsync( """ class C { void Goo() { new Bar(baz: 4, quux: $$ """); - } [Fact] - public async Task TestNotInInvocationExpression() - { - await VerifyAbsenceAsync( + public Task TestNotInInvocationExpression() + => VerifyAbsenceAsync( """ class C { void Goo() { Bar($$ """); - } [Fact] - public async Task TestNotInInvocationAfterComma() - { - await VerifyAbsenceAsync( + public Task TestNotInInvocationAfterComma() + => VerifyAbsenceAsync( """ class C { void Goo() { Bar(baz, $$ """); - } [Fact] - public async Task TestNotInInvocationAfterSecondComma() - { - await VerifyAbsenceAsync( + public Task TestNotInInvocationAfterSecondComma() + => VerifyAbsenceAsync( """ class C { void Goo() { Bar(baz, quux, $$ """); - } [Fact] - public async Task TestNotInInvocationAfterSecondNamedParam() - { - await VerifyAbsenceAsync( + public Task TestNotInInvocationAfterSecondNamedParam() + => VerifyAbsenceAsync( """ class C { void Goo() { Bar(baz: 4, quux: $$ """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/PartialKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/PartialKeywordRecommenderTests.cs index befa4afd857a3..8b22bfd6a7176 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/PartialKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/PartialKeywordRecommenderTests.cs @@ -13,379 +13,297 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class PartialKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInCompilationUnit() - { - await VerifyKeywordAsync( + public Task TestInCompilationUnit() + => VerifyKeywordAsync( @"$$"); - } [Fact] - public async Task TestAfterExtern() - { - await VerifyKeywordAsync( + public Task TestAfterExtern() + => VerifyKeywordAsync( """ extern alias Goo; $$ """); - } [Fact] - public async Task TestAfterUsing() - { - await VerifyKeywordAsync( + public Task TestAfterUsing() + => VerifyKeywordAsync( """ using Goo; $$ """); - } [Fact] - public async Task TestAfterGlobalUsing() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalUsing() + => VerifyKeywordAsync( """ global using Goo; $$ """); - } [Fact] - public async Task TestAfterNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterNamespace() + => VerifyKeywordAsync( """ namespace N {} $$ """); - } [Fact] - public async Task TestAfterFileScopedNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterFileScopedNamespace() + => VerifyKeywordAsync( """ namespace N; $$ """); - } [Fact] - public async Task TestAfterTypeDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterTypeDeclaration() + => VerifyKeywordAsync( """ class C {} $$ """); - } [Fact] - public async Task TestAfterDelegateDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateDeclaration() + => VerifyKeywordAsync( """ delegate void Goo(); $$ """); - } [Fact] - public async Task TestNotAfterMethod() - { - await VerifyKeywordAsync( + public Task TestNotAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterMethodInPartialType() - { - await VerifyKeywordAsync( + public Task TestAfterMethodInPartialType() + => VerifyKeywordAsync( """ partial class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterFieldInPartialClass() - { - await VerifyKeywordAsync( + public Task TestAfterFieldInPartialClass() + => VerifyKeywordAsync( """ partial class C { int i; $$ """); - } [Fact] - public async Task TestAfterPropertyInPartialClass() - { - await VerifyKeywordAsync( + public Task TestAfterPropertyInPartialClass() + => VerifyKeywordAsync( """ partial class C { int i { get; } $$ """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ global using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeGlobalUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeGlobalUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ global using Goo; """); - } [Fact] - public async Task TestAfterAssemblyAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterAssemblyAttribute() + => VerifyKeywordAsync( """ [assembly: goo] $$ """); - } [Fact] - public async Task TestAfterRootAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterRootAttribute() + => VerifyKeywordAsync( """ [goo] $$ """); - } [Fact] - public async Task TestAfterNestedAttributeInPartialClass() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttributeInPartialClass() + => VerifyKeywordAsync( """ partial class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } // This will be fixed once we have accessibility for members [Fact] - public async Task TestInsidePartialStruct() - { - await VerifyKeywordAsync( + public Task TestInsidePartialStruct() + => VerifyKeywordAsync( """ partial struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync(""" + public Task TestInsideInterface() + => VerifyKeywordAsync(""" interface I { $$ """); - } [Fact] - public async Task TestInsidePartialClass() - { - await VerifyKeywordAsync( + public Task TestInsidePartialClass() + => VerifyKeywordAsync( """ partial class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact] - public async Task TestAfterAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterAbstract() + => VerifyKeywordAsync( @"abstract $$"); - } [Fact] - public async Task TestAfterInternal() - { - await VerifyKeywordAsync( + public Task TestAfterInternal() + => VerifyKeywordAsync( @"internal $$"); - } [Fact] - public async Task TestAfterPublic() - { - await VerifyKeywordAsync( + public Task TestAfterPublic() + => VerifyKeywordAsync( @"public $$"); - } [Fact] - public async Task TestAfterStaticPublic() - { - await VerifyKeywordAsync( + public Task TestAfterStaticPublic() + => VerifyKeywordAsync( @"static public $$"); - } [Fact] - public async Task TestAfterPublicStatic() - { - await VerifyKeywordAsync( + public Task TestAfterPublicStatic() + => VerifyKeywordAsync( @"public static $$"); - } [Fact] public async Task TestNotAfterInvalidPublic() => await VerifyAbsenceAsync(@"virtual public $$"); [Fact] - public async Task TestAfterPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterPrivate() + => VerifyKeywordAsync( @"private $$"); - } [Fact] - public async Task TestAfterProtected() - { - await VerifyKeywordAsync( + public Task TestAfterProtected() + => VerifyKeywordAsync( @"protected $$"); - } [Fact] - public async Task TestAfterSealed() - { - await VerifyKeywordAsync( + public Task TestAfterSealed() + => VerifyKeywordAsync( @"sealed $$"); - } [Fact] - public async Task TestAfterStatic() - { - await VerifyKeywordAsync( + public Task TestAfterStatic() + => VerifyKeywordAsync( @"static $$"); - } [Fact] - public async Task TestNotAfterStaticInUsingDirective() - { - await VerifyAbsenceAsync( + public Task TestNotAfterStaticInUsingDirective() + => VerifyAbsenceAsync( @"using static $$"); - } [Fact] - public async Task TestNotAfterStaticInGlobalUsingDirective() - { - await VerifyAbsenceAsync( + public Task TestNotAfterStaticInGlobalUsingDirective() + => VerifyAbsenceAsync( @"global using static $$"); - } [Fact] public async Task TestNotAfterClass() @@ -396,110 +314,86 @@ public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32214")] - public async Task TestNotBetweenUsings() - { - // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBetweenUsings() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ using Goo; $$ using Bar; """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32214")] - public async Task TestNotBetweenGlobalUsings_01() - { - // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBetweenGlobalUsings_01() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ global using Goo; $$ using Bar; """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32214")] - public async Task TestNotBetweenGlobalUsings_02() - { - // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBetweenGlobalUsings_02() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ global using Goo; $$ global using Bar; """); - } [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] - public async Task TestNotAfterNestedVirtual() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedVirtual() + => VerifyAbsenceAsync(""" class C { virtual $$ """); - } [Fact] - public async Task TestNotAfterNestedOverride() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedOverride() + => VerifyAbsenceAsync(""" class C { override $$ """); - } [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] - public async Task TestAfterNestedReadOnly() - { - await VerifyKeywordAsync(""" + public Task TestAfterNestedReadOnly() + => VerifyKeywordAsync(""" class C { readonly $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578075")] - public async Task TestAfterAsync() - { - await VerifyKeywordAsync(""" + public Task TestAfterAsync() + => VerifyKeywordAsync(""" partial class C { async $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61439")] - public async Task TestAfterMemberButNonClassModifier() - { - await VerifyKeywordAsync(""" + public Task TestAfterMemberButNonClassModifier() + => VerifyKeywordAsync(""" partial class C { virtual $$ """); - } [Fact] - public async Task TestWithinExtension() - { - await VerifyAbsenceAsync( + public Task TestWithinExtension() + => VerifyAbsenceAsync( """ static class C { @@ -509,5 +403,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/PragmaKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/PragmaKeywordRecommenderTests.cs index 0cc83914e86cb..2aa83af1dd319 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/PragmaKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/PragmaKeywordRecommenderTests.cs @@ -12,74 +12,56 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class PragmaKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterHash() - { - await VerifyKeywordAsync( + public Task TestAfterHash() + => VerifyKeywordAsync( @"#$$"); - } [Fact] - public async Task TestAfterHashAndSpace() - { - await VerifyKeywordAsync( + public Task TestAfterHashAndSpace() + => VerifyKeywordAsync( @"# $$"); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/PrivateKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/PrivateKeywordRecommenderTests.cs index 42bf3f354f335..df8db9cbcafb8 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/PrivateKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/PrivateKeywordRecommenderTests.cs @@ -12,304 +12,240 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class PrivateKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalStatement_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] public async Task TestNotInCompilationUnit() => await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$"); [Fact] - public async Task TestNotAfterExtern() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotAfterExtern() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ extern alias Goo; $$ """); - } [Fact] - public async Task TestAfterExtern_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, """ + public Task TestAfterExtern_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ extern alias Goo; $$ """); - } [Fact] - public async Task TestNotAfterUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotAfterUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ using Goo; $$ """); - } [Fact] - public async Task TestAfterUsing_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, """ + public Task TestAfterUsing_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ using Goo; $$ """); - } [Fact] - public async Task TestNotAfterGlobalUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotAfterGlobalUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ global using Goo; $$ """); - } [Fact] - public async Task TestAfterGlobalUsing_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, """ + public Task TestAfterGlobalUsing_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ global using Goo; $$ """); - } [Fact] - public async Task TestNotAfterNamespace() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotAfterNamespace() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ namespace N {} $$ """); - } [Fact] - public async Task TestNotAfterFileScopedNamespace() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotAfterFileScopedNamespace() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ namespace N; $$ """); - } [Fact] - public async Task TestNotAfterTypeDeclaration() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotAfterTypeDeclaration() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ class C {} $$ """); - } [Fact] - public async Task TestNotAfterDelegateDeclaration() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotAfterDelegateDeclaration() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ delegate void Goo(); $$ """); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, """ + public Task TestNotBeforeUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ global using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeGlobalUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeGlobalUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ global using Goo; """); - } [Fact] - public async Task TestNotAfterAssemblyAttribute() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotAfterAssemblyAttribute() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ [assembly: goo] $$ """); - } [Fact] - public async Task TestAfterAssemblyAttribute_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, """ + public Task TestAfterAssemblyAttribute_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ [assembly: goo] $$ """); - } [Fact] - public async Task TestNotAfterRootAttribute() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotAfterRootAttribute() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ [goo] $$ """); - } [Fact] - public async Task TestAfterRootAttribute_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, """ + public Task TestAfterRootAttribute_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ [goo] $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync(""" + public Task TestInsideInterface() + => VerifyKeywordAsync(""" interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() @@ -321,14 +257,12 @@ public async Task TestNotAfterAbstract() // You can have an abstract private class. [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] public async Task TestNotAfterInternal() @@ -368,14 +302,12 @@ public async Task TestNotAfterSealed() // You can have a 'sealed private class'. [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] public async Task TestNotAfterStatic() @@ -386,143 +318,116 @@ public async Task TestAfterStatic_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"static $$"); [Fact] - public async Task TestAfterNestedStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStatic() + => VerifyKeywordAsync( """ class C { static $$ """); - } [Fact] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact] - public async Task TestNotAfterNestedVirtual() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedVirtual() + => VerifyAbsenceAsync(""" class C { virtual $$ """); - } [Fact] - public async Task TestNotAfterNestedOverride() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedOverride() + => VerifyAbsenceAsync(""" class C { override $$ """); - } [Fact] - public async Task TestInProperty() - { - await VerifyKeywordAsync( + public Task TestInProperty() + => VerifyKeywordAsync( """ class C { int Goo { $$ """); - } [Fact] - public async Task TestInPropertyAfterAccessor() - { - await VerifyKeywordAsync( + public Task TestInPropertyAfterAccessor() + => VerifyKeywordAsync( """ class C { int Goo { get; $$ """); - } [Fact] - public async Task TestNotInPropertyAfterAccessibility() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAfterAccessibility() + => VerifyAbsenceAsync( """ class C { int Goo { get; private $$ """); - } [Fact] - public async Task TestAfterRegion() - { - await VerifyKeywordAsync( + public Task TestAfterRegion() + => VerifyKeywordAsync( """ class C { #region Interop stuff $$ """); - } [Fact] - public async Task TestAfterTypeWithSemicolon() - { - await VerifyKeywordAsync( + public Task TestAfterTypeWithSemicolon() + => VerifyKeywordAsync( """ class C { private enum PageAccess : int { PAGE_READONLY = 0x02 }; $$ """); - } [Fact] - public async Task TestInIndexer() - { - await VerifyKeywordAsync( + public Task TestInIndexer() + => VerifyKeywordAsync( """ class C { int this[int i] { $$ """); - } [Fact] - public async Task TestInIndexerAfterAccessor() - { - await VerifyKeywordAsync( + public Task TestInIndexerAfterAccessor() + => VerifyKeywordAsync( """ class C { int this[int i] { get { } $$ """); - } [Fact] - public async Task TestNotInIndexerAfterPrivateAccessibility() - { - await VerifyAbsenceAsync( + public Task TestNotInIndexerAfterPrivateAccessibility() + => VerifyAbsenceAsync( """ class C { int this[int i] { get { } private $$ """); - } [Fact] - public async Task TestNotInIndexerAfterProtectedAccessibility() - { - await VerifyKeywordAsync( + public Task TestNotInIndexerAfterProtectedAccessibility() + => VerifyKeywordAsync( """ class C { int this[int i] { get { } protected $$ """); - } [Fact] - public async Task TestNotInIndexerAfterInternalAccessibility() - { - await VerifyAbsenceAsync( + public Task TestNotInIndexerAfterInternalAccessibility() + => VerifyAbsenceAsync( """ class C { int this[int i] { get { } internal $$ """); - } [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -534,5 +439,4 @@ static class C """, CSharpNextParseOptions, CSharpNextScriptParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/PropertyKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/PropertyKeywordRecommenderTests.cs index c62126d4c6541..625cad275c07a 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/PropertyKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/PropertyKeywordRecommenderTests.cs @@ -13,100 +13,79 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class PropertyKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInAttributeInsideClass() - { - await VerifyKeywordAsync( + public Task TestInAttributeInsideClass() + => VerifyKeywordAsync( """ class C { [$$ """); - } [Fact] - public async Task TestInAttributeAfterAttributeInsideClass() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterAttributeInsideClass() + => VerifyKeywordAsync( """ class C { [Goo] [$$ """); - } [Fact] - public async Task TestInAttributeAfterMethod() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() { } [$$ """); - } [Fact] - public async Task TestInAttributeAfterProperty() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterProperty() + => VerifyKeywordAsync( """ class C { int Goo { @@ -114,161 +93,125 @@ int Goo { } [$$ """); - } [Fact] - public async Task TestInAttributeAfterField() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterField() + => VerifyKeywordAsync( """ class C { int Goo; [$$ """); - } [Fact] - public async Task TestInAttributeAfterEvent() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterEvent() + => VerifyKeywordAsync( """ class C { event Action Goo; [$$ """); - } [Fact] - public async Task TestNotInOuterAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInOuterAttribute() + => VerifyAbsenceAsync( @"[$$"); - } [Fact] - public async Task TestNotInParameterAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInParameterAttribute() + => VerifyAbsenceAsync( """ class C { void Goo([$$ """); - } [Fact] - public async Task TestNotInPropertyAttribute1() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAttribute1() + => VerifyAbsenceAsync( """ class C { int Goo { [$$ """); - } [Fact] - public async Task TestNotInPropertyAttribute2() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAttribute2() + => VerifyAbsenceAsync( """ class C { int Goo { get { } [$$ """); - } [Fact] - public async Task TestNotInEventAttribute1() - { - await VerifyAbsenceAsync( + public Task TestNotInEventAttribute1() + => VerifyAbsenceAsync( """ class C { event Action Goo { [$$ """); - } [Fact] - public async Task TestNotInEventAttribute2() - { - await VerifyAbsenceAsync( + public Task TestNotInEventAttribute2() + => VerifyAbsenceAsync( """ class C { event Action Goo { add { } [$$ """); - } [Fact] - public async Task TestNotInTypeParameters() - { - await VerifyAbsenceAsync( + public Task TestNotInTypeParameters() + => VerifyAbsenceAsync( @"class C<[$$"); - } [Fact] - public async Task TestInInterface() - { - await VerifyKeywordAsync( + public Task TestInInterface() + => VerifyKeywordAsync( """ interface I { [$$ """); - } [Fact] - public async Task TestInStruct() - { - await VerifyKeywordAsync( + public Task TestInStruct() + => VerifyKeywordAsync( """ struct S { [$$ """); - } [Fact] - public async Task TestNotInEnum() - { - await VerifyAbsenceAsync( + public Task TestNotInEnum() + => VerifyAbsenceAsync( """ enum E { [$$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51756")] - public async Task TestInRecordPositionalParameter1() - { - await VerifyKeywordAsync("public record R([$$] string M);"); - } + public Task TestInRecordPositionalParameter1() + => VerifyKeywordAsync("public record R([$$] string M);"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51756")] - public async Task TestInRecordPositionalParameter2() - { - await VerifyKeywordAsync("public record R([$$ SomeAttribute] string M);"); - } + public Task TestInRecordPositionalParameter2() + => VerifyKeywordAsync("public record R([$$ SomeAttribute] string M);"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51756")] - public async Task TestInRecordPositionalParameter3() - { - await VerifyKeywordAsync("public record R([$$ string M);"); - } + public Task TestInRecordPositionalParameter3() + => VerifyKeywordAsync("public record R([$$ string M);"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51756")] - public async Task TestInRecordPositionalParameter4() - { - await VerifyKeywordAsync("public record R([$$"); - } + public Task TestInRecordPositionalParameter4() + => VerifyKeywordAsync("public record R([$$"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68399")] - public async Task TestInRecordParameterAttribute() - { - await VerifyKeywordAsync( + public Task TestInRecordParameterAttribute() + => VerifyKeywordAsync( """ record R([$$] int i) { } """); - } [Fact] - public async Task TestWithinExtension1() - { - await VerifyAbsenceAsync( + public Task TestWithinExtension1() + => VerifyAbsenceAsync( """ static class C { @@ -278,12 +221,10 @@ static class C } } """, CSharpNextParseOptions); - } [Fact] - public async Task TestWithinExtension2() - { - await VerifyKeywordAsync( + public Task TestWithinExtension2() + => VerifyKeywordAsync( """ static class C { @@ -293,7 +234,6 @@ static class C } } """, - CSharpNextParseOptions, - CSharpNextScriptParseOptions); - } + CSharpNextParseOptions, + CSharpNextScriptParseOptions); } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ProtectedKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ProtectedKeywordRecommenderTests.cs index cfbb354478eb3..8d7dcba6cdcfd 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ProtectedKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ProtectedKeywordRecommenderTests.cs @@ -12,239 +12,189 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ProtectedKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] public async Task TestNotInCompilationUnit() => await VerifyAbsenceAsync(@"$$"); [Fact] - public async Task TestNotAfterExtern() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterExtern() + => VerifyAbsenceAsync(""" extern alias Goo; $$ """); - } [Fact] - public async Task TestNotAfterUsing() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterUsing() + => VerifyAbsenceAsync(""" using Goo; $$ """); - } [Fact] - public async Task TestNotAfterGlobalUsing() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterGlobalUsing() + => VerifyAbsenceAsync(""" global using Goo; $$ """); - } [Fact] - public async Task TestNotAfterNamespace() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNamespace() + => VerifyAbsenceAsync(""" namespace N {} $$ """); - } [Fact] - public async Task TestNotAfterFileScopedNamespace() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterFileScopedNamespace() + => VerifyAbsenceAsync(""" namespace N; $$ """); - } [Fact] - public async Task TestNotAfterTypeDeclaration() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterTypeDeclaration() + => VerifyAbsenceAsync(""" class C {} $$ """); - } [Fact] - public async Task TestNotAfterDelegateDeclaration() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterDelegateDeclaration() + => VerifyAbsenceAsync(""" delegate void Goo(); $$ """); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync( + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync( """ $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync( + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync( """ $$ global using Goo; """); - } [Fact] - public async Task TestNotAfterAssemblyAttribute() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterAssemblyAttribute() + => VerifyAbsenceAsync(""" [assembly: goo] $$ """); - } [Fact] - public async Task TestNotAfterRootAttribute() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterRootAttribute() + => VerifyAbsenceAsync(""" [goo] $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestNotInsideStruct() - { - await VerifyAbsenceAsync(""" + public Task TestNotInsideStruct() + => VerifyAbsenceAsync(""" struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync(""" + public Task TestInsideInterface() + => VerifyKeywordAsync(""" interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() @@ -295,146 +245,118 @@ public async Task TestNotAfterStatic() => await VerifyAbsenceAsync(@"static $$"); [Fact] - public async Task TestAfterNestedStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStatic() + => VerifyKeywordAsync( """ class C { static $$ """); - } [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] - public async Task TestAfterNestedVirtual() - { - await VerifyKeywordAsync( + public Task TestAfterNestedVirtual() + => VerifyKeywordAsync( """ class C { virtual $$ """); - } [Fact] - public async Task TestAfterNestedOverride() - { - await VerifyKeywordAsync( + public Task TestAfterNestedOverride() + => VerifyKeywordAsync( """ class C { override $$ """); - } [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] - public async Task TestInProperty() - { - await VerifyKeywordAsync( + public Task TestInProperty() + => VerifyKeywordAsync( """ class C { int Goo { $$ """); - } [Fact] - public async Task TestInPropertyAfterAccessor() - { - await VerifyKeywordAsync( + public Task TestInPropertyAfterAccessor() + => VerifyKeywordAsync( """ class C { int Goo { get; $$ """); - } [Fact] - public async Task TestNotInPropertyAfterAccessibility() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAfterAccessibility() + => VerifyAbsenceAsync( """ class C { int Goo { get; protected $$ """); - } [Fact] - public async Task TestInPropertyAfterInternal() - { - await VerifyKeywordAsync( + public Task TestInPropertyAfterInternal() + => VerifyKeywordAsync( """ class C { int Goo { get; internal $$ """); - } [Fact] - public async Task TestInIndexer() - { - await VerifyKeywordAsync( + public Task TestInIndexer() + => VerifyKeywordAsync( """ class C { int this[int i] { $$ """); - } [Fact] - public async Task TestInIndexerAfterAccessor() - { - await VerifyKeywordAsync( + public Task TestInIndexerAfterAccessor() + => VerifyKeywordAsync( """ class C { int this[int i] { get { } $$ """); - } [Fact] - public async Task TestNotInIndexerAfterAccessibility() - { - await VerifyAbsenceAsync( + public Task TestNotInIndexerAfterAccessibility() + => VerifyAbsenceAsync( """ class C { int this[int i] { get { } protected $$ """); - } [Fact] - public async Task TestInIndexerAfterInternal() - { - await VerifyKeywordAsync( + public Task TestInIndexerAfterInternal() + => VerifyKeywordAsync( """ class C { int this[int i] { get { } internal $$ """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/PublicKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/PublicKeywordRecommenderTests.cs index ddc7b054b4cd9..3f95c956756fa 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/PublicKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/PublicKeywordRecommenderTests.cs @@ -13,285 +13,227 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class PublicKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInCompilationUnit() - { - await VerifyKeywordAsync( + public Task TestInCompilationUnit() + => VerifyKeywordAsync( @"$$"); - } [Fact] - public async Task TestAfterExtern() - { - await VerifyKeywordAsync( + public Task TestAfterExtern() + => VerifyKeywordAsync( """ extern alias Goo; $$ """); - } [Fact] - public async Task TestAfterUsing() - { - await VerifyKeywordAsync( + public Task TestAfterUsing() + => VerifyKeywordAsync( """ using Goo; $$ """); - } [Fact] - public async Task TestAfterGlobalUsing() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalUsing() + => VerifyKeywordAsync( """ global using Goo; $$ """); - } [Fact] - public async Task TestAfterNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterNamespace() + => VerifyKeywordAsync( """ namespace N {} $$ """); - } [Fact] - public async Task TestAfterFileScopedNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterFileScopedNamespace() + => VerifyKeywordAsync( """ namespace N; $$ """); - } [Fact] - public async Task TestAfterTypeDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterTypeDeclaration() + => VerifyKeywordAsync( """ class C {} $$ """); - } [Fact] - public async Task TestAfterDelegateDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateDeclaration() + => VerifyKeywordAsync( """ delegate void Goo(); $$ """); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ global using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeGlobalUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeGlobalUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ global using Goo; """); - } [Fact] - public async Task TestAfterAssemblyAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterAssemblyAttribute() + => VerifyKeywordAsync( """ [assembly: goo] $$ """); - } [Fact] - public async Task TestAfterRootAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterRootAttribute() + => VerifyKeywordAsync( """ [goo] $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } // This will be fixed once we have accessibility for members [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync( + public Task TestInsideInterface() + => VerifyKeywordAsync( """ interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact] - public async Task TestAfterAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterAbstract() + => VerifyKeywordAsync( @"abstract $$"); - } [Fact] public async Task TestNotAfterInternal() @@ -322,32 +264,24 @@ public async Task TestNotAfterProtected() => await VerifyAbsenceAsync(@"protected $$"); [Fact] - public async Task TestAfterSealed() - { - await VerifyKeywordAsync( + public Task TestAfterSealed() + => VerifyKeywordAsync( @"sealed $$"); - } [Fact] - public async Task TestAfterStatic() - { - await VerifyKeywordAsync( + public Task TestAfterStatic() + => VerifyKeywordAsync( @"static $$"); - } [Fact] - public async Task TestNotAfterStaticInUsingDirective() - { - await VerifyAbsenceAsync( + public Task TestNotAfterStaticInUsingDirective() + => VerifyAbsenceAsync( @"using static $$"); - } [Fact] - public async Task TestNotAfterStaticInGlobalUsingDirective() - { - await VerifyAbsenceAsync( + public Task TestNotAfterStaticInGlobalUsingDirective() + => VerifyAbsenceAsync( @"global using static $$"); - } [Fact] public async Task TestNotAfterClass() @@ -358,96 +292,76 @@ public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32214")] - public async Task TestNotBetweenUsings() - { - // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBetweenUsings() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ using Goo; $$ using Bar; """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32214")] - public async Task TestNotBetweenGlobalUsings_01() - { - // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBetweenGlobalUsings_01() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ global using Goo; $$ using Bar; """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32214")] - public async Task TestNotBetweenGlobalUsings_02() - { - // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBetweenGlobalUsings_02() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ global using Goo; $$ global using Bar; """); - } [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] - public async Task TestAfterNestedVirtual() - { - await VerifyKeywordAsync( + public Task TestAfterNestedVirtual() + => VerifyKeywordAsync( """ class C { virtual $$ """); - } [Fact] - public async Task TestAfterNestedOverride() - { - await VerifyKeywordAsync( + public Task TestAfterNestedOverride() + => VerifyKeywordAsync( """ class C { override $$ """); - } [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] - public async Task TestAfterEnum() - { - await VerifyKeywordAsync( + public Task TestAfterEnum() + => VerifyKeywordAsync( """ enum E { } $$ """); - } [Fact] - public async Task TestAfterDocComment1() - { - await VerifyKeywordAsync( + public Task TestAfterDocComment1() + => VerifyKeywordAsync( """ using System; using System.Collections.Generic; @@ -458,12 +372,10 @@ await VerifyKeywordAsync( /// $$ """); - } [Fact] - public async Task TestAfterDocComment2() - { - await VerifyKeywordAsync( + public Task TestAfterDocComment2() + => VerifyKeywordAsync( """ using System; using System.Collections.Generic; @@ -475,12 +387,10 @@ await VerifyKeywordAsync( $$ """); - } [Fact] - public async Task TestAfterDocComment3() - { - await VerifyKeywordAsync( + public Task TestAfterDocComment3() + => VerifyKeywordAsync( """ using System; using System.Collections.Generic; @@ -492,12 +402,10 @@ await VerifyKeywordAsync( $$ """); - } [Fact] - public async Task TestAfterDocComment4() - { - await VerifyKeywordAsync( + public Task TestAfterDocComment4() + => VerifyKeywordAsync( """ using System; using System.Collections.Generic; @@ -509,54 +417,44 @@ await VerifyKeywordAsync( $$ """); - } [Fact] - public async Task TestAfterComment1() - { - await VerifyKeywordAsync( + public Task TestAfterComment1() + => VerifyKeywordAsync( """ // $$ """); - } [Fact] - public async Task TestAfterComment2() - { - await VerifyKeywordAsync( + public Task TestAfterComment2() + => VerifyKeywordAsync( """ // $$ """); - } [Fact] - public async Task TestAfterComment3() - { - await VerifyKeywordAsync( + public Task TestAfterComment3() + => VerifyKeywordAsync( """ // $$ """); - } [Fact] - public async Task TestAfterComment4() - { - await VerifyKeywordAsync( + public Task TestAfterComment4() + => VerifyKeywordAsync( """ // $$ """); - } [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -568,5 +466,4 @@ static class C """, CSharpNextParseOptions, CSharpNextScriptParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ReadOnlyKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ReadOnlyKeywordRecommenderTests.cs index 247e1a150be3d..61d02897930f4 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ReadOnlyKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ReadOnlyKeywordRecommenderTests.cs @@ -13,289 +13,229 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ReadOnlyKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot() - { - await VerifyKeywordAsync( + public Task TestAtRoot() + => VerifyKeywordAsync( @"$$"); - } [Fact] - public async Task TestAfterClass() - { - await VerifyKeywordAsync( + public Task TestAfterClass() + => VerifyKeywordAsync( """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalVariableDeclaration() + => VerifyKeywordAsync( """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterExtern() - { - await VerifyKeywordAsync(""" + public Task TestAfterExtern() + => VerifyKeywordAsync(""" extern alias Goo; $$ """); - } [Fact] - public async Task TestAfterUsing() - { - await VerifyKeywordAsync(""" + public Task TestAfterUsing() + => VerifyKeywordAsync(""" using Goo; $$ """); - } [Fact] - public async Task TestAfterGlobalUsing() - { - await VerifyKeywordAsync(""" + public Task TestAfterGlobalUsing() + => VerifyKeywordAsync(""" global using Goo; $$ """); - } [Fact] - public async Task TestAfterNamespace() - { - await VerifyKeywordAsync(""" + public Task TestAfterNamespace() + => VerifyKeywordAsync(""" namespace N {} $$ """); - } [Fact] - public async Task TestAfterFileScopedNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterFileScopedNamespace() + => VerifyKeywordAsync( """ namespace N; $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestFileKeywordInsideNamespace() - { - await VerifyKeywordAsync( + public Task TestFileKeywordInsideNamespace() + => VerifyKeywordAsync( """ namespace N { file $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestFileKeywordInsideNamespaceBeforeClass() - { - await VerifyKeywordAsync( + public Task TestFileKeywordInsideNamespaceBeforeClass() + => VerifyKeywordAsync( """ namespace N { file $$ class C {} } """); - } [Fact] - public async Task TestAfterTypeDeclaration() - { - await VerifyKeywordAsync(""" + public Task TestAfterTypeDeclaration() + => VerifyKeywordAsync(""" class C {} $$ """); - } [Fact] - public async Task TestAfterDelegateDeclaration() - { - await VerifyKeywordAsync(""" + public Task TestAfterDelegateDeclaration() + => VerifyKeywordAsync(""" delegate void Goo(); $$ """); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestNotBeforeUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ global using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] - public async Task TestNotBeforeGlobalUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeGlobalUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ global using Goo; """); - } [Fact] - public async Task TestAfterAssemblyAttribute() - { - await VerifyKeywordAsync(""" + public Task TestAfterAssemblyAttribute() + => VerifyKeywordAsync(""" [assembly: goo] $$ """); - } [Fact] - public async Task TestAfterRootAttribute() - { - await VerifyKeywordAsync(""" + public Task TestAfterRootAttribute() + => VerifyKeywordAsync(""" [goo] $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync(""" + public Task TestInsideInterface() + => VerifyKeywordAsync(""" interface I { $$ """); - } [Fact] - public async Task TestNotInsideEnum() - { - await VerifyAbsenceAsync(""" + public Task TestNotInsideEnum() + => VerifyAbsenceAsync(""" enum E { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() @@ -310,14 +250,12 @@ public async Task TestAfterInternal() => await VerifyKeywordAsync(@"internal $$"); [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] public async Task TestAfterPublic() @@ -328,153 +266,125 @@ public async Task TestAfterFile() => await VerifyKeywordAsync(SourceCodeKind.Regular, @"file $$"); [Fact] - public async Task TestAfterNestedPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublic() + => VerifyKeywordAsync( """ class C { public $$ """); - } [Fact] - public async Task TestAfterPrivate() - { - await VerifyKeywordAsync(@"private $$"); - } + public Task TestAfterPrivate() + => VerifyKeywordAsync(@"private $$"); [Fact] - public async Task TestAfterNestedPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPrivate() + => VerifyKeywordAsync( """ class C { private $$ """); - } [Fact] - public async Task TestAfterProtected() - { - await VerifyKeywordAsync( + public Task TestAfterProtected() + => VerifyKeywordAsync( @"protected $$"); - } [Fact] - public async Task TestAfterNestedProtected() - { - await VerifyKeywordAsync( + public Task TestAfterNestedProtected() + => VerifyKeywordAsync( """ class C { protected $$ """); - } [Fact] public async Task TestAfterSealed() => await VerifyKeywordAsync(@"sealed $$"); [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] public async Task TestAfterStatic() => await VerifyKeywordAsync(@"static $$"); [Fact] - public async Task TestAfterNestedStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStatic() + => VerifyKeywordAsync( """ class C { static $$ """); - } [Fact] public async Task TestAfterStaticPublic() => await VerifyKeywordAsync(@"static public $$"); [Fact] - public async Task TestAfterNestedStaticPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticPublic() + => VerifyKeywordAsync( """ class C { static public $$ """); - } [Fact] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact] - public async Task TestNotAfterEvent() - { - await VerifyAbsenceAsync( + public Task TestNotAfterEvent() + => VerifyAbsenceAsync( """ class C { event $$ """); - } [Fact] - public async Task TestNotAfterConst() - { - await VerifyAbsenceAsync( + public Task TestNotAfterConst() + => VerifyAbsenceAsync( """ class C { const $$ """); - } [Fact] - public async Task TestNotAfterPublicReadOnly() - { - await VerifyAbsenceAsync( + public Task TestNotAfterPublicReadOnly() + => VerifyAbsenceAsync( """ class C { public readonly $$ """); - } [Fact] - public async Task TestNotAfterReadOnlyPartial() - { - await VerifyAbsenceAsync( + public Task TestNotAfterReadOnlyPartial() + => VerifyAbsenceAsync( """ class C { readonly partial $$ """); - } [Fact] - public async Task TestNotAfterReadOnly() - { - await VerifyAbsenceAsync( + public Task TestNotAfterReadOnly() + => VerifyAbsenceAsync( """ class C { readonly $$ """); - } [Fact] - public async Task TestNotAfterVolatile() - { - await VerifyAbsenceAsync( + public Task TestNotAfterVolatile() + => VerifyAbsenceAsync( """ class C { volatile $$ """); - } [Fact] public async Task TestAfterRef() @@ -497,73 +407,60 @@ public async Task TestAfterNewInClass() => await VerifyKeywordAsync(@"class C { new $$ }"); [Fact] - public async Task TestAfterNestedNew() - { - await VerifyKeywordAsync( + public Task TestAfterNestedNew() + => VerifyKeywordAsync( """ class C { new $$ """); - } [Fact] - public async Task TestNotInMethod() - { - await VerifyAbsenceAsync( + public Task TestNotInMethod() + => VerifyAbsenceAsync( """ class C { void Goo() { $$ """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task TestRefReadonlyAsParameterModifierInMethods() - { - await VerifyKeywordAsync(""" + public Task TestRefReadonlyAsParameterModifierInMethods() + => VerifyKeywordAsync(""" class Program { public static void Test(ref $$ p) { } } """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task TestRefReadonlyAsParameterModifierInSecondParameter() - { - await VerifyKeywordAsync(""" + public Task TestRefReadonlyAsParameterModifierInSecondParameter() + => VerifyKeywordAsync(""" class Program { public static void Test(int p1, ref $$ p2) { } } """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task TestRefReadonlyAsParameterModifierInDelegates() - { - await VerifyKeywordAsync(""" + public Task TestRefReadonlyAsParameterModifierInDelegates() + => VerifyKeywordAsync(""" public delegate int Delegate(ref $$ int p); """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [CombinatorialData] - public async Task TestRefReadonlyAsParameterModifierInLocalFunctions(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestRefReadonlyAsParameterModifierInLocalFunctions(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"void localFunc(ref $$ int p) { }", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task TestRefReadonlyAsParameterModifierInLambdaExpressions() - { - await VerifyKeywordAsync(""" + public Task TestRefReadonlyAsParameterModifierInLambdaExpressions() + => VerifyKeywordAsync(""" public delegate int Delegate(ref int p); class Program @@ -574,13 +471,11 @@ public static void Test() } } """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task TestRefReadonlyAsParameterModifierInAnonymousMethods() - { - await VerifyKeywordAsync(""" + public Task TestRefReadonlyAsParameterModifierInAnonymousMethods() + => VerifyKeywordAsync(""" public delegate int Delegate(ref int p); class Program @@ -591,13 +486,11 @@ public static void Test() } } """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task TestRefReadonlyAsModifierInMethodReturnTypes() - { - await VerifyKeywordAsync(""" + public Task TestRefReadonlyAsModifierInMethodReturnTypes() + => VerifyKeywordAsync(""" class Program { public ref $$ int Test() @@ -606,127 +499,102 @@ class Program } } """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task TestRefReadonlyAsModifierInGlobalMemberDeclaration() - { - await VerifyKeywordAsync(""" + public Task TestRefReadonlyAsModifierInGlobalMemberDeclaration() + => VerifyKeywordAsync(""" public ref $$ """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task TestRefReadonlyAsModifierInDelegateReturnType() - { - await VerifyKeywordAsync(""" + public Task TestRefReadonlyAsModifierInDelegateReturnType() + => VerifyKeywordAsync(""" public delegate ref $$ int Delegate(); class Program { } """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task TestRefReadonlyAsModifierInMemberDeclaration() - { - await VerifyKeywordAsync(""" + public Task TestRefReadonlyAsModifierInMemberDeclaration() + => VerifyKeywordAsync(""" class Program { public ref $$ int Test { get; set; } } """); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem("https://github.com/dotnet/roslyn/issues/25569")] [CombinatorialData] - public async Task TestRefReadonlyInStatementContext(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestRefReadonlyInStatementContext(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"ref $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [CombinatorialData] - public async Task TestRefReadonlyInLocalDeclaration(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestRefReadonlyInLocalDeclaration(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [CombinatorialData] - public async Task TestRefReadonlyInLocalFunction(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestRefReadonlyInLocalFunction(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [CombinatorialData] - public async Task TestRefReadonlyNotInRefExpression(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestRefReadonlyNotInRefExpression(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( @"ref int x = ref $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions, // Top level statement with script tested below, so skip it here. scriptOptions: topLevelStatement ? CSharp9ParseOptions : null); - } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] - public async Task TestRefReadonlyInRefExpression_TopLevelStatementScript() - { - // Recognized as parameter context, so readonly keyword is suggested. - await VerifyKeywordAsync(AddInsideMethod( + public Task TestRefReadonlyInRefExpression_TopLevelStatementScript() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$", topLevelStatement: true), options: CSharp9ParseOptions.WithKind(SourceCodeKind.Script)); - } [Fact] - public async Task TestInFunctionPointerTypeAfterRef() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerTypeAfterRef() + => VerifyKeywordAsync(""" class C { delegate* VerifyAbsenceAsync(""" class C { delegate*<$$ """); - } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("in")] [InlineData("out")] [InlineData("ref readonly")] - public async Task TestNotInFunctionPointerTypeAfterOtherRefModifier(string modifier) - { - await VerifyAbsenceAsync($$""" + public Task TestNotInFunctionPointerTypeAfterOtherRefModifier(string modifier) + => VerifyAbsenceAsync($$""" class C { delegate*<{{modifier}} $$ """); - } [Fact] - public async Task TestWithinExtension() - { - await VerifyAbsenceAsync( + public Task TestWithinExtension() + => VerifyAbsenceAsync( """ static class C { @@ -736,5 +604,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/RecordKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/RecordKeywordRecommenderTests.cs index bbc530670703c..bb2adcb641eb6 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/RecordKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/RecordKeywordRecommenderTests.cs @@ -14,537 +14,414 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class RecordKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInCompilationUnit() - { - await VerifyKeywordAsync( + public Task TestInCompilationUnit() + => VerifyKeywordAsync( @"$$"); - } [Fact] - public async Task TestAfterExtern() - { - await VerifyKeywordAsync( + public Task TestAfterExtern() + => VerifyKeywordAsync( """ extern alias Goo; $$ """); - } [Fact] - public async Task TestAfterUsing() - { - await VerifyKeywordAsync( + public Task TestAfterUsing() + => VerifyKeywordAsync( """ using Goo; $$ """); - } [Fact] - public async Task TestAfterGlobalUsing() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalUsing() + => VerifyKeywordAsync( """ global using Goo; $$ """); - } [Fact] - public async Task TestAfterNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterNamespace() + => VerifyKeywordAsync( """ namespace N {} $$ """); - } [Fact] - public async Task TestAfterFileScopedNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterFileScopedNamespace() + => VerifyKeywordAsync( """ namespace N; $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestFileKeywordInsideNamespace() - { - await VerifyKeywordAsync( + public Task TestFileKeywordInsideNamespace() + => VerifyKeywordAsync( """ namespace N { file $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestFileKeywordInsideNamespaceBeforeClass() - { - await VerifyKeywordAsync( + public Task TestFileKeywordInsideNamespaceBeforeClass() + => VerifyKeywordAsync( """ namespace N { file $$ class C {} } """); - } [Fact] - public async Task TestAfterTypeDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterTypeDeclaration() + => VerifyKeywordAsync( """ class C {} $$ """); - } [Fact] - public async Task TestAfterDelegateDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateDeclaration() + => VerifyKeywordAsync( """ delegate void Goo(); $$ """); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ global using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeGlobalUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeGlobalUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ global using Goo; """); - } [Fact] - public async Task TestAfterAssemblyAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterAssemblyAttribute() + => VerifyKeywordAsync( """ [assembly: goo] $$ """); - } [Fact] - public async Task TestAfterRootAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterRootAttribute() + => VerifyKeywordAsync( """ [goo] $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync(""" + public Task TestInsideInterface() + => VerifyKeywordAsync(""" interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] - public async Task TestInsideRecord1() - { - // The recommender doesn't work in record in script - // Tracked by https://github.com/dotnet/roslyn/issues/44865 - await VerifyWorkerAsync( + public Task TestInsideRecord1() + => VerifyWorkerAsync( """ record C { $$ """, absent: false, options: TestOptions.RegularPreview); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50783")] - public async Task TestInsideRecord2() - { - // The recommender doesn't work in record in script - // Tracked by https://github.com/dotnet/roslyn/issues/44865 - await VerifyWorkerAsync( + public Task TestInsideRecord2() + => VerifyWorkerAsync( """ record C { public $$ """, absent: false, options: TestOptions.RegularPreview); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50783")] - public async Task TestInsideRecord3() - { - // The recommender doesn't work in record in script - // Tracked by https://github.com/dotnet/roslyn/issues/44865 - await VerifyWorkerAsync( + public Task TestInsideRecord3() + => VerifyWorkerAsync( """ record C { [X] $$ """, absent: false, options: TestOptions.RegularPreview); - } [Fact] - public async Task TestAfterPartial() - { - await VerifyKeywordAsync( + public Task TestAfterPartial() + => VerifyKeywordAsync( @"partial $$"); - } [Fact] - public async Task TestAfterPublicRecord() - { - await VerifyAbsenceAsync( + public Task TestAfterPublicRecord() + => VerifyAbsenceAsync( @"public record $$"); - } [Fact] - public async Task TestAfterAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterAbstract() + => VerifyKeywordAsync( @"abstract $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestAfterFile() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterFile() + => VerifyKeywordAsync(SourceCodeKind.Regular, @"file $$"); - } [Fact] - public async Task TestAfterInternal() - { - await VerifyKeywordAsync( + public Task TestAfterInternal() + => VerifyKeywordAsync( @"internal $$"); - } [Fact] - public async Task TestAfterStaticPublic() - { - await VerifyKeywordAsync( + public Task TestAfterStaticPublic() + => VerifyKeywordAsync( @"static public $$"); - } [Fact] - public async Task TestAfterPublicStatic() - { - await VerifyKeywordAsync( + public Task TestAfterPublicStatic() + => VerifyKeywordAsync( @"public static $$"); - } [Fact] public async Task TestNotAfterInvalidPublic() => await VerifyAbsenceAsync(@"virtual public $$"); [Fact] - public async Task TestAfterPublic() - { - await VerifyKeywordAsync( + public Task TestAfterPublic() + => VerifyKeywordAsync( @"public $$"); - } [Fact] - public async Task TestAfterPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterPrivate() + => VerifyKeywordAsync( @"private $$"); - } [Fact] - public async Task TestAfterProtected() - { - await VerifyKeywordAsync( + public Task TestAfterProtected() + => VerifyKeywordAsync( @"protected $$"); - } [Fact] - public async Task TestAfterSealed() - { - await VerifyKeywordAsync( + public Task TestAfterSealed() + => VerifyKeywordAsync( @"sealed $$"); - } [Fact] - public async Task TestAfterStatic() - { - await VerifyKeywordAsync( + public Task TestAfterStatic() + => VerifyKeywordAsync( @"static $$"); - } [Fact] - public async Task TestNotAfterStaticInUsingDirective() - { - await VerifyAbsenceAsync( + public Task TestNotAfterStaticInUsingDirective() + => VerifyAbsenceAsync( @"using static $$"); - } [Fact] - public async Task TestNotAfterStaticInGlobalUsingDirective() - { - await VerifyAbsenceAsync( + public Task TestNotAfterStaticInGlobalUsingDirective() + => VerifyAbsenceAsync( @"global using static $$"); - } [Fact] public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32214")] - public async Task TestNotBetweenUsings() - { - // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBetweenUsings() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ using Goo; $$ using Bar; """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32214")] - public async Task TestNotBetweenGlobalUsings_01() - { - // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBetweenGlobalUsings_01() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ global using Goo; $$ using Bar; """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32214")] - public async Task TestNotBetweenGlobalUsings_02() - { - // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBetweenGlobalUsings_02() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ global using Goo; $$ global using Bar; """); - } [Fact] - public async Task TestAfterClassTypeParameterConstraint() - { - await VerifyAbsenceAsync( + public Task TestAfterClassTypeParameterConstraint() + => VerifyAbsenceAsync( @"class C where T : $$"); - } [Fact] - public async Task TestAfterClassTypeParameterConstraint2() - { - await VerifyAbsenceAsync( + public Task TestAfterClassTypeParameterConstraint2() + => VerifyAbsenceAsync( """ class C where T : $$ where U : U """); - } [Fact] - public async Task TestAfterMethodTypeParameterConstraint() - { - await VerifyAbsenceAsync( + public Task TestAfterMethodTypeParameterConstraint() + => VerifyAbsenceAsync( """ class C { void Goo() where T : $$ """); - } [Fact] - public async Task TestAfterMethodTypeParameterConstraint2() - { - await VerifyAbsenceAsync( + public Task TestAfterMethodTypeParameterConstraint2() + => VerifyAbsenceAsync( """ class C { void Goo() where T : $$ where U : T """); - } [Fact] - public async Task TestAfterNew() - { - await VerifyKeywordAsync( + public Task TestAfterNew() + => VerifyKeywordAsync( """ class C { new $$ """); - } [Fact] - public async Task TestAfterReadonly() - { - // readonly record struct is allowed. - await VerifyKeywordAsync("readonly $$"); - } + public Task TestAfterReadonly() + => VerifyKeywordAsync("readonly $$"); [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -556,5 +433,4 @@ static class C """, CSharpNextParseOptions, CSharpNextScriptParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/RefKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/RefKeywordRecommenderTests.cs index 00f4b0de67f3f..3d6d503d191ca 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/RefKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/RefKeywordRecommenderTests.cs @@ -13,586 +13,456 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class RefKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot() - { - await VerifyKeywordAsync( + public Task TestAtRoot() + => VerifyKeywordAsync( @"$$"); - } [Fact] - public async Task TestNotAfterClass() - { - await VerifyKeywordAsync( + public Task TestNotAfterClass() + => VerifyKeywordAsync( """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalVariableDeclaration() + => VerifyKeywordAsync( """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotAfterAngle() - { - await VerifyAbsenceAsync( + public Task TestNotAfterAngle() + => VerifyAbsenceAsync( @"interface IGoo<$$"); - } [Fact] - public async Task TestInterfaceTypeVarianceNotAfterIn() - { - await VerifyAbsenceAsync( + public Task TestInterfaceTypeVarianceNotAfterIn() + => VerifyAbsenceAsync( @"interface IGoo VerifyAbsenceAsync( @"interface IGoo VerifyAbsenceAsync( @"interface IGoo<[Goo]$$"); - } [Fact] - public async Task TestDelegateTypeVarianceNotAfterAngle() - { - await VerifyAbsenceAsync( + public Task TestDelegateTypeVarianceNotAfterAngle() + => VerifyAbsenceAsync( @"delegate void D<$$"); - } [Fact] - public async Task TestDelegateTypeVarianceNotAfterComma() - { - await VerifyAbsenceAsync( + public Task TestDelegateTypeVarianceNotAfterComma() + => VerifyAbsenceAsync( @"delegate void D VerifyAbsenceAsync( @"delegate void D<[Goo]$$"); - } [Fact] - public async Task TestNotRefBaseListAfterAngle() - { - await VerifyAbsenceAsync( + public Task TestNotRefBaseListAfterAngle() + => VerifyAbsenceAsync( @"interface IGoo : Bar<$$"); - } [Fact] - public async Task TestNotInGenericMethod() - { - await VerifyAbsenceAsync( + public Task TestNotInGenericMethod() + => VerifyAbsenceAsync( """ interface IGoo { void Goo<$$ """); - } [Fact] - public async Task TestNotAfterRef() - { - await VerifyAbsenceAsync( + public Task TestNotAfterRef() + => VerifyAbsenceAsync( """ class C { void Goo(ref $$ """); - } [Fact] - public async Task TestNotAfterOut() - { - await VerifyAbsenceAsync( + public Task TestNotAfterOut() + => VerifyAbsenceAsync( """ class C { void Goo(out $$ """); - } [Fact] - public async Task TestAfterMethodOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterMethodOpenParen() + => VerifyKeywordAsync( """ class C { void Goo($$ """); - } [Fact] - public async Task TestAfterMethodComma() - { - await VerifyKeywordAsync( + public Task TestAfterMethodComma() + => VerifyKeywordAsync( """ class C { void Goo(int i, $$ """); - } [Fact] - public async Task TestAfterMethodAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterMethodAttribute() + => VerifyKeywordAsync( """ class C { void Goo(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterConstructorOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorOpenParen() + => VerifyKeywordAsync( """ class C { public C($$ """); - } [Fact] - public async Task TestAfterConstructorComma() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorComma() + => VerifyKeywordAsync( """ class C { public C(int i, $$ """); - } [Fact] - public async Task TestAfterConstructorAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorAttribute() + => VerifyKeywordAsync( """ class C { public C(int i, [Goo]$$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933972")] - public async Task TestAfterThisConstructorInitializer() - { - await VerifyKeywordAsync( + public Task TestAfterThisConstructorInitializer() + => VerifyKeywordAsync( """ class C { public C():this($$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933972")] - public async Task TestAfterThisConstructorInitializerNamedArgument() - { - await VerifyKeywordAsync( + public Task TestAfterThisConstructorInitializerNamedArgument() + => VerifyKeywordAsync( """ class C { public C():this(Goo:$$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933972")] - public async Task TestAfterBaseConstructorInitializer() - { - await VerifyKeywordAsync( + public Task TestAfterBaseConstructorInitializer() + => VerifyKeywordAsync( """ class C { public C():base($$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933972")] - public async Task TestAfterBaseConstructorInitializerNamedArgument() - { - await VerifyKeywordAsync( + public Task TestAfterBaseConstructorInitializerNamedArgument() + => VerifyKeywordAsync( """ class C { public C():base(5, Goo:$$ """); - } [Fact] - public async Task TestAfterDelegateOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateOpenParen() + => VerifyKeywordAsync( @"delegate void D($$"); - } [Fact] - public async Task TestAfterDelegateComma() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateComma() + => VerifyKeywordAsync( @"delegate void D(int i, $$"); - } [Fact] - public async Task TestAfterDelegateAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateAttribute() + => VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); - } [Fact] - public async Task TestNotAfterOperator() - { - await VerifyAbsenceAsync( + public Task TestNotAfterOperator() + => VerifyAbsenceAsync( """ class C { static int operator +($$ """); - } [Fact] - public async Task TestNotAfterDestructor() - { - await VerifyAbsenceAsync( + public Task TestNotAfterDestructor() + => VerifyAbsenceAsync( """ class C { ~C($$ """); - } [Fact] - public async Task TestNotAfterIndexer() - { - await VerifyAbsenceAsync( + public Task TestNotAfterIndexer() + => VerifyAbsenceAsync( """ class C { int this[$$ """); - } [Fact] - public async Task TestInObjectCreationAfterOpenParen() - { - await VerifyKeywordAsync( + public Task TestInObjectCreationAfterOpenParen() + => VerifyKeywordAsync( """ class C { void Goo() { new Bar($$ """); - } [Fact] - public async Task TestNotAfterRefParam() - { - await VerifyAbsenceAsync( + public Task TestNotAfterRefParam() + => VerifyAbsenceAsync( """ class C { void Goo() { new Bar(ref $$ """); - } [Fact] - public async Task TestNotAfterOutParam() - { - await VerifyAbsenceAsync( + public Task TestNotAfterOutParam() + => VerifyAbsenceAsync( """ class C { void Goo() { new Bar(out $$ """); - } [Fact] - public async Task TestInObjectCreationAfterComma() - { - await VerifyKeywordAsync( + public Task TestInObjectCreationAfterComma() + => VerifyKeywordAsync( """ class C { void Goo() { new Bar(baz, $$ """); - } [Fact] - public async Task TestInObjectCreationAfterSecondComma() - { - await VerifyKeywordAsync( + public Task TestInObjectCreationAfterSecondComma() + => VerifyKeywordAsync( """ class C { void Goo() { new Bar(baz, quux, $$ """); - } [Fact] - public async Task TestInObjectCreationAfterSecondNamedParam() - { - await VerifyKeywordAsync( + public Task TestInObjectCreationAfterSecondNamedParam() + => VerifyKeywordAsync( """ class C { void Goo() { new Bar(baz: 4, quux: $$ """); - } [Fact] - public async Task TestInInvocationExpression() - { - await VerifyKeywordAsync( + public Task TestInInvocationExpression() + => VerifyKeywordAsync( """ class C { void Goo() { Bar($$ """); - } [Fact] - public async Task TestInInvocationAfterComma() - { - await VerifyKeywordAsync( + public Task TestInInvocationAfterComma() + => VerifyKeywordAsync( """ class C { void Goo() { Bar(baz, $$ """); - } [Fact] - public async Task TestInInvocationAfterSecondComma() - { - await VerifyKeywordAsync( + public Task TestInInvocationAfterSecondComma() + => VerifyKeywordAsync( """ class C { void Goo() { Bar(baz, quux, $$ """); - } [Fact] - public async Task TestInInvocationAfterSecondNamedParam() - { - await VerifyKeywordAsync( + public Task TestInInvocationAfterSecondNamedParam() + => VerifyKeywordAsync( """ class C { void Goo() { Bar(baz: 4, quux: $$ """); - } [Theory, CombinatorialData] - public async Task TestInLambdaDeclaration(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLambdaDeclaration(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"var q = ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInLambdaDeclaration2(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLambdaDeclaration2(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"var q = (ref int a, $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInLambdaDeclaration3(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLambdaDeclaration3(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"var q = (int a, $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInDelegateDeclaration(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDelegateDeclaration(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"var q = delegate ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInDelegateDeclaration2(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDelegateDeclaration2(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"var q = delegate (a, $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInDelegateDeclaration3(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDelegateDeclaration3(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"var q = delegate (int a, $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestInCrefParameterList() - { - var text = """ + public Task TestInCrefParameterList() + => VerifyKeywordAsync(""" Class c { /// void main(out goo) { } } - """; - - await VerifyKeywordAsync(text); - } + """); [Theory, CombinatorialData] - public async Task TestEmptyStatement(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestEmptyStatement(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterReturn(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterReturn(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"return $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInFor(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFor(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"for ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestNotInFor(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInFor(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( @"for (var $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInFor2(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFor2(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"for ($$;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInFor3(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFor3(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"for ($$;;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestNotAfterVar(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterVar(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( @"var $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestNotInUsing(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInUsing(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( @"using ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync( + public Task TestInsideInterface() + => VerifyKeywordAsync( """ interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestAfterPartial() => await VerifyKeywordAsync(@"partial $$"); [Fact] - public async Task TestAfterNestedPartial() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPartial() + => VerifyKeywordAsync( """ class C { partial $$ """); - } [Fact] public async Task TestAfterAbstract() => await VerifyKeywordAsync(@"abstract $$"); [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] public async Task TestAfterInternal() => await VerifyKeywordAsync(@"internal $$"); [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] public async Task TestAfterPublic() @@ -603,519 +473,414 @@ public async Task TestAfterFile() => await VerifyKeywordAsync(SourceCodeKind.Regular, @"file $$"); [Fact] - public async Task TestAfterNestedPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublic() + => VerifyKeywordAsync( """ class C { public $$ """); - } [Fact] - public async Task TestAfterPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterPrivate() + => VerifyKeywordAsync( @"private $$"); - } [Fact] - public async Task TestAfterNestedPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPrivate() + => VerifyKeywordAsync( """ class C { private $$ """); - } [Fact] - public async Task TestAfterProtected() - { - await VerifyKeywordAsync( + public Task TestAfterProtected() + => VerifyKeywordAsync( @"protected $$"); - } [Fact] - public async Task TestAfterNestedProtected() - { - await VerifyKeywordAsync( + public Task TestAfterNestedProtected() + => VerifyKeywordAsync( """ class C { protected $$ """); - } [Fact] public async Task TestAfterSealed() => await VerifyKeywordAsync(@"sealed $$"); [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] public async Task TestAfterStatic() => await VerifyKeywordAsync(@"static $$"); [Fact] - public async Task TestAfterStatic_InClass() - { - await VerifyKeywordAsync( + public Task TestAfterStatic_InClass() + => VerifyKeywordAsync( """ class C { static $$ """); - } [Fact] public async Task TestAfterStaticPublic() => await VerifyKeywordAsync(@"static public $$"); [Fact] - public async Task TestAfterNestedStaticPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticPublic() + => VerifyKeywordAsync( """ class C { static public $$ """); - } [Fact] - public async Task TestAfterDelegate() - { - await VerifyKeywordAsync( + public Task TestAfterDelegate() + => VerifyKeywordAsync( @"delegate $$"); - } [Theory, CombinatorialData] - public async Task TestNotAfterAnonymousDelegate(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterAnonymousDelegate(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( @"var q = delegate $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestNotAfterEvent() - { - await VerifyAbsenceAsync( + public Task TestNotAfterEvent() + => VerifyAbsenceAsync( """ class C { event $$ """); - } [Fact] - public async Task TestNotAfterVoid() - { - await VerifyAbsenceAsync( + public Task TestNotAfterVoid() + => VerifyAbsenceAsync( """ class C { void $$ """); - } [Fact] - public async Task TestAfterReadonly() - { - await VerifyKeywordAsync( + public Task TestAfterReadonly() + => VerifyKeywordAsync( @"readonly $$"); - } [Fact] - public async Task TestInReadonlyStruct() - { - await VerifyKeywordAsync( + public Task TestInReadonlyStruct() + => VerifyKeywordAsync( @"readonly $$ struct { }"); - } [Fact] - public async Task TestInReadonlyStruct_AfterReadonly() - { - await VerifyKeywordAsync( + public Task TestInReadonlyStruct_AfterReadonly() + => VerifyKeywordAsync( @"$$ readonly struct { }"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44423")] - public async Task TestAfterNew() - { - await VerifyAbsenceAsync( + public Task TestAfterNew() + => VerifyAbsenceAsync( @"new $$"); - } [Fact] - public async Task TestAfterNewInClass() - { - await VerifyKeywordAsync( + public Task TestAfterNewInClass() + => VerifyKeywordAsync( @"class C { new $$ }"); - } [Fact] - public async Task TestAfterNewInStruct() - { - await VerifyKeywordAsync( + public Task TestAfterNewInStruct() + => VerifyKeywordAsync( @"struct S { new $$ }"); - } [Fact] - public async Task TestAfterNestedNew() - { - await VerifyKeywordAsync( + public Task TestAfterNestedNew() + => VerifyKeywordAsync( """ class C { new $$ """); - } [Theory, CombinatorialData] - public async Task TestInUnsafeBlock(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInUnsafeBlock(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ unsafe { $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestInUnsafeMethod() - { - await VerifyKeywordAsync( + public Task TestInUnsafeMethod() + => VerifyKeywordAsync( """ class C { unsafe void Goo() { $$ """); - } [Fact] - public async Task TestInUnsafeClass() - { - await VerifyKeywordAsync( + public Task TestInUnsafeClass() + => VerifyKeywordAsync( """ unsafe class C { void Goo() { $$ """); - } [Fact] - public async Task TestInMemberArrowMethod() - { - await VerifyKeywordAsync( + public Task TestInMemberArrowMethod() + => VerifyKeywordAsync( """ unsafe class C { void Goo() { $$ """); - } [Fact] - public async Task TestInMemberArrowProperty() - { - await VerifyKeywordAsync( + public Task TestInMemberArrowProperty() + => VerifyKeywordAsync( """ class C { ref int Goo() => $$ """); - } [Fact] - public async Task TestInMemberArrowIndexer() - { - await VerifyKeywordAsync( + public Task TestInMemberArrowIndexer() + => VerifyKeywordAsync( """ class C { ref int Goo => $$ """); - } [Theory, CombinatorialData] - public async Task TestInLocalArrowMethod(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLocalArrowMethod(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @" ref int Goo() => $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInArrowLambda(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInArrowLambda(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @" D1 lambda = () => $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/21889")] [InlineData(SourceCodeKind.Regular, true)] [InlineData(SourceCodeKind.Regular, false)] [InlineData(SourceCodeKind.Script, true, Skip = "https://github.com/dotnet/roslyn/issues/44630")] [InlineData(SourceCodeKind.Script, false)] - public async Task TestInConditionalExpressionTrueBranch(SourceCodeKind sourceCodeKind, bool topLevelStatement) - { - await VerifyWorkerAsync( + public Task TestInConditionalExpressionTrueBranch(SourceCodeKind sourceCodeKind, bool topLevelStatement) + => VerifyWorkerAsync( AddInsideMethod(""" ref int x = ref true ? $$ """, topLevelStatement: topLevelStatement), absent: false, options: sourceCodeKind == SourceCodeKind.Script ? Options.Script : CSharp9ParseOptions); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/21889")] [InlineData(SourceCodeKind.Regular, true)] [InlineData(SourceCodeKind.Regular, false)] [InlineData(SourceCodeKind.Script, true, Skip = "https://github.com/dotnet/roslyn/issues/44630")] [InlineData(SourceCodeKind.Script, false)] - public async Task TestInConditionalExpressionFalseBranch(SourceCodeKind sourceCodeKind, bool topLevelStatement) - { - await VerifyWorkerAsync( + public Task TestInConditionalExpressionFalseBranch(SourceCodeKind sourceCodeKind, bool topLevelStatement) + => VerifyWorkerAsync( AddInsideMethod(""" int x = 0; ref int y = ref true ? ref x : $$ """, topLevelStatement: topLevelStatement), absent: false, options: sourceCodeKind == SourceCodeKind.Script ? Options.Script : CSharp9ParseOptions); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/22253")] [CombinatorialData] - public async Task TestInLocalMethod(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLocalMethod(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @" void Goo(int test, $$) ", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } - [Theory, CombinatorialData] - public async Task TestRefInFor(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod(""" + public Task TestRefInFor(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod(""" for ($$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestRefForeachVariable(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod(""" + public Task TestRefForeachVariable(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod(""" foreach ($$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestRefExpressionInAssignment(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod(""" + public Task TestRefExpressionInAssignment(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod(""" int x = 0; ref int y = ref x; y = $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestRefExpressionAfterReturn(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod(""" + public Task TestRefExpressionAfterReturn(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod(""" ref int x = ref (new int[1])[0]; return ref (x = $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestExtensionMethods_FirstParameter() - { - await VerifyKeywordAsync( + public Task TestExtensionMethods_FirstParameter() + => VerifyKeywordAsync( """ static class Extensions { static void Extension($$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30339")] - public async Task TestExtensionMethods_FirstParameter_AfterThisKeyword() - { - await VerifyKeywordAsync( + public Task TestExtensionMethods_FirstParameter_AfterThisKeyword() + => VerifyKeywordAsync( """ static class Extensions { static void Extension(this $$ """); - } [Fact] - public async Task TestExtensionMethods_SecondParameter() - { - await VerifyKeywordAsync( + public Task TestExtensionMethods_SecondParameter() + => VerifyKeywordAsync( """ static class Extensions { static void Extension(this int i, $$ """); - } [Fact] - public async Task TestExtensionMethods_SecondParameter_AfterThisKeyword() - { - await VerifyAbsenceAsync( + public Task TestExtensionMethods_SecondParameter_AfterThisKeyword() + => VerifyAbsenceAsync( """ static class Extensions { static void Extension(this int i, this $$ """); - } [Fact] - public async Task TestExtensionMethods_FirstParameter_NonStaticClass() - { - await VerifyKeywordAsync( + public Task TestExtensionMethods_FirstParameter_NonStaticClass() + => VerifyKeywordAsync( """ class Extensions { static void Extension($$ """); - } [Fact] - public async Task TestExtensionMethods_FirstParameter_AfterThisKeyword_NonStaticClass() - { - await VerifyAbsenceAsync( + public Task TestExtensionMethods_FirstParameter_AfterThisKeyword_NonStaticClass() + => VerifyAbsenceAsync( """ class Extensions { static void Extension(this $$ """); - } [Fact] - public async Task TestExtensionMethods_SecondParameter_NonStaticClass() - { - await VerifyKeywordAsync( + public Task TestExtensionMethods_SecondParameter_NonStaticClass() + => VerifyKeywordAsync( """ class Extensions { static void Extension(this int i, $$ """); - } [Fact] - public async Task TestExtensionMethods_SecondParameter_AfterThisKeyword_NonStaticClass() - { - await VerifyAbsenceAsync( + public Task TestExtensionMethods_SecondParameter_AfterThisKeyword_NonStaticClass() + => VerifyAbsenceAsync( """ class Extensions { static void Extension(this int i, this $$ """); - } [Fact] - public async Task TestExtensionMethods_FirstParameter_NonStaticMethod() - { - await VerifyKeywordAsync( + public Task TestExtensionMethods_FirstParameter_NonStaticMethod() + => VerifyKeywordAsync( """ static class Extensions { void Extension($$ """); - } [Fact] - public async Task TestExtensionMethods_FirstParameter_AfterThisKeyword_NonStaticMethod() - { - await VerifyAbsenceAsync( + public Task TestExtensionMethods_FirstParameter_AfterThisKeyword_NonStaticMethod() + => VerifyAbsenceAsync( """ static class Extensions { void Extension(this $$ """); - } [Fact] - public async Task TestExtensionMethods_SecondParameter_NonStaticMethod() - { - await VerifyKeywordAsync( + public Task TestExtensionMethods_SecondParameter_NonStaticMethod() + => VerifyKeywordAsync( """ static class Extensions { void Extension(this int i, $$ """); - } [Fact] - public async Task TestExtensionMethods_SecondParameter_AfterThisKeyword_NonStaticMethod() - { - await VerifyAbsenceAsync( + public Task TestExtensionMethods_SecondParameter_AfterThisKeyword_NonStaticMethod() + => VerifyAbsenceAsync( """ static class Extensions { void Extension(this int i, this $$ """); - } [Fact] - public async Task TestInFunctionPointerTypeNoExistingModifiers() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerTypeNoExistingModifiers() + => VerifyKeywordAsync(""" class C { delegate*<$$ """); - } [Theory] [InlineData("in")] [InlineData("out")] [InlineData("ref")] [InlineData("ref readonly")] - public async Task TestNotInFunctionPointerTypeExistingModifiers(string modifier) - { - await VerifyAbsenceAsync($@" -class C -{{ - delegate*<{modifier} $$"); - } + public Task TestNotInFunctionPointerTypeExistingModifiers(string modifier) + => VerifyAbsenceAsync($$""" + class C + { + delegate*<{{modifier}} $$ + """); [Fact] - public async Task TestAfterNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterNamespace() + => VerifyKeywordAsync( """ namespace N { } $$ """); - } [Fact] - public async Task TestAfterFileScopedNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterFileScopedNamespace() + => VerifyKeywordAsync( """ namespace N; $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestFileKeywordInsideNamespace() - { - await VerifyKeywordAsync( + public Task TestFileKeywordInsideNamespace() + => VerifyKeywordAsync( """ namespace N { file $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestFileKeywordInsideNamespaceBeforeClass() - { - await VerifyKeywordAsync( + public Task TestFileKeywordInsideNamespaceBeforeClass() + => VerifyKeywordAsync( """ namespace N { file $$ class C {} } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58906")] - public async Task TestInPotentialLambdaParamListParsedAsCastOnDifferentLines() - { - await VerifyKeywordAsync( + public Task TestInPotentialLambdaParamListParsedAsCastOnDifferentLines() + => VerifyKeywordAsync( """ class C { @@ -1126,12 +891,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58906")] - public async Task TestInPotentialLambdaParamListParsedAsCastOnSameLine() - { - await VerifyKeywordAsync( + public Task TestInPotentialLambdaParamListParsedAsCastOnSameLine() + => VerifyKeywordAsync( """ class C { @@ -1141,12 +904,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestAfterScoped() - { - await VerifyKeywordAsync( + public Task TestAfterScoped() + => VerifyKeywordAsync( """ class C { @@ -1156,34 +917,28 @@ void M() } } """); - } [Fact] - public async Task TestInParameterAfterScoped() - { - await VerifyKeywordAsync(""" + public Task TestInParameterAfterScoped() + => VerifyKeywordAsync(""" class C { void M(scoped $$) } """); - } [Fact] - public async Task TestInParameterAfterThisScoped() - { - await VerifyKeywordAsync(""" + public Task TestInParameterAfterThisScoped() + => VerifyKeywordAsync(""" static class C { static void M(this scoped $$) } """); - } [Fact] - public async Task TestInAnonymousMethodParameterAfterScoped() - { - await VerifyKeywordAsync(""" + public Task TestInAnonymousMethodParameterAfterScoped() + => VerifyKeywordAsync(""" class C { void M() @@ -1192,203 +947,161 @@ void M() } } """); - } [Fact] - public async Task TestAfterAllowsInTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterAllowsInTypeParameterConstraint() + => VerifyKeywordAsync( """ class C where T : allows $$ """); - } [Fact] - public async Task TestAfterAllowsInTypeParameterConstraint2() - { - await VerifyKeywordAsync( + public Task TestAfterAllowsInTypeParameterConstraint2() + => VerifyKeywordAsync( """ class C where T : allows $$ where U : U """); - } [Fact] - public async Task TestAfterAllowsInMethodTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterAllowsInMethodTypeParameterConstraint() + => VerifyKeywordAsync( """ class C { void Goo() where T : allows $$ """); - } [Fact] - public async Task TestAfterAllowsInMethodTypeParameterConstraint2() - { - await VerifyKeywordAsync( + public Task TestAfterAllowsInMethodTypeParameterConstraint2() + => VerifyKeywordAsync( """ class C { void Goo() where T : allows $$ where U : T """); - } [Fact] - public async Task TestNotAfterClassTypeParameterConstraint() - { - await VerifyAbsenceAsync( + public Task TestNotAfterClassTypeParameterConstraint() + => VerifyAbsenceAsync( """ class C where T : class, allows $$ """); - } [Fact] - public async Task TestAfterStructTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterStructTypeParameterConstraint() + => VerifyKeywordAsync( """ class C where T : struct, allows $$ """); - } [Fact] - public async Task TestAfterSimpleTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterSimpleTypeParameterConstraint() + => VerifyKeywordAsync( """ class C where T : IGoo, allows $$ """); - } [Fact] - public async Task TestAfterConstructorTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorTypeParameterConstraint() + => VerifyKeywordAsync( """ class C where T : new(), allows $$ """); - } [Fact] - public async Task TestNotAfterGenericNameInTypeParameterConstraint() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGenericNameInTypeParameterConstraint() + => VerifyAbsenceAsync( """ class C where T : allows $$ """); - } [Fact] - public async Task TestNotAfterGenericNameInTypeParameterConstraint2() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGenericNameInTypeParameterConstraint2() + => VerifyAbsenceAsync( """ class C where T : allows $$ where U : U """); - } [Fact] - public async Task TestNotAfterGenericNameAfterClassTypeParameterConstraint() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGenericNameAfterClassTypeParameterConstraint() + => VerifyAbsenceAsync( """ class C where T : class, allows $$ """); - } [Fact] - public async Task TestNotAfterGenericNameAfterStructTypeParameterConstraint() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGenericNameAfterStructTypeParameterConstraint() + => VerifyAbsenceAsync( """ class C where T : struct, allows $$ """); - } [Fact] - public async Task TestNotAfterGenericNameAfterSimpleTypeParameterConstraint() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGenericNameAfterSimpleTypeParameterConstraint() + => VerifyAbsenceAsync( """ class C where T : IGoo, allows $$ """); - } [Fact] - public async Task TestNotAfterGenericNameAfterConstructorTypeParameterConstraint() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGenericNameAfterConstructorTypeParameterConstraint() + => VerifyAbsenceAsync( """ class C where T : new(), allows $$ """); - } [Fact] - public async Task TestNotAfterRefInTypeParameterConstraint() - { - await VerifyAbsenceAsync( + public Task TestNotAfterRefInTypeParameterConstraint() + => VerifyAbsenceAsync( """ class C where T : allows ref $$ """); - } [Fact] - public async Task TestNotAfterRefInTypeParameterConstraint2() - { - await VerifyAbsenceAsync( + public Task TestNotAfterRefInTypeParameterConstraint2() + => VerifyAbsenceAsync( """ class C where T : allows ref $$ where U : U """); - } [Fact] - public async Task TestNotAfterRefAfterClassTypeParameterConstraint() - { - await VerifyAbsenceAsync( + public Task TestNotAfterRefAfterClassTypeParameterConstraint() + => VerifyAbsenceAsync( """ class C where T : class, allows ref $$ """); - } [Fact] - public async Task TestNotAfterRefAfterStructTypeParameterConstraint() - { - await VerifyAbsenceAsync( + public Task TestNotAfterRefAfterStructTypeParameterConstraint() + => VerifyAbsenceAsync( """ class C where T : struct, allows ref $$ """); - } [Fact] - public async Task TestNotAfterRefAfterSimpleTypeParameterConstraint() - { - await VerifyAbsenceAsync( + public Task TestNotAfterRefAfterSimpleTypeParameterConstraint() + => VerifyAbsenceAsync( """ class C where T : IGoo, allows ref $$ """); - } [Fact] - public async Task TestNotAfterRefAfterConstructorTypeParameterConstraint() - { - await VerifyAbsenceAsync( + public Task TestNotAfterRefAfterConstructorTypeParameterConstraint() + => VerifyAbsenceAsync( """ class C where T : new(), allows ref $$ """); - } [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -1398,5 +1111,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ReferenceKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ReferenceKeywordRecommenderTests.cs index 2218448a39670..a38b411057f6a 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ReferenceKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ReferenceKeywordRecommenderTests.cs @@ -12,139 +12,107 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ReferenceKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync( + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync( @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync( + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync( """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync( """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestNotAfterHash() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotAfterHash() + => VerifyAbsenceAsync(SourceCodeKind.Regular, @"#$$"); - } [Fact] - public async Task TestAfterHash_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterHash_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"#$$"); - } [Fact] - public async Task TestNotAfterHashAndSpace() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotAfterHashAndSpace() + => VerifyAbsenceAsync(SourceCodeKind.Regular, @"# $$"); - } [Fact] - public async Task TestAfterHashAndSpace_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterHashAndSpace_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"# $$"); - } [Fact] - public async Task TestNestedPreprocessor() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestNestedPreprocessor() + => VerifyKeywordAsync(SourceCodeKind.Script, """ #if true #$$ #endif """); - } [Fact] - public async Task TestBeforeUsing() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestBeforeUsing() + => VerifyKeywordAsync(SourceCodeKind.Script, """ #$$ using System; """); - } [Fact] - public async Task TestBeforeGlobalUsing() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestBeforeGlobalUsing() + => VerifyKeywordAsync(SourceCodeKind.Script, """ #$$ global using System; """); - } [Fact] - public async Task TestNotAfterUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterUsing() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ using System; #$$ """); - } [Fact] - public async Task TestNotAfterGlobalUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalUsing() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ global using System; #$$ """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/RegionKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/RegionKeywordRecommenderTests.cs index 592a6be9a7cf9..97d5fbaccfbd9 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/RegionKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/RegionKeywordRecommenderTests.cs @@ -12,74 +12,56 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class RegionKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterHash() - { - await VerifyKeywordAsync( + public Task TestAfterHash() + => VerifyKeywordAsync( @"#$$"); - } [Fact] - public async Task TestAfterHashAndSpace() - { - await VerifyKeywordAsync( + public Task TestAfterHashAndSpace() + => VerifyKeywordAsync( @"# $$"); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/RemoveKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/RemoveKeywordRecommenderTests.cs index 799bf3cdbc6ab..b864feba8d437 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/RemoveKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/RemoveKeywordRecommenderTests.cs @@ -12,140 +12,110 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class RemoveKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterEvent() - { - await VerifyKeywordAsync( + public Task TestAfterEvent() + => VerifyKeywordAsync( """ class C { event Goo Bar { $$ """); - } [Fact] - public async Task TestAfterAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterAttribute() + => VerifyKeywordAsync( """ class C { event Goo Bar { [Bar] $$ """); - } [Fact] - public async Task TestAfterAdd() - { - await VerifyKeywordAsync( + public Task TestAfterAdd() + => VerifyKeywordAsync( """ class C { event Goo Bar { add { } $$ """); - } [Fact] - public async Task TestAfterAddAndAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterAddAndAttribute() + => VerifyKeywordAsync( """ class C { event Goo Bar { add { } [Bar] $$ """); - } [Fact] - public async Task TestAfterAddBlock() - { - await VerifyKeywordAsync( + public Task TestAfterAddBlock() + => VerifyKeywordAsync( """ class C { event Goo Bar { add { } $$ """); - } [Fact] - public async Task TestNotAfterRemoveKeyword() - { - await VerifyAbsenceAsync( + public Task TestNotAfterRemoveKeyword() + => VerifyAbsenceAsync( """ class C { event Goo Bar { remove $$ """); - } [Fact] - public async Task TestNotAfterRemoveAccessor() - { - await VerifyAbsenceAsync( + public Task TestNotAfterRemoveAccessor() + => VerifyAbsenceAsync( """ class C { event Goo Bar { remove { } $$ """); - } [Fact] - public async Task TestNotInProperty() - { - await VerifyAbsenceAsync( + public Task TestNotInProperty() + => VerifyAbsenceAsync( """ class C { int Goo { $$ """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/RestoreKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/RestoreKeywordRecommenderTests.cs index 06b7370aa10fe..5bd413d244950 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/RestoreKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/RestoreKeywordRecommenderTests.cs @@ -12,62 +12,48 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class RestoreKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] public async Task TestNotAfterHash() @@ -78,26 +64,20 @@ public async Task TestNotAfterPragma() => await VerifyAbsenceAsync(@"#pragma $$"); [Fact] - public async Task TestAfterPragmaWarning() - { - await VerifyKeywordAsync( + public Task TestAfterPragmaWarning() + => VerifyKeywordAsync( @"#pragma warning $$"); - } [Fact] - public async Task TestAfterNullable() - { - await VerifyKeywordAsync( + public Task TestAfterNullable() + => VerifyKeywordAsync( @"#nullable $$"); - } [Fact] - public async Task TestNotAfterNullableAndNewline() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNullableAndNewline() + => VerifyAbsenceAsync(""" #nullable $$ """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ReturnKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ReturnKeywordRecommenderTests.cs index ab22e8f34a362..c069d1de987b9 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ReturnKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ReturnKeywordRecommenderTests.cs @@ -13,139 +13,106 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ReturnKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57121")] - public async Task TestAtRoot_Regular() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAtRoot_Regular() + => VerifyKeywordAsync(SourceCodeKind.Regular, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57121")] - public async Task TestAfterClass_Regular() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterClass_Regular() + => VerifyKeywordAsync(SourceCodeKind.Regular, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57121")] - public async Task TestAfterGlobalStatement_Regular() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterGlobalStatement_Regular() + => VerifyKeywordAsync(SourceCodeKind.Regular, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57121")] - public async Task TestAfterGlobalVariableDeclaration_Regular() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterGlobalVariableDeclaration_Regular() + => VerifyKeywordAsync(SourceCodeKind.Regular, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestIncompleteStatementAttributeList() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestIncompleteStatementAttributeList() + => VerifyKeywordAsync(AddInsideMethod( @"[$$")); - } [Fact] - public async Task TestStatementAttributeList() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestStatementAttributeList() + => VerifyKeywordAsync(AddInsideMethod( @"[$$Attr]")); - } [Fact] - public async Task TestLocalFunctionAttributeList() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestLocalFunctionAttributeList() + => VerifyKeywordAsync(AddInsideMethod( @"[$$Attr] void local1() { }")); - } [Fact] - public async Task TestNotInLocalFunctionParameterAttributeList() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInLocalFunctionParameterAttributeList() + => VerifyAbsenceAsync(AddInsideMethod( @"void local1([$$Attr] int i) { }")); - } [Fact] - public async Task TestNotInLocalFunctionTypeParameterAttributeList() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInLocalFunctionTypeParameterAttributeList() + => VerifyAbsenceAsync(AddInsideMethod( @"void local1<[$$Attr] T>() { }")); - } [Fact] - public async Task TestEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterAwait() - { - await VerifyAbsenceAsync( + public Task TestAfterAwait() + => VerifyAbsenceAsync( """ class C { @@ -155,101 +122,81 @@ async void M() } } """); - } [Fact] - public async Task TestBeforeStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBeforeStatement() + => VerifyKeywordAsync(AddInsideMethod( """ $$ return true; """)); - } [Fact] - public async Task TestAfterStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterStatement() + => VerifyKeywordAsync(AddInsideMethod( """ return true; $$ """)); - } [Fact] - public async Task TestAfterBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBlock() + => VerifyKeywordAsync(AddInsideMethod( """ if (true) { } $$ """)); - } [Fact] - public async Task TestNotAfterReturn() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterReturn() + => VerifyAbsenceAsync(AddInsideMethod( @"return $$")); - } [Fact] - public async Task TestAfterYield() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterYield() + => VerifyKeywordAsync(AddInsideMethod( @"yield $$")); - } [Fact] - public async Task TestNotInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotInClass() + => VerifyAbsenceAsync(""" class C { $$ } """); - } [Fact] - public async Task TestInAttributeInsideClass() - { - await VerifyKeywordAsync( + public Task TestInAttributeInsideClass() + => VerifyKeywordAsync( """ class C { [$$ """); - } [Fact] - public async Task TestInAttributeAfterAttributeInsideClass() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterAttributeInsideClass() + => VerifyKeywordAsync( """ class C { [Goo] [$$ """); - } [Fact] - public async Task TestInAttributeAfterMethod() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() { } [$$ """); - } [Fact] - public async Task TestInAttributeAfterProperty() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterProperty() + => VerifyKeywordAsync( """ class C { int Goo { @@ -257,209 +204,167 @@ int Goo { } [$$ """); - } [Fact] - public async Task TestInAttributeAfterField() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterField() + => VerifyKeywordAsync( """ class C { int Goo; [$$ """); - } [Fact] - public async Task TestInAttributeAfterEvent() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterEvent() + => VerifyKeywordAsync( """ class C { event Action Goo; [$$ """); - } [Fact] - public async Task TestNotInOuterAttribute() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotInOuterAttribute() + => VerifyAbsenceAsync(SourceCodeKind.Regular, @"[$$"); - } [Fact] - public async Task TestInOuterAttributeScripting() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestInOuterAttributeScripting() + => VerifyKeywordAsync(SourceCodeKind.Script, @"[$$"); - } [Fact] - public async Task TestNotInParameterAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInParameterAttribute() + => VerifyAbsenceAsync( """ class C { void Goo([$$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71200")] - public async Task TestInPropertyAttribute() - { - await VerifyKeywordAsync( + public Task TestInPropertyAttribute() + => VerifyKeywordAsync( """ class C { int Goo { [$$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71200")] - public async Task TestInEventAttribute() - { - await VerifyKeywordAsync( + public Task TestInEventAttribute() + => VerifyKeywordAsync( """ class C { event Action Goo { [$$ """); - } [Fact] - public async Task TestNotInClassReturnParameters() - { - await VerifyAbsenceAsync( + public Task TestNotInClassReturnParameters() + => VerifyAbsenceAsync( @"class C<[$$"); - } [Fact] - public async Task TestNotInDelegateReturnParameters() - { - await VerifyAbsenceAsync( + public Task TestNotInDelegateReturnParameters() + => VerifyAbsenceAsync( @"delegate void D<[$$"); - } [Fact] - public async Task TestNotInMethodReturnParameters() - { - await VerifyAbsenceAsync( + public Task TestNotInMethodReturnParameters() + => VerifyAbsenceAsync( """ class C { void M<[$$ """); - } [Fact] - public async Task TestInInterface() - { - await VerifyKeywordAsync( + public Task TestInInterface() + => VerifyKeywordAsync( """ interface I { [$$ """); - } [Fact] - public async Task TestInStruct() - { - await VerifyKeywordAsync( + public Task TestInStruct() + => VerifyKeywordAsync( """ struct S { [$$ """); - } [Fact] - public async Task TestNotInEnum() - { - await VerifyAbsenceAsync( + public Task TestNotInEnum() + => VerifyAbsenceAsync( """ enum E { [$$ """); - } [Fact] - public async Task TestAfterElse() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterElse() + => VerifyKeywordAsync(AddInsideMethod( """ if (goo) { } else $$ """)); - } [Fact] - public async Task TestAfterElseClause() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterElseClause() + => VerifyKeywordAsync(AddInsideMethod( """ if (goo) { } else { } $$ """)); - } [Fact] - public async Task TestAfterFixed() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterFixed() + => VerifyKeywordAsync(AddInsideMethod( """ fixed (byte* pResult = result) { } $$ """)); - } [Fact] - public async Task TestAfterSwitch() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterSwitch() + => VerifyKeywordAsync(AddInsideMethod( """ switch (goo) { } $$ """)); - } [Fact] - public async Task TestAfterCatch() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterCatch() + => VerifyKeywordAsync(AddInsideMethod( """ try { } catch { } $$ """)); - } [Fact] - public async Task TestAfterFinally() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterFinally() + => VerifyKeywordAsync(AddInsideMethod( """ try { } finally { } $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68399")] - public async Task TestNotInRecordParameterAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInRecordParameterAttribute() + => VerifyAbsenceAsync( """ record R([$$] int i) { } """); - } [Fact] - public async Task TestWithinExtension1() - { - await VerifyAbsenceAsync( + public Task TestWithinExtension1() + => VerifyAbsenceAsync( """ static class C { @@ -469,14 +374,12 @@ static class C } } """, - CSharpNextParseOptions, - CSharpNextScriptParseOptions); - } + CSharpNextParseOptions, + CSharpNextScriptParseOptions); [Fact] - public async Task TestWithinExtension2() - { - await VerifyKeywordAsync( + public Task TestWithinExtension2() + => VerifyKeywordAsync( """ static class C { @@ -486,7 +389,6 @@ static class C } } """, - CSharpNextParseOptions, - CSharpNextScriptParseOptions); - } + CSharpNextParseOptions, + CSharpNextScriptParseOptions); } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/SByteKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/SByteKeywordRecommenderTests.cs index 0d06369238813..26c1fbc4b2c16 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/SByteKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/SByteKeywordRecommenderTests.cs @@ -13,712 +13,549 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class SByteKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsing() - { - await VerifyAbsenceAsync( + public Task TestNotInUsing() + => VerifyAbsenceAsync( @"using $$"); - } [Fact] - public async Task TestInUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInUsingAlias() + => VerifyKeywordAsync( @"using Goo = $$"); - } [Fact] - public async Task TestInGlobalUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInGlobalUsingAlias() + => VerifyKeywordAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestAfterStackAlloc() - { - await VerifyKeywordAsync( + public Task TestAfterStackAlloc() + => VerifyKeywordAsync( """ class C { int* goo = stackalloc $$ """); - } [Fact] - public async Task TestInFixedStatement() - { - await VerifyKeywordAsync( + public Task TestInFixedStatement() + => VerifyKeywordAsync( @"fixed ($$"); - } [Fact] - public async Task TestInDelegateReturnType() - { - await VerifyKeywordAsync( + public Task TestInDelegateReturnType() + => VerifyKeywordAsync( @"public delegate $$"); - } [Fact] - public async Task TestInCastType() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); - } [Fact] - public async Task TestInCastType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType2() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); - } [Fact] - public async Task TestAfterConstInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterConstInMemberContext() + => VerifyKeywordAsync( """ class C { const $$ """); - } [Fact] - public async Task TestAfterRefInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefInMemberContext() + => VerifyKeywordAsync( """ class C { ref $$ """); - } [Fact] - public async Task TestAfterRefReadonlyInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyInMemberContext() + => VerifyKeywordAsync( """ class C { ref readonly $$ """); - } [Fact] - public async Task TestAfterConstInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"const $$")); - } [Fact] - public async Task TestAfterRefInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$")); - } [Fact] - public async Task TestAfterRefReadonlyInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); - } [Fact] - public async Task TestAfterConstLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); - } [Fact] - public async Task TestAfterRefReadonlyLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); - } [Fact] - public async Task TestAfterRefReadonlyLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); - } [Fact] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } [Fact] - public async Task TestInEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestEnumBaseTypes() - { - await VerifyKeywordAsync( + public Task TestEnumBaseTypes() + => VerifyKeywordAsync( @"enum E : $$"); - } [Fact] - public async Task TestInGenericType1() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType1() + => VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); - } [Fact] - public async Task TestInGenericType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType2() + => VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList,$$")); - } [Fact] - public async Task TestNotInBaseList() - { - await VerifyAbsenceAsync( + public Task TestNotInBaseList() + => VerifyAbsenceAsync( @"class C : $$"); - } [Fact] - public async Task TestInGenericType_InBaseList() - { - await VerifyKeywordAsync( + public Task TestInGenericType_InBaseList() + => VerifyKeywordAsync( @"class C : IList<$$"); - } [Fact] - public async Task TestAfterIs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); - } [Fact] - public async Task TestAfterAs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterAs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync( + public Task TestInsideInterface() + => VerifyKeywordAsync( """ interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact] - public async Task TestAfterNestedPartial() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPartial() + => VerifyKeywordAsync( """ class C { partial $$ """); - } [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] - public async Task TestAfterNestedStaticPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticPublic() + => VerifyKeywordAsync( """ class C { static public $$ """); - } [Fact] - public async Task TestAfterNestedPublicStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublicStatic() + => VerifyKeywordAsync( """ class C { public static $$ """); - } [Fact] - public async Task TestAfterVirtualPublic() - { - await VerifyKeywordAsync( + public Task TestAfterVirtualPublic() + => VerifyKeywordAsync( """ class C { virtual public $$ """); - } [Fact] - public async Task TestAfterNestedPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublic() + => VerifyKeywordAsync( """ class C { public $$ """); - } [Fact] - public async Task TestAfterNestedPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPrivate() + => VerifyKeywordAsync( """ class C { private $$ """); - } [Fact] - public async Task TestAfterNestedProtected() - { - await VerifyKeywordAsync( + public Task TestAfterNestedProtected() + => VerifyKeywordAsync( """ class C { protected $$ """); - } [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] - public async Task TestAfterNestedStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStatic() + => VerifyKeywordAsync( """ class C { static $$ """); - } [Fact] - public async Task TestInLocalVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLocalVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInForVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"for ($$")); - } [Fact] - public async Task TestInForeachVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForeachVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); - } [Fact] - public async Task TestInUsingVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInUsingVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"using ($$")); - } [Fact] - public async Task TestInFromVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFromVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); - } [Fact] - public async Task TestInJoinVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInJoinVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from a in b join $$ """)); - } [Fact] - public async Task TestAfterMethodOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterMethodOpenParen() + => VerifyKeywordAsync( """ class C { void Goo($$ """); - } [Fact] - public async Task TestAfterMethodComma() - { - await VerifyKeywordAsync( + public Task TestAfterMethodComma() + => VerifyKeywordAsync( """ class C { void Goo(int i, $$ """); - } [Fact] - public async Task TestAfterMethodAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterMethodAttribute() + => VerifyKeywordAsync( """ class C { void Goo(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterConstructorOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorOpenParen() + => VerifyKeywordAsync( """ class C { public C($$ """); - } [Fact] - public async Task TestAfterConstructorComma() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorComma() + => VerifyKeywordAsync( """ class C { public C(int i, $$ """); - } [Fact] - public async Task TestAfterConstructorAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorAttribute() + => VerifyKeywordAsync( """ class C { public C(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterDelegateOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateOpenParen() + => VerifyKeywordAsync( @"delegate void D($$"); - } [Fact] - public async Task TestAfterDelegateComma() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateComma() + => VerifyKeywordAsync( @"delegate void D(int i, $$"); - } [Fact] - public async Task TestAfterDelegateAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateAttribute() + => VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); - } [Fact] - public async Task TestAfterThis() - { - await VerifyKeywordAsync( + public Task TestAfterThis() + => VerifyKeywordAsync( """ static class C { public static void Goo(this $$ """); - } [Fact] - public async Task TestAfterRef() - { - await VerifyKeywordAsync( + public Task TestAfterRef() + => VerifyKeywordAsync( """ class C { void Goo(ref $$ """); - } [Fact] - public async Task TestAfterOut() - { - await VerifyKeywordAsync( + public Task TestAfterOut() + => VerifyKeywordAsync( """ class C { void Goo(out $$ """); - } [Fact] - public async Task TestAfterLambdaRef() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaRef() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (ref $$ """); - } [Fact] - public async Task TestAfterLambdaOut() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaOut() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (out $$ """); - } [Fact] - public async Task TestAfterParams() - { - await VerifyKeywordAsync( + public Task TestAfterParams() + => VerifyKeywordAsync( """ class C { void Goo(params $$ """); - } [Fact] - public async Task TestInImplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInImplicitOperator() + => VerifyKeywordAsync( """ class C { public static implicit operator $$ """); - } [Fact] - public async Task TestInExplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInExplicitOperator() + => VerifyKeywordAsync( """ class C { public static explicit operator $$ """); - } [Fact] - public async Task TestAfterIndexerBracket() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracket() + => VerifyKeywordAsync( """ class C { int this[$$ """); - } [Fact] - public async Task TestAfterIndexerBracketComma() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracketComma() + => VerifyKeywordAsync( """ class C { int this[int i, $$ """); - } [Fact] - public async Task TestAfterNewInExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterNewInExpression() + => VerifyKeywordAsync(AddInsideMethod( @"new $$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInTypeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInTypeOf() + => VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInDefault() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDefault() + => VerifyKeywordAsync(AddInsideMethod( @"default($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInSizeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInSizeOf() + => VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -726,12 +563,10 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] - public async Task TestInCrefContext() - { - await VerifyKeywordAsync(""" + public Task TestInCrefContext() + => VerifyKeywordAsync(""" class Program { /// @@ -741,16 +576,13 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] - public async Task TestInCrefContextNotAfterDot() - { - await VerifyAbsenceAsync(""" + public Task TestInCrefContextNotAfterDot() + => VerifyAbsenceAsync(""" /// class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] public async Task TestNotAfterAsync() @@ -761,19 +593,16 @@ public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1468")] - public async Task TestNotInCrefTypeParameter() - { - await VerifyAbsenceAsync(""" + public Task TestNotInCrefTypeParameter() + => VerifyAbsenceAsync(""" using System; /// class C { } """); - } [Fact] - public async Task Preselection() - { - await VerifyKeywordAsync(""" + public Task Preselection() + => VerifyKeywordAsync(""" class Program { static void Main(string[] args) @@ -783,23 +612,19 @@ static void Main(string[] args) static void Helper(sbyte x) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinType() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinType() + => VerifyKeywordAsync(""" class Program { ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinMember() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinMember() + => VerifyKeywordAsync(""" class Program { void Method() @@ -808,82 +633,66 @@ void Method() } } """); - } [Fact] - public async Task TestInFunctionPointerType() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerType() + => VerifyKeywordAsync(""" class C { delegate*<$$ """); - } [Fact] - public async Task TestInFunctionPointerTypeAfterComma() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerTypeAfterComma() + => VerifyKeywordAsync(""" class C { delegate* VerifyKeywordAsync(""" class C { delegate* VerifyAbsenceAsync(""" class C { delegate*$$ """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/53585")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithoutAsync))] - public async Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) - { - await VerifyKeywordAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) + => VerifyKeywordAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithAsync))] - public async Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) - { - await VerifyAbsenceAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) + => VerifyAbsenceAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64585")] - public async Task TestAfterRequired() - { - await VerifyKeywordAsync(""" + public Task TestAfterRequired() + => VerifyKeywordAsync(""" class C { required $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefAtTopLevel1() + => VerifyKeywordAsync( @"ref $$"); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [CombinatorialData] @@ -904,216 +713,183 @@ await VerifyAbsenceAsync( } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefReadonlyAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyAtTopLevel1() + => VerifyKeywordAsync( @"ref readonly $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { readonly $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref readonly $$ } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref $$ -}}"); - } + public Task TestAfterRefInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - readonly $$ -}}"); - } + public Task TestAfterReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + readonly $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref readonly $$ -}}"); - } + public Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref readonly $$ + } + """); #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -1123,5 +899,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ScopedKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ScopedKeywordRecommenderTests.cs index fd8349df67c90..fac11b89f108e 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ScopedKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ScopedKeywordRecommenderTests.cs @@ -21,411 +21,309 @@ public ScopedKeywordRecommenderTests() } [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotAfterStackAlloc() - { - await VerifyAbsenceAsync( + public Task TestNotAfterStackAlloc() + => VerifyAbsenceAsync( """ class C { int* goo = stackalloc $$ """); - } [Fact] - public async Task TestNotInFixedStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInFixedStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"fixed ($$")); - } [Fact] - public async Task TestNotInDelegateReturnType() - { - await VerifyAbsenceAsync( + public Task TestNotInDelegateReturnType() + => VerifyAbsenceAsync( @"public delegate $$"); - } [Fact] - public async Task TestPossibleLambda() - { - // Could be `var x = ((scoped ref int x) => x);` - await VerifyKeywordAsync(AddInsideMethod( + public Task TestPossibleLambda() + => VerifyKeywordAsync(AddInsideMethod( @"var x = (($$")); - } [Fact] - public async Task TestEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestBeforeStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBeforeStatement() + => VerifyKeywordAsync(AddInsideMethod( """ $$ return true; """)); - } [Fact] - public async Task TestAfterStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterStatement() + => VerifyKeywordAsync(AddInsideMethod( """ return true; $$ """)); - } [Fact] - public async Task TestNotInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotInClass() + => VerifyAbsenceAsync(""" class C { $$ } """); - } [Fact] - public async Task TestInFor() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFor() + => VerifyKeywordAsync(AddInsideMethod( @"for ($$")); - } [Fact] - public async Task TestInFor2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFor2() + => VerifyKeywordAsync(AddInsideMethod( @"for ($$;")); - } [Fact] - public async Task TestInFor3() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFor3() + => VerifyKeywordAsync(AddInsideMethod( @"for ($$;;")); - } [Fact] - public async Task TestNotInFor() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInFor() + => VerifyAbsenceAsync(AddInsideMethod( @"for (var $$")); - } [Fact] - public async Task TestNotAfterVar() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterVar() + => VerifyAbsenceAsync(AddInsideMethod( @"var $$")); - } [Fact] - public async Task TestInForEach() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForEach() + => VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); - } [Fact] - public async Task TestNotInForEach() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInForEach() + => VerifyAbsenceAsync(AddInsideMethod( @"foreach (var $$")); - } [Fact] - public async Task TestInAwaitForEach() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInAwaitForEach() + => VerifyKeywordAsync(AddInsideMethod( @"await foreach ($$")); - } [Fact] - public async Task TestNotInAwaitForEach() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInAwaitForEach() + => VerifyAbsenceAsync(AddInsideMethod( @"await foreach (var $$")); - } [Fact] - public async Task TestNotInForEachRefLoop0() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInForEachRefLoop0() + => VerifyAbsenceAsync(AddInsideMethod( @"foreach (ref $$")); - } [Fact] - public async Task TestNotInForEachRefLoop1() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInForEachRefLoop1() + => VerifyAbsenceAsync(AddInsideMethod( @"foreach (ref $$ x")); - } [Fact] - public async Task TestNotInForEachRefLoop2() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInForEachRefLoop2() + => VerifyAbsenceAsync(AddInsideMethod( @"foreach (ref s$$ x")); - } [Fact] - public async Task TestNotInForEachRefReadonlyLoop0() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInForEachRefReadonlyLoop0() + => VerifyAbsenceAsync(AddInsideMethod( @"foreach (ref readonly $$ x")); - } [Fact] - public async Task TestNotInForRefLoop0() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInForRefLoop0() + => VerifyAbsenceAsync(AddInsideMethod( @"for (ref $$")); - } [Fact] - public async Task TestNotInForRefLoop1() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInForRefLoop1() + => VerifyAbsenceAsync(AddInsideMethod( @"for (ref s$$")); - } [Fact] - public async Task TestNotInForRefReadonlyLoop0() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInForRefReadonlyLoop0() + => VerifyAbsenceAsync(AddInsideMethod( @"for (ref readonly $$")); - } [Fact] - public async Task TestNotInForRefReadonlyLoop1() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInForRefReadonlyLoop1() + => VerifyAbsenceAsync(AddInsideMethod( @"for (ref readonly s$$")); - } [Fact] - public async Task TestNotInUsing() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInUsing() + => VerifyAbsenceAsync(AddInsideMethod( @"using ($$")); - } [Fact] - public async Task TestNotInUsing2() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInUsing2() + => VerifyAbsenceAsync(AddInsideMethod( @"using (var $$")); - } [Fact] - public async Task TestNotInAwaitUsing() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInAwaitUsing() + => VerifyAbsenceAsync(AddInsideMethod( @"await using ($$")); - } [Fact] - public async Task TestNotInAwaitUsing2() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInAwaitUsing2() + => VerifyAbsenceAsync(AddInsideMethod( @"await using (var $$")); - } [Fact] - public async Task TestNotAfterConstLocal() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterConstLocal() + => VerifyAbsenceAsync(AddInsideMethod( @"const $$")); - } [Fact] - public async Task TestNotAfterConstField() - { - await VerifyAbsenceAsync( + public Task TestNotAfterConstField() + => VerifyAbsenceAsync( """ class C { const $$ """); - } [Fact] - public async Task TestAfterOutKeywordInArgument() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterOutKeywordInArgument() + => VerifyKeywordAsync(AddInsideMethod( @"M(out $$")); - } [Fact] - public async Task TestNotAfterRefInMemberContext() - { - await VerifyAbsenceAsync( + public Task TestNotAfterRefInMemberContext() + => VerifyAbsenceAsync( """ class C { ref $$ """); - } [Fact] - public async Task TestNotAfterRefReadonlyInMemberContext() - { - await VerifyAbsenceAsync( + public Task TestNotAfterRefReadonlyInMemberContext() + => VerifyAbsenceAsync( """ class C { ref readonly $$ """); - } [Fact] - public async Task TestNotAfterRefInStatementContext() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterRefInStatementContext() + => VerifyAbsenceAsync(AddInsideMethod( @"ref $$")); - } [Fact] - public async Task TestNotAfterRefReadonlyInStatementContext() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterRefReadonlyInStatementContext() + => VerifyAbsenceAsync(AddInsideMethod( @"ref readonly $$")); - } [Fact] - public async Task TestNotAfterRefLocalDeclaration() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterRefLocalDeclaration() + => VerifyAbsenceAsync(AddInsideMethod( @"ref $$ int local;")); - } [Fact] - public async Task TestNotAfterRefReadonlyLocalDeclaration() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterRefReadonlyLocalDeclaration() + => VerifyAbsenceAsync(AddInsideMethod( @"ref readonly $$ int local;")); - } [Fact] - public async Task TestNotAfterRefExpression() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterRefExpression() + => VerifyAbsenceAsync(AddInsideMethod( @"ref int x = ref $$")); - } [Fact] - public async Task TestInParameter1() - { - await VerifyKeywordAsync(""" + public Task TestInParameter1() + => VerifyKeywordAsync(""" class C { public void M($$) } """); - } [Fact] - public async Task TestInParameter2() - { - await VerifyKeywordAsync(""" + public Task TestInParameter2() + => VerifyKeywordAsync(""" class C { public void M($$ ref) } """); - } [Fact] - public async Task TestInParameter3() - { - await VerifyKeywordAsync(""" + public Task TestInParameter3() + => VerifyKeywordAsync(""" class C { public void M($$ ref int i) } """); - } [Fact] - public async Task TestInParameter4() - { - await VerifyKeywordAsync(""" + public Task TestInParameter4() + => VerifyKeywordAsync(""" class C { public void M($$ ref int i) } """); - } [Fact] - public async Task TestInOperatorParameter() - { - await VerifyKeywordAsync(""" + public Task TestInOperatorParameter() + => VerifyKeywordAsync(""" class C { public static C operator +($$ in C c) } """); - } [Fact] - public async Task TestInAnonymousMethodParameter() - { - await VerifyKeywordAsync(""" + public Task TestInAnonymousMethodParameter() + => VerifyKeywordAsync(""" class C { void M() @@ -434,16 +332,13 @@ void M() } } """); - } [Fact] - public async Task TestInParameterAfterThisScoped() - { - await VerifyKeywordAsync(""" + public Task TestInParameterAfterThisScoped() + => VerifyKeywordAsync(""" static class C { static void M(this $$) } """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/SealedKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/SealedKeywordRecommenderTests.cs index 35a862f436514..dd71dc9d99be5 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/SealedKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/SealedKeywordRecommenderTests.cs @@ -13,295 +13,235 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class SealedKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInCompilationUnit() - { - await VerifyKeywordAsync( + public Task TestInCompilationUnit() + => VerifyKeywordAsync( @"$$"); - } [Fact] - public async Task TestAfterExtern() - { - await VerifyKeywordAsync( + public Task TestAfterExtern() + => VerifyKeywordAsync( """ extern alias Goo; $$ """); - } [Fact] - public async Task TestAfterUsing() - { - await VerifyKeywordAsync( + public Task TestAfterUsing() + => VerifyKeywordAsync( """ using Goo; $$ """); - } [Fact] - public async Task TestAfterGlobalUsing() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalUsing() + => VerifyKeywordAsync( """ global using Goo; $$ """); - } [Fact] - public async Task TestAfterNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterNamespace() + => VerifyKeywordAsync( """ namespace N {} $$ """); - } [Fact] - public async Task TestAfterFileScopedNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterFileScopedNamespace() + => VerifyKeywordAsync( """ namespace N; $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestFileKeywordInsideNamespace() - { - await VerifyKeywordAsync( + public Task TestFileKeywordInsideNamespace() + => VerifyKeywordAsync( """ namespace N { file $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestFileKeywordInsideNamespaceBeforeClass() - { - await VerifyKeywordAsync( + public Task TestFileKeywordInsideNamespaceBeforeClass() + => VerifyKeywordAsync( """ namespace N { file $$ class C {} } """); - } [Fact] - public async Task TestAfterTypeDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterTypeDeclaration() + => VerifyKeywordAsync( """ class C {} $$ """); - } [Fact] - public async Task TestAfterDelegateDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateDeclaration() + => VerifyKeywordAsync( """ delegate void Goo(); $$ """); - } [Fact] - public async Task TestAfterMethodInClass() - { - await VerifyKeywordAsync( + public Task TestAfterMethodInClass() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterFieldInClass() - { - await VerifyKeywordAsync( + public Task TestAfterFieldInClass() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterPropertyInClass() - { - await VerifyKeywordAsync( + public Task TestAfterPropertyInClass() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ global using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeGlobalUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeGlobalUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ global using Goo; """); - } [Fact] - public async Task TestAfterAssemblyAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterAssemblyAttribute() + => VerifyKeywordAsync( """ [assembly: goo] $$ """); - } [Fact] - public async Task TestAfterRootAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterRootAttribute() + => VerifyKeywordAsync( """ [goo] $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync(""" + public Task TestInsideInterface() + => VerifyKeywordAsync(""" interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() @@ -312,25 +252,19 @@ public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact] - public async Task TestAfterInternal() - { - await VerifyKeywordAsync( + public Task TestAfterInternal() + => VerifyKeywordAsync( @"internal $$"); - } [Fact] - public async Task TestAfterPublic() - { - await VerifyKeywordAsync( + public Task TestAfterPublic() + => VerifyKeywordAsync( @"public $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestAfterFile() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterFile() + => VerifyKeywordAsync(SourceCodeKind.Regular, @"file $$"); - } [Fact] public async Task TestNotAfterStaticInternal() @@ -349,11 +283,9 @@ public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact] - public async Task TestAfterPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterPrivate() + => VerifyKeywordAsync( @"private $$"); - } [Fact] public async Task TestNotAfterSealed() @@ -364,118 +296,95 @@ public async Task TestNotAfterStatic() => await VerifyAbsenceAsync(@"static $$"); [Theory, CombinatorialData] - public async Task TestNotAfterNestedStatic([CombinatorialValues("class", "struct", "record", "record struct", "record class")] string declarationKind) - { - await VerifyAbsenceAsync(declarationKind + """ + public Task TestNotAfterNestedStatic([CombinatorialValues("class", "struct", "record", "record struct", "record class")] string declarationKind) + => VerifyAbsenceAsync(declarationKind + """ C { static $$ """); - } [Fact] - public async Task TestAfterNestedStaticInInterface() - { - await VerifyKeywordAsync(""" + public Task TestAfterNestedStaticInInterface() + => VerifyKeywordAsync(""" interface C { static $$ """); - } [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Theory, CombinatorialData] - public async Task TestNotAfterNestedAbstract([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) - { - await VerifyAbsenceAsync(declarationKind + """ + public Task TestNotAfterNestedAbstract([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) + => VerifyAbsenceAsync(declarationKind + """ C { abstract $$ """); - } [Theory, CombinatorialData] - public async Task TestNotAfterNestedVirtual([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) - { - await VerifyAbsenceAsync(declarationKind + """ + public Task TestNotAfterNestedVirtual([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) + => VerifyAbsenceAsync(declarationKind + """ C { virtual $$ """); - } [Fact] - public async Task TestAfterNestedOverride() - { - await VerifyKeywordAsync( + public Task TestAfterNestedOverride() + => VerifyKeywordAsync( """ class C { override $$ """); - } [Theory, CombinatorialData] - public async Task TestNotAfterNestedSealed([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) - { - await VerifyAbsenceAsync(declarationKind + """ + public Task TestNotAfterNestedSealed([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) + => VerifyAbsenceAsync(declarationKind + """ C { sealed $$ """); - } [Fact] - public async Task TestNotInProperty() - { - await VerifyAbsenceAsync( + public Task TestNotInProperty() + => VerifyAbsenceAsync( """ class C { int Goo { $$ """); - } [Fact] - public async Task TestNotInPropertyAfterAccessor() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAfterAccessor() + => VerifyAbsenceAsync( """ class C { int Goo { get; $$ """); - } [Fact] - public async Task TestNotInPropertyAfterAccessibility() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAfterAccessibility() + => VerifyAbsenceAsync( """ class C { int Goo { get; protected $$ """); - } [Fact] - public async Task TestNotInPropertyAfterInternal() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAfterInternal() + => VerifyAbsenceAsync( """ class C { int Goo { get; internal $$ """); - } [Fact] - public async Task TestWithinExtension() - { - await VerifyAbsenceAsync( + public Task TestWithinExtension() + => VerifyAbsenceAsync( """ static class C { @@ -485,5 +394,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/SelectKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/SelectKeywordRecommenderTests.cs index 6514f0a88045f..78405a29e303b 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/SelectKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/SelectKeywordRecommenderTests.cs @@ -12,175 +12,137 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class SelectKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestNotAtEndOfPreviousClause() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAtEndOfPreviousClause() + => VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y$$")); - } [Fact] - public async Task TestNewClause() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestNewClause() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y $$ """)); - } [Fact] - public async Task TestAfterPreviousClause() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterPreviousClause() + => VerifyKeywordAsync(AddInsideMethod( """ var v = from x in y where x > y $$ """)); - } [Fact] - public async Task TestAfterPreviousContinuationClause() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterPreviousContinuationClause() + => VerifyKeywordAsync(AddInsideMethod( """ var v = from x in y group x by y into g $$ """)); - } [Fact] - public async Task TestAfterOrderByExpr() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterOrderByExpr() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y orderby x $$ """)); - } [Fact] - public async Task TestAfterOrderByAscendingExpr() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterOrderByAscendingExpr() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y orderby x ascending $$ """)); - } [Fact] - public async Task TestAfterOrderByDescendingExpr() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterOrderByDescendingExpr() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y orderby x descending $$ """)); - } [Fact] - public async Task TestBetweenClauses() - { - // Technically going to generate invalid code, but we - // shouldn't stop users from doing this. - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBetweenClauses() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y $$ from z in w """)); - } [Fact] - public async Task TestNotAfterSelect() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterSelect() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y select $$ """)); - } [Fact] - public async Task TestNotAfterDot() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterDot() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y orderby x.$$ """)); - } [Fact] - public async Task TestNotAfterComma() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterComma() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y orderby x, $$ """)); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/SetKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/SetKeywordRecommenderTests.cs index 9ac0293265e31..ba1f0ef852b69 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/SetKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/SetKeywordRecommenderTests.cs @@ -12,350 +12,278 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class SetKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int Goo { $$ """); - } [Fact] - public async Task TestAfterPropertyPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterPropertyPrivate() + => VerifyKeywordAsync( """ class C { int Goo { private $$ """); - } [Fact] - public async Task TestAfterPropertyAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterPropertyAttribute() + => VerifyKeywordAsync( """ class C { int Goo { [Bar] $$ """); - } [Fact] - public async Task TestAfterPropertyAttributeAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterPropertyAttributeAndPrivate() + => VerifyKeywordAsync( """ class C { int Goo { [Bar] private $$ """); - } [Fact] - public async Task TestAfterPropertyGet() - { - await VerifyKeywordAsync( + public Task TestAfterPropertyGet() + => VerifyKeywordAsync( """ class C { int Goo { get; $$ """); - } [Fact] - public async Task TestAfterPropertyGetAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterPropertyGetAndPrivate() + => VerifyKeywordAsync( """ class C { int Goo { get; private $$ """); - } [Fact] - public async Task TestAfterPropertyGetAndAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterPropertyGetAndAttribute() + => VerifyKeywordAsync( """ class C { int Goo { get; [Bar] $$ """); - } [Fact] - public async Task TestAfterPropertyGetAndAttributeAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterPropertyGetAndAttributeAndPrivate() + => VerifyKeywordAsync( """ class C { int Goo { get; [Bar] private $$ """); - } [Fact] - public async Task TestAfterGetAccessorBlock() - { - await VerifyKeywordAsync( + public Task TestAfterGetAccessorBlock() + => VerifyKeywordAsync( """ class C { int Goo { get { } $$ """); - } [Fact] - public async Task TestAfterGetAccessorBlockAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterGetAccessorBlockAndPrivate() + => VerifyKeywordAsync( """ class C { int Goo { get { } private $$ """); - } [Fact] - public async Task TestAfterGetAccessorBlockAndAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterGetAccessorBlockAndAttribute() + => VerifyKeywordAsync( """ class C { int Goo { get { } [Bar] $$ """); - } [Fact] - public async Task TestAfterGetAccessorBlockAndAttributeAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterGetAccessorBlockAndAttributeAndPrivate() + => VerifyKeywordAsync( """ class C { int Goo { get { } [Bar] private $$ """); - } [Fact] - public async Task TestNotAfterPropertySetKeyword() - { - await VerifyAbsenceAsync( + public Task TestNotAfterPropertySetKeyword() + => VerifyAbsenceAsync( """ class C { int Goo { set $$ """); - } [Fact] - public async Task TestNotAfterPropertySetAccessor() - { - await VerifyAbsenceAsync( + public Task TestNotAfterPropertySetAccessor() + => VerifyAbsenceAsync( """ class C { int Goo { set; $$ """); - } [Fact] - public async Task TestNotInEvent() - { - await VerifyAbsenceAsync( + public Task TestNotInEvent() + => VerifyAbsenceAsync( """ class C { event Goo E { $$ """); - } [Fact] - public async Task TestAfterIndexer() - { - await VerifyKeywordAsync( + public Task TestAfterIndexer() + => VerifyKeywordAsync( """ class C { int this[int i] { $$ """); - } [Fact] - public async Task TestAfterIndexerPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerPrivate() + => VerifyKeywordAsync( """ class C { int this[int i] { private $$ """); - } [Fact] - public async Task TestAfterIndexerAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerAttribute() + => VerifyKeywordAsync( """ class C { int this[int i] { [Bar] $$ """); - } [Fact] - public async Task TestAfterIndexerAttributeAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerAttributeAndPrivate() + => VerifyKeywordAsync( """ class C { int this[int i] { [Bar] private $$ """); - } [Fact] - public async Task TestAfterIndexerGet() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerGet() + => VerifyKeywordAsync( """ class C { int this[int i] { get; $$ """); - } [Fact] - public async Task TestAfterIndexerGetAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerGetAndPrivate() + => VerifyKeywordAsync( """ class C { int this[int i] { get; private $$ """); - } [Fact] - public async Task TestAfterIndexerGetAndAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerGetAndAttribute() + => VerifyKeywordAsync( """ class C { int this[int i] { get; [Bar] $$ """); - } [Fact] - public async Task TestAfterIndexerGetAndAttributeAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerGetAndAttributeAndPrivate() + => VerifyKeywordAsync( """ class C { int this[int i] { get; [Bar] private $$ """); - } [Fact] - public async Task TestAfterIndexerGetBlock() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerGetBlock() + => VerifyKeywordAsync( """ class C { int this[int i] { get { } $$ """); - } [Fact] - public async Task TestAfterIndexerGetBlockAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerGetBlockAndPrivate() + => VerifyKeywordAsync( """ class C { int this[int i] { get { } private $$ """); - } [Fact] - public async Task TestAfterIndexerGetBlockAndAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerGetBlockAndAttribute() + => VerifyKeywordAsync( """ class C { int this[int i] { get { } [Bar] $$ """); - } [Fact] - public async Task TestAfterIndexerGetBlockAndAttributeAndPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerGetBlockAndAttributeAndPrivate() + => VerifyKeywordAsync( """ class C { int this[int i] { get { } [Bar] private $$ """); - } [Fact] - public async Task TestNotAfterIndexerSetKeyword() - { - await VerifyAbsenceAsync( + public Task TestNotAfterIndexerSetKeyword() + => VerifyAbsenceAsync( """ class C { int this[int i] { set $$ """); - } [Fact] - public async Task TestNotAfterIndexerSetAccessor() - { - await VerifyAbsenceAsync( + public Task TestNotAfterIndexerSetAccessor() + => VerifyAbsenceAsync( """ class C { int this[int i] { set; $$ """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ShortKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ShortKeywordRecommenderTests.cs index 0c94217b6a805..d45af2bd12766 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ShortKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ShortKeywordRecommenderTests.cs @@ -13,712 +13,549 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ShortKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsing() - { - await VerifyAbsenceAsync( + public Task TestNotInUsing() + => VerifyAbsenceAsync( @"using $$"); - } [Fact] - public async Task TestInUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInUsingAlias() + => VerifyKeywordAsync( @"using Goo = $$"); - } [Fact] - public async Task TestInGlobalUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInGlobalUsingAlias() + => VerifyKeywordAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestAfterStackAlloc() - { - await VerifyKeywordAsync( + public Task TestAfterStackAlloc() + => VerifyKeywordAsync( """ class C { int* goo = stackalloc $$ """); - } [Fact] - public async Task TestInFixedStatement() - { - await VerifyKeywordAsync( + public Task TestInFixedStatement() + => VerifyKeywordAsync( @"fixed ($$"); - } [Fact] - public async Task TestInDelegateReturnType() - { - await VerifyKeywordAsync( + public Task TestInDelegateReturnType() + => VerifyKeywordAsync( @"public delegate $$"); - } [Fact] - public async Task TestInCastType() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); - } [Fact] - public async Task TestInCastType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType2() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); - } [Fact] - public async Task TestAfterConstInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterConstInMemberContext() + => VerifyKeywordAsync( """ class C { const $$ """); - } [Fact] - public async Task TestAfterRefInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefInMemberContext() + => VerifyKeywordAsync( """ class C { ref $$ """); - } [Fact] - public async Task TestAfterRefReadonlyInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyInMemberContext() + => VerifyKeywordAsync( """ class C { ref readonly $$ """); - } [Fact] - public async Task TestAfterConstInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"const $$")); - } [Fact] - public async Task TestAfterRefInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$")); - } [Fact] - public async Task TestAfterRefReadonlyInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); - } [Fact] - public async Task TestAfterConstLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); - } [Fact] - public async Task TestAfterRefReadonlyLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); - } [Fact] - public async Task TestAfterRefReadonlyLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); - } [Fact] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } [Fact] - public async Task TestInEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestEnumBaseTypes() - { - await VerifyKeywordAsync( + public Task TestEnumBaseTypes() + => VerifyKeywordAsync( @"enum E : $$"); - } [Fact] - public async Task TestInGenericType1() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType1() + => VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); - } [Fact] - public async Task TestInGenericType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType2() + => VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList,$$")); - } [Fact] - public async Task TestNotInBaseList() - { - await VerifyAbsenceAsync( + public Task TestNotInBaseList() + => VerifyAbsenceAsync( @"class C : $$"); - } [Fact] - public async Task TestInGenericType_InBaseList() - { - await VerifyKeywordAsync( + public Task TestInGenericType_InBaseList() + => VerifyKeywordAsync( @"class C : IList<$$"); - } [Fact] - public async Task TestAfterIs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); - } [Fact] - public async Task TestAfterAs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterAs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync( + public Task TestInsideInterface() + => VerifyKeywordAsync( """ interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact] - public async Task TestAfterNestedPartial() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPartial() + => VerifyKeywordAsync( """ class C { partial $$ """); - } [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] - public async Task TestAfterNestedStaticPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticPublic() + => VerifyKeywordAsync( """ class C { static public $$ """); - } [Fact] - public async Task TestAfterNestedPublicStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublicStatic() + => VerifyKeywordAsync( """ class C { public static $$ """); - } [Fact] - public async Task TestAfterVirtualPublic() - { - await VerifyKeywordAsync( + public Task TestAfterVirtualPublic() + => VerifyKeywordAsync( """ class C { virtual public $$ """); - } [Fact] - public async Task TestAfterNestedPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublic() + => VerifyKeywordAsync( """ class C { public $$ """); - } [Fact] - public async Task TestAfterNestedPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPrivate() + => VerifyKeywordAsync( """ class C { private $$ """); - } [Fact] - public async Task TestAfterNestedProtected() - { - await VerifyKeywordAsync( + public Task TestAfterNestedProtected() + => VerifyKeywordAsync( """ class C { protected $$ """); - } [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] - public async Task TestAfterNestedStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStatic() + => VerifyKeywordAsync( """ class C { static $$ """); - } [Fact] - public async Task TestInLocalVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLocalVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInForVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"for ($$")); - } [Fact] - public async Task TestInForeachVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForeachVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); - } [Fact] - public async Task TestInUsingVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInUsingVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"using ($$")); - } [Fact] - public async Task TestInFromVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFromVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); - } [Fact] - public async Task TestInJoinVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInJoinVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from a in b join $$ """)); - } [Fact] - public async Task TestAfterMethodOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterMethodOpenParen() + => VerifyKeywordAsync( """ class C { void Goo($$ """); - } [Fact] - public async Task TestAfterMethodComma() - { - await VerifyKeywordAsync( + public Task TestAfterMethodComma() + => VerifyKeywordAsync( """ class C { void Goo(int i, $$ """); - } [Fact] - public async Task TestAfterMethodAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterMethodAttribute() + => VerifyKeywordAsync( """ class C { void Goo(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterConstructorOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorOpenParen() + => VerifyKeywordAsync( """ class C { public C($$ """); - } [Fact] - public async Task TestAfterConstructorComma() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorComma() + => VerifyKeywordAsync( """ class C { public C(int i, $$ """); - } [Fact] - public async Task TestAfterConstructorAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorAttribute() + => VerifyKeywordAsync( """ class C { public C(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterDelegateOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateOpenParen() + => VerifyKeywordAsync( @"delegate void D($$"); - } [Fact] - public async Task TestAfterDelegateComma() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateComma() + => VerifyKeywordAsync( @"delegate void D(int i, $$"); - } [Fact] - public async Task TestAfterDelegateAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateAttribute() + => VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); - } [Fact] - public async Task TestAfterThis() - { - await VerifyKeywordAsync( + public Task TestAfterThis() + => VerifyKeywordAsync( """ static class C { public static void Goo(this $$ """); - } [Fact] - public async Task TestAfterRef() - { - await VerifyKeywordAsync( + public Task TestAfterRef() + => VerifyKeywordAsync( """ class C { void Goo(ref $$ """); - } [Fact] - public async Task TestAfterOut() - { - await VerifyKeywordAsync( + public Task TestAfterOut() + => VerifyKeywordAsync( """ class C { void Goo(out $$ """); - } [Fact] - public async Task TestAfterLambdaRef() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaRef() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (ref $$ """); - } [Fact] - public async Task TestAfterLambdaOut() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaOut() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (out $$ """); - } [Fact] - public async Task TestAfterParams() - { - await VerifyKeywordAsync( + public Task TestAfterParams() + => VerifyKeywordAsync( """ class C { void Goo(params $$ """); - } [Fact] - public async Task TestInImplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInImplicitOperator() + => VerifyKeywordAsync( """ class C { public static implicit operator $$ """); - } [Fact] - public async Task TestInExplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInExplicitOperator() + => VerifyKeywordAsync( """ class C { public static explicit operator $$ """); - } [Fact] - public async Task TestAfterIndexerBracket() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracket() + => VerifyKeywordAsync( """ class C { int this[$$ """); - } [Fact] - public async Task TestAfterIndexerBracketComma() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracketComma() + => VerifyKeywordAsync( """ class C { int this[int i, $$ """); - } [Fact] - public async Task TestAfterNewInExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterNewInExpression() + => VerifyKeywordAsync(AddInsideMethod( @"new $$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInTypeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInTypeOf() + => VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInDefault() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDefault() + => VerifyKeywordAsync(AddInsideMethod( @"default($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInSizeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInSizeOf() + => VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -726,12 +563,10 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] - public async Task TestInCrefContext() - { - await VerifyKeywordAsync(""" + public Task TestInCrefContext() + => VerifyKeywordAsync(""" class Program { /// @@ -741,16 +576,13 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] - public async Task TestInCrefContextNotAfterDot() - { - await VerifyAbsenceAsync(""" + public Task TestInCrefContextNotAfterDot() + => VerifyAbsenceAsync(""" /// class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] public async Task TestNotAfterAsync() @@ -761,19 +593,16 @@ public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1468")] - public async Task TestNotInCrefTypeParameter() - { - await VerifyAbsenceAsync(""" + public Task TestNotInCrefTypeParameter() + => VerifyAbsenceAsync(""" using System; /// class C { } """); - } [Fact] - public async Task Preselection() - { - await VerifyKeywordAsync(""" + public Task Preselection() + => VerifyKeywordAsync(""" class Program { static void Main(string[] args) @@ -783,23 +612,19 @@ static void Main(string[] args) static void Helper(short x) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinType() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinType() + => VerifyKeywordAsync(""" class Program { ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinMember() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinMember() + => VerifyKeywordAsync(""" class Program { void Method() @@ -808,82 +633,66 @@ void Method() } } """); - } [Fact] - public async Task TestInFunctionPointerType() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerType() + => VerifyKeywordAsync(""" class C { delegate*<$$ """); - } [Fact] - public async Task TestInFunctionPointerTypeAfterComma() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerTypeAfterComma() + => VerifyKeywordAsync(""" class C { delegate* VerifyKeywordAsync(""" class C { delegate* VerifyAbsenceAsync(""" class C { delegate*$$ """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/53585")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithoutAsync))] - public async Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) - { - await VerifyKeywordAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) + => VerifyKeywordAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithAsync))] - public async Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) - { - await VerifyAbsenceAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) + => VerifyAbsenceAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64585")] - public async Task TestAfterRequired() - { - await VerifyKeywordAsync(""" + public Task TestAfterRequired() + => VerifyKeywordAsync(""" class C { required $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefAtTopLevel1() + => VerifyKeywordAsync( @"ref $$"); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [CombinatorialData] @@ -904,104 +713,85 @@ await VerifyAbsenceAsync( } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefReadonlyAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyAtTopLevel1() + => VerifyKeywordAsync( @"ref readonly $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { readonly $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref readonly $$ } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( + public Task TestAfterRefInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( $$""" {{type}} N { ref $$ } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( + public Task TestAfterReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( $$""" {{type}} N { readonly $$ } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( $$""" {{type}} N { ref readonly $$ } """); - } [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -1011,5 +801,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/SizeOfKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/SizeOfKeywordRecommenderTests.cs index 9fb35988d692e..1572cded7e10d 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/SizeOfKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/SizeOfKeywordRecommenderTests.cs @@ -13,94 +13,73 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class SizeOfKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestInsideEmptyMethod() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideEmptyMethod() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInsideSafeExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideSafeExpression() + => VerifyKeywordAsync(AddInsideMethod( @"var q = $$")); - } [Fact] - public async Task TestInsideUnsafeBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideUnsafeBlock() + => VerifyKeywordAsync(AddInsideMethod( """ unsafe { $$ """)); - } [Fact] - public async Task TestInsideUnsafeExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideUnsafeExpression() + => VerifyKeywordAsync(AddInsideMethod( """ unsafe { var q = $$ """)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -108,12 +87,9 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/StackAllocKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/StackAllocKeywordRecommenderTests.cs index 7b9dcc148ae68..a652b15b4d49b 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/StackAllocKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/StackAllocKeywordRecommenderTests.cs @@ -13,123 +13,92 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class StackAllocKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestInEmptyStatement() - { - // e.g. this is a valid statement - // stackalloc[] { 1, 2, 3 }.IndexOf(1); - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInEmptySpaceAfterAssignment() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptySpaceAfterAssignment() + => VerifyKeywordAsync(AddInsideMethod( @"var v = $$")); - } [Fact] - public async Task TestInUnsafeEmptySpace() - { - await VerifyKeywordAsync( + public Task TestInUnsafeEmptySpace() + => VerifyKeywordAsync( """ unsafe class C { void Goo() { var v = $$ """); - } [Fact] - public async Task TestInUnsafeEmptySpace_AfterNonPointer() - { - // There can be an implicit conversion to int - await VerifyKeywordAsync( + public Task TestInUnsafeEmptySpace_AfterNonPointer() + => VerifyKeywordAsync( """ unsafe class C { void Goo() { int v = $$ """); - } [Fact] - public async Task TestInUnsafeEmptySpace_AfterPointer() - { - await VerifyKeywordAsync( + public Task TestInUnsafeEmptySpace_AfterPointer() + => VerifyKeywordAsync( """ unsafe class C { void Goo() { int* v = $$ """); - } [Fact] - public async Task TestInField() - { - // While assigning stackalloc'd value to a field is invalid, - // using one in the initializer is OK. e.g. - // int _f = stackalloc[] { 1, 2, 3 }.IndexOf(1); - await VerifyKeywordAsync( + public Task TestInField() + => VerifyKeywordAsync( """ class C { int v = $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544504")] - public async Task TestInsideForStatementVarDecl1() - { - await VerifyKeywordAsync( + public Task TestInsideForStatementVarDecl1() + => VerifyKeywordAsync( """ class C { @@ -137,12 +106,10 @@ unsafe static void Main(string[] args) { for (var i = $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544504")] - public async Task TestInsideForStatementVarDecl2() - { - await VerifyKeywordAsync( + public Task TestInsideForStatementVarDecl2() + => VerifyKeywordAsync( """ class C { @@ -150,12 +117,10 @@ unsafe static void Main(string[] args) { for (int* i = $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544504")] - public async Task TestInsideForStatementVarDecl3() - { - await VerifyKeywordAsync( + public Task TestInsideForStatementVarDecl3() + => VerifyKeywordAsync( """ class C { @@ -163,29 +128,22 @@ unsafe static void Main(string[] args) { for (string i = $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23584")] - public async Task TestOnRHSOfAssignment_Span() - { - await VerifyKeywordAsync(AddInsideMethod(""" + public Task TestOnRHSOfAssignment_Span() + => VerifyKeywordAsync(AddInsideMethod(""" Span s = $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23584")] - public async Task TestOnRHSOfAssignment_Pointer() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestOnRHSOfAssignment_Pointer() + => VerifyKeywordAsync(AddInsideMethod( @"int* v = $$")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23584")] - public async Task TestOnRHSOfAssignment_ReAssignment() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestOnRHSOfAssignment_ReAssignment() + => VerifyKeywordAsync(AddInsideMethod( @"v = $$")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23584")] public async Task TestOnRHSWithCast() @@ -332,131 +290,109 @@ static void Method(int x, System.Span span) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41736")] - public async Task TestNotInConstFieldInitializer() - { - await VerifyAbsenceAsync(""" + public Task TestNotInConstFieldInitializer() + => VerifyAbsenceAsync(""" class Program { private const int _f = $$ } """); - } #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/StaticKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/StaticKeywordRecommenderTests.cs index 267b64cb67c1d..dcc4a3644898f 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/StaticKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/StaticKeywordRecommenderTests.cs @@ -13,296 +13,236 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class StaticKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32174")] - public async Task TestInEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInCompilationUnit() - { - await VerifyKeywordAsync( + public Task TestInCompilationUnit() + => VerifyKeywordAsync( @"$$"); - } [Fact] - public async Task TestAfterExtern() - { - await VerifyKeywordAsync( + public Task TestAfterExtern() + => VerifyKeywordAsync( """ extern alias Goo; $$ """); - } [Fact] - public async Task TestAfterUsing() - { - await VerifyKeywordAsync( + public Task TestAfterUsing() + => VerifyKeywordAsync( """ using Goo; $$ """); - } [Fact] - public async Task TestAfterGlobalUsing() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalUsing() + => VerifyKeywordAsync( """ global using Goo; $$ """); - } [Fact] - public async Task TestAfterNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterNamespace() + => VerifyKeywordAsync( """ namespace N {} $$ """); - } [Fact] - public async Task TestAfterFileScopedNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterFileScopedNamespace() + => VerifyKeywordAsync( """ namespace N; $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestFileKeywordInsideNamespace() - { - await VerifyKeywordAsync( + public Task TestFileKeywordInsideNamespace() + => VerifyKeywordAsync( """ namespace N { file $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestFileKeywordInsideNamespaceBeforeClass() - { - await VerifyKeywordAsync( + public Task TestFileKeywordInsideNamespaceBeforeClass() + => VerifyKeywordAsync( """ namespace N { file $$ class C {} } """); - } [Fact] - public async Task TestAfterTypeDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterTypeDeclaration() + => VerifyKeywordAsync( """ class C {} $$ """); - } [Fact] - public async Task TestAfterDelegateDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateDeclaration() + => VerifyKeywordAsync( """ delegate void Goo(); $$ """); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ global using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeGlobalUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeGlobalUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ global using Goo; """); - } [Fact] - public async Task TestAfterAssemblyAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterAssemblyAttribute() + => VerifyKeywordAsync( """ [assembly: goo] $$ """); - } [Fact] - public async Task TestAfterRootAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterRootAttribute() + => VerifyKeywordAsync( """ [goo] $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } // This will be fixed once we have accessibility for members [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync(""" + public Task TestInsideInterface() + => VerifyKeywordAsync(""" interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() @@ -313,25 +253,19 @@ public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact] - public async Task TestAfterInternal() - { - await VerifyKeywordAsync( + public Task TestAfterInternal() + => VerifyKeywordAsync( @"internal $$"); - } [Fact] - public async Task TestAfterPublic() - { - await VerifyKeywordAsync( + public Task TestAfterPublic() + => VerifyKeywordAsync( @"public $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestAfterFile() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterFile() + => VerifyKeywordAsync(SourceCodeKind.Regular, @"file $$"); - } [Fact] public async Task TestNotAfterStaticPublic() @@ -346,18 +280,14 @@ public async Task TestNotAfterVirtualPublic() => await VerifyAbsenceAsync(@"virtual public $$"); [Fact] - public async Task TestAfterPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterPrivate() + => VerifyKeywordAsync( @"private $$"); - } [Fact] - public async Task TestAfterProtected() - { - await VerifyKeywordAsync( + public Task TestAfterProtected() + => VerifyKeywordAsync( @"protected $$"); - } [Fact] public async Task TestNotAfterSealed() @@ -376,298 +306,220 @@ public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32214")] - public async Task TestNotBetweenUsings() - { - var source = """ + public Task TestNotBetweenUsings() + => VerifyWorkerAsync(""" using Goo; $$ using Bar; - """; - - await VerifyWorkerAsync(source, absent: true); - - // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 - //await VerifyWorkerAsync(source, absent: true, Options.Script); - } + """, absent: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32214")] - public async Task TestNotBetweenGlobalUsings_01() - { - var source = """ + public Task TestNotBetweenGlobalUsings_01() + => VerifyWorkerAsync(""" global using Goo; $$ using Bar; - """; - - await VerifyWorkerAsync(source, absent: true); - - // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 - //await VerifyWorkerAsync(source, absent: true, Options.Script); - } + """, absent: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32214")] - public async Task TestNotBetweenGlobalUsings_02() - { - var source = """ + public Task TestNotBetweenGlobalUsings_02() + => VerifyWorkerAsync(""" global using Goo; $$ global using Bar; - """; - - await VerifyWorkerAsync(source, absent: true); - - // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 - //await VerifyWorkerAsync(source, absent: true, Options.Script); - } + """, absent: true); [Theory, CombinatorialData] - public async Task TestNotAfterNestedAbstract([CombinatorialValues("class", "struct", "record", "record struct", "record class")] string declarationKind) - { - await VerifyAbsenceAsync(declarationKind + """ + public Task TestNotAfterNestedAbstract([CombinatorialValues("class", "struct", "record", "record struct", "record class")] string declarationKind) + => VerifyAbsenceAsync(declarationKind + """ C { abstract $$ """); - } [Fact] - public async Task TestAfterNestedAbstractInInterface() - { - await VerifyKeywordAsync(""" + public Task TestAfterNestedAbstractInInterface() + => VerifyKeywordAsync(""" interface C { abstract $$ """); - } [Theory, CombinatorialData] - public async Task TestNotAfterNestedVirtual([CombinatorialValues("class", "struct", "record", "record struct", "record class")] string declarationKind) - { - await VerifyAbsenceAsync(declarationKind + """ + public Task TestNotAfterNestedVirtual([CombinatorialValues("class", "struct", "record", "record struct", "record class")] string declarationKind) + => VerifyAbsenceAsync(declarationKind + """ C { virtual $$ """); - } [Fact] - public async Task TestAfterNestedVirtualInInterface() - { - await VerifyKeywordAsync(""" + public Task TestAfterNestedVirtualInInterface() + => VerifyKeywordAsync(""" interface C { virtual $$ """); - } [Theory, CombinatorialData] - public async Task TestNotAfterNestedOverride([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) - { - await VerifyAbsenceAsync(declarationKind + """ + public Task TestNotAfterNestedOverride([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) + => VerifyAbsenceAsync(declarationKind + """ C { override $$ """); - } [Theory, CombinatorialData] - public async Task TestNotAfterNestedStatic([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) - { - await VerifyAbsenceAsync(declarationKind + """ + public Task TestNotAfterNestedStatic([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) + => VerifyAbsenceAsync(declarationKind + """ C { static $$ """); - } [Theory, CombinatorialData] - public async Task TestNotAfterNestedSealed([CombinatorialValues("class", "struct", "record", "record struct", "record class")] string declarationKind) - { - await VerifyAbsenceAsync(declarationKind + """ + public Task TestNotAfterNestedSealed([CombinatorialValues("class", "struct", "record", "record struct", "record class")] string declarationKind) + => VerifyAbsenceAsync(declarationKind + """ C { sealed $$ """); - } [Fact] - public async Task TestAfterNestedSealedInInterface() - { - await VerifyKeywordAsync(""" + public Task TestAfterNestedSealedInInterface() + => VerifyKeywordAsync(""" interface C { sealed $$ """); - } [Fact] - public async Task TestAfterNestedReadOnly() - { - await VerifyKeywordAsync( + public Task TestAfterNestedReadOnly() + => VerifyKeywordAsync( """ class C { readonly $$ """); - } [Fact] - public async Task TestAfterAsync() - { - await VerifyKeywordAsync( + public Task TestAfterAsync() + => VerifyKeywordAsync( """ class C { async $$ """); - } [Fact] - public async Task TestAfterUsingInCompilationUnit() - { - await VerifyKeywordAsync( + public Task TestAfterUsingInCompilationUnit() + => VerifyKeywordAsync( @"using $$"); - } [Fact] - public async Task TestAfterGlobalUsingInCompilationUnit() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalUsingInCompilationUnit() + => VerifyKeywordAsync( @"global using $$"); - } [Fact] - public async Task TestNotAfterUsingInMethodBody() - { - await VerifyAbsenceAsync( + public Task TestNotAfterUsingInMethodBody() + => VerifyAbsenceAsync( """ class C { void M() { using $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32174")] public async Task TestLocalFunction() => await VerifyKeywordAsync(AddInsideMethod(@" $$ void local() { }")); [Fact] - public async Task TestInCase() - { - await VerifyKeywordAsync(AddInsideMethod(""" + public Task TestInCase() + => VerifyKeywordAsync(AddInsideMethod(""" switch (i) { case 0: $$ """)); - } [Fact] - public async Task TestInAssignment() - { - await VerifyKeywordAsync(AddInsideMethod(""" + public Task TestInAssignment() + => VerifyKeywordAsync(AddInsideMethod(""" System.Action x = $$ """)); - } [Fact] - public async Task TestBeforeLambdaInAssignment() - { - await VerifyKeywordAsync(AddInsideMethod(""" + public Task TestBeforeLambdaInAssignment() + => VerifyKeywordAsync(AddInsideMethod(""" System.Action x = $$ (x) => { } """)); - } [Fact] - public async Task TestBeforeAnonymousMethodInAssignment() - { - await VerifyKeywordAsync(AddInsideMethod(""" + public Task TestBeforeAnonymousMethodInAssignment() + => VerifyKeywordAsync(AddInsideMethod(""" System.Action x = $$ delegate(x) { } """)); - } [Fact] - public async Task TestAfterAsyncInAssignment() - { - await VerifyKeywordAsync(AddInsideMethod(""" + public Task TestAfterAsyncInAssignment() + => VerifyKeywordAsync(AddInsideMethod(""" System.Action x = async $$ """)); - } [Fact] - public async Task TestBeforeAsyncInAssignment() - { - await VerifyKeywordAsync(AddInsideMethod(""" + public Task TestBeforeAsyncInAssignment() + => VerifyKeywordAsync(AddInsideMethod(""" System.Action x = $$ async """)); - } [Fact] - public async Task TestBeforeAsyncLambdaInAssignment() - { - await VerifyKeywordAsync(AddInsideMethod(""" + public Task TestBeforeAsyncLambdaInAssignment() + => VerifyKeywordAsync(AddInsideMethod(""" System.Action x = $$ async (x) => { } """)); - } [Fact] - public async Task TestAfterAsyncBeforeLambdaInAssignment() - { - await VerifyKeywordAsync(AddInsideMethod(""" + public Task TestAfterAsyncBeforeLambdaInAssignment() + => VerifyKeywordAsync(AddInsideMethod(""" System.Action x = async $$ (x) => { } """)); - } [Fact] - public async Task TestAfterAsyncLambdaParamInAssignment() - { - await VerifyKeywordAsync(AddInsideMethod(""" + public Task TestAfterAsyncLambdaParamInAssignment() + => VerifyKeywordAsync(AddInsideMethod(""" System.Action x = async async $$ (x) => { } """)); - } [Fact] - public async Task TestInCall() - { - await VerifyKeywordAsync(AddInsideMethod(""" + public Task TestInCall() + => VerifyKeywordAsync(AddInsideMethod(""" M($$ """)); - } [Fact] - public async Task TestInIndexer() - { - await VerifyKeywordAsync(AddInsideMethod(""" + public Task TestInIndexer() + => VerifyKeywordAsync(AddInsideMethod(""" this[$$ """)); - } [Fact] - public async Task TestInCallAfterArgumentLabel() - { - await VerifyKeywordAsync(AddInsideMethod(""" + public Task TestInCallAfterArgumentLabel() + => VerifyKeywordAsync(AddInsideMethod(""" M(param: $$ """)); - } [Fact] - public async Task TestInCallAfterRef() - { - await VerifyAbsenceAsync(AddInsideMethod(""" + public Task TestInCallAfterRef() + => VerifyAbsenceAsync(AddInsideMethod(""" M(ref $$ """)); - } [Fact] - public async Task TestInCallAfterIn() - { - await VerifyAbsenceAsync(AddInsideMethod(""" + public Task TestInCallAfterIn() + => VerifyAbsenceAsync(AddInsideMethod(""" M(in $$ """)); - } [Fact] - public async Task TestInCallAfterOut() - { - await VerifyAbsenceAsync(AddInsideMethod(""" + public Task TestInCallAfterOut() + => VerifyAbsenceAsync(AddInsideMethod(""" M(in $$ """)); - } [Fact] - public async Task TestInAttribute() - { - await VerifyAbsenceAsync(""" + public Task TestInAttribute() + => VerifyAbsenceAsync(""" class C { [$$ @@ -676,12 +528,10 @@ void M() } } """); - } [Fact] - public async Task TestInAttributeArgument() - { - await VerifyAbsenceAsync(""" + public Task TestInAttributeArgument() + => VerifyAbsenceAsync(""" class C { [Attr($$ @@ -690,25 +540,21 @@ void M() } } """); - } [Fact] public async Task TestInFor() => await VerifyKeywordAsync(AddInsideMethod(@" for (int i = 0; i < 0; $$) ")); [Fact] - public async Task TestAfterUsingKeywordBeforeTopLevelStatement() - { - await VerifyKeywordAsync(""" + public Task TestAfterUsingKeywordBeforeTopLevelStatement() + => VerifyKeywordAsync(""" using $$ var i = 1; """); - } [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -718,5 +564,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/StringKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/StringKeywordRecommenderTests.cs index 8046956276553..359155e4f397b 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/StringKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/StringKeywordRecommenderTests.cs @@ -13,251 +13,189 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class StringKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsing() - { - await VerifyAbsenceAsync( + public Task TestNotInUsing() + => VerifyAbsenceAsync( @"using $$"); - } [Fact] - public async Task TestInUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInUsingAlias() + => VerifyKeywordAsync( @"using Goo = $$"); - } [Fact] - public async Task TestInGlobalUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInGlobalUsingAlias() + => VerifyKeywordAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotAfterStackAlloc() - { - await VerifyAbsenceAsync( + public Task TestNotAfterStackAlloc() + => VerifyAbsenceAsync( """ class C { int* goo = stackalloc $$ """); - } [Fact] - public async Task TestNotInFixedStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInFixedStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"fixed ($$")); - } [Fact] - public async Task TestInDelegateReturnType() - { - await VerifyKeywordAsync( + public Task TestInDelegateReturnType() + => VerifyKeywordAsync( @"public delegate $$"); - } [Fact] - public async Task TestInCastType() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); - } [Fact] - public async Task TestInCastType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType2() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); - } [Fact] - public async Task TestAfterConstInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterConstInMemberContext() + => VerifyKeywordAsync( """ class C { const $$ """); - } [Fact] - public async Task TestAfterRefInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefInMemberContext() + => VerifyKeywordAsync( """ class C { ref $$ """); - } [Fact] - public async Task TestAfterRefReadonlyInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyInMemberContext() + => VerifyKeywordAsync( """ class C { ref readonly $$ """); - } [Fact] - public async Task TestAfterConstInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"const $$")); - } [Fact] - public async Task TestAfterRefInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$")); - } [Fact] - public async Task TestAfterRefReadonlyInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); - } [Fact] - public async Task TestAfterConstLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); - } [Fact] - public async Task TestAfterRefReadonlyLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); - } [Fact] - public async Task TestAfterRefReadonlyLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/53585")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithoutAsync))] - public async Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) - { - await VerifyKeywordAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) + => VerifyKeywordAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithAsync))] - public async Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) - { - await VerifyAbsenceAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) + => VerifyAbsenceAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Fact] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } [Fact] - public async Task TestInEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestNotInEnumBaseTypes() - { - await VerifyAbsenceAsync( + public Task TestNotInEnumBaseTypes() + => VerifyAbsenceAsync( @"enum E : $$"); - } [Fact] - public async Task TestInGenericType1() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType1() + => VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); - } [Fact] - public async Task TestInGenericType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType2() + => VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList,$$")); - } [Fact] public async Task TestInGenericClassDecl() @@ -300,474 +238,373 @@ public async Task TestInGenericMethodDeclList() => await VerifyAbsenceAsync(@"class C { void Method VerifyAbsenceAsync( @"class C : $$"); - } [Fact] - public async Task TestInGenericType_InBaseList() - { - await VerifyKeywordAsync( + public Task TestInGenericType_InBaseList() + => VerifyKeywordAsync( @"class C : IList<$$"); - } [Fact] - public async Task TestAfterIs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); - } [Fact] - public async Task TestAfterAs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterAs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync( + public Task TestInsideInterface() + => VerifyKeywordAsync( """ interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact] - public async Task TestAfterNestedPartial() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPartial() + => VerifyKeywordAsync( """ class C { partial $$ """); - } [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] - public async Task TestAfterNestedStaticPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticPublic() + => VerifyKeywordAsync( """ class C { static public $$ """); - } [Fact] - public async Task TestAfterNestedPublicStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublicStatic() + => VerifyKeywordAsync( """ class C { public static $$ """); - } [Fact] - public async Task TestAfterVirtualPublic() - { - await VerifyKeywordAsync( + public Task TestAfterVirtualPublic() + => VerifyKeywordAsync( """ class C { virtual public $$ """); - } [Fact] - public async Task TestAfterNestedPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublic() + => VerifyKeywordAsync( """ class C { public $$ """); - } [Fact] - public async Task TestAfterNestedPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPrivate() + => VerifyKeywordAsync( """ class C { private $$ """); - } [Fact] - public async Task TestAfterNestedProtected() - { - await VerifyKeywordAsync( + public Task TestAfterNestedProtected() + => VerifyKeywordAsync( """ class C { protected $$ """); - } [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] - public async Task TestAfterNestedStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStatic() + => VerifyKeywordAsync( """ class C { static $$ """); - } [Fact] - public async Task TestInLocalVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLocalVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInForVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"for ($$")); - } [Fact] - public async Task TestInForCondition() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForCondition() + => VerifyKeywordAsync(AddInsideMethod( @"for (;$$")); - } [Fact] - public async Task TestInForIncrementor() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForIncrementor() + => VerifyKeywordAsync(AddInsideMethod( @"for (;;$$")); - } [Fact] - public async Task TestInForeachVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForeachVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); - } [Fact] - public async Task TestInUsingVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInUsingVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"using ($$")); - } [Fact] - public async Task TestInFromVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFromVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); - } [Fact] - public async Task TestInJoinVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInJoinVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from a in b join $$ """)); - } [Fact] - public async Task TestAfterMethodOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterMethodOpenParen() + => VerifyKeywordAsync( """ class C { void Goo($$ """); - } [Fact] - public async Task TestAfterMethodComma() - { - await VerifyKeywordAsync( + public Task TestAfterMethodComma() + => VerifyKeywordAsync( """ class C { void Goo(int i, $$ """); - } [Fact] - public async Task TestAfterMethodAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterMethodAttribute() + => VerifyKeywordAsync( """ class C { void Goo(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterConstructorOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorOpenParen() + => VerifyKeywordAsync( """ class C { public C($$ """); - } [Fact] - public async Task TestAfterConstructorComma() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorComma() + => VerifyKeywordAsync( """ class C { public C(int i, $$ """); - } [Fact] - public async Task TestAfterConstructorAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorAttribute() + => VerifyKeywordAsync( """ class C { public C(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterDelegateOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateOpenParen() + => VerifyKeywordAsync( @"delegate void D($$"); - } [Fact] - public async Task TestAfterDelegateComma() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateComma() + => VerifyKeywordAsync( @"delegate void D(int i, $$"); - } [Fact] - public async Task TestAfterDelegateAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateAttribute() + => VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); - } [Fact] - public async Task TestAfterThis() - { - await VerifyKeywordAsync( + public Task TestAfterThis() + => VerifyKeywordAsync( """ static class C { public static void Goo(this $$ """); - } [Fact] - public async Task TestAfterRef() - { - await VerifyKeywordAsync( + public Task TestAfterRef() + => VerifyKeywordAsync( """ class C { void Goo(ref $$ """); - } [Fact] - public async Task TestAfterOut() - { - await VerifyKeywordAsync( + public Task TestAfterOut() + => VerifyKeywordAsync( """ class C { void Goo(out $$ """); - } [Fact] - public async Task TestAfterLambdaRef() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaRef() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (ref $$ """); - } [Fact] - public async Task TestAfterLambdaOut() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaOut() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (out $$ """); - } [Fact] - public async Task TestAfterParams() - { - await VerifyKeywordAsync( + public Task TestAfterParams() + => VerifyKeywordAsync( """ class C { void Goo(params $$ """); - } [Fact] - public async Task TestInImplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInImplicitOperator() + => VerifyKeywordAsync( """ class C { public static implicit operator $$ """); - } [Fact] - public async Task TestInExplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInExplicitOperator() + => VerifyKeywordAsync( """ class C { public static explicit operator $$ """); - } [Fact] - public async Task TestAfterIndexerBracket() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracket() + => VerifyKeywordAsync( """ class C { int this[$$ """); - } [Fact] - public async Task TestAfterIndexerBracketComma() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracketComma() + => VerifyKeywordAsync( """ class C { int this[int i, $$ """); - } [Fact] - public async Task TestAfterNewInExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterNewInExpression() + => VerifyKeywordAsync(AddInsideMethod( @"new $$")); - } [Fact] - public async Task TestAfterNestedType() - { - await VerifyKeywordAsync( + public Task TestAfterNestedType() + => VerifyKeywordAsync( """ class SimpleParsedExpression { enum CommandType @@ -776,33 +613,25 @@ enum CommandType }; $$[] commandNames """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInTypeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInTypeOf() + => VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInDefault() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDefault() + => VerifyKeywordAsync(AddInsideMethod( @"default($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInSizeOf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInSizeOf() + => VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -810,16 +639,13 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] - public async Task TestInCrefContextNotAfterDot() - { - await VerifyAbsenceAsync(""" + public Task TestInCrefContextNotAfterDot() + => VerifyAbsenceAsync(""" /// class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] public async Task TestNotAfterAsync() @@ -830,30 +656,25 @@ public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1468")] - public async Task TestNotInCrefTypeParameter() - { - await VerifyAbsenceAsync(""" + public Task TestNotInCrefTypeParameter() + => VerifyAbsenceAsync(""" using System; /// class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinType() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinType() + => VerifyKeywordAsync(""" class Program { ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinMember() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinMember() + => VerifyKeywordAsync(""" class Program { void Method() @@ -862,66 +683,52 @@ void Method() } } """); - } [Fact] - public async Task TestInFunctionPointerType() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerType() + => VerifyKeywordAsync(""" class C { delegate*<$$ """); - } [Fact] - public async Task TestInFunctionPointerTypeAfterComma() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerTypeAfterComma() + => VerifyKeywordAsync(""" class C { delegate* VerifyKeywordAsync(""" class C { delegate* VerifyAbsenceAsync(""" class C { delegate*$$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64585")] - public async Task TestAfterRequired() - { - await VerifyKeywordAsync(""" + public Task TestAfterRequired() + => VerifyKeywordAsync(""" class C { required $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefAtTopLevel1() + => VerifyKeywordAsync( @"ref $$"); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [CombinatorialData] @@ -942,216 +749,183 @@ await VerifyAbsenceAsync( } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefReadonlyAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyAtTopLevel1() + => VerifyKeywordAsync( @"ref readonly $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { readonly $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref readonly $$ } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref $$ -}}"); - } + public Task TestAfterRefInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - readonly $$ -}}"); - } + public Task TestAfterReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + readonly $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref readonly $$ -}}"); - } + public Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref readonly $$ + } + """); #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -1161,5 +935,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/StructKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/StructKeywordRecommenderTests.cs index ff42ecb384cc1..3741084109817 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/StructKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/StructKeywordRecommenderTests.cs @@ -13,404 +13,314 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class StructKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInCompilationUnit() - { - await VerifyKeywordAsync( + public Task TestInCompilationUnit() + => VerifyKeywordAsync( @"$$"); - } [Fact] - public async Task TestAfterExtern() - { - await VerifyKeywordAsync( + public Task TestAfterExtern() + => VerifyKeywordAsync( """ extern alias Goo; $$ """); - } [Fact] - public async Task TestAfterUsing() - { - await VerifyKeywordAsync( + public Task TestAfterUsing() + => VerifyKeywordAsync( """ using Goo; $$ """); - } [Fact] - public async Task TestAfterGlobalUsing() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalUsing() + => VerifyKeywordAsync( """ global using Goo; $$ """); - } [Fact] - public async Task TestAfterNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterNamespace() + => VerifyKeywordAsync( """ namespace N {} $$ """); - } [Fact] - public async Task TestAfterFileScopedNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterFileScopedNamespace() + => VerifyKeywordAsync( """ namespace N; $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestFileKeywordInsideNamespace() - { - await VerifyKeywordAsync( + public Task TestFileKeywordInsideNamespace() + => VerifyKeywordAsync( """ namespace N { file $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestFileKeywordInsideNamespaceBeforeClass() - { - await VerifyKeywordAsync( + public Task TestFileKeywordInsideNamespaceBeforeClass() + => VerifyKeywordAsync( """ namespace N { file $$ class C {} } """); - } [Fact] - public async Task TestAfterTypeDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterTypeDeclaration() + => VerifyKeywordAsync( """ class C {} $$ """); - } [Fact] - public async Task TestAfterDelegateDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateDeclaration() + => VerifyKeywordAsync( """ delegate void Goo(); $$ """); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ global using Goo; """); - } [Fact] - public async Task TestAfterReadonly() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterReadonly() + => VerifyKeywordAsync(SourceCodeKind.Regular, @"readonly $$"); - } [Fact] - public async Task TestAfterRef() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterRef() + => VerifyKeywordAsync(SourceCodeKind.Regular, @"ref $$"); - } [Fact] - public async Task TestAfterRefReadonly() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterRefReadonly() + => VerifyKeywordAsync(SourceCodeKind.Regular, @"ref readonly $$"); - } [Fact] - public async Task TestAfterPublicRefReadonly() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterPublicRefReadonly() + => VerifyKeywordAsync(SourceCodeKind.Regular, @"public ref readonly $$"); - } [Fact] - public async Task TestAfterReadonlyRef() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterReadonlyRef() + => VerifyKeywordAsync(SourceCodeKind.Regular, @"readonly ref $$"); - } [Fact] - public async Task TestAfterInternalReadonlyRef() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterInternalReadonlyRef() + => VerifyKeywordAsync(SourceCodeKind.Regular, @"internal readonly ref $$"); - } [Fact] - public async Task TestNotAfterReadonlyInMethod() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotAfterReadonlyInMethod() + => VerifyAbsenceAsync(SourceCodeKind.Regular, @"class C { void M() { readonly $$ } }"); - } [Fact] - public async Task TestNotAfterRefInMethod() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotAfterRefInMethod() + => VerifyAbsenceAsync(SourceCodeKind.Regular, @"class C { void M() { ref $$ } }"); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeGlobalUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeGlobalUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ global using Goo; """); - } [Fact] - public async Task TestAfterAssemblyAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterAssemblyAttribute() + => VerifyKeywordAsync( """ [assembly: goo] $$ """); - } [Fact] - public async Task TestAfterRootAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterRootAttribute() + => VerifyKeywordAsync( """ [goo] $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync(""" + public Task TestInsideInterface() + => VerifyKeywordAsync(""" interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] - public async Task TestAfterPartial() - { - await VerifyKeywordAsync( + public Task TestAfterPartial() + => VerifyKeywordAsync( @"partial $$"); - } [Fact] public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact] - public async Task TestAfterInternal() - { - await VerifyKeywordAsync( + public Task TestAfterInternal() + => VerifyKeywordAsync( @"internal $$"); - } [Fact] - public async Task TestAfterPublic() - { - await VerifyKeywordAsync( + public Task TestAfterPublic() + => VerifyKeywordAsync( @"public $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestAfterFile() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterFile() + => VerifyKeywordAsync(SourceCodeKind.Regular, @"file $$"); - } [Fact] - public async Task TestAfterPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterPrivate() + => VerifyKeywordAsync( @"private $$"); - } [Fact] - public async Task TestAfterProtected() - { - await VerifyKeywordAsync( + public Task TestAfterProtected() + => VerifyKeywordAsync( @"protected $$"); - } [Fact] - public async Task TestAfterRecord() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterRecord() + => VerifyKeywordAsync(SourceCodeKind.Regular, @"record $$"); - } [Fact] public async Task TestNotAfterSealed() @@ -429,290 +339,231 @@ public async Task TestNotAfterStruct() => await VerifyAbsenceAsync(@"struct $$"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TestAfterClassTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterClassTypeParameterConstraint() + => VerifyKeywordAsync( @"class C where T : $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TestNotAfterClassTypeParameterConstraintWhenNotDirectlyInConstraint() - { - await VerifyAbsenceAsync( + public Task TestNotAfterClassTypeParameterConstraintWhenNotDirectlyInConstraint() + => VerifyAbsenceAsync( @"class C where T : IList<$$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TestAfterClassTypeParameterConstraint2() - { - await VerifyKeywordAsync( + public Task TestAfterClassTypeParameterConstraint2() + => VerifyKeywordAsync( """ class C where T : $$ where U : U """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TestNotAfterClassTypeParameterConstraintWhenNotDirectlyInConstraint2() - { - await VerifyAbsenceAsync( + public Task TestNotAfterClassTypeParameterConstraintWhenNotDirectlyInConstraint2() + => VerifyAbsenceAsync( """ class C where T : IList<$$ where U : U """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TestAfterMethodTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterMethodTypeParameterConstraint() + => VerifyKeywordAsync( """ class C { void Goo() where T : $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TestNotAfterMethodTypeParameterConstraintWhenNotDirectlyInConstraint() - { - await VerifyAbsenceAsync( + public Task TestNotAfterMethodTypeParameterConstraintWhenNotDirectlyInConstraint() + => VerifyAbsenceAsync( """ class C { void Goo() where T : IList<$$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TestAfterMethodTypeParameterConstraint2() - { - await VerifyKeywordAsync( + public Task TestAfterMethodTypeParameterConstraint2() + => VerifyKeywordAsync( """ class C { void Goo() where T : $$ where U : T """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30784")] - public async Task TestNotAfterMethodTypeParameterConstraintWhenNotDirectlyInConstraint2() - { - await VerifyAbsenceAsync( + public Task TestNotAfterMethodTypeParameterConstraintWhenNotDirectlyInConstraint2() + => VerifyAbsenceAsync( """ class C { void Goo() where T : IList<$$ where U : T """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64465")] - public async Task TestNotAfterRecord_AbstractModifier() - { - await VerifyAbsenceAsync("abstract record $$"); - } + public Task TestNotAfterRecord_AbstractModifier() + => VerifyAbsenceAsync("abstract record $$"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64465")] - public async Task TestNotAfterRecord_SealedModifier() - { - await VerifyAbsenceAsync("sealed record $$"); - } + public Task TestNotAfterRecord_SealedModifier() + => VerifyAbsenceAsync("sealed record $$"); [Fact] - public async Task TestAfterAllowsRefInTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterAllowsRefInTypeParameterConstraint() + => VerifyKeywordAsync( """ class C where T : allows ref $$ """); - } [Fact] - public async Task TestAfterAllowsRefInTypeParameterConstraint2() - { - await VerifyKeywordAsync( + public Task TestAfterAllowsRefInTypeParameterConstraint2() + => VerifyKeywordAsync( """ class C where T : allows ref $$ where U : U """); - } [Fact] - public async Task TestAfterAllowsRefInMethodTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterAllowsRefInMethodTypeParameterConstraint() + => VerifyKeywordAsync( """ class C { void Goo() where T : allows ref $$ """); - } [Fact] - public async Task TestAfterAllowsRefInMethodTypeParameterConstraint2() - { - await VerifyKeywordAsync( + public Task TestAfterAllowsRefInMethodTypeParameterConstraint2() + => VerifyKeywordAsync( """ class C { void Goo() where T : allows ref $$ where U : T """); - } [Fact] - public async Task TestAfterAllowsRefAfterClassTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterAllowsRefAfterClassTypeParameterConstraint() + => VerifyKeywordAsync( """ class C where T : class, allows ref $$ """); - } [Fact] - public async Task TestAfterStructTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterStructTypeParameterConstraint() + => VerifyKeywordAsync( """ class C where T : struct, allows ref $$ """); - } [Fact] - public async Task TestAfterSimpleTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterSimpleTypeParameterConstraint() + => VerifyKeywordAsync( """ class C where T : IGoo, allows ref $$ """); - } [Fact] - public async Task TestAfterConstructorTypeParameterConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorTypeParameterConstraint() + => VerifyKeywordAsync( """ class C where T : new(), allows ref $$ """); - } [Fact] - public async Task TestNotAfterStructInTypeParameterConstraint() - { - await VerifyAbsenceAsync( + public Task TestNotAfterStructInTypeParameterConstraint() + => VerifyAbsenceAsync( """ class C where T : allows ref struct $$ """); - } [Fact] - public async Task TestNotAfterStructInTypeParameterConstraint2() - { - await VerifyAbsenceAsync( + public Task TestNotAfterStructInTypeParameterConstraint2() + => VerifyAbsenceAsync( """ class C where T : allows ref struct $$ where U : U """); - } [Fact] - public async Task TestNotAfterStructAfterClassTypeParameterConstraint() - { - await VerifyAbsenceAsync( + public Task TestNotAfterStructAfterClassTypeParameterConstraint() + => VerifyAbsenceAsync( """ class C where T : class, allows ref struct $$ """); - } [Fact] - public async Task TestNotAfterStructAfterStructTypeParameterConstraint() - { - await VerifyAbsenceAsync( + public Task TestNotAfterStructAfterStructTypeParameterConstraint() + => VerifyAbsenceAsync( """ class C where T : struct, allows ref struct $$ """); - } [Fact] - public async Task TestNotAfterStructAfterSimpleTypeParameterConstraint() - { - await VerifyAbsenceAsync( + public Task TestNotAfterStructAfterSimpleTypeParameterConstraint() + => VerifyAbsenceAsync( """ class C where T : IGoo, allows ref struct $$ """); - } [Fact] - public async Task TestNotAfterStructAfterConstructorTypeParameterConstraint() - { - await VerifyAbsenceAsync( + public Task TestNotAfterStructAfterConstructorTypeParameterConstraint() + => VerifyAbsenceAsync( """ class C where T : new(), allows ref struct $$ """); - } [Fact] - public async Task TestAfterAllowsInTypeParameterConstraint() - { - await VerifyAbsenceAsync( + public Task TestAfterAllowsInTypeParameterConstraint() + => VerifyAbsenceAsync( """ class C where T : allows $$ """); - } [Fact] - public async Task TestAfterAllowsInTypeParameterConstraint2() - { - await VerifyAbsenceAsync( + public Task TestAfterAllowsInTypeParameterConstraint2() + => VerifyAbsenceAsync( """ class C where T : allows $$ where U : U """); - } [Fact] - public async Task TestAfterAllowsInMethodTypeParameterConstraint() - { - await VerifyAbsenceAsync( + public Task TestAfterAllowsInMethodTypeParameterConstraint() + => VerifyAbsenceAsync( """ class C { void Goo() where T : allows $$ """); - } [Fact] - public async Task TestAfterAllowsInMethodTypeParameterConstraint2() - { - await VerifyAbsenceAsync( + public Task TestAfterAllowsInMethodTypeParameterConstraint2() + => VerifyAbsenceAsync( """ class C { void Goo() where T : allows $$ where U : T """); - } [Fact] - public async Task TestAfterAllowsAfterClassTypeParameterConstraint() - { - await VerifyAbsenceAsync( + public Task TestAfterAllowsAfterClassTypeParameterConstraint() + => VerifyAbsenceAsync( """ class C where T : class, allows $$ """); - } [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -724,5 +575,4 @@ static class C """, CSharpNextParseOptions, CSharpNextScriptParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/SwitchKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/SwitchKeywordRecommenderTests.cs index 1fed621ffdfdd..6d1d19f4e05dc 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/SwitchKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/SwitchKeywordRecommenderTests.cs @@ -13,126 +13,100 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class SwitchKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestBeforeStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBeforeStatement() + => VerifyKeywordAsync(AddInsideMethod( """ $$ return true; """)); - } [Fact] - public async Task TestAfterStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterStatement() + => VerifyKeywordAsync(AddInsideMethod( """ return true; $$ """)); - } [Fact] - public async Task TestAfterBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBlock() + => VerifyKeywordAsync(AddInsideMethod( """ if (true) { } $$ """)); - } [Fact] - public async Task TestInsideSwitchBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideSwitchBlock() + => VerifyKeywordAsync(AddInsideMethod( """ switch (E) { case 0: $$ """)); - } [Fact] - public async Task TestNotAfterSwitch1() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterSwitch1() + => VerifyAbsenceAsync(AddInsideMethod( @"switch $$")); - } [Fact] public async Task TestAfterExpression() => await VerifyKeywordAsync(AddInsideMethod(@"_ = expr $$")); [Fact] - public async Task TestAfterExpression_InMethodWithArrowBody() - { - await VerifyKeywordAsync(""" + public Task TestAfterExpression_InMethodWithArrowBody() + => VerifyKeywordAsync(""" class C { bool M() => this $$ } """); - } [Fact] public async Task TestAfterForeachVar() @@ -143,39 +117,32 @@ public async Task TestAfterTuple() => await VerifyKeywordAsync(AddInsideMethod(@"_ = (expr, expr) $$")); [Fact] - public async Task TestNotAfterSwitch2() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterSwitch2() + => VerifyAbsenceAsync(AddInsideMethod( @"switch ($$")); - } [Fact] - public async Task TestNotInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotInClass() + => VerifyAbsenceAsync(""" class C { $$ } """); - } [Fact] - public async Task TestAfterSwitch() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterSwitch() + => VerifyKeywordAsync(AddInsideMethod( """ switch (expr) { default: } $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8319")] - public async Task TestNotAfterMethodReference() - { - await VerifyAbsenceAsync( + public Task TestNotAfterMethodReference() + => VerifyAbsenceAsync( """ using System; @@ -183,12 +150,10 @@ class C { void M() { var v = Console.WriteLine $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8319")] - public async Task TestNotAfterAnonymousMethod() - { - await VerifyAbsenceAsync( + public Task TestNotAfterAnonymousMethod() + => VerifyAbsenceAsync( """ using System; @@ -196,12 +161,10 @@ class C { void M() { Action a = delegate { } $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8319")] - public async Task TestNotAfterLambda1() - { - await VerifyAbsenceAsync( + public Task TestNotAfterLambda1() + => VerifyAbsenceAsync( """ using System; @@ -209,12 +172,10 @@ class C { void M() { Action b = (() => 0) $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8319")] - public async Task TestNotAfterLambda2() - { - await VerifyAbsenceAsync( + public Task TestNotAfterLambda2() + => VerifyAbsenceAsync( """ using System; @@ -222,12 +183,10 @@ class C { void M() { Action b = () => {} $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48573")] - public async Task TestMissingAfterNumericLiteral() - { - await VerifyAbsenceAsync( + public Task TestMissingAfterNumericLiteral() + => VerifyAbsenceAsync( """ class C { @@ -237,12 +196,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48573")] - public async Task TestMissingAfterNumericLiteralAndDot() - { - await VerifyAbsenceAsync( + public Task TestMissingAfterNumericLiteralAndDot() + => VerifyAbsenceAsync( """ class C { @@ -252,12 +209,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48573")] - public async Task TestMissingAfterNumericLiteralDotAndSpace() - { - await VerifyAbsenceAsync( + public Task TestMissingAfterNumericLiteralDotAndSpace() + => VerifyAbsenceAsync( """ class C { @@ -267,12 +222,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31367")] - public async Task TestMissingInCaseClause1() - { - await VerifyAbsenceAsync( + public Task TestMissingInCaseClause1() + => VerifyAbsenceAsync( """ class A { @@ -290,12 +243,10 @@ void M(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31367")] - public async Task TestMissingInCaseClause2() - { - await VerifyAbsenceAsync( + public Task TestMissingInCaseClause2() + => VerifyAbsenceAsync( """ namespace N { @@ -316,5 +267,4 @@ void M(object o) } } """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ThisKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ThisKeywordRecommenderTests.cs index a1583aa608265..9cb38ee0e1cb2 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ThisKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ThisKeywordRecommenderTests.cs @@ -13,316 +13,245 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ThisKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotAfterAngle() - { - await VerifyAbsenceAsync( + public Task TestNotAfterAngle() + => VerifyAbsenceAsync( @"interface IGoo<$$"); - } [Fact] - public async Task TestInterfaceTypeVarianceNotAfterIn() - { - await VerifyAbsenceAsync( + public Task TestInterfaceTypeVarianceNotAfterIn() + => VerifyAbsenceAsync( @"interface IGoo VerifyAbsenceAsync( @"interface IGoo VerifyAbsenceAsync( @"interface IGoo<[Goo]$$"); - } [Fact] - public async Task TestDelegateTypeVarianceNotAfterAngle() - { - await VerifyAbsenceAsync( + public Task TestDelegateTypeVarianceNotAfterAngle() + => VerifyAbsenceAsync( @"delegate void D<$$"); - } [Fact] - public async Task TestDelegateTypeVarianceNotAfterComma() - { - await VerifyAbsenceAsync( + public Task TestDelegateTypeVarianceNotAfterComma() + => VerifyAbsenceAsync( @"delegate void D VerifyAbsenceAsync( @"delegate void D<[Goo]$$"); - } [Fact] - public async Task TestNotThisBaseListAfterAngle() - { - await VerifyAbsenceAsync( + public Task TestNotThisBaseListAfterAngle() + => VerifyAbsenceAsync( @"interface IGoo : Bar<$$"); - } [Fact] - public async Task TestNotInGenericMethod() - { - await VerifyAbsenceAsync( + public Task TestNotInGenericMethod() + => VerifyAbsenceAsync( """ interface IGoo { void Goo<$$ """); - } [Fact] - public async Task TestNotAfterRef() - { - await VerifyAbsenceAsync( + public Task TestNotAfterRef() + => VerifyAbsenceAsync( """ class C { void Goo(ref $$ """); - } [Theory, CombinatorialData] - public async Task TestNotAfterIn([CombinatorialValues("in", "ref readonly")] string modifier) - { - await VerifyAbsenceAsync($$""" + public Task TestNotAfterIn([CombinatorialValues("in", "ref readonly")] string modifier) + => VerifyAbsenceAsync($$""" class C { void Goo({{modifier}} $$ """); - } [Fact] - public async Task TestNotAfterThis_InBogusMethod() - { - await VerifyAbsenceAsync( + public Task TestNotAfterThis_InBogusMethod() + => VerifyAbsenceAsync( """ class C { void Goo(this $$ """); - } [Fact] - public async Task TestNotAfterOut() - { - await VerifyAbsenceAsync( + public Task TestNotAfterOut() + => VerifyAbsenceAsync( """ class C { void Goo(out $$ """); - } [Fact] - public async Task TestNotAfterMethodOpenParen() - { - await VerifyAbsenceAsync( + public Task TestNotAfterMethodOpenParen() + => VerifyAbsenceAsync( """ class C { void Goo($$ """); - } [Fact] - public async Task TestNotAfterMethodComma() - { - await VerifyAbsenceAsync( + public Task TestNotAfterMethodComma() + => VerifyAbsenceAsync( """ class C { void Goo(int i, $$ """); - } [Fact] - public async Task TestNotAfterMethodAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotAfterMethodAttribute() + => VerifyAbsenceAsync( """ class C { void Goo(int i, [Goo]$$ """); - } [Fact] - public async Task TestNotAfterConstructorOpenParen() - { - await VerifyAbsenceAsync( + public Task TestNotAfterConstructorOpenParen() + => VerifyAbsenceAsync( """ class C { public C($$ """); - } [Fact] - public async Task TestNotAfterConstructorComma() - { - await VerifyAbsenceAsync( + public Task TestNotAfterConstructorComma() + => VerifyAbsenceAsync( """ class C { public C(int i, $$ """); - } [Fact] - public async Task TestNotAfterConstructorAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotAfterConstructorAttribute() + => VerifyAbsenceAsync( """ class C { public C(int i, [Goo]$$ """); - } [Fact] - public async Task TestNotAfterDelegateOpenParen() - { - await VerifyAbsenceAsync( + public Task TestNotAfterDelegateOpenParen() + => VerifyAbsenceAsync( @"delegate void D($$"); - } [Fact] - public async Task TestNotAfterDelegateComma() - { - await VerifyAbsenceAsync( + public Task TestNotAfterDelegateComma() + => VerifyAbsenceAsync( @"delegate void D(int i, $$"); - } [Fact] - public async Task TestNotAfterDelegateAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotAfterDelegateAttribute() + => VerifyAbsenceAsync( @"delegate void D(int i, [Goo]$$"); - } [Fact] - public async Task TestNotAfterOperator() - { - await VerifyAbsenceAsync( + public Task TestNotAfterOperator() + => VerifyAbsenceAsync( """ class C { static int operator +($$ """); - } [Fact] - public async Task TestNotAfterDestructor() - { - await VerifyAbsenceAsync( + public Task TestNotAfterDestructor() + => VerifyAbsenceAsync( """ class C { ~C($$ """); - } [Fact] - public async Task TestNotAfterIndexer() - { - await VerifyAbsenceAsync( + public Task TestNotAfterIndexer() + => VerifyAbsenceAsync( """ class C { int this[$$ """); - } [Fact] - public async Task TestNotInInstanceMethodInInstanceClass() - { - await VerifyAbsenceAsync( + public Task TestNotInInstanceMethodInInstanceClass() + => VerifyAbsenceAsync( """ class C { int Goo($$ """); - } [Fact] - public async Task TestNotInStaticMethodInInstanceClass() - { - await VerifyAbsenceAsync( + public Task TestNotInStaticMethodInInstanceClass() + => VerifyAbsenceAsync( """ class C { static int Goo($$ """); - } [Fact] - public async Task TestNotInInstanceMethodInStaticClass() - { - await VerifyAbsenceAsync( + public Task TestNotInInstanceMethodInStaticClass() + => VerifyAbsenceAsync( """ static class C { int Goo($$ """); - } [Fact] - public async Task TestInStaticMethodInStaticClass() - { - await VerifyKeywordAsync( + public Task TestInStaticMethodInStaticClass() + => VerifyKeywordAsync( """ static class C { static int Goo($$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27028")] - public async Task TestInLocalFunction() - { - await VerifyKeywordAsync( + public Task TestInLocalFunction() + => VerifyKeywordAsync( """ class C { @@ -335,12 +264,10 @@ void local() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27028")] - public async Task TestInNestedLocalFunction() - { - await VerifyKeywordAsync( + public Task TestInNestedLocalFunction() + => VerifyKeywordAsync( """ class C { @@ -356,12 +283,10 @@ void nested() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27028")] - public async Task TestInLocalFunctionInStaticMethod() - { - await VerifyAbsenceAsync( + public Task TestInLocalFunctionInStaticMethod() + => VerifyAbsenceAsync( """ class C { static int Method() @@ -373,12 +298,10 @@ void local() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27028")] - public async Task TestInNestedLocalFunctionInStaticMethod() - { - await VerifyAbsenceAsync( + public Task TestInNestedLocalFunctionInStaticMethod() + => VerifyAbsenceAsync( """ class C { @@ -394,12 +317,10 @@ void nested() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35644")] - public async Task TestInStaticLocalFunction() - { - await VerifyAbsenceAsync( + public Task TestInStaticLocalFunction() + => VerifyAbsenceAsync( """ class C { int Method() @@ -411,12 +332,10 @@ static void local() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35644")] - public async Task TestInNestedInStaticLocalFunction() - { - await VerifyAbsenceAsync( + public Task TestInNestedInStaticLocalFunction() + => VerifyAbsenceAsync( """ class C { @@ -432,12 +351,10 @@ void nested() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27923")] - public async Task TestInAnonymousMethod() - { - await VerifyKeywordAsync( + public Task TestInAnonymousMethod() + => VerifyKeywordAsync( """ class C { @@ -450,12 +367,10 @@ int Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27923")] - public async Task TestInNestedAnonymousMethod() - { - await VerifyKeywordAsync( + public Task TestInNestedAnonymousMethod() + => VerifyKeywordAsync( """ class C { @@ -471,12 +386,10 @@ int Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27923")] - public async Task TestInAnonymousMethodInStaticMethod() - { - await VerifyAbsenceAsync( + public Task TestInAnonymousMethodInStaticMethod() + => VerifyAbsenceAsync( """ class C { @@ -489,12 +402,10 @@ static int Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27923")] - public async Task TestInNestedAnonymousMethodInStaticMethod() - { - await VerifyAbsenceAsync( + public Task TestInNestedAnonymousMethodInStaticMethod() + => VerifyAbsenceAsync( """ class C { @@ -510,12 +421,10 @@ static int Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27923")] - public async Task TestInLambdaExpression() - { - await VerifyKeywordAsync( + public Task TestInLambdaExpression() + => VerifyKeywordAsync( """ class C { @@ -528,12 +437,10 @@ int Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27923")] - public async Task TestInNestedLambdaExpression() - { - await VerifyKeywordAsync( + public Task TestInNestedLambdaExpression() + => VerifyKeywordAsync( """ class C { @@ -549,12 +456,10 @@ int Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27923")] - public async Task TestInLambdaExpressionInStaticMethod() - { - await VerifyAbsenceAsync( + public Task TestInLambdaExpressionInStaticMethod() + => VerifyAbsenceAsync( """ class C { @@ -567,12 +472,10 @@ static int Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27923")] - public async Task TestInNestedLambdaExpressionInStaticMethod() - { - await VerifyAbsenceAsync( + public Task TestInNestedLambdaExpressionInStaticMethod() + => VerifyAbsenceAsync( """ class C { @@ -588,12 +491,10 @@ static int Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27923")] - public async Task TestInNestedLambdaExpressionInAnonymousMethod() - { - await VerifyKeywordAsync( + public Task TestInNestedLambdaExpressionInAnonymousMethod() + => VerifyKeywordAsync( """ class C { @@ -609,12 +510,10 @@ int Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27923")] - public async Task TestInNestedAnonymousInLambdaExpression() - { - await VerifyKeywordAsync( + public Task TestInNestedAnonymousInLambdaExpression() + => VerifyKeywordAsync( """ class C { @@ -630,12 +529,10 @@ int Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27923")] - public async Task TestInNestedAnonymousMethodInLambdaExpressionInStaticMethod() - { - await VerifyAbsenceAsync( + public Task TestInNestedAnonymousMethodInLambdaExpressionInStaticMethod() + => VerifyAbsenceAsync( """ class C { @@ -651,12 +548,10 @@ static int Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27923")] - public async Task TestInNestedLambdaExpressionInAnonymousMethodInStaticMethod() - { - await VerifyAbsenceAsync( + public Task TestInNestedLambdaExpressionInAnonymousMethodInStaticMethod() + => VerifyAbsenceAsync( """ class C { @@ -672,12 +567,10 @@ static int Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27923")] - public async Task TestInAnonymousMethodInAProperty() - { - await VerifyKeywordAsync( + public Task TestInAnonymousMethodInAProperty() + => VerifyKeywordAsync( """ class C { @@ -687,48 +580,40 @@ Action A } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27923")] - public async Task TestInAnonymousMethodInAPropertyInitializer() - { - await VerifyKeywordAsync( + public Task TestInAnonymousMethodInAPropertyInitializer() + => VerifyKeywordAsync( """ class C { Action B { get; } = delegate { $$ } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27923")] - public async Task TestInAnonymousMethodInAExpressionProperty() - { - await VerifyKeywordAsync( + public Task TestInAnonymousMethodInAExpressionProperty() + => VerifyKeywordAsync( """ class C { Action A => delegate { $$ } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27923")] - public async Task TestInAnonymousMethodInAFieldInitializer() - { - await VerifyKeywordAsync( + public Task TestInAnonymousMethodInAFieldInitializer() + => VerifyKeywordAsync( """ class C { Action A = delegate { $$ } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27923")] - public async Task TestInAnonymousMethodInAStaticProperty() - { - await VerifyAbsenceAsync( + public Task TestInAnonymousMethodInAStaticProperty() + => VerifyAbsenceAsync( """ class C { @@ -738,212 +623,168 @@ static Action A } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27923")] - public async Task TestInAnonymousMethodInAStaticPropertyInitializer() - { - await VerifyAbsenceAsync( + public Task TestInAnonymousMethodInAStaticPropertyInitializer() + => VerifyAbsenceAsync( """ class C { static Action B { get; } = delegate { $$ } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27923")] - public async Task TestInAnonymousMethodInAStaticExpressionProperty() - { - await VerifyAbsenceAsync( + public Task TestInAnonymousMethodInAStaticExpressionProperty() + => VerifyAbsenceAsync( """ class C { static Action A => delegate { $$ } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27923")] - public async Task TestInAnonymousMethodInAStaticFieldInitializer() - { - await VerifyAbsenceAsync( + public Task TestInAnonymousMethodInAStaticFieldInitializer() + => VerifyAbsenceAsync( """ class C { static Action A = delegate { $$ } } """); - } [Fact] - public async Task TestAfterAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterAttribute() + => VerifyKeywordAsync( """ static class C { static int Goo([Bar]$$ """); - } [Fact] - public async Task TestNotAfterSecondAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotAfterSecondAttribute() + => VerifyAbsenceAsync( """ static class C { static int Goo(this int i, [Bar]$$ """); - } [Fact] - public async Task TestNotAfterThis() - { - await VerifyAbsenceAsync( + public Task TestNotAfterThis() + => VerifyAbsenceAsync( """ static class C { static int Goo(this $$ """); - } [Fact] - public async Task TestNotAfterFirstParameter() - { - await VerifyAbsenceAsync( + public Task TestNotAfterFirstParameter() + => VerifyAbsenceAsync( """ static class C { static int Goo(this int a, $$ """); - } [Fact] - public async Task TestInClassConstructorInitializer() - { - await VerifyKeywordAsync( + public Task TestInClassConstructorInitializer() + => VerifyKeywordAsync( """ class C { public C() : $$ """); - } [Fact] - public async Task TestNotInStaticClassConstructorInitializer() - { - await VerifyAbsenceAsync( + public Task TestNotInStaticClassConstructorInitializer() + => VerifyAbsenceAsync( """ class C { static C() : $$ """); - } [Fact] - public async Task TestInStructConstructorInitializer() - { - await VerifyKeywordAsync( + public Task TestInStructConstructorInitializer() + => VerifyKeywordAsync( """ struct C { public C() : $$ """); - } [Fact] - public async Task TestInEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterCast() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterCast() + => VerifyKeywordAsync(AddInsideMethod( @"stack.Push(((IEnumerable)((TreeSegment)$$")); - } [Fact] - public async Task TestAfterReturn() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterReturn() + => VerifyKeywordAsync(AddInsideMethod( @"return $$")); - } [Fact] - public async Task TestAfterIndexer() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIndexer() + => VerifyKeywordAsync(AddInsideMethod( @"return this.items[$$")); - } [Fact] - public async Task TestAfterSimpleCast() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterSimpleCast() + => VerifyKeywordAsync(AddInsideMethod( @"return ((IEnumerable)$$")); - } [Fact] - public async Task TestNotInClass() - { - await VerifyAbsenceAsync( + public Task TestNotInClass() + => VerifyAbsenceAsync( """ class C { $$ """); - } [Fact] - public async Task TestNotAfterVoid() - { - await VerifyAbsenceAsync( + public Task TestNotAfterVoid() + => VerifyAbsenceAsync( """ class C { void $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542636")] - public async Task TestAfterType() - { - await VerifyAbsenceAsync( + public Task TestAfterType() + => VerifyAbsenceAsync( """ class C { int $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542636")] - public async Task TestAfterTypeArray() - { - await VerifyAbsenceAsync( + public Task TestAfterTypeArray() + => VerifyAbsenceAsync( """ class C { internal byte[] $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542636")] - public async Task TestAfterTypeArrayBeforeArguments() - { - await VerifyAbsenceAsync( + public Task TestAfterTypeArrayBeforeArguments() + => VerifyAbsenceAsync( """ class C { internal byte[] $$[int i] { get; } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542636")] - public async Task TestAfterTypeBeforeArguments() - { - await VerifyAbsenceAsync( + public Task TestAfterTypeBeforeArguments() + => VerifyAbsenceAsync( """ class C { internal byte $$[int i] { get; } """); - } [Fact] - public async Task TestAfterMultiply() - { - await VerifyKeywordAsync( + public Task TestAfterMultiply() + => VerifyKeywordAsync( """ class C { internal CustomAttributeRow this[uint rowId] // This is 1 based... @@ -953,102 +794,84 @@ internal CustomAttributeRow this[uint rowId] // This is 1 based... { int rowOffset = (int)(rowId - 1) * $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] - public async Task TestNotInStaticMethod() - { - await VerifyAbsenceAsync( + public Task TestNotInStaticMethod() + => VerifyAbsenceAsync( """ class C { static void Goo() { int i = $$ } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] - public async Task TestNotInStaticProperty() - { - await VerifyAbsenceAsync( + public Task TestNotInStaticProperty() + => VerifyAbsenceAsync( """ class C { static int Goo { get { int i = $$ } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] - public async Task TestInInstanceProperty() - { - await VerifyKeywordAsync( + public Task TestInInstanceProperty() + => VerifyKeywordAsync( """ class C { int Goo { get { int i = $$ } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] - public async Task TestNotInStaticConstructor() - { - await VerifyAbsenceAsync( + public Task TestNotInStaticConstructor() + => VerifyAbsenceAsync( """ class C { static C() { int i = $$ } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] - public async Task TestInInstanceConstructor() - { - await VerifyKeywordAsync( + public Task TestInInstanceConstructor() + => VerifyKeywordAsync( """ class C { public C() { int i = $$ } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] - public async Task TestNotInEnumMemberInitializer1() - { - await VerifyAbsenceAsync( + public Task TestNotInEnumMemberInitializer1() + => VerifyAbsenceAsync( """ enum E { a = $$ } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539334")] - public async Task TestNotAfterPartialInType() - { - await VerifyAbsenceAsync( + public Task TestNotAfterPartialInType() + => VerifyAbsenceAsync( """ class C { partial $$ } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540476")] - public async Task TestNotAfterIncompleteTypeName() - { - await VerifyAbsenceAsync( + public Task TestNotAfterIncompleteTypeName() + => VerifyAbsenceAsync( """ class C { Goo.$$ } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541712")] - public async Task TestNotInStaticMethodContext() - { - await VerifyAbsenceAsync( + public Task TestNotInStaticMethodContext() + => VerifyAbsenceAsync( """ class Program { @@ -1058,12 +881,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -1071,13 +892,11 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107414")] [WorkItem("https://github.com/dotnet/roslyn/issues/725")] - public async Task TestInExpressionBodiedMembersProperty() - { - await VerifyKeywordAsync(""" + public Task TestInExpressionBodiedMembersProperty() + => VerifyKeywordAsync(""" class C { int x; @@ -1085,61 +904,51 @@ class C int p; } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107414")] [WorkItem("https://github.com/dotnet/roslyn/issues/725")] - public async Task TestInExpressionBodiedMembersMethod() - { - await VerifyKeywordAsync(""" + public Task TestInExpressionBodiedMembersMethod() + => VerifyKeywordAsync(""" class C { int x; int give() => $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107414")] [WorkItem("https://github.com/dotnet/roslyn/issues/725")] - public async Task TestInExpressionBodiedMembersIndexer() - { - await VerifyKeywordAsync(""" + public Task TestInExpressionBodiedMembersIndexer() + => VerifyKeywordAsync(""" class C { int x; public object this[int i] => $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107414")] [WorkItem("https://github.com/dotnet/roslyn/issues/725")] - public async Task TestNotInExpressionBodiedMembers_Static() - { - await VerifyAbsenceAsync(""" + public Task TestNotInExpressionBodiedMembers_Static() + => VerifyAbsenceAsync(""" class C { int x; static int M => $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107414")] [WorkItem("https://github.com/dotnet/roslyn/issues/725")] - public async Task TestNotInExpressionBodiedMembersOperator() - { - await VerifyAbsenceAsync(""" + public Task TestNotInExpressionBodiedMembersOperator() + => VerifyAbsenceAsync(""" class C { int x; public static C operator - (C c1) => $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107414")] [WorkItem("https://github.com/dotnet/roslyn/issues/725")] - public async Task TestNotInExpressionBodiedMembersConversionOperator() - { - await VerifyAbsenceAsync(""" + public Task TestNotInExpressionBodiedMembersConversionOperator() + => VerifyAbsenceAsync(""" class F { } @@ -1149,13 +958,11 @@ class C int x; public static explicit operator F(C c1) => $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107414")] [WorkItem("https://github.com/dotnet/roslyn/issues/725")] - public async Task TestOutsideExpressionBodiedMember() - { - await VerifyAbsenceAsync(""" + public Task TestOutsideExpressionBodiedMember() + => VerifyAbsenceAsync(""" class C { int x; @@ -1163,12 +970,10 @@ class C int p; } """); - } [Fact] - public async Task Preselection() - { - await VerifyKeywordAsync(""" + public Task Preselection() + => VerifyKeywordAsync(""" class Program { void Main(string[] args) @@ -1178,7 +983,6 @@ void Main(string[] args) void Helper(Program x) { } } """); - } [Fact] public async Task TestExtensionMethods_FirstParameter_AfterRefKeyword_InClass() @@ -1409,127 +1213,105 @@ public void Extension(out $$ object obj, int x) { } } [Fact] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ThrowKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ThrowKeywordRecommenderTests.cs index b96e882875b8d..b29728c806f91 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ThrowKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ThrowKeywordRecommenderTests.cs @@ -13,188 +13,149 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ThrowKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestBeforeStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBeforeStatement() + => VerifyKeywordAsync(AddInsideMethod( """ $$ return true; """)); - } [Fact] - public async Task TestAfterStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterStatement() + => VerifyKeywordAsync(AddInsideMethod( """ return true; $$ """)); - } [Fact] - public async Task TestAfterBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBlock() + => VerifyKeywordAsync(AddInsideMethod( """ if (true) { } $$ """)); - } [Fact] - public async Task TestAfterIf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIf() + => VerifyKeywordAsync(AddInsideMethod( """ if (true) $$ """)); - } [Fact] - public async Task TestAfterDo() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterDo() + => VerifyKeywordAsync(AddInsideMethod( """ do $$ """)); - } [Fact] - public async Task TestAfterWhile() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterWhile() + => VerifyKeywordAsync(AddInsideMethod( """ while (true) $$ """)); - } [Fact] - public async Task TestAfterFor() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterFor() + => VerifyKeywordAsync(AddInsideMethod( """ for (int i = 0; i < 10; i++) $$ """)); - } [Fact] - public async Task TestAfterForeach() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterForeach() + => VerifyKeywordAsync(AddInsideMethod( """ foreach (var v in bar) $$ """)); - } [Fact] - public async Task TestNotAfterThrow() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterThrow() + => VerifyAbsenceAsync(AddInsideMethod( @"throw $$")); - } [Fact] - public async Task TestNotInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotInClass() + => VerifyAbsenceAsync(""" class C { $$ } """); - } [Fact] - public async Task TestInNestedIf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInNestedIf() + => VerifyKeywordAsync(AddInsideMethod( """ if (caseOrDefaultKeywordOpt != null) { if (caseOrDefaultKeyword.Kind != SyntaxKind.CaseKeyword && caseOrDefaultKeyword.Kind != SyntaxKind.DefaultKeyword) $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/9099")] - public async Task TestAfterArrow() - { - await VerifyKeywordAsync( + public Task TestAfterArrow() + => VerifyKeywordAsync( """ class C { void Goo() => $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/9099")] - public async Task TestAfterQuestionQuestion() - { - await VerifyKeywordAsync( + public Task TestAfterQuestionQuestion() + => VerifyKeywordAsync( """ class C { @@ -202,12 +163,10 @@ public C(object o) { _o = o ?? $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/9099")] - public async Task TestInConditional1() - { - await VerifyKeywordAsync( + public Task TestInConditional1() + => VerifyKeywordAsync( """ class C { @@ -215,12 +174,10 @@ public C(object o) { var v= true ? $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/9099")] - public async Task TestInConditional2() - { - await VerifyKeywordAsync( + public Task TestInConditional2() + => VerifyKeywordAsync( """ class C { @@ -228,5 +185,4 @@ public C(object o) { var v= true ? 0 : $$ """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/TrueKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/TrueKeywordRecommenderTests.cs index 3a5444e580661..c2731d3db450b 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/TrueKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/TrueKeywordRecommenderTests.cs @@ -13,243 +13,188 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class TrueKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInPreprocessor1() - { - await VerifyAbsenceAsync( + public Task TestNotInPreprocessor1() + => VerifyAbsenceAsync( """ class C { #$$ """); - } [Fact] - public async Task TestNotInPreprocessor2() - { - await VerifyAbsenceAsync( + public Task TestNotInPreprocessor2() + => VerifyAbsenceAsync( """ class C { #line $$ """); - } [Fact] - public async Task TestInEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInExpression() + => VerifyKeywordAsync(AddInsideMethod( @"var q = $$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542970")] - public async Task TestInPPIf() - { - await VerifyKeywordAsync( + public Task TestInPPIf() + => VerifyKeywordAsync( @"#if $$"); - } [Fact] - public async Task TestInPPIf_Or() - { - await VerifyKeywordAsync( + public Task TestInPPIf_Or() + => VerifyKeywordAsync( @"#if a || $$"); - } [Fact] - public async Task TestInPPIf_And() - { - await VerifyKeywordAsync( + public Task TestInPPIf_And() + => VerifyKeywordAsync( @"#if a && $$"); - } [Fact] - public async Task TestInPPIf_Not() - { - await VerifyKeywordAsync( + public Task TestInPPIf_Not() + => VerifyKeywordAsync( @"#if ! $$"); - } [Fact] - public async Task TestInPPIf_Paren() - { - await VerifyKeywordAsync( + public Task TestInPPIf_Paren() + => VerifyKeywordAsync( @"#if ( $$"); - } [Fact] - public async Task TestInPPIf_Equals() - { - await VerifyKeywordAsync( + public Task TestInPPIf_Equals() + => VerifyKeywordAsync( @"#if a == $$"); - } [Fact] - public async Task TestInPPIf_NotEquals() - { - await VerifyKeywordAsync( + public Task TestInPPIf_NotEquals() + => VerifyKeywordAsync( @"#if a != $$"); - } [Fact] - public async Task TestInPPElIf() - { - await VerifyKeywordAsync( + public Task TestInPPElIf() + => VerifyKeywordAsync( """ #if true #elif $$ """); - } [Fact] - public async Task TestInPPelIf_Or() - { - await VerifyKeywordAsync( + public Task TestInPPelIf_Or() + => VerifyKeywordAsync( """ #if true #elif a || $$ """); - } [Fact] - public async Task TestInPPElIf_And() - { - await VerifyKeywordAsync( + public Task TestInPPElIf_And() + => VerifyKeywordAsync( """ #if true #elif a && $$ """); - } [Fact] - public async Task TestInPPElIf_Not() - { - await VerifyKeywordAsync( + public Task TestInPPElIf_Not() + => VerifyKeywordAsync( """ #if true #elif ! $$ """); - } [Fact] - public async Task TestInPPElIf_Paren() - { - await VerifyKeywordAsync( + public Task TestInPPElIf_Paren() + => VerifyKeywordAsync( """ #if true #elif ( $$ """); - } [Fact] - public async Task TestInPPElIf_Equals() - { - await VerifyKeywordAsync( + public Task TestInPPElIf_Equals() + => VerifyKeywordAsync( """ #if true #elif a == $$ """); - } [Fact] - public async Task TestInPPElIf_NotEquals() - { - await VerifyKeywordAsync( + public Task TestInPPElIf_NotEquals() + => VerifyKeywordAsync( """ #if true #elif a != $$ """); - } [Fact] - public async Task TestAfterUnaryOperator() - { - await VerifyKeywordAsync( + public Task TestAfterUnaryOperator() + => VerifyKeywordAsync( """ class C { public static bool operator $$ """); - } [Fact] - public async Task TestNotAfterImplicitOperator() - { - await VerifyAbsenceAsync( + public Task TestNotAfterImplicitOperator() + => VerifyAbsenceAsync( """ class C { public static implicit operator $$ """); - } [Fact] - public async Task TestNotAfterExplicitOperator() - { - await VerifyAbsenceAsync( + public Task TestNotAfterExplicitOperator() + => VerifyAbsenceAsync( """ class C { public static implicit operator $$ """); - } [Fact] - public async Task TestBeforeInactiveRegion() - { - await VerifyKeywordAsync( + public Task TestBeforeInactiveRegion() + => VerifyKeywordAsync( """ class C { @@ -258,33 +203,25 @@ void Init() #if $$ H """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotAfterTypeOf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterTypeOf() + => VerifyAbsenceAsync(AddInsideMethod( @"typeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotAfterDefault() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterDefault() + => VerifyAbsenceAsync(AddInsideMethod( @"default($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotAfterSizeOf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterSizeOf() + => VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -292,129 +229,106 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/TryKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/TryKeywordRecommenderTests.cs index 10d22d88dfb30..0df3b38cdd3fc 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/TryKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/TryKeywordRecommenderTests.cs @@ -12,141 +12,111 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class TryKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestBeforeStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBeforeStatement() + => VerifyKeywordAsync(AddInsideMethod( """ $$ return true; """)); - } [Fact] - public async Task TestAfterStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterStatement() + => VerifyKeywordAsync(AddInsideMethod( """ return true; $$ """)); - } [Fact] - public async Task TestAfterBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBlock() + => VerifyKeywordAsync(AddInsideMethod( """ if (true) { } $$ """)); - } [Fact] - public async Task TestNotAfterTry() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterTry() + => VerifyAbsenceAsync(AddInsideMethod( @"try $$")); - } [Fact] - public async Task TestInsideTry() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideTry() + => VerifyKeywordAsync(AddInsideMethod( """ try { $$ """)); - } [Fact] - public async Task TestInsideCatch() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideCatch() + => VerifyKeywordAsync(AddInsideMethod( """ try { } catch { $$ """)); - } [Fact] - public async Task TestInsideFinally() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideFinally() + => VerifyKeywordAsync(AddInsideMethod( """ try { } finally { $$ """)); - } [Fact] - public async Task TestNotInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotInClass() + => VerifyAbsenceAsync(""" class C { $$ } """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/TypeKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/TypeKeywordRecommenderTests.cs index fbfa8f28f8189..980a92264d571 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/TypeKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/TypeKeywordRecommenderTests.cs @@ -12,100 +12,79 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class TypeKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInAttributeInsideClass() - { - await VerifyKeywordAsync( + public Task TestInAttributeInsideClass() + => VerifyKeywordAsync( """ class C { [$$ """); - } [Fact] - public async Task TestInAttributeAfterAttributeInsideClass() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterAttributeInsideClass() + => VerifyKeywordAsync( """ class C { [Goo] [$$ """); - } [Fact] - public async Task TestInAttributeAfterMethod() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() { } [$$ """); - } [Fact] - public async Task TestInAttributeAfterProperty() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterProperty() + => VerifyKeywordAsync( """ class C { int Goo { @@ -113,118 +92,93 @@ int Goo { } [$$ """); - } [Fact] - public async Task TestInAttributeAfterField() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterField() + => VerifyKeywordAsync( """ class C { int Goo; [$$ """); - } [Fact] - public async Task TestInAttributeAfterEvent() - { - await VerifyKeywordAsync( + public Task TestInAttributeAfterEvent() + => VerifyKeywordAsync( """ class C { event Action Goo; [$$ """); - } [Fact] - public async Task TestInOuterAttribute() - { - await VerifyKeywordAsync( + public Task TestInOuterAttribute() + => VerifyKeywordAsync( @"[$$"); - } [Fact] - public async Task TestNotInParameterAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInParameterAttribute() + => VerifyAbsenceAsync( """ class C { void Goo([$$ """); - } [Fact] - public async Task TestNotInPropertyAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAttribute() + => VerifyAbsenceAsync( """ class C { int Goo { [$$ """); - } [Fact] - public async Task TestNotInEventAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInEventAttribute() + => VerifyAbsenceAsync( """ class C { event Action Goo { [$$ """); - } [Fact] - public async Task TestNotInClassTypeParameters() - { - await VerifyAbsenceAsync( + public Task TestNotInClassTypeParameters() + => VerifyAbsenceAsync( @"class C<[$$"); - } [Fact] - public async Task TestNotInDelegateTypeParameters() - { - await VerifyAbsenceAsync( + public Task TestNotInDelegateTypeParameters() + => VerifyAbsenceAsync( @"delegate void D<[$$"); - } [Fact] - public async Task TestNotInMethodTypeParameters() - { - await VerifyAbsenceAsync( + public Task TestNotInMethodTypeParameters() + => VerifyAbsenceAsync( """ class C { void M<[$$ """); - } [Fact] - public async Task TestInInterface() - { - await VerifyKeywordAsync( + public Task TestInInterface() + => VerifyKeywordAsync( """ interface I { [$$ """); - } [Fact] - public async Task TestInStruct() - { - await VerifyKeywordAsync( + public Task TestInStruct() + => VerifyKeywordAsync( """ struct S { [$$ """); - } [Fact] - public async Task TestNotInEnum() - { - await VerifyAbsenceAsync( + public Task TestNotInEnum() + => VerifyAbsenceAsync( """ enum E { [$$ """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/TypeOfKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/TypeOfKeywordRecommenderTests.cs index 4b1775ac8bc75..b57a85f254b8e 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/TypeOfKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/TypeOfKeywordRecommenderTests.cs @@ -17,57 +17,46 @@ public async Task TestOfferedInAttributeConstructorArgumentList() => await VerifyKeywordAsync("using System.ComponentModel; [DefaultValue($$ class C { }"); [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] - public async Task TestNotInConstMemberInitializer1() - { - await VerifyAbsenceAsync( + public Task TestNotInConstMemberInitializer1() + => VerifyAbsenceAsync( """ class E { const int a = $$ } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] - public async Task TestNotInConstLocalInitializer1() - { - await VerifyAbsenceAsync( + public Task TestNotInConstLocalInitializer1() + => VerifyAbsenceAsync( """ class E { void Goo() { @@ -75,44 +64,34 @@ void Goo() { } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] - public async Task TestInMemberInitializer1() - { - await VerifyKeywordAsync( + public Task TestInMemberInitializer1() + => VerifyKeywordAsync( """ class E { int a = $$ } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInTypeOf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInTypeOf() + => VerifyAbsenceAsync(AddInsideMethod( @"typeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInDefault() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInDefault() + => VerifyAbsenceAsync(AddInsideMethod( @"default($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInSizeOf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInSizeOf() + => VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -120,130 +99,107 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/TypeVarKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/TypeVarKeywordRecommenderTests.cs index f0d11ec13f3d0..da5979022d522 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/TypeVarKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/TypeVarKeywordRecommenderTests.cs @@ -12,100 +12,79 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class TypeVarKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestNotInAttributeInsideClass() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeInsideClass() + => VerifyAbsenceAsync( """ class C { [$$ """); - } [Fact] - public async Task TestNotInAttributeAfterAttributeInsideClass() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeAfterAttributeInsideClass() + => VerifyAbsenceAsync( """ class C { [Goo] [$$ """); - } [Fact] - public async Task TestNotInAttributeAfterMethod() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeAfterMethod() + => VerifyAbsenceAsync( """ class C { void Goo() { } [$$ """); - } [Fact] - public async Task TestNotInAttributeAfterProperty() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeAfterProperty() + => VerifyAbsenceAsync( """ class C { int Goo { @@ -113,118 +92,93 @@ int Goo { } [$$ """); - } [Fact] - public async Task TestNotInAttributeAfterField() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeAfterField() + => VerifyAbsenceAsync( """ class C { int Goo; [$$ """); - } [Fact] - public async Task TestNotInAttributeAfterEvent() - { - await VerifyAbsenceAsync( + public Task TestNotInAttributeAfterEvent() + => VerifyAbsenceAsync( """ class C { event Action Goo; [$$ """); - } [Fact] - public async Task TestNotInOuterAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInOuterAttribute() + => VerifyAbsenceAsync( @"[$$"); - } [Fact] - public async Task TestNotInParameterAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInParameterAttribute() + => VerifyAbsenceAsync( """ class C { void Goo([$$ """); - } [Fact] - public async Task TestNotInPropertyAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAttribute() + => VerifyAbsenceAsync( """ class C { int Goo { [$$ """); - } [Fact] - public async Task TestNotInEventAttribute() - { - await VerifyAbsenceAsync( + public Task TestNotInEventAttribute() + => VerifyAbsenceAsync( """ class C { event Action Goo { [$$ """); - } [Fact] - public async Task TestInClassTypeParameters() - { - await VerifyKeywordAsync( + public Task TestInClassTypeParameters() + => VerifyKeywordAsync( @"class C<[$$"); - } [Fact] - public async Task TestInDelegateTypeParameters() - { - await VerifyKeywordAsync( + public Task TestInDelegateTypeParameters() + => VerifyKeywordAsync( @"delegate void D<[$$"); - } [Fact] - public async Task TestInMethodTypeParameters() - { - await VerifyKeywordAsync( + public Task TestInMethodTypeParameters() + => VerifyKeywordAsync( """ class C { void M<[$$ """); - } [Fact] - public async Task TestNotInInterface() - { - await VerifyAbsenceAsync( + public Task TestNotInInterface() + => VerifyAbsenceAsync( """ interface I { [$$ """); - } [Fact] - public async Task TestNotInStruct() - { - await VerifyAbsenceAsync( + public Task TestNotInStruct() + => VerifyAbsenceAsync( """ struct S { [$$ """); - } [Fact] - public async Task TestNotInEnum() - { - await VerifyAbsenceAsync( + public Task TestNotInEnum() + => VerifyAbsenceAsync( """ enum E { [$$ """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/UIntKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/UIntKeywordRecommenderTests.cs index bf5e7a447a1b7..eadcd8c9fe097 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/UIntKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/UIntKeywordRecommenderTests.cs @@ -13,712 +13,549 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class UIntKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsing() - { - await VerifyAbsenceAsync( + public Task TestNotInUsing() + => VerifyAbsenceAsync( @"using $$"); - } [Fact] - public async Task TestInUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInUsingAlias() + => VerifyKeywordAsync( @"using Goo = $$"); - } [Fact] - public async Task TestInGlobalUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInGlobalUsingAlias() + => VerifyKeywordAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestAfterStackAlloc() - { - await VerifyKeywordAsync( + public Task TestAfterStackAlloc() + => VerifyKeywordAsync( """ class C { int* goo = stackalloc $$ """); - } [Fact] - public async Task TestInFixedStatement() - { - await VerifyKeywordAsync( + public Task TestInFixedStatement() + => VerifyKeywordAsync( @"fixed ($$"); - } [Fact] - public async Task TestInDelegateReturnType() - { - await VerifyKeywordAsync( + public Task TestInDelegateReturnType() + => VerifyKeywordAsync( @"public delegate $$"); - } [Fact] - public async Task TestInCastType() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); - } [Fact] - public async Task TestInCastType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType2() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); - } [Fact] - public async Task TestAfterConstInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterConstInMemberContext() + => VerifyKeywordAsync( """ class C { const $$ """); - } [Fact] - public async Task TestAfterRefInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefInMemberContext() + => VerifyKeywordAsync( """ class C { ref $$ """); - } [Fact] - public async Task TestAfterRefReadonlyInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyInMemberContext() + => VerifyKeywordAsync( """ class C { ref readonly $$ """); - } [Fact] - public async Task TestAfterConstInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"const $$")); - } [Fact] - public async Task TestAfterRefInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$")); - } [Fact] - public async Task TestAfterRefReadonlyInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); - } [Fact] - public async Task TestAfterConstLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); - } [Fact] - public async Task TestAfterRefReadonlyLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); - } [Fact] - public async Task TestAfterRefReadonlyLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); - } [Fact] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } [Fact] - public async Task TestInEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestEnumBaseTypes() - { - await VerifyKeywordAsync( + public Task TestEnumBaseTypes() + => VerifyKeywordAsync( @"enum E : $$"); - } [Fact] - public async Task TestInGenericType1() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType1() + => VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); - } [Fact] - public async Task TestInGenericType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType2() + => VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList,$$")); - } [Fact] - public async Task TestNotInBaseList() - { - await VerifyAbsenceAsync( + public Task TestNotInBaseList() + => VerifyAbsenceAsync( @"class C : $$"); - } [Fact] - public async Task TestInGenericType_InBaseList() - { - await VerifyKeywordAsync( + public Task TestInGenericType_InBaseList() + => VerifyKeywordAsync( @"class C : IList<$$"); - } [Fact] - public async Task TestAfterIs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); - } [Fact] - public async Task TestAfterAs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterAs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync( + public Task TestInsideInterface() + => VerifyKeywordAsync( """ interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact] - public async Task TestAfterNestedPartial() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPartial() + => VerifyKeywordAsync( """ class C { partial $$ """); - } [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] - public async Task TestAfterNestedStaticPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticPublic() + => VerifyKeywordAsync( """ class C { static public $$ """); - } [Fact] - public async Task TestAfterNestedPublicStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublicStatic() + => VerifyKeywordAsync( """ class C { public static $$ """); - } [Fact] - public async Task TestAfterVirtualPublic() - { - await VerifyKeywordAsync( + public Task TestAfterVirtualPublic() + => VerifyKeywordAsync( """ class C { virtual public $$ """); - } [Fact] - public async Task TestAfterNestedPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublic() + => VerifyKeywordAsync( """ class C { public $$ """); - } [Fact] - public async Task TestAfterNestedPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPrivate() + => VerifyKeywordAsync( """ class C { private $$ """); - } [Fact] - public async Task TestAfterNestedProtected() - { - await VerifyKeywordAsync( + public Task TestAfterNestedProtected() + => VerifyKeywordAsync( """ class C { protected $$ """); - } [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] - public async Task TestAfterNestedStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStatic() + => VerifyKeywordAsync( """ class C { static $$ """); - } [Fact] - public async Task TestInLocalVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLocalVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInForVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"for ($$")); - } [Fact] - public async Task TestInForeachVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForeachVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); - } [Fact] - public async Task TestInUsingVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInUsingVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"using ($$")); - } [Fact] - public async Task TestInFromVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFromVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); - } [Fact] - public async Task TestInJoinVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInJoinVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from a in b join $$ """)); - } [Fact] - public async Task TestAfterMethodOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterMethodOpenParen() + => VerifyKeywordAsync( """ class C { void Goo($$ """); - } [Fact] - public async Task TestAfterMethodComma() - { - await VerifyKeywordAsync( + public Task TestAfterMethodComma() + => VerifyKeywordAsync( """ class C { void Goo(int i, $$ """); - } [Fact] - public async Task TestAfterMethodAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterMethodAttribute() + => VerifyKeywordAsync( """ class C { void Goo(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterConstructorOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorOpenParen() + => VerifyKeywordAsync( """ class C { public C($$ """); - } [Fact] - public async Task TestAfterConstructorComma() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorComma() + => VerifyKeywordAsync( """ class C { public C(int i, $$ """); - } [Fact] - public async Task TestAfterConstructorAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorAttribute() + => VerifyKeywordAsync( """ class C { public C(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterDelegateOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateOpenParen() + => VerifyKeywordAsync( @"delegate void D($$"); - } [Fact] - public async Task TestAfterDelegateComma() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateComma() + => VerifyKeywordAsync( @"delegate void D(int i, $$"); - } [Fact] - public async Task TestAfterDelegateAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateAttribute() + => VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); - } [Fact] - public async Task TestAfterThis() - { - await VerifyKeywordAsync( + public Task TestAfterThis() + => VerifyKeywordAsync( """ static class C { public static void Goo(this $$ """); - } [Fact] - public async Task TestAfterRef() - { - await VerifyKeywordAsync( + public Task TestAfterRef() + => VerifyKeywordAsync( """ class C { void Goo(ref $$ """); - } [Fact] - public async Task TestAfterOut() - { - await VerifyKeywordAsync( + public Task TestAfterOut() + => VerifyKeywordAsync( """ class C { void Goo(out $$ """); - } [Fact] - public async Task TestAfterLambdaRef() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaRef() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (ref $$ """); - } [Fact] - public async Task TestAfterLambdaOut() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaOut() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (out $$ """); - } [Fact] - public async Task TestAfterParams() - { - await VerifyKeywordAsync( + public Task TestAfterParams() + => VerifyKeywordAsync( """ class C { void Goo(params $$ """); - } [Fact] - public async Task TestInImplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInImplicitOperator() + => VerifyKeywordAsync( """ class C { public static implicit operator $$ """); - } [Fact] - public async Task TestInExplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInExplicitOperator() + => VerifyKeywordAsync( """ class C { public static explicit operator $$ """); - } [Fact] - public async Task TestAfterIndexerBracket() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracket() + => VerifyKeywordAsync( """ class C { int this[$$ """); - } [Fact] - public async Task TestAfterIndexerBracketComma() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracketComma() + => VerifyKeywordAsync( """ class C { int this[int i, $$ """); - } [Fact] - public async Task TestAfterNewInExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterNewInExpression() + => VerifyKeywordAsync(AddInsideMethod( @"new $$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInTypeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInTypeOf() + => VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInDefault() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDefault() + => VerifyKeywordAsync(AddInsideMethod( @"default($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInSizeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInSizeOf() + => VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -726,12 +563,10 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] - public async Task TestInCrefContext() - { - await VerifyKeywordAsync(""" + public Task TestInCrefContext() + => VerifyKeywordAsync(""" class Program { /// @@ -741,16 +576,13 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] - public async Task TestInCrefContextNotAfterDot() - { - await VerifyAbsenceAsync(""" + public Task TestInCrefContextNotAfterDot() + => VerifyAbsenceAsync(""" /// class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] public async Task TestNotAfterAsync() @@ -761,19 +593,16 @@ public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1468")] - public async Task TestNotInCrefTypeParameter() - { - await VerifyAbsenceAsync(""" + public Task TestNotInCrefTypeParameter() + => VerifyAbsenceAsync(""" using System; /// class C { } """); - } [Fact] - public async Task Preselection() - { - await VerifyKeywordAsync(""" + public Task Preselection() + => VerifyKeywordAsync(""" class Program { static void Main(string[] args) @@ -783,23 +612,19 @@ static void Main(string[] args) static void Helper(uint x) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinType() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinType() + => VerifyKeywordAsync(""" class Program { ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinMember() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinMember() + => VerifyKeywordAsync(""" class Program { void Method() @@ -808,82 +633,66 @@ void Method() } } """); - } [Fact] - public async Task TestInFunctionPointerType() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerType() + => VerifyKeywordAsync(""" class C { delegate*<$$ """); - } [Fact] - public async Task TestInFunctionPointerTypeAfterComma() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerTypeAfterComma() + => VerifyKeywordAsync(""" class C { delegate* VerifyKeywordAsync(""" class C { delegate* VerifyAbsenceAsync(""" class C { delegate*$$ """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/53585")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithoutAsync))] - public async Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) - { - await VerifyKeywordAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) + => VerifyKeywordAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithAsync))] - public async Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) - { - await VerifyAbsenceAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) + => VerifyAbsenceAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64585")] - public async Task TestAfterRequired() - { - await VerifyKeywordAsync(""" + public Task TestAfterRequired() + => VerifyKeywordAsync(""" class C { required $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefAtTopLevel1() + => VerifyKeywordAsync( @"ref $$"); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [CombinatorialData] @@ -904,216 +713,183 @@ await VerifyAbsenceAsync( } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefReadonlyAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyAtTopLevel1() + => VerifyKeywordAsync( @"ref readonly $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { readonly $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref readonly $$ } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref $$ -}}"); - } + public Task TestAfterRefInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - readonly $$ -}}"); - } + public Task TestAfterReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + readonly $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref readonly $$ -}}"); - } + public Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref readonly $$ + } + """); #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -1123,5 +899,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ULongKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ULongKeywordRecommenderTests.cs index 16def3daa22da..a868e591c5eb6 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ULongKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ULongKeywordRecommenderTests.cs @@ -13,712 +13,549 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class ULongKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsing() - { - await VerifyAbsenceAsync( + public Task TestNotInUsing() + => VerifyAbsenceAsync( @"using $$"); - } [Fact] - public async Task TestInUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInUsingAlias() + => VerifyKeywordAsync( @"using Goo = $$"); - } [Fact] - public async Task TestInGlobalUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInGlobalUsingAlias() + => VerifyKeywordAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestAfterStackAlloc() - { - await VerifyKeywordAsync( + public Task TestAfterStackAlloc() + => VerifyKeywordAsync( """ class C { int* goo = stackalloc $$ """); - } [Fact] - public async Task TestInFixedStatement() - { - await VerifyKeywordAsync( + public Task TestInFixedStatement() + => VerifyKeywordAsync( @"fixed ($$"); - } [Fact] - public async Task TestInDelegateReturnType() - { - await VerifyKeywordAsync( + public Task TestInDelegateReturnType() + => VerifyKeywordAsync( @"public delegate $$"); - } [Fact] - public async Task TestInCastType() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); - } [Fact] - public async Task TestInCastType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType2() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); - } [Fact] - public async Task TestAfterConstInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterConstInMemberContext() + => VerifyKeywordAsync( """ class C { const $$ """); - } [Fact] - public async Task TestAfterRefInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefInMemberContext() + => VerifyKeywordAsync( """ class C { ref $$ """); - } [Fact] - public async Task TestAfterRefReadonlyInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyInMemberContext() + => VerifyKeywordAsync( """ class C { ref readonly $$ """); - } [Fact] - public async Task TestAfterConstInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"const $$")); - } [Fact] - public async Task TestAfterRefInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$")); - } [Fact] - public async Task TestAfterRefReadonlyInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); - } [Fact] - public async Task TestAfterConstLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); - } [Fact] - public async Task TestAfterRefReadonlyLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); - } [Fact] - public async Task TestAfterRefReadonlyLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); - } [Fact] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } [Fact] - public async Task TestInEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestEnumBaseTypes() - { - await VerifyKeywordAsync( + public Task TestEnumBaseTypes() + => VerifyKeywordAsync( @"enum E : $$"); - } [Fact] - public async Task TestInGenericType1() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType1() + => VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); - } [Fact] - public async Task TestInGenericType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType2() + => VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList,$$")); - } [Fact] - public async Task TestNotInBaseList() - { - await VerifyAbsenceAsync( + public Task TestNotInBaseList() + => VerifyAbsenceAsync( @"class C : $$"); - } [Fact] - public async Task TestInGenericType_InBaseList() - { - await VerifyKeywordAsync( + public Task TestInGenericType_InBaseList() + => VerifyKeywordAsync( @"class C : IList<$$"); - } [Fact] - public async Task TestAfterIs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); - } [Fact] - public async Task TestAfterAs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterAs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync( + public Task TestInsideInterface() + => VerifyKeywordAsync( """ interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact] - public async Task TestAfterNestedPartial() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPartial() + => VerifyKeywordAsync( """ class C { partial $$ """); - } [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] - public async Task TestAfterNestedStaticPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticPublic() + => VerifyKeywordAsync( """ class C { static public $$ """); - } [Fact] - public async Task TestAfterNestedPublicStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublicStatic() + => VerifyKeywordAsync( """ class C { public static $$ """); - } [Fact] - public async Task TestAfterVirtualPublic() - { - await VerifyKeywordAsync( + public Task TestAfterVirtualPublic() + => VerifyKeywordAsync( """ class C { virtual public $$ """); - } [Fact] - public async Task TestAfterNestedPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublic() + => VerifyKeywordAsync( """ class C { public $$ """); - } [Fact] - public async Task TestAfterNestedPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPrivate() + => VerifyKeywordAsync( """ class C { private $$ """); - } [Fact] - public async Task TestAfterNestedProtected() - { - await VerifyKeywordAsync( + public Task TestAfterNestedProtected() + => VerifyKeywordAsync( """ class C { protected $$ """); - } [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] - public async Task TestAfterNestedStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStatic() + => VerifyKeywordAsync( """ class C { static $$ """); - } [Fact] - public async Task TestInLocalVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLocalVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInForVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"for ($$")); - } [Fact] - public async Task TestInForeachVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForeachVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); - } [Fact] - public async Task TestInUsingVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInUsingVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"using ($$")); - } [Fact] - public async Task TestInFromVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFromVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); - } [Fact] - public async Task TestInJoinVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInJoinVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from a in b join $$ """)); - } [Fact] - public async Task TestAfterMethodOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterMethodOpenParen() + => VerifyKeywordAsync( """ class C { void Goo($$ """); - } [Fact] - public async Task TestAfterMethodComma() - { - await VerifyKeywordAsync( + public Task TestAfterMethodComma() + => VerifyKeywordAsync( """ class C { void Goo(int i, $$ """); - } [Fact] - public async Task TestAfterMethodAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterMethodAttribute() + => VerifyKeywordAsync( """ class C { void Goo(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterConstructorOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorOpenParen() + => VerifyKeywordAsync( """ class C { public C($$ """); - } [Fact] - public async Task TestAfterConstructorComma() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorComma() + => VerifyKeywordAsync( """ class C { public C(int i, $$ """); - } [Fact] - public async Task TestAfterConstructorAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorAttribute() + => VerifyKeywordAsync( """ class C { public C(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterDelegateOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateOpenParen() + => VerifyKeywordAsync( @"delegate void D($$"); - } [Fact] - public async Task TestAfterDelegateComma() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateComma() + => VerifyKeywordAsync( @"delegate void D(int i, $$"); - } [Fact] - public async Task TestAfterDelegateAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateAttribute() + => VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); - } [Fact] - public async Task TestAfterThis() - { - await VerifyKeywordAsync( + public Task TestAfterThis() + => VerifyKeywordAsync( """ static class C { public static void Goo(this $$ """); - } [Fact] - public async Task TestAfterRef() - { - await VerifyKeywordAsync( + public Task TestAfterRef() + => VerifyKeywordAsync( """ class C { void Goo(ref $$ """); - } [Fact] - public async Task TestAfterOut() - { - await VerifyKeywordAsync( + public Task TestAfterOut() + => VerifyKeywordAsync( """ class C { void Goo(out $$ """); - } [Fact] - public async Task TestAfterLambdaRef() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaRef() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (ref $$ """); - } [Fact] - public async Task TestAfterLambdaOut() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaOut() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (out $$ """); - } [Fact] - public async Task TestAfterParams() - { - await VerifyKeywordAsync( + public Task TestAfterParams() + => VerifyKeywordAsync( """ class C { void Goo(params $$ """); - } [Fact] - public async Task TestInImplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInImplicitOperator() + => VerifyKeywordAsync( """ class C { public static implicit operator $$ """); - } [Fact] - public async Task TestInExplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInExplicitOperator() + => VerifyKeywordAsync( """ class C { public static explicit operator $$ """); - } [Fact] - public async Task TestAfterIndexerBracket() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracket() + => VerifyKeywordAsync( """ class C { int this[$$ """); - } [Fact] - public async Task TestAfterIndexerBracketComma() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracketComma() + => VerifyKeywordAsync( """ class C { int this[int i, $$ """); - } [Fact] - public async Task TestAfterNewInExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterNewInExpression() + => VerifyKeywordAsync(AddInsideMethod( @"new $$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInTypeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInTypeOf() + => VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInDefault() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDefault() + => VerifyKeywordAsync(AddInsideMethod( @"default($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInSizeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInSizeOf() + => VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -726,12 +563,10 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] - public async Task TestInCrefContext() - { - await VerifyKeywordAsync(""" + public Task TestInCrefContext() + => VerifyKeywordAsync(""" class Program { /// @@ -741,16 +576,13 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] - public async Task TestInCrefContextNotAfterDot() - { - await VerifyAbsenceAsync(""" + public Task TestInCrefContextNotAfterDot() + => VerifyAbsenceAsync(""" /// class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] public async Task TestNotAfterAsync() @@ -761,19 +593,16 @@ public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1468")] - public async Task TestNotInCrefTypeParameter() - { - await VerifyAbsenceAsync(""" + public Task TestNotInCrefTypeParameter() + => VerifyAbsenceAsync(""" using System; /// class C { } """); - } [Fact] - public async Task Preselection() - { - await VerifyKeywordAsync(""" + public Task Preselection() + => VerifyKeywordAsync(""" class Program { static void Main(string[] args) @@ -783,23 +612,19 @@ static void Main(string[] args) static void Helper(ulong x) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinType() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinType() + => VerifyKeywordAsync(""" class Program { ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinMember() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinMember() + => VerifyKeywordAsync(""" class Program { void Method() @@ -808,82 +633,66 @@ void Method() } } """); - } [Fact] - public async Task TestInFunctionPointerType() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerType() + => VerifyKeywordAsync(""" class C { delegate*<$$ """); - } [Fact] - public async Task TestInFunctionPointerTypeAfterComma() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerTypeAfterComma() + => VerifyKeywordAsync(""" class C { delegate* VerifyKeywordAsync(""" class C { delegate* VerifyAbsenceAsync(""" class C { delegate*$$ """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/53585")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithoutAsync))] - public async Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) - { - await VerifyKeywordAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) + => VerifyKeywordAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithAsync))] - public async Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) - { - await VerifyAbsenceAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) + => VerifyAbsenceAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64585")] - public async Task TestAfterRequired() - { - await VerifyKeywordAsync(""" + public Task TestAfterRequired() + => VerifyKeywordAsync(""" class C { required $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefAtTopLevel1() + => VerifyKeywordAsync( @"ref $$"); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [CombinatorialData] @@ -904,216 +713,183 @@ await VerifyAbsenceAsync( } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefReadonlyAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyAtTopLevel1() + => VerifyKeywordAsync( @"ref readonly $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { readonly $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref readonly $$ } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref $$ -}}"); - } + public Task TestAfterRefInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - readonly $$ -}}"); - } + public Task TestAfterReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + readonly $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref readonly $$ -}}"); - } + public Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref readonly $$ + } + """); #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -1123,5 +899,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/UShortKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/UShortKeywordRecommenderTests.cs index 118f955e4861a..c37d15f1cf787 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/UShortKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/UShortKeywordRecommenderTests.cs @@ -13,712 +13,549 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class UShortKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsing() - { - await VerifyAbsenceAsync( + public Task TestNotInUsing() + => VerifyAbsenceAsync( @"using $$"); - } [Fact] - public async Task TestInUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInUsingAlias() + => VerifyKeywordAsync( @"using Goo = $$"); - } [Fact] - public async Task TestInGlobalUsingAlias() - { - await VerifyKeywordAsync( + public Task TestInGlobalUsingAlias() + => VerifyKeywordAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestAfterStackAlloc() - { - await VerifyKeywordAsync( + public Task TestAfterStackAlloc() + => VerifyKeywordAsync( """ class C { int* goo = stackalloc $$ """); - } [Fact] - public async Task TestInFixedStatement() - { - await VerifyKeywordAsync( + public Task TestInFixedStatement() + => VerifyKeywordAsync( @"fixed ($$"); - } [Fact] - public async Task TestInDelegateReturnType() - { - await VerifyKeywordAsync( + public Task TestInDelegateReturnType() + => VerifyKeywordAsync( @"public delegate $$"); - } [Fact] - public async Task TestInCastType() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); - } [Fact] - public async Task TestInCastType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType2() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); - } [Fact] - public async Task TestAfterConstInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterConstInMemberContext() + => VerifyKeywordAsync( """ class C { const $$ """); - } [Fact] - public async Task TestAfterRefInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefInMemberContext() + => VerifyKeywordAsync( """ class C { ref $$ """); - } [Fact] - public async Task TestAfterRefReadonlyInMemberContext() - { - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyInMemberContext() + => VerifyKeywordAsync( """ class C { ref readonly $$ """); - } [Fact] - public async Task TestAfterConstInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"const $$")); - } [Fact] - public async Task TestAfterRefInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$")); - } [Fact] - public async Task TestAfterRefReadonlyInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); - } [Fact] - public async Task TestAfterConstLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); - } [Fact] - public async Task TestAfterRefReadonlyLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); - } [Fact] - public async Task TestAfterRefLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); - } [Fact] - public async Task TestAfterRefReadonlyLocalFunction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalFunction() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); - } [Fact] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } [Fact] - public async Task TestInEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestEnumBaseTypes() - { - await VerifyKeywordAsync( + public Task TestEnumBaseTypes() + => VerifyKeywordAsync( @"enum E : $$"); - } [Fact] - public async Task TestInGenericType1() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType1() + => VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); - } [Fact] - public async Task TestInGenericType2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInGenericType2() + => VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList VerifyKeywordAsync(AddInsideMethod( @"IList,$$")); - } [Fact] - public async Task TestNotInBaseList() - { - await VerifyAbsenceAsync( + public Task TestNotInBaseList() + => VerifyAbsenceAsync( @"class C : $$"); - } [Fact] - public async Task TestInGenericType_InBaseList() - { - await VerifyKeywordAsync( + public Task TestInGenericType_InBaseList() + => VerifyKeywordAsync( @"class C : IList<$$"); - } [Fact] - public async Task TestAfterIs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); - } [Fact] - public async Task TestAfterAs() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterAs() + => VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync( + public Task TestInsideInterface() + => VerifyKeywordAsync( """ interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact] - public async Task TestAfterNestedPartial() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPartial() + => VerifyKeywordAsync( """ class C { partial $$ """); - } [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] - public async Task TestAfterNestedStaticPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticPublic() + => VerifyKeywordAsync( """ class C { static public $$ """); - } [Fact] - public async Task TestAfterNestedPublicStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublicStatic() + => VerifyKeywordAsync( """ class C { public static $$ """); - } [Fact] - public async Task TestAfterVirtualPublic() - { - await VerifyKeywordAsync( + public Task TestAfterVirtualPublic() + => VerifyKeywordAsync( """ class C { virtual public $$ """); - } [Fact] - public async Task TestAfterNestedPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublic() + => VerifyKeywordAsync( """ class C { public $$ """); - } [Fact] - public async Task TestAfterNestedPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPrivate() + => VerifyKeywordAsync( """ class C { private $$ """); - } [Fact] - public async Task TestAfterNestedProtected() - { - await VerifyKeywordAsync( + public Task TestAfterNestedProtected() + => VerifyKeywordAsync( """ class C { protected $$ """); - } [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] - public async Task TestAfterNestedStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStatic() + => VerifyKeywordAsync( """ class C { static $$ """); - } [Fact] - public async Task TestInLocalVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInLocalVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInForVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"for ($$")); - } [Fact] - public async Task TestInForeachVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForeachVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); - } [Fact] - public async Task TestInUsingVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInUsingVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"using ($$")); - } [Fact] - public async Task TestInFromVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFromVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); - } [Fact] - public async Task TestInJoinVariableDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInJoinVariableDeclaration() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from a in b join $$ """)); - } [Fact] - public async Task TestAfterMethodOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterMethodOpenParen() + => VerifyKeywordAsync( """ class C { void Goo($$ """); - } [Fact] - public async Task TestAfterMethodComma() - { - await VerifyKeywordAsync( + public Task TestAfterMethodComma() + => VerifyKeywordAsync( """ class C { void Goo(int i, $$ """); - } [Fact] - public async Task TestAfterMethodAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterMethodAttribute() + => VerifyKeywordAsync( """ class C { void Goo(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterConstructorOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorOpenParen() + => VerifyKeywordAsync( """ class C { public C($$ """); - } [Fact] - public async Task TestAfterConstructorComma() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorComma() + => VerifyKeywordAsync( """ class C { public C(int i, $$ """); - } [Fact] - public async Task TestAfterConstructorAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterConstructorAttribute() + => VerifyKeywordAsync( """ class C { public C(int i, [Goo]$$ """); - } [Fact] - public async Task TestAfterDelegateOpenParen() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateOpenParen() + => VerifyKeywordAsync( @"delegate void D($$"); - } [Fact] - public async Task TestAfterDelegateComma() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateComma() + => VerifyKeywordAsync( @"delegate void D(int i, $$"); - } [Fact] - public async Task TestAfterDelegateAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateAttribute() + => VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); - } [Fact] - public async Task TestAfterThis() - { - await VerifyKeywordAsync( + public Task TestAfterThis() + => VerifyKeywordAsync( """ static class C { public static void Goo(this $$ """); - } [Fact] - public async Task TestAfterRef() - { - await VerifyKeywordAsync( + public Task TestAfterRef() + => VerifyKeywordAsync( """ class C { void Goo(ref $$ """); - } [Fact] - public async Task TestAfterOut() - { - await VerifyKeywordAsync( + public Task TestAfterOut() + => VerifyKeywordAsync( """ class C { void Goo(out $$ """); - } [Fact] - public async Task TestAfterLambdaRef() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaRef() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (ref $$ """); - } [Fact] - public async Task TestAfterLambdaOut() - { - await VerifyKeywordAsync( + public Task TestAfterLambdaOut() + => VerifyKeywordAsync( """ class C { void Goo() { System.Func f = (out $$ """); - } [Fact] - public async Task TestAfterParams() - { - await VerifyKeywordAsync( + public Task TestAfterParams() + => VerifyKeywordAsync( """ class C { void Goo(params $$ """); - } [Fact] - public async Task TestInImplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInImplicitOperator() + => VerifyKeywordAsync( """ class C { public static implicit operator $$ """); - } [Fact] - public async Task TestInExplicitOperator() - { - await VerifyKeywordAsync( + public Task TestInExplicitOperator() + => VerifyKeywordAsync( """ class C { public static explicit operator $$ """); - } [Fact] - public async Task TestAfterIndexerBracket() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracket() + => VerifyKeywordAsync( """ class C { int this[$$ """); - } [Fact] - public async Task TestAfterIndexerBracketComma() - { - await VerifyKeywordAsync( + public Task TestAfterIndexerBracketComma() + => VerifyKeywordAsync( """ class C { int this[int i, $$ """); - } [Fact] - public async Task TestAfterNewInExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterNewInExpression() + => VerifyKeywordAsync(AddInsideMethod( @"new $$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInTypeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInTypeOf() + => VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInDefault() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInDefault() + => VerifyKeywordAsync(AddInsideMethod( @"default($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestInSizeOf() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInSizeOf() + => VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -726,12 +563,10 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] - public async Task TestInCrefContext() - { - await VerifyKeywordAsync(""" + public Task TestInCrefContext() + => VerifyKeywordAsync(""" class Program { /// @@ -741,16 +576,13 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] - public async Task TestInCrefContextNotAfterDot() - { - await VerifyAbsenceAsync(""" + public Task TestInCrefContextNotAfterDot() + => VerifyAbsenceAsync(""" /// class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] public async Task TestNotAfterAsync() @@ -761,19 +593,16 @@ public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1468")] - public async Task TestNotInCrefTypeParameter() - { - await VerifyAbsenceAsync(""" + public Task TestNotInCrefTypeParameter() + => VerifyAbsenceAsync(""" using System; /// class C { } """); - } [Fact] - public async Task Preselection() - { - await VerifyKeywordAsync(""" + public Task Preselection() + => VerifyKeywordAsync(""" class Program { static void Main(string[] args) @@ -783,23 +612,19 @@ static void Main(string[] args) static void Helper(ushort x) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinType() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinType() + => VerifyKeywordAsync(""" class Program { ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14127")] - public async Task TestInTupleWithinMember() - { - await VerifyKeywordAsync(""" + public Task TestInTupleWithinMember() + => VerifyKeywordAsync(""" class Program { void Method() @@ -808,82 +633,66 @@ void Method() } } """); - } [Fact] - public async Task TestInFunctionPointerType() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerType() + => VerifyKeywordAsync(""" class C { delegate*<$$ """); - } [Fact] - public async Task TestInFunctionPointerTypeAfterComma() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointerTypeAfterComma() + => VerifyKeywordAsync(""" class C { delegate* VerifyKeywordAsync(""" class C { delegate* VerifyAbsenceAsync(""" class C { delegate*$$ """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/53585")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithoutAsync))] - public async Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) - { - await VerifyKeywordAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestAfterKeywordIndicatingLocalFunctionWithoutAsync(string keyword) + => VerifyKeywordAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/60341")] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunctionWithAsync))] - public async Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) - { - await VerifyAbsenceAsync(AddInsideMethod($@" -{keyword} $$")); - } + public Task TestNotAfterKeywordIndicatingLocalFunctionWithAsync(string keyword) + => VerifyAbsenceAsync(AddInsideMethod($""" + {keyword} $$ + """)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64585")] - public async Task TestAfterRequired() - { - await VerifyKeywordAsync(""" + public Task TestAfterRequired() + => VerifyKeywordAsync(""" class C { required $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefAtTopLevel1() + => VerifyKeywordAsync( @"ref $$"); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [CombinatorialData] @@ -904,216 +713,183 @@ await VerifyAbsenceAsync( } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestAfterRefReadonlyAtTopLevel1() - { - // Could be defining a ref-local in top-level-code - await VerifyKeywordAsync( + public Task TestAfterRefReadonlyAtTopLevel1() + => VerifyKeywordAsync( @"ref readonly $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { readonly $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] - public async Task TestNotAfterRefReadonlyInNamespace() - { - // This is only legal for a struct declaration - await VerifyAbsenceAsync( + public Task TestNotAfterRefReadonlyInNamespace() + => VerifyAbsenceAsync( """ namespace N { ref readonly $$ } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref $$ -}}"); - } + public Task TestAfterRefInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - readonly $$ -}}"); - } + public Task TestAfterReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + readonly $$ + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/67061")] [InlineData("class")] [InlineData("interface")] [InlineData("struct")] [InlineData("record")] - public async Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) - { - await VerifyKeywordAsync( -$@"{type} N -{{ - ref readonly $$ -}}"); - } + public Task TestAfterRefReadonlyInClassInterfaceStructRecord(string type) + => VerifyKeywordAsync( + $$""" + {{type}} N + { + ref readonly $$ + } + """); #region Collection expressions [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_BeforeFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [$$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_BeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_BeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToVar() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCollectionExpressions_AfterFirstElementToVar() + => VerifyKeywordAsync(AddInsideMethod( """ var x = [new object(), $$ """)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_AfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_AfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadBeforeFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_SpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAtFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [.. ($$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70677")] - public async Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() - { - await VerifyKeywordAsync( + public Task TestInCollectionExpressions_ParenSpreadAfterFirstElementToReturn() + => VerifyKeywordAsync( """ class C { IEnumerable M() => [string.Empty, .. ($$ } """); - } #endregion [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -1123,5 +899,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/UncheckedKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/UncheckedKeywordRecommenderTests.cs index 951261f0003c3..ca68cb3fdc8ac 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/UncheckedKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/UncheckedKeywordRecommenderTests.cs @@ -13,95 +13,72 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class UncheckedKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInExpression() + => VerifyKeywordAsync(AddInsideMethod( @"var q = $$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInTypeOf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInTypeOf() + => VerifyAbsenceAsync(AddInsideMethod( @"typeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInDefault() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInDefault() + => VerifyAbsenceAsync(AddInsideMethod( @"default($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] - public async Task TestNotInSizeOf() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInSizeOf() + => VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] - public async Task TestNotInObjectInitializerMemberContext() - { - await VerifyAbsenceAsync(""" + public Task TestNotInObjectInitializerMemberContext() + => VerifyAbsenceAsync(""" class C { public int x, y; @@ -109,19 +86,15 @@ void M() { var c = new C { x = 2, y = 3, $$ """); - } [Fact] - public async Task TestAfterRefExpression() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefExpression() + => VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); - } [Fact] - public async Task TestWithinExtension() - { - await VerifyAbsenceAsync( + public Task TestWithinExtension() + => VerifyAbsenceAsync( """ static class C { @@ -133,5 +106,4 @@ static class C """, CSharpNextParseOptions, CSharpNextScriptParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/UndefKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/UndefKeywordRecommenderTests.cs index d976c7c1d01a4..005e8b345f861 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/UndefKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/UndefKeywordRecommenderTests.cs @@ -12,125 +12,97 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class UndefKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterHash() - { - await VerifyKeywordAsync( + public Task TestAfterHash() + => VerifyKeywordAsync( @"#$$"); - } [Fact] - public async Task TestAfterHashAndSpace() - { - await VerifyKeywordAsync( + public Task TestAfterHashAndSpace() + => VerifyKeywordAsync( @"# $$"); - } [Fact] - public async Task TestNestedPreprocessor() - { - await VerifyKeywordAsync( + public Task TestNestedPreprocessor() + => VerifyKeywordAsync( """ #if true #$$ #endif """); - } [Fact] - public async Task TestBeforeUsing() - { - await VerifyKeywordAsync( + public Task TestBeforeUsing() + => VerifyKeywordAsync( """ #$$ using System; """); - } [Fact] - public async Task TestBeforeGlobalUsing() - { - await VerifyKeywordAsync( + public Task TestBeforeGlobalUsing() + => VerifyKeywordAsync( """ #$$ global using System; """); - } [Fact] - public async Task TestNotAfterUsing() - { - await VerifyAbsenceAsync( + public Task TestNotAfterUsing() + => VerifyAbsenceAsync( """ using System; #$$ """); - } [Fact] - public async Task TestNotAfterGlobalUsing() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGlobalUsing() + => VerifyAbsenceAsync( """ global using System; #$$ """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/UnmanagedKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/UnmanagedKeywordRecommenderTests.cs index 4530d507ee47d..d548a7ece187b 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/UnmanagedKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/UnmanagedKeywordRecommenderTests.cs @@ -12,255 +12,197 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class UnmanagedKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotAfterName_Type() - { - await VerifyAbsenceAsync( + public Task TestNotAfterName_Type() + => VerifyAbsenceAsync( @"class Test $$"); - } [Fact] - public async Task TestNotAfterWhereClause_Type() - { - await VerifyAbsenceAsync( + public Task TestNotAfterWhereClause_Type() + => VerifyAbsenceAsync( @"class Test where $$"); - } [Fact] - public async Task TestNotAfterWhereClauseType_Type() - { - await VerifyAbsenceAsync( + public Task TestNotAfterWhereClauseType_Type() + => VerifyAbsenceAsync( @"class Test where T $$"); - } [Fact] - public async Task TestAfterWhereClauseColon_Type() - { - await VerifyKeywordAsync( + public Task TestAfterWhereClauseColon_Type() + => VerifyKeywordAsync( @"class Test where T : $$"); - } [Fact] - public async Task TestNotAfterTypeConstraint_Type() - { - await VerifyAbsenceAsync( + public Task TestNotAfterTypeConstraint_Type() + => VerifyAbsenceAsync( @"class Test where T : I $$"); - } [Fact] - public async Task TestAfterTypeConstraintComma_Type() - { - await VerifyKeywordAsync( + public Task TestAfterTypeConstraintComma_Type() + => VerifyKeywordAsync( @"class Test where T : I, $$"); - } [Fact] - public async Task TestNotAfterName_Method() - { - await VerifyAbsenceAsync( + public Task TestNotAfterName_Method() + => VerifyAbsenceAsync( """ class Test { void M $$ """); - } [Fact] - public async Task TestNotAfterWhereClause_Method() - { - await VerifyAbsenceAsync( + public Task TestNotAfterWhereClause_Method() + => VerifyAbsenceAsync( """ class Test { void M where $$ """); - } [Fact] - public async Task TestNotAfterWhereClauseType_Method() - { - await VerifyAbsenceAsync( + public Task TestNotAfterWhereClauseType_Method() + => VerifyAbsenceAsync( """ class Test { void M where T $$ """); - } [Fact] - public async Task TestAfterWhereClauseColon_Method() - { - await VerifyKeywordAsync( + public Task TestAfterWhereClauseColon_Method() + => VerifyKeywordAsync( """ class Test { void M where T : $$ """); - } [Fact] - public async Task TestNotAfterTypeConstraint_Method() - { - await VerifyAbsenceAsync( + public Task TestNotAfterTypeConstraint_Method() + => VerifyAbsenceAsync( """ class Test { void M where T : I $$ """); - } [Fact] - public async Task TestAfterTypeConstraintComma_Method() - { - await VerifyKeywordAsync( + public Task TestAfterTypeConstraintComma_Method() + => VerifyKeywordAsync( """ class Test { void M where T : I, $$ """); - } [Fact] - public async Task TestNotAfterName_Delegate() - { - await VerifyAbsenceAsync( + public Task TestNotAfterName_Delegate() + => VerifyAbsenceAsync( @"delegate void D $$"); - } [Fact] - public async Task TestNotAfterWhereClause_Delegate() - { - await VerifyAbsenceAsync( + public Task TestNotAfterWhereClause_Delegate() + => VerifyAbsenceAsync( @"delegate void D() where $$"); - } [Fact] - public async Task TestNotAfterWhereClauseType_Delegate() - { - await VerifyAbsenceAsync( + public Task TestNotAfterWhereClauseType_Delegate() + => VerifyAbsenceAsync( @"delegate void D() where T $$"); - } [Fact] - public async Task TestAfterWhereClauseColon_Delegate() - { - await VerifyKeywordAsync( + public Task TestAfterWhereClauseColon_Delegate() + => VerifyKeywordAsync( @"delegate void D() where T : $$"); - } [Fact] - public async Task TestNotAfterTypeConstraint_Delegate() - { - await VerifyAbsenceAsync( + public Task TestNotAfterTypeConstraint_Delegate() + => VerifyAbsenceAsync( @"delegate void D() where T : I $$"); - } [Fact] - public async Task TestAfterTypeConstraintComma_Delegate() - { - await VerifyKeywordAsync( + public Task TestAfterTypeConstraintComma_Delegate() + => VerifyKeywordAsync( @"delegate void D() where T : I, $$"); - } [Fact] - public async Task TestNotAfterName_LocalFunction() - { - await VerifyAbsenceAsync( + public Task TestNotAfterName_LocalFunction() + => VerifyAbsenceAsync( """ class Test { void N() { void M $$ """); - } [Fact] - public async Task TestNotAfterWhereClause_LocalFunction() - { - await VerifyAbsenceAsync( + public Task TestNotAfterWhereClause_LocalFunction() + => VerifyAbsenceAsync( """ class Test { void N() { void M where $$ """); - } [Fact] - public async Task TestNotAfterWhereClauseType_LocalFunction() - { - await VerifyAbsenceAsync( + public Task TestNotAfterWhereClauseType_LocalFunction() + => VerifyAbsenceAsync( """ class Test { void N() { void M where T $$ """); - } [Fact] - public async Task TestAfterWhereClauseColon_LocalFunction() - { - await VerifyKeywordAsync( + public Task TestAfterWhereClauseColon_LocalFunction() + => VerifyKeywordAsync( """ class Test { void N() { void M where T : $$ """); - } [Fact] - public async Task TestNotAfterTypeConstraint_LocalFunction() - { - await VerifyAbsenceAsync( + public Task TestNotAfterTypeConstraint_LocalFunction() + => VerifyAbsenceAsync( """ class Test { void N() { void M where T : I $$ """); - } [Fact] - public async Task TestAfterTypeConstraintComma_LocalFunction() - { - await VerifyKeywordAsync( + public Task TestAfterTypeConstraintComma_LocalFunction() + => VerifyKeywordAsync( """ class Test { void N() { void M where T : I, $$ """); - } [Fact] - public async Task TestInFunctionPointerDeclaration() - { - await VerifyKeywordAsync( + public Task TestInFunctionPointerDeclaration() + => VerifyKeywordAsync( """ class Test { unsafe void N() { delegate* $$ """); - } [Fact] - public async Task TestInFunctionPointerDeclarationTouchingAsterisk() - { - await VerifyKeywordAsync( + public Task TestInFunctionPointerDeclarationTouchingAsterisk() + => VerifyKeywordAsync( """ class Test { unsafe void N() { delegate*$$ """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/UnsafeKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/UnsafeKeywordRecommenderTests.cs index a26c5593299dc..f1e8ad6642c3b 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/UnsafeKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/UnsafeKeywordRecommenderTests.cs @@ -13,315 +13,251 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class UnsafeKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestInEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestInCompilationUnit() - { - await VerifyKeywordAsync( + public Task TestInCompilationUnit() + => VerifyKeywordAsync( @"$$"); - } [Fact] - public async Task TestAfterExtern() - { - await VerifyKeywordAsync( + public Task TestAfterExtern() + => VerifyKeywordAsync( """ extern alias Goo; $$ """); - } [Fact] - public async Task TestAfterUsing() - { - await VerifyKeywordAsync( + public Task TestAfterUsing() + => VerifyKeywordAsync( """ using Goo; $$ """); - } [Fact] - public async Task TestAfterGlobalUsing() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalUsing() + => VerifyKeywordAsync( """ global using Goo; $$ """); - } [Fact] - public async Task TestAfterNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterNamespace() + => VerifyKeywordAsync( """ namespace N {} $$ """); - } [Fact] - public async Task TestAfterFileScopedNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterFileScopedNamespace() + => VerifyKeywordAsync( """ namespace N; $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestFileKeywordInsideNamespace() - { - await VerifyKeywordAsync( + public Task TestFileKeywordInsideNamespace() + => VerifyKeywordAsync( """ namespace N { file $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestFileKeywordInsideNamespaceBeforeClass() - { - await VerifyKeywordAsync( + public Task TestFileKeywordInsideNamespaceBeforeClass() + => VerifyKeywordAsync( """ namespace N { file $$ class C {} } """); - } [Fact] - public async Task TestAfterTypeDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterTypeDeclaration() + => VerifyKeywordAsync( """ class C {} $$ """); - } [Fact] - public async Task TestAfterDelegateDeclaration() - { - await VerifyKeywordAsync( + public Task TestAfterDelegateDeclaration() + => VerifyKeywordAsync( """ delegate void Goo(); $$ """); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ global using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeGlobalUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeGlobalUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ global using Goo; """); - } [Fact] - public async Task TestAfterAssemblyAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterAssemblyAttribute() + => VerifyKeywordAsync( """ [assembly: goo] $$ """); - } [Fact] - public async Task TestAfterRootAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterRootAttribute() + => VerifyKeywordAsync( """ [goo] $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } // This will be fixed once we have accessibility for members [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync( + public Task TestInsideInterface() + => VerifyKeywordAsync( """ interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact] - public async Task TestAfterAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterAbstract() + => VerifyKeywordAsync( @"abstract $$"); - } [Fact] - public async Task TestAfterInternal() - { - await VerifyKeywordAsync( + public Task TestAfterInternal() + => VerifyKeywordAsync( @"internal $$"); - } [Fact] public async Task TestNotAfterUnsafe() @@ -336,39 +272,29 @@ public async Task TestNotAfterUnsafeStatic() => await VerifyAbsenceAsync(@"unsafe static $$"); [Fact] - public async Task TestAfterPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterPrivate() + => VerifyKeywordAsync( @"private $$"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66319")] - public async Task TestAfterFile() - { - await VerifyKeywordAsync(SourceCodeKind.Regular, + public Task TestAfterFile() + => VerifyKeywordAsync(SourceCodeKind.Regular, @"file $$"); - } [Fact] - public async Task TestAfterProtected() - { - await VerifyKeywordAsync( + public Task TestAfterProtected() + => VerifyKeywordAsync( @"protected $$"); - } [Fact] - public async Task TestAfterSealed() - { - await VerifyKeywordAsync( + public Task TestAfterSealed() + => VerifyKeywordAsync( @"sealed $$"); - } [Fact] - public async Task TestAfterStatic() - { - await VerifyKeywordAsync( + public Task TestAfterStatic() + => VerifyKeywordAsync( @"static $$"); - } [Fact] public async Task TestNotAfterClass() @@ -379,129 +305,100 @@ public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] - public async Task TestAfterNestedVirtual() - { - await VerifyKeywordAsync( + public Task TestAfterNestedVirtual() + => VerifyKeywordAsync( """ class C { virtual $$ """); - } [Fact] - public async Task TestAfterNestedOverride() - { - await VerifyKeywordAsync( + public Task TestAfterNestedOverride() + => VerifyKeywordAsync( """ class C { override $$ """); - } [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] - public async Task TestBeforeStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBeforeStatement() + => VerifyKeywordAsync(AddInsideMethod( """ $$ return true; """)); - } [Fact] - public async Task TestAfterStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterStatement() + => VerifyKeywordAsync(AddInsideMethod( """ return true; $$ """)); - } [Fact] - public async Task TestAfterBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBlock() + => VerifyKeywordAsync(AddInsideMethod( """ if (true) { } $$ """)); - } [Fact] - public async Task TestInsideSwitchBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideSwitchBlock() + => VerifyKeywordAsync(AddInsideMethod( """ switch (E) { case 0: $$ """)); - } [Fact] - public async Task TestNotAfterUnsafe_InMethod() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterUnsafe_InMethod() + => VerifyAbsenceAsync(AddInsideMethod( @"unsafe $$")); - } [Fact] - public async Task TestAfterInterfaceModifiers() - { - await VerifyKeywordAsync( + public Task TestAfterInterfaceModifiers() + => VerifyKeywordAsync( @"public $$ interface IBinaryDocumentMemoryBlock {"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67984")] - public async Task TestAfterUsingKeywordInUsingDirective() - { - await VerifyKeywordAsync("using $$"); - } + public Task TestAfterUsingKeywordInUsingDirective() + => VerifyKeywordAsync("using $$"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67984")] - public async Task TestAfterStaticKeywordInUsingDirective() - { - await VerifyKeywordAsync("using static $$"); - } + public Task TestAfterStaticKeywordInUsingDirective() + => VerifyKeywordAsync("using static $$"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67984")] - public async Task TestAfterUsingKeywordInGlobalUsingDirective() - { - await VerifyKeywordAsync("global using $$"); - } + public Task TestAfterUsingKeywordInGlobalUsingDirective() + => VerifyKeywordAsync("global using $$"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67984")] - public async Task TestAfterStaticKeywordInGlobalUsingDirective() - { - await VerifyKeywordAsync("global using static $$"); - } + public Task TestAfterStaticKeywordInGlobalUsingDirective() + => VerifyKeywordAsync("global using static $$"); [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -511,5 +408,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/UsingKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/UsingKeywordRecommenderTests.cs index 7a4595101aea4..f58f9f7bce01d 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/UsingKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/UsingKeywordRecommenderTests.cs @@ -12,60 +12,47 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class UsingKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestAfterClass() - { - await VerifyKeywordAsync( + public Task TestAfterClass() + => VerifyKeywordAsync( """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Theory, CombinatorialData] - public async Task TestInEmptyStatement(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInEmptyStatement(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestAfterAwait() - { - await VerifyKeywordAsync( + public Task TestAfterAwait() + => VerifyKeywordAsync( """ class C { @@ -75,12 +62,10 @@ async void M() } } """); - } [Fact] - public async Task TestAfterAwaitInAssignment() - { - await VerifyAbsenceAsync( + public Task TestAfterAwaitInAssignment() + => VerifyAbsenceAsync( """ class C { @@ -90,508 +75,408 @@ async void M() } } """); - } [Fact] - public async Task TestAtRoot() - { - await VerifyKeywordAsync( + public Task TestAtRoot() + => VerifyKeywordAsync( @"$$"); - } [Fact] public async Task TestNotAfterUsingKeyword() => await VerifyAbsenceAsync(@"using $$"); [Fact] - public async Task TestAfterPreviousUsing() - { - await VerifyKeywordAsync( + public Task TestAfterPreviousUsing() + => VerifyKeywordAsync( """ using Goo; $$ """); - } [Fact] - public async Task TestAfterPreviousGlobalUsing() - { - await VerifyKeywordAsync( + public Task TestAfterPreviousGlobalUsing() + => VerifyKeywordAsync( """ global using Goo; $$ """); - } [Fact] - public async Task TestAfterExtern() - { - await VerifyKeywordAsync( + public Task TestAfterExtern() + => VerifyKeywordAsync( """ extern alias goo; $$ """); - } [Fact] - public async Task TestAfterGlobalAfterExtern() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalAfterExtern() + => VerifyKeywordAsync( """ extern alias goo; global $$ """); - } [Fact] - public async Task TestAfterGlobalAfterExternBeforeUsing_01() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalAfterExternBeforeUsing_01() + => VerifyKeywordAsync( """ extern alias goo; global $$ using Goo; """); - } [Fact] - public async Task TestAfterGlobalAfterExternBeforeUsing_02() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalAfterExternBeforeUsing_02() + => VerifyKeywordAsync( """ extern alias goo; global $$ global using Goo; """); - } [Fact] - public async Task TestBeforeUsing() - { - await VerifyKeywordAsync( + public Task TestBeforeUsing() + => VerifyKeywordAsync( """ $$ using Goo; """); - } [Fact] - public async Task TestBeforeUsingAfterGlobal() - { - await VerifyKeywordAsync( + public Task TestBeforeUsingAfterGlobal() + => VerifyKeywordAsync( """ global $$ using Goo; """); - } [Fact] - public async Task TestAfterUsingAlias() - { - await VerifyKeywordAsync( + public Task TestAfterUsingAlias() + => VerifyKeywordAsync( """ using Goo = Bar; $$ """); - } [Fact] - public async Task TestAfterGlobalUsingAlias() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalUsingAlias() + => VerifyKeywordAsync( """ global using Goo = Bar; $$ """); - } [Fact] - public async Task TestNotAfterNestedTypeDeclaration() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedTypeDeclaration() + => VerifyAbsenceAsync(""" class A { class C {} $$ """); - } [Fact] - public async Task TestInsideNamespace() - { - await VerifyKeywordAsync( + public Task TestInsideNamespace() + => VerifyKeywordAsync( """ namespace N { $$ """); - } [Fact] - public async Task TestAfterFileScopedNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterFileScopedNamespace() + => VerifyKeywordAsync( """ namespace N; $$ """); - } [Fact] - public async Task TestNotAfterUsingKeyword_InsideNamespace() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterUsingKeyword_InsideNamespace() + => VerifyAbsenceAsync(""" namespace N { using $$ """); - } [Fact] - public async Task TestAfterPreviousUsing_InsideNamespace() - { - await VerifyKeywordAsync( + public Task TestAfterPreviousUsing_InsideNamespace() + => VerifyKeywordAsync( """ namespace N { using Goo; $$ """); - } [Fact] - public async Task TestBeforeUsing_InsideNamespace() - { - await VerifyKeywordAsync( + public Task TestBeforeUsing_InsideNamespace() + => VerifyKeywordAsync( """ namespace N { $$ using Goo; """); - } [Fact] - public async Task TestNotAfterMember_InsideNamespace() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterMember_InsideNamespace() + => VerifyAbsenceAsync(""" namespace N { class C {} $$ """); - } [Fact] - public async Task TestNotAfterNestedMember_InsideNamespace() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedMember_InsideNamespace() + => VerifyAbsenceAsync(""" namespace N { class A { class C {} $$ """); - } [Fact] - public async Task TestNotBeforeExtern() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeExtern() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ extern alias Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeExtern_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeExtern_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ extern alias Goo; """); - } [Fact] - public async Task TestNotBeforeExternAfterGlobal() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeExternAfterGlobal() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ global $$ extern alias Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeExternAfterGlobal_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeExternAfterGlobal_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ global $$ extern alias Goo; """); - } [Theory, CombinatorialData] - public async Task TestBeforeStatement(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBeforeStatement(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ $$ return true; """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterStatement(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterStatement(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ return true; $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterBlock(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBlock(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ if (true) { } $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterIf(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterIf(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ if (true) $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterDo(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterDo(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ do $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterWhile(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterWhile(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ while (true) $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterFor(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterFor(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ for (int i = 0; i < 10; i++) $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestAfterForeach(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterForeach(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ foreach (var v in bar) $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestNotAfterUsing() - { - await VerifyAbsenceAsync( + public Task TestNotAfterUsing() + => VerifyAbsenceAsync( @"using $$"); - } [Fact] - public async Task TestNotAfterGlobalUsing() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGlobalUsing() + => VerifyAbsenceAsync( @"global using $$"); - } [Fact] - public async Task TestNotInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotInClass() + => VerifyAbsenceAsync(""" class C { $$ } """); - } [Fact] - public async Task TestBetweenUsings_01() - { - await VerifyKeywordAsync( + public Task TestBetweenUsings_01() + => VerifyKeywordAsync( """ using Goo; $$ using Bar; """); - } [Fact] - public async Task TestBetweenUsings_02() - { - await VerifyKeywordAsync( + public Task TestBetweenUsings_02() + => VerifyKeywordAsync( """ global using Goo; $$ using Bar; """); - } [Fact] - public async Task TestAfterGlobalBetweenUsings_01() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalBetweenUsings_01() + => VerifyKeywordAsync( """ global using Goo; global $$ using Bar; """); - } [Fact] - public async Task TestAfterGlobalBetweenUsings_02() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalBetweenUsings_02() + => VerifyKeywordAsync( """ global using Goo; global $$ global using Bar; """); - } [Fact] - public async Task TestAfterGlobal() - { - await VerifyKeywordAsync( + public Task TestAfterGlobal() + => VerifyKeywordAsync( @"global $$"); - } [Fact] - public async Task TestBeforeNamespace() - { - await VerifyKeywordAsync( + public Task TestBeforeNamespace() + => VerifyKeywordAsync( """ $$ namespace NS {} """); - } [Fact] - public async Task TestBeforeFileScopedNamespace() - { - await VerifyKeywordAsync( + public Task TestBeforeFileScopedNamespace() + => VerifyKeywordAsync( """ $$ namespace NS; """); - } [Fact] - public async Task TestBeforeClass() - { - await VerifyKeywordAsync( + public Task TestBeforeClass() + => VerifyKeywordAsync( """ $$ class C1 {} """); - } [Fact] - public async Task TestBeforeAttribute_01() - { - await VerifyKeywordAsync( + public Task TestBeforeAttribute_01() + => VerifyKeywordAsync( """ $$ [Call()] """); - } [Fact] - public async Task TestBeforeAttribute_02() - { - await VerifyKeywordAsync( + public Task TestBeforeAttribute_02() + => VerifyKeywordAsync( """ $$ [assembly: Call()] """); - } [Fact] - public async Task TestBeforeNamespaceAfterGlobal() - { - await VerifyKeywordAsync( + public Task TestBeforeNamespaceAfterGlobal() + => VerifyKeywordAsync( """ global $$ namespace NS {} """); - } [Fact] - public async Task TestBeforeClassAfterGlobal() - { - await VerifyKeywordAsync( + public Task TestBeforeClassAfterGlobal() + => VerifyKeywordAsync( """ global $$ class C1 {} """); - } [Fact] - public async Task TestBeforeStatementAfterGlobal() - { - await VerifyKeywordAsync( + public Task TestBeforeStatementAfterGlobal() + => VerifyKeywordAsync( """ global $$ Call(); """); - } [Fact] - public async Task TestBeforeAttributeAfterGlobal_01() - { - await VerifyKeywordAsync( + public Task TestBeforeAttributeAfterGlobal_01() + => VerifyKeywordAsync( """ global $$ [Call()] """); - } [Fact] - public async Task TestBeforeAttributeAfterGlobal_02() - { - await VerifyKeywordAsync( + public Task TestBeforeAttributeAfterGlobal_02() + => VerifyKeywordAsync( """ global $$ [assembly: Call()] """); - } [Fact] - public async Task TestWithinExtension() - { - await VerifyAbsenceAsync( + public Task TestWithinExtension() + => VerifyAbsenceAsync( """ static class C { @@ -603,5 +488,4 @@ static class C """, CSharpNextParseOptions, CSharpNextScriptParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/VarKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/VarKeywordRecommenderTests.cs index 830936f9ac78a..3d34562407077 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/VarKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/VarKeywordRecommenderTests.cs @@ -24,410 +24,306 @@ public VarKeywordRecommenderTests() } [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotAfterStackAlloc() - { - await VerifyAbsenceAsync( + public Task TestNotAfterStackAlloc() + => VerifyAbsenceAsync( """ class C { int* goo = stackalloc $$ """); - } [Fact] - public async Task TestNotInFixedStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInFixedStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"fixed ($$")); - } [Fact] - public async Task TestNotInDelegateReturnType() - { - await VerifyAbsenceAsync( + public Task TestNotInDelegateReturnType() + => VerifyAbsenceAsync( @"public delegate $$"); - } [Fact] - public async Task TestInCastType() - { - // Could be a deconstruction - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); - } [Fact] - public async Task TestInCastType2() - { - // Could be a deconstruction - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInCastType2() + => VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); - } [Fact] - public async Task TestEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestBeforeStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBeforeStatement() + => VerifyKeywordAsync(AddInsideMethod( """ $$ return true; """)); - } [Fact] - public async Task TestAfterStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterStatement() + => VerifyKeywordAsync(AddInsideMethod( """ return true; $$ """)); - } [Fact] - public async Task TestAfterBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBlock() + => VerifyKeywordAsync(AddInsideMethod( """ if (true) { } $$ """)); - } [Fact] - public async Task TestNotAfterLock() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterLock() + => VerifyAbsenceAsync(AddInsideMethod( @"lock $$")); - } [Fact] - public async Task TestNotAfterLock2() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterLock2() + => VerifyAbsenceAsync(AddInsideMethod( @"lock ($$")); - } [Fact] - public async Task TestNotAfterLock3() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterLock3() + => VerifyAbsenceAsync(AddInsideMethod( @"lock (l$$")); - } [Fact] - public async Task TestNotInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotInClass() + => VerifyAbsenceAsync(""" class C { $$ } """); - } [Fact] - public async Task TestInFor() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFor() + => VerifyKeywordAsync(AddInsideMethod( @"for ($$")); - } [Fact] - public async Task TestNotInFor() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInFor() + => VerifyAbsenceAsync(AddInsideMethod( @"for (var $$")); - } [Fact] - public async Task TestInFor2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFor2() + => VerifyKeywordAsync(AddInsideMethod( @"for ($$;")); - } [Fact] - public async Task TestInFor3() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInFor3() + => VerifyKeywordAsync(AddInsideMethod( @"for ($$;;")); - } [Fact] - public async Task TestNotAfterVar() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterVar() + => VerifyAbsenceAsync(AddInsideMethod( @"var $$")); - } [Fact] - public async Task TestInForEach() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForEach() + => VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); - } [Fact] - public async Task TestNotInForEach() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInForEach() + => VerifyAbsenceAsync(AddInsideMethod( @"foreach (var $$")); - } [Fact] - public async Task TestInAwaitForEach() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInAwaitForEach() + => VerifyKeywordAsync(AddInsideMethod( @"await foreach ($$")); - } [Fact] - public async Task TestNotInAwaitForEach() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInAwaitForEach() + => VerifyAbsenceAsync(AddInsideMethod( @"await foreach (var $$")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37223")] - public async Task TestInForEachRefLoop0() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForEachRefLoop0() + => VerifyKeywordAsync(AddInsideMethod( @"foreach (ref $$")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37223")] - public async Task TestInForEachRefLoop1() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForEachRefLoop1() + => VerifyKeywordAsync(AddInsideMethod( @"foreach (ref $$ x")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37223")] - public async Task TestInForEachRefLoop2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForEachRefLoop2() + => VerifyKeywordAsync(AddInsideMethod( @"foreach (ref v$$ x")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37223")] - public async Task TestInForEachRefReadonlyLoop0() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForEachRefReadonlyLoop0() + => VerifyKeywordAsync(AddInsideMethod( @"foreach (ref readonly $$ x")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37223")] - public async Task TestInForRefLoop0() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForRefLoop0() + => VerifyKeywordAsync(AddInsideMethod( @"for (ref $$")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37223")] - public async Task TestInForRefLoop1() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForRefLoop1() + => VerifyKeywordAsync(AddInsideMethod( @"for (ref v$$")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37223")] - public async Task TestInForRefReadonlyLoop0() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForRefReadonlyLoop0() + => VerifyKeywordAsync(AddInsideMethod( @"for (ref readonly $$")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37223")] - public async Task TestInForRefReadonlyLoop1() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInForRefReadonlyLoop1() + => VerifyKeywordAsync(AddInsideMethod( @"for (ref readonly v$$")); - } [Fact] - public async Task TestInUsing() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInUsing() + => VerifyKeywordAsync(AddInsideMethod( @"using ($$")); - } [Fact] - public async Task TestNotInUsing() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInUsing() + => VerifyAbsenceAsync(AddInsideMethod( @"using (var $$")); - } [Fact] - public async Task TestInAwaitUsing() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInAwaitUsing() + => VerifyKeywordAsync(AddInsideMethod( @"await using ($$")); - } [Fact] - public async Task TestNotInAwaitUsing() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInAwaitUsing() + => VerifyAbsenceAsync(AddInsideMethod( @"await using (var $$")); - } [Fact] - public async Task TestAfterConstLocal() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterConstLocal() + => VerifyKeywordAsync(AddInsideMethod( @"const $$")); - } [Fact] - public async Task TestNotAfterConstField() - { - await VerifyAbsenceAsync( + public Task TestNotAfterConstField() + => VerifyAbsenceAsync( """ class C { const $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/12121")] - public async Task TestAfterOutKeywordInArgument() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterOutKeywordInArgument() + => VerifyKeywordAsync(AddInsideMethod( @"M(out $$")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/12121")] - public async Task TestAfterOutKeywordInParameter() - { - await VerifyAbsenceAsync( + public Task TestAfterOutKeywordInParameter() + => VerifyAbsenceAsync( """ class C { void M1(out $$ """); - } [Fact] - public async Task TestVarPatternInSwitch() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestVarPatternInSwitch() + => VerifyKeywordAsync(AddInsideMethod( """ switch(o) { case $$ } """)); - } [Fact] public async Task TestVarPatternInIs() => await VerifyKeywordAsync(AddInsideMethod("var b = o is $$ ")); [Fact] - public async Task TestNotAfterRefInMemberContext() - { - await VerifyAbsenceAsync( + public Task TestNotAfterRefInMemberContext() + => VerifyAbsenceAsync( """ class C { ref $$ """); - } [Fact] - public async Task TestNotAfterRefReadonlyInMemberContext() - { - await VerifyAbsenceAsync( + public Task TestNotAfterRefReadonlyInMemberContext() + => VerifyAbsenceAsync( """ class C { ref readonly $$ """); - } [Fact] - public async Task TestAfterRefInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$")); - } [Fact] - public async Task TestAfterRefReadonlyInStatementContext() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyInStatementContext() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); - } [Fact] - public async Task TestAfterRefLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); - } [Fact] - public async Task TestAfterRefReadonlyLocalDeclaration() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterRefReadonlyLocalDeclaration() + => VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); - } // For a local function, we can't add any tests - sometimes the keyword is offered and sometimes it's not, // depending on whether the keyword is partially written or not. This is because a partially written keyword @@ -435,16 +331,13 @@ await VerifyKeywordAsync(AddInsideMethod( // VerifyKeywordAsync & VerifyAbsenceAsync check for both cases - with the keyword partially written and without. [Fact] - public async Task TestNotAfterRefExpression() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterRefExpression() + => VerifyAbsenceAsync(AddInsideMethod( @"ref int x = ref $$")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/10170")] - public async Task TestInPropertyPattern() - { - await VerifyKeywordAsync( + public Task TestInPropertyPattern() + => VerifyKeywordAsync( """ using System; @@ -461,21 +354,16 @@ void Goo(object o) } } """); - } [Fact] - public async Task TestNotInDeclarationDeconstruction() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInDeclarationDeconstruction() + => VerifyAbsenceAsync(AddInsideMethod( @"var (x, $$) = (0, 0);")); - } [Fact] - public async Task TestInMixedDeclarationAndAssignmentInDeconstruction() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInMixedDeclarationAndAssignmentInDeconstruction() + => VerifyKeywordAsync(AddInsideMethod( @"(x, $$) = (0, 0);")); - } [Fact] public async Task TestAfterScoped() @@ -485,9 +373,8 @@ public async Task TestAfterScoped() } [Fact] - public async Task TestWithinExtension() - { - await VerifyAbsenceAsync( + public Task TestWithinExtension() + => VerifyAbsenceAsync( """ static class C { @@ -499,5 +386,4 @@ static class C """, CSharpNextParseOptions, CSharpNextScriptParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/VirtualKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/VirtualKeywordRecommenderTests.cs index 04396b693afee..5a157821f317b 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/VirtualKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/VirtualKeywordRecommenderTests.cs @@ -12,230 +12,182 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class VirtualKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] public async Task TestNotInCompilationUnit() => await VerifyAbsenceAsync(@"$$"); [Fact] - public async Task TestNotAfterExtern() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterExtern() + => VerifyAbsenceAsync(""" extern alias Goo; $$ """); - } [Fact] - public async Task TestNotAfterUsing() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterUsing() + => VerifyAbsenceAsync(""" using Goo; $$ """); - } [Fact] - public async Task TestNotAfterGlobalUsing() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterGlobalUsing() + => VerifyAbsenceAsync(""" global using Goo; $$ """); - } [Fact] - public async Task TestNotAfterNamespace() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNamespace() + => VerifyAbsenceAsync(""" namespace N {} $$ """); - } [Fact] - public async Task TestNotAfterTypeDeclaration() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterTypeDeclaration() + => VerifyAbsenceAsync(""" class C {} $$ """); - } [Fact] - public async Task TestNotAfterDelegateDeclaration() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterDelegateDeclaration() + => VerifyAbsenceAsync(""" delegate void Goo(); $$ """); - } [Fact] - public async Task TestAfterMethodInClass() - { - await VerifyKeywordAsync( + public Task TestAfterMethodInClass() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterFieldInClass() - { - await VerifyKeywordAsync( + public Task TestAfterFieldInClass() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterPropertyInClass() - { - await VerifyKeywordAsync( + public Task TestAfterPropertyInClass() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync( + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync( """ $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync( + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync( """ $$ global using Goo; """); - } [Fact] - public async Task TestNotAfterAssemblyAttribute() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterAssemblyAttribute() + => VerifyAbsenceAsync(""" [assembly: goo] $$ """); - } [Fact] - public async Task TestNotAfterRootAttribute() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterRootAttribute() + => VerifyAbsenceAsync(""" [goo] $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestNotInsideStruct() - { - await VerifyAbsenceAsync(""" + public Task TestNotInsideStruct() + => VerifyAbsenceAsync(""" struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync(""" + public Task TestInsideInterface() + => VerifyKeywordAsync(""" interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() @@ -282,136 +234,109 @@ public async Task TestNotAfterStatic() => await VerifyAbsenceAsync(@"static $$"); [Theory, CombinatorialData] - public async Task TestNotAfterNestedStatic([CombinatorialValues("class", "struct", "record", "record struct", "record class")] string declarationKind) - { - await VerifyAbsenceAsync(declarationKind + """ + public Task TestNotAfterNestedStatic([CombinatorialValues("class", "struct", "record", "record struct", "record class")] string declarationKind) + => VerifyAbsenceAsync(declarationKind + """ C { static $$ """); - } [Fact] - public async Task TestAfterNestedStaticInInterface() - { - await VerifyKeywordAsync(""" + public Task TestAfterNestedStaticInInterface() + => VerifyKeywordAsync(""" interface C { static $$ """); - } [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] - public async Task TestNotAfterNestedPrivate() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedPrivate() + => VerifyAbsenceAsync(""" class C { private $$ """); - } [Fact] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact] - public async Task TestNotAfterNestedAbstract() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedAbstract() + => VerifyAbsenceAsync(""" class C { abstract $$ """); - } [Fact] - public async Task TestNotAfterNestedVirtual() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedVirtual() + => VerifyAbsenceAsync(""" class C { virtual $$ """); - } [Fact] - public async Task TestNotAfterNestedOverride() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedOverride() + => VerifyAbsenceAsync(""" class C { override $$ """); - } [Fact] - public async Task TestNotAfterNestedSealed() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterNestedSealed() + => VerifyAbsenceAsync(""" class C { sealed $$ """); - } [Fact] - public async Task TestNotInProperty() - { - await VerifyAbsenceAsync( + public Task TestNotInProperty() + => VerifyAbsenceAsync( """ class C { int Goo { $$ """); - } [Fact] - public async Task TestNotInPropertyAfterAccessor() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAfterAccessor() + => VerifyAbsenceAsync( """ class C { int Goo { get; $$ """); - } [Fact] - public async Task TestNotInPropertyAfterAccessibility() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAfterAccessibility() + => VerifyAbsenceAsync( """ class C { int Goo { get; protected $$ """); - } [Fact] - public async Task TestNotInPropertyAfterInternal() - { - await VerifyAbsenceAsync( + public Task TestNotInPropertyAfterInternal() + => VerifyAbsenceAsync( """ class C { int Goo { get; internal $$ """); - } [Fact] - public async Task TestAfterPrivateProtected() - { - await VerifyKeywordAsync( + public Task TestAfterPrivateProtected() + => VerifyKeywordAsync( """ class C { private protected $$ """); - } [Fact] - public async Task TestWithinExtension() - { - await VerifyAbsenceAsync( + public Task TestWithinExtension() + => VerifyAbsenceAsync( """ static class C { @@ -421,5 +346,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/VoidKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/VoidKeywordRecommenderTests.cs index 2f43c924c07c3..8c9db924ad65c 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/VoidKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/VoidKeywordRecommenderTests.cs @@ -13,314 +13,248 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class VoidKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot() - { - await VerifyKeywordAsync( + public Task TestAtRoot() + => VerifyKeywordAsync( @"$$"); - } [Fact] - public async Task TestAfterClass() - { - await VerifyKeywordAsync( + public Task TestAfterClass() + => VerifyKeywordAsync( """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotAfterStackAlloc() - { - await VerifyAbsenceAsync( + public Task TestNotAfterStackAlloc() + => VerifyAbsenceAsync( """ class C { int* goo = stackalloc $$ """); - } [Fact] - public async Task TestInFixedStatement() - { - await VerifyKeywordAsync( + public Task TestInFixedStatement() + => VerifyKeywordAsync( @"fixed ($$"); - } [Fact] - public async Task TestInDelegateReturnType() - { - await VerifyKeywordAsync( + public Task TestInDelegateReturnType() + => VerifyKeywordAsync( @"public delegate $$"); - } [Theory, CombinatorialData] - public async Task TestNotInCastType(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInCastType(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( @"var str = (($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestNotInCastType2(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInCastType2(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( @"var str = (($$)items) as string;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, CombinatorialData] - public async Task TestInTypeOf(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInTypeOf(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"typeof($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestAfterExtern() - { - await VerifyKeywordAsync(""" + public Task TestAfterExtern() + => VerifyKeywordAsync(""" extern alias Goo; $$ """); - } [Fact] - public async Task TestAfterUsing() - { - await VerifyKeywordAsync(""" + public Task TestAfterUsing() + => VerifyKeywordAsync(""" using Goo; $$ """); - } [Fact] - public async Task TestAfterGlobalUsing() - { - await VerifyKeywordAsync(""" + public Task TestAfterGlobalUsing() + => VerifyKeywordAsync(""" global using Goo; $$ """); - } [Fact] - public async Task TestAfterNamespace() - { - await VerifyKeywordAsync(""" + public Task TestAfterNamespace() + => VerifyKeywordAsync(""" namespace N {} $$ """); - } [Fact] - public async Task TestAfterDelegateDeclaration() - { - await VerifyKeywordAsync(""" + public Task TestAfterDelegateDeclaration() + => VerifyKeywordAsync(""" delegate void Goo(); $$ """); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ global using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeGlobalUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeGlobalUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ global using Goo; """); - } [Fact] - public async Task TestAfterAssemblyAttribute() - { - await VerifyKeywordAsync(""" + public Task TestAfterAssemblyAttribute() + => VerifyKeywordAsync(""" [assembly: goo] $$ """); - } [Fact] - public async Task TestAfterRootAttribute() - { - await VerifyKeywordAsync(""" + public Task TestAfterRootAttribute() + => VerifyKeywordAsync(""" [goo] $$ """); - } [Fact] - public async Task TestAfterMultipleRootAttributes() - { - await VerifyKeywordAsync(""" + public Task TestAfterMultipleRootAttributes() + => VerifyKeywordAsync(""" [goo][goo] $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync( + public Task TestInsideInterface() + => VerifyKeywordAsync( """ interface I { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact] - public async Task TestAfterNestedPartial() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPartial() + => VerifyKeywordAsync( """ class C { partial $$ """); - } [Fact] public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact] - public async Task TestAfterNestedAbstract() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAbstract() + => VerifyKeywordAsync( """ class C { abstract $$ """); - } [Fact] public async Task TestNotAfterInternal() @@ -331,14 +265,12 @@ public async Task TestAfterInternal_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"internal $$"); [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] public async Task TestNotAfterPublic() @@ -349,83 +281,67 @@ public async Task TestAfterPublic_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"public $$"); [Fact] - public async Task TestAfterNestedPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublic() + => VerifyKeywordAsync( """ class C { public $$ """); - } [Fact] - public async Task TestNotAfterPrivate() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotAfterPrivate() + => VerifyAbsenceAsync(SourceCodeKind.Regular, @"private $$"); - } [Fact] - public async Task TestAfterPrivate_Script() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterPrivate_Script() + => VerifyKeywordAsync(SourceCodeKind.Script, @"private $$"); - } [Fact] - public async Task TestAfterNestedPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPrivate() + => VerifyKeywordAsync( """ class C { private $$ """); - } [Fact] - public async Task TestNotAfterProtected() - { - await VerifyAbsenceAsync( + public Task TestNotAfterProtected() + => VerifyAbsenceAsync( @"protected $$"); - } [Fact] - public async Task TestAfterNestedProtected() - { - await VerifyKeywordAsync( + public Task TestAfterNestedProtected() + => VerifyKeywordAsync( """ class C { protected $$ """); - } [Fact] public async Task TestNotAfterSealed() => await VerifyAbsenceAsync(@"sealed $$"); [Fact] - public async Task TestAfterNestedSealed() - { - await VerifyKeywordAsync( + public Task TestAfterNestedSealed() + => VerifyKeywordAsync( """ class C { sealed $$ """); - } [Fact] public async Task TestAfterStatic() => await VerifyKeywordAsync(@"static $$"); [Fact] - public async Task TestAfterStaticInClass() - { - await VerifyKeywordAsync( + public Task TestAfterStaticInClass() + => VerifyKeywordAsync( """ class C { static $$ """); - } [Fact] public async Task TestNotAfterStaticPublic() @@ -436,277 +352,223 @@ public async Task TestAfterStaticPublic_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"static public $$"); [Fact] - public async Task TestAfterNestedStaticPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticPublic() + => VerifyKeywordAsync( """ class C { static public $$ """); - } [Fact] - public async Task TestAfterDelegate() - { - await VerifyKeywordAsync( + public Task TestAfterDelegate() + => VerifyKeywordAsync( @"delegate $$"); - } [Theory, CombinatorialData] - public async Task TestNotAfterAnonymousDelegate(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterAnonymousDelegate(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( @"var q = delegate $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestNotAfterEvent() - { - await VerifyAbsenceAsync( + public Task TestNotAfterEvent() + => VerifyAbsenceAsync( """ class C { event $$ """); - } [Fact] - public async Task TestNotAfterVoid() - { - await VerifyAbsenceAsync( + public Task TestNotAfterVoid() + => VerifyAbsenceAsync( """ class C { void $$ """); - } [Fact] - public async Task TestNotAfterNew() - { - await VerifyAbsenceAsync( + public Task TestNotAfterNew() + => VerifyAbsenceAsync( @"new $$"); - } [Fact] - public async Task TestAfterNestedNew() - { - await VerifyKeywordAsync( + public Task TestAfterNestedNew() + => VerifyKeywordAsync( """ class C { new $$ """); - } [Theory, CombinatorialData] - public async Task TestInUnsafeBlock(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInUnsafeBlock(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( """ unsafe { $$ """, topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact] - public async Task TestInUnsafeMethod() - { - await VerifyKeywordAsync( + public Task TestInUnsafeMethod() + => VerifyKeywordAsync( """ class C { unsafe void Goo() { $$ """); - } [Fact] - public async Task TestInUnsafeClass() - { - await VerifyKeywordAsync( + public Task TestInUnsafeClass() + => VerifyKeywordAsync( """ unsafe class C { void Goo() { $$ """); - } [Fact] - public async Task TestNotInParameter() - { - await VerifyAbsenceAsync( + public Task TestNotInParameter() + => VerifyAbsenceAsync( """ class C { void Goo($$ """); - } [Fact] - public async Task TestInUnsafeParameter1() - { - await VerifyKeywordAsync( + public Task TestInUnsafeParameter1() + => VerifyKeywordAsync( """ class C { unsafe void Goo($$ """); - } [Fact] - public async Task TestInUnsafeParameter2() - { - await VerifyKeywordAsync( + public Task TestInUnsafeParameter2() + => VerifyKeywordAsync( """ unsafe class C { void Goo($$ """); - } [Fact] - public async Task TestNotInCast() - { - await VerifyAbsenceAsync( + public Task TestNotInCast() + => VerifyAbsenceAsync( """ class C { void Goo() { hr = GetRealProcAddress("CompareAssemblyIdentity", ($$ """); - } [Fact] - public async Task TestNotInCast2() - { - await VerifyAbsenceAsync( + public Task TestNotInCast2() + => VerifyAbsenceAsync( """ class C { void Goo() { hr = GetRealProcAddress("CompareAssemblyIdentity", ($$**)pfnCompareAssemblyIdentity); """); - } [Fact] - public async Task TestInUnsafeCast() - { - await VerifyKeywordAsync( + public Task TestInUnsafeCast() + => VerifyKeywordAsync( """ unsafe class C { void Goo() { hr = GetRealProcAddress("CompareAssemblyIdentity", ($$ """); - } [Fact] - public async Task TestInUnsafeCast2() - { - await VerifyKeywordAsync( + public Task TestInUnsafeCast2() + => VerifyKeywordAsync( """ unsafe class C { void Goo() { hr = GetRealProcAddress("CompareAssemblyIdentity", ($$**)pfnCompareAssemblyIdentity); """); - } [Fact] - public async Task TestInUnsafeConversionOperator() - { - await VerifyKeywordAsync( + public Task TestInUnsafeConversionOperator() + => VerifyKeywordAsync( """ class C { unsafe implicit operator int(C c) { $$ """); - } [Fact] - public async Task TestInUnsafeOperator() - { - await VerifyKeywordAsync( + public Task TestInUnsafeOperator() + => VerifyKeywordAsync( """ class C { unsafe int operator ++(C c) { $$ """); - } [Fact] - public async Task TestInUnsafeConstructor() - { - await VerifyKeywordAsync( + public Task TestInUnsafeConstructor() + => VerifyKeywordAsync( """ class C { unsafe C() { $$ """); - } [Fact] - public async Task TestInUnsafeDestructor() - { - await VerifyKeywordAsync( + public Task TestInUnsafeDestructor() + => VerifyKeywordAsync( """ class C { unsafe ~C() { $$ """); - } [Fact] - public async Task TestInUnsafeProperty() - { - await VerifyKeywordAsync( + public Task TestInUnsafeProperty() + => VerifyKeywordAsync( """ class C { unsafe int Goo { get { $$ """); - } [Fact] - public async Task TestInUnsafeIndexer() - { - await VerifyKeywordAsync( + public Task TestInUnsafeIndexer() + => VerifyKeywordAsync( """ class C { unsafe int this[int i] { get { $$ """); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [CombinatorialData] - public async Task TestNotInDefault(bool topLevelStatement) - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInDefault(bool topLevelStatement) + => VerifyAbsenceAsync(AddInsideMethod( @"default($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [CombinatorialData] - public async Task TestInSizeOf(bool topLevelStatement) - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInSizeOf(bool topLevelStatement) + => VerifyKeywordAsync(AddInsideMethod( @"sizeof($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544347")] - public async Task TestInUnsafeDefaultExpression() - { - await VerifyKeywordAsync( + public Task TestInUnsafeDefaultExpression() + => VerifyKeywordAsync( """ unsafe class C { static void Method1(void* p1 = default($$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544347")] - public async Task TestNotInDefaultExpression() - { - await VerifyAbsenceAsync( + public Task TestNotInDefaultExpression() + => VerifyAbsenceAsync( """ class C { static void Method1(void* p1 = default($$ """); - } [Fact] public async Task TestAfterAsync() @@ -718,9 +580,8 @@ public async Task TestAfterAsyncAsType() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] - public async Task TestLocalFunction() - { - await VerifyKeywordAsync(""" + public Task TestLocalFunction() + => VerifyKeywordAsync(""" class C { void M() @@ -729,14 +590,12 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8617")] [WorkItem("https://github.com/dotnet/roslyn/issues/14525")] [CompilerTrait(CompilerFeature.LocalFunctions)] - public async Task TestLocalFunction2() - { - await VerifyKeywordAsync(""" + public Task TestLocalFunction2() + => VerifyKeywordAsync(""" class C { void M() @@ -745,13 +604,11 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] - public async Task TestLocalFunction3() - { - await VerifyKeywordAsync(""" + public Task TestLocalFunction3() + => VerifyKeywordAsync(""" class C { void M() @@ -760,13 +617,11 @@ async async $$ } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] - public async Task TestLocalFunction4() - { - await VerifyAbsenceAsync(""" + public Task TestLocalFunction4() + => VerifyAbsenceAsync(""" class C { void M() @@ -775,13 +630,11 @@ var async $$ } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] - public async Task TestLocalFunction5() - { - await VerifyAbsenceAsync(""" + public Task TestLocalFunction5() + => VerifyAbsenceAsync(""" using System; class C { @@ -791,13 +644,11 @@ void M(Action a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] - public async Task TestLocalFunction6() - { - await VerifyKeywordAsync(""" + public Task TestLocalFunction6() + => VerifyKeywordAsync(""" class C { void M() @@ -806,13 +657,11 @@ unsafe async $$ } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] - public async Task TestLocalFunction7() - { - await VerifyKeywordAsync(""" + public Task TestLocalFunction7() + => VerifyKeywordAsync(""" using System; class C { @@ -825,124 +674,98 @@ void M(Action a) } } """); - } [Fact] - public async Task TestInFunctionPointer01() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointer01() + => VerifyKeywordAsync(""" class C { delegate*<$$ """); - } [Fact] - public async Task TestInFunctionPointer02() - { - await VerifyKeywordAsync(""" + public Task TestInFunctionPointer02() + => VerifyKeywordAsync(""" class C { C VerifyKeywordAsync(""" class C { delegate* VerifyKeywordAsync(""" class C { delegate* VerifyKeywordAsync(""" class C { delegate* VerifyKeywordAsync(""" class C { delegate* VerifyAbsenceAsync(""" class C { delegate*$$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43295")] - public async Task TestAfterReadonlyInStruct() - { - await VerifyKeywordAsync(""" + public Task TestAfterReadonlyInStruct() + => VerifyKeywordAsync(""" struct S { public readonly $$ """); - } [Fact] - public async Task TestAfterReadonlyInRecordStruct() - { - await VerifyKeywordAsync(""" + public Task TestAfterReadonlyInRecordStruct() + => VerifyKeywordAsync(""" record struct S { public readonly $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43295")] - public async Task TestNotAfterReadonlyInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotAfterReadonlyInClass() + => VerifyAbsenceAsync(""" class C { public readonly $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67986")] - public async Task TestInUsingUnsafeDirective() - { - await VerifyKeywordAsync("using unsafe T = $$"); - } + public Task TestInUsingUnsafeDirective() + => VerifyKeywordAsync("using unsafe T = $$"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67986")] - public async Task TestNotInRegularUsingDirective() - { - await VerifyAbsenceAsync("using T = $$"); - } + public Task TestNotInRegularUsingDirective() + => VerifyAbsenceAsync("using T = $$"); [Fact] - public async Task TestWithinExtension() - { - await VerifyKeywordAsync( + public Task TestWithinExtension() + => VerifyKeywordAsync( """ static class C { @@ -952,5 +775,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/VolatileKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/VolatileKeywordRecommenderTests.cs index 2b109267c3073..d29364ffd091b 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/VolatileKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/VolatileKeywordRecommenderTests.cs @@ -12,305 +12,241 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class VolatileKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalStatement_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] public async Task TestNotInCompilationUnit() => await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$"); [Fact] - public async Task TestNotAfterExtern() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotAfterExtern() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ extern alias Goo; $$ """); - } [Fact] - public async Task TestAfterExtern_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, """ + public Task TestAfterExtern_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ extern alias Goo; $$ """); - } [Fact] - public async Task TestNotAfterUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotAfterUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ using Goo; $$ """); - } [Fact] - public async Task TestAfterUsing_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, """ + public Task TestAfterUsing_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ using Goo; $$ """); - } [Fact] - public async Task TestNotAfterGlobalUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotAfterGlobalUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ global using Goo; $$ """); - } [Fact] - public async Task TestAfterGlobalUsing_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, """ + public Task TestAfterGlobalUsing_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ global using Goo; $$ """); - } [Fact] - public async Task TestNotAfterNamespace() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotAfterNamespace() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ namespace N {} $$ """); - } [Fact] - public async Task TestNotAfterTypeDeclaration() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotAfterTypeDeclaration() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ class C {} $$ """); - } [Fact] - public async Task TestNotAfterDelegateDeclaration() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotAfterDelegateDeclaration() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ delegate void Goo(); $$ """); - } [Fact] - public async Task TestAfterMethod() - { - await VerifyKeywordAsync( + public Task TestAfterMethod() + => VerifyKeywordAsync( """ class C { void Goo() {} $$ """); - } [Fact] - public async Task TestAfterField() - { - await VerifyKeywordAsync( + public Task TestAfterField() + => VerifyKeywordAsync( """ class C { int i; $$ """); - } [Fact] - public async Task TestAfterProperty() - { - await VerifyKeywordAsync( + public Task TestAfterProperty() + => VerifyKeywordAsync( """ class C { int i { get; } $$ """); - } [Fact] - public async Task TestNotBeforeUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ using Goo; """); - } [Fact] - public async Task TestNotBeforeGlobalUsing() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotBeforeGlobalUsing() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ $$ global using Goo; """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9880")] - public async Task TestNotBeforeGlobalUsing_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotBeforeGlobalUsing_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ $$ global using Goo; """); - } [Fact] - public async Task TestNotAfterAssemblyAttribute() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotAfterAssemblyAttribute() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ [assembly: goo] $$ """); - } [Fact] - public async Task TestAfterAssemblyAttribute_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, """ + public Task TestAfterAssemblyAttribute_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ [assembly: goo] $$ """); - } [Fact] - public async Task TestNotAfterRootAttribute() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, """ + public Task TestNotAfterRootAttribute() + => VerifyAbsenceAsync(SourceCodeKind.Regular, """ [goo] $$ """); - } [Fact] - public async Task TestAfterRootAttribute_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, """ + public Task TestAfterRootAttribute_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ [goo] $$ """); - } [Fact] - public async Task TestAfterNestedAttribute() - { - await VerifyKeywordAsync( + public Task TestAfterNestedAttribute() + => VerifyKeywordAsync( """ class C { [goo] $$ """); - } [Fact] - public async Task TestInsideStruct() - { - await VerifyKeywordAsync( + public Task TestInsideStruct() + => VerifyKeywordAsync( """ struct S { $$ """); - } [Fact] - public async Task TestInsideInterface() - { - await VerifyKeywordAsync(""" + public Task TestInsideInterface() + => VerifyKeywordAsync(""" interface I { $$ """); - } [Fact] - public async Task TestNotInsideEnum() - { - await VerifyAbsenceAsync(""" + public Task TestNotInsideEnum() + => VerifyAbsenceAsync(""" enum E { $$ """); - } [Fact] - public async Task TestInsideClass() - { - await VerifyKeywordAsync( + public Task TestInsideClass() + => VerifyKeywordAsync( """ class C { $$ """); - } [Fact] public async Task TestNotAfterPartial() @@ -329,14 +265,12 @@ public async Task TestAfterInternal_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"internal $$"); [Fact] - public async Task TestAfterNestedInternal() - { - await VerifyKeywordAsync( + public Task TestAfterNestedInternal() + => VerifyKeywordAsync( """ class C { internal $$ """); - } [Fact] public async Task TestNotAfterPublic() @@ -347,69 +281,55 @@ public async Task TestAfterPublic_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"public $$"); [Fact] - public async Task TestAfterNestedPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPublic() + => VerifyKeywordAsync( """ class C { public $$ """); - } [Fact] - public async Task TestNotAfterPrivate() - { - await VerifyAbsenceAsync(SourceCodeKind.Regular, + public Task TestNotAfterPrivate() + => VerifyAbsenceAsync(SourceCodeKind.Regular, @"private $$"); - } [Fact] - public async Task TestAfterPrivate_Script() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterPrivate_Script() + => VerifyKeywordAsync(SourceCodeKind.Script, @"private $$"); - } [Fact] - public async Task TestAfterNestedPrivate() - { - await VerifyKeywordAsync( + public Task TestAfterNestedPrivate() + => VerifyKeywordAsync( """ class C { private $$ """); - } [Fact] - public async Task TestNotAfterProtected() - { - await VerifyAbsenceAsync( + public Task TestNotAfterProtected() + => VerifyAbsenceAsync( @"protected $$"); - } [Fact] - public async Task TestAfterNestedProtected() - { - await VerifyKeywordAsync( + public Task TestAfterNestedProtected() + => VerifyKeywordAsync( """ class C { protected $$ """); - } [Fact] public async Task TestNotAfterSealed() => await VerifyAbsenceAsync(@"sealed $$"); [Fact] - public async Task TestNotAfterNestedSealed() - { - await VerifyAbsenceAsync( + public Task TestNotAfterNestedSealed() + => VerifyAbsenceAsync( """ class C { sealed $$ """); - } [Fact] public async Task TestNotAfterStatic() @@ -420,14 +340,12 @@ public async Task TestAfterStatic_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"static $$"); [Fact] - public async Task TestAfterNestedStatic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStatic() + => VerifyKeywordAsync( """ class C { static $$ """); - } [Fact] public async Task TestNotAfterStaticPublic() @@ -438,81 +356,66 @@ public async Task TestAfterStaticPublic_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"static public $$"); [Fact] - public async Task TestAfterNestedStaticPublic() - { - await VerifyKeywordAsync( + public Task TestAfterNestedStaticPublic() + => VerifyKeywordAsync( """ class C { static public $$ """); - } [Fact] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact] - public async Task TestNotAfterEvent() - { - await VerifyAbsenceAsync( + public Task TestNotAfterEvent() + => VerifyAbsenceAsync( """ class C { event $$ """); - } [Fact] - public async Task TestNotAfterConst() - { - await VerifyAbsenceAsync( + public Task TestNotAfterConst() + => VerifyAbsenceAsync( """ class C { const $$ """); - } [Fact] - public async Task TestNotAfterVolatile() - { - await VerifyAbsenceAsync( + public Task TestNotAfterVolatile() + => VerifyAbsenceAsync( """ class C { volatile $$ """); - } [Fact] - public async Task TestNotAfterNew() - { - await VerifyAbsenceAsync( + public Task TestNotAfterNew() + => VerifyAbsenceAsync( @"new $$"); - } [Fact] - public async Task TestAfterNestedNew() - { - await VerifyKeywordAsync( + public Task TestAfterNestedNew() + => VerifyKeywordAsync( """ class C { new $$ """); - } [Fact] - public async Task TestNotInMethod() - { - await VerifyAbsenceAsync( + public Task TestNotInMethod() + => VerifyAbsenceAsync( """ class C { void Goo() { $$ """); - } [Fact] - public async Task TestWithinExtension() - { - await VerifyAbsenceAsync( + public Task TestWithinExtension() + => VerifyAbsenceAsync( """ static class C { @@ -522,5 +425,4 @@ static class C } } """, CSharpNextParseOptions); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/WarningKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/WarningKeywordRecommenderTests.cs index eac7bec5aa2cb..77be370666b73 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/WarningKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/WarningKeywordRecommenderTests.cs @@ -12,81 +12,61 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class WarningKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterHash() - { - await VerifyKeywordAsync( + public Task TestAfterHash() + => VerifyKeywordAsync( @"#$$"); - } [Fact] - public async Task TestAfterHashAndSpace() - { - await VerifyKeywordAsync( + public Task TestAfterHashAndSpace() + => VerifyKeywordAsync( @"# $$"); - } [Fact] - public async Task TestAfterPragma() - { - await VerifyKeywordAsync( + public Task TestAfterPragma() + => VerifyKeywordAsync( @"#pragma $$"); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/WarningsKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/WarningsKeywordRecommenderTests.cs index 1d50bc6043ee6..85deca1e482a4 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/WarningsKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/WarningsKeywordRecommenderTests.cs @@ -12,116 +12,86 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class WarningsKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterHash() - { - await VerifyAbsenceAsync( + public Task TestAfterHash() + => VerifyAbsenceAsync( @"#$$"); - } [Fact] - public async Task TestAfterHashAndSpace() - { - await VerifyAbsenceAsync( + public Task TestAfterHashAndSpace() + => VerifyAbsenceAsync( @"# $$"); - } [Fact] - public async Task TestAfterPragma() - { - await VerifyAbsenceAsync( + public Task TestAfterPragma() + => VerifyAbsenceAsync( @"#pragma $$"); - } [Fact] - public async Task TestAfterNullable() - { - await VerifyAbsenceAsync( + public Task TestAfterNullable() + => VerifyAbsenceAsync( @"#nullable $$"); - } [Fact] - public async Task TestAfterNullableEnable() - { - await VerifyKeywordAsync( + public Task TestAfterNullableEnable() + => VerifyKeywordAsync( @"#nullable enable $$"); - } [Fact] - public async Task TestAfterNullableDisable() - { - await VerifyKeywordAsync( + public Task TestAfterNullableDisable() + => VerifyKeywordAsync( @"#nullable disable $$"); - } [Fact] - public async Task TestAfterNullableRestore() - { - await VerifyKeywordAsync( + public Task TestAfterNullableRestore() + => VerifyKeywordAsync( @"#nullable restore $$"); - } [Fact] - public async Task TestAfterNullableBadSetting() - { - await VerifyAbsenceAsync( + public Task TestAfterNullableBadSetting() + => VerifyAbsenceAsync( @"#nullable true $$"); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/WhenKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/WhenKeywordRecommenderTests.cs index ea1aa019709bf..38d46c025cbff 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/WhenKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/WhenKeywordRecommenderTests.cs @@ -13,60 +13,44 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class WhenKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestForCatchClause_AfterCatch() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestForCatchClause_AfterCatch() + => VerifyKeywordAsync(AddInsideMethod( @"try {} catch $$")); - } [Fact] - public async Task TestForCatchClause_AfterCatchDeclaration1() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestForCatchClause_AfterCatchDeclaration1() + => VerifyKeywordAsync(AddInsideMethod( @"try {} catch (Exception) $$")); - } [Fact] - public async Task TestForCatchClause_AfterCatchDeclaration2() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestForCatchClause_AfterCatchDeclaration2() + => VerifyKeywordAsync(AddInsideMethod( @"try {} catch (Exception e) $$")); - } [Fact] - public async Task TestForCatchClause_AfterCatchDeclarationEmpty() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestForCatchClause_AfterCatchDeclarationEmpty() + => VerifyKeywordAsync(AddInsideMethod( @"try {} catch () $$")); - } [Fact] - public async Task TestForCatchClause_NotAfterTryBlock() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestForCatchClause_NotAfterTryBlock() + => VerifyAbsenceAsync(AddInsideMethod( @"try {} $$")); - } [Fact] - public async Task TestForCatchClause_NotAfterFilter1() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestForCatchClause_NotAfterFilter1() + => VerifyAbsenceAsync(AddInsideMethod( @"try {} catch (Exception e) when $$")); - } [Fact] - public async Task TestForCatchClause_NotAfterFilter2() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestForCatchClause_NotAfterFilter2() + => VerifyAbsenceAsync(AddInsideMethod( @"try {} catch (Exception e) when ($$")); - } [Fact] - public async Task TestForCatchClause_NotAfterFilter3() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestForCatchClause_NotAfterFilter3() + => VerifyAbsenceAsync(AddInsideMethod( @"try {} catch (Exception e) when (true) $$")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24113")] public async Task TestForSwitchCase_AfterDeclarationPattern() @@ -445,40 +429,34 @@ class C """); [Fact] - public async Task TestForSwitchCase_SemanticCheck_NotAfterTypeAliasVar() - { - await VerifyAbsenceAsync(""" + public Task TestForSwitchCase_SemanticCheck_NotAfterTypeAliasVar() + => VerifyAbsenceAsync(""" using var = System.String; class C { void M() { switch (new object()) { case var $$ } } } """); - } [Fact] - public async Task TestForSwitchCase_SemanticCheck_NotAfterTypeAliasVar_BeforeBreak() - { - await VerifyAbsenceAsync(""" + public Task TestForSwitchCase_SemanticCheck_NotAfterTypeAliasVar_BeforeBreak() + => VerifyAbsenceAsync(""" using var = System.String; class C { void M() { switch (new object()) { case var $$ break; } } } """); - } [Fact] - public async Task TestForSwitchCase_SemanticCheck_NotAfterTypeAliasVar_BeforeWhen() - { - await VerifyAbsenceAsync(""" + public Task TestForSwitchCase_SemanticCheck_NotAfterTypeAliasVar_BeforeWhen() + => VerifyAbsenceAsync(""" using var = System.String; class C { void M() { switch (new object()) { case var $$ when } } } """); - } [Fact] public async Task TestForSwitchCase_SemanticCheck_AfterLocalConstantVar() @@ -523,9 +501,8 @@ class C """); [Fact] - public async Task TestForSwitchCase_SemanticCheck_AfterTypeAliasAndFieldConstantVar() - { - await VerifyAbsenceAsync(""" + public Task TestForSwitchCase_SemanticCheck_AfterTypeAliasAndFieldConstantVar() + => VerifyAbsenceAsync(""" using var = System.String; class C { @@ -533,12 +510,10 @@ class C void M() { switch (new object()) { case var $$ } } } """); - } [Fact] - public async Task TestForSwitchCase_SemanticCheck_AfterTypeAliasAndFieldConstantVar_BeforeBreak() - { - await VerifyAbsenceAsync(""" + public Task TestForSwitchCase_SemanticCheck_AfterTypeAliasAndFieldConstantVar_BeforeBreak() + => VerifyAbsenceAsync(""" using var = System.String; class C { @@ -546,12 +521,10 @@ class C void M() { switch (new object()) { case var $$ break; } } } """); - } [Fact] - public async Task TestForSwitchCase_SemanticCheck_AfterTypeAliasAndFieldConstantVar_BeforeWhen() - { - await VerifyAbsenceAsync(""" + public Task TestForSwitchCase_SemanticCheck_AfterTypeAliasAndFieldConstantVar_BeforeWhen() + => VerifyAbsenceAsync(""" using var = System.String; class C { @@ -559,12 +532,10 @@ class C void M() { switch (new object()) { case var $$ when } } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44480")] - public async Task TestAfterSwitchExpressionPattern1() - { - await VerifyKeywordAsync(""" + public Task TestAfterSwitchExpressionPattern1() + => VerifyKeywordAsync(""" using var = System.String; class C { @@ -577,12 +548,10 @@ void M(int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44480")] - public async Task TestAfterSwitchExpressionPattern2() - { - await VerifyKeywordAsync(""" + public Task TestAfterSwitchExpressionPattern2() + => VerifyKeywordAsync(""" using var = System.String; class C { @@ -595,12 +564,10 @@ void M(int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44480")] - public async Task TestAfterSwitchExpressionPattern3() - { - await VerifyKeywordAsync(""" + public Task TestAfterSwitchExpressionPattern3() + => VerifyKeywordAsync(""" using var = System.String; class C { @@ -613,12 +580,10 @@ void M(int i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44480")] - public async Task TestAfterSwitchExpressionPattern4() - { - await VerifyKeywordAsync(""" + public Task TestAfterSwitchExpressionPattern4() + => VerifyKeywordAsync(""" using var = System.String; class C { @@ -631,5 +596,4 @@ void M(int i) } } """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/WhereKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/WhereKeywordRecommenderTests.cs index 72def08d18ab2..12294102d9d82 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/WhereKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/WhereKeywordRecommenderTests.cs @@ -13,643 +13,512 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class WhereKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestNewClause() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestNewClause() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y $$ """)); - } [Fact] - public async Task TestAfterPreviousClause() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterPreviousClause() + => VerifyKeywordAsync(AddInsideMethod( """ var v = from x in y where x > y $$ """)); - } [Fact] - public async Task TestAfterPreviousContinuationClause() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterPreviousContinuationClause() + => VerifyKeywordAsync(AddInsideMethod( """ var v = from x in y group x by y into g $$ """)); - } [Fact] - public async Task TestNotAtEndOfPreviousClause() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAtEndOfPreviousClause() + => VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y$$")); - } [Fact] - public async Task TestBetweenClauses() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBetweenClauses() + => VerifyKeywordAsync(AddInsideMethod( """ var q = from x in y $$ from z in w """)); - } [Fact] - public async Task TestNotAfterWhere() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterWhere() + => VerifyAbsenceAsync(AddInsideMethod( """ var q = from x in y where $$ from z in w """)); - } [Fact] - public async Task TestNotAfterClass() - { - await VerifyAbsenceAsync( + public Task TestNotAfterClass() + => VerifyAbsenceAsync( @"class C $$"); - } [Fact] - public async Task TestAfterGenericClass() - { - await VerifyKeywordAsync( + public Task TestAfterGenericClass() + => VerifyKeywordAsync( @"class C $$"); - } [Fact] - public async Task TestNotAfterClassBaseList() - { - await VerifyAbsenceAsync( + public Task TestNotAfterClassBaseList() + => VerifyAbsenceAsync( @"class C : IGoo $$"); - } [Fact] - public async Task TestAfterGenericClassBaseList() - { - await VerifyKeywordAsync( + public Task TestAfterGenericClassBaseList() + => VerifyKeywordAsync( @"class C : IGoo $$"); - } [Fact] - public async Task TestNotAfterDelegate() - { - await VerifyAbsenceAsync( + public Task TestNotAfterDelegate() + => VerifyAbsenceAsync( @"delegate void D() $$"); - } [Fact] - public async Task TestAfterGenericDelegate() - { - await VerifyKeywordAsync( + public Task TestAfterGenericDelegate() + => VerifyKeywordAsync( @"delegate void D() $$"); - } [Fact] - public async Task TestAfterPreviousClassConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterPreviousClassConstraint() + => VerifyKeywordAsync( @"class C where T : class $$"); - } [Fact] - public async Task TestAfterPreviousStructConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterPreviousStructConstraint() + => VerifyKeywordAsync( @"class C where T : struct $$"); - } [Fact] - public async Task TestAfterPreviousNewConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterPreviousNewConstraint() + => VerifyKeywordAsync( @"class C where T : new() $$"); - } [Fact] - public async Task TestAfterPreviousAllowsRefStructConstraint_01() - { - await VerifyKeywordAsync( + public Task TestAfterPreviousAllowsRefStructConstraint_01() + => VerifyKeywordAsync( @"class C where T : allows ref struct $$"); - } [Fact] - public async Task TestAfterPreviousAllowsRefStructConstraint_02() - { - await VerifyKeywordAsync( + public Task TestAfterPreviousAllowsRefStructConstraint_02() + => VerifyKeywordAsync( @"class C { void M() where T : allows ref struct $$"); - } [Fact] - public async Task TestAfterPreviousConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterPreviousConstraint() + => VerifyKeywordAsync( @"class C where T : IList $$"); - } [Fact] - public async Task TestAfterPreviousDelegateClassConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterPreviousDelegateClassConstraint() + => VerifyKeywordAsync( @"delegate void D() where T : class $$"); - } [Fact] - public async Task TestAfterPreviousDelegateStructConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterPreviousDelegateStructConstraint() + => VerifyKeywordAsync( @"delegate void D() where T : struct $$"); - } [Fact] - public async Task TestAfterPreviousDelegateNewConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterPreviousDelegateNewConstraint() + => VerifyKeywordAsync( @"delegate void D() where T : new() $$"); - } [Fact] - public async Task TestAfterPreviousDelegateConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterPreviousDelegateConstraint() + => VerifyKeywordAsync( @"delegate void D() where T : IList $$"); - } [Fact] - public async Task TestNotAfterMethod() - { - await VerifyAbsenceAsync( + public Task TestNotAfterMethod() + => VerifyAbsenceAsync( """ class C { void D() $$ """); - } [Fact] - public async Task TestAfterGenericMethod() - { - await VerifyKeywordAsync( + public Task TestAfterGenericMethod() + => VerifyKeywordAsync( """ class C { void D() $$ """); - } [Fact] - public async Task TestAfterPreviousMethodClassConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterPreviousMethodClassConstraint() + => VerifyKeywordAsync( """ class C { void D() where T : class $$ """); - } [Fact] - public async Task TestAfterPreviousMethodStructConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterPreviousMethodStructConstraint() + => VerifyKeywordAsync( """ class C { void D() where T : struct $$ """); - } [Fact] - public async Task TestAfterPreviousMethodNewConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterPreviousMethodNewConstraint() + => VerifyKeywordAsync( """ class C { void D() where T : new() $$ """); - } [Fact] - public async Task TestAfterPreviousMethodConstraint() - { - await VerifyKeywordAsync( + public Task TestAfterPreviousMethodConstraint() + => VerifyKeywordAsync( """ class C { void D() where T : IList $$ """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/550715")] - public async Task TestNotAfterWhereTypeConstraint() - { - await VerifyAbsenceAsync( + public Task TestNotAfterWhereTypeConstraint() + => VerifyAbsenceAsync( """ public class Goo : System.Object where $$ { } """); - } [Fact] - public async Task TestNotAfterWhereWhere() - { - await VerifyAbsenceAsync( + public Task TestNotAfterWhereWhere() + => VerifyAbsenceAsync( """ public class Goo : System.Object where where $$ { } """); - } [Fact] - public async Task TestNotAfterWhereWhereWhere() - { - await VerifyAbsenceAsync( + public Task TestNotAfterWhereWhereWhere() + => VerifyAbsenceAsync( """ public class Goo : System.Object where where where $$ { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/550720")] - public async Task TestNoWhereAfterDot() - { - await VerifyAbsenceAsync( + public Task TestNoWhereAfterDot() + => VerifyAbsenceAsync( """ public class Goo : System.$$ { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30785")] - public async Task TestNotAfterDot1() - { - await VerifyAbsenceAsync( + public Task TestNotAfterDot1() + => VerifyAbsenceAsync( """ public class C { void M where T : System.$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30785")] - public async Task TestNotAfterDot2() - { - await VerifyAbsenceAsync( + public Task TestNotAfterDot2() + => VerifyAbsenceAsync( """ public class C where T : System.$$ { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30785")] - public async Task TestAfterValidConstraint1() - { - await VerifyKeywordAsync( + public Task TestAfterValidConstraint1() + => VerifyKeywordAsync( """ public class C { void M where T : System.Exception $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30785")] - public async Task TestAfterValidConstraint2() - { - await VerifyKeywordAsync( + public Task TestAfterValidConstraint2() + => VerifyKeywordAsync( """ public class C where T : System.Exception $$ { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30785")] - public async Task TestNotAfterGlobal1() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGlobal1() + => VerifyAbsenceAsync( """ public class C { void M where T : global::$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30785")] - public async Task TestNotAfterGlobal2() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGlobal2() + => VerifyAbsenceAsync( """ public class C where T : global::$$ { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30785")] - public async Task TestAfterValidConstraint3() - { - await VerifyKeywordAsync( + public Task TestAfterValidConstraint3() + => VerifyKeywordAsync( """ public class C { void M where T : global::System.Exception $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30785")] - public async Task TestAfterValidConstraint4() - { - await VerifyKeywordAsync( + public Task TestAfterValidConstraint4() + => VerifyKeywordAsync( """ public class C where T : global::System.Exception $$ { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30785")] - public async Task TestNotAfterGenericConstraintStart1() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGenericConstraintStart1() + => VerifyAbsenceAsync( """ public class C { void M where T : List<$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30785")] - public async Task TestNotAfterGenericConstraintStart2() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGenericConstraintStart2() + => VerifyAbsenceAsync( """ public class C where T : List<$$ { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30785")] - public async Task TestAfterValidGenericConstraint1() - { - await VerifyKeywordAsync( + public Task TestAfterValidGenericConstraint1() + => VerifyKeywordAsync( """ public class C { void M where T : List $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30785")] - public async Task TestAfterValidGenericConstraint2() - { - await VerifyKeywordAsync( + public Task TestAfterValidGenericConstraint2() + => VerifyKeywordAsync( """ public class C where T : List $$ { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30785")] - public async Task TestNotAfterGenericConstraintStartSecondParameter1() - { - await VerifyAbsenceAsync( + public Task TestNotAfterGenericConstraintStartSecondParameter1() + => VerifyAbsenceAsync( """ public class C { void M where T : Dictionary VerifyAbsenceAsync( """ public class C where T : Dictionary VerifyKeywordAsync( """ public class C { void M where T : Dictionary $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30785")] - public async Task TestAfterValidGenericConstraint4() - { - await VerifyKeywordAsync( + public Task TestAfterValidGenericConstraint4() + => VerifyKeywordAsync( """ public class C where T : Dictionary $$ { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30785")] - public async Task TestNotAfterDoubleUnclosedGenericConstraint1() - { - await VerifyAbsenceAsync( + public Task TestNotAfterDoubleUnclosedGenericConstraint1() + => VerifyAbsenceAsync( """ public class C { void M where T : List$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30785")] - public async Task TestNotAfterDoubleUnclosedGenericConstraint2() - { - await VerifyAbsenceAsync( + public Task TestNotAfterDoubleUnclosedGenericConstraint2() + => VerifyAbsenceAsync( """ public class C where T : List$$ { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30785")] - public async Task TestAfterValidGenericConstraint5() - { - await VerifyKeywordAsync( + public Task TestAfterValidGenericConstraint5() + => VerifyKeywordAsync( """ public class C { void M where T : List> $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30785")] - public async Task TestAfterValidGenericConstraint6() - { - await VerifyKeywordAsync( + public Task TestAfterValidGenericConstraint6() + => VerifyKeywordAsync( """ public class C where T : List> $$ { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30785")] - public async Task TestNotAfterTupleInsideGenericConstraintStart1() - { - await VerifyAbsenceAsync( + public Task TestNotAfterTupleInsideGenericConstraintStart1() + => VerifyAbsenceAsync( """ public class C { void M where T : List<(int, $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30785")] - public async Task TestNotAfterTupleInsideGenericConstraintStart2() - { - await VerifyAbsenceAsync( + public Task TestNotAfterTupleInsideGenericConstraintStart2() + => VerifyAbsenceAsync( """ public class C where T : List<(int, $$ { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30785")] - public async Task TestNotAfterTupleClosedInsideGenericConstraintStart1() - { - await VerifyAbsenceAsync( + public Task TestNotAfterTupleClosedInsideGenericConstraintStart1() + => VerifyAbsenceAsync( """ public class C { void M where T : List<(int, string)$$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30785")] - public async Task TestNotAfterTupleClosedInsideGenericConstraintStart2() - { - await VerifyAbsenceAsync( + public Task TestNotAfterTupleClosedInsideGenericConstraintStart2() + => VerifyAbsenceAsync( """ public class C where T : List<(int, string)$$ { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30785")] - public async Task TestAfterValidGenericConstraintWithTuple1() - { - await VerifyKeywordAsync( + public Task TestAfterValidGenericConstraintWithTuple1() + => VerifyKeywordAsync( """ public class C { void M where T : List<(int, string)> $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30785")] - public async Task TestAfterValidGenericConstraintWithTuple2() - { - await VerifyKeywordAsync( + public Task TestAfterValidGenericConstraintWithTuple2() + => VerifyKeywordAsync( """ public class C where T : List<(int, string)> $$ { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72821")] - public async Task TestNotAfterLocalFunction() - { - await VerifyAbsenceAsync( + public Task TestNotAfterLocalFunction() + => VerifyAbsenceAsync( """ class C { @@ -657,12 +526,10 @@ void M() { void Inner() $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72821")] - public async Task TestAfterGenericLocalFunction() - { - await VerifyKeywordAsync( + public Task TestAfterGenericLocalFunction() + => VerifyKeywordAsync( """ class C { @@ -670,12 +537,10 @@ void M() { void Inner() $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72821")] - public async Task TestAfterFirstValidConstraintInGenericLocalFunction() - { - await VerifyKeywordAsync( + public Task TestAfterFirstValidConstraintInGenericLocalFunction() + => VerifyKeywordAsync( """ class C { @@ -685,5 +550,4 @@ void Inner() where T1 : C $$ """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/WhileKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/WhileKeywordRecommenderTests.cs index e46a7b3217cdd..c90fd48683017 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/WhileKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/WhileKeywordRecommenderTests.cs @@ -12,195 +12,153 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class WhileKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestAtRoot_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAtRoot_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestAfterClass_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterClass_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestAfterGlobalStatement() - { - await VerifyKeywordAsync( + public Task TestAfterGlobalStatement() + => VerifyKeywordAsync( """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestAfterGlobalVariableDeclaration_Interactive() - { - await VerifyKeywordAsync(SourceCodeKind.Script, + public Task TestAfterGlobalVariableDeclaration_Interactive() + => VerifyKeywordAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestBeforeStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBeforeStatement() + => VerifyKeywordAsync(AddInsideMethod( """ $$ return true; """)); - } [Fact] - public async Task TestAfterStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterStatement() + => VerifyKeywordAsync(AddInsideMethod( """ return true; $$ """)); - } [Fact] - public async Task TestAfterBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBlock() + => VerifyKeywordAsync(AddInsideMethod( """ if (true) { } $$ """)); - } [Fact] - public async Task TestInsideWhile() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideWhile() + => VerifyKeywordAsync(AddInsideMethod( """ while (true) $$ """)); - } [Fact] - public async Task TestInsideWhileInsideWhile() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideWhileInsideWhile() + => VerifyKeywordAsync(AddInsideMethod( """ while (true) while (true) $$ """)); - } [Fact] - public async Task TestInsideWhileBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestInsideWhileBlock() + => VerifyKeywordAsync(AddInsideMethod( """ while (true) { $$ """)); - } [Fact] - public async Task TestAfterDo() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterDo() + => VerifyKeywordAsync(AddInsideMethod( """ do Console.WriteLine(); $$ """)); - } [Fact] - public async Task TestAfterDoBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterDoBlock() + => VerifyKeywordAsync(AddInsideMethod( """ do { } $$ """)); - } [Fact] - public async Task TestNotAfterWhile1() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterWhile1() + => VerifyAbsenceAsync(AddInsideMethod( @"while $$")); - } [Fact] - public async Task TestNotAfterWhile2() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterWhile2() + => VerifyAbsenceAsync(AddInsideMethod( @"while ($$")); - } [Fact] - public async Task TestNotAfterWhile3() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterWhile3() + => VerifyAbsenceAsync(AddInsideMethod( @"while (true $$")); - } [Fact] - public async Task TestNotInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotInClass() + => VerifyAbsenceAsync(""" class C { $$ } """); - } [Fact] - public async Task TestAfterUsing() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterUsing() + => VerifyKeywordAsync(AddInsideMethod( """ using (var e2 = other.TypeArguments.GetEnumerator()) $$ """)); - } [Fact] - public async Task TestAfterLock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterLock() + => VerifyKeywordAsync(AddInsideMethod( """ lock (expr) $$ """)); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/WithKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/WithKeywordRecommenderTests.cs index ade017f3e040a..8ec155e651bad 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/WithKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/WithKeywordRecommenderTests.cs @@ -13,136 +13,103 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class WithKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAfterWith() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterWith() + => VerifyAbsenceAsync(AddInsideMethod( @"var q = goo with $$")); - } [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestNotInEmptyStatement() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotInEmptyStatement() + => VerifyAbsenceAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestAfterExpr() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterExpr() + => VerifyKeywordAsync(AddInsideMethod( @"var q = goo $$")); - } [Fact] - public async Task TestAfterDottedName() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterDottedName() + => VerifyKeywordAsync(AddInsideMethod( @"var q = goo.Current $$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543041")] - public async Task TestNotAfterVarInForLoop() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterVarInForLoop() + => VerifyAbsenceAsync(AddInsideMethod( @"for (var $$")); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] - public async Task TestNotBeforeFirstStringHole() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotBeforeFirstStringHole() + => VerifyAbsenceAsync(AddInsideMethod( """ var x = "\{0}$$\{1}\{2}" """)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] - public async Task TestNotBetweenStringHoles() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotBetweenStringHoles() + => VerifyAbsenceAsync(AddInsideMethod( """ var x = "\{0}\{1}$$\{2}" """)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] - public async Task TestNotAfterStringHoles() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterStringHoles() + => VerifyAbsenceAsync(AddInsideMethod( """ var x = "\{0}\{1}\{2}$$" """)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] - public async Task TestAfterLastStringHole() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterLastStringHole() + => VerifyKeywordAsync(AddInsideMethod( @"var x = ""\{0}\{1}\{2}"" $$")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1736")] - public async Task TestNotWithinNumericLiteral() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotWithinNumericLiteral() + => VerifyAbsenceAsync(AddInsideMethod( @"var x = .$$0;")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28586")] - public async Task TestNotAfterAsync() - { - await VerifyAbsenceAsync( + public Task TestNotAfterAsync() + => VerifyAbsenceAsync( """ using System; @@ -158,12 +125,10 @@ void Bar(Func f) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8319")] - public async Task TestNotAfterMethodReference() - { - await VerifyAbsenceAsync( + public Task TestNotAfterMethodReference() + => VerifyAbsenceAsync( """ using System; @@ -171,12 +136,10 @@ class C { void M() { var v = Console.WriteLine $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8319")] - public async Task TestNotAfterAnonymousMethod() - { - await VerifyAbsenceAsync( + public Task TestNotAfterAnonymousMethod() + => VerifyAbsenceAsync( """ using System; @@ -184,12 +147,10 @@ class C { void M() { Action a = delegate { } $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8319")] - public async Task TestNotAfterLambda1() - { - await VerifyAbsenceAsync( + public Task TestNotAfterLambda1() + => VerifyAbsenceAsync( """ using System; @@ -197,12 +158,10 @@ class C { void M() { Action b = (() => 0) $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8319")] - public async Task TestNotAfterLambda2() - { - await VerifyAbsenceAsync( + public Task TestNotAfterLambda2() + => VerifyAbsenceAsync( """ using System; @@ -210,12 +169,10 @@ class C { void M() { Action b = () => {} $$ """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48573")] - public async Task TestMissingAfterNumericLiteral() - { - await VerifyAbsenceAsync( + public Task TestMissingAfterNumericLiteral() + => VerifyAbsenceAsync( """ class C { @@ -225,12 +182,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48573")] - public async Task TestMissingAfterNumericLiteralAndDot() - { - await VerifyAbsenceAsync( + public Task TestMissingAfterNumericLiteralAndDot() + => VerifyAbsenceAsync( """ class C { @@ -240,12 +195,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48573")] - public async Task TestMissingAfterNumericLiteralDotAndSpace() - { - await VerifyAbsenceAsync( + public Task TestMissingAfterNumericLiteralDotAndSpace() + => VerifyAbsenceAsync( """ class C { @@ -255,12 +208,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31367")] - public async Task TestMissingInCaseClause1() - { - await VerifyAbsenceAsync( + public Task TestMissingInCaseClause1() + => VerifyAbsenceAsync( """ class A { @@ -278,12 +229,10 @@ void M(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31367")] - public async Task TestMissingInCaseClause2() - { - await VerifyAbsenceAsync( + public Task TestMissingInCaseClause2() + => VerifyAbsenceAsync( """ namespace N { @@ -304,5 +253,4 @@ void M(object o) } } """); - } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/YieldKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/YieldKeywordRecommenderTests.cs index 2a6a501784d19..0f2f8e00ff987 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/YieldKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/YieldKeywordRecommenderTests.cs @@ -12,109 +12,85 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations; public sealed class YieldKeywordRecommenderTests : KeywordRecommenderTests { [Fact] - public async Task TestNotAtRoot_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAtRoot_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); - } [Fact] - public async Task TestNotAfterClass_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterClass_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ class C { } $$ """); - } [Fact] - public async Task TestNotAfterGlobalStatement_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalStatement_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ System.Console.WriteLine(); $$ """); - } [Fact] - public async Task TestNotAfterGlobalVariableDeclaration_Interactive() - { - await VerifyAbsenceAsync(SourceCodeKind.Script, + public Task TestNotAfterGlobalVariableDeclaration_Interactive() + => VerifyAbsenceAsync(SourceCodeKind.Script, """ int i = 0; $$ """); - } [Fact] - public async Task TestNotInUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInUsingAlias() + => VerifyAbsenceAsync( @"using Goo = $$"); - } [Fact] - public async Task TestNotInGlobalUsingAlias() - { - await VerifyAbsenceAsync( + public Task TestNotInGlobalUsingAlias() + => VerifyAbsenceAsync( @"global using Goo = $$"); - } [Fact] - public async Task TestEmptyStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestEmptyStatement() + => VerifyKeywordAsync(AddInsideMethod( @"$$")); - } [Fact] - public async Task TestBeforeStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestBeforeStatement() + => VerifyKeywordAsync(AddInsideMethod( """ $$ return true; """)); - } [Fact] - public async Task TestAfterStatement() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterStatement() + => VerifyKeywordAsync(AddInsideMethod( """ return true; $$ """)); - } [Fact] - public async Task TestAfterBlock() - { - await VerifyKeywordAsync(AddInsideMethod( + public Task TestAfterBlock() + => VerifyKeywordAsync(AddInsideMethod( """ if (true) { } $$ """)); - } [Fact] - public async Task TestNotAfterYield() - { - await VerifyAbsenceAsync(AddInsideMethod( + public Task TestNotAfterYield() + => VerifyAbsenceAsync(AddInsideMethod( @"yield $$")); - } [Fact] - public async Task TestNotInClass() - { - await VerifyAbsenceAsync(""" + public Task TestNotInClass() + => VerifyAbsenceAsync(""" class C { $$ } """); - } } diff --git a/src/EditorFeatures/Core/BackgroundWorkIndicator/IBackgroundWorkIndicatorContext.cs b/src/EditorFeatures/Core/BackgroundWorkIndicator/IBackgroundWorkIndicatorContext.cs index f3116913287cd..72e7ba939d781 100644 --- a/src/EditorFeatures/Core/BackgroundWorkIndicator/IBackgroundWorkIndicatorContext.cs +++ b/src/EditorFeatures/Core/BackgroundWorkIndicator/IBackgroundWorkIndicatorContext.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System; -using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.Utilities; diff --git a/src/EditorFeatures/Core/BackgroundWorkIndicator/WpfBackgroundWorkIndicatorFactory.cs b/src/EditorFeatures/Core/BackgroundWorkIndicator/WpfBackgroundWorkIndicatorFactory.cs index 341f5cc8ed18f..1f0652ba46201 100644 --- a/src/EditorFeatures/Core/BackgroundWorkIndicator/WpfBackgroundWorkIndicatorFactory.cs +++ b/src/EditorFeatures/Core/BackgroundWorkIndicator/WpfBackgroundWorkIndicatorFactory.cs @@ -7,7 +7,6 @@ using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; -using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; diff --git a/src/EditorFeatures/Core/Classification/CopyPasteAndPrintingClassificationBufferTaggerProvider.Tagger.cs b/src/EditorFeatures/Core/Classification/CopyPasteAndPrintingClassificationBufferTaggerProvider.Tagger.cs index b803f0707b15b..fbc8cdd2d6372 100644 --- a/src/EditorFeatures/Core/Classification/CopyPasteAndPrintingClassificationBufferTaggerProvider.Tagger.cs +++ b/src/EditorFeatures/Core/Classification/CopyPasteAndPrintingClassificationBufferTaggerProvider.Tagger.cs @@ -19,7 +19,6 @@ using Microsoft.CodeAnalysis.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Classification; diff --git a/src/EditorFeatures/Core/CodeDefinitionWindow/DefinitionContextTracker.cs b/src/EditorFeatures/Core/CodeDefinitionWindow/DefinitionContextTracker.cs index 21ee6222e5e08..11f07e2da927a 100644 --- a/src/EditorFeatures/Core/CodeDefinitionWindow/DefinitionContextTracker.cs +++ b/src/EditorFeatures/Core/CodeDefinitionWindow/DefinitionContextTracker.cs @@ -26,7 +26,6 @@ using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeDefinitionWindow; diff --git a/src/EditorFeatures/Core/Copilot/CopilotTaggerProvider.cs b/src/EditorFeatures/Core/Copilot/CopilotTaggerProvider.cs index a1105e718c04c..06ea0001f65e8 100644 --- a/src/EditorFeatures/Core/Copilot/CopilotTaggerProvider.cs +++ b/src/EditorFeatures/Core/Copilot/CopilotTaggerProvider.cs @@ -6,6 +6,7 @@ using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Copilot; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; diff --git a/src/EditorFeatures/Core/Copilot/CopilotWpfTextCreationListener.cs b/src/EditorFeatures/Core/Copilot/CopilotWpfTextCreationListener.cs index 8bdb1bfaf16db..b99cc2e15032d 100644 --- a/src/EditorFeatures/Core/Copilot/CopilotWpfTextCreationListener.cs +++ b/src/EditorFeatures/Core/Copilot/CopilotWpfTextCreationListener.cs @@ -3,8 +3,6 @@ // See the LICENSE file in the project root for more information. using System; -using System.Collections.Generic; -using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Linq; using System.Threading; diff --git a/src/EditorFeatures/Core/DocumentationComments/CopilotGenerateDocumentationCommentProvider.cs b/src/EditorFeatures/Core/DocumentationComments/CopilotGenerateDocumentationCommentProvider.cs index 29ccf52e6a832..23700994fd238 100644 --- a/src/EditorFeatures/Core/DocumentationComments/CopilotGenerateDocumentationCommentProvider.cs +++ b/src/EditorFeatures/Core/DocumentationComments/CopilotGenerateDocumentationCommentProvider.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System; -using System.CodeDom.Compiler; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; diff --git a/src/EditorFeatures/Core/DocumentationComments/DocumentationCommentSuggestion.cs b/src/EditorFeatures/Core/DocumentationComments/DocumentationCommentSuggestion.cs index 752d4e935c727..3289df5905ec2 100644 --- a/src/EditorFeatures/Core/DocumentationComments/DocumentationCommentSuggestion.cs +++ b/src/EditorFeatures/Core/DocumentationComments/DocumentationCommentSuggestion.cs @@ -4,12 +4,10 @@ using System; using System.ComponentModel; -using System.Drawing; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Copilot; using Microsoft.CodeAnalysis.Internal.Log; -using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Language.Proposals; using Microsoft.VisualStudio.Language.Suggestions; using Microsoft.VisualStudio.Text; @@ -98,7 +96,7 @@ private async Task StartSuggestionSessionAsync(CancellationToken cancellat _suggestionSession = await RunWithEnqueueActionAsync( "StartWork", async () => await SuggestionManager.TryDisplaySuggestionAsync(this, cancellationToken).ConfigureAwait(false), - cancellationToken).ConfigureAwait(false); + cancellationToken).ConfigureAwait(false); if (_suggestionSession is null) { diff --git a/src/EditorFeatures/Core/EditAndContinue/EditAndContinueLanguageService.cs b/src/EditorFeatures/Core/EditAndContinue/EditAndContinueLanguageService.cs index 8ba83cfca7f08..81115532f4766 100644 --- a/src/EditorFeatures/Core/EditAndContinue/EditAndContinueLanguageService.cs +++ b/src/EditorFeatures/Core/EditAndContinue/EditAndContinueLanguageService.cs @@ -6,7 +6,6 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; -using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -385,8 +384,10 @@ public async ValueTask GetUpdatesAsync(ImmutableArray changes); + ITextSnapshot ApplyChanges(IEnumerable changes); } diff --git a/src/EditorFeatures/Core/EditorConfigSettings/Aggregator/SettingsAggregator.cs b/src/EditorFeatures/Core/EditorConfigSettings/Aggregator/SettingsAggregator.cs index a3e0f455df219..0d9689e30347a 100644 --- a/src/EditorFeatures/Core/EditorConfigSettings/Aggregator/SettingsAggregator.cs +++ b/src/EditorFeatures/Core/EditorConfigSettings/Aggregator/SettingsAggregator.cs @@ -6,6 +6,7 @@ using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; diff --git a/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/Analyzer/AnalyzerSettingsProviderFactory.cs b/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/Analyzer/AnalyzerSettingsProviderFactory.cs index 49de006cc6b58..fbc9ae4ea8686 100644 --- a/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/Analyzer/AnalyzerSettingsProviderFactory.cs +++ b/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/Analyzer/AnalyzerSettingsProviderFactory.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater; using Microsoft.CodeAnalysis.Options; diff --git a/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/Analyzer/AnalyzerSettingsWorkspaceServiceFactory.cs b/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/Analyzer/AnalyzerSettingsWorkspaceServiceFactory.cs index 095d1a9d5624a..8252e0ed64113 100644 --- a/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/Analyzer/AnalyzerSettingsWorkspaceServiceFactory.cs +++ b/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/Analyzer/AnalyzerSettingsWorkspaceServiceFactory.cs @@ -4,7 +4,6 @@ using System; using System.Composition; -using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; diff --git a/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/CombinedOptionsProviderFactory.cs b/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/CombinedOptionsProviderFactory.cs index d65c5b57a97d4..9749b62a6c92a 100644 --- a/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/CombinedOptionsProviderFactory.cs +++ b/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/CombinedOptionsProviderFactory.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Collections; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider; diff --git a/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/CombinedProvider.cs b/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/CombinedProvider.cs index b2e46867238dd..05b54170199f1 100644 --- a/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/CombinedProvider.cs +++ b/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/CombinedProvider.cs @@ -3,7 +3,9 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using System.Linq; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider; @@ -24,13 +26,11 @@ public async Task GetChangedEditorConfigAsync(SourceText sourceText) public ImmutableArray GetCurrentDataSnapshot() { - var snapShot = ImmutableArray.Empty; + using var _ = ArrayBuilder.GetInstance(out var builder); foreach (var provider in _providers) - { - snapShot = snapShot.Concat(provider.GetCurrentDataSnapshot()); - } + builder.AddRange(provider.GetCurrentDataSnapshot()); - return snapShot; + return builder.ToImmutableAndClear(); } public void RegisterViewModel(ISettingsEditorViewModel model) diff --git a/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/NamingStyles/NamingStyleSettingsProvider.cs b/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/NamingStyles/NamingStyleSettingsProvider.cs index bee8b3dd67249..f12d8777c89e4 100644 --- a/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/NamingStyles/NamingStyleSettingsProvider.cs +++ b/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/NamingStyles/NamingStyleSettingsProvider.cs @@ -3,8 +3,8 @@ // See the LICENSE file in the project root for more information. using System; -using System.Linq; using System.Collections.Immutable; +using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; diff --git a/src/EditorFeatures/Core/EncapsulateField/AbstractEncapsulateFieldCommandHandler.cs b/src/EditorFeatures/Core/EncapsulateField/AbstractEncapsulateFieldCommandHandler.cs index 63fac5bc1056b..e0279ccbd2c7b 100644 --- a/src/EditorFeatures/Core/EncapsulateField/AbstractEncapsulateFieldCommandHandler.cs +++ b/src/EditorFeatures/Core/EncapsulateField/AbstractEncapsulateFieldCommandHandler.cs @@ -109,13 +109,13 @@ private async Task ApplyChangeAsync( { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); finalSolution = previewService.PreviewChanges( - string.Format(EditorFeaturesResources.Preview_Changes_0, EditorFeaturesResources.Encapsulate_Field), + string.Format(EditorFeaturesResources.Preview_Changes_0, EditorFeaturesResources.Encapsulate_Field), "vs.csharp.refactoring.preview", - EditorFeaturesResources.Encapsulate_Field_colon, - result.Name, - result.Glyph, - finalSolution, - solution); + EditorFeaturesResources.Encapsulate_Field_colon, + result.Name, + result.Glyph, + finalSolution, + solution); } if (finalSolution == null) diff --git a/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/AbstactVSTypeScriptLspServiceFactory.cs b/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/AbstactVSTypeScriptLspServiceFactory.cs index 1db0de0e33e8e..c53a8465281a5 100644 --- a/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/AbstactVSTypeScriptLspServiceFactory.cs +++ b/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/AbstactVSTypeScriptLspServiceFactory.cs @@ -5,6 +5,7 @@ using Microsoft.CodeAnalysis.LanguageServer; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; + internal abstract class AbstractVSTypeScriptRequestHandlerFactory : ILspServiceFactory { public ILspService CreateILspService(LspServices lspServices, WellKnownLspServerKinds serverKind) diff --git a/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/VSTypeScriptAsynchronousTaggerProvider.cs b/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/VSTypeScriptAsynchronousTaggerProvider.cs index 29de0595ff23e..50b58a3d580cb 100644 --- a/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/VSTypeScriptAsynchronousTaggerProvider.cs +++ b/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/VSTypeScriptAsynchronousTaggerProvider.cs @@ -6,7 +6,7 @@ using System.Collections.Generic; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Shared.Collections; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; diff --git a/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptBlockStructureService.cs b/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptBlockStructureService.cs index 47d8f9766c3ef..ea20a98981274 100644 --- a/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptBlockStructureService.cs +++ b/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptBlockStructureService.cs @@ -6,9 +6,9 @@ using System.Composition; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Structure; -using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript; diff --git a/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptFindUsagesContext.cs b/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptFindUsagesContext.cs index 9815fe3f04dfc..eadf81c78509f 100644 --- a/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptFindUsagesContext.cs +++ b/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptFindUsagesContext.cs @@ -4,8 +4,8 @@ using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; +using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript; diff --git a/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptFindUsagesService.cs b/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptFindUsagesService.cs index 736e7ade3a2ba..d71ef18593bb2 100644 --- a/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptFindUsagesService.cs +++ b/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptFindUsagesService.cs @@ -6,13 +6,13 @@ using System.Composition; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; -using Microsoft.CodeAnalysis.Classification; -using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript; diff --git a/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptFormattingInteractionService.cs b/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptFormattingInteractionService.cs index 37e98496343c5..bfe542bc523e5 100644 --- a/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptFormattingInteractionService.cs +++ b/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptFormattingInteractionService.cs @@ -7,8 +7,8 @@ using System.Composition; using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; +using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; diff --git a/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptNavigationBarItemService.cs b/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptNavigationBarItemService.cs index 5ec8bc9f7de2d..4bb90d368ca3e 100644 --- a/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptNavigationBarItemService.cs +++ b/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptNavigationBarItemService.cs @@ -15,7 +15,6 @@ using Microsoft.CodeAnalysis.Navigation; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript; diff --git a/src/EditorFeatures/Core/GoOrFind/AbstractGoOrFindNavigationService.cs b/src/EditorFeatures/Core/GoOrFind/AbstractGoOrFindNavigationService.cs index 660e2aa630ce3..8f6db66fbc773 100644 --- a/src/EditorFeatures/Core/GoOrFind/AbstractGoOrFindNavigationService.cs +++ b/src/EditorFeatures/Core/GoOrFind/AbstractGoOrFindNavigationService.cs @@ -18,7 +18,6 @@ using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; -using Microsoft.CodeAnalysis.Threading; using Microsoft.VisualStudio.Threading; namespace Microsoft.CodeAnalysis.GoOrFind; diff --git a/src/EditorFeatures/Core/GoOrFind/GoToImplementation/GoToImplementationCommandHandler.cs b/src/EditorFeatures/Core/GoOrFind/GoToImplementation/GoToImplementationCommandHandler.cs index baaaa8fa487dd..e6b6690fcdd55 100644 --- a/src/EditorFeatures/Core/GoOrFind/GoToImplementation/GoToImplementationCommandHandler.cs +++ b/src/EditorFeatures/Core/GoOrFind/GoToImplementation/GoToImplementationCommandHandler.cs @@ -7,7 +7,6 @@ using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Commanding.Commands; using Microsoft.CodeAnalysis.GoOrFind; -using Microsoft.CodeAnalysis.GoToDefinition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Utilities; diff --git a/src/EditorFeatures/Core/IInlineRenameSession.cs b/src/EditorFeatures/Core/IInlineRenameSession.cs index a7e52195f24dd..961e7dad4c7ef 100644 --- a/src/EditorFeatures/Core/IInlineRenameSession.cs +++ b/src/EditorFeatures/Core/IInlineRenameSession.cs @@ -54,5 +54,5 @@ internal interface IInlineRenameSession /// /// It will only be async when InlineRenameUIOptionsStorage.CommitRenameAsynchronously is set to true. /// - Task CommitAsync(bool previewChanges, IUIThreadOperationContext editorOperationContext = null); + Task CommitAsync(bool previewChanges, IUIThreadOperationContext editorOperationContext); } diff --git a/src/EditorFeatures/Core/InlineDiagnostics/AbstractDiagnosticsTaggerProvider.cs b/src/EditorFeatures/Core/InlineDiagnostics/AbstractDiagnosticsTaggerProvider.cs index 3aaacb2c06c51..51007f4360ebb 100644 --- a/src/EditorFeatures/Core/InlineDiagnostics/AbstractDiagnosticsTaggerProvider.cs +++ b/src/EditorFeatures/Core/InlineDiagnostics/AbstractDiagnosticsTaggerProvider.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Collections; diff --git a/src/EditorFeatures/Core/InlineHints/InlineHintsDataTaggerProvider.cs b/src/EditorFeatures/Core/InlineHints/InlineHintsDataTaggerProvider.cs index b104436e84086..96fe85c769e9e 100644 --- a/src/EditorFeatures/Core/InlineHints/InlineHintsDataTaggerProvider.cs +++ b/src/EditorFeatures/Core/InlineHints/InlineHintsDataTaggerProvider.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; diff --git a/src/EditorFeatures/Core/InlineRename/AbstractEditorInlineRenameService.cs b/src/EditorFeatures/Core/InlineRename/AbstractEditorInlineRenameService.cs index 12a77bc565221..a8469d2ea920a 100644 --- a/src/EditorFeatures/Core/InlineRename/AbstractEditorInlineRenameService.cs +++ b/src/EditorFeatures/Core/InlineRename/AbstractEditorInlineRenameService.cs @@ -24,7 +24,7 @@ protected AbstractEditorInlineRenameService(IEnumerable public async Task GetRenameInfoAsync(Document document, int position, CancellationToken cancellationToken) { - var symbolicInfo = await SymbolicRenameInfo.GetRenameInfoAsync(document, position, cancellationToken).ConfigureAwait(false); + var symbolicInfo = await SymbolicRenameInfo.GetRenameInfoAsync(document, position, includeSourceGenerated: false, cancellationToken).ConfigureAwait(false); if (symbolicInfo.LocalizedErrorMessage != null) return new FailureInlineRenameInfo(symbolicInfo.LocalizedErrorMessage); diff --git a/src/EditorFeatures/Core/InlineRename/AbstractInlineRenameUndoManager.cs b/src/EditorFeatures/Core/InlineRename/AbstractInlineRenameUndoManager.cs index 6993ca0487d72..45e07d043b66f 100644 --- a/src/EditorFeatures/Core/InlineRename/AbstractInlineRenameUndoManager.cs +++ b/src/EditorFeatures/Core/InlineRename/AbstractInlineRenameUndoManager.cs @@ -7,9 +7,7 @@ using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Editor.InlineRename; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; -using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; diff --git a/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler.cs b/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler.cs index 923c015b056ff..4972997778414 100644 --- a/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler.cs +++ b/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler.cs @@ -6,22 +6,18 @@ using System.Linq; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; -using Microsoft.CodeAnalysis.InlineRename; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding; using Microsoft.VisualStudio.Utilities; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename; internal abstract partial class AbstractRenameCommandHandler( IThreadingContext threadingContext, InlineRenameService renameService, - IGlobalOptionService globalOptionService, IAsynchronousOperationListener listener) { public string DisplayName => EditorFeaturesResources.Rename; @@ -76,7 +72,7 @@ private void HandlePossibleTypingCommand(TArgs args, Action nextHandler, } else if (renameService.ActiveSession.IsInOpenTextBuffer(singleSpan.Start)) { - HandleTypingOutsideEditableSpan(args, operationContext); + CancelRenameSession(); nextHandler(); } else @@ -86,40 +82,9 @@ private void HandlePossibleTypingCommand(TArgs args, Action nextHandler, } } - private void HandleTypingOutsideEditableSpan(EditorCommandArgs args, IUIThreadOperationContext operationContext) - => CommitIfSynchronousOrCancelIfAsynchronous(args, operationContext, placeCaretAtTheEndOfIdentifier: true); - - private void CommitIfActive(EditorCommandArgs args, IUIThreadOperationContext operationContext, bool placeCaretAtTheEndOfIdentifier = true) - { - if (renameService.ActiveSession != null) - { - var selection = args.TextView.Selection.VirtualSelectedSpans.First(); - Commit(operationContext); - if (placeCaretAtTheEndOfIdentifier) - { - var translatedSelection = selection.TranslateTo(args.TextView.TextBuffer.CurrentSnapshot); - args.TextView.Selection.Select(translatedSelection.Start, translatedSelection.End); - args.TextView.Caret.MoveTo(translatedSelection.End); - } - } - } - - /// - /// Commit() will be called if rename commit is sync. Editor command would be executed after the rename operation complete and it is our legacy behavior. - /// Cancel() will be called if rename is async. It also matches the other editor's behavior (like VS LSP and VSCode). - /// - private void CommitIfSynchronousOrCancelIfAsynchronous(EditorCommandArgs args, IUIThreadOperationContext operationContext, bool placeCaretAtTheEndOfIdentifier) - { - if (globalOptionService.ShouldCommitAsynchronously()) - renameService.ActiveSession?.Cancel(); - else - CommitIfActive(args, operationContext, placeCaretAtTheEndOfIdentifier); - } - - private void Commit(IUIThreadOperationContext operationContext) + private void CancelRenameSession() { - RoslynDebug.AssertNotNull(renameService.ActiveSession); - renameService.ActiveSession.Commit(previewChanges: false, operationContext); + renameService.ActiveSession?.Cancel(); } private bool IsRenameCommitInProgress() diff --git a/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_MoveSelectedLinesHandler.cs b/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_MoveSelectedLinesHandler.cs index 48dda4380552b..e19ad16b8bf2c 100644 --- a/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_MoveSelectedLinesHandler.cs +++ b/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_MoveSelectedLinesHandler.cs @@ -15,21 +15,21 @@ public CommandState GetCommandState(MoveSelectedLinesUpCommandArgs args) => CommandState.Unspecified; public bool ExecuteCommand(MoveSelectedLinesUpCommandArgs args, CommandExecutionContext context) - => HandleMoveSelectLinesUpOrDownCommand(args, context); + => HandleMoveSelectLinesUpOrDownCommand(); public CommandState GetCommandState(MoveSelectedLinesDownCommandArgs args) => CommandState.Unspecified; public bool ExecuteCommand(MoveSelectedLinesDownCommandArgs args, CommandExecutionContext context) - => HandleMoveSelectLinesUpOrDownCommand(args, context); + => HandleMoveSelectLinesUpOrDownCommand(); - private bool HandleMoveSelectLinesUpOrDownCommand(EditorCommandArgs args, CommandExecutionContext context) + private bool HandleMoveSelectLinesUpOrDownCommand() { // When rename commit is in progress, swallow the command so it won't change the workspace if (IsRenameCommitInProgress()) return true; - CommitIfSynchronousOrCancelIfAsynchronous(args, context.OperationContext, placeCaretAtTheEndOfIdentifier: true); + CancelRenameSession(); return false; } } diff --git a/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_OpenLineAboveHandler.cs b/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_OpenLineAboveHandler.cs index e547a8cfe0a8e..91a28352839e6 100644 --- a/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_OpenLineAboveHandler.cs +++ b/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_OpenLineAboveHandler.cs @@ -18,7 +18,7 @@ public void ExecuteCommand(OpenLineAboveCommandArgs args, Action nextHandler, Co HandlePossibleTypingCommand(args, nextHandler, context.OperationContext, (activeSession, operationContext, span) => { // Caret would be moved to the new line when editor command is handled, so we don't need to move it. - CommitIfSynchronousOrCancelIfAsynchronous(args, operationContext, placeCaretAtTheEndOfIdentifier: false); + CancelRenameSession(); nextHandler(); }); } diff --git a/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_OpenLineBelowHandler.cs b/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_OpenLineBelowHandler.cs index 1682fd8673d75..c3884e7d41a1d 100644 --- a/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_OpenLineBelowHandler.cs +++ b/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_OpenLineBelowHandler.cs @@ -18,7 +18,7 @@ public void ExecuteCommand(OpenLineBelowCommandArgs args, Action nextHandler, Co HandlePossibleTypingCommand(args, nextHandler, context.OperationContext, (activeSession, operationContext, span) => { // Caret would be moved to the new line when editor command is handled, so we don't need to move it. - CommitIfSynchronousOrCancelIfAsynchronous(args, operationContext, placeCaretAtTheEndOfIdentifier: false); + CancelRenameSession(); nextHandler(); }); } diff --git a/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_RefactoringWithCommandHandler.cs b/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_RefactoringWithCommandHandler.cs index c578b382308c2..6f5b00bbcdede 100644 --- a/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_RefactoringWithCommandHandler.cs +++ b/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_RefactoringWithCommandHandler.cs @@ -18,32 +18,32 @@ public CommandState GetCommandState(ReorderParametersCommandArgs args) => CommandState.Unspecified; public bool ExecuteCommand(ReorderParametersCommandArgs args, CommandExecutionContext context) - => HandleRefactoringCommands(args, context); + => HandleRefactoringCommands(); public CommandState GetCommandState(RemoveParametersCommandArgs args) => CommandState.Unspecified; public bool ExecuteCommand(RemoveParametersCommandArgs args, CommandExecutionContext context) - => HandleRefactoringCommands(args, context); + => HandleRefactoringCommands(); public CommandState GetCommandState(ExtractInterfaceCommandArgs args) => CommandState.Unspecified; public bool ExecuteCommand(ExtractInterfaceCommandArgs args, CommandExecutionContext context) - => HandleRefactoringCommands(args, context); + => HandleRefactoringCommands(); public CommandState GetCommandState(EncapsulateFieldCommandArgs args) => CommandState.Unspecified; public bool ExecuteCommand(EncapsulateFieldCommandArgs args, CommandExecutionContext context) - => HandleRefactoringCommands(args, context); + => HandleRefactoringCommands(); - private bool HandleRefactoringCommands(EditorCommandArgs args, CommandExecutionContext context) + private bool HandleRefactoringCommands() { if (IsRenameCommitInProgress()) return true; - CommitIfSynchronousOrCancelIfAsynchronous(args, context.OperationContext, placeCaretAtTheEndOfIdentifier: true); + CancelRenameSession(); return false; } } diff --git a/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_RenameHandler.cs b/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_RenameHandler.cs index fbadb6588e48f..acd8908e0351d 100644 --- a/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_RenameHandler.cs +++ b/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_RenameHandler.cs @@ -44,11 +44,11 @@ public bool ExecuteCommand(RenameCommandArgs args, CommandExecutionContext conte } var token = listener.BeginAsyncOperation(nameof(ExecuteCommand)); - _ = ExecuteCommandAsync(args, context.OperationContext).CompletesAsyncOperation(token); + _ = ExecuteCommandAsync(args).CompletesAsyncOperation(token); return true; } - private async Task ExecuteCommandAsync(RenameCommandArgs args, IUIThreadOperationContext editorOperationContext) + private async Task ExecuteCommandAsync(RenameCommandArgs args) { threadingContext.ThrowIfNotOnUIThread(); @@ -81,9 +81,8 @@ private async Task ExecuteCommandAsync(RenameCommandArgs args, IUIThreadOperatio } else { - // Otherwise, commit or cancel the existing session and start a new one. - // Set placeCaretAtTheEndOfIdentifier to false because a new rename session will be created based on caret's location. - CommitIfSynchronousOrCancelIfAsynchronous(args, editorOperationContext, placeCaretAtTheEndOfIdentifier: false); + // Otherwise, cancel the existing session and start a new one. + CancelRenameSession(); } } diff --git a/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_ReturnHandler.cs b/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_ReturnHandler.cs index cd51267b3d521..5996b90a01f4f 100644 --- a/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_ReturnHandler.cs +++ b/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_ReturnHandler.cs @@ -2,9 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Runtime.Remoting.Contexts; +using Microsoft.CodeAnalysis.ErrorReporting; +using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; +using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename; @@ -27,7 +31,11 @@ public bool ExecuteCommand(ReturnKeyCommandArgs args, CommandExecutionContext co protected virtual void CommitAndSetFocus(InlineRenameSession activeSession, ITextView textView, IUIThreadOperationContext operationContext) { - activeSession.InitiateCommit(operationContext); + var token = listener.BeginAsyncOperation(nameof(ExecuteCommand)); + + // CommitAsync will display UI to the user while this asynchronous work is being done. + activeSession.CommitAsync(previewChanges: false, operationContext) + .ReportNonFatalErrorAsync().CompletesAsyncOperation(token); SetFocusToTextView(textView); } } diff --git a/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_SaveHandler.cs b/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_SaveHandler.cs index 0ea62864e63a3..53685bef61a13 100644 --- a/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_SaveHandler.cs +++ b/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_SaveHandler.cs @@ -17,12 +17,6 @@ public bool ExecuteCommand(SaveCommandArgs args, CommandExecutionContext context { // If commit is async, just let editor save the document. // If call async commit here, it could finish after the save command so the workspace would still be dirty. - if (renameService.ActiveSession != null && !globalOptionService.ShouldCommitAsynchronously()) - { - Commit(context.OperationContext); - SetFocusToTextView(args.TextView); - } - return false; } } diff --git a/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_WordDeleteHandler.cs b/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_WordDeleteHandler.cs index c04cfa53a2e09..4572997c93e17 100644 --- a/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_WordDeleteHandler.cs +++ b/src/EditorFeatures/Core/InlineRename/CommandHandlers/AbstractRenameCommandHandler_WordDeleteHandler.cs @@ -23,12 +23,12 @@ public CommandState GetCommandState(WordDeleteToEndCommandArgs args) => GetCommandState(); public bool ExecuteCommand(WordDeleteToStartCommandArgs args, CommandExecutionContext context) - => HandleWordDeleteCommand(args, context, args.TextView, deleteToStart: true); + => HandleWordDeleteCommand(args, args.TextView, deleteToStart: true); public bool ExecuteCommand(WordDeleteToEndCommandArgs args, CommandExecutionContext context) - => HandleWordDeleteCommand(args, context, args.TextView, deleteToStart: false); + => HandleWordDeleteCommand(args, args.TextView, deleteToStart: false); - private bool HandleWordDeleteCommand(EditorCommandArgs args, CommandExecutionContext context, ITextView view, bool deleteToStart) + private bool HandleWordDeleteCommand(EditorCommandArgs args, ITextView view, bool deleteToStart) { var subjectBuffer = args.SubjectBuffer; if (renameService.ActiveSession == null) @@ -73,7 +73,7 @@ private bool HandleWordDeleteCommand(EditorCommandArgs args, CommandExecutionCon } else { - CommitIfSynchronousOrCancelIfAsynchronous(args, context.OperationContext, placeCaretAtTheEndOfIdentifier: true); + CancelRenameSession(); } } diff --git a/src/EditorFeatures/Core/InlineRename/CommandHandlers/RenameCommandHandler.cs b/src/EditorFeatures/Core/InlineRename/CommandHandlers/RenameCommandHandler.cs index 82b07c4211399..e77c946a11b15 100644 --- a/src/EditorFeatures/Core/InlineRename/CommandHandlers/RenameCommandHandler.cs +++ b/src/EditorFeatures/Core/InlineRename/CommandHandlers/RenameCommandHandler.cs @@ -6,15 +6,15 @@ using System.ComponentModel.Composition; using System.Linq; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; +using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.Notification; +using Microsoft.CodeAnalysis.Options; +using Microsoft.CodeAnalysis.Shared.TestHooks; +using Microsoft.CodeAnalysis.Telemetry; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; -using Microsoft.CodeAnalysis.Notification; -using Microsoft.CodeAnalysis.ErrorReporting; -using Microsoft.CodeAnalysis.Telemetry; -using Microsoft.CodeAnalysis.Shared.TestHooks; -using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename; @@ -34,9 +34,8 @@ namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename; internal sealed partial class RenameCommandHandler( IThreadingContext threadingContext, InlineRenameService renameService, - IGlobalOptionService globalOptionService, IAsynchronousOperationListenerProvider asynchronousOperationListenerProvider) - : AbstractRenameCommandHandler(threadingContext, renameService, globalOptionService, asynchronousOperationListenerProvider.GetListener(FeatureAttribute.Rename)) + : AbstractRenameCommandHandler(threadingContext, renameService, asynchronousOperationListenerProvider.GetListener(FeatureAttribute.Rename)) { protected override void SetFocusToTextView(ITextView textView) { diff --git a/src/EditorFeatures/Core/InlineRename/InlineRenameService.cs b/src/EditorFeatures/Core/InlineRename/InlineRenameService.cs index 112142313e2ae..0b07ccf887b54 100644 --- a/src/EditorFeatures/Core/InlineRename/InlineRenameService.cs +++ b/src/EditorFeatures/Core/InlineRename/InlineRenameService.cs @@ -29,20 +29,16 @@ namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename; [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] internal sealed class InlineRenameService( IThreadingContext threadingContext, - IUIThreadOperationExecutor uiThreadOperationExecutor, ITextBufferAssociatedViewService textBufferAssociatedViewService, ITextBufferFactoryService textBufferFactoryService, ITextBufferCloneService textBufferCloneService, IFeatureServiceFactory featureServiceFactory, IGlobalOptionService globalOptions, - [ImportMany] IEnumerable refactorNotifyServices, IAsynchronousOperationListenerProvider listenerProvider) : IInlineRenameService { private readonly IThreadingContext _threadingContext = threadingContext; - private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor = uiThreadOperationExecutor; private readonly ITextBufferAssociatedViewService _textBufferAssociatedViewService = textBufferAssociatedViewService; private readonly IAsynchronousOperationListener _asyncListener = listenerProvider.GetListener(FeatureAttribute.Rename); - private readonly IEnumerable _refactorNotifyServices = refactorNotifyServices; private readonly ITextBufferFactoryService _textBufferFactoryService = textBufferFactoryService; private readonly ITextBufferCloneService _textBufferCloneService = textBufferCloneService; private readonly IFeatureServiceFactory _featureServiceFactory = featureServiceFactory; @@ -109,12 +105,10 @@ public async Task StartInlineSessionAsync( renameInfo, options, previewChanges, - _uiThreadOperationExecutor, _textBufferAssociatedViewService, _textBufferFactoryService, _textBufferCloneService, _featureServiceFactory, - _refactorNotifyServices, _asyncListener); return new InlineRenameSessionInfo(ActiveSession); diff --git a/src/EditorFeatures/Core/InlineRename/InlineRenameSession.OpenTextBufferManager.cs b/src/EditorFeatures/Core/InlineRename/InlineRenameSession.OpenTextBufferManager.cs index 63bfdce6c2549..9a7ddc572ed2e 100644 --- a/src/EditorFeatures/Core/InlineRename/InlineRenameSession.OpenTextBufferManager.cs +++ b/src/EditorFeatures/Core/InlineRename/InlineRenameSession.OpenTextBufferManager.cs @@ -231,7 +231,7 @@ private void OnTextBufferChanged(object sender, TextContentChangedEventArgs args var spansTouchedInEdit = new NormalizedSpanCollection(args.Changes.Select(c => c.NewSpan)); var intersectionSpans = NormalizedSpanCollection.Intersection(trackingSpansAfterEdit, spansTouchedInEdit); - if (intersectionSpans.Count == 0) + if (intersectionSpans is not ([var firstSpan, ..] and [.., var lastSpan])) { // In Razor we sometimes get formatting changes during inline rename that // do not intersect with any of our spans. Ideally this shouldn't happen at @@ -243,7 +243,7 @@ private void OnTextBufferChanged(object sender, TextContentChangedEventArgs args // spans, but they should still all map to a single tracked rename span (e.g. // renaming "two" to "one two three" may be interpreted as two distinct // additions of "one" and "three"). - var boundingIntersectionSpan = Span.FromBounds(intersectionSpans.First().Start, intersectionSpans.Last().End); + var boundingIntersectionSpan = Span.FromBounds(firstSpan.Start, lastSpan.End); var trackingSpansTouched = GetEditableSpansForSnapshot(args.After).Where(ss => ss.IntersectsWith(boundingIntersectionSpan)); Debug.Assert(trackingSpansTouched.Count() == 1); diff --git a/src/EditorFeatures/Core/InlineRename/InlineRenameSession.cs b/src/EditorFeatures/Core/InlineRename/InlineRenameSession.cs index 8c1cdffb5808a..ff3450ab70def 100644 --- a/src/EditorFeatures/Core/InlineRename/InlineRenameSession.cs +++ b/src/EditorFeatures/Core/InlineRename/InlineRenameSession.cs @@ -19,7 +19,6 @@ using Microsoft.CodeAnalysis.Editor.Undo; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; -using Microsoft.CodeAnalysis.InlineRename; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Remote; @@ -37,15 +36,12 @@ namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename; internal sealed partial class InlineRenameSession : IInlineRenameSession, IFeatureController { - private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; - private readonly ITextBufferAssociatedViewService _textBufferAssociatedViewService; private readonly ITextBufferFactoryService _textBufferFactoryService; private readonly ITextBufferCloneService _textBufferCloneService; private readonly IFeatureService _featureService; private readonly IFeatureDisableToken _completionDisabledToken; - private readonly IEnumerable _refactorNotifyServices; private readonly IAsynchronousOperationListener _asyncListener; private readonly Solution _baseSolution; private readonly ITextView _triggerView; @@ -57,7 +53,6 @@ internal sealed partial class InlineRenameSession : IInlineRenameSession, IFeatu private bool _dismissed; private bool _isApplyingEdit; - private string _replacementText; private readonly Dictionary _openTextBuffers = []; /// @@ -76,13 +71,10 @@ internal sealed partial class InlineRenameSession : IInlineRenameSession, IFeatu /// public string ReplacementText { - get - { - return _replacementText; - } + get; private set { - _replacementText = value; + field = value; ReplacementTextChanged?.Invoke(this, EventArgs.Empty); } } @@ -141,12 +133,10 @@ public InlineRenameSession( IInlineRenameInfo renameInfo, SymbolRenameOptions options, bool previewChanges, - IUIThreadOperationExecutor uiThreadOperationExecutor, ITextBufferAssociatedViewService textBufferAssociatedViewService, ITextBufferFactoryService textBufferFactoryService, ITextBufferCloneService textBufferCloneService, IFeatureServiceFactory featureServiceFactory, - IEnumerable refactorNotifyServices, IAsynchronousOperationListener asyncListener) { // This should always be touching a symbol since we verified that upon invocation @@ -176,8 +166,6 @@ public InlineRenameSession( _featureService = featureServiceFactory.GlobalFeatureService; _completionDisabledToken = _featureService.Disable(PredefinedEditorFeatureNames.Completion, this); RenameService = renameService; - _uiThreadOperationExecutor = uiThreadOperationExecutor; - _refactorNotifyServices = refactorNotifyServices; _asyncListener = asyncListener; _triggerView = textBufferAssociatedViewService.GetAssociatedTextViews(triggerSpan.Snapshot.TextBuffer).FirstOrDefault(v => v.HasAggregateFocus) ?? textBufferAssociatedViewService.GetAssociatedTextViews(triggerSpan.Snapshot.TextBuffer).First(); @@ -733,54 +721,10 @@ void DismissUIAndRollbackEdits() } /// - /// Caller should pass in the IUIThreadOperationContext if it is called from editor so rename commit operation could set up the its own context correctly. + /// Caller should pass in the IUIThreadOperationContext if it is called from editor so rename commit operation could set up its own context correctly. + /// When the editorOperationContext is not null it will take ownership of the UI thread and try to create a BackgroundWorkIndicator /// - public void Commit(bool previewChanges = false, IUIThreadOperationContext editorOperationContext = null) - => CommitSynchronously(previewChanges, editorOperationContext); - - /// if the rename operation was committed, otherwise - private bool CommitSynchronously(bool previewChanges, IUIThreadOperationContext operationContext = null) - { - // We're going to synchronously block the UI thread here. So we can't use the background work indicator (as - // it needs the UI thread to update itself. This will force us to go through the Threaded-Wait-Dialog path - // which at least will allow the user to cancel the rename if they want. - // - // In the future we should remove this entrypoint and have all callers use CommitAsync instead. - return _threadingContext.JoinableTaskFactory.Run(() => CommitWorkerAsync(previewChanges, canUseBackgroundWorkIndicator: false, operationContext)); - } - - /// - /// Start to commit the rename session. - /// Session might be committed sync or async, depends on the value of InlineRenameUIOptionsStorage.CommitRenameAsynchronously. - /// If it is committed async, method will only kick off the task. - /// - /// - public void InitiateCommit(IUIThreadOperationContext editorOperationContext = null) - { - var token = _asyncListener.BeginAsyncOperation(nameof(InitiateCommit)); - _ = CommitAsync(previewChanges: false, editorOperationContext) - .ReportNonFatalErrorAsync().CompletesAsyncOperation(token); - } - - /// - /// Caller should pass in the IUIThreadOperationContext if it is called from editor so rename commit operation could set up the its own context correctly. - /// - public async Task CommitAsync(bool previewChanges, IUIThreadOperationContext editorOperationContext = null) - { - if (this.RenameService.GlobalOptions.ShouldCommitAsynchronously()) - { - await CommitWorkerAsync(previewChanges, canUseBackgroundWorkIndicator: true, editorOperationContext).ConfigureAwait(false); - } - else - { - CommitSynchronously(previewChanges, editorOperationContext); - } - } - - /// if the rename operation was committed, otherwise - private async Task CommitWorkerAsync(bool previewChanges, bool canUseBackgroundWorkIndicator, IUIThreadOperationContext editorUIOperationContext) + public async Task CommitAsync(bool previewChanges, IUIThreadOperationContext editorOperationContext) { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(); VerifyNotDismissed(); @@ -798,23 +742,20 @@ private async Task CommitWorkerAsync(bool previewChanges, bool canUseBackg this.ReplacementText == _initialRenameText) { Cancel(); - return false; + return; } // Don't dup commit. if (this.IsCommitInProgress) { - return false; + return; } previewChanges = previewChanges || PreviewChanges; - if (editorUIOperationContext is not null) - { - // Prevent Editor's typing responsiveness auto canceling the rename operation. - // InlineRenameSession will call IUIThreadOperationExecutor to sets up our own IUIThreadOperationContext - editorUIOperationContext.TakeOwnership(); - } + // Prevent Editor's typing responsiveness auto canceling the rename operation. + // InlineRenameSession will call IUIThreadOperationExecutor to sets up our own IUIThreadOperationContext + editorOperationContext?.TakeOwnership(); try { @@ -822,40 +763,27 @@ private async Task CommitWorkerAsync(bool previewChanges, bool canUseBackg this.IsCommitInProgress = true; this.CommitStateChange?.Invoke(this, EventArgs.Empty); - if (canUseBackgroundWorkIndicator) - { - // We do not cancel on edit because as part of the rename system we have asynchronous work still - // occurring that itself may be asynchronously editing the buffer (for example, updating reference - // locations with the final renamed text). Ideally though, once we start comitting, we would cancel - // any of that work and then only have the work of rolling back to the original state of the world - // and applying the desired edits ourselves. - var factory = Workspace.Services.GetRequiredService(); - using var context = factory.Create( + // We do not cancel on edit because as part of the rename system we have asynchronous work still + // occurring that itself may be asynchronously editing the buffer (for example, updating reference + // locations with the final renamed text). Ideally though, once we start comitting, we would cancel + // any of that work and then only have the work of rolling back to the original state of the world + // and applying the desired edits ourselves. + var factory = Workspace.Services.GetRequiredService(); + using var context = factory.Create( _triggerView, TriggerSpan, EditorFeaturesResources.Computing_Rename_information, cancelOnEdit: false, cancelOnFocusLost: false); - await CommitCoreAsync(context, previewChanges).ConfigureAwait(true); - } - else - { - using var context = _uiThreadOperationExecutor.BeginExecute( - title: EditorFeaturesResources.Rename, - defaultDescription: EditorFeaturesResources.Computing_Rename_information, - allowCancellation: true, - showProgress: false); - - // .ConfigureAwait(true); so we can return to the UI thread to dispose the operation context. It - // has a non-JTF threading dependency on the main thread. So it can deadlock if you call it on a BG - // thread when in a blocking JTF call. - await CommitCoreAsync(context, previewChanges).ConfigureAwait(true); - } + // .ConfigureAwait(true); so we can return to the UI thread to dispose the operation context. It + // has a non-JTF threading dependency on the main thread. So it can deadlock if you call it on a BG + // thread when in a blocking JTF call. + await CommitCoreAsync(context, previewChanges).ConfigureAwait(true); } catch (OperationCanceledException) { // We've used CA(true) consistently in this method. So we should always be on the UI thread. DismissUIAndRollbackEditsAndEndRenameSession_MustBeCalledOnUIThread( RenameLogMessage.UserActionOutcome.Canceled | RenameLogMessage.UserActionOutcome.Committed, previewChanges); - return false; + return; } finally { @@ -863,7 +791,7 @@ private async Task CommitWorkerAsync(bool previewChanges, bool canUseBackg this.CommitStateChange?.Invoke(this, EventArgs.Empty); } - return true; + return; } private async Task CommitCoreAsync(IUIThreadOperationContext operationContext, bool previewChanges) @@ -1028,15 +956,4 @@ internal bool TryGetContainingEditableSpan(SnapshotPoint point, out SnapshotSpan internal bool IsInOpenTextBuffer(SnapshotPoint point) => _openTextBuffers.ContainsKey(point.Snapshot.TextBuffer); - - internal TestAccessor GetTestAccessor() - => new TestAccessor(this); - - public readonly struct TestAccessor(InlineRenameSession inlineRenameSession) - { - private readonly InlineRenameSession _inlineRenameSession = inlineRenameSession; - - public bool CommitWorker(bool previewChanges) - => _inlineRenameSession.CommitSynchronously(previewChanges); - } } diff --git a/src/EditorFeatures/Core/InlineRename/InlineRenameSessionOptionsStorage.cs b/src/EditorFeatures/Core/InlineRename/InlineRenameSessionOptionsStorage.cs index 63a6dfa25ae22..406d7871df0d1 100644 --- a/src/EditorFeatures/Core/InlineRename/InlineRenameSessionOptionsStorage.cs +++ b/src/EditorFeatures/Core/InlineRename/InlineRenameSessionOptionsStorage.cs @@ -13,9 +13,4 @@ internal static class InlineRenameSessionOptionsStorage public static readonly Option2 RenameInComments = new("dotnet_rename_in_comments", defaultValue: false); public static readonly Option2 RenameFile = new("dotnet_rename_file", defaultValue: true); public static readonly Option2 PreviewChanges = new("dotnet_preview_inline_rename_changes", defaultValue: false); - - public static readonly Option2 CommitRenameAsynchronously = new("dotnet_commit_rename_asynchronously", defaultValue: true); - - public static bool ShouldCommitAsynchronously(this IGlobalOptionService globalOptionService) - => globalOptionService.GetOption(CommitRenameAsynchronously); } diff --git a/src/EditorFeatures/Core/InlineRename/Taggers/AbstractRenameTagger.cs b/src/EditorFeatures/Core/InlineRename/Taggers/AbstractRenameTagger.cs index c111df73c478e..e0c59a6b17d41 100644 --- a/src/EditorFeatures/Core/InlineRename/Taggers/AbstractRenameTagger.cs +++ b/src/EditorFeatures/Core/InlineRename/Taggers/AbstractRenameTagger.cs @@ -10,7 +10,6 @@ using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename; diff --git a/src/EditorFeatures/Core/InlineRename/UI/Adornment/RenameFlyout.xaml.cs b/src/EditorFeatures/Core/InlineRename/UI/Adornment/RenameFlyout.xaml.cs index 4df5f946b4991..2bca898670fe3 100644 --- a/src/EditorFeatures/Core/InlineRename/UI/Adornment/RenameFlyout.xaml.cs +++ b/src/EditorFeatures/Core/InlineRename/UI/Adornment/RenameFlyout.xaml.cs @@ -13,7 +13,6 @@ using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename; @@ -147,7 +146,8 @@ private void PositionAdornment() MaxWidth = _textView.ViewportRight; MinWidth = Math.Min(DefaultMinWidth, _textView.ViewportWidth); - Canvas.SetTop(this, Math.Max(0, top)); + // Top can be negative if the viewport is scrolled up, but not left + Canvas.SetTop(this, top); Canvas.SetLeft(this, Math.Max(0, left)); } diff --git a/src/EditorFeatures/Core/InlineRename/UI/Adornment/RenameFlyoutViewModel.cs b/src/EditorFeatures/Core/InlineRename/UI/Adornment/RenameFlyoutViewModel.cs index f0d2baf6d6704..e5d4ed313e564 100644 --- a/src/EditorFeatures/Core/InlineRename/UI/Adornment/RenameFlyoutViewModel.cs +++ b/src/EditorFeatures/Core/InlineRename/UI/Adornment/RenameFlyoutViewModel.cs @@ -15,6 +15,7 @@ using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.EditorFeatures.Lightup; +using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.InlineRename; using Microsoft.CodeAnalysis.InlineRename.UI.SmartRename; using Microsoft.CodeAnalysis.Options; @@ -32,6 +33,7 @@ internal class RenameFlyoutViewModel : INotifyPropertyChanged, IDisposable { private readonly bool _registerOleComponent; private readonly IGlobalOptionService _globalOptionService; + private readonly IAsynchronousOperationListener _asyncListener; private OleComponent? _oleComponent; private bool _disposedValue; private bool _isReplacementTextValid = true; @@ -51,6 +53,7 @@ public RenameFlyoutViewModel( Session = session; _registerOleComponent = registerOleComponent; _globalOptionService = globalOptionService; + _asyncListener = listenerProvider.GetListener(FeatureAttribute.Rename); Session.ReplacementTextChanged += OnReplacementTextChanged; Session.ReplacementsComputed += OnReplacementsComputed; Session.ReferenceLocationsChanged += OnReferenceLocationsChanged; @@ -229,7 +232,12 @@ public bool Submit() } SmartRenameViewModel?.Commit(IdentifierText); - Session.InitiateCommit(); + + var token = _asyncListener.BeginAsyncOperation(nameof(Submit)); + + // CommitAsync will display UI to the user while this asynchronous work is being done. + Session.CommitAsync(previewChanges: false, editorOperationContext: null) + .ReportNonFatalErrorAsync().CompletesAsyncOperation(token); return true; } @@ -325,10 +333,7 @@ protected virtual void Dispose(bool disposing) Session.ReplacementsComputed -= OnReplacementsComputed; Session.CommitStateChange -= CommitStateChange; - if (SmartRenameViewModel is not null) - { - SmartRenameViewModel.Dispose(); - } + SmartRenameViewModel?.Dispose(); UnregisterOleComponent(); } diff --git a/src/EditorFeatures/Core/InlineRename/UI/IInlineRenameColorUpdater.cs b/src/EditorFeatures/Core/InlineRename/UI/IInlineRenameColorUpdater.cs index 430b82840d08c..a273f76d84123 100644 --- a/src/EditorFeatures/Core/InlineRename/UI/IInlineRenameColorUpdater.cs +++ b/src/EditorFeatures/Core/InlineRename/UI/IInlineRenameColorUpdater.cs @@ -9,5 +9,5 @@ internal interface IInlineRenameColorUpdater /// /// Implemented by a host to set the properties on . /// - public void UpdateColors(); + void UpdateColors(); } diff --git a/src/EditorFeatures/Core/InlineRename/UI/InlineRenameAdornmentManager.cs b/src/EditorFeatures/Core/InlineRename/UI/InlineRenameAdornmentManager.cs index c7c23f84250af..527c141511880 100644 --- a/src/EditorFeatures/Core/InlineRename/UI/InlineRenameAdornmentManager.cs +++ b/src/EditorFeatures/Core/InlineRename/UI/InlineRenameAdornmentManager.cs @@ -8,13 +8,10 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.EditorFeatures.Lightup; -using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; -using Microsoft.CodeAnalysis.Telemetry; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Language.Intellisense; -using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename; diff --git a/src/EditorFeatures/Core/InlineRename/UI/InlineRenameAdornmentProvider.cs b/src/EditorFeatures/Core/InlineRename/UI/InlineRenameAdornmentProvider.cs index 38a6e9abcc7c3..3f5443d0d28a1 100644 --- a/src/EditorFeatures/Core/InlineRename/UI/InlineRenameAdornmentProvider.cs +++ b/src/EditorFeatures/Core/InlineRename/UI/InlineRenameAdornmentProvider.cs @@ -14,7 +14,6 @@ using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; diff --git a/src/EditorFeatures/Core/InlineRename/UI/SmartRename/SmartRenameViewModel.cs b/src/EditorFeatures/Core/InlineRename/UI/SmartRename/SmartRenameViewModel.cs index 337c4373f3a2b..4270630246e85 100644 --- a/src/EditorFeatures/Core/InlineRename/UI/SmartRename/SmartRenameViewModel.cs +++ b/src/EditorFeatures/Core/InlineRename/UI/SmartRename/SmartRenameViewModel.cs @@ -45,16 +45,10 @@ internal sealed partial class SmartRenameViewModel : INotifyPropertyChanged, IDi /// private CancellationTokenSource _cancellationTokenSource = new(); private bool _isDisposed; - private TimeSpan AutomaticFetchDelay => _smartRenameSession.AutomaticFetchDelay; private TimeSpan _semanticContextDelay; private bool _semanticContextError; private bool _semanticContextUsed; - /// - /// Backing field for . - /// - private bool _isInProgress = false; - public event PropertyChangedEventHandler? PropertyChanged; public RenameFlyoutViewModel BaseViewModel { get; } @@ -67,7 +61,7 @@ internal sealed partial class SmartRenameViewModel : INotifyPropertyChanged, IDi /// /// Indicates whether a request to get suggestions is in progress. - /// The request to get suggestions is comprised of initial short delay, + /// The request to get suggestions is comprised of initial short delay, see AutomaticFetchDelay /// and call to . /// When true, the UI shows the progress bar, and prevents from making parallel request. /// @@ -76,15 +70,15 @@ public bool IsInProgress get { _threadingContext.ThrowIfNotOnUIThread(); - return _isInProgress; + return field; } set { _threadingContext.ThrowIfNotOnUIThread(); - _isInProgress = value; + field = value; NotifyPropertyChanged(nameof(IsInProgress)); } - } + } = false; public string StatusMessage => _smartRenameSession.StatusMessage; @@ -109,20 +103,18 @@ public bool IsInProgress /// public bool IsUsingSemanticContext { get; } - private string? _selectedSuggestedName; - /// /// The last selected name when user click one of the suggestions. if user hasn't clicked any suggestions. /// public string? SelectedSuggestedName { - get => _selectedSuggestedName; + get; set { - if (_selectedSuggestedName != value) + if (field != value) { _threadingContext.ThrowIfNotOnUIThread(); - _selectedSuggestedName = value; + field = value; BaseViewModel.IdentifierText = value ?? string.Empty; } } @@ -196,7 +188,7 @@ private void FetchSuggestions(bool isAutomaticOnInitialization) /// /// The request for rename suggestions. It's made of three parts: - /// 1. Short delay of duration . + /// 1. Short delay of duration AutomaticFetchDelay. /// 2. Get definition and references if is set. /// 3. Call to . /// diff --git a/src/EditorFeatures/Core/InlineRename/UndoManagerServiceFactory.cs b/src/EditorFeatures/Core/InlineRename/UndoManagerServiceFactory.cs index 6b846353100dc..0ac192adcc86f 100644 --- a/src/EditorFeatures/Core/InlineRename/UndoManagerServiceFactory.cs +++ b/src/EditorFeatures/Core/InlineRename/UndoManagerServiceFactory.cs @@ -11,7 +11,6 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; -using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Utilities; diff --git a/src/EditorFeatures/Core/IntelliSense/AbstractController.cs b/src/EditorFeatures/Core/IntelliSense/AbstractController.cs index 5d67f48531cde..7da789ae228e7 100644 --- a/src/EditorFeatures/Core/IntelliSense/AbstractController.cs +++ b/src/EditorFeatures/Core/IntelliSense/AbstractController.cs @@ -5,13 +5,13 @@ #nullable disable using System; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; -using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Options; +using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; -using Microsoft.CodeAnalysis.Editor.Shared.Extensions; -using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense; diff --git a/src/EditorFeatures/Core/IntelliSense/AsyncCompletion/ItemManager.CompletionListUpdater.cs b/src/EditorFeatures/Core/IntelliSense/AsyncCompletion/ItemManager.CompletionListUpdater.cs index 2760f7f65fae4..fc033f8039388 100644 --- a/src/EditorFeatures/Core/IntelliSense/AsyncCompletion/ItemManager.CompletionListUpdater.cs +++ b/src/EditorFeatures/Core/IntelliSense/AsyncCompletion/ItemManager.CompletionListUpdater.cs @@ -11,6 +11,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/EditorFeatures/Core/IntelliSense/ModelComputation.cs b/src/EditorFeatures/Core/IntelliSense/ModelComputation.cs index 9813af452df05..66650c74844b4 100644 --- a/src/EditorFeatures/Core/IntelliSense/ModelComputation.cs +++ b/src/EditorFeatures/Core/IntelliSense/ModelComputation.cs @@ -146,12 +146,21 @@ public void ChainTaskAndNotifyControllerWhenFinished( async Task TransformModelAsync(Task lastTask) { - // Ensure we're on the BG before doing any model transformation work. Also, ensure we yield so that we don't - // end up with an enormously long chain of tasks unwinding. That can otherwise cause a stack overflow if - // this chain gets too long. - await Task.Yield().ConfigureAwait(false); - var model = await lastTask.ConfigureAwait(false); - return await transformModelAsync(model, _stopCancellationToken).ConfigureAwait(false); + // Ensure we're on the BG before doing any model transformation work. + await TaskScheduler.Default; + + try + { + var model = await lastTask.ConfigureAwait(false); + return await transformModelAsync(model, _stopCancellationToken).ConfigureAwait(false); + } + catch + { + // Also, ensure we yield during exception stack unwinding so that we don't end up with an enormously + // long chain of tasks unwinding. That can otherwise cause a stack overflow if this chain gets too long. + await Task.Yield().ConfigureAwait(false); + throw; + } } } diff --git a/src/EditorFeatures/Core/IntelliSense/QuickInfo/QuickInfoSourceProvider.QuickInfoSource.cs b/src/EditorFeatures/Core/IntelliSense/QuickInfo/QuickInfoSourceProvider.QuickInfoSource.cs index 1ef03c5d098b5..1f45ff94d8956 100644 --- a/src/EditorFeatures/Core/IntelliSense/QuickInfo/QuickInfoSourceProvider.QuickInfoSource.cs +++ b/src/EditorFeatures/Core/IntelliSense/QuickInfo/QuickInfoSourceProvider.QuickInfoSource.cs @@ -14,15 +14,14 @@ using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageService; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.QuickInfo; using Microsoft.CodeAnalysis.Shared.TestHooks; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Utilities; - using IntellisenseQuickInfoItem = Microsoft.VisualStudio.Language.Intellisense.QuickInfoItem; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo; diff --git a/src/EditorFeatures/Core/IntelliSense/ViewTextSpan.cs b/src/EditorFeatures/Core/IntelliSense/ViewTextSpan.cs index 684e6fc271ffe..91ab859a322ae 100644 --- a/src/EditorFeatures/Core/IntelliSense/ViewTextSpan.cs +++ b/src/EditorFeatures/Core/IntelliSense/ViewTextSpan.cs @@ -11,7 +11,6 @@ using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Projection; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense; diff --git a/src/EditorFeatures/Core/Intents/DeleteParameterIntentProvider.cs b/src/EditorFeatures/Core/Intents/DeleteParameterIntentProvider.cs deleted file mode 100644 index 1b685db55cba0..0000000000000 --- a/src/EditorFeatures/Core/Intents/DeleteParameterIntentProvider.cs +++ /dev/null @@ -1,64 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Immutable; -using System.Composition; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis.ChangeSignature; -using Microsoft.CodeAnalysis.Features.Intents; -using Microsoft.CodeAnalysis.Host.Mef; -using Microsoft.CodeAnalysis.Shared.Extensions; -using Microsoft.CodeAnalysis.Text; -using Roslyn.Utilities; - -namespace Microsoft.CodeAnalysis.EditorFeatures.Intents; - -[IntentProvider(WellKnownIntents.DeleteParameter, LanguageNames.CSharp), Shared] -[method: ImportingConstructor] -[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] -internal sealed class DeleteParameterIntentProvider() : IIntentProvider -{ - public async Task> ComputeIntentAsync( - Document priorDocument, - TextSpan priorSelection, - Document currentDocument, - IntentDataProvider intentDataProvider, - CancellationToken cancellationToken) - { - var changeSignatureService = priorDocument.GetRequiredLanguageService(); - var contextResult = await changeSignatureService.GetChangeSignatureContextAsync( - priorDocument, priorSelection.Start, restrictToDeclarations: false, cancellationToken).ConfigureAwait(false); - - if (contextResult is not ChangeSignatureAnalysisSucceededContext context) - { - return []; - } - - var parameterIndexToDelete = context.ParameterConfiguration.SelectedIndex; - var parameters = context.ParameterConfiguration.ToListOfParameters(); - var isExtensionMethod = context.ParameterConfiguration.ThisParameter != null; - - if (isExtensionMethod && parameterIndexToDelete == 0) - { - // We can't delete the 'this' parameter of an extension method. - return []; - } - - var newParameters = parameters.RemoveAt(parameterIndexToDelete); - - var signatureChange = new SignatureChange(context.ParameterConfiguration, ParameterConfiguration.Create(newParameters, isExtensionMethod, selectedIndex: 0)); - var changeSignatureOptionResult = new ChangeSignatureOptionsResult(signatureChange, previewChanges: false); - - var changeSignatureResult = await changeSignatureService.ChangeSignatureWithContextAsync(context, changeSignatureOptionResult, cancellationToken).ConfigureAwait(false); - if (!changeSignatureResult.Succeeded) - { - return []; - } - - var changedDocuments = changeSignatureResult.UpdatedSolution.GetChangedDocuments(priorDocument.Project.Solution).ToImmutableArray(); - return [new IntentProcessorResult(changeSignatureResult.UpdatedSolution, changedDocuments, EditorFeaturesResources.Change_Signature, WellKnownIntents.DeleteParameter)]; - } -} diff --git a/src/EditorFeatures/Core/Intents/RenameIntentProvider.cs b/src/EditorFeatures/Core/Intents/RenameIntentProvider.cs deleted file mode 100644 index 7cfc38df565b4..0000000000000 --- a/src/EditorFeatures/Core/Intents/RenameIntentProvider.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Immutable; -using System.Composition; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis.Editor; -using Microsoft.CodeAnalysis.Features.Intents; -using Microsoft.CodeAnalysis.Host.Mef; -using Microsoft.CodeAnalysis.Rename; -using Microsoft.CodeAnalysis.Shared.Extensions; -using Microsoft.CodeAnalysis.Text; - -namespace Microsoft.CodeAnalysis.EditorFeatures.Intents; - -[IntentProvider(WellKnownIntents.Rename, LanguageNames.CSharp), Shared] -internal sealed class RenameIntentProvider : IIntentProvider -{ - private sealed record RenameIntentData(string NewName); - - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public RenameIntentProvider() - { - } - - public async Task> ComputeIntentAsync( - Document priorDocument, - TextSpan priorSelection, - Document currentDocument, - IntentDataProvider intentDataProvider, - CancellationToken cancellationToken) - { - var renameIntentData = intentDataProvider.GetIntentData(); - Contract.ThrowIfNull(renameIntentData); - - var renameService = priorDocument.GetRequiredLanguageService(); - var renameInfo = await renameService.GetRenameInfoAsync(priorDocument, priorSelection.Start, cancellationToken).ConfigureAwait(false); - if (!renameInfo.CanRename) - { - return []; - } - - var options = new SymbolRenameOptions( - RenameOverloads: false, - RenameInStrings: false, - RenameInComments: false, - RenameFile: false); - - var renameLocationSet = await renameInfo.FindRenameLocationsAsync(options, cancellationToken).ConfigureAwait(false); - var renameReplacementInfo = await renameLocationSet.GetReplacementsAsync(renameIntentData.NewName, options, cancellationToken).ConfigureAwait(false); - - return [new IntentProcessorResult(renameReplacementInfo.NewSolution, [.. renameReplacementInfo.DocumentIds], EditorFeaturesResources.Rename, WellKnownIntents.Rename)]; - } -} diff --git a/src/EditorFeatures/Core/Interactive/ISendToInteractiveSubmissionProvider.cs b/src/EditorFeatures/Core/Interactive/ISendToInteractiveSubmissionProvider.cs index f583c4ab6ef08..d1a04b13b84e6 100644 --- a/src/EditorFeatures/Core/Interactive/ISendToInteractiveSubmissionProvider.cs +++ b/src/EditorFeatures/Core/Interactive/ISendToInteractiveSubmissionProvider.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Threading; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding; -using System.Threading; namespace Microsoft.CodeAnalysis.Interactive; diff --git a/src/EditorFeatures/Core/Interactive/InteractiveCommandHandler.cs b/src/EditorFeatures/Core/Interactive/InteractiveCommandHandler.cs index 2247b89a5048b..b8a079f5d7d9c 100644 --- a/src/EditorFeatures/Core/Interactive/InteractiveCommandHandler.cs +++ b/src/EditorFeatures/Core/Interactive/InteractiveCommandHandler.cs @@ -6,16 +6,16 @@ using System; using System.Diagnostics; +using System.Threading; +using Microsoft.CodeAnalysis.Options; +using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.Text; +using Microsoft.VisualStudio.Text.Editor.Commanding; +using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Utilities; -using System.Threading; -using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; -using Microsoft.VisualStudio.Commanding; -using Microsoft.VisualStudio.Text.Editor.Commanding; -using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Interactive; diff --git a/src/EditorFeatures/Core/Interactive/InteractiveEvaluator.cs b/src/EditorFeatures/Core/Interactive/InteractiveEvaluator.cs index 8d9504d206ca7..546b311f2efc5 100644 --- a/src/EditorFeatures/Core/Interactive/InteractiveEvaluator.cs +++ b/src/EditorFeatures/Core/Interactive/InteractiveEvaluator.cs @@ -123,7 +123,7 @@ public IInteractiveWindow? CurrentWindow { _threadingContext.ThrowIfNotOnUIThread(); - if (_lazyInteractiveWindow != null) + if (CurrentWindow != null) { throw new NotSupportedException(EditorFeaturesWpfResources.The_CurrentWindow_property_may_only_be_assigned_once); } diff --git a/src/EditorFeatures/Core/Interactive/InteractiveSupportsFeatureService.cs b/src/EditorFeatures/Core/Interactive/InteractiveSupportsFeatureService.cs index cbc4efde44b00..9cec0a55cba36 100644 --- a/src/EditorFeatures/Core/Interactive/InteractiveSupportsFeatureService.cs +++ b/src/EditorFeatures/Core/Interactive/InteractiveSupportsFeatureService.cs @@ -2,13 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System; using System.Composition; using Microsoft.CodeAnalysis.Editor.Shared; using Microsoft.CodeAnalysis.Host.Mef; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.CodeAnalysis.Shared; -using System; +using Microsoft.VisualStudio.InteractiveWindow; +using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Interactive; diff --git a/src/EditorFeatures/Core/Interactive/InteractiveWindowResetCommand.cs b/src/EditorFeatures/Core/Interactive/InteractiveWindowResetCommand.cs index 3ff72b7aaf95f..f813d05ff9ab8 100644 --- a/src/EditorFeatures/Core/Interactive/InteractiveWindowResetCommand.cs +++ b/src/EditorFeatures/Core/Interactive/InteractiveWindowResetCommand.cs @@ -5,11 +5,11 @@ #nullable disable extern alias InteractiveHost; - using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Threading.Tasks; +using InteractiveHost::Microsoft.CodeAnalysis.Interactive; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.InteractiveWindow.Commands; @@ -17,7 +17,6 @@ using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; -using InteractiveHost::Microsoft.CodeAnalysis.Interactive; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Interactive; @@ -60,8 +59,8 @@ public IEnumerable> ParametersDescription { get { - yield return KeyValuePairUtil.Create(NoConfigParameterName, EditorFeaturesWpfResources.Reset_to_a_clean_environment_only_mscorlib_referenced_do_not_run_initialization_script); - yield return KeyValuePairUtil.Create(PlatformNames, EditorFeaturesWpfResources.Interactive_host_process_platform); + yield return KeyValuePair.Create(NoConfigParameterName, EditorFeaturesWpfResources.Reset_to_a_clean_environment_only_mscorlib_referenced_do_not_run_initialization_script); + yield return KeyValuePair.Create(PlatformNames, EditorFeaturesWpfResources.Interactive_host_process_platform); } } diff --git a/src/EditorFeatures/Core/Interactive/SendToInteractiveSubmissionProvider.cs b/src/EditorFeatures/Core/Interactive/SendToInteractiveSubmissionProvider.cs index d9e58301b1d66..a65de46a2d2fd 100644 --- a/src/EditorFeatures/Core/Interactive/SendToInteractiveSubmissionProvider.cs +++ b/src/EditorFeatures/Core/Interactive/SendToInteractiveSubmissionProvider.cs @@ -4,15 +4,15 @@ #nullable disable -using Microsoft.CodeAnalysis.Editor.Shared.Extensions; -using Microsoft.CodeAnalysis.Text; -using Microsoft.VisualStudio.Text; using System.Collections.Generic; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Editor.Shared.Extensions; +using Microsoft.CodeAnalysis.Text; +using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; -using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Microsoft.VisualStudio.Text.Editor.Commanding; +using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; namespace Microsoft.CodeAnalysis.Interactive; diff --git a/src/EditorFeatures/Core/LanguageServer/AbstractInProcLanguageClient.cs b/src/EditorFeatures/Core/LanguageServer/AbstractInProcLanguageClient.cs index 0f1753257a44f..e53cd9238b5f3 100644 --- a/src/EditorFeatures/Core/LanguageServer/AbstractInProcLanguageClient.cs +++ b/src/EditorFeatures/Core/LanguageServer/AbstractInProcLanguageClient.cs @@ -110,10 +110,16 @@ internal abstract partial class AbstractInProcLanguageClient( public event AsyncEventHandler? StartAsync; + public event AsyncEventHandler? StopAsync; + /// - /// Unused, implementing + /// Stops the server if it has been started. /// - public event AsyncEventHandler? StopAsync { add { } remove { } } + /// + /// Per the documentation on , the event is ignored if the server has not been started. + /// + public Task StopServerAsync() + => StopAsync?.InvokeAsync(this, EventArgs.Empty) ?? Task.CompletedTask; public async Task ActivateAsync(CancellationToken cancellationToken) { diff --git a/src/EditorFeatures/Core/LanguageServer/AlwaysActiveLanguageClientEventListener.cs b/src/EditorFeatures/Core/LanguageServer/AlwaysActiveLanguageClientEventListener.cs index ebf66dd49fd06..ab3c312d9416c 100644 --- a/src/EditorFeatures/Core/LanguageServer/AlwaysActiveLanguageClientEventListener.cs +++ b/src/EditorFeatures/Core/LanguageServer/AlwaysActiveLanguageClientEventListener.cs @@ -40,8 +40,25 @@ internal sealed class AlwaysActiveLanguageClientEventListener( /// public void StartListening(Workspace workspace) { - // Trigger a fire and forget request to the VS LSP client to load our ILanguageClient. - _ = LoadAsync(); + _ = workspace.RegisterWorkspaceChangedHandler(Workspace_WorkspaceChanged); + } + + private void Workspace_WorkspaceChanged(WorkspaceChangeEventArgs e) + { + if (e.Kind == WorkspaceChangeKind.SolutionAdded) + { + // Normally VS will load the language client when an editor window is created for one of our content types, + // but we want to load it as soon as a solution is loaded so workspace diagnostics work, and so 3rd parties + // like Razor can use dynamic registration. + LoadLanguageClient(); + } + else if (e.Kind is WorkspaceChangeKind.SolutionRemoved) + { + // VS will unload the language client when the solution is closed, but sometimes its a little slow to do so, + // and we can end up trying to load it, above, before it has been asked to unload. We wait for the previous + // instance to shutdown when we load, but we have to ensure that it at least gets signaled to do so first. + UnloadLanguageClient(); + } } public void StopListening(Workspace workspace) @@ -49,12 +66,13 @@ public void StopListening(Workspace workspace) // Nothing to do here. There's no concept of unloading an ILanguageClient. } - private async Task LoadAsync() + private void LoadLanguageClient() { - try - { - using var token = _asynchronousOperationListener.BeginAsyncOperation(nameof(LoadAsync)); + using var token = _asynchronousOperationListener.BeginAsyncOperation(nameof(LoadLanguageClient)); + LoadAsync().ReportNonFatalErrorAsync().CompletesAsyncOperation(token); + async Task LoadAsync() + { // Explicitly switch to the bg so that if this causes any expensive work (like mef loads) it // doesn't block the UI thread. Note, we always yield because sometimes our caller starts // on the threadpool thread but is indirectly blocked on by the UI thread. @@ -67,9 +85,14 @@ await _languageClientBroker.Value.LoadAsync(new LanguageClientMetadata( ContentTypeNames.FSharpContentType ]), _languageClient).ConfigureAwait(false); } - catch (Exception e) when (FatalError.ReportAndCatch(e)) - { - } + } + + private void UnloadLanguageClient() + { + // We just want to signal that an unload should happen, in case the above call to Load comes in quick. + // We don't want to wait for it to complete, not do we care about errors that may occur during the unload. + // The language client/server does its own error reporting as necessary. + _languageClient.StopServerAsync().Forget(); } /// diff --git a/src/EditorFeatures/Core/Lightup/ISmartRenameSessionWrapper.cs b/src/EditorFeatures/Core/Lightup/ISmartRenameSessionWrapper.cs index 45efb9baff566..e81fc283634cf 100644 --- a/src/EditorFeatures/Core/Lightup/ISmartRenameSessionWrapper.cs +++ b/src/EditorFeatures/Core/Lightup/ISmartRenameSessionWrapper.cs @@ -63,10 +63,10 @@ static ISmartRenameSessionWrapper() defaultValue: SpecializedTasks.Null()); s_renameContextImmutableListBuilderAddAccessor = LightupHelpers.CreateActionAccessor(typeof(ImmutableArray<>.Builder).MakeGenericType(s_wrappedRenameContextType), - nameof(ImmutableArray.Builder.Add), + nameof(ImmutableArray<>.Builder.Add), s_wrappedRenameContextType); s_renameContextImmutableListBuilderToArrayAccessor = LightupHelpers.CreateFunctionAccessor(typeof(ImmutableArray<>.Builder).MakeGenericType(s_wrappedRenameContextType), - nameof(ImmutableArray.Builder.ToImmutable), + nameof(ImmutableArray<>.Builder.ToImmutable), typeof(ImmutableArray<>).MakeGenericType(s_wrappedRenameContextType)); var immutableArrayOfRenameContextType = typeof(ImmutableArray<>).MakeGenericType(s_wrappedRenameContextType); diff --git a/src/EditorFeatures/Core/Logging/FunctionIdOptions.cs b/src/EditorFeatures/Core/Logging/FunctionIdOptions.cs index 776277f7b13c2..80522259cf438 100644 --- a/src/EditorFeatures/Core/Logging/FunctionIdOptions.cs +++ b/src/EditorFeatures/Core/Logging/FunctionIdOptions.cs @@ -3,10 +3,10 @@ // See the LICENSE file in the project root for more information. using System; -using System.Linq; using System.Collections.Concurrent; -using Microsoft.CodeAnalysis.Options; using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Internal.Log; diff --git a/src/EditorFeatures/Core/Microsoft.CodeAnalysis.EditorFeatures.csproj b/src/EditorFeatures/Core/Microsoft.CodeAnalysis.EditorFeatures.csproj index 15fae0b23707c..43c88bb2c1d1c 100644 --- a/src/EditorFeatures/Core/Microsoft.CodeAnalysis.EditorFeatures.csproj +++ b/src/EditorFeatures/Core/Microsoft.CodeAnalysis.EditorFeatures.csproj @@ -112,7 +112,4 @@ - - - \ No newline at end of file diff --git a/src/EditorFeatures/Core/NavigableSymbols/NavigableSymbolService.cs b/src/EditorFeatures/Core/NavigableSymbols/NavigableSymbolService.cs index faea40e182b44..c8f83d84223ce 100644 --- a/src/EditorFeatures/Core/NavigableSymbols/NavigableSymbolService.cs +++ b/src/EditorFeatures/Core/NavigableSymbols/NavigableSymbolService.cs @@ -21,18 +21,15 @@ internal sealed partial class NavigableSymbolService : INavigableSymbolSourcePro { private static readonly object s_key = new(); - private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; private readonly IThreadingContext _threadingContext; private readonly IAsynchronousOperationListener _listener; [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public NavigableSymbolService( - IUIThreadOperationExecutor uiThreadOperationExecutor, IThreadingContext threadingContext, IAsynchronousOperationListenerProvider listenerProvider) { - _uiThreadOperationExecutor = uiThreadOperationExecutor; _threadingContext = threadingContext; _listener = listenerProvider.GetListener(FeatureAttribute.NavigableSymbols); } diff --git a/src/EditorFeatures/Core/Navigation/AbstractDefinitionLocationService.cs b/src/EditorFeatures/Core/Navigation/AbstractDefinitionLocationService.cs index ef6a5fba60c5b..95a6002282571 100644 --- a/src/EditorFeatures/Core/Navigation/AbstractDefinitionLocationService.cs +++ b/src/EditorFeatures/Core/Navigation/AbstractDefinitionLocationService.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Collections.Immutable; +using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; diff --git a/src/EditorFeatures/Core/Navigation/IDocumentNavigationServiceExtensions.cs b/src/EditorFeatures/Core/Navigation/IDocumentNavigationServiceExtensions.cs index d2bc7ec0c15da..001b3e6651c7a 100644 --- a/src/EditorFeatures/Core/Navigation/IDocumentNavigationServiceExtensions.cs +++ b/src/EditorFeatures/Core/Navigation/IDocumentNavigationServiceExtensions.cs @@ -5,8 +5,8 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; -using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Shared.Extensions; +using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Navigation; diff --git a/src/EditorFeatures/Core/Options/EditorAnalyzerConfigOptions.cs b/src/EditorFeatures/Core/Options/EditorAnalyzerConfigOptions.cs index 399e56ba7519d..9f39045173bbd 100644 --- a/src/EditorFeatures/Core/Options/EditorAnalyzerConfigOptions.cs +++ b/src/EditorFeatures/Core/Options/EditorAnalyzerConfigOptions.cs @@ -7,7 +7,6 @@ using System.Linq; using Microsoft.CodeAnalysis.Collections; using Microsoft.VisualStudio.Text.Editor; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics; diff --git a/src/EditorFeatures/Core/Organizing/OrganizeDocumentCommandHandler.cs b/src/EditorFeatures/Core/Organizing/OrganizeDocumentCommandHandler.cs index 320832e90b68c..ef1fcee6668af 100644 --- a/src/EditorFeatures/Core/Organizing/OrganizeDocumentCommandHandler.cs +++ b/src/EditorFeatures/Core/Organizing/OrganizeDocumentCommandHandler.cs @@ -20,7 +20,6 @@ using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; -using Microsoft.VisualStudio.Language.Intellisense.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding; using Microsoft.VisualStudio.Threading; diff --git a/src/EditorFeatures/Core/Peek/PeekableItemSource.cs b/src/EditorFeatures/Core/Peek/PeekableItemSource.cs index 25e74cfbde1ba..f4337bbfd34ed 100644 --- a/src/EditorFeatures/Core/Peek/PeekableItemSource.cs +++ b/src/EditorFeatures/Core/Peek/PeekableItemSource.cs @@ -7,6 +7,7 @@ using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Navigation; @@ -16,7 +17,6 @@ using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Utilities; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Peek; diff --git a/src/EditorFeatures/Core/Preview/IDifferenceViewerPreview.cs b/src/EditorFeatures/Core/Preview/IDifferenceViewerPreview.cs index 082f6e540b9b4..271e9073dfce7 100644 --- a/src/EditorFeatures/Core/Preview/IDifferenceViewerPreview.cs +++ b/src/EditorFeatures/Core/Preview/IDifferenceViewerPreview.cs @@ -10,5 +10,5 @@ namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview; internal interface IDifferenceViewerPreview : IDisposable where TDifferenceViewer : IDifferenceViewer { - public TDifferenceViewer Viewer { get; } + TDifferenceViewer Viewer { get; } } diff --git a/src/EditorFeatures/Core/Preview/PreviewReferenceHighlightingTaggerProvider.cs b/src/EditorFeatures/Core/Preview/PreviewReferenceHighlightingTaggerProvider.cs index e539b5b54c433..f67fb5f40e9be 100644 --- a/src/EditorFeatures/Core/Preview/PreviewReferenceHighlightingTaggerProvider.cs +++ b/src/EditorFeatures/Core/Preview/PreviewReferenceHighlightingTaggerProvider.cs @@ -4,15 +4,15 @@ #nullable disable +using System; using System.ComponentModel.Composition; +using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; +using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; -using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting; -using System; -using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview; diff --git a/src/EditorFeatures/Core/Preview/PreviewWarningViewTaggerProvider.cs b/src/EditorFeatures/Core/Preview/PreviewWarningViewTaggerProvider.cs index d8e609dc6a1df..9ddab23853c34 100644 --- a/src/EditorFeatures/Core/Preview/PreviewWarningViewTaggerProvider.cs +++ b/src/EditorFeatures/Core/Preview/PreviewWarningViewTaggerProvider.cs @@ -4,14 +4,14 @@ #nullable disable +using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; +using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; -using System; -using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview; diff --git a/src/EditorFeatures/Core/QuickInfo/OnTheFlyDocsView.xaml.cs b/src/EditorFeatures/Core/QuickInfo/OnTheFlyDocsView.xaml.cs index 5871e62bfbf09..22794fa18ffe5 100644 --- a/src/EditorFeatures/Core/QuickInfo/OnTheFlyDocsView.xaml.cs +++ b/src/EditorFeatures/Core/QuickInfo/OnTheFlyDocsView.xaml.cs @@ -50,8 +50,6 @@ internal sealed partial class OnTheFlyDocsView : UserControl, INotifyPropertyCha private readonly List quotaExceededContent; private readonly IServiceProvider _serviceProvider; - private OnTheFlyDocsState _currentState = OnTheFlyDocsState.OnDemandLink; - /// public event PropertyChangedEventHandler? PropertyChanged; @@ -262,9 +260,9 @@ private void OnQuickInfoSessionChanged() public OnTheFlyDocsState CurrentState { - get => _currentState; - set => OnPropertyChanged(ref _currentState, value); - } + get; + set => OnPropertyChanged(ref field, value); + } = OnTheFlyDocsState.OnDemandLink; public UIElement OnDemandLinkContent { get; } diff --git a/src/EditorFeatures/Core/ReferenceHighlighting/ReferenceHighlightingViewTaggerProvider.cs b/src/EditorFeatures/Core/ReferenceHighlighting/ReferenceHighlightingViewTaggerProvider.cs index ceb74bae26bfb..bd1ea87d40c84 100644 --- a/src/EditorFeatures/Core/ReferenceHighlighting/ReferenceHighlightingViewTaggerProvider.cs +++ b/src/EditorFeatures/Core/ReferenceHighlighting/ReferenceHighlightingViewTaggerProvider.cs @@ -10,6 +10,7 @@ using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.DocumentHighlighting; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Tagging; diff --git a/src/EditorFeatures/Core/Remote/SolutionChecksumUpdater.cs b/src/EditorFeatures/Core/Remote/SolutionChecksumUpdater.cs index 033c8a6db585a..eb2afb0a1cbea 100644 --- a/src/EditorFeatures/Core/Remote/SolutionChecksumUpdater.cs +++ b/src/EditorFeatures/Core/Remote/SolutionChecksumUpdater.cs @@ -3,17 +3,14 @@ // See the LICENSE file in the project root for more information. using System; -using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; -using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Telemetry; using Microsoft.CodeAnalysis.Threading; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote; @@ -25,12 +22,6 @@ internal sealed class SolutionChecksumUpdater { private readonly Workspace _workspace; - /// - /// We're not at a layer where we are guaranteed to have an IGlobalOperationNotificationService. So allow for - /// it being null. - /// - private readonly IGlobalOperationNotificationService? _globalOperationService; - private readonly IDocumentTrackingService _documentTrackingService; /// @@ -54,8 +45,6 @@ internal sealed class SolutionChecksumUpdater private const string SynchronizeTextChangesStatusSucceededKeyName = nameof(SolutionChecksumUpdater) + "." + SynchronizeTextChangesStatusSucceededMetricName; private const string SynchronizeTextChangesStatusFailedKeyName = nameof(SolutionChecksumUpdater) + "." + SynchronizeTextChangesStatusFailedMetricName; - private bool _isSynchronizeWorkspacePaused; - public SolutionChecksumUpdater( Workspace workspace, IAsynchronousOperationListenerProvider listenerProvider, @@ -63,8 +52,6 @@ public SolutionChecksumUpdater( { var listener = listenerProvider.GetListener(FeatureAttribute.SolutionChecksumUpdater); - _globalOperationService = workspace.Services.SolutionServices.ExportProvider.GetExports().FirstOrDefault()?.Value; - _workspace = workspace; _documentTrackingService = workspace.Services.GetRequiredService(); @@ -87,12 +74,6 @@ public SolutionChecksumUpdater( _workspaceChangedImmediateDisposer = _workspace.RegisterWorkspaceChangedImmediateHandler(OnWorkspaceChangedImmediate); _documentTrackingService.ActiveDocumentChanged += OnActiveDocumentChanged; - if (_globalOperationService != null) - { - _globalOperationService.Started += OnGlobalOperationStarted; - _globalOperationService.Stopped += OnGlobalOperationStopped; - } - // Enqueue the work to sync the initial data over. _synchronizeActiveDocumentQueue.AddWork(); _synchronizeWorkspaceQueue.AddWork(); @@ -101,53 +82,21 @@ public SolutionChecksumUpdater( public void Shutdown() { // Try to stop any work that is in progress. - PauseSynchronizingPrimaryWorkspace(); - - _documentTrackingService.ActiveDocumentChanged -= OnActiveDocumentChanged; - _workspaceChangedDisposer.Dispose(); - _workspaceChangedImmediateDisposer.Dispose(); - - if (_globalOperationService != null) - { - _globalOperationService.Started -= OnGlobalOperationStarted; - _globalOperationService.Stopped -= OnGlobalOperationStopped; - } - } - - private void OnGlobalOperationStarted(object? sender, EventArgs e) - => PauseSynchronizingPrimaryWorkspace(); - - private void OnGlobalOperationStopped(object? sender, EventArgs e) - => ResumeSynchronizingPrimaryWorkspace(); - - private void PauseSynchronizingPrimaryWorkspace() - { - // An expensive global operation started (like a build). Pause ourselves and cancel any outstanding work in - // progress to synchronize the solution. lock (_gate) { _synchronizeWorkspaceQueue.CancelExistingWork(); - _isSynchronizeWorkspacePaused = true; } - } - private void ResumeSynchronizingPrimaryWorkspace() - { - lock (_gate) - { - _isSynchronizeWorkspacePaused = false; - _synchronizeWorkspaceQueue.AddWork(); - } + _documentTrackingService.ActiveDocumentChanged -= OnActiveDocumentChanged; + _workspaceChangedDisposer.Dispose(); + _workspaceChangedImmediateDisposer.Dispose(); } private void OnWorkspaceChanged(WorkspaceChangeEventArgs _) { - // Check if we're currently paused. If so ignore this notification. We don't want to any work in response - // to whatever the workspace is doing. lock (_gate) { - if (!_isSynchronizeWorkspacePaused) - _synchronizeWorkspaceQueue.AddWork(); + _synchronizeWorkspaceQueue.AddWork(); } } diff --git a/src/EditorFeatures/Core/RenameTracking/RenameTrackingTaggerProvider.cs b/src/EditorFeatures/Core/RenameTracking/RenameTrackingTaggerProvider.cs index 4fb1de3d67acc..13b1d7124f051 100644 --- a/src/EditorFeatures/Core/RenameTracking/RenameTrackingTaggerProvider.cs +++ b/src/EditorFeatures/Core/RenameTracking/RenameTrackingTaggerProvider.cs @@ -10,7 +10,6 @@ using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; -using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Options; diff --git a/src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.ParseOptionChangedEventSource.cs b/src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.ParseOptionChangedEventSource.cs index 074daf5c33638..c020273216290 100644 --- a/src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.ParseOptionChangedEventSource.cs +++ b/src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.ParseOptionChangedEventSource.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; +using System.Linq; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; diff --git a/src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.ViewSpanChangedEventSource.cs b/src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.ViewSpanChangedEventSource.cs index 650555e802baf..7a5dbb9278a74 100644 --- a/src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.ViewSpanChangedEventSource.cs +++ b/src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.ViewSpanChangedEventSource.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Text; diff --git a/src/EditorFeatures/Core/Shared/Utilities/CaretPreservingEditTransaction.cs b/src/EditorFeatures/Core/Shared/Utilities/CaretPreservingEditTransaction.cs index 5bcb2e0203bce..7dfdafeb9d975 100644 --- a/src/EditorFeatures/Core/Shared/Utilities/CaretPreservingEditTransaction.cs +++ b/src/EditorFeatures/Core/Shared/Utilities/CaretPreservingEditTransaction.cs @@ -93,10 +93,7 @@ public IMergeTextUndoTransactionPolicy? MergePolicy set { - if (_transaction != null) - { - _transaction.MergePolicy = value; - } + _transaction?.MergePolicy = value; } } diff --git a/src/EditorFeatures/Core/SignatureHelp/Controller_TypeChar.cs b/src/EditorFeatures/Core/SignatureHelp/Controller_TypeChar.cs index 56b1264e7e4d0..9a6bde5678aaf 100644 --- a/src/EditorFeatures/Core/SignatureHelp/Controller_TypeChar.cs +++ b/src/EditorFeatures/Core/SignatureHelp/Controller_TypeChar.cs @@ -117,7 +117,7 @@ void IChainedCommandHandler.ExecuteCommand(TypeCharCommandA // // Or it can trigger a new list. Ask the computation to compute again. sessionOpt.ComputeModel( - textuallyTriggeredProviders.Concat(untriggeredProviders), triggerInfo); + [.. textuallyTriggeredProviders, .. untriggeredProviders], triggerInfo); computed = true; } diff --git a/src/EditorFeatures/Core/SignatureHelp/Presentation/SignatureHelpPresenter.SignatureHelpPresenterSession.cs b/src/EditorFeatures/Core/SignatureHelp/Presentation/SignatureHelpPresenter.SignatureHelpPresenterSession.cs index 0c1dd62d2d604..4bdd65c15742b 100644 --- a/src/EditorFeatures/Core/SignatureHelp/Presentation/SignatureHelpPresenter.SignatureHelpPresenterSession.cs +++ b/src/EditorFeatures/Core/SignatureHelp/Presentation/SignatureHelpPresenter.SignatureHelpPresenterSession.cs @@ -8,6 +8,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.SignatureHelp; @@ -97,10 +98,7 @@ public void PresentItems( Contract.ThrowIfNull(_signatureMap); var defaultValue = _signatureMap.GetValueOrDefault(_selectedItem); - if (_editorSessionOpt != null) - { - _editorSessionOpt.SelectedSignature = defaultValue; - } + _editorSessionOpt?.SelectedSignature = defaultValue; } finally { diff --git a/src/EditorFeatures/Core/SplitComment/SplitCommentCommandHandler.cs b/src/EditorFeatures/Core/SplitComment/SplitCommentCommandHandler.cs index a255eabcd154f..8de344caa12a2 100644 --- a/src/EditorFeatures/Core/SplitComment/SplitCommentCommandHandler.cs +++ b/src/EditorFeatures/Core/SplitComment/SplitCommentCommandHandler.cs @@ -33,13 +33,11 @@ internal sealed class SplitCommentCommandHandler( ITextUndoHistoryRegistry undoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService, EditorOptionsService editorOptionsService, - IIndentationManagerService indentationManager, IGlobalOptionService globalOptions) : ICommandHandler { private readonly ITextUndoHistoryRegistry _undoHistoryRegistry = undoHistoryRegistry; private readonly IEditorOperationsFactoryService _editorOperationsFactoryService = editorOperationsFactoryService; private readonly EditorOptionsService _editorOptionsService = editorOptionsService; - private readonly IIndentationManagerService _indentationManager = indentationManager; private readonly IGlobalOptionService _globalOptions = globalOptions; public string DisplayName => EditorFeaturesResources.Split_comment; diff --git a/src/EditorFeatures/Core/StringIndentation/StringIndentationAdornmentManagerProvider.cs b/src/EditorFeatures/Core/StringIndentation/StringIndentationAdornmentManagerProvider.cs index 50123845f168f..ae0a21f4294ff 100644 --- a/src/EditorFeatures/Core/StringIndentation/StringIndentationAdornmentManagerProvider.cs +++ b/src/EditorFeatures/Core/StringIndentation/StringIndentationAdornmentManagerProvider.cs @@ -5,8 +5,8 @@ using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Implementation.Adornments; -using Microsoft.CodeAnalysis.Editor.StringIndentation; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; +using Microsoft.CodeAnalysis.Editor.StringIndentation; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; diff --git a/src/EditorFeatures/Core/Suggestions/Copilot/FlavoredSuggestedAction.cs b/src/EditorFeatures/Core/Suggestions/Copilot/FlavoredSuggestedAction.cs index db5f020c46022..ecef4935b1d80 100644 --- a/src/EditorFeatures/Core/Suggestions/Copilot/FlavoredSuggestedAction.cs +++ b/src/EditorFeatures/Core/Suggestions/Copilot/FlavoredSuggestedAction.cs @@ -4,9 +4,9 @@ #nullable disable +using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Text; -using Microsoft.CodeAnalysis.CodeActions; namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions; diff --git a/src/EditorFeatures/Core/Suggestions/FixAll/FixMultipleOccurrencesService.cs b/src/EditorFeatures/Core/Suggestions/FixAll/FixMultipleOccurrencesService.cs index 3d38af13ce9ad..c1c6a26dbefb0 100644 --- a/src/EditorFeatures/Core/Suggestions/FixAll/FixMultipleOccurrencesService.cs +++ b/src/EditorFeatures/Core/Suggestions/FixAll/FixMultipleOccurrencesService.cs @@ -9,6 +9,7 @@ using System.Composition; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Host.Mef; @@ -67,16 +68,14 @@ private static async Task GetFixedSolutionAsync( IProgress progress, CancellationToken cancellationToken) { - var fixMultipleCodeAction = new FixMultipleCodeAction( - fixAllState, title, waitDialogMessage); + var fixMultipleCodeAction = new FixMultipleCodeAction(fixAllState, title, waitDialogMessage); Solution newSolution = null; var extensionManager = workspace.Services.GetService(); await extensionManager.PerformActionAsync(fixAllState.FixAllProvider, async () => { - // We don't need to post process changes here as the inner code action created for Fix multiple code fix already executes. newSolution = await fixMultipleCodeAction.GetChangedSolutionInternalAsync( - fixAllState.Solution, progress, postProcessChanges: false, cancellationToken).ConfigureAwait(false); + fixAllState.Solution, progress, cancellationToken).ConfigureAwait(false); }).ConfigureAwait(false); return newSolution; diff --git a/src/EditorFeatures/Core/Suggestions/RefineUsingCopilot/RefineUsingCopilotCodeAction.cs b/src/EditorFeatures/Core/Suggestions/RefineUsingCopilot/RefineUsingCopilotCodeAction.cs index 7dc2781361a52..79048bfa20684 100644 --- a/src/EditorFeatures/Core/Suggestions/RefineUsingCopilot/RefineUsingCopilotCodeAction.cs +++ b/src/EditorFeatures/Core/Suggestions/RefineUsingCopilot/RefineUsingCopilotCodeAction.cs @@ -59,7 +59,7 @@ protected override async Task> ComputeOperat // Consider if there could be better UX/platform support for such flavored actions // where clicking on the hyperlink needs to bring up another unrelated UI. - var newSolution = await originalCodeAction.GetChangedSolutionInternalAsync(originalSolution, progress, cancellationToken: cancellationToken).ConfigureAwait(false); + var newSolution = await originalCodeAction.GetChangedSolutionInternalAsync(originalSolution, progress, cancellationToken).ConfigureAwait(false); if (newSolution == null) return []; diff --git a/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource.cs b/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource.cs index 6c929302293d1..d209d08b0498c 100644 --- a/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource.cs +++ b/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource.cs @@ -11,7 +11,6 @@ using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Threading; using Microsoft.CodeAnalysis.Workspaces; using Microsoft.VisualStudio.Text; @@ -336,7 +335,7 @@ private void RaiseTagsChanged(ITextBuffer buffer, DiffResult difference) } OnTagsChangedForBuffer( - [KeyValuePairUtil.Create(buffer, difference)], + [KeyValuePair.Create(buffer, difference)], highPriority: false); } } diff --git a/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_TagsChanged.cs b/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_TagsChanged.cs index a0862bffeebb7..c81993f1f283d 100644 --- a/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_TagsChanged.cs +++ b/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_TagsChanged.cs @@ -50,14 +50,14 @@ private ValueTask ProcessTagsChangedAsync( foreach (var collection in snapshotSpans) { - if (collection.Count == 0) + if (collection is not ([var firstSpan, ..] and [.., var lastSpan])) continue; - var snapshot = collection.First().Snapshot; + var snapshot = firstSpan.Snapshot; // Coalesce the spans if there are a lot of them. var coalesced = collection.Count > CoalesceDifferenceCount - ? new NormalizedSnapshotSpanCollection(snapshot.GetSpanFromBounds(collection.First().Start, collection.Last().End)) + ? new NormalizedSnapshotSpanCollection(snapshot.GetSpanFromBounds(firstSpan.Start, lastSpan.End)) : collection; _dataSource.BeforeTagsChanged(snapshot); diff --git a/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.cs b/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.cs index 6a09fbf6164d9..b0f36225c007f 100644 --- a/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.cs +++ b/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.cs @@ -24,6 +24,7 @@ using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; +using Microsoft.CodeAnalysis.Collections; namespace Microsoft.CodeAnalysis.Editor.Tagging; diff --git a/src/EditorFeatures/Core/Tagging/AsynchronousViewportTaggerProvider.SingleViewportTaggerProvider.cs b/src/EditorFeatures/Core/Tagging/AsynchronousViewportTaggerProvider.SingleViewportTaggerProvider.cs index 8d26290225dda..079df1441acf3 100644 --- a/src/EditorFeatures/Core/Tagging/AsynchronousViewportTaggerProvider.SingleViewportTaggerProvider.cs +++ b/src/EditorFeatures/Core/Tagging/AsynchronousViewportTaggerProvider.SingleViewportTaggerProvider.cs @@ -7,13 +7,13 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Tagging; @@ -74,12 +74,11 @@ protected override bool CancelOnNewWork // that, determine the start/end line for the buffer that is in view. var visibleSpan = textView.TextViewLines.FormattedSpan; var visibleSpansInBuffer = textView.BufferGraph.MapDownToBuffer(visibleSpan, SpanTrackingMode.EdgeInclusive, subjectBuffer); - if (visibleSpansInBuffer.Count == 0) + if (visibleSpansInBuffer is not ([var firstVisibleSpan, ..] and [.., var lastVisibleSpan])) return null; - var visibleStart = visibleSpansInBuffer.First().Start; - var visibleEnd = visibleSpansInBuffer.Last().End; - + var visibleStart = firstVisibleSpan.Start; + var visibleEnd = lastVisibleSpan.End; var snapshot = subjectBuffer.CurrentSnapshot; var startLine = visibleStart.GetContainingLineNumber(); var endLine = visibleEnd.GetContainingLineNumber(); diff --git a/src/EditorFeatures/Core/Tagging/AsynchronousViewportTaggerProvider.cs b/src/EditorFeatures/Core/Tagging/AsynchronousViewportTaggerProvider.cs index db3a31b0f6930..d0a95c2cf91a8 100644 --- a/src/EditorFeatures/Core/Tagging/AsynchronousViewportTaggerProvider.cs +++ b/src/EditorFeatures/Core/Tagging/AsynchronousViewportTaggerProvider.cs @@ -5,6 +5,7 @@ using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Collections; diff --git a/src/EditorFeatures/Core/Tagging/TaggerMainThreadManager.cs b/src/EditorFeatures/Core/Tagging/TaggerMainThreadManager.cs index b850082da78a1..d47b1c406b2d5 100644 --- a/src/EditorFeatures/Core/Tagging/TaggerMainThreadManager.cs +++ b/src/EditorFeatures/Core/Tagging/TaggerMainThreadManager.cs @@ -10,7 +10,7 @@ using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Threading; -using TaggerUIData = (bool isVisible, Microsoft.VisualStudio.Text.SnapshotPoint? caretPosition, Roslyn.Utilities.OneOrMany spansToTag); +using TaggerUIData = (bool isVisible, Microsoft.VisualStudio.Text.SnapshotPoint? caretPosition, Microsoft.CodeAnalysis.Collections.OneOrMany spansToTag); namespace Microsoft.CodeAnalysis.Editor.Tagging; diff --git a/src/EditorFeatures/Core/Undo/EditorSourceTextUndoService.cs b/src/EditorFeatures/Core/Undo/EditorSourceTextUndoService.cs index d1d716ca6b7ab..872d7bf2d23a4 100644 --- a/src/EditorFeatures/Core/Undo/EditorSourceTextUndoService.cs +++ b/src/EditorFeatures/Core/Undo/EditorSourceTextUndoService.cs @@ -4,14 +4,14 @@ #nullable disable +using System; using System.Collections.Generic; using System.Composition; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; -using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Text; -using System; +using Microsoft.VisualStudio.Text.Operations; namespace Microsoft.CodeAnalysis.Editor.Undo; diff --git a/src/EditorFeatures/Core/Workspaces/AbstractTextBufferVisibilityTracker.cs b/src/EditorFeatures/Core/Workspaces/AbstractTextBufferVisibilityTracker.cs index 31e0d68b529db..c3c83d4f76dbf 100644 --- a/src/EditorFeatures/Core/Workspaces/AbstractTextBufferVisibilityTracker.cs +++ b/src/EditorFeatures/Core/Workspaces/AbstractTextBufferVisibilityTracker.cs @@ -7,6 +7,7 @@ using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; diff --git a/src/EditorFeatures/Core/WpfClassificationExtensions.cs b/src/EditorFeatures/Core/WpfClassificationExtensions.cs index 0d71aa01edbb5..822e342d3e66e 100644 --- a/src/EditorFeatures/Core/WpfClassificationExtensions.cs +++ b/src/EditorFeatures/Core/WpfClassificationExtensions.cs @@ -14,7 +14,6 @@ using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Text.Classification; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions; diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest.cs b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest.cs index 0bcab4d1337bf..0c1a3714ff676 100644 --- a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest.cs +++ b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest.cs @@ -855,14 +855,17 @@ static void VerifyCodeAction( { var messageSuffix = codeAction.EquivalenceKey != null ? string.Empty - : @" -Consider using the title as the equivalence key instead of 'null'"; - - Assert.False(true, @$"Expected different 'CodeAction.EquivalenceKey' for code actions registered for same diagnostic: -- Name: '{provider.GetType().Name}' -- Title 1: '{codeAction.Title}' -- Title 2: '{existingTitle}' -- Shared equivalence key: '{codeAction.EquivalenceKey ?? ""}'{messageSuffix}"); + : """ + Consider using the title as the equivalence key instead of 'null' + """; + + Assert.False(true, $""" + Expected different 'CodeAction.EquivalenceKey' for code actions registered for same diagnostic: + - Name: '{provider.GetType().Name}' + - Title 1: '{codeAction.Title}' + - Title 2: '{existingTitle}' + - Shared equivalence key: '{codeAction.EquivalenceKey ?? ""}'{messageSuffix} + """); } } } diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionTest.cs b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionTest.cs index aa5f7030fb9f9..7090b5e0b51a7 100644 --- a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionTest.cs +++ b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionTest.cs @@ -166,10 +166,7 @@ internal static void EnableOptions( internal static void EnableOption(ImmutableArray options, string id) { var option = options.FirstOrDefault(o => o.Id == id); - if (option != null) - { - option.Value = true; - } + option?.Value = true; } internal Task TestWithPickMembersDialogAsync( diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractUserDiagnosticTest.cs b/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractUserDiagnosticTest.cs index eccfc3fcc3938..370c8dd53a4b4 100644 --- a/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractUserDiagnosticTest.cs +++ b/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractUserDiagnosticTest.cs @@ -209,7 +209,7 @@ private static FixAllState GetFixAllState( if (scope == FixAllScope.Custom) { // Bulk fixing diagnostics in selected scope. - var diagnosticsToFix = ImmutableDictionary.CreateRange([KeyValuePairUtil.Create(document, diagnostics.ToImmutableArray())]); + var diagnosticsToFix = ImmutableDictionary.CreateRange([KeyValuePair.Create(document, diagnostics.ToImmutableArray())]); return FixAllState.Create(fixAllProvider, diagnosticsToFix, fixer, equivalenceKey); } diff --git a/src/EditorFeatures/Test/CodeFixes/CodeFixServiceTests.cs b/src/EditorFeatures/Test/CodeFixes/CodeFixServiceTests.cs index 505d948836c40..8b214d9fb4949 100644 --- a/src/EditorFeatures/Test/CodeFixes/CodeFixServiceTests.cs +++ b/src/EditorFeatures/Test/CodeFixes/CodeFixServiceTests.cs @@ -39,9 +39,9 @@ public sealed class CodeFixServiceTests public async Task TestGetFirstDiagnosticWithFixAsync() { var fixers = CreateFixers(); - var code = @" - a -"; + var code = """ + a + """; using var workspace = TestWorkspace.CreateCSharp(code, composition: s_compositionWithMockDiagnosticUpdateSourceRegistrationService, openDocuments: true); var diagnosticService = workspace.Services.GetRequiredService(); @@ -217,52 +217,36 @@ public async Task TestGetFixesAsyncForGeneratorDiagnosticAsync() } [Fact] - public async Task TestGetCodeFixWithExceptionInRegisterMethod_Diagnostic() - { - await GetFirstDiagnosticWithFixWithExceptionValidationAsync(new ErrorCases.ExceptionInRegisterMethod()); - } + public Task TestGetCodeFixWithExceptionInRegisterMethod_Diagnostic() + => GetFirstDiagnosticWithFixWithExceptionValidationAsync(new ErrorCases.ExceptionInRegisterMethod()); [Fact] - public async Task TestGetCodeFixWithExceptionInRegisterMethod_Fixes() - { - await GetAddedFixesWithExceptionValidationAsync(new ErrorCases.ExceptionInRegisterMethod()); - } + public Task TestGetCodeFixWithExceptionInRegisterMethod_Fixes() + => GetAddedFixesWithExceptionValidationAsync(new ErrorCases.ExceptionInRegisterMethod()); [Fact] - public async Task TestGetCodeFixWithExceptionInRegisterMethodAsync_Diagnostic() - { - await GetFirstDiagnosticWithFixWithExceptionValidationAsync(new ErrorCases.ExceptionInRegisterMethodAsync()); - } + public Task TestGetCodeFixWithExceptionInRegisterMethodAsync_Diagnostic() + => GetFirstDiagnosticWithFixWithExceptionValidationAsync(new ErrorCases.ExceptionInRegisterMethodAsync()); [Fact] - public async Task TestGetCodeFixWithExceptionInRegisterMethodAsync_Fixes() - { - await GetAddedFixesWithExceptionValidationAsync(new ErrorCases.ExceptionInRegisterMethodAsync()); - } + public Task TestGetCodeFixWithExceptionInRegisterMethodAsync_Fixes() + => GetAddedFixesWithExceptionValidationAsync(new ErrorCases.ExceptionInRegisterMethodAsync()); [Fact] - public async Task TestGetCodeFixWithExceptionInFixableDiagnosticIds_Diagnostic() - { - await GetFirstDiagnosticWithFixWithExceptionValidationAsync(new ErrorCases.ExceptionInFixableDiagnosticIds()); - } + public Task TestGetCodeFixWithExceptionInFixableDiagnosticIds_Diagnostic() + => GetFirstDiagnosticWithFixWithExceptionValidationAsync(new ErrorCases.ExceptionInFixableDiagnosticIds()); [Fact] - public async Task TestGetCodeFixWithExceptionInFixableDiagnosticIds_Fixes() - { - await GetAddedFixesWithExceptionValidationAsync(new ErrorCases.ExceptionInFixableDiagnosticIds()); - } + public Task TestGetCodeFixWithExceptionInFixableDiagnosticIds_Fixes() + => GetAddedFixesWithExceptionValidationAsync(new ErrorCases.ExceptionInFixableDiagnosticIds()); [Fact(Skip = "https://github.com/dotnet/roslyn/issues/21533")] - public async Task TestGetCodeFixWithExceptionInFixableDiagnosticIds_Diagnostic2() - { - await GetFirstDiagnosticWithFixWithExceptionValidationAsync(new ErrorCases.ExceptionInFixableDiagnosticIds2()); - } + public Task TestGetCodeFixWithExceptionInFixableDiagnosticIds_Diagnostic2() + => GetFirstDiagnosticWithFixWithExceptionValidationAsync(new ErrorCases.ExceptionInFixableDiagnosticIds2()); [Fact(Skip = "https://github.com/dotnet/roslyn/issues/21533")] - public async Task TestGetCodeFixWithExceptionInFixableDiagnosticIds_Fixes2() - { - await GetAddedFixesWithExceptionValidationAsync(new ErrorCases.ExceptionInFixableDiagnosticIds2()); - } + public Task TestGetCodeFixWithExceptionInFixableDiagnosticIds_Fixes2() + => GetAddedFixesWithExceptionValidationAsync(new ErrorCases.ExceptionInFixableDiagnosticIds2()); [Fact] public async Task TestGetCodeFixWithExceptionInGetFixAllProvider() @@ -874,7 +858,7 @@ public async Task TestAdditionalDocumentCodeFixAsync() // Verify code fix application var codeAction = txtDocumentCodeFixes.Single(s => s.Fixes.Single().Action.Title == fixer1.Title).Fixes.Single().Action; - var solution = await codeAction.GetChangedSolutionInternalAsync(txtDocument.Project.Solution, CodeAnalysisProgress.None); + var solution = await codeAction.GetChangedSolutionInternalAsync(txtDocument.Project.Solution, CodeAnalysisProgress.None, CancellationToken.None); var changedtxtDocument = solution!.Projects.Single().AdditionalDocuments.Single(t => t.Id == txtDocument.Id); Assert.Equal("Additional Document", txtDocument.GetTextSynchronously(CancellationToken.None).ToString()); Assert.Equal($"Additional Document{fixer1.Title}", changedtxtDocument.GetTextSynchronously(CancellationToken.None).ToString()); @@ -1012,15 +996,16 @@ public async Task TestGetFixesWithDeprioritizedAnalyzerAsync( var expectDeprioritization = GetExpectDeprioritization(actionKind, diagnosticOnFixLineInPriorSnapshot, addNewLineWithEdit); var priorSnapshotFixLine = diagnosticOnFixLineInPriorSnapshot ? "int x1 = 0;" : "System.Console.WriteLine();"; - var code = $@" -#pragma warning disable CS0219 -class C -{{ - void M() - {{ - {priorSnapshotFixLine} - }} -}}"; + var code = $$""" + #pragma warning disable CS0219 + class C + { + void M() + { + {{priorSnapshotFixLine}} + } + } + """; var codeFix = new FixerForDeprioritizedAnalyzer(); var analyzer = new DeprioritizedAnalyzer(actionKind); diff --git a/src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.CSharp.cs b/src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.CSharp.cs index 7e8424d770fc7..8116117a18b60 100644 --- a/src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.CSharp.cs +++ b/src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.CSharp.cs @@ -31,231 +31,190 @@ public sealed partial class CodeGenerationTests public class CSharp { [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddNamespace() - { - var input = "namespace [|N1|] { }"; - var expected = @"namespace N1 { - namespace N2 - { - } -}"; - await TestAddNamespaceAsync(input, expected, + public Task AddNamespace() + => TestAddNamespaceAsync("namespace [|N1|] { }", """ + namespace N1 { + namespace N2 + { + } + } + """, name: "N2"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddField() - { - var input = "class [|C|] { }"; - var expected = @"class C -{ - public int F; -}"; - await TestAddFieldAsync(input, expected, + public Task AddField() + => TestAddFieldAsync("class [|C|] { }", """ + class C + { + public int F; + } + """, type: GetTypeSymbol(typeof(int))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddStaticField() - { - var input = "class [|C|] { }"; - var expected = @"class C -{ - private static string F; -}"; - await TestAddFieldAsync(input, expected, + public Task AddStaticField() + => TestAddFieldAsync("class [|C|] { }", """ + class C + { + private static string F; + } + """, type: GetTypeSymbol(typeof(string)), accessibility: Accessibility.Private, modifiers: new Editing.DeclarationModifiers(isStatic: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddArrayField() - { - var input = "class [|C|] { }"; - var expected = @"class C -{ - public int[] F; -}"; - await TestAddFieldAsync(input, expected, + public Task AddArrayField() + => TestAddFieldAsync("class [|C|] { }", """ + class C + { + public int[] F; + } + """, type: CreateArrayType(typeof(int))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddUnsafeField() - { - var input = "class [|C|] { }"; - var expected = @"class C -{ - public unsafe int F; -}"; - await TestAddFieldAsync(input, expected, + public Task AddUnsafeField() + => TestAddFieldAsync("class [|C|] { }", """ + class C + { + public unsafe int F; + } + """, modifiers: new Editing.DeclarationModifiers(isUnsafe: true), type: GetTypeSymbol(typeof(int))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddFieldToCompilationUnit() - { - var input = ""; - var expected = "public int F;\n"; - await TestAddFieldAsync(input, expected, + public Task AddFieldToCompilationUnit() + => TestAddFieldAsync("", "public int F;\n", type: GetTypeSymbol(typeof(int)), addToCompilationUnit: true); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddConstructor() - { - var input = "class [|C|] { }"; - var expected = @"class C -{ - public C() - { - } -}"; - await TestAddConstructorAsync(input, expected); - } + public Task AddConstructor() + => TestAddConstructorAsync("class [|C|] { }", """ + class C + { + public C() + { + } + } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddConstructorWithoutBody() - { - var input = "class [|C|] { }"; - var expected = @"class C -{ - public C(); -}"; - await TestAddConstructorAsync(input, expected, + public Task AddConstructorWithoutBody() + => TestAddConstructorAsync("class [|C|] { }", """ + class C + { + public C(); + } + """, context: new CodeGenerationContext(generateMethodBodies: false)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddConstructorResolveNamespaceImport() - { - var input = "class [|C|] { }"; - var expected = @"using System; + public Task AddConstructorResolveNamespaceImport() + => TestAddConstructorAsync("class [|C|] { }", """ + using System; -class C -{ - public C(DateTime dt, int i) - { - } -}"; - await TestAddConstructorAsync(input, expected, + class C + { + public C(DateTime dt, int i) + { + } + } + """, parameters: Parameters(Parameter(typeof(DateTime), "dt"), Parameter(typeof(int), "i"))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddChainedConstructor() - { - var input = "class [|C|] { public C(int i) { } }"; - var expected = "class C { public C() : this(42) { } public C(int i) { } }"; - await TestAddConstructorAsync(input, expected, + public Task AddChainedConstructor() + => TestAddConstructorAsync("class [|C|] { public C(int i) { } }", "class C { public C() : this(42) { } public C(int i) { } }", thisArguments: [CS.SyntaxFactory.ParseExpression("42")]); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddStaticConstructor() - { - var input = "class [|C|] { }"; - var expected = @"class C -{ - static C() - { - } -}"; - await TestAddConstructorAsync(input, expected, + public Task AddStaticConstructor() + => TestAddConstructorAsync("class [|C|] { }", """ + class C + { + static C() + { + } + } + """, modifiers: new Editing.DeclarationModifiers(isStatic: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544082")] - public async Task AddClass() - { - var input = "namespace [|N|] { }"; - var expected = @"namespace N -{ - public class C - { - } -}"; - await TestAddNamedTypeAsync(input, expected); - } + public Task AddClass() + => TestAddNamedTypeAsync("namespace [|N|] { }", """ + namespace N + { + public class C + { + } + } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddClassEscapeName() - { - var input = "namespace [|N|] { }"; - var expected = @"namespace N -{ - public class @class - { - } -}"; - await TestAddNamedTypeAsync(input, expected, + public Task AddClassEscapeName() + => TestAddNamedTypeAsync("namespace [|N|] { }", """ + namespace N + { + public class @class + { + } + } + """, name: "class"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddClassUnicodeName() - { - var input = "namespace [|N|] { }"; - var expected = @"namespace N -{ - public class classæøå - { - } -}"; - await TestAddNamedTypeAsync(input, expected, + public Task AddClassUnicodeName() + => TestAddNamedTypeAsync("namespace [|N|] { }", """ + namespace N + { + public class classæøå + { + } + } + """, name: "classæøå"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544405")] - public async Task AddStaticClass() - { - var input = "namespace [|N|] { }"; - var expected = @"namespace N -{ - public static class C - { - } -}"; - await TestAddNamedTypeAsync(input, expected, + public Task AddStaticClass() + => TestAddNamedTypeAsync("namespace [|N|] { }", """ + namespace N + { + public static class C + { + } + } + """, modifiers: new Editing.DeclarationModifiers(isStatic: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544405")] - public async Task AddStaticAbstractClass() - { - var input = "namespace [|N|] { }"; - var expected = @"namespace N -{ - public static class C - { - } -}"; - // note that 'abstract' is dropped here - await TestAddNamedTypeAsync(input, expected, + public Task AddStaticAbstractClass() + => TestAddNamedTypeAsync("namespace [|N|] { }", """ + namespace N + { + public static class C + { + } + } + """, modifiers: new Editing.DeclarationModifiers(isStatic: true, isAbstract: true)); - } [Theory, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544405")] [InlineData(Accessibility.NotApplicable)] [InlineData(Accessibility.Internal)] [InlineData(Accessibility.Public)] - public async Task AddFileClass(Accessibility accessibility) - { - var input = "namespace [|N|] { }"; - var expected = @"namespace N -{ - file class C - { - } -}"; - // note: when invalid combinations of modifiers+accessibility are present here, - // we actually drop the accessibility. This is similar to what is done if someone declares a 'static abstract class C { }'. - await TestAddNamedTypeAsync(input, expected, + public Task AddFileClass(Accessibility accessibility) + => TestAddNamedTypeAsync("namespace [|N|] { }", """ + namespace N + { + file class C + { + } + } + """, accessibility: accessibility, modifiers: new Editing.DeclarationModifiers(isFile: true)); - } [Theory, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544405")] [InlineData("struct", TypeKind.Struct)] @@ -263,417 +222,381 @@ await TestAddNamedTypeAsync(input, expected, [InlineData("enum", TypeKind.Enum)] public async Task AddFileType(string kindString, TypeKind typeKind) { - var input = "namespace [|N|] { }"; - var expected = @"namespace N -{ - file " + kindString + @" C - { - } -}"; - await TestAddNamedTypeAsync(input, expected, + var expected = """ + namespace N + { + file + """ + kindString + """ + C + { + } + } + """; + await TestAddNamedTypeAsync("namespace [|N|] { }", expected, typeKind: typeKind, modifiers: new Editing.DeclarationModifiers(isFile: true)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544405")] - public async Task AddSealedClass() - { - var input = "namespace [|N|] { }"; - var expected = @"namespace N -{ - private sealed class C - { - } -}"; - await TestAddNamedTypeAsync(input, expected, + public Task AddSealedClass() + => TestAddNamedTypeAsync("namespace [|N|] { }", """ + namespace N + { + private sealed class C + { + } + } + """, accessibility: Accessibility.Private, modifiers: new Editing.DeclarationModifiers(isSealed: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544405")] - public async Task AddAbstractClass() - { - var input = "namespace [|N|] { }"; - var expected = @"namespace N -{ - protected internal abstract class C - { - } -}"; - await TestAddNamedTypeAsync(input, expected, + public Task AddAbstractClass() + => TestAddNamedTypeAsync("namespace [|N|] { }", """ + namespace N + { + protected internal abstract class C + { + } + } + """, accessibility: Accessibility.ProtectedOrInternal, modifiers: new Editing.DeclarationModifiers(isAbstract: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddStruct() - { - var input = "namespace [|N|] { }"; - var expected = @"namespace N -{ - internal struct S - { - } -}"; - await TestAddNamedTypeAsync(input, expected, + public Task AddStruct() + => TestAddNamedTypeAsync("namespace [|N|] { }", """ + namespace N + { + internal struct S + { + } + } + """, name: "S", accessibility: Accessibility.Internal, typeKind: TypeKind.Struct); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546224")] - public async Task AddSealedStruct() - { - var input = "namespace [|N|] { }"; - var expected = @"namespace N -{ - public struct S - { - } -}"; - await TestAddNamedTypeAsync(input, expected, + public Task AddSealedStruct() + => TestAddNamedTypeAsync("namespace [|N|] { }", """ + namespace N + { + public struct S + { + } + } + """, name: "S", modifiers: new Editing.DeclarationModifiers(isSealed: true), accessibility: Accessibility.Public, typeKind: TypeKind.Struct); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddInterface() - { - var input = "namespace [|N|] { }"; - var expected = @"namespace N -{ - public interface I - { - } -}"; - await TestAddNamedTypeAsync(input, expected, + public Task AddInterface() + => TestAddNamedTypeAsync("namespace [|N|] { }", """ + namespace N + { + public interface I + { + } + } + """, name: "I", typeKind: TypeKind.Interface); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544080")] - public async Task AddEnum() - { - var input = "namespace [|N|] { }"; - var expected = @"namespace N -{ - public enum E - { - } -}"; - await TestAddNamedTypeAsync(input, expected, "E", + public Task AddEnum() + => TestAddNamedTypeAsync("namespace [|N|] { }", """ + namespace N + { + public enum E + { + } + } + """, "E", typeKind: TypeKind.Enum); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544527")] - public async Task AddEnumWithValues() - { - var input = "namespace [|N|] { }"; - var expected = @"namespace N -{ - public enum E - { - F1 = 1, - F2 = 2 - } -}"; - await TestAddNamedTypeAsync(input, expected, "E", + public Task AddEnumWithValues() + => TestAddNamedTypeAsync("namespace [|N|] { }", """ + namespace N + { + public enum E + { + F1 = 1, + F2 = 2 + } + } + """, "E", typeKind: TypeKind.Enum, members: Members(CreateEnumField("F1", 1), CreateEnumField("F2", 2))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544080")] - public async Task AddDelegateType() - { - var input = "class [|C|] { }"; - var expected = @"class C -{ - public delegate int D(string s); -}"; - await TestAddDelegateTypeAsync(input, expected, + public Task AddDelegateType() + => TestAddDelegateTypeAsync("class [|C|] { }", """ + class C + { + public delegate int D(string s); + } + """, returnType: typeof(int), parameters: Parameters(Parameter(typeof(string), "s"))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546224")] - public async Task AddSealedDelegateType() - { - var input = "class [|C|] { }"; - var expected = @"class C -{ - public delegate int D(string s); -}"; - await TestAddDelegateTypeAsync(input, expected, + public Task AddSealedDelegateType() + => TestAddDelegateTypeAsync("class [|C|] { }", """ + class C + { + public delegate int D(string s); + } + """, returnType: typeof(int), parameters: Parameters(Parameter(typeof(string), "s")), modifiers: new Editing.DeclarationModifiers(isSealed: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddEvent() - { - var input = "class [|C|] { }"; - var expected = @"class C -{ - public event System.Action E; -}"; - await TestAddEventAsync(input, expected, + public Task AddEvent() + => TestAddEventAsync("class [|C|] { }", """ + class C + { + public event System.Action E; + } + """, context: new CodeGenerationContext(addImports: false)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public async Task AddCustomEventToClassFromSourceSymbol() { - var sourceGenerated = @"class [|C2|] -{ - event EventHandler Click - { - add - { - Events.AddHandler(""ClickEvent"", value) - } - remove - { - Events.RemoveHandler(""ClickEvent"", value) - } - } -}"; - var input = "class [|C1|] { }"; - var expected = @"class C1 -{ - event EventHandler Click - { - add - { - Events.AddHandler(""ClickEvent"", value) - } - remove - { - Events.RemoveHandler(""ClickEvent"", value) - } - } -}"; var context = new CodeGenerationContext(reuseSyntax: true); - await TestGenerateFromSourceSymbolAsync(sourceGenerated, input, expected, onlyGenerateMembers: true, context: context); + await TestGenerateFromSourceSymbolAsync(""" + class [|C2|] + { + event EventHandler Click + { + add + { + Events.AddHandler("ClickEvent", value) + } + remove + { + Events.RemoveHandler("ClickEvent", value) + } + } + } + """, "class [|C1|] { }", """ + class C1 + { + event EventHandler Click + { + add + { + Events.AddHandler("ClickEvent", value) + } + remove + { + Events.RemoveHandler("ClickEvent", value) + } + } + } + """, onlyGenerateMembers: true, context: context); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddUnsafeEvent() - { - var input = "class [|C|] { }"; - var expected = @"class C -{ - public unsafe event System.Action E; -}"; - await TestAddEventAsync(input, expected, + public Task AddUnsafeEvent() + => TestAddEventAsync("class [|C|] { }", """ + class C + { + public unsafe event System.Action E; + } + """, modifiers: new Editing.DeclarationModifiers(isUnsafe: true), context: new CodeGenerationContext(addImports: false)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddEventWithAccessors() - { - var input = "class [|C|] { }"; - var expected = @"class C -{ - public event System.Action E - { - add - { - } - - remove - { - } - } -}"; - await TestAddEventAsync(input, expected, + public Task AddEventWithAccessors() + => TestAddEventAsync("class [|C|] { }", """ + class C + { + public event System.Action E + { + add + { + } + + remove + { + } + } + } + """, addMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol([], Accessibility.NotApplicable, []), removeMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol([], Accessibility.NotApplicable, []), context: new CodeGenerationContext(addImports: false)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddMethodToClass() - { - var input = "class [|C|] { }"; - var expected = @"class C -{ - public void M() - { - } -}"; - await TestAddMethodAsync(input, expected, + public Task AddMethodToClass() + => TestAddMethodAsync("class [|C|] { }", """ + class C + { + public void M() + { + } + } + """, returnType: typeof(void)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public async Task AddMethodToClassFromSourceSymbol() { - var sourceGenerated = @"class [|C2|] -{ - public int FInt() - { - return 0; - } -}"; - var input = "class [|C1|] { }"; - var expected = @"class C1 -{ - public int FInt() - { - return 0; - } -}"; var context = new CodeGenerationContext(reuseSyntax: true); - await TestGenerateFromSourceSymbolAsync(sourceGenerated, input, expected, onlyGenerateMembers: true, context: context); + await TestGenerateFromSourceSymbolAsync(""" + class [|C2|] + { + public int FInt() + { + return 0; + } + } + """, "class [|C1|] { }", """ + class C1 + { + public int FInt() + { + return 0; + } + } + """, onlyGenerateMembers: true, context: context); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddMethodToClassEscapedName() - { - var input = "class [|C|] { }"; - var expected = @"using System; + public Task AddMethodToClassEscapedName() + => TestAddMethodAsync("class [|C|] { }", """ + using System; -class C -{ - public DateTime @static() - { - } -}"; - await TestAddMethodAsync(input, expected, + class C + { + public DateTime @static() + { + } + } + """, name: "static", returnType: typeof(DateTime)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddStaticMethodToStruct() - { - var input = "struct [|S|] { }"; - var expected = @"struct S -{ - public static int M() - { - $$ - } -}"; - await TestAddMethodAsync(input, expected, + public Task AddStaticMethodToStruct() + => TestAddMethodAsync("struct [|S|] { }", """ + struct S + { + public static int M() + { + $$ + } + } + """, modifiers: new Editing.DeclarationModifiers(isStatic: true), returnType: typeof(int), statements: "return 0;"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddSealedOverrideMethod() - { - var input = "class [|C|] { }"; - var expected = @"class C -{ - public sealed override int GetHashCode() - { - $$ - } -}"; - await TestAddMethodAsync(input, expected, + public Task AddSealedOverrideMethod() + => TestAddMethodAsync("class [|C|] { }", """ + class C + { + public sealed override int GetHashCode() + { + $$ + } + } + """, name: "GetHashCode", modifiers: new Editing.DeclarationModifiers(isOverride: true, isSealed: true), returnType: typeof(int), statements: "return 0;"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAbstractMethod() - { - var input = "abstract class [|C|] { }"; - var expected = @"abstract class C -{ - public abstract int M(); -}"; - await TestAddMethodAsync(input, expected, + public Task AddAbstractMethod() + => TestAddMethodAsync("abstract class [|C|] { }", """ + abstract class C + { + public abstract int M(); + } + """, modifiers: new Editing.DeclarationModifiers(isAbstract: true), returnType: typeof(int)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddMethodWithoutBody() - { - var input = "class [|C|] { }"; - var expected = @"class C -{ - public int M(); -}"; - await TestAddMethodAsync(input, expected, + public Task AddMethodWithoutBody() + => TestAddMethodAsync("class [|C|] { }", """ + class C + { + public int M(); + } + """, returnType: typeof(int), context: new CodeGenerationContext(generateMethodBodies: false)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddGenericMethod() - { - var input = "class [|C|] { }"; - var expected = @"class C -{ - public int M() - { - $$ - } -}"; - await TestAddMethodAsync(input, expected, + public Task AddGenericMethod() + => TestAddMethodAsync("class [|C|] { }", """ + class C + { + public int M() + { + $$ + } + } + """, returnType: typeof(int), typeParameters: [CodeGenerationSymbolFactory.CreateTypeParameterSymbol("T")], statements: "return new T().GetHashCode();"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddVirtualMethod() - { - var input = "class [|C|] { }"; - var expected = @"class C -{ - protected virtual int M() - { - $$ - } -}"; - await TestAddMethodAsync(input, expected, + public Task AddVirtualMethod() + => TestAddMethodAsync("class [|C|] { }", """ + class C + { + protected virtual int M() + { + $$ + } + } + """, accessibility: Accessibility.Protected, modifiers: new Editing.DeclarationModifiers(isVirtual: true), returnType: typeof(int), statements: "return 0;"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddUnsafeNewMethod() - { - var input = "class [|C|] { }"; - var expected = @"class C -{ - public unsafe new string ToString() - { - $$ - } -}"; - await TestAddMethodAsync(input, expected, + public Task AddUnsafeNewMethod() + => TestAddMethodAsync("class [|C|] { }", """ + class C + { + public unsafe new string ToString() + { + $$ + } + } + """, name: "ToString", modifiers: new Editing.DeclarationModifiers(isNew: true, isUnsafe: true), returnType: typeof(string), statements: "return String.Empty;"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public async Task AddExplicitImplementationOfUnsafeMethod() { var input = "interface I { unsafe void M(int i); } class [|C|] : I { }"; - var expected = @"interface I { unsafe void M(int i); } -class C : I -{ - unsafe void I.M(int i) - { - } -}"; - await TestAddMethodAsync(input, expected, + await TestAddMethodAsync(input, """ + interface I { unsafe void M(int i); } + class C : I + { + unsafe void I.M(int i) + { + } + } + """, name: "M", returnType: typeof(void), parameters: Parameters(Parameter(typeof(int), "i")), @@ -685,14 +608,15 @@ await TestAddMethodAsync(input, expected, public async Task AddExplicitImplementation() { var input = "interface I { void M(int i); } class [|C|] : I { }"; - var expected = @"interface I { void M(int i); } -class C : I -{ - void I.M(int i) - { - } -}"; - await TestAddMethodAsync(input, expected, + await TestAddMethodAsync(input, """ + interface I { void M(int i); } + class C : I + { + void I.M(int i) + { + } + } + """, name: "M", returnType: typeof(void), parameters: Parameters(Parameter(typeof(int), "i")), @@ -700,73 +624,70 @@ await TestAddMethodAsync(input, expected, } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddTrueFalseOperators() - { - var input = @" -class [|C|] -{ -}"; - var expected = @" -class C -{ - public static bool operator true(C other) - { - $$ - } - - public static bool operator false(C other) - { - $$ - } -}"; - await TestAddOperatorsAsync(input, expected, + public Task AddTrueFalseOperators() + => TestAddOperatorsAsync(""" + class [|C|] + { + } + """, """ + class C + { + public static bool operator true(C other) + { + $$ + } + + public static bool operator false(C other) + { + $$ + } + } + """, [CodeGenerationOperatorKind.True, CodeGenerationOperatorKind.False], parameters: Parameters(Parameter("C", "other")), returnType: typeof(bool), statements: "return false;"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddUnaryOperators() - { - var input = @" -class [|C|] -{ -}"; - var expected = @" -class C -{ - public static object operator +(C other) - { - $$ - } - - public static object operator -(C other) - { - $$ - } - - public static object operator !(C other) - { - $$ - } - - public static object operator ~(C other) - { - $$ - } - - public static object operator ++(C other) - { - $$ - } - - public static object operator --(C other) - { - $$ - } -}"; - await TestAddOperatorsAsync(input, expected, + public Task AddUnaryOperators() + => TestAddOperatorsAsync(""" + class [|C|] + { + } + """, """ + class C + { + public static object operator +(C other) + { + $$ + } + + public static object operator -(C other) + { + $$ + } + + public static object operator !(C other) + { + $$ + } + + public static object operator ~(C other) + { + $$ + } + + public static object operator ++(C other) + { + $$ + } + + public static object operator --(C other) + { + $$ + } + } + """, [ CodeGenerationOperatorKind.UnaryPlus, CodeGenerationOperatorKind.UnaryNegation, @@ -778,69 +699,67 @@ await TestAddOperatorsAsync(input, expected, parameters: Parameters(Parameter("C", "other")), returnType: typeof(object), statements: "return null;"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddBinaryOperators() - { - var input = @" -class [|C|] -{ -}"; - var expected = @" -class C -{ - public static object operator +(C a, C b) - { - $$ - } - - public static object operator -(C a, C b) - { - $$ - } - - public static object operator *(C a, C b) - { - $$ - } - - public static object operator /(C a, C b) - { - $$ - } - - public static object operator %(C a, C b) - { - $$ - } - - public static object operator &(C a, C b) - { - $$ - } - - public static object operator |(C a, C b) - { - $$ - } - - public static object operator ^(C a, C b) - { - $$ - } - - public static object operator <<(C a, C b) - { - $$ - } - - public static object operator >>(C a, C b) - { - $$ - } -}"; - await TestAddOperatorsAsync(input, expected, + public Task AddBinaryOperators() + => TestAddOperatorsAsync(""" + class [|C|] + { + } + """, """ + class C + { + public static object operator +(C a, C b) + { + $$ + } + + public static object operator -(C a, C b) + { + $$ + } + + public static object operator *(C a, C b) + { + $$ + } + + public static object operator /(C a, C b) + { + $$ + } + + public static object operator %(C a, C b) + { + $$ + } + + public static object operator &(C a, C b) + { + $$ + } + + public static object operator |(C a, C b) + { + $$ + } + + public static object operator ^(C a, C b) + { + $$ + } + + public static object operator <<(C a, C b) + { + $$ + } + + public static object operator >>(C a, C b) + { + $$ + } + } + """, [ CodeGenerationOperatorKind.Addition, CodeGenerationOperatorKind.Subtraction, @@ -852,53 +771,51 @@ await TestAddOperatorsAsync(input, expected, CodeGenerationOperatorKind.ExclusiveOr, CodeGenerationOperatorKind.LeftShift, CodeGenerationOperatorKind.RightShift - ], - parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")), - returnType: typeof(object), - statements: "return null;"); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddComparisonOperators() - { - var input = @" -class [|C|] -{ -}"; - var expected = @" -class C -{ - public static bool operator ==(C a, C b) - { - $$ - } - - public static bool operator !=(C a, C b) - { - $$ - } - - public static bool operator <(C a, C b) - { - $$ - } - - public static bool operator >(C a, C b) - { - $$ - } - - public static bool operator <=(C a, C b) - { - $$ - } + ], + parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")), + returnType: typeof(object), + statements: "return null;"); - public static bool operator >=(C a, C b) - { - $$ - } -}"; - await TestAddOperatorsAsync(input, expected, + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task AddComparisonOperators() + => TestAddOperatorsAsync(""" + class [|C|] + { + } + """, """ + class C + { + public static bool operator ==(C a, C b) + { + $$ + } + + public static bool operator !=(C a, C b) + { + $$ + } + + public static bool operator <(C a, C b) + { + $$ + } + + public static bool operator >(C a, C b) + { + $$ + } + + public static bool operator <=(C a, C b) + { + $$ + } + + public static bool operator >=(C a, C b) + { + $$ + } + } + """, [ CodeGenerationOperatorKind.Equality, CodeGenerationOperatorKind.Inequality, @@ -910,182 +827,146 @@ await TestAddOperatorsAsync(input, expected, parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")), returnType: typeof(bool), statements: "return true;"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddUnsupportedOperator() - { - var input = "class [|C|] { }"; - await TestAddUnsupportedOperatorAsync(input, + public Task AddUnsupportedOperator() + => TestAddUnsupportedOperatorAsync("class [|C|] { }", operatorKind: CodeGenerationOperatorKind.Like, parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")), returnType: typeof(bool), statements: "return true;"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddExplicitConversion() - { - var input = @"class [|C|] { }"; - var expected = @"class C -{ - public static explicit operator int(C other) - { - $$ - } -}"; - await TestAddConversionAsync(input, expected, + public Task AddExplicitConversion() + => TestAddConversionAsync(@"class [|C|] { }", """ + class C + { + public static explicit operator int(C other) + { + $$ + } + } + """, toType: typeof(int), fromType: Parameter("C", "other"), statements: "return 0;"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddImplicitConversion() - { - var input = @"class [|C|] { }"; - var expected = @"class C -{ - public static implicit operator int(C other) - { - $$ - } -}"; - await TestAddConversionAsync(input, expected, + public Task AddImplicitConversion() + => TestAddConversionAsync(@"class [|C|] { }", """ + class C + { + public static implicit operator int(C other) + { + $$ + } + } + """, toType: typeof(int), fromType: Parameter("C", "other"), isImplicit: true, statements: "return 0;"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddStatements() - { - var input = "class C { public void [|M|]() { Console.WriteLine(1); } }"; - var expected = "class C { public void M() { Console.WriteLine(1); $$} }"; - await TestAddStatementsAsync(input, expected, "Console.WriteLine(2);"); - } + public Task AddStatements() + => TestAddStatementsAsync("class C { public void [|M|]() { Console.WriteLine(1); } }", "class C { public void M() { Console.WriteLine(1); $$} }", "Console.WriteLine(2);"); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/840265")] - public async Task AddDefaultParameterWithNonDefaultValueToMethod() - { - var input = "class C { public void [|M|]() { } }"; - var expected = "class C { public void M(string text =\"Hello\") { } }"; - await TestAddParametersAsync(input, expected, + public Task AddDefaultParameterWithNonDefaultValueToMethod() + => TestAddParametersAsync("class C { public void [|M|]() { } }", "class C { public void M(string text =\"Hello\") { } }", Parameters(Parameter(typeof(string), "text", true, "Hello"))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddDefaultParameterWithDefaultValueToMethod() - { - var input = "class C { public void [|M|]() { } }"; - var expected = "class C { public void M(double number =0) { } }"; - await TestAddParametersAsync(input, expected, + public Task AddDefaultParameterWithDefaultValueToMethod() + => TestAddParametersAsync("class C { public void [|M|]() { } }", "class C { public void M(double number =0) { } }", Parameters(Parameter(typeof(double), "number", true))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddParametersToMethod() - { - var input = "class C { public void [|M|]() { } }"; - var expected = "class C { public void M(int num, string text =\"Hello!\", float floating =0.5F) { } }"; - await TestAddParametersAsync(input, expected, + public Task AddParametersToMethod() + => TestAddParametersAsync("class C { public void [|M|]() { } }", "class C { public void M(int num, string text =\"Hello!\", float floating =0.5F) { } }", Parameters(Parameter(typeof(int), "num"), Parameter(typeof(string), "text", true, "Hello!"), Parameter(typeof(float), "floating", true, .5f))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/841365")] - public async Task AddParamsParameterToMethod() - { - var input = "class C { public void [|M|]() { } }"; - var expected = "class C { public void M(params char[]characters) { } }"; - await TestAddParametersAsync(input, expected, + public Task AddParamsParameterToMethod() + => TestAddParametersAsync("class C { public void [|M|]() { } }", "class C { public void M(params char[]characters) { } }", Parameters(Parameter(typeof(char[]), "characters", isParams: true))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544015")] - public async Task AddAutoProperty() - { - var input = "class [|C|] { }"; - var expected = @"class C -{ - public int P { get; internal set; } -}"; - await TestAddPropertyAsync(input, expected, + public Task AddAutoProperty() + => TestAddPropertyAsync("class [|C|] { }", """ + class C + { + public int P { get; internal set; } + } + """, type: typeof(int), setterAccessibility: Accessibility.Internal); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddUnsafeAutoProperty() - { - var input = "class [|C|] { }"; - var expected = @"class C -{ - public unsafe int P { get; internal set; } -}"; - await TestAddPropertyAsync(input, expected, + public Task AddUnsafeAutoProperty() + => TestAddPropertyAsync("class [|C|] { }", """ + class C + { + public unsafe int P { get; internal set; } + } + """, type: typeof(int), modifiers: new Editing.DeclarationModifiers(isUnsafe: true), setterAccessibility: Accessibility.Internal); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public async Task AddPropertyToClassFromSourceSymbol() { - var sourceGenerated = @"class [|C2|] -{ - public int P - { - get - { - return 0; - } - } -}"; - var input = "class [|C1|] { }"; - var expected = @"class C1 -{ - public int P - { - get - { - return 0; - } - } -}"; var context = new CodeGenerationContext(reuseSyntax: true); - await TestGenerateFromSourceSymbolAsync(sourceGenerated, input, expected, onlyGenerateMembers: true, context: context); + await TestGenerateFromSourceSymbolAsync(""" + class [|C2|] + { + public int P + { + get + { + return 0; + } + } + } + """, "class [|C1|] { }", """ + class C1 + { + public int P + { + get + { + return 0; + } + } + } + """, onlyGenerateMembers: true, context: context); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddIndexer1() - { - var input = "class [|C|] { }"; - var expected = "class C { public string this[int i] => String.Empty; }"; - await TestAddPropertyAsync(input, expected, + public Task AddIndexer1() + => TestAddPropertyAsync("class [|C|] { }", "class C { public string this[int i] => String.Empty; }", type: typeof(string), parameters: Parameters(Parameter(typeof(int), "i")), getStatements: "return String.Empty;", isIndexer: true); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddIndexer2() - { - var input = "class [|C|] { }"; - var expected = @"class C -{ - public string this[int i] - { - get - { - $$ - } - } -}"; - await TestAddPropertyAsync(input, expected, + public Task AddIndexer2() + => TestAddPropertyAsync("class [|C|] { }", """ + class C + { + public string this[int i] + { + get + { + $$ + } + } + } + """, type: typeof(string), parameters: Parameters(Parameter(typeof(int), "i")), getStatements: "return String.Empty;", @@ -1095,249 +976,149 @@ await TestAddPropertyAsync(input, expected, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, }); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddParameterfulProperty() - { - var input = "class [|C|] { }"; - var expected = @"class C -{ - public string get_P(int i, int j) - { - $$ - } - - public void set_P(int i, int j, string value) - { - } -}"; - await TestAddPropertyAsync(input, expected, + public Task AddParameterfulProperty() + => TestAddPropertyAsync("class [|C|] { }", """ + class C + { + public string get_P(int i, int j) + { + $$ + } + + public void set_P(int i, int j, string value) + { + } + } + """, type: typeof(string), getStatements: "return String.Empty;", setStatements: "", parameters: Parameters(Parameter(typeof(int), "i"), Parameter(typeof(int), "j"))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToTypes() - { - var input = "class [|C|] { }"; - var expected = @"[System.Serializable] -class C { }"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task AddAttributeToTypes() + => TestAddAttributeAsync("class [|C|] { }", """ + [System.Serializable] + class C { } + """, typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeFromTypes() - { - var input = @"[System.Serializable] class [|C|] { }"; - var expected = "class C { }"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task RemoveAttributeFromTypes() + => TestRemoveAttributeAsync(@"[System.Serializable] class [|C|] { }", "class C { }", typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToMethods() - { - var input = "class C { public void [|M()|] { } }"; - var expected = "class C { [System.Serializable] public void M() { } }"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task AddAttributeToMethods() + => TestAddAttributeAsync("class C { public void [|M()|] { } }", "class C { [System.Serializable] public void M() { } }", typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeFromMethods() - { - var input = "class C { [System.Serializable] public void [|M()|] { } }"; - var expected = "class C { public void M() { } }"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task RemoveAttributeFromMethods() + => TestRemoveAttributeAsync("class C { [System.Serializable] public void [|M()|] { } }", "class C { public void M() { } }", typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToFields() - { - var input = "class C { [|public int F|]; }"; - var expected = "class C { [System.Serializable] public int F; }"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task AddAttributeToFields() + => TestAddAttributeAsync("class C { [|public int F|]; }", "class C { [System.Serializable] public int F; }", typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeFromFields() - { - var input = "class C { [System.Serializable] public int [|F|]; }"; - var expected = "class C { public int F; }"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task RemoveAttributeFromFields() + => TestRemoveAttributeAsync("class C { [System.Serializable] public int [|F|]; }", "class C { public int F; }", typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToProperties() - { - var input = "class C { public int [|P|] { get; set; }}"; - var expected = "class C { [System.Serializable] public int P { get; set; } }"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task AddAttributeToProperties() + => TestAddAttributeAsync("class C { public int [|P|] { get; set; }}", "class C { [System.Serializable] public int P { get; set; } }", typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeFromProperties() - { - var input = "class C { [System.Serializable] public int [|P|] { get; set; }}"; - var expected = "class C { public int P { get; set; } }"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task RemoveAttributeFromProperties() + => TestRemoveAttributeAsync("class C { [System.Serializable] public int [|P|] { get; set; }}", "class C { public int P { get; set; } }", typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToPropertyAccessor() - { - var input = "class C { public int P { [|get|]; set; }}"; - var expected = "class C { public int P { [System.Serializable] get; set; }}"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task AddAttributeToPropertyAccessor() + => TestAddAttributeAsync("class C { public int P { [|get|]; set; }}", "class C { public int P { [System.Serializable] get; set; }}", typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeFromPropertyAccessor() - { - var input = "class C { public int P { [System.Serializable] [|get|]; set; } }"; - var expected = "class C { public int P { get; set; } }"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task RemoveAttributeFromPropertyAccessor() + => TestRemoveAttributeAsync("class C { public int P { [System.Serializable] [|get|]; set; } }", "class C { public int P { get; set; } }", typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToEnums() - { - var input = "enum [|C|] { One, Two }"; - var expected = @"[System.Serializable] -enum C { One, Two }"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task AddAttributeToEnums() + => TestAddAttributeAsync("enum [|C|] { One, Two }", """ + [System.Serializable] + enum C { One, Two } + """, typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeFromEnums() - { - var input = "[System.Serializable] enum [|C|] { One, Two }"; - var expected = "enum C { One, Two }"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task RemoveAttributeFromEnums() + => TestRemoveAttributeAsync("[System.Serializable] enum [|C|] { One, Two }", "enum C { One, Two }", typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToEnumMembers() - { - var input = "enum C { [|One|], Two }"; - var expected = "enum C { [System.Serializable] One, Two }"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task AddAttributeToEnumMembers() + => TestAddAttributeAsync("enum C { [|One|], Two }", "enum C { [System.Serializable] One, Two }", typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeFromEnumMembers() - { - var input = "enum C { [System.Serializable] [|One|], Two }"; - var expected = "enum C { One, Two }"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task RemoveAttributeFromEnumMembers() + => TestRemoveAttributeAsync("enum C { [System.Serializable] [|One|], Two }", "enum C { One, Two }", typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToIndexer() - { - var input = "class C { public int [|this[int y]|] { get; set; }}"; - var expected = "class C { [System.Serializable] public int this[int y] { get; set; } }"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task AddAttributeToIndexer() + => TestAddAttributeAsync("class C { public int [|this[int y]|] { get; set; }}", "class C { [System.Serializable] public int this[int y] { get; set; } }", typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeFromIndexer() - { - var input = "class C { [System.Serializable] public int [|this[int y]|] { get; set; }}"; - var expected = "class C { public int this[int y] { get; set; } }"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task RemoveAttributeFromIndexer() + => TestRemoveAttributeAsync("class C { [System.Serializable] public int [|this[int y]|] { get; set; }}", "class C { public int this[int y] { get; set; } }", typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToOperator() - { - var input = "class C { public static C operator [|+|] (C c1, C c2) { return new C(); }}"; - var expected = "class C { [System.Serializable] public static C operator +(C c1, C c2) { return new C(); } }"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task AddAttributeToOperator() + => TestAddAttributeAsync("class C { public static C operator [|+|] (C c1, C c2) { return new C(); }}", "class C { [System.Serializable] public static C operator +(C c1, C c2) { return new C(); } }", typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeFromOperator() - { - var input = "class C { [System.Serializable] public static C operator [|+|](C c1, C c2) { return new C(); }}"; - var expected = "class C { public static C operator +(C c1, C c2) { return new C(); } }"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task RemoveAttributeFromOperator() + => TestRemoveAttributeAsync("class C { [System.Serializable] public static C operator [|+|](C c1, C c2) { return new C(); }}", "class C { public static C operator +(C c1, C c2) { return new C(); } }", typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToDelegate() - { - var input = "delegate int [|D()|];"; - var expected = @"[System.Serializable] -delegate int D();"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task AddAttributeToDelegate() + => TestAddAttributeAsync("delegate int [|D()|];", """ + [System.Serializable] + delegate int D(); + """, typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeFromDelegate() - { - var input = "[System.Serializable] delegate int [|D()|];"; - var expected = "delegate int D();"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task RemoveAttributeFromDelegate() + => TestRemoveAttributeAsync("[System.Serializable] delegate int [|D()|];", "delegate int D();", typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToParam() - { - var input = "class C { public void M([|int x|]) { } }"; - var expected = "class C { public void M([System.Serializable] int x) { } }"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task AddAttributeToParam() + => TestAddAttributeAsync("class C { public void M([|int x|]) { } }", "class C { public void M([System.Serializable] int x) { } }", typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeFromParam() - { - var input = "class C { public void M([System.Serializable] [|int x|]) { } }"; - var expected = "class C { public void M(int x) { } }"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task RemoveAttributeFromParam() + => TestRemoveAttributeAsync("class C { public void M([System.Serializable] [|int x|]) { } }", "class C { public void M(int x) { } }", typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToTypeParam() - { - var input = "class C<[|T|]> { }"; - var expected = "class C<[System.Serializable] T> { }"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task AddAttributeToTypeParam() + => TestAddAttributeAsync("class C<[|T|]> { }", "class C<[System.Serializable] T> { }", typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeFromTypeParam() - { - var input = "class C<[System.Serializable] [|T|]> { }"; - var expected = "class C { }"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task RemoveAttributeFromTypeParam() + => TestRemoveAttributeAsync("class C<[System.Serializable] [|T|]> { }", "class C { }", typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToCompilationUnit() - { - var input = "[|class C { } class D {} |]"; - var expected = @"[assembly: System.Serializable] + public Task AddAttributeToCompilationUnit() + => TestAddAttributeAsync("[|class C { } class D {} |]", """ + [assembly: System.Serializable] -class C { } -class D { }"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute), AssemblyKeyword); - } + class C { } + class D { } + """, typeof(SerializableAttribute), AssemblyKeyword); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeWithWrongTarget() - { - var input = "[|class C { } class D {} |]"; - var expected = ""; - await Assert.ThrowsAsync(async () => - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute), RefKeyword)); - } + public Task AddAttributeWithWrongTarget() + => Assert.ThrowsAsync(async () => + await TestAddAttributeAsync("[|class C { } class D {} |]", "", typeof(SerializableAttribute), RefKeyword)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeWithArrayParams() - { - var input = """ + public Task AddAttributeWithArrayParams() + => TestAddAttributeAsync(""" using System; class ExampleAttribute : Attribute { @@ -1352,8 +1133,7 @@ class C { public void [|M|]2() { } } - """; - var expected = """ + """, """ using System; class ExampleAttribute : Attribute { @@ -1369,372 +1149,350 @@ class C [Example(new[] { 1, 2, 3 })] public void M2() { } } - """; - await TestAddAttributeAsync(input, expected, (context) => + """, (context) => { var method = context.GetAnnotatedDeclaredSymbols("method", context.SemanticModel).Single(); var attribute = method.GetAttributes().Single(); return attribute; }); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeWithTrivia() - { - // With trivia. - var input = @"// Comment 1 -[System.Serializable] // Comment 2 -/* Comment 3*/ class [|C|] { }"; - var expected = @"// Comment 1 -/* Comment 3*/ class C { }"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeWithTrivia_NewLine() - { - // With trivia, redundant newline at end of attribute removed. - var input = @"// Comment 1 -[System.Serializable] -/* Comment 3*/ class [|C|] { }"; - var expected = @"// Comment 1 -/* Comment 3*/ class C { }"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeWithMultipleAttributes() - { - // Multiple attributes. - var input = @"// Comment 1 -/*Comment2*/[ /*Comment3*/ System.Serializable /*Comment4*/, /*Comment5*/System.Flags /*Comment6*/] /*Comment7*/ -/* Comment 8*/ -class [|C|] { }"; - var expected = @"// Comment 1 -/*Comment2*/[ /*Comment3*/ /*Comment5*/System.Flags /*Comment6*/] /*Comment7*/ -/* Comment 8*/ -class C { }"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeWithMultipleAttributeLists() - { - // Multiple attributes. - var input = @"// Comment 1 -/*Comment2*/[ /*Comment3*/ System.Serializable /*Comment4*/, /*Comment5*/System.Flags /*Comment6*/] /*Comment7*/ -[ /*Comment9*/ System.Obsolete /*Comment10*/] /*Comment11*/ -/* Comment12*/ -class [|C|] { }"; - var expected = @"// Comment 1 -/*Comment2*/[ /*Comment3*/ /*Comment5*/System.Flags /*Comment6*/] /*Comment7*/ -[ /*Comment9*/ System.Obsolete /*Comment10*/] /*Comment11*/ -/* Comment12*/ -class C { }"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task RemoveAttributeWithTrivia() + => TestRemoveAttributeAsync(""" + // Comment 1 + [System.Serializable] // Comment 2 + /* Comment 3*/ class [|C|] { } + """, """ + // Comment 1 + /* Comment 3*/ class C { } + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task RemoveAttributeWithTrivia_NewLine() + => TestRemoveAttributeAsync(""" + // Comment 1 + [System.Serializable] + /* Comment 3*/ class [|C|] { } + """, """ + // Comment 1 + /* Comment 3*/ class C { } + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task RemoveAttributeWithMultipleAttributes() + => TestRemoveAttributeAsync(""" + // Comment 1 + /*Comment2*/[ /*Comment3*/ System.Serializable /*Comment4*/, /*Comment5*/System.Flags /*Comment6*/] /*Comment7*/ + /* Comment 8*/ + class [|C|] { } + """, """ + // Comment 1 + /*Comment2*/[ /*Comment3*/ /*Comment5*/System.Flags /*Comment6*/] /*Comment7*/ + /* Comment 8*/ + class C { } + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task RemoveAttributeWithMultipleAttributeLists() + => TestRemoveAttributeAsync(""" + // Comment 1 + /*Comment2*/[ /*Comment3*/ System.Serializable /*Comment4*/, /*Comment5*/System.Flags /*Comment6*/] /*Comment7*/ + [ /*Comment9*/ System.Obsolete /*Comment10*/] /*Comment11*/ + /* Comment12*/ + class [|C|] { } + """, """ + // Comment 1 + /*Comment2*/[ /*Comment3*/ /*Comment5*/System.Flags /*Comment6*/] /*Comment7*/ + [ /*Comment9*/ System.Obsolete /*Comment10*/] /*Comment11*/ + /* Comment12*/ + class C { } + """, typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public async Task TestUpdateModifiers() { - var input = @"public static class [|C|] // Comment 1 -{ - // Comment 2 -}"; - var expected = @"internal partial sealed class C // Comment 1 -{ - // Comment 2 -}"; var eol = SyntaxFactory.EndOfLine(@""); var newModifiers = new[] { InternalKeyword.WithLeadingTrivia(eol) }.Concat( CreateModifierTokens(new Editing.DeclarationModifiers(isSealed: true, isPartial: true), LanguageNames.CSharp)); - await TestUpdateDeclarationAsync(input, expected, modifiers: newModifiers); + await TestUpdateDeclarationAsync(""" + public static class [|C|] // Comment 1 + { + // Comment 2 + } + """, """ + internal partial sealed class C // Comment 1 + { + // Comment 2 + } + """, modifiers: newModifiers); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task TestUpdateAccessibility() - { - var input = @"// Comment 0 -public static class [|C|] // Comment 1 -{ - // Comment 2 -}"; - var expected = @"// Comment 0 -internal static class C // Comment 1 -{ - // Comment 2 -}"; - await TestUpdateDeclarationAsync(input, expected, accessibility: Accessibility.Internal); - } + public Task TestUpdateAccessibility() + => TestUpdateDeclarationAsync(""" + // Comment 0 + public static class [|C|] // Comment 1 + { + // Comment 2 + } + """, """ + // Comment 0 + internal static class C // Comment 1 + { + // Comment 2 + } + """, accessibility: Accessibility.Internal); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task TestUpdateDeclarationType() - { - var input = @" -public static class C -{ - // Comment 1 - public static char [|F|]() { return 0; } -}"; - var expected = @" -public static class C -{ - // Comment 1 - public static int F() { return 0; } -}"; - await TestUpdateDeclarationAsync(input, expected, getType: GetTypeSymbol(typeof(int))); - } + public Task TestUpdateDeclarationType() + => TestUpdateDeclarationAsync(""" + public static class C + { + // Comment 1 + public static char [|F|]() { return 0; } + } + """, """ + public static class C + { + // Comment 1 + public static int F() { return 0; } + } + """, getType: GetTypeSymbol(typeof(int))); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public async Task TestUpdateDeclarationMembers() { - var input = @" -public static class [|C|] -{ - // Comment 0 - public int {|RetainedMember:f|}; - - // Comment 1 - public static char F() { return 0; } -}"; - var expected = @" -public static class C -{ - // Comment 0 - public int f; - public int f2; -}"; var getField = CreateField(Accessibility.Public, new Editing.DeclarationModifiers(), typeof(int), "f2"); var getMembers = ImmutableArray.Create(getField); await TestUpdateDeclarationAsync( - input, expected, getNewMembers: getMembers); + """ + public static class [|C|] + { + // Comment 0 + public int {|RetainedMember:f|}; + + // Comment 1 + public static char F() { return 0; } + } + """, """ + public static class C + { + // Comment 0 + public int f; + public int f2; + } + """, getNewMembers: getMembers); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public async Task TestUpdateDeclarationMembers_DifferentOrder() { - var input = @" -public static class [|C|] -{ - // Comment 0 - public int f; - - // Comment 1 - public static char {|RetainedMember:F|}() { return 0; } -}"; - var expected = @" -public static class C -{ - public int f2; - - // Comment 1 - public static char F() { return 0; } -}"; var getField = CreateField(Accessibility.Public, new Editing.DeclarationModifiers(), typeof(int), "f2"); var getMembers = ImmutableArray.Create(getField); - await TestUpdateDeclarationAsync(input, expected, getNewMembers: getMembers, declareNewMembersAtTop: true); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)] - public async Task SortAroundDestructor() - { - var generationSource = "public class [|C|] { public C(){} public int this[int index]{get{return 0;}set{value = 0;}} }"; - var initial = "public class [|C|] { ~C(){} }"; - var expected = @"public class C { - public C() - { - } + await TestUpdateDeclarationAsync(""" + public static class [|C|] + { + // Comment 0 + public int f; - ~C(){} + // Comment 1 + public static char {|RetainedMember:F|}() { return 0; } + } + """, """ + public static class C + { + public int f2; - public int this[int index] - { - get - { + // Comment 1 + public static char F() { return 0; } + } + """, getNewMembers: getMembers, declareNewMembersAtTop: true); } - set - { - } - } -}"; - await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers: true); - } + [Fact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)] + public Task SortAroundDestructor() + => TestGenerateFromSourceSymbolAsync("public class [|C|] { public C(){} public int this[int index]{get{return 0;}set{value = 0;}} }", "public class [|C|] { ~C(){} }", """ + public class C { + public C() + { + } + + ~C(){} + + public int this[int index] + { + get + { + } + + set + { + } + } + } + """, onlyGenerateMembers: true); [Fact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)] - public async Task SortOperators() - { - var generationSource = @" -namespace N -{ - public class [|C|] - { - // Unary operators - public static bool operator false (C other) { return false; } - public static bool operator true (C other) { return true; } - public static C operator ++ (C other) { return null; } - public static C operator -- (C other) { return null; } - public static C operator ~ (C other) { return null; } - public static C operator ! (C other) { return null; } - public static C operator - (C other) { return null; } - public static C operator + (C other) { return null; } - - // Binary operators - public static C operator >> (C a, int shift) { return null; } - public static C operator << (C a, int shift) { return null; } - public static C operator ^ (C a, C b) { return null; } - public static C operator | (C a, C b) { return null; } - public static C operator & (C a, C b) { return null; } - public static C operator % (C a, C b) { return null; } - public static C operator / (C a, C b) { return null; } - public static C operator * (C a, C b) { return null; } - public static C operator - (C a, C b) { return null; } - public static C operator + (C a, C b) { return null; } - - // Comparison operators - public static bool operator >= (C a, C b) { return true; } - public static bool operator <= (C a, C b) { return true; } - public static bool operator > (C a, C b) { return true; } - public static bool operator < (C a, C b) { return true; } - public static bool operator != (C a, C b) { return true; } - public static bool operator == (C a, C b) { return true; } - } -}"; - var initial = "namespace [|N|] { }"; - var expected = @"namespace N -{ - public class C - { - public static C operator +(C other); - public static C operator +(C a, C b); - public static C operator -(C other); - public static C operator -(C a, C b); - public static C operator !(C other); - public static C operator ~(C other); - public static C operator ++(C other); - public static C operator --(C other); - public static C operator *(C a, C b); - public static C operator /(C a, C b); - public static C operator %(C a, C b); - public static C operator &(C a, C b); - public static C operator |(C a, C b); - public static C operator ^(C a, C b); - public static C operator <<(C a, int shift); - public static C operator >>(C a, int shift); - public static bool operator ==(C a, C b); - public static bool operator !=(C a, C b); - public static bool operator <(C a, C b); - public static bool operator >(C a, C b); - public static bool operator <=(C a, C b); - public static bool operator >=(C a, C b); - public static bool operator true(C other); - public static bool operator false(C other); - } -}"; - await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, + public Task SortOperators() + => TestGenerateFromSourceSymbolAsync(""" + namespace N + { + public class [|C|] + { + // Unary operators + public static bool operator false (C other) { return false; } + public static bool operator true (C other) { return true; } + public static C operator ++ (C other) { return null; } + public static C operator -- (C other) { return null; } + public static C operator ~ (C other) { return null; } + public static C operator ! (C other) { return null; } + public static C operator - (C other) { return null; } + public static C operator + (C other) { return null; } + + // Binary operators + public static C operator >> (C a, int shift) { return null; } + public static C operator << (C a, int shift) { return null; } + public static C operator ^ (C a, C b) { return null; } + public static C operator | (C a, C b) { return null; } + public static C operator & (C a, C b) { return null; } + public static C operator % (C a, C b) { return null; } + public static C operator / (C a, C b) { return null; } + public static C operator * (C a, C b) { return null; } + public static C operator - (C a, C b) { return null; } + public static C operator + (C a, C b) { return null; } + + // Comparison operators + public static bool operator >= (C a, C b) { return true; } + public static bool operator <= (C a, C b) { return true; } + public static bool operator > (C a, C b) { return true; } + public static bool operator < (C a, C b) { return true; } + public static bool operator != (C a, C b) { return true; } + public static bool operator == (C a, C b) { return true; } + } + } + """, "namespace [|N|] { }", """ + namespace N + { + public class C + { + public static C operator +(C other); + public static C operator +(C a, C b); + public static C operator -(C other); + public static C operator -(C a, C b); + public static C operator !(C other); + public static C operator ~(C other); + public static C operator ++(C other); + public static C operator --(C other); + public static C operator *(C a, C b); + public static C operator /(C a, C b); + public static C operator %(C a, C b); + public static C operator &(C a, C b); + public static C operator |(C a, C b); + public static C operator ^(C a, C b); + public static C operator <<(C a, int shift); + public static C operator >>(C a, int shift); + public static bool operator ==(C a, C b); + public static bool operator !=(C a, C b); + public static bool operator <(C a, C b); + public static bool operator >(C a, C b); + public static bool operator <=(C a, C b); + public static bool operator >=(C a, C b); + public static bool operator true(C other); + public static bool operator false(C other); + } + } + """, forceLanguage: LanguageNames.CSharp, context: new CodeGenerationContext(generateMethodBodies: false)); - } } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665008")] - public async Task TestExtensionMethods() - { - var generationSource = @" -public static class [|C|] -{ - public static void ExtMethod1(this string s, int y, string z) {} -}"; - var initial = "public static class [|C|] {}"; - var expected = @"public static class C -{ - public static void ExtMethod1(this string s, int y, string z); -}"; - await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, + public Task TestExtensionMethods() + => TestGenerateFromSourceSymbolAsync(""" + public static class [|C|] + { + public static void ExtMethod1(this string s, int y, string z) {} + } + """, "public static class [|C|] {}", """ + public static class C + { + public static void ExtMethod1(this string s, int y, string z); + } + """, context: new CodeGenerationContext(generateMethodBodies: false), onlyGenerateMembers: true); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530829")] - public async Task TestVBPropertiesWithParams() - { - var generationSource = @" -Namespace N - Public Class [|C|] - Public Overridable Property IndexProp(ByVal p1 As Integer) As String - Get - Return Nothing - End Get - Set(ByVal value As String) - End Set - End Property - End Class -End Namespace -"; - - var initial = "namespace [|N|] {}"; - var expected = @"namespace N -{ - public class C - { - public virtual string get_IndexProp(int p1); - public virtual void set_IndexProp(int p1, string value); - } -}"; - await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, + public Task TestVBPropertiesWithParams() + => TestGenerateFromSourceSymbolAsync(""" + Namespace N + Public Class [|C|] + Public Overridable Property IndexProp(ByVal p1 As Integer) As String + Get + Return Nothing + End Get + Set(ByVal value As String) + End Set + End Property + End Class + End Namespace + """, "namespace [|N|] {}", """ + namespace N + { + public class C + { + public virtual string get_IndexProp(int p1); + public virtual void set_IndexProp(int p1, string value); + } + } + """, context: new CodeGenerationContext(generateMethodBodies: false)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/812738")] - public async Task TestRefParamsWithDefaultValue() - { - var generationSource = @" -Public Class [|C|] - Public Sub Goo(x As Integer, Optional ByRef y As Integer = 10, Optional ByRef z As Object = Nothing) - End Sub -End Class"; - var initial = "public class [|C|] {}"; - var expected = @"public class C -{ - public void Goo(int x, ref int y, ref object z); -}"; - await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, + public Task TestRefParamsWithDefaultValue() + => TestGenerateFromSourceSymbolAsync(""" + Public Class [|C|] + Public Sub Goo(x As Integer, Optional ByRef y As Integer = 10, Optional ByRef z As Object = Nothing) + End Sub + End Class + """, "public class [|C|] {}", """ + public class C + { + public void Goo(int x, ref int y, ref object z); + } + """, context: new CodeGenerationContext(generateMethodBodies: false), onlyGenerateMembers: true); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/848357")] - public async Task TestConstraints() - { - var generationSource = @" -namespace N -{ - public class [|C|] where T : struct where U : class - { - public void Goo() where Q : new() where R : IComparable { } - public delegate void D(T t, U u) where T : struct where U : class; - } -} -"; - var initial = "namespace [|N|] {}"; - var expected = @"namespace N -{ - public class C - where T : struct - where U : class - { - public void Goo() - where Q : new() - where R : IComparable; + public Task TestConstraints() + => TestGenerateFromSourceSymbolAsync(""" + namespace N + { + public class [|C|] where T : struct where U : class + { + public void Goo() where Q : new() where R : IComparable { } + public delegate void D(T t, U u) where T : struct where U : class; + } + } + """, "namespace [|N|] {}", """ + namespace N + { + public class C + where T : struct + where U : class + { + public void Goo() + where Q : new() + where R : IComparable; - public delegate void D(T t, U u) - where T : struct - where U : class; - } -}"; - await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, + public delegate void D(T t, U u) + where T : struct + where U : class; + } + } + """, context: new CodeGenerationContext(generateMethodBodies: false), onlyGenerateMembers: true); - } } diff --git a/src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.Shared.cs b/src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.Shared.cs index 4129011e16e16..dcb47734db9ec 100644 --- a/src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.Shared.cs +++ b/src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.Shared.cs @@ -20,495 +20,500 @@ public class Shared public async Task TestSorting() { var initial = "namespace [|N|] { }"; - var generationSource = @" -using System; + var generationSource = """ + using System; + + namespace N + { + public class [|C|] + { + private delegate void DAccessA(); + internal delegate void DAccessB(); + protected internal delegate void DAccessC(); + protected delegate void DAccessD(); + public delegate void DAccessE(); + public delegate void DGeneric(T1 a, T2 b); + public delegate void DGeneric(T t, int i); + + public class CNotStatic { } + public static class CStatic { } + private class CAccessA { } + internal class CAccessB { } + protected internal class CAccessC { } + protected class CAccessD { } + public class CAccessE { } + public class CGeneric { } + public class CGeneric { } + + private struct SAccessA { } + internal struct SAccessB { } + protected internal struct SAccessC { } + protected struct SAccessD { } + public struct SAccessE { } + public struct SGeneric { } + public struct SGeneric { } + public struct SNameB { } + public struct SNameA { } + + private enum EAccessA { } + internal enum EAccessB { } + protected internal enum EAccessC { } + protected enum EAccessD { } + public enum EAccessE { } + public enum ENameB { } + public enum ENameA { } + + private interface IAccessA { } + internal interface IAccessB { } + protected internal interface IAccessC { } + protected interface IAccessD { } + public interface IAccessE { } + public interface IGeneric { } + public interface IGeneric { } + + public static C operator !(C c) { return c; } + public static C operator +(C c) { return c; } + + public void MNotStatic() { } + public static void MStatic() { } + private void MAccessA() { } + internal void MAccessB() { } + protected internal void MAccessC() { } + protected void MAccessD() { } + public void MAccessE() { } + public void MGeneric() { } + public void MGeneric(int param) { } + public void MGeneric() { } + + public int M2NotStatic() { return 0; } + public static int M2Static() { return 0; } + private int M2AccessA() { return 0; } + internal int M2AccessB() { return 0; } + protected internal int M2AccessC() { return 0; } + protected int M2AccessD() { return 0; } + public int M2AccessE() { return 0; } + public int M2Generic() { return 0; } + public int M2Generic(int param) { return 0; } + public int M2Generic() { return 0; } + + public int PNotStatic { get { return 0; } } + public static int PStatic { get { return 0; } } + private int PAccessA { get { return 0; } } + internal int PAccessB { get { return 0; } } + protected internal int PAccessC { get { return 0; } } + protected int PAccessD { get { return 0; } } + public int PAccessE { get { return 0; } } + + public int this[int index1, int index2] { get { return 0; } } + public int this[int index] { get { return 0; } } + + public event Action EFNotStatic; + public static event Action EFStatic; + private event Action EFAccessA; + internal event Action EFAccessB; + protected event Action EFAccessC; + protected internal event Action EFAccessD; + public event Action EFAccessE; + + private C(string s); + internal C(long l); + protected C(char c); + protected internal C(short s); + public C(int a); + public C(int a, int b); + public C(); + + public string FNotStatic; + public static string FStatic; + public string FNotConst; + public const string FConst = "Const, Indeed"; + private string FAccessA; + internal string FAccessB; + protected string FAccessC; + protected internal string FAccessD; + public string FAccessE; + } + } + """; + var expected = """ + namespace N + { + public class C + { + public const string FConst; + public static string FStatic; + public string FNotStatic; + public string FNotConst; + public string FAccessE; + protected string FAccessC; + protected internal string FAccessD; + internal string FAccessB; + private string FAccessA; + + public C(); + public C(int a); + public C(int a, int b); + protected C(char c); + protected internal C(short s); + internal C(long l); + private C(string s); + + public int this[int index] { get; } + public int this[int index1, int index2] { get; } + + public static int PStatic { get; } + public int PNotStatic { get; } + public int PAccessE { get; } + protected int PAccessD { get; } + protected internal int PAccessC { get; } + internal int PAccessB { get; } + private int PAccessA { get; } + + public static event Action EFStatic; + public event Action EFNotStatic; + public event Action EFAccessE; + protected event Action EFAccessC; + protected internal event Action EFAccessD; + internal event Action EFAccessB; + private event Action EFAccessA; + + public static int M2Static(); + public static void MStatic(); + public int M2AccessE(); + public int M2Generic(); + public int M2Generic(int param); + public int M2Generic(); + public int M2NotStatic(); + public void MAccessE(); + public void MGeneric(); + public void MGeneric(int param); + public void MGeneric(); + public void MNotStatic(); + protected int M2AccessD(); + protected void MAccessD(); + protected internal int M2AccessC(); + protected internal void MAccessC(); + internal int M2AccessB(); + internal void MAccessB(); + private int M2AccessA(); + private void MAccessA(); + + public static C operator +(C c); + public static C operator !(C c); + + public enum EAccessE + { + } + + public enum ENameB + { + } + + public enum ENameA + { + } + + protected enum EAccessD + { + } + + protected internal enum EAccessC + { + } + + internal enum EAccessB + { + } + + private enum EAccessA + { + } + + public interface IAccessE + { + } + + public interface IGeneric + { + } + + public interface IGeneric + { + } + + protected interface IAccessD + { + } + + protected internal interface IAccessC + { + } + + internal interface IAccessB + { + } + + private interface IAccessA + { + } + + public struct SAccessE + { + } + + public struct SGeneric + { + } + + public struct SGeneric + { + } + + public struct SNameB + { + } + + public struct SNameA + { + } + + protected struct SAccessD + { + } + + protected internal struct SAccessC + { + } -namespace N -{ - public class [|C|] - { - private delegate void DAccessA(); - internal delegate void DAccessB(); - protected internal delegate void DAccessC(); - protected delegate void DAccessD(); - public delegate void DAccessE(); - public delegate void DGeneric(T1 a, T2 b); - public delegate void DGeneric(T t, int i); - - public class CNotStatic { } - public static class CStatic { } - private class CAccessA { } - internal class CAccessB { } - protected internal class CAccessC { } - protected class CAccessD { } - public class CAccessE { } - public class CGeneric { } - public class CGeneric { } - - private struct SAccessA { } - internal struct SAccessB { } - protected internal struct SAccessC { } - protected struct SAccessD { } - public struct SAccessE { } - public struct SGeneric { } - public struct SGeneric { } - public struct SNameB { } - public struct SNameA { } - - private enum EAccessA { } - internal enum EAccessB { } - protected internal enum EAccessC { } - protected enum EAccessD { } - public enum EAccessE { } - public enum ENameB { } - public enum ENameA { } - - private interface IAccessA { } - internal interface IAccessB { } - protected internal interface IAccessC { } - protected interface IAccessD { } - public interface IAccessE { } - public interface IGeneric { } - public interface IGeneric { } - - public static C operator !(C c) { return c; } - public static C operator +(C c) { return c; } - - public void MNotStatic() { } - public static void MStatic() { } - private void MAccessA() { } - internal void MAccessB() { } - protected internal void MAccessC() { } - protected void MAccessD() { } - public void MAccessE() { } - public void MGeneric() { } - public void MGeneric(int param) { } - public void MGeneric() { } - - public int M2NotStatic() { return 0; } - public static int M2Static() { return 0; } - private int M2AccessA() { return 0; } - internal int M2AccessB() { return 0; } - protected internal int M2AccessC() { return 0; } - protected int M2AccessD() { return 0; } - public int M2AccessE() { return 0; } - public int M2Generic() { return 0; } - public int M2Generic(int param) { return 0; } - public int M2Generic() { return 0; } - - public int PNotStatic { get { return 0; } } - public static int PStatic { get { return 0; } } - private int PAccessA { get { return 0; } } - internal int PAccessB { get { return 0; } } - protected internal int PAccessC { get { return 0; } } - protected int PAccessD { get { return 0; } } - public int PAccessE { get { return 0; } } - - public int this[int index1, int index2] { get { return 0; } } - public int this[int index] { get { return 0; } } - - public event Action EFNotStatic; - public static event Action EFStatic; - private event Action EFAccessA; - internal event Action EFAccessB; - protected event Action EFAccessC; - protected internal event Action EFAccessD; - public event Action EFAccessE; - - private C(string s); - internal C(long l); - protected C(char c); - protected internal C(short s); - public C(int a); - public C(int a, int b); - public C(); - - public string FNotStatic; - public static string FStatic; - public string FNotConst; - public const string FConst = ""Const, Indeed""; - private string FAccessA; - internal string FAccessB; - protected string FAccessC; - protected internal string FAccessD; - public string FAccessE; - } -}"; - var expected = @"namespace N -{ - public class C - { - public const string FConst; - public static string FStatic; - public string FNotStatic; - public string FNotConst; - public string FAccessE; - protected string FAccessC; - protected internal string FAccessD; - internal string FAccessB; - private string FAccessA; - - public C(); - public C(int a); - public C(int a, int b); - protected C(char c); - protected internal C(short s); - internal C(long l); - private C(string s); - - public int this[int index] { get; } - public int this[int index1, int index2] { get; } - - public static int PStatic { get; } - public int PNotStatic { get; } - public int PAccessE { get; } - protected int PAccessD { get; } - protected internal int PAccessC { get; } - internal int PAccessB { get; } - private int PAccessA { get; } - - public static event Action EFStatic; - public event Action EFNotStatic; - public event Action EFAccessE; - protected event Action EFAccessC; - protected internal event Action EFAccessD; - internal event Action EFAccessB; - private event Action EFAccessA; - - public static int M2Static(); - public static void MStatic(); - public int M2AccessE(); - public int M2Generic(); - public int M2Generic(int param); - public int M2Generic(); - public int M2NotStatic(); - public void MAccessE(); - public void MGeneric(); - public void MGeneric(int param); - public void MGeneric(); - public void MNotStatic(); - protected int M2AccessD(); - protected void MAccessD(); - protected internal int M2AccessC(); - protected internal void MAccessC(); - internal int M2AccessB(); - internal void MAccessB(); - private int M2AccessA(); - private void MAccessA(); - - public static C operator +(C c); - public static C operator !(C c); - - public enum EAccessE - { - } + internal struct SAccessB + { + } - public enum ENameB - { - } + private struct SAccessA + { + } - public enum ENameA - { - } + public static class CStatic + { + } - protected enum EAccessD - { - } + public class CNotStatic + { + } - protected internal enum EAccessC - { - } + public class CAccessE + { + } - internal enum EAccessB - { - } + public class CGeneric + { + } - private enum EAccessA - { - } + public class CGeneric + { + } - public interface IAccessE - { - } + protected class CAccessD + { + } - public interface IGeneric - { - } + protected internal class CAccessC + { + } - public interface IGeneric - { - } + internal class CAccessB + { + } - protected interface IAccessD - { - } + private class CAccessA + { + } - protected internal interface IAccessC - { - } + public delegate void DAccessE(); - internal interface IAccessB - { - } + public delegate void DGeneric(T1 a, T2 b); - private interface IAccessA - { - } - - public struct SAccessE - { - } - - public struct SGeneric - { - } - - public struct SGeneric - { - } + public delegate void DGeneric(T t, int i); - public struct SNameB - { - } + protected delegate void DAccessD(); - public struct SNameA - { - } + protected internal delegate void DAccessC(); - protected struct SAccessD - { - } - - protected internal struct SAccessC - { - } - - internal struct SAccessB - { - } - - private struct SAccessA - { - } - - public static class CStatic - { - } - - public class CNotStatic - { - } + internal delegate void DAccessB(); - public class CAccessE - { - } - - public class CGeneric - { - } - - public class CGeneric - { - } - - protected class CAccessD - { - } - - protected internal class CAccessC - { - } - - internal class CAccessB - { - } - - private class CAccessA - { - } - - public delegate void DAccessE(); - - public delegate void DGeneric(T1 a, T2 b); - - public delegate void DGeneric(T t, int i); - - protected delegate void DAccessD(); - - protected internal delegate void DAccessC(); - - internal delegate void DAccessB(); - - private delegate void DAccessA(); - } -}"; + private delegate void DAccessA(); + } + } + """; await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, context: new CodeGenerationContext(generateMethodBodies: false), forceLanguage: LanguageNames.CSharp); initial = "Namespace [|N|] \n End Namespace"; - expected = @"Namespace N - Public Class C - Public Const FConst As String - Public Shared FStatic As String - Public FNotStatic As String - Public FNotConst As String - Public FAccessE As String - Protected FAccessC As String - Protected Friend FAccessD As String - Friend FAccessB As String - Private FAccessA As String - Public Sub New() - Public Sub New(a As Integer) - Public Sub New(a As Integer, b As Integer) - Protected Sub New(c As Char) - Protected Friend Sub New(s As Short) - Friend Sub New(l As Long) - Private Sub New(s As String) - Public Shared ReadOnly Property PStatic As Integer - Public ReadOnly Property PNotStatic As Integer - Public ReadOnly Property PAccessE As Integer - Default Public ReadOnly Property this[](index1 As Integer, index2 As Integer) As Integer - Default Public ReadOnly Property this[](index As Integer) As Integer - Protected ReadOnly Property PAccessD As Integer - Protected Friend ReadOnly Property PAccessC As Integer - Friend ReadOnly Property PAccessB As Integer - Private ReadOnly Property PAccessA As Integer - Public Shared Event EFStatic As Action - Public Event EFNotStatic As Action - Public Event EFAccessE As Action - Protected Event EFAccessC As Action - Protected Friend Event EFAccessD As Action - Friend Event EFAccessB As Action - Private Event EFAccessA As Action - Public Shared Sub MStatic() - Public Sub MNotStatic() - Public Sub MAccessE() - Public Sub MGeneric(Of T1, T2)() - Public Sub MGeneric(Of T)(param As Integer) - Public Sub MGeneric(Of T)() - Protected Sub MAccessD() - Protected Friend Sub MAccessC() - Friend Sub MAccessB() - Private Sub MAccessA() - Public Shared Function M2Static() As Integer - Public Function M2NotStatic() As Integer - Public Function M2AccessE() As Integer - Public Function M2Generic(Of T1, T2)() As Integer - Public Function M2Generic(Of T)(param As Integer) As Integer - Public Function M2Generic(Of T)() As Integer - Protected Function M2AccessD() As Integer - Protected Friend Function M2AccessC() As Integer - Friend Function M2AccessB() As Integer - Private Function M2AccessA() As Integer - Public Shared Operator +(c As C) As C - Public Shared Operator Not(c As C) As C - - Public Enum EAccessE - End Enum - - Public Enum ENameB - End Enum - - Public Enum ENameA - End Enum - - Protected Enum EAccessD - End Enum - - Protected Friend Enum EAccessC - End Enum - - Friend Enum EAccessB - End Enum - - Private Enum EAccessA - End Enum - - Public Interface IAccessE - End Interface - - Public Interface IGeneric(Of T1, T2) - End Interface - - Public Interface IGeneric(Of T) - End Interface - - Protected Interface IAccessD - End Interface - - Protected Friend Interface IAccessC - End Interface - - Friend Interface IAccessB - End Interface - - Private Interface IAccessA - End Interface - - Public Structure SAccessE - End Structure - - Public Structure SGeneric(Of T1, T2) - End Structure - - Public Structure SGeneric(Of T) - End Structure - - Public Structure SNameB - End Structure - - Public Structure SNameA - End Structure - - Protected Structure SAccessD - End Structure - - Protected Friend Structure SAccessC - End Structure - - Friend Structure SAccessB - End Structure - - Private Structure SAccessA - End Structure - - Public Class CNotStatic - End Class + expected = """ + Namespace N + Public Class C + Public Const FConst As String + Public Shared FStatic As String + Public FNotStatic As String + Public FNotConst As String + Public FAccessE As String + Protected FAccessC As String + Protected Friend FAccessD As String + Friend FAccessB As String + Private FAccessA As String + Public Sub New() + Public Sub New(a As Integer) + Public Sub New(a As Integer, b As Integer) + Protected Sub New(c As Char) + Protected Friend Sub New(s As Short) + Friend Sub New(l As Long) + Private Sub New(s As String) + Public Shared ReadOnly Property PStatic As Integer + Public ReadOnly Property PNotStatic As Integer + Public ReadOnly Property PAccessE As Integer + Default Public ReadOnly Property this[](index1 As Integer, index2 As Integer) As Integer + Default Public ReadOnly Property this[](index As Integer) As Integer + Protected ReadOnly Property PAccessD As Integer + Protected Friend ReadOnly Property PAccessC As Integer + Friend ReadOnly Property PAccessB As Integer + Private ReadOnly Property PAccessA As Integer + Public Shared Event EFStatic As Action + Public Event EFNotStatic As Action + Public Event EFAccessE As Action + Protected Event EFAccessC As Action + Protected Friend Event EFAccessD As Action + Friend Event EFAccessB As Action + Private Event EFAccessA As Action + Public Shared Sub MStatic() + Public Sub MNotStatic() + Public Sub MAccessE() + Public Sub MGeneric(Of T1, T2)() + Public Sub MGeneric(Of T)(param As Integer) + Public Sub MGeneric(Of T)() + Protected Sub MAccessD() + Protected Friend Sub MAccessC() + Friend Sub MAccessB() + Private Sub MAccessA() + Public Shared Function M2Static() As Integer + Public Function M2NotStatic() As Integer + Public Function M2AccessE() As Integer + Public Function M2Generic(Of T1, T2)() As Integer + Public Function M2Generic(Of T)(param As Integer) As Integer + Public Function M2Generic(Of T)() As Integer + Protected Function M2AccessD() As Integer + Protected Friend Function M2AccessC() As Integer + Friend Function M2AccessB() As Integer + Private Function M2AccessA() As Integer + Public Shared Operator +(c As C) As C + Public Shared Operator Not(c As C) As C + + Public Enum EAccessE + End Enum + + Public Enum ENameB + End Enum + + Public Enum ENameA + End Enum + + Protected Enum EAccessD + End Enum + + Protected Friend Enum EAccessC + End Enum + + Friend Enum EAccessB + End Enum + + Private Enum EAccessA + End Enum + + Public Interface IAccessE + End Interface + + Public Interface IGeneric(Of T1, T2) + End Interface + + Public Interface IGeneric(Of T) + End Interface + + Protected Interface IAccessD + End Interface + + Protected Friend Interface IAccessC + End Interface + + Friend Interface IAccessB + End Interface + + Private Interface IAccessA + End Interface + + Public Structure SAccessE + End Structure + + Public Structure SGeneric(Of T1, T2) + End Structure + + Public Structure SGeneric(Of T) + End Structure + + Public Structure SNameB + End Structure + + Public Structure SNameA + End Structure + + Protected Structure SAccessD + End Structure + + Protected Friend Structure SAccessC + End Structure + + Friend Structure SAccessB + End Structure + + Private Structure SAccessA + End Structure + + Public Class CNotStatic + End Class - Public Class CStatic - End Class + Public Class CStatic + End Class - Public Class CAccessE - End Class + Public Class CAccessE + End Class - Public Class CGeneric(Of T1, T2) - End Class + Public Class CGeneric(Of T1, T2) + End Class - Public Class CGeneric(Of T) - End Class + Public Class CGeneric(Of T) + End Class - Protected Class CAccessD - End Class + Protected Class CAccessD + End Class - Protected Friend Class CAccessC - End Class + Protected Friend Class CAccessC + End Class - Friend Class CAccessB - End Class + Friend Class CAccessB + End Class - Private Class CAccessA - End Class + Private Class CAccessA + End Class - Public Delegate Sub DAccessE() - Public Delegate Sub DGeneric(Of T1, T2)(a As T1, b As T2) - Public Delegate Sub DGeneric(Of T)(t As T, i As Integer) - Protected Delegate Sub DAccessD() - Protected Friend Delegate Sub DAccessC() - Friend Delegate Sub DAccessB() - Private Delegate Sub DAccessA() - End Class -End Namespace"; + Public Delegate Sub DAccessE() + Public Delegate Sub DGeneric(Of T1, T2)(a As T1, b As T2) + Public Delegate Sub DGeneric(Of T)(t As T, i As Integer) + Protected Delegate Sub DAccessD() + Protected Friend Delegate Sub DAccessC() + Friend Delegate Sub DAccessB() + Private Delegate Sub DAccessA() + End Class + End Namespace + """; await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, context: new CodeGenerationContext(generateMethodBodies: false), forceLanguage: LanguageNames.VisualBasic); @@ -519,43 +524,53 @@ public async Task TestSortingDefaultTypeMemberAccessibility1() { var generationSource = "public class [|C|] { private string B; public string C; }"; var initial = "public class [|C|] { string A; }"; - var expected = @"public class C { - public string C; - string A; - private string B; -}"; + var expected = """ + public class C { + public string C; + string A; + private string B; + } + """; await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers: true); initial = "public struct [|S|] { string A; }"; - expected = @"public struct S { - public string C; - string A; - private string B; -}"; + expected = """ + public struct S { + public string C; + string A; + private string B; + } + """; await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers: true); initial = "Public Class [|C|] \n Dim A As String \n End Class"; - expected = @"Public Class C - Public C As String - Dim A As String - Private B As String -End Class"; + expected = """ + Public Class C + Public C As String + Dim A As String + Private B As String + End Class + """; await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers: true); initial = "Public Module [|M|] \n Dim A As String \n End Module"; - expected = @"Public Module M - Public C As String - Dim A As String - Private B As String -End Module"; + expected = """ + Public Module M + Public C As String + Dim A As String + Private B As String + End Module + """; await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers: true); initial = "Public Structure [|S|] \n Dim A As String \n End Structure"; - expected = @"Public Structure S - Dim A As String - Public C As String - Private B As String -End Structure"; + expected = """ + Public Structure S + Dim A As String + Public C As String + Private B As String + End Structure + """; await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers: true); } @@ -566,44 +581,52 @@ public async Task TestDefaultTypeMemberAccessibility2() var generationSource = "public class [|C|] { private void B(){} public void C(){} }"; var initial = "public interface [|I|] { void A(); }"; - var expected = @"public interface I { void A(); - void B(); - void C(); -}"; + var expected = """ + public interface I { void A(); + void B(); + void C(); + } + """; await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers: true, context: codeGenOptionNoBody); initial = "Public Interface [|I|] \n Sub A() \n End Interface"; - expected = @"Public Interface I - Sub A() - Sub B() - Sub C() -End Interface"; + expected = """ + Public Interface I + Sub A() + Sub B() + Sub C() + End Interface + """; await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers: true, context: codeGenOptionNoBody); initial = "Public Class [|C|] \n Sub A() \n End Sub \n End Class"; - expected = @"Public Class C - Sub A() - End Sub - - Public Sub C() - End Sub - - Private Sub B() - End Sub -End Class"; + expected = """ + Public Class C + Sub A() + End Sub + + Public Sub C() + End Sub + + Private Sub B() + End Sub + End Class + """; await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers: true); initial = "Public Module [|M|] \n Sub A() \n End Sub \n End Module"; - expected = @"Public Module M - Sub A() - End Sub - - Public Sub C() - End Sub - - Private Sub B() - End Sub -End Module"; + expected = """ + Public Module M + Sub A() + End Sub + + Public Sub C() + End Sub + + Private Sub B() + End Sub + End Module + """; await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers: true); } @@ -612,22 +635,26 @@ public async Task TestDefaultNamespaceMemberAccessibility1() { var generationSource = "internal class [|B|]{}"; var initial = "namespace [|N|] { class A{} }"; - var expected = @"namespace N { class A{} - - internal class B - { - } -}"; + var expected = """ + namespace N { class A{} + + internal class B + { + } + } + """; await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected); initial = "Namespace [|N|] \n Class A \n End Class \n End Namespace"; - expected = @"Namespace N - Class A - End Class - - Friend Class B - End Class -End Namespace"; + expected = """ + Namespace N + Class A + End Class + + Friend Class B + End Class + End Namespace + """; await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected); } @@ -640,101 +667,100 @@ public async Task TestDefaultNamespaceMemberAccessibility2() await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected); initial = "Namespace [|N|] \n Class A \n End Class \n End Namespace"; - expected = @"Namespace N - Public Class C - End Class - - Class A - End Class - End Namespace"; + expected = """ + Namespace N + Public Class C + End Class + + Class A + End Class + End Namespace + """; await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] - public async Task TestDocumentationComment() - { - var generationSource = @" -public class [|C|] -{ - /// When in need, a documented method is a friend, indeed. - public C() { } -}"; - var initial = "public class [|C|] { }"; - var expected = @"public class C -{ - /// - /// - /// When in need, a documented method is a friend, indeed. - /// - /// - public C(); -}"; - await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, + public Task TestDocumentationComment() + => TestGenerateFromSourceSymbolAsync(""" + public class [|C|] + { + /// When in need, a documented method is a friend, indeed. + public C() { } + } + """, "public class [|C|] { }", """ + public class C + { + /// + /// + /// When in need, a documented method is a friend, indeed. + /// + /// + public C(); + } + """, context: new CodeGenerationContext(generateMethodBodies: false, generateDocumentationComments: true), onlyGenerateMembers: true); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public async Task TestModifiers() { - var generationSource = @" -namespace [|N|] -{ - public class A - { - public virtual string Property { get { return null; } } - public static abstract string Property1 { get; } - - public virtual void Method1() {} - public static abstract void Method2() {} - } - - public class C - { - public sealed override string Property { get { return null; } } - public sealed override void Method1() {} - } -}"; - - var initial = "namespace [|N|] { }"; - var expected = @"namespace N { - namespace N - { - public class A - { - public static string Property1 { get; } - public virtual string Property { get; } - - public static void Method2(); - public virtual void Method1(); - } - - public class C - { - public sealed override string Property { get; } - - public sealed override void Method1(); - } - } -}"; - await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, + var generationSource = """ + namespace [|N|] + { + public class A + { + public virtual string Property { get { return null; } } + public static abstract string Property1 { get; } + + public virtual void Method1() {} + public static abstract void Method2() {} + } + + public class C + { + public sealed override string Property { get { return null; } } + public sealed override void Method1() {} + } + } + """; + await TestGenerateFromSourceSymbolAsync(generationSource, "namespace [|N|] { }", """ + namespace N { + namespace N + { + public class A + { + public static string Property1 { get; } + public virtual string Property { get; } + + public static void Method2(); + public virtual void Method1(); + } + + public class C + { + public sealed override string Property { get; } + + public sealed override void Method1(); + } + } + } + """, context: new CodeGenerationContext(generateMethodBodies: false)); - - var initialVB = "Namespace [|N|] End Namespace"; - var expectedVB = @"Namespace N End NamespaceNamespace N - Public Class A - Public Shared ReadOnly Property Property1 As String - Public Overridable ReadOnly Property [Property] As String - Public Shared Sub Method2() - Public Overridable Sub Method1() - End Class - - Public Class C - Public Overrides NotOverridable ReadOnly Property [Property] As String - Public NotOverridable Overrides Sub Method1() - End Class - End Namespace"; - await TestGenerateFromSourceSymbolAsync(generationSource, initialVB, expectedVB, + await TestGenerateFromSourceSymbolAsync(generationSource, "Namespace [|N|] End Namespace", """ + Namespace N End NamespaceNamespace N + Public Class A + Public Shared ReadOnly Property Property1 As String + Public Overridable ReadOnly Property [Property] As String + Public Shared Sub Method2() + Public Overridable Sub Method1() + End Class + + Public Class C + Public Overrides NotOverridable ReadOnly Property [Property] As String + Public NotOverridable Overrides Sub Method1() + End Class + End Namespace + """, context: new CodeGenerationContext(generateMethodBodies: false)); } } diff --git a/src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.VisualBasic.cs b/src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.VisualBasic.cs index 683b82b254dac..d6dbf45070729 100644 --- a/src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.VisualBasic.cs +++ b/src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.VisualBasic.cs @@ -27,385 +27,325 @@ public sealed partial class CodeGenerationTests public class VisualBasic { [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddNamespace() - { - var input = "Namespace [|N1|]\n End Namespace"; - var expected = @"Namespace N1 - Namespace N2 - End Namespace -End Namespace"; - await TestAddNamespaceAsync(input, expected, + public Task AddNamespace() + => TestAddNamespaceAsync("Namespace [|N1|]\n End Namespace", """ + Namespace N1 + Namespace N2 + End Namespace + End Namespace + """, name: "N2"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddField() - { - var input = "Class [|C|]\n End Class"; - var expected = @"Class C - Public F As Integer -End Class"; - await TestAddFieldAsync(input, expected, + public Task AddField() + => TestAddFieldAsync("Class [|C|]\n End Class", """ + Class C + Public F As Integer + End Class + """, type: GetTypeSymbol(typeof(int))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddSharedField() - { - var input = "Class [|C|]\n End Class"; - var expected = @"Class C - Private Shared F As String -End Class"; - await TestAddFieldAsync(input, expected, + public Task AddSharedField() + => TestAddFieldAsync("Class [|C|]\n End Class", """ + Class C + Private Shared F As String + End Class + """, type: GetTypeSymbol(typeof(string)), accessibility: Accessibility.Private, modifiers: new DeclarationModifiers(isStatic: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddArrayField() - { - var input = "Class [|C|]\n End Class"; - var expected = @"Class C - Public F As Integer() -End Class"; - await TestAddFieldAsync(input, expected, + public Task AddArrayField() + => TestAddFieldAsync("Class [|C|]\n End Class", """ + Class C + Public F As Integer() + End Class + """, type: CreateArrayType(typeof(int))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddConstructor() - { - var input = "Class [|C|]\n End Class"; - var expected = @"Class C - Public Sub New() - End Sub -End Class"; - await TestAddConstructorAsync(input, expected); - } + public Task AddConstructor() + => TestAddConstructorAsync("Class [|C|]\n End Class", """ + Class C + Public Sub New() + End Sub + End Class + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530785")] - public async Task AddConstructorWithXmlComment() - { - var input = @" -Public Class [|C|] -''' -''' Do Nothing -''' -Public Sub GetStates() -End Sub -End Class"; - var expected = @" -Public Class C - Public Sub New() - End Sub - ''' - ''' Do Nothing - ''' - Public Sub GetStates() -End Sub -End Class"; - await TestAddConstructorAsync(input, expected); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddConstructorWithoutBody() - { - var input = "Class [|C|]\n End Class"; - var expected = @"Class C - Public Sub New() -End Class"; - await TestAddConstructorAsync(input, expected, + public Task AddConstructorWithXmlComment() + => TestAddConstructorAsync(""" + Public Class [|C|] + ''' + ''' Do Nothing + ''' + Public Sub GetStates() + End Sub + End Class + """, """ + Public Class C + Public Sub New() + End Sub + ''' + ''' Do Nothing + ''' + Public Sub GetStates() + End Sub + End Class + """); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task AddConstructorWithoutBody() + => TestAddConstructorAsync("Class [|C|]\n End Class", """ + Class C + Public Sub New() + End Class + """, context: new CodeGenerationContext(generateMethodBodies: false)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddConstructorResolveNamespaceImport() - { - var input = "Class [|C|]\n End Class"; - var expected = @"Imports System.Text - -Class C - Public Sub New(s As StringBuilder) - End Sub -End Class"; - await TestAddConstructorAsync(input, expected, + public Task AddConstructorResolveNamespaceImport() + => TestAddConstructorAsync("Class [|C|]\n End Class", """ + Imports System.Text + + Class C + Public Sub New(s As StringBuilder) + End Sub + End Class + """, parameters: Parameters(Parameter(typeof(StringBuilder), "s"))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddSharedConstructor() - { - var input = "Class [|C|]\n End Class"; - var expected = @"Class C - Shared Sub New() - End Sub -End Class"; - await TestAddConstructorAsync(input, expected, + public Task AddSharedConstructor() + => TestAddConstructorAsync("Class [|C|]\n End Class", """ + Class C + Shared Sub New() + End Sub + End Class + """, modifiers: new DeclarationModifiers(isStatic: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddChainedConstructor() - { - var input = "Class [|C|]\n Public Sub New(i As Integer)\n End Sub\n End Class"; - var expected = @"Class C - Public Sub New() - Me.New(42) - End Sub - - Public Sub New(i As Integer) - End Sub - End Class"; - await TestAddConstructorAsync(input, expected, + public Task AddChainedConstructor() + => TestAddConstructorAsync("Class [|C|]\n Public Sub New(i As Integer)\n End Sub\n End Class", """ + Class C + Public Sub New() + Me.New(42) + End Sub + + Public Sub New(i As Integer) + End Sub + End Class + """, thisArguments: [VB.SyntaxFactory.ParseExpression("42")]); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544476")] - public async Task AddClass() - { - var input = "Namespace [|N|]\n End Namespace"; - var expected = @"Namespace N - Public Class C - End Class -End Namespace"; - await TestAddNamedTypeAsync(input, expected); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddClassEscapeName() - { - var input = "Namespace [|N|]\n End Namespace"; - var expected = @"Namespace N - Public Class [Class] - End Class -End Namespace"; - await TestAddNamedTypeAsync(input, expected, + public Task AddClass() + => TestAddNamedTypeAsync("Namespace [|N|]\n End Namespace", """ + Namespace N + Public Class C + End Class + End Namespace + """); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task AddClassEscapeName() + => TestAddNamedTypeAsync("Namespace [|N|]\n End Namespace", """ + Namespace N + Public Class [Class] + End Class + End Namespace + """, name: "Class"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddClassUnicodeName() - { - var input = "Namespace [|N|]\n End Namespace"; - var expected = @"Namespace N - Public Class [Class] - End Class -End Namespace"; - await TestAddNamedTypeAsync(input, expected, + public Task AddClassUnicodeName() + => TestAddNamedTypeAsync("Namespace [|N|]\n End Namespace", """ + Namespace N + Public Class [Class] + End Class + End Namespace + """, name: "Class"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544477")] - public async Task AddNotInheritableClass() - { - var input = "Namespace [|N|]\n End Namespace"; - var expected = @"Namespace N - Public NotInheritable Class C - End Class -End Namespace"; - await TestAddNamedTypeAsync(input, expected, + public Task AddNotInheritableClass() + => TestAddNamedTypeAsync("Namespace [|N|]\n End Namespace", """ + Namespace N + Public NotInheritable Class C + End Class + End Namespace + """, modifiers: new DeclarationModifiers(isSealed: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544477")] - public async Task AddMustInheritClass() - { - var input = "Namespace [|N|]\n End Namespace"; - var expected = @"Namespace N - Friend MustInherit Class C - End Class -End Namespace"; - await TestAddNamedTypeAsync(input, expected, + public Task AddMustInheritClass() + => TestAddNamedTypeAsync("Namespace [|N|]\n End Namespace", """ + Namespace N + Friend MustInherit Class C + End Class + End Namespace + """, accessibility: Accessibility.Internal, modifiers: new DeclarationModifiers(isAbstract: true)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddStructure() - { - var input = "Namespace [|N|]\n End Namespace"; - var expected = @"Namespace N - Friend Structure S - End Structure -End Namespace"; - await TestAddNamedTypeAsync(input, expected, + public Task AddStructure() + => TestAddNamedTypeAsync("Namespace [|N|]\n End Namespace", """ + Namespace N + Friend Structure S + End Structure + End Namespace + """, name: "S", accessibility: Accessibility.Internal, typeKind: TypeKind.Struct); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546224")] - public async Task AddSealedStructure() - { - var input = "Namespace [|N|]\n End Namespace"; - var expected = @"Namespace N - Public Structure S - End Structure -End Namespace"; - await TestAddNamedTypeAsync(input, expected, + public Task AddSealedStructure() + => TestAddNamedTypeAsync("Namespace [|N|]\n End Namespace", """ + Namespace N + Public Structure S + End Structure + End Namespace + """, name: "S", accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isSealed: true), typeKind: TypeKind.Struct); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddInterface() - { - var input = "Namespace [|N|]\n End Namespace"; - var expected = @"Namespace N - Public Interface I - End Interface -End Namespace"; - await TestAddNamedTypeAsync(input, expected, + public Task AddInterface() + => TestAddNamedTypeAsync("Namespace [|N|]\n End Namespace", """ + Namespace N + Public Interface I + End Interface + End Namespace + """, name: "I", typeKind: TypeKind.Interface); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544528")] - public async Task AddEnum() - { - var input = "Namespace [|N|]\n End Namespace"; - var expected = @"Namespace N - Public Enum E - F1 - End Enum -End Namespace"; - await TestAddNamedTypeAsync(input, expected, "E", + public Task AddEnum() + => TestAddNamedTypeAsync("Namespace [|N|]\n End Namespace", """ + Namespace N + Public Enum E + F1 + End Enum + End Namespace + """, "E", typeKind: TypeKind.Enum, members: Members(CreateEnumField("F1", null))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544527")] - public async Task AddEnumWithValues() - { - var input = "Namespace [|N|]\n End Namespace"; - var expected = @"Namespace N - Public Enum E - F1 = 1 - F2 = 2 - End Enum -End Namespace"; - await TestAddNamedTypeAsync(input, expected, "E", + public Task AddEnumWithValues() + => TestAddNamedTypeAsync("Namespace [|N|]\n End Namespace", """ + Namespace N + Public Enum E + F1 = 1 + F2 = 2 + End Enum + End Namespace + """, "E", typeKind: TypeKind.Enum, members: Members(CreateEnumField("F1", 1), CreateEnumField("F2", 2))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddEnumMember() - { - var input = "Public Enum [|E|]\n F1 = 1\n F2 = 2\n End Enum"; - var expected = @"Public Enum E - F1 = 1 - F2 = 2 - F3 -End Enum"; - await TestAddFieldAsync(input, expected, + public Task AddEnumMember() + => TestAddFieldAsync("Public Enum [|E|]\n F1 = 1\n F2 = 2\n End Enum", """ + Public Enum E + F1 = 1 + F2 = 2 + F3 + End Enum + """, name: "F3"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddEnumMemberWithValue() - { - var input = "Public Enum [|E|]\n F1 = 1\n F2\n End Enum"; - var expected = @"Public Enum E - F1 = 1 - F2 - F3 = 3 -End Enum"; - await TestAddFieldAsync(input, expected, + public Task AddEnumMemberWithValue() + => TestAddFieldAsync("Public Enum [|E|]\n F1 = 1\n F2\n End Enum", """ + Public Enum E + F1 = 1 + F2 + F3 = 3 + End Enum + """, name: "F3", hasConstantValue: true, constantValue: 3); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544529")] - public async Task AddDelegateType() - { - var input = "Class [|C|]\n End Class"; - var expected = @"Class C - Public Delegate Function D(s As String) As Integer -End Class"; - await TestAddDelegateTypeAsync(input, expected, + public Task AddDelegateType() + => TestAddDelegateTypeAsync("Class [|C|]\n End Class", """ + Class C + Public Delegate Function D(s As String) As Integer + End Class + """, returnType: typeof(int), parameters: Parameters(Parameter(typeof(string), "s"))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546224")] - public async Task AddSealedDelegateType() - { - var input = "Class [|C|]\n End Class"; - var expected = @"Class C - Public Delegate Function D(s As String) As Integer -End Class"; - await TestAddDelegateTypeAsync(input, expected, + public Task AddSealedDelegateType() + => TestAddDelegateTypeAsync("Class [|C|]\n End Class", """ + Class C + Public Delegate Function D(s As String) As Integer + End Class + """, returnType: typeof(int), modifiers: new DeclarationModifiers(isSealed: true), parameters: Parameters(Parameter(typeof(string), "s"))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddEvent() - { - var input = @" -Class [|C|] -End Class"; - var expected = @" -Class C - Public Event E As Action -End Class"; - await TestAddEventAsync(input, expected, + public Task AddEvent() + => TestAddEventAsync(""" + Class [|C|] + End Class + """, """ + Class C + Public Event E As Action + End Class + """, context: new CodeGenerationContext(addImports: false)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public async Task AddCustomEventToClassFromSourceSymbol() { - var sourceGenerated = @"Public Class [|C2|] - Public Custom Event Click As EventHandler - AddHandler(ByVal value As EventHandler) - Events.AddHandler(""ClickEvent"", value) - End AddHandler - RemoveHandler(ByVal value As EventHandler) - Events.RemoveHandler(""ClickEvent"", value) - End RemoveHandler - RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) - CType(Events(""ClickEvent""), EventHandler).Invoke(sender, e) - End RaiseEvent - End Event -End Class"; - var input = "Class [|C1|]\nEnd Class"; - var expected = @"Class C1 - Public Custom Event Click As EventHandler - AddHandler(ByVal value As EventHandler) - Events.AddHandler(""ClickEvent"", value) - End AddHandler - RemoveHandler(ByVal value As EventHandler) - Events.RemoveHandler(""ClickEvent"", value) - End RemoveHandler - RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) - CType(Events(""ClickEvent""), EventHandler).Invoke(sender, e) - End RaiseEvent - End Event -End Class"; var context = new CodeGenerationContext(reuseSyntax: true); - await TestGenerateFromSourceSymbolAsync(sourceGenerated, input, expected, onlyGenerateMembers: true, context: context); + await TestGenerateFromSourceSymbolAsync(""" + Public Class [|C2|] + Public Custom Event Click As EventHandler + AddHandler(ByVal value As EventHandler) + Events.AddHandler("ClickEvent", value) + End AddHandler + RemoveHandler(ByVal value As EventHandler) + Events.RemoveHandler("ClickEvent", value) + End RemoveHandler + RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) + CType(Events("ClickEvent"), EventHandler).Invoke(sender, e) + End RaiseEvent + End Event + End Class + """, "Class [|C1|]\nEnd Class", """ + Class C1 + Public Custom Event Click As EventHandler + AddHandler(ByVal value As EventHandler) + Events.AddHandler("ClickEvent", value) + End AddHandler + RemoveHandler(ByVal value As EventHandler) + Events.RemoveHandler("ClickEvent", value) + End RemoveHandler + RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) + CType(Events("ClickEvent"), EventHandler).Invoke(sender, e) + End RaiseEvent + End Event + End Class + """, onlyGenerateMembers: true, context: context); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public async Task AddEventWithAccessorAndImplementsClause() { - var input = "Class [|C|] \n End Class"; - var expected = @"Class C - Public Custom Event E As ComponentModel.PropertyChangedEventHandler Implements ComponentModel.INotifyPropertyChanged.PropertyChanged - AddHandler(value As ComponentModel.PropertyChangedEventHandler) - End AddHandler - RemoveHandler(value As ComponentModel.PropertyChangedEventHandler) - End RemoveHandler - RaiseEvent(sender As Object, e As ComponentModel.PropertyChangedEventArgs) - End RaiseEvent - End Event -End Class"; static ImmutableArray GetExplicitInterfaceEvent(SemanticModel semanticModel) { return [new CodeGenerationEventSymbol( @@ -418,7 +358,18 @@ static ImmutableArray GetExplicitInterfaceEvent(SemanticModel sema nameof(System.ComponentModel.INotifyPropertyChanged.PropertyChanged), null, null, null)]; } - await TestAddEventAsync(input, expected, + await TestAddEventAsync("Class [|C|] \n End Class", """ + Class C + Public Custom Event E As ComponentModel.PropertyChangedEventHandler Implements ComponentModel.INotifyPropertyChanged.PropertyChanged + AddHandler(value As ComponentModel.PropertyChangedEventHandler) + End AddHandler + RemoveHandler(value As ComponentModel.PropertyChangedEventHandler) + End RemoveHandler + RaiseEvent(sender As Object, e As ComponentModel.PropertyChangedEventArgs) + End RaiseEvent + End Event + End Class + """, addMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol( [], Accessibility.NotApplicable, []), getExplicitInterfaceImplementations: GetExplicitInterfaceEvent, @@ -427,51 +378,49 @@ await TestAddEventAsync(input, expected, } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddEventWithAddAccessor() - { - var input = @" -Class [|C|] -End Class"; - var expected = @" -Class C - Public Custom Event E As Action - AddHandler(value As Action) - End AddHandler - RemoveHandler(value As Action) - End RemoveHandler - RaiseEvent() - End RaiseEvent - End Event -End Class"; - await TestAddEventAsync(input, expected, + public Task AddEventWithAddAccessor() + => TestAddEventAsync(""" + Class [|C|] + End Class + """, """ + Class C + Public Custom Event E As Action + AddHandler(value As Action) + End AddHandler + RemoveHandler(value As Action) + End RemoveHandler + RaiseEvent() + End RaiseEvent + End Event + End Class + """, addMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol([], Accessibility.NotApplicable, []), context: new CodeGenerationContext(addImports: false)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public async Task AddEventWithAccessors() { - var input = @" -Class [|C|] -End Class"; - var expected = @" -Class C - Public Custom Event E As Action - AddHandler(value As Action) - Console.WriteLine(0) - End AddHandler - RemoveHandler(value As Action) - Console.WriteLine(1) - End RemoveHandler - RaiseEvent() - Console.WriteLine(2) - End RaiseEvent - End Event -End Class"; var addStatements = ImmutableArray.Create(VB.SyntaxFactory.ParseExecutableStatement("Console.WriteLine(0)")); var removeStatements = ImmutableArray.Create(VB.SyntaxFactory.ParseExecutableStatement("Console.WriteLine(1)")); var raiseStatements = ImmutableArray.Create(VB.SyntaxFactory.ParseExecutableStatement("Console.WriteLine(2)")); - await TestAddEventAsync(input, expected, + await TestAddEventAsync(""" + Class [|C|] + End Class + """, """ + Class C + Public Custom Event E As Action + AddHandler(value As Action) + Console.WriteLine(0) + End AddHandler + RemoveHandler(value As Action) + Console.WriteLine(1) + End RemoveHandler + RaiseEvent() + Console.WriteLine(2) + End RaiseEvent + End Event + End Class + """, addMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol( [], Accessibility.NotApplicable, addStatements), removeMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol( @@ -482,164 +431,146 @@ await TestAddEventAsync(input, expected, } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddMethodToClass() - { - var input = "Class [|C|]\n End Class"; - var expected = @"Class C - Public Sub M() - End Sub -End Class"; - await TestAddMethodAsync(input, expected, + public Task AddMethodToClass() + => TestAddMethodAsync("Class [|C|]\n End Class", """ + Class C + Public Sub M() + End Sub + End Class + """, returnType: typeof(void)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public async Task AddMethodToClassFromSourceSymbol() { - var sourceGenerated = @"Public Class [|C2|] - Public Function FInt() As Integer - Return 0 - End Function -End Class"; - var input = "Class [|C1|]\nEnd Class"; - var expected = @"Class C1 - Public Function FInt() As Integer - Return 0 - End Function -End Class"; var context = new CodeGenerationContext(reuseSyntax: true); - await TestGenerateFromSourceSymbolAsync(sourceGenerated, input, expected, onlyGenerateMembers: true, context: context); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddMethodToClassEscapedName() - { - var input = "Class [|C|]\n End Class"; - var expected = @"Class C - Protected Friend Sub [Sub]() - End Sub -End Class"; - await TestAddMethodAsync(input, expected, + await TestGenerateFromSourceSymbolAsync(""" + Public Class [|C2|] + Public Function FInt() As Integer + Return 0 + End Function + End Class + """, "Class [|C1|]\nEnd Class", """ + Class C1 + Public Function FInt() As Integer + Return 0 + End Function + End Class + """, onlyGenerateMembers: true, context: context); + } + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task AddMethodToClassEscapedName() + => TestAddMethodAsync("Class [|C|]\n End Class", """ + Class C + Protected Friend Sub [Sub]() + End Sub + End Class + """, accessibility: Accessibility.ProtectedOrInternal, name: "Sub", returnType: typeof(void)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544477")] - public async Task AddSharedMethodToStructure() - { - var input = "Structure [|S|]\n End Structure"; - var expected = @"Structure S - Public Shared Function M() As Integer - Return 0 - End Function -End Structure"; - await TestAddMethodAsync(input, expected, + public Task AddSharedMethodToStructure() + => TestAddMethodAsync("Structure [|S|]\n End Structure", """ + Structure S + Public Shared Function M() As Integer + Return 0 + End Function + End Structure + """, modifiers: new DeclarationModifiers(isStatic: true), returnType: typeof(int), statements: "Return 0"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddNotOverridableOverridesMethod() - { - var input = "Class [|C|]\n End Class"; - var expected = @"Class C - Public NotOverridable Overrides Function GetHashCode() As Integer - $$ - End Function -End Class"; - await TestAddMethodAsync(input, expected, + public Task AddNotOverridableOverridesMethod() + => TestAddMethodAsync("Class [|C|]\n End Class", """ + Class C + Public NotOverridable Overrides Function GetHashCode() As Integer + $$ + End Function + End Class + """, name: "GetHashCode", modifiers: new DeclarationModifiers(isOverride: true, isSealed: true), returnType: typeof(int), statements: "Return 0"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddMustOverrideMethod() - { - var input = "MustInherit Class [|C|]\n End Class"; - var expected = "MustInherit Class C\n Public MustOverride Sub M()\nEnd Class"; - await TestAddMethodAsync(input, expected, + public Task AddMustOverrideMethod() + => TestAddMethodAsync("MustInherit Class [|C|]\n End Class", "MustInherit Class C\n Public MustOverride Sub M()\nEnd Class", modifiers: new DeclarationModifiers(isAbstract: true), returnType: typeof(void)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddMethodWithoutBody() - { - var input = "Class [|C|]\n End Class"; - var expected = @"Class C - Public Sub M() -End Class"; - await TestAddMethodAsync(input, expected, + public Task AddMethodWithoutBody() + => TestAddMethodAsync("Class [|C|]\n End Class", """ + Class C + Public Sub M() + End Class + """, returnType: typeof(void), context: new CodeGenerationContext(generateMethodBodies: false)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddGenericMethod() - { - var input = "Class [|C|]\n End Class"; - var expected = @"Class C - Public Function M(Of T)() As Integer - $$ - End Function -End Class"; - await TestAddMethodAsync(input, expected, + public Task AddGenericMethod() + => TestAddMethodAsync("Class [|C|]\n End Class", """ + Class C + Public Function M(Of T)() As Integer + $$ + End Function + End Class + """, returnType: typeof(int), typeParameters: [CodeGenerationSymbolFactory.CreateTypeParameterSymbol("T")], statements: "Return new T().GetHashCode()"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddVirtualMethod() - { - var input = "Class [|C|]\n End Class"; - var expected = @"Class C - Protected Overridable Function M() As Integer - $$ - End Function -End Class"; - await TestAddMethodAsync(input, expected, + public Task AddVirtualMethod() + => TestAddMethodAsync("Class [|C|]\n End Class", """ + Class C + Protected Overridable Function M() As Integer + $$ + End Function + End Class + """, accessibility: Accessibility.Protected, modifiers: new DeclarationModifiers(isVirtual: true), returnType: typeof(int), statements: "Return 0"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddShadowsMethod() - { - var input = "Class [|C|]\n End Class"; - var expected = @"Class C - Public Shadows Function ToString() As String - $$ - End Function -End Class"; - await TestAddMethodAsync(input, expected, + public Task AddShadowsMethod() + => TestAddMethodAsync("Class [|C|]\n End Class", """ + Class C + Public Shadows Function ToString() As String + $$ + End Function + End Class + """, name: "ToString", accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isNew: true), returnType: typeof(string), statements: "Return String.Empty"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public async Task AddExplicitImplementation() { var input = "Interface I\n Sub M(i As Integer)\n End Interface\n Class [|C|]\n Implements I\n End Class"; - var expected = @"Interface I - Sub M(i As Integer) - End Interface - Class C - Implements I - - Public Sub M(i As Integer) Implements I.M - End Sub -End Class"; - await TestAddMethodAsync(input, expected, + await TestAddMethodAsync(input, """ + Interface I + Sub M(i As Integer) + End Interface + Class C + Implements I + + Public Sub M(i As Integer) Implements I.M + End Sub + End Class + """, name: "M", returnType: typeof(void), parameters: Parameters(Parameter(typeof(int), "i")), @@ -647,53 +578,46 @@ await TestAddMethodAsync(input, expected, } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddTrueFalseOperators() - { - var input = @" -Class [|C|] -End Class -"; - var expected = @" -Class C - Public Shared Operator IsTrue(other As C) As Boolean - $$ - End Operator - - Public Shared Operator IsFalse(other As C) As Boolean - $$ - End Operator -End Class -"; - await TestAddOperatorsAsync(input, expected, + public Task AddTrueFalseOperators() + => TestAddOperatorsAsync(""" + Class [|C|] + End Class + """, """ + Class C + Public Shared Operator IsTrue(other As C) As Boolean + $$ + End Operator + + Public Shared Operator IsFalse(other As C) As Boolean + $$ + End Operator + End Class + """, [CodeGenerationOperatorKind.True, CodeGenerationOperatorKind.False], parameters: Parameters(Parameter("C", "other")), returnType: typeof(bool), statements: "Return False"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddUnaryOperators() - { - var input = @" -Class [|C|] -End Class -"; - var expected = @" -Class C - Public Shared Operator +(other As C) As Object - $$ - End Operator - - Public Shared Operator -(other As C) As Object - $$ - End Operator - - Public Shared Operator Not(other As C) As Object - $$ - End Operator -End Class -"; - await TestAddOperatorsAsync(input, expected, + public Task AddUnaryOperators() + => TestAddOperatorsAsync(""" + Class [|C|] + End Class + """, """ + Class C + Public Shared Operator +(other As C) As Object + $$ + End Operator + + Public Shared Operator -(other As C) As Object + $$ + End Operator + + Public Shared Operator Not(other As C) As Object + $$ + End Operator + End Class + """, [ CodeGenerationOperatorKind.UnaryPlus, CodeGenerationOperatorKind.UnaryNegation, @@ -702,75 +626,71 @@ await TestAddOperatorsAsync(input, expected, parameters: Parameters(Parameter("C", "other")), returnType: typeof(object), statements: "Return Nothing"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddBinaryOperators() - { - var input = @" -Class [|C|] -End Class -"; - var expected = @" -Class C - Public Shared Operator +(a As C, b As C) As Object - $$ - End Operator - - Public Shared Operator -(a As C, b As C) As Object - $$ - End Operator - - Public Shared Operator *(a As C, b As C) As Object - $$ - End Operator - - Public Shared Operator /(a As C, b As C) As Object - $$ - End Operator - - Public Shared Operator \(a As C, b As C) As Object - $$ - End Operator - - Public Shared Operator ^(a As C, b As C) As Object - $$ - End Operator - - Public Shared Operator &(a As C, b As C) As Object - $$ - End Operator - - Public Shared Operator Like(a As C, b As C) As Object - $$ - End Operator - - Public Shared Operator Mod(a As C, b As C) As Object - $$ - End Operator - - Public Shared Operator And(a As C, b As C) As Object - $$ - End Operator - - Public Shared Operator Or(a As C, b As C) As Object - $$ - End Operator - - Public Shared Operator Xor(a As C, b As C) As Object - $$ - End Operator - - Public Shared Operator <<(a As C, b As C) As Object - $$ - End Operator - - Public Shared Operator >>(a As C, b As C) As Object - $$ - End Operator -End Class -"; - await TestAddOperatorsAsync(input, expected, + public Task AddBinaryOperators() + => TestAddOperatorsAsync(""" + Class [|C|] + End Class + """, """ + Class C + Public Shared Operator +(a As C, b As C) As Object + $$ + End Operator + + Public Shared Operator -(a As C, b As C) As Object + $$ + End Operator + + Public Shared Operator *(a As C, b As C) As Object + $$ + End Operator + + Public Shared Operator /(a As C, b As C) As Object + $$ + End Operator + + Public Shared Operator \(a As C, b As C) As Object + $$ + End Operator + + Public Shared Operator ^(a As C, b As C) As Object + $$ + End Operator + + Public Shared Operator &(a As C, b As C) As Object + $$ + End Operator + + Public Shared Operator Like(a As C, b As C) As Object + $$ + End Operator + + Public Shared Operator Mod(a As C, b As C) As Object + $$ + End Operator + + Public Shared Operator And(a As C, b As C) As Object + $$ + End Operator + + Public Shared Operator Or(a As C, b As C) As Object + $$ + End Operator + + Public Shared Operator Xor(a As C, b As C) As Object + $$ + End Operator + + Public Shared Operator <<(a As C, b As C) As Object + $$ + End Operator + + Public Shared Operator >>(a As C, b As C) As Object + $$ + End Operator + End Class + """, [ CodeGenerationOperatorKind.Addition, CodeGenerationOperatorKind.Subtraction, @@ -790,43 +710,39 @@ await TestAddOperatorsAsync(input, expected, parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")), returnType: typeof(object), statements: "Return Nothing"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddComparisonOperators() - { - var input = @" -Class [|C|] -End Class -"; - var expected = @" -Class C - Public Shared Operator =(a As C, b As C) As Boolean - $$ - End Operator - - Public Shared Operator <>(a As C, b As C) As Boolean - $$ - End Operator - - Public Shared Operator >(a As C, b As C) As Boolean - $$ - End Operator - - Public Shared Operator <(a As C, b As C) As Boolean - $$ - End Operator - - Public Shared Operator >=(a As C, b As C) As Boolean - $$ - End Operator - - Public Shared Operator <=(a As C, b As C) As Boolean - $$ - End Operator -End Class -"; - await TestAddOperatorsAsync(input, expected, + public Task AddComparisonOperators() + => TestAddOperatorsAsync(""" + Class [|C|] + End Class + """, """ + Class C + Public Shared Operator =(a As C, b As C) As Boolean + $$ + End Operator + + Public Shared Operator <>(a As C, b As C) As Boolean + $$ + End Operator + + Public Shared Operator >(a As C, b As C) As Boolean + $$ + End Operator + + Public Shared Operator <(a As C, b As C) As Boolean + $$ + End Operator + + Public Shared Operator >=(a As C, b As C) As Boolean + $$ + End Operator + + Public Shared Operator <=(a As C, b As C) As Boolean + $$ + End Operator + End Class + """, [ CodeGenerationOperatorKind.Equality, CodeGenerationOperatorKind.Inequality, @@ -838,866 +754,764 @@ await TestAddOperatorsAsync(input, expected, parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")), returnType: typeof(bool), statements: "Return True"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddUnsupportedOperator() - { - var input = "Class [|C|]\n End Class"; - await TestAddUnsupportedOperatorAsync(input, + public Task AddUnsupportedOperator() + => TestAddUnsupportedOperatorAsync("Class [|C|]\n End Class", operatorKind: CodeGenerationOperatorKind.Increment, parameters: Parameters(Parameter("C", "other")), returnType: typeof(bool), statements: "Return True"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddExplicitConversion() - { - var input = "Class [|C|]\n End Class"; - var expected = @"Class C - Public Shared Narrowing Operator CType(other As C) As Integer - $$ - End Operator -End Class"; - await TestAddConversionAsync(input, expected, + public Task AddExplicitConversion() + => TestAddConversionAsync("Class [|C|]\n End Class", """ + Class C + Public Shared Narrowing Operator CType(other As C) As Integer + $$ + End Operator + End Class + """, toType: typeof(int), fromType: Parameter("C", "other"), statements: "Return 0"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddImplicitConversion() - { - var input = "Class [|C|]\n End Class"; - var expected = @"Class C - Public Shared Widening Operator CType(other As C) As Integer - $$ - End Operator -End Class"; - await TestAddConversionAsync(input, expected, + public Task AddImplicitConversion() + => TestAddConversionAsync("Class [|C|]\n End Class", """ + Class C + Public Shared Widening Operator CType(other As C) As Integer + $$ + End Operator + End Class + """, toType: typeof(int), fromType: Parameter("C", "other"), isImplicit: true, statements: "Return 0"); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddStatementsToSub() - { - var input = "Class C\n [|Public Sub M\n Console.WriteLine(1)\n End Sub|]\n End Class"; - var expected = @"Class C - Public Sub M - Console.WriteLine(1) -$$ End Sub - End Class"; - await TestAddStatementsAsync(input, expected, "Console.WriteLine(2)"); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddStatementsToOperator() - { - var input = "Class C\n [|Shared Operator +(arg As C) As C\n Return arg\n End Operator|]\n End Class"; - var expected = @"Class C - Shared Operator +(arg As C) As C - Return arg -$$ End Operator - End Class"; - await TestAddStatementsAsync(input, expected, "Return Nothing"); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddStatementsToPropertySetter() - { - var input = "Imports System\n Class C\n WriteOnly Property P As String\n [|Set\n End Set|]\n End Property\n End Class"; - var expected = @"Imports System - Class C - WriteOnly Property P As String - Set -$$ End Set - End Property - End Class"; - await TestAddStatementsAsync(input, expected, "Console.WriteLine(\"Setting the value\""); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddParametersToMethod() - { - var input = "Class C\n Public [|Sub M()\n End Sub|]\n End Class"; - var expected = @"Class C - Public Sub M(numAs Integer, OptionaltextAs String = ""Hello!"",OptionalfloatingAs Single = 0.5) - End Sub - End Class"; - await TestAddParametersAsync(input, expected, + public Task AddStatementsToSub() + => TestAddStatementsAsync("Class C\n [|Public Sub M\n Console.WriteLine(1)\n End Sub|]\n End Class", """ + Class C + Public Sub M + Console.WriteLine(1) + $$ End Sub + End Class + """, "Console.WriteLine(2)"); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task AddStatementsToOperator() + => TestAddStatementsAsync("Class C\n [|Shared Operator +(arg As C) As C\n Return arg\n End Operator|]\n End Class", """ + Class C + Shared Operator +(arg As C) As C + Return arg + $$ End Operator + End Class + """, "Return Nothing"); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task AddStatementsToPropertySetter() + => TestAddStatementsAsync("Imports System\n Class C\n WriteOnly Property P As String\n [|Set\n End Set|]\n End Property\n End Class", """ + Imports System + Class C + WriteOnly Property P As String + Set + $$ End Set + End Property + End Class + """, """ + Console.WriteLine("Setting the value" + """); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task AddParametersToMethod() + => TestAddParametersAsync("Class C\n Public [|Sub M()\n End Sub|]\n End Class", """ + Class C + Public Sub M(numAs Integer, OptionaltextAs String = "Hello!",OptionalfloatingAs Single = 0.5) + End Sub + End Class + """, Parameters(Parameter(typeof(int), "num"), Parameter(typeof(string), "text", true, "Hello!"), Parameter(typeof(float), "floating", true, .5F))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844460")] - public async Task AddParametersToPropertyBlock() - { - var input = "Class C\n [|Public Property P As String\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property|]\n End Class"; - var expected = @"Class C - Public Property P (numAs Integer) As String - Get - Return String.Empty - End Get - Set(value As String) - End Set - End Property - End Class"; - await TestAddParametersAsync(input, expected, + public Task AddParametersToPropertyBlock() + => TestAddParametersAsync("Class C\n [|Public Property P As String\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property|]\n End Class", """ + Class C + Public Property P (numAs Integer) As String + Get + Return String.Empty + End Get + Set(value As String) + End Set + End Property + End Class + """, Parameters(Parameter(typeof(int), "num"))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844460")] - public async Task AddParametersToPropertyStatement() - { - var input = "Class C\n [|Public Property P As String|]\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property\n End Class"; - var expected = @"Class C - Public Property P (numAs Integer) As String - Get - Return String.Empty - End Get - Set(value As String) - End Set - End Property - End Class"; - await TestAddParametersAsync(input, expected, + public Task AddParametersToPropertyStatement() + => TestAddParametersAsync("Class C\n [|Public Property P As String|]\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property\n End Class", """ + Class C + Public Property P (numAs Integer) As String + Get + Return String.Empty + End Get + Set(value As String) + End Set + End Property + End Class + """, Parameters(Parameter(typeof(int), "num"))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844460")] - public async Task AddParametersToPropertyGetter_ShouldNotSucceed() - { - var input = "Class C\n Public Property P As String\n [|Get\n Return String.Empty\n End Get|]\n Set(value As String)\n End Set\n End Property\n End Class"; - var expected = "Class C\n Public Property P As String\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property\n End Class"; - await TestAddParametersAsync(input, expected, + public Task AddParametersToPropertyGetter_ShouldNotSucceed() + => TestAddParametersAsync("Class C\n Public Property P As String\n [|Get\n Return String.Empty\n End Get|]\n Set(value As String)\n End Set\n End Property\n End Class", "Class C\n Public Property P As String\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property\n End Class", Parameters(Parameter(typeof(int), "num"))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844460")] - public async Task AddParametersToPropertySetter_ShouldNotSucceed() - { - var input = "Class C\n Public Property P As String\n Get\n Return String.Empty\n End Get\n [|Set(value As String)\n End Set|]\n End Property\n End Class"; - var expected = "Class C\n Public Property P As String\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property\n End Class"; - await TestAddParametersAsync(input, expected, + public Task AddParametersToPropertySetter_ShouldNotSucceed() + => TestAddParametersAsync("Class C\n Public Property P As String\n Get\n Return String.Empty\n End Get\n [|Set(value As String)\n End Set|]\n End Property\n End Class", "Class C\n Public Property P As String\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property\n End Class", Parameters(Parameter(typeof(int), "num"))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddParametersToOperator() - { - var input = "Class C\n [|Shared Operator +(a As C) As C\n Return a\n End Operator|]\n End Class"; - var expected = @"Class C - Shared Operator +(a As C,bAs C) As C - Return a - End Operator - End Class"; - await TestAddParametersAsync(input, expected, + public Task AddParametersToOperator() + => TestAddParametersAsync("Class C\n [|Shared Operator +(a As C) As C\n Return a\n End Operator|]\n End Class", """ + Class C + Shared Operator +(a As C,bAs C) As C + Return a + End Operator + End Class + """, Parameters(Parameter("C", "b"))); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAutoProperty() - { - var input = "Class [|C|]\n End Class"; - var expected = @"Class C - Public Property P As Integer -End Class"; - await TestAddPropertyAsync(input, expected, + public Task AddAutoProperty() + => TestAddPropertyAsync("Class [|C|]\n End Class", """ + Class C + Public Property P As Integer + End Class + """, type: typeof(int)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public async Task AddPropertyToClassFromSourceSymbol() { - var sourceGenerated = @"Public Class [|C2|] - Public Property P As Integer - Get - Return 0 - End Get - End Property -End Class"; - var input = "Class [|C1|]\nEnd Class"; - var expected = @"Class C1 - Public Property P As Integer - Get - Return 0 - End Get - End Property -End Class"; var context = new CodeGenerationContext(reuseSyntax: true); - await TestGenerateFromSourceSymbolAsync(sourceGenerated, input, expected, onlyGenerateMembers: true, context: context); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddPropertyWithoutAccessorBodies() - { - var input = "Class [|C|]\n End Class"; - var expected = @"Class C - Public Property P As Integer -End Class"; - await TestAddPropertyAsync(input, expected, + await TestGenerateFromSourceSymbolAsync(""" + Public Class [|C2|] + Public Property P As Integer + Get + Return 0 + End Get + End Property + End Class + """, "Class [|C1|]\nEnd Class", """ + Class C1 + Public Property P As Integer + Get + Return 0 + End Get + End Property + End Class + """, onlyGenerateMembers: true, context: context); + } + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task AddPropertyWithoutAccessorBodies() + => TestAddPropertyAsync("Class [|C|]\n End Class", """ + Class C + Public Property P As Integer + End Class + """, type: typeof(int), getStatements: "Return 0", setStatements: "Me.P = Value", context: new CodeGenerationContext(generateMethodBodies: false)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddIndexer() - { - var input = "Class [|C|]\n End Class"; - var expected = @"Class C - Default Public ReadOnly Property Item(i As Integer) As String - Get - $$ - End Get - End Property -End Class"; - await TestAddPropertyAsync(input, expected, + public Task AddIndexer() + => TestAddPropertyAsync("Class [|C|]\n End Class", """ + Class C + Default Public ReadOnly Property Item(i As Integer) As String + Get + $$ + End Get + End Property + End Class + """, name: "Item", type: typeof(string), parameters: Parameters(Parameter(typeof(int), "i")), getStatements: "Return String.Empty", isIndexer: true); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToTypes() - { - var input = "Class [|C|]\n End Class"; - var expected = @" -Class C -End Class"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeFromTypes() - { - var input = @" - -Class [|C|] -End Class"; - var expected = @" -Class C -End Class"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToMethods() - { - var input = "Class C\n Public Sub [|M()|] \n End Sub \n End Class"; - var expected = @"Class C - - Public Sub M() - End Sub - End Class"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeFromMethods() - { - var input = @" -Class C - - Public Sub [|M()|] - End Sub -End Class"; - var expected = @" -Class C - Public Sub M() - End Sub -End Class"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToFields() - { - var input = "Class C\n [|Public F As Integer|]\n End Class"; - var expected = @"Class C - - Public F As Integer -End Class"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeFromFields() - { - var input = @" -Class C - - Public [|F|] As Integer -End Class"; - var expected = @" -Class C - Public F As Integer -End Class"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToProperties() - { - var input = "Class C \n Public Property [|P|] As Integer \n End Class"; - var expected = @"Class C - - Public Property P As Integer -End Class"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeFromProperties() - { - var input = @" -Class C - - Public Property [|P|] As Integer -End Class"; - var expected = @" -Class C - Public Property P As Integer -End Class"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToPropertyAccessor() - { - var input = "Class C \n Public ReadOnly Property P As Integer \n [|Get|] \n Return 10 \n End Get \n End Property \n End Class"; - var expected = @"Class C - Public ReadOnly Property P As Integer - - Get - Return 10 - End Get - End Property - End Class"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeFromPropertyAccessor() - { - var input = @" -Class C - Public Property P As Integer - - [|Get|] - Return 10 - End Get -End Class"; - var expected = @" -Class C - Public Property P As Integer - Get - Return 10 - End Get -End Class"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToEnums() - { - var input = "Module M \n [|Enum C|] \n One \n Two \n End Enum\n End Module"; - var expected = @"Module M - - Enum C - One - Two - End Enum - End Module"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeFromEnums() - { - var input = @" -Module M - - Enum [|C|] - One - Two - End Enum -End Module"; - var expected = @" -Module M - Enum C - One - Two - End Enum -End Module"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToEnumMembers() - { - var input = "Module M \n Enum C \n [|One|] \n Two \n End Enum\n End Module"; - var expected = @"Module M - Enum C - - One - Two - End Enum - End Module"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeFromEnumMembers() - { - var input = @" -Module M - Enum C - - [|One|] - Two - End Enum -End Module"; - var expected = @" -Module M - Enum C - One - Two - End Enum -End Module"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToModule() - { - var input = "Module [|M|] \n End Module"; - var expected = @" -Module M -End Module"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeFromModule() - { - var input = @" - -Module [|M|] -End Module"; - var expected = @" -Module M -End Module"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToOperator() - { - var input = "Class C \n Public Shared Operator [|+|] (x As C, y As C) As C \n Return New C() \n End Operator \n End Class"; - var expected = @"Class C - - Public Shared Operator +(x As C, y As C) As C - Return New C() - End Operator - End Class"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeFromOperator() - { - var input = @" -Module M - Class C - - Public Shared Operator [|+|](x As C, y As C) As C - Return New C() - End Operator - End Class -End Module"; - var expected = @" -Module M - Class C - Public Shared Operator +(x As C, y As C) As C - Return New C() - End Operator - End Class -End Module"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToDelegate() - { - var input = "Module M \n Delegate Sub [|D()|]\n End Module"; - var expected = "Module M\n \n Delegate Sub D()\nEnd Module"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeFromDelegate() - { - var input = @" -Module M - - Delegate Sub [|D()|] -End Module"; - var expected = @" -Module M - Delegate Sub D() -End Module"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToParam() - { - var input = "Class C \n Public Sub M([|x As Integer|]) \n End Sub \n End Class"; - var expected = "Class C \n Public Sub M( x As Integer) \n End Sub \n End Class"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeFromParam() - { - var input = @" -Class C - Public Sub M( [|x As Integer|]) - End Sub -End Class"; - var expected = @" -Class C - Public Sub M(x As Integer) - End Sub -End Class"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeToCompilationUnit() - { - var input = "[|Class C \n End Class \n Class D \n End Class|]"; - var expected = "\nClass C\nEnd Class\nClass D\nEnd Class"; - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute), VB.SyntaxFactory.Token(VB.SyntaxKind.AssemblyKeyword)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task AddAttributeWithWrongTarget() - { - var input = "[|Class C \n End Class \n Class D \n End Class|]"; - var expected = " Class C \n End Class \n Class D \n End Class"; - await Assert.ThrowsAsync(async () => - await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute), VB.SyntaxFactory.Token(VB.SyntaxKind.ReturnKeyword))); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeWithTrivia() - { - // With trivia. - var input = @"' Comment 1 - ' Comment 2 -Class [|C|] -End Class"; - var expected = @"' Comment 1 -Class C -End Class"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeWithTrivia_NewLine() - { - // With trivia, redundant newline at end of attribute removed. - var input = @"' Comment 1 - -Class [|C|] -End Class"; - var expected = @"' Comment 1 -Class C -End Class"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeWithMultipleAttributes() - { - // Multiple attributes. - var input = @"' Comment 1 -< System.Serializable , System.Flags> ' Comment 2 -Class [|C|] -End Class"; - var expected = @"' Comment 1 - ' Comment 2 -Class C -End Class"; - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task RemoveAttributeWithMultipleAttributeLists() - { - // Multiple attribute lists. - var input = @"' Comment 1 -< System.Serializable , System.Flags> ' Comment 2 - ' Comment 3 -Class [|C|] -End Class"; - var expected = @"' Comment 1 - ' Comment 2 - ' Comment 3 -Class C -End Class"; - - await TestRemoveAttributeAsync(input, expected, typeof(SerializableAttribute)); - } + public Task AddAttributeToTypes() + => TestAddAttributeAsync("Class [|C|]\n End Class", """ + + Class C + End Class + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task RemoveAttributeFromTypes() + => TestRemoveAttributeAsync(""" + + Class [|C|] + End Class + """, """ + Class C + End Class + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task AddAttributeToMethods() + => TestAddAttributeAsync("Class C\n Public Sub [|M()|] \n End Sub \n End Class", """ + Class C + + Public Sub M() + End Sub + End Class + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task RemoveAttributeFromMethods() + => TestRemoveAttributeAsync(""" + Class C + + Public Sub [|M()|] + End Sub + End Class + """, """ + Class C + Public Sub M() + End Sub + End Class + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task AddAttributeToFields() + => TestAddAttributeAsync("Class C\n [|Public F As Integer|]\n End Class", """ + Class C + + Public F As Integer + End Class + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task RemoveAttributeFromFields() + => TestRemoveAttributeAsync(""" + Class C + + Public [|F|] As Integer + End Class + """, """ + Class C + Public F As Integer + End Class + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task AddAttributeToProperties() + => TestAddAttributeAsync("Class C \n Public Property [|P|] As Integer \n End Class", """ + Class C + + Public Property P As Integer + End Class + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task RemoveAttributeFromProperties() + => TestRemoveAttributeAsync(""" + Class C + + Public Property [|P|] As Integer + End Class + """, """ + Class C + Public Property P As Integer + End Class + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task AddAttributeToPropertyAccessor() + => TestAddAttributeAsync("Class C \n Public ReadOnly Property P As Integer \n [|Get|] \n Return 10 \n End Get \n End Property \n End Class", """ + Class C + Public ReadOnly Property P As Integer + + Get + Return 10 + End Get + End Property + End Class + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task RemoveAttributeFromPropertyAccessor() + => TestRemoveAttributeAsync(""" + Class C + Public Property P As Integer + + [|Get|] + Return 10 + End Get + End Class + """, """ + Class C + Public Property P As Integer + Get + Return 10 + End Get + End Class + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task AddAttributeToEnums() + => TestAddAttributeAsync("Module M \n [|Enum C|] \n One \n Two \n End Enum\n End Module", """ + Module M + + Enum C + One + Two + End Enum + End Module + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task RemoveAttributeFromEnums() + => TestRemoveAttributeAsync(""" + Module M + + Enum [|C|] + One + Two + End Enum + End Module + """, """ + Module M + Enum C + One + Two + End Enum + End Module + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task AddAttributeToEnumMembers() + => TestAddAttributeAsync("Module M \n Enum C \n [|One|] \n Two \n End Enum\n End Module", """ + Module M + Enum C + + One + Two + End Enum + End Module + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task RemoveAttributeFromEnumMembers() + => TestRemoveAttributeAsync(""" + Module M + Enum C + + [|One|] + Two + End Enum + End Module + """, """ + Module M + Enum C + One + Two + End Enum + End Module + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task AddAttributeToModule() + => TestAddAttributeAsync("Module [|M|] \n End Module", """ + + Module M + End Module + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task RemoveAttributeFromModule() + => TestRemoveAttributeAsync(""" + + Module [|M|] + End Module + """, """ + Module M + End Module + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task AddAttributeToOperator() + => TestAddAttributeAsync("Class C \n Public Shared Operator [|+|] (x As C, y As C) As C \n Return New C() \n End Operator \n End Class", """ + Class C + + Public Shared Operator +(x As C, y As C) As C + Return New C() + End Operator + End Class + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task RemoveAttributeFromOperator() + => TestRemoveAttributeAsync(""" + Module M + Class C + + Public Shared Operator [|+|](x As C, y As C) As C + Return New C() + End Operator + End Class + End Module + """, """ + Module M + Class C + Public Shared Operator +(x As C, y As C) As C + Return New C() + End Operator + End Class + End Module + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task AddAttributeToDelegate() + => TestAddAttributeAsync("Module M \n Delegate Sub [|D()|]\n End Module", "Module M\n \n Delegate Sub D()\nEnd Module", typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task RemoveAttributeFromDelegate() + => TestRemoveAttributeAsync(""" + Module M + + Delegate Sub [|D()|] + End Module + """, """ + Module M + Delegate Sub D() + End Module + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task AddAttributeToParam() + => TestAddAttributeAsync("Class C \n Public Sub M([|x As Integer|]) \n End Sub \n End Class", "Class C \n Public Sub M( x As Integer) \n End Sub \n End Class", typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task RemoveAttributeFromParam() + => TestRemoveAttributeAsync(""" + Class C + Public Sub M( [|x As Integer|]) + End Sub + End Class + """, """ + Class C + Public Sub M(x As Integer) + End Sub + End Class + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task AddAttributeToCompilationUnit() + => TestAddAttributeAsync("[|Class C \n End Class \n Class D \n End Class|]", "\nClass C\nEnd Class\nClass D\nEnd Class", typeof(SerializableAttribute), VB.SyntaxFactory.Token(VB.SyntaxKind.AssemblyKeyword)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task AddAttributeWithWrongTarget() + => Assert.ThrowsAsync(async () => + await TestAddAttributeAsync("[|Class C \n End Class \n Class D \n End Class|]", " Class C \n End Class \n Class D \n End Class", typeof(SerializableAttribute), VB.SyntaxFactory.Token(VB.SyntaxKind.ReturnKeyword))); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task RemoveAttributeWithTrivia() + => TestRemoveAttributeAsync(""" + ' Comment 1 + ' Comment 2 + Class [|C|] + End Class + """, """ + ' Comment 1 + Class C + End Class + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task RemoveAttributeWithTrivia_NewLine() + => TestRemoveAttributeAsync(""" + ' Comment 1 + + Class [|C|] + End Class + """, """ + ' Comment 1 + Class C + End Class + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task RemoveAttributeWithMultipleAttributes() + => TestRemoveAttributeAsync(""" + ' Comment 1 + < System.Serializable , System.Flags> ' Comment 2 + Class [|C|] + End Class + """, """ + ' Comment 1 + ' Comment 2 + Class C + End Class + """, typeof(SerializableAttribute)); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task RemoveAttributeWithMultipleAttributeLists() + => TestRemoveAttributeAsync(""" + ' Comment 1 + < System.Serializable , System.Flags> ' Comment 2 + ' Comment 3 + Class [|C|] + End Class + """, """ + ' Comment 1 + ' Comment 2 + ' Comment 3 + Class C + End Class + """, typeof(SerializableAttribute)); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public async Task TestUpdateModifiers() { - var input = @"Public Shared Class [|C|] ' Comment 1 - ' Comment 2 -End Class"; - var expected = @"Friend Partial NotInheritable Class C ' Comment 1 - ' Comment 2 -End Class"; var eol = VB.SyntaxFactory.EndOfLine(@""); var newModifiers = new[] { VB.SyntaxFactory.Token(VB.SyntaxKind.FriendKeyword).WithLeadingTrivia(eol) }.Concat( CreateModifierTokens(new DeclarationModifiers(isSealed: true, isPartial: true), LanguageNames.VisualBasic)); - await TestUpdateDeclarationAsync(input, expected, modifiers: newModifiers); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task TestUpdateAccessibility() - { - var input = @"' Comment 0 -Public Shared Class [|C|] ' Comment 1 - ' Comment 2 -End Class"; - var expected = @"' Comment 0 -Protected Friend Shared Class C ' Comment 1 - ' Comment 2 -End Class"; - await TestUpdateDeclarationAsync(input, expected, accessibility: Accessibility.ProtectedOrFriend); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] - public async Task TestUpdateDeclarationType() - { - var input = @" -Public Shared Class C - ' Comment 1 - Public Shared Function [|F|]() As Char - Return 0 - End Function -End Class"; - var expected = @" -Public Shared Class C - ' Comment 1 - Public Shared Function F() As Integer - Return 0 - End Function -End Class"; - await TestUpdateDeclarationAsync(input, expected, getType: GetTypeSymbol(typeof(int))); - } + await TestUpdateDeclarationAsync(""" + Public Shared Class [|C|] ' Comment 1 + ' Comment 2 + End Class + """, """ + Friend Partial NotInheritable Class C ' Comment 1 + ' Comment 2 + End Class + """, modifiers: newModifiers); + } + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task TestUpdateAccessibility() + => TestUpdateDeclarationAsync(""" + ' Comment 0 + Public Shared Class [|C|] ' Comment 1 + ' Comment 2 + End Class + """, """ + ' Comment 0 + Protected Friend Shared Class C ' Comment 1 + ' Comment 2 + End Class + """, accessibility: Accessibility.ProtectedOrFriend); + + [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] + public Task TestUpdateDeclarationType() + => TestUpdateDeclarationAsync(""" + Public Shared Class C + ' Comment 1 + Public Shared Function [|F|]() As Char + Return 0 + End Function + End Class + """, """ + Public Shared Class C + ' Comment 1 + Public Shared Function F() As Integer + Return 0 + End Function + End Class + """, getType: GetTypeSymbol(typeof(int))); [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public async Task TestUpdateDeclarationMembers() { - var input = @" -Public Shared Class [|C|] - ' Comment 0 - Public Shared {|RetainedMember:f|} As Integer - - ' Comment 1 - Public Shared Function F() As Char - Return 0 - End Function -End Class"; - var expected = @" -Public Shared Class C - ' Comment 0 - Public Shared f As Integer - Public Shared f2 As Integer -End Class"; var getField = CreateField(Accessibility.Public, new DeclarationModifiers(isStatic: true), typeof(int), "f2"); var getMembers = ImmutableArray.Create(getField); - await TestUpdateDeclarationAsync(input, expected, getNewMembers: getMembers); + await TestUpdateDeclarationAsync(""" + Public Shared Class [|C|] + ' Comment 0 + Public Shared {|RetainedMember:f|} As Integer + + ' Comment 1 + Public Shared Function F() As Char + Return 0 + End Function + End Class + """, """ + Public Shared Class C + ' Comment 0 + Public Shared f As Integer + Public Shared f2 As Integer + End Class + """, getNewMembers: getMembers); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)] - public async Task SortModules() - { - var generationSource = "Public Class [|C|] \n End Class"; - var initial = "Namespace [|N|] \n Module M \n End Module \n End Namespace"; - var expected = @"Namespace N - Public Class C - End Class - - Module M - End Module - End Namespace"; - await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected); - } + public Task SortModules() + => TestGenerateFromSourceSymbolAsync("Public Class [|C|] \n End Class", "Namespace [|N|] \n Module M \n End Module \n End Namespace", """ + Namespace N + Public Class C + End Class + + Module M + End Module + End Namespace + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)] - public async Task SortOperators() - { - var generationSource = @" -Namespace N - Public Class [|C|] - ' Unary operators - Public Shared Operator IsFalse(other As C) As Boolean - Return False - End Operator - Public Shared Operator IsTrue(other As C) As Boolean - Return True - End Operator - Public Shared Operator Not(other As C) As C - Return Nothing - End Operator - Public Shared Operator -(other As C) As C - Return Nothing - End Operator - Public Shared Operator + (other As C) As C - Return Nothing - End Operator - Public Shared Narrowing Operator CType(c As C) As Integer - Return 0 - End Operator - - ' Binary operators - Public Shared Operator >= (a As C, b As C) As Boolean - Return True - End Operator - Public Shared Operator <= (a As C, b As C) As Boolean - Return True - End Operator - Public Shared Operator > (a As C, b As C) As Boolean - Return True - End Operator - Public Shared Operator < (a As C, b As C) As Boolean - Return True - End Operator - Public Shared Operator <> (a As C, b As C) As Boolean - Return True - End Operator - Public Shared Operator = (a As C, b As C) As Boolean - Return True - End Operator - Public Shared Operator >> (a As C, shift As Integer) As C - Return Nothing - End Operator - Public Shared Operator << (a As C, shift As Integer) As C - Return Nothing - End Operator - Public Shared Operator Xor(a As C, b As C) As C - Return Nothing - End Operator - Public Shared Operator Or(a As C, b As C) As C - Return Nothing - End Operator - Public Shared Operator And(a As C, b As C) As C - Return Nothing - End Operator - Public Shared Operator Mod(a As C, b As C) As C - Return Nothing - End Operator - Public Shared Operator Like (a As C, b As C) As C - Return Nothing - End Operator - Public Shared Operator & (a As C, b As C) As C - Return Nothing - End Operator - Public Shared Operator ^ (a As C, b As C) As C - Return Nothing - End Operator - Public Shared Operator \ (a As C, b As C) As C - Return Nothing - End Operator - Public Shared Operator / (a As C, b As C) As C - Return Nothing - End Operator - Public Shared Operator *(a As C, b As C) As C - Return Nothing - End Operator - Public Shared Operator -(a As C, b As C) As C - Return Nothing - End Operator - Public Shared Operator + (a As C, b As C) As C - Return Nothing - End Operator - End Class -End Namespace"; - var initial = "Namespace [|N|] \n End Namespace"; - var expected = @"Namespace N - Public Class C - Public Shared Operator +(other As C) As C - Public Shared Operator +(a As C, b As C) As C - Public Shared Operator -(other As C) As C - Public Shared Operator -(a As C, b As C) As C - Public Shared Operator *(a As C, b As C) As C - Public Shared Operator /(a As C, b As C) As C - Public Shared Operator \(a As C, b As C) As C - Public Shared Operator ^(a As C, b As C) As C - Public Shared Operator &(a As C, b As C) As C - Public Shared Operator Not(other As C) As C - Public Shared Operator Like(a As C, b As C) As C - Public Shared Operator Mod(a As C, b As C) As C - Public Shared Operator And(a As C, b As C) As C - Public Shared Operator Or(a As C, b As C) As C - Public Shared Operator Xor(a As C, b As C) As C - Public Shared Operator <<(a As C, shift As Integer) As C - Public Shared Operator >>(a As C, shift As Integer) As C - Public Shared Operator =(a As C, b As C) As Boolean - Public Shared Operator <>(a As C, b As C) As Boolean - Public Shared Operator >(a As C, b As C) As Boolean - Public Shared Operator <(a As C, b As C) As Boolean - Public Shared Operator >=(a As C, b As C) As Boolean - Public Shared Operator <=(a As C, b As C) As Boolean - Public Shared Operator IsTrue(other As C) As Boolean - Public Shared Operator IsFalse(other As C) As Boolean - Public Shared Narrowing Operator CType(c As C) As Integer - End Class -End Namespace"; - await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, + public Task SortOperators() + => TestGenerateFromSourceSymbolAsync(""" + Namespace N + Public Class [|C|] + ' Unary operators + Public Shared Operator IsFalse(other As C) As Boolean + Return False + End Operator + Public Shared Operator IsTrue(other As C) As Boolean + Return True + End Operator + Public Shared Operator Not(other As C) As C + Return Nothing + End Operator + Public Shared Operator -(other As C) As C + Return Nothing + End Operator + Public Shared Operator + (other As C) As C + Return Nothing + End Operator + Public Shared Narrowing Operator CType(c As C) As Integer + Return 0 + End Operator + + ' Binary operators + Public Shared Operator >= (a As C, b As C) As Boolean + Return True + End Operator + Public Shared Operator <= (a As C, b As C) As Boolean + Return True + End Operator + Public Shared Operator > (a As C, b As C) As Boolean + Return True + End Operator + Public Shared Operator < (a As C, b As C) As Boolean + Return True + End Operator + Public Shared Operator <> (a As C, b As C) As Boolean + Return True + End Operator + Public Shared Operator = (a As C, b As C) As Boolean + Return True + End Operator + Public Shared Operator >> (a As C, shift As Integer) As C + Return Nothing + End Operator + Public Shared Operator << (a As C, shift As Integer) As C + Return Nothing + End Operator + Public Shared Operator Xor(a As C, b As C) As C + Return Nothing + End Operator + Public Shared Operator Or(a As C, b As C) As C + Return Nothing + End Operator + Public Shared Operator And(a As C, b As C) As C + Return Nothing + End Operator + Public Shared Operator Mod(a As C, b As C) As C + Return Nothing + End Operator + Public Shared Operator Like (a As C, b As C) As C + Return Nothing + End Operator + Public Shared Operator & (a As C, b As C) As C + Return Nothing + End Operator + Public Shared Operator ^ (a As C, b As C) As C + Return Nothing + End Operator + Public Shared Operator \ (a As C, b As C) As C + Return Nothing + End Operator + Public Shared Operator / (a As C, b As C) As C + Return Nothing + End Operator + Public Shared Operator *(a As C, b As C) As C + Return Nothing + End Operator + Public Shared Operator -(a As C, b As C) As C + Return Nothing + End Operator + Public Shared Operator + (a As C, b As C) As C + Return Nothing + End Operator + End Class + End Namespace + """, "Namespace [|N|] \n End Namespace", """ + Namespace N + Public Class C + Public Shared Operator +(other As C) As C + Public Shared Operator +(a As C, b As C) As C + Public Shared Operator -(other As C) As C + Public Shared Operator -(a As C, b As C) As C + Public Shared Operator *(a As C, b As C) As C + Public Shared Operator /(a As C, b As C) As C + Public Shared Operator \(a As C, b As C) As C + Public Shared Operator ^(a As C, b As C) As C + Public Shared Operator &(a As C, b As C) As C + Public Shared Operator Not(other As C) As C + Public Shared Operator Like(a As C, b As C) As C + Public Shared Operator Mod(a As C, b As C) As C + Public Shared Operator And(a As C, b As C) As C + Public Shared Operator Or(a As C, b As C) As C + Public Shared Operator Xor(a As C, b As C) As C + Public Shared Operator <<(a As C, shift As Integer) As C + Public Shared Operator >>(a As C, shift As Integer) As C + Public Shared Operator =(a As C, b As C) As Boolean + Public Shared Operator <>(a As C, b As C) As Boolean + Public Shared Operator >(a As C, b As C) As Boolean + Public Shared Operator <(a As C, b As C) As Boolean + Public Shared Operator >=(a As C, b As C) As Boolean + Public Shared Operator <=(a As C, b As C) As Boolean + Public Shared Operator IsTrue(other As C) As Boolean + Public Shared Operator IsFalse(other As C) As Boolean + Public Shared Narrowing Operator CType(c As C) As Integer + End Class + End Namespace + """, forceLanguage: LanguageNames.VisualBasic, context: new CodeGenerationContext(generateMethodBodies: false)); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/848357")] - public async Task TestConstraints() - { - var generationSource = @" -Namespace N - Public Class [|C|](Of T As Structure, U As Class) - Public Sub Goo(Of Q As New, R As IComparable)() - End Sub - Public Delegate Sub D(Of T1 As Structure, T2 As Class)(t As T1, u As T2) - End Class -End Namespace -"; - var initial = "Namespace [|N|] \n End Namespace"; - var expected = @"Namespace N - Public Class C(Of T As Structure, U As Class) - Public Sub Goo(Of Q As New, R As IComparable)() - Public Delegate Sub D(Of T1 As Structure, T2 As Class)(t As T1, u As T2) - End Class -End Namespace"; - await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, + public Task TestConstraints() + => TestGenerateFromSourceSymbolAsync(""" + Namespace N + Public Class [|C|](Of T As Structure, U As Class) + Public Sub Goo(Of Q As New, R As IComparable)() + End Sub + Public Delegate Sub D(Of T1 As Structure, T2 As Class)(t As T1, u As T2) + End Class + End Namespace + """, "Namespace [|N|] \n End Namespace", """ + Namespace N + Public Class C(Of T As Structure, U As Class) + Public Sub Goo(Of Q As New, R As IComparable)() + Public Delegate Sub D(Of T1 As Structure, T2 As Class)(t As T1, u As T2) + End Class + End Namespace + """, context: new CodeGenerationContext(generateMethodBodies: false), onlyGenerateMembers: true); - } } } diff --git a/src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.cs b/src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.cs index 03262947775fe..a9971796c1c3c 100644 --- a/src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.cs +++ b/src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.cs @@ -8,7 +8,6 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; -using System.Reflection.Metadata.Ecma335; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; diff --git a/src/EditorFeatures/Test/CodeRefactorings/CodeRefactoringServiceTest.cs b/src/EditorFeatures/Test/CodeRefactorings/CodeRefactoringServiceTest.cs index 975ee8a809929..cb23b6f13d489 100644 --- a/src/EditorFeatures/Test/CodeRefactorings/CodeRefactoringServiceTest.cs +++ b/src/EditorFeatures/Test/CodeRefactorings/CodeRefactoringServiceTest.cs @@ -38,9 +38,9 @@ public async Task TestExceptionInComputeRefactoringsAsync() [Fact] public async Task TestProjectRefactoringAsync() { - var code = @" - a -"; + var code = """ + a + """; using var workspace = TestWorkspace.CreateCSharp(code, composition: FeaturesTestCompositions.Features); var refactoringService = workspace.GetService(); @@ -76,12 +76,13 @@ public async Task TestTypeScriptRefactorings() { var composition = FeaturesTestCompositions.Features.AddParts(typeof(TypeScriptCodeRefactoringProvider)); - using var workspace = TestWorkspace.Create(@" - - - abc - -", composition: composition); + using var workspace = TestWorkspace.Create(""" + + + abc + + + """, composition: composition); var refactoringService = workspace.GetService(); @@ -178,7 +179,7 @@ public async Task TestAdditionalDocumentRefactoringAsync() // Verify code refactoring application var codeAction = txtRefactorings.Single(s => s.CodeActions.Single().action.Title == refactoring1.Title).CodeActions.Single().action; - var solution = await codeAction.GetChangedSolutionInternalAsync(project.Solution, CodeAnalysisProgress.None); + var solution = await codeAction.GetChangedSolutionInternalAsync(project.Solution, CodeAnalysisProgress.None, CancellationToken.None); var changedtxtDocument = solution.Projects.Single().AdditionalDocuments.Single(t => t.Id == txtAdditionalDocument.Id); Assert.Empty(txtAdditionalDocument.GetTextSynchronously(CancellationToken.None).ToString()); Assert.Equal(refactoring1.Title, changedtxtDocument.GetTextSynchronously(CancellationToken.None).ToString()); @@ -217,7 +218,7 @@ public async Task TestAnalyzerConfigDocumentRefactoringAsync() // Verify code refactoring application var codeAction = editorConfigRefactorings.Single(s => s.CodeActions.Single().action.Title == refactoring1.Title).CodeActions.Single().action; - var solution = await codeAction.GetChangedSolutionInternalAsync(project.Solution, CodeAnalysisProgress.None); + var solution = await codeAction.GetChangedSolutionInternalAsync(project.Solution, CodeAnalysisProgress.None, CancellationToken.None); var changedEditorConfig = solution.Projects.Single().AnalyzerConfigDocuments.Single(t => t.Id == editorConfig.Id); Assert.Empty(editorConfig.GetTextSynchronously(CancellationToken.None).ToString()); Assert.Equal(refactoring1.Title, changedEditorConfig.GetTextSynchronously(CancellationToken.None).ToString()); diff --git a/src/EditorFeatures/Test/CommentSelection/CommentUncommentSelectionCommandHandlerTests.cs b/src/EditorFeatures/Test/CommentSelection/CommentUncommentSelectionCommandHandlerTests.cs index 262d4caedafcb..166d491a783e9 100644 --- a/src/EditorFeatures/Test/CommentSelection/CommentUncommentSelectionCommandHandlerTests.cs +++ b/src/EditorFeatures/Test/CommentSelection/CommentUncommentSelectionCommandHandlerTests.cs @@ -76,70 +76,57 @@ public void Create() [WpfFact] public void Comment_EmptyLine() { - var code = @"|start||end|"; - CommentSelection(code, [], supportBlockComments: true); + CommentSelection(@"|start||end|", [], supportBlockComments: true); } [WpfFact] public void Comment_NoSelectionAtEndOfLine() { - var code = @"Some text on a line|start||end|"; - CommentSelection(code, new[] { new TextChange(TextSpan.FromBounds(0, 0), "//") }, supportBlockComments: true); + CommentSelection(@"Some text on a line|start||end|", new[] { new TextChange(TextSpan.FromBounds(0, 0), "//") }, supportBlockComments: true); } [WpfFact] public void Comment_Whitespace() { - var code = @" |start| |end| "; - CommentSelection(code, [], supportBlockComments: true); + CommentSelection(@" |start| |end| ", [], supportBlockComments: true); } [WpfFact] public void Comment_SingleLineBlockWithBlockSelection() { - var code = @"this is |start| some |end| text"; var expectedChanges = new[] { new TextChange(new TextSpan(8, 0), "/*"), new TextChange(new TextSpan(14, 0), "*/"), }; - CommentSelection(code, expectedChanges, supportBlockComments: true); + CommentSelection(@"this is |start| some |end| text", expectedChanges, supportBlockComments: true); } [WpfFact] public void Comment_MultilineWithBlockSelection() { - var code = @"this is |start| some -text that is |end| on -multiple lines"; var expectedChanges = new[] { new TextChange(new TextSpan(0, 0), "//"), new TextChange(new TextSpan(16, 0), "//"), }; - CommentSelection(code, expectedChanges, supportBlockComments: true); + CommentSelection(""" + this is |start| some + text that is |end| on + multiple lines + """, expectedChanges, supportBlockComments: true); } [WpfFact] public void Comment_SingleLineBlockWithNoBlockSelection() { - var code = @"this is |start| some |end| text"; - CommentSelection(code, new[] { new TextChange(TextSpan.FromBounds(0, 0), "//") }, supportBlockComments: false); + CommentSelection(@"this is |start| some |end| text", new[] { new TextChange(TextSpan.FromBounds(0, 0), "//") }, supportBlockComments: false); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/563915")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530300")] public void Comment_MultilineIndented() { - var code = @" -class Goo -{ - |start|void M() - { - }|end| -} -"; - var expectedChanges = new[] { new TextChange(new TextSpan(20, 0), "//"), @@ -147,7 +134,16 @@ class Goo new TextChange(new TextSpan(41, 0), "//"), }; CommentSelection( - code, + """ + + class Goo + { + |start|void M() + { + }|end| + } + + """, expectedChanges, supportBlockComments: false, expectedSelectedSpans: new[] { Span.FromBounds(16, 48) }); @@ -157,11 +153,13 @@ class Goo [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/563924")] public void Comment_ApplyTwice() { - var code = @"|start|class C -{ - void M() { } -}|end| -"; + var code = """ + |start|class C + { + void M() { } + }|end| + + """; var exportProvider = CreateExportProvider(); using var disposableView = EditorFactory.CreateView(exportProvider, code); var selectedSpans = SetupSelection(disposableView.TextView); @@ -198,35 +196,27 @@ void M() { } [WpfFact] public void Comment_SelectionEndsAtColumnZero() { - var code = @" -class Goo -{ -|start| void M() - { - } -|end|} -"; var expectedChanges = new[] { new TextChange(new TextSpan(20, 0), "//"), new TextChange(new TextSpan(34, 0), "//"), new TextChange(new TextSpan(41, 0), "//"), }; - CommentSelection(code, expectedChanges, supportBlockComments: false); + CommentSelection(""" + + class Goo + { + |start| void M() + { + } + |end|} + + """, expectedChanges, supportBlockComments: false); } [WpfFact] public void Comment_BoxSelectionAtStartOfLines() { - var code = @" -class Goo -{ -|start||end| void M() -|start||end| { -|start||end| } -} -"; - var expectedChanges = new[] { new TextChange(new TextSpan(20, 0), "//"), @@ -234,21 +224,21 @@ class Goo new TextChange(new TextSpan(41, 0), "//"), }; - CommentSelection(code, expectedChanges, supportBlockComments: true); + CommentSelection(""" + + class Goo + { + |start||end| void M() + |start||end| { + |start||end| } + } + + """, expectedChanges, supportBlockComments: true); } [WpfFact] public void Comment_BoxSelectionIndentedAtStart() { - var code = @" -class Goo -{ - |start||end|void M() - |start||end|{ - |start||end|} -} -"; - var expectedChanges = new[] { new TextChange(new TextSpan(20, 0), "//"), @@ -256,22 +246,21 @@ class Goo new TextChange(new TextSpan(41, 0), "//"), }; - CommentSelection(code, expectedChanges, supportBlockComments: true); + CommentSelection(""" + + class Goo + { + |start||end|void M() + |start||end|{ + |start||end|} + } + + """, expectedChanges, supportBlockComments: true); } [WpfFact] public void Comment_BoxSelectionBlock() { - var code = @" -class Goo -{ - |start|v|end|oid M() - |start|{|end| - |start|o|end|ther - |start|}|end| -} -"; - var expectedChanges = new[] { new TextChange(new TextSpan(20, 0), "/*"), @@ -282,78 +271,73 @@ class Goo new TextChange(new TextSpan(52, 0), "//"), }; - CommentSelection(code, expectedChanges, supportBlockComments: true); + CommentSelection(""" + + class Goo + { + |start|v|end|oid M() + |start|{|end| + |start|o|end|ther + |start|}|end| + } + + """, expectedChanges, supportBlockComments: true); } [WpfFact] public void Comment_BoxSelectionBlockWithoutSupport() { - var code = @" -class Goo -{ - |start|v|end|oid M() - |start|{|end| - |start|}|end| -} -"; - var expectedChanges = new[] { new TextChange(new TextSpan(20, 0), "//"), new TextChange(new TextSpan(34, 0), "//"), new TextChange(new TextSpan(41, 0), "//"), }; - CommentSelection(code, expectedChanges, supportBlockComments: false); + CommentSelection(""" + + class Goo + { + |start|v|end|oid M() + |start|{|end| + |start|}|end| + } + + """, expectedChanges, supportBlockComments: false); } [WpfFact] public void Uncomment_NoSelection() { - var code = @"//Goo|start||end|Bar"; - UncommentSelection(code, new[] { new TextChange(new TextSpan(0, 2), string.Empty) }, Span.FromBounds(0, 6), supportBlockComments: true); + UncommentSelection(@"//Goo|start||end|Bar", new[] { new TextChange(new TextSpan(0, 2), string.Empty) }, Span.FromBounds(0, 6), supportBlockComments: true); } [WpfFact] public void Uncomment_MatchesBlockComment() { - var code = @"Before |start|/* Some Commented Text */|end| after"; var expectedChanges = new[] { new TextChange(new TextSpan(7, 2), string.Empty), new TextChange(new TextSpan(30, 2), string.Empty), }; - UncommentSelection(code, expectedChanges, Span.FromBounds(7, 28), supportBlockComments: true); + UncommentSelection(@"Before |start|/* Some Commented Text */|end| after", expectedChanges, Span.FromBounds(7, 28), supportBlockComments: true); } [WpfFact] public void Uncomment_InWhitespaceOutsideBlockComment() { - var code = @"Before |start| /* Some Commented Text */ |end| after"; var expectedChanges = new[] { new TextChange(new TextSpan(11, 2), string.Empty), new TextChange(new TextSpan(34, 2), string.Empty), }; - UncommentSelection(code, expectedChanges, Span.FromBounds(11, 32), supportBlockComments: true); + UncommentSelection(@"Before |start| /* Some Commented Text */ |end| after", expectedChanges, Span.FromBounds(11, 32), supportBlockComments: true); } [WpfFact] public void Uncomment_IndentedSingleLineCommentsAndUncommentedLines() { - var code = @" -class C -{ -|start| //void M() - //{ - //if (true) - //{ - SomethingNotCommented(); - //} - //} -|end|}"; - var expectedChanges = new[] { new TextChange(new TextSpan(18, 2), string.Empty), @@ -364,22 +348,25 @@ class C new TextChange(new TextSpan(128, 2), string.Empty), }; - UncommentSelection(code, expectedChanges, Span.FromBounds(14, 119), supportBlockComments: true); + UncommentSelection(""" + + class C + { + |start| //void M() + //{ + //if (true) + //{ + SomethingNotCommented(); + //} + //} + |end|} + """, expectedChanges, Span.FromBounds(14, 119), supportBlockComments: true); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/563927")] // This test is just measuring current behavior, there is no reason not to support maintaining box selection. public void Uncomment_BoxSelection() { - var code = @" -class Goo -{ - |start|/*v*/|end|oid M() - |start|//{ |end| - |start|/*o*/|end|ther - |start|//} |end| -}"; - var expectedChanges = new[] { new TextChange(new TextSpan(20, 2), string.Empty), @@ -395,39 +382,46 @@ class Goo Span.FromBounds(20, 21) }; - UncommentSelection(code, expectedChanges, expectedSelectedSpans, supportBlockComments: true); + UncommentSelection(""" + + class Goo + { + |start|/*v*/|end|oid M() + |start|//{ |end| + |start|/*o*/|end|ther + |start|//} |end| + } + """, expectedChanges, expectedSelectedSpans, supportBlockComments: true); } [WpfFact] public void Uncomment_PartOfMultipleComments() { - var code = @" -//|start|//namespace N -////{ -//|end|//}"; - var expectedChanges = new[] { new TextChange(new TextSpan(2, 2), string.Empty), new TextChange(new TextSpan(19, 2), string.Empty), new TextChange(new TextSpan(26, 2), string.Empty), }; - UncommentSelection(code, expectedChanges, Span.FromBounds(2, 25), supportBlockComments: true); + UncommentSelection(""" + + //|start|//namespace N + ////{ + //|end|//} + """, expectedChanges, Span.FromBounds(2, 25), supportBlockComments: true); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530300")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/563924")] public void Comment_NoSelectionAtStartOfLine() { - var code = @"|start||end|using System;"; - CommentSelection(code, new[] { new TextChange(TextSpan.FromBounds(0, 0), "//") }, new[] { new Span(0, 15) }, supportBlockComments: true); + CommentSelection(@"|start||end|using System;", new[] { new TextChange(TextSpan.FromBounds(0, 0), "//") }, new[] { new Span(0, 15) }, supportBlockComments: true); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932411")] public void Uncomment_NoSelectionInBlockComment() { - var code = @"using /* Sy|start||end|stem.*/IO;"; - UncommentSelection(code, + UncommentSelection(@"using /* Sy|start||end|stem.*/IO;", expectedChanges: new[] { new TextChange(new TextSpan(6, 2), string.Empty), @@ -440,8 +434,7 @@ public void Uncomment_NoSelectionInBlockComment() [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932411")] public void Uncomment_BlockCommentWithPreviousBlockComment() { - var code = @"/* comment */using /* Sy|start||end|stem.*/IO;"; - UncommentSelection(code, + UncommentSelection(@"/* comment */using /* Sy|start||end|stem.*/IO;", expectedChanges: new[] { new TextChange(new TextSpan(19, 2), string.Empty), @@ -454,8 +447,7 @@ public void Uncomment_BlockCommentWithPreviousBlockComment() [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932411")] public void Uncomment_InsideEndOfBlockComment() { - var code = @"/*using System;*|start||end|/"; - UncommentSelection(code, + UncommentSelection(@"/*using System;*|start||end|/", expectedChanges: new[] { new TextChange(new TextSpan(0, 2), string.Empty), @@ -468,8 +460,7 @@ public void Uncomment_InsideEndOfBlockComment() [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932411")] public void Uncomment_AtBeginningOfEndOfBlockComment() { - var code = @"/*using System;|start||end|*/"; - UncommentSelection(code, + UncommentSelection(@"/*using System;|start||end|*/", expectedChanges: new[] { new TextChange(new TextSpan(0, 2), string.Empty), @@ -482,32 +473,18 @@ public void Uncomment_AtBeginningOfEndOfBlockComment() [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932411")] public void Uncomment_AtEndOfBlockComment() { - var code = @"/*using System;*/|start||end|"; - UncommentSelection(code, [], new Span(17, 0), supportBlockComments: true); + UncommentSelection(@"/*using System;*/|start||end|", [], new Span(17, 0), supportBlockComments: true); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932411")] public void Uncomment_BlockCommentWithNoEnd() { - var code = @"/*using |start||end|System;"; - UncommentSelection(code, [], new Span(8, 0), supportBlockComments: true); + UncommentSelection(@"/*using |start||end|System;", [], new Span(8, 0), supportBlockComments: true); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/31669")] public void Uncomment_BlockWithSingleInside() { - var code = @" -class A -{ - |start|/* - void M() - { - // A comment - // Another comment - } - */|end| -}"; - var expectedChanges = new[] { new TextChange(new TextSpan(18, 2), string.Empty), @@ -519,26 +496,24 @@ void M() Span.FromBounds(18, 110) }; - UncommentSelection(code, expectedChanges, expectedSelectedSpans, supportBlockComments: true); + UncommentSelection(""" + + class A + { + |start|/* + void M() + { + // A comment + // Another comment + } + */|end| + } + """, expectedChanges, expectedSelectedSpans, supportBlockComments: true); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/31669")] public void Uncomment_BlockWithSingleInsideAndSelectionIncludesNewLines() { - var code = @" -class A -{ -|start| - /* - void M() - { - // A comment - // Another comment - } - */ -|end| -}"; - var expectedChanges = new[] { new TextChange(new TextSpan(20, 2), string.Empty), @@ -550,24 +525,26 @@ void M() Span.FromBounds(20, 112) }; - UncommentSelection(code, expectedChanges, expectedSelectedSpans, supportBlockComments: true); + UncommentSelection(""" + + class A + { + |start| + /* + void M() + { + // A comment + // Another comment + } + */ + |end| + } + """, expectedChanges, expectedSelectedSpans, supportBlockComments: true); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/31669")] public void Uncomment_BlockWithSingleInsideAndSelectionStartsWithSpaces() { - var code = @" -class A -{ -|start| /* - void M() - { - // A comment - // Another comment - } - */ -|end|}"; - var expectedChanges = new[] { new TextChange(new TextSpan(18, 2), string.Empty), @@ -579,24 +556,24 @@ void M() Span.FromBounds(18, 110) }; - UncommentSelection(code, expectedChanges, expectedSelectedSpans, supportBlockComments: true); + UncommentSelection(""" + + class A + { + |start| /* + void M() + { + // A comment + // Another comment + } + */ + |end|} + """, expectedChanges, expectedSelectedSpans, supportBlockComments: true); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/31669")] public void Uncomment_BlockWithSingleInsideAndBlockSelected() { - var code = @" -class A -{ - /* - void |start|M|end|() - { - // A comment - // Another comment - } - */ -}"; - var expectedChanges = new[] { new TextChange(new TextSpan(18, 2), string.Empty), @@ -608,24 +585,24 @@ class A Span.FromBounds(18, 110) }; - UncommentSelection(code, expectedChanges, expectedSelectedSpans, supportBlockComments: true); + UncommentSelection(""" + + class A + { + /* + void |start|M|end|() + { + // A comment + // Another comment + } + */ + } + """, expectedChanges, expectedSelectedSpans, supportBlockComments: true); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/31669")] public void Uncomment_SingleLineInsideBlockAndSingleSelected() { - var code = @" -class A -{ - /* - void M() - { - // A |start|comm|end|ent - // Another comment - } - */ -}"; - var expectedChanges = new[] { new TextChange(new TextSpan(55, 2), string.Empty), @@ -636,24 +613,24 @@ void M() Span.FromBounds(43, 65) }; - UncommentSelection(code, expectedChanges, expectedSelectedSpans, supportBlockComments: true); + UncommentSelection(""" + + class A + { + /* + void M() + { + // A |start|comm|end|ent + // Another comment + } + */ + } + """, expectedChanges, expectedSelectedSpans, supportBlockComments: true); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/31669")] public void Uncomment_SingleLineInsideBlockAndBothSelected() { - var code = @" -class A -{ - /* - void |start|M() - { - // A comm|end|ent - // Another comment - } - */ -}"; - var expectedChanges = new[] { new TextChange(new TextSpan(55, 2), string.Empty), @@ -664,24 +641,24 @@ class A Span.FromBounds(22, 65) }; - UncommentSelection(code, expectedChanges, expectedSelectedSpans, supportBlockComments: true); + UncommentSelection(""" + + class A + { + /* + void |start|M() + { + // A comm|end|ent + // Another comment + } + */ + } + """, expectedChanges, expectedSelectedSpans, supportBlockComments: true); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/31669")] public void Uncomment_SingleLinesWithBlockAndSingleInside() { - var code = @" -class A -{ - |start|///* - //void M() - //{ - // // A comment - // // Another comment - //} - //*/|end| -}"; - var expectedChanges = new[] { new TextChange(new TextSpan(18, 2), string.Empty), @@ -698,7 +675,19 @@ class A Span.FromBounds(14, 108) }; - UncommentSelection(code, expectedChanges, expectedSelectedSpans, supportBlockComments: true); + UncommentSelection(""" + + class A + { + |start|///* + //void M() + //{ + // // A comment + // // Another comment + //} + //*/|end| + } + """, expectedChanges, expectedSelectedSpans, supportBlockComments: true); } private static void UncommentSelection(string code, IEnumerable expectedChanges, Span expectedSelectedSpan, bool supportBlockComments) diff --git a/src/EditorFeatures/Test/CommentSelection/ToggleBlockCommentCommandHandlerTests.cs b/src/EditorFeatures/Test/CommentSelection/ToggleBlockCommentCommandHandlerTests.cs index 9dfc3e2b618a0..7d46d29099056 100644 --- a/src/EditorFeatures/Test/CommentSelection/ToggleBlockCommentCommandHandlerTests.cs +++ b/src/EditorFeatures/Test/CommentSelection/ToggleBlockCommentCommandHandlerTests.cs @@ -22,1480 +22,1332 @@ public sealed class ToggleBlockCommentCommandHandlerTests : AbstractToggleCommen [WpfFact] public void AddComment_EmptyCaret() { - var markup = @"$$"; - var expected = @"[|/**/|]"; - - ToggleComment(markup, expected); + ToggleComment(@"$$", @"[|/**/|]"); } [WpfFact] public void AddComment_EmptySelection() { - var markup = @"[| |]"; - var expected = @"[|/* */|]"; - - ToggleComment(markup, expected); + ToggleComment(@"[| |]", @"[|/* */|]"); } [WpfFact] public void AddComment_SingleLineSelected() { - var markup = -@" -class C -{ - void M() - { - [|var i = 1;|] - } -}"; - var expected = -@" -class C -{ - void M() - { - [|/*var i = 1;*/|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + [|var i = 1;|] + } + } + """, """ + class C + { + void M() + { + [|/*var i = 1;*/|] + } + } + """); } [WpfFact] public void AddComment_SingleLineWithWhitespaceSelected() { - var markup = -@" -class C -{ - void M() - { -[| var i = 1;|] - } -}"; - var expected = -@" -class C -{ - void M() - { -[|/* var i = 1;*/|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + [| var i = 1;|] + } + } + """, """ + class C + { + void M() + { + [|/* var i = 1;*/|] + } + } + """); } [WpfFact] public void AddComment_CaretInsideSingleLine() { - var markup = -@" -class C -{ - void M() - { - var$$ i = 1; - } -}"; - var expected = -@" -class C -{ - void M() - { - var[|/**/|] i = 1; - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + var$$ i = 1; + } + } + """, """ + class C + { + void M() + { + var[|/**/|] i = 1; + } + } + """); } [WpfFact] public void AddComment_PartialLineSelected() { - var markup = -@" -class C -{ - void M() - { - var [|i = 1|]; - } -}"; - var expected = -@" -class C -{ - void M() - { - var [|/*i = 1*/|]; - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + var [|i = 1|]; + } + } + """, """ + class C + { + void M() + { + var [|/*i = 1*/|]; + } + } + """); } [WpfFact] public void AddComment_CaretInsideToken() { - var markup = -@" -class C -{ - void M() - { - va$$r i = 1; - } -}"; - var expected = -@" -class C -{ - void M() - { - var[|/**/|] i = 1; - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + va$$r i = 1; + } + } + """, """ + class C + { + void M() + { + var[|/**/|] i = 1; + } + } + """); } [WpfFact] public void AddComment_CaretInsideOperatorToken() { - var markup = @" -class C -{ - void M() - { - Func myFunc = x =$$> x == 5; - } -}"; - var expected = -@" -class C -{ - void M() - { - Func myFunc = x =>[|/**/|] x == 5; - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + Func myFunc = x =$$> x == 5; + } + } + """, """ + class C + { + void M() + { + Func myFunc = x =>[|/**/|] x == 5; + } + } + """); } [WpfFact] public void AddComment_CaretInsideNewline() { - var markup = -@" -class C -{ - void M() - { - var i = 1;$$ - } -}"; - var expected = -@" -class C -{ - void M() - { - var i = 1;[|/**/|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + var i = 1;$$ + } + } + """, """ + class C + { + void M() + { + var i = 1;[|/**/|] + } + } + """); } [WpfFact] public void AddComment_MultiLineSelection() { - var markup = -@" -class C -{ - void M() - { - [|var i = 1; - var j = 2; - var k = 3;|] - } -}"; - var expected = -@" -class C -{ - void M() - { - [|/*var i = 1; - var j = 2; - var k = 3;*/|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + [|var i = 1; + var j = 2; + var k = 3;|] + } + } + """, """ + class C + { + void M() + { + [|/*var i = 1; + var j = 2; + var k = 3;*/|] + } + } + """); } [WpfFact] public void AddComment_MultiLineSelectionWithWhitespace() { - var markup = -@" -class C -{ - void M() - { - [|var i = 1; - var j = 2; - var k = 3; - -|] - } -}"; - var expected = -@" -class C -{ - void M() - { - [|/*var i = 1; - var j = 2; - var k = 3; - -*/|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + [|var i = 1; + var j = 2; + var k = 3; + + |] + } + } + """, """ + class C + { + void M() + { + [|/*var i = 1; + var j = 2; + var k = 3; + + */|] + } + } + """); } [WpfFact] public void AddComment_SingleLineCommentInSelection() { - var markup = -@" -class C -{ - void M() - { - [|//var i = 1; - var j = 2;|] - } -}"; - var expected = -@" -class C -{ - void M() - { - [|/*//var i = 1; - var j = 2;*/|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + [|//var i = 1; + var j = 2;|] + } + } + """, """ + class C + { + void M() + { + [|/*//var i = 1; + var j = 2;*/|] + } + } + """); } [WpfFact] public void AddComment_BlockCommentBetweenCodeInSelection() { - var markup = -@" -class C -{ - void M() - { - [|var i = 1; - /*var j = 2; - var k = 3;*/ - var l = 4;|] - } -}"; - var expected = -@" -class C -{ - void M() - { - [|/*var i = 1; - *//*var j = 2; - var k = 3;*//* - var l = 4;*/|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + [|var i = 1; + /*var j = 2; + var k = 3;*/ + var l = 4;|] + } + } + """, """ + class C + { + void M() + { + [|/*var i = 1; + *//*var j = 2; + var k = 3;*//* + var l = 4;*/|] + } + } + """); } [WpfFact] public void AddComment_SequentialBlockCommentBetweenCodeInSelection() { - var markup = -@" -class C -{ - void M() - { - [|var i = 1; - /*var j = 2; - var k = 3;*//* - var l = 4;*/ - var m = 5;|] - } -}"; - var expected = -@" -class C -{ - void M() - { - [|/*var i = 1; - *//*var j = 2; - var k = 3;*//* - var l = 4;*//* - var m = 5;*/|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + [|var i = 1; + /*var j = 2; + var k = 3;*//* + var l = 4;*/ + var m = 5;|] + } + } + """, """ + class C + { + void M() + { + [|/*var i = 1; + *//*var j = 2; + var k = 3;*//* + var l = 4;*//* + var m = 5;*/|] + } + } + """); } [WpfFact] public void AddComment_SequentialBlockCommentsAndWhitespaceBetweenCodeInSelection() { - var markup = -@" -class C -{ - void M() - { - [|var i = 1; - /*var j = 2; - var k = 3;*/ - - /* - var l = 4;*/ - var m = 5;|] - } -}"; - var expected = -@" -class C -{ - void M() - { - [|/*var i = 1; - *//*var j = 2; - var k = 3;*/ - - /* - var l = 4;*//* - var m = 5;*/|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + [|var i = 1; + /*var j = 2; + var k = 3;*/ + + /* + var l = 4;*/ + var m = 5;|] + } + } + """, """ + class C + { + void M() + { + [|/*var i = 1; + *//*var j = 2; + var k = 3;*/ + + /* + var l = 4;*//* + var m = 5;*/|] + } + } + """); } [WpfFact] public void AddComment_CodeBetweenBlockCommentsInSelection() { - var markup = -@" -class C -{ - void M() - { - [|/*var i = 1; - var j = 2;*/ - var k = 3; - /*var l = 4; - var m = 5;*/|] - } -}"; - var expected = -@" -class C -{ - void M() - { - [|/*var i = 1; - var j = 2;*//* - var k = 3; - *//*var l = 4; - var m = 5;*/|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + [|/*var i = 1; + var j = 2;*/ + var k = 3; + /*var l = 4; + var m = 5;*/|] + } + } + """, """ + class C + { + void M() + { + [|/*var i = 1; + var j = 2;*//* + var k = 3; + *//*var l = 4; + var m = 5;*/|] + } + } + """); } [WpfFact] public void AddComment_CodeThenCommentInSelection() { - var markup = -@" -class C -{ - void M() - { - [|var i = 1; - /*var j = 2; - var k = 3;*/|] - } -}"; - var expected = -@" -class C -{ - void M() - { - [|/*var i = 1; - *//*var j = 2; - var k = 3;*/|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + [|var i = 1; + /*var j = 2; + var k = 3;*/|] + } + } + """, """ + class C + { + void M() + { + [|/*var i = 1; + *//*var j = 2; + var k = 3;*/|] + } + } + """); } [WpfFact] public void AddComment_CodeThenCommentAndWhitespaceInSelection() { - var markup = -@" -class C -{ - void M() - { - [|var i = 1; - /*var j = 2; - var k = 3;*/ - |] - } -}"; - var expected = -@" -class C -{ - void M() - { - [|/*var i = 1; - *//*var j = 2; - var k = 3;*/ - |] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + [|var i = 1; + /*var j = 2; + var k = 3;*/ + |] + } + } + """, """ + class C + { + void M() + { + [|/*var i = 1; + *//*var j = 2; + var k = 3;*/ + |] + } + } + """); } [WpfFact] public void AddComment_CloseCommentOnlyInSelection() { - var markup = -@" -class C -{ - void M() - { - [|var i = 1; - var j = 2;*/ - var k = 3;|] - } -}"; - var expected = -@" -class C -{ - void M() - { - [|/*var i = 1; - var j = 2;*/ - var k = 3;*/|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + [|var i = 1; + var j = 2;*/ + var k = 3;|] + } + } + """, """ + class C + { + void M() + { + [|/*var i = 1; + var j = 2;*/ + var k = 3;*/|] + } + } + """); } [WpfFact] public void AddComment_CodeThenPartialCommentInSelection() { - var markup = -@" -class C -{ - void M() - { - [|var i = 1; - /*var j = 2; - var|] k = 3;*/ - } -}"; - var expected = -@" -class C -{ - void M() - { - [|/*var i = 1; - *//*var j = 2; - var*/|]/* k = 3;*/ - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + [|var i = 1; + /*var j = 2; + var|] k = 3;*/ + } + } + """, """ + class C + { + void M() + { + [|/*var i = 1; + *//*var j = 2; + var*/|]/* k = 3;*/ + } + } + """); } [WpfFact] public void AddComment_CommentThenCodeInSelection() { - var markup = -@" -class C -{ - void M() - { - [|/*var i = 1; - var j = 2;*/ - var k = 3;|] - } -}"; - var expected = -@" -class C -{ - void M() - { - [|/*var i = 1; - var j = 2;*//* - var k = 3;*/|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + [|/*var i = 1; + var j = 2;*/ + var k = 3;|] + } + } + """, """ + class C + { + void M() + { + [|/*var i = 1; + var j = 2;*//* + var k = 3;*/|] + } + } + """); } [WpfFact] public void AddComment_CommentAndWhitespaceThenCodeInSelection() { - var markup = -@" -class C -{ - void M() - { -[| /*var i = 1; - var j = 2;*/ - var k = 3; - |] - } -}"; - var expected = -@" -class C -{ - void M() - { -[| /*var i = 1; - var j = 2;*//* - var k = 3; - */|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + [| /*var i = 1; + var j = 2;*/ + var k = 3; + |] + } + } + """, """ + class C + { + void M() + { + [| /*var i = 1; + var j = 2;*//* + var k = 3; + */|] + } + } + """); } [WpfFact] public void AddComment_CommentCloseMarkerThenCodeInSelection() { - var markup = -@" -class C -{ - void M() - { - /*var i = 1; - var j = 2;[|*/ - var k = 3;|] - } -}"; - var expected = -@" -class C -{ - void M() - { - /*var i = 1; - var j = 2;[|*//* - var k = 3;*/|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + /*var i = 1; + var j = 2;[|*/ + var k = 3;|] + } + } + """, """ + class C + { + void M() + { + /*var i = 1; + var j = 2;[|*//* + var k = 3;*/|] + } + } + """); } [WpfFact] public void AddComment_CodeThenCommentStartMarkerInSelection() { - var markup = -@" -class C -{ - void M() - { - [|var i = 1; - var j = 2;/*|] - var k = 3;*/ - } -}"; - var expected = -@" -class C -{ - void M() - { - [|/*var i = 1; - var j = 2;*//*|] - var k = 3;*/ - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + [|var i = 1; + var j = 2;/*|] + var k = 3;*/ + } + } + """, """ + class C + { + void M() + { + [|/*var i = 1; + var j = 2;*//*|] + var k = 3;*/ + } + } + """); } [WpfFact] public void AddComment_PartialCommentThenCodeInSelection() { - var markup = -@" -class C -{ - void M() - { - /*var i = 1; - var [|j = 2;*/ - var k = 3;|] - } -}"; - var expected = -@" -class C -{ - void M() - { - /*var i = 1; - var */[|/*j = 2;*//* - var k = 3;*/|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + /*var i = 1; + var [|j = 2;*/ + var k = 3;|] + } + } + """, """ + class C + { + void M() + { + /*var i = 1; + var */[|/*j = 2;*//* + var k = 3;*/|] + } + } + """); } [WpfFact] public void AddComment_CaretBeforeBlockOnNewLine() { - var markup = -@" -class C -{ - void M() - {$$ - /*var i = 1;*/ - } -}"; - var expected = -@" -class C -{ - void M() - {[|/**/|] - /*var i = 1;*/ - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + {$$ + /*var i = 1;*/ + } + } + """, """ + class C + { + void M() + {[|/**/|] + /*var i = 1;*/ + } + } + """); } [WpfFact] public void AddComment_CaretBeforeCodeAndBlock() { - var markup = -@" -class C -{ - void M() - { - $$ var /*i*/ = 1; - } -}"; - var expected = -@" -class C -{ - void M() - { - [|/**/|] var /*i*/ = 1; - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + $$ var /*i*/ = 1; + } + } + """, """ + class C + { + void M() + { + [|/**/|] var /*i*/ = 1; + } + } + """); } [WpfFact] public void AddComment_CaretAfterBlockOnNewLine() { - var markup = -@" -class C -{ - void M() - { - /*var i = 1*/ -$$ - } -}"; - var expected = -@" -class C -{ - void M() - { - /*var i = 1*/ -[|/**/|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + /*var i = 1*/ + $$ + } + } + """, """ + class C + { + void M() + { + /*var i = 1*/ + [|/**/|] + } + } + """); } [WpfFact] public void AddComment_CaretAfterBlockAndCode() { - var markup = -@" -class C -{ - void M() - { - /*var */i = 1; $$ - } -}"; - var expected = -@" -class C -{ - void M() - { - /*var */i = 1; [|/**/|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + /*var */i = 1; $$ + } + } + """, """ + class C + { + void M() + { + /*var */i = 1; [|/**/|] + } + } + """); } [WpfFact] public void AddComment_BlockSelection() { - var markup = -@" -class C -{ - void M() - { - [|var i = 1;|] - [|var j = 2;|] - [|var k = 3;|] - } -}"; - var expected = -@" -class C -{ - void M() - { - [|/*var i = 1;*/|] - [|/*var j = 2;*/|] - [|/*var k = 3;*/|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + [|var i = 1;|] + [|var j = 2;|] + [|var k = 3;|] + } + } + """, """ + class C + { + void M() + { + [|/*var i = 1;*/|] + [|/*var j = 2;*/|] + [|/*var k = 3;*/|] + } + } + """); } [WpfFact] public void AddComment_BlockSelectionPartiallyCommented() { - var markup = -@" -class C -{ - void M() - { - [|/*var i = 1;|] - [|var j = 2;*/|] - [|var k = 3; |] - } -}"; - var expected = -@" -class C -{ - void M() - { - [|/*var i = 1;*/|]/* - */[|/*var j = 2;*/|] - [|/*var k = 3; */|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + [|/*var i = 1;|] + [|var j = 2;*/|] + [|var k = 3; |] + } + } + """, """ + class C + { + void M() + { + [|/*var i = 1;*/|]/* + */[|/*var j = 2;*/|] + [|/*var k = 3; */|] + } + } + """); } [WpfFact] public void AddComment_DirectiveInsideSelection() { - var markup = -@" -class C -{ - void M() - { - [|var i = 1; -#if false - var j = 2; -#endif - var k = 3;|] - } -}"; - var expected = -@" -class C -{ - void M() - { - [|/*var i = 1; -#if false - var j = 2; -#endif - var k = 3;*/|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + [|var i = 1; + #if false + var j = 2; + #endif + var k = 3;|] + } + } + """, """ + class C + { + void M() + { + [|/*var i = 1; + #if false + var j = 2; + #endif + var k = 3;*/|] + } + } + """); } [WpfFact] public void AddComment_WithProjectionBuffer() { - var surfaceMarkup = @"< html >@{|S1:|}"; - var csharpMarkup = -@" -{|S1:class C -{ - void M() - { - [|var i = 1;|] - } -}|}"; - var expected = -@"< html >@class C -{ - void M() - { - [|/*var i = 1;*/|] - } -}"; - ToggleCommentWithProjectionBuffer(surfaceMarkup, csharpMarkup, expected); + ToggleCommentWithProjectionBuffer(@"< html >@{|S1:|}", """ + {|S1:class C + { + void M() + { + [|var i = 1;|] + } + }|} + """, """ + < html >@class C + { + void M() + { + [|/*var i = 1;*/|] + } + } + """); } [WpfFact] public void RemoveComment_AtBeginningOfFile() { - var markup = @"[|/**/|]"; - var expected = @""; - - ToggleComment(markup, expected); + ToggleComment(@"[|/**/|]", @""); } [WpfFact] public void RemoveComment_CaretInsideBlock() { - var markup = -@" -class C -{ - void M() - { - /*var i = 1; - var $$j = 2; - var k = 3;*/ - } -}"; - var expected = -@" -class C -{ - void M() - { - [|var i = 1; - var j = 2; - var k = 3;|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + /*var i = 1; + var $$j = 2; + var k = 3;*/ + } + } + """, """ + class C + { + void M() + { + [|var i = 1; + var j = 2; + var k = 3;|] + } + } + """); } [WpfFact] public void RemoveComment_CaretInsideSequentialBlock() { - var markup = -@" -class C -{ - void M() - { - /*var i = 1; - var $$j = 2;*//* - var k = 3;*/ - } -}"; - var expected = -@" -class C -{ - void M() - { - [|var i = 1; - var j = 2;|]/* - var k = 3;*/ - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + /*var i = 1; + var $$j = 2;*//* + var k = 3;*/ + } + } + """, """ + class C + { + void M() + { + [|var i = 1; + var j = 2;|]/* + var k = 3;*/ + } + } + """); } [WpfFact] public void RemoveComment_CaretBeforeBlockOnlyWhitespace() { - var markup = -@" -class C -{ - void M() - { - $$ /*var i = 1; - var*//* j = 2;*/ - var k = 3; - } -}"; - var expected = -@" -class C -{ - void M() - { - [|var i = 1; - var|]/* j = 2;*/ - var k = 3; - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + $$ /*var i = 1; + var*//* j = 2;*/ + var k = 3; + } + } + """, """ + class C + { + void M() + { + [|var i = 1; + var|]/* j = 2;*/ + var k = 3; + } + } + """); } [WpfFact] public void RemoveComment_CaretBeforeMultipleBlocksOnlyWhitespace() { - var markup = -@" -class C -{ - void M() - { - $$ /*var*/ i = 1/**/; - var/* j = 2;*/ - var k = 3; - } -}"; - var expected = -@" -class C -{ - void M() - { - [|var|] i = 1/**/; - var/* j = 2;*/ - var k = 3; - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + $$ /*var*/ i = 1/**/; + var/* j = 2;*/ + var k = 3; + } + } + """, """ + class C + { + void M() + { + [|var|] i = 1/**/; + var/* j = 2;*/ + var k = 3; + } + } + """); } [WpfFact] public void RemoveComment_CaretAfterBlockOnlyWhitespace() { - var markup = -@" -class C -{ - void M() - { - /*var i = 1; - var j = 2;*/ $$ - } -}"; - var expected = -@" -class C -{ - void M() - { - [|var i = 1; - var j = 2;|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + /*var i = 1; + var j = 2;*/ $$ + } + } + """, """ + class C + { + void M() + { + [|var i = 1; + var j = 2;|] + } + } + """); } [WpfFact] public void RemoveComment_CaretAfterMultipleBlocksOnlyWhitespace() { - var markup = -@" -class C -{ - void M() - { - var i = 1; - /*var*/ j /*= 2;*/ $$ - } -}"; - var expected = -@" -class C -{ - void M() - { - var i = 1; - /*var*/ j [|= 2;|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + var i = 1; + /*var*/ j /*= 2;*/ $$ + } + } + """, """ + class C + { + void M() + { + var i = 1; + /*var*/ j [|= 2;|] + } + } + """); } [WpfFact] public void RemoveComment_CaretInsideUnclosedBlock() { - var markup = -@" -class C -{ - void M() - { - /*var i = 1; - var $$j = 2; - var k = 3; - } -}"; - var expected = -@" -class C -{ - void M() - { - [|var i = 1; - var j = 2; - var k = 3; - } -}|]"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + /*var i = 1; + var $$j = 2; + var k = 3; + } + } + """, """ + class C + { + void M() + { + [|var i = 1; + var j = 2; + var k = 3; + } + }|] + """); } [WpfFact] public void RemoveComment_CommentInsideSelection() { - var markup = -@" -class C -{ - void M() - { - [|/*var i = 1; - var j = 2; - var k = 3;*/|] - } -}"; - var expected = -@" -class C -{ - void M() - { - [|var i = 1; - var j = 2; - var k = 3;|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + [|/*var i = 1; + var j = 2; + var k = 3;*/|] + } + } + """, """ + class C + { + void M() + { + [|var i = 1; + var j = 2; + var k = 3;|] + } + } + """); } [WpfFact] public void RemoveComment_CommentAndWhitespaceInSelection() { - var markup = -@" -class C -{ - void M() - {[| - - /*var i = 1; - var j = 2; - var k = 3;*/ |] - } -}"; - var expected = -@" -class C -{ - void M() - { - - [|var i = 1; - var j = 2; - var k = 3;|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + {[| + + /*var i = 1; + var j = 2; + var k = 3;*/ |] + } + } + """, """ + class C + { + void M() + { + + [|var i = 1; + var j = 2; + var k = 3;|] + } + } + """); } [WpfFact] public void RemoveComment_CommentWithSingleLineCommentInSelection() { - var markup = -@" -class C -{ - void M() - { - [|/*var i = 1; - //var j = 2; - var k = 3;*/|] - } -}"; - var expected = -@" -class C -{ - void M() - { - [|var i = 1; - //var j = 2; - var k = 3;|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + [|/*var i = 1; + //var j = 2; + var k = 3;*/|] + } + } + """, """ + class C + { + void M() + { + [|var i = 1; + //var j = 2; + var k = 3;|] + } + } + """); } [WpfFact] public void RemoveComment_SequentialBlockInSelection() { - var markup = -@" -class C -{ - void M() - { - [|/*var i = 1; - *//*var j = 2; - var k = 3;*/|] - } -}"; - var expected = -@" -class C -{ - void M() - { - [|var i = 1; - var j = 2; - var k = 3;|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + [|/*var i = 1; + *//*var j = 2; + var k = 3;*/|] + } + } + """, """ + class C + { + void M() + { + [|var i = 1; + var j = 2; + var k = 3;|] + } + } + """); } [WpfFact] public void RemoveComment_SequentialBlockAndWhitespaceInSelection() { - var markup = -@" -class C -{ - void M() - {[| - - /*var i = 1; - */ - /*var j = 2; - var k = 3;*/ |] - } -}"; - var expected = -@" -class C -{ - void M() - { - - [|var i = 1; - - var j = 2; - var k = 3;|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + {[| + + /*var i = 1; + */ + /*var j = 2; + var k = 3;*/ |] + } + } + """, """ + class C + { + void M() + { + + [|var i = 1; + + var j = 2; + var k = 3;|] + } + } + """); } [WpfFact] public void RemoveComment_CommentPartiallyInsideSelection() { - var markup = -@" -class C -{ - void M() - { - /*var [|i = 1; - var j = 2;|] - var k = 3;*/ - } -}"; - var expected = -@" -class C -{ - void M() - { - [|var i = 1; - var j = 2; - var k = 3;|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + /*var [|i = 1; + var j = 2;|] + var k = 3;*/ + } + } + """, """ + class C + { + void M() + { + [|var i = 1; + var j = 2; + var k = 3;|] + } + } + """); } [WpfFact] public void RemoveComment_PartialSequentialBlockInSelection() { - var markup = -@" -class C -{ - void M() - { - /*var [|i = 1; - *//*var j = 2; - var |]k = 3;*/ - } -}"; - var expected = -@" -class C -{ - void M() - { - [|var i = 1; - var j = 2; - var k = 3;|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + /*var [|i = 1; + *//*var j = 2; + var |]k = 3;*/ + } + } + """, """ + class C + { + void M() + { + [|var i = 1; + var j = 2; + var k = 3;|] + } + } + """); } [WpfFact] public void RemoveComment_BlockSelectionWithMultipleComments() { - var markup = -@" -class C -{ - void M() - { - [|/*var i = 1;*/|] - [|/*var j = 2;*/|] - [|/*var k = 3;*/|] - } -}"; - var expected = -@" -class C -{ - void M() - { - [|var i = 1;|] - [|var j = 2;|] - [|var k = 3;|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + [|/*var i = 1;*/|] + [|/*var j = 2;*/|] + [|/*var k = 3;*/|] + } + } + """, """ + class C + { + void M() + { + [|var i = 1;|] + [|var j = 2;|] + [|var k = 3;|] + } + } + """); } [WpfFact] public void RemoveComment_BlockSelectionWithOneComment() { - var markup = -@" -class C -{ - void M() - { - [|/*var i = 1;|] - [|var j = 2; |] - [|var k = 3;*/|] - } -}"; - var expected = -@" -class C -{ - void M() - { - [|var i = 1; - var j = 2; - var k = 3;|] - } -}"; - - ToggleComment(markup, expected); + ToggleComment(""" + class C + { + void M() + { + [|/*var i = 1;|] + [|var j = 2; |] + [|var k = 3;*/|] + } + } + """, """ + class C + { + void M() + { + [|var i = 1; + var j = 2; + var k = 3;|] + } + } + """); } [WpfFact] public void RemoveComment_WithProjectionBuffer() { - var surfaceMarkup = @"< html >@{|S1:|}"; - var csharpMarkup = -@" -{|S1:class C -{ - void M() - { - [|/*var i = 1;*/|] - } -}|}"; - var expected = -@"< html >@class C -{ - void M() - { - [|var i = 1;|] - } -}"; - ToggleCommentWithProjectionBuffer(surfaceMarkup, csharpMarkup, expected); + ToggleCommentWithProjectionBuffer(@"< html >@{|S1:|}", """ + {|S1:class C + { + void M() + { + [|/*var i = 1;*/|] + } + }|} + """, """ + < html >@class C + { + void M() + { + [|var i = 1;|] + } + } + """); } [WpfFact] public void ToggleComment_MultiLineSelection() { - var markup = -@" -class C -{ - void M() - { - [|var i = 1; - var j = 2; - var k = 3;|] - } -}"; var expectedText = new[] { -@" -class C -{ - void M() - { - [|/*var i = 1; - var j = 2; - var k = 3;*/|] - } -}", -@" -class C -{ - void M() - { - [|var i = 1; - var j = 2; - var k = 3;|] - } -}" + """ + class C + { + void M() + { + [|/*var i = 1; + var j = 2; + var k = 3;*/|] + } + } + """, + """ + class C + { + void M() + { + [|var i = 1; + var j = 2; + var k = 3;|] + } + } + """ }; - ToggleCommentMultiple(markup, expectedText); + ToggleCommentMultiple(""" + class C + { + void M() + { + [|var i = 1; + var j = 2; + var k = 3;|] + } + } + """, expectedText); } [WpfFact] public void ToggleComment_MultiCommentSelection() { - var markup = -@" -class C -{ - void M() - { - /*var i = 1; - [|var */ j = 2; - var k = 3;|] - } -}"; var expectedText = new[] { -@" -class C -{ - void M() - { - /*var i = 1; - */[|/*var *//* j = 2; - var k = 3;*/|] - } -}", -@" -class C -{ - void M() - { - /*var i = 1; - */ - [|var j = 2; - var k = 3;|] - } -}" + """ + class C + { + void M() + { + /*var i = 1; + */[|/*var *//* j = 2; + var k = 3;*/|] + } + } + """, + """ + class C + { + void M() + { + /*var i = 1; + */ + [|var j = 2; + var k = 3;|] + } + } + """ }; - ToggleCommentMultiple(markup, expectedText); + ToggleCommentMultiple(""" + class C + { + void M() + { + /*var i = 1; + [|var */ j = 2; + var k = 3;|] + } + } + """, expectedText); } internal override AbstractCommentSelectionBase GetToggleCommentCommandHandler(EditorTestWorkspace workspace) diff --git a/src/EditorFeatures/Test/Completion/CompletionServiceTests.cs b/src/EditorFeatures/Test/Completion/CompletionServiceTests.cs index 419ab3d0c72fa..fc3e35d1c6a9d 100644 --- a/src/EditorFeatures/Test/Completion/CompletionServiceTests.cs +++ b/src/EditorFeatures/Test/Completion/CompletionServiceTests.cs @@ -27,14 +27,14 @@ public sealed class CompletionServiceTests [Fact] public async Task TestNuGetCompletionProvider() { - var code = @" -using System.Diagnostics; -class Test { - void Method() { - Debug.Assert(true, ""$$""); - } -} -"; + var code = """ + using System.Diagnostics; + class Test { + void Method() { + Debug.Assert(true, "$$"); + } + } + """; using var workspace = TestWorkspace.CreateCSharp(code, openDocuments: true); diff --git a/src/EditorFeatures/Test/Completion/FileSystemCompletionHelperTests.cs b/src/EditorFeatures/Test/Completion/FileSystemCompletionHelperTests.cs index 269016c8d7f45..93849d96034d1 100644 --- a/src/EditorFeatures/Test/Completion/FileSystemCompletionHelperTests.cs +++ b/src/EditorFeatures/Test/Completion/FileSystemCompletionHelperTests.cs @@ -18,7 +18,9 @@ private static void AssertItemsEqual(ImmutableArray actual, para AssertEx.Equal( expected, actual.Select(c => $"'{c.DisplayText}', {string.Join(", ", c.Tags)}, '{c.GetProperty(CommonCompletionItem.DescriptionProperty)}'"), - itemInspector: c => $"@\"{c}\""); + itemInspector: c => $""" + @"{c}" + """); Assert.True(actual.All(i => i.Rules == TestFileSystemCompletionHelper.CompletionRules)); } diff --git a/src/EditorFeatures/Test/Completion/GlobalAssemblyCacheCompletionHelperTests.cs b/src/EditorFeatures/Test/Completion/GlobalAssemblyCacheCompletionHelperTests.cs index 79c7e60039c2a..c1cc5caef0d97 100644 --- a/src/EditorFeatures/Test/Completion/GlobalAssemblyCacheCompletionHelperTests.cs +++ b/src/EditorFeatures/Test/Completion/GlobalAssemblyCacheCompletionHelperTests.cs @@ -22,15 +22,13 @@ public sealed class GlobalAssemblyCacheCompletionHelperTests [ConditionalFact(typeof(WindowsOnly))] public void ExistingReference() { - var code = "System.Windows"; - VerifyPresence(code, "System.Windows.Forms"); + VerifyPresence("System.Windows", "System.Windows.Forms"); } [ConditionalFact(typeof(WindowsOnly))] public void FullReferenceIdentity() { - var code = "System,"; - VerifyPresence(code, typeof(System.Diagnostics.Process).Assembly.FullName); + VerifyPresence("System,", typeof(System.Diagnostics.Process).Assembly.FullName); } private static void VerifyPresence(string pathSoFar, string completionItem) diff --git a/src/EditorFeatures/Test/Diagnostics/DiagnosticAnalyzerServiceTests.cs b/src/EditorFeatures/Test/Diagnostics/DiagnosticAnalyzerServiceTests.cs index cb03323a0cf9f..e69caaf2db2f3 100644 --- a/src/EditorFeatures/Test/Diagnostics/DiagnosticAnalyzerServiceTests.cs +++ b/src/EditorFeatures/Test/Diagnostics/DiagnosticAnalyzerServiceTests.cs @@ -160,14 +160,12 @@ public async Task TestDisabledByDefaultAnalyzerEnabledWithEditorConfig(bool enab if (enabledWithEditorconfig) { - var editorconfigText = $""" + project = project.AddAnalyzerConfigDocument(".editorconfig", filePath: "z:\\.editorconfig", text: SourceText.From($""" [*.cs] dotnet_diagnostic.{DisabledByDefaultAnalyzer.s_syntaxRule.Id}.severity = warning dotnet_diagnostic.{DisabledByDefaultAnalyzer.s_semanticRule.Id}.severity = warning dotnet_diagnostic.{DisabledByDefaultAnalyzer.s_compilationRule.Id}.severity = warning - """; - - project = project.AddAnalyzerConfigDocument(".editorconfig", filePath: "z:\\.editorconfig", text: SourceText.From(editorconfigText)).Project; + """)).Project; } var document = project.AddDocument("test.cs", SourceText.From("class A {}"), filePath: "z:\\test.cs"); @@ -293,14 +291,13 @@ public async Task TestFullSolutionAnalysisForHiddenAnalyzers_SeverityInAnalyzerC // Escalating the analyzer to non-hidden effective severity through analyzer config options // ensures that analyzer executes in full solution analysis. - var analyzerConfigText = $""" - [*.cs] - dotnet_diagnostic.{NamedTypeAnalyzer.DiagnosticId}.severity = warning - """; project = project.AddAnalyzerConfigDocument( ".editorconfig", - text: SourceText.From(analyzerConfigText), + text: SourceText.From($""" + [*.cs] + dotnet_diagnostic.{NamedTypeAnalyzer.DiagnosticId}.severity = warning + """), filePath: "z:\\.editorconfig").Project; await TestFullSolutionAnalysisForProjectAsync(workspace, project, expectAnalyzerExecuted: true); @@ -668,11 +665,9 @@ void M() } } """; - var additionalText = @"This is an additional file!"; - using var workspace = TestWorkspace.CreateCSharp(source); var project = workspace.CurrentSolution.Projects.Single(); - project = project.AddAdditionalDocument("additional.txt", additionalText).Project; + project = project.AddAdditionalDocument("additional.txt", @"This is an additional file!").Project; var analyzer = new FilterSpanTestAnalyzer(kind); var analyzerId = analyzer.GetAnalyzerId(); diff --git a/src/EditorFeatures/Test/Diagnostics/DiagnosticDataTests.cs b/src/EditorFeatures/Test/Diagnostics/DiagnosticDataTests.cs index ce7fec37766b4..8eeac99915000 100644 --- a/src/EditorFeatures/Test/Diagnostics/DiagnosticDataTests.cs +++ b/src/EditorFeatures/Test/Diagnostics/DiagnosticDataTests.cs @@ -22,17 +22,16 @@ namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; public sealed class DiagnosticDataTests { [Fact] - public async Task DiagnosticData_GetText() - { - var code = ""; - await VerifyTextSpanAsync(code, 10, 10, 20, 20, new TextSpan(0, 0)); - } + public Task DiagnosticData_GetText() + => VerifyTextSpanAsync("", 10, 10, 20, 20, new TextSpan(0, 0)); [Fact] public async Task DiagnosticData_GetText1() { - var code = @" -"; + var code = """ + + + """; await VerifyTextSpanAsync(code, 30, 30, 40, 40, new TextSpan(code.Length, 0)); } @@ -40,8 +39,10 @@ public async Task DiagnosticData_GetText1() [Fact] public async Task DiagnosticData_GetText2() { - var code = @" -"; + var code = """ + + + """; await VerifyTextSpanAsync(code, 0, 30, 40, 40, new TextSpan(code.Length, 0)); } @@ -49,8 +50,10 @@ public async Task DiagnosticData_GetText2() [Fact] public async Task DiagnosticData_GetText3() { - var code = @" -"; + var code = """ + + + """; await VerifyTextSpanAsync(code, 0, 30, 0, 40, new TextSpan(code.Length, 0)); } @@ -58,8 +61,10 @@ public async Task DiagnosticData_GetText3() [Fact] public async Task DiagnosticData_GetText4() { - var code = @" -"; + var code = """ + + + """; await VerifyTextSpanAsync(code, 1, 30, 1, 40, new TextSpan(code.Length, 0)); } @@ -67,8 +72,10 @@ public async Task DiagnosticData_GetText4() [Fact] public async Task DiagnosticData_GetText5() { - var code = @" -"; + var code = """ + + + """; await VerifyTextSpanAsync(code, 1, 30, 1, 40, new TextSpan(code.Length, 0)); } @@ -76,8 +83,10 @@ public async Task DiagnosticData_GetText5() [Fact] public async Task DiagnosticData_GetText6() { - var code = @" -"; + var code = """ + + + """; await VerifyTextSpanAsync(code, 1, 30, 2, 40, new TextSpan(code.Length, 0)); } @@ -85,26 +94,26 @@ public async Task DiagnosticData_GetText6() [Fact] public async Task DiagnosticData_GetText7() { - var code = @" -"; + var code = """ + + + """; await VerifyTextSpanAsync(code, 1, 0, 1, 2, new TextSpan(code.Length, 0)); } [Fact] - public async Task DiagnosticData_GetText8() - { - var code = @" -namespace B -{ - class A - { - } -} -"; + public Task DiagnosticData_GetText8() + => VerifyTextSpanAsync(""" - await VerifyTextSpanAsync(code, 3, 10, 3, 11, new TextSpan(28, 1)); - } + namespace B + { + class A + { + } + } + + """, 3, 10, 3, 11, new TextSpan(28, 1)); private static async Task VerifyTextSpanAsync(string code, int startLine, int startColumn, int endLine, int endColumn, TextSpan span) { @@ -207,14 +216,16 @@ public async Task DiagnosticData_NoneAdditionalLocationIsPreserved() [Fact] public async Task DiagnosticData_SourceGeneratedDocumentLocationIsPreserved() { - var content = @" -namespace B -{ - class A - { - } -} -"; + var content = """ + + namespace B + { + class A + { + } + } + + """; using var workspace = TestWorkspace.CreateCSharp(files: [], sourceGeneratedFiles: [content], composition: EditorTestCompositions.EditorFeatures); var hostDocument = workspace.Documents.Single(); Assert.True(hostDocument.IsSourceGenerated); diff --git a/src/EditorFeatures/Test/Diagnostics/IDEDiagnosticIDConfigurationTests.cs b/src/EditorFeatures/Test/Diagnostics/IDEDiagnosticIDConfigurationTests.cs index 9a07c6f32a7f1..4f39dd2c94668 100644 --- a/src/EditorFeatures/Test/Diagnostics/IDEDiagnosticIDConfigurationTests.cs +++ b/src/EditorFeatures/Test/Diagnostics/IDEDiagnosticIDConfigurationTests.cs @@ -132,20 +132,22 @@ private static void VerifyConfigureSeverityCore(string expected, string language if (!expectedMap.TryGetValue(diagnosticIdString, out var expectedValue)) { - Assert.False(true, $@"Missing entry: + Assert.False(true, $""" + Missing entry: -{diagnosticIdString} -{editorConfigString} -"); + {diagnosticIdString} + {editorConfigString} + """); } // Verify entries match for diagnosticId if (expectedValue != editorConfigString) { - Assert.False(true, $@"Mismatch for '{diagnosticId}' -Expected: {expectedValue} -Actual: {editorConfigString} -"); + Assert.False(true, $""" + Mismatch for '{diagnosticId}' + Expected: {expectedValue} + Actual: {editorConfigString} + """); } expectedMap.Remove(diagnosticIdString); @@ -173,7 +175,7 @@ private static void VerifyConfigureSeverityCore(string expected, string language [Fact] public void CSharp_VerifyIDEDiagnosticSeveritiesAreConfigurable() { - var expected = """ + VerifyConfigureSeverityCore(""" # IDE0001 dotnet_diagnostic.IDE0001.severity = %value% @@ -536,175 +538,172 @@ public void CSharp_VerifyIDEDiagnosticSeveritiesAreConfigurable() # JSON002 dotnet_diagnostic.JSON002.severity = %value% - """; - - VerifyConfigureSeverityCore(expected, LanguageNames.CSharp); + """, LanguageNames.CSharp); } [Fact] public void VisualBasic_VerifyIDEDiagnosticSeveritiesAreConfigurable() { - var expected = @" -# IDE0001 -dotnet_diagnostic.IDE0001.severity = %value% + VerifyConfigureSeverityCore(""" + # IDE0001 + dotnet_diagnostic.IDE0001.severity = %value% -# IDE0002 -dotnet_diagnostic.IDE0002.severity = %value% + # IDE0002 + dotnet_diagnostic.IDE0002.severity = %value% -# IDE0003 -dotnet_diagnostic.IDE0003.severity = %value% + # IDE0003 + dotnet_diagnostic.IDE0003.severity = %value% -# IDE0004 -dotnet_diagnostic.IDE0004.severity = %value% + # IDE0004 + dotnet_diagnostic.IDE0004.severity = %value% -# IDE0005 -dotnet_diagnostic.IDE0005.severity = %value% + # IDE0005 + dotnet_diagnostic.IDE0005.severity = %value% -# IDE0009 -dotnet_diagnostic.IDE0009.severity = %value% + # IDE0009 + dotnet_diagnostic.IDE0009.severity = %value% -# IDE0010 -dotnet_diagnostic.IDE0010.severity = %value% + # IDE0010 + dotnet_diagnostic.IDE0010.severity = %value% -# IDE0017 -dotnet_diagnostic.IDE0017.severity = %value% + # IDE0017 + dotnet_diagnostic.IDE0017.severity = %value% -# IDE0028 -dotnet_diagnostic.IDE0028.severity = %value% + # IDE0028 + dotnet_diagnostic.IDE0028.severity = %value% -# IDE0029 -dotnet_diagnostic.IDE0029.severity = %value% + # IDE0029 + dotnet_diagnostic.IDE0029.severity = %value% -# IDE0030 -dotnet_diagnostic.IDE0030.severity = %value% + # IDE0030 + dotnet_diagnostic.IDE0030.severity = %value% -# IDE0031 -dotnet_diagnostic.IDE0031.severity = %value% + # IDE0031 + dotnet_diagnostic.IDE0031.severity = %value% -# IDE0032 -dotnet_diagnostic.IDE0032.severity = %value% + # IDE0032 + dotnet_diagnostic.IDE0032.severity = %value% -# IDE0033 -dotnet_diagnostic.IDE0033.severity = %value% + # IDE0033 + dotnet_diagnostic.IDE0033.severity = %value% -# IDE0036 -dotnet_diagnostic.IDE0036.severity = %value% + # IDE0036 + dotnet_diagnostic.IDE0036.severity = %value% -# IDE0037 -dotnet_diagnostic.IDE0037.severity = %value% + # IDE0037 + dotnet_diagnostic.IDE0037.severity = %value% -# IDE0040 -dotnet_diagnostic.IDE0040.severity = %value% + # IDE0040 + dotnet_diagnostic.IDE0040.severity = %value% -# IDE0041 -dotnet_diagnostic.IDE0041.severity = %value% + # IDE0041 + dotnet_diagnostic.IDE0041.severity = %value% -# IDE0043 -dotnet_diagnostic.IDE0043.severity = %value% + # IDE0043 + dotnet_diagnostic.IDE0043.severity = %value% -# IDE0044 -dotnet_diagnostic.IDE0044.severity = %value% + # IDE0044 + dotnet_diagnostic.IDE0044.severity = %value% -# IDE0045 -dotnet_diagnostic.IDE0045.severity = %value% + # IDE0045 + dotnet_diagnostic.IDE0045.severity = %value% -# IDE0046 -dotnet_diagnostic.IDE0046.severity = %value% + # IDE0046 + dotnet_diagnostic.IDE0046.severity = %value% -# IDE0047 -dotnet_diagnostic.IDE0047.severity = %value% + # IDE0047 + dotnet_diagnostic.IDE0047.severity = %value% -# IDE0048 -dotnet_diagnostic.IDE0048.severity = %value% + # IDE0048 + dotnet_diagnostic.IDE0048.severity = %value% -# IDE0049 -dotnet_diagnostic.IDE0049.severity = %value% + # IDE0049 + dotnet_diagnostic.IDE0049.severity = %value% -# IDE0051 -dotnet_diagnostic.IDE0051.severity = %value% + # IDE0051 + dotnet_diagnostic.IDE0051.severity = %value% -# IDE0052 -dotnet_diagnostic.IDE0052.severity = %value% + # IDE0052 + dotnet_diagnostic.IDE0052.severity = %value% -# IDE0054 -dotnet_diagnostic.IDE0054.severity = %value% + # IDE0054 + dotnet_diagnostic.IDE0054.severity = %value% -# IDE0055 -dotnet_diagnostic.IDE0055.severity = %value% + # IDE0055 + dotnet_diagnostic.IDE0055.severity = %value% -# IDE0058 -dotnet_diagnostic.IDE0058.severity = %value% + # IDE0058 + dotnet_diagnostic.IDE0058.severity = %value% -# IDE0059 -dotnet_diagnostic.IDE0059.severity = %value% + # IDE0059 + dotnet_diagnostic.IDE0059.severity = %value% -# IDE0060 -dotnet_diagnostic.IDE0060.severity = %value% + # IDE0060 + dotnet_diagnostic.IDE0060.severity = %value% -# IDE0070 -dotnet_diagnostic.IDE0070.severity = %value% + # IDE0070 + dotnet_diagnostic.IDE0070.severity = %value% -# IDE0071 -dotnet_diagnostic.IDE0071.severity = %value% + # IDE0071 + dotnet_diagnostic.IDE0071.severity = %value% -# IDE0073 -dotnet_diagnostic.IDE0073.severity = %value% + # IDE0073 + dotnet_diagnostic.IDE0073.severity = %value% -# IDE0075 -dotnet_diagnostic.IDE0075.severity = %value% + # IDE0075 + dotnet_diagnostic.IDE0075.severity = %value% -# IDE0076 -dotnet_diagnostic.IDE0076.severity = %value% + # IDE0076 + dotnet_diagnostic.IDE0076.severity = %value% -# IDE0077 -dotnet_diagnostic.IDE0077.severity = %value% + # IDE0077 + dotnet_diagnostic.IDE0077.severity = %value% -# IDE0079 -dotnet_diagnostic.IDE0079.severity = %value% + # IDE0079 + dotnet_diagnostic.IDE0079.severity = %value% -# IDE0081 -dotnet_diagnostic.IDE0081.severity = %value% + # IDE0081 + dotnet_diagnostic.IDE0081.severity = %value% -# IDE0082 -dotnet_diagnostic.IDE0082.severity = %value% + # IDE0082 + dotnet_diagnostic.IDE0082.severity = %value% -# IDE0084 -dotnet_diagnostic.IDE0084.severity = %value% + # IDE0084 + dotnet_diagnostic.IDE0084.severity = %value% -# IDE0100 -dotnet_diagnostic.IDE0100.severity = %value% + # IDE0100 + dotnet_diagnostic.IDE0100.severity = %value% -# IDE1006 -dotnet_diagnostic.IDE1006.severity = %value% + # IDE1006 + dotnet_diagnostic.IDE1006.severity = %value% -# IDE1007 -dotnet_diagnostic.IDE1007.severity = %value% + # IDE1007 + dotnet_diagnostic.IDE1007.severity = %value% -# IDE0120 -dotnet_diagnostic.IDE0120.severity = %value% + # IDE0120 + dotnet_diagnostic.IDE0120.severity = %value% -# IDE0140 -dotnet_diagnostic.IDE0140.severity = %value% + # IDE0140 + dotnet_diagnostic.IDE0140.severity = %value% -# IDE0270 -dotnet_diagnostic.IDE0270.severity = %value% + # IDE0270 + dotnet_diagnostic.IDE0270.severity = %value% -# IDE2000 -dotnet_diagnostic.IDE2000.severity = %value% + # IDE2000 + dotnet_diagnostic.IDE2000.severity = %value% -# IDE2003 -dotnet_diagnostic.IDE2003.severity = %value% + # IDE2003 + dotnet_diagnostic.IDE2003.severity = %value% -# RE0001 -dotnet_diagnostic.RE0001.severity = %value% + # RE0001 + dotnet_diagnostic.RE0001.severity = %value% -# JSON001 -dotnet_diagnostic.JSON001.severity = %value% + # JSON001 + dotnet_diagnostic.JSON001.severity = %value% -# JSON002 -dotnet_diagnostic.JSON002.severity = %value% -"; - VerifyConfigureSeverityCore(expected, LanguageNames.VisualBasic); + # JSON002 + dotnet_diagnostic.JSON002.severity = %value% + """, LanguageNames.VisualBasic); } private static void VerifyConfigureCodeStyleOptionsCore((string diagnosticId, string optionName, string optionValue)[] expected, string languageName) diff --git a/src/EditorFeatures/Test/Diagnostics/SuppressMessageAttributeWorkspaceTests.cs b/src/EditorFeatures/Test/Diagnostics/SuppressMessageAttributeWorkspaceTests.cs index 7f31dd44fcdfa..0201b6017e08c 100644 --- a/src/EditorFeatures/Test/Diagnostics/SuppressMessageAttributeWorkspaceTests.cs +++ b/src/EditorFeatures/Test/Diagnostics/SuppressMessageAttributeWorkspaceTests.cs @@ -25,25 +25,26 @@ public sealed class SuppressMessageAttributeWorkspaceTests : SuppressMessageAttr private static readonly Lazy _unconditionalSuppressMessageRef = new(() => { - const string unconditionalSuppressMessageDef = @" -namespace System.Diagnostics.CodeAnalysis -{ - [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple=true, Inherited=false)] - public sealed class UnconditionalSuppressMessageAttribute : System.Attribute - { - public UnconditionalSuppressMessageAttribute(string category, string checkId) + const string unconditionalSuppressMessageDef = """ + namespace System.Diagnostics.CodeAnalysis { - Category = category; - CheckId = checkId; + [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple=true, Inherited=false)] + public sealed class UnconditionalSuppressMessageAttribute : System.Attribute + { + public UnconditionalSuppressMessageAttribute(string category, string checkId) + { + Category = category; + CheckId = checkId; + } + public string Category { get; } + public string CheckId { get; } + public string Scope { get; set; } + public string Target { get; set; } + public string MessageId { get; set; } + public string Justification { get; set; } + } } - public string Category { get; } - public string CheckId { get; } - public string Scope { get; set; } - public string Target { get; set; } - public string MessageId { get; set; } - public string Justification { get; set; } - } -}"; + """; return CSharpCompilation.Create("unconditionalsuppress", options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), syntaxTrees: [CSharpSyntaxTree.ParseText(unconditionalSuppressMessageDef)], @@ -101,17 +102,17 @@ public async Task AnalyzerExceptionDiagnosticsWithDifferentContext() var diagnostic = Diagnostic("AD0001", null); // expect 3 different diagnostics with 3 different contexts. - await VerifyCSharpAsync(@" -public class C -{ -} -public class C1 -{ -} -public class C2 -{ -} -", + await VerifyCSharpAsync(""" + public class C + { + } + public class C1 + { + } + public class C2 + { + } + """, [new ThrowExceptionForEachNamedTypeAnalyzer(ExceptionDispatchInfo.Capture(new Exception()))], diagnostics: [diagnostic, diagnostic, diagnostic]); } diff --git a/src/EditorFeatures/Test/DocCommentFormatting/DocCommentFormattingTests.cs b/src/EditorFeatures/Test/DocCommentFormatting/DocCommentFormattingTests.cs index 4de3efef230b8..31795dc86e2d2 100644 --- a/src/EditorFeatures/Test/DocCommentFormatting/DocCommentFormattingTests.cs +++ b/src/EditorFeatures/Test/DocCommentFormatting/DocCommentFormattingTests.cs @@ -33,236 +33,173 @@ private void TestFormat(string xmlFragment, string expected) [Fact] public void CTag() { - var comment = "Class Point models a point in a two-dimensional plane."; - var expected = "Class Point models a point in a two-dimensional plane."; - - TestFormat(comment, expected); + TestFormat("Class Point models a point in a two-dimensional plane.", "Class Point models a point in a two-dimensional plane."); } [Fact] public void ExampleAndCodeTags() { - var comment = @"This method changes the point's location by the given x- and y-offsets. - For example: - - Point p = new Point(3,5); - p.Translate(-1,3); - - results in p's having the value (2,8). - "; - - var expected = "This method changes the point's location by the given x- and y-offsets. For example:\r\n\r\n Point p = new Point(3,5);\r\n p.Translate(-1,3);\r\n \r\n\r\nresults in p's having the value (2,8)."; - - TestFormat(comment, expected); + TestFormat(""" + This method changes the point's location by the given x- and y-offsets. + For example: + + Point p = new Point(3,5); + p.Translate(-1,3); + + results in p's having the value (2,8). + + """, "This method changes the point's location by the given x- and y-offsets. For example:\r\n\r\n Point p = new Point(3,5);\r\n p.Translate(-1,3);\r\n \r\n\r\nresults in p's having the value (2,8)."); } [Fact] public void ListTag() { - var comment = @"Here is an example of a bulleted list: - - - Item 1. - - - Item 2. - - "; - - var expected = "Here is an example of a bulleted list:\r\n\r\n• Item 1.\r\n• Item 2."; - - TestFormat(comment, expected); + TestFormat(""" + Here is an example of a bulleted list: + + + Item 1. + + + Item 2. + + + """, "Here is an example of a bulleted list:\r\n\r\n• Item 1.\r\n• Item 2."); } [Fact] public void ParaTag() { - var comment = @"This is the entry point of the Point class testing program. - This program tests each method and operator, and - is intended to be run after any non-trivial maintenance has - been performed on the Point class."; - - var expected = -@"This is the entry point of the Point class testing program. + TestFormat(""" + This is the entry point of the Point class testing program. + This program tests each method and operator, and + is intended to be run after any non-trivial maintenance has + been performed on the Point class. + """, """ + This is the entry point of the Point class testing program. -This program tests each method and operator, and is intended to be run after any non-trivial maintenance has been performed on the Point class."; - - TestFormat(comment, expected); + This program tests each method and operator, and is intended to be run after any non-trivial maintenance has been performed on the Point class. + """); } [Fact] public void TestPermissionTag() { - var comment = @"Everyone can access this method."; - - var expected = @"Everyone can access this method."; - - TestFormat(comment, expected); + TestFormat(@"Everyone can access this method.", @"Everyone can access this method."); } [Fact] public void SeeTag() { - var comment = @""; - - var expected = @"AnotherFunction"; - - TestFormat(comment, expected); + TestFormat(@"", @"AnotherFunction"); } [Fact] public void SeeAlsoTag() { - var comment = @""; - - var expected = @"AnotherFunction"; - - TestFormat(comment, expected); + TestFormat(@"", @"AnotherFunction"); } [Fact] public void ValueTag() { - var comment = @"Property X represents the point's x-coordinate."; - - var expected = @"Property X represents the point's x-coordinate."; - - TestFormat(comment, expected); + TestFormat(@"Property X represents the point's x-coordinate.", @"Property X represents the point's x-coordinate."); } [Fact] public void TestParamRefTag() { - var comment = -@"This constructor initializes the new Point to -(,)."; - - var expected = "This constructor initializes the new Point to (xor,yor)."; - - TestFormat(comment, expected); + TestFormat(""" + This constructor initializes the new Point to + (,). + """, "This constructor initializes the new Point to (xor,yor)."); } [Fact] public void TestTypeParamRefTag() { - var comment = @"This method fetches data and returns a list of ."; - - var expected = @"This method fetches data and returns a list of Z."; - - TestFormat(comment, expected); + TestFormat(@"This method fetches data and returns a list of .", @"This method fetches data and returns a list of Z."); } [Fact] public void Whitespace1() { - var comment = " This has extra whitespace. "; - - var expected = "This has extra whitespace."; - - TestFormat(comment, expected); + TestFormat(" This has extra whitespace. ", "This has extra whitespace."); } [Fact] public void Whitespace2() { - var comment = -@" -This has extra -whitespace. -"; - - var expected = "This has extra whitespace."; - - TestFormat(comment, expected); + TestFormat(""" + This has extra + whitespace. + """, "This has extra whitespace."); } [Fact] public void Whitespace3() { - var comment = "This has extra whitespace."; - var expected = "This has extra whitespace."; - - TestFormat(comment, expected); + TestFormat("This has extra whitespace.", "This has extra whitespace."); } [Fact] public void Paragraphs1() { - var comment = -@" -This is part of a paragraph. -"; - var expected = "This is part of a paragraph."; - - TestFormat(comment, expected); + TestFormat(""" + This is part of a paragraph. + """, "This is part of a paragraph."); } [Fact] public void Paragraphs2() { - var comment = -@" -This is part of a paragraph. -This is also part of a paragraph. -"; - - var expected = -@"This is part of a paragraph. - -This is also part of a paragraph."; + TestFormat(""" + This is part of a paragraph. + This is also part of a paragraph. + """, """ + This is part of a paragraph. - TestFormat(comment, expected); + This is also part of a paragraph. + """); } [Fact] public void Paragraphs3() { - var comment = -@" -This is a summary. -This is part of a paragraph. -"; + TestFormat(""" + This is a summary. + This is part of a paragraph. + """, """ + This is a summary. - var expected = -@"This is a summary. - -This is part of a paragraph."; - - TestFormat(comment, expected); + This is part of a paragraph. + """); } [Fact] public void Paragraphs4() { - var comment = -@" -This is part of a paragraph. This is part of the summary, too. -"; - - var expected = -@"This is part of a paragraph. + TestFormat(""" + This is part of a paragraph. This is part of the summary, too. + """, """ + This is part of a paragraph. -This is part of the summary, too."; - - TestFormat(comment, expected); + This is part of the summary, too. + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32838")] public void Paragraphs5() { - var comment = -@" -This is part of a
paragraph.
-This is also part of a paragraph. -"; - - var expected = -@"This is part of a -paragraph. + TestFormat(""" + This is part of a
paragraph.
+ This is also part of a paragraph. + """, """ + This is part of a + paragraph. -This is also part of a paragraph."; - - TestFormat(comment, expected); + This is also part of a paragraph. + """); } [Theory] @@ -271,139 +208,87 @@ public void Paragraphs5() [WorkItem("https://github.com/dotnet/roslyn/issues/32838")] public void Paragraphs6(string lineBreak) { - var comment = -$@" -This is part of a{lineBreak}paragraph. -This is also part of a paragraph. -"; - - var expected = -@"This is part of a + TestFormat($""" + This is part of a{lineBreak}paragraph. + This is also part of a paragraph. + """, """ + This is part of a -paragraph. + paragraph. -This is also part of a paragraph."; - - TestFormat(comment, expected); + This is also part of a paragraph. + """); } [Fact] public void See1() { - var comment = @"See "; - - var expected = "See System.Object"; - - TestFormat(comment, expected); + TestFormat(@"See ", "See System.Object"); } [Fact] public void See2() { - var comment = @"See "; - - var expected = @"See"; - - TestFormat(comment, expected); + TestFormat(@"See ", @"See"); } [Fact] public void See3() { - var comment = @"See "; - - var expected = "See true"; - - TestFormat(comment, expected); + TestFormat(@"See ", "See true"); } [Fact] public void See4() { - var comment = @"See "; - - var expected = "See https://github.com"; - - TestFormat(comment, expected); + TestFormat(@"See ", "See https://github.com"); } [Fact] public void See5() { - var comment = @"See GitHub"; - - var expected = "See GitHub"; - - TestFormat(comment, expected); + TestFormat(@"See GitHub", "See GitHub"); } [Fact] public void See6() { - var comment = @"See "; - - var expected = "See https://github.com"; - - TestFormat(comment, expected); + TestFormat(@"See ", "See https://github.com"); } [Fact] public void SeeAlso1() { - var comment = @"See also "; - - var expected = @"See also System.Object"; - - TestFormat(comment, expected); + TestFormat(@"See also ", @"See also System.Object"); } [Fact] public void SeeAlso2() { - var comment = @"See also "; - - var expected = @"See also"; - - TestFormat(comment, expected); + TestFormat(@"See also ", @"See also"); } [Fact] public void SeeAlso3() { - var comment = @"See also "; - - var expected = "See also true"; - - TestFormat(comment, expected); + TestFormat(@"See also ", "See also true"); } [Fact] public void SeeAlso4() { - var comment = @"See also "; - - var expected = "See also https://github.com"; - - TestFormat(comment, expected); + TestFormat(@"See also ", "See also https://github.com"); } [Fact] public void SeeAlso5() { - var comment = @"See also GitHub"; - - var expected = "See also GitHub"; - - TestFormat(comment, expected); + TestFormat(@"See also GitHub", "See also GitHub"); } [Fact] public void SeeAlso6() { - var comment = @"See also "; - - var expected = "See also https://github.com"; - - TestFormat(comment, expected); + TestFormat(@"See also ", "See also https://github.com"); } } diff --git a/src/EditorFeatures/Test/EditAndContinue/EditAndContinueLanguageServiceTests.cs b/src/EditorFeatures/Test/EditAndContinue/EditAndContinueLanguageServiceTests.cs index 5f0c1571e4343..07909235d0237 100644 --- a/src/EditorFeatures/Test/EditAndContinue/EditAndContinueLanguageServiceTests.cs +++ b/src/EditorFeatures/Test/EditAndContinue/EditAndContinueLanguageServiceTests.cs @@ -5,6 +5,7 @@ #nullable disable using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; @@ -14,6 +15,7 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.BrokeredServices; using Microsoft.CodeAnalysis.BrokeredServices.UnitTests; +using Microsoft.CodeAnalysis.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; @@ -143,7 +145,7 @@ await localWorkspace.ChangeSolutionAsync(localWorkspace.CurrentSolution // EnterBreakStateAsync - mockEncService.BreakStateOrCapabilitiesChangedImpl = (bool? inBreakState) => + mockEncService.BreakStateOrCapabilitiesChangedImpl = inBreakState => { Assert.True(inBreakState); }; @@ -243,6 +245,70 @@ await localWorkspace.ChangeSolutionAsync(localWorkspace.CurrentSolution $"Error CS0001: {document.FilePath}(0, 1, 0, 2): Syntax error", ], updates.Diagnostics.Select(Inspect)); + var moduleId = Guid.NewGuid(); + var methodId = new ManagedModuleMethodId(token: 0x06000001, version: 2); + + mockEncService.EmitSolutionUpdateImpl = (solution, _, _) => + { + var syntaxTree = solution.GetRequiredDocument(documentId).GetSyntaxTreeSynchronously(CancellationToken.None)!; + + return new() + { + Solution = solution, + ModuleUpdates = new ModuleUpdates( + ModuleUpdateStatus.Ready, + [ + new ManagedHotReloadUpdate( + moduleId, + "module.dll", + project.Id, + ilDelta: [1], + metadataDelta: [2], + pdbDelta: [3], + updatedTypes: [0x02000001], + requiredCapabilities: ["Baseline"], + updatedMethods: [0x06000002], + sequencePoints: [new SequencePointUpdates("file.cs", [new SourceLineUpdate(1, 2)])], + activeStatements: [new ManagedActiveStatementUpdate(methodId, ilOffset: 1, new(1, 2, 3, 4))], + exceptionRegions: [new ManagedExceptionRegionUpdate(methodId, delta: 1, new(10, 20, 30, 40))]) + ]), + Diagnostics = [], + SyntaxError = null, + ProjectsToRebuild = [], + ProjectsToRestart = ImmutableDictionary>.Empty, + }; + }; + + updates = await localService.GetUpdatesAsync(runningProjects: [project.FilePath], CancellationToken.None); + + Assert.Equal(++observedDiagnosticVersion, diagnosticRefresher.GlobalStateVersion); + + var update = updates.Updates.Single(); + Assert.Equal(moduleId, update.Module); + Assert.Equal("module.dll", update.ModuleName); + AssertEx.SequenceEqual([(byte)1], update.ILDelta); + AssertEx.SequenceEqual([(byte)2], update.MetadataDelta); + AssertEx.SequenceEqual([(byte)3], update.PdbDelta); + AssertEx.SequenceEqual([0x02000001], update.UpdatedTypes); + AssertEx.SequenceEqual(["Baseline"], update.RequiredCapabilities); + AssertEx.SequenceEqual([0x06000002], update.UpdatedMethods); + + var sequencePoint = update.SequencePoints.Single(); + Assert.Equal("file.cs", sequencePoint.FileName); + AssertEx.SequenceEqual(["1->2"], sequencePoint.LineUpdates.Select(u => $"{u.OldLine}->{u.NewLine}")); + + var activeStatement = update.ActiveStatements.Single(); + Assert.Equal(0x06000001, activeStatement.Method.Token); + Assert.Equal(2, activeStatement.Method.Version); + Assert.Equal(1, activeStatement.ILOffset); + Assert.Equal(new(1, 2, 3, 4), activeStatement.NewSpan); + + var exceptionRegion = update.ExceptionRegions.Single(); + Assert.Equal(0x06000001, exceptionRegion.Method.Token); + Assert.Equal(2, exceptionRegion.Method.Version); + Assert.Equal(1, exceptionRegion.Delta); + Assert.Equal(new(10, 20, 30, 40), exceptionRegion.NewSpan); + Assert.True(sessionState.IsSessionActive); if (commitChanges) @@ -279,9 +345,6 @@ await localWorkspace.ChangeSolutionAsync(localWorkspace.CurrentSolution public async Task DefaultPdbMatchingSourceTextProvider() { var source1 = "class C1 { void M() { System.Console.WriteLine(\"a\"); } }"; - var source2 = "class C1 { void M() { System.Console.WriteLine(\"b\"); } }"; - var source3 = "class C1 { void M() { System.Console.WriteLine(\"c\"); } }"; - var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1, Encoding.UTF8); @@ -310,14 +373,14 @@ public async Task DefaultPdbMatchingSourceTextProvider() var document1 = solution.GetRequiredDocument(documentId); _ = await document1.GetTextAsync(CancellationToken.None); - File.WriteAllText(sourceFile.Path, source2, Encoding.UTF8); + File.WriteAllText(sourceFile.Path, "class C1 { void M() { System.Console.WriteLine(\"b\"); } }", Encoding.UTF8); await languageService.StartSessionAsync(CancellationToken.None); await languageService.EnterBreakStateAsync(CancellationToken.None); workspace.OnDocumentOpened(documentId, new TestSourceTextContainer() { - Text = SourceText.From(source3, Encoding.UTF8, SourceHashAlgorithm.Sha1) + Text = SourceText.From("class C1 { void M() { System.Console.WriteLine(\"c\"); } }", Encoding.UTF8, SourceHashAlgorithm.Sha1) }); await workspace.GetService().GetWaiter(FeatureAttribute.Workspace).ExpeditedWaitAsync(); diff --git a/src/EditorFeatures/Test/EditorConfigSettings/Data/CodeStyleSettingsTest.cs b/src/EditorFeatures/Test/EditorConfigSettings/Data/CodeStyleSettingsTest.cs index 14326bc577643..9005115118f75 100644 --- a/src/EditorFeatures/Test/EditorConfigSettings/Data/CodeStyleSettingsTest.cs +++ b/src/EditorFeatures/Test/EditorConfigSettings/Data/CodeStyleSettingsTest.cs @@ -9,8 +9,8 @@ using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; -using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Options; +using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.EditorConfigSettings.Data; diff --git a/src/EditorFeatures/Test/EmbeddedLanguages/StackFrame/StackFrameParserTests.cs b/src/EditorFeatures/Test/EmbeddedLanguages/StackFrame/StackFrameParserTests.cs index 4060969aa320d..a28aec926349d 100644 --- a/src/EditorFeatures/Test/EmbeddedLanguages/StackFrame/StackFrameParserTests.cs +++ b/src/EditorFeatures/Test/EmbeddedLanguages/StackFrame/StackFrameParserTests.cs @@ -2,11 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Xunit; using System.Collections.Immutable; +using Microsoft.CodeAnalysis.EmbeddedLanguages.StackFrame; +using Xunit; using static Microsoft.CodeAnalysis.Editor.UnitTests.EmbeddedLanguages.StackFrame.StackFrameSyntaxFactory; using static Microsoft.CodeAnalysis.EmbeddedLanguages.StackFrame.StackFrameExtensions; -using Microsoft.CodeAnalysis.EmbeddedLanguages.StackFrame; namespace Microsoft.CodeAnalysis.Editor.UnitTests.EmbeddedLanguages.StackFrame; diff --git a/src/EditorFeatures/Test/EmbeddedLanguages/StackFrame/StackFrameSyntaxFactory.cs b/src/EditorFeatures/Test/EmbeddedLanguages/StackFrame/StackFrameSyntaxFactory.cs index 4a54195c51c4a..90c1c567b9007 100644 --- a/src/EditorFeatures/Test/EmbeddedLanguages/StackFrame/StackFrameSyntaxFactory.cs +++ b/src/EditorFeatures/Test/EmbeddedLanguages/StackFrame/StackFrameSyntaxFactory.cs @@ -12,9 +12,9 @@ namespace Microsoft.CodeAnalysis.Editor.UnitTests.EmbeddedLanguages.StackFrame; +using StackFrameNodeOrToken = EmbeddedSyntaxNodeOrToken; using StackFrameToken = EmbeddedSyntaxToken; using StackFrameTrivia = EmbeddedSyntaxTrivia; -using StackFrameNodeOrToken = EmbeddedSyntaxNodeOrToken; internal static class StackFrameSyntaxFactory { diff --git a/src/EditorFeatures/Test/Extensions/EnumerableExtensionTests.cs b/src/EditorFeatures/Test/Extensions/EnumerableExtensionTests.cs deleted file mode 100644 index a282445092221..0000000000000 --- a/src/EditorFeatures/Test/Extensions/EnumerableExtensionTests.cs +++ /dev/null @@ -1,97 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Linq; -using Roslyn.Utilities; -using Xunit; - -namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; - -public sealed class EnumerableExtensionTests -{ - private static IEnumerable Enumerable(params T[] values) - => values; - - [Fact] - public void TestDo() - { - var elements = Enumerable(1, 2, 3); - var result = new List(); - - elements.Do(a => result.Add(a)); - - Assert.True(elements.SequenceEqual(result)); - } - - [Fact] - public void TestConcat() - { - var elements = Enumerable(1, 2, 3); - Assert.True(Enumerable(1, 2, 3, 4).SequenceEqual(elements.Concat(4))); - } - - [Fact] - public void TestSetEquals() - => Assert.True(Enumerable(1, 2, 3, 4).SetEquals(Enumerable(4, 2, 3, 1))); - - [Fact] - public void TestIsEmpty() - { - Assert.True(Enumerable().IsEmpty()); - Assert.False(Enumerable(0).IsEmpty()); - } - - [Fact] - public void TestAll() - { - Assert.True(Enumerable().All()); - Assert.True(Enumerable(true).All()); - Assert.True(Enumerable(true, true).All()); - - Assert.False(Enumerable(false).All()); - Assert.False(Enumerable(false, false).All()); - Assert.False(Enumerable(true, false).All()); - Assert.False(Enumerable(false, true).All()); - } - - [Fact] - public void TestJoin() - { - Assert.Equal(string.Empty, Enumerable().Join(", ")); - Assert.Equal("a", Enumerable("a").Join(", ")); - Assert.Equal("a, b", Enumerable("a", "b").Join(", ")); - Assert.Equal("a, b, c", Enumerable("a", "b", "c").Join(", ")); - } - - [Fact] - public void TestFlatten() - { - var sequence = Enumerable(Enumerable("a", "b"), Enumerable("c", "d"), Enumerable("e", "f")); - Assert.True(sequence.Flatten().SequenceEqual(Enumerable("a", "b", "c", "d", "e", "f"))); - } - - [Fact] - public void TestSequenceEqualWithFunction() - { - static bool equality(int a, int b) => a == b; - var seq = new List() { 1, 2, 3 }; - - // same object reference - Assert.True(seq.SequenceEqual(seq, equality)); - - // matching values, matching lengths - Assert.True(seq.SequenceEqual(new int[] { 1, 2, 3 }, equality)); - - // matching values, different lengths - Assert.False(seq.SequenceEqual(new int[] { 1, 2, 3, 4 }, equality)); - Assert.False(seq.SequenceEqual(new int[] { 1, 2 }, equality)); - - // different values, matching lengths - Assert.False(seq.SequenceEqual(new int[] { 1, 2, 6 }, equality)); - } -} diff --git a/src/EditorFeatures/Test/Extensions/IProjectionBufferFactoryServiceExtensionsTests.cs b/src/EditorFeatures/Test/Extensions/IProjectionBufferFactoryServiceExtensionsTests.cs index 148f1caf0cb28..00cac3c1d6cb3 100644 --- a/src/EditorFeatures/Test/Extensions/IProjectionBufferFactoryServiceExtensionsTests.cs +++ b/src/EditorFeatures/Test/Extensions/IProjectionBufferFactoryServiceExtensionsTests.cs @@ -27,9 +27,11 @@ public void TestCreateElisionBufferWithoutIndentation() var exportProvider = EditorTestCompositions.Editor.ExportProviderFactory.CreateExportProvider(); var contentTypeRegistryService = exportProvider.GetExportedValue(); var textBuffer = exportProvider.GetExportedValue().CreateTextBuffer( -@" line 1 - line 2 - line 3", contentTypeRegistryService.GetContentType("text")); + """ + line 1 + line 2 + line 3 + """, contentTypeRegistryService.GetContentType("text")); var elisionBuffer = IProjectionBufferFactoryServiceExtensions.CreateProjectionBufferWithoutIndentation( exportProvider.GetExportedValue(), @@ -53,10 +55,12 @@ public void TestCreateProjectionBuffer() var exportProvider = composition.ExportProviderFactory.CreateExportProvider(); var contentTypeRegistryService = exportProvider.GetExportedValue(); var textBuffer = exportProvider.GetExportedValue().CreateTextBuffer( -@" line 1 - line 2 - line 3 - line 4", contentTypeRegistryService.GetContentType("text")); + """ + line 1 + line 2 + line 3 + line 4 + """, contentTypeRegistryService.GetContentType("text")); var projectionBuffer = IProjectionBufferFactoryServiceExtensions.CreateProjectionBuffer( exportProvider.GetExportedValue(), @@ -83,10 +87,12 @@ public void TestCreateProjectionBufferWithoutIndentation() var exportProvider = composition.ExportProviderFactory.CreateExportProvider(); var contentTypeRegistryService = exportProvider.GetExportedValue(); var textBuffer = exportProvider.GetExportedValue().CreateTextBuffer( -@" line 1 - line 2 - line 3 - line 4", contentTypeRegistryService.GetContentType("text")); + """ + line 1 + line 2 + line 3 + line 4 + """, contentTypeRegistryService.GetContentType("text")); var projectionBuffer = IProjectionBufferFactoryServiceExtensions.CreateProjectionBufferWithoutIndentation( exportProvider.GetExportedValue(), diff --git a/src/EditorFeatures/Test/InheritanceMargin/InheritanceMarginTests.cs b/src/EditorFeatures/Test/InheritanceMargin/InheritanceMarginTests.cs index 7240963ce03ca..1067001816f0b 100644 --- a/src/EditorFeatures/Test/InheritanceMargin/InheritanceMarginTests.cs +++ b/src/EditorFeatures/Test/InheritanceMargin/InheritanceMarginTests.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.InheritanceMargin; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote.Testing; @@ -37,17 +38,21 @@ private static async Task VerifyInSingleDocumentAsync( TestHost testHost, params TestInheritanceMemberItem[] memberItems) { - markup = @$""; - - var workspaceFile = $@" - - - - {markup} - - -"; + markup = $""" + + """; + + var workspaceFile = $""" + + + + + {markup} + + + + """; var cancellationToken = CancellationToken.None; @@ -66,17 +71,19 @@ private static async Task VerifyInMultipleDocumentsAsync( TestHost testHost, params TestInheritanceMemberItem[] memberItems) { - var workspaceFile = $@" - - - - - - - - - -"; + var workspaceFile = $""" + + + + + + + + + + + + """; var cancellationToken = CancellationToken.None; @@ -186,22 +193,24 @@ private static async Task VerifyInDifferentProjectsAsync( TestHost testHost) { var workspaceFile = - $@" - - - Assembly2 - - - - - - - - - -"; + $""" + + + + Assembly2 + + + + + + + + + + + """; var cancellationToken = CancellationToken.None; using var testWorkspace = TestWorkspace.Create( @@ -359,22 +368,17 @@ public static TestInheritanceTargetItem Create( [Theory, CombinatorialData] public Task TestCSharpClassWithErrorBaseType(TestHost testHost) { - var markup = @" -public class Bar : SomethingUnknown -{ -}"; - return VerifyNoItemForDocumentAsync(markup, LanguageNames.CSharp, testHost); + return VerifyNoItemForDocumentAsync(""" + + public class Bar : SomethingUnknown + { + } + """, LanguageNames.CSharp, testHost); } [Theory, CombinatorialData] public Task TestCSharpReferencingMetadata(TestHost testHost) { - var markup = @" -using System.Collections; -public class Bar : IEnumerable -{ - public IEnumerator GetEnumerator () { return null }; -}"; var itemForBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "class Bar", @@ -391,19 +395,19 @@ public class Bar : IEnumerable relationship: InheritanceRelationship.ImplementedMember, inMetadata: true)]); - return VerifyInSingleDocumentAsync(markup, LanguageNames.CSharp, testHost, itemForBar, itemForGetEnumerator); + return VerifyInSingleDocumentAsync(""" + + using System.Collections; + public class Bar : IEnumerable + { + public IEnumerator GetEnumerator () { return null }; + } + """, LanguageNames.CSharp, testHost, itemForBar, itemForGetEnumerator); } [Theory, CombinatorialData] public Task TestCSharpClassImplementingInterface(TestHost testHost) { - var markup = @" -interface {|target1:IBar|} { } -public class {|target2:Bar|} : IBar -{ -} - "; - var itemOnLine2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", @@ -421,7 +425,14 @@ public class {|target2:Bar|} : IBar relationship: InheritanceRelationship.ImplementedInterface)]); return VerifyInSingleDocumentAsync( - markup, + """ + + interface {|target1:IBar|} { } + public class {|target2:Bar|} : IBar + { + } + + """, LanguageNames.CSharp, testHost, itemOnLine2, @@ -431,11 +442,6 @@ public class {|target2:Bar|} : IBar [Theory, CombinatorialData] public Task TestCSharpInterfaceImplementingInterface(TestHost testHost) { - var markup = @" - interface {|target1:IBar|} { } - interface {|target2:IBar2|} : IBar { } - "; - var itemOnLine2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", @@ -454,7 +460,12 @@ interface {|target2:IBar2|} : IBar { } ); return VerifyInSingleDocumentAsync( - markup, + """ + + interface {|target1:IBar|} { } + interface {|target2:IBar2|} : IBar { } + + """, LanguageNames.CSharp, testHost, itemOnLine2, @@ -464,11 +475,6 @@ interface {|target2:IBar2|} : IBar { } [Theory, CombinatorialData] public Task TestCSharpClassInheritsClass(TestHost testHost) { - var markup = @" - class {|target2:A|} { } - class {|target1:B|} : A { } - "; - var itemOnLine2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "class A", @@ -487,7 +493,12 @@ class {|target1:B|} : A { } ); return VerifyInSingleDocumentAsync( - markup, + """ + + class {|target2:A|} { } + class {|target1:B|} : A { } + + """, LanguageNames.CSharp, testHost, itemOnLine2, @@ -505,11 +516,12 @@ class {|target1:B|} : A { } [InlineData("interface", TestHost.OutOfProcess)] public Task TestCSharpTypeWithoutBaseType(string typeName, TestHost testHost) { - var markup = $@" - public {typeName} Bar - {{ - }}"; - return VerifyNoItemForDocumentAsync(markup, LanguageNames.CSharp, testHost); + return VerifyNoItemForDocumentAsync($$""" + + public {{typeName}} Bar + { + } + """, LanguageNames.CSharp, testHost); } [Theory] @@ -523,15 +535,16 @@ public Task TestCSharpTypeWithoutBaseType(string typeName, TestHost testHost) [InlineData("public static Bar operator +(Bar a, Bar b) => new Bar();", TestHost.OutOfProcess)] public Task TestCSharpSpecialMember(string memberDeclaration, TestHost testHost) { - var markup = $@" - public abstract class {{|target1:Bar1|}} - {{}} - public class {{|{SearchAreaTag}:Bar : Bar1 - {{ - {{{memberDeclaration}|}} - }}"; return VerifyInSingleDocumentAsync( - markup, + $$""" + + public abstract class {|target1:Bar1|} + {} + public class {|{{SearchAreaTag}}:Bar : Bar1 + { + {{{memberDeclaration}}|} + } + """, LanguageNames.CSharp, testHost, new TestInheritanceMemberItem( @@ -546,19 +559,6 @@ public class {{|{SearchAreaTag}:Bar : Bar1 [Theory, CombinatorialData] public Task TestCSharpEventDeclaration(TestHost testHost) { - var markup = @" - using System; - interface {|target2:IBar|} - { - event EventHandler {|target4:e|}; - } - public class {|target1:Bar|} : IBar - { - public event EventHandler {|target3:e|} - { - add {} remove {} - } - }"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "interface IBar", @@ -592,7 +592,21 @@ [new TargetInfo( relationship: InheritanceRelationship.ImplementedMember)]); return VerifyInSingleDocumentAsync( - markup, + """ + + using System; + interface {|target2:IBar|} + { + event EventHandler {|target4:e|}; + } + public class {|target1:Bar|} : IBar + { + public event EventHandler {|target3:e|} + { + add {} remove {} + } + } + """, LanguageNames.CSharp, testHost, itemForIBar, @@ -604,15 +618,6 @@ [new TargetInfo( [Theory, CombinatorialData] public Task TestCSharpEventFieldDeclarations(TestHost testHost) { - var markup = @"using System; - interface {|target2:IBar|} - { - event EventHandler {|target5:e1|}, {|target6:e2|}; - } - public class {|target1:Bar|} : IBar - { - public event EventHandler {|target3:e1|}, {|target4:e2|}; - }"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", @@ -662,7 +667,17 @@ [new TargetInfo( relationship: InheritanceRelationship.ImplementedMember)]); return VerifyInSingleDocumentAsync( - markup, + """ + using System; + interface {|target2:IBar|} + { + event EventHandler {|target5:e1|}, {|target6:e2|}; + } + public class {|target1:Bar|} : IBar + { + public event EventHandler {|target3:e1|}, {|target4:e2|}; + } + """, LanguageNames.CSharp, testHost, itemForIBar, @@ -676,21 +691,6 @@ [new TargetInfo( [Theory, CombinatorialData] public Task TestCSharpInterfaceMembers(TestHost testHost) { - var markup = @"using System; - interface {|target1:IBar|} - { - void {|target4:Foo|}(); - int {|target6:Poo|} { get; set; } - event EventHandler {|target8:Eoo|}; - int {|target9:this|}[int i] { get; set; } - } - public class {|target2:Bar|} : IBar - { - public void {|target3:Foo|}() { } - public int {|target5:Poo|} { get; set; } - public event EventHandler {|target7:Eoo|}; - public int {|target10:this|}[int i] { get => 1; set { } } - }"; var itemForEooInClass = new TestInheritanceMemberItem( lineNumber: 13, memberName: "event EventHandler Bar.Eoo", @@ -782,7 +782,23 @@ public class {|target2:Bar|} : IBar ); return VerifyInSingleDocumentAsync( - markup, + """ + using System; + interface {|target1:IBar|} + { + void {|target4:Foo|}(); + int {|target6:Poo|} { get; set; } + event EventHandler {|target8:Eoo|}; + int {|target9:this|}[int i] { get; set; } + } + public class {|target2:Bar|} : IBar + { + public void {|target3:Foo|}() { } + public int {|target5:Poo|} { get; set; } + public event EventHandler {|target7:Eoo|}; + public int {|target10:this|}[int i] { get => 1; set { } } + } + """, LanguageNames.CSharp, testHost, itemForEooInClass, @@ -804,21 +820,6 @@ public class {|target2:Bar|} : IBar [InlineData("virtual", TestHost.OutOfProcess)] public Task TestCSharpAbstractClassMembers(string modifier, TestHost testHost) { - var markup = $@"using System; - public abstract class {{|target2:Bar|}} - {{ - public {modifier} void {{|target4:Foo|}}(); - public {modifier} int {{|target6:Poo|}} {{ get; set; }} - public {modifier} event EventHandler {{|target8:Eoo|}}; - }} - public class {{|target1:Bar2|}} : Bar - {{ - public override void {{|target3:Foo|}}() {{ }} - public override int {{|target5:Poo|}} {{ get; set; }} - public override event EventHandler {{|target7:Eoo|}}; - }} - "; - var itemForEooInClass = new TestInheritanceMemberItem( lineNumber: 12, memberName: "override event EventHandler Bar2.Eoo", @@ -884,7 +885,22 @@ public class {{|target1:Bar2|}} : Bar relationship: InheritanceRelationship.BaseType)]); return VerifyInSingleDocumentAsync( - markup, + $$""" + using System; + public abstract class {|target2:Bar|} + { + public {{modifier}} void {|target4:Foo|}(); + public {{modifier}} int {|target6:Poo|} { get; set; } + public {{modifier}} event EventHandler {|target8:Eoo|}; + } + public class {|target1:Bar2|} : Bar + { + public override void {|target3:Foo|}() { } + public override int {|target5:Poo|} { get; set; } + public override event EventHandler {|target7:Eoo|}; + } + + """, LanguageNames.CSharp, testHost, itemForBar, @@ -900,33 +916,37 @@ public class {{|target1:Bar2|}} : Bar [Theory, CombinatorialData] public Task TestCSharpOverrideMemberCanFindImplementingInterface(bool testDuplicate, TestHost testHost) { - var markup1 = @"using System; - public interface {|target4:IBar|} - { - void {|target6:Foo|}(); - } - public class {|target1:Bar1|} : IBar - { - public virtual void {|target2:Foo|}() { } - } - public class {|target5:Bar2|} : Bar1 - { - public override void {|target3:Foo|}() { } - }"; + var markup1 = """ + using System; + public interface {|target4:IBar|} + { + void {|target6:Foo|}(); + } + public class {|target1:Bar1|} : IBar + { + public virtual void {|target2:Foo|}() { } + } + public class {|target5:Bar2|} : Bar1 + { + public override void {|target3:Foo|}() { } + } + """; - var markup2 = @"using System; - public interface {|target4:IBar|} - { - void {|target6:Foo|}(); - } - public class {|target1:Bar1|} : IBar - { - public virtual void {|target2:Foo|}() { } - } - public class {|target5:Bar2|} : Bar1, IBar - { - public override void {|target3:Foo|}() { } - }"; + var markup2 = """ + using System; + public interface {|target4:IBar|} + { + void {|target6:Foo|}(); + } + public class {|target1:Bar1|} : IBar + { + public virtual void {|target2:Foo|}() { } + } + public class {|target5:Bar2|} : Bar1, IBar + { + public override void {|target3:Foo|}() { } + } + """; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, @@ -1037,21 +1057,6 @@ public class {|target5:Bar2|} : Bar1, IBar [InlineData("virtual", TestHost.OutOfProcess)] public Task TestCSharpAbstractClassMembers_LooseMatch(string modifier, TestHost testHost) { - var markup = $@"using System; - public abstract class {{|target2:Bar|}} - {{ - public {modifier} void {{|target4:Foo|}}(); - public {modifier} int {{|target6:Poo|}} {{ get; set; }} - public {modifier} event EventHandler {{|target8:Eoo|}}; - }} - public class {{|target1:Bar2|}} : Bar - {{ - public override void {{|target3:Foo|}}(int i) {{ }} - public override string {{|target5:Poo|}} {{ get; set; }} - public override event Action {{|target7:Eoo|}}; - }} - "; - var itemForEooInClass = new TestInheritanceMemberItem( lineNumber: 12, memberName: "override event Action Bar2.Eoo", @@ -1117,7 +1122,22 @@ public class {{|target1:Bar2|}} : Bar relationship: InheritanceRelationship.BaseType)]); return VerifyInSingleDocumentAsync( - markup, + $$""" + using System; + public abstract class {|target2:Bar|} + { + public {{modifier}} void {|target4:Foo|}(); + public {{modifier}} int {|target6:Poo|} { get; set; } + public {{modifier}} event EventHandler {|target8:Eoo|}; + } + public class {|target1:Bar2|} : Bar + { + public override void {|target3:Foo|}(int i) { } + public override string {|target5:Poo|} { get; set; } + public override event Action {|target7:Eoo|}; + } + + """, LanguageNames.CSharp, testHost, itemForBar, @@ -1133,17 +1153,6 @@ public class {{|target1:Bar2|}} : Bar [Theory, CombinatorialData] public Task TestCSharpFindGenericsBaseType(TestHost testHost) { - var markup = @" -public interface {|target2:IBar|} -{ - void {|target4:Foo|}(); -} - -public class {|target1:Bar2|} : IBar, IBar -{ - public void {|target3:Foo|}(); -}"; - var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", @@ -1179,7 +1188,18 @@ public class {|target1:Bar2|} : IBar, IBar relationship: InheritanceRelationship.ImplementedMember)]); return VerifyInSingleDocumentAsync( - markup, + """ + + public interface {|target2:IBar|} + { + void {|target4:Foo|}(); + } + + public class {|target1:Bar2|} : IBar, IBar + { + public void {|target3:Foo|}(); + } + """, LanguageNames.CSharp, testHost, itemForIBar, @@ -1191,19 +1211,6 @@ public class {|target1:Bar2|} : IBar, IBar [Theory, CombinatorialData] public Task TestCSharpExplicitInterfaceImplementation(TestHost testHost) { - var markup = @" -interface {|target2:IBar|} -{ - void {|target3:Foo|}(T t); -} - -abstract class {|target1:AbsBar|} : IBar -{ - void IBar.{|target4:Foo|}(int t) - { - throw new System.NotImplementedException(); - } -}"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", @@ -1237,7 +1244,21 @@ abstract class {|target1:AbsBar|} : IBar relationship: InheritanceRelationship.ImplementedMember)]); return VerifyInSingleDocumentAsync( - markup, + """ + + interface {|target2:IBar|} + { + void {|target3:Foo|}(T t); + } + + abstract class {|target1:AbsBar|} : IBar + { + void IBar.{|target4:Foo|}(int t) + { + throw new System.NotImplementedException(); + } + } + """, LanguageNames.CSharp, testHost, itemForIBar, @@ -1249,24 +1270,6 @@ abstract class {|target1:AbsBar|} : IBar [Theory, CombinatorialData] public Task TestStaticAbstractMemberInterface(TestHost testHost) { - var markup = @" -interface {|target5:I1|} where T : I1 -{ - static abstract void {|target4:M1|}(); - static abstract int {|target7:P1|} { get; set; } - static abstract event EventHandler {|target9:e1|}; - static abstract int operator {|target11:+|}(T i1); - static abstract implicit operator {|target12:int|}(T i1); -} - -public class {|target1:Class1|} : I1 -{ - public static void {|target2:M1|}() {} - public static int {|target6:P1|} { get => 1; set { } } - public static event EventHandler {|target8:e1|}; - public static int operator {|target10:+|}(Class1 i) => 1; - public static implicit operator {|target13:int|}(Class1 i) => 0; -}"; var itemForI1 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface I1", @@ -1364,7 +1367,26 @@ public class {|target1:Class1|} : I1 relationship: InheritanceRelationship.ImplementedMember)]); return VerifyInSingleDocumentAsync( - markup, + """ + + interface {|target5:I1|} where T : I1 + { + static abstract void {|target4:M1|}(); + static abstract int {|target7:P1|} { get; set; } + static abstract event EventHandler {|target9:e1|}; + static abstract int operator {|target11:+|}(T i1); + static abstract implicit operator {|target12:int|}(T i1); + } + + public class {|target1:Class1|} : I1 + { + public static void {|target2:M1|}() {} + public static int {|target6:P1|} { get => 1; set { } } + public static event EventHandler {|target8:e1|}; + public static int operator {|target10:+|}(Class1 i) => 1; + public static implicit operator {|target13:int|}(Class1 i) => 0; + } + """, LanguageNames.CSharp, testHost, itemForI1, @@ -1384,20 +1406,6 @@ public class {|target1:Class1|} : I1 [Theory, CombinatorialData] public Task TestCSharpPartialClass(TestHost testHost) { - var markup = @" -interface {|target1:IBar|} -{ -} - -public partial class {|target2:Bar|} : IBar -{ -} - -public partial class {|target3:Bar|} -{ -} - "; - var itemOnLine2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", @@ -1423,7 +1431,21 @@ public partial class {|target3:Bar|} relationship: InheritanceRelationship.ImplementedInterface)]); return VerifyInSingleDocumentAsync( - markup, + """ + + interface {|target1:IBar|} + { + } + + public partial class {|target2:Bar|} : IBar + { + } + + public partial class {|target3:Bar|} + { + } + + """, LanguageNames.CSharp, testHost, itemOnLine2, @@ -1434,11 +1456,8 @@ public partial class {|target3:Bar|} [Theory, CombinatorialData] public Task TestEmptyFileSingleGlobalImportInOtherFile(TestHost testHost) { - var markup1 = @""; - var markup2 = @"{|target1:global using System;|}"; - return VerifyInMultipleDocumentsAsync( - markup1, markup2, LanguageNames.CSharp, + @"", @"{|target1:global using System;|}", LanguageNames.CSharp, testHost, new TestInheritanceMemberItem( lineNumber: 0, @@ -1451,13 +1470,12 @@ public Task TestEmptyFileSingleGlobalImportInOtherFile(TestHost testHost) [Theory, CombinatorialData] public Task TestEmptyFileMultipleGlobalImportInOtherFile(TestHost testHost) { - var markup1 = @""; - var markup2 = @" -{|target1:global using System;|} -{|target2:global using System.Collections;|}"; - return VerifyInMultipleDocumentsAsync( - markup1, markup2, LanguageNames.CSharp, + @"", """ + + {|target1:global using System;|} + {|target2:global using System.Collections;|} + """, LanguageNames.CSharp, testHost, new TestInheritanceMemberItem( lineNumber: 0, @@ -1476,12 +1494,11 @@ public Task TestEmptyFileMultipleGlobalImportInOtherFile(TestHost testHost) [Theory, CombinatorialData] public Task TestFileWithUsing_SingleGlobalImportInOtherFile(TestHost testHost) { - var markup1 = @" -using System.Collections;"; - var markup2 = @"{|target1:global using System;|}"; - return VerifyInMultipleDocumentsAsync( - markup1, markup2, LanguageNames.CSharp, + """ + + using System.Collections; + """, @"{|target1:global using System;|}", LanguageNames.CSharp, testHost, new TestInheritanceMemberItem( lineNumber: 1, @@ -1494,13 +1511,12 @@ public Task TestFileWithUsing_SingleGlobalImportInOtherFile(TestHost testHost) [Theory, CombinatorialData] public Task TestIgnoreGlobalImportFromSameFile(TestHost testHost) { - var markup1 = @" -global using System.Collections.Generic; -using System.Collections;"; - var markup2 = @"{|target1:global using System;|}"; - return VerifyInMultipleDocumentsAsync( - markup1, markup2, LanguageNames.CSharp, + """ + + global using System.Collections.Generic; + using System.Collections; + """, @"{|target1:global using System;|}", LanguageNames.CSharp, testHost, new TestInheritanceMemberItem( lineNumber: 1, @@ -1517,28 +1533,19 @@ public Task TestIgnoreGlobalImportFromSameFile(TestHost testHost) [Theory, CombinatorialData] public Task TestVisualBasicWithErrorBaseType(TestHost testHost) { - var markup = @" - Namespace MyNamespace - Public Class Bar - Implements SomethingNotExist - End Class - End Namespace"; - - return VerifyNoItemForDocumentAsync(markup, LanguageNames.VisualBasic, testHost); + return VerifyNoItemForDocumentAsync(""" + + Namespace MyNamespace + Public Class Bar + Implements SomethingNotExist + End Class + End Namespace + """, LanguageNames.VisualBasic, testHost); } [Theory, CombinatorialData] public Task TestVisualBasicReferencingMetadata(TestHost testHost) { - var markup = @" - Namespace MyNamespace - Public Class Bar - Implements System.Collections.IEnumerable - Public Function GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator - Throw New NotImplementedException() - End Function - End Class - End Namespace"; var itemForBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Class Bar", @@ -1555,18 +1562,22 @@ End Class relationship: InheritanceRelationship.ImplementedMember, inMetadata: true)]); - return VerifyInSingleDocumentAsync(markup, LanguageNames.VisualBasic, testHost, itemForBar, itemForGetEnumerator); + return VerifyInSingleDocumentAsync(""" + + Namespace MyNamespace + Public Class Bar + Implements System.Collections.IEnumerable + Public Function GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator + Throw New NotImplementedException() + End Function + End Class + End Namespace + """, LanguageNames.VisualBasic, testHost, itemForBar, itemForGetEnumerator); } [Theory, CombinatorialData] public Task TestVisualBasicClassImplementingInterface(TestHost testHost) { - var markup = @" - Interface {|target2:IBar|} - End Interface - Class {|target1:Bar|} - Implements IBar - End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", @@ -1584,7 +1595,14 @@ [new TargetInfo( relationship: InheritanceRelationship.ImplementedInterface)]); return VerifyInSingleDocumentAsync( - markup, + """ + + Interface {|target2:IBar|} + End Interface + Class {|target1:Bar|} + Implements IBar + End Class + """, LanguageNames.VisualBasic, testHost, itemForIBar, @@ -1594,13 +1612,6 @@ [new TargetInfo( [Theory, CombinatorialData] public Task TestVisualBasicInterfaceImplementingInterface(TestHost testHost) { - var markup = @" - Interface {|target2:IBar2|} - End Interface - Interface {|target1:IBar|} - Inherits IBar2 - End Interface"; - var itemForIBar2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar2", @@ -1616,19 +1627,19 @@ [new TargetInfo( targetSymbolDisplayName: "IBar2", locationTag: "target2", relationship: InheritanceRelationship.InheritedInterface)]); - return VerifyInSingleDocumentAsync(markup, LanguageNames.VisualBasic, testHost, itemForIBar2, itemForIBar); + return VerifyInSingleDocumentAsync(""" + + Interface {|target2:IBar2|} + End Interface + Interface {|target1:IBar|} + Inherits IBar2 + End Interface + """, LanguageNames.VisualBasic, testHost, itemForIBar2, itemForIBar); } [Theory, CombinatorialData] public Task TestVisualBasicClassInheritsClass(TestHost testHost) { - var markup = @" - Class {|target2:Bar2|} - End Class - Class {|target1:Bar|} - Inherits Bar2 - End Class"; - var itemForBar2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Class Bar2", @@ -1644,7 +1655,14 @@ [new TargetInfo( targetSymbolDisplayName: "Bar2", locationTag: "target2", relationship: InheritanceRelationship.BaseType)]); - return VerifyInSingleDocumentAsync(markup, LanguageNames.VisualBasic, testHost, itemForBar2, itemForBar); + return VerifyInSingleDocumentAsync(""" + + Class {|target2:Bar2|} + End Class + Class {|target1:Bar|} + Inherits Bar2 + End Class + """, LanguageNames.VisualBasic, testHost, itemForBar2, itemForBar); } [Theory] @@ -1658,23 +1676,24 @@ [new TargetInfo( [InlineData("Interface", TestHost.OutOfProcess)] public Task TestVisualBasicTypeWithoutBaseType(string typeName, TestHost testHost) { - var markup = $@" - {typeName} Bar - End {typeName}"; + return VerifyNoItemForDocumentAsync($""" - return VerifyNoItemForDocumentAsync(markup, LanguageNames.VisualBasic, testHost); + {typeName} Bar + End {typeName} + """, LanguageNames.VisualBasic, testHost); } [Theory, CombinatorialData] public Task TestVisualBasicMetadataInterface(TestHost testHost) { - var markup = @" - Imports System.Collections - Class Bar - Implements IEnumerable - End Class"; return VerifyInSingleDocumentAsync( - markup, + """ + + Imports System.Collections + Class Bar + Implements IEnumerable + End Class + """, LanguageNames.VisualBasic, testHost, new TestInheritanceMemberItem( @@ -1698,15 +1717,6 @@ Implements IEnumerable [Theory, CombinatorialData] public Task TestVisualBasicEventStatement(TestHost testHost) { - var markup = @" - Interface {|target2:IBar|} - Event {|target4:e|} As EventHandler - End Interface - Class {|target1:Bar|} - Implements IBar - Public Event {|target3:e|} As EventHandler Implements IBar.e - End Class"; - var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", @@ -1740,7 +1750,16 @@ [new TargetInfo( relationship: InheritanceRelationship.ImplementedMember)]); return VerifyInSingleDocumentAsync( - markup, + """ + + Interface {|target2:IBar|} + Event {|target4:e|} As EventHandler + End Interface + Class {|target1:Bar|} + Implements IBar + Public Event {|target3:e|} As EventHandler Implements IBar.e + End Class + """, LanguageNames.VisualBasic, testHost, itemForIBar, @@ -1752,15 +1771,6 @@ [new TargetInfo( [Theory, CombinatorialData] public Task TestVisualBasicEventBlock(TestHost testHost) { - var markup = @" - Interface {|target2:IBar|} - Event {|target4:e|} As EventHandler - End Interface - Class {|target1:Bar|} - Implements IBar - Public Custom Event {|target3:e|} As EventHandler Implements IBar.e - End Event - End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", @@ -1794,7 +1804,17 @@ [new TargetInfo( relationship: InheritanceRelationship.ImplementedMember)]); return VerifyInSingleDocumentAsync( - markup, + """ + + Interface {|target2:IBar|} + Event {|target4:e|} As EventHandler + End Interface + Class {|target1:Bar|} + Implements IBar + Public Custom Event {|target3:e|} As EventHandler Implements IBar.e + End Event + End Class + """, LanguageNames.VisualBasic, testHost, itemForIBar, @@ -1806,25 +1826,6 @@ [new TargetInfo( [Theory, CombinatorialData] public Task TestVisualBasicInterfaceMembers(TestHost testHost) { - var markup = @" - Interface {|target2:IBar|} - Property {|target4:Poo|} As Integer - Function {|target6:Foo|}() As Integer - End Interface - - Class {|target1:Bar|} - Implements IBar - Public Property {|target3:Poo|} As Integer Implements IBar.Poo - Get - Return 1 - End Get - Set(value As Integer) - End Set - End Property - Public Function {|target5:Foo|}() As Integer Implements IBar.Foo - Return 1 - End Function - End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", @@ -1874,7 +1875,27 @@ End Function relationship: InheritanceRelationship.ImplementedMember)]); return VerifyInSingleDocumentAsync( - markup, + """ + + Interface {|target2:IBar|} + Property {|target4:Poo|} As Integer + Function {|target6:Foo|}() As Integer + End Interface + + Class {|target1:Bar|} + Implements IBar + Public Property {|target3:Poo|} As Integer Implements IBar.Poo + Get + Return 1 + End Get + Set(value As Integer) + End Set + End Property + Public Function {|target5:Foo|}() As Integer Implements IBar.Foo + Return 1 + End Function + End Class + """, LanguageNames.VisualBasic, testHost, itemForIBar, @@ -1888,16 +1909,6 @@ End Function [Theory, CombinatorialData] public Task TestVisualBasicMustInheritClassMember(TestHost testHost) { - var markup = @" - MustInherit Class {|target2:Bar1|} - Public MustOverride Sub {|target4:Foo|}() - End Class - - Class {|target1:Bar|} - Inherits Bar1 - Public Overrides Sub {|target3:Foo|}() - End Sub - End Class"; var itemForBar1 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Class Bar1", @@ -1931,9 +1942,20 @@ End Sub relationship: InheritanceRelationship.OverriddenMember)]); return VerifyInSingleDocumentAsync( - markup, + """ + + MustInherit Class {|target2:Bar1|} + Public MustOverride Sub {|target4:Foo|}() + End Class + + Class {|target1:Bar|} + Inherits Bar1 + Public Overrides Sub {|target3:Foo|}() + End Sub + End Class + """, LanguageNames.VisualBasic, - testHost, + testHost, itemForBar1, itemForBar, itemForFooInBar1, @@ -1943,39 +1965,43 @@ End Sub [Theory, CombinatorialData] public Task TestVisualBasicOverrideMemberCanFindImplementingInterface(bool testDuplicate, TestHost testHost) { - var markup1 = @" - Interface {|target4:IBar|} - Sub {|target6:Foo|}() - End Interface - - Class {|target1:Bar1|} - Implements IBar - Public Overridable Sub {|target2:Foo|}() Implements IBar.Foo - End Sub - End Class - - Class {|target5:Bar2|} - Inherits Bar1 - Public Overrides Sub {|target3:Foo|}() - End Sub - End Class"; - - var markup2 = @" - Interface {|target4:IBar|} - Sub {|target6:Foo|}() - End Interface - - Class {|target1:Bar1|} - Implements IBar - Public Overridable Sub {|target2:Foo|}() Implements IBar.Foo - End Sub - End Class - - Class {|target5:Bar2|} - Inherits Bar1 - Public Overrides Sub {|target3:Foo|}() - End Sub - End Class"; + var markup1 = """ + + Interface {|target4:IBar|} + Sub {|target6:Foo|}() + End Interface + + Class {|target1:Bar1|} + Implements IBar + Public Overridable Sub {|target2:Foo|}() Implements IBar.Foo + End Sub + End Class + + Class {|target5:Bar2|} + Inherits Bar1 + Public Overrides Sub {|target3:Foo|}() + End Sub + End Class + """; + + var markup2 = """ + + Interface {|target4:IBar|} + Sub {|target6:Foo|}() + End Interface + + Class {|target1:Bar1|} + Implements IBar + Public Overridable Sub {|target2:Foo|}() Implements IBar.Foo + End Sub + End Class + + Class {|target5:Bar2|} + Inherits Bar1 + Public Overrides Sub {|target3:Foo|}() + End Sub + End Class + """; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", @@ -2082,24 +2108,6 @@ End Sub [Theory, CombinatorialData] public Task TestVisualBasicFindGenericsBaseType(TestHost testHost) { - var markup = @" - Public Interface {|target5:IBar|}(Of T) - Sub {|target6:Foo|}() - End Interface - - Public Class {|target1:Bar|} - Implements IBar(Of Integer) - Implements IBar(Of String) - - Public Sub {|target3:Foo|}() Implements IBar(Of Integer).Foo - Throw New NotImplementedException() - End Sub - - Private Sub {|target4:IBar_Foo|}() Implements IBar(Of String).Foo - Throw New NotImplementedException() - End Sub - End Class"; - var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar(Of T)", @@ -2148,7 +2156,25 @@ End Sub relationship: InheritanceRelationship.ImplementedMember)]); return VerifyInSingleDocumentAsync( - markup, + """ + + Public Interface {|target5:IBar|}(Of T) + Sub {|target6:Foo|}() + End Interface + + Public Class {|target1:Bar|} + Implements IBar(Of Integer) + Implements IBar(Of String) + + Public Sub {|target3:Foo|}() Implements IBar(Of Integer).Foo + Throw New NotImplementedException() + End Sub + + Private Sub {|target4:IBar_Foo|}() Implements IBar(Of String).Foo + Throw New NotImplementedException() + End Sub + End Class + """, LanguageNames.VisualBasic, testHost, itemForIBar, @@ -2163,23 +2189,6 @@ End Sub [Theory, CombinatorialData] public Task TestCSharpProjectReferencingVisualBasicProject(TestHost testHost) { - var markup1 = @" - using MyNamespace; - namespace BarNs - { - public class {|target2:Bar|} : IBar - { - public void {|target4:Foo|}() { } - } - }"; - - var markup2 = @" - Namespace MyNamespace - Public Interface {|target1:IBar|} - Sub {|target3:Foo|}() - End Interface - End Namespace"; - var itemForBar = new TestInheritanceMemberItem( lineNumber: 5, memberName: "class Bar", @@ -2213,8 +2222,25 @@ End Interface relationship: InheritanceRelationship.ImplementingMember)]); return VerifyInDifferentProjectsAsync( - (markup1, LanguageNames.CSharp), - (markup2, LanguageNames.VisualBasic), + (""" + + using MyNamespace; + namespace BarNs + { + public class {|target2:Bar|} : IBar + { + public void {|target4:Foo|}() { } + } + } + """, LanguageNames.CSharp), + (""" + + Namespace MyNamespace + Public Interface {|target1:IBar|} + Sub {|target3:Foo|}() + End Interface + End Namespace + """, LanguageNames.VisualBasic), [itemForBar, itemForFooInMarkup1], [itemForIBar, itemForFooInMarkup2], testHost); @@ -2223,25 +2249,6 @@ End Interface [Theory, CombinatorialData] public Task TestVisualBasicProjectReferencingCSharpProject(TestHost testHost) { - var markup1 = @" - Imports BarNs - Namespace MyNamespace - Public Class {|target2:Bar44|} - Implements IBar - - Public Sub {|target4:Foo|}() Implements IBar.Foo - End Sub - End Class - End Namespace"; - - var markup2 = @" - namespace BarNs - { - public interface {|target1:IBar|} - { - void {|target3:Foo|}(); - } - }"; var itemForProjectImports = new TestInheritanceMemberItem( lineNumber: 2, @@ -2286,8 +2293,28 @@ public interface {|target1:IBar|} relationship: InheritanceRelationship.ImplementingMember)]); return VerifyInDifferentProjectsAsync( - (markup1, LanguageNames.VisualBasic), - (markup2, LanguageNames.CSharp), + (""" + + Imports BarNs + Namespace MyNamespace + Public Class {|target2:Bar44|} + Implements IBar + + Public Sub {|target4:Foo|}() Implements IBar.Foo + End Sub + End Class + End Namespace + """, LanguageNames.VisualBasic), + (""" + + namespace BarNs + { + public interface {|target1:IBar|} + { + void {|target3:Foo|}(); + } + } + """, LanguageNames.CSharp), [itemForProjectImports, itemForBar44, itemForFooInMarkup1], [itemForIBar, itemForFooInMarkup2], testHost); @@ -2296,25 +2323,6 @@ public interface {|target1:IBar|} [Theory, CombinatorialData] public Task TestSameNameSymbolInDifferentLanguageProjects(TestHost testHost) { - var markup1 = @" - using MyNamespace; - namespace BarNs - { - public class {|target1:Bar|} : IBar - { - } - }"; - - var markup2 = @" - Namespace MyNamespace - Public Interface {|target2:IBar|} - End Interface - - Public Class {|target3:Bar|} - Implements IBar - End Class - End Namespace"; - var itemForBarInMarkup1 = new TestInheritanceMemberItem( lineNumber: 5, memberName: "class Bar", @@ -2351,8 +2359,27 @@ End Class relationship: InheritanceRelationship.ImplementedInterface)]); return VerifyInDifferentProjectsAsync( - (markup1, LanguageNames.CSharp), - (markup2, LanguageNames.VisualBasic), + (""" + + using MyNamespace; + namespace BarNs + { + public class {|target1:Bar|} : IBar + { + } + } + """, LanguageNames.CSharp), + (""" + + Namespace MyNamespace + Public Interface {|target2:IBar|} + End Interface + + Public Class {|target3:Bar|} + Implements IBar + End Class + End Namespace + """, LanguageNames.VisualBasic), [itemForBarInMarkup1], [itemForIBar, itemForBarInMarkup2], testHost); @@ -2361,25 +2388,6 @@ End Class [Theory, CombinatorialData] public Task TestSameNameSymbolInSameLanguageProjects(TestHost testHost) { - var markup1 = @" - using MyNamespace; - namespace BarNs - { - public class {|target1:Bar|} : IBar - { - } - }"; - - var markup2 = @" - namespace MyNamespace { - public interface {|target2:IBar|} - {} - - public class {|target3:Bar|} - : IBar - {} - }"; - var itemForBarInMarkup1 = new TestInheritanceMemberItem( lineNumber: 5, memberName: "class Bar", @@ -2416,72 +2424,93 @@ public class {|target3:Bar|} relationship: InheritanceRelationship.ImplementedInterface)]); return VerifyInDifferentProjectsAsync( - (markup1, LanguageNames.CSharp), - (markup2, LanguageNames.CSharp), + (""" + + using MyNamespace; + namespace BarNs + { + public class {|target1:Bar|} : IBar + { + } + } + """, LanguageNames.CSharp), + (""" + + namespace MyNamespace { + public interface {|target2:IBar|} + {} + + public class {|target3:Bar|} + : IBar + {} + } + """, LanguageNames.CSharp), [itemForBarInMarkup1], [itemForIBar, itemForBarInMarkup2], testHost); } [Theory, CombinatorialData] - public async Task TestHiddenLocationSymbol(TestHost testHost) - { - await VerifyNoItemForDocumentAsync(@" -public class {|target2:B|} : C -{ -} + public Task TestHiddenLocationSymbol(TestHost testHost) + => VerifyNoItemForDocumentAsync(""" -#line hidden -public class {|target1:C|} -{ -}", + public class {|target2:B|} : C + { + } + + #line hidden + public class {|target1:C|} + { + } + """, LanguageNames.CSharp, testHost); - } [Theory, CombinatorialData] [WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1988154/")] public async Task TestNoResultOutsideSpan(TestHost testHost) { // 1. If the searching span is the empty body, nothing should be returned. - var noResultCode = $@" -public class B : C -{{ -{{|{SearchAreaTag}: + await VerifyNoItemForDocumentAsync($$""" + public class B : C + { + + {|{{SearchAreaTag}}: -|}} -}} + |} -public class C -{{ -}}"; + } - await VerifyNoItemForDocumentAsync(noResultCode, + public class C + { + } + """, LanguageNames.CSharp, testHost); // 2. If the searching span contains the identifier, correct result should be returned. - var correctSearchingCode = $@" -public class {{|{SearchAreaTag}:B|}} : C -{{ + await VerifyInSingleDocumentAsync($$""" + public class {|{{SearchAreaTag}}:B|} : C + { -}} -public class {{|target:C|}} -{{ -}}"; - await VerifyInSingleDocumentAsync(correctSearchingCode, + } + + public class {|target:C|} + { + } + """, LanguageNames.CSharp, testHost, memberItems: [new TestInheritanceMemberItem( diff --git a/src/EditorFeatures/Test/LanguageServer/VSTypeScriptHandlerTests.cs b/src/EditorFeatures/Test/LanguageServer/VSTypeScriptHandlerTests.cs index 0e3199cbaec88..911342776de1b 100644 --- a/src/EditorFeatures/Test/LanguageServer/VSTypeScriptHandlerTests.cs +++ b/src/EditorFeatures/Test/LanguageServer/VSTypeScriptHandlerTests.cs @@ -7,6 +7,7 @@ using System.Composition; using System.IO; using System.Linq; +using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; @@ -22,7 +23,6 @@ using StreamJsonRpc; using Xunit; using Xunit.Abstractions; -using System.Text.Json.Serialization; namespace Microsoft.CodeAnalysis.Editor.UnitTests.LanguageServer; @@ -40,11 +40,13 @@ public VSTypeScriptHandlerTests(ITestOutputHelper testOutputHelper) : base(testO public async Task TestExternalAccessTypeScriptHandlerInvoked() { var workspaceXml = -@$" - - - -"; + $""" + + + + + + """; await using var testLspServer = await CreateTsTestLspServerAsync(workspaceXml); @@ -59,11 +61,13 @@ public async Task TestExternalAccessTypeScriptHandlerInvoked() public async Task TestRoslynTypeScriptHandlerInvoked() { var workspaceXml = -@$" - - - -"; + $""" + + + + + + """; await using var testLspServer = await CreateTsTestLspServerAsync(workspaceXml, new InitializationOptions()); @@ -81,11 +85,13 @@ public async Task TestRoslynTypeScriptHandlerInvoked() public async Task TestGetSimplifierOptionsOnTypeScriptDocument() { var workspaceXml = -@$" - - - -"; + $""" + + + + + + """; await using var testLspServer = await CreateTsTestLspServerAsync(workspaceXml); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); diff --git a/src/EditorFeatures/Test/MetadataAsSource/DocCommentFormatterTests.cs b/src/EditorFeatures/Test/MetadataAsSource/DocCommentFormatterTests.cs index 00d2d475f6394..c281e1e6aee93 100644 --- a/src/EditorFeatures/Test/MetadataAsSource/DocCommentFormatterTests.cs +++ b/src/EditorFeatures/Test/MetadataAsSource/DocCommentFormatterTests.cs @@ -37,81 +37,52 @@ private void TestFormat(string docCommentXmlFragment, string expectedCSharp, str [Fact] public void Summary() { - var comment = "This is a summary."; - - var expected = -$@"{FeaturesResources.Summary_colon} - This is a summary."; - - TestFormat(comment, expected); + TestFormat("This is a summary.", $@"{FeaturesResources.Summary_colon} + This is a summary."); } [Fact] public void Wrapping1() { - var comment = "I am the very model of a modern major general. This is a very long comment. And getting longer by the minute."; - - var expected = -$@"{FeaturesResources.Summary_colon} + TestFormat("I am the very model of a modern major general. This is a very long comment. And getting longer by the minute.", $@"{FeaturesResources.Summary_colon} I am the very model of a modern major general. This is a very long comment. And - getting longer by the minute."; - - TestFormat(comment, expected); + getting longer by the minute."); } [Fact] public void Wrapping2() { - var comment = "I amtheverymodelofamodernmajorgeneral.Thisisaverylongcomment.Andgettinglongerbythe minute."; - var expected = -$@"{FeaturesResources.Summary_colon} + TestFormat("I amtheverymodelofamodernmajorgeneral.Thisisaverylongcomment.Andgettinglongerbythe minute.", $@"{FeaturesResources.Summary_colon} I amtheverymodelofamodernmajorgeneral.Thisisaverylongcomment.Andgettinglongerbythe - minute."; - - TestFormat(comment, expected); + minute."); } [Fact] public void Exception() { - var comment = @"throws NotImplementedException"; - - var expected = -$@"{WorkspacesResources.Exceptions_colon} + TestFormat(@"throws NotImplementedException", $@"{WorkspacesResources.Exceptions_colon} T:System.NotImplementedException: - throws NotImplementedException"; - - TestFormat(comment, expected); + throws NotImplementedException"); } [Fact] public void MultipleExceptionTags() { - var comment = -@"throws NotImplementedException -throws InvalidOperationException"; - - var expected = -$@"{WorkspacesResources.Exceptions_colon} + TestFormat(@"throws NotImplementedException +throws InvalidOperationException", $@"{WorkspacesResources.Exceptions_colon} T:System.NotImplementedException: throws NotImplementedException T:System.InvalidOperationException: - throws InvalidOperationException"; - - TestFormat(comment, expected); + throws InvalidOperationException"); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530760")] public void MultipleExceptionTagsWithSameType() { - var comment = -@"throws NotImplementedException for reason X + TestFormat(@"throws NotImplementedException for reason X throws InvalidOperationException -also throws NotImplementedException for reason Y"; - - var expected = -$@"{WorkspacesResources.Exceptions_colon} +also throws NotImplementedException for reason Y", $@"{WorkspacesResources.Exceptions_colon} T:System.NotImplementedException: throws NotImplementedException for reason X @@ -119,45 +90,29 @@ public void MultipleExceptionTagsWithSameType() also throws NotImplementedException for reason Y T:System.InvalidOperationException: - throws InvalidOperationException"; - - TestFormat(comment, expected); + throws InvalidOperationException"); } [Fact] public void Returns() { - var comment = @"A string is returned"; - - var expected = -$@"{FeaturesResources.Returns_colon} - A string is returned"; - - TestFormat(comment, expected); + TestFormat(@"A string is returned", $@"{FeaturesResources.Returns_colon} + A string is returned"); } [Fact] public void Value() { - var comment = @"A string value"; - - var expected = -$@"{FeaturesResources.Value_colon} - A string value"; - - TestFormat(comment, expected); + TestFormat(@"A string value", $@"{FeaturesResources.Value_colon} + A string value"); } [Fact] public void SummaryAndParams() { - var comment = -@"This is the summary. + TestFormat(@"This is the summary. The param named 'a' -The param named 'b'"; - - var expected = -$@"{FeaturesResources.Summary_colon} +The param named 'b'", $@"{FeaturesResources.Summary_colon} This is the summary. {FeaturesResources.Parameters_colon} @@ -165,34 +120,25 @@ This is the summary. The param named 'a' b: - The param named 'b'"; - - TestFormat(comment, expected); + The param named 'b'"); } [Fact] public void TypeParameters() { - var comment = -@"The type param named 'T' -The type param named 'U'"; - - var expected = -$@"{FeaturesResources.Type_parameters_colon} + TestFormat(@"The type param named 'T' +The type param named 'U'", $@"{FeaturesResources.Type_parameters_colon} T: The type param named 'T' U: - The type param named 'U'"; - - TestFormat(comment, expected); + The type param named 'U'"); } [Fact] public void FormatEverything() { - var comment = -@" + TestFormat(@" This is a summary of something. The param named 'a'. @@ -206,10 +152,7 @@ This is a summary of something. Thrown for an unknown reason Thrown when blah blah blah -This doc comment is really not very remarkable."; - - var expected = -$@"{FeaturesResources.Summary_colon} +This doc comment is really not very remarkable.", $@"{FeaturesResources.Summary_colon} This is a summary of something. {FeaturesResources.Parameters_colon} @@ -246,8 +189,6 @@ This has no value. Thrown when blah blah blah {FeaturesResources.Remarks_colon} - This doc comment is really not very remarkable."; - - TestFormat(comment, expected); + This doc comment is really not very remarkable."); } } diff --git a/src/EditorFeatures/Test/MetadataAsSource/MetadataAsSourceTests.CSharp.cs b/src/EditorFeatures/Test/MetadataAsSource/MetadataAsSourceTests.CSharp.cs index e41a7710f5525..fb2eb578b52e8 100644 --- a/src/EditorFeatures/Test/MetadataAsSource/MetadataAsSourceTests.CSharp.cs +++ b/src/EditorFeatures/Test/MetadataAsSource/MetadataAsSourceTests.CSharp.cs @@ -24,25 +24,19 @@ public void ExtractXMLFromDocComment() /// I am the very model of a modern major general. /// """; + var extractedXMLFragment = DocumentationCommentUtilities.ExtractXMLFragment(docCommentText, "///"); - var expectedXMLFragment = """ + Assert.Equal(""" I am the very model of a modern major general. - """; - - var extractedXMLFragment = DocumentationCommentUtilities.ExtractXMLFragment(docCommentText, "///"); - - Assert.Equal(expectedXMLFragment, extractedXMLFragment); + """, extractedXMLFragment); } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/42986")] public async Task TestNativeInteger(bool signaturesOnly) { - var metadataSource = "public class C { public nint i; public nuint i2; }"; - var symbolName = "C"; - var expected = signaturesOnly switch { true => $$""" @@ -80,22 +74,12 @@ public class [|C|] """, }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", expected: expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync("public class C { public nint i; public nuint i2; }", "C", LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", expected: expected, signaturesOnly: signaturesOnly); } [Theory, CombinatorialData] public async Task TestInitOnlyProperty(bool signaturesOnly) { - var metadataSource = """ - public class C { public int Property { get; init; } } - namespace System.Runtime.CompilerServices - { - public sealed class IsExternalInit { } - } - - """; - var symbolName = "C"; - var expected = signaturesOnly switch { true => $$""" @@ -130,15 +114,19 @@ public class [|C|] """, }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", expected: expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync(""" + public class C { public int Property { get; init; } } + namespace System.Runtime.CompilerServices + { + public sealed class IsExternalInit { } + } + + """, "C", LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", expected: expected, signaturesOnly: signaturesOnly); } [Theory, CombinatorialData] public async Task TestTupleWithNames(bool signaturesOnly) { - var metadataSource = "public class C { public (int a, int b) t; }"; - var symbolName = "C"; - var expected = signaturesOnly switch { true => $$""" @@ -180,7 +168,7 @@ public class [|C|] """, }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, expected: expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync("public class C { public (int a, int b) t; }", "C", LanguageNames.CSharp, expected: expected, signaturesOnly: signaturesOnly); } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/26605")] @@ -410,9 +398,6 @@ internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int [Theory, CombinatorialData] public async Task TestExtendedPartialMethod1(bool signaturesOnly) { - var metadataSource = "public partial class C { public partial void F(); public partial void F() { } }"; - var symbolName = "C"; - var expected = signaturesOnly switch { true => $$""" @@ -449,16 +434,13 @@ public void F() """, }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", expected: expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync("public partial class C { public partial void F(); public partial void F() { } }", "C", LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", expected: expected, signaturesOnly: signaturesOnly); } [Theory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/44566")] public async Task TestRecordType(bool signaturesOnly) { - var metadataSource = "public record R;"; - var symbolName = "R"; - var expected = signaturesOnly switch { true => $$""" @@ -517,7 +499,7 @@ public record [|R|]; """, }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, expected: expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync("public record R;", "R", LanguageNames.CSharp, expected: expected, signaturesOnly: signaturesOnly); } /// @@ -527,25 +509,6 @@ public record [|R|]; [WorkItem("https://github.com/dotnet/roslyn/issues/42986")] public async Task TestCheckedOperators(bool signaturesOnly) { - var metadataSource = """ - - public class C - { - public static explicit operator string(C x) => throw new System.Exception(); - - public static explicit operator checked string(C x) => throw new System.Exception(); - - public static C operator -(C x) => throw new System.Exception(); - - public static C operator checked -(C x) => throw new System.Exception(); - - public static C operator +(C x, C y) => throw new System.Exception(); - - public static C operator checked +(C x, C y) => throw new System.Exception(); - } - """; - var symbolName = "C"; - var expected = signaturesOnly switch { true => $$""" @@ -616,29 +579,28 @@ public static explicit operator checked string(C x) """, }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", expected: expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync(""" + + public class C + { + public static explicit operator string(C x) => throw new System.Exception(); + + public static explicit operator checked string(C x) => throw new System.Exception(); + + public static C operator -(C x) => throw new System.Exception(); + + public static C operator checked -(C x) => throw new System.Exception(); + + public static C operator +(C x, C y) => throw new System.Exception(); + + public static C operator checked +(C x, C y) => throw new System.Exception(); + } + """, "C", LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", expected: expected, signaturesOnly: signaturesOnly); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60567")] public async Task TestStaticInterfaceMembers() { - var metadataSource = """ - - interface I where T : I - { - static abstract T P { get; set; } - static abstract event System.Action E; - static abstract void M(); - static void NonAbstract() { } - static abstract T operator +(T l, T r); - static abstract bool operator ==(T l, T r); - static abstract bool operator !=(T l, T r); - static abstract implicit operator T(string s); - static abstract explicit operator string(T t); - } - """; - var symbolName = "I`1.M"; - var expected = $$""" #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {{CodeAnalysisResources.InMemoryAssembly}} @@ -664,15 +626,26 @@ internal interface I where T : I } """; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", expected: expected, signaturesOnly: true, metadataCommonReferences: "CommonReferencesNet6"); + await GenerateAndVerifySourceAsync(""" + + interface I where T : I + { + static abstract T P { get; set; } + static abstract event System.Action E; + static abstract void M(); + static void NonAbstract() { } + static abstract T operator +(T l, T r); + static abstract bool operator ==(T l, T r); + static abstract bool operator !=(T l, T r); + static abstract implicit operator T(string s); + static abstract explicit operator string(T t); + } + """, "I`1.M", LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", expected: expected, signaturesOnly: true, metadataCommonReferences: "CommonReferencesNet6"); } [Theory, CombinatorialData] public async Task UnsignedRightShift(bool signaturesOnly) { - var metadataSource = "public class C { public static C operator >>>(C x, int y) => x; }"; - var symbolName = "C.op_UnsignedRightShift"; - var expected = signaturesOnly switch { true => $$""" @@ -710,7 +683,7 @@ public class C """, }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, expected: expected, signaturesOnly: signaturesOnly, languageVersion: "Preview", metadataLanguageVersion: "Preview"); + await GenerateAndVerifySourceAsync("public class C { public static C operator >>>(C x, int y) => x; }", "C.op_UnsignedRightShift", LanguageNames.CSharp, expected: expected, signaturesOnly: signaturesOnly, languageVersion: "Preview", metadataLanguageVersion: "Preview"); } private const string CompilerFeatureRequiredAttribute = """ @@ -956,28 +929,6 @@ public class C [Theory, CombinatorialData] public async Task TestRequiredProperty(bool signaturesOnly) { - var metadataSource = """ - public class C - { - public required int Property { get; set; } - public required int Field; - } - namespace System.Runtime.CompilerServices - { - public sealed class RequiredMemberAttribute : Attribute { } - public sealed class CompilerFeatureRequiredAttribute : Attribute - { - public CompilerFeatureRequiredAttribute(string featureName) - { - FeatureName = featureName; - } - public string FeatureName { get; } - public bool IsOptional { get; set; } - } - } - - """; - var symbolName = "C"; // ICSharpDecompiler does not yet support decoding required members nicely var expected = signaturesOnly switch @@ -1018,28 +969,32 @@ public class [|C|] """, }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", expected: expected, signaturesOnly: signaturesOnly); - } - - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76676")] - public async Task TestParamsScoped() - { - var metadataSource = """ + await GenerateAndVerifySourceAsync(""" public class C { - public void M(params scoped System.ReadOnlySpan x) { } + public required int Property { get; set; } + public required int Field; } - - namespace System + namespace System.Runtime.CompilerServices { - public readonly ref struct ReadOnlySpan + public sealed class RequiredMemberAttribute : Attribute { } + public sealed class CompilerFeatureRequiredAttribute : Attribute { + public CompilerFeatureRequiredAttribute(string featureName) + { + FeatureName = featureName; + } + public string FeatureName { get; } + public bool IsOptional { get; set; } } } - """; - var symbolName = "C"; + """, "C", LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", expected: expected, signaturesOnly: signaturesOnly); + } + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76676")] + public async Task TestParamsScoped() + { var expected = $$""" #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {{CodeAnalysisResources.InMemoryAssembly}} @@ -1056,8 +1011,20 @@ public class [|C|] """; await GenerateAndVerifySourceAsync( - metadataSource, - symbolName, + """ + public class C + { + public void M(params scoped System.ReadOnlySpan x) { } + } + + namespace System + { + public readonly ref struct ReadOnlySpan + { + } + } + """, + "C", LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", diff --git a/src/EditorFeatures/Test/MetadataAsSource/MetadataAsSourceTests.VisualBasic.cs b/src/EditorFeatures/Test/MetadataAsSource/MetadataAsSourceTests.VisualBasic.cs index fe95925bdf2e5..043b2f1bf0c37 100644 --- a/src/EditorFeatures/Test/MetadataAsSource/MetadataAsSourceTests.VisualBasic.cs +++ b/src/EditorFeatures/Test/MetadataAsSource/MetadataAsSourceTests.VisualBasic.cs @@ -20,75 +20,75 @@ public class VisualBasic : AbstractMetadataAsSourceTests [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530123")] public async Task TestGenerateTypeInModule(bool signaturesOnly) { - var metadataSource = @" -Module M - Public Class D - End Class -End Module"; - var expected = signaturesOnly switch { - true => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" -' {CodeAnalysisResources.InMemoryAssembly} -#End Region - -Friend Module M - Public Class [|D|] - Public Sub New() - End Class -End Module", - false => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -// {FeaturesResources.location_unknown} -// Decompiled with ICSharpCode.Decompiler {ICSharpCodeDecompilerVersion} -#endregion - -using Microsoft.VisualBasic.CompilerServices; - -[StandardModule] -internal sealed class M -{{ - public class [|D|] - {{ - }} -}} -#if false // {FeaturesResources.Decompilation_log} -{string.Format(FeaturesResources._0_items_in_cache, 9)} ------------------- -{string.Format(FeaturesResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} -{string.Format(FeaturesResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} -{string.Format(FeaturesResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} ------------------- -{string.Format(FeaturesResources.Resolve_0, "Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} -{string.Format(FeaturesResources.Found_single_assembly_0, "Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} -{string.Format(FeaturesResources.Load_from_0, "Microsoft.VisualBasic (net461)")} -#endif", + true => $""" + #Region "{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" + ' {CodeAnalysisResources.InMemoryAssembly} + #End Region + + Friend Module M + Public Class [|D|] + Public Sub New() + End Class + End Module + """, + false => $$""" + #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + // {{FeaturesResources.location_unknown}} + // Decompiled with ICSharpCode.Decompiler {{ICSharpCodeDecompilerVersion}} + #endregion + + using Microsoft.VisualBasic.CompilerServices; + + [StandardModule] + internal sealed class M + { + public class [|D|] + { + } + } + #if false // {{FeaturesResources.Decompilation_log}} + {{string.Format(FeaturesResources._0_items_in_cache, 9)}} + ------------------ + {{string.Format(FeaturesResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")}} + {{string.Format(FeaturesResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")}} + {{string.Format(FeaturesResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")}} + ------------------ + {{string.Format(FeaturesResources.Resolve_0, "Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")}} + {{string.Format(FeaturesResources.Found_single_assembly_0, "Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")}} + {{string.Format(FeaturesResources.Load_from_0, "Microsoft.VisualBasic (net461)")}} + #endif + """, }; - await GenerateAndVerifySourceAsync(metadataSource, "M+D", LanguageNames.VisualBasic, expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync(""" + Module M + Public Class D + End Class + End Module + """, "M+D", LanguageNames.VisualBasic, expected, signaturesOnly: signaturesOnly); } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/60253")] - public async Task TestReferenceAssembly(bool signaturesOnly) - { - var metadataSource = @" - -Module M - Public Class D - End Class -End Module"; - - var expected = $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" -' {CodeAnalysisResources.InMemoryAssembly} -#End Region - -Friend Module M - Public Class [|D|] - Public Sub New() - End Class -End Module"; - - await GenerateAndVerifySourceAsync(metadataSource, "M+D", LanguageNames.VisualBasic, expected, signaturesOnly: signaturesOnly); - } + public Task TestReferenceAssembly(bool signaturesOnly) + => GenerateAndVerifySourceAsync(""" + + Module M + Public Class D + End Class + End Module + """, "M+D", LanguageNames.VisualBasic, $""" + #Region "{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" + ' {CodeAnalysisResources.InMemoryAssembly} + #End Region + + Friend Module M + Public Class [|D|] + Public Sub New() + End Class + End Module + """, signaturesOnly: signaturesOnly); // This test depends on the version of mscorlib used by the TestWorkspace and may // change in the future @@ -99,78 +99,82 @@ public async Task BracketedIdentifierSimplificationTest(bool signaturesOnly) { var expected = signaturesOnly switch { - true => $@"#Region ""{FeaturesResources.Assembly} mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" -' mscorlib.v4_6_1038_0.dll -#End Region - -Imports System.Runtime.InteropServices - -Namespace System - - Public NotInheritable Class [|ObsoleteAttribute|] - Inherits Attribute - - Public Sub New() - Public Sub New(message As String) - Public Sub New(message As String, [error] As Boolean) - - Public ReadOnly Property Message As String - Public ReadOnly Property IsError As Boolean - End Class -End Namespace", - false => $@"#region {FeaturesResources.Assembly} mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 -// {FeaturesResources.location_unknown} -// Decompiled with ICSharpCode.Decompiler {ICSharpCodeDecompilerVersion} -#endregion - -using System.Runtime.InteropServices; - -namespace System; - -[Serializable] -[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] -[ComVisible(true)] -public sealed class [|ObsoleteAttribute|] : Attribute -{{ - public string Message - {{ - get - {{ - /*Error: Empty body found. Decompiled assembly might be a reference assembly.*/ - ; - }} - }} - - public bool IsError - {{ - get - {{ - /*Error: Empty body found. Decompiled assembly might be a reference assembly.*/ - ; - }} - }} - - public ObsoleteAttribute() - {{ - /*Error: Empty body found. Decompiled assembly might be a reference assembly.*/ - ; - }} - - public ObsoleteAttribute(string message) - {{ - /*Error: Empty body found. Decompiled assembly might be a reference assembly.*/ - ; - }} - - public ObsoleteAttribute(string message, bool error) - {{ - /*Error: Empty body found. Decompiled assembly might be a reference assembly.*/ - ; - }} -}} -#if false // {FeaturesResources.Decompilation_log} -{string.Format(FeaturesResources._0_items_in_cache, 9)} -#endif", + true => $""" + #Region "{FeaturesResources.Assembly} mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + ' mscorlib.v4_6_1038_0.dll + #End Region + + Imports System.Runtime.InteropServices + + Namespace System + + Public NotInheritable Class [|ObsoleteAttribute|] + Inherits Attribute + + Public Sub New() + Public Sub New(message As String) + Public Sub New(message As String, [error] As Boolean) + + Public ReadOnly Property Message As String + Public ReadOnly Property IsError As Boolean + End Class + End Namespace + """, + false => $$""" + #region {{FeaturesResources.Assembly}} mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + // {{FeaturesResources.location_unknown}} + // Decompiled with ICSharpCode.Decompiler {{ICSharpCodeDecompilerVersion}} + #endregion + + using System.Runtime.InteropServices; + + namespace System; + + [Serializable] + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] + [ComVisible(true)] + public sealed class [|ObsoleteAttribute|] : Attribute + { + public string Message + { + get + { + /*Error: Empty body found. Decompiled assembly might be a reference assembly.*/ + ; + } + } + + public bool IsError + { + get + { + /*Error: Empty body found. Decompiled assembly might be a reference assembly.*/ + ; + } + } + + public ObsoleteAttribute() + { + /*Error: Empty body found. Decompiled assembly might be a reference assembly.*/ + ; + } + + public ObsoleteAttribute(string message) + { + /*Error: Empty body found. Decompiled assembly might be a reference assembly.*/ + ; + } + + public ObsoleteAttribute(string message, bool error) + { + /*Error: Empty body found. Decompiled assembly might be a reference assembly.*/ + ; + } + } + #if false // {{FeaturesResources.Decompilation_log}} + {{string.Format(FeaturesResources._0_items_in_cache, 9)}} + #endif + """, }; using var context = TestContext.Create(LanguageNames.VisualBasic); @@ -180,17 +184,18 @@ public ObsoleteAttribute(string message, bool error) [Fact] public void ExtractXMLFromDocComment() { - var docCommentText = @"''' -''' I am the very model of a modern major general. -''' "; - - var expectedXMLFragment = @" - I am the very model of a modern major general. - "; - + var docCommentText = """ + ''' + ''' I am the very model of a modern major general. + ''' + """; var extractedXMLFragment = DocumentationCommentUtilities.ExtractXMLFragment(docCommentText, "'''"); - Assert.Equal(expectedXMLFragment, extractedXMLFragment); + Assert.Equal(""" + + I am the very model of a modern major general. + + """, extractedXMLFragment); } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/26605")] @@ -200,214 +205,218 @@ public async Task TestValueTuple(bool signaturesOnly) var expected = signaturesOnly switch { - true => $@"#Region ""{FeaturesResources.Assembly} System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51"" -' System.ValueTuple (net461) -#End Region - -Imports System.Collections - -Namespace System - Public Structure [|ValueTuple|] - Implements IEquatable(Of ValueTuple), IStructuralEquatable, IStructuralComparable, IComparable, IComparable(Of ValueTuple), ITupleInternal - - Public Shared Function Create() As ValueTuple - Public Shared Function Create(Of T1)(item1 As T1) As ValueTuple(Of T1) - Public Shared Function Create(Of T1, T2)(item1 As T1, item2 As T2) As (T1, T2) - Public Shared Function Create(Of T1, T2, T3)(item1 As T1, item2 As T2, item3 As T3) As (T1, T2, T3) - Public Shared Function Create(Of T1, T2, T3, T4)(item1 As T1, item2 As T2, item3 As T3, item4 As T4) As (T1, T2, T3, T4) - Public Shared Function Create(Of T1, T2, T3, T4, T5)(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5) As (T1, T2, T3, T4, T5) - Public Shared Function Create(Of T1, T2, T3, T4, T5, T6)(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5, item6 As T6) As (T1, T2, T3, T4, T5, T6) - Public Shared Function Create(Of T1, T2, T3, T4, T5, T6, T7)(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5, item6 As T6, item7 As T7) As (T1, T2, T3, T4, T5, T6, T7) - Public Shared Function Create(Of T1, T2, T3, T4, T5, T6, T7, T8)(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5, item6 As T6, item7 As T7, item8 As T8) As (T1, T2, T3, T4, T5, T6, T7, T8) - Public Overrides Function Equals(obj As Object) As Boolean - Public Function Equals(other As ValueTuple) As Boolean - Public Function CompareTo(other As ValueTuple) As Integer - Public Overrides Function GetHashCode() As Integer - Public Overrides Function ToString() As String - End Structure -End Namespace", - false => $@"#region {FeaturesResources.Assembly} System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51 -// {FeaturesResources.location_unknown} -// Decompiled with ICSharpCode.Decompiler {ICSharpCodeDecompilerVersion} -#endregion - -using System.Collections; -using System.Numerics.Hashing; -using System.Runtime.InteropServices; - -namespace System; - -[StructLayout(LayoutKind.Sequential, Size = 1)] -public struct [|ValueTuple|] : IEquatable, IStructuralEquatable, IStructuralComparable, IComparable, IComparable, ITupleInternal -{{ - int ITupleInternal.Size => 0; - - public override bool Equals(object obj) - {{ - return obj is ValueTuple; - }} - - public bool Equals(ValueTuple other) - {{ - return true; - }} - - bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) - {{ - return other is ValueTuple; - }} - - int IComparable.CompareTo(object other) - {{ - if (other == null) - {{ - return 1; - }} - - if (!(other is ValueTuple)) - {{ - throw new ArgumentException(System.SR.ArgumentException_ValueTupleIncorrectType, ""other""); - }} - - return 0; - }} - - public int CompareTo(ValueTuple other) - {{ - return 0; - }} - - int IStructuralComparable.CompareTo(object other, IComparer comparer) - {{ - if (other == null) - {{ - return 1; - }} - - if (!(other is ValueTuple)) - {{ - throw new ArgumentException(System.SR.ArgumentException_ValueTupleIncorrectType, ""other""); - }} - - return 0; - }} - - public override int GetHashCode() - {{ - return 0; - }} - - int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) - {{ - return 0; - }} - - int ITupleInternal.GetHashCode(IEqualityComparer comparer) - {{ - return 0; - }} - - public override string ToString() - {{ - return ""()""; - }} - - string ITupleInternal.ToStringEnd() - {{ - return "")""; - }} - - public static ValueTuple Create() - {{ - return default(ValueTuple); - }} - - public static ValueTuple Create(T1 item1) - {{ - return new ValueTuple(item1); - }} - - public static (T1, T2) Create(T1 item1, T2 item2) - {{ - return (item1, item2); - }} - - public static (T1, T2, T3) Create(T1 item1, T2 item2, T3 item3) - {{ - return (item1, item2, item3); - }} - - public static (T1, T2, T3, T4) Create(T1 item1, T2 item2, T3 item3, T4 item4) - {{ - return (item1, item2, item3, item4); - }} - - public static (T1, T2, T3, T4, T5) Create(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) - {{ - return (item1, item2, item3, item4, item5); - }} - - public static (T1, T2, T3, T4, T5, T6) Create(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) - {{ - return (item1, item2, item3, item4, item5, item6); - }} - - public static (T1, T2, T3, T4, T5, T6, T7) Create(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) - {{ - return (item1, item2, item3, item4, item5, item6, item7); - }} - - public static (T1, T2, T3, T4, T5, T6, T7, T8) Create(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) - {{ - return new ValueTuple>(item1, item2, item3, item4, item5, item6, item7, Create(item8)); - }} - - internal static int CombineHashCodes(int h1, int h2) - {{ - return HashHelpers.Combine(HashHelpers.Combine(HashHelpers.RandomSeed, h1), h2); - }} - - internal static int CombineHashCodes(int h1, int h2, int h3) - {{ - return HashHelpers.Combine(CombineHashCodes(h1, h2), h3); - }} - - internal static int CombineHashCodes(int h1, int h2, int h3, int h4) - {{ - return HashHelpers.Combine(CombineHashCodes(h1, h2, h3), h4); - }} - - internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5) - {{ - return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4), h5); - }} - - internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6) - {{ - return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4, h5), h6); - }} - - internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7) - {{ - return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4, h5, h6), h7); - }} - - internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8) - {{ - return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4, h5, h6, h7), h8); - }} -}} -#if false // {FeaturesResources.Decompilation_log} -{string.Format(FeaturesResources._0_items_in_cache, 9)} ------------------- -{string.Format(FeaturesResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} -{string.Format(FeaturesResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} -{string.Format(FeaturesResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} ------------------- -{string.Format(FeaturesResources.Resolve_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} -{string.Format(FeaturesResources.Found_single_assembly_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} -{string.Format(FeaturesResources.Load_from_0, "System.v4_6_1038_0.dll")} -#endif", + true => $""" + #Region "{FeaturesResources.Assembly} System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" + ' System.ValueTuple (net461) + #End Region + + Imports System.Collections + + Namespace System + Public Structure [|ValueTuple|] + Implements IEquatable(Of ValueTuple), IStructuralEquatable, IStructuralComparable, IComparable, IComparable(Of ValueTuple), ITupleInternal + + Public Shared Function Create() As ValueTuple + Public Shared Function Create(Of T1)(item1 As T1) As ValueTuple(Of T1) + Public Shared Function Create(Of T1, T2)(item1 As T1, item2 As T2) As (T1, T2) + Public Shared Function Create(Of T1, T2, T3)(item1 As T1, item2 As T2, item3 As T3) As (T1, T2, T3) + Public Shared Function Create(Of T1, T2, T3, T4)(item1 As T1, item2 As T2, item3 As T3, item4 As T4) As (T1, T2, T3, T4) + Public Shared Function Create(Of T1, T2, T3, T4, T5)(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5) As (T1, T2, T3, T4, T5) + Public Shared Function Create(Of T1, T2, T3, T4, T5, T6)(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5, item6 As T6) As (T1, T2, T3, T4, T5, T6) + Public Shared Function Create(Of T1, T2, T3, T4, T5, T6, T7)(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5, item6 As T6, item7 As T7) As (T1, T2, T3, T4, T5, T6, T7) + Public Shared Function Create(Of T1, T2, T3, T4, T5, T6, T7, T8)(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5, item6 As T6, item7 As T7, item8 As T8) As (T1, T2, T3, T4, T5, T6, T7, T8) + Public Overrides Function Equals(obj As Object) As Boolean + Public Function Equals(other As ValueTuple) As Boolean + Public Function CompareTo(other As ValueTuple) As Integer + Public Overrides Function GetHashCode() As Integer + Public Overrides Function ToString() As String + End Structure + End Namespace + """, + false => $$""" + #region {{FeaturesResources.Assembly}} System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51 + // {{FeaturesResources.location_unknown}} + // Decompiled with ICSharpCode.Decompiler {{ICSharpCodeDecompilerVersion}} + #endregion + + using System.Collections; + using System.Numerics.Hashing; + using System.Runtime.InteropServices; + + namespace System; + + [StructLayout(LayoutKind.Sequential, Size = 1)] + public struct [|ValueTuple|] : IEquatable, IStructuralEquatable, IStructuralComparable, IComparable, IComparable, ITupleInternal + { + int ITupleInternal.Size => 0; + + public override bool Equals(object obj) + { + return obj is ValueTuple; + } + + public bool Equals(ValueTuple other) + { + return true; + } + + bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) + { + return other is ValueTuple; + } + + int IComparable.CompareTo(object other) + { + if (other == null) + { + return 1; + } + + if (!(other is ValueTuple)) + { + throw new ArgumentException(System.SR.ArgumentException_ValueTupleIncorrectType, "other"); + } + + return 0; + } + + public int CompareTo(ValueTuple other) + { + return 0; + } + + int IStructuralComparable.CompareTo(object other, IComparer comparer) + { + if (other == null) + { + return 1; + } + + if (!(other is ValueTuple)) + { + throw new ArgumentException(System.SR.ArgumentException_ValueTupleIncorrectType, "other"); + } + + return 0; + } + + public override int GetHashCode() + { + return 0; + } + + int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) + { + return 0; + } + + int ITupleInternal.GetHashCode(IEqualityComparer comparer) + { + return 0; + } + + public override string ToString() + { + return "()"; + } + + string ITupleInternal.ToStringEnd() + { + return ")"; + } + + public static ValueTuple Create() + { + return default(ValueTuple); + } + + public static ValueTuple Create(T1 item1) + { + return new ValueTuple(item1); + } + + public static (T1, T2) Create(T1 item1, T2 item2) + { + return (item1, item2); + } + + public static (T1, T2, T3) Create(T1 item1, T2 item2, T3 item3) + { + return (item1, item2, item3); + } + + public static (T1, T2, T3, T4) Create(T1 item1, T2 item2, T3 item3, T4 item4) + { + return (item1, item2, item3, item4); + } + + public static (T1, T2, T3, T4, T5) Create(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) + { + return (item1, item2, item3, item4, item5); + } + + public static (T1, T2, T3, T4, T5, T6) Create(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) + { + return (item1, item2, item3, item4, item5, item6); + } + + public static (T1, T2, T3, T4, T5, T6, T7) Create(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) + { + return (item1, item2, item3, item4, item5, item6, item7); + } + + public static (T1, T2, T3, T4, T5, T6, T7, T8) Create(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) + { + return new ValueTuple>(item1, item2, item3, item4, item5, item6, item7, Create(item8)); + } + + internal static int CombineHashCodes(int h1, int h2) + { + return HashHelpers.Combine(HashHelpers.Combine(HashHelpers.RandomSeed, h1), h2); + } + + internal static int CombineHashCodes(int h1, int h2, int h3) + { + return HashHelpers.Combine(CombineHashCodes(h1, h2), h3); + } + + internal static int CombineHashCodes(int h1, int h2, int h3, int h4) + { + return HashHelpers.Combine(CombineHashCodes(h1, h2, h3), h4); + } + + internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5) + { + return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4), h5); + } + + internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6) + { + return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4, h5), h6); + } + + internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7) + { + return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4, h5, h6), h7); + } + + internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8) + { + return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4, h5, h6, h7), h8); + } + } + #if false // {{FeaturesResources.Decompilation_log}} + {{string.Format(FeaturesResources._0_items_in_cache, 9)}} + ------------------ + {{string.Format(FeaturesResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")}} + {{string.Format(FeaturesResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")}} + {{string.Format(FeaturesResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")}} + ------------------ + {{string.Format(FeaturesResources.Resolve_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")}} + {{string.Format(FeaturesResources.Found_single_assembly_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")}} + {{string.Format(FeaturesResources.Load_from_0, "System.v4_6_1038_0.dll")}} + #endif + """, }; await context.GenerateAndVerifySourceAsync("System.ValueTuple", expected, signaturesOnly: signaturesOnly); diff --git a/src/EditorFeatures/Test/MetadataAsSource/MetadataAsSourceTests.cs b/src/EditorFeatures/Test/MetadataAsSource/MetadataAsSourceTests.cs index cd59bdfd05638..f5cce598b235e 100644 --- a/src/EditorFeatures/Test/MetadataAsSource/MetadataAsSourceTests.cs +++ b/src/EditorFeatures/Test/MetadataAsSource/MetadataAsSourceTests.cs @@ -38,9 +38,6 @@ private static string ToLanguageName(OriginatingProjectLanguage language) [WpfTheory, CombinatorialData] public async Task TestClass(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = "public class C {}"; - var symbolName = "C"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -99,15 +96,12 @@ public class [|C|] _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync("public class C {}", "C", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfTheory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546241"), CombinatorialData] public async Task TestInterface(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = "public interface I {}"; - var symbolName = "I"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -164,15 +158,12 @@ public interface [|I|] _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync("public interface I {}", "I", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfTheory, CombinatorialData] public async Task TestConstructor(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = "public class C {}"; - var symbolName = "C..ctor"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -231,15 +222,12 @@ public class [|C|] _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync("public class C {}", "C..ctor", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfTheory, CombinatorialData] public async Task TestMethod(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = "public class C { public void Goo() {} }"; - var symbolName = "C.Goo"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -308,15 +296,12 @@ public class C _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync("public class C { public void Goo() {} }", "C.Goo", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfTheory, CombinatorialData] public async Task TestField(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = "public class C { public string S; }"; - var symbolName = "C.S"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -381,15 +366,12 @@ public class C _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync("public class C { public string S; }", "C.S", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfTheory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546240"), CombinatorialData] public async Task TestProperty(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = "public class C { public string S { get; protected set; } }"; - var symbolName = "C.S"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -454,16 +436,13 @@ public class C _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync("public class C { public string S { get; protected set; } }", "C.S", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfTheory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546291"), CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546194")] public async Task TestEvent(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = "using System; public class C { public event Action E; }"; - var symbolName = "C.E"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -536,15 +515,12 @@ public class C _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync("using System; public class C { public event Action E; }", "C.E", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfTheory, CombinatorialData] public async Task TestNestedType(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = "public class C { protected class D { } }"; - var symbolName = "C+D"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -618,15 +594,12 @@ protected class [|D|] _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync("public class C { protected class D { } }", "C+D", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfTheory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546195"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546269"), CombinatorialData] public async Task TestEnum(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = "public enum E { A, B, C }"; - var symbolName = "E"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -695,15 +668,12 @@ public enum [|E|] _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync("public enum E { A, B, C }", "E", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfTheory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546195"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546269"), CombinatorialData] public async Task TestEnumFromField(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = "public enum E { A, B, C }"; - var symbolName = "E.C"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -772,15 +742,12 @@ public enum E _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync("public enum E { A, B, C }", "E.C", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfTheory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546273"), CombinatorialData] public async Task TestEnumWithUnderlyingType(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = "public enum E : short { A = 0, B = 1, C = 2 }"; - var symbolName = "E.C"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -849,15 +816,12 @@ public enum E : short _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync("public enum E : short { A = 0, B = 1, C = 2 }", "E.C", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfTheory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/650741"), CombinatorialData] public async Task TestEnumWithOverflowingUnderlyingType(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = "public enum E : ulong { A = 9223372036854775808 }"; - var symbolName = "E.A"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -918,15 +882,12 @@ public enum E : ulong _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync("public enum E : ulong { A = 9223372036854775808 }", "E.A", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfTheory, CombinatorialData] public async Task TestEnumWithDifferentValues(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = "public enum E : short { A = 1, B = 2, C = 3 }"; - var symbolName = "E.C"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -995,15 +956,12 @@ public enum E : short _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync("public enum E : short { A = 1, B = 2, C = 3 }", "E.C", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfTheory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546198"), CombinatorialData] public async Task TestTypeInNamespace(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = "namespace N { public class C {} }"; - var symbolName = "N.C"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -1071,7 +1029,7 @@ public class [|C|] _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync("namespace N { public class C {} }", "N.C", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546198")] @@ -1148,9 +1106,6 @@ public class [|C|] [WpfTheory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546223"), CombinatorialData] public async Task TestInlineConstant(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = @"public class C { public const string S = ""Hello mas""; }"; - var symbolName = "C.S"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -1215,27 +1170,12 @@ public class C _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync(@"public class C { public const string S = ""Hello mas""; }", "C.S", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfTheory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546221"), CombinatorialData] public async Task TestInlineTypeOf(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = """ - - using System; - - public class MyTypeAttribute : Attribute - { - public MyTypeAttribute(Type type) {} - } - - [MyType(typeof(string))] - public class C {} - """; - - var symbolName = "C"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -1298,15 +1238,23 @@ public class [|C|] _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync(""" + + using System; + + public class MyTypeAttribute : Attribute + { + public MyTypeAttribute(Type type) {} + } + + [MyType(typeof(string))] + public class C {} + """, "C", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfTheory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546231"), CombinatorialData] public async Task TestNoDefaultConstructorInStructs(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = "public struct S {}"; - var symbolName = "S"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -1369,15 +1317,12 @@ public struct [|S|] _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync("public struct S {}", "S", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfTheory, CombinatorialData] public async Task TestReferenceDefinedType(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = "public class C { public static C Create() { return new C(); } }"; - var symbolName = "C"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -1448,15 +1393,12 @@ public static C Create() _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync("public class C { public static C Create() { return new C(); } }", "C", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfTheory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546227"), CombinatorialData] public async Task TestGenericType(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = "public class G { public SomeType S; }"; - var symbolName = "G`1"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -1521,25 +1463,13 @@ public class [|G|] _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync("public class G { public SomeType S; }", "G`1", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfTheory, CombinatorialData] [WorkItem("https://github.com/dotnet/roslyn/issues/38916")] public async Task TestParameterAttributes(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = """ - - public class C<[My] T> - { - public void Method([My] T x, [My] T y) { } - } - - internal class MyAttribute : System.Attribute { } - - """; - var symbolName = "C`1"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -1608,26 +1538,22 @@ public void Method([My] T x, [My] T y) _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); - } - - [WpfTheory, CombinatorialData] - [WorkItem("https://github.com/dotnet/roslyn/issues/38916")] - public async Task TestGenericWithNullableReferenceTypes(OriginatingProjectLanguage language, bool signaturesOnly) - { - var metadataSource = """ + await GenerateAndVerifySourceAsync(""" - #nullable enable - public interface C + public class C<[My] T> { - bool Equals([AllowNull] T other); + public void Method([My] T x, [My] T y) { } } - internal class AllowNullAttribute : System.Attribute { } + internal class MyAttribute : System.Attribute { } - """; - var symbolName = "C`1"; + """, "C`1", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + } + [WpfTheory, CombinatorialData] + [WorkItem("https://github.com/dotnet/roslyn/issues/38916")] + public async Task TestGenericWithNullableReferenceTypes(OriginatingProjectLanguage language, bool signaturesOnly) + { var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -1688,15 +1614,22 @@ public interface [|C|] _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync(""" + + #nullable enable + public interface C + { + bool Equals([AllowNull] T other); + } + + internal class AllowNullAttribute : System.Attribute { } + + """, "C`1", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfTheory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546227"), CombinatorialData] public async Task TestGenericDelegate(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = "public class C { public delegate void D(SomeType s); }"; - var symbolName = "C+D`1"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -1760,30 +1693,12 @@ public class C _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync("public class C { public delegate void D(SomeType s); }", "C+D`1", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfTheory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546200"), CombinatorialData] public async Task TestAttribute(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = """ - - using System; - - namespace N - { - public class WorkingAttribute : Attribute - { - public WorkingAttribute(bool working) {} - } - } - - [N.Working(true)] - public class C {} - """; - - var symbolName = "C"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -1854,7 +1769,21 @@ public class [|C|] _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync(""" + + using System; + + namespace N + { + public class WorkingAttribute : Attribute + { + public WorkingAttribute(bool working) {} + } + } + + [N.Working(true)] + public class C {} + """, "C", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfFact] @@ -1954,9 +1883,8 @@ public async Task FormatMetadataAsSource() } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530829")] - public async Task IndexedProperty() - { - var metadataSource = """ + public Task IndexedProperty() + => GenerateAndVerifySourceAsync(""" Public Class C Public Property IndexProp(ByVal p1 As Integer) As String @@ -1968,8 +1896,7 @@ End Get End Set End Property End Class - """; - var expected = $$""" + """, "C.get_IndexProp", LanguageNames.CSharp, $$""" #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {{CodeAnalysisResources.InMemoryAssembly}} #endregion @@ -1981,15 +1908,11 @@ public class C public string [|get_IndexProp|](int p1); public void set_IndexProp(int p1, string value); } - """; - var symbolName = "C.get_IndexProp"; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, expected); - } + """); [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/566688")] - public async Task AttributeReferencingInternalNestedType() - { - var metadataSource = """ + public Task AttributeReferencingInternalNestedType() + => GenerateAndVerifySourceAsync(""" using System; [My(typeof(D))] public class C @@ -2003,9 +1926,7 @@ public class MyAttribute : Attribute { public MyAttribute(Type t) { } } - """; - - var expected = $$""" + """, "C", LanguageNames.CSharp, $$""" #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {{CodeAnalysisResources.InMemoryAssembly}} #endregion @@ -2015,57 +1936,11 @@ public class [|C|] { public C(); } - """; - var symbolName = "C"; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, expected); - } + """); [WpfTheory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530978"), CombinatorialData] public async Task TestAttributesOnMembers(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = """ - using System; - - [Obsolete] - public class C - { - [Obsolete] - [ThreadStatic] - public int field1; - - [Obsolete] - public int prop1 { get; set; } - - [Obsolete] - public int prop2 { get { return 10; } set {} } - - [Obsolete] - public void method1() {} - - [Obsolete] - public C() {} - - [Obsolete] - ~C() {} - - [Obsolete] - public int this[int x] { get { return 10; } set {} } - - [Obsolete] - public event Action event1; - - [Obsolete] - public event Action event2 { add {} remove {}} - - public void method2([System.Runtime.CompilerServices.CallerMemberName] string name = "") {} - - [Obsolete] - public static C operator + (C c1, C c2) { return new C(); } - } - - """; - var symbolName = "C"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -2334,35 +2209,52 @@ public void method2([CallerMemberName] string name = "") _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); - } - - [WpfTheory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530923"), CombinatorialData] - public async Task TestEmptyLineBetweenMembers(OriginatingProjectLanguage language, bool signaturesOnly) - { - var metadataSource = """ + await GenerateAndVerifySourceAsync(""" using System; + [Obsolete] public class C { + [Obsolete] + [ThreadStatic] public int field1; + + [Obsolete] public int prop1 { get; set; } - public int field2; + + [Obsolete] public int prop2 { get { return 10; } set {} } + + [Obsolete] public void method1() {} + + [Obsolete] public C() {} - public void method2([System.Runtime.CompilerServices.CallerMemberName] string name = "") {} + + [Obsolete] ~C() {} + + [Obsolete] public int this[int x] { get { return 10; } set {} } + + [Obsolete] public event Action event1; - public static C operator + (C c1, C c2) { return new C(); } + + [Obsolete] public event Action event2 { add {} remove {}} - public static C operator - (C c1, C c2) { return new C(); } + + public void method2([System.Runtime.CompilerServices.CallerMemberName] string name = "") {} + + [Obsolete] + public static C operator + (C c1, C c2) { return new C(); } } - """; - var symbolName = "C"; + """, "C", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + } + [WpfTheory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530923"), CombinatorialData] + public async Task TestEmptyLineBetweenMembers(OriginatingProjectLanguage language, bool signaturesOnly) + { var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -2595,28 +2487,32 @@ public void method2([CallerMemberName] string name = "") _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); - } - - [WpfTheory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728644"), CombinatorialData] - public async Task TestEmptyLineBetweenMembers2(OriginatingProjectLanguage language, bool signaturesOnly) - { - var source = """ - + await GenerateAndVerifySourceAsync(""" using System; - /// T:IGoo - public interface IGoo + public class C { - /// P:IGoo.Prop1 - Uri Prop1 { get; set; } - /// M:IGoo.Method1 - Uri Method1(); + public int field1; + public int prop1 { get; set; } + public int field2; + public int prop2 { get { return 10; } set {} } + public void method1() {} + public C() {} + public void method2([System.Runtime.CompilerServices.CallerMemberName] string name = "") {} + ~C() {} + public int this[int x] { get { return 10; } set {} } + public event Action event1; + public static C operator + (C c1, C c2) { return new C(); } + public event Action event2 { add {} remove {}} + public static C operator - (C c1, C c2) { return new C(); } } - """; - var symbolName = "IGoo"; + """, "C", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + } + [WpfTheory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728644"), CombinatorialData] + public async Task TestEmptyLineBetweenMembers2(OriginatingProjectLanguage language, bool signaturesOnly) + { var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -2719,24 +2615,25 @@ public interface [|IGoo|] _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(source, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly, includeXmlDocComments: true); - } - - [WpfTheory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/679114"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715013"), CombinatorialData] - public async Task TestDefaultValueEnum(OriginatingProjectLanguage language, bool signaturesOnly) - { - var source = """ + await GenerateAndVerifySourceAsync(""" - using System.IO; + using System; - public class Test + /// T:IGoo + public interface IGoo { - public void goo(FileOptions options = 0) {} + /// P:IGoo.Prop1 + Uri Prop1 { get; set; } + /// M:IGoo.Method1 + Uri Method1(); } - """; - var symbolName = "Test"; + """, "IGoo", ToLanguageName(language), expected, signaturesOnly: signaturesOnly, includeXmlDocComments: true); + } + [WpfTheory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/679114"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715013"), CombinatorialData] + public async Task TestDefaultValueEnum(OriginatingProjectLanguage language, bool signaturesOnly) + { var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -2813,26 +2710,21 @@ public void goo(FileOptions options = FileOptions.None) _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(source, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); - } + await GenerateAndVerifySourceAsync(""" - [WpfTheory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651261"), CombinatorialData] - public async Task TestNullAttribute(OriginatingProjectLanguage language, bool signaturesOnly) - { - var source = """ - - using System; + using System.IO; - [Test(null)] - public class TestAttribute : Attribute + public class Test { - public TestAttribute(int[] i) - { - } + public void goo(FileOptions options = 0) {} } - """; - var symbolName = "TestAttribute"; + """, "Test", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + } + + [WpfTheory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651261"), CombinatorialData] + public async Task TestNullAttribute(OriginatingProjectLanguage language, bool signaturesOnly) + { var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -2911,7 +2803,18 @@ public TestAttribute(int[] i) _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(source, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync(""" + + using System; + + [Test(null)] + public class TestAttribute : Attribute + { + public TestAttribute(int[] i) + { + } + } + """, "TestAttribute", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/897006")] @@ -2934,7 +2837,14 @@ void M() } } """; - var expected = $$""" + using var context = TestContext.Create( + LanguageNames.CSharp, + [metadata], + includeXmlDocComments: false, + sourceWithSymbolReference: sourceWithSymbolReference); + var navigationSymbol = await context.GetNavigationSymbolAsync(); + var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); + TestContext.VerifyResult(metadataAsSourceFile, $$""" #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {{CodeAnalysisResources.InMemoryAssembly}} #endregion @@ -2943,16 +2853,7 @@ public static class ObjectExtensions { public static void [|M|](this object o, int x); } - """; - - using var context = TestContext.Create( - LanguageNames.CSharp, - [metadata], - includeXmlDocComments: false, - sourceWithSymbolReference: sourceWithSymbolReference); - var navigationSymbol = await context.GetNavigationSymbolAsync(); - var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); - TestContext.VerifyResult(metadataAsSourceFile, expected); + """); } [WpfFact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/897006")] @@ -2978,7 +2879,14 @@ Sub M() End Sub End Module """; - var expected = $""" + using var context = TestContext.Create( + LanguageNames.VisualBasic, + [metadata], + includeXmlDocComments: false, + sourceWithSymbolReference: sourceWithSymbolReference); + var navigationSymbol = await context.GetNavigationSymbolAsync(); + var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); + TestContext.VerifyResult(metadataAsSourceFile, $""" #Region "{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" ' {CodeAnalysisResources.InMemoryAssembly} #End Region @@ -2991,44 +2899,12 @@ Public Module StringExtensions Public Sub [|M|](o As String, x As Integer) End Module End Namespace - """; - - using var context = TestContext.Create( - LanguageNames.VisualBasic, - [metadata], - includeXmlDocComments: false, - sourceWithSymbolReference: sourceWithSymbolReference); - var navigationSymbol = await context.GetNavigationSymbolAsync(); - var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); - TestContext.VerifyResult(metadataAsSourceFile, expected); + """); } [WpfTheory, CombinatorialData] public async Task TestIndexersAndOperators(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = """ - public class Program - { - public int this[int x] - { - get - { - return 0; - } - set - { - - } - } - - public static Program operator + (Program p1, Program p2) - { - return new Program(); - } - } - """; - var symbolName = "Program"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -3131,28 +3007,32 @@ public int this[int x] _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync(""" + public class Program + { + public int this[int x] + { + get + { + return 0; + } + set + { + + } + } + + public static Program operator + (Program p1, Program p2) + { + return new Program(); + } + } + """, "Program", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/15387"), CombinatorialData] public async Task TestComImport1(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = """ - - using System.Runtime.InteropServices; - - [ComImport] - [Guid("666A175D-2448-447A-B786-CCC82CBEF156")] - public interface IComImport - { - void MOverload(); - void X(); - void MOverload(int i); - int Prop { get; } - } - """; - var symbolName = "IComImport"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -3247,22 +3127,25 @@ public interface [|IComImport|] _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync(""" + + using System.Runtime.InteropServices; + + [ComImport] + [Guid("666A175D-2448-447A-B786-CCC82CBEF156")] + public interface IComImport + { + void MOverload(); + void X(); + void MOverload(int i); + int Prop { get; } + } + """, "IComImport", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfTheory, CombinatorialData] public async Task TestOptionalParameterWithDefaultLiteral(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = """ - - using System.Threading; - - public class C { - public void M(CancellationToken cancellationToken = default(CancellationToken)) { } - } - """; - var symbolName = "C"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -3346,7 +3229,14 @@ public class [|C|] _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly, languageVersion: languageVersion); + await GenerateAndVerifySourceAsync(""" + + using System.Threading; + + public class C { + public void M(CancellationToken cancellationToken = default(CancellationToken)) { } + } + """, "C", ToLanguageName(language), expected, signaturesOnly: signaturesOnly, languageVersion: languageVersion); } [WpfTheory, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=446567"), CombinatorialData] @@ -3384,8 +3274,6 @@ public interface IGoo } """; - var symbolName = "IGoo"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -3488,7 +3376,7 @@ public interface [|IGoo|] _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(source, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly, includeXmlDocComments: true); + await GenerateAndVerifySourceAsync(source, "IGoo", ToLanguageName(language), expected, signaturesOnly: signaturesOnly, includeXmlDocComments: true); } [WpfFact] @@ -3510,17 +3398,6 @@ void M() } } """; - var expected = $$""" - #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null - // {{CodeAnalysisResources.InMemoryAssembly}} - #endregion - - public class [|TestType|] where T : unmanaged - { - public TestType(); - } - """; - using var context = TestContext.Create( LanguageNames.CSharp, [metadata], @@ -3529,7 +3406,16 @@ public class [|TestType|] where T : unmanaged sourceWithSymbolReference: sourceWithSymbolReference); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); - TestContext.VerifyResult(metadataAsSourceFile, expected); + TestContext.VerifyResult(metadataAsSourceFile, $$""" + #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + // {{CodeAnalysisResources.InMemoryAssembly}} + #endregion + + public class [|TestType|] where T : unmanaged + { + public TestType(); + } + """); } [WpfFact] @@ -3554,7 +3440,15 @@ void M() } } """; - var expected = $$""" + using var context = TestContext.Create( + LanguageNames.CSharp, + [metadata], + includeXmlDocComments: false, + languageVersion: "7.3", + sourceWithSymbolReference: sourceWithSymbolReference); + var navigationSymbol = await context.GetNavigationSymbolAsync(); + var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); + TestContext.VerifyResult(metadataAsSourceFile, $$""" #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {{CodeAnalysisResources.InMemoryAssembly}} #endregion @@ -3565,17 +3459,7 @@ public class TestType public void [|M|]() where T : unmanaged; } - """; - - using var context = TestContext.Create( - LanguageNames.CSharp, - [metadata], - includeXmlDocComments: false, - languageVersion: "7.3", - sourceWithSymbolReference: sourceWithSymbolReference); - var navigationSymbol = await context.GetNavigationSymbolAsync(); - var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); - TestContext.VerifyResult(metadataAsSourceFile, expected); + """); } [WpfFact] @@ -3594,14 +3478,6 @@ class C } } """; - var expected = $""" - #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null - // {CodeAnalysisResources.InMemoryAssembly} - #endregion - - public delegate void [|D|]() where T : unmanaged; - """; - using var context = TestContext.Create( LanguageNames.CSharp, [metadata], @@ -3610,146 +3486,94 @@ class C sourceWithSymbolReference: sourceWithSymbolReference); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); - TestContext.VerifyResult(metadataAsSourceFile, expected); + TestContext.VerifyResult(metadataAsSourceFile, $""" + #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + // {CodeAnalysisResources.InMemoryAssembly} + #endregion + + public delegate void [|D|]() where T : unmanaged; + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/29786")] - public async Task TestSByteMinValue() - { - var source = """ + public Task TestSByteMinValue() + => GenerateAndVerifySourceLineAsync(""" class C { sbyte Goo = sbyte.[|MinValue|]; } - """; - - var expected = "public const SByte MinValue = -128;"; - - await GenerateAndVerifySourceLineAsync(source, LanguageNames.CSharp, expected); - } + """, LanguageNames.CSharp, "public const SByte MinValue = -128;"); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/29786")] - public async Task TestSByteMinValueVB() - { - var source = """ + public Task TestSByteMinValueVB() + => GenerateAndVerifySourceLineAsync(""" Class C Public Goo = SByte.[|MinValue|] End Class - """; - - var expected = "Public Const MinValue As [SByte] = -128"; - - await GenerateAndVerifySourceLineAsync(source, LanguageNames.VisualBasic, expected); - } + """, LanguageNames.VisualBasic, "Public Const MinValue As [SByte] = -128"); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/29786")] - public async Task TestInt16MinValue() - { - var source = """ + public Task TestInt16MinValue() + => GenerateAndVerifySourceLineAsync(""" class C { short Goo = short.[|MinValue|]; } - """; - - var expected = $"public const Int16 MinValue = -32768;"; - - await GenerateAndVerifySourceLineAsync(source, LanguageNames.CSharp, expected); - } + """, LanguageNames.CSharp, $"public const Int16 MinValue = -32768;"); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/29786")] - public async Task TestInt16MinValueVB() - { - var source = """ + public Task TestInt16MinValueVB() + => GenerateAndVerifySourceLineAsync(""" Class C Public Goo = Short.[|MinValue|] End Class - """; - - var expected = $"Public Const MinValue As Int16 = -32768"; - - await GenerateAndVerifySourceLineAsync(source, LanguageNames.VisualBasic, expected); - } + """, LanguageNames.VisualBasic, $"Public Const MinValue As Int16 = -32768"); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/29786")] - public async Task TestInt32MinValue() - { - var source = """ + public Task TestInt32MinValue() + => GenerateAndVerifySourceLineAsync(""" class C { int Goo = int.[|MinValue|]; } - """; - - var expected = $"public const Int32 MinValue = -2147483648;"; - - await GenerateAndVerifySourceLineAsync(source, LanguageNames.CSharp, expected); - } + """, LanguageNames.CSharp, $"public const Int32 MinValue = -2147483648;"); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/29786")] - public async Task TestInt32MinValueVB() - { - var source = """ + public Task TestInt32MinValueVB() + => GenerateAndVerifySourceLineAsync(""" Class C Public Goo = Integer.[|MinValue|] End Class - """; - - var expected = $"Public Const MinValue As Int32 = -2147483648"; - - await GenerateAndVerifySourceLineAsync(source, LanguageNames.VisualBasic, expected); - } + """, LanguageNames.VisualBasic, $"Public Const MinValue As Int32 = -2147483648"); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/29786")] - public async Task TestInt64MinValue() - { - var source = """ + public Task TestInt64MinValue() + => GenerateAndVerifySourceLineAsync(""" class C { long Goo = long.[|MinValue|]; } - """; - - var expected = $"public const Int64 MinValue = -9223372036854775808;"; - - await GenerateAndVerifySourceLineAsync(source, LanguageNames.CSharp, expected); - } + """, LanguageNames.CSharp, $"public const Int64 MinValue = -9223372036854775808;"); [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/29786")] - public async Task TestInt64MinValueVB() - { - var source = """ + public Task TestInt64MinValueVB() + => GenerateAndVerifySourceLineAsync(""" Class C Public Goo = Long.[|MinValue|] End Class - """; - - var expected = $"Public Const MinValue As Int64 = -9223372036854775808"; - - await GenerateAndVerifySourceLineAsync(source, LanguageNames.VisualBasic, expected); - } + """, LanguageNames.VisualBasic, $"Public Const MinValue As Int64 = -9223372036854775808"); [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] public async Task TestReadOnlyStruct_ReadOnlyField(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = """ - - public readonly struct S - { - public readonly int i; - } - - """; - var symbolName = "S"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -3812,22 +3636,19 @@ public readonly struct [|S|] _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync(""" + + public readonly struct S + { + public readonly int i; + } + + """, "S", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] public async Task TestStruct_ReadOnlyField(OriginatingProjectLanguage language, bool signaturesOnly) { - var metadataSource = """ - - public struct S - { - public readonly int i; - } - - """; - var symbolName = "S"; - var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -3888,21 +3709,19 @@ public struct [|S|] _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); - } - - [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] - public async Task TestRefStruct(OriginatingProjectLanguage language, bool signaturesOnly) - { - var metadataSource = """ + await GenerateAndVerifySourceAsync(""" - public ref struct S + public struct S { + public readonly int i; } - """; - var symbolName = "S"; + """, "S", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + } + [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] + public async Task TestRefStruct(OriginatingProjectLanguage language, bool signaturesOnly) + { var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -3968,21 +3787,18 @@ public ref struct [|S|] _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); - } - - [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] - public async Task TestReadOnlyRefStruct(OriginatingProjectLanguage language, bool signaturesOnly) - { - var metadataSource = """ + await GenerateAndVerifySourceAsync(""" - public readonly ref struct S + public ref struct S { } - """; - var symbolName = "S"; + """, "S", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + } + [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] + public async Task TestReadOnlyRefStruct(OriginatingProjectLanguage language, bool signaturesOnly) + { var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -4048,22 +3864,18 @@ public readonly ref struct [|S|] _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); - } - - [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] - public async Task TestReadOnlyMethod(OriginatingProjectLanguage language, bool signaturesOnly) - { - var metadataSource = """ + await GenerateAndVerifySourceAsync(""" - public struct S + public readonly ref struct S { - public readonly void M() {} } - """; - var symbolName = "S.M"; + """, "S", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + } + [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] + public async Task TestReadOnlyMethod(OriginatingProjectLanguage language, bool signaturesOnly) + { var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -4135,22 +3947,19 @@ public struct S _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); - } - - [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] - public async Task TestReadOnlyMethod_InReadOnlyStruct(OriginatingProjectLanguage language, bool signaturesOnly) - { - var metadataSource = """ + await GenerateAndVerifySourceAsync(""" - public readonly struct S + public struct S { - public void M() {} + public readonly void M() {} } - """; - var symbolName = "S.M"; + """, "S.M", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + } + [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] + public async Task TestReadOnlyMethod_InReadOnlyStruct(OriginatingProjectLanguage language, bool signaturesOnly) + { var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -4223,22 +4032,19 @@ public readonly struct S _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); - } - - [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] - public async Task TestStructProperty_ReadOnly(OriginatingProjectLanguage language, bool signaturesOnly) - { - var metadataSource = """ + await GenerateAndVerifySourceAsync(""" - public struct S + public readonly struct S { - public int P { get; } + public void M() {} } - """; - var symbolName = "S.P"; + """, "S.M", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + } + [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] + public async Task TestStructProperty_ReadOnly(OriginatingProjectLanguage language, bool signaturesOnly) + { var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -4299,22 +4105,19 @@ public struct S _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); - } - - [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] - public async Task TestStructProperty_ReadOnly_CSharp7_3(OriginatingProjectLanguage language, bool signaturesOnly) - { - var metadataSource = """ + await GenerateAndVerifySourceAsync(""" public struct S { public int P { get; } } - """; - var symbolName = "S.P"; + """, "S.P", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + } + [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] + public async Task TestStructProperty_ReadOnly_CSharp7_3(OriginatingProjectLanguage language, bool signaturesOnly) + { var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -4382,22 +4185,19 @@ public struct S _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly, metadataLanguageVersion: metadataLanguageVersion); - } - - [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] - public async Task TestStructProperty_ReadOnlyGet(OriginatingProjectLanguage language, bool signaturesOnly) - { - var metadataSource = """ + await GenerateAndVerifySourceAsync(""" public struct S { - public readonly int P { get; } + public int P { get; } } - """; - var symbolName = "S.P"; + """, "S.P", ToLanguageName(language), expected, signaturesOnly: signaturesOnly, metadataLanguageVersion: metadataLanguageVersion); + } + [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] + public async Task TestStructProperty_ReadOnlyGet(OriginatingProjectLanguage language, bool signaturesOnly) + { var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -4458,22 +4258,19 @@ public struct S _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); - } - - [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] - public async Task TestReadOnlyStructProperty_ReadOnlyGet(OriginatingProjectLanguage language, bool signaturesOnly) - { - var metadataSource = """ + await GenerateAndVerifySourceAsync(""" - public readonly struct S + public struct S { public readonly int P { get; } } - """; - var symbolName = "S.P"; + """, "S.P", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + } + [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] + public async Task TestReadOnlyStructProperty_ReadOnlyGet(OriginatingProjectLanguage language, bool signaturesOnly) + { var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -4536,22 +4333,19 @@ public readonly struct S _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); - } - - [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] - public async Task TestStructProperty_ReadOnlyGet_Set(OriginatingProjectLanguage language, bool signaturesOnly) - { - var metadataSource = """ + await GenerateAndVerifySourceAsync(""" - public struct S + public readonly struct S { - public int P { readonly get => 123; set {} } + public readonly int P { get; } } - """; - var symbolName = "S.P"; + """, "S.P", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + } + [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] + public async Task TestStructProperty_ReadOnlyGet_Set(OriginatingProjectLanguage language, bool signaturesOnly) + { var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -4636,22 +4430,19 @@ readonly get _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); - } - - [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] - public async Task TestStructProperty_Get_ReadOnlySet(OriginatingProjectLanguage language, bool signaturesOnly) - { - var metadataSource = """ + await GenerateAndVerifySourceAsync(""" public struct S { - public int P { get => 123; readonly set {} } + public int P { readonly get => 123; set {} } } - """; - var symbolName = "S.P"; + """, "S.P", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + } + [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] + public async Task TestStructProperty_Get_ReadOnlySet(OriginatingProjectLanguage language, bool signaturesOnly) + { var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -4736,22 +4527,19 @@ readonly set _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); - } - - [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] - public async Task TestStructProperty_ReadOnlyGet_ReadOnlySet(OriginatingProjectLanguage language, bool signaturesOnly) - { - var metadataSource = """ + await GenerateAndVerifySourceAsync(""" public struct S { - public readonly int P { get => 123; set {} } + public int P { get => 123; readonly set {} } } - """; - var symbolName = "S.P"; + """, "S.P", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + } + [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] + public async Task TestStructProperty_ReadOnlyGet_ReadOnlySet(OriginatingProjectLanguage language, bool signaturesOnly) + { var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -4836,22 +4624,19 @@ public readonly int [|P|] _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); - } - - [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] - public async Task TestStructIndexer_ReadOnlyGet(OriginatingProjectLanguage language, bool signaturesOnly) - { - var metadataSource = """ + await GenerateAndVerifySourceAsync(""" public struct S { - public readonly int this[int i] => i; + public readonly int P { get => 123; set {} } } - """; - var symbolName = "S.Item"; + """, "S.P", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + } + [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] + public async Task TestStructIndexer_ReadOnlyGet(OriginatingProjectLanguage language, bool signaturesOnly) + { var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -4924,22 +4709,19 @@ public struct S _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); - } - - [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] - public async Task TestStructIndexer_ReadOnlyGet_Set(OriginatingProjectLanguage language, bool signaturesOnly) - { - var metadataSource = """ + await GenerateAndVerifySourceAsync(""" public struct S { - public int this[int i] { readonly get => i; set {} } + public readonly int this[int i] => i; } - """; - var symbolName = "S.Item"; + """, "S.Item", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + } + [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] + public async Task TestStructIndexer_ReadOnlyGet_Set(OriginatingProjectLanguage language, bool signaturesOnly) + { var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -5030,22 +4812,19 @@ readonly get _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); - } - - [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] - public async Task TestStruct_ReadOnlyEvent(OriginatingProjectLanguage language, bool signaturesOnly) - { - var metadataSource = """ + await GenerateAndVerifySourceAsync(""" public struct S { - public readonly event System.Action E { add {} remove {} } + public int this[int i] { readonly get => i; set {} } } - """; - var symbolName = "S.E"; + """, "S.Item", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + } + [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] + public async Task TestStruct_ReadOnlyEvent(OriginatingProjectLanguage language, bool signaturesOnly) + { var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -5134,22 +4913,19 @@ public readonly event Action [|E|] _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); - } - - [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] - public async Task TestReadOnlyStruct_ReadOnlyEvent(OriginatingProjectLanguage language, bool signaturesOnly) - { - var metadataSource = """ + await GenerateAndVerifySourceAsync(""" - public readonly struct S + public struct S { - public event System.Action E { add {} remove {} } + public readonly event System.Action E { add {} remove {} } } - """; - var symbolName = "S.E"; + """, "S.E", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + } + [WpfTheory, WorkItem("https://github.com/dotnet/roslyn/issues/34650"), CombinatorialData] + public async Task TestReadOnlyStruct_ReadOnlyEvent(OriginatingProjectLanguage language, bool signaturesOnly) + { var expected = (language, signaturesOnly) switch { (OriginatingProjectLanguage.CSharp, true) => $$""" @@ -5239,7 +5015,14 @@ public event Action [|E|] _ => throw ExceptionUtilities.Unreachable(), }; - await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, signaturesOnly: signaturesOnly); + await GenerateAndVerifySourceAsync(""" + + public readonly struct S + { + public event System.Action E { add {} remove {} } + } + + """, "S.E", ToLanguageName(language), expected, signaturesOnly: signaturesOnly); } [WpfFact] @@ -5261,17 +5044,6 @@ void M() } } """; - var expected = $$""" - #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null - // {{CodeAnalysisResources.InMemoryAssembly}} - #endregion - - public class [|TestType|] where T : notnull - { - public TestType(); - } - """; - using var context = TestContext.Create( LanguageNames.CSharp, [metadata], @@ -5282,7 +5054,16 @@ public class [|TestType|] where T : notnull var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); - TestContext.VerifyResult(metadataAsSourceFile, expected); + TestContext.VerifyResult(metadataAsSourceFile, $$""" + #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + // {{CodeAnalysisResources.InMemoryAssembly}} + #endregion + + public class [|TestType|] where T : notnull + { + public TestType(); + } + """); } [WpfFact] @@ -5307,19 +5088,6 @@ void M() } } """; - var expected = $$""" - #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null - // {{CodeAnalysisResources.InMemoryAssembly}} - #endregion - - public class TestType - { - public TestType(); - - public void [|M|]() where T : notnull; - } - """; - using var context = TestContext.Create( LanguageNames.CSharp, [metadata], @@ -5330,7 +5098,18 @@ public class TestType var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); - TestContext.VerifyResult(metadataAsSourceFile, expected); + TestContext.VerifyResult(metadataAsSourceFile, $$""" + #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + // {{CodeAnalysisResources.InMemoryAssembly}} + #endregion + + public class TestType + { + public TestType(); + + public void [|M|]() where T : notnull; + } + """); } [WpfFact] @@ -5349,14 +5128,6 @@ class C } } """; - var expected = $""" - #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null - // {CodeAnalysisResources.InMemoryAssembly} - #endregion - - public delegate void [|D|]() where T : notnull; - """; - using var context = TestContext.Create( LanguageNames.CSharp, [metadata], @@ -5367,10 +5138,16 @@ class C var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); - TestContext.VerifyResult(metadataAsSourceFile, expected); - } + TestContext.VerifyResult(metadataAsSourceFile, $""" + #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + // {CodeAnalysisResources.InMemoryAssembly} + #endregion - [WpfFact] + public delegate void [|D|]() where T : notnull; + """); + } + + [WpfFact] public async Task TestNullableEnableDisable1() { var metadata = """ @@ -5402,7 +5179,17 @@ void M() } } """; - var expected = $$""" + using var context = TestContext.Create( + LanguageNames.CSharp, + [metadata], + includeXmlDocComments: false, + languageVersion: "8", + sourceWithSymbolReference: sourceWithSymbolReference, + metadataLanguageVersion: "8"); + + var navigationSymbol = await context.GetNavigationSymbolAsync(); + var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); + TestContext.VerifyResult(metadataAsSourceFile, $$""" #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {{CodeAnalysisResources.InMemoryAssembly}} #endregion @@ -5419,19 +5206,7 @@ public class TestType #nullable enable } - """; - - using var context = TestContext.Create( - LanguageNames.CSharp, - [metadata], - includeXmlDocComments: false, - languageVersion: "8", - sourceWithSymbolReference: sourceWithSymbolReference, - metadataLanguageVersion: "8"); - - var navigationSymbol = await context.GetNavigationSymbolAsync(); - var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); - TestContext.VerifyResult(metadataAsSourceFile, expected); + """); } [WpfFact] @@ -5464,7 +5239,17 @@ void M() } } """; - var expected = $$""" + using var context = TestContext.Create( + LanguageNames.CSharp, + [metadata], + includeXmlDocComments: false, + languageVersion: "8", + sourceWithSymbolReference: sourceWithSymbolReference, + metadataLanguageVersion: "8"); + + var navigationSymbol = await context.GetNavigationSymbolAsync(); + var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); + TestContext.VerifyResult(metadataAsSourceFile, $$""" #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {{CodeAnalysisResources.InMemoryAssembly}} #endregion @@ -5480,19 +5265,7 @@ public class TestType #nullable enable public void M2(string s); } - """; - - using var context = TestContext.Create( - LanguageNames.CSharp, - [metadata], - includeXmlDocComments: false, - languageVersion: "8", - sourceWithSymbolReference: sourceWithSymbolReference, - metadataLanguageVersion: "8"); - - var navigationSymbol = await context.GetNavigationSymbolAsync(); - var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); - TestContext.VerifyResult(metadataAsSourceFile, expected); + """); } [WpfFact] @@ -5531,7 +5304,17 @@ void M() } } """; - var expected = $$""" + using var context = TestContext.Create( + LanguageNames.CSharp, + [metadata], + includeXmlDocComments: false, + languageVersion: "8", + sourceWithSymbolReference: sourceWithSymbolReference, + metadataLanguageVersion: "8"); + + var navigationSymbol = await context.GetNavigationSymbolAsync(); + var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); + TestContext.VerifyResult(metadataAsSourceFile, $$""" #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {{CodeAnalysisResources.InMemoryAssembly}} #endregion @@ -5549,19 +5332,7 @@ public class TestType #nullable enable } - """; - - using var context = TestContext.Create( - LanguageNames.CSharp, - [metadata], - includeXmlDocComments: false, - languageVersion: "8", - sourceWithSymbolReference: sourceWithSymbolReference, - metadataLanguageVersion: "8"); - - var navigationSymbol = await context.GetNavigationSymbolAsync(); - var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); - TestContext.VerifyResult(metadataAsSourceFile, expected); + """); } [WpfFact] @@ -5590,7 +5361,17 @@ void M() } } """; - var expected = $$""" + using var context = TestContext.Create( + LanguageNames.CSharp, + [metadata], + includeXmlDocComments: false, + languageVersion: "8", + sourceWithSymbolReference: sourceWithSymbolReference, + metadataLanguageVersion: "8"); + + var navigationSymbol = await context.GetNavigationSymbolAsync(); + var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); + TestContext.VerifyResult(metadataAsSourceFile, $$""" #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {{CodeAnalysisResources.InMemoryAssembly}} #endregion @@ -5605,19 +5386,7 @@ public class TestType public void [|M1|](ICloneable s); } - """; - - using var context = TestContext.Create( - LanguageNames.CSharp, - [metadata], - includeXmlDocComments: false, - languageVersion: "8", - sourceWithSymbolReference: sourceWithSymbolReference, - metadataLanguageVersion: "8"); - - var navigationSymbol = await context.GetNavigationSymbolAsync(); - var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); - TestContext.VerifyResult(metadataAsSourceFile, expected); + """); } [WpfFact] @@ -5647,7 +5416,17 @@ void M() } } """; - var expected = $$""" + using var context = TestContext.Create( + LanguageNames.CSharp, + [metadata], + includeXmlDocComments: false, + languageVersion: "8", + sourceWithSymbolReference: sourceWithSymbolReference, + metadataLanguageVersion: "8"); + + var navigationSymbol = await context.GetNavigationSymbolAsync(); + var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); + TestContext.VerifyResult(metadataAsSourceFile, $$""" #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {{CodeAnalysisResources.InMemoryAssembly}} #endregion @@ -5662,19 +5441,7 @@ public class TestType public void [|M1|](ICloneable s); } - """; - - using var context = TestContext.Create( - LanguageNames.CSharp, - [metadata], - includeXmlDocComments: false, - languageVersion: "8", - sourceWithSymbolReference: sourceWithSymbolReference, - metadataLanguageVersion: "8"); - - var navigationSymbol = await context.GetNavigationSymbolAsync(); - var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); - TestContext.VerifyResult(metadataAsSourceFile, expected); + """); } [WpfFact] @@ -5703,7 +5470,17 @@ void M() } } """; - var expected = $$""" + using var context = TestContext.Create( + LanguageNames.CSharp, + [metadata], + includeXmlDocComments: false, + languageVersion: "8", + sourceWithSymbolReference: sourceWithSymbolReference, + metadataLanguageVersion: "8"); + + var navigationSymbol = await context.GetNavigationSymbolAsync(); + var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); + TestContext.VerifyResult(metadataAsSourceFile, $$""" #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {{CodeAnalysisResources.InMemoryAssembly}} #endregion @@ -5716,19 +5493,7 @@ public class TestType public void [|M1|](T? s) where T : class; } - """; - - using var context = TestContext.Create( - LanguageNames.CSharp, - [metadata], - includeXmlDocComments: false, - languageVersion: "8", - sourceWithSymbolReference: sourceWithSymbolReference, - metadataLanguageVersion: "8"); - - var navigationSymbol = await context.GetNavigationSymbolAsync(); - var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); - TestContext.VerifyResult(metadataAsSourceFile, expected); + """); } [WpfFact] @@ -5757,7 +5522,17 @@ void M() } } """; - var expected = $$""" + using var context = TestContext.Create( + LanguageNames.CSharp, + [metadata], + includeXmlDocComments: false, + languageVersion: "8", + sourceWithSymbolReference: sourceWithSymbolReference, + metadataLanguageVersion: "8"); + + var navigationSymbol = await context.GetNavigationSymbolAsync(); + var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); + TestContext.VerifyResult(metadataAsSourceFile, $$""" #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {{CodeAnalysisResources.InMemoryAssembly}} #endregion @@ -5770,19 +5545,7 @@ public class TestType public void [|M1|](T s) where T : class; } - """; - - using var context = TestContext.Create( - LanguageNames.CSharp, - [metadata], - includeXmlDocComments: false, - languageVersion: "8", - sourceWithSymbolReference: sourceWithSymbolReference, - metadataLanguageVersion: "8"); - - var navigationSymbol = await context.GetNavigationSymbolAsync(); - var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); - TestContext.VerifyResult(metadataAsSourceFile, expected); + """); } [WpfFact] @@ -5811,19 +5574,6 @@ void M() } } """; - var expected = $$""" - #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null - // {{CodeAnalysisResources.InMemoryAssembly}} - #endregion - - public class TestType - { - public TestType(); - - public void [|M1|](T? s) where T : struct; - } - """; - using var context = TestContext.Create( LanguageNames.CSharp, [metadata], @@ -5834,7 +5584,18 @@ public class TestType var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); - TestContext.VerifyResult(metadataAsSourceFile, expected); + TestContext.VerifyResult(metadataAsSourceFile, $$""" + #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + // {{CodeAnalysisResources.InMemoryAssembly}} + #endregion + + public class TestType + { + public TestType(); + + public void [|M1|](T? s) where T : struct; + } + """); } [WpfFact] @@ -5863,19 +5624,6 @@ void M() } } """; - var expected = $$""" - #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null - // {{CodeAnalysisResources.InMemoryAssembly}} - #endregion - - public class TestType - { - public TestType(); - - public void [|M1|](T s) where T : struct; - } - """; - using var context = TestContext.Create( LanguageNames.CSharp, [metadata], @@ -5886,7 +5634,18 @@ public class TestType var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); - TestContext.VerifyResult(metadataAsSourceFile, expected); + TestContext.VerifyResult(metadataAsSourceFile, $$""" + #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + // {{CodeAnalysisResources.InMemoryAssembly}} + #endregion + + public class TestType + { + public TestType(); + + public void [|M1|](T s) where T : struct; + } + """); } [WpfFact] @@ -5915,19 +5674,6 @@ void M() } } """; - var expected = $$""" - #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null - // {{CodeAnalysisResources.InMemoryAssembly}} - #endregion - - public class TestType - { - public TestType(); - - public void [|M1|](T s); - } - """; - using var context = TestContext.Create( LanguageNames.CSharp, [metadata], @@ -5938,7 +5684,18 @@ public class TestType var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); - TestContext.VerifyResult(metadataAsSourceFile, expected); + TestContext.VerifyResult(metadataAsSourceFile, $$""" + #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + // {{CodeAnalysisResources.InMemoryAssembly}} + #endregion + + public class TestType + { + public TestType(); + + public void [|M1|](T s); + } + """); } [WpfFact] @@ -5965,19 +5722,6 @@ void M() } } """; - var expected = $$""" - #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null - // {{CodeAnalysisResources.InMemoryAssembly}} - #endregion - - public class TestType - { - public TestType(); - - public void [|M1|](T s); - } - """; - using var context = TestContext.Create( LanguageNames.CSharp, [metadata], @@ -5988,7 +5732,18 @@ public class TestType var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); - TestContext.VerifyResult(metadataAsSourceFile, expected); + TestContext.VerifyResult(metadataAsSourceFile, $$""" + #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + // {{CodeAnalysisResources.InMemoryAssembly}} + #endregion + + public class TestType + { + public TestType(); + + public void [|M1|](T s); + } + """); } [WpfFact] @@ -6026,7 +5781,17 @@ void M() } } """; - var expected = $$""" + using var context = TestContext.Create( + LanguageNames.CSharp, + [metadata], + includeXmlDocComments: false, + languageVersion: "8", + sourceWithSymbolReference: sourceWithSymbolReference, + metadataLanguageVersion: "8"); + + var navigationSymbol = await context.GetNavigationSymbolAsync(); + var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); + TestContext.VerifyResult(metadataAsSourceFile, $$""" #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {{CodeAnalysisResources.InMemoryAssembly}} #endregion @@ -6046,19 +5811,7 @@ public class TestType #nullable enable } } - """; - - using var context = TestContext.Create( - LanguageNames.CSharp, - [metadata], - includeXmlDocComments: false, - languageVersion: "8", - sourceWithSymbolReference: sourceWithSymbolReference, - metadataLanguageVersion: "8"); - - var navigationSymbol = await context.GetNavigationSymbolAsync(); - var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); - TestContext.VerifyResult(metadataAsSourceFile, expected); + """); } [WpfFact] @@ -6102,7 +5855,17 @@ void M() } } """; - var expected = $$""" + using var context = TestContext.Create( + LanguageNames.CSharp, + [metadata], + includeXmlDocComments: false, + languageVersion: "8", + sourceWithSymbolReference: sourceWithSymbolReference, + metadataLanguageVersion: "8"); + + var navigationSymbol = await context.GetNavigationSymbolAsync(); + var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); + TestContext.VerifyResult(metadataAsSourceFile, $$""" #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {{CodeAnalysisResources.InMemoryAssembly}} #endregion @@ -6126,19 +5889,7 @@ public class Nested #nullable enable } } - """; - - using var context = TestContext.Create( - LanguageNames.CSharp, - [metadata], - includeXmlDocComments: false, - languageVersion: "8", - sourceWithSymbolReference: sourceWithSymbolReference, - metadataLanguageVersion: "8"); - - var navigationSymbol = await context.GetNavigationSymbolAsync(); - var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); - TestContext.VerifyResult(metadataAsSourceFile, expected); + """); } [WpfFact] @@ -6165,19 +5916,6 @@ void M() } } """; - var expected = $$""" - #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null - // {{CodeAnalysisResources.InMemoryAssembly}} - #endregion - - public class TestType - { - public TestType(); - - public void [|M1|](dynamic s); - } - """; - using var context = TestContext.Create( LanguageNames.CSharp, [metadata], @@ -6188,13 +5926,23 @@ public class TestType var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); - TestContext.VerifyResult(metadataAsSourceFile, expected); + TestContext.VerifyResult(metadataAsSourceFile, $$""" + #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + // {{CodeAnalysisResources.InMemoryAssembly}} + #endregion + + public class TestType + { + public TestType(); + + public void [|M1|](dynamic s); + } + """); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/22431")] - public async Task TestCDATAComment() - { - var source = """ + public Task TestCDATAComment() + => GenerateAndVerifySourceAsync(""" public enum BinaryOperatorKind { @@ -6204,9 +5952,7 @@ public enum BinaryOperatorKind LeftShift = 0x8, } - """; - var symbolName = "BinaryOperatorKind.LeftShift"; - var expectedCS = $$""" + """, "BinaryOperatorKind.LeftShift", LanguageNames.CSharp, $$""" #region {{FeaturesResources.Assembly}} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {{CodeAnalysisResources.InMemoryAssembly}} #endregion @@ -6218,7 +5964,5 @@ public enum BinaryOperatorKind // Represents the '<<' operator. [|LeftShift|] = 8 } - """; - await GenerateAndVerifySourceAsync(source, symbolName, LanguageNames.CSharp, expectedCS, includeXmlDocComments: true); - } + """, includeXmlDocComments: true); } diff --git a/src/EditorFeatures/Test/RenameTracking/RenameTrackingTaggerProviderTests.cs b/src/EditorFeatures/Test/RenameTracking/RenameTrackingTaggerProviderTests.cs index 19b887caa37c0..5df8404bdbf88 100644 --- a/src/EditorFeatures/Test/RenameTracking/RenameTrackingTaggerProviderTests.cs +++ b/src/EditorFeatures/Test/RenameTracking/RenameTrackingTaggerProviderTests.cs @@ -629,14 +629,13 @@ class [|$$ustom|]Attribute : Attribute using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp); state.EditorOperations.InsertText("C"); await state.AssertTag("ustomAttribute", "CustomAttribute", invokeAction: true); - var expectedCode = """ + Assert.Equal(""" using System; class CustomAttribute : Attribute { } - """; - Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText()); + """, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText()); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/21657")] @@ -652,14 +651,13 @@ End Class using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic); state.EditorOperations.InsertText("C"); await state.AssertTag("ustomAttribute", "CustomAttribute", invokeAction: true); - var expectedCode = """ + Assert.Equal(""" Import System; Public Class CustomAttribute Inherits Attribute End Class - """; - Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText()); + """, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText()); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/21657")] @@ -675,14 +673,13 @@ End Class using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic); state.EditorOperations.InsertText("C"); await state.AssertTag("ustomATTRIBUTE", "CustomATTRIBUTE", invokeAction: true); - var expectedCode = """ + Assert.Equal(""" Import System; Public Class CustomATTRIBUTE Inherits Attribute End Class - """; - Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText()); + """, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText()); } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/21657")] @@ -698,14 +695,13 @@ End Class using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic); state.EditorOperations.InsertText("C"); await state.AssertTag("ustomattribute", "Customattribute", invokeAction: true); - var expectedCode = """ + Assert.Equal(""" Import System; Public Class Customattribute Inherits Attribute End Class - """; - Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText()); + """, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText()); } [WpfFact] @@ -724,16 +720,14 @@ public Cat() await state.AssertTag("Cat", "Cats", invokeAction: true); Assert.Equal(1, state.RefactorNotifyService.OnBeforeSymbolRenamedCount); Assert.Equal(1, state.RefactorNotifyService.OnAfterSymbolRenamedCount); - - var expectedCode = """ + Assert.Equal(""" class Cats { public Cats() { } } - """; - Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText()); + """, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText()); state.AssertNoNotificationMessage(); await state.AssertNoTag(); @@ -758,16 +752,14 @@ public Cat() // Make sure the rename didn't proceed Assert.Equal(0, state.RefactorNotifyService.OnAfterSymbolRenamedCount); await state.AssertNoTag(); - - var expectedCode = """ + Assert.Equal(""" class Cat { public Cat() { } } - """; - Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText()); + """, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText()); state.AssertNotificationMessage(); } @@ -792,15 +784,14 @@ public Cat() state.AssertNotificationMessage(); // Make sure the rename completed - var expectedCode = """ + Assert.Equal(""" class Cats { public Cats() { } } - """; - Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText()); + """, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText()); await state.AssertNoTag(); } @@ -1008,7 +999,7 @@ void M(int x) await state.AssertTag("M", "Mat", invokeAction: true); // Make sure the rename completed - var expectedCode = """ + Assert.Equal(""" class C { void Mat() @@ -1020,8 +1011,7 @@ void Mat(int x) { } } - """; - Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText()); + """, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText()); await state.AssertNoTag(); } @@ -1043,7 +1033,7 @@ class C await state.AssertTag("M", "Mat", invokeAction: true); // Make sure the rename completed - var expectedCode = """ + Assert.Equal(""" class C { void Mat() @@ -1051,8 +1041,7 @@ void Mat() nameof(Mat).ToString(); } } - """; - Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText()); + """, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText()); await state.AssertNoTag(); } @@ -1078,7 +1067,7 @@ void M(int x) await state.AssertTag("M", "Mat", invokeAction: true); // Make sure the rename completed - var expectedCode = """ + Assert.Equal(""" class C { void Mat() @@ -1090,8 +1079,7 @@ void M(int x) { } } - """; - Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText()); + """, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText()); await state.AssertNoTag(); } @@ -1515,15 +1503,14 @@ class C<T> where T : $$unmanaged await state.AssertTag("unmanaged", "myunmanaged", invokeAction: true); // Make sure the rename completed - var expectedCode = """ + Assert.Equal(""" interface myunmanaged { } class C where T : myunmanaged { } - """; - Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText()); + """, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText()); await state.AssertNoTag(); } } diff --git a/src/EditorFeatures/Test/RenameTracking/RenameTrackingTestState.cs b/src/EditorFeatures/Test/RenameTracking/RenameTrackingTestState.cs index a8e4384a24247..9ac0a85996e25 100644 --- a/src/EditorFeatures/Test/RenameTracking/RenameTrackingTestState.cs +++ b/src/EditorFeatures/Test/RenameTracking/RenameTrackingTestState.cs @@ -12,7 +12,6 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; -using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; @@ -118,12 +117,13 @@ public RenameTrackingTestState( private static EditorTestWorkspace CreateTestWorkspace(string code, string languageName) { - return CreateTestWorkspace(string.Format(@" - - - {1} - -", languageName, code)); + return CreateTestWorkspace(string.Format(""" + + + {1} + + + """, languageName, code)); } private static EditorTestWorkspace CreateTestWorkspace(string xml) diff --git a/src/EditorFeatures/Test/Snippets/RoslynLSPSnippetConvertTests.cs b/src/EditorFeatures/Test/Snippets/RoslynLSPSnippetConvertTests.cs index 86fddcb98fb11..73a5607f1ba22 100644 --- a/src/EditorFeatures/Test/Snippets/RoslynLSPSnippetConvertTests.cs +++ b/src/EditorFeatures/Test/Snippets/RoslynLSPSnippetConvertTests.cs @@ -26,372 +26,330 @@ public class RoslynLSPSnippetConvertTests [Fact] public Task TestExtendSnippetTextChangeForwardsForCaret() { - var markup = -@"[|if ({|placeholder:true|}) -{ -}|] $$"; - - var expectedLSPSnippet = -@"if (${1:true}) -{ -} $0"; - - return TestAsync(markup, expectedLSPSnippet); + return TestAsync(""" + [|if ({|placeholder:true|}) + { + }|] $$ + """, """ + if (${1:true}) + { + } $0 + """); } [Fact] public Task TestExtendSnippetTextChangeBackwardsForCaret() { - var markup = -@"$$ [|if ({|placeholder:true|}) -{ -}|]"; - - var expectedLSPSnippet = -@"$0 if (${1:true}) -{ -}"; - - return TestAsync(markup, expectedLSPSnippet); + return TestAsync(""" + $$ [|if ({|placeholder:true|}) + { + }|] + """, """ + $0 if (${1:true}) + { + } + """); } [Fact] public Task TestExtendSnippetTextChangeForwardsForPlaceholder() { - var markup = -@"[|if (true) -{$$ -}|] {|placeholder:test|}"; - - var expectedLSPSnippet = -@"if (true) -{$0 -} ${1:test}"; - - return TestAsync(markup, expectedLSPSnippet); + return TestAsync(""" + [|if (true) + {$$ + }|] {|placeholder:test|} + """, """ + if (true) + {$0 + } ${1:test} + """); } [Fact] public Task TestExtendSnippetTextChangeBackwardsForPlaceholder() { - var markup = -@"{|placeholder:test|} [|if (true) -{$$ -}|]"; - - var expectedLSPSnippet = -@"${1:test} if (true) -{$0 -}"; - - return TestAsync(markup, expectedLSPSnippet); + return TestAsync(""" + {|placeholder:test|} [|if (true) + {$$ + }|] + """, """ + ${1:test} if (true) + {$0 + } + """); } [Fact] public Task TestExtendSnippetTextChangeForwardsForPlaceholderThenCaret() { - var markup = -@"[|if (true) -{ -}|] {|placeholder:test|} $$"; - - var expectedLSPSnippet = -@"if (true) -{ -} ${1:test} $0"; - - return TestAsync(markup, expectedLSPSnippet); + return TestAsync(""" + [|if (true) + { + }|] {|placeholder:test|} $$ + """, """ + if (true) + { + } ${1:test} $0 + """); } [Fact] public Task TestExtendSnippetTextChangeForwardsForCaretThenPlaceholder() { - var markup = -@"[|if (true) -{ -}|] $$ {|placeholder:test|}"; - - var expectedLSPSnippet = -@"if (true) -{ -} $0 ${1:test}"; - - return TestAsync(markup, expectedLSPSnippet); + return TestAsync(""" + [|if (true) + { + }|] $$ {|placeholder:test|} + """, """ + if (true) + { + } $0 ${1:test} + """); } [Fact] public Task TestExtendSnippetTextChangeBackwardsForPlaceholderThenCaret() { - var markup = -@"{|placeholder:test|} $$ [|if (true) -{ -}|]"; - - var expectedLSPSnippet = -@"${1:test} $0 if (true) -{ -}"; - - return TestAsync(markup, expectedLSPSnippet); + return TestAsync(""" + {|placeholder:test|} $$ [|if (true) + { + }|] + """, """ + ${1:test} $0 if (true) + { + } + """); } [Fact] public Task TestExtendSnippetTextChangeBackwardsForCaretThenPlaceholder() { - var markup = -@"$$ {|placeholder:test|} [|if (true) -{ -}|]"; - - var expectedLSPSnippet = -@"$0 ${1:test} if (true) -{ -}"; - - return TestAsync(markup, expectedLSPSnippet); + return TestAsync(""" + $$ {|placeholder:test|} [|if (true) + { + }|] + """, """ + $0 ${1:test} if (true) + { + } + """); } [Fact] public Task TestExtendSnippetTextChangeBackwardsForCaretForwardsForPlaceholder() { - var markup = -@"$$ [|if (true) -{ -}|] {|placeholder:test|}"; - - var expectedLSPSnippet = -@"$0 if (true) -{ -} ${1:test}"; - - return TestAsync(markup, expectedLSPSnippet); + return TestAsync(""" + $$ [|if (true) + { + }|] {|placeholder:test|} + """, """ + $0 if (true) + { + } ${1:test} + """); } [Fact] public Task TestExtendSnippetTextChangeBackwardsForPlaceholderForwardsForCaret() { - var markup = -@"{|placeholder:test|} [|if (true) -{ -}|] $$"; - - var expectedLSPSnippet = -@"${1:test} if (true) -{ -} $0"; - - return TestAsync(markup, expectedLSPSnippet); + return TestAsync(""" + {|placeholder:test|} [|if (true) + { + }|] $$ + """, """ + ${1:test} if (true) + { + } $0 + """); } [Fact] public Task TestExtendSnippetTextChangeInMethodForwardsForCaret() { - var markup = -@"public void Method() -{ - [|if ({|placeholder:true|}) - { - }|] $$ -}"; - - var expectedLSPSnippet = -@"if (${1:true}) - { - } $0"; - - return TestAsync(markup, expectedLSPSnippet); + return TestAsync(""" + public void Method() + { + [|if ({|placeholder:true|}) + { + }|] $$ + } + """, """ + if (${1:true}) + { + } $0 + """); } [Fact] public Task TestExtendSnippetTextChangeInMethodBackwardsForCaret() { - var markup = -@"public void Method() -{ - $$ [|if ({|placeholder:true|}) - { - }|] -}"; - - var expectedLSPSnippet = -@"$0 if (${1:true}) - { - }"; - - return TestAsync(markup, expectedLSPSnippet); + return TestAsync(""" + public void Method() + { + $$ [|if ({|placeholder:true|}) + { + }|] + } + """, """ + $0 if (${1:true}) + { + } + """); } [Fact] public Task TestExtendSnippetTextChangeInMethodForwardsForPlaceholder() { - var markup = -@"public void Method() -{ - [|if (true) - {$$ - }|] {|placeholder:test|} -}"; - - var expectedLSPSnippet = -@"if (true) - {$0 - } ${1:test}"; - - return TestAsync(markup, expectedLSPSnippet); + return TestAsync(""" + public void Method() + { + [|if (true) + {$$ + }|] {|placeholder:test|} + } + """, """ + if (true) + {$0 + } ${1:test} + """); } [Fact] public Task TestExtendSnippetTextChangeInMethodBackwardsForPlaceholder() { - var markup = -@"public void Method() -{ - {|placeholder:test|} [|if (true) - {$$ - }|]"; - - var expectedLSPSnippet = -@"${1:test} if (true) - {$0 - }"; - - return TestAsync(markup, expectedLSPSnippet); + return TestAsync(""" + public void Method() + { + {|placeholder:test|} [|if (true) + {$$ + }|] + """, """ + ${1:test} if (true) + {$0 + } + """); } [Fact] public Task TestExtendSnippetTextChangeInMethodForwardsForPlaceholderThenCaret() { - var markup = -@"public void Method() -{ - [|if (true) - { - }|] {|placeholder:test|} $$ -}"; - - var expectedLSPSnippet = -@"if (true) - { - } ${1:test} $0"; - - return TestAsync(markup, expectedLSPSnippet); + return TestAsync(""" + public void Method() + { + [|if (true) + { + }|] {|placeholder:test|} $$ + } + """, """ + if (true) + { + } ${1:test} $0 + """); } [Fact] public Task TestExtendSnippetTextChangeInMethodForwardsForCaretThenPlaceholder() { - var markup = -@"public void Method() -{ - [|if (true) - { - }|] $$ {|placeholder:test|} -}"; - - var expectedLSPSnippet = -@"if (true) - { - } $0 ${1:test}"; - - return TestAsync(markup, expectedLSPSnippet); + return TestAsync(""" + public void Method() + { + [|if (true) + { + }|] $$ {|placeholder:test|} + } + """, """ + if (true) + { + } $0 ${1:test} + """); } [Fact] public Task TestExtendSnippetTextChangeInMethodBackwardsForPlaceholderThenCaret() { - var markup = -@"public void Method() -{ - {|placeholder:test|} $$ [|if (true) - { - }|] -}"; - - var expectedLSPSnippet = -@"${1:test} $0 if (true) - { - }"; - - return TestAsync(markup, expectedLSPSnippet); + return TestAsync(""" + public void Method() + { + {|placeholder:test|} $$ [|if (true) + { + }|] + } + """, """ + ${1:test} $0 if (true) + { + } + """); } [Fact] public Task TestExtendSnippetTextChangeInMethodBackwardsForCaretThenPlaceholder() { - var markup = -@"public void Method() -{ - $$ {|placeholder:test|} [|if (true) - { - }|] -}"; - - var expectedLSPSnippet = -@"$0 ${1:test} if (true) - { - }"; - - return TestAsync(markup, expectedLSPSnippet); + return TestAsync(""" + public void Method() + { + $$ {|placeholder:test|} [|if (true) + { + }|] + } + """, """ + $0 ${1:test} if (true) + { + } + """); } [Fact] public Task TestExtendSnippetTextChangeInMethodBackwardsForCaretForwardsForPlaceholder() { - var markup = -@"public void Method() -{ - $$ [|if (true) - { - }|] {|placeholder:test|} -}"; - - var expectedLSPSnippet = -@"$0 if (true) - { - } ${1:test}"; - - return TestAsync(markup, expectedLSPSnippet); + return TestAsync(""" + public void Method() + { + $$ [|if (true) + { + }|] {|placeholder:test|} + } + """, """ + $0 if (true) + { + } ${1:test} + """); } [Fact] public Task TestExtendSnippetTextChangeInMethodBackwardsForPlaceholderForwardsForCaret() { - var markup = -@"public void Method() -{ - {|placeholder:test|} [|if (true) - { - }|] $$ -}"; - - var expectedLSPSnippet = -@"${1:test} if (true) - { - } $0"; - - return TestAsync(markup, expectedLSPSnippet); + return TestAsync(""" + public void Method() + { + {|placeholder:test|} [|if (true) + { + }|] $$ + } + """, """ + ${1:test} if (true) + { + } $0 + """); } [Fact] public Task TestExtendSnippetTextChangeInMethodWithCodeBeforeAndAfterBackwardsForPlaceholderForwardsForCaret() { - var markup = -@"public void Method() -{ - var x = 5; - {|placeholder:test|} [|if (true) - { - }|] $$ - - x = 3; -}"; - - var expectedLSPSnippet = -@"${1:test} if (true) - { - } $0"; + return TestAsync(""" + public void Method() + { + var x = 5; + {|placeholder:test|} [|if (true) + { + }|] $$ - return TestAsync(markup, expectedLSPSnippet); + x = 3; + } + """, """ + ${1:test} if (true) + { + } $0 + """); } [Fact] @@ -423,61 +381,55 @@ public void TestExtendTextChangeReplacement() [Fact] public Task TestForLoopSnippet() { - var markup = -@"[|for (var {|placeholder1:i|} = 0; {|placeholder1:i|} < {|placeholder2:length|}; {|placeholder1:i|}++) -{$$ -}|]"; - - var expectedLSPSnippet = -@"for (var ${1:i} = 0; ${1:i} < ${2:length}; ${1:i}++) -{$0 -}"; - - return TestAsync(markup, expectedLSPSnippet); + return TestAsync(""" + [|for (var {|placeholder1:i|} = 0; {|placeholder1:i|} < {|placeholder2:length|}; {|placeholder1:i|}++) + {$$ + }|] + """, """ + for (var ${1:i} = 0; ${1:i} < ${2:length}; ${1:i}++) + {$0 + } + """); } [Fact] public Task TestIfSnippetSamePlaceholderCursorLocation() { - var markup = -@"public void Method() -{ - var x = 5; - [|if ({|placeholder:true|}$$) - { - }|] - - x = 3; -}"; - - var expectedLSPSnippet = -@"if (${1:true}$0) - { - }"; + return TestAsync(""" + public void Method() + { + var x = 5; + [|if ({|placeholder:true|}$$) + { + }|] - return TestAsync(markup, expectedLSPSnippet); + x = 3; + } + """, """ + if (${1:true}$0) + { + } + """); } [Fact] public Task TestIfSnippetSameCursorPlaceholderLocation() { - var markup = -@"public void Method() -{ - var x = 5; - [|if ($${|placeholder:true|}) - { - }|] - - x = 3; -}"; - - var expectedLSPSnippet = -@"if ($0${1:true}) - { - }"; + return TestAsync(""" + public void Method() + { + var x = 5; + [|if ($${|placeholder:true|}) + { + }|] - return TestAsync(markup, expectedLSPSnippet); + x = 3; + } + """, """ + if ($0${1:true}) + { + } + """); } #endregion diff --git a/src/EditorFeatures/Test/StackTraceExplorer/StackTraceExplorerTests.cs b/src/EditorFeatures/Test/StackTraceExplorer/StackTraceExplorerTests.cs index 9275291fc7981..ad44dd3ff8b53 100644 --- a/src/EditorFeatures/Test/StackTraceExplorer/StackTraceExplorerTests.cs +++ b/src/EditorFeatures/Test/StackTraceExplorer/StackTraceExplorerTests.cs @@ -75,15 +75,17 @@ public Task TestSymbolFound_DebuggerLine() { return TestSymbolFoundAsync( "ConsoleApp4.dll!ConsoleApp4.MyClass.M()", - @"using System; + """ + using System; -namespace ConsoleApp4 -{ - class MyClass - { - void [|M|]() {} - } -}"); + namespace ConsoleApp4 + { + class MyClass + { + void [|M|]() {} + } + } + """); } [Theory] @@ -105,15 +107,17 @@ public Task TestSpecialTypes(string type, string typeName) { return TestSymbolFoundAsync( $"at ConsoleApp.MyClass.M({typeName} value)", - @$"using System; + $$""" + using System; -namespace ConsoleApp -{{ - class MyClass - {{ - void [|M|]({type} value) {{}} - }} -}}"); + namespace ConsoleApp + { + class MyClass + { + void [|M|]({{type}} value) {} + } + } + """); } [Fact] @@ -121,15 +125,17 @@ public Task TestSymbolFound_DebuggerLine_SingleSimpleClassParam() { return TestSymbolFoundAsync( "ConsoleApp4.dll!ConsoleApp4.MyClass.M(String s)", - @"using System; + """ + using System; -namespace ConsoleApp4 -{ - class MyClass - { - void [|M|](string s) {} - } -}"); + namespace ConsoleApp4 + { + class MyClass + { + void [|M|](string s) {} + } + } + """); } [Fact] @@ -137,15 +143,17 @@ public Task TestSymbolFound_ExceptionLine() { return TestSymbolFoundAsync( "at ConsoleApp4.MyClass.M()", - @"using System; + """ + using System; -namespace ConsoleApp4 -{ - class MyClass - { - void [|M|]() {} - } -}"); + namespace ConsoleApp4 + { + class MyClass + { + void [|M|]() {} + } + } + """); } [Fact] @@ -153,15 +161,17 @@ public Task TestSymbolFound_ExceptionLine_SingleSimpleClassParam() { return TestSymbolFoundAsync( "at ConsoleApp4.MyClass.M(String s)", - @"using System; + """ + using System; -namespace ConsoleApp4 -{ - class MyClass - { - void [|M|](string s) {} - } -}"); + namespace ConsoleApp4 + { + class MyClass + { + void [|M|](string s) {} + } + } + """); } [Fact] @@ -169,15 +179,17 @@ public Task TestSymbolFound_ExceptionLineWithFile() { return TestSymbolFoundAsync( @"at ConsoleApp4.MyClass.M() in C:\repos\ConsoleApp4\ConsoleApp4\Program.cs:line 26", - @"using System; + """ + using System; -namespace ConsoleApp4 -{ - class MyClass - { - void [|M|]() {} - } -}"); + namespace ConsoleApp4 + { + class MyClass + { + void [|M|]() {} + } + } + """); } [Fact] @@ -185,14 +197,16 @@ public Task TestSymbolFound_GenericType() { return TestSymbolFoundAsync( @"at ConsoleApp.MyClass`1.M(String s)", - @"using System; -namespace ConsoleApp -{ - class MyClass - { - void [|M|](string s) { } - } -}"); + """ + using System; + namespace ConsoleApp + { + class MyClass + { + void [|M|](string s) { } + } + } + """); } [Fact] @@ -200,14 +214,16 @@ public Task TestSymbolFound_GenericType2() { return TestSymbolFoundAsync( @"at ConsoleApp.MyClass`2.M(String s)", - @"using System; -namespace ConsoleApp -{ - class MyClass - { - void [|M|](string s) { } - } -}"); + """ + using System; + namespace ConsoleApp + { + class MyClass + { + void [|M|](string s) { } + } + } + """); } [Fact] @@ -215,14 +231,16 @@ public Task TestSymbolFound_GenericType_GenericArg() { return TestSymbolFoundAsync( @"at ConsoleApp.MyClass`1.M(T s)", - @"using System; -namespace ConsoleApp -{ - class MyClass - { - void [|M|](T s) { } - } -}"); + """ + using System; + namespace ConsoleApp + { + class MyClass + { + void [|M|](T s) { } + } + } + """); } [Fact] @@ -230,15 +248,17 @@ public Task TestSymbolFound_ExceptionLine_GenericMethod() { return TestSymbolFoundAsync( @"at ConsoleApp4.MyClass.M[T](T t) in C:\repos\Test\MyClass.cs:line 7", - @"using System; + """ + using System; -namespace ConsoleApp4 -{ - class MyClass - { - void [|M|](T t) {} - } -}"); + namespace ConsoleApp4 + { + class MyClass + { + void [|M|](T t) {} + } + } + """); } [Fact] @@ -246,15 +266,17 @@ public Task TestSymbolFound_ExceptionLine_GenericMethod_FromActivityLog() { return TestSymbolFoundAsync( @"at ConsoleApp4.MyClass.M<T>(T t)", - @"using System; + """ + using System; -namespace ConsoleApp4 -{ - class MyClass - { - void [|M|](T t) {} - } -}"); + namespace ConsoleApp4 + { + class MyClass + { + void [|M|](T t) {} + } + } + """); } [Fact] @@ -262,15 +284,17 @@ public Task TestSymbolFound_ExceptionLine_MultipleGenerics() { return TestSymbolFoundAsync( "at ConsoleApp4.MyClass.M(T t)", - @"using System; + """ + using System; -namespace ConsoleApp4 -{ - class MyClass - { - void [|M|](T t) {} - } -}"); + namespace ConsoleApp4 + { + class MyClass + { + void [|M|](T t) {} + } + } + """); } [Fact] @@ -278,16 +302,17 @@ public Task TestSymbolFound_ParameterSpacing() { return TestSymbolFoundAsync( "at ConsoleApp.MyClass.M( String s )", - @" -namespace ConsoleApp -{ - class MyClass - { - void [|M|](string s) - { - } - } -}"); + """ + namespace ConsoleApp + { + class MyClass + { + void [|M|](string s) + { + } + } + } + """); } [Fact] @@ -295,20 +320,21 @@ public Task TestSymbolFound_OverloadsWithSameName() { return TestSymbolFoundAsync( "at ConsoleApp.MyClass.M(String value)", - @" -namespace ConsoleApp -{ - class MyClass - { - void [|M|](string value) - { - } - - void M(int value) - { - } - } -}"); + """ + namespace ConsoleApp + { + class MyClass + { + void [|M|](string value) + { + } + + void M(int value) + { + } + } + } + """); } [Fact] @@ -316,16 +342,17 @@ public Task TestSymbolFound_ArrayParameter() { return TestSymbolFoundAsync( "at ConsoleApp.MyClass.M(String[] s)", - @" -namespace ConsoleApp -{ - class MyClass - { - void [|M|](string[] s) - { - } - } -}"); + """ + namespace ConsoleApp + { + class MyClass + { + void [|M|](string[] s) + { + } + } + } + """); } [Fact] @@ -333,16 +360,17 @@ public Task TestSymbolFound_MultidimensionArrayParameter() { return TestSymbolFoundAsync( "at ConsoleApp.MyClass.M(String[,] s)", - @" -namespace ConsoleApp -{ - class MyClass - { - void [|M|](string[,] s) - { - } - } -}"); + """ + namespace ConsoleApp + { + class MyClass + { + void [|M|](string[,] s) + { + } + } + } + """); } [Fact] @@ -350,16 +378,17 @@ public Task TestSymbolFound_MultidimensionArrayParameter_WithSpaces() { return TestSymbolFoundAsync( "at ConsoleApp.MyClass.M(String[ , ] s)", - @" -namespace ConsoleApp -{ - class MyClass - { - void [|M|](string[,] s) - { - } - } -}"); + """ + namespace ConsoleApp + { + class MyClass + { + void [|M|](string[,] s) + { + } + } + } + """); } [Fact] @@ -367,16 +396,17 @@ public Task TestSymbolFound_MultidimensionArrayParameter_WithSpaces2() { return TestSymbolFoundAsync( "at ConsoleApp.MyClass.M(String[,] s)", - @" -namespace ConsoleApp -{ - class MyClass - { - void [|M|](string[ , ] s) - { - } - } -}"); + """ + namespace ConsoleApp + { + class MyClass + { + void [|M|](string[ , ] s) + { + } + } + } + """); } [Fact] @@ -384,16 +414,17 @@ public Task TestSymbolFound_MultidimensionArrayParameter2() { return TestSymbolFoundAsync( "at ConsoleApp.MyClass.M(String[,][] s)", - @" -namespace ConsoleApp -{ - class MyClass - { - void [|M|](string[,][] s) - { - } - } -}"); + """ + namespace ConsoleApp + { + class MyClass + { + void [|M|](string[,][] s) + { + } + } + } + """); } [Fact(Skip = "Symbol search for nested types does not work")] @@ -401,21 +432,23 @@ public Task TestSymbolFound_ExceptionLine_GenericsHierarchy() { return TestSymbolFoundAsync( "at ConsoleApp4.MyClass`1.MyInnerClass`1.M[T](T t)", - @"using System; + """ + using System; -namespace ConsoleApp4 -{ - class MyClass - { - public class MyInnerClass - { - public void [|M|](T t) + namespace ConsoleApp4 { - throw new Exception(); + class MyClass + { + public class MyInnerClass + { + public void [|M|](T t) + { + throw new Exception(); + } + } + } } - } - } -}"); + """); } [Fact(Skip = "ref params do not work yet")] @@ -423,18 +456,20 @@ public Task TestSymbolFound_ExceptionLine_RefArg() { return TestSymbolFoundAsync( @"at ConsoleApp4.MyClass.M(String& s) in C:\repos\Test\MyClass.cs:line 8", - @"using System; + """ + using System; -namespace ConsoleApp4 -{ - class MyClass - { - void [|M|](ref string s) - { - s = string.Empty; - } - } -}"); + namespace ConsoleApp4 + { + class MyClass + { + void [|M|](ref string s) + { + s = string.Empty; + } + } + } + """); } [Fact(Skip = "out params do not work yet")] @@ -442,18 +477,20 @@ public Task TestSymbolFound_ExceptionLine_OutArg() { return TestSymbolFoundAsync( @"at ConsoleApp4.MyClass.M(String& s) in C:\repos\Test\MyClass.cs:line 8", - @"using System; + """ + using System; -namespace ConsoleApp4 -{ - class MyClass - { - void [|M|](out string s) - { - s = string.Empty; - } - } -}"); + namespace ConsoleApp4 + { + class MyClass + { + void [|M|](out string s) + { + s = string.Empty; + } + } + } + """); } [Fact(Skip = "in params do not work yet")] @@ -461,18 +498,20 @@ public Task TestSymbolFound_ExceptionLine_InArg() { return TestSymbolFoundAsync( @"at ConsoleApp4.MyClass.M(Int32& i)", - @"using System; + """ + using System; -namespace ConsoleApp4 -{ - class MyClass - { - void [|M|](in int i) - { - throw new Exception(); - } - } -}"); + namespace ConsoleApp4 + { + class MyClass + { + void [|M|](in int i) + { + throw new Exception(); + } + } + } + """); } [Fact(Skip = "Generated types/methods are not supported")] @@ -480,29 +519,31 @@ public Task TestSymbolFound_ExceptionLine_AsyncMethod() { return TestSymbolFoundAsync( @"at ConsoleApp4.MyClass.<>c.b__1_0() in C:\repos\Test\MyClass.cs:line 15", - @"namespace ConsoleApp4 -{ - class MyClass - { - public async Task M() - { - await DoThingAsync(); - } - - async Task DoThingAsync() - { - var task = new Task(() => + """ + namespace ConsoleApp4 { - Console.WriteLine(""Doing async work""); - throw new Exception(); - }); + class MyClass + { + public async Task M() + { + await DoThingAsync(); + } + + async Task DoThingAsync() + { + var task = new Task(() => + { + Console.WriteLine("Doing async work"); + throw new Exception(); + }); - task.Start(); + task.Start(); - await task; - } - } -}"); + await task; + } + } + } + """); } [Fact] @@ -510,19 +551,21 @@ public Task TestSymbolFound_ExceptionLine_PropertySet() { return TestSymbolFoundAsync( @"at ConsoleApp4.MyClass.set_I(Int32 value)", - @"using System; + """ + using System; -namespace ConsoleApp4 -{ - class MyClass - { - public int I - { - get => throw new Exception(); - [|set|] => throw new Exception(); - } - } -}"); + namespace ConsoleApp4 + { + class MyClass + { + public int I + { + get => throw new Exception(); + [|set|] => throw new Exception(); + } + } + } + """); } [Fact] @@ -530,19 +573,21 @@ public Task TestSymbolFound_ExceptionLine_PropertyGet() { return TestSymbolFoundAsync( @"at ConsoleApp4.MyClass.get_I()", - @"using System; + """ + using System; -namespace ConsoleApp4 -{ - class MyClass - { - public int I - { - [|get|] => throw new Exception(); - set => throw new Exception(); - } - } -}"); + namespace ConsoleApp4 + { + class MyClass + { + public int I + { + [|get|] => throw new Exception(); + set => throw new Exception(); + } + } + } + """); } [Fact] @@ -550,19 +595,21 @@ public Task TestSymbolFound_ExceptionLine_IndexerSet() { return TestSymbolFoundAsync( @"at ConsoleApp4.MyClass.set_Item(Int32 i, Int32 value)", - @"using System; + """ + using System; -namespace ConsoleApp4 -{ - class MyClass - { - public int this[int i] - { - get => throw new Exception(); - [|set|] => throw new Exception(); - } - } -}"); + namespace ConsoleApp4 + { + class MyClass + { + public int this[int i] + { + get => throw new Exception(); + [|set|] => throw new Exception(); + } + } + } + """); } [Fact] @@ -570,19 +617,21 @@ public Task TestSymbolFound_ExceptionLine_IndexerGet() { return TestSymbolFoundAsync( @"at ConsoleApp4.MyClass.get_Item(Int32 i)", - @"using System; + """ + using System; -namespace ConsoleApp4 -{ - class MyClass - { - public int this[int i] - { - [|get|] => throw new Exception(); - set => throw new Exception(); - } - } -}"); + namespace ConsoleApp4 + { + class MyClass + { + public int this[int i] + { + [|get|] => throw new Exception(); + set => throw new Exception(); + } + } + } + """); } [Fact] @@ -590,27 +639,29 @@ public Task TestSymbolFound_ExceptionLine_LocalFunction() { return TestSymbolFoundAsync( @"at ConsoleApp4.MyClass.g__LocalFunction|0_0()", - @"using System; - -namespace ConsoleApp4 -{ - class MyClass - { - public void M() - { - LocalFunction(); + """ + using System; - void [|LocalFunction|]() + namespace ConsoleApp4 { - throw new Exception(); - } - } + class MyClass + { + public void M() + { + LocalFunction(); - public void LocalFunction() - { - } - } -}"); + void [|LocalFunction|]() + { + throw new Exception(); + } + } + + public void LocalFunction() + { + } + } + } + """); } [Fact] @@ -618,33 +669,35 @@ public Task TestSymbolFound_ExceptionLine_MultipleLocalFunctions() { return TestSymbolFoundAsync( @"at ConsoleApp4.MyClass.g__LocalFunction|0_0()", - @"using System; - -namespace ConsoleApp4 -{ - class MyClass - { - public void M() - { - LocalFunction(); + """ + using System; - void [|LocalFunction|]() + namespace ConsoleApp4 { - throw new Exception(); - } - } + class MyClass + { + public void M() + { + LocalFunction(); - public void M2() - { - LocalFunction(); + void [|LocalFunction|]() + { + throw new Exception(); + } + } - void LocalFunction() - { - throw new Exception(); + public void M2() + { + LocalFunction(); + + void LocalFunction() + { + throw new Exception(); + } + } + } } - } - } -}"); + """); } [Fact] @@ -652,33 +705,35 @@ public Task TestSymbolFound_ExceptionLine_MultipleLocalFunctions2() { return TestSymbolFoundAsync( @"at ConsoleApp4.MyClass.g__LocalFunction|0_0()", - @"using System; - -namespace ConsoleApp4 -{ - class MyClass - { - public void M() - { - LocalFunction(); + """ + using System; - void LocalFunction() + namespace ConsoleApp4 { - throw new Exception(); - } - } + class MyClass + { + public void M() + { + LocalFunction(); - public void M2() - { - LocalFunction(); + void LocalFunction() + { + throw new Exception(); + } + } - void [|LocalFunction()|] - { - throw new Exception(); + public void M2() + { + LocalFunction(); + + void [|LocalFunction()|] + { + throw new Exception(); + } + } + } } - } - } -}"); + """); } [Fact] @@ -686,27 +741,29 @@ public Task TestSymbolFound_ExceptionLine_MemberFunctionSameNameAsFunction() { return TestSymbolFoundAsync( @"at ConsoleApp4.MyClass.LocalFunction()", - @"using System; - -namespace ConsoleApp4 -{ - class MyClass - { - public void M() - { - LocalFunction(); + """ + using System; - void LocalFunction() + namespace ConsoleApp4 { - throw new Exception(); - } - } + class MyClass + { + public void M() + { + LocalFunction(); - public void [|LocalFunction|]() - { - } - } -}"); + void LocalFunction() + { + throw new Exception(); + } + } + + public void [|LocalFunction|]() + { + } + } + } + """); } /// @@ -725,25 +782,27 @@ public Task TestSymbolFound_ExceptionLine_NestedLocalFunctions() { return TestSymbolFoundAsync( @"at C.g__Local|0_1()", - @"using System; + """ + using System; -class C -{ - public void M() - { - Local(); - - void [|Local|]() - { - Local(); - - void Local() + class C { - throw new Exception(); + public void M() + { + Local(); + + void [|Local|]() + { + Local(); + + void Local() + { + throw new Exception(); + } + } + } } - } - } -}"); + """); } [Fact(Skip = "Top level local functions are not supported")] @@ -751,14 +810,16 @@ public Task TestSymbolFound_ExceptionLine_LocalInTopLevelStatement() { return TestSymbolFoundAsync( @"at ConsoleApp4.Program.g__LocalInTopLevelStatement|0_0()", - @"using System; + """ + using System; -LocalInTopLevelStatement(); + LocalInTopLevelStatement(); -void [|LocalInTopLevelStatement|]() -{ - throw new Exception(); -}"); + void [|LocalInTopLevelStatement|]() + { + throw new Exception(); + } + """); } [Fact(Skip = "The parser doesn't correctly handle ..ctor() methods yet")] @@ -766,21 +827,23 @@ public Task TestSymbolFound_ExceptionLine_Constructor() { return TestSymbolFoundAsync( @"at ConsoleApp4.MyClass..ctor()", - @"namespace ConsoleApp4 -{ - class MyClass - { - public MyClass() - { - throw new Exception(); - } - - ~MyClass() - { - throw new Exception(); - } - } -}"); + """ + namespace ConsoleApp4 + { + class MyClass + { + public MyClass() + { + throw new Exception(); + } + + ~MyClass() + { + throw new Exception(); + } + } + } + """); } [Theory] @@ -811,10 +874,11 @@ public async Task TestFailureToParse(string line) [InlineData("abcd!__.__._()")] public async Task TestInvalidSymbol(string line) { - using var workspace = TestWorkspace.CreateCSharp(@" -class C -{ -}"); + using var workspace = TestWorkspace.CreateCSharp(""" + class C + { + } + """); var result = await StackTraceAnalyzer.AnalyzeAsync(line, CancellationToken.None); Assert.Equal(1, result.ParsedFrames.Length); diff --git a/src/EditorFeatures/Test/Structure/AbstractStructureTaggerProviderTests.cs b/src/EditorFeatures/Test/Structure/AbstractStructureTaggerProviderTests.cs index 331cb065ad036..b193cd048e87f 100644 --- a/src/EditorFeatures/Test/Structure/AbstractStructureTaggerProviderTests.cs +++ b/src/EditorFeatures/Test/Structure/AbstractStructureTaggerProviderTests.cs @@ -26,103 +26,83 @@ private static void TextContainsRegionOrUsing(string input, bool expected, strin [Fact] public void UsingDirective() { - var input = @" -using System; -"; - - TextContainsRegionOrUsing(input, true, LanguageNames.CSharp); + TextContainsRegionOrUsing(""" + using System; + """, true, LanguageNames.CSharp); } [Fact] public void UsingDirectiveInNamespace() { - var input = @" -namespace Goo -{ - using System; -} -"; - - TextContainsRegionOrUsing(input, true, LanguageNames.CSharp); + TextContainsRegionOrUsing(""" + namespace Goo + { + using System; + } + """, true, LanguageNames.CSharp); } [Fact] public void UsingStaticDirective() { - var input = @" -using static System; -"; - - TextContainsRegionOrUsing(input, true, LanguageNames.CSharp); + TextContainsRegionOrUsing(""" + using static System; + """, true, LanguageNames.CSharp); } [Fact] public void UsingAliasDirective() { - var input = @" -using A = System; -"; - - TextContainsRegionOrUsing(input, true, LanguageNames.CSharp); + TextContainsRegionOrUsing(""" + using A = System; + """, true, LanguageNames.CSharp); } [Fact] public void ExternAlias() { - var input = @" -extern alias Goo; -"; - - TextContainsRegionOrUsing(input, true, LanguageNames.CSharp); + TextContainsRegionOrUsing(""" + extern alias Goo; + """, true, LanguageNames.CSharp); } [Fact] public void ImportsStatement() { - var input = @" -Imports System -"; - - TextContainsRegionOrUsing(input, true, LanguageNames.VisualBasic); + TextContainsRegionOrUsing(""" + Imports System + """, true, LanguageNames.VisualBasic); } [Fact] public void ImportsAliasStatement() { - var input = @" -Imports A = System -"; - - TextContainsRegionOrUsing(input, true, LanguageNames.VisualBasic); + TextContainsRegionOrUsing(""" + Imports A = System + """, true, LanguageNames.VisualBasic); } [Fact] public void CSharpRegion1() { - var input = @" - #region -"; - - TextContainsRegionOrUsing(input, true, LanguageNames.CSharp); + TextContainsRegionOrUsing(""" + #region + """, true, LanguageNames.CSharp); } [Fact] public void CSharpRegion() { - var input = @" - #region Goo -"; - - TextContainsRegionOrUsing(input, true, LanguageNames.CSharp); + TextContainsRegionOrUsing(""" + #region Goo + """, true, LanguageNames.CSharp); } [Fact] public void VisualBasicRegion() { - var input = @" -#Region Goo -"; - - TextContainsRegionOrUsing(input, true, LanguageNames.VisualBasic); + TextContainsRegionOrUsing(""" + #Region Goo + """, true, LanguageNames.VisualBasic); } } diff --git a/src/EditorFeatures/Test/Structure/BlockStructureServiceTests.cs b/src/EditorFeatures/Test/Structure/BlockStructureServiceTests.cs index 61c12c3df5e8a..c63992d662c0c 100644 --- a/src/EditorFeatures/Test/Structure/BlockStructureServiceTests.cs +++ b/src/EditorFeatures/Test/Structure/BlockStructureServiceTests.cs @@ -23,18 +23,19 @@ public sealed class BlockStructureServiceTests public async Task TestSimpleLambda() { var code = -@"using System.Linq; -class C -{ - static void Goo() - { - var q = Enumerable.Range(1, 100).Where(x => - { - return x % 2 == 0; - }); - } -} -"; + """ + using System.Linq; + class C + { + static void Goo() + { + var q = Enumerable.Range(1, 100).Where(x => + { + return x % 2 == 0; + }); + } + } + """; using var workspace = TestWorkspace.CreateCSharp(code); var spans = await GetSpansFromWorkspaceAsync(workspace); @@ -47,18 +48,19 @@ static void Goo() public async Task TestParenthesizedLambda() { var code = -@"using System.Linq; -class C -{ - static void Goo() - { - var q = Enumerable.Range(1, 100).Where((x) => - { - return x % 2 == 0; - }); - } -} -"; + """ + using System.Linq; + class C + { + static void Goo() + { + var q = Enumerable.Range(1, 100).Where((x) => + { + return x % 2 == 0; + }); + } + } + """; using var workspace = TestWorkspace.CreateCSharp(code); var spans = await GetSpansFromWorkspaceAsync(workspace); @@ -71,18 +73,19 @@ static void Goo() public async Task TestAnonymousDelegate() { var code = -@"using System.Linq; -class C -{ - static void Goo() - { - var q = Enumerable.Range(1, 100).Where(delegate (int x) - { - return x % 2 == 0; - }); - } -} -"; + """ + using System.Linq; + class C + { + static void Goo() + { + var q = Enumerable.Range(1, 100).Where(delegate (int x) + { + return x % 2 == 0; + }); + } + } + """; using var workspace = TestWorkspace.CreateCSharp(code); var spans = await GetSpansFromWorkspaceAsync(workspace); diff --git a/src/EditorFeatures/Test/Structure/StructureTaggerTests.cs b/src/EditorFeatures/Test/Structure/StructureTaggerTests.cs index 48bc08e15157e..920a50bda9a79 100644 --- a/src/EditorFeatures/Test/Structure/StructureTaggerTests.cs +++ b/src/EditorFeatures/Test/Structure/StructureTaggerTests.cs @@ -33,24 +33,26 @@ public async Task CSharpOutliningTagger( bool showBlockStructureGuidesForCommentsAndPreprocessorRegions) { var code = -@"using System; -namespace MyNamespace -{ -#region MyRegion - public class MyClass - { - static void Main(string[] args) - { - if (false) + """ + using System; + namespace MyNamespace { - return; + #region MyRegion + public class MyClass + { + static void Main(string[] args) + { + if (false) + { + return; + } + + int x = 5; + } + } + #endregion } - - int x = 5; - } - } -#endregion -}"; + """; using var workspace = EditorTestWorkspace.CreateCSharp(code, composition: EditorTestCompositions.EditorFeatures); var globalOptions = workspace.GlobalOptions; @@ -108,16 +110,16 @@ public async Task CSharpImportsFileScopedNamespaceTest( bool showBlockStructureGuidesForCodeLevelConstructs) { var code = -@" -namespace Foo; + """ + namespace Foo; -using System; -using System.Linq; -public class Bar -{ + using System; + using System.Linq; + public class Bar + { -} -"; + } + """; using var workspace = EditorTestWorkspace.CreateCSharp(code, composition: EditorTestCompositions.EditorFeatures); var globalOptions = workspace.GlobalOptions; @@ -152,17 +154,17 @@ public async Task CSharpCommentsFileScopedNamespace( bool showBlockStructureGuidesForCommentsAndPreprocessorRegions) { var code = -@" -namespace Foo; -/// -/// -/// + """ + namespace Foo; + /// + /// + /// -public class Bar -{ + public class Bar + { -} -"; + } + """; using var workspace = EditorTestWorkspace.CreateCSharp(code, composition: EditorTestCompositions.EditorFeatures); var globalOptions = workspace.GlobalOptions; @@ -197,17 +199,17 @@ public async Task CSharpImportsNormalNamespaceTest( bool showBlockStructureGuidesForCodeLevelConstructs) { var code = -@" -namespace Foo -{ - using System; - using System.Linq; - public class Bar - { + """ + namespace Foo + { + using System; + using System.Linq; + public class Bar + { - } -} -"; + } + } + """; using var workspace = EditorTestWorkspace.CreateCSharp(code, composition: EditorTestCompositions.EditorFeatures); var globalOptions = workspace.GlobalOptions; @@ -246,20 +248,22 @@ public async Task VisualBasicOutliningTagger( bool showBlockStructureGuidesForDeclarationLevelConstructs, bool showBlockStructureGuidesForCodeLevelConstructs) { - var code = @"Imports System -Namespace MyNamespace -#Region ""MyRegion"" - Module M - Sub Main(args As String()) - If False Then - Return - End If - - Dim x As Integer = 5 - End Sub - End Module -#End Region -End Namespace"; + var code = """ + Imports System + Namespace MyNamespace + #Region "MyRegion" + Module M + Sub Main(args As String()) + If False Then + Return + End If + + Dim x As Integer = 5 + End Sub + End Module + #End Region + End Namespace + """; using var workspace = EditorTestWorkspace.CreateVisualBasic(code, composition: EditorTestCompositions.EditorFeatures); var globalOptions = workspace.GlobalOptions; @@ -283,7 +287,9 @@ End Module Assert.Equal(collapseRegionsWhenCollapsingToDefinitions, regionTag.IsImplementation); Assert.Equal(11, GetCollapsedHintLineCount(regionTag)); Assert.Equal(PredefinedStructureTagTypes.Nonstructural, regionTag.Type); - Assert.Equal(@"#Region ""MyRegion""", GetHeaderText(regionTag)); + Assert.Equal(""" + #Region "MyRegion" + """, GetHeaderText(regionTag)); }, moduleTag => { @@ -312,10 +318,12 @@ End Module [WpfFact] public async Task OutliningTaggerTooltipText() { - var code = @"Module Module1 - Sub Main(args As String()) - End Sub -End Module"; + var code = """ + Module Module1 + Sub Main(args As String()) + End Sub + End Module + """; using var workspace = EditorTestWorkspace.CreateVisualBasic(code, composition: EditorTestCompositions.EditorFeatures); var tags = await GetTagsFromWorkspaceAsync(workspace); @@ -329,15 +337,16 @@ End Sub [WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/2094051")] public async Task IfShouldBeCollapsed() { - var code = @" -Module Program - Sub Main(args As String()) - Dim str = """" - If str.Contains(""foo"") Then - - End If - End Sub -End Module"; + var code = """ + Module Program + Sub Main(args As String()) + Dim str = "" + If str.Contains("foo") Then + + End If + End Sub + End Module + """; using var workspace = EditorTestWorkspace.CreateVisualBasic(code, composition: EditorTestCompositions.EditorFeatures); var tags = await GetTagsFromWorkspaceAsync(workspace); diff --git a/src/EditorFeatures/Test/SymbolFinder/FindSymbolAtPositionTests.cs b/src/EditorFeatures/Test/SymbolFinder/FindSymbolAtPositionTests.cs index d1f068774f4fe..f5fd7adb04bd8 100644 --- a/src/EditorFeatures/Test/SymbolFinder/FindSymbolAtPositionTests.cs +++ b/src/EditorFeatures/Test/SymbolFinder/FindSymbolAtPositionTests.cs @@ -26,16 +26,18 @@ private static Task FindSymbolAtPositionAsync(TestWorkspace workspace) public async Task PositionOnLeadingTrivia() { using var workspace = TestWorkspace.CreateCSharp( - @"using System; - class Program - { - static void Main() - { - $$#pragma warning disable 612 - Goo(); - #pragma warning restore 612 - } - }"); + """ + using System; + class Program + { + static void Main() + { + $$#pragma warning disable 612 + Goo(); + #pragma warning restore 612 + } + } + """); var symbol = await FindSymbolAtPositionAsync(workspace); Assert.Null(symbol); } @@ -44,19 +46,21 @@ static void Main() public async Task PositionInCaseLabel() { using var workspace = TestWorkspace.CreateCSharp( - @"using System; - enum E { A, B } - class Program - { - static void Main() - { - E e = default; - switch (e) - { - case E.$$A: break; - } - } - }"); + """ + using System; + enum E { A, B } + class Program + { + static void Main() + { + E e = default; + switch (e) + { + case E.$$A: break; + } + } + } + """); var fieldSymbol = Assert.IsAssignableFrom(await FindSymbolAtPositionAsync(workspace)); Assert.Equal(TypeKind.Enum, fieldSymbol.ContainingType.TypeKind); diff --git a/src/EditorFeatures/Test/SymbolFinder/SymbolFinderTests.cs b/src/EditorFeatures/Test/SymbolFinder/SymbolFinderTests.cs index 211b55143f489..24b645d715cce 100644 --- a/src/EditorFeatures/Test/SymbolFinder/SymbolFinderTests.cs +++ b/src/EditorFeatures/Test/SymbolFinder/SymbolFinderTests.cs @@ -58,23 +58,23 @@ public async Task ImmediatelyDerivedTypes_CSharp(TestHost host) var solution = workspace.CurrentSolution; // create portable assembly with an abstract base class - solution = AddProjectWithMetadataReferences(solution, "PortableProject", LanguageNames.CSharp, @" -namespace N -{ - public abstract class BaseClass { } -} -", Net40.References.mscorlib); + solution = AddProjectWithMetadataReferences(solution, "PortableProject", LanguageNames.CSharp, """ + namespace N + { + public abstract class BaseClass { } + } + """, Net40.References.mscorlib); var portableProject = GetPortableProject(solution); // create a normal assembly with a type derived from the portable abstract base - solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.CSharp, @" -using N; -namespace M -{ - public class DerivedClass : BaseClass { } -} -", Net461.References.mscorlib, portableProject.Id); + solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.CSharp, """ + using N; + namespace M + { + public class DerivedClass : BaseClass { } + } + """, Net461.References.mscorlib, portableProject.Id); // get symbols for types var portableCompilation = await GetPortableProject(solution).GetCompilationAsync(); @@ -99,23 +99,23 @@ public async Task ImmediatelyDerivedInterfaces_CSharp(TestHost host) var solution = workspace.CurrentSolution; // create portable assembly with an abstract base class - solution = AddProjectWithMetadataReferences(solution, "PortableProject", LanguageNames.CSharp, @" -namespace N -{ - public interface BaseInterface { } -} -", Net40.References.mscorlib); + solution = AddProjectWithMetadataReferences(solution, "PortableProject", LanguageNames.CSharp, """ + namespace N + { + public interface BaseInterface { } + } + """, Net40.References.mscorlib); var portableProject = GetPortableProject(solution); // create a normal assembly with a type derived from the portable abstract base - solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.CSharp, @" -using N; -namespace M -{ - public interface DerivedInterface : BaseInterface { } -} -", Net461.References.mscorlib, portableProject.Id); + solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.CSharp, """ + using N; + namespace M + { + public interface DerivedInterface : BaseInterface { } + } + """, Net461.References.mscorlib, portableProject.Id); // get symbols for types var portableCompilation = await GetPortableProject(solution).GetCompilationAsync(); @@ -146,27 +146,27 @@ public async Task ImmediatelyDerivedTypes_CSharp_AliasedNames(TestHost host) var solution = workspace.CurrentSolution; // create portable assembly with an abstract base class - solution = AddProjectWithMetadataReferences(solution, "PortableProject", LanguageNames.CSharp, @" -namespace N -{ - public abstract class BaseClass { } -} -", Net40.References.mscorlib); + solution = AddProjectWithMetadataReferences(solution, "PortableProject", LanguageNames.CSharp, """ + namespace N + { + public abstract class BaseClass { } + } + """, Net40.References.mscorlib); var portableProject = GetPortableProject(solution); // create a normal assembly with a type derived from the portable abstract base - solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.CSharp, @" -using N; -using Alias1 = N.BaseClass; + solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.CSharp, """ + using N; + using Alias1 = N.BaseClass; -namespace M -{ - using Alias2 = Alias1; + namespace M + { + using Alias2 = Alias1; - public class DerivedClass : Alias2 { } -} -", Net461.References.mscorlib, portableProject.Id); + public class DerivedClass : Alias2 { } + } + """, Net461.References.mscorlib, portableProject.Id); // get symbols for types var portableCompilation = await GetPortableProject(solution).GetCompilationAsync(); @@ -191,23 +191,23 @@ public async Task ImmediatelyDerivedTypes_CSharp_PortableProfile7(TestHost host) var solution = workspace.CurrentSolution; // create portable assembly with an abstract base class - solution = AddProjectWithMetadataReferences(solution, "PortableProject", LanguageNames.CSharp, @" -namespace N -{ - public abstract class BaseClass { } -} -", Net40.References.mscorlib); + solution = AddProjectWithMetadataReferences(solution, "PortableProject", LanguageNames.CSharp, """ + namespace N + { + public abstract class BaseClass { } + } + """, Net40.References.mscorlib); var portableProject = GetPortableProject(solution); // create a normal assembly with a type derived from the portable abstract base - solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.CSharp, @" -using N; -namespace M -{ - public class DerivedClass : BaseClass { } -} -", SystemRuntimePP7Ref, portableProject.Id); + solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.CSharp, """ + using N; + namespace M + { + public class DerivedClass : BaseClass { } + } + """, SystemRuntimePP7Ref, portableProject.Id); // get symbols for types var portableCompilation = await GetPortableProject(solution).GetCompilationAsync(); @@ -232,24 +232,24 @@ public async Task ImmediatelyDerivedTypes_VisualBasic(TestHost host) var solution = workspace.CurrentSolution; // create portable assembly with an abstract base class - solution = AddProjectWithMetadataReferences(solution, "PortableProject", LanguageNames.VisualBasic, @" -Namespace N - Public MustInherit Class BaseClass - End Class -End Namespace -", Net40.References.mscorlib); + solution = AddProjectWithMetadataReferences(solution, "PortableProject", LanguageNames.VisualBasic, """ + Namespace N + Public MustInherit Class BaseClass + End Class + End Namespace + """, Net40.References.mscorlib); var portableProject = GetPortableProject(solution); // create a normal assembly with a type derived from the portable abstract base - solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.VisualBasic, @" -Imports N -Namespace M - Public Class DerivedClass - Inherits BaseClass - End Class -End Namespace -", Net461.References.mscorlib, portableProject.Id); + solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.VisualBasic, """ + Imports N + Namespace M + Public Class DerivedClass + Inherits BaseClass + End Class + End Namespace + """, Net461.References.mscorlib, portableProject.Id); // get symbols for types var portableCompilation = await GetPortableProject(solution).GetCompilationAsync(); @@ -274,24 +274,24 @@ public async Task ImmediatelyDerivedTypes_CrossLanguage(TestHost host) var solution = workspace.CurrentSolution; // create portable assembly with an abstract base class - solution = AddProjectWithMetadataReferences(solution, "PortableProject", LanguageNames.CSharp, @" -namespace N -{ - public abstract class BaseClass { } -} -", Net40.References.mscorlib); + solution = AddProjectWithMetadataReferences(solution, "PortableProject", LanguageNames.CSharp, """ + namespace N + { + public abstract class BaseClass { } + } + """, Net40.References.mscorlib); var portableProject = GetPortableProject(solution); // create a normal assembly with a type derived from the portable abstract base - solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.VisualBasic, @" -Imports N -Namespace M - Public Class DerivedClass - Inherits BaseClass - End Class -End Namespace -", Net40.References.mscorlib, portableProject.Id); + solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.VisualBasic, """ + Imports N + Namespace M + Public Class DerivedClass + Inherits BaseClass + End Class + End Namespace + """, Net40.References.mscorlib, portableProject.Id); // get symbols for types var portableCompilation = await GetPortableProject(solution).GetCompilationAsync(); @@ -316,23 +316,23 @@ public async Task ImmediatelyDerivedAndImplementingInterfaces_CSharp(TestHost ho var solution = workspace.CurrentSolution; // create portable assembly with an interface - solution = AddProjectWithMetadataReferences(solution, "PortableProject", LanguageNames.CSharp, @" -namespace N -{ - public interface IBaseInterface { } -} -", Net40.References.mscorlib); + solution = AddProjectWithMetadataReferences(solution, "PortableProject", LanguageNames.CSharp, """ + namespace N + { + public interface IBaseInterface { } + } + """, Net40.References.mscorlib); var portableProject = GetPortableProject(solution); // create a normal assembly with a type implementing that interface - solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.CSharp, @" -using N; -namespace M -{ - public class ImplementingClass : IBaseInterface { } -} -", Net461.References.mscorlib, portableProject.Id); + solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.CSharp, """ + using N; + namespace M + { + public class ImplementingClass : IBaseInterface { } + } + """, Net461.References.mscorlib, portableProject.Id); // get symbols for types var portableCompilation = await GetPortableProject(solution).GetCompilationAsync(); @@ -356,24 +356,24 @@ public async Task ImmediatelyDerivedInterfaces_VisualBasic(TestHost host) var solution = workspace.CurrentSolution; // create portable assembly with an interface - solution = AddProjectWithMetadataReferences(solution, "PortableProject", LanguageNames.VisualBasic, @" -Namespace N - Public Interface IBaseInterface - End Interface -End Namespace -", Net40.References.mscorlib); + solution = AddProjectWithMetadataReferences(solution, "PortableProject", LanguageNames.VisualBasic, """ + Namespace N + Public Interface IBaseInterface + End Interface + End Namespace + """, Net40.References.mscorlib); var portableProject = GetPortableProject(solution); // create a normal assembly with a type implementing that interface - solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.VisualBasic, @" -Imports N -Namespace M - Public Class ImplementingClass - Implements IBaseInterface - End Class -End Namespace -", Net461.References.mscorlib, portableProject.Id); + solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.VisualBasic, """ + Imports N + Namespace M + Public Class ImplementingClass + Implements IBaseInterface + End Class + End Namespace + """, Net461.References.mscorlib, portableProject.Id); // get symbols for types var portableCompilation = await GetPortableProject(solution).GetCompilationAsync(); @@ -397,23 +397,23 @@ public async Task ImmediatelyDerivedAndImplementingInterfaces_CrossLanguage(Test var solution = workspace.CurrentSolution; // create portable assembly with an interface - solution = AddProjectWithMetadataReferences(solution, "PortableProject", LanguageNames.VisualBasic, @" -Namespace N - Public Interface IBaseInterface - End Interface -End Namespace -", Net40.References.mscorlib); + solution = AddProjectWithMetadataReferences(solution, "PortableProject", LanguageNames.VisualBasic, """ + Namespace N + Public Interface IBaseInterface + End Interface + End Namespace + """, Net40.References.mscorlib); var portableProject = GetPortableProject(solution); // create a normal assembly with a type implementing that interface - solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.CSharp, @" -using N; -namespace M -{ - public class ImplementingClass : IBaseInterface { } -} -", Net40.References.mscorlib, portableProject.Id); + solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.CSharp, """ + using N; + namespace M + { + public class ImplementingClass : IBaseInterface { } + } + """, Net40.References.mscorlib, portableProject.Id); // get symbols for types var portableCompilation = await GetPortableProject(solution).GetCompilationAsync(); @@ -468,21 +468,21 @@ public async Task DerivedSourceInterfaces(TestHost host) var solution = workspace.CurrentSolution; // create a normal assembly with a type derived from the portable abstract base - solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.CSharp, @" -interface IA { } + solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.CSharp, """ + interface IA { } -interface IB1 : IA { } -interface IB2 : IA { } -interface IB3 : IEquatable, IA { } + interface IB1 : IA { } + interface IB2 : IA { } + interface IB3 : IEquatable, IA { } -interface IC1 : IB1 { } -interface IC2 : IA, IB2 { } -interface IC3 : IB3 { } + interface IC1 : IB1 { } + interface IC2 : IA, IB2 { } + interface IC3 : IB3 { } -interface ID1 : IC1 { } + interface ID1 : IC1 { } -interface IOther { } -", Net40.References.mscorlib); + interface IOther { } + """, Net40.References.mscorlib); // get symbols for types var compilation = await GetNormalProject(solution).GetCompilationAsync(); @@ -517,24 +517,24 @@ public async Task ImplementingSourceTypes(TestHost host) var solution = workspace.CurrentSolution; // create a normal assembly with a type derived from the portable abstract base - solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.CSharp, @" -interface IA { } + solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.CSharp, """ + interface IA { } -class B1 : IA { } -class B2 : IA { } -class B3 : IEquatable, IA { } + class B1 : IA { } + class B2 : IA { } + class B3 : IEquatable, IA { } -class C1 : B1 { } -class C2 : B2, IA { } -class C3 : B3 { } + class C1 : B1 { } + class C2 : B2, IA { } + class C3 : B3 { } -struct S1 : IA { } + struct S1 : IA { } -class D1 : C1 { } + class D1 : C1 { } -class OtherClass { } -struct OtherStruct { } -", Net40.References.mscorlib); + class OtherClass { } + struct OtherStruct { } + """, Net40.References.mscorlib); // get symbols for types var compilation = await GetNormalProject(solution).GetCompilationAsync(); @@ -569,9 +569,9 @@ public async Task ImplementingTypesDoesProduceDelegates(TestHost host) var solution = workspace.CurrentSolution; // create a normal assembly with a type derived from the portable abstract base - solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.CSharp, @" -delegate void D(); -", Net40.References.mscorlib); + solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.CSharp, """ + delegate void D(); + """, Net40.References.mscorlib); // get symbols for types var compilation = await GetNormalProject(solution).GetCompilationAsync(); @@ -596,12 +596,12 @@ public async Task ImplementingTypesDoesProduceEnums(TestHost host) var solution = workspace.CurrentSolution; // create a normal assembly with a type derived from the portable abstract base - solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.CSharp, @" -enum E -{ - A, B, C, -} -", Net40.References.mscorlib); + solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.CSharp, """ + enum E + { + A, B, C, + } + """, Net40.References.mscorlib); // get symbols for types var compilation = await GetNormalProject(solution).GetCompilationAsync(); @@ -626,20 +626,21 @@ public async Task DependentTypeFinderSkipsNoCompilationLanguages(TestHost host) var composition = EditorTestCompositions.EditorFeatures.WithTestHostParts(host); using var workspace = TestWorkspace.Create( -@" - - - - Dummy ts content - - - - - public class Base { } - public class Derived : Base { } - - -", composition: composition); + """ + + + + Dummy ts content + + + + + public class Base { } + public class Derived : Base { } + + + + """, composition: composition); var solution = workspace.CurrentSolution; var csProject = solution.Projects.Single(p => p.Language == LanguageNames.CSharp); @@ -669,35 +670,35 @@ public async Task TestDerivedTypesWithIntermediaryType1(TestHost host) var solution = workspace.CurrentSolution; // create portable assembly with an interface - solution = AddProjectWithMetadataReferences(solution, "NormalProject1", LanguageNames.CSharp, @" -namespace N_Main -{ - // All these types should find T_DependProject_Class as a derived class, - // even if only searching the second project. - - abstract public class T_BaseProject_BaseClass - { - } - public abstract class T_BaseProject_DerivedClass1 : T_BaseProject_BaseClass - { - } - public abstract class T_BaseProject_DerivedClass2 : T_BaseProject_DerivedClass1 - { - } -} -", Net40.References.mscorlib); + solution = AddProjectWithMetadataReferences(solution, "NormalProject1", LanguageNames.CSharp, """ + namespace N_Main + { + // All these types should find T_DependProject_Class as a derived class, + // even if only searching the second project. + + abstract public class T_BaseProject_BaseClass + { + } + public abstract class T_BaseProject_DerivedClass1 : T_BaseProject_BaseClass + { + } + public abstract class T_BaseProject_DerivedClass2 : T_BaseProject_DerivedClass1 + { + } + } + """, Net40.References.mscorlib); var normalProject1 = solution.Projects.Single(); // create a normal assembly with a type implementing that interface - solution = AddProjectWithMetadataReferences(solution, "NormalProject2", LanguageNames.CSharp, @" -namespace N_Main -{ - public class T_DependProject_Class : T_BaseProject_DerivedClass2 - { - } -} -", Net40.References.mscorlib, normalProject1.Id); + solution = AddProjectWithMetadataReferences(solution, "NormalProject2", LanguageNames.CSharp, """ + namespace N_Main + { + public class T_DependProject_Class : T_BaseProject_DerivedClass2 + { + } + } + """, Net40.References.mscorlib, normalProject1.Id); normalProject1 = solution.GetProject(normalProject1.Id); var normalProject2 = solution.Projects.Single(p => p != normalProject1); @@ -732,28 +733,28 @@ public async Task ImplementedInterface_CSharp1(TestHost host) using var workspace = CreateWorkspace(host); var solution = workspace.CurrentSolution; - solution = AddProjectWithMetadataReferences(solution, "PortableProject1", LanguageNames.CSharp, @" -namespace N -{ - public interface I - { - void M(); - } -} -", Net40.References.mscorlib); + solution = AddProjectWithMetadataReferences(solution, "PortableProject1", LanguageNames.CSharp, """ + namespace N + { + public interface I + { + void M(); + } + } + """, Net40.References.mscorlib); var portableProject1 = solution.Projects.Single(p => p.Name == "PortableProject1"); - solution = AddProjectWithMetadataReferences(solution, "PortableProject2", LanguageNames.CSharp, @" -using N; -namespace M -{ - public class C : I - { - public void M() { } - } -} -", Net40.References.mscorlib, portableProject1.Id); + solution = AddProjectWithMetadataReferences(solution, "PortableProject2", LanguageNames.CSharp, """ + using N; + namespace M + { + public class C : I + { + public void M() { } + } + } + """, Net40.References.mscorlib, portableProject1.Id); // get symbols for types var compilation1 = await solution.Projects.Single(p => p.Name == "PortableProject1").GetCompilationAsync(); @@ -776,15 +777,15 @@ public async Task ImplementedInterface_CSharp2(TestHost host) var solution = workspace.CurrentSolution; // create portable assembly with an abstract base class - solution = AddProjectWithMetadataReferences(solution, "PortableProject", LanguageNames.CSharp, @" -namespace N -{ - public interface I - { - void M(); - } -} -", Net40.References.mscorlib); + solution = AddProjectWithMetadataReferences(solution, "PortableProject", LanguageNames.CSharp, """ + namespace N + { + public interface I + { + void M(); + } + } + """, Net40.References.mscorlib); var portableProject1 = GetPortableProject(solution); @@ -804,12 +805,12 @@ public async Task FindSourceDefinition_CrossAssembly(TestHost host) var solution = workspace.CurrentSolution; // Create a source assembly with a class in Visual Basic - solution = AddProjectWithMetadataReferences(solution, "ReferencedProject", LanguageNames.VisualBasic, @" -Namespace N - Public Class ReferencedClass - End Class -End Namespace -", Net40.References.mscorlib); + solution = AddProjectWithMetadataReferences(solution, "ReferencedProject", LanguageNames.VisualBasic, """ + Namespace N + Public Class ReferencedClass + End Class + End Namespace + """, Net40.References.mscorlib); var referencedProjectId = solution.Projects.Single(p => p.Name == "ReferencedProject").Id; @@ -841,15 +842,15 @@ public async Task FindSourceDefinition_CrossAssembly_WithFrozen(TestHost host) using var workspace = CreateWorkspace(host); var solution = workspace.CurrentSolution; - var code = @" -Namespace N - Public Class ReferencedClass - Public Sub M() - Dim x As Integer = 0 - End Sub - End Class -End Namespace -"; + var code = """ + Namespace N + Public Class ReferencedClass + Public Sub M() + Dim x As Integer = 0 + End Sub + End Class + End Namespace + """; // Create a source assembly with a class in Visual Basic solution = AddProjectWithMetadataReferences(solution, "ReferencedProject", LanguageNames.VisualBasic, code, Net40.References.mscorlib); diff --git a/src/EditorFeatures/Test/SymbolKey/SymbolKeyCrossLanguageTests.cs b/src/EditorFeatures/Test/SymbolKey/SymbolKeyCrossLanguageTests.cs index cb257c0228895..2ef71c8998752 100644 --- a/src/EditorFeatures/Test/SymbolKey/SymbolKeyCrossLanguageTests.cs +++ b/src/EditorFeatures/Test/SymbolKey/SymbolKeyCrossLanguageTests.cs @@ -22,20 +22,22 @@ public sealed class SymbolKeyCrossLanguageTests public async Task TestUnsupportedVBTypes(string parameterType) { using var workspace = TestWorkspace.Create( -@$" - - -public class C -{{ - public void M({parameterType} d) {{ }} -}} - - - - CSProject - - -"); + $$""" + + + + public class C + { + public void M({{parameterType}} d) { } + } + + + + CSProject + + + + """); var solution = workspace.CurrentSolution; var csDocument = solution.Projects.Single(p => p.Language == LanguageNames.CSharp).Documents.Single(); diff --git a/src/EditorFeatures/Test/TextEditor/TryGetDocumentTests.cs b/src/EditorFeatures/Test/TextEditor/TryGetDocumentTests.cs index f51c90f853107..e0acd6d7700b4 100644 --- a/src/EditorFeatures/Test/TextEditor/TryGetDocumentTests.cs +++ b/src/EditorFeatures/Test/TextEditor/TryGetDocumentTests.cs @@ -19,8 +19,10 @@ public sealed class TryGetDocumentTests [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624315")] public void MultipleTextChangesTest() { - var code = @"class C -"; + var code = """ + class C + + """; using var workspace = EditorTestWorkspace.CreateCSharp(code); var hostDocument = workspace.Documents.First(); var document = workspace.CurrentSolution.GetDocument(workspace.GetDocumentId(hostDocument)); @@ -35,12 +37,11 @@ public void MultipleTextChangesTest() var newDocument = buffer.CurrentSnapshot.GetRelatedDocumentsWithChanges().FirstOrDefault(); Assert.NotNull(newDocument); - - var expected = @"class C -{ }"; - var newSourceText = newDocument.GetTextAsync().Result; - Assert.Equal(expected, newSourceText.ToString()); + Assert.Equal(""" + class C + { } + """, newSourceText.ToString()); Assert.True(container == newSourceText.Container); } diff --git a/src/EditorFeatures/Test/Utilities/PatternMatcherTests.cs b/src/EditorFeatures/Test/Utilities/PatternMatcherTests.cs index d87581e4931b0..2936d807119fc 100644 --- a/src/EditorFeatures/Test/Utilities/PatternMatcherTests.cs +++ b/src/EditorFeatures/Test/Utilities/PatternMatcherTests.cs @@ -11,6 +11,7 @@ using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PatternMatching; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Utilities; diff --git a/src/EditorFeatures/Test/Utilities/SymbolEquivalenceComparerTests.cs b/src/EditorFeatures/Test/Utilities/SymbolEquivalenceComparerTests.cs index 2a0f3cd3caba4..2b3e164455089 100644 --- a/src/EditorFeatures/Test/Utilities/SymbolEquivalenceComparerTests.cs +++ b/src/EditorFeatures/Test/Utilities/SymbolEquivalenceComparerTests.cs @@ -30,22 +30,24 @@ public sealed class SymbolEquivalenceComparerTests public async Task TestArraysAreEquivalent() { var csharpCode = -@"class C -{ - int intField1; - int[] intArrayField1; - string[] stringArrayField1; - int[][] intArrayArrayField1; - int[,] intArrayRank2Field1; - System.Int32 int32Field1; - - int intField2; - int[] intArrayField2; - string[] stringArrayField2; - int[][] intArrayArrayField2; - int[,] intArrayRank2Field2; - System.Int32 int32Field2; -}"; + """ + class C + { + int intField1; + int[] intArrayField1; + string[] stringArrayField1; + int[][] intArrayArrayField1; + int[,] intArrayRank2Field1; + System.Int32 int32Field1; + + int intField2; + int[] intArrayField2; + string[] stringArrayField2; + int[][] intArrayArrayField2; + int[,] intArrayRank2Field2; + System.Int32 int32Field2; + } + """; using var workspace = TestWorkspace.CreateCSharp(csharpCode); var type = (ITypeSymbol)(await workspace.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("C").Single(); @@ -99,24 +101,28 @@ public async Task TestArraysAreEquivalent() public async Task TestArraysInDifferentLanguagesAreEquivalent() { var csharpCode = -@"class C -{ - int intField1; - int[] intArrayField1; - string[] stringArrayField1; - int[][] intArrayArrayField1; - int[,] intArrayRank2Field1; - System.Int32 int32Field1; -}"; + """ + class C + { + int intField1; + int[] intArrayField1; + string[] stringArrayField1; + int[][] intArrayArrayField1; + int[,] intArrayRank2Field1; + System.Int32 int32Field1; + } + """; var vbCode = -@"class C - dim intField1 as Integer; - dim intArrayField1 as Integer() - dim stringArrayField1 as String() - dim intArrayArrayField1 as Integer()() - dim intArrayRank2Field1 as Integer(,) - dim int32Field1 as System.Int32 -end class"; + """ + class C + dim intField1 as Integer; + dim intArrayField1 as Integer() + dim stringArrayField1 as String() + dim intArrayArrayField1 as Integer()() + dim intArrayRank2Field1 as Integer(,) + dim int32Field1 as System.Int32 + end class + """; using var csharpWorkspace = TestWorkspace.CreateCSharp(csharpCode); using var vbWorkspace = TestWorkspace.CreateVisualBasic(vbCode); @@ -164,30 +170,34 @@ dim int32Field1 as System.Int32 public async Task TestFields() { var csharpCode1 = -@"class Type1 -{ - int field1; - string field2; -} - -class Type2 -{ - bool field3; - short field4; -}"; + """ + class Type1 + { + int field1; + string field2; + } + + class Type2 + { + bool field3; + short field4; + } + """; var csharpCode2 = -@"class Type1 -{ - int field1; - short field4; -} - -class Type2 -{ - bool field3; - string field2; -}"; + """ + class Type1 + { + int field1; + short field4; + } + + class Type2 + { + bool field3; + string field2; + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); @@ -217,28 +227,32 @@ class Type2 public async Task TestFieldsAcrossLanguages() { var csharpCode1 = -@"class Type1 -{ - int field1; - string field2; -} - -class Type2 -{ - bool field3; - short field4; -}"; + """ + class Type1 + { + int field1; + string field2; + } + + class Type2 + { + bool field3; + short field4; + } + """; var vbCode1 = -@"class Type1 - dim field1 as Integer; - dim field4 as Short; -end class - -class Type2 - dim field3 as Boolean; - dim field2 as String; -end class"; + """ + class Type1 + dim field1 as Integer; + dim field4 as Short; + end class + + class Type2 + dim field3 as Boolean; + dim field2 as String; + end class + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateVisualBasic(vbCode1); var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); @@ -265,19 +279,20 @@ class Type2 public async Task TestFieldsInGenericTypes() { var code = -@"class C -{ - int goo; - C intInstantiation1; - C stringInstantiation; - C instanceInstantiation; -} - -class D -{ - C intInstantiation2; -} -"; + """ + class C + { + int goo; + C intInstantiation1; + C stringInstantiation; + C instanceInstantiation; + } + + class D + { + C intInstantiation2; + } + """; using var workspace = TestWorkspace.CreateCSharp(code); var typeC = (await workspace.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("C").Single(); @@ -312,16 +327,20 @@ class D public async Task TestMethodsWithDifferentReturnTypeNotEquivalent() { var csharpCode1 = -@"class Type1 -{ - void Goo() {} -}"; + """ + class Type1 + { + void Goo() {} + } + """; var csharpCode2 = -@"class Type1 -{ - int Goo() {} -}"; + """ + class Type1 + { + int Goo() {} + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); @@ -337,16 +356,20 @@ int Goo() {} public async Task TestMethodsWithDifferentNamesAreNotEquivalent() { var csharpCode1 = -@"class Type1 -{ - void Goo() {} -}"; + """ + class Type1 + { + void Goo() {} + } + """; var csharpCode2 = -@"class Type1 -{ - void Goo1() {} -}"; + """ + class Type1 + { + void Goo1() {} + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); @@ -362,16 +385,20 @@ void Goo1() {} public async Task TestMethodsWithDifferentAritiesAreNotEquivalent() { var csharpCode1 = -@"class Type1 -{ - void Goo() {} -}"; + """ + class Type1 + { + void Goo() {} + } + """; var csharpCode2 = -@"class Type1 -{ - void Goo() {} -}"; + """ + class Type1 + { + void Goo() {} + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); @@ -387,16 +414,20 @@ void Goo() {} public async Task TestMethodsWithDifferentParametersAreNotEquivalent() { var csharpCode1 = -@"class Type1 -{ - void Goo() {} -}"; + """ + class Type1 + { + void Goo() {} + } + """; var csharpCode2 = -@"class Type1 -{ - void Goo(int a) {} -}"; + """ + class Type1 + { + void Goo(int a) {} + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); @@ -412,16 +443,20 @@ void Goo(int a) {} public async Task TestMethodsWithDifferentTypeParameters() { var csharpCode1 = -@"class Type1 -{ - void Goo(A a) {} -}"; + """ + class Type1 + { + void Goo(A a) {} + } + """; var csharpCode2 = -@"class Type1 -{ - void Goo(B a) {} -}"; + """ + class Type1 + { + void Goo(B a) {} + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); @@ -439,16 +474,20 @@ void Goo(B a) {} public async Task TestMethodsWithSameParameters() { var csharpCode1 = -@"class Type1 -{ - void Goo(int a) {} -}"; + """ + class Type1 + { + void Goo(int a) {} + } + """; var csharpCode2 = -@"class Type1 -{ - void Goo(int a) {} -}"; + """ + class Type1 + { + void Goo(int a) {} + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); @@ -466,16 +505,20 @@ void Goo(int a) {} public async Task TestMethodsWithDifferentParameterNames() { var csharpCode1 = -@"class Type1 -{ - void Goo(int a) {} -}"; + """ + class Type1 + { + void Goo(int a) {} + } + """; var csharpCode2 = -@"class Type1 -{ - void Goo(int b) {} -}"; + """ + class Type1 + { + void Goo(int b) {} + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); @@ -493,16 +536,20 @@ void Goo(int b) {} public async Task TestMethodsAreEquivalentOutToRef() { var csharpCode1 = -@"class Type1 -{ - void Goo(out int a) {} -}"; + """ + class Type1 + { + void Goo(out int a) {} + } + """; var csharpCode2 = -@"class Type1 -{ - void Goo(ref int a) {} -}"; + """ + class Type1 + { + void Goo(ref int a) {} + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); @@ -518,16 +565,20 @@ void Goo(ref int a) {} public async Task TestMethodsNotEquivalentRemoveOut() { var csharpCode1 = -@"class Type1 -{ - void Goo(out int a) {} -}"; + """ + class Type1 + { + void Goo(out int a) {} + } + """; var csharpCode2 = -@"class Type1 -{ - void Goo(int a) {} -}"; + """ + class Type1 + { + void Goo(int a) {} + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); @@ -543,16 +594,20 @@ void Goo(int a) {} public async Task TestMethodsAreEquivalentIgnoreParams() { var csharpCode1 = -@"class Type1 -{ - void Goo(params int[] a) {} -}"; + """ + class Type1 + { + void Goo(params int[] a) {} + } + """; var csharpCode2 = -@"class Type1 -{ - void Goo(int[] a) {} -}"; + """ + class Type1 + { + void Goo(int[] a) {} + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); @@ -570,16 +625,20 @@ void Goo(int[] a) {} public async Task TestMethodsNotEquivalentDifferentParameterTypes() { var csharpCode1 = -@"class Type1 -{ - void Goo(int[] a) {} -}"; + """ + class Type1 + { + void Goo(int[] a) {} + } + """; var csharpCode2 = -@"class Type1 -{ - void Goo(string[] a) {} -}"; + """ + class Type1 + { + void Goo(string[] a) {} + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); @@ -595,25 +654,27 @@ void Goo(string[] a) {} public async Task TestMethodsAcrossLanguages() { var csharpCode1 = -@" -using System.Collections.Generic; + """ + using System.Collections.Generic; -class Type1 -{ - T Goo(IList list, int a) {} - void Bar() { } -}"; + class Type1 + { + T Goo(IList list, int a) {} + void Bar() { } + } + """; var vbCode1 = -@" -Imports System.Collections.Generic - -class Type1 - function Goo(of U)(list as IList(of U), a as Integer) as U - end function - sub Quux() - end sub -end class"; + """ + Imports System.Collections.Generic + + class Type1 + function Goo(of U)(list as IList(of U), a as Integer) as U + end function + sub Quux() + end sub + end class + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateVisualBasic(vbCode1); var csharpType1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); @@ -640,25 +701,27 @@ end sub public async Task TestMethodsInGenericTypesAcrossLanguages() { var csharpCode1 = -@" -using System.Collections.Generic; + """ + using System.Collections.Generic; -class Type1 -{ - T Goo(IList list, X a) {} - void Bar(X x) { } -}"; + class Type1 + { + T Goo(IList list, X a) {} + void Bar(X x) { } + } + """; var vbCode1 = -@" -Imports System.Collections.Generic - -class Type1(of M) - function Goo(of U)(list as IList(of U), a as M) as U - end function - sub Bar(x as Object) - end sub -end class"; + """ + Imports System.Collections.Generic + + class Type1(of M) + function Goo(of U)(list as IList(of U), a as M) as U + end function + sub Bar(x as Object) + end sub + end class + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateVisualBasic(vbCode1); var csharpType1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); @@ -685,11 +748,13 @@ end sub public async Task TestObjectAndDynamicAreNotEqualNormally() { var csharpCode1 = -@"class Type1 -{ - object field1; - dynamic field2; -}"; + """ + class Type1 + { + object field1; + dynamic field2; + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); @@ -705,16 +770,20 @@ public async Task TestObjectAndDynamicAreNotEqualNormally() public async Task TestObjectAndDynamicAreEqualInSignatures() { var csharpCode1 = -@"class Type1 -{ - void Goo(object o1) { } -}"; + """ + class Type1 + { + void Goo(object o1) { } + } + """; var csharpCode2 = -@"class Type1 -{ - void Goo(dynamic o1) { } -}"; + """ + class Type1 + { + void Goo(dynamic o1) { } + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); @@ -734,22 +803,24 @@ void Goo(dynamic o1) { } public async Task TestUnequalGenericsInSignatures() { var csharpCode1 = -@" -using System.Collections.Generic; + """ + using System.Collections.Generic; -class Type1 -{ - void Goo(IList o1) { } -}"; + class Type1 + { + void Goo(IList o1) { } + } + """; var csharpCode2 = -@" -using System.Collections.Generic; + """ + using System.Collections.Generic; -class Type1 -{ - void Goo(IList o1) { } -}"; + class Type1 + { + void Goo(IList o1) { } + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); @@ -767,22 +838,24 @@ void Goo(IList o1) { } public async Task TestGenericsWithDynamicAndObjectInSignatures() { var csharpCode1 = -@" -using System.Collections.Generic; + """ + using System.Collections.Generic; -class Type1 -{ - void Goo(IList o1) { } -}"; + class Type1 + { + void Goo(IList o1) { } + } + """; var csharpCode2 = -@" -using System.Collections.Generic; + """ + using System.Collections.Generic; -class Type1 -{ - void Goo(IList o1) { } -}"; + class Type1 + { + void Goo(IList o1) { } + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); @@ -802,22 +875,24 @@ void Goo(IList o1) { } public async Task TestDynamicAndUnrelatedTypeInSignatures() { var csharpCode1 = -@" -using System.Collections.Generic; + """ + using System.Collections.Generic; -class Type1 -{ - void Goo(dynamic o1) { } -}"; + class Type1 + { + void Goo(dynamic o1) { } + } + """; var csharpCode2 = -@" -using System.Collections.Generic; + """ + using System.Collections.Generic; -class Type1 -{ - void Goo(string o1) { } -}"; + class Type1 + { + void Goo(string o1) { } + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); @@ -835,20 +910,21 @@ void Goo(string o1) { } public async Task TestNamespaces() { var csharpCode1 = -@"namespace Outer -{ - namespace Inner - { - class Type - { - } - } - - class Type - { - } -} -"; + """ + namespace Outer + { + namespace Inner + { + class Type + { + } + } + + class Type + { + } + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode1); @@ -906,26 +982,27 @@ class Type public async Task TestNamedTypesEquivalent() { var csharpCode1 = -@" -class Type1 -{ -} + """ + class Type1 + { + } -class Type2 -{ -} -"; + class Type2 + { + } + """; var csharpCode2 = -@" -class Type1 -{ - void Goo(); -} + """ + class Type1 + { + void Goo(); + } -class Type2 -{ -}"; + class Type2 + { + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); @@ -952,17 +1029,19 @@ class Type2 public async Task TestNamedTypesDifferentIfNameChanges() { var csharpCode1 = -@" -class Type1 -{ -}"; + """ + class Type1 + { + } + """; var csharpCode2 = -@" -class Type2 -{ - void Goo(); -}"; + """ + class Type2 + { + void Goo(); + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); @@ -977,17 +1056,19 @@ class Type2 public async Task TestNamedTypesDifferentIfTypeKindChanges() { var csharpCode1 = -@" -struct Type1 -{ -}"; + """ + struct Type1 + { + } + """; var csharpCode2 = -@" -class Type1 -{ - void Goo(); -}"; + """ + class Type1 + { + void Goo(); + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); @@ -1002,17 +1083,19 @@ class Type1 public async Task TestNamedTypesDifferentIfArityChanges() { var csharpCode1 = -@" -class Type1 -{ -}"; + """ + class Type1 + { + } + """; var csharpCode2 = -@" -class Type1 -{ - void Goo(); -}"; + """ + class Type1 + { + void Goo(); + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); @@ -1027,23 +1110,25 @@ class Type1 public async Task TestNamedTypesDifferentIfContainerDifferent() { var csharpCode1 = -@" -class Outer -{ - class Type1 - { - } -}"; + """ + class Outer + { + class Type1 + { + } + } + """; var csharpCode2 = -@" -class Other -{ - class Type1 - { - void Goo(); - } -}"; + """ + class Other + { + class Type1 + { + void Goo(); + } + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); @@ -1060,20 +1145,22 @@ class Type1 public async Task TestAliasedTypes1() { var csharpCode1 = -@" -using i = System.Int32; + """ + using i = System.Int32; -class Type1 -{ - void Goo(i o1) { } -}"; + class Type1 + { + void Goo(i o1) { } + } + """; var csharpCode2 = -@" -class Type1 -{ - void Goo(int o1) { } -}"; + """ + class Type1 + { + void Goo(int o1) { } + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); @@ -1093,18 +1180,20 @@ void Goo(int o1) { } public async Task TestRefVersusOut() { var csharpCode1 = -@" -class C -{ - void M(out int i) { } -}"; + """ + class C + { + void M(out int i) { } + } + """; var csharpCode2 = -@" -class C -{ - void M(ref int i) { } -}"; + """ + class C + { + void M(ref int i) { } + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); @@ -1133,18 +1222,20 @@ void M(ref int i) { } public async Task TestTuples1() { var csharpCode1 = -@" -class C -{ - void M((int, int) i) { } -}"; + """ + class C + { + void M((int, int) i) { } + } + """; var csharpCode2 = -@" -class C -{ - void M(int i) { } -}"; + """ + class C + { + void M(int i) { } + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); @@ -1163,18 +1254,20 @@ void M(int i) { } public async Task TestTuples2() { var csharpCode1 = -@" -class C -{ - void M((int, int) i) { } -}"; + """ + class C + { + void M((int, int) i) { } + } + """; var csharpCode2 = -@" -class C -{ - void M(System.ValueTuple i) { } -}"; + """ + class C + { + void M(System.ValueTuple i) { } + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); @@ -1193,18 +1286,20 @@ void M(System.ValueTuple i) { } public async Task TestTuples3() { var csharpCode1 = -@" -class C -{ - void M((int, int) i) { } -}"; + """ + class C + { + void M((int, int) i) { } + } + """; var csharpCode2 = -@" -class C -{ - void M(System.ValueTuple i) { } -}"; + """ + class C + { + void M(System.ValueTuple i) { } + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); @@ -1224,18 +1319,20 @@ void M(System.ValueTuple i) { } public async Task TestTuples4() { var csharpCode1 = -@" -class C -{ - void M((int a, int b) i) { } -}"; + """ + class C + { + void M((int a, int b) i) { } + } + """; var csharpCode2 = -@" -class C -{ - void M(System.ValueTuple i) { } -}"; + """ + class C + { + void M(System.ValueTuple i) { } + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); @@ -1255,18 +1352,20 @@ void M(System.ValueTuple i) { } public async Task TestTuples5() { var csharpCode1 = -@" -class C -{ - void M((int a, int b) i) { } -}"; + """ + class C + { + void M((int a, int b) i) { } + } + """; var csharpCode2 = -@" -class C -{ - void M((int, int) i) { } -}"; + """ + class C + { + void M((int, int) i) { } + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); @@ -1287,18 +1386,20 @@ void M((int, int) i) { } public async Task TestTuples6() { var csharpCode1 = -@" -class C -{ - void M((int a, int b) i) { } -}"; + """ + class C + { + void M((int a, int b) i) { } + } + """; var csharpCode2 = -@" -class C -{ - void M((int a, int b, int c) i) { } -}"; + """ + class C + { + void M((int a, int b, int c) i) { } + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); @@ -1316,26 +1417,28 @@ public async Task TestNullableBothEnabled() { // Both are nullable enabled. So `T?` should not be equal to `T` unless we are ignoring nullability. var csharpCode1 = -@" -#nullable enable -class T -{ - string? A; - string[]? B; - dynamic? C; - dynamic?[]? D; -}"; + """ + #nullable enable + class T + { + string? A; + string[]? B; + dynamic? C; + dynamic?[]? D; + } + """; var csharpCode2 = -@" -#nullable enable -class T -{ - string A; - string[] B; - dynamic C; - dynamic[] D; -}"; + """ + #nullable enable + class T + { + string A; + string[] B; + dynamic C; + dynamic[] D; + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); @@ -1380,26 +1483,28 @@ public async Task TestNullableDisableVsEnable1() // type without nullability. var csharpCode1 = -@" -#nullable disable -class T -{ - string A; - string[] B; - dynamic C; - dynamic[] D; -}"; + """ + #nullable disable + class T + { + string A; + string[] B; + dynamic C; + dynamic[] D; + } + """; var csharpCode2 = -@" -#nullable enable -class T -{ - string A; - string[] B; - dynamic C; - dynamic[] D; -}"; + """ + #nullable enable + class T + { + string A; + string[] B; + dynamic C; + dynamic[] D; + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); @@ -1443,26 +1548,28 @@ public async Task TestNullableDisableVsEnable2() // One side is nullable disabled. One side definitely annotated. Treat as different. var csharpCode1 = -@" -#nullable disable -class T -{ - string A; - string[] B; - dynamic C; - dynamic[] D; -}"; + """ + #nullable disable + class T + { + string A; + string[] B; + dynamic C; + dynamic[] D; + } + """; var csharpCode2 = -@" -#nullable enable -class T -{ - string? A; - string?[] B; - dynamic? C; - dynamic?[] D; -}"; + """ + #nullable enable + class T + { + string? A; + string?[] B; + dynamic? C; + dynamic?[] D; + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); @@ -1506,26 +1613,28 @@ public async Task TestNullableDisableVsEnable3() // One side is nullable disabled. One side definitely annotated. Treat as different. var csharpCode1 = -@" -#nullable disable -class T -{ - string A; - string[] B; - dynamic C; - dynamic[] D; -}"; + """ + #nullable disable + class T + { + string A; + string[] B; + dynamic C; + dynamic[] D; + } + """; var csharpCode2 = -@" -#nullable enable -class T -{ - string? A; - string[]? B; - dynamic? C; - dynamic[]? D; -}"; + """ + #nullable enable + class T + { + string? A; + string[]? B; + dynamic? C; + dynamic[]? D; + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode1); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode2); @@ -1566,55 +1675,55 @@ class T [Fact] public async Task TestCSharpReducedExtensionMethodsAreEquivalent() { - var code = @" -class Zed {} - -public static class Extensions -{ - public static void NotGeneric(this Zed z, int data) { } - public static void GenericThis(this T me, int data) where T : Zed { } - public static void GenericNotThis(this Zed z, T data) { } - public static void GenericThisAndMore(this T me, S data) where T : Zed { } - public static void GenericThisAndOther(this T me, T data) where T : Zed { } -} - -class Test -{ - void NotGeneric() - { - Zed z; - int n; - z.NotGeneric(n); - } - - void GenericThis() - { - Zed z; - int n; - z.GenericThis(n); - } - - void GenericNotThis() - { - Zed z; - int n; - z.GenericNotThis(n); - } - - void GenericThisAndMore() - { - Zed z; - int n; - z.GenericThisAndMore(n); - } - - void GenericThisAndOther() - { - Zed z; - z.GenericThisAndOther(z); - } -} -"; + var code = """ + class Zed {} + + public static class Extensions + { + public static void NotGeneric(this Zed z, int data) { } + public static void GenericThis(this T me, int data) where T : Zed { } + public static void GenericNotThis(this Zed z, T data) { } + public static void GenericThisAndMore(this T me, S data) where T : Zed { } + public static void GenericThisAndOther(this T me, T data) where T : Zed { } + } + + class Test + { + void NotGeneric() + { + Zed z; + int n; + z.NotGeneric(n); + } + + void GenericThis() + { + Zed z; + int n; + z.GenericThis(n); + } + + void GenericNotThis() + { + Zed z; + int n; + z.GenericNotThis(n); + } + + void GenericThisAndMore() + { + Zed z; + int n; + z.GenericThisAndMore(n); + } + + void GenericThisAndOther() + { + Zed z; + z.GenericThisAndOther(z); + } + } + """; using var workspace1 = TestWorkspace.CreateCSharp(code); using var workspace2 = TestWorkspace.CreateCSharp(code); var comp1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()); @@ -1630,65 +1739,65 @@ void GenericThisAndOther() [Fact] public async Task TestVisualBasicReducedExtensionMethodsAreEquivalent() { - var code = @" -Imports System.Runtime.CompilerServices - -Class Zed -End Class - -Module Extensions - - Public Sub NotGeneric(z As Zed, data As Integer) - End Sub - - - Public Sub GenericThis(Of T As Zed)(m As T, data as Integer) - End Sub - - - Public Sub GenericNotThis(Of T)(z As Zed, data As T) - End Sub - - - Public Sub GenericThisAndMore(Of T As Zed, S)(m As T, data As S) - End Sub - - - Public Sub GenericThisAndOther(Of T As Zed)(m As T, data As T) - End Sub -End Module - -Class Test - Sub NotGeneric() - Dim z As Zed - Dim n As Integer - z.NotGeneric(n) - End Sub - - Sub GenericThis() - Dim z As Zed - Dim n As Integer - z.GenericThis(n) - End Sub - - Sub GenericNotThis() - Dim z As Zed - Dim n As Integer - z.GenericNotThis(n) - End Sub - - Sub GenericThisAndMore() - Dim z As Zed - Dim n As Integer - z.GenericThisAndMore(n) - End Sub - - Sub GenericThisAndOther() - Dim z As Zed - z.GenericThisAndOther(z) - End Sub -End Class -"; + var code = """ + Imports System.Runtime.CompilerServices + + Class Zed + End Class + + Module Extensions + + Public Sub NotGeneric(z As Zed, data As Integer) + End Sub + + + Public Sub GenericThis(Of T As Zed)(m As T, data as Integer) + End Sub + + + Public Sub GenericNotThis(Of T)(z As Zed, data As T) + End Sub + + + Public Sub GenericThisAndMore(Of T As Zed, S)(m As T, data As S) + End Sub + + + Public Sub GenericThisAndOther(Of T As Zed)(m As T, data As T) + End Sub + End Module + + Class Test + Sub NotGeneric() + Dim z As Zed + Dim n As Integer + z.NotGeneric(n) + End Sub + + Sub GenericThis() + Dim z As Zed + Dim n As Integer + z.GenericThis(n) + End Sub + + Sub GenericNotThis() + Dim z As Zed + Dim n As Integer + z.GenericNotThis(n) + End Sub + + Sub GenericThisAndMore() + Dim z As Zed + Dim n As Integer + z.GenericThisAndMore(n) + End Sub + + Sub GenericThisAndOther() + Dim z As Zed + z.GenericThisAndOther(z) + End Sub + End Class + """; using var workspace1 = TestWorkspace.CreateVisualBasic(code); using var workspace2 = TestWorkspace.CreateVisualBasic(code); var comp1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()); @@ -1705,12 +1814,14 @@ End Class public async Task TestDifferentModules() { var csharpCode = -@"namespace N -{ - namespace M - { - } -}"; + """ + namespace N + { + namespace M + { + } + } + """; using var workspace1 = TestWorkspace.CreateCSharp(csharpCode, compilationOptions: new CS.CSharpCompilationOptions(OutputKind.NetModule, moduleName: "GooModule")); using var workspace2 = TestWorkspace.CreateCSharp(csharpCode, compilationOptions: new CS.CSharpCompilationOptions(OutputKind.NetModule, moduleName: "BarModule")); @@ -1785,42 +1896,42 @@ public int GetHashCode(IAssemblySymbol obj) [Fact] public void CustomModifiers_Methods1() { - const string ilSource = @" -.class public C -{ - .method public instance int32 [] modopt([mscorlib]System.Int64) F( // 0 - int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, - int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) - { - ldnull - throw - } - - .method public instance int32 [] modopt([mscorlib]System.Boolean) F( // 1 - int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, - int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) - { - ldnull - throw - } - - .method public instance int32[] F( // 2 - int32 a, - int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) - { - ldnull - throw - } - - .method public instance int32[] F( // 3 - int32 a, - int32 b) - { - ldnull - throw - } -} -"; + const string ilSource = """ + .class public C + { + .method public instance int32 [] modopt([mscorlib]System.Int64) F( // 0 + int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, + int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) + { + ldnull + throw + } + + .method public instance int32 [] modopt([mscorlib]System.Boolean) F( // 1 + int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, + int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) + { + ldnull + throw + } + + .method public instance int32[] F( // 2 + int32 a, + int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) + { + ldnull + throw + } + + .method public instance int32[] F( // 3 + int32 a, + int32 b) + { + ldnull + throw + } + } + """; MetadataReference r1, r2; using (var tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource)) { diff --git a/src/EditorFeatures/Test/ValueTracking/AbstractBaseValueTrackingTests.cs b/src/EditorFeatures/Test/ValueTracking/AbstractBaseValueTrackingTests.cs index e039d4f6d3b4c..db07c476304be 100644 --- a/src/EditorFeatures/Test/ValueTracking/AbstractBaseValueTrackingTests.cs +++ b/src/EditorFeatures/Test/ValueTracking/AbstractBaseValueTrackingTests.cs @@ -2,17 +2,17 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Linq; +using System.Collections.Generic; using System.Collections.Immutable; +using System.Linq; +using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis.ValueTracking; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; -using System.Threading; using Microsoft.CodeAnalysis.Text; +using Microsoft.CodeAnalysis.ValueTracking; using Xunit; -using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Editor.UnitTests.ValueTracking; diff --git a/src/EditorFeatures/Test/ValueTracking/VisualBasicValueTrackingTests.cs b/src/EditorFeatures/Test/ValueTracking/VisualBasicValueTrackingTests.cs index 471e9c96e7b5e..3a4c76cd0e717 100644 --- a/src/EditorFeatures/Test/ValueTracking/VisualBasicValueTrackingTests.cs +++ b/src/EditorFeatures/Test/ValueTracking/VisualBasicValueTrackingTests.cs @@ -20,28 +20,30 @@ protected override TestWorkspace CreateWorkspace(string code, TestComposition co public async Task TestProperty(TestHost testHost) { var code = -@" -Class C - Private _s As String - Public Property $$S() As String - Get - Return _s - End Get - Set(ByVal value As String) - _s = value - End Set - End Property - - - Public Sub SetS(s As String) - Me.S = s - End Sub - - Public Function GetS() As String - Return Me.S - End Function -End Class -"; + """ + + Class C + Private _s As String + Public Property $$S() As String + Get + Return _s + End Get + Set(ByVal value As String) + _s = value + End Set + End Property + + + Public Sub SetS(s As String) + Me.S = s + End Sub + + Public Function GetS() As String + Return Me.S + End Function + End Class + + """; using var workspace = CreateWorkspace(code, testHost); var initialItems = await GetTrackedItemsAsync(workspace); @@ -60,28 +62,30 @@ End Class public async Task TestPropertyValue(TestHost testHost) { var code = -@" -Class C - Private _s As String - Public Property S() As String - Get - Return _s - End Get - Set(ByVal value As String) - _s = $$value - End Set - End Property - - - Public Sub SetS(s As String) - Me.S = s - End Sub - - Public Function GetS() As String - Return Me.S - End Function -End Class -"; + """ + + Class C + Private _s As String + Public Property S() As String + Get + Return _s + End Get + Set(ByVal value As String) + _s = $$value + End Set + End Property + + + Public Sub SetS(s As String) + Me.S = s + End Sub + + Public Function GetS() As String + Return Me.S + End Function + End Class + + """; // // _s = value [Code.vb:8] @@ -111,19 +115,21 @@ End Class public async Task TestField(TestHost testHost) { var code = -@" -Class C - Private $$_s As String = """" - - Public Sub SetS(s As String) - Me._s = s - End Sub - - Public Function GetS() As String - Return Me._s - End Function -End Class -"; + """ + + Class C + Private $$_s As String = "" + + Public Sub SetS(s As String) + Me._s = s + End Sub + + Public Function GetS() As String + Return Me._s + End Function + End Class + + """; using var workspace = CreateWorkspace(code, testHost); var initialItems = await GetTrackedItemsAsync(workspace); @@ -146,15 +152,17 @@ await ValidateItemsAsync( public async Task TestLocal(TestHost testHost) { var code = -@" -Class C - Public Function Add(x As Integer, y As Integer) As Integer - Dim $$z = x - z += y - Return z - End Function -End Class -"; + """ + + Class C + Public Function Add(x As Integer, y As Integer) As Integer + Dim $$z = x + z += y + Return z + End Function + End Class + + """; using var workspace = CreateWorkspace(code, testHost); var initialItems = await GetTrackedItemsAsync(workspace); @@ -173,14 +181,16 @@ End Class public async Task TestParameter(TestHost testHost) { var code = -@" -Class C - Public Function Add($$x As Integer, y As Integer) As Integer - x += y - Return x - End Function -End Class -"; + """ + + Class C + Public Function Add($$x As Integer, y As Integer) As Integer + x += y + Return x + End Function + End Class + + """; using var workspace = CreateWorkspace(code, testHost); var initialItems = await GetTrackedItemsAsync(workspace); @@ -199,19 +209,21 @@ End Class public async Task TestVariableReferenceStart(TestHost testHost) { var code = -@" -Class Test - Public Sub M() - Dim x = GetM() - Console.Write(x) - Dim y = $$x + 1 - End Sub - - Public Function GetM() As Integer - Dim x = 0 - Return x - End Function -End Class"; + """ + + Class Test + Public Sub M() + Dim x = GetM() + Console.Write(x) + Dim y = $$x + 1 + End Sub + + Public Function GetM() As Integer + Dim x = 0 + Return x + End Function + End Class + """; // // |> Dim y = x + 1 [Code.vb:7] @@ -258,19 +270,21 @@ End Function public async Task TestVariableReferenceStart2(TestHost testHost) { var code = -@" -Class Test - Public Sub M() - Dim x = GetM() - Console.Write($$x) - Dim y = x + 1 - End Sub - - Public Function GetM() As Integer - Dim x = 0 - Return x - End Function -End Class"; + """ + + Class Test + Public Sub M() + Dim x = GetM() + Console.Write($$x) + Dim y = x + 1 + End Sub + + Public Function GetM() As Integer + Dim x = 0 + Return x + End Function + End Class + """; // // |> Dim y = x + 1 [Code.vb:7] @@ -317,21 +331,23 @@ End Function public async Task TestMultipleDeclarators(TestHost testHost) { var code = -@" -Imports System - -Class Test - Public Sub M() - Dim x = GetM(), z = 1, m As Boolean, n As Boolean, o As Boolean - Console.Write(x) - Dim y = $$x + 1 - End Sub - - Public Function GetM() As Integer - Dim x = 0 - Return x - End Function -End Class"; + """ + + Imports System + + Class Test + Public Sub M() + Dim x = GetM(), z = 1, m As Boolean, n As Boolean, o As Boolean + Console.Write(x) + Dim y = $$x + 1 + End Sub + + Public Function GetM() As Integer + Dim x = 0 + Return x + End Function + End Class + """; // // |> Dim y = x + 1 [Code.vb:7] diff --git a/src/EditorFeatures/Test2/Classification/ClassificationTests.vb b/src/EditorFeatures/Test2/Classification/ClassificationTests.vb index 166ada785d62b..fb632742a6f6a 100644 --- a/src/EditorFeatures/Test2/Classification/ClassificationTests.vb +++ b/src/EditorFeatures/Test2/Classification/ClassificationTests.vb @@ -18,7 +18,6 @@ Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.UnitTests Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Classification -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Classification diff --git a/src/EditorFeatures/Test2/Classification/SyntacticChangeRangeComputerTests.vb b/src/EditorFeatures/Test2/Classification/SyntacticChangeRangeComputerTests.vb index 8fab33c07bc3a..93b1f26f3f7a1 100644 --- a/src/EditorFeatures/Test2/Classification/SyntacticChangeRangeComputerTests.vb +++ b/src/EditorFeatures/Test2/Classification/SyntacticChangeRangeComputerTests.vb @@ -4,7 +4,6 @@ Imports System.Text Imports Microsoft.CodeAnalysis.Classification -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Classification diff --git a/src/EditorFeatures/Test2/CodeDefinitionWindow/AbstractCodeDefinitionWindowTests.vb b/src/EditorFeatures/Test2/CodeDefinitionWindow/AbstractCodeDefinitionWindowTests.vb index 275aa87f0741e..8d4960fa42a12 100644 --- a/src/EditorFeatures/Test2/CodeDefinitionWindow/AbstractCodeDefinitionWindowTests.vb +++ b/src/EditorFeatures/Test2/CodeDefinitionWindow/AbstractCodeDefinitionWindowTests.vb @@ -6,6 +6,7 @@ Imports System.Collections.Immutable Imports System.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.CodeDefinitionWindow +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces diff --git a/src/EditorFeatures/Test2/CodeDefinitionWindow/CSharpCodeDefinitionWindowTests.vb b/src/EditorFeatures/Test2/CodeDefinitionWindow/CSharpCodeDefinitionWindowTests.vb index a4dd9670fc9dc..dc82bc9b0a445 100644 --- a/src/EditorFeatures/Test2/CodeDefinitionWindow/CSharpCodeDefinitionWindowTests.vb +++ b/src/EditorFeatures/Test2/CodeDefinitionWindow/CSharpCodeDefinitionWindowTests.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces - Namespace Microsoft.CodeAnalysis.Editor.CodeDefinitionWindow.UnitTests diff --git a/src/EditorFeatures/Test2/CodeDefinitionWindow/CrossLanguageCodeDefinitionWindowTests.vb b/src/EditorFeatures/Test2/CodeDefinitionWindow/CrossLanguageCodeDefinitionWindowTests.vb index e38537ca2c832..e2ea546514054 100644 --- a/src/EditorFeatures/Test2/CodeDefinitionWindow/CrossLanguageCodeDefinitionWindowTests.vb +++ b/src/EditorFeatures/Test2/CodeDefinitionWindow/CrossLanguageCodeDefinitionWindowTests.vb @@ -6,13 +6,10 @@ Imports System.Collections.Immutable Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.CodeDefinitionWindow -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.GoToDefinition Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Navigation Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.UnitTests -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.Editor.CodeDefinitionWindow.UnitTests diff --git a/src/EditorFeatures/Test2/CodeDefinitionWindow/VisualBasicCodeDefinitionWindowTests.vb b/src/EditorFeatures/Test2/CodeDefinitionWindow/VisualBasicCodeDefinitionWindowTests.vb index d8245a9b0a448..bcfff72ed7982 100644 --- a/src/EditorFeatures/Test2/CodeDefinitionWindow/VisualBasicCodeDefinitionWindowTests.vb +++ b/src/EditorFeatures/Test2/CodeDefinitionWindow/VisualBasicCodeDefinitionWindowTests.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces - Namespace Microsoft.CodeAnalysis.Editor.CodeDefinitionWindow.UnitTests diff --git a/src/EditorFeatures/Test2/Diagnostics/AddImport/AddImportCrossLanguageTests.vb b/src/EditorFeatures/Test2/Diagnostics/AddImport/AddImportCrossLanguageTests.vb index 379f7ef01468c..f548332549517 100644 --- a/src/EditorFeatures/Test2/Diagnostics/AddImport/AddImportCrossLanguageTests.vb +++ b/src/EditorFeatures/Test2/Diagnostics/AddImport/AddImportCrossLanguageTests.vb @@ -3,17 +3,14 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable +Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CSharp.AddImport Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.FindSymbols.SymbolTree -Imports Microsoft.CodeAnalysis.SolutionCrawler Imports Microsoft.CodeAnalysis.Tags Imports Microsoft.CodeAnalysis.VisualBasic.AddImport Imports Roslyn.Utilities -Imports Microsoft.CodeAnalysis.CodeActions Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.AddImport diff --git a/src/EditorFeatures/Test2/Diagnostics/AddMissingReference/AddMissingReferenceTests.vb b/src/EditorFeatures/Test2/Diagnostics/AddMissingReference/AddMissingReferenceTests.vb index 6b985b7390aec..2d46088271970 100644 --- a/src/EditorFeatures/Test2/Diagnostics/AddMissingReference/AddMissingReferenceTests.vb +++ b/src/EditorFeatures/Test2/Diagnostics/AddMissingReference/AddMissingReferenceTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Reflection -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CSharp.AddMissingReference Imports Microsoft.CodeAnalysis.Diagnostics diff --git a/src/EditorFeatures/Test2/Diagnostics/AdditionalFileDiagnosticsTests.vb b/src/EditorFeatures/Test2/Diagnostics/AdditionalFileDiagnosticsTests.vb index 1f0349b7979f4..5a48606469e4e 100644 --- a/src/EditorFeatures/Test2/Diagnostics/AdditionalFileDiagnosticsTests.vb +++ b/src/EditorFeatures/Test2/Diagnostics/AdditionalFileDiagnosticsTests.vb @@ -4,11 +4,9 @@ Imports System.Collections.Immutable Imports System.Threading -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.UnitTests diff --git a/src/EditorFeatures/Test2/Diagnostics/GenerateEvent/GenerateEventCrossLanguageTests.vb b/src/EditorFeatures/Test2/Diagnostics/GenerateEvent/GenerateEventCrossLanguageTests.vb index e0cdd2e70b8f4..7d8d9f2665112 100644 --- a/src/EditorFeatures/Test2/Diagnostics/GenerateEvent/GenerateEventCrossLanguageTests.vb +++ b/src/EditorFeatures/Test2/Diagnostics/GenerateEvent/GenerateEventCrossLanguageTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics diff --git a/src/EditorFeatures/Test2/Diagnostics/GenerateFromUsage/GenerateMethodCrossLanguageTests.vb b/src/EditorFeatures/Test2/Diagnostics/GenerateFromUsage/GenerateMethodCrossLanguageTests.vb index 57c41327250ed..71cb4dbecc9a7 100644 --- a/src/EditorFeatures/Test2/Diagnostics/GenerateFromUsage/GenerateMethodCrossLanguageTests.vb +++ b/src/EditorFeatures/Test2/Diagnostics/GenerateFromUsage/GenerateMethodCrossLanguageTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Xunit.Abstractions diff --git a/src/EditorFeatures/Test2/Diagnostics/GenerateFromUsage/GenerateVariableCrossLanguageTests.vb b/src/EditorFeatures/Test2/Diagnostics/GenerateFromUsage/GenerateVariableCrossLanguageTests.vb index 692c6a36a38c4..a41d267ee7fdd 100644 --- a/src/EditorFeatures/Test2/Diagnostics/GenerateFromUsage/GenerateVariableCrossLanguageTests.vb +++ b/src/EditorFeatures/Test2/Diagnostics/GenerateFromUsage/GenerateVariableCrossLanguageTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CSharp.GenerateVariable diff --git a/src/EditorFeatures/Test2/Expansion/AbstractExpansionTest.vb b/src/EditorFeatures/Test2/Expansion/AbstractExpansionTest.vb index bf180f3f0b201..ee6f8d67c00f1 100644 --- a/src/EditorFeatures/Test2/Expansion/AbstractExpansionTest.vb +++ b/src/EditorFeatures/Test2/Expansion/AbstractExpansionTest.vb @@ -10,7 +10,6 @@ Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.Text -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Expansion <[UseExportProvider]> diff --git a/src/EditorFeatures/Test2/Expansion/ExtensionMethodExpansionRewriteTests.vb b/src/EditorFeatures/Test2/Expansion/ExtensionMethodExpansionRewriteTests.vb index 942613c950d43..9d20151191e57 100644 --- a/src/EditorFeatures/Test2/Expansion/ExtensionMethodExpansionRewriteTests.vb +++ b/src/EditorFeatures/Test2/Expansion/ExtensionMethodExpansionRewriteTests.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks - Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Expansion Public Class ExtensionMethodExpansionRewriteTests diff --git a/src/EditorFeatures/Test2/Expansion/LambdaParameterExpansionTests.vb b/src/EditorFeatures/Test2/Expansion/LambdaParameterExpansionTests.vb index e096240944898..5cff9d94658d6 100644 --- a/src/EditorFeatures/Test2/Expansion/LambdaParameterExpansionTests.vb +++ b/src/EditorFeatures/Test2/Expansion/LambdaParameterExpansionTests.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks - Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Expansion Public Class LambdaParameterExpansionTests diff --git a/src/EditorFeatures/Test2/Expansion/ModuleNameExpansionTests.vb b/src/EditorFeatures/Test2/Expansion/ModuleNameExpansionTests.vb index c46c75ecb0ccd..760b420fcb05c 100644 --- a/src/EditorFeatures/Test2/Expansion/ModuleNameExpansionTests.vb +++ b/src/EditorFeatures/Test2/Expansion/ModuleNameExpansionTests.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks - Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Expansion Public Class ModuleNameExpansionTests diff --git a/src/EditorFeatures/Test2/Expansion/NameExpansionTests.vb b/src/EditorFeatures/Test2/Expansion/NameExpansionTests.vb index 659a3179f7ace..67290d55d31f7 100644 --- a/src/EditorFeatures/Test2/Expansion/NameExpansionTests.vb +++ b/src/EditorFeatures/Test2/Expansion/NameExpansionTests.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks - Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Expansion Public Class NameExpansionTests diff --git a/src/EditorFeatures/Test2/Extensions/ISymbolExtensionsTests.vb b/src/EditorFeatures/Test2/Extensions/ISymbolExtensionsTests.vb index a4f3884fb8da9..d5f8160e40c6f 100644 --- a/src/EditorFeatures/Test2/Extensions/ISymbolExtensionsTests.vb +++ b/src/EditorFeatures/Test2/Extensions/ISymbolExtensionsTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.FindSymbols diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.AccessorSymbols.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.AccessorSymbols.vb index 2a0c51cbeafa0..23a8a4aef2b83 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.AccessorSymbols.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.AccessorSymbols.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.AnonymousTypeSymbols.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.AnonymousTypeSymbols.vb index cd189d520a5f1..d06a415f8299b 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.AnonymousTypeSymbols.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.AnonymousTypeSymbols.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.AsyncSymbols.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.AsyncSymbols.vb index e5f687f95fec0..1945a6a11ecdf 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.AsyncSymbols.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.AsyncSymbols.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.BuiltinOperatorSymbols.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.BuiltinOperatorSymbols.vb index c3e17b25cc20e..7a2949ac841d0 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.BuiltinOperatorSymbols.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.BuiltinOperatorSymbols.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DelegateInvokeMethodSymbols.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DelegateInvokeMethodSymbols.vb index a6dc0603b4b62..4a56248ccf73c 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DelegateInvokeMethodSymbols.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DelegateInvokeMethodSymbols.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicAssemblies.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicAssemblies.vb index 5e2fd4ccd037b..af224d4d38d85 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicAssemblies.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicAssemblies.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicBinding.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicBinding.vb index cd9132e160cb0..018d8ca4cf450 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicBinding.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicBinding.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicConstructors.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicConstructors.vb index 90b2d72b7add8..d394e22aa8a0e 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicConstructors.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicConstructors.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicDelegatesAndIndexers.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicDelegatesAndIndexers.vb index c111349bfb1b8..869ac29fe112b 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicDelegatesAndIndexers.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicDelegatesAndIndexers.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicFunctions.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicFunctions.vb index cb68c6bc68ef8..9124c83b54aa9 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicFunctions.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicFunctions.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicIdentifiers.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicIdentifiers.vb index 35177011d5e1d..67c19c153bf10 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicIdentifiers.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicIdentifiers.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicPartialClass.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicPartialClass.vb index 64ac738934c1a..8f9b3ca90f2b4 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicPartialClass.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicPartialClass.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicTypeSymbol.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicTypeSymbol.vb index b8a63ca91175a..03afdd472f210 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicTypeSymbol.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicTypeSymbol.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.EventSymbols.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.EventSymbols.vb index ded1fcc943905..0909163f2bd48 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.EventSymbols.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.EventSymbols.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.ExplicitInterfaceMethodSymbols.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.ExplicitInterfaceMethodSymbols.vb index e95742fc33a96..3007d6aa24146 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.ExplicitInterfaceMethodSymbols.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.ExplicitInterfaceMethodSymbols.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.FieldSymbols.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.FieldSymbols.vb index 77d7caf0997da..47098764821ec 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.FieldSymbols.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.FieldSymbols.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.IndexerSymbols.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.IndexerSymbols.vb index 1e3b74b43cce6..dbd48d215701c 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.IndexerSymbols.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.IndexerSymbols.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.InternalsVisibleTo.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.InternalsVisibleTo.vb index 6107bc0234882..00cd2cd163f37 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.InternalsVisibleTo.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.InternalsVisibleTo.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.LabelSymbols.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.LabelSymbols.vb index 2368e00c50020..0a64fee17eb44 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.LabelSymbols.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.LabelSymbols.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.LambdaSymbols.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.LambdaSymbols.vb index 7d64bf337a1c9..fff723c85b6e1 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.LambdaSymbols.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.LambdaSymbols.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.LinkedFiles.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.LinkedFiles.vb index ad14f69efdcab..ea3849b92cac7 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.LinkedFiles.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.LinkedFiles.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.FindSymbols Imports Microsoft.CodeAnalysis.Remote.Testing diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.Literals.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.Literals.vb index fa83a7a548e9a..e516b2e02d40b 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.Literals.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.Literals.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.LocalFunctions.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.LocalFunctions.vb index 40791d1712e6d..5cb452a8b1031 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.LocalFunctions.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.LocalFunctions.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.MethodTypeParameterTypeSymbol.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.MethodTypeParameterTypeSymbol.vb index e1f9424f76949..3caecae97cbe7 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.MethodTypeParameterTypeSymbol.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.MethodTypeParameterTypeSymbol.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.NamedTypeSymbols.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.NamedTypeSymbols.vb index 84ea352ffbfbc..97c02854545a2 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.NamedTypeSymbols.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.NamedTypeSymbols.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences @@ -255,6 +254,66 @@ class var { } Await TestAPIAndFeature(input, kind, host) End Function + + + Public Async Function TestNamedType_TypeOfOperator_Name(kind As TestKind, host As TestHost) As Task + Dim input = + + + + class {|Definition:Celsius|} + { + public {|Definition:Celsius|}() + { + System.Type t = typeof({|ValueUsageInfo.Name:[|$$Celsius|]|}); + } + } + + + + Await TestAPIAndFeature(input, kind, host) + End Function + + + + Public Async Function TestNamedType_SizeOfOperator_Name(kind As TestKind, host As TestHost) As Task + Dim input = + + + + class {|Definition:Celsius|} + { + public {|Definition:Celsius|}() + { + int t = sizeof({|ValueUsageInfo.Name:[|$$Celsius|]|}); + } + } + + + + Await TestAPIAndFeature(input, kind, host) + End Function + + + + Public Async Function TestNamedType_NameOfOperator_Name(kind As TestKind, host As TestHost) As Task + Dim input = + + + + class {|Definition:Celsius|} + { + public {|Definition:Celsius|}() + { + string t = nameof({|ValueUsageInfo.Name:[|$$Celsius|]|}); + } + } + + + + Await TestAPIAndFeature(input, kind, host) + End Function + Public Async Function TestNamedType_InaccessibleType(kind As TestKind, host As TestHost) As Task diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.NamespaceSymbols.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.NamespaceSymbols.vb index dc11e758c31af..bd725cc2f8c51 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.NamespaceSymbols.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.NamespaceSymbols.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.OperatorSymbols.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.OperatorSymbols.vb index f7956351b2d8f..3e694ecf00df4 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.OperatorSymbols.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.OperatorSymbols.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.OrdinaryMethodSymbols.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.OrdinaryMethodSymbols.vb index 3441b85505e33..1ccbf3cd6f6e6 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.OrdinaryMethodSymbols.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.OrdinaryMethodSymbols.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Runtime.CompilerServices -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.PreprocessingSymbols.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.PreprocessingSymbols.vb index 60f7e7b246fb0..fb264fe2094cc 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.PreprocessingSymbols.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.PreprocessingSymbols.vb @@ -3,7 +3,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.PropertySymbols.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.PropertySymbols.vb index 0a9a3db21b813..3b36b2f15d37b 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.PropertySymbols.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.PropertySymbols.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.Tuples.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.Tuples.vb index 0aa066f41665c..a4f8bc9c78327 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.Tuples.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.Tuples.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.XmlDocSymbols.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.XmlDocSymbols.vb index aa13c06240da9..d6f939296683b 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.XmlDocSymbols.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.XmlDocSymbols.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences diff --git a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.vb b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.vb index 24fc3401ac82a..7e399b64ddb94 100644 --- a/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.vb +++ b/src/EditorFeatures/Test2/FindReferences/FindReferencesTests.vb @@ -6,6 +6,7 @@ Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Classification +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.CSharp.Syntax Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.FindSymbols diff --git a/src/EditorFeatures/Test2/GoToDefinition/GoToDefinitionCommandHandlerTests.vb b/src/EditorFeatures/Test2/GoToDefinition/GoToDefinitionCommandHandlerTests.vb index cdeca6bf967c3..fb8a79e479bbd 100644 --- a/src/EditorFeatures/Test2/GoToDefinition/GoToDefinitionCommandHandlerTests.vb +++ b/src/EditorFeatures/Test2/GoToDefinition/GoToDefinitionCommandHandlerTests.vb @@ -8,12 +8,9 @@ Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities.GoToHelpers Imports Microsoft.CodeAnalysis.GoToDefinition Imports Microsoft.CodeAnalysis.Navigation -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands -Imports Microsoft.VisualStudio.Utilities -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.Editor.UnitTests.GoToDefinition diff --git a/src/EditorFeatures/Test2/GoToDefinition/GoToDefinitionTestsBase.vb b/src/EditorFeatures/Test2/GoToDefinition/GoToDefinitionTestsBase.vb index ae2fc2c0e3982..b664a567a618f 100644 --- a/src/EditorFeatures/Test2/GoToDefinition/GoToDefinitionTestsBase.vb +++ b/src/EditorFeatures/Test2/GoToDefinition/GoToDefinitionTestsBase.vb @@ -3,6 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.CSharp.Navigation Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities.GoToHelpers diff --git a/src/EditorFeatures/Test2/GoToHelpers/GoToHelpers.vb b/src/EditorFeatures/Test2/GoToHelpers/GoToHelpers.vb index 9e35a2e110b5f..69a688494c7d9 100644 --- a/src/EditorFeatures/Test2/GoToHelpers/GoToHelpers.vb +++ b/src/EditorFeatures/Test2/GoToHelpers/GoToHelpers.vb @@ -2,10 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities.GoToHelpers -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.FindUsages Imports Microsoft.CodeAnalysis.Remote.Testing @@ -22,7 +22,7 @@ Friend Class GoToHelpers Dim position = documentWithCursor.CursorPosition.Value Dim solution = workspace.CurrentSolution - Dim document = Await solution.GetRequiredDocumentAsync(documentWithCursor.Id, includeSourceGenerated:=True) + Dim document = Await solution.GetRequiredDocumentAsync(documentWithCursor.Id, includeSourceGenerated:=True, CancellationToken.None) Dim context = New SimpleFindUsagesContext() Await testingMethod(document, position, context) diff --git a/src/EditorFeatures/Test2/GoToImplementation/GoToImplementationTests.vb b/src/EditorFeatures/Test2/GoToImplementation/GoToImplementationTests.vb index 3bf22eadb66cb..3564e8869bf67 100644 --- a/src/EditorFeatures/Test2/GoToImplementation/GoToImplementationTests.vb +++ b/src/EditorFeatures/Test2/GoToImplementation/GoToImplementationTests.vb @@ -2,10 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Remote.Testing -Imports Microsoft.CodeAnalysis.FindUsages Imports System.Threading Imports Microsoft.CodeAnalysis.Classification +Imports Microsoft.CodeAnalysis.FindUsages +Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.GoToImplementation <[UseExportProvider]> diff --git a/src/EditorFeatures/Test2/IntelliSense/AbstractIntellisenseQuickInfoBuilderTests.vb b/src/EditorFeatures/Test2/IntelliSense/AbstractIntellisenseQuickInfoBuilderTests.vb index ec50f62aa6c6a..adeeffbad288c 100644 --- a/src/EditorFeatures/Test2/IntelliSense/AbstractIntellisenseQuickInfoBuilderTests.vb +++ b/src/EditorFeatures/Test2/IntelliSense/AbstractIntellisenseQuickInfoBuilderTests.vb @@ -15,7 +15,6 @@ Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Utilities Imports Moq - Imports VSQuickInfoItem = Microsoft.VisualStudio.Language.Intellisense.QuickInfoItem Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense diff --git a/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests.vb b/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests.vb index 54508a0063daf..5a12ebcc98c89 100644 --- a/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests.vb +++ b/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests.vb @@ -7,6 +7,7 @@ Imports System.Composition Imports System.Globalization Imports System.Threading Imports Microsoft.CodeAnalysis.Classification +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.CSharp diff --git a/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests_DeclarationName.vb b/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests_DeclarationName.vb index 58843079b534d..13105570454a4 100644 --- a/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests_DeclarationName.vb +++ b/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests_DeclarationName.vb @@ -2,28 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.Immutable -Imports System.Composition -Imports System.Globalization -Imports System.Threading -Imports Microsoft.CodeAnalysis.Completion -Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.CSharp -Imports Microsoft.CodeAnalysis.CSharp.Formatting -Imports Microsoft.CodeAnalysis.CSharp.[Shared].Extensions -Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion -Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions -Imports Microsoft.CodeAnalysis.Host.Mef -Imports Microsoft.CodeAnalysis.Options -Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.Tags -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion -Imports Microsoft.VisualStudio.Text -Imports Microsoft.VisualStudio.Text.Editor -Imports Microsoft.VisualStudio.Text.Operations -Imports Microsoft.VisualStudio.Text.Projection Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense <[UseExportProvider]> diff --git a/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests_DefaultsSource.vb b/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests_DefaultsSource.vb index c32cf16fb0494..8e8a47b770c4c 100644 --- a/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests_DefaultsSource.vb +++ b/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests_DefaultsSource.vb @@ -5,6 +5,7 @@ Imports System.Collections.Immutable Imports System.Composition Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.CSharp.Completion diff --git a/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests_HandleNonRoslynCompletionSources.vb b/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests_HandleNonRoslynCompletionSources.vb index 704fb20af3392..125cf5492c7eb 100644 --- a/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests_HandleNonRoslynCompletionSources.vb +++ b/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests_HandleNonRoslynCompletionSources.vb @@ -4,6 +4,7 @@ Imports System.Collections.Immutable Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text diff --git a/src/EditorFeatures/Test2/IntelliSense/CompletionRulesTests.vb b/src/EditorFeatures/Test2/IntelliSense/CompletionRulesTests.vb index d68daca51b92b..ea8fc3b264b96 100644 --- a/src/EditorFeatures/Test2/IntelliSense/CompletionRulesTests.vb +++ b/src/EditorFeatures/Test2/IntelliSense/CompletionRulesTests.vb @@ -4,7 +4,6 @@ Imports System.Globalization Imports Microsoft.CodeAnalysis.Completion -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense diff --git a/src/EditorFeatures/Test2/IntelliSense/CompletionServiceTests_Exclusivitiy.vb b/src/EditorFeatures/Test2/IntelliSense/CompletionServiceTests_Exclusivitiy.vb index aae1c2fb4b2a2..183a26922a0cc 100644 --- a/src/EditorFeatures/Test2/IntelliSense/CompletionServiceTests_Exclusivitiy.vb +++ b/src/EditorFeatures/Test2/IntelliSense/CompletionServiceTests_Exclusivitiy.vb @@ -2,9 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.Immutable Imports System.Composition -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Host diff --git a/src/EditorFeatures/Test2/IntelliSense/MockCompletionProvider.vb b/src/EditorFeatures/Test2/IntelliSense/MockCompletionProvider.vb index 683030af08f07..2895d1a487f92 100644 --- a/src/EditorFeatures/Test2/IntelliSense/MockCompletionProvider.vb +++ b/src/EditorFeatures/Test2/IntelliSense/MockCompletionProvider.vb @@ -2,11 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Host.Mef -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense diff --git a/src/EditorFeatures/Test2/IntelliSense/SignatureHelpControllerTests.vb b/src/EditorFeatures/Test2/IntelliSense/SignatureHelpControllerTests.vb index 6314ace2ba66b..9af6ff6690eab 100644 --- a/src/EditorFeatures/Test2/IntelliSense/SignatureHelpControllerTests.vb +++ b/src/EditorFeatures/Test2/IntelliSense/SignatureHelpControllerTests.vb @@ -5,6 +5,7 @@ Imports System.Collections.Immutable Imports System.Runtime.CompilerServices Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities diff --git a/src/EditorFeatures/Test2/IntelliSense/VisualBasicCompletionCommandHandlerTests.vb b/src/EditorFeatures/Test2/IntelliSense/VisualBasicCompletionCommandHandlerTests.vb index a63e361df44df..0bd026ff10c27 100644 --- a/src/EditorFeatures/Test2/IntelliSense/VisualBasicCompletionCommandHandlerTests.vb +++ b/src/EditorFeatures/Test2/IntelliSense/VisualBasicCompletionCommandHandlerTests.vb @@ -10,7 +10,6 @@ Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Host.Mef -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Snippets Imports Microsoft.CodeAnalysis.Tags diff --git a/src/EditorFeatures/Test2/IntelliSense/VisualBasicCompletionCommandHandlerTests_AwaitCompletion.vb b/src/EditorFeatures/Test2/IntelliSense/VisualBasicCompletionCommandHandlerTests_AwaitCompletion.vb index 93c42335f48d7..77fb0dccfce60 100644 --- a/src/EditorFeatures/Test2/IntelliSense/VisualBasicCompletionCommandHandlerTests_AwaitCompletion.vb +++ b/src/EditorFeatures/Test2/IntelliSense/VisualBasicCompletionCommandHandlerTests_AwaitCompletion.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic - Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense diff --git a/src/EditorFeatures/Test2/InteractivePaste/InteractivePasteCommandHandlerTests.vb b/src/EditorFeatures/Test2/InteractivePaste/InteractivePasteCommandHandlerTests.vb index 47a05d06159c6..94e7e9b86d432 100644 --- a/src/EditorFeatures/Test2/InteractivePaste/InteractivePasteCommandHandlerTests.vb +++ b/src/EditorFeatures/Test2/InteractivePaste/InteractivePasteCommandHandlerTests.vb @@ -6,7 +6,6 @@ Imports System.Text Imports System.Windows Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Interactive Imports Microsoft.VisualStudio.InteractiveWindow Imports Microsoft.VisualStudio.Text.Editor diff --git a/src/EditorFeatures/Test2/KeywordHighlighting/AbstractKeywordHighlightingTests.vb b/src/EditorFeatures/Test2/KeywordHighlighting/AbstractKeywordHighlightingTests.vb index a07a50f9a0c24..526bf791ed4a5 100644 --- a/src/EditorFeatures/Test2/KeywordHighlighting/AbstractKeywordHighlightingTests.vb +++ b/src/EditorFeatures/Test2/KeywordHighlighting/AbstractKeywordHighlightingTests.vb @@ -11,7 +11,6 @@ Imports Microsoft.CodeAnalysis.Highlighting Imports Microsoft.CodeAnalysis.KeywordHighlighting Imports Microsoft.CodeAnalysis.Options Imports Microsoft.VisualStudio.Text -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.Editor.UnitTests.KeywordHighlighting diff --git a/src/EditorFeatures/Test2/KeywordHighlighting/CSharpKeywordHighlightingTests.vb b/src/EditorFeatures/Test2/KeywordHighlighting/CSharpKeywordHighlightingTests.vb index 8ab8c2d657ed0..1d5c5764e0295 100644 --- a/src/EditorFeatures/Test2/KeywordHighlighting/CSharpKeywordHighlightingTests.vb +++ b/src/EditorFeatures/Test2/KeywordHighlighting/CSharpKeywordHighlightingTests.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks - Namespace Microsoft.CodeAnalysis.Editor.UnitTests.KeywordHighlighting Public Class CSharpKeywordHighlightingTests diff --git a/src/EditorFeatures/Test2/LanguageServices/SyntaxFactsServiceTests.vb b/src/EditorFeatures/Test2/LanguageServices/SyntaxFactsServiceTests.vb index f152b2bca13be..df5cc982a74ef 100644 --- a/src/EditorFeatures/Test2/LanguageServices/SyntaxFactsServiceTests.vb +++ b/src/EditorFeatures/Test2/LanguageServices/SyntaxFactsServiceTests.vb @@ -4,8 +4,6 @@ Imports System.Collections.Immutable Imports System.Threading -Imports System.Threading.Tasks -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.Text diff --git a/src/EditorFeatures/Test2/NavigableSymbols/NavigableSymbolsTest.vb b/src/EditorFeatures/Test2/NavigableSymbols/NavigableSymbolsTest.vb index 8ab47c5c34f02..48a245cdab61a 100644 --- a/src/EditorFeatures/Test2/NavigableSymbols/NavigableSymbolsTest.vb +++ b/src/EditorFeatures/Test2/NavigableSymbols/NavigableSymbolsTest.vb @@ -111,7 +111,7 @@ End Class" Private Shared Function ExtractSymbol(workspace As EditorTestWorkspace, position As Integer) As Task(Of INavigableSymbol) Dim threadingContext = workspace.ExportProvider.GetExportedValue(Of IThreadingContext)() Dim listenerProvider = workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider) - Dim service = New NavigableSymbolService(workspace.ExportProvider.GetExportedValue(Of IUIThreadOperationExecutor)(), threadingContext, listenerProvider) + Dim service = New NavigableSymbolService(threadingContext, listenerProvider) Dim view = workspace.Documents.First().GetTextView() Dim buffer = workspace.Documents.First().GetTextBuffer() Dim triggerSpan = New SnapshotSpan(buffer.CurrentSnapshot, New Span(position, 0)) diff --git a/src/EditorFeatures/Test2/NavigationBar/CSharpNavigationBarTests.vb b/src/EditorFeatures/Test2/NavigationBar/CSharpNavigationBarTests.vb index 191e6d486ef2e..d3f17b607bbd7 100644 --- a/src/EditorFeatures/Test2/NavigationBar/CSharpNavigationBarTests.vb +++ b/src/EditorFeatures/Test2/NavigationBar/CSharpNavigationBarTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigationBar diff --git a/src/EditorFeatures/Test2/NavigationBar/NavigationBarControllerTests.vb b/src/EditorFeatures/Test2/NavigationBar/NavigationBarControllerTests.vb index 6014876931652..4126cdda5bc8f 100644 --- a/src/EditorFeatures/Test2/NavigationBar/NavigationBarControllerTests.vb +++ b/src/EditorFeatures/Test2/NavigationBar/NavigationBarControllerTests.vb @@ -2,6 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.Implementation.NavigationBar Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Shared.TestHooks diff --git a/src/EditorFeatures/Test2/NavigationBar/TestHelpers.vb b/src/EditorFeatures/Test2/NavigationBar/TestHelpers.vb index e59a7ceebee6b..4f4723b9b4d90 100644 --- a/src/EditorFeatures/Test2/NavigationBar/TestHelpers.vb +++ b/src/EditorFeatures/Test2/NavigationBar/TestHelpers.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Extensibility.NavigationBar @@ -14,7 +13,6 @@ Imports Microsoft.CodeAnalysis.NavigationBar Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Text -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigationBar Friend Module TestHelpers diff --git a/src/EditorFeatures/Test2/NavigationBar/VisualBasicNavigationBarTests.vb b/src/EditorFeatures/Test2/NavigationBar/VisualBasicNavigationBarTests.vb index 6421067290643..7a50e703aeb0d 100644 --- a/src/EditorFeatures/Test2/NavigationBar/VisualBasicNavigationBarTests.vb +++ b/src/EditorFeatures/Test2/NavigationBar/VisualBasicNavigationBarTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Editor.VisualBasic Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.VisualBasic diff --git a/src/EditorFeatures/Test2/PasteTracking/PasteTrackingTestState.vb b/src/EditorFeatures/Test2/PasteTracking/PasteTrackingTestState.vb index d2420c234d0a2..46c9c49fb3714 100644 --- a/src/EditorFeatures/Test2/PasteTracking/PasteTrackingTestState.vb +++ b/src/EditorFeatures/Test2/PasteTracking/PasteTrackingTestState.vb @@ -2,11 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.VisualStudio.Composition Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Imports Microsoft.VisualStudio.Text.Operations diff --git a/src/EditorFeatures/Test2/Peek/PeekTests.vb b/src/EditorFeatures/Test2/Peek/PeekTests.vb index 233b2cc93e29a..15c84f6f7a1a7 100644 --- a/src/EditorFeatures/Test2/Peek/PeekTests.vb +++ b/src/EditorFeatures/Test2/Peek/PeekTests.vb @@ -4,11 +4,9 @@ Imports System.IO Imports System.Threading -Imports Microsoft.CodeAnalysis.Editor.Host +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.Implementation.Peek -Imports Microsoft.CodeAnalysis.Editor.Peek Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.VisualStudio.Imaging.Interop Imports Microsoft.VisualStudio.Language.Intellisense Imports Microsoft.VisualStudio.Text diff --git a/src/EditorFeatures/Test2/ReferenceHighlighting/AbstractReferenceHighlightingTests.vb b/src/EditorFeatures/Test2/ReferenceHighlighting/AbstractReferenceHighlightingTests.vb index 6c9507df763a7..0db7eda216ff9 100644 --- a/src/EditorFeatures/Test2/ReferenceHighlighting/AbstractReferenceHighlightingTests.vb +++ b/src/EditorFeatures/Test2/ReferenceHighlighting/AbstractReferenceHighlightingTests.vb @@ -11,7 +11,6 @@ Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.ReferenceHighlighting Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.VisualStudio.Text -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.Editor.UnitTests.ReferenceHighlighting <[UseExportProvider]> diff --git a/src/EditorFeatures/Test2/ReferenceHighlighting/DocumentHighlightsServiceTests.vb b/src/EditorFeatures/Test2/ReferenceHighlighting/DocumentHighlightsServiceTests.vb index c4008a39c807e..e846f1f910258 100644 --- a/src/EditorFeatures/Test2/ReferenceHighlighting/DocumentHighlightsServiceTests.vb +++ b/src/EditorFeatures/Test2/ReferenceHighlighting/DocumentHighlightsServiceTests.vb @@ -5,7 +5,6 @@ Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.DocumentHighlighting -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.ReferenceHighlighting diff --git a/src/EditorFeatures/Test2/Rename/CSharp/AliasTests.vb b/src/EditorFeatures/Test2/Rename/CSharp/AliasTests.vb index 073673e56f5e0..9ce727b466882 100644 --- a/src/EditorFeatures/Test2/Rename/CSharp/AliasTests.vb +++ b/src/EditorFeatures/Test2/Rename/CSharp/AliasTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Rename.ConflictEngine -Imports Microsoft.CodeAnalysis.Remote.Testing Imports Xunit.Abstractions Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.CSharp @@ -731,5 +730,46 @@ class Program result.AssertLabeledSpansAre("resolved", "var y = (x as int?) + 1;", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub + + + + Public Sub RenameReferencingConstreuctorViaAlias(host As RenameTestHost) + Using result = RenameEngineResult.Create(_outputHelper, + + + + + + , host:=host, renameTo:="ThisIsTheNewName") + + End Using + End Sub End Class End Namespace diff --git a/src/EditorFeatures/Test2/Rename/CSharp/DeclarationConflictTests.vb b/src/EditorFeatures/Test2/Rename/CSharp/DeclarationConflictTests.vb index 9c6f30025ed61..be1fbe12caab9 100644 --- a/src/EditorFeatures/Test2/Rename/CSharp/DeclarationConflictTests.vb +++ b/src/EditorFeatures/Test2/Rename/CSharp/DeclarationConflictTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.CSharp diff --git a/src/EditorFeatures/Test2/Rename/CSharp/EscapingTests.vb b/src/EditorFeatures/Test2/Rename/CSharp/EscapingTests.vb index 6bc4a79b24498..484635e783398 100644 --- a/src/EditorFeatures/Test2/Rename/CSharp/EscapingTests.vb +++ b/src/EditorFeatures/Test2/Rename/CSharp/EscapingTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.CSharp diff --git a/src/EditorFeatures/Test2/Rename/CSharp/GenericTypeParameterTests.vb b/src/EditorFeatures/Test2/Rename/CSharp/GenericTypeParameterTests.vb index 9c2d124e76b39..76c76dfbc170a 100644 --- a/src/EditorFeatures/Test2/Rename/CSharp/GenericTypeParameterTests.vb +++ b/src/EditorFeatures/Test2/Rename/CSharp/GenericTypeParameterTests.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Remote.Testing - Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.CSharp <[UseExportProvider]> Public Class GenericTypeParameterTests diff --git a/src/EditorFeatures/Test2/Rename/CSharp/ImplicitReferenceConflictTests.vb b/src/EditorFeatures/Test2/Rename/CSharp/ImplicitReferenceConflictTests.vb index 8607db0423099..6d1a421535659 100644 --- a/src/EditorFeatures/Test2/Rename/CSharp/ImplicitReferenceConflictTests.vb +++ b/src/EditorFeatures/Test2/Rename/CSharp/ImplicitReferenceConflictTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.CSharp diff --git a/src/EditorFeatures/Test2/Rename/CSharp/InteractiveTests.vb b/src/EditorFeatures/Test2/Rename/CSharp/InteractiveTests.vb index 2f95aa72a1022..949d1bc28832e 100644 --- a/src/EditorFeatures/Test2/Rename/CSharp/InteractiveTests.vb +++ b/src/EditorFeatures/Test2/Rename/CSharp/InteractiveTests.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Remote.Testing - Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.CSharp <[UseExportProvider]> Public Class InteractiveTests diff --git a/src/EditorFeatures/Test2/Rename/CSharp/InterfaceTests.vb b/src/EditorFeatures/Test2/Rename/CSharp/InterfaceTests.vb index 2328a7a9add96..3ad569c1841db 100644 --- a/src/EditorFeatures/Test2/Rename/CSharp/InterfaceTests.vb +++ b/src/EditorFeatures/Test2/Rename/CSharp/InterfaceTests.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Remote.Testing - Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.CSharp <[UseExportProvider]> diff --git a/src/EditorFeatures/Test2/Rename/CSharp/LocalConflictTests.vb b/src/EditorFeatures/Test2/Rename/CSharp/LocalConflictTests.vb index 27eae4d46222e..c24b4488495ca 100644 --- a/src/EditorFeatures/Test2/Rename/CSharp/LocalConflictTests.vb +++ b/src/EditorFeatures/Test2/Rename/CSharp/LocalConflictTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.CSharp diff --git a/src/EditorFeatures/Test2/Rename/CSharp/OverrideTests.vb b/src/EditorFeatures/Test2/Rename/CSharp/OverrideTests.vb index 950fdb9259c8e..29306753b0371 100644 --- a/src/EditorFeatures/Test2/Rename/CSharp/OverrideTests.vb +++ b/src/EditorFeatures/Test2/Rename/CSharp/OverrideTests.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Remote.Testing - Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.CSharp <[UseExportProvider]> diff --git a/src/EditorFeatures/Test2/Rename/InlineRenameTests.vb b/src/EditorFeatures/Test2/Rename/InlineRenameTests.vb index 1b4286de6b95b..0d6e86c3b498f 100644 --- a/src/EditorFeatures/Test2/Rename/InlineRenameTests.vb +++ b/src/EditorFeatures/Test2/Rename/InlineRenameTests.vb @@ -5,16 +5,14 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.Host -Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename Imports Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.InlineRename Imports Microsoft.CodeAnalysis.IntroduceVariable Imports Microsoft.CodeAnalysis.Notification Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Rename -Imports Microsoft.CodeAnalysis.Shared.Utilities Imports Microsoft.VisualStudio.Text Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename @@ -52,7 +50,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename textBuffer.Insert(caretPosition, "Bar") - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) VerifyFileName(workspace, "BarTest1") @@ -80,7 +78,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename textBuffer.Insert(caretPosition, "renamed") - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using @@ -135,7 +133,7 @@ class [|Test1$$|] ' User could use copy & paste to enter invalid character textBuffer.Insert(selectedSpan, "<>") - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) VerifyFileName(workspace, "Test1") End Using @@ -229,7 +227,7 @@ class Deconstructable Await VerifyTagsAreCorrect(workspace) - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) VerifyFileName(workspace, "BarTest1") @@ -262,7 +260,7 @@ class Deconstructable Await VerifyTagsAreCorrect(workspace) - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) @@ -785,7 +783,7 @@ End Class textBuffer.Insert(caretPosition, "goo") - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using @@ -918,7 +916,7 @@ End Class Await VerifyTagsAreCorrect(workspace) Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) VerifyFileName(workspace, "BarTest1") End Using @@ -952,7 +950,7 @@ End Class Await VerifyTagsAreCorrect(workspace) Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) VerifyFileName(workspace, "BarTest1") End Using @@ -989,7 +987,7 @@ End Class Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace) - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) VerifyFileName(workspace, "BarTest1") @@ -1064,7 +1062,7 @@ End Class Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace) - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) VerifyFileName(workspace, "BarTest1") @@ -1103,7 +1101,7 @@ End Class textBuffer.Insert(caretPosition, "Bar") - session.Commit(previewChanges:=True) + Await session.CommitAsync(previewChanges:=True, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) Assert.True(previewService.Called) @@ -1137,7 +1135,7 @@ End Class Dim session = StartSession(workspace) session.ApplyReplacementText("BarGoo", propagateEditImmediately:=True) - session.Commit(previewChanges:=True) + Await session.CommitAsync(previewChanges:=True, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) Assert.True(previewService.Called) @@ -1147,7 +1145,7 @@ End Class previewService.ReturnsNull = False previewService.Called = False - session.Commit(previewChanges:=True) + Await session.CommitAsync(previewChanges:=True, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) Assert.True(previewService.Called) End Using @@ -1194,7 +1192,7 @@ End Class Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace) - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using End Function @@ -1239,7 +1237,7 @@ End Class Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace) - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using End Function @@ -1352,7 +1350,7 @@ class C Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace) - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using End Function @@ -1384,7 +1382,7 @@ class C Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace) - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using End Function @@ -1418,7 +1416,7 @@ class C Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace) - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using End Function @@ -1452,7 +1450,7 @@ class C Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace) - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using End Function @@ -1511,7 +1509,7 @@ End Module Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "q") - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using @@ -1541,7 +1539,7 @@ End Module textBuffer.Delete(New Span(caretPosition, 1)) textBuffer.Insert(caretPosition, "x") - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using @@ -1585,7 +1583,7 @@ End Class textBuffer.Delete(New Span(caretPosition, 1)) textBuffer.Insert(caretPosition, "x") - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using @@ -1594,7 +1592,7 @@ End Class - Public Sub VerifyVBRenameDoesNotCrashOnAsNewClause(host As RenameTestHost) + Public Async Function VerifyVBRenameDoesNotCrashOnAsNewClause(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( @@ -1628,9 +1626,9 @@ End Class ' Ensure the rename doesn't crash textBuffer.Insert(caretPosition, "e") - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) End Using - End Sub + End Function @@ -1832,7 +1830,7 @@ End Class - Public Sub VerifyFileRenamesCorrectlyWhenCaseChanges(host As RenameTestHost) + Public Async Function VerifyFileRenamesCorrectlyWhenCaseChanges(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( @@ -1853,10 +1851,12 @@ class [|$$Test1|] textBuffer.Delete(New Span(caretPosition, 1)) textBuffer.Insert(caretPosition, "t") - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) + Await VerifyTagsAreCorrect(workspace) + VerifyFileName(workspace, "test1") End Using - End Sub + End Function @@ -1885,8 +1885,7 @@ class [|$$Test1|] textBuffer.Insert(caretPosition, "Bar") textBuffer.Delete(New Span(caretPosition, "Bar".Length)) - Dim committed = session.GetTestAccessor().CommitWorker(previewChanges:=False) - Assert.False(committed) + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using @@ -1970,7 +1969,7 @@ class [|C|] textBuffer.Insert(caretPosition, "Bar") - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using @@ -2000,7 +1999,7 @@ class [|C|] textBuffer.Insert(caretPosition, "Bar") - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using @@ -2030,7 +2029,7 @@ class [|C|] textBuffer.Insert(caretPosition, "Bar") - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using @@ -2060,7 +2059,7 @@ class [|C|] textBuffer.Insert(caretPosition, "Bar") - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using @@ -2090,7 +2089,7 @@ class [|C|] textBuffer.Insert(caretPosition, "Bar") - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using @@ -2120,7 +2119,7 @@ class [|C|] textBuffer.Insert(caretPosition, "Bar") - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using @@ -2150,7 +2149,7 @@ class [|C|] textBuffer.Insert(caretPosition, "Bar") - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using @@ -2180,7 +2179,7 @@ class [|C|] textBuffer.Insert(caretPosition, "Bar") - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using @@ -2210,7 +2209,7 @@ class [|C|] textBuffer.Insert(caretPosition, "Bar") - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using @@ -2240,7 +2239,7 @@ class [|C|] textBuffer.Insert(caretPosition, "Bar") - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using @@ -2270,7 +2269,7 @@ class [|C|] textBuffer.Insert(caretPosition, "Bar") - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using @@ -2305,7 +2304,7 @@ class [|C|] textBuffer.Insert(caretPosition, "Bar") - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using @@ -2336,7 +2335,7 @@ class [|C|] session.ApplyReplacementText("Example", True) session.RefreshRenameSessionWithOptionsChanged(New SymbolRenameOptions(RenameInComments:=True)) - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using @@ -2377,7 +2376,7 @@ class [|C|] textBuffer.Insert(caretPosition, "Example") - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Await VerifyTagsAreCorrect(workspace) End Using diff --git a/src/EditorFeatures/Test2/Rename/RenameCommandHandlerTests.vb b/src/EditorFeatures/Test2/Rename/RenameCommandHandlerTests.vb index 5c028b35ac1c1..5809e46cd83bf 100644 --- a/src/EditorFeatures/Test2/Rename/RenameCommandHandlerTests.vb +++ b/src/EditorFeatures/Test2/Rename/RenameCommandHandlerTests.vb @@ -2,12 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename -Imports Microsoft.CodeAnalysis.Editor.InlineRename Imports Microsoft.CodeAnalysis.Editor.Shared.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions -Imports Microsoft.CodeAnalysis.InlineRename -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text.Shared.Extensions Imports Microsoft.VisualStudio.Commanding Imports Microsoft.VisualStudio.Text @@ -1000,9 +998,6 @@ partial class [|Program|] , host) - Dim globalOptions = workspace.GetService(Of IGlobalOptionService) - globalOptions.SetGlobalOption(InlineRenameSessionOptionsStorage.CommitRenameAsynchronously, False) - Dim view = workspace.Documents.Single().GetTextView() Dim commandHandler = CreateCommandHandler(workspace) @@ -1017,20 +1012,21 @@ partial class [|Program|] commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "B"c), Sub() editorOperations.InsertText("B"), Utilities.TestCommandExecutionContext.Create()) - ' Now save the document, which should commit Rename + ' Now save the document commandHandler.ExecuteCommand(New SaveCommandArgs(view, view.TextBuffer), Sub() Exit Sub, Utilities.TestCommandExecutionContext.Create()) Await VerifyTagsAreCorrect(workspace) - ' Rename session was indeed committed and is no longer active - Assert.Null(workspace.GetService(Of IInlineRenameService).ActiveSession) + ' Rename session was not commited and is active + ' If we were to try and async rename it could finish after the save command so the workspace would still be dirty. + Assert.NotNull(workspace.GetService(Of IInlineRenameService).ActiveSession) End Using End Function Public Sub MoveSelectedLinesUpDuringRename(host As RenameTestHost) - VerifyCommandCommitsRenameSessionAndExecutesCommand( + VerifyCommandDoesNotCommitRenameSessionAndExecuteCommand( host, Sub(commandHandler As RenameCommandHandler, view As IWpfTextView, nextHandler As Action) commandHandler.ExecuteCommand(New MoveSelectedLinesUpCommandArgs(view, view.TextBuffer), nextHandler, Utilities.TestCommandExecutionContext.Create()) @@ -1040,7 +1036,7 @@ partial class [|Program|] Public Sub MoveSelectedLinesDownDuringRename(host As RenameTestHost) - VerifyCommandCommitsRenameSessionAndExecutesCommand( + VerifyCommandDoesNotCommitRenameSessionAndExecuteCommand( host, Sub(commandHandler As RenameCommandHandler, view As IWpfTextView, nextHandler As Action) commandHandler.ExecuteCommand(New MoveSelectedLinesDownCommandArgs(view, view.TextBuffer), nextHandler, Utilities.TestCommandExecutionContext.Create()) @@ -1050,7 +1046,7 @@ partial class [|Program|] Public Sub ReorderParametersDuringRename(host As RenameTestHost) - VerifyCommandCommitsRenameSessionAndExecutesCommand( + VerifyCommandDoesNotCommitRenameSessionAndExecuteCommand( host, Sub(commandHandler As RenameCommandHandler, view As IWpfTextView, nextHandler As Action) commandHandler.ExecuteCommand(New ReorderParametersCommandArgs(view, view.TextBuffer), nextHandler, Utilities.TestCommandExecutionContext.Create()) @@ -1060,7 +1056,7 @@ partial class [|Program|] Public Sub RemoveParametersDuringRename(host As RenameTestHost) - VerifyCommandCommitsRenameSessionAndExecutesCommand( + VerifyCommandDoesNotCommitRenameSessionAndExecuteCommand( host, Sub(commandHandler As RenameCommandHandler, view As IWpfTextView, nextHandler As Action) commandHandler.ExecuteCommand(New RemoveParametersCommandArgs(view, view.TextBuffer), nextHandler, Utilities.TestCommandExecutionContext.Create()) @@ -1070,7 +1066,7 @@ partial class [|Program|] Public Sub ExtractInterfaceDuringRename(host As RenameTestHost) - VerifyCommandCommitsRenameSessionAndExecutesCommand( + VerifyCommandDoesNotCommitRenameSessionAndExecuteCommand( host, Sub(commandHandler As RenameCommandHandler, view As IWpfTextView, nextHandler As Action) commandHandler.ExecuteCommand(New ExtractInterfaceCommandArgs(view, view.TextBuffer), nextHandler, Utilities.TestCommandExecutionContext.Create()) @@ -1080,7 +1076,7 @@ partial class [|Program|] Public Sub EncapsulateFieldDuringRename(host As RenameTestHost) - VerifyCommandCommitsRenameSessionAndExecutesCommand( + VerifyCommandDoesNotCommitRenameSessionAndExecuteCommand( host, Sub(commandHandler As RenameCommandHandler, view As IWpfTextView, nextHandler As Action) commandHandler.ExecuteCommand(New EncapsulateFieldCommandArgs(view, view.TextBuffer), nextHandler, Utilities.TestCommandExecutionContext.Create()) @@ -1110,7 +1106,7 @@ partial class [|Program|] Public Sub CutDuringRename_OutsideIdentifier(host As RenameTestHost) - VerifySessionCommittedAfterCutPasteOutsideIdentifier( + VerifySessionNotCommittedAfterCutPasteOutsideIdentifier( host, Sub(commandHandler As RenameCommandHandler, view As IWpfTextView, nextHandler As Action) commandHandler.ExecuteCommand(New CutCommandArgs(view, view.TextBuffer), nextHandler, Utilities.TestCommandExecutionContext.Create()) @@ -1120,17 +1116,16 @@ partial class [|Program|] Public Sub PasteDuringRename_OutsideIdentifier(host As RenameTestHost) - VerifySessionCommittedAfterCutPasteOutsideIdentifier( + VerifySessionNotCommittedAfterCutPasteOutsideIdentifier( host, Sub(commandHandler As RenameCommandHandler, view As IWpfTextView, nextHandler As Action) commandHandler.ExecuteCommand(New PasteCommandArgs(view, view.TextBuffer), nextHandler, Utilities.TestCommandExecutionContext.Create()) End Sub) End Sub - Private Shared Sub VerifyCommandCommitsRenameSessionAndExecutesCommand( + Private Shared Sub VerifyCommandDoesNotCommitRenameSessionAndExecuteCommand( host As RenameTestHost, - executeCommand As Action(Of RenameCommandHandler, IWpfTextView, Action), - Optional commitAsynchronously As Boolean = False) + executeCommand As Action(Of RenameCommandHandler, IWpfTextView, Action)) Using workspace = CreateWorkspaceWithWaiter( @@ -1144,9 +1139,6 @@ class [|C$$|] , host) - Dim globalOptions = workspace.GetService(Of IGlobalOptionService) - globalOptions.SetGlobalOption(InlineRenameSessionOptionsStorage.CommitRenameAsynchronously, commitAsynchronously) - Dim view = workspace.Documents.Single().GetTextView() view.Caret.MoveTo(New SnapshotPoint(view.TextBuffer.CurrentSnapshot, workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value)) @@ -1166,9 +1158,9 @@ class [|C$$|] Dim commandInvokedString = "/*Command Invoked*/" executeCommand(commandHandler, view, Sub() editorOperations.InsertText(commandInvokedString)) - ' Verify rename session was committed. + ' Verify rename session was not committed because the scenarios are not supported in async rename. Assert.Null(workspace.GetService(Of IInlineRenameService).ActiveSession) - Assert.Contains("D f", view.TextBuffer.CurrentSnapshot.GetText()) + Assert.Contains("C f", view.TextBuffer.CurrentSnapshot.GetText()) ' Verify the command was routed to the editor. Assert.Contains(commandInvokedString, view.TextBuffer.CurrentSnapshot.GetText()) @@ -1207,10 +1199,9 @@ class [|C$$|] End Using End Function - Private Shared Sub VerifySessionCommittedAfterCutPasteOutsideIdentifier( + Private Shared Sub VerifySessionNotCommittedAfterCutPasteOutsideIdentifier( host As RenameTestHost, - executeCommand As Action(Of RenameCommandHandler, IWpfTextView, Action), - Optional commitAsynchronously As Boolean = False) + executeCommand As Action(Of RenameCommandHandler, IWpfTextView, Action)) Using workspace = CreateWorkspaceWithWaiter( @@ -1224,9 +1215,6 @@ class [|C$$|] , host) - Dim globalOptions = workspace.GetService(Of IGlobalOptionService) - globalOptions.SetGlobalOption(InlineRenameSessionOptionsStorage.CommitRenameAsynchronously, commitAsynchronously) - Dim view = workspace.Documents.Single().GetTextView() view.Caret.MoveTo(New SnapshotPoint(view.TextBuffer.CurrentSnapshot, workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value)) @@ -1251,9 +1239,9 @@ class [|C$$|] executeCommand(commandHandler, view, Sub() editorOperations.InsertText(commandInvokedString)) - ' Verify rename session was committed + ' If a user cuts/pastes outside the identifier then that cancels the rename operation as it is not supported in async rename. Assert.Null(workspace.GetService(Of IInlineRenameService).ActiveSession) - Assert.Contains("D f", view.TextBuffer.CurrentSnapshot.GetText()) + Assert.Contains("C f", view.TextBuffer.CurrentSnapshot.GetText()) Assert.Contains(commandInvokedString, view.TextBuffer.CurrentSnapshot.GetText()) End Using End Sub diff --git a/src/EditorFeatures/Test2/Rename/RenameEngineResult.vb b/src/EditorFeatures/Test2/Rename/RenameEngineResult.vb index 9ae5870c7b80f..203590a2e9807 100644 --- a/src/EditorFeatures/Test2/Rename/RenameEngineResult.vb +++ b/src/EditorFeatures/Test2/Rename/RenameEngineResult.vb @@ -5,7 +5,6 @@ Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Remote.Testing diff --git a/src/EditorFeatures/Test2/Rename/RenameEngineTests.CSharpConflicts.vb b/src/EditorFeatures/Test2/Rename/RenameEngineTests.CSharpConflicts.vb index 67f105053a3a1..6027b0c79dca0 100644 --- a/src/EditorFeatures/Test2/Rename/RenameEngineTests.CSharpConflicts.vb +++ b/src/EditorFeatures/Test2/Rename/RenameEngineTests.CSharpConflicts.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename diff --git a/src/EditorFeatures/Test2/Rename/RenameEngineTests.VisualBasicConflicts.vb b/src/EditorFeatures/Test2/Rename/RenameEngineTests.VisualBasicConflicts.vb index cc43200450708..0ac648e03e210 100644 --- a/src/EditorFeatures/Test2/Rename/RenameEngineTests.VisualBasicConflicts.vb +++ b/src/EditorFeatures/Test2/Rename/RenameEngineTests.VisualBasicConflicts.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename diff --git a/src/EditorFeatures/Test2/Rename/RenameEngineTests.vb b/src/EditorFeatures/Test2/Rename/RenameEngineTests.vb index 88df9f53b3fdf..425e5963d0b0b 100644 --- a/src/EditorFeatures/Test2/Rename/RenameEngineTests.vb +++ b/src/EditorFeatures/Test2/Rename/RenameEngineTests.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Options -Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename Imports Microsoft.CodeAnalysis.Rename.ConflictEngine diff --git a/src/EditorFeatures/Test2/Rename/RenameNonRenameableSymbols.vb b/src/EditorFeatures/Test2/Rename/RenameNonRenameableSymbols.vb index d00714e271950..42442f94e7abc 100644 --- a/src/EditorFeatures/Test2/Rename/RenameNonRenameableSymbols.vb +++ b/src/EditorFeatures/Test2/Rename/RenameNonRenameableSymbols.vb @@ -4,7 +4,6 @@ Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities.GoToHelpers Imports Microsoft.CodeAnalysis.Navigation -Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Imports Microsoft.VisualStudio.Text diff --git a/src/EditorFeatures/Test2/Rename/RenameTagProducerTests.vb b/src/EditorFeatures/Test2/Rename/RenameTagProducerTests.vb index 2edfc36c53190..7af1b4f847990 100644 --- a/src/EditorFeatures/Test2/Rename/RenameTagProducerTests.vb +++ b/src/EditorFeatures/Test2/Rename/RenameTagProducerTests.vb @@ -3,12 +3,10 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.ObjectModel -Imports System.Threading Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename.HighlightTags Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Rename Imports Microsoft.CodeAnalysis.Text.Shared.Extensions Imports Microsoft.VisualStudio.Text @@ -16,7 +14,6 @@ Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Imports Microsoft.VisualStudio.Text.Operations Imports Microsoft.VisualStudio.Text.Tagging -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename <[UseExportProvider]> @@ -90,7 +87,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename session.Cancel() VerifyBufferContentsInWorkspace(actualWorkspace, actualWorkspace) ElseIf sessionCommit Then - Await session.CommitAsync(previewChanges:=False) + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) VerifyBufferContentsInWorkspace(actualWorkspace, resolvedConflictWorkspace) End If End If @@ -468,7 +465,7 @@ public class Class1 VerifyBufferContentsInWorkspace(workspace, resolvedConflictWorkspace) End Using - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( @@ -1175,7 +1172,7 @@ End Class commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "f"c), Sub() editorOperations.InsertText("f"), Utilities.TestCommandExecutionContext.Create()) commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "g"c), Sub() editorOperations.InsertText("g"), Utilities.TestCommandExecutionContext.Create()) - session.Commit() + Await session.CommitAsync(previewChanges:=False, editorOperationContext:=Nothing) Dim selectionLength = view.Selection.End.Position - view.Selection.Start.Position Assert.Equal(0, selectionLength) End Using diff --git a/src/EditorFeatures/Test2/Rename/RenameTestHelpers.vb b/src/EditorFeatures/Test2/Rename/RenameTestHelpers.vb index 87e16d03f9a4e..412bb2f72de08 100644 --- a/src/EditorFeatures/Test2/Rename/RenameTestHelpers.vb +++ b/src/EditorFeatures/Test2/Rename/RenameTestHelpers.vb @@ -4,7 +4,6 @@ Imports System.IO Imports System.Threading -Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename Imports Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities diff --git a/src/EditorFeatures/Test2/Rename/VisualBasic/AliasTests.vb b/src/EditorFeatures/Test2/Rename/VisualBasic/AliasTests.vb index f2f59a7aea4ca..ca16ca2fdf8cb 100644 --- a/src/EditorFeatures/Test2/Rename/VisualBasic/AliasTests.vb +++ b/src/EditorFeatures/Test2/Rename/VisualBasic/AliasTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.VisualBasic diff --git a/src/EditorFeatures/Test2/Rename/VisualBasic/CallSiteConflictResolutionTests.vb b/src/EditorFeatures/Test2/Rename/VisualBasic/CallSiteConflictResolutionTests.vb index 3d143168af81a..7454e573d6c12 100644 --- a/src/EditorFeatures/Test2/Rename/VisualBasic/CallSiteConflictResolutionTests.vb +++ b/src/EditorFeatures/Test2/Rename/VisualBasic/CallSiteConflictResolutionTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.VisualBasic diff --git a/src/EditorFeatures/Test2/Rename/VisualBasic/DeclarationConflictTests.vb b/src/EditorFeatures/Test2/Rename/VisualBasic/DeclarationConflictTests.vb index ebd4b7a69a9cc..557783ef7aca2 100644 --- a/src/EditorFeatures/Test2/Rename/VisualBasic/DeclarationConflictTests.vb +++ b/src/EditorFeatures/Test2/Rename/VisualBasic/DeclarationConflictTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.VisualBasic diff --git a/src/EditorFeatures/Test2/Rename/VisualBasic/EscapingTests.vb b/src/EditorFeatures/Test2/Rename/VisualBasic/EscapingTests.vb index 105eca08b5cd7..16d629236c6fb 100644 --- a/src/EditorFeatures/Test2/Rename/VisualBasic/EscapingTests.vb +++ b/src/EditorFeatures/Test2/Rename/VisualBasic/EscapingTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.VisualBasic diff --git a/src/EditorFeatures/Test2/Rename/VisualBasic/ImplicitReferenceConflictTests.vb b/src/EditorFeatures/Test2/Rename/VisualBasic/ImplicitReferenceConflictTests.vb index 75865d5f50e05..6bcdb4568517c 100644 --- a/src/EditorFeatures/Test2/Rename/VisualBasic/ImplicitReferenceConflictTests.vb +++ b/src/EditorFeatures/Test2/Rename/VisualBasic/ImplicitReferenceConflictTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.VisualBasic diff --git a/src/EditorFeatures/Test2/Rename/VisualBasic/InvalidIdentifierTests.vb b/src/EditorFeatures/Test2/Rename/VisualBasic/InvalidIdentifierTests.vb index 5f3af01efaf0a..69132089f6e23 100644 --- a/src/EditorFeatures/Test2/Rename/VisualBasic/InvalidIdentifierTests.vb +++ b/src/EditorFeatures/Test2/Rename/VisualBasic/InvalidIdentifierTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.VisualBasic diff --git a/src/EditorFeatures/Test2/Rename/VisualBasic/QualificationTests.vb b/src/EditorFeatures/Test2/Rename/VisualBasic/QualificationTests.vb index 3d51197ef8bc8..946e8df865da7 100644 --- a/src/EditorFeatures/Test2/Rename/VisualBasic/QualificationTests.vb +++ b/src/EditorFeatures/Test2/Rename/VisualBasic/QualificationTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.VisualBasic diff --git a/src/EditorFeatures/Test2/Simplification/AbstractSimplificationTests.vb b/src/EditorFeatures/Test2/Simplification/AbstractSimplificationTests.vb index 5b1eb5edb3dcc..829c9da6851e5 100644 --- a/src/EditorFeatures/Test2/Simplification/AbstractSimplificationTests.vb +++ b/src/EditorFeatures/Test2/Simplification/AbstractSimplificationTests.vb @@ -7,8 +7,6 @@ Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CSharp Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.Text Imports Roslyn.Utilities diff --git a/src/EditorFeatures/Test2/Simplification/BlockSimplificationTests.vb b/src/EditorFeatures/Test2/Simplification/BlockSimplificationTests.vb index 957e2eb07f148..01a088d31205f 100644 --- a/src/EditorFeatures/Test2/Simplification/BlockSimplificationTests.vb +++ b/src/EditorFeatures/Test2/Simplification/BlockSimplificationTests.vb @@ -5,7 +5,6 @@ Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.CSharp.CodeStyle Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions -Imports Microsoft.CodeAnalysis.Options Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification diff --git a/src/EditorFeatures/Test2/Simplification/EscapingSimplifierTest.vb b/src/EditorFeatures/Test2/Simplification/EscapingSimplifierTest.vb index e6691d1567269..ec31cce226ac7 100644 --- a/src/EditorFeatures/Test2/Simplification/EscapingSimplifierTest.vb +++ b/src/EditorFeatures/Test2/Simplification/EscapingSimplifierTest.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks - Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification Public Class EscapingSimplifierTest diff --git a/src/EditorFeatures/Test2/Simplification/ExtensionMethodSimplificationTests.vb b/src/EditorFeatures/Test2/Simplification/ExtensionMethodSimplificationTests.vb index 3c8a2111a7a1c..f7c3fd812872f 100644 --- a/src/EditorFeatures/Test2/Simplification/ExtensionMethodSimplificationTests.vb +++ b/src/EditorFeatures/Test2/Simplification/ExtensionMethodSimplificationTests.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks - Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification Public Class ExtensionMethodSimplificationTests diff --git a/src/EditorFeatures/Test2/Simplification/InitializerSimplificationTests.vb b/src/EditorFeatures/Test2/Simplification/InitializerSimplificationTests.vb index ccc37352b60f6..38dd630d15485 100644 --- a/src/EditorFeatures/Test2/Simplification/InitializerSimplificationTests.vb +++ b/src/EditorFeatures/Test2/Simplification/InitializerSimplificationTests.vb @@ -2,9 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Simplification -Imports Microsoft.CodeAnalysis.Text - Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification Public Class InitializerSimplificationTests diff --git a/src/EditorFeatures/Test2/Simplification/ModuleNameSimplificationTests.vb b/src/EditorFeatures/Test2/Simplification/ModuleNameSimplificationTests.vb index 636ad1b9eba6e..0762c2db6f71c 100644 --- a/src/EditorFeatures/Test2/Simplification/ModuleNameSimplificationTests.vb +++ b/src/EditorFeatures/Test2/Simplification/ModuleNameSimplificationTests.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks - Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification Public Class ModuleNameSimplifierTest diff --git a/src/EditorFeatures/Test2/Simplification/NullableAnnotationSimplificationTests.vb b/src/EditorFeatures/Test2/Simplification/NullableAnnotationSimplificationTests.vb index 10357a19397f1..c3ab232b8c7f2 100644 --- a/src/EditorFeatures/Test2/Simplification/NullableAnnotationSimplificationTests.vb +++ b/src/EditorFeatures/Test2/Simplification/NullableAnnotationSimplificationTests.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks - Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification Public Class NullableAnnotationSimplificationTests diff --git a/src/EditorFeatures/Test2/Simplification/ParenthesisSimplificationTests.vb b/src/EditorFeatures/Test2/Simplification/ParenthesisSimplificationTests.vb index fdcdfaa5a38a8..72fb113aa0646 100644 --- a/src/EditorFeatures/Test2/Simplification/ParenthesisSimplificationTests.vb +++ b/src/EditorFeatures/Test2/Simplification/ParenthesisSimplificationTests.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks - Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification Public Class ParenthesisSimplificationTests diff --git a/src/EditorFeatures/Test2/Simplification/TypeInferenceSimplifierTests.vb b/src/EditorFeatures/Test2/Simplification/TypeInferenceSimplifierTests.vb index 40d13a777cd0b..faa0bc42e6958 100644 --- a/src/EditorFeatures/Test2/Simplification/TypeInferenceSimplifierTests.vb +++ b/src/EditorFeatures/Test2/Simplification/TypeInferenceSimplifierTests.vb @@ -2,10 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks -Imports Microsoft.CodeAnalysis.Options -Imports Microsoft.CodeAnalysis.Simplification - Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification Public Class TypeInferenceSimplifierTests diff --git a/src/EditorFeatures/Test2/Simplification/TypeNameSimplifierTest.vb b/src/EditorFeatures/Test2/Simplification/TypeNameSimplifierTest.vb index 8cd7c31c36ceb..e36f71ed4b87a 100644 --- a/src/EditorFeatures/Test2/Simplification/TypeNameSimplifierTest.vb +++ b/src/EditorFeatures/Test2/Simplification/TypeNameSimplifierTest.vb @@ -5,8 +5,6 @@ Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.CSharp.CodeStyle Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/EditorFeatures/Test2/UnitTesting/UnitTestingSearchHelpersTests.vb b/src/EditorFeatures/Test2/UnitTesting/UnitTestingSearchHelpersTests.vb index c621b27d32d90..67f2c49a12b68 100644 --- a/src/EditorFeatures/Test2/UnitTesting/UnitTestingSearchHelpersTests.vb +++ b/src/EditorFeatures/Test2/UnitTesting/UnitTestingSearchHelpersTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api Imports Microsoft.CodeAnalysis.Remote.Testing diff --git a/src/EditorFeatures/Test2/UnitTesting/UnitTestingSearchHelpersTests_CSharp.vb b/src/EditorFeatures/Test2/UnitTesting/UnitTestingSearchHelpersTests_CSharp.vb index 270853fd6b6e8..c7f573e39c815 100644 --- a/src/EditorFeatures/Test2/UnitTesting/UnitTestingSearchHelpersTests_CSharp.vb +++ b/src/EditorFeatures/Test2/UnitTesting/UnitTestingSearchHelpersTests_CSharp.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api Imports Microsoft.CodeAnalysis.Remote.Testing diff --git a/src/EditorFeatures/Test2/UnitTesting/UnitTestingSearchHelpersTests_VisualBasic.vb b/src/EditorFeatures/Test2/UnitTesting/UnitTestingSearchHelpersTests_VisualBasic.vb index d0c08939d3183..e9f7b4e79a802 100644 --- a/src/EditorFeatures/Test2/UnitTesting/UnitTestingSearchHelpersTests_VisualBasic.vb +++ b/src/EditorFeatures/Test2/UnitTesting/UnitTestingSearchHelpersTests_VisualBasic.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api Imports Microsoft.CodeAnalysis.Remote.Testing diff --git a/src/EditorFeatures/Test2/Workspaces/SymbolDescriptionServiceTests.vb b/src/EditorFeatures/Test2/Workspaces/SymbolDescriptionServiceTests.vb index d3a06bef056a3..b1cf7a4bd2e86 100644 --- a/src/EditorFeatures/Test2/Workspaces/SymbolDescriptionServiceTests.vb +++ b/src/EditorFeatures/Test2/Workspaces/SymbolDescriptionServiceTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.FindSymbols Imports Microsoft.CodeAnalysis.Host diff --git a/src/EditorFeatures/Test2/Workspaces/TryFindSourceDefinitionTests.vb b/src/EditorFeatures/Test2/Workspaces/TryFindSourceDefinitionTests.vb index 72312db0677d6..ec15295848f1c 100644 --- a/src/EditorFeatures/Test2/Workspaces/TryFindSourceDefinitionTests.vb +++ b/src/EditorFeatures/Test2/Workspaces/TryFindSourceDefinitionTests.vb @@ -3,8 +3,8 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.FindSymbols Imports Microsoft.CodeAnalysis.Host Imports Xunit.Abstractions diff --git a/src/EditorFeatures/TestUtilities/AbstractCommandHandlerTestState.cs b/src/EditorFeatures/TestUtilities/AbstractCommandHandlerTestState.cs index 475a1b04d153f..207f9a1bbae32 100644 --- a/src/EditorFeatures/TestUtilities/AbstractCommandHandlerTestState.cs +++ b/src/EditorFeatures/TestUtilities/AbstractCommandHandlerTestState.cs @@ -18,8 +18,8 @@ using Microsoft.VisualStudio.Text.Operations; using Roslyn.Test.EditorUtilities; using Roslyn.Test.Utilities; -using Xunit; using Roslyn.Utilities; +using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests; diff --git a/src/EditorFeatures/TestUtilities/BraceHighlighting/MultiCharacterBraceHighlightingTests.cs b/src/EditorFeatures/TestUtilities/BraceHighlighting/MultiCharacterBraceHighlightingTests.cs index 8485776b9a8ed..19b3bd8f0c9e7 100644 --- a/src/EditorFeatures/TestUtilities/BraceHighlighting/MultiCharacterBraceHighlightingTests.cs +++ b/src/EditorFeatures/TestUtilities/BraceHighlighting/MultiCharacterBraceHighlightingTests.cs @@ -89,149 +89,107 @@ private sealed class TestBraceMatchingService : IBraceMatchingService } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/18050")] - public async Task TestNotOnBrace() - { - await TestBraceHighlightingAsync( + public Task TestNotOnBrace() + => TestBraceHighlightingAsync( "$$ <@ @>"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/18050")] - public async Task TestOnLeftOfStartBrace() - { - await TestBraceHighlightingAsync( + public Task TestOnLeftOfStartBrace() + => TestBraceHighlightingAsync( "$$[|<@|] [|@>|]"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/18050")] - public async Task TestInsideStartBrace() - { - await TestBraceHighlightingAsync( + public Task TestInsideStartBrace() + => TestBraceHighlightingAsync( "[|<$$@|] [|@>|]"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/18050")] - public async Task TestNotOnRightOfStartBrace() - { - await TestBraceHighlightingAsync( + public Task TestNotOnRightOfStartBrace() + => TestBraceHighlightingAsync( "<@$$ @>"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/18050")] - public async Task TestNotOnLeftOfCloseBrace() - { - await TestBraceHighlightingAsync( + public Task TestNotOnLeftOfCloseBrace() + => TestBraceHighlightingAsync( "<@ $$@>"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/18050")] - public async Task TestInsideCloseBrace() - { - await TestBraceHighlightingAsync( + public Task TestInsideCloseBrace() + => TestBraceHighlightingAsync( "[|<@|] [|@$$>|]"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/18050")] - public async Task TestOnRightOfCloseBrace() - { - await TestBraceHighlightingAsync( + public Task TestOnRightOfCloseBrace() + => TestBraceHighlightingAsync( "[|<@|] [|@>$$|]"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/18050")] - public async Task TestNotAfterBrace() - { - await TestBraceHighlightingAsync( + public Task TestNotAfterBrace() + => TestBraceHighlightingAsync( "<@ @> $$"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/18050")] - public async Task TestNotOnBrace2() - { - await TestBraceHighlightingAsync( + public Task TestNotOnBrace2() + => TestBraceHighlightingAsync( "$$ <@ @><@ @>"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/18050")] - public async Task TestOnLeftOfStartBrace2() - { - await TestBraceHighlightingAsync( + public Task TestOnLeftOfStartBrace2() + => TestBraceHighlightingAsync( "$$[|<@|] [|@>|]<@ @>"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/18050")] - public async Task TestInsideStartBrace2() - { - await TestBraceHighlightingAsync( + public Task TestInsideStartBrace2() + => TestBraceHighlightingAsync( "[|<$$@|] [|@>|]<@ @>"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/18050")] - public async Task TestNotOnRightOfStartBrace2() - { - await TestBraceHighlightingAsync( + public Task TestNotOnRightOfStartBrace2() + => TestBraceHighlightingAsync( "<@$$ @><@ @>"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/18050")] - public async Task TestNotOnLeftOfCloseBrace2() - { - await TestBraceHighlightingAsync( + public Task TestNotOnLeftOfCloseBrace2() + => TestBraceHighlightingAsync( "<@ $$@><@ @>"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/18050")] - public async Task TestInsideCloseBrace3() - { - await TestBraceHighlightingAsync( + public Task TestInsideCloseBrace3() + => TestBraceHighlightingAsync( "[|<@|] [|@$$>|]<@ @>"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/18050")] - public async Task TestOnRightOfCloseBrace2() - { - await TestBraceHighlightingAsync( + public Task TestOnRightOfCloseBrace2() + => TestBraceHighlightingAsync( "[|<@|] [|@>|]$$[|<@|] [|@>|]"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/18050")] - public async Task TestInSecondBracePair() - { - await TestBraceHighlightingAsync( + public Task TestInSecondBracePair() + => TestBraceHighlightingAsync( "<@ @>[|<$$@|] [|@>|]"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/18050")] - public async Task TestNotAfterSecondBracePairStart() - { - await TestBraceHighlightingAsync( + public Task TestNotAfterSecondBracePairStart() + => TestBraceHighlightingAsync( "<@ @><@$$ @>"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/18050")] - public async Task TestNotBeforeSecondBracePairEnd() - { - await TestBraceHighlightingAsync( + public Task TestNotBeforeSecondBracePairEnd() + => TestBraceHighlightingAsync( "<@ @><@ $$@>"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/18050")] - public async Task TestInSecondBracePairEnd() - { - await TestBraceHighlightingAsync( + public Task TestInSecondBracePairEnd() + => TestBraceHighlightingAsync( "<@ @>[|<@|] [|@$$>|]"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/18050")] - public async Task TestAtSecondBracePairEnd() - { - await TestBraceHighlightingAsync( + public Task TestAtSecondBracePairEnd() + => TestBraceHighlightingAsync( "<@ @>[|<@|] [|@>|]$$"); - } [WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/18050")] - public async Task TestNotAfterSecondBracePairEnd() - { - await TestBraceHighlightingAsync( + public Task TestNotAfterSecondBracePairEnd() + => TestBraceHighlightingAsync( "<@ @><@ @> $$"); - } } diff --git a/src/EditorFeatures/TestUtilities/Classification/AbstractClassifierTests.cs b/src/EditorFeatures/TestUtilities/Classification/AbstractClassifierTests.cs index 8ac203e758158..fd839ec054db2 100644 --- a/src/EditorFeatures/TestUtilities/Classification/AbstractClassifierTests.cs +++ b/src/EditorFeatures/TestUtilities/Classification/AbstractClassifierTests.cs @@ -10,6 +10,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; @@ -81,40 +82,32 @@ private async Task TestAsync( } } - protected async Task TestAsync( + protected Task TestAsync( string code, TestHost testHost, ParseOptions[] parseOptionsSet, params FormattedClassification[] expected) - { - await TestAsync(code, code, testHost, parseOptionsSet, expected); - } + => TestAsync(code, code, testHost, parseOptionsSet, expected); - protected async Task TestAsync( + protected Task TestAsync( string code, TestHost testHost, params FormattedClassification[] expected) - { - await DefaultTestAsync(code, code, testHost, expected); - } + => DefaultTestAsync(code, code, testHost, expected); - protected async Task TestAsync( + protected Task TestAsync( string code, TestHost testHost, ParseOptions? parseOptions, params FormattedClassification[] expected) - { - await TestAsync(code, code, testHost, parseOptions, expected); - } + => TestAsync(code, code, testHost, parseOptions, expected); - protected async Task TestAsync( + protected Task TestAsync( string code, string allCode, TestHost testHost, params FormattedClassification[] expected) - { - await DefaultTestAsync(code, allCode, testHost, expected); - } + => DefaultTestAsync(code, allCode, testHost, expected); protected async Task TestInClassAsync( string className, diff --git a/src/EditorFeatures/TestUtilities/Completion/AbstractCompletionProviderTests.cs b/src/EditorFeatures/TestUtilities/Completion/AbstractCompletionProviderTests.cs index bfc3492feea70..f676d202b0bcb 100644 --- a/src/EditorFeatures/TestUtilities/Completion/AbstractCompletionProviderTests.cs +++ b/src/EditorFeatures/TestUtilities/Completion/AbstractCompletionProviderTests.cs @@ -427,69 +427,59 @@ protected bool CompareItems(string actualItem, string expectedItem) protected virtual IEqualityComparer GetStringComparer() => StringComparer.Ordinal; - private protected async Task VerifyItemExistsAsync( + private protected Task VerifyItemExistsAsync( string markup, string expectedItem, string expectedDescriptionOrNull = null, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false, char? deletedCharTrigger = null, Glyph? glyph = null, int? matchPriority = null, bool? hasSuggestionModeItem = null, string displayTextSuffix = null, string displayTextPrefix = null, string inlineDescription = null, bool? isComplexTextEdit = null, List matchingFilters = null, CompletionItemFlags? flags = null, CompletionOptions options = null, bool skipSpeculation = false) - { - await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, + => VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, deletedCharTrigger, checkForAbsence: false, glyph: glyph, matchPriority: matchPriority, hasSuggestionModeItem: hasSuggestionModeItem, displayTextSuffix: displayTextSuffix, displayTextPrefix: displayTextPrefix, inlineDescription: inlineDescription, isComplexTextEdit: isComplexTextEdit, matchingFilters: matchingFilters, flags: flags, options, skipSpeculation: skipSpeculation); - } - private protected async Task VerifyItemIsAbsentAsync( + private protected Task VerifyItemIsAbsentAsync( string markup, string expectedItem, string expectedDescriptionOrNull = null, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false, char? deletedCharTrigger = null, bool? hasSuggestionModeItem = null, string displayTextSuffix = null, string displayTextPrefix = null, string inlineDescription = null, bool? isComplexTextEdit = null, List matchingFilters = null, CompletionItemFlags? flags = null, CompletionOptions options = null) - { - await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, sourceCodeKind, + => VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, deletedCharTrigger, checkForAbsence: true, glyph: null, matchPriority: null, hasSuggestionModeItem: hasSuggestionModeItem, displayTextSuffix: displayTextSuffix, displayTextPrefix: displayTextPrefix, inlineDescription: inlineDescription, isComplexTextEdit: isComplexTextEdit, matchingFilters: matchingFilters, flags: flags, options); - } - private protected async Task VerifyAnyItemExistsAsync( + private protected Task VerifyAnyItemExistsAsync( string markup, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false, bool? hasSuggestionModeItem = null, CompletionOptions options = null) - { - await VerifyExpectedItemsAsync( + => VerifyExpectedItemsAsync( markup, results: ItemExpectation.Any, sourceCodeKind, usePreviousCharAsTrigger: usePreviousCharAsTrigger, hasSuggestionModeItem: hasSuggestionModeItem, options: options); - } - private protected async Task VerifyNoItemsExistAsync( + private protected Task VerifyNoItemsExistAsync( string markup, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false, bool? hasSuggestionModeItem = null, CompletionOptions options = null) - { - await VerifyExpectedItemsAsync( + => VerifyExpectedItemsAsync( markup, results: ItemExpectation.None, sourceCodeKind, usePreviousCharAsTrigger: usePreviousCharAsTrigger, hasSuggestionModeItem: hasSuggestionModeItem, options: options); - } - private protected async Task VerifyExpectedItemsAsync( + private protected Task VerifyExpectedItemsAsync( string markup, ItemExpectation[] results, SourceCodeKind? sourceCodeKind = null, char? deletedCharTrigger = null, bool usePreviousCharAsTrigger = false, bool? hasSuggestionModeItem = null, CompletionOptions options = null) - { - await VerifyAsync(markup, + => VerifyAsync(markup, sourceCodeKind, deletedCharTrigger: deletedCharTrigger, usePreviousCharAsTrigger, results: results, hasSuggestionModeItem: hasSuggestionModeItem, matchingFilters: null, flags: null, options); - } internal abstract Type GetCompletionProviderType(); @@ -804,15 +794,16 @@ protected static string GetMarkupWithReference(string currentFile, string refere protected static string CreateMarkupForProjectWithMetadataReference(string markup, string metadataReferenceCode, string sourceLanguage, string referencedLanguage) { - return string.Format(@" - - - {1} - - {3} - - -", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(metadataReferenceCode), GetLanguageVersionAttribute(referencedLanguage)); + return string.Format(""" + + + {1} + + {3} + + + + """, sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(metadataReferenceCode), GetLanguageVersionAttribute(referencedLanguage)); } protected async Task VerifyItemWithAliasedMetadataReferencesAsync(string markup, string metadataAlias, string expectedItem, int expectedSymbols, @@ -825,21 +816,24 @@ protected async Task VerifyItemWithAliasedMetadataReferencesAsync(string markup, private static string GetLanguageVersionAttribute(string languageName) { - return languageName == LanguageNames.CSharp ? @"LanguageVersion = ""preview""" : string.Empty; + return languageName == LanguageNames.CSharp ? """ + LanguageVersion = "preview" + """ : string.Empty; } protected static string CreateMarkupForProjectWithAliasedMetadataReference(string markup, string metadataAlias, string referencedCode, string sourceLanguage, string referencedLanguage, bool hasGlobalAlias = true) { var aliases = hasGlobalAlias ? $"{metadataAlias},{MetadataReferenceProperties.GlobalAlias}" : $"{metadataAlias}"; - return string.Format(@" - - - {2} - - {6} - - -", sourceLanguage, GetLanguageVersionAttribute(sourceLanguage), SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(aliases), GetLanguageVersionAttribute(referencedLanguage), SecurityElement.Escape(referencedCode)); + return string.Format(""" + + + {2} + + {6} + + + + """, sourceLanguage, GetLanguageVersionAttribute(sourceLanguage), SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(aliases), GetLanguageVersionAttribute(referencedLanguage), SecurityElement.Escape(referencedCode)); } protected async Task VerifyItemWithProjectReferenceAsync(string markup, string referencedCode, string expectedItem, int expectedSymbols, string sourceLanguage, string referencedLanguage) @@ -851,44 +845,47 @@ protected async Task VerifyItemWithProjectReferenceAsync(string markup, string r protected static string CreateMarkupForProjectWithAliasedProjectReference(string markup, string projectAlias, string referencedCode, string sourceLanguage, string referencedLanguage) { - return string.Format(@" - - - ReferencedProject - {1} - - - {3} - - -", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(referencedCode), SecurityElement.Escape(projectAlias)); + return string.Format(""" + + + ReferencedProject + {1} + + + {3} + + + + """, sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(referencedCode), SecurityElement.Escape(projectAlias)); } protected static string CreateMarkupForProjectWithProjectReference(string markup, string referencedCode, string sourceLanguage, string referencedLanguage) { - return string.Format(@" - - - ReferencedProject - {2} - - - {5} - - -", sourceLanguage, GetLanguageVersionAttribute(sourceLanguage), SecurityElement.Escape(markup), referencedLanguage, GetLanguageVersionAttribute(referencedLanguage), SecurityElement.Escape(referencedCode)); + return string.Format(""" + + + ReferencedProject + {2} + + + {5} + + + + """, sourceLanguage, GetLanguageVersionAttribute(sourceLanguage), SecurityElement.Escape(markup), referencedLanguage, GetLanguageVersionAttribute(referencedLanguage), SecurityElement.Escape(referencedCode)); } protected static string CreateMarkupForProjectWithMultupleProjectReferences(string sourceText, string sourceLanguage, string referencedLanguage, string[] referencedTexts) { - return $@" - - -{GetProjectReferenceElements(referencedTexts)} - {SecurityElement.Escape(sourceText)} - -{GetReferencedProjectElements(referencedLanguage, referencedTexts)} -"; + return $""" + + + {GetProjectReferenceElements(referencedTexts)} + {SecurityElement.Escape(sourceText)} + + {GetReferencedProjectElements(referencedLanguage, referencedTexts)} + + """; static string GetProjectReferenceElements(string[] referencedTexts) { @@ -906,10 +903,11 @@ static string GetReferencedProjectElements(string language, string[] referencedT var builder = new StringBuilder(); for (var i = 0; i < referencedTexts.Length; ++i) { - builder.Append($@" - - {SecurityElement.Escape(referencedTexts[i])} -"); + builder.Append($""" + + {SecurityElement.Escape(referencedTexts[i])} + + """); } return builder.ToString(); @@ -918,18 +916,19 @@ static string GetReferencedProjectElements(string language, string[] referencedT protected static string CreateMarkupForProjecWithVBProjectReference(string markup, string referencedCode, string sourceLanguage, string rootNamespace = "") { - return string.Format(@" - - - ReferencedProject - {1} - - - {3} - - - -", sourceLanguage, SecurityElement.Escape(markup), LanguageNames.VisualBasic, SecurityElement.Escape(referencedCode), rootNamespace); + return string.Format(""" + + + ReferencedProject + {1} + + + {3} + + + + + """, sourceLanguage, SecurityElement.Escape(markup), LanguageNames.VisualBasic, SecurityElement.Escape(referencedCode), rootNamespace); } private Task VerifyItemInSameProjectAsync(string markup, string referencedCode, string expectedItem, int expectedSymbols, string sourceLanguage) @@ -946,13 +945,14 @@ protected static string CreateMarkupForSingleProject( string sourceFileName = "SourceDocument", string referencedFileName = "ReferencedDocument") { - return string.Format(@" - - - {1} - {2} - -", sourceLanguage, SecurityElement.Escape(sourceCode), SecurityElement.Escape(referencedCode), sourceFileName, referencedFileName, GetLanguageVersionAttribute(sourceLanguage)); + return string.Format(""" + + + {1} + {2} + + + """, sourceLanguage, SecurityElement.Escape(sourceCode), SecurityElement.Escape(referencedCode), sourceFileName, referencedFileName, GetLanguageVersionAttribute(sourceLanguage)); } private async Task VerifyItemWithReferenceWorkerAsync( @@ -999,14 +999,15 @@ private async Task VerifyItemWithReferenceWorkerAsync( protected async Task VerifyItemWithMscorlib45Async(string markup, string expectedItem, string expectedDescription, string sourceLanguage) { - var xmlString = string.Format(@" - - - -{1} - - -", sourceLanguage, SecurityElement.Escape(markup)); + var xmlString = string.Format(""" + + + + {1} + + + + """, sourceLanguage, SecurityElement.Escape(markup)); await VerifyItemWithMscorlib45WorkerAsync(xmlString, expectedItem, expectedDescription); } @@ -1077,25 +1078,21 @@ await BaseVerifyWorkerAsync(code, position, usePreviousCharAsTrigger, matchingFilters, flags, options, skipSpeculation: skipSpeculation); } - private protected async Task VerifyAtPositionAsync( + private protected Task VerifyAtPositionAsync( string code, int position, bool usePreviousCharAsTrigger, char? deletedCharTrigger, bool? hasSuggestionItem, SourceCodeKind sourceCodeKind, ItemExpectation[] expectedResults, List matchingFilters, CompletionItemFlags? flags, CompletionOptions options, bool skipSpeculation = false) - { - await VerifyAtPositionAsync(code, position, string.Empty, usePreviousCharAsTrigger, + => VerifyAtPositionAsync(code, position, string.Empty, usePreviousCharAsTrigger, deletedCharTrigger, hasSuggestionItem, sourceCodeKind, expectedResults, matchingFilters, flags, options, skipSpeculation: skipSpeculation); - } - private protected async Task VerifyAtPosition_ItemPartiallyWrittenAsync( + private protected Task VerifyAtPosition_ItemPartiallyWrittenAsync( string code, int position, bool usePreviousCharAsTrigger, char? deletedCharTrigger, bool? hasSuggestionItem, SourceCodeKind sourceCodeKind, ItemExpectation[] expectedResults, string partialItem, List matchingFilters, CompletionItemFlags? flags, CompletionOptions options, bool skipSpeculation = false) - { - await VerifyAtPositionAsync(code, position, ItemPartiallyWritten(partialItem), + => VerifyAtPositionAsync(code, position, ItemPartiallyWritten(partialItem), usePreviousCharAsTrigger, deletedCharTrigger, hasSuggestionItem, sourceCodeKind, expectedResults, matchingFilters, flags, options, skipSpeculation: skipSpeculation); - } private protected async Task VerifyAtPositionAsync( string code, int position, string insertText, bool usePreviousCharAsTrigger, char? deletedCharTrigger, @@ -1115,22 +1112,20 @@ await BaseVerifyWorkerAsync(code, position, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags, options, skipSpeculation: skipSpeculation); } - private protected async Task VerifyAtPositionAsync( + private protected Task VerifyAtPositionAsync( string code, int position, bool usePreviousCharAsTrigger, char? deletedCharTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, Glyph? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List matchingFilters = null, CompletionItemFlags? flags = null, CompletionOptions options = null, bool skipSpeculation = false) - { - await VerifyAtPositionAsync( + => VerifyAtPositionAsync( code, position, string.Empty, usePreviousCharAsTrigger, deletedCharTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags, options, skipSpeculation: skipSpeculation); - } - private protected async Task VerifyAtPosition_ItemPartiallyWrittenAsync( + private protected Task VerifyAtPosition_ItemPartiallyWrittenAsync( string code, int position, bool usePreviousCharAsTrigger, char? deletedCharTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, Glyph? glyph, @@ -1138,14 +1133,12 @@ private protected async Task VerifyAtPosition_ItemPartiallyWrittenAsync( string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List matchingFilters = null, CompletionItemFlags? flags = null, CompletionOptions options = null, bool skipSpeculation = false) - { - await VerifyAtPositionAsync( + => VerifyAtPositionAsync( code, position, ItemPartiallyWritten(expectedItemOrNull), usePreviousCharAsTrigger, deletedCharTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags, options, skipSpeculation: skipSpeculation); - } private protected async Task VerifyAtEndOfFileAsync( string code, int position, string insertText, bool usePreviousCharAsTrigger, char? deletedCharTrigger, bool? hasSuggestionItem, @@ -1166,25 +1159,21 @@ await BaseVerifyWorkerAsync(code, position, matchingFilters, flags, options, skipSpeculation: skipSpeculation); } - private protected async Task VerifyAtEndOfFileAsync( + private protected Task VerifyAtEndOfFileAsync( string code, int position, bool usePreviousCharAsTrigger, char? deletedCharTrigger, bool? hasSuggestionItem, SourceCodeKind sourceCodeKind, ItemExpectation[] expectedResults, List matchingFilters, CompletionItemFlags? flags, CompletionOptions options, bool skipSpeculation = false) - { - await VerifyAtEndOfFileAsync(code, position, string.Empty, + => VerifyAtEndOfFileAsync(code, position, string.Empty, usePreviousCharAsTrigger, deletedCharTrigger, hasSuggestionItem, sourceCodeKind, expectedResults, matchingFilters, flags, options, skipSpeculation: skipSpeculation); - } - private protected async Task VerifyAtEndOfFileAsync( + private protected Task VerifyAtEndOfFileAsync( string code, int position, bool usePreviousCharAsTrigger, char? deletedCharTrigger, bool? hasSuggestionItem, SourceCodeKind sourceCodeKind, ItemExpectation[] expectedResults, List matchingFilters, CompletionItemFlags? flags, CompletionOptions options) - { - await VerifyAtEndOfFileAsync(code, position, string.Empty, + => VerifyAtEndOfFileAsync(code, position, string.Empty, usePreviousCharAsTrigger, deletedCharTrigger, hasSuggestionItem, sourceCodeKind, expectedResults, matchingFilters, flags, options); - } private protected async Task VerifyAtEndOfFileAsync( string code, int position, string insertText, bool usePreviousCharAsTrigger, char? deletedCharTrigger, @@ -1211,7 +1200,7 @@ await BaseVerifyWorkerAsync( inlineDescription, isComplexTextEdit, matchingFilters, flags, options); } - private protected async Task VerifyAtEndOfFileAsync( + private protected Task VerifyAtEndOfFileAsync( string code, int position, bool usePreviousCharAsTrigger, char? deletedCharTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, Glyph? glyph, @@ -1219,25 +1208,21 @@ private protected async Task VerifyAtEndOfFileAsync( string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List matchingFilters = null, CompletionItemFlags? flags = null, CompletionOptions options = null) - { - await VerifyAtEndOfFileAsync(code, position, string.Empty, usePreviousCharAsTrigger, deletedCharTrigger, + => VerifyAtEndOfFileAsync(code, position, string.Empty, usePreviousCharAsTrigger, deletedCharTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags, options); - } - private protected async Task VerifyAtEndOfFile_ItemPartiallyWrittenAsync( + private protected Task VerifyAtEndOfFile_ItemPartiallyWrittenAsync( string code, int position, bool usePreviousCharAsTrigger, char? deletedCharTrigger, bool? hasSuggestionItem, SourceCodeKind sourceCodeKind, ItemExpectation[] expectedResults, string partialItem, List matchingFilters, CompletionItemFlags? flags, CompletionOptions options) - { - await VerifyAtEndOfFileAsync( + => VerifyAtEndOfFileAsync( code, position, ItemPartiallyWritten(partialItem), usePreviousCharAsTrigger, deletedCharTrigger, hasSuggestionItem, sourceCodeKind, expectedResults, matchingFilters, flags, options); - } - private protected async Task VerifyAtEndOfFile_ItemPartiallyWrittenAsync( + private protected Task VerifyAtEndOfFile_ItemPartiallyWrittenAsync( string code, int position, bool usePreviousCharAsTrigger, char? deletedCharTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, Glyph? glyph, @@ -1245,13 +1230,11 @@ private protected async Task VerifyAtEndOfFile_ItemPartiallyWrittenAsync( string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List matchingFilters = null, CompletionItemFlags? flags = null, CompletionOptions options = null) - { - await VerifyAtEndOfFileAsync( + => VerifyAtEndOfFileAsync( code, position, ItemPartiallyWritten(expectedItemOrNull), usePreviousCharAsTrigger, deletedCharTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags, options); - } protected void VerifyTextualTriggerCharacter( string markup, diff --git a/src/EditorFeatures/TestUtilities/Debugging/AbstractDataTipInfoGetterTests.cs b/src/EditorFeatures/TestUtilities/Debugging/AbstractDataTipInfoGetterTests.cs index 9c966d5b4de63..133baa990b2e5 100644 --- a/src/EditorFeatures/TestUtilities/Debugging/AbstractDataTipInfoGetterTests.cs +++ b/src/EditorFeatures/TestUtilities/Debugging/AbstractDataTipInfoGetterTests.cs @@ -28,9 +28,8 @@ protected Task TestAsync(XElement markup, string? expectedText = null) protected Task TestNoDataTipAsync(XElement markup) => TestNoDataTipAsync(markup.NormalizedValue()); - protected async Task TestAsync(string markup, string? expectedText = null) - { - await TestSpanGetterAsync(markup, async (workspace, document, position, expectedSpan) => + protected Task TestAsync(string markup, string? expectedText = null) + => TestSpanGetterAsync(markup, async (workspace, document, position, expectedSpan) => { var service = document.GetRequiredLanguageService(); var result = await service.GetDataTipInfoAsync(document, position, includeKind: true, CancellationToken.None); @@ -46,16 +45,13 @@ await TestSpanGetterAsync(markup, async (workspace, document, position, expected Assert.Equal(linqExpressionSpans.Single(), result.ExpressionSpan); } }); - } - protected async Task TestNoDataTipAsync(string markup) - { - await TestSpanGetterAsync(markup, async (workspace, document, position, expectedSpan) => + protected Task TestNoDataTipAsync(string markup) + => TestSpanGetterAsync(markup, async (workspace, document, position, expectedSpan) => { var result = await DataTipInfoGetter.GetInfoAsync(document, position, includeKind: true, CancellationToken.None); Assert.True(result.IsDefault); }); - } private async Task TestSpanGetterAsync(string markup, Func continuation) { diff --git a/src/EditorFeatures/TestUtilities/Diagnostics/DiagnosticTaggerWrapper.cs b/src/EditorFeatures/TestUtilities/Diagnostics/DiagnosticTaggerWrapper.cs index 3dfd854ead0d1..6cbaf3ff839c7 100644 --- a/src/EditorFeatures/TestUtilities/Diagnostics/DiagnosticTaggerWrapper.cs +++ b/src/EditorFeatures/TestUtilities/Diagnostics/DiagnosticTaggerWrapper.cs @@ -55,7 +55,7 @@ public AbstractDiagnosticsTaggerProvider TaggerProvider { if (_taggerProvider == null) { - WpfTestRunner.RequireWpfFact($"{nameof(DiagnosticTaggerWrapper)}.{nameof(TaggerProvider)} creates asynchronous taggers"); + WpfTestRunner.RequireWpfFact($"{nameof(DiagnosticTaggerWrapper<,>)}.{nameof(TaggerProvider)} creates asynchronous taggers"); if (typeof(TProvider) == typeof(InlineDiagnosticsTaggerProvider)) { @@ -73,14 +73,12 @@ public AbstractDiagnosticsTaggerProvider TaggerProvider } } - public async Task WaitForTags() - { - await _listenerProvider.WaitAllDispatcherOperationAndTasksAsync( + public Task WaitForTags() + => _listenerProvider.WaitAllDispatcherOperationAndTasksAsync( _workspace, FeatureAttribute.Workspace, FeatureAttribute.SolutionCrawlerLegacy, FeatureAttribute.DiagnosticService, FeatureAttribute.ErrorSquiggles, FeatureAttribute.Classification); - } } diff --git a/src/EditorFeatures/TestUtilities/DocumentTracking/FirstDocumentIsActiveAndVisibleDocumentTrackingService.cs b/src/EditorFeatures/TestUtilities/DocumentTracking/FirstDocumentIsActiveAndVisibleDocumentTrackingService.cs index fd9c71579d17a..2d80b2bf2a531 100644 --- a/src/EditorFeatures/TestUtilities/DocumentTracking/FirstDocumentIsActiveAndVisibleDocumentTrackingService.cs +++ b/src/EditorFeatures/TestUtilities/DocumentTracking/FirstDocumentIsActiveAndVisibleDocumentTrackingService.cs @@ -8,7 +8,6 @@ using System.Linq; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Test; diff --git a/src/EditorFeatures/TestUtilities/EditorTestCompositions.cs b/src/EditorFeatures/TestUtilities/EditorTestCompositions.cs index 2fdf5a8f5cc45..f000aae87914f 100644 --- a/src/EditorFeatures/TestUtilities/EditorTestCompositions.cs +++ b/src/EditorFeatures/TestUtilities/EditorTestCompositions.cs @@ -7,7 +7,6 @@ using Microsoft.CodeAnalysis.Editor.Implementation.Notification; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Test.Utilities; -using Microsoft.CodeAnalysis.Test.Utilities.Notification; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests.Fakes; using Microsoft.CodeAnalysis.UnitTests.Remote; @@ -57,7 +56,6 @@ public static class EditorTestCompositions typeof(TestObscuringTipManager)); // TODO: https://devdiv.visualstudio.com/DevDiv/_workitems?id=544569 public static readonly TestComposition EditorFeatures = FeaturesTestCompositions.Features - .AddParts(typeof(TestGlobalOperationNotificationService)) .Add(Editor) .AddAssemblies( typeof(TextEditorResources).Assembly, diff --git a/src/EditorFeatures/TestUtilities/ExtractInterface/AbstractExtractInterfaceTests.cs b/src/EditorFeatures/TestUtilities/ExtractInterface/AbstractExtractInterfaceTests.cs index c911544f93e60..4a5fc6a9e4be2 100644 --- a/src/EditorFeatures/TestUtilities/ExtractInterface/AbstractExtractInterfaceTests.cs +++ b/src/EditorFeatures/TestUtilities/ExtractInterface/AbstractExtractInterfaceTests.cs @@ -18,7 +18,7 @@ namespace Microsoft.CodeAnalysis.Editor.UnitTests.ExtractInterface; [UseExportProvider] public abstract class AbstractExtractInterfaceTests { - public static async Task TestExtractInterfaceCommandCSharpAsync( + public static Task TestExtractInterfaceCommandCSharpAsync( string markup, bool expectedSuccess, string expectedMemberName = null, @@ -28,8 +28,7 @@ public static async Task TestExtractInterfaceCommandCSharpAsync( string expectedUpdatedOriginalDocumentCode = null, string expectedInterfaceCode = null, ParseOptions parseOptions = null) - { - await TestExtractInterfaceCommandAsync( + => TestExtractInterfaceCommandAsync( markup, LanguageNames.CSharp, expectedSuccess, @@ -40,19 +39,16 @@ await TestExtractInterfaceCommandAsync( expectedUpdatedOriginalDocumentCode, expectedInterfaceCode, parseOptions: parseOptions); - } - public static async Task TestExtractInterfaceCodeActionCSharpAsync( + public static Task TestExtractInterfaceCodeActionCSharpAsync( string markup, string expectedMarkup) - { - await TestExtractInterfaceCodeActionAsync( + => TestExtractInterfaceCodeActionAsync( markup, LanguageNames.CSharp, expectedMarkup); - } - public static async Task TestExtractInterfaceCommandVisualBasicAsync( + public static Task TestExtractInterfaceCommandVisualBasicAsync( string markup, bool expectedSuccess, string expectedMemberName = null, @@ -62,8 +58,7 @@ public static async Task TestExtractInterfaceCommandVisualBasicAsync( string expectedUpdatedOriginalDocumentCode = null, string expectedInterfaceCode = null, string rootNamespace = null) - { - await TestExtractInterfaceCommandAsync( + => TestExtractInterfaceCommandAsync( markup, LanguageNames.VisualBasic, expectedSuccess, @@ -74,17 +69,14 @@ await TestExtractInterfaceCommandAsync( expectedUpdatedOriginalDocumentCode, expectedInterfaceCode, new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, rootNamespace: rootNamespace)); - } - public static async Task TestExtractInterfaceCodeActionVisualBasicAsync( + public static Task TestExtractInterfaceCodeActionVisualBasicAsync( string markup, string expectedMarkup) - { - await TestExtractInterfaceCodeActionAsync( + => TestExtractInterfaceCodeActionAsync( markup, LanguageNames.VisualBasic, expectedMarkup); - } private static async Task TestExtractInterfaceCommandAsync( string markup, diff --git a/src/EditorFeatures/TestUtilities/Formatting/CoreFormatterTestsBase.cs b/src/EditorFeatures/TestUtilities/Formatting/CoreFormatterTestsBase.cs index 1edb1867951e8..d013a59d06c75 100644 --- a/src/EditorFeatures/TestUtilities/Formatting/CoreFormatterTestsBase.cs +++ b/src/EditorFeatures/TestUtilities/Formatting/CoreFormatterTestsBase.cs @@ -31,7 +31,6 @@ using Moq; using Roslyn.Test.EditorUtilities; using Roslyn.Test.Utilities; -using Roslyn.Utilities; using Xunit; using Xunit.Abstractions; diff --git a/src/EditorFeatures/TestUtilities/GoToAdjacentMember/AbstractGoToAdjacentMemberTests.cs b/src/EditorFeatures/TestUtilities/GoToAdjacentMember/AbstractGoToAdjacentMemberTests.cs index 84e6a0396b800..427bcee85dccd 100644 --- a/src/EditorFeatures/TestUtilities/GoToAdjacentMember/AbstractGoToAdjacentMemberTests.cs +++ b/src/EditorFeatures/TestUtilities/GoToAdjacentMember/AbstractGoToAdjacentMemberTests.cs @@ -11,7 +11,6 @@ using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; -using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.GoToAdjacentMember; diff --git a/src/EditorFeatures/TestUtilities/Notification/TestGlobalOperationNotificationService.cs b/src/EditorFeatures/TestUtilities/Notification/TestGlobalOperationNotificationService.cs deleted file mode 100644 index d0b89fb4cdd71..0000000000000 --- a/src/EditorFeatures/TestUtilities/Notification/TestGlobalOperationNotificationService.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Composition; -using System.Threading; -using Microsoft.CodeAnalysis.Host.Mef; -using Microsoft.CodeAnalysis.Notification; -using Microsoft.CodeAnalysis.Shared.TestHooks; -using Microsoft.VisualStudio.Composition; - -namespace Microsoft.CodeAnalysis.Test.Utilities.Notification; - -[Export(typeof(IGlobalOperationNotificationService)), PartNotDiscoverable, Shared] -[method: ImportingConstructor] -[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] -internal sealed class TestGlobalOperationNotificationService( - IAsynchronousOperationListenerProvider listenerProvider) - : AbstractGlobalOperationNotificationService(listenerProvider, CancellationToken.None); diff --git a/src/EditorFeatures/TestUtilities/QuickInfo/ToolTipAssert.cs b/src/EditorFeatures/TestUtilities/QuickInfo/ToolTipAssert.cs index b9e4d9e0cc900..04aacf62d43cd 100644 --- a/src/EditorFeatures/TestUtilities/QuickInfo/ToolTipAssert.cs +++ b/src/EditorFeatures/TestUtilities/QuickInfo/ToolTipAssert.cs @@ -172,10 +172,14 @@ private static void ContainerToString(object element, string indent, StringBuild if (element is ClassifiedTextRun classifiedTextRun) { var classification = GetKnownClassification(classifiedTextRun.ClassificationTypeName); - result.Append($"{classification}, \"{classifiedTextRun.Text.Replace("\"", "\"\"")}\""); + result.Append($""" + {classification}, "{classifiedTextRun.Text.Replace("\"", "\"\"")}" + """); if (classifiedTextRun.NavigationAction is object || !string.IsNullOrEmpty(classifiedTextRun.Tooltip)) { - var tooltip = classifiedTextRun.Tooltip is object ? $"\"{classifiedTextRun.Tooltip.Replace("\"", "\"\"")}\"" : "Nothing"; + var tooltip = classifiedTextRun.Tooltip is object ? $""" + "{classifiedTextRun.Tooltip.Replace("\"", "\"\"")}" + """ : "Nothing"; if (classifiedTextRun.NavigationAction?.Target is QuickInfoHyperLink hyperLink) { result.Append($", QuickInfoHyperLink.TestAccessor.CreateNavigationAction(new Uri(\"{hyperLink.Uri}\", UriKind.Absolute))"); @@ -224,7 +228,9 @@ private static string GetKnownClassification(string classification) return $"{nameof(ClassificationTypeNames)}.{field.Name}"; } - return $"\"{classification}\""; + return $""" + "{classification}" + """; } private static string GetKnownImageGuid(Guid guid) diff --git a/src/EditorFeatures/TestUtilities/SignatureHelp/AbstractSignatureHelpProviderTests.cs b/src/EditorFeatures/TestUtilities/SignatureHelp/AbstractSignatureHelpProviderTests.cs index 5bf6810b8e009..9c3b93cf5bfc1 100644 --- a/src/EditorFeatures/TestUtilities/SignatureHelp/AbstractSignatureHelpProviderTests.cs +++ b/src/EditorFeatures/TestUtilities/SignatureHelp/AbstractSignatureHelpProviderTests.cs @@ -281,19 +281,20 @@ protected async Task TestSignatureHelpInEditorBrowsableContextsAsync( public Task TestSignatureHelpWithMetadataReferenceHelperAsync(string sourceCode, string referencedCode, IEnumerable expectedOrderedItems, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers) { - var xmlString = string.Format(@" - - - -{1} - - - -{3} - - - -", sourceLanguage, SecurityElement.Escape(sourceCode), + var xmlString = string.Format(""" + + + + {1} + + + + {3} + + + + + """, sourceLanguage, SecurityElement.Escape(sourceCode), referencedLanguage, SecurityElement.Escape(referencedCode)); return VerifyItemWithReferenceWorkerAsync(xmlString, expectedOrderedItems, hideAdvancedMembers); @@ -302,21 +303,22 @@ public Task TestSignatureHelpWithMetadataReferenceHelperAsync(string sourceCode, public async Task TestSignatureHelpWithProjectReferenceHelperAsync(string sourceCode, string referencedCode, IEnumerable expectedOrderedItems, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers) { - var xmlString = string.Format(@" - - - ReferencedProject - -{1} - - - - -{3} - - - -", sourceLanguage, SecurityElement.Escape(sourceCode), + var xmlString = string.Format(""" + + + ReferencedProject + + {1} + + + + + {3} + + + + + """, sourceLanguage, SecurityElement.Escape(sourceCode), referencedLanguage, SecurityElement.Escape(referencedCode)); await VerifyItemWithReferenceWorkerAsync(xmlString, expectedOrderedItems, hideAdvancedMembers); @@ -325,17 +327,18 @@ public async Task TestSignatureHelpWithProjectReferenceHelperAsync(string source private async Task TestSignatureHelpInSameProjectHelperAsync(string sourceCode, string referencedCode, IEnumerable expectedOrderedItems, string sourceLanguage, bool hideAdvancedMembers) { - var xmlString = string.Format(@" - - - -{1} - - -{2} - - -", sourceLanguage, SecurityElement.Escape(sourceCode), SecurityElement.Escape(referencedCode)); + var xmlString = string.Format(""" + + + + {1} + + + {2} + + + + """, sourceLanguage, SecurityElement.Escape(sourceCode), SecurityElement.Escape(referencedCode)); await VerifyItemWithReferenceWorkerAsync(xmlString, expectedOrderedItems, hideAdvancedMembers); } @@ -452,14 +455,15 @@ protected async Task TestSignatureHelpWithMscorlib45Async( IEnumerable expectedOrderedItems, string sourceLanguage) { - var xmlString = string.Format(@" - - - -{1} - - -", sourceLanguage, SecurityElement.Escape(markup)); + var xmlString = string.Format(""" + + + + {1} + + + + """, sourceLanguage, SecurityElement.Escape(markup)); using var testWorkspace = EditorTestWorkspace.Create(xmlString); diff --git a/src/EditorFeatures/TestUtilities/SpellCheck/AbstractSpellCheckFixerProviderTests.cs b/src/EditorFeatures/TestUtilities/SpellCheck/AbstractSpellCheckFixerProviderTests.cs index b3a5b8ece54e2..cd0766a166fee 100644 --- a/src/EditorFeatures/TestUtilities/SpellCheck/AbstractSpellCheckFixerProviderTests.cs +++ b/src/EditorFeatures/TestUtilities/SpellCheck/AbstractSpellCheckFixerProviderTests.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; diff --git a/src/EditorFeatures/TestUtilities/TextEditorFactoryExtensions.cs b/src/EditorFeatures/TestUtilities/TextEditorFactoryExtensions.cs index d479ff20ba222..66cbb7f30d668 100644 --- a/src/EditorFeatures/TestUtilities/TextEditorFactoryExtensions.cs +++ b/src/EditorFeatures/TestUtilities/TextEditorFactoryExtensions.cs @@ -4,10 +4,10 @@ #nullable disable -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Editor; using System; using System.Collections.Immutable; +using Microsoft.VisualStudio.Text; +using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.UnitTests; diff --git a/src/EditorFeatures/TestUtilities/TextStructureNavigation/AbstractTextStructureNavigationTests.cs b/src/EditorFeatures/TestUtilities/TextStructureNavigation/AbstractTextStructureNavigationTests.cs index 2781eea22cdd7..ba3bd615d3f13 100644 --- a/src/EditorFeatures/TestUtilities/TextStructureNavigation/AbstractTextStructureNavigationTests.cs +++ b/src/EditorFeatures/TestUtilities/TextStructureNavigation/AbstractTextStructureNavigationTests.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; diff --git a/src/EditorFeatures/TestUtilities/Threading/WpfTestRunner.cs b/src/EditorFeatures/TestUtilities/Threading/WpfTestRunner.cs index c35a58937b097..4fa53567819e3 100644 --- a/src/EditorFeatures/TestUtilities/Threading/WpfTestRunner.cs +++ b/src/EditorFeatures/TestUtilities/Threading/WpfTestRunner.cs @@ -29,7 +29,9 @@ namespace Roslyn.Test.Utilities; /// public sealed class WpfTestRunner : XunitTestRunner { +#pragma warning disable IDE0052 // Remove unread private members. Can be used for debugging purposes. private static string s_wpfFactRequirementReason; +#pragma warning restore IDE0052 // Remove unread private members public WpfTestSharedData SharedData { get; } diff --git a/src/EditorFeatures/TestUtilities/Threading/WpfTestSharedData.cs b/src/EditorFeatures/TestUtilities/Threading/WpfTestSharedData.cs index 920d991cfcca4..54743a3518113 100644 --- a/src/EditorFeatures/TestUtilities/Threading/WpfTestSharedData.cs +++ b/src/EditorFeatures/TestUtilities/Threading/WpfTestSharedData.cs @@ -29,19 +29,17 @@ private WpfTestSharedData() public void ExecutingTest(ITestMethod testMethod) { - var name = $"{testMethod.TestClass.Class.Name}::{testMethod.Method.Name}"; lock (_recentTestCases) { - _recentTestCases.Add(name); + _recentTestCases.Add($"{testMethod.TestClass.Class.Name}::{testMethod.Method.Name}"); } } public void ExecutingTest(MethodInfo testMethod) { - var name = $"{testMethod.DeclaringType.Name}::{testMethod.Name}"; lock (_recentTestCases) { - _recentTestCases.Add(name); + _recentTestCases.Add($"{testMethod.DeclaringType.Name}::{testMethod.Name}"); } } } diff --git a/src/EditorFeatures/TestUtilities/Workspaces/EditorTestHostDocument.cs b/src/EditorFeatures/TestUtilities/Workspaces/EditorTestHostDocument.cs index 65e8775e6edf3..ca95af6b4e6a7 100644 --- a/src/EditorFeatures/TestUtilities/Workspaces/EditorTestHostDocument.cs +++ b/src/EditorFeatures/TestUtilities/Workspaces/EditorTestHostDocument.cs @@ -38,11 +38,6 @@ public sealed class EditorTestHostDocument : TestHostDocument /// private ITextBuffer2? _textBuffer; - /// - /// The when the buffer was first created, which can be used for tracking changes to the current buffer. - /// - private ITextSnapshot? _initialTextSnapshot; - internal EditorTestHostDocument( ExportProvider exportProvider, HostLanguageServices? languageServiceProvider, @@ -77,7 +72,7 @@ internal EditorTestHostDocument( if (textBuffer != null) { _textBuffer = textBuffer; - _initialTextSnapshot = textBuffer.CurrentSnapshot; + InitialTextSnapshot = textBuffer.CurrentSnapshot; } } @@ -103,13 +98,18 @@ internal EditorTestHostDocument( } // TODO: delete this + /// + /// The when the buffer was first created, which can be used for tracking changes to the current buffer. + /// public ITextSnapshot InitialTextSnapshot { get { - Contract.ThrowIfNull(_initialTextSnapshot); - return _initialTextSnapshot; + Contract.ThrowIfNull(field); + return field; } + + private set; } public IWpfTextView GetTextView() @@ -151,7 +151,7 @@ public ITextBuffer2 GetTextBuffer() var contentType = LanguageServiceProvider.GetRequiredService().GetDefaultContentType(); _textBuffer = workspace!.GetOrCreateBufferForPath(FilePath, contentType, LanguageServiceProvider.Language, InitialText); - _initialTextSnapshot = _textBuffer.CurrentSnapshot; + InitialTextSnapshot = _textBuffer.CurrentSnapshot; } if (workspace != null) @@ -198,13 +198,6 @@ public override void Open() public SourceTextContainer GetOpenTextContainer() => this.GetTextBuffer().AsTextContainer(); - private void Update(string newText) - { - using var edit = this.GetTextBuffer().CreateEdit(EditOptions.DefaultMinimalChange, reiteratedVersionNumber: null, editTag: null); - edit.Replace(new Span(0, this.GetTextBuffer().CurrentSnapshot.Length), newText); - edit.Apply(); - } - internal void CloseTextView() { if (_textView != null && !_textView.IsClosed) diff --git a/src/EditorFeatures/TestUtilities/Workspaces/InteractiveCSharpTestWorkspaceFixture.cs b/src/EditorFeatures/TestUtilities/Workspaces/InteractiveCSharpTestWorkspaceFixture.cs index 3d15ac0636800..ad3b8137c555d 100644 --- a/src/EditorFeatures/TestUtilities/Workspaces/InteractiveCSharpTestWorkspaceFixture.cs +++ b/src/EditorFeatures/TestUtilities/Workspaces/InteractiveCSharpTestWorkspaceFixture.cs @@ -13,15 +13,14 @@ public sealed class InteractiveCSharpTestWorkspaceFixture : CSharpTestWorkspaceF { internal static EditorTestWorkspace CreateInteractiveWorkspace(string fileContent, TestComposition composition) { - var workspaceDefinition = $@" - - - - - -"; - return EditorTestWorkspace.Create(XElement.Parse(workspaceDefinition), composition: composition, workspaceKind: WorkspaceKind.Interactive); + return EditorTestWorkspace.Create(XElement.Parse($""" + + + + + + """), composition: composition, workspaceKind: WorkspaceKind.Interactive); } protected override EditorTestWorkspace CreateWorkspace(TestComposition composition = null) diff --git a/src/EditorFeatures/TestUtilities2/Intellisense/TestState.vb b/src/EditorFeatures/TestUtilities2/Intellisense/TestState.vb index 1178e00fbc7fb..14ca172867409 100644 --- a/src/EditorFeatures/TestUtilities2/Intellisense/TestState.vb +++ b/src/EditorFeatures/TestUtilities2/Intellisense/TestState.vb @@ -4,6 +4,7 @@ Imports System.Collections.Immutable Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Editor.CommandHandlers Imports Microsoft.CodeAnalysis.Editor.CSharp.CompleteStatement @@ -23,7 +24,6 @@ Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense Friend Class TestState diff --git a/src/EditorFeatures/TestUtilities2/Intellisense/TestStateFactory.vb b/src/EditorFeatures/TestUtilities2/Intellisense/TestStateFactory.vb index 5919d389d0e9a..ab106efbb1236 100644 --- a/src/EditorFeatures/TestUtilities2/Intellisense/TestStateFactory.vb +++ b/src/EditorFeatures/TestUtilities2/Intellisense/TestStateFactory.vb @@ -4,7 +4,6 @@ Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.CSharp -Imports Microsoft.CodeAnalysis.Options Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense Friend Class TestStateFactory diff --git a/src/EditorFeatures/TestUtilities2/Utilities/AssertEx.vb b/src/EditorFeatures/TestUtilities2/Utilities/AssertEx.vb index 2f03d1565c51d..b6b5a9be8febf 100644 --- a/src/EditorFeatures/TestUtilities2/Utilities/AssertEx.vb +++ b/src/EditorFeatures/TestUtilities2/Utilities/AssertEx.vb @@ -4,7 +4,6 @@ Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Public NotInheritable Class AssertEx diff --git a/src/EditorFeatures/TestUtilities2/Utilities/GoToHelpers/MockDocumentNavigationService.vb b/src/EditorFeatures/TestUtilities2/Utilities/GoToHelpers/MockDocumentNavigationService.vb index 1dd2706e31da3..e9984424d87ef 100644 --- a/src/EditorFeatures/TestUtilities2/Utilities/GoToHelpers/MockDocumentNavigationService.vb +++ b/src/EditorFeatures/TestUtilities2/Utilities/GoToHelpers/MockDocumentNavigationService.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.Navigation -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Imports Roslyn.Utilities diff --git a/src/EditorFeatures/TestUtilities2/Utilities/MockSymbolNavigationServiceProvider.vb b/src/EditorFeatures/TestUtilities2/Utilities/MockSymbolNavigationServiceProvider.vb index 50d005dfc5d5b..bcd83d6be7fc2 100644 --- a/src/EditorFeatures/TestUtilities2/Utilities/MockSymbolNavigationServiceProvider.vb +++ b/src/EditorFeatures/TestUtilities2/Utilities/MockSymbolNavigationServiceProvider.vb @@ -8,9 +8,7 @@ Imports Microsoft.CodeAnalysis.FindUsages Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Navigation -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities ' Note: by default, TestWorkspace produces a composition from all assemblies except EditorServicesTest2. diff --git a/src/EditorFeatures/VisualBasic/AutomaticCompletion/AutomaticLineEnderCommandHandler.vb b/src/EditorFeatures/VisualBasic/AutomaticCompletion/AutomaticLineEnderCommandHandler.vb index 7a6bd7e369f98..b35b4d190a8a2 100644 --- a/src/EditorFeatures/VisualBasic/AutomaticCompletion/AutomaticLineEnderCommandHandler.vb +++ b/src/EditorFeatures/VisualBasic/AutomaticCompletion/AutomaticLineEnderCommandHandler.vb @@ -13,7 +13,6 @@ Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Commanding Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion -Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Imports Microsoft.VisualStudio.Text.Operations Imports Microsoft.VisualStudio.Utilities diff --git a/src/EditorFeatures/VisualBasic/AutomaticEndConstructCorrection/AutomaticEndConstructCorrector.vb b/src/EditorFeatures/VisualBasic/AutomaticEndConstructCorrection/AutomaticEndConstructCorrector.vb index 787df1a7aac7e..332894f15a356 100644 --- a/src/EditorFeatures/VisualBasic/AutomaticEndConstructCorrection/AutomaticEndConstructCorrector.vb +++ b/src/EditorFeatures/VisualBasic/AutomaticEndConstructCorrection/AutomaticEndConstructCorrector.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading -Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.Text.Shared.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/EditorFeatures/VisualBasic/ChangeSignature/VisualBasicChangeSignatureCommandHandler.vb b/src/EditorFeatures/VisualBasic/ChangeSignature/VisualBasicChangeSignatureCommandHandler.vb index 4d3eb23909fbd..a5b353b551371 100644 --- a/src/EditorFeatures/VisualBasic/ChangeSignature/VisualBasicChangeSignatureCommandHandler.vb +++ b/src/EditorFeatures/VisualBasic/ChangeSignature/VisualBasicChangeSignatureCommandHandler.vb @@ -6,7 +6,6 @@ Imports System.ComponentModel.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.VisualStudio.Commanding Imports Microsoft.VisualStudio.Utilities diff --git a/src/EditorFeatures/VisualBasic/DocumentationComments/DocumentationCommentCommandHandler.vb b/src/EditorFeatures/VisualBasic/DocumentationComments/DocumentationCommentCommandHandler.vb index 0b05ceb21e86c..d1f4f6ce21d12 100644 --- a/src/EditorFeatures/VisualBasic/DocumentationComments/DocumentationCommentCommandHandler.vb +++ b/src/EditorFeatures/VisualBasic/DocumentationComments/DocumentationCommentCommandHandler.vb @@ -3,15 +3,13 @@ ' See the LICENSE file in the project root for more information. Imports System.ComponentModel.Composition +Imports Microsoft.CodeAnalysis.DocumentationComments Imports Microsoft.CodeAnalysis.Host.Mef -Imports Microsoft.CodeAnalysis.Editor.Host +Imports Microsoft.CodeAnalysis.Options Imports Microsoft.VisualStudio.Commanding Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion Imports Microsoft.VisualStudio.Text.Operations Imports Microsoft.VisualStudio.Utilities -Imports Microsoft.CodeAnalysis.DocumentationComments -Imports Microsoft.CodeAnalysis.Options -Imports Microsoft.VisualStudio.Text.Editor Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.DocumentationComments diff --git a/src/EditorFeatures/VisualBasic/EncapsulateField/EncapsulateFieldCommandHandler.vb b/src/EditorFeatures/VisualBasic/EncapsulateField/EncapsulateFieldCommandHandler.vb index d4b69f411287a..790d06bfe8137 100644 --- a/src/EditorFeatures/VisualBasic/EncapsulateField/EncapsulateFieldCommandHandler.vb +++ b/src/EditorFeatures/VisualBasic/EncapsulateField/EncapsulateFieldCommandHandler.vb @@ -4,14 +4,13 @@ Imports System.ComponentModel.Composition Imports System.Diagnostics.CodeAnalysis -Imports Microsoft.CodeAnalysis.EncapsulateField Imports Microsoft.CodeAnalysis.Editor Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities +Imports Microsoft.CodeAnalysis.EncapsulateField Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.VisualStudio.Commanding Imports Microsoft.VisualStudio.Text.Operations Imports Microsoft.VisualStudio.Utilities -Imports Microsoft.CodeAnalysis.Options Namespace Microsoft.CodeAnalysis.VisualBasic.EncapsulateField diff --git a/src/EditorFeatures/VisualBasic/EndConstructGeneration/ReplaceSpanResult.vb b/src/EditorFeatures/VisualBasic/EndConstructGeneration/ReplaceSpanResult.vb index da7392e50945a..c63c13a53edc5 100644 --- a/src/EditorFeatures/VisualBasic/EndConstructGeneration/ReplaceSpanResult.vb +++ b/src/EditorFeatures/VisualBasic/EndConstructGeneration/ReplaceSpanResult.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor diff --git a/src/EditorFeatures/VisualBasic/EndConstructGeneration/SpitLinesResult.vb b/src/EditorFeatures/VisualBasic/EndConstructGeneration/SpitLinesResult.vb index 547f1e94eb88f..30bd6d1ac3b30 100644 --- a/src/EditorFeatures/VisualBasic/EndConstructGeneration/SpitLinesResult.vb +++ b/src/EditorFeatures/VisualBasic/EndConstructGeneration/SpitLinesResult.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Text diff --git a/src/EditorFeatures/VisualBasic/EndConstructGeneration/VisualBasicEndConstructGenerationService.vb b/src/EditorFeatures/VisualBasic/EndConstructGeneration/VisualBasicEndConstructGenerationService.vb index 11b3e8dee49be..cec902d4febf7 100644 --- a/src/EditorFeatures/VisualBasic/EndConstructGeneration/VisualBasicEndConstructGenerationService.vb +++ b/src/EditorFeatures/VisualBasic/EndConstructGeneration/VisualBasicEndConstructGenerationService.vb @@ -6,6 +6,7 @@ Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.Implementation.EndConstructGeneration Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Host.Mef diff --git a/src/EditorFeatures/VisualBasic/ImplementAbstractClass/ImplementAbstractClassCommandHandler.vb b/src/EditorFeatures/VisualBasic/ImplementAbstractClass/ImplementAbstractClassCommandHandler.vb index 2d9b2bd791135..78dc9fee27e25 100644 --- a/src/EditorFeatures/VisualBasic/ImplementAbstractClass/ImplementAbstractClassCommandHandler.vb +++ b/src/EditorFeatures/VisualBasic/ImplementAbstractClass/ImplementAbstractClassCommandHandler.vb @@ -5,6 +5,7 @@ Imports System.ComponentModel.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities.CommandHandlers Imports Microsoft.CodeAnalysis.ImplementAbstractClass diff --git a/src/EditorFeatures/VisualBasic/ImplementInterface/ImplementInterfaceCommandHandler.vb b/src/EditorFeatures/VisualBasic/ImplementInterface/ImplementInterfaceCommandHandler.vb index 445fee3dc4f21..c647499965685 100644 --- a/src/EditorFeatures/VisualBasic/ImplementInterface/ImplementInterfaceCommandHandler.vb +++ b/src/EditorFeatures/VisualBasic/ImplementInterface/ImplementInterfaceCommandHandler.vb @@ -5,6 +5,7 @@ Imports System.ComponentModel.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities.CommandHandlers Imports Microsoft.CodeAnalysis.ImplementInterface diff --git a/src/EditorFeatures/VisualBasic/InlineRename/VisualBasicEditorInlineRenameService.vb b/src/EditorFeatures/VisualBasic/InlineRename/VisualBasicEditorInlineRenameService.vb index 1cf77bbc7ccfd..c0eb6b6c9440b 100644 --- a/src/EditorFeatures/VisualBasic/InlineRename/VisualBasicEditorInlineRenameService.vb +++ b/src/EditorFeatures/VisualBasic/InlineRename/VisualBasicEditorInlineRenameService.vb @@ -5,7 +5,6 @@ Imports System.Composition Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename Imports Microsoft.CodeAnalysis.Host.Mef -Imports Microsoft.CodeAnalysis.Options Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.InlineRename diff --git a/src/EditorFeatures/VisualBasic/LineCommit/AbstractCommitCaretMoveUndoPrimitive.vb b/src/EditorFeatures/VisualBasic/LineCommit/AbstractCommitCaretMoveUndoPrimitive.vb index 177e8b148476c..40e4aad1138cb 100644 --- a/src/EditorFeatures/VisualBasic/LineCommit/AbstractCommitCaretMoveUndoPrimitive.vb +++ b/src/EditorFeatures/VisualBasic/LineCommit/AbstractCommitCaretMoveUndoPrimitive.vb @@ -2,6 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Operations diff --git a/src/EditorFeatures/VisualBasic/LineCommit/CommitBufferManager.vb b/src/EditorFeatures/VisualBasic/LineCommit/CommitBufferManager.vb index ab97764e5d05f..8444241dcfdab 100644 --- a/src/EditorFeatures/VisualBasic/LineCommit/CommitBufferManager.vb +++ b/src/EditorFeatures/VisualBasic/LineCommit/CommitBufferManager.vb @@ -3,8 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading -Imports System.Threading.Tasks -Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Projection diff --git a/src/EditorFeatures/VisualBasic/LineCommit/CommitConnectionListener.vb b/src/EditorFeatures/VisualBasic/LineCommit/CommitConnectionListener.vb index 4c70da37830a2..9edc74fdb004f 100644 --- a/src/EditorFeatures/VisualBasic/LineCommit/CommitConnectionListener.vb +++ b/src/EditorFeatures/VisualBasic/LineCommit/CommitConnectionListener.vb @@ -2,9 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.ObjectModel Imports System.ComponentModel.Composition -Imports Microsoft.CodeAnalysis.Editor.Host +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor diff --git a/src/EditorFeatures/VisualBasic/LineCommit/CommitFormatter.vb b/src/EditorFeatures/VisualBasic/LineCommit/CommitFormatter.vb index 884c6285bdc93..8af96b410a680 100644 --- a/src/EditorFeatures/VisualBasic/LineCommit/CommitFormatter.vb +++ b/src/EditorFeatures/VisualBasic/LineCommit/CommitFormatter.vb @@ -8,6 +8,7 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.AddImport Imports Microsoft.CodeAnalysis.CodeCleanup Imports Microsoft.CodeAnalysis.CodeCleanup.Providers +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.Host diff --git a/src/EditorFeatures/VisualBasicTest/AddMissingImports/VisualBasicAddMissingImportsRefactoringProviderTests.vb b/src/EditorFeatures/VisualBasicTest/AddMissingImports/VisualBasicAddMissingImportsRefactoringProviderTests.vb index 96358fabc9c91..b64411e62bc48 100644 --- a/src/EditorFeatures/VisualBasicTest/AddMissingImports/VisualBasicAddMissingImportsRefactoringProviderTests.vb +++ b/src/EditorFeatures/VisualBasicTest/AddMissingImports/VisualBasicAddMissingImportsRefactoringProviderTests.vb @@ -3,11 +3,10 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings -Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.PasteTracking Namespace Microsoft.CodeAnalysis.AddMissingImports diff --git a/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticBraceCompletionTests.vb b/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticBraceCompletionTests.vb index fcb173ee02627..7bc49c52d65d9 100644 --- a/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticBraceCompletionTests.vb +++ b/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticBraceCompletionTests.vb @@ -2,11 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.AutomaticCompletion Imports Microsoft.CodeAnalysis.BraceCompletion.AbstractBraceCompletionService Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AutomaticCompletion diff --git a/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticBracketCompletionTests.vb b/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticBracketCompletionTests.vb index 4cec7afe2d7b7..1fe2a11204363 100644 --- a/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticBracketCompletionTests.vb +++ b/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticBracketCompletionTests.vb @@ -2,11 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.AutomaticCompletion Imports Microsoft.CodeAnalysis.BraceCompletion.AbstractBraceCompletionService Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AutomaticCompletion diff --git a/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticInterpolatedStringExpressionCompletionTests.vb b/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticInterpolatedStringExpressionCompletionTests.vb index 4ad09c6819bef..a1f290bcf3171 100644 --- a/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticInterpolatedStringExpressionCompletionTests.vb +++ b/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticInterpolatedStringExpressionCompletionTests.vb @@ -2,11 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.AutomaticCompletion Imports Microsoft.CodeAnalysis.BraceCompletion.AbstractBraceCompletionService Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AutomaticCompletion diff --git a/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticInterpolationCompletionTests.vb b/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticInterpolationCompletionTests.vb index 9fb615df87301..0e4000ef0e328 100644 --- a/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticInterpolationCompletionTests.vb +++ b/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticInterpolationCompletionTests.vb @@ -2,11 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.AutomaticCompletion Imports Microsoft.CodeAnalysis.BraceCompletion.AbstractBraceCompletionService Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AutomaticCompletion diff --git a/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticLessAndGreaterThanCompletionTests.vb b/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticLessAndGreaterThanCompletionTests.vb index 59c8eadcc43ce..53e8d1db98914 100644 --- a/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticLessAndGreaterThanCompletionTests.vb +++ b/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticLessAndGreaterThanCompletionTests.vb @@ -2,11 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.AutomaticCompletion Imports Microsoft.CodeAnalysis.BraceCompletion.AbstractBraceCompletionService Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AutomaticCompletion diff --git a/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticLineEnderTests.vb b/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticLineEnderTests.vb index 90c5bcc51eb35..ffa02bbee2479 100644 --- a/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticLineEnderTests.vb +++ b/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticLineEnderTests.vb @@ -6,7 +6,6 @@ Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.AutomaticCompletion Imports Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration Imports Microsoft.CodeAnalysis.Options diff --git a/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticParenthesesCompletion.vb b/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticParenthesesCompletion.vb index 08d71f6ff16d4..9d16fe1397fd0 100644 --- a/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticParenthesesCompletion.vb +++ b/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticParenthesesCompletion.vb @@ -2,12 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Xml.Linq +Imports Microsoft.CodeAnalysis.BraceCompletion.AbstractBraceCompletionService Imports Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.AutomaticCompletion -Imports Microsoft.CodeAnalysis.BraceCompletion.AbstractBraceCompletionService Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AutomaticCompletion diff --git a/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticStringLiteralCompletionTests.vb b/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticStringLiteralCompletionTests.vb index 81892d1b5c78e..70122833705fa 100644 --- a/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticStringLiteralCompletionTests.vb +++ b/src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticStringLiteralCompletionTests.vb @@ -2,11 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.AutomaticCompletion Imports Microsoft.CodeAnalysis.BraceCompletion.AbstractBraceCompletionService Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AutomaticCompletion diff --git a/src/EditorFeatures/VisualBasicTest/AutomaticEndConstructCorrection/AutomaticEndConstructCorrectorTests.vb b/src/EditorFeatures/VisualBasicTest/AutomaticEndConstructCorrection/AutomaticEndConstructCorrectorTests.vb index 1eea36c4a08d4..8c70be0d02499 100644 --- a/src/EditorFeatures/VisualBasicTest/AutomaticEndConstructCorrection/AutomaticEndConstructCorrectorTests.vb +++ b/src/EditorFeatures/VisualBasicTest/AutomaticEndConstructCorrection/AutomaticEndConstructCorrectorTests.vb @@ -3,8 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.AutomaticEndConstructCorrection Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.Text.Shared.Extensions diff --git a/src/EditorFeatures/VisualBasicTest/BraceMatching/BraceHighlightingTests.vb b/src/EditorFeatures/VisualBasicTest/BraceMatching/BraceHighlightingTests.vb index 86ec175db3724..1a0e98ad367fa 100644 --- a/src/EditorFeatures/VisualBasicTest/BraceMatching/BraceHighlightingTests.vb +++ b/src/EditorFeatures/VisualBasicTest/BraceMatching/BraceHighlightingTests.vb @@ -5,6 +5,7 @@ Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.BraceMatching +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.Tagging Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Text diff --git a/src/EditorFeatures/VisualBasicTest/BraceMatching/VisualBasicBraceMatcherTests.vb b/src/EditorFeatures/VisualBasicTest/BraceMatching/VisualBasicBraceMatcherTests.vb index a71ffeb23e31c..96aabd4d0783f 100644 --- a/src/EditorFeatures/VisualBasicTest/BraceMatching/VisualBasicBraceMatcherTests.vb +++ b/src/EditorFeatures/VisualBasicTest/BraceMatching/VisualBasicBraceMatcherTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.BraceMatching -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.BraceMatching diff --git a/src/EditorFeatures/VisualBasicTest/BracePairs/VisualBasicBracePairsTests.vb b/src/EditorFeatures/VisualBasicTest/BracePairs/VisualBasicBracePairsTests.vb index 1c15269cc4905..7235e7ffe39a7 100644 --- a/src/EditorFeatures/VisualBasicTest/BracePairs/VisualBasicBracePairsTests.vb +++ b/src/EditorFeatures/VisualBasicTest/BracePairs/VisualBasicBracePairsTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Test.Utilities.BracePairs Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.BracePairs diff --git a/src/EditorFeatures/VisualBasicTest/CaseCorrecting/CaseCorrectionServiceTests.vb b/src/EditorFeatures/VisualBasicTest/CaseCorrecting/CaseCorrectionServiceTests.vb index eaca1431049d9..fcff54c4533b2 100644 --- a/src/EditorFeatures/VisualBasicTest/CaseCorrecting/CaseCorrectionServiceTests.vb +++ b/src/EditorFeatures/VisualBasicTest/CaseCorrecting/CaseCorrectionServiceTests.vb @@ -5,11 +5,9 @@ Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeCleanup Imports Microsoft.CodeAnalysis.CodeCleanup.Providers Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CaseCorrecting diff --git a/src/EditorFeatures/VisualBasicTest/ChangeSignature/ChangeSignatureTests.vb b/src/EditorFeatures/VisualBasicTest/ChangeSignature/ChangeSignatureTests.vb index 60b16b783f74e..e4a6038c07d07 100644 --- a/src/EditorFeatures/VisualBasicTest/ChangeSignature/ChangeSignatureTests.vb +++ b/src/EditorFeatures/VisualBasicTest/ChangeSignature/ChangeSignatureTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature diff --git a/src/EditorFeatures/VisualBasicTest/ChangeSignature/ChangeSignature_Delegates.vb b/src/EditorFeatures/VisualBasicTest/ChangeSignature/ChangeSignature_Delegates.vb index d1d85ba474177..4b5850e7f6c10 100644 --- a/src/EditorFeatures/VisualBasicTest/ChangeSignature/ChangeSignature_Delegates.vb +++ b/src/EditorFeatures/VisualBasicTest/ChangeSignature/ChangeSignature_Delegates.vb @@ -6,7 +6,6 @@ Imports Microsoft.CodeAnalysis.ChangeSignature Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature diff --git a/src/EditorFeatures/VisualBasicTest/ChangeSignature/RemoveParametersTests.vb b/src/EditorFeatures/VisualBasicTest/ChangeSignature/RemoveParametersTests.vb index 27db84f7619b8..c15f568438f1e 100644 --- a/src/EditorFeatures/VisualBasicTest/ChangeSignature/RemoveParametersTests.vb +++ b/src/EditorFeatures/VisualBasicTest/ChangeSignature/RemoveParametersTests.vb @@ -6,7 +6,6 @@ Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.ChangeSignature Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands diff --git a/src/EditorFeatures/VisualBasicTest/ChangeSignature/ReorderParameters.MultiFile.vb b/src/EditorFeatures/VisualBasicTest/ChangeSignature/ReorderParameters.MultiFile.vb index 2f0a83cbae32e..fbd778d048b04 100644 --- a/src/EditorFeatures/VisualBasicTest/ChangeSignature/ReorderParameters.MultiFile.vb +++ b/src/EditorFeatures/VisualBasicTest/ChangeSignature/ReorderParameters.MultiFile.vb @@ -2,12 +2,11 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature Imports Microsoft.VisualStudio.Text.Operations -Imports Microsoft.CodeAnalysis.Editor.UnitTests Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature diff --git a/src/EditorFeatures/VisualBasicTest/Classification/AbstractVisualBasicClassifierTests.vb b/src/EditorFeatures/VisualBasicTest/Classification/AbstractVisualBasicClassifierTests.vb index 67d60acd74fa9..c4e72f2d7efab 100644 --- a/src/EditorFeatures/VisualBasicTest/Classification/AbstractVisualBasicClassifierTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Classification/AbstractVisualBasicClassifierTests.vb @@ -4,7 +4,6 @@ Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Classification -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Classification diff --git a/src/EditorFeatures/VisualBasicTest/CodeActions/AbstractVisualBasicCodeActionTest.vb b/src/EditorFeatures/VisualBasicTest/CodeActions/AbstractVisualBasicCodeActionTest.vb index 6954f7c864071..a9fea777402a4 100644 --- a/src/EditorFeatures/VisualBasicTest/CodeActions/AbstractVisualBasicCodeActionTest.vb +++ b/src/EditorFeatures/VisualBasicTest/CodeActions/AbstractVisualBasicCodeActionTest.vb @@ -2,9 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings diff --git a/src/EditorFeatures/VisualBasicTest/CodeActions/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.vb b/src/EditorFeatures/VisualBasicTest/CodeActions/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.vb index c5ce91c7c8423..2adb44e0d09bb 100644 --- a/src/EditorFeatures/VisualBasicTest/CodeActions/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.vb +++ b/src/EditorFeatures/VisualBasicTest/CodeActions/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.vb @@ -3,7 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers Imports Microsoft.CodeAnalysis.PickMembers diff --git a/src/EditorFeatures/VisualBasicTest/CodeActions/GenerateOverrides/GenerateOverridesTests.vb b/src/EditorFeatures/VisualBasicTest/CodeActions/GenerateOverrides/GenerateOverridesTests.vb index 6a70568710f09..4b0b01a1b7dd4 100644 --- a/src/EditorFeatures/VisualBasicTest/CodeActions/GenerateOverrides/GenerateOverridesTests.vb +++ b/src/EditorFeatures/VisualBasicTest/CodeActions/GenerateOverrides/GenerateOverridesTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.GenerateOverrides Imports Microsoft.CodeAnalysis.PickMembers diff --git a/src/EditorFeatures/VisualBasicTest/CodeActions/GenerateType/GenerateTypeTests.vb b/src/EditorFeatures/VisualBasicTest/CodeActions/GenerateType/GenerateTypeTests.vb index 22e86a294a7f6..9732a2e2226ef 100644 --- a/src/EditorFeatures/VisualBasicTest/CodeActions/GenerateType/GenerateTypeTests.vb +++ b/src/EditorFeatures/VisualBasicTest/CodeActions/GenerateType/GenerateTypeTests.vb @@ -8,7 +8,6 @@ Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.NamingStyles Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateType diff --git a/src/EditorFeatures/VisualBasicTest/CodeActions/InitializeParameter/AddParameterCheckTests.vb b/src/EditorFeatures/VisualBasicTest/CodeActions/InitializeParameter/AddParameterCheckTests.vb index 3c4dd2c73fe34..76aefb0ad312a 100644 --- a/src/EditorFeatures/VisualBasicTest/CodeActions/InitializeParameter/AddParameterCheckTests.vb +++ b/src/EditorFeatures/VisualBasicTest/CodeActions/InitializeParameter/AddParameterCheckTests.vb @@ -4,7 +4,6 @@ Imports System.Globalization Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.InitializeParameter diff --git a/src/EditorFeatures/VisualBasicTest/CodeActions/InitializeParameter/InitializeMemberFromParameterTests.vb b/src/EditorFeatures/VisualBasicTest/CodeActions/InitializeParameter/InitializeMemberFromParameterTests.vb index 826fe1b8679c3..539f22a50b1aa 100644 --- a/src/EditorFeatures/VisualBasicTest/CodeActions/InitializeParameter/InitializeMemberFromParameterTests.vb +++ b/src/EditorFeatures/VisualBasicTest/CodeActions/InitializeParameter/InitializeMemberFromParameterTests.vb @@ -4,7 +4,6 @@ Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.CodeStyle -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.InitializeParameter diff --git a/src/EditorFeatures/VisualBasicTest/CodeActions/MoveStaticMembers/VisualBasicMoveStaticMembersTests.vb b/src/EditorFeatures/VisualBasicTest/CodeActions/MoveStaticMembers/VisualBasicMoveStaticMembersTests.vb index 88f31223d1d0e..4ad43ece80c31 100644 --- a/src/EditorFeatures/VisualBasicTest/CodeActions/MoveStaticMembers/VisualBasicMoveStaticMembersTests.vb +++ b/src/EditorFeatures/VisualBasicTest/CodeActions/MoveStaticMembers/VisualBasicMoveStaticMembersTests.vb @@ -6,7 +6,6 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.MoveStaticMembers Imports Microsoft.CodeAnalysis.Test.Utilities.MoveStaticMembers Imports Microsoft.CodeAnalysis.Testing -Imports Microsoft.CodeAnalysis.Testing.Verifiers Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeRefactoringVerifier(Of Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings.MoveStaticMembers.VisualBasicMoveStaticMembersRefactoringProvider) diff --git a/src/EditorFeatures/VisualBasicTest/CodeActions/MoveType/BasicMoveTypeTestsBase.vb b/src/EditorFeatures/VisualBasicTest/CodeActions/MoveType/BasicMoveTypeTestsBase.vb index 629faf6778e08..08e700458c38c 100644 --- a/src/EditorFeatures/VisualBasicTest/CodeActions/MoveType/BasicMoveTypeTestsBase.vb +++ b/src/EditorFeatures/VisualBasicTest/CodeActions/MoveType/BasicMoveTypeTestsBase.vb @@ -3,11 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.Xml.Linq -Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.CodeRefactorings.MoveType Imports Microsoft.CodeAnalysis.Editor.UnitTests.MoveType -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings.MoveType Public Class BasicMoveTypeTestsBase diff --git a/src/EditorFeatures/VisualBasicTest/CodeActions/Preview/PreviewTests.vb b/src/EditorFeatures/VisualBasicTest/CodeActions/Preview/PreviewTests.vb index 152aa4e467335..8f8e04d5d5997 100644 --- a/src/EditorFeatures/VisualBasicTest/CodeActions/Preview/PreviewTests.vb +++ b/src/EditorFeatures/VisualBasicTest/CodeActions/Preview/PreviewTests.vb @@ -5,12 +5,9 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.Implementation.Preview Imports Microsoft.CodeAnalysis.Editor.UnitTests -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Preview -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings diff --git a/src/EditorFeatures/VisualBasicTest/CodeActions/SpellCheck/SpellCheckSpanTests.vb b/src/EditorFeatures/VisualBasicTest/CodeActions/SpellCheck/SpellCheckSpanTests.vb index a3969a8f7beda..37f20ba94307d 100644 --- a/src/EditorFeatures/VisualBasicTest/CodeActions/SpellCheck/SpellCheckSpanTests.vb +++ b/src/EditorFeatures/VisualBasicTest/CodeActions/SpellCheck/SpellCheckSpanTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.SpellCheck -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SpellCheck diff --git a/src/EditorFeatures/VisualBasicTest/CommentSelection/VisualBasicCommentSelectionTests.vb b/src/EditorFeatures/VisualBasicTest/CommentSelection/VisualBasicCommentSelectionTests.vb index 92cd33c09bc9d..d09cde48834c1 100644 --- a/src/EditorFeatures/VisualBasicTest/CommentSelection/VisualBasicCommentSelectionTests.vb +++ b/src/EditorFeatures/VisualBasicTest/CommentSelection/VisualBasicCommentSelectionTests.vb @@ -6,7 +6,6 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CommentSelection Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Text diff --git a/src/EditorFeatures/VisualBasicTest/CommentSelection/VisualBasicToggleLineCommentTests.vb b/src/EditorFeatures/VisualBasicTest/CommentSelection/VisualBasicToggleLineCommentTests.vb index 6d6a5a049081c..9351e87c01b88 100644 --- a/src/EditorFeatures/VisualBasicTest/CommentSelection/VisualBasicToggleLineCommentTests.vb +++ b/src/EditorFeatures/VisualBasicTest/CommentSelection/VisualBasicToggleLineCommentTests.vb @@ -3,10 +3,8 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CommentSelection -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Test.Utilities.CommentSelection Imports Microsoft.VisualStudio.Commanding -Imports Microsoft.VisualStudio.Composition Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CommentSelection <[UseExportProvider]> diff --git a/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/CrefCompletionProviderTests.vb b/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/CrefCompletionProviderTests.vb index 57c82ab5fe557..1c60fddbc1358 100644 --- a/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/CrefCompletionProviderTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/CrefCompletionProviderTests.vb @@ -4,7 +4,6 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Completion -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/ExtensionMethodImportCompletionProviderTests.vb b/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/ExtensionMethodImportCompletionProviderTests.vb index 290fa46663e19..4f414a5a54be8 100644 --- a/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/ExtensionMethodImportCompletionProviderTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/ExtensionMethodImportCompletionProviderTests.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Completion -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders diff --git a/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/ImplementsClauseCompletionProviderTests.vb b/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/ImplementsClauseCompletionProviderTests.vb index 9c57e0f036006..d930c7750ef39 100644 --- a/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/ImplementsClauseCompletionProviderTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/ImplementsClauseCompletionProviderTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Completion -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders diff --git a/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/ObjectInitializerCompletionProviderTests.vb b/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/ObjectInitializerCompletionProviderTests.vb index 184f9c62ba854..90249f5e6fb81 100644 --- a/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/ObjectInitializerCompletionProviderTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/ObjectInitializerCompletionProviderTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Completion -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data Imports RoslynCompletion = Microsoft.CodeAnalysis.Completion diff --git a/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/OverrideCompletionProviderTests.vb b/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/OverrideCompletionProviderTests.vb index 3f89b6cd77b9b..72e1f15fc1b0e 100644 --- a/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/OverrideCompletionProviderTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/OverrideCompletionProviderTests.vb @@ -3,8 +3,8 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Completion -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers diff --git a/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/SuggestionModeCompletionProviderTests.vb b/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/SuggestionModeCompletionProviderTests.vb index 88f475576e1b4..bc6eb54d8e91b 100644 --- a/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/SuggestionModeCompletionProviderTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/SuggestionModeCompletionProviderTests.vb @@ -7,7 +7,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders diff --git a/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/SymbolCompletionProviderTests.vb b/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/SymbolCompletionProviderTests.vb index f0bf1e3d87221..60b86e8abf5c4 100644 --- a/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/SymbolCompletionProviderTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/SymbolCompletionProviderTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data diff --git a/src/EditorFeatures/VisualBasicTest/Debugging/LocationInfoGetterTests.vb b/src/EditorFeatures/VisualBasicTest/Debugging/LocationInfoGetterTests.vb index 55caa072724c0..52e82ae956091 100644 --- a/src/EditorFeatures/VisualBasicTest/Debugging/LocationInfoGetterTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Debugging/LocationInfoGetterTests.vb @@ -3,14 +3,8 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading -Imports System.Threading.Tasks -Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Debugging -Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Debugging diff --git a/src/EditorFeatures/VisualBasicTest/Debugging/NameResolverTests.vb b/src/EditorFeatures/VisualBasicTest/Debugging/NameResolverTests.vb index 25e9efd62b798..a8b085cc227fd 100644 --- a/src/EditorFeatures/VisualBasicTest/Debugging/NameResolverTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Debugging/NameResolverTests.vb @@ -3,11 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Debugging Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Debugging diff --git a/src/EditorFeatures/VisualBasicTest/Debugging/ProximityExpressionsGetterTests.Statements.vb b/src/EditorFeatures/VisualBasicTest/Debugging/ProximityExpressionsGetterTests.Statements.vb index ab07a7ada79ec..a852ce159a540 100644 --- a/src/EditorFeatures/VisualBasicTest/Debugging/ProximityExpressionsGetterTests.Statements.vb +++ b/src/EditorFeatures/VisualBasicTest/Debugging/ProximityExpressionsGetterTests.Statements.vb @@ -2,10 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Debugging -Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Debugging <[UseExportProvider]> diff --git a/src/EditorFeatures/VisualBasicTest/Debugging/ProximityExpressionsGetterTests.vb b/src/EditorFeatures/VisualBasicTest/Debugging/ProximityExpressionsGetterTests.vb index 1d99da1f80421..44dacd13d40a8 100644 --- a/src/EditorFeatures/VisualBasicTest/Debugging/ProximityExpressionsGetterTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Debugging/ProximityExpressionsGetterTests.vb @@ -5,19 +5,12 @@ Imports System.IO Imports System.Text Imports System.Threading -Imports System.Threading.Tasks Imports System.Windows Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.Shared.Extensions -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Debugging Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.Text -Imports Roslyn.Test.Utilities -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Debugging diff --git a/src/EditorFeatures/VisualBasicTest/Diagnostics/AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest.vb b/src/EditorFeatures/VisualBasicTest/Diagnostics/AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest.vb index b3af39f3ff3d3..bf99aaf26ab69 100644 --- a/src/EditorFeatures/VisualBasicTest/Diagnostics/AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest.vb +++ b/src/EditorFeatures/VisualBasicTest/Diagnostics/AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest.vb @@ -2,9 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions +Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics Imports Xunit.Abstractions Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics diff --git a/src/EditorFeatures/VisualBasicTest/Diagnostics/DiagnosticAnalyzerDriver/DiagnosticAnalyzerDriverTests.vb b/src/EditorFeatures/VisualBasicTest/Diagnostics/DiagnosticAnalyzerDriver/DiagnosticAnalyzerDriverTests.vb index 4a19bc92bab85..07bc81522e0c7 100644 --- a/src/EditorFeatures/VisualBasicTest/Diagnostics/DiagnosticAnalyzerDriver/DiagnosticAnalyzerDriverTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Diagnostics/DiagnosticAnalyzerDriver/DiagnosticAnalyzerDriverTests.vb @@ -4,10 +4,9 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.UnitTests.Diagnostics diff --git a/src/EditorFeatures/VisualBasicTest/DocumentationComments/DocumentationCommentTests.vb b/src/EditorFeatures/VisualBasicTest/DocumentationComments/DocumentationCommentTests.vb index da55365f986c3..0ddc982391f64 100644 --- a/src/EditorFeatures/VisualBasicTest/DocumentationComments/DocumentationCommentTests.vb +++ b/src/EditorFeatures/VisualBasicTest/DocumentationComments/DocumentationCommentTests.vb @@ -7,7 +7,6 @@ Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.Editor.UnitTests.DocumentationComments Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.DocumentationComments Imports Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit Imports Microsoft.VisualStudio.Commanding diff --git a/src/EditorFeatures/VisualBasicTest/DocumentationComments/XmlTagCompletionTests.vb b/src/EditorFeatures/VisualBasicTest/DocumentationComments/XmlTagCompletionTests.vb index 12eb121e45cad..ecd1f908f7508 100644 --- a/src/EditorFeatures/VisualBasicTest/DocumentationComments/XmlTagCompletionTests.vb +++ b/src/EditorFeatures/VisualBasicTest/DocumentationComments/XmlTagCompletionTests.vb @@ -4,7 +4,6 @@ Imports Microsoft.CodeAnalysis.Editor.UnitTests.DocumentationComments Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.DocumentationComments Imports Microsoft.VisualStudio.Commanding Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands diff --git a/src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldCommandHandlerTests.vb b/src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldCommandHandlerTests.vb index 6e3bfe2bf3382..5027531055e3c 100644 --- a/src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldCommandHandlerTests.vb +++ b/src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldCommandHandlerTests.vb @@ -4,9 +4,7 @@ Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.CodeAnalysis.VisualBasic.EncapsulateField Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands diff --git a/src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldTestState.vb b/src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldTestState.vb index efdacb32827ab..151000ecc0830 100644 --- a/src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldTestState.vb +++ b/src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldTestState.vb @@ -2,12 +2,12 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.VisualBasic.EncapsulateField Imports Microsoft.CodeAnalysis.Shared.TestHooks +Imports Microsoft.CodeAnalysis.VisualBasic.EncapsulateField Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Imports Microsoft.VisualStudio.Text.Operations diff --git a/src/EditorFeatures/VisualBasicTest/EndConstructGeneration/EndConstructCommandHandlerTests.vb b/src/EditorFeatures/VisualBasicTest/EndConstructGeneration/EndConstructCommandHandlerTests.vb index b7fcfe8135e32..45ff78c47ccd6 100644 --- a/src/EditorFeatures/VisualBasicTest/EndConstructGeneration/EndConstructCommandHandlerTests.vb +++ b/src/EditorFeatures/VisualBasicTest/EndConstructGeneration/EndConstructCommandHandlerTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.Implementation.EndConstructGeneration -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Moq diff --git a/src/EditorFeatures/VisualBasicTest/EndConstructGeneration/MiscellaneousTests.vb b/src/EditorFeatures/VisualBasicTest/EndConstructGeneration/MiscellaneousTests.vb index 422a2a7084333..37e25fb90daf2 100644 --- a/src/EditorFeatures/VisualBasicTest/EndConstructGeneration/MiscellaneousTests.vb +++ b/src/EditorFeatures/VisualBasicTest/EndConstructGeneration/MiscellaneousTests.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor diff --git a/src/EditorFeatures/VisualBasicTest/Extensions/StatementSyntaxExtensionTests.vb b/src/EditorFeatures/VisualBasicTest/Extensions/StatementSyntaxExtensionTests.vb index 363e08108a6b2..466f342aa7dd7 100644 --- a/src/EditorFeatures/VisualBasicTest/Extensions/StatementSyntaxExtensionTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Extensions/StatementSyntaxExtensionTests.vb @@ -2,10 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax +Imports System.Threading Imports Microsoft.CodeAnalysis.VisualBasic.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery -Imports System.Threading +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Extensions Public Class StatementSyntaxExtensionTests diff --git a/src/EditorFeatures/VisualBasicTest/ExtractInterface/ExtractInterfaceTests.vb b/src/EditorFeatures/VisualBasicTest/ExtractInterface/ExtractInterfaceTests.vb index e5d600159edb4..14e63b60cfaa2 100644 --- a/src/EditorFeatures/VisualBasicTest/ExtractInterface/ExtractInterfaceTests.vb +++ b/src/EditorFeatures/VisualBasicTest/ExtractInterface/ExtractInterfaceTests.vb @@ -6,9 +6,8 @@ Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.ExtractInterface -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.VisualBasic.ExtractInterface Imports Microsoft.CodeAnalysis.ExtractInterface +Imports Microsoft.CodeAnalysis.VisualBasic.ExtractInterface Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ExtractInterface diff --git a/src/EditorFeatures/VisualBasicTest/ExtractMethod/ExtractMethodTests.LanguageInteraction.vb b/src/EditorFeatures/VisualBasicTest/ExtractMethod/ExtractMethodTests.LanguageInteraction.vb index 54151135cd8ba..0c8f0d0ce0ea4 100644 --- a/src/EditorFeatures/VisualBasicTest/ExtractMethod/ExtractMethodTests.LanguageInteraction.vb +++ b/src/EditorFeatures/VisualBasicTest/ExtractMethod/ExtractMethodTests.LanguageInteraction.vb @@ -2,17 +2,11 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.ExtractMethod -Imports Microsoft.CodeAnalysis.Options -Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.CodeAnalysis.UnitTests -Imports Microsoft.CodeAnalysis.VisualBasic.ExtractMethod Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands -Imports Microsoft.VisualStudio.Text.Operations Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ExtractMethod Partial Public Class ExtractMethodTests diff --git a/src/EditorFeatures/VisualBasicTest/Formatting/CodeCleanUpTests.vb b/src/EditorFeatures/VisualBasicTest/Formatting/CodeCleanUpTests.vb index 2bca427694654..d67ba6133a000 100644 --- a/src/EditorFeatures/VisualBasicTest/Formatting/CodeCleanUpTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Formatting/CodeCleanUpTests.vb @@ -5,31 +5,19 @@ Imports System.Collections.Immutable Imports System.Composition Imports System.Threading -Imports Microsoft.CodeAnalysis.AddImport +Imports Microsoft.CodeAnalysis.AddFileBanner Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeCleanup -Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Diagnostics.VisualBasic Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Editor.UnitTests -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.Formatting +Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.Host.Mef -Imports Microsoft.CodeAnalysis.MakeFieldReadonly -Imports Microsoft.CodeAnalysis.Options -Imports Microsoft.CodeAnalysis.Shared.Utilities -Imports Microsoft.CodeAnalysis.SolutionCrawler -Imports Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.Diagnostics.Analyzers -Imports Microsoft.CodeAnalysis.VisualBasic.Formatting -Imports Microsoft.CodeAnalysis.VisualBasic.Simplification -Imports Microsoft.CodeAnalysis.VisualBasic.MakeFieldReadonly -Imports Microsoft.CodeAnalysis.AddFileBanner -Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Formatting diff --git a/src/EditorFeatures/VisualBasicTest/Formatting/Indentation/SmartIndentProviderTests.vb b/src/EditorFeatures/VisualBasicTest/Formatting/Indentation/SmartIndentProviderTests.vb index 0c1551d5bb0e2..3a1441f0ccda2 100644 --- a/src/EditorFeatures/VisualBasicTest/Formatting/Indentation/SmartIndentProviderTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Formatting/Indentation/SmartIndentProviderTests.vb @@ -4,7 +4,6 @@ Imports Microsoft.CodeAnalysis.Editor.Implementation.SmartIndent Imports Microsoft.CodeAnalysis.Editor.UnitTests -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Options Imports Microsoft.VisualStudio.Text.Editor diff --git a/src/EditorFeatures/VisualBasicTest/Formatting/Indentation/SmartTokenFormatter_FormatTokenTests.vb b/src/EditorFeatures/VisualBasicTest/Formatting/Indentation/SmartTokenFormatter_FormatTokenTests.vb index e57a62172f560..d87cffa905fde 100644 --- a/src/EditorFeatures/VisualBasicTest/Formatting/Indentation/SmartTokenFormatter_FormatTokenTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Formatting/Indentation/SmartTokenFormatter_FormatTokenTests.vb @@ -3,12 +3,9 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.Threading Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Formatting.Rules -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.Text.Shared.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.Formatting diff --git a/src/EditorFeatures/VisualBasicTest/Formatting/VisualBasicFormattingEngineTests.vb b/src/EditorFeatures/VisualBasicTest/Formatting/VisualBasicFormattingEngineTests.vb index dced91769d1e0..9aea018b3e76b 100644 --- a/src/EditorFeatures/VisualBasicTest/Formatting/VisualBasicFormattingEngineTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Formatting/VisualBasicFormattingEngineTests.vb @@ -4,7 +4,6 @@ Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions -Imports Microsoft.CodeAnalysis.Options Imports Xunit.Abstractions Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Formatting diff --git a/src/EditorFeatures/VisualBasicTest/Formatting/VisualBasicNewDocumentFormattingServiceTests.vb b/src/EditorFeatures/VisualBasicTest/Formatting/VisualBasicNewDocumentFormattingServiceTests.vb index 3a75f9c7095c4..3b664c106575f 100644 --- a/src/EditorFeatures/VisualBasicTest/Formatting/VisualBasicNewDocumentFormattingServiceTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Formatting/VisualBasicNewDocumentFormattingServiceTests.vb @@ -4,8 +4,6 @@ Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Test.Utilities.Formatting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Formatting diff --git a/src/EditorFeatures/VisualBasicTest/ImplementAbstractClass/ImplementAbstractClassCommandHandlerTests.vb b/src/EditorFeatures/VisualBasicTest/ImplementAbstractClass/ImplementAbstractClassCommandHandlerTests.vb index 8bb86da7ec8a6..d9cefbeb18576 100644 --- a/src/EditorFeatures/VisualBasicTest/ImplementAbstractClass/ImplementAbstractClassCommandHandlerTests.vb +++ b/src/EditorFeatures/VisualBasicTest/ImplementAbstractClass/ImplementAbstractClassCommandHandlerTests.vb @@ -6,7 +6,6 @@ Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.ImplementAbstractClass Imports Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit Imports Microsoft.CodeAnalysis.Options diff --git a/src/EditorFeatures/VisualBasicTest/ImplementInterface/ImplementInterfaceCommandHandlerTests.vb b/src/EditorFeatures/VisualBasicTest/ImplementInterface/ImplementInterfaceCommandHandlerTests.vb index 13868b4423c74..de87dbcd519cd 100644 --- a/src/EditorFeatures/VisualBasicTest/ImplementInterface/ImplementInterfaceCommandHandlerTests.vb +++ b/src/EditorFeatures/VisualBasicTest/ImplementInterface/ImplementInterfaceCommandHandlerTests.vb @@ -5,7 +5,6 @@ Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.ImplementInterface Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text diff --git a/src/EditorFeatures/VisualBasicTest/KeywordHighlighting/AbstractVisualBasicKeywordHighlighterTests.vb b/src/EditorFeatures/VisualBasicTest/KeywordHighlighting/AbstractVisualBasicKeywordHighlighterTests.vb index fa8ff80f7abd0..b7aee0ccbc3c0 100644 --- a/src/EditorFeatures/VisualBasicTest/KeywordHighlighting/AbstractVisualBasicKeywordHighlighterTests.vb +++ b/src/EditorFeatures/VisualBasicTest/KeywordHighlighting/AbstractVisualBasicKeywordHighlighterTests.vb @@ -5,7 +5,6 @@ Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.KeywordHighlighting -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting Public MustInherit Class AbstractVisualBasicKeywordHighlighterTests diff --git a/src/EditorFeatures/VisualBasicTest/LineCommit/CommitOnEnterTests.vb b/src/EditorFeatures/VisualBasicTest/LineCommit/CommitOnEnterTests.vb index d2eb16148c21f..c774c78fb102a 100644 --- a/src/EditorFeatures/VisualBasicTest/LineCommit/CommitOnEnterTests.vb +++ b/src/EditorFeatures/VisualBasicTest/LineCommit/CommitOnEnterTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands diff --git a/src/EditorFeatures/VisualBasicTest/LineCommit/CommitTestData.vb b/src/EditorFeatures/VisualBasicTest/LineCommit/CommitTestData.vb index 6957c7f027bf0..65cb2f6d9b9e5 100644 --- a/src/EditorFeatures/VisualBasicTest/LineCommit/CommitTestData.vb +++ b/src/EditorFeatures/VisualBasicTest/LineCommit/CommitTestData.vb @@ -3,14 +3,12 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit Imports Microsoft.CodeAnalysis.Options -Imports Microsoft.CodeAnalysis.Rename Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.Text.Shared.Extensions Imports Microsoft.VisualStudio.Text @@ -112,7 +110,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.LineCommit Throw New NotImplementedException() End Sub - Public Function CommitAsync(previewChanges As Boolean, Optional editorOperationContext As IUIThreadOperationContext = Nothing) As Task Implements IInlineRenameSession.CommitAsync + Public Function CommitAsync(previewChanges As Boolean, editorOperationContext As IUIThreadOperationContext) As Task Implements IInlineRenameSession.CommitAsync Throw New NotImplementedException() End Function End Class diff --git a/src/EditorFeatures/VisualBasicTest/LineSeparators/LineSeparatorTests.vb b/src/EditorFeatures/VisualBasicTest/LineSeparators/LineSeparatorTests.vb index 1fbdf4e6e1af5..f6b6fa1e784f5 100644 --- a/src/EditorFeatures/VisualBasicTest/LineSeparators/LineSeparatorTests.vb +++ b/src/EditorFeatures/VisualBasicTest/LineSeparators/LineSeparatorTests.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.LineSeparators Imports Microsoft.CodeAnalysis.LineSeparators Imports Microsoft.CodeAnalysis.Text diff --git a/src/EditorFeatures/VisualBasicTest/NavigateTo/NavigateToTests.vb b/src/EditorFeatures/VisualBasicTest/NavigateTo/NavigateToTests.vb index 56e6382b9af58..070f4441e7c01 100644 --- a/src/EditorFeatures/VisualBasicTest/NavigateTo/NavigateToTests.vb +++ b/src/EditorFeatures/VisualBasicTest/NavigateTo/NavigateToTests.vb @@ -2,13 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo -Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.NavigateTo -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Remote.Testing -Imports Microsoft.CodeAnalysis.Shared.TestHooks -Imports Microsoft.VisualStudio.Composition Imports Microsoft.VisualStudio.Language.NavigateTo.Interfaces Imports Microsoft.VisualStudio.Text.PatternMatching Imports Roslyn.Test.EditorUtilities.NavigateTo diff --git a/src/EditorFeatures/VisualBasicTest/Organizing/AbstractOrganizerTests.vb b/src/EditorFeatures/VisualBasicTest/Organizing/AbstractOrganizerTests.vb index c1608ab413a0b..5fb589c44afdc 100644 --- a/src/EditorFeatures/VisualBasicTest/Organizing/AbstractOrganizerTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Organizing/AbstractOrganizerTests.vb @@ -2,10 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Organizing Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Organizing diff --git a/src/EditorFeatures/VisualBasicTest/Organizing/OrganizeTypeDeclarationTests.vb b/src/EditorFeatures/VisualBasicTest/Organizing/OrganizeTypeDeclarationTests.vb index 3d54ab2e13a6d..41733244a6806 100644 --- a/src/EditorFeatures/VisualBasicTest/Organizing/OrganizeTypeDeclarationTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Organizing/OrganizeTypeDeclarationTests.vb @@ -6,7 +6,6 @@ Imports Microsoft.CodeAnalysis.Editor.Commanding.Commands Imports Microsoft.CodeAnalysis.Editor.Implementation.Organizing Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.[Shared].TestHooks Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Organizing diff --git a/src/EditorFeatures/VisualBasicTest/QuickInfo/SemanticQuickInfoSourceTests.vb b/src/EditorFeatures/VisualBasicTest/QuickInfo/SemanticQuickInfoSourceTests.vb index 17a494f776275..0fa42fad0fa7f 100644 --- a/src/EditorFeatures/VisualBasicTest/QuickInfo/SemanticQuickInfoSourceTests.vb +++ b/src/EditorFeatures/VisualBasicTest/QuickInfo/SemanticQuickInfoSourceTests.vb @@ -6,7 +6,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.QuickInfo -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.QuickInfo diff --git a/src/EditorFeatures/VisualBasicTest/ReassignedVariable/VisualBasicReassignedVariableTests.vb b/src/EditorFeatures/VisualBasicTest/ReassignedVariable/VisualBasicReassignedVariableTests.vb index 4f145f5135b45..7640d2d8cacb0 100644 --- a/src/EditorFeatures/VisualBasicTest/ReassignedVariable/VisualBasicReassignedVariableTests.vb +++ b/src/EditorFeatures/VisualBasicTest/ReassignedVariable/VisualBasicReassignedVariableTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.ReassignedVariable -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ReassignedVariable Public Class VisualBasicReassignedVariableTests diff --git a/src/EditorFeatures/VisualBasicTest/Recommendations/RecommendationTestHelpers.vb b/src/EditorFeatures/VisualBasicTest/Recommendations/RecommendationTestHelpers.vb index d9e46a4ee0d3a..273f5e0596f9c 100644 --- a/src/EditorFeatures/VisualBasicTest/Recommendations/RecommendationTestHelpers.vb +++ b/src/EditorFeatures/VisualBasicTest/Recommendations/RecommendationTestHelpers.vb @@ -5,7 +5,6 @@ Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery diff --git a/src/EditorFeatures/VisualBasicTest/Semantics/SpeculationAnalyzerTests.vb b/src/EditorFeatures/VisualBasicTest/Semantics/SpeculationAnalyzerTests.vb index 49196ff75fdf2..46414ac22fe92 100644 --- a/src/EditorFeatures/VisualBasicTest/Semantics/SpeculationAnalyzerTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Semantics/SpeculationAnalyzerTests.vb @@ -4,6 +4,7 @@ Imports System.IO Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.UnitTests.Semantics Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities @@ -135,7 +136,7 @@ End Class CompilationName, {DirectCast(tree, VisualBasicSyntaxTree)}, References, - TestOptions.ReleaseDll.WithSpecificDiagnosticOptions({KeyValuePairUtil.Create("BC0219", ReportDiagnostic.Suppress)})) + TestOptions.ReleaseDll.WithSpecificDiagnosticOptions({KeyValuePair.Create("BC0219", ReportDiagnostic.Suppress)})) End Function Protected Overrides Function CompilationSucceeded(compilation As Compilation, temporaryStream As Stream) As Boolean diff --git a/src/EditorFeatures/VisualBasicTest/SplitComment/SplitCommentCommandHandlerTests.vb b/src/EditorFeatures/VisualBasicTest/SplitComment/SplitCommentCommandHandlerTests.vb index f3616eab7a90d..65adaed9dbb7c 100644 --- a/src/EditorFeatures/VisualBasicTest/SplitComment/SplitCommentCommandHandlerTests.vb +++ b/src/EditorFeatures/VisualBasicTest/SplitComment/SplitCommentCommandHandlerTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.SplitComment -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SplitComment diff --git a/src/EditorFeatures/VisualBasicTest/SymbolId/SymbolKeyCompilationsTests.vb b/src/EditorFeatures/VisualBasicTest/SymbolId/SymbolKeyCompilationsTests.vb index 17942d197f644..4077f33c31ce5 100644 --- a/src/EditorFeatures/VisualBasicTest/SymbolId/SymbolKeyCompilationsTests.vb +++ b/src/EditorFeatures/VisualBasicTest/SymbolId/SymbolKeyCompilationsTests.vb @@ -3,7 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax +Imports Microsoft.CodeAnalysis.Collections Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SymbolId diff --git a/src/EditorFeatures/VisualBasicTest/SymbolId/SymbolKeyMetadataVsSourceTests.vb b/src/EditorFeatures/VisualBasicTest/SymbolId/SymbolKeyMetadataVsSourceTests.vb index df2f6b8f76b8e..606016e225124 100644 --- a/src/EditorFeatures/VisualBasicTest/SymbolId/SymbolKeyMetadataVsSourceTests.vb +++ b/src/EditorFeatures/VisualBasicTest/SymbolId/SymbolKeyMetadataVsSourceTests.vb @@ -2,9 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Basic.Reference.Assemblies +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SymbolId diff --git a/src/EditorFeatures/VisualBasicTest/TaskList/VisualBasicTaskListTests.vb b/src/EditorFeatures/VisualBasicTest/TaskList/VisualBasicTaskListTests.vb index e3a7955a54c83..7b2a304f13e97 100644 --- a/src/EditorFeatures/VisualBasicTest/TaskList/VisualBasicTaskListTests.vb +++ b/src/EditorFeatures/VisualBasicTest/TaskList/VisualBasicTaskListTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Test.Utilities.TaskList diff --git a/src/EditorFeatures/VisualBasicTest/TextStructureNavigation/TextStructureNavigatorTests.vb b/src/EditorFeatures/VisualBasicTest/TextStructureNavigation/TextStructureNavigatorTests.vb index e1b9171847a6c..119a2563a2b46 100644 --- a/src/EditorFeatures/VisualBasicTest/TextStructureNavigation/TextStructureNavigatorTests.vb +++ b/src/EditorFeatures/VisualBasicTest/TextStructureNavigation/TextStructureNavigatorTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Test.Utilities.TextStructureNavigation Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.TextStructureNavigation diff --git a/src/EditorFeatures/XunitHook/XunitDisposeHook.cs b/src/EditorFeatures/XunitHook/XunitDisposeHook.cs index 96297521040c6..9aaf36680280e 100644 --- a/src/EditorFeatures/XunitHook/XunitDisposeHook.cs +++ b/src/EditorFeatures/XunitHook/XunitDisposeHook.cs @@ -18,7 +18,7 @@ public void Execute() if (!AppDomain.CurrentDomain.IsDefaultAppDomain()) throw new InvalidOperationException(); - var xunitUtilities = AppDomain.CurrentDomain.GetAssemblies().Where(static assembly => assembly.GetName().Name.StartsWith("xunit.runner.utility")).ToArray(); + var xunitUtilities = AppDomain.CurrentDomain.GetAssemblies().Where(static assembly => assembly.GetName().Name.StartsWith("xunit.runner.visualstudio")).ToArray(); foreach (var xunitUtility in xunitUtilities) { var appDomainManagerType = xunitUtility.GetType("Xunit.AppDomainManager_AppDomain"); diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Binders/EEMethodBinder.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Binders/EEMethodBinder.cs index 67f9abba0ad0d..fd0484f896535 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Binders/EEMethodBinder.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Binders/EEMethodBinder.cs @@ -5,7 +5,6 @@ #nullable disable using System; -using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Binders/PlaceholderLocalBinder.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Binders/PlaceholderLocalBinder.cs index 00f0ac418dc3d..300a4c0568204 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Binders/PlaceholderLocalBinder.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Binders/PlaceholderLocalBinder.cs @@ -5,12 +5,9 @@ #nullable disable using System; -using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; using Microsoft.CodeAnalysis.CSharp.Symbols; -using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; -using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.Debugger.Clr; diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Binders/WithTypeArgumentsBinder.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Binders/WithTypeArgumentsBinder.cs index b52b6a306014d..5fc8abe71e17d 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Binders/WithTypeArgumentsBinder.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Binders/WithTypeArgumentsBinder.cs @@ -4,12 +4,12 @@ #nullable disable -using Microsoft.CodeAnalysis.CSharp.Symbols; -using Roslyn.Utilities; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpFrameDecoder.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpFrameDecoder.cs index 1a5d85860f086..dce04a6b508a8 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpFrameDecoder.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpFrameDecoder.cs @@ -3,10 +3,9 @@ // See the LICENSE file in the project root for more information. using System; -using System.Diagnostics; -using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; +using Microsoft.CodeAnalysis.ExpressionEvaluator; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpInstructionDecoder.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpInstructionDecoder.cs index f401de6dea6b4..803b28610740f 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpInstructionDecoder.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpInstructionDecoder.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpLanguageInstructionDecoder.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpLanguageInstructionDecoder.cs index e6642ecd7a9f6..fd725ab360b54 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpLanguageInstructionDecoder.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpLanguageInstructionDecoder.cs @@ -3,9 +3,9 @@ // See the LICENSE file in the project root for more information. using System; -using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; +using Microsoft.CodeAnalysis.ExpressionEvaluator; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CompilationContext.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CompilationContext.cs index 04af7e975cd94..e0caa15defe77 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CompilationContext.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CompilationContext.cs @@ -2,6 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; @@ -13,13 +20,6 @@ using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Utilities; -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CompilationExtensions.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CompilationExtensions.cs index 226b7413c3c22..6cd007c844751 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CompilationExtensions.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CompilationExtensions.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Diagnostics; diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/EEAssemblyBuilder.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/EEAssemblyBuilder.cs index b0bcd47af9095..fa0b0b9cff9c0 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/EEAssemblyBuilder.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/EEAssemblyBuilder.cs @@ -2,6 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Reflection.Metadata; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; @@ -10,12 +14,6 @@ using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; -using Roslyn.Utilities; -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Diagnostics; -using System.Reflection.Metadata; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Rewriters/CapturedVariableRewriter.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Rewriters/CapturedVariableRewriter.cs index 2b21c8b1bcd58..66e791940b347 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Rewriters/CapturedVariableRewriter.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Rewriters/CapturedVariableRewriter.cs @@ -4,12 +4,11 @@ #nullable disable -using Microsoft.CodeAnalysis.CSharp.Symbols; -using Roslyn.Utilities; -using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Rewriters/LocalDeclarationRewriter.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Rewriters/LocalDeclarationRewriter.cs index 3ea66b14fe8f6..83cf9a18f6d6c 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Rewriters/LocalDeclarationRewriter.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Rewriters/LocalDeclarationRewriter.cs @@ -4,12 +4,12 @@ #nullable disable -using Microsoft.CodeAnalysis.CSharp.Symbols; -using Microsoft.CodeAnalysis.ExpressionEvaluator; -using Microsoft.CodeAnalysis.PooledObjects; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.ExpressionEvaluator; +using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Rewriters/PlaceholderLocalRewriter.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Rewriters/PlaceholderLocalRewriter.cs index 55d10b2326806..0c56945724c0c 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Rewriters/PlaceholderLocalRewriter.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Rewriters/PlaceholderLocalRewriter.cs @@ -4,9 +4,9 @@ #nullable disable -using Microsoft.CodeAnalysis.CSharp.Symbols; using System.Collections.Generic; using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/DisplayClassInstance.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/DisplayClassInstance.cs index 01c0f6d2a3e05..23781feff6177 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/DisplayClassInstance.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/DisplayClassInstance.cs @@ -4,9 +4,9 @@ #nullable disable -using Microsoft.CodeAnalysis.CSharp.Symbols; using System; using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/DisplayClassVariable.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/DisplayClassVariable.cs index 1744b43756706..89fbcefb98436 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/DisplayClassVariable.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/DisplayClassVariable.cs @@ -4,11 +4,11 @@ #nullable disable +using System.Collections.Immutable; +using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; -using System.Collections.Immutable; -using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EECompilationContextMethod.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EECompilationContextMethod.cs index 700958410f360..94e17f080c907 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EECompilationContextMethod.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EECompilationContextMethod.cs @@ -78,6 +78,8 @@ internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree l return _underlyingMethod.GetUnmanagedCallersOnlyAttributeData(forceComplete); } + internal sealed override bool HasSpecialNameAttribute => throw ExceptionUtilities.Unreachable(); + internal override bool IsNullableAnalysisEnabled() { return _underlyingMethod.IsNullableAnalysisEnabled(); diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EEDisplayClassFieldLocalSymbol.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EEDisplayClassFieldLocalSymbol.cs index 9949ab0fa0721..510db73ed0063 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EEDisplayClassFieldLocalSymbol.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EEDisplayClassFieldLocalSymbol.cs @@ -4,10 +4,9 @@ #nullable disable -using Microsoft.CodeAnalysis.CSharp.Symbols; using System.Collections.Immutable; using System.Diagnostics; -using Roslyn.Utilities; +using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EELocalConstantSymbol.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EELocalConstantSymbol.cs index b801c139c6586..ba9747d9dcfeb 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EELocalConstantSymbol.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EELocalConstantSymbol.cs @@ -6,7 +6,6 @@ using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EELocalSymbol.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EELocalSymbol.cs index 82665d5d9ef61..8dd6ed0faa248 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EELocalSymbol.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EELocalSymbol.cs @@ -4,11 +4,9 @@ #nullable disable -using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EELocalSymbolBase.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EELocalSymbolBase.cs index 6322e157e38c8..a6ee54eed3ce0 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EELocalSymbolBase.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EELocalSymbolBase.cs @@ -4,12 +4,10 @@ #nullable disable -using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.CSharp.Symbols; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EEMethodSymbol.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EEMethodSymbol.cs index 5b50a64384805..12f1b49f2f260 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EEMethodSymbol.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EEMethodSymbol.cs @@ -458,6 +458,8 @@ internal override ObsoleteAttributeData ObsoleteAttributeData internal sealed override UnmanagedCallersOnlyAttributeData GetUnmanagedCallersOnlyAttributeData(bool forceComplete) => throw ExceptionUtilities.Unreachable(); + internal sealed override bool HasSpecialNameAttribute => throw ExceptionUtilities.Unreachable(); + internal override bool HasUnscopedRefAttribute => false; internal override bool UseUpdatedEscapeRules => false; diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/ObjectIdLocalSymbol.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/ObjectIdLocalSymbol.cs index 1e343bdf15b89..a85462774c012 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/ObjectIdLocalSymbol.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/ObjectIdLocalSymbol.cs @@ -4,10 +4,9 @@ #nullable disable +using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.ExpressionEvaluator; -using System.Collections.Immutable; -using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/PlaceholderLocalSymbol.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/PlaceholderLocalSymbol.cs index ccb2c046a763f..9742f443e4e94 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/PlaceholderLocalSymbol.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/PlaceholderLocalSymbol.cs @@ -4,7 +4,6 @@ #nullable disable -using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Diagnostics; @@ -13,7 +12,6 @@ using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.Debugger.Clr; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/PlaceholderMethodSymbol.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/PlaceholderMethodSymbol.cs index 96aec08e8669b..1dc43850fcbfb 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/PlaceholderMethodSymbol.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/PlaceholderMethodSymbol.cs @@ -4,12 +4,10 @@ #nullable disable -using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { @@ -218,6 +216,8 @@ internal override ObsoleteAttributeData ObsoleteAttributeData internal sealed override UnmanagedCallersOnlyAttributeData GetUnmanagedCallersOnlyAttributeData(bool forceComplete) => throw ExceptionUtilities.Unreachable(); + internal sealed override bool HasSpecialNameAttribute => throw ExceptionUtilities.Unreachable(); + internal override bool HasUnscopedRefAttribute => false; internal override bool UseUpdatedEscapeRules => false; diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/ReturnValueLocalSymbol.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/ReturnValueLocalSymbol.cs index e58a04ff4bd9b..068a2a4f92cd4 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/ReturnValueLocalSymbol.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/ReturnValueLocalSymbol.cs @@ -4,9 +4,9 @@ #nullable disable +using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.ExpressionEvaluator; -using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/SimpleTypeParameterSymbol.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/SimpleTypeParameterSymbol.cs index 9390a0d2e3459..ec7af0969795f 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/SimpleTypeParameterSymbol.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/SimpleTypeParameterSymbol.cs @@ -4,11 +4,10 @@ #nullable disable -using Microsoft.CodeAnalysis.CSharp.Symbols; -using Roslyn.Utilities; -using System; using System.Collections.Immutable; using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/SynthesizedContextMethodSymbol.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/SynthesizedContextMethodSymbol.cs index 47f0ed0f0b488..1bc9eb96accb1 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/SynthesizedContextMethodSymbol.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/SynthesizedContextMethodSymbol.cs @@ -4,12 +4,10 @@ #nullable disable -using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Reflection; using Microsoft.CodeAnalysis.CSharp.Symbols; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/SyntaxHelpers.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/SyntaxHelpers.cs index 89d7721cd3d96..9db98697d1e0d 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/SyntaxHelpers.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/SyntaxHelpers.cs @@ -2,13 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Text; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator diff --git a/src/ExpressionEvaluator/CSharp/Source/ResultProvider/CSharpFormatter.Values.cs b/src/ExpressionEvaluator/CSharp/Source/ResultProvider/CSharpFormatter.Values.cs index b1f861f6b9fa5..451e9d43f6cca 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ResultProvider/CSharpFormatter.Values.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ResultProvider/CSharpFormatter.Values.cs @@ -4,7 +4,6 @@ #nullable disable -using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Text; diff --git a/src/ExpressionEvaluator/CSharp/Source/ResultProvider/Helpers/TypeExtensions.cs b/src/ExpressionEvaluator/CSharp/Source/ResultProvider/Helpers/TypeExtensions.cs index c9d2aa5ac121b..c932f1cd93247 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ResultProvider/Helpers/TypeExtensions.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ResultProvider/Helpers/TypeExtensions.cs @@ -4,7 +4,6 @@ #nullable disable -using System; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; using TypeCode = Microsoft.VisualStudio.Debugger.Metadata.TypeCode; diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/AccessibilityTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/AccessibilityTests.cs index 126c3bfeeff1a..d4fde92c9efdd 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/AccessibilityTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/AccessibilityTests.cs @@ -4,15 +4,13 @@ #nullable disable +using System; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; -using Microsoft.CodeAnalysis.Test.Utilities; -using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; -using System; -using Xunit; -using Roslyn.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; +using Roslyn.Test.Utilities; +using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/CompileExpressionsTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/CompileExpressionsTests.cs index 29bf1a279a554..b0e9c7f271fcd 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/CompileExpressionsTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/CompileExpressionsTests.cs @@ -6,6 +6,7 @@ using System.Collections.Immutable; using System.Text; +using Basic.Reference.Assemblies; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; @@ -16,7 +17,6 @@ using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using Xunit; -using Basic.Reference.Assemblies; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/DeclarationTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/DeclarationTests.cs index b4e77452a5f52..a1c176bf3602f 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/DeclarationTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/DeclarationTests.cs @@ -5,7 +5,6 @@ #nullable disable using System.Collections.Immutable; -using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/DynamicTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/DynamicTests.cs index d5281c3a50157..a7513a8b447a8 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/DynamicTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/DynamicTests.cs @@ -12,7 +12,6 @@ using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; -using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTestBase.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTestBase.cs index 230bf3926c994..e695e022915dd 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTestBase.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTestBase.cs @@ -8,7 +8,6 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; -using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTests.cs index 5ed458adb7962..66e13233e09f7 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTests.cs @@ -22,9 +22,9 @@ using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.PdbUtilities; -using static Roslyn.Test.Utilities.SigningTestHelpers; using Roslyn.Test.Utilities; using Xunit; +using static Roslyn.Test.Utilities.SigningTestHelpers; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/HoistedStateMachineLocalTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/HoistedStateMachineLocalTests.cs index 8b28a453aa30b..de4daecf727bc 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/HoistedStateMachineLocalTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/HoistedStateMachineLocalTests.cs @@ -4,7 +4,6 @@ #nullable disable -using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/HoistedThisTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/HoistedThisTests.cs index 1cec6a2fd690e..5c8a2b590dd1e 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/HoistedThisTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/HoistedThisTests.cs @@ -5,7 +5,6 @@ #nullable disable using System; -using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/InstructionDecoderTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/InstructionDecoderTests.cs index b08988356335a..36072c26a0aa2 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/InstructionDecoderTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/InstructionDecoderTests.cs @@ -9,9 +9,9 @@ using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; +using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.ExpressionEvaluator; -using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/LocalsTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/LocalsTests.cs index b79db1b87fdbe..32b07ab763234 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/LocalsTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/LocalsTests.cs @@ -4,7 +4,6 @@ #nullable disable -using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/MissingAssemblyTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/MissingAssemblyTests.cs index 2a1b5564ebd61..c9fc47ac7aa58 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/MissingAssemblyTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/MissingAssemblyTests.cs @@ -9,8 +9,8 @@ using System.Collections.ObjectModel; using System.Linq; using System.Runtime.InteropServices; +using Basic.Reference.Assemblies; using Microsoft.CodeAnalysis.CodeGen; -using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.ExpressionEvaluator; @@ -21,7 +21,6 @@ using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; -using Basic.Reference.Assemblies; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/NoPIATests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/NoPIATests.cs index 6be9504318e4c..120197cadeeac 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/NoPIATests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/NoPIATests.cs @@ -4,16 +4,13 @@ #nullable disable -using System; using System.Collections.Immutable; -using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; -using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Xunit; diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/PseudoVariableTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/PseudoVariableTests.cs index 484b08b834f87..7c79f39c8b01e 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/PseudoVariableTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/PseudoVariableTests.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Immutable; -using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; @@ -14,7 +13,6 @@ using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; -using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Xunit; diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ResultPropertiesTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ResultPropertiesTests.cs index dd00fc3579d04..38c973ee201d4 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ResultPropertiesTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ResultPropertiesTests.cs @@ -5,14 +5,12 @@ #nullable disable using System.Collections.Immutable; -using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; -using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Xunit; diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/UsingDebugInfoTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/UsingDebugInfoTests.cs index 1bdf2288df498..123b463aacbbd 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/UsingDebugInfoTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/UsingDebugInfoTests.cs @@ -13,7 +13,6 @@ using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; -using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/WinMdTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/WinMdTests.cs index 28a79165f7940..5cfb40af40711 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/WinMdTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/WinMdTests.cs @@ -16,7 +16,6 @@ using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; -using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; diff --git a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/AccessibilityTests.cs b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/AccessibilityTests.cs index b292523148547..d827e5fc36ec7 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/AccessibilityTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/AccessibilityTests.cs @@ -4,6 +4,7 @@ #nullable disable +using System; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; @@ -11,7 +12,6 @@ using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; -using System; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests diff --git a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/CSharpResultProviderTestBase.cs b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/CSharpResultProviderTestBase.cs index 04c0a3bc59a41..955da442baf9e 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/CSharpResultProviderTestBase.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/CSharpResultProviderTestBase.cs @@ -7,8 +7,8 @@ using System; using System.Collections.Immutable; using System.Reflection; -using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; +using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; diff --git a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/DebuggerTypeProxyAttributeTests.cs b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/DebuggerTypeProxyAttributeTests.cs index 5319c74a5d74f..a5457c566ad6a 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/DebuggerTypeProxyAttributeTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/DebuggerTypeProxyAttributeTests.cs @@ -4,11 +4,11 @@ #nullable disable +using System; +using System.Linq; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; -using System; -using System.Linq; using Roslyn.Test.Utilities; using Xunit; diff --git a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/DynamicViewTests.cs b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/DynamicViewTests.cs index b11864d946b70..f67b94405fdab 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/DynamicViewTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/DynamicViewTests.cs @@ -11,8 +11,8 @@ using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; -using Xunit; using Roslyn.Test.Utilities; +using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { diff --git a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/ExpansionTests.cs b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/ExpansionTests.cs index 39a4a78e4c7c2..37d56c4063ac4 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/ExpansionTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/ExpansionTests.cs @@ -8,7 +8,6 @@ using System.Collections.Immutable; using System.Globalization; using System.Linq; -using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; diff --git a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/FullNameTests.cs b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/FullNameTests.cs index a15ce76b7ccd0..5c020a1e1a0d0 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/FullNameTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/FullNameTests.cs @@ -9,8 +9,8 @@ using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; -using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Clr; +using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using Xunit; diff --git a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/FunctionPointerTests.cs b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/FunctionPointerTests.cs index 3ea3c36009af4..f0112689c4eba 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/FunctionPointerTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/FunctionPointerTests.cs @@ -4,13 +4,13 @@ #nullable disable +using System; +using System.Diagnostics; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Microsoft.VisualStudio.Debugger.Metadata; -using System; -using System.Diagnostics; using Xunit; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; diff --git a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/ObjectFavoritesTests.cs b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/ObjectFavoritesTests.cs index b495734bf50ea..c02a8caf4868d 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/ObjectFavoritesTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/ObjectFavoritesTests.cs @@ -6,20 +6,9 @@ using System; using System.Collections.Generic; -using System.Collections.Immutable; -using System.Globalization; -using System.Linq; -using DiffPlex.Model; -using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator; -using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; -using Microsoft.CodeAnalysis.Test.Utilities; -using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Clr; -using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; -using Microsoft.VisualStudio.Debugger.Symbols; -using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests diff --git a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/ObjectIdTests.cs b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/ObjectIdTests.cs index d807d8f45a3e8..cd965ca4f6c45 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/ObjectIdTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/ObjectIdTests.cs @@ -4,11 +4,11 @@ #nullable disable +using System; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; -using System; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests diff --git a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/TupleTests.cs b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/TupleTests.cs index adb67771ee299..58f1dd4828352 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/TupleTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/TupleTests.cs @@ -4,6 +4,9 @@ #nullable disable +using System; +using System.Collections.Immutable; +using System.Collections.ObjectModel; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; @@ -11,9 +14,6 @@ using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; -using System; -using System.Collections.Immutable; -using System.Collections.ObjectModel; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests diff --git a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/TypeNameFormatterTests.cs b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/TypeNameFormatterTests.cs index 51229aa4fd78a..39e063d5b6d41 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/TypeNameFormatterTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/TypeNameFormatterTests.cs @@ -7,10 +7,8 @@ using System; using System.Collections.Immutable; using System.Collections.ObjectModel; -using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; -using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using Xunit; diff --git a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/TypeVariablesExpansionTests.cs b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/TypeVariablesExpansionTests.cs index 04d54261119cf..4f08ee8df21ab 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/TypeVariablesExpansionTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/TypeVariablesExpansionTests.cs @@ -4,10 +4,10 @@ #nullable disable +using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Evaluation; -using System.Collections.Immutable; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests diff --git a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/AbstractTypeParameterChecker.cs b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/AbstractTypeParameterChecker.cs index 1208527f8aeaf..2b5dd2c626809 100644 --- a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/AbstractTypeParameterChecker.cs +++ b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/AbstractTypeParameterChecker.cs @@ -7,7 +7,6 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/AssemblyReference.cs b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/AssemblyReference.cs index f8fbb15fab163..c0ff44bc82ae8 100644 --- a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/AssemblyReference.cs +++ b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/AssemblyReference.cs @@ -7,7 +7,6 @@ using Microsoft.Cci; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Emit; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/CustomTypeInfo.cs b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/CustomTypeInfo.cs index 06543610ef65c..6cd4efdbb85ef 100644 --- a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/CustomTypeInfo.cs +++ b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/CustomTypeInfo.cs @@ -2,12 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Text; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/DebuggerDiagnosticFormatter.cs b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/DebuggerDiagnosticFormatter.cs index 62deead0c3c22..c5710db4fdb27 100644 --- a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/DebuggerDiagnosticFormatter.cs +++ b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/DebuggerDiagnosticFormatter.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System; -using System.Diagnostics; using System.Globalization; namespace Microsoft.CodeAnalysis.ExpressionEvaluator diff --git a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/DkmUtilities.cs b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/DkmUtilities.cs index 3aa81e301d757..1872ac559b404 100644 --- a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/DkmUtilities.cs +++ b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/DkmUtilities.cs @@ -18,7 +18,6 @@ using Microsoft.VisualStudio.Debugger.Clr.NativeCompilation; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/EEMetadataReferenceResolver.cs b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/EEMetadataReferenceResolver.cs index c2248aeb087fd..66e2705eb6c1a 100644 --- a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/EEMetadataReferenceResolver.cs +++ b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/EEMetadataReferenceResolver.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Collections.Immutable; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/EvaluationContextBase.cs b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/EvaluationContextBase.cs index 72d21b15e0d55..cc096e1740060 100644 --- a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/EvaluationContextBase.cs +++ b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/EvaluationContextBase.cs @@ -6,7 +6,6 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; -using System.Diagnostics; using System.Globalization; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; diff --git a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/LanguageInstructionDecoder.cs b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/LanguageInstructionDecoder.cs index 8e0cc0dc871ea..41b3a77660b4d 100644 --- a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/LanguageInstructionDecoder.cs +++ b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/LanguageInstructionDecoder.cs @@ -8,7 +8,6 @@ using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/LocalAndMethod.cs b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/LocalAndMethod.cs index 33fc314adcc1c..96e18f76705bf 100644 --- a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/LocalAndMethod.cs +++ b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/LocalAndMethod.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using System; using System.Collections.ObjectModel; +using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/MetadataContextId.cs b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/MetadataContextId.cs index b4d15d2bce5f2..3e7b5556e8cba 100644 --- a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/MetadataContextId.cs +++ b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/MetadataContextId.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/PDB/MethodDebugInfo.Native.cs b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/PDB/MethodDebugInfo.Native.cs index 1b22686f04323..532a688679d12 100644 --- a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/PDB/MethodDebugInfo.Native.cs +++ b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/PDB/MethodDebugInfo.Native.cs @@ -290,7 +290,7 @@ private static void ReadCSharpNativeImportsInfo( var importStringGroups = CustomDebugInfoReader.GetCSharpGroupedImportStrings( methodToken, - KeyValuePairUtil.Create(reader, methodVersion), + KeyValuePair.Create(reader, methodVersion), getMethodCustomDebugInfo: (token, arg) => GetCustomDebugInfoBytes(arg.Key, token, arg.Value), getMethodImportStrings: (token, arg) => GetImportStrings(arg.Key, token, arg.Value), externAliasStrings: out externAliasStrings); @@ -525,7 +525,7 @@ private static void ReadVisualBasicImportsDebugInfo( var importStrings = CustomDebugInfoReader.GetVisualBasicImportStrings( methodToken, - KeyValuePairUtil.Create(reader, methodVersion), + KeyValuePair.Create(reader, methodVersion), (token, arg) => GetImportStrings(arg.Key, token, arg.Value)); if (importStrings.IsDefault) diff --git a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/PseudoVariableUtilities.cs b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/PseudoVariableUtilities.cs index f4527d25bd048..264923f3291ca 100644 --- a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/PseudoVariableUtilities.cs +++ b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/PseudoVariableUtilities.cs @@ -2,13 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Microsoft.VisualStudio.Debugger.Clr; -using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; -using Roslyn.Utilities; using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; +using Microsoft.VisualStudio.Debugger.Clr; +using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/Core/Source/FunctionResolver/CSharp/MemberSignatureParser.cs b/src/ExpressionEvaluator/Core/Source/FunctionResolver/CSharp/MemberSignatureParser.cs index bfeffd304ff78..9bc2fce1372dc 100644 --- a/src/ExpressionEvaluator/Core/Source/FunctionResolver/CSharp/MemberSignatureParser.cs +++ b/src/ExpressionEvaluator/Core/Source/FunctionResolver/CSharp/MemberSignatureParser.cs @@ -4,10 +4,10 @@ #nullable disable -using Microsoft.CodeAnalysis.ExpressionEvaluator; using System; using System.Collections.Immutable; using System.Diagnostics; +using Microsoft.CodeAnalysis.ExpressionEvaluator; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/Core/Source/FunctionResolver/CSharp/Scanner.cs b/src/ExpressionEvaluator/Core/Source/FunctionResolver/CSharp/Scanner.cs index 8112faeee6dac..481438d7e5ad5 100644 --- a/src/ExpressionEvaluator/Core/Source/FunctionResolver/CSharp/Scanner.cs +++ b/src/ExpressionEvaluator/Core/Source/FunctionResolver/CSharp/Scanner.cs @@ -4,9 +4,9 @@ #nullable disable -using Roslyn.Utilities; using System; using System.Diagnostics; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/Core/Source/FunctionResolver/FunctionResolver.cs b/src/ExpressionEvaluator/Core/Source/FunctionResolver/FunctionResolver.cs index 0a0ed3c08de17..ffd108526a0b8 100644 --- a/src/ExpressionEvaluator/Core/Source/FunctionResolver/FunctionResolver.cs +++ b/src/ExpressionEvaluator/Core/Source/FunctionResolver/FunctionResolver.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Reflection.Metadata; using Microsoft.CodeAnalysis.Debugging; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Clr; diff --git a/src/ExpressionEvaluator/Core/Source/FunctionResolver/FunctionResolverBase.cs b/src/ExpressionEvaluator/Core/Source/FunctionResolver/FunctionResolverBase.cs index 5cef86cec4264..9969400498db4 100644 --- a/src/ExpressionEvaluator/Core/Source/FunctionResolver/FunctionResolverBase.cs +++ b/src/ExpressionEvaluator/Core/Source/FunctionResolver/FunctionResolverBase.cs @@ -4,10 +4,10 @@ #nullable disable -using Microsoft.VisualStudio.Debugger.Evaluation; using System; using System.Collections.Generic; using System.Reflection.Metadata; +using Microsoft.VisualStudio.Debugger.Evaluation; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/Core/Source/FunctionResolver/MetadataResolver.cs b/src/ExpressionEvaluator/Core/Source/FunctionResolver/MetadataResolver.cs index 136c6fde10840..062b0f33f0fcb 100644 --- a/src/ExpressionEvaluator/Core/Source/FunctionResolver/MetadataResolver.cs +++ b/src/ExpressionEvaluator/Core/Source/FunctionResolver/MetadataResolver.cs @@ -12,7 +12,6 @@ using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CSharp.Symbols; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/Core/Source/FunctionResolver/VisualBasic/MemberSignatureParser.cs b/src/ExpressionEvaluator/Core/Source/FunctionResolver/VisualBasic/MemberSignatureParser.cs index 4afc5040ba008..24375fd60b590 100644 --- a/src/ExpressionEvaluator/Core/Source/FunctionResolver/VisualBasic/MemberSignatureParser.cs +++ b/src/ExpressionEvaluator/Core/Source/FunctionResolver/VisualBasic/MemberSignatureParser.cs @@ -4,10 +4,10 @@ #nullable disable -using Microsoft.CodeAnalysis.ExpressionEvaluator; using System; using System.Collections.Immutable; using System.Diagnostics; +using Microsoft.CodeAnalysis.ExpressionEvaluator; namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/Core/Source/FunctionResolver/VisualBasic/Scanner.cs b/src/ExpressionEvaluator/Core/Source/FunctionResolver/VisualBasic/Scanner.cs index 71103029232a3..70f84e7e2a138 100644 --- a/src/ExpressionEvaluator/Core/Source/FunctionResolver/VisualBasic/Scanner.cs +++ b/src/ExpressionEvaluator/Core/Source/FunctionResolver/VisualBasic/Scanner.cs @@ -4,9 +4,9 @@ #nullable disable -using Roslyn.Utilities; using System; using System.Diagnostics; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/ArrayExpansion.cs b/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/ArrayExpansion.cs index c6328bdaf1277..afdd28f00f290 100644 --- a/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/ArrayExpansion.cs +++ b/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/ArrayExpansion.cs @@ -10,7 +10,6 @@ using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; -using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/DebuggerTypeProxyExpansion.cs b/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/DebuggerTypeProxyExpansion.cs index 06c263daaba69..1ab58547c544f 100644 --- a/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/DebuggerTypeProxyExpansion.cs +++ b/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/DebuggerTypeProxyExpansion.cs @@ -4,10 +4,10 @@ #nullable disable -using Microsoft.VisualStudio.Debugger.Evaluation; -using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using System.Collections.ObjectModel; using System.Diagnostics; +using Microsoft.VisualStudio.Debugger.Evaluation; +using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/DynamicViewExpansion.cs b/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/DynamicViewExpansion.cs index 71f3ed1d888e0..cec05bdf81abd 100644 --- a/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/DynamicViewExpansion.cs +++ b/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/DynamicViewExpansion.cs @@ -4,7 +4,6 @@ #nullable disable -using System; using System.Diagnostics; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; diff --git a/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/MemberExpansion.cs b/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/MemberExpansion.cs index 11db75b2729a3..7028c7151c65f 100644 --- a/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/MemberExpansion.cs +++ b/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/MemberExpansion.cs @@ -13,7 +13,6 @@ using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Microsoft.VisualStudio.Debugger.Metadata; -using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/NativeViewExpansion.cs b/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/NativeViewExpansion.cs index 3affb150ffd7e..a14de18faf620 100644 --- a/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/NativeViewExpansion.cs +++ b/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/NativeViewExpansion.cs @@ -4,10 +4,10 @@ #nullable disable +using System; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; -using System; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/PointerDereferenceExpansion.cs b/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/PointerDereferenceExpansion.cs index b9f0809b50409..2901f476e4554 100644 --- a/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/PointerDereferenceExpansion.cs +++ b/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/PointerDereferenceExpansion.cs @@ -5,7 +5,6 @@ #nullable disable using System.Diagnostics; -using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; diff --git a/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/TupleExpansion.cs b/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/TupleExpansion.cs index 96bc6e7e13e9d..2c514c21fbc15 100644 --- a/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/TupleExpansion.cs +++ b/src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/TupleExpansion.cs @@ -4,15 +4,14 @@ #nullable disable +using System; +using System.Collections.ObjectModel; +using System.Diagnostics; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; -using System; -using System.Collections.ObjectModel; -using System.Diagnostics; using FieldInfo = Microsoft.VisualStudio.Debugger.Metadata.FieldInfo; -using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/Core/Source/ResultProvider/Formatter.cs b/src/ExpressionEvaluator/Core/Source/ResultProvider/Formatter.cs index b8dbb0a3a0ece..79c7d1c7dc132 100644 --- a/src/ExpressionEvaluator/Core/Source/ResultProvider/Formatter.cs +++ b/src/ExpressionEvaluator/Core/Source/ResultProvider/Formatter.cs @@ -11,7 +11,6 @@ using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.MetadataReader; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; diff --git a/src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/ArrayBuilder.cs b/src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/ArrayBuilder.cs index 8a9508f09f541..3d9caa2f8f439 100644 --- a/src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/ArrayBuilder.cs +++ b/src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/ArrayBuilder.cs @@ -10,7 +10,6 @@ using System.Collections.ObjectModel; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { diff --git a/src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/CustomTypeInfoTypeArgumentMap.cs b/src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/CustomTypeInfoTypeArgumentMap.cs index cc1d7ddc53345..eea9f436092a9 100644 --- a/src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/CustomTypeInfoTypeArgumentMap.cs +++ b/src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/CustomTypeInfoTypeArgumentMap.cs @@ -4,10 +4,9 @@ #nullable disable -using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; -using System; using System.Collections.ObjectModel; using System.Diagnostics; +using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator diff --git a/src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/DebuggerDisplayInfo.cs b/src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/DebuggerDisplayInfo.cs index 19657657f5a78..194c1a0b3630e 100644 --- a/src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/DebuggerDisplayInfo.cs +++ b/src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/DebuggerDisplayInfo.cs @@ -4,7 +4,6 @@ #nullable disable -using System; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; diff --git a/src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/FavoritesDataItem.cs b/src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/FavoritesDataItem.cs index 13dc214f09e88..9cd010108eabc 100644 --- a/src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/FavoritesDataItem.cs +++ b/src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/FavoritesDataItem.cs @@ -4,9 +4,6 @@ #nullable disable -using System; -using System.Collections.Generic; -using System.Text; using Microsoft.VisualStudio.Debugger; namespace Microsoft.CodeAnalysis.ExpressionEvaluator diff --git a/src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/TypeHelpers.cs b/src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/TypeHelpers.cs index 8954b47d7eeef..91bf946abbe7c 100644 --- a/src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/TypeHelpers.cs +++ b/src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/TypeHelpers.cs @@ -12,7 +12,6 @@ using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Microsoft.VisualStudio.Debugger.Metadata; -using Roslyn.Utilities; using MethodAttributes = System.Reflection.MethodAttributes; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; using TypeCode = Microsoft.VisualStudio.Debugger.Metadata.TypeCode; diff --git a/src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/ValueHelpers.cs b/src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/ValueHelpers.cs index b46c0b1fb962e..95debf4f92a9f 100644 --- a/src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/ValueHelpers.cs +++ b/src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/ValueHelpers.cs @@ -4,11 +4,11 @@ #nullable disable +using System.Diagnostics; +using System.Text; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; -using System.Diagnostics; -using System.Text; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/Core/Source/ResultProvider/ResultProvider.cs b/src/ExpressionEvaluator/Core/Source/ResultProvider/ResultProvider.cs index 846b5e97b5a00..a3bd70266c3c4 100644 --- a/src/ExpressionEvaluator/Core/Source/ResultProvider/ResultProvider.cs +++ b/src/ExpressionEvaluator/Core/Source/ResultProvider/ResultProvider.cs @@ -17,8 +17,6 @@ using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; -using Microsoft.VisualStudio.Debugger.Metadata; -using Roslyn.Utilities; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator diff --git a/src/ExpressionEvaluator/Core/Test/ExpressionCompiler/ExpressionCompilerTestHelpers.cs b/src/ExpressionEvaluator/Core/Test/ExpressionCompiler/ExpressionCompilerTestHelpers.cs index 03f09c05baa73..074dd5898e66f 100644 --- a/src/ExpressionEvaluator/Core/Test/ExpressionCompiler/ExpressionCompilerTestHelpers.cs +++ b/src/ExpressionEvaluator/Core/Test/ExpressionCompiler/ExpressionCompilerTestHelpers.cs @@ -5,7 +5,6 @@ #nullable disable extern alias PDB; - using System; using System.Collections.Generic; using System.Collections.Immutable; @@ -30,10 +29,10 @@ using Microsoft.Metadata.Tools; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; +using PDB::Roslyn.Test.PdbUtilities; +using PDB::Roslyn.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; -using PDB::Roslyn.Test.Utilities; -using PDB::Roslyn.Test.PdbUtilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { diff --git a/src/ExpressionEvaluator/Core/Test/ExpressionCompiler/NamespaceTypeDefinitionNoBase.cs b/src/ExpressionEvaluator/Core/Test/ExpressionCompiler/NamespaceTypeDefinitionNoBase.cs index 9adcc73fa102b..ca0e3b31c1973 100644 --- a/src/ExpressionEvaluator/Core/Test/ExpressionCompiler/NamespaceTypeDefinitionNoBase.cs +++ b/src/ExpressionEvaluator/Core/Test/ExpressionCompiler/NamespaceTypeDefinitionNoBase.cs @@ -4,11 +4,11 @@ #nullable disable -using Microsoft.Cci; -using Microsoft.CodeAnalysis.Emit; using System.Collections.Generic; using System.Reflection.Metadata; using System.Runtime.InteropServices; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Emit; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { diff --git a/src/ExpressionEvaluator/Core/Test/FunctionResolver/CSharpFunctionResolverTests.cs b/src/ExpressionEvaluator/Core/Test/FunctionResolver/CSharpFunctionResolverTests.cs index f6c57002f47b7..e7447140b96c1 100644 --- a/src/ExpressionEvaluator/Core/Test/FunctionResolver/CSharpFunctionResolverTests.cs +++ b/src/ExpressionEvaluator/Core/Test/FunctionResolver/CSharpFunctionResolverTests.cs @@ -4,13 +4,13 @@ #nullable disable +using System; +using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; -using System; -using System.Collections.Immutable; using Xunit; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests diff --git a/src/ExpressionEvaluator/Core/Test/FunctionResolver/FunctionResolverTestBase.cs b/src/ExpressionEvaluator/Core/Test/FunctionResolver/FunctionResolverTestBase.cs index 0d6f42ef46832..3546c616d7880 100644 --- a/src/ExpressionEvaluator/Core/Test/FunctionResolver/FunctionResolverTestBase.cs +++ b/src/ExpressionEvaluator/Core/Test/FunctionResolver/FunctionResolverTestBase.cs @@ -4,8 +4,6 @@ #nullable disable -using Microsoft.CodeAnalysis.CSharp.Test.Utilities; -using Roslyn.Test.Utilities; using System; using System.Collections.Immutable; using System.Diagnostics; @@ -13,6 +11,8 @@ using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Text; +using Microsoft.CodeAnalysis.CSharp.Test.Utilities; +using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { diff --git a/src/ExpressionEvaluator/Core/Test/FunctionResolver/ParsingTestBase.cs b/src/ExpressionEvaluator/Core/Test/FunctionResolver/ParsingTestBase.cs index cbcafcf0ef785..ac805e36680f5 100644 --- a/src/ExpressionEvaluator/Core/Test/FunctionResolver/ParsingTestBase.cs +++ b/src/ExpressionEvaluator/Core/Test/FunctionResolver/ParsingTestBase.cs @@ -4,10 +4,10 @@ #nullable disable -using Microsoft.CodeAnalysis.CSharp.Test.Utilities; -using Roslyn.Test.Utilities; using System.Collections.Immutable; using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Test.Utilities; +using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests diff --git a/src/ExpressionEvaluator/Core/Test/FunctionResolver/Resolver.cs b/src/ExpressionEvaluator/Core/Test/FunctionResolver/Resolver.cs index 4ca31325e38c5..635200bebd42a 100644 --- a/src/ExpressionEvaluator/Core/Test/FunctionResolver/Resolver.cs +++ b/src/ExpressionEvaluator/Core/Test/FunctionResolver/Resolver.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Generic; -using System.Reflection.Metadata; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { diff --git a/src/ExpressionEvaluator/Core/Test/FunctionResolver/VisualBasicFunctionResolverTests.cs b/src/ExpressionEvaluator/Core/Test/FunctionResolver/VisualBasicFunctionResolverTests.cs index a6034d0894f48..e5999c999fcfc 100644 --- a/src/ExpressionEvaluator/Core/Test/FunctionResolver/VisualBasicFunctionResolverTests.cs +++ b/src/ExpressionEvaluator/Core/Test/FunctionResolver/VisualBasicFunctionResolverTests.cs @@ -4,11 +4,11 @@ #nullable disable +using System; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; -using System; using Xunit; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests diff --git a/src/ExpressionEvaluator/Core/Test/FunctionResolver/VisualBasicParsingTests.cs b/src/ExpressionEvaluator/Core/Test/FunctionResolver/VisualBasicParsingTests.cs index c998701451341..e6789339a83eb 100644 --- a/src/ExpressionEvaluator/Core/Test/FunctionResolver/VisualBasicParsingTests.cs +++ b/src/ExpressionEvaluator/Core/Test/FunctionResolver/VisualBasicParsingTests.cs @@ -4,12 +4,12 @@ #nullable disable -using Microsoft.CodeAnalysis.VisualBasic; -using Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator; -using Roslyn.Test.Utilities; using System; using System.Collections.Immutable; using System.Linq; +using Microsoft.CodeAnalysis.VisualBasic; +using Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator; +using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests diff --git a/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrAppDomain.cs b/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrAppDomain.cs index c687b3bbaa896..29320d20c7e14 100644 --- a/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrAppDomain.cs +++ b/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrAppDomain.cs @@ -11,7 +11,6 @@ using System; using System.Collections.Concurrent; -using System.Collections.Generic; using System.Collections.ObjectModel; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; diff --git a/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrDebuggerVisualizerAttribute.cs b/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrDebuggerVisualizerAttribute.cs index 09a006e0fb304..b104ec7f60ea4 100644 --- a/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrDebuggerVisualizerAttribute.cs +++ b/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrDebuggerVisualizerAttribute.cs @@ -9,8 +9,6 @@ #endregion -using Microsoft.VisualStudio.Debugger.Clr; - namespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation { public class DkmClrDebuggerVisualizerAttribute : DkmClrEvalAttribute diff --git a/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrModuleInstance.cs b/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrModuleInstance.cs index c2153daf539e8..65ec3602ff5e7 100644 --- a/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrModuleInstance.cs +++ b/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrModuleInstance.cs @@ -9,9 +9,6 @@ #endregion -using Microsoft.CodeAnalysis.ExpressionEvaluator; -using Microsoft.MetadataReader; -using Microsoft.VisualStudio.Debugger.Symbols; using System; using System.Collections.ObjectModel; using System.Diagnostics; @@ -20,6 +17,9 @@ using System.Reflection.Adds; using System.Text; using System.Threading; +using Microsoft.CodeAnalysis.ExpressionEvaluator; +using Microsoft.MetadataReader; +using Microsoft.VisualStudio.Debugger.Symbols; namespace Microsoft.VisualStudio.Debugger.Clr { diff --git a/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrObjectFavoritesInfo.cs b/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrObjectFavoritesInfo.cs index b32f966ac0f75..3097fa70d6a8f 100644 --- a/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrObjectFavoritesInfo.cs +++ b/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrObjectFavoritesInfo.cs @@ -9,7 +9,6 @@ #endregion -using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; diff --git a/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrValue.cs b/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrValue.cs index 890aab6f123e4..c76545d9d58c9 100644 --- a/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrValue.cs +++ b/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrValue.cs @@ -14,12 +14,10 @@ using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.Debugger.CallStack; using Microsoft.VisualStudio.Debugger.Clr; -using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Metadata; using Microsoft.VisualStudio.Debugger.Symbols; using Roslyn.Utilities; diff --git a/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmEvaluationResult.cs b/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmEvaluationResult.cs index 666b86cc9bc18..c0887debfef05 100644 --- a/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmEvaluationResult.cs +++ b/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmEvaluationResult.cs @@ -9,7 +9,6 @@ #endregion -using System; using Microsoft.VisualStudio.Debugger.CallStack; namespace Microsoft.VisualStudio.Debugger.Evaluation diff --git a/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmEvaluationResultEnumContext.cs b/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmEvaluationResultEnumContext.cs index 95b99c69d5634..588b979048410 100644 --- a/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmEvaluationResultEnumContext.cs +++ b/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmEvaluationResultEnumContext.cs @@ -9,8 +9,6 @@ #endregion -using System; -using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.CallStack; namespace Microsoft.VisualStudio.Debugger.Evaluation diff --git a/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmILRange.cs b/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmILRange.cs index f410268a4b00b..b68740860872c 100644 --- a/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmILRange.cs +++ b/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmILRange.cs @@ -9,8 +9,6 @@ #endregion -using System; - namespace Microsoft.VisualStudio.Debugger.Clr { public readonly struct DkmILRange diff --git a/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmWorkList.cs b/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmWorkList.cs index 6dfb8b912c05c..76d1940c675c2 100644 --- a/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmWorkList.cs +++ b/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmWorkList.cs @@ -10,7 +10,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; namespace Microsoft.VisualStudio.Debugger { diff --git a/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/IDkmClrFullNameProvider2.cs b/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/IDkmClrFullNameProvider2.cs index 73909819d14b8..d3e923fefbf65 100644 --- a/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/IDkmClrFullNameProvider2.cs +++ b/src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/IDkmClrFullNameProvider2.cs @@ -8,10 +8,8 @@ // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion -using System.Collections.ObjectModel; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; -using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; namespace Microsoft.VisualStudio.Debugger.ComponentInterfaces { diff --git a/src/ExpressionEvaluator/Core/Test/ResultProvider/ReflectionUtilities.cs b/src/ExpressionEvaluator/Core/Test/ResultProvider/ReflectionUtilities.cs index c46088fa8a4c1..174afa506f427 100644 --- a/src/ExpressionEvaluator/Core/Test/ResultProvider/ReflectionUtilities.cs +++ b/src/ExpressionEvaluator/Core/Test/ResultProvider/ReflectionUtilities.cs @@ -4,11 +4,11 @@ #nullable disable -using Microsoft.VisualStudio.Debugger.Clr; using System; using System.Collections.Immutable; using System.Linq; using System.Reflection; +using Microsoft.VisualStudio.Debugger.Clr; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { diff --git a/src/ExpressionEvaluator/Core/Test/ResultProvider/ResultProviderTestBase.cs b/src/ExpressionEvaluator/Core/Test/ResultProvider/ResultProviderTestBase.cs index d7e5c3b99275d..f9057b5dbca56 100644 --- a/src/ExpressionEvaluator/Core/Test/ResultProvider/ResultProviderTestBase.cs +++ b/src/ExpressionEvaluator/Core/Test/ResultProvider/ResultProviderTestBase.cs @@ -5,11 +5,10 @@ #nullable disable using System; -using System.Collections.ObjectModel; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Linq; using System.Runtime.ExceptionServices; -using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Clr; diff --git a/src/ExpressionEvaluator/Package/ExpressionEvaluatorPackage.csproj b/src/ExpressionEvaluator/Package/ExpressionEvaluatorPackage.csproj index b3c6aa8857dac..55d851d019ed0 100644 --- a/src/ExpressionEvaluator/Package/ExpressionEvaluatorPackage.csproj +++ b/src/ExpressionEvaluator/Package/ExpressionEvaluatorPackage.csproj @@ -13,6 +13,7 @@ false $(CommonExtensionInstallationRoot) Microsoft\VBCSharp\ExpressionEvaluators + true Microsoft.CodeAnalysis.LanguageServices diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Binders/ParametersAndLocalsBinder.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Binders/ParametersAndLocalsBinder.vb index 2cf1d15bd2f9f..ef69854406ddd 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Binders/ParametersAndLocalsBinder.vb +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Binders/ParametersAndLocalsBinder.vb @@ -5,7 +5,6 @@ Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend NotInheritable Class ParametersAndLocalsBinder diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Binders/PlaceholderLocalBinder.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Binders/PlaceholderLocalBinder.vb index 8b0ae8c7d9691..8bc63aa44ad95 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Binders/PlaceholderLocalBinder.vb +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Binders/PlaceholderLocalBinder.vb @@ -7,7 +7,6 @@ Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/CompilationContext.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/CompilationContext.vb index b2f78dba09954..bf6e928fbc7d5 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/CompilationContext.vb +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/CompilationContext.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/EEAssemblyBuilder.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/EEAssemblyBuilder.vb index 9a404f842d441..6ee1727e54ffb 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/EEAssemblyBuilder.vb +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/EEAssemblyBuilder.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.Diagnostics Imports System.Reflection.Metadata Imports System.Runtime.InteropServices Imports Microsoft.Cci @@ -16,7 +15,6 @@ Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/EvaluationContext.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/EvaluationContext.vb index 7512de0a950fd..9ec5af56baebd 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/EvaluationContext.vb +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/EvaluationContext.vb @@ -19,7 +19,6 @@ Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.DiaSymReader -Imports Microsoft.VisualStudio.Debugger.Clr Imports Microsoft.VisualStudio.Debugger.Evaluation Imports Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation Imports Roslyn.Utilities diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Rewriters/LocalDeclarationRewriter.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Rewriters/LocalDeclarationRewriter.vb index 7c0b9a9af9400..ca1f414104a11 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Rewriters/LocalDeclarationRewriter.vb +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Rewriters/LocalDeclarationRewriter.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EEDisplayClassFieldLocalSymbol.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EEDisplayClassFieldLocalSymbol.vb index cf44b3ff97f5a..2c2f7ed46836a 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EEDisplayClassFieldLocalSymbol.vb +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EEDisplayClassFieldLocalSymbol.vb @@ -4,7 +4,6 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator ''' diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EELocalConstantSymbol.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EELocalConstantSymbol.vb index 09e815943241b..5e7f3aef77a65 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EELocalConstantSymbol.vb +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EELocalConstantSymbol.vb @@ -3,9 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.Threading Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend NotInheritable Class EELocalConstantSymbol diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EELocalSymbol.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EELocalSymbol.vb index ed14372a1b9d2..054bf9965e1a6 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EELocalSymbol.vb +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EELocalSymbol.vb @@ -4,7 +4,6 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend NotInheritable Class EELocalSymbol diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EELocalSymbolBase.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EELocalSymbolBase.vb index 61fdceacdda52..e69525eca8d6a 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EELocalSymbolBase.vb +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EELocalSymbolBase.vb @@ -5,7 +5,6 @@ Imports System.Collections.Immutable Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend Module LocalSymbolExtensions diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EEStaticLocalSymbol.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EEStaticLocalSymbol.vb index 2d51e5e2da088..16a3066bb1336 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EEStaticLocalSymbol.vb +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EEStaticLocalSymbol.vb @@ -4,7 +4,6 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EETypeParameterSymbol.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EETypeParameterSymbol.vb index a2de7b87fbc9a..6172d674f8c33 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EETypeParameterSymbol.vb +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EETypeParameterSymbol.vb @@ -4,7 +4,6 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend NotInheritable Class EETypeParameterSymbol diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/PlaceholderMethodSymbol.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/PlaceholderMethodSymbol.vb index d9b119605237c..6e8f82983f5ba 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/PlaceholderMethodSymbol.vb +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/PlaceholderMethodSymbol.vb @@ -3,9 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/SimpleTypeParameterSymbol.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/SimpleTypeParameterSymbol.vb index c72350f30684f..d14c5288ea5be 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/SimpleTypeParameterSymbol.vb +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/SimpleTypeParameterSymbol.vb @@ -4,7 +4,6 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator ''' diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/SynthesizedContextMethodSymbol.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/SynthesizedContextMethodSymbol.vb index 874d1a7416993..3e2ed0d846605 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/SynthesizedContextMethodSymbol.vb +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/SynthesizedContextMethodSymbol.vb @@ -4,7 +4,6 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator ''' diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/SyntaxHelpers.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/SyntaxHelpers.vb index 48b1319c59f5c..a575c050bac68 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/SyntaxHelpers.vb +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/SyntaxHelpers.vb @@ -5,7 +5,6 @@ Imports System.Collections.ObjectModel Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices -Imports System.Text Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/VisualBasicEESymbolProvider.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/VisualBasicEESymbolProvider.vb index ad61fb053d091..40ac3450ed5b6 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/VisualBasicEESymbolProvider.vb +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/VisualBasicEESymbolProvider.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System Imports System.Collections.Immutable Imports System.Reflection.Metadata Imports Microsoft.CodeAnalysis.VisualBasic.Symbols diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/VisualBasicExpressionCompiler.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/VisualBasicExpressionCompiler.vb index 899797768e5d8..e897b64efde22 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/VisualBasicExpressionCompiler.vb +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/VisualBasicExpressionCompiler.vb @@ -4,7 +4,6 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.ExpressionEvaluator -Imports Microsoft.VisualStudio.Debugger Imports Microsoft.VisualStudio.Debugger.Clr Imports Microsoft.VisualStudio.Debugger.Evaluation diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ResultProvider/VisualBasicFormatter.vb b/src/ExpressionEvaluator/VisualBasic/Source/ResultProvider/VisualBasicFormatter.vb index 75f3892a1a40d..ad4fb7a6432be 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ResultProvider/VisualBasicFormatter.vb +++ b/src/ExpressionEvaluator/VisualBasic/Source/ResultProvider/VisualBasicFormatter.vb @@ -4,7 +4,6 @@ Imports System.Collections.ObjectModel Imports Microsoft.CodeAnalysis.ExpressionEvaluator -Imports Microsoft.VisualStudio.Debugger.ComponentInterfaces Imports Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation Imports Microsoft.VisualStudio.Debugger.Metadata diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/DteeTests.vb b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/DteeTests.vb index d478ea4e7aeac..0eb11e0d8b843 100644 --- a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/DteeTests.vb +++ b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/DteeTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.IO Imports System.Threading Imports Microsoft.CodeAnalysis.Debugging Imports Microsoft.CodeAnalysis.ExpressionEvaluator @@ -11,7 +10,6 @@ Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests -Imports Roslyn.Test.PdbUtilities Imports Roslyn.Test.Utilities Imports Xunit diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ExpressionCompilerTestBase.vb b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ExpressionCompilerTestBase.vb index dc6c949e11817..d500db1daf113 100644 --- a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ExpressionCompilerTestBase.vb +++ b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ExpressionCompilerTestBase.vb @@ -7,7 +7,6 @@ Imports System.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.ExpressionEvaluator diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ExpressionCompilerTests.vb b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ExpressionCompilerTests.vb index 568aa79b5bdc4..c605d5cf0df2a 100644 --- a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ExpressionCompilerTests.vb +++ b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ExpressionCompilerTests.vb @@ -7,7 +7,6 @@ Imports System.Globalization Imports System.IO Imports System.Threading Imports Microsoft.CodeAnalysis.CodeGen -Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.PooledObjects diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/HoistedMeTests.vb b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/HoistedMeTests.vb index acdf2335b21f6..588b836b3fdf4 100644 --- a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/HoistedMeTests.vb +++ b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/HoistedMeTests.vb @@ -2,15 +2,14 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeGen +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests -Imports Roslyn.Test.PdbUtilities Imports Roslyn.Test.Utilities Imports Xunit diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ImportDebugInfoTests.vb b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ImportDebugInfoTests.vb index e22df1c4db963..03a34032d90a9 100644 --- a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ImportDebugInfoTests.vb +++ b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ImportDebugInfoTests.vb @@ -11,10 +11,8 @@ Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities -Imports Roslyn.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/LocalsTests.vb b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/LocalsTests.vb index 8ed7524cf3bbc..6f4d1fd2da0b3 100644 --- a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/LocalsTests.vb +++ b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/LocalsTests.vb @@ -3,18 +3,18 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.PooledObjects +Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests -Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.Debugger.Evaluation Imports Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation Imports Roslyn.Test.Utilities Imports Xunit -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class LocalsTests diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/MissingAssemblyTests.vb b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/MissingAssemblyTests.vb index 5b6bd8eeb95f3..6aa5b03d50839 100644 --- a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/MissingAssemblyTests.vb +++ b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/MissingAssemblyTests.vb @@ -4,7 +4,9 @@ Imports System.Collections.Immutable Imports System.Reflection +Imports Basic.Reference.Assemblies Imports Microsoft.CodeAnalysis.CodeGen +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.Test.Utilities @@ -14,9 +16,7 @@ Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Microsoft.DiaSymReader Imports Microsoft.VisualStudio.Debugger.Evaluation Imports Roslyn.Test.Utilities -Imports Roslyn.Utilities Imports Xunit -Imports Basic.Reference.Assemblies Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class MissingAssemblyTests diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/PseudoVariableTests.vb b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/PseudoVariableTests.vb index c477e1b7c62e1..85a94b9c778e6 100644 --- a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/PseudoVariableTests.vb +++ b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/PseudoVariableTests.vb @@ -7,12 +7,8 @@ Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests -Imports Microsoft.DiaSymReader -Imports Microsoft.VisualStudio.Debugger.Clr Imports Microsoft.VisualStudio.Debugger.Evaluation -Imports Roslyn.Test.PdbUtilities Imports Roslyn.Test.Utilities Imports Xunit diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ReferencedModulesTests.vb b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ReferencedModulesTests.vb index e2afb96c254f2..2cb5012e8d339 100644 --- a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ReferencedModulesTests.vb +++ b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ReferencedModulesTests.vb @@ -20,7 +20,6 @@ Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Microsoft.DiaSymReader Imports Microsoft.VisualStudio.Debugger.Evaluation -Imports Roslyn.Test.PdbUtilities Imports Roslyn.Test.Utilities Imports Xunit diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ResultPropertiesTests.vb b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ResultPropertiesTests.vb index e9bbe29077ed7..251ff637136a1 100644 --- a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ResultPropertiesTests.vb +++ b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ResultPropertiesTests.vb @@ -9,7 +9,6 @@ Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.VisualStudio.Debugger.Evaluation Imports Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests -Imports Roslyn.Test.PdbUtilities Imports Roslyn.Test.Utilities Imports Xunit diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/ObjectFavoritesTests.vb b/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/ObjectFavoritesTests.vb index 4cb5dbe1459c5..9bc45e2b22535 100644 --- a/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/ObjectFavoritesTests.vb +++ b/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/ObjectFavoritesTests.vb @@ -2,13 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.Immutable -Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.ExpressionEvaluator -Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.Debugger.Clr Imports Microsoft.VisualStudio.Debugger.Evaluation -Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/ResultsViewTests.vb b/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/ResultsViewTests.vb index 53592383950d4..2a6fb9c5038ed 100644 --- a/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/ResultsViewTests.vb +++ b/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/ResultsViewTests.vb @@ -2,10 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports System.Reflection Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.VisualStudio.Debugger.Clr Imports Microsoft.VisualStudio.Debugger.Evaluation -Imports System.Reflection Imports Roslyn.Test.Utilities Imports Xunit diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/TupleTests.vb b/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/TupleTests.vb index a4dc95661a1cc..fe3bf50577e08 100644 --- a/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/TupleTests.vb +++ b/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/TupleTests.vb @@ -2,6 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CSharp Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.Test.Utilities @@ -9,7 +10,6 @@ Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Microsoft.VisualStudio.Debugger.Clr Imports Microsoft.VisualStudio.Debugger.Evaluation Imports Roslyn.Test.Utilities -Imports System.Collections.Immutable Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/TypeNameFormatterTests.vb b/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/TypeNameFormatterTests.vb index 9f22508b87f3c..0351feef684e4 100644 --- a/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/TypeNameFormatterTests.vb +++ b/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/TypeNameFormatterTests.vb @@ -2,14 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System -Imports System.Collections.Generic Imports System.Collections.ObjectModel -Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation Imports Roslyn.Test.Utilities Imports Xunit -Imports Type = Microsoft.VisualStudio.Debugger.Metadata.Type Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/TypeVariablesExpansionTests.vb b/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/TypeVariablesExpansionTests.vb index 370e60fd32502..82a66029c8fe4 100644 --- a/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/TypeVariablesExpansionTests.vb +++ b/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/TypeVariablesExpansionTests.vb @@ -2,10 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Microsoft.VisualStudio.Debugger.Evaluation -Imports System.Collections.Immutable Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/ValueFormatterTests.vb b/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/ValueFormatterTests.vb index 6b6be63e3e109..a14c77d982915 100644 --- a/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/ValueFormatterTests.vb +++ b/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/ValueFormatterTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.VisualStudio.Debugger.Clr Imports Microsoft.VisualStudio.Debugger.Evaluation diff --git a/src/Features/CSharp/Portable/AddImport/CSharpAddImportCodeFixProvider.cs b/src/Features/CSharp/Portable/AddImport/CSharpAddImportCodeFixProvider.cs index 909fa9fd33b53..ef3f133a2e2e8 100644 --- a/src/Features/CSharp/Portable/AddImport/CSharpAddImportCodeFixProvider.cs +++ b/src/Features/CSharp/Portable/AddImport/CSharpAddImportCodeFixProvider.cs @@ -5,6 +5,7 @@ using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; +using System.Linq; using Microsoft.CodeAnalysis.AddImport; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; @@ -155,23 +156,23 @@ internal static class AddImportDiagnosticIds [CS0103, CS0234, CS0246, CS0305, CS0308, CS0122, CS0307, CS0616, CS1580, CS1581, CS8129, IDEDiagnosticIds.UnboundIdentifierId]; public static ImmutableArray FixableDiagnosticIds = - FixableTypeIds.Concat([ - CS1061, - CS1935, - CS1501, - CS1503, - CS1574, - CS1584, - CS1929, - CS1955, - CS0428, - CS7036, - CS0281, - CS4036, - CS1579, - CS8414, - CS8411, - CS8415]); + [.. FixableTypeIds, + CS1061, + CS1935, + CS1501, + CS1503, + CS1574, + CS1584, + CS1929, + CS1955, + CS0428, + CS7036, + CS0281, + CS4036, + CS1579, + CS8414, + CS8411, + CS8415]; } [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.AddImport), Shared] diff --git a/src/Features/CSharp/Portable/BraceCompletion/StringLiteralBraceCompletionService.cs b/src/Features/CSharp/Portable/BraceCompletion/StringLiteralBraceCompletionService.cs index 53c2702692fea..f94cee841cdf3 100644 --- a/src/Features/CSharp/Portable/BraceCompletion/StringLiteralBraceCompletionService.cs +++ b/src/Features/CSharp/Portable/BraceCompletion/StringLiteralBraceCompletionService.cs @@ -5,6 +5,7 @@ using System; using System.Composition; using System.Threading; +using System.Linq; using Microsoft.CodeAnalysis.BraceCompletion; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; diff --git a/src/Features/CSharp/Portable/ChangeSignature/CSharpChangeSignatureService.cs b/src/Features/CSharp/Portable/ChangeSignature/CSharpChangeSignatureService.cs index c3f2f98829936..76e3c2a57e6a5 100644 --- a/src/Features/CSharp/Portable/ChangeSignature/CSharpChangeSignatureService.cs +++ b/src/Features/CSharp/Portable/ChangeSignature/CSharpChangeSignatureService.cs @@ -54,8 +54,7 @@ internal sealed class CSharpChangeSignatureService : AbstractChangeSignatureServ ]; private static readonly ImmutableArray _declarationAndInvocableKinds = - _declarationKinds.Concat( - [ + [.. _declarationKinds, SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression, SyntaxKind.ThisConstructorInitializer, @@ -63,8 +62,7 @@ internal sealed class CSharpChangeSignatureService : AbstractChangeSignatureServ SyntaxKind.ObjectCreationExpression, SyntaxKind.ImplicitObjectCreationExpression, SyntaxKind.Attribute, - SyntaxKind.NameMemberCref, - ]); + SyntaxKind.NameMemberCref]; private static readonly ImmutableArray _updatableAncestorKinds = [ diff --git a/src/Features/CSharp/Portable/CodeRefactorings/EnableNullable/EnableNullableCodeRefactoringProvider.FixAllProvider.cs b/src/Features/CSharp/Portable/CodeRefactorings/EnableNullable/EnableNullableCodeRefactoringProvider.FixAllProvider.cs index 284bc6945b647..d88a6969b117d 100644 --- a/src/Features/CSharp/Portable/CodeRefactorings/EnableNullable/EnableNullableCodeRefactoringProvider.FixAllProvider.cs +++ b/src/Features/CSharp/Portable/CodeRefactorings/EnableNullable/EnableNullableCodeRefactoringProvider.FixAllProvider.cs @@ -57,7 +57,9 @@ private sealed class FixAllCodeAction(Func createChangedSolution(CodeActionPurpose.Apply, progress, cancellationToken), - nameof(CSharpFeaturesResources.Enable_nullable_reference_types_in_solution)) + nameof(CSharpFeaturesResources.Enable_nullable_reference_types_in_solution), + CodeActionPriority.Default, + CodeActionCleanup.Default) { private readonly Func, CancellationToken, Task> _createChangedSolution = createChangedSolution; diff --git a/src/Features/CSharp/Portable/CodeRefactorings/EnableNullable/EnableNullableCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/CodeRefactorings/EnableNullable/EnableNullableCodeRefactoringProvider.cs index 311f5745b401b..631bf1682fce3 100644 --- a/src/Features/CSharp/Portable/CodeRefactorings/EnableNullable/EnableNullableCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/CodeRefactorings/EnableNullable/EnableNullableCodeRefactoringProvider.cs @@ -267,7 +267,9 @@ private sealed class CustomCodeAction( : CodeAction.SolutionChangeAction( CSharpFeaturesResources.Enable_nullable_reference_types_in_project, (progress, cancellationToken) => createChangedSolution(CodeActionPurpose.Apply, progress, cancellationToken), - nameof(CSharpFeaturesResources.Enable_nullable_reference_types_in_project)) + nameof(CSharpFeaturesResources.Enable_nullable_reference_types_in_project), + CodeActionPriority.Default, + CodeActionCleanup.Default) { private readonly Func, CancellationToken, Task> _createChangedSolution = createChangedSolution; diff --git a/src/Features/CSharp/Portable/Completion/CompletionProviders/CrefCompletionProvider.cs b/src/Features/CSharp/Portable/Completion/CompletionProviders/CrefCompletionProvider.cs index f2aebe782dd43..3b7d3e7ac60c6 100644 --- a/src/Features/CSharp/Portable/Completion/CompletionProviders/CrefCompletionProvider.cs +++ b/src/Features/CSharp/Portable/Completion/CompletionProviders/CrefCompletionProvider.cs @@ -75,7 +75,7 @@ public override async Task ProvideCompletionsAsync(CompletionContext context) var text = await document.GetValueTextAsync(cancellationToken).ConfigureAwait(false); var span = GetCompletionItemSpan(text, position); - var serializedOptions = ImmutableArray.Create(KeyValuePairUtil.Create(HideAdvancedMembers, options.MemberDisplayOptions.HideAdvancedMembers.ToString())); + var serializedOptions = ImmutableArray.Create(KeyValuePair.Create(HideAdvancedMembers, options.MemberDisplayOptions.HideAdvancedMembers.ToString())); var items = CreateCompletionItems(semanticModel, symbols, token, position, serializedOptions); diff --git a/src/Features/CSharp/Portable/Completion/CompletionProviders/DeclarationName/DeclarationNameInfo.cs b/src/Features/CSharp/Portable/Completion/CompletionProviders/DeclarationName/DeclarationNameInfo.cs index 5035ebf1054dc..897bc08e1e224 100644 --- a/src/Features/CSharp/Portable/Completion/CompletionProviders/DeclarationName/DeclarationNameInfo.cs +++ b/src/Features/CSharp/Portable/Completion/CompletionProviders/DeclarationName/DeclarationNameInfo.cs @@ -29,9 +29,6 @@ internal readonly struct NameDeclarationInfo( private static readonly ImmutableArray s_propertySyntaxKind = [new SymbolKindOrTypeKind(SymbolKind.Property)]; - - private readonly ImmutableArray _possibleSymbolKinds = possibleSymbolKinds; - public readonly DeclarationModifiers Modifiers = declarationModifiers; public readonly Accessibility? DeclaredAccessibility = accessibility; @@ -39,7 +36,7 @@ internal readonly struct NameDeclarationInfo( public readonly IAliasSymbol? Alias = alias; public readonly ISymbol? Symbol = symbol; - public ImmutableArray PossibleSymbolKinds => _possibleSymbolKinds.NullToEmpty(); + public ImmutableArray PossibleSymbolKinds { get => field.NullToEmpty(); } = possibleSymbolKinds; public static async Task GetDeclarationInfoAsync(Document document, int position, CancellationToken cancellationToken) { @@ -554,7 +551,7 @@ private static ImmutableArray GetPossibleLocalDeclarations private static DeclarationModifiers GetDeclarationModifiers(SyntaxTokenList modifiers) { - var declarationModifiers = new DeclarationModifiers(); + var declarationModifiers = DeclarationModifiers.None; foreach (var modifer in modifiers) { switch (modifer.Kind()) diff --git a/src/Features/CSharp/Portable/Completion/CompletionProviders/DeclarationName/DeclarationNameRecommender.NameGenerator.cs b/src/Features/CSharp/Portable/Completion/CompletionProviders/DeclarationName/DeclarationNameRecommender.NameGenerator.cs index d6e9be675da15..a6f11bb95aabd 100644 --- a/src/Features/CSharp/Portable/Completion/CompletionProviders/DeclarationName/DeclarationNameRecommender.NameGenerator.cs +++ b/src/Features/CSharp/Portable/Completion/CompletionProviders/DeclarationName/DeclarationNameRecommender.NameGenerator.cs @@ -4,6 +4,7 @@ using System.Collections.Immutable; using Humanizer; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; diff --git a/src/Features/CSharp/Portable/Completion/CompletionProviders/DeclarationName/DeclarationNameRecommender.cs b/src/Features/CSharp/Portable/Completion/CompletionProviders/DeclarationName/DeclarationNameRecommender.cs index 264b8429d9e18..17fed3ba63b3f 100644 --- a/src/Features/CSharp/Portable/Completion/CompletionProviders/DeclarationName/DeclarationNameRecommender.cs +++ b/src/Features/CSharp/Portable/Completion/CompletionProviders/DeclarationName/DeclarationNameRecommender.cs @@ -12,6 +12,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeStyle; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; @@ -237,7 +238,7 @@ static void ProcessRules( var modifiers = declarationInfo.Modifiers; foreach (var rule in rules) { - if (rule.SymbolSpecification.AppliesTo(kind, declarationInfo.Modifiers, declarationInfo.DeclaredAccessibility)) + if (rule.SymbolSpecification.AppliesTo(kind, declarationInfo.Modifiers.Modifiers, declarationInfo.DeclaredAccessibility)) { foreach (var baseName in baseNames) { diff --git a/src/Features/CSharp/Portable/Completion/CompletionProviders/ExplicitInterfaceTypeCompletionProvider.cs b/src/Features/CSharp/Portable/Completion/CompletionProviders/ExplicitInterfaceTypeCompletionProvider.cs index d81c1d8f34809..65a62f5b1d49b 100644 --- a/src/Features/CSharp/Portable/Completion/CompletionProviders/ExplicitInterfaceTypeCompletionProvider.cs +++ b/src/Features/CSharp/Portable/Completion/CompletionProviders/ExplicitInterfaceTypeCompletionProvider.cs @@ -8,6 +8,7 @@ using System.Diagnostics; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; diff --git a/src/Features/CSharp/Portable/Completion/CompletionProviders/OperatorsAndIndexer/UnnamedSymbolCompletionProvider_Conversions.cs b/src/Features/CSharp/Portable/Completion/CompletionProviders/OperatorsAndIndexer/UnnamedSymbolCompletionProvider_Conversions.cs index 5e7b87b690ada..b16fac4261e15 100644 --- a/src/Features/CSharp/Portable/Completion/CompletionProviders/OperatorsAndIndexer/UnnamedSymbolCompletionProvider_Conversions.cs +++ b/src/Features/CSharp/Portable/Completion/CompletionProviders/OperatorsAndIndexer/UnnamedSymbolCompletionProvider_Conversions.cs @@ -31,7 +31,7 @@ internal sealed partial class UnnamedSymbolCompletionProvider /// private const string RehydrateName = "Rehydrate"; private static readonly ImmutableArray> s_conversionProperties = - [KeyValuePairUtil.Create(KindName, ConversionKindName)]; + [KeyValuePair.Create(KindName, ConversionKindName)]; // We set conversion items' match priority to "Deprioritize" so completion selects other symbols over it when user starts typing. // e.g. method symbol `Should` should be selected over `(short)` when "sh" is typed. @@ -67,8 +67,8 @@ private static (ImmutableArray symbols, ImmutableArray>.GetInstance(out var builder); builder.AddRange(s_conversionProperties); - builder.Add(KeyValuePairUtil.Create(RehydrateName, RehydrateName)); - builder.Add(KeyValuePairUtil.Create(DocumentationCommentXmlName, conversion.GetDocumentationCommentXml(cancellationToken: context.CancellationToken) ?? "")); + builder.Add(KeyValuePair.Create(RehydrateName, RehydrateName)); + builder.Add(KeyValuePair.Create(DocumentationCommentXmlName, conversion.GetDocumentationCommentXml(cancellationToken: context.CancellationToken) ?? "")); var symbols = ImmutableArray.Create(conversion.ContainingType, conversion.Parameters.First().Type, conversion.ReturnType); return (symbols, builder.ToImmutable()); } diff --git a/src/Features/CSharp/Portable/Completion/CompletionProviders/OperatorsAndIndexer/UnnamedSymbolCompletionProvider_Indexers.cs b/src/Features/CSharp/Portable/Completion/CompletionProviders/OperatorsAndIndexer/UnnamedSymbolCompletionProvider_Indexers.cs index 820325f9cc452..86b76ced0ed51 100644 --- a/src/Features/CSharp/Portable/Completion/CompletionProviders/OperatorsAndIndexer/UnnamedSymbolCompletionProvider_Indexers.cs +++ b/src/Features/CSharp/Portable/Completion/CompletionProviders/OperatorsAndIndexer/UnnamedSymbolCompletionProvider_Indexers.cs @@ -16,7 +16,7 @@ namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers; internal sealed partial class UnnamedSymbolCompletionProvider { private readonly ImmutableArray> IndexerProperties = - [KeyValuePairUtil.Create(KindName, IndexerKindName)]; + [KeyValuePair.Create(KindName, IndexerKindName)]; private void AddIndexers(CompletionContext context, ImmutableArray indexers) { diff --git a/src/Features/CSharp/Portable/Completion/CompletionProviders/OperatorsAndIndexer/UnnamedSymbolCompletionProvider_Operators.cs b/src/Features/CSharp/Portable/Completion/CompletionProviders/OperatorsAndIndexer/UnnamedSymbolCompletionProvider_Operators.cs index 7a05b2bd909f1..5b53ace0876cc 100644 --- a/src/Features/CSharp/Portable/Completion/CompletionProviders/OperatorsAndIndexer/UnnamedSymbolCompletionProvider_Operators.cs +++ b/src/Features/CSharp/Portable/Completion/CompletionProviders/OperatorsAndIndexer/UnnamedSymbolCompletionProvider_Operators.cs @@ -33,7 +33,7 @@ private enum OperatorPosition private readonly string OperatorName = nameof(OperatorName); private readonly ImmutableArray> OperatorProperties = - [KeyValuePairUtil.Create(KindName, OperatorKindName)]; + [KeyValuePair.Create(KindName, OperatorKindName)]; /// /// Ordered in the order we want to display operators in the completion list. @@ -113,7 +113,7 @@ private void AddOperatorGroup(CompletionContext context, string opName, IEnumera symbols: [.. operators], rules: s_operatorRules, contextPosition: context.Position, - properties: [.. OperatorProperties, KeyValuePairUtil.Create(OperatorName, opName)], + properties: [.. OperatorProperties, KeyValuePair.Create(OperatorName, opName)], isComplexTextEdit: true)); } diff --git a/src/Features/CSharp/Portable/Completion/CompletionProviders/PartialTypeCompletionProvider.cs b/src/Features/CSharp/Portable/Completion/CompletionProviders/PartialTypeCompletionProvider.cs index f6caf18cf30ea..e739099a35ba5 100644 --- a/src/Features/CSharp/Portable/Completion/CompletionProviders/PartialTypeCompletionProvider.cs +++ b/src/Features/CSharp/Portable/Completion/CompletionProviders/PartialTypeCompletionProvider.cs @@ -37,9 +37,6 @@ internal sealed partial class PartialTypeCompletionProvider : AbstractPartialTyp SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); - private static readonly SymbolDisplayFormat _symbolFormatWithoutGenerics = - _symbolFormatWithGenerics.WithGenericsOptions(SymbolDisplayGenericsOptions.None); - [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PartialTypeCompletionProvider() @@ -76,7 +73,7 @@ private static bool IsPartialTypeDeclaration(SyntaxNode syntax) => syntax is BaseTypeDeclarationSyntax declarationSyntax && declarationSyntax.Modifiers.Any(SyntaxKind.PartialKeyword); protected override ImmutableArray> GetProperties(INamedTypeSymbol symbol, CSharpSyntaxContext context) - => [KeyValuePairUtil.Create(InsertionTextOnLessThan, symbol.Name.EscapeIdentifier())]; + => [KeyValuePair.Create(InsertionTextOnLessThan, symbol.Name.EscapeIdentifier())]; public override async Task GetTextChangeAsync( Document document, CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) diff --git a/src/Features/CSharp/Portable/Completion/KeywordRecommenders/AbstractSpecialTypePreselectingKeywordRecommender.cs b/src/Features/CSharp/Portable/Completion/KeywordRecommenders/AbstractSpecialTypePreselectingKeywordRecommender.cs index fb2e7e54ca4a6..960a520c6de7c 100644 --- a/src/Features/CSharp/Portable/Completion/KeywordRecommenders/AbstractSpecialTypePreselectingKeywordRecommender.cs +++ b/src/Features/CSharp/Portable/Completion/KeywordRecommenders/AbstractSpecialTypePreselectingKeywordRecommender.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; diff --git a/src/Features/CSharp/Portable/Completion/KeywordRecommenders/RefKeywordRecommender.cs b/src/Features/CSharp/Portable/Completion/KeywordRecommenders/RefKeywordRecommender.cs index 4c938e9c00599..6cf761b505855 100644 --- a/src/Features/CSharp/Portable/Completion/KeywordRecommenders/RefKeywordRecommender.cs +++ b/src/Features/CSharp/Portable/Completion/KeywordRecommenders/RefKeywordRecommender.cs @@ -2,13 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; -using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; -using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders; diff --git a/src/Features/CSharp/Portable/Completion/KeywordRecommenders/StringKeywordRecommender.cs b/src/Features/CSharp/Portable/Completion/KeywordRecommenders/StringKeywordRecommender.cs index 551d43ddc299a..dec0ac71db8d5 100644 --- a/src/Features/CSharp/Portable/Completion/KeywordRecommenders/StringKeywordRecommender.cs +++ b/src/Features/CSharp/Portable/Completion/KeywordRecommenders/StringKeywordRecommender.cs @@ -3,9 +3,9 @@ // See the LICENSE file in the project root for more information. using System.Threading; -using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; +using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; diff --git a/src/Features/CSharp/Portable/Completion/KeywordRecommenders/StructKeywordRecommender.cs b/src/Features/CSharp/Portable/Completion/KeywordRecommenders/StructKeywordRecommender.cs index 20e7d957579a7..622c6424c2204 100644 --- a/src/Features/CSharp/Portable/Completion/KeywordRecommenders/StructKeywordRecommender.cs +++ b/src/Features/CSharp/Portable/Completion/KeywordRecommenders/StructKeywordRecommender.cs @@ -5,8 +5,8 @@ using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; -using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.CSharp.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders; diff --git a/src/Features/CSharp/Portable/Completion/KeywordRecommenders/ThisKeywordRecommender.cs b/src/Features/CSharp/Portable/Completion/KeywordRecommenders/ThisKeywordRecommender.cs index 771d543c67d29..e0329cf9006e0 100644 --- a/src/Features/CSharp/Portable/Completion/KeywordRecommenders/ThisKeywordRecommender.cs +++ b/src/Features/CSharp/Portable/Completion/KeywordRecommenders/ThisKeywordRecommender.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; diff --git a/src/Features/CSharp/Portable/ConvertAutoPropertyToFullProperty/CSharpConvertAutoPropertyToFullPropertyCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/ConvertAutoPropertyToFullProperty/CSharpConvertAutoPropertyToFullPropertyCodeRefactoringProvider.cs index 5cb11e73a8cf6..5813ae1ab1a74 100644 --- a/src/Features/CSharp/Portable/ConvertAutoPropertyToFullProperty/CSharpConvertAutoPropertyToFullPropertyCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/ConvertAutoPropertyToFullProperty/CSharpConvertAutoPropertyToFullPropertyCodeRefactoringProvider.cs @@ -37,7 +37,7 @@ protected override async Task GetFieldNameAsync(Document document, IProp { var rule = await document.GetApplicableNamingRuleAsync( new SymbolSpecification.SymbolKindOrTypeKind(SymbolKind.Field), - property.IsStatic ? DeclarationModifiers.Static : DeclarationModifiers.None, + property.IsStatic ? Modifiers.Static : Modifiers.None, Accessibility.Private, cancellationToken).ConfigureAwait(false); diff --git a/src/Features/CSharp/Portable/ConvertIfToSwitch/CSharpConvertIfToSwitchCodeRefactoringProvider.Rewriting.cs b/src/Features/CSharp/Portable/ConvertIfToSwitch/CSharpConvertIfToSwitchCodeRefactoringProvider.Rewriting.cs index fbf6694b316ba..b244a54ebf846 100644 --- a/src/Features/CSharp/Portable/ConvertIfToSwitch/CSharpConvertIfToSwitchCodeRefactoringProvider.Rewriting.cs +++ b/src/Features/CSharp/Portable/ConvertIfToSwitch/CSharpConvertIfToSwitchCodeRefactoringProvider.Rewriting.cs @@ -19,7 +19,7 @@ namespace Microsoft.CodeAnalysis.CSharp.ConvertIfToSwitch; internal sealed partial class CSharpConvertIfToSwitchCodeRefactoringProvider { - private static readonly Dictionary s_operatorMap = new Dictionary + private static readonly Dictionary s_operatorMap = new() { { BinaryOperatorKind.LessThan, SyntaxKind.LessThanToken }, { BinaryOperatorKind.GreaterThan, SyntaxKind.GreaterThanToken }, @@ -27,13 +27,12 @@ internal sealed partial class CSharpConvertIfToSwitchCodeRefactoringProvider { BinaryOperatorKind.GreaterThanOrEqual, SyntaxKind.GreaterThanEqualsToken }, }; - public override SyntaxNode CreateSwitchExpressionStatement(SyntaxNode target, ImmutableArray sections, Feature feature) - { - return ReturnStatement( + public override SyntaxNode CreateSwitchExpressionStatement( + ExpressionSyntax target, ImmutableArray sections, Feature feature) + => ReturnStatement( SwitchExpression( - (ExpressionSyntax)target, + target, [.. sections.Select(section => AsSwitchExpressionArmSyntax(section, feature))])); - } private static SwitchExpressionArmSyntax AsSwitchExpressionArmSyntax(AnalyzedSwitchSection section, Feature feature) { @@ -59,23 +58,24 @@ private static SwitchExpressionArmSyntax AsSwitchExpressionArmSyntax(AnalyzedSwi private static ExpressionSyntax AsExpressionSyntax(IOperation operation) => operation switch { - IReturnOperation { ReturnedValue: { } value } => (ExpressionSyntax)value.Syntax, - IThrowOperation { Exception: { } exception } => ThrowExpression((ExpressionSyntax)exception.Syntax), - IBlockOperation op => AsExpressionSyntax(op.Operations.Single()), + IReturnOperation { ReturnedValue.Syntax: ExpressionSyntax value } => value, + IThrowOperation { Exception.Syntax: ExpressionSyntax exception } => ThrowExpression(exception), + IBlockOperation { Operations: [var op] } => AsExpressionSyntax(op), var v => throw ExceptionUtilities.UnexpectedValue(v.Kind) }; - public override SyntaxNode CreateSwitchStatement(IfStatementSyntax ifStatement, SyntaxNode expression, IEnumerable sectionList) + public override SyntaxNode CreateSwitchStatement( + IfStatementSyntax ifStatement, ExpressionSyntax expression, IEnumerable sectionList) { var block = ifStatement.Statement as BlockSyntax; return SwitchStatement( - switchKeyword: SwitchKeyword.WithTriviaFrom(ifStatement.IfKeyword), - openParenToken: ifStatement.OpenParenToken, - expression: (ExpressionSyntax)expression, - closeParenToken: ifStatement.CloseParenToken.WithPrependedLeadingTrivia(ElasticMarker), - openBraceToken: block?.OpenBraceToken ?? OpenBraceToken, - sections: [.. sectionList.Cast()], - closeBraceToken: block?.CloseBraceToken.WithoutLeadingTrivia() ?? CloseBraceToken); + SwitchKeyword.WithTriviaFrom(ifStatement.IfKeyword), + ifStatement.OpenParenToken, + expression, + ifStatement.CloseParenToken.WithPrependedLeadingTrivia(ElasticMarker), + block?.OpenBraceToken ?? OpenBraceToken, + [.. sectionList.Cast()], + block?.CloseBraceToken.WithoutLeadingTrivia() ?? CloseBraceToken); } private static WhenClauseSyntax? AsWhenClause(AnalyzedSwitchLabel label) diff --git a/src/Features/CSharp/Portable/ConvertLinq/CSharpConvertLinqQueryToForEachProvider.cs b/src/Features/CSharp/Portable/ConvertLinq/CSharpConvertLinqQueryToForEachProvider.cs index 0babb22fbf6a6..b200a250d3aa4 100644 --- a/src/Features/CSharp/Portable/ConvertLinq/CSharpConvertLinqQueryToForEachProvider.cs +++ b/src/Features/CSharp/Portable/ConvertLinq/CSharpConvertLinqQueryToForEachProvider.cs @@ -760,8 +760,7 @@ private bool TryConvertIfInReturnStatement( // } // // yield break; - var statements = GenerateStatements((ExpressionSyntax expression) - => YieldStatement(SyntaxKind.YieldReturnStatement, expression), queryExpressionProcessingInfo); + var statements = GenerateStatements(expression => YieldStatement(SyntaxKind.YieldReturnStatement, expression), queryExpressionProcessingInfo); // add an yield break to avoid throws after the return. var yieldBreakStatement = YieldStatement(SyntaxKind.YieldBreakStatement); diff --git a/src/Features/CSharp/Portable/ConvertLinq/ConvertForEachToLinqQuery/ToToListConverter.cs b/src/Features/CSharp/Portable/ConvertLinq/ConvertForEachToLinqQuery/ToToListConverter.cs index 5785807a26f2f..234c5ba672848 100644 --- a/src/Features/CSharp/Portable/ConvertLinq/ConvertForEachToLinqQuery/ToToListConverter.cs +++ b/src/Features/CSharp/Portable/ConvertLinq/ConvertForEachToLinqQuery/ToToListConverter.cs @@ -49,6 +49,6 @@ protected override StatementSyntax CreateDefaultStatement(ExpressionSyntax query SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, expression, - SyntaxFactory.IdentifierName(nameof(List.AddRange))), + SyntaxFactory.IdentifierName(nameof(List<>.AddRange))), SyntaxFactory.ArgumentList([SyntaxFactory.Argument(queryOrLinqInvocationExpression)]))); } diff --git a/src/Features/CSharp/Portable/ConvertPrimaryToRegularConstructor/ConvertPrimaryToRegularConstructorCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/ConvertPrimaryToRegularConstructor/ConvertPrimaryToRegularConstructorCodeRefactoringProvider.cs index 77b1e7e32d0b6..af236d25f72fd 100644 --- a/src/Features/CSharp/Portable/ConvertPrimaryToRegularConstructor/ConvertPrimaryToRegularConstructorCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/ConvertPrimaryToRegularConstructor/ConvertPrimaryToRegularConstructorCodeRefactoringProvider.cs @@ -12,6 +12,7 @@ using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CodeRefactorings; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; @@ -84,7 +85,7 @@ private static async Task ConvertAsync( // The naming rule we need to follow if we synthesize new private fields. var fieldNameRule = await document.GetApplicableNamingRuleAsync( new SymbolSpecification.SymbolKindOrTypeKind(SymbolKind.Field), - DeclarationModifiers.None, + Modifiers.None, Accessibility.Private, cancellationToken).ConfigureAwait(false); @@ -119,7 +120,7 @@ private static async Task ConvertAsync( RemovePrimaryConstructorParameterList(); RemovePrimaryConstructorBaseTypeArgumentList(); RemovePrimaryConstructorTargetingAttributes(); - RemoveDirectFieldAndPropertyAssignments(); + await RemoveDirectFieldAndPropertyAssignmentsAsync().ConfigureAwait(false); AddNewFields(); AddConstructorDeclaration(); await RewritePrimaryConstructorParameterReferencesAsync().ConfigureAwait(false); @@ -265,14 +266,16 @@ void RemovePrimaryConstructorTargetingAttributes() mainDocumentEditor.RemoveNode(attributeList); } - void RemoveDirectFieldAndPropertyAssignments() + async Task RemoveDirectFieldAndPropertyAssignmentsAsync() { // Remove all the initializers from existing fields/props the params are assigned to. foreach (var (_, initializer) in initializedFieldsAndProperties) { + var editor = await solutionEditor.GetDocumentEditorAsync(solution.GetDocumentId(initializer.SyntaxTree), cancellationToken).ConfigureAwait(false); + if (initializer.Parent is PropertyDeclarationSyntax propertyDeclaration) { - mainDocumentEditor.ReplaceNode( + editor.ReplaceNode( propertyDeclaration, propertyDeclaration .WithInitializer(null) @@ -281,7 +284,7 @@ void RemoveDirectFieldAndPropertyAssignments() } else if (initializer.Parent is VariableDeclaratorSyntax) { - mainDocumentEditor.RemoveNode(initializer); + editor.RemoveNode(initializer); } else { @@ -468,14 +471,17 @@ ConstructorDeclarationSyntax CreateConstructorDeclaration() assignmentStatements.Add(ExpressionStatement(assignment)); } - // Next, actually assign to all the fields/properties that were previously referencing any primary - // constructor parameters. - foreach (var (fieldOrProperty, initializer) in initializedFieldsAndProperties.OrderBy(i => i.initializer.SpanStart)) + // Next, actually assign to all the fields/properties that were previously referencing any primary constructor parameters. + // Chunk assignments by declarations they are in starting from the declaration with the primary constructor + foreach (var location in namedType.Locations.OrderBy(l => !ReferenceEquals(l.SourceTree, typeDeclaration.SyntaxTree))) { - var left = MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, ThisExpression(), fieldOrProperty.Name.ToIdentifierName()) - .WithAdditionalAnnotations(Simplifier.Annotation); - var assignment = AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, left, initializer.EqualsToken, initializer.Value); - assignmentStatements.Add(ExpressionStatement(assignment)); + foreach (var (fieldOrProperty, initializer) in initializedFieldsAndProperties.Where(i => ReferenceEquals(i.initializer.SyntaxTree, location.SourceTree)).OrderBy(i => i.initializer.SpanStart)) + { + var left = MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, ThisExpression(), fieldOrProperty.Name.ToIdentifierName()) + .WithAdditionalAnnotations(Simplifier.Annotation); + var assignment = AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, left, initializer.EqualsToken, initializer.Value); + assignmentStatements.Add(ExpressionStatement(assignment)); + } } var rewrittenParameters = parameterList.ReplaceNodes( diff --git a/src/Features/CSharp/Portable/ConvertProgram/ConvertProgramTransform_TopLevelStatements.cs b/src/Features/CSharp/Portable/ConvertProgram/ConvertProgramTransform_TopLevelStatements.cs index 384f28f7892ea..417e32ed5203a 100644 --- a/src/Features/CSharp/Portable/ConvertProgram/ConvertProgramTransform_TopLevelStatements.cs +++ b/src/Features/CSharp/Portable/ConvertProgram/ConvertProgramTransform_TopLevelStatements.cs @@ -17,6 +17,7 @@ using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.RemoveUnnecessaryImports; +using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; @@ -33,7 +34,7 @@ public static async Task ConvertToTopLevelStatementsAsync( Contract.ThrowIfNull(typeDeclaration); // checked by analyzer var generator = document.GetRequiredLanguageService(); - var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + var root = (CompilationUnitSyntax)await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var rootWithGlobalStatements = GetRootWithGlobalStatements( @@ -97,7 +98,7 @@ private static void AddUsingDirectives(NameSyntax name, SyntaxAnnotation annotat private static SyntaxNode GetRootWithGlobalStatements( SemanticModel semanticModel, SyntaxGenerator generator, - SyntaxNode root, + CompilationUnitSyntax root, TypeDeclarationSyntax typeDeclaration, MethodDeclarationSyntax methodDeclaration, CancellationToken cancellationToken) @@ -107,19 +108,17 @@ private static SyntaxNode GetRootWithGlobalStatements( semanticModel, typeDeclaration, methodDeclaration, cancellationToken); var namespaceDeclaration = typeDeclaration.Parent as BaseNamespaceDeclarationSyntax; + if (namespaceDeclaration != null && namespaceDeclaration.Members.Count >= 2) { // Our parent namespace has another symbol in it. Keep the namespace declaration around, removing only // the existing Program type from it. editor.RemoveNode(typeDeclaration); - editor.ReplaceNode( - root, - (current, _) => - { - var currentRoot = (CompilationUnitSyntax)current; - return currentRoot.WithMembers(currentRoot.Members.InsertRange(0, globalStatements)); - }); + editor.InsertBefore(namespaceDeclaration, globalStatements); + + // We want to place the trailing directive on the namespace declaration we're preceding. + AddDirectivesToNextMemberOrEndOfFile(root.Members.IndexOf(namespaceDeclaration)); } else if (namespaceDeclaration != null) { @@ -136,18 +135,60 @@ private static SyntaxNode GetRootWithGlobalStatements( globalStatements[0].WithPrependedLeadingTrivia(fileBanner)); } - editor.ReplaceNode( - root, - root.ReplaceNode(namespaceDeclaration, globalStatements)); + editor.ReplaceNode(namespaceDeclaration, (_, _) => globalStatements); + + // We're removing the namespace itself. So we want to place the trailing directive on the element that follows that. + AddDirectivesToNextMemberOrEndOfFile(root.Members.IndexOf(namespaceDeclaration) + 1); } else { // type wasn't in a namespace. just remove the type and replace it with the new global statements. - editor.ReplaceNode( - root, root.ReplaceNode(typeDeclaration, globalStatements)); + editor.ReplaceNode(typeDeclaration, (_, _) => globalStatements); + + // We're removing the namespace itself. So we want to place the trailing directive on the element that follows that. + AddDirectivesToNextMemberOrEndOfFile(root.Members.IndexOf(typeDeclaration) + 1); } return editor.GetChangedRoot(); + + void AddDirectivesToNextMemberOrEndOfFile(int memberIndexToPlaceTrailingDirectivesOn) + { + // If the method has trailing directive on the close brace, move them to whatever will come after the + // final global statement in the new file. That could be the next namespace/type member declaration. Or + // it could be the end of file token if there are no more members in the file. + if (methodDeclaration.Body is not BlockSyntax block) + return; + + var leadingCloseBraceTrivia = block.CloseBraceToken.LeadingTrivia; + if (!leadingCloseBraceTrivia.Any(t => t.IsDirective)) + return; + + if (memberIndexToPlaceTrailingDirectivesOn < root.Members.Count) + { + editor.ReplaceNode( + root.Members[memberIndexToPlaceTrailingDirectivesOn], + (current, _) => + { + var updated = current.WithPrependedLeadingTrivia(leadingCloseBraceTrivia); + updated = updated.ReplaceToken( + updated.GetFirstToken(), + updated.GetFirstToken().WithAdditionalAnnotations(Formatter.Annotation)); + return updated; + }); + } + else + { + editor.ReplaceNode( + root, + (current, _) => + { + var currentRoot = (CompilationUnitSyntax)current; + return currentRoot.WithEndOfFileToken(currentRoot.EndOfFileToken + .WithPrependedLeadingTrivia(leadingCloseBraceTrivia) + .WithAdditionalAnnotations(Formatter.Annotation)); + }); + } + } } private static ImmutableArray GetGlobalStatements( diff --git a/src/Features/CSharp/Portable/ConvertToExtension/ConvertToExtensionCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/ConvertToExtension/ConvertToExtensionCodeRefactoringProvider.cs index f6ff6eb35cc54..3d3799a1b186f 100644 --- a/src/Features/CSharp/Portable/ConvertToExtension/ConvertToExtensionCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/ConvertToExtension/ConvertToExtensionCodeRefactoringProvider.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; diff --git a/src/Features/CSharp/Portable/ConvertToExtension/ExtensionMethodEqualityComparer.cs b/src/Features/CSharp/Portable/ConvertToExtension/ExtensionMethodEqualityComparer.cs index f7a5fbc065bf1..879545a84e538 100644 --- a/src/Features/CSharp/Portable/ConvertToExtension/ExtensionMethodEqualityComparer.cs +++ b/src/Features/CSharp/Portable/ConvertToExtension/ExtensionMethodEqualityComparer.cs @@ -7,8 +7,8 @@ using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; -using Roslyn.Utilities; using Microsoft.CodeAnalysis.Shared.Utilities; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ConvertToExtension; diff --git a/src/Features/CSharp/Portable/ConvertToRawString/ConvertStringToRawStringCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/ConvertToRawString/ConvertStringToRawStringCodeRefactoringProvider.cs index f5ed7832fd664..a4c11272512ad 100644 --- a/src/Features/CSharp/Portable/ConvertToRawString/ConvertStringToRawStringCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/ConvertToRawString/ConvertStringToRawStringCodeRefactoringProvider.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; @@ -16,6 +17,7 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; +using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; @@ -36,10 +38,13 @@ static ConvertStringToRawStringCodeRefactoringProvider() s_kindToEquivalenceKeyMap[i] = i.ToString(CultureInfo.InvariantCulture); } - private static readonly ImmutableArray s_convertStringProviders = [ConvertRegularStringToRawStringProvider.Instance, ConvertInterpolatedStringToRawStringProvider.Instance]; + private static readonly ImmutableArray s_convertStringProviders = + [ConvertRegularStringToRawStringProvider.Instance, ConvertInterpolatedStringToRawStringProvider.Instance]; protected override ImmutableArray SupportedFixAllScopes => AllFixAllScopes; + protected override CodeActionCleanup Cleanup => CodeActionCleanup.SyntaxOnly; + private static bool CanConvert( ParsedDocument parsedDocument, ExpressionSyntax expression, @@ -148,6 +153,8 @@ protected override async Task FixAllAsync( var formattingOptions = await document.GetSyntaxFormattingOptionsAsync(cancellationToken).ConfigureAwait(false); var parsedDocument = await ParsedDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false); + using var _ = PooledDictionary.GetInstance(out var expressionToProvider); + foreach (var fixSpan in fixAllSpans) { var node = editor.OriginalRoot.FindNode(fixSpan); @@ -180,19 +187,29 @@ protected override async Task FixAllAsync( if (!hasMatchingKind) continue; - editor.ReplaceNode( - expression, - (current, _) => - { - if (current is not ExpressionSyntax currentExpression) - return current; - - var currentParsedDocument = parsedDocument.WithChangedRoot( - currentExpression.SyntaxTree.GetRoot(cancellationToken), cancellationToken); - var replacement = provider.Convert(currentParsedDocument, currentExpression, kind, formattingOptions, cancellationToken); - return replacement; - }); + expressionToProvider[expression] = provider; } } + + foreach (var (expression, provider) in expressionToProvider) + { + // Don't update a string if we're updating a parent string around it. We may not be able to find + // it if we've already updated the parent string. + if (expression.Ancestors().OfType().Any(static (e, expressionToProvider) => expressionToProvider.ContainsKey(e), expressionToProvider)) + continue; + + editor.ReplaceNode( + expression, + (current, _) => + { + if (current is not ExpressionSyntax currentExpression) + return current; + + var currentParsedDocument = parsedDocument.WithChangedRoot( + currentExpression.SyntaxTree.GetRoot(cancellationToken), cancellationToken); + var replacement = provider.Convert(currentParsedDocument, currentExpression, kind, formattingOptions, cancellationToken); + return replacement; + }); + } } } diff --git a/src/Features/CSharp/Portable/Debugging/BreakpointResolver.cs b/src/Features/CSharp/Portable/Debugging/BreakpointResolver.cs index 89ad28813503f..dfaabb2e76058 100644 --- a/src/Features/CSharp/Portable/Debugging/BreakpointResolver.cs +++ b/src/Features/CSharp/Portable/Debugging/BreakpointResolver.cs @@ -11,8 +11,8 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Debugging; +using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Debugging; diff --git a/src/Features/CSharp/Portable/Debugging/CSharpProximityExpressionsService.cs b/src/Features/CSharp/Portable/Debugging/CSharpProximityExpressionsService.cs index 9f5f41d83e345..505fec53af9e3 100644 --- a/src/Features/CSharp/Portable/Debugging/CSharpProximityExpressionsService.cs +++ b/src/Features/CSharp/Portable/Debugging/CSharpProximityExpressionsService.cs @@ -103,10 +103,6 @@ public async Task> GetProximityExpressionsAsync( public static IList GetProximityExpressions(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) => new Worker(syntaxTree, position).Do(cancellationToken); - [Obsolete($"Use {nameof(GetProximityExpressions)}.")] - private static IList Do(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) - => new Worker(syntaxTree, position).Do(cancellationToken); - private static void AddRelevantExpressions( StatementSyntax statement, IList expressions, diff --git a/src/Features/CSharp/Portable/DocumentationComments/CSharpDocumentationCommentSnippetService.cs b/src/Features/CSharp/Portable/DocumentationComments/CSharpDocumentationCommentSnippetService.cs index 1c58cabad0796..f55a22d08e247 100644 --- a/src/Features/CSharp/Portable/DocumentationComments/CSharpDocumentationCommentSnippetService.cs +++ b/src/Features/CSharp/Portable/DocumentationComments/CSharpDocumentationCommentSnippetService.cs @@ -4,10 +4,11 @@ using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Composition; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; -using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DocumentationComments; @@ -15,7 +16,6 @@ using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; -using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp.DocumentationComments; diff --git a/src/Features/CSharp/Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs b/src/Features/CSharp/Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs index 4156166936372..9794ced6bf2ff 100644 --- a/src/Features/CSharp/Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs +++ b/src/Features/CSharp/Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs @@ -11,14 +11,13 @@ using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Host.Mef; -using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; @@ -2678,14 +2677,14 @@ protected override TextSpan GetExceptionHandlingRegion(SyntaxNode node, out bool tryStatement = (TryStatementSyntax)node; coversAllChildren = false; - if (tryStatement.Catches.Count == 0) + if (tryStatement.Catches is not [var firstCatch, ..]) { RoslynDebug.Assert(tryStatement.Finally != null); return tryStatement.Finally.Span; } return TextSpan.FromBounds( - tryStatement.Catches.First().SpanStart, + firstCatch.SpanStart, (tryStatement.Finally != null) ? tryStatement.Finally.Span.End : tryStatement.Catches.Last().Span.End); diff --git a/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/CSharpLambdaBody.cs b/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/CSharpLambdaBody.cs index a08875d79f112..07f38101be329 100644 --- a/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/CSharpLambdaBody.cs +++ b/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/CSharpLambdaBody.cs @@ -6,6 +6,7 @@ using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.EditAndContinue; using Roslyn.Utilities; diff --git a/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/CopyConstructorDeclarationBody.cs b/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/CopyConstructorDeclarationBody.cs index cd35b66e55c17..8f9364919581c 100644 --- a/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/CopyConstructorDeclarationBody.cs +++ b/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/CopyConstructorDeclarationBody.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/FieldWithInitializerDeclarationBody.cs b/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/FieldWithInitializerDeclarationBody.cs index 70a19e2f26e7c..c55766313e83c 100644 --- a/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/FieldWithInitializerDeclarationBody.cs +++ b/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/FieldWithInitializerDeclarationBody.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.EditAndContinue; diff --git a/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/OrdinaryInstanceConstructorDeclarationBody.cs b/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/OrdinaryInstanceConstructorDeclarationBody.cs index f3590a16e6d8e..405018dabe1e0 100644 --- a/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/OrdinaryInstanceConstructorDeclarationBody.cs +++ b/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/OrdinaryInstanceConstructorDeclarationBody.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; diff --git a/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/PrimaryConstructorDeclarationBody.cs b/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/PrimaryConstructorDeclarationBody.cs index a787c962a23c0..425941a9a3e8a 100644 --- a/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/PrimaryConstructorDeclarationBody.cs +++ b/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/PrimaryConstructorDeclarationBody.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/PropertyOrIndexerAccessorDeclarationBody.cs b/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/PropertyOrIndexerAccessorDeclarationBody.cs index daa459c7b4ccf..3fcb562dcf0ad 100644 --- a/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/PropertyOrIndexerAccessorDeclarationBody.cs +++ b/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/PropertyOrIndexerAccessorDeclarationBody.cs @@ -6,6 +6,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.EditAndContinue; diff --git a/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/TopLevelCodeDeclarationBody.cs b/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/TopLevelCodeDeclarationBody.cs index bda8462e94e9d..40674397667f4 100644 --- a/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/TopLevelCodeDeclarationBody.cs +++ b/src/Features/CSharp/Portable/EditAndContinue/DeclarationBody/TopLevelCodeDeclarationBody.cs @@ -7,6 +7,7 @@ using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.EditAndContinue; diff --git a/src/Features/CSharp/Portable/ExternalAccess/Pythia/Api/IPythiaDeclarationNameRecommenderImplmentation.cs b/src/Features/CSharp/Portable/ExternalAccess/Pythia/Api/IPythiaDeclarationNameRecommenderImplmentation.cs index 98f0f1cce3601..9c592520a7c37 100644 --- a/src/Features/CSharp/Portable/ExternalAccess/Pythia/Api/IPythiaDeclarationNameRecommenderImplmentation.cs +++ b/src/Features/CSharp/Portable/ExternalAccess/Pythia/Api/IPythiaDeclarationNameRecommenderImplmentation.cs @@ -14,7 +14,7 @@ internal interface IPythiaDeclarationNameRecommenderImplementation /// /// Order of returned recommendation decides the order of those items in completion list /// - public Task> ProvideRecommendationsAsync(PythiaDeclarationNameContext context, CancellationToken cancellationToken); + Task> ProvideRecommendationsAsync(PythiaDeclarationNameContext context, CancellationToken cancellationToken); } internal readonly struct PythiaDeclarationNameContext(CSharpSyntaxContext context) diff --git a/src/Features/CSharp/Portable/ExternalAccess/Pythia/PythiaSignatureHelpProvider.cs b/src/Features/CSharp/Portable/ExternalAccess/Pythia/PythiaSignatureHelpProvider.cs index bc5689d7b345c..d1e7e46bd1299 100644 --- a/src/Features/CSharp/Portable/ExternalAccess/Pythia/PythiaSignatureHelpProvider.cs +++ b/src/Features/CSharp/Portable/ExternalAccess/Pythia/PythiaSignatureHelpProvider.cs @@ -2,16 +2,16 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.SignatureHelp; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api; -using System; using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.SignatureHelp; namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia; diff --git a/src/Features/CSharp/Portable/ExtractInterface/CSharpExtractInterfaceService.cs b/src/Features/CSharp/Portable/ExtractInterface/CSharpExtractInterfaceService.cs index c13adcaa33516..36b10c8df0b20 100644 --- a/src/Features/CSharp/Portable/ExtractInterface/CSharpExtractInterfaceService.cs +++ b/src/Features/CSharp/Portable/ExtractInterface/CSharpExtractInterfaceService.cs @@ -11,12 +11,12 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ExtractInterface; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; -using Microsoft.CodeAnalysis.CodeRefactorings; namespace Microsoft.CodeAnalysis.CSharp.ExtractInterface; diff --git a/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.Analyzer.cs b/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.Analyzer.cs index 6278cd82325a4..083796ea8dfa1 100644 --- a/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.Analyzer.cs +++ b/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.Analyzer.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Threading; +using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ExtractMethod; diff --git a/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.ExpressionCodeGenerator.cs b/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.ExpressionCodeGenerator.cs index 3fd2a225a2645..b84f47b5d5225 100644 --- a/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.ExpressionCodeGenerator.cs +++ b/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.ExpressionCodeGenerator.cs @@ -12,7 +12,6 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Shared.Extensions; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod; diff --git a/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.cs b/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.cs index 082e857e2a425..41f97af64e97a 100644 --- a/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.cs +++ b/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.cs @@ -788,7 +788,7 @@ private ImmutableArray SplitOrMoveDeclarationIntoMethodDefiniti var declStatements = CreateDeclarationStatements(AnalyzerResult.GetVariablesToSplitOrMoveIntoMethodDefinition(), cancellationToken); declStatements = postProcessor.MergeDeclarationStatements(declStatements); - return declStatements.Concat(statements); + return [.. declStatements, .. statements]; } protected override bool LastStatementOrHasReturnStatementInReturnableConstruct() @@ -1153,13 +1153,13 @@ protected string GenerateMethodNameFromUserPreference() } // For local functions, pascal case and camel case should be the most common and therefore we only consider those cases. - var localFunctionPreferences = Options.NamingStyle.SymbolSpecifications.Where(symbol => symbol.AppliesTo(new SymbolSpecification.SymbolKindOrTypeKind(MethodKind.LocalFunction), CreateMethodModifiers(), null)); + var localFunctionPreferences = Options.NamingStyle.SymbolSpecifications.Where(symbol => symbol.AppliesTo(new SymbolSpecification.SymbolKindOrTypeKind(MethodKind.LocalFunction), CreateMethodModifiers().Modifiers, null)); var namingRules = Options.NamingStyle.Rules.NamingRules; var localFunctionKind = new SymbolSpecification.SymbolKindOrTypeKind(MethodKind.LocalFunction); if (LocalFunction) { - if (namingRules.Any(static (rule, arg) => rule.NamingStyle.CapitalizationScheme.Equals(Capitalization.CamelCase) && rule.SymbolSpecification.AppliesTo(arg.localFunctionKind, arg.self.CreateMethodModifiers(), null), (self: this, localFunctionKind))) + if (namingRules.Any(static (rule, arg) => rule.NamingStyle.CapitalizationScheme.Equals(Capitalization.CamelCase) && rule.SymbolSpecification.AppliesTo(arg.localFunctionKind, arg.self.CreateMethodModifiers().Modifiers, null), (self: this, localFunctionKind))) { methodName = NewMethodCamelCaseStr; } diff --git a/src/Features/CSharp/Portable/ExtractMethod/CSharpSelectionResult.StatementResult.cs b/src/Features/CSharp/Portable/ExtractMethod/CSharpSelectionResult.StatementResult.cs index cf99437e03284..65cb3d633df1e 100644 --- a/src/Features/CSharp/Portable/ExtractMethod/CSharpSelectionResult.StatementResult.cs +++ b/src/Features/CSharp/Portable/ExtractMethod/CSharpSelectionResult.StatementResult.cs @@ -9,7 +9,6 @@ using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod; diff --git a/src/Features/CSharp/Portable/Formatting/CSharpAccessibilityModifiersNewDocumentFormattingProvider.cs b/src/Features/CSharp/Portable/Formatting/CSharpAccessibilityModifiersNewDocumentFormattingProvider.cs index 30be48ebbb5c5..14243dfb1210a 100644 --- a/src/Features/CSharp/Portable/Formatting/CSharpAccessibilityModifiersNewDocumentFormattingProvider.cs +++ b/src/Features/CSharp/Portable/Formatting/CSharpAccessibilityModifiersNewDocumentFormattingProvider.cs @@ -62,7 +62,7 @@ public async Task FormatNewDocumentAsync(Document document, Document? // error. var modifiers = syntaxFacts.GetModifiers(declaration); CSharpAccessibilityFacts.GetAccessibilityAndModifiers(modifiers, out _, out var declarationModifiers, out _); - if (declarationModifiers.IsPartial) + if (declarationModifiers.HasFlag(Modifiers.Partial)) continue; var type = semanticModel.GetDeclaredSymbol(declaration, cancellationToken); diff --git a/src/Features/CSharp/Portable/Formatting/CSharpUseProgramMainNewDocumentFormattingProvider.cs b/src/Features/CSharp/Portable/Formatting/CSharpUseProgramMainNewDocumentFormattingProvider.cs index b3745d1059636..b22c4e26b2d7f 100644 --- a/src/Features/CSharp/Portable/Formatting/CSharpUseProgramMainNewDocumentFormattingProvider.cs +++ b/src/Features/CSharp/Portable/Formatting/CSharpUseProgramMainNewDocumentFormattingProvider.cs @@ -6,8 +6,8 @@ using System.Composition; using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis.CSharp.ConvertProgram; using Microsoft.CodeAnalysis.CodeCleanup; +using Microsoft.CodeAnalysis.CSharp.ConvertProgram; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; diff --git a/src/Features/CSharp/Portable/GenerateConstructors/CSharpGenerateConstructorsCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/GenerateConstructors/CSharpGenerateConstructorsCodeRefactoringProvider.cs index 2a31537cf8b32..7dd5413db607d 100644 --- a/src/Features/CSharp/Portable/GenerateConstructors/CSharpGenerateConstructorsCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/GenerateConstructors/CSharpGenerateConstructorsCodeRefactoringProvider.cs @@ -5,18 +5,18 @@ using System; using System.Composition; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Extensions; +using Microsoft.CodeAnalysis.CSharp.Simplification; +using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Features.Intents; +using Microsoft.CodeAnalysis.GenerateConstructors; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PickMembers; using Microsoft.CodeAnalysis.Simplification; -using Microsoft.CodeAnalysis.CSharp.Simplification; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using System.Linq; -using Microsoft.CodeAnalysis.GenerateConstructors; namespace Microsoft.CodeAnalysis.CSharp.GenerateConstructors; @@ -91,8 +91,8 @@ protected override async ValueTask PrefersThrowExpressionAsync(Document do return GetAccessedMemberName(arrowExpression.Expression); // { return this.name; } - if (body is BlockSyntax { Statements.Count: > 0 } block) - return GetAccessedMemberName(block.Statements.First()); + if (body is BlockSyntax { Statements: [var firstStatement, ..] }) + return GetAccessedMemberName(firstStatement); return null; } diff --git a/src/Features/CSharp/Portable/GenerateType/CSharpGenerateTypeService.cs b/src/Features/CSharp/Portable/GenerateType/CSharpGenerateTypeService.cs index 902a2fdbaeaab..4514a859ad8df 100644 --- a/src/Features/CSharp/Portable/GenerateType/CSharpGenerateTypeService.cs +++ b/src/Features/CSharp/Portable/GenerateType/CSharpGenerateTypeService.cs @@ -782,7 +782,7 @@ private static IPropertySymbol CreatePropertySymbol( return CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: [], accessibility: Accessibility.Public, - modifiers: new DeclarationModifiers(), + modifiers: DeclarationModifiers.None, explicitInterfaceImplementations: default, name: propertyName.Identifier.ValueText, type: propertyType, diff --git a/src/Features/CSharp/Portable/Highlighting/KeywordHighlighters/AsyncAwaitHighlighter.cs b/src/Features/CSharp/Portable/Highlighting/KeywordHighlighters/AsyncAwaitHighlighter.cs index 29de390545098..7c7f938a1001f 100644 --- a/src/Features/CSharp/Portable/Highlighting/KeywordHighlighters/AsyncAwaitHighlighter.cs +++ b/src/Features/CSharp/Portable/Highlighting/KeywordHighlighters/AsyncAwaitHighlighter.cs @@ -7,6 +7,7 @@ using System.Composition; using System.Threading; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Highlighting; diff --git a/src/Features/CSharp/Portable/Highlighting/KeywordHighlighters/IfStatementHighlighter.cs b/src/Features/CSharp/Portable/Highlighting/KeywordHighlighters/IfStatementHighlighter.cs index 3aad59cea4a07..d01b9e877664f 100644 --- a/src/Features/CSharp/Portable/Highlighting/KeywordHighlighters/IfStatementHighlighter.cs +++ b/src/Features/CSharp/Portable/Highlighting/KeywordHighlighters/IfStatementHighlighter.cs @@ -10,6 +10,7 @@ using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Highlighting; diff --git a/src/Features/CSharp/Portable/Highlighting/KeywordHighlighters/LoopHighlighter.cs b/src/Features/CSharp/Portable/Highlighting/KeywordHighlighters/LoopHighlighter.cs index d91aa600fd163..06ad6407ba2bc 100644 --- a/src/Features/CSharp/Portable/Highlighting/KeywordHighlighters/LoopHighlighter.cs +++ b/src/Features/CSharp/Portable/Highlighting/KeywordHighlighters/LoopHighlighter.cs @@ -7,6 +7,7 @@ using System.Composition; using System.Diagnostics; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Highlighting; diff --git a/src/Features/CSharp/Portable/Highlighting/KeywordHighlighters/SwitchStatementHighlighter.cs b/src/Features/CSharp/Portable/Highlighting/KeywordHighlighters/SwitchStatementHighlighter.cs index f5949d1c8f43b..98ce9c9d200a8 100644 --- a/src/Features/CSharp/Portable/Highlighting/KeywordHighlighters/SwitchStatementHighlighter.cs +++ b/src/Features/CSharp/Portable/Highlighting/KeywordHighlighters/SwitchStatementHighlighter.cs @@ -7,6 +7,7 @@ using System.Composition; using System.Diagnostics; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Highlighting; diff --git a/src/Features/CSharp/Portable/ImplementInterface/AbstractChangeImplementationCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/ImplementInterface/AbstractChangeImplementationCodeRefactoringProvider.cs index a670685ec852e..2dfc050e68727 100644 --- a/src/Features/CSharp/Portable/ImplementInterface/AbstractChangeImplementationCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/ImplementInterface/AbstractChangeImplementationCodeRefactoringProvider.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; @@ -10,6 +11,7 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Collections; diff --git a/src/Features/CSharp/Portable/ImplementInterface/CSharpImplementImplicitlyCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/ImplementInterface/CSharpImplementImplicitlyCodeRefactoringProvider.cs index b31cd2819eb08..8db03310c12f7 100644 --- a/src/Features/CSharp/Portable/ImplementInterface/CSharpImplementImplicitlyCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/ImplementInterface/CSharpImplementImplicitlyCodeRefactoringProvider.cs @@ -4,6 +4,7 @@ using System.Composition; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; diff --git a/src/Features/CSharp/Portable/InitializeParameter/CSharpInitializeMemberFromParameterCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/InitializeParameter/CSharpInitializeMemberFromParameterCodeRefactoringProvider.cs index cb4955e25a9fd..6fb0669b07437 100644 --- a/src/Features/CSharp/Portable/InitializeParameter/CSharpInitializeMemberFromParameterCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/InitializeParameter/CSharpInitializeMemberFromParameterCodeRefactoringProvider.cs @@ -9,6 +9,7 @@ using Microsoft.CodeAnalysis.InitializeParameter; namespace Microsoft.CodeAnalysis.CSharp.InitializeParameter; + [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.InitializeMemberFromParameter), Shared] [ExtensionOrder(Before = nameof(CSharpAddParameterCheckCodeRefactoringProvider))] [ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.Wrapping)] diff --git a/src/Features/CSharp/Portable/InitializeParameter/CSharpInitializeMemberFromPrimaryConstructorParameterCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/InitializeParameter/CSharpInitializeMemberFromPrimaryConstructorParameterCodeRefactoringProvider.cs index a8789d8d43d48..4e02d3fe20834 100644 --- a/src/Features/CSharp/Portable/InitializeParameter/CSharpInitializeMemberFromPrimaryConstructorParameterCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/InitializeParameter/CSharpInitializeMemberFromPrimaryConstructorParameterCodeRefactoringProvider.cs @@ -14,12 +14,12 @@ using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.InitializeParameter; -using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Naming; using Roslyn.Utilities; @@ -72,11 +72,18 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte var formattingOptions = await document.GetSyntaxFormattingOptionsAsync(cancellationToken).ConfigureAwait(false); var fieldOrProperty = TryFindMatchingUninitializedFieldOrPropertySymbol(); - var refactorings = fieldOrProperty == null - ? HandleNoExistingFieldOrProperty() - : HandleExistingFieldOrProperty(); + using var refactorings = TemporaryArray.Empty; + if (fieldOrProperty != null) + { + // Found a field/property that this parameter should be assigned to. Just offer the simple assignment to it. + refactorings.Add(CreateCodeAction( + string.Format(fieldOrProperty.Kind == SymbolKind.Field ? FeaturesResources.Initialize_field_0 : FeaturesResources.Initialize_property_0, fieldOrProperty.Name), + cancellationToken => AddAssignmentForPrimaryConstructorAsync(document, parameter, fieldOrProperty, cancellationToken))); + } + + AddCreateFieldOrPropertyCodeActions(); - context.RegisterRefactorings(refactorings.ToImmutableArray(), context.Span); + context.RegisterRefactorings(refactorings.ToImmutableAndClear(), context.Span); return; ISymbol? TryFindMatchingUninitializedFieldOrPropertySymbol() @@ -132,15 +139,7 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte static CodeAction CreateCodeAction(string title, Func> createSolution) => CodeAction.Create(title, createSolution, title); - IEnumerable HandleExistingFieldOrProperty() - { - // Found a field/property that this parameter should be assigned to. Just offer the simple assignment to it. - yield return CreateCodeAction( - string.Format(fieldOrProperty.Kind == SymbolKind.Field ? FeaturesResources.Initialize_field_0 : FeaturesResources.Initialize_property_0, fieldOrProperty.Name), - cancellationToken => AddAssignmentForPrimaryConstructorAsync(document, parameter, fieldOrProperty, cancellationToken)); - } - - IEnumerable HandleNoExistingFieldOrProperty() + void AddCreateFieldOrPropertyCodeActions() { // Didn't find a field/prop that this parameter could be assigned to. Offer to create new one and assign to that. @@ -158,8 +157,8 @@ IEnumerable HandleNoExistingFieldOrProperty() string.Format(FeaturesResources.Create_and_assign_property_0, property.Name), cancellationToken => AddMultipleMembersAsync(document, typeDeclaration, [parameter], [property], cancellationToken)); - yield return siblingFieldOrProperty is IFieldSymbol ? fieldAction : propertyAction; - yield return siblingFieldOrProperty is IFieldSymbol ? propertyAction : fieldAction; + refactorings.Add(siblingFieldOrProperty is IFieldSymbol ? fieldAction : propertyAction); + refactorings.Add(siblingFieldOrProperty is IFieldSymbol ? propertyAction : fieldAction); var parameters = GetParametersWithoutAssociatedMembers(); if (parameters.Length >= 2) @@ -171,8 +170,8 @@ IEnumerable HandleNoExistingFieldOrProperty() FeaturesResources.Create_and_assign_remaining_as_properties, cancellationToken => AddMultipleMembersAsync(document, typeDeclaration, parameters, parameters.SelectAsArray(CreateProperty), cancellationToken)); - yield return siblingFieldOrProperty is IFieldSymbol ? allFieldsAction : allPropertiesAction; - yield return siblingFieldOrProperty is IFieldSymbol ? allPropertiesAction : allFieldsAction; + refactorings.Add(siblingFieldOrProperty is IFieldSymbol ? allFieldsAction : allPropertiesAction); + refactorings.Add(siblingFieldOrProperty is IFieldSymbol ? allPropertiesAction : allFieldsAction); } } diff --git a/src/Features/CSharp/Portable/QuickInfo/CSharpSemanticQuickInfoProvider.cs b/src/Features/CSharp/Portable/QuickInfo/CSharpSemanticQuickInfoProvider.cs index ed4a0f76acd4e..f0dacfaf0cf95 100644 --- a/src/Features/CSharp/Portable/QuickInfo/CSharpSemanticQuickInfoProvider.cs +++ b/src/Features/CSharp/Portable/QuickInfo/CSharpSemanticQuickInfoProvider.cs @@ -83,13 +83,13 @@ protected override bool GetBindableNodeForTokenIndicatingMemberAccess(SyntaxToke protected override bool ShouldCheckPreviousToken(SyntaxToken token) => !token.Parent.IsKind(SyntaxKind.XmlCrefAttribute); - protected override NullableFlowState GetNullabilityAnalysis(SemanticModel semanticModel, ISymbol symbol, SyntaxNode node, CancellationToken cancellationToken) + protected override (NullableAnnotation, NullableFlowState) GetNullabilityAnalysis(SemanticModel semanticModel, ISymbol symbol, SyntaxNode node, CancellationToken cancellationToken) { // Anything less than C# 8 we just won't show anything, even if the compiler could theoretically give analysis var parseOptions = (CSharpParseOptions)semanticModel.SyntaxTree!.Options; if (parseOptions.LanguageVersion < LanguageVersion.CSharp8) { - return NullableFlowState.None; + return default; } // If the user doesn't have nullable enabled, don't show anything. For now we're not trying to be more precise if the user has just annotations or just @@ -98,7 +98,7 @@ protected override NullableFlowState GetNullabilityAnalysis(SemanticModel semant var nullableContext = semanticModel.GetNullableContext(node.SpanStart); if (!nullableContext.WarningsEnabled() || !nullableContext.AnnotationsEnabled()) { - return NullableFlowState.None; + return default; } // Although GetTypeInfo can return nullability for uses of all sorts of things, it's not always useful for quick info. @@ -118,10 +118,20 @@ protected override NullableFlowState GetNullabilityAnalysis(SemanticModel semant case IRangeVariableSymbol: break; + // Although methods have no nullable flow state, + // we still want to show when they are "not nullable aware". + case IMethodSymbol { ReturnsVoid: false }: + break; + default: return default; } + if (symbol.GetMemberType() is { IsValueType: false, NullableAnnotation: NullableAnnotation.None }) + { + return (NullableAnnotation.None, NullableFlowState.NotNull); + } + var typeInfo = semanticModel.GetTypeInfo(node, cancellationToken); // Nullability is a reference type only feature, value types can use @@ -133,7 +143,8 @@ protected override NullableFlowState GetNullabilityAnalysis(SemanticModel semant return default; } - return typeInfo.Nullability.FlowState; + var nullability = typeInfo.Nullability; + return (nullability.Annotation, nullability.FlowState); } protected override async Task GetOnTheFlyDocsInfoAsync(QuickInfoContext context, CancellationToken cancellationToken) diff --git a/src/Features/CSharp/Portable/ReplacePropertyWithMethods/CSharpReplacePropertyWithMethodsService.cs b/src/Features/CSharp/Portable/ReplacePropertyWithMethods/CSharpReplacePropertyWithMethodsService.cs index d88cd6af1630b..7d67c16752202 100644 --- a/src/Features/CSharp/Portable/ReplacePropertyWithMethods/CSharpReplacePropertyWithMethodsService.cs +++ b/src/Features/CSharp/Portable/ReplacePropertyWithMethods/CSharpReplacePropertyWithMethodsService.cs @@ -10,6 +10,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CodeStyle; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; diff --git a/src/Features/CSharp/Portable/SignatureHelp/LightweightOverloadResolution.cs b/src/Features/CSharp/Portable/SignatureHelp/LightweightOverloadResolution.cs index eef3b2d32f7a7..dd47f8b4d4ddb 100644 --- a/src/Features/CSharp/Portable/SignatureHelp/LightweightOverloadResolution.cs +++ b/src/Features/CSharp/Portable/SignatureHelp/LightweightOverloadResolution.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Immutable; using System.Diagnostics; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; diff --git a/src/Features/CSharp/Portable/SignatureHelp/SignatureHelpUtilities.cs b/src/Features/CSharp/Portable/SignatureHelp/SignatureHelpUtilities.cs index dfaf0f5d31b9d..b5f9ab5bd691f 100644 --- a/src/Features/CSharp/Portable/SignatureHelp/SignatureHelpUtilities.cs +++ b/src/Features/CSharp/Portable/SignatureHelp/SignatureHelpUtilities.cs @@ -4,13 +4,13 @@ using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; -using Microsoft.CodeAnalysis.Shared.Extensions; -using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp; diff --git a/src/Features/CSharp/Portable/Snippets/AbstractCSharpForLoopSnippetProvider.cs b/src/Features/CSharp/Portable/Snippets/AbstractCSharpForLoopSnippetProvider.cs index 96e5075f2a99d..477c9a75ac9f2 100644 --- a/src/Features/CSharp/Portable/Snippets/AbstractCSharpForLoopSnippetProvider.cs +++ b/src/Features/CSharp/Portable/Snippets/AbstractCSharpForLoopSnippetProvider.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; diff --git a/src/Features/CSharp/Portable/Snippets/AbstractCSharpMainMethodSnippetProvider.cs b/src/Features/CSharp/Portable/Snippets/AbstractCSharpMainMethodSnippetProvider.cs index cc9cce7497814..f190b43610df9 100644 --- a/src/Features/CSharp/Portable/Snippets/AbstractCSharpMainMethodSnippetProvider.cs +++ b/src/Features/CSharp/Portable/Snippets/AbstractCSharpMainMethodSnippetProvider.cs @@ -6,7 +6,6 @@ using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; -using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Snippets; using Microsoft.CodeAnalysis.Snippets.SnippetProviders; diff --git a/src/Features/CSharp/Portable/SolutionExplorer/CSharpSolutionExplorerSymbolTreeItemProvider.cs b/src/Features/CSharp/Portable/SolutionExplorer/CSharpSolutionExplorerSymbolTreeItemProvider.cs index ceb7dd4c610f9..b94347cd8bf9d 100644 --- a/src/Features/CSharp/Portable/SolutionExplorer/CSharpSolutionExplorerSymbolTreeItemProvider.cs +++ b/src/Features/CSharp/Portable/SolutionExplorer/CSharpSolutionExplorerSymbolTreeItemProvider.cs @@ -5,7 +5,6 @@ using System; using System.Composition; using System.Diagnostics; -using System.Reflection.Metadata; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; diff --git a/src/Features/CSharp/Portable/StringIndentation/CSharpStringIndentationService.cs b/src/Features/CSharp/Portable/StringIndentation/CSharpStringIndentationService.cs index 45a98bb72253c..0a695150fb79f 100644 --- a/src/Features/CSharp/Portable/StringIndentation/CSharpStringIndentationService.cs +++ b/src/Features/CSharp/Portable/StringIndentation/CSharpStringIndentationService.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Features/CSharp/Portable/Structure/Providers/BlockSyntaxStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/BlockSyntaxStructureProvider.cs index 5c96efa3c8be2..a1257321cfcba 100644 --- a/src/Features/CSharp/Portable/Structure/Providers/BlockSyntaxStructureProvider.cs +++ b/src/Features/CSharp/Portable/Structure/Providers/BlockSyntaxStructureProvider.cs @@ -4,6 +4,7 @@ using System; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Features/CSharp/Portable/UseExpressionBody/UseExpressionBodyCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/UseExpressionBody/UseExpressionBodyCodeRefactoringProvider.cs index c34dbb872552c..a59129b661249 100644 --- a/src/Features/CSharp/Portable/UseExpressionBody/UseExpressionBodyCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/UseExpressionBody/UseExpressionBodyCodeRefactoringProvider.cs @@ -47,8 +47,8 @@ internal sealed class UseExpressionBodyCodeRefactoringProvider() : SyntaxEditorB { foreach (var helper in helpers) { - yield return KeyValuePairUtil.Create((helper, useExpressionBody: true), helper.GetType().Name + "_UseExpressionBody"); - yield return KeyValuePairUtil.Create((helper, useExpressionBody: false), helper.GetType().Name + "_UseBlockBody"); + yield return KeyValuePair.Create((helper, useExpressionBody: true), helper.GetType().Name + "_UseExpressionBody"); + yield return KeyValuePair.Create((helper, useExpressionBody: false), helper.GetType().Name + "_UseBlockBody"); } } } diff --git a/src/Features/CSharp/Portable/UseExpressionBodyForLambda/UseExpressionBodyForLambdaCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/UseExpressionBodyForLambda/UseExpressionBodyForLambdaCodeRefactoringProvider.cs index fdca9437eb188..fd05e2e11a416 100644 --- a/src/Features/CSharp/Portable/UseExpressionBodyForLambda/UseExpressionBodyForLambdaCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/UseExpressionBodyForLambda/UseExpressionBodyForLambdaCodeRefactoringProvider.cs @@ -10,6 +10,7 @@ using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.CodeFixes.UseExpressionBodyForLambda; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; diff --git a/src/Features/CSharp/Portable/Wrapping/SeparatedSyntaxList/CSharpParameterWrapper.cs b/src/Features/CSharp/Portable/Wrapping/SeparatedSyntaxList/CSharpParameterWrapper.cs index 7a95485f9969f..824ef1c61858c 100644 --- a/src/Features/CSharp/Portable/Wrapping/SeparatedSyntaxList/CSharpParameterWrapper.cs +++ b/src/Features/CSharp/Portable/Wrapping/SeparatedSyntaxList/CSharpParameterWrapper.cs @@ -9,7 +9,6 @@ using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Utilities; using Microsoft.CodeAnalysis.Wrapping; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Wrapping.SeparatedSyntaxList; diff --git a/src/Features/CSharpTest/AddAwait/AddAwaitTests.cs b/src/Features/CSharpTest/AddAwait/AddAwaitTests.cs index f19dc9aa12f56..00486135838fb 100644 --- a/src/Features/CSharpTest/AddAwait/AddAwaitTests.cs +++ b/src/Features/CSharpTest/AddAwait/AddAwaitTests.cs @@ -19,9 +19,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor => new CSharpAddAwaitCodeRefactoringProvider(); [Fact] - public async Task Simple() - { - await TestInRegularAndScriptAsync(""" + public Task Simple() + => TestInRegularAndScriptAsync(""" using System.Threading.Tasks; class Program { @@ -40,12 +39,10 @@ async Task GetNumberAsync() } } """); - } [Fact] - public async Task SimpleWithConfigureAwait() - { - await TestInRegularAndScriptAsync(""" + public Task SimpleWithConfigureAwait() + => TestInRegularAndScriptAsync(""" using System.Threading.Tasks; class Program { @@ -64,12 +61,10 @@ async Task GetNumberAsync() } } """, index: 1); - } [Fact] - public async Task InArgument() - { - await TestInRegularAndScriptAsync(""" + public Task InArgument() + => TestInRegularAndScriptAsync(""" using System.Threading.Tasks; class Program { @@ -88,12 +83,10 @@ async Task GetNumberAsync(int argument) } } """); - } [Fact] - public async Task InvocationInArgument() - { - await TestInRegularAndScriptAsync(""" + public Task InvocationInArgument() + => TestInRegularAndScriptAsync(""" using System.Threading.Tasks; class Program { @@ -112,12 +105,10 @@ async Task GetNumberAsync() } } """); - } [Fact] - public async Task InvocationInArgumentWithConfigureAwait() - { - await TestInRegularAndScriptAsync(""" + public Task InvocationInArgumentWithConfigureAwait() + => TestInRegularAndScriptAsync(""" using System.Threading.Tasks; class Program { @@ -136,12 +127,10 @@ async Task GetNumberAsync() } } """, index: 1); - } [Fact] - public async Task AlreadyAwaited() - { - await TestMissingInRegularAndScriptAsync(""" + public Task AlreadyAwaited() + => TestMissingInRegularAndScriptAsync(""" using System.Threading.Tasks; class Program { @@ -151,12 +140,10 @@ async Task GetNumberAsync() } } """); - } [Fact] - public async Task AlreadyAwaitedAndConfigured() - { - await TestMissingInRegularAndScriptAsync(""" + public Task AlreadyAwaitedAndConfigured() + => TestMissingInRegularAndScriptAsync(""" using System.Threading.Tasks; class Program { @@ -166,12 +153,10 @@ async Task GetNumberAsync() } } """); - } [Fact] - public async Task AlreadyAwaitedAndConfigured2() - { - await TestMissingInRegularAndScriptAsync(""" + public Task AlreadyAwaitedAndConfigured2() + => TestMissingInRegularAndScriptAsync(""" using System.Threading.Tasks; class Program { @@ -181,12 +166,10 @@ async Task GetNumberAsync() } } """); - } [Fact] - public async Task SimpleWithTrivia() - { - await TestInRegularAndScriptAsync(""" + public Task SimpleWithTrivia() + => TestInRegularAndScriptAsync(""" using System.Threading.Tasks; class Program { @@ -207,12 +190,10 @@ await GetNumberAsync()[||] /* comment */ } } """); - } [Fact] - public async Task SimpleWithTrivia2() - { - await TestInRegularAndScriptAsync(""" + public Task SimpleWithTrivia2() + => TestInRegularAndScriptAsync(""" using System.Threading.Tasks; class Program { @@ -231,12 +212,10 @@ async Task GetNumberAsync() } } """); - } [Fact] - public async Task SimpleWithTriviaWithConfigureAwait() - { - await TestInRegularAndScriptAsync(""" + public Task SimpleWithTriviaWithConfigureAwait() + => TestInRegularAndScriptAsync(""" using System.Threading.Tasks; class Program { @@ -257,12 +236,10 @@ await GetNumberAsync().ConfigureAwait(false) /* comment */ } } """, index: 1); - } [Fact] - public async Task SimpleWithTrivia2WithConfigureAwait() - { - await TestInRegularAndScriptAsync(""" + public Task SimpleWithTrivia2WithConfigureAwait() + => TestInRegularAndScriptAsync(""" using System.Threading.Tasks; class Program { @@ -281,12 +258,10 @@ async Task GetNumberAsync() } } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task OnSemiColon() - { - await TestInRegularAndScriptAsync(""" + public Task OnSemiColon() + => TestInRegularAndScriptAsync(""" using System.Threading.Tasks; class Program { @@ -305,12 +280,10 @@ async Task GetNumberAsync() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task Selection() - { - await TestInRegularAndScriptAsync(""" + public Task Selection() + => TestInRegularAndScriptAsync(""" using System.Threading.Tasks; class Program { @@ -329,12 +302,10 @@ async Task GetNumberAsync() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task Selection2() - { - await TestInRegularAndScriptAsync(""" + public Task Selection2() + => TestInRegularAndScriptAsync(""" using System.Threading.Tasks; class Program { @@ -353,12 +324,10 @@ async Task GetNumberAsync() } } """); - } [Fact] - public async Task ChainedInvocation() - { - await TestMissingInRegularAndScriptAsync(""" + public Task ChainedInvocation() + => TestMissingInRegularAndScriptAsync(""" using System.Threading.Tasks; class Program { @@ -369,12 +338,10 @@ async void M() } } """); - } [Fact] - public async Task ChainedInvocation_ExpressionOfInvalidInvocation() - { - await TestInRegularAndScript1Async(""" + public Task ChainedInvocation_ExpressionOfInvalidInvocation() + => TestInRegularAndScript1Async(""" using System.Threading.Tasks; class Program { @@ -395,13 +362,10 @@ async void M() } } """); - } [Fact] - public async Task BadAsyncReturnOperand1() - { - var initial = - """ + public Task BadAsyncReturnOperand1() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; @@ -417,10 +381,7 @@ async Task Test2() return [|Test()|]; } } - """; - - var expected = - """ + """, """ using System; using System.Threading.Tasks; @@ -436,15 +397,11 @@ async Task Test2() return await Test(); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task BadAsyncReturnOperand_WithLeadingTrivia1() - { - var initial = - """ + public Task BadAsyncReturnOperand_WithLeadingTrivia1() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; @@ -462,10 +419,7 @@ async Task Test2() [|Test()|]; } } - """; - - var expected = - """ + """, """ using System; using System.Threading.Tasks; @@ -483,15 +437,11 @@ async Task Test2() await Test(); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task BadAsyncReturnOperand_ConditionalExpressionWithTrailingTrivia_SingleLine() - { - var initial = - """ + public Task BadAsyncReturnOperand_ConditionalExpressionWithTrailingTrivia_SingleLine() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; @@ -504,10 +454,7 @@ async Task Test2() return [|true ? Test() /* true */ : Test()|] /* false */; } } - """; - - var expected = - """ + """, """ using System; using System.Threading.Tasks; @@ -520,15 +467,11 @@ async Task Test2() return await (true ? Test() /* true */ : Test()) /* false */; } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task BadAsyncReturnOperand_ConditionalExpressionWithTrailingTrivia_Multiline() - { - var initial = - """ + public Task BadAsyncReturnOperand_ConditionalExpressionWithTrailingTrivia_Multiline() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; @@ -543,10 +486,7 @@ async Task Test2() ; } } - """; - - var expected = - """ + """, """ using System; using System.Threading.Tasks; @@ -561,15 +501,11 @@ async Task Test2() ; } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task BadAsyncReturnOperand_NullCoalescingExpressionWithTrailingTrivia_SingleLine() - { - var initial = - """ + public Task BadAsyncReturnOperand_NullCoalescingExpressionWithTrailingTrivia_SingleLine() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; @@ -582,10 +518,7 @@ async Task Test2() return [|null /* 0 */ ?? Test()|] /* 1 */; } } - """; - - var expected = - """ + """, """ using System; using System.Threading.Tasks; @@ -598,15 +531,11 @@ async Task Test2() return await (null /* 0 */ ?? Test()) /* 1 */; } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task BadAsyncReturnOperand_NullCoalescingExpressionWithTrailingTrivia_Multiline() - { - var initial = - """ + public Task BadAsyncReturnOperand_NullCoalescingExpressionWithTrailingTrivia_Multiline() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; @@ -621,10 +550,7 @@ async Task Test2() ; } } - """; - - var expected = - """ + """, """ using System; using System.Threading.Tasks; @@ -639,15 +565,11 @@ async Task Test2() ; } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task BadAsyncReturnOperand_AsExpressionWithTrailingTrivia_SingleLine() - { - var initial = - """ + public Task BadAsyncReturnOperand_AsExpressionWithTrailingTrivia_SingleLine() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; @@ -658,10 +580,7 @@ async Task Test2() return [|null /* 0 */ as Task|] /* 1 */; } } - """; - - var expected = - """ + """, """ using System; using System.Threading.Tasks; @@ -672,15 +591,11 @@ async Task Test2() return await (null /* 0 */ as Task) /* 1 */; } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task BadAsyncReturnOperand_AsExpressionWithTrailingTrivia_Multiline() - { - var initial = - """ + public Task BadAsyncReturnOperand_AsExpressionWithTrailingTrivia_Multiline() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; @@ -695,10 +610,7 @@ as Task|] // bbb ; } } - """; - - var expected = - """ + """, """ using System; using System.Threading.Tasks; @@ -713,15 +625,11 @@ async Task Test2() ; } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TaskNotAwaited() - { - var initial = - """ + public Task TaskNotAwaited() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; class Program @@ -731,10 +639,7 @@ async void Test() [|Task.Delay(3)|]; } } - """; - - var expected = - """ + """, """ using System; using System.Threading.Tasks; class Program @@ -744,15 +649,11 @@ async void Test() await Task.Delay(3); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TaskNotAwaited_WithLeadingTrivia() - { - var initial = - """ + public Task TaskNotAwaited_WithLeadingTrivia() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; class Program @@ -764,10 +665,7 @@ async void Test() [|Task.Delay(3)|]; } } - """; - - var expected = - """ + """, """ using System; using System.Threading.Tasks; class Program @@ -779,15 +677,11 @@ async void Test() await Task.Delay(3); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task FunctionNotAwaited() - { - var initial = - """ + public Task FunctionNotAwaited() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; class Program @@ -802,10 +696,7 @@ async void Test() [|AwaitableFunction()|]; } } - """; - - var expected = - """ + """, """ using System; using System.Threading.Tasks; class Program @@ -820,15 +711,11 @@ async void Test() await AwaitableFunction(); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task FunctionNotAwaited_WithLeadingTrivia() - { - var initial = - """ + public Task FunctionNotAwaited_WithLeadingTrivia() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; class Program @@ -845,10 +732,7 @@ async void Test() [|AwaitableFunction()|]; } } - """; - - var expected = - """ + """, """ using System; using System.Threading.Tasks; class Program @@ -865,15 +749,11 @@ async void Test() await AwaitableFunction(); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task FunctionNotAwaited_WithLeadingTrivia1() - { - var initial = - """ + public Task FunctionNotAwaited_WithLeadingTrivia1() + => TestInRegularAndScriptAsync(""" using System; using System.Threading.Tasks; class Program @@ -890,10 +770,7 @@ async void Test() [|AwaitableFunction()|]; } } - """; - - var expected = - """ + """, """ using System; using System.Threading.Tasks; class Program @@ -910,14 +787,11 @@ async void Test() await AwaitableFunction(); } } - """; - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestAssignmentExpression() - { - await TestInRegularAndScriptAsync( + public Task TestAssignmentExpression() + => TestInRegularAndScriptAsync( """ using System.Threading.Tasks; @@ -950,12 +824,10 @@ private Task MyIntMethodAsync() } } """); - } [Fact] - public async Task TestAssignmentExpressionWithConversion() - { - await TestInRegularAndScriptAsync( + public Task TestAssignmentExpressionWithConversion() + => TestInRegularAndScriptAsync( """ using System.Threading.Tasks; @@ -988,13 +860,10 @@ private Task MyIntMethodAsync() } } """); - } [Fact] - public async Task TestAssignmentExpressionWithConversionInNonAsyncFunction() - { - - await TestMissingAsync(""" + public Task TestAssignmentExpressionWithConversionInNonAsyncFunction() + => TestMissingAsync(""" using System.Threading.Tasks; class TestClass @@ -1011,12 +880,10 @@ private Task MyIntMethodAsync() } } """); - } [Fact] - public async Task TestAssignmentExpressionWithConversionInAsyncFunction() - { - await TestInRegularAndScriptAsync( + public Task TestAssignmentExpressionWithConversionInAsyncFunction() + => TestInRegularAndScriptAsync( """ using System.Threading.Tasks; @@ -1049,12 +916,10 @@ private Task MyIntMethodAsync() } } """); - } [Fact] - public async Task TestAssignmentExpression1() - { - await TestInRegularAndScriptAsync( + public Task TestAssignmentExpression1() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1093,12 +958,10 @@ private Task MyIntMethodAsync() } } """); - } [Fact] - public async Task TestAssignmentExpression2() - { - await TestInRegularAndScriptAsync( + public Task TestAssignmentExpression2() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1137,12 +1000,10 @@ private Task MyIntMethodAsync() } } """); - } [Fact] - public async Task TestAssignmentExpression3() - { - await TestMissingAsync( + public Task TestAssignmentExpression3() + => TestMissingAsync( """ using System; using System.Threading.Tasks; @@ -1163,12 +1024,10 @@ private Task MyIntMethodAsync() } } """); - } [Fact] - public async Task TestAssignmentExpression3_1() - { - await TestInRegularAndScriptAsync( + public Task TestAssignmentExpression3_1() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1209,12 +1068,10 @@ private Task MyIntMethodAsync() } } """); - } [Fact] - public async Task TestAssignmentExpression4() - { - await TestMissingAsync( + public Task TestAssignmentExpression4() + => TestMissingAsync( """ using System; using System.Threading.Tasks; @@ -1234,12 +1091,10 @@ private Task MyIntMethodAsync() } } """); - } [Fact] - public async Task TestAssignmentExpression4_1() - { - await TestInRegularAndScriptAsync( + public Task TestAssignmentExpression4_1() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1278,12 +1133,10 @@ private Task MyIntMethodAsync() } } """); - } [Fact] - public async Task TestAssignmentExpression5() - { - await TestInRegularAndScriptAsync( + public Task TestAssignmentExpression5() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1322,12 +1175,10 @@ private Task MyIntMethodAsync() } } """); - } [Fact] - public async Task TestAssignmentExpression6() - { - await TestInRegularAndScriptAsync( + public Task TestAssignmentExpression6() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1366,12 +1217,10 @@ private Task MyIntMethodAsync() } } """); - } [Fact] - public async Task TestAssignmentExpression7() - { - await TestMissingAsync( + public Task TestAssignmentExpression7() + => TestMissingAsync( """ using System; using System.Threading.Tasks; @@ -1391,12 +1240,10 @@ private Task MyIntMethodAsync() } } """); - } [Fact] - public async Task TestAssignmentExpression7_1() - { - await TestInRegularAndScriptAsync( + public Task TestAssignmentExpression7_1() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1435,12 +1282,10 @@ private Task MyIntMethodAsync() } } """); - } [Fact] - public async Task TestAssignmentExpression8() - { - await TestMissingAsync( + public Task TestAssignmentExpression8() + => TestMissingAsync( """ using System; using System.Threading.Tasks; @@ -1461,12 +1306,10 @@ private Task MyIntMethodAsync() } } """); - } [Fact] - public async Task TestAssignmentExpression8_1() - { - await TestInRegularAndScriptAsync( + public Task TestAssignmentExpression8_1() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1507,12 +1350,10 @@ private Task MyIntMethodAsync() } } """); - } [Fact] - public async Task TestTernaryOperator() - { - await TestInRegularAndScriptAsync( + public Task TestTernaryOperator() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1537,12 +1378,10 @@ async Task A() } } """); - } [Fact] - public async Task TestNullCoalescingOperator() - { - await TestInRegularAndScriptAsync( + public Task TestNullCoalescingOperator() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1565,12 +1404,10 @@ async Task A() return await (null ?? Task.FromResult(1)); } } """); - } [Fact] - public async Task TestAsExpression() - { - await TestInRegularAndScriptAsync( + public Task TestAsExpression() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1593,12 +1430,10 @@ async Task A() return await (null as Task); } } """); - } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1345322")] - public async Task TestOnTaskTypeItself() - { - await TestMissingAsync( + public Task TestOnTaskTypeItself() + => TestMissingAsync( """ using System.Threading.Tasks; @@ -1609,12 +1444,10 @@ class Program } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66726")] - public async Task NotOnBindingExpression1() - { - await TestMissingInRegularAndScriptAsync(""" + public Task NotOnBindingExpression1() + => TestMissingInRegularAndScriptAsync(""" using System.Threading.Tasks; class TestClass @@ -1630,12 +1463,10 @@ private Task MyIntMethodAsync() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66726")] - public async Task NotOnBindingExpression2() - { - await TestMissingInRegularAndScriptAsync(""" + public Task NotOnBindingExpression2() + => TestMissingInRegularAndScriptAsync(""" using System.Threading.Tasks; class TestClass @@ -1653,12 +1484,10 @@ private Task MyIntMethodAsync() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66726")] - public async Task NotOnBindingExpression3() - { - await TestMissingInRegularAndScriptAsync(""" + public Task NotOnBindingExpression3() + => TestMissingInRegularAndScriptAsync(""" using System.Threading.Tasks; class TestClass @@ -1676,12 +1505,10 @@ private Task MyIntMethodAsync() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66726")] - public async Task NotOnBindingExpression4() - { - await TestMissingInRegularAndScriptAsync(""" + public Task NotOnBindingExpression4() + => TestMissingInRegularAndScriptAsync(""" using System.Threading.Tasks; class TestClass @@ -1694,5 +1521,4 @@ private async Task MyTestMethod1Async(TestClass c) } } """); - } } diff --git a/src/Features/CSharpTest/AddDebuggerDisplay/AddDebuggerDisplayTests.cs b/src/Features/CSharpTest/AddDebuggerDisplay/AddDebuggerDisplayTests.cs index 656a7e56e705d..4c2d5c5b82470 100644 --- a/src/Features/CSharpTest/AddDebuggerDisplay/AddDebuggerDisplayTests.cs +++ b/src/Features/CSharpTest/AddDebuggerDisplay/AddDebuggerDisplayTests.cs @@ -19,9 +19,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddDebuggerDisplay; public sealed class AddDebuggerDisplayTests { [Fact] - public async Task OfferedOnEmptyClass() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task OfferedOnEmptyClass() + => VerifyCS.VerifyRefactoringAsync(""" [||]class C { } @@ -37,17 +36,18 @@ private string GetDebuggerDisplay() } } """); - } [Fact] - public async Task SupportsConstantInterpolatedStrings() - { - var code = """ + public Task SupportsConstantInterpolatedStrings() + => new VerifyCS.Test() + { + LanguageVersion = LanguageVersion.CSharp12, + TestCode = """ [||]class C { } - """; - var fixedCode = """ + """, + FixedCode = """ using System.Diagnostics; [DebuggerDisplay($"{{{nameof(GetDebuggerDisplay)}(),nq}}")] @@ -58,23 +58,19 @@ private string GetDebuggerDisplay() return ToString(); } } - """; - - await new VerifyCS.Test() - { - LanguageVersion = LanguageVersion.CSharp12, - TestCode = code, - FixedCode = fixedCode, + """, }.RunAsync(); - } [Fact] - public async Task OfferedOnEmptyRecord() - { - var code = """ + public Task OfferedOnEmptyRecord() + => new VerifyCS.Test() + { + LanguageVersion = LanguageVersion.CSharp9, + ReferenceAssemblies = ReferenceAssemblies.Net.Net50, + TestCode = """ [||]record C; - """; - var fixedCode = """ + """, + FixedCode = """ using System.Diagnostics; [DebuggerDisplay("{" + nameof(GetDebuggerDisplay) + "(),nq}")] @@ -85,21 +81,12 @@ private string GetDebuggerDisplay() return ToString(); } } - """; - - await new VerifyCS.Test() - { - LanguageVersion = LanguageVersion.CSharp9, - ReferenceAssemblies = ReferenceAssemblies.Net.Net50, - TestCode = code, - FixedCode = fixedCode, + """, }.RunAsync(); - } [Fact] - public async Task OfferedOnEmptyStruct() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task OfferedOnEmptyStruct() + => VerifyCS.VerifyRefactoringAsync(""" [||]struct Foo { } @@ -115,7 +102,6 @@ private string GetDebuggerDisplay() } } """); - } [Fact] public async Task NotOfferedOnStaticClass() @@ -178,9 +164,8 @@ class C } [Fact] - public async Task OfferedOnToString() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task OfferedOnToString() + => VerifyCS.VerifyRefactoringAsync(""" class C { public override string [||]ToString() => "Foo"; @@ -199,12 +184,10 @@ private string GetDebuggerDisplay() } } """); - } [Fact] - public async Task OfferedOnShadowingToString() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task OfferedOnShadowingToString() + => VerifyCS.VerifyRefactoringAsync(""" class A { public new string [||]ToString() => "Foo"; @@ -223,7 +206,6 @@ private string GetDebuggerDisplay() } } """); - } [Fact] public async Task NotOfferedOnWrongOverloadOfToString() @@ -244,9 +226,8 @@ class B : A } [Fact] - public async Task OfferedOnExistingDebuggerDisplayMethod() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task OfferedOnExistingDebuggerDisplayMethod() + => VerifyCS.VerifyRefactoringAsync(""" class C { private string [||]GetDebuggerDisplay() => "Foo"; @@ -260,7 +241,6 @@ class C private string GetDebuggerDisplay() => "Foo"; } """); - } [Fact] public async Task NotOfferedOnWrongOverloadOfDebuggerDisplayMethod() @@ -276,9 +256,8 @@ class A } [Fact] - public async Task NamespaceImportIsNotDuplicated() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task NamespaceImportIsNotDuplicated() + => VerifyCS.VerifyRefactoringAsync(""" using System.Diagnostics; [||]class C @@ -296,12 +275,10 @@ private string GetDebuggerDisplay() } } """); - } [Fact] - public async Task NamespaceImportIsSorted() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task NamespaceImportIsSorted() + => VerifyCS.VerifyRefactoringAsync(""" using System.Xml; [||]class C @@ -320,7 +297,6 @@ private string GetDebuggerDisplay() } } """); - } [Fact] public async Task NotOfferedWhenAlreadySpecified() @@ -349,9 +325,8 @@ public async Task NotOfferedWhenAlreadySpecifiedWithSuffix() } [Fact] - public async Task OfferedWhenAttributeWithTheSameNameIsSpecified() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task OfferedWhenAttributeWithTheSameNameIsSpecified() + => VerifyCS.VerifyRefactoringAsync(""" [{|CS0246:BrokenCode|}.DebuggerDisplay("Foo")] [||]class C { @@ -369,12 +344,10 @@ private string GetDebuggerDisplay() } } """); - } [Fact] - public async Task OfferedWhenAttributeWithTheSameNameIsSpecifiedWithSuffix() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task OfferedWhenAttributeWithTheSameNameIsSpecifiedWithSuffix() + => VerifyCS.VerifyRefactoringAsync(""" [{|CS0246:BrokenCode|}.DebuggerDisplayAttribute("Foo")] [||]class C { @@ -392,7 +365,6 @@ private string GetDebuggerDisplay() } } """); - } [Fact] public async Task AliasedTypeIsRecognized() @@ -410,9 +382,8 @@ public async Task AliasedTypeIsRecognized() } [Fact] - public async Task OfferedWhenBaseClassHasDebuggerDisplay() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task OfferedWhenBaseClassHasDebuggerDisplay() + => VerifyCS.VerifyRefactoringAsync(""" using System.Diagnostics; [DebuggerDisplay("Foo")] @@ -440,12 +411,10 @@ private string GetDebuggerDisplay() } } """); - } [Fact] - public async Task ExistingDebuggerDisplayMethodIsUsedEvenWhenPublicStaticNonString() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task ExistingDebuggerDisplayMethodIsUsedEvenWhenPublicStaticNonString() + => VerifyCS.VerifyRefactoringAsync(""" [||]class C { public static object GetDebuggerDisplay() => "Foo"; @@ -459,12 +428,10 @@ class C public static object GetDebuggerDisplay() => "Foo"; } """); - } [Fact] - public async Task ExistingDebuggerDisplayMethodWithParameterIsNotUsed() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task ExistingDebuggerDisplayMethodWithParameterIsNotUsed() + => VerifyCS.VerifyRefactoringAsync(""" [||]class C { private string GetDebuggerDisplay(int foo = 0) => foo.ToString(); @@ -483,5 +450,4 @@ private string GetDebuggerDisplay() } } """); - } } diff --git a/src/Features/CSharpTest/AddFileBanner/AddFileBannerTests.cs b/src/Features/CSharpTest/AddFileBanner/AddFileBannerTests.cs index 2d73d42672ee9..7b58406a30659 100644 --- a/src/Features/CSharpTest/AddFileBanner/AddFileBannerTests.cs +++ b/src/Features/CSharpTest/AddFileBanner/AddFileBannerTests.cs @@ -19,9 +19,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor => new CSharpAddFileBannerCodeRefactoringProvider(); [Fact] - public async Task TestBanner1() - { - await TestInRegularAndScriptAsync( + public Task TestBanner1() + => TestInRegularAndScriptAsync( """ @@ -66,12 +65,10 @@ class Program2 """); - } [Fact] - public async Task TestMultiLineBanner1() - { - await TestInRegularAndScriptAsync( + public Task TestMultiLineBanner1() + => TestInRegularAndScriptAsync( """ @@ -119,12 +116,10 @@ class Program2 """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33251")] - public async Task TestSingleLineDocCommentBanner() - { - await TestInRegularAndScriptAsync( + public Task TestSingleLineDocCommentBanner() + => TestInRegularAndScriptAsync( """ @@ -172,12 +167,10 @@ class Program2 """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33251")] - public async Task TestMultiLineDocCommentBanner() - { - await TestInRegularAndScriptAsync( + public Task TestMultiLineDocCommentBanner() + => TestInRegularAndScriptAsync( """ @@ -228,12 +221,10 @@ class Program2 """); - } [Fact] - public async Task TestMissingWhenAlreadyThere() - { - await TestMissingAsync( + public Task TestMissingWhenAlreadyThere() + => TestMissingAsync( """ @@ -257,50 +248,45 @@ class Program2 """); - } [Theory] [InlineData("", 1)] [InlineData("file_header_template =", 1)] [InlineData("file_header_template = unset", 1)] [InlineData("file_header_template = defined file header", 0)] - public async Task TestMissingWhenHandledByAnalyzer(string fileHeaderTemplate, int expectedActionCount) - { - var initialMarkup = $@" - - - [||]using System; - -class Program1 -{{ - static void Main() - {{ - }} -}} - - /// This is the banner -/// It goes over multiple lines - -class Program2 -{{ -}} - - -root = true - -[*] -{fileHeaderTemplate} - - -"; - - await TestActionCountAsync(initialMarkup, expectedActionCount); - } + public Task TestMissingWhenHandledByAnalyzer(string fileHeaderTemplate, int expectedActionCount) + => TestActionCountAsync($$""" + + + [||]using System; + + class Program1 + { + static void Main() + { + } + } + + /// This is the banner + /// It goes over multiple lines + + class Program2 + { + } + + + root = true + + [*] + {{fileHeaderTemplate}} + + + + """, expectedActionCount); [Fact] - public async Task TestMissingIfOtherFileDoesNotHaveBanner() - { - await TestMissingAsync( + public Task TestMissingIfOtherFileDoesNotHaveBanner() + => TestMissingAsync( """ @@ -324,12 +310,10 @@ class Program2 """); - } [Fact] - public async Task TestMissingIfOtherFileIsAutoGenerated() - { - await TestMissingAsync( + public Task TestMissingIfOtherFileIsAutoGenerated() + => TestMissingAsync( """ @@ -353,12 +337,10 @@ class Program2 """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32792")] - public async Task TestUpdateFileNameInComment() - { - await TestInRegularAndScriptAsync( + public Task TestUpdateFileNameInComment() + => TestInRegularAndScriptAsync( """ @@ -409,12 +391,10 @@ class Program2 """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32792")] - public async Task TestUpdateFileNameInComment2() - { - await TestInRegularAndScriptAsync( + public Task TestUpdateFileNameInComment2() + => TestInRegularAndScriptAsync( """ @@ -465,12 +445,10 @@ class Program2 """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33251")] - public async Task TestUpdateFileNameInComment3() - { - await TestInRegularAndScriptAsync( + public Task TestUpdateFileNameInComment3() + => TestInRegularAndScriptAsync( """ @@ -521,12 +499,10 @@ class Program2 """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33251")] - public async Task TestUpdateFileNameInComment4() - { - await TestInRegularAndScriptAsync( + public Task TestUpdateFileNameInComment4() + => TestInRegularAndScriptAsync( """ @@ -577,5 +553,4 @@ class Program2 """); - } } diff --git a/src/Features/CSharpTest/AddFileBanner/AddFileBannerTests_FixAll.cs b/src/Features/CSharpTest/AddFileBanner/AddFileBannerTests_FixAll.cs index 2534a71c68e0e..4e29e9604945d 100644 --- a/src/Features/CSharpTest/AddFileBanner/AddFileBannerTests_FixAll.cs +++ b/src/Features/CSharpTest/AddFileBanner/AddFileBannerTests_FixAll.cs @@ -14,286 +14,286 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddFileBanner; public sealed partial class AddFileBannerTests { [Fact] - public async Task FixAllInProject() - { - await TestInRegularAndScriptAsync( -@" - - - {|FixAllInProject:|}using System; - -class Program1 -{ - static void Main() - { - } -} - - // This is the banner - -class Program2 -{ -} - - -class Program3 -{ -} - - -", -@" - - - // This is the banner - -using System; - -class Program1 -{ - static void Main() - { - } -} - - // This is the banner - -class Program2 -{ -} - - // This is the banner - - -class Program3 -{ -} - - -"); - } + public Task FixAllInProject() + => TestInRegularAndScriptAsync( + """ + + + {|FixAllInProject:|}using System; + + class Program1 + { + static void Main() + { + } + } + + // This is the banner + + class Program2 + { + } + + + class Program3 + { + } + + + + """, + """ + + + // This is the banner + + using System; + + class Program1 + { + static void Main() + { + } + } + + // This is the banner + + class Program2 + { + } + + // This is the banner + + + class Program3 + { + } + + + + """); [Fact] - public async Task FixAllInSolution() - { - await TestInRegularAndScriptAsync( -@" - - - {|FixAllInSolution:|}using System; - -class Program1 -{ - static void Main() - { - } -} - - // This is the banner - -class Program2 -{ -} - - - - -class Program3 -{ -} - - -", -@" - - - // This is the banner - -using System; - -class Program1 -{ - static void Main() - { - } -} - - // This is the banner - -class Program2 -{ -} - - - - // This is the banner - - -class Program3 -{ -} - - -"); - } + public Task FixAllInSolution() + => TestInRegularAndScriptAsync( + """ + + + {|FixAllInSolution:|}using System; + + class Program1 + { + static void Main() + { + } + } + + // This is the banner + + class Program2 + { + } + + + + + class Program3 + { + } + + + + """, + """ + + + // This is the banner + + using System; + + class Program1 + { + static void Main() + { + } + } + + // This is the banner + + class Program2 + { + } + + + + // This is the banner + + + class Program3 + { + } + + + + """); [Fact] - public async Task FixAll_AlreadyHasBanner() - { - await TestInRegularAndScriptAsync( -@" - - - {|FixAllInProject:|}using System; - -class Program1 -{ - static void Main() - { - } -} - - // This is the banner - -class Program2 -{ -} - - -class Program3 -{ -} - - // This is the banner -// It goes over multiple lines - -class Program4 -{ -} - - /** This is the banner -* It goes over multiple lines -*/ - -class Program5 -{ -} - - -", -@" - - - // This is the banner - -using System; - -class Program1 -{ - static void Main() - { - } -} - - // This is the banner - -class Program2 -{ -} - - // This is the banner - - -class Program3 -{ -} - - // This is the banner -// It goes over multiple lines - -class Program4 -{ -} - - /** This is the banner -* It goes over multiple lines -*/ - -class Program5 -{ -} - - -"); - } + public Task FixAll_AlreadyHasBanner() + => TestInRegularAndScriptAsync( + """ + + + {|FixAllInProject:|}using System; + + class Program1 + { + static void Main() + { + } + } + + // This is the banner + + class Program2 + { + } + + + class Program3 + { + } + + // This is the banner + // It goes over multiple lines + + class Program4 + { + } + + /** This is the banner + * It goes over multiple lines + */ + + class Program5 + { + } + + + + """, + """ + + + // This is the banner + + using System; + + class Program1 + { + static void Main() + { + } + } + + // This is the banner + + class Program2 + { + } + + // This is the banner + + + class Program3 + { + } + + // This is the banner + // It goes over multiple lines + + class Program4 + { + } + + /** This is the banner + * It goes over multiple lines + */ + + class Program5 + { + } + + + + """); [Fact] - public async Task FixAll_UpdatedFileNameInBanner() - { - await TestInRegularAndScriptAsync( -@" - - - {|FixAllInProject:|}using System; - -class Program1 -{ - static void Main() - { - } -} - - // This is the banner in Bar2.cs -// It goes over multiple lines. This line has Baz.cs -// The last line includes Bar2.cs - -class Program2 -{ -} - - -class Program3 -{ -} - - -", -@" - - - // This is the banner in Bar1.cs -// It goes over multiple lines. This line has Baz.cs -// The last line includes Bar1.cs - -using System; - -class Program1 -{ - static void Main() - { - } -} - - // This is the banner in Bar2.cs -// It goes over multiple lines. This line has Baz.cs -// The last line includes Bar2.cs - -class Program2 -{ -} - - // This is the banner in Bar3.cs -// It goes over multiple lines. This line has Baz.cs -// The last line includes Bar3.cs - - -class Program3 -{ -} - - -"); - } + public Task FixAll_UpdatedFileNameInBanner() + => TestInRegularAndScriptAsync( + """ + + + {|FixAllInProject:|}using System; + + class Program1 + { + static void Main() + { + } + } + + // This is the banner in Bar2.cs + // It goes over multiple lines. This line has Baz.cs + // The last line includes Bar2.cs + + class Program2 + { + } + + + class Program3 + { + } + + + + """, + """ + + + // This is the banner in Bar1.cs + // It goes over multiple lines. This line has Baz.cs + // The last line includes Bar1.cs + + using System; + + class Program1 + { + static void Main() + { + } + } + + // This is the banner in Bar2.cs + // It goes over multiple lines. This line has Baz.cs + // The last line includes Bar2.cs + + class Program2 + { + } + + // This is the banner in Bar3.cs + // It goes over multiple lines. This line has Baz.cs + // The last line includes Bar3.cs + + + class Program3 + { + } + + + + """); [Theory] [InlineData(FixAllScope.ContainingMember)] @@ -304,25 +304,26 @@ public async Task FixAllScopes_NotApplicable(FixAllScope fixAllScope) var fixAllScopeString = $"FixAllIn{fixAllScope}"; await TestMissingInRegularAndScriptAsync( -@$" - - - {{|{fixAllScopeString}:|}}using System; - -class Program1 -{{ - static void Main() - {{ - }} -}} - - // This is the banner - -class Program2 -{{ -}} - - -"); + $$""" + + + {|{{fixAllScopeString}}:|}using System; + + class Program1 + { + static void Main() + { + } + } + + // This is the banner + + class Program2 + { + } + + + + """); } } diff --git a/src/Features/CSharpTest/ConvertAnonymousType/ConvertAnonymousTypeToClassTests.cs b/src/Features/CSharpTest/ConvertAnonymousType/ConvertAnonymousTypeToClassTests.cs index 75b9a2ff0b8c8..8d07d6f0133ab 100644 --- a/src/Features/CSharpTest/ConvertAnonymousType/ConvertAnonymousTypeToClassTests.cs +++ b/src/Features/CSharpTest/ConvertAnonymousType/ConvertAnonymousTypeToClassTests.cs @@ -23,9 +23,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor => new CSharpConvertAnonymousTypeToClassCodeRefactoringProvider(); [Fact] - public async Task ConvertSingleAnonymousType() - { - var text = """ + public Task ConvertSingleAnonymousType() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -33,8 +32,7 @@ void Method() var t1 = [||]new { a = 1, b = 2 }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -69,14 +67,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact] - public async Task ConvertSingleAnonymousType_FileScopedNamespace() - { - var text = """ + public Task ConvertSingleAnonymousType_FileScopedNamespace() + => TestInRegularAndScriptAsync(""" namespace N; class Test @@ -86,8 +81,7 @@ void Method() var t1 = [||]new { a = 1, b = 2 }; } } - """; - var expected = """ + """, """ namespace N; class Test @@ -124,14 +118,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact] - public async Task ConvertSingleAnonymousType_CSharp9() - { - var text = """ + public Task ConvertSingleAnonymousType_CSharp9() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -139,8 +130,7 @@ void Method() var t1 = [||]new { a = 1, b = 2 }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -151,14 +141,11 @@ void Method() internal record NewRecord(int A, int B); - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); - } + """, options: this.PreferImplicitTypeWithInfo()); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39916")] - public async Task ConvertSingleAnonymousType_Explicit() - { - var text = """ + public Task ConvertSingleAnonymousType_Explicit() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -166,8 +153,7 @@ void Method() var t1 = [||]new { a = 1, b = 2 }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -202,14 +188,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, parseOptions: CSharp8); - } + """, parseOptions: CSharp8); [Fact] - public async Task OnEmptyAnonymousType() - { - await TestInRegularAndScriptAsync(""" + public Task OnEmptyAnonymousType() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -244,12 +227,10 @@ public override int GetHashCode() } } """, parseOptions: CSharp8); - } [Fact] - public async Task OnEmptyAnonymousType_CSharp9() - { - await TestInRegularAndScriptAsync(""" + public Task OnEmptyAnonymousType_CSharp9() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -270,12 +251,10 @@ void Method() internal record NewRecord(); """); - } [Fact] - public async Task OnSingleFieldAnonymousType() - { - await TestInRegularAndScriptAsync(""" + public Task OnSingleFieldAnonymousType() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -314,12 +293,10 @@ public override int GetHashCode() } } """, parseOptions: CSharp8); - } [Fact] - public async Task OnSingleFieldAnonymousType_CSharp9() - { - await TestInRegularAndScriptAsync(""" + public Task OnSingleFieldAnonymousType_CSharp9() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -340,12 +317,10 @@ void Method() internal record NewRecord(int A); """); - } [Fact] - public async Task ConvertSingleAnonymousTypeWithInferredName() - { - var text = """ + public Task ConvertSingleAnonymousTypeWithInferredName() + => TestInRegularAndScriptAsync(""" class Test { void Method(int b) @@ -353,8 +328,7 @@ void Method(int b) var t1 = [||]new { a = 1, b }; } } - """; - var expected = """ + """, """ class Test { void Method(int b) @@ -389,14 +363,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact] - public async Task ConvertSingleAnonymousTypeWithInferredName_CSharp9() - { - var text = """ + public Task ConvertSingleAnonymousTypeWithInferredName_CSharp9() + => TestInRegularAndScriptAsync(""" class Test { void Method(int b) @@ -404,8 +375,7 @@ void Method(int b) var t1 = [||]new { a = 1, b }; } } - """; - var expected = """ + """, """ class Test { void Method(int b) @@ -416,14 +386,11 @@ void Method(int b) internal record NewRecord(int A, int B); - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); - } + """, options: this.PreferImplicitTypeWithInfo()); [Fact] - public async Task ConvertMultipleInstancesInSameMethod() - { - var text = """ + public Task ConvertMultipleInstancesInSameMethod() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -432,8 +399,7 @@ void Method() var t2 = new { a = 3, b = 4 }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -469,14 +435,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact] - public async Task ConvertMultipleInstancesInSameMethod_CSharp9() - { - var text = """ + public Task ConvertMultipleInstancesInSameMethod_CSharp9() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -485,8 +448,7 @@ void Method() var t2 = new { a = 3, b = 4 }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -498,14 +460,11 @@ void Method() internal record NewRecord(int A, int B); - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); - } + """, options: this.PreferImplicitTypeWithInfo()); [Fact] - public async Task ConvertMultipleInstancesAcrossMethods() - { - var text = """ + public Task ConvertMultipleInstancesAcrossMethods() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -520,8 +479,7 @@ void Method2() var t2 = new { a = 3, b = 4 }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -563,14 +521,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact] - public async Task OnlyConvertMatchingTypesInSameMethod() - { - var text = """ + public Task OnlyConvertMatchingTypesInSameMethod() + => TestInRegularAndScriptAsync(""" class Test { void Method(int b) @@ -581,8 +536,7 @@ void Method(int b) var t4 = new { b = 5, a = 6 }; } } - """; - var expected = """ + """, """ class Test { void Method(int b) @@ -620,14 +574,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact] - public async Task TestFixAllMatchesInSingleMethod() - { - var text = """ + public Task TestFixAllMatchesInSingleMethod() + => TestInRegularAndScriptAsync(""" class Test { void Method(int b) @@ -638,8 +589,7 @@ void Method(int b) var t4 = new { b = 5, a = 6 }; } } - """; - var expected = """ + """, """ class Test { void Method(int b) @@ -677,14 +627,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact] - public async Task TestFixNotAcrossMethods() - { - var text = """ + public Task TestFixNotAcrossMethods() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -699,8 +646,7 @@ void Method2() var t2 = new { a = 3, b = 4 }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -742,14 +688,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact] - public async Task TestTrivia() - { - var text = """ + public Task TestTrivia() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -757,8 +700,7 @@ void Method() var t1 = /*1*/ [||]new /*2*/ { /*3*/ a /*4*/ = /*5*/ 1 /*7*/ , /*8*/ b /*9*/ = /*10*/ 2 /*11*/ } /*12*/ ; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -793,14 +735,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact] - public async Task TestTrivia2() - { - var text = """ + public Task TestTrivia2() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -809,8 +748,7 @@ void Method() var t2 = /*1*/ new /*2*/ { /*3*/ a /*4*/ = /*5*/ 1 /*7*/ , /*8*/ b /*9*/ = /*10*/ 2 /*11*/ } /*12*/ ; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -846,14 +784,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact] - public async Task NotIfReferencesAnonymousTypeInternally() - { - var text = """ + public Task NotIfReferencesAnonymousTypeInternally() + => TestMissingInRegularAndScriptAsync(""" class Test { void Method() @@ -861,15 +796,11 @@ void Method() var t1 = [||]new { a = 1, b = new { c = 1, d = 2 } }; } } - """; - - await TestMissingInRegularAndScriptAsync(text); - } + """); [Fact] - public async Task ConvertMultipleNestedInstancesInSameMethod() - { - var text = """ + public Task ConvertMultipleNestedInstancesInSameMethod() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -877,8 +808,7 @@ void Method() var t1 = [||]new { a = 1, b = (object)new { a = 1, b = default(object) } }; } } - """; - var expected = """ + """, """ using System.Collections.Generic; class Test @@ -915,14 +845,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact] - public async Task RenameAnnotationOnStartingPoint() - { - var text = """ + public Task RenameAnnotationOnStartingPoint() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -931,8 +858,7 @@ void Method() var t2 = [||]new { a = 3, b = 4 }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -968,14 +894,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact] - public async Task UpdateReferences() - { - var text = """ + public Task UpdateReferences() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -984,8 +907,7 @@ void Method() Console.WriteLine(t1.a + t1?.b); } } - """; - var expected = """ + """, """ class Test { void Method() @@ -1021,14 +943,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact] - public async Task CapturedTypeParameters() - { - var text = """ + public Task CapturedTypeParameters() + => TestInRegularAndScriptAsync(""" class Test where X : struct { void Method(List x, Y[] y) where Y : class, new() @@ -1036,8 +955,7 @@ class Test where X : struct var t1 = [||]new { a = x, b = y }; } } - """; - var expected = """ + """, """ class Test where X : struct { void Method(List x, Y[] y) where Y : class, new() @@ -1074,14 +992,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact] - public async Task CapturedTypeParameters_CSharp9() - { - var text = """ + public Task CapturedTypeParameters_CSharp9() + => TestInRegularAndScriptAsync(""" class Test where X : struct { void Method(List x, Y[] y) where Y : class, new() @@ -1089,8 +1004,7 @@ class Test where X : struct var t1 = [||]new { a = x, b = y }; } } - """; - var expected = """ + """, """ class Test where X : struct { void Method(List x, Y[] y) where Y : class, new() @@ -1103,14 +1017,11 @@ internal record NewRecord(List A, Y[] B) where X : struct where Y : class, new(); - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); - } + """, options: this.PreferImplicitTypeWithInfo()); [Fact] - public async Task NewTypeNameCollision() - { - var text = """ + public Task NewTypeNameCollision() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -1122,8 +1033,7 @@ void Method() class NewClass { } - """; - var expected = """ + """, """ class Test { void Method() @@ -1162,14 +1072,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact] - public async Task TestDuplicatedName() - { - var text = """ + public Task TestDuplicatedName() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -1177,8 +1084,7 @@ void Method() var t1 = [||]new { a = 1, a = 2 }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -1213,14 +1119,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact] - public async Task TestDuplicatedName_CSharp9() - { - var text = """ + public Task TestDuplicatedName_CSharp9() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -1228,8 +1131,7 @@ void Method() var t1 = [||]new { a = 1, a = 2 }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -1240,14 +1142,11 @@ void Method() internal record NewRecord(int A, int Item); - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); - } + """, options: this.PreferImplicitTypeWithInfo()); [Fact] - public async Task TestNewSelection() - { - var text = """ + public Task TestNewSelection() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -1255,8 +1154,7 @@ void Method() var t1 = [|new|] { a = 1, b = 2 }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -1291,14 +1189,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact] - public async Task TestInLambda1() - { - var text = """ + public Task TestInLambda1() + => TestInRegularAndScriptAsync(""" using System; class Test @@ -1312,8 +1207,7 @@ void Method() }; } } - """; - var expected = """ + """, """ using System; class Test @@ -1354,14 +1248,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact] - public async Task TestInLambda2() - { - var text = """ + public Task TestInLambda2() + => TestInRegularAndScriptAsync(""" using System; class Test @@ -1375,8 +1266,7 @@ void Method() }; } } - """; - var expected = """ + """, """ using System; class Test @@ -1417,14 +1307,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact] - public async Task TestInLocalFunction1() - { - var text = """ + public Task TestInLocalFunction1() + => TestInRegularAndScriptAsync(""" using System; class Test @@ -1438,8 +1325,7 @@ void Goo() } } } - """; - var expected = """ + """, """ using System; class Test @@ -1480,14 +1366,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact] - public async Task TestInLocalFunction2() - { - var text = """ + public Task TestInLocalFunction2() + => TestInRegularAndScriptAsync(""" using System; class Test @@ -1501,8 +1384,7 @@ void Goo() } } } - """; - var expected = """ + """, """ using System; class Test @@ -1543,14 +1425,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task ConvertSingleAnonymousTypeSelection1() - { - var text = """ + public Task ConvertSingleAnonymousTypeSelection1() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -1558,8 +1437,7 @@ void Method() var t1 = [|new { a = 1, b = 2 }|]; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -1594,14 +1472,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task ConvertSingleAnonymousTypeSelection2() - { - var text = """ + public Task ConvertSingleAnonymousTypeSelection2() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -1609,8 +1484,7 @@ void Method() [|var t1 = new { a = 1, b = 2 };|] } } - """; - var expected = """ + """, """ class Test { void Method() @@ -1645,14 +1519,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task ConvertSingleAnonymousTypeSelection3() - { - var text = """ + public Task ConvertSingleAnonymousTypeSelection3() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -1660,8 +1531,7 @@ void Method() var t1 = [|new { a = 1, b = 2 };|] } } - """; - var expected = """ + """, """ class Test { void Method() @@ -1696,14 +1566,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45747")] - public async Task ConvertOmittingTrailingComma() - { - var text = """ + public Task ConvertOmittingTrailingComma() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -1715,8 +1582,7 @@ void Method() }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -1754,14 +1620,11 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45747")] - public async Task ConvertOmittingTrailingCommaButPreservingTrivia() - { - var text = """ + public Task ConvertOmittingTrailingCommaButPreservingTrivia() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -1775,8 +1638,7 @@ void Method() }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -1816,7 +1678,5 @@ public override int GetHashCode() return hashCode; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); - } + """, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } diff --git a/src/Features/CSharpTest/ConvertAnonymousType/ConvertAnonymousTypeToTupleTests.cs b/src/Features/CSharpTest/ConvertAnonymousType/ConvertAnonymousTypeToTupleTests.cs index 8e897d29dc8a5..6b4c609eaa9ee 100644 --- a/src/Features/CSharpTest/ConvertAnonymousType/ConvertAnonymousTypeToTupleTests.cs +++ b/src/Features/CSharpTest/ConvertAnonymousType/ConvertAnonymousTypeToTupleTests.cs @@ -24,9 +24,8 @@ protected override ImmutableArray MassageActions(ImmutableArray FlattenActions(actions); [Fact] - public async Task ConvertSingleAnonymousType() - { - var text = """ + public Task ConvertSingleAnonymousType() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -34,8 +33,7 @@ void Method() var t1 = [||]new { a = 1, b = 2 }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -43,14 +41,11 @@ void Method() var t1 = (a: 1, b: 2); } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task NotOnEmptyAnonymousType() - { - await TestMissingInRegularAndScriptAsync(""" + public Task NotOnEmptyAnonymousType() + => TestMissingInRegularAndScriptAsync(""" class Test { void Method() @@ -59,12 +54,10 @@ void Method() } } """); - } [Fact] - public async Task NotOnSingleFieldAnonymousType() - { - await TestMissingInRegularAndScriptAsync(""" + public Task NotOnSingleFieldAnonymousType() + => TestMissingInRegularAndScriptAsync(""" class Test { void Method() @@ -73,12 +66,10 @@ void Method() } } """); - } [Fact] - public async Task ConvertSingleAnonymousTypeWithInferredName() - { - var text = """ + public Task ConvertSingleAnonymousTypeWithInferredName() + => TestInRegularAndScriptAsync(""" class Test { void Method(int b) @@ -86,8 +77,7 @@ void Method(int b) var t1 = [||]new { a = 1, b }; } } - """; - var expected = """ + """, """ class Test { void Method(int b) @@ -95,14 +85,11 @@ void Method(int b) var t1 = (a: 1, b); } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task ConvertMultipleInstancesInSameMethod() - { - var text = """ + public Task ConvertMultipleInstancesInSameMethod() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -111,8 +98,7 @@ void Method() var t2 = new { a = 3, b = 4 }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -121,14 +107,11 @@ void Method() var t2 = (a: 3, b: 4); } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task ConvertMultipleInstancesAcrossMethods() - { - var text = """ + public Task ConvertMultipleInstancesAcrossMethods() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -143,8 +126,7 @@ void Method2() var t2 = new { a = 3, b = 4 }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -159,14 +141,11 @@ void Method2() var t2 = new { a = 3, b = 4 }; } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task OnlyConvertMatchingTypesInSameMethod() - { - var text = """ + public Task OnlyConvertMatchingTypesInSameMethod() + => TestInRegularAndScriptAsync(""" class Test { void Method(int b) @@ -177,8 +156,7 @@ void Method(int b) var t4 = new { b = 5, a = 6 }; } } - """; - var expected = """ + """, """ class Test { void Method(int b) @@ -189,14 +167,11 @@ void Method(int b) var t4 = new { b = 5, a = 6 }; } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task TestFixAllInSingleMethod() - { - var text = """ + public Task TestFixAllInSingleMethod() + => TestInRegularAndScriptAsync(""" class Test { void Method(int b) @@ -207,8 +182,7 @@ void Method(int b) var t4 = new { b = 5, a = 6 }; } } - """; - var expected = """ + """, """ class Test { void Method(int b) @@ -219,14 +193,11 @@ void Method(int b) var t4 = (b: 5, a: 6); } } - """; - await TestInRegularAndScriptAsync(text, expected, index: 1); - } + """, index: 1); [Fact] - public async Task TestFixNotAcrossMethods() - { - var text = """ + public Task TestFixNotAcrossMethods() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -241,8 +212,7 @@ void Method2() var t2 = new { a = 3, b = 4 }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -257,14 +227,11 @@ void Method2() var t2 = new { a = 3, b = 4 }; } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task TestTrivia() - { - var text = """ + public Task TestTrivia() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -272,8 +239,7 @@ void Method() var t1 = /*1*/ [||]new /*2*/ { /*3*/ a /*4*/ = /*5*/ 1 /*7*/ , /*8*/ b /*9*/ = /*10*/ 2 /*11*/ } /*12*/ ; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -281,14 +247,11 @@ void Method() var t1 = /*1*/ ( /*3*/ a /*4*/ : /*5*/ 1 /*7*/ , /*8*/ b /*9*/ : /*10*/ 2 /*11*/ ) /*12*/ ; } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task TestFixAllNestedTypes() - { - var text = """ + public Task TestFixAllNestedTypes() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -296,8 +259,7 @@ void Method() var t1 = [||]new { a = 1, b = new { c = 1, d = 2 } }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -305,14 +267,11 @@ void Method() var t1 = (a: 1, b: (c: 1, d: 2)); } } - """; - await TestInRegularAndScriptAsync(text, expected, index: 1); - } + """, index: 1); [Fact] - public async Task ConvertMultipleNestedInstancesInSameMethod() - { - var text = """ + public Task ConvertMultipleNestedInstancesInSameMethod() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -320,8 +279,7 @@ void Method() var t1 = [||]new { a = 1, b = (object)new { a = 1, b = default(object) } }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -329,14 +287,11 @@ void Method() var t1 = (a: 1, b: (object)(a: 1, b: default(object))); } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task ConvertWithLambda1() - { - var text = """ + public Task ConvertWithLambda1() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -348,8 +303,7 @@ void Method() }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -361,14 +315,11 @@ void Method() }; } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task ConvertWithLambda2() - { - var text = """ + public Task ConvertWithLambda2() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -380,8 +331,7 @@ void Method() }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -393,14 +343,11 @@ void Method() }; } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task ConvertWithLocalFunction1() - { - var text = """ + public Task ConvertWithLocalFunction1() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -412,8 +359,7 @@ void func() } } } - """; - var expected = """ + """, """ class Test { void Method() @@ -425,14 +371,11 @@ void func() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task ConvertWithLocalFunction2() - { - var text = """ + public Task ConvertWithLocalFunction2() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -444,8 +387,7 @@ void func() } } } - """; - var expected = """ + """, """ class Test { void Method() @@ -457,14 +399,11 @@ void func() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task TestIncompleteAnonymousType() - { - var text = """ + public Task TestIncompleteAnonymousType() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -472,8 +411,7 @@ void Method() var t1 = [||]new { a = , b = }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -481,14 +419,11 @@ void Method() var t1 = (a: , b: ); } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34749")] - public async Task NotInExpressionTree() - { - await TestMissingInRegularAndScriptAsync(""" + public Task NotInExpressionTree() + => TestMissingInRegularAndScriptAsync(""" using System.Linq.Expressions; class C @@ -500,12 +435,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75950")] - public async Task RemoveTrailingComma() - { - var text = """ + public Task RemoveTrailingComma() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -513,8 +446,7 @@ void Method() var t1 = [||]new { a = 1, b = 2, }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -522,14 +454,11 @@ void Method() var t1 = (a: 1, b: 2); } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50470")] - public async Task TestMultiLine1() - { - var text = """ + public Task TestMultiLine1() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -544,8 +473,7 @@ void Method() }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -559,14 +487,11 @@ void Method() }; } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50470")] - public async Task TestMultiLine2() - { - var text = """ + public Task TestMultiLine2() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -581,8 +506,7 @@ void Method() }; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -596,7 +520,5 @@ void Method() }; } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); } diff --git a/src/Features/CSharpTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests.cs b/src/Features/CSharpTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests.cs index 1884ab2379f76..c4f2f631e7c1e 100644 --- a/src/Features/CSharpTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests.cs +++ b/src/Features/CSharpTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests.cs @@ -25,15 +25,13 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor [Theory] [InlineData("set"), InlineData("init")] [WorkItem("https://github.com/dotnet/roslyn/issues/48133")] - public async Task SimpleAutoPropertyTest(string setter) - { - var text = $$""" + public Task SimpleAutoPropertyTest(string setter) + => TestInRegularAndScriptAsync($$""" class TestClass { public int G[||]oo { get; {{setter}}; } } - """; - var expected = $$""" + """, $$""" class TestClass { private int goo; @@ -50,21 +48,17 @@ public int Goo } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); - } + """, options: DoNotPreferExpressionBodiedAccessors); [Fact] - public async Task ExtraLineAfterProperty() - { - var text = """ + public Task ExtraLineAfterProperty() + => TestInRegularAndScriptAsync(""" class TestClass { public int G[||]oo { get; set; } } - """; - var expected = """ + """, """ class TestClass { private int goo; @@ -82,20 +76,16 @@ public int Goo } } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); - } + """, options: DoNotPreferExpressionBodiedAccessors); [Fact] - public async Task WithInitialValue() - { - var text = """ + public Task WithInitialValue() + => TestInRegularAndScriptAsync(""" class TestClass { public int G[||]oo { get; set; } = 2 } - """; - var expected = """ + """, """ class TestClass { private int goo = 2; @@ -112,21 +102,17 @@ public int Goo } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); - } + """, options: DoNotPreferExpressionBodiedAccessors); [Fact] - public async Task WithCalculatedInitialValue() - { - var text = """ + public Task WithCalculatedInitialValue() + => TestInRegularAndScriptAsync(""" class TestClass { const int num = 345; public int G[||]oo { get; set; } = 2*num } - """; - var expected = """ + """, """ class TestClass { const int num = 345; @@ -144,20 +130,16 @@ public int Goo } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); - } + """, options: DoNotPreferExpressionBodiedAccessors); [Fact] - public async Task WithPrivateSetter() - { - var text = """ + public Task WithPrivateSetter() + => TestInRegularAndScriptAsync(""" class TestClass { public int G[||]oo { get; private set; } } - """; - var expected = """ + """, """ class TestClass { private int goo; @@ -174,22 +156,18 @@ private set } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); - } + """, options: DoNotPreferExpressionBodiedAccessors); [Fact] - public async Task WithFieldNameAlreadyUsed() - { - var text = """ + public Task WithFieldNameAlreadyUsed() + => TestInRegularAndScriptAsync(""" class TestClass { private int goo; public int G[||]oo { get; private set; } } - """; - var expected = """ + """, """ class TestClass { private int goo; @@ -207,22 +185,18 @@ private set } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); - } + """, options: DoNotPreferExpressionBodiedAccessors); [Fact] - public async Task WithComments() - { - var text = """ + public Task WithComments() + => TestInRegularAndScriptAsync(""" class TestClass { // Comments before public int G[||]oo { get; private set; } //Comments during //Comments after } - """; - var expected = """ + """, """ class TestClass { private int goo; @@ -241,54 +215,43 @@ private set } //Comments during //Comments after } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); - } + """, options: DoNotPreferExpressionBodiedAccessors); [Fact] - public async Task WithExpressionBody() - { - var text = """ + public Task WithExpressionBody() + => TestInRegularAndScriptAsync(""" class TestClass { public int G[||]oo { get; set; } } - """; - var expected = """ + """, """ class TestClass { private int goo; public int Goo { get => goo; set => goo = value; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiedAccessorsWhenPossible); - } + """, options: PreferExpressionBodiedAccessorsWhenPossible); [Fact] - public async Task WithExpressionBodyWhenOnSingleLine() - { - var text = """ + public Task WithExpressionBodyWhenOnSingleLine() + => TestInRegularAndScriptAsync(""" class TestClass { public int G[||]oo { get; set; } } - """; - var expected = """ + """, """ class TestClass { private int goo; public int Goo { get => goo; set => goo = value; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiedAccessorsWhenOnSingleLine); - } + """, options: PreferExpressionBodiedAccessorsWhenOnSingleLine); [Fact] - public async Task WithExpressionBodyWhenOnSingleLine2() - { - var text = """ + public Task WithExpressionBodyWhenOnSingleLine2() + => TestInRegularAndScriptAsync(""" class TestClass { public int G[||]oo @@ -297,8 +260,7 @@ public int G[||]oo set; } } - """; - var expected = """ + """, """ class TestClass { private int goo; @@ -309,40 +271,32 @@ public int Goo set => goo = value; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiedAccessorsWhenOnSingleLine); - } + """, options: PreferExpressionBodiedAccessorsWhenOnSingleLine); [Fact] - public async Task WithExpressionBodyWithTrivia() - { - var text = """ + public Task WithExpressionBodyWithTrivia() + => TestInRegularAndScriptAsync(""" class TestClass { public int G[||]oo { get /* test */ ; set /* test2 */ ; } } - """; - var expected = """ + """, """ class TestClass { private int goo; public int Goo { get /* test */ => goo; set /* test2 */ => goo = value; } } - """; - await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiedAccessorsWhenPossible); - } + """, options: PreferExpressionBodiedAccessorsWhenPossible); [Fact] - public async Task WithPropertyOpenBraceOnSameLine() - { - var text = """ + public Task WithPropertyOpenBraceOnSameLine() + => TestInRegularAndScriptAsync(""" class TestClass { public int G[||]oo { get; set; } } - """; - var expected = """ + """, """ class TestClass { private int goo; @@ -358,20 +312,16 @@ public int Goo { } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessorsAndPropertyOpenBraceOnSameLine); - } + """, options: DoNotPreferExpressionBodiedAccessorsAndPropertyOpenBraceOnSameLine); [Fact] - public async Task WithAccessorOpenBraceOnSameLine() - { - var text = """ + public Task WithAccessorOpenBraceOnSameLine() + => TestInRegularAndScriptAsync(""" class TestClass { public int G[||]oo { get; set; } } - """; - var expected = """ + """, """ class TestClass { private int goo; @@ -386,20 +336,16 @@ public int Goo } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessorsAndAccessorOpenBraceOnSameLine); - } + """, options: DoNotPreferExpressionBodiedAccessorsAndAccessorOpenBraceOnSameLine); [Fact] - public async Task StaticProperty() - { - var text = """ + public Task StaticProperty() + => TestInRegularAndScriptAsync(""" class TestClass { public static int G[||]oo { get; set; } } - """; - var expected = """ + """, """ class TestClass { private static int goo; @@ -416,20 +362,16 @@ public static int Goo } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); - } + """, options: DoNotPreferExpressionBodiedAccessors); [Fact] - public async Task ProtectedProperty() - { - var text = """ + public Task ProtectedProperty() + => TestInRegularAndScriptAsync(""" class TestClass { protected int G[||]oo { get; set; } } - """; - var expected = """ + """, """ class TestClass { private int goo; @@ -446,20 +388,16 @@ protected int Goo } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); - } + """, options: DoNotPreferExpressionBodiedAccessors); [Fact] - public async Task InternalProperty() - { - var text = """ + public Task InternalProperty() + => TestInRegularAndScriptAsync(""" class TestClass { internal int G[||]oo { get; set; } } - """; - var expected = """ + """, """ class TestClass { private int goo; @@ -476,21 +414,17 @@ internal int Goo } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); - } + """, options: DoNotPreferExpressionBodiedAccessors); [Fact] - public async Task WithAttributes() - { - var text = """ + public Task WithAttributes() + => TestInRegularAndScriptAsync(""" class TestClass { [A] public int G[||]oo { get; set; } } - """; - var expected = """ + """, """ class TestClass { private int goo; @@ -508,14 +442,11 @@ public int Goo } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); - } + """, options: DoNotPreferExpressionBodiedAccessors); [Fact] - public async Task CommentsInAccessors() - { - var text = """ + public Task CommentsInAccessors() + => TestInRegularAndScriptAsync(""" class TestClass { /// @@ -523,8 +454,7 @@ class TestClass /// public int Testg[||]oo { /* test1 */ get /* test2 */; /* test3 */ set /* test4 */; /* test5 */ } /* test6 */ } - """; - var expected = """ + """, """ class TestClass { private int testgoo; @@ -544,14 +474,11 @@ public int Testgoo } /* test5 */ } /* test6 */ } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); - } + """, options: DoNotPreferExpressionBodiedAccessors); [Fact] - public async Task OverrideProperty() - { - var text = """ + public Task OverrideProperty() + => TestInRegularAndScriptAsync(""" class MyBaseClass { public virtual string Name { get; set; } @@ -561,8 +488,7 @@ class MyDerivedClass : MyBaseClass { public override string N[||]ame {get; set;} } - """; - var expected = """ + """, """ class MyBaseClass { public virtual string Name { get; set; } @@ -584,20 +510,16 @@ public override string Name } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); - } + """, options: DoNotPreferExpressionBodiedAccessors); [Fact] - public async Task SealedProperty() - { - var text = """ + public Task SealedProperty() + => TestInRegularAndScriptAsync(""" class MyClass { public sealed string N[||]ame {get; set;} } - """; - var expected = """ + """, """ class MyClass { private string name; @@ -614,14 +536,11 @@ public sealed string Name } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); - } + """, options: DoNotPreferExpressionBodiedAccessors); [Fact] - public async Task VirtualProperty() - { - var text = """ + public Task VirtualProperty() + => TestInRegularAndScriptAsync(""" class MyBaseClass { public virtual string N[||]ame { get; set; } @@ -631,8 +550,7 @@ class MyDerivedClass : MyBaseClass { public override string Name {get; set;} } - """; - var expected = """ + """, """ class MyBaseClass { private string name; @@ -654,20 +572,16 @@ class MyDerivedClass : MyBaseClass { public override string Name {get; set;} } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); - } + """, options: DoNotPreferExpressionBodiedAccessors); [Fact] - public async Task PrivateProperty() - { - var text = """ + public Task PrivateProperty() + => TestInRegularAndScriptAsync(""" class MyClass { private string N[||]ame { get; set; } } - """; - var expected = """ + """, """ class MyClass { private string name; @@ -684,14 +598,11 @@ private string Name } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); - } + """, options: DoNotPreferExpressionBodiedAccessors); [Fact] - public async Task AbstractProperty() - { - var text = """ + public Task AbstractProperty() + => TestMissingAsync(""" class MyBaseClass { public abstract string N[||]ame { get; set; } @@ -701,32 +612,25 @@ class MyDerivedClass : MyBaseClass { public override string Name {get; set;} } - """; - await TestMissingAsync(text); - } + """); [Fact] - public async Task ExternProperty() - { - var text = """ + public Task ExternProperty() + => TestMissingAsync(""" class MyBaseClass { extern string N[||]ame { get; set; } } - """; - await TestMissingAsync(text); - } + """); [Fact] - public async Task GetterOnly() - { - var text = """ + public Task GetterOnly() + => TestInRegularAndScriptAsync(""" class TestClass { public int G[||]oo { get;} } - """; - var expected = """ + """, """ class TestClass { private readonly int goo; @@ -739,53 +643,42 @@ public int Goo } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); - } + """, options: DoNotPreferExpressionBodiedAccessors); [Fact] - public async Task GetterOnlyExpressionBodies() - { - var text = """ + public Task GetterOnlyExpressionBodies() + => TestInRegularAndScriptAsync(""" class TestClass { public int G[||]oo { get;} } - """; - var expected = """ + """, """ class TestClass { private readonly int goo; public int Goo => goo; } - """; - await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiesOnAccessorsAndMethods); - } + """, options: PreferExpressionBodiesOnAccessorsAndMethods); [Fact] - public async Task GetterOnlyExpressionBodies_Field() - { - var text = """ + public Task GetterOnlyExpressionBodies_Field() + => TestInRegularAndScriptAsync( + """ class TestClass { public int G[||]oo { get;} } - """; - var expected = """ + """, """ class TestClass { public int Goo => field; } - """; - await TestInRegularAndScriptAsync( - text, expected, options: PreferExpressionBodiesOnAccessorsAndMethods, index: 1, parseOptions: CSharp14); - } + """, options: PreferExpressionBodiesOnAccessorsAndMethods, index: 1, parseOptions: CSharp14); [Fact] - public async Task SetterOnly() - { - var text = """ + public Task SetterOnly() + => TestMissingAsync(""" class TestClass { public int G[||]oo @@ -793,34 +686,27 @@ public int G[||]oo set {} } } - """; - await TestMissingAsync(text); - } + """); [Fact] - public async Task ExpressionBodiedAccessors() - { - var text = """ + public Task ExpressionBodiedAccessors() + => TestMissingAsync(""" class TestClass { private int testgoo; public int testg[||]oo {get => testgoo; set => testgoo = value; } } - """; - await TestMissingAsync(text); - } + """); [Fact] - public async Task CursorAtBeginning() - { - var text = """ + public Task CursorAtBeginning() + => TestInRegularAndScriptAsync(""" class TestClass { [||]public int Goo { get; set; } } - """; - var expected = """ + """, """ class TestClass { private int goo; @@ -837,20 +723,16 @@ public int Goo } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); - } + """, options: DoNotPreferExpressionBodiedAccessors); [Fact] - public async Task CursorAtEnd() - { - var text = """ + public Task CursorAtEnd() + => TestInRegularAndScriptAsync(""" class TestClass { public int Goo[||] { get; set; } } - """; - var expected = """ + """, """ class TestClass { private int goo; @@ -867,32 +749,25 @@ public int Goo } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); - } + """, options: DoNotPreferExpressionBodiedAccessors); [Fact] - public async Task CursorOnAccessors() - { - var text = """ + public Task CursorOnAccessors() + => TestMissingAsync(""" class TestClass { public int Goo { g[||]et; set; } } - """; - await TestMissingAsync(text); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task CursorInType() - { - var text = """ + public Task CursorInType() + => TestInRegularAndScriptAsync(""" class TestClass { public in[||]t Goo { get; set; } } - """; - var expected = """ + """, """ class TestClass { private int goo; @@ -909,20 +784,16 @@ public int Goo } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); - } + """, options: DoNotPreferExpressionBodiedAccessors); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task SelectionWhole() - { - var text = """ + public Task SelectionWhole() + => TestInRegularAndScriptAsync(""" class TestClass { [|public int Goo { get; set; }|] } - """; - var expected = """ + """, """ class TestClass { private int goo; @@ -939,20 +810,16 @@ public int Goo } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); - } + """, options: DoNotPreferExpressionBodiedAccessors); [Fact] - public async Task SelectionName() - { - var text = """ + public Task SelectionName() + => TestInRegularAndScriptAsync(""" class TestClass { public int [|Goo|] { get; set; } } - """; - var expected = """ + """, """ class TestClass { private int goo; @@ -969,44 +836,34 @@ public int Goo } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); - } + """, options: DoNotPreferExpressionBodiedAccessors); [Fact] - public async Task MoreThanOneGetter() - { - var text = """ + public Task MoreThanOneGetter() + => TestMissingAsync(""" class TestClass { public int Goo { g[||]et; get; } } - """; - await TestMissingAsync(text); - } + """); [Fact] - public async Task MoreThanOneSetter() - { - var text = """ + public Task MoreThanOneSetter() + => TestMissingAsync(""" class TestClass { public int Goo { get; s[||]et; set; } } - """; - await TestMissingAsync(text); - } + """); [Fact] - public async Task CustomFieldName() - { - var text = """ + public Task CustomFieldName() + => TestInRegularAndScriptAsync(""" class TestClass { public int G[||]oo { get; set; } } - """; - var expected = """ + """, """ class TestClass { private int testingGoo; @@ -1023,20 +880,16 @@ public int Goo } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: UseCustomFieldName); - } + """, options: UseCustomFieldName); [Fact, WorkItem(28013, "https://github.com/dotnet/roslyn/issues/26992")] - public async Task UnderscorePrefixedFieldName() - { - var text = """ + public Task UnderscorePrefixedFieldName() + => TestInRegularAndScriptAsync(""" class TestClass { public int G[||]oo { get; set; } } - """; - var expected = """ + """, """ class TestClass { private int _goo; @@ -1053,41 +906,33 @@ public int Goo } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: UseUnderscorePrefixedFieldName); - } + """, options: UseUnderscorePrefixedFieldName); [Fact, WorkItem(28013, "https://github.com/dotnet/roslyn/issues/26992")] [WorkItem("https://github.com/dotnet/roslyn/issues/30208")] - public async Task PropertyNameEqualsToClassNameExceptFirstCharCasingWhichCausesFieldNameCollisionByDefault() - { - var text = """ + public Task PropertyNameEqualsToClassNameExceptFirstCharCasingWhichCausesFieldNameCollisionByDefault() + => TestInRegularAndScriptAsync(""" class stranger { public int S[||]tranger { get; set; } } - """; - var expected = """ + """, """ class stranger { private int stranger1; public int Stranger { get => stranger1; set => stranger1 = value; } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task NonStaticPropertyWithCustomStaticFieldName() - { - var text = """ + public Task NonStaticPropertyWithCustomStaticFieldName() + => TestInRegularAndScriptAsync(""" class TestClass { public int G[||]oo { get; set; } } - """; - var expected = """ + """, """ class TestClass { private int goo; @@ -1104,20 +949,16 @@ public int Goo } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: UseCustomStaticFieldName); - } + """, options: UseCustomStaticFieldName); [Fact] - public async Task StaticPropertyWithCustomStaticFieldName() - { - var text = """ + public Task StaticPropertyWithCustomStaticFieldName() + => TestInRegularAndScriptAsync(""" class TestClass { public static int G[||]oo { get; set; } } - """; - var expected = """ + """, """ class TestClass { private static int staticfieldtestGoo; @@ -1134,32 +975,25 @@ public static int Goo } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: UseCustomStaticFieldName); - } + """, options: UseCustomStaticFieldName); [Fact] - public async Task InInterface() - { - var text = """ + public Task InInterface() + => TestMissingAsync(""" interface IGoo { public int Goo { get; s[||]et; } } - """; - await TestMissingAsync(text); - } + """); [Fact] - public async Task InStruct() - { - var text = """ + public Task InStruct() + => TestInRegularAndScriptAsync(""" struct goo { public int G[||]oo { get; set; } } - """; - var expected = """ + """, """ struct goo { private int goo1; @@ -1176,14 +1010,11 @@ public int Goo } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); - } + """, options: DoNotPreferExpressionBodiedAccessors); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22146")] - public async Task PartialClasses() - { - var text = """ + public Task PartialClasses() + => TestInRegularAndScriptAsync(""" partial class Program { int P { get; set; } @@ -1193,8 +1024,7 @@ partial class Program { int [||]Q { get; set; } } - """; - var expected = """ + """, """ partial class Program { int P { get; set; } @@ -1206,9 +1036,7 @@ partial class Program int Q { get => q; set => q = value; } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22146")] public async Task PartialClassInSeparateFiles1() @@ -1225,15 +1053,6 @@ partial class Program int Q { get; set; } } """; - var file1AfterRefactor = """ - partial class Program - { - private int p; - - int P { get => p; set => p = value; } - } - """; - var xmlString = string.Format(""" @@ -1248,7 +1067,14 @@ partial class Program var (_, action) = await GetCodeActionsAsync(testWorkspace); await TestActionAsync( testWorkspace, - file1AfterRefactor, + """ + partial class Program + { + private int p; + + int P { get => p; set => p = value; } + } + """, action, conflictSpans: [], renameSpans: [], @@ -1272,15 +1098,6 @@ partial class Program int Q[||] { get; set; } } """; - var file2AfterRefactor = """ - partial class Program - { - private int q; - - int Q { get => q; set => q = value; } - } - """; - var xmlString = string.Format(""" @@ -1295,7 +1112,14 @@ partial class Program var (_, action) = await GetCodeActionsAsync(testWorkspace); await TestActionAsync( testWorkspace, - file2AfterRefactor, + """ + partial class Program + { + private int q; + + int Q { get => q; set => q = value; } + } + """, action, conflictSpans: [], renameSpans: [], @@ -1318,9 +1142,8 @@ namespace NS } [Fact] - public async Task NullBackingField() - { - await TestInRegularAndScriptAsync( + public Task NullBackingField() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -1339,12 +1162,10 @@ class Program string? Name { get => name; set => name = value; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29021")] - public async Task ConstructorInitializerIndentation() - { - await TestInRegularAndScriptAsync( + public Task ConstructorInitializerIndentation() + => TestInRegularAndScriptAsync( """ internal class EvaluationCommandLineHandler { @@ -1372,12 +1193,10 @@ public EvaluationCommandLineHandler(UnconfiguredProject project) public Dictionary> Files => files; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75547")] - public async Task ConvertField1() - { - await TestInRegularAndScriptAsync( + public Task ConvertField1() + => TestInRegularAndScriptAsync( """ class Class { @@ -1413,20 +1232,17 @@ void M(int i) { } } """, parseOptions: CSharp14); - } [Theory] [InlineData("set"), InlineData("init")] [WorkItem("https://github.com/dotnet/roslyn/issues/76899")] - public async Task ProduceFieldBackedProperty(string setter) - { - var text = $$""" + public Task ProduceFieldBackedProperty(string setter) + => TestInRegularAndScriptAsync($$""" class TestClass { public int G[||]oo { get; {{setter}}; } } - """; - var expected = $$""" + """, $$""" class TestClass { public int Goo @@ -1441,22 +1257,18 @@ public int Goo } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors, index: 1, parseOptions: CSharp14); - } + """, options: DoNotPreferExpressionBodiedAccessors, index: 1, parseOptions: CSharp14); [Theory] [InlineData("set"), InlineData("init")] [WorkItem("https://github.com/dotnet/roslyn/issues/76992")] - public async Task ProduceFieldBackedProperty2(string setter) - { - var text = $$""" + public Task ProduceFieldBackedProperty2(string setter) + => TestInRegularAndScriptAsync($$""" class TestClass { public int G[||]oo { get; {{setter}}; } = 0; } - """; - var expected = $$""" + """, $$""" class TestClass { public int Goo @@ -1471,7 +1283,5 @@ public int Goo } } = 0; } - """; - await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors, index: 1, parseOptions: CSharp14); - } + """, options: DoNotPreferExpressionBodiedAccessors, index: 1, parseOptions: CSharp14); } diff --git a/src/Features/CSharpTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests_OptionSets.cs b/src/Features/CSharpTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests_OptionSets.cs index 9a986b7cd4c31..6ab1e4fde3dc1 100644 --- a/src/Features/CSharpTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests_OptionSets.cs +++ b/src/Features/CSharpTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests_OptionSets.cs @@ -140,7 +140,7 @@ private static NamingStylePreferences CreateCustomStaticFieldNamingStylePreferen "Name", [new SymbolKindOrTypeKind(SymbolKind.Field)], accessibilityList: default, - [new ModifierKind(DeclarationModifiers.Static)]); + [new ModifierKind(Modifiers.Static)]); var namingStyle = new NamingStyle( Guid.NewGuid(), diff --git a/src/Features/CSharpTest/ConvertBetweenRegularAndVerbatimString/ConvertBetweenRegularAndVerbatimInterpolatedStringTests.cs b/src/Features/CSharpTest/ConvertBetweenRegularAndVerbatimString/ConvertBetweenRegularAndVerbatimInterpolatedStringTests.cs index ab2328d254a3e..798eeda61bb86 100644 --- a/src/Features/CSharpTest/ConvertBetweenRegularAndVerbatimString/ConvertBetweenRegularAndVerbatimInterpolatedStringTests.cs +++ b/src/Features/CSharpTest/ConvertBetweenRegularAndVerbatimString/ConvertBetweenRegularAndVerbatimInterpolatedStringTests.cs @@ -20,9 +20,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor => new ConvertBetweenRegularAndVerbatimInterpolatedStringCodeRefactoringProvider(); [Fact] - public async Task EmptyRegularString() - { - await TestMissingAsync(""" + public Task EmptyRegularString() + => TestMissingAsync(""" class Test { void Method() @@ -31,12 +30,10 @@ void Method() } } """); - } [Fact] - public async Task RegularStringWithMissingCloseQuote() - { - await TestMissingAsync(""" + public Task RegularStringWithMissingCloseQuote() + => TestMissingAsync(""" class Test { void Method() @@ -45,12 +42,10 @@ void Method() } } """); - } [Fact] - public async Task VerbatimStringWithMissingCloseQuote() - { - await TestMissingAsync(""" + public Task VerbatimStringWithMissingCloseQuote() + => TestMissingAsync(""" class Test { void Method() @@ -59,12 +54,10 @@ void Method() } } """); - } [Fact] - public async Task EmptyVerbatimString() - { - await TestInRegularAndScript1Async(""" + public Task EmptyVerbatimString() + => TestInRegularAndScript1Async(""" class Test { void Method() @@ -82,12 +75,10 @@ void Method() } } """); - } [Fact] - public async Task TestLeadingAndTrailingTrivia() - { - await TestInRegularAndScript1Async(""" + public Task TestLeadingAndTrailingTrivia() + => TestInRegularAndScript1Async(""" class Test { void Method() @@ -109,12 +100,10 @@ void Method() } } """); - } [Fact] - public async Task RegularStringWithBasicText() - { - await TestMissingAsync(""" + public Task RegularStringWithBasicText() + => TestMissingAsync(""" class Test { void Method() @@ -123,12 +112,10 @@ void Method() } } """); - } [Fact] - public async Task VerbatimStringWithBasicText() - { - await TestInRegularAndScript1Async(""" + public Task VerbatimStringWithBasicText() + => TestInRegularAndScript1Async(""" class Test { void Method() @@ -146,12 +133,10 @@ void Method() } } """); - } [Fact] - public async Task RegularStringWithUnicodeEscape() - { - await TestMissingAsync(""" + public Task RegularStringWithUnicodeEscape() + => TestMissingAsync(""" class Test { void Method() @@ -160,12 +145,10 @@ void Method() } } """); - } [Fact] - public async Task RegularStringWithEscapedNewLine() - { - await TestInRegularAndScript1Async(""" + public Task RegularStringWithEscapedNewLine() + => TestInRegularAndScript1Async(""" class Test { void Method() @@ -184,12 +167,10 @@ void Method() } } """); - } [Fact] - public async Task VerbatimStringWithNewLine() - { - await TestInRegularAndScript1Async(""" + public Task VerbatimStringWithNewLine() + => TestInRegularAndScript1Async(""" class Test { void Method() @@ -208,12 +189,10 @@ void Method() } } """); - } [Fact] - public async Task RegularStringWithEscapedNull() - { - await TestMissingAsync(""" + public Task RegularStringWithEscapedNull() + => TestMissingAsync(""" class Test { void Method() @@ -222,12 +201,10 @@ void Method() } } """); - } [Fact] - public async Task RegularStringWithEscapedQuote() - { - await TestInRegularAndScript1Async(""" + public Task RegularStringWithEscapedQuote() + => TestInRegularAndScript1Async(""" class Test { void Method() @@ -245,12 +222,10 @@ void Method() } } """); - } [Fact] - public async Task VerbatimStringWithEscapedQuote() - { - await TestInRegularAndScript1Async(""" + public Task VerbatimStringWithEscapedQuote() + => TestInRegularAndScript1Async(""" class Test { void Method() @@ -268,12 +243,10 @@ void Method() } } """); - } [Fact] - public async Task RegularStringWithEscapedQuoteAndMultipleParts() - { - await TestInRegularAndScript1Async(""" + public Task RegularStringWithEscapedQuoteAndMultipleParts() + => TestInRegularAndScript1Async(""" class Test { void Method() @@ -291,12 +264,10 @@ void Method() } } """); - } [Fact] - public async Task VerbatimStringWithEscapedQuoteAndMultipleParts() - { - await TestInRegularAndScript1Async(""" + public Task VerbatimStringWithEscapedQuoteAndMultipleParts() + => TestInRegularAndScript1Async(""" class Test { void Method() @@ -314,12 +285,10 @@ void Method() } } """); - } [Fact] - public async Task EscapedCurlyBracesInRegularString() - { - await TestInRegularAndScript1Async(""" + public Task EscapedCurlyBracesInRegularString() + => TestInRegularAndScript1Async(""" class Test { void Method() @@ -338,12 +307,10 @@ void Method() } } """); - } [Fact] - public async Task EscapedCurlyBracesInVerbatimString() - { - await TestInRegularAndScript1Async(""" + public Task EscapedCurlyBracesInVerbatimString() + => TestInRegularAndScript1Async(""" class Test { void Method() @@ -362,5 +329,4 @@ void Method() } } """); - } } diff --git a/src/Features/CSharpTest/ConvertBetweenRegularAndVerbatimString/ConvertBetweenRegularAndVerbatimStringTests.cs b/src/Features/CSharpTest/ConvertBetweenRegularAndVerbatimString/ConvertBetweenRegularAndVerbatimStringTests.cs index 0d8fc62ecf44f..09f44404cfc76 100644 --- a/src/Features/CSharpTest/ConvertBetweenRegularAndVerbatimString/ConvertBetweenRegularAndVerbatimStringTests.cs +++ b/src/Features/CSharpTest/ConvertBetweenRegularAndVerbatimString/ConvertBetweenRegularAndVerbatimStringTests.cs @@ -20,9 +20,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor => new ConvertBetweenRegularAndVerbatimStringCodeRefactoringProvider(); [Fact] - public async Task EmptyRegularString() - { - await TestMissingAsync(""" + public Task EmptyRegularString() + => TestMissingAsync(""" class Test { void Method() @@ -31,12 +30,10 @@ void Method() } } """); - } [Fact] - public async Task RegularStringWithMissingCloseQuote() - { - await TestMissingAsync(""" + public Task RegularStringWithMissingCloseQuote() + => TestMissingAsync(""" class Test { void Method() @@ -45,12 +42,10 @@ void Method() } } """); - } [Fact] - public async Task VerbatimStringWithMissingCloseQuote() - { - await TestMissingAsync(""" + public Task VerbatimStringWithMissingCloseQuote() + => TestMissingAsync(""" class Test { void Method() @@ -59,12 +54,10 @@ void Method() } } """); - } [Fact] - public async Task EmptyVerbatimString() - { - await TestInRegularAndScript1Async(""" + public Task EmptyVerbatimString() + => TestInRegularAndScript1Async(""" class Test { void Method() @@ -82,12 +75,10 @@ void Method() } } """); - } [Fact] - public async Task TestLeadingAndTrailingTrivia() - { - await TestInRegularAndScript1Async(""" + public Task TestLeadingAndTrailingTrivia() + => TestInRegularAndScript1Async(""" class Test { void Method() @@ -109,12 +100,10 @@ void Method() } } """); - } [Fact] - public async Task RegularStringWithBasicText() - { - await TestMissingAsync(""" + public Task RegularStringWithBasicText() + => TestMissingAsync(""" class Test { void Method() @@ -123,12 +112,10 @@ void Method() } } """); - } [Fact] - public async Task VerbatimStringWithBasicText() - { - await TestInRegularAndScript1Async(""" + public Task VerbatimStringWithBasicText() + => TestInRegularAndScript1Async(""" class Test { void Method() @@ -146,12 +133,10 @@ void Method() } } """); - } [Fact] - public async Task RegularStringWithUnicodeEscape() - { - await TestMissingAsync(""" + public Task RegularStringWithUnicodeEscape() + => TestMissingAsync(""" class Test { void Method() @@ -160,12 +145,10 @@ void Method() } } """); - } [Fact] - public async Task RegularStringWithEscapedNewLine() - { - await TestInRegularAndScript1Async(""" + public Task RegularStringWithEscapedNewLine() + => TestInRegularAndScript1Async(""" class Test { void Method() @@ -184,12 +167,10 @@ void Method() } } """); - } [Fact] - public async Task VerbatimStringWithNewLine() - { - await TestInRegularAndScript1Async(""" + public Task VerbatimStringWithNewLine() + => TestInRegularAndScript1Async(""" class Test { void Method() @@ -208,12 +189,10 @@ void Method() } } """); - } [Fact] - public async Task RegularStringWithEscapedNull() - { - await TestMissingAsync(""" + public Task RegularStringWithEscapedNull() + => TestMissingAsync(""" class Test { void Method() @@ -222,12 +201,10 @@ void Method() } } """); - } [Fact] - public async Task RegularStringWithEscapedQuote() - { - await TestInRegularAndScript1Async(""" + public Task RegularStringWithEscapedQuote() + => TestInRegularAndScript1Async(""" class Test { void Method() @@ -245,12 +222,10 @@ void Method() } } """); - } [Fact] - public async Task VerbatimStringWithEscapedQuote() - { - await TestInRegularAndScript1Async(""" + public Task VerbatimStringWithEscapedQuote() + => TestInRegularAndScript1Async(""" class Test { void Method() @@ -268,12 +243,10 @@ void Method() } } """); - } [Fact] - public async Task DoNotEscapeCurlyBracesInRegularString() - { - await TestInRegularAndScript1Async(""" + public Task DoNotEscapeCurlyBracesInRegularString() + => TestInRegularAndScript1Async(""" class Test { void Method() @@ -292,12 +265,10 @@ void Method() } } """); - } [Fact] - public async Task DoNotEscapeCurlyBracesInVerbatimString() - { - await TestInRegularAndScript1Async(""" + public Task DoNotEscapeCurlyBracesInVerbatimString() + => TestInRegularAndScript1Async(""" class Test { void Method() @@ -316,5 +287,4 @@ void Method() } } """); - } } diff --git a/src/Features/CSharpTest/ConvertCast/ConvertDirectCastToTryCastTests.cs b/src/Features/CSharpTest/ConvertCast/ConvertDirectCastToTryCastTests.cs index 622717fef32a4..ced9ca4c14d2d 100644 --- a/src/Features/CSharpTest/ConvertCast/ConvertDirectCastToTryCastTests.cs +++ b/src/Features/CSharpTest/ConvertCast/ConvertDirectCastToTryCastTests.cs @@ -19,9 +19,10 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertConversionOperat public sealed class ConvertDirectCastToTryCastTests { [Fact] - public async Task ConvertFromExplicitToAs() - { - const string InitialMarkup = """ + public Task ConvertFromExplicitToAs() + => new VerifyCS.Test + { + TestCode = """ class Program { public static void Main() @@ -29,8 +30,8 @@ public static void Main() var x = ([||]object)1; } } - """; - const string ExpectedMarkup = """ + """, + FixedCode = """ class Program { public static void Main() @@ -38,14 +39,9 @@ public static void Main() var x = 1 as object; } } - """; - await new VerifyCS.Test - { - TestCode = InitialMarkup, - FixedCode = ExpectedMarkup, + """, CodeActionValidationMode = CodeActionValidationMode.Full, }.RunAsync(); - } [Theory] [InlineData("dynamic")] @@ -53,45 +49,43 @@ public static void Main() [InlineData("Action")] [InlineData("int[]")] [InlineData("List")] - public async Task ConvertFromExplicitToAsSpecialTypes(string targetType) - { - var initialMarkup = @$" -using System; -using System.Collections.Generic; - -class Program -{{ - public static void Main() - {{ - var o = new object(); - var x = ([||]{targetType})o; - }} -}}"; - var expectedMarkup = @$" -using System; -using System.Collections.Generic; + public Task ConvertFromExplicitToAsSpecialTypes(string targetType) + => new VerifyCS.Test + { + TestCode = $$""" + using System; + using System.Collections.Generic; -class Program -{{ - public static void Main() - {{ - var o = new object(); - var x = o as {targetType}; - }} -}}"; + class Program + { + public static void Main() + { + var o = new object(); + var x = ([||]{{targetType}})o; + } + } + """, + FixedCode = $$""" + using System; + using System.Collections.Generic; - await new VerifyCS.Test - { - TestCode = initialMarkup, - FixedCode = expectedMarkup, + class Program + { + public static void Main() + { + var o = new object(); + var x = o as {{targetType}}; + } + } + """, CodeActionValidationMode = CodeActionValidationMode.Full, }.RunAsync(); - } [Fact] - public async Task ConvertFromExplicitToAs_ValueType() - { - const string InitialMarkup = """ + public Task ConvertFromExplicitToAs_ValueType() + => new VerifyCS.Test + { + TestCode = """ class Program { public static void Main() @@ -99,19 +93,16 @@ public static void Main() var x = ([||]byte)1; } } - """; - await new VerifyCS.Test - { - TestCode = InitialMarkup, + """, OffersEmptyRefactoring = false, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact] - public async Task ConvertFromExplicitToAs_ValueTypeConstraint() - { - const string InitialMarkup = """ + public Task ConvertFromExplicitToAs_ValueTypeConstraint() + => new VerifyCS.Test + { + TestCode = """ public class C { public void M() where T: struct @@ -120,19 +111,16 @@ public void M() where T: struct var t = (T[||])o; } } - """; - await new VerifyCS.Test - { - TestCode = InitialMarkup, + """, OffersEmptyRefactoring = false, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact] - public async Task ConvertFromExplicitToAs_Unconstraint() - { - const string InitialMarkup = """ + public Task ConvertFromExplicitToAs_Unconstraint() + => new VerifyCS.Test + { + TestCode = """ public class C { public void M() @@ -141,41 +129,36 @@ public void M() var t = (T[||])o; } } - """; - await new VerifyCS.Test - { - TestCode = InitialMarkup, + """, OffersEmptyRefactoring = false, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact] public async Task ConvertFromExplicitToAs_ClassConstraint() { - const string InitialMarkup = """ + const string FixedCode = """ public class C { public void M() where T: class { var o = new object(); - var t = (T[||])o; + var t = o as T; } } """; - const string FixedCode = """ + await new VerifyCS.Test + { + TestCode = """ public class C { public void M() where T: class { var o = new object(); - var t = o as T; + var t = (T[||])o; } } - """; - await new VerifyCS.Test - { - TestCode = InitialMarkup, + """, FixedCode = FixedCode, CodeActionValidationMode = CodeActionValidationMode.Full, }.RunAsync(); @@ -186,30 +169,30 @@ public void M() where T: class [InlineData("interface", false)] public async Task ConvertFromExplicitToAs_ConcreteClassOrInterfaceConstraint(string targetTypeKind, bool shouldBeFixed) { - var initialMarkup = @$" -public {targetTypeKind} Target {{ }} + var initialMarkup = $$""" + public {{targetTypeKind}} Target { } -public class C -{{ - public void M() where T: Target - {{ - var o = new object(); - var t = (T[||])o; - }} -}} -"; - var fixedCode = @$" -public {targetTypeKind} Target {{ }} + public class C + { + public void M() where T: Target + { + var o = new object(); + var t = (T[||])o; + } + } + """; + var fixedCode = $$""" + public {{targetTypeKind}} Target { } -public class C -{{ - public void M() where T: Target - {{ - var o = new object(); - var t = o as T; - }} -}} -"; + public class C + { + public void M() where T: Target + { + var o = new object(); + var t = o as T; + } + } + """; await new VerifyCS.Test { TestCode = initialMarkup, @@ -220,9 +203,10 @@ public void M() where T: Target } [Fact] - public async Task ConvertFromExplicitToAs_NestedTypeParameters() - { - var initialMarkup = """ + public Task ConvertFromExplicitToAs_NestedTypeParameters() + => new VerifyCS.Test + { + TestCode = """ public class Target { } public class C @@ -235,8 +219,8 @@ public void M() var u = (U[||])o; } } - """; - var fixedCode = """ + """, + FixedCode = """ public class Target { } public class C @@ -249,15 +233,10 @@ public void M() var u = o as U; } } - """; - await new VerifyCS.Test - { - TestCode = initialMarkup, - FixedCode = fixedCode, + """, OffersEmptyRefactoring = false, CodeActionValidationMode = CodeActionValidationMode.Full, }.RunAsync(); - } [Fact] public async Task ConvertFromExplicitToAs_MissingType() @@ -289,39 +268,34 @@ public void M() "((object)1) as C")] [InlineData("(C)((object$$)1)", "(C)(1 as object)")] - public async Task ConvertFromExplicitToAs_Nested(string cast, string asExpression) - { - var initialMarkup = @$" -class C {{ }} + public Task ConvertFromExplicitToAs_Nested(string cast, string asExpression) + => new VerifyCS.Test + { + TestCode = $$""" + class C { } -class Program -{{ - public static void Main() - {{ - var x = {cast}; - }} -}} -"; - var expectedMarkup = @$" -class C {{ }} + class Program + { + public static void Main() + { + var x = {{cast}}; + } + } + """, + FixedCode = $$""" + class C { } -class Program -{{ - public static void Main() - {{ - var x = {asExpression}; - }} -}} -"; - await new VerifyCS.Test - { - TestCode = initialMarkup, - FixedCode = expectedMarkup, + class Program + { + public static void Main() + { + var x = {{asExpression}}; + } + } + """, CodeActionValidationMode = CodeActionValidationMode.Full, }.RunAsync(); - } - [Theory] [InlineData("/* Leading */ (obj$$ect)1", "/* Leading */ 1 as object")] @@ -353,38 +327,35 @@ 1 as 1 as object """)] - public async Task ConvertFromExplicitToAs_Trivia(string cast, string asExpression) - { - var initialMarkup = @$" -class Program -{{ - public static void Main() - {{ - var x = {cast}; - }} -}} -"; - var expectedMarkup = @$" -class Program -{{ - public static void Main() - {{ - var x = {asExpression}; - }} -}} -"; - await new VerifyCS.Test + public Task ConvertFromExplicitToAs_Trivia(string cast, string asExpression) + => new VerifyCS.Test { - TestCode = initialMarkup, - FixedCode = expectedMarkup, + TestCode = $$""" + class Program + { + public static void Main() + { + var x = {{cast}}; + } + } + """, + FixedCode = $$""" + class Program + { + public static void Main() + { + var x = {{asExpression}}; + } + } + """, CodeActionValidationMode = CodeActionValidationMode.SemanticStructure, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64052")] - public async Task ConvertFromExplicitToAs_NullableReferenceType_NullableEnable() - { - var initialMarkup = """ + public Task ConvertFromExplicitToAs_NullableReferenceType_NullableEnable() + => new VerifyCS.Test + { + TestCode = """ #nullable enable class Program @@ -394,8 +365,8 @@ public static void Main() var x = ([||]string?)null; } } - """; - var expectedMarkup = """ + """, + FixedCode = """ #nullable enable class Program @@ -405,19 +376,15 @@ public static void Main() var x = null as string; } } - """; - await new VerifyCS.Test - { - TestCode = initialMarkup, - FixedCode = expectedMarkup, + """, CodeActionValidationMode = CodeActionValidationMode.Full, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64052")] - public async Task ConvertFromExplicitToAs_NullableReferenceType_NullableDisable() - { - var initialMarkup = """ + public Task ConvertFromExplicitToAs_NullableReferenceType_NullableDisable() + => new VerifyCS.Test + { + TestCode = """ #nullable disable class Program @@ -427,8 +394,8 @@ public static void Main() var x = ([||]string?)null; } } - """; - var expectedMarkup = """ + """, + FixedCode = """ #nullable disable class Program @@ -438,40 +405,34 @@ public static void Main() var x = null as string; } } - """; - await new VerifyCS.Test - { - TestCode = initialMarkup, - FixedCode = expectedMarkup, + """, CompilerDiagnostics = CompilerDiagnostics.None, // Suppress compiler warning about nullable string in non-nullable context CodeActionValidationMode = CodeActionValidationMode.Full, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64466")] public async Task ConvertFromExplicitToAs_NullableValueType() { - const string InitialMarkup = """ + const string FixedCode = """ class Program { public static void Main() { - var x = ([||]byte?)null; + var x = null as byte?; } } """; - const string FixedCode = """ + await new VerifyCS.Test + { + TestCode = """ class Program { public static void Main() { - var x = null as byte?; + var x = ([||]byte?)null; } } - """; - await new VerifyCS.Test - { - TestCode = InitialMarkup, + """, FixedCode = FixedCode, CodeActionValidationMode = CodeActionValidationMode.Full, }.RunAsync(); diff --git a/src/Features/CSharpTest/ConvertCast/ConvertTryCastToDirectCastTests.cs b/src/Features/CSharpTest/ConvertCast/ConvertTryCastToDirectCastTests.cs index 746989fe6a876..9088b3b6188d9 100644 --- a/src/Features/CSharpTest/ConvertCast/ConvertTryCastToDirectCastTests.cs +++ b/src/Features/CSharpTest/ConvertCast/ConvertTryCastToDirectCastTests.cs @@ -19,9 +19,10 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertConversionOperat public sealed class ConvertTryCastToDirectCastTests { [Fact] - public async Task ConvertFromAsToExplicit() - { - const string InitialMarkup = """ + public Task ConvertFromAsToExplicit() + => new VerifyCS.Test + { + TestCode = """ class Program { public static void Main() @@ -29,8 +30,8 @@ public static void Main() var x = 1 as[||] object; } } - """; - const string ExpectedMarkup = """ + """, + FixedCode = """ class Program { public static void Main() @@ -38,19 +39,15 @@ public static void Main() var x = (object)1; } } - """; - await new VerifyCS.Test - { - TestCode = InitialMarkup, - FixedCode = ExpectedMarkup, + """, CodeActionValidationMode = CodeActionValidationMode.SemanticStructure }.RunAsync(); - } [Fact] - public async Task ConvertFromAsToExplicit_ValueType() - { - const string InitialMarkup = """ + public Task ConvertFromAsToExplicit_ValueType() + => new VerifyCS.Test + { + TestCode = """ class Program { public static void Main() @@ -58,20 +55,17 @@ public static void Main() var x = 1 as[||] byte; } } - """; - await new VerifyCS.Test - { - TestCode = InitialMarkup, + """, CompilerDiagnostics = CompilerDiagnostics.None, // CS0077 is present, but we present the refactoring anyway (this may overlap with a diagnostic fixer) OffersEmptyRefactoring = false, CodeActionValidationMode = CodeActionValidationMode.Full, }.RunAsync(); - } [Fact] - public async Task ConvertFromAsToExplicit_NoTypeSyntaxRightOfAs() - { - const string InitialMarkup = """ + public Task ConvertFromAsToExplicit_NoTypeSyntaxRightOfAs() + => new VerifyCS.Test + { + TestCode = """ class Program { public static void Main() @@ -79,85 +73,73 @@ public static void Main() var x = 1 as[||] 1; } } - """; - await new VerifyCS.Test - { - TestCode = InitialMarkup, + """, CompilerDiagnostics = CompilerDiagnostics.None, OffersEmptyRefactoring = false, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Theory] [InlineData("(1 as object) as $$C", "(C)(1 as object)")] [InlineData("(1 as$$ object) as C", "((object)1) as C")] - public async Task ConvertFromAsToExplicit_Nested(string asExpression, string cast) - { - var initialMarkup = @$" -class C {{ }} + public Task ConvertFromAsToExplicit_Nested(string asExpression, string cast) + => new VerifyCS.Test + { + TestCode = $$""" + class C { } -class Program -{{ - public static void Main() - {{ - var x = {asExpression}; - }} -}} -"; - var expectedMarkup = @$" -class C {{ }} + class Program + { + public static void Main() + { + var x = {{asExpression}}; + } + } + """, + FixedCode = $$""" + class C { } -class Program -{{ - public static void Main() - {{ - var x = {cast}; - }} -}} -"; - await new VerifyCS.Test - { - TestCode = initialMarkup, - FixedCode = expectedMarkup, + class Program + { + public static void Main() + { + var x = {{cast}}; + } + } + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Theory] [InlineData("(1 + 1) as $$object", "(object)(1 + 1)")] [InlineData("(1 $$+ 1) as object", "(object)(1 + 1)")] - public async Task ConvertFromAsToExplicit_OtherBinaryExpressions(string asExpression, string cast) - { - var initialMarkup = @$" -class Program -{{ - public static void Main() - {{ - var x = {asExpression}; - }} -}} -"; - var expectedMarkup = @$" -class Program -{{ - public static void Main() - {{ - var x = {cast}; - }} -}} -"; - await new VerifyCS.Test + public Task ConvertFromAsToExplicit_OtherBinaryExpressions(string asExpression, string cast) + => new VerifyCS.Test { - TestCode = initialMarkup, - FixedCode = expectedMarkup, + TestCode = $$""" + class Program + { + public static void Main() + { + var x = {{asExpression}}; + } + } + """, + FixedCode = $$""" + class Program + { + public static void Main() + { + var x = {{cast}}; + } + } + """, CodeActionValidationMode = CodeActionValidationMode.SemanticStructure, }.RunAsync(); - } [Theory] [InlineData("/* Leading */ 1 as $$object", @@ -170,38 +152,35 @@ public static void Main() "/* Middle2 */ (object)1")] [InlineData("/* Leading */ 1 /* Middle1 */ as /* Middle2 */ $$object /* Trailing */", "/* Leading */ /* Middle2 */ (object)1/* Middle1 */ /* Trailing */")] - public async Task ConvertFromAsToExplicit_TriviaHandling(string asExpression, string cast) - { - var initialMarkup = @$" -class Program -{{ - public static void Main() - {{ - var x = {asExpression}; - }} -}} -"; - var expectedMarkup = @$" -class Program -{{ - public static void Main() - {{ - var x = {cast}; - }} -}} -"; - await new VerifyCS.Test + public Task ConvertFromAsToExplicit_TriviaHandling(string asExpression, string cast) + => new VerifyCS.Test { - TestCode = initialMarkup, - FixedCode = expectedMarkup, + TestCode = $$""" + class Program + { + public static void Main() + { + var x = {{asExpression}}; + } + } + """, + FixedCode = $$""" + class Program + { + public static void Main() + { + var x = {{cast}}; + } + } + """, CodeActionValidationMode = CodeActionValidationMode.SemanticStructure, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64052")] - public async Task ConvertFromAsToExplicit_NullableReferenceType_NullableEnable() - { - var initialMarkup = """ + public Task ConvertFromAsToExplicit_NullableReferenceType_NullableEnable() + => new VerifyCS.Test + { + TestCode = """ #nullable enable class Program @@ -211,8 +190,8 @@ public static void Main() var x = null as[||] string; } } - """; - var expectedMarkup = """ + """, + FixedCode = """ #nullable enable class Program @@ -222,19 +201,15 @@ public static void Main() var x = (string?)null; } } - """; - await new VerifyCS.Test - { - TestCode = initialMarkup, - FixedCode = expectedMarkup, + """, CodeActionValidationMode = CodeActionValidationMode.SemanticStructure, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64052")] - public async Task ConvertFromAsToExplicit_NullableReferenceType_NullableDisable() - { - var initialMarkup = """ + public Task ConvertFromAsToExplicit_NullableReferenceType_NullableDisable() + => new VerifyCS.Test + { + TestCode = """ #nullable disable class Program @@ -244,8 +219,8 @@ public static void Main() var x = null as[||] string; } } - """; - var expectedMarkup = """ + """, + FixedCode = """ #nullable disable class Program @@ -255,39 +230,33 @@ public static void Main() var x = (string)null; } } - """; - await new VerifyCS.Test - { - TestCode = initialMarkup, - FixedCode = expectedMarkup, + """, CodeActionValidationMode = CodeActionValidationMode.SemanticStructure, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64466")] public async Task ConvertFromExplicitToAs_NullableValueType() { - const string InitialMarkup = """ + const string FixedCode = """ class Program { public static void Main() { - var x = null as[||] byte?; + var x = (byte?)null; } } """; - const string FixedCode = """ + await new VerifyCS.Test + { + TestCode = """ class Program { public static void Main() { - var x = (byte?)null; + var x = null as[||] byte?; } } - """; - await new VerifyCS.Test - { - TestCode = InitialMarkup, + """, FixedCode = FixedCode, CodeActionValidationMode = CodeActionValidationMode.SemanticStructure, }.RunAsync(); diff --git a/src/Features/CSharpTest/ConvertForEachToFor/ConvertForEachToForTests.cs b/src/Features/CSharpTest/ConvertForEachToFor/ConvertForEachToForTests.cs index d5be62406de7e..a9e98c15c2c3d 100644 --- a/src/Features/CSharpTest/ConvertForEachToFor/ConvertForEachToForTests.cs +++ b/src/Features/CSharpTest/ConvertForEachToFor/ConvertForEachToForTests.cs @@ -35,9 +35,8 @@ private OptionsCollection ImplicitTypeEverywhere }; [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31621")] - public async Task EmptyBlockBody() - { - var text = """ + public Task EmptyBlockBody() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -48,8 +47,7 @@ void Method() } } } - """; - var expected = """ + """, """ class Test { void Method() @@ -61,14 +59,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task EmptyBody() - { - var text = """ + public Task EmptyBody() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -77,8 +72,7 @@ void Method() foreach[||](var a in array) ; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -87,14 +81,11 @@ void Method() for (int {|Rename:i|} = 0; i < array.Length; i++) ; } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task Body() - { - var text = """ + public Task Body() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -103,8 +94,7 @@ void Method() foreach[||](var a in array) Console.WriteLine(a); } } - """; - var expected = """ + """, """ class Test { void Method() @@ -117,14 +107,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task BlockBody() - { - var text = """ + public Task BlockBody() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -136,8 +123,7 @@ void Method() } } } - """; - var expected = """ + """, """ class Test { void Method() @@ -150,14 +136,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31621")] - public async Task Comment() - { - var text = """ + public Task Comment() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -169,8 +152,7 @@ void Method() } } } - """; - var expected = """ + """, """ class Test { void Method() @@ -183,14 +165,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31621")] - public async Task Comment2() - { - var text = """ + public Task Comment2() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -202,8 +181,7 @@ void Method() }/* comment */ } } - """; - var expected = """ + """, """ class Test { void Method() @@ -216,14 +194,11 @@ void Method() }/* comment */ } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task Comment3() - { - var text = """ + public Task Comment3() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -232,8 +207,7 @@ void Method() foreach[||](var a in array) /* comment */; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -242,14 +216,11 @@ void Method() for (int {|Rename:i|} = 0; i < array.Length; i++) /* comment */; } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task Comment4() - { - var text = """ + public Task Comment4() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -258,8 +229,7 @@ void Method() foreach[||](var a in array) Console.WriteLine(a); // test } } - """; - var expected = """ + """, """ class Test { void Method() @@ -272,14 +242,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task Comment5() - { - var text = """ + public Task Comment5() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -288,8 +255,7 @@ void Method() foreach [||] (var a in array) /* test */ Console.WriteLine(a); } } - """; - var expected = """ + """, """ class Test { void Method() @@ -302,14 +268,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task Comment6() - { - var text = """ + public Task Comment6() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -319,8 +282,7 @@ void Method() /* test */ Console.WriteLine(a); } } - """; - var expected = """ + """, """ class Test { void Method() @@ -334,14 +296,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31621")] - public async Task Comment7() - { - var text = """ + public Task Comment7() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -352,8 +311,7 @@ void Method() } } } - """; - var expected = """ + """, """ class Test { void Method() @@ -366,14 +324,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task TestCommentsInTheMiddleOfParentheses() - { - var text = """ + public Task TestCommentsInTheMiddleOfParentheses() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -382,8 +337,7 @@ void Method() foreach [||] (var a /* test */ in array) ; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -392,14 +346,11 @@ void Method() for (int {|Rename:i|} = 0; i < array.Length; i++) ; } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task TestCommentsAtBeginningOfParentheses() - { - var text = """ + public Task TestCommentsAtBeginningOfParentheses() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -408,8 +359,7 @@ void Method() foreach [||] (/* test */ var a in array) ; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -418,14 +368,11 @@ void Method() for (int {|Rename:i|} = 0; i < array.Length; i++) ; } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task TestCommentsAtTheEndOfParentheses() - { - var text = """ + public Task TestCommentsAtTheEndOfParentheses() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -434,8 +381,7 @@ void Method() foreach [||] (var a in array /* test */) ; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -444,14 +390,11 @@ void Method() for (int {|Rename:i|} = 0; i < array.Length; i++) ; } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task CollectionStatement() - { - var text = """ + public Task CollectionStatement() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -462,8 +405,7 @@ void Method() } } } - """; - var expected = """ + """, """ class Test { void Method() @@ -476,14 +418,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task CollectionConflict() - { - var text = """ + public Task CollectionConflict() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -496,8 +435,7 @@ void Method() } } } - """; - var expected = """ + """, """ class Test { void Method() @@ -512,14 +450,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task VariableWritten() - { - var text = """ + public Task VariableWritten() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -531,8 +466,7 @@ void Method() } } } - """; - var expected = """ + """, """ class Test { void Method() @@ -545,14 +479,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task IndexConflict() - { - var text = """ + public Task IndexConflict() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -564,8 +495,7 @@ void Method() } } } - """; - var expected = """ + """, """ class Test { void Method() @@ -578,14 +508,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task StructPropertyReadFromAndDiscarded() - { - var text = """ + public Task StructPropertyReadFromAndDiscarded() + => TestInRegularAndScriptAsync(""" class Test { struct Struct @@ -602,8 +529,7 @@ void Method() } } } - """; - var expected = """ + """, """ class Test { struct Struct @@ -621,14 +547,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task StructPropertyReadFromAndAssignedToLocal() - { - var text = """ + public Task StructPropertyReadFromAndAssignedToLocal() + => TestInRegularAndScriptAsync(""" class Test { struct Struct @@ -645,8 +568,7 @@ void Method() } } } - """; - var expected = """ + """, """ class Test { struct Struct @@ -664,14 +586,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task WrongCaretPosition() - { - var text = """ + public Task WrongCaretPosition() + => TestMissingInRegularAndScriptAsync(""" class Test { void Method() @@ -683,15 +602,12 @@ void Method() } } } - """; - await TestMissingInRegularAndScriptAsync(text); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] [WorkItem("https://github.com/dotnet/roslyn/issues/31621")] - public async Task TestCaretBefore() - { - var text = """ + public Task TestCaretBefore() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -702,8 +618,7 @@ void Method() } } } - """; - var expected = """ + """, """ class Test { void Method() @@ -715,15 +630,12 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] [WorkItem("https://github.com/dotnet/roslyn/issues/31621")] - public async Task TestCaretAfter() - { - var text = """ + public Task TestCaretAfter() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -734,8 +646,7 @@ void Method() } } } - """; - var expected = """ + """, """ class Test { void Method() @@ -747,15 +658,12 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] [WorkItem("https://github.com/dotnet/roslyn/issues/31621")] - public async Task TestSelection() - { - var text = """ + public Task TestSelection() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -766,8 +674,7 @@ void Method() }|] } } - """; - var expected = """ + """, """ class Test { void Method() @@ -779,14 +686,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31621")] - public async Task Field() - { - var text = """ + public Task Field() + => TestInRegularAndScriptAsync(""" class Test { int[] array = new int[] { 1, 3, 4 }; @@ -798,8 +702,7 @@ void Method() } } } - """; - var expected = """ + """, """ class Test { int[] array = new int[] { 1, 3, 4 }; @@ -812,14 +715,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task ArrayElement() - { - var text = """ + public Task ArrayElement() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -831,8 +731,7 @@ void Method() } } } - """; - var expected = """ + """, """ class Test { void Method() @@ -845,14 +744,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31621")] - public async Task Parameter() - { - var text = """ + public Task Parameter() + => TestInRegularAndScriptAsync(""" class Test { void Method(int[] array) @@ -862,8 +758,7 @@ void Method(int[] array) } } } - """; - var expected = """ + """, """ class Test { void Method(int[] array) @@ -874,14 +769,11 @@ void Method(int[] array) } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31621")] - public async Task Property() - { - var text = """ + public Task Property() + => TestInRegularAndScriptAsync(""" class Test { int [] Prop { get; } = new int[] { 1, 2, 3 }; @@ -893,8 +785,7 @@ void Method() } } } - """; - var expected = """ + """, """ class Test { int [] Prop { get; } = new int[] { 1, 2, 3 }; @@ -907,14 +798,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task Interface() - { - var text = """ + public Task Interface() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; class Test @@ -928,8 +816,7 @@ void Method() } } } - """; - var expected = """ + """, """ using System.Collections.Generic; class Test @@ -944,14 +831,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task IListOfT() - { - var text = """ + public Task IListOfT() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; class Test @@ -965,8 +849,7 @@ void Method() } } } - """; - var expected = """ + """, """ using System.Collections.Generic; class Test @@ -981,14 +864,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task IReadOnlyListOfT() - { - var text = """ + public Task IReadOnlyListOfT() + => TestInRegularAndScriptAsync(""" using System.Collections; using System.Collections.Generic; @@ -1012,8 +892,7 @@ class ReadOnly : IReadOnlyList public IEnumerator GetEnumerator() => throw new System.NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new System.NotImplementedException(); } - """; - var expected = """ + """, """ using System.Collections; using System.Collections.Generic; @@ -1038,14 +917,11 @@ class ReadOnly : IReadOnlyList public IEnumerator GetEnumerator() => throw new System.NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new System.NotImplementedException(); } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task IList() - { - var text = """ + public Task IList() + => TestInRegularAndScriptAsync(""" using System; using System.Collections; @@ -1080,8 +956,7 @@ class List : IList public void Remove(object value) => throw new NotImplementedException(); public void RemoveAt(int index) => throw new NotImplementedException(); } - """; - var expected = """ + """, """ using System; using System.Collections; @@ -1117,9 +992,7 @@ class List : IList public void Remove(object value) => throw new NotImplementedException(); public void RemoveAt(int index) => throw new NotImplementedException(); } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact(Skip = "https://github.com/dotnet/roslyn/issues/29740")] public async Task ImmutableArray() @@ -1148,8 +1021,7 @@ void Method() """; - - var expected = """ + await TestInRegularAndScriptAsync(text, """ using System; using System.Collections.Immutable; @@ -1165,14 +1037,12 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); + """); } [Fact] - public async Task ExplicitInterface() - { - var text = """ + public Task ExplicitInterface() + => TestInRegularAndScriptAsync(""" using System; using System.Collections; using System.Collections.Generic; @@ -1196,9 +1066,7 @@ class Explicit : IReadOnlyList IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); } - """; - - var expected = """ + """, """ using System; using System.Collections; using System.Collections.Generic; @@ -1224,14 +1092,11 @@ class Explicit : IReadOnlyList IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task DoubleExplicitInterface() - { - var text = """ + public Task DoubleExplicitInterface() + => TestMissingInRegularAndScriptAsync(""" using System; using System.Collections; using System.Collections.Generic; @@ -1259,14 +1124,11 @@ class Explicit : IReadOnlyList, IReadOnlyList int IReadOnlyCollection.Count => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); } - """; - await TestMissingInRegularAndScriptAsync(text); - } + """); [Fact] - public async Task DoubleExplicitInterfaceWithExplicitType() - { - var text = """ + public Task DoubleExplicitInterfaceWithExplicitType() + => TestInRegularAndScriptAsync(""" using System; using System.Collections; using System.Collections.Generic; @@ -1294,9 +1156,7 @@ class Explicit : IReadOnlyList, IReadOnlyList int IReadOnlyCollection.Count => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); } - """; - - var expected = """ + """, """ using System; using System.Collections; using System.Collections.Generic; @@ -1326,14 +1186,11 @@ class Explicit : IReadOnlyList, IReadOnlyList int IReadOnlyCollection.Count => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task MixedInterfaceImplementation() - { - var text = """ + public Task MixedInterfaceImplementation() + => TestInRegularAndScriptAsync(""" using System; using System.Collections; using System.Collections.Generic; @@ -1361,9 +1218,7 @@ class Mixed : IReadOnlyList, IReadOnlyList int IReadOnlyCollection.Count => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); } - """; - - var expected = """ + """, """ using System; using System.Collections; using System.Collections.Generic; @@ -1392,14 +1247,11 @@ class Mixed : IReadOnlyList, IReadOnlyList int IReadOnlyCollection.Count => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task MixedInterfaceImplementationWithExplicitType() - { - var text = """ + public Task MixedInterfaceImplementationWithExplicitType() + => TestInRegularAndScriptAsync(""" using System; using System.Collections; using System.Collections.Generic; @@ -1427,9 +1279,7 @@ class Mixed : IReadOnlyList, IReadOnlyList int IReadOnlyCollection.Count => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); } - """; - - var expected = """ + """, """ using System; using System.Collections; using System.Collections.Generic; @@ -1459,14 +1309,11 @@ class Mixed : IReadOnlyList, IReadOnlyList int IReadOnlyCollection.Count => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task PreserveUserExpression() - { - var text = """ + public Task PreserveUserExpression() + => TestInRegularAndScriptAsync(""" using System; using System.Collections; using System.Collections.Generic; @@ -1496,9 +1343,7 @@ class Mixed : IReadOnlyList, IReadOnlyList IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); } } - """; - - var expected = """ + """, """ using System; using System.Collections; using System.Collections.Generic; @@ -1530,14 +1375,11 @@ class Mixed : IReadOnlyList, IReadOnlyList IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task EmbededStatement() - { - var text = """ + public Task EmbededStatement() + => TestMissingInRegularAndScriptAsync(""" class Test { void Method() @@ -1546,14 +1388,11 @@ void Method() foreach [||] (var a in new int[] {}); } } - """; - await TestMissingInRegularAndScriptAsync(text); - } + """); [Fact] - public async Task EmbededStatement2() - { - var text = """ + public Task EmbededStatement2() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -1563,8 +1402,7 @@ void Method() foreach [||] (var a in array) Console.WriteLine(a); } } - """; - var expected = """ + """, """ class Test { void Method() @@ -1578,14 +1416,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task IndexConflict2() - { - var text = """ + public Task IndexConflict2() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -1597,8 +1432,7 @@ void Method() } } } - """; - var expected = """ + """, """ class Test { void Method() @@ -1611,14 +1445,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task UseTypeAsUsedInForeach() - { - var text = """ + public Task UseTypeAsUsedInForeach() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -1630,8 +1461,7 @@ void Method() } } } - """; - var expected = """ + """, """ class Test { void Method() @@ -1644,14 +1474,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task String() - { - var text = """ + public Task String() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -1662,8 +1489,7 @@ void Method() } } } - """; - var expected = """ + """, """ class Test { void Method() @@ -1676,15 +1502,11 @@ void Method() } } } - """; - - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task StringLocalConst() - { - var text = """ + public Task StringLocalConst() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -1696,8 +1518,7 @@ void Method() } } } - """; - var expected = """ + """, """ class Test { void Method() @@ -1710,14 +1531,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task StringConst() - { - var text = """ + public Task StringConst() + => TestInRegularAndScriptAsync(""" class Test { const string test = "test"; @@ -1730,8 +1548,7 @@ void Method() } } } - """; - var expected = """ + """, """ class Test { const string test = "test"; @@ -1745,14 +1562,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task ElementExplicitCast() - { - var text = """ + public Task ElementExplicitCast() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -1764,8 +1578,7 @@ void Method() } } } - """; - var expected = """ + """, """ class Test { void Method() @@ -1778,14 +1591,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50469")] - public async Task PreventExplicitCastToVar() - { - var text = """ + public Task PreventExplicitCastToVar() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -1797,8 +1607,7 @@ void Method() } } } - """; - var expected = """ + """, """ class Test { void Method() @@ -1811,14 +1620,11 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task NotAssignable() - { - var text = """ + public Task NotAssignable() + => TestMissingInRegularAndScriptAsync(""" class Test { void Method() @@ -1830,14 +1636,11 @@ void Method() } } } - """; - await TestMissingInRegularAndScriptAsync(text); - } + """); [Fact] - public async Task ElementMissing() - { - var text = """ + public Task ElementMissing() + => TestMissingInRegularAndScriptAsync(""" class Test { void Method() @@ -1849,14 +1652,11 @@ void Method() } } } - """; - await TestMissingInRegularAndScriptAsync(text); - } + """); [Fact] - public async Task ElementMissing2() - { - var text = """ + public Task ElementMissing2() + => TestMissingInRegularAndScriptAsync(""" class Test { void Method() @@ -1867,14 +1667,11 @@ void Method() } } } - """; - await TestMissingInRegularAndScriptAsync(text); - } + """); [Fact] - public async Task StringExplicitType() - { - var text = """ + public Task StringExplicitType() + => TestInRegularAndScriptAsync(""" class Test { void Method() @@ -1885,8 +1682,7 @@ void Method() } } } - """; - var expected = """ + """, """ class Test { void Method() @@ -1899,15 +1695,11 @@ void Method() } } } - """; - - await TestInRegularAndScriptAsync(text, expected); - } + """); [Fact] - public async Task Var() - { - var text = """ + public Task Var() + => TestInRegularAndScriptAsync(""" using System; using System.Collections; using System.Collections.Generic; @@ -1931,9 +1723,7 @@ class Explicit : IReadOnlyList IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); } - """; - - var expected = """ + """, """ using System; using System.Collections; using System.Collections.Generic; @@ -1959,14 +1749,11 @@ class Explicit : IReadOnlyList IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); } - """; - await TestInRegularAndScriptAsync(text, expected, options: ImplicitTypeEverywhere); - } + """, options: ImplicitTypeEverywhere); [Fact] - public async Task ArrayRank2() - { - var text = """ + public Task ArrayRank2() + => TestMissingAsync(""" class Test { void Method() @@ -1977,14 +1764,11 @@ void Method() } } } - """; - await TestMissingAsync(text); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48950")] - public async Task NullableReferenceVar() - { - var text = """ + public Task NullableReferenceVar() + => TestInRegularAndScriptAsync(""" #nullable enable class Test { @@ -1996,8 +1780,7 @@ void Method() } } } - """; - var expected = """ + """, """ #nullable enable class Test { @@ -2011,7 +1794,5 @@ void Method() } } } - """; - await TestInRegularAndScriptAsync(text, expected, options: ImplicitTypeEverywhere); - } + """, options: ImplicitTypeEverywhere); } diff --git a/src/Features/CSharpTest/ConvertForToForEach/ConvertForToForEachTests.cs b/src/Features/CSharpTest/ConvertForToForEach/ConvertForToForEachTests.cs index 8513bd48f76a6..ffd86e9d2edad 100644 --- a/src/Features/CSharpTest/ConvertForToForEach/ConvertForToForEachTests.cs +++ b/src/Features/CSharpTest/ConvertForToForEach/ConvertForToForEachTests.cs @@ -33,9 +33,8 @@ private OptionsCollection ImplicitTypeEverywhere() }; [Fact] - public async Task TestArray1() - { - await TestInRegularAndScript1Async( + public Task TestArray1() + => TestInRegularAndScript1Async( """ using System; @@ -64,12 +63,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestWarnIfCrossesFunctionBoundary() - { - await TestInRegularAndScript1Async( + public Task TestWarnIfCrossesFunctionBoundary() + => TestInRegularAndScript1Async( """ using System; @@ -104,12 +101,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestWarnIfCollectionPotentiallyMutated1() - { - await TestInRegularAndScript1Async( + public Task TestWarnIfCollectionPotentiallyMutated1() + => TestInRegularAndScript1Async( """ using System; using System.Collections.Generic; @@ -142,12 +137,10 @@ void Test(IList list) } } """); - } [Fact] - public async Task TestWarnIfCollectionPotentiallyMutated2() - { - await TestInRegularAndScript1Async( + public Task TestWarnIfCollectionPotentiallyMutated2() + => TestInRegularAndScript1Async( """ using System; using System.Collections.Generic; @@ -180,12 +173,10 @@ void Test(IList list) } } """); - } [Fact] - public async Task TestNoWarnIfCollectionPropertyAccess() - { - await TestInRegularAndScript1Async( + public Task TestNoWarnIfCollectionPropertyAccess() + => TestInRegularAndScript1Async( """ using System; using System.Collections.Generic; @@ -218,12 +209,10 @@ void Test(IList list) } } """); - } [Fact] - public async Task TestNoWarnIfDoesNotCrossFunctionBoundary() - { - await TestInRegularAndScript1Async( + public Task TestNoWarnIfDoesNotCrossFunctionBoundary() + => TestInRegularAndScript1Async( """ using System; @@ -258,12 +247,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestMultipleReferences() - { - await TestInRegularAndScript1Async( + public Task TestMultipleReferences() + => TestInRegularAndScript1Async( """ using System; @@ -294,12 +281,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestEmbeddedStatement() - { - await TestInRegularAndScript1Async( + public Task TestEmbeddedStatement() + => TestInRegularAndScript1Async( """ using System; @@ -324,12 +309,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestPostIncrement() - { - await TestInRegularAndScript1Async( + public Task TestPostIncrement() + => TestInRegularAndScript1Async( """ using System; @@ -358,12 +341,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestArrayPlusEqualsIncrementor() - { - await TestInRegularAndScript1Async( + public Task TestArrayPlusEqualsIncrementor() + => TestInRegularAndScript1Async( """ using System; @@ -392,12 +373,10 @@ void Test(string[] array) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestBeforeKeyword() - { - await TestInRegularAndScript1Async( + public Task TestBeforeKeyword() + => TestInRegularAndScript1Async( """ using System; @@ -426,12 +405,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestMissingAfterOpenParen() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingAfterOpenParen() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -446,12 +423,10 @@ void Test(string[] array) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestInParentheses() - { - await TestInRegularAndScript1Async( + public Task TestInParentheses() + => TestInRegularAndScript1Async( """ using System; @@ -480,12 +455,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestMissingBeforeCloseParen() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingBeforeCloseParen() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -500,12 +473,10 @@ void Test(string[] array) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestInParentheses2() - { - await TestInRegularAndScript1Async( + public Task TestInParentheses2() + => TestInRegularAndScript1Async( """ using System; @@ -534,12 +505,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestAtEndOfFor() - { - await TestInRegularAndScript1Async( + public Task TestAtEndOfFor() + => TestInRegularAndScript1Async( """ using System; @@ -568,12 +537,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestForSelected() - { - await TestInRegularAndScript1Async( + public Task TestForSelected() + => TestInRegularAndScript1Async( """ using System; @@ -602,12 +569,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestBeforeOpenParen() - { - await TestInRegularAndScript1Async( + public Task TestBeforeOpenParen() + => TestInRegularAndScript1Async( """ using System; @@ -636,12 +601,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestAfterCloseParen() - { - await TestInRegularAndScript1Async( + public Task TestAfterCloseParen() + => TestInRegularAndScript1Async( """ using System; @@ -670,12 +633,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestMissingWithoutIncrementor() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWithoutIncrementor() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -690,12 +651,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestMissingWithoutIncorrectIncrementor1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWithoutIncorrectIncrementor1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -710,12 +669,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestMissingWithoutIncorrectIncrementor2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWithoutIncorrectIncrementor2() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -730,12 +687,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestMissingWithoutCondition() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWithoutCondition() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -750,12 +705,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestMissingWithIncorrectCondition1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWithIncorrectCondition1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -770,12 +723,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestMissingWithIncorrectCondition2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWithIncorrectCondition2() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -790,12 +741,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestWithoutInitializer() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithoutInitializer() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -810,12 +759,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestWithInitializerOfVariableOutsideLoop() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithInitializerOfVariableOutsideLoop() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -831,12 +778,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestWithUninitializedVariable() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithUninitializedVariable() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -851,12 +796,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestNotStartingAtZero() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotStartingAtZero() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -871,12 +814,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestWithMultipleVariables() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithMultipleVariables() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -891,12 +832,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestList1() - { - await TestInRegularAndScript1Async( + public Task TestList1() + => TestInRegularAndScript1Async( """ using System; using System.Collections.Generic; @@ -927,12 +866,10 @@ void Test(IList list) } } """); - } [Fact] - public async Task TestChooseNameFromDeclarationStatement() - { - await TestInRegularAndScript1Async( + public Task TestChooseNameFromDeclarationStatement() + => TestInRegularAndScript1Async( """ using System; using System.Collections.Generic; @@ -964,12 +901,10 @@ void Test(IList list) } } """); - } [Fact] - public async Task TestIgnoreFormattingForReferences() - { - await TestInRegularAndScript1Async( + public Task TestIgnoreFormattingForReferences() + => TestInRegularAndScript1Async( """ using System; using System.Collections.Generic; @@ -1001,12 +936,10 @@ void Test(IList list) } } """); - } [Fact] - public async Task TestChooseNameFromDeclarationStatement_PreserveComments() - { - await TestInRegularAndScript1Async( + public Task TestChooseNameFromDeclarationStatement_PreserveComments() + => TestInRegularAndScript1Async( """ using System; using System.Collections.Generic; @@ -1042,12 +975,10 @@ void Test(IList list) } } """); - } [Fact] - public async Task TestChooseNameFromDeclarationStatement_PreserveDirectives() - { - await TestInRegularAndScript1Async( + public Task TestChooseNameFromDeclarationStatement_PreserveDirectives() + => TestInRegularAndScript1Async( """ using System; using System.Collections.Generic; @@ -1087,12 +1018,10 @@ void Test(IList list) } } """); - } [Fact] - public async Task TestMissingIfVariableUsedNotForIndexing() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingIfVariableUsedNotForIndexing() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1107,12 +1036,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestMissingIfVariableUsedForIndexingNonCollection() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingIfVariableUsedForIndexingNonCollection() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1127,12 +1054,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestWarningIfCollectionWrittenTo() - { - await TestInRegularAndScript1Async( + public Task TestWarningIfCollectionWrittenTo() + => TestInRegularAndScript1Async( """ using System; @@ -1161,12 +1086,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task UseVarIfPreferred1() - { - await TestInRegularAndScriptAsync( + public Task UseVarIfPreferred1() + => TestInRegularAndScriptAsync( """ using System; @@ -1195,12 +1118,10 @@ void Test(string[] array) } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task TestDifferentIndexerAndEnumeratorType() - { - await TestInRegularAndScriptAsync( + public Task TestDifferentIndexerAndEnumeratorType() + => TestInRegularAndScriptAsync( """ using System; @@ -1249,12 +1170,10 @@ void Test(MyList list) } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task TestSameIndexerAndEnumeratorType() - { - await TestInRegularAndScriptAsync( + public Task TestSameIndexerAndEnumeratorType() + => TestInRegularAndScriptAsync( """ using System; @@ -1303,12 +1222,10 @@ void Test(MyList list) } } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task TestTrivia() - { - await TestInRegularAndScript1Async( + public Task TestTrivia() + => TestInRegularAndScript1Async( """ using System; @@ -1341,12 +1258,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestNotWithDeconstruction() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithDeconstruction() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1361,12 +1276,10 @@ void Test(string[] array) } } """); - } [Fact] - public async Task TestMultidimensionalArray1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMultidimensionalArray1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1381,12 +1294,10 @@ void Test(string[,] array) } } """); - } [Fact] - public async Task TestMultidimensionalArray2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMultidimensionalArray2() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1401,12 +1312,10 @@ void Test(string[,] array) } } """); - } [Fact] - public async Task TestJaggedArray1() - { - await TestInRegularAndScript1Async( + public Task TestJaggedArray1() + => TestInRegularAndScript1Async( """ using System; @@ -1435,12 +1344,10 @@ void Test(string[][] array) } } """); - } [Fact] - public async Task TestJaggedArray2() - { - await TestInRegularAndScript1Async( + public Task TestJaggedArray2() + => TestInRegularAndScript1Async( """ using System; @@ -1469,12 +1376,10 @@ void Test(string[][] array) } } """); - } [Fact] - public async Task TestJaggedArray3() - { - await TestInRegularAndScript1Async( + public Task TestJaggedArray3() + => TestInRegularAndScript1Async( """ using System; @@ -1510,12 +1415,10 @@ void Test(string[][] array) } } """); - } [Fact] - public async Task TestJaggedArray4() - { - await TestInRegularAndScript1Async( + public Task TestJaggedArray4() + => TestInRegularAndScript1Async( """ using System; @@ -1550,12 +1453,10 @@ void Test(string[][] array) } } """); - } [Fact] - public async Task TestJaggedArray5() - { - await TestInRegularAndScript1Async( + public Task TestJaggedArray5() + => TestInRegularAndScript1Async( """ using System; @@ -1590,12 +1491,10 @@ void Test(string[][] array) } } """); - } [Fact] - public async Task TestJaggedArray6() - { - await TestMissingInRegularAndScriptAsync( + public Task TestJaggedArray6() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1610,12 +1509,10 @@ void Test(string[][] array) } } """); - } [Fact] - public async Task TestDoesNotUseLocalFunctionName() - { - await TestInRegularAndScript1Async( + public Task TestDoesNotUseLocalFunctionName() + => TestInRegularAndScript1Async( """ using System; @@ -1648,12 +1545,10 @@ void v() { } } } """); - } [Fact] - public async Task TestUsesLocalFunctionParameterName() - { - await TestInRegularAndScript1Async( + public Task TestUsesLocalFunctionParameterName() + => TestInRegularAndScript1Async( """ using System; @@ -1690,12 +1585,10 @@ void M(string v) } } """); - } [Fact] - public async Task TestDoesNotUseLambdaParameterWithCSharpLessThan8() - { - await TestInRegularAndScript1Async( + public Task TestDoesNotUseLambdaParameterWithCSharpLessThan8() + => TestInRegularAndScript1Async( """ using System; @@ -1728,12 +1621,10 @@ void Test(string[] array) } } """, parameters: new TestParameters(new CSharpParseOptions(LanguageVersion.CSharp7_3))); - } [Fact] - public async Task TestUsesLambdaParameterNameInCSharp8() - { - await TestInRegularAndScript1Async( + public Task TestUsesLambdaParameterNameInCSharp8() + => TestInRegularAndScript1Async( """ using System; @@ -1766,12 +1657,10 @@ void Test(string[] array) } } """, parameters: new TestParameters(new CSharpParseOptions(LanguageVersion.CSharp8))); - } [Fact] - public async Task TestNotWhenIteratingDifferentLists() - { - await TestMissingAsync( + public Task TestNotWhenIteratingDifferentLists() + => TestMissingAsync( """ using System; using System.Collection.Generic; @@ -1792,12 +1681,10 @@ static void Test() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36305")] - public async Task TestOnElementAt1() - { - await TestInRegularAndScript1Async( + public Task TestOnElementAt1() + => TestInRegularAndScript1Async( """ using System; using System.Collections.Generic; @@ -1835,5 +1722,4 @@ private void M() } } """); - } } diff --git a/src/Features/CSharpTest/ConvertIfToSwitch/ConvertIfToSwitchFixAllTests.cs b/src/Features/CSharpTest/ConvertIfToSwitch/ConvertIfToSwitchFixAllTests.cs index 9dc8cf322ac26..94af24d651948 100644 --- a/src/Features/CSharpTest/ConvertIfToSwitch/ConvertIfToSwitchFixAllTests.cs +++ b/src/Features/CSharpTest/ConvertIfToSwitch/ConvertIfToSwitchFixAllTests.cs @@ -18,608 +18,620 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor => new CSharpConvertIfToSwitchCodeRefactoringProvider(); [Fact] - public async Task ConvertIfToSwitchStatement_FixAllInDocument() - { - await TestInRegularAndScriptAsync( -@"class C -{ - int M(int i) - { - {|FixAllInDocument:|}if (i == 3) - { - return 0; - } - else - { - if (i == 6) return 1; - if (i == 7) return 1; - return 0; - } - } + public Task ConvertIfToSwitchStatement_FixAllInDocument() + => TestInRegularAndScriptAsync( + """ + class C + { + int M(int i) + { + {|FixAllInDocument:|}if (i == 3) + { + return 0; + } + else + { + if (i == 6) return 1; + if (i == 7) return 1; + return 0; + } + } - int M2(int i) - { - if (i == 3) - { - return 0; - } - else - { - if (i == 6) return 1; - if (i == 7) return 1; - return 0; - } - } -}", -@"class C -{ - int M(int i) - { - switch (i) - { - case 3: - return 0; - case 6: - return 1; - case 7: - return 1; - default: - return 0; - } - } + int M2(int i) + { + if (i == 3) + { + return 0; + } + else + { + if (i == 6) return 1; + if (i == 7) return 1; + return 0; + } + } + } + """, + """ + class C + { + int M(int i) + { + switch (i) + { + case 3: + return 0; + case 6: + return 1; + case 7: + return 1; + default: + return 0; + } + } - int M2(int i) - { - switch (i) - { - case 3: - return 0; - case 6: - return 1; - case 7: - return 1; - default: - return 0; - } - } -}"); - } + int M2(int i) + { + switch (i) + { + case 3: + return 0; + case 6: + return 1; + case 7: + return 1; + default: + return 0; + } + } + } + """); [Fact] - public async Task ConvertIfToSwitchExpression_FixAllInDocument() - { - await TestInRegularAndScriptAsync( -@"class C -{ - int M(int i) - { - {|FixAllInDocument:|}if (i == 3) - { - return 0; - } - else - { - if (i == 6) return 1; - if (i == 7) return 1; - return 0; - } - } + public Task ConvertIfToSwitchExpression_FixAllInDocument() + => TestInRegularAndScriptAsync( + """ + class C + { + int M(int i) + { + {|FixAllInDocument:|}if (i == 3) + { + return 0; + } + else + { + if (i == 6) return 1; + if (i == 7) return 1; + return 0; + } + } - int M2(int i) - { - if (i == 3) - { - return 0; - } - else - { - if (i == 6) return 1; - if (i == 7) return 1; - return 0; - } - } -}", -@"class C -{ - int M(int i) - { - return i switch - { - 3 => 0, - 6 => 1, - 7 => 1, - _ => 0 - }; - } + int M2(int i) + { + if (i == 3) + { + return 0; + } + else + { + if (i == 6) return 1; + if (i == 7) return 1; + return 0; + } + } + } + """, + """ + class C + { + int M(int i) + { + return i switch + { + 3 => 0, + 6 => 1, + 7 => 1, + _ => 0 + }; + } - int M2(int i) - { - return i switch - { - 3 => 0, - 6 => 1, - 7 => 1, - _ => 0 - }; - } -}", index: 1); - } + int M2(int i) + { + return i switch + { + 3 => 0, + 6 => 1, + 7 => 1, + _ => 0 + }; + } + } + """, index: 1); [Fact] - public async Task ConvertIfToSwitchStatement_Nested_FixAllInDocument() - { - await TestInRegularAndScriptAsync( -@"class C -{ - int M(int i, int j) - { - {|FixAllInDocument:|}if (i == 3) - { - return 0; - } - else - { - if (j == 6) + public Task ConvertIfToSwitchStatement_Nested_FixAllInDocument() + => TestInRegularAndScriptAsync( + """ + class C { - if (i == 6) return 1; - if (i == 7) return 2; - return 3; + int M(int i, int j) + { + {|FixAllInDocument:|}if (i == 3) + { + return 0; + } + else + { + if (j == 6) + { + if (i == 6) return 1; + if (i == 7) return 2; + return 3; + } + } + } } - } - } -}", -@"class C -{ - int M(int i, int j) - { - switch (i) - { - case 3: - return 0; - default: - if (j == 6) + """, + """ + class C + { + int M(int i, int j) + { + switch (i) + { + case 3: + return 0; + default: + if (j == 6) + { + switch (i) + { + case 6: + return 1; + case 7: + return 2; + default: + return 3; + } + } + break; + } + } + } + """); + + [Fact] + public Task ConvertIfToSwitchStatement_FixAllInProject() + => TestInRegularAndScriptAsync( + """ + + + + class C + { + int M(int i) + { + {|FixAllInProject:|}if (i == 3) + { + return 0; + } + else + { + if (i == 6) return 1; + if (i == 7) return 1; + return 0; + } + } + } + + + class C2 + { + int M2(int i) + { + if (i == 3) + { + return 0; + } + else + { + if (i == 6) return 1; + if (i == 7) return 1; + return 0; + } + } + } + + + + + class C3 + { + int M3(int i) + { + if (i == 3) + { + return 0; + } + else + { + if (i == 6) return 1; + if (i == 7) return 1; + return 0; + } + } + } + + + + """, + """ + + + + class C + { + int M(int i) { switch (i) { + case 3: + return 0; case 6: return 1; case 7: - return 2; + return 1; default: - return 3; + return 0; } } - break; - } - } -}"); - } - - [Fact] - public async Task ConvertIfToSwitchStatement_FixAllInProject() - { - await TestInRegularAndScriptAsync( -@" - - - -class C -{ - int M(int i) - { - {|FixAllInProject:|}if (i == 3) - { - return 0; - } - else - { - if (i == 6) return 1; - if (i == 7) return 1; - return 0; - } - } -} - - -class C2 -{ - int M2(int i) - { - if (i == 3) - { - return 0; - } - else - { - if (i == 6) return 1; - if (i == 7) return 1; - return 0; - } - } -} - - - - -class C3 -{ - int M3(int i) - { - if (i == 3) - { - return 0; - } - else - { - if (i == 6) return 1; - if (i == 7) return 1; - return 0; - } - } -} - - -", -@" - - -class C -{ - int M(int i) - { - switch (i) - { - case 3: - return 0; - case 6: - return 1; - case 7: - return 1; - default: - return 0; - } - } -} - - -class C2 -{ - int M2(int i) - { - switch (i) - { - case 3: - return 0; - case 6: - return 1; - case 7: - return 1; - default: - return 0; - } - } -} - - - - -class C3 -{ - int M3(int i) - { - if (i == 3) - { - return 0; - } - else - { - if (i == 6) return 1; - if (i == 7) return 1; - return 0; - } - } -} - - -"); - } + } + + + class C2 + { + int M2(int i) + { + switch (i) + { + case 3: + return 0; + case 6: + return 1; + case 7: + return 1; + default: + return 0; + } + } + } + + + + + class C3 + { + int M3(int i) + { + if (i == 3) + { + return 0; + } + else + { + if (i == 6) return 1; + if (i == 7) return 1; + return 0; + } + } + } + + + + """); [Fact] - public async Task ConvertIfToSwitchStatement_FixAllInSolution() - { - await TestInRegularAndScriptAsync( -@" - - - -class C -{ - int M(int i) - { - {|FixAllInSolution:|}if (i == 3) - { - return 0; - } - else - { - if (i == 6) return 1; - if (i == 7) return 1; - return 0; - } - } -} - - -class C2 -{ - int M2(int i) - { - if (i == 3) - { - return 0; - } - else - { - if (i == 6) return 1; - if (i == 7) return 1; - return 0; - } - } -} - - - - -class C3 -{ - int M3(int i) - { - if (i == 3) - { - return 0; - } - else - { - if (i == 6) return 1; - if (i == 7) return 1; - return 0; - } - } -} - - -", -@" - - -class C -{ - int M(int i) - { - switch (i) - { - case 3: - return 0; - case 6: - return 1; - case 7: - return 1; - default: - return 0; - } - } -} - - -class C2 -{ - int M2(int i) - { - switch (i) - { - case 3: - return 0; - case 6: - return 1; - case 7: - return 1; - default: - return 0; - } - } -} - - - - -class C3 -{ - int M3(int i) - { - switch (i) - { - case 3: - return 0; - case 6: - return 1; - case 7: - return 1; - default: - return 0; - } - } -} - - -"); - } + public Task ConvertIfToSwitchStatement_FixAllInSolution() + => TestInRegularAndScriptAsync( + """ + + + + class C + { + int M(int i) + { + {|FixAllInSolution:|}if (i == 3) + { + return 0; + } + else + { + if (i == 6) return 1; + if (i == 7) return 1; + return 0; + } + } + } + + + class C2 + { + int M2(int i) + { + if (i == 3) + { + return 0; + } + else + { + if (i == 6) return 1; + if (i == 7) return 1; + return 0; + } + } + } + + + + + class C3 + { + int M3(int i) + { + if (i == 3) + { + return 0; + } + else + { + if (i == 6) return 1; + if (i == 7) return 1; + return 0; + } + } + } + + + + """, + """ + + + + class C + { + int M(int i) + { + switch (i) + { + case 3: + return 0; + case 6: + return 1; + case 7: + return 1; + default: + return 0; + } + } + } + + + class C2 + { + int M2(int i) + { + switch (i) + { + case 3: + return 0; + case 6: + return 1; + case 7: + return 1; + default: + return 0; + } + } + } + + + + + class C3 + { + int M3(int i) + { + switch (i) + { + case 3: + return 0; + case 6: + return 1; + case 7: + return 1; + default: + return 0; + } + } + } + + + + """); [Fact] - public async Task ConvertIfToSwitchStatement_FixAllInContainingMember() - { - await TestInRegularAndScriptAsync( -@"class C -{ - int M(int i) - { - {|FixAllInContainingMember:|}if (i == 3) - { - return 0; - } - else - { - if (i == 6) return 1; - if (i == 7) return 1; - return 0; - } - } + public Task ConvertIfToSwitchStatement_FixAllInContainingMember() + => TestInRegularAndScriptAsync( + """ + class C + { + int M(int i) + { + {|FixAllInContainingMember:|}if (i == 3) + { + return 0; + } + else + { + if (i == 6) return 1; + if (i == 7) return 1; + return 0; + } + } - int M2(int i) - { - if (i == 3) - { - return 0; - } - else - { - if (i == 6) return 1; - if (i == 7) return 1; - return 0; - } - } -}", -@"class C -{ - int M(int i) - { - switch (i) - { - case 3: - return 0; - case 6: - return 1; - case 7: - return 1; - default: - return 0; - } - } + int M2(int i) + { + if (i == 3) + { + return 0; + } + else + { + if (i == 6) return 1; + if (i == 7) return 1; + return 0; + } + } + } + """, + """ + class C + { + int M(int i) + { + switch (i) + { + case 3: + return 0; + case 6: + return 1; + case 7: + return 1; + default: + return 0; + } + } - int M2(int i) - { - if (i == 3) - { - return 0; - } - else - { - if (i == 6) return 1; - if (i == 7) return 1; - return 0; - } - } -}"); - } + int M2(int i) + { + if (i == 3) + { + return 0; + } + else + { + if (i == 6) return 1; + if (i == 7) return 1; + return 0; + } + } + } + """); [Fact] - public async Task ConvertIfToSwitchStatement_FixAllInContainingType() - { - await TestInRegularAndScriptAsync( -@"class C -{ - int M(int i) - { - {|FixAllInContainingType:|}if (i == 3) - { - return 0; - } - else - { - if (i == 6) return 1; - if (i == 7) return 1; - return 0; - } - } + public Task ConvertIfToSwitchStatement_FixAllInContainingType() + => TestInRegularAndScriptAsync( + """ + class C + { + int M(int i) + { + {|FixAllInContainingType:|}if (i == 3) + { + return 0; + } + else + { + if (i == 6) return 1; + if (i == 7) return 1; + return 0; + } + } - int M2(int i) - { - if (i == 3) - { - return 0; - } - else - { - if (i == 6) return 1; - if (i == 7) return 1; - return 0; - } - } -} + int M2(int i) + { + if (i == 3) + { + return 0; + } + else + { + if (i == 6) return 1; + if (i == 7) return 1; + return 0; + } + } + } -class C2 -{ - int M3(int i) - { - if (i == 3) - { - return 0; - } - else - { - if (i == 6) return 1; - if (i == 7) return 1; - return 0; - } - } -}", -@"class C -{ - int M(int i) - { - switch (i) - { - case 3: - return 0; - case 6: - return 1; - case 7: - return 1; - default: - return 0; - } - } + class C2 + { + int M3(int i) + { + if (i == 3) + { + return 0; + } + else + { + if (i == 6) return 1; + if (i == 7) return 1; + return 0; + } + } + } + """, + """ + class C + { + int M(int i) + { + switch (i) + { + case 3: + return 0; + case 6: + return 1; + case 7: + return 1; + default: + return 0; + } + } - int M2(int i) - { - switch (i) - { - case 3: - return 0; - case 6: - return 1; - case 7: - return 1; - default: - return 0; - } - } -} + int M2(int i) + { + switch (i) + { + case 3: + return 0; + case 6: + return 1; + case 7: + return 1; + default: + return 0; + } + } + } -class C2 -{ - int M3(int i) - { - if (i == 3) - { - return 0; - } - else - { - if (i == 6) return 1; - if (i == 7) return 1; - return 0; - } - } -}"); - } + class C2 + { + int M3(int i) + { + if (i == 3) + { + return 0; + } + else + { + if (i == 6) return 1; + if (i == 7) return 1; + return 0; + } + } + } + """); } diff --git a/src/Features/CSharpTest/ConvertIfToSwitch/ConvertIfToSwitchTests.cs b/src/Features/CSharpTest/ConvertIfToSwitch/ConvertIfToSwitchTests.cs index b6740d8190d2b..f7f586b16b66b 100644 --- a/src/Features/CSharpTest/ConvertIfToSwitch/ConvertIfToSwitchTests.cs +++ b/src/Features/CSharpTest/ConvertIfToSwitch/ConvertIfToSwitchTests.cs @@ -20,10 +20,10 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.ConvertIfTo public sealed class ConvertIfToSwitchTests { [Fact] - public async Task TestUnreachableEndPoint() - { - var source = - """ + public Task TestUnreachableEndPoint() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -32,9 +32,8 @@ void M(int i) return; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -48,21 +47,15 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact] - public async Task TestReachableEndPoint() - { - var source = - """ + public Task TestReachableEndPoint() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -71,9 +64,8 @@ void M(int i) M(i); } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -88,15 +80,9 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact] public async Task TestMissingOnSubsequentBlock() @@ -172,10 +158,10 @@ class C } [Fact] - public async Task TestElseBlock_02() - { - var source = - """ + public Task TestElseBlock_02() + => new VerifyCS.Test + { + TestCode = """ class C { int M(int i) @@ -192,9 +178,8 @@ int M(int i) } } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { int M(int i) @@ -212,21 +197,15 @@ int M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact] - public async Task TestMultipleCases_01() - { - var source = - """ + public Task TestMultipleCases_01() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -236,9 +215,8 @@ void M(int i) else M(2); } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -261,21 +239,15 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact] - public async Task TestMultipleCases_02_CSharp8() - { - var source = - """ + public Task TestMultipleCases_02_CSharp8() + => new VerifyCS.Test + { + TestCode = """ class C { void M(object o) @@ -285,9 +257,8 @@ void M(object o) else return; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(object o) @@ -305,21 +276,15 @@ void M(object o) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] - public async Task TestMultipleCases_02_CSharp9() - { - var source = - """ + public Task TestMultipleCases_02_CSharp9() + => new VerifyCS.Test + { + TestCode = """ class C { void M(object o) @@ -329,9 +294,8 @@ void M(object o) else return; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(object o) @@ -349,21 +313,15 @@ void M(object o) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestExpressionOrder() - { - var source = - """ + public Task TestExpressionOrder() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -372,9 +330,8 @@ void M(int i) return; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -388,21 +345,15 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact] - public async Task TestConstantExpression() - { - var source = - """ + public Task TestConstantExpression() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -412,9 +363,8 @@ void M(int i) return; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -429,15 +379,9 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact] public async Task TestMissingOnNonConstantExpression() @@ -496,17 +440,6 @@ void M(int i) public async Task TestIsExpression( [CombinatorialValues(LanguageVersion.CSharp8, LanguageVersion.CSharp9)] LanguageVersion languageVersion) { - var source = - """ - class C - { - void M(object o) - { - $$if (o is int || o is string || o is C) - return; - } - } - """; var fixedSource = languageVersion switch { LanguageVersion.CSharp8 => @@ -546,7 +479,16 @@ void M(object o) await new VerifyCS.Test { - TestCode = source, + TestCode = """ + class C + { + void M(object o) + { + $$if (o is int || o is string || o is C) + return; + } + } + """, FixedCode = fixedSource, LanguageVersion = languageVersion, CodeActionValidationMode = CodeActionValidationMode.None, @@ -554,9 +496,8 @@ void M(object o) } [Fact] - public async Task TestIsPatternExpression_01() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestIsPatternExpression_01() + => VerifyCS.VerifyRefactoringAsync( """ class C { @@ -584,13 +525,12 @@ void M(object o) } } """); - } [Fact] - public async Task TestIsPatternExpression_02_CSharp8() - { - var source = - """ + public Task TestIsPatternExpression_02_CSharp8() + => new VerifyCS.Test + { + TestCode = """ class C { void M(object o) @@ -601,9 +541,8 @@ void M(object o) return; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(object o) @@ -617,21 +556,15 @@ void M(object o) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] - public async Task TestIsPatternExpression_02_CSharp9() - { - var source = - """ + public Task TestIsPatternExpression_02_CSharp9() + => new VerifyCS.Test + { + TestCode = """ class C { void M(object o) @@ -642,9 +575,8 @@ void M(object o) return; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(object o) @@ -658,20 +590,13 @@ void M(object o) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] - public async Task TestIsPatternExpression_03() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestIsPatternExpression_03() + => VerifyCS.VerifyRefactoringAsync( """ class C { @@ -699,12 +624,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestIsPatternExpression_04() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestIsPatternExpression_04() + => VerifyCS.VerifyRefactoringAsync( """ class C { @@ -732,12 +655,10 @@ void M(object o) } } """); - } [Fact] - public async Task TestComplexExpression_01() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestComplexExpression_01() + => VerifyCS.VerifyRefactoringAsync( """ class C { @@ -774,7 +695,6 @@ void M(object o) } } """); - } [Fact] public async Task TestMissingIfCaretDoesntIntersectWithTheIfKeyword() @@ -794,10 +714,10 @@ void M(int i) } [Fact] - public async Task TestKeepBlockIfThereIsVariableDeclaration() - { - var source = - """ + public Task TestKeepBlockIfThereIsVariableDeclaration() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -811,9 +731,8 @@ void M(int i) } } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -831,15 +750,9 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact] public async Task TestMissingOnBreak_01() @@ -887,10 +800,10 @@ await VerifyCS.VerifyRefactoringAsync( } [Fact] - public async Task TestNestedBreak() - { - var source = - """ + public Task TestNestedBreak() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -907,9 +820,8 @@ void M(int i) } } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -927,21 +839,15 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact] - public async Task TestSubsequentIfStatements_01() - { - var source = - """ + public Task TestSubsequentIfStatements_01() + => new VerifyCS.Test + { + TestCode = """ class C { int M(int? i) @@ -951,9 +857,8 @@ int M(int? i) return 7; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { int M(int? i) @@ -969,21 +874,15 @@ int M(int? i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact] - public async Task TestSwitchExpression_01() - { - var source = - """ + public Task TestSwitchExpression_01() + => new VerifyCS.Test + { + TestCode = """ class C { int M(int? i) @@ -993,9 +892,8 @@ int M(int? i) return 7; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { int M(int? i) @@ -1008,22 +906,16 @@ int M(int? i) }; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionIndex = 1, CodeActionEquivalenceKey = "SwitchExpression", }.RunAsync(); - } [Fact] - public async Task TestSwitchExpression_02() - { - var source = - """ + public Task TestSwitchExpression_02() + => new VerifyCS.Test + { + TestCode = """ class C { int M(int? i) @@ -1033,9 +925,8 @@ int M(int? i) else { return 7; } } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { int M(int? i) @@ -1048,22 +939,16 @@ int M(int? i) }; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionIndex = 1, CodeActionEquivalenceKey = "SwitchExpression", }.RunAsync(); - } [Fact] - public async Task TestSubsequentIfStatements_02() - { - var source = - """ + public Task TestSubsequentIfStatements_02() + => new VerifyCS.Test + { + TestCode = """ class C { int M(int? i) @@ -1074,9 +959,8 @@ int M(int? i) return 7; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { int M(int? i) @@ -1092,15 +976,9 @@ int M(int? i) return 7; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact] public async Task TestSubsequentIfStatements_03() @@ -1169,10 +1047,10 @@ class C } [Fact] - public async Task TestSubsequentIfStatements_04() - { - var source = - """ + public Task TestSubsequentIfStatements_04() + => new VerifyCS.Test + { + TestCode = """ class C { string M(object i) @@ -1182,9 +1060,8 @@ string M(object i) else return i.ToString(); } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { string M(object i) @@ -1201,21 +1078,15 @@ string M(object i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact] - public async Task TestSubsequentIfStatements_05() - { - var source = - """ + public Task TestSubsequentIfStatements_05() + => new VerifyCS.Test + { + TestCode = """ class C { int M(int i) @@ -1226,9 +1097,8 @@ int M(int i) return 7; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { int M(int i) @@ -1244,21 +1114,15 @@ int M(int i) return 7; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact] - public async Task TestSubsequentIfStatements_06() - { - var source = - """ + public Task TestSubsequentIfStatements_06() + => new VerifyCS.Test + { + TestCode = """ class C { int M(int i) @@ -1278,9 +1142,8 @@ int M(int i) return 7; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { int M(int i) @@ -1299,21 +1162,15 @@ int M(int i) return 7; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact] - public async Task TestSubsequentIfStatements_07() - { - var source = - """ + public Task TestSubsequentIfStatements_07() + => new VerifyCS.Test + { + TestCode = """ class C { int M(int i) @@ -1342,9 +1199,8 @@ int M(int i) return 7; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { int M(int i) @@ -1372,15 +1228,9 @@ int M(int i) return 7; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21109")] public async Task TestTrivia1() @@ -1466,10 +1316,10 @@ class C } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21101")] - public async Task TestTrivia2() - { - var source = - """ + public Task TestTrivia2() + => new VerifyCS.Test + { + TestCode = """ class C { int M(int i, string[] args) @@ -1480,9 +1330,8 @@ int M(int i, string[] args) return /* t7 */ 3 /* t8 */; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { int M(int i, string[] args) @@ -1496,21 +1345,15 @@ int M(int i, string[] args) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21360")] - public async Task TestCompoundLogicalAnd1_CSharp8() - { - var source = - """ + public Task TestCompoundLogicalAnd1_CSharp8() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -1521,9 +1364,8 @@ void M(int i) return; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -1537,33 +1379,14 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp8, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21360")] public async Task TestCompoundLogicalAnd1_CSharp9() { - var source = - """ - class C - { - void M(int i) - { - $$if (i == 1 && i == 2) - return; - else if (i == 10) - return; - } - } - """; var fixedSource = """ class C @@ -1583,7 +1406,18 @@ void M(int i) await new VerifyCS.Test { - TestCode = source, + TestCode = """ + class C + { + void M(int i) + { + $$if (i == 1 && i == 2) + return; + else if (i == 10) + return; + } + } + """, FixedState = { Sources = { fixedSource }, @@ -1599,10 +1433,10 @@ void M(int i) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21360")] - public async Task TestCompoundLogicalAnd2_CSharp8() - { - var source = - """ + public Task TestCompoundLogicalAnd2_CSharp8() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -1613,9 +1447,8 @@ void M(int i) return; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -1629,33 +1462,14 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp8, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21360")] public async Task TestCompoundLogicalAnd2_CSharp9() { - var source = - """ - class C - { - void M(int i) - { - $$if (i == 1 && i == 2 && i == 3) - return; - else if (i == 10) - return; - } - } - """; var fixedSource = """ class C @@ -1675,7 +1489,18 @@ void M(int i) await new VerifyCS.Test { - TestCode = source, + TestCode = """ + class C + { + void M(int i) + { + $$if (i == 1 && i == 2 && i == 3) + return; + else if (i == 10) + return; + } + } + """, FixedState = { Sources = { fixedSource }, @@ -1691,10 +1516,10 @@ void M(int i) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21360")] - public async Task TestCompoundLogicalAnd3_CSharp8() - { - var source = - """ + public Task TestCompoundLogicalAnd3_CSharp8() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -1705,9 +1530,8 @@ void M(int i) return; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -1721,33 +1545,14 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp8, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21360")] public async Task TestCompoundLogicalAnd3_CSharp9() { - var source = - """ - class C - { - void M(int i) - { - $$if (i == 1 && i == 2 && (i == 3)) - return; - else if (i == 10) - return; - } - } - """; var fixedSource = """ class C @@ -1767,7 +1572,18 @@ void M(int i) await new VerifyCS.Test { - TestCode = source, + TestCode = """ + class C + { + void M(int i) + { + $$if (i == 1 && i == 2 && (i == 3)) + return; + else if (i == 10) + return; + } + } + """, FixedState = { Sources = { fixedSource }, @@ -1783,10 +1599,10 @@ void M(int i) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21360")] - public async Task TestCompoundLogicalAnd4() - { - var source = - """ + public Task TestCompoundLogicalAnd4() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -1797,9 +1613,8 @@ void M(int i) return; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -1813,33 +1628,14 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp8, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21360")] public async Task TestCompoundLogicalAnd4_CSharp9() { - var source = - """ - class C - { - void M(int i) - { - $$if (i == 1 && (i == 2) && i == 3) - return; - else if (i == 10) - return; - } - } - """; var fixedSource = """ class C @@ -1859,7 +1655,18 @@ void M(int i) await new VerifyCS.Test { - TestCode = source, + TestCode = """ + class C + { + void M(int i) + { + $$if (i == 1 && (i == 2) && i == 3) + return; + else if (i == 10) + return; + } + } + """, FixedState = { Sources = { fixedSource }, @@ -1875,10 +1682,10 @@ void M(int i) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21360")] - public async Task TestCompoundLogicalAnd5() - { - var source = - """ + public Task TestCompoundLogicalAnd5() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -1889,9 +1696,8 @@ void M(int i) return; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -1905,21 +1711,15 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21360")] - public async Task TestCompoundLogicalAnd6() - { - var source = - """ + public Task TestCompoundLogicalAnd6() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -1930,9 +1730,8 @@ void M(int i) return; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -1946,21 +1745,15 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21360")] - public async Task TestCompoundLogicalAnd7() - { - var source = - """ + public Task TestCompoundLogicalAnd7() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -1971,9 +1764,8 @@ void M(int i) return; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -1987,21 +1779,15 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21360")] - public async Task TestCompoundLogicalAnd8() - { - var source = - """ + public Task TestCompoundLogicalAnd8() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -2012,9 +1798,8 @@ void M(int i) return; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -2028,21 +1813,15 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21360")] - public async Task TestCompoundLogicalAnd9() - { - var source = - """ + public Task TestCompoundLogicalAnd9() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -2053,9 +1832,8 @@ void M(int i) return; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -2069,21 +1847,15 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21360")] - public async Task TestCompoundLogicalAnd10() - { - var source = - """ + public Task TestCompoundLogicalAnd10() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -2094,9 +1866,8 @@ void M(int i) return; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -2110,21 +1881,15 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21360")] - public async Task TestCompoundLogicalAnd11() - { - var source = - """ + public Task TestCompoundLogicalAnd11() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -2135,9 +1900,8 @@ void M(int i) return; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -2151,21 +1915,15 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21360")] - public async Task TestCompoundLogicalAnd12() - { - var source = - """ + public Task TestCompoundLogicalAnd12() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -2176,9 +1934,8 @@ void M(int i) return; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -2192,21 +1949,15 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21360")] - public async Task TestCompoundLogicalAnd13() - { - var source = - """ + public Task TestCompoundLogicalAnd13() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -2217,9 +1968,8 @@ void M(int i) return; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -2233,21 +1983,15 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21360")] - public async Task TestCompoundLogicalAnd14() - { - var source = - """ + public Task TestCompoundLogicalAnd14() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -2258,9 +2002,8 @@ void M(int i) return; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -2274,21 +2017,15 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21360")] - public async Task TestCompoundLogicalAnd15() - { - var source = - """ + public Task TestCompoundLogicalAnd15() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -2299,9 +2036,8 @@ void M(int i) return; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -2315,21 +2051,15 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21360")] - public async Task TestCompoundLogicalAnd16() - { - var source = - """ + public Task TestCompoundLogicalAnd16() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -2340,9 +2070,8 @@ void M(int i) return; } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -2356,20 +2085,13 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37035")] - public async Task TestComplexExpression_02() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestComplexExpression_02() + => VerifyCS.VerifyRefactoringAsync( """ class C { @@ -2401,13 +2123,12 @@ void M(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task TestRange_CSharp8() - { - var source = - """ + public Task TestRange_CSharp8() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -2422,20 +2143,15 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task TestRange_CSharp9() - { - var source = - """ + public Task TestRange_CSharp9() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -2450,9 +2166,8 @@ void M(int i) } } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -2466,21 +2181,15 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task TestComparison_CSharp8() - { - var source = - """ + public Task TestComparison_CSharp8() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -2491,20 +2200,15 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task TestComparison_CSharp9() - { - var source = - """ + public Task TestComparison_CSharp9() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -2515,9 +2219,8 @@ void M(int i) } } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -2530,36 +2233,13 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] public async Task TestComparison_SwitchExpression_CSharp9() { - var source = - """ - class C - { - int M(int i) - { - $$if (5 >= i || 1 <= i) - { - return 1; - } - else - { - return 2; - } - } - } - """; var fixedSource = """ class C @@ -2577,7 +2257,22 @@ int M(int i) await new VerifyCS.Test { - TestCode = source, + TestCode = """ + class C + { + int M(int i) + { + $$if (5 >= i || 1 <= i) + { + return 1; + } + else + { + return 2; + } + } + } + """, FixedState = { Sources = { fixedSource }, @@ -2594,10 +2289,10 @@ int M(int i) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task TestComplexIf_CSharp8() - { - var source = - """ + public Task TestComplexIf_CSharp8() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -2608,31 +2303,13 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] public async Task TestComplexIf_CSharp9() { - var source = - """ - class C - { - void M(int i) - { - $$if (i < 10 || 20 < i || (i >= 30 && 40 >= i) || i == 50) - { - return; - } - } - } - """; var fixedSource = """ class C @@ -2653,7 +2330,18 @@ void M(int i) await new VerifyCS.Test { - TestCode = source, + TestCode = """ + class C + { + void M(int i) + { + $$if (i < 10 || 20 < i || (i >= 30 && 40 >= i) || i == 50) + { + return; + } + } + } + """, FixedState = { Sources = { fixedSource }, @@ -2671,10 +2359,10 @@ void M(int i) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task TestComplexIf_Precedence_CSharp9() - { - var source = - """ + public Task TestComplexIf_Precedence_CSharp9() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -2685,9 +2373,8 @@ void M(int i) } } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void M(int i) @@ -2700,22 +2387,16 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp9, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact] - public async Task TestInequality() - { - var source = - """ + public Task TestInequality() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int i) @@ -2726,10 +2407,8 @@ void M(int i) } } } - """; - - var fixedSource = -""" + """, + FixedCode = """ class C { void M(int i) @@ -2742,21 +2421,17 @@ void M(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp9, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44278")] public async Task TestTopLevelStatement() { - var source = """ + var test = new VerifyCS.Test + { + TestCode = """ var e = new ET1(); [||]if (e == ET1.A) @@ -2772,9 +2447,8 @@ enum ET1 B, C, } - """; - - var fixedSource = """ + """, + FixedCode = """ var e = new ET1(); switch (e) @@ -2791,12 +2465,7 @@ enum ET1 B, C, } - """; - - var test = new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp9, CodeActionValidationMode = CodeActionValidationMode.None, }; @@ -2809,9 +2478,10 @@ enum ET1 } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46863")] - public async Task CommentsAtTheEndOfBlocksShouldBePlacedBeforeBreakStatements() - { - var source = """ + public Task CommentsAtTheEndOfBlocksShouldBePlacedBeforeBreakStatements() + => new VerifyCS.Test + { + TestCode = """ class C { void M(int p) @@ -2831,9 +2501,8 @@ void M(int p) void DoA() { } void DoB() { } } - """; - - var fixedSource = """ + """, + FixedCode = """ class C { void M(int p) @@ -2854,21 +2523,15 @@ void M(int p) void DoA() { } void DoB() { } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact] - public async Task TestMissingOnImplicitCastInRelationalPattern() - { - var source = - """ + public Task TestMissingOnImplicitCastInRelationalPattern() + => new VerifyCS.Test + { + TestCode = """ class C { void M(char c) @@ -2877,20 +2540,15 @@ void M(char c) System.Console.WriteLine(c); } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestMissingExpressionOnImplicitCastInRelationalPattern() - { - var source = - """ + public Task TestMissingExpressionOnImplicitCastInRelationalPattern() + => new VerifyCS.Test + { + TestCode = """ class C { int M(char c) @@ -2901,20 +2559,15 @@ int M(char c) return 2; } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestMissingOnImplicitCastInRangePattern() - { - var source = - """ + public Task TestMissingOnImplicitCastInRangePattern() + => new VerifyCS.Test + { + TestCode = """ class C { void M(char c) @@ -2923,20 +2576,15 @@ void M(char c) System.Console.WriteLine(c); } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestMissingOnImplicitCastInConstantPattern() - { - var source = - """ + public Task TestMissingOnImplicitCastInConstantPattern() + => new VerifyCS.Test + { + TestCode = """ class C { void M(char c) @@ -2945,20 +2593,15 @@ void M(char c) System.Console.WriteLine(c); } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task TestExplicitCastInConstantPattern() - { - var source = - """ + public Task TestExplicitCastInConstantPattern() + => new VerifyCS.Test + { + TestCode = """ class C { void M(char c) @@ -2967,10 +2610,8 @@ void M(char c) System.Console.WriteLine(c); } } - """; - - var fixedSource = - """ + """, + FixedCode = """ class C { void M(char c) @@ -2984,22 +2625,16 @@ void M(char c) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, LanguageVersion = LanguageVersion.CSharp9, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41131")] - public async Task MoveTriviaFromElse1() - { - var source = - """ + public Task MoveTriviaFromElse1() + => new VerifyCS.Test + { + TestCode = """ using System; class C @@ -3022,9 +2657,8 @@ void M() } } } - """; - var fixedSource = - """ + """, + FixedCode = """ using System; class C @@ -3047,21 +2681,15 @@ void M() } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41131")] - public async Task MoveTriviaFromElse2() - { - var source = - """ + public Task MoveTriviaFromElse2() + => new VerifyCS.Test + { + TestCode = """ using System; class C @@ -3085,9 +2713,8 @@ void M() } } } - """; - var fixedSource = - """ + """, + FixedCode = """ using System; class C @@ -3111,21 +2738,15 @@ void M() } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71295")] - public async Task TestCodeAfterElseIf() - { - var source = - """ + public Task TestCodeAfterElseIf() + => new VerifyCS.Test + { + TestCode = """ class C { void TestThing(int a, int b) @@ -3144,9 +2765,8 @@ void TestThing(int a, int b) } } } - """; - var fixedSource = - """ + """, + FixedCode = """ class C { void TestThing(int a, int b) @@ -3166,13 +2786,7 @@ void TestThing(int a, int b) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = fixedSource, + """, CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); - } } diff --git a/src/Features/CSharpTest/ConvertLinq/ConvertForEachToLinqQueryTests.cs b/src/Features/CSharpTest/ConvertLinq/ConvertForEachToLinqQueryTests.cs index 91a4baf8d852b..8a71b09403eea 100644 --- a/src/Features/CSharpTest/ConvertLinq/ConvertForEachToLinqQueryTests.cs +++ b/src/Features/CSharpTest/ConvertLinq/ConvertForEachToLinqQueryTests.cs @@ -45,7 +45,7 @@ public IEnumerable void Main(string[] args) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class Query @@ -60,11 +60,8 @@ where object.Equals(x1, x2 / 10) select x1 + x2; } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class Query @@ -76,9 +73,7 @@ public IEnumerable void Main(string[] args) return c1.SelectMany(x1 => c2.Where(x2 => object.Equals(x1, x2 / 10)).Select(x2 => x1 + x2)); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -103,7 +98,7 @@ public IEnumerable void Main(string[] args) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class Query @@ -117,11 +112,8 @@ from x2 in c2 select @object + x2; } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class Query @@ -133,9 +125,7 @@ public IEnumerable void Main(string[] args) return c1.SelectMany(@object => c2.Select(x2 => @object + x2)); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -172,7 +162,7 @@ IEnumerable M() } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Linq; class C @@ -190,9 +180,7 @@ where object.Equals(num, x2) select n2 + n1; } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); + """, index: 0); // No linq refactoring offered due to variable declaration within the outermost foreach. await TestActionCountAsync(source, count: 1); @@ -233,7 +221,7 @@ IEnumerable M() } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; @@ -252,11 +240,8 @@ where object.Equals(num, x2) select n2 + n1; } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; @@ -272,9 +257,7 @@ IEnumerable M() } } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -312,7 +295,7 @@ IEnumerable M() } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; @@ -331,11 +314,8 @@ where object.Equals(num, x2) select n2 + n1; } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; @@ -360,9 +340,7 @@ IEnumerable M() } } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -388,7 +366,7 @@ void M() } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System; using System.Collections.Generic; using System.Linq; @@ -404,18 +382,15 @@ void M() select x + z - a).ToList(); } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); + """, index: 0); // No linq invocation refactoring offered due to variable declaration(s) in topmost foreach. await TestActionCountAsync(source, count: 1); } [Fact] - public async Task QueryEmptyDeclarations() - { - var source = """ + public Task QueryEmptyDeclarations() + => TestMissingInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -434,10 +409,7 @@ void M() }|] } } - """; - - await TestMissingInRegularAndScriptAsync(source); - } + """); [Fact] public async Task QueryWhereClause() @@ -460,7 +432,7 @@ IEnumerable M() } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System; using System.Linq; class C @@ -473,10 +445,8 @@ where x > 2 select x; } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System; using System.Linq; class C @@ -487,9 +457,7 @@ IEnumerable M() return nums.Where(x => x > 2); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -513,7 +481,7 @@ IEnumerable M() } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System; using System.Linq; class C @@ -528,10 +496,8 @@ from x in nums select x select y; } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System; using System.Linq; class C @@ -542,9 +508,7 @@ IEnumerable M() return (from x in nums select x).SelectMany(y => (from x in nums select x).Select(z => y)); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -567,7 +531,7 @@ void M() } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System; using System.Linq; class C @@ -582,10 +546,8 @@ from b in new[] { 2 } } } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System; using System.Linq; class C @@ -598,9 +560,7 @@ void M() } } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -619,7 +579,7 @@ void M() } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System; using System.Linq; class C @@ -634,10 +594,8 @@ from b in new[] { 2 } } } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System; using System.Linq; class C @@ -650,9 +608,7 @@ void M() } } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -671,7 +627,7 @@ void M() } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System; using System.Linq; class C @@ -686,10 +642,8 @@ from b in new[] { 2 } } } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System; using System.Linq; class C @@ -702,9 +656,7 @@ void M() } } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -726,7 +678,7 @@ void M() } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System; using System.Linq; class C @@ -742,10 +694,8 @@ from b in new[] { 2 } } } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System; using System.Linq; class C @@ -759,9 +709,7 @@ void M() } } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -783,7 +731,7 @@ void M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -797,10 +745,8 @@ from int n2 in nums } } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -812,9 +758,7 @@ void M(IEnumerable nums) } } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -834,7 +778,7 @@ void M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -848,10 +792,8 @@ from int n2 in nums } } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -863,9 +805,7 @@ void M(IEnumerable nums) } } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -884,7 +824,7 @@ void M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; @@ -899,10 +839,8 @@ from int n2 in nums } } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; @@ -915,9 +853,7 @@ void M(IEnumerable nums) } } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -935,7 +871,7 @@ void M(int[] nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Linq; class C @@ -949,10 +885,8 @@ from int n2 in nums } } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Linq; class C @@ -964,9 +898,7 @@ void M(int[] nums) } } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -989,7 +921,7 @@ void M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -1004,10 +936,8 @@ from int n2 in nums } } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -1020,9 +950,7 @@ void M(IEnumerable nums) } } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -1045,7 +973,7 @@ void M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -1061,10 +989,8 @@ from int n2 in nums } } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -1077,9 +1003,7 @@ void M(IEnumerable nums) } } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } #endregion @@ -1109,7 +1033,7 @@ IEnumerable M(IEnumerable nums) int N(int n) => n; } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System; using System.Collections.Generic; using System.Linq; @@ -1124,10 +1048,8 @@ from int n2 in nums int N(int n) => n; } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System; using System.Collections.Generic; using System.Linq; @@ -1140,9 +1062,7 @@ IEnumerable M(IEnumerable nums) int N(int n) => n; } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -1157,7 +1077,7 @@ public class Test public IEnumerable Query1 { get { [|foreach (var x in _nums) { yield return x + 1; }|] } } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; public class Test @@ -1165,11 +1085,8 @@ public class Test private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable Query1 { get { return from x in _nums select x + 1; } } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; public class Test @@ -1177,9 +1094,7 @@ public class Test private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable Query1 { get { return _nums.Select(x => x + 1); } } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -1202,7 +1117,7 @@ IEnumerable M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -1214,11 +1129,8 @@ from int n2 in nums select n1; } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -1228,9 +1140,7 @@ IEnumerable M(IEnumerable nums) return nums.SelectMany(n1 => nums.Select(n2 => n1)); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -1260,7 +1170,7 @@ IEnumerable f(int a) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -1276,11 +1186,8 @@ IEnumerable f(int a) } } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -1294,9 +1201,7 @@ IEnumerable f(int a) } } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -1325,7 +1230,7 @@ partial IEnumerable M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; partial class C @@ -1341,10 +1246,8 @@ from int n2 in nums select n1; } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; partial class C @@ -1358,9 +1261,7 @@ partial IEnumerable M(IEnumerable nums) return nums.SelectMany(n1 => nums.Select(n2 => n1)); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -1389,7 +1290,7 @@ public partial IEnumerable M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; partial class C @@ -1405,10 +1306,8 @@ from int n2 in nums select n1; } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; partial class C @@ -1422,15 +1321,12 @@ public partial IEnumerable M(IEnumerable nums) return nums.SelectMany(n1 => nums.Select(n2 => n1)); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31784")] - public async Task QueryWhichRequiresSelectManyWithIdentityLambda() - { - var source = """ + public Task QueryWhichRequiresSelectManyWithIdentityLambda() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; class C @@ -1446,9 +1342,7 @@ IEnumerable M() }|] } } - """; - - var linqInvocationOutput = """ + """, """ using System.Collections.Generic; using System.Linq; @@ -1459,10 +1353,7 @@ IEnumerable M() return (new[] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 } }).SelectMany(x => x); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); - } + """, index: 1); #endregion @@ -1502,7 +1393,7 @@ void M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System; using System.Collections.Generic; using System.Linq; @@ -1531,10 +1422,8 @@ from A c in nums } } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System; using System.Collections.Generic; using System.Linq; @@ -1561,9 +1450,7 @@ void M(IEnumerable nums) } } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -1599,7 +1486,7 @@ void M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System; using System.Collections.Generic; using System.Linq; @@ -1627,10 +1514,8 @@ from A c in nums } } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System; using System.Collections.Generic; using System.Linq; @@ -1656,9 +1541,7 @@ void M(IEnumerable nums) } } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -1694,7 +1577,7 @@ IEnumerable Test() } } """; - var queryOutput = """ + await TestAsync(source, """ using System; using System.Collections.Generic; using System.Linq; @@ -1722,10 +1605,8 @@ IEnumerable Test() select x; } } - """; - await TestAsync(source, queryOutput, parseOptions: null); - - var linqInvocationOutput = """ + """, parseOptions: null); + await TestInRegularAndScriptAsync(source, """ using System; using System.Collections.Generic; using System.Linq; @@ -1752,9 +1633,7 @@ IEnumerable Test() return new[] { 1, 2, 3 }; } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -1777,7 +1656,7 @@ IEnumerable M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; @@ -1789,10 +1668,8 @@ IEnumerable M(IEnumerable nums) select n1; } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; @@ -1803,9 +1680,7 @@ IEnumerable M(IEnumerable nums) return nums.AsQueryable(); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -1826,7 +1701,7 @@ IEnumerable M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; @@ -1838,10 +1713,8 @@ IEnumerable M(IEnumerable nums) select n1; } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; @@ -1852,9 +1725,7 @@ IEnumerable M(IEnumerable nums) return nums.AsQueryable(); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } #endregion @@ -1884,7 +1755,7 @@ List M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -1897,11 +1768,8 @@ from int n2 in nums select n1).ToList(); } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -1912,9 +1780,7 @@ List M(IEnumerable nums) return nums.SelectMany(n1 => nums.Select(n2 => n1)).ToList(); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -1940,7 +1806,7 @@ List M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -1954,11 +1820,8 @@ from int n2 in nums return list; } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -1970,9 +1833,7 @@ List M(IEnumerable nums) return list; } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -1998,7 +1859,7 @@ List M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -2012,11 +1873,8 @@ from int n2 in nums return list; } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -2028,9 +1886,7 @@ List M(IEnumerable nums) return list; } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -2056,7 +1912,7 @@ List M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -2068,11 +1924,8 @@ from int n2 in nums select n1).ToList(); } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -2082,9 +1935,7 @@ List M(IEnumerable nums) return nums.SelectMany(n1 => nums.Select(n2 => n1)).ToList(); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -2110,7 +1961,7 @@ List M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -2124,11 +1975,8 @@ from int n2 in nums return list; } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -2140,9 +1988,7 @@ List M(IEnumerable nums) return list; } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -2168,7 +2014,7 @@ List M(IEnumerable nums, List list) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -2181,11 +2027,8 @@ from int n2 in nums return list; } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -2196,9 +2039,7 @@ List M(IEnumerable nums, List list) return list; } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -2221,7 +2062,7 @@ void M(IEnumerable nums, List[] lists) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -2233,10 +2074,8 @@ from int n2 in nums select n1); } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -2246,9 +2085,7 @@ void M(IEnumerable nums, List[] lists) lists[0].AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1))); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -2272,7 +2109,7 @@ void M(IEnumerable nums, List[] lists) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -2284,10 +2121,8 @@ from int n2 in nums select n1).ToList(); } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -2297,15 +2132,12 @@ void M(IEnumerable nums, List[] lists) lists[0] = nums.SelectMany(n1 => nums.Select(n2 => n1)).ToList(); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] - public async Task ToListHashSetNoConversion() - { - var source = """ + public Task ToListHashSetNoConversion() + => TestMissingAsync(""" using System.Collections.Generic; class C { @@ -2318,9 +2150,7 @@ void M(IEnumerable nums) }|] } } - """; - await TestMissingAsync(source); - } + """); [Fact] public async Task ToListMergeWithReturn() @@ -2345,7 +2175,7 @@ List M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -2357,11 +2187,8 @@ from int n2 in nums select n1).ToList(); } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -2371,9 +2198,7 @@ List M(IEnumerable nums) return nums.SelectMany(n1 => nums.Select(n2 => n1)).ToList(); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -2400,7 +2225,7 @@ List M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -2413,11 +2238,8 @@ from int n2 in nums select n1).ToList(); } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -2428,9 +2250,7 @@ List M(IEnumerable nums) return nums.SelectMany(n1 => nums.Select(n2 => n1)).ToList(); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -2457,7 +2277,7 @@ int M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -2471,10 +2291,8 @@ from int n2 in nums return list.Count; } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -2486,9 +2304,7 @@ int M(IEnumerable nums) return list.Count; } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -2525,7 +2341,7 @@ public static void Main(string[] args) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System; using System.Linq; using C = System.Collections.Generic.List; @@ -2545,10 +2361,8 @@ where x + y / 10 + z / 100 < 6 Console.WriteLine(r1); } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System; using System.Linq; using C = System.Collections.Generic.List; @@ -2572,9 +2386,7 @@ public static void Main(string[] args) Console.WriteLine(r1); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -2607,7 +2419,7 @@ public static void Main(string[] args) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Linq; using System; using C = System.Collections.Generic.List; @@ -2625,10 +2437,8 @@ where Equals(x, y / 10) Console.WriteLine(r1); } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Linq; using System; using C = System.Collections.Generic.List; @@ -2648,9 +2458,7 @@ public static void Main(string[] args) Console.WriteLine(r1); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -2678,7 +2486,7 @@ class C } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; public class Test @@ -2696,10 +2504,8 @@ class C public List A { get; set; } } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; public class Test @@ -2716,9 +2522,7 @@ class C public List A { get; set; } } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -2745,7 +2549,7 @@ class C } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; public class Test @@ -2763,10 +2567,8 @@ class C public List A { get; set; } } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; public class Test @@ -2783,9 +2585,7 @@ class C public List A { get; set; } } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -2807,7 +2607,7 @@ void M() } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; public class Test @@ -2820,10 +2620,8 @@ void M() select x + 1); } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; public class Test @@ -2835,15 +2633,12 @@ void M() A.AddRange((new int[] { 1, 2, 3, 4 }).Select(x => x + 1)); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] - public async Task ToListOverride() - { - var source = """ + public Task ToListOverride() + => TestMissingAsync(""" using System.Collections.Generic; using System.Linq; @@ -2862,9 +2657,7 @@ void M() }|] } } - """; - await TestMissingAsync(source); - } + """); #endregion @@ -2891,7 +2684,7 @@ void M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -2903,11 +2696,8 @@ from int n2 in nums select n1).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -2917,9 +2707,7 @@ void M(IEnumerable nums) int i = 0, cnt = nums.SelectMany(n1 => nums.Select(n2 => n1)).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -2943,7 +2731,7 @@ void M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -2956,11 +2744,8 @@ from int n2 in nums select n1).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -2971,9 +2756,7 @@ void M(IEnumerable nums) cnt += nums.SelectMany(n1 => nums.Select(n2 => n1)).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -2996,7 +2779,7 @@ void M(IEnumerable nums, int c) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3008,10 +2791,8 @@ from int n2 in nums select n1).Count(); } } - """; - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3021,9 +2802,7 @@ void M(IEnumerable nums, int c) c += nums.SelectMany(n1 => nums.Select(n2 => n1)).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -3047,7 +2826,7 @@ void M(IEnumerable nums, int c) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3059,11 +2838,8 @@ from int n2 in nums select n1).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3073,9 +2849,7 @@ void M(IEnumerable nums, int c) c = nums.SelectMany(n1 => nums.Select(n2 => n1)).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -3099,7 +2873,7 @@ void M(IEnumerable nums, int c) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3112,11 +2886,8 @@ from int n2 in nums select n1).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3127,9 +2898,7 @@ void M(IEnumerable nums, int c) c += nums.SelectMany(n1 => nums.Select(n2 => n1)).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -3155,7 +2924,7 @@ int M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3167,11 +2936,8 @@ from int n2 in nums select n1).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3181,9 +2947,7 @@ int M(IEnumerable nums) return nums.SelectMany(n1 => nums.Select(n2 => n1)).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -3209,7 +2973,7 @@ double M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3221,11 +2985,8 @@ from int n2 in nums select n1).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3235,9 +2996,7 @@ double M(IEnumerable nums) return nums.SelectMany(n1 => nums.Select(n2 => n1)).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -3263,7 +3022,7 @@ int M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3276,11 +3035,8 @@ from int n2 in nums select n1).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3291,9 +3047,7 @@ int M(IEnumerable nums) return nums.SelectMany(n1 => nums.Select(n2 => n1)).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -3319,7 +3073,7 @@ int M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3333,11 +3087,8 @@ from int n2 in nums return cnt; } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3349,9 +3100,7 @@ int M(IEnumerable nums) return cnt; } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -3377,7 +3126,7 @@ int M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3391,11 +3140,8 @@ from int n2 in nums return cnt; } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3407,9 +3153,7 @@ int M(IEnumerable nums) return cnt; } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -3435,7 +3179,7 @@ int M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3449,11 +3193,8 @@ from int n2 in nums return cnt; } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3465,9 +3206,7 @@ int M(IEnumerable nums) return cnt; } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -3494,7 +3233,7 @@ int M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3507,11 +3246,8 @@ from int n2 in nums select n1).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3522,9 +3258,7 @@ int M(IEnumerable nums) return nums.SelectMany(n1 => nums.Select(n2 => n1)).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -3551,7 +3285,7 @@ int M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3566,11 +3300,8 @@ from int n2 in nums return cnt; } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3583,9 +3314,7 @@ int M(IEnumerable nums) return cnt; } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -3610,7 +3339,7 @@ int M(IEnumerable nums, int c) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3623,11 +3352,8 @@ from int n2 in nums return c; } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3638,9 +3364,7 @@ int M(IEnumerable nums, int c) return c; } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -3664,7 +3388,7 @@ void M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3677,11 +3401,8 @@ from int n2 in nums select n1).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3692,9 +3413,7 @@ void M(IEnumerable nums) count += nums.SelectMany(n1 => nums.Select(n2 => n1)).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -3719,7 +3438,7 @@ void M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3732,11 +3451,8 @@ from int n2 in nums select n1).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3747,9 +3463,7 @@ void M(IEnumerable nums) count = nums.SelectMany(n1 => nums.Select(n2 => n1)).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -3774,7 +3488,7 @@ void M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3788,11 +3502,8 @@ from int n2 in nums select n1).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -3804,9 +3515,7 @@ void M(IEnumerable nums) count += nums.SelectMany(n1 => nums.Select(n2 => n1)).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -3831,7 +3540,7 @@ void M(IEnumerable nums, A a) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} @@ -3844,11 +3553,8 @@ from int n2 in nums select n1).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} @@ -3859,9 +3565,7 @@ void M(IEnumerable nums, A a) a.B = nums.SelectMany(n1 => nums.Select(n2 => n1)).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -3886,7 +3590,7 @@ void M(IEnumerable nums, A a) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} @@ -3900,11 +3604,8 @@ from int n2 in nums select n1).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} @@ -3916,9 +3617,7 @@ void M(IEnumerable nums, A a) a.B += nums.SelectMany(n1 => nums.Select(n2 => n1)).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -3942,7 +3641,7 @@ void M(IEnumerable nums, A a) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} @@ -3955,11 +3654,8 @@ from int n2 in nums select n1).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} @@ -3970,9 +3666,7 @@ void M(IEnumerable nums, A a) a.B += nums.SelectMany(n1 => nums.Select(n2 => n1)).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -3994,7 +3688,7 @@ void M(IEnumerable nums) } } """; - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; @@ -4006,11 +3700,8 @@ void M(IEnumerable nums) select n1).Count(); } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; @@ -4021,9 +3712,7 @@ void M(IEnumerable nums) int c = nums.AsQueryable().Count(); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } #endregion @@ -4063,8 +3752,7 @@ IEnumerable M(IEnumerable nums) } } """; - - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -4089,11 +3777,8 @@ select x * y/* 29 *//* 31 */// 32 ; } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -4119,9 +3804,7 @@ IEnumerable M(IEnumerable nums) ); } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -4144,8 +3827,7 @@ List M(IEnumerable nums) } } """; - - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -4164,9 +3846,7 @@ List M(IEnumerable nums) ; //32 } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); + """, index: 0); // No linq refactoring offered due to variable declaration in outermost foreach. await TestActionCountAsync(source, count: 1); @@ -4192,8 +3872,7 @@ List M(IEnumerable nums) } } """; - - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -4210,11 +3889,8 @@ List M(IEnumerable nums) ; //26 } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -4232,9 +3908,7 @@ List M(IEnumerable nums) ; //26 } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -4256,8 +3930,7 @@ int M(IEnumerable nums) } } """; - - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -4274,11 +3947,8 @@ int M(IEnumerable nums) ; //24 } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System.Collections.Generic; using System.Linq; class C @@ -4295,9 +3965,7 @@ int M(IEnumerable nums) ; //24 } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } [Fact] @@ -4319,8 +3987,7 @@ void M(IEnumerable nums) } } """; - - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System; using System.Collections.Generic; using System.Linq; @@ -4341,9 +4008,7 @@ void M(IEnumerable nums) } } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); + """, index: 0); // No linq refactoring offered due to variable declaration(s) in outermost foreach. await TestActionCountAsync(source, count: 1); @@ -4370,8 +4035,7 @@ void M(IEnumerable nums) } } """; - - var queryOutput = """ + await TestInRegularAndScriptAsync(source, """ using System; using System.Collections.Generic; using System.Linq; @@ -4394,11 +4058,8 @@ select n1/* 4 *//* 21 */// 22 } } } - """; - - await TestInRegularAndScriptAsync(source, queryOutput, index: 0); - - var linqInvocationOutput = """ + """, index: 0); + await TestInRegularAndScriptAsync(source, """ using System; using System.Collections.Generic; using System.Linq; @@ -4421,9 +4082,7 @@ void M(IEnumerable nums) } } } - """; - - await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); + """, index: 1); } #endregion @@ -4431,9 +4090,8 @@ void M(IEnumerable nums) #region Preprocessor directives [Fact] - public async Task NoConversionPreprocessorDirectives() - { - var source = """ + public Task NoConversionPreprocessorDirectives() + => TestMissingAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -4448,11 +4106,7 @@ IEnumerable M(IEnumerable nums) }|] } } - """; - - // Cannot convert expressions with preprocessor directives - await TestMissingAsync(source); - } + """); #endregion } diff --git a/src/Features/CSharpTest/ConvertLinq/ConvertLinqQueryToForEachTests.cs b/src/Features/CSharpTest/ConvertLinq/ConvertLinqQueryToForEachTests.cs index 9921ba981eb37..af8ab5c6bcd96 100644 --- a/src/Features/CSharpTest/ConvertLinq/ConvertLinqQueryToForEachTests.cs +++ b/src/Features/CSharpTest/ConvertLinq/ConvertLinqQueryToForEachTests.cs @@ -23,9 +23,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor #region Query Expressions [Fact] - public async Task Select() - { - var source = """ + public Task Select() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -37,8 +36,7 @@ public static void Main(string[] args) var r = [|from i in c select i+1|]; } } - """; - var output = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -58,14 +56,11 @@ IEnumerable enumerable() var r = enumerable(); } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task GroupBy01() - { - var source = """ + public Task GroupBy01() + => TestMissingAsync(""" using System.Collections.Generic; using System.Linq; class Query @@ -77,16 +72,11 @@ public static void Main(string[] args) Console.WriteLine(r); } } - """; - - // Group by is not supported - await TestMissingAsync(source); - } + """); [Fact] - public async Task GroupBy02() - { - var source = """ + public Task GroupBy02() + => TestMissingAsync(""" using System.Collections.Generic; using System.Linq; class Query @@ -98,16 +88,11 @@ public static void Main(string[] args) Console.WriteLine(r); } } - """; - - // Group by is not supported - await TestMissingAsync(source); - } + """); [Fact] - public async Task FromJoinSelect01() - { - var source = """ + public Task FromJoinSelect01() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; class Query @@ -121,8 +106,7 @@ join x2 in c2 on x1 equals x2/10 select x1+x2|]; } } - """; - var output = """ + """, """ using System.Collections.Generic; using System.Linq; class Query @@ -148,14 +132,11 @@ IEnumerable enumerable() var r = enumerable(); } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task FromJoinSelect02() - { - var source = """ + public Task FromJoinSelect02() + => TestInRegularAndScriptAsync(""" using System.Linq; class Program @@ -168,8 +149,7 @@ static void Main(string[] args) select x1 + 5|]; } } - """; - var output = """ + """, """ using System.Linq; class Program @@ -198,14 +178,11 @@ System.Collections.Generic.IEnumerable enumerable() var q1 = enumerable(); } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task FromJoinSelect03() - { - var source = """ + public Task FromJoinSelect03() + => TestInRegularAndScriptAsync(""" using System.Linq; class Program @@ -219,8 +196,7 @@ static void Main(string[] args) select x1 + 5|]; } } - """; - var output = """ + """, """ using System.Linq; class Program @@ -256,14 +232,11 @@ System.Collections.Generic.IEnumerable enumerable() var q1 = enumerable(); } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task OrderBy() - { - var source = """ + public Task OrderBy() + => TestMissingAsync(""" using System.Collections.Generic; using System.Linq; class Query @@ -278,15 +251,11 @@ public static void Main(string[] args) Console.WriteLine(r); } } - """; - // order by is not supported by foreach. - await TestMissingAsync(source); - } + """); [Fact] - public async Task Let() - { - var source = """ + public Task Let() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -304,8 +273,7 @@ public static void Main(string[] args) Console.WriteLine(r1); } } - """; - var output = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -326,14 +294,11 @@ public static void Main(string[] args) Console.WriteLine(r1); } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task GroupJoin() - { - var source = """ + public Task GroupJoin() + => TestMissingAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -350,15 +315,11 @@ where x1 < 7 Console.WriteLine(r1); } } - """; - // GroupJoin is not supported - await TestMissingAsync(source); - } + """); [Fact] - public async Task SelectFromType01() - { - var source = """ + public Task SelectFromType01() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; @@ -371,8 +332,7 @@ static void Main() static IEnumerable Select(Func f) { return null; } } - """; - var output = """ + """, """ using System; using System.Collections.Generic; @@ -393,14 +353,11 @@ IEnumerable enumerable() static IEnumerable Select(Func f) { return null; } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task SelectFromType02() - { - var source = """ + public Task SelectFromType02() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; @@ -413,8 +370,7 @@ static void Main() static Func, IEnumerable> Select = null; } - """; - var output = """ + """, """ using System; using System.Collections.Generic; @@ -435,14 +391,11 @@ IEnumerable enumerable() static Func, IEnumerable> Select = null; } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task JoinClause() - { - var source = """ + public Task JoinClause() + => TestInRegularAndScriptAsync(""" using System; using System.Linq; class Program @@ -460,8 +413,7 @@ join b in Enumerable.Range(1, 13) on 4 * a equals b } } } - """; - var output = """ + """, """ using System; using System.Linq; class Program @@ -492,14 +444,11 @@ System.Collections.Generic.IEnumerable enumerable2() } } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task WhereClause() - { - var source = """ + public Task WhereClause() + => TestInRegularAndScriptAsync(""" using System; using System.Linq; class Program @@ -520,9 +469,7 @@ static void Main() System.Console.Write(serializer.Trim()); } } - """; - - var output = """ + """, """ using System; using System.Linq; class Program @@ -551,14 +498,11 @@ System.Collections.Generic.IEnumerable enumerable() System.Console.Write(serializer.Trim()); } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task WhereDefinedInType() - { - var source = """ + public Task WhereDefinedInType() + => TestMissingAsync(""" using System.Collections.Generic; using System.Linq; class Y @@ -581,15 +525,11 @@ where x > 0 Console.Write(query); } } - """; - // should not provide a conversion because of the custom Where. - await TestMissingAsync(source); - } + """); [Fact] - public async Task QueryContinuation() - { - var source = """ + public Task QueryContinuation() + => TestInRegularAndScriptAsync(""" using System; using System.Linq; public class Test @@ -603,8 +543,7 @@ select x into w select w|]; } } - """; - var output = """ + """, """ using System; using System.Linq; public class Test @@ -624,14 +563,11 @@ System.Collections.Generic.IEnumerable enumerable() var q2 = enumerable(); } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task SelectInto() - { - var source = """ + public Task SelectInto() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -645,8 +581,7 @@ select x+1 into w select w+1|]; } } - """; - var output = """ + """, """ using System.Collections.Generic; using System.Linq; public class Test @@ -666,14 +601,11 @@ IEnumerable enumerable() var q2 = enumerable(); } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task ComputeQueryVariableType() - { - var source = """ + public Task ComputeQueryVariableType() + => TestInRegularAndScriptAsync(""" using System.Linq; public class Test { @@ -685,8 +617,7 @@ public static void Main() select 5|]; } } - """; - var output = """ + """, """ using System.Linq; public class Test { @@ -704,14 +635,11 @@ System.Collections.Generic.IEnumerable enumerable() var q2 = enumerable(); } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task JoinIntoClause() - { - var source = """ + public Task JoinIntoClause() + => TestMissingAsync(""" using System; using System.Linq; @@ -724,15 +652,11 @@ join x7 in (new int[] { 0 }) on 5 equals 5 into x8 select x8|]; } } - """; - // GroupJoin is not supported - await TestMissingAsync(source); - } + """); [Fact] - public async Task SemanticErrorInQuery() - { - var source = """ + public Task SemanticErrorInQuery() + => TestMissingAsync(""" using System.Linq; class Program { @@ -744,16 +668,11 @@ static void Main() select num|]; } } - """; - - // Error: Range variable already being declared. - await TestMissingAsync(source); - } + """); [Fact] - public async Task SelectFromVoid() - { - var source = """ + public Task SelectFromVoid() + => TestMissingAsync(""" using System.Linq; class Test { @@ -766,19 +685,15 @@ public static int Main() var e1 = [|from i in V() select i|]; } } - """; - - await TestMissingAsync(source); - } + """); #endregion #region Assignments, Declarations, Returns [Fact] - public async Task AssignExpression() - { - var source = """ + public Task AssignExpression() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -796,9 +711,7 @@ from int n2 in nums void N(IEnumerable q) {} } - """; - - var output = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -825,14 +738,11 @@ IEnumerable enumerable() void N(IEnumerable q) {} } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task MultipleAssignments() - { - var source = """ + public Task MultipleAssignments() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -844,9 +754,7 @@ public static void Main() q1 = q2 = [|from x in nums select x + 1|]; } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; public class Test @@ -866,15 +774,11 @@ IEnumerable enumerable() q1 = q2 = enumerable(); } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task PropertyAssignment() - { - var source = """ + public Task PropertyAssignment() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -891,9 +795,7 @@ class C public IEnumerable A { get; set; } } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; public class Test @@ -918,15 +820,11 @@ class C public IEnumerable A { get; set; } } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task MultipleDeclarationsFirst() - { - var source = """ + public Task MultipleDeclarationsFirst() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -937,9 +835,7 @@ public static void Main() IEnumerable q1 = [|from x in nums select x + 1|], q2 = from x in nums select x + 1; } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; public class Test @@ -958,15 +854,11 @@ IEnumerable enumerable() IEnumerable q1 = enumerable(), q2 = from x in nums select x + 1; } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task MultipleDeclarationsSecond() - { - var source = """ + public Task MultipleDeclarationsSecond() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -977,9 +869,7 @@ public static void Main() IEnumerable q1 = from x in nums select x + 1, q2 = [|from x in nums select x + 1|]; } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; public class Test @@ -998,16 +888,12 @@ IEnumerable enumerable() IEnumerable q1 = from x in nums select x + 1, q2 = enumerable(); } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); // TODO support tuples in the test class, follow CodeGenTupleTests [Fact(Skip = "https://github.com/dotnet/roslyn/issues/25639")] - public async Task TupleDeclaration() - { - var source = """ + public Task TupleDeclaration() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -1018,9 +904,7 @@ public static void Main() var q = ([|from x in nums select x + 1|], from x in nums select x + 1); } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; public class Test @@ -1039,15 +923,11 @@ IEnumerable enumerable() var q = (enumerable(), from x in nums select x + 1); } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task AssignAndReturnIEnumerable() - { - var source = """ + public Task AssignAndReturnIEnumerable() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -1060,9 +940,7 @@ from int n2 in nums return q; } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; class C @@ -1084,15 +962,11 @@ IEnumerable enumerable() return q; } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task BlockBodiedProperty() - { - var source = """ + public Task BlockBodiedProperty() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -1100,9 +974,7 @@ public class Test private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable Query1 { get { return [|from x in _nums select x + 1|]; } } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; public class Test @@ -1110,14 +982,11 @@ public class Test private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable Query1 { get { foreach (var x in _nums) { yield return x + 1; } yield break; } } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task AnonymousType() - { - var source = """ + public Task AnonymousType() + => TestMissingAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -1127,15 +996,11 @@ void M(IEnumerable nums) var q = [|from a in nums from b in nums select new { a, b }|]; } } - """; - // No conversion can be made because it expects to introduce a local function but the return type contains anonymous. - await TestMissingAsync(source); - } + """); [Fact] - public async Task AnonymousTypeInternally() - { - var source = """ + public Task AnonymousTypeInternally() + => TestMissingAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -1145,15 +1010,11 @@ void M(IEnumerable nums) var q = [|from a in nums from b in nums select new { a, b } into c select c.a|]; } } - """; - // No conversion can be made because it expects to introduce a local function but the return type contains anonymous. - await TestMissingAsync(source); - } + """); [Fact] - public async Task DuplicateIdentifiers() - { - var source = """ + public Task DuplicateIdentifiers() + => TestMissingAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -1163,15 +1024,11 @@ void M() var q = [|from x in new[] { 1 } select x + 2 into x where x > 0 select 7 into y let x = "aaa" select x|]; } } - """; - // Duplicate identifiers are not allowed. - await TestMissingAsync(source); - } + """); [Fact] - public async Task ReturnIEnumerable() - { - var source = """ + public Task ReturnIEnumerable() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -1183,9 +1040,7 @@ from int n2 in nums select n1|]; } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; class C @@ -1203,15 +1058,11 @@ IEnumerable M(IEnumerable nums) yield break; } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task ReturnIEnumerablePartialMethod() - { - var source = """ + public Task ReturnIEnumerablePartialMethod() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; partial class C @@ -1227,9 +1078,7 @@ from int n2 in nums select n1|]; } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; partial class C @@ -1251,15 +1100,11 @@ partial IEnumerable M(IEnumerable nums) yield break; } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task ReturnIEnumerableExtendedPartialMethod() - { - var source = """ + public Task ReturnIEnumerableExtendedPartialMethod() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; partial class C @@ -1275,9 +1120,7 @@ from int n2 in nums select n1|]; } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; partial class C @@ -1299,15 +1142,11 @@ public partial IEnumerable M(IEnumerable nums) yield break; } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task ReturnIEnumerableWithOtherReturn() - { - var source = """ + public Task ReturnIEnumerableWithOtherReturn() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -1326,9 +1165,7 @@ from int n2 in nums } } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; class C @@ -1356,15 +1193,11 @@ IEnumerable enumerable() } } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task ReturnObject() - { - var source = """ + public Task ReturnObject() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -1376,9 +1209,7 @@ from int n2 in nums select n1|]; } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; class C @@ -1399,15 +1230,11 @@ IEnumerable enumerable() return enumerable(); } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task ExtraParenthesis() - { - var source = """ + public Task ExtraParenthesis() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -1418,9 +1245,7 @@ IEnumerable M() return ([|from x in nums select x + 1|]); } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; public class Test @@ -1436,15 +1261,12 @@ IEnumerable M() yield break; } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); // TODO support tuples in the test class [Fact(Skip = "https://github.com/dotnet/roslyn/issues/25639")] - public async Task InReturningTuple() - { - var source = """ + public Task InReturningTuple() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -1454,9 +1276,7 @@ public class Test return (([|from a in q select a * a|]), 1); } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; public class Test @@ -1474,15 +1294,12 @@ IEnumerable enumerable() return (enumerable(), 1); } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); // TODO support tuples in the test class [Fact(Skip = "https://github.com/dotnet/roslyn/issues/25639")] - public async Task InInvocationReturningInTuple() - { - var source = """ + public Task InInvocationReturningInTuple() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -1492,9 +1309,7 @@ public class Test return (([|from a in q select a * a|]).Count(), 1); } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; public class Test @@ -1512,15 +1327,11 @@ IEnumerable enumerable() return (enumerable().Count(), 1); } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task RangeVariables() - { - var source = """ + public Task RangeVariables() + => TestInRegularAndScriptAsync(""" using System; using System.Linq; class Query @@ -1538,8 +1349,7 @@ from int z in c3 Console.WriteLine(r1); } } - """; - var output = """ + """, """ using System; using System.Linq; class Query @@ -1567,14 +1377,11 @@ System.Collections.Generic.IEnumerable enumerable() Console.WriteLine(r1); } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task CallingMethodWithIEnumerable() - { - var source = """ + public Task CallingMethodWithIEnumerable() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -1590,9 +1397,7 @@ from int n2 in nums void N(IEnumerable q) {} } - """; - - var output = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -1617,14 +1422,11 @@ IEnumerable enumerable() void N(IEnumerable q) {} } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task ReturnFirstOrDefault() - { - var source = """ + public Task ReturnFirstOrDefault() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -1636,9 +1438,7 @@ from n2 in nums select n1|]).FirstOrDefault(); } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; class C @@ -1659,15 +1459,11 @@ IEnumerable enumerable() return enumerable().FirstOrDefault(); } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task IncompleteQueryWithSyntaxErrors() - { - var source = """ + public Task IncompleteQueryWithSyntaxErrors() + => TestMissingAsync(""" using System.Linq; class Program @@ -1680,15 +1476,11 @@ select x + 1 into z select z.T|] } } - """; - - await TestMissingAsync(source); - } + """); [Fact] - public async Task ErrorNameDoesNotExistsInContext() - { - var source = """ + public Task ErrorNameDoesNotExistsInContext() + => TestMissingAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -1698,15 +1490,11 @@ IEnumerable M() return [|from int n1 in nums select n1|]; } } - """; - - await TestMissingAsync(source); - } + """); [Fact] - public async Task InArrayInitialization() - { - var source = """ + public Task InArrayInitialization() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -1716,9 +1504,7 @@ IEnumerable[] M(IEnumerable q) return new[] { [|from a in q select a * a|] }; } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; public class Test @@ -1736,14 +1522,11 @@ IEnumerable enumerable() return new[] { enumerable() }; } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task InCollectionInitialization() - { - var source = """ + public Task InCollectionInitialization() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -1753,9 +1536,7 @@ List> M(IEnumerable q) return new List> { [|from a in q select a * a|] }; } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; public class Test @@ -1773,14 +1554,11 @@ IEnumerable enumerable() return new List> { enumerable() }; } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task InStructInitialization() - { - var source = """ + public Task InStructInitialization() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -1795,9 +1573,7 @@ X M(IEnumerable q) return new X() { P = [|from a in q select a|] }; } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; public class Test @@ -1820,14 +1596,11 @@ IEnumerable enumerable() return new X() { P = enumerable() }; } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task InClassInitialization() - { - var source = """ + public Task InClassInitialization() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -1842,9 +1615,7 @@ X M(IEnumerable q) return new X() { P = [|from a in q select a|] }; } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; public class Test @@ -1867,14 +1638,11 @@ IEnumerable enumerable() return new X() { P = enumerable() }; } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task InConstructor() - { - var source = """ + public Task InConstructor() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -1884,9 +1652,7 @@ List M(IEnumerable q) return new List([|from a in q select a * a|]); } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; public class Test @@ -1904,14 +1670,11 @@ IEnumerable collection() return new List(collection()); } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task InInlineConstructor() - { - var source = """ + public Task InInlineConstructor() + => TestMissingAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -1919,16 +1682,11 @@ public class Test List M(IEnumerable q) => new List([|from a in q select a * a|]); } - """; - - // No support for expression bodied constructors yet. - await TestMissingAsync(source); - } + """); [Fact] - public async Task IninlineIf() - { - var source = """ + public Task IninlineIf() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -1941,9 +1699,7 @@ List M(IEnumerable q) return null; } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; public class Test @@ -1966,18 +1722,15 @@ IEnumerable collection() return null; } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); #endregion #region In foreach [Fact] - public async Task UsageInForEach() - { - var source = """ + public Task UsageInForEach() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -1994,9 +1747,7 @@ from int n2 in nums } } } - """; - - var output = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -2022,15 +1773,11 @@ IEnumerable enumerable() } } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task UsageInForEachSameVariableName() - { - var source = """ + public Task UsageInForEachSameVariableName() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -2047,9 +1794,7 @@ from int n2 in nums } } } - """; - - var output = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -2075,14 +1820,11 @@ IEnumerable enumerable() } } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task QueryInForEach() - { - var source = """ + public Task QueryInForEach() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -2098,9 +1840,7 @@ from int n2 in nums } } } - """; - - var output = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -2118,15 +1858,11 @@ void M(IEnumerable nums) } } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task QueryInForEachSameVariableNameNoType() - { - var source = """ + public Task QueryInForEachSameVariableNameNoType() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -2142,9 +1878,7 @@ from int n2 in nums } } } - """; - - var output = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -2161,14 +1895,11 @@ void M(IEnumerable nums) } } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task QueryInForEachWithExpressionBody() - { - var source = """ + public Task QueryInForEachWithExpressionBody() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -2181,9 +1912,7 @@ from int n2 in nums select n1|]) Console.WriteLine(b); } } - """; - - var output = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -2201,15 +1930,11 @@ void M(IEnumerable nums) } } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task QueryInForEachWithSameVariableNameAndDifferentType() - { - var source = """ + public Task QueryInForEachWithSameVariableNameAndDifferentType() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -2225,9 +1950,7 @@ void M(IEnumerable nums) } } } - """; - - var output = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -2254,15 +1977,11 @@ IEnumerable @as() } } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task QueryInForEachWithSameVariableNameAndSameType() - { - var source = """ + public Task QueryInForEachWithSameVariableNameAndSameType() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -2278,9 +1997,7 @@ void M(IEnumerable nums) } } } - """; - - var output = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -2299,15 +2016,11 @@ void M(IEnumerable nums) } } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task QueryInForEachVariableUsedInBody() - { - var source = """ + public Task QueryInForEachVariableUsedInBody() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -2324,9 +2037,7 @@ from int n2 in nums } } } - """; - - var output = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -2352,15 +2063,11 @@ IEnumerable bs() } } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task QueryInForEachWithConvertedType() - { - var source = """ + public Task QueryInForEachWithConvertedType() + => TestAsync(""" using System; using System.Collections.Generic; @@ -2389,9 +2096,7 @@ void Test() } } } - """; - - var output = """ + """, """ using System; using System.Collections.Generic; @@ -2428,14 +2133,11 @@ IEnumerable xes() } } } - """; - await TestAsync(source, output, parseOptions: null); - } + """, parseOptions: null); [Fact] - public async Task QueryInForEachWithSelectIdentifierButNotVariable() - { - var source = """ + public Task QueryInForEachWithSelectIdentifierButNotVariable() + => TestAsync(""" using System; using System.Collections.Generic; @@ -2464,9 +2166,7 @@ void Test() } } } - """; - - var output = """ + """, """ using System; using System.Collections.Generic; @@ -2496,15 +2196,11 @@ void Test() } } } - """; - - await TestAsync(source, output, parseOptions: null); - } + """, parseOptions: null); [Fact] - public async Task IQueryable() - { - var source = """ + public Task IQueryable() + => TestMissingAsync(""" using System.Collections.Generic; using System.Linq; @@ -2515,15 +2211,11 @@ IQueryable M(IEnumerable nums) return [|from int n1 in nums.AsQueryable() select n1|]; } } - """; - - await TestMissingAsync(source); - } + """); [Fact] - public async Task IQueryableConvertedToIEnumerableInReturn() - { - var source = """ + public Task IQueryableConvertedToIEnumerableInReturn() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; @@ -2534,8 +2226,7 @@ IEnumerable M(IEnumerable nums) return [|from int n1 in nums.AsQueryable() select n1|]; } } - """; - var output = """ + """, """ using System.Collections.Generic; using System.Linq; @@ -2551,15 +2242,11 @@ IEnumerable M(IEnumerable nums) yield break; } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task IQueryableConvertedToIEnumerableInAssignment() - { - var source = """ + public Task IQueryableConvertedToIEnumerableInAssignment() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; @@ -2570,9 +2257,7 @@ void M(IEnumerable nums) IEnumerable q = [|from int n1 in nums.AsQueryable() select n1|]; } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; @@ -2591,15 +2276,11 @@ IEnumerable queryable() IEnumerable q = queryable(); } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task IQueryableInInvocation() - { - var source = """ + public Task IQueryableInInvocation() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; @@ -2610,9 +2291,7 @@ void M(IEnumerable nums) int c = ([|from int n1 in nums.AsQueryable() select n1|]).Count(); } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; @@ -2627,19 +2306,15 @@ void M(IEnumerable nums) } } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); #endregion #region In ToList [Fact] - public async Task PropertyAssignmentInInvocation() - { - var source = """ + public Task PropertyAssignmentInInvocation() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -2656,9 +2331,7 @@ class C public List A { get; set; } } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; public class Test @@ -2681,15 +2354,11 @@ class C public List A { get; set; } } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task NullablePropertyAssignmentInInvocation() - { - var source = """ + public Task NullablePropertyAssignmentInInvocation() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -2706,9 +2375,7 @@ class C public List A { get; set; } } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; public class Test @@ -2731,15 +2398,11 @@ class C public List A { get; set; } } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task AssignList() - { - var source = """ + public Task AssignList() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -2752,9 +2415,7 @@ from int n2 in nums return list; } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; class C @@ -2773,15 +2434,11 @@ List M(IEnumerable nums) return list; } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task AssignToListToParameter() - { - var source = """ + public Task AssignToListToParameter() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -2794,9 +2451,7 @@ from int n2 in nums return list; } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; class C @@ -2815,15 +2470,11 @@ List M(IEnumerable nums, List list) return list; } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task AssignToListToArrayElement() - { - var source = """ + public Task AssignToListToArrayElement() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -2835,9 +2486,7 @@ from int n2 in nums select n1|]).ToList(); } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; class C @@ -2856,15 +2505,11 @@ List M(IEnumerable nums, List[] lists) lists[0] = list; } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task AssignListWithTypeArgument() - { - var source = """ + public Task AssignListWithTypeArgument() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -2877,9 +2522,7 @@ from int n2 in nums return list; } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; class C @@ -2898,15 +2541,11 @@ List M(IEnumerable nums) return list; } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task AssignListToObject() - { - var source = """ + public Task AssignListToObject() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -2919,9 +2558,7 @@ from int n2 in nums return list; } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; class C @@ -2941,15 +2578,11 @@ object M(IEnumerable nums) return list; } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task AssignListWithNullableToList() - { - var source = """ + public Task AssignListWithNullableToList() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -2962,9 +2595,7 @@ from int n2 in nums return list; } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; class C @@ -2986,15 +2617,11 @@ IEnumerable enumerable() return list; } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task ReturnList() - { - var source = """ + public Task ReturnList() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -3006,9 +2633,7 @@ from int n2 in nums select n1|]).ToList(); } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; class C @@ -3027,15 +2652,11 @@ List M(IEnumerable nums) return list; } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task ReturnListNameGeneration() - { - var source = """ + public Task ReturnListNameGeneration() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -3048,9 +2669,7 @@ from int n2 in nums select n1|]).ToList(); } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; class C @@ -3070,15 +2689,11 @@ List M(IEnumerable nums) return list1; } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task ToListTypeReplacement01() - { - var source = """ + public Task ToListTypeReplacement01() + => TestInRegularAndScriptAsync(""" using System; using System.Linq; using C = System.Collections.Generic.List; @@ -3098,8 +2713,7 @@ from int z in c3 Console.WriteLine(r1); } } - """; - var output = """ + """, """ using System; using System.Linq; using C = System.Collections.Generic.List; @@ -3129,14 +2743,11 @@ public static void Main(string[] args) Console.WriteLine(r1); } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task ToListTypeReplacement02() - { - var source = """ + public Task ToListTypeReplacement02() + => TestInRegularAndScriptAsync(""" using System.Linq; using System; using C = System.Collections.Generic.List; @@ -3154,8 +2765,7 @@ join y in c2 on x equals y / 10 Console.WriteLine(r1); } } - """; - var output = """ + """, """ using System.Linq; using System; using C = System.Collections.Generic.List; @@ -3181,14 +2791,11 @@ public static void Main(string[] args) Console.WriteLine(r1); } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task ToListOverloadAssignTo() - { - var source = """ + public Task ToListOverloadAssignTo() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; @@ -3206,9 +2813,7 @@ void M() } } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; @@ -3234,14 +2839,11 @@ IEnumerable enumerable() } } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task ToListRefOverload() - { - var source = """ + public Task ToListRefOverload() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; @@ -3259,9 +2861,7 @@ void M() } } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; @@ -3287,18 +2887,15 @@ IEnumerable enumerable() } } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); #endregion #region In Count [Fact] - public async Task CountInMultipleDeclaration() - { - var source = """ + public Task CountInMultipleDeclaration() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -3311,9 +2908,7 @@ from int n2 in nums return cnt; } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; class C @@ -3335,15 +2930,11 @@ IEnumerable enumerable() return cnt; } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task CountInNonLocalDeclaration() - { - var source = """ + public Task CountInNonLocalDeclaration() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -3359,9 +2950,7 @@ from int n2 in nums } } } - """; - - var output = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -3383,15 +2972,11 @@ void M(IEnumerable nums) } } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task CountInDeclaration() - { - var source = """ + public Task CountInDeclaration() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -3404,9 +2989,7 @@ from int n2 in nums return cnt; } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; class C @@ -3425,15 +3008,11 @@ int M(IEnumerable nums) return cnt; } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task ReturnCount() - { - var source = """ + public Task ReturnCount() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -3445,9 +3024,7 @@ from int n2 in nums select n1|]).Count(); } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; class C @@ -3466,15 +3043,11 @@ int M(IEnumerable nums) return count; } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task ReturnCountExtraParethesis() - { - var source = """ + public Task ReturnCountExtraParethesis() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -3486,9 +3059,7 @@ from int n2 in nums select n1|]).Count()); } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; class C @@ -3507,15 +3078,11 @@ int M(IEnumerable nums) return count; } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task CountAsArgument() - { - var source = """ + public Task CountAsArgument() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -3528,9 +3095,7 @@ from int n2 in nums select n1|]).Count()); } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; class C @@ -3552,15 +3117,11 @@ IEnumerable enumerable() N(enumerable().Count()); } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task CountAsArgumentExpressionBody() - { - var source = """ + public Task CountAsArgumentExpressionBody() + => TestMissingAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -3571,15 +3132,11 @@ void M(IEnumerable nums) from int n2 in nums select n1|]).Count()); } - """; - - await TestMissingAsync(source); - } + """); [Fact] - public async Task ReturnCountNameGeneration() - { - var source = """ + public Task ReturnCountNameGeneration() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -3592,9 +3149,7 @@ from int n2 in nums select n1|]).Count(); } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; class C @@ -3614,15 +3169,11 @@ int M(IEnumerable nums) return count1; } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task CountNameUsedAfter() - { - var source = """ + public Task CountNameUsedAfter() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -3640,9 +3191,7 @@ from int n2 in nums return count; } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; class C @@ -3667,15 +3216,11 @@ int M(IEnumerable nums) return count; } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task ReturnCountNameUsedBefore() - { - var source = """ + public Task ReturnCountNameUsedBefore() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -3692,9 +3237,7 @@ from int n2 in nums select n1|]).Count(); } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; class C @@ -3718,15 +3261,11 @@ int M(IEnumerable nums) return count1; } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task CountOverload() - { - var source = """ + public Task CountOverload() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -3739,9 +3278,7 @@ from int n2 in nums return cnt; } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; class C @@ -3763,14 +3300,11 @@ IEnumerable enumerable() return cnt; } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task CountOverloadAssignTo() - { - var source = """ + public Task CountOverloadAssignTo() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; @@ -3788,9 +3322,7 @@ void M() } } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; @@ -3816,14 +3348,11 @@ IEnumerable enumerable() } } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task CountRefOverload() - { - var source = """ + public Task CountRefOverload() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; using System.Linq; @@ -3841,9 +3370,7 @@ void M() } } } - """; - - var output = """ + """, """ using System.Collections.Generic; using System.Linq; @@ -3869,18 +3396,15 @@ IEnumerable enumerable() } } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); #endregion #region Expression Bodied [Fact] - public async Task ExpressionBodiedProperty() - { - var source = """ + public Task ExpressionBodiedProperty() + => TestMissingAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -3888,15 +3412,11 @@ public class Test private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable Query => [|from x in _nums select x + 1|]; } - """; - // Cannot convert in expression bodied property - await TestMissingAsync(source); - } + """); [Fact] - public async Task ExpressionBodiedField() - { - var source = """ + public Task ExpressionBodiedField() + => TestMissingAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -3904,14 +3424,11 @@ public class Test private static readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public List Query = ([|from x in _nums select x + 1|]).ToList(); } - """; - await TestMissingAsync(source); - } + """); [Fact] - public async Task Field() - { - var source = """ + public Task Field() + => TestMissingAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -3919,14 +3436,11 @@ public class Test private static readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable Query = [|from x in _nums select x + 1|]; } - """; - await TestMissingAsync(source); - } + """); [Fact] - public async Task ExpressionBodiedMethod() - { - var source = """ + public Task ExpressionBodiedMethod() + => TestMissingAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -3934,15 +3448,11 @@ public class Test private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable Query() => [|from x in _nums select x + 1|]; } - """; - // Cannot convert in expression bodied method - await TestMissingAsync(source); - } + """); [Fact] - public async Task ExpressionBodiedMethodUnderInvocation() - { - var source = """ + public Task ExpressionBodiedMethodUnderInvocation() + => TestMissingAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -3950,15 +3460,11 @@ public class Test private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public List Query() => ([|from x in _nums select x + 1|]).ToList(); } - """; - // Cannot convert in expression bodied method - await TestMissingAsync(source); - } + """); [Fact] - public async Task ExpressionBodiedenumerable() - { - var source = """ + public Task ExpressionBodiedenumerable() + => TestMissingAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -3969,15 +3475,11 @@ public void M() IEnumerable Query() => [|from x in _nums select x + 1|]; } } - """; - // Cannot convert in expression bodied property - await TestMissingAsync(source); - } + """); [Fact] - public async Task ExpressionBodiedAccessor() - { - var source = """ + public Task ExpressionBodiedAccessor() + => TestMissingAsync(""" using System.Collections.Generic; using System.Linq; public class Test @@ -3985,15 +3487,11 @@ public class Test private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable Query { get => [|from x in _nums select x + 1|]; } } - """; - // Cannot convert in expression bodied property - await TestMissingAsync(source); - } + """); [Fact] - public async Task InInlineLambda() - { - var source = """ + public Task InInlineLambda() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -4004,8 +3502,7 @@ void M(IEnumerable nums) Func> lambda = () => [|from x in new int[] { 1 } select x|]; } } - """; - var output = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -4024,15 +3521,11 @@ IEnumerable enumerable() Func> lambda = () => enumerable(); } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task InParameterLambda() - { - var source = """ + public Task InParameterLambda() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -4047,8 +3540,7 @@ void M(IEnumerable nums) { } } - """; - var output = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -4071,15 +3563,11 @@ void M(IEnumerable nums) { } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task InParenthesizedLambdaWithBody() - { - var source = """ + public Task InParenthesizedLambdaWithBody() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -4090,9 +3578,7 @@ void M(IEnumerable nums) Func> lambda = () => { return [|from x in new int[] { 1 } select x|]; }; } } - """; - - var output = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -4112,15 +3598,11 @@ IEnumerable enumerable() return enumerable(); }; } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task InSimplifiedLambdaWithBody() - { - var source = """ + public Task InSimplifiedLambdaWithBody() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -4131,9 +3613,7 @@ void M(IEnumerable nums) Func> lambda = n => { return [|from x in new int[] { 1 } select x|]; }; } } - """; - - var output = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -4153,15 +3633,11 @@ IEnumerable enumerable() return enumerable(); }; } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task InAnonymousMethod() - { - var source = """ + public Task InAnonymousMethod() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -4172,9 +3648,7 @@ void M(IEnumerable nums) Func> a = delegate () { return [|from x in new int[] { 1 } select x|]; }; } } - """; - - var output = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -4194,15 +3668,11 @@ IEnumerable enumerable() return enumerable(); }; } } - """; - - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task InWhen() - { - var source = """ + public Task InWhen() + => TestMissingAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -4218,19 +3688,15 @@ void M(IEnumerable nums) } } } - """; - // In when is not supported - await TestMissingAsync(source); - } + """); #endregion #region Comments and Preprocessor directives [Fact] - public async Task InlineComments() - { - var source = """ + public Task InlineComments() + => TestMissingAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -4242,15 +3708,11 @@ from int n2 in nums select n1|]; } } - """; - // Cannot convert expressions with comments - await TestMissingAsync(source); - } + """); [Fact] - public async Task Comments() - { - var source = """ + public Task Comments() + => TestMissingAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -4262,16 +3724,11 @@ from int n2 in nums select n1|]; } } - """; - // Cannot convert expressions with comments - await TestMissingAsync(source); - } + """); [Fact] - public async Task PreprocessorDirectives() - { - - var source = """ + public Task PreprocessorDirectives() + => TestMissingAsync(""" using System.Collections.Generic; using System.Linq; class C @@ -4285,20 +3742,15 @@ from int n2 in nums select n1|]; } } - """; - - // Cannot convert expressions with preprocessor directives - await TestMissingAsync(source); - } + """); #endregion #region Name Generation [Fact] - public async Task EnumerableFunctionDoesNotUseLocalFunctionName() - { - var source = """ + public Task EnumerableFunctionDoesNotUseLocalFunctionName() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -4312,8 +3764,7 @@ public static void Main(string[] args) void enumerable() { } } } - """; - var output = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -4335,14 +3786,11 @@ IEnumerable enumerable1() void enumerable() { } } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task EnumerableFunctionCanUseLocalFunctionParameterName() - { - var source = """ + public Task EnumerableFunctionCanUseLocalFunctionParameterName() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -4356,8 +3804,7 @@ public static void Main(string[] args) void M(IEnumerable enumerable) { } } } - """; - var output = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -4379,14 +3826,11 @@ IEnumerable enumerable() void M(IEnumerable enumerable) { } } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact] - public async Task EnumerableFunctionDoesNotUseLambdaParameterNameWithCSharpLessThan8() - { - var source = """ + public Task EnumerableFunctionDoesNotUseLambdaParameterNameWithCSharpLessThan8() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -4400,8 +3844,7 @@ public static void Main(string[] args) Action myLambda = enumerable => { }; } } - """; - var output = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -4423,14 +3866,11 @@ IEnumerable enumerable1() Action myLambda = enumerable => { }; } } - """; - await TestInRegularAndScriptAsync(source, output, parseOptions: new CSharpParseOptions(CodeAnalysis.CSharp.LanguageVersion.CSharp7_3)); - } + """, parseOptions: new CSharpParseOptions(CodeAnalysis.CSharp.LanguageVersion.CSharp7_3)); [Fact] - public async Task EnumerableFunctionCanUseLambdaParameterNameInCSharp8() - { - var source = """ + public Task EnumerableFunctionCanUseLambdaParameterNameInCSharp8() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -4444,8 +3884,7 @@ public static void Main(string[] args) Action myLambda = enumerable => { }; } } - """; - var output = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -4467,17 +3906,14 @@ IEnumerable enumerable() Action myLambda = enumerable => { }; } } - """; - await TestInRegularAndScriptAsync(source, output, parseOptions: new CSharpParseOptions(CodeAnalysis.CSharp.LanguageVersion.CSharp8)); - } + """, parseOptions: new CSharpParseOptions(CodeAnalysis.CSharp.LanguageVersion.CSharp8)); #endregion #region CaretSelection [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task DeclarationSelection() - { - var source = """ + public Task DeclarationSelection() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -4489,8 +3925,7 @@ public static void Main(string[] args) var r = [|from i in c select i+1;|] } } - """; - var output = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -4510,14 +3945,11 @@ IEnumerable enumerable() var r = enumerable(); } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task LocalAssignmentSelection() - { - var source = """ + public Task LocalAssignmentSelection() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -4530,8 +3962,7 @@ public static void Main(string[] args) [|r = from i in c select i+1;|] } } - """; - var output = """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -4552,9 +3983,7 @@ IEnumerable enumerable() r = enumerable(); } } - """; - await TestInRegularAndScriptAsync(source, output); - } + """); #endregion } diff --git a/src/Features/CSharpTest/ConvertLocalFunctionToMethod/ConvertLocalFunctionToMethodTests.cs b/src/Features/CSharpTest/ConvertLocalFunctionToMethod/ConvertLocalFunctionToMethodTests.cs index a9d24023ad830..2dc3cdbc418d9 100644 --- a/src/Features/CSharpTest/ConvertLocalFunctionToMethod/ConvertLocalFunctionToMethodTests.cs +++ b/src/Features/CSharpTest/ConvertLocalFunctionToMethod/ConvertLocalFunctionToMethodTests.cs @@ -20,9 +20,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor => new CSharpConvertLocalFunctionToMethodCodeRefactoringProvider(); [Fact] - public async Task TestCaptures1() - { - await TestInRegularAndScriptAsync( + public Task TestCaptures1() + => TestInRegularAndScriptAsync( """ class C { @@ -82,12 +81,10 @@ private void LocalFunction1(T1 param1, ref T2 param2, int local1, ref in } } """); - } [Fact] - public async Task TestCaptures2() - { - await TestInRegularAndScriptAsync( + public Task TestCaptures2() + => TestInRegularAndScriptAsync( """ class C { @@ -119,12 +116,10 @@ struct S public int Value; } """); - } [Fact] - public async Task TestCaptures3() - { - await TestInRegularAndScriptAsync( + public Task TestCaptures3() + => TestInRegularAndScriptAsync( """ class C { @@ -152,12 +147,10 @@ private static void LocalFunction(int value) } } """); - } [Fact] - public async Task TestCaptures4() - { - await TestInRegularAndScriptAsync( + public Task TestCaptures4() + => TestInRegularAndScriptAsync( """ class C { @@ -181,12 +174,10 @@ public static void M(int i, int j) private static int LocalFunction1(int i) => i; } """); - } [Fact] - public async Task TestCaptures5() - { - await TestInRegularAndScriptAsync( + public Task TestCaptures5() + => TestInRegularAndScriptAsync( """ class C { @@ -216,12 +207,10 @@ private static void LocalFunction() } } """); - } [Fact] - public async Task TestTypeParameters1() - { - await TestInRegularAndScriptAsync( + public Task TestTypeParameters1() + => TestInRegularAndScriptAsync( """ class C { @@ -274,12 +263,10 @@ private static void LocalFunction1(T5 a, T6 b) } } """); - } [Fact] - public async Task TestTypeParameters2() - { - await TestInRegularAndScriptAsync( + public Task TestTypeParameters2() + => TestInRegularAndScriptAsync( """ class C { @@ -301,12 +288,10 @@ void M(int i) private static int LocalFunction(T1 a, T2 b, int i) => i; } """); - } [Fact] - public async Task TestNameConflict() - { - await TestInRegularAndScriptAsync( + public Task TestNameConflict() + => TestInRegularAndScriptAsync( """ class C { @@ -334,12 +319,10 @@ void M() private void LocalFunction1() => M(); } """); - } [Fact] - public async Task TestNamedArguments1() - { - await TestAsync( + public Task TestNamedArguments1() + => TestAsync( """ class C { @@ -373,12 +356,10 @@ private static int LocalFunction1(int i, int var) } } """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_2)); - } [Fact] - public async Task TestNamedArguments2() - { - await TestAsync( + public Task TestNamedArguments2() + => TestAsync( """ class C { @@ -412,12 +393,10 @@ private static int LocalFunction1(int i, int var) } } """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7)); - } [Fact] - public async Task TestDelegate1() - { - await TestInRegularAndScriptAsync( + public Task TestDelegate1() + => TestInRegularAndScriptAsync( """ class C { @@ -443,12 +422,10 @@ void M(int i) private static int LocalFunction1(int i) => i; } """); - } [Fact] - public async Task TestDelegate2() - { - await TestInRegularAndScriptAsync( + public Task TestDelegate2() + => TestInRegularAndScriptAsync( """ class C { @@ -474,12 +451,10 @@ void M(int i, int j) private static int LocalFunction1(int a, ref string b, ref int i, int j) => i = j; } """); - } [Fact] - public async Task TestAsyncFunction1() - { - await TestInRegularAndScriptAsync( + public Task TestAsyncFunction1() + => TestInRegularAndScriptAsync( """ using System; using System.Threading; @@ -515,12 +490,10 @@ private static async Task LocalFunction(CancellationToken c, Task task) } } """); - } [Fact] - public async Task TestAsyncFunction2() - { - await TestInRegularAndScriptAsync( + public Task TestAsyncFunction2() + => TestInRegularAndScriptAsync( """ using System; using System.Threading; @@ -556,7 +529,6 @@ private static async void LocalFunction(CancellationToken c, Task task) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] public async Task TestCaretPositon() @@ -577,16 +549,18 @@ public async Task TestCaretPositon() async Task TestAsync(string signature) { await TestInRegularAndScriptAsync( -$@"class C -{{ - void M() - {{ - {signature} - {{ - return null; - }} - }} -}}", + $$""" + class C + { + void M() + { + {{signature}} + { + return null; + } + } + } + """, """ class C { @@ -605,23 +579,24 @@ private static C LocalFunction(C c) async Task TestMissingAsync(string signature) { await this.TestMissingAsync( -$@"class C -{{ - void M() - {{ - {signature} - {{ - return null; - }} - }} -}}"); + $$""" + class C + { + void M() + { + {{signature}} + { + return null; + } + } + } + """); } } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestMethodBlockSelection1() - { - await TestInRegularAndScriptAsync( + public Task TestMethodBlockSelection1() + => TestInRegularAndScriptAsync( """ class C { @@ -647,13 +622,10 @@ private static C LocalFunction(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestMethodBlockSelection2() - { - - await TestMissingAsync( + public Task TestMethodBlockSelection2() + => TestMissingAsync( """ class C { @@ -666,12 +638,10 @@ C LocalFunction(C c)[| } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestMethodBlockSelection3() - { - await TestInRegularAndScriptAsync( + public Task TestMethodBlockSelection3() + => TestInRegularAndScriptAsync( """ class C @@ -701,13 +671,10 @@ private static C LocalFunction(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestMethodBlockSelection4() - { - - await this.TestMissingAsync( + public Task TestMethodBlockSelection4() + => this.TestMissingAsync( """ class C { @@ -723,13 +690,10 @@ C LocalFunction(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestMethodBlockSelection5() - { - - await this.TestMissingAsync( + public Task TestMethodBlockSelection5() + => this.TestMissingAsync( """ class C { @@ -746,13 +710,10 @@ C LocalFunction(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestMethodBlockSelection6() - { - - await this.TestMissingAsync( + public Task TestMethodBlockSelection6() + => this.TestMissingAsync( """ class C { @@ -770,12 +731,10 @@ C LocalFunction(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestMethodBlockSelection7() - { - await TestMissingAsync( + public Task TestMethodBlockSelection7() + => TestMissingAsync( """ class C { @@ -788,12 +747,10 @@ C LocalFunction(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestMethodBlockSelection8() - { - await TestInRegularAndScriptAsync( + public Task TestMethodBlockSelection8() + => TestInRegularAndScriptAsync( """ class C { @@ -819,12 +776,10 @@ private static C LocalFunction(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestMethodBlockSelection9() - { - await TestInRegularAndScriptAsync( + public Task TestMethodBlockSelection9() + => TestInRegularAndScriptAsync( """ class C { @@ -850,12 +805,10 @@ private static C LocalFunction(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestMethodBlockSelection10() - { - await TestInRegularAndScriptAsync( + public Task TestMethodBlockSelection10() + => TestInRegularAndScriptAsync( """ class C { @@ -881,12 +834,10 @@ private static C LocalFunction(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestMethodBlockSelection11() - { - await TestMissingAsync( + public Task TestMethodBlockSelection11() + => TestMissingAsync( """ class C { @@ -900,12 +851,10 @@ C LocalFunction(C c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32976")] - public async Task TestUnsafeLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafeLocalFunction() + => TestInRegularAndScriptAsync( """ class C { @@ -935,12 +884,10 @@ public unsafe void UnsafeFunction() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32976")] - public async Task TestUnsafeLocalFunctionInUnsafeMethod() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafeLocalFunctionInUnsafeMethod() + => TestInRegularAndScriptAsync( """ class C { @@ -970,12 +917,10 @@ public unsafe void UnsafeFunction() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32976")] - public async Task TestLocalFunctionInUnsafeMethod() - { - await TestInRegularAndScriptAsync( + public Task TestLocalFunctionInUnsafeMethod() + => TestInRegularAndScriptAsync( """ class C { @@ -1005,12 +950,10 @@ private static byte GetPtr(byte bytePt) } } """); - } [Fact] - public async Task TestTopLevelStatements() - { - await TestMissingAsync(""" + public Task TestTopLevelStatements() + => TestMissingAsync(""" Console.WriteLine("Hello"); { public static int [|Add|](int x, int y) @@ -1019,12 +962,10 @@ await TestMissingAsync(""" } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32975")] - public async Task TestRefReturn() - { - await TestInRegularAndScript1Async(""" + public Task TestRefReturn() + => TestInRegularAndScript1Async(""" class ClassA { class RefClass { } @@ -1054,12 +995,10 @@ private ref RefClass GetRef() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32975")] - public async Task TestAttributes() - { - await TestInRegularAndScript1Async(""" + public Task TestAttributes() + => TestInRegularAndScript1Async(""" class ClassA { class RefClass { } @@ -1091,12 +1030,10 @@ private ref RefClass GetRef() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72024")] - public async Task TestLocalFunctionInField() - { - await TestMissingInRegularAndScriptAsync( + public Task TestLocalFunctionInField() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1114,12 +1051,10 @@ struct S public int Value; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64904")] - public async Task TestNameofReferenceInParameterInitializer() - { - await TestInRegularAndScript1Async( + public Task TestNameofReferenceInParameterInitializer() + => TestInRegularAndScript1Async( """ using System; @@ -1161,5 +1096,4 @@ private static void M2([A(nameof(b), P = nameof(b))] string b) } """); - } } diff --git a/src/Features/CSharpTest/ConvertNamespace/ConvertNamespaceRefactoringFixAllTests.cs b/src/Features/CSharpTest/ConvertNamespace/ConvertNamespaceRefactoringFixAllTests.cs index 993de6424c10f..d42a2711169c3 100644 --- a/src/Features/CSharpTest/ConvertNamespace/ConvertNamespaceRefactoringFixAllTests.cs +++ b/src/Features/CSharpTest/ConvertNamespace/ConvertNamespaceRefactoringFixAllTests.cs @@ -26,286 +26,275 @@ private OptionsCollection PreferFileScopedNamespace => this.Option(CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped, NotificationOption2.Warning); [Fact] - public async Task TestConvertToFileScope_FixAllInProject() - { - await TestInRegularAndScript1Async(@" - - - -namespace {|FixAllInProject:|}N1 -{ -} - - -namespace N2 -{ - class C { } -} - - -namespace N3.N4 -{ - class C2 { } -} - - -namespace N5; - - - - -namespace N6 -{ -} - - - -", @" - - - -namespace N1; - - -namespace N2; + public Task TestConvertToFileScope_FixAllInProject() + => TestInRegularAndScript1Async(""" + + + + namespace {|FixAllInProject:|}N1 + { + } + + + namespace N2 + { + class C { } + } + + + namespace N3.N4 + { + class C2 { } + } + + + namespace N5; + + + + + namespace N6 + { + } + + + + """, """ + + + + namespace N1; + + + namespace N2; -class C { } - - -namespace N3.N4; + class C { } + + + namespace N3.N4; -class C2 { } - - -namespace N5; - - - - -namespace N6 -{ -} - - - -", new TestParameters(options: PreferBlockScopedNamespace)); - } + class C2 { } + + + namespace N5; + + + + + namespace N6 + { + } + + + + """, new TestParameters(options: PreferBlockScopedNamespace)); [Fact] - public async Task TestConvertToFileScope_FixAllInSolution() - { - await TestInRegularAndScript1Async(@" - - - -namespace {|FixAllInSolution:|}N1 -{ -} - - -namespace N2 -{ - class C { } -} - - -namespace N3.N4 -{ - class C2 { } -} - - -namespace N5; - - - - -namespace N6 -{ -} - - - -", @" - - - -namespace N1; - - -namespace N2; + public Task TestConvertToFileScope_FixAllInSolution() + => TestInRegularAndScript1Async(""" + + + + namespace {|FixAllInSolution:|}N1 + { + } + + + namespace N2 + { + class C { } + } + + + namespace N3.N4 + { + class C2 { } + } + + + namespace N5; + + + + + namespace N6 + { + } + + + + """, """ + + + + namespace N1; + + + namespace N2; -class C { } - - -namespace N3.N4; + class C { } + + + namespace N3.N4; -class C2 { } - - -namespace N5; - - - - -namespace N6; - - - -", new TestParameters(options: PreferBlockScopedNamespace)); - } + class C2 { } + + + namespace N5; + + + + + namespace N6; + + + + """, new TestParameters(options: PreferBlockScopedNamespace)); [Theory] [InlineData("FixAllInDocument")] [InlineData("FixAllInContainingType")] [InlineData("FixAllInContainingMember")] - public async Task TestConvertToFileScope_UnsupportedFixAllScopes(string fixAllScope) - { - await TestMissingInRegularAndScriptAsync($@" -namespace {{|{fixAllScope}:|}}N1 -{{ -}}", new TestParameters(options: PreferBlockScopedNamespace)); - } + public Task TestConvertToFileScope_UnsupportedFixAllScopes(string fixAllScope) + => TestMissingInRegularAndScriptAsync($$""" + namespace {|{{fixAllScope}}:|}N1 + { + } + """, new TestParameters(options: PreferBlockScopedNamespace)); [Fact] - public async Task TestConvertToBlockScope_FixAllInProject() - { - await TestInRegularAndScript1Async(@" - - - -namespace {|FixAllInProject:|}N1; - - -namespace N2; + public Task TestConvertToBlockScope_FixAllInProject() + => TestInRegularAndScript1Async(""" + + + + namespace {|FixAllInProject:|}N1; + + + namespace N2; -class C { } - - -namespace N3.N4; + class C { } + + + namespace N3.N4; -class C2 { } - - -namespace N5 -{ -} - - - - -namespace N6; - - - -", @" - - - -namespace N1 -{ -} - -namespace N2 -{ - class C { } + class C2 { } + + + namespace N5 + { + } + + + + + namespace N6; + + + + """, """ + + + + namespace N1 + { + } + + namespace N2 + { + class C { } -} - -namespace N3.N4 -{ - class C2 { } + } + + namespace N3.N4 + { + class C2 { } -} - -namespace N5 -{ -} - - - - -namespace N6; - - - -", new TestParameters(options: PreferFileScopedNamespace)); - } + } + + namespace N5 + { + } + + + + + namespace N6; + + + + """, new TestParameters(options: PreferFileScopedNamespace)); [Fact] - public async Task TestConvertToBlockScope_FixAllInSolution() - { - await TestInRegularAndScript1Async(@" - - - -namespace {|FixAllInSolution:|}N1; - - -namespace N2; + public Task TestConvertToBlockScope_FixAllInSolution() + => TestInRegularAndScript1Async(""" + + + + namespace {|FixAllInSolution:|}N1; + + + namespace N2; -class C { } - - -namespace N3.N4; + class C { } + + + namespace N3.N4; -class C2 { } - - -namespace N5 -{ -} - - - - -namespace N6; - - - -", @" - - - -namespace N1 -{ -} - -namespace N2 -{ - class C { } + class C2 { } + + + namespace N5 + { + } + + + + + namespace N6; + + + + """, """ + + + + namespace N1 + { + } + + namespace N2 + { + class C { } -} - -namespace N3.N4 -{ - class C2 { } + } + + namespace N3.N4 + { + class C2 { } -} - -namespace N5 -{ -} - - - - -namespace N6 -{ -} - - -", new TestParameters(options: PreferFileScopedNamespace)); - } + } + + namespace N5 + { + } + + + + + namespace N6 + { + } + + + """, new TestParameters(options: PreferFileScopedNamespace)); [Theory] [InlineData("FixAllInDocument")] [InlineData("FixAllInContainingType")] [InlineData("FixAllInContainingMember")] - public async Task TestConvertToBlockScope_UnsupportedFixAllScopes(string fixAllScope) - { - await TestMissingInRegularAndScriptAsync($@" -namespace {{|{fixAllScope}:|}}N1; -", new TestParameters(options: PreferFileScopedNamespace)); - } + public Task TestConvertToBlockScope_UnsupportedFixAllScopes(string fixAllScope) + => TestMissingInRegularAndScriptAsync($$""" + namespace {|{{fixAllScope}}:|}N1; + """, new TestParameters(options: PreferFileScopedNamespace)); } diff --git a/src/Features/CSharpTest/ConvertNamespace/ConvertNamespaceRefactoringTests.cs b/src/Features/CSharpTest/ConvertNamespace/ConvertNamespaceRefactoringTests.cs index fa645a11949f8..f042dbbcef5c5 100644 --- a/src/Features/CSharpTest/ConvertNamespace/ConvertNamespaceRefactoringTests.cs +++ b/src/Features/CSharpTest/ConvertNamespace/ConvertNamespaceRefactoringTests.cs @@ -26,47 +26,40 @@ public sealed class ConvertNamespaceRefactoringTests #region Convert To File Scoped [Fact] - public async Task TestNoConvertToFileScopedInCSharp9() - { - var code = """ + public Task TestNoConvertToFileScopedInCSharp9() + => new VerifyCS.Test + { + TestCode = """ namespace $$N { } - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp9, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestNoConvertToFileScopedInCSharp10WithFileScopedPreference() - { - var code = """ + public Task TestNoConvertToFileScopedInCSharp10WithFileScopedPreference() + => new VerifyCS.Test + { + TestCode = """ namespace $$N { } - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedInCSharp10WithBlockScopedPreference() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedInCSharp10WithBlockScopedPreference() + => new VerifyCS.Test { TestCode = """ namespace $$N @@ -82,12 +75,10 @@ namespace $$N; { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestOnNamespaceToken() - { - await new VerifyCS.Test + public Task TestOnNamespaceToken() + => new VerifyCS.Test { TestCode = """ $$namespace N @@ -103,51 +94,45 @@ namespace N; { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestNotBeforeNamespaceToken() - { - var code = """ + public Task TestNotBeforeNamespaceToken() + => new VerifyCS.Test + { + TestCode = """ $$ namespace N { } - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestNotOnOpenBrace() - { - var code = """ + public Task TestNotOnOpenBrace() + => new VerifyCS.Test + { + TestCode = """ namespace N $${ } - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestNoConvertWithMultipleNamespaces() - { - var code = """ + public Task TestNoConvertWithMultipleNamespaces() + => new VerifyCS.Test + { + TestCode = """ namespace $$N { } @@ -155,108 +140,91 @@ namespace $$N namespace N2 { } - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestNoConvertWithNestedNamespaces1() - { - var code = """ + public Task TestNoConvertWithNestedNamespaces1() + => new VerifyCS.Test + { + TestCode = """ namespace $$N { namespace N2 { } } - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestNoConvertWithNestedNamespaces2() - { - var code = """ + public Task TestNoConvertWithNestedNamespaces2() + => new VerifyCS.Test + { + TestCode = """ namespace N { namespace $$N2 { } } - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestNoConvertWithTopLevelStatement1() - { - var code = """ + public Task TestNoConvertWithTopLevelStatement1() + => new VerifyCS.Test + { + TestCode = """ {|CS8805:int i = 0;|} namespace $$N { } - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestNoConvertWithTopLevelStatement2() - { - var code = """ + public Task TestNoConvertWithTopLevelStatement2() + => new VerifyCS.Test + { + TestCode = """ namespace $$N { } {|CS8805:{|CS8803:int i = 0;|}|} - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedWithUsing1() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithUsing1() + => new VerifyCS.Test { TestCode = """ using System; @@ -276,12 +244,10 @@ namespace $$N; { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedWithUsing2() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithUsing2() + => new VerifyCS.Test { TestCode = """ namespace $$N @@ -300,12 +266,10 @@ namespace $$N; { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedWithClass() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithClass() + => new VerifyCS.Test { TestCode = """ namespace $$N @@ -328,12 +292,10 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedWithClassWithDocComment() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithClassWithDocComment() + => new VerifyCS.Test { TestCode = """ namespace $$N @@ -358,12 +320,10 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedWithMissingCloseBrace() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithMissingCloseBrace() + => new VerifyCS.Test { TestCode = """ namespace $$N @@ -387,12 +347,10 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedWithCommentOnOpenCurly() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithCommentOnOpenCurly() + => new VerifyCS.Test { TestCode = """ namespace $$N @@ -415,12 +373,10 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToFileScopedWithLeadingComment() - { - await new VerifyCS.Test + public Task TestConvertToFileScopedWithLeadingComment() + => new VerifyCS.Test { TestCode = """ // copyright @@ -445,12 +401,10 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57564")] - public async Task TextConvertToFileScopedWithCommentedOutContents() - { - await new VerifyCS.Test + public Task TextConvertToFileScopedWithCommentedOutContents() + => new VerifyCS.Test { TestCode = """ $$namespace N @@ -473,12 +427,10 @@ namespace N; { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57564")] - public async Task TextConvertToFileScopedWithCommentedAfterContents() - { - await new VerifyCS.Test + public Task TextConvertToFileScopedWithCommentedAfterContents() + => new VerifyCS.Test { TestCode = """ $$namespace N @@ -505,12 +457,10 @@ public class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57564")] - public async Task TextConvertToFileScopedWithTriviaAroundNamespace1() - { - await new VerifyCS.Test + public Task TextConvertToFileScopedWithTriviaAroundNamespace1() + => new VerifyCS.Test { TestCode = """ #if !NONEXISTENT @@ -541,12 +491,10 @@ public class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57564")] - public async Task TextConvertToFileScopedWithTriviaAroundNamespace2() - { - await new VerifyCS.Test + public Task TextConvertToFileScopedWithTriviaAroundNamespace2() + => new VerifyCS.Test { TestCode = """ #if NONEXISTENT @@ -577,7 +525,6 @@ public class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } #endregion @@ -585,9 +532,8 @@ public class C [Theory] [MemberData(nameof(EndOfDocumentSequences))] - public async Task TestConvertToBlockScopedInCSharp9(string endOfDocumentSequence) - { - await new VerifyCS.Test + public Task TestConvertToBlockScopedInCSharp9(string endOfDocumentSequence) + => new VerifyCS.Test { TestCode = $$""" {|CS8773:namespace|} $$N;{{endOfDocumentSequence}} @@ -603,29 +549,24 @@ namespace $$N { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestNoConvertToBlockScopedInCSharp10WithBlockScopedPreference() - { - var code = """ - namespace $$N; - """; - await new VerifyCS.Test + public Task TestNoConvertToBlockScopedInCSharp10WithBlockScopedPreference() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + namespace $$N; + """, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockScopedInCSharp10WithFileScopedPreference() - { - await new VerifyCS.Test + public Task TestConvertToBlockScopedInCSharp10WithFileScopedPreference() + => new VerifyCS.Test { TestCode = """ namespace $$N; @@ -641,12 +582,10 @@ namespace $$N { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockOnNamespaceToken2() - { - await new VerifyCS.Test + public Task TestConvertToBlockOnNamespaceToken2() + => new VerifyCS.Test { TestCode = """ $$namespace N; @@ -662,65 +601,54 @@ namespace N { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockNotBeforeNamespaceToken2() - { - var code = """ + public Task TestConvertToBlockNotBeforeNamespaceToken2() + => new VerifyCS.Test + { + TestCode = """ $$ namespace N; - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockNotAfterSemicolon() - { - var code = """ + public Task TestConvertToBlockNotAfterSemicolon() + => new VerifyCS.Test + { + TestCode = """ namespace N; $$ - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockAfterSemicolon() - { - var code = """ - namespace N; $$ - """; - await new VerifyCS.Test + public Task TestConvertToBlockAfterSemicolon() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + namespace N; $$ + """, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockWithMultipleNamespaces() - { - await new VerifyCS.Test + public Task TestConvertToBlockWithMultipleNamespaces() + => new VerifyCS.Test { TestCode = """ namespace $$N; @@ -743,12 +671,10 @@ namespace N2 { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockWithNestedNamespaces1() - { - await new VerifyCS.Test + public Task TestConvertToBlockWithNestedNamespaces1() + => new VerifyCS.Test { TestCode = """ namespace $$N; @@ -767,12 +693,10 @@ namespace {|CS8955:N2|}; { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockWithNestedNamespaces2() - { - await new VerifyCS.Test + public Task TestConvertToBlockWithNestedNamespaces2() + => new VerifyCS.Test { TestCode = """ namespace N @@ -794,12 +718,10 @@ namespace $$N2 { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockWithTopLevelStatement1() - { - await new VerifyCS.Test + public Task TestConvertToBlockWithTopLevelStatement1() + => new VerifyCS.Test { TestCode = """ {|CS8805:int i = 0;|} @@ -819,12 +741,10 @@ namespace $$N { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockWithTopLevelStatement2() - { - await new VerifyCS.Test + public Task TestConvertToBlockWithTopLevelStatement2() + => new VerifyCS.Test { TestCode = """ namespace $$N; @@ -843,12 +763,10 @@ namespace $$N { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockScopedWithUsing1() - { - await new VerifyCS.Test + public Task TestConvertToBlockScopedWithUsing1() + => new VerifyCS.Test { TestCode = """ using System; @@ -868,12 +786,10 @@ namespace $$N { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockScopedWithUsing2() - { - await new VerifyCS.Test + public Task TestConvertToBlockScopedWithUsing2() + => new VerifyCS.Test { TestCode = """ namespace $$N; @@ -892,12 +808,10 @@ namespace $$N { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockScopedWithClass() - { - await new VerifyCS.Test + public Task TestConvertToBlockScopedWithClass() + => new VerifyCS.Test { TestCode = """ namespace $$N; @@ -920,12 +834,10 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockScopedWithClassWithDocComment() - { - await new VerifyCS.Test + public Task TestConvertToBlockScopedWithClassWithDocComment() + => new VerifyCS.Test { TestCode = """ namespace $$N; @@ -950,12 +862,10 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockScopedWithMissingCloseBrace() - { - await new VerifyCS.Test + public Task TestConvertToBlockScopedWithMissingCloseBrace() + => new VerifyCS.Test { TestCode = """ namespace $$N; @@ -979,12 +889,10 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockScopedWithCommentOnSemicolon() - { - await new VerifyCS.Test + public Task TestConvertToBlockScopedWithCommentOnSemicolon() + => new VerifyCS.Test { TestCode = """ namespace $$N; // comment @@ -1007,12 +915,10 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } [Fact] - public async Task TestConvertToBlockScopedWithLeadingComment() - { - await new VerifyCS.Test + public Task TestConvertToBlockScopedWithLeadingComment() + => new VerifyCS.Test { TestCode = """ // copyright @@ -1037,7 +943,6 @@ class C { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); - } #endregion } diff --git a/src/Features/CSharpTest/ConvertNumericLiteral/ConvertNumericLiteralTests.cs b/src/Features/CSharpTest/ConvertNumericLiteral/ConvertNumericLiteralTests.cs index 4ac229c60b990..d3c704e47b33d 100644 --- a/src/Features/CSharpTest/ConvertNumericLiteral/ConvertNumericLiteralTests.cs +++ b/src/Features/CSharpTest/ConvertNumericLiteral/ConvertNumericLiteralTests.cs @@ -79,9 +79,8 @@ public async Task TestTypeCharacter() => await TestFixOneAsync("0x1e5UL", "0b111100101UL", Refactoring.ChangeBase2); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19225")] - public async Task TestPreserveWhitespaces() - { - await TestInRegularAndScriptAsync( + public Task TestPreserveWhitespaces() + => TestInRegularAndScriptAsync( """ class Program { @@ -104,12 +103,10 @@ void M() } } """, index: (int)Refactoring.ChangeBase2); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19369")] - public async Task TestCaretPositionAtTheEnd() - { - await TestInRegularAndScriptAsync( + public Task TestCaretPositionAtTheEnd() + => TestInRegularAndScriptAsync( """ class C { @@ -122,12 +119,10 @@ class C int a = 0b101010; } """, index: (int)Refactoring.ChangeBase1); - } [Fact] - public async Task TestSelectionMatchesToken() - { - await TestInRegularAndScriptAsync( + public Task TestSelectionMatchesToken() + => TestInRegularAndScriptAsync( """ class C { @@ -140,17 +135,14 @@ class C int a = 0b101010; } """, index: (int)Refactoring.ChangeBase1); - } [Fact] - public async Task TestSelectionDoesNotMatchToken() - { - await TestMissingInRegularAndScriptAsync( + public Task TestSelectionDoesNotMatchToken() + => TestMissingInRegularAndScriptAsync( """ class C { int a = [|42 * 2|]; } """); - } } diff --git a/src/Features/CSharpTest/ConvertPrimaryToRegularConstructor/ConvertPrimaryToRegularConstructorTests.cs b/src/Features/CSharpTest/ConvertPrimaryToRegularConstructor/ConvertPrimaryToRegularConstructorTests.cs index 94568186cfcdf..b8507cedb4325 100644 --- a/src/Features/CSharpTest/ConvertPrimaryToRegularConstructor/ConvertPrimaryToRegularConstructorTests.cs +++ b/src/Features/CSharpTest/ConvertPrimaryToRegularConstructor/ConvertPrimaryToRegularConstructorTests.cs @@ -31,9 +31,8 @@ public sealed class ConvertPrimaryToRegularConstructorTests """; [Fact] - public async Task TestInCSharp12() - { - await new VerifyCS.Test + public Task TestInCSharp12() + => new VerifyCS.Test { TestCode = """ class [|C(int i)|] @@ -50,12 +49,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithRecord() - { - await new VerifyCS.Test + public Task TestNotWithRecord() + => new VerifyCS.Test { TestCode = """ record class [|C(int i)|] @@ -70,12 +67,10 @@ record class C(int i) LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); - } [Fact] - public async Task TestStruct() - { - await new VerifyCS.Test + public Task TestStruct() + => new VerifyCS.Test { TestCode = """ struct [|C(int i)|] @@ -92,12 +87,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithThisChainedConstructor() - { - await new VerifyCS.Test + public Task TestWithThisChainedConstructor() + => new VerifyCS.Test { TestCode = """ class [|C(int i)|] @@ -121,12 +114,10 @@ public C() : this(0) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithBaseChainedConstructor1() - { - await new VerifyCS.Test + public Task TestWithBaseChainedConstructor1() + => new VerifyCS.Test { TestCode = """ class B(int i) @@ -158,12 +149,10 @@ public C() : this(0) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithBaseChainedConstructor2() - { - await new VerifyCS.Test + public Task TestWithBaseChainedConstructor2() + => new VerifyCS.Test { TestCode = """ class B(int i) @@ -195,12 +184,10 @@ public C() : this(0) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithBaseChainedConstructor3() - { - await new VerifyCS.Test + public Task TestWithBaseChainedConstructor3() + => new VerifyCS.Test { TestCode = """ class B(int i, int j) @@ -234,12 +221,10 @@ public C() : this(0, 0) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithBaseChainedConstructor4() - { - await new VerifyCS.Test + public Task TestWithBaseChainedConstructor4() + => new VerifyCS.Test { TestCode = """ class B(int i, int j) @@ -273,12 +258,10 @@ public C() : this(0, 0) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithBaseChainedConstructor5() - { - await new VerifyCS.Test + public Task TestWithBaseChainedConstructor5() + => new VerifyCS.Test { TestCode = """ class B(int i, int j) @@ -314,12 +297,10 @@ public C() : this(0, 0) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithReferenceOnlyInExistingSameNamedField() - { - await new VerifyCS.Test + public Task TestWithReferenceOnlyInExistingSameNamedField() + => new VerifyCS.Test { TestCode = """ class [|C(int i)|] @@ -340,12 +321,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithReferenceOnlyInPropertyInitializer1() - { - await new VerifyCS.Test + public Task TestWithReferenceOnlyInPropertyInitializer1() + => new VerifyCS.Test { TestCode = """ class [|C(int i)|] @@ -366,12 +345,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithReferenceInDifferentNamedField() - { - await new VerifyCS.Test + public Task TestWithReferenceInDifferentNamedField() + => new VerifyCS.Test { TestCode = """ class [|C(int j)|] @@ -392,12 +369,10 @@ public C(int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithComplexFieldInitializer1() - { - await new VerifyCS.Test + public Task TestWithComplexFieldInitializer1() + => new VerifyCS.Test { TestCode = """ class [|C(int i)|] @@ -418,12 +393,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithComplexFieldInitializer2() - { - await new VerifyCS.Test + public Task TestWithComplexFieldInitializer2() + => new VerifyCS.Test { TestCode = """ class [|C(int i)|] @@ -444,12 +417,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithComplexFieldInitializer3() - { - await new VerifyCS.Test + public Task TestWithComplexFieldInitializer3() + => new VerifyCS.Test { TestCode = """ class [|C(int i)|] @@ -473,12 +444,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultipleParametersWithFieldInitializers1() - { - await new VerifyCS.Test + public Task TestMultipleParametersWithFieldInitializers1() + => new VerifyCS.Test { TestCode = """ class [|C(int i, int j)|] @@ -502,12 +471,10 @@ public C(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultipleParametersWithFieldInitializers2() - { - await new VerifyCS.Test + public Task TestMultipleParametersWithFieldInitializers2() + => new VerifyCS.Test { TestCode = """ class [|C(int i, int j)|] @@ -529,12 +496,10 @@ public C(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithParametersReferencedOutsideOfConstructor() - { - await new VerifyCS.Test + public Task TestWithParametersReferencedOutsideOfConstructor() + => new VerifyCS.Test { TestCode = """ class [|C(int i, int j)|] @@ -565,12 +530,10 @@ int M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithParametersReferencedOutsideOfConstructor_Mutation1() - { - await new VerifyCS.Test + public Task TestWithParametersReferencedOutsideOfConstructor_Mutation1() + => new VerifyCS.Test { TestCode = """ class [|C(int i, int j)|] @@ -601,12 +564,10 @@ int M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithoutParametersReferencedOutsideOfConstructor() - { - await new VerifyCS.Test + public Task TestWithoutParametersReferencedOutsideOfConstructor() + => new VerifyCS.Test { TestCode = """ class [|C(int i, int j)|] @@ -623,12 +584,10 @@ public C(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestAssignmentToPropertyOfDifferentType() - { - await new VerifyCS.Test + public Task TestAssignmentToPropertyOfDifferentType() + => new VerifyCS.Test { TestCode = """ class [|C(int i, int j)|] @@ -649,12 +608,10 @@ public C(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestAssignedToFieldUsedInNestedType() - { - await new VerifyCS.Test + public Task TestAssignedToFieldUsedInNestedType() + => new VerifyCS.Test { TestCode = """ using System; @@ -701,12 +658,10 @@ public Enumerator(OuterType c) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithNotMutatedReferencesOutsideOfConstructor1() - { - await new VerifyCS.Test + public Task TestWithNotMutatedReferencesOutsideOfConstructor1() + => new VerifyCS.Test { TestCode = """ using System; @@ -739,12 +694,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestEscapedParameterNames() - { - await new VerifyCS.Test + public Task TestEscapedParameterNames() + => new VerifyCS.Test { TestCode = """ using System; @@ -777,12 +730,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithNotMutatedReferencesOutsideOfConstructor2() - { - await new VerifyCS.Test + public Task TestWithNotMutatedReferencesOutsideOfConstructor2() + => new VerifyCS.Test { TestCode = """ using System; @@ -817,12 +768,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithNotMutatedReferencesOutsideOfConstructor3() - { - await new VerifyCS.Test + public Task TestWithNotMutatedReferencesOutsideOfConstructor3() + => new VerifyCS.Test { TestCode = """ using System; @@ -859,12 +808,10 @@ void M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestGenerateUnderscoreName1() - { - await new VerifyCS.Test + public Task TestGenerateUnderscoreName1() + => new VerifyCS.Test { TestCode = """ using System; @@ -902,12 +849,10 @@ void M(C c) LanguageVersion = LanguageVersion.CSharp12, EditorConfig = FieldNamesCamelCaseWithFieldUnderscorePrefixEditorConfig, }.RunAsync(); - } [Fact] - public async Task TestGenerateUnderscoreName2() - { - await new VerifyCS.Test + public Task TestGenerateUnderscoreName2() + => new VerifyCS.Test { TestCode = """ using System; @@ -945,12 +890,10 @@ void M(C c) LanguageVersion = LanguageVersion.CSharp12, EditorConfig = FieldNamesCamelCaseWithFieldUnderscorePrefixEditorConfig, }.RunAsync(); - } [Fact] - public async Task TestComplexFieldInitializer() - { - await new VerifyCS.Test + public Task TestComplexFieldInitializer() + => new VerifyCS.Test { TestCode = """ class [|C(int i)|] @@ -975,12 +918,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveParamDocs1() - { - await new VerifyCS.Test + public Task TestMoveParamDocs1() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1011,12 +952,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveParamDocs2() - { - await new VerifyCS.Test + public Task TestMoveParamDocs2() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1051,12 +990,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveParamDocs3() - { - await new VerifyCS.Test + public Task TestMoveParamDocs3() + => new VerifyCS.Test { TestCode = """ ///Doc comment on single line @@ -1081,12 +1018,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveParamDocs4() - { - await new VerifyCS.Test + public Task TestMoveParamDocs4() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1129,12 +1064,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveParamDocs5() - { - await new VerifyCS.Test + public Task TestMoveParamDocs5() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1173,12 +1106,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveParamDocs6() - { - await new VerifyCS.Test + public Task TestMoveParamDocs6() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1213,12 +1144,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveParamDocs7() - { - await new VerifyCS.Test + public Task TestMoveParamDocs7() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1261,12 +1190,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveParamDocs9() - { - await new VerifyCS.Test + public Task TestMoveParamDocs9() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1310,12 +1237,10 @@ public C(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveParamDocs10() - { - await new VerifyCS.Test + public Task TestMoveParamDocs10() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1357,12 +1282,10 @@ public C(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveParamDocs11() - { - await new VerifyCS.Test + public Task TestMoveParamDocs11() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1393,12 +1316,10 @@ public C(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveParamDocs13() - { - await new VerifyCS.Test + public Task TestMoveParamDocs13() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1425,12 +1346,10 @@ public C(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveParamDocs14() - { - await new VerifyCS.Test + public Task TestMoveParamDocs14() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1457,12 +1376,10 @@ public C(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveParamDocs15() - { - await new VerifyCS.Test + public Task TestMoveParamDocs15() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1489,12 +1406,10 @@ public C(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveParamDocs16() - { - await new VerifyCS.Test + public Task TestMoveParamDocs16() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1525,12 +1440,10 @@ public C(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveParamDocs17() - { - await new VerifyCS.Test + public Task TestMoveParamDocs17() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1557,12 +1470,10 @@ public C(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveParamDocs18() - { - await new VerifyCS.Test + public Task TestMoveParamDocs18() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1593,12 +1504,10 @@ public C(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveParamDocs19() - { - await new VerifyCS.Test + public Task TestMoveParamDocs19() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1635,12 +1544,10 @@ public C(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveParamDocs20() - { - await new VerifyCS.Test + public Task TestMoveParamDocs20() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1673,12 +1580,10 @@ public C(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveParamDocs21() - { - await new VerifyCS.Test + public Task TestMoveParamDocs21() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1711,12 +1616,10 @@ public C(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveParamDocs22() - { - await new VerifyCS.Test + public Task TestMoveParamDocs22() + => new VerifyCS.Test { TestCode = """ namespace N @@ -1753,12 +1656,10 @@ public C(int i, int j) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveConstructorAttributes1() - { - await new VerifyCS.Test + public Task TestMoveConstructorAttributes1() + => new VerifyCS.Test { TestCode = """ using System; @@ -1780,12 +1681,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveConstructorAttributes1A() - { - await new VerifyCS.Test + public Task TestMoveConstructorAttributes1A() + => new VerifyCS.Test { TestCode = """ using System; @@ -1808,12 +1707,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveConstructorAttributes2() - { - await new VerifyCS.Test + public Task TestMoveConstructorAttributes2() + => new VerifyCS.Test { TestCode = """ using System; @@ -1842,12 +1739,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveConstructorAttributes2A() - { - await new VerifyCS.Test + public Task TestMoveConstructorAttributes2A() + => new VerifyCS.Test { TestCode = """ using System; @@ -1878,12 +1773,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveConstructorAttributes3() - { - await new VerifyCS.Test + public Task TestMoveConstructorAttributes3() + => new VerifyCS.Test { TestCode = """ using System; @@ -1915,12 +1808,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveConstructorAttributes3A() - { - await new VerifyCS.Test + public Task TestMoveConstructorAttributes3A() + => new VerifyCS.Test { TestCode = """ using System; @@ -1954,12 +1845,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveConstructorAttributes4() - { - await new VerifyCS.Test + public Task TestMoveConstructorAttributes4() + => new VerifyCS.Test { TestCode = """ using System; @@ -1986,12 +1875,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMoveConstructorAttributes4A() - { - await new VerifyCS.Test + public Task TestMoveConstructorAttributes4A() + => new VerifyCS.Test { TestCode = """ using System; @@ -2021,12 +1908,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultipleParametersMove1() - { - await new VerifyCS.Test + public Task TestMultipleParametersMove1() + => new VerifyCS.Test { TestCode = """ using System; @@ -2049,12 +1934,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultipleParametersMove1A() - { - await new VerifyCS.Test + public Task TestMultipleParametersMove1A() + => new VerifyCS.Test { TestCode = """ using System; @@ -2083,12 +1966,10 @@ class C """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultipleParametersMove2() - { - await new VerifyCS.Test + public Task TestMultipleParametersMove2() + => new VerifyCS.Test { TestCode = """ using System; @@ -2113,12 +1994,10 @@ public C( """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultipleParametersMove2A() - { - await new VerifyCS.Test + public Task TestMultipleParametersMove2A() + => new VerifyCS.Test { TestCode = """ using System; @@ -2149,12 +2028,10 @@ public C( """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultipleParametersMove3() - { - await new VerifyCS.Test + public Task TestMultipleParametersMove3() + => new VerifyCS.Test { TestCode = """ using System; @@ -2177,12 +2054,10 @@ public C( """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultipleParametersMove3A() - { - await new VerifyCS.Test + public Task TestMultipleParametersMove3A() + => new VerifyCS.Test { TestCode = """ using System; @@ -2211,12 +2086,10 @@ public C( """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultipleParametersMove4() - { - await new VerifyCS.Test + public Task TestMultipleParametersMove4() + => new VerifyCS.Test { TestCode = """ using System; @@ -2241,12 +2114,10 @@ public C( """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestMultipleParametersMove4A() - { - await new VerifyCS.Test + public Task TestMultipleParametersMove4A() + => new VerifyCS.Test { TestCode = """ using System; @@ -2277,12 +2148,10 @@ public C( """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestReferenceToNestedType1() - { - await new VerifyCS.Test + public Task TestReferenceToNestedType1() + => new VerifyCS.Test { TestCode = """ class [|C(C.D d)|] @@ -2306,12 +2175,10 @@ public class D """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestReferenceToNestedType2() - { - await new VerifyCS.Test + public Task TestReferenceToNestedType2() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -2339,12 +2206,10 @@ public class D """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestReferenceToNestedType3() - { - await new VerifyCS.Test + public Task TestReferenceToNestedType3() + => new VerifyCS.Test { TestCode = """ class [|C(C.D d)|] @@ -2368,12 +2233,10 @@ public class D """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestReferenceToNestedType4() - { - await new VerifyCS.Test + public Task TestReferenceToNestedType4() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -2401,12 +2264,10 @@ public class D """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInParameter1() - { - await new VerifyCS.Test + public Task TestInParameter1() + => new VerifyCS.Test { TestCode = """ class [|C(in int i)|] @@ -2427,12 +2288,10 @@ public C(in int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestInParameter2_Unused() - { - await new VerifyCS.Test + public Task TestInParameter2_Unused() + => new VerifyCS.Test { TestCode = """ class [|C(in int i)|] @@ -2449,12 +2308,10 @@ public C(in int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithRegionDirective1() - { - await new VerifyCS.Test + public Task TestWithRegionDirective1() + => new VerifyCS.Test { TestCode = """ class [|C(int i)|] @@ -2480,12 +2337,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestWithRegionDirective2() - { - await new VerifyCS.Test + public Task TestWithRegionDirective2() + => new VerifyCS.Test { TestCode = """ class [|C(int i)|] @@ -2520,12 +2375,10 @@ public C(string s) : this(s.Length) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestSeeTag1() - { - await new VerifyCS.Test + public Task TestSeeTag1() + => new VerifyCS.Test { TestCode = """ /// @@ -2552,12 +2405,10 @@ public C(int i) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestSeeTag2() - { - await new VerifyCS.Test + public Task TestSeeTag2() + => new VerifyCS.Test { TestCode = """ /// @@ -2592,12 +2443,10 @@ int M() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestSeeTag3() - { - await new VerifyCS.Test + public Task TestSeeTag3() + => new VerifyCS.Test { TestCode = """ /// @@ -2633,12 +2482,10 @@ int M() LanguageVersion = LanguageVersion.CSharp12, EditorConfig = FieldNamesCamelCaseWithFieldUnderscorePrefixEditorConfig, }.RunAsync(); - } [Fact] - public async Task TestReferenceToConstantInParameterInitializer1() - { - await new VerifyCS.Test + public Task TestReferenceToConstantInParameterInitializer1() + => new VerifyCS.Test { TestCode = """ class [|C(int i = C.Default)|] @@ -2661,12 +2508,10 @@ public C(int i = Default) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestReferenceToConstantInParameterInitializer2() - { - await new VerifyCS.Test + public Task TestReferenceToConstantInParameterInitializer2() + => new VerifyCS.Test { TestCode = """ class [|C(int i = C.Default)|] @@ -2689,12 +2534,10 @@ public C(int i = Default) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestReferenceToConstantInParameterInitializer3() - { - await new VerifyCS.Test + public Task TestReferenceToConstantInParameterInitializer3() + => new VerifyCS.Test { TestCode = """ class [|C(int i = C.Default)|] @@ -2717,12 +2560,10 @@ public C(int i = Default) """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72340")] - public async Task TestClassWithoutBody() - { - await new VerifyCS.Test + public Task TestClassWithoutBody() + => new VerifyCS.Test { TestCode = """ class [|Class1()|]; @@ -2738,12 +2579,10 @@ public Class1() """, LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotOnExtension() - { - await new VerifyCS.Test + public Task TestNotOnExtension() + => new VerifyCS.Test { TestCode = """ static class Class1 @@ -2756,12 +2595,10 @@ public void Goo() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76981")] - public async Task TestConvertWithReferencesToParameter1() - { - await new VerifyCS.Test + public Task TestConvertWithReferencesToParameter1() + => new VerifyCS.Test { TestCode = """ namespace N @@ -2801,5 +2638,507 @@ public void Baz() """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/79077")] + public Task TestOnPartialType_NotUsed() + => new VerifyCS.Test() + { + TestState = + { + Sources = + { + """ + partial class [|C(int i)|] + { + } + """, """ + partial class C + { + } + """ + } + }, + FixedState = + { + Sources = + { + """ + partial class C + { + public C(int i) + { + } + } + """, """ + partial class C + { + } + """ + } + }, + LanguageVersion = LanguageVersion.CSharp12, + }.RunAsync(); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/79077")] + public Task TestOnPartialType_UsedInSamePartialPart() + => new VerifyCS.Test() + { + TestState = + { + Sources = + { + """ + partial class [|C(int i)|] + { + public int I { get; } = i; + } + """, """ + partial class C + { + } + """ + } + }, + FixedState = + { + Sources = + { + """ + partial class C + { + public int I { get; } + + public C(int i) + { + I = i; + } + } + """, """ + partial class C + { + } + """ + } + }, + LanguageVersion = LanguageVersion.CSharp12, + }.RunAsync(); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/79077")] + public Task TestOnPartialType_UsedInOtherPartialPart() + => new VerifyCS.Test() + { + TestState = + { + Sources = + { + """ + partial class [|C(int i)|] + { + } + """, """ + partial class C + { + public int I { get; } = i; + } + """ + } + }, + FixedState = + { + Sources = + { + """ + partial class C + { + public C(int i) + { + I = i; + } + } + """, """ + partial class C + { + public int I { get; } + } + """ + } + }, + LanguageVersion = LanguageVersion.CSharp12, + }.RunAsync(); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/79077")] + public Task TestOnPartialType_UsedInAllPartialParts() + => new VerifyCS.Test() + { + TestState = + { + Sources = + { + """ + partial class [|C(int i)|] + { + public int I1 { get; } = i + 1; + } + """, """ + partial class C + { + public int I2 { get; } = i + 2; + } + """ + } + }, + FixedState = + { + Sources = + { + """ + partial class C + { + public int I1 { get; } + + public C(int i) + { + I1 = i + 1; + I2 = i + 2; + } + } + """, """ + partial class C + { + public int I2 { get; } + } + """ + } + }, + LanguageVersion = LanguageVersion.CSharp12, + }.RunAsync(); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/79077")] + public Task TestOnPartialType_CapturedInSamePartialPart_SameFieldName() + => new VerifyCS.Test() + { + TestState = + { + Sources = + { + """ + partial class [|C(int i)|] + { + int M() + { + return i; + } + } + """, """ + partial class C + { + } + """ + } + }, + FixedState = + { + Sources = + { + """ + partial class C + { + private readonly int i; + + public C(int i) + { + this.i = i; + } + + int M() + { + return i; + } + } + """, """ + partial class C + { + } + """ + } + }, + LanguageVersion = LanguageVersion.CSharp12, + }.RunAsync(); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/79077")] + public Task TestOnPartialType_CapturedInSamePartialPart_UnderscoreFieldName() + => new VerifyCS.Test() + { + TestState = + { + Sources = + { + """ + partial class [|C(int i)|] + { + int M() + { + return i; + } + } + """, """ + partial class C + { + } + """ + } + }, + FixedState = + { + Sources = + { + """ + partial class C + { + private readonly int _i; + + public C(int i) + { + _i = i; + } + + int M() + { + return _i; + } + } + """, """ + partial class C + { + } + """ + } + }, + LanguageVersion = LanguageVersion.CSharp12, + EditorConfig = FieldNamesCamelCaseWithFieldUnderscorePrefixEditorConfig, + }.RunAsync(); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/79077")] + public Task TestOnPartialType_CapturedInOtherPartialPart_SameFieldName() + => new VerifyCS.Test() + { + TestState = + { + Sources = + { + """ + partial class [|C(int i)|] + { + } + """, """ + partial class C + { + int M() + { + return i; + } + } + """ + } + }, + FixedState = + { + Sources = + { + """ + partial class C + { + private readonly int i; + + public C(int i) + { + this.i = i; + } + } + """, """ + partial class C + { + int M() + { + return i; + } + } + """ + } + }, + LanguageVersion = LanguageVersion.CSharp12, + }.RunAsync(); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/79077")] + public Task TestOnPartialType_CapturedInOtherPartialPart_UnderscoreFieldName() + => new VerifyCS.Test() + { + TestState = + { + Sources = + { + """ + partial class [|C(int i)|] + { + } + """, """ + partial class C + { + int M() + { + return i; + } + } + """ + } + }, + FixedState = + { + Sources = + { + """ + partial class C + { + private readonly int _i; + + public C(int i) + { + _i = i; + } + } + """, """ + partial class C + { + int M() + { + return _i; + } + } + """ + } + }, + LanguageVersion = LanguageVersion.CSharp12, + EditorConfig = FieldNamesCamelCaseWithFieldUnderscorePrefixEditorConfig, + }.RunAsync(); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/79077")] + public Task TestOnPartialType_CapturedInAllPartialParts_SameFieldName() + => new VerifyCS.Test() + { + TestState = + { + Sources = + { + """ + partial class [|C(int i)|] + { + int M() + { + return i; + } + } + """, """ + partial class C + { + int N() + { + return i; + } + } + """ + } + }, + FixedState = + { + Sources = + { + """ + partial class C + { + private readonly int i; + + public C(int i) + { + this.i = i; + } + + int M() + { + return i; + } + } + """, """ + partial class C + { + int N() + { + return i; + } + } + """ + } + }, + LanguageVersion = LanguageVersion.CSharp12, + }.RunAsync(); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/79077")] + public Task TestOnPartialType_CapturedInAllPartialParts_UnderscoreFieldName() + => new VerifyCS.Test() + { + TestState = + { + Sources = + { + """ + partial class [|C(int i)|] + { + int M() + { + return i; + } + } + """, """ + partial class C + { + int N() + { + return i; + } + } + """ + } + }, + FixedState = + { + Sources = + { + """ + partial class C + { + private readonly int _i; + + public C(int i) + { + _i = i; + } + + int M() + { + return _i; + } + } + """, """ + partial class C + { + int N() + { + return _i; + } + } + """ + } + }, + LanguageVersion = LanguageVersion.CSharp12, + EditorConfig = FieldNamesCamelCaseWithFieldUnderscorePrefixEditorConfig, + }.RunAsync(); } diff --git a/src/Features/CSharpTest/ConvertProgram/ConvertToProgramMainAnalyzerTests.cs b/src/Features/CSharpTest/ConvertProgram/ConvertToProgramMainAnalyzerTests.cs index 1e02a8306e68c..201215d5e4af2 100644 --- a/src/Features/CSharpTest/ConvertProgram/ConvertToProgramMainAnalyzerTests.cs +++ b/src/Features/CSharpTest/ConvertProgram/ConvertToProgramMainAnalyzerTests.cs @@ -19,25 +19,22 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertProgram; public sealed class ConvertToProgramMainAnalyzerTests { [Fact] - public async Task NotOfferedWhenUserPrefersTopLevelStatements() - { - var code = """ - System.Console.WriteLine(0); - """; - - await new VerifyCS.Test + public Task NotOfferedWhenUserPrefersTopLevelStatements() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + System.Console.WriteLine(0); + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true } }, }.RunAsync(); - } [Fact] - public async Task NotOfferedWhenUserPrefersProgramMainButNoTopLevelStatements() - { - var code = """ + public Task NotOfferedWhenUserPrefersProgramMainButNoTopLevelStatements() + => new VerifyCS.Test + { + TestCode = """ class C { void M() @@ -45,20 +42,14 @@ void M() System.Console.WriteLine(0); } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp9, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false } }, }.RunAsync(); - } [Fact] - public async Task OfferedWhenUserPrefersProgramMainAndTopLevelStatements_Silent() - { - await new VerifyCS.Test + public Task OfferedWhenUserPrefersProgramMainAndTopLevelStatements_Silent() + => new VerifyCS.Test { TestCode = """ {|IDE0211: @@ -79,12 +70,10 @@ private static void Main(string[] args) TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Silent } }, }.RunAsync(); - } [Fact] - public async Task TestHeader1() - { - await new VerifyCS.Test + public Task TestHeader1() + => new VerifyCS.Test { TestCode = """ {|IDE0211:// This is a file banner @@ -107,12 +96,10 @@ private static void Main(string[] args) TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Silent } }, }.RunAsync(); - } [Fact] - public async Task TestHeader2() - { - await new VerifyCS.Test + public Task TestHeader2() + => new VerifyCS.Test { TestCode = """ {|IDE0211:// This is a file banner @@ -137,43 +124,33 @@ private static void Main(string[] args) TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Silent } }, }.RunAsync(); - } [Fact] - public async Task NotOfferedInLibrary() - { - var code = """ - {|CS8805:System.Console.WriteLine(0);|} - """; - - await new VerifyCS.Test + public Task NotOfferedInLibrary() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + {|CS8805:System.Console.WriteLine(0);|} + """, LanguageVersion = LanguageVersion.CSharp9, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Silent } }, }.RunAsync(); - } [Fact] - public async Task NotOfferedWhenSuppressed() - { - var code = """ - System.Console.WriteLine(0); - """; - - await new VerifyCS.Test + public Task NotOfferedWhenSuppressed() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + System.Console.WriteLine(0); + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.None } }, }.RunAsync(); - } [Fact] - public async Task OfferedWhenUserPrefersProgramMainAndTopLevelStatements_Suggestion() - { - await new VerifyCS.Test + public Task OfferedWhenUserPrefersProgramMainAndTopLevelStatements_Suggestion() + => new VerifyCS.Test { TestCode = """ {|IDE0211:System|}.Console.WriteLine(0); @@ -191,12 +168,10 @@ private static void Main(string[] args) TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task PreferNoAccessibility() - { - await new VerifyCS.Test + public Task PreferNoAccessibility() + => new VerifyCS.Test { TestCode = """ {|IDE0211:System|}.Console.WriteLine(0); @@ -218,12 +193,10 @@ static void Main(string[] args) { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion }, }, }.RunAsync(); - } [Fact] - public async Task TestWithExistingUsings() - { - await new VerifyCS.Test + public Task TestWithExistingUsings() + => new VerifyCS.Test { TestCode = """ using System; @@ -245,12 +218,10 @@ private static void Main(string[] args) TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestWithNumericReturn() - { - await new VerifyCS.Test + public Task TestWithNumericReturn() + => new VerifyCS.Test { TestCode = """ using System; @@ -276,12 +247,10 @@ private static int Main(string[] args) TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestWithLocalFunction() - { - await new VerifyCS.Test + public Task TestWithLocalFunction() + => new VerifyCS.Test { TestCode = """ using System; @@ -315,12 +284,10 @@ void M() TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestWithAwait() - { - await new VerifyCS.Test + public Task TestWithAwait() + => new VerifyCS.Test { TestCode = """ using System; @@ -343,12 +310,10 @@ private static async Task Main(string[] args) TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestWithAwaitAndNumericReturn() - { - await new VerifyCS.Test + public Task TestWithAwaitAndNumericReturn() + => new VerifyCS.Test { TestCode = """ using System; @@ -375,12 +340,10 @@ private static async Task Main(string[] args) TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61126")] - public async Task TestNormalCommentStaysInsideMainIfTouchingStatement() - { - await new VerifyCS.Test + public Task TestNormalCommentStaysInsideMainIfTouchingStatement() + => new VerifyCS.Test { TestCode = """ using System; @@ -404,12 +367,10 @@ private static void Main(string[] args) TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61126")] - public async Task TestNormalCommentMovesIfNotTouching() - { - await new VerifyCS.Test + public Task TestNormalCommentMovesIfNotTouching() + => new VerifyCS.Test { TestCode = """ using System; @@ -435,12 +396,10 @@ private static void Main(string[] args) TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestTopLevelStatementExplanationCommentRemoved() - { - await new VerifyCS.Test + public Task TestTopLevelStatementExplanationCommentRemoved() + => new VerifyCS.Test { TestCode = """ using System; @@ -463,12 +422,10 @@ private static void Main(string[] args) TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestTopLevelStatementExplanationCommentRemoved2() - { - await new VerifyCS.Test + public Task TestTopLevelStatementExplanationCommentRemoved2() + => new VerifyCS.Test { TestCode = """ using System; @@ -492,12 +449,10 @@ private static void Main(string[] args) TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestTopLevelStatementExplanationCommentRemoved3() - { - await new VerifyCS.Test + public Task TestTopLevelStatementExplanationCommentRemoved3() + => new VerifyCS.Test { TestCode = """ // See https://aka.ms/new-console-template for more information @@ -517,12 +472,10 @@ private static void Main(string[] args) TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestTopLevelStatementExplanationCommentRemoved4() - { - await new VerifyCS.Test + public Task TestTopLevelStatementExplanationCommentRemoved4() + => new VerifyCS.Test { TestCode = """ // See https://aka.ms/new-console-template for more information @@ -541,12 +494,10 @@ private static void Main(string[] args) TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestPreprocessorDirective1() - { - await new VerifyCS.Test + public Task TestPreprocessorDirective1() + => new VerifyCS.Test { TestCode = """ using System; @@ -576,12 +527,10 @@ private static void Main(string[] args) TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestPreprocessorDirective2() - { - await new VerifyCS.Test + public Task TestPreprocessorDirective2() + => new VerifyCS.Test { TestCode = """ using System; @@ -615,12 +564,10 @@ private static void Main(string[] args) TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/62943")] - public async Task TestHasExistingPart() - { - await new VerifyCS.Test + public Task TestHasExistingPart() + => new VerifyCS.Test { TestCode = """ using System; @@ -649,7 +596,6 @@ private static void Main(string[] args) TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/62943")] [InlineData("public")] @@ -657,9 +603,8 @@ private static void Main(string[] args) [InlineData("static")] [InlineData("abstract")] [InlineData("file")] - public async Task TestHasExistingPart_KeepsModifiers(string modifier) - { - await new VerifyCS.Test + public Task TestHasExistingPart_KeepsModifiers(string modifier) + => new VerifyCS.Test { TestCode = $$""" using System; @@ -688,12 +633,10 @@ private static void Main(string[] args) TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestBeforeExistingClass() - { - await new VerifyCS.Test + public Task TestBeforeExistingClass() + => new VerifyCS.Test { TestCode = """ using System; @@ -725,5 +668,4 @@ class X TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion } }, }.RunAsync(); - } } diff --git a/src/Features/CSharpTest/ConvertProgram/ConvertToProgramMainRefactoringTests.cs b/src/Features/CSharpTest/ConvertProgram/ConvertToProgramMainRefactoringTests.cs index cce3f3a0e7b22..5acb5cd7531bc 100644 --- a/src/Features/CSharpTest/ConvertProgram/ConvertToProgramMainRefactoringTests.cs +++ b/src/Features/CSharpTest/ConvertProgram/ConvertToProgramMainRefactoringTests.cs @@ -20,17 +20,15 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertProgram; public sealed class ConvertToProgramMainRefactoringTests { [Fact] - public async Task TestNotOnFileWithNoGlobalStatements() - { - var code = @" -$$ -class C -{ -} -"; - await new VerifyCS.Test + public Task TestNotOnFileWithNoGlobalStatements() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + $$ + class C + { + } + """, LanguageVersion = LanguageVersion.CSharp10, TestState = { OutputKind = OutputKind.ConsoleApplication }, ExpectedDiagnostics = @@ -39,17 +37,14 @@ class C DiagnosticResult.CompilerError("CS5001"), } }.RunAsync(); - } [Fact] - public async Task TestNotOnEmptyFile() - { - var code = @" -$$ -"; - await new VerifyCS.Test + public Task TestNotOnEmptyFile() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + $$ + """, LanguageVersion = LanguageVersion.CSharp10, TestState = { OutputKind = OutputKind.ConsoleApplication }, ExpectedDiagnostics = @@ -58,60 +53,53 @@ public async Task TestNotOnEmptyFile() DiagnosticResult.CompilerError("CS5001"), } }.RunAsync(); - } [Fact] - public async Task TestConvertToProgramMainWithDefaultTopLevelStatementPreference() - { - // default preference is to prefer top level namespaces. As such, we only offer to convert to the alternative as a refactoring. - await new VerifyCS.Test + public Task TestConvertToProgramMainWithDefaultTopLevelStatementPreference() + => new VerifyCS.Test { - TestCode = @" -$$System.Console.WriteLine(0); -", - FixedCode = @" -internal class Program -{ - private static void Main(string[] args) - { - System.Console.WriteLine(0); - } -}", + TestCode = """ + $$System.Console.WriteLine(0); + """, + FixedCode = """ + internal class Program + { + private static void Main(string[] args) + { + System.Console.WriteLine(0); + } + } + """, LanguageVersion = LanguageVersion.CSharp10, TestState = { OutputKind = OutputKind.ConsoleApplication }, }.RunAsync(); - } [Fact] - public async Task TestNotOfferedInLibrary() - { - var code = @" -$${|CS8805:System.Console.WriteLine(0);|} -"; - await new VerifyCS.Test + public Task TestNotOfferedInLibrary() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + $${|CS8805:System.Console.WriteLine(0);|} + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task TestConvertToProgramMainWithTopLevelStatementPreferenceSuggestion() - { - // user actually prefers top level statements. As such, we only offer to convert to the alternative as a refactoring. - await new VerifyCS.Test + public Task TestConvertToProgramMainWithTopLevelStatementPreferenceSuggestion() + => new VerifyCS.Test { - TestCode = @" -$$System.Console.WriteLine(0); -", - FixedCode = @" -internal class Program -{ - private static void Main(string[] args) - { - System.Console.WriteLine(0); - } -}", + TestCode = """ + $$System.Console.WriteLine(0); + """, + FixedCode = """ + internal class Program + { + private static void Main(string[] args) + { + System.Console.WriteLine(0); + } + } + """, LanguageVersion = LanguageVersion.CSharp10, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = @@ -119,17 +107,14 @@ private static void Main(string[] args) { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion }, } }.RunAsync(); - } [Fact] - public async Task TestNoConvertToProgramMainWithProgramMainPreferenceSuggestion() - { - var code = @" -$$System.Console.WriteLine(0); -"; - await new VerifyCS.Test + public Task TestNoConvertToProgramMainWithProgramMainPreferenceSuggestion() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + $$System.Console.WriteLine(0); + """, LanguageVersion = LanguageVersion.CSharp10, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = @@ -137,17 +122,14 @@ public async Task TestNoConvertToProgramMainWithProgramMainPreferenceSuggestion( { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion }, } }.RunAsync(); - } [Fact] - public async Task TestNoConvertToProgramMainWithProgramMainPreferenceSilent() - { - var code = @" -$$System.Console.WriteLine(0); -"; - await new VerifyCS.Test + public Task TestNoConvertToProgramMainWithProgramMainPreferenceSilent() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + $$System.Console.WriteLine(0); + """, LanguageVersion = LanguageVersion.CSharp10, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = @@ -155,25 +137,23 @@ public async Task TestNoConvertToProgramMainWithProgramMainPreferenceSilent() { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Silent }, } }.RunAsync(); - } [Fact] - public async Task TestConvertToProgramMainWithProgramMainPreferenceSuppress() - { - // if the user has the analyzer suppressed, then we want to supply teh refactoring. - await new VerifyCS.Test + public Task TestConvertToProgramMainWithProgramMainPreferenceSuppress() + => new VerifyCS.Test { - TestCode = @" -$$System.Console.WriteLine(0); -", - FixedCode = @" -internal class Program -{ - private static void Main(string[] args) - { - System.Console.WriteLine(0); - } -}", + TestCode = """ + $$System.Console.WriteLine(0); + """, + FixedCode = """ + internal class Program + { + private static void Main(string[] args) + { + System.Console.WriteLine(0); + } + } + """, LanguageVersion = LanguageVersion.CSharp10, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = @@ -181,5 +161,4 @@ private static void Main(string[] args) { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.None }, } }.RunAsync(); - } } diff --git a/src/Features/CSharpTest/ConvertProgram/ConvertToTopLevelStatementsAnalyzerTests.cs b/src/Features/CSharpTest/ConvertProgram/ConvertToTopLevelStatementsAnalyzerTests.cs index 62de3d03c2417..79b7d29ea36fe 100644 --- a/src/Features/CSharpTest/ConvertProgram/ConvertToTopLevelStatementsAnalyzerTests.cs +++ b/src/Features/CSharpTest/ConvertProgram/ConvertToTopLevelStatementsAnalyzerTests.cs @@ -29,265 +29,272 @@ public static IEnumerable EndOfDocumentSequences } [Fact] - public async Task NotOfferedWhenUserPrefersProgramMain() - { - var code = @" -class Program -{ - static void Main(string[] args) - { - System.Console.WriteLine(0); - } -} -"; - - await new VerifyCS.Test + public Task NotOfferedWhenUserPrefersProgramMain() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + + class Program + { + static void Main(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false } }, }.RunAsync(); - } [Fact] - public async Task NotOfferedPriorToCSharp9() - { - var code = @" -class Program -{ - static void Main(string[] args) - { - System.Console.WriteLine(0); - } -} -"; - - await new VerifyCS.Test + public Task NotOfferedPriorToCSharp9() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + + class Program + { + static void Main(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, LanguageVersion = LanguageVersion.CSharp8, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true } }, }.RunAsync(); - } [Fact] - public async Task OfferedInCSharp9() - { - await new VerifyCS.Test + public Task OfferedInCSharp9() + => new VerifyCS.Test { - TestCode = @" -class Program -{ - {|IDE0210:static void Main(string[] args) - { - System.Console.WriteLine(0); - }|} -} -", - FixedCode = @" -System.Console.WriteLine(0); -", + TestCode = """ + + class Program + { + {|IDE0210:static void Main(string[] args) + { + System.Console.WriteLine(0); + }|} + } + + """, + FixedCode = """ + + System.Console.WriteLine(0); + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true } }, }.RunAsync(); - } [Fact] - public async Task TestFileHeader1() - { - await new VerifyCS.Test + public Task TestFileHeader1() + => new VerifyCS.Test { - TestCode = @"// This is a file header + TestCode = """ + // This is a file header -class Program -{ - {|IDE0210:static void Main(string[] args) - { - System.Console.WriteLine(0); - }|} -} -", - FixedCode = @"// This is a file header + class Program + { + {|IDE0210:static void Main(string[] args) + { + System.Console.WriteLine(0); + }|} + } -System.Console.WriteLine(0); -", + """, + FixedCode = """ + // This is a file header + + System.Console.WriteLine(0); + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true } }, }.RunAsync(); - } [Fact] - public async Task TestFileHeader2() - { - await new VerifyCS.Test + public Task TestFileHeader2() + => new VerifyCS.Test { - TestCode = @"// This is a file header + TestCode = """ + // This is a file header + + namespace N + { + class Program + { + {|IDE0210:static void Main(string[] args) + { + System.Console.WriteLine(0); + }|} + } + } + + """, + FixedCode = """ + // This is a file header -namespace N -{ - class Program - { - {|IDE0210:static void Main(string[] args) - { System.Console.WriteLine(0); - }|} - } -} -", - FixedCode = @"// This is a file header -System.Console.WriteLine(0); -", + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true } }, }.RunAsync(); - } [Fact] - public async Task TestFileHeader3() - { - await new VerifyCS.Test + public Task TestFileHeader3() + => new VerifyCS.Test { - TestCode = @"// This is a file header + TestCode = """ + // This is a file header -namespace N; + namespace N; -class Program -{ - {|IDE0210:static void Main(string[] args) - { - System.Console.WriteLine(0); - }|} -} -", - FixedCode = @"// This is a file header + class Program + { + {|IDE0210:static void Main(string[] args) + { + System.Console.WriteLine(0); + }|} + } + + """, + FixedCode = """ + // This is a file header -System.Console.WriteLine(0); -", + System.Console.WriteLine(0); + + """, LanguageVersion = LanguageVersion.CSharp10, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true } }, }.RunAsync(); - } [Fact] - public async Task TestFileHeader4() - { - await new VerifyCS.Test + public Task TestFileHeader4() + => new VerifyCS.Test { - TestCode = @"// This is a file header -using System; + TestCode = """ + // This is a file header + using System; -namespace N; + namespace N; -class Program -{ - {|IDE0210:static void Main(string[] args) - { - System.Console.WriteLine(0); - }|} -} -", - FixedCode = @"// This is a file header -using System; + class Program + { + {|IDE0210:static void Main(string[] args) + { + System.Console.WriteLine(0); + }|} + } + + """, + FixedCode = """ + // This is a file header + using System; -System.Console.WriteLine(0); -", + System.Console.WriteLine(0); + + """, LanguageVersion = LanguageVersion.CSharp10, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true } }, }.RunAsync(); - } [Fact] - public async Task OfferedWithoutArgs() - { - await new VerifyCS.Test + public Task OfferedWithoutArgs() + => new VerifyCS.Test { - TestCode = @" -class Program -{ - {|IDE0210:static void Main() - { - System.Console.WriteLine(0); - }|} -} -", - FixedCode = @" -System.Console.WriteLine(0); -", + TestCode = """ + + class Program + { + {|IDE0210:static void Main() + { + System.Console.WriteLine(0); + }|} + } + + """, + FixedCode = """ + + System.Console.WriteLine(0); + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true } }, }.RunAsync(); - } [Fact] - public async Task NotOfferedInLibrary() - { - var code = @" -class Program -{ - static void Main() - { - System.Console.WriteLine(0); - } -} -"; - - await new VerifyCS.Test + public Task NotOfferedInLibrary() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + + class Program + { + static void Main() + { + System.Console.WriteLine(0); + } + } + + """, LanguageVersion = LanguageVersion.CSharp9, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true } }, }.RunAsync(); - } [Fact] - public async Task OfferedOnNameWhenNotHidden() - { - await new VerifyCS.Test + public Task OfferedOnNameWhenNotHidden() + => new VerifyCS.Test { - TestCode = @" -class Program -{ - static void {|IDE0210:Main|}(string[] args) - { - System.Console.WriteLine(0); - } -} -", - FixedCode = @" -System.Console.WriteLine(0); -", + TestCode = """ + + class Program + { + static void {|IDE0210:Main|}(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, + FixedCode = """ + + System.Console.WriteLine(0); + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task NotOnNonStaticMain() - { - var code = @" -class Program -{ - void Main(string[] args) - { - System.Console.WriteLine(0); - } -} -"; - - await new VerifyCS.Test + public Task NotOnNonStaticMain() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + + class Program + { + void Main(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, @@ -297,24 +304,22 @@ void Main(string[] args) DiagnosticResult.CompilerError("CS5001"), } }.RunAsync(); - } [Fact] - public async Task NotOnGenericMain() - { - var code = @" -class Program -{ - static void Main(string[] args) - { - System.Console.WriteLine(0); - } -} -"; - - await new VerifyCS.Test + public Task NotOnGenericMain() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + + class Program + { + static void Main(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, @@ -324,24 +329,22 @@ static void Main(string[] args) DiagnosticResult.CompilerError("CS5001"), } }.RunAsync(); - } [Fact] - public async Task NotOnRandomMethod() - { - var code = @" -class Program -{ - static void Main1(string[] args) - { - System.Console.WriteLine(0); - } -} -"; - - await new VerifyCS.Test + public Task NotOnRandomMethod() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + + class Program + { + static void Main1(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, @@ -351,1208 +354,1212 @@ static void Main1(string[] args) DiagnosticResult.CompilerError("CS5001"), } }.RunAsync(); - } [Fact] - public async Task NotOnMethodWithNoBody() - { - var code = @" -class Program -{ - static void {|CS0501:Main|}(string[] args); -} -"; - - await new VerifyCS.Test + public Task NotOnMethodWithNoBody() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + + class Program + { + static void {|CS0501:Main|}(string[] args); + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task NotOnExpressionBody() - { - // we could choose to support this in the future. It's not supported for now for simplicity. - var code = @" -class Program -{ - static void Main(string[] args) - => System.Console.WriteLine(0); -} -"; - - await new VerifyCS.Test + public Task NotOnExpressionBody() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + + class Program + { + static void Main(string[] args) + => System.Console.WriteLine(0); + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task NotOnTypeWithInheritance1() - { - var code = @" -class Program : System.Exception -{ - static void Main(string[] args) - { - System.Console.WriteLine(0); - } -} -"; - - await new VerifyCS.Test + public Task NotOnTypeWithInheritance1() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + + class Program : System.Exception + { + static void Main(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task NotOnTypeWithInheritance2() - { - var code = @" -class Program : {|CS0535:System.IComparable|} -{ - static void Main(string[] args) - { - System.Console.WriteLine(0); - } -} -"; - - await new VerifyCS.Test + public Task NotOnTypeWithInheritance2() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + + class Program : {|CS0535:System.IComparable|} + { + static void Main(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task NotOnMultiPartType() - { - var code = @" -partial class Program -{ - static void Main(string[] args) - { - System.Console.WriteLine(0); - } -} + public Task NotOnMultiPartType() + => new VerifyCS.Test + { + TestCode = """ -partial class Program -{ -} -"; + partial class Program + { + static void Main(string[] args) + { + System.Console.WriteLine(0); + } + } - await new VerifyCS.Test - { - TestCode = code, + partial class Program + { + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task NotOnPublicType() - { - var code = @" -public class Program -{ - static void Main(string[] args) - { - System.Console.WriteLine(0); - } -} -"; - - await new VerifyCS.Test + public Task NotOnPublicType() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + + public class Program + { + static void Main(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task NotOnTypeWithAttribute() - { - var code = @" -[System.CLSCompliant(true)] -class Program -{ - static void Main(string[] args) - { - System.Console.WriteLine(0); - } -} -"; - - await new VerifyCS.Test + public Task NotOnTypeWithAttribute() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + + [System.CLSCompliant(true)] + class Program + { + static void Main(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task NotOnTypeWithDocComment() - { - var code = @" -/// -class Program -{ - static void Main(string[] args) - { - System.Console.WriteLine(0); - } -} -"; - - await new VerifyCS.Test + public Task NotOnTypeWithDocComment() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + + /// + class Program + { + static void Main(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task NotOnTypeWithNormalComment() - { - await new VerifyCS.Test + public Task NotOnTypeWithNormalComment() + => new VerifyCS.Test { - TestCode = @" -// -class Program -{ - static void {|IDE0210:Main|}(string[] args) - { - System.Console.WriteLine(0); - } -} -", - FixedCode = @" -// -System.Console.WriteLine(0); -", + TestCode = """ + + // + class Program + { + static void {|IDE0210:Main|}(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, + FixedCode = """ + + // + System.Console.WriteLine(0); + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task NotWithMemberWithAttributes() - { - var code = @" -class Program -{ - [System.CLSCompliant(true)] - static int x; + public Task NotWithMemberWithAttributes() + => new VerifyCS.Test + { + TestCode = """ - static void Main(string[] args) - { - System.Console.WriteLine(0); - } -} -"; + class Program + { + [System.CLSCompliant(true)] + static int x; - await new VerifyCS.Test - { - TestCode = code, + static void Main(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task NotWithMethodWithAttribute1() - { - var code = @" -class Program -{ - [System.CLSCompliant(true)] - static void M() { } + public Task NotWithMethodWithAttribute1() + => new VerifyCS.Test + { + TestCode = """ - static void Main(string[] args) - { - System.Console.WriteLine(0); - } -} -"; + class Program + { + [System.CLSCompliant(true)] + static void M() { } - await new VerifyCS.Test - { - TestCode = code, + static void Main(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task NotWithMethodWithAttribute2() - { - var code = @" -class Program -{ - static void M() { } + public Task NotWithMethodWithAttribute2() + => new VerifyCS.Test + { + TestCode = """ - [System.CLSCompliant(true)] - static void Main(string[] args) - { - System.Console.WriteLine(0); - } -} -"; + class Program + { + static void M() { } - await new VerifyCS.Test - { - TestCode = code, + [System.CLSCompliant(true)] + static void Main(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task NotWithMemberWithDocComment() - { - var code = @" -class Program -{ - /// - static int x; + public Task NotWithMemberWithDocComment() + => new VerifyCS.Test + { + TestCode = """ - static void Main(string[] args) - { - System.Console.WriteLine(0); - } -} -"; + class Program + { + /// + static int x; - await new VerifyCS.Test - { - TestCode = code, + static void Main(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task NotWithNonPrivateMember() - { - var code = @" -class Program -{ - public static int x; + public Task NotWithNonPrivateMember() + => new VerifyCS.Test + { + TestCode = """ - static void Main(string[] args) - { - System.Console.WriteLine(0); - } -} -"; + class Program + { + public static int x; - await new VerifyCS.Test - { - TestCode = code, + static void Main(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task NotWithNonStaticMember() - { - var code = @" -class Program -{ - int x; + public Task NotWithNonStaticMember() + => new VerifyCS.Test + { + TestCode = """ - static void Main(string[] args) - { - System.Console.WriteLine(0); - } -} -"; + class Program + { + int x; - await new VerifyCS.Test - { - TestCode = code, + static void Main(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task NotWithStaticConstructor() - { - var code = @" -class Program -{ - static Program() - { - } + public Task NotWithStaticConstructor() + => new VerifyCS.Test + { + TestCode = """ - static void Main(string[] args) - { - System.Console.WriteLine(0); - } -} -"; + class Program + { + static Program() + { + } + + static void Main(string[] args) + { + System.Console.WriteLine(0); + } + } - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task NotWithInstanceConstructor() - { - var code = @" -class Program -{ - private Program() - { - } + public Task NotWithInstanceConstructor() + => new VerifyCS.Test + { + TestCode = """ - static void Main(string[] args) - { - System.Console.WriteLine(0); - } -} -"; + class Program + { + private Program() + { + } + + static void Main(string[] args) + { + System.Console.WriteLine(0); + } + } - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task NotWithProperty() - { - var code = @" -class Program -{ - private int X { get; } + public Task NotWithProperty() + => new VerifyCS.Test + { + TestCode = """ - static void Main(string[] args) - { - System.Console.WriteLine(0); - } -} -"; + class Program + { + private int X { get; } - await new VerifyCS.Test - { - TestCode = code, + static void Main(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task NotWithEvent() - { - var code = @" -class Program -{ - private event System.Action X; + public Task NotWithEvent() + => new VerifyCS.Test + { + TestCode = """ - static void Main(string[] args) - { - System.Console.WriteLine(0); - } -} -"; + class Program + { + private event System.Action X; - await new VerifyCS.Test - { - TestCode = code, + static void Main(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task NotWithOperator() - { - var code = @" -class Program -{ - public static Program operator+(Program p1, Program p2) => null; + public Task NotWithOperator() + => new VerifyCS.Test + { + TestCode = """ - static void Main(string[] args) - { - System.Console.WriteLine(0); - } -} -"; + class Program + { + public static Program operator+(Program p1, Program p2) => null; - await new VerifyCS.Test - { - TestCode = code, + static void Main(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task NotWithMethodWithWrongArgsName() - { - var code = @" -class Program -{ - static void Main(string[] args1) - { - System.Console.WriteLine(0); - } -} -"; - - await new VerifyCS.Test + public Task NotWithMethodWithWrongArgsName() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + + class Program + { + static void Main(string[] args1) + { + System.Console.WriteLine(0); + } + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestFieldWithNoAccessibility() - { - await new VerifyCS.Test + public Task TestFieldWithNoAccessibility() + => new VerifyCS.Test { - TestCode = @" -class Program -{ - static int x; + TestCode = """ - static void {|IDE0210:Main|}(string[] args) - { - System.Console.WriteLine(0); - } -} -", - FixedCode = @" -int x = 0; + class Program + { + static int x; + + static void {|IDE0210:Main|}(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, + FixedCode = """ -System.Console.WriteLine(0); -", + int x = 0; + + System.Console.WriteLine(0); + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestFollowingField() - { - await new VerifyCS.Test + public Task TestFollowingField() + => new VerifyCS.Test { - TestCode = @" -class Program -{ - static void {|IDE0210:Main|}(string[] args) - { - System.Console.WriteLine(0); - } + TestCode = """ - static int x; -} -", - FixedCode = @" + class Program + { + static void {|IDE0210:Main|}(string[] args) + { + System.Console.WriteLine(0); + } + + static int x; + } -int x = 0; -System.Console.WriteLine(0); -", + """, + FixedCode = """ + + + int x = 0; + System.Console.WriteLine(0); + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestFieldWithPrivateAccessibility() - { - await new VerifyCS.Test + public Task TestFieldWithPrivateAccessibility() + => new VerifyCS.Test { - TestCode = @" -class Program -{ - private static int x; + TestCode = """ - static void {|IDE0210:Main|}(string[] args) - { - System.Console.WriteLine(0); - } -} -", - FixedCode = @" -int x = 0; + class Program + { + private static int x; -System.Console.WriteLine(0); -", + static void {|IDE0210:Main|}(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, + FixedCode = """ + + int x = 0; + + System.Console.WriteLine(0); + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestFieldWithMultipleDeclarators() - { - await new VerifyCS.Test + public Task TestFieldWithMultipleDeclarators() + => new VerifyCS.Test { - TestCode = @" -class Program -{ - private static int x, y; + TestCode = """ - static void {|IDE0210:Main|}(string[] args) - { - System.Console.WriteLine(0); - } -} -", - FixedCode = @" -int x = 0, y = 0; + class Program + { + private static int x, y; + + static void {|IDE0210:Main|}(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, + FixedCode = """ -System.Console.WriteLine(0); -", + int x = 0, y = 0; + + System.Console.WriteLine(0); + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestFieldWithInitializer() - { - await new VerifyCS.Test + public Task TestFieldWithInitializer() + => new VerifyCS.Test { - TestCode = @" -class Program -{ - private static int x = 1; + TestCode = """ - static void {|IDE0210:Main|}(string[] args) - { - System.Console.WriteLine(0); - } -} -", - FixedCode = @" -int x = 1; + class Program + { + private static int x = 1; + + static void {|IDE0210:Main|}(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, + FixedCode = """ -System.Console.WriteLine(0); -", + int x = 1; + + System.Console.WriteLine(0); + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestReferenceField() - { - await new VerifyCS.Test + public Task TestReferenceField() + => new VerifyCS.Test { - TestCode = @" -class Program -{ - private static string x; + TestCode = """ - static void {|IDE0210:Main|}(string[] args) - { - System.Console.WriteLine(0); - } -} -", - FixedCode = @" -string x = null; + class Program + { + private static string x; + + static void {|IDE0210:Main|}(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, + FixedCode = """ + + string x = null; -System.Console.WriteLine(0); -", + System.Console.WriteLine(0); + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestBooleanField() - { - await new VerifyCS.Test + public Task TestBooleanField() + => new VerifyCS.Test { - TestCode = @" -class Program -{ - private static bool x; + TestCode = """ - static void {|IDE0210:Main|}(string[] args) - { - System.Console.WriteLine(0); - } -} -", - FixedCode = @" -bool x = false; + class Program + { + private static bool x; + + static void {|IDE0210:Main|}(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, + FixedCode = """ + + bool x = false; + + System.Console.WriteLine(0); -System.Console.WriteLine(0); -", + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestStructField() - { - await new VerifyCS.Test + public Task TestStructField() + => new VerifyCS.Test { - TestCode = @" -class Program -{ - private static System.DateTime x; + TestCode = """ - static void {|IDE0210:Main|}(string[] args) - { - System.Console.WriteLine(0); - } -} -", - FixedCode = @" -System.DateTime x = default; + class Program + { + private static System.DateTime x; -System.Console.WriteLine(0); -", + static void {|IDE0210:Main|}(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, + FixedCode = """ + + System.DateTime x = default; + + System.Console.WriteLine(0); + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestFieldWithComments() - { - await new VerifyCS.Test + public Task TestFieldWithComments() + => new VerifyCS.Test { - TestCode = @" -class Program -{ - // Leading - private static int x = 0; // Trailing + TestCode = """ - static void {|IDE0210:Main|}(string[] args) - { - System.Console.WriteLine(0); - } -} -", - FixedCode = @" -// Leading -int x = 0; // Trailing + class Program + { + // Leading + private static int x = 0; // Trailing + + static void {|IDE0210:Main|}(string[] args) + { + System.Console.WriteLine(0); + } + } + + """, + FixedCode = """ + + // Leading + int x = 0; // Trailing + + System.Console.WriteLine(0); -System.Console.WriteLine(0); -", + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestEmptyMethod() - { - await new VerifyCS.Test + public Task TestEmptyMethod() + => new VerifyCS.Test { - TestCode = @" -class Program -{ - private static int x = 0; + TestCode = """ - static void {|IDE0210:Main|}(string[] args) - { - } -} -", - FixedCode = @" -int x = 0; -", + class Program + { + private static int x = 0; + + static void {|IDE0210:Main|}(string[] args) + { + } + } + + """, + FixedCode = """ + + int x = 0; + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestMultipleStatements() - { - await new VerifyCS.Test + public Task TestMultipleStatements() + => new VerifyCS.Test { - TestCode = @" -class Program -{ - private static int x = 0; + TestCode = """ - static void {|IDE0210:Main|}(string[] args) - { - System.Console.WriteLine(args); - return; - } -} -", - FixedCode = @" -int x = 0; + class Program + { + private static int x = 0; + + static void {|IDE0210:Main|}(string[] args) + { + System.Console.WriteLine(args); + return; + } + } + + """, + FixedCode = """ -System.Console.WriteLine(args); -return; -", + int x = 0; + + System.Console.WriteLine(args); + return; + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestOtherMethodBecomesLocalFunction() - { - await new VerifyCS.Test + public Task TestOtherMethodBecomesLocalFunction() + => new VerifyCS.Test { - TestCode = @" -class Program -{ - private static int x = 0; + TestCode = """ - static void OtherMethod() - { - return; - } + class Program + { + private static int x = 0; - static void {|IDE0210:Main|}(string[] args) - { - System.Console.WriteLine(args); - } -} -", - FixedCode = @" -int x = 0; + static void OtherMethod() + { + return; + } -void OtherMethod() -{ - return; -} + static void {|IDE0210:Main|}(string[] args) + { + System.Console.WriteLine(args); + } + } + + """, + FixedCode = """ -System.Console.WriteLine(args); -", + int x = 0; + + void OtherMethod() + { + return; + } + + System.Console.WriteLine(args); + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestWithUnsafeMethod() - { - await new VerifyCS.Test + public Task TestWithUnsafeMethod() + => new VerifyCS.Test { - TestCode = @" -class Program -{ - private static int x = 0; + TestCode = """ - unsafe static void OtherMethod() - { - return; - } + class Program + { + private static int x = 0; - static void {|IDE0210:Main|}(string[] args) - { - System.Console.WriteLine(args); - } -} -", - FixedCode = @" -int x = 0; + unsafe static void OtherMethod() + { + return; + } -unsafe void OtherMethod() -{ - return; -} + static void {|IDE0210:Main|}(string[] args) + { + System.Console.WriteLine(args); + } + } -System.Console.WriteLine(args); -", + """, + FixedCode = """ + + int x = 0; + + unsafe void OtherMethod() + { + return; + } + + System.Console.WriteLine(args); + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestOtherComplexMethodBecomesLocalFunction() - { - await new VerifyCS.Test + public Task TestOtherComplexMethodBecomesLocalFunction() + => new VerifyCS.Test { - TestCode = @" -using System.Threading.Tasks; + TestCode = """ -class Program -{ - private static int x = 0; + using System.Threading.Tasks; - static async Task OtherMethod(T param) where T : struct - { - return; - } + class Program + { + private static int x = 0; - static void {|IDE0210:Main|}(string[] args) - { - System.Console.WriteLine(args); - } -} -", - FixedCode = @" -using System.Threading.Tasks; + static async Task OtherMethod(T param) where T : struct + { + return; + } -int x = 0; + static void {|IDE0210:Main|}(string[] args) + { + System.Console.WriteLine(args); + } + } -async Task OtherMethod(T param) where T : struct -{ - return; -} + """, + FixedCode = """ + + using System.Threading.Tasks; + + int x = 0; -System.Console.WriteLine(args); -", + async Task OtherMethod(T param) where T : struct + { + return; + } + + System.Console.WriteLine(args); + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestAwaitExpression() - { - await new VerifyCS.Test + public Task TestAwaitExpression() + => new VerifyCS.Test { - TestCode = @" -using System.Threading.Tasks; + TestCode = """ -class Program -{ - static async Task {|IDE0210:Main|}(string[] args) - { - await Task.CompletedTask; - } -} -", - FixedCode = @" -using System.Threading.Tasks; + using System.Threading.Tasks; + + class Program + { + static async Task {|IDE0210:Main|}(string[] args) + { + await Task.CompletedTask; + } + } -await Task.CompletedTask; -", + """, + FixedCode = """ + + using System.Threading.Tasks; + + await Task.CompletedTask; + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestInNamespaceWithOtherType() - { - await new VerifyCS.Test + public Task TestInNamespaceWithOtherType() + => new VerifyCS.Test { - TestCode = @" -using System.Threading.Tasks; + TestCode = """ -namespace X.Y -{ - class Program - { - static async Task {|IDE0210:Main|}(string[] args) - { - await Task.CompletedTask; - } - } + using System.Threading.Tasks; - class Other - { - } -} -", - FixedCode = @" -using System.Threading.Tasks; + namespace X.Y + { + class Program + { + static async Task {|IDE0210:Main|}(string[] args) + { + await Task.CompletedTask; + } + } + + class Other + { + } + } -await Task.CompletedTask; + """, + FixedCode = """ -namespace X.Y -{ - class Other - { - } -} -", + using System.Threading.Tasks; + + await Task.CompletedTask; + + namespace X.Y + { + class Other + { + } + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Theory] [MemberData(nameof(EndOfDocumentSequences))] - public async Task TestInTopLevelNamespaceWithOtherType(string endOfDocumentSequence) - { - await new VerifyCS.Test + public Task TestInTopLevelNamespaceWithOtherType(string endOfDocumentSequence) + => new VerifyCS.Test { - TestCode = $@" -using System.Threading.Tasks; + TestCode = $$""" -namespace X.Y; + using System.Threading.Tasks; -class Program -{{ - static async Task {{|IDE0210:Main|}}(string[] args) - {{ - await Task.CompletedTask; - }} -}} + namespace X.Y; -class Other -{{ -}}{endOfDocumentSequence}", - FixedCode = $@" -using System.Threading.Tasks; + class Program + { + static async Task {|IDE0210:Main|}(string[] args) + { + await Task.CompletedTask; + } + } + + class Other + { + }{{endOfDocumentSequence}} + """, + FixedCode = $$""" + + using System.Threading.Tasks; -await Task.CompletedTask; + await Task.CompletedTask; -namespace X.Y -{{ - class Other - {{ - }} -}}{endOfDocumentSequence}", + namespace X.Y + { + class Other + { + } + }{{endOfDocumentSequence}} + """, LanguageVersion = LanguageVersion.CSharp10, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestInNamespaceWithOtherTypeThatIsReferenced() - { - await new VerifyCS.Test + public Task TestInNamespaceWithOtherTypeThatIsReferenced() + => new VerifyCS.Test { - TestCode = @" -using System.Threading.Tasks; + TestCode = """ -namespace X.Y -{ - class Program - { - static void {|IDE0210:Main|}(string[] args) - { - System.Console.WriteLine(typeof(Other)); - } - } + using System.Threading.Tasks; - class Other - { - } -} -", - FixedCode = @" -using System.Threading.Tasks; -using X.Y; + namespace X.Y + { + class Program + { + static void {|IDE0210:Main|}(string[] args) + { + System.Console.WriteLine(typeof(Other)); + } + } + + class Other + { + } + } -System.Console.WriteLine(typeof(Other)); + """, + FixedCode = """ -namespace X.Y -{ - class Other - { - } -} -", + using System.Threading.Tasks; + using X.Y; + + System.Console.WriteLine(typeof(Other)); + + namespace X.Y + { + class Other + { + } + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Theory] [MemberData(nameof(EndOfDocumentSequences))] - public async Task TestInTopLevelNamespaceWithOtherTypeThatIsReferenced(string endOfDocumentSequence) - { - await new VerifyCS.Test + public Task TestInTopLevelNamespaceWithOtherTypeThatIsReferenced(string endOfDocumentSequence) + => new VerifyCS.Test { - TestCode = $@" -using System.Threading.Tasks; + TestCode = $$""" -namespace X.Y; + using System.Threading.Tasks; -class Program -{{ - static void {{|IDE0210:Main|}}(string[] args) - {{ - System.Console.WriteLine(typeof(Other)); - }} -}} + namespace X.Y; -class Other -{{ -}}{endOfDocumentSequence}", - FixedCode = $@" -using System.Threading.Tasks; -using X.Y; + class Program + { + static void {|IDE0210:Main|}(string[] args) + { + System.Console.WriteLine(typeof(Other)); + } + } + + class Other + { + }{{endOfDocumentSequence}} + """, + FixedCode = $$""" -System.Console.WriteLine(typeof(Other)); + using System.Threading.Tasks; + using X.Y; -namespace X.Y -{{ - class Other - {{ - }} -}}{endOfDocumentSequence}", + System.Console.WriteLine(typeof(Other)); + + namespace X.Y + { + class Other + { + } + }{{endOfDocumentSequence}} + """, LanguageVersion = LanguageVersion.CSharp10, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestInNamespaceWithNoOtherTypes() - { - await new VerifyCS.Test + public Task TestInNamespaceWithNoOtherTypes() + => new VerifyCS.Test { - TestCode = @" -using System.Threading.Tasks; + TestCode = """ + + using System.Threading.Tasks; + + namespace X.Y + { + class Program + { + static void {|IDE0210:Main|}(string[] args) + { + System.Console.WriteLine(); + } + } + } + + """, + FixedCode = """ + + using System.Threading.Tasks; -namespace X.Y -{ - class Program - { - static void {|IDE0210:Main|}(string[] args) - { System.Console.WriteLine(); - } - } -} -", - FixedCode = @" -using System.Threading.Tasks; -System.Console.WriteLine(); -", + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestInTopLevelNamespaceWithNoOtherTypes() - { - await new VerifyCS.Test + public Task TestInTopLevelNamespaceWithNoOtherTypes() + => new VerifyCS.Test { - TestCode = @" -using System.Threading.Tasks; + TestCode = """ -namespace X.Y; + using System.Threading.Tasks; -class Program -{ - static void {|IDE0210:Main|}(string[] args) - { - System.Console.WriteLine(); - } -} -", - FixedCode = @" -using System.Threading.Tasks; + namespace X.Y; + + class Program + { + static void {|IDE0210:Main|}(string[] args) + { + System.Console.WriteLine(); + } + } + + """, + FixedCode = """ -System.Console.WriteLine(); -", + using System.Threading.Tasks; + + System.Console.WriteLine(); + + """, LanguageVersion = LanguageVersion.CSharp10, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } [Fact] - public async Task TestInSingletonNamespaceWithOtherTypeThatIsReferenced() - { - await new VerifyCS.Test + public Task TestInSingletonNamespaceWithOtherTypeThatIsReferenced() + => new VerifyCS.Test { - TestCode = @" -using System.Threading.Tasks; + TestCode = """ -namespace X.Y -{ - class Program - { - static void {|IDE0210:Main|}(string[] args) - { - System.Console.WriteLine(typeof(Other)); - } - } -} + using System.Threading.Tasks; -namespace X -{ - class Other - { - } -} -", - FixedCode = @" -using System.Threading.Tasks; -using X; + namespace X.Y + { + class Program + { + static void {|IDE0210:Main|}(string[] args) + { + System.Console.WriteLine(typeof(Other)); + } + } + } -System.Console.WriteLine(typeof(Other)); + namespace X + { + class Other + { + } + } -namespace X -{ - class Other - { - } -} -", + """, + FixedCode = """ + + using System.Threading.Tasks; + using X; + + System.Console.WriteLine(typeof(Other)); + + namespace X + { + class Other + { + } + } + + """, LanguageVersion = LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion } }, }.RunAsync(); - } } diff --git a/src/Features/CSharpTest/ConvertProgram/ConvertToTopLevelStatementsRefactoringTests.cs b/src/Features/CSharpTest/ConvertProgram/ConvertToTopLevelStatementsRefactoringTests.cs index c40f1be9fa6b5..93bcad2e52056 100644 --- a/src/Features/CSharpTest/ConvertProgram/ConvertToTopLevelStatementsRefactoringTests.cs +++ b/src/Features/CSharpTest/ConvertProgram/ConvertToTopLevelStatementsRefactoringTests.cs @@ -10,6 +10,7 @@ using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; +using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertProgram; @@ -20,17 +21,12 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertProgram; public sealed class ConvertToTopLevelStatementsRefactoringTests { [Fact] - public async Task TestNotOnEmptyFile() - { - var code = @" -$$ -"; - - // default preference is to prefer top level namespaces. As such, we should not have the refactoring here - // since the analyzer will take over. - await new VerifyCS.Test + public Task TestNotOnEmptyFile() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + $$ + """, LanguageVersion = LanguageVersion.CSharp10, TestState = { OutputKind = OutputKind.ConsoleApplication }, ExpectedDiagnostics = @@ -39,48 +35,41 @@ public async Task TestNotOnEmptyFile() DiagnosticResult.CompilerError("CS5001"), } }.RunAsync(); - } [Fact] - public async Task TestConvertToTopLevelStatementsWithDefaultTopLevelStatementPreference() - { - var code = @" -class Program -{ - static void $$Main(string[] args) - { - System.Console.WriteLine(args[0]); - } -}"; - - // default preference is to prefer top level namespaces. As such, we should not have the refactoring here - // since the analyzer will take over. - await new VerifyCS.Test + public Task TestConvertToTopLevelStatementsWithDefaultTopLevelStatementPreference() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + class Program + { + static void $$Main(string[] args) + { + System.Console.WriteLine(args[0]); + } + } + """, LanguageVersion = LanguageVersion.CSharp10, TestState = { OutputKind = OutputKind.ConsoleApplication }, }.RunAsync(); - } [Fact] - public async Task TestConvertToTopLevelStatementsWithProgramMainPreferenceSuggestion() - { - // user actually prefers Program.Main. As such, we only offer to convert to the alternative as a refactoring. - await new VerifyCS.Test + public Task TestConvertToTopLevelStatementsWithProgramMainPreferenceSuggestion() + => new VerifyCS.Test { - TestCode = @" -class Program -{ - static void $$Main(string[] args) - { - System.Console.WriteLine(args[0]); - } -} -", - FixedCode = @" -System.Console.WriteLine(args[0]); -", + TestCode = """ + class Program + { + static void $$Main(string[] args) + { + System.Console.WriteLine(args[0]); + } + } + """, + FixedCode = """ + System.Console.WriteLine(args[0]); + + """, LanguageVersion = LanguageVersion.CSharp10, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = @@ -88,48 +77,40 @@ class Program { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion }, } }.RunAsync(); - } [Fact] - public async Task TestNotOfferedInLibrary() - { - var code = @" -class Program -{ - static void $$Main(string[] args) - { - System.Console.WriteLine(args[0]); - } -} -"; - - await new VerifyCS.Test + public Task TestNotOfferedInLibrary() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + class Program + { + static void $$Main(string[] args) + { + System.Console.WriteLine(args[0]); + } + } + """, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion }, } }.RunAsync(); - } [Fact] - public async Task TestNotWithNonViableType() - { - var code = @" -class Program -{ - void $$Main(string[] args) - { - System.Console.WriteLine(args[0]); - } -} -"; - - await new VerifyCS.Test + public Task TestNotWithNonViableType() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + class Program + { + void $$Main(string[] args) + { + System.Console.WriteLine(args[0]); + } + } + """, LanguageVersion = LanguageVersion.CSharp10, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = @@ -142,25 +123,20 @@ class Program DiagnosticResult.CompilerError("CS5001"), } }.RunAsync(); - } [Fact] - public async Task TestNoConvertToTopLevelStatementsWithProgramMainPreferenceSuggestionBeforeCSharp9() - { - var code = @" -class Program -{ - static void $$Main(string[] args) - { - System.Console.WriteLine(args[0]); - } -} -"; - - // user actually prefers Program.Main. As such, we only offer to convert to the alternative as a refactoring. - await new VerifyCS.Test + public Task TestNoConvertToTopLevelStatementsWithProgramMainPreferenceSuggestionBeforeCSharp9() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + class Program + { + static void $$Main(string[] args) + { + System.Console.WriteLine(args[0]); + } + } + """, LanguageVersion = LanguageVersion.CSharp8, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = @@ -168,23 +144,20 @@ class Program { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion }, } }.RunAsync(); - } [Fact] - public async Task TestNoConvertToTopLevelStatementsWithTopLevelStatementsPreferenceSuggestion() - { - var code = @" -class Program -{ - static void $$Main(string[] args) - { - System.Console.WriteLine(args[0]); - } -} -"; - await new VerifyCS.Test + public Task TestNoConvertToTopLevelStatementsWithTopLevelStatementsPreferenceSuggestion() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + class Program + { + static void $$Main(string[] args) + { + System.Console.WriteLine(args[0]); + } + } + """, LanguageVersion = LanguageVersion.CSharp10, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = @@ -192,23 +165,20 @@ class Program { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Suggestion }, } }.RunAsync(); - } [Fact] - public async Task TestNoConvertToTopLevelStatementsWithTopLevelStatementsPreferenceSilent() - { - var code = @" -class Program -{ - static void $$Main(string[] args) - { - System.Console.WriteLine(args[0]); - } -} -"; - await new VerifyCS.Test + public Task TestNoConvertToTopLevelStatementsWithTopLevelStatementsPreferenceSilent() + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + class Program + { + static void $$Main(string[] args) + { + System.Console.WriteLine(args[0]); + } + } + """, LanguageVersion = LanguageVersion.CSharp10, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = @@ -216,26 +186,24 @@ class Program { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.Silent }, } }.RunAsync(); - } [Fact] - public async Task TestConvertToTopLevelStatementWithTopLevelStatementPreferenceSuppress() - { - // if the user has the analyzer suppressed, then we want to supply teh refactoring. - await new VerifyCS.Test + public Task TestConvertToTopLevelStatementWithTopLevelStatementPreferenceSuppress() + => new VerifyCS.Test { - TestCode = @" -internal class Program -{ - private static void $$Main(string[] args) - { - System.Console.WriteLine(0); - } -} -", - FixedCode = @" -System.Console.WriteLine(0); -", + TestCode = """ + internal class Program + { + private static void $$Main(string[] args) + { + System.Console.WriteLine(0); + } + } + """, + FixedCode = """ + System.Console.WriteLine(0); + + """, LanguageVersion = LanguageVersion.CSharp10, TestState = { OutputKind = OutputKind.ConsoleApplication }, Options = @@ -243,5 +211,175 @@ internal class Program { CSharpCodeStyleOptions.PreferTopLevelStatements, true, NotificationOption2.None }, } }.RunAsync(); - } + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78002")] + public Task TestPreserveStatementDirectives1() + => new VerifyCS.Test + { + TestCode = """ + using System; + + class Program + { + static void $$Main(string[] args) + { + #if true + Console.WriteLine("true"); + #else + Console.WriteLine("false"); + #endif + } + } + """, + FixedCode = """ + using System; + + #if true + Console.WriteLine("true"); + #else + Console.WriteLine("false"); + #endif + + """, + LanguageVersion = LanguageVersion.CSharp10, + TestState = { OutputKind = OutputKind.ConsoleApplication }, + Options = + { + { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion }, + } + }.RunAsync(); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78002")] + public Task TestPreserveStatementDirectives2() + => new VerifyCS.Test + { + TestCode = """ + using System; + + class Program + { + static void $$Main(string[] args) + { + #if true + Console.WriteLine("true"); + #else + Console.WriteLine("false"); + #endif + } + } + + class Next + { + } + """, + FixedCode = """ + using System; + + #if true + Console.WriteLine("true"); + #else + Console.WriteLine("false"); + #endif + + class Next + { + } + """, + LanguageVersion = LanguageVersion.CSharp10, + TestState = { OutputKind = OutputKind.ConsoleApplication }, + Options = + { + { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion }, + } + }.RunAsync(); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78002")] + public Task TestPreserveStatementDirectives3() + => new VerifyCS.Test + { + TestCode = """ + using System; + + namespace N + { + class Program + { + static void $$Main(string[] args) + { + #if true + Console.WriteLine("true"); + #else + Console.WriteLine("false"); + #endif + } + } + } + """, + FixedCode = """ + using System; + + #if true + Console.WriteLine("true"); + #else + Console.WriteLine("false"); + #endif + + """, + LanguageVersion = LanguageVersion.CSharp10, + TestState = { OutputKind = OutputKind.ConsoleApplication }, + Options = + { + { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion }, + } + }.RunAsync(); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78002")] + public Task TestPreserveStatementDirectives4() + => new VerifyCS.Test + { + TestCode = """ + using System; + + namespace N + { + class Program + { + static void $$Main(string[] args) + { + #if true + Console.WriteLine("true"); + #else + Console.WriteLine("false"); + #endif + } + } + + class Next + { + } + } + """, + FixedCode = """ + using System; + + #if true + Console.WriteLine("true"); + #else + Console.WriteLine("false"); + #endif + + namespace N + { + class Next + { + } + } + """, + LanguageVersion = LanguageVersion.CSharp10, + TestState = { OutputKind = OutputKind.ConsoleApplication }, + Options = + { + { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion }, + } + }.RunAsync(); } diff --git a/src/Features/CSharpTest/ConvertToExtension/ConvertToExtensionTests.cs b/src/Features/CSharpTest/ConvertToExtension/ConvertToExtensionTests.cs index 511a8f28301f7..7af71cc2270fe 100644 --- a/src/Features/CSharpTest/ConvertToExtension/ConvertToExtensionTests.cs +++ b/src/Features/CSharpTest/ConvertToExtension/ConvertToExtensionTests.cs @@ -19,9 +19,8 @@ namespace Microsoft.CodeAnalysis.CSharp.UnitTests.ConvertToExtension; public sealed class ConvertToExtensionTests { [Fact] - public async Task TestBaseCase() - { - await new VerifyCS.Test + public Task TestBaseCase() + => new VerifyCS.Test { TestCode = """ static class C @@ -40,12 +39,10 @@ public void M() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestRefReceiver() - { - await new VerifyCS.Test + public Task TestRefReceiver() + => new VerifyCS.Test { TestCode = """ static class C @@ -64,12 +61,10 @@ public void M() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestInReceiver() - { - await new VerifyCS.Test + public Task TestInReceiver() + => new VerifyCS.Test { TestCode = """ static class C @@ -88,12 +83,10 @@ public void M() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestRefReadonlyReceiver() - { - await new VerifyCS.Test + public Task TestRefReadonlyReceiver() + => new VerifyCS.Test { TestCode = """ static class C @@ -112,12 +105,10 @@ public void M() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestNotOnCSharp13() - { - await new VerifyCS.Test + public Task TestNotOnCSharp13() + => new VerifyCS.Test { TestCode = """ static class C @@ -127,12 +118,10 @@ static class C """, LanguageVersion = LanguageVersion.CSharp13, }.RunAsync(); - } [Fact] - public async Task TestWithMultipleParameters() - { - await new VerifyCS.Test + public Task TestWithMultipleParameters() + => new VerifyCS.Test { TestCode = """ static class C @@ -151,12 +140,10 @@ public void M(string j) { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestInsideNamespace1() - { - await new VerifyCS.Test + public Task TestInsideNamespace1() + => new VerifyCS.Test { TestCode = """ namespace N @@ -181,12 +168,10 @@ public void M(string j) { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestInsideNamespace2() - { - await new VerifyCS.Test + public Task TestInsideNamespace2() + => new VerifyCS.Test { TestCode = """ namespace N; @@ -209,12 +194,10 @@ public void M(string j) { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestNotWithNoParameters() - { - await new VerifyCS.Test + public Task TestNotWithNoParameters() + => new VerifyCS.Test { TestCode = """ static class C @@ -224,12 +207,10 @@ static class C """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestNotInsideStruct() - { - await new VerifyCS.Test + public Task TestNotInsideStruct() + => new VerifyCS.Test { TestCode = """ struct C @@ -247,12 +228,10 @@ struct C } } }.RunAsync(); - } [Fact] - public async Task TestNotInsideInstanceClass() - { - await new VerifyCS.Test + public Task TestNotInsideInstanceClass() + => new VerifyCS.Test { TestCode = """ class C @@ -270,12 +249,10 @@ class C } } }.RunAsync(); - } [Fact] - public async Task TestNotForInstanceMethod() - { - await new VerifyCS.Test + public Task TestNotForInstanceMethod() + => new VerifyCS.Test { TestCode = """ static class C @@ -295,12 +272,10 @@ static class C } } }.RunAsync(); - } [Fact] - public async Task TestNotForNestedClass() - { - await new VerifyCS.Test + public Task TestNotForNestedClass() + => new VerifyCS.Test { TestCode = """ static class Outer @@ -323,12 +298,10 @@ static class C } } }.RunAsync(); - } [Fact] - public async Task TestWithReferencedTypeParameterInOrder1() - { - await new VerifyCS.Test + public Task TestWithReferencedTypeParameterInOrder1() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -351,12 +324,10 @@ public void M() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestWithReferencedTypeParameterInOrder2() - { - await new VerifyCS.Test + public Task TestWithReferencedTypeParameterInOrder2() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -379,12 +350,10 @@ public void M() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestWithReferencedTypeParameterInOrder3() - { - await new VerifyCS.Test + public Task TestWithReferencedTypeParameterInOrder3() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -407,12 +376,10 @@ public void M() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestWithReferencedTypeParameterInOrder4() - { - await new VerifyCS.Test + public Task TestWithReferencedTypeParameterInOrder4() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -435,12 +402,10 @@ public void M() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestWithReferencedTypeParameterNotInOrder1() - { - await new VerifyCS.Test + public Task TestWithReferencedTypeParameterNotInOrder1() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -452,12 +417,10 @@ static class C """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping1() - { - await new VerifyCS.Test + public Task TestSimpleGrouping1() + => new VerifyCS.Test { TestCode = """ static class C @@ -478,12 +441,10 @@ public void N() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping1_A() - { - await new VerifyCS.Test + public Task TestSimpleGrouping1_A() + => new VerifyCS.Test { TestCode = """ static class C @@ -504,12 +465,10 @@ public void N() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping2() - { - await new VerifyCS.Test + public Task TestSimpleGrouping2() + => new VerifyCS.Test { TestCode = """ static class C @@ -530,12 +489,10 @@ public void N(string s) { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping2_A() - { - await new VerifyCS.Test + public Task TestSimpleGrouping2_A() + => new VerifyCS.Test { TestCode = """ static class C @@ -556,12 +513,10 @@ public void N(string s) { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_MatchingAttributes1() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_MatchingAttributes1() + => new VerifyCS.Test { TestCode = """ using System; @@ -590,12 +545,10 @@ public void N() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_MatchingAttributes2() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_MatchingAttributes2() + => new VerifyCS.Test { TestCode = """ using System; @@ -624,12 +577,10 @@ public void N() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_MatchingAttributes3() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_MatchingAttributes3() + => new VerifyCS.Test { TestCode = """ using System; @@ -664,12 +615,10 @@ public void N() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_MatchingAttributes4() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_MatchingAttributes4() + => new VerifyCS.Test { TestCode = """ using System; @@ -704,12 +653,10 @@ public void N() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_NonMatchingAttributes1() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_NonMatchingAttributes1() + => new VerifyCS.Test { TestCode = """ using System; @@ -738,12 +685,10 @@ public void N() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_NonMatchingAttributes2() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_NonMatchingAttributes2() + => new VerifyCS.Test { TestCode = """ using System; @@ -774,12 +719,10 @@ public void N() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_NonMatchingAttributes3() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_NonMatchingAttributes3() + => new VerifyCS.Test { TestCode = """ using System; @@ -814,12 +757,10 @@ public void N() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_NonMatchingAttributes4() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_NonMatchingAttributes4() + => new VerifyCS.Test { TestCode = """ using System; @@ -854,12 +795,10 @@ public void N() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_UnrelatedAttributes() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_UnrelatedAttributes() + => new VerifyCS.Test { TestCode = """ using System; @@ -890,12 +829,10 @@ public void N([Y] string s) { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_TypeParameters1() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_TypeParameters1() + => new VerifyCS.Test { TestCode = """ using System; @@ -928,12 +865,10 @@ public void N() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_TypeParameters_DifferentName() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_TypeParameters_DifferentName() + => new VerifyCS.Test { TestCode = """ using System; @@ -967,12 +902,10 @@ public static void N(this IList list) { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_TypeParameters_SameAttributes() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_TypeParameters_SameAttributes() + => new VerifyCS.Test { TestCode = """ using System; @@ -1005,12 +938,10 @@ public void N() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_TypeParameters_DifferentAttributes() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_TypeParameters_DifferentAttributes() + => new VerifyCS.Test { TestCode = """ using System; @@ -1044,12 +975,10 @@ public static void N([Y] this IList list) { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_TypeParameters_SameConstructorConstraint() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_TypeParameters_SameConstructorConstraint() + => new VerifyCS.Test { TestCode = """ using System; @@ -1076,12 +1005,10 @@ public void N() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_TypeParameters_DifferentConstructorConstraint() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_TypeParameters_DifferentConstructorConstraint() + => new VerifyCS.Test { TestCode = """ using System; @@ -1109,12 +1036,10 @@ public static void N(this IList list) { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_TypeParameters_SameClassConstraint() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_TypeParameters_SameClassConstraint() + => new VerifyCS.Test { TestCode = """ using System; @@ -1141,12 +1066,10 @@ public void N() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_TypeParameters_DifferentClassConstraint() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_TypeParameters_DifferentClassConstraint() + => new VerifyCS.Test { TestCode = """ using System; @@ -1174,12 +1097,10 @@ public static void N(this IList list) { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_TypeParameters_SameTypeConstraint() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_TypeParameters_SameTypeConstraint() + => new VerifyCS.Test { TestCode = """ using System; @@ -1206,12 +1127,10 @@ public void N() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_TypeParameters_DifferentTypeConstraint() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_TypeParameters_DifferentTypeConstraint() + => new VerifyCS.Test { TestCode = """ using System; @@ -1239,12 +1158,10 @@ public static void N(this IList list) { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_Parameters_SameParameterRef() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_Parameters_SameParameterRef() + => new VerifyCS.Test { TestCode = """ using System; @@ -1271,12 +1188,10 @@ public void N() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_Parameters_DifferentParameterRef() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_Parameters_DifferentParameterRef() + => new VerifyCS.Test { TestCode = """ using System; @@ -1304,12 +1219,10 @@ public static void N(this int i) { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_Parameters_SameParameterName() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_Parameters_SameParameterName() + => new VerifyCS.Test { TestCode = """ using System; @@ -1336,12 +1249,10 @@ public void N() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_Parameters_DifferentParameterName() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_Parameters_DifferentParameterName() + => new VerifyCS.Test { TestCode = """ using System; @@ -1369,12 +1280,10 @@ public static void N(this int j) { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_Parameters_SameParameterTupleNames() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_Parameters_SameParameterTupleNames() + => new VerifyCS.Test { TestCode = """ using System; @@ -1401,12 +1310,10 @@ public void N() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_Parameters_DifferentParameterTupleNames() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_Parameters_DifferentParameterTupleNames() + => new VerifyCS.Test { TestCode = """ using System; @@ -1434,12 +1341,10 @@ public static void N(this (int k, int l) i) { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_Parameters_SameParameterNullability() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_Parameters_SameParameterNullability() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -1470,12 +1375,10 @@ public void N() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_Parameters_DifferentParameterNullability() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_Parameters_DifferentParameterNullability() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -1507,12 +1410,10 @@ public static void N(this string i) { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_Parameters_SameParameterDynamic() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_Parameters_SameParameterDynamic() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -1543,12 +1444,10 @@ public void N() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestSimpleGrouping_Parameters_DifferentDynamic() - { - await new VerifyCS.Test + public Task TestSimpleGrouping_Parameters_DifferentDynamic() + => new VerifyCS.Test { TestCode = """ #nullable enable @@ -1580,12 +1479,10 @@ public static void N(this object i) { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestTriviaMove1() - { - await new VerifyCS.Test + public Task TestTriviaMove1() + => new VerifyCS.Test { TestCode = """ using System; @@ -1614,12 +1511,10 @@ public void N() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestTriviaMove2() - { - await new VerifyCS.Test + public Task TestTriviaMove2() + => new VerifyCS.Test { TestCode = """ using System; @@ -1650,12 +1545,10 @@ public void N() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestGroupingWithNonExtension1() - { - await new VerifyCS.Test + public Task TestGroupingWithNonExtension1() + => new VerifyCS.Test { TestCode = """ using System; @@ -1688,12 +1581,10 @@ public void N() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestGroupingWithNonExtension2() - { - await new VerifyCS.Test + public Task TestGroupingWithNonExtension2() + => new VerifyCS.Test { TestCode = """ using System; @@ -1726,12 +1617,10 @@ public static void O() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestGroupingWithNonExtension3() - { - await new VerifyCS.Test + public Task TestGroupingWithNonExtension3() + => new VerifyCS.Test { TestCode = """ using System; @@ -1764,12 +1653,10 @@ public static void O() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestFixClass1() - { - await new VerifyCS.Test + public Task TestFixClass1() + => new VerifyCS.Test { TestCode = """ using System; @@ -1809,12 +1696,10 @@ public void P() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestFixClass2() - { - await new VerifyCS.Test + public Task TestFixClass2() + => new VerifyCS.Test { TestCode = """ using System; @@ -1854,12 +1739,10 @@ public void P() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestCodeBody1() - { - await new VerifyCS.Test + public Task TestCodeBody1() + => new VerifyCS.Test { TestCode = """ static class C @@ -1884,12 +1767,10 @@ public void M() """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestCodeBody2() - { - await new VerifyCS.Test + public Task TestCodeBody2() + => new VerifyCS.Test { TestCode = """ using System; @@ -1922,12 +1803,10 @@ public DateTime M() """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestMultipleConstraints1() - { - await new VerifyCS.Test + public Task TestMultipleConstraints1() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -1952,12 +1831,10 @@ public void M() { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } [Fact] - public async Task TestMultipleConstraints2() - { - await new VerifyCS.Test + public Task TestMultipleConstraints2() + => new VerifyCS.Test { TestCode = """ using System.Collections.Generic; @@ -1980,5 +1857,4 @@ public void M() where V : class { } """, LanguageVersion = LanguageVersionExtensions.CSharpNext, }.RunAsync(); - } } diff --git a/src/Features/CSharpTest/ConvertToInterpolatedString/ConvertConcatenationToInterpolatedStringTests.cs b/src/Features/CSharpTest/ConvertToInterpolatedString/ConvertConcatenationToInterpolatedStringTests.cs index aa11bbaca2a27..8ca301d98bfda 100644 --- a/src/Features/CSharpTest/ConvertToInterpolatedString/ConvertConcatenationToInterpolatedStringTests.cs +++ b/src/Features/CSharpTest/ConvertToInterpolatedString/ConvertConcatenationToInterpolatedStringTests.cs @@ -20,9 +20,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertToInterpolatedSt public sealed class ConvertConcatenationToInterpolatedStringTests { [Fact] - public async Task TestMissingOnSimpleString() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task TestMissingOnSimpleString() + => VerifyCS.VerifyRefactoringAsync(""" public class C { void M() @@ -31,12 +30,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingOnConcatenatedStrings1() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task TestMissingOnConcatenatedStrings1() + => VerifyCS.VerifyRefactoringAsync(""" public class C { void M() @@ -45,12 +42,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingOnConcatenatedStrings2() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task TestMissingOnConcatenatedStrings2() + => VerifyCS.VerifyRefactoringAsync(""" public class C { void M() @@ -59,12 +54,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingOnConcatenatedStrings3() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task TestMissingOnConcatenatedStrings3() + => VerifyCS.VerifyRefactoringAsync(""" public class C { void M() @@ -73,12 +66,10 @@ void M() } } """); - } [Fact] - public async Task TestWithStringOnLeft() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithStringOnLeft() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -97,12 +88,10 @@ void M() } } """); - } [Fact] - public async Task TestRightSideOfString() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestRightSideOfString() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -121,12 +110,10 @@ void M() } } """); - } [Fact] - public async Task TestWithStringOnRight() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithStringOnRight() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -145,12 +132,10 @@ void M() } } """); - } [Fact] - public async Task TestWithComplexExpressionOnLeft() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithComplexExpressionOnLeft() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -169,12 +154,10 @@ void M() } } """); - } [Fact] - public async Task TestWithTrivia1() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithTrivia1() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -197,12 +180,10 @@ void M() } } """); - } [Fact] - public async Task TestWithComplexExpressions() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithComplexExpressions() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -221,12 +202,10 @@ void M() } } """); - } [Fact] - public async Task TestWithEscapes1() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithEscapes1() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -245,12 +224,10 @@ void M() } } """); - } [Fact] - public async Task TestWithEscapes2() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithEscapes2() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -269,12 +246,10 @@ void M() } } """); - } [Fact] - public async Task TestWithVerbatimString1() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithVerbatimString1() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -293,12 +268,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingWithMixedStringTypes1() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task TestMissingWithMixedStringTypes1() + => VerifyCS.VerifyRefactoringAsync(""" public class C { void M() @@ -307,12 +280,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingWithMixedStringTypes2() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task TestMissingWithMixedStringTypes2() + => VerifyCS.VerifyRefactoringAsync(""" public class C { void M() @@ -321,12 +292,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingWithMixedStringTypes3() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task TestMissingWithMixedStringTypes3() + => VerifyCS.VerifyRefactoringAsync(""" public class C { void M() @@ -335,12 +304,10 @@ void M() } } """); - } [Fact] - public async Task TestWithOverloadedOperator() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithOverloadedOperator() + => VerifyCS.VerifyRefactoringAsync( """ public class D { @@ -373,12 +340,10 @@ void M() } } """); - } [Fact] - public async Task TestWithOverloadedOperator2() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task TestWithOverloadedOperator2() + => VerifyCS.VerifyRefactoringAsync(""" public class D { public static int operator +(D d, string s) => 0; @@ -394,12 +359,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16820")] - public async Task TestWithMultipleStringConcatenations() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithMultipleStringConcatenations() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -418,12 +381,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16820")] - public async Task TestWithMultipleStringConcatenations2() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithMultipleStringConcatenations2() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -442,12 +403,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16820")] - public async Task TestWithMultipleStringConcatenations3() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithMultipleStringConcatenations3() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -466,12 +425,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16820")] - public async Task TestWithMultipleStringConcatenations4() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task TestWithMultipleStringConcatenations4() + => VerifyCS.VerifyRefactoringAsync(""" public class C { void M() @@ -480,12 +437,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20943")] - public async Task TestMissingWithDynamic1() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task TestMissingWithDynamic1() + => VerifyCS.VerifyRefactoringAsync(""" class C { void M() @@ -495,12 +450,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20943")] - public async Task TestMissingWithDynamic2() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task TestMissingWithDynamic2() + => VerifyCS.VerifyRefactoringAsync(""" class C { void M() @@ -510,12 +463,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23536")] - public async Task TestWithStringLiteralWithBraces() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithStringLiteralWithBraces() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -534,12 +485,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23536")] - public async Task TestWithStringLiteralWithBraces2() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithStringLiteralWithBraces2() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -558,12 +507,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23536")] - public async Task TestWithStringLiteralWithDoubleBraces() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithStringLiteralWithDoubleBraces() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -582,12 +529,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23536")] - public async Task TestWithMultipleStringLiteralsWithBraces() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithMultipleStringLiteralsWithBraces() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -606,12 +551,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23536")] - public async Task TestWithVerbatimStringWithBraces() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithVerbatimStringWithBraces() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -630,12 +573,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23536")] - public async Task TestWithMultipleVerbatimStringsWithBraces() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithMultipleVerbatimStringsWithBraces() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -654,13 +595,11 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] [WorkItem("https://github.com/dotnet/roslyn/issues/16981")] - public async Task TestWithSelectionOnEntireToBeInterpolatedString() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithSelectionOnEntireToBeInterpolatedString() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -679,13 +618,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16981")] - public async Task TestMissingWithSelectionOnPartOfToBeInterpolatedStringPrefix() - { - // see comment in AbstractConvertConcatenationToInterpolatedStringRefactoringProvider:ComputeRefactoringsAsync - await VerifyCS.VerifyRefactoringAsync(""" + public Task TestMissingWithSelectionOnPartOfToBeInterpolatedStringPrefix() + => VerifyCS.VerifyRefactoringAsync(""" public class C { void M() @@ -694,14 +630,11 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] [WorkItem("https://github.com/dotnet/roslyn/issues/16981")] - public async Task TestMissingWithSelectionOnPartOfToBeInterpolatedStringSuffix() - { - // see comment in AbstractConvertConcatenationToInterpolatedStringRefactoringProvider:ComputeRefactoringsAsync - await VerifyCS.VerifyRefactoringAsync(""" + public Task TestMissingWithSelectionOnPartOfToBeInterpolatedStringSuffix() + => VerifyCS.VerifyRefactoringAsync(""" public class C { void M() @@ -710,14 +643,11 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] [WorkItem("https://github.com/dotnet/roslyn/issues/16981")] - public async Task TestMissingWithSelectionOnMiddlePartOfToBeInterpolatedString() - { - // see comment in AbstractConvertConcatenationToInterpolatedStringRefactoringProvider:ComputeRefactoringsAsync - await VerifyCS.VerifyRefactoringAsync(""" + public Task TestMissingWithSelectionOnMiddlePartOfToBeInterpolatedString() + => VerifyCS.VerifyRefactoringAsync(""" public class C { void M() @@ -726,12 +656,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16981")] - public async Task TestWithSelectionExceedingToBeInterpolatedString() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithSelectionExceedingToBeInterpolatedString() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -750,12 +678,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16981")] - public async Task TestWithCaretBeforeNonStringToken() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithCaretBeforeNonStringToken() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -774,12 +700,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16981")] - public async Task TestWithCaretAfterNonStringToken() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithCaretAfterNonStringToken() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -798,12 +722,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16981")] - public async Task TestWithCaretBeforePlusToken() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithCaretBeforePlusToken() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -822,12 +744,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16981")] - public async Task TestWithCaretAfterPlusToken() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithCaretAfterPlusToken() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -846,12 +766,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16981")] - public async Task TestWithCaretBeforeLastPlusToken() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithCaretBeforeLastPlusToken() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -870,12 +788,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16981")] - public async Task TestWithCaretAfterLastPlusToken() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithCaretAfterLastPlusToken() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -894,12 +810,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32864")] - public async Task TestConcatenationWithNoStringLiterals() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestConcatenationWithNoStringLiterals() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -918,12 +832,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37324")] - public async Task TestConcatenationWithChar() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestConcatenationWithChar() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -946,12 +858,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37324")] - public async Task TestConcatenationWithCharAfterStringLiteral() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestConcatenationWithCharAfterStringLiteral() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -972,12 +882,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37324")] - public async Task TestConcatenationWithCharBeforeStringLiteral() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestConcatenationWithCharBeforeStringLiteral() + => VerifyCS.VerifyRefactoringAsync( """ public class C { @@ -998,31 +906,25 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40413")] - public async Task TestConcatenationWithConstMemberCSharp9() - { - // lang=c#-test - var code = """ + public Task TestConcatenationWithConstMemberCSharp9() + => new VerifyCS.Test + { + LanguageVersion = LanguageVersion.CSharp9, + TestCode = """ class C { const string Hello = "Hello"; const string World = "World"; const string Message = Hello + " " + [||]World; } - """; - await new VerifyCS.Test - { - LanguageVersion = LanguageVersion.CSharp9, - TestCode = code, + """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40413")] - public async Task TestConcatenationWithConstMember() - { - await new VerifyCS.Test + public Task TestConcatenationWithConstMember() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.Preview, TestCode = """ @@ -1042,7 +944,6 @@ class C } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40413")] public async Task TestConcatenationWithConstDeclaration() @@ -1057,17 +958,6 @@ void M() { } } """; - var fixedCode = """ - class C - { - void M() { - const string Hello = "Hello"; - const string World = "World"; - const string Message = $"{Hello} {World}"; - } - } - """; - await new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp9, @@ -1078,14 +968,22 @@ void M() { { LanguageVersion = LanguageVersion.Preview, TestCode = code, - FixedCode = fixedCode, + FixedCode = """ + class C + { + void M() { + const string Hello = "Hello"; + const string World = "World"; + const string Message = $"{Hello} {World}"; + } + } + """, }.RunAsync(); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40413")] - public async Task TestConcatenationWithInlineString() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task TestConcatenationWithInlineString() + => VerifyCS.VerifyRefactoringAsync(""" using System; class C { @@ -1107,7 +1005,6 @@ void M() { } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/49229")] [InlineData(@"[|""a"" + $""{1:000}""|]", @@ -1146,24 +1043,22 @@ void M() { """ $"a{@$"{1:000}"}" """)] - public async Task TestInliningOfInterpolatedString(string before, string after) - { - var initialMarkup = $@" -class C -{{ - void M() {{ - _ = {before}; - }} -}}"; - var expected = $@" -class C -{{ - void M() {{ - _ = {after}; - }} -}}"; - await VerifyCS.VerifyRefactoringAsync(initialMarkup, expected); - } + public Task TestInliningOfInterpolatedString(string before, string after) + => VerifyCS.VerifyRefactoringAsync($$""" + class C + { + void M() { + _ = {{before}}; + } + } + """, $$""" + class C + { + void M() { + _ = {{after}}; + } + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/49229")] [InlineData(""" @@ -1196,26 +1091,22 @@ void M() {{ """ $"{{}}{1}" """)] - public async Task TestUnicodeAndEscapeHandling(string before, string after) - { - var initialMarkup = $$""" + public Task TestUnicodeAndEscapeHandling(string before, string after) + => VerifyCS.VerifyRefactoringAsync($$""" class C { void M() { _ = {{before}}; } } - """; - var expected = $$""" + """, $$""" class C { void M() { _ = {{after}}; } } - """; - await VerifyCS.VerifyRefactoringAsync(initialMarkup, expected); - } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/49229")] [InlineData(""" @@ -1242,31 +1133,26 @@ void M() { """ $"a{(1 + 1)}" """)] - public async Task TestRemovalOfSuperflousParenthesis(string before, string after) - { - var initialMarkup = $$""" + public Task TestRemovalOfSuperflousParenthesis(string before, string after) + => VerifyCS.VerifyRefactoringAsync($$""" class C { void M() { _ = {{before}}; } } - """; - var expected = $$""" + """, $$""" class C { void M() { _ = {{after}}; } } - """; - await VerifyCS.VerifyRefactoringAsync(initialMarkup, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69721")] - public async Task TestToString1() - { - await new VerifyCS.Test + public Task TestToString1() + => new VerifyCS.Test { TestCode = """ struct ValueTuple @@ -1293,12 +1179,10 @@ public override string ToString() } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69721")] - public async Task TestToString1_Net6() - { - await new VerifyCS.Test + public Task TestToString1_Net6() + => new VerifyCS.Test { TestCode = """ struct ValueTuple @@ -1326,12 +1210,10 @@ public override string ToString() """, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69721")] - public async Task TestToString2() - { - await new VerifyCS.Test + public Task TestToString2() + => new VerifyCS.Test { TestCode = """ struct ValueTuple @@ -1352,12 +1234,10 @@ public override string ToString() } """, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69721")] - public async Task TestToString2_Net6() - { - await new VerifyCS.Test + public Task TestToString2_Net6() + => new VerifyCS.Test { TestCode = """ struct ValueTuple @@ -1379,12 +1259,10 @@ public override string ToString() """, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61256")] - public async Task TestWithRawString() - { - await new VerifyCS.Test + public Task TestWithRawString() + => new VerifyCS.Test { TestCode = """" struct ValueTuple @@ -1401,12 +1279,10 @@ Appended line """", LanguageVersion = LanguageVersion.CSharp11, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68425")] - public async Task TestQuoteCharacter1() - { - await new VerifyCS.Test + public Task TestQuoteCharacter1() + => new VerifyCS.Test { TestCode = """ class C @@ -1428,12 +1304,10 @@ static void Main(string[] args) """, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68425")] - public async Task TestQuoteCharacter2() - { - await new VerifyCS.Test + public Task TestQuoteCharacter2() + => new VerifyCS.Test { TestCode = """ class C @@ -1446,5 +1320,4 @@ static void Main(string[] args) """, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } } diff --git a/src/Features/CSharpTest/ConvertToInterpolatedString/ConvertPlaceholderToInterpolatedStringTests.cs b/src/Features/CSharpTest/ConvertToInterpolatedString/ConvertPlaceholderToInterpolatedStringTests.cs index 394d5834bb4e9..194bf4a264568 100644 --- a/src/Features/CSharpTest/ConvertToInterpolatedString/ConvertPlaceholderToInterpolatedStringTests.cs +++ b/src/Features/CSharpTest/ConvertToInterpolatedString/ConvertPlaceholderToInterpolatedStringTests.cs @@ -62,14 +62,18 @@ public static IEnumerable InvocationData // Makes a string of form "{0} {1}..." static string MakeInterpolatedString(int numberOfParameters) { - var interpolatedString = "\""; + var interpolatedString = """ + " + """; for (var i = 0; i < numberOfParameters; i++) { interpolatedString += $"{{{i}}}"; } - return interpolatedString + "\""; + return interpolatedString + """ + " + """; } // Makes a string of form "{0} {1}..., 0, 1, ..." @@ -83,9 +87,8 @@ static string MakeFormattedParameters(int numberOfParameters) } [Theory, MemberData(nameof(InvocationData))] - public async Task TestInvocationSubstitution(string before, string after) - { - await TestInRegularAndScriptAsync( + public Task TestInvocationSubstitution(string before, string after) + => TestInRegularAndScriptAsync( $$""" using System; using System.Diagnostics; @@ -110,12 +113,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/55053")] - public async Task TestMissing_ConsoleWriteLine() - { - await TestMissingAsync( + public Task TestMissing_ConsoleWriteLine() + => TestMissingAsync( """ using System; @@ -130,12 +131,10 @@ void M() string GetString() => ""; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/55053")] - public async Task TestMissing_ConsoleWrite() - { - await TestMissingAsync( + public Task TestMissing_ConsoleWrite() + => TestMissingAsync( """ using System; @@ -150,12 +149,10 @@ void M() string GetString() => ""; } """); - } [Fact] - public async Task TestItemOrdering() - { - await TestInRegularAndScriptAsync( + public Task TestItemOrdering() + => TestInRegularAndScriptAsync( """ using System; @@ -178,12 +175,10 @@ void M() } } """); - } [Fact] - public async Task TestItemOrdering2() - { - await TestInRegularAndScriptAsync( + public Task TestItemOrdering2() + => TestInRegularAndScriptAsync( """ using System; @@ -206,14 +201,10 @@ void M() } } """); - } [Fact] - public async Task TestItemOrdering3() - { - // Missing as we have arguments we don't know what to do with here. Likely a bug in user code that needs - // fixing first. - await TestMissingAsync( + public Task TestItemOrdering3() + => TestMissingAsync( """ using System; @@ -225,12 +216,10 @@ void M() } } """); - } [Fact] - public async Task TestItemOrdering4() - { - await TestInRegularAndScriptAsync( + public Task TestItemOrdering4() + => TestInRegularAndScriptAsync( """ using System; @@ -253,12 +242,10 @@ void M() } } """); - } [Fact] - public async Task TestNotWithMissingCurly1() - { - await TestMissingAsync( + public Task TestNotWithMissingCurly1() + => TestMissingAsync( """ using System; @@ -270,12 +257,10 @@ void M() } } """); - } [Fact] - public async Task TestNotWithMissingCurly2() - { - await TestMissingAsync( + public Task TestNotWithMissingCurly2() + => TestMissingAsync( """ using System; @@ -287,12 +272,10 @@ void M() } } """); - } [Fact] - public async Task TestNotWithIncorrectSyntax1() - { - await TestMissingAsync( + public Task TestNotWithIncorrectSyntax1() + => TestMissingAsync( """ using System; @@ -304,13 +287,10 @@ void M() } } """); - } [Fact] - public async Task TestNotWithMatchWithFollowingNumber() - { - // want to make sure that `{1` is not matched as `{1}` - await TestMissingAsync( + public Task TestNotWithMatchWithFollowingNumber() + => TestMissingAsync( """ using System; @@ -322,12 +302,10 @@ void M() } } """); - } [Fact] - public async Task TestNotWithStringThatParsesWrongAsInterpolation() - { - await TestMissingAsync( + public Task TestNotWithStringThatParsesWrongAsInterpolation() + => TestMissingAsync( """ using System; @@ -339,13 +317,10 @@ void M() } } """); - } [Fact] - public async Task TestItemOutsideRange() - { - // Missing as the format string refers to parameters that aren't provided. - await TestMissingAsync( + public Task TestItemOutsideRange() + => TestMissingAsync( """ using System; @@ -357,12 +332,10 @@ void M() } } """); - } [Fact] - public async Task TestItemDoNotHaveCast() - { - await TestInRegularAndScriptAsync( + public Task TestItemDoNotHaveCast() + => TestInRegularAndScriptAsync( """ using System; @@ -385,12 +358,10 @@ void M() } } """); - } [Fact] - public async Task TestItemWithSyntaxErrorDoesHaveCast() - { - await TestInRegularAndScriptAsync( + public Task TestItemWithSyntaxErrorDoesHaveCast() + => TestInRegularAndScriptAsync( """ using System; @@ -413,12 +384,10 @@ void M() } } """); - } [Fact] - public async Task TestItemWithoutSyntaxErrorDoesNotHaveCast() - { - await TestInRegularAndScriptAsync( + public Task TestItemWithoutSyntaxErrorDoesNotHaveCast() + => TestInRegularAndScriptAsync( """ using System; @@ -441,12 +410,10 @@ void M() } } """); - } [Fact] - public async Task TestParenthesisAddedForTernaryExpression() - { - await TestInRegularAndScriptAsync( + public Task TestParenthesisAddedForTernaryExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -469,12 +436,10 @@ void M() } } """); - } [Fact] - public async Task TestDoesNotAddDoubleParenthesisForTernaryExpression() - { - await TestInRegularAndScriptAsync( + public Task TestDoesNotAddDoubleParenthesisForTernaryExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -497,12 +462,10 @@ void M() } } """); - } [Fact] - public async Task TestMultiLineExpression() - { - await TestInRegularAndScriptAsync( + public Task TestMultiLineExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -527,12 +490,10 @@ void M() } } """); - } [Fact] - public async Task TestFormatSpecifiers() - { - await TestInRegularAndScriptAsync( + public Task TestFormatSpecifiers() + => TestInRegularAndScriptAsync( """ using System; @@ -558,12 +519,10 @@ void M() } } """); - } [Fact] - public async Task TestFormatSpecifiers2() - { - await TestInRegularAndScriptAsync( + public Task TestFormatSpecifiers2() + => TestInRegularAndScriptAsync( """ using System; @@ -586,12 +545,10 @@ void M() } } """); - } [Fact] - public async Task TestFormatSpecifiers3() - { - await TestInRegularAndScriptAsync( + public Task TestFormatSpecifiers3() + => TestInRegularAndScriptAsync( """ using System; class T @@ -621,12 +578,10 @@ void M() } } """); - } [Fact] - public async Task TestFormatSpecifiers4() - { - await TestInRegularAndScriptAsync( + public Task TestFormatSpecifiers4() + => TestInRegularAndScriptAsync( """ using System; @@ -649,12 +604,10 @@ void M() } } """); - } [Fact] - public async Task TestFormatSpecifiers5() - { - await TestInRegularAndScriptAsync( + public Task TestFormatSpecifiers5() + => TestInRegularAndScriptAsync( """ using System; @@ -707,12 +660,10 @@ public static void M() } } """); - } [Fact] - public async Task TestFormatSpecifiers6() - { - await TestInRegularAndScriptAsync( + public Task TestFormatSpecifiers6() + => TestInRegularAndScriptAsync( """ using System; @@ -755,12 +706,10 @@ public static void M() } } """); - } [Fact] - public async Task TestVerbatimStringLiteral() - { - await TestInRegularAndScriptAsync( + public Task TestVerbatimStringLiteral() + => TestInRegularAndScriptAsync( """ using System; @@ -794,12 +743,10 @@ public static void M() } } """); - } [Fact] - public async Task TestFormatWithParams() - { - await TestMissingInRegularAndScriptAsync( + public Task TestFormatWithParams() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -819,12 +766,10 @@ public static void M() } } """); - } [Fact] - public async Task TestInvalidInteger() - { - await TestInRegularAndScriptAsync( + public Task TestInvalidInteger() + => TestInRegularAndScriptAsync( """ using System; @@ -847,12 +792,10 @@ public static void M() } } """); - } [Fact] - public async Task TestOutVariableDeclaration_01() - { - await TestMissingInRegularAndScriptAsync( + public Task TestOutVariableDeclaration_01() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -864,12 +807,10 @@ void M() } } """); - } [Fact] - public async Task TestOutVariableDeclaration_02() - { - await TestMissingInRegularAndScriptAsync( + public Task TestOutVariableDeclaration_02() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -881,14 +822,10 @@ void M() } } """); - } [Fact] - public async Task TestFormatWithNamedArguments1() - { - // Missing as this scenario is too esoteric. I was not able to find any examples of code that reorders and - // names thigns like this with format strings. - await TestMissingAsync( + public Task TestFormatWithNamedArguments1() + => TestMissingAsync( """ using System; @@ -900,12 +837,10 @@ void M() } } """); - } [Fact] - public async Task TestFormatWithNamedArguments2() - { - await TestInRegularAndScriptAsync( + public Task TestFormatWithNamedArguments2() + => TestInRegularAndScriptAsync( """ using System; @@ -928,12 +863,10 @@ void M() } } """); - } [Fact] - public async Task TestFormatWithNamedArguments3() - { - await TestInRegularAndScriptAsync( + public Task TestFormatWithNamedArguments3() + => TestInRegularAndScriptAsync( """ using System; @@ -956,12 +889,10 @@ void M() } } """); - } [Fact] - public async Task TestFormatWithNamedArguments4() - { - await TestInRegularAndScriptAsync( + public Task TestFormatWithNamedArguments4() + => TestInRegularAndScriptAsync( """ using System; @@ -984,12 +915,10 @@ void M() } } """); - } [Fact] - public async Task TestFormatWithNamedArguments5() - { - await TestInRegularAndScriptAsync( + public Task TestFormatWithNamedArguments5() + => TestInRegularAndScriptAsync( """ using System; @@ -1012,12 +941,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestOnlyArgumentSelection1() - { - await TestInRegularAndScriptAsync( + public Task TestOnlyArgumentSelection1() + => TestInRegularAndScriptAsync( """ using System; @@ -1040,12 +967,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestOnlyArgumentSelection2() - { - await TestInRegularAndScriptAsync( + public Task TestOnlyArgumentSelection2() + => TestInRegularAndScriptAsync( """ using System; @@ -1068,12 +993,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestArgumentsSelection2() - { - await TestInRegularAndScriptAsync( + public Task TestArgumentsSelection2() + => TestInRegularAndScriptAsync( """ using System; @@ -1096,12 +1019,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61346")] - public async Task TestNoCastToObjectWhenNullableEnabled() - { - await TestInRegularAndScriptAsync( + public Task TestNoCastToObjectWhenNullableEnabled() + => TestInRegularAndScriptAsync( """ using System; @@ -1128,12 +1049,10 @@ void M() } } """); - } [Fact, WorkItem(1756068, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1756068")] - public async Task TestArbitraryAPI() - { - await TestInRegularAndScriptAsync( + public Task TestArbitraryAPI() + => TestInRegularAndScriptAsync( """ using System; @@ -1168,12 +1087,10 @@ void M(ILogger logger) } } """); - } [Fact, WorkItem(61346, "https://github.com/dotnet/roslyn/issues/61346")] - public async Task TestNotWithExplicitCultureInfo() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotWithExplicitCultureInfo() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Globalization; @@ -1186,13 +1103,11 @@ void M() } } """); - } [Theory, MemberData(nameof(InvocationData))] [WorkItem("https://github.com/dotnet/roslyn/issues/68469")] - public async Task TestInvocationSubstitution_FixAll(string before, string after) - { - await TestInRegularAndScriptAsync( + public Task TestInvocationSubstitution_FixAll(string before, string after) + => TestInRegularAndScriptAsync( $$""" using System; using System.Diagnostics; @@ -1219,5 +1134,4 @@ void M() } } """); - } } diff --git a/src/Features/CSharpTest/ConvertToInterpolatedString/ConvertRegularStringToInterpolatedStringTests.cs b/src/Features/CSharpTest/ConvertToInterpolatedString/ConvertRegularStringToInterpolatedStringTests.cs index 3ce878b98e510..71a85d584e5ba 100644 --- a/src/Features/CSharpTest/ConvertToInterpolatedString/ConvertRegularStringToInterpolatedStringTests.cs +++ b/src/Features/CSharpTest/ConvertToInterpolatedString/ConvertRegularStringToInterpolatedStringTests.cs @@ -20,9 +20,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor => new ConvertRegularStringToInterpolatedStringRefactoringProvider(); [Fact] - public async Task TestMissingOnRegularStringWithNoBraces() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnRegularStringWithNoBraces() + => TestMissingInRegularAndScriptAsync( """ public class C { @@ -32,12 +31,10 @@ void M() } } """); - } [Fact] - public async Task TestOnRegularStringWithBraces() - { - await TestInRegularAndScriptAsync( + public Task TestOnRegularStringWithBraces() + => TestInRegularAndScriptAsync( """ public class C { @@ -56,12 +53,10 @@ void M() } } """); - } [Fact] - public async Task TestOnRegularStringWithBracesAndEscapedCharacters() - { - await TestInRegularAndScriptAsync( + public Task TestOnRegularStringWithBracesAndEscapedCharacters() + => TestInRegularAndScriptAsync( """ public class C { @@ -80,12 +75,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingOnInterpolatedString() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnInterpolatedString() + => TestMissingInRegularAndScriptAsync( """ public class C { @@ -96,12 +89,10 @@ void M() } } """); - } [Fact] - public async Task TestOnVerbatimStringWithBraces() - { - await TestInRegularAndScriptAsync( + public Task TestOnVerbatimStringWithBraces() + => TestInRegularAndScriptAsync( """ public class C { @@ -122,12 +113,10 @@ void M() } } """); - } [Fact] - public async Task TestOnVerbatimStringWithBracesAndEscapedQuotes() - { - await TestInRegularAndScriptAsync( + public Task TestOnVerbatimStringWithBracesAndEscapedQuotes() + => TestInRegularAndScriptAsync( """ public class C { @@ -148,12 +137,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52243")] - public async Task TestMissingOnRegularStringWithBracesAssignedToConstBeforeCSharp10() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnRegularStringWithBracesAssignedToConstBeforeCSharp10() + => TestMissingInRegularAndScriptAsync( """ public class C { @@ -163,12 +150,10 @@ void M() } } """, new(new CSharpParseOptions(LanguageVersion.CSharp9))); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52243")] - public async Task TestOnRegularStringWithBracesAssignedToConstForCSharp10AndNewer() - { - await TestInRegularAndScriptAsync( + public Task TestOnRegularStringWithBracesAssignedToConstForCSharp10AndNewer() + => TestInRegularAndScriptAsync( """ public class C { @@ -187,12 +172,10 @@ void M() } } """, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp10)); - } [Fact] - public async Task TestMissingOnUnterminatedStringWithBraces() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnUnterminatedStringWithBraces() + => TestMissingInRegularAndScriptAsync( """ public class C { @@ -202,12 +185,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52243")] - public async Task TestMissingOnAttributeStringParameterWithBracesBeforeCSharp10() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnAttributeStringParameterWithBracesBeforeCSharp10() + => TestMissingInRegularAndScriptAsync( """ [System.Diagnostics.DebuggerDisplay([||]"FirstName={FirstName}, LastName={LastName}")] public class C @@ -216,12 +197,10 @@ public class C public string LastName { get; set; } } """, new(new CSharpParseOptions(LanguageVersion.CSharp9))); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52243")] - public async Task TestOnAttributeStringParameterWithBracesForCSharp10AndNewer() - { - await TestInRegularAndScriptAsync( + public Task TestOnAttributeStringParameterWithBracesForCSharp10AndNewer() + => TestInRegularAndScriptAsync( """ [System.Diagnostics.DebuggerDisplay([||]"FirstName={FirstName}, LastName={LastName}")] public class C @@ -238,12 +217,10 @@ public class C public string LastName { get; set; } } """, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp10)); - } [Fact] - public async Task TestMissingOnRegularStringWithBracesAndCursorOutOfBounds() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnRegularStringWithBracesAndCursorOutOfBounds() + => TestMissingInRegularAndScriptAsync( """ public class C { @@ -253,5 +230,4 @@ void M() } } """); - } } diff --git a/src/Features/CSharpTest/ConvertToRawString/ConvertInterpolatedStringToRawStringTests.cs b/src/Features/CSharpTest/ConvertToRawString/ConvertInterpolatedStringToRawStringTests.cs index ce9769cd77604..b8bed77ee0732 100644 --- a/src/Features/CSharpTest/ConvertToRawString/ConvertInterpolatedStringToRawStringTests.cs +++ b/src/Features/CSharpTest/ConvertToRawString/ConvertInterpolatedStringToRawStringTests.cs @@ -149,9 +149,8 @@ void M() } [Fact] - public async Task TestOnCombinedSurrogate() - { - await VerifyRefactoringAsync( + public Task TestOnCombinedSurrogate() + => VerifyRefactoringAsync( """ public class C { @@ -170,12 +169,10 @@ void M() } } """"); - } [Fact] - public async Task TestOnSplitSurrogate() - { - await VerifyRefactoringAsync( + public Task TestOnSplitSurrogate() + => VerifyRefactoringAsync( """ public class C { @@ -185,7 +182,6 @@ void M() } } """); - } [Fact] public async Task TestNotOnNullChar() @@ -284,9 +280,8 @@ void M() } [Fact] - public async Task TestSimpleString() - { - await VerifyRefactoringAsync(""" + public Task TestSimpleString() + => VerifyRefactoringAsync(""" public class C { void M() @@ -303,12 +298,10 @@ void M() } } """"); - } [Fact] - public async Task TestBraces1() - { - await VerifyRefactoringAsync(""" + public Task TestBraces1() + => VerifyRefactoringAsync(""" public class C { void M() @@ -325,12 +318,10 @@ void M() } } """"); - } [Fact] - public async Task TestBraces1_A() - { - await VerifyRefactoringAsync(""" + public Task TestBraces1_A() + => VerifyRefactoringAsync(""" public class C { void M() @@ -347,12 +338,10 @@ void M() } } """"); - } [Fact] - public async Task TestBraces2() - { - await VerifyRefactoringAsync(""" + public Task TestBraces2() + => VerifyRefactoringAsync(""" public class C { void M() @@ -369,12 +358,10 @@ void M() } } """"); - } [Fact] - public async Task TestBraces2_A() - { - await VerifyRefactoringAsync(""" + public Task TestBraces2_A() + => VerifyRefactoringAsync(""" public class C { void M() @@ -391,12 +378,10 @@ void M() } } """"); - } [Fact] - public async Task TestBraces3() - { - await VerifyRefactoringAsync(""" + public Task TestBraces3() + => VerifyRefactoringAsync(""" public class C { void M() @@ -413,12 +398,10 @@ void M() } } """"); - } [Fact] - public async Task TestBraces3_A() - { - await VerifyRefactoringAsync(""" + public Task TestBraces3_A() + => VerifyRefactoringAsync(""" public class C { void M() @@ -435,12 +418,10 @@ void M() } } """"); - } [Fact] - public async Task TestBraces4_A() - { - await VerifyRefactoringAsync(""" + public Task TestBraces4_A() + => VerifyRefactoringAsync(""" public class C { void M() @@ -457,12 +438,10 @@ void M() } } """"); - } [Fact] - public async Task TestInterpolation_SingleLine1() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_SingleLine1() + => VerifyRefactoringAsync(""" public class C { void M() @@ -479,12 +458,10 @@ void M() } } """"); - } [Fact] - public async Task TestInterpolation_SingleLine2() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_SingleLine2() + => VerifyRefactoringAsync(""" public class C { void M() @@ -501,12 +478,10 @@ void M() } } """"); - } [Fact] - public async Task TestInterpolation_SingleLine3() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_SingleLine3() + => VerifyRefactoringAsync(""" public class C { void M() @@ -523,12 +498,10 @@ void M() } } """"); - } [Fact] - public async Task TestInterpolation_SingleLine4() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_SingleLine4() + => VerifyRefactoringAsync(""" public class C { void M() @@ -545,12 +518,10 @@ void M() } } """"); - } [Fact] - public async Task TestInterpolation_SingleLine5() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_SingleLine5() + => VerifyRefactoringAsync(""" public class C { void M() @@ -567,12 +538,10 @@ void M() } } """"); - } [Fact] - public async Task TestInterpolation_SingleLine6() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_SingleLine6() + => VerifyRefactoringAsync(""" public class C { void M() @@ -589,12 +558,10 @@ void M() } } """"); - } [Fact] - public async Task TestInterpolation_SingleLine7() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_SingleLine7() + => VerifyRefactoringAsync(""" public class C { void M() @@ -611,12 +578,10 @@ void M() } } """"); - } [Fact] - public async Task TestInterpolation_MultiLine1() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_MultiLine1() + => VerifyRefactoringAsync(""" public class C { void M() @@ -639,12 +604,10 @@ void M() } } """"); - } [Fact] - public async Task TestInterpolation_MultiLine1_A() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_MultiLine1_A() + => VerifyRefactoringAsync(""" public class C { void M() @@ -667,12 +630,10 @@ void M() } } """"); - } [Fact] - public async Task TestInterpolation_MultiLine1_B() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_MultiLine1_B() + => VerifyRefactoringAsync(""" public class C { void M() @@ -695,12 +656,10 @@ void M() } } """"); - } [Fact] - public async Task TestInterpolation_MultiLine1_C() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_MultiLine1_C() + => VerifyRefactoringAsync(""" public class C { void M() @@ -723,12 +682,10 @@ void M() } } """"); - } [Fact] - public async Task TestInterpolation_MultiLine1_D() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_MultiLine1_D() + => VerifyRefactoringAsync(""" public class C { void M() @@ -751,12 +708,10 @@ void M() } } """"); - } [Fact] - public async Task TestInterpolation_MultiLine1_E() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_MultiLine1_E() + => VerifyRefactoringAsync(""" public class C { void M() @@ -779,12 +734,10 @@ void M() } } """"); - } [Fact] - public async Task TestInterpolation_MultiLine1_F() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_MultiLine1_F() + => VerifyRefactoringAsync(""" public class C { void M() @@ -807,12 +760,10 @@ void M() } } """"); - } [Fact] - public async Task TestInterpolation_MultiLine2() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_MultiLine2() + => VerifyRefactoringAsync(""" public class C { void M() @@ -835,12 +786,10 @@ void M() } } """"); - } [Fact] - public async Task TestInterpolation_MultiLine3() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_MultiLine3() + => VerifyRefactoringAsync(""" public class C { void M() @@ -863,12 +812,10 @@ void M() } } """"); - } [Fact] - public async Task TestInterpolation_MultiLine4() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_MultiLine4() + => VerifyRefactoringAsync(""" public class C { void M() @@ -890,12 +837,10 @@ void M() } } """", index: 1); - } [Fact] - public async Task TestInterpolation_MultiLine4_A() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_MultiLine4_A() + => VerifyRefactoringAsync(""" public class C { void M() @@ -918,12 +863,10 @@ void M() } } """", index: 1); - } [Fact] - public async Task TestInterpolation_MultiLine5() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_MultiLine5() + => VerifyRefactoringAsync(""" public class C { void M() @@ -945,12 +888,10 @@ void M() } } """", index: 1); - } [Fact] - public async Task TestInterpolation_MultiLine5_A() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_MultiLine5_A() + => VerifyRefactoringAsync(""" public class C { void M() @@ -973,12 +914,10 @@ void M() } } """", index: 1); - } [Fact] - public async Task TestInterpolation_MultiLine6() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_MultiLine6() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1002,12 +941,10 @@ void M() } } """", index: 1); - } [Fact] - public async Task TestInterpolation_MultiLine6_A() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_MultiLine6_A() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1032,12 +969,10 @@ void M() } } """", index: 1); - } [Fact] - public async Task TestInterpolation_MultiLine7() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_MultiLine7() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1068,12 +1003,10 @@ void M() } } """"); - } [Fact] - public async Task TestInterpolation_MultiLine8() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_MultiLine8() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1096,12 +1029,10 @@ void M() } } """"); - } [Fact] - public async Task TestInterpolation_MultiLine9() - { - await VerifyRefactoringAsync(""" + public Task TestInterpolation_MultiLine9() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1122,12 +1053,10 @@ void M() } } """"); - } [Fact] - public async Task TestVerbatimSimpleString1() - { - await VerifyRefactoringAsync(""" + public Task TestVerbatimSimpleString1() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1144,12 +1073,10 @@ void M() } } """"); - } [Fact] - public async Task TestVerbatimSimpleString2() - { - await VerifyRefactoringAsync(""" + public Task TestVerbatimSimpleString2() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1166,22 +1093,18 @@ void M() } } """"); - } [Fact] - public async Task TestSimpleStringTopLevel() - { - await VerifyRefactoringAsync(""" + public Task TestSimpleStringTopLevel() + => VerifyRefactoringAsync(""" var v = [||]$"a"; """, """" var v = $"""a"""; """", outputKind: OutputKind.ConsoleApplication); - } [Fact] - public async Task TestStringWithQuoteInMiddle() - { - await VerifyRefactoringAsync(""" + public Task TestStringWithQuoteInMiddle() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1198,12 +1121,10 @@ void M() } } """"); - } [Fact] - public async Task TestVerbatimStringWithQuoteInMiddle1() - { - await VerifyRefactoringAsync(""" + public Task TestVerbatimStringWithQuoteInMiddle1() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1220,12 +1141,10 @@ void M() } } """"); - } [Fact] - public async Task TestVerbatimStringWithQuoteInMiddle2() - { - await VerifyRefactoringAsync(""" + public Task TestVerbatimStringWithQuoteInMiddle2() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1242,12 +1161,10 @@ void M() } } """"); - } [Fact] - public async Task TestStringWithQuoteAtStart() - { - await VerifyRefactoringAsync(""" + public Task TestStringWithQuoteAtStart() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1266,12 +1183,10 @@ void M() } } """"); - } [Fact] - public async Task TestVerbatimStringWithQuoteAtStart1() - { - await VerifyRefactoringAsync("""" + public Task TestVerbatimStringWithQuoteAtStart1() + => VerifyRefactoringAsync("""" public class C { void M() @@ -1290,12 +1205,10 @@ void M() } } """"); - } [Fact] - public async Task TestVerbatimStringWithQuoteAtStart2() - { - await VerifyRefactoringAsync("""" + public Task TestVerbatimStringWithQuoteAtStart2() + => VerifyRefactoringAsync("""" public class C { void M() @@ -1314,12 +1227,10 @@ void M() } } """"); - } [Fact] - public async Task TestStringWithQuoteAtEnd() - { - await VerifyRefactoringAsync(""" + public Task TestStringWithQuoteAtEnd() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1338,12 +1249,10 @@ void M() } } """"); - } [Fact] - public async Task TestVerbatimStringWithQuoteAtEnd1() - { - await VerifyRefactoringAsync("""" + public Task TestVerbatimStringWithQuoteAtEnd1() + => VerifyRefactoringAsync("""" public class C { void M() @@ -1362,12 +1271,10 @@ void M() } } """"); - } [Fact] - public async Task TestVerbatimStringWithQuoteAtEnd2() - { - await VerifyRefactoringAsync("""" + public Task TestVerbatimStringWithQuoteAtEnd2() + => VerifyRefactoringAsync("""" public class C { void M() @@ -1386,12 +1293,10 @@ void M() } } """"); - } [Fact] - public async Task TestStringWithNewLine() - { - await VerifyRefactoringAsync(""" + public Task TestStringWithNewLine() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1411,12 +1316,10 @@ void M() } } """"); - } [Fact] - public async Task TestVerbatimStringWithNewLine1() - { - await VerifyRefactoringAsync(""" + public Task TestVerbatimStringWithNewLine1() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1437,12 +1340,10 @@ void M() } } """"); - } [Fact] - public async Task TestVerbatimStringWithNewLine2() - { - await VerifyRefactoringAsync(""" + public Task TestVerbatimStringWithNewLine2() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1463,12 +1364,10 @@ void M() } } """"); - } [Fact] - public async Task TestStringWithNewLineAtStartAndEnd() - { - await VerifyRefactoringAsync(""" + public Task TestStringWithNewLineAtStartAndEnd() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1489,12 +1388,10 @@ void M() } } """"); - } [Fact] - public async Task TestVerbatimStringWithNewLineAtStartAndEnd1() - { - await VerifyRefactoringAsync(""" + public Task TestVerbatimStringWithNewLineAtStartAndEnd1() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1517,12 +1414,10 @@ void M() } } """"); - } [Fact] - public async Task TestVerbatimStringWithNewLineAtStartAndEnd2() - { - await VerifyRefactoringAsync(""" + public Task TestVerbatimStringWithNewLineAtStartAndEnd2() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1545,12 +1440,10 @@ void M() } } """"); - } [Fact] - public async Task TestNoIndentVerbatimStringWithNewLineAtStartAndEnd() - { - await VerifyRefactoringAsync(""" + public Task TestNoIndentVerbatimStringWithNewLineAtStartAndEnd() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1571,12 +1464,10 @@ void M() } } """", index: 1); - } [Fact] - public async Task TestIndentedString() - { - await VerifyRefactoringAsync(""" + public Task TestIndentedString() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1596,12 +1487,10 @@ void M() } } """"); - } [Fact] - public async Task TestWithoutLeadingWhitespace1() - { - await VerifyRefactoringAsync(""" + public Task TestWithoutLeadingWhitespace1() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1625,12 +1514,10 @@ select x } } """", index: 1); - } [Fact] - public async Task TestIndentedStringTopLevel() - { - await VerifyRefactoringAsync(""" + public Task TestIndentedStringTopLevel() + => VerifyRefactoringAsync(""" var v = [||]$"goo\r\nbar"; """, """" var v = $""" @@ -1638,12 +1525,10 @@ await VerifyRefactoringAsync(""" bar """; """", outputKind: OutputKind.ConsoleApplication); - } [Fact] - public async Task TestWithoutLeadingWhitespaceTopLevel() - { - await VerifyRefactoringAsync(""" + public Task TestWithoutLeadingWhitespaceTopLevel() + => VerifyRefactoringAsync(""" var v = [||]@$" from x in y where x > 0 @@ -1655,12 +1540,10 @@ where x > 0 select x """; """", index: 1, outputKind: OutputKind.ConsoleApplication); - } [Fact] - public async Task TestVerbatimIndentedString() - { - await VerifyRefactoringAsync(""" + public Task TestVerbatimIndentedString() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1681,12 +1564,10 @@ void M() } } """"); - } [Fact] - public async Task TestIndentedStringOnOwnLine() - { - await VerifyRefactoringAsync(""" + public Task TestIndentedStringOnOwnLine() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1708,12 +1589,10 @@ void M() } } """"); - } [Fact] - public async Task TestVerbatimIndentedStringOnOwnLine() - { - await VerifyRefactoringAsync(""" + public Task TestVerbatimIndentedStringOnOwnLine() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1736,12 +1615,10 @@ void M() } } """"); - } [Fact] - public async Task TestWithoutLeadingWhitespace2() - { - await VerifyRefactoringAsync(""" + public Task TestWithoutLeadingWhitespace2() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1765,12 +1642,10 @@ select x } } """", index: 1); - } [Fact] - public async Task TestWithoutLeadingWhitespace3() - { - await VerifyRefactoringAsync(""" + public Task TestWithoutLeadingWhitespace3() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1795,12 +1670,10 @@ select x } } """", index: 1); - } [Fact] - public async Task TestWithoutLeadingWhitespace4() - { - await VerifyRefactoringAsync(""" + public Task TestWithoutLeadingWhitespace4() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1825,12 +1698,10 @@ select x } } """", index: 1); - } [Fact] - public async Task TestWithoutLeadingWhitespace5() - { - await VerifyRefactoringAsync(""" + public Task TestWithoutLeadingWhitespace5() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1855,12 +1726,10 @@ select x } } """", index: 1); - } [Fact] - public async Task TestWithoutLeadingWhitespace6() - { - await VerifyRefactoringAsync(""" + public Task TestWithoutLeadingWhitespace6() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1889,12 +1758,10 @@ select x } } """", index: 1); - } [Fact] - public async Task TestWithoutLeadingWhitespace7() - { - await VerifyRefactoringAsync(""" + public Task TestWithoutLeadingWhitespace7() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1918,12 +1785,10 @@ select x } } """", index: 1); - } [Fact] - public async Task TestWithoutLeadingWhitespace7_A() - { - await VerifyRefactoringAsync(""" + public Task TestWithoutLeadingWhitespace7_A() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1946,12 +1811,10 @@ select x } } """", index: 1); - } [Fact] - public async Task TestWithoutLeadingWhitespace7_B() - { - await VerifyRefactoringAsync(""" + public Task TestWithoutLeadingWhitespace7_B() + => VerifyRefactoringAsync(""" public class C { void M() @@ -1975,12 +1838,10 @@ select x } } """", index: 1); - } [Fact] - public async Task TestWithoutLeadingWhitespace8() - { - await VerifyRefactoringAsync(""" + public Task TestWithoutLeadingWhitespace8() + => VerifyRefactoringAsync(""" public class C { void M() @@ -2003,12 +1864,10 @@ select x } } """", index: 1); - } [Fact] - public async Task TestWithNestedVerbatimString1() - { - await VerifyRefactoringAsync(""" + public Task TestWithNestedVerbatimString1() + => VerifyRefactoringAsync(""" public class C { void M() @@ -2043,12 +1902,10 @@ This needs stay indented } } """", index: 1); - } [Fact] - public async Task TestWithNestedVerbatimString2() - { - await VerifyRefactoringAsync(""" + public Task TestWithNestedVerbatimString2() + => VerifyRefactoringAsync(""" public class C { void M() @@ -2083,12 +1940,10 @@ This should not prevent dedentation } } """", index: 1); - } [Fact] - public async Task TestWithNestedVerbatimString3() - { - await VerifyRefactoringAsync(""" + public Task TestWithNestedVerbatimString3() + => VerifyRefactoringAsync(""" public class C { void M() @@ -2127,12 +1982,10 @@ The whitespace above/below me needs to stay } } """", index: 1); - } [Fact] - public async Task TestWithNestedVerbatimString4() - { - await VerifyRefactoringAsync(""" + public Task TestWithNestedVerbatimString4() + => VerifyRefactoringAsync(""" public class C { void M() @@ -2171,12 +2024,10 @@ The whitespace above/below me needs to stay } } """", index: 1); - } [Fact] - public async Task TestWithNestedVerbatimString5() - { - await VerifyRefactoringAsync(""" + public Task TestWithNestedVerbatimString5() + => VerifyRefactoringAsync(""" public class C { void M() @@ -2211,12 +2062,10 @@ This needs to stay put } } """", index: 1); - } [Fact] - public async Task TestWithNestedVerbatimString6() - { - await VerifyRefactoringAsync(""" + public Task TestWithNestedVerbatimString6() + => VerifyRefactoringAsync(""" public class C { void M() @@ -2251,12 +2100,10 @@ This needs to stay put } } """", index: 1); - } [Fact] - public async Task TestWithNestedVerbatimString7() - { - await VerifyRefactoringAsync(""" + public Task TestWithNestedVerbatimString7() + => VerifyRefactoringAsync(""" public class C { void M() @@ -2287,12 +2134,10 @@ select x } } """", index: 1); - } [Fact] - public async Task TestWithNestedVerbatimString8() - { - await VerifyRefactoringAsync(""" + public Task TestWithNestedVerbatimString8() + => VerifyRefactoringAsync(""" public class C { void M() @@ -2323,5 +2168,4 @@ select x } } """", index: 1); - } } diff --git a/src/Features/CSharpTest/ConvertToRawString/ConvertInterpolatedStringToRawString_FixAllTests.cs b/src/Features/CSharpTest/ConvertToRawString/ConvertInterpolatedStringToRawString_FixAllTests.cs index f1d3be3104043..00b9efd29b8f1 100644 --- a/src/Features/CSharpTest/ConvertToRawString/ConvertInterpolatedStringToRawString_FixAllTests.cs +++ b/src/Features/CSharpTest/ConvertToRawString/ConvertInterpolatedStringToRawString_FixAllTests.cs @@ -19,9 +19,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor => new ConvertStringToRawStringCodeRefactoringProvider(); [Fact] - public async Task FixAllInDocument_SingleLine() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument_SingleLine() + => TestInRegularAndScriptAsync( """ class C { @@ -106,12 +105,10 @@ where x2 > 0 } } """"); - } [Fact] - public async Task FixAllInDocument_MultiLine() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument_MultiLine() + => TestInRegularAndScriptAsync( """ class C { @@ -214,12 +211,10 @@ select x2 } } """"); - } [Fact] - public async Task FixAllInDocument_MultiLineWithoutLeadingWhitespace() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument_MultiLineWithoutLeadingWhitespace() + => TestInRegularAndScriptAsync( """ class C { @@ -312,12 +307,10 @@ select x2 } } """", index: 1); - } [Fact] - public async Task FixAllInProject() - { - await TestInRegularAndScriptAsync( + public Task FixAllInProject() + => TestInRegularAndScriptAsync( """ @@ -394,12 +387,10 @@ void M3() """"); - } [Fact] - public async Task FixAllInSolution() - { - await TestInRegularAndScriptAsync( + public Task FixAllInSolution() + => TestInRegularAndScriptAsync( """ @@ -476,12 +467,10 @@ void M3() """"); - } [Fact] - public async Task FixAllInContainingMember() - { - await TestInRegularAndScriptAsync( + public Task FixAllInContainingMember() + => TestInRegularAndScriptAsync( """ class C { @@ -532,12 +521,10 @@ void M() } } """"); - } [Fact] - public async Task FixAllInContainingType() - { - await TestInRegularAndScriptAsync( + public Task FixAllInContainingType() + => TestInRegularAndScriptAsync( """ partial class C { @@ -606,12 +593,10 @@ void M3() } } """"); - } [Fact] - public async Task FixAllInContainingType_AcrossFiles() - { - await TestInRegularAndScriptAsync( + public Task FixAllInContainingType_AcrossFiles() + => TestInRegularAndScriptAsync( """ @@ -718,12 +703,10 @@ void M3() """"); - } [Fact] - public async Task FixAllCommonRoslynTestPattern1() - { - await TestInRegularAndScript1Async( + public Task FixAllCommonRoslynTestPattern1() + => TestInRegularAndScript1Async( """ class C { @@ -759,12 +742,10 @@ class Y } """", new TestParameters(treatPositionIndicatorsAsCode: true)); - } [Fact] - public async Task FixAllCommonRoslynTestPattern1_B() - { - await TestInRegularAndScript1Async( + public Task FixAllCommonRoslynTestPattern1_B() + => TestInRegularAndScript1Async( """ class C { @@ -798,12 +779,10 @@ class Y } """", new TestParameters(treatPositionIndicatorsAsCode: true)); - } [Fact] - public async Task FixAllCommonRoslynTestPattern2() - { - await TestInRegularAndScript1Async( + public Task FixAllCommonRoslynTestPattern2() + => TestInRegularAndScript1Async( """ class C { @@ -841,12 +820,10 @@ class Y } """", index: 1, new TestParameters(treatPositionIndicatorsAsCode: true)); - } [Fact] - public async Task FixAllCommonRoslynTestPattern2_B() - { - await TestInRegularAndScript1Async( + public Task FixAllCommonRoslynTestPattern2_B() + => TestInRegularAndScript1Async( """ class C { @@ -882,12 +859,10 @@ class Y } """", index: 1, new TestParameters(treatPositionIndicatorsAsCode: true)); - } [Fact] - public async Task FixAllCommonRoslynTestPattern3() - { - await TestInRegularAndScript1Async( + public Task FixAllCommonRoslynTestPattern3() + => TestInRegularAndScript1Async( """ class C { @@ -927,12 +902,10 @@ class Y } """", index: 1, new TestParameters(treatPositionIndicatorsAsCode: true)); - } [Fact] - public async Task FixAllCommonRoslynTestPattern3_B() - { - await TestInRegularAndScript1Async( + public Task FixAllCommonRoslynTestPattern3_B() + => TestInRegularAndScript1Async( """ class C { @@ -970,12 +943,10 @@ class Y } """", index: 1, new TestParameters(treatPositionIndicatorsAsCode: true)); - } [Fact] - public async Task FixAllCommonRoslynTestPattern4() - { - await TestInRegularAndScript1Async( + public Task FixAllCommonRoslynTestPattern4() + => TestInRegularAndScript1Async( """ class C { @@ -1017,12 +988,10 @@ class Y } """", index: 1, new TestParameters(treatPositionIndicatorsAsCode: true)); - } [Fact] - public async Task FixAllCommonRoslynTestPattern5() - { - await TestInRegularAndScript1Async( + public Task FixAllCommonRoslynTestPattern5() + => TestInRegularAndScript1Async( """ class C { @@ -1062,12 +1031,10 @@ class Y } """", index: 1, new TestParameters(treatPositionIndicatorsAsCode: true)); - } [Fact] - public async Task FixAllCommonRoslynTestPattern6() - { - await TestInRegularAndScript1Async( + public Task FixAllCommonRoslynTestPattern6() + => TestInRegularAndScript1Async( """ class C { @@ -1107,5 +1074,4 @@ class Y } """", index: 1, new TestParameters(treatPositionIndicatorsAsCode: true)); - } } diff --git a/src/Features/CSharpTest/ConvertToRawString/ConvertRegularStringToRawStringTests.cs b/src/Features/CSharpTest/ConvertToRawString/ConvertRegularStringToRawStringTests.cs index a5ec7c8c1d4f4..31a03be16e168 100644 --- a/src/Features/CSharpTest/ConvertToRawString/ConvertRegularStringToRawStringTests.cs +++ b/src/Features/CSharpTest/ConvertToRawString/ConvertRegularStringToRawStringTests.cs @@ -18,9 +18,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertToRawString; [Trait(Traits.Feature, Traits.Features.CodeActionsConvertToRawString)] public sealed class ConvertRegularStringToRawStringTests { - private static async Task VerifyRefactoringAsync(string testCode, string fixedCode, int index = 0, OutputKind outputKind = OutputKind.DynamicallyLinkedLibrary) - { - await new VerifyCS.Test + private static Task VerifyRefactoringAsync(string testCode, string fixedCode, int index = 0, OutputKind outputKind = OutputKind.DynamicallyLinkedLibrary) + => new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, @@ -31,7 +30,6 @@ private static async Task VerifyRefactoringAsync(string testCode, string fixedCo OutputKind = outputKind, }, }.RunAsync(); - } [Fact] public async Task TestNotInDirective() @@ -108,9 +106,8 @@ void M() } [Fact] - public async Task TestOnCombinedSurrogate() - { - await VerifyRefactoringAsync( + public Task TestOnCombinedSurrogate() + => VerifyRefactoringAsync( """ public class C { @@ -129,7 +126,6 @@ void M() } } """"); - } [Fact] public async Task TestNotOnNullChar() @@ -164,9 +160,8 @@ void M() } [Fact] - public async Task TestSimpleString() - { - await VerifyRefactoringAsync(""" + public Task TestSimpleString() + => VerifyRefactoringAsync(""" public class C { void M() @@ -183,12 +178,10 @@ void M() } } """"); - } [Fact] - public async Task TestVerbatimSimpleString() - { - await VerifyRefactoringAsync(""" + public Task TestVerbatimSimpleString() + => VerifyRefactoringAsync(""" public class C { void M() @@ -205,22 +198,18 @@ void M() } } """"); - } [Fact] - public async Task TestSimpleStringTopLevel() - { - await VerifyRefactoringAsync(""" + public Task TestSimpleStringTopLevel() + => VerifyRefactoringAsync(""" var v = [||]"a"; """, """" var v = """a"""; """", outputKind: OutputKind.ConsoleApplication); - } [Fact] - public async Task TestStringWithQuoteInMiddle() - { - await VerifyRefactoringAsync(""" + public Task TestStringWithQuoteInMiddle() + => VerifyRefactoringAsync(""" public class C { void M() @@ -237,12 +226,10 @@ void M() } } """"); - } [Fact] - public async Task TestVerbatimStringWithQuoteInMiddle() - { - await VerifyRefactoringAsync(""" + public Task TestVerbatimStringWithQuoteInMiddle() + => VerifyRefactoringAsync(""" public class C { void M() @@ -259,12 +246,10 @@ void M() } } """"); - } [Fact] - public async Task TestStringWithQuoteAtStart() - { - await VerifyRefactoringAsync(""" + public Task TestStringWithQuoteAtStart() + => VerifyRefactoringAsync(""" public class C { void M() @@ -283,12 +268,10 @@ void M() } } """"); - } [Fact] - public async Task TestVerbatimStringWithQuoteAtStart() - { - await VerifyRefactoringAsync("""" + public Task TestVerbatimStringWithQuoteAtStart() + => VerifyRefactoringAsync("""" public class C { void M() @@ -307,12 +290,10 @@ void M() } } """"); - } [Fact] - public async Task TestStringWithQuoteAtEnd() - { - await VerifyRefactoringAsync(""" + public Task TestStringWithQuoteAtEnd() + => VerifyRefactoringAsync(""" public class C { void M() @@ -331,12 +312,10 @@ void M() } } """"); - } [Fact] - public async Task TestVerbatimStringWithQuoteAtEnd() - { - await VerifyRefactoringAsync("""" + public Task TestVerbatimStringWithQuoteAtEnd() + => VerifyRefactoringAsync("""" public class C { void M() @@ -355,12 +334,10 @@ void M() } } """"); - } [Fact] - public async Task TestStringWithNewLine() - { - await VerifyRefactoringAsync(""" + public Task TestStringWithNewLine() + => VerifyRefactoringAsync(""" public class C { void M() @@ -380,12 +357,10 @@ void M() } } """"); - } [Fact] - public async Task TestVerbatimStringWithNewLine() - { - await VerifyRefactoringAsync(""" + public Task TestVerbatimStringWithNewLine() + => VerifyRefactoringAsync(""" public class C { void M() @@ -406,12 +381,10 @@ void M() } } """"); - } [Fact] - public async Task TestStringWithNewLineAtStartAndEnd() - { - await VerifyRefactoringAsync(""" + public Task TestStringWithNewLineAtStartAndEnd() + => VerifyRefactoringAsync(""" public class C { void M() @@ -432,12 +405,10 @@ void M() } } """"); - } [Fact] - public async Task TestVerbatimStringWithNewLineAtStartAndEnd() - { - await VerifyRefactoringAsync(""" + public Task TestVerbatimStringWithNewLineAtStartAndEnd() + => VerifyRefactoringAsync(""" public class C { void M() @@ -460,12 +431,10 @@ void M() } } """"); - } [Fact] - public async Task TestNoIndentVerbatimStringWithNewLineAtStartAndEnd() - { - await VerifyRefactoringAsync(""" + public Task TestNoIndentVerbatimStringWithNewLineAtStartAndEnd() + => VerifyRefactoringAsync(""" public class C { void M() @@ -486,12 +455,10 @@ void M() } } """", index: 1); - } [Fact] - public async Task TestIndentedString() - { - await VerifyRefactoringAsync(""" + public Task TestIndentedString() + => VerifyRefactoringAsync(""" public class C { void M() @@ -511,12 +478,10 @@ void M() } } """"); - } [Fact] - public async Task TestWithoutLeadingWhitespace1() - { - await VerifyRefactoringAsync(""" + public Task TestWithoutLeadingWhitespace1() + => VerifyRefactoringAsync(""" public class C { void M() @@ -540,12 +505,10 @@ select x } } """", index: 1); - } [Fact] - public async Task TestIndentedStringTopLevel() - { - await VerifyRefactoringAsync(""" + public Task TestIndentedStringTopLevel() + => VerifyRefactoringAsync(""" var v = [||]"goo\r\nbar"; """, """" var v = """ @@ -553,12 +516,10 @@ await VerifyRefactoringAsync(""" bar """; """", outputKind: OutputKind.ConsoleApplication); - } [Fact] - public async Task TestWithoutLeadingWhitespaceTopLevel() - { - await VerifyRefactoringAsync(""" + public Task TestWithoutLeadingWhitespaceTopLevel() + => VerifyRefactoringAsync(""" var v = [||]@" from x in y where x > 0 @@ -570,12 +531,10 @@ where x > 0 select x """; """", index: 1, outputKind: OutputKind.ConsoleApplication); - } [Fact] - public async Task TestVerbatimIndentedString() - { - await VerifyRefactoringAsync(""" + public Task TestVerbatimIndentedString() + => VerifyRefactoringAsync(""" public class C { void M() @@ -596,12 +555,10 @@ void M() } } """"); - } [Fact] - public async Task TestIndentedStringOnOwnLine() - { - await VerifyRefactoringAsync(""" + public Task TestIndentedStringOnOwnLine() + => VerifyRefactoringAsync(""" public class C { void M() @@ -623,12 +580,10 @@ void M() } } """"); - } [Fact] - public async Task TestVerbatimIndentedStringOnOwnLine() - { - await VerifyRefactoringAsync(""" + public Task TestVerbatimIndentedStringOnOwnLine() + => VerifyRefactoringAsync(""" public class C { void M() @@ -651,12 +606,10 @@ void M() } } """"); - } [Fact] - public async Task TestWithoutLeadingWhitespace2() - { - await VerifyRefactoringAsync(""" + public Task TestWithoutLeadingWhitespace2() + => VerifyRefactoringAsync(""" public class C { void M() @@ -680,12 +633,10 @@ select x } } """", index: 1); - } [Fact] - public async Task TestWithoutLeadingWhitespace3() - { - await VerifyRefactoringAsync(""" + public Task TestWithoutLeadingWhitespace3() + => VerifyRefactoringAsync(""" public class C { void M() @@ -710,12 +661,10 @@ select x } } """", index: 1); - } [Fact] - public async Task TestWithoutLeadingWhitespace4() - { - await VerifyRefactoringAsync(""" + public Task TestWithoutLeadingWhitespace4() + => VerifyRefactoringAsync(""" public class C { void M() @@ -740,12 +689,10 @@ select x } } """", index: 1); - } [Fact] - public async Task TestWithoutLeadingWhitespace5() - { - await VerifyRefactoringAsync(""" + public Task TestWithoutLeadingWhitespace5() + => VerifyRefactoringAsync(""" public class C { void M() @@ -770,12 +717,10 @@ select x } } """", index: 1); - } [Fact] - public async Task TestWithoutLeadingWhitespace6() - { - await VerifyRefactoringAsync(""" + public Task TestWithoutLeadingWhitespace6() + => VerifyRefactoringAsync(""" public class C { void M() @@ -804,5 +749,4 @@ select x } } """", index: 1); - } } diff --git a/src/Features/CSharpTest/ConvertToRawString/ConvertRegularStringToRawString_FixAllTests.cs b/src/Features/CSharpTest/ConvertToRawString/ConvertRegularStringToRawString_FixAllTests.cs index 482411b8e8f64..b0215f0afe68e 100644 --- a/src/Features/CSharpTest/ConvertToRawString/ConvertRegularStringToRawString_FixAllTests.cs +++ b/src/Features/CSharpTest/ConvertToRawString/ConvertRegularStringToRawString_FixAllTests.cs @@ -20,9 +20,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor => new ConvertStringToRawStringCodeRefactoringProvider(); [Fact] - public async Task FixAllInDocument_SingleLine() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument_SingleLine() + => TestInRegularAndScriptAsync( """ class C { @@ -107,12 +106,10 @@ where x2 > 0 } } """"); - } [Fact] - public async Task FixAllInDocument_MultiLine() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument_MultiLine() + => TestInRegularAndScriptAsync( """ class C { @@ -215,12 +212,10 @@ select x2 } } """"); - } [Fact] - public async Task FixAllInDocument_MultiLineWithoutLeadingWhitespace() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument_MultiLineWithoutLeadingWhitespace() + => TestInRegularAndScriptAsync( """ class C { @@ -313,12 +308,10 @@ select x2 } } """", index: 1); - } [Fact] - public async Task FixAllInProject() - { - await TestInRegularAndScriptAsync( + public Task FixAllInProject() + => TestInRegularAndScriptAsync( """ @@ -395,12 +388,10 @@ void M3() """"); - } [Fact] - public async Task FixAllInSolution() - { - await TestInRegularAndScriptAsync( + public Task FixAllInSolution() + => TestInRegularAndScriptAsync( """ @@ -477,12 +468,10 @@ void M3() """"); - } [Fact] - public async Task FixAllInContainingMember() - { - await TestInRegularAndScriptAsync( + public Task FixAllInContainingMember() + => TestInRegularAndScriptAsync( """ class C { @@ -533,12 +522,10 @@ void M() } } """"); - } [Fact] - public async Task FixAllInContainingType() - { - await TestInRegularAndScriptAsync( + public Task FixAllInContainingType() + => TestInRegularAndScriptAsync( """ partial class C { @@ -607,12 +594,10 @@ void M3() } } """"); - } [Fact] - public async Task FixAllInContainingType_AcrossFiles() - { - await TestInRegularAndScriptAsync( + public Task FixAllInContainingType_AcrossFiles() + => TestInRegularAndScriptAsync( """ @@ -719,12 +704,10 @@ void M3() """"); - } [Fact] - public async Task FixAllCommonRoslynTestPattern1() - { - await TestInRegularAndScriptAsync( + public Task FixAllCommonRoslynTestPattern1() + => TestInRegularAndScriptAsync( """ class C { @@ -759,12 +742,10 @@ class Y } } """"); - } [Fact] - public async Task FixAllCommonRoslynTestPattern1_B() - { - await TestInRegularAndScriptAsync( + public Task FixAllCommonRoslynTestPattern1_B() + => TestInRegularAndScriptAsync( """ class C { @@ -797,12 +778,10 @@ class Y } } """"); - } [Fact] - public async Task FixAllCommonRoslynTestPattern2() - { - await TestInRegularAndScriptAsync( + public Task FixAllCommonRoslynTestPattern2() + => TestInRegularAndScriptAsync( """ class C { @@ -839,12 +818,10 @@ class Y } } """", index: 1); - } [Fact] - public async Task FixAllCommonRoslynTestPattern2_B() - { - await TestInRegularAndScriptAsync( + public Task FixAllCommonRoslynTestPattern2_B() + => TestInRegularAndScriptAsync( """ class C { @@ -879,12 +856,10 @@ class Y } } """", index: 1); - } [Fact] - public async Task FixAllCommonRoslynTestPattern3() - { - await TestInRegularAndScriptAsync( + public Task FixAllCommonRoslynTestPattern3() + => TestInRegularAndScriptAsync( """ class C { @@ -923,12 +898,10 @@ class Y } } """", index: 1); - } [Fact] - public async Task FixAllCommonRoslynTestPattern3_B() - { - await TestInRegularAndScriptAsync( + public Task FixAllCommonRoslynTestPattern3_B() + => TestInRegularAndScriptAsync( """ class C { @@ -965,12 +938,10 @@ class Y } } """", index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70209")] - public async Task FixAllInDocument_MultiLineShouldNotImpactExplicitEscapedString() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument_MultiLineShouldNotImpactExplicitEscapedString() + => TestInRegularAndScriptAsync( """ class C { @@ -999,12 +970,10 @@ void M() } } """"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70209")] - public async Task FixAllInDocument_EscapedCanAffectMultiLine() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument_EscapedCanAffectMultiLine() + => TestInRegularAndScriptAsync( """ class C { @@ -1036,12 +1005,10 @@ void M() } } """"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70209")] - public async Task FixAllInDocument_EscapedCanAffectMultiLine2() - { - await TestInRegularAndScriptAsync( + public Task FixAllInDocument_EscapedCanAffectMultiLine2() + => TestInRegularAndScriptAsync( """ class C { @@ -1078,5 +1045,4 @@ void M() } } """"); - } } diff --git a/src/Features/CSharpTest/ConvertToRecord/ConvertToRecordCodeRefactoringTests.cs b/src/Features/CSharpTest/ConvertToRecord/ConvertToRecordCodeRefactoringTests.cs index f43705061298e..a0af4acb581da 100644 --- a/src/Features/CSharpTest/ConvertToRecord/ConvertToRecordCodeRefactoringTests.cs +++ b/src/Features/CSharpTest/ConvertToRecord/ConvertToRecordCodeRefactoringTests.cs @@ -27,7 +27,7 @@ public sealed class ConvertToRecordCodeRefactoringTests [Fact] public async Task VerifyRefactoringAndFixHaveSameEquivalenceKey() { - var initialMarkupCodeFix = """ + var changedMarkup = """ namespace N { public record B @@ -35,13 +35,13 @@ public record B public int Foo { get; init; } } - public class C : [|B|] - { - public int P { get; init; } - } + public record C(int P) : B; } """; - var initialMarkupRefactoring = """ + CodeAction? codeAction = null; + var refactoringTest = new RefactoringTest + { + TestCode = """ namespace N { public record B @@ -54,8 +54,13 @@ public class [|C : {|CS8865:B|}|] public int P { get; init; } } } - """; - var changedMarkup = """ + """, + FixedCode = changedMarkup, + CodeActionVerifier = Verify, + }; + var codeFixTest = new CodeFixTest + { + TestCode = """ namespace N { public record B @@ -63,19 +68,12 @@ public record B public int Foo { get; init; } } - public record C(int P) : B; + public class C : [|B|] + { + public int P { get; init; } + } } - """; - CodeAction? codeAction = null; - var refactoringTest = new RefactoringTest - { - TestCode = initialMarkupRefactoring, - FixedCode = changedMarkup, - CodeActionVerifier = Verify, - }; - var codeFixTest = new CodeFixTest - { - TestCode = initialMarkupCodeFix, + """, FixedCode = changedMarkup, CodeActionVerifier = Verify, }; @@ -98,9 +96,8 @@ void Verify(CodeAction action, IVerifier _) } [Fact] - public async Task TestNoProperties_NoAction() - { - var initialMarkup = """ + public Task TestNoProperties_NoAction() + => TestNoRefactoringAsync(""" namespace N { public class [|C|] @@ -109,14 +106,11 @@ public class [|C|] public int f = 0; } } - """; - await TestNoRefactoringAsync(initialMarkup); - } + """); [Fact] - public async Task TestPartialClass_NoAction() - { - var initialMarkup = """ + public Task TestPartialClass_NoAction() + => TestNoRefactoringAsync(""" namespace N { public partial class [|C|] @@ -129,14 +123,11 @@ public partial class C public bool B { get; init; } } } - """; - await TestNoRefactoringAsync(initialMarkup); - } + """); [Fact] - public async Task TestExplicitProperty_NoAction1() - { - var initialMarkup = """ + public Task TestExplicitProperty_NoAction1() + => TestNoRefactoringAsync(""" namespace N { public class [|C|] @@ -150,14 +141,11 @@ public int P } } } - """; - await TestNoRefactoringAsync(initialMarkup); - } + """); [Fact] - public async Task TestExplicitProperty_NoAction2() - { - var initialMarkup = """ + public Task TestExplicitProperty_NoAction2() + => TestNoRefactoringAsync(""" namespace N { public class [|C|] @@ -178,14 +166,11 @@ public int P } } } - """; - await TestNoRefactoringAsync(initialMarkup); - } + """); [Fact] - public async Task TestExplicitProperty_NoAction3() - { - var initialMarkup = """ + public Task TestExplicitProperty_NoAction3() + => TestNoRefactoringAsync(""" namespace N { public class [|C|] @@ -193,14 +178,11 @@ public class [|C|] public int P { get; init; } = 4; } } - """; - await TestNoRefactoringAsync(initialMarkup); - } + """); [Fact] - public async Task TestPrivateGetProperty_NoAction() - { - var initialMarkup = """ + public Task TestPrivateGetProperty_NoAction() + => TestNoRefactoringAsync(""" namespace N { public class [|C|] @@ -208,14 +190,11 @@ public class [|C|] public int P { private get; init; } } } - """; - await TestNoRefactoringAsync(initialMarkup); - } + """); [Fact] - public async Task TestSetProperty() - { - var initialMarkup = """ + public Task TestSetProperty() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -223,20 +202,16 @@ public class [|C|] public int P { get; set; } } } - """; - var fixedMarkup = """ + """, """ namespace N { public record [|C|](int P); } - """; - await TestRefactoringAsync(initialMarkup, fixedMarkup); - } + """); [Fact] - public async Task TestInitPropertyOnStruct() - { - var initialMarkup = """ + public Task TestInitPropertyOnStruct() + => TestRefactoringAsync(""" namespace N { public struct [|C|] @@ -244,8 +219,7 @@ public struct [|C|] public int P { get; init; } } } - """; - var fixedMarkup = """ + """, """ namespace N { public record struct [|C|](int P) @@ -253,14 +227,11 @@ public record struct [|C|](int P) public int P { get; init; } = P; } } - """; - await TestRefactoringAsync(initialMarkup, fixedMarkup); - } + """); [Fact] - public async Task TestPrivateSetProperty() - { - var initialMarkup = """ + public Task TestPrivateSetProperty() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -268,8 +239,7 @@ public class [|C|] public int P { get; private set; } } } - """; - var fixedMarkup = """ + """, """ namespace N { public record [|C|](int P) @@ -277,14 +247,11 @@ public record [|C|](int P) public int P { get; private set; } = P; } } - """; - await TestRefactoringAsync(initialMarkup, fixedMarkup); - } + """); [Fact] - public async Task TestMoveSimpleProperty() - { - var initialMarkup = """ + public Task TestMoveSimpleProperty() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -292,20 +259,16 @@ public class [|C|] public int P { get; init; } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestReadonlyProperty() - { - var initialMarkup = """ + public Task TestReadonlyProperty() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -313,20 +276,16 @@ public class [|C|] public int P { get; } } } - """; - var fixedMarkup = """ + """, """ namespace N { public record [|C|](int P); } - """; - await TestRefactoringAsync(initialMarkup, fixedMarkup); - } + """); [Fact] - public async Task TestInitPropertyOnReadonlyStruct() - { - var initialMarkup = """ + public Task TestInitPropertyOnReadonlyStruct() + => TestRefactoringAsync(""" namespace N { public readonly struct [|C|] @@ -334,20 +293,16 @@ public readonly struct [|C|] public int P { get; init; } } } - """; - var fixedMarkup = """ + """, """ namespace N { public readonly record struct [|C|](int P); } - """; - await TestRefactoringAsync(initialMarkup, fixedMarkup); - } + """); [Fact] - public async Task TestMovePropertySimpleInheritance() - { - var initialMarkup = """ + public Task TestMovePropertySimpleInheritance() + => TestRefactoringAsync(""" namespace N { public class B @@ -359,13 +314,7 @@ public class [|C|] : B public int P { get; init; } } } - """; - // three of the same error on C because the generated - // EqualityConstract, Equals, and PrintMembers are all declared override - // and there's nothing to override. - // The other errors are copy constructor expected in B, and the - // "records can't inherit from class" on B as well - var changedMarkup = """ + """, """ namespace N { public class B @@ -374,14 +323,11 @@ public class B public record {|CS0115:{|CS0115:{|CS0115:{|CS8867:C|}|}|}|}(int P) : {|CS8864:B|}; } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertySimpleRecordInheritance() - { - var initialMarkup = """ + public Task TestMovePropertySimpleRecordInheritance() + => TestRefactoringAsync(""" namespace N { public record B @@ -394,8 +340,7 @@ public class [|C|] : {|CS8865:B|} public int P { get; init; } } } - """; - var changedMarkup = """ + """, """ namespace N { public record B @@ -405,14 +350,11 @@ public record B public record C(int P) : B; } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertyPositionalParameterRecordInheritance() - { - var initialMarkup = """ + public Task TestMovePropertyPositionalParameterRecordInheritance() + => TestRefactoringAsync(""" namespace N { public record B(int Foo, int Bar); @@ -422,22 +364,18 @@ public class [|{|CS1729:C|}|] : {|CS8865:B|} public int P { get; init; } } } - """; - var changedMarkup = """ + """, """ namespace N { public record B(int Foo, int Bar); public record C(int Foo, int Bar, int P) : B(Foo, Bar); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertyPositionalParameterRecordInheritanceWithComments() - { - var initialMarkup = """ + public Task TestMovePropertyPositionalParameterRecordInheritanceWithComments() + => TestRefactoringAsync(""" namespace N { /// B @@ -452,8 +390,7 @@ public class [|{|CS1729:C|}|] : {|CS8865:B|} public int P { get; init; } } } - """; - var changedMarkup = """ + """, """ namespace N { /// B @@ -467,14 +404,11 @@ public record B(int Foo, int Bar); /// P can be initialized public record C(int Foo, int Bar, int P) : B(Foo, Bar); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertyAndReorderWithPositionalParameterRecordInheritance() - { - var initialMarkup = """ + public Task TestMovePropertyAndReorderWithPositionalParameterRecordInheritance() + => TestRefactoringAsync(""" namespace N { public record B(int Foo, int Bar); @@ -491,22 +425,18 @@ public class [|C|] : {|CS8865:B|} } } } - """; - var changedMarkup = """ + """, """ namespace N { public record B(int Foo, int Bar); public record C(int P, int Bar, int Foo) : B(Foo, Bar); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertySimpleInterfaceInheritance() - { - var initialMarkup = """ + public Task TestMovePropertySimpleInterfaceInheritance() + => TestRefactoringAsync(""" namespace N { public interface IInterface @@ -524,8 +454,7 @@ public int Foo() } } } - """; - var changedMarkup = """ + """, """ namespace N { public interface IInterface @@ -541,14 +470,11 @@ public int Foo() } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMoveMultiplePropertiesWithInterfaceImplementation() - { - var initialMarkup = """ + public Task TestMoveMultiplePropertiesWithInterfaceImplementation() + => TestRefactoringAsync(""" using System; namespace N @@ -561,8 +487,7 @@ public class [|C|] : IComparable public int CompareTo(object? other) => 0; } } - """; - var changedMarkup = """ + """, """ using System; namespace N @@ -572,14 +497,11 @@ public record C(int P, bool B) : IComparable public int CompareTo(object? other) => 0; } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMoveMultipleProperties() - { - var initialMarkup = """ + public Task TestMoveMultipleProperties() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -588,20 +510,16 @@ public class [|C|] public bool B { get; init; } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMoveMultiplePropertiesOnStruct() - { - var initialMarkup = """ + public Task TestMoveMultiplePropertiesOnStruct() + => TestRefactoringAsync(""" namespace N { public struct [|C|] @@ -610,20 +528,16 @@ public struct [|C|] public bool B { get; set; } } } - """; - var changedMarkup = """ + """, """ namespace N { public record struct C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMoveMultiplePropertiesOnReadonlyStruct() - { - var initialMarkup = """ + public Task TestMoveMultiplePropertiesOnReadonlyStruct() + => TestRefactoringAsync(""" namespace N { public readonly struct [|C|] @@ -632,21 +546,17 @@ public readonly struct [|C|] public bool B { get; init; } } } - """; - var changedMarkup = """ + """, """ namespace N { public readonly record struct C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); // if there are both init and set properties, convert both but keep set property override [Fact] - public async Task TestSetAndInitProperties() - { - var initialMarkup = """ + public Task TestSetAndInitProperties() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -656,8 +566,7 @@ public class [|C|] public int Q { get; init; } } } - """; - var fixedMarkup = """ + """, """ namespace N { public record [|C|](int P, int Q) @@ -665,14 +574,11 @@ public record [|C|](int P, int Q) public int P { get; set; } = P; } } - """; - await TestRefactoringAsync(initialMarkup, fixedMarkup); - } + """); [Fact] - public async Task TestMoveMultiplePropertiesOnGeneric() - { - var initialMarkup = """ + public Task TestMoveMultiplePropertiesOnGeneric() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -681,20 +587,16 @@ public class [|C|] public TB? B { get; init; } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(TA? P, TB? B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMoveMultiplePropertiesOnGenericWithConstraints() - { - var initialMarkup = """ + public Task TestMoveMultiplePropertiesOnGenericWithConstraints() + => TestRefactoringAsync(""" using System; using System.Collections.Generic; @@ -708,8 +610,7 @@ public class [|C|] public TB? B { get; init; } } } - """; - var changedMarkup = """ + """, """ using System; using System.Collections.Generic; @@ -718,14 +619,11 @@ namespace N public record C(TA? P, TB? B) where TA : Exception where TB : IEnumerable; } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesWithAttributes() - { - var initialMarkup = """ + public Task TestMovePropertiesWithAttributes() + => TestRefactoringAsync(""" using System; namespace N @@ -739,22 +637,18 @@ public class [|C|] public bool B { get; init; } } } - """; - var changedMarkup = """ + """, """ using System; namespace N { public record C([property: Obsolete("P is Obsolete", error: true)] int P, [property: Obsolete("B will be obsolete, error: false")] bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesWithAttributesAndComments1() - { - var initialMarkup = """ + public Task TestMovePropertiesWithAttributesAndComments1() + => TestRefactoringAsync(""" using System; namespace N @@ -770,8 +664,7 @@ public class [|C|] public bool B { get; init; } } } - """; - var changedMarkup = """ + """, """ using System; namespace N @@ -780,14 +673,11 @@ namespace N // comment after public record C([property: Obsolete("P is Obsolete", error: true)] int P, [property: Obsolete("B will be obsolete, error: false")] bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesWithAttributesAndComments2() - { - var initialMarkup = """ + public Task TestMovePropertiesWithAttributesAndComments2() + => TestRefactoringAsync(""" using System; namespace N @@ -801,22 +691,18 @@ public class [|C|] public bool B { get; init; } } } - """; - var changedMarkup = """ + """, """ using System; namespace N { public record C([/*comment before*/ property: Obsolete("P is Obsolete", error: true)] int P, [property: Obsolete("B will be obsolete, error: false") /* comment after*/] bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteSimpleEquals1() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteSimpleEquals1() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -830,20 +716,16 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteSimpleEqualsWithFields() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteSimpleEqualsWithFields() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -858,8 +740,7 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B) @@ -867,16 +748,11 @@ public record C(int P, bool B) private int num = 10; } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndKeepSimpleEqualsWithConstFields() - { - // we only want users to compare all instance fields of the type and no more - // comparing a static/const value, although it's always true, is unexpected here - var initialMarkup = """ + public Task TestMovePropertiesAndKeepSimpleEqualsWithConstFields() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -891,8 +767,7 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B) @@ -905,14 +780,11 @@ public record C(int P, bool B) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteSimpleEqualsWithConstAndStaticFieldsAndProps() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteSimpleEqualsWithConstAndStaticFieldsAndProps() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -929,8 +801,7 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B) @@ -940,14 +811,11 @@ public record C(int P, bool B) public static bool StaticProp { get; set; } = false; } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteSimpleEquals2() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteSimpleEquals2() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -961,20 +829,16 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteInvertedEquals() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteInvertedEquals() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -988,21 +852,16 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteEqualsDoubleComparison() - { - // comparing the same thing twice shouldn't matter - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteEqualsDoubleComparison() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -1016,20 +875,16 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndKeepEqualsMissingComparison() - { - var initialMarkup = """ + public Task TestMovePropertiesAndKeepEqualsMissingComparison() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -1043,8 +898,7 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B) @@ -1055,14 +909,11 @@ public record C(int P, bool B) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndKeepEqualsSelfComparison1() - { - var initialMarkup = """ + public Task TestMovePropertiesAndKeepEqualsSelfComparison1() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -1076,8 +927,7 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B) @@ -1088,14 +938,11 @@ public record C(int P, bool B) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndKeepEqualsSelfComparison2() - { - var initialMarkup = """ + public Task TestMovePropertiesAndKeepEqualsSelfComparison2() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -1109,8 +956,7 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B) @@ -1121,14 +967,11 @@ public record C(int P, bool B) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndKeepEqualsWithSideEffect() - { - var initialMarkup = """ + public Task TestMovePropertiesAndKeepEqualsWithSideEffect() + => TestRefactoringAsync(""" using System; namespace N @@ -1145,8 +988,7 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ using System; namespace N @@ -1160,14 +1002,11 @@ public record C(int P, bool B) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndKeepEqualsIncorrectComparison() - { - var initialMarkup = """ + public Task TestMovePropertiesAndKeepEqualsIncorrectComparison() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -1181,8 +1020,7 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, int B) @@ -1193,14 +1031,11 @@ public record C(int P, int B) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndKeepWrongInvertedEquals() - { - var initialMarkup = """ + public Task TestMovePropertiesAndKeepWrongInvertedEquals() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -1214,8 +1049,7 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B) @@ -1226,14 +1060,11 @@ public record C(int P, bool B) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndKeepOrEquals() - { - var initialMarkup = """ + public Task TestMovePropertiesAndKeepOrEquals() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -1252,8 +1083,7 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B) @@ -1269,14 +1099,11 @@ public record C(int P, bool B) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteIfCastEquals1() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteIfCastEquals1() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -1295,20 +1122,16 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteIfCastEquals2() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteIfCastEquals2() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -1327,20 +1150,16 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteInvertedIfCastEquals() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteInvertedIfCastEquals() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -1359,20 +1178,16 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndKeepWrongInvertedIfCastEquals() - { - var initialMarkup = """ + public Task TestMovePropertiesAndKeepWrongInvertedIfCastEquals() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -1392,8 +1207,7 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B) @@ -1410,14 +1224,11 @@ public record C(int P, bool B) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteIfThenCastEquals() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteIfThenCastEquals() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -1437,20 +1248,16 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteIfChainEquals() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteIfChainEquals() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -1480,20 +1287,16 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteIfElseChainEquals() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteIfElseChainEquals() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -1523,20 +1326,16 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteInvertedIfChainEquals() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteInvertedIfChainEquals() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -1562,20 +1361,16 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteAsCastEquals() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteAsCastEquals() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -1590,20 +1385,16 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteAsCastEqualsWithIsNotNull() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteAsCastEqualsWithIsNotNull() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -1618,20 +1409,16 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndKeepAsCastEqualsWithIncorrectIsNull() - { - var initialMarkup = """ + public Task TestMovePropertiesAndKeepAsCastEqualsWithIncorrectIsNull() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -1646,8 +1433,7 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B) @@ -1659,14 +1445,11 @@ public record C(int P, bool B) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteAsCastEqualsWithIsNull() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteAsCastEqualsWithIsNull() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -1681,20 +1464,16 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteSimpleTypeEquals() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteSimpleTypeEquals() + => TestRefactoringAsync(""" using System; namespace N @@ -1710,22 +1489,18 @@ public bool Equals(C? otherC) } } } - """; - var changedMarkup = """ + """, """ using System; namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteSimpleTypeEqualsWithAdditionalInterface() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteSimpleTypeEqualsWithAdditionalInterface() + => TestRefactoringAsync(""" using System; namespace N @@ -1743,8 +1518,7 @@ public bool Equals(C? otherC) public int CompareTo(object? other) => 0; } } - """; - var changedMarkup = """ + """, """ using System; namespace N @@ -1754,14 +1528,11 @@ public record C(int P, bool B) : IComparable public int CompareTo(object? other) => 0; } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteSimpleTypeEqualsAndObjectEquals() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteSimpleTypeEqualsAndObjectEquals() + => TestRefactoringAsync(""" using System; namespace N @@ -1782,22 +1553,18 @@ public override bool Equals(object? other) } } } - """; - var changedMarkup = """ + """, """ using System; namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteTypeEqualsIfChain() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteTypeEqualsIfChain() + => TestRefactoringAsync(""" using System; namespace N @@ -1828,22 +1595,18 @@ public bool Equals(C? otherC) } } } - """; - var changedMarkup = """ + """, """ using System; namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteObjectAndTypeEquals() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteObjectAndTypeEquals() + => TestRefactoringAsync(""" using System; namespace N @@ -1864,22 +1627,18 @@ public bool Equals(C? otherC) } } } - """; - var changedMarkup = """ + """, """ using System; namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndKeepIncorrectObjectAndDeleteCorrectTypeEquals() - { - var initialMarkup = """ + public Task TestMovePropertiesAndKeepIncorrectObjectAndDeleteCorrectTypeEquals() + => TestRefactoringAsync(""" using System; namespace N @@ -1905,8 +1664,7 @@ public bool Equals(C? otherC) } } } - """; - var changedMarkup = """ + """, """ using System; namespace N @@ -1924,14 +1682,11 @@ public bool Foo(C? c) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteHashCode1() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteHashCode1() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -1948,20 +1703,16 @@ public override int GetHashCode() } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteHashCode2() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteHashCode2() + => TestRefactoringAsync(""" using System.Collections.Generic; namespace N @@ -1980,22 +1731,18 @@ public override int GetHashCode() } } } - """; - var changedMarkup = """ + """, """ using System.Collections.Generic; namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndKeepComplexHashCode() - { - var initialMarkup = """ + public Task TestMovePropertiesAndKeepComplexHashCode() + => TestRefactoringAsync(""" using System; using System.Collections.Generic; @@ -2016,8 +1763,7 @@ public override int GetHashCode() } } } - """; - var changedMarkup = """ + """, """ using System; using System.Collections.Generic; @@ -2035,14 +1781,11 @@ public override int GetHashCode() } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteSimpleEqualOperatorsWithNullableObjectParam1() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteSimpleEqualOperatorsWithNullableObjectParam1() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -2059,20 +1802,16 @@ public class [|C|] } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteSimpleEqualOperatorsWithNullableObjectParam2() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteSimpleEqualOperatorsWithNullableObjectParam2() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -2089,20 +1828,16 @@ public class [|C|] } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteSimpleEqualOperatorsWithNullableObjectParam3() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteSimpleEqualOperatorsWithNullableObjectParam3() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -2119,20 +1854,16 @@ public class [|C|] } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteSimpleEqualOperatorsWithObjectParam() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteSimpleEqualOperatorsWithObjectParam() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -2149,20 +1880,16 @@ public class [|C|] } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteEqualOperatorsWithExpressionBodies() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteEqualOperatorsWithExpressionBodies() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -2177,20 +1904,16 @@ public class [|C|] => !(c1 == c2); } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteSimpleEqualOperatorsWithSameTypeParams() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteSimpleEqualOperatorsWithSameTypeParams() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -2207,20 +1930,16 @@ public class [|C|] } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteSimpleEqualOperatorsWithNullableTypeParams() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteSimpleEqualOperatorsWithNullableTypeParams() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -2237,20 +1956,16 @@ public class [|C|] } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndKeepSideEffectOperator1() - { - var initialMarkup = """ + public Task TestMovePropertiesAndKeepSideEffectOperator1() + => TestRefactoringAsync(""" using System; namespace N @@ -2272,8 +1987,7 @@ public class [|C|] } } } - """; - var changedMarkup = """ + """, """ using System; namespace N @@ -2292,14 +2006,11 @@ public record C(int P, bool B) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndKeepSideEffectOperator2() - { - var initialMarkup = """ + public Task TestMovePropertiesAndKeepSideEffectOperator2() + => TestRefactoringAsync(""" using System; namespace N @@ -2321,8 +2032,7 @@ public class [|C|] } } } - """; - var changedMarkup = """ + """, """ using System; namespace N @@ -2341,14 +2051,11 @@ public record C(int P, bool B) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndKeepSideEffectOperator_WhenSameParamUsed1() - { - var initialMarkup = """ + public Task TestMovePropertiesAndKeepSideEffectOperator_WhenSameParamUsed1() + => TestRefactoringAsync(""" using System; namespace N @@ -2369,8 +2076,7 @@ public class [|C|] } } } - """; - var changedMarkup = """ + """, """ using System; namespace N @@ -2388,14 +2094,11 @@ public record C(int P, bool B) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndKeepSideEffectOperator_WhenSameParamUsed2() - { - var initialMarkup = """ + public Task TestMovePropertiesAndKeepSideEffectOperator_WhenSameParamUsed2() + => TestRefactoringAsync(""" using System; namespace N @@ -2416,8 +2119,7 @@ public class [|C|] } } } - """; - var changedMarkup = """ + """, """ using System; namespace N @@ -2435,14 +2137,11 @@ public record C(int P, bool B) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteClone() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteClone() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -2456,20 +2155,16 @@ public C Clone() } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteSimpleCopyConstructor() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteSimpleCopyConstructor() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -2484,20 +2179,16 @@ public C(C other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteCopyConstructorWithFields() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteCopyConstructorWithFields() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -2514,8 +2205,7 @@ public C(C other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B) @@ -2523,14 +2213,11 @@ public record C(int P, bool B) int foo = 0; } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteCopyConstructorWithConstAndStaticFieldsAndProps() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteCopyConstructorWithConstAndStaticFieldsAndProps() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -2548,8 +2235,7 @@ public C(C other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B) @@ -2559,14 +2245,11 @@ public record C(int P, bool B) public static bool StaticProp { get; set; } = false; } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndKeepCopyConstructorWithoutFieldAccess() - { - var initialMarkup = """ + public Task TestMovePropertiesAndKeepCopyConstructorWithoutFieldAccess() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -2582,8 +2265,7 @@ public C(C other) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B) @@ -2597,14 +2279,11 @@ public C(C other) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteSimplePrimaryConstructor() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteSimplePrimaryConstructor() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -2619,20 +2298,16 @@ public C(int p, bool b) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDeleteSimpleExpressionPrimaryConstructor() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDeleteSimpleExpressionPrimaryConstructor() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -2643,20 +2318,16 @@ public C(int p) => P = p; } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndModifyOrderFromPrimaryConstructor() - { - var initialMarkup = """ + public Task TestMovePropertiesAndModifyOrderFromPrimaryConstructor() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -2671,20 +2342,16 @@ public C(bool b, int p) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(bool B, int P); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndModifyPrimaryConstructorOrderAndDefaults() - { - var initialMarkup = """ + public Task TestMovePropertiesAndModifyPrimaryConstructorOrderAndDefaults() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -2699,20 +2366,16 @@ public C(bool b = false, int p = 0) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(bool B = false, int P = 0); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndProvideThisInitializerValuesWithOperators() - { - var initialMarkup = """ + public Task TestMovePropertiesAndProvideThisInitializerValuesWithOperators() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -2733,8 +2396,7 @@ public C(bool b1, bool b2, bool b3) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(bool B, int P) @@ -2744,14 +2406,11 @@ public C(bool b1, bool b2, bool b3) : this(!b2 == b3, b1 ? 1 : 0) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndProvideThisInitializerValuesWithStaticMemberAndInvocation() - { - var initialMarkup = """ + public Task TestMovePropertiesAndProvideThisInitializerValuesWithStaticMemberAndInvocation() + => TestRefactoringAsync(""" namespace N { public static class Stuff @@ -2775,8 +2434,7 @@ public C(bool b1, bool b2, bool b3) } } } - """; - var changedMarkup = """ + """, """ namespace N { public static class Stuff @@ -2796,14 +2454,11 @@ public C(bool b1, bool b2, bool b3) : this(b3 ? DefaultP : 0, Stuff.GetB(b1, b2) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndProvideThisInitializerValuesWithReferences() - { - var initialMarkup = """ + public Task TestMovePropertiesAndProvideThisInitializerValuesWithReferences() + => TestRefactoringAsync(""" namespace N { public record R(int Foo, int Bar) @@ -2834,8 +2489,7 @@ public C(R r) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record R(int Foo, int Bar) @@ -2855,14 +2509,11 @@ public C(R r) : this(r.IsBarNum(r.Foo), r.field) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndProvideThisInitializerValuesWithNullOperations() - { - var initialMarkup = """ + public Task TestMovePropertiesAndProvideThisInitializerValuesWithNullOperations() + => TestRefactoringAsync(""" namespace N { public record R(int? Foo, int Bar) @@ -2893,8 +2544,7 @@ public C(R? r, int backup) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record R(int? Foo, int Bar) @@ -2914,14 +2564,11 @@ public C(R? r, int backup) : this(r?.IsBarNum(backup), r?.Foo ?? 10) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndProvideThisInitializerValuesWithIsExpressions() - { - var initialMarkup = """ + public Task TestMovePropertiesAndProvideThisInitializerValuesWithIsExpressions() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -2942,8 +2589,7 @@ public C(object b1, bool b2, object b3) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(bool B, int P) @@ -2953,14 +2599,11 @@ public C(object b1, bool b2, object b3) : this(!b2 && b3 is C { P: 10 }, b1 is i } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndProvideThisInitializerValuesWithSwitchExpressions() - { - var initialMarkup = """ + public Task TestMovePropertiesAndProvideThisInitializerValuesWithSwitchExpressions() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -2986,8 +2629,7 @@ public C(int f1, bool b2, bool b3) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(bool B, int P) @@ -3002,14 +2644,11 @@ public record C(bool B, int P) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndProvideThisInitializerValuesWithSideEffects() - { - var initialMarkup = """ + public Task TestMovePropertiesAndProvideThisInitializerValuesWithSideEffects() + => TestRefactoringAsync(""" using System; namespace N @@ -3033,8 +2672,7 @@ public C(bool b1, bool b2) } } } - """; - var changedMarkup = """ + """, """ using System; namespace N @@ -3047,14 +2685,11 @@ public C(bool b1, bool b2) : this(!b2, b1 ? 1 : 0) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndProvideThisInitializerValuesComplex() - { - var initialMarkup = """ + public Task TestMovePropertiesAndProvideThisInitializerValuesComplex() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -3076,8 +2711,7 @@ public C(bool b1, bool b2) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(bool B, int P) @@ -3089,14 +2723,11 @@ public C(bool b1, bool b2) : this(default, b1 ? 1 : 0) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndProvideThisInitializerValuesPatternVariable() - { - var initialMarkup = """ + public Task TestMovePropertiesAndProvideThisInitializerValuesPatternVariable() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -3121,8 +2752,7 @@ public C(bool b1, object b2) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(bool B, int P) @@ -3137,14 +2767,11 @@ public C(bool b1, object b2) : this(default, b1 ? 1 : 0) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndProvideThisInitializerDefaultAndNull() - { - var initialMarkup = """ + public Task TestMovePropertiesAndProvideThisInitializerDefaultAndNull() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -3165,8 +2792,7 @@ public C(bool b1, bool b2) } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(bool B, int? P) @@ -3178,14 +2804,11 @@ public C(bool b1, bool b2) : this(default, null) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndKeepComplexPrimaryConstructor1() - { - var initialMarkup = """ + public Task TestMovePropertiesAndKeepComplexPrimaryConstructor1() + => TestRefactoringAsync(""" using System; namespace N @@ -3203,8 +2826,7 @@ public C(int p, bool b) } } } - """; - var changedMarkup = """ + """, """ using System; namespace N @@ -3219,14 +2841,11 @@ public record C(int P, bool B) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndKeepComplexPrimaryConstructor2() - { - var initialMarkup = """ + public Task TestMovePropertiesAndKeepComplexPrimaryConstructor2() + => TestRefactoringAsync(""" using System; namespace N @@ -3243,8 +2862,7 @@ public C(int p, bool b) } } } - """; - var changedMarkup = """ + """, """ using System; namespace N @@ -3258,14 +2876,11 @@ public record C(int P, bool B) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndKeepComplexPrimaryConstructor3() - { - var initialMarkup = """ + public Task TestMovePropertiesAndKeepComplexPrimaryConstructor3() + => TestRefactoringAsync(""" using System; namespace N @@ -3281,8 +2896,7 @@ public C(int p, bool b) } } } - """; - var changedMarkup = """ + """, """ using System; namespace N @@ -3295,14 +2909,11 @@ public record C(int P, bool B) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesWithMultiplePotentialPrimaryConstructors() - { - var initialMarkup = """ + public Task TestMovePropertiesWithMultiplePotentialPrimaryConstructors() + => TestRefactoringAsync(""" using System; namespace N @@ -3324,8 +2935,7 @@ public C(bool b, int p) } } } - """; - var changedMarkup = """ + """, """ using System; namespace N @@ -3337,14 +2947,11 @@ public C(int p, bool b) : this(b, default) } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesWithSimpleDocComments() - { - var initialMarkup = """ + public Task TestMovePropertiesWithSimpleDocComments() + => TestRefactoringAsync(""" namespace N { @@ -3365,8 +2972,7 @@ public class [|C|] public bool B { get; init; } } } - """; - var changedMarkup = """ + """, """ namespace N { /// @@ -3376,14 +2982,11 @@ namespace N /// B is a bool public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesWithMultilineDocComments() - { - var initialMarkup = """ + public Task TestMovePropertiesWithMultilineDocComments() + => TestRefactoringAsync(""" namespace N { @@ -3410,24 +3013,7 @@ public class [|C|] public bool B { get; init; } } } - """; - // this is what it should be - // var changedMarkup = @" - //namespace N - //{ - // /** - // * - // * some summary - // * - // * P is an int - // * B is a bool - // */ - // public record C(int P, bool B); - //} - //"; - - // this is what it is currently - var changedMarkup = """ + """, """ namespace N { /** @@ -3439,14 +3025,11 @@ namespace N */ public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesWithMultilineDocComments_NoClassSummary() - { - var initialMarkup = """ + public Task TestMovePropertiesWithMultilineDocComments_NoClassSummary() + => TestRefactoringAsync(""" namespace N { @@ -3468,20 +3051,7 @@ public class [|C|] public bool B { get; init; } } } - """; - // this is what it should be - // var changedMarkup = @" - //namespace N - //{ - // /** - // * P is an int - // * B is a bool - // */ - // public record C(int P, bool B); - //} - //"; - // this is what it is currently - var changedMarkup = """ + """, """ namespace N { /** @@ -3490,15 +3060,11 @@ namespace N */ public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesWithMixedDocComments1() - { - // class-level comment should be default - var initialMarkup = """ + public Task TestMovePropertiesWithMixedDocComments1() + => TestRefactoringAsync(""" namespace N { @@ -3523,8 +3089,7 @@ public class [|C|] public bool B { get; init; } } } - """; - var changedMarkup = """ + """, """ namespace N { /// @@ -3534,15 +3099,11 @@ namespace N /// B is a bool public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesWithMixedDocComments2() - { - // class-level comment should be default - var initialMarkup = """ + public Task TestMovePropertiesWithMixedDocComments2() + => TestRefactoringAsync(""" namespace N { @@ -3565,24 +3126,7 @@ public class [|C|] public bool B { get; init; } } } - """; - // This is what it should be - // var changedMarkup = @" - //namespace N - //{ - // /** - // * - // * some summary - // * - // * P is an int - // * B is a bool - // */ - // public record C(int P, bool B); - //} - //"; - - // this is what it is right now - var changedMarkup = """ + """, """ namespace N { /** @@ -3594,14 +3138,11 @@ namespace N */ public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesWithMixedDocComments3() - { - var initialMarkup = """ + public Task TestMovePropertiesWithMixedDocComments3() + => TestRefactoringAsync(""" namespace N { @@ -3625,25 +3166,7 @@ public class [|C|] public bool B { get; init; } } } - """; - // this is what it should be - // var changedMarkup = @" - //namespace N - //{ - // /** - // * - // * some summary - // * - // * P is an int - // * with a multiline comment - // * B is a bool - // */ - // public record C(int P, bool B); - //} - //"; - - // this is what it actually is - var changedMarkup = """ + """, """ namespace N { /** @@ -3656,14 +3179,11 @@ namespace N */ public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesWithDocComments_NoClassSummary() - { - var initialMarkup = """ + public Task TestMovePropertiesWithDocComments_NoClassSummary() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -3680,22 +3200,18 @@ public class [|C|] public bool B { get; init; } } } - """; - var changedMarkup = """ + """, """ namespace N { /// P is an int /// B is a bool public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesWithDocComments_MissingPropertySummary() - { - var initialMarkup = """ + public Task TestMovePropertiesWithDocComments_MissingPropertySummary() + => TestRefactoringAsync(""" namespace N { @@ -3712,8 +3228,7 @@ public class [|C|] public bool B { get; init; } } } - """; - var changedMarkup = """ + """, """ namespace N { /// @@ -3723,14 +3238,11 @@ namespace N /// B is a bool public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesWithDocComments_AdditionalClassSection() - { - var initialMarkup = """ + public Task TestMovePropertiesWithDocComments_AdditionalClassSection() + => TestRefactoringAsync(""" namespace N { @@ -3754,8 +3266,7 @@ public class [|C|] public bool B { get; init; } } } - """; - var changedMarkup = """ + """, """ namespace N { /// @@ -3768,14 +3279,11 @@ namespace N /// public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesWithDocComments_NestedPropertyElements() - { - var initialMarkup = """ + public Task TestMovePropertiesWithDocComments_NestedPropertyElements() + => TestRefactoringAsync(""" namespace N { @@ -3797,8 +3305,7 @@ public class [|C|] public bool B { get; init; } } } - """; - var changedMarkup = """ + """, """ namespace N { /// @@ -3809,15 +3316,11 @@ namespace N /// Some code text public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesWithDocAndNonDocComments1() - { - // we should try to keep the order in the same as the order on the class comments - var initialMarkup = """ + public Task TestMovePropertiesWithDocAndNonDocComments1() + => TestRefactoringAsync(""" namespace N { @@ -3841,8 +3344,7 @@ public class [|C|] public bool B { get; init; } } } - """; - var changedMarkup = """ + """, """ namespace N { // Non-Doc comment before class @@ -3855,15 +3357,11 @@ namespace N /// B is a bool public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesWithDocAndNonDocComments2() - { - // we should try to keep the order in the same as the order on the class comments - var initialMarkup = """ + public Task TestMovePropertiesWithDocAndNonDocComments2() + => TestRefactoringAsync(""" namespace N { @@ -3887,8 +3385,7 @@ public class [|C|] public bool B { get; init; } } } - """; - var changedMarkup = """ + """, """ namespace N { /// @@ -3901,14 +3398,11 @@ namespace N // Non-Doc property comment for B public record C(int P, bool B); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndRefactorInitializer() - { - var initialMarkup = """ + public Task TestMovePropertiesAndRefactorInitializer() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -3929,8 +3423,7 @@ public static C GetC() } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); @@ -3943,14 +3436,11 @@ public static C GetC() } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndRefactorInitializerWithNullableReferenceTypes() - { - var initialMarkup = """ + public Task TestMovePropertiesAndRefactorInitializerWithNullableReferenceTypes() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -3970,8 +3460,7 @@ public static C GetC() } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, C? Node); @@ -3984,14 +3473,11 @@ public static C GetC() } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndRefactorInitializerWithNullableValueTypes() - { - var initialMarkup = """ + public Task TestMovePropertiesAndRefactorInitializerWithNullableValueTypes() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -4011,8 +3497,7 @@ public static C GetC() } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool? B); @@ -4025,14 +3510,11 @@ public static C GetC() } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndRefactorInitializerInSameClass1() - { - var initialMarkup = """ + public Task TestMovePropertiesAndRefactorInitializerInSameClass1() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -4050,8 +3532,7 @@ public static C GetC() } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B) @@ -4062,14 +3543,11 @@ public static C GetC() } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndRefactorInitializerInSameClass2() - { - var initialMarkup = """ + public Task TestMovePropertiesAndRefactorInitializerInSameClass2() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -4091,8 +3569,7 @@ public static C GetC() } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, C? Node) @@ -4103,14 +3580,11 @@ public static C GetC() } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndRefactorInitializerInSameClass3() - { - var initialMarkup = """ + public Task TestMovePropertiesAndRefactorInitializerInSameClass3() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -4125,8 +3599,7 @@ public class [|C|] }; } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B) @@ -4134,14 +3607,11 @@ public record C(int P, bool B) public static C Default = new C(0, true); } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndRefactorInitializerWithNestedInitializers() - { - var initialMarkup = """ + public Task TestMovePropertiesAndRefactorInitializerWithNestedInitializers() + => TestRefactoringAsync(""" namespace N { public record Foo @@ -4164,8 +3634,7 @@ public static C GetC() } } } - """; - var changedMarkup = """ + """, """ namespace N { public record Foo @@ -4181,14 +3650,11 @@ public static C GetC() } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndRefactorInitializerKeepSomeProperties() - { - var initialMarkup = """ + public Task TestMovePropertiesAndRefactorInitializerKeepSomeProperties() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -4212,8 +3678,7 @@ public static C GetC() } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B) @@ -4232,14 +3697,11 @@ public static C GetC() } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndRefactorInitializerWithDefault() - { - var initialMarkup = """ + public Task TestMovePropertiesAndRefactorInitializerWithDefault() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -4259,8 +3721,7 @@ public static C GetC() } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); @@ -4273,14 +3734,11 @@ public static C GetC() } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestMovePropertiesAndDoNotRefactorInitializerWithExistingConstructor() - { - var initialMarkup = """ + public Task TestMovePropertiesAndDoNotRefactorInitializerWithExistingConstructor() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -4306,8 +3764,7 @@ public static C GetC() } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B) @@ -4328,9 +3785,7 @@ public static C GetC() } } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] public async Task TestMovePropertiesAndRefactorInitializerInSeparateFile() @@ -4405,9 +3860,8 @@ public static C GetC() } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_queries/edit/1932546")] - public async Task TestInvalidObjectCreation() - { - var initialMarkup = """ + public Task TestInvalidObjectCreation() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -4428,9 +3882,7 @@ public static C GetC() } } } - """; - - var changedMarkup = """ + """, """ namespace N { public record C(int P, bool B); @@ -4447,15 +3899,11 @@ public static C GetC() } } } - """; - - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72032")] - public async Task TestConstructorWithoutBody() - { - var initialMarkup = """ + public Task TestConstructorWithoutBody() + => TestRefactoringAsync(""" namespace N { public class [|C|] @@ -4465,8 +3913,7 @@ public class [|C|] public extern C(); } } - """; - var fixedMarkup = """ + """, """ namespace N { public record [|C|](int P) @@ -4476,14 +3923,11 @@ public record [|C|](int P) public extern C(); } } - """; - await TestRefactoringAsync(initialMarkup, fixedMarkup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72067")] - public async Task TestMovePropertiesAndRefactorInitializer_SourceGeneratedDocuments() - { - await new RefactoringTestWithGenerator + public Task TestMovePropertiesAndRefactorInitializer_SourceGeneratedDocuments() + => new RefactoringTestWithGenerator { TestCode = """ namespace N @@ -4513,12 +3957,10 @@ public record C(int P, bool B); } } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78664")] - public async Task TestDoesNotCrashOnAbstractMethod() - { - var initialMarkup = """ + public Task TestDoesNotCrashOnAbstractMethod() + => TestRefactoringAsync(""" namespace N { public abstract class [|C|] @@ -4528,8 +3970,7 @@ public abstract class [|C|] public abstract System.Guid F(); } } - """; - var changedMarkup = """ + """, """ namespace N { public abstract record C(string? S) @@ -4537,14 +3978,11 @@ public abstract record C(string? S) public abstract System.Guid F(); } } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78664")] - public async Task TestDoesNotCrashOnAbstractCloneMethod() - { - var initialMarkup = """ + public Task TestDoesNotCrashOnAbstractCloneMethod() + => TestRefactoringAsync(""" namespace N { public abstract class [|C|] @@ -4554,15 +3992,12 @@ public abstract class [|C|] public abstract object Clone(); } } - """; - var changedMarkup = """ + """, """ namespace N { public abstract record C(string? S); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); #pragma warning disable RS1042 // Do not implement private sealed class ConvertToRecordTestGenerator : ISourceGenerator @@ -4596,9 +4031,8 @@ public static C GetC() #region selection [Fact] - public async Task TestSelectOnProperty_NoAction() - { - var initialMarkup = """ + public Task TestSelectOnProperty_NoAction() + => TestNoRefactoringAsync(""" namespace N { public class C @@ -4606,14 +4040,11 @@ public class C public int [|P|] { get; init; } } } - """; - await TestNoRefactoringAsync(initialMarkup); - } + """); [Fact] - public async Task TestSelectOnNamespace_NoAction() - { - var initialMarkup = """ + public Task TestSelectOnNamespace_NoAction() + => TestNoRefactoringAsync(""" namespace [|N|] { public class C @@ -4621,14 +4052,11 @@ public class C public int P { get; init; } } } - """; - await TestNoRefactoringAsync(initialMarkup); - } + """); [Fact] - public async Task TestSelectLargeRegionIncludingNamespace_NoAction() - { - var initialMarkup = """ + public Task TestSelectLargeRegionIncludingNamespace_NoAction() + => TestNoRefactoringAsync(""" namespace [|N { public clas|]s C @@ -4636,14 +4064,11 @@ public clas|]s C public int P { get; init; } } } - """; - await TestNoRefactoringAsync(initialMarkup); - } + """); [Fact] - public async Task TestSelectMultipleMembersWithinClass() - { - var initialMarkup = """ + public Task TestSelectMultipleMembersWithinClass() + => TestRefactoringAsync(""" namespace N { public class C @@ -4656,8 +4081,7 @@ public int Foo() }|] } } - """; - var fixedMarkup = """ + """, """ namespace N { public record C(int P) @@ -4668,14 +4092,11 @@ public int Foo() } } } - """; - await TestRefactoringAsync(initialMarkup, fixedMarkup); - } + """); [Fact] - public async Task TestSelectRegionIncludingClass() - { - var initialMarkup = """ + public Task TestSelectRegionIncludingClass() + => TestRefactoringAsync(""" namespace N { public class [|C @@ -4683,20 +4104,16 @@ public class [|C public int P { get; init; }|] } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestSelectClassKeyword() - { - var initialMarkup = """ + public Task TestSelectClassKeyword() + => TestRefactoringAsync(""" namespace N { public cl[||]ass C @@ -4704,20 +4121,16 @@ public cl[||]ass C public int P { get; init; } } } - """; - var changedMarkup = """ + """, """ namespace N { public record C(int P); } - """; - await TestRefactoringAsync(initialMarkup, changedMarkup); - } + """); [Fact] - public async Task TestSelectBaseClassItem_NoAction() - { - var initialMarkup = """ + public Task TestSelectBaseClassItem_NoAction() + => TestNoRefactoringAsync(""" namespace N { public class B {} @@ -4727,9 +4140,7 @@ public class C : [|B|] public int P { get; init; } } } - """; - await TestNoRefactoringAsync(initialMarkup); - } + """); #endregion diff --git a/src/Features/CSharpTest/ConvertTupleToStruct/ConvertTupleToStructTests.cs b/src/Features/CSharpTest/ConvertTupleToStruct/ConvertTupleToStructTests.cs index 17c6a325595c5..bfdc3193546f1 100644 --- a/src/Features/CSharpTest/ConvertTupleToStruct/ConvertTupleToStructTests.cs +++ b/src/Features/CSharpTest/ConvertTupleToStruct/ConvertTupleToStructTests.cs @@ -68,9 +68,8 @@ private static async Task TestAsync( #region update containing member tests [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task ConvertSingleTupleType(TestHost host) - { - var text = """ + public Task ConvertSingleTupleType(TestHost host) + => TestAsync(""" class Test { void Method() @@ -78,8 +77,7 @@ void Method() var t1 = [||](a: 1, b: 2); } } - """; - var expected = """ + """, """ class Test { void Method() @@ -130,14 +128,11 @@ public static implicit operator NewStruct((int a, int b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task ConvertSingleTupleTypeToRecord(TestHost host) - { - var text = """ + public Task ConvertSingleTupleTypeToRecord(TestHost host) + => TestAsync(""" class Test { void Method() @@ -145,8 +140,7 @@ void Method() var t1 = [||](a: 1, B: 2); } } - """; - var expected = """ + """, """ class Test { void Method() @@ -167,14 +161,11 @@ public static implicit operator NewStruct((int a, int B) value) return new NewStruct(value.a, value.B); } } - """; - await TestAsync(text, expected, languageVersion: LanguageVersion.CSharp12, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, languageVersion: LanguageVersion.CSharp12, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task ConvertSingleTupleTypeToRecord_FileScopedNamespace(TestHost host) - { - var text = """ + public Task ConvertSingleTupleTypeToRecord_FileScopedNamespace(TestHost host) + => TestAsync(""" namespace N; class Test @@ -184,8 +175,7 @@ void Method() var t1 = [||](a: 1, b: 2); } } - """; - var expected = """ + """, """ namespace N; class Test @@ -208,14 +198,11 @@ public static implicit operator NewStruct((int a, int b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync(text, expected, languageVersion: LanguageVersion.CSharp12, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, languageVersion: LanguageVersion.CSharp12, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task ConvertSingleTupleTypeToRecord_MatchedNameCasing(TestHost host) - { - var text = """ + public Task ConvertSingleTupleTypeToRecord_MatchedNameCasing(TestHost host) + => TestAsync(""" class Test { void Method() @@ -223,8 +210,7 @@ void Method() var t1 = [||](A: 1, B: 2); } } - """; - var expected = """ + """, """ class Test { void Method() @@ -245,14 +231,11 @@ public static implicit operator NewStruct((int A, int B) value) return new NewStruct(value.A, value.B); } } - """; - await TestAsync(text, expected, languageVersion: LanguageVersion.CSharp12, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, languageVersion: LanguageVersion.CSharp12, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), WorkItem("https://github.com/dotnet/roslyn/issues/45451"), CombinatorialData] - public async Task ConvertSingleTupleType_ChangeArgumentNameCase(TestHost host) - { - var text = """ + public Task ConvertSingleTupleType_ChangeArgumentNameCase(TestHost host) + => TestAsync(""" class Test { void Method() @@ -260,8 +243,7 @@ void Method() var t1 = [||](A: 1, B: 2); } } - """; - var expected = """ + """, """ class Test { void Method() @@ -312,14 +294,42 @@ public static implicit operator NewStruct((int A, int B) value) return new NewStruct(value.A, value.B); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), WorkItem("https://github.com/dotnet/roslyn/issues/45451"), CombinatorialData] public async Task ConvertSingleTupleType_ChangeArgumentNameCase_Uppercase(TestHost host) { - var text = """ + var symbolSpecification = new SymbolSpecification( + Guid.NewGuid(), + "Name2", + [new SymbolSpecification.SymbolKindOrTypeKind(SymbolKind.Parameter)], + accessibilityList: default, + modifiers: default); + + var namingStyle = new NamingStyle( + Guid.NewGuid(), + capitalizationScheme: Capitalization.CamelCase, + name: "Name2", + prefix: "p_", + suffix: "_", + wordSeparator: ""); + + var namingRule = new SerializableNamingRule() + { + SymbolSpecificationID = symbolSpecification.ID, + NamingStyleID = namingStyle.ID, + EnforcementLevel = ReportDiagnostic.Error + }; + + var info = new NamingStylePreferences( + [symbolSpecification], + [namingStyle], + [namingRule]); + + var options = PreferImplicitTypeWithInfo(); + options.Add(NamingStyleOptions.NamingPreferences, info); + + await TestAsync(""" class Test { void Method() @@ -327,8 +337,7 @@ void Method() var t1 = [||](A: 1, B: 2); } } - """; - var expected = """ + """, """ class Test { void Method() @@ -379,44 +388,12 @@ public static implicit operator NewStruct((int A, int B) value) return new NewStruct(value.A, value.B); } } - """; - var symbolSpecification = new SymbolSpecification( - Guid.NewGuid(), - "Name2", - [new SymbolSpecification.SymbolKindOrTypeKind(SymbolKind.Parameter)], - accessibilityList: default, - modifiers: default); - - var namingStyle = new NamingStyle( - Guid.NewGuid(), - capitalizationScheme: Capitalization.CamelCase, - name: "Name2", - prefix: "p_", - suffix: "_", - wordSeparator: ""); - - var namingRule = new SerializableNamingRule() - { - SymbolSpecificationID = symbolSpecification.ID, - NamingStyleID = namingStyle.ID, - EnforcementLevel = ReportDiagnostic.Error - }; - - var info = new NamingStylePreferences( - [symbolSpecification], - [namingStyle], - [namingRule]); - - var options = PreferImplicitTypeWithInfo(); - options.Add(NamingStyleOptions.NamingPreferences, info); - - await TestAsync(text, expected, options: options, testHost: host); + """, options: options, testHost: host); } [ConditionalTheory(typeof(DesktopOnly)), WorkItem("https://github.com/dotnet/roslyn/issues/39916"), CombinatorialData] - public async Task ConvertSingleTupleType_Explicit(TestHost host) - { - var text = """ + public Task ConvertSingleTupleType_Explicit(TestHost host) + => TestAsync(""" class Test { void Method() @@ -424,8 +401,7 @@ void Method() var t1 = [||](a: 1, b: 2); } } - """; - var expected = """ + """, """ class Test { void Method() @@ -476,14 +452,11 @@ public static implicit operator NewStruct((int a, int b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync(text, expected, testHost: host); - } + """, testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task ConvertSingleTupleTypeNoNames(TestHost host) - { - var text = """ + public Task ConvertSingleTupleTypeNoNames(TestHost host) + => TestAsync(""" class Test { void Method() @@ -491,8 +464,7 @@ void Method() var t1 = [||](1, 2); } } - """; - var expected = """ + """, """ class Test { void Method() @@ -543,14 +515,11 @@ public static implicit operator NewStruct((int, int) value) return new NewStruct(value.Item1, value.Item2); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task ConvertSingleTupleTypePartialNames(TestHost host) - { - var text = """ + public Task ConvertSingleTupleTypePartialNames(TestHost host) + => TestAsync(""" class Test { void Method() @@ -558,8 +527,7 @@ void Method() var t1 = [||](1, b: 2); } } - """; - var expected = """ + """, """ class Test { void Method() @@ -610,14 +578,11 @@ public static implicit operator NewStruct((int, int b) value) return new NewStruct(value.Item1, value.b); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task ConvertFromType(TestHost host) - { - var text = """ + public Task ConvertFromType(TestHost host) + => TestAsync(""" class Test { void Method() @@ -626,8 +591,7 @@ void Method() (int a, int b) t2 = (a: 1, b: 2); } } - """; - var expected = """ + """, """ class Test { void Method() @@ -679,14 +643,11 @@ public static implicit operator NewStruct((int a, int b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task ConvertFromType2(TestHost host) - { - var text = """ + public Task ConvertFromType2(TestHost host) + => TestAsync(""" class Test { (int a, int b) Method() @@ -696,8 +657,7 @@ class Test return default; } } - """; - var expected = """ + """, """ class Test { NewStruct Method() @@ -750,14 +710,11 @@ public static implicit operator NewStruct((int a, int b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task ConvertFromType3(TestHost host) - { - var text = """ + public Task ConvertFromType3(TestHost host) + => TestAsync(""" class Test { (int a, int b) Method() @@ -767,8 +724,7 @@ class Test return default; } } - """; - var expected = """ + """, """ class Test { NewStruct Method() @@ -821,14 +777,11 @@ public static implicit operator NewStruct((int a, int b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task ConvertFromType4(TestHost host) - { - var text = """ + public Task ConvertFromType4(TestHost host) + => TestAsync(""" class Test { void Method() @@ -837,8 +790,7 @@ void Method() [||](int a, int b) t2 = (a: 1, b: 2); } } - """; - var expected = """ + """, """ class Test { void Method() @@ -890,14 +842,11 @@ public static implicit operator NewStruct((int a, int b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task ConvertSingleTupleTypeInNamespace(TestHost host) - { - var text = """ + public Task ConvertSingleTupleTypeInNamespace(TestHost host) + => TestAsync(""" namespace N { class Test @@ -908,8 +857,7 @@ void Method() } } } - """; - var expected = """ + """, """ namespace N { class Test @@ -963,14 +911,11 @@ public static implicit operator NewStruct((int a, int b) value) } } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task TestNonLiteralNames_WithUsings(TestHost host) - { - var text = """ + public Task TestNonLiteralNames_WithUsings(TestHost host) + => TestAsync(""" using System.Collections.Generic; class Test { @@ -979,8 +924,7 @@ void Method() var t1 = [||](a: {|CS0103:Goo|}(), b: {|CS0103:Bar|}()); } } - """; - var expected = """ + """, """ using System.Collections.Generic; class Test { @@ -1032,14 +976,11 @@ public static implicit operator NewStruct((object a, object b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task TestNonLiteralNames_WithoutUsings(TestHost host) - { - var text = """ + public Task TestNonLiteralNames_WithoutUsings(TestHost host) + => TestAsync(""" class Test { void Method() @@ -1047,8 +988,7 @@ void Method() var t1 = [||](a: {|CS0103:Goo|}(), b: {|CS0103:Bar|}()); } } - """; - var expected = """ + """, """ class Test { void Method() @@ -1099,14 +1039,11 @@ public static implicit operator NewStruct((object a, object b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task ConvertSingleTupleTypeWithInferredName(TestHost host) - { - var text = """ + public Task ConvertSingleTupleTypeWithInferredName(TestHost host) + => TestAsync(""" class Test { void Method(int b) @@ -1114,8 +1051,7 @@ void Method(int b) var t1 = [||](a: 1, b); } } - """; - var expected = """ + """, """ class Test { void Method(int b) @@ -1166,14 +1102,11 @@ public static implicit operator NewStruct((int a, int b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task ConvertMultipleInstancesInSameMethod(TestHost host) - { - var text = """ + public Task ConvertMultipleInstancesInSameMethod(TestHost host) + => TestAsync(""" class Test { void Method() @@ -1182,8 +1115,7 @@ void Method() var t2 = (a: 3, b: 4); } } - """; - var expected = """ + """, """ class Test { void Method() @@ -1235,14 +1167,11 @@ public static implicit operator NewStruct((int a, int b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task ConvertMultipleInstancesAcrossMethods(TestHost host) - { - var text = """ + public Task ConvertMultipleInstancesAcrossMethods(TestHost host) + => TestAsync(""" class Test { void Method() @@ -1257,8 +1186,7 @@ void Method2() var t2 = (a: 3, b: 4); } } - """; - var expected = """ + """, """ class Test { void Method() @@ -1316,14 +1244,11 @@ public static implicit operator NewStruct((int a, int b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task OnlyConvertMatchingTypesInSameMethod(TestHost host) - { - var text = """ + public Task OnlyConvertMatchingTypesInSameMethod(TestHost host) + => TestAsync(""" class Test { void Method(int b) @@ -1334,8 +1259,7 @@ void Method(int b) var t4 = (b: 5, a: 6); } } - """; - var expected = """ + """, """ class Test { void Method(int b) @@ -1389,14 +1313,11 @@ public static implicit operator NewStruct((int a, int b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task TestFixAllMatchesInSingleMethod(TestHost host) - { - var text = """ + public Task TestFixAllMatchesInSingleMethod(TestHost host) + => TestAsync(""" class Test { void Method(int b) @@ -1407,8 +1328,7 @@ void Method(int b) var t4 = (b: 5, a: 6); } } - """; - var expected = """ + """, """ class Test { void Method(int b) @@ -1462,14 +1382,11 @@ public static implicit operator NewStruct((int a, int b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task TestFixNotAcrossMethods(TestHost host) - { - var text = """ + public Task TestFixNotAcrossMethods(TestHost host) + => TestAsync(""" class Test { void Method() @@ -1484,8 +1401,7 @@ void Method2() var t2 = (a: 3, b: 4); } } - """; - var expected = """ + """, """ class Test { void Method() @@ -1543,14 +1459,11 @@ public static implicit operator NewStruct((int a, int b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task TestTrivia_WithUsings(TestHost host) - { - var text = """ + public Task TestTrivia_WithUsings(TestHost host) + => TestAsync(""" using System.Collections.Generic; class Test { @@ -1559,8 +1472,7 @@ void Method() var t1 = /*1*/ [||]( /*2*/ a /*3*/ : /*4*/ 1 /*5*/ , /*6*/ {|CS0103:b|} /*7*/ = /*8*/ 2 /*9*/ ) /*10*/ ; } } - """; - var expected = """ + """, """ using System.Collections.Generic; class Test { @@ -1612,14 +1524,11 @@ public static implicit operator NewStruct((int a, object) value) return new NewStruct(value.a, value.Item2); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task TestTrivia_WithoutUsings(TestHost host) - { - var text = """ + public Task TestTrivia_WithoutUsings(TestHost host) + => TestAsync(""" class Test { void Method() @@ -1627,8 +1536,7 @@ void Method() var t1 = /*1*/ [||]( /*2*/ a /*3*/ : /*4*/ 1 /*5*/ , /*6*/ {|CS0103:b|} /*7*/ = /*8*/ 2 /*9*/ ) /*10*/ ; } } - """; - var expected = """ + """, """ class Test { void Method() @@ -1679,9 +1587,7 @@ public static implicit operator NewStruct((int a, object) value) return new NewStruct(value.a, value.Item2); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] public async Task NotIfReferencesAnonymousTypeInternally(TestHost host) @@ -1700,9 +1606,8 @@ void Method() } [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task ConvertMultipleNestedInstancesInSameMethod1_WithUsings(TestHost host) - { - var text = """ + public Task ConvertMultipleNestedInstancesInSameMethod1_WithUsings(TestHost host) + => TestAsync(""" class Test { void Method() @@ -1710,8 +1615,7 @@ void Method() var t1 = [||](a: 1, b: (object)(a: 1, b: default(object))); } } - """; - var expected = """ + """, """ using System.Collections.Generic; class Test @@ -1764,14 +1668,11 @@ public static implicit operator NewStruct((int a, object b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task ConvertMultipleNestedInstancesInSameMethod1_WithoutUsings(TestHost host) - { - var text = """ + public Task ConvertMultipleNestedInstancesInSameMethod1_WithoutUsings(TestHost host) + => TestAsync(""" class Test { void Method() @@ -1779,8 +1680,7 @@ void Method() var t1 = [||](a: 1, b: (object)(a: 1, b: default(object))); } } - """; - var expected = """ + """, """ using System.Collections.Generic; class Test @@ -1833,14 +1733,11 @@ public static implicit operator NewStruct((int a, object b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task ConvertMultipleNestedInstancesInSameMethod2_WithUsings(TestHost host) - { - var text = """ + public Task ConvertMultipleNestedInstancesInSameMethod2_WithUsings(TestHost host) + => TestAsync(""" class Test { void Method() @@ -1848,8 +1745,7 @@ void Method() var t1 = (a: 1, b: (object)[||](a: 1, b: default(object))); } } - """; - var expected = """ + """, """ using System.Collections.Generic; class Test @@ -1902,14 +1798,11 @@ public static implicit operator NewStruct((int a, object b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task ConvertMultipleNestedInstancesInSameMethod2_WithoutUsings(TestHost host) - { - var text = """ + public Task ConvertMultipleNestedInstancesInSameMethod2_WithoutUsings(TestHost host) + => TestAsync(""" class Test { void Method() @@ -1917,8 +1810,7 @@ void Method() var t1 = (a: 1, b: (object)[||](a: 1, b: default(object))); } } - """; - var expected = """ + """, """ using System.Collections.Generic; class Test @@ -1971,14 +1863,11 @@ public static implicit operator NewStruct((int a, object b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task RenameAnnotationOnStartingPoint(TestHost host) - { - var text = """ + public Task RenameAnnotationOnStartingPoint(TestHost host) + => TestAsync(""" class Test { void Method() @@ -1987,8 +1876,7 @@ void Method() var t2 = [||](a: 3, b: 4); } } - """; - var expected = """ + """, """ class Test { void Method() @@ -2040,14 +1928,11 @@ public static implicit operator NewStruct((int a, int b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task CapturedMethodTypeParameters_WithUsings(TestHost host) - { - var text = """ + public Task CapturedMethodTypeParameters_WithUsings(TestHost host) + => TestAsync(""" using System.Collections.Generic; class Test where X : struct { @@ -2056,8 +1941,7 @@ class Test where X : struct var t1 = [||](a: x, b: y); } } - """; - var expected = """ + """, """ using System.Collections.Generic; class Test where X : struct { @@ -2111,18 +1995,14 @@ public static implicit operator NewStruct((List a, Y[] b) value) return new NewStruct(value.a, value.b); } } - """; - - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host, actions: + """, options: PreferImplicitTypeWithInfo(), testHost: host, actions: [ FeaturesResources.updating_usages_in_containing_member ]); - } [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task CapturedMethodTypeParameters_WithoutUsings(TestHost host) - { - var text = """ + public Task CapturedMethodTypeParameters_WithoutUsings(TestHost host) + => TestAsync(""" class Test where X : struct { void Method(System.Collections.Generic.List x, Y[] y) where Y : class, new() @@ -2130,8 +2010,7 @@ class Test where X : struct var t1 = [||](a: x, b: y); } } - """; - var expected = """ + """, """ using System.Collections.Generic; class Test where X : struct @@ -2186,18 +2065,14 @@ public static implicit operator NewStruct((List a, Y[] b) value) return new NewStruct(value.a, value.b); } } - """; - - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host, actions: + """, options: PreferImplicitTypeWithInfo(), testHost: host, actions: [ FeaturesResources.updating_usages_in_containing_member ]); - } [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task NewTypeNameCollision(TestHost host) - { - var text = """ + public Task NewTypeNameCollision(TestHost host) + => TestAsync(""" class Test { void Method() @@ -2209,8 +2084,7 @@ void Method() class NewStruct { } - """; - var expected = """ + """, """ class Test { void Method() @@ -2265,14 +2139,13 @@ public static implicit operator NewStruct1((int a, int b) value) return new NewStruct1(value.a, value.b); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task TestDuplicatedName(TestHost host) - { - var text = """ + public Task TestDuplicatedName(TestHost host) + => new VerifyCS.Test + { + TestCode = """ class Test { void Method() @@ -2280,8 +2153,8 @@ void Method() var t1 = [||](a: 1, a: 2); } } - """; - var expected = """ + """, + FixedCode = """ class Test { void Method() @@ -2332,12 +2205,7 @@ public static implicit operator NewStruct((int a, int a) value) return new NewStruct(value.a, value.a); } } - """; - - await new VerifyCS.Test - { - TestCode = text, - FixedCode = expected, + """, TestHost = host, ExpectedDiagnostics = { @@ -2408,12 +2276,10 @@ public static implicit operator NewStruct((int a, int a) value) }, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); - } [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task TestInLambda1(TestHost host) - { - var text = """ + public Task TestInLambda1(TestHost host) + => TestAsync(""" using System; class Test @@ -2427,8 +2293,7 @@ void Method() }; } } - """; - var expected = """ + """, """ using System; class Test @@ -2485,14 +2350,11 @@ public static implicit operator NewStruct((int a, int b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task TestInLambda2(TestHost host) - { - var text = """ + public Task TestInLambda2(TestHost host) + => TestAsync(""" using System; class Test @@ -2506,8 +2368,7 @@ void Method() }; } } - """; - var expected = """ + """, """ using System; class Test @@ -2564,14 +2425,11 @@ public static implicit operator NewStruct((int a, int b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task TestInLocalFunction1(TestHost host) - { - var text = """ + public Task TestInLocalFunction1(TestHost host) + => TestAsync(""" using System; class Test @@ -2585,8 +2443,7 @@ void Goo() } } } - """; - var expected = """ + """, """ using System; class Test @@ -2643,14 +2500,11 @@ public static implicit operator NewStruct((int a, int b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task TestInLocalFunction2(TestHost host) - { - var text = """ + public Task TestInLocalFunction2(TestHost host) + => TestAsync(""" using System; class Test @@ -2664,8 +2518,7 @@ void Goo() } } } - """; - var expected = """ + """, """ using System; class Test @@ -2722,14 +2575,11 @@ public static implicit operator NewStruct((int a, int b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); - } + """, options: PreferImplicitTypeWithInfo(), testHost: host); [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task ConvertWithDefaultNames1(TestHost host) - { - var text = """ + public Task ConvertWithDefaultNames1(TestHost host) + => TestAsync(""" class Test { void Method() @@ -2741,8 +2591,7 @@ void Method() var t5 = (Item1: 1, Item2: 2); } } - """; - var expected = """ + """, """ class Test { void Method() @@ -2797,19 +2646,15 @@ public static implicit operator NewStruct((int, int) value) return new NewStruct(value.Item1, value.Item2); } } - """; - - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host, actions: + """, options: PreferImplicitTypeWithInfo(), testHost: host, actions: [ FeaturesResources.updating_usages_in_containing_member, FeaturesResources.updating_usages_in_containing_type, ]); - } [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task ConvertWithDefaultNames2(TestHost host) - { - var text = """ + public Task ConvertWithDefaultNames2(TestHost host) + => TestAsync(""" class Test { void Method() @@ -2821,8 +2666,7 @@ void Method() var t5 = (Item1: 1, Item2: 2); } } - """; - var expected = """ + """, """ class Test { void Method() @@ -2877,23 +2721,20 @@ public static implicit operator NewStruct((int Item1, int Item2) value) return new NewStruct(value.Item1, value.Item2); } } - """; - - await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host, actions: + """, options: PreferImplicitTypeWithInfo(), testHost: host, actions: [ FeaturesResources.updating_usages_in_containing_member, FeaturesResources.updating_usages_in_containing_type, ]); - } #endregion #region update containing type tests [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task TestCapturedTypeParameter_UpdateType_WithUsings(TestHost host) - { - var text = """ + public Task TestCapturedTypeParameter_UpdateType_WithUsings(TestHost host) + => TestAsync( + """ using System; class Test @@ -2914,8 +2755,7 @@ void Blah(T t) var t2 = (a: t, b: 4); } } - """; - var expected = """ + """, """ using System; using System.Collections.Generic; @@ -2980,21 +2820,17 @@ public static implicit operator NewStruct((T a, int b) value) return new NewStruct(value.a, value.b); } } - """; - - await TestAsync( - text, expected, index: 1, equivalenceKey: Scope.ContainingType.ToString(), + """, index: 1, equivalenceKey: Scope.ContainingType.ToString(), options: PreferImplicitTypeWithInfo(), testHost: host, actions: [ FeaturesResources.updating_usages_in_containing_member, FeaturesResources.updating_usages_in_containing_type ]); - } [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task TestCapturedTypeParameter_UpdateType_WithoutUsings(TestHost host) - { - var text = """ + public Task TestCapturedTypeParameter_UpdateType_WithoutUsings(TestHost host) + => TestAsync( + """ class Test { void Method(T t) @@ -3013,8 +2849,7 @@ void Blah(T t) var t2 = (a: t, b: 4); } } - """; - var expected = """ + """, """ using System.Collections.Generic; class Test @@ -3078,21 +2913,17 @@ public static implicit operator NewStruct((T a, int b) value) return new NewStruct(value.a, value.b); } } - """; - - await TestAsync( - text, expected, index: 1, equivalenceKey: Scope.ContainingType.ToString(), + """, index: 1, equivalenceKey: Scope.ContainingType.ToString(), options: PreferImplicitTypeWithInfo(), testHost: host, actions: [ FeaturesResources.updating_usages_in_containing_member, FeaturesResources.updating_usages_in_containing_type ]); - } [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task UpdateAllInType_SinglePart_SingleFile(TestHost host) - { - var text = """ + public Task UpdateAllInType_SinglePart_SingleFile(TestHost host) + => TestAsync( + """ using System; class Test @@ -3115,8 +2946,7 @@ void Method() var t1 = (a: 1, b: 2); } } - """; - var expected = """ + """, """ using System; class Test @@ -3182,16 +3012,13 @@ public static implicit operator NewStruct((int a, int b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync( - text, expected, index: 1, equivalenceKey: Scope.ContainingType.ToString(), + """, index: 1, equivalenceKey: Scope.ContainingType.ToString(), options: PreferImplicitTypeWithInfo(), testHost: host); - } [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] - public async Task UpdateAllInType_MultiplePart_SingleFile(TestHost host) - { - var text = """ + public Task UpdateAllInType_MultiplePart_SingleFile(TestHost host) + => TestAsync( + """ using System; partial class Test @@ -3218,8 +3045,7 @@ void Method() var t1 = (a: 1, b: 2); } } - """; - var expected = """ + """, """ using System; partial class Test @@ -3289,11 +3115,8 @@ public static implicit operator NewStruct((int a, int b) value) return new NewStruct(value.a, value.b); } } - """; - await TestAsync( - text, expected, index: 1, equivalenceKey: Scope.ContainingType.ToString(), + """, index: 1, equivalenceKey: Scope.ContainingType.ToString(), options: PreferImplicitTypeWithInfo(), testHost: host); - } [ConditionalTheory(typeof(DesktopOnly)), CombinatorialData] public async Task UpdateAllInType_MultiplePart_MultipleFile(TestHost host) diff --git a/src/Features/CSharpTest/Copilot/CSharpImplementNotImplementedExceptionDiagnosticAnalyzerTests.cs b/src/Features/CSharpTest/Copilot/CSharpImplementNotImplementedExceptionDiagnosticAnalyzerTests.cs index 6874fc59461ca..1aed18a05b5cb 100644 --- a/src/Features/CSharpTest/Copilot/CSharpImplementNotImplementedExceptionDiagnosticAnalyzerTests.cs +++ b/src/Features/CSharpTest/Copilot/CSharpImplementNotImplementedExceptionDiagnosticAnalyzerTests.cs @@ -16,9 +16,8 @@ namespace Microsoft.CodeAnalysis.CSharp.Copilot.UnitTests; public sealed class CSharpImplementNotImplementedExceptionDiagnosticAnalyzerTests { [Fact] - public async Task TestThrowNotImplementedExceptionInStatement() - { - await new VerifyCS.Test + public Task TestThrowNotImplementedExceptionInStatement() + => new VerifyCS.Test { TestCode = """ using System; @@ -34,12 +33,10 @@ class C LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact] - public async Task TestThrowNotImplementedExceptionInExpression() - { - await new VerifyCS.Test + public Task TestThrowNotImplementedExceptionInExpression() + => new VerifyCS.Test { TestCode = """ using System; @@ -52,12 +49,10 @@ class C LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact] - public async Task TestThrowNotImplementedExceptionInConstructor() - { - await new VerifyCS.Test + public Task TestThrowNotImplementedExceptionInConstructor() + => new VerifyCS.Test { TestCode = """ using System; @@ -73,12 +68,10 @@ class C LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact] - public async Task TestThrowNotImplementedExceptionInDestructor() - { - await new VerifyCS.Test + public Task TestThrowNotImplementedExceptionInDestructor() + => new VerifyCS.Test { TestCode = """ using System; @@ -94,12 +87,10 @@ class C LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact] - public async Task TestThrowNotImplementedExceptionInIndexer() - { - await new VerifyCS.Test + public Task TestThrowNotImplementedExceptionInIndexer() + => new VerifyCS.Test { TestCode = """ using System; @@ -116,12 +107,10 @@ public int this[int index] LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact] - public async Task TestThrowNotImplementedExceptionInEvent() - { - await new VerifyCS.Test + public Task TestThrowNotImplementedExceptionInEvent() + => new VerifyCS.Test { TestCode = """ using System; @@ -138,12 +127,10 @@ public event EventHandler MyEvent LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact] - public async Task TestThrowNotImplementedExceptionInOperator() - { - await new VerifyCS.Test + public Task TestThrowNotImplementedExceptionInOperator() + => new VerifyCS.Test { TestCode = """ using System; @@ -159,12 +146,10 @@ class C LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact] - public async Task TestDifferentFlavorsOfThrowNotImplementedException() - { - await new VerifyCS.Test + public Task TestDifferentFlavorsOfThrowNotImplementedException() + => new VerifyCS.Test { TestCode = """ using System; @@ -234,12 +219,10 @@ internal void ThrowOnAllStatements(bool condition) LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact] - public async Task WhenShouldNotReportOnMember() - { - await new VerifyCS.Test + public Task WhenShouldNotReportOnMember() + => new VerifyCS.Test { TestCode = """ using System; @@ -451,5 +434,4 @@ internal class Person LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } } diff --git a/src/Features/CSharpTest/Copilot/CSharpImplementNotImplementedExceptionFixProviderTests.CodeBlockSuggestions.cs b/src/Features/CSharpTest/Copilot/CSharpImplementNotImplementedExceptionFixProviderTests.CodeBlockSuggestions.cs index b88a61aba1639..06bf2d1f6bcf6 100644 --- a/src/Features/CSharpTest/Copilot/CSharpImplementNotImplementedExceptionFixProviderTests.CodeBlockSuggestions.cs +++ b/src/Features/CSharpTest/Copilot/CSharpImplementNotImplementedExceptionFixProviderTests.CodeBlockSuggestions.cs @@ -28,9 +28,8 @@ public static IEnumerable TestMethodCodeBlockSuggestions() [Theory] [MemberData(nameof(TestMethodCodeBlockSuggestions))] - public async Task FixerResponse_ReplacesCodeBlockCorrectly(string notImplementedCodeBlock, string replacementCodeBlock) - { - await new CustomCompositionCSharpTest + public Task FixerResponse_ReplacesCodeBlockCorrectly(string notImplementedCodeBlock, string replacementCodeBlock) + => new CustomCompositionCSharpTest { CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne | CodeFixTestBehaviors.SkipLocalDiagnosticCheck, TestCode = $$""" @@ -62,119 +61,152 @@ public class TestService }; }) .RunAsync(); - } private static readonly Dictionary s_codeBlockSuggestions = new() { // Single statement with NotImplementedException [ - @"public void {|IDE3000:TestMethod|}() - { - {|IDE3000:throw new NotImplementedException();|} - }" + """ + public void {|IDE3000:TestMethod|}() + { + {|IDE3000:throw new NotImplementedException();|} + } + """ ] = [ @"public void TestMethod() => Console.WriteLine(""Hello, World!"");", - @"public void TestMethod() - { - Console.WriteLine(""This is a single statement""); - }", - @"public void TestMethod() - { - int x = 10; - int y = 20; - Console.WriteLine(x + y); - }", - @"public void TestMethod() - { - /* Comment before */ - Console.WriteLine(""First line""); - /* Comment after */ - Console.WriteLine(""Second line""); - }", - @"public void TestMethod() - { - // Initialize variables - int a = 5; - int b = 10; - // Perform calculation - int result = a + b; - Console.WriteLine(result); - }", - @"public void TestMethod() - { - var list = new int[] { 1, 2, 3, 4, 5 }; - foreach (var item in list) + """ + public void TestMethod() { - Console.WriteLine(item); + Console.WriteLine("This is a single statement"); } - }", - @"public void TestMethod() - { - try + """, + """ + public void TestMethod() { - // Try block - Console.WriteLine(""This is a test method.""); + int x = 10; + int y = 20; + Console.WriteLine(x + y); } - catch (Exception ex) + """, + """ + public void TestMethod() { - Console.WriteLine(ex.Message); + /* Comment before */ + Console.WriteLine("First line"); + /* Comment after */ + Console.WriteLine("Second line"); } - }", - @"public void TestMethod() - { - if (DateTime.Now.DayOfWeek == DayOfWeek.Friday) + """, + """ + public void TestMethod() { - Console.WriteLine(""It's Friday!""); + // Initialize variables + int a = 5; + int b = 10; + // Perform calculation + int result = a + b; + Console.WriteLine(result); } - else + """, + """ + public void TestMethod() { - Console.WriteLine(""It's not Friday.""); + var list = new int[] { 1, 2, 3, 4, 5 }; + foreach (var item in list) + { + Console.WriteLine(item); + } } - }", - @"public void TestMethod() - { - Console.WriteLine(""Start""); // Comment at the end - }", - @"public void TestMethod() - { - /* Multi-line comment at the beginning */ - Console.WriteLine(""Middle""); - }", - @"public void TestMethod() - { - Console.WriteLine(""End""); /* Multi-line comment at the end */ - }", - @"public void TestMethod() - { - // Single-line comment at the beginning - Console.WriteLine(""Middle""); - }", - @"public void TestMethod() - { - Console.WriteLine(""End""); // Single-line comment at the end - }", - @"public void TestMethod() - { - Console.WriteLine(""Hi""); - throw new InvalidOperationException(); - }" + """, + """ + public void TestMethod() + { + try + { + // Try block + Console.WriteLine("This is a test method."); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + """, + """ + public void TestMethod() + { + if (DateTime.Now.DayOfWeek == DayOfWeek.Friday) + { + Console.WriteLine("It's Friday!"); + } + else + { + Console.WriteLine("It's not Friday."); + } + } + """, + """ + public void TestMethod() + { + Console.WriteLine("Start"); // Comment at the end + } + """, + """ + public void TestMethod() + { + /* Multi-line comment at the beginning */ + Console.WriteLine("Middle"); + } + """, + """ + public void TestMethod() + { + Console.WriteLine("End"); /* Multi-line comment at the end */ + } + """, + """ + public void TestMethod() + { + // Single-line comment at the beginning + Console.WriteLine("Middle"); + } + """, + """ + public void TestMethod() + { + Console.WriteLine("End"); // Single-line comment at the end + } + """, + """ + public void TestMethod() + { + Console.WriteLine("Hi"); + throw new InvalidOperationException(); + } + """ ], // Async method with NotImplementedException [ - @"public async Task {|IDE3000:TestMethodAsync|}() - { - {|IDE3000:throw new NotImplementedException();|} - }" + """ + public async Task {|IDE3000:TestMethodAsync|}() + { + {|IDE3000:throw new NotImplementedException();|} + } + """ ] = [ - @"public async Task TestMethodAsync() - { - await Task.Delay(1000); - Console.WriteLine(""Async operation completed""); - }", - @"public async Task TestMethodAsync() - => await Task.Run(() => Console.WriteLine(""Running async task""));" + """ + public async Task TestMethodAsync() + { + await Task.Delay(1000); + Console.WriteLine("Async operation completed"); + } + """, + """ + public async Task TestMethodAsync() + => await Task.Run(() => Console.WriteLine("Running async task")); + """ ], // Property with NotImplementedException in expression-bodied member [ @@ -182,8 +214,10 @@ public class TestService ] = [ @"public int TestProperty => 42;", - @"public int TestProperty - => DateTime.Now.Year;" + """ + public int TestProperty + => DateTime.Now.Year; + """ ] }; } diff --git a/src/Features/CSharpTest/Copilot/CSharpImplementNotImplementedExceptionFixProviderTests.cs b/src/Features/CSharpTest/Copilot/CSharpImplementNotImplementedExceptionFixProviderTests.cs index 3e7bf465b0193..0d937ea4b9e77 100644 --- a/src/Features/CSharpTest/Copilot/CSharpImplementNotImplementedExceptionFixProviderTests.cs +++ b/src/Features/CSharpTest/Copilot/CSharpImplementNotImplementedExceptionFixProviderTests.cs @@ -31,9 +31,8 @@ namespace Microsoft.CodeAnalysis.CSharp.Copilot.UnitTests; public sealed partial class CSharpImplementNotImplementedExceptionFixProviderTests { [Fact] - public async Task FixAll_ParseSuccessfully() - { - await new CustomCompositionCSharpTest + public Task FixAll_ParseSuccessfully() + => new CustomCompositionCSharpTest { CodeFixTestBehaviors = CodeFixTestBehaviors.SkipLocalDiagnosticCheck, TestCode = """ @@ -176,7 +175,7 @@ public interface IMathService } .WithMockCopilotService(copilotService => { - copilotService.SetupFixAll = (Document document, ImmutableDictionary> memberReferences, CancellationToken cancellationToken) => + copilotService.SetupFixAll = (document, memberReferences, cancellationToken) => { // Create a map of method/property implementations var implementationMap = new Dictionary @@ -197,15 +196,13 @@ public interface IMathService }; }) .RunAsync(); - } [Theory] [InlineData("Failed to receive implementation from Copilot service")] [InlineData("Generated implementation doesn't match the original method signature.")] [InlineData("The generated implementation isn't a valid method or property.")] - public async Task NullReplacementNode_MethodHasCommentsInVariousForms_PrintsMessageAsComment(string copilotErrorMessage) - { - await new CustomCompositionCSharpTest + public Task NullReplacementNode_MethodHasCommentsInVariousForms_PrintsMessageAsComment(string copilotErrorMessage) + => new CustomCompositionCSharpTest { CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne | CodeFixTestBehaviors.SkipLocalDiagnosticCheck, TestCode = """ @@ -382,12 +379,10 @@ public interface IDataService }; }) .RunAsync(); - } [Fact] - public async Task HandleInvalidCode_SuggestsAsComment() - { - await new CustomCompositionCSharpTest + public Task HandleInvalidCode_SuggestsAsComment() + => new CustomCompositionCSharpTest { CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne | CodeFixTestBehaviors.SkipLocalDiagnosticCheck, TestCode = """ @@ -447,18 +442,15 @@ void M() }; }) .RunAsync(); - } [Fact] - public async Task ReplacementNode_Null_NotifiesWithComment() - { - await TestHandlesInvalidReplacementNode( + public Task ReplacementNode_Null_NotifiesWithComment() + => TestHandlesInvalidReplacementNode( new() { ReplacementNode = null, Message = "Custom Error Message", }); - } [Theory] [InlineData("class MyClass { }", typeof(ClassDeclarationSyntax))] diff --git a/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureCodeStyle/BooleanCodeStyleOptionConfigurationTests.cs b/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureCodeStyle/BooleanCodeStyleOptionConfigurationTests.cs index e605e190d54b7..1b9c1ea706d83 100644 --- a/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureCodeStyle/BooleanCodeStyleOptionConfigurationTests.cs +++ b/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureCodeStyle/BooleanCodeStyleOptionConfigurationTests.cs @@ -35,9 +35,8 @@ public sealed class TrueConfigurationTests : BooleanCodeStyleOptionConfiguration protected override int CodeActionIndex => 0; [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_Empty_True() - { - var input = """ + public Task ConfigureEditorconfig_Empty_True() + => TestInRegularAndScriptAsync(""" @@ -67,9 +66,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -103,15 +100,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact(Skip = "https://github.com/dotnet/roslyn/issues/39466")] - public async Task ConfigureEditorconfig_RuleExists_True() - { - var input = """ + public Task ConfigureEditorconfig_RuleExists_True() + => TestInRegularAndScriptAsync(""" @@ -143,9 +136,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -177,15 +168,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_InvalidHeader_True() - { - var input = """ + public Task ConfigureEditorconfig_InvalidHeader_True() + => TestInRegularAndScriptAsync(""" @@ -217,9 +204,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -256,15 +241,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact(Skip = "https://github.com/dotnet/roslyn/issues/39466")] - public async Task ConfigureEditorconfig_MaintainSeverity_True() - { - var input = """ + public Task ConfigureEditorconfig_MaintainSeverity_True() + => TestInRegularAndScriptAsync(""" @@ -296,9 +277,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -330,15 +309,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_InvalidRule_True() - { - var input = """ + public Task ConfigureEditorconfig_InvalidRule_True() + => TestInRegularAndScriptAsync(""" @@ -371,9 +346,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -409,10 +382,7 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); } [Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] @@ -421,9 +391,8 @@ public sealed class FalseConfigurationTests : BooleanCodeStyleOptionConfiguratio protected override int CodeActionIndex => 1; [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_Empty_False() - { - var input = """ + public Task ConfigureEditorconfig_Empty_False() + => TestInRegularAndScriptAsync(""" @@ -453,9 +422,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -489,15 +456,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_RuleExists_False() - { - var input = """ + public Task ConfigureEditorconfig_RuleExists_False() + => TestInRegularAndScriptAsync(""" @@ -529,9 +492,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -563,15 +524,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_RuleExists_False_NoSeveritySuffix() - { - var input = """ + public Task ConfigureEditorconfig_RuleExists_False_NoSeveritySuffix() + => TestInRegularAndScriptAsync(""" @@ -603,9 +560,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -637,15 +592,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_RuleExists_DotnetDiagnosticEntry() - { - var input = """ + public Task ConfigureEditorconfig_RuleExists_DotnetDiagnosticEntry() + => TestInRegularAndScriptAsync(""" @@ -677,9 +628,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -714,15 +663,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_RuleExists_ConflitingDotnetDiagnosticEntry() - { - var input = """ + public Task ConfigureEditorconfig_RuleExists_ConflitingDotnetDiagnosticEntry() + => TestInRegularAndScriptAsync(""" @@ -755,9 +700,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -790,15 +733,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_InvalidHeader_False() - { - var input = """ + public Task ConfigureEditorconfig_InvalidHeader_False() + => TestInRegularAndScriptAsync(""" @@ -830,9 +769,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -869,15 +806,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_MaintainSeverity_False() - { - var input = """ + public Task ConfigureEditorconfig_MaintainSeverity_False() + => TestInRegularAndScriptAsync(""" @@ -909,9 +842,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -943,15 +874,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_InvalidRule_False() - { - var input = """ + public Task ConfigureEditorconfig_InvalidRule_False() + => TestInRegularAndScriptAsync(""" @@ -983,9 +910,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -1020,9 +945,6 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); } } diff --git a/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureCodeStyle/EnumCodeStyleOptionConfigurationTests.cs b/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureCodeStyle/EnumCodeStyleOptionConfigurationTests.cs index 7652b1e6529a1..083eb0f1e9588 100644 --- a/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureCodeStyle/EnumCodeStyleOptionConfigurationTests.cs +++ b/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureCodeStyle/EnumCodeStyleOptionConfigurationTests.cs @@ -49,9 +49,8 @@ public sealed class UnusedLocalVariableConfigurationTests : EnumCodeStyleOptionC protected override int CodeActionIndex => 0; [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_Empty_UnusedLocalVariable() - { - var input = """ + public Task ConfigureEditorconfig_Empty_UnusedLocalVariable() + => TestInRegularAndScriptAsync(""" @@ -69,9 +68,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -93,15 +90,11 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_RuleExists_UnusedLocalVariable() - { - var input = """ + public Task ConfigureEditorconfig_RuleExists_UnusedLocalVariable() + => TestInRegularAndScriptAsync(""" @@ -121,9 +114,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -143,15 +134,11 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_RuleExists_DotnetDiagnosticEntry() - { - var input = """ + public Task ConfigureEditorconfig_RuleExists_DotnetDiagnosticEntry() + => TestInRegularAndScriptAsync(""" @@ -171,9 +158,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -196,15 +181,11 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_RuleExists_ConflictingDotnetDiagnosticEntry() - { - var input = """ + public Task ConfigureEditorconfig_RuleExists_ConflictingDotnetDiagnosticEntry() + => TestInRegularAndScriptAsync(""" @@ -225,9 +206,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -248,15 +227,11 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_InvalidHeader_UnusedLocalVariable() - { - var input = """ + public Task ConfigureEditorconfig_InvalidHeader_UnusedLocalVariable() + => TestInRegularAndScriptAsync(""" @@ -276,9 +251,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -303,15 +276,11 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_MaintainSeverity_UnusedLocalVariable() - { - var input = """ + public Task ConfigureEditorconfig_MaintainSeverity_UnusedLocalVariable() + => TestInRegularAndScriptAsync(""" @@ -331,9 +300,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -353,15 +320,11 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_InvalidRule_UnusedLocalVariable() - { - var input = """ + public Task ConfigureEditorconfig_InvalidRule_UnusedLocalVariable() + => TestInRegularAndScriptAsync(""" @@ -381,9 +344,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -406,10 +367,7 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); } [Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] @@ -418,9 +376,8 @@ public sealed class DiscardVariableConfigurationTests : EnumCodeStyleOptionConfi protected override int CodeActionIndex => 1; [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_Empty_DiscardVariable() - { - var input = """ + public Task ConfigureEditorconfig_Empty_DiscardVariable() + => TestInRegularAndScriptAsync(""" @@ -438,9 +395,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -462,15 +417,11 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_RuleExists_DiscardVariable() - { - var input = """ + public Task ConfigureEditorconfig_RuleExists_DiscardVariable() + => TestInRegularAndScriptAsync(""" @@ -490,9 +441,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -512,15 +461,11 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_RuleExists_DiscardVariable_WithoutSeveritySuffix() - { - var input = """ + public Task ConfigureEditorconfig_RuleExists_DiscardVariable_WithoutSeveritySuffix() + => TestInRegularAndScriptAsync(""" @@ -540,9 +485,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -562,15 +505,11 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_InvalidHeader_DiscardVariable() - { - var input = """ + public Task ConfigureEditorconfig_InvalidHeader_DiscardVariable() + => TestInRegularAndScriptAsync(""" @@ -590,9 +529,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -617,15 +554,11 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_MaintainSeverity_DiscardVariable() - { - var input = """ + public Task ConfigureEditorconfig_MaintainSeverity_DiscardVariable() + => TestInRegularAndScriptAsync(""" @@ -645,9 +578,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -667,15 +598,11 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_InvalidRule_DiscardVariable() - { - var input = """ + public Task ConfigureEditorconfig_InvalidRule_DiscardVariable() + => TestInRegularAndScriptAsync(""" @@ -695,9 +622,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -720,9 +645,6 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); } } diff --git a/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureCodeStyle/MultipleCodeStyleOptionConfigurationTests.cs b/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureCodeStyle/MultipleCodeStyleOptionConfigurationTests.cs index e3784347cbf6b..bd088d06ab016 100644 --- a/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureCodeStyle/MultipleCodeStyleOptionConfigurationTests.cs +++ b/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureCodeStyle/MultipleCodeStyleOptionConfigurationTests.cs @@ -53,9 +53,8 @@ public sealed class VarElsewhere_TrueConfigurationTests : MultipleCodeStyleOptio protected override int CodeActionIndex => 0; [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_Empty_True() - { - var input = """ + public Task ConfigureEditorconfig_Empty_True() + => TestInRegularAndScriptAsync(""" @@ -71,9 +70,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -93,15 +90,11 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_RuleExists_True() - { - var input = """ + public Task ConfigureEditorconfig_RuleExists_True() + => TestInRegularAndScriptAsync(""" @@ -120,9 +113,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -141,15 +132,11 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_RuleExists_True_WithoutSeveritySuffix() - { - var input = """ + public Task ConfigureEditorconfig_RuleExists_True_WithoutSeveritySuffix() + => TestInRegularAndScriptAsync(""" @@ -168,9 +155,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -189,15 +174,11 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_InvalidHeader_True() - { - var input = """ + public Task ConfigureEditorconfig_InvalidHeader_True() + => TestInRegularAndScriptAsync(""" @@ -215,9 +196,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -240,15 +219,11 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_MaintainSeverity_True() - { - var input = """ + public Task ConfigureEditorconfig_MaintainSeverity_True() + => TestInRegularAndScriptAsync(""" @@ -266,9 +241,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -286,15 +259,11 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_InvalidRule_True() - { - var input = """ + public Task ConfigureEditorconfig_InvalidRule_True() + => TestInRegularAndScriptAsync(""" @@ -312,9 +281,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -335,10 +302,7 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); } [Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] @@ -349,9 +313,8 @@ public sealed class VarForBuiltInTypes_FalseConfigurationTests : MultipleCodeSty protected override int CodeActionIndex => 1; [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_Empty_False() - { - var input = """ + public Task ConfigureEditorconfig_Empty_False() + => TestInRegularAndScriptAsync(""" @@ -367,9 +330,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -389,15 +350,11 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_RuleExists_False() - { - var input = """ + public Task ConfigureEditorconfig_RuleExists_False() + => TestInRegularAndScriptAsync(""" @@ -415,9 +372,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -435,15 +390,11 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_RuleExists_False_WithoutSeveritySuffix() - { - var input = """ + public Task ConfigureEditorconfig_RuleExists_False_WithoutSeveritySuffix() + => TestInRegularAndScriptAsync(""" @@ -461,9 +412,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -481,15 +430,11 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_InvalidHeader_False() - { - var input = """ + public Task ConfigureEditorconfig_InvalidHeader_False() + => TestInRegularAndScriptAsync(""" @@ -507,9 +452,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -532,15 +475,11 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_MaintainSeverity_False() - { - var input = """ + public Task ConfigureEditorconfig_MaintainSeverity_False() + => TestInRegularAndScriptAsync(""" @@ -558,9 +497,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -578,15 +515,11 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_InvalidRule_False() - { - var input = """ + public Task ConfigureEditorconfig_InvalidRule_False() + => TestInRegularAndScriptAsync(""" @@ -604,9 +537,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -627,9 +558,6 @@ static void Main() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); } } diff --git a/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/AllAnalyzersSeverityConfigurationTests.cs b/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/AllAnalyzersSeverityConfigurationTests.cs index 4ab812a36302e..60033709f3b95 100644 --- a/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/AllAnalyzersSeverityConfigurationTests.cs +++ b/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/AllAnalyzersSeverityConfigurationTests.cs @@ -62,9 +62,8 @@ public sealed class SilentConfigurationTests : AllAnalyzersSeverityConfiguration protected override int CodeActionIndex => 11; [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_Empty() - { - var input = """ + public Task ConfigureEditorconfig_Empty() + => TestInRegularAndScriptAsync(""" @@ -73,9 +72,7 @@ public async Task ConfigureEditorconfig_Empty() - """; - - var expected = """ + """, """ @@ -88,15 +85,11 @@ class Program1 { } - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_RuleExists() - { - var input = """ + public Task ConfigureEditorconfig_RuleExists() + => TestInRegularAndScriptAsync(""" @@ -107,9 +100,7 @@ public async Task ConfigureEditorconfig_RuleExists() - """; - - var expected = """ + """, """ @@ -120,15 +111,11 @@ class Program1 { } - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_RuleIdEntryExists() - { - var input = """ + public Task ConfigureEditorconfig_RuleIdEntryExists() + => TestInRegularAndScriptAsync(""" @@ -140,9 +127,7 @@ public async Task ConfigureEditorconfig_RuleIdEntryExists() - """; - - var expected = """ + """, """ @@ -157,15 +142,11 @@ class Program1 { } - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_InvalidHeader() - { - var input = """ + public Task ConfigureEditorconfig_InvalidHeader() + => TestInRegularAndScriptAsync(""" @@ -176,9 +157,7 @@ public async Task ConfigureEditorconfig_InvalidHeader() - """; - - var expected = """ + """, """ @@ -194,10 +173,7 @@ class Program1 { } - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] public async Task ConfigureEditorconfig_MaintainExistingEntry() @@ -219,9 +195,8 @@ public async Task ConfigureEditorconfig_MaintainExistingEntry() } [Fact] - public async Task ConfigureEditorconfig_DiagnosticsSuppressed() - { - var input = """ + public Task ConfigureEditorconfig_DiagnosticsSuppressed() + => TestMissingInRegularAndScriptAsync(""" @@ -232,15 +207,11 @@ public async Task ConfigureEditorconfig_DiagnosticsSuppressed() - """; - - await TestMissingInRegularAndScriptAsync(input); - } + """); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_InvalidRule() - { - var input = """ + public Task ConfigureEditorconfig_InvalidRule() + => TestInRegularAndScriptAsync(""" @@ -251,9 +222,7 @@ public async Task ConfigureEditorconfig_InvalidRule() - """; - - var expected = """ + """, """ @@ -267,17 +236,11 @@ public async Task ConfigureEditorconfig_InvalidRule() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_RegexHeaderMatch() - { - // NOTE: Even though we have a regex match, bulk configuration code fix is always applied to all files - // within the editorconfig cone, so it generates a new entry. - var input = """ + public Task ConfigureEditorconfig_RegexHeaderMatch() + => TestInRegularAndScriptAsync(""" @@ -289,9 +252,7 @@ public async Task ConfigureEditorconfig_RegexHeaderMatch() - """; - - var expected = """ + """, """ @@ -308,15 +269,11 @@ class Program1 { } - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_RegexHeaderNonMatch() - { - var input = """ + public Task ConfigureEditorconfig_RegexHeaderNonMatch() + => TestInRegularAndScriptAsync(""" @@ -328,9 +285,7 @@ public async Task ConfigureEditorconfig_RegexHeaderNonMatch() - """; - - var expected = """ + """, """ @@ -347,9 +302,6 @@ class Program1 { } - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); } } diff --git a/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/CSharpCodeStyleOptionBasedSeverityConfigurationTests.cs b/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/CSharpCodeStyleOptionBasedSeverityConfigurationTests.cs index 9eef526cd0263..6348b99f8bebb 100644 --- a/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/CSharpCodeStyleOptionBasedSeverityConfigurationTests.cs +++ b/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/CSharpCodeStyleOptionBasedSeverityConfigurationTests.cs @@ -35,9 +35,8 @@ public sealed class ErrorConfigurationTests : CSharpCodeStyleOptionBasedSeverity protected override int CodeActionIndex => 4; [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_Empty_Error() - { - var input = """ + public Task ConfigureEditorconfig_Empty_Error() + => TestInRegularAndScriptAsync(""" @@ -56,9 +55,7 @@ public int Test() - """; - - var expected = """ + """, """ @@ -80,15 +77,11 @@ public int Test() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_ExistingRule_Error() - { - var input = """ + public Task ConfigureEditorconfig_ExistingRule_Error() + => TestInRegularAndScriptAsync(""" @@ -111,9 +104,7 @@ public int Test() - """; - - var expected = """ + """, """ @@ -136,15 +127,11 @@ public int Test() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_ExistingRuleDotNetHeader_Error() - { - var input = """ + public Task ConfigureEditorconfig_ExistingRuleDotNetHeader_Error() + => TestInRegularAndScriptAsync(""" @@ -167,9 +154,7 @@ public int Test() - """; - - var expected = """ + """, """ @@ -192,15 +177,11 @@ public int Test() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_ChooseBestHeader_Error() - { - var input = """ + public Task ConfigureEditorconfig_ChooseBestHeader_Error() + => TestInRegularAndScriptAsync(""" @@ -223,9 +204,7 @@ public int Test() - """; - - var expected = """ + """, """ @@ -251,15 +230,11 @@ public int Test() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_ChooseBestHeaderReversed_Error() - { - var input = """ + public Task ConfigureEditorconfig_ChooseBestHeaderReversed_Error() + => TestInRegularAndScriptAsync(""" @@ -282,9 +257,7 @@ public int Test() - """; - - var expected = """ + """, """ @@ -310,9 +283,6 @@ public int Test() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); } } diff --git a/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/CategoryBasedSeverityConfigurationTests.cs b/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/CategoryBasedSeverityConfigurationTests.cs index 4d1f288a4b60f..b4e367a7025bd 100644 --- a/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/CategoryBasedSeverityConfigurationTests.cs +++ b/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/CategoryBasedSeverityConfigurationTests.cs @@ -62,9 +62,8 @@ public sealed class SilentConfigurationTests : CategoryBasedSeverityConfiguratio protected override int CodeActionIndex => 6; [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_Empty() - { - var input = """ + public Task ConfigureEditorconfig_Empty() + => TestInRegularAndScriptAsync(""" @@ -73,9 +72,7 @@ public async Task ConfigureEditorconfig_Empty() - """; - - var expected = """ + """, """ @@ -88,15 +85,11 @@ class Program1 { } - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_RuleExists() - { - var input = """ + public Task ConfigureEditorconfig_RuleExists() + => TestInRegularAndScriptAsync(""" @@ -107,9 +100,7 @@ public async Task ConfigureEditorconfig_RuleExists() - """; - - var expected = """ + """, """ @@ -120,15 +111,11 @@ class Program1 { } - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_RuleIdEntryExists() - { - var input = """ + public Task ConfigureEditorconfig_RuleIdEntryExists() + => TestInRegularAndScriptAsync(""" @@ -139,9 +126,7 @@ public async Task ConfigureEditorconfig_RuleIdEntryExists() - """; - - var expected = """ + """, """ @@ -155,15 +140,11 @@ class Program1 { } - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_InvalidHeader() - { - var input = """ + public Task ConfigureEditorconfig_InvalidHeader() + => TestInRegularAndScriptAsync(""" @@ -174,9 +155,7 @@ public async Task ConfigureEditorconfig_InvalidHeader() - """; - - var expected = """ + """, """ @@ -192,10 +171,7 @@ class Program1 { } - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] public async Task ConfigureEditorconfig_MaintainExistingEntry() @@ -217,9 +193,8 @@ public async Task ConfigureEditorconfig_MaintainExistingEntry() } [Fact] - public async Task ConfigureEditorconfig_DiagnosticsSuppressed() - { - var input = """ + public Task ConfigureEditorconfig_DiagnosticsSuppressed() + => TestMissingInRegularAndScriptAsync(""" @@ -230,15 +205,11 @@ public async Task ConfigureEditorconfig_DiagnosticsSuppressed() - """; - - await TestMissingInRegularAndScriptAsync(input); - } + """); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_InvalidRule() - { - var input = """ + public Task ConfigureEditorconfig_InvalidRule() + => TestInRegularAndScriptAsync(""" @@ -249,9 +220,7 @@ public async Task ConfigureEditorconfig_InvalidRule() - """; - - var expected = """ + """, """ @@ -265,17 +234,11 @@ public async Task ConfigureEditorconfig_InvalidRule() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_RegexHeaderMatch() - { - // NOTE: Even though we have a regex match, bulk configuration code fix is always applied to all files - // within the editorconfig cone, so it generates a new entry. - var input = """ + public Task ConfigureEditorconfig_RegexHeaderMatch() + => TestInRegularAndScriptAsync(""" @@ -287,9 +250,7 @@ public async Task ConfigureEditorconfig_RegexHeaderMatch() - """; - - var expected = """ + """, """ @@ -306,15 +267,11 @@ class Program1 { } - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_RegexHeaderNonMatch() - { - var input = """ + public Task ConfigureEditorconfig_RegexHeaderNonMatch() + => TestInRegularAndScriptAsync(""" @@ -326,9 +283,7 @@ public async Task ConfigureEditorconfig_RegexHeaderNonMatch() - """; - - var expected = """ + """, """ @@ -345,9 +300,6 @@ class Program1 { } - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); } } diff --git a/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/CodeStyleOptionBasedSeverityConfigurationTests.cs b/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/CodeStyleOptionBasedSeverityConfigurationTests.cs index 1717f0862b108..76298d09bc94d 100644 --- a/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/CodeStyleOptionBasedSeverityConfigurationTests.cs +++ b/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/CodeStyleOptionBasedSeverityConfigurationTests.cs @@ -35,9 +35,8 @@ public sealed class NoneConfigurationTests : CodeStyleOptionBasedSeverityConfigu protected override int CodeActionIndex => 0; [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_Empty_None() - { - var input = """ + public Task ConfigureEditorconfig_Empty_None() + => TestInRegularAndScriptAsync(""" @@ -67,9 +66,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -103,15 +100,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_RuleExists_None() - { - var input = """ + public Task ConfigureEditorconfig_RuleExists_None() + => TestInRegularAndScriptAsync(""" @@ -144,9 +137,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -179,15 +170,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_InvalidHeader_None() - { - var input = """ + public Task ConfigureEditorconfig_InvalidHeader_None() + => TestInRegularAndScriptAsync(""" @@ -219,9 +206,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -258,15 +243,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_MaintainOption_None() - { - var input = """ + public Task ConfigureEditorconfig_MaintainOption_None() + => TestInRegularAndScriptAsync(""" @@ -299,9 +280,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -334,15 +313,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_InvalidRule_None() - { - var input = """ + public Task ConfigureEditorconfig_InvalidRule_None() + => TestInRegularAndScriptAsync(""" @@ -375,9 +350,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -413,10 +386,7 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); } [Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] @@ -425,9 +395,8 @@ public sealed class SilentConfigurationTests : CodeStyleOptionBasedSeverityConfi protected override int CodeActionIndex => 1; [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_Empty_Silent() - { - var input = """ + public Task ConfigureEditorconfig_Empty_Silent() + => TestInRegularAndScriptAsync(""" @@ -457,9 +426,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -493,15 +460,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_RuleExists_Silent() - { - var input = """ + public Task ConfigureEditorconfig_RuleExists_Silent() + => TestInRegularAndScriptAsync(""" @@ -533,9 +496,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -567,10 +528,7 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); } [Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] @@ -579,9 +537,8 @@ public sealed class SuggestionConfigurationTests : CodeStyleOptionBasedSeverityC protected override int CodeActionIndex => 2; [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_Empty_Suggestion() - { - var input = """ + public Task ConfigureEditorconfig_Empty_Suggestion() + => TestInRegularAndScriptAsync(""" @@ -611,9 +568,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -647,15 +602,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_RuleExists_Suggestion() - { - var input = """ + public Task ConfigureEditorconfig_RuleExists_Suggestion() + => TestInRegularAndScriptAsync(""" @@ -688,9 +639,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -723,10 +672,7 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); } [Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] @@ -735,9 +681,8 @@ public sealed class WarningConfigurationTests : CodeStyleOptionBasedSeverityConf protected override int CodeActionIndex => 3; [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_Empty_Warning() - { - var input = """ + public Task ConfigureEditorconfig_Empty_Warning() + => TestInRegularAndScriptAsync(""" @@ -767,9 +712,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -803,15 +746,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_RuleExists_Warning() - { - var input = """ + public Task ConfigureEditorconfig_RuleExists_Warning() + => TestInRegularAndScriptAsync(""" @@ -843,9 +782,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -877,10 +814,7 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); } [Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] @@ -889,9 +823,8 @@ public sealed class ErrorConfigurationTests : CodeStyleOptionBasedSeverityConfig protected override int CodeActionIndex => 4; [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_Empty_Error() - { - var input = """ + public Task ConfigureEditorconfig_Empty_Error() + => TestInRegularAndScriptAsync(""" @@ -921,9 +854,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -957,15 +888,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_RuleExists_CodeStyleBased_Error() - { - var input = """ + public Task ConfigureEditorconfig_RuleExists_CodeStyleBased_Error() + => TestInRegularAndScriptAsync(""" @@ -997,9 +924,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -1034,15 +959,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_RuleExists_SeverityBased_Error() - { - var input = """ + public Task ConfigureEditorconfig_RuleExists_SeverityBased_Error() + => TestInRegularAndScriptAsync(""" @@ -1074,9 +995,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -1108,15 +1027,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_RuleExists_CodeStyleAndSeverityBased_Error() - { - var input = """ + public Task ConfigureEditorconfig_RuleExists_CodeStyleAndSeverityBased_Error() + => TestInRegularAndScriptAsync(""" @@ -1149,9 +1064,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -1184,15 +1097,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_InvalidHeader_Error() - { - var input = """ + public Task ConfigureEditorconfig_InvalidHeader_Error() + => TestInRegularAndScriptAsync(""" @@ -1224,9 +1133,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -1263,15 +1170,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_InvalidRule_Error() - { - var input = """ + public Task ConfigureEditorconfig_InvalidRule_Error() + => TestInRegularAndScriptAsync(""" @@ -1304,9 +1207,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -1342,15 +1243,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_ConcreteHeader_Error() - { - var input = """ + public Task ConfigureEditorconfig_ConcreteHeader_Error() + => TestInRegularAndScriptAsync(""" @@ -1383,9 +1280,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -1418,15 +1313,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_NestedDirectory_Error() - { - var input = """ + public Task ConfigureEditorconfig_NestedDirectory_Error() + => TestInRegularAndScriptAsync(""" @@ -1459,9 +1350,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -1494,15 +1383,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_NestedDirectoryNestedHeader_Error() - { - var input = """ + public Task ConfigureEditorconfig_NestedDirectoryNestedHeader_Error() + => TestInRegularAndScriptAsync(""" @@ -1535,9 +1420,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -1570,15 +1453,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_NestedDirectoryIncorrectHeader_Error() - { - var input = """ + public Task ConfigureEditorconfig_NestedDirectoryIncorrectHeader_Error() + => TestInRegularAndScriptAsync(""" @@ -1611,9 +1490,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -1651,15 +1528,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_IncorrectExtension_Error() - { - var input = """ + public Task ConfigureEditorconfig_IncorrectExtension_Error() + => TestInRegularAndScriptAsync(""" @@ -1692,9 +1565,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -1732,15 +1603,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_HeaderRegex_Error() - { - var input = """ + public Task ConfigureEditorconfig_HeaderRegex_Error() + => TestInRegularAndScriptAsync(""" @@ -1773,9 +1640,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -1808,15 +1673,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_HeaderAllFiles_Error() - { - var input = """ + public Task ConfigureEditorconfig_HeaderAllFiles_Error() + => TestInRegularAndScriptAsync(""" @@ -1849,9 +1710,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -1884,15 +1743,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_MultipleHeaders_Error() - { - var input = """ + public Task ConfigureEditorconfig_MultipleHeaders_Error() + => TestInRegularAndScriptAsync(""" @@ -1940,9 +1795,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -1990,15 +1843,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_RegexPartialMatch_Error() - { - var input = """ + public Task ConfigureEditorconfig_RegexPartialMatch_Error() + => TestInRegularAndScriptAsync(""" @@ -2030,9 +1879,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -2069,15 +1916,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_VerifyCaseInsensitive_Warning() - { - var input = """ + public Task ConfigureEditorconfig_VerifyCaseInsensitive_Warning() + => TestInRegularAndScriptAsync(""" @@ -2109,9 +1952,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -2143,15 +1984,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_DuplicateRule_Error() - { - var input = """ + public Task ConfigureEditorconfig_DuplicateRule_Error() + => TestInRegularAndScriptAsync(""" @@ -2188,9 +2025,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -2227,15 +2062,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_ChooseBestHeader_Error() - { - var input = """ + public Task ConfigureEditorconfig_ChooseBestHeader_Error() + => TestInRegularAndScriptAsync(""" @@ -2270,9 +2101,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -2310,15 +2139,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_ChooseBestHeaderReversed_Error() - { - var input = """ + public Task ConfigureEditorconfig_ChooseBestHeaderReversed_Error() + => TestInRegularAndScriptAsync(""" @@ -2353,9 +2178,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -2393,15 +2216,11 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_DotFileName_Error() - { - var input = """ + public Task ConfigureEditorconfig_DotFileName_Error() + => TestInRegularAndScriptAsync(""" @@ -2436,9 +2255,7 @@ public Customer() - """; - - var expected = """ + """, """ @@ -2473,9 +2290,6 @@ public Customer() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); } } diff --git a/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/DotNetDiagnosticSeverityBasedSeverityConfigurationTests.cs b/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/DotNetDiagnosticSeverityBasedSeverityConfigurationTests.cs index d7c281542ee12..576b46278a070 100644 --- a/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/DotNetDiagnosticSeverityBasedSeverityConfigurationTests.cs +++ b/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/DotNetDiagnosticSeverityBasedSeverityConfigurationTests.cs @@ -56,9 +56,8 @@ public sealed class NoneConfigurationTests : DotNetDiagnosticSeverityBasedSeveri protected override int CodeActionIndex => 0; [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_Empty_None() - { - var input = """ + public Task ConfigureEditorconfig_Empty_None() + => TestInRegularAndScriptAsync(""" @@ -67,9 +66,7 @@ public async Task ConfigureEditorconfig_Empty_None() - """; - - var expected = """ + """, """ @@ -82,15 +79,11 @@ class Program1 { } - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_RuleExists_None() - { - var input = """ + public Task ConfigureEditorconfig_RuleExists_None() + => TestInRegularAndScriptAsync(""" @@ -101,9 +94,7 @@ public async Task ConfigureEditorconfig_RuleExists_None() - """; - - var expected = """ + """, """ @@ -114,15 +105,11 @@ class Program1 { } - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_InvalidHeader_None() - { - var input = """ + public Task ConfigureEditorconfig_InvalidHeader_None() + => TestInRegularAndScriptAsync(""" @@ -133,9 +120,7 @@ public async Task ConfigureEditorconfig_InvalidHeader_None() - """; - - var expected = """ + """, """ @@ -151,15 +136,11 @@ class Program1 { } - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureEditorconfig_MaintainExistingEntry_None() - { - var input = """ + public Task ConfigureEditorconfig_MaintainExistingEntry_None() + => TestMissingInRegularAndScriptAsync(""" @@ -170,15 +151,11 @@ public async Task ConfigureEditorconfig_MaintainExistingEntry_None() - """; - - await TestMissingInRegularAndScriptAsync(input); - } + """); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_InvalidRule_None() - { - var input = """ + public Task ConfigureEditorconfig_InvalidRule_None() + => TestInRegularAndScriptAsync(""" @@ -189,9 +166,7 @@ public async Task ConfigureEditorconfig_InvalidRule_None() - """; - - var expected = """ + """, """ @@ -205,16 +180,12 @@ public async Task ConfigureEditorconfig_InvalidRule_None() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] [WorkItem("https://github.com/dotnet/roslyn/issues/45446")] - public async Task ConfigureEditorconfig_MissingRule_None() - { - var input = """ + public Task ConfigureEditorconfig_MissingRule_None() + => TestInRegularAndScriptAsync(""" @@ -225,9 +196,7 @@ public async Task ConfigureEditorconfig_MissingRule_None() - """; - - var expected = """ + """, """ @@ -241,15 +210,11 @@ public async Task ConfigureEditorconfig_MissingRule_None() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_RegexHeaderMatch_None() - { - var input = """ + public Task ConfigureEditorconfig_RegexHeaderMatch_None() + => TestInRegularAndScriptAsync(""" @@ -261,9 +226,7 @@ public async Task ConfigureEditorconfig_RegexHeaderMatch_None() - """; - - var expected = """ + """, """ @@ -275,15 +238,11 @@ class Program1 { } - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_RegexHeaderNonMatch_None() - { - var input = """ + public Task ConfigureEditorconfig_RegexHeaderNonMatch_None() + => TestInRegularAndScriptAsync(""" @@ -295,9 +254,7 @@ public async Task ConfigureEditorconfig_RegexHeaderNonMatch_None() - """; - - var expected = """ + """, """ @@ -314,15 +271,11 @@ class Program1 { } - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureGlobalconfig_Empty_None() - { - var input = """ + public Task ConfigureGlobalconfig_Empty_None() + => TestInRegularAndScriptAsync(""" @@ -331,9 +284,7 @@ public async Task ConfigureGlobalconfig_Empty_None() is_global = true - """; - - var expected = """ + """, """ @@ -346,15 +297,11 @@ class Program1 { } - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] - public async Task ConfigureGlobalconfig_RuleExists_None() - { - var input = """ + public Task ConfigureGlobalconfig_RuleExists_None() + => TestInRegularAndScriptAsync(""" @@ -365,9 +312,7 @@ public async Task ConfigureGlobalconfig_RuleExists_None() - """; - - var expected = """ + """, """ @@ -378,15 +323,11 @@ class Program1 { } - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureGlobalconfig_InvalidHeader_None() - { - var input = """ + public Task ConfigureGlobalconfig_InvalidHeader_None() + => TestInRegularAndScriptAsync(""" @@ -397,9 +338,7 @@ public async Task ConfigureGlobalconfig_InvalidHeader_None() - """; - - var expected = """ + """, """ @@ -415,9 +354,6 @@ class Program1 { } - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); } } diff --git a/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/MultipleCodeStyleOptionBasedSeverityConfigurationTests.cs b/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/MultipleCodeStyleOptionBasedSeverityConfigurationTests.cs index 82b8ce30ca8ca..af012ec15a752 100644 --- a/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/MultipleCodeStyleOptionBasedSeverityConfigurationTests.cs +++ b/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/MultipleCodeStyleOptionBasedSeverityConfigurationTests.cs @@ -36,9 +36,8 @@ public sealed class ErrorConfigurationTests : MultipleCodeStyleOptionBasedSeveri [WorkItem("https://github.com/dotnet/roslyn/issues/39664")] [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_Empty_Error() - { - var input = """ + public Task ConfigureEditorconfig_Empty_Error() + => TestInRegularAndScriptAsync(""" @@ -67,9 +66,7 @@ static void Main(string[] args) - """; - - var expected = """ + """, """ @@ -102,16 +99,12 @@ static void Main(string[] args) - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [WorkItem("https://github.com/dotnet/roslyn/issues/39664")] [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_BothRulesExist_Error() - { - var input = """ + public Task ConfigureEditorconfig_BothRulesExist_Error() + => TestInRegularAndScriptAsync(""" @@ -147,9 +140,7 @@ static void Main(string[] args) - """; - - var expected = """ + """, """ @@ -188,16 +179,12 @@ static void Main(string[] args) - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [WorkItem("https://github.com/dotnet/roslyn/issues/39664")] [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_OneRuleExists_Error() - { - var input = """ + public Task ConfigureEditorconfig_OneRuleExists_Error() + => TestInRegularAndScriptAsync(""" @@ -230,9 +217,7 @@ static void Main(string[] args) - """; - - var expected = """ + """, """ @@ -268,16 +253,12 @@ static void Main(string[] args) - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [WorkItem("https://github.com/dotnet/roslyn/issues/39664")] [ConditionalFact(typeof(IsEnglishLocal))] - public async Task ConfigureEditorconfig_AllPossibleEntriesExist_Error() - { - var input = """ + public Task ConfigureEditorconfig_AllPossibleEntriesExist_Error() + => TestInRegularAndScriptAsync(""" @@ -316,9 +297,7 @@ static void Main(string[] args) - """; - - var expected = """ + """, """ @@ -357,9 +336,6 @@ static void Main(string[] args) - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); - } + """, CodeActionIndex); } } diff --git a/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/VarForBuiltInTypesSeverityConfigurationTests.cs b/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/VarForBuiltInTypesSeverityConfigurationTests.cs index 775dfe39c8714..7907d2c9a3874 100644 --- a/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/VarForBuiltInTypesSeverityConfigurationTests.cs +++ b/src/Features/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/VarForBuiltInTypesSeverityConfigurationTests.cs @@ -35,8 +35,7 @@ public async Task MaintainValue() // specified in the editorconfig that's different from the default value: Assert.False(CSharpCodeStyleOptions.VarForBuiltInTypes.DefaultValue.Value); Assert.Equal(NotificationOption2.Silent, CSharpCodeStyleOptions.VarForBuiltInTypes.DefaultValue.Notification); - - var input = """ + await TestInRegularAndScriptAsync(""" @@ -49,9 +48,7 @@ public async Task MaintainValue() - """; - - var expected = """ + """, """ @@ -64,8 +61,6 @@ public async Task MaintainValue() - """; - - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); + """, CodeActionIndex); } } diff --git a/src/Features/CSharpTest/Diagnostics/Suppression/RemoveSuppressionTests.cs b/src/Features/CSharpTest/Diagnostics/Suppression/RemoveSuppressionTests.cs index bf77df784d610..c875ec80500ae 100644 --- a/src/Features/CSharpTest/Diagnostics/Suppression/RemoveSuppressionTests.cs +++ b/src/Features/CSharpTest/Diagnostics/Suppression/RemoveSuppressionTests.cs @@ -60,512 +60,520 @@ internal override Tuple CreateDia } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] - public async Task TestRemovePragmaSuppression() - { - await TestAsync( - @" -using System; + public Task TestRemovePragmaSuppression() + => TestAsync( + """ -#pragma warning disable InfoDiagnostic // InfoDiagnostic Title -[|class Class|] -#pragma warning restore InfoDiagnostic // InfoDiagnostic Title -{ - int Method() - { - int x = 0; - } -}", - @" -using System; + using System; -class Class -{ - int Method() + #pragma warning disable InfoDiagnostic // InfoDiagnostic Title + [|class Class|] + #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { - int x = 0; - } -}"); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] - public async Task TestRemovePragmaSuppression_AdjacentTrivia() + int Method() { - await TestAsync( - @" -using System; - -#pragma warning disable InfoDiagnostic // InfoDiagnostic Title -class Class1 { } -#pragma warning restore InfoDiagnostic // InfoDiagnostic Title -#pragma warning disable InfoDiagnostic // InfoDiagnostic Title -[|class Class2|] -#pragma warning restore InfoDiagnostic // InfoDiagnostic Title -{ - int Method() - { - int x = 0; + int x = 0; + } } -}", - @" -using System; + """, + """ -#pragma warning disable InfoDiagnostic // InfoDiagnostic Title -class Class1 { } -#pragma warning restore InfoDiagnostic // InfoDiagnostic Title -class Class2 -{ - int Method() + using System; + + class Class { - int x = 0; - } -}"); + int Method() + { + int x = 0; } + } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] - public async Task TestRemovePragmaSuppression_TriviaWithMultipleIDs() - { - await TestAsync( - @" -using System; + public Task TestRemovePragmaSuppression_AdjacentTrivia() + => TestAsync( + """ -#pragma warning disable InfoDiagnostic, SomeOtherDiagnostic -[|class Class|] -#pragma warning restore InfoDiagnostic, SomeOtherDiagnostic -{ - int Method() + using System; + + #pragma warning disable InfoDiagnostic // InfoDiagnostic Title + class Class1 { } + #pragma warning restore InfoDiagnostic // InfoDiagnostic Title + #pragma warning disable InfoDiagnostic // InfoDiagnostic Title + [|class Class2|] + #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { - int x = 0; + int Method() + { + int x = 0; + } } -}", - @" -using System; + """, + """ -#pragma warning disable InfoDiagnostic, SomeOtherDiagnostic -#pragma warning restore InfoDiagnostic // InfoDiagnostic Title -class Class -#pragma warning disable InfoDiagnostic // InfoDiagnostic Title -#pragma warning restore InfoDiagnostic, SomeOtherDiagnostic -{ - int Method() + using System; + + #pragma warning disable InfoDiagnostic // InfoDiagnostic Title + class Class1 { } + #pragma warning restore InfoDiagnostic // InfoDiagnostic Title + class Class2 { - int x = 0; - } -}"); + int Method() + { + int x = 0; } + } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] - public async Task TestRemovePragmaSuppression_WithEnclosingSuppression() - { - await TestAsync( - @" -#pragma warning disable InfoDiagnostic -using System; + public Task TestRemovePragmaSuppression_TriviaWithMultipleIDs() + => TestAsync( + """ -#pragma warning disable InfoDiagnostic -[|class Class|] -#pragma warning restore InfoDiagnostic -{ - int Method() - { - int x = 0; - } -}", - @" -#pragma warning disable InfoDiagnostic -using System; + using System; -#pragma warning restore InfoDiagnostic -class Class -#pragma warning disable InfoDiagnostic -{ - int Method() + #pragma warning disable InfoDiagnostic, SomeOtherDiagnostic + [|class Class|] + #pragma warning restore InfoDiagnostic, SomeOtherDiagnostic { - int x = 0; - } -}"); - } - - [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] - public async Task TestRemoveLocalAttributeSuppression() + int Method() { - await TestAsync( - $@" -using System; + int x = 0; + } + } + """, + """ -[System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] -[|class Class|] -{{ - int Method() - {{ - int x = 0; - }} -}}", - @" -using System; + using System; -class Class -{ - int Method() + #pragma warning disable InfoDiagnostic, SomeOtherDiagnostic + #pragma warning restore InfoDiagnostic // InfoDiagnostic Title + class Class + #pragma warning disable InfoDiagnostic // InfoDiagnostic Title + #pragma warning restore InfoDiagnostic, SomeOtherDiagnostic { - int x = 0; - } -}"); + int Method() + { + int x = 0; } + } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] - public async Task TestRemoveLocalAttributeSuppression2() - { - await TestAsync( - $@" -using System; + public Task TestRemovePragmaSuppression_WithEnclosingSuppression() + => TestAsync( + """ -class Class1 -{{ - [System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] - [|class Class2|] - {{ + #pragma warning disable InfoDiagnostic + using System; + + #pragma warning disable InfoDiagnostic + [|class Class|] + #pragma warning restore InfoDiagnostic + { int Method() - {{ + { int x = 0; - }} - }} -}}", - @" -using System; + } + } + """, + """ -class Class1 -{ - class Class2 + #pragma warning disable InfoDiagnostic + using System; + + #pragma warning restore InfoDiagnostic + class Class + #pragma warning disable InfoDiagnostic { int Method() { int x = 0; } } -}"); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] - public async Task TestRemoveGlobalAttributeSuppression() - { - await TestAsync( - $@" -using System; - -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class"")] + public Task TestRemoveLocalAttributeSuppression() + => TestAsync( + $$""" -[|class Class|] -{{ - int Method() - {{ - int x = 0; - }} -}}", - @" -using System; + using System; -class Class -{ - int Method() + [System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{{FeaturesResources.Pending}}")] + [|class Class|] { - int x = 0; - } -}"); + int Method() + { + int x = 0; } + } + """, + """ - #region "Fix all occurrences tests" - - #region "Pragma disable tests" - - [Fact] - [Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] - [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInDocument_RemovePragmaSuppressions() - { - var input = @" - - - -using System; + using System; -#pragma warning disable InfoDiagnostic // InfoDiagnostic Title -{|FixAllInDocument:class Class1|} -#pragma warning restore InfoDiagnostic // InfoDiagnostic Title -{ - int Method() + class Class { - int x = 0; + int Method() + { + int x = 0; + } } -} + """); -#pragma warning disable InfoDiagnostic // InfoDiagnostic Title -class Class2 -#pragma warning restore InfoDiagnostic // InfoDiagnostic Title -{ -} - - -class Class3 -{ -} - - - - -class Class1 -{ - int Method() - { - int x = 0; - } -} + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] + public Task TestRemoveLocalAttributeSuppression2() + => TestAsync( + $$""" -class Class2 -{ -} - - -"; - - var expected = @" - - - -using System; + using System; -class Class1 -{ - int Method() + class Class1 { - int x = 0; + [System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{{FeaturesResources.Pending}}")] + [|class Class2|] + { + int Method() + { + int x = 0; + } + } } -} + """, + """ -class Class2 -{ -} - - -class Class3 -{ -} - - - - -class Class1 -{ - int Method() + using System; + + class Class1 { - int x = 0; + class Class2 + { + int Method() + { + int x = 0; + } + } } -} + """); -class Class2 -{ -} - - -"; + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] + public Task TestRemoveGlobalAttributeSuppression() + => TestAsync( + $$""" - await TestInRegularAndScriptAsync(input, expected); - } + using System; - [Fact] - [Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] - [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInProject_RemovePragmaSuppressions() - { - var input = @" - - - -using System; - -#pragma warning disable InfoDiagnostic // InfoDiagnostic Title -{|FixAllInProject:class Class1|} -#pragma warning restore InfoDiagnostic // InfoDiagnostic Title -{ - int Method() - { - int x = 0; - } -} + [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{{FeaturesResources.Pending}}", Scope = "type", Target = "~T:Class")] -#pragma warning disable InfoDiagnostic // InfoDiagnostic Title -class Class2 -#pragma warning restore InfoDiagnostic // InfoDiagnostic Title -{ -} - - -#pragma warning disable InfoDiagnostic // InfoDiagnostic Title -class Class3 -#pragma warning restore InfoDiagnostic // InfoDiagnostic Title -{ -} - - - - -class Class1 -{ - int Method() + [|class Class|] { - int x = 0; + int Method() + { + int x = 0; + } } -} + """, + """ -class Class2 -{ -} - - -"; - - var expected = @" - - - -using System; + using System; -class Class1 -{ - int Method() + class Class { - int x = 0; - } -} - -class Class2 -{ -} - - -class Class3 -{ -} - - - - -class Class1 -{ - int Method() - { - int x = 0; + int Method() + { + int x = 0; + } } -} + """); -class Class2 -{ -} - - -"; + #region "Fix all occurrences tests" - await TestInRegularAndScriptAsync(input, expected); - } + #region "Pragma disable tests" [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInSolution() - { - var input = @" - - - -using System; - -#pragma warning disable InfoDiagnostic // InfoDiagnostic Title -{|FixAllInSolution:class Class1|} -#pragma warning restore InfoDiagnostic // InfoDiagnostic Title -{ - int Method() - { - int x = 0; - } -} + public Task TestFixAllInDocument_RemovePragmaSuppressions() + => TestInRegularAndScriptAsync(""" + + + + + using System; + + #pragma warning disable InfoDiagnostic // InfoDiagnostic Title + {|FixAllInDocument:class Class1|} + #pragma warning restore InfoDiagnostic // InfoDiagnostic Title + { + int Method() + { + int x = 0; + } + } + + #pragma warning disable InfoDiagnostic // InfoDiagnostic Title + class Class2 + #pragma warning restore InfoDiagnostic // InfoDiagnostic Title + { + } + + + class Class3 + { + } + + + + + class Class1 + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + + """, """ + + + + + using System; + + class Class1 + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + class Class3 + { + } + + + + + class Class1 + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + + """); -#pragma warning disable InfoDiagnostic // InfoDiagnostic Title -class Class2 -#pragma warning restore InfoDiagnostic // InfoDiagnostic Title -{ -} - - -#pragma warning disable InfoDiagnostic // InfoDiagnostic Title -class Class3 -#pragma warning restore InfoDiagnostic // InfoDiagnostic Title -{ -} - - - - -#pragma warning disable InfoDiagnostic // InfoDiagnostic Title -class Class1 -#pragma warning restore InfoDiagnostic // InfoDiagnostic Title -{ - int Method() - { - int x = 0; - } -} - -#pragma warning disable InfoDiagnostic // InfoDiagnostic Title -class Class2 -#pragma warning restore InfoDiagnostic // InfoDiagnostic Title -{ -} - - -"; - - var expected = @" - - - -using System; - -class Class1 -{ - int Method() - { - int x = 0; - } -} - -class Class2 -{ -} - - -class Class3 -{ -} - - - - -class Class1 -{ - int Method() - { - int x = 0; - } -} - -class Class2 -{ -} - - -"; + [Fact] + [Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] + [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] + public Task TestFixAllInProject_RemovePragmaSuppressions() + => TestInRegularAndScriptAsync(""" + + + + + using System; + + #pragma warning disable InfoDiagnostic // InfoDiagnostic Title + {|FixAllInProject:class Class1|} + #pragma warning restore InfoDiagnostic // InfoDiagnostic Title + { + int Method() + { + int x = 0; + } + } + + #pragma warning disable InfoDiagnostic // InfoDiagnostic Title + class Class2 + #pragma warning restore InfoDiagnostic // InfoDiagnostic Title + { + } + + + #pragma warning disable InfoDiagnostic // InfoDiagnostic Title + class Class3 + #pragma warning restore InfoDiagnostic // InfoDiagnostic Title + { + } + + + + + class Class1 + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + + """, """ + + + + + using System; + + class Class1 + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + class Class3 + { + } + + + + + class Class1 + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + + """); - await TestInRegularAndScriptAsync(input, expected); - } + [Fact] + [Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] + [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] + public Task TestFixAllInSolution() + => TestInRegularAndScriptAsync(""" + + + + + using System; + + #pragma warning disable InfoDiagnostic // InfoDiagnostic Title + {|FixAllInSolution:class Class1|} + #pragma warning restore InfoDiagnostic // InfoDiagnostic Title + { + int Method() + { + int x = 0; + } + } + + #pragma warning disable InfoDiagnostic // InfoDiagnostic Title + class Class2 + #pragma warning restore InfoDiagnostic // InfoDiagnostic Title + { + } + + + #pragma warning disable InfoDiagnostic // InfoDiagnostic Title + class Class3 + #pragma warning restore InfoDiagnostic // InfoDiagnostic Title + { + } + + + + + #pragma warning disable InfoDiagnostic // InfoDiagnostic Title + class Class1 + #pragma warning restore InfoDiagnostic // InfoDiagnostic Title + { + int Method() + { + int x = 0; + } + } + + #pragma warning disable InfoDiagnostic // InfoDiagnostic Title + class Class2 + #pragma warning restore InfoDiagnostic // InfoDiagnostic Title + { + } + + + + """, """ + + + + + using System; + + class Class1 + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + class Class3 + { + } + + + + + class Class1 + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + + """); #endregion @@ -576,118 +584,134 @@ class Class2 [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocument_RemoveAttributeSuppressions() { - var addedGlobalSuppressions = $@" -// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. - -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~M:Class1.Method~System.Int32"")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class1"")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class3"")] - -".Replace("<", "<").Replace(">", ">"); - - var input = @" - - - -using System; - -{|FixAllInDocument:class Class1|} -{ - int Method() - { - int x = 0; - } -} - -class Class2 -{ -} - - -class Class3 -{ -} - - " + addedGlobalSuppressions + -@" - - - -class Class1 -{ - int Method() - { - int x = 0; - } -} - -class Class2 -{ -} - - " + addedGlobalSuppressions + -@" - -"; - - var newGlobalSuppressionsFile = $@" -// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. - -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~M:Class1.Method~System.Int32"")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class3"")] - -".Replace("<", "<").Replace(">", ">"); - var expected = @" - - - -using System; - -class Class1 -{ - int Method() - { - int x = 0; - } -} - -class Class2 -{ -} - - -class Class3 -{ -} - - " + newGlobalSuppressionsFile + -@" - - - -class Class1 -{ - int Method() - { - int x = 0; - } -} - -class Class2 -{ -} - - " + addedGlobalSuppressions + -@" - -"; + var addedGlobalSuppressions = $""" + + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. + + [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "member", Target = "~M:Class1.Method~System.Int32")] + [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class1")] + [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class2")] + [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class3")] + + + """.Replace("<", "<").Replace(">", ">"); + + var input = """ + + + + + using System; + + {|FixAllInDocument:class Class1|} + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + class Class3 + { + } + + + """ + addedGlobalSuppressions + + """ + + + + + class Class1 + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + """ + addedGlobalSuppressions + + """ + + + + """; + + var newGlobalSuppressionsFile = $""" + + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. + + [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "member", Target = "~M:Class1.Method~System.Int32")] + [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class3")] + + + """.Replace("<", "<").Replace(">", ">"); + var expected = """ + + + + + using System; + + class Class1 + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + class Class3 + { + } + + + """ + newGlobalSuppressionsFile + + """ + + + + + class Class1 + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + """ + addedGlobalSuppressions + + """ + + + + """; await TestInRegularAndScriptAsync(input, expected); } @@ -697,115 +721,131 @@ class Class2 [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInProject_RemoveAttributeSuppressions() { - var addedGlobalSuppressions = $@" -// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. - -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class1"")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class3"")] - -".Replace("<", "<").Replace(">", ">"); - - var input = @" - - - -using System; - -{|FixAllInProject:class Class1|} -{ - int Method() - { - int x = 0; - } -} - -class Class2 -{ -} - - -class Class3 -{ -} - - " + addedGlobalSuppressions + -@" - - - -class Class1 -{ - int Method() - { - int x = 0; - } -} - -class Class2 -{ -} - - " + addedGlobalSuppressions + -@" - -"; - - var newGlobalSuppressionsFile = $@" -// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. - - -"; - var expected = @" - - - -using System; - -class Class1 -{ - int Method() - { - int x = 0; - } -} - -class Class2 -{ -} - - -class Class3 -{ -} - - " + newGlobalSuppressionsFile + -@" - - - -class Class1 -{ - int Method() - { - int x = 0; - } -} - -class Class2 -{ -} - - " + addedGlobalSuppressions + -@" - -"; + var addedGlobalSuppressions = $""" + + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. + + [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class1")] + [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class2")] + [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class3")] + + + """.Replace("<", "<").Replace(">", ">"); + + var input = """ + + + + + using System; + + {|FixAllInProject:class Class1|} + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + class Class3 + { + } + + + """ + addedGlobalSuppressions + + """ + + + + + class Class1 + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + """ + addedGlobalSuppressions + + """ + + + + """; + + var newGlobalSuppressionsFile = $""" + + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. + + + + """; + var expected = """ + + + + + using System; + + class Class1 + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + class Class3 + { + } + + + """ + newGlobalSuppressionsFile + + """ + + + + + class Class1 + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + """ + addedGlobalSuppressions + + """ + + + + """; await TestInRegularAndScriptAsync(input, expected); } @@ -815,126 +855,144 @@ class Class2 [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution_RemoveAttributeSuppression() { - var addedGlobalSuppressionsProject1 = $@" -// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. - -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class1"")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class3"")] - -".Replace("<", "<").Replace(">", ">"); - - var addedGlobalSuppressionsProject2 = $@" -// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. - -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class1"")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] - -".Replace("<", "<").Replace(">", ">"); - - var input = @" - - - -using System; - -{|FixAllInSolution:class Class1|} -{ - int Method() - { - int x = 0; - } -} - -class Class2 -{ -} - - -class Class3 -{ -} - - " + addedGlobalSuppressionsProject1 + -@" - - - -class Class1 -{ - int Method() - { - int x = 0; - } -} - -class Class2 -{ -} - - " + addedGlobalSuppressionsProject2 + -@" - -"; - - var newGlobalSuppressionsFile = $@" -// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. - - -"; - var expected = @" - - - -using System; - -class Class1 -{ - int Method() - { - int x = 0; - } -} - -class Class2 -{ -} - - -class Class3 -{ -} - - " + newGlobalSuppressionsFile + -@" - - - -class Class1 -{ - int Method() - { - int x = 0; - } -} - -class Class2 -{ -} - - " + newGlobalSuppressionsFile + -@" - -"; + var addedGlobalSuppressionsProject1 = $""" + + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. + + [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class1")] + [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class2")] + [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class3")] + + + """.Replace("<", "<").Replace(">", ">"); + + var addedGlobalSuppressionsProject2 = $""" + + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. + + [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class1")] + [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class2")] + + + """.Replace("<", "<").Replace(">", ">"); + + var input = """ + + + + + using System; + + {|FixAllInSolution:class Class1|} + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + class Class3 + { + } + + + """ + addedGlobalSuppressionsProject1 + + """ + + + + + class Class1 + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + """ + addedGlobalSuppressionsProject2 + + """ + + + + """; + + var newGlobalSuppressionsFile = $""" + + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. + + + + """; + var expected = """ + + + + + using System; + + class Class1 + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + class Class3 + { + } + + + """ + newGlobalSuppressionsFile + + """ + + + + + class Class1 + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + """ + newGlobalSuppressionsFile + + """ + + + + """; await TestInRegularAndScriptAsync(input, expected); } @@ -953,113 +1011,129 @@ internal override Tuple CreateDia [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInProject_RemoveAttributeSuppressions() { - var addedGlobalSuppressions = $@" -// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. - -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] - -".Replace("<", "<").Replace(">", ">"); - - var input = @" - - - {|FixAllInProject:|} -using System; - -class Class1 -{ - int Method() - { - int x = 0; - } -} - -class Class2 -{ -} - - -class Class3 -{ -} - - " + addedGlobalSuppressions + -@" - - - -class Class1 -{ - int Method() - { - int x = 0; - } -} - -class Class2 -{ -} - - " + addedGlobalSuppressions + -@" - -"; - - var newGlobalSuppressionsFile = $@" -// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. - - -"; - var expected = @" - - - -using System; - -class Class1 -{ - int Method() - { - int x = 0; - } -} - -class Class2 -{ -} - - -class Class3 -{ -} - - " + newGlobalSuppressionsFile + -@" - - - -class Class1 -{ - int Method() - { - int x = 0; - } -} - -class Class2 -{ -} - - " + addedGlobalSuppressions + -@" - -"; + var addedGlobalSuppressions = $""" + + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. + + [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}")] + + + """.Replace("<", "<").Replace(">", ">"); + + var input = """ + + + + {|FixAllInProject:|} + using System; + + class Class1 + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + class Class3 + { + } + + + """ + addedGlobalSuppressions + + """ + + + + + class Class1 + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + """ + addedGlobalSuppressions + + """ + + + + """; + + var newGlobalSuppressionsFile = $""" + + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. + + + + """; + var expected = """ + + + + + using System; + + class Class1 + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + class Class3 + { + } + + + """ + newGlobalSuppressionsFile + + """ + + + + + class Class1 + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + """ + addedGlobalSuppressions + + """ + + + + """; await TestInRegularAndScriptAsync(input, expected); } diff --git a/src/Features/CSharpTest/Diagnostics/Suppression/RemoveUnnecessaryPragmaSuppressionsTests.cs b/src/Features/CSharpTest/Diagnostics/Suppression/RemoveUnnecessaryPragmaSuppressionsTests.cs index 3271d0b4b302e..0fcb161152254 100644 --- a/src/Features/CSharpTest/Diagnostics/Suppression/RemoveUnnecessaryPragmaSuppressionsTests.cs +++ b/src/Features/CSharpTest/Diagnostics/Suppression/RemoveUnnecessaryPragmaSuppressionsTests.cs @@ -31,13 +31,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnnecessarySuppre [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessarySuppressions)] [WorkItem("https://github.com/dotnet/roslyn/issues/44177")] -public abstract class RemoveUnnecessaryInlineSuppressionsTests : AbstractUnncessarySuppressionDiagnosticTest +public abstract class RemoveUnnecessaryInlineSuppressionsTests(ITestOutputHelper logger) : AbstractUnnecessarySuppressionDiagnosticTest(logger) { - protected RemoveUnnecessaryInlineSuppressionsTests(ITestOutputHelper logger) - : base(logger) - { - } - #region Helpers internal sealed override CodeFixProvider CodeFixProvider @@ -122,25 +117,15 @@ public override void Initialize(AnalysisContext context) #region Single analyzer tests (Compiler OR Analyzer) - public abstract class CompilerOrAnalyzerTests : RemoveUnnecessaryInlineSuppressionsTests + public abstract class CompilerOrAnalyzerTests(ITestOutputHelper logger) : RemoveUnnecessaryInlineSuppressionsTests(logger) { - protected CompilerOrAnalyzerTests(ITestOutputHelper logger) - : base(logger) - { - } - protected abstract bool IsCompilerDiagnosticsTest { get; } protected abstract string VariableDeclaredButNotUsedDiagnosticId { get; } protected abstract string VariableAssignedButNotUsedDiagnosticId { get; } protected abstract ImmutableArray UnsupportedDiagnosticIds { get; } - public sealed class CompilerTests : CompilerOrAnalyzerTests + public sealed class CompilerTests(ITestOutputHelper logger) : CompilerOrAnalyzerTests(logger) { - public CompilerTests(ITestOutputHelper logger) - : base(logger) - { - } - internal override ImmutableArray OtherAnalyzers => [new CSharpCompilerDiagnosticAnalyzer()]; @@ -173,13 +158,8 @@ protected override ImmutableArray UnsupportedDiagnosticIds } } - public sealed class AnalyzerTests : CompilerOrAnalyzerTests + public sealed class AnalyzerTests(ITestOutputHelper logger) : CompilerOrAnalyzerTests(logger) { - public AnalyzerTests(ITestOutputHelper logger) - : base(logger) - { - } - internal override ImmutableArray OtherAnalyzers => [new UserDiagnosticAnalyzer(), new CompilationEndDiagnosticAnalyzer()]; protected override bool IsCompilerDiagnosticsTest => false; @@ -195,48 +175,50 @@ protected override ImmutableArray UnsupportedDiagnosticIds } [Fact] - public async Task TestDoNotRemoveRequiredDiagnosticSuppression_Pragma() + public Task TestDoNotRemoveRequiredDiagnosticSuppression_Pragma() + => TestMissingInRegularAndScriptAsync( + $$""" + + class Class + { + void M() { - await TestMissingInRegularAndScriptAsync( - $@" -class Class -{{ - void M() - {{ -[|#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Necessary - int y; -#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Necessary|] - }} -}}"); + [|#pragma warning disable {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Necessary + int y; + #pragma warning restore {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Necessary|] } + } + """); [Fact] - public async Task TestDoNotRemoveRequiredDiagnosticSuppression_Pragma_02() + public Task TestDoNotRemoveRequiredDiagnosticSuppression_Pragma_02() + => TestMissingInRegularAndScriptAsync( + $$""" + + [|#pragma warning disable {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Necessary|] + class Class + { + void M() { - await TestMissingInRegularAndScriptAsync( - $@" -[|#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Necessary|] -class Class -{{ - void M() - {{ - int y; - }} -}}"); + int y; } + } + """); [Fact] public async Task TestDoNotRemoveRequiredDiagnosticSuppression_Attribute_Method() { - var code = $@" -class Class -{{ - [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")]|] - void M() - {{ - int y; - }} -}}"; + var code = $$""" + + class Class + { + [|[System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{VariableDeclaredButNotUsedDiagnosticId}}")]|] + void M() + { + int y; + } + } + """; // Compiler diagnostics cannot be suppressed with SuppressMessageAttribute. // Hence, attribute suppressions for compiler diagnostics are always unnecessary. if (!IsCompilerDiagnosticsTest) @@ -245,29 +227,33 @@ void M() } else { - await TestInRegularAndScript1Async(code, @" -class Class -{ - void M() - { - int y; - } -}"); + await TestInRegularAndScript1Async(code, """ + + class Class + { + void M() + { + int y; + } + } + """); } } [Fact] public async Task TestDoNotRemoveRequiredDiagnosticSuppression_Attribute_02() { - var code = $@" -[|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")]|] -class Class -{{ - void M() - {{ - int y; - }} -}}"; + var code = $$""" + + [|[System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{VariableDeclaredButNotUsedDiagnosticId}}")]|] + class Class + { + void M() + { + int y; + } + } + """; // Compiler diagnostics cannot be suppressed with SuppressMessageAttribute. // Hence, attribute suppressions for compiler diagnostics are always unnecessary. if (!IsCompilerDiagnosticsTest) @@ -276,14 +262,16 @@ void M() } else { - await TestInRegularAndScript1Async(code, @" -class Class -{ - void M() - { - int y; - } -}"); + await TestInRegularAndScript1Async(code, """ + + class Class + { + void M() + { + int y; + } + } + """); } } @@ -320,94 +308,93 @@ public async Task TestDoNotRemoveUnsupportedDiagnosticSuppression(bool disable, } else { - var fixedSource = $@"{pragmas}class Class {{ }}"; - await TestInRegularAndScriptAsync(source, fixedSource); + await TestInRegularAndScriptAsync(source, $@"{pragmas}class Class {{ }}"); } } [Fact] - public async Task TestDoNotRemoveInactiveDiagnosticSuppression() + public Task TestDoNotRemoveInactiveDiagnosticSuppression() + => TestMissingInRegularAndScriptAsync( + $$""" + + #if false + [| + class Class + { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{VariableDeclaredButNotUsedDiagnosticId}}")] + void M() { - await TestMissingInRegularAndScriptAsync( - $@" -#if false -[| -class Class -{{ - [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] - void M() - {{ -#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Inactive - int y; -#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Inactive - y = 1; - }} -}} -|] -#endif"); + #pragma warning disable {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Inactive + int y; + #pragma warning restore {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Inactive + y = 1; } + } + |] + #endif + """); [Fact] - public async Task TestDoNotRemoveDiagnosticSuppressionsInCodeWithSyntaxErrors() + public Task TestDoNotRemoveDiagnosticSuppressionsInCodeWithSyntaxErrors() + => TestMissingInRegularAndScriptAsync( + $$""" + + [| + class Class + { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{VariableDeclaredButNotUsedDiagnosticId}}")] + void M() { - await TestMissingInRegularAndScriptAsync( - $@" -[| -class Class -{{ - [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] - void M() - {{ -#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - int y // CS1002: ; expected -#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - y = 1; - }} -}} -|]"); + #pragma warning disable {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used + int y // CS1002: ; expected + #pragma warning restore {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used + y = 1; } + } + |] + """); [Fact] - public async Task TestDoNotRemoveDiagnosticSuppressionWhenAnalyzerSuppressed() + public Task TestDoNotRemoveDiagnosticSuppressionWhenAnalyzerSuppressed() + => TestMissingInRegularAndScriptAsync( + $$""" + + #pragma warning disable {{IDEDiagnosticIds.RemoveUnnecessarySuppressionDiagnosticId}} + [| + class Class + { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{VariableDeclaredButNotUsedDiagnosticId}}")] + void M() { - await TestMissingInRegularAndScriptAsync( - $@" -#pragma warning disable {IDEDiagnosticIds.RemoveUnnecessarySuppressionDiagnosticId} -[| -class Class -{{ - [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] - void M() - {{ -#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary, but suppressed - int y; -#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary, but suppressed - y = 1; - }} -}} -|]"); + #pragma warning disable {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Unnecessary, but suppressed + int y; + #pragma warning restore {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Unnecessary, but suppressed + y = 1; } + } + |] + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46075")] - public async Task TestDoNotRemoveDiagnosticSuppressionInGeneratedCode() + public Task TestDoNotRemoveDiagnosticSuppressionInGeneratedCode() + => TestMissingInRegularAndScriptAsync( + $$""" + + // + [| + class Class + { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{VariableDeclaredButNotUsedDiagnosticId}}")] // Variable is declared but never used - Unnecessary, but not reported in generated code + void M() { - await TestMissingInRegularAndScriptAsync( - $@" -// -[| -class Class -{{ - [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] // Variable is declared but never used - Unnecessary, but not reported in generated code - void M() - {{ -#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary, but not reported in generated code - int y; -#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary, but not reported in generated code - y = 1; - }} -}} -|]"); + #pragma warning disable {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Unnecessary, but not reported in generated code + int y; + #pragma warning restore {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Unnecessary, but not reported in generated code + y = 1; } + } + |] + """); [Theory, CombinatorialData] public async Task TestDoNotRemoveExcludedDiagnosticSuppression(bool excludeAll) @@ -418,20 +405,22 @@ public async Task TestDoNotRemoveExcludedDiagnosticSuppression(bool excludeAll) }; await TestMissingInRegularAndScriptAsync( - $@" -[| -class Class -{{ - [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] - void M() - {{ -#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary, but suppressed - int y; -#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary, but suppressed - y = 1; - }} -}} -|]", new TestParameters(options: options)); + $$""" + + [| + class Class + { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{VariableDeclaredButNotUsedDiagnosticId}}")] + void M() + { + #pragma warning disable {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Unnecessary, but suppressed + int y; + #pragma warning restore {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Unnecessary, but suppressed + y = 1; + } + } + |] + """, new TestParameters(options: options)); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47288")] @@ -443,31 +432,32 @@ public async Task TestDoNotRemoveExcludedDiagnosticCategorySuppression() }; await TestMissingInRegularAndScriptAsync( - $@" -[| -class Class -{{ - [System.Diagnostics.CodeAnalysis.SuppressMessage(""ExcludedCategory"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] - [System.Diagnostics.CodeAnalysis.SuppressMessage(""ExcludedCategory"", ""{VariableAssignedButNotUsedDiagnosticId}"")] - void M() - {{ - int y; - y = 1; - - int z = 1; - z++; - }} -}} -|]", new TestParameters(options: options)); + $$""" + + [| + class Class + { + [System.Diagnostics.CodeAnalysis.SuppressMessage("ExcludedCategory", "{{VariableDeclaredButNotUsedDiagnosticId}}")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("ExcludedCategory", "{{VariableAssignedButNotUsedDiagnosticId}}")] + void M() + { + int y; + y = 1; + + int z = 1; + z++; + } + } + |] + """, new TestParameters(options: options)); } [Theory] [InlineData("event", "EventHandler")] [InlineData("static", "int")] [WorkItem("https://github.com/dotnet/roslyn/issues/78786")] - public async Task TestRemoveDiagnosticSuppression_Attribute_MultiVariableDeclaration(string keyword, string type) - { - await TestInRegularAndScript1Async( + public Task TestRemoveDiagnosticSuppression_Attribute_MultiVariableDeclaration(string keyword, string type) + => TestInRegularAndScript1Async( $$""" public class C { @@ -481,13 +471,11 @@ public class C public {{keyword}} {{type}} A, B; } """); - } [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/78786")] - public async Task TestRemoveDiagnosticSuppression_Attribute_PartialMethodDefinition() - { - await TestInRegularAndScript1Async( + public Task TestRemoveDiagnosticSuppression_Attribute_PartialMethodDefinition() + => TestInRegularAndScript1Async( """ public partial class C { @@ -515,13 +503,11 @@ partial void M() } } """); - } [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/78786")] - public async Task TestRemoveDiagnosticSuppression_Attribute_PartialMethodImplementation() - { - await TestInRegularAndScript1Async( + public Task TestRemoveDiagnosticSuppression_Attribute_PartialMethodImplementation() + => TestInRegularAndScript1Async( """ public partial class C { @@ -549,13 +535,11 @@ partial void M() } } """); - } [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/78786")] - public async Task TestRemoveDiagnosticSuppression_Attribute_PartialPropertyDefinition() - { - await TestInRegularAndScript1Async( + public Task TestRemoveDiagnosticSuppression_Attribute_PartialPropertyDefinition() + => TestInRegularAndScript1Async( """ public partial class C { @@ -579,13 +563,11 @@ public partial class C partial int P => 5230; } """); - } [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/78786")] - public async Task TestRemoveDiagnosticSuppression_Attribute_PartialPropertyImplementation() - { - await TestInRegularAndScript1Async( + public Task TestRemoveDiagnosticSuppression_Attribute_PartialPropertyImplementation() + => TestInRegularAndScript1Async( """ public partial class C { @@ -609,30 +591,29 @@ public partial class C partial int P => 5230; } """); - } [Fact] - public async Task TestDoNotRemoveDiagnosticSuppression_Attribute_OnPartialDeclarations() + public Task TestDoNotRemoveDiagnosticSuppression_Attribute_OnPartialDeclarations() + => TestMissingInRegularAndScriptAsync( + $$""" + + [| + // Unnecessary, but we do not perform analysis for SuppressMessageAttributes on partial declarations. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{VariableDeclaredButNotUsedDiagnosticId}}")] + partial class Class + { + } + + partial class Class + { + void M() { - await TestMissingInRegularAndScriptAsync( - $@" -[| -// Unnecessary, but we do not perform analysis for SuppressMessageAttributes on partial declarations. -[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] -partial class Class -{{ -}} - -partial class Class -{{ - void M() - {{ - int y; - y = 1; - }} -}} -|]"); + int y; + y = 1; } + } + |] + """); [Theory, CombinatorialData] public async Task TestRemoveDiagnosticSuppression_Pragma(bool testFixFromDisable) @@ -642,139 +623,151 @@ public async Task TestRemoveDiagnosticSuppression_Pragma(bool testFixFromDisable : ("", "", "[|", "|]"); await TestInRegularAndScript1Async( - $@" -class Class -{{ - void M() - {{ -{disablePrefix}#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{disableSuffix} - int y; -{restorePrefix}#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{restoreSuffix} - y = 1; - }} -}}", - @" -class Class -{ - void M() + $$""" + + class Class + { + void M() + { + {{disablePrefix}}#pragma warning disable {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Unnecessary{{disableSuffix}} + int y; + {{restorePrefix}}#pragma warning restore {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Unnecessary{{restoreSuffix}} + y = 1; + } + } + """, + """ + + class Class { - int y; - y = 1; + void M() + { + int y; + y = 1; + } } -}"); + """); } [Fact] - public async Task TestRemoveDiagnosticSuppression_Attribute() - { - await TestInRegularAndScript1Async( - $@" -class Class -{{ - [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")]|] // Variable is declared but never used - Unnecessary - void M() - {{ - int y; - y = 1; - }} -}}", - @" -class Class -{ - void M() + public Task TestRemoveDiagnosticSuppression_Attribute() + => TestInRegularAndScript1Async( + $$""" + + class Class { - int y; - y = 1; + [|[System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{VariableDeclaredButNotUsedDiagnosticId}}")]|] // Variable is declared but never used - Unnecessary + void M() + { + int y; + y = 1; + } } -}"); + """, + """ + + class Class + { + void M() + { + int y; + y = 1; } + } + """); [Fact] - public async Task TestRemoveDiagnosticSuppression_Attribute_Trivia() - { - await TestInRegularAndScript1Async( - $@" -class Class -{{ - // Comment1 - /// - /// DocComment - /// - // Comment2 - [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")]|] // Comment3 - // Comment4 - void M() - {{ - int y; - y = 1; - }} -}}", - @" -class Class -{ - // Comment1 - /// - /// DocComment - /// - // Comment2 - // Comment4 - void M() + public Task TestRemoveDiagnosticSuppression_Attribute_Trivia() + => TestInRegularAndScript1Async( + $$""" + + class Class { - int y; - y = 1; + // Comment1 + /// + /// DocComment + /// + // Comment2 + [|[System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{VariableDeclaredButNotUsedDiagnosticId}}")]|] // Comment3 + // Comment4 + void M() + { + int y; + y = 1; + } } -}"); + """, + """ + + class Class + { + // Comment1 + /// + /// DocComment + /// + // Comment2 + // Comment4 + void M() + { + int y; + y = 1; } + } + """); [Fact] - public async Task TestRemoveDiagnosticSuppression_OnlyDisableDirective() - { - await TestInRegularAndScript1Async( - $@" -class Class -{{ - void M() - {{ -[|#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary|] - int y; - y = 1; - }} -}}", - @" -class Class -{ - void M() + public Task TestRemoveDiagnosticSuppression_OnlyDisableDirective() + => TestInRegularAndScript1Async( + $$""" + + class Class { - int y; - y = 1; + void M() + { + [|#pragma warning disable {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Unnecessary|] + int y; + y = 1; + } } -}"); + """, + """ + + class Class + { + void M() + { + int y; + y = 1; } + } + """); [Fact] - public async Task TestRemoveDiagnosticSuppression_OnlyRestoreDirective() - { - await TestInRegularAndScript1Async( - $@" -class Class -{{ - void M() - {{ - int y; -[|#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary|] - y = 1; - }} -}}", - @" -class Class -{ - void M() + public Task TestRemoveDiagnosticSuppression_OnlyRestoreDirective() + => TestInRegularAndScript1Async( + $$""" + + class Class { - int y; - y = 1; + void M() + { + int y; + [|#pragma warning restore {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Unnecessary|] + y = 1; + } } -}"); + """, + """ + + class Class + { + void M() + { + int y; + y = 1; } + } + """); [Theory, CombinatorialData] public async Task TestRemoveDiagnosticSuppression_DuplicatePragmaSuppression(bool testFixFromDisable) @@ -784,28 +777,32 @@ public async Task TestRemoveDiagnosticSuppression_DuplicatePragmaSuppression(boo : ("", "", "[|", "|]"); await TestInRegularAndScript1Async( - $@" -class Class -{{ -{disablePrefix}#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{disableSuffix} - void M() - {{ -#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Necessary - int y; -#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Necessary - }} -{restorePrefix}#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{restoreSuffix} -}}", - $@" -class Class -{{ - void M() - {{ -#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Necessary - int y; -#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Necessary - }} -}}"); + $$""" + + class Class + { + {{disablePrefix}}#pragma warning disable {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Unnecessary{{disableSuffix}} + void M() + { + #pragma warning disable {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Necessary + int y; + #pragma warning restore {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Necessary + } + {{restorePrefix}}#pragma warning restore {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Unnecessary{{restoreSuffix}} + } + """, + $$""" + + class Class + { + void M() + { + #pragma warning disable {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Necessary + int y; + #pragma warning restore {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Necessary + } + } + """); } [Fact] @@ -815,28 +812,34 @@ public async Task TestRemoveDiagnosticSuppression_DuplicateAttributeSuppression( // Hence, attribute suppressions for compiler diagnostics are always unnecessary. var retainedAttributesInFixCode = IsCompilerDiagnosticsTest ? string.Empty - : $@"[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] // Variable is declared but never used - Necessary - "; + : $""" + [System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{VariableDeclaredButNotUsedDiagnosticId}")] // Variable is declared but never used - Necessary + + """; await TestInRegularAndScript1Async( - $@" -class Class -{{ - [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] // Variable is declared but never used - Necessary - {{|FixAllInDocument:[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] // Variable is declared but never used - Unnecessary|}} - void M() - {{ - int y; - }} -}}", - $@" -class Class -{{ - {retainedAttributesInFixCode}void M() - {{ - int y; - }} -}}"); + $$""" + + class Class + { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{VariableDeclaredButNotUsedDiagnosticId}}")] // Variable is declared but never used - Necessary + {|FixAllInDocument:[System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{VariableDeclaredButNotUsedDiagnosticId}}")] // Variable is declared but never used - Unnecessary|} + void M() + { + int y; + } + } + """, + $$""" + + class Class + { + {{retainedAttributesInFixCode}}void M() + { + int y; + } + } + """); } [Fact] @@ -846,77 +849,88 @@ public async Task TestRemoveDiagnosticSuppression_DuplicateAttributeSuppression_ // Hence, attribute suppressions for compiler diagnostics are always unnecessary. var retainedAttributesInFixCode = IsCompilerDiagnosticsTest ? string.Empty - : $@"[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] // Variable is declared but never used - Necessary - "; + : $""" + [System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{VariableDeclaredButNotUsedDiagnosticId}")] // Variable is declared but never used - Necessary + + """; await TestInRegularAndScript1Async( - $@" -{{|FixAllInDocument:[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] // Variable is declared but never used - Unnecessary|}} -class Class -{{ - [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] // Variable is declared but never used - Necessary - void M() - {{ - int y; - }} -}}", - $@" -class Class -{{ - {retainedAttributesInFixCode}void M() - {{ - int y; - }} -}}"); + $$""" + + {|FixAllInDocument:[System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{VariableDeclaredButNotUsedDiagnosticId}}")] // Variable is declared but never used - Unnecessary|} + class Class + { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{VariableDeclaredButNotUsedDiagnosticId}}")] // Variable is declared but never used - Necessary + void M() + { + int y; + } + } + """, + $$""" + + class Class + { + {{retainedAttributesInFixCode}}void M() + { + int y; + } + } + """); } [Fact] public async Task TestRemoveDiagnosticSuppression_DuplicatePragmaAndAttributeSuppression() { - var source = $@" -class Class -{{ - [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] - void M() - {{ -#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId}|] - int y; -#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} - }} -}}"; string fixedSource; if (IsCompilerDiagnosticsTest) { // Compiler diagnostics cannot be suppressed with SuppressMessageAttribute. // Hence, attribute suppressions for compiler diagnostics are always unnecessary. - fixedSource = $@" -class Class -{{ - void M() - {{ -#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} - int y; -#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} - }} -}}"; + fixedSource = $$""" + + class Class + { + void M() + { + #pragma warning disable {{VariableDeclaredButNotUsedDiagnosticId}} + int y; + #pragma warning restore {{VariableDeclaredButNotUsedDiagnosticId}} + } + } + """; } else { // Analyzer diagnostics can be suppressed with both SuppressMessageAttribute and pragmas. // SuppressMessageAttribute takes precedence over pragmas for duplicate suppressions, // hence duplicate pragmas are considered unnecessary. - fixedSource = $@" -class Class -{{ - [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] - void M() - {{ - int y; - }} -}}"; + fixedSource = $$""" + + class Class + { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{VariableDeclaredButNotUsedDiagnosticId}}")] + void M() + { + int y; + } + } + """; } - await TestInRegularAndScript1Async(source, fixedSource); + await TestInRegularAndScript1Async($$""" + + class Class + { + [|[System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{VariableDeclaredButNotUsedDiagnosticId}}")] + void M() + { + #pragma warning disable {{VariableDeclaredButNotUsedDiagnosticId}}|] + int y; + #pragma warning restore {{VariableDeclaredButNotUsedDiagnosticId}} + } + } + """, fixedSource); } [Theory, CombinatorialData] @@ -927,54 +941,60 @@ public async Task TestRemoveDiagnosticSuppression_Pragma_InnerValidSuppression(b : ("", "", "[|", "|]"); await TestInRegularAndScript1Async( - $@" -class Class -{{ - void M() - {{ -{disablePrefix}#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{disableSuffix} -#pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary - int y = 0; -#pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary -{restorePrefix}#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{restoreSuffix} - }} -}}", - $@" -class Class -{{ - void M() - {{ -#pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary - int y = 0; -#pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary - }} -}}"); + $$""" + + class Class + { + void M() + { + {{disablePrefix}}#pragma warning disable {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Unnecessary{{disableSuffix}} + #pragma warning disable {{VariableAssignedButNotUsedDiagnosticId}} // Variable is assigned but its value is never used - Necessary + int y = 0; + #pragma warning restore {{VariableAssignedButNotUsedDiagnosticId}} // Variable is assigned but its value is never used - Necessary + {{restorePrefix}}#pragma warning restore {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Unnecessary{{restoreSuffix}} + } + } + """, + $$""" + + class Class + { + void M() + { + #pragma warning disable {{VariableAssignedButNotUsedDiagnosticId}} // Variable is assigned but its value is never used - Necessary + int y = 0; + #pragma warning restore {{VariableAssignedButNotUsedDiagnosticId}} // Variable is assigned but its value is never used - Necessary + } + } + """); } [Fact] - public async Task TestRemoveDiagnosticSuppression_Attribute_InnerValidSuppression() + public Task TestRemoveDiagnosticSuppression_Attribute_InnerValidSuppression() + => TestInRegularAndScript1Async( + $$""" + + class Class + { + [|[System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{VariableDeclaredButNotUsedDiagnosticId}}")]|] // Variable is declared but never used - Unnecessary + [System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{VariableAssignedButNotUsedDiagnosticId}}")] // Variable is assigned but its value is never used - Necessary + void M() { - await TestInRegularAndScript1Async( - $@" -class Class -{{ - [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")]|] // Variable is declared but never used - Unnecessary - [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableAssignedButNotUsedDiagnosticId}"")] // Variable is assigned but its value is never used - Necessary - void M() - {{ - int y = 0; - }} -}}", - $@" -class Class -{{ - [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableAssignedButNotUsedDiagnosticId}"")] // Variable is assigned but its value is never used - Necessary - void M() - {{ - int y = 0; - }} -}}"); + int y = 0; } + } + """, + $$""" + + class Class + { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{VariableAssignedButNotUsedDiagnosticId}}")] // Variable is assigned but its value is never used - Necessary + void M() + { + int y = 0; + } + } + """); [Theory, CombinatorialData] public async Task TestRemoveDiagnosticSuppression_Pragma_OuterValidSuppression(bool testFixFromDisable) @@ -984,54 +1004,60 @@ public async Task TestRemoveDiagnosticSuppression_Pragma_OuterValidSuppression(b : ("", "", "[|", "|]"); await TestInRegularAndScript1Async( - $@" -class Class -{{ - void M() - {{ -#pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary -{disablePrefix}#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{disableSuffix} - int y = 0; -{restorePrefix}#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{restoreSuffix} -#pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary - }} -}}", - $@" -class Class -{{ - void M() - {{ -#pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary - int y = 0; -#pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary - }} -}}"); + $$""" + + class Class + { + void M() + { + #pragma warning disable {{VariableAssignedButNotUsedDiagnosticId}} // Variable is assigned but its value is never used - Necessary + {{disablePrefix}}#pragma warning disable {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Unnecessary{{disableSuffix}} + int y = 0; + {{restorePrefix}}#pragma warning restore {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Unnecessary{{restoreSuffix}} + #pragma warning restore {{VariableAssignedButNotUsedDiagnosticId}} // Variable is assigned but its value is never used - Necessary + } + } + """, + $$""" + + class Class + { + void M() + { + #pragma warning disable {{VariableAssignedButNotUsedDiagnosticId}} // Variable is assigned but its value is never used - Necessary + int y = 0; + #pragma warning restore {{VariableAssignedButNotUsedDiagnosticId}} // Variable is assigned but its value is never used - Necessary + } + } + """); } [Fact] - public async Task TestRemoveDiagnosticSuppression_Attribute_OuterValidSuppression() + public Task TestRemoveDiagnosticSuppression_Attribute_OuterValidSuppression() + => TestInRegularAndScript1Async( + $$""" + + class Class + { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{VariableAssignedButNotUsedDiagnosticId}}")] // Variable is assigned but its value is never used - Necessary + [|[System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{VariableDeclaredButNotUsedDiagnosticId}}")]|] // Variable is declared but never used - Unnecessary + void M() { - await TestInRegularAndScript1Async( - $@" -class Class -{{ - [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableAssignedButNotUsedDiagnosticId}"")] // Variable is assigned but its value is never used - Necessary - [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")]|] // Variable is declared but never used - Unnecessary - void M() - {{ - int y = 0; - }} -}}", - $@" -class Class -{{ - [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableAssignedButNotUsedDiagnosticId}"")] // Variable is assigned but its value is never used - Necessary - void M() - {{ - int y = 0; - }} -}}"); + int y = 0; } + } + """, + $$""" + + class Class + { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{VariableAssignedButNotUsedDiagnosticId}}")] // Variable is assigned but its value is never used - Necessary + void M() + { + int y = 0; + } + } + """); [Theory, CombinatorialData] public async Task TestRemoveDiagnosticSuppression_OverlappingDirectives(bool testFixFromDisable) @@ -1041,83 +1067,91 @@ public async Task TestRemoveDiagnosticSuppression_OverlappingDirectives(bool tes : ("", "", "[|", "|]"); await TestInRegularAndScript1Async( - $@" -class Class -{{ - void M() - {{ -{disablePrefix}#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{disableSuffix} -#pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary - int y = 0; -{restorePrefix}#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{restoreSuffix} -#pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary - }} -}}", - $@" -class Class -{{ - void M() - {{ -#pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary - int y = 0; -#pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary - }} -}}"); + $$""" + + class Class + { + void M() + { + {{disablePrefix}}#pragma warning disable {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Unnecessary{{disableSuffix}} + #pragma warning disable {{VariableAssignedButNotUsedDiagnosticId}} // Variable is assigned but its value is never used - Necessary + int y = 0; + {{restorePrefix}}#pragma warning restore {{VariableDeclaredButNotUsedDiagnosticId}} // Variable is declared but never used - Unnecessary{{restoreSuffix}} + #pragma warning restore {{VariableAssignedButNotUsedDiagnosticId}} // Variable is assigned but its value is never used - Necessary + } + } + """, + $$""" + + class Class + { + void M() + { + #pragma warning disable {{VariableAssignedButNotUsedDiagnosticId}} // Variable is assigned but its value is never used - Necessary + int y = 0; + #pragma warning restore {{VariableAssignedButNotUsedDiagnosticId}} // Variable is assigned but its value is never used - Necessary + } + } + """); } [Fact] - public async Task TestRemoveDiagnosticSuppression_DuplicateDisableWithoutMatchingRestoreDirective() + public Task TestRemoveDiagnosticSuppression_DuplicateDisableWithoutMatchingRestoreDirective() + => TestInRegularAndScript1Async( + $$""" + + class Class + { + void M() { - await TestInRegularAndScript1Async( - $@" -class Class -{{ - void M() - {{ -[|#pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Unnecessary|] -#pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary - int y = 0; -#pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary - }} -}}", - $@" -class Class -{{ - void M() - {{ -#pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary - int y = 0; -#pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary - }} -}}"); + [|#pragma warning disable {{VariableAssignedButNotUsedDiagnosticId}} // Variable is assigned but its value is never used - Unnecessary|] + #pragma warning disable {{VariableAssignedButNotUsedDiagnosticId}} // Variable is assigned but its value is never used - Necessary + int y = 0; + #pragma warning restore {{VariableAssignedButNotUsedDiagnosticId}} // Variable is assigned but its value is never used - Necessary } + } + """, + $$""" + + class Class + { + void M() + { + #pragma warning disable {{VariableAssignedButNotUsedDiagnosticId}} // Variable is assigned but its value is never used - Necessary + int y = 0; + #pragma warning restore {{VariableAssignedButNotUsedDiagnosticId}} // Variable is assigned but its value is never used - Necessary + } + } + """); [Fact] - public async Task TestRemoveDiagnosticSuppression_DuplicateRestoreWithoutMatchingDisableDirective() + public Task TestRemoveDiagnosticSuppression_DuplicateRestoreWithoutMatchingDisableDirective() + => TestInRegularAndScript1Async( + $$""" + + class Class + { + void M() { - await TestInRegularAndScript1Async( - $@" -class Class -{{ - void M() - {{ -#pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary - int y = 0; -#pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary -[|#pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Unnecessary|] - }} -}}", - $@" -class Class -{{ - void M() - {{ -#pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary - int y = 0; -#pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary - }} -}}"); + #pragma warning disable {{VariableAssignedButNotUsedDiagnosticId}} // Variable is assigned but its value is never used - Necessary + int y = 0; + #pragma warning restore {{VariableAssignedButNotUsedDiagnosticId}} // Variable is assigned but its value is never used - Necessary + [|#pragma warning restore {{VariableAssignedButNotUsedDiagnosticId}} // Variable is assigned but its value is never used - Unnecessary|] } + } + """, + $$""" + + class Class + { + void M() + { + #pragma warning disable {{VariableAssignedButNotUsedDiagnosticId}} // Variable is assigned but its value is never used - Necessary + int y = 0; + #pragma warning restore {{VariableAssignedButNotUsedDiagnosticId}} // Variable is assigned but its value is never used - Necessary + } + } + """); [Theory, CombinatorialData] public async Task TestRemoveUnknownDiagnosticSuppression_Pragma(bool testFixFromDisable) @@ -1127,84 +1161,87 @@ public async Task TestRemoveUnknownDiagnosticSuppression_Pragma(bool testFixFrom : ("", "", "[|", "|]"); await TestInRegularAndScript1Async( - $@" -{disablePrefix}#pragma warning disable UnknownId{disableSuffix} -class Class -{restorePrefix}#pragma warning restore UnknownId{restoreSuffix} -{{ -}}", - @" -class Class -{ -}"); + $$""" + + {{disablePrefix}}#pragma warning disable UnknownId{{disableSuffix}} + class Class + {{restorePrefix}}#pragma warning restore UnknownId{{restoreSuffix}} + { + } + """, + """ + + class Class + { + } + """); } [Fact] - public async Task TestRemoveUnknownDiagnosticSuppression_Attribute() - { - await TestInRegularAndScript1Async( - @" -[|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""UnknownId"")]|] -class Class -{ -}", - @" -class Class -{ -}"); - } + public Task TestRemoveUnknownDiagnosticSuppression_Attribute() + => TestInRegularAndScript1Async( + """ + + [|[System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "UnknownId")]|] + class Class + { + } + """, + """ + + class Class + { + } + """); } #endregion #region Multiple analyzer tests (Compiler AND Analyzer) - public sealed class CompilerAndAnalyzerTests : RemoveUnnecessaryInlineSuppressionsTests + public sealed class CompilerAndAnalyzerTests(ITestOutputHelper logger) : RemoveUnnecessaryInlineSuppressionsTests(logger) { - public CompilerAndAnalyzerTests(ITestOutputHelper logger) - : base(logger) - { - } - internal override ImmutableArray OtherAnalyzers => [new CSharpCompilerDiagnosticAnalyzer(), new UserDiagnosticAnalyzer()]; [Fact] - public async Task TestDoNotRemoveInvalidDiagnosticSuppression() + public Task TestDoNotRemoveInvalidDiagnosticSuppression() + => TestMissingInRegularAndScriptAsync( + $$""" + + class Class + { + void M() { - await TestMissingInRegularAndScriptAsync( - $@" -class Class -{{ - void M() - {{ -[|#pragma warning disable - int y; -#pragma warning restore |] - y = 1; - }} -}} -"); + [|#pragma warning disable + int y; + #pragma warning restore |] + y = 1; } + } + + """); [Fact] public async Task TestDoNotRemoveDiagnosticSuppressionsForSuppressedAnalyzer() { - var source = $@" -[|class Class -{{ - [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""CS0168"")] // Variable is declared but never used - Unnecessary, but suppressed - [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{UserDiagnosticAnalyzer.Descriptor0168.Id}"")] // Variable is declared but never used - Unnecessary, but suppressed - void M() - {{ -#pragma warning disable CS0168 // Variable is declared but never used - Unnecessary, but suppressed -#pragma warning disable {UserDiagnosticAnalyzer.Descriptor0168.Id} // Variable is declared but never used - Unnecessary, but suppressed - int y; -#pragma warning restore {UserDiagnosticAnalyzer.Descriptor0168.Id} // Variable is declared but never used - Unnecessary, but suppressed -#pragma warning restore CS0168 // Variable is declared but never used - Unnecessary, but suppressed - y = 1; - }} -}}|]"; + var source = $$""" + + [|class Class + { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "CS0168")] // Variable is declared but never used - Unnecessary, but suppressed + [System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{UserDiagnosticAnalyzer.Descriptor0168.Id}}")] // Variable is declared but never used - Unnecessary, but suppressed + void M() + { + #pragma warning disable CS0168 // Variable is declared but never used - Unnecessary, but suppressed + #pragma warning disable {{UserDiagnosticAnalyzer.Descriptor0168.Id}} // Variable is declared but never used - Unnecessary, but suppressed + int y; + #pragma warning restore {{UserDiagnosticAnalyzer.Descriptor0168.Id}} // Variable is declared but never used - Unnecessary, but suppressed + #pragma warning restore CS0168 // Variable is declared but never used - Unnecessary, but suppressed + y = 1; + } + }|] + """; var parameters = new TestParameters(); using var workspace = CreateWorkspaceFromOptions(source, parameters); @@ -1224,16 +1261,18 @@ public async Task TestDoNotRemoveCompilerDiagnosticSuppression_IntegerId(bool le { var id = leadingZero ? "0168" : "168"; await TestMissingInRegularAndScriptAsync( - $@" -class Class -{{ - void M() - {{ -[|#pragma warning disable {id} // Variable is declared but never used - Necessary - int y; -#pragma warning restore {id} // Variable is declared but never used - Necessary|] - }} -}}"); + $$""" + + class Class + { + void M() + { + [|#pragma warning disable {{id}} // Variable is declared but never used - Necessary + int y; + #pragma warning restore {{id}} // Variable is declared but never used - Necessary|] + } + } + """); } [Theory, CombinatorialData] @@ -1241,26 +1280,30 @@ public async Task TestRemoveCompilerDiagnosticSuppression_IntegerId(bool leading { var id = leadingZero ? "0168" : "168"; await TestInRegularAndScript1Async( - $@" -class Class -{{ - void M() - {{ -[|#pragma warning disable {id} // Variable is declared but never used - Unnecessary|] - int y; -#pragma warning restore {id} // Variable is declared but never used - Unnecessary - y = 1; - }} -}}", - @" -class Class -{ - void M() + $$""" + + class Class { - int y; - y = 1; + void M() + { + [|#pragma warning disable {{id}} // Variable is declared but never used - Unnecessary|] + int y; + #pragma warning restore {{id}} // Variable is declared but never used - Unnecessary + y = 1; + } + } + """, + """ + + class Class + { + void M() + { + int y; + y = 1; + } } -}"); + """); } [Theory, CombinatorialData] @@ -1272,21 +1315,23 @@ public async Task TestDoNotRemoveExcludedDiagnosticSuppression_Multiple(bool exc }; await TestMissingInRegularAndScriptAsync( - $@" -[|class Class -{{ - [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""CS0168"")] // Variable is declared but never used - Unnecessary, but suppressed - [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{UserDiagnosticAnalyzer.Descriptor0168.Id}"")] // Variable is declared but never used - Unnecessary, but suppressed - void M() - {{ -#pragma warning disable CS0168 // Variable is declared but never used - Unnecessary, but suppressed -#pragma warning disable {UserDiagnosticAnalyzer.Descriptor0168.Id} // Variable is declared but never used - Unnecessary, but suppressed - int y; -#pragma warning restore {UserDiagnosticAnalyzer.Descriptor0168.Id} // Variable is declared but never used - Unnecessary, but suppressed -#pragma warning restore CS0168 // Variable is declared but never used - Unnecessary, but suppressed - y = 1; - }} -}}|]", new TestParameters(options: options)); + $$""" + + [|class Class + { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "CS0168")] // Variable is declared but never used - Unnecessary, but suppressed + [System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{UserDiagnosticAnalyzer.Descriptor0168.Id}}")] // Variable is declared but never used - Unnecessary, but suppressed + void M() + { + #pragma warning disable CS0168 // Variable is declared but never used - Unnecessary, but suppressed + #pragma warning disable {{UserDiagnosticAnalyzer.Descriptor0168.Id}} // Variable is declared but never used - Unnecessary, but suppressed + int y; + #pragma warning restore {{UserDiagnosticAnalyzer.Descriptor0168.Id}} // Variable is declared but never used - Unnecessary, but suppressed + #pragma warning restore CS0168 // Variable is declared but never used - Unnecessary, but suppressed + y = 1; + } + }|] + """, new TestParameters(options: options)); } [Theory, CombinatorialData] @@ -1307,45 +1352,51 @@ public async Task TestDoNotRemoveExcludedDiagnosticSuppression_Subset(bool suppr // Verify disabled ID is not marked unnecessary. await TestMissingInRegularAndScriptAsync( - $@" -class Class -{{ - void M() - {{ -{disablePrefix}#pragma warning disable {disabledId} // Variable is declared but never used - Unnecessary, but suppressed{disableSuffix} -#pragma warning disable {enabledId} // Variable is declared but never used - Unnecessary, not suppressed - int y; -#pragma warning restore {enabledId} // Variable is declared but never used - Unnecessary, not suppressed -{restorePrefix}#pragma warning restore {disabledId} // Variable is declared but never used - Unnecessary, but suppressed{restoreSuffix} - y = 1; - }} -}}", new TestParameters(options: options)); + $$""" + + class Class + { + void M() + { + {{disablePrefix}}#pragma warning disable {{disabledId}} // Variable is declared but never used - Unnecessary, but suppressed{{disableSuffix}} + #pragma warning disable {{enabledId}} // Variable is declared but never used - Unnecessary, not suppressed + int y; + #pragma warning restore {{enabledId}} // Variable is declared but never used - Unnecessary, not suppressed + {{restorePrefix}}#pragma warning restore {{disabledId}} // Variable is declared but never used - Unnecessary, but suppressed{{restoreSuffix}} + y = 1; + } + } + """, new TestParameters(options: options)); // Verify enabled ID is marked unnecessary and removed with code fix. await TestInRegularAndScriptAsync( - $@" -class Class -{{ - void M() - {{ -#pragma warning disable {disabledId} // Variable is declared but never used - Unnecessary, but suppressed -{disablePrefix}#pragma warning disable {enabledId} // Variable is declared but never used - Unnecessary, not suppressed{disableSuffix} - int y; -{restorePrefix}#pragma warning restore {enabledId} // Variable is declared but never used - Unnecessary, not suppressed{restoreSuffix} -#pragma warning restore {disabledId} // Variable is declared but never used - Unnecessary, but suppressed - y = 1; - }} -}}", $@" -class Class -{{ - void M() - {{ -#pragma warning disable {disabledId} // Variable is declared but never used - Unnecessary, but suppressed - int y; -#pragma warning restore {disabledId} // Variable is declared but never used - Unnecessary, but suppressed - y = 1; - }} -}}", options: options); + $$""" + + class Class + { + void M() + { + #pragma warning disable {{disabledId}} // Variable is declared but never used - Unnecessary, but suppressed + {{disablePrefix}}#pragma warning disable {{enabledId}} // Variable is declared but never used - Unnecessary, not suppressed{{disableSuffix}} + int y; + {{restorePrefix}}#pragma warning restore {{enabledId}} // Variable is declared but never used - Unnecessary, not suppressed{{restoreSuffix}} + #pragma warning restore {{disabledId}} // Variable is declared but never used - Unnecessary, but suppressed + y = 1; + } + } + """, $$""" + + class Class + { + void M() + { + #pragma warning disable {{disabledId}} // Variable is declared but never used - Unnecessary, but suppressed + int y; + #pragma warning restore {{disabledId}} // Variable is declared but never used - Unnecessary, but suppressed + y = 1; + } + } + """, options: options); } [Theory, CombinatorialData] @@ -1356,92 +1407,97 @@ public async Task TestRemoveDiagnosticSuppression_FixAll(bool testFixFromDisable : ("", "", "{|FixAllInDocument:", "|}"); await TestInRegularAndScript1Async( - $@" -#pragma warning disable CS0168 // Variable is declared but never used - Unnecessary -#pragma warning disable {UserDiagnosticAnalyzer.Descriptor0168.Id} -[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""CS0168"")] -[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{UserDiagnosticAnalyzer.Descriptor0168.Id}"")] -class Class -{{ - [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""CS0168"")] - [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{UserDiagnosticAnalyzer.Descriptor0168.Id}"")] - void M() - {{ -{disablePrefix}#pragma warning disable {UserDiagnosticAnalyzer.Descriptor0168.Id} // Variable is declared but never used - Unnecessary{disableSuffix} -#pragma warning disable CS0168 // Variable is declared but never used - Unnecessary - int y; -{restorePrefix}#pragma warning restore {UserDiagnosticAnalyzer.Descriptor0168.Id} // Variable is declared but never used - Unnecessary{restoreSuffix} -#pragma warning restore CS0168 // Variable is declared but never used - y = 1; - }} -}}", - @" -class Class -{ - void M() + $$""" + + #pragma warning disable CS0168 // Variable is declared but never used - Unnecessary + #pragma warning disable {{UserDiagnosticAnalyzer.Descriptor0168.Id}} + [System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "CS0168")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{UserDiagnosticAnalyzer.Descriptor0168.Id}}")] + class Class { - int y; - y = 1; - } -}"); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "CS0168")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "{{UserDiagnosticAnalyzer.Descriptor0168.Id}}")] + void M() + { + {{disablePrefix}}#pragma warning disable {{UserDiagnosticAnalyzer.Descriptor0168.Id}} // Variable is declared but never used - Unnecessary{{disableSuffix}} + #pragma warning disable CS0168 // Variable is declared but never used - Unnecessary + int y; + {{restorePrefix}}#pragma warning restore {{UserDiagnosticAnalyzer.Descriptor0168.Id}} // Variable is declared but never used - Unnecessary{{restoreSuffix}} + #pragma warning restore CS0168 // Variable is declared but never used + y = 1; } } + """, + """ - [Fact] - public async Task TestRemoveDiagnosticSuppression_Attribute_Field() + class Class { - await TestInRegularAndScript1Async( -$@" -class Class -{{ - [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""UnknownId"")]|] - private int f; -}}", @" -class Class -{ - private int f; -}"); + void M() + { + int y; + y = 1; + } + } + """); + } } [Fact] - public async Task TestRemoveDiagnosticSuppression_Attribute_Property() - { - await TestInRegularAndScript1Async( -$@" -class Class -{{ - [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""UnknownId"")]|] - public int P {{ get; }} -}}", @" -class Class -{ - public int P { get; } -}"); - } + public Task TestRemoveDiagnosticSuppression_Attribute_Field() + => TestInRegularAndScript1Async( + $$""" + + class Class + { + [|[System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "UnknownId")]|] + private int f; + } + """, """ + + class Class + { + private int f; + } + """); [Fact] - public async Task TestRemoveDiagnosticSuppression_Attribute_Event() - { - await TestInRegularAndScript1Async( -$@" -class Class -{{ - [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""UnknownId"")]|] - private event System.EventHandler SampleEvent; -}}", @" -class Class -{ - private event System.EventHandler SampleEvent; -}"); - } + public Task TestRemoveDiagnosticSuppression_Attribute_Property() + => TestInRegularAndScript1Async( + $$""" - public sealed class NonLocalDiagnosticsAnalyzerTests : RemoveUnnecessaryInlineSuppressionsTests - { - public NonLocalDiagnosticsAnalyzerTests(ITestOutputHelper logger) - : base(logger) - { - } + class Class + { + [|[System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "UnknownId")]|] + public int P { get; } + } + """, """ + class Class + { + public int P { get; } + } + """); + + [Fact] + public Task TestRemoveDiagnosticSuppression_Attribute_Event() + => TestInRegularAndScript1Async( + $$""" + + class Class + { + [|[System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "UnknownId")]|] + private event System.EventHandler SampleEvent; + } + """, """ + + class Class + { + private event System.EventHandler SampleEvent; + } + """); + + public sealed class NonLocalDiagnosticsAnalyzerTests(ITestOutputHelper logger) : RemoveUnnecessaryInlineSuppressionsTests(logger) + { private sealed class NonLocalDiagnosticsAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "NonLocalDiagnosticId"; @@ -1467,45 +1523,40 @@ internal override ImmutableArray OtherAnalyzers => [new NonLocalDiagnosticsAnalyzer()]; [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50203")] - public async Task TestDoNotRemoveInvalidDiagnosticSuppression() - { - await TestMissingInRegularAndScriptAsync( - $@" -[|#pragma warning disable {NonLocalDiagnosticsAnalyzer.DiagnosticId} -namespace N -#pragma warning restore {NonLocalDiagnosticsAnalyzer.DiagnosticId}|] -{{ - class Class - {{ - }} -}}"); - } - } + public Task TestDoNotRemoveInvalidDiagnosticSuppression() + => TestMissingInRegularAndScriptAsync( + $$""" - public sealed class UseAutoPropertyAnalyzerTests : RemoveUnnecessaryInlineSuppressionsTests + [|#pragma warning disable {{NonLocalDiagnosticsAnalyzer.DiagnosticId}} + namespace N + #pragma warning restore {{NonLocalDiagnosticsAnalyzer.DiagnosticId}}|] { - public UseAutoPropertyAnalyzerTests(ITestOutputHelper logger) - : base(logger) + class Class { } + } + """); + } + public sealed class UseAutoPropertyAnalyzerTests(ITestOutputHelper logger) : RemoveUnnecessaryInlineSuppressionsTests(logger) + { internal override ImmutableArray OtherAnalyzers => [new CSharpUseAutoPropertyAnalyzer()]; [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/55529")] - public async Task TestDoNotRemoveAutoPropertySuppression() - { - await TestMissingInRegularAndScriptAsync( - $@" -public class Test2 -{{ - // Message IDE0079 Remove unnecessary suppression - [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Style"", ""IDE0032: Use auto property"", Justification = """")]|] - private readonly int i; - public int I => i; -}} -", new TestParameters(options: Option(CodeStyleOptions2.PreferAutoProperties, true, NotificationOption2.Warning))); - } + public Task TestDoNotRemoveAutoPropertySuppression() + => TestMissingInRegularAndScriptAsync( + $$""" + + public class Test2 + { + // Message IDE0079 Remove unnecessary suppression + [|[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0032: Use auto property", Justification = "")]|] + private readonly int i; + public int I => i; + } + + """, new TestParameters(options: Option(CodeStyleOptions2.PreferAutoProperties, true, NotificationOption2.Warning))); } #endregion diff --git a/src/Features/CSharpTest/Diagnostics/Suppression/SuppressionAllCodeTests.cs b/src/Features/CSharpTest/Diagnostics/Suppression/SuppressionAllCodeTests.cs index 79f4aece45e0a..e0e17228856fe 100644 --- a/src/Features/CSharpTest/Diagnostics/Suppression/SuppressionAllCodeTests.cs +++ b/src/Features/CSharpTest/Diagnostics/Suppression/SuppressionAllCodeTests.cs @@ -36,12 +36,10 @@ public async Task TestPragmaWarningOnEveryNodes() => await TestPragmaAsync(TestResource.AllInOneCSharpCode, CSharpParseOptions.Default, verifier: t => t.IndexOf("#pragma warning disable", StringComparison.Ordinal) >= 0); [Fact] - public async Task TestSuppressionWithAttributeOnEveryNodes() - { - await TestSuppressionWithAttributeAsync( + public Task TestSuppressionWithAttributeOnEveryNodes() + => TestSuppressionWithAttributeAsync( TestResource.AllInOneCSharpCode, CSharpParseOptions.Default, digInto: n => n is not StatementSyntax or BlockSyntax, verifier: t => t.IndexOf("SuppressMessage", StringComparison.Ordinal) >= 0); - } } diff --git a/src/Features/CSharpTest/Diagnostics/Suppression/SuppressionTest_FixAllTests.cs b/src/Features/CSharpTest/Diagnostics/Suppression/SuppressionTest_FixAllTests.cs index 1e57570545a2b..0828b42f48c76 100644 --- a/src/Features/CSharpTest/Diagnostics/Suppression/SuppressionTest_FixAllTests.cs +++ b/src/Features/CSharpTest/Diagnostics/Suppression/SuppressionTest_FixAllTests.cs @@ -24,9 +24,8 @@ public sealed partial class UserInfoDiagnosticSuppressionTests : CSharpPragmaWar { [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInDocument() - { - var input = """ + public Task TestFixAllInDocument() + => TestInRegularAndScriptAsync(""" @@ -67,9 +66,7 @@ class Class2 - """; - - var expected = """ + """, """ @@ -116,16 +113,12 @@ class Class2 - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInProject() - { - var input = """ + public Task TestFixAllInProject() + => TestInRegularAndScriptAsync(""" @@ -165,9 +158,7 @@ class Class2 - """; - - var expected = """ + """, """ @@ -213,16 +204,12 @@ class Class2 - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInSolution() - { - var input = """ + public Task TestFixAllInSolution() + => TestInRegularAndScriptAsync(""" @@ -262,9 +249,7 @@ class Class2 - """; - - var expected = """ + """, """ @@ -314,16 +299,12 @@ class Class2 - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInContainingMember() - { - var input = """ + public Task TestFixAllInContainingMember() + => TestMissingInRegularAndScriptAsync(""" @@ -344,16 +325,12 @@ class Class3 { } - """; - - await TestMissingInRegularAndScriptAsync(input); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInContainingType() - { - var input = """ + public Task TestFixAllInContainingType() + => TestInRegularAndScriptAsync(""" @@ -394,9 +371,7 @@ int Method4() - """; - - var expected = """ + """, """ @@ -441,10 +416,7 @@ int Method4() - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); } } @@ -460,60 +432,20 @@ public sealed partial class UserInfoDiagnosticSuppressionTests : CSharpGlobalSup [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocument() { - var input = """ - - - - using System; - - {|FixAllInDocument:class Class1|} - { - int Method() - { - int x = 0; - } - } - - class Class2 - { - } - - - class Class3 - { - } - - - - - class Class1 - { - int Method() - { - int x = 0; - } - } - - class Class2 - { - } - - - - """; - var addedGlobalSuppressions = -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. + $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. -using System.Diagnostics.CodeAnalysis; + using System.Diagnostics.CodeAnalysis; -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~M:Class1.Method~System.Int32"")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class1"")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] -" + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "member", Target = "~M:Class1.Method~System.Int32")] + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class1")] + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class2")] + + """ .Replace("<", "<").Replace(">", ">"); var expected = """ @@ -562,20 +494,13 @@ class Class2 """; - await TestInRegularAndScriptAsync(input, expected, index: 1); - } - - [Fact] - [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInProject() - { - var input = """ + await TestInRegularAndScriptAsync(""" using System; - {|FixAllInProject:class Class1|} + {|FixAllInDocument:class Class1|} { int Method() { @@ -609,21 +534,28 @@ class Class2 - """; + """, expected, index: 1); + } + [Fact] + [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] + public async Task TestFixAllInProject() + { var addedGlobalSuppressions = -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. - -using System.Diagnostics.CodeAnalysis; - -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~M:Class1.Method~System.Int32"")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class1"")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class3"")] -" + $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. + + using System.Diagnostics.CodeAnalysis; + + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "member", Target = "~M:Class1.Method~System.Int32")] + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class1")] + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class2")] + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class3")] + + """ .Replace("<", "<").Replace(">", ">"); var expected = """ @@ -672,20 +604,13 @@ class Class2 """; - await TestInRegularAndScriptAsync(input, expected, index: 1); - } - - [Fact(Skip = "TODO: File a GitHubIssue for test framework unable to handle multiple projects in solution with same file name.")] - [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInSolution() - { - var input = """ + await TestInRegularAndScriptAsync(""" using System; - {|FixAllInSolution:class Class1|} + {|FixAllInProject:class Class1|} { int Method() { @@ -719,36 +644,41 @@ class Class2 - """; + """, expected, index: 1); + } + [Fact(Skip = "TODO: File a GitHubIssue for test framework unable to handle multiple projects in solution with same file name.")] + [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] + public async Task TestFixAllInSolution() + { var addedGlobalSuppressionsProject1 = -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. + $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. -using System.Diagnostics.CodeAnalysis; + using System.Diagnostics.CodeAnalysis; -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~M:Class1.Method~System.Int32"")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class1"")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class3"")] - -".Replace("<", "<").Replace(">", ">"); + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "member", Target = "~M:Class1.Method~System.Int32")] + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class1")] + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class2")] + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class3")] + """.Replace("<", "<").Replace(">", ">"); var addedGlobalSuppressionsProject2 = -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. - -using System.Diagnostics.CodeAnalysis; + $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~M:Class1.Method~System.Int32"")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class1"")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] + using System.Diagnostics.CodeAnalysis; -".Replace("<", "<").Replace(">", ">"); + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "member", Target = "~M:Class1.Method~System.Int32")] + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class1")] + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class2")] + """.Replace("<", "<").Replace(">", ">"); var expected = """ @@ -800,14 +730,53 @@ class Class2 """; - await TestInRegularAndScriptAsync(input, expected); + await TestInRegularAndScriptAsync(""" + + + + using System; + + {|FixAllInSolution:class Class1|} + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + class Class3 + { + } + + + + + class Class1 + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + + """, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInContainingMember() - { - var input = """ + public Task TestFixAllInContainingMember() + => TestMissingInRegularAndScriptAsync(""" @@ -827,22 +796,35 @@ class Class2 - """; - - await TestMissingInRegularAndScriptAsync(input); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInContainingType() { - var input = """ + var addedGlobalSuppressions = + $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. + + using System.Diagnostics.CodeAnalysis; + + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "member", Target = "~M:Class1.Method1~System.Int32")] + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "member", Target = "~M:Class1.Method2~System.Int32")] + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class1")] + + """ +.Replace("<", "<").Replace(">", ">"); + + var expected = """ using System; - {|FixAllInContainingType:partial class Class1|} + partial class Class1 { int Method1() { @@ -867,31 +849,21 @@ class Class3 { } - - - """; - - var addedGlobalSuppressions = -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. - -using System.Diagnostics.CodeAnalysis; - -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~M:Class1.Method1~System.Int32"")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~M:Class1.Method2~System.Int32"")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class1"")] -" -.Replace("<", "<").Replace(">", ">"); + + """ + addedGlobalSuppressions + + """ + + + + """; - var expected = """ + await TestInRegularAndScriptAsync(""" using System; - partial class Class1 + {|FixAllInContainingType:partial class Class1|} { int Method1() { @@ -916,15 +888,9 @@ class Class3 { } - - """ + addedGlobalSuppressions + - """ - - - - """; - - await TestInRegularAndScriptAsync(input, expected, index: 1); + + + """, expected, index: 1); } } } @@ -936,58 +902,18 @@ public sealed partial class CSharpDiagnosticWithoutLocationSuppressionTests : CS [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInProject() { - var input = """ - - - {|FixAllInProject:|} - using System; - - class Class1 - { - int Method() - { - int x = 0; - } - } - - class Class2 - { - } - - - class Class3 - { - } - - - - - class Class1 - { - int Method() - { - int x = 0; - } - } - - class Class2 - { - } - - - - """; - var addedGlobalSuppressions = -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. + $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. -using System.Diagnostics.CodeAnalysis; + using System.Diagnostics.CodeAnalysis; -[assembly: SuppressMessage(""NoLocationDiagnostic"", ""NoLocationDiagnostic:NoLocationDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] -" + [assembly: SuppressMessage("NoLocationDiagnostic", "NoLocationDiagnostic:NoLocationDiagnostic", Justification = "{FeaturesResources.Pending}")] + + """ .Replace("<", "<").Replace(">", ">"); var expected = """ @@ -1036,7 +962,47 @@ class Class2 """; - await TestInRegularAndScriptAsync(input, expected); + await TestInRegularAndScriptAsync(""" + + + {|FixAllInProject:|} + using System; + + class Class1 + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + class Class3 + { + } + + + + + class Class1 + { + int Method() + { + int x = 0; + } + } + + class Class2 + { + } + + + + """, expected); } } diff --git a/src/Features/CSharpTest/Diagnostics/Suppression/SuppressionTest_FixMultipleTests.cs b/src/Features/CSharpTest/Diagnostics/Suppression/SuppressionTest_FixMultipleTests.cs index 951a39785f704..86fb78b71732e 100644 --- a/src/Features/CSharpTest/Diagnostics/Suppression/SuppressionTest_FixMultipleTests.cs +++ b/src/Features/CSharpTest/Diagnostics/Suppression/SuppressionTest_FixMultipleTests.cs @@ -62,9 +62,8 @@ public sealed class CSharpFixMultiplePragmaWarningSuppressionTests : CSharpFixMu [Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] [WorkItem("https://github.com/dotnet/roslyn/issues/6455")] - public async Task TestFixMultipleInDocument() - { - var input = """ + public Task TestFixMultipleInDocument() + => TestInRegularAndScriptAsync(""" @@ -105,9 +104,7 @@ class Class2 - """; - - var expected = """ + """, """ @@ -156,10 +153,7 @@ class Class2 - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); } #endregion diff --git a/src/Features/CSharpTest/Diagnostics/Suppression/SuppressionTests.cs b/src/Features/CSharpTest/Diagnostics/Suppression/SuppressionTests.cs index a9493c70def88..17c65cd1ff735 100644 --- a/src/Features/CSharpTest/Diagnostics/Suppression/SuppressionTests.cs +++ b/src/Features/CSharpTest/Diagnostics/Suppression/SuppressionTests.cs @@ -5,6 +5,7 @@ #nullable disable using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text.RegularExpressions; @@ -50,396 +51,424 @@ internal override Tuple CreateDia => Tuple.Create(null, new CSharpSuppressionCodeFixProvider()); [Fact] - public async Task TestPragmaWarningDirective() - { - await TestAsync( - @" -class Class -{ - void Method() + public Task TestPragmaWarningDirective() + => TestAsync( + """ + + class Class { - [|int x = 0;|] + void Method() + { + [|int x = 0;|] + } } -}", - $@" -class Class -{{ - void Method() - {{ -#pragma warning disable CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} - int x = 0; -#pragma warning restore CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} - }} -}}"); - } + """, + $$""" - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26015")] - public async Task TestPragmaWarningDirectiveAroundMultiLineStatement() - { - await TestAsync( - @" -class Class -{ - void Method() + class Class { - [|string x = @""multi -line"";|] + void Method() + { + #pragma warning disable CS0219 // {{CSharpResources.WRN_UnreferencedVarAssg_Title}} + int x = 0; + #pragma warning restore CS0219 // {{CSharpResources.WRN_UnreferencedVarAssg_Title}} + } } -}", - $@" -class Class -{{ - void Method() - {{ -#pragma warning disable CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} - string x = @""multi -line""; -#pragma warning restore CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} - }} -}}"); - } + """); - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56165")] - public async Task TestPragmaWarningDirectiveAroundMultiLineInterpolatedString() - { - await TestAsync( - @" -using System; + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26015")] + public Task TestPragmaWarningDirectiveAroundMultiLineStatement() + => TestAsync( + """ -[Obsolete] -class Session { } + class Class + { + void Method() + { + [|string x = @"multi + line";|] + } + } + """, + $$""" -class Class -{ - void Method() + class Class { - var s = $@"" -hi {[|new Session()|]} -""; + void Method() + { + #pragma warning disable CS0219 // {{CSharpResources.WRN_UnreferencedVarAssg_Title}} + string x = @"multi + line"; + #pragma warning restore CS0219 // {{CSharpResources.WRN_UnreferencedVarAssg_Title}} + } } -}", - $@" -using System; + """); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56165")] + public Task TestPragmaWarningDirectiveAroundMultiLineInterpolatedString() + => TestAsync( + """ -[Obsolete] -class Session {{ }} + using System; -class Class -{{ - void Method() - {{ -#pragma warning disable CS0612 // {CSharpResources.WRN_DeprecatedSymbol_Title} - var s = $@"" -hi {{new Session()}} -""; -#pragma warning restore CS0612 // {CSharpResources.WRN_DeprecatedSymbol_Title} - }} -}}"); + [Obsolete] + class Session { } + + class Class + { + void Method() + { + var s = $@" + hi {[|new Session()|]} + "; } + } + """, + $$""" - [Fact] - public async Task TestMultilineStatementPragmaWarningDirective() + using System; + + [Obsolete] + class Session { } + + class Class + { + void Method() { - await TestAsync( - @" -class Class -{ - void Method() + #pragma warning disable CS0612 // {{CSharpResources.WRN_DeprecatedSymbol_Title}} + var s = $@" + hi {new Session()} + "; + #pragma warning restore CS0612 // {{CSharpResources.WRN_DeprecatedSymbol_Title}} + } + } + """); + + [Fact] + public Task TestMultilineStatementPragmaWarningDirective() + => TestAsync( + """ + + class Class + { + void Method() + { + [|int x = 0 + + 1;|] + } + } + """, + $$""" + + class Class { - [|int x = 0 - + 1;|] + void Method() + { + #pragma warning disable CS0219 // {{CSharpResources.WRN_UnreferencedVarAssg_Title}} + int x = 0 + + 1; + #pragma warning restore CS0219 // {{CSharpResources.WRN_UnreferencedVarAssg_Title}} + } } -}", - $@" -class Class -{{ - void Method() - {{ -#pragma warning disable CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} - int x = 0 - + 1; -#pragma warning restore CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} - }} -}}"); - } + """); [Fact] - public async Task TestMultilineStatementPragmaWarningDirective2() - { - await TestAsync( - @" -class Class -{ - void Method() + public Task TestMultilineStatementPragmaWarningDirective2() + => TestAsync( + """ + + class Class { - [|int x = 0, - y = 1;|] + void Method() + { + [|int x = 0, + y = 1;|] + } } -}", - $@" -class Class -{{ - void Method() - {{ -#pragma warning disable CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} - int x = 0, - y = 1; -#pragma warning restore CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} - }} -}}"); - } + """, + $$""" + + class Class + { + void Method() + { + #pragma warning disable CS0219 // {{CSharpResources.WRN_UnreferencedVarAssg_Title}} + int x = 0, + y = 1; + #pragma warning restore CS0219 // {{CSharpResources.WRN_UnreferencedVarAssg_Title}} + } + } + """); [Fact] - public async Task TestPragmaWarningDirectiveWithExistingTrivia() - { - await TestAsync( - @" -class Class -{ - void Method() + public Task TestPragmaWarningDirectiveWithExistingTrivia() + => TestAsync( + """ + + class Class + { + void Method() + { + // Start comment previous line + /* Start comment same line */ [|int x = 0;|] // End comment same line + /* End comment next line */ + } + } + """, + $$""" + + class Class { - // Start comment previous line - /* Start comment same line */ [|int x = 0;|] // End comment same line - /* End comment next line */ + void Method() + { + // Start comment previous line + #pragma warning disable CS0219 // {{CSharpResources.WRN_UnreferencedVarAssg_Title}} + /* Start comment same line */ + int x = 0; // End comment same line + #pragma warning restore CS0219 // {{CSharpResources.WRN_UnreferencedVarAssg_Title}} + /* End comment next line */ + } } -}", - $@" -class Class -{{ - void Method() - {{ - // Start comment previous line -#pragma warning disable CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} - /* Start comment same line */ - int x = 0; // End comment same line -#pragma warning restore CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} - /* End comment next line */ - }} -}}"); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16681")] - public async Task TestPragmaWarningDirectiveWithDocumentationComment1() - { - await TestAsync( - @" -sealed class Class -{ - /// Text - [|protected void Method()|] + public Task TestPragmaWarningDirectiveWithDocumentationComment1() + => TestAsync( + """ + + sealed class Class { + /// Text + [|protected void Method()|] + { + } } -}", - $@" -sealed class Class -{{ - /// Text -#pragma warning disable CS0628 // {CSharpResources.WRN_ProtectedInSealed_Title} - protected void Method() -#pragma warning restore CS0628 // {CSharpResources.WRN_ProtectedInSealed_Title} - {{ - }} -}}"); - } + """, + $$""" + + sealed class Class + { + /// Text + #pragma warning disable CS0628 // {{CSharpResources.WRN_ProtectedInSealed_Title}} + protected void Method() + #pragma warning restore CS0628 // {{CSharpResources.WRN_ProtectedInSealed_Title}} + { + } + } + """); [Fact] - public async Task TestPragmaWarningExpressionBodiedMember1() - { - await TestAsync( - @" -sealed class Class -{ - [|protected int Method()|] => 1; -}", - $@" -sealed class Class -{{ -#pragma warning disable CS0628 // {CSharpResources.WRN_ProtectedInSealed_Title} - protected int Method() => 1; -#pragma warning restore CS0628 // {CSharpResources.WRN_ProtectedInSealed_Title} -}}"); - } + public Task TestPragmaWarningExpressionBodiedMember1() + => TestAsync( + """ + + sealed class Class + { + [|protected int Method()|] => 1; + } + """, + $$""" + + sealed class Class + { + #pragma warning disable CS0628 // {{CSharpResources.WRN_ProtectedInSealed_Title}} + protected int Method() => 1; + #pragma warning restore CS0628 // {{CSharpResources.WRN_ProtectedInSealed_Title}} + } + """); [Fact] - public async Task TestPragmaWarningExpressionBodiedMember2() - { - await TestAsync( - @" -using System; + public Task TestPragmaWarningExpressionBodiedMember2() + => TestAsync( + """ -[Obsolete] -class Session { } + using System; -class Class -{ - string Method() - => @$""hi - {[|new Session()|]} - ""; -}", - $@" -using System; + [Obsolete] + class Session { } -[Obsolete] -class Session {{ }} + class Class + { + string Method() + => @$"hi + {[|new Session()|]} + "; + } + """, + $$""" -class Class -{{ - string Method() -#pragma warning disable CS0612 // {CSharpResources.WRN_DeprecatedSymbol_Title} - => @$""hi - {{new Session()}} - ""; -#pragma warning restore CS0612 // {CSharpResources.WRN_DeprecatedSymbol_Title} -}}"); - } + using System; + + [Obsolete] + class Session { } + + class Class + { + string Method() + #pragma warning disable CS0612 // {{CSharpResources.WRN_DeprecatedSymbol_Title}} + => @$"hi + {new Session()} + "; + #pragma warning restore CS0612 // {{CSharpResources.WRN_DeprecatedSymbol_Title}} + } + """); [Fact] - public async Task TestPragmaWarningExpressionBodiedLocalFunction() - { - await TestAsync( - @" -using System; + public Task TestPragmaWarningExpressionBodiedLocalFunction() + => TestAsync( + """ -[Obsolete] -class Session { } + using System; -class Class -{ - void M() - { - string Method() - => @$""hi - {[|new Session()|]} - ""; - } -}", - $@" -using System; + [Obsolete] + class Session { } + + class Class + { + void M() + { + string Method() + => @$"hi + {[|new Session()|]} + "; + } + } + """, + $$""" + + using System; -[Obsolete] -class Session {{ }} + [Obsolete] + class Session { } -class Class -{{ - void M() - {{ -#pragma warning disable CS0612 // {CSharpResources.WRN_DeprecatedSymbol_Title} - string Method() - => @$""hi - {{new Session()}} - ""; -#pragma warning restore CS0612 // {CSharpResources.WRN_DeprecatedSymbol_Title} - }} -}}"); + class Class + { + void M() + { + #pragma warning disable CS0612 // {{CSharpResources.WRN_DeprecatedSymbol_Title}} + string Method() + => @$"hi + {new Session()} + "; + #pragma warning restore CS0612 // {{CSharpResources.WRN_DeprecatedSymbol_Title}} } + } + """); [Fact] - public async Task TestPragmaWarningExpressionBodiedLambda() - { - await TestAsync( - @" -using System; + public Task TestPragmaWarningExpressionBodiedLambda() + => TestAsync( + """ -[Obsolete] -class Session { } + using System; -class Class -{ - void M() - { - new Func(() - => @$""hi - {[|new Session()|]} - ""); - } -}", - $@" -using System; + [Obsolete] + class Session { } + + class Class + { + void M() + { + new Func(() + => @$"hi + {[|new Session()|]} + "); + } + } + """, + $$""" -[Obsolete] -class Session {{ }} + using System; -class Class -{{ - void M() - {{ -#pragma warning disable CS0612 // {CSharpResources.WRN_DeprecatedSymbol_Title} - new Func(() - => @$""hi - {{new Session()}} - ""); -#pragma warning restore CS0612 // {CSharpResources.WRN_DeprecatedSymbol_Title} - }} -}}"); + [Obsolete] + class Session { } + + class Class + { + void M() + { + #pragma warning disable CS0612 // {{CSharpResources.WRN_DeprecatedSymbol_Title}} + new Func(() + => @$"hi + {new Session()} + "); + #pragma warning restore CS0612 // {{CSharpResources.WRN_DeprecatedSymbol_Title}} } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16681")] - public async Task TestPragmaWarningDirectiveWithDocumentationComment2() - { - await TestAsync( - @" -sealed class Class -{ - /// Text - /// - /// - /// - void Method() + public Task TestPragmaWarningDirectiveWithDocumentationComment2() + => TestAsync( + """ + + sealed class Class { + /// Text + /// + /// + /// + void Method() + { + } } -}", - $@" -sealed class Class -{{ - -#pragma warning disable CS1574 // {CSharpResources.WRN_BadXMLRef_Title} - /// Text - /// - /// - /// - void Method() -#pragma warning restore CS1574 // {CSharpResources.WRN_BadXMLRef_Title} - {{ - }} -}}", new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose)); - } + """, + $$""" + + sealed class Class + { + + #pragma warning disable CS1574 // {{CSharpResources.WRN_BadXMLRef_Title}} + /// Text + /// + /// + /// + void Method() + #pragma warning restore CS1574 // {{CSharpResources.WRN_BadXMLRef_Title}} + { + } + } + """, new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose)); [Fact] - public async Task TestMultipleInstancesOfPragmaWarningDirective() - { - await TestAsync( - @" -class Class -{ - void Method() + public Task TestMultipleInstancesOfPragmaWarningDirective() + => TestAsync( + """ + + class Class { - [|int x = 0, y = 0;|] + void Method() + { + [|int x = 0, y = 0;|] + } } -}", - $@" -class Class -{{ - void Method() - {{ -#pragma warning disable CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} - int x = 0, y = 0; -#pragma warning restore CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} - }} -}}"); - } + """, + $$""" + + class Class + { + void Method() + { + #pragma warning disable CS0219 // {{CSharpResources.WRN_UnreferencedVarAssg_Title}} + int x = 0, y = 0; + #pragma warning restore CS0219 // {{CSharpResources.WRN_UnreferencedVarAssg_Title}} + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/3311")] public async Task TestNoDuplicateSuppressionCodeFixes() { - var source = @" -class Class -{ - void Method() - { - [|int x = 0, y = 0; string s;|] - } -}"; + var source = """ + + class Class + { + void Method() + { + [|int x = 0, y = 0; string s;|] + } + } + """; var parameters = new TestParameters(); using var workspace = CreateWorkspaceFromOptions(source, parameters); @@ -479,183 +508,195 @@ void Method() } [Fact] - public async Task TestErrorAndWarningScenario() - { - await TestAsync( - @" -class Class -{ - void Method() + public Task TestErrorAndWarningScenario() + => TestAsync( + """ + + class Class { - return 0; - [|int x = ""0"";|] + void Method() + { + return 0; + [|int x = "0";|] + } } -}", - $@" -class Class -{{ - void Method() - {{ - return 0; -#pragma warning disable CS0162 // {CSharpResources.WRN_UnreachableCode_Title} - int x = ""0""; -#pragma warning restore CS0162 // {CSharpResources.WRN_UnreachableCode_Title} - }} -}}"); - } + """, + $$""" + + class Class + { + void Method() + { + return 0; + #pragma warning disable CS0162 // {{CSharpResources.WRN_UnreachableCode_Title}} + int x = "0"; + #pragma warning restore CS0162 // {{CSharpResources.WRN_UnreachableCode_Title}} + } + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/956453")] - public async Task TestWholeFilePragmaWarningDirective() - { - await TestAsync( + public Task TestWholeFilePragmaWarningDirective() + => TestAsync( @"class Class { void Method() { [|int x = 0;|] } }", - $@"#pragma warning disable CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} -class Class {{ void Method() {{ int x = 0; }} }} -#pragma warning restore CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title}"); - } + $$""" + #pragma warning disable CS0219 // {{CSharpResources.WRN_UnreferencedVarAssg_Title}} + class Class { void Method() { int x = 0; } } + #pragma warning restore CS0219 // {{CSharpResources.WRN_UnreferencedVarAssg_Title}} + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/970129")] - public async Task TestSuppressionAroundSingleToken() - { - await TestAsync( - @" -using System; -[Obsolete] -class Session { } -class Program -{ - static void Main() + public Task TestSuppressionAroundSingleToken() + => TestAsync( + """ + + using System; + [Obsolete] + class Session { } + class Program + { + static void Main() + { + [|Session|] + } + } + """, + $$""" + + using System; + [Obsolete] + class Session { } + class Program { - [|Session|] + static void Main() + { + #pragma warning disable CS0612 // {{CSharpResources.WRN_DeprecatedSymbol_Title}} + Session + #pragma warning restore CS0612 // {{CSharpResources.WRN_DeprecatedSymbol_Title}} + } } -}", - $@" -using System; -[Obsolete] -class Session {{ }} -class Program -{{ - static void Main() - {{ -#pragma warning disable CS0612 // {CSharpResources.WRN_DeprecatedSymbol_Title} - Session -#pragma warning restore CS0612 // {CSharpResources.WRN_DeprecatedSymbol_Title} - }} -}}"); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")] - public async Task TestPragmaWarningDirectiveAroundTrivia1() - { - await TestAsync( - @" -class Class -{ - void Method() + public Task TestPragmaWarningDirectiveAroundTrivia1() + => TestAsync( + """ + + class Class { + void Method() + { -// Comment -// Comment -[|#pragma abcde|] + // Comment + // Comment + [|#pragma abcde|] - } // Comment + } // Comment -}", - $@" -class Class -{{ - void Method() -#pragma warning disable CS1633 // {CSharpResources.WRN_IllegalPragma_Title} - {{ + } + """, + $$""" -// Comment -// Comment -#pragma abcde + class Class + { + void Method() + #pragma warning disable CS1633 // {{CSharpResources.WRN_IllegalPragma_Title}} + { - }} // Comment -#pragma warning restore CS1633 // {CSharpResources.WRN_IllegalPragma_Title} + // Comment + // Comment + #pragma abcde + } // Comment + #pragma warning restore CS1633 // {{CSharpResources.WRN_IllegalPragma_Title}} -}}"); - } + + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")] - public async Task TestPragmaWarningDirectiveAroundTrivia2() - { - await TestAsync( + public Task TestPragmaWarningDirectiveAroundTrivia2() + => TestAsync( @"[|#pragma abcde|]", - $@"#pragma warning disable CS1633 // {CSharpResources.WRN_IllegalPragma_Title} -#pragma abcde -#pragma warning restore CS1633 // {CSharpResources.WRN_IllegalPragma_Title}"); - } + $""" + #pragma warning disable CS1633 // {CSharpResources.WRN_IllegalPragma_Title} + #pragma abcde + #pragma warning restore CS1633 // {CSharpResources.WRN_IllegalPragma_Title} + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")] - public async Task TestPragmaWarningDirectiveAroundTrivia3() - { - await TestAsync( + public Task TestPragmaWarningDirectiveAroundTrivia3() + => TestAsync( @"[|#pragma abcde|] ", - $@"#pragma warning disable CS1633 // {CSharpResources.WRN_IllegalPragma_Title} -#pragma abcde -#pragma warning restore CS1633 // {CSharpResources.WRN_IllegalPragma_Title}"); - } + $""" + #pragma warning disable CS1633 // {CSharpResources.WRN_IllegalPragma_Title} + #pragma abcde + #pragma warning restore CS1633 // {CSharpResources.WRN_IllegalPragma_Title} + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")] - public async Task TestPragmaWarningDirectiveAroundTrivia4() - { - await TestAsync( - @" + public Task TestPragmaWarningDirectiveAroundTrivia4() + => TestAsync( + """ -[|#pragma abc|] -class C { } -", - $@" + [|#pragma abc|] + class C { } -#pragma warning disable CS1633 // {CSharpResources.WRN_IllegalPragma_Title} -#pragma abc -class C {{ }} -#pragma warning restore CS1633 // {CSharpResources.WRN_IllegalPragma_Title} -"); - } + """, + $$""" + + + #pragma warning disable CS1633 // {{CSharpResources.WRN_IllegalPragma_Title}} + #pragma abc + class C { } + #pragma warning restore CS1633 // {{CSharpResources.WRN_IllegalPragma_Title}} + + + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")] - public async Task TestPragmaWarningDirectiveAroundTrivia5() - { - await TestAsync( - @"class C1 { } -[|#pragma abc|] -class C2 { } -class C3 { }", - $@"class C1 {{ }} -#pragma warning disable CS1633 // {CSharpResources.WRN_IllegalPragma_Title} -#pragma abc -class C2 {{ }} -#pragma warning restore CS1633 // {CSharpResources.WRN_IllegalPragma_Title} -class C3 {{ }}"); - } + public Task TestPragmaWarningDirectiveAroundTrivia5() + => TestAsync( + """ + class C1 { } + [|#pragma abc|] + class C2 { } + class C3 { } + """, + $$""" + class C1 { } + #pragma warning disable CS1633 // {{CSharpResources.WRN_IllegalPragma_Title}} + #pragma abc + class C2 { } + #pragma warning restore CS1633 // {{CSharpResources.WRN_IllegalPragma_Title}} + class C3 { } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")] - public async Task TestPragmaWarningDirectiveAroundTrivia6() - { - await TestAsync( - @"class C1 { } -class C2 { } /// -class C3 { } // comment - // comment -// comment", -$@"class C1 {{ }} -#pragma warning disable CS1574 // {CSharpResources.WRN_BadXMLRef_Title} -class C2 {{ }} /// -class -#pragma warning restore CS1574 // {CSharpResources.WRN_BadXMLRef_Title} -C3 {{ }} // comment - // comment -// comment", CSharpParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)); - } + public Task TestPragmaWarningDirectiveAroundTrivia6() + => TestAsync( + """ + class C1 { } + class C2 { } /// + class C3 { } // comment + // comment + // comment + """, + $$""" + class C1 { } + #pragma warning disable CS1574 // {{CSharpResources.WRN_BadXMLRef_Title}} + class C2 { } /// + class + #pragma warning restore CS1574 // {{CSharpResources.WRN_BadXMLRef_Title}} + C3 { } // comment + // comment + // comment + """, CSharpParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)); } public sealed class UserHiddenDiagnosticSuppressionTests : CSharpPragmaWarningDisableSuppressionTests @@ -667,21 +708,21 @@ internal override Tuple CreateDia } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] - public async Task TestHiddenDiagnosticCannotBeSuppressed() - { - await TestMissingAsync( - @" -using System; + public Task TestHiddenDiagnosticCannotBeSuppressed() + => TestMissingAsync( + """ -class Class -{ -int Method() -{ - [|System.Int32 x = 0;|] - return x; -} -}"); - } + using System; + + class Class + { + int Method() + { + [|System.Int32 x = 0;|] + return x; + } + } + """); } public sealed partial class UserInfoDiagnosticSuppressionTests : CSharpPragmaWarningDisableSuppressionTests @@ -716,33 +757,35 @@ internal override Tuple CreateDia } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] - public async Task TestInfoDiagnosticSuppressed() + public Task TestInfoDiagnosticSuppressed() + => TestAsync( + """ + + using System; + + [|class Class|] + { + int Method() { - await TestAsync( - @" -using System; + int x = 0; + } + } + """, + """ -[|class Class|] -{ - int Method() - { - int x = 0; - } -}", - @" -using System; + using System; -#pragma warning disable InfoDiagnostic // InfoDiagnostic Title -class Class -#pragma warning restore InfoDiagnostic // InfoDiagnostic Title -{ - int Method() - { - int x = 0; - } -}"); + #pragma warning disable InfoDiagnostic // InfoDiagnostic Title + class Class + #pragma warning restore InfoDiagnostic // InfoDiagnostic Title + { + int Method() + { + int x = 0; } } + """); + } public sealed partial class FormattingDiagnosticSuppressionTests : CSharpPragmaWarningDisableSuppressionTests { @@ -756,7 +799,7 @@ internal override Tuple CreateDia { var solution = workspace.CurrentSolution; var compilationOptions = solution.Projects.Single().CompilationOptions; - var specificDiagnosticOptions = new[] { KeyValuePairUtil.Create(IDEDiagnosticIds.FormattingDiagnosticId, ReportDiagnostic.Warn) }; + var specificDiagnosticOptions = new[] { KeyValuePair.Create(IDEDiagnosticIds.FormattingDiagnosticId, ReportDiagnostic.Warn) }; compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(specificDiagnosticOptions); var updatedSolution = solution.WithProjectCompilationOptions(solution.ProjectIds.Single(), compilationOptions); await workspace.ChangeSolutionAsync(updatedSolution); @@ -766,33 +809,35 @@ internal override Tuple CreateDia [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [WorkItem("https://github.com/dotnet/roslyn/issues/38587")] - public async Task TestFormattingDiagnosticSuppressed() + public Task TestFormattingDiagnosticSuppressed() + => TestAsync( + """ + + using System; + + class Class + { + int Method() { - await TestAsync( - @" -using System; + [|int x = 0 ;|] + } + } + """, + """ -class Class -{ - int Method() - { - [|int x = 0 ;|] - } -}", - @" -using System; + using System; -class Class -{ - int Method() - { -#pragma warning disable format - int x = 0 ; -#pragma warning restore format - } -}"); + class Class + { + int Method() + { + #pragma warning disable format + int x = 0 ; + #pragma warning restore format } } + """); + } public sealed class UserErrorDiagnosticSuppressionTests : CSharpPragmaWarningDisableSuppressionTests { @@ -826,33 +871,35 @@ internal override Tuple CreateDia } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] - public async Task TestErrorDiagnosticCanBeSuppressed() + public Task TestErrorDiagnosticCanBeSuppressed() + => TestAsync( + """ + + using System; + + [|class Class|] + { + int Method() { - await TestAsync( - @" -using System; + int x = 0; + } + } + """, + """ -[|class Class|] -{ - int Method() - { - int x = 0; - } -}", - @" -using System; + using System; -#pragma warning disable ErrorDiagnostic // ErrorDiagnostic -class Class -#pragma warning restore ErrorDiagnostic // ErrorDiagnostic -{ - int Method() - { - int x = 0; - } -}"); + #pragma warning disable ErrorDiagnostic // ErrorDiagnostic + class Class + #pragma warning restore ErrorDiagnostic // ErrorDiagnostic + { + int Method() + { + int x = 0; } } + """); + } public sealed class DiagnosticWithBadIdSuppressionTests : CSharpPragmaWarningDisableSuppressionTests { @@ -889,22 +936,21 @@ internal override Tuple CreateDia } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] - public async Task TestDiagnosticWithBadIdSuppressed() - { - // Diagnostics with bad/invalid ID are not reported. - await TestMissingAsync( - @" -using System; + public Task TestDiagnosticWithBadIdSuppressed() + => TestMissingAsync( + """ -[|class Class|] -{ - int Method() - { - int x = 0; - } -}"); + using System; + + [|class Class|] + { + int Method() + { + int x = 0; } } + """); + } } public sealed partial class MultilineDiagnosticSuppressionTests : CSharpPragmaWarningDisableSuppressionTests @@ -940,22 +986,24 @@ internal override Tuple CreateDia [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [WorkItem("https://github.com/dotnet/roslyn/issues/2764")] - public async Task TestPragmaWarningDirectiveAroundMultilineDiagnostic() - { - await TestAsync( -@" -[|class Class -{ -}|] -", -$@" -#pragma warning disable {UserDiagnosticAnalyzer.Decsciptor.Id} // {UserDiagnosticAnalyzer.Decsciptor.Title} -class Class -{{ -}} -#pragma warning restore {UserDiagnosticAnalyzer.Decsciptor.Id} // {UserDiagnosticAnalyzer.Decsciptor.Title} -"); - } + public Task TestPragmaWarningDirectiveAroundMultilineDiagnostic() + => TestAsync( + """ + + [|class Class + { + }|] + + """, + $$""" + + #pragma warning disable {{UserDiagnosticAnalyzer.Decsciptor.Id}} // {{UserDiagnosticAnalyzer.Decsciptor.Title}} + class Class + { + } + #pragma warning restore {{UserDiagnosticAnalyzer.Decsciptor.Id}} // {{UserDiagnosticAnalyzer.Decsciptor.Title}} + + """); } #endregion @@ -971,19 +1019,18 @@ internal override Tuple CreateDia => Tuple.Create(null, new CSharpSuppressionCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] - public async Task TestCompilerDiagnosticsCannotBeSuppressed() - { - // Another test verifies we have a pragma warning action for this source, this verifies there are no other suppression actions. - await TestActionCountAsync( - @" -class Class -{ - void Method() + public Task TestCompilerDiagnosticsCannotBeSuppressed() + => TestActionCountAsync( + """ + + class Class { - [|int x = 0;|] + void Method() + { + [|int x = 0;|] + } } -}", 1); - } + """, 1); } public sealed class FormattingDiagnosticSuppressionTests : CSharpGlobalSuppressMessageSuppressionTests @@ -998,7 +1045,7 @@ internal override Tuple CreateDia { var solution = workspace.CurrentSolution; var compilationOptions = solution.Projects.Single().CompilationOptions; - var specificDiagnosticOptions = new[] { KeyValuePairUtil.Create(IDEDiagnosticIds.FormattingDiagnosticId, ReportDiagnostic.Warn) }; + var specificDiagnosticOptions = new[] { KeyValuePair.Create(IDEDiagnosticIds.FormattingDiagnosticId, ReportDiagnostic.Warn) }; compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(specificDiagnosticOptions); var updatedSolution = solution.WithProjectCompilationOptions(solution.ProjectIds.Single(), compilationOptions); await workspace.ChangeSolutionAsync(updatedSolution); @@ -1008,19 +1055,18 @@ internal override Tuple CreateDia [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [WorkItem("https://github.com/dotnet/roslyn/issues/38587")] - public async Task TestCompilerDiagnosticsCannotBeSuppressed() - { - // Another test verifies we have a pragma warning action for this source, this verifies there are no other suppression actions. - await TestActionCountAsync( - @" -class Class -{ - void Method() + public Task TestCompilerDiagnosticsCannotBeSuppressed() + => TestActionCountAsync( + """ + + class Class { - [|int x = 0 ;|] + void Method() + { + [|int x = 0 ;|] + } } -}", 1); - } + """, 1); } public sealed class UserHiddenDiagnosticSuppressionTests : CSharpGlobalSuppressMessageSuppressionTests @@ -1032,19 +1078,19 @@ internal override Tuple CreateDia } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] - public async Task TestHiddenDiagnosticsCannotBeSuppressed() - { - await TestMissingAsync( - @" -using System; -class Class -{ - void Method() + public Task TestHiddenDiagnosticsCannotBeSuppressed() + => TestMissingAsync( + """ + + using System; + class Class { - [|System.Int32 x = 0;|] + void Method() + { + [|System.Int32 x = 0;|] + } } -}"); - } + """); } [Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] @@ -1122,29 +1168,33 @@ internal override Tuple CreateDia public async Task GeneratedCodeShouldNotHaveTrailingWhitespace() { var expected = -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. + $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. -using System.Diagnostics.CodeAnalysis; + using System.Diagnostics.CodeAnalysis; -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class"")] -"; + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class")] + + """; Assert.All(Regex.Split(expected, "\r?\n"), line => Assert.False(HasTrailingWhitespace(line))); await TestAsync( - @" -using System; + """ -[|class Class|] -{ - int Method() - { - int x = 0; - } -}", expected); + using System; + + [|class Class|] + { + int Method() + { + int x = 0; + } + } + """, expected); } private static bool HasTrailingWhitespace(string line) @@ -1154,892 +1204,964 @@ private static bool HasTrailingWhitespace(string line) public async Task GeneratedCodeShouldNotHaveLeadingBlankLines() { var expected = -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. + $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. + + using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.CodeAnalysis; + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class"")] -"; + """; var lines = Regex.Split(expected, "\r?\n"); Assert.False(string.IsNullOrWhiteSpace(lines.First())); await TestAsync( - @" -using System; + """ -[|class Class|] -{ - int Method() - { - int x = 0; - } -}", expected); + using System; + + [|class Class|] + { + int Method() + { + int x = 0; + } + } + """, expected); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37529")] public async Task GeneratedCodeShouldNotHaveMoreThanOneTrailingBlankLine() { var expected = -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. + $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. + + using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.CodeAnalysis; + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class"")] -"; + """; var lines = Regex.Split(expected, "\r?\n"); Assert.False(string.IsNullOrWhiteSpace(lines[^2])); await TestAsync( - @" -using System; + """ -[|class Class|] -{ - int Method() - { - int x = 0; - } -}", expected); + using System; + + [|class Class|] + { + int Method() + { + int x = 0; + } + } + """, expected); } [Fact] public async Task TestSuppressionOnSimpleType() { await TestAsync( - @" -using System; + """ -[|class Class|] -{ - int Method() - { - int x = 0; - } -}", -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. + using System; + + [|class Class|] + { + int Method() + { + int x = 0; + } + } + """, + $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. + + using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.CodeAnalysis; + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class"")] -"); + """); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( - @" -using System; + """ -using System.Diagnostics.CodeAnalysis; + using System; -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = """", Scope = ""type"", Target = ""~T:Class"")] + using System.Diagnostics.CodeAnalysis; -[|class Class|] -{ - int Method() - { - int x = 0; - } -}"); + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "", Scope = "type", Target = "~T:Class")] + + [|class Class|] + { + int Method() + { + int x = 0; + } + } + """); } [Fact] public async Task TestSuppressionOnNamespace() { await TestInRegularAndScriptAsync( - @" -using System; + """ -[|namespace N|] -{ - class Class - { - int Method() + using System; + + [|namespace N|] { - int x = 0; + class Class + { + int Method() + { + int x = 0; + } + } } - } -}", -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. + """, + $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. + + using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.CodeAnalysis; + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "namespace", Target = "~N:N")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""namespace"", Target = ""~N:N"")] -", index: 1); + """, index: 1); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( - @" -using System; + """ -using System.Diagnostics.CodeAnalysis; + using System; -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = """", Scope = ""namespace"", Target = ""~N:N"")] + using System.Diagnostics.CodeAnalysis; -[|namespace N|] -{ - class Class - { - int Method() + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "", Scope = "namespace", Target = "~N:N")] + + [|namespace N|] { - int x = 0; + class Class + { + int Method() + { + int x = 0; + } + } } - } -}"); + """); } [Fact] public async Task TestSuppressionOnTypeInsideNamespace() { await TestAsync( - @" -using System; + """ -namespace N1 -{ - namespace N2 - { - [|class Class|] + using System; + + namespace N1 { - int Method() + namespace N2 { - int x = 0; + [|class Class|] + { + int Method() + { + int x = 0; + } + } } } - } -}", -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. + """, + $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. -using System.Diagnostics.CodeAnalysis; + using System.Diagnostics.CodeAnalysis; -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:N1.N2.Class"")] -"); + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:N1.N2.Class")] + + """); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( - @" -using System; + """ -using System.Diagnostics.CodeAnalysis; + using System; -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = """", Scope = ""type"", Target = ""~T:N1.N2.Class"")] + using System.Diagnostics.CodeAnalysis; -namespace N1 -{ - namespace N2 - { - [|class Class|] + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "", Scope = "type", Target = "~T:N1.N2.Class")] + + namespace N1 { - int Method() + namespace N2 { - int x = 0; + [|class Class|] + { + int Method() + { + int x = 0; + } + } } } - } -}"); + """); } [Fact] public async Task TestSuppressionOnNestedType() { await TestAsync( - @" -using System; + """ -namespace N -{ - class Generic - { - [|class Class|] + using System; + + namespace N { - int Method() + class Generic { - int x = 0; + [|class Class|] + { + int Method() + { + int x = 0; + } + } } } - } -}", -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. + """, + $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. + + using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.CodeAnalysis; + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:N.Generic`1.Class")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:N.Generic`1.Class"")] -"); + """); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( - @" -using System; + """ -using System.Diagnostics.CodeAnalysis; + using System; -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = """", Scope = ""type"", Target = ""~T:N.Generic`1.Class"")] + using System.Diagnostics.CodeAnalysis; -namespace N -{ - class Generic - { - [|class Class|] + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "", Scope = "type", Target = "~T:N.Generic`1.Class")] + + namespace N { - int Method() + class Generic { - int x = 0; + [|class Class|] + { + int Method() + { + int x = 0; + } + } } } - } -}"); + """); } [Fact] public async Task TestSuppressionOnMethod() { await TestAsync( - @" -using System; + """ -namespace N -{ - class Generic - { - class Class + using System; + + namespace N { - [|int Method() + class Generic { - int x = 0; - }|] + class Class + { + [|int Method() + { + int x = 0; + }|] + } + } } - } -}", -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. + """, + $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. -using System.Diagnostics.CodeAnalysis; + using System.Diagnostics.CodeAnalysis; -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~M:N.Generic`1.Class.Method~System.Int32"")] -"); + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "member", Target = "~M:N.Generic`1.Class.Method~System.Int32")] + + """); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( - @" -using System; + """ -using System.Diagnostics.CodeAnalysis; + using System; -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = """", Scope = ""member"", Target = ""~M:N.Generic`1.Class.Method~System.Int32"")] + using System.Diagnostics.CodeAnalysis; -namespace N -{ - class Generic - { - class Class + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "", Scope = "member", Target = "~M:N.Generic`1.Class.Method~System.Int32")] + + namespace N { - [|int Method()|] + class Generic { - int x = 0; + class Class + { + [|int Method()|] + { + int x = 0; + } + } } } - } -}"); + """); } [Fact] public async Task TestSuppressionOnOverloadedMethod() { await TestAsync( - @" -using System; + """ -namespace N -{ - class Generic - { - class Class + using System; + + namespace N { - [|int Method(int y, ref char z) + class Generic { - int x = 0; - }|] + class Class + { + [|int Method(int y, ref char z) + { + int x = 0; + }|] - int Method() - { - int x = 0; + int Method() + { + int x = 0; + } + } } } - } -}", -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. + """, + $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. -using System.Diagnostics.CodeAnalysis; + using System.Diagnostics.CodeAnalysis; -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~M:N.Generic`1.Class.Method(System.Int32,System.Char@)~System.Int32"")] -"); + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "member", Target = "~M:N.Generic`1.Class.Method(System.Int32,System.Char@)~System.Int32")] + + """); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( - @" -using System; + """ -using System.Diagnostics.CodeAnalysis; + using System; -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = """", Scope = ""member"", Target = ""~M:N.Generic`1.Class.Method(System.Int32,System.Char@)~System.Int32"")] + using System.Diagnostics.CodeAnalysis; -namespace N -{ - class Generic - { - class Class + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "", Scope = "member", Target = "~M:N.Generic`1.Class.Method(System.Int32,System.Char@)~System.Int32")] + + namespace N { - [|int Method(int y, ref char z)|] + class Generic { - int x = 0; - } + class Class + { + [|int Method(int y, ref char z)|] + { + int x = 0; + } - int Method() - { - int x = 0; + int Method() + { + int x = 0; + } + } } } - } -}"); + """); await TestAsync( - @" -using System; + """ -using System.Diagnostics.CodeAnalysis; + using System; -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = """", Scope = ""member"", Target = ""~M:N.Generic`1.Class.Method(System.Int32,System.Char@)~System.Int32"")] + using System.Diagnostics.CodeAnalysis; -namespace N -{ - class Generic + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "", Scope = "member", Target = "~M:N.Generic`1.Class.Method(System.Int32,System.Char@)~System.Int32")] + + namespace N { - class Class + class Generic { - [|int Method(int y, ref char z) + class Class { - int x = 0; - } + [|int Method(int y, ref char z) + { + int x = 0; + } - int Method() - { - int x = 0; - }|] + int Method() + { + int x = 0; + }|] + } } } -}", -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. + """, + $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. -using System.Diagnostics.CodeAnalysis; + using System.Diagnostics.CodeAnalysis; -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~M:N.Generic`1.Class.Method~System.Int32"")] -"); + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "member", Target = "~M:N.Generic`1.Class.Method~System.Int32")] + + """); } [Fact] public async Task TestSuppressionOnGenericMethod() { await TestAsync( - @" -using System; + """ -namespace N -{ - class Generic - { - class Class + using System; + + namespace N { - [|int Method(U u) + class Generic { - int x = 0; - }|] + class Class + { + [|int Method(U u) + { + int x = 0; + }|] + } + } } - } -}", -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. + """, + $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. + + using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.CodeAnalysis; + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "member", Target = "~M:N.Generic`1.Class.Method``1(``0)~System.Int32")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~M:N.Generic`1.Class.Method``1(``0)~System.Int32"")] -"); + """); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( - @" -using System; + """ -using System.Diagnostics.CodeAnalysis; + using System; -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = """", Scope = ""member"", Target = ""~M:N.Generic`1.Class.Method``1(``0)~System.Int32"")] + using System.Diagnostics.CodeAnalysis; -namespace N -{ - class Generic - { - class Class + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "", Scope = "member", Target = "~M:N.Generic`1.Class.Method``1(``0)~System.Int32")] + + namespace N { - [|int Method(U u)|] + class Generic { - int x = 0; + class Class + { + [|int Method(U u)|] + { + int x = 0; + } + } } } - } -}"); + """); } [Fact] public async Task TestSuppressionOnProperty() { await TestAsync( - @" -using System; - -namespace N -{ - class Generic - { - class Class - { - [|int Property|] - { - get { int x = 0; } - } - } - } -}", -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. - -using System.Diagnostics.CodeAnalysis; - -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~P:N.Generic.Class.Property"")] -"); - - // Also verify that the added attribute does indeed suppress the diagnostic. - await TestMissingAsync( - @" -using System; - -using System.Diagnostics.CodeAnalysis; + """ -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = """", Scope = ""member"", Target = ""~P:N.Generic.Class.Property"")] + using System; -namespace N -{ - class Generic - { - class Class + namespace N { - [|int Property|] + class Generic { - get { int x = 0; } + class Class + { + [|int Property|] + { + get { int x = 0; } + } + } } } - } -}"); - } - - [Fact] - public async Task TestSuppressionOnField() - { - await TestAsync( - @" -using System; - -class Class -{ - [|int field = 0;|] -}", -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. - -using System.Diagnostics.CodeAnalysis; - -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~F:Class.field"")] -"); - - // Also verify that the added attribute does indeed suppress the diagnostic. - await TestMissingAsync( - @" -using System; - -using System.Diagnostics.CodeAnalysis; - -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = """", Scope = ""member"", Target = ""~F:Class.field"")] - -class Class -{ - [|int field = 0;|] -}"); - } - - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/6379")] - public async Task TestSuppressionOnTriviaBetweenFields() - { - await TestAsync( - @" -using System; + """, + $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. -// suppressions on field are not relevant. -using System.Diagnostics.CodeAnalysis; - -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~F:E.Field1"")] -using System.Diagnostics.CodeAnalysis; - -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~F:E.Field2"")] - -enum E -{ - [| - Field1, // trailing trivia for comma token which doesn't belong to span of any of the fields - Field2 - |] -}", -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. + using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.CodeAnalysis; + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "member", Target = "~P:N.Generic.Class.Property")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:E"")] -"); + """); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( - @" -using System; + """ -using System.Diagnostics.CodeAnalysis; + using System; -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:E"")] + using System.Diagnostics.CodeAnalysis; -enum E -{ - [| - Field1, // trailing trivia for comma token which doesn't belong to span of any of the fields - Field2 - |] -}"); + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "", Scope = "member", Target = "~P:N.Generic.Class.Property")] + + namespace N + { + class Generic + { + class Class + { + [|int Property|] + { + get { int x = 0; } + } + } + } + } + """); } [Fact] - public async Task TestSuppressionOnField2() + public async Task TestSuppressionOnField() { await TestAsync( - @" -using System; + """ -class Class -{ - int [|field = 0|], field2 = 1; -}", -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. + using System; + + class Class + { + [|int field = 0;|] + } + """, + $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. + + using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.CodeAnalysis; + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "member", Target = "~F:Class.field")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~F:Class.field"")] -"); + """); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( - @" -using System; + """ -using System.Diagnostics.CodeAnalysis; + using System; -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = """", Scope = ""member"", Target = ""~F:Class.field"")] + using System.Diagnostics.CodeAnalysis; -class Class -{ - int [|field|] = 0, field2 = 1; -}"); + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "", Scope = "member", Target = "~F:Class.field")] + + class Class + { + [|int field = 0;|] + } + """); } - [Fact] - public async Task TestSuppressionOnEvent() + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/6379")] + public async Task TestSuppressionOnTriviaBetweenFields() { await TestAsync( - @" -using System; + """ -public class SampleEventArgs -{ - public SampleEventArgs(string s) { Text = s; } - public String Text {get; private set;} // readonly - } + using System; -class Class -{ - // Declare the delegate (if using non-generic pattern). - public delegate void SampleEventHandler(object sender, SampleEventArgs e); + // suppressions on field are not relevant. + using System.Diagnostics.CodeAnalysis; - // Declare the event. - [|public event SampleEventHandler SampleEvent - { - add { } - remove { } - }|] -}", -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "member", Target = "~F:E.Field1")] + using System.Diagnostics.CodeAnalysis; + + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "member", Target = "~F:E.Field2")] + + enum E + { + [| + Field1, // trailing trivia for comma token which doesn't belong to span of any of the fields + Field2 + |] + } + """, + $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. + + using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.CodeAnalysis; + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:E")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~E:Class.SampleEvent"")] -"); + """); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( - @" -using System; - -using System.Diagnostics.CodeAnalysis; + """ -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = """", Scope = ""member"", Target = ""~E:Class.SampleEvent"")] + using System; -public class SampleEventArgs -{ - public SampleEventArgs(string s) { Text = s; } - public String Text {get; private set;} // readonly -} + using System.Diagnostics.CodeAnalysis; -class Class -{ - // Declare the delegate (if using non-generic pattern). - public delegate void SampleEventHandler(object sender, SampleEventArgs e); + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:E")] - // Declare the event. - [|public event SampleEventHandler SampleEvent|] - { - add { } - remove { } - } -}"); + enum E + { + [| + Field1, // trailing trivia for comma token which doesn't belong to span of any of the fields + Field2 + |] + } + """); } [Fact] - public async Task TestSuppressionWithExistingGlobalSuppressionsDocument() + public async Task TestSuppressionOnField2() { - var initialMarkup = @" - - - - "", Scope = ""type"", Target = ""Class"")] -]]> - - -"; - var expectedText = -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. + using System; -using System.Diagnostics.CodeAnalysis; + using System.Diagnostics.CodeAnalysis; -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = """", Scope = ""type"", Target = ""Class"")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] -"; + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "", Scope = "member", Target = "~F:Class.field")] - await TestAsync(initialMarkup, expectedText); + class Class + { + int [|field|] = 0, field2 = 1; + } + """); } [Fact] - public async Task TestSuppressionWithExistingGlobalSuppressionsDocument2() + public async Task TestSuppressionOnEvent() { - // Own custom file named GlobalSuppressions.cs - var initialMarkup = @" - - - - - - -"; - var expectedText = -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. + public class SampleEventArgs + { + public SampleEventArgs(string s) { Text = s; } + public String Text {get; private set;} // readonly + } -using System.Diagnostics.CodeAnalysis; + class Class + { + // Declare the delegate (if using non-generic pattern). + public delegate void SampleEventHandler(object sender, SampleEventArgs e); -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] -"; + // Declare the event. + [|public event SampleEventHandler SampleEvent + { + add { } + remove { } + }|] + } + """, + $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. - await TestAsync(initialMarkup, expectedText); - } + using System.Diagnostics.CodeAnalysis; - [Fact] - public async Task TestSuppressionWithExistingGlobalSuppressionsDocument3() - { - // Own custom file named GlobalSuppressions.cs + existing GlobalSuppressions2.cs with global suppressions - var initialMarkup = @" - - - - - - "", Scope = ""type"", Target = ""Class"")] -]]> - - -"; - var expectedText = -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "", Scope = "member", Target = "~E:Class.SampleEvent")] -using System.Diagnostics.CodeAnalysis; + public class SampleEventArgs + { + public SampleEventArgs(string s) { Text = s; } + public String Text {get; private set;} // readonly + } -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = """", Scope = ""type"", Target = ""Class"")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] -"; + class Class + { + // Declare the delegate (if using non-generic pattern). + public delegate void SampleEventHandler(object sender, SampleEventArgs e); - await TestAsync(initialMarkup, expectedText); + // Declare the event. + [|public event SampleEventHandler SampleEvent|] + { + add { } + remove { } + } + } + """); } [Fact] - public async Task TestSuppressionWithUsingDirectiveInExistingGlobalSuppressionsDocument() - { - var initialMarkup = @" - - TestAsync(""" + + + + + ", Scope = "type", Target = "Class")] + ]]> + + + + """, $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. + + using System.Diagnostics.CodeAnalysis; + + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "", Scope = "type", Target = "Class")] + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class2")] + + """); -class Class { } + [Fact] + public Task TestSuppressionWithExistingGlobalSuppressionsDocument2() + => TestAsync(""" + + + + + + + + + """, $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. + + using System.Diagnostics.CodeAnalysis; + + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class2")] + + """); -[|class Class2|] { } -]]> - - TestAsync(""" + + + + + + + ", Scope = "type", Target = "Class")] + ]]> + + + + """, $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. + + using System.Diagnostics.CodeAnalysis; + + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "", Scope = "type", Target = "Class")] + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class2")] + + """); -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = """", Scope = ""type"", Target = ""Class"")] -]]> - - -"; - var expectedText = - $@" -using System.Diagnostics.CodeAnalysis; + [Fact] + public Task TestSuppressionWithUsingDirectiveInExistingGlobalSuppressionsDocument() + => TestAsync(""" + + + "", Scope = ""type"", Target = ""Class"")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] -"; + class Class { } - await TestAsync(initialMarkup, expectedText); - } + [|class Class2|] { } + ]]> + + - - ", Scope = "type", Target = "Class")] + ]]> + + + + """, $""" -class Class { } + using System.Diagnostics.CodeAnalysis; -[|class Class2|] { } -]]> - - "", Scope = ""type"", Target = ""Class"")] -]]> - - -"; - var expectedText = -$@" -using System.Diagnostics.CodeAnalysis; + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "", Scope = "type", Target = "Class")] + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class2")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = """", Scope = ""type"", Target = ""Class"")] -[assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] -"; + """); - await TestAsync(initialMarkup, expectedText); - } + [Fact] + public Task TestSuppressionWithoutUsingDirectiveInExistingGlobalSuppressionsDocument() + => TestAsync(""" + + + + + ", Scope = "type", Target = "Class")] + ]]> + + + + """, $""" + + using System.Diagnostics.CodeAnalysis; + + [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "", Scope = "type", Target = "Class")] + [assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{FeaturesResources.Pending}", Scope = "type", Target = "~T:Class2")] + + """); } } @@ -2091,31 +2213,34 @@ internal override Tuple CreateDia [Fact] public async Task TestSuppressionOnSimpleType() { - var initial = @" -using System; + var expected = $$""" -// Some trivia -/* More Trivia */ [|class Class|] -{ - int Method() - { - int x = 0; - } -}"; - var expected = $@" -using System; + using System; -// Some trivia -/* More Trivia */ -[System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] -class Class -{{ - int Method() - {{ - int x = 0; - }} -}}"; - await TestAsync(initial, expected); + // Some trivia + /* More Trivia */ + [System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{{FeaturesResources.Pending}}")] + class Class + { + int Method() + { + int x = 0; + } + } + """; + await TestAsync(""" + + using System; + + // Some trivia + /* More Trivia */ [|class Class|] + { + int Method() + { + int x = 0; + } + } + """, expected); // Also verify that the added attribute does indeed suppress the diagnostic. expected = expected.Replace("class Class", "[|class Class|]"); @@ -2126,34 +2251,37 @@ int Method() public async Task TestSuppressionOnSimpleType2() { // Type already has attributes. - var initial = @" -using System; + var expected = $$""" -// Some trivia -/* More Trivia */ -[System.Diagnostics.CodeAnalysis.SuppressMessage(""SomeOtherDiagnostic"", ""SomeOtherDiagnostic:Title"", Justification = """")] -[|class Class|] -{ - int Method() - { - int x = 0; - } -}"; - var expected = $@" -using System; + using System; -// Some trivia -/* More Trivia */ -[System.Diagnostics.CodeAnalysis.SuppressMessage(""SomeOtherDiagnostic"", ""SomeOtherDiagnostic:Title"", Justification = """")] -[System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] -class Class -{{ - int Method() - {{ - int x = 0; - }} -}}"; - await TestAsync(initial, expected); + // Some trivia + /* More Trivia */ + [System.Diagnostics.CodeAnalysis.SuppressMessage("SomeOtherDiagnostic", "SomeOtherDiagnostic:Title", Justification = "")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{{FeaturesResources.Pending}}")] + class Class + { + int Method() + { + int x = 0; + } + } + """; + await TestAsync(""" + + using System; + + // Some trivia + /* More Trivia */ + [System.Diagnostics.CodeAnalysis.SuppressMessage("SomeOtherDiagnostic", "SomeOtherDiagnostic:Title", Justification = "")] + [|class Class|] + { + int Method() + { + int x = 0; + } + } + """, expected); // Also verify that the added attribute does indeed suppress the diagnostic. expected = expected.Replace("class Class", "[|class Class|]"); @@ -2164,36 +2292,39 @@ int Method() public async Task TestSuppressionOnSimpleType3() { // Type already has attributes with trailing trivia. - var initial = @" -using System; + var expected = $$""" -// Some trivia -/* More Trivia */ -[System.Diagnostics.CodeAnalysis.SuppressMessage(""SomeOtherDiagnostic"", ""SomeOtherDiagnostic:Title"", Justification = """")] -/* Some More Trivia */ -[|class Class|] -{ - int Method() - { - int x = 0; - } -}"; - var expected = $@" -using System; + using System; -// Some trivia -/* More Trivia */ -[System.Diagnostics.CodeAnalysis.SuppressMessage(""SomeOtherDiagnostic"", ""SomeOtherDiagnostic:Title"", Justification = """")] -[System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] -/* Some More Trivia */ -class Class -{{ - int Method() - {{ - int x = 0; - }} -}}"; - await TestAsync(initial, expected); + // Some trivia + /* More Trivia */ + [System.Diagnostics.CodeAnalysis.SuppressMessage("SomeOtherDiagnostic", "SomeOtherDiagnostic:Title", Justification = "")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{{FeaturesResources.Pending}}")] + /* Some More Trivia */ + class Class + { + int Method() + { + int x = 0; + } + } + """; + await TestAsync(""" + + using System; + + // Some trivia + /* More Trivia */ + [System.Diagnostics.CodeAnalysis.SuppressMessage("SomeOtherDiagnostic", "SomeOtherDiagnostic:Title", Justification = "")] + /* Some More Trivia */ + [|class Class|] + { + int Method() + { + int x = 0; + } + } + """, expected); // Also verify that the added attribute does indeed suppress the diagnostic. expected = expected.Replace("class Class", "[|class Class|]"); @@ -2203,40 +2334,43 @@ int Method() [Fact] public async Task TestSuppressionOnTypeInsideNamespace() { - var initial = @" -using System; + var expected = $$""" -namespace N1 -{ - namespace N2 - { - [|class Class|] - { - int Method() - { - int x = 0; - } - } - } -}"; - var expected = $@" -using System; + using System; -namespace N1 -{{ - namespace N2 - {{ - [System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] - class Class - {{ - int Method() - {{ - int x = 0; - }} - }} - }} -}}"; - await TestAsync(initial, expected); + namespace N1 + { + namespace N2 + { + [System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{{FeaturesResources.Pending}}")] + class Class + { + int Method() + { + int x = 0; + } + } + } + } + """; + await TestAsync(""" + + using System; + + namespace N1 + { + namespace N2 + { + [|class Class|] + { + int Method() + { + int x = 0; + } + } + } + } + """, expected); // Also verify that the added attribute does indeed suppress the diagnostic. expected = expected.Replace("class Class", "[|class Class|]"); @@ -2246,40 +2380,43 @@ int Method() [Fact] public async Task TestSuppressionOnNestedType() { - var initial = @" -using System; + var expected = $$""" -namespace N -{ - class Generic - { - [|class Class|] - { - int Method() - { - int x = 0; - } - } - } -}"; - var expected = $@" -using System; + using System; -namespace N -{{ - class Generic - {{ - [System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] - class Class - {{ - int Method() - {{ - int x = 0; - }} - }} - }} -}}"; - await TestAsync(initial, expected); + namespace N + { + class Generic + { + [System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{{FeaturesResources.Pending}}")] + class Class + { + int Method() + { + int x = 0; + } + } + } + } + """; + await TestAsync(""" + + using System; + + namespace N + { + class Generic + { + [|class Class|] + { + int Method() + { + int x = 0; + } + } + } + } + """, expected); // Also verify that the added attribute does indeed suppress the diagnostic. expected = expected.Replace("class Class", "[|class Class|]"); @@ -2289,40 +2426,43 @@ int Method() [Fact] public async Task TestSuppressionOnMethod() { - var initial = @" -using System; + var expected = $$""" -namespace N -{ - class Generic - { - class Class - { - [|int Method()|] - { - int x = 0; - } - } - } -}"; - var expected = $@" -using System; + using System; -namespace N -{{ - class Generic - {{ - class Class - {{ - [System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] - int Method() - {{ - int x = 0; - }} - }} - }} -}}"; - await TestAsync(initial, expected); + namespace N + { + class Generic + { + class Class + { + [System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{{FeaturesResources.Pending}}")] + int Method() + { + int x = 0; + } + } + } + } + """; + await TestAsync(""" + + using System; + + namespace N + { + class Generic + { + class Class + { + [|int Method()|] + { + int x = 0; + } + } + } + } + """, expected); // Also verify that the added attribute does indeed suppress the diagnostic. expected = expected.Replace("int Method()", "[|int Method()|]"); @@ -2332,38 +2472,41 @@ int Method() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47427")] public async Task TestSuppressionOnMethodWithXmlDoc() { - var initial = @" -using System; + var expected = $$""" -namespace ClassLibrary10 -{ - public class Class1 - { - int x; + using System; - /// - /// This is a description - /// - [|public void Method(int unused)|] { } - } -}"; - var expected = $@" -using System; + namespace ClassLibrary10 + { + public class Class1 + { + int x; + + /// + /// This is a description + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{{FeaturesResources.Pending}}")] + public void Method(int unused) { } + } + } + """; + await TestAsync(""" -namespace ClassLibrary10 -{{ - public class Class1 - {{ - int x; - - /// - /// This is a description - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] - public void Method(int unused) {{ }} - }} -}}"; - await TestAsync(initial, expected); + using System; + + namespace ClassLibrary10 + { + public class Class1 + { + int x; + + /// + /// This is a description + /// + [|public void Method(int unused)|] { } + } + } + """, expected); // Also verify that the added attribute does indeed suppress the diagnostic. expected = expected.Replace("public void Method(int unused)", "[|public void Method(int unused)|]"); @@ -2373,30 +2516,33 @@ public void Method(int unused) {{ }} [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47427")] public async Task TestSuppressionOnMethodWithNoTrivia() { - var initial = @" -using System; + var expected = $$""" -namespace ClassLibrary10 -{ - public class Class1 - { - int x; -[|public void Method(int unused)|] { } - } -}"; - var expected = $@" -using System; + using System; + + namespace ClassLibrary10 + { + public class Class1 + { + int x; + [System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{{FeaturesResources.Pending}}")] + public void Method(int unused) { } + } + } + """; + await TestAsync(""" + + using System; -namespace ClassLibrary10 -{{ - public class Class1 - {{ - int x; - [System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] - public void Method(int unused) {{ }} - }} -}}"; - await TestAsync(initial, expected); + namespace ClassLibrary10 + { + public class Class1 + { + int x; + [|public void Method(int unused)|] { } + } + } + """, expected); // Also verify that the added attribute does indeed suppress the diagnostic. expected = expected.Replace("public void Method(int unused)", "[|public void Method(int unused)|]"); @@ -2406,31 +2552,34 @@ public void Method(int unused) {{ }} [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47427")] public async Task TestSuppressionOnMethodWithTriviaStartsOnTheSameLine() { - var initial = @" -using System; + var expected = $$""" -namespace ClassLibrary10 -{ - public class Class1 - { - int x; - /*test*/[|public void Method(int unused)|] { } - } -}"; - var expected = $@" -using System; + using System; + + namespace ClassLibrary10 + { + public class Class1 + { + int x; + /*test*/ + [System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification = "{{FeaturesResources.Pending}}")] + public void Method(int unused) { } + } + } + """; + await TestAsync(""" -namespace ClassLibrary10 -{{ - public class Class1 - {{ - int x; - /*test*/ - [System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] - public void Method(int unused) {{ }} - }} -}}"; - await TestAsync(initial, expected); + using System; + + namespace ClassLibrary10 + { + public class Class1 + { + int x; + /*test*/[|public void Method(int unused)|] { } + } + } + """, expected); // Also verify that the added attribute does indeed suppress the diagnostic. expected = expected.Replace("public void Method(int unused)", "[|public void Method(int unused)|]"); @@ -2470,29 +2619,31 @@ internal override Tuple CreateDia [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073825")] - public async Task TestDiagnosticWithoutLocationCanBeSuppressed() - { - await TestAsync( - @"[||] -using System; + public Task TestDiagnosticWithoutLocationCanBeSuppressed() + => TestAsync( + """ + [||] + using System; -class Class -{ - int Method() + class Class { - int x = 0; + int Method() + { + int x = 0; + } } -}", -$@"// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. + """, + $""" + // This file is used by Code Analysis to maintain SuppressMessage + // attributes that are applied to this project. + // Project-level suppressions either have no target or are given + // a specific target and scoped to a namespace, type, member, etc. -using System.Diagnostics.CodeAnalysis; + using System.Diagnostics.CodeAnalysis; -[assembly: SuppressMessage(""NoLocationDiagnostic"", ""NoLocationDiagnostic:NoLocationDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] -"); - } + [assembly: SuppressMessage("NoLocationDiagnostic", "NoLocationDiagnostic:NoLocationDiagnostic", Justification = "{FeaturesResources.Pending}")] + + """); } #endregion diff --git a/src/Features/CSharpTest/EditAndContinue/ActiveStatementTests.Methods.cs b/src/Features/CSharpTest/EditAndContinue/ActiveStatementTests.Methods.cs index dd54e3b88f3ef..c0d0ea3cea1f4 100644 --- a/src/Features/CSharpTest/EditAndContinue/ActiveStatementTests.Methods.cs +++ b/src/Features/CSharpTest/EditAndContinue/ActiveStatementTests.Methods.cs @@ -22,28 +22,29 @@ public sealed class ActiveStatementTests_Methods : EditingTestBase [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/740443")] public void Method_Delete_Leaf1() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Goo(1); - } - - static void Goo(int a) - { - Console.WriteLine(a); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - Goo(1); - } -} -"; + var src1 = """ + class C + { + static void Main(string[] args) + { + Goo(1); + } + + static void Goo(int a) + { + Console.WriteLine(a); + } + } + """; + var src2 = """ + class C + { + static void Main(string[] args) + { + Goo(1); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -60,23 +61,24 @@ static void Main(string[] args) [Fact] public void Method_Rename_Leaf1() { - var src1 = @" -class C -{ - static void Goo(int a) - { - Console.WriteLine(a); - } -}"; - var src2 = @" -class C -{ - static void Boo(int a) - { - Console.WriteLine(a); - } -} -"; + var src1 = """ + class C + { + static void Goo(int a) + { + Console.WriteLine(a); + } + } + """; + var src2 = """ + class C + { + static void Boo(int a) + { + Console.WriteLine(a); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -158,42 +160,43 @@ public void Method_BlockBodyToExpressionBody1() [Fact] public void Update_Inner_GenericMethod() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - C c = new C(); - int a = 5; - int b = 10; - c.Swap(ref a, ref b); - } - - void Swap(ref T lhs, ref T rhs) where T : System.IComparable - { - Console.WriteLine(""hello""); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - while (true) - { - C c = new C(); - int a = 5; - int b = 10; - c.Swap(ref b, ref a); - } - } - - void Swap(ref T lhs, ref T rhs) where T : System.IComparable - { - Console.WriteLine(""hello""); - } -} -"; + var src1 = """ + class C + { + static void Main(string[] args) + { + C c = new C(); + int a = 5; + int b = 10; + c.Swap(ref a, ref b); + } + + void Swap(ref T lhs, ref T rhs) where T : System.IComparable + { + Console.WriteLine("hello"); + } + } + """; + var src2 = """ + class C + { + static void Main(string[] args) + { + while (true) + { + C c = new C(); + int a = 5; + int b = 10; + c.Swap(ref b, ref a); + } + } + + void Swap(ref T lhs, ref T rhs) where T : System.IComparable + { + Console.WriteLine("hello"); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -204,36 +207,37 @@ void Swap(ref T lhs, ref T rhs) where T : System.IComparable [Fact] public void Update_Inner_ParameterType_GenericMethod() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Swap(5,6); - } - - static void Swap(T lhs, T rhs) where T : System.IComparable - { - Console.WriteLine(""hello""); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - while (true) - { - Swap(null, null); - } - } - - static void Swap(T lhs, T rhs) where T : System.IComparable - { - Console.WriteLine(""hello""); - } -} -"; + var src1 = """ + class C + { + static void Main(string[] args) + { + Swap(5,6); + } + + static void Swap(T lhs, T rhs) where T : System.IComparable + { + Console.WriteLine("hello"); + } + } + """; + var src2 = """ + class C + { + static void Main(string[] args) + { + while (true) + { + Swap(null, null); + } + } + + static void Swap(T lhs, T rhs) where T : System.IComparable + { + Console.WriteLine("hello"); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -244,33 +248,34 @@ static void Swap(T lhs, T rhs) where T : System.IComparable [Fact] public void Update_Leaf_GenericMethod() { - var src1 = @" -class C -{ - static void Main() - { - Swap(5,6); - } - - static void Swap(T lhs, T rhs) where T : System.IComparable - { - Console.WriteLine(""hello""); - } -}"; - var src2 = @" -class C -{ - static void Main() - { - Swap(5,6); - } - - static void Swap(T lhs, T rhs) where T : System.IComparable - { - Console.WriteLine(""hello world!""); - } -} -"; + var src1 = """ + class C + { + static void Main() + { + Swap(5,6); + } + + static void Swap(T lhs, T rhs) where T : System.IComparable + { + Console.WriteLine("hello"); + } + } + """; + var src2 = """ + class C + { + static void Main() + { + Swap(5,6); + } + + static void Swap(T lhs, T rhs) where T : System.IComparable + { + Console.WriteLine("hello world!"); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -289,36 +294,38 @@ static void Swap(T lhs, T rhs) where T : System.IComparable [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/749458")] public void Update_Leaf_AsyncMethod() { - var src1 = @" -class Test -{ - static void Main(string[] args) - { - Test f = new Test(); - string result = f.WaitAsync().Result; - } - - public async Task WaitAsync() - { - await Task.Delay(1000); - return ""Done""; - } -}"; - var src2 = @" -class Test -{ - static void Main(string[] args) - { - Test f = new Test(); - string result = f.WaitAsync().Result; - } - - public async Task WaitAsync() - { - await Task.Delay(100); - return ""Done""; - } -}"; + var src1 = """ + class Test + { + static void Main(string[] args) + { + Test f = new Test(); + string result = f.WaitAsync().Result; + } + + public async Task WaitAsync() + { + await Task.Delay(1000); + return "Done"; + } + } + """; + var src2 = """ + class Test + { + static void Main(string[] args) + { + Test f = new Test(); + string result = f.WaitAsync().Result; + } + + public async Task WaitAsync() + { + await Task.Delay(100); + return "Done"; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -329,36 +336,38 @@ public async Task WaitAsync() [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/749440")] public void Update_Inner_AsyncMethod() { - var src1 = @" -class Test -{ - static void Main(string[] args) - { - Test f = new Test(); - string result = f.WaitAsync(5).Result; - } - - public async Task WaitAsync(int millis) - { - await Task.Delay(millis); - return ""Done""; - } -}"; - var src2 = @" -class Test -{ - static void Main(string[] args) - { - Test f = new Test(); - string result = f.WaitAsync(6).Result; - } - - public async Task WaitAsync(int millis) - { - await Task.Delay(millis); - return ""Done""; - } -}"; + var src1 = """ + class Test + { + static void Main(string[] args) + { + Test f = new Test(); + string result = f.WaitAsync(5).Result; + } + + public async Task WaitAsync(int millis) + { + await Task.Delay(millis); + return "Done"; + } + } + """; + var src2 = """ + class Test + { + static void Main(string[] args) + { + Test f = new Test(); + string result = f.WaitAsync(6).Result; + } + + public async Task WaitAsync(int millis) + { + await Task.Delay(millis); + return "Done"; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -369,42 +378,44 @@ public async Task WaitAsync(int millis) [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/749440")] public void Update_Initializer_MultipleVariables1() { - var src1 = @" -class Test -{ - static void Main(string[] args) - { - int a = F(), b = G(); - } - - public int F() - { - return 1; - } - - public int G() - { - return 2; - } -}"; - var src2 = @" -class Test -{ - static void Main(string[] args) - { - int a = G(), b = F(); - } - - public int F() - { - return 1; - } - - public int G() - { - return 2; - } -}"; + var src1 = """ + class Test + { + static void Main(string[] args) + { + int a = F(), b = G(); + } + + public int F() + { + return 1; + } + + public int G() + { + return 2; + } + } + """; + var src2 = """ + class Test + { + static void Main(string[] args) + { + int a = G(), b = F(); + } + + public int F() + { + return 1; + } + + public int G() + { + return 2; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -415,42 +426,44 @@ public int G() [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/749440")] public void Update_Initializer_MultipleVariables2() { - var src1 = @" -class Test -{ - static void Main(string[] args) - { - int a = F(), b = G(); - } - - public int F() - { - return 1; - } - - public int G() - { - return 2; - } -}"; - var src2 = @" -class Test -{ - static void Main(string[] args) - { - int a = G(), b = F(); - } - - public int F() - { - return 1; - } - - public int G() - { - return 2; - } -}"; + var src1 = """ + class Test + { + static void Main(string[] args) + { + int a = F(), b = G(); + } + + public int F() + { + return 1; + } + + public int G() + { + return 2; + } + } + """; + var src2 = """ + class Test + { + static void Main(string[] args) + { + int a = G(), b = F(); + } + + public int F() + { + return 1; + } + + public int G() + { + return 2; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -461,27 +474,28 @@ public int G() [Fact] public void MethodUpdateWithLocalVariables() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - int a = 1; - int b = 2; - System.Console.WriteLine(a + b); - } -} -"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - int b = 2; - int a = 1; - System.Console.WriteLine(a + b); - } -}"; + var src1 = """ + class C + { + static void Main(string[] args) + { + int a = 1; + int b = 2; + System.Console.WriteLine(a + b); + } + } + """; + var src2 = """ + class C + { + static void Main(string[] args) + { + int b = 2; + int a = 1; + System.Console.WriteLine(a + b); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -708,20 +722,20 @@ public void Property_ExpressionBodyToBlockBody3() [Fact] public void Property_ExpressionBodyToBlockBody_NonLeaf() { - var src1 = @" -class C -{ - int P => M(); - int M() { return 1; } -} -"; - var src2 = @" -class C -{ - int P { get { return M(); } } - int M() { return 1; } -} -"; + var src1 = """ + class C + { + int P => M(); + int M() { return 1; } + } + """; + var src2 = """ + class C + { + int P { get { return M(); } } + int M() { return 1; } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -732,20 +746,20 @@ class C [Fact] public void Property_ExpressionBody_NonLeaf() { - var src1 = @" -class C -{ - int P => M(); - int M() { return 1; } -} -"; - var src2 = @" -class C -{ - int P => M(); - int M() { return 2; } -} -"; + var src1 = """ + class C + { + int P => M(); + int M() { return 1; } + } + """; + var src2 = """ + class C + { + int P => M(); + int M() { return 2; } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -784,20 +798,20 @@ public void Property_BlockBodyToExpressionBody2() [Fact] public void Property_BlockBodyToExpressionBody_NonLeaf() { - var src1 = @" -class C -{ - int P { get { return M(); } } - int M() { return 1; } -} -"; - var src2 = @" -class C -{ - int P => M(); - int M() { return 1; } -} -"; + var src1 = """ + class C + { + int P { get { return M(); } } + int M() { return 1; } + } + """; + var src2 = """ + class C + { + int P => M(); + int M() { return 1; } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -870,20 +884,20 @@ public void Indexer_BlockBodyToExpressionBody2() [Fact] public void Indexer_ExpressionBody_NonLeaf() { - var src1 = @" -class C -{ - int this[int index] => M(); - int M() { return 1; } -} -"; - var src2 = @" -class C -{ - int this[int index] => M(); - int M() { return 2; } -} -"; + var src1 = """ + class C + { + int this[int index] => M(); + int M() { return 1; } + } + """; + var src2 = """ + class C + { + int this[int index] => M(); + int M() { return 2; } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -893,42 +907,44 @@ class C [Fact] public void Update_Leaf_Indexers1() { - var src1 = @" -class Test -{ - static void Main() - { - var c = new C(); - c[0] = 1; - } -} - -class C -{ - public T this[int i] - { - get => 0; - set { value = i; } - } -}"; - var src2 = @" -class Test -{ - static void Main() - { - var c = new C(); - c[0] = 1; - } -} - -class C -{ - public T this[int i] - { - get => 0; - set { value = i + 1; } - } -}"; + var src1 = """ + class Test + { + static void Main() + { + var c = new C(); + c[0] = 1; + } + } + + class C + { + public T this[int i] + { + get => 0; + set { value = i; } + } + } + """; + var src2 = """ + class Test + { + static void Main() + { + var c = new C(); + c[0] = 1; + } + } + + class C + { + public T this[int i] + { + get => 0; + set { value = i + 1; } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -944,48 +960,50 @@ public T this[int i] [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750244")] public void Update_Inner_Indexers_Setter() { - var src1 = @" -using System; -class Test -{ - static void Main(string[] args) - { - SampleCollection stringCollection = new SampleCollection(); - stringCollection[0] = ""hello""; - Console.WriteLine(stringCollection[0]); - } -} - -class SampleCollection -{ - private T[] arr = new T[100]; - public T this[int i] - { - get { return arr[i]; } - set { arr[i] = value; } - } -}"; - var src2 = @" -using System; -class Test -{ - static void Main(string[] args) - { - SampleCollection stringCollection = new SampleCollection(); - stringCollection[1] = ""hello""; - Console.WriteLine(stringCollection[0]); - } -} - -class SampleCollection -{ - private T[] arr = new T[100]; - public T this[int i] - { - get { return arr[i]; } - set { arr[i+1] = value; } - } -}"; + var src1 = """ + using System; + class Test + { + static void Main(string[] args) + { + SampleCollection stringCollection = new SampleCollection(); + stringCollection[0] = "hello"; + Console.WriteLine(stringCollection[0]); + } + } + + class SampleCollection + { + private T[] arr = new T[100]; + public T this[int i] + { + get { return arr[i]; } + set { arr[i] = value; } + } + } + """; + var src2 = """ + using System; + class Test + { + static void Main(string[] args) + { + SampleCollection stringCollection = new SampleCollection(); + stringCollection[1] = "hello"; + Console.WriteLine(stringCollection[0]); + } + } + + class SampleCollection + { + private T[] arr = new T[100]; + public T this[int i] + { + get { return arr[i]; } + set { arr[i+1] = value; } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -997,42 +1015,44 @@ public T this[int i] [Fact] public void Update_Leaf_Indexers_Getter() { - var src1 = @" -class Test -{ - static void Main() - { - var c = new C(); - Console.WriteLine(c[0]); - } -} - -class C -{ - public T this[int i] - { - get { return 0; } - set { } - } -}"; - var src2 = @" -class Test -{ - static void Main() - { - var c = new C(); - Console.WriteLine(c[0]); - } -} - -class C -{ - public T this[int i] - { - get { return 1; } - set { } - } -}"; + var src1 = """ + class Test + { + static void Main() + { + var c = new C(); + Console.WriteLine(c[0]); + } + } + + class C + { + public T this[int i] + { + get { return 0; } + set { } + } + } + """; + var src2 = """ + class Test + { + static void Main() + { + var c = new C(); + Console.WriteLine(c[0]); + } + } + + class C + { + public T this[int i] + { + get { return 1; } + set { } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1048,46 +1068,48 @@ public T this[int i] [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750244")] public void Update_Inner_Indexers2() { - var src1 = @" -class Test -{ - static void Main(string[] args) - { - SampleCollection stringCollection = new SampleCollection(); - stringCollection[0] = ""hello""; - Console.WriteLine(stringCollection[0]); - } -} - -class SampleCollection -{ - private T[] arr = new T[100]; - public T this[int i] - { - get { return arr[i]; } - set { arr[i] = value; } - } -}"; - var src2 = @" -class Test -{ - static void Main(string[] args) - { - SampleCollection stringCollection = new SampleCollection(); - stringCollection[0] = ""hello""; - Console.WriteLine(stringCollection[1]); - } -} - -class SampleCollection -{ - private T[] arr = new T[100]; - public T this[int i] - { - get { return arr[0]; } - set { arr[i] = value; } - } -}"; + var src1 = """ + class Test + { + static void Main(string[] args) + { + SampleCollection stringCollection = new SampleCollection(); + stringCollection[0] = "hello"; + Console.WriteLine(stringCollection[0]); + } + } + + class SampleCollection + { + private T[] arr = new T[100]; + public T this[int i] + { + get { return arr[i]; } + set { arr[i] = value; } + } + } + """; + var src2 = """ + class Test + { + static void Main(string[] args) + { + SampleCollection stringCollection = new SampleCollection(); + stringCollection[0] = "hello"; + Console.WriteLine(stringCollection[1]); + } + } + + class SampleCollection + { + private T[] arr = new T[100]; + public T this[int i] + { + get { return arr[0]; } + set { arr[i] = value; } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1099,42 +1121,44 @@ public T this[int i] [Fact] public void Deleted_Leaf_Indexers_Setter() { - var src1 = @" -class Test -{ - static void Main() - { - var c = new C(); - c[0] = 1; - } -} - -class C -{ - public T this[int i] - { - get => 0; - set { throw null; } - } -}"; - var src2 = @" -class Test -{ - static void Main() - { - var c = new C(); - c[0] = 1; - } -} - -class C -{ - public T this[int i] - { - get => 0; - set { } - } -}"; + var src1 = """ + class Test + { + static void Main() + { + var c = new C(); + c[0] = 1; + } + } + + class C + { + public T this[int i] + { + get => 0; + set { throw null; } + } + } + """; + var src2 = """ + class Test + { + static void Main() + { + var c = new C(); + c[0] = 1; + } + } + + class C + { + public T this[int i] + { + get => 0; + set { } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1150,45 +1174,47 @@ public T this[int i] [Fact] public void Deleted_Inner_Indexers_Setter() { - var src1 = @" -class Test -{ - static void Main(string[] args) - { - SampleCollection stringCollection = new SampleCollection(); - stringCollection[0] = ""hello""; - Console.WriteLine(stringCollection[0]); - } -} - -class SampleCollection -{ - private T[] arr = new T[100]; - public T this[int i] - { - get { return arr[i]; } - set { arr[i] = value; } - } -}"; - var src2 = @" -class Test -{ - static void Main(string[] args) - { - SampleCollection stringCollection = new SampleCollection(); - Console.WriteLine(stringCollection[0]); - } -} - -class SampleCollection -{ - private T[] arr = new T[100]; - public T this[int i] - { - get { return arr[i]; } - set { arr[i] = value; } - } -}"; + var src1 = """ + class Test + { + static void Main(string[] args) + { + SampleCollection stringCollection = new SampleCollection(); + stringCollection[0] = "hello"; + Console.WriteLine(stringCollection[0]); + } + } + + class SampleCollection + { + private T[] arr = new T[100]; + public T this[int i] + { + get { return arr[i]; } + set { arr[i] = value; } + } + } + """; + var src2 = """ + class Test + { + static void Main(string[] args) + { + SampleCollection stringCollection = new SampleCollection(); + Console.WriteLine(stringCollection[0]); + } + } + + class SampleCollection + { + private T[] arr = new T[100]; + public T this[int i] + { + get { return arr[i]; } + set { arr[i] = value; } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1199,42 +1225,44 @@ public T this[int i] [Fact] public void Deleted_Leaf_Indexers_Getter() { - var src1 = @" -class Test -{ - static void Main(string[] args) - { - var c = new C(); - Console.WriteLine(c[0]); - } -} - -class C -{ - public T this[int i] - { - get { return 1; } - set { } - } -}"; - var src2 = @" -class Test -{ - static void Main(string[] args) - { - var c = new C(); - Console.WriteLine(c[0]); - } -} - -class C -{ - public T this[int i] - { - get { } - set { } - } -}"; + var src1 = """ + class Test + { + static void Main(string[] args) + { + var c = new C(); + Console.WriteLine(c[0]); + } + } + + class C + { + public T this[int i] + { + get { return 1; } + set { } + } + } + """; + var src2 = """ + class Test + { + static void Main(string[] args) + { + var c = new C(); + Console.WriteLine(c[0]); + } + } + + class C + { + public T this[int i] + { + get { } + set { } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1250,45 +1278,47 @@ public T this[int i] [Fact] public void Deleted_Inner_Indexers_Getter() { - var src1 = @" -class Test -{ - static void Main(string[] args) - { - SampleCollection stringCollection = new SampleCollection(); - stringCollection[0] = ""hello""; - Console.WriteLine(stringCollection[0]); - } -} - -class SampleCollection -{ - private T[] arr = new T[100]; - public T this[int i] - { - get { return arr[i]; } - set { arr[i] = value; } - } -}"; - var src2 = @" -class Test -{ - static void Main(string[] args) - { - SampleCollection stringCollection = new SampleCollection(); - stringCollection[0] = ""hello""; - } -} - -class SampleCollection -{ - private T[] arr = new T[100]; - public T this[int i] - { - get { return arr[i]; } - set { arr[i] = value; } - } -}"; + var src1 = """ + class Test + { + static void Main(string[] args) + { + SampleCollection stringCollection = new SampleCollection(); + stringCollection[0] = "hello"; + Console.WriteLine(stringCollection[0]); + } + } + + class SampleCollection + { + private T[] arr = new T[100]; + public T this[int i] + { + get { return arr[i]; } + set { arr[i] = value; } + } + } + """; + var src2 = """ + class Test + { + static void Main(string[] args) + { + SampleCollection stringCollection = new SampleCollection(); + stringCollection[0] = "hello"; + } + } + + class SampleCollection + { + private T[] arr = new T[100]; + public T this[int i] + { + get { return arr[i]; } + set { arr[i] = value; } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1351,34 +1381,36 @@ public void Operator_BlockBodyToExpressionBody2() [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754274")] public void Update_Leaf_OverloadedOperator() { - var src1 = @" -class Test -{ - static void Main(string[] args) - { - Test t1 = new Test(5); - Test t2 = new Test(5); - Test t3 = t1 + t2; - } - public static Test operator +(Test t1, Test t2) - { - return new Test(t1.a + t2.a); - } -}"; - var src2 = @" -class Test -{ - static void Main(string[] args) - { - Test t1 = new Test(5); - Test t2 = new Test(5); - Test t3 = t1 + t2; - } - public static Test operator +(Test t1, Test t2) - { - return new Test(t1.a + 2 * t2.a); - } -}"; + var src1 = """ + class Test + { + static void Main(string[] args) + { + Test t1 = new Test(5); + Test t2 = new Test(5); + Test t3 = t1 + t2; + } + public static Test operator +(Test t1, Test t2) + { + return new Test(t1.a + t2.a); + } + } + """; + var src2 = """ + class Test + { + static void Main(string[] args) + { + Test t1 = new Test(5); + Test t2 = new Test(5); + Test t3 = t1 + t2; + } + public static Test operator +(Test t1, Test t2) + { + return new Test(t1.a + 2 * t2.a); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1388,42 +1420,44 @@ static void Main(string[] args) [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754274")] public void Update_Inner_OverloadedOperator() { - var src1 = @" -class Test -{ - static void Main(string[] args) - { - Test t1 = new Test(5); - Test t2 = new Test(5); - Test t3 = t1 + t2; - } - public static Test operator +(Test t1, Test t2) - { - return new Test(t1.a + t2.a); - } - public static Test operator *(Test t1, Test t2) - { - return new Test(t1.a * t2.a); - } -}"; - var src2 = @" -class Test -{ - static void Main(string[] args) - { - Test t1 = new Test(5); - Test t2 = new Test(5); - Test t3 = t1 * t2; - } - public static Test operator +(Test t1, Test t2) - { - return new Test(t1.a + t2.a); - } - public static Test operator *(Test t1, Test t2) - { - return new Test(t1.a * t2.a); - } -}"; + var src1 = """ + class Test + { + static void Main(string[] args) + { + Test t1 = new Test(5); + Test t2 = new Test(5); + Test t3 = t1 + t2; + } + public static Test operator +(Test t1, Test t2) + { + return new Test(t1.a + t2.a); + } + public static Test operator *(Test t1, Test t2) + { + return new Test(t1.a * t2.a); + } + } + """; + var src2 = """ + class Test + { + static void Main(string[] args) + { + Test t1 = new Test(5); + Test t2 = new Test(5); + Test t3 = t1 * t2; + } + public static Test operator +(Test t1, Test t2) + { + return new Test(t1.a + t2.a); + } + public static Test operator *(Test t1, Test t2) + { + return new Test(t1.a * t2.a); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); diff --git a/src/Features/CSharpTest/EditAndContinue/ActiveStatementTests.cs b/src/Features/CSharpTest/EditAndContinue/ActiveStatementTests.cs index ac41ce3687d1a..67e592775454f 100644 --- a/src/Features/CSharpTest/EditAndContinue/ActiveStatementTests.cs +++ b/src/Features/CSharpTest/EditAndContinue/ActiveStatementTests.cs @@ -26,36 +26,40 @@ public sealed class ActiveStatementTests : EditingTestBase [Fact] public void Update_Inner() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Goo(1); - } + var src1 = """ - static void Goo(int a) - { - Console.WriteLine(a); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - while (true) - { - Goo(2); - } - } + class C + { + static void Main(string[] args) + { + Goo(1); + } - static void Goo(int a) - { - Console.WriteLine(a); - } -} -"; + static void Goo(int a) + { + Console.WriteLine(a); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + while (true) + { + Goo(2); + } + } + + static void Goo(int a) + { + Console.WriteLine(a); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -66,33 +70,37 @@ static void Goo(int a) [Fact] public void Update_Inner_NewCommentAtEndOfActiveStatement() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Goo(1); - } + var src1 = """ - static void Goo(int a) - { - Console.WriteLine(a); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - Goo(1);// - } + class C + { + static void Main(string[] args) + { + Goo(1); + } - static void Goo(int a) - { - Console.WriteLine(a); - } -} -"; + static void Goo(int a) + { + Console.WriteLine(a); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + Goo(1);// + } + + static void Goo(int a) + { + Console.WriteLine(a); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -105,38 +113,42 @@ static void Goo(int a) [Fact] public void Update_Inner_Reloadable() { - var src1 = ReloadableAttributeSrc + @" -[CreateNewOnMetadataUpdate] -class C -{ - static void F() - { - Goo(1); - } + var src1 = ReloadableAttributeSrc + """ - static void Goo(int a) - { - Console.WriteLine(a); - } -}"; - var src2 = ReloadableAttributeSrc + @" -[CreateNewOnMetadataUpdate] -class C -{ - static void F() - { - while (true) - { - Goo(2); - } - } + [CreateNewOnMetadataUpdate] + class C + { + static void F() + { + Goo(1); + } - static void Goo(int a) - { - Console.WriteLine(a); - } -} -"; + static void Goo(int a) + { + Console.WriteLine(a); + } + } + """; + var src2 = ReloadableAttributeSrc + """ + + [CreateNewOnMetadataUpdate] + class C + { + static void F() + { + while (true) + { + Goo(2); + } + } + + static void Goo(int a) + { + Console.WriteLine(a); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -147,36 +159,40 @@ static void Goo(int a) [Fact] public void Update_Leaf() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Goo(1); - } + var src1 = """ - static void Goo(int a) - { - Console.WriteLine(a); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - while (true) - { - Goo(1); - } - } + class C + { + static void Main(string[] args) + { + Goo(1); + } - static void Goo(int a) - { - Console.WriteLine(a + 1); - } -} -"; + static void Goo(int a) + { + Console.WriteLine(a); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + while (true) + { + Goo(1); + } + } + + static void Goo(int a) + { + Console.WriteLine(a + 1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -186,33 +202,37 @@ static void Goo(int a) [Fact] public void Update_Leaf_NewCommentAtEndOfActiveStatement() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Goo(1); - } + var src1 = """ - static void Goo(int a) - { - Console.WriteLine(a); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - Goo(1); - } + class C + { + static void Main(string[] args) + { + Goo(1); + } - static void Goo(int a) - { - Console.WriteLine(a);// - } -} -"; + static void Goo(int a) + { + Console.WriteLine(a); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + Goo(1); + } + + static void Goo(int a) + { + Console.WriteLine(a);// + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -225,38 +245,42 @@ static void Goo(int a) [Fact] public void Update_Leaf_Reloadable() { - var src1 = ReloadableAttributeSrc + @" -[CreateNewOnMetadataUpdate] -class C -{ - static void Main(string[] args) - { - Goo(1); - } + var src1 = ReloadableAttributeSrc + """ - static void Goo(int a) - { - Console.WriteLine(a); - } -}"; - var src2 = ReloadableAttributeSrc + @" -[CreateNewOnMetadataUpdate] -class C -{ - static void Main(string[] args) - { - while (true) - { - Goo(1); - } - } + [CreateNewOnMetadataUpdate] + class C + { + static void Main(string[] args) + { + Goo(1); + } - static void Goo(int a) - { - Console.WriteLine(a + 1); - } -} -"; + static void Goo(int a) + { + Console.WriteLine(a); + } + } + """; + var src2 = ReloadableAttributeSrc + """ + + [CreateNewOnMetadataUpdate] + class C + { + static void Main(string[] args) + { + while (true) + { + Goo(1); + } + } + + static void Goo(int a) + { + Console.WriteLine(a + 1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -271,27 +295,31 @@ static void Goo(int a) [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846588")] public void Update_Leaf_Block() { - var src1 = @" -class C : System.IDisposable -{ - public void Dispose() {} + var src1 = """ - static void Main(string[] args) - { - using (C x = null) {} - } -}"; - var src2 = @" -class C : System.IDisposable -{ - public void Dispose() {} + class C : System.IDisposable + { + public void Dispose() {} - static void Main(string[] args) - { - using (C x = new C()) {} - } -} -"; + static void Main(string[] args) + { + using (C x = null) {} + } + } + """; + var src2 = """ + + class C : System.IDisposable + { + public void Dispose() {} + + static void Main(string[] args) + { + using (C x = new C()) {} + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -305,160 +333,168 @@ static void Main(string[] args) [Fact] public void Delete_Inner() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Goo(1); - } + var src1 = """ - static void Goo(int a) - { - Console.WriteLine(a); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - while (true) - { - } - } + class C + { + static void Main(string[] args) + { + Goo(1); + } - static void Goo(int a) - { - Console.WriteLine(a); - } -} -"; - var edits = GetTopEdits(src1, src2); - var active = GetActiveStatements(src1, src2); + static void Goo(int a) + { + Console.WriteLine(a); + } + } + """; + var src2 = """ - edits.VerifySemanticDiagnostics(active, - Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); + class C + { + static void Main(string[] args) + { + while (true) + { + } + } + + static void Goo(int a) + { + Console.WriteLine(a); + } + } + + """; + var edits = GetTopEdits(src1, src2); + var active = GetActiveStatements(src1, src2); + + edits.VerifySemanticDiagnostics(active, + Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } // TODO (tomat): considering a change [Fact] public void Delete_Inner_MultipleParents() { - var src1 = @" -class C : IDisposable -{ - unsafe static void Main(string[] args) - { - { - Goo(1); - } + var src1 = """ - if (true) - { - Goo(2); - } - else - { - Goo(3); - } + class C : IDisposable + { + unsafe static void Main(string[] args) + { + { + Goo(1); + } - int x = 1; - switch (x) - { - case 1: - case 2: - Goo(4); - break; - - default: - Goo(5); - break; - } + if (true) + { + Goo(2); + } + else + { + Goo(3); + } - checked - { - Goo(4); - } + int x = 1; + switch (x) + { + case 1: + case 2: + Goo(4); + break; + + default: + Goo(5); + break; + } - unchecked - { - Goo(7); - } + checked + { + Goo(4); + } - while (true) Goo(8); - - do Goo(9); while (true); + unchecked + { + Goo(7); + } - for (int i = 0; i < 10; i++) Goo(10); + while (true) Goo(8); + + do Goo(9); while (true); - foreach (var i in new[] { 1, 2}) Goo(11); + for (int i = 0; i < 10; i++) Goo(10); - using (var z = new C()) Goo(12); + foreach (var i in new[] { 1, 2}) Goo(11); - fixed (char* p = ""s"") Goo(13); + using (var z = new C()) Goo(12); - label: Goo(14); - } + fixed (char* p = "s") Goo(13); - static void Goo(int a) - { - Console.WriteLine(a); - } -}"; - var src2 = @" -class C : IDisposable -{ - unsafe static void Main(string[] args) - { - { - } + label: Goo(14); + } - if (true) - { } - else - { } + static void Goo(int a) + { + Console.WriteLine(a); + } + } + """; + var src2 = """ - int x = 1; - switch (x) - { - case 1: - case 2: - break; + class C : IDisposable + { + unsafe static void Main(string[] args) + { + { + } - default: - break; - } + if (true) + { } + else + { } - checked - { - } + int x = 1; + switch (x) + { + case 1: + case 2: + break; - unchecked - { - } + default: + break; + } - while (true) { } - - do { } while (true); + checked + { + } - for (int i = 0; i < 10; i++) { } + unchecked + { + } - foreach (var i in new[] { 1, 2 }) { } + while (true) { } + + do { } while (true); - using (var z = new C()) { } + for (int i = 0; i < 10; i++) { } - fixed (char* p = ""s"") { } + foreach (var i in new[] { 1, 2 }) { } - label: { } - } + using (var z = new C()) { } - static void Goo(int a) - { - Console.WriteLine(a); - } -} -"; + fixed (char* p = "s") { } + + label: { } + } + + static void Goo(int a) + { + Console.WriteLine(a); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -482,32 +518,36 @@ static void Goo(int a) [Fact] public void Delete_Leaf1() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Goo(1); - } + var src1 = """ - static void Goo(int a) - { - Console.WriteLine(a); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - Goo(1); - } + class C + { + static void Main(string[] args) + { + Goo(1); + } - static void Goo(int a) - { - } -} -"; + static void Goo(int a) + { + Console.WriteLine(a); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + Goo(1); + } + + static void Goo(int a) + { + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -517,29 +557,33 @@ static void Goo(int a) [Fact] public void Delete_Leaf2() { - var src1 = @" -class C -{ - static void Goo(int a) - { - Console.WriteLine(1); - Console.WriteLine(2); - Console.WriteLine(3); - Console.WriteLine(4); - } -}"; - var src2 = @" -class C -{ - static void Goo(int a) - { - Console.WriteLine(1); - Console.WriteLine(2); + var src1 = """ - Console.WriteLine(4); - } -} -"; + class C + { + static void Goo(int a) + { + Console.WriteLine(1); + Console.WriteLine(2); + Console.WriteLine(3); + Console.WriteLine(4); + } + } + """; + var src2 = """ + + class C + { + static void Goo(int a) + { + Console.WriteLine(1); + Console.WriteLine(2); + + Console.WriteLine(4); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -549,44 +593,48 @@ static void Goo(int a) [Fact] public void Delete_Leaf_InTry() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Goo(1); - } + var src1 = """ - static void Goo(int a) - { - try - { - Console.WriteLine(a); - } - catch - { - } - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - Goo(1); - } + class C + { + static void Main(string[] args) + { + Goo(1); + } - static void Goo(int a) - { - try - { - } - catch - { - } - } -} -"; + static void Goo(int a) + { + try + { + Console.WriteLine(a); + } + catch + { + } + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + Goo(1); + } + + static void Goo(int a) + { + try + { + } + catch + { + } + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -596,56 +644,60 @@ static void Goo(int a) [Fact] public void Delete_Leaf_InTry2() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Goo(1); - } + var src1 = """ - static void Goo(int a) - { - try - { - try - { - Console.WriteLine(a); - } - catch + class C { + static void Main(string[] args) + { + Goo(1); + } + + static void Goo(int a) + { + try + { + try + { + Console.WriteLine(a); + } + catch + { + } + } + catch + { + } + } } - } - catch - { - } - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - Goo(1); - } + """; + var src2 = """ - static void Goo(int a) - { - try - { - try - { - } - catch + class C { + static void Main(string[] args) + { + Goo(1); + } + + static void Goo(int a) + { + try + { + try + { + } + catch + { + } + } + catch + { + } + } } - } - catch - { - } - } -} -"; + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -655,33 +707,37 @@ static void Goo(int a) [Fact] public void Delete_Inner_CommentActiveStatement() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Goo(1); - } + var src1 = """ - static void Goo(int a) - { - Console.WriteLine(a); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - //Goo(1); - } + class C + { + static void Main(string[] args) + { + Goo(1); + } - static void Goo(int a) - { - Console.WriteLine(a); - } -} -"; + static void Goo(int a) + { + Console.WriteLine(a); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + //Goo(1); + } + + static void Goo(int a) + { + Console.WriteLine(a); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -692,33 +748,37 @@ static void Goo(int a) [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755959")] public void Delete_Leaf_CommentActiveStatement() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Goo(1); - } + var src1 = """ - static void Goo(int a) - { - Console.WriteLine(a); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - Goo(1); - } + class C + { + static void Main(string[] args) + { + Goo(1); + } - static void Goo(int a) - { - //Console.WriteLine(a); - } -} -"; + static void Goo(int a) + { + Console.WriteLine(a); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + Goo(1); + } + + static void Goo(int a) + { + //Console.WriteLine(a); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -728,17 +788,19 @@ static void Goo(int a) [Fact] public void Delete_Entire_Namespace() { - var src1 = @" -namespace N -{ - class C - { - static void F() - { - Console.WriteLine(1); - } - } -}"; + var src1 = """ + + namespace N + { + class C + { + static void F() + { + Console.WriteLine(1); + } + } + } + """; var src2 = @""; var edits = GetTopEdits(src1, src2); @@ -752,17 +814,19 @@ static void F() [Fact] public void Delete_Entire_Type() { - var src1 = @" -namespace N -{ - class C - { - static void F() - { - Console.WriteLine(1); - } - } -}"; + var src1 = """ + + namespace N + { + class C + { + static void F() + { + Console.WriteLine(1); + } + } + } + """; var src2 = @"namespace N;"; var edits = GetTopEdits(src1, src2); @@ -776,25 +840,29 @@ static void F() [Fact] public void Delete_Entire_Method() { - var src1 = @" -namespace N -{ - class C - { - static void F() - { - Console.WriteLine(1); - } - } -}"; - var src2 = @" -namespace N -{ - class C - { - } -} -"; + var src1 = """ + + namespace N + { + class C + { + static void F() + { + Console.WriteLine(1); + } + } + } + """; + var src2 = """ + + namespace N + { + class C + { + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -946,44 +1014,48 @@ public void Return_TypeChange_RefReadonly() [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/740949")] public void Updated_Inner_Constructor() { - var src1 = @" -using System; + var src1 = """ -class Program -{ - static void Main(string[] args) - { - Goo f = new Goo(5); - } -} + using System; -class Goo -{ - int value; - public Goo(int a) - { - this.value = a; - } -}"; - var src2 = @" -using System; + class Program + { + static void Main(string[] args) + { + Goo f = new Goo(5); + } + } -class Program -{ - static void Main(string[] args) - { - Goo f = new Goo(5*2); - } -} + class Goo + { + int value; + public Goo(int a) + { + this.value = a; + } + } + """; + var src2 = """ -class Goo -{ - int value; - public Goo(int a) - { - this.value = a; - } -}"; + using System; + + class Program + { + static void Main(string[] args) + { + Goo f = new Goo(5*2); + } + } + + class Goo + { + int value; + public Goo(int a) + { + this.value = a; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -994,44 +1066,48 @@ public Goo(int a) [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/741249")] public void Updated_Leaf_Constructor() { - var src1 = @" -using System; + var src1 = """ -class Program -{ - static void Main(string[] args) - { - Goo f = new Goo(5); - } -} + using System; -class Goo -{ - int value; - public Goo(int a) - { - this.value = a; - } -}"; - var src2 = @" -using System; + class Program + { + static void Main(string[] args) + { + Goo f = new Goo(5); + } + } -class Program -{ - static void Main(string[] args) - { - Goo f = new Goo(5); - } -} + class Goo + { + int value; + public Goo(int a) + { + this.value = a; + } + } + """; + var src2 = """ -class Goo -{ - int value; - public Goo(int a) - { - this.value = a*2; - } -}"; + using System; + + class Program + { + static void Main(string[] args) + { + Goo f = new Goo(5); + } + } + + class Goo + { + int value; + public Goo(int a) + { + this.value = a*2; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1041,44 +1117,48 @@ public Goo(int a) [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] public void Updated_Leaf_Constructor_Parameter() { - var src1 = @" -using System; + var src1 = """ -class Program -{ - static void Main(string[] args) - { - Goo f = new Goo(5); - } -} + using System; -class Goo -{ - int value; - public Goo(int a) - { - this.value = a; - } -}"; - var src2 = @" -using System; + class Program + { + static void Main(string[] args) + { + Goo f = new Goo(5); + } + } -class Program -{ - static void Main(string[] args) - { - Goo f = new Goo(5); - } -} + class Goo + { + int value; + public Goo(int a) + { + this.value = a; + } + } + """; + var src2 = """ -class Goo -{ - int value; - public Goo(int b) - { - this.value = b; - } -}"; + using System; + + class Program + { + static void Main(string[] args) + { + Goo f = new Goo(5); + } + } + + class Goo + { + int value; + public Goo(int b) + { + this.value = b; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1093,94 +1173,102 @@ class Goo [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] public void Updated_Leaf_Constructor_Parameter_DefaultValue() { - var src1 = @" -using System; + var src1 = """ -class Program -{ - static void Main(string[] args) - { - Goo f = new Goo(5); - } -} + using System; -class Goo -{ - int value; - public Goo(int a = 5) - { - this.value = a; - } -}"; - var src2 = @" -using System; + class Program + { + static void Main(string[] args) + { + Goo f = new Goo(5); + } + } -class Program -{ - static void Main(string[] args) - { - Goo f = new Goo(5); - } -} + class Goo + { + int value; + public Goo(int a = 5) + { + this.value = a; + } + } + """; + var src2 = """ -class Goo -{ - int value; - public Goo(int a = 42) - { - this.value = a; - } -}"; - var edits = GetTopEdits(src1, src2); - var active = GetActiveStatements(src1, src2); + using System; - edits.VerifySemanticDiagnostics(active, - Diagnostic(RudeEditKind.InitializerUpdate, "int a = 42", FeaturesResources.parameter)); + class Program + { + static void Main(string[] args) + { + Goo f = new Goo(5); + } + } + + class Goo + { + int value; + public Goo(int a = 42) + { + this.value = a; + } + } + """; + var edits = GetTopEdits(src1, src2); + var active = GetActiveStatements(src1, src2); + + edits.VerifySemanticDiagnostics(active, + Diagnostic(RudeEditKind.InitializerUpdate, "int a = 42", FeaturesResources.parameter)); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] public void Updated_Leaf_ConstructorChaining1() { - var src1 = @" -using System; + var src1 = """ -class Test -{ - static void Main(string[] args) - { - B b = new B(2, 3); - } -} -class B : A -{ - public B(int x, int y) : base(x + y, x - y) { } -} -class A -{ - public A(int x, int y) : this(5 + x, y, 0) { } + using System; - public A(int x, int y, int z) { } -}"; - var src2 = @" -using System; + class Test + { + static void Main(string[] args) + { + B b = new B(2, 3); + } + } + class B : A + { + public B(int x, int y) : base(x + y, x - y) { } + } + class A + { + public A(int x, int y) : this(5 + x, y, 0) { } -class Test -{ - static void Main(string[] args) - { - B b = new B(2, 3); - } -} -class B : A -{ - public B(int x, int y) : base(x + y + 5, x - y) { } -} -class A -{ - public A(int x, int y) : this(x, y, 0) { } + public A(int x, int y, int z) { } + } + """; + var src2 = """ + + using System; + + class Test + { + static void Main(string[] args) + { + B b = new B(2, 3); + } + } + class B : A + { + public B(int x, int y) : base(x + y + 5, x - y) { } + } + class A + { + public A(int x, int y) : this(x, y, 0) { } - public A(int x, int y, int z) { } -}"; + public A(int x, int y, int z) { } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1190,46 +1278,50 @@ public A(int x, int y, int z) { } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] public void Updated_Leaf_ConstructorChaining2() { - var src1 = @" -using System; + var src1 = """ -class Test -{ - static void Main(string[] args) - { - B b = new B(2, 3); - } -} -class B : A -{ - public B(int x, int y) : base(x + y, x - y) { } -} -class A -{ - public A(int x, int y) : this(x, y, 0) { } + using System; - public A(int x, int y, int z) { } -}"; - var src2 = @" -using System; + class Test + { + static void Main(string[] args) + { + B b = new B(2, 3); + } + } + class B : A + { + public B(int x, int y) : base(x + y, x - y) { } + } + class A + { + public A(int x, int y) : this(x, y, 0) { } -class Test -{ - static void Main(string[] args) - { - B b = new B(2, 3); - } -} -class B : A -{ - public B(int x, int y) : base(x + y, x - y) { } -} -class A -{ - public A(int x, int y) : this(5 + x, y, 0) { } + public A(int x, int y, int z) { } + } + """; + var src2 = """ + + using System; + + class Test + { + static void Main(string[] args) + { + B b = new B(2, 3); + } + } + class B : A + { + public B(int x, int y) : base(x + y, x - y) { } + } + class A + { + public A(int x, int y) : this(5 + x, y, 0) { } - public A(int x, int y, int z) { } -}"; + public A(int x, int y, int z) { } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1239,30 +1331,34 @@ public A(int x, int y, int z) { } [Fact] public void Constructor_Instance_ImplicitInitializer() { - var src1 = @" -class C -{ - int a = 5; + var src1 = """ - public C(int a) { } + class C + { + int a = 5; - static void Main(string[] args) - { - C c = new C(3); - } -}"; - var src2 = @" -class C -{ - int a = 42; + public C(int a) { } + + static void Main(string[] args) + { + C c = new C(3); + } + } + """; + var src2 = """ - public C(int a) { } + class C + { + int a = 42; - static void Main(string[] args) - { - C c = new C(3); - } -}"; + public C(int a) { } + + static void Main(string[] args) + { + C c = new C(3); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1272,16 +1368,20 @@ static void Main(string[] args) [Fact] public void Constructor_Instance_ExplicitInitializer_Update_Subexpression() { - var src1 = @" -class C -{ - public C(int a) : base(a switch { 1 => 1, _ => 2 }) {} -}"; - var src2 = @" -class C -{ - public C(int a) : base(1) {} -}"; + var src1 = """ + + class C + { + public C(int a) : base(a switch { 1 => 1, _ => 2 }) {} + } + """; + var src2 = """ + + class C + { + public C(int a) : base(1) {} + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1291,54 +1391,58 @@ public C(int a) : base(1) {} [Fact] public void Constructor_Instance_ExplicitInitializer_Update_Internal() { - var src1 = @" -class D -{ - public D(int d) {} -} + var src1 = """ -class C : D -{ - int a = 5; + class D + { + public D(int d) {} + } - public C(int a) : this(true) { } + class C : D + { + int a = 5; - public C(bool b) : base(F()) {} + public C(int a) : this(true) { } - static int F() - { - return 1; - } + public C(bool b) : base(F()) {} - static void Main(string[] args) - { - C c = new C(3); - } -}"; - var src2 = @" -class D -{ - public D(int d) {} -} + static int F() + { + return 1; + } -class C : D -{ - int a = 5; + static void Main(string[] args) + { + C c = new C(3); + } + } + """; + var src2 = """ - public C(int a) : this(false) { } + class D + { + public D(int d) {} + } - public C(bool b) : base(F()) {} + class C : D + { + int a = 5; - static int F() - { - return 1; - } + public C(int a) : this(false) { } - static void Main(string[] args) - { - C c = new C(3); - } -}"; + public C(bool b) : base(F()) {} + + static int F() + { + return 1; + } + + static void Main(string[] args) + { + C c = new C(3); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1349,36 +1453,40 @@ static void Main(string[] args) [Fact] public void Constructor_Instance_ExplicitInitializer_Update_Leaf() { - var src1 = @" -class D -{ - public D(int d) { } -} + var src1 = """ -class C : D -{ - public C() : base(1) {} + class D + { + public D(int d) { } + } - static void Main(string[] args) - { - C c = new C(); - } -}"; - var src2 = @" -class D -{ - public D(int d) { } -} + class C : D + { + public C() : base(1) {} -class C : D -{ - public C() : base(2) {} + static void Main(string[] args) + { + C c = new C(); + } + } + """; + var src2 = """ - static void Main(string[] args) - { - C c = new C(); - } -}"; + class D + { + public D(int d) { } + } + + class C : D + { + public C() : base(2) {} + + static void Main(string[] args) + { + C c = new C(); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1388,38 +1496,42 @@ static void Main(string[] args) [Fact] public void Constructor_Instance_ImplicitInitializer_Update_ToExplicit_Leaf() { - var src1 = @" -class D -{ - public D() { } - public D(int d) { } -} + var src1 = """ -class C : D -{ - public C() {} + class D + { + public D() { } + public D(int d) { } + } - static void Main(string[] args) - { - C c = new C(); - } -}"; - var src2 = @" -class D -{ - public D() { } - public D(int d) { } -} + class C : D + { + public C() {} -class C : D -{ - public C() : base(2) {} + static void Main(string[] args) + { + C c = new C(); + } + } + """; + var src2 = """ - static void Main(string[] args) - { - C c = new C(); - } -}"; + class D + { + public D() { } + public D(int d) { } + } + + class C : D + { + public C() : base(2) {} + + static void Main(string[] args) + { + C c = new C(); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1429,26 +1541,30 @@ static void Main(string[] args) [Fact] public void Constructor_Instance_ImplicitInitializer_Update_ToExplicit_Internal() { - var src1 = @" -class D -{ - public D(int d) { } -} + var src1 = """ -class C : D -{ - public C() {} -}"; - var src2 = @" -class D -{ - public D(int d) { } -} + class D + { + public D(int d) { } + } -class C : D -{ - public C() : base(1) {} -}"; + class C : D + { + public C() {} + } + """; + var src2 = """ + + class D + { + public D(int d) { } + } + + class C : D + { + public C() : base(1) {} + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1459,46 +1575,50 @@ public C() : base(1) {} [Fact] public void Constructor_Instance_ExplicitInitializer_Update_ToImplicit_Internal() { - var src1 = @" -class D -{ - public D(int d) {} -} + var src1 = """ -class C : D -{ - public C() : base(F()) {} + class D + { + public D(int d) {} + } - static int F() - { - return 1; - } + class C : D + { + public C() : base(F()) {} - static void Main(string[] args) - { - C c = new C(); - } -}"; - var src2 = @" -class D -{ - public D(int d) {} -} + static int F() + { + return 1; + } -class C : D -{ - public C() {} + static void Main(string[] args) + { + C c = new C(); + } + } + """; + var src2 = """ - static int F() - { - return 1; - } + class D + { + public D(int d) {} + } - static void Main(string[] args) - { - C c = new C(); - } -}"; + class C : D + { + public C() {} + + static int F() + { + return 1; + } + + static void Main(string[] args) + { + C c = new C(); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1509,38 +1629,42 @@ static void Main(string[] args) [Fact] public void Constructor_Instance_ExplicitInitializer_Update_ToImplicit_Leaf() { - var src1 = @" -class D -{ - public D() { } - public D(int d) { } -} + var src1 = """ -class C : D -{ - public C() : base(2) {} + class D + { + public D() { } + public D(int d) { } + } - static void Main(string[] args) - { - C c = new C(); - } -}"; - var src2 = @" -class D -{ - public D() { } - public D(int d) { } -} + class C : D + { + public C() : base(2) {} -class C : D -{ - public C() {} + static void Main(string[] args) + { + C c = new C(); + } + } + """; + var src2 = """ - static void Main(string[] args) - { - C c = new C(); - } -}"; + class D + { + public D() { } + public D(int d) { } + } + + class C : D + { + public C() {} + + static void Main(string[] args) + { + C c = new C(); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1550,16 +1674,20 @@ static void Main(string[] args) [Fact] public void Constructor_Instance_ExplicitInitializer_WithLambda_Update1() { - var src1 = @" -class C -{ - public C() : this((a, b) => { Console.WriteLine(a + b); }) { } -}"; - var src2 = @" -class C -{ - public C() : base((a, b) => { Console.WriteLine(a - b); }) { } -}"; + var src1 = """ + + class C + { + public C() : this((a, b) => { Console.WriteLine(a + b); }) { } + } + """; + var src2 = """ + + class C + { + public C() : base((a, b) => { Console.WriteLine(a - b); }) { } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1569,16 +1697,20 @@ class C [Fact] public void Constructor_Instance_ExplicitInitializer_WithLambda_Update2() { - var src1 = @" -class C -{ - public C() : this((a, b) => { Console.WriteLine(a + b); }) { Console.WriteLine(1); } -}"; - var src2 = @" -class C -{ - public C() : this((a, b) => { Console.WriteLine(a + b); }) { Console.WriteLine(2); } -}"; + var src1 = """ + + class C + { + public C() : this((a, b) => { Console.WriteLine(a + b); }) { Console.WriteLine(1); } + } + """; + var src2 = """ + + class C + { + public C() : this((a, b) => { Console.WriteLine(a + b); }) { Console.WriteLine(2); } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1588,16 +1720,20 @@ class C [Fact] public void Constructor_Instance_ExplicitInitializer_WithLambda_Update3() { - var src1 = @" -class C -{ - public C() : this((a, b) => { Console.WriteLine(a + b); }) { Console.WriteLine(1); } -}"; - var src2 = @" -class C -{ - public C() : this((a, b) => { Console.WriteLine(a - b); }) { Console.WriteLine(1); } -}"; + var src1 = """ + + class C + { + public C() : this((a, b) => { Console.WriteLine(a + b); }) { Console.WriteLine(1); } + } + """; + var src2 = """ + + class C + { + public C() : this((a, b) => { Console.WriteLine(a - b); }) { Console.WriteLine(1); } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1607,16 +1743,20 @@ class C [Fact] public void Constructor_Instance_ExplicitInitializer_Delete() { - var src1 = @" -class C -{ - public C(int a) : base(a switch { 1 => 1, _ => 2 }) {} -}"; - var src2 = @" -class C -{ - public C(int a) {} -}"; + var src1 = """ + + class C + { + public C(int a) : base(a switch { 1 => 1, _ => 2 }) {} + } + """; + var src2 = """ + + class C + { + public C(int a) {} + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1829,16 +1969,20 @@ public void Constructor_Instance_Copy_TypeParameterAttributeChange(string keywor [Fact] public void Constructor_Instance_Copy_ReplacingPrimaryWithNonPrimary() { - var src1 = @" -public record C(int P);"; - var src2 = @" -public record C -{ - public int P { get; init; } - public C(int P) { } - protected C(C original) { P = original.P; } -} -"; + var src1 = """ + + public record C(int P); + """; + var src2 = """ + + public record C + { + public int P { get; init; } + public C(int P) { } + protected C(C original) { P = original.P; } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1848,16 +1992,20 @@ public C(int P) { } [Fact] public void Constructor_Instance_Copy_ReplacingNonPrimaryWithPrimary_Initializer() { - var src1 = @" -public record C -{ - public int P { get; init; } - public C(int P) { } - protected C(C original) { P = original.P; } -} -"; - var src2 = @" -public record C(int P);"; + var src1 = """ + + public record C + { + public int P { get; init; } + public C(int P) { } + protected C(C original) { P = original.P; } + } + + """; + var src2 = """ + + public record C(int P); + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1868,16 +2016,20 @@ public record C(int P);"; [Fact] public void Constructor_Instance_Copy_ReplacingNonPrimaryWithPrimary_Body1() { - var src1 = @" -public record C -{ - public int P { get; init; } - public C(int P) { } - protected C(C original) { P = original.P; } -} -"; - var src2 = @" -public record C(int P);"; + var src1 = """ + + public record C + { + public int P { get; init; } + public C(int P) { } + protected C(C original) { P = original.P; } + } + + """; + var src2 = """ + + public record C(int P); + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -1888,16 +2040,20 @@ public record C(int P);"; [Fact] public void Constructor_Instance_Copy_ReplacingNonPrimaryWithPrimary_Body2() { - var src1 = @" -public record C -{ - public int P { get; init; } - public C(int P) { } - protected C(C original) { P = original.P; } -} -"; - var src2 = @" -public record C(int P);"; + var src1 = """ + + public record C + { + public int P { get; init; } + public C(int P) { } + protected C(C original) { P = original.P; } + } + + """; + var src2 = """ + + public record C(int P); + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2014,16 +2170,20 @@ public void Constructor_Instance_Unchanged(string typeKind) [Fact] public void Constructor_Instance_Primary_Record_ReplacingPrimaryWithNonPrimary() { - var src1 = @" -public record C(int P);"; - var src2 = @" -public record C -{ - public int P { get; init; } - public C(int P) { } - protected C(C original) { P = original.P; } -} -"; + var src1 = """ + + public record C(int P); + """; + var src2 = """ + + public record C + { + public int P { get; init; } + public C(int P) { } + protected C(C original) { P = original.P; } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2033,16 +2193,20 @@ public record C [Fact] public void Constructor_Instance_Primary_Record_ReplacingNonPrimaryWithPrimary_Initializer() { - var src1 = @" -public record C -{ - public int P { get; init; } - public C(int P) { } - protected C(C original) { P = original.P; } -} -"; - var src2 = @" -public record C(int P);"; + var src1 = """ + + public record C + { + public int P { get; init; } + public C(int P) { } + protected C(C original) { P = original.P; } + } + + """; + var src2 = """ + + public record C(int P); + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2053,16 +2217,20 @@ public record C(int P);"; [Fact] public void Constructor_Instance_Primary_Record_ReplacingNonPrimaryWithPrimary_Body() { - var src1 = @" -public record C -{ - public int P { get; init; } - public C(int P) { } - protected C(C original) { P = original.P; } -} -"; - var src2 = @" -public record C(int P);"; + var src1 = """ + + public record C + { + public int P { get; init; } + public C(int P) { } + protected C(C original) { P = original.P; } + } + + """; + var src2 = """ + + public record C(int P); + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2073,16 +2241,20 @@ public record C(int P);"; [Fact] public void Constructor_Instance_ReplacingNonPrimaryWithPrimary_Record() { - var src1 = @" -public record C -{ - public int P { get; init; } - public C(int P) { } - protected C(C original) { P = original.P; } -}"; - var src2 = @" -public record C(int P); -"; + var src1 = """ + + public record C + { + public int P { get; init; } + public C(int P) { } + protected C(C original) { P = original.P; } + } + """; + var src2 = """ + + public record C(int P); + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2095,16 +2267,20 @@ public record C(int P); [Fact] public void Constructor_Instance_ReplacingPrimaryWithNonPrimary_Record_PrimaryConstructor2() { - var src1 = @" -public record C(int P);"; - var src2 = @" -public record C -{ - public int P { get; init; } - public C(int P) { } - protected C(C original) { P = original.P; } -} -"; + var src1 = """ + + public record C(int P); + """; + var src2 = """ + + public record C + { + public int P { get; init; } + public C(int P) { } + protected C(C original) { P = original.P; } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2121,18 +2297,22 @@ public record C public void Property_Update_Type_ActiveAccessors() { // only type is changed, no changes to the accessors (not even whitespace) - var src1 = @" -class C -{ - public byte P { get => 1; set { } } -} -"; - var src2 = @" -class C -{ - public long P { get => 1; set { } } -} -"; + var src1 = """ + + class C + { + public byte P { get => 1; set { } } + } + + """; + var src2 = """ + + class C + { + public long P { get => 1; set { } } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2150,18 +2330,22 @@ class C public void Property_Update_Type_ActiveInitializer() { // only type is changed, no changes to the accessors (not even whitespace) - var src1 = @" -class C -{ - public byte P { get; } = 1; -} -"; - var src2 = @" -class C -{ - public long P { get; } = 1; -} -"; + var src1 = """ + + class C + { + public byte P { get; } = 1; + } + + """; + var src2 = """ + + class C + { + public long P { get; } = 1; + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2174,46 +2358,54 @@ class C [Fact] public void Property_Rename_ActiveAccessors() { - var src1 = @" -class C -{ - public int P { get => 1; set { } } -} -"; - var src2 = @" -class C -{ - public int Q { get => 1; set { } } -} -"; - var edits = GetTopEdits(src1, src2); - var active = GetActiveStatements(src1, src2); + var src1 = """ - edits.VerifySemanticDiagnostics( - active, - diagnostics: - [ - Diagnostic(RudeEditKind.ChangingNameOrSignatureOfActiveMember, "public int Q", GetResource("property getter")), - Diagnostic(RudeEditKind.ChangingNameOrSignatureOfActiveMember, "public int Q", GetResource("property setter")) - ], - capabilities: EditAndContinueCapabilities.AddMethodToExistingType); + class C + { + public int P { get => 1; set { } } + } + + """; + var src2 = """ + + class C + { + public int Q { get => 1; set { } } + } + + """; + var edits = GetTopEdits(src1, src2); + var active = GetActiveStatements(src1, src2); + + edits.VerifySemanticDiagnostics( + active, + diagnostics: + [ + Diagnostic(RudeEditKind.ChangingNameOrSignatureOfActiveMember, "public int Q", GetResource("property getter")), + Diagnostic(RudeEditKind.ChangingNameOrSignatureOfActiveMember, "public int Q", GetResource("property setter")) + ], + capabilities: EditAndContinueCapabilities.AddMethodToExistingType); } [Fact] public void Property_Update_ExpressionBodyToAutoProp_FieldAccess() { - var src1 = @" -class C -{ - public int P => 1; -} -"; - var src2 = @" -class C -{ - public int P => field; -} -"; + var src1 = """ + + class C + { + public int P => 1; + } + + """; + var src2 = """ + + class C + { + public int P => field; + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2225,18 +2417,22 @@ class C [Fact] public void Property_Update_Accessor_ExpressionBodyToAutoProp_FieldAccess() { - var src1 = @" -class C -{ - public int P { get => 1; } -} -"; - var src2 = @" -class C -{ - public int P { get => field; } -} -"; + var src1 = """ + + class C + { + public int P { get => 1; } + } + + """; + var src2 = """ + + class C + { + public int P { get => field; } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2248,16 +2444,20 @@ class C [Fact] public void Property_Auto_Record_ReplacingNonPrimaryWithPrimary_Getter() { - var src1 = @" -public record C -{ - public int P { get; init; } - public C(int P) { } - protected C(C original) {P = original.P; } -}"; - var src2 = @" -public record C(int P); -"; + var src1 = """ + + public record C + { + public int P { get; init; } + public C(int P) { } + protected C(C original) {P = original.P; } + } + """; + var src2 = """ + + public record C(int P); + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2267,16 +2467,20 @@ public record C(int P); [Fact] public void Property_Auto_Record_ReplacingNonPrimaryWithPrimary_Setter() { - var src1 = @" -public record C -{ - public int P { get; init; } - public C(int P) { } - protected C(C original) {P = original.P; } -}"; - var src2 = @" -public record C(int P); -"; + var src1 = """ + + public record C + { + public int P { get; init; } + public C(int P) { } + protected C(C original) {P = original.P; } + } + """; + var src2 = """ + + public record C(int P); + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2289,16 +2493,20 @@ public void Property_Auto_Record_ReplacingPrimaryWithNonPrimary_Getter() // Consider: Just looking at the span we do not know whether the active statement is in the getter of the setter. // We could resolve the method token associated with the method to find out and map the statement accordingly. - var src1 = @" -public record C(int P); -"; - var src2 = @" -public record C -{ - public int P { get; init; } - public C(int P) { } - protected C(C original) {P = original.P; } -}"; + var src1 = """ + + public record C(int P); + + """; + var src2 = """ + + public record C + { + public int P { get; init; } + public C(int P) { } + protected C(C original) {P = original.P; } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2311,16 +2519,20 @@ public void Property_Auto_Record_ReplacingPrimaryWithNonPrimary_Setter() // Consider: Just looking at the span we do not know whether the active statement is in the getter of the setter. // We could resolve the method token associated with the method to find out and map the statement accordingly. - var src1 = @" -public record C(int P); -"; - var src2 = @" -public record C -{ - public int P { init; get; } - public C(int P) { } - protected C(C original) {P = original.P; } -}"; + var src1 = """ + + public record C(int P); + + """; + var src2 = """ + + public record C + { + public int P { init; get; } + public C(int P) { } + protected C(C original) {P = original.P; } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2336,30 +2548,38 @@ public C(int P) { } [InlineData("struct")] public void InstancePropertyInitializer_Leaf_Update(string typeKind) { - var src1 = @" -" + typeKind + @" C -{ - int a { get; } = 1; + var src1 = """ - public C() {} - static void Main(string[] args) - { - C c = new C(); - } -}"; - var src2 = @" -" + typeKind + @" C -{ - int a { get; } = 2; + """ + typeKind + """ + C + { + int a { get; } = 1; - public C() {} + public C() {} - static void Main(string[] args) - { - C c = new C(); - } -}"; + static void Main(string[] args) + { + C c = new C(); + } + } + """; + var src2 = """ + + + """ + typeKind + """ + C + { + int a { get; } = 2; + + public C() {} + + static void Main(string[] args) + { + C c = new C(); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2371,26 +2591,34 @@ static void Main(string[] args) [InlineData("struct")] public void InstancePropertyInitializer_Leaf_Update_SynthesizedConstructor(string typeKind) { - var src1 = @" -" + typeKind + @" C -{ - int a { get; } = 1; + var src1 = """ - static void Main(string[] args) - { - C c = new C(); - } -}"; - var src2 = @" -" + typeKind + @" C -{ - int a { get; } = 2; - static void Main(string[] args) - { - C c = new C(); - } -}"; + """ + typeKind + """ + C + { + int a { get; } = 1; + + static void Main(string[] args) + { + C c = new C(); + } + } + """; + var src2 = """ + + + """ + typeKind + """ + C + { + int a { get; } = 2; + + static void Main(string[] args) + { + C c = new C(); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2402,30 +2630,38 @@ static void Main(string[] args) [InlineData("struct")] public void InstanceFieldInitializer_Leaf_Update1(string typeKind) { - var src1 = @" -" + typeKind + @" C -{ - int a = 1, b = 2; + var src1 = """ - public C() {} - static void Main(string[] args) - { - C c = new C(); - } -}"; - var src2 = @" -" + typeKind + @" C -{ - int a = 2, b = 2; + """ + typeKind + """ + C + { + int a = 1, b = 2; - public C() {} + public C() {} - static void Main(string[] args) - { - C c = new C(); - } -}"; + static void Main(string[] args) + { + C c = new C(); + } + } + """; + var src2 = """ + + + """ + typeKind + """ + C + { + int a = 2, b = 2; + + public C() {} + + static void Main(string[] args) + { + C c = new C(); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2437,26 +2673,34 @@ static void Main(string[] args) [InlineData("struct")] public void InstanceFieldInitializer_Leaf_Update1_SynthesizedConstructor(string typeKind) { - var src1 = @" -" + typeKind + @" C -{ - int a = 1, b = 2; + var src1 = """ - static void Main(string[] args) - { - C c = new C(); - } -}"; - var src2 = @" -" + typeKind + @" C -{ - int a = 2, b = 2; - static void Main(string[] args) - { - C c = new C(); - } -}"; + """ + typeKind + """ + C + { + int a = 1, b = 2; + + static void Main(string[] args) + { + C c = new C(); + } + } + """; + var src2 = """ + + + """ + typeKind + """ + C + { + int a = 2, b = 2; + + static void Main(string[] args) + { + C c = new C(); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2466,40 +2710,44 @@ static void Main(string[] args) [Fact] public void InstanceFieldInitializer_Internal_Update1() { - var src1 = @" -class C -{ - int a = F(1), b = F(2); + var src1 = """ - public C() {} + class C + { + int a = F(1), b = F(2); - public static int F(int a) - { - return a; - } + public C() {} - static void Main(string[] args) - { - C c = new C(); - } -}"; - var src2 = @" -class C -{ - int a = F(2), b = F(2); + public static int F(int a) + { + return a; + } - public C() {} + static void Main(string[] args) + { + C c = new C(); + } + } + """; + var src2 = """ - public static int F(int a) - { - return a; - } + class C + { + int a = F(2), b = F(2); - static void Main(string[] args) - { - C c = new C(); - } -}"; + public C() {} + + public static int F(int a) + { + return a; + } + + static void Main(string[] args) + { + C c = new C(); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2510,40 +2758,44 @@ static void Main(string[] args) [Fact] public void InstanceFieldInitializer_Internal_Update2() { - var src1 = @" -class C -{ - int a = F(1), b = F(2); + var src1 = """ - public C() {} + class C + { + int a = F(1), b = F(2); - public static int F(int a) - { - return a; - } + public C() {} - static void Main(string[] args) - { - C c = new C(); - } -}"; - var src2 = @" -class C -{ - int a = F(1), b = F(3); + public static int F(int a) + { + return a; + } + + static void Main(string[] args) + { + C c = new C(); + } + } + """; + var src2 = """ - public C() {} + class C + { + int a = F(1), b = F(3); - public static int F(int a) - { - return a; - } + public C() {} - static void Main(string[] args) - { - C c = new C(); - } -}"; + public static int F(int a) + { + return a; + } + + static void Main(string[] args) + { + C c = new C(); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2554,55 +2806,63 @@ static void Main(string[] args) [Fact] public void InstancePropertyInitializer_Internal_Delete1() { - var src1 = @" -class C -{ - int a { get; } = 1; - int b { get; } = 2; -}"; - var src2 = @" -class C -{ - int a { get { return 1; } } - int b { get; } = 2; -}"; - var edits = GetTopEdits(src1, src2); - var active = GetActiveStatements(src1, src2); - - edits.VerifySemanticDiagnostics(active); - } + var src1 = """ - [Fact] + class C + { + int a { get; } = 1; + int b { get; } = 2; + } + """; + var src2 = """ + + class C + { + int a { get { return 1; } } + int b { get; } = 2; + } + """; + var edits = GetTopEdits(src1, src2); + var active = GetActiveStatements(src1, src2); + + edits.VerifySemanticDiagnostics(active); + } + + [Fact] public void InstancePropertyInitializer_Internal_Delete2() { - var src1 = @" -class C -{ - int a { get; } = 1; - static int s { get; } = 2; - int b { get; } = 2; + var src1 = """ - public C() {} + class C + { + int a { get; } = 1; + static int s { get; } = 2; + int b { get; } = 2; - static void Main(string[] args) - { - C c = new C(); - } -}"; - var src2 = @" -class C -{ - int a { get; } - static int s { get; } = 2; - int b { get; } = 3; + public C() {} - public C() { } + static void Main(string[] args) + { + C c = new C(); + } + } + """; + var src2 = """ - static void Main(string[] args) - { - C c = new C(); - } -}"; + class C + { + int a { get; } + static int s { get; } = 2; + int b { get; } = 3; + + public C() { } + + static void Main(string[] args) + { + C c = new C(); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2612,40 +2872,44 @@ static void Main(string[] args) [Fact] public void InstanceFieldInitializer_Internal_Delete1() { - var src1 = @" -class C -{ - int a = F(1), b = F(2); + var src1 = """ - public C() {} + class C + { + int a = F(1), b = F(2); - public static int F(int a) - { - return a; - } + public C() {} - static void Main(string[] args) - { - C c = new C(); - } -}"; - var src2 = @" -class C -{ - int a, b = F(2); + public static int F(int a) + { + return a; + } - public C() {} + static void Main(string[] args) + { + C c = new C(); + } + } + """; + var src2 = """ - public static int F(int a) - { - return a; - } + class C + { + int a, b = F(2); - static void Main(string[] args) - { - C c = new C(); - } -}"; + public C() {} + + public static int F(int a) + { + return a; + } + + static void Main(string[] args) + { + C c = new C(); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2655,20 +2919,24 @@ static void Main(string[] args) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69249")] public void InstanceFieldInitializer_Internal_Delete2() { - var src1 = @" -class C -{ - int a = F(1), b = F(2); + var src1 = """ - public static int F(int a) => 1; -}"; - var src2 = @" -class C -{ - int a, b; + class C + { + int a = F(1), b = F(2); + + public static int F(int a) => 1; + } + """; + var src2 = """ + + class C + { + int a, b; - public static int F(int a) => 1; -}"; + public static int F(int a) => 1; + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2678,20 +2946,24 @@ class C [Fact] public void InstancePropertyAndFieldInitializers_Delete1() { - var src1 = @" -class C -{ - int a { get; } = 1; - static int s { get; } = 2; - int b = 2; -}"; - var src2 = @" -class C -{ - int a { get; } - static int s { get; } = 2; - int b = 3; -}"; + var src1 = """ + + class C + { + int a { get; } = 1; + static int s { get; } = 2; + int b = 2; + } + """; + var src2 = """ + + class C + { + int a { get; } + static int s { get; } = 2; + int b = 3; + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2701,34 +2973,38 @@ class C [Fact] public void InstancePropertyAndFieldInitializers_Delete2() { - var src1 = @" -class C -{ - int a = 1; - static int s { get; } = 2; - int b { get; } = 2; + var src1 = """ - public C() {} + class C + { + int a = 1; + static int s { get; } = 2; + int b { get; } = 2; - static void Main(string[] args) - { - C c = new C(); - } -}"; - var src2 = @" -class C -{ - int a; - static int s { get; } = 2; - int b { get; } = 3; + public C() {} - public C() { } + static void Main(string[] args) + { + C c = new C(); + } + } + """; + var src2 = """ - static void Main(string[] args) - { - C c = new C(); - } -}"; + class C + { + int a; + static int s { get; } = 2; + int b { get; } = 3; + + public C() { } + + static void Main(string[] args) + { + C c = new C(); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2738,40 +3014,44 @@ static void Main(string[] args) [Fact] public void InstanceFieldInitializer_SingleDeclarator() { - var src1 = @" -class C -{ - public static readonly int a = F(1); + var src1 = """ - public C() {} + class C + { + public static readonly int a = F(1); - public static int F(int a) - { - return a; - } + public C() {} - static void Main(string[] args) - { - C c = new C(); - } -}"; - var src2 = @" -class C -{ - public static readonly int a = F(1); + public static int F(int a) + { + return a; + } - public C() {} + static void Main(string[] args) + { + C c = new C(); + } + } + """; + var src2 = """ - public static int F(int a) - { - return a + 1; - } + class C + { + public static readonly int a = F(1); - static void Main(string[] args) - { - C c = new C(); - } -}"; + public C() {} + + public static int F(int a) + { + return a + 1; + } + + static void Main(string[] args) + { + C c = new C(); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2781,26 +3061,30 @@ static void Main(string[] args) [Fact] public void FieldInitializer_Lambda1() { - var src1 = @" -class C -{ - Func a = z => z + 1; + var src1 = """ - static void Main(string[] args) - { - new C().a(1); - } -}"; - var src2 = @" -class C -{ - Func a = F(z => z + 1); + class C + { + Func a = z => z + 1; - static void Main(string[] args) - { - new C().a(1); - } -}"; + static void Main(string[] args) + { + new C().a(1); + } + } + """; + var src2 = """ + + class C + { + Func a = F(z => z + 1); + + static void Main(string[] args) + { + new C().a(1); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2810,26 +3094,30 @@ static void Main(string[] args) [Fact] public void PropertyInitializer_Lambda1() { - var src1 = @" -class C -{ - Func a { get; } = z => z + 1; + var src1 = """ - static void Main(string[] args) - { - new C().a(1); - } -}"; - var src2 = @" -class C -{ - Func a { get; } = F(z => z + 1); + class C + { + Func a { get; } = z => z + 1; - static void Main(string[] args) - { - new C().a(1); - } -}"; + static void Main(string[] args) + { + new C().a(1); + } + } + """; + var src2 = """ + + class C + { + Func a { get; } = F(z => z + 1); + + static void Main(string[] args) + { + new C().a(1); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2839,26 +3127,30 @@ static void Main(string[] args) [Fact] public void FieldInitializer_Lambda2() { - var src1 = @" -class C -{ - Func> a = z => () => z + 1; + var src1 = """ - static void Main(string[] args) - { - new C().a(1)(); - } -}"; - var src2 = @" -class C -{ - Func> a = z => () => z + 2; + class C + { + Func> a = z => () => z + 1; - static void Main(string[] args) - { - new C().a(1)(); - } -}"; + static void Main(string[] args) + { + new C().a(1)(); + } + } + """; + var src2 = """ + + class C + { + Func> a = z => () => z + 2; + + static void Main(string[] args) + { + new C().a(1)(); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2868,26 +3160,30 @@ static void Main(string[] args) [Fact] public void PropertyInitializer_Lambda2() { - var src1 = @" -class C -{ - Func> a { get; } = z => () => z + 1; + var src1 = """ - static void Main(string[] args) - { - new C().a(1)(); - } -}"; - var src2 = @" -class C -{ - Func> a { get; } = z => () => z + 2; + class C + { + Func> a { get; } = z => () => z + 1; - static void Main(string[] args) - { - new C().a(1)(); - } -}"; + static void Main(string[] args) + { + new C().a(1)(); + } + } + """; + var src2 = """ + + class C + { + Func> a { get; } = z => () => z + 2; + + static void Main(string[] args) + { + new C().a(1)(); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2897,20 +3193,24 @@ static void Main(string[] args) [Fact] public void FieldInitializer_InsertConst1() { - var src1 = @" -class C -{ - int a = 1; + var src1 = """ - public C() {} -}"; - var src2 = @" -class C -{ - const int a = 1; + class C + { + int a = 1; + + public C() {} + } + """; + var src2 = """ + + class C + { + const int a = 1; - public C() {} -}"; + public C() {} + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -2925,22 +3225,26 @@ public C() {} [Fact] public void LocalInitializer_InsertConst1() { - var src1 = @" -class C -{ - public void M() - { - int a = 1; - } -}"; - var src2 = @" -class C -{ - public void M() - { - const int a = 1; - } -}"; + var src1 = """ + + class C + { + public void M() + { + int a = 1; + } + } + """; + var src2 = """ + + class C + { + public void M() + { + const int a = 1; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2950,20 +3254,24 @@ public void M() [Fact] public void FieldInitializer_InsertConst2() { - var src1 = @" -class C -{ - int a = 1, b = 2; + var src1 = """ - public C() {} -}"; - var src2 = @" -class C -{ - const int a = 1, b = 2; + class C + { + int a = 1, b = 2; + + public C() {} + } + """; + var src2 = """ - public C() {} -}"; + class C + { + const int a = 1, b = 2; + + public C() {} + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -2976,22 +3284,26 @@ public C() {} [Fact] public void LocalInitializer_InsertConst2() { - var src1 = @" -class C -{ - public void M() - { - int a = 1, b = 2; - } -}"; - var src2 = @" -class C -{ - public void M() - { - const int a = 1, b = 2; - } -}"; + var src1 = """ + + class C + { + public void M() + { + int a = 1, b = 2; + } + } + """; + var src2 = """ + + class C + { + public void M() + { + const int a = 1, b = 2; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3001,22 +3313,26 @@ public void M() [Fact] public void FieldInitializer_Delete1() { - var src1 = @" -class C -{ - int a = 1; - int b = 1; + var src1 = """ - public C() {} -}"; - var src2 = @" -class C -{ - int a; - int b = 1; + class C + { + int a = 1; + int b = 1; + + public C() {} + } + """; + var src2 = """ + + class C + { + int a; + int b = 1; - public C() {} -}"; + public C() {} + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3026,16 +3342,20 @@ public C() {} [Fact] public void LocalInitializer_Delete1() { - var src1 = @" -class C -{ - public void M() { int a = 1; } -}"; - var src2 = @" -class C -{ - public void M() { int a; } -}"; + var src1 = """ + + class C + { + public void M() { int a = 1; } + } + """; + var src2 = """ + + class C + { + public void M() { int a; } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3045,24 +3365,28 @@ class C [Fact] public void FieldInitializer_Delete2() { - var src1 = @" -class C -{ - int b = 1; - int c; - int a = 1; - - public C() {} -}"; - var src2 = @" -class C -{ - int b = 1; - int c; - int a; + var src1 = """ - public C() {} -}"; + class C + { + int b = 1; + int c; + int a = 1; + + public C() {} + } + """; + var src2 = """ + + class C + { + int b = 1; + int c; + int a; + + public C() {} + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3072,26 +3396,30 @@ public C() {} [Fact] public void LocalInitializer_Delete2() { - var src1 = @" -class C -{ - public void M() - { - int b = 1; - int c; - int a = 1; - } -}"; - var src2 = @" -class C -{ - public void M() - { - int b = 1; - int c; - int a; - } -}"; + var src1 = """ + + class C + { + public void M() + { + int b = 1; + int c; + int a = 1; + } + } + """; + var src2 = """ + + class C + { + public void M() + { + int b = 1; + int c; + int a; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3101,23 +3429,27 @@ public void M() [Fact] public void FieldInitializer_Delete3() { - var src1 = @" -class C -{ - int b = 1; - int c; - int a = 1; - - public C() {} -}"; - var src2 = @" -class C -{ - int b = 1; - int c; + var src1 = """ + + class C + { + int b = 1; + int c; + int a = 1; + + public C() {} + } + """; + var src2 = """ - public C() {} -}"; + class C + { + int b = 1; + int c; + + public C() {} + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3129,25 +3461,29 @@ public C() {} [Fact] public void LocalInitializer_Delete3() { - var src1 = @" -class C -{ - public void M() - { - int b = 1; - int c; - int a = 1; - } -}"; - var src2 = @" -class C -{ - public void M() - { - int b = 1; - int c; - } -}"; + var src1 = """ + + class C + { + public void M() + { + int b = 1; + int c; + int a = 1; + } + } + """; + var src2 = """ + + class C + { + public void M() + { + int b = 1; + int c; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3157,24 +3493,28 @@ public void M() [Fact] public void FieldInitializer_DeleteStaticInstance1() { - var src1 = @" -class C -{ - int a = 1; - static int b = 1; - int c = 1; - - public C() {} -}"; - var src2 = @" -class C -{ - int a; - static int b = 1; - int c = 1; + var src1 = """ + + class C + { + int a = 1; + static int b = 1; + int c = 1; + + public C() {} + } + """; + var src2 = """ + + class C + { + int a; + static int b = 1; + int c = 1; - public C() {} -}"; + public C() {} + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3184,24 +3524,28 @@ public C() {} [Fact] public void FieldInitializer_DeleteStaticInstance2() { - var src1 = @" -class C -{ - static int c = 1; - static int a = 1; - int b = 1; - - public C() {} -}"; - var src2 = @" -class C -{ - static int c = 1; - static int a; - int b = 1; + var src1 = """ + + class C + { + static int c = 1; + static int a = 1; + int b = 1; + + public C() {} + } + """; + var src2 = """ - public C() {} -}"; + class C + { + static int c = 1; + static int a; + int b = 1; + + public C() {} + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3211,22 +3555,26 @@ public C() {} [Fact] public void FieldInitializer_DeleteStaticInstance3() { - var src1 = @" -class C -{ - static int a = 1; - int b = 1; - - public C() {} -}"; - var src2 = @" -class C -{ - static int a; - int b = 1; + var src1 = """ - public C() {} -}"; + class C + { + static int a = 1; + int b = 1; + + public C() {} + } + """; + var src2 = """ + + class C + { + static int a; + int b = 1; + + public C() {} + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3236,23 +3584,27 @@ public C() {} [Fact] public void FieldInitializer_DeleteMove1() { - var src1 = @" -class C -{ - int b = 1; - int c; - int a = 1; - - public C() {} -}"; - var src2 = @" -class C -{ - int c; - int b = 1; + var src1 = """ + + class C + { + int b = 1; + int c; + int a = 1; + + public C() {} + } + """; + var src2 = """ + + class C + { + int c; + int b = 1; - public C() {} -}"; + public C() {} + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3264,25 +3616,29 @@ public C() {} [Fact] public void LocalInitializer_DeleteReorder1() { - var src1 = @" -class C -{ - public void M() - { - int b = 1; - int a = 1; - int c; - } -}"; - var src2 = @" -class C -{ - public void M() - { - int c; - int b = 1; - } -}"; + var src1 = """ + + class C + { + public void M() + { + int b = 1; + int a = 1; + int c; + } + } + """; + var src2 = """ + + class C + { + public void M() + { + int c; + int b = 1; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3292,18 +3648,22 @@ public void M() [Fact] public void FieldToProperty1() { - var src1 = @" -class C -{ - int a = 1; -}"; + var src1 = """ + + class C + { + int a = 1; + } + """; // The placement of the active statement is not ideal, but acceptable. - var src2 = @" -class C -{ - int a { get; } = 1; -}"; + var src2 = """ + + class C + { + int a { get; } = 1; + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3315,18 +3675,22 @@ class C [Fact] public void PropertyToField1() { - var src1 = @" -class C -{ - int a { get; } = 1; -}"; + var src1 = """ + + class C + { + int a { get; } = 1; + } + """; // The placement of the active statement is not ideal, but acceptable. - var src2 = @" -class C -{ - int a = 1; -}"; + var src2 = """ + + class C + { + int a = 1; + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3347,32 +3711,36 @@ class C [Fact] public void LockBody_Update() { - var src1 = @" -class Test -{ - private static object F() { return new object(); } + var src1 = """ - static void Main(string[] args) - { - lock (F()) - { - System.Console.Write(0); - } - } -}"; - var src2 = @" -class Test -{ - private static object F() { return new object(); } + class Test + { + private static object F() { return new object(); } - static void Main(string[] args) - { - lock (F()) - { - System.Console.Write(1); - } - } -}"; + static void Main(string[] args) + { + lock (F()) + { + System.Console.Write(0); + } + } + } + """; + var src2 = """ + + class Test + { + private static object F() { return new object(); } + + static void Main(string[] args) + { + lock (F()) + { + System.Console.Write(1); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3382,27 +3750,31 @@ static void Main(string[] args) [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755749")] public void Lock_Insert_Leaf() { - var src1 = @" -class Test -{ - private static object lockThis = new object(); - static void Main(string[] args) - { - System.Console.Write(5); - } -}"; - var src2 = @" -class Test -{ - private static object lockThis = new object(); - static void Main(string[] args) - { - lock (lockThis) - { - System.Console.Write(5); - } - } -}"; + var src1 = """ + + class Test + { + private static object lockThis = new object(); + static void Main(string[] args) + { + System.Console.Write(5); + } + } + """; + var src2 = """ + + class Test + { + private static object lockThis = new object(); + static void Main(string[] args) + { + lock (lockThis) + { + System.Console.Write(5); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3413,29 +3785,33 @@ static void Main(string[] args) [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755749")] public void Lock_Insert_Leaf2() { - var src1 = @" -class Test -{ - private static object lockThis = new object(); - static void Main(string[] args) - { - { - System.Console.Write(5); - } - } -}"; - var src2 = @" -class Test -{ - private static object lockThis = new object(); - static void Main(string[] args) - { - lock (lockThis) - { - System.Console.Write(5); - } - } -}"; + var src1 = """ + + class Test + { + private static object lockThis = new object(); + static void Main(string[] args) + { + { + System.Console.Write(5); + } + } + } + """; + var src2 = """ + + class Test + { + private static object lockThis = new object(); + static void Main(string[] args) + { + lock (lockThis) + { + System.Console.Write(5); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3446,31 +3822,35 @@ static void Main(string[] args) [Fact] public void Lock_Insert_Leaf3() { - var src1 = @" -class Test -{ - private static object lockThis = new object(); - static void Main(string[] args) - { - { - System.Console.Write(5); - } - System.Console.Write(10); - } -}"; - var src2 = @" -class Test -{ - private static object lockThis = new object(); - static void Main(string[] args) - { - lock (lockThis) - { - System.Console.Write(5); - } - System.Console.Write(5); - } -}"; + var src1 = """ + + class Test + { + private static object lockThis = new object(); + static void Main(string[] args) + { + { + System.Console.Write(5); + } + System.Console.Write(10); + } + } + """; + var src2 = """ + + class Test + { + private static object lockThis = new object(); + static void Main(string[] args) + { + lock (lockThis) + { + System.Console.Write(5); + } + System.Console.Write(5); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3480,55 +3860,59 @@ static void Main(string[] args) [Fact] public void Lock_Insert_Leaf4() { - var src1 = @" -class Test -{ - public static object a = new object(); - public static object b = new object(); - public static object c = new object(); - public static object d = new object(); - public static object e = new object(); - - static void Main(string[] args) - { - lock (a) - { - lock (b) + var src1 = """ + + class Test { - lock (c) + public static object a = new object(); + public static object b = new object(); + public static object c = new object(); + public static object d = new object(); + public static object e = new object(); + + static void Main(string[] args) { - System.Console.Write(); + lock (a) + { + lock (b) + { + lock (c) + { + System.Console.Write(); + } + } + } } } - } - } -}"; - var src2 = @" -class Test -{ - public static object a = new object(); - public static object b = new object(); - public static object c = new object(); - public static object d = new object(); - public static object e = new object(); - - static void Main(string[] args) - { - lock (b) - { - lock (d) + """; + var src2 = """ + + class Test { - lock (a) + public static object a = new object(); + public static object b = new object(); + public static object c = new object(); + public static object d = new object(); + public static object e = new object(); + + static void Main(string[] args) { - lock (e) + lock (b) { - System.Console.Write(); + lock (d) + { + lock (a) + { + lock (e) + { + System.Console.Write(); + } + } + } } } } - } - } -}"; + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3540,56 +3924,60 @@ static void Main(string[] args) [Fact] public void Lock_Insert_Leaf5() { - var src1 = @" -class Test -{ - public static object a = new object(); - public static object b = new object(); - public static object c = new object(); - public static object d = new object(); - public static object e = new object(); - - static void Main(string[] args) - { - lock (a) - { - lock (c) + var src1 = """ + + class Test { - lock (b) + public static object a = new object(); + public static object b = new object(); + public static object c = new object(); + public static object d = new object(); + public static object e = new object(); + + static void Main(string[] args) { - lock (e) + lock (a) { - System.Console.Write(); + lock (c) + { + lock (b) + { + lock (e) + { + System.Console.Write(); + } + } + } } } } - } - } -}"; + """; - var src2 = @" -class Test -{ - public static object a = new object(); - public static object b = new object(); - public static object c = new object(); - public static object d = new object(); - public static object e = new object(); - - static void Main(string[] args) - { - lock (b) - { - lock (d) + var src2 = """ + + class Test { - lock (a) + public static object a = new object(); + public static object b = new object(); + public static object c = new object(); + public static object d = new object(); + public static object e = new object(); + + static void Main(string[] args) { - System.Console.Write(); + lock (b) + { + lock (d) + { + lock (a) + { + System.Console.Write(); + } + } + } } } - } - } -}"; + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3600,30 +3988,34 @@ static void Main(string[] args) [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755752")] public void Lock_Update_Leaf() { - var src1 = @" -class Test -{ - private static object lockThis = new object(); - static void Main(string[] args) - { - lock (lockThis) - { - System.Console.Write(5); - } - } -}"; - var src2 = @" -class Test -{ - private static object lockThis = new object(); - static void Main(string[] args) - { - lock (""test"") - { - System.Console.Write(5); - } - } -}"; + var src1 = """ + + class Test + { + private static object lockThis = new object(); + static void Main(string[] args) + { + lock (lockThis) + { + System.Console.Write(5); + } + } + } + """; + var src2 = """ + + class Test + { + private static object lockThis = new object(); + static void Main(string[] args) + { + lock ("test") + { + System.Console.Write(5); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3634,32 +4026,36 @@ static void Main(string[] args) [Fact] public void Lock_Update_Leaf2() { - var src1 = @" -class Test -{ - private static object lockThis = new object(); - static void Main(string[] args) - { - lock (lockThis) - { - System.Console.Write(5); - } - System.Console.Write(5); - } -}"; - var src2 = @" -class Test -{ - private static object lockThis = new object(); - static void Main(string[] args) - { - lock (""test"") - { - System.Console.Write(5); - } - System.Console.Write(5); - } -}"; + var src1 = """ + + class Test + { + private static object lockThis = new object(); + static void Main(string[] args) + { + lock (lockThis) + { + System.Console.Write(5); + } + System.Console.Write(5); + } + } + """; + var src2 = """ + + class Test + { + private static object lockThis = new object(); + static void Main(string[] args) + { + lock ("test") + { + System.Console.Write(5); + } + System.Console.Write(5); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3669,27 +4065,31 @@ static void Main(string[] args) [Fact] public void Lock_Delete_Leaf() { - var src1 = @" -class Test -{ - private static object lockThis = new object(); - static void Main(string[] args) - { - lock (lockThis) - { - System.Console.Write(5); - } - } -}"; - var src2 = @" -class Test -{ - private static object lockThis = new object(); - static void Main(string[] args) - { - System.Console.Write(5); - } -}"; + var src1 = """ + + class Test + { + private static object lockThis = new object(); + static void Main(string[] args) + { + lock (lockThis) + { + System.Console.Write(5); + } + } + } + """; + var src2 = """ + + class Test + { + private static object lockThis = new object(); + static void Main(string[] args) + { + System.Console.Write(5); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3699,63 +4099,71 @@ static void Main(string[] args) [Fact] public void Lock_Update_Lambda1() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - lock (F(a => a)) - { - Console.WriteLine(1); - } - } -} -"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - lock (F(a => a + 1)) - { - Console.WriteLine(2); - } - } -} -"; - var edits = GetTopEdits(src1, src2); - var active = GetActiveStatements(src1, src2); + var src1 = """ - edits.VerifySemanticDiagnostics(active); + class C + { + static void Main(string[] args) + { + lock (F(a => a)) + { + Console.WriteLine(1); + } + } + } + + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + lock (F(a => a + 1)) + { + Console.WriteLine(2); + } + } + } + + """; + var edits = GetTopEdits(src1, src2); + var active = GetActiveStatements(src1, src2); + + edits.VerifySemanticDiagnostics(active); } [Fact] public void Lock_Update_Lambda2() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - lock (F(a => a)) - { - Console.WriteLine(1); - } - } -} -"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - lock (G(a => a)) - { - Console.WriteLine(1); - } - } -} -"; + var src1 = """ + + class C + { + static void Main(string[] args) + { + lock (F(a => a)) + { + Console.WriteLine(1); + } + } + } + + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + lock (G(a => a)) + { + Console.WriteLine(1); + } + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3864,40 +4272,44 @@ static void F() [Fact] public void FixedBody_Update() { - var src1 = @" -class Test -{ - private static string F() { return null; } + var src1 = """ - static void Main(string[] args) - { - unsafe - { - char* px2; - fixed (char* pj = &F()) + class Test { - System.Console.WriteLine(0); + private static string F() { return null; } + + static void Main(string[] args) + { + unsafe + { + char* px2; + fixed (char* pj = &F()) + { + System.Console.WriteLine(0); + } + } + } } - } - } -}"; - var src2 = @" -class Test -{ - private static string F() { return null; } + """; + var src2 = """ - static void Main(string[] args) - { - unsafe - { - char* px2; - fixed (char* pj = &F()) + class Test { - System.Console.WriteLine(1); + private static string F() { return null; } + + static void Main(string[] args) + { + unsafe + { + char* px2; + fixed (char* pj = &F()) + { + System.Console.WriteLine(1); + } + } + } } - } - } -}"; + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3950,35 +4362,39 @@ static unsafe void F() [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755742")] public void Fixed_Insert_Leaf() { - var src1 = @" -class Test -{ - static int value = 20; - static void Main(string[] args) - { - unsafe - { - int* px2; - px2 = null; - } - } -}"; - var src2 = @" -class Test -{ - static int value = 20; - static void Main(string[] args) - { - unsafe - { - int* px2; - fixed (int* pj = &value) + var src1 = """ + + class Test { - px2 = null; + static int value = 20; + static void Main(string[] args) + { + unsafe + { + int* px2; + px2 = null; + } + } } - } - } -}"; + """; + var src2 = """ + + class Test + { + static int value = 20; + static void Main(string[] args) + { + unsafe + { + int* px2; + fixed (int* pj = &value) + { + px2 = null; + } + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -3989,34 +4405,38 @@ static void Main(string[] args) [Fact] public void Fixed_Insert_Leaf2() { - var src1 = @" -class Test -{ - static int value = 20; - static void Main(string[] args) - { - unsafe - { - int* px2; - } - } -}"; - var src2 = @" -class Test -{ - static int value = 20; - static void Main(string[] args) - { - unsafe - { - int* px2; - fixed (int* pj = &value) + var src1 = """ + + class Test { - px2 = null; + static int value = 20; + static void Main(string[] args) + { + unsafe + { + int* px2; + } + } } - } - } -}"; + """; + var src2 = """ + + class Test + { + static int value = 20; + static void Main(string[] args) + { + unsafe + { + int* px2; + fixed (int* pj = &value) + { + px2 = null; + } + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -4026,40 +4446,44 @@ static void Main(string[] args) [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755742")] public void Fixed_Insert_Leaf3() { - var src1 = @" -class Test -{ - static int value = 20; - static void Main(string[] args) - { - unsafe - { - int* px2; - px2 = null; + var src1 = """ - fixed (int* pj = &value) + class Test { - + static int value = 20; + static void Main(string[] args) + { + unsafe + { + int* px2; + px2 = null; + + fixed (int* pj = &value) + { + + } + } + } } - } - } -}"; - var src2 = @" -class Test -{ - static int value = 20; - static void Main(string[] args) - { - unsafe - { - int* px2; - fixed (int* pj = &value) + """; + var src2 = """ + + class Test { - px2 = null; + static int value = 20; + static void Main(string[] args) + { + unsafe + { + int* px2; + fixed (int* pj = &value) + { + px2 = null; + } + } + } } - } - } -}"; + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -4070,44 +4494,48 @@ static void Main(string[] args) [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755742")] public void Fixed_Reorder_Leaf1() { - var src1 = @" -class Test -{ - static int value = 20; - static void Main(string[] args) - { - unsafe - { - int* px2; - fixed (int* a = &value) + var src1 = """ + + class Test { - fixed (int* b = &value) + static int value = 20; + static void Main(string[] args) { - px2 = null; + unsafe + { + int* px2; + fixed (int* a = &value) + { + fixed (int* b = &value) + { + px2 = null; + } + } + } } } - } - } -}"; - var src2 = @" -class Test -{ - static int value = 20; - static void Main(string[] args) - { - unsafe - { - int* px2; - fixed (int* b = &value) + """; + var src2 = """ + + class Test { - fixed (int* a = &value) + static int value = 20; + static void Main(string[] args) { - px2 = null; + unsafe + { + int* px2; + fixed (int* b = &value) + { + fixed (int* a = &value) + { + px2 = null; + } + } + } } } - } - } -}"; + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -4117,38 +4545,42 @@ static void Main(string[] args) [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755746")] public void Fixed_Update_Leaf1() { - var src1 = @" -class Test -{ - static int value = 20; - static void Main(string[] args) - { - unsafe - { - int* px2; - fixed (int* pj = &value) + var src1 = """ + + class Test { - px2 = null; + static int value = 20; + static void Main(string[] args) + { + unsafe + { + int* px2; + fixed (int* pj = &value) + { + px2 = null; + } + } + } } - } - } -}"; - var src2 = @" -class Test -{ - static int value = 20; - static void Main(string[] args) - { - unsafe - { - int* px2; - fixed (int* p = &value) + """; + var src2 = """ + + class Test { - px2 = null; + static int value = 20; + static void Main(string[] args) + { + unsafe + { + int* px2; + fixed (int* p = &value) + { + px2 = null; + } + } + } } - } - } -}"; + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -4159,55 +4591,59 @@ static void Main(string[] args) [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755746")] public void Fixed_Update_Leaf2() { - var src1 = @" -class Test -{ - public static int value1 = 10; - public static int value2 = 20; - static void Main(string[] args) - { - unsafe - { - int* px2; - fixed (int* a = &value1) + var src1 = """ + + class Test { - fixed (int* b = &value1) + public static int value1 = 10; + public static int value2 = 20; + static void Main(string[] args) { - fixed (int* c = &value1) + unsafe { - px2 = null; + int* px2; + fixed (int* a = &value1) + { + fixed (int* b = &value1) + { + fixed (int* c = &value1) + { + px2 = null; + } + } + } } } } - } - } -}"; - var src2 = @" -class Test -{ - public static int value1 = 10; - public static int value2 = 20; - static void Main(string[] args) - { - unsafe - { - int* px2; - fixed (int* c = &value1) + """; + var src2 = """ + + class Test { - fixed (int* d = &value1) + public static int value1 = 10; + public static int value2 = 20; + static void Main(string[] args) { - fixed (int* a = &value2) + unsafe { - fixed (int* e = &value1) + int* px2; + fixed (int* c = &value1) { - px2 = null; + fixed (int* d = &value1) + { + fixed (int* a = &value2) + { + fixed (int* e = &value1) + { + px2 = null; + } + } + } } } } } - } - } -}"; + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -4220,35 +4656,39 @@ static void Main(string[] args) [Fact] public void Fixed_Delete_Leaf() { - var src1 = @" -class Test -{ - static int value = 20; - static void Main(string[] args) - { - unsafe - { - int* px2; - fixed (int* pj = &value) + var src1 = """ + + class Test { - px2 = null; + static int value = 20; + static void Main(string[] args) + { + unsafe + { + int* px2; + fixed (int* pj = &value) + { + px2 = null; + } + } + } } - } - } -}"; - var src2 = @" -class Test -{ - static int value = 20; - static void Main(string[] args) - { - unsafe - { - int* px2; - px2 = null; - } - } -}"; + """; + var src2 = """ + + class Test + { + static int value = 20; + static void Main(string[] args) + { + unsafe + { + int* px2; + px2 = null; + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -4258,30 +4698,34 @@ static void Main(string[] args) [Fact] public void Fixed_Update_Lambda1() { - var src1 = @" -class C -{ - static unsafe void Main(string[] args) - { - fixed (byte* p = &F(a => a)) - { - Console.WriteLine(1); - } - } -} -"; - var src2 = @" -class C -{ - static unsafe void Main(string[] args) - { - fixed (byte* p = &F(a => a + 1)) - { - Console.WriteLine(2); - } - } -} -"; + var src1 = """ + + class C + { + static unsafe void Main(string[] args) + { + fixed (byte* p = &F(a => a)) + { + Console.WriteLine(1); + } + } + } + + """; + var src2 = """ + + class C + { + static unsafe void Main(string[] args) + { + fixed (byte* p = &F(a => a + 1)) + { + Console.WriteLine(2); + } + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -4291,30 +4735,34 @@ static unsafe void Main(string[] args) [Fact] public void Fixed_Update_Lambda2() { - var src1 = @" -class C -{ - static unsafe void Main(string[] args) - { - fixed (byte* p = &F(a => a)) - { - Console.WriteLine(1); - } - } -} -"; - var src2 = @" -class C -{ - static unsafe void Main(string[] args) - { - fixed (byte* p = &G(a => a)) - { - Console.WriteLine(1); - } - } -} -"; + var src1 = """ + + class C + { + static unsafe void Main(string[] args) + { + fixed (byte* p = &F(a => a)) + { + Console.WriteLine(1); + } + } + } + + """; + var src2 = """ + + class C + { + static unsafe void Main(string[] args) + { + fixed (byte* p = &G(a => a)) + { + Console.WriteLine(1); + } + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -4329,32 +4777,36 @@ static unsafe void Main(string[] args) [Fact] public void ForEachBody_Update_ExpressionActive() { - var src1 = @" -class Test -{ - private static string F() { return null; } + var src1 = """ - static void Main(string[] args) - { - foreach (char c in F()) - { - System.Console.Write(0); - } - } -}"; - var src2 = @" -class Test -{ - private static string F() { return null; } + class Test + { + private static string F() { return null; } - static void Main(string[] args) - { - foreach (char c in F()) - { - System.Console.Write(1); - } - } -}"; + static void Main(string[] args) + { + foreach (char c in F()) + { + System.Console.Write(0); + } + } + } + """; + var src2 = """ + + class Test + { + private static string F() { return null; } + + static void Main(string[] args) + { + foreach (char c in F()) + { + System.Console.Write(1); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -4364,32 +4816,36 @@ static void Main(string[] args) [Fact] public void ForEachVariableBody_Update_ExpressionActive() { - var src1 = @" -class Test -{ - private static (string, int) F() { return null; } + var src1 = """ - static void Main(string[] args) - { - foreach ((string s, int i) in F()) - { - System.Console.Write(0); - } - } -}"; - var src2 = @" -class Test -{ - private static (string, int) F() { return null; } + class Test + { + private static (string, int) F() { return null; } - static void Main(string[] args) - { - foreach ((string s, int i) in F()) - { - System.Console.Write(1); - } - } -}"; + static void Main(string[] args) + { + foreach ((string s, int i) in F()) + { + System.Console.Write(0); + } + } + } + """; + var src2 = """ + + class Test + { + private static (string, int) F() { return null; } + + static void Main(string[] args) + { + foreach ((string s, int i) in F()) + { + System.Console.Write(1); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -4399,32 +4855,36 @@ static void Main(string[] args) [Fact] public void ForEachBody_Update_InKeywordActive() { - var src1 = @" -class Test -{ - private static string F() { return null; } + var src1 = """ - static void Main(string[] args) - { - foreach (char c in F()) - { - System.Console.Write(0); - } - } -}"; - var src2 = @" -class Test -{ - private static string F() { return null; } + class Test + { + private static string F() { return null; } - static void Main(string[] args) - { - foreach (char c in F()) - { - System.Console.Write(1); - } - } -}"; + static void Main(string[] args) + { + foreach (char c in F()) + { + System.Console.Write(0); + } + } + } + """; + var src2 = """ + + class Test + { + private static string F() { return null; } + + static void Main(string[] args) + { + foreach (char c in F()) + { + System.Console.Write(1); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -4434,32 +4894,36 @@ static void Main(string[] args) [Fact] public void ForEachVariableBody_Update_InKeywordActive() { - var src1 = @" -class Test -{ - private static (string, int) F() { return null; } + var src1 = """ - static void Main(string[] args) - { - foreach ((string s, int i) in F()) - { - System.Console.Write(0); - } - } -}"; - var src2 = @" -class Test -{ - private static (string, int) F() { return null; } + class Test + { + private static (string, int) F() { return null; } - static void Main(string[] args) - { - foreach ((string s, int i) in F()) - { - System.Console.Write(1); - } - } -}"; + static void Main(string[] args) + { + foreach ((string s, int i) in F()) + { + System.Console.Write(0); + } + } + } + """; + var src2 = """ + + class Test + { + private static (string, int) F() { return null; } + + static void Main(string[] args) + { + foreach ((string s, int i) in F()) + { + System.Console.Write(1); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -4469,32 +4933,36 @@ static void Main(string[] args) [Fact] public void ForEachBody_Update_VariableActive() { - var src1 = @" -class Test -{ - private static string[] F() { return null; } + var src1 = """ - static void Main(string[] args) - { - foreach (string c in F()) - { - System.Console.Write(0); - } - } -}"; - var src2 = @" -class Test -{ - private static string[] F() { return null; } + class Test + { + private static string[] F() { return null; } - static void Main(string[] args) - { - foreach (string c in F()) - { - System.Console.Write(1); - } - } -}"; + static void Main(string[] args) + { + foreach (string c in F()) + { + System.Console.Write(0); + } + } + } + """; + var src2 = """ + + class Test + { + private static string[] F() { return null; } + + static void Main(string[] args) + { + foreach (string c in F()) + { + System.Console.Write(1); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -4504,34 +4972,38 @@ static void Main(string[] args) [Fact] public void ForEachVariableBody_Update_VariableActive() { - var src1 = @" -class Test -{ - private static (string, int) F() { return null; } - - static void Main(string[] args) - { - foreach ((string s, int i) in F()) - { - System.Console.Write(0); - } - } -}"; - var src2 = @" -class Test -{ - private static (string, int) F() { return null; } + var src1 = """ - static void Main(string[] args) - { - foreach ((string s, int i) in F()) - { - System.Console.Write(1); - } - } -}"; - var edits = GetTopEdits(src1, src2); - var active = GetActiveStatements(src1, src2); + class Test + { + private static (string, int) F() { return null; } + + static void Main(string[] args) + { + foreach ((string s, int i) in F()) + { + System.Console.Write(0); + } + } + } + """; + var src2 = """ + + class Test + { + private static (string, int) F() { return null; } + + static void Main(string[] args) + { + foreach ((string s, int i) in F()) + { + System.Console.Write(1); + } + } + } + """; + var edits = GetTopEdits(src1, src2); + var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active); } @@ -4539,32 +5011,36 @@ static void Main(string[] args) [Fact] public void ForEachBody_Update_ForeachKeywordActive() { - var src1 = @" -class Test -{ - private static string F() { return null; } + var src1 = """ - static void Main(string[] args) - { - foreach (char c in F()) - { - System.Console.Write(0); - } - } -}"; - var src2 = @" -class Test -{ - private static string F() { return null; } + class Test + { + private static string F() { return null; } - static void Main(string[] args) - { - foreach (char c in F()) - { - System.Console.Write(1); - } - } -}"; + static void Main(string[] args) + { + foreach (char c in F()) + { + System.Console.Write(0); + } + } + } + """; + var src2 = """ + + class Test + { + private static string F() { return null; } + + static void Main(string[] args) + { + foreach (char c in F()) + { + System.Console.Write(1); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -4574,32 +5050,36 @@ static void Main(string[] args) [Fact] public void ForEachVariableBody_Update_ForeachKeywordActive() { - var src1 = @" -class Test -{ - private static (string, int) F() { return null; } + var src1 = """ - static void Main(string[] args) - { - foreach ((string s, int i) in F()) - { - System.Console.Write(0); - } - } -}"; - var src2 = @" -class Test -{ - private static (string, int) F() { return null; } + class Test + { + private static (string, int) F() { return null; } - static void Main(string[] args) - { - foreach ((string s, int i) in F()) - { - System.Console.Write(1); - } - } -}"; + static void Main(string[] args) + { + foreach ((string s, int i) in F()) + { + System.Console.Write(0); + } + } + } + """; + var src2 = """ + + class Test + { + private static (string, int) F() { return null; } + + static void Main(string[] args) + { + foreach ((string s, int i) in F()) + { + System.Console.Write(1); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -4609,32 +5089,36 @@ static void Main(string[] args) [Fact] public void ForEachVariable_Update() { - var src1 = @" -class Test -{ - private static string[] F() { return null; } + var src1 = """ - static void Main(string[] args) - { - foreach (string c in F()) - { - System.Console.Write(0); - } - } -}"; - var src2 = @" -class Test -{ - private static string[] F() { return null; } + class Test + { + private static string[] F() { return null; } - static void Main(string[] args) - { - foreach (object c in F()) - { - System.Console.Write(1); - } - } -}"; + static void Main(string[] args) + { + foreach (string c in F()) + { + System.Console.Write(0); + } + } + } + """; + var src2 = """ + + class Test + { + private static string[] F() { return null; } + + static void Main(string[] args) + { + foreach (object c in F()) + { + System.Console.Write(1); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -4647,32 +5131,36 @@ static void Main(string[] args) [Fact] public void ForEachDeconstructionVariable_Update() { - var src1 = @" -class Test -{ - private static (int, (bool, double))[] F() { return new[] { (1, (true, 2.0)) }; } + var src1 = """ - static void Main(string[] args) - { - foreach ((int i, (bool b, double d)) in F()) - { - System.Console.Write(0); - } - } -}"; - var src2 = @" -class Test -{ - private static (int, (bool, double))[] F() { return new[] { (1, (true, 2.0)) }; } + class Test + { + private static (int, (bool, double))[] F() { return new[] { (1, (true, 2.0)) }; } - static void Main(string[] args) - { - foreach ((int i, (var b, double d)) in F()) - { - System.Console.Write(1); - } - } -}"; + static void Main(string[] args) + { + foreach ((int i, (bool b, double d)) in F()) + { + System.Console.Write(0); + } + } + } + """; + var src2 = """ + + class Test + { + private static (int, (bool, double))[] F() { return new[] { (1, (true, 2.0)) }; } + + static void Main(string[] args) + { + foreach ((int i, (var b, double d)) in F()) + { + System.Console.Write(1); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -4684,46 +5172,50 @@ static void Main(string[] args) [Fact] public void ForEach_Reorder_Leaf() { - var src1 = @" -class Test -{ - public static int[] e1 = new int[1]; - public static int[] e2 = new int[1]; - - static void Main(string[] args) - { - foreach (var a in e1) - { - foreach (var b in e1) + var src1 = """ + + class Test { - foreach (var c in e1) + public static int[] e1 = new int[1]; + public static int[] e2 = new int[1]; + + static void Main(string[] args) { - System.Console.Write(); + foreach (var a in e1) + { + foreach (var b in e1) + { + foreach (var c in e1) + { + System.Console.Write(); + } + } + } } } - } - } -}"; - var src2 = @" -class Test -{ - public static int[] e1 = new int[1]; - public static int[] e2 = new int[1]; - - static void Main(string[] args) - { - foreach (var b in e1) - { - foreach (var c in e1) + """; + var src2 = """ + + class Test { - foreach (var a in e1) + public static int[] e1 = new int[1]; + public static int[] e2 = new int[1]; + + static void Main(string[] args) { - System.Console.Write(); + foreach (var b in e1) + { + foreach (var c in e1) + { + foreach (var a in e1) + { + System.Console.Write(); + } + } + } } } - } - } -}"; + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -4733,46 +5225,50 @@ static void Main(string[] args) [Fact] public void ForEachVariable_Reorder_Leaf() { - var src1 = @" -class Test -{ - public static (int, bool)[] e1 = new (int, bool)[1]; - public static (int, bool)[] e2 = new (int, bool)[1]; - - static void Main(string[] args) - { - foreach ((var a1, var a2) in e1) - { - foreach ((int b1, bool b2) in e1) + var src1 = """ + + class Test { - foreach (var c in e1) + public static (int, bool)[] e1 = new (int, bool)[1]; + public static (int, bool)[] e2 = new (int, bool)[1]; + + static void Main(string[] args) { - System.Console.Write(); + foreach ((var a1, var a2) in e1) + { + foreach ((int b1, bool b2) in e1) + { + foreach (var c in e1) + { + System.Console.Write(); + } + } + } } } - } - } -}"; - var src2 = @" -class Test -{ - public static (int, bool)[] e1 = new (int, bool)[1]; - public static (int, bool)[] e2 = new (int, bool)[1]; - - static void Main(string[] args) - { - foreach ((int b1, bool b2) in e1) - { - foreach (var c in e1) + """; + var src2 = """ + + class Test { - foreach ((var a1, var a2) in e1) + public static (int, bool)[] e1 = new (int, bool)[1]; + public static (int, bool)[] e2 = new (int, bool)[1]; + + static void Main(string[] args) { - System.Console.Write(); + foreach ((int b1, bool b2) in e1) + { + foreach (var c in e1) + { + foreach ((var a1, var a2) in e1) + { + System.Console.Write(); + } + } + } } } - } - } -}"; + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -4782,37 +5278,41 @@ static void Main(string[] args) [Fact] public void ForEach_Update_Leaf() { - var src1 = @" -class Test -{ - public static int[] e1 = new int[1]; - public static int[] e2 = new int[1]; - - static void Main(string[] args) - { - System.Console.Write(); - } -}"; - var src2 = @" -class Test -{ - public static int[] e1 = new int[1]; - public static int[] e2 = new int[1]; - - static void Main(string[] args) - { - foreach (var b in e1) - { - foreach (var c in e1) + var src1 = """ + + class Test { - foreach (var a in e1) + public static int[] e1 = new int[1]; + public static int[] e2 = new int[1]; + + static void Main(string[] args) { System.Console.Write(); } } - } - } -}"; + """; + var src2 = """ + + class Test + { + public static int[] e1 = new int[1]; + public static int[] e2 = new int[1]; + + static void Main(string[] args) + { + foreach (var b in e1) + { + foreach (var c in e1) + { + foreach (var a in e1) + { + System.Console.Write(); + } + } + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -4825,37 +5325,41 @@ static void Main(string[] args) [Fact] public void ForEachVariable_Update_Leaf() { - var src1 = @" -class Test -{ - public static (int, bool)[] e1 = new (int, bool)[1]; - public static (int, bool)[] e2 = new (int, bool)[1]; - - static void Main(string[] args) - { - System.Console.Write(); - } -}"; - var src2 = @" -class Test -{ - public static (int, bool)[] e1 = new (int, bool)[1]; - public static (int, bool)[] e2 = new (int, bool)[1]; - - static void Main(string[] args) - { - foreach ((int b1, bool b2) in e1) - { - foreach (var c in e1) + var src1 = """ + + class Test { - foreach ((var a1, var a2) in e1) + public static (int, bool)[] e1 = new (int, bool)[1]; + public static (int, bool)[] e2 = new (int, bool)[1]; + + static void Main(string[] args) { System.Console.Write(); } } - } - } -}"; + """; + var src2 = """ + + class Test + { + public static (int, bool)[] e1 = new (int, bool)[1]; + public static (int, bool)[] e2 = new (int, bool)[1]; + + static void Main(string[] args) + { + foreach ((int b1, bool b2) in e1) + { + foreach (var c in e1) + { + foreach ((var a1, var a2) in e1) + { + System.Console.Write(); + } + } + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -4868,43 +5372,47 @@ static void Main(string[] args) [Fact] public void ForEach_Delete_Leaf1() { - var src1 = @" -class Test -{ - public static int[] e1 = new int[1]; - public static int[] e2 = new int[1]; - - static void Main(string[] args) - { - foreach (var a in e1) - { - foreach (var b in e1) + var src1 = """ + + class Test { - foreach (var c in e1) + public static int[] e1 = new int[1]; + public static int[] e2 = new int[1]; + + static void Main(string[] args) { - System.Console.Write(); + foreach (var a in e1) + { + foreach (var b in e1) + { + foreach (var c in e1) + { + System.Console.Write(); + } + } + } } } - } - } -}"; - var src2 = @" -class Test -{ - public static int[] e1 = new int[1]; - public static int[] e2 = new int[1]; - - static void Main(string[] args) - { - foreach (var a in e1) - { - foreach (var b in e1) + """; + var src2 = """ + + class Test { - System.Console.Write(); + public static int[] e1 = new int[1]; + public static int[] e2 = new int[1]; + + static void Main(string[] args) + { + foreach (var a in e1) + { + foreach (var b in e1) + { + System.Console.Write(); + } + } + } } - } - } -}"; + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -4914,43 +5422,47 @@ static void Main(string[] args) [Fact] public void ForEachVariable_Delete_Leaf1() { - var src1 = @" -class Test -{ - public static (int, bool)[] e1 = new (int, bool)[1]; - public static (int, bool)[] e2 = new (int, bool)[1]; - - static void Main(string[] args) - { - foreach ((var a1, var a2) in e1) - { - foreach ((int b1, bool b2) in e1) + var src1 = """ + + class Test { - foreach (var c in e1) + public static (int, bool)[] e1 = new (int, bool)[1]; + public static (int, bool)[] e2 = new (int, bool)[1]; + + static void Main(string[] args) { - System.Console.Write(); + foreach ((var a1, var a2) in e1) + { + foreach ((int b1, bool b2) in e1) + { + foreach (var c in e1) + { + System.Console.Write(); + } + } + } } } - } - } -}"; - var src2 = @" -class Test -{ - public static (int, bool)[] e1 = new (int, bool)[1]; - public static (int, bool)[] e2 = new (int, bool)[1]; - - static void Main(string[] args) - { - foreach ((var a1, var a2) in e1) - { - foreach ((int b1, bool b2) in e1) + """; + var src2 = """ + + class Test { - System.Console.Write(); + public static (int, bool)[] e1 = new (int, bool)[1]; + public static (int, bool)[] e2 = new (int, bool)[1]; + + static void Main(string[] args) + { + foreach ((var a1, var a2) in e1) + { + foreach ((int b1, bool b2) in e1) + { + System.Console.Write(); + } + } + } } - } - } -}"; + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -4960,43 +5472,47 @@ static void Main(string[] args) [Fact] public void ForEach_Delete_Leaf2() { - var src1 = @" -class Test -{ - public static int[] e1 = new int[1]; - public static int[] e2 = new int[1]; - - static void Main(string[] args) - { - foreach (var a in e1) - { - foreach (var b in e1) + var src1 = """ + + class Test { - foreach (var c in e1) + public static int[] e1 = new int[1]; + public static int[] e2 = new int[1]; + + static void Main(string[] args) { - System.Console.Write(); + foreach (var a in e1) + { + foreach (var b in e1) + { + foreach (var c in e1) + { + System.Console.Write(); + } + } + } } } - } - } -}"; - var src2 = @" -class Test -{ - public static int[] e1 = new int[1]; - public static int[] e2 = new int[1]; - - static void Main(string[] args) - { - foreach (var b in e1) - { - foreach (var c in e1) + """; + var src2 = """ + + class Test { - System.Console.Write(); + public static int[] e1 = new int[1]; + public static int[] e2 = new int[1]; + + static void Main(string[] args) + { + foreach (var b in e1) + { + foreach (var c in e1) + { + System.Console.Write(); + } + } + } } - } - } -}"; + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -5006,43 +5522,47 @@ static void Main(string[] args) [Fact] public void ForEachVariable_Delete_Leaf2() { - var src1 = @" -class Test -{ - public static (int, bool)[] e1 = new (int, bool)[1]; - public static (int, bool)[] e2 = new (int, bool)[1]; - - static void Main(string[] args) - { - foreach ((var a1, var a2) in e1) - { - foreach ((int b1, bool b2) in e1) + var src1 = """ + + class Test { - foreach (var c in e1) + public static (int, bool)[] e1 = new (int, bool)[1]; + public static (int, bool)[] e2 = new (int, bool)[1]; + + static void Main(string[] args) { - System.Console.Write(); + foreach ((var a1, var a2) in e1) + { + foreach ((int b1, bool b2) in e1) + { + foreach (var c in e1) + { + System.Console.Write(); + } + } + } } } - } - } -}"; - var src2 = @" -class Test -{ - public static (int, bool)[] e1 = new (int, bool)[1]; - public static (int, bool)[] e2 = new (int, bool)[1]; - - static void Main(string[] args) - { - foreach ((int b1, bool b2) in e1) - { - foreach (var c in e1) + """; + var src2 = """ + + class Test { - System.Console.Write(); + public static (int, bool)[] e1 = new (int, bool)[1]; + public static (int, bool)[] e2 = new (int, bool)[1]; + + static void Main(string[] args) + { + foreach ((int b1, bool b2) in e1) + { + foreach (var c in e1) + { + System.Console.Write(); + } + } + } } - } - } -}"; + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -5052,43 +5572,47 @@ static void Main(string[] args) [Fact] public void ForEach_Delete_Leaf3() { - var src1 = @" -class Test -{ - public static int[] e1 = new int[1]; - public static int[] e2 = new int[1]; - - static void Main(string[] args) - { - foreach (var a in e1) - { - foreach (var b in e1) + var src1 = """ + + class Test { - foreach (var c in e1) + public static int[] e1 = new int[1]; + public static int[] e2 = new int[1]; + + static void Main(string[] args) { - System.Console.Write(); + foreach (var a in e1) + { + foreach (var b in e1) + { + foreach (var c in e1) + { + System.Console.Write(); + } + } + } } } - } - } -}"; - var src2 = @" -class Test -{ - public static int[] e1 = new int[1]; - public static int[] e2 = new int[1]; - - static void Main(string[] args) - { - foreach (var a in e1) - { - foreach (var c in e1) + """; + var src2 = """ + + class Test { - System.Console.Write(); + public static int[] e1 = new int[1]; + public static int[] e2 = new int[1]; + + static void Main(string[] args) + { + foreach (var a in e1) + { + foreach (var c in e1) + { + System.Console.Write(); + } + } + } } - } - } -}"; + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -5098,43 +5622,47 @@ static void Main(string[] args) [Fact] public void ForEachVariable_Delete_Leaf3() { - var src1 = @" -class Test -{ - public static int[] e1 = new int[1]; - public static int[] e2 = new int[1]; - - static void Main(string[] args) - { - foreach ((var a1, var a2) in e1) - { - foreach ((int b1, bool b2) in e1) + var src1 = """ + + class Test { - foreach (var c in e1) + public static int[] e1 = new int[1]; + public static int[] e2 = new int[1]; + + static void Main(string[] args) { - System.Console.Write(); + foreach ((var a1, var a2) in e1) + { + foreach ((int b1, bool b2) in e1) + { + foreach (var c in e1) + { + System.Console.Write(); + } + } + } } } - } - } -}"; - var src2 = @" -class Test -{ - public static int[] e1 = new int[1]; - public static int[] e2 = new int[1]; - - static void Main(string[] args) - { - foreach ((var a1, var a2) in e1) - { - foreach (var c in e1) + """; + var src2 = """ + + class Test { - System.Console.Write(); + public static int[] e1 = new int[1]; + public static int[] e2 = new int[1]; + + static void Main(string[] args) + { + foreach ((var a1, var a2) in e1) + { + foreach (var c in e1) + { + System.Console.Write(); + } + } + } } - } - } -}"; + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -5144,47 +5672,51 @@ static void Main(string[] args) [Fact] public void ForEach_Lambda1() { - var src1 = @" -class Test -{ - public static int[] e1 = new int[1]; - public static int[] e2 = new int[1]; - - static void Main(string[] args) - { - Action a = () => - { - System.Console.Write(); - }; + var src1 = """ - a(); - } -}"; - var src2 = @" -class Test -{ - public static int[] e1 = new int[1]; - public static int[] e2 = new int[1]; - - static void Main(string[] args) - { - foreach (var b in e1) - { - foreach (var c in e1) + class Test { - Action a = () => - { - foreach (var a in e1) + public static int[] e1 = new int[1]; + public static int[] e2 = new int[1]; + + static void Main(string[] args) + { + Action a = () => { System.Console.Write(); - } - }; + }; + + a(); + } } + """; + var src2 = """ - a(); - } - } -}"; + class Test + { + public static int[] e1 = new int[1]; + public static int[] e2 = new int[1]; + + static void Main(string[] args) + { + foreach (var b in e1) + { + foreach (var c in e1) + { + Action a = () => + { + foreach (var a in e1) + { + System.Console.Write(); + } + }; + } + + a(); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -5196,63 +5728,71 @@ static void Main(string[] args) [Fact] public void ForEach_Update_Lambda1() { - var src1 = @" -class C -{ - static unsafe void Main(string[] args) - { - foreach (var a in F(a => a)) - { - Console.WriteLine(1); - } - } -} -"; - var src2 = @" -class C -{ - static unsafe void Main(string[] args) - { - foreach (var a in F(a => a + 1)) - { - Console.WriteLine(2); - } - } -} -"; - var edits = GetTopEdits(src1, src2); - var active = GetActiveStatements(src1, src2); + var src1 = """ - edits.VerifySemanticDiagnostics(active); - } + class C + { + static unsafe void Main(string[] args) + { + foreach (var a in F(a => a)) + { + Console.WriteLine(1); + } + } + } - [Fact] - public void ForEach_Update_Lambda2() - { - var src1 = @" -class C -{ - static unsafe void Main(string[] args) - { - foreach (var a in F(a => a)) - { - Console.WriteLine(1); - } + """; + var src2 = """ + + class C + { + static unsafe void Main(string[] args) + { + foreach (var a in F(a => a + 1)) + { + Console.WriteLine(2); + } + } + } + + """; + var edits = GetTopEdits(src1, src2); + var active = GetActiveStatements(src1, src2); + + edits.VerifySemanticDiagnostics(active); } -} -"; - var src2 = @" -class C -{ - static unsafe void Main(string[] args) + + [Fact] + public void ForEach_Update_Lambda2() { - foreach (var a in G(a => a)) - { - Console.WriteLine(1); - } - } -} -"; + var src1 = """ + + class C + { + static unsafe void Main(string[] args) + { + foreach (var a in F(a => a)) + { + Console.WriteLine(1); + } + } + } + + """; + var src2 = """ + + class C + { + static unsafe void Main(string[] args) + { + foreach (var a in G(a => a)) + { + Console.WriteLine(1); + } + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -5263,36 +5803,40 @@ static unsafe void Main(string[] args) [Fact] public void ForEach_Update_Collection_01() { - var src1 = @" -class C -{ - static void F() - { - var aa = new int[4]; - var bb = new int[4]; - - foreach (var a in aa) - { - Console.WriteLine(1); - } - } -} -"; - var src2 = @" -class C -{ - static void F() - { - var aa = new int[4]; - var bb = new int[4]; - - foreach (var a in bb) - { - Console.WriteLine(1); - } - } -} -"; + var src1 = """ + + class C + { + static void F() + { + var aa = new int[4]; + var bb = new int[4]; + + foreach (var a in aa) + { + Console.WriteLine(1); + } + } + } + + """; + var src2 = """ + + class C + { + static void F() + { + var aa = new int[4]; + var bb = new int[4]; + + foreach (var a in bb) + { + Console.WriteLine(1); + } + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -5303,48 +5847,52 @@ static void F() [Fact] public void ForEach_Update_Collection_02() { - var src1 = @" -class C -{ - static void F() - { - Buffer4 aa = default; - Buffer4 bb = default; - - foreach (var a in aa) - { - Console.WriteLine(1); - } - } -} + var src1 = """ -[System.Runtime.CompilerServices.InlineArray(4)] -struct Buffer4 -{ - private int _f; -} -"; - var src2 = @" -class C -{ - static void F() - { - Buffer4 aa = default; - Buffer4 bb = default; - - foreach (var a in bb) - { - Console.WriteLine(1); - } - } -} + class C + { + static void F() + { + Buffer4 aa = default; + Buffer4 bb = default; + + foreach (var a in aa) + { + Console.WriteLine(1); + } + } + } -[System.Runtime.CompilerServices.InlineArray(4)] -struct Buffer4 -{ - private int _f; -} -"; + [System.Runtime.CompilerServices.InlineArray(4)] + struct Buffer4 + { + private int _f; + } + + """; + var src2 = """ + + class C + { + static void F() + { + Buffer4 aa = default; + Buffer4 bb = default; + + foreach (var a in bb) + { + Console.WriteLine(1); + } + } + } + + [System.Runtime.CompilerServices.InlineArray(4)] + struct Buffer4 + { + private int _f; + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -5355,54 +5903,58 @@ struct Buffer4 [Fact] public void ForEach_Update_Collection_03() { - var src1 = @" -class C -{ - public readonly Buffer4 F = default; -} + var src1 = """ -class Program -{ - static System.Collections.Generic.IEnumerable Test(C x, C z) - { - foreach (var y in x.F) - { - Console.WriteLine(1); - yield return -1; - } - } -} + class C + { + public readonly Buffer4 F = default; + } -[System.Runtime.CompilerServices.InlineArray(4)] -struct Buffer4 -{ - private int _f; -} -"; - var src2 = @" -class C -{ - public readonly Buffer4 F = default; -} + class Program + { + static System.Collections.Generic.IEnumerable Test(C x, C z) + { + foreach (var y in x.F) + { + Console.WriteLine(1); + yield return -1; + } + } + } -class Program -{ - static System.Collections.Generic.IEnumerable Test(C x, C z) - { - foreach (var y in z.F) - { - Console.WriteLine(1); - yield return -1; - } - } -} + [System.Runtime.CompilerServices.InlineArray(4)] + struct Buffer4 + { + private int _f; + } -[System.Runtime.CompilerServices.InlineArray(4)] -struct Buffer4 -{ - private int _f; -} -"; + """; + var src2 = """ + + class C + { + public readonly Buffer4 F = default; + } + + class Program + { + static System.Collections.Generic.IEnumerable Test(C x, C z) + { + foreach (var y in z.F) + { + Console.WriteLine(1); + yield return -1; + } + } + } + + [System.Runtime.CompilerServices.InlineArray(4)] + struct Buffer4 + { + private int _f; + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -5413,50 +5965,54 @@ struct Buffer4 [Fact] public void ForEach_Update_Collection_04() { - var src1 = @" -class Program -{ - static System.Collections.Generic.IEnumerable Test() - { - foreach (var y in GetBuffer1()) - { - Console.WriteLine(1); - yield return -1; - } - } + var src1 = """ - static Buffer4 GetBuffer1() => default; - static Buffer4 GetBuffer2() => default; -} + class Program + { + static System.Collections.Generic.IEnumerable Test() + { + foreach (var y in GetBuffer1()) + { + Console.WriteLine(1); + yield return -1; + } + } -[System.Runtime.CompilerServices.InlineArray(4)] -struct Buffer4 -{ - private int _f; -} -"; - var src2 = @" -class Program -{ - static System.Collections.Generic.IEnumerable Test() - { - foreach (var y in GetBuffer2()) - { - Console.WriteLine(1); - yield return -1; - } - } + static Buffer4 GetBuffer1() => default; + static Buffer4 GetBuffer2() => default; + } - static Buffer4 GetBuffer1() => default; - static Buffer4 GetBuffer2() => default; -} + [System.Runtime.CompilerServices.InlineArray(4)] + struct Buffer4 + { + private int _f; + } -[System.Runtime.CompilerServices.InlineArray(4)] -struct Buffer4 -{ - private int _f; -} -"; + """; + var src2 = """ + + class Program + { + static System.Collections.Generic.IEnumerable Test() + { + foreach (var y in GetBuffer2()) + { + Console.WriteLine(1); + yield return -1; + } + } + + static Buffer4 GetBuffer1() => default; + static Buffer4 GetBuffer2() => default; + } + + [System.Runtime.CompilerServices.InlineArray(4)] + struct Buffer4 + { + private int _f; + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -5467,68 +6023,76 @@ struct Buffer4 [Fact] public void ForEach_Update_Nullable_Struct() { - var src1 = @" -class C -{ - static void F() - { - var arr = new int?[] { 0 }; - foreach (var s in arr) - { - Console.WriteLine(1); - } - } -} -"; - var src2 = @" -class C -{ - static void F() - { - var arr = new int[] { 0 }; - foreach (var s in arr) - { - Console.WriteLine(1); - } - } -} -"; - var edits = GetTopEdits(src1, src2); - var active = GetActiveStatements(src1, src2); - - edits.VerifySemanticDiagnostics(active, - Diagnostic(RudeEditKind.TypeUpdateAroundActiveStatement, "foreach (var s in arr)", CSharpFeaturesResources.foreach_statement, "int?[]", "int[]")); - } + var src1 = """ - [Fact] - public void ForEach_Update_Nullable_Class() - { - var src1 = @" -class C -{ - static void F() - { - var arr = new object?[] { 0 }; - foreach (var s in arr) - { - Console.WriteLine(1); - } + class C + { + static void F() + { + var arr = new int?[] { 0 }; + foreach (var s in arr) + { + Console.WriteLine(1); + } + } + } + + """; + var src2 = """ + + class C + { + static void F() + { + var arr = new int[] { 0 }; + foreach (var s in arr) + { + Console.WriteLine(1); + } + } + } + + """; + var edits = GetTopEdits(src1, src2); + var active = GetActiveStatements(src1, src2); + + edits.VerifySemanticDiagnostics(active, + Diagnostic(RudeEditKind.TypeUpdateAroundActiveStatement, "foreach (var s in arr)", CSharpFeaturesResources.foreach_statement, "int?[]", "int[]")); } -} -"; - var src2 = @" -class C -{ - static void F() + + [Fact] + public void ForEach_Update_Nullable_Class() { - var arr = new object[] { 0 }; - foreach (var s in arr) - { - Console.WriteLine(1); - } - } -} -"; + var src1 = """ + + class C + { + static void F() + { + var arr = new object?[] { 0 }; + foreach (var s in arr) + { + Console.WriteLine(1); + } + } + } + + """; + var src2 = """ + + class C + { + static void F() + { + var arr = new object[] { 0 }; + foreach (var s in arr) + { + Console.WriteLine(1); + } + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -5538,24 +6102,28 @@ static void F() [Fact] public void ForEach_DeleteBody() { - var src1 = @" -class C -{ - static void F() - { - foreach (var s in new[] { 1 }) G(); - } -} -"; - var src2 = @" -class C -{ - static void F() - { - foreach (var s in new[] { 1 }) ; - } -} -"; + var src1 = """ + + class C + { + static void F() + { + foreach (var s in new[] { 1 }) G(); + } + } + + """; + var src2 = """ + + class C + { + static void F() + { + foreach (var s in new[] { 1 }) ; + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -5565,24 +6133,28 @@ static void F() [Fact] public void ForEachVariable_DeleteBody() { - var src1 = @" -class C -{ - static void F() - { - foreach ((var a1, var a2) in new[] { (1,1) }) G(); - } -} -"; - var src2 = @" -class C -{ - static void F() - { - foreach ((var a1, var a2) in new[] { (1,1) }) ; - } -} -"; + var src1 = """ + + class C + { + static void F() + { + foreach ((var a1, var a2) in new[] { (1,1) }) G(); + } + } + + """; + var src2 = """ + + class C + { + static void F() + { + foreach ((var a1, var a2) in new[] { (1,1) }) ; + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -5596,34 +6168,38 @@ static void F() [Fact] public void ForStatement_Initializer1() { - var src1 = @" -class Test -{ - private static int F(int a) { return a; } + var src1 = """ - static void Main(string[] args) - { - int i; - for (i = F(1); i < 10; i++) - { - System.Console.Write(0); - } - } -}"; - var src2 = @" -class Test -{ - private static int F(int a) { return a; } + class Test + { + private static int F(int a) { return a; } - static void Main(string[] args) - { - int i; - for (i = F(2); i < 10; i++) - { - System.Console.Write(0); - } - } -}"; + static void Main(string[] args) + { + int i; + for (i = F(1); i < 10; i++) + { + System.Console.Write(0); + } + } + } + """; + var src2 = """ + + class Test + { + private static int F(int a) { return a; } + + static void Main(string[] args) + { + int i; + for (i = F(2); i < 10; i++) + { + System.Console.Write(0); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -5634,34 +6210,38 @@ static void Main(string[] args) [Fact] public void ForStatement_Initializer2() { - var src1 = @" -class Test -{ - private static int F(int a) { return a; } + var src1 = """ - static void Main(string[] args) - { - int i; - for (i = F(1), F(1); i < 10; i++) - { - System.Console.Write(0); - } - } -}"; - var src2 = @" -class Test -{ - private static int F(int a) { return a; } + class Test + { + private static int F(int a) { return a; } - static void Main(string[] args) - { - int i; - for (i = F(1), F(2); i < 10; i++) - { - System.Console.Write(0); - } - } -}"; + static void Main(string[] args) + { + int i; + for (i = F(1), F(1); i < 10; i++) + { + System.Console.Write(0); + } + } + } + """; + var src2 = """ + + class Test + { + private static int F(int a) { return a; } + + static void Main(string[] args) + { + int i; + for (i = F(1), F(2); i < 10; i++) + { + System.Console.Write(0); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -5671,34 +6251,38 @@ static void Main(string[] args) [Fact] public void ForStatement_Initializer_Delete() { - var src1 = @" -class Test -{ - private static int F(int a) { return a; } + var src1 = """ - static void Main(string[] args) - { - int i; - for (i = F(1); i < 10; i++) - { - System.Console.Write(0); - } - } -}"; - var src2 = @" -class Test -{ - private static int F(int a) { return a; } + class Test + { + private static int F(int a) { return a; } - static void Main(string[] args) - { - int i; - for (; i < 10; i++) - { - System.Console.Write(0); - } - } -}"; + static void Main(string[] args) + { + int i; + for (i = F(1); i < 10; i++) + { + System.Console.Write(0); + } + } + } + """; + var src2 = """ + + class Test + { + private static int F(int a) { return a; } + + static void Main(string[] args) + { + int i; + for (; i < 10; i++) + { + System.Console.Write(0); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -5709,32 +6293,36 @@ static void Main(string[] args) [Fact] public void ForStatement_Declarator1() { - var src1 = @" -class Test -{ - private static int F(int a) { return a; } + var src1 = """ - static void Main(string[] args) - { - for (var i = F(1); i < 10; i++) - { - System.Console.Write(0); - } - } -}"; - var src2 = @" -class Test -{ - private static int F(int a) { return a; } + class Test + { + private static int F(int a) { return a; } - static void Main(string[] args) - { - for (var i = F(2); i < 10; i++) - { - System.Console.Write(0); - } - } -}"; + static void Main(string[] args) + { + for (var i = F(1); i < 10; i++) + { + System.Console.Write(0); + } + } + } + """; + var src2 = """ + + class Test + { + private static int F(int a) { return a; } + + static void Main(string[] args) + { + for (var i = F(2); i < 10; i++) + { + System.Console.Write(0); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -5745,67 +6333,75 @@ static void Main(string[] args) [Fact] public void ForStatement_Declarator2() { - var src1 = @" -class Test -{ - private static int F(int a) { return a; } + var src1 = """ - static void Main(string[] args) - { - for (int i = F(1), j = F(1); i < 10; i++) - { - System.Console.Write(0); - } - } -}"; - var src2 = @" -class Test -{ - private static int F(int a) { return a; } + class Test + { + private static int F(int a) { return a; } - static void Main(string[] args) - { - for (int i = F(1), j = F(2); i < 10; i++) - { - System.Console.Write(0); - } - } -}"; - var edits = GetTopEdits(src1, src2); - var active = GetActiveStatements(src1, src2); + static void Main(string[] args) + { + for (int i = F(1), j = F(1); i < 10; i++) + { + System.Console.Write(0); + } + } + } + """; + var src2 = """ - edits.VerifySemanticDiagnostics(active); + class Test + { + private static int F(int a) { return a; } + + static void Main(string[] args) + { + for (int i = F(1), j = F(2); i < 10; i++) + { + System.Console.Write(0); + } + } + } + """; + var edits = GetTopEdits(src1, src2); + var active = GetActiveStatements(src1, src2); + + edits.VerifySemanticDiagnostics(active); } [Fact] public void ForStatement_Declarator3() { - var src1 = @" -class Test -{ - private static int F(int a) { return a; } + var src1 = """ - static void Main(string[] args) - { - for (int i = F(1); i < 10; i++) - { - System.Console.Write(0); - } - } -}"; - var src2 = @" -class Test -{ - private static int F(int a) { return a; } + class Test + { + private static int F(int a) { return a; } - static void Main(string[] args) - { - for (int i = F(1), j = F(2); i < 10; i++) - { - System.Console.Write(0); - } - } -}"; + static void Main(string[] args) + { + for (int i = F(1); i < 10; i++) + { + System.Console.Write(0); + } + } + } + """; + var src2 = """ + + class Test + { + private static int F(int a) { return a; } + + static void Main(string[] args) + { + for (int i = F(1), j = F(2); i < 10; i++) + { + System.Console.Write(0); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -5815,32 +6411,36 @@ static void Main(string[] args) [Fact] public void ForStatement_Condition1() { - var src1 = @" -class Test -{ - private static int F(int a) { return a; } + var src1 = """ - static void Main(string[] args) - { - for (int i = 1; i < F(10); i++) - { - System.Console.Write(0); - } - } -}"; - var src2 = @" -class Test -{ - private static int F(int a) { return a; } + class Test + { + private static int F(int a) { return a; } - static void Main(string[] args) - { - for (int i = 1; i < F(20); i++) - { - System.Console.Write(0); - } - } -}"; + static void Main(string[] args) + { + for (int i = 1; i < F(10); i++) + { + System.Console.Write(0); + } + } + } + """; + var src2 = """ + + class Test + { + private static int F(int a) { return a; } + + static void Main(string[] args) + { + for (int i = 1; i < F(20); i++) + { + System.Console.Write(0); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -5851,32 +6451,36 @@ static void Main(string[] args) [Fact] public void ForStatement_Condition_Delete() { - var src1 = @" -class Test -{ - private static int F(int a) { return a; } + var src1 = """ - static void Main(string[] args) - { - for (int i = 1; i < F(10); i++) - { - System.Console.Write(0); - } - } -}"; - var src2 = @" -class Test -{ - private static int F(int a) { return a; } + class Test + { + private static int F(int a) { return a; } - static void Main(string[] args) - { - for (int i = 1; ; i++) - { - System.Console.Write(0); - } - } -}"; + static void Main(string[] args) + { + for (int i = 1; i < F(10); i++) + { + System.Console.Write(0); + } + } + } + """; + var src2 = """ + + class Test + { + private static int F(int a) { return a; } + + static void Main(string[] args) + { + for (int i = 1; ; i++) + { + System.Console.Write(0); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -5887,32 +6491,36 @@ static void Main(string[] args) [Fact] public void ForStatement_Incrementors1() { - var src1 = @" -class Test -{ - private static int F(int a) { return a; } + var src1 = """ - static void Main(string[] args) - { - for (int i = 1; i < F(10); F(1)) - { - System.Console.Write(0); - } - } -}"; - var src2 = @" -class Test -{ - private static int F(int a) { return a; } + class Test + { + private static int F(int a) { return a; } - static void Main(string[] args) - { - for (int i = 1; i < F(20); F(1)) - { - System.Console.Write(0); - } - } -}"; + static void Main(string[] args) + { + for (int i = 1; i < F(10); F(1)) + { + System.Console.Write(0); + } + } + } + """; + var src2 = """ + + class Test + { + private static int F(int a) { return a; } + + static void Main(string[] args) + { + for (int i = 1; i < F(20); F(1)) + { + System.Console.Write(0); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -5922,32 +6530,36 @@ static void Main(string[] args) [Fact] public void ForStatement_Incrementors2() { - var src1 = @" -class Test -{ - private static int F(int a) { return a; } + var src1 = """ - static void Main(string[] args) - { - for (int i = 1; i < F(10); F(1)) - { - System.Console.Write(0); - } - } -}"; - var src2 = @" -class Test -{ - private static int F(int a) { return a; } + class Test + { + private static int F(int a) { return a; } - static void Main(string[] args) - { - for (int i = 1; i < F(10); F(2)) - { - System.Console.Write(0); - } - } -}"; + static void Main(string[] args) + { + for (int i = 1; i < F(10); F(1)) + { + System.Console.Write(0); + } + } + } + """; + var src2 = """ + + class Test + { + private static int F(int a) { return a; } + + static void Main(string[] args) + { + for (int i = 1; i < F(10); F(2)) + { + System.Console.Write(0); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -5958,32 +6570,36 @@ static void Main(string[] args) [Fact] public void ForStatement_Incrementors3() { - var src1 = @" -class Test -{ - private static int F(int a) { return a; } + var src1 = """ - static void Main(string[] args) - { - for (int i = 1; i < F(10); F(1)) - { - System.Console.Write(0); - } - } -}"; - var src2 = @" -class Test -{ - private static int F(int a) { return a; } + class Test + { + private static int F(int a) { return a; } - static void Main(string[] args) - { - for (int i = 1; i < F(10); F(1), i++) - { - System.Console.Write(0); - } - } -}"; + static void Main(string[] args) + { + for (int i = 1; i < F(10); F(1)) + { + System.Console.Write(0); + } + } + } + """; + var src2 = """ + + class Test + { + private static int F(int a) { return a; } + + static void Main(string[] args) + { + for (int i = 1; i < F(10); F(1), i++) + { + System.Console.Write(0); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -5993,32 +6609,36 @@ static void Main(string[] args) [Fact] public void ForStatement_Incrementors4() { - var src1 = @" -class Test -{ - private static int F(int a) { return a; } + var src1 = """ - static void Main(string[] args) - { - for (int i = 1; i < F(10); F(1), i++) - { - System.Console.Write(0); - } - } -}"; - var src2 = @" -class Test -{ - private static int F(int a) { return a; } + class Test + { + private static int F(int a) { return a; } - static void Main(string[] args) - { - for (int i = 1; i < F(10); i++, F(1)) - { - System.Console.Write(0); - } - } -}"; + static void Main(string[] args) + { + for (int i = 1; i < F(10); F(1), i++) + { + System.Console.Write(0); + } + } + } + """; + var src2 = """ + + class Test + { + private static int F(int a) { return a; } + + static void Main(string[] args) + { + for (int i = 1; i < F(10); i++, F(1)) + { + System.Console.Write(0); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -6032,45 +6652,49 @@ static void Main(string[] args) [Fact] public void UsingStatement_Expression_Update_Leaf() { - var src1 = @" -class Test -{ - public static System.IDisposable a = null; - public static System.IDisposable b = null; - public static System.IDisposable c = null; - - static void Main(string[] args) - { - using (a) - { - using (b) + var src1 = """ + + class Test { - System.Console.Write(); + public static System.IDisposable a = null; + public static System.IDisposable b = null; + public static System.IDisposable c = null; + + static void Main(string[] args) + { + using (a) + { + using (b) + { + System.Console.Write(); + } + } + } } - } - } -}"; - var src2 = @" -class Test -{ - public static System.IDisposable a = null; - public static System.IDisposable b = null; - public static System.IDisposable c = null; - - static void Main(string[] args) - { - using (a) - { - using (c) + """; + var src2 = """ + + class Test { - using (b) + public static System.IDisposable a = null; + public static System.IDisposable b = null; + public static System.IDisposable c = null; + + static void Main(string[] args) { - System.Console.Write(); + using (a) + { + using (c) + { + using (b) + { + System.Console.Write(); + } + } + } } } - } - } -}"; + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -6132,37 +6756,41 @@ class D2 : IDisposable { public void Dispose() { } } [Fact] public void UsingStatement_Declaration_Update_Leaf() { - var src1 = @" -class Test -{ - static void Main(string[] args) - { - using (var a = new Disposable()) - { - using (var b = new Disposable()) - { - System.Console.Write(); - } - } - } -}"; - var src2 = @" -class Test -{ - static void Main(string[] args) - { - using (var a = new Disposable()) - { - using (var c = new Disposable()) + var src1 = """ + + class Test { - using (var b = new Disposable()) + static void Main(string[] args) { - System.Console.Write(); - } - } - } - } -}"; + using (var a = new Disposable()) + { + using (var b = new Disposable()) + { + System.Console.Write(); + } + } + } + } + """; + var src2 = """ + + class Test + { + static void Main(string[] args) + { + using (var a = new Disposable()) + { + using (var c = new Disposable()) + { + using (var b = new Disposable()) + { + System.Console.Write(); + } + } + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -6175,24 +6803,28 @@ static void Main(string[] args) [Fact] public void UsingLocalDeclaration_Update_Leaf1() { - var src1 = @" -class Test -{ - static void Main(string[] args) - { - using var a = new Disposable(), b = new Disposable(); - System.Console.Write(); - } -}"; - var src2 = @" -class Test -{ - static void Main(string[] args) - { - using var a = new Disposable(), c = new Disposable(), b = new Disposable(); - System.Console.Write(); - } -}"; + var src1 = """ + + class Test + { + static void Main(string[] args) + { + using var a = new Disposable(), b = new Disposable(); + System.Console.Write(); + } + } + """; + var src2 = """ + + class Test + { + static void Main(string[] args) + { + using var a = new Disposable(), c = new Disposable(), b = new Disposable(); + System.Console.Write(); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -6205,27 +6837,31 @@ static void Main(string[] args) [Fact] public void UsingLocalDeclaration_Update_Leaf2() { - var src1 = @" -class Test -{ - static void Main(string[] args) - { - using var a = new Disposable(); - using var b = new Disposable(); - System.Console.Write(); - } -}"; - var src2 = @" -class Test -{ - static void Main(string[] args) - { - using var a = new Disposable(); - using var c = new Disposable(); - using var b = new Disposable(); - System.Console.Write(); - } -}"; + var src1 = """ + + class Test + { + static void Main(string[] args) + { + using var a = new Disposable(); + using var b = new Disposable(); + System.Console.Write(); + } + } + """; + var src2 = """ + + class Test + { + static void Main(string[] args) + { + using var a = new Disposable(); + using var c = new Disposable(); + using var b = new Disposable(); + System.Console.Write(); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -6238,32 +6874,36 @@ static void Main(string[] args) [Fact] public void UsingStatement_Update_NonLeaf1() { - var src1 = @" -class Disposable : IDisposable -{ - public void Dispose() {} -} + var src1 = """ -class Test -{ - static void Main(string[] args) - { - using (var a = new Disposable(1)) { System.Console.Write(); } - } -}"; - var src2 = @" -class Disposable : IDisposable -{ - public void Dispose() {} -} + class Disposable : IDisposable + { + public void Dispose() {} + } -class Test -{ - static void Main(string[] args) - { - using (var a = new Disposable(2)) { System.Console.Write(); } - } -}"; + class Test + { + static void Main(string[] args) + { + using (var a = new Disposable(1)) { System.Console.Write(); } + } + } + """; + var src2 = """ + + class Disposable : IDisposable + { + public void Dispose() {} + } + + class Test + { + static void Main(string[] args) + { + using (var a = new Disposable(2)) { System.Console.Write(); } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -6274,32 +6914,36 @@ static void Main(string[] args) [Fact] public void UsingStatement_Update_NonLeaf2() { - var src1 = @" -class Disposable : IDisposable -{ - public void Dispose() {} -} + var src1 = """ -class Test -{ - static void Main(string[] args) - { - using (Disposable a = new Disposable(1), b = Disposable(2)) { System.Console.Write(); } - } -}"; - var src2 = @" -class Disposable : IDisposable -{ - public void Dispose() {} -} + class Disposable : IDisposable + { + public void Dispose() {} + } -class Test -{ - static void Main(string[] args) - { - using (Disposable a = new Disposable(1)) { System.Console.Write(); } - } -}"; + class Test + { + static void Main(string[] args) + { + using (Disposable a = new Disposable(1), b = Disposable(2)) { System.Console.Write(); } + } + } + """; + var src2 = """ + + class Disposable : IDisposable + { + public void Dispose() {} + } + + class Test + { + static void Main(string[] args) + { + using (Disposable a = new Disposable(1)) { System.Console.Write(); } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -6310,32 +6954,36 @@ static void Main(string[] args) [Fact] public void UsingStatement_Update_NonLeaf_Lambda() { - var src1 = @" -class Disposable : IDisposable -{ - public void Dispose() {} -} + var src1 = """ -class Test -{ - static void Main(string[] args) - { - using (var a = new Disposable(() => 1)) { System.Console.Write(); } - } -}"; - var src2 = @" -class Disposable : IDisposable -{ - public void Dispose() {} -} + class Disposable : IDisposable + { + public void Dispose() {} + } -class Test -{ - static void Main(string[] args) - { - using (var a = new Disposable(() => 2)) { System.Console.Write(); } - } -}"; + class Test + { + static void Main(string[] args) + { + using (var a = new Disposable(() => 1)) { System.Console.Write(); } + } + } + """; + var src2 = """ + + class Disposable : IDisposable + { + public void Dispose() {} + } + + class Test + { + static void Main(string[] args) + { + using (var a = new Disposable(() => 2)) { System.Console.Write(); } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -6345,44 +6993,48 @@ static void Main(string[] args) [Fact] public void UsingLocalDeclaration_Update_NonLeaf1() { - var src1 = @" -class Disposable : IDisposable -{ - public void Dispose() {} -} + var src1 = """ -class Test -{ - static void Main(string[] args) - { - if (F()) - { - using Disposable a = new Disposable(1); + class Disposable : IDisposable + { + public void Dispose() {} + } - using Disposable b = new Disposable(2), c = new Disposable(3); + class Test + { + static void Main(string[] args) + { + if (F()) + { + using Disposable a = new Disposable(1); - } - } -}"; - var src2 = @" -class Disposable : IDisposable -{ - public void Dispose() {} -} + using Disposable b = new Disposable(2), c = new Disposable(3); -class Test -{ - static void Main(string[] args) - { - if (F()) - { - using Disposable a = new Disposable(1); + } + } + } + """; + var src2 = """ - using Disposable b = new Disposable(20), c = new Disposable(3); + class Disposable : IDisposable + { + public void Dispose() {} + } - } - } -}"; + class Test + { + static void Main(string[] args) + { + if (F()) + { + using Disposable a = new Disposable(1); + + using Disposable b = new Disposable(20), c = new Disposable(3); + + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -6393,54 +7045,58 @@ static void Main(string[] args) [Fact] public void UsingLocalDeclaration_Update_NonLeaf_Lambda() { - var src1 = @" -class Disposable : IDisposable -{ - public void Dispose() {} -} - -class Test -{ - static void Main(string[] args) - { - if (F()) - { - using Disposable a = new Disposable(() => 1); + var src1 = """ + class Disposable : IDisposable { - using var x = new Disposable(1); + public void Dispose() {} } - using Disposable b = new Disposable(() => 2), c = new Disposable(() => 3); + class Test + { + static void Main(string[] args) + { + if (F()) + { + using Disposable a = new Disposable(() => 1); - } - } -}"; - var src2 = @" -class Disposable : IDisposable -{ - public void Dispose() {} -} + { + using var x = new Disposable(1); + } -class Test -{ - static void Main(string[] args) - { - if (F()) - { - using Disposable a = new Disposable(() => 10); + using Disposable b = new Disposable(() => 2), c = new Disposable(() => 3); + + } + } + } + """; + var src2 = """ + class Disposable : IDisposable { - using var x = new Disposable(2); + public void Dispose() {} } - Console.WriteLine(1); + class Test + { + static void Main(string[] args) + { + if (F()) + { + using Disposable a = new Disposable(() => 10); + + { + using var x = new Disposable(2); + } - using Disposable b = new Disposable(() => 20), c = new Disposable(() => 30); + Console.WriteLine(1); - } - } -}"; + using Disposable b = new Disposable(() => 20), c = new Disposable(() => 30); + + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -6450,57 +7106,61 @@ static void Main(string[] args) [Fact] public void UsingStatement_Expression_InLambdaBody1() { - var src1 = @" -class Test -{ - public static System.IDisposable a = null; - public static System.IDisposable b = null; - public static System.IDisposable c = null; - public static System.IDisposable d = null; - - static void Main(string[] args) - { - using (a) - { - Action a = () => + var src1 = """ + + class Test { - using (b) + public static System.IDisposable a = null; + public static System.IDisposable b = null; + public static System.IDisposable c = null; + public static System.IDisposable d = null; + + static void Main(string[] args) { - System.Console.Write(); + using (a) + { + Action a = () => + { + using (b) + { + System.Console.Write(); + } + }; + } + + a(); } - }; - } + } + """; + var src2 = """ - a(); - } -}"; - var src2 = @" -class Test -{ - public static System.IDisposable a = null; - public static System.IDisposable b = null; - public static System.IDisposable c = null; - public static System.IDisposable d = null; - - static void Main(string[] args) - { - using (d) - { - Action a = () => + class Test { - using (c) + public static System.IDisposable a = null; + public static System.IDisposable b = null; + public static System.IDisposable c = null; + public static System.IDisposable d = null; + + static void Main(string[] args) { - using (b) + using (d) { - System.Console.Write(); + Action a = () => + { + using (c) + { + using (b) + { + System.Console.Write(); + } + } + }; } - } - }; - } - a(); - } -}"; + a(); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -6511,32 +7171,36 @@ static void Main(string[] args) [Fact] public void UsingStatement_Expression_Update_Lambda1() { - var src1 = @" -class C -{ - static unsafe void Main(string[] args) - { - using (F(a => a)) - { - Console.WriteLine(1); - } - } -} -"; - var src2 = @" -class C -{ - static unsafe void Main(string[] args) - { - using (F(a => a + 1)) - { - Console.WriteLine(2); - } - } -} -"; - var edits = GetTopEdits(src1, src2); - var active = GetActiveStatements(src1, src2); + var src1 = """ + + class C + { + static unsafe void Main(string[] args) + { + using (F(a => a)) + { + Console.WriteLine(1); + } + } + } + + """; + var src2 = """ + + class C + { + static unsafe void Main(string[] args) + { + using (F(a => a + 1)) + { + Console.WriteLine(2); + } + } + } + + """; + var edits = GetTopEdits(src1, src2); + var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active); } @@ -6544,30 +7208,34 @@ static unsafe void Main(string[] args) [Fact] public void UsingStatement_Expression_Update_Lambda2() { - var src1 = @" -class C -{ - static unsafe void Main(string[] args) - { - using (F(a => a)) - { - Console.WriteLine(1); - } - } -} -"; - var src2 = @" -class C -{ - static unsafe void Main(string[] args) - { - using (G(a => a)) - { - Console.WriteLine(1); - } - } -} -"; + var src1 = """ + + class C + { + static unsafe void Main(string[] args) + { + using (F(a => a)) + { + Console.WriteLine(1); + } + } + } + + """; + var src2 = """ + + class C + { + static unsafe void Main(string[] args) + { + using (G(a => a)) + { + Console.WriteLine(1); + } + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -6582,32 +7250,36 @@ static unsafe void Main(string[] args) [Fact] public void IfBody_Update1() { - var src1 = @" -class C -{ - public static bool B() { return false; } - - public static void F() - { - if (B()) - { - System.Console.WriteLine(0); - } - } -}"; - var src2 = @" -class C -{ - public static bool B() { return false; } - - public static void F() - { - if (B()) - { - System.Console.WriteLine(1); - } - } -}"; + var src1 = """ + + class C + { + public static bool B() { return false; } + + public static void F() + { + if (B()) + { + System.Console.WriteLine(0); + } + } + } + """; + var src2 = """ + + class C + { + public static bool B() { return false; } + + public static void F() + { + if (B()) + { + System.Console.WriteLine(1); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -6617,32 +7289,36 @@ public static void F() [Fact] public void IfBody_Update2() { - var src1 = @" -class C -{ - public static bool B() { return false; } - - public static void F() - { - if (B()) - { - System.Console.WriteLine(0); - } - } -}"; - var src2 = @" -class C -{ - public static bool B() { return false; } - - public static void F() - { - if (!B()) - { - System.Console.WriteLine(0); - } - } -}"; + var src1 = """ + + class C + { + public static bool B() { return false; } + + public static void F() + { + if (B()) + { + System.Console.WriteLine(0); + } + } + } + """; + var src2 = """ + + class C + { + public static bool B() { return false; } + + public static void F() + { + if (!B()) + { + System.Console.WriteLine(0); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -6653,32 +7329,36 @@ public static void F() [Fact] public void IfBody_Update_Lambda() { - var src1 = @" -class C -{ - public static bool B(Func a) => false; - - public static void F() - { - if (B(() => 1)) - { - System.Console.WriteLine(0); - } - } -}"; - var src2 = @" -class C -{ - public static bool B(Func a) => false; - - public static void F() - { - if (B(() => 2)) - { - System.Console.WriteLine(0); - } - } -}"; + var src1 = """ + + class C + { + public static bool B(Func a) => false; + + public static void F() + { + if (B(() => 1)) + { + System.Console.WriteLine(0); + } + } + } + """; + var src2 = """ + + class C + { + public static bool B(Func a) => false; + + public static void F() + { + if (B(() => 2)) + { + System.Console.WriteLine(0); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -6688,32 +7368,36 @@ public static void F() [Fact] public void WhileBody_Update1() { - var src1 = @" -class C -{ - public static bool B() { return false; } - - public static void F() - { - while (B()) - { - System.Console.WriteLine(0); - } - } -}"; - var src2 = @" -class C -{ - public static bool B() { return false; } - - public static void F() - { - while (B()) - { - System.Console.WriteLine(1); - } - } -}"; + var src1 = """ + + class C + { + public static bool B() { return false; } + + public static void F() + { + while (B()) + { + System.Console.WriteLine(0); + } + } + } + """; + var src2 = """ + + class C + { + public static bool B() { return false; } + + public static void F() + { + while (B()) + { + System.Console.WriteLine(1); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -6723,32 +7407,36 @@ public static void F() [Fact] public void WhileBody_Update2() { - var src1 = @" -class C -{ - public static bool B() { return false; } - - public static void F() - { - while (B()) - { - System.Console.WriteLine(0); - } - } -}"; - var src2 = @" -class C -{ - public static bool B() { return false; } - - public static void F() - { - while (!B()) - { - System.Console.WriteLine(1); - } - } -}"; + var src1 = """ + + class C + { + public static bool B() { return false; } + + public static void F() + { + while (B()) + { + System.Console.WriteLine(0); + } + } + } + """; + var src2 = """ + + class C + { + public static bool B() { return false; } + + public static void F() + { + while (!B()) + { + System.Console.WriteLine(1); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -6759,32 +7447,36 @@ public static void F() [Fact] public void WhileBody_Update_Lambda() { - var src1 = @" -class C -{ - public static bool B(Func a) => false; - - public static void F() - { - while (B(() => 1)) - { - System.Console.WriteLine(0); - } - } -}"; - var src2 = @" -class C -{ - public static bool B(Func a) => false; - - public static void F() - { - while (B(() => 2)) - { - System.Console.WriteLine(1); - } - } -}"; + var src1 = """ + + class C + { + public static bool B(Func a) => false; + + public static void F() + { + while (B(() => 1)) + { + System.Console.WriteLine(0); + } + } + } + """; + var src2 = """ + + class C + { + public static bool B(Func a) => false; + + public static void F() + { + while (B(() => 2)) + { + System.Console.WriteLine(1); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -6794,34 +7486,38 @@ public static void F() [Fact] public void DoWhileBody_Update1() { - var src1 = @" -class C -{ - public static bool B() { return false; } - - public static void F() - { - do - { - System.Console.WriteLine(0); - } - while (B()); - } -}"; - var src2 = @" -class C -{ - public static bool B() { return false; } - - public static void F() - { - do - { - System.Console.WriteLine(1); - } - while (B()); - } -}"; + var src1 = """ + + class C + { + public static bool B() { return false; } + + public static void F() + { + do + { + System.Console.WriteLine(0); + } + while (B()); + } + } + """; + var src2 = """ + + class C + { + public static bool B() { return false; } + + public static void F() + { + do + { + System.Console.WriteLine(1); + } + while (B()); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -6831,34 +7527,38 @@ public static void F() [Fact] public void DoWhileBody_Update2() { - var src1 = @" -class C -{ - public static bool B() { return false; } - - public static void F() - { - do - { - System.Console.WriteLine(0); - } - while (B()); - } -}"; - var src2 = @" -class C -{ - public static bool B() { return false; } - - public static void F() - { - do - { - System.Console.WriteLine(1); - } - while (!B()); - } -}"; + var src1 = """ + + class C + { + public static bool B() { return false; } + + public static void F() + { + do + { + System.Console.WriteLine(0); + } + while (B()); + } + } + """; + var src2 = """ + + class C + { + public static bool B() { return false; } + + public static void F() + { + do + { + System.Console.WriteLine(1); + } + while (!B()); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -6869,34 +7569,38 @@ public static void F() [Fact] public void DoWhileBody_Update_Lambda() { - var src1 = @" -class C -{ - public static bool B(Func a) => false; - - public static void F() - { - do - { - System.Console.WriteLine(0); - } - while (B(() => 1)); - } -}"; - var src2 = @" -class C -{ - public static bool B(Func a) => false; - - public static void F() - { - do - { - System.Console.WriteLine(1); - } - while (B(() => 2)); - } -}"; + var src1 = """ + + class C + { + public static bool B(Func a) => false; + + public static void F() + { + do + { + System.Console.WriteLine(0); + } + while (B(() => 1)); + } + } + """; + var src2 = """ + + class C + { + public static bool B(Func a) => false; + + public static void F() + { + do + { + System.Console.WriteLine(1); + } + while (B(() => 2)); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -6906,24 +7610,28 @@ public static void F() [Fact] public void DoWhileBody_Delete() { - var src1 = @" -class C -{ - static void F() - { - do G(); while (true); - } -} -"; - var src2 = @" -class C -{ - static void F() - { - do ; while (true); - } -} -"; + var src1 = """ + + class C + { + static void F() + { + do G(); while (true); + } + } + + """; + var src2 = """ + + class C + { + static void F() + { + do ; while (true); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -6933,34 +7641,38 @@ static void F() [Fact] public void SwitchCase_Update1() { - var src1 = @" -class C -{ - public static string F() { return null; } - - public static void G() - { - switch (F()) - { - case ""a"": System.Console.WriteLine(0); break; - case ""b"": System.Console.WriteLine(1); break; - } - } -}"; - var src2 = @" -class C -{ - public static string F() { return null; } - - public static void G() - { - switch (F()) - { - case ""a"": System.Console.WriteLine(0); break; - case ""b"": System.Console.WriteLine(2); break; - } - } -}"; + var src1 = """ + + class C + { + public static string F() { return null; } + + public static void G() + { + switch (F()) + { + case "a": System.Console.WriteLine(0); break; + case "b": System.Console.WriteLine(1); break; + } + } + } + """; + var src2 = """ + + class C + { + public static string F() { return null; } + + public static void G() + { + switch (F()) + { + case "a": System.Console.WriteLine(0); break; + case "b": System.Console.WriteLine(2); break; + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -6970,34 +7682,38 @@ public static void G() [Fact] public void SwitchCase_Update_Lambda() { - var src1 = @" -class C -{ - public static bool B(Func a) => false; - - public static void F() - { - switch (B(() => 1)) - { - case ""a"": System.Console.WriteLine(0); break; - case ""b"": System.Console.WriteLine(1); break; - } - } -}"; - var src2 = @" -class C -{ - public static bool B(Func a) => false; - - public static void F() - { - switch (B(() => 2)) - { - case ""a"": System.Console.WriteLine(0); break; - case ""b"": System.Console.WriteLine(2); break; - } - } -}"; + var src1 = """ + + class C + { + public static bool B(Func a) => false; + + public static void F() + { + switch (B(() => 1)) + { + case "a": System.Console.WriteLine(0); break; + case "b": System.Console.WriteLine(1); break; + } + } + } + """; + var src2 = """ + + class C + { + public static bool B(Func a) => false; + + public static void F() + { + switch (B(() => 2)) + { + case "a": System.Console.WriteLine(0); break; + case "b": System.Console.WriteLine(2); break; + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7011,60 +7727,64 @@ public static void F() [Fact] public void SwitchWhenClause_PatternUpdate1() { - var src1 = @" -class C -{ - public static int Main() - { - switch (F()) - { - case int a1 when G1(a1): - case int a2 when G1(a2): - return 10; - - case byte a when G5(a): - return 10; - - case double b when G2(b): - return 20; - - case C { X: 2 } when G4(9): - return 30; - - case C { X: 2, Y: C { X: 1 } } c1 when G3(c1): - return 40; - } + var src1 = """ - return 0; - } -}"; - var src2 = @" -class C -{ - public static int Main() - { - switch (F()) - { - case int a1 when G1(a1): - case int a2 when G1(a2): - return 10; - - case byte a when G5(a): - return 10; - - case double b when G2(b): - return 20; - - case C { X: 2 } when G4(9): - return 30; - - case C { X: 2, Y: C { X: 2 } } c1 when G3(c1): - return 40; - } + class C + { + public static int Main() + { + switch (F()) + { + case int a1 when G1(a1): + case int a2 when G1(a2): + return 10; + + case byte a when G5(a): + return 10; + + case double b when G2(b): + return 20; + + case C { X: 2 } when G4(9): + return 30; + + case C { X: 2, Y: C { X: 1 } } c1 when G3(c1): + return 40; + } - return 0; - } -}"; + return 0; + } + } + """; + var src2 = """ + + class C + { + public static int Main() + { + switch (F()) + { + case int a1 when G1(a1): + case int a2 when G1(a2): + return 10; + + case byte a when G5(a): + return 10; + + case double b when G2(b): + return 20; + + case C { X: 2 } when G4(9): + return 30; + + case C { X: 2, Y: C { X: 2 } } c1 when G3(c1): + return 40; + } + + return 0; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7075,35 +7795,39 @@ public static int Main() [Fact] public void SwitchWhenClause_PatternInsert() { - var src1 = @" -class C -{ - public static int Main() - { - switch (F()) - { - case int a2 when G1(a2): - return 10; - } + var src1 = """ - return 0; - } -}"; - var src2 = @" -class C -{ - public static int Main() - { - switch (F()) - { - case int a1 when G1(a1): - case int a2 when G1(a2): - return 10; - } + class C + { + public static int Main() + { + switch (F()) + { + case int a2 when G1(a2): + return 10; + } - return 0; - } -}"; + return 0; + } + } + """; + var src2 = """ + + class C + { + public static int Main() + { + switch (F()) + { + case int a1 when G1(a1): + case int a2 when G1(a2): + return 10; + } + + return 0; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7114,35 +7838,39 @@ public static int Main() [Fact] public void SwitchWhenClause_PatternDelete() { - var src1 = @" -class C -{ - public static int Main() - { - switch (F()) - { - case int a1 when G1(a1): - case int a2 when G1(a2): - return 10; - } + var src1 = """ - return 0; - } -}"; - var src2 = @" -class C -{ - public static int Main() - { - switch (F()) - { - case int a2 when G1(a2): - return 10; - } + class C + { + public static int Main() + { + switch (F()) + { + case int a1 when G1(a1): + case int a2 when G1(a2): + return 10; + } - return 0; - } -}"; + return 0; + } + } + """; + var src2 = """ + + class C + { + public static int Main() + { + switch (F()) + { + case int a2 when G1(a2): + return 10; + } + + return 0; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7153,36 +7881,40 @@ public static int Main() [Fact] public void SwitchWhenClause_WhenDelete() { - var src1 = @" -class C -{ - public static int Main() - { - switch (F()) - { - case byte a1 when G1(a1): - case int a2 when G1(a2): - return 10; - } + var src1 = """ - return 0; - } -}"; - var src2 = @" -class C -{ - public static int Main() - { - switch (F()) - { - case byte a1: - case int a2 when G1(a2): - return 10; - } + class C + { + public static int Main() + { + switch (F()) + { + case byte a1 when G1(a1): + case int a2 when G1(a2): + return 10; + } - return 0; - } -}"; + return 0; + } + } + """; + var src2 = """ + + class C + { + public static int Main() + { + switch (F()) + { + case byte a1: + case int a2 when G1(a2): + return 10; + } + + return 0; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7193,36 +7925,40 @@ public static int Main() [Fact] public void SwitchWhenClause_WhenAdd() { - var src1 = @" -class C -{ - public static int Main() - { - switch (F()) - { - case byte a1: - case int a2 when G1(a2): - return 10; - } + var src1 = """ - return 0; - } -}"; - var src2 = @" -class C -{ - public static int Main() - { - switch (F()) - { - case byte a1 when G1(a1): - case int a2 when G1(a2): - return 10; - } + class C + { + public static int Main() + { + switch (F()) + { + case byte a1: + case int a2 when G1(a2): + return 10; + } - return 0; - } -}"; + return 0; + } + } + """; + var src2 = """ + + class C + { + public static int Main() + { + switch (F()) + { + case byte a1 when G1(a1): + case int a2 when G1(a2): + return 10; + } + + return 0; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7233,36 +7969,40 @@ public static int Main() [Fact] public void SwitchWhenClause_WhenUpdate() { - var src1 = @" -class C -{ - public static int Main() - { - switch (F()) - { - case byte a1 when G1(a1): - case int a2 when G1(a2): - return 10; - } + var src1 = """ - return 0; - } -}"; - var src2 = @" -class C -{ - public static int Main() - { - switch (F()) - { - case byte a1 when G1(a1 * 2): - case int a2 when G1(a2): - return 10; - } + class C + { + public static int Main() + { + switch (F()) + { + case byte a1 when G1(a1): + case int a2 when G1(a2): + return 10; + } - return 0; - } -}"; + return 0; + } + } + """; + var src2 = """ + + class C + { + public static int Main() + { + switch (F()) + { + case byte a1 when G1(a1 * 2): + case int a2 when G1(a2): + return 10; + } + + return 0; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7272,36 +8012,40 @@ public static int Main() [Fact] public void SwitchWhenClause_UpdateGoverningExpression() { - var src1 = @" -class C -{ - public static int Main() - { - switch (F(1)) - { - case int a1 when G1(a1): - case int a2 when G1(a2): - return 10; - } + var src1 = """ - return 0; - } -}"; - var src2 = @" -class C -{ - public static int Main() - { - switch (F(2)) - { - case int a1 when G1(a1): - case int a2 when G1(a2): - return 10; - } + class C + { + public static int Main() + { + switch (F(1)) + { + case int a1 when G1(a1): + case int a2 when G1(a2): + return 10; + } - return 0; - } -}"; + return 0; + } + } + """; + var src2 = """ + + class C + { + public static int Main() + { + switch (F(2)) + { + case int a1 when G1(a1): + case int a2 when G1(a2): + return 10; + } + + return 0; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7312,38 +8056,42 @@ public static int Main() [Fact] public void Switch_PropertyPattern_Update_NonLeaf() { - var src1 = @" -class C -{ - public int X { get => 1; } + var src1 = """ - public static int F(object obj) - { - switch (obj) - { - case C { X: 1 }: - return 1; - } + class C + { + public int X { get => 1; } - return 0; - } -}"; - var src2 = @" -class C -{ - public int X { get => 1; } + public static int F(object obj) + { + switch (obj) + { + case C { X: 1 }: + return 1; + } - public static int F(object obj) - { - switch (obj) - { - case C { X: 2 }: - return 1; - } + return 0; + } + } + """; + var src2 = """ - return 0; - } -}"; + class C + { + public int X { get => 1; } + + public static int F(object obj) + { + switch (obj) + { + case C { X: 2 }: + return 1; + } + + return 0; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7354,38 +8102,42 @@ public static int F(object obj) [Fact] public void Switch_PositionalPattern_Update_NonLeaf() { - var src1 = @" -class C -{ - public void Deconstruct(out int x) => x = X; + var src1 = """ - public static int F(object obj) - { - switch (obj) - { - case C ( x: 1 ): - return 1; - } + class C + { + public void Deconstruct(out int x) => x = X; - return 0; - } -}"; - var src2 = @" -class C -{ - public void Deconstruct(out int x) => x = X; + public static int F(object obj) + { + switch (obj) + { + case C ( x: 1 ): + return 1; + } - public static int F(object obj) - { - switch (obj) - { - case C ( x: 2 ): - return 1; - } + return 0; + } + } + """; + var src2 = """ - return 0; - } -}"; + class C + { + public void Deconstruct(out int x) => x = X; + + public static int F(object obj) + { + switch (obj) + { + case C ( x: 2 ): + return 1; + } + + return 0; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7396,44 +8148,48 @@ public static int F(object obj) [Fact] public void Switch_VarPattern_Update_NonLeaf() { - var src1 = @" -class C -{ - public static object G() => null; - - public static int F(object obj) - { - switch (G()) - { - case var (x, y): - return 1; + var src1 = """ - case 2: - return 2; - } + class C + { + public static object G() => null; + + public static int F(object obj) + { + switch (G()) + { + case var (x, y): + return 1; - return 0; - } -}"; - var src2 = @" -class C -{ - public static object G() => null; + case 2: + return 2; + } - public static int F(object obj) - { - switch (G()) - { - case var (x, y): - return 1; + return 0; + } + } + """; + var src2 = """ - case 3: - return 2; - } + class C + { + public static object G() => null; - return 0; - } -}"; + public static int F(object obj) + { + switch (G()) + { + case var (x, y): + return 1; + + case 3: + return 2; + } + + return 0; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7444,39 +8200,43 @@ public static int F(object obj) [Fact] public void Switch_DiscardPattern_Update_NonLeaf() { - var src1 = @" -class C -{ - public static object G() => null; - - public static int F(object obj) - { - switch (G()) - { - case bool _: - return 1; - } - - return 0; - } -}"; - var src2 = @" -class C -{ - public static object G() => null; + var src1 = """ - public static int F(object obj) - { - switch (G()) - { - case int _: - return 1; - } + class C + { + public static object G() => null; + + public static int F(object obj) + { + switch (G()) + { + case bool _: + return 1; + } - return 0; - } -}"; - var edits = GetTopEdits(src1, src2); + return 0; + } + } + """; + var src2 = """ + + class C + { + public static object G() => null; + + public static int F(object obj) + { + switch (G()) + { + case int _: + return 1; + } + + return 0; + } + } + """; + var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, @@ -7486,38 +8246,42 @@ public static int F(object obj) [Fact] public void Switch_NoPatterns_Update_NonLeaf() { - var src1 = @" -class C -{ - public static object G() => null; + var src1 = """ - public static int F(object obj) - { - switch (G()) - { - case 1: - return 1; - } + class C + { + public static object G() => null; - return 0; - } -}"; - var src2 = @" -class C -{ - public static object G() => null; + public static int F(object obj) + { + switch (G()) + { + case 1: + return 1; + } - public static int F(object obj) - { - switch (G()) - { - case 2: - return 1; - } + return 0; + } + } + """; + var src2 = """ - return 0; - } -}"; + class C + { + public static object G() => null; + + public static int F(object obj) + { + switch (G()) + { + case 2: + return 1; + } + + return 0; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7531,36 +8295,40 @@ public static int F(object obj) [Fact] public void SwitchExpression() { - var src1 = @" -class C -{ - public static int Main() - { - Console.WriteLine(1); + var src1 = """ - return F() switch - { - int a when F1() => F2(), - bool b => F3(), - _ => F4() - }; - } -}"; - var src2 = @" -class C -{ - public static int Main() - { - Console.WriteLine(2); + class C + { + public static int Main() + { + Console.WriteLine(1); - return F() switch - { - int a when F1() => F2(), - bool b => F3(), - _ => F4() - }; - } -}"; + return F() switch + { + int a when F1() => F2(), + bool b => F3(), + _ => F4() + }; + } + } + """; + var src2 = """ + + class C + { + public static int Main() + { + Console.WriteLine(2); + + return F() switch + { + int a when F1() => F2(), + bool b => F3(), + _ => F4() + }; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7571,16 +8339,20 @@ public static int Main() [Fact] public void SwitchExpression_Lambda1() { - var src1 = @" -class C -{ - public static int Main() => F() switch { 0 => new Func(() => 1)(), _ => 2}; -}"; - var src2 = @" -class C -{ - public static int Main() => F() switch { 0 => new Func(() => 3)(), _ => 2}; -}"; + var src1 = """ + + class C + { + public static int Main() => F() switch { 0 => new Func(() => 1)(), _ => 2}; + } + """; + var src2 = """ + + class C + { + public static int Main() => F() switch { 0 => new Func(() => 3)(), _ => 2}; + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7591,16 +8363,20 @@ class C [Fact] public void SwitchExpression_Lambda2() { - var src1 = @" -class C -{ - public static int Main() => F() switch { i => new Func(() => i + 1)(), _ => 2}; -}"; - var src2 = @" -class C -{ - public static int Main() => F() switch { i => new Func(() => i + 3)(), _ => 2}; -}"; + var src1 = """ + + class C + { + public static int Main() => F() switch { i => new Func(() => i + 1)(), _ => 2}; + } + """; + var src2 = """ + + class C + { + public static int Main() => F() switch { i => new Func(() => i + 3)(), _ => 2}; + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7611,16 +8387,20 @@ class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_MemberExpressionBody() { - var src1 = @" -class C -{ - public static int Main() => F() switch { 0 => 1, _ => 2}; -}"; - var src2 = @" -class C -{ - public static int Main() => G() switch { 0 => 10, _ => 20}; -}"; + var src1 = """ + + class C + { + public static int Main() => F() switch { 0 => 1, _ => 2}; + } + """; + var src2 = """ + + class C + { + public static int Main() => G() switch { 0 => 10, _ => 20}; + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7630,16 +8410,20 @@ class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_LambdaBody() { - var src1 = @" -class C -{ - public static Func M() => () => F() switch { 0 => 1, _ => 2}; -}"; - var src2 = @" -class C -{ - public static Func M() => () => G() switch { 0 => 10, _ => 20}; -}"; + var src1 = """ + + class C + { + public static Func M() => () => F() switch { 0 => 1, _ => 2}; + } + """; + var src2 = """ + + class C + { + public static Func M() => () => G() switch { 0 => 10, _ => 20}; + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7649,28 +8433,32 @@ class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_QueryLambdaBody() { - var src1 = @" -class C -{ - public static IEnumerable M() - { - return - from a in new[] { 1 } - where F() switch { 0 => true, _ => false} - select a; - } -}"; - var src2 = @" -class C -{ - public static IEnumerable M() - { - return - from a in new[] { 2 } - where F() switch { 0 => true, _ => false} - select a; - } -}"; + var src1 = """ + + class C + { + public static IEnumerable M() + { + return + from a in new[] { 1 } + where F() switch { 0 => true, _ => false} + select a; + } + } + """; + var src2 = """ + + class C + { + public static IEnumerable M() + { + return + from a in new[] { 2 } + where F() switch { 0 => true, _ => false} + select a; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7680,16 +8468,20 @@ from a in new[] { 2 } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_NestedInGoverningExpression() { - var src1 = @" -class C -{ - public static int Main() => (F() switch { 0 => 1, _ => 2 }) switch { 1 => 10, _ => 20 }; -}"; - var src2 = @" -class C -{ - public static int Main() => (G() switch { 0 => 10, _ => 20 }) switch { 10 => 100, _ => 200 }; -}"; + var src1 = """ + + class C + { + public static int Main() => (F() switch { 0 => 1, _ => 2 }) switch { 1 => 10, _ => 20 }; + } + """; + var src2 = """ + + class C + { + public static int Main() => (G() switch { 0 => 10, _ => 20 }) switch { 10 => 100, _ => 200 }; + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7700,24 +8492,28 @@ class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_NestedInArm() { - var src1 = @" -class C -{ - public static int Main() => F1() switch - { - 1 when F2() switch { 0 => true, _ => false } => F3() switch { 0 => 1, _ => 2 }, - _ => 20 - }; -}"; - var src2 = @" -class C -{ - public static int Main() => F1() switch - { - 1 when F2() switch { 0 => true, _ => false } => F3() switch { 0 => 1, _ => 2 }, - _ => 20 - }; -}"; + var src1 = """ + + class C + { + public static int Main() => F1() switch + { + 1 when F2() switch { 0 => true, _ => false } => F3() switch { 0 => 1, _ => 2 }, + _ => 20 + }; + } + """; + var src2 = """ + + class C + { + public static int Main() => F1() switch + { + 1 when F2() switch { 0 => true, _ => false } => F3() switch { 0 => 1, _ => 2 }, + _ => 20 + }; + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7727,22 +8523,26 @@ 1 when F2() switch { 0 => true, _ => false } => F3() switch { [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_Delete1() { - var src1 = @" -class C -{ - public static int Main() - { - return Method() switch { true => G(), _ => F2() switch { 1 => 0, _ => 2 } }; - } -}"; - var src2 = @" -class C -{ - public static int Main() - { - return Method() switch { true => G(), _ => 1 }; - } -}"; + var src1 = """ + + class C + { + public static int Main() + { + return Method() switch { true => G(), _ => F2() switch { 1 => 0, _ => 2 } }; + } + } + """; + var src2 = """ + + class C + { + public static int Main() + { + return Method() switch { true => G(), _ => 1 }; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7752,22 +8552,26 @@ public static int Main() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_Delete2() { - var src1 = @" -class C -{ - public static int Main() - { - return F1() switch { 1 => 0, _ => F2() switch { 1 => 0, _ => 2 } }; - } -}"; - var src2 = @" -class C -{ - public static int Main() - { - return F1() switch { 1 => 0, _ => 1 }; - } -}"; + var src1 = """ + + class C + { + public static int Main() + { + return F1() switch { 1 => 0, _ => F2() switch { 1 => 0, _ => 2 } }; + } + } + """; + var src2 = """ + + class C + { + public static int Main() + { + return F1() switch { 1 => 0, _ => 1 }; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7777,22 +8581,26 @@ public static int Main() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_Delete3() { - var src1 = @" -class C -{ - public static int Main() - { - return F1() switch { 1 when F2() switch { 1 => true, _ => false } => 0, _ => 2 }; - } -}"; - var src2 = @" -class C -{ - public static int Main() - { - return F1() switch { 1 when F3() => 0, _ => 1 }; - } -}"; + var src1 = """ + + class C + { + public static int Main() + { + return F1() switch { 1 when F2() switch { 1 => true, _ => false } => 0, _ => 2 }; + } + } + """; + var src2 = """ + + class C + { + public static int Main() + { + return F1() switch { 1 when F3() => 0, _ => 1 }; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7806,39 +8614,43 @@ public static int Main() [Fact] public void Try_Add_Inner() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Goo(); - } + var src1 = """ - static void Goo() - { - Console.WriteLine(1); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - try - { - Goo(); - } - catch - { - } - } + class C + { + static void Main(string[] args) + { + Goo(); + } - static void Goo() - { - Console.WriteLine(1); - } -} -"; + static void Goo() + { + Console.WriteLine(1); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + try + { + Goo(); + } + catch + { + } + } + + static void Goo() + { + Console.WriteLine(1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7849,39 +8661,43 @@ static void Goo() [Fact] public void Try_Add_Leaf() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Goo(); - } + var src1 = """ - static void Goo() - { - Console.WriteLine(1); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - Goo(); - } + class C + { + static void Main(string[] args) + { + Goo(); + } - static void Goo() - { - try - { - Console.WriteLine(1); - } - catch - { - } - } -} -"; + static void Goo() + { + Console.WriteLine(1); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + Goo(); + } + + static void Goo() + { + try + { + Console.WriteLine(1); + } + catch + { + } + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7891,39 +8707,43 @@ static void Goo() [Fact] public void Try_Delete_Inner() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - try - { - Goo(); - } - catch - { - } - } + var src1 = """ - static void Goo() - { - Console.WriteLine(1); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - Goo(); - } + class C + { + static void Main(string[] args) + { + try + { + Goo(); + } + catch + { + } + } - static void Goo() - { - Console.WriteLine(1); - } -} -"; + static void Goo() + { + Console.WriteLine(1); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + Goo(); + } + + static void Goo() + { + Console.WriteLine(1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7934,39 +8754,43 @@ static void Goo() [Fact] public void Try_Delete_Leaf() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Goo(); - } + var src1 = """ - static void Goo() - { - try - { - Console.WriteLine(1); - } - catch - { - } - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - Goo(); - } + class C + { + static void Main(string[] args) + { + Goo(); + } - static void Goo() - { - Console.WriteLine(1); - } -} -"; + static void Goo() + { + try + { + Console.WriteLine(1); + } + catch + { + } + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + Goo(); + } + + static void Goo() + { + Console.WriteLine(1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -7976,45 +8800,49 @@ static void Goo() [Fact] public void Try_Update_Inner() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - try - { - Goo(); - } - catch - { - } - } + var src1 = """ - static void Goo() - { - Console.WriteLine(1); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - try - { - Goo(); - } - catch (IOException) - { - } - } + class C + { + static void Main(string[] args) + { + try + { + Goo(); + } + catch + { + } + } - static void Goo() - { - Console.WriteLine(1); - } -} -"; + static void Goo() + { + Console.WriteLine(1); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + try + { + Goo(); + } + catch (IOException) + { + } + } + + static void Goo() + { + Console.WriteLine(1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -8025,45 +8853,49 @@ static void Goo() [Fact] public void Try_Update_Inner2() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - try - { - Goo(); - } - catch - { - } - } + var src1 = """ - static void Goo() - { - Console.WriteLine(1); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - try - { - Goo(); - } - catch - { - } - Console.WriteLine(2); - } + class C + { + static void Main(string[] args) + { + try + { + Goo(); + } + catch + { + } + } - static void Goo() - { - Console.WriteLine(1); - } -}"; + static void Goo() + { + Console.WriteLine(1); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + try + { + Goo(); + } + catch + { + } + Console.WriteLine(2); + } + + static void Goo() + { + Console.WriteLine(1); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -8073,45 +8905,49 @@ static void Goo() [Fact] public void TryFinally_Update_Inner() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - try - { - Goo(); - } - finally - { - } - } + var src1 = """ - static void Goo() - { - Console.WriteLine(1); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - try - { - Goo(); - } - finally - { - } - Console.WriteLine(2); - } + class C + { + static void Main(string[] args) + { + try + { + Goo(); + } + finally + { + } + } - static void Goo() - { - Console.WriteLine(1); - } -}"; + static void Goo() + { + Console.WriteLine(1); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + try + { + Goo(); + } + finally + { + } + Console.WriteLine(2); + } + + static void Goo() + { + Console.WriteLine(1); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -8121,45 +8957,49 @@ static void Goo() [Fact] public void Try_Update_Leaf() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Goo(); - } + var src1 = """ - static void Goo() - { - try - { - Console.WriteLine(1); - } - catch - { - } - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - Goo(); - } + class C + { + static void Main(string[] args) + { + Goo(); + } - static void Goo() - { - try - { - Console.WriteLine(1); - } - catch (IOException) - { - } - } -} -"; + static void Goo() + { + try + { + Console.WriteLine(1); + } + catch + { + } + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + Goo(); + } + + static void Goo() + { + try + { + Console.WriteLine(1); + } + catch (IOException) + { + } + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -8169,39 +9009,43 @@ static void Goo() [Fact] public void TryFinally_DeleteStatement_Inner() { - var src1 = @" -class C -{ - static void F() - { - Console.WriteLine(0); + var src1 = """ - try - { - Console.WriteLine(1); - } - finally - { - Console.WriteLine(2); - } - } -}"; - var src2 = @" -class C -{ - static void F() - { - Console.WriteLine(0); - - try - { - } - finally - { - Console.WriteLine(2); - } - } -}"; + class C + { + static void F() + { + Console.WriteLine(0); + + try + { + Console.WriteLine(1); + } + finally + { + Console.WriteLine(2); + } + } + } + """; + var src2 = """ + + class C + { + static void F() + { + Console.WriteLine(0); + + try + { + } + finally + { + Console.WriteLine(2); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -8212,35 +9056,39 @@ static void F() [Fact] public void TryFinally_DeleteStatement_Leaf() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - try - { - Console.WriteLine(0); - } - finally - { - Console.WriteLine(1); - } - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - try - { - Console.WriteLine(0); - } - finally - { - } - } -}"; + var src1 = """ + + class C + { + static void Main(string[] args) + { + try + { + Console.WriteLine(0); + } + finally + { + Console.WriteLine(1); + } + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + try + { + Console.WriteLine(0); + } + finally + { + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -8251,39 +9099,43 @@ static void Main(string[] args) [Fact] public void Try_DeleteStatement_Inner() { - var src1 = @" -class C -{ - static void F() - { - Console.WriteLine(0); - - try - { - Console.WriteLine(1); - } - finally - { - Console.WriteLine(2); - } - } -}"; - var src2 = @" -class C -{ - static void F() - { - Console.WriteLine(0); - - try - { - } - finally - { - Console.WriteLine(2); - } - } -}"; + var src1 = """ + + class C + { + static void F() + { + Console.WriteLine(0); + + try + { + Console.WriteLine(1); + } + finally + { + Console.WriteLine(2); + } + } + } + """; + var src2 = """ + + class C + { + static void F() + { + Console.WriteLine(0); + + try + { + } + finally + { + Console.WriteLine(2); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -8294,35 +9146,39 @@ static void F() [Fact] public void Try_DeleteStatement_Leaf() { - var src1 = @" -class C -{ - static void F() - { - try - { - Console.WriteLine(1); - } - finally - { - Console.WriteLine(2); - } - } -}"; - var src2 = @" -class C -{ - static void F() - { - try - { - } - finally - { - Console.WriteLine(2); - } - } -}"; + var src1 = """ + + class C + { + static void F() + { + try + { + Console.WriteLine(1); + } + finally + { + Console.WriteLine(2); + } + } + } + """; + var src2 = """ + + class C + { + static void F() + { + try + { + } + finally + { + Console.WriteLine(2); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -8336,39 +9192,43 @@ static void F() [Fact] public void Catch_Add_Inner() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Goo(); - } + var src1 = """ - static void Goo() - { - Console.WriteLine(1); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - try - { - } - catch - { - Goo(); - } - } + class C + { + static void Main(string[] args) + { + Goo(); + } - static void Goo() - { - Console.WriteLine(1); - } -} -"; + static void Goo() + { + Console.WriteLine(1); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + try + { + } + catch + { + Goo(); + } + } + + static void Goo() + { + Console.WriteLine(1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -8379,39 +9239,43 @@ static void Goo() [Fact] public void Catch_Add_Leaf() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Goo(); - } + var src1 = """ - static void Goo() - { - Console.WriteLine(1); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - Goo(); - } + class C + { + static void Main(string[] args) + { + Goo(); + } - static void Goo() - { - try - { - } - catch - { - Console.WriteLine(1); - } - } -} -"; + static void Goo() + { + Console.WriteLine(1); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + Goo(); + } + + static void Goo() + { + try + { + } + catch + { + Console.WriteLine(1); + } + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -8422,39 +9286,43 @@ static void Goo() [Fact] public void Catch_Delete_Inner() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - try - { - } - catch - { - Goo(); - } - } + var src1 = """ - static void Goo() - { - Console.WriteLine(1); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - Goo(); - } + class C + { + static void Main(string[] args) + { + try + { + } + catch + { + Goo(); + } + } - static void Goo() - { - Console.WriteLine(1); - } -} -"; + static void Goo() + { + Console.WriteLine(1); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + Goo(); + } + + static void Goo() + { + Console.WriteLine(1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -8465,39 +9333,43 @@ static void Goo() [Fact] public void Catch_Delete_Leaf() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Goo(); - } + var src1 = """ - static void Goo() - { - try - { - } - catch - { - Console.WriteLine(1); - } - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - Goo(); - } + class C + { + static void Main(string[] args) + { + Goo(); + } - static void Goo() - { - Console.WriteLine(1); - } -} -"; + static void Goo() + { + try + { + } + catch + { + Console.WriteLine(1); + } + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + Goo(); + } + + static void Goo() + { + Console.WriteLine(1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -8508,45 +9380,49 @@ static void Goo() [Fact] public void Catch_Update_Inner() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - try - { - } - catch - { - Goo(); - } - } + var src1 = """ - static void Goo() - { - Console.WriteLine(1); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - try - { - } - catch (IOException) - { - Goo(); - } - } + class C + { + static void Main(string[] args) + { + try + { + } + catch + { + Goo(); + } + } - static void Goo() - { - Console.WriteLine(1); - } -} -"; + static void Goo() + { + Console.WriteLine(1); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + try + { + } + catch (IOException) + { + Goo(); + } + } + + static void Goo() + { + Console.WriteLine(1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -8557,42 +9433,46 @@ static void Goo() [Fact] public void Catch_Update_InFilter_Inner() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - try - { - } - catch (IOException) when (Goo(1)) - { - } - } + var src1 = """ - static void Goo() - { - Console.WriteLine(1); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - try - { - } - catch (Exception) when (Goo(1)) - { - } - } + class C + { + static void Main(string[] args) + { + try + { + } + catch (IOException) when (Goo(1)) + { + } + } - static void Goo() - { - Console.WriteLine(1); - } -}"; + static void Goo() + { + Console.WriteLine(1); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + try + { + } + catch (Exception) when (Goo(1)) + { + } + } + + static void Goo() + { + Console.WriteLine(1); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -8603,45 +9483,49 @@ static void Goo() [Fact] public void Catch_Update_Leaf() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Goo(); - } + var src1 = """ - static void Goo() - { - try - { - } - catch - { - Console.WriteLine(1); - } - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - Goo(); - } + class C + { + static void Main(string[] args) + { + Goo(); + } - static void Goo() - { - try - { - } - catch (IOException) - { - Console.WriteLine(1); - } - } -} -"; + static void Goo() + { + try + { + } + catch + { + Console.WriteLine(1); + } + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + Goo(); + } + + static void Goo() + { + try + { + } + catch (IOException) + { + Console.WriteLine(1); + } + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -8652,42 +9536,46 @@ static void Goo() [Fact] public void CatchFilter_Update_Inner() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - try - { - } - catch (IOException) when (Goo(1)) - { - } - } + var src1 = """ - static void Goo() - { - Console.WriteLine(1); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - try - { - } - catch (IOException) when (Goo(2)) - { - } - } + class C + { + static void Main(string[] args) + { + try + { + } + catch (IOException) when (Goo(1)) + { + } + } - static void Goo() - { - Console.WriteLine(1); - } -}"; + static void Goo() + { + Console.WriteLine(1); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + try + { + } + catch (IOException) when (Goo(2)) + { + } + } + + static void Goo() + { + Console.WriteLine(1); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -8699,32 +9587,36 @@ static void Goo() [Fact] public void CatchFilter_Update_Leaf1() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - try - { - } - catch (IOException) when (Goo(1)) - { - } - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - try - { - } - catch (IOException) when (Goo(2)) - { - } - } -}"; + var src1 = """ + + class C + { + static void Main(string[] args) + { + try + { + } + catch (IOException) when (Goo(1)) + { + } + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + try + { + } + catch (IOException) when (Goo(2)) + { + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -8735,32 +9627,36 @@ static void Main(string[] args) [Fact] public void CatchFilter_Update_Leaf2() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - try - { - } - catch (IOException) when (Goo(1)) - { - } - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - try - { - } - catch (Exception) when (Goo(1)) - { - } - } -}"; + var src1 = """ + + class C + { + static void Main(string[] args) + { + try + { + } + catch (IOException) when (Goo(1)) + { + } + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + try + { + } + catch (Exception) when (Goo(1)) + { + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -8775,39 +9671,43 @@ static void Main(string[] args) [Fact] public void Finally_Add_Inner() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Goo(); - } + var src1 = """ - static void Goo() - { - Console.WriteLine(1); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - try - { - } - finally - { - Goo(); - } - } + class C + { + static void Main(string[] args) + { + Goo(); + } - static void Goo() - { - Console.WriteLine(1); - } -} -"; + static void Goo() + { + Console.WriteLine(1); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + try + { + } + finally + { + Goo(); + } + } + + static void Goo() + { + Console.WriteLine(1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -8818,39 +9718,43 @@ static void Goo() [Fact] public void Finally_Add_Leaf() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Goo(); - } + var src1 = """ + + class C + { + static void Main(string[] args) + { + Goo(); + } + + static void Goo() + { + Console.WriteLine(1); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + Goo(); + } - static void Goo() - { - Console.WriteLine(1); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - Goo(); - } + static void Goo() + { + try + { + } + finally + { + Console.WriteLine(1); + } + } + } - static void Goo() - { - try - { - } - finally - { - Console.WriteLine(1); - } - } -} -"; + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -8861,39 +9765,43 @@ static void Goo() [Fact] public void Finally_Delete_Inner() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - try - { - } - finally - { - Goo(); - } - } + var src1 = """ - static void Goo() - { - Console.WriteLine(1); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - Goo(); - } + class C + { + static void Main(string[] args) + { + try + { + } + finally + { + Goo(); + } + } - static void Goo() - { - Console.WriteLine(1); - } -} -"; + static void Goo() + { + Console.WriteLine(1); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + Goo(); + } + + static void Goo() + { + Console.WriteLine(1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -8904,39 +9812,43 @@ static void Goo() [Fact] public void Finally_Delete_Leaf() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Goo(); - } + var src1 = """ - static void Goo() - { - try - { - } - finally - { - Console.WriteLine(1); - } - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - Goo(); - } + class C + { + static void Main(string[] args) + { + Goo(); + } - static void Goo() - { - Console.WriteLine(1); - } -} -"; + static void Goo() + { + try + { + } + finally + { + Console.WriteLine(1); + } + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + Goo(); + } + + static void Goo() + { + Console.WriteLine(1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -8951,81 +9863,85 @@ static void Goo() [Fact] public void TryCatchFinally() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - try - { - } - catch (IOException) - { - try + var src1 = """ + + class C { - try + static void Main(string[] args) { try - { - Goo(); + { } - catch + catch (IOException) { - } + try + { + try + { + try + { + Goo(); + } + catch + { + } + } + catch (Exception) + { + } + } + finally + { + } + } } - catch (Exception) + + static void Goo() { + Console.WriteLine(1); } } - finally - { - } - } - } + """; + var src2 = """ - static void Goo() - { - Console.WriteLine(1); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - try - { - } - catch (Exception) - { - try + class C { - try - { - } - finally + static void Main(string[] args) { try { - Goo(); } - catch + catch (Exception) { - } - } - } - catch (Exception) - { + try + { + try + { + } + finally + { + try + { + Goo(); + } + catch + { + } + } + } + catch (Exception) + { + } + } + } + + static void Goo() + { + Console.WriteLine(1); + } } - } - } - static void Goo() - { - Console.WriteLine(1); - } -} -"; + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -9039,63 +9955,67 @@ static void Goo() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23865")] public void TryCatchFinally_Regions() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - try - { - } - catch (IOException) - { - try + var src1 = """ + + class C { - try + static void Main(string[] args) { try - { - Goo(); + { } - catch + catch (IOException) { - } + try + { + try + { + try + { + Goo(); + } + catch + { + } + } + catch (Exception) + { + } + } + finally + { + } + } } - catch (Exception) + + static void Goo() { + Console.WriteLine(1); } } - finally + """; + var src2 = """ + + class C { - } - } - } + static void Main(string[] args) + { + try + { + } + catch (IOException) + { + try { try { try { Goo(); } catch { } } catch (Exception) { } } finally { } + } + } - static void Goo() - { - Console.WriteLine(1); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - try - { - } - catch (IOException) - { - try { try { try { Goo(); } catch { } } catch (Exception) { } } finally { } - } - } + static void Goo() + { + Console.WriteLine(1); + } + } - static void Goo() - { - Console.WriteLine(1); - } -} -"; + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -9106,92 +10026,96 @@ static void Goo() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23865")] public void TryCatchFinally2_Regions() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - try - { - try + var src1 = """ + + class C { - try + static void Main(string[] args) { try + { + try + { + try + { + try + { + Goo(); + } + catch + { + } + } + catch (Exception) + { + } + } + finally + { + } + } + catch (IOException) { - Goo(); + } - catch + finally { - } + + } } - catch (Exception) + + static void Goo() { - } + Console.WriteLine(1); + } } - finally - { - } - } - catch (IOException) - { - - } - finally - { - - } - } + """; + var src2 = """ - static void Goo() - { - Console.WriteLine(1); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - try - { - try + class C { - try + static void Main(string[] args) { try + { + try + { + try + { + try + { + Goo(); + } + catch + { + + } + } + catch (Exception) + { + } + } + finally + { + } + } + catch (IOException) { - Goo(); + } - catch + finally { - - } + + } } - catch (Exception) - { - } - } - finally - { - } - } - catch (IOException) - { - - } - finally - { - - } - } - static void Goo() - { - Console.WriteLine(1); - } -} -"; + static void Goo() + { + Console.WriteLine(1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -9202,42 +10126,46 @@ static void Goo() [Fact] public void TryFilter_Regions1() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - try - { - } - catch (IOException e) when (e == null) - { - Goo(); - } - } + var src1 = """ - static void Goo() - { - Console.WriteLine(1); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - try - { - } - catch (IOException e) when (e == null) { Goo(); } - } + class C + { + static void Main(string[] args) + { + try + { + } + catch (IOException e) when (e == null) + { + Goo(); + } + } - static void Goo() - { - Console.WriteLine(1); - } -} -"; + static void Goo() + { + Console.WriteLine(1); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + try + { + } + catch (IOException e) when (e == null) { Goo(); } + } + + static void Goo() + { + Console.WriteLine(1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -9247,42 +10175,46 @@ static void Goo() [Fact] public void TryFilter_Regions2() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - try - { - } - catch (IOException e) when (e == null) - { - Goo(); - } - } + var src1 = """ - static void Goo() - { - Console.WriteLine(1); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - try - { - } - catch (IOException e) when (e == null) { Goo(); } - } + class C + { + static void Main(string[] args) + { + try + { + } + catch (IOException e) when (e == null) + { + Goo(); + } + } - static void Goo() - { - Console.WriteLine(1); - } -} -"; + static void Goo() + { + Console.WriteLine(1); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + try + { + } + catch (IOException e) when (e == null) { Goo(); } + } + + static void Goo() + { + Console.WriteLine(1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -9292,49 +10224,53 @@ static void Goo() [Fact] public void Try_Lambda1() { - var src1 = @" -using System; -using System.Linq; -class C -{ - static int Goo(int x) - { - return 1; - } + var src1 = """ - static void F() - { - Func f = null; - try - { - f = x => 1 + Goo(x); - } - catch - { - } + using System; + using System.Linq; + class C + { + static int Goo(int x) + { + return 1; + } - Console.Write(f(2)); - } -}"; - var src2 = @" -using System; -using System.Linq; -class C -{ - static int Goo(int x) - { - return 1; - } + static void F() + { + Func f = null; + try + { + f = x => 1 + Goo(x); + } + catch + { + } - static void F() - { - Func f = null; + Console.Write(f(2)); + } + } + """; + var src2 = """ - f = x => 1 + Goo(x); + using System; + using System.Linq; + class C + { + static int Goo(int x) + { + return 1; + } - Console.Write(f(2)); - } -}"; + static void F() + { + Func f = null; + + f = x => 1 + Goo(x); + + Console.Write(f(2)); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -9345,52 +10281,56 @@ static void F() [Fact] public void Try_Lambda2() { - var src1 = @" -using System; -using System.Linq; -class C -{ - static int Goo(int x) - { - return 1; - } + var src1 = """ - static void F() - { - Func f = x => - { - try + using System; + using System.Linq; + class C { - return 1 + Goo(x); + static int Goo(int x) + { + return 1; + } + + static void F() + { + Func f = x => + { + try + { + return 1 + Goo(x); + } + catch + { + } + }; + + Console.Write(f(2)); + } } - catch - { - } - }; + """; + var src2 = """ - Console.Write(f(2)); - } -}"; - var src2 = @" -using System; -using System.Linq; -class C -{ - static int Goo(int x) - { - return 1; - } + using System; + using System.Linq; + class C + { + static int Goo(int x) + { + return 1; + } - static void F() - { - Func f = x => - { - return 1 + Goo(x); - }; + static void F() + { + Func f = x => + { + return 1 + Goo(x); + }; - Console.Write(f(2)); - } -}"; + Console.Write(f(2)); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -9402,46 +10342,50 @@ static void F() [Fact] public void Try_Query_Join1() { - var src1 = @" -class C -{ - static int Goo(int x) - { - return 1; - } + var src1 = """ - static void F() - { - try - { - q = from x in xs - join y in ys on F() equals G() - select 1; - } - catch - { - } + class C + { + static int Goo(int x) + { + return 1; + } - q.ToArray(); - } -}"; - var src2 = @" -class C -{ - static int Goo(int x) - { - return 1; - } + static void F() + { + try + { + q = from x in xs + join y in ys on F() equals G() + select 1; + } + catch + { + } - static void F() - { - q = from x in xs - join y in ys on F() equals G() - select 1; + q.ToArray(); + } + } + """; + var src2 = """ - q.ToArray(); - } -}"; + class C + { + static int Goo(int x) + { + return 1; + } + + static void F() + { + q = from x in xs + join y in ys on F() equals G() + select 1; + + q.ToArray(); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -9456,65 +10400,73 @@ static void F() [Fact] public void CheckedUnchecked_Insert_Leaf() { - var src1 = @" -class Test -{ - static void Main(string[] args) - { - int a = 1, b = 2; - Console.WriteLine(a*b); - } -}"; - var src2 = @" -class Test -{ - static void Main(string[] args) - { - int a = 1, b = 2; - checked - { - Console.WriteLine(a*b); - } - } -}"; + var src1 = """ + + class Test + { + static void Main(string[] args) + { + int a = 1, b = 2; + Console.WriteLine(a*b); + } + } + """; + var src2 = """ + + class Test + { + static void Main(string[] args) + { + int a = 1, b = 2; + checked + { + Console.WriteLine(a*b); + } + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active); } - [Fact] - public void CheckedUnchecked_Insert_Internal() - { - var src1 = @" -class Test -{ - static void Main(string[] args) - { - System.Console.WriteLine(5 * M(1, 2)); - } - - private static int M(int a, int b) - { - return a * b; - } -}"; - var src2 = @" -class Test -{ - static void Main(string[] args) - { - checked - { - System.Console.WriteLine(5 * M(1, 2)); - } - } - - private static int M(int a, int b) + [Fact] + public void CheckedUnchecked_Insert_Internal() { - return a * b; - } -}"; + var src1 = """ + + class Test + { + static void Main(string[] args) + { + System.Console.WriteLine(5 * M(1, 2)); + } + + private static int M(int a, int b) + { + return a * b; + } + } + """; + var src2 = """ + + class Test + { + static void Main(string[] args) + { + checked + { + System.Console.WriteLine(5 * M(1, 2)); + } + } + + private static int M(int a, int b) + { + return a * b; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -9525,35 +10477,39 @@ private static int M(int a, int b) [Fact] public void CheckedUnchecked_Delete_Internal() { - var src1 = @" -class Test -{ - static void Main(string[] args) - { - checked - { - System.Console.WriteLine(5 * M(1, 2)); - } - } + var src1 = """ - private static int M(int a, int b) - { - return a * b; - } -}"; - var src2 = @" -class Test -{ - static void Main(string[] args) - { - System.Console.WriteLine(5 * M(1, 2)); - } + class Test + { + static void Main(string[] args) + { + checked + { + System.Console.WriteLine(5 * M(1, 2)); + } + } - private static int M(int a, int b) - { - return a * b; - } -}"; + private static int M(int a, int b) + { + return a * b; + } + } + """; + var src2 = """ + + class Test + { + static void Main(string[] args) + { + System.Console.WriteLine(5 * M(1, 2)); + } + + private static int M(int a, int b) + { + return a * b; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -9564,38 +10520,42 @@ private static int M(int a, int b) [Fact] public void CheckedUnchecked_Update_Internal() { - var src1 = @" -class Test -{ - static void Main(string[] args) - { - unchecked - { - System.Console.WriteLine(5 * M(1, 2)); - } - } + var src1 = """ - private static int M(int a, int b) - { - return a * b; - } -}"; - var src2 = @" -class Test -{ - static void Main(string[] args) - { - checked - { - System.Console.WriteLine(5 * M(1, 2)); - } - } + class Test + { + static void Main(string[] args) + { + unchecked + { + System.Console.WriteLine(5 * M(1, 2)); + } + } - private static int M(int a, int b) - { - return a * b; - } -}"; + private static int M(int a, int b) + { + return a * b; + } + } + """; + var src2 = """ + + class Test + { + static void Main(string[] args) + { + checked + { + System.Console.WriteLine(5 * M(1, 2)); + } + } + + private static int M(int a, int b) + { + return a * b; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -9606,42 +10566,46 @@ private static int M(int a, int b) [Fact] public void CheckedUnchecked_Lambda1() { - var src1 = @" -class Test -{ - static void Main(string[] args) - { - unchecked - { - Action f = () => 5 * M(1, 2); - } + var src1 = """ - f(); - } + class Test + { + static void Main(string[] args) + { + unchecked + { + Action f = () => 5 * M(1, 2); + } - private static int M(int a, int b) - { - return a * b; - } -}"; - var src2 = @" -class Test -{ - static void Main(string[] args) - { - checked - { - Action f = () => 5 * M(1, 2); - } + f(); + } - f(); - } + private static int M(int a, int b) + { + return a * b; + } + } + """; + var src2 = """ - private static int M(int a, int b) - { - return a * b; - } -}"; + class Test + { + static void Main(string[] args) + { + checked + { + Action f = () => 5 * M(1, 2); + } + + f(); + } + + private static int M(int a, int b) + { + return a * b; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -9652,50 +10616,54 @@ private static int M(int a, int b) [Fact] public void CheckedUnchecked_Query1() { - var src1 = @" -using System.Collections.Generic; -using System.Linq; + var src1 = """ -class Test -{ - static void F() - { - IEnumerable f; - unchecked - { - f = from a in new[] { 5 } select M(a, int.MaxValue); - } + using System.Collections.Generic; + using System.Linq; - f.ToArray(); - } + class Test + { + static void F() + { + IEnumerable f; + unchecked + { + f = from a in new[] { 5 } select M(a, int.MaxValue); + } - private static int M(int a, int b) - { - return a * b; - } -}"; - var src2 = @" -using System.Collections.Generic; -using System.Linq; + f.ToArray(); + } -class Test -{ - static void F() - { - IEnumerable f; - checked - { - f = from a in new[] { 5 } select M(a, int.MaxValue); - } + private static int M(int a, int b) + { + return a * b; + } + } + """; + var src2 = """ - f.ToArray(); - } + using System.Collections.Generic; + using System.Linq; - private static int M(int a, int b) - { - return a * b; - } -}"; + class Test + { + static void F() + { + IEnumerable f; + checked + { + f = from a in new[] { 5 } select M(a, int.MaxValue); + } + + f.ToArray(); + } + + private static int M(int a, int b) + { + return a * b; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -9710,24 +10678,28 @@ private static int M(int a, int b) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_GeneralStatement() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - F(a => 1); - } -} -"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - F(a => 2); - } -} -"; + var src1 = """ + + class C + { + static void Main(string[] args) + { + F(a => 1); + } + } + + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + F(a => 2); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -9737,24 +10709,28 @@ static void Main(string[] args) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_Nested1() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - F(b => F(a => 1)); - } -} -"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - F(b => F(a => 2)); - } -} -"; + var src1 = """ + + class C + { + static void Main(string[] args) + { + F(b => F(a => 1)); + } + } + + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + F(b => F(a => 2)); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -9764,24 +10740,28 @@ static void Main(string[] args) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_Nested2() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - F(b => F(a => 1)); - } -} -"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - F(b => G(a => 2)); - } -} -"; + var src1 = """ + + class C + { + static void Main(string[] args) + { + F(b => F(a => 1)); + } + } + + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + F(b => G(a => 2)); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -9789,27 +10769,31 @@ static void Main(string[] args) Diagnostic(RudeEditKind.ActiveStatementUpdate, "G(a => 2 )")); } - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1359")] - public void Lambdas_LeafEdits_IfStatement() - { - var src1 = @" -class C -{ - static void Main(string[] args) - { - if (F(a => 1)) { } - } -} -"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - if (F(a => 2)) { } - } -} -"; + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1359")] + public void Lambdas_LeafEdits_IfStatement() + { + var src1 = """ + + class C + { + static void Main(string[] args) + { + if (F(a => 1)) { } + } + } + + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + if (F(a => 2)) { } + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -9819,24 +10803,28 @@ static void Main(string[] args) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_WhileStatement() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - while (F(a => 1)) { } - } -} -"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - while (F(a => 2)) { } - } -} -"; + var src1 = """ + + class C + { + static void Main(string[] args) + { + while (F(a => 1)) { } + } + } + + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + while (F(a => 2)) { } + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -9846,24 +10834,28 @@ static void Main(string[] args) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_DoStatement() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - do {} while (F(a => 1)); - } -} -"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - do {} while (F(a => 2)); - } -} -"; + var src1 = """ + + class C + { + static void Main(string[] args) + { + do {} while (F(a => 1)); + } + } + + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + do {} while (F(a => 2)); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -9873,32 +10865,36 @@ static void Main(string[] args) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_SwitchStatement() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - switch (F(a => 1)) - { - case 0: break; - case 1: break; - } - } -} -"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - switch (F(a => 2)) - { - case 0: break; - case 1: break; - } - } -} -"; + var src1 = """ + + class C + { + static void Main(string[] args) + { + switch (F(a => 1)) + { + case 0: break; + case 1: break; + } + } + } + + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + switch (F(a => 2)) + { + case 0: break; + case 1: break; + } + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -9908,24 +10904,28 @@ static void Main(string[] args) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_LockStatement() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - lock (F(a => 1)) {} - } -} -"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - lock (F(a => 2)) {} - } -} -"; + var src1 = """ + + class C + { + static void Main(string[] args) + { + lock (F(a => 1)) {} + } + } + + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + lock (F(a => 2)) {} + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -9935,24 +10935,28 @@ static void Main(string[] args) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_UsingStatement1() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - using (F(a => 1)) {} - } -} -"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - using (F(a => 2)) {} - } -} -"; + var src1 = """ + + class C + { + static void Main(string[] args) + { + using (F(a => 1)) {} + } + } + + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + using (F(a => 2)) {} + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -9965,24 +10969,28 @@ public void Lambdas_ExpressionToStatements() { // TODO: The active statement should be mapped to the return statement. - var src1 = @" -class C -{ - static void Main() - { - Func f = a => 1; - } -} -"; - var src2 = @" -class C -{ - static void Main() - { - Func f = a => { return 1; }; - } -} -"; + var src1 = """ + + class C + { + static void Main() + { + Func f = a => 1; + } + } + + """; + var src2 = """ + + class C + { + static void Main() + { + Func f = a => { return 1; }; + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -9995,24 +11003,28 @@ public void Lambdas_ExpressionToStatements_WithSignatureChange() { // TODO: The active statement should be mapped to the return statement. - var src1 = @" -class C -{ - static void Main() - { - Func f = a => 1; - } -} -"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - Func f = a => { return 1; }; - } -} -"; + var src1 = """ + + class C + { + static void Main() + { + Func f = a => 1; + } + } + + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + Func f = a => { return 1; }; + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -10024,26 +11036,30 @@ static void Main(string[] args) [Fact] public void Lambdas_ExpressionToDelegate() { - var src1 = @" -using System; -class C -{ - static void F() - { - Func f = a => 1; - } -} -"; - var src2 = @" -using System; -class C -{ - static void F() - { - Func f = delegate(int a) { return 1; }; - } -} -"; + var src1 = """ + + using System; + class C + { + static void F() + { + Func f = a => 1; + } + } + + """; + var src2 = """ + + using System; + class C + { + static void F() + { + Func f = delegate(int a) { return 1; }; + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -10102,24 +11118,28 @@ void G() [Fact] public void Lambdas_StatementsToExpression() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Func f = a => { return 1; }; - } -} -"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - Func f = a => 1; - } -} -"; + var src1 = """ + + class C + { + static void Main(string[] args) + { + Func f = a => { return 1; }; + } + } + + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + Func f = a => 1; + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -10129,26 +11149,30 @@ static void Main(string[] args) [Fact] public void Lambdas_DelegateToExpression() { - var src1 = @" -using System; -class C -{ - static void F() - { - Func f = delegate(int a) { return 1; }; - } -} -"; - var src2 = @" -using System; -class C -{ - static void F() - { - Func f = a => 1; - } -} -"; + var src1 = """ + + using System; + class C + { + static void F() + { + Func f = delegate(int a) { return 1; }; + } + } + + """; + var src2 = """ + + using System; + class C + { + static void F() + { + Func f = a => 1; + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -10158,26 +11182,30 @@ static void F() [Fact] public void Lambdas_StatementsToDelegate() { - var src1 = @" -using System; -class C -{ - static void F() - { - Func f = a => { return 1; }; - } -} -"; - var src2 = @" -using System; -class C -{ - static void F() - { - Func f = delegate(int a) { return 2; }; - } -} -"; + var src1 = """ + + using System; + class C + { + static void F() + { + Func f = a => { return 1; }; + } + } + + """; + var src2 = """ + + using System; + class C + { + static void F() + { + Func f = delegate(int a) { return 2; }; + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -10187,27 +11215,31 @@ static void F() [Fact] public void Lambdas_ActiveStatementUpdate() { - var src1 = @" -using System; -class C -{ - static void Main(string[] args) - { - Func f = (int a, int b) => a + b + 1; - f(2); - } -}"; - var src2 = @" -using System; -class C -{ - static void Main(string[] args) - { - Func f = (_, _) => 10; - f(2); - } -} -"; + var src1 = """ + + using System; + class C + { + static void Main(string[] args) + { + Func f = (int a, int b) => a + b + 1; + f(2); + } + } + """; + var src2 = """ + + using System; + class C + { + static void Main(string[] args) + { + Func f = (_, _) => 10; + f(2); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -10217,38 +11249,42 @@ static void Main(string[] args) [Fact] public void Lambdas_ActiveStatementRemoved1() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Func> f = a => - { - return b => + var src1 = """ + + class C { - return b; - }; - }; + static void Main(string[] args) + { + Func> f = a => + { + return b => + { + return b; + }; + }; - var z = f(1); - z(2); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - Func f = b => - { - return b; - }; + var z = f(1); + z(2); + } + } + """; + var src2 = """ - var z = f; - z(2); - } -} -"; + class C + { + static void Main(string[] args) + { + Func f = b => + { + return b; + }; + + var z = f; + z(2); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -10259,29 +11295,33 @@ static void Main(string[] args) [Fact] public void Lambdas_ActiveStatementRemoved2() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Func> f = a => (b) => b; + var src1 = """ - var z = f(1); - z(2); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - Func f = (b) => b; + class C + { + static void Main(string[] args) + { + Func> f = a => (b) => b; - var z = f; - z(2); - } -} -"; + var z = f(1); + z(2); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + Func f = (b) => b; + + var z = f; + z(2); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -10292,44 +11332,48 @@ static void Main(string[] args) [Fact] public void Lambdas_ActiveStatementRemoved3() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Func> f = a => - { - Func z; + var src1 = """ - F(b => + class C { - return b; - }, out z); + static void Main(string[] args) + { + Func> f = a => + { + Func z; + + F(b => + { + return b; + }, out z); - return z; - }; + return z; + }; - var z = f(1); - z(2); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - Func f = b => - { - F(b); + var z = f(1); + z(2); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + Func f = b => + { + F(b); - return 1; - }; + return 1; + }; - var z = f; - z(2); - } -} -"; + var z = f; + z(2); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -10340,31 +11384,35 @@ static void Main(string[] args) [Fact] public void Lambdas_ActiveStatementRemoved4() { - var src1 = @" -class C -{ - static void Main() - { - Func> f = a => - { - z(2); + var src1 = """ - return b => + class C { - return b; - }; - }; - } -}"; - var src2 = @" -class C -{ - static void Main() - { - - } -} -"; + static void Main() + { + Func> f = a => + { + z(2); + + return b => + { + return b; + }; + }; + } + } + """; + var src2 = """ + + class C + { + static void Main() + { + + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -10635,25 +11683,29 @@ public C() : this(0) [Fact] public void Queries_ActiveStatementRemoved_WhereClause() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - var s = from a in b where b.goo select b.bar; - s.ToArray(); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - var s = from a in b select b.bar; - s.ToArray(); - } -} -"; + var src1 = """ + + class C + { + static void Main(string[] args) + { + var s = from a in b where b.goo select b.bar; + s.ToArray(); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + var s = from a in b select b.bar; + s.ToArray(); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -10664,25 +11716,29 @@ static void Main(string[] args) [Fact] public void Queries_ActiveStatementRemoved_LetClause() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - var s = from a in b let x = b.goo select x; - s.ToArray(); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - var s = from a in b select a.bar; - s.ToArray(); - } -} -"; + var src1 = """ + + class C + { + static void Main(string[] args) + { + var s = from a in b let x = b.goo select x; + s.ToArray(); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + var s = from a in b select a.bar; + s.ToArray(); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -10693,28 +11749,32 @@ static void Main(string[] args) [Fact] public void Queries_ActiveStatementRemoved_JoinClauseLeft() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - var s = from a in b - join c in d on a.goo equals c.bar - select a.bar; + var src1 = """ - s.ToArray(); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - var s = from a in b select a.bar; - s.ToArray(); - } -} -"; + class C + { + static void Main(string[] args) + { + var s = from a in b + join c in d on a.goo equals c.bar + select a.bar; + + s.ToArray(); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + var s = from a in b select a.bar; + s.ToArray(); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -10725,28 +11785,32 @@ static void Main(string[] args) [Fact] public void Queries_ActiveStatementRemoved_OrderBy1() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - var s = from a in b - orderby a.x, a.y descending, a.z ascending - select a; + var src1 = """ - s.ToArray(); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - var s = from a in b select a.bar; - s.ToArray(); - } -} -"; + class C + { + static void Main(string[] args) + { + var s = from a in b + orderby a.x, a.y descending, a.z ascending + select a; + + s.ToArray(); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + var s = from a in b select a.bar; + s.ToArray(); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -10757,28 +11821,32 @@ static void Main(string[] args) [Fact] public void Queries_ActiveStatementRemoved_OrderBy2() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - var s = from a in b - orderby a.x, a.y descending, a.z ascending - select a; + var src1 = """ - s.ToArray(); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - var s = from a in b select a.bar; - s.ToArray(); - } -} -"; + class C + { + static void Main(string[] args) + { + var s = from a in b + orderby a.x, a.y descending, a.z ascending + select a; + + s.ToArray(); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + var s = from a in b select a.bar; + s.ToArray(); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -10789,28 +11857,32 @@ static void Main(string[] args) [Fact] public void Queries_ActiveStatementRemoved_OrderBy3() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - var s = from a in b - orderby a.x, a.y descending, a.z ascending - select a; + var src1 = """ - s.ToArray(); - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - var s = from a in b select a.bar; - s.ToArray(); - } -} -"; + class C + { + static void Main(string[] args) + { + var s = from a in b + orderby a.x, a.y descending, a.z ascending + select a; + + s.ToArray(); + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + var s = from a in b select a.bar; + s.ToArray(); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -10821,26 +11893,30 @@ static void Main(string[] args) [Fact] public void Queries_Remove_JoinInto1() { - var src1 = @" -class C -{ - static void F() - { - var q = from x in xs - join y in ys on F() equals G() into g - select 1; - } -}"; - var src2 = @" -class C -{ - static void F() - { - var q = from x in xs - join y in ys on F() equals G() - select 1; - } -}"; + var src1 = """ + + class C + { + static void F() + { + var q = from x in xs + join y in ys on F() equals G() into g + select 1; + } + } + """; + var src2 = """ + + class C + { + static void F() + { + var q = from x in xs + join y in ys on F() equals G() + select 1; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -10851,27 +11927,31 @@ join y in ys on F() equals G() [Fact] public void Queries_Remove_QueryContinuation1() { - var src1 = @" -class C -{ - static void F() - { - var q = from x in xs - group x by x.F() into g - where g.F() - select 1; - } -}"; - var src2 = @" -class C -{ - static void F() - { - var q = from x in xs - group x by x.F() into g - select 1; - } -}"; + var src1 = """ + + class C + { + static void F() + { + var q = from x in xs + group x by x.F() into g + where g.F() + select 1; + } + } + """; + var src2 = """ + + class C + { + static void F() + { + var q = from x in xs + group x by x.F() into g + select 1; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -10883,26 +11963,30 @@ group x by x.F() into g [Fact] public void Queries_Remove_QueryContinuation2() { - var src1 = @" -class C -{ - static void F() - { - var q = from x in xs - group x by x.F() into g - select 1; - } -}"; - var src2 = @" -class C -{ - static void F() - { - var q = from x in xs - join y in ys on F() equals G() into g - select 1; - } -}"; + var src1 = """ + + class C + { + static void F() + { + var q = from x in xs + group x by x.F() into g + select 1; + } + } + """; + var src2 = """ + + class C + { + static void F() + { + var q = from x in xs + join y in ys on F() equals G() into g + select 1; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -10914,26 +11998,30 @@ static void F() [Fact] public void Queries_Select_Reduced1() { - var src1 = @" -class C -{ - static void F() - { - var q = from a in array - where a > 0 - select a + 1; - } -}"; - var src2 = @" -class C -{ - static void F() - { - var q = from a in array - where a > 0 - select a; - } -}"; + var src1 = """ + + class C + { + static void F() + { + var q = from a in array + where a > 0 + select a + 1; + } + } + """; + var src2 = """ + + class C + { + static void F() + { + var q = from a in array + where a > 0 + select a; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -10945,26 +12033,30 @@ where a > 0 [Fact] public void Queries_Select_Reduced2() { - var src1 = @" -class C -{ - static int F(IEnumerable e) => 1; + var src1 = """ - static void F() - { - F(from a in array where a > 0 select a + 1); - } -}"; - var src2 = @" -class C -{ - static int F(IEnumerable e) => 1; - - static void F() - { - F(from a in array where a > 0 select a); - } -}"; + class C + { + static int F(IEnumerable e) => 1; + + static void F() + { + F(from a in array where a > 0 select a + 1); + } + } + """; + var src2 = """ + + class C + { + static int F(IEnumerable e) => 1; + + static void F() + { + F(from a in array where a > 0 select a); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -10976,24 +12068,28 @@ static void F() [Fact] public void Queries_GroupBy_Reduced1() { - var src1 = @" -class C -{ - static void F() - { - var q = from a in array - group a + 1 by a; - } -}"; - var src2 = @" -class C -{ - static void F() - { - var q = from a in array - group a by a; - } -}"; + var src1 = """ + + class C + { + static void F() + { + var q = from a in array + group a + 1 by a; + } + } + """; + var src2 = """ + + class C + { + static void F() + { + var q = from a in array + group a by a; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11005,26 +12101,30 @@ static void F() [Fact] public void Queries_GroupBy_Reduced2() { - var src1 = @" -class C -{ - static int F(IEnumerable> e) => 1; + var src1 = """ - static void F() - { - F(from a in array group a by a); - } -}"; - var src2 = @" -class C -{ - static int F(IEnumerable> e) => 1; - - static void F() - { - F(from a in array group a + 1 by a); - } -}"; + class C + { + static int F(IEnumerable> e) => 1; + + static void F() + { + F(from a in array group a by a); + } + } + """; + var src2 = """ + + class C + { + static int F(IEnumerable> e) => 1; + + static void F() + { + F(from a in array group a + 1 by a); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11040,26 +12140,30 @@ static void F() [Fact] public void MethodToIteratorMethod_WithActiveStatement() { - var src1 = @" -class C -{ - static IEnumerable F() - { - Console.WriteLine(1); - return new[] { 1, 2, 3 }; - } -} -"; - var src2 = @" -class C -{ - static IEnumerable F() - { - Console.WriteLine(1); - yield return 1; - } -} -"; + var src1 = """ + + class C + { + static IEnumerable F() + { + Console.WriteLine(1); + return new[] { 1, 2, 3 }; + } + } + + """; + var src2 = """ + + class C + { + static IEnumerable F() + { + Console.WriteLine(1); + yield return 1; + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11070,26 +12174,30 @@ static IEnumerable F() [Fact] public void MethodToIteratorMethod_WithActiveStatementInLambda() { - var src1 = @" -class C -{ - static IEnumerable F() - { - var f = new Action(() => { Console.WriteLine(1); }); - return new[] { 1, 2, 3 }; - } -} -"; - var src2 = @" -class C -{ - static IEnumerable F() - { - var f = new Action(() => { Console.WriteLine(1); }); - yield return 1; - } -} -"; + var src1 = """ + + class C + { + static IEnumerable F() + { + var f = new Action(() => { Console.WriteLine(1); }); + return new[] { 1, 2, 3 }; + } + } + + """; + var src2 = """ + + class C + { + static IEnumerable F() + { + var f = new Action(() => { Console.WriteLine(1); }); + yield return 1; + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11102,26 +12210,30 @@ static IEnumerable F() [Fact] public void MethodToIteratorMethod_WithoutActiveStatement() { - var src1 = @" -class C -{ - static IEnumerable F() - { - Console.WriteLine(1); - return new[] { 1, 2, 3 }; - } -} -"; - var src2 = @" -class C -{ - static IEnumerable F() - { - Console.WriteLine(1); - yield return 1; - } -} -"; + var src1 = """ + + class C + { + static IEnumerable F() + { + Console.WriteLine(1); + return new[] { 1, 2, 3 }; + } + } + + """; + var src2 = """ + + class C + { + static IEnumerable F() + { + Console.WriteLine(1); + yield return 1; + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11133,27 +12245,31 @@ static IEnumerable F() [Fact] public void MethodToAsyncMethod_WithActiveStatement_AwaitExpression() { - var src1 = @" -class C -{ - static Task F() - { - Console.WriteLine(1); + var src1 = """ - return Task.FromResult(1); - } -} -"; - var src2 = @" -class C -{ - static async Task F() - { - Console.WriteLine(1); - return await Task.FromResult(1); - } -} -"; + class C + { + static Task F() + { + Console.WriteLine(1); + + return Task.FromResult(1); + } + } + + """; + var src2 = """ + + class C + { + static async Task F() + { + Console.WriteLine(1); + return await Task.FromResult(1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11164,28 +12280,32 @@ static async Task F() [Fact] public void MethodToAsyncMethod_WithActiveStatement_AwaitForEach() { - var src1 = @" -class C -{ - static Task F() - { - Console.WriteLine(1); + var src1 = """ - return Task.FromResult(1); - } -} -"; - var src2 = @" -class C -{ - static async Task F() - { - Console.WriteLine(1); - await foreach (var x in AsyncIter()) { } - return 1; - } -} -"; + class C + { + static Task F() + { + Console.WriteLine(1); + + return Task.FromResult(1); + } + } + + """; + var src2 = """ + + class C + { + static async Task F() + { + Console.WriteLine(1); + await foreach (var x in AsyncIter()) { } + return 1; + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11196,28 +12316,32 @@ static async Task F() [Fact] public void MethodToAsyncMethod_WithActiveStatement_AwaitUsing() { - var src1 = @" -class C -{ - static Task F() - { - Console.WriteLine(1); + var src1 = """ - return Task.FromResult(1); - } -} -"; - var src2 = @" -class C -{ - static async Task F() - { - Console.WriteLine(1); - await using IAsyncDisposable x = new AsyncDisposable(), y = new AsyncDisposable(); - return 1; - } -} -"; + class C + { + static Task F() + { + Console.WriteLine(1); + + return Task.FromResult(1); + } + } + + """; + var src2 = """ + + class C + { + static async Task F() + { + Console.WriteLine(1); + await using IAsyncDisposable x = new AsyncDisposable(), y = new AsyncDisposable(); + return 1; + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11228,24 +12352,28 @@ static async Task F() [Fact] public void MethodToAsyncMethod_WithActiveStatement_NoAwait1() { - var src1 = @" -class C -{ - static void F() - { - Console.WriteLine(1); - } -} -"; - var src2 = @" -class C -{ - static async void F() - { - Console.WriteLine(1); - } -} -"; + var src1 = """ + + class C + { + static void F() + { + Console.WriteLine(1); + } + } + + """; + var src2 = """ + + class C + { + static async void F() + { + Console.WriteLine(1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11256,24 +12384,28 @@ static async void F() [Fact] public void MethodToAsyncMethod_WithActiveStatement_NoAwait2() { - var src1 = @" -class C -{ - static void F() - { - Console.WriteLine(1); - } -} -"; - var src2 = @" -class C -{ - static async void F() - { - Console.WriteLine(1); - } -} -"; + var src1 = """ + + class C + { + static void F() + { + Console.WriteLine(1); + } + } + + """; + var src2 = """ + + class C + { + static async void F() + { + Console.WriteLine(1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11284,26 +12416,30 @@ static async void F() [Fact] public void MethodToAsyncMethod_WithActiveStatementInLambda1() { - var src1 = @" -class C -{ - static Task F() - { - var f = new Action(() => { Console.WriteLine(1); }); - return Task.FromResult(1); - } -} -"; - var src2 = @" -class C -{ - static async Task F() - { - var f = new Action(() => { Console.WriteLine(1); }); - return await Task.FromResult(1); - } -} -"; + var src1 = """ + + class C + { + static Task F() + { + var f = new Action(() => { Console.WriteLine(1); }); + return Task.FromResult(1); + } + } + + """; + var src2 = """ + + class C + { + static async Task F() + { + var f = new Action(() => { Console.WriteLine(1); }); + return await Task.FromResult(1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11313,29 +12449,33 @@ static async Task F() capabilities: EditAndContinueCapabilities.NewTypeDefinition | EditAndContinueCapabilities.AddExplicitInterfaceImplementation); } - [Fact] - public void MethodToAsyncMethod_WithActiveStatementInLambda_2() - { - var src1 = @" -class C -{ - static void F() - { - var f = new Action(() => { Console.WriteLine(1); }); - f(); - } -} -"; - var src2 = @" -class C -{ - static async void F() - { - var f = new Action(() => { Console.WriteLine(1); }); - f(); - } -} -"; + [Fact] + public void MethodToAsyncMethod_WithActiveStatementInLambda_2() + { + var src1 = """ + + class C + { + static void F() + { + var f = new Action(() => { Console.WriteLine(1); }); + f(); + } + } + + """; + var src2 = """ + + class C + { + static async void F() + { + var f = new Action(() => { Console.WriteLine(1); }); + f(); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11346,26 +12486,30 @@ static async void F() [Fact] public void MethodToAsyncMethod_WithLambda() { - var src1 = @" -class C -{ - static void F() - { - var f = new Action(() => { Console.WriteLine(1); }); - f(); - } -} -"; - var src2 = @" -class C -{ - static async void F() - { - var f = new Action(() => { Console.WriteLine(1); }); - f(); - } -} -"; + var src1 = """ + + class C + { + static void F() + { + var f = new Action(() => { Console.WriteLine(1); }); + f(); + } + } + + """; + var src2 = """ + + class C + { + static async void F() + { + var f = new Action(() => { Console.WriteLine(1); }); + f(); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11376,26 +12520,30 @@ static async void F() [Fact] public void MethodToAsyncMethod_WithoutActiveStatement_1() { - var src1 = @" -class C -{ - static Task F() - { - Console.WriteLine(1); - return Task.FromResult(1); - } -} -"; - var src2 = @" -class C -{ - static async Task F() - { - Console.WriteLine(1); - return await Task.FromResult(1); - } -} -"; + var src1 = """ + + class C + { + static Task F() + { + Console.WriteLine(1); + return Task.FromResult(1); + } + } + + """; + var src2 = """ + + class C + { + static async Task F() + { + Console.WriteLine(1); + return await Task.FromResult(1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11407,24 +12555,28 @@ static async Task F() [Fact] public void MethodToAsyncMethod_WithoutActiveStatement_2() { - var src1 = @" -class C -{ - static void F() - { - Console.WriteLine(1); - } -} -"; - var src2 = @" -class C -{ - static async void F() - { - Console.WriteLine(1); - } -} -"; + var src1 = """ + + class C + { + static void F() + { + Console.WriteLine(1); + } + } + + """; + var src2 = """ + + class C + { + static async void F() + { + Console.WriteLine(1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11435,38 +12587,42 @@ static async void F() [Fact] public void LambdaToAsyncLambda_WithActiveStatement() { - var src1 = @" -using System; -using System.Threading.Tasks; + var src1 = """ -class C -{ - static void F() - { - var f = new Func>(() => - { - Console.WriteLine(1); - return Task.FromResult(1); - }); - } -} -"; - var src2 = @" -using System; -using System.Threading.Tasks; + using System; + using System.Threading.Tasks; -class C -{ - static void F() - { - var f = new Func>(async () => - { - Console.WriteLine(1); - return await Task.FromResult(1); - }); - } -} -"; + class C + { + static void F() + { + var f = new Func>(() => + { + Console.WriteLine(1); + return Task.FromResult(1); + }); + } + } + + """; + var src2 = """ + + using System; + using System.Threading.Tasks; + + class C + { + static void F() + { + var f = new Func>(async () => + { + Console.WriteLine(1); + return await Task.FromResult(1); + }); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11477,28 +12633,32 @@ static void F() [Fact] public void LambdaToAsyncLambda_WithActiveStatement_NoAwait() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static void F() - { - var f = new Action(() => { Console.WriteLine(1); }); - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - static void F() - { - var f = new Action(async () => { Console.WriteLine(1); }); - } -} -"; + class C + { + static void F() + { + var f = new Action(() => { Console.WriteLine(1); }); + } + } + + """; + var src2 = """ + + using System; + + class C + { + static void F() + { + var f = new Action(async () => { Console.WriteLine(1); }); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11509,24 +12669,28 @@ static void F() [Fact] public void LambdaToAsyncLambda_WithActiveStatement_NoAwait_Nested() { - var src1 = @" -class C -{ - static void F() - { - var f = new Func>(a => b => 1); - } -} -"; - var src2 = @" -class C -{ - static void F() - { - var f = new Func>(async a => b => 1); - } -} -"; + var src1 = """ + + class C + { + static void F() + { + var f = new Func>(a => b => 1); + } + } + + """; + var src2 = """ + + class C + { + static void F() + { + var f = new Func>(async a => b => 1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11537,32 +12701,36 @@ static void F() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37054")] public void LocalFunctionToAsyncLocalFunction_BlockBody_WithActiveStatement() { - var src1 = @" -class C -{ - static void F() - { - Task f() - { - Console.WriteLine(1); - return Task.FromResult(1); - } - } -} -"; - var src2 = @" -class C -{ - static void F() - { - async Task f() - { - Console.WriteLine(1); - return await Task.FromResult(1); - } - } -} -"; + var src1 = """ + + class C + { + static void F() + { + Task f() + { + Console.WriteLine(1); + return Task.FromResult(1); + } + } + } + + """; + var src2 = """ + + class C + { + static void F() + { + async Task f() + { + Console.WriteLine(1); + return await Task.FromResult(1); + } + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11622,24 +12790,28 @@ void G() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37054")] public void LocalFunctionToAsyncLocalFunction_ExpressionBody_WithActiveStatement() { - var src1 = @" -class C -{ - static void F() - { - Task f() => Task.FromResult(1); - } -} -"; - var src2 = @" -class C -{ - static void F() - { - async Task f() => await Task.FromResult(1); - } -} -"; + var src1 = """ + + class C + { + static void F() + { + Task f() => Task.FromResult(1); + } + } + + """; + var src2 = """ + + class C + { + static void F() + { + async Task f() => await Task.FromResult(1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11650,28 +12822,32 @@ static void F() [Fact] public void AnonymousFunctionToAsyncAnonymousFunction_WithActiveStatement_NoAwait() { - var src1 = @" -using System.Threading.Tasks; + var src1 = """ -class C -{ - static void F() - { - var f = new Func(delegate() { Console.WriteLine(1); return Task.CompletedTask; }); - } -} -"; - var src2 = @" -using System.Threading.Tasks; + using System.Threading.Tasks; -class C -{ - static async void F() - { - var f = new Func(async delegate() { Console.WriteLine(1); }); - } -} -"; + class C + { + static void F() + { + var f = new Func(delegate() { Console.WriteLine(1); return Task.CompletedTask; }); + } + } + + """; + var src2 = """ + + using System.Threading.Tasks; + + class C + { + static async void F() + { + var f = new Func(async delegate() { Console.WriteLine(1); }); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11682,44 +12858,48 @@ static async void F() [Fact] public void AsyncMethodEdit_Semantics() { - var src1 = @" -using System; -using System.Threading.Tasks; + var src1 = """ -class C -{ - static async Task F() - { - await using var x = new AsyncDisposable(); + using System; + using System.Threading.Tasks; - await foreach (var x in AsyncIter()) - { - Console.WriteLine(x); - } + class C + { + static async Task F() + { + await using var x = new AsyncDisposable(); - return await Task.FromResult(1); - } -} -"; - var src2 = @" -using System; -using System.Threading.Tasks; + await foreach (var x in AsyncIter()) + { + Console.WriteLine(x); + } -class C -{ - static async Task F() - { - await using var x = new AsyncDisposable(); + return await Task.FromResult(1); + } + } - await foreach (var x in AsyncIter()) - { - Console.WriteLine(x + 1); - } + """; + var src2 = """ - return await Task.FromResult(2); - } -} -"; + using System; + using System.Threading.Tasks; + + class C + { + static async Task F() + { + await using var x = new AsyncDisposable(); + + await foreach (var x in AsyncIter()) + { + Console.WriteLine(x + 1); + } + + return await Task.FromResult(2); + } + } + + """; var edits = GetTopEdits(src1, src2); _ = GetActiveStatements(src1, src2); @@ -11730,32 +12910,36 @@ static async Task F() [Fact] public void IteratorMethodEdit_Semantics() { - var src1 = @" -using System; -using System.Collections.Generic; + var src1 = """ -class C -{ - static IEnumerable F() - { - Console.WriteLine(1); - yield return 1; - } -} -"; - var src2 = @" -using System; -using System.Collections.Generic; + using System; + using System.Collections.Generic; -class C -{ - static IEnumerable F() - { - Console.WriteLine(2); - yield return 2; - } -} -"; + class C + { + static IEnumerable F() + { + Console.WriteLine(1); + yield return 1; + } + } + + """; + var src2 = """ + + using System; + using System.Collections.Generic; + + class C + { + static IEnumerable F() + { + Console.WriteLine(2); + yield return 2; + } + } + + """; var edits = GetTopEdits(src1, src2); _ = GetActiveStatements(src1, src2); @@ -11766,36 +12950,40 @@ static IEnumerable F() [Fact] public void AsyncIteratorMethodEdit_Semantics() { - var src1 = @" -using System; -using System.Collections.Generic; -using System.Threading.Tasks; + var src1 = """ -class C -{ - static async IAsyncEnumerable F() - { - Console.WriteLine(1); - await Task.Delay(1); - yield return 1; - } -} -"; - var src2 = @" -using System; -using System.Collections.Generic; -using System.Threading.Tasks; + using System; + using System.Collections.Generic; + using System.Threading.Tasks; -class C -{ - static async IAsyncEnumerable F() - { - Console.WriteLine(2); - await Task.Delay(2); - yield return 2; - } -} -"; + class C + { + static async IAsyncEnumerable F() + { + Console.WriteLine(1); + await Task.Delay(1); + yield return 1; + } + } + + """; + var src2 = """ + + using System; + using System.Collections.Generic; + using System.Threading.Tasks; + + class C + { + static async IAsyncEnumerable F() + { + Console.WriteLine(2); + await Task.Delay(2); + yield return 2; + } + } + + """; var edits = GetTopEdits(src1, src2); _ = GetActiveStatements(src1, src2); @@ -11807,22 +12995,26 @@ static async IAsyncEnumerable F() [Fact] public void AsyncMethodToMethod() { - var src1 = @" -class C -{ - static async void F() - { - } -} -"; - var src2 = @" -class C -{ - static void F() - { - } -} -"; + var src1 = """ + + class C + { + static async void F() + { + } + } + + """; + var src2 = """ + + class C + { + static void F() + { + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11837,24 +13029,28 @@ static void F() [Fact] public void MisplacedActiveStatement1() { - var src1 = @" -class C -{ - public static int F(int a) - { - return a; - return a; - } -}"; - var src2 = @" -class C -{ - public static int F(int a) - { - return a; - return a; - } -}"; + var src1 = """ + + class C + { + public static int F(int a) + { + return a; + return a; + } + } + """; + var src2 = """ + + class C + { + public static int F(int a) + { + return a; + return a; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11864,20 +13060,24 @@ public static int F(int a) [Fact] public void MisplacedActiveStatement2() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - } -}"; + var src1 = """ + + class C + { + static void Main(string[] args) + { + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11887,20 +13087,24 @@ static void Main(string[] args) [Fact] public void MisplacedTrackingSpan1() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - } -}"; - var src2 = @" -class C -{ - static void Main(string[] args) - { - } -}"; + var src1 = """ + + class C + { + static void Main(string[] args) + { + } + } + """; + var src2 = """ + + class C + { + static void Main(string[] args) + { + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11914,55 +13118,63 @@ class C [Fact] public void UpdateAroundActiveStatement_IsPattern() { - var src1 = @" -class C -{ - static void F(object x) - { - Console.WriteLine(1); - if (x is int i) { Console.WriteLine(""match""); } - } -} -"; - var src2 = @" -class C -{ - static void F(object x) - { - Console.WriteLine(1); - if (x is string s) { Console.WriteLine(""match""); } - } -} -"; + var src1 = """ + + class C + { + static void F(object x) + { + Console.WriteLine(1); + if (x is int i) { Console.WriteLine("match"); } + } + } + + """; + var src2 = """ + + class C + { + static void F(object x) + { + Console.WriteLine(1); + if (x is string s) { Console.WriteLine("match"); } + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active); } - [Fact] - public void UpdateAroundActiveStatement_DeconstructionDeclarationStatement() - { - var src1 = @" -class C -{ - static void F(object x) - { - Console.WriteLine(1); - var (x, y) = (1, 2); - } -} -"; - var src2 = @" -class C -{ - static void F(object x) - { - Console.WriteLine(1); - var (x, y) = x; - } -} -"; + [Fact] + public void UpdateAroundActiveStatement_DeconstructionDeclarationStatement() + { + var src1 = """ + + class C + { + static void F(object x) + { + Console.WriteLine(1); + var (x, y) = (1, 2); + } + } + + """; + var src2 = """ + + class C + { + static void F(object x) + { + Console.WriteLine(1); + var (x, y) = x; + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -11972,26 +13184,30 @@ static void F(object x) [Fact] public void UpdateAroundActiveStatement_DeconstructionForEach() { - var src1 = @" -class C -{ - static void F(object o) - { - Console.WriteLine(1); - foreach (var (x, y) in new[] { (1, 2) }) { Console.WriteLine(2); } - } -} -"; - var src2 = @" -class C -{ - static void F(object o) - { - Console.WriteLine(1); - foreach (var (x, y) in new[] { o }) { Console.WriteLine(2); } - } -} -"; + var src1 = """ + + class C + { + static void F(object o) + { + Console.WriteLine(1); + foreach (var (x, y) in new[] { (1, 2) }) { Console.WriteLine(2); } + } + } + + """; + var src2 = """ + + class C + { + static void F(object o) + { + Console.WriteLine(1); + foreach (var (x, y) in new[] { o }) { Console.WriteLine(2); } + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -12001,26 +13217,30 @@ static void F(object o) [Fact] public void UpdateAroundActiveStatement_VarDeconstruction() { - var src1 = @" -class C -{ - static void F(object o1, object o2) - { - Console.WriteLine(1); - for (var (x, y) = o1; ; ) { } - } -} -"; - var src2 = @" -class C -{ - static void F(object o1, object o2) - { - Console.WriteLine(1); - for (var (x, y) = o2; ; ) { } - } -} -"; + var src1 = """ + + class C + { + static void F(object o1, object o2) + { + Console.WriteLine(1); + for (var (x, y) = o1; ; ) { } + } + } + + """; + var src2 = """ + + class C + { + static void F(object o1, object o2) + { + Console.WriteLine(1); + for (var (x, y) = o2; ; ) { } + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -12030,26 +13250,30 @@ static void F(object o1, object o2) [Fact] public void UpdateAroundActiveStatement_TypedDeconstruction() { - var src1 = @" -class C -{ - static void F(object o1, object o2) - { - Console.WriteLine(1); - for ((int x, int y) = o1; ; ) { } - } -} -"; - var src2 = @" -class C -{ - static void F(object o1, object o2) - { - Console.WriteLine(1); - for ((int x, int y) = o2; ; ) { } - } -} -"; + var src1 = """ + + class C + { + static void F(object o1, object o2) + { + Console.WriteLine(1); + for ((int x, int y) = o1; ; ) { } + } + } + + """; + var src2 = """ + + class C + { + static void F(object o1, object o2) + { + Console.WriteLine(1); + for ((int x, int y) = o2; ; ) { } + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -12059,26 +13283,30 @@ static void F(object o1, object o2) [Fact] public void UpdateAroundActiveStatement_Tuple() { - var src1 = @" -class C -{ - static void F(object o) - { - Console.WriteLine(1); - (int, int) t; - } -} -"; - var src2 = @" -class C -{ - static void F(object o) - { - Console.WriteLine(1); - (int, int) t = (1, 2); - } -} -"; + var src1 = """ + + class C + { + static void F(object o) + { + Console.WriteLine(1); + (int, int) t; + } + } + + """; + var src2 = """ + + class C + { + static void F(object o) + { + Console.WriteLine(1); + (int, int) t = (1, 2); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -12088,26 +13316,30 @@ static void F(object o) [Fact] public void UpdateAroundActiveStatement_LocalFunction() { - var src1 = @" -class C -{ - static void F(object o) - { - Console.WriteLine(1); - void M() { Console.WriteLine(2); } - } -} -"; - var src2 = @" -class C -{ - static void F(object o) - { - Console.WriteLine(1); - void M() { Console.WriteLine(3); } - } -} -"; + var src1 = """ + + class C + { + static void F(object o) + { + Console.WriteLine(1); + void M() { Console.WriteLine(2); } + } + } + + """; + var src2 = """ + + class C + { + static void F(object o) + { + Console.WriteLine(1); + void M() { Console.WriteLine(3); } + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -12117,26 +13349,30 @@ static void F(object o) [Fact] public void UpdateAroundActiveStatement_OutVar() { - var src1 = @" -class C -{ - static void F() - { - Console.WriteLine(1); - M(); - } -} -"; - var src2 = @" -class C -{ - static void F() - { - Console.WriteLine(1); - M(out var x); - } -} -"; + var src1 = """ + + class C + { + static void F() + { + Console.WriteLine(1); + M(); + } + } + + """; + var src2 = """ + + class C + { + static void F() + { + Console.WriteLine(1); + M(out var x); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -12146,25 +13382,29 @@ static void F() [Fact] public void UpdateAroundActiveStatement_OutVarRemoved() { - var src1 = @" -class C -{ - static void F() - { - Console.WriteLine(1); - M(out var x); - } -} -"; - var src2 = @" -class C -{ - static void F() - { - Console.WriteLine(1); - } -} -"; + var src1 = """ + + class C + { + static void F() + { + Console.WriteLine(1); + M(out var x); + } + } + + """; + var src2 = """ + + class C + { + static void F() + { + Console.WriteLine(1); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -12174,26 +13414,30 @@ static void F() [Fact] public void UpdateAroundActiveStatement_Ref() { - var src1 = @" -class C -{ - static void F() - { - Console.WriteLine(1); - ref int i = ref 1; - } -} -"; - var src2 = @" -class C -{ - static void F() - { - Console.WriteLine(1); - ref int i = ref 2; - } -} -"; + var src1 = """ + + class C + { + static void F() + { + Console.WriteLine(1); + ref int i = ref 1; + } + } + + """; + var src2 = """ + + class C + { + static void F() + { + Console.WriteLine(1); + ref int i = ref 2; + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -12203,26 +13447,30 @@ static void F() [Fact] public void UpdateAroundActiveStatement_DeconstructionDeclaration() { - var src1 = @" -class C -{ - static void F(object o1, object o2) - { - Console.WriteLine(1); - var (x, y) = o1; - } -} -"; - var src2 = @" -class C -{ - static void F(object o1, object o2) - { - Console.WriteLine(1); - var (x, y) = o2; - } -} -"; + var src1 = """ + + class C + { + static void F(object o1, object o2) + { + Console.WriteLine(1); + var (x, y) = o1; + } + } + + """; + var src2 = """ + + class C + { + static void F(object o1, object o2) + { + Console.WriteLine(1); + var (x, y) = o2; + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -12232,28 +13480,32 @@ static void F(object o1, object o2) [Fact] public void UpdateAroundActiveStatement_DeconstructionAssignment() { - var src1 = @" -class C -{ - static void F(object o1, object o2) - { - Console.WriteLine(1); - int x, y; - (x, y) = o1; - } -} -"; - var src2 = @" -class C -{ - static void F(object o1, object o2) - { - Console.WriteLine(1); - int x, y; - (x, y) = o2; - } -} -"; + var src1 = """ + + class C + { + static void F(object o1, object o2) + { + Console.WriteLine(1); + int x, y; + (x, y) = o1; + } + } + + """; + var src2 = """ + + class C + { + static void F(object o1, object o2) + { + Console.WriteLine(1); + int x, y; + (x, y) = o2; + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -12263,34 +13515,38 @@ static void F(object o1, object o2) [Fact] public void UpdateAroundActiveStatement_SwitchWithPattern() { - var src1 = @" -class C -{ - static void F(object o1, object o2) - { - System.Console.WriteLine(1); - switch (o1) - { - case int i: - break; - } - } -} -"; - var src2 = @" -class C -{ - static void F(object o1, object o2) - { - System.Console.WriteLine(1); - switch (o2) - { - case int i: - break; - } - } -} -"; + var src1 = """ + + class C + { + static void F(object o1, object o2) + { + System.Console.WriteLine(1); + switch (o1) + { + case int i: + break; + } + } + } + + """; + var src2 = """ + + class C + { + static void F(object o1, object o2) + { + System.Console.WriteLine(1); + switch (o2) + { + case int i: + break; + } + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -12305,24 +13561,28 @@ static void F(object o1, object o2) [Fact] public void ChangeLocalNullableToNonNullable() { - var src1 = @" -class C -{ - static void F() - { - string? s = ""a""; - } -} -"; - var src2 = @" -class C -{ - static void F() - { - string s = ""a""; - } -} -"; + var src1 = """ + + class C + { + static void F() + { + string? s = "a"; + } + } + + """; + var src2 = """ + + class C + { + static void F() + { + string s = "a"; + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -12332,24 +13592,28 @@ static void F() [Fact] public void ChangeLocalNonNullableToNullable() { - var src1 = @" -class C -{ - static void F() - { - string s = ""a""; - } -} -"; - var src2 = @" -class C -{ - static void F() - { - string? s = ""a""; - } -} -"; + var src1 = """ + + class C + { + static void F() + { + string s = "a"; + } + } + + """; + var src2 = """ + + class C + { + static void F() + { + string? s = "a"; + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -12441,16 +13705,20 @@ public void InsertDeleteMethod_Active_EntirePartialTypeDeclaration() [Fact] public void Record() { - var src1 = @" -record C(int X) -{ - public int X { get; init; } = 1; -}"; - var src2 = @" -record C(int X) -{ - public int X { get; init; } = 2; -}"; + var src1 = """ + + record C(int X) + { + public int X { get; init; } = 1; + } + """; + var src2 = """ + + record C(int X) + { + public int X { get; init; } = 2; + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -12460,26 +13728,30 @@ record C(int X) [Fact] public void Record_Constructor() { - var src1 = @" -record C(int X) -{ - public int X { get; init; } = 1; + var src1 = """ - static void Main(string[] args) - { - var x = new C(1); - } -}"; - var src2 = @" -record C(int X) -{ - public int X { get; init; } = 2; + record C(int X) + { + public int X { get; init; } = 1; - static void Main(string[] args) - { - var x = new C(1); - } -}"; + static void Main(string[] args) + { + var x = new C(1); + } + } + """; + var src2 = """ + + record C(int X) + { + public int X { get; init; } = 2; + + static void Main(string[] args) + { + var x = new C(1); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -12489,26 +13761,30 @@ static void Main(string[] args) [Fact] public void Record_FieldInitializer_Lambda2() { - var src1 = @" -record C(int X) -{ - Func> a = z => () => z + 1; + var src1 = """ - static void Main(string[] args) - { - new C(1).a(1)(); - } -}"; - var src2 = @" -record C(int X) -{ - Func> a = z => () => z + 2; + record C(int X) + { + Func> a = z => () => z + 1; - static void Main(string[] args) - { - new C(1).a(1)(); - } -}"; + static void Main(string[] args) + { + new C(1).a(1)(); + } + } + """; + var src2 = """ + + record C(int X) + { + Func> a = z => () => z + 2; + + static void Main(string[] args) + { + new C(1).a(1)(); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -12525,44 +13801,48 @@ static void Main(string[] args) [Fact] public void LineMapping_ChangeLineNumber_WithinMethod() { - var src1 = @" -class C -{ -#line 1 ""a"" - static void F() - { - A(); -#line 5 ""b"" - B(1); - B(); -#line 2 ""c"" - C(); - C(); -#line hidden - D(); -#line default - E(); - } -}"; - var src2 = @" -class C -{ -#line 1 ""a"" - static void F() - { - A(); -#line 5 ""b"" - B(2); - B(); -#line 9 ""c"" - C(); - C(); -#line hidden - D(); -#line default - E(); - } -}"; + var src1 = """ + + class C + { + #line 1 "a" + static void F() + { + A(); + #line 5 "b" + B(1); + B(); + #line 2 "c" + C(); + C(); + #line hidden + D(); + #line default + E(); + } + } + """; + var src2 = """ + + class C + { + #line 1 "a" + static void F() + { + A(); + #line 5 "b" + B(2); + B(); + #line 9 "c" + C(); + C(); + #line hidden + D(); + #line default + E(); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -12572,26 +13852,30 @@ static void F() [Fact] public void LineMapping_ChangeFilePath() { - var src1 = @" -class C -{ - static void F() - { - A(); -#line 1 ""a"" - B(); - } -}"; - var src2 = @" -class C -{ - static void F() - { - A(); -#line 1 ""b"" - B(); - } -}"; + var src1 = """ + + class C + { + static void F() + { + A(); + #line 1 "a" + B(); + } + } + """; + var src2 = """ + + class C + { + static void F() + { + A(); + #line 1 "b" + B(); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -12602,46 +13886,50 @@ static void F() [Fact] public void LineMapping_ExceptionRegions_ChangeLineNumber() { - var src1 = @" -class C -{ - static void F() - { - try - { - try + var src1 = """ + + class C { - Goo(); + static void F() + { + try + { + try + { + Goo(); + } + #line 20 "a" + catch (E1 e) { } + #line default + } + #line 20 "b" + catch (E2 e) { } + #line default + } } -#line 20 ""a"" - catch (E1 e) { } -#line default - } -#line 20 ""b"" - catch (E2 e) { } -#line default - } -}"; - var src2 = @" -class C -{ - static void F() - { - try - { - try + """; + var src2 = """ + + class C { - Goo(); + static void F() + { + try + { + try + { + Goo(); + } + #line 20 "a" + catch (E1 e) { } + #line default + } + #line 30 "b" + catch (E2 e) { } + #line default + } } -#line 20 ""a"" - catch (E1 e) { } -#line default - } -#line 30 ""b"" - catch (E2 e) { } -#line default - } -}"; + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -12651,46 +13939,50 @@ static void F() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52971")] public void LineMapping_ExceptionRegions_ChangeFilePath() { - var src1 = @" -class C -{ - static void F() - { - try - { - try + var src1 = """ + + class C { - Goo(); + static void F() + { + try + { + try + { + Goo(); + } + #line 20 "a" + catch (E1 e) { } + #line default + } + #line 20 "b" + catch (E2 e) { } + #line default + } } -#line 20 ""a"" - catch (E1 e) { } -#line default - } -#line 20 ""b"" - catch (E2 e) { } -#line default - } -}"; - var src2 = @" -class C -{ - static void F() - { - try - { - try + """; + var src2 = """ + + class C { - Goo(); + static void F() + { + try + { + try + { + Goo(); + } + #line 20 "a" + catch (E1 e) { } + #line default + } + #line 20 "c" + catch (E2 e) { } + #line default + } } -#line 20 ""a"" - catch (E1 e) { } -#line default - } -#line 20 ""c"" - catch (E2 e) { } -#line default - } -}"; + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -12701,38 +13993,42 @@ static void F() [Fact(Skip = "https://github.com/dotnet/roslyn/issues/52971"), WorkItem("https://github.com/dotnet/roslyn/issues/52971")] public void LineMapping_ExceptionRegions_LineChange_MultipleMappedFiles() { - var src1 = @" -class C -{ - static void F() - { - try - { - Goo(); - } -#line 20 ""a"" - catch (E1 e) { } -#line 20 ""b"" - catch (E2 e) { } -#line default - } -}"; - var src2 = @" -class C -{ - static void F() - { - try - { - Goo(); - } -#line 20 ""a"" - catch (E1 e) { } -#line 30 ""b"" - catch (E2 e) { } -#line default - } -}"; + var src1 = """ + + class C + { + static void F() + { + try + { + Goo(); + } + #line 20 "a" + catch (E1 e) { } + #line 20 "b" + catch (E2 e) { } + #line default + } + } + """; + var src2 = """ + + class C + { + static void F() + { + try + { + Goo(); + } + #line 20 "a" + catch (E1 e) { } + #line 30 "b" + catch (E2 e) { } + #line default + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -12747,19 +14043,21 @@ static void F() [Fact] public void Delete_All_SourceText() { - var src1 = @" -class C -{ - static void Main(string[] args) - { - Goo(1); - } + var src1 = """ - static void Goo(int a) - { - Console.WriteLine(a); - } -}"; + class C + { + static void Main(string[] args) + { + Goo(1); + } + + static void Goo(int a) + { + Console.WriteLine(a); + } + } + """; var src2 = @""; var edits = GetTopEdits(src1, src2); @@ -12770,30 +14068,34 @@ static void Goo(int a) [Fact] public void PartiallyExecutedActiveStatement() { - var src1 = @" -class C -{ - public static void F() - { - Console.WriteLine(1); - Console.WriteLine(2); - Console.WriteLine(3); - Console.WriteLine(4); - Console.WriteLine(5); - } -}"; - var src2 = @" -class C -{ - public static void F() - { - Console.WriteLine(10); - Console.WriteLine(20); - Console.WriteLine(30); - Console.WriteLine(40); - Console.WriteLine(50); - } -}"; + var src1 = """ + + class C + { + public static void F() + { + Console.WriteLine(1); + Console.WriteLine(2); + Console.WriteLine(3); + Console.WriteLine(4); + Console.WriteLine(5); + } + } + """; + var src2 = """ + + class C + { + public static void F() + { + Console.WriteLine(10); + Console.WriteLine(20); + Console.WriteLine(30); + Console.WriteLine(40); + Console.WriteLine(50); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2, flags: [ @@ -12814,21 +14116,25 @@ public static void F() [Fact] public void PartiallyExecutedActiveStatement_Deleted1() { - var src1 = @" -class C -{ - public static void F() - { - Console.WriteLine(1); - } -}"; - var src2 = @" -class C -{ - public static void F() - { - } -}"; + var src1 = """ + + class C + { + public static void F() + { + Console.WriteLine(1); + } + } + """; + var src2 = """ + + class C + { + public static void F() + { + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2, flags: [ @@ -12842,21 +14148,25 @@ public static void F() [Fact] public void PartiallyExecutedActiveStatement_Deleted2() { - var src1 = @" -class C -{ - public static void F() - { - Console.WriteLine(1); - } -}"; - var src2 = @" -class C -{ - public static void F() - { - } -}"; + var src1 = """ + + class C + { + public static void F() + { + Console.WriteLine(1); + } + } + """; + var src2 = """ + + class C + { + public static void F() + { + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2, flags: [ @@ -12870,27 +14180,31 @@ public static void F() [Fact] public void Block_Delete() { - var src1 = @" -class C -{ - public static void F() - { - G(1); - { G(2); } - G(3); - } -} -"; - var src2 = @" -class C -{ - public static void F() - { - G(1); - G(3); - } -} -"; + var src1 = """ + + class C + { + public static void F() + { + G(1); + { G(2); } + G(3); + } + } + + """; + var src2 = """ + + class C + { + public static void F() + { + G(1); + G(3); + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -12901,42 +14215,46 @@ public static void F() [Theory, CombinatorialData] public void MemberBodyInternalError(bool outOfMemory) { - var src1 = @" -class C -{ - public static void F() - { - G(); - } + var src1 = """ - public static void G() - { - H(1); - } + class C + { + public static void F() + { + G(); + } - public static void H(int x) - { - } -} -"; - var src2 = @" -class C -{ - public static void F() - { - G(); - } + public static void G() + { + H(1); + } - public static void G() - { - H(2); - } + public static void H(int x) + { + } + } - public static void H(int x) - { - } -} -"; + """; + var src2 = """ + + class C + { + public static void F() + { + G(); + } + + public static void G() + { + H(2); + } + + public static void H(int x) + { + } + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -12979,18 +14297,22 @@ public override string ToString() [Fact] public void TopLevelStatements_UpdateAroundActiveStatement_LocalFunction() { - var src1 = @" -using System; + var src1 = """ -Console.WriteLine(1); -void M() { Console.WriteLine(2); } -"; - var src2 = @" -using System; + using System; + + Console.WriteLine(1); + void M() { Console.WriteLine(2); } + + """; + var src2 = """ + + using System; + + Console.WriteLine(1); + void M() { Console.WriteLine(3); } -Console.WriteLine(1); -void M() { Console.WriteLine(3); } -"; + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -13000,18 +14322,22 @@ public void TopLevelStatements_UpdateAroundActiveStatement_LocalFunction() [Fact] public void TopLevelStatements_UpdateAroundActiveStatement_OutVar() { - var src1 = @" -using System; + var src1 = """ -Console.WriteLine(1); -M(); -"; - var src2 = @" -using System; + using System; + + Console.WriteLine(1); + M(); + + """; + var src2 = """ + + using System; + + Console.WriteLine(1); + M(out var x); -Console.WriteLine(1); -M(out var x); -"; + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -13021,29 +14347,33 @@ public void TopLevelStatements_UpdateAroundActiveStatement_OutVar() [Fact] public void TopLevelStatements_Inner() { - var src1 = @" -using System; + var src1 = """ -Goo(1); + using System; -static void Goo(int a) -{ - Console.WriteLine(a); -} -"; - var src2 = @" -using System; + Goo(1); -while (true) -{ - Goo(2); -} + static void Goo(int a) + { + Console.WriteLine(a); + } -static void Goo(int a) -{ - Console.WriteLine(a); -} -"; + """; + var src2 = """ + + using System; + + while (true) + { + Goo(2); + } + + static void Goo(int a) + { + Console.WriteLine(a); + } + + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); diff --git a/src/Features/CSharpTest/EditAndContinue/BreakpointSpansTests.cs b/src/Features/CSharpTest/EditAndContinue/BreakpointSpansTests.cs index 6e26458284219..4d76254439d4c 100644 --- a/src/Features/CSharpTest/EditAndContinue/BreakpointSpansTests.cs +++ b/src/Features/CSharpTest/EditAndContinue/BreakpointSpansTests.cs @@ -108,172 +108,180 @@ public static IEnumerable GetBreakpointSequence(SyntaxNode root, int p [Fact] public void GetBreakpointSequence1() { - VerifyAllSpansInDeclaration(@" -class C -{ - $$void Goo() - [|{|] - [|int d = 5;|] - [|int a = 1|], [|b = 2|], [|c = 3|]; - for ([|int i = 0|], [|j = 1|], [|k = 2|]; [|i < 10|]; [|i++|], [|j++|], [|k--|]) - [|while (b > 0)|] - [|{|] - [|if (c < b)|] - try - [|{|] - [|System.Console.WriteLine(a);|] - [|}|] - [|catch (Exception e)|] - [|{|] - [|System.Console.WriteLine(e);|] - [|}|] - finally - [|{|] - [|}|] - else [|if (b < 10)|] - [|System.Console.WriteLine(b);|] - else - [|System.Console.WriteLine(c);|] - [|}|] - [|}|] -}"); + VerifyAllSpansInDeclaration(""" + class C + { + $$void Goo() + [|{|] + [|int d = 5;|] + [|int a = 1|], [|b = 2|], [|c = 3|]; + for ([|int i = 0|], [|j = 1|], [|k = 2|]; [|i < 10|]; [|i++|], [|j++|], [|k--|]) + [|while (b > 0)|] + [|{|] + [|if (c < b)|] + try + [|{|] + [|System.Console.WriteLine(a);|] + [|}|] + [|catch (Exception e)|] + [|{|] + [|System.Console.WriteLine(e);|] + [|}|] + finally + [|{|] + [|}|] + else [|if (b < 10)|] + [|System.Console.WriteLine(b);|] + else + [|System.Console.WriteLine(c);|] + [|}|] + [|}|] + } + """); } [Fact] public void GetBreakpointSequence2() { - VerifyAllSpansInDeclaration(@" -class C -{ - $$void Goo() - [|{|] - do - [|{|] - label: - [|i++;|] - [|var l = new List() - { - F(), - F(), - };|] - [|break;|] - [|continue;|] - [|}|] - [|while (a);|] - [|goto label;|] - [|}|] -}"); + VerifyAllSpansInDeclaration(""" + class C + { + $$void Goo() + [|{|] + do + [|{|] + label: + [|i++;|] + [|var l = new List() + { + F(), + F(), + };|] + [|break;|] + [|continue;|] + [|}|] + [|while (a);|] + [|goto label;|] + [|}|] + } + """); } [Fact] public void GetBreakpointSequence3() { - VerifyAllSpansInDeclaration(@" -class C -{ - $$int Goo() - [|{|] - [|switch(a)|] - { - case 1: - case 2: - [|break;|] - - case 3: - [|goto case 4;|] - - case 4: - [|throw new Exception();|] - [|goto default;|] - - default: - [|return 1;|] - } - [|return 2;|] - [|}|] -}"); + VerifyAllSpansInDeclaration(""" + class C + { + $$int Goo() + [|{|] + [|switch(a)|] + { + case 1: + case 2: + [|break;|] + + case 3: + [|goto case 4;|] + + case 4: + [|throw new Exception();|] + [|goto default;|] + + default: + [|return 1;|] + } + [|return 2;|] + [|}|] + } + """); } [Fact] public void GetBreakpointSequence4() { - VerifyAllSpansInDeclaration(@" -class C -{ - $$IEnumerable Goo() - [|{|] - [|yield return 1;|] - [|foreach|] ([|var f|] [|in|] [|Goo()|]) - [|{|] - [|using (z)|] - using ([|var q = null|]) - using ([|var u = null|], [|v = null|]) - [|{|] - [|while (a)|] [|yield return 2;|] - [|}|] - [|}|] - fixed([|int* a = new int[1]|], [|b = new int[1]|], [|c = new int[1]|]) [|{|][|}|] - [|yield break;|] - [|}|] -}"); + VerifyAllSpansInDeclaration(""" + class C + { + $$IEnumerable Goo() + [|{|] + [|yield return 1;|] + [|foreach|] ([|var f|] [|in|] [|Goo()|]) + [|{|] + [|using (z)|] + using ([|var q = null|]) + using ([|var u = null|], [|v = null|]) + [|{|] + [|while (a)|] [|yield return 2;|] + [|}|] + [|}|] + fixed([|int* a = new int[1]|], [|b = new int[1]|], [|c = new int[1]|]) [|{|][|}|] + [|yield break;|] + [|}|] + } + """); } [Fact] public void GetBreakpointSequence5() { - VerifyAllSpansInDeclaration(@" -class C -{ - $$IEnumerable Goo() - [|{|][|while(t)|][|{|][|}|][|}|] -}"); + VerifyAllSpansInDeclaration(""" + class C + { + $$IEnumerable Goo() + [|{|][|while(t)|][|{|][|}|][|}|] + } + """); } [Fact] public void GetBreakpointSequence6() { - VerifyAllSpansInDeclaration(@" -class C -{ - $$IEnumerable Goo() - [|{|] - checked - [|{|] - const int a = 1; - const int b = 2; - unchecked - [|{|] - unsafe + VerifyAllSpansInDeclaration(""" + class C + { + $$IEnumerable Goo() [|{|] - [|lock(l)|] + checked [|{|] - [|;|] - [|}|] - [|}|] - [|}|] - [|}|] - [|}|] -}"); + const int a = 1; + const int b = 2; + unchecked + [|{|] + unsafe + [|{|] + [|lock(l)|] + [|{|] + [|;|] + [|}|] + [|}|] + [|}|] + [|}|] + [|}|] + } + """); } [Fact] public void GetBreakpointSequence_StaticContructor_NoBody() { - VerifyAllSpansInDeclaration(@" -class Class -{ - static Clas$$s() -}"); + VerifyAllSpansInDeclaration(""" + class Class + { + static Clas$$s() + } + """); } [Fact] public void GetBreakpointSequence_Method_NoBody() { - VerifyAllSpansInDeclaration(@" -class Class -{ - int F$$unction() -}"); + VerifyAllSpansInDeclaration(""" + class Class + { + int F$$unction() + } + """); } #region Switch Expression @@ -281,240 +289,265 @@ class Class [Fact] public void SwitchExpression_All() { - VerifyAllSpansInDeclaration(@" -class C -{ - $$IEnumerable Goo() - [|{|] - [|_ = M2( - c - switch + VerifyAllSpansInDeclaration(""" + class C { - (1) _ [|when f|] => [|M(0)|], - (3) _ [|when f|] => [|M(1)|], - (1, 2) _ [|when f|] => [|M(0)|], - (3, 4) _ [|when f|] => [|M(2)|], - _ => [|M(4)|], - }, - M(5));|] - [|}|] -}"); + $$IEnumerable Goo() + [|{|] + [|_ = M2( + c + switch + { + (1) _ [|when f|] => [|M(0)|], + (3) _ [|when f|] => [|M(1)|], + (1, 2) _ [|when f|] => [|M(0)|], + (3, 4) _ [|when f|] => [|M(2)|], + _ => [|M(4)|], + }, + M(5));|] + [|}|] + } + """); } [Fact] public void SwitchExpression01() { TestSpan( -@"class C -{ - void Goo() - { -$$ [|_ = e switch - { - 1 when f => 2, - 3 when g => 4, - _ => 5, - };|] - } -}"); + """ + class C + { + void Goo() + { + $$ [|_ = e switch + { + 1 when f => 2, + 3 when g => 4, + _ => 5, + };|] + } + } + """); } [Fact] public void SwitchExpression02() { TestSpan( -@"class C -{ - void Goo() - { - [|_ = e switch - $${ - 1 when f => 2, - 3 when g => 4, - _ => 5, - };|] - } -}"); + """ + class C + { + void Goo() + { + [|_ = e switch + $${ + 1 when f => 2, + 3 when g => 4, + _ => 5, + };|] + } + } + """); } [Fact] public void SwitchExpression03() { TestSpan( -@"class C -{ - void Goo() - { - _ = e switch - {$$ - 1 [|when f|] => 2, - 3 when g => 4, - _ => 5, - }; - } -}"); + """ + class C + { + void Goo() + { + _ = e switch + {$$ + 1 [|when f|] => 2, + 3 when g => 4, + _ => 5, + }; + } + } + """); } [Fact] public void SwitchExpression04() { TestSpan( -@"class C -{ - void Goo() - { - _ = e switch - { - 1 [|when f|] $$=> 2, - 3 when g => 4, - _ => 5, - }; - } -}"); + """ + class C + { + void Goo() + { + _ = e switch + { + 1 [|when f|] $$=> 2, + 3 when g => 4, + _ => 5, + }; + } + } + """); } [Fact] public void SwitchExpression05() { TestSpan( -@"class C -{ - void Goo() - { - _ = e switch - { - 1 when f =$$> [|2|], - 3 when g => 4, - _ => 5, - }; - } -}"); + """ + class C + { + void Goo() + { + _ = e switch + { + 1 when f =$$> [|2|], + 3 when g => 4, + _ => 5, + }; + } + } + """); } [Fact] public void SwitchExpression06() { TestSpan( -@"class C -{ - void Goo() - { - _ = e switch - { - 1 when f => [|2|],$$ - 3 when g => 4, - _ => 5, - }; - } -}"); + """ + class C + { + void Goo() + { + _ = e switch + { + 1 when f => [|2|],$$ + 3 when g => 4, + _ => 5, + }; + } + } + """); } [Fact] public void SwitchExpression07() { TestSpan( -@"class C -{ - void Goo() - { - _ = e switch - { - 1 when f => 2, -$$ 3 [|when g|] => 4, - _ => 5, - }; - } -}"); + """ + class C + { + void Goo() + { + _ = e switch + { + 1 when f => 2, + $$ 3 [|when g|] => 4, + _ => 5, + }; + } + } + """); } [Fact] public void SwitchExpression08() { TestSpan( -@"class C -{ - void Goo() - { - _ = e switch - { - 1 when f => 2, - 3 when g => [|4|],$$ - _ => 5, - }; - } -}"); + """ + class C + { + void Goo() + { + _ = e switch + { + 1 when f => 2, + 3 when g => [|4|],$$ + _ => 5, + }; + } + } + """); } [Fact] public void SwitchExpression09() { TestSpan( -@"class C -{ - void Goo() - { - _ = e switch - { - 1 when f => 2, - 3 when g => 4, -$$ _ => [|5|], - }; - } -}"); + """ + class C + { + void Goo() + { + _ = e switch + { + 1 when f => 2, + 3 when g => 4, + $$ _ => [|5|], + }; + } + } + """); } [Fact] public void SwitchExpression10() { TestSpan( -@"class C -{ - void Goo() - { - _ = e switch - { - 1 when f => 2, - 3 when g => 4, - _ => [|5|],$$ - }; - } -}"); + """ + class C + { + void Goo() + { + _ = e switch + { + 1 when f => 2, + 3 when g => 4, + _ => [|5|],$$ + }; + } + } + """); } [Fact] public void SwitchExpression11() { TestSpan( -@"class C -{ - void Goo() - { - _ = e switch - { - 1 when f => 2, - 3 when g => 4, - _ => [|5|], - $$}; - } -}"); + """ + class C + { + void Goo() + { + _ = e switch + { + 1 when f => 2, + 3 when g => 4, + _ => [|5|], + $$}; + } + } + """); } [Fact] public void SwitchExpression12() { TestSpan( -@"class C -{ - void Goo() - { - [|_ = e switch - { - 1 when f => 2, - 3 when g => 4, - _ => 5, - }$$;|] - } -}"); + """ + class C + { + void Goo() + { + [|_ = e switch + { + 1 when f => 2, + 3 when g => 4, + _ => 5, + }$$;|] + } + } + """); } #endregion @@ -525,77 +558,87 @@ void Goo() public void ForStatementInitializer1a() { TestSpan( -@"class C -{ - void Goo() - { -$$ for ([|i = 0|], j = 0; i < 10 && j < 10; i++, j++) - { - } - } -}"); + """ + class C + { + void Goo() + { + $$ for ([|i = 0|], j = 0; i < 10 && j < 10; i++, j++) + { + } + } + } + """); } [Fact] public void ForStatementInitializer1b() { TestSpan( -@"class C -{ - void Goo() - { - f$$or ([|i = 0|], j = 0; i < 10 && j < 10; i++, j++) - { - } - } -}"); + """ + class C + { + void Goo() + { + f$$or ([|i = 0|], j = 0; i < 10 && j < 10; i++, j++) + { + } + } + } + """); } [Fact] public void ForStatementInitializer1c() { TestSpan( -@"class C -{ - void Goo() - { - for ([|i $$= 0|], j = 0; i < 10 && j < 10; i++, j++) - { - } - } -}"); + """ + class C + { + void Goo() + { + for ([|i $$= 0|], j = 0; i < 10 && j < 10; i++, j++) + { + } + } + } + """); } [Fact] public void ForStatementInitializer1d() { TestSpan( -@"class C -{ - void Goo() - { - for -$$ ( -[|i = 0|], j = 0; i < 10 && j < 10; i++, j++) - { - } - } -}"); + """ + class C + { + void Goo() + { + for + $$ ( + [|i = 0|], j = 0; i < 10 && j < 10; i++, j++) + { + } + } + } + """); } [Fact] public void ForStatementInitializer2() { TestSpan( -@"class C -{ - void Goo() - { - for (i = 0, [|$$j = 0|]; i < 10 && j < 10; i++, j++) - { - } - } -}"); + """ + class C + { + void Goo() + { + for (i = 0, [|$$j = 0|]; i < 10 && j < 10; i++, j++) + { + } + } + } + """); } [Fact] @@ -606,75 +649,85 @@ public void ForStatementInitializer3() public void ForStatementCondition() { TestSpan( -@"class C -{ - void Goo() - { - for (i = 0, j = 0; [|i < 10 && j < $$10|]; i++, j++) - { - } - } -}"); + """ + class C + { + void Goo() + { + for (i = 0, j = 0; [|i < 10 && j < $$10|]; i++, j++) + { + } + } + } + """); } [Fact] public void ForStatementIncrementor1() { TestSpan( -@"class C -{ - void Goo() - { - for (i = 0, j = 0; i < 10 && j < 10; [|i+$$+|], j++) - { - } - } -}"); + """ + class C + { + void Goo() + { + for (i = 0, j = 0; i < 10 && j < 10; [|i+$$+|], j++) + { + } + } + } + """); } [Fact] public void ForStatementIncrementor2() { TestSpan( -@"class C -{ - void Goo() - { - for (i = 0, j = 0; i < 10 && j < 10; i++, [|$$j++|]) - { - } - } -}"); + """ + class C + { + void Goo() + { + for (i = 0, j = 0; i < 10 && j < 10; i++, [|$$j++|]) + { + } + } + } + """); } [Fact] public void ForEachStatementExpression() { TestSpan( -@"class C -{ - void Goo() - { - foreach (var v in [|Goo().B$$ar()|]) - { - } - } -}"); + """ + class C + { + void Goo() + { + foreach (var v in [|Goo().B$$ar()|]) + { + } + } + } + """); } [Fact] public void ForEachDeconstructionStatementExpression() { TestSpan( -@"class C -{ - void Goo() - { - foreach (var (x, y) in [|Goo().B$$ar()|]) - { - } - } -}"); + """ + class C + { + void Goo() + { + foreach (var (x, y) in [|Goo().B$$ar()|]) + { + } + } + } + """); } #endregion @@ -685,52 +738,60 @@ void Goo() public void SimpleLambdaBody() { TestSpan( -@"class C -{ - void Goo() - { - Func f = s => [|G$$oo()|]; - } -}"); + """ + class C + { + void Goo() + { + Func f = s => [|G$$oo()|]; + } + } + """); } [Fact] public void ParenthesizedLambdaBody() { TestSpan( -@"class C -{ - void Goo() - { - Func f = (s, i) => [|G$$oo()|]; - } -}"); + """ + class C + { + void Goo() + { + Func f = (s, i) => [|G$$oo()|]; + } + } + """); } [Fact] public void AnonymousMethod1() { TestSpan( -@"class C -{ - void Goo() - { - Func f = delegate [|$${|] return 1; }; - } -}"); + """ + class C + { + void Goo() + { + Func f = delegate [|$${|] return 1; }; + } + } + """); } [Fact] public void AnonymousMethod2() { TestSpan( -@"class C -{ - void Goo() - { - Func f = delegate { [|$$return 1;|] }; - } -}"); + """ + class C + { + void Goo() + { + Func f = delegate { [|$$return 1;|] }; + } + } + """); } #endregion @@ -741,237 +802,267 @@ void Goo() public void FirstFromClauseExpression() { TestSpan( -@"class C -{ - void Goo() - { - [|var q = from x in bl$$ah() - from y in quux().z() - select y;|] - } -}"); + """ + class C + { + void Goo() + { + [|var q = from x in bl$$ah() + from y in quux().z() + select y;|] + } + } + """); } [Fact] public void SecondFromClauseExpression() { TestSpan( -@"class C -{ - void Goo() - { - var q = from x in blah() - from y in [|quux().z$$()|] - select y; - } -}"); + """ + class C + { + void Goo() + { + var q = from x in blah() + from y in [|quux().z$$()|] + select y; + } + } + """); } [Fact] public void FromInQueryContinuation1() { TestSpan( -@"class C -{ - void Goo() - { - var q = from x in blah() - from y in quux().z() - group x by y into g - from m in [|g.C$$ount()|] - select m.Blah(); - } -}"); + """ + class C + { + void Goo() + { + var q = from x in blah() + from y in quux().z() + group x by y into g + from m in [|g.C$$ount()|] + select m.Blah(); + } + } + """); } [Fact] public void FromInQueryContinuation2() { TestSpan( -@"class C -{ - void Goo() - { - var q = from x in blah() - from y in quux().z() - group x by y into g - $$ from m in [|g.Count()|] - select m.Blah(); - } -}"); + """ + class C + { + void Goo() + { + var q = from x in blah() + from y in quux().z() + group x by y into g + $$ from m in [|g.Count()|] + select m.Blah(); + } + } + """); } [Fact] public void JoinClauseLeftExpression() { TestSpan( -@"class C -{ - void Goo() - { - var q = from x in blah() - join a in alpha on [|left().exp$$r()|] equals right().expr() - select y; - } -}"); + """ + class C + { + void Goo() + { + var q = from x in blah() + join a in alpha on [|left().exp$$r()|] equals right().expr() + select y; + } + } + """); } [Fact] public void JoinClauseRightExpression() { TestSpan( -@"class C -{ - void Goo() - { - var q = from x in blah() - join a in alpha on left().expr() equals [|righ$$t().expr()|] - select y; - } -}"); + """ + class C + { + void Goo() + { + var q = from x in blah() + join a in alpha on left().expr() equals [|righ$$t().expr()|] + select y; + } + } + """); } [Fact] public void LetClauseExpression() { TestSpan( -@"class C -{ - void Goo() - { - var q = from x in blah() - join a in alpha on left().expr() equals right.expr() - let a = [|expr().$$expr()|] - select y; - } -}"); + """ + class C + { + void Goo() + { + var q = from x in blah() + join a in alpha on left().expr() equals right.expr() + let a = [|expr().$$expr()|] + select y; + } + } + """); } [Fact] public void WhereClauseExpression() { TestSpan( -@"class C -{ - void Goo() - { - var q = from x in blah() - join a in alpha on left().expr() equals right.expr() - where [|expr().$$expr()|] - select y; - } -}"); + """ + class C + { + void Goo() + { + var q = from x in blah() + join a in alpha on left().expr() equals right.expr() + where [|expr().$$expr()|] + select y; + } + } + """); } [Fact] public void WhereClauseKeyword() { TestSpan( -@"class C -{ - void Goo() - { - var q = from x in blah() - whe$$re [|expr().expr()|] - select y; - } -}"); + """ + class C + { + void Goo() + { + var q = from x in blah() + whe$$re [|expr().expr()|] + select y; + } + } + """); } [Fact] public void SimpleOrdering1() { TestSpan( -@"class C -{ - void Goo() - { - var q = from x in blah() - join a in alpha on left().expr() equals right.expr() - orderby [|expr().$$expr()|] - select y; - } -}"); + """ + class C + { + void Goo() + { + var q = from x in blah() + join a in alpha on left().expr() equals right.expr() + orderby [|expr().$$expr()|] + select y; + } + } + """); } [Fact] public void SimpleOrdering2() { TestSpan( -@"class C -{ - void Goo() - { - var q = from x in blah() - join a in alpha on left().expr() equals right.expr() - orderby goo, [|expr().$$expr()|] - select y; - } -}"); + """ + class C + { + void Goo() + { + var q = from x in blah() + join a in alpha on left().expr() equals right.expr() + orderby goo, [|expr().$$expr()|] + select y; + } + } + """); } [Fact] public void AscendingOrdering1() { TestSpan( -@"class C -{ - void Goo() - { - var q = from x in blah() - join a in alpha on left().expr() equals right.expr() - orderby [|expr().$$expr()|] ascending - select y; - } -}"); + """ + class C + { + void Goo() + { + var q = from x in blah() + join a in alpha on left().expr() equals right.expr() + orderby [|expr().$$expr()|] ascending + select y; + } + } + """); } [Fact] public void AscendingOrdering2() { TestSpan( -@"class C -{ - void Goo() - { - var q = from x in blah() - join a in alpha on left().expr() equals right.expr() - orderby goo, [|expr().$$expr()|] ascending - select y; - } -}"); + """ + class C + { + void Goo() + { + var q = from x in blah() + join a in alpha on left().expr() equals right.expr() + orderby goo, [|expr().$$expr()|] ascending + select y; + } + } + """); } [Fact] public void DescendingOrdering1() { TestSpan( -@"class C -{ - void Goo() - { - var q = from x in blah() - join a in alpha on left().expr() equals right.expr() - orderby [|expr().$$expr()|] descending - select y; - } -}"); + """ + class C + { + void Goo() + { + var q = from x in blah() + join a in alpha on left().expr() equals right.expr() + orderby [|expr().$$expr()|] descending + select y; + } + } + """); } [Fact] public void DescendingOrdering2() { TestSpan( -@"class C -{ - void Goo() - { - var q = from x in blah() - join a in alpha on left().expr() equals right.expr() - orderby goo, [|expr().$$expr()|] descending - select y; - } -}"); + """ + class C + { + void Goo() + { + var q = from x in blah() + join a in alpha on left().expr() equals right.expr() + orderby goo, [|expr().$$expr()|] descending + select y; + } + } + """); } [Fact] @@ -986,298 +1077,329 @@ public void AscendingKeyword() public void SelectExpression() { TestSpan( -@"class C -{ - void Goo() - { - var q = from x in blah() - join a in alpha on left().expr() equals right.expr() - orderby goo, expr().expr() descending - select [|y.$$blah()|]; - } -}"); + """ + class C + { + void Goo() + { + var q = from x in blah() + join a in alpha on left().expr() equals right.expr() + orderby goo, expr().expr() descending + select [|y.$$blah()|]; + } + } + """); } [Fact] public void AnonymousTypeAfterSelect() { TestSpan( -@"class C -{ - public void () - { - var q = - from c in categories - join p in products on c equals p.Category into ps - select [|new { Category = c, $$Products = ps }|]; - } -}"); + """ + class C + { + public void () + { + var q = + from c in categories + join p in products on c equals p.Category into ps + select [|new { Category = c, $$Products = ps }|]; + } + } + """); } [Fact] public void GroupExpression() { TestSpan( -@"class C -{ - void Goo() - { - var q = from x in blah() - join a in alpha on left().expr() equals right.expr() - orderby goo, expr().expr() descending - group [|bar()$$.goo()|] by blah().zap() - select y.blah(); - } -}"); + """ + class C + { + void Goo() + { + var q = from x in blah() + join a in alpha on left().expr() equals right.expr() + orderby goo, expr().expr() descending + group [|bar()$$.goo()|] by blah().zap() + select y.blah(); + } + } + """); } [Fact] public void GroupByKeyword() { TestSpan( -@"class C -{ - void Goo() - { - var q = from x in blah() - join a in alpha on left().expr() equals right.expr() - orderby goo, expr().expr() descending - group [|bar().goo()|] b$$y blah().zap() - select y.blah(); - } -}"); + """ + class C + { + void Goo() + { + var q = from x in blah() + join a in alpha on left().expr() equals right.expr() + orderby goo, expr().expr() descending + group [|bar().goo()|] b$$y blah().zap() + select y.blah(); + } + } + """); } [Fact] public void GroupByExpression() { TestSpan( -@"class C -{ - void Goo() - { - var q = from x in blah() - join a in alpha on left().expr() equals right.expr() - orderby goo, expr().expr() descending - group bar().goo() by [|blah()$$.zap()|] - select y.blah(); - } -}"); + """ + class C + { + void Goo() + { + var q = from x in blah() + join a in alpha on left().expr() equals right.expr() + orderby goo, expr().expr() descending + group bar().goo() by [|blah()$$.zap()|] + select y.blah(); + } + } + """); } [Fact] public void InFrontOfFirstFromClause() { TestSpan( -@"class C -{ - void Goo() - { - [|var q = - $$ from x in blah() - from y in zap() - let m = quux() - join a in alpha on left().expr() equals right.expr() - orderby goo, expr().expr() descending - group bar().goo() by blah().zap() into g - select y.blah();|] - } -}"); + """ + class C + { + void Goo() + { + [|var q = + $$ from x in blah() + from y in zap() + let m = quux() + join a in alpha on left().expr() equals right.expr() + orderby goo, expr().expr() descending + group bar().goo() by blah().zap() into g + select y.blah();|] + } + } + """); } [Fact] public void InFrontOfSecondFromClause() { TestSpan( -@"class C -{ - void Goo() - { - var q = - from x in blah() - $$ from y in [|zap()|] - let m = quux() - join a in alpha on left().expr() equals right.expr() - orderby goo, expr().expr() descending - group bar().goo() by blah().zap() into g - select y.blah(); - } -}"); + """ + class C + { + void Goo() + { + var q = + from x in blah() + $$ from y in [|zap()|] + let m = quux() + join a in alpha on left().expr() equals right.expr() + orderby goo, expr().expr() descending + group bar().goo() by blah().zap() into g + select y.blah(); + } + } + """); } [Fact] public void InFrontOfLetClause() { TestSpan( -@"class C -{ - void Goo() - { - var q = - from x in blah() - from y in zap() - $$ let m = [|quux()|] - join a in alpha on left().expr() equals right.expr() - orderby goo, expr().expr() descending - group bar().goo() by blah().zap() into g - select y.blah(); - } -}"); + """ + class C + { + void Goo() + { + var q = + from x in blah() + from y in zap() + $$ let m = [|quux()|] + join a in alpha on left().expr() equals right.expr() + orderby goo, expr().expr() descending + group bar().goo() by blah().zap() into g + select y.blah(); + } + } + """); } [Fact] public void InFrontOfJoinClause() { TestSpan( -@"class C -{ - void Goo() - { - var q = - from x in blah() - from y in zap() - let m = quux() - $$ join a in alpha on [|left().expr()|] equals right.expr() - orderby goo, expr().expr() descending - group bar().goo() by blah().zap() into g - select y.blah(); - } -}"); + """ + class C + { + void Goo() + { + var q = + from x in blah() + from y in zap() + let m = quux() + $$ join a in alpha on [|left().expr()|] equals right.expr() + orderby goo, expr().expr() descending + group bar().goo() by blah().zap() into g + select y.blah(); + } + } + """); } [Fact] public void InFrontOfOrderByClause() { TestSpan( -@"class C -{ - void Goo() - { - var q = - from x in blah() - from y in zap() - let m = quux() - join a in alpha on left().expr() equals right.expr() - $$ orderby [|goo|], expr().expr() descending - group bar().goo() by blah().zap() into g - select y.blah(); - } -}"); + """ + class C + { + void Goo() + { + var q = + from x in blah() + from y in zap() + let m = quux() + join a in alpha on left().expr() equals right.expr() + $$ orderby [|goo|], expr().expr() descending + group bar().goo() by blah().zap() into g + select y.blah(); + } + } + """); } [Fact] public void InFrontOfGroupByClause() { TestSpan( -@"class C -{ - void Goo() - { - var q = - from x in blah() - from y in zap() - let m = quux() - join a in alpha on left().expr() equals right.expr() - orderby goo, expr().expr() descending - $$ group [|bar().goo()|] by blah().zap() into g - select y.blah(); - }"); + """ + class C + { + void Goo() + { + var q = + from x in blah() + from y in zap() + let m = quux() + join a in alpha on left().expr() equals right.expr() + orderby goo, expr().expr() descending + $$ group [|bar().goo()|] by blah().zap() into g + select y.blah(); + } + """); } [Fact] public void InFrontOfSelectClause() { TestSpan( -@"class C -{ - void Goo() - { - var q = - from x in blah() - from y in zap() - let m = quux() - join a in alpha on left().expr() equals right.expr() - orderby goo, expr().expr() descending - group bar().goo() by blah().zap() into g - $$ select [|y.blah()|]; - }"); + """ + class C + { + void Goo() + { + var q = + from x in blah() + from y in zap() + let m = quux() + join a in alpha on left().expr() equals right.expr() + orderby goo, expr().expr() descending + group bar().goo() by blah().zap() into g + $$ select [|y.blah()|]; + } + """); } [Fact] public void Select1() { TestSpan( -@"class C -{ - IEnumerable Goo() => from x in new[] { 1 } select [|$$x|]; -} -"); + """ + class C + { + IEnumerable Goo() => from x in new[] { 1 } select [|$$x|]; + } + """); } [Fact] public void Select_NoLambda1() { TestSpan( -@"class C -{ - IEnumerable Goo() => [|from x in new[] { 1 } where x > 0 select $$x|]; -} -"); + """ + class C + { + IEnumerable Goo() => [|from x in new[] { 1 } where x > 0 select $$x|]; + } + """); } [Fact] public void Select_NoLambda2() { TestSpan( -@"class C -{ - IEnumerable Goo() => [|from x in new[] { 1 } select x into y orderby y select $$y|]; -} -"); + """ + class C + { + IEnumerable Goo() => [|from x in new[] { 1 } select x into y orderby y select $$y|]; + } + """); } [Fact] public void GroupBy1() { TestSpan( -@"class C -{ - IEnumerable Goo() => from x in new[] { 1 } group x by [|$$x|]; -} -"); + """ + class C + { + IEnumerable Goo() => from x in new[] { 1 } group x by [|$$x|]; + } + """); } [Fact] public void GroupBy_NoLambda1() { TestSpan( -@"class C -{ - IEnumerable Goo() => [|from x in new[] { 1 } group $$x by x|]; -} -"); + """ + class C + { + IEnumerable Goo() => [|from x in new[] { 1 } group $$x by x|]; + } + """); } [Fact] public void GroupBy_NoLambda2() { TestSpan( -@"class C -{ - IEnumerable Goo() => [|from x in new[] { 1 } group $$x by x + 1 into y group y by y.Key + 2|]; -} -"); + """ + class C + { + IEnumerable Goo() => [|from x in new[] { 1 } group $$x by x + 1 into y group y by y.Key + 2|]; + } + """); } [Fact] public void GroupBy_NoLambda3() { TestSpan( -@"class C -{ - IEnumerable Goo() => [|from x in new[] { 1 } group x by x + 1 into y group $$y by y.Key + 2|]; -} -"); + """ + class C + { + IEnumerable Goo() => [|from x in new[] { 1 } group x by x + 1 into y group $$y by y.Key + 2|]; + } + """); } #endregion @@ -1288,146 +1410,174 @@ public void GroupBy_NoLambda3() public void FieldDeclarator_WithoutInitializer_All() { VerifyAllSpansInDeclaration( -@"class C -{ - int $$i, j; -}"); + """ + class C + { + int $$i, j; + } + """); } [Fact] public void FieldDeclarator_WithoutInitializer1() { TestMissing( -@"class C -{ - int $$i; -}"); + """ + class C + { + int $$i; + } + """); } [Fact] public void FieldDeclarator_WithoutInitializer2() { TestMissing( -@"class C -{ - pri$$vate int i; -}"); + """ + class C + { + pri$$vate int i; + } + """); } [Fact] public void FieldDeclarator_SingleVariable_Initializer_All1() { VerifyAllSpansInDeclaration( -@"class C -{ - [Goo] - private int $$i; -}"); + """ + class C + { + [Goo] + private int $$i; + } + """); } [Fact] public void FieldDeclarator_SingleVariable_Initializer_All2() { VerifyAllSpansInDeclaration( -@"class C -{ - [Goo] - [|int $$i = 0;|] -}"); + """ + class C + { + [Goo] + [|int $$i = 0;|] + } + """); } [Fact] public void FieldDeclarator_SingleVariable_Initializer_All3() { VerifyAllSpansInDeclaration( -@"class C -{ - [Goo] - [|private int $$i = 0;|] -}"); + """ + class C + { + [Goo] + [|private int $$i = 0;|] + } + """); } [Fact] public void FieldDeclarator_MultiVariable_Initializer_All1() { VerifyAllSpansInDeclaration( -@"class C -{ - [Goo] - [|private int $$i = 0|], j = 2; -}"); + """ + class C + { + [Goo] + [|private int $$i = 0|], j = 2; + } + """); } [Fact] public void FieldDeclarator_MultiVariable_Initializer_All2() { VerifyAllSpansInDeclaration( -@"class C -{ - [Goo] - [|int $$i = 0|], j = 2; -}"); + """ + class C + { + [Goo] + [|int $$i = 0|], j = 2; + } + """); } [Fact] public void FieldDeclarator_MultiVariable_Initializer_All3() { VerifyAllSpansInDeclaration( -@"class C -{ - [Goo] - private int i = 0, [|$$j = 0|]; -}"); + """ + class C + { + [Goo] + private int i = 0, [|$$j = 0|]; + } + """); } [Fact] public void FieldDeclarator_Initializer1() { TestSpan( -@"class C -{ - [|int $$i = 1;|] -}"); + """ + class C + { + [|int $$i = 1;|] + } + """); } [Fact] public void FieldDeclarator_Initializer2() { TestSpan( -@"class C -{ - [|private int $$i = 1;|] -}"); + """ + class C + { + [|private int $$i = 1;|] + } + """); } [Fact] public void FieldDeclarator_Initializer3() { TestSpan( -@"class C -{ - [Goo] - [|private int $$i = 0;|] -}"); + """ + class C + { + [Goo] + [|private int $$i = 0;|] + } + """); } [Fact] public void FieldDeclarator_Initializer4() { TestSpan( -@"class C -{ - [|pri$$vate int i = 1;|] -}"); + """ + class C + { + [|pri$$vate int i = 1;|] + } + """); } [Fact] public void FieldDeclarator_Initializer5() { TestSpan( -@"class C -{ -$$ [|private int i = 3;|] -}"); + """ + class C + { + $$ [|private int i = 3;|] + } + """); } [Fact] @@ -1446,11 +1596,13 @@ public void ConstVariableDeclarator2() public void ConstFieldVariableDeclarator_All() { VerifyAllSpansInDeclaration( -@"class C -{ - [Goo] - private const int i = 0, j, $$k = 0; -}"); + """ + class C + { + [Goo] + private const int i = 0, j, $$k = 0; + } + """); } [Fact] @@ -1473,154 +1625,180 @@ public void VariableDeclarator0() public void VariableDeclarator1() { TestMissing( -@"class C -{ - void Goo() - { - int $$i; - } -}"); + """ + class C + { + void Goo() + { + int $$i; + } + } + """); } [Fact] public void VariableDeclarator2a() { TestSpan( -@"class C -{ - void Goo() - { - [|int $$i = 0;|] - } -}"); + """ + class C + { + void Goo() + { + [|int $$i = 0;|] + } + } + """); } [Fact] public void VariableDeclarator2b() { TestSpan( -@"class C -{ - void Goo() - { - $$ [|int i = 0;|] - } -}"); + """ + class C + { + void Goo() + { + $$ [|int i = 0;|] + } + } + """); } [Fact] public void VariableDeclarator2c() { TestSpan( -@"class C -{ - void Goo() - { - [|$$int i = 0;|] - } -}"); + """ + class C + { + void Goo() + { + [|$$int i = 0;|] + } + } + """); } [Fact] public void VariableDeclarator3a() { TestSpan( -@"class C -{ - void Goo() - { - int i = 0, [|$$j = 3|]; - } -}"); + """ + class C + { + void Goo() + { + int i = 0, [|$$j = 3|]; + } + } + """); } [Fact] public void VariableDeclarator3b() { TestSpan( -@"class C -{ - void Goo() - { - [|int i = 0|], $$j; - } -}"); + """ + class C + { + void Goo() + { + [|int i = 0|], $$j; + } + } + """); } [Fact] public void VariableDeclarator3c() { TestSpan( -@"class C -{ - void Goo() - { - int $$i, [|j = 0|]; - } -}"); + """ + class C + { + void Goo() + { + int $$i, [|j = 0|]; + } + } + """); } [Fact] public void VariableDeclarator4() { TestSpan( -@"class C -{ - void Goo() - { - int i = 0, [|j = $$1|]; - } -}"); + """ + class C + { + void Goo() + { + int i = 0, [|j = $$1|]; + } + } + """); } [Fact] public void VariableDeclarator5() { TestSpan( -@"class C -{ - [|int $$i = 0;|] -}"); + """ + class C + { + [|int $$i = 0;|] + } + """); } [Fact] public void VariableDeclarator6() { TestSpan( -@"class C -{ - [|int i = 0|], $$j; -}"); + """ + class C + { + [|int i = 0|], $$j; + } + """); } [Fact] public void VariableDeclarator7() { TestSpan( -@"class C -{ - private int i = 0, [|j = $$1|]; -}"); + """ + class C + { + private int i = 0, [|j = $$1|]; + } + """); } [Fact] public void VariableDeclarator8() { TestSpan( -@"class C -{ - [|priv$$ate int i = 0|], j = 1; -}"); + """ + class C + { + [|priv$$ate int i = 0|], j = 1; + } + """); } [Fact] public void VariableDeclarator9() { TestSpan( -@"class C -{ -$$ [|private int i = 0|], j = 1; -}"); + """ + class C + { + $$ [|private int i = 0|], j = 1; + } + """); } [Fact] @@ -1631,210 +1809,246 @@ public void VariableDeclarator10() public void VariableDeclarator_Separators0() { TestSpan( -@"class C -{ - void Goo() - { -$$ [|int i = 0|], j = 1, k = 2; - } -}"); + """ + class C + { + void Goo() + { + $$ [|int i = 0|], j = 1, k = 2; + } + } + """); } [Fact] public void VariableDeclarator_Separators1() { TestSpan( -@"class C -{ - void Goo() - { - [|int i = 0|]$$, j = 1, k = 2; - } -}"); + """ + class C + { + void Goo() + { + [|int i = 0|]$$, j = 1, k = 2; + } + } + """); } [Fact] public void VariableDeclarator_Separators2() { TestSpan( -@"class C -{ - void Goo() - { - int i = 0, [|j = 1|]$$, k = 2; - } -}"); + """ + class C + { + void Goo() + { + int i = 0, [|j = 1|]$$, k = 2; + } + } + """); } [Fact] public void VariableDeclarator_Separators3() { TestSpan( -@"class C -{ - void Goo() - { - int i = 0, j = 1,$$ [|k = 2|]; - } -}"); + """ + class C + { + void Goo() + { + int i = 0, j = 1,$$ [|k = 2|]; + } + } + """); } [Fact] public void VariableDeclarator_Separators4() { TestSpan( -@"class C -{ - void Goo() - { - int i = 0, j = 1, [|k = 2|]$$; - } -}"); + """ + class C + { + void Goo() + { + int i = 0, j = 1, [|k = 2|]$$; + } + } + """); } [Fact] public void VariableDeclarator_Separators5() { TestSpan( -@"class C -{ - void Goo() - { - [|int i = 0|], j = 1, k = 2;$$ - } -}"); + """ + class C + { + void Goo() + { + [|int i = 0|], j = 1, k = 2;$$ + } + } + """); } [Fact] public void VariableDeclarator_Separators6() { TestSpan( -@"class C -{ - void Goo() - { - int i = 1, j, $$k, [|l = 2|]; - } -}"); + """ + class C + { + void Goo() + { + int i = 1, j, $$k, [|l = 2|]; + } + } + """); } [Fact] public void VariableDeclarator_Separators7() { TestSpan( -@"class C -{ - void Goo() - { - int i$$, j, k, [|l = 2|]; - } -}"); + """ + class C + { + void Goo() + { + int i$$, j, k, [|l = 2|]; + } + } + """); } [Fact] public void VariableDeclarator_Separators8() { TestSpan( -@"class C -{ - void Goo() - { - [|int i = 2|], j, k, l$$; - } -}"); + """ + class C + { + void Goo() + { + [|int i = 2|], j, k, l$$; + } + } + """); } [Fact] public void VariableDeclarator_Separators9() { TestSpan( -@"class C -{ - void Goo() - { - int i, j, [|k = 1|], m, l = 2;$$ - } -}"); + """ + class C + { + void Goo() + { + int i, j, [|k = 1|], m, l = 2;$$ + } + } + """); } [Fact] public void EventFieldDeclarator1() { TestSpan( -@"class C -{ -$$ [|public event EventHandler MyEvent = delegate { };|] -}"); + """ + class C + { + $$ [|public event EventHandler MyEvent = delegate { };|] + } + """); } [Fact] public void EventFieldDeclarator2() { TestSpan( -@"class C -{ - [|pub$$lic event EventHandler MyEvent = delegate { };|] -}"); + """ + class C + { + [|pub$$lic event EventHandler MyEvent = delegate { };|] + } + """); } [Fact] public void EventFieldDeclarator3() { TestSpan( -@"class C -{ - [|public ev$$ent EventHandler MyEvent = delegate { };|] -}"); + """ + class C + { + [|public ev$$ent EventHandler MyEvent = delegate { };|] + } + """); } [Fact] public void EventFieldDeclarator4() { TestSpan( -@"class C -{ - [|public event EventHan$$dler MyEvent = delegate { };|] -}"); + """ + class C + { + [|public event EventHan$$dler MyEvent = delegate { };|] + } + """); } [Fact] public void EventFieldDeclarator5() { TestSpan( -@"class C -{ - [|public event EventHandler MyE$$vent = delegate { };|] -}"); + """ + class C + { + [|public event EventHandler MyE$$vent = delegate { };|] + } + """); } [Fact] public void EventFieldDeclarator6() { TestSpan( -@"class C -{ - [|public event EventHandler MyEvent $$= delegate { };|] -}"); + """ + class C + { + [|public event EventHandler MyEvent $$= delegate { };|] + } + """); } [Fact] public void EventFieldDeclarator7() { TestSpan( -@"class C -{ - [|public event EventHandler MyEvent = del$$egate { };|] -}"); + """ + class C + { + [|public event EventHandler MyEvent = del$$egate { };|] + } + """); } [Fact] public void EventFieldDeclarator8() { TestSpan( -@"class C -{ - public event EventHandler MyEvent = delegate [|{|] $$ }; -}"); + """ + class C + { + public event EventHandler MyEvent = delegate [|{|] $$ }; + } + """); } #endregion @@ -1855,306 +2069,340 @@ public void EventAccessorRemove() public void ElseClauseWithBlock() { TestSpan( -@"class C -{ - void Goo() - { - if (bar) - { - } - el$$se - [|{|] - } - } -}"); + """ + class C + { + void Goo() + { + if (bar) + { + } + el$$se + [|{|] + } + } + } + """); } [Fact] public void ElseClauseWithStatement() { TestSpan( -@"class C -{ - void Goo() - { - if (bar) - { - } - el$$se - [|Goo();|] - } -}"); + """ + class C + { + void Goo() + { + if (bar) + { + } + el$$se + [|Goo();|] + } + } + """); } [Fact] public void ElseIf() { TestSpan( -@"class C -{ - void Goo() - { - if (bar) - { - } - el$$se [|if (baz)|] - Goo(); - } -}"); + """ + class C + { + void Goo() + { + if (bar) + { + } + el$$se [|if (baz)|] + Goo(); + } + } + """); } [Fact] public void EmptyCatch() { TestSpan( -@"class C -{ - void Goo() - { - try - { - } - [|cat$$ch|] - { - } - } -}"); + """ + class C + { + void Goo() + { + try + { + } + [|cat$$ch|] + { + } + } + } + """); } [Fact] public void CatchWithType() { TestSpan( -@"class C -{ - void Goo() - { - try - { - } - [|cat$$ch(Exception)|] - { - } - } -}"); + """ + class C + { + void Goo() + { + try + { + } + [|cat$$ch(Exception)|] + { + } + } + } + """); } [Fact] public void CatchWithTypeInType() { TestSpan( -@"class C -{ - void Goo() - { - try - { - } - [|catch(Exce$$ption)|] - { - } - } -}"); + """ + class C + { + void Goo() + { + try + { + } + [|catch(Exce$$ption)|] + { + } + } + } + """); } [Fact] public void CatchWithTypeAndNameInType() { TestSpan( -@"class C -{ - void Goo() - { - try - { - } - [|catch(Exce$$ption e)|] - { - } - } -}"); + """ + class C + { + void Goo() + { + try + { + } + [|catch(Exce$$ption e)|] + { + } + } + } + """); } [Fact] public void CatchWithTypeAndNameInName() { TestSpan( -@"class C -{ - void Goo() - { - try - { - } - [|catch(Exception $$e)|] - { - } - } -}"); + """ + class C + { + void Goo() + { + try + { + } + [|catch(Exception $$e)|] + { + } + } + } + """); } [Fact] public void Filter1() { TestSpan( -@"class C -{ - void Goo() - { - try - { - } - $$catch(Exception e) [|when (e.Message != null)|] - { - } - } -}"); + """ + class C + { + void Goo() + { + try + { + } + $$catch(Exception e) [|when (e.Message != null)|] + { + } + } + } + """); } [Fact] public void Filter3() { TestSpan( -@"class C -{ - void Goo() - { - try - { - } - catch(Exception e)$$ [|when (e.Message != null)|] - { - } - } -}"); + """ + class C + { + void Goo() + { + try + { + } + catch(Exception e)$$ [|when (e.Message != null)|] + { + } + } + } + """); } [Fact] public void Filter4() { TestSpan( -@"class C -{ - void Goo() - { - try - { - } - catch(Exception e) [|when$$ (e.Message != null)|] - { - } - } -}"); + """ + class C + { + void Goo() + { + try + { + } + catch(Exception e) [|when$$ (e.Message != null)|] + { + } + } + } + """); } [Fact] public void Filter5() { TestSpan( -@"class C -{ - void Goo() - { - try - { - } - catch(Exception e) [|when (e.Message != null)|] $$ - { - } - } -}"); + """ + class C + { + void Goo() + { + try + { + } + catch(Exception e) [|when (e.Message != null)|] $$ + { + } + } + } + """); } [Fact] public void SimpleFinally() { TestSpan( -@"class C -{ - void Goo() - { - try - { - } - final$$ly - [|{|] - } - } -}"); + """ + class C + { + void Goo() + { + try + { + } + final$$ly + [|{|] + } + } + } + """); } [Fact] public void FinallyWithCatch() { TestSpan( -@"class C -{ - void Goo() - { - try - { - } - catch - { - } - final$$ly - [|{|] - } - } -}"); + """ + class C + { + void Goo() + { + try + { + } + catch + { + } + final$$ly + [|{|] + } + } + } + """); } [Fact] public void SwitchLabelWithBlock() { TestSpan( -@"class C -{ - void Goo() - { - switch (goo) - { - case $$1: - [|{|] + """ + class C + { + void Goo() + { + switch (goo) + { + case $$1: + [|{|] + } + } + } } - } - } -}"); + """); } [Fact] public void SwitchLabelWithStatement() { TestSpan( -@"class C -{ - void Goo() - { - switch (goo) - { - cas$$e 1: - [|goo();|] - } - } -}"); + """ + class C + { + void Goo() + { + switch (goo) + { + cas$$e 1: + [|goo();|] + } + } + } + """); } [Fact] public void SwitchLabelWithStatement2() { TestSpan( -@"class C -{ - void Goo() - { - switch (goo) - { - cas$$e 1: - [|goo();|] - bar(); - } - } -}"); + """ + class C + { + void Goo() + { + switch (goo) + { + cas$$e 1: + [|goo();|] + bar(); + } + } + } + """); } [Fact] @@ -2165,2104 +2413,2398 @@ public void SwitchLabelWithoutStatement() public void MultipleLabelsOnFirstLabel() { TestSpan( -@"class C -{ - void Goo() - { - switch (goo) - { - cas$$e 1: - case 2: - [|goo();|] - - case 3: - default: - bar(); - } - } -}"); + """ + class C + { + void Goo() + { + switch (goo) + { + cas$$e 1: + case 2: + [|goo();|] + + case 3: + default: + bar(); + } + } + } + """); } [Fact] public void MultipleLabelsOnSecondLabel() { TestSpan( -@"class C -{ - void Goo() - { - switch (goo) - { - case 1: - cas$$e 2: - [|goo();|] - - case 3: - default: - bar(); - } - } -}"); + """ + class C + { + void Goo() + { + switch (goo) + { + case 1: + cas$$e 2: + [|goo();|] + + case 3: + default: + bar(); + } + } + } + """); } [Fact] public void MultipleLabelsOnLabelWithDefault() { TestSpan( -@"class C -{ - void Goo() - { - switch (goo) - { - case 1: - case 2: - goo(); - - cas$$e 3: - default: - [|bar();|] - } - } -}"); + """ + class C + { + void Goo() + { + switch (goo) + { + case 1: + case 2: + goo(); + + cas$$e 3: + default: + [|bar();|] + } + } + } + """); } [Fact] public void MultipleLabelsOnDefault() { TestSpan( -@"class C -{ - void Goo() - { - switch (goo) - { - case 1: - case 2: - goo(); - - case 3: - default:$$ - [|bar();|] - } - } -}"); + """ + class C + { + void Goo() + { + switch (goo) + { + case 1: + case 2: + goo(); + + case 3: + default:$$ + [|bar();|] + } + } + } + """); } [Fact] public void BlockBeforeStartToken() { TestSpan( -@"class C -{ - void Goo() - [|$${|] - - } -}"); + """ + class C + { + void Goo() + [|$${|] + + } + } + """); } [Fact] public void BlockBeforeStartToken2() { TestSpan( -@"class C -{ - void Goo() - $$ [|{|] - - } -}"); + """ + class C + { + void Goo() + $$ [|{|] + + } + } + """); } [Fact] public void BlockAfterStartToken() { TestSpan( -@"class C -{ - void Goo() - [|{$$|] - - } -}"); + """ + class C + { + void Goo() + [|{$$|] + + } + } + """); } [Fact] public void BlockAfterStartToken2() { TestSpan( -@"class C -{ - void Goo() - [|{|] $$ - - } -}"); + """ + class C + { + void Goo() + [|{|] $$ + + } + } + """); } [Fact] public void BlockBeforeEndToken1() { TestSpan( -@"class C -{ - void Goo() - { - $$[|}|] -}"); + """ + class C + { + void Goo() + { + $$[|}|] + } + """); } [Fact] public void BlockBeforeEndToken2() { TestSpan( -@"class C -{ - void Goo() - { - $$ [|}|] -}"); + """ + class C + { + void Goo() + { + $$ [|}|] + } + """); } [Fact] public void BlockAfterEndToken1() { TestSpan( -@"class C -{ - void Goo() - { - [|}|]$$ -}"); + """ + class C + { + void Goo() + { + [|}|]$$ + } + """); } [Fact] public void BlockAfterEndToken2() { TestSpan( -@"class C -{ - void Goo() - { - [|}|] $$ -}"); + """ + class C + { + void Goo() + { + [|}|] $$ + } + """); } [Fact] public void SingleDeclarationOnType() { TestMissing( -@"class C -{ - void Goo() - { - i$$nt i; - } -}"); + """ + class C + { + void Goo() + { + i$$nt i; + } + } + """); } [Fact] public void MultipleDeclarationsOnType() { TestSpan( -@"class C -{ - void Goo() - { - [|i$$nt i = 0|], j = 1; - } -}"); + """ + class C + { + void Goo() + { + [|i$$nt i = 0|], j = 1; + } + } + """); } [Fact] public void Label() { TestSpan( -@"class C -{ - void Goo() - { - go$$o: - [|bar();|] - } -}"); + """ + class C + { + void Goo() + { + go$$o: + [|bar();|] + } + } + """); } [Fact] public void WhileInWhile() { TestSpan( -@"class C -{ - void Goo() - { - [|w$$hile (expr)|] - { - } - } -}"); + """ + class C + { + void Goo() + { + [|w$$hile (expr)|] + { + } + } + } + """); } [Fact] public void WhileInExpr() { TestSpan( -@"class C -{ - void Goo() - { - [|while (ex$$pr)|] - { - } - } -}"); + """ + class C + { + void Goo() + { + [|while (ex$$pr)|] + { + } + } + } + """); } [Fact] public void OnWhileBlock() { TestSpan( -@"class C -{ - void Goo() - { - while (expr) - $$ [|{|] - } - } -}"); + """ + class C + { + void Goo() + { + while (expr) + $$ [|{|] + } + } + } + """); } [Fact] public void OnDoKeyword() { TestSpan( -@"class C -{ - void Goo() - { - d$$o - [|{|] - } - while(expr); - } -}"); + """ + class C + { + void Goo() + { + d$$o + [|{|] + } + while(expr); + } + } + """); } [Fact] public void OnDoBlock() { TestSpan( -@"class C -{ - void Goo() - { - do - $$ [|{|] - } - while(expr); - } -}"); + """ + class C + { + void Goo() + { + do + $$ [|{|] + } + while(expr); + } + } + """); } [Fact] public void OnDoWhile() { TestSpan( -@"class C -{ - void Goo() - { - do - { - } - [|wh$$ile(expr);|] - } -}"); + """ + class C + { + void Goo() + { + do + { + } + [|wh$$ile(expr);|] + } + } + """); } [Fact] public void OnDoWhile_MissingSemicolon() { TestSpan( -@"class C -{ - void Goo() - { - do - { - } - [|wh$$ile(expr)|] - } -}"); + """ + class C + { + void Goo() + { + do + { + } + [|wh$$ile(expr)|] + } + } + """); } [Fact] public void OnDoExpression() { TestSpan( -@"class C -{ - void Goo() - { - do - { - } - [|while(ex$$pr);|] - } -}"); + """ + class C + { + void Goo() + { + do + { + } + [|while(ex$$pr);|] + } + } + """); } [Fact] public void OnForWithDeclaration1() { TestSpan( -@"class C -{ - void Goo() - { - f$$or ([|int i = 0|], j = 1; i < 10 && j < 10; i++, j++) - { - } - } -}"); + """ + class C + { + void Goo() + { + f$$or ([|int i = 0|], j = 1; i < 10 && j < 10; i++, j++) + { + } + } + } + """); } [Fact] public void OnForWithDeclaration2() { TestSpan( -@"class C -{ - void Goo() - { - f$$or ([|int i = 0|]; i < 10 && j < 10; i++, j++) - { - } - } -}"); + """ + class C + { + void Goo() + { + f$$or ([|int i = 0|]; i < 10 && j < 10; i++, j++) + { + } + } + } + """); } [Fact] public void OnForWithCondition() { TestSpan( -@"class C -{ - void Goo() - { - f$$or (; [|i < 10 && j < 10|]; i++, j++) - { - } - } -}"); + """ + class C + { + void Goo() + { + f$$or (; [|i < 10 && j < 10|]; i++, j++) + { + } + } + } + """); } [Fact] public void OnForWithIncrementor1() { TestSpan( -@"class C -{ - void Goo() - { - f$$or (; ; [|i++|], j++) - { - } - } -}"); + """ + class C + { + void Goo() + { + f$$or (; ; [|i++|], j++) + { + } + } + } + """); } [Fact] public void OnForWithIncrementor2() { TestSpan( -@"class C -{ - void Goo() - { - f$$or (; ; [|i++|]) - { - } - } -}"); + """ + class C + { + void Goo() + { + f$$or (; ; [|i++|]) + { + } + } + } + """); } [Fact] public void OnEmptyFor() { TestSpan( -@"class C -{ - void Goo() - { - f$$or (; ; ) - [|{|] - } - } -}"); + """ + class C + { + void Goo() + { + f$$or (; ; ) + [|{|] + } + } + } + """); } [Fact] public void OnForEachKeyword1() { TestSpan( -@"class C -{ - void Goo() - { -$$ [|foreach|] (var v in expr().blah()) - { - } - } -}"); + """ + class C + { + void Goo() + { + $$ [|foreach|] (var v in expr().blah()) + { + } + } + } + """); } [Fact] public void OnForEachKeyword2() { TestSpan( -@"class C -{ - void Goo() - { - [|fo$$reach|] (var v in expr().blah()) - { - } - } -}"); + """ + class C + { + void Goo() + { + [|fo$$reach|] (var v in expr().blah()) + { + } + } + } + """); } [Fact] public void OnForEachKeyword3() { TestSpan( -@"class C -{ - void Goo() - { - [|foreach|] $$ -(var v in expr().blah()) - { - } - } -}"); + """ + class C + { + void Goo() + { + [|foreach|] $$ + (var v in expr().blah()) + { + } + } + } + """); } [Fact] public void OnForEachKeyword4() { TestSpan( -@"class C -{ - void Goo() - { - [|foreach|] -$$ (var v in expr().blah()) - { - } - } -}"); + """ + class C + { + void Goo() + { + [|foreach|] + $$ (var v in expr().blah()) + { + } + } + } + """); } [Fact] public void OnForEachKeyword5() { TestSpan( -@"class C -{ - void Goo() - { - [|foreach|] $$(var v in expr().blah()) - { - } - } -}"); + """ + class C + { + void Goo() + { + [|foreach|] $$(var v in expr().blah()) + { + } + } + } + """); } [Fact] public void OnForEachType1() { TestSpan( -@"class C -{ - void Goo() - { - foreach ( $$ -[|var v|] in expr().blah()) - { - } - } -}"); + """ + class C + { + void Goo() + { + foreach ( $$ + [|var v|] in expr().blah()) + { + } + } + } + """); } [Fact] public void OnForEachType2() { TestSpan( -@"class C -{ - void Goo() - { - foreach ([|v$$ar v|] in expr().blah()) - { - } - } -}"); + """ + class C + { + void Goo() + { + foreach ([|v$$ar v|] in expr().blah()) + { + } + } + } + """); } [Fact] public void OnForEachIdentifier() { TestSpan( -@"class C -{ - void Goo() - { - foreach ([|var v$$v|] in expr().blah()) - { - } - } -}"); + """ + class C + { + void Goo() + { + foreach ([|var v$$v|] in expr().blah()) + { + } + } + } + """); } [Fact] public void OnForEachIn1() { TestSpan( -@"class C -{ - void Goo() - { - foreach (var v [|i$$n|] expr().blah()) - { - } - } -}"); + """ + class C + { + void Goo() + { + foreach (var v [|i$$n|] expr().blah()) + { + } + } + } + """); } [Fact] public void OnForEachIn2() { TestSpan( -@"class C -{ - void Goo() - { - foreach (var v -$$ [|in|] expr().blah()) - { - } - } -}"); + """ + class C + { + void Goo() + { + foreach (var v + $$ [|in|] expr().blah()) + { + } + } + } + """); } [Fact] public void OnForEachIn3() { TestSpan( -@"class C -{ - void Goo() - { - foreach (var v - [|in|] $$ -expr().blah()) - { - } - } -}"); + """ + class C + { + void Goo() + { + foreach (var v + [|in|] $$ + expr().blah()) + { + } + } + } + """); } [Fact] public void OnForEachExpr1() { TestSpan( -@"class C -{ - void Goo() - { - foreach (var v in [|expr($$).blah()|]) - { - } - } -}"); + """ + class C + { + void Goo() + { + foreach (var v in [|expr($$).blah()|]) + { + } + } + } + """); } [Fact] public void OnForEachExpr2() { TestSpan( -@"class C -{ - void Goo() - { - foreach (var v in [|expr().blah()|] - $$ ) - { - } - } -}"); + """ + class C + { + void Goo() + { + foreach (var v in [|expr().blah()|] + $$ ) + { + } + } + } + """); } [Fact] public void OnForEachExpr3() { TestSpan( -@"class C -{ - void Goo() - { - foreach (var v in - $$ [|expr().blah()|] - ) - { - } - } -}"); + """ + class C + { + void Goo() + { + foreach (var v in + $$ [|expr().blah()|] + ) + { + } + } + } + """); } [Fact] public void OnForEachStatement() { TestSpan( -@"class C -{ - void Goo() - { - [|foreach|](var v in expr().blah()) $$ - { - } - } -}"); + """ + class C + { + void Goo() + { + [|foreach|](var v in expr().blah()) $$ + { + } + } + } + """); } [Fact] public void OnForEachBlock1() { TestSpan( -@"class C -{ - void Goo() - { - foreach (var v in expr().blah()) - $$ [|{|] - } - } -}"); + """ + class C + { + void Goo() + { + foreach (var v in expr().blah()) + $$ [|{|] + } + } + } + """); } [Fact] public void OnForEachDeconstructionKeyword1() { TestSpan( -@"class C -{ - void Goo() - { -$$ [|foreach|] (var (x, y) in expr().blah()) - { - } - } -}"); + """ + class C + { + void Goo() + { + $$ [|foreach|] (var (x, y) in expr().blah()) + { + } + } + } + """); } [Fact] public void OnForEachDeconstructionKeyword2() { TestSpan( -@"class C -{ - void Goo() - { - [|fo$$reach|] (var (x, y) in expr().blah()) - { - } - } -}"); + """ + class C + { + void Goo() + { + [|fo$$reach|] (var (x, y) in expr().blah()) + { + } + } + } + """); } [Fact] public void OnForEachDeconstructionKeyword3() { TestSpan( -@"class C -{ - void Goo() - { - [|foreach|] $$ -(var (x, y) in expr().blah()) - { - } - } -}"); + """ + class C + { + void Goo() + { + [|foreach|] $$ + (var (x, y) in expr().blah()) + { + } + } + } + """); } [Fact] public void OnForEachDeconstructionKeyword4() { TestSpan( -@"class C -{ - void Goo() - { - [|foreach|] -$$ (var (x, y) in expr().blah()) - { - } - } -}"); + """ + class C + { + void Goo() + { + [|foreach|] + $$ (var (x, y) in expr().blah()) + { + } + } + } + """); } [Fact] public void OnForEachDeconstructionKeyword5() { TestSpan( -@"class C -{ - void Goo() - { - [|foreach|] $$(var (x, y) in expr().blah()) - { - } - } -}"); + """ + class C + { + void Goo() + { + [|foreach|] $$(var (x, y) in expr().blah()) + { + } + } + } + """); } [Fact] public void OnForEachDeconstructionType1() { TestSpan( -@"class C -{ - void Goo() - { - foreach ( $$ -[|var (x, y)|] in expr().blah()) - { - } - } -}"); + """ + class C + { + void Goo() + { + foreach ( $$ + [|var (x, y)|] in expr().blah()) + { + } + } + } + """); } [Fact] public void OnForEachDeconstructionType2() { TestSpan( -@"class C -{ - void Goo() - { - foreach ([|v$$ar (x, y)|] in expr().blah()) - { - } - } -}"); + """ + class C + { + void Goo() + { + foreach ([|v$$ar (x, y)|] in expr().blah()) + { + } + } + } + """); } [Fact] public void OnForEachDeconstructionIdentifier() { TestSpan( -@"class C -{ - void Goo() - { - foreach ([|var (v$$v, y)|] in expr().blah()) - { - } - } -}"); + """ + class C + { + void Goo() + { + foreach ([|var (v$$v, y)|] in expr().blah()) + { + } + } + } + """); } [Fact] public void OnForEachDeconstructionIn1() { TestSpan( -@"class C -{ - void Goo() - { - foreach (var (x, y) [|i$$n|] expr().blah()) - { - } - } -}"); + """ + class C + { + void Goo() + { + foreach (var (x, y) [|i$$n|] expr().blah()) + { + } + } + } + """); } [Fact] public void OnForEachDeconstructionIn2() { TestSpan( -@"class C -{ - void Goo() - { - foreach (var (x, y) -$$ [|in|] expr().blah()) - { - } - } -}"); + """ + class C + { + void Goo() + { + foreach (var (x, y) + $$ [|in|] expr().blah()) + { + } + } + } + """); } [Fact] public void OnForEachDeconstructionIn3() { TestSpan( -@"class C -{ - void Goo() - { - foreach (var (x, y) - [|in|] $$ -expr().blah()) - { - } - } -}"); + """ + class C + { + void Goo() + { + foreach (var (x, y) + [|in|] $$ + expr().blah()) + { + } + } + } + """); } [Fact] public void OnForEachDeconstructionExpr1() { TestSpan( -@"class C -{ - void Goo() - { - foreach (var (x, y) in [|expr($$).blah()|]) - { - } - } -}"); + """ + class C + { + void Goo() + { + foreach (var (x, y) in [|expr($$).blah()|]) + { + } + } + } + """); } [Fact] public void OnForEachDeconstructionExpr2() { TestSpan( -@"class C -{ - void Goo() - { - foreach (var (x, y) in [|expr().blah()|] - $$ ) - { - } - } -}"); + """ + class C + { + void Goo() + { + foreach (var (x, y) in [|expr().blah()|] + $$ ) + { + } + } + } + """); } [Fact] public void OnForEachDeconstructionExpr3() { TestSpan( -@"class C -{ - void Goo() - { - foreach (var (x, y) in - $$ [|expr().blah()|] - ) - { - } - } -}"); + """ + class C + { + void Goo() + { + foreach (var (x, y) in + $$ [|expr().blah()|] + ) + { + } + } + } + """); } [Fact] public void OnForEachDeconstructionStatement() { TestSpan( -@"class C -{ - void Goo() - { - [|foreach|](var (x, y) in expr().blah()) $$ - { - } - } -}"); + """ + class C + { + void Goo() + { + [|foreach|](var (x, y) in expr().blah()) $$ + { + } + } + } + """); } [Fact] public void OnForEachDeconstructionBlock1() { TestSpan( -@"class C -{ - void Goo() - { - foreach (var (x, y) in expr().blah()) - $$ [|{|] - } - } -}"); + """ + class C + { + void Goo() + { + foreach (var (x, y) in expr().blah()) + $$ [|{|] + } + } + } + """); } [Fact] public void OnUsingWithDecl1() { TestSpan( -@"class C -{ - void Goo() - { - us$$ing ([|var v = goo()|]) - { - } - } -}"); + """ + class C + { + void Goo() + { + us$$ing ([|var v = goo()|]) + { + } + } + } + """); } [Fact] public void OnUsingWithDecl2() { TestSpan( -@"class C -{ - void Goo() - { - us$$ing ([|var v = goo()|], x = bar()) - { - } - } -}"); + """ + class C + { + void Goo() + { + us$$ing ([|var v = goo()|], x = bar()) + { + } + } + } + """); } [Fact] public void OnUsingWithDeclType() { TestSpan( -@"class C -{ - void Goo() - { - using ([|v$$ar v = goo()|]) - { - } - } -}"); + """ + class C + { + void Goo() + { + using ([|v$$ar v = goo()|]) + { + } + } + } + """); } [Fact] public void OnUsingWithDeclIdentifier1() { TestSpan( -@"class C -{ - void Goo() - { - using ([|var v$$v = goo()|]) - { - } - } -}"); + """ + class C + { + void Goo() + { + using ([|var v$$v = goo()|]) + { + } + } + } + """); } [Fact] public void OnUsingWithDeclIdentifier2() { TestSpan( -@"class C -{ - void Goo() - { - using ([|var vv = goo()|]) $$ - { - } - } -}"); + """ + class C + { + void Goo() + { + using ([|var vv = goo()|]) $$ + { + } + } + } + """); } [Fact] public void OnUsingWithDeclIdentifier3() { TestSpan( -@"class C -{ - void Goo() - { -$$ using ([|var vv = goo()|]) - { - } - } -}"); + """ + class C + { + void Goo() + { + $$ using ([|var vv = goo()|]) + { + } + } + } + """); } [Fact] public void OnUsingWithDeclExpression() { TestSpan( -@"class C -{ - void Goo() - { - using ([|var vv = go$$o()|]) - { - } - } -}"); + """ + class C + { + void Goo() + { + using ([|var vv = go$$o()|]) + { + } + } + } + """); } [Fact] public void OnUsingWithExpression1() { TestSpan( -@"class C -{ - void Goo() - { - [|usi$$ng (goo().bar())|] - { - } - } -}"); + """ + class C + { + void Goo() + { + [|usi$$ng (goo().bar())|] + { + } + } + } + """); } [Fact] public void OnUsingWithExpression2() { TestSpan( -@"class C -{ - void Goo() - { - [|using (goo$$().bar())|] - { - } - } -}"); + """ + class C + { + void Goo() + { + [|using (goo$$().bar())|] + { + } + } + } + """); } [Fact] public void OnFixed1() { TestSpan( -@"class C -{ - void Goo() - { - fi$$xed ([|int* i = &j|]) - { - } - } -}"); + """ + class C + { + void Goo() + { + fi$$xed ([|int* i = &j|]) + { + } + } + } + """); } [Fact] public void OnFixed2() { TestSpan( -@"class C -{ - void Goo() - { - fi$$xed ([|int* i = &j|], k = &m) - { - } - } -}"); + """ + class C + { + void Goo() + { + fi$$xed ([|int* i = &j|], k = &m) + { + } + } + } + """); } [Fact] public void OnFixed3() { TestSpan( -@"class C -{ - void Goo() - { - fixed ([|i$$nt* i = &j|]) - { - } - } -}"); + """ + class C + { + void Goo() + { + fixed ([|i$$nt* i = &j|]) + { + } + } + } + """); } [Fact] public void OnFixed4() { TestSpan( -@"class C -{ - void Goo() - { - fixed ([|int* $$i = &j|]) - { - } - } -}"); + """ + class C + { + void Goo() + { + fixed ([|int* $$i = &j|]) + { + } + } + } + """); } [Fact] public void OnFixed5() { TestSpan( -@"class C -{ - void Goo() - { - fixed ([|int* i $$= &j|]) - { - } - } -}"); + """ + class C + { + void Goo() + { + fixed ([|int* i $$= &j|]) + { + } + } + } + """); } [Fact] public void OnFixed6() { TestSpan( -@"class C -{ - void Goo() - { - fixed ([|int* i = &$$j|]) - { - } - } -}"); + """ + class C + { + void Goo() + { + fixed ([|int* i = &$$j|]) + { + } + } + } + """); } [Fact] public void OnChecked1() { TestSpan( -@"class C -{ - void Goo() - { - che$$cked - [|{|] - } - } -}"); + """ + class C + { + void Goo() + { + che$$cked + [|{|] + } + } + } + """); } [Fact] public void OnUnchecked1() { TestSpan( -@"class C -{ - void Goo() - { - unche$$cked - [|{|] - } - } -}"); + """ + class C + { + void Goo() + { + unche$$cked + [|{|] + } + } + } + """); } [Fact] public void OnUnsafe1() { TestSpan( -@"class C -{ - void Goo() - { - uns$$afe - [|{|] - } - } -}"); + """ + class C + { + void Goo() + { + uns$$afe + [|{|] + } + } + } + """); } [Fact] public void OnLock1() { TestSpan( -@"class C -{ - void Goo() - { - [|lo$$ck (expr)|] - { - } - } -}"); + """ + class C + { + void Goo() + { + [|lo$$ck (expr)|] + { + } + } + } + """); } [Fact] public void OnLock2() { TestSpan( -@"class C -{ - void Goo() - { - [|lock (ex$$pr)|] - { - } - } -}"); + """ + class C + { + void Goo() + { + [|lock (ex$$pr)|] + { + } + } + } + """); } [Fact] public void OnIf1() { TestSpan( -@"class C -{ - void Goo() - { - [|i$$f (goo().bar())|] - { - } - } -}"); + """ + class C + { + void Goo() + { + [|i$$f (goo().bar())|] + { + } + } + } + """); } [Fact] public void OnIf2() { TestSpan( -@"class C -{ - void Goo() - { - [|if (go$$o().bar())|] - { - } - } -}"); + """ + class C + { + void Goo() + { + [|if (go$$o().bar())|] + { + } + } + } + """); } [Fact] public void OnIfBlock() { TestSpan( -@"class C -{ - void Goo() - { - if (goo().bar()) - $$ [|{|] - } - } -}"); + """ + class C + { + void Goo() + { + if (goo().bar()) + $$ [|{|] + } + } + } + """); } [Fact] public void OnSwitch1() { TestSpan( -@"class C -{ - void Goo() - { - [|swi$$tch (expr)|] - { - default: - goo(); - } - } -}"); + """ + class C + { + void Goo() + { + [|swi$$tch (expr)|] + { + default: + goo(); + } + } + } + """); } [Fact] public void OnSwitch2() { TestSpan( -@"class C -{ - void Goo() - { - [|switch (ex$$pr)|] - { - default: - goo(); - } - } -}"); + """ + class C + { + void Goo() + { + [|switch (ex$$pr)|] + { + default: + goo(); + } + } + } + """); } [Fact] public void OnSwitch3() { TestSpan( -@"class C -{ - void Goo() - { - [|switch (expr)|] - $$ { - default: - goo(); - } - } -}"); + """ + class C + { + void Goo() + { + [|switch (expr)|] + $$ { + default: + goo(); + } + } + } + """); } [Fact] public void OnSwitch4() { TestSpan( -@"class C -{ - void Goo() - { - [|switch (expr)|] - { - default: - goo(); - $$ } - } -}"); + """ + class C + { + void Goo() + { + [|switch (expr)|] + { + default: + goo(); + $$ } + } + } + """); } [Fact] public void OnTry1() { TestSpan( -@"class C -{ - void Goo() - { - t$$ry - [|{|] - } - finally - { - } - } -}"); + """ + class C + { + void Goo() + { + t$$ry + [|{|] + } + finally + { + } + } + } + """); } [Fact] public void OnTry2() { - TestSpan( -@"class C -{ - void Goo() - { - try - $$ [|{|] - } - finally - { - } - } -}"); + TestSpan( + """ + class C + { + void Goo() + { + try + $$ [|{|] + } + finally + { + } + } + } + """); } [Fact] public void OnGotoStatement1() { TestSpan( -@"class C -{ - void Goo() - { - [|g$$oto goo;|] - } -}"); + """ + class C + { + void Goo() + { + [|g$$oto goo;|] + } + } + """); } [Fact] public void OnGotoStatement2() { TestSpan( -@"class C -{ - void Goo() - { - [|goto go$$o;|] - } -}"); + """ + class C + { + void Goo() + { + [|goto go$$o;|] + } + } + """); } [Fact] public void OnGotoCaseStatement1() { TestSpan( -@"class C -{ - void Goo() - { - switch (expr) - { - case 1: - [|go$$to case 2;|] - } - } -}"); + """ + class C + { + void Goo() + { + switch (expr) + { + case 1: + [|go$$to case 2;|] + } + } + } + """); } [Fact] public void OnGotoCaseStatement2() { TestSpan( -@"class C -{ - void Goo() - { - switch (expr) - { - case 1: - [|goto ca$$se 2;|] - } - } -}"); + """ + class C + { + void Goo() + { + switch (expr) + { + case 1: + [|goto ca$$se 2;|] + } + } + } + """); } [Fact] public void OnGotoCaseStatement3() { TestSpan( -@"class C -{ - void Goo() - { - switch (expr) - { - case 1: - [|goto case $$2;|] - } - } -}"); + """ + class C + { + void Goo() + { + switch (expr) + { + case 1: + [|goto case $$2;|] + } + } + } + """); } [Fact] public void OnGotoDefault1() { TestSpan( -@"class C -{ - void Goo() - { - switch (expr) - { - case 1: - [|go$$to default;|] - } - } -}"); + """ + class C + { + void Goo() + { + switch (expr) + { + case 1: + [|go$$to default;|] + } + } + } + """); } [Fact] public void OnGotoDefault2() { TestSpan( -@"class C -{ - void Goo() - { - switch (expr) - { - case 1: - [|goto defau$$lt;|] - } - } -}"); + """ + class C + { + void Goo() + { + switch (expr) + { + case 1: + [|goto defau$$lt;|] + } + } + } + """); } [Fact] public void OnBreak1() { TestSpan( -@"class C -{ - void Goo() - { - while (true) - { - [|bre$$ak;|] - } - } -}"); + """ + class C + { + void Goo() + { + while (true) + { + [|bre$$ak;|] + } + } + } + """); } [Fact] public void OnContinue1() { TestSpan( -@"class C -{ - void Goo() - { - while (true) - { - [|cont$$inue;|] - } - } -}"); + """ + class C + { + void Goo() + { + while (true) + { + [|cont$$inue;|] + } + } + } + """); } [Fact] public void OnReturn1() { TestSpan( -@"class C -{ - void Goo() - { - [|retu$$rn;|] - } -}"); + """ + class C + { + void Goo() + { + [|retu$$rn;|] + } + } + """); } [Fact] public void OnReturn2() { TestSpan( -@"class C -{ - void Goo() - { - [|retu$$rn expr();|] - } -}"); + """ + class C + { + void Goo() + { + [|retu$$rn expr();|] + } + } + """); } [Fact] public void OnReturn3() { TestSpan( -@"class C -{ - void Goo() - { - [|return expr$$().bar();|] - } -}"); + """ + class C + { + void Goo() + { + [|return expr$$().bar();|] + } + } + """); } [Fact] public void OnYieldReturn1() { TestSpan( -@"class C -{ - void Goo() - { - [|yi$$eld return goo().bar();|] - } -}"); + """ + class C + { + void Goo() + { + [|yi$$eld return goo().bar();|] + } + } + """); } [Fact] public void OnYieldReturn2() { TestSpan( -@"class C -{ - void Goo() - { - [|yield re$$turn goo().bar();|] - } -}"); + """ + class C + { + void Goo() + { + [|yield re$$turn goo().bar();|] + } + } + """); } [Fact] public void OnYieldReturn3() { TestSpan( -@"class C -{ - void Goo() - { - [|yield return goo()$$.bar();|] - } -}"); + """ + class C + { + void Goo() + { + [|yield return goo()$$.bar();|] + } + } + """); } [Fact] public void OnYieldBreak1() { TestSpan( -@"class C -{ - void Goo() - { - [|yi$$eld break;|] - } -}"); + """ + class C + { + void Goo() + { + [|yi$$eld break;|] + } + } + """); } [Fact] public void OnYieldBreak2() { TestSpan( -@"class C -{ - void Goo() - { - [|yield brea$$k;|] - } -}"); + """ + class C + { + void Goo() + { + [|yield brea$$k;|] + } + } + """); } [Fact] public void OnThrow1() { TestSpan( -@"class C -{ - void Goo() - { - [|th$$row;|] - } -}"); + """ + class C + { + void Goo() + { + [|th$$row;|] + } + } + """); } [Fact] public void OnThrow2() { TestSpan( -@"class C -{ - void Goo() - { - [|thr$$ow new Goo();|] - } -}"); + """ + class C + { + void Goo() + { + [|thr$$ow new Goo();|] + } + } + """); } [Fact] public void OnThrow3() { TestSpan( -@"class C -{ - void Goo() - { - [|throw ne$$w Goo();|] - } -}"); + """ + class C + { + void Goo() + { + [|throw ne$$w Goo();|] + } + } + """); } [Fact] public void OnThrow4() { TestSpan( -@"class C -{ - void Goo() - { - [|throw new Go$$o();|] - } -}"); + """ + class C + { + void Goo() + { + [|throw new Go$$o();|] + } + } + """); } [Fact] public void OnExpressionStatement1() { TestSpan( -@"class C -{ - void Goo() - { - [|goo().$$bar();|] - } -}"); + """ + class C + { + void Goo() + { + [|goo().$$bar();|] + } + } + """); } [Fact] public void OnEmptyStatement1() { TestSpan( -@"class C -{ - void Goo() - { - [|$$;|] - } -}"); + """ + class C + { + void Goo() + { + [|$$;|] + } + } + """); } [Fact] public void OnEmptyStatement2() { TestSpan( -@"class C -{ - void Goo() - { - while (true) - { - $$ [|;|] - } - } -}"); + """ + class C + { + void Goo() + { + while (true) + { + $$ [|;|] + } + } + } + """); } [Fact] public void OnPropertyAccessor1() { TestSpan( -@"class C -{ - int Goo - { - g$$et - [|{|] - } - } -}"); + """ + class C + { + int Goo + { + g$$et + [|{|] + } + } + } + """); } [Fact] public void OnPropertyAccessor2() { TestSpan( -@"class C -{ - int Goo - { - [|g$$et;|] - } -}"); + """ + class C + { + int Goo + { + [|g$$et;|] + } + } + """); } [Fact] public void OnPropertyAccessor3() { TestSpan( -@"class C -{ - int Goo - { - get - { - } + """ + class C + { + int Goo + { + get + { + } - s$$et - [|{|] - } - } -}"); + s$$et + [|{|] + } + } + } + """); } [Fact] public void OnPropertyAccessor4() { TestSpan( -@"class C -{ - int Goo - { - [|s$$et;|] - } -}"); + """ + class C + { + int Goo + { + [|s$$et;|] + } + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48504")] public void OnPropertyAccessor5() { TestSpan( -@"class C -{ - int Goo - { - [|in$$it;|] - } -}"); + """ + class C + { + int Goo + { + [|in$$it;|] + } + } + """); } [Fact] public void OnProperty1() { TestSpan( -@"class C -{ - int G$$oo - { - get - [|{|] - } - - set - { - } - } -}"); + """ + class C + { + int G$$oo + { + get + [|{|] + } + + set + { + } + } + } + """); } [Fact] public void OnProperty2() { TestSpan( -@"class C -{ - int G$$oo - { - [|get;|] - set {} - } -}"); + """ + class C + { + int G$$oo + { + [|get;|] + set {} + } + } + """); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932711")] public void OnPropertyWithInitializer() { TestSpan( -@"class C -{ - public int Id { get; set; } = [|int.Pa$$rse(""42"")|]; -}"); + """ + class C + { + public int Id { get; set; } = [|int.Pa$$rse("42")|]; + } + """); TestSpan( -@"class C -{ - public int$$ Id { [|get;|] set; } = int.Parse(""42""); -}"); + """ + class C + { + public int$$ Id { [|get;|] set; } = int.Parse("42"); + } + """); TestSpan( -@"class C -{ - public int Id { get; [|set;|] $$} = int.Parse(""42""); -}"); + """ + class C + { + public int Id { get; [|set;|] $$} = int.Parse("42"); + } + """); TestSpan( -@"class C -{ - public int Id { get; [|set;|] }$$ = int.Parse(""42""); -}"); + """ + class C + { + public int Id { get; [|set;|] }$$ = int.Parse("42"); + } + """); TestSpan( -@"class C -{ - public int Id { get; set; } =$$ [|int.Parse(""42"")|]; -}"); + """ + class C + { + public int Id { get; set; } =$$ [|int.Parse("42")|]; + } + """); } [Fact] public void OnPropertyExpressionBody1() { TestSpan( -@"class C -{ - public int Id => [|12$$3|]; -}"); + """ + class C + { + public int Id => [|12$$3|]; + } + """); } [Fact] public void OnPropertyExpressionBody2() { TestSpan( -@"class C -{ - public int Id $$=> [|123|]; -}"); + """ + class C + { + public int Id $$=> [|123|]; + } + """); } [Fact] public void OnPropertyExpressionBody3() { TestSpan( -@"class C -{ - $$public int Id => [|123|]; -}"); + """ + class C + { + $$public int Id => [|123|]; + } + """); } [Fact] public void OnPropertyExpressionBody4() { TestSpan( -@"class C -{ - public int Id => [|123|]; $$ -}"); + """ + class C + { + public int Id => [|123|]; $$ + } + """); } [Fact] public void OnIndexerExpressionBody1() { TestSpan( -@"class C -{ - public int this[int a] => [|12$$3|]; -}"); + """ + class C + { + public int this[int a] => [|12$$3|]; + } + """); } [Fact] public void OnIndexer1() { TestSpan( -@"class C -{ - int this[int$$ a] - { - get - [|{|] - } - - set - { - } - } -}"); + """ + class C + { + int this[int$$ a] + { + get + [|{|] + } + + set + { + } + } + } + """); } [Fact] public void OnIndexer2() { TestSpan( -@"class C -{ - int this[int$$ a] - { - [|get;|] - set { } - } -}"); + """ + class C + { + int this[int$$ a] + { + [|get;|] + set { } + } + } + """); } [Fact] public void OnIndexerExpressionBody2() { TestSpan( -@"class C -{ - public int this[int a] $$=> [|123|]; -}"); + """ + class C + { + public int this[int a] $$=> [|123|]; + } + """); } [Fact] public void OnIndexerExpressionBody3() { TestSpan( -@"class C -{ - $$public int this[int a] => [|123|]; -}"); + """ + class C + { + $$public int this[int a] => [|123|]; + } + """); } [Fact] public void OnIndexerExpressionBody4() { TestSpan( -@"class C -{ - public int this[int a] => [|123|]; $$ -}"); + """ + class C + { + public int this[int a] => [|123|]; $$ + } + """); } [Fact] public void OnIndexerExpressionBody5() { TestSpan( -@"class C -{ - public int this[int $$a] => [|123|]; -}"); + """ + class C + { + public int this[int $$a] => [|123|]; + } + """); } [Fact] public void OnMethod1() { TestSpan( -@"class C -{ - v$$oid Goo() - [|{|] - } -}"); + """ + class C + { + v$$oid Goo() + [|{|] + } + } + """); } [Fact] public void OnMethod2() { TestSpan( -@"class C -{ - void G$$oo() - [|{|] - } -}"); + """ + class C + { + void G$$oo() + [|{|] + } + } + """); } [Fact] public void OnMethod3() { TestSpan( -@"class C -{ - void Goo(in$$t i) - [|{|] - } -}"); + """ + class C + { + void Goo(in$$t i) + [|{|] + } + } + """); } [Fact] public void OnMethod4() { TestSpan( -@"class C -{ - void Goo(int $$i) - [|{|] - } -}"); + """ + class C + { + void Goo(int $$i) + [|{|] + } + } + """); } [Fact] public void OnMethod5() { TestSpan( -@"class C -{ - void Goo(int i = g$$oo) - [|{|] - } -}"); + """ + class C + { + void Goo(int i = g$$oo) + [|{|] + } + } + """); } [Fact] public void OnMethodWithExpressionBody1() { TestSpan( -@"class C -{ - v$$oid Goo() => [|123|]; -}"); + """ + class C + { + v$$oid Goo() => [|123|]; + } + """); } [Fact] public void OnMethodWithExpressionBody2() { TestSpan( -@"class C -{ - void Goo() =>$$ [|123|]; -}"); + """ + class C + { + void Goo() =>$$ [|123|]; + } + """); } [Fact] public void OnMethodWithExpressionBody3() { TestSpan( -@"class C -{ - void Goo() => [|123|]; $$ -}"); + """ + class C + { + void Goo() => [|123|]; $$ + } + """); } [Fact] public void OnMethodWithExpressionBody4() { TestSpan( -@"class C -{ - void Goo() => [|12$$3|]; -}"); + """ + class C + { + void Goo() => [|12$$3|]; + } + """); } [Fact] public void MissingOnMethod() { TestMissing( -@"class C -{ - void Goo($$); -}"); + """ + class C + { + void Goo($$); + } + """); } #region Constructors @@ -4271,10 +4813,12 @@ public void MissingOnMethod() public void InstanceConstructor_NoInitializer_BlockBody_All() { VerifyAllSpansInDeclaration( -@"class C -{ - [Attribute1, Attribute2][Attribute3][|$$public C()|] [|{|] [|}|] -}"); + """ + class C + { + [Attribute1, Attribute2][Attribute3][|$$public C()|] [|{|] [|}|] + } + """); } [Fact] @@ -4282,32 +4826,38 @@ public void InstanceConstructor_NoInitializer_BlockBody() { // a sequence point for base constructor call TestSpan( -@"class C -{ - [|pub$$lic C()|] - { - } -}"); + """ + class C + { + [|pub$$lic C()|] + { + } + } + """); } [Fact] public void InstanceConstructor_NoBody() { TestSpan( -@"class Class -{ - [|Cla$$ss()|] -}"); + """ + class Class + { + [|Cla$$ss()|] + } + """); } [Fact] public void InstanceConstructor_NoInitializer_ExpressionBody_All() { VerifyAllSpansInDeclaration( -@"class C -{ - [Attribute1, Attribute2][Attribute3][|$$public C()|] => [|x = 1|]; -}"); + """ + class C + { + [Attribute1, Attribute2][Attribute3][|$$public C()|] => [|x = 1|]; + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14438")] @@ -4315,10 +4865,12 @@ public void InstanceConstructor_NoInitializer_ExpressionBody1() { // a sequence point for base constructor call TestSpan( -@"class C -{ - [|pub$$lic C()|] => F(); -}"); + """ + class C + { + [|pub$$lic C()|] => F(); + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14438")] @@ -4326,10 +4878,12 @@ public void InstanceConstructor_NoInitializer_ExpressionBody2() { // a sequence point for base constructor call TestSpan( -@"class C -{ - [|public C()|] $$=> x = 1); -}"); + """ + class C + { + [|public C()|] $$=> x = 1); + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14438")] @@ -4337,10 +4891,12 @@ public void InstanceConstructor_NoInitializer_ExpressionBody3() { // a sequence point for base constructor call TestSpan( -@"class C -{ - public C() =$$> [|x = 1|]; -}"); + """ + class C + { + public C() =$$> [|x = 1|]; + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14438")] @@ -4348,56 +4904,66 @@ public void InstanceConstructor_NoInitializer_ExpressionBody4() { // a sequence point for base constructor call TestSpan( -@"class C -{ - public C() => [|$$x = 1|]; -}"); + """ + class C + { + public C() => [|$$x = 1|]; + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14438")] public void InstanceConstructor_NoInitializer_ExpressionBody5() { TestSpan( -@"class C -{ - public C() => [|x =$$ 1|]; -}"); + """ + class C + { + public C() => [|x =$$ 1|]; + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14438")] public void InstanceConstructor_NoInitializer_ExpressionBody6() { TestSpan( -@"class C -{ - public C() => [|x = 1|]$$; -}"); + """ + class C + { + public C() => [|x = 1|]$$; + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14438")] public void InstanceConstructor_NoInitializer_ExpressionBody7() { TestSpan( -@"class C -{ - public C() => [|x = 1|];$$ -}"); + """ + class C + { + public C() => [|x = 1|];$$ + } + """); } [Fact] public void InstanceConstructor_NoInitializer_Attributes() { TestSpan( -@"class C -{ - [Attribute1,$$ Attribute2] - [Attribute3] - [|public + """ + class C + { + [Attribute1,$$ Attribute2] + [Attribute3] + [|public - C()|] - { - } -}"); + C()|] + { + } + } + """); } [Theory, CombinatorialData] @@ -4550,10 +5116,12 @@ public void InstanceConstructor_Primary_ExplicitBaseInitializer_NoBreakpoint( public void InstanceConstructor_BaseInitializer_BlockBody_All() { VerifyAllSpansInDeclaration( -@"class C -{ - [Attribute1, Attribute2][Attribute3]$$public C() : [|base(42)|] [|{|][|}|] -}"); + """ + class C + { + [Attribute1, Attribute2][Attribute3]$$public C() : [|base(42)|] [|{|][|}|] + } + """); } [Fact] @@ -4561,23 +5129,27 @@ public void InstanceConstructor_BaseInitializer_BlockBody() { // a sequence point for base constructor call TestSpan( -@"class C -{ - pub$$lic C() - : [|base(42)|] - { - } -}"); + """ + class C + { + pub$$lic C() + : [|base(42)|] + { + } + } + """); } [Fact] public void InstanceConstructor_BaseInitializer_ExpressionBody_All() { VerifyAllSpansInDeclaration( -@"class C -{ - [Attribute1, Attribute2][Attribute3]$$public C() : [|base(42)|] => [|x = 1|]; -}"); + """ + class C + { + [Attribute1, Attribute2][Attribute3]$$public C() : [|base(42)|] => [|x = 1|]; + } + """); } [Fact] @@ -4585,11 +5157,13 @@ public void InstanceConstructor_BaseInitializer_ExpressionBody1() { // a sequence point for base constructor call TestSpan( -@"class C -{ - pub$$lic C() : [|base(42)|] => F(); - -}"); + """ + class C + { + pub$$lic C() : [|base(42)|] => F(); + + } + """); } [Fact] @@ -4597,11 +5171,13 @@ public void InstanceConstructor_BaseInitializer_ExpressionBody2() { // a sequence point for base constructor call TestSpan( -@"class C -{ - public C() : [|base(42)|] $$=> F(); - -}"); + """ + class C + { + public C() : [|base(42)|] $$=> F(); + + } + """); } [Fact] @@ -4609,11 +5185,13 @@ public void InstanceConstructor_BaseInitializer_ExpressionBody3() { // a sequence point for base constructor call TestSpan( -@"class C -{ - public C() : base(42) =$$> [|F()|]; - -}"); + """ + class C + { + public C() : base(42) =$$> [|F()|]; + + } + """); } [Fact] @@ -4621,11 +5199,13 @@ public void InstanceConstructor_BaseInitializer_ExpressionBody4() { // a sequence point for base constructor call TestSpan( -@"class C -{ - public C() : base(42) => [|$$F()|]; - -}"); + """ + class C + { + public C() : base(42) => [|$$F()|]; + + } + """); } [Fact] @@ -4633,65 +5213,77 @@ public void InstanceConstructor_ThisInitializer() { // a sequence point for this constructor call TestSpan( -@"class C -{ - pub$$lic C() - : [|this(42)|] - { - } -}"); + """ + class C + { + pub$$lic C() + : [|this(42)|] + { + } + } + """); } [Fact] public void StaticConstructor_BlockBody_All() { VerifyAllSpansInDeclaration( -@"class C -{ - [Attribute1, Attribute2][Attribute3]$$static public C() [|{|] [|}|] -}"); + """ + class C + { + [Attribute1, Attribute2][Attribute3]$$static public C() [|{|] [|}|] + } + """); } [Fact] public void StaticConstructor_BlockBody() { TestSpan( -@"class C -{ - $$static C() - [|{|] - } -}"); + """ + class C + { + $$static C() + [|{|] + } + } + """); } [Fact] public void StaticConstructor_ExpressionBody_All() { VerifyAllSpansInDeclaration( -@"class C -{ - [Attribute1, Attribute2][Attribute3]$$static public C() => [|x = 1|]; -}"); + """ + class C + { + [Attribute1, Attribute2][Attribute3]$$static public C() => [|x = 1|]; + } + """); } [Fact] public void StaticConstructor_ExpressionBody() { TestSpan( -@"class C -{ - static C() => [|$$F()|]; -}"); + """ + class C + { + static C() => [|$$F()|]; + } + """); } [Fact] public void StaticConstructor_NoBody() { TestMissing( -@"class Class -{ - static Cla$$ss() -}"); + """ + class Class + { + static Cla$$ss() + } + """); } [Fact] @@ -4699,13 +5291,15 @@ public void InstanceConstructorInitializer() { // a sequence point for this constructor call TestSpan( -@"class Derived : Base -{ - public Derived() - : [|this($$42)|] - { - } -}"); + """ + class Derived : Base + { + public Derived() + : [|this($$42)|] + { + } + } + """); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543968")] @@ -4713,26 +5307,29 @@ public void ConstructorInitializer() { // a sequence point for base constructor call TestSpan( -@"class Derived : Base -{ - public Derived() - : [|base($$42)|] - { - } -} -"); + """ + class Derived : Base + { + public Derived() + : [|base($$42)|] + { + } + } + """); } [Fact] public void OnStaticConstructor() { TestSpan( -@"class C -{ - st$$atic C() - [|{|] - } -}"); + """ + class C + { + st$$atic C() + [|{|] + } + } + """); } #endregion @@ -4741,589 +5338,688 @@ public void OnStaticConstructor() public void OnDestructor() { TestSpan( -@"class C -{ - ~C$$() - [|{|] - } -}"); + """ + class C + { + ~C$$() + [|{|] + } + } + """); } [Fact] public void OnOperator() { TestSpan( -@"class C -{ - public static int op$$erator+(C c1, C c2) - [|{|] - } -}"); + """ + class C + { + public static int op$$erator+(C c1, C c2) + [|{|] + } + } + """); } [Fact] public void OnOperatorWithExpressionBody1() { TestSpan( -@"class C -{ - public static int op$$erator+(C c1, C c2) => [|c1|]; -}"); + """ + class C + { + public static int op$$erator+(C c1, C c2) => [|c1|]; + } + """); } [Fact] public void OnOperatorWithExpressionBody2() { TestSpan( -@"class C -{ - public static int operator+(C c1, C c2) =>$$ [|c1|]; -}"); + """ + class C + { + public static int operator+(C c1, C c2) =>$$ [|c1|]; + } + """); } [Fact] public void OnOperatorWithExpressionBody3() { TestSpan( -@"class C -{ - public static int operator+(C c1, C c2) => [|c1|]; $$ -}"); + """ + class C + { + public static int operator+(C c1, C c2) => [|c1|]; $$ + } + """); } [Fact] public void OnOperatorWithExpressionBody4() { TestSpan( -@"class C -{ - public static int operator+(C c1, C c2) => [|c$$1|]; -}"); + """ + class C + { + public static int operator+(C c1, C c2) => [|c$$1|]; + } + """); } [Fact] public void OnConversionOperator() { TestSpan( -@"class C -{ - public static op$$erator DateTime(C c1) - [|{|] - } -}"); + """ + class C + { + public static op$$erator DateTime(C c1) + [|{|] + } + } + """); } [Fact] public void OnConversionOperatorWithExpressionBody1() { TestSpan( -@"class C -{ - public static op$$erator DateTime(C c1) => [|DataTime.Now|]; -}"); + """ + class C + { + public static op$$erator DateTime(C c1) => [|DataTime.Now|]; + } + """); } [Fact] public void OnConversionOperatorWithExpressionBody2() { TestSpan( -@"class C -{ - public static operator DateTime(C c1) =>$$ [|DataTime.Now|]; -}"); + """ + class C + { + public static operator DateTime(C c1) =>$$ [|DataTime.Now|]; + } + """); } [Fact] public void OnConversionOperatorWithExpressionBody3() { TestSpan( -@"class C -{ - public static operator DateTime(C c1) => [|DataTime.Now|];$$ -}"); + """ + class C + { + public static operator DateTime(C c1) => [|DataTime.Now|];$$ + } + """); } [Fact] public void OnConversionOperatorWithExpressionBody4() { TestSpan( -@"class C -{ - public static operator DateTime(C c1) => [|DataTime$$.Now|]; -}"); + """ + class C + { + public static operator DateTime(C c1) => [|DataTime$$.Now|]; + } + """); } [Fact, WorkItem(3557, "DevDiv_Projects/Roslyn")] public void InFrontOfAttribute() { TestSpan( -@"class C -{ -$$ [method: Obsolete] - void Goo() - [|{|] - } -}"); + """ + class C + { + $$ [method: Obsolete] + void Goo() + [|{|] + } + } + """); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538058")] public void InInactivePPRegion() { TestLine( -@" - -#if blahblah -$$gooby -#endif"); + """ + #if blahblah + $$gooby + #endif + """); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538777")] public void WithIncompleteDeclaration() { TestMissing( -@" -clas C -{ - void Goo() - { -$$ int - } -}"); + """ + clas C + { + void Goo() + { + $$ int + } + } + """); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/937290")] public void OnGetter() { TestSpan( -@"class C -{ - public int $$Id { [|get;|] set; } -}"); + """ + class C + { + public int $$Id { [|get;|] set; } + } + """); TestSpan( -@"class C -{ - public int Id { [|g$$et;|] set; } -}"); + """ + class C + { + public int Id { [|g$$et;|] set; } + } + """); TestSpan( -@"class C -{ - public int Id { g$$et [|{|] return 42; } set {} } -}"); + """ + class C + { + public int Id { g$$et [|{|] return 42; } set {} } + } + """); TestSpan( -@"class C -{ - public int$$ Id { get [|{|] return 42; } set {} } -}"); + """ + class C + { + public int$$ Id { get [|{|] return 42; } set {} } + } + """); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/937290")] public void OnSetter() { TestSpan( -@"class C -{ - public int Id { get; [|se$$t;|] } -}"); + """ + class C + { + public int Id { get; [|se$$t;|] } + } + """); TestSpan( -@"class C -{ - public int Id { get; [|set;|] $$ } -}"); + """ + class C + { + public int Id { get; [|set;|] $$ } + } + """); TestSpan( -@"class C -{ - public int $$Id { [|set;|] get; } -}"); + """ + class C + { + public int $$Id { [|set;|] get; } + } + """); TestSpan( -@"class C -{ - public int Id { get { return 42; } s$$et [|{|] } } -}"); + """ + class C + { + public int Id { get { return 42; } s$$et [|{|] } } + } + """); TestSpan( -@"class C -{ - public int Id { get { return 42; } set { [|}|] $$} -}"); + """ + class C + { + public int Id { get { return 42; } set { [|}|] $$} + } + """); } [Fact] public void WhenClause_1() { TestSpan( -@"class C -{ - string s; - bool b; - void Goo() - { - switch (s) - { -$$ case string s [|when b|]: - break; - } - } -}"); + """ + class C + { + string s; + bool b; + void Goo() + { + switch (s) + { + $$ case string s [|when b|]: + break; + } + } + } + """); } [Fact] public void WhenClause_2() { TestSpan( -@"class C -{ - string s; - bool b; - void Goo() - { - switch (s) - { - case string s [|whe$$n b|]: - break; - } - } -}"); + """ + class C + { + string s; + bool b; + void Goo() + { + switch (s) + { + case string s [|whe$$n b|]: + break; + } + } + } + """); } [Fact] public void WhenClause_3() { TestSpan( -@"class C -{ - string s; - bool b; - void Goo() - { - switch (s) - { - case string s [|when b|]:$$ - break; - } - } -}"); + """ + class C + { + string s; + bool b; + void Goo() + { + switch (s) + { + case string s [|when b|]:$$ + break; + } + } + } + """); } [Fact] public void PatternSwitchCase_1() { TestSpan( -@"class C -{ - string s; - bool b; - void Goo() - { - switch (s) - { -$$ case string s: - default: - [|break;|] - } - } -}"); + """ + class C + { + string s; + bool b; + void Goo() + { + switch (s) + { + $$ case string s: + default: + [|break;|] + } + } + } + """); } [Fact] public void PatternSwitchCase_2() { TestSpan( -@"class C -{ - string s; - bool b; - void Goo() - { - switch (s) - { - $$case string s: - default: - [|break;|] - } - } -}"); + """ + class C + { + string s; + bool b; + void Goo() + { + switch (s) + { + $$case string s: + default: + [|break;|] + } + } + } + """); } [Fact] public void PatternSwitchCase_3() { TestSpan( -@"class C -{ - string s; - bool b; - void Goo() - { - switch (s) - { - case string s:$$ - default: - [|break;|] - } - } -}"); + """ + class C + { + string s; + bool b; + void Goo() + { + switch (s) + { + case string s:$$ + default: + [|break;|] + } + } + } + """); } [Fact] public void DeconstructionDeclarationStatement_1() { TestSpan( -@"class C -{ - void Goo() - { -$$ [|var (x, y) = (1, 2);|] - } -}"); + """ + class C + { + void Goo() + { + $$ [|var (x, y) = (1, 2);|] + } + } + """); } [Fact] public void DeconstructionDeclarationStatement_2() { TestSpan( -@"class C -{ - void Goo() - { - [|var (x, y) = $$(1, 2);|] - } -}"); + """ + class C + { + void Goo() + { + [|var (x, y) = $$(1, 2);|] + } + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14438")] public void OnAccessorExpressionBody1() { TestSpan( -@"class C -{ - public int Id { get => [|12$$3|]; } -}"); + """ + class C + { + public int Id { get => [|12$$3|]; } + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14438")] public void OnAccessorExpressionBody2() { TestSpan( -@"class C -{ - public int Id { get $$=> [|123|]; } -}"); + """ + class C + { + public int Id { get $$=> [|123|]; } + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14438")] public void OnAccessorExpressionBody3() { TestSpan( -@"class C -{ - $$public int Id { get => [|123|]; } -}"); + """ + class C + { + $$public int Id { get => [|123|]; } + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14438")] public void OnAccessorExpressionBody4() { TestSpan( -@"class C -{ - public int Id { get => [|123|]; $$ } -}"); + """ + class C + { + public int Id { get => [|123|]; $$ } + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14438")] public void OnAccessorExpressionBody5() { TestSpan( -@"class C -{ -$$ public event Action Goo { add => [|123|]; remove => 456; } -}"); + """ + class C + { + $$ public event Action Goo { add => [|123|]; remove => 456; } + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14438")] public void OnAccessorExpressionBody6() { TestSpan( -@"class C -{ - public event Action Goo { add => [|123|];$$ remove => 456; } -}"); + """ + class C + { + public event Action Goo { add => [|123|];$$ remove => 456; } + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14438")] public void OnAccessorExpressionBody7() { TestSpan( -@"class C -{ - public event Action Goo { add => 123; $$remove => [|456|]; } -}"); + """ + class C + { + public event Action Goo { add => 123; $$remove => [|456|]; } + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14438")] public void OnAccessorExpressionBody8() { TestSpan( -@"class C -{ - public event Action Goo { add => 123; remove => [|456|]; }$$ -}"); + """ + class C + { + public event Action Goo { add => 123; remove => [|456|]; }$$ + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14438")] public void OnDtorExpressionBody1() { TestSpan( -@"class C -{ -$$ public ~C() => [|x = 1|]; -}"); + """ + class C + { + $$ public ~C() => [|x = 1|]; + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14438")] public void OnDtorExpressionBody2() { TestSpan( -@"class C -{ - public ~C() => $$[|x = 1|]; -}"); + """ + class C + { + public ~C() => $$[|x = 1|]; + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14438")] public void OnDtorExpressionBody3() { TestSpan( -@"class C -{ - public ~C() => [|x =$$ 1|]; -}"); + """ + class C + { + public ~C() => [|x =$$ 1|]; + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14438")] public void OnDtorExpressionBody4() { TestSpan( -@"class C -{ - public ~C() => [|x = 1|]$$; -}"); + """ + class C + { + public ~C() => [|x = 1|]$$; + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14438")] public void OnDtorExpressionBody5() { TestSpan( -@"class C -{ - public ~C() => [|x = 1|];$$ -}"); + """ + class C + { + public ~C() => [|x = 1|];$$ + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14437")] public void OnLocalFunctionDecl_1() { TestSpan( -@"class C -{ - static void M() - { -$$ int Local(object[] a) - [|{|] - return a.Length; - } - } -}"); + """ + class C + { + static void M() + { + $$ int Local(object[] a) + [|{|] + return a.Length; + } + } + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14437")] public void OnLocalFunctionDecl_2() { TestSpan( -@"class C -{ - static void M() - { - int Local(object[] a)$$ - [|{|] - return a.Length; - } - } -}"); + """ + class C + { + static void M() + { + int Local(object[] a)$$ + [|{|] + return a.Length; + } + } + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14437")] public void OnLocalFunctionDecl_3() { TestSpan( -@"class C -{ - static void M() - { - int Local(object[] a) -$$ [|{|] - return a.Length; - } - } -}"); + """ + class C + { + static void M() + { + int Local(object[] a) + $$ [|{|] + return a.Length; + } + } + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14437")] public void OnLocalFunctionDecl_4() { TestSpan( -@"class C -{ - static void M() - { -$$ int Local(object[] a) => [|a.Length|]; - } -}"); + """ + class C + { + static void M() + { + $$ int Local(object[] a) => [|a.Length|]; + } + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14437")] public void OnLocalFunctionDecl_5() { TestSpan( -@"class C -{ - static void M() - { - int Local(object$$[] a) => [|a.Length|]; - } -}"); + """ + class C + { + static void M() + { + int Local(object$$[] a) => [|a.Length|]; + } + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14437")] public void OnLocalFunctionDecl_6() { TestSpan( -@"class C -{ - static void M() - { - int Local(object[] a) => [|a.Length|];$$ - } -}"); + """ + class C + { + static void M() + { + int Local(object[] a) => [|a.Length|];$$ + } + } + """); } [Fact, WorkItem("https://developercommunity.visualstudio.com/content/problem/98990/cant-set-breakpoint.html")] public void IncompleteExpressionStatement() { TestSpan( -@"class C -{ - void Goo() - { - [|$$aaa|] - } -}"); + """ + class C + { + void Goo() + { + [|$$aaa|] + } + } + """); } #region Top Level Statements @@ -5331,30 +6027,31 @@ void Goo() [Fact] public void TopLevelStatements() { - VerifyAllSpansInDeclaration(@" -$$[|int d = 5;|] -[|int a = 1|], [|b = 2|], [|c = 3|]; -for ([|int i = 0|], [|j = 1|], [|k = 2|]; [|i < 10|]; [|i++|], [|j++|], [|k--|]) - [|while (b > 0)|] - [|{|] - [|if (c < b)|] - try - [|{|] - [|System.Console.WriteLine(a);|] - [|}|] - [|catch (Exception e)|] - [|{|] - [|System.Console.WriteLine(e);|] - [|}|] - finally - [|{|] - [|}|] - else [|if (b < 10)|] - [|System.Console.WriteLine(b);|] - else - [|System.Console.WriteLine(c);|] - [|}|] -"); + VerifyAllSpansInDeclaration(""" + + $$[|int d = 5;|] + [|int a = 1|], [|b = 2|], [|c = 3|]; + for ([|int i = 0|], [|j = 1|], [|k = 2|]; [|i < 10|]; [|i++|], [|j++|], [|k--|]) + [|while (b > 0)|] + [|{|] + [|if (c < b)|] + try + [|{|] + [|System.Console.WriteLine(a);|] + [|}|] + [|catch (Exception e)|] + [|{|] + [|System.Console.WriteLine(e);|] + [|}|] + finally + [|{|] + [|}|] + else [|if (b < 10)|] + [|System.Console.WriteLine(b);|] + else + [|System.Console.WriteLine(c);|] + [|}|] + """); } #endregion diff --git a/src/Features/CSharpTest/EditAndContinue/CSharpEditAndContinueAnalyzerTests.cs b/src/Features/CSharpTest/EditAndContinue/CSharpEditAndContinueAnalyzerTests.cs index 0e713bf62aaf2..046a9fd0a91c5 100644 --- a/src/Features/CSharpTest/EditAndContinue/CSharpEditAndContinueAnalyzerTests.cs +++ b/src/Features/CSharpTest/EditAndContinue/CSharpEditAndContinueAnalyzerTests.cs @@ -9,14 +9,13 @@ using System.Collections.Immutable; using System.IO; using System.Linq; -using System.Text; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.EditAndContinue; -using Microsoft.CodeAnalysis.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; @@ -130,136 +129,134 @@ private static async Task AnalyzeDocumentAsync( [Fact] public void ErrorSpans_TopLevel() { - var source = @" -/**/extern alias A;/**/ -/**/using Z = Goo.Bar;/**/ + TestSpans(""" + /**/extern alias A;/**/ + /**/using Z = Goo.Bar;/**/ -[assembly: /**/A(1,2,3,4)/**/, /**/B/**/] + [assembly: /**/A(1,2,3,4)/**/, /**/B/**/] -/**/namespace N.M/**/ { } + /**/namespace N.M/**/ { } -[A, B] -/**/struct S<[A]T>/**/ : B - /**/where T : new, struct/**/ { } + [A, B] + /**/struct S<[A]T>/**/ : B + /**/where T : new, struct/**/ { } -[A, B] -/**/public abstract partial class C/**/ { } + [A, B] + /**/public abstract partial class C/**/ { } -[A, B] -/**/public abstract partial record R/**/ { } + [A, B] + /**/public abstract partial record R/**/ { } -[A, B] -/**/public abstract partial record struct R/**/ { } + [A, B] + /**/public abstract partial record struct R/**/ { } -/**/interface I/**/ : J, K, L { } + /**/interface I/**/ : J, K, L { } -[A] -/**/enum E1/**/ { } + [A] + /**/enum E1/**/ { } -/**/enum E2/**/ : uint { } + /**/enum E2/**/ : uint { } -/**/public enum E3/**/ -{ - Q, - [A]R = 3 -} + /**/public enum E3/**/ + { + Q, + [A]R = 3 + } -[A] -/**/public delegate void D1()/**/ where T : struct; + [A] + /**/public delegate void D1()/**/ where T : struct; -/**/delegate C D2()/**/; + /**/delegate C D2()/**/; -[Attrib] -/**/public class Z/**/ -{ - /**/int f/**/; - [A]/**/int f = 1/**/; - /**/public static readonly int f/**/; + [Attrib] + /**/public class Z/**/ + { + /**/int f/**/; + [A]/**/int f = 1/**/; + /**/public static readonly int f/**/; - /**/int M1()/**/ { } - [A]/**/int M2()/**/ { } - [A]/**/int M3()/**/ where T1 : bar where T2 : baz { } + /**/int M1()/**/ { } + [A]/**/int M2()/**/ { } + [A]/**/int M3()/**/ where T1 : bar where T2 : baz { } - [A]/**/abstract C M4()/**/; - int M5([A]/**/Z d = 2345/**/, /**/ref int x/**/, /**/params int[] x/**/) { return 1; } + [A]/**/abstract C M4()/**/; + int M5([A]/**/Z d = 2345/**/, /**/ref int x/**/, /**/params int[] x/**/) { return 1; } - [A]/**/event A E1/**/; - [A]/**/public event A E2/**/; + [A]/**/event A E1/**/; + [A]/**/public event A E2/**/; - [A]/**/public abstract event A E3/**/ { /**/add/**/; /**/remove/**/; } - [A]/**/public abstract event A E4/**/ { [A, B]/**/add/**/ { } [A]/**/internal remove/**/ { } } + [A]/**/public abstract event A E3/**/ { /**/add/**/; /**/remove/**/; } + [A]/**/public abstract event A E4/**/ { [A, B]/**/add/**/ { } [A]/**/internal remove/**/ { } } - [A]/**/int P/**/ { get; set; } - [A]/**/internal string P/**/ { /**/internal get/**/ { } [A]/**/set/**/ { }} - - [A]/**/internal string this[int a, int b]/**/ { /**/get/**/ { } /**/set/**/ { } } - [A]/**/string this[[A]int a = 123]/**/ { get { } set { } } + [A]/**/int P/**/ { get; set; } + [A]/**/internal string P/**/ { /**/internal get/**/ { } [A]/**/set/**/ { }} - [A]/**/public static explicit operator int(Z d)/**/ { return 1; } - [A]/**/operator double(Z d)/**/ { return 1; } + [A]/**/internal string this[int a, int b]/**/ { /**/get/**/ { } /**/set/**/ { } } + [A]/**/string this[[A]int a = 123]/**/ { get { } set { } } - [A]/**/public static operator +(Z d, int x)/**/ { return 1; } - [A]/**/operator +(Z d, int x)/**/ { return 1; } - -} -"; - TestSpans(source, SyntaxComparer.TopLevel.HasLabel); + [A]/**/public static explicit operator int(Z d)/**/ { return 1; } + [A]/**/operator double(Z d)/**/ { return 1; } + + [A]/**/public static operator +(Z d, int x)/**/ { return 1; } + [A]/**/operator +(Z d, int x)/**/ { return 1; } + + } + """, SyntaxComparer.TopLevel.HasLabel); } [Fact] public void ErrorSpans_StatementLevel_Update() { - var source = @" -class C -{ - void M() - { - /**/{/**/} - /**/using (expr)/**/ {} - /**/fixed (int* a = expr)/**/ {} - /**/lock (expr)/**/ {} - /**/yield break;/**/ - /**/yield return 1;/**/ - /**/try/**/ {} catch { }; - try {} /**/catch/**/ { }; - try {} /**/finally/**/ { }; - /**/if (expr)/**/ { }; - if (expr) { } /**/else/**/ { }; - /**/while (expr)/**/ { }; - /**/do/**/ {} while (expr); - /**/for (;;)/**/ { }; - /**/foreach (var a in b)/**/ { }; - /**/switch (expr)/**/ { case 1: break; }; - switch (expr) { case 1: /**/goto case 1;/**/ }; - switch (expr) { case 1: /**/goto case default;/**/ }; - /**/label/**/: Goo(); - /**/checked/**/ { }; - /**/unchecked/**/ { }; - /**/unsafe/**/ { }; - /**/return expr;/**/ - /**/throw expr;/**/ - /**/break;/**/ - /**/continue;/**/ - /**/goto label;/**/ - /**/expr;/**/ - /**/int a;/**/ - F(/**/(x)/**/ => x); - F(/**/x/**/ => x); - F(/**/delegate/**/(x) { }); - F(from a in b /**/select/**/ a.x); - F(from a in b /**/let/**/ x = expr select expr); - F(from a in b /**/where/**/ expr select expr); - F(from a in b /**/join/**/ c in d on e equals f select g); - F(from a in b orderby /**/a/**/ select b); - F(from a in b orderby a, /**/b descending/**/ select b); - F(from a in b /**/group/**/ a by b select d); - } -} -"; // TODO: test // /**/F($$from a in b from c in d select a.x);/**/ // /**/F(from a in b $$from c in d select a.x);/**/ - TestSpans(source, SyntaxComparer.Statement.HasLabel); + TestSpans(""" + class C + { + void M() + { + /**/{/**/} + /**/using (expr)/**/ {} + /**/fixed (int* a = expr)/**/ {} + /**/lock (expr)/**/ {} + /**/yield break;/**/ + /**/yield return 1;/**/ + /**/try/**/ {} catch { }; + try {} /**/catch/**/ { }; + try {} /**/finally/**/ { }; + /**/if (expr)/**/ { }; + if (expr) { } /**/else/**/ { }; + /**/while (expr)/**/ { }; + /**/do/**/ {} while (expr); + /**/for (;;)/**/ { }; + /**/foreach (var a in b)/**/ { }; + /**/switch (expr)/**/ { case 1: break; }; + switch (expr) { case 1: /**/goto case 1;/**/ }; + switch (expr) { case 1: /**/goto case default;/**/ }; + /**/label/**/: Goo(); + /**/checked/**/ { }; + /**/unchecked/**/ { }; + /**/unsafe/**/ { }; + /**/return expr;/**/ + /**/throw expr;/**/ + /**/break;/**/ + /**/continue;/**/ + /**/goto label;/**/ + /**/expr;/**/ + /**/int a;/**/ + F(/**/(x)/**/ => x); + F(/**/x/**/ => x); + F(/**/delegate/**/(x) { }); + F(from a in b /**/select/**/ a.x); + F(from a in b /**/let/**/ x = expr select expr); + F(from a in b /**/where/**/ expr select expr); + F(from a in b /**/join/**/ c in d on e equals f select g); + F(from a in b orderby /**/a/**/ select b); + F(from a in b orderby a, /**/b descending/**/ select b); + F(from a in b /**/group/**/ a by b select d); + } + } + """, SyntaxComparer.Statement.HasLabel); } /// @@ -275,24 +272,24 @@ public void ErrorSpansAllKinds() [Fact] public async Task AnalyzeDocumentAsync_InsignificantChangesInMethodBody() { - var source1 = @" -class C -{ - public static void Main() - { - /* comment */ System.Console.WriteLine(1); - } -} -"; - var source2 = @" -class C -{ - public static void Main() - { - System.Console.WriteLine(1); - } -} -"; + var source1 = """ + class C + { + public static void Main() + { + /* comment */ System.Console.WriteLine(1); + } + } + """; + var source2 = """ + class C + { + public static void Main() + { + System.Console.WriteLine(1); + } + } + """; using var workspace = CreateWorkspace(); var oldSolution = AddDefaultTestProject(workspace.CurrentSolution, source1); @@ -315,7 +312,7 @@ public static void Main() var baseActiveStatements = new ActiveStatementsMap( ImmutableDictionary.CreateRange( [ - KeyValuePairUtil.Create(newDocument.FilePath, ImmutableArray.Create( + KeyValuePair.Create(newDocument.FilePath, ImmutableArray.Create( new ActiveStatement( new ActiveStatementId(0), ActiveStatementFlags.LeafFrame, @@ -342,24 +339,24 @@ public static void Main() [Fact] public async Task AnalyzeDocumentAsync_SyntaxError_Change() { - var source1 = @" -class C -{ - public static void Main() - { - System.Console.WriteLine(1) // syntax error - } -} -"; - var source2 = @" -class C -{ - public static void Main() - { - System.Console.WriteLine(2) // syntax error - } -} -"; + var source1 = """ + class C + { + public static void Main() + { + System.Console.WriteLine(1) // syntax error + } + } + """; + var source2 = """ + class C + { + public static void Main() + { + System.Console.WriteLine(2) // syntax error + } + } + """; using var workspace = CreateWorkspace(); var oldSolution = AddDefaultTestProject(workspace.CurrentSolution, source1); @@ -378,15 +375,15 @@ public static void Main() [Fact] public async Task AnalyzeDocumentAsync_SyntaxError_NoChange() { - var source = @" -class C -{ - public static void Main() - { - System.Console.WriteLine(1) // syntax error - } -} -"; + var source = """ + class C + { + public static void Main() + { + System.Console.WriteLine(1) // syntax error + } + } + """; using var workspace = CreateWorkspace(); var oldSolution = AddDefaultTestProject(workspace.CurrentSolution, source); @@ -403,24 +400,24 @@ public static void Main() [Fact] public async Task AnalyzeDocumentAsync_SyntaxError_NoChange2() { - var source1 = @" -class C -{ - public static void Main() - { - System.Console.WriteLine(1) // syntax error - } -} -"; - var source2 = @" -class C -{ - public static void Main() - { - System.Console.WriteLine(1) // syntax error - } -} -"; + var source1 = """ + class C + { + public static void Main() + { + System.Console.WriteLine(1) // syntax error + } + } + """; + var source2 = """ + class C + { + public static void Main() + { + System.Console.WriteLine(1) // syntax error + } + } + """; using var workspace = CreateWorkspace(); var oldSolution = AddDefaultTestProject(workspace.CurrentSolution, source1); @@ -440,15 +437,15 @@ public static void Main() [Fact] public async Task AnalyzeDocumentAsync_Features_NoChange() { - var source = @" -class C -{ - public static void Main() - { - System.Console.WriteLine(1); - } -} -"; + var source = """ + class C + { + public static void Main() + { + System.Console.WriteLine(1); + } + } + """; var experimentalFeatures = new Dictionary(); // no experimental features to enable var experimental = TestOptions.Regular.WithFeatures(experimentalFeatures); @@ -478,24 +475,24 @@ public async Task AnalyzeDocumentAsync_Features_Change() foreach (var feature in experimentalFeatures) { - var source1 = @" -class C -{ - public static void Main() - { - System.Console.WriteLine(1); - } -} -"; - var source2 = @" -class C -{ - public static void Main() - { - System.Console.WriteLine(2); - } -} -"; + var source1 = """ + class C + { + public static void Main() + { + System.Console.WriteLine(1); + } + } + """; + var source2 = """ + class C + { + public static void Main() + { + System.Console.WriteLine(2); + } + } + """; var featuresToEnable = new Dictionary() { { feature, "enabled" } }; var experimental = TestOptions.Regular.WithFeatures(featuresToEnable); @@ -522,16 +519,16 @@ public static void Main() [Fact] public async Task AnalyzeDocumentAsync_SemanticError_NoChange() { - var source = @" -class C -{ - public static void Main() - { - System.Console.WriteLine(1); - Bar(); // semantic error - } -} -"; + var source = """ + class C + { + public static void Main() + { + System.Console.WriteLine(1); + Bar(); // semantic error + } + } + """; using var workspace = CreateWorkspace(); var oldSolution = AddDefaultTestProject(workspace.CurrentSolution, source); @@ -550,26 +547,26 @@ public static void Main() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/10683")] public async Task AnalyzeDocumentAsync_SemanticErrorInMethodBody_Change() { - var source1 = @" -class C -{ - public static void Main() - { - System.Console.WriteLine(1); - Bar(); // semantic error - } -} -"; - var source2 = @" -class C -{ - public static void Main() - { - System.Console.WriteLine(2); - Bar(); // semantic error - } -} -"; + var source1 = """ + class C + { + public static void Main() + { + System.Console.WriteLine(1); + Bar(); // semantic error + } + } + """; + var source2 = """ + class C + { + public static void Main() + { + System.Console.WriteLine(2); + Bar(); // semantic error + } + } + """; using var workspace = CreateWorkspace(); var oldSolution = AddDefaultTestProject(workspace.CurrentSolution, source1); @@ -591,24 +588,24 @@ public static void Main() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/10683")] public async Task AnalyzeDocumentAsync_SemanticErrorInDeclaration_Change() { - var source1 = @" -class C -{ - public static void Main(Bar x) - { - System.Console.WriteLine(1); - } -} -"; - var source2 = @" -class C -{ - public static void Main(Bar x) - { - System.Console.WriteLine(2); - } -} -"; + var source1 = """ + class C + { + public static void Main(Bar x) + { + System.Console.WriteLine(1); + } + } + """; + var source2 = """ + class C + { + public static void Main(Bar x) + { + System.Console.WriteLine(2); + } + } + """; using var workspace = CreateWorkspace(); var oldSolution = AddDefaultTestProject(workspace.CurrentSolution, source1); @@ -631,25 +628,25 @@ public static void Main(Bar x) [Fact] public async Task AnalyzeDocumentAsync_AddingNewFileHavingRudeEdits() { - var source1 = @" -namespace N -{ - class C - { - public static void Main() - { - } - } -} -"; - var source2 = @" -namespace N -{ - public class D - { - } -} -"; + var source1 = """ + namespace N + { + class C + { + public static void Main() + { + } + } + } + """; + var source2 = """ + namespace N + { + public class D + { + } + } + """; using var workspace = CreateWorkspace(); var oldSolution = AddDefaultTestProject(workspace.CurrentSolution, source1); @@ -681,22 +678,22 @@ public class D [Fact] public async Task AnalyzeDocumentAsync_AddingNewFile() { - var source1 = @" -namespace N -{ - class C - { - public static void Main() - { - } - } -} -"; - var source2 = @" -class D -{ -} -"; + var source1 = """ + namespace N + { + class C + { + public static void Main() + { + } + } + } + """; + var source2 = """ + class D + { + } + """; using var workspace = CreateWorkspace(); var oldSolution = AddDefaultTestProject(workspace.CurrentSolution, source1); @@ -769,24 +766,24 @@ public async Task AnalyzeDocumentAsync_InternalError(bool outOfMemory) [Fact] public async Task AnalyzeDocumentAsync_NotSupportedByRuntime() { - var source1 = @" -class C -{ - public static void Main() - { - System.Console.WriteLine(1); - } -} -"; - var source2 = @" -class C -{ - public static void Main() - { - System.Console.WriteLine(2); - } -} -"; + var source1 = """ + class C + { + public static void Main() + { + System.Console.WriteLine(1); + } + } + """; + var source2 = """ + class C + { + public static void Main() + { + System.Console.WriteLine(2); + } + } + """; using var workspace = CreateWorkspace(); var oldSolution = AddDefaultTestProject(workspace.CurrentSolution, source1); diff --git a/src/Features/CSharpTest/EditAndContinue/Helpers/EditingTestBase.cs b/src/Features/CSharpTest/EditAndContinue/Helpers/EditingTestBase.cs index 4f4a3690aa25e..eadc7ab944ea9 100644 --- a/src/Features/CSharpTest/EditAndContinue/Helpers/EditingTestBase.cs +++ b/src/Features/CSharpTest/EditAndContinue/Helpers/EditingTestBase.cs @@ -24,18 +24,24 @@ public abstract class EditingTestBase : CSharpTestBase public static readonly string ReloadableAttributeDefSrc = "namespace System.Runtime.CompilerServices { class CreateNewOnMetadataUpdateAttribute : Attribute {} }"; - public static readonly string ReloadableAttributeSrc = $@" -using System.Runtime.CompilerServices; -{ReloadableAttributeDefSrc} -"; - - public static readonly string RestartRequiredOnMetadataUpdateAttributeDefSrc = @" -namespace System.Runtime.CompilerServices { class RestartRequiredOnMetadataUpdateAttribute : Attribute {} } -"; - - public static readonly string RestartRequiredOnMetadataUpdateAttributeSrc = $@" -using System.Runtime.CompilerServices; -{RestartRequiredOnMetadataUpdateAttributeDefSrc}"; + public static readonly string ReloadableAttributeSrc = $""" + + using System.Runtime.CompilerServices; + {ReloadableAttributeDefSrc} + + """; + + public static readonly string RestartRequiredOnMetadataUpdateAttributeDefSrc = """ + + namespace System.Runtime.CompilerServices { class RestartRequiredOnMetadataUpdateAttribute : Attribute {} } + + """; + + public static readonly string RestartRequiredOnMetadataUpdateAttributeSrc = $""" + + using System.Runtime.CompilerServices; + {RestartRequiredOnMetadataUpdateAttributeDefSrc} + """; internal enum MethodKind { diff --git a/src/Features/CSharpTest/EditAndContinue/LineEditTests.cs b/src/Features/CSharpTest/EditAndContinue/LineEditTests.cs index 0817d528c834e..84ac668be7143 100644 --- a/src/Features/CSharpTest/EditAndContinue/LineEditTests.cs +++ b/src/Features/CSharpTest/EditAndContinue/LineEditTests.cs @@ -7,9 +7,9 @@ using System; using System.Linq; +using Microsoft.CodeAnalysis.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.EditAndContinue; -using Microsoft.CodeAnalysis.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; @@ -25,13 +25,17 @@ public sealed class LineEditTests : EditingTestBase [Fact, WorkItem("https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1426286")] public void TopLevelCode_LineChange() { - var src1 = @" -Console.ReadLine(1); -"; - var src2 = @" + var src1 = """ + + Console.ReadLine(1); + + """; + var src2 = """ + + + Console.ReadLine(1); -Console.ReadLine(1); -"; + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(1, 2)]); @@ -40,19 +44,23 @@ public void TopLevelCode_LineChange() [Fact, WorkItem("https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1426286")] public void TopLevelCode_LocalFunction_LineChange() { - var src1 = @" -void F() -{ - Console.ReadLine(1); -} -"; - var src2 = @" -void F() -{ + var src1 = """ - Console.ReadLine(1); -} -"; + void F() + { + Console.ReadLine(1); + } + + """; + var src2 = """ + + void F() + { + + Console.ReadLine(1); + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(3, 4)]); @@ -65,33 +73,37 @@ void F() [Fact] public void Method_Reorder1() { - var src1 = @" -class C -{ - static void G() - { - Console.ReadLine(1); - } + var src1 = """ - static void F() - { - Console.ReadLine(2); - } -} -"; - var src2 = @" -class C -{ - static void F() - { - Console.ReadLine(2); - } + class C + { + static void G() + { + Console.ReadLine(1); + } - static void G() - { - Console.ReadLine(1); - } -}"; + static void F() + { + Console.ReadLine(2); + } + } + + """; + var src2 = """ + + class C + { + static void F() + { + Console.ReadLine(2); + } + + static void G() + { + Console.ReadLine(1); + } + } + """; var edits = GetTopEdits(src1, src2); // Consider: we could detect that the body of the method hasn't changed and avoid creating an update. @@ -107,44 +119,48 @@ static void G() [Fact] public void Method_Reorder2() { - var src1 = @" -class C -{ - static void Main() - { - F(); - G(); - } - - static int G() - { - return 1; - } + var src1 = """ - static int F() - { - return 2; - } -}"; - var src2 = @" -class C -{ - static int F() - { - return 1; - } + class C + { + static void Main() + { + F(); + G(); + } + + static int G() + { + return 1; + } + + static int F() + { + return 2; + } + } + """; + var src2 = """ + + class C + { + static int F() + { + return 1; + } - static void Main() - { - F(); - G(); - } + static void Main() + { + F(); + G(); + } - static int G() - { - return 2; - } -}"; + static int G() + { + return 2; + } + } + """; var edits = GetTopEdits(src1, src2); // Consider: we could detect that the body of the method hasn't changed and create line edits instead of an update. @@ -162,26 +178,30 @@ static int G() [Fact] public void Method_MultilineBreakpointSpans() { - var src1 = @" -class C -{ - void F() - { - var x = -1; - } -} -"; - var src2 = @" -class C -{ - void F() - { - var x = + var src1 = """ -1; - } -}"; + class C + { + void F() + { + var x = + 1; + } + } + + """; + var src2 = """ + + class C + { + void F() + { + var x = + + 1; + } + } + """; // We need to recompile the method since an active statement span [|var x = 1;|] // needs to be updated but can't be by a line update. var edits = GetTopEdits(src1, src2); @@ -193,25 +213,29 @@ void F() [Fact] public void Method_BlockBody_EntireBody1() { - var src1 = @" -class C -{ - static void Bar() - { - Console.ReadLine(2); - } -} -"; - var src2 = @" -class C -{ + var src1 = """ + class C + { + static void Bar() + { + Console.ReadLine(2); + } + } - static void Bar() - { - Console.ReadLine(2); - } -}"; + """; + var src2 = """ + + class C + { + + + static void Bar() + { + Console.ReadLine(2); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(4, 6)]); @@ -220,24 +244,28 @@ static void Bar() [Fact] public void Method_BlockBody_EntireBody2() { - var src1 = @" -class C -{ - static void Bar() - { - Console.ReadLine(2); - } -} -"; - var src2 = @" -class C -{ - static void Bar() + var src1 = """ - { - Console.ReadLine(2); - } -}"; + class C + { + static void Bar() + { + Console.ReadLine(2); + } + } + + """; + var src2 = """ + + class C + { + static void Bar() + + { + Console.ReadLine(2); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(4, 5)]); @@ -246,24 +274,28 @@ static void Bar() [Fact] public void Method_BlockBody1() { - var src1 = @" -class C -{ - static void Bar() - { - Console.ReadLine(2); - } -} -"; - var src2 = @" -class C -{ - static void Bar() - { + var src1 = """ - Console.ReadLine(2); - } -}"; + class C + { + static void Bar() + { + Console.ReadLine(2); + } + } + + """; + var src2 = """ + + class C + { + static void Bar() + { + + Console.ReadLine(2); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(5, 6)]); @@ -272,24 +304,28 @@ static void Bar() [Fact] public void Method_BlockBody2() { - var src1 = @" -class C -{ - static void Bar() - { + var src1 = """ - Console.ReadLine(2); - } -} -"; - var src2 = @" -class C -{ - static void Bar() - { - Console.ReadLine(2); - } -}"; + class C + { + static void Bar() + { + + Console.ReadLine(2); + } + } + + """; + var src2 = """ + + class C + { + static void Bar() + { + Console.ReadLine(2); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(6, 5)]); @@ -298,25 +334,29 @@ static void Bar() [Fact] public void Method_BlockBody3() { - var src1 = @" -class C -{ - static void Bar() - /*1*/ - { - Console.ReadLine(2); - } -} -"; - var src2 = @" -class C -{ - static void Bar() - { - /*2*/ - Console.ReadLine(2); - } -}"; + var src1 = """ + + class C + { + static void Bar() + /*1*/ + { + Console.ReadLine(2); + } + } + + """; + var src2 = """ + + class C + { + static void Bar() + { + /*2*/ + Console.ReadLine(2); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(5, 4)]); @@ -325,24 +365,28 @@ static void Bar() [Fact] public void Method_BlockBody4() { - var src1 = @" -class C -{ - static void Bar() - { - Console.ReadLine(2); - } -} -"; - var src2 = @" -class C -{ - static void Bar() - { - Console.ReadLine(2); + var src1 = """ - } -}"; + class C + { + static void Bar() + { + Console.ReadLine(2); + } + } + + """; + var src2 = """ + + class C + { + static void Bar() + { + Console.ReadLine(2); + + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(6, 7)]); @@ -351,30 +395,34 @@ static void Bar() [Fact] public void Method_BlockBody5() { - var src1 = @" -class C -{ - static void Bar() - { - if (F()) - { - Console.ReadLine(2); - } - } -} -"; - var src2 = @" -class C -{ - static void Bar() - { - if (F()) - { - Console.ReadLine(2); + var src1 = """ - } - } -}"; + class C + { + static void Bar() + { + if (F()) + { + Console.ReadLine(2); + } + } + } + + """; + var src2 = """ + + class C + { + static void Bar() + { + if (F()) + { + Console.ReadLine(2); + + } + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(8, 9)]); @@ -383,11 +431,15 @@ static void Bar() [Fact] public void Method_BlockBody_Recompile() { - var src1 = @" -class C { static void Bar() { } } -"; - var src2 = @" -class C { /*--*/static void Bar() { } }"; + var src1 = """ + + class C { static void Bar() { } } + + """; + var src2 = """ + + class C { /*--*/static void Bar() { } } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( @@ -398,21 +450,25 @@ class C { /*--*/static void Bar() { } }"; [Fact] public void Method_ExpressionBody_EntireBody() { - var src1 = @" -class C -{ - static int X() => 1; + var src1 = """ - static int Y() => 1; -} -"; - var src2 = @" -class C -{ + class C + { + static int X() => 1; + + static int Y() => 1; + } + + """; + var src2 = """ - static int X() => 1; - static int Y() => 1; -}"; + class C + { + + static int X() => 1; + static int Y() => 1; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [ @@ -424,23 +480,27 @@ class C [Fact] public void Method_Statement_Recompile1() { - var src1 = @" -class C -{ - static void Bar() - { - Console.ReadLine(2); - } -} -"; - var src2 = @" -class C -{ - static void Bar() - { - /**/Console.ReadLine(2); - } -}"; + var src1 = """ + + class C + { + static void Bar() + { + Console.ReadLine(2); + } + } + + """; + var src2 = """ + + class C + { + static void Bar() + { + /**/Console.ReadLine(2); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -450,27 +510,31 @@ static void Bar() [Fact] public void Method_Statement_Recompile2() { - var src1 = @" -class C -{ - static void Bar() - { - int a = 1; - int b = 2; - System.Console.WriteLine(1); - } -} -"; - var src2 = @" -class C -{ - static void Bar() - { - int a = 1; - int b = 2; - System.Console.WriteLine(1); - } -}"; + var src1 = """ + + class C + { + static void Bar() + { + int a = 1; + int b = 2; + System.Console.WriteLine(1); + } + } + + """; + var src2 = """ + + class C + { + static void Bar() + { + int a = 1; + int b = 2; + System.Console.WriteLine(1); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -487,24 +551,28 @@ static void Bar() [Fact] public void Method_GenericType_LineChange() { - var src1 = @" -class C -{ - static void Bar() - { - /*edit*/ - Console.ReadLine(2); - } -} -"; - var src2 = @" -class C -{ - static void Bar() - { - Console.ReadLine(2); - } -}"; + var src1 = """ + + class C + { + static void Bar() + { + /*edit*/ + Console.ReadLine(2); + } + } + + """; + var src2 = """ + + class C + { + static void Bar() + { + Console.ReadLine(2); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( @@ -514,23 +582,27 @@ static void Bar() [Fact] public void Method_GenericType_Recompile() { - var src1 = @" -class C -{ - static void Bar() - { -/******/Console.ReadLine(2); - } -} -"; - var src2 = @" -class C -{ - static void Bar() - { -/******//*edit*/Console.ReadLine(2); - } -}"; + var src1 = """ + + class C + { + static void Bar() + { + /******/Console.ReadLine(2); + } + } + + """; + var src2 = """ + + class C + { + static void Bar() + { + /******//*edit*/Console.ReadLine(2); + } + } + """; var edits = GetTopEdits(src1, src2); @@ -548,23 +620,27 @@ static void Bar() [Fact] public void Method_GenericMethod_Recompile() { - var src1 = @" -class C -{ - static void Bar() - { -/******//*edit*/Console.ReadLine(2); - } -} -"; - var src2 = @" -class C -{ - static void Bar() - { -/******/Console.ReadLine(2); - } -}"; + var src1 = """ + + class C + { + static void Bar() + { + /******//*edit*/Console.ReadLine(2); + } + } + + """; + var src2 = """ + + class C + { + static void Bar() + { + /******/Console.ReadLine(2); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( @@ -581,25 +657,29 @@ static void Bar() [Fact] public void Method_Async_Recompile() { - var src1 = @" -class C -{ - static async Task Bar() - { - Console.ReadLine(2); - } -} -"; - var src2 = @" -class C -{ - static async Task Bar() - { - Console.ReadLine( + var src1 = """ -2); - } -}"; + class C + { + static async Task Bar() + { + Console.ReadLine(2); + } + } + + """; + var src2 = """ + + class C + { + static async Task Bar() + { + Console.ReadLine( + + 2); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( @@ -610,24 +690,28 @@ static async Task Bar() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69027")] public void Method_StackAlloc_LineChange() { - var src1 = @" -class C -{ - void F() - { - Span x = stackalloc bool[64]; - } -} -"; - var src2 = @" -class C -{ - void F() - { + var src1 = """ - Span x = stackalloc bool[64]; - } -}"; + class C + { + void F() + { + Span x = stackalloc bool[64]; + } + } + + """; + var src2 = """ + + class C + { + void F() + { + + Span x = stackalloc bool[64]; + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( @@ -637,23 +721,27 @@ void F() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69027")] public void Method_StackAlloc_Recompile() { - var src1 = @" -class C -{ - void F() - { - Span x = stackalloc bool[64]; - } -} -"; - var src2 = @" -class C -{ - void F() - { - /**/Span x = stackalloc bool[64]; - } -}"; + var src1 = """ + + class C + { + void F() + { + Span x = stackalloc bool[64]; + } + } + + """; + var src2 = """ + + class C + { + void F() + { + /**/Span x = stackalloc bool[64]; + } + } + """; // TODO: https://github.com/dotnet/roslyn/issues/67307 // When we allow updating non-active bodies with stack alloc we will need to pass active statements to VerifyLineEdits @@ -672,23 +760,27 @@ void F() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69027")] public void Method_StackAlloc_NonActive() { - var src1 = @" -class C -{ - void F() - { - Span x = stackalloc bool[64]; - } -} -"; - var src2 = @" -class C -{ - void F() - { - /**/Span x = stackalloc bool[64]; - } -}"; + var src1 = """ + + class C + { + void F() + { + Span x = stackalloc bool[64]; + } + } + + """; + var src2 = """ + + class C + { + void F() + { + /**/Span x = stackalloc bool[64]; + } + } + """; // TODO: consider allowing change in non-active members var edits = GetTopEdits(src1, src2); @@ -700,28 +792,32 @@ void F() [Fact] public void Lambda_Recompile() { - var src1 = @" -class C -{ - void F() - { - var x = new System.Func( - () => 1 + var src1 = """ - ); - } -}"; - var src2 = @" -class C -{ - void F() - { - var x = new System.Func( - () => - 1 - ); - } -}"; + class C + { + void F() + { + var x = new System.Func( + () => 1 + + ); + } + } + """; + var src2 = """ + + class C + { + void F() + { + var x = new System.Func( + () => + 1 + ); + } + } + """; var edits = GetTopEdits(src1, src2); @@ -737,29 +833,33 @@ void F() [Fact] public void Constructor_Reorder() { - var src1 = @" -class C -{ - public C(int a) - { - } + var src1 = """ - public C(bool a) - { - } -} -"; - var src2 = @" -class C -{ - public C(bool a) - { - } + class C + { + public C(int a) + { + } - public C(int a) - { - } -}"; + public C(bool a) + { + } + } + + """; + var src2 = """ + + class C + { + public C(bool a) + { + } + + public C(int a) + { + } + } + """; var edits = GetTopEdits(src1, src2); // Consider: we could detect that the body of the method hasn't changed and avoid creating an update. @@ -778,21 +878,25 @@ public C(int a) [Fact] public void Constructor_ImplicitInitializer_BlockBody_LineChange() { - var src1 = @" -class C -{ - public C(int a) + var src1 = """ - {} -} -"; - var src2 = @" -class C -{ + class C + { + public C(int a) - public C(int a) - {} -}"; + {} + } + + """; + var src2 = """ + + class C + { + + public C(int a) + {} + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [ @@ -804,21 +908,25 @@ public C(int a) [Fact] public void Constructor_ImplicitInitializer_BlockBody_Recompile() { - var src1 = @" -class C -{ - public C(int a - ) - {} -} -"; - var src2 = @" -class C -{ - public C(int a - ) - {} -}"; + var src1 = """ + + class C + { + public C(int a + ) + {} + } + + """; + var src2 = """ + + class C + { + public C(int a + ) + {} + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -829,22 +937,26 @@ public C(int a [Fact] public void Constructor_ImplicitInitializer_ExpressionBodied_LineChange1() { - var src1 = @" -class C -{ - int _a; - public C(int a) => - _a = a; -} -"; - var src2 = @" -class C -{ - int _a; - public C(int a) => + var src1 = """ - _a = a; -}"; + class C + { + int _a; + public C(int a) => + _a = a; + } + + """; + var src2 = """ + + class C + { + int _a; + public C(int a) => + + _a = a; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(5, 6)]); @@ -853,22 +965,26 @@ public C(int a) => [Fact] public void Constructor_ImplicitInitializer_ExpressionBodied_LineChange2() { - var src1 = @" -class C -{ - int _a; - public C(int a) - => _a = a; -} -"; - var src2 = @" -class C -{ - int _a; - public C(int a) + var src1 = """ - => _a = a; -}"; + class C + { + int _a; + public C(int a) + => _a = a; + } + + """; + var src2 = """ + + class C + { + int _a; + public C(int a) + + => _a = a; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(5, 6)]); @@ -877,22 +993,26 @@ public C(int a) [Fact] public void Constructor_ImplicitInitializer_ExpressionBodied_LineChange3() { - var src1 = @" -class C -{ - int _a; - public C(int a) => - _a = a; -} -"; - var src2 = @" -class C -{ - int _a; - public C(int a) => + var src1 = """ + + class C + { + int _a; + public C(int a) => + _a = a; + } - _a = a; -}"; + """; + var src2 = """ + + class C + { + int _a; + public C(int a) => + + _a = a; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(5, 6)]); @@ -901,25 +1021,29 @@ public C(int a) => [Fact] public void Constructor_ImplicitInitializer_ExpressionBodied_LineChange4() { - var src1 = @" -class C -{ - int _a; - public C(int a) - => - _a = a; -} -"; - var src2 = @" -class C -{ - int _a; - public C(int a) - - => + var src1 = """ + + class C + { + int _a; + public C(int a) + => + _a = a; + } - _a = a; -}"; + """; + var src2 = """ + + class C + { + int _a; + public C(int a) + + => + + _a = a; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(6, 8)]); @@ -928,12 +1052,16 @@ public C(int a) [Fact] public void Constructor_ImplicitInitializer_Primary_LineChange() { - var src1 = @" -class C(int a); -"; - var src2 = @" -class - C(int a);"; + var src1 = """ + + class C(int a); + + """; + var src2 = """ + + class + C(int a); + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( @@ -945,12 +1073,16 @@ class C(int a); [Fact] public void Constructor_ImplicitInitializer_Primary_Recompile1() { - var src1 = @" -class C (int a); -"; - var src2 = @" -class C(int a); -"; + var src1 = """ + + class C (int a); + + """; + var src2 = """ + + class C(int a); + + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -961,12 +1093,16 @@ class C(int a); [Fact] public void Constructor_ImplicitInitializer_Primary_Recompile2() { - var src1 = @" -class C(int a); -"; - var src2 = @" -class C(int a ); -"; + var src1 = """ + + class C(int a); + + """; + var src2 = """ + + class C(int a ); + + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -977,12 +1113,16 @@ class C(int a ); [Fact] public void Constructor_ImplicitInitializer_PrimaryRecord_Recompile1() { - var src1 = @" -record C (int P); -"; - var src2 = @" -record C(int P); -"; + var src1 = """ + + record C (int P); + + """; + var src2 = """ + + record C(int P); + + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -996,12 +1136,16 @@ record C(int P); [Fact] public void Constructor_ImplicitInitializer_PrimaryRecord_Recompile2() { - var src1 = @" -record C(int P); -"; - var src2 = @" -record C(int P ); -"; + var src1 = """ + + record C(int P); + + """; + var src2 = """ + + record C(int P ); + + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -1015,12 +1159,16 @@ record C(int P ); [Fact] public void Constructor_ImplicitInitializer_PrimaryAndParameter_Recompile3() { - var src1 = @" -record C(int P); -"; - var src2 = @" -record C( int P); -"; + var src1 = """ + + record C(int P); + + """; + var src2 = """ + + record C( int P); + + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -1036,12 +1184,16 @@ record C( int P); [Fact] public void Constructor_ImplicitInitializer_PrimaryAndCopyCtorAndParameter_Recompile3() { - var src1 = @" -record C(int P); -"; - var src2 = @" -record C(int P); -"; + var src1 = """ + + record C(int P); + + """; + var src2 = """ + + record C(int P); + + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -1059,24 +1211,28 @@ record C(int P); [Fact] public void Constructor_ExplicitInitializer_BlockBody_LineChange1() { - var src1 = @" -class C -{ - public C(int a) - : base() - { - } -} -"; - var src2 = @" -class C -{ - public C(int a) + var src1 = """ - : base() - { - } -}"; + class C + { + public C(int a) + : base() + { + } + } + + """; + var src2 = """ + + class C + { + public C(int a) + + : base() + { + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(4, 5)]); @@ -1085,23 +1241,27 @@ public C(int a) [Fact] public void Constructor_ExplicitInitializer_BlockBody_Recompile() { - var src1 = @" -class C -{ - public C(int a) - : base() - { - } -} -"; - var src2 = @" -class C -{ - public C(int a) - : base() - { - } -}"; + var src1 = """ + + class C + { + public C(int a) + : base() + { + } + } + + """; + var src2 = """ + + class C + { + public C(int a) + : base() + { + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -1111,24 +1271,28 @@ public C(int a) [Fact] public void Constructor_ExplicitInitializer_BlockBody_PartialBodyLineChange1() { - var src1 = @" -class C -{ - public C(int a) - : base() - { - } -} -"; - var src2 = @" -class C -{ - public C(int a) - : base() + var src1 = """ - { - } -}"; + class C + { + public C(int a) + : base() + { + } + } + + """; + var src2 = """ + + class C + { + public C(int a) + : base() + + { + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new SourceLineUpdate[] { new(5, 6) }); @@ -1137,23 +1301,27 @@ public C(int a) [Fact] public void Constructor_ExplicitInitializer_BlockBody_RudeRecompile1() { - var src1 = @" -class C -{ - public C(int a) - : base() - { - } -} -"; - var src2 = @" -class C -{ - public C(int a) - : base() - { - } -}"; + var src1 = """ + + class C + { + public C(int a) + : base() + { + } + } + + """; + var src2 = """ + + class C + { + public C(int a) + : base() + { + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -1169,22 +1337,26 @@ public C(int a) [Fact] public void Constructor_ExplicitInitializer_ExpressionBodied_LineChange1() { - var src1 = @" -class C -{ - int _a; - public C(int a) - : base() => _a = a; -} -"; - var src2 = @" -class C -{ - int _a; - public C(int a) + var src1 = """ + + class C + { + int _a; + public C(int a) + : base() => _a = a; + } - : base() => _a = a; -}"; + """; + var src2 = """ + + class C + { + int _a; + public C(int a) + + : base() => _a = a; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(5, 6)]); @@ -1193,23 +1365,27 @@ public C(int a) [Fact] public void Constructor_ExplicitInitializer_ExpressionBodied_LineChange2() { - var src1 = @" -class C -{ - int _a; - public C(int a) - : base() => - _a = a; -} -"; - var src2 = @" -class C -{ - int _a; - public C(int a) + var src1 = """ + + class C + { + int _a; + public C(int a) + : base() => + _a = a; + } + + """; + var src2 = """ + + class C + { + int _a; + public C(int a) - : base() => _a = a; -}"; + : base() => _a = a; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new SourceLineUpdate[] { new(5, 6) }); @@ -1218,22 +1394,26 @@ public C(int a) [Fact] public void Constructor_ExplicitInitializer_ExpressionBodied_Recompile1() { - var src1 = @" -class C -{ - int _a; - public C(int a) - : base() => _a - = a; -} -"; - var src2 = @" -class C -{ - int _a; - public C(int a) - : base() => _a = a; -}"; + var src1 = """ + + class C + { + int _a; + public C(int a) + : base() => _a + = a; + } + + """; + var src2 = """ + + class C + { + int _a; + public C(int a) + : base() => _a = a; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -1247,22 +1427,26 @@ public C(int a) [Fact] public void Destructor_LineChange1() { - var src1 = @" -class C -{ - ~C() + var src1 = """ - { - } -} -"; - var src2 = @" -class C -{ - ~C() - { - } -}"; + class C + { + ~C() + + { + } + } + + """; + var src2 = """ + + class C + { + ~C() + { + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(5, 4)]); @@ -1271,18 +1455,22 @@ class C [Fact] public void Destructor_ExpressionBodied_LineChange1() { - var src1 = @" -class C -{ - ~C() => F(); -} -"; - var src2 = @" -class C -{ - ~C() => - F(); -}"; + var src1 = """ + + class C + { + ~C() => F(); + } + + """; + var src2 = """ + + class C + { + ~C() => + F(); + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(3, 4)]); @@ -1291,18 +1479,22 @@ class C [Fact] public void Destructor_ExpressionBodied_LineChange2() { - var src1 = @" -class C -{ - ~C() => F(); -} -"; - var src2 = @" -class C -{ - ~C() - => F(); -}"; + var src1 = """ + + class C + { + ~C() => F(); + } + + """; + var src2 = """ + + class C + { + ~C() + => F(); + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(3, 4)]); @@ -1315,18 +1507,22 @@ class C [Fact] public void ConstantField() { - var src1 = @" -class C -{ - const int Goo = 1; -} -"; - var src2 = @" -class C -{ - const int Goo = - 1; -}"; + var src1 = """ + + class C + { + const int Goo = 1; + } + + """; + var src2 = """ + + class C + { + const int Goo = + 1; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty()); @@ -1335,18 +1531,22 @@ class C [Fact] public void NoInitializer() { - var src1 = @" -class C -{ - int Goo; -} -"; - var src2 = @" -class C -{ - int - Goo; -}"; + var src1 = """ + + class C + { + int Goo; + } + + """; + var src2 = """ + + class C + { + int + Goo; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty()); @@ -1355,19 +1555,23 @@ class C [Fact] public void Field_Reorder() { - var src1 = @" -class C -{ - static int Goo = 1; - static int Bar = 2; -} -"; - var src2 = @" -class C -{ - static int Bar = 1; - static int Goo = 2; -}"; + var src1 = """ + + class C + { + static int Goo = 1; + static int Bar = 2; + } + + """; + var src2 = """ + + class C + { + static int Bar = 1; + static int Goo = 2; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -1378,20 +1582,24 @@ class C [Fact] public void Field_LineChange1() { - var src1 = @" -class C -{ - static int Goo = 1; -} -"; - var src2 = @" -class C -{ + var src1 = """ + + class C + { + static int Goo = 1; + } + + """; + var src2 = """ + + class C + { - static int Goo = 1; -}"; + static int Goo = 1; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(3, 6)]); @@ -1400,18 +1608,22 @@ class C [Fact] public void Field_LineChange2() { - var src1 = @" -class C -{ - int Goo = 1, Bar = 2; -} -"; - var src2 = @" -class C -{ - int Goo = 1, - Bar = 2; -}"; + var src1 = """ + + class C + { + int Goo = 1, Bar = 2; + } + + """; + var src2 = """ + + class C + { + int Goo = 1, + Bar = 2; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -1424,18 +1636,22 @@ class C [Fact] public void Field_LineChange3() { - var src1 = @" -class C -{ - [A]static int Goo = 1, Bar = 2; -} -"; - var src2 = @" -class C -{ - [A] - static int Goo = 1, Bar = 2; -}"; + var src1 = """ + + class C + { + [A]static int Goo = 1, Bar = 2; + } + + """; + var src2 = """ + + class C + { + [A] + static int Goo = 1, Bar = 2; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(3, 4)]); @@ -1444,20 +1660,24 @@ class C [Fact] public void Field_LineChange_Reloadable() { - var src1 = ReloadableAttributeSrc + @" -[CreateNewOnMetadataUpdate] -class C -{ - int Goo = 1, Bar = 2; -} -"; - var src2 = ReloadableAttributeSrc + @" -[CreateNewOnMetadataUpdate] -class C -{ - int Goo = 1, - Bar = 2; -}"; + var src1 = ReloadableAttributeSrc + """ + + [CreateNewOnMetadataUpdate] + class C + { + int Goo = 1, Bar = 2; + } + + """; + var src2 = ReloadableAttributeSrc + """ + + [CreateNewOnMetadataUpdate] + class C + { + int Goo = 1, + Bar = 2; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -1471,18 +1691,22 @@ class C [Fact] public void Field_Recompile1a() { - var src1 = @" -class C -{ - static int Goo = 1; -} -"; - var src2 = @" -class C -{ - static int Goo = - 1; -}"; + var src1 = """ + + class C + { + static int Goo = 1; + } + + """; + var src2 = """ + + class C + { + static int Goo = + 1; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -1495,18 +1719,22 @@ class C [Fact] public void Field_Recompile1b() { - var src1 = @" -class C -{ - static int Goo = 1; -} -"; - var src2 = @" -class C -{ - static int Goo - = 1; -}"; + var src1 = """ + + class C + { + static int Goo = 1; + } + + """; + var src2 = """ + + class C + { + static int Goo + = 1; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -1519,18 +1747,22 @@ static int Goo [Fact] public void Field_Recompile1c() { - var src1 = @" -class C -{ - static int Goo = 1; -} -"; - var src2 = @" -class C -{ - static int - Goo = 1; -}"; + var src1 = """ + + class C + { + static int Goo = 1; + } + + """; + var src2 = """ + + class C + { + static int + Goo = 1; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -1543,18 +1775,22 @@ static int [Fact] public void Field_Recompile1d() { - var src1 = @" -class C -{ - static int Goo = 1; -} -"; - var src2 = @" -class C -{ - static - int Goo = 1; -}"; + var src1 = """ + + class C + { + static int Goo = 1; + } + + """; + var src2 = """ + + class C + { + static + int Goo = 1; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -1567,18 +1803,22 @@ class C [Fact] public void Field_Recompile1e() { - var src1 = @" -class C -{ - static int Goo = 1; -} -"; - var src2 = @" -class C -{ - static int Goo = 1 - ; -}"; + var src1 = """ + + class C + { + static int Goo = 1; + } + + """; + var src2 = """ + + class C + { + static int Goo = 1 + ; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -1591,17 +1831,21 @@ class C [Fact] public void Field_Recompile2() { - var src1 = @" -class C -{ - static int Goo = 1 + 1; -} -"; - var src2 = @" -class C -{ - static int Goo = 1 + 1; -}"; + var src1 = """ + + class C + { + static int Goo = 1 + 1; + } + + """; + var src2 = """ + + class C + { + static int Goo = 1 + 1; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -1614,17 +1858,21 @@ class C [Fact] public void Field_RudeRecompile1() { - var src1 = @" -class C -{ - static int Goo = 1 + 1; -} -"; - var src2 = @" -class C -{ - static int Goo = 1 +/**/1; -}"; + var src1 = """ + + class C + { + static int Goo = 1 + 1; + } + + """; + var src2 = """ + + class C + { + static int Goo = 1 +/**/1; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( @@ -1644,19 +1892,23 @@ class C [Fact] public void Field_Generic_Reloadable() { - var src1 = ReloadableAttributeSrc + @" -[CreateNewOnMetadataUpdate] -class C -{ - static int Goo = 1 + 1; -} -"; - var src2 = ReloadableAttributeSrc + @" -[CreateNewOnMetadataUpdate] -class C -{ - static int Goo = 1 + 1; -}"; + var src1 = ReloadableAttributeSrc + """ + + [CreateNewOnMetadataUpdate] + class C + { + static int Goo = 1 + 1; + } + + """; + var src2 = ReloadableAttributeSrc + """ + + [CreateNewOnMetadataUpdate] + class C + { + static int Goo = 1 + 1; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -1673,19 +1925,23 @@ class C [Fact] public void Property1() - { - var src1 = @" -class C -{ - int P { get { return 1; } } -} -"; - var src2 = @" -class C -{ - int P { get { return - 1; } } -}"; + { + var src1 = """ + + class C + { + int P { get { return 1; } } + } + + """; + var src2 = """ + + class C + { + int P { get { return + 1; } } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -1695,18 +1951,22 @@ class C [Fact] public void Property2() { - var src1 = @" -class C -{ - int P { get { return 1; } } -} -"; - var src2 = @" -class C -{ - int P { get - { return 1; } } -}"; + var src1 = """ + + class C + { + int P { get { return 1; } } + } + + """; + var src2 = """ + + class C + { + int P { get + { return 1; } } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits([new SourceLineUpdate(3, 4)]); } @@ -1714,18 +1974,22 @@ int P { get [Fact] public void Property3() { - var src1 = @" -class C -{ - int P { get { return 1; } set { } } -} -"; - var src2 = @" -class C -{ - - int P { get { return 1; } set { } } -}"; + var src1 = """ + + class C + { + int P { get { return 1; } set { } } + } + + """; + var src2 = """ + + class C + { + + int P { get { return 1; } set { } } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(3, 4)]); @@ -1734,18 +1998,22 @@ class C [Fact] public void Property_ExpressionBody1() { - var src1 = @" -class C -{ - int P => 1; -} -"; - var src2 = @" -class C -{ - int P => - 1; -}"; + var src1 = """ + + class C + { + int P => 1; + } + + """; + var src2 = """ + + class C + { + int P => + 1; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(3, 4)]); @@ -1754,18 +2022,22 @@ class C [Fact] public void Property_GetterExpressionBody1() { - var src1 = @" -class C -{ - int P { get => 1; } -} -"; - var src2 = @" -class C -{ - int P { get => - 1; } -}"; + var src1 = """ + + class C + { + int P { get => 1; } + } + + """; + var src2 = """ + + class C + { + int P { get => + 1; } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(3, 4)]); @@ -1774,18 +2046,22 @@ class C [Fact] public void Property_SetterExpressionBody1() { - var src1 = @" -class C -{ - int P { set => F(); } -} -"; - var src2 = @" -class C -{ - int P { set => - F(); } -}"; + var src1 = """ + + class C + { + int P { set => F(); } + } + + """; + var src2 = """ + + class C + { + int P { set => + F(); } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(3, 4)]); @@ -1794,18 +2070,22 @@ class C [Fact] public void Property_Initializer1() { - var src1 = @" -class C -{ - int P { get; } = 1; -} -"; - var src2 = @" -class C -{ - int P { - get; } = 1; -}"; + var src1 = """ + + class C + { + int P { get; } = 1; + } + + """; + var src2 = """ + + class C + { + int P { + get; } = 1; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(3, 4)]); @@ -1814,18 +2094,22 @@ int P { [Fact] public void Property_Initializer2() { - var src1 = @" -class C -{ - int P { get; } = 1; -} -"; - var src2 = @" -class C -{ - int P { get; } = - 1; -}"; + var src1 = """ + + class C + { + int P { get; } = 1; + } + + """; + var src2 = """ + + class C + { + int P { get; } = + 1; + } + """; // We can only apply one delta per line, but that affects both getter and initializer. So we need to recompile one of them. var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( @@ -1836,19 +2120,23 @@ class C [Fact] public void Property_Initializer3() { - var src1 = @" -class C -{ - int P { get; } = 1; -} -"; - var src2 = @" -class C -{ - int P - { get; } = - 1; -}"; + var src1 = """ + + class C + { + int P { get; } = 1; + } + + """; + var src2 = """ + + class C + { + int P + { get; } = + 1; + } + """; // We can only apply one delta per line, but that affects both getter and initializer. So we need to recompile one of them. var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( @@ -1859,17 +2147,21 @@ int P [Fact] public void Property_Initializer4() { - var src1 = @" -class C -{ - int P { get; } = 1; -} -"; - var src2 = @" -class C -{ - int P { get; } = 1; -}"; + var src1 = """ + + class C + { + int P { get; } = 1; + } + + """; + var src2 = """ + + class C + { + int P { get; } = 1; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -1883,18 +2175,22 @@ class C [Fact] public void Indexer1() { - var src1 = @" -class C -{ - int this[int a] { get { return 1; } } -} -"; - var src2 = @" -class C -{ - int this[int a] { get { return - 1; } } -}"; + var src1 = """ + + class C + { + int this[int a] { get { return 1; } } + } + + """; + var src2 = """ + + class C + { + int this[int a] { get { return + 1; } } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty(), @@ -1904,18 +2200,22 @@ class C [Fact] public void Indexer2() { - var src1 = @" -class C -{ - int this[int a] { get { return 1; } } -} -"; - var src2 = @" -class C -{ - int this[int a] { get - { return 1; } } -}"; + var src1 = """ + + class C + { + int this[int a] { get { return 1; } } + } + + """; + var src2 = """ + + class C + { + int this[int a] { get + { return 1; } } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits([new SourceLineUpdate(3, 4)]); } @@ -1923,18 +2223,22 @@ int this[int a] { get [Fact] public void Indexer3() { - var src1 = @" -class C -{ - int this[int a] { get { return 1; } set { } } -} -"; - var src2 = @" -class C -{ - - int this[int a] { get { return 1; } set { } } -}"; + var src1 = """ + + class C + { + int this[int a] { get { return 1; } set { } } + } + + """; + var src2 = """ + + class C + { + + int this[int a] { get { return 1; } set { } } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits([new SourceLineUpdate(3, 4)]); } @@ -1942,18 +2246,22 @@ class C [Fact] public void Indexer_ExpressionBody1() { - var src1 = @" -class C -{ - int this[int a] => 1; -} -"; - var src2 = @" -class C -{ - int this[int a] => - 1; -}"; + var src1 = """ + + class C + { + int this[int a] => 1; + } + + """; + var src2 = """ + + class C + { + int this[int a] => + 1; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(3, 4)]); @@ -1962,18 +2270,22 @@ class C [Fact] public void Indexer_GetterExpressionBody1() { - var src1 = @" -class C -{ - int this[int a] { get => 1; } -} -"; - var src2 = @" -class C -{ - int this[int a] { get => - 1; } -}"; + var src1 = """ + + class C + { + int this[int a] { get => 1; } + } + + """; + var src2 = """ + + class C + { + int this[int a] { get => + 1; } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(3, 4)]); @@ -1982,18 +2294,22 @@ class C [Fact] public void Indexer_SetterExpressionBody1() { - var src1 = @" -class C -{ - int this[int a] { set => F(); } -} -"; - var src2 = @" -class C -{ - int this[int a] { set => - F(); } -}"; + var src1 = """ + + class C + { + int this[int a] { set => F(); } + } + + """; + var src2 = """ + + class C + { + int this[int a] { set => + F(); } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(3, 4)]); @@ -2006,18 +2322,22 @@ class C [Fact] public void Event_LineChange1() { - var src1 = @" -class C -{ - event Action E { add { } remove { } } -} -"; - var src2 = @" -class C -{ + var src1 = """ + + class C + { + event Action E { add { } remove { } } + } + + """; + var src2 = """ - event Action E { add { } remove { } } -}"; + class C + { + + event Action E { add { } remove { } } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(3, 4)]); @@ -2026,18 +2346,22 @@ event Action E { add { } remove { } } [Fact] public void Event_LineChange2() { - var src1 = @" -class C -{ - event Action E { add - { } remove { } } -} -"; - var src2 = @" -class C -{ - event Action E { add { } remove { } } -}"; + var src1 = """ + + class C + { + event Action E { add + { } remove { } } + } + + """; + var src2 = """ + + class C + { + event Action E { add { } remove { } } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(4, 3)]); @@ -2046,18 +2370,22 @@ event Action E { add { } remove { } } [Fact] public void Event_LineChange3() { - var src1 = @" -class C -{ - event Action E { add { - } remove { } } -} -"; - var src2 = @" -class C -{ - event Action E { add { } remove { } } -}"; + var src1 = """ + + class C + { + event Action E { add { + } remove { } } + } + + """; + var src2 = """ + + class C + { + event Action E { add { } remove { } } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(4, 3)]); @@ -2066,18 +2394,22 @@ event Action E { add { } remove { } } [Fact] public void Event_LineChange4() { - var src1 = @" -class C -{ - event Action E { add { } remove { - } } -} -"; - var src2 = @" -class C -{ - event Action E { add { } remove { } } -}"; + var src1 = """ + + class C + { + event Action E { add { } remove { + } } + } + + """; + var src2 = """ + + class C + { + event Action E { add { } remove { } } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(4, 3)]); @@ -2086,18 +2418,22 @@ event Action E { add { } remove { } } [Fact] public void Event_Recompile1() { - var src1 = @" -class C -{ - event Action E { add { } remove { } } -} -"; - var src2 = @" -class C -{ - event Action E { add { } remove - { } } -}"; + var src1 = """ + + class C + { + event Action E { add { } remove { } } + } + + """; + var src2 = """ + + class C + { + event Action E { add { } remove + { } } + } + """; // we can only apply one delta per line, but that would affect add and remove differently, so need to recompile var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( @@ -2108,18 +2444,22 @@ event Action E { add { } remove [Fact] public void Event_Recompile2() { - var src1 = @" -class C -{ - event Action E { add { } remove { } } -} -"; - var src2 = @" -class C -{ - event Action E { add { } remove { - } } -}"; + var src1 = """ + + class C + { + event Action E { add { } remove { } } + } + + """; + var src2 = """ + + class C + { + event Action E { add { } remove { + } } + } + """; // we can only apply one delta per line, but that would affect add and remove differently, so need to recompile var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( @@ -2130,19 +2470,23 @@ event Action E { add { } remove { [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53263")] public void Event_ExpressionBody_MultipleBodiesOnTheSameLine1() { - var src1 = @" -class C -{ - event Action E { add => F(); remove => F(); } -} -"; - var src2 = @" -class C -{ - event Action E { add => - F(); remove => - F(); } -}"; + var src1 = """ + + class C + { + event Action E { add => F(); remove => F(); } + } + + """; + var src2 = """ + + class C + { + event Action E { add => + F(); remove => + F(); } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(3, 4)], @@ -2152,19 +2496,23 @@ [new SourceLineUpdate(3, 4)], [Fact] public void Event_ExpressionBody() { - var src1 = @" -class C -{ - event Action E { add - => F(); remove - => F(); } -} -"; - var src2 = @" -class C -{ - event Action E { add => F(); remove => F(); } -}"; + var src1 = """ + + class C + { + event Action E { add + => F(); remove + => F(); } + } + + """; + var src2 = """ + + class C + { + event Action E { add => F(); remove => F(); } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [new SourceLineUpdate(4, 3), new SourceLineUpdate(5, 3)]); @@ -2177,32 +2525,36 @@ class C [Fact] public void Type_Reorder1() { - var src1 = @" -class C -{ - static int F1() => 1; - static int F2() => 1; -} + var src1 = """ -class D -{ - static int G1() => 1; - static int G2() => 1; -} -"; - var src2 = @" -class D -{ - static int G1() => 1; - static int G2() => 1; -} + class C + { + static int F1() => 1; + static int F2() => 1; + } -class C -{ - static int F1() => 1; - static int F2() => 1; -} -"; + class D + { + static int G1() => 1; + static int G2() => 1; + } + + """; + var src2 = """ + + class D + { + static int G1() => 1; + static int G2() => 1; + } + + class C + { + static int F1() => 1; + static int F2() => 1; + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( [ @@ -2219,30 +2571,34 @@ class C [Fact] public void LineMapping_ChangeLineNumber_WithinMethod_NoSequencePointImpact() { - var src1 = @" -class C -{ - static void F() - { - G( -#line 2 ""c"" - 123 -#line default - ); - } -}"; - var src2 = @" -class C -{ - static void F() - { - G( -#line 3 ""c"" - 123 -#line default - ); - } -}"; + var src1 = """ + + class C + { + static void F() + { + G( + #line 2 "c" + 123 + #line default + ); + } + } + """; + var src2 = """ + + class C + { + static void F() + { + G( + #line 3 "c" + 123 + #line default + ); + } + } + """; var edits = GetTopEdits(src1, src2); // Line deltas can't be applied on the whole breakpoint span hence recompilation. @@ -2257,43 +2613,47 @@ static void F() [Fact] public void LineMapping_ChangeLineNumber_OutsideOfMethod() { - var src1 = @" -#line 1 ""a"" -class C -{ - int x = 1; - static int y = 1; - void F1() { } - void F2() { } -} -class D -{ - public D() {} + var src1 = """ -#line 5 ""a"" - void F3() {} + #line 1 "a" + class C + { + int x = 1; + static int y = 1; + void F1() { } + void F2() { } + } + class D + { + public D() {} -#line 6 ""a"" - void F4() {} -}"; - var src2 = @" -#line 11 ""a"" -class C -{ - int x = 1; - static int y = 1; - void F1() { } - void F2() { } -} -class D -{ - public D() {} + #line 5 "a" + void F3() {} -#line 5 ""a"" - void F3() {} - void F4() {} -} -"; + #line 6 "a" + void F4() {} + } + """; + var src2 = """ + + #line 11 "a" + class C + { + int x = 1; + static int y = 1; + void F1() { } + void F2() { } + } + class D + { + public D() {} + + #line 5 "a" + void F3() {} + void F4() {} + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( @@ -2311,22 +2671,26 @@ void F4() {} [Fact] public void LineMapping_LineDirectivesAndWhitespace() { - var src1 = @" -class C -{ -#line 5 ""a"" -#line 6 ""a"" + var src1 = """ + class C + { + #line 5 "a" + #line 6 "a" - static void F() { } // line 9 -}"; - var src2 = @" -class C -{ -#line 9 ""a"" - static void F() { } -}"; + + static void F() { } // line 9 + } + """; + var src2 = """ + + class C + { + #line 9 "a" + static void F() { } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); @@ -2335,30 +2699,34 @@ static void F() { } [Fact] public void LineMapping_MultipleFiles() { - var src1 = @" -class C -{ - static void F() - { -#line 1 ""a"" - A(); -#line 1 ""b"" - B(); -#line default - } -}"; - var src2 = @" -class C -{ - static void F() - { -#line 2 ""a"" - A(); -#line 2 ""b"" - B(); -#line default - } -}"; + var src1 = """ + + class C + { + static void F() + { + #line 1 "a" + A(); + #line 1 "b" + B(); + #line default + } + } + """; + var src2 = """ + + class C + { + static void F() + { + #line 2 "a" + A(); + #line 2 "b" + B(); + #line default + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( @@ -2372,35 +2740,39 @@ static void F() [Fact] public void LineMapping_FileChange_Recompile() { - var src1 = @" -class C -{ - static void F() - { - A(); -#line 1 ""a"" - B(); -#line 3 ""a"" - C(); - } - + var src1 = """ - int x = 1; -}"; - var src2 = @" -class C -{ - static void F() - { - A(); -#line 1 ""b"" - B(); -#line 2 ""a"" - C(); - } + class C + { + static void F() + { + A(); + #line 1 "a" + B(); + #line 3 "a" + C(); + } + + + int x = 1; + } + """; + var src2 = """ + + class C + { + static void F() + { + A(); + #line 1 "b" + B(); + #line 2 "a" + C(); + } - int x = 1; -}"; + int x = 1; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( @@ -2417,13 +2789,17 @@ static void F() [Fact] public void LineMapping_FileChange_RudeEdit() { - var src1 = @" -#line 1 ""a"" -class C { static void F() { } } -"; - var src2 = @" -#line 1 ""b"" -class C { static void F() { } }"; + var src1 = """ + + #line 1 "a" + class C { static void F() { } } + + """; + var src2 = """ + + #line 1 "b" + class C { static void F() { } } + """; var edits = GetTopEdits(src1, src2); diff --git a/src/Features/CSharpTest/EditAndContinue/StatementEditingTests.cs b/src/Features/CSharpTest/EditAndContinue/StatementEditingTests.cs index 327f26d15b621..c86f90ebbc89e 100644 --- a/src/Features/CSharpTest/EditAndContinue/StatementEditingTests.cs +++ b/src/Features/CSharpTest/EditAndContinue/StatementEditingTests.cs @@ -19,31 +19,37 @@ namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests; [UseExportProvider] public sealed class StatementEditingTests : EditingTestBase { - private readonly string s_asyncIteratorStateMachineAttributeSource = @" -namespace System.Runtime.CompilerServices -{ - [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] - public sealed class AsyncIteratorStateMachineAttribute : StateMachineAttribute - { - public AsyncIteratorStateMachineAttribute(Type stateMachineType) - : base(stateMachineType) + private readonly string s_asyncIteratorStateMachineAttributeSource = """ + + namespace System.Runtime.CompilerServices { + [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] + public sealed class AsyncIteratorStateMachineAttribute : StateMachineAttribute + { + public AsyncIteratorStateMachineAttribute(Type stateMachineType) + : base(stateMachineType) + { + } + } } - } -} -"; + + """; #region Strings [Fact] public void StringLiteral_update() { - var src1 = @" -var x = ""Hello1""; -"; - var src2 = @" -var x = ""Hello2""; -"; + var src1 = """ + + var x = "Hello1"; + + """; + var src2 = """ + + var x = "Hello2"; + + """; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [x = \"Hello1\"]@8 -> [x = \"Hello2\"]@8"); @@ -52,12 +58,16 @@ public void StringLiteral_update() [Fact] public void InterpolatedStringText_update() { - var src1 = @" -var x = $""Hello1""; -"; - var src2 = @" -var x = $""Hello2""; -"; + var src1 = """ + + var x = $"Hello1"; + + """; + var src2 = """ + + var x = $"Hello2"; + + """; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [x = $\"Hello1\"]@8 -> [x = $\"Hello2\"]@8"); @@ -66,12 +76,16 @@ public void InterpolatedStringText_update() [Fact] public void Interpolation_update() { - var src1 = @" -var x = $""Hello{123}""; -"; - var src2 = @" -var x = $""Hello{124}""; -"; + var src1 = """ + + var x = $"Hello{123}"; + + """; + var src2 = """ + + var x = $"Hello{124}"; + + """; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [x = $\"Hello{123}\"]@8 -> [x = $\"Hello{124}\"]@8"); @@ -80,12 +94,16 @@ public void Interpolation_update() [Fact] public void InterpolationFormatClause_update() { - var src1 = @" -var x = $""Hello{123:N1}""; -"; - var src2 = @" -var x = $""Hello{123:N2}""; -"; + var src1 = """ + + var x = $"Hello{123:N1}"; + + """; + var src2 = """ + + var x = $"Hello{123:N2}"; + + """; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [x = $\"Hello{123:N1}\"]@8 -> [x = $\"Hello{123:N2}\"]@8"); @@ -125,14 +143,18 @@ public void VariableDeclaration_Update() [Fact] public void ParenthesizedVariableDeclaration_Update() { - var src1 = @" -var (x1, (x2, x3)) = (1, (2, true)); -var (a1, a2) = (1, () => { return 7; }); -"; - var src2 = @" -var (x1, (x2, x4)) = (1, (2, true)); -var (a1, a3) = (1, () => { return 8; }); -"; + var src1 = """ + + var (x1, (x2, x3)) = (1, (2, true)); + var (a1, a2) = (1, () => { return 7; }); + + """; + var src2 = """ + + var (x1, (x2, x4)) = (1, (2, true)); + var (a1, a3) = (1, () => { return 8; }); + + """; var edits = GetMethodEdits(src1, src2); @@ -368,20 +390,24 @@ public void Switch_Case_Update() [Fact] public void CasePatternLabel_UpdateDelete() { - var src1 = @" -switch(shape) -{ - case Point p: return 0; - case Circle c: return 1; -} -"; + var src1 = """ - var src2 = @" -switch(shape) -{ - case Circle circle: return 1; -} -"; + switch(shape) + { + case Point p: return 0; + case Circle c: return 1; + } + + """; + + var src2 = """ + + switch(shape) + { + case Circle circle: return 1; + } + + """; var edits = GetMethodEdits(src1, src2); @@ -401,16 +427,20 @@ public void CasePatternLabel_UpdateDelete() [Fact] public void MethodUpdate_UpdateSwitchExpression1() { - var src1 = @" -class C -{ - static int F(int a) => a switch { 0 => 0, _ => 1 }; -}"; - var src2 = @" -class C -{ - static int F(int a) => a switch { 0 => 0, _ => 2 }; -}"; + var src1 = """ + + class C + { + static int F(int a) => a switch { 0 => 0, _ => 1 }; + } + """; + var src2 = """ + + class C + { + static int F(int a) => a switch { 0 => 0, _ => 2 }; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) => a switch { 0 => 0, _ => 1 };]@18 -> [static int F(int a) => a switch { 0 => 0, _ => 2 };]@18"); @@ -421,16 +451,20 @@ class C [Fact] public void MethodUpdate_UpdateSwitchExpression2() { - var src1 = @" -class C -{ - static int F(int a) => a switch { 0 => 0, _ => 1 }; -}"; - var src2 = @" -class C -{ - static int F(int a) => a switch { 1 => 0, _ => 2 }; -}"; + var src1 = """ + + class C + { + static int F(int a) => a switch { 0 => 0, _ => 1 }; + } + """; + var src2 = """ + + class C + { + static int F(int a) => a switch { 1 => 0, _ => 2 }; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) => a switch { 0 => 0, _ => 1 };]@18 -> [static int F(int a) => a switch { 1 => 0, _ => 2 };]@18"); @@ -441,16 +475,20 @@ class C [Fact] public void MethodUpdate_UpdateSwitchExpression3() { - var src1 = @" -class C -{ - static int F(int a) => a switch { 0 => 0, _ => 1 }; -}"; - var src2 = @" -class C -{ - static int F(int a) => a switch { 0 => 0, 1 => 1, _ => 2 }; -}"; + var src1 = """ + + class C + { + static int F(int a) => a switch { 0 => 0, _ => 1 }; + } + """; + var src2 = """ + + class C + { + static int F(int a) => a switch { 0 => 0, 1 => 1, _ => 2 }; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) => a switch { 0 => 0, _ => 1 };]@18 -> [static int F(int a) => a switch { 0 => 0, 1 => 1, _ => 2 };]@18"); @@ -657,13 +695,17 @@ public void CatchFilterReorder2() [Fact] public void CatchInsertDelete() { - var src1 = @" -try { x++; } catch (E e) { /*1*/ } catch (Exception e) { /*2*/ } -try { Console.WriteLine(); } finally { /*3*/ }"; + var src1 = """ - var src2 = @" -try { x++; } catch (Exception e) { /*2*/ } -try { Console.WriteLine(); } catch (E e) { /*1*/ } finally { /*3*/ }"; + try { x++; } catch (E e) { /*1*/ } catch (Exception e) { /*2*/ } + try { Console.WriteLine(); } finally { /*3*/ } + """; + + var src2 = """ + + try { x++; } catch (Exception e) { /*2*/ } + try { Console.WriteLine(); } catch (E e) { /*1*/ } finally { /*3*/ } + """; var edits = GetMethodEdits(src1, src2); @@ -914,8 +956,10 @@ public void Block_Reorder() public void Block_AddLine() { var src1 = "{ x++; }"; - var src2 = @"{ // - x++; }"; + var src2 = """ + { // + x++; } + """; var edits = GetMethodEdits(src1, src2); @@ -1238,17 +1282,21 @@ public void Foreach_InsertHeader() [Fact] public void ForeachVariable_Update1() { - var src1 = @" -foreach (var (a1, a2) in e) { } -foreach ((var b1, var b2) in e) { } -foreach (var a in e1) { } -"; + var src1 = """ - var src2 = @" -foreach (var (a1, a3) in e) { } -foreach ((var b3, int b2) in e) { } -foreach (_ in e1) { } -"; + foreach (var (a1, a2) in e) { } + foreach ((var b1, var b2) in e) { } + foreach (var a in e1) { } + + """; + + var src2 = """ + + foreach (var (a1, a3) in e) { } + foreach ((var b3, int b2) in e) { } + foreach (_ in e1) { } + + """; var edits = GetMethodEdits(src1, src2); @@ -1262,15 +1310,19 @@ public void ForeachVariable_Update1() [Fact] public void ForeachVariable_Update2() { - var src1 = @" -foreach (_ in e2) { } -foreach (_ in e3) { A(); } -"; + var src1 = """ - var src2 = @" -foreach (var b in e2) { } -foreach (_ in e4) { A(); } -"; + foreach (_ in e2) { } + foreach (_ in e3) { A(); } + + """; + + var src2 = """ + + foreach (var b in e2) { } + foreach (_ in e4) { A(); } + + """; var edits = GetMethodEdits(src1, src2); @@ -1282,15 +1334,19 @@ public void ForeachVariable_Update2() [Fact] public void ForeachVariable_Insert() { - var src1 = @" -foreach (var (a3, a4) in e) { } -foreach ((var b4, var b5) in e) { } -"; + var src1 = """ - var src2 = @" -foreach (var (a3, a5, a4) in e) { } -foreach ((var b6, var b4, var b5) in e) { } -"; + foreach (var (a3, a4) in e) { } + foreach ((var b4, var b5) in e) { } + + """; + + var src2 = """ + + foreach (var (a3, a5, a4) in e) { } + foreach ((var b6, var b4, var b5) in e) { } + + """; var edits = GetMethodEdits(src1, src2); @@ -1304,15 +1360,19 @@ public void ForeachVariable_Insert() [Fact] public void ForeachVariable_Delete() { - var src1 = @" -foreach (var (a11, a12, a13) in e) { F(); } -foreach ((var b7, var b8, var b9) in e) { G(); } -"; + var src1 = """ - var src2 = @" -foreach (var (a12, a13) in e1) { F(); } -foreach ((var b7, var b9) in e) { G(); } -"; + foreach (var (a11, a12, a13) in e) { F(); } + foreach ((var b7, var b8, var b9) in e) { G(); } + + """; + + var src2 = """ + + foreach (var (a12, a13) in e1) { F(); } + foreach ((var b7, var b9) in e) { G(); } + + """; var edits = GetMethodEdits(src1, src2); @@ -1326,15 +1386,19 @@ public void ForeachVariable_Delete() [Fact] public void ForeachVariable_Reorder() { - var src1 = @" -foreach (var (a, b) in e1) { } -foreach ((var x, var y) in e2) { } -"; + var src1 = """ - var src2 = @" -foreach ((var x, var y) in e2) { } -foreach (var (a, b) in e1) { } -"; + foreach (var (a, b) in e1) { } + foreach ((var x, var y) in e2) { } + + """; + + var src2 = """ + + foreach ((var x, var y) in e2) { } + foreach (var (a, b) in e1) { } + + """; var edits = GetMethodEdits(src1, src2); @@ -1345,16 +1409,20 @@ public void ForeachVariable_Reorder() [Fact] public void ForeachVariableEmbedded_Reorder() { - var src1 = @" -foreach (var (a, b) in e1) { - foreach ((var x, var y) in e2) { } -} -"; + var src1 = """ + + foreach (var (a, b) in e1) { + foreach ((var x, var y) in e2) { } + } + + """; + + var src2 = """ + + foreach ((var x, var y) in e2) { } + foreach (var (a, b) in e1) { } - var src2 = @" -foreach ((var x, var y) in e2) { } -foreach (var (a, b) in e1) { } -"; + """; var edits = GetMethodEdits(src1, src2); @@ -2097,27 +2165,31 @@ public void Lambdas_InLambda_ChangeOnlyInLambdaBody() [Fact] public void Lambdas_Insert_First_Static() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - var f = new Func(a => a); - } -} -"; + class C + { + void F() + { + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + var f = new Func(a => a); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -2131,23 +2203,27 @@ void F() [Fact] public void Lambdas_Insert_First_Static_InGenericContext_Method() { - var src1 = @" -using System; -class C -{ - void F() - { - } -}"; - var src2 = @" -using System; -class C -{ - void F() - { - var f = new Func(a => a); - } -}"; + var src1 = """ + + using System; + class C + { + void F() + { + } + } + """; + var src2 = """ + + using System; + class C + { + void F() + { + var f = new Func(a => a); + } + } + """; var edits = GetTopEdits(src1, src2); @@ -2168,23 +2244,27 @@ void F() [Fact] public void Lambdas_Insert_First_Static_InGenericContext_Type() { - var src1 = @" -using System; -class C -{ - void F() - { - } -}"; - var src2 = @" -using System; -class C -{ - void F() - { - var f = new Func(a => a); - } -}"; + var src1 = """ + + using System; + class C + { + void F() + { + } + } + """; + var src2 = """ + + using System; + class C + { + void F() + { + var f = new Func(a => a); + } + } + """; var edits = GetTopEdits(src1, src2); @@ -2205,29 +2285,33 @@ void F() [Fact] public void Lambdas_Insert_First_Static_InGenericContext_LocalFunction() { - var src1 = @" -using System; -class C -{ - void F() - { - void L() - { - } - } -}"; - var src2 = @" -using System; -class C -{ - void F() - { - void L() - { - var f = new Func(a => a); - } - } -}"; + var src1 = """ + + using System; + class C + { + void F() + { + void L() + { + } + } + } + """; + var src2 = """ + + using System; + class C + { + void F() + { + void L() + { + var f = new Func(a => a); + } + } + } + """; var edits = GetTopEdits(src1, src2); @@ -2246,32 +2330,36 @@ void L() [Fact] public void Lambdas_Insert_Static_Nested() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static int G(Func f) => 0; + using System; - void F() - { - G(a => a); - } -} -"; - var src2 = @" -using System; + class C + { + static int G(Func f) => 0; -class C -{ - static int G(Func f) => 0; - - void F() - { - G(a => G(b => b) + a); - } -} -"; + void F() + { + G(a => a); + } + } + + """; + var src2 = """ + + using System; + + class C + { + static int G(Func f) => 0; + + void F() + { + G(a => G(b => b) + a); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -2285,34 +2373,38 @@ void F() [Fact] public void Lambdas_Insert_ThisOnly_Top1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int x = 0; - int G(Func f) => 0; + using System; - void F() - { + class C + { + int x = 0; + int G(Func f) => 0; - } -} -"; - var src2 = @" -using System; + void F() + { -class C -{ - int x = 0; - int G(Func f) => 0; - - void F() - { - G(a => x); - } -} -"; + } + } + + """; + var src2 = """ + + using System; + + class C + { + int x = 0; + int G(Func f) => 0; + + void F() + { + G(a => x); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -2323,39 +2415,43 @@ void F() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1291")] public void Lambdas_Insert_ThisOnly_Top2() { - var src1 = @" -using System; -using System.Linq; + var src1 = """ -class C -{ - void F() - { - int y = 1; - { - int x = 2; - var f1 = new Func(a => y); - } - } -} -"; - var src2 = @" -using System; -using System.Linq; + using System; + using System.Linq; -class C -{ - void F() - { - int y = 1; - { - int x = 2; - var f2 = from a in new[] { 1 } select a + y; - var f3 = from a in new[] { 1 } where x > 0 select a; - } - } -} -"; + class C + { + void F() + { + int y = 1; + { + int x = 2; + var f1 = new Func(a => y); + } + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + + class C + { + void F() + { + int y = 1; + { + int x = 2; + var f2 = from a in new[] { 1 } select a + y; + var f3 = from a in new[] { 1 } where x > 0 select a; + } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -2366,34 +2462,38 @@ void F() [Fact] public void Lambdas_Insert_ThisOnly_Nested1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int x = 0; - int G(Func f) => 0; + using System; - void F() - { - G(a => a); - } -} -"; - var src2 = @" -using System; + class C + { + int x = 0; + int G(Func f) => 0; -class C -{ - int x = 0; - int G(Func f) => 0; - - void F() - { - G(a => G(b => x)); - } -} -"; + void F() + { + G(a => a); + } + } + + """; + var src2 = """ + + using System; + + class C + { + int x = 0; + int G(Func f) => 0; + + void F() + { + G(a => G(b => x)); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -2404,53 +2504,57 @@ void F() [Fact] public void Lambdas_Insert_ThisOnly_Nested2() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int x = 0; + using System; - void F() - { - var f1 = new Func(a => - { - var f2 = new Func(b => + class C { - return b; - }); + int x = 0; - return a; - }); - } -} -"; - var src2 = @" -using System; + void F() + { + var f1 = new Func(a => + { + var f2 = new Func(b => + { + return b; + }); + + return a; + }); + } + } -class C -{ - int x = 0; - - void F() - { - var f1 = new Func(a => - { - var f2 = new Func(b => - { - return b; - }); + """; + var src2 = """ - var f3 = new Func(c => + using System; + + class C { - return c + x; - }); + int x = 0; + + void F() + { + var f1 = new Func(a => + { + var f2 = new Func(b => + { + return b; + }); + + var f3 = new Func(c => + { + return c + x; + }); + + return a; + }); + } + } - return a; - }); - } -} -"; + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -2461,32 +2565,36 @@ void F() [Fact] public void Lambdas_Insert_PrimaryParameterOnly_Top() { - var src1 = @" -using System; + var src1 = """ -class C(int x) -{ - int G(Func f) => 0; + using System; - void F() - { - - } -} -"; - var src2 = @" -using System; + class C(int x) + { + int G(Func f) => 0; -class C(int x) -{ - int G(Func f) => 0; - - void F() - { - G(a => x); - } -} -"; + void F() + { + + } + } + + """; + var src2 = """ + + using System; + + class C(int x) + { + int G(Func f) => 0; + + void F() + { + G(a => x); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -2497,49 +2605,53 @@ void F() [Fact] public void Lambdas_Insert_PrimaryParameterOnly_Nested() { - var src1 = @" -using System; + var src1 = """ -class C(int x) -{ - void F() - { - var f1 = new Func(a => - { - var f2 = new Func(b => + using System; + + class C(int x) { - return b; - }); + void F() + { + var f1 = new Func(a => + { + var f2 = new Func(b => + { + return b; + }); + + return a; + }); + } + } - return a; - }); - } -} -"; - var src2 = @" -using System; + """; + var src2 = """ -class C(int x) -{ - void F() - { - var f1 = new Func(a => - { - var f2 = new Func(b => - { - return b; - }); + using System; - var f3 = new Func(c => + class C(int x) { - return c + x; - }); + void F() + { + var f1 = new Func(a => + { + var f2 = new Func(b => + { + return b; + }); + + var f3 = new Func(c => + { + return c + x; + }); + + return a; + }); + } + } - return a; - }); - } -} -"; + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -2550,33 +2662,37 @@ void F() [Fact] public void Lambdas_Insert_ThisOnly_Second() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int x = 0; + using System; - void F() - { - var f1 = new Func(a => x); - } -} -"; - var src2 = @" -using System; + class C + { + int x = 0; -class C -{ - int x = 0; - - void F() - { - var f1 = new Func(a => x); - var f2 = new Func(b => x); - } -} -"; + void F() + { + var f1 = new Func(a => x); + } + } + + """; + var src2 = """ + + using System; + + class C + { + int x = 0; + + void F() + { + var f1 = new Func(a => x); + var f2 = new Func(b => x); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -2590,33 +2706,37 @@ void F() [Fact] public void Lambdas_Insert_ThisAndPrimaryParameter() { - var src1 = @" -using System; + var src1 = """ -class C(int y) -{ - int x = 0; + using System; - void F() - { - var f1 = new Func(a => x); - } -} -"; - var src2 = @" -using System; + class C(int y) + { + int x = 0; -class C(int y) -{ - int x = 0; - - void F() - { - var f1 = new Func(a => x); - var f2 = new Func(b => y); - } -} -"; + void F() + { + var f1 = new Func(a => x); + } + } + + """; + var src2 = """ + + using System; + + class C(int y) + { + int x = 0; + + void F() + { + var f1 = new Func(a => x); + var f2 = new Func(b => y); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -2630,31 +2750,35 @@ void F() [Fact] public void Lambdas_Insert_Closure_Second() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - int x = 1; - var f1 = new Func(a => x); - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - int x = 1; - var f1 = new Func(a => x); - var f2 = new Func(b => x); - } -} -"; + class C + { + void F() + { + int x = 1; + var f1 = new Func(a => x); + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + int x = 1; + var f1 = new Func(a => x); + var f2 = new Func(b => x); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -2668,69 +2792,73 @@ void F() [Fact] public void Lambdas_InsertAndDelete_Scopes1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void G(Func f) {} + using System; - int x = 0, y = 0; // Group #0 + class C + { + void G(Func f) {} - void F() - { - int x0 = 0, y0 = 0; // Group #1 - - { int x1 = 0, y1 = 0; // Group #2 - - { int x2 = 0, y2 = 0; // Group #1 - - { int x3 = 0, y3 = 0; // Group #2 - - G(a => x3 + x1); - G(b => x0 + y0 + x2); - G(c => x); + int x = 0, y = 0; // Group #0 + + void F() + { + int x0 = 0, y0 = 0; // Group #1 + + { int x1 = 0, y1 = 0; // Group #2 + + { int x2 = 0, y2 = 0; // Group #1 + + { int x3 = 0, y3 = 0; // Group #2 + + G(a => x3 + x1); + G(b => x0 + y0 + x2); + G(c => x); + } + } + } } } - } - } -} -"; - var src2 = @" -using System; -class C -{ - void G(Func f) {} + """; + var src2 = """ - int x = 0, y = 0; // Group #0 + using System; - void F() - { - int x0 = 0, y0 = 0; // Group #1 - - { int x1 = 0, y1 = 0; // Group #2 - - { int x2 = 0, y2 = 0; // Group #1 - - { int x3 = 0, y3 = 0; // Group #2 - - G(a => x3 + x1); - G(b => x0 + y0 + x2); - G(c => x); + class C + { + void G(Func f) {} - G(d => x); // OK - G(e => x0 + y0); // OK - G(f => x1 + y0); // runtime rude edit - connecting Group #1 and Group #2 - G(g => x3 + x1); // runtime rude edit - multi-scope (conservative) - G(h => x + y0); // runtime rude edit - connecting Group #0 and Group #1 - G(i => x + x3); // runtime rude edit - connecting Group #0 and Group #2 + int x = 0, y = 0; // Group #0 + + void F() + { + int x0 = 0, y0 = 0; // Group #1 + + { int x1 = 0, y1 = 0; // Group #2 + + { int x2 = 0, y2 = 0; // Group #1 + + { int x3 = 0, y3 = 0; // Group #2 + + G(a => x3 + x1); + G(b => x0 + y0 + x2); + G(c => x); + + G(d => x); // OK + G(e => x0 + y0); // OK + G(f => x1 + y0); // runtime rude edit - connecting Group #1 and Group #2 + G(g => x3 + x1); // runtime rude edit - multi-scope (conservative) + G(h => x + y0); // runtime rude edit - connecting Group #0 and Group #1 + G(i => x + x3); // runtime rude edit - connecting Group #0 and Group #2 + } + } + } } } - } - } -} -"; + + """; var insert = GetTopEdits(src1, src2); insert.VerifySemantics( @@ -2747,46 +2875,50 @@ void F() [Fact] public void Lambdas_Insert_ForEach1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void G(Func f) {} + using System; - void F() - { - foreach (int x0 in new[] { 1 }) // Group #0 - { // Group #1 - int x1 = 0; - - G(a => x0); - G(a => x1); - } - } -} -"; - var src2 = @" -using System; + class C + { + void G(Func f) {} + + void F() + { + foreach (int x0 in new[] { 1 }) // Group #0 + { // Group #1 + int x1 = 0; + + G(a => x0); + G(a => x1); + } + } + } -class C -{ - void G(Func f) {} + """; + var src2 = """ - void F() - { - foreach (int x0 in new[] { 1 }) // Group #0 - { // Group #1 - int x1 = 0; - - G(a => x0); - G(a => x1); + using System; - G(a => x0 + x1); // runtime rude edit: connecting previously disconnected closures - } - } -} -"; + class C + { + void G(Func f) {} + + void F() + { + foreach (int x0 in new[] { 1 }) // Group #0 + { // Group #1 + int x1 = 0; + + G(a => x0); + G(a => x1); + + G(a => x0 + x1); // runtime rude edit: connecting previously disconnected closures + } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -2797,36 +2929,40 @@ void F() [Fact] public void Lambdas_Insert_ForEach2() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void G(Func f1, Func f2, Func f3) {} + using System; - void F() - { - int x0 = 0; // Group #0 - foreach (int x1 in new[] { 1 }) // Group #1 - G(a => x0, a => x1, null); - } -} -"; - var src2 = @" -using System; + class C + { + void G(Func f1, Func f2, Func f3) {} -class C -{ - void G(Func f1, Func f2, Func f3) {} + void F() + { + int x0 = 0; // Group #0 + foreach (int x1 in new[] { 1 }) // Group #1 + G(a => x0, a => x1, null); + } + } - void F() - { - int x0 = 0; // Group #0 - foreach (int x1 in new[] { 1 }) // Group #1 - G(a => x0, a => x1, a => x0 + x1); // runtime rude edit: connecting previously disconnected closures - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + void G(Func f1, Func f2, Func f3) {} + + void F() + { + int x0 = 0; // Group #0 + foreach (int x1 in new[] { 1 }) // Group #1 + G(a => x0, a => x1, a => x0 + x1); // runtime rude edit: connecting previously disconnected closures + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -2837,43 +2973,47 @@ void F() [Fact] public void Lambdas_Insert_For1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - bool G(Func f) => true; + using System; - void F() - { - for (int x0 = 0, x1 = 0; G(a => x0) && G(a => x1);) - { - int x2 = 0; - G(a => x2); - } - } -} -"; - var src2 = @" -using System; + class C + { + bool G(Func f) => true; + + void F() + { + for (int x0 = 0, x1 = 0; G(a => x0) && G(a => x1);) + { + int x2 = 0; + G(a => x2); + } + } + } -class C -{ - bool G(Func f) => true; + """; + var src2 = """ - void F() - { - for (int x0 = 0, x1 = 0; G(a => x0) && G(a => x1);) - { - int x2 = 0; - G(a => x2); + using System; - G(a => x0 + x1); // ok - G(a => x0 + x2); // runtime rude edit: connecting previously disconnected closures - } - } -} -"; + class C + { + bool G(Func f) => true; + + void F() + { + for (int x0 = 0, x1 = 0; G(a => x0) && G(a => x1);) + { + int x2 = 0; + G(a => x2); + + G(a => x0 + x1); // ok + G(a => x0 + x2); // runtime rude edit: connecting previously disconnected closures + } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)], @@ -2883,71 +3023,75 @@ void F() [Fact] public void Lambdas_Insert_Switch1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - bool G(Func f) => true; + using System; - int a = 1; + class C + { + bool G(Func f) => true; + + int a = 1; + + void F() + { + int x2 = 1; + G(() => x2); + + switch (a) + { + case 1: + int x0 = 1; + G(() => x0); + break; + + case 2: + int x1 = 1; + G(() => x1); + break; + } + } + } - void F() - { - int x2 = 1; - G(() => x2); - - switch (a) - { - case 1: - int x0 = 1; - G(() => x0); - break; - - case 2: - int x1 = 1; - G(() => x1); - break; - } - } -} -"; - var src2 = @" -using System; + """; + var src2 = """ -class C -{ - bool G(Func f) => true; + using System; - int a = 1; + class C + { + bool G(Func f) => true; - void F() - { - int x2 = 1; - G(() => x2); - - switch (a) - { - case 1: - int x0 = 1; - G(() => x0); - goto case 2; - - case 2: - int x1 = 1; - G(() => x1); - goto default; - - default: - x0 = 1; - x1 = 2; - G(() => x0 + x1); // ok - G(() => x0 + x2); // runtime rude edit - break; - } - } -} -"; + int a = 1; + + void F() + { + int x2 = 1; + G(() => x2); + + switch (a) + { + case 1: + int x0 = 1; + G(() => x0); + goto case 2; + + case 2: + int x1 = 1; + G(() => x1); + goto default; + + default: + x0 = 1; + x1 = 2; + G(() => x0 + x1); // ok + G(() => x0 + x2); // runtime rude edit + break; + } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)], @@ -2957,55 +3101,59 @@ void F() [Fact] public void Lambdas_Insert_Using1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static bool G(Func f) => true; - static int H(object a, object b) => 1; - - static IDisposable D() => null; - - static void F() - { - using (IDisposable x0 = D(), y0 = D()) - { - int x1 = 1; - - G(() => x0); - G(() => y0); - G(() => x1); - } - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - static bool G(Func f) => true; - static int H(object a, object b) => 1; - - static IDisposable D() => null; - - static void F() - { - using (IDisposable x0 = D(), y0 = D()) - { - int x1 = 1; - - G(() => x0); - G(() => y0); - G(() => x1); + class C + { + static bool G(Func f) => true; + static int H(object a, object b) => 1; + + static IDisposable D() => null; + + static void F() + { + using (IDisposable x0 = D(), y0 = D()) + { + int x1 = 1; + + G(() => x0); + G(() => y0); + G(() => x1); + } + } + } - G(() => H(x0, y0)); // ok - G(() => H(x0, x1)); // runtime rude edit - } - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + static bool G(Func f) => true; + static int H(object a, object b) => 1; + + static IDisposable D() => null; + + static void F() + { + using (IDisposable x0 = D(), y0 = D()) + { + int x1 = 1; + + G(() => x0); + G(() => y0); + G(() => x1); + + G(() => H(x0, y0)); // ok + G(() => H(x0, x1)); // runtime rude edit + } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)], @@ -3015,53 +3163,57 @@ static void F() [Fact] public void Lambdas_Insert_Catch1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static bool G(Func f) => true; - static int H(object a, object b) => 1; - - static void F() - { - try - { - } - catch (Exception x0) - { - int x1 = 1; - G(() => x0); - G(() => x1); - } - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - static bool G(Func f) => true; - static int H(object a, object b) => 1; - - static void F() - { - try - { - } - catch (Exception x0) - { - int x1 = 1; - G(() => x0); - G(() => x1); + class C + { + static bool G(Func f) => true; + static int H(object a, object b) => 1; + + static void F() + { + try + { + } + catch (Exception x0) + { + int x1 = 1; + G(() => x0); + G(() => x1); + } + } + } - G(() => x0); //ok - G(() => H(x0, x1)); // runtime rude edit - } - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + static bool G(Func f) => true; + static int H(object a, object b) => 1; + + static void F() + { + try + { + } + catch (Exception x0) + { + int x1 = 1; + G(() => x0); + G(() => x1); + + G(() => x0); //ok + G(() => H(x0, x1)); // runtime rude edit + } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)], @@ -3071,51 +3223,55 @@ static void F() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1504")] public void Lambdas_Insert_CatchFilter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static bool G(Func f) => true; - - static void F() - { - Exception x1 = null; - - try - { - G(() => x1); - } - catch (Exception x0) when (G(() => x0)) - { - } - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - static bool G(Func f) => true; - - static void F() - { - Exception x1 = null; - - try - { - G(() => x1); - } - catch (Exception x0) when (G(() => x0) && - G(() => x0) && // ok - G(() => x0 != x1)) // runtime rude edit - { - G(() => x0); // ok - } - } -} -"; + class C + { + static bool G(Func f) => true; + + static void F() + { + Exception x1 = null; + + try + { + G(() => x1); + } + catch (Exception x0) when (G(() => x0)) + { + } + } + } + + """; + var src2 = """ + + using System; + + class C + { + static bool G(Func f) => true; + + static void F() + { + Exception x1 = null; + + try + { + G(() => x1); + } + catch (Exception x0) when (G(() => x0) && + G(() => x0) && // ok + G(() => x0 != x1)) // runtime rude edit + { + G(() => x0); // ok + } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)], @@ -3125,29 +3281,33 @@ static void F() [Fact] public void Lambdas_Insert_Static_Second() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - var f = new Func(a => a); - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - var f = new Func(a => a); - var g = new Func(b => b); - } -} -"; + class C + { + void F() + { + var f = new Func(a => a); + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + var f = new Func(a => a); + var g = new Func(b => b); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -3173,34 +3333,38 @@ public void Lambdas_Update_ParameterRefness_NoBodyChange() [Fact] public void Lambdas_Update_Signature1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void G1(Func f) {} - void G2(Func f) {} + using System; - void F() - { - G1(a => a); - } -} -"; - var src2 = @" -using System; + class C + { + void G1(Func f) {} + void G2(Func f) {} -class C -{ - void G1(Func f) {} - void G2(Func f) {} + void F() + { + G1(a => a); + } + } - void F() - { - G2(a => a); - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + void G1(Func f) {} + void G2(Func f) {} + + void F() + { + G2(a => a); + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -3214,34 +3378,38 @@ void F() [Fact] public void Lambdas_Update_Signature2() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void G1(Func f) {} - void G2(Func f) {} + using System; - void F() - { - G1(a => a); - } -} -"; - var src2 = @" -using System; + class C + { + void G1(Func f) {} + void G2(Func f) {} -class C -{ - void G1(Func f) {} - void G2(Func f) {} + void F() + { + G1(a => a); + } + } - void F() - { - G2((a, b) => a + b); - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + void G1(Func f) {} + void G2(Func f) {} + + void F() + { + G2((a, b) => a + b); + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -3255,34 +3423,38 @@ void F() [Fact] public void Lambdas_Update_Signature3() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void G1(Func f) {} - void G2(Func f) {} + using System; - void F() - { - G1(a => a); - } -} -"; - var src2 = @" -using System; + class C + { + void G1(Func f) {} + void G2(Func f) {} -class C -{ - void G1(Func f) {} - void G2(Func f) {} + void F() + { + G1(a => a); + } + } - void F() - { - G2(a => a); - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + void G1(Func f) {} + void G2(Func f) {} + + void F() + { + G2(a => a); + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -3296,34 +3468,38 @@ void F() [Fact] public void Lambdas_Update_Signature_Nullable() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void G1(Func f) {} - void G2(Func f) {} + using System; - void F() - { - G1(a => a); - } -} -"; - var src2 = @" -using System; + class C + { + void G1(Func f) {} + void G2(Func f) {} -class C -{ - void G1(Func f) {} - void G2(Func f) {} + void F() + { + G1(a => a); + } + } - void F() - { - G2(a => a); - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + void G1(Func f) {} + void G2(Func f) {} + + void F() + { + G2(a => a); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); @@ -3332,34 +3508,38 @@ void F() [Fact] public void Lambdas_Update_Signature_SyntaxOnly1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void G1(Func f) {} - void G2(Func f) {} + using System; - void F() - { - G1(a => a); - } -} -"; - var src2 = @" -using System; + class C + { + void G1(Func f) {} + void G2(Func f) {} -class C -{ - void G1(Func f) {} - void G2(Func f) {} + void F() + { + G1(a => a); + } + } - void F() - { - G2((a) => a); - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + void G1(Func f) {} + void G2(Func f) {} + + void F() + { + G2((a) => a); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); @@ -3368,34 +3548,38 @@ void F() [Fact] public void Lambdas_Update_Signature_ReturnType1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void G1(Func f) {} - void G2(Action f) {} + using System; - void F() - { - G1(a => { return 1; }); - } -} -"; - var src2 = @" -using System; + class C + { + void G1(Func f) {} + void G2(Action f) {} -class C -{ - void G1(Func f) {} - void G2(Action f) {} + void F() + { + G1(a => { return 1; }); + } + } - void F() - { - G2(a => { }); - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + void G1(Func f) {} + void G2(Action f) {} + + void F() + { + G2(a => { }); + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -3409,34 +3593,38 @@ void F() [Fact] public void Lambdas_Update_Signature_ReturnType2() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void G1(Func f) {} - void G2(Action f) {} + using System; - void F() - { - var x = int (int a) => a; - } -} -"; - var src2 = @" -using System; + class C + { + void G1(Func f) {} + void G2(Action f) {} -class C -{ - void G1(Func f) {} - void G2(Action f) {} + void F() + { + var x = int (int a) => a; + } + } - void F() - { - var x = long (int a) => a; - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + void G1(Func f) {} + void G2(Action f) {} + + void F() + { + var x = long (int a) => a; + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -3450,28 +3638,32 @@ void F() [Fact] public void Lambdas_Update_Signature_ReturnType_Anonymous() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - var x = (int* a, int b) => a; - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - var x = (int* a, int b) => b; - } -} -"; + class C + { + void F() + { + var x = (int* a, int b) => a; + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + var x = (int* a, int b) => b; + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -3485,34 +3677,38 @@ void F() [Fact] public void Lambdas_Update_Signature_BodySyntaxOnly() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void G1(Func f) {} - void G2(Func f) {} + using System; - void F() - { - G1(a => { return 1; }); - } -} -"; - var src2 = @" -using System; + class C + { + void G1(Func f) {} + void G2(Func f) {} -class C -{ - void G1(Func f) {} - void G2(Func f) {} + void F() + { + G1(a => { return 1; }); + } + } - void F() - { - G2(a => 2); - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + void G1(Func f) {} + void G2(Func f) {} + + void F() + { + G2(a => 2); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); @@ -3521,34 +3717,38 @@ void F() [Fact] public void Lambdas_Update_Signature_ParameterName1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void G1(Func f) {} - void G2(Func f) {} + using System; - void F() - { - G1(a => 1); - } -} -"; - var src2 = @" -using System; + class C + { + void G1(Func f) {} + void G2(Func f) {} -class C -{ - void G1(Func f) {} - void G2(Func f) {} + void F() + { + G1(a => 1); + } + } - void F() - { - G2(b => 2); - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + void G1(Func f) {} + void G2(Func f) {} + + void F() + { + G2(b => 2); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); @@ -3557,40 +3757,44 @@ void F() [Fact] public void Lambdas_Update_Signature_ParameterRefness1() { - var src1 = @" -using System; + var src1 = """ -delegate int D1(ref int a); -delegate int D2(int a); + using System; -class C -{ - void G1(D1 f) {} - void G2(D2 f) {} + delegate int D1(ref int a); + delegate int D2(int a); - void F() - { - G1((ref int a) => 1); - } -} -"; - var src2 = @" -using System; + class C + { + void G1(D1 f) {} + void G2(D2 f) {} -delegate int D1(ref int a); -delegate int D2(int a); + void F() + { + G1((ref int a) => 1); + } + } -class C -{ - void G1(D1 f) {} - void G2(D2 f) {} + """; + var src2 = """ - void F() - { - G2((int a) => 2); - } -} -"; + using System; + + delegate int D1(ref int a); + delegate int D2(int a); + + class C + { + void G1(D1 f) {} + void G2(D2 f) {} + + void F() + { + G2((int a) => 2); + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -3604,40 +3808,44 @@ void F() [Fact] public void Lambdas_Update_Signature_ParameterRefness2() { - var src1 = @" -using System; + var src1 = """ -delegate int D1(ref int a); -delegate int D2(out int a); + using System; -class C -{ - void G(D1 f) {} - void G(D2 f) {} + delegate int D1(ref int a); + delegate int D2(out int a); - void F() - { - G((ref int a) => a = 1); - } -} -"; - var src2 = @" -using System; + class C + { + void G(D1 f) {} + void G(D2 f) {} -delegate int D1(ref int a); -delegate int D2(out int a); + void F() + { + G((ref int a) => a = 1); + } + } -class C -{ - void G(D1 f) {} - void G(D2 f) {} + """; + var src2 = """ - void F() - { - G((out int a) => a = 1); - } -} -"; + using System; + + delegate int D1(ref int a); + delegate int D2(out int a); + + class C + { + void G(D1 f) {} + void G(D2 f) {} + + void F() + { + G((out int a) => a = 1); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -3647,81 +3855,85 @@ void F() [Fact(Skip = "TODO")] public void Lambdas_Update_Signature_CustomModifiers1() { - var delegateSource = @" -.class public auto ansi sealed D1 - extends [mscorlib]System.MulticastDelegate -{ - .method public specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed - { - } - - .method public newslot virtual instance int32 [] modopt([mscorlib]System.Int64) Invoke( - int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, - int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) runtime managed - { - } -} + var src1 = """ -.class public auto ansi sealed D2 - extends [mscorlib]System.MulticastDelegate -{ - .method public specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed - { - } - - .method public newslot virtual instance int32 [] modopt([mscorlib]System.Boolean) Invoke( - int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, - int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) runtime managed - { - } -} + using System; -.class public auto ansi sealed D3 - extends [mscorlib]System.MulticastDelegate -{ - .method public specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed - { - } + class C + { + void G1(D1 f) {} + void G2(D2 f) {} - .method public newslot virtual instance int32 [] modopt([mscorlib]System.Boolean) Invoke( - int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, - int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) runtime managed - { - } -}"; + void F() + { + G1(a => a); + } + } - var src1 = @" -using System; + """; + var src2 = """ -class C -{ - void G1(D1 f) {} - void G2(D2 f) {} + using System; - void F() - { - G1(a => a); - } -} -"; - var src2 = @" -using System; + class C + { + void G1(D1 f) {} + void G2(D2 f) {} -class C -{ - void G1(D1 f) {} - void G2(D2 f) {} + void F() + { + G2(a => a); + } + } - void F() - { - G2(a => a); - } -} -"; + """; MetadataReference delegateDefs; - using (var tempAssembly = IlasmUtilities.CreateTempAssembly(delegateSource)) - { - delegateDefs = MetadataReference.CreateFromImage(File.ReadAllBytes(tempAssembly.Path)); + using (var tempAssembly = IlasmUtilities.CreateTempAssembly(""" + + .class public auto ansi sealed D1 + extends [mscorlib]System.MulticastDelegate + { + .method public specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed + { + } + + .method public newslot virtual instance int32 [] modopt([mscorlib]System.Int64) Invoke( + int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, + int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) runtime managed + { + } + } + + .class public auto ansi sealed D2 + extends [mscorlib]System.MulticastDelegate + { + .method public specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed + { + } + + .method public newslot virtual instance int32 [] modopt([mscorlib]System.Boolean) Invoke( + int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, + int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) runtime managed + { + } + } + + .class public auto ansi sealed D3 + extends [mscorlib]System.MulticastDelegate + { + .method public specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed + { + } + + .method public newslot virtual instance int32 [] modopt([mscorlib]System.Boolean) Invoke( + int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, + int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) runtime managed + { + } + } + """)) + { + delegateDefs = MetadataReference.CreateFromImage(File.ReadAllBytes(tempAssembly.Path)); } var edits = GetTopEdits(src1, src2); @@ -3733,32 +3945,36 @@ void F() [Fact] public void Lambdas_Update_Signature_MatchingErrorType() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void G(Func f) {} + using System; - void F() - { - G(a => 1); - } -} -"; - var src2 = @" -using System; + class C + { + void G(Func f) {} -class C -{ - void G(Func f) {} + void F() + { + G(a => 1); + } + } - void F() - { - G(a => 2); - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + void G(Func f) {} + + void F() + { + G(a => 2); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -3772,34 +3988,38 @@ void F() [Fact] public void Lambdas_Update_Signature_NonMatchingErrorType() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void G1(Func f) {} - void G2(Func f) {} + using System; - void F() - { - G1(a => 1); - } -} -"; - var src2 = @" -using System; + class C + { + void G1(Func f) {} + void G2(Func f) {} -class C -{ - void G1(Func f) {} - void G2(Func f) {} + void F() + { + G1(a => 1); + } + } - void F() - { - G2(a => 2); - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + void G1(Func f) {} + void G2(Func f) {} + + void F() + { + G2(a => 2); + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -3813,40 +4033,44 @@ void F() [Fact] public void Lambdas_Update_DelegateType1() { - var src1 = @" -using System; + var src1 = """ -delegate int D1(int a); -delegate int D2(int a); + using System; -class C -{ - void G1(D1 f) {} - void G2(D2 f) {} + delegate int D1(int a); + delegate int D2(int a); - void F() - { - G1(a => a); - } -} -"; - var src2 = @" -using System; + class C + { + void G1(D1 f) {} + void G2(D2 f) {} -delegate int D1(int a); -delegate int D2(int a); + void F() + { + G1(a => a); + } + } -class C -{ - void G1(D1 f) {} - void G2(D2 f) {} + """; + var src2 = """ - void F() - { - G2(a => a); - } -} -"; + using System; + + delegate int D1(int a); + delegate int D2(int a); + + class C + { + void G1(D1 f) {} + void G2(D2 f) {} + + void F() + { + G2(a => a); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } @@ -3854,40 +4078,44 @@ void F() [Fact] public void Lambdas_Update_SourceType1() { - var src1 = @" -using System; + var src1 = """ -delegate C D1(C a); -delegate C D2(C a); + using System; -class C -{ - void G1(D1 f) {} - void G2(D2 f) {} + delegate C D1(C a); + delegate C D2(C a); - void F() - { - G1(a => a); - } -} -"; - var src2 = @" -using System; + class C + { + void G1(D1 f) {} + void G2(D2 f) {} -delegate C D1(C a); -delegate C D2(C a); + void F() + { + G1(a => a); + } + } -class C -{ - void G1(D1 f) {} - void G2(D2 f) {} + """; + var src2 = """ - void F() - { - G2(a => a); - } -} -"; + using System; + + delegate C D1(C a); + delegate C D2(C a); + + class C + { + void G1(D1 f) {} + void G2(D2 f) {} + + void F() + { + G2(a => a); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } @@ -3895,44 +4123,48 @@ void F() [Fact] public void Lambdas_Update_SourceType2() { - var src1 = @" -using System; + var src1 = """ -delegate C D1(C a); -delegate B D2(B a); + using System; -class B { } + delegate C D1(C a); + delegate B D2(B a); -class C -{ - void G1(D1 f) {} - void G2(D2 f) {} + class B { } - void F() - { - G1(a => a); - } -} -"; - var src2 = @" -using System; + class C + { + void G1(D1 f) {} + void G2(D2 f) {} -delegate C D1(C a); -delegate B D2(B a); + void F() + { + G1(a => a); + } + } -class B { } + """; + var src2 = """ -class C -{ - void G1(D1 f) {} - void G2(D2 f) {} + using System; - void F() - { - G2(a => a); - } -} -"; + delegate C D1(C a); + delegate B D2(B a); + + class B { } + + class C + { + void G1(D1 f) {} + void G2(D2 f) {} + + void F() + { + G2(a => a); + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -3946,46 +4178,50 @@ void F() [Fact] public void Lambdas_Update_SourceTypeAndMetadataType1() { - var src1 = @" -namespace System -{ - delegate string D1(string a); - delegate String D2(String a); + var src1 = """ - class String { } + namespace System + { + delegate string D1(string a); + delegate String D2(String a); - class C - { - void G1(D1 f) {} - void G2(D2 f) {} + class String { } - void F() - { - G1(a => a); - } - } -} -"; - var src2 = @" -namespace System -{ - delegate string D1(string a); - delegate String D2(String a); + class C + { + void G1(D1 f) {} + void G2(D2 f) {} - class String { } + void F() + { + G1(a => a); + } + } + } - class C - { - void G1(D1 f) {} - void G2(D2 f) {} + """; + var src2 = """ - void F() - { - G2(a => a); - } - } -} -"; + namespace System + { + delegate string D1(string a); + delegate String D2(String a); + + class String { } + + class C + { + void G1(D1 f) {} + void G2(D2 f) {} + + void F() + { + G2(a => a); + } + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -3999,36 +4235,40 @@ void F() [Fact] public void Lambdas_Update_Generic1() { - var src1 = @" -delegate T D1(S a, T b); -delegate T D2(T a, S b); + var src1 = """ -class C -{ - void G1(D1 f) {} - void G2(D2 f) {} + delegate T D1(S a, T b); + delegate T D2(T a, S b); - void F() - { - G1((a, b) => a + b); - } -} -"; - var src2 = @" -delegate T D1(S a, T b); -delegate T D2(T a, S b); + class C + { + void G1(D1 f) {} + void G2(D2 f) {} -class C -{ - void G1(D1 f) {} - void G2(D2 f) {} + void F() + { + G1((a, b) => a + b); + } + } - void F() - { - G2((a, b) => a + b); - } -} -"; + """; + var src2 = """ + + delegate T D1(S a, T b); + delegate T D2(T a, S b); + + class C + { + void G1(D1 f) {} + void G2(D2 f) {} + + void F() + { + G2((a, b) => a + b); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } @@ -4036,36 +4276,40 @@ void F() [Fact] public void Lambdas_Update_Generic2() { - var src1 = @" -delegate int D1(S a, T b); -delegate int D2(T a, S b); + var src1 = """ -class C -{ - void G1(D1 f) {} - void G2(D2 f) {} + delegate int D1(S a, T b); + delegate int D2(T a, S b); - void F() - { - G1((a, b) => 1); - } -} -"; - var src2 = @" -delegate int D1(S a, T b); -delegate int D2(T a, S b); + class C + { + void G1(D1 f) {} + void G2(D2 f) {} -class C -{ - void G1(D1 f) {} - void G2(D2 f) {} + void F() + { + G1((a, b) => 1); + } + } - void F() - { - G2((a, b) => 1); - } -} -"; + """; + var src2 = """ + + delegate int D1(S a, T b); + delegate int D2(T a, S b); + + class C + { + void G1(D1 f) {} + void G2(D2 f) {} + + void F() + { + G2((a, b) => 1); + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -4079,36 +4323,40 @@ void F() [Fact] public void Lambdas_Update_CapturedParameters1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F(int x1) - { - var f1 = new Func((a1, a2) => - { - var f2 = new Func(a3 => x1 + a2); - return a1; - }); - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F(int x1) - { - var f1 = new Func((a1, a2) => - { - var f2 = new Func(a3 => x1 + a2 + 1); - return a1; - }); - } -} -"; + class C + { + void F(int x1) + { + var f1 = new Func((a1, a2) => + { + var f2 = new Func(a3 => x1 + a2); + return a1; + }); + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F(int x1) + { + var f1 = new Func((a1, a2) => + { + var f2 = new Func(a3 => x1 + a2 + 1); + return a1; + }); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); @@ -4117,82 +4365,90 @@ void F(int x1) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2223")] public void Lambdas_Update_CapturedParameters2() { - var src1 = @" -using System; - -class C -{ - void F(int x1) - { - var f1 = new Func((a1, a2) => - { - var f2 = new Func(a3 => x1 + a2); - return a1; - }); + var src1 = """ - var f3 = new Func((a1, a2) => - { - var f4 = new Func(a3 => x1 + a2); - return a1; - }); - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F(int x1) - { - var f1 = new Func((a1, a2) => - { - var f2 = new Func(a3 => x1 + a2 + 1); - return a1; - }); + class C + { + void F(int x1) + { + var f1 = new Func((a1, a2) => + { + var f2 = new Func(a3 => x1 + a2); + return a1; + }); + + var f3 = new Func((a1, a2) => + { + var f4 = new Func(a3 => x1 + a2); + return a1; + }); + } + } - var f3 = new Func((a1, a2) => - { - var f4 = new Func(a3 => x1 + a2 + 1); - return a1; - }); - } -} -"; - var edits = GetTopEdits(src1, src2); + """; + var src2 = """ - edits.VerifySemanticDiagnostics(); - } + using System; + + class C + { + void F(int x1) + { + var f1 = new Func((a1, a2) => + { + var f2 = new Func(a3 => x1 + a2 + 1); + return a1; + }); + + var f3 = new Func((a1, a2) => + { + var f4 = new Func(a3 => x1 + a2 + 1); + return a1; + }); + } + } + + """; + var edits = GetTopEdits(src1, src2); + + edits.VerifySemanticDiagnostics(); + } [Fact] public void Lambdas_Update_CeaseCapture_This() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int x = 1; + using System; - void F() - { - var f = new Func(a => a + x); - } -} -"; - var src2 = @" -using System; + class C + { + int x = 1; -class C -{ - int x = 1; - - void F() - { - var f = new Func(a => a); - } -} -"; + void F() + { + var f = new Func(a => a + x); + } + } + + """; + var src2 = """ + + using System; + + class C + { + int x = 1; + + void F() + { + var f = new Func(a => a); + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -4203,38 +4459,42 @@ void F() [Fact] public void Lambdas_Update_CeaseCapture_Closure1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - int y = 1; - var f1 = new Func(a1 => - { - var f2 = new Func(a2 => y + a2); - return a1; - }); - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - int y = 1; - var f1 = new Func(a1 => - { - var f2 = new Func(a2 => a2); - return a1 + y; - }); - } -} -"; + class C + { + void F() + { + int y = 1; + var f1 = new Func(a1 => + { + var f2 = new Func(a2 => y + a2); + return a1; + }); + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + int y = 1; + var f1 = new Func(a1 => + { + var f2 = new Func(a2 => a2); + return a1 + y; + }); + } + } + + """; var edits = GetTopEdits(src1, src2); // y is no longer captured in f2 @@ -4245,22 +4505,26 @@ void F() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51297")] public void Lambdas_Update_CeaseCapture_IndexerParameter_WithExpressionBody() { - var src1 = @" -using System; + var src1 = """ -class C -{ - Func this[int a1, int a2] => new Func(a3 => a1 + a2); -} -"; - var src2 = @" -using System; + using System; -class C -{ - Func this[int a1, int a2] => new Func(a3 => a2); -} -"; + class C + { + Func this[int a1, int a2] => new Func(a3 => a1 + a2); + } + + """; + var src2 = """ + + using System; + + class C + { + Func this[int a1, int a2] => new Func(a3 => a2); + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( [ @@ -4273,21 +4537,25 @@ class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51297")] public void Lambdas_Update_CeaseCapture_IndexerParameter_WithExpressionBody_LambdaBlock() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int this[int a] => new Func(() => { return a + 1; })(); -} -"; - var src2 = @" -using System; + using System; -class C -{ - int this[int a] => new Func(() => { return 2; })(); // not capturing a anymore -}"; + class C + { + int this[int a] => new Func(() => { return a + 1; })(); + } + + """; + var src2 = """ + + using System; + + class C + { + int this[int a] => new Func(() => { return 2; })(); // not capturing a anymore + } + """; var edits = GetTopEdits(src1, src2); @@ -4306,21 +4574,25 @@ class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51297")] public void Lambdas_Update_CeaseCapture_IndexerParameter_WithExpressionBody_Delegate() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int this[int a] => new Func(delegate { return a + 1; })(); -} -"; - var src2 = @" -using System; + using System; -class C -{ - int this[int a] => new Func(delegate { return 2; })(); // not capturing a anymore -}"; + class C + { + int this[int a] => new Func(delegate { return a + 1; })(); + } + + """; + var src2 = """ + + using System; + + class C + { + int this[int a] => new Func(delegate { return 2; })(); // not capturing a anymore + } + """; var edits = GetTopEdits(src1, src2); @@ -4339,22 +4611,26 @@ class C [Fact] public void Lambdas_Update_CeaseCapture_IndexerParameter_WithExpressionBody_Getter() { - var src1 = @" -using System; + var src1 = """ -class C -{ - Func this[int a1, int a2] { get => new(a3 => a1 + a2); } -} -"; - var src2 = @" -using System; + using System; -class C -{ - Func this[int a1, int a2] { get { return new Func(a3 => a2); } } -} -"; + class C + { + Func this[int a1, int a2] { get => new(a3 => a1 + a2); } + } + + """; + var src2 = """ + + using System; + + class C + { + Func this[int a1, int a2] { get { return new Func(a3 => a2); } } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: true)); @@ -4363,28 +4639,30 @@ class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51297")] public void Lambdas_Update_CeaseCapture_IndexerParameter_WithExpressionBody_Partial() { - var srcA1 = @" -partial class C -{ -}"; - var srcB1 = @" -partial class C -{ - int this[int a] => new System.Func(() => a + 1); -}"; + EditAndContinueValidation.VerifySemantics( + [GetTopEdits(""" - var srcA2 = @" -partial class C -{ - int this[int a] => new System.Func(() => 2); // no capture -}"; - var srcB2 = @" -partial class C -{ -}"; + partial class C + { + } + """, """ - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + partial class C + { + int this[int a] => new System.Func(() => 2); // no capture + } + """), GetTopEdits(""" + + partial class C + { + int this[int a] => new System.Func(() => a + 1); + } + """, """ + + partial class C + { + } + """)], [ DocumentResults( semanticEdits: [ @@ -4399,22 +4677,26 @@ partial class C [Fact] public void Lambdas_Update_CeaseCapture_IndexerParameter_ParameterDelete() { - var src1 = @" -using System; + var src1 = """ -class C -{ - Func this[int a1, int a2] { get { return new Func(a3 => a1 + a2); } } -} -"; - var src2 = @" -using System; + using System; -class C -{ - Func this[int a2] { get { return new Func(a3 => a2); } } -} -"; + class C + { + Func this[int a1, int a2] { get { return new Func(a3 => a1 + a2); } } + } + + """; + var src2 = """ + + using System; + + class C + { + Func this[int a2] { get { return new Func(a3 => a2); } } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -4430,28 +4712,32 @@ class C [Fact] public void Lambdas_Update_CeaseCapture_MethodParameter() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F(int a1, int a2) - { - var f2 = new Func(a3 => a1 + a2); - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F(int a1, int a2) - { - var f2 = new Func(a3 => a1); - } -} -"; + class C + { + void F(int a1, int a2) + { + var f2 = new Func(a3 => a1 + a2); + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F(int a1, int a2) + { + var f2 = new Func(a3 => a1); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -4461,22 +4747,26 @@ void F(int a1, int a2) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51297")] public void Lambdas_Update_CeaseCapture_MethodParameter_WithExpressionBody() { - var src1 = @" -using System; + var src1 = """ -class C -{ - Func F(int a1, int a2) => new Func(a3 => a1 + a2); -} -"; - var src2 = @" -using System; + using System; -class C -{ - Func F(int a1, int a2) => new Func(a3 => a1); -} -"; + class C + { + Func F(int a1, int a2) => new Func(a3 => a1 + a2); + } + + """; + var src2 = """ + + using System; + + class C + { + Func F(int a1, int a2) => new Func(a3 => a1); + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -4485,22 +4775,26 @@ class C [Fact] public void Lambdas_Update_CeaseCapture_MethodParameter_ParameterDelete() { - var src1 = @" -using System; + var src1 = """ -class C -{ - Func F(int a1, int a2) => new Func(a3 => a1 + a2); -} -"; - var src2 = @" -using System; + using System; -class C -{ - Func F(int a1) => new Func(a3 => a1); -} -"; + class C + { + Func F(int a1, int a2) => new Func(a3 => a1 + a2); + } + + """; + var src2 = """ + + using System; + + class C + { + Func F(int a1) => new Func(a3 => a1); + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( [ @@ -4513,22 +4807,26 @@ class C [Fact] public void Lambdas_Update_CeaseCapture_MethodParameter_ParameterTypeChange() { - var src1 = @" -using System; + var src1 = """ -class C -{ - Func F(int a1, int a2) => new Func(a3 => a1 + a2); -} -"; - var src2 = @" -using System; + using System; -class C -{ - Func F(byte a1) => new Func(a3 => a1); -} -"; + class C + { + Func F(int a1, int a2) => new Func(a3 => a1 + a2); + } + + """; + var src2 = """ + + using System; + + class C + { + Func F(byte a1) => new Func(a3 => a1); + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -4542,22 +4840,26 @@ class C [Fact] public void Lambdas_Update_CeaseCapture_MethodParameter_LocalToParameter() { - var src1 = @" -using System; + var src1 = """ -class C -{ - Func F(int a1) { int a2 = 1; return new Func(a3 => a1 + a2); } -} -"; - var src2 = @" -using System; + using System; -class C -{ - Func F(int a1, int a2) { return new Func(a3 => a1 + a2); } -} -"; + class C + { + Func F(int a1) { int a2 = 1; return new Func(a3 => a1 + a2); } + } + + """; + var src2 = """ + + using System; + + class C + { + Func F(int a1, int a2) { return new Func(a3 => a1 + a2); } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -4571,22 +4873,26 @@ class C [Fact] public void Lambdas_Update_CeaseCapture_MethodParameter_ParameterToLocal() { - var src1 = @" -using System; + var src1 = """ -class C -{ - Func F(int a1, int a2) { return new Func(a3 => a1 + a2); } -} -"; - var src2 = @" -using System; + using System; -class C -{ - Func F(int a1) { int a2 = 1; return new Func(a3 => a1 + a2); } -} -"; + class C + { + Func F(int a1, int a2) { return new Func(a3 => a1 + a2); } + } + + """; + var src2 = """ + + using System; + + class C + { + Func F(int a1) { int a2 = 1; return new Func(a3 => a1 + a2); } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -4600,44 +4906,48 @@ class C [Fact] public void Lambdas_Update_CeaseCapture_LambdaParameter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - var f1 = new Func((a1, a2) => - { - var f2 = new Func(a3 => + using System; + + class C { - var f3 = new Func(a4 => a1 + a2 + a3); - return 1; - }); - return a1; - }); - } -} -"; - var src2 = @" -using System; + void F() + { + var f1 = new Func((a1, a2) => + { + var f2 = new Func(a3 => + { + var f3 = new Func(a4 => a1 + a2 + a3); + return 1; + }); + return a1; + }); + } + } -class C -{ - void F() - { - var f1 = new Func((a1, a2) => - { - var f2 = new Func(a3 => + """; + var src2 = """ + + using System; + + class C { - var f3 = new Func(a4 => a2); - return 1; - }); - return a1; - }); - } -} -"; + void F() + { + var f1 = new Func((a1, a2) => + { + var f2 = new Func(a3 => + { + var f3 = new Func(a4 => a2); + return 1; + }); + return a1; + }); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -4646,30 +4956,34 @@ void F() [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")] public void Lambdas_Update_CeaseCapture_SetterValueParameter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int D - { - get { return 0; } - set { new Action(() => { Console.Write(value); }).Invoke(); } - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - int D - { - get { return 0; } - set { } - } -} -"; + class C + { + int D + { + get { return 0; } + set { new Action(() => { Console.Write(value); }).Invoke(); } + } + } + + """; + var src2 = """ + + using System; + + class C + { + int D + { + get { return 0; } + set { } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_D"))); @@ -4678,30 +4992,34 @@ int D [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")] public void Lambdas_Update_CeaseCapture_IndexerSetterValueParameter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int this[int a1, int a2] - { - get { return 0; } - set { new Action(() => { Console.Write(value); }).Invoke(); } - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - int this[int a1, int a2] - { - get { return 0; } - set { } - } -} -"; + class C + { + int this[int a1, int a2] + { + get { return 0; } + set { new Action(() => { Console.Write(value); }).Invoke(); } + } + } + + """; + var src2 = """ + + using System; + + class C + { + int this[int a1, int a2] + { + get { return 0; } + set { } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"))); @@ -4710,30 +5028,34 @@ class C [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")] public void Lambdas_Update_CeaseCapture_EventAdderValueParameter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - event Action D - { - add { new Action(() => { Console.Write(value); }).Invoke(); } - remove { } - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - event Action D - { - add { } - remove { } - } -} -"; + class C + { + event Action D + { + add { new Action(() => { Console.Write(value); }).Invoke(); } + remove { } + } + } + + """; + var src2 = """ + + using System; + + class C + { + event Action D + { + add { } + remove { } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.add_D"))); @@ -4742,30 +5064,34 @@ event Action D [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")] public void Lambdas_Update_CeaseCapture_EventRemoverValueParameter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - event Action D - { - add { } - remove { new Action(() => { Console.Write(value); }).Invoke(); } - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - event Action D - { - add { } - remove { } - } -} -"; + class C + { + event Action D + { + add { } + remove { new Action(() => { Console.Write(value); }).Invoke(); } + } + } + + """; + var src2 = """ + + using System; + + class C + { + event Action D + { + add { } + remove { } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.remove_D"))); @@ -4885,37 +5211,41 @@ public void Lambdas_Update_CeaseCapture_PrimaryParameter_Method_PrimaryToThisCap [Fact] public void Lambdas_Update_DeleteCapture1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - int y = 1; - var f1 = new Func(a1 => - { - var f2 = new Func(a2 => y + a2); - return y; - }); - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { // error - var f1 = new Func(a1 => - { - var f2 = new Func(a2 => a2); - return a1; - }); - } -} -"; + class C + { + void F() + { + int y = 1; + var f1 = new Func(a1 => + { + var f2 = new Func(a2 => y + a2); + return y; + }); + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { // error + var f1 = new Func(a1 => + { + var f2 = new Func(a2 => a2); + return a1; + }); + } + } + + """; var edits = GetTopEdits(src1, src2); // y is no longer captured in f2 @@ -4926,22 +5256,26 @@ void F() [Fact] public void Lambdas_Update_Capturing_IndexerGetterParameter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - Func this[int a1, int a2] => new Func(a3 => a2); -} -"; - var src2 = @" -using System; + using System; -class C -{ - Func this[int a1, int a2] => new Func(a3 => a1 + a2); -} -"; + class C + { + Func this[int a1, int a2] => new Func(a3 => a2); + } + + """; + var src2 = """ + + using System; + + class C + { + Func this[int a1, int a2] => new Func(a3 => a1 + a2); + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -4954,22 +5288,26 @@ class C [Fact] public void Lambdas_Update_Capturing_IndexerGetterParameter2() { - var src1 = @" -using System; + var src1 = """ -class C -{ - Func this[int a1, int a2] { get { return new Func(a3 => a2); } } -} -"; - var src2 = @" -using System; + using System; -class C -{ - Func this[int a1, int a2] { get { return new Func(a3 => a1 + a2); } } -} -"; + class C + { + Func this[int a1, int a2] { get { return new Func(a3 => a2); } } + } + + """; + var src2 = """ + + using System; + + class C + { + Func this[int a1, int a2] { get { return new Func(a3 => a1 + a2); } } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -4979,22 +5317,26 @@ class C [Fact] public void Lambdas_Update_Capturing_IndexerGetterParameter_ParameterInsert() { - var src1 = @" -using System; + var src1 = """ -class C -{ - Func this[int a1] => new(a3 => a1); -} -"; - var src2 = @" -using System; + using System; -class C -{ - Func this[int a1, int a2] => new(a3 => a1 + a2); -} -"; + class C + { + Func this[int a1] => new(a3 => a1); + } + + """; + var src2 = """ + + using System; + + class C + { + Func this[int a1, int a2] => new(a3 => a1 + a2); + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( [ @@ -5009,22 +5351,26 @@ class C [Fact] public void Lambdas_Update_Capturing_IndexerSetterParameter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - Func this[int a1, int a2] { get { return null; } set { var f = new Func(a3 => a2); } } -} -"; - var src2 = @" -using System; + using System; -class C -{ - Func this[int a1, int a2] { get { return null; } set { var f = new Func(a3 => a1 + a2); } } -} -"; + class C + { + Func this[int a1, int a2] { get { return null; } set { var f = new Func(a3 => a2); } } + } + + """; + var src2 = """ + + using System; + + class C + { + Func this[int a1, int a2] { get { return null; } set { var f = new Func(a3 => a1 + a2); } } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -5034,30 +5380,34 @@ class C [Fact] public void Lambdas_Update_Capturing_IndexerSetterValueParameter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int this[int a1, int a2] - { - get { return 0; } - set { } - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - int this[int a1, int a2] - { - get { return 0; } - set { new Action(() => { Console.Write(value); }).Invoke(); } - } -} -"; + class C + { + int this[int a1, int a2] + { + get { return 0; } + set { } + } + } + + """; + var src2 = """ + + using System; + + class C + { + int this[int a1, int a2] + { + get { return 0; } + set { new Action(() => { Console.Write(value); }).Invoke(); } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: true)], @@ -5067,30 +5417,34 @@ class C [Fact] public void Lambdas_Update_Capturing_EventAdderValueParameter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - event Action D - { - add { } - remove { } - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - event Action D - { - add { } - remove { new Action(() => { Console.Write(value); }).Invoke(); } - } -} -"; + class C + { + event Action D + { + add { } + remove { } + } + } + + """; + var src2 = """ + + using System; + + class C + { + event Action D + { + add { } + remove { new Action(() => { Console.Write(value); }).Invoke(); } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.remove_D"), preserveLocalVariables: true)], @@ -5100,30 +5454,34 @@ event Action D [Fact] public void Lambdas_Update_Capturing_EventRemoverValueParameter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - event Action D - { - add { } - remove { } - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - event Action D - { - add { } - remove { new Action(() => { Console.Write(value); }).Invoke(); } - } -} -"; + class C + { + event Action D + { + add { } + remove { } + } + } + + """; + var src2 = """ + + using System; + + class C + { + event Action D + { + add { } + remove { new Action(() => { Console.Write(value); }).Invoke(); } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -5134,28 +5492,32 @@ event Action D [Fact] public void Lambdas_Update_Capturing_MethodParameter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F(int a1, int a2) - { - var f2 = new Func(a3 => a1); - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F(int a1, int a2) - { - var f2 = new Func(a3 => a1 + a2); - } -} -"; + class C + { + void F(int a1, int a2) + { + var f2 = new Func(a3 => a1); + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F(int a1, int a2) + { + var f2 = new Func(a3 => a1 + a2); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -5164,22 +5526,26 @@ void F(int a1, int a2) [Fact] public void Lambdas_Update_Capturing_MethodParameter2() { - var src1 = @" -using System; + var src1 = """ -class C -{ - Func F(int a1, int a2) => new Func(a3 => a1); -} -"; - var src2 = @" -using System; + using System; -class C -{ - Func F(int a1, int a2) => new Func(a3 => a1 + a2); -} -"; + class C + { + Func F(int a1, int a2) => new Func(a3 => a1); + } + + """; + var src2 = """ + + using System; + + class C + { + Func F(int a1, int a2) => new Func(a3 => a1 + a2); + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -5188,22 +5554,26 @@ class C [Fact] public void Lambdas_Update_Capturing_MethodParameter_ParameterInsert() { - var src1 = @" -using System; + var src1 = """ -class C -{ - Func F(int a1) => new Func(a3 => a1); -} -"; - var src2 = @" -using System; + using System; -class C -{ - Func F(int a1, int a2) => new Func(a3 => a1 + a2); -} -"; + class C + { + Func F(int a1) => new Func(a3 => a1); + } + + """; + var src2 = """ + + using System; + + class C + { + Func F(int a1, int a2) => new Func(a3 => a1 + a2); + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( [ @@ -5216,32 +5586,36 @@ class C [Fact] public void Lambdas_Update_Capturing_MethodParameter_ParameterInsert_Partial() { - var src1 = @" -using System; + var src1 = """ -partial class C -{ - public partial Func F(int a1); -} + using System; -partial class C -{ - public partial Func F(int a1) => new Func(a3 => a1); -} -"; - var src2 = @" -using System; + partial class C + { + public partial Func F(int a1); + } -partial class C -{ - public partial Func F(int a1, int a2); -} + partial class C + { + public partial Func F(int a1) => new Func(a3 => a1); + } -partial class C -{ - public partial Func F(int a1, int a2) => new Func(a3 => a1 + a2); -} -"; + """; + var src2 = """ + + using System; + + partial class C + { + public partial Func F(int a1, int a2); + } + + partial class C + { + public partial Func F(int a1, int a2) => new Func(a3 => a1 + a2); + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( [ @@ -5254,36 +5628,40 @@ partial class C [Fact] public void Lambdas_Update_Capturing_LambdaParameter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - var f1 = new Func((a1, a2) => - { - var f2 = new Func(a3 => a2); - return a1; - }); - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - var f1 = new Func((a1, a2) => - { - var f2 = new Func(a3 => a1 + a2); - return a1; - }); - } -} -"; + class C + { + void F() + { + var f1 = new Func((a1, a2) => + { + var f2 = new Func(a3 => a2); + return a1; + }); + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + var f1 = new Func((a1, a2) => + { + var f2 = new Func(a3 => a1 + a2); + return a1; + }); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -5403,29 +5781,33 @@ public void Lambdas_Update_Capturing_PrimaryParameter_Method_PrimaryToThisCaptur [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69152")] public void Lambdas_Update_PrimaryParameterOutsideOfLambda() { - var src1 = @" -using System; + var src1 = """ -class C(int x) -{ - void F() - { - var f = new Func(a => 1); - } -} -"; - var src2 = @" -using System; + using System; -class C(int x) -{ - void F() - { - var f = new Func(a => 2); - var y = x; - } -} -"; + class C(int x) + { + void F() + { + var f = new Func(a => 1); + } + } + + """; + var src2 = """ + + using System; + + class C(int x) + { + void F() + { + var f = new Func(a => 2); + var y = x; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } @@ -5433,32 +5815,36 @@ void F() [Fact] public void Lambdas_Update_StaticToThisOnly1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int x = 1; + using System; - void F() - { - var f = new Func(a => a); - } -} -"; - var src2 = @" -using System; + class C + { + int x = 1; -class C -{ - int x = 1; - - void F() - { - var f = new Func(a => a + x); - } -} -"; + void F() + { + var f = new Func(a => a); + } + } + + """; + var src2 = """ + + using System; + + class C + { + int x = 1; + + void F() + { + var f = new Func(a => a + x); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -5467,40 +5853,44 @@ void F() [Fact] public void Lambdas_Update_StaticToThisOnly_Partial() { - var src1 = @" -using System; + var src1 = """ -partial class C -{ - int x = 1; - partial void F(); // def -} + using System; -partial class C -{ - partial void F() // impl - { - var f = new Func(a => a); - } -} -"; - var src2 = @" -using System; + partial class C + { + int x = 1; + partial void F(); // def + } -partial class C -{ - int x = 1; - partial void F(); // def -} + partial class C + { + partial void F() // impl + { + var f = new Func(a => a); + } + } -partial class C -{ - partial void F() // impl - { - var f = new Func(a => a + x); - } -} -"; + """; + var src2 = """ + + using System; + + partial class C + { + int x = 1; + partial void F(); // def + } + + partial class C + { + partial void F() // impl + { + var f = new Func(a => a + x); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F").PartialImplementationPart, preserveLocalVariables: true, partialType: "C")); @@ -5509,38 +5899,42 @@ partial void F() // impl [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69152")] public void Lambdas_Update_StaticToPrimaryParameterOnly_Partial() { - var src1 = @" -using System; + var src1 = """ -partial class C(int x) -{ - partial void F(); // def -} + using System; -partial class C -{ - partial void F() // impl - { - var f = new Func(a => a); - } -} -"; - var src2 = @" -using System; + partial class C(int x) + { + partial void F(); // def + } -partial class C(int x) -{ - partial void F(); // def -} + partial class C + { + partial void F() // impl + { + var f = new Func(a => a); + } + } -partial class C -{ - partial void F() // impl - { - var f = new Func(a => a + x); - } -} -"; + """; + var src2 = """ + + using System; + + partial class C(int x) + { + partial void F(); // def + } + + partial class C + { + partial void F() // impl + { + var f = new Func(a => a + x); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -5550,67 +5944,75 @@ partial void F() // impl [Fact] public void Lambdas_Update_StaticToThisOnly3() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int x = 1; + using System; - void F() - { - var f1 = new Func(a1 => a1); - var f2 = new Func(a2 => a2 + x); - } -} -"; - var src2 = @" -using System; + class C + { + int x = 1; -class C -{ - int x = 1; - - void F() - { - var f1 = new Func(a1 => a1 + x); - var f2 = new Func(a2 => a2 + x); - } -} -"; - var edits = GetTopEdits(src1, src2); + void F() + { + var f1 = new Func(a1 => a1); + var f2 = new Func(a2 => a2 + x); + } + } - edits.VerifySemantics( - SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); - } + """; + var src2 = """ + + using System; + + class C + { + int x = 1; + + void F() + { + var f1 = new Func(a1 => a1 + x); + var f2 = new Func(a2 => a2 + x); + } + } + + """; + var edits = GetTopEdits(src1, src2); + + edits.VerifySemantics( + SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); + } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69152")] public void Lambdas_Update_StaticToPrimaryParameterOnly3() { - var src1 = @" -using System; + var src1 = """ -class C(int x) -{ - void F() - { - var f1 = new Func(a1 => a1); - var f2 = new Func(a2 => a2 + x); - } -} -"; - var src2 = @" -using System; + using System; -class C(int x) -{ - void F() - { - var f1 = new Func(a1 => a1 + x); - var f2 = new Func(a2 => a2 + x); - } -} -"; + class C(int x) + { + void F() + { + var f1 = new Func(a1 => a1); + var f2 = new Func(a2 => a2 + x); + } + } + + """; + var src2 = """ + + using System; + + class C(int x) + { + void F() + { + var f1 = new Func(a1 => a1 + x); + var f2 = new Func(a2 => a2 + x); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -5619,28 +6021,32 @@ void F() [Fact] public void Lambdas_Update_StaticToPrimaryParameterOnly() { - var src1 = @" -using System; + var src1 = """ -class C(int x) -{ - void F() - { - var f = new Func(a => a); - } -} -"; - var src2 = @" -using System; + using System; -class C(int x) -{ - void F() - { - var f = new Func(a => a + x); - } -} -"; + class C(int x) + { + void F() + { + var f = new Func(a => a); + } + } + + """; + var src2 = """ + + using System; + + class C(int x) + { + void F() + { + var f = new Func(a => a + x); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -5649,38 +6055,42 @@ void F() [Fact] public void Lambdas_Update_StaticToClosure1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - int x = 1; - var f1 = new Func(a1 => a1); - var f2 = new Func(a2 => a2 + x); - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - int x = 1; - var f1 = new Func(a1 => - { - return a1 + - x+ // 1 - x; // 2 - }); + class C + { + void F() + { + int x = 1; + var f1 = new Func(a1 => a1); + var f2 = new Func(a2 => a2 + x); + } + } - var f2 = new Func(a2 => a2 + x); - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + void F() + { + int x = 1; + var f1 = new Func(a1 => + { + return a1 + + x+ // 1 + x; // 2 + }); + + var f2 = new Func(a2 => a2 + x); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -5690,36 +6100,40 @@ void F() [Fact] public void Lambdas_Update_ThisOnlyToClosure1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int x = 1; + using System; - void F() - { - int y = 1; - var f1 = new Func(a1 => a1 + x); - var f2 = new Func(a2 => a2 + x + y); - } -} -"; - var src2 = @" -using System; + class C + { + int x = 1; -class C -{ - int x = 1; + void F() + { + int y = 1; + var f1 = new Func(a1 => a1 + x); + var f2 = new Func(a2 => a2 + x + y); + } + } - void F() - { - int y = 1; - var f1 = new Func(a1 => a1 + x + y); - var f2 = new Func(a2 => a2 + x + y); - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + int x = 1; + + void F() + { + int y = 1; + var f1 = new Func(a1 => a1 + x + y); + var f2 = new Func(a2 => a2 + x + y); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -5728,38 +6142,42 @@ void F() [Fact] public void Lambdas_Update_Nested1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - int y = 1; - var f1 = new Func(a1 => - { - var f2 = new Func(a2 => a2 + y); - return a1; - }); - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - int y = 1; - var f1 = new Func(a1 => - { - var f2 = new Func(a2 => a2 + y); - return a1 + y; - }); - } -} -"; + class C + { + void F() + { + int y = 1; + var f1 = new Func(a1 => + { + var f2 = new Func(a2 => a2 + y); + return a1; + }); + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + int y = 1; + var f1 = new Func(a1 => + { + var f2 = new Func(a2 => a2 + y); + return a1 + y; + }); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); @@ -5768,38 +6186,42 @@ void F() [Fact] public void Lambdas_Update_Nested2() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - int y = 1; - var f1 = new Func(a1 => - { - var f2 = new Func(a2 => a2); - return a1; - }); - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - int y = 1; - var f1 = new Func(a1 => - { - var f2 = new Func(a2 => a1 + a2); - return a1; - }); - } -} -"; + class C + { + void F() + { + int y = 1; + var f1 = new Func(a1 => + { + var f2 = new Func(a2 => a2); + return a1; + }); + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + int y = 1; + var f1 = new Func(a1 => + { + var f2 = new Func(a2 => a1 + a2); + return a1; + }); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -5809,38 +6231,42 @@ void F() [Fact] public void Lambdas_Update_Accessing_Closure1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void G(Func f) {} + using System; - void F() - { - int x0 = 0, y0 = 0; - - G(a => x0); - G(a => y0); - } -} -"; - var src2 = @" -using System; + class C + { + void G(Func f) {} -class C -{ - void G(Func f) {} + void F() + { + int x0 = 0, y0 = 0; + + G(a => x0); + G(a => y0); + } + } - void F() - { - int x0 = 0, y0 = 0; - - G(a => x0); - G(a => y0 + x0); - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + void G(Func f) {} + + void F() + { + int x0 = 0, y0 = 0; + + G(a => x0); + G(a => y0 + x0); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -5849,51 +6275,55 @@ void F() [Fact] public void Lambdas_Update_Accessing_Closure2() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void G(Func f) {} - - int x = 0; // Group #0 - - void F() - { - { int x0 = 0, y0 = 0; // Group #0 - { int x1 = 0, y1 = 0; // Group #1 - - G(a => x + x0); - G(a => x0); - G(a => y0); - G(a => x1); + using System; + + class C + { + void G(Func f) {} + + int x = 0; // Group #0 + + void F() + { + { int x0 = 0, y0 = 0; // Group #0 + { int x1 = 0, y1 = 0; // Group #1 + + G(a => x + x0); + G(a => x0); + G(a => y0); + G(a => x1); + } + } + } } - } - } -} -"; - var src2 = @" -using System; -class C -{ - void G(Func f) {} - int x = 0; // Group #0 + """; + var src2 = """ - void F() - { - { int x0 = 0, y0 = 0; // Group #0 - { int x1 = 0, y1 = 0; // Group #1 - - G(a => x); // error: disconnecting previously connected closures - G(a => x0); - G(a => y0); - G(a => x1); + using System; + + class C + { + void G(Func f) {} + int x = 0; // Group #0 + + void F() + { + { int x0 = 0, y0 = 0; // Group #0 + { int x1 = 0, y1 = 0; // Group #1 + + G(a => x); // error: disconnecting previously connected closures + G(a => x0); + G(a => y0); + G(a => x1); + } + } + } } - } - } -} -"; + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -5902,53 +6332,57 @@ void F() [Fact] public void Lambdas_Update_Accessing_Closure3() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void G(Func f) {} - - int x = 0; // Group #0 - - void F() - { - { int x0 = 0, y0 = 0; // Group #0 - { int x1 = 0, y1 = 0; // Group #1 - - G(a => x); - G(a => x0); - G(a => y0); - G(a => x1); - G(a => y1); + using System; + + class C + { + void G(Func f) {} + + int x = 0; // Group #0 + + void F() + { + { int x0 = 0, y0 = 0; // Group #0 + { int x1 = 0, y1 = 0; // Group #1 + + G(a => x); + G(a => x0); + G(a => y0); + G(a => x1); + G(a => y1); + } + } + } } - } - } -} -"; - var src2 = @" -using System; -class C -{ - void G(Func f) {} - int x = 0; // Group #0 + """; + var src2 = """ - void F() - { - { int x0 = 0, y0 = 0; // Group #0 - { int x1 = 0, y1 = 0; // Group #1 - - G(a => x); - G(a => x0); - G(a => y0); - G(a => x1); - G(a => y1 + x0); // error: connecting previously disconnected closures + using System; + + class C + { + void G(Func f) {} + int x = 0; // Group #0 + + void F() + { + { int x0 = 0, y0 = 0; // Group #0 + { int x1 = 0, y1 = 0; // Group #1 + + G(a => x); + G(a => x0); + G(a => y0); + G(a => x1); + G(a => y1 + x0); // error: connecting previously disconnected closures + } + } + } } - } - } -} -"; + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -5958,53 +6392,57 @@ void F() [Fact] public void Lambdas_Update_Accessing_Closure4() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void G(Func f) {} - - int x = 0; // Group #0 - - void F() - { - { int x0 = 0, y0 = 0; // Group #0 - { int x1 = 0, y1 = 0; // Group #1 - - G(a => x + x0); - G(a => x0); - G(a => y0); - G(a => x1); - G(a => y1); + using System; + + class C + { + void G(Func f) {} + + int x = 0; // Group #0 + + void F() + { + { int x0 = 0, y0 = 0; // Group #0 + { int x1 = 0, y1 = 0; // Group #1 + + G(a => x + x0); + G(a => x0); + G(a => y0); + G(a => x1); + G(a => y1); + } + } + } } - } - } -} -"; - var src2 = @" -using System; -class C -{ - void G(Func f) {} - int x = 0; // Group #0 + """; + var src2 = """ - void F() - { - { int x0 = 0, y0 = 0; // Group #0 - { int x1 = 0, y1 = 0; // Group #1 - - G(a => x); // error: disconnecting previously connected closures - G(a => x0); - G(a => y0); - G(a => x1); - G(a => y1 + x0); // error: connecting previously disconnected closures + using System; + + class C + { + void G(Func f) {} + int x = 0; // Group #0 + + void F() + { + { int x0 = 0, y0 = 0; // Group #0 + { int x1 = 0, y1 = 0; // Group #1 + + G(a => x); // error: disconnecting previously connected closures + G(a => x0); + G(a => y0); + G(a => x1); + G(a => y1 + x0); // error: connecting previously disconnected closures + } + } + } } - } - } -} -"; + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -6014,48 +6452,52 @@ void F() [Fact] public void Lambdas_Update_Accessing_Closure_NestedLambdas() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void G(Func> f) {} + using System; - void F() - { - { int x0 = 0; // Group #0 - { int x1 = 0; // Group #1 - - G(a => b => x0); - G(a => b => x1); + class C + { + void G(Func> f) {} + + void F() + { + { int x0 = 0; // Group #0 + { int x1 = 0; // Group #1 + + G(a => b => x0); + G(a => b => x1); + } + } + } } - } - } -} -"; - var src2 = @" -using System; -class C -{ - void G(Func> f) {} + """; + var src2 = """ - void F() - { - { int x0 = 0; // Group #0 - { int x1 = 0; // Group #1 - - G(a => b => x0); - G(a => b => x1); + using System; + + class C + { + void G(Func> f) {} - G(a => b => x0); // ok - G(a => b => x1); // ok - G(a => b => x0 + x1); // runtime rude edit + void F() + { + { int x0 = 0; // Group #0 + { int x1 = 0; // Group #1 + + G(a => b => x0); + G(a => b => x1); + + G(a => b => x0); // ok + G(a => b => x1); // ok + G(a => b => x0 + x1); // runtime rude edit + } + } + } } - } - } -} -"; + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)], @@ -6065,28 +6507,32 @@ void F() [Fact] public void Lambdas_CapturedLocal_Rename() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static void F() - { - int x = 1; - Func f = () => x; - } -}"; - var src2 = @" -using System; - -class C -{ - static void F() - { - int X = 1; - Func f = () => X; - } -}"; + using System; + + class C + { + static void F() + { + int x = 1; + Func f = () => x; + } + } + """; + var src2 = """ + + using System; + + class C + { + static void F() + { + int X = 1; + Func f = () => X; + } + } + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -6101,28 +6547,32 @@ static void F() [Fact] public void Lambdas_CapturedLocal_ChangeType() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static void F() - { - int x = 1; - Func f = () => x; - } -}"; - var src2 = @" -using System; - -class C -{ - static void F() - { - byte x = 1; - Func f = () => x; - } -}"; + using System; + + class C + { + static void F() + { + int x = 1; + Func f = () => x; + } + } + """; + var src2 = """ + + using System; + + class C + { + static void F() + { + byte x = 1; + Func f = () => x; + } + } + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -6138,26 +6588,30 @@ static void F() [Fact] public void Lambdas_CapturedParameter_Rename_BlockBody() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static void F(int x) - { - Func f = () => x; - } -}"; - var src2 = @" -using System; - -class C -{ - static void F(int X) - { - Func f = () => X; - } -}"; + using System; + + class C + { + static void F(int x) + { + Func f = () => x; + } + } + """; + var src2 = """ + + using System; + + class C + { + static void F(int X) + { + Func f = () => X; + } + } + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -6173,22 +6627,26 @@ static void F(int X) [Fact] public void Lambdas_CapturedParameter_Rename_ExpressionBody() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static void G(Func f) {} - static void F(int x) => G(() => x); -}"; - var src2 = @" -using System; + using System; -class C -{ - static void G(Func f) {} - static void F(int X) => G(() => X); -}"; + class C + { + static void G(Func f) {} + static void F(int x) => G(() => x); + } + """; + var src2 = """ + + using System; + + class C + { + static void G(Func f) {} + static void F(int X) => G(() => X); + } + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -6204,32 +6662,36 @@ static void G(Func f) {} [Fact] public void Lambdas_CapturedParameter_Rename_Lambda_BlockBody() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static void F() - { - Func f1 = x => - { - Func f2 = () => x; - }; - } -}"; - var src2 = @" -using System; - -class C -{ - static void F() - { - Func f1 = X => - { - Func f2 = () => X; - }; - } -}"; + using System; + + class C + { + static void F() + { + Func f1 = x => + { + Func f2 = () => x; + }; + } + } + """; + var src2 = """ + + using System; + + class C + { + static void F() + { + Func f1 = X => + { + Func f2 = () => X; + }; + } + } + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -6245,30 +6707,34 @@ static void F() [Fact] public void Lambdas_CapturedParameter_Rename_Lambda_ExpressionBody() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static int G(Func f) => 1; + using System; - static void F() - { - Func f1 = x => G(() => x); - } -}"; - var src2 = @" -using System; + class C + { + static int G(Func f) => 1; -class C -{ - static int G(Func f) => 1; + static void F() + { + Func f1 = x => G(() => x); + } + } + """; + var src2 = """ - static void F() - { - Func f1 = X => G(() => X); - } -}"; + using System; + + class C + { + static int G(Func f) => 1; + + static void F() + { + Func f1 = X => G(() => X); + } + } + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -6284,30 +6750,34 @@ static void F() [Fact] public void Lambdas_CapturedParameter_Rename_ConstructorDeclaration() { - var src1 = @" -using System; + var src1 = """ -class B(Func f); + using System; -class C -{ - C(int x, int y) : base(() => x) - { - Func g = () => y; - } -}"; - var src2 = @" -using System; + class B(Func f); + + class C + { + C(int x, int y) : base(() => x) + { + Func g = () => y; + } + } + """; + var src2 = """ -class B(Func f); + using System; -class C -{ - C(int X, int Y) : base(() => X) - { - Func g = () => Y; - } -}"; + class B(Func f); + + class C + { + C(int X, int Y) : base(() => X) + { + Func g = () => Y; + } + } + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -6324,20 +6794,24 @@ class C [Fact] public void Lambdas_CapturedParameter_Rename_PrimaryConstructorDeclaration() { - var src1 = @" -using System; + var src1 = """ + + using System; + + class B(Func f); + + class C(int x) : B(() => x); -class B(Func f); + """; + var src2 = """ -class C(int x) : B(() => x); -"; - var src2 = @" -using System; + using System; -class B(Func f); + class B(Func f); -class C(int X) : B(() => X); -"; + class C(int X) : B(() => X); + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -6353,26 +6827,30 @@ class B(Func f); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68708")] public void Lambdas_CapturedParameter_ChangeType() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static void F(int x) - { - Func f = () => x; - } -}"; - var src2 = @" -using System; + using System; -class C -{ - static void F(byte x) - { - Func f = () => x; - } -}"; + class C + { + static void F(int x) + { + Func f = () => x; + } + } + """; + var src2 = """ + + using System; + + class C + { + static void F(byte x) + { + Func f = () => x; + } + } + """; var edits = GetTopEdits(src1, src2); @@ -6387,22 +6865,26 @@ static void F(byte x) [Fact] public void Lambdas_CapturedParameter_ChangeType_Indexer1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - Func this[int a] { get => () => a; } -} -"; - var src2 = @" -using System; + using System; -class C -{ - Func this[byte a] => () => a; -} -"; + class C + { + Func this[int a] { get => () => a; } + } + + """; + var src2 = """ + + using System; + + class C + { + Func this[byte a] => () => a; + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -6418,22 +6900,26 @@ class C [Fact] public void Lambdas_CapturedParameter_ChangeType_Indexer_NoBodyChange() { - var src1 = @" -using System; + var src1 = """ -class C -{ - Func this[int a ] => () => a; -} -"; - var src2 = @" -using System; + using System; -class C -{ - Func this[byte a] => () => a; -} -"; + class C + { + Func this[int a ] => () => a; + } + + """; + var src2 = """ + + using System; + + class C + { + Func this[byte a] => () => a; + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -6449,28 +6935,32 @@ class C [Fact] public void Lambdas_ReorderCapturedParameters() { - var src1 = @" -using System; -using System.Diagnostics; + var src1 = """ -class Program -{ - static void Main(int x, int y) - { - Func f = () => x + y; - } -}"; - var src2 = @" -using System; -using System.Diagnostics; + using System; + using System.Diagnostics; -class Program -{ - static void Main(int y, int x) - { - Func f = () => x + y; - } -}"; + class Program + { + static void Main(int x, int y) + { + Func f = () => x + y; + } + } + """; + var src2 = """ + + using System; + using System.Diagnostics; + + class Program + { + static void Main(int y, int x) + { + Func f = () => x + y; + } + } + """; var edits = GetTopEdits(src1, src2); @@ -6529,18 +7019,22 @@ public void Lambdas_Parameter_To_Discard3() [Fact] public void Lambdas_StackAlloc_Update() { - var src1 = @" -using System; -class C -{ - Delegate F() => () => { Span s = stackalloc int[10]; }; -}"; - var src2 = @" -using System; -class C -{ - Delegate F() => () => { Span s = stackalloc int[20]; }; -}"; + var src1 = """ + + using System; + class C + { + Delegate F() => () => { Span s = stackalloc int[10]; }; + } + """; + var src2 = """ + + using System; + class C + { + Delegate F() => () => { Span s = stackalloc int[20]; }; + } + """; var edits = GetTopEdits(src1, src2); @@ -6551,18 +7045,22 @@ class C [Fact] public void Lambdas_StackAlloc_Insert() { - var src1 = @" -using System; -class C -{ - Delegate F() => () => { }; -}"; - var src2 = @" -using System; -class C -{ - Delegate F() => () => { Span s = stackalloc int[10]; }; -}"; + var src1 = """ + + using System; + class C + { + Delegate F() => () => { }; + } + """; + var src2 = """ + + using System; + class C + { + Delegate F() => () => { Span s = stackalloc int[10]; }; + } + """; var edits = GetTopEdits(src1, src2); @@ -6573,18 +7071,22 @@ class C [Fact] public void Lambdas_StackAlloc_Delete() { - var src1 = @" -using System; -class C -{ - Delegate F() => () => { Span s = stackalloc int[10]; }; -}"; - var src2 = @" -using System; -class C -{ - Delegate F() => () => { }; -}"; + var src1 = """ + + using System; + class C + { + Delegate F() => () => { Span s = stackalloc int[10]; }; + } + """; + var src2 = """ + + using System; + class C + { + Delegate F() => () => { }; + } + """; var edits = GetTopEdits(src1, src2); @@ -6606,28 +7108,32 @@ public void Lambdas_StackAlloc_UpdateAround() [Fact] public void Lambdas_AsyncModifier_Add() { - var src1 = @" -using System; -using System.Threading.Tasks; + var src1 = """ -class Test -{ - public void F() - { - var f = new Func>(() => Task.FromResult(1)); - } -}"; - var src2 = @" -using System; -using System.Threading.Tasks; + using System; + using System.Threading.Tasks; -class Test -{ - public void F() - { - var f = new Func>(async () => 1); - } -}"; + class Test + { + public void F() + { + var f = new Func>(() => Task.FromResult(1)); + } + } + """; + var src2 = """ + + using System; + using System.Threading.Tasks; + + class Test + { + public void F() + { + var f = new Func>(async () => 1); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( [Diagnostic(RudeEditKind.MakeMethodAsyncNotSupportedByRuntime, "()")], @@ -6813,27 +7319,31 @@ public void LocalFunctions_Update_ParameterRefness_NoBodyChange() [Fact] public void LocalFunctions_Insert_Static() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - int f(int a) => a; - } -} -"; + class C + { + void F() + { + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + int f(int a) => a; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -6843,27 +7353,31 @@ void F() [Fact] public void LocalFunctions_Insert_Static_InGenericContext_Method() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - int f(int a) => a; - } -} -"; + class C + { + void F() + { + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + int f(int a) => a; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -6883,27 +7397,31 @@ void F() [Fact] public void LocalFunctions_Insert_Static_InGenericContext_Type() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - int f(int a) => a; - } -} -"; + class C + { + void F() + { + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + int f(int a) => a; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -6923,39 +7441,43 @@ void F() [Fact] public void LocalFunctions_Insert_Static_InGenericContext_LocalFunction() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - void L() - { - void M() + using System; + + class C { + void F() + { + void L() + { + void M() + { + } + } + } } - } - } -} -"; - var src2 = @" -using System; -class C -{ - void F() - { - void L() - { - void M() + """; + var src2 = """ + + using System; + + class C { - int f(int a) => a; + void F() + { + void L() + { + void M() + { + int f(int a) => a; + } + } + } } - } - } -} -"; + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -6975,35 +7497,39 @@ void M() [Fact] public void LocalFunctions_Insert_Static_Nested_ExpressionBodies() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static int G(Func f) => 0; - - void F() - { - int localF(int a) => a; - G(localF); - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - static int G(Func f) => 0; + class C + { + static int G(Func f) => 0; + + void F() + { + int localF(int a) => a; + G(localF); + } + } - void F() - { - int localF(int a) => a; - int localG(int a) => G(localF) + a; - G(localG); - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + static int G(Func f) => 0; + + void F() + { + int localF(int a) => a; + int localG(int a) => G(localF) + a; + G(localG); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -7013,35 +7539,39 @@ void F() [Fact] public void LocalFunctions_Insert_Static_Nested_BlockBodies() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static int G(Func f) => 0; - - void F() - { - int localF(int a) { return a; } - G(localF); - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - static int G(Func f) => 0; + class C + { + static int G(Func f) => 0; + + void F() + { + int localF(int a) { return a; } + G(localF); + } + } - void F() - { - int localF(int a) { return a; } - int localG(int a) { return G(localF) + a; } - G(localG); - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + static int G(Func f) => 0; + + void F() + { + int localF(int a) { return a; } + int localG(int a) { return G(localF) + a; } + G(localG); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -7051,33 +7581,37 @@ void F() [Fact] public void LocalFunctions_LocalFunction_Replace_Lambda() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static int G(Func f) => 0; - - void F() - { - G(a => a); - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - static int G(Func f) => 0; + class C + { + static int G(Func f) => 0; + + void F() + { + G(a => a); + } + } - void F() - { - int localF(int a) { return a; } - G(localF); - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + static int G(Func f) => 0; + + void F() + { + int localF(int a) { return a; } + G(localF); + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -7093,33 +7627,37 @@ void F() [Fact] public void LocalFunctions_Lambda_Replace_LocalFunction() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static int G(Func f) => 0; + using System; - void F() - { - int localF(int a) { return a; } - G(localF); - } -} -"; - var src2 = @" -using System; + class C + { + static int G(Func f) => 0; -class C -{ - static int G(Func f) => 0; - - void F() - { - G(a => a); - } -} -"; + void F() + { + int localF(int a) { return a; } + G(localF); + } + } + + """; + var src2 = """ + + using System; + + class C + { + static int G(Func f) => 0; + + void F() + { + G(a => a); + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -7134,31 +7672,35 @@ void F() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ThisOnly_Top1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int x = 0; + using System; - void F() - { - } -} -"; - var src2 = @" -using System; + class C + { + int x = 0; -class C -{ - int x = 0; + void F() + { + } + } - void F() - { - int G(int a) => x; - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + int x = 0; + + void F() + { + int G(int a) => x; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -7169,39 +7711,43 @@ void F() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1291"), WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ThisOnly_Top2() { - var src1 = @" -using System; -using System.Linq; + var src1 = """ -class C -{ - void F() - { - int y = 1; - { - int x = 2; - int f1(int a) => y; - } - } -} -"; - var src2 = @" -using System; -using System.Linq; + using System; + using System.Linq; -class C -{ - void F() - { - int y = 1; - { - int x = 2; - var f2 = from a in new[] { 1 } select a + y; - var f3 = from a in new[] { 1 } where x > 0 select a; - } - } -} -"; + class C + { + void F() + { + int y = 1; + { + int x = 2; + int f1(int a) => y; + } + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + + class C + { + void F() + { + int y = 1; + { + int x = 2; + var f2 = from a in new[] { 1 } select a + y; + var f3 = from a in new[] { 1 } where x > 0 select a; + } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -7212,38 +7758,42 @@ void F() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ThisOnly_Nested1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int x = 0; - int G(Func f) => 0; + using System; - void F() - { - int f(int a) => a; - G(f); - } -} -"; - var src2 = @" -using System; + class C + { + int x = 0; + int G(Func f) => 0; -class C -{ - int x = 0; - int G(Func f) => 0; + void F() + { + int f(int a) => a; + G(f); + } + } - void F() - { - int f(int a) => x; - int g(int a) => G(f); - G(g); - } -} -"; - var edits = GetTopEdits(src1, src2); + """; + var src2 = """ + + using System; + + class C + { + int x = 0; + int G(Func f) => 0; + + void F() + { + int f(int a) => x; + int g(int a) => G(f); + G(g); + } + } + + """; + var edits = GetTopEdits(src1, src2); edits.VerifySemantics( [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)], capabilities: EditAndContinueCapabilities.AddMethodToExistingType | EditAndContinueCapabilities.NewTypeDefinition); @@ -7252,53 +7802,57 @@ void F() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ThisOnly_Nested2() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int x = 0; + using System; - void F() - { - int f1(int a) - { - int f2(int b) + class C { - return b; - }; + int x = 0; - return a; - }; - } -} -"; - var src2 = @" -using System; + void F() + { + int f1(int a) + { + int f2(int b) + { + return b; + }; + + return a; + }; + } + } -class C -{ - int x = 0; + """; + var src2 = """ - void F() - { - int f1(int a) - { - int f2(int b) - { - return b; - }; + using System; - int f3(int c) + class C { - return c + x; - }; + int x = 0; - return a; - }; - } -} -"; + void F() + { + int f1(int a) + { + int f2(int b) + { + return b; + }; + + int f3(int c) + { + return c + x; + }; + + return a; + }; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -7309,69 +7863,73 @@ int f3(int c) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_InsertAndDelete_Scopes1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void G(Func f) {} + using System; + + class C + { + void G(Func f) {} - int x = 0, y = 0; // Group #0 + int x = 0, y = 0; // Group #0 - void F() - { - int x0 = 0, y0 = 0; // Group #1 + void F() + { + int x0 = 0, y0 = 0; // Group #1 - { int x1 = 0, y1 = 0; // Group #2 + { int x1 = 0, y1 = 0; // Group #2 - { int x2 = 0, y2 = 0; // Group #1 + { int x2 = 0, y2 = 0; // Group #1 - { int x3 = 0, y3 = 0; // Group #2 + { int x3 = 0, y3 = 0; // Group #2 - int f1(int a) => x3 + x1; - int f2(int a) => x0 + y0 + x2; - int f3(int a) => x; + int f1(int a) => x3 + x1; + int f2(int a) => x0 + y0 + x2; + int f3(int a) => x; + } + } + } } } - } - } -} -"; - var src2 = @" -using System; -class C -{ - void G(Func f) {} + """; + var src2 = """ - int x = 0, y = 0; // Group #0 + using System; - void F() - { - int x0 = 0, y0 = 0; // Group #1 + class C + { + void G(Func f) {} + + int x = 0, y = 0; // Group #0 + + void F() + { + int x0 = 0, y0 = 0; // Group #1 - { int x1 = 0, y1 = 0; // Group #2 + { int x1 = 0, y1 = 0; // Group #2 - { int x2 = 0, y2 = 0; // Group #1 + { int x2 = 0, y2 = 0; // Group #1 - { int x3 = 0, y3 = 0; // Group #2 + { int x3 = 0, y3 = 0; // Group #2 - int f1(int a) => x3 + x1; - int f2(int a) => x0 + y0 + x2; - int f3(int a) => x; + int f1(int a) => x3 + x1; + int f2(int a) => x0 + y0 + x2; + int f3(int a) => x; - int f4(int a) => x; // OK - int f5(int a) => x0 + y0; // OK - int f6(int a) => x1 + y0; // runtime rude edit - connecting Group #1 and Group #2 - int f7(int a) => x3 + x1; // runtime rude edit - multi-scope (conservative) - int f8(int a) => x + y0; // runtime rude edit - connecting Group #0 and Group #1 - int f9(int a) => x + x3; // runtime rude edit - connecting Group #0 and Group #2 + int f4(int a) => x; // OK + int f5(int a) => x0 + y0; // OK + int f6(int a) => x1 + y0; // runtime rude edit - connecting Group #1 and Group #2 + int f7(int a) => x3 + x1; // runtime rude edit - multi-scope (conservative) + int f8(int a) => x + y0; // runtime rude edit - connecting Group #0 and Group #1 + int f9(int a) => x + x3; // runtime rude edit - connecting Group #0 and Group #2 + } + } + } } } - } - } -} -"; + + """; var insert = GetTopEdits(src1, src2); insert.VerifySemantics( [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)], @@ -7386,46 +7944,50 @@ void F() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ForEach1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void G(Func f) {} + using System; - void F() - { - foreach (int x0 in new[] { 1 }) // Group #0 - { // Group #1 - int x1 = 0; + class C + { + void G(Func f) {} - int f0(int a) => x0; - int f1(int a) => x1; - } - } -} -"; - var src2 = @" -using System; + void F() + { + foreach (int x0 in new[] { 1 }) // Group #0 + { // Group #1 + int x1 = 0; -class C -{ - void G(Func f) {} + int f0(int a) => x0; + int f1(int a) => x1; + } + } + } - void F() - { - foreach (int x0 in new[] { 1 }) // Group #0 - { // Group #1 - int x1 = 0; + """; + var src2 = """ - int f0(int a) => x0; - int f1(int a) => x1; + using System; - int f2(int a) => x0 + x1; // runtime rude edit: connecting previously disconnected closures - } - } -} -"; + class C + { + void G(Func f) {} + + void F() + { + foreach (int x0 in new[] { 1 }) // Group #0 + { // Group #1 + int x1 = 0; + + int f0(int a) => x0; + int f1(int a) => x1; + + int f2(int a) => x0 + x1; // runtime rude edit: connecting previously disconnected closures + } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)], @@ -7435,71 +7997,75 @@ void F() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_Switch1() { - var src1 = @" -using System; - -class C -{ - bool G(Func f) => true; - - int a = 1; + var src1 = """ - void F() - { - int x2 = 1; - int f2() => x2; + using System; - switch (a) - { - case 1: - int x0 = 1; - int f0() => x0; - break; - - case 2: - int x1 = 1; - int f1() => x1; - break; - } - } -} -"; - var src2 = @" -using System; + class C + { + bool G(Func f) => true; + + int a = 1; + + void F() + { + int x2 = 1; + int f2() => x2; + + switch (a) + { + case 1: + int x0 = 1; + int f0() => x0; + break; + + case 2: + int x1 = 1; + int f1() => x1; + break; + } + } + } -class C -{ - bool G(Func f) => true; + """; + var src2 = """ - int a = 1; + using System; - void F() - { - int x2 = 1; - int f2() => x2; + class C + { + bool G(Func f) => true; + + int a = 1; + + void F() + { + int x2 = 1; + int f2() => x2; + + switch (a) + { + case 1: + int x0 = 1; + int f0() => x0; + goto case 2; + + case 2: + int x1 = 1; + int f1() => x1; + goto default; + + default: + x0 = 1; + x1 = 2; + int f01() => x0 + x1; // ok + int f02() => x0 + x2; // runtime rude edit + break; + } + } + } - switch (a) - { - case 1: - int x0 = 1; - int f0() => x0; - goto case 2; - - case 2: - int x1 = 1; - int f1() => x1; - goto default; - - default: - x0 = 1; - x1 = 2; - int f01() => x0 + x1; // ok - int f02() => x0 + x2; // runtime rude edit - break; - } - } -} -"; + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)], @@ -7509,47 +8075,51 @@ void F() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_Catch1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static void F() - { - try - { - } - catch (Exception x0) - { - int x1 = 1; - int f0() => x0; - int f1() => x1; - } - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - static void F() - { - try - { - } - catch (Exception x0) - { - int x1 = 1; - int f0() => x0; - int f1() => x1; + class C + { + static void F() + { + try + { + } + catch (Exception x0) + { + int x1 = 1; + int f0() => x0; + int f1() => x1; + } + } + } - int f00() => x0; //ok - int f01() => F(x0, x1); // runtime rude edit - } - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + static void F() + { + try + { + } + catch (Exception x0) + { + int x1 = 1; + int f0() => x0; + int f1() => x1; + + int f00() => x0; //ok + int f01() => F(x0, x1); // runtime rude edit + } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)], @@ -7559,29 +8129,33 @@ static void F() [Fact] public void LocalFunctions_Insert_NotSupported() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - void M() - { - } - } -} -"; + class C + { + void F() + { + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + void M() + { + } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -7592,32 +8166,36 @@ void M() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_This() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int x = 1; + using System; - void F() - { - int f(int a) => a + x; - } -} -"; - var src2 = @" -using System; + class C + { + int x = 1; -class C -{ - int x = 1; + void F() + { + int f(int a) => a + x; + } + } - void F() - { - int f(int a) => a; - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + int x = 1; + + void F() + { + int f(int a) => a; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -7626,28 +8204,32 @@ void F() [Fact] public void LocalFunctions_Update_Signature1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - int f(int a) => a; - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - long f(long a) => a; - } -} -"; + class C + { + void F() + { + int f(int a) => a; + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + long f(long a) => a; + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -7663,28 +8245,32 @@ void F() [Fact] public void LocalFunctions_Update_Signature2() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - int f(int a) => a; - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - int f(int a, int b) => a + b; - } -} -"; + class C + { + void F() + { + int f(int a) => a; + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + int f(int a, int b) => a + b; + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -7700,34 +8286,38 @@ void F() [Fact] public void LocalFunctions_Update_Signature3() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - int f(int a) => a; - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - long f(int a) => a; - } -} -"; - var edits = GetTopEdits(src1, src2); - var syntaxMap = edits.GetSyntaxMap(); + class C + { + void F() + { + int f(int a) => a; + } + } - edits.VerifySemantics( - [ - SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), syntaxMap, rudeEdits: + """; + var src2 = """ + + using System; + + class C + { + void F() + { + long f(int a) => a; + } + } + + """; + var edits = GetTopEdits(src1, src2); + var syntaxMap = edits.GetSyntaxMap(); + + edits.VerifySemantics( + [ + SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), syntaxMap, rudeEdits: [ RuntimeRudeEdit(0, RudeEditKind.ChangingLambdaReturnType, syntaxMap.Position(0), [GetResource("local function")]) ]) @@ -7737,28 +8327,32 @@ void F() [Fact] public void LocalFunctions_Update_Signature_ReturnType1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - int f(int a) { return 1; } - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - void f(int a) { } - } -} -"; + class C + { + void F() + { + int f(int a) { return 1; } + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + void f(int a) { } + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -7774,31 +8368,35 @@ void F() [Fact] public void LocalFunctions_Update_Signature_BodySyntaxOnly() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - int f(int a) => a; - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void G1(Func f) {} - void G2(Func f) {} + class C + { + void F() + { + int f(int a) => a; + } + } - void F() - { - int f(int a) { return a; } - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + void G1(Func f) {} + void G2(Func f) {} + + void F() + { + int f(int a) { return a; } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -7808,28 +8406,32 @@ void F() [Fact] public void LocalFunctions_Update_Signature_ParameterName1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - int f(int a) => 1; - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - int f(int b) => 2; - } -} -"; + class C + { + void F() + { + int f(int a) => 1; + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + int f(int b) => 2; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); @@ -7838,28 +8440,32 @@ void F() [Fact] public void LocalFunctions_Update_Signature_ParameterRefness1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - int f(ref int a) => 1; - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - int f(int a) => 2; - } -} -"; + class C + { + void F() + { + int f(ref int a) => 1; + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + int f(int a) => 2; + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -7875,28 +8481,32 @@ void F() [Fact] public void LocalFunctions_Update_Signature_ParameterRefness2() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - int f(out int a) => 1; - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - int f(ref int a) => 2; - } -} -"; + class C + { + void F() + { + int f(out int a) => 1; + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + int f(ref int a) => 2; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -7905,28 +8515,32 @@ void F() [Fact] public void LocalFunctions_Update_Signature_ParameterRefness3() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - int f(ref int a) => 1; - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - int f(out int a) => 1; - } -} -"; + class C + { + void F() + { + int f(ref int a) => 1; + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + int f(out int a) => 1; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -7935,28 +8549,32 @@ void F() [Fact] public void LocalFunctions_Signature_SemanticErrors() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - Unknown f(Unknown a) => 1; - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - Unknown f(Unknown a) => 2; - } -} -"; + class C + { + void F() + { + Unknown f(Unknown a) => 1; + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + Unknown f(Unknown a) => 2; + } + } + + """; var edits = GetTopEdits(src1, src2); // There are semantics errors in the case. The errors are captured during the emit execution. @@ -7966,36 +8584,40 @@ void F() [Fact] public void LocalFunctions_Update_CapturedParameters1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F(int x1) - { - int f1(int a1, int a2) - { - int f2(int a3) => x1 + a2; - return a1; - }; - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F(int x1) - { - int f1(int a1, int a2) - { - int f2(int a3) => x1 + a2 + 1; - return a1; - }; - } -} -"; + class C + { + void F(int x1) + { + int f1(int a1, int a2) + { + int f2(int a3) => x1 + a2; + return a1; + }; + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F(int x1) + { + int f1(int a1, int a2) + { + int f2(int a3) => x1 + a2 + 1; + return a1; + }; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); @@ -8004,48 +8626,52 @@ int f1(int a1, int a2) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2223")] public void LocalFunctions_Update_CapturedParameters2() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F(int x1) - { - int f1(int a1, int a2) - { - int f2(int a3) => x1 + a2; - return a1; - }; + using System; - int f3(int a1, int a2) - { - int f4(int a3) => x1 + a2; - return a1; - }; - } -} -"; - var src2 = @" -using System; + class C + { + void F(int x1) + { + int f1(int a1, int a2) + { + int f2(int a3) => x1 + a2; + return a1; + }; + + int f3(int a1, int a2) + { + int f4(int a3) => x1 + a2; + return a1; + }; + } + } -class C -{ - void F(int x1) - { - int f1(int a1, int a2) - { - int f2(int a3) => x1 + a2 + 1; - return a1; - }; + """; + var src2 = """ - int f3(int a1, int a2) - { - int f4(int a3) => x1 + a2 + 1; - return a1; - }; - } -} -"; + using System; + + class C + { + void F(int x1) + { + int f1(int a1, int a2) + { + int f2(int a3) => x1 + a2 + 1; + return a1; + }; + + int f3(int a1, int a2) + { + int f4(int a3) => x1 + a2 + 1; + return a1; + }; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); @@ -8054,39 +8680,43 @@ int f3(int a1, int a2) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_Closure1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - int y = 1; - int f1(int a1) - { - int f2(int a2) => y + a2; - return a1; - }; - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - int y = 1; - int f1(int a1) - { - int f2(int a2) => a2; - return a1 + y; - }; - } -} -"; - var edits = GetTopEdits(src1, src2); + class C + { + void F() + { + int y = 1; + int f1(int a1) + { + int f2(int a2) => y + a2; + return a1; + }; + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + int y = 1; + int f1(int a1) + { + int f2(int a2) => a2; + return a1 + y; + }; + } + } + + """; + var edits = GetTopEdits(src1, src2); // y is no longer captured in f2 edits.VerifySemantics( @@ -8096,22 +8726,26 @@ int f1(int a1) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_IndexerParameter() { - var src1 = @" -using System; + var src1 = """ -class C -{ - Func this[int a1, int a2] { get { int f(int a3) => a1 + a2; return f; } } -} -"; - var src2 = @" -using System; + using System; -class C -{ - Func this[int a1, int a2] { get { int f(int a3) => a2; return f; } } -} -"; + class C + { + Func this[int a1, int a2] { get { int f(int a3) => a1 + a2; return f; } } + } + + """; + var src2 = """ + + using System; + + class C + { + Func this[int a1, int a2] { get { int f(int a3) => a2; return f; } } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: true)); @@ -8120,28 +8754,32 @@ class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_MethodParameter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F(int a1, int a2) - { - int f2(int a3) => a1 + a2; - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F(int a1, int a2) - { - int f2(int a3) => a1; - } -} -"; + class C + { + void F(int a1, int a2) + { + int f2(int a3) => a1 + a2; + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F(int a1, int a2) + { + int f2(int a3) => a1; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -8150,36 +8788,40 @@ void F(int a1, int a2) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_LambdaParameter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - int f1(int a1, int a2) - { - int f2(int a3) => a1 + a2; - return a1; - }; - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - int f1(int a1, int a2) - { - int f2(int a3) => a2; - return a1; - }; - } -} -"; + class C + { + void F() + { + int f1(int a1, int a2) + { + int f2(int a3) => a1 + a2; + return a1; + }; + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + int f1(int a1, int a2) + { + int f2(int a3) => a2; + return a1; + }; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -8188,30 +8830,34 @@ int f1(int a1, int a2) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_SetterValueParameter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int D - { - get { return 0; } - set { void f() { Console.Write(value); } f(); } - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - int D - { - get { return 0; } - set { } - } -} -"; + class C + { + int D + { + get { return 0; } + set { void f() { Console.Write(value); } f(); } + } + } + + """; + var src2 = """ + + using System; + + class C + { + int D + { + get { return 0; } + set { } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_D"))); @@ -8220,30 +8866,34 @@ int D [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_IndexerSetterValueParameter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int this[int a1, int a2] - { - get { return 0; } - set { void f() { Console.Write(value); } f(); } - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - int this[int a1, int a2] - { - get { return 0; } - set { } - } -} -"; + class C + { + int this[int a1, int a2] + { + get { return 0; } + set { void f() { Console.Write(value); } f(); } + } + } + + """; + var src2 = """ + + using System; + + class C + { + int this[int a1, int a2] + { + get { return 0; } + set { } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"))); @@ -8252,30 +8902,34 @@ class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_EventAdderValueParameter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - event Action D - { - add { void f() { Console.Write(value); } f(); } - remove { } - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - event Action D - { - add { } - remove { } - } -} -"; + class C + { + event Action D + { + add { void f() { Console.Write(value); } f(); } + remove { } + } + } + + """; + var src2 = """ + + using System; + + class C + { + event Action D + { + add { } + remove { } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.add_D"))); @@ -8284,30 +8938,34 @@ event Action D [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_EventRemoverValueParameter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - event Action D - { - add { } - remove { void f() { Console.Write(value); } f(); } - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - event Action D - { - add { } - remove { } - } -} -"; + class C + { + event Action D + { + add { } + remove { void f() { Console.Write(value); } f(); } + } + } + + """; + var src2 = """ + + using System; + + class C + { + event Action D + { + add { } + remove { } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.remove_D"))); @@ -8316,37 +8974,41 @@ event Action D [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_DeleteCapture1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - int y = 1; - int f1(int a1) - { - int f2(int a2) => y + a2; - return y; - }; - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { // error - int f1(int a1) - { - int f2(int a2) => a2; - return a1; - }; - } -} -"; + class C + { + void F() + { + int y = 1; + int f1(int a1) + { + int f2(int a2) => y + a2; + return y; + }; + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { // error + int f1(int a1) + { + int f2(int a2) => a2; + return a1; + }; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -8356,22 +9018,26 @@ int f1(int a1) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_IndexerGetterParameter2() { - var src1 = @" -using System; + var src1 = """ -class C -{ - Func this[int a1, int a2] { get { int f(int a3) => a2; return f; } } -} -"; - var src2 = @" -using System; + using System; -class C -{ - Func this[int a1, int a2] { get { int f(int a3) => a1 + a2; return f; } } -} -"; + class C + { + Func this[int a1, int a2] { get { int f(int a3) => a2; return f; } } + } + + """; + var src2 = """ + + using System; + + class C + { + Func this[int a1, int a2] { get { int f(int a3) => a1 + a2; return f; } } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -8381,22 +9047,26 @@ class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_IndexerSetterParameter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - Func this[int a1, int a2] { get { return null; } set { int f(int a3) => a2; } } -} -"; - var src2 = @" -using System; + using System; -class C -{ - Func this[int a1, int a2] { get { return null; } set { int f(int a3) => a1 + a2; } } -} -"; + class C + { + Func this[int a1, int a2] { get { return null; } set { int f(int a3) => a2; } } + } + + """; + var src2 = """ + + using System; + + class C + { + Func this[int a1, int a2] { get { return null; } set { int f(int a3) => a1 + a2; } } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -8406,30 +9076,34 @@ class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_IndexerSetterValueParameter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int this[int a1, int a2] - { - get { return 0; } - set { } - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - int this[int a1, int a2] - { - get { return 0; } - set { void f() { Console.Write(value); } f(); } - } -} -"; + class C + { + int this[int a1, int a2] + { + get { return 0; } + set { } + } + } + + """; + var src2 = """ + + using System; + + class C + { + int this[int a1, int a2] + { + get { return 0; } + set { void f() { Console.Write(value); } f(); } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: true)], @@ -8439,30 +9113,34 @@ class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_EventAdderValueParameter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - event Action D - { - add { } - remove { } - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - event Action D - { - add { } - remove { void f() { Console.Write(value); } f(); } - } -} -"; + class C + { + event Action D + { + add { } + remove { } + } + } + + """; + var src2 = """ + + using System; + + class C + { + event Action D + { + add { } + remove { void f() { Console.Write(value); } f(); } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.remove_D"), preserveLocalVariables: true)], @@ -8472,30 +9150,34 @@ event Action D [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_EventRemoverValueParameter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - event Action D - { - add { } - remove { } - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - event Action D - { - add { } - remove { void f() { Console.Write(value); } f(); } - } -} -"; + class C + { + event Action D + { + add { } + remove { } + } + } + + """; + var src2 = """ + + using System; + + class C + { + event Action D + { + add { } + remove { void f() { Console.Write(value); } f(); } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.remove_D"), preserveLocalVariables: true)], @@ -8505,28 +9187,32 @@ event Action D [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_MethodParameter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F(int a1, int a2) - { - int f2(int a3) => a1; - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F(int a1, int a2) - { - int f2(int a3) => a1 + a2; - } -} -"; + class C + { + void F(int a1, int a2) + { + int f2(int a3) => a1; + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F(int a1, int a2) + { + int f2(int a3) => a1 + a2; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -8535,36 +9221,40 @@ void F(int a1, int a2) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_LambdaParameter1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - int f1(int a1, int a2) - { - int f2(int a3) => a2; - return a1; - }; - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - int f1(int a1, int a2) - { - int f2(int a3) => a1 + a2; - return a1; - }; - } -} -"; + class C + { + void F() + { + int f1(int a1, int a2) + { + int f2(int a3) => a2; + return a1; + }; + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + int f1(int a1, int a2) + { + int f2(int a3) => a1 + a2; + return a1; + }; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -8573,32 +9263,36 @@ int f1(int a1, int a2) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_StaticToThisOnly1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int x = 1; + using System; - void F() - { - int f(int a) => a; - } -} -"; - var src2 = @" -using System; + class C + { + int x = 1; -class C -{ - int x = 1; + void F() + { + int f(int a) => a; + } + } - void F() - { - int f(int a) => a + x; - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + int x = 1; + + void F() + { + int f(int a) => a + x; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -8607,40 +9301,44 @@ void F() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_StaticToThisOnly_Partial() { - var src1 = @" -using System; + var src1 = """ -partial class C -{ - int x = 1; - partial void F(); // def -} + using System; -partial class C -{ - partial void F() // impl - { - int f(int a) => a; - } -} -"; - var src2 = @" -using System; + partial class C + { + int x = 1; + partial void F(); // def + } -partial class C -{ - int x = 1; - partial void F(); // def -} + partial class C + { + partial void F() // impl + { + int f(int a) => a; + } + } -partial class C -{ - partial void F() // impl - { - int f(int a) => a + x; - } -} -"; + """; + var src2 = """ + + using System; + + partial class C + { + int x = 1; + partial void F(); // def + } + + partial class C + { + partial void F() // impl + { + int f(int a) => a + x; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F").PartialImplementationPart, preserveLocalVariables: true, partialType: "C")); @@ -8649,34 +9347,38 @@ partial void F() // impl [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_StaticToThisOnly3() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int x = 1; + using System; - void F() - { - int f1(int a1) => a1; - int f2(int a2) => a2 + x; - } -} -"; - var src2 = @" -using System; + class C + { + int x = 1; -class C -{ - int x = 1; + void F() + { + int f1(int a1) => a1; + int f2(int a2) => a2 + x; + } + } - void F() - { - int f1(int a1) => a1 + x; - int f2(int a2) => a2 + x; - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + int x = 1; + + void F() + { + int f1(int a1) => a1 + x; + int f2(int a2) => a2 + x; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -8685,38 +9387,42 @@ void F() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_StaticToClosure1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - int x = 1; - int f1(int a1) => a1; - int f2(int a2) => a2 + x; - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - int x = 1; - int f1(int a1) - { - return a1 + - x+ // 1 - x; // 2 - }; + class C + { + void F() + { + int x = 1; + int f1(int a1) => a1; + int f2(int a2) => a2 + x; + } + } - int f2(int a2) => a2 + x; - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + void F() + { + int x = 1; + int f1(int a1) + { + return a1 + + x+ // 1 + x; // 2 + }; + + int f2(int a2) => a2 + x; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -8726,36 +9432,40 @@ int f1(int a1) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_ThisOnlyToClosure1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int x = 1; + using System; - void F() - { - int y = 1; - int f1(int a1) => a1 + x; - int f2(int a2) => a2 + x + y; - } -} -"; - var src2 = @" -using System; + class C + { + int x = 1; -class C -{ - int x = 1; + void F() + { + int y = 1; + int f1(int a1) => a1 + x; + int f2(int a2) => a2 + x + y; + } + } - void F() - { - int y = 1; - int f1(int a1) => a1 + x + y; - int f2(int a2) => a2 + x + y; - } -} -"; + """; + var src2 = """ + + using System; + + class C + { + int x = 1; + + void F() + { + int y = 1; + int f1(int a1) => a1 + x + y; + int f2(int a2) => a2 + x + y; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -8764,38 +9474,42 @@ void F() [Fact] public void LocalFunctions_Update_Nested1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - int y = 1; - int f1(int a1) - { - int f2(int a2) => a2 + y; - return a1; - }; - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - int y = 1; - int f1(int a1) - { - int f2(int a2) => a2 + y; - return a1 + y; - }; - } -} -"; + class C + { + void F() + { + int y = 1; + int f1(int a1) + { + int f2(int a2) => a2 + y; + return a1; + }; + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + int y = 1; + int f1(int a1) + { + int f2(int a2) => a2 + y; + return a1 + y; + }; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); @@ -8804,38 +9518,42 @@ int f1(int a1) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Nested2() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void F() - { - int y = 1; - int f1(int a1) - { - int f2(int a2) => a2; - return a1; - }; - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - void F() - { - int y = 1; - int f1(int a1) - { - int f2(int a2) => a1 + a2; - return a1; - }; - } -} -"; + class C + { + void F() + { + int y = 1; + int f1(int a1) + { + int f2(int a2) => a2; + return a1; + }; + } + } + + """; + var src2 = """ + + using System; + + class C + { + void F() + { + int y = 1; + int f1(int a1) + { + int f2(int a2) => a1 + a2; + return a1; + }; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -8844,28 +9562,32 @@ int f1(int a1) [Fact] public void LocalFunctions_Update_Generic() { - var src1 = @" -class C -{ - void F() - { - int L() => 1; - int M() => 1; - int N() => 1; - int O() => 1; - } -}"; - var src2 = @" -class C -{ - void F() - { - int L() => 1; - int M() => 2; - int N() => 1 ; - int O() => 1; - } -}"; + var src1 = """ + + class C + { + void F() + { + int L() => 1; + int M() => 1; + int N() => 1; + int O() => 1; + } + } + """; + var src2 = """ + + class C + { + void F() + { + int L() => 1; + int M() => 2; + int N() => 1 ; + int O() => 1; + } + } + """; var edits = GetTopEdits(src1, src2); @@ -8882,30 +9604,34 @@ void F() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_RenameCapturedLocal() { - var src1 = @" -using System; -using System.Diagnostics; + var src1 = """ -class C -{ - static void F() - { - int x = 1; - int f() => x; - } -}"; - var src2 = @" -using System; -using System.Diagnostics; - -class C -{ - static void F() - { - int X = 1; - int f() => X; - } -}"; + using System; + using System.Diagnostics; + + class C + { + static void F() + { + int x = 1; + int f() => x; + } + } + """; + var src2 = """ + + using System; + using System.Diagnostics; + + class C + { + static void F() + { + int X = 1; + int f() => X; + } + } + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -8920,31 +9646,35 @@ static void F() capabilities: EditAndContinueCapabilities.AddMethodToExistingType | EditAndContinueCapabilities.NewTypeDefinition); } - [Fact] - public void LocalFunctions_RenameCapturedParameter() - { - var src1 = @" -using System; -using System.Diagnostics; + [Fact] + public void LocalFunctions_RenameCapturedParameter() + { + var src1 = """ + + using System; + using System.Diagnostics; + + class C + { + static void F(int x) + { + int f() => x; + } + } + """; + var src2 = """ + + using System; + using System.Diagnostics; -class C -{ - static void F(int x) - { - int f() => x; - } -}"; - var src2 = @" -using System; -using System.Diagnostics; - -class C -{ - static void F(int X) - { - int f() => X; - } -}"; + class C + { + static void F(int X) + { + int f() => X; + } + } + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -8962,43 +9692,47 @@ static void F(int X) [Fact] public void LocalFunctions_Update() { - var src1 = @" -using System; + var src1 = """ -class C -{ - void M() - { - N(3); - - void N(int x) - { - if (x > 3) + using System; + + class C { - x.ToString(); + void M() + { + N(3); + + void N(int x) + { + if (x > 3) + { + x.ToString(); + } + else + { + N(x - 1); + } + } + } } - else + """; + var src2 = """ + + using System; + + class C { - N(x - 1); + void M() + { + N(3); + + void N(int x) + { + Console.WriteLine("Hello"); + } + } } - } - } -}"; - var src2 = @" -using System; - -class C -{ - void M() - { - N(3); - - void N(int x) - { - Console.WriteLine(""Hello""); - } - } -}"; + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M"), preserveLocalVariables: true)); @@ -9087,38 +9821,42 @@ public void LocalFunction_ReadOnlyRef_ReturnType_Update() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37128")] public void LocalFunction_AddToInterfaceMethod() { - var src1 = @" -using System; -interface I -{ - static int X = M(() => 1); - static int M() => 1; + var src1 = """ - static void F() - { - void g() { } - } -} -"; - var src2 = @" -using System; -interface I -{ - static int X = M(() => { void f3() {} return 2; }); - static int M() => 1; + using System; + interface I + { + static int X = M(() => 1); + static int M() => 1; - static void F() - { - int f1() => 1; - f1(); + static void F() + { + void g() { } + } + } - void g() { void f2() {} f2(); } + """; + var src2 = """ - var l = new Func(() => 1); - l(); - } -} -"; + using System; + interface I + { + static int X = M(() => { void f3() {} return 2; }); + static int M() => 1; + + static void F() + { + int f1() => 1; + f1(); + + void g() { void f2() {} f2(); } + + var l = new Func(() => 1); + l(); + } + } + + """; var edits = GetTopEdits(src1, src2); // lambdas are ok as they are emitted to a nested type @@ -9564,38 +10302,42 @@ public void LocalFunctions_TypeParameter_Constraint_Clause_Add() [Fact] public void LocalFunctions_Stackalloc_Update() { - var src1 = @" -using System; -class C -{ - void F() - { - void L1() - { - Span s = stackalloc int[10]; - } - void L2() - { - Span s = stackalloc int[10]; - } - } -}"; - var src2 = @" -using System; -class C -{ - void F() - { - void L1() - { - Span s = stackalloc int[20]; - } - void L2() - { - Span s = stackalloc int[10 ]; - } - } -}"; + var src1 = """ + + using System; + class C + { + void F() + { + void L1() + { + Span s = stackalloc int[10]; + } + void L2() + { + Span s = stackalloc int[10]; + } + } + } + """; + var src2 = """ + + using System; + class C + { + void F() + { + void L1() + { + Span s = stackalloc int[20]; + } + void L2() + { + Span s = stackalloc int[10 ]; + } + } + } + """; var edits = GetTopEdits(src1, src2); @@ -9606,29 +10348,33 @@ void L2() [Fact] public void LocalFunctions_Stackalloc_Insert() { - var src1 = @" -using System; -class C -{ - void F() - { - void L1() - { - } - } -}"; - var src2 = @" -using System; -class C -{ - void F() - { - void L1() - { - Span s = stackalloc int[10]; - } - } -}"; + var src1 = """ + + using System; + class C + { + void F() + { + void L1() + { + } + } + } + """; + var src2 = """ + + using System; + class C + { + void F() + { + void L1() + { + Span s = stackalloc int[10]; + } + } + } + """; var edits = GetTopEdits(src1, src2); @@ -9639,29 +10385,33 @@ void L1() [Fact] public void LocalFunctions_Stackalloc_Delete() { - var src1 = @" -using System; -class C -{ - void F() - { - void L1() - { - Span s = stackalloc int[10]; - } - } -}"; - var src2 = @" -using System; -class C -{ - void F() - { - void L1() - { - } - } -}"; + var src1 = """ + + using System; + class C + { + void F() + { + void L1() + { + Span s = stackalloc int[10]; + } + } + } + """; + var src2 = """ + + using System; + class C + { + void F() + { + void L1() + { + } + } + } + """; var edits = GetTopEdits(src1, src2); @@ -9672,40 +10422,44 @@ void L1() [Fact] public void LocalFunctions_Stackalloc_InNestedLocalFunction() { - var src1 = @" -using System; -class C -{ - void F() - { - void L() - { - void M() + var src1 = """ + + using System; + class C { - Span s = stackalloc int[10]; + void F() + { + void L() + { + void M() + { + Span s = stackalloc int[10]; + } + + Console.WriteLine(1); + } + } } + """; + var src2 = """ - Console.WriteLine(1); - } - } -}"; - var src2 = @" -using System; -class C -{ - void F() - { - void L() - { - void M() + using System; + class C { - Span s = stackalloc int[10]; + void F() + { + void L() + { + void M() + { + Span s = stackalloc int[10]; + } + + Console.WriteLine(2); + } + } } - - Console.WriteLine(2); - } - } -}"; + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); @@ -9714,29 +10468,33 @@ void M() [Fact] public void LocalFunctions_AsyncModifier_Add() { - var src1 = @" -class Test -{ - public void F() - { - Task WaitAsync() - { - return 1; - } - } -}"; - var src2 = @" -class Test -{ - public void F() - { - async Task WaitAsync() - { - await Task.Delay(1000); - return 1; - } - } -}"; + var src1 = """ + + class Test + { + public void F() + { + Task WaitAsync() + { + return 1; + } + } + } + """; + var src2 = """ + + class Test + { + public void F() + { + async Task WaitAsync() + { + await Task.Delay(1000); + return 1; + } + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( [Diagnostic(RudeEditKind.MakeMethodAsyncNotSupportedByRuntime, "WaitAsync")], @@ -9749,28 +10507,32 @@ async Task WaitAsync() [Fact] public void LocalFunctions_Iterator_Add() { - var src1 = @" -class Test -{ - public void F() - { - IEnumerable Iter() - { - return null; - } - } -}"; - var src2 = @" -class Test -{ - public void F() - { - IEnumerable Iter() - { - yield return 1; - } - } -}"; + var src1 = """ + + class Test + { + public void F() + { + IEnumerable Iter() + { + return null; + } + } + } + """; + var src2 = """ + + class Test + { + public void F() + { + IEnumerable Iter() + { + yield return 1; + } + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( [Diagnostic(RudeEditKind.MakeMethodIteratorNotSupportedByRuntime, "Iter")], @@ -9862,31 +10624,78 @@ public void Queries_UpdateAround_ExpressionBody() [Fact] public void Queries_Update_Signature_Select1() { - var src1 = @" -using System; -using System.Linq; + var src1 = """ -class C -{ - void F() - { - var result = from a in new[] {1} select a; + using System; + using System.Linq; + + class C + { + void F() + { + var result = from a in new[] {1} select a; + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + + class C + { + void F() + { + var result = from a in new[] {1.0} select a; + } + } + + """; + + var edits = GetTopEdits(src1, src2); + var syntaxMap = edits.GetSyntaxMap(); + + edits.VerifySemantics( + [ + SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), syntaxMap, rudeEdits: + [ + RuntimeRudeEdit(0, RudeEditKind.ChangingQueryLambdaType, syntaxMap.NodePosition(0), [GetResource("select clause")]) + ]) + ]); } -} -"; - var src2 = @" -using System; -using System.Linq; -class C -{ - void F() + [Fact] + public void Queries_Update_Signature_Select2() { - var result = from a in new[] {1.0} select a; - } -} -"; + var src1 = """ + + using System; + using System.Linq; + + class C + { + void F() + { + var result = from a in new[] {1} select a; + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + + class C + { + void F() + { + var result = from a in new[] {1} select a.ToString(); + } + } + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -9900,71 +10709,36 @@ void F() } [Fact] - public void Queries_Update_Signature_Select2() + public void Queries_Update_Signature_From1() { - var src1 = @" -using System; -using System.Linq; + var src1 = """ -class C -{ - void F() - { - var result = from a in new[] {1} select a; - } -} -"; - var src2 = @" -using System; -using System.Linq; + using System; + using System.Linq; -class C -{ - void F() - { - var result = from a in new[] {1} select a.ToString(); - } -} -"; - var edits = GetTopEdits(src1, src2); - var syntaxMap = edits.GetSyntaxMap(); + class C + { + void F() + { + var result = from a in new[] {1} from b in new[] {2} select b; + } + } - edits.VerifySemantics( - [ - SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), syntaxMap, rudeEdits: - [ - RuntimeRudeEdit(0, RudeEditKind.ChangingQueryLambdaType, syntaxMap.NodePosition(0), [GetResource("select clause")]) - ]) - ]); - } + """; + var src2 = """ - [Fact] - public void Queries_Update_Signature_From1() - { - var src1 = @" -using System; -using System.Linq; + using System; + using System.Linq; -class C -{ - void F() - { - var result = from a in new[] {1} from b in new[] {2} select b; - } -} -"; - var src2 = @" -using System; -using System.Linq; + class C + { + void F() + { + var result = from long a in new[] {1} from b in new[] {2} select b; + } + } -class C -{ - void F() - { - var result = from long a in new[] {1} from b in new[] {2} select b; - } -} -"; + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -9980,30 +10754,34 @@ void F() [Fact] public void Queries_Update_Signature_From2() { - var src1 = @" -using System; -using System.Linq; + var src1 = """ -class C -{ - void F() - { - var result = from System.Int64 a in new[] {1} from b in new[] {2} select b; - } -} -"; - var src2 = @" -using System; -using System.Linq; + using System; + using System.Linq; -class C -{ - void F() - { - var result = from long a in new[] {1} from b in new[] {2} select b; - } -} -"; + class C + { + void F() + { + var result = from System.Int64 a in new[] {1} from b in new[] {2} select b; + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + + class C + { + void F() + { + var result = from long a in new[] {1} from b in new[] {2} select b; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); @@ -10012,32 +10790,36 @@ void F() [Fact] public void Queries_Update_Signature_From3() { - var src1 = @" -using System; -using System.Linq; -using System.Collections.Generic; + var src1 = """ -class C -{ - void F() - { - var result = from a in new[] {1} from b in new[] {2} select b; - } -} -"; - var src2 = @" -using System; -using System.Linq; -using System.Collections.Generic; + using System; + using System.Linq; + using System.Collections.Generic; -class C -{ - void F() - { - var result = from a in new List() from b in new List() select b; - } -} -"; + class C + { + void F() + { + var result = from a in new[] {1} from b in new[] {2} select b; + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + using System.Collections.Generic; + + class C + { + void F() + { + var result = from a in new List() from b in new List() select b; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); @@ -10046,32 +10828,36 @@ void F() [Fact] public void Queries_Update_Signature_Let1() { - var src1 = @" -using System; -using System.Linq; -using System.Collections.Generic; + var src1 = """ -class C -{ - void F() - { - var result = from a in new[] {1} let b = 1 select a; - } -} -"; - var src2 = @" -using System; -using System.Linq; -using System.Collections.Generic; + using System; + using System.Linq; + using System.Collections.Generic; -class C -{ - void F() - { - var result = from a in new[] {1} let b = 1.0 select a; - } -} -"; + class C + { + void F() + { + var result = from a in new[] {1} let b = 1 select a; + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + using System.Collections.Generic; + + class C + { + void F() + { + var result = from a in new[] {1} let b = 1.0 select a; + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -10087,32 +10873,36 @@ void F() [Fact] public void Queries_Update_Signature_OrderBy1() { - var src1 = @" -using System; -using System.Linq; -using System.Collections.Generic; + var src1 = """ -class C -{ - void F() - { - var result = from a in new[] {1} orderby a + 1 descending, a + 2 ascending select a; - } -} -"; - var src2 = @" -using System; -using System.Linq; -using System.Collections.Generic; + using System; + using System.Linq; + using System.Collections.Generic; -class C -{ - void F() - { - var result = from a in new[] {1} orderby a + 1.0 descending, a + 2 ascending select a; - } -} -"; + class C + { + void F() + { + var result = from a in new[] {1} orderby a + 1 descending, a + 2 ascending select a; + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + using System.Collections.Generic; + + class C + { + void F() + { + var result = from a in new[] {1} orderby a + 1.0 descending, a + 2 ascending select a; + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -10128,32 +10918,36 @@ void F() [Fact] public void Queries_Update_Signature_OrderBy2() { - var src1 = @" -using System; -using System.Linq; -using System.Collections.Generic; + var src1 = """ -class C -{ - void F() - { - var result = from a in new[] {1} orderby a + 1 descending, a + 2 ascending select a; - } -} -"; - var src2 = @" -using System; -using System.Linq; -using System.Collections.Generic; + using System; + using System.Linq; + using System.Collections.Generic; -class C -{ - void F() - { - var result = from a in new[] {1} orderby a + 1 descending, a + 2.0 ascending select a; - } -} -"; + class C + { + void F() + { + var result = from a in new[] {1} orderby a + 1 descending, a + 2 ascending select a; + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + using System.Collections.Generic; + + class C + { + void F() + { + var result = from a in new[] {1} orderby a + 1 descending, a + 2.0 ascending select a; + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -10169,32 +10963,36 @@ void F() [Fact] public void Queries_Update_Signature_Join1() { - var src1 = @" -using System; -using System.Linq; -using System.Collections.Generic; + var src1 = """ -class C -{ - void F() - { - var result = from a in new[] {1} join b in new[] {1} on a equals b select b; - } -} -"; - var src2 = @" -using System; -using System.Linq; -using System.Collections.Generic; + using System; + using System.Linq; + using System.Collections.Generic; -class C -{ - void F() - { - var result = from a in new[] {1} join b in new[] {1.0} on a equals b select b; - } -} -"; + class C + { + void F() + { + var result = from a in new[] {1} join b in new[] {1} on a equals b select b; + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + using System.Collections.Generic; + + class C + { + void F() + { + var result = from a in new[] {1} join b in new[] {1.0} on a equals b select b; + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -10211,32 +11009,36 @@ void F() [Fact] public void Queries_Update_Signature_Join2() { - var src1 = @" -using System; -using System.Linq; -using System.Collections.Generic; + var src1 = """ -class C -{ - void F() - { - var result = from a in new[] {1} join b in new[] {1} on a equals b select b; - } -} -"; - var src2 = @" -using System; -using System.Linq; -using System.Collections.Generic; + using System; + using System.Linq; + using System.Collections.Generic; -class C -{ - void F() - { - var result = from a in new[] {1} join byte b in new[] {1} on a equals b select b; - } -} -"; + class C + { + void F() + { + var result = from a in new[] {1} join b in new[] {1} on a equals b select b; + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + using System.Collections.Generic; + + class C + { + void F() + { + var result = from a in new[] {1} join byte b in new[] {1} on a equals b select b; + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -10252,32 +11054,36 @@ void F() [Fact] public void Queries_Update_Signature_Join3() { - var src1 = @" -using System; -using System.Linq; -using System.Collections.Generic; + var src1 = """ -class C -{ - void F() - { - var result = from a in new[] {1} join b in new[] {1} on a + 1 equals b select b; - } -} -"; - var src2 = @" -using System; -using System.Linq; -using System.Collections.Generic; + using System; + using System.Linq; + using System.Collections.Generic; -class C -{ - void F() - { - var result = from a in new[] {1} join b in new[] {1} on a + 1.0 equals b select b; - } -} -"; + class C + { + void F() + { + var result = from a in new[] {1} join b in new[] {1} on a + 1 equals b select b; + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + using System.Collections.Generic; + + class C + { + void F() + { + var result = from a in new[] {1} join b in new[] {1} on a + 1.0 equals b select b; + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -10293,32 +11099,36 @@ void F() [Fact] public void Queries_Update_Signature_Join4() { - var src1 = @" -using System; -using System.Linq; -using System.Collections.Generic; + var src1 = """ -class C -{ - void F() - { - var result = from a in new[] {1} join b in new[] {1} on a equals b + 1 select b; - } -} -"; - var src2 = @" -using System; -using System.Linq; -using System.Collections.Generic; + using System; + using System.Linq; + using System.Collections.Generic; -class C -{ - void F() - { - var result = from a in new[] {1} join b in new[] {1} on a equals b + 1.0 select b; - } -} -"; + class C + { + void F() + { + var result = from a in new[] {1} join b in new[] {1} on a equals b + 1 select b; + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + using System.Collections.Generic; + + class C + { + void F() + { + var result = from a in new[] {1} join b in new[] {1} on a equals b + 1.0 select b; + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -10334,32 +11144,36 @@ void F() [Fact] public void Queries_Update_Signature_GroupBy1() { - var src1 = @" -using System; -using System.Linq; -using System.Collections.Generic; + var src1 = """ -class C -{ - void F() - { - var result = from a in new[] {1} group a + 1 by a into z select z; - } -} -"; - var src2 = @" -using System; -using System.Linq; -using System.Collections.Generic; + using System; + using System.Linq; + using System.Collections.Generic; -class C -{ - void F() - { - var result = from a in new[] {1} group a + 1.0 by a into z select z; - } -} -"; + class C + { + void F() + { + var result = from a in new[] {1} group a + 1 by a into z select z; + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + using System.Collections.Generic; + + class C + { + void F() + { + var result = from a in new[] {1} group a + 1.0 by a into z select z; + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -10375,32 +11189,36 @@ void F() [Fact] public void Queries_Update_Signature_GroupBy2() { - var src1 = @" -using System; -using System.Linq; -using System.Collections.Generic; + var src1 = """ -class C -{ - void F() - { - var result = from a in new[] {1} group a by a into z select z; - } -} -"; - var src2 = @" -using System; -using System.Linq; -using System.Collections.Generic; + using System; + using System.Linq; + using System.Collections.Generic; -class C -{ - void F() - { - var result = from a in new[] {1} group a by a + 1.0 into z select z; - } -} -"; + class C + { + void F() + { + var result = from a in new[] {1} group a by a into z select z; + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + using System.Collections.Generic; + + class C + { + void F() + { + var result = from a in new[] {1} group a by a + 1.0 into z select z; + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -10416,38 +11234,42 @@ void F() [Fact] public void Queries_Update_Signature_GroupBy_MatchingErrorTypes() { - var src1 = @" -using System; -using System.Linq; -using System.Collections.Generic; + var src1 = """ -class C -{ - Unknown G1(int a) => null; - Unknown G2(int a) => null; + using System; + using System.Linq; + using System.Collections.Generic; - void F() - { - var result = from a in new[] {1} group G1(a) by a into z select z; - } -} -"; - var src2 = @" -using System; -using System.Linq; -using System.Collections.Generic; + class C + { + Unknown G1(int a) => null; + Unknown G2(int a) => null; -class C -{ - Unknown G1(int a) => null; - Unknown G2(int a) => null; - - void F() - { - var result = from a in new[] {1} group G2(a) by a into z select z; - } -} -"; + void F() + { + var result = from a in new[] {1} group G1(a) by a into z select z; + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + using System.Collections.Generic; + + class C + { + Unknown G1(int a) => null; + Unknown G2(int a) => null; + + void F() + { + var result = from a in new[] {1} group G2(a) by a into z select z; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); @@ -10456,38 +11278,42 @@ void F() [Fact] public void Queries_Update_Signature_GroupBy_NonMatchingErrorTypes() { - var src1 = @" -using System; -using System.Linq; -using System.Collections.Generic; + var src1 = """ -class C -{ - Unknown1 G1(int a) => null; - Unknown2 G2(int a) => null; + using System; + using System.Linq; + using System.Collections.Generic; - void F() - { - var result = from a in new[] {1} group G1(a) by a into z select z; - } -} -"; - var src2 = @" -using System; -using System.Linq; -using System.Collections.Generic; + class C + { + Unknown1 G1(int a) => null; + Unknown2 G2(int a) => null; -class C -{ - Unknown1 G1(int a) => null; - Unknown2 G2(int a) => null; - - void F() - { - var result = from a in new[] {1} group G2(a) by a into z select z; - } -} -"; + void F() + { + var result = from a in new[] {1} group G1(a) by a into z select z; + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + using System.Collections.Generic; + + class C + { + Unknown1 G1(int a) => null; + Unknown2 G2(int a) => null; + + void F() + { + var result = from a in new[] {1} group G2(a) by a into z select z; + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -10541,32 +11367,36 @@ public void Queries_FromSelect_Update3() [Fact] public void Queries_Select_Reduced1() { - var src1 = @" -using System; -using System.Linq; -using System.Collections.Generic; + var src1 = """ -class C -{ - void F() - { - var result = from a in new[] {1} where a > 0 select a; - } -} -"; - var src2 = @" -using System; -using System.Linq; -using System.Collections.Generic; + using System; + using System.Linq; + using System.Collections.Generic; -class C -{ - void F() - { - var result = from a in new[] {1} where a > 0 select a + 1; - } -} -"; + class C + { + void F() + { + var result = from a in new[] {1} where a > 0 select a; + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + using System.Collections.Generic; + + class C + { + void F() + { + var result = from a in new[] {1} where a > 0 select a + 1; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } @@ -10574,32 +11404,36 @@ void F() [Fact] public void Queries_Select_Reduced2() { - var src1 = @" -using System; -using System.Linq; -using System.Collections.Generic; + var src1 = """ -class C -{ - void F() - { - var result = from a in new[] {1} where a > 0 select a + 1; - } -} -"; - var src2 = @" -using System; -using System.Linq; -using System.Collections.Generic; + using System; + using System.Linq; + using System.Collections.Generic; -class C -{ - void F() - { - var result = from a in new[] {1} where a > 0 select a; - } -} -"; + class C + { + void F() + { + var result = from a in new[] {1} where a > 0 select a + 1; + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + using System.Collections.Generic; + + class C + { + void F() + { + var result = from a in new[] {1} where a > 0 select a; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } @@ -10671,30 +11505,34 @@ public void Queries_OrderBy_Reorder() [Fact] public void Queries_GroupBy_Reduced1() { - var src1 = @" -using System; -using System.Linq; + var src1 = """ -class C -{ - void F() - { - var result = from a in new[] {1} group a by a; - } -} -"; - var src2 = @" -using System; -using System.Linq; + using System; + using System.Linq; -class C -{ - void F() - { - var result = from a in new[] {1} group a + 1.0 by a; - } -} -"; + class C + { + void F() + { + var result = from a in new[] {1} group a by a; + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + + class C + { + void F() + { + var result = from a in new[] {1} group a + 1.0 by a; + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -10710,30 +11548,34 @@ void F() [Fact] public void Queries_GroupBy_Reduced2() { - var src1 = @" -using System; -using System.Linq; + var src1 = """ -class C -{ - void F() - { - var result = from a in new[] {1} group a by a; - } -} -"; - var src2 = @" -using System; -using System.Linq; + using System; + using System.Linq; -class C -{ - void F() - { - var result = from a in new[] {1} group a + 1 by a; - } -} -"; + class C + { + void F() + { + var result = from a in new[] {1} group a by a; + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + + class C + { + void F() + { + var result = from a in new[] {1} group a + 1 by a; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } @@ -10741,30 +11583,34 @@ void F() [Fact] public void Queries_GroupBy_Reduced3() { - var src1 = @" -using System; -using System.Linq; + var src1 = """ -class C -{ - void F() - { - var result = from a in new[] {1} group a + 1.0 by a; - } -} -"; - var src2 = @" -using System; -using System.Linq; + using System; + using System.Linq; -class C -{ - void F() - { - var result = from a in new[] {1} group a by a; - } -} -"; + class C + { + void F() + { + var result = from a in new[] {1} group a + 1.0 by a; + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + + class C + { + void F() + { + var result = from a in new[] {1} group a by a; + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = edits.GetSyntaxMap(); @@ -10780,30 +11626,34 @@ void F() [Fact] public void Queries_GroupBy_Reduced4() { - var src1 = @" -using System; -using System.Linq; + var src1 = """ -class C -{ - void F() - { - var result = from a in new[] {1} group a + 1 by a; - } -} -"; - var src2 = @" -using System; -using System.Linq; + using System; + using System.Linq; -class C -{ - void F() - { - var result = from a in new[] {1} group a by a; - } -} -"; + class C + { + void F() + { + var result = from a in new[] {1} group a + 1 by a; + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + + class C + { + void F() + { + var result = from a in new[] {1} group a by a; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } @@ -10844,50 +11694,54 @@ public void Queries_OrderBy_Continuation_Update() [Fact] public void Queries_CapturedTransparentIdentifiers_FromClause1() { - var src1 = @" -using System; -using System.Linq; + var src1 = """ -class C -{ - int Z(Func f) - { - return 1; - } - - void F() - { - var result = from a in new[] { 1 } - from b in new[] { 2 } - where Z(() => a) > 0 - where Z(() => b) > 0 - where Z(() => a) > 0 - where Z(() => b) > 0 - select a; - } -}"; - var src2 = @" -using System; -using System.Linq; + using System; + using System.Linq; -class C -{ - int Z(Func f) - { - return 1; - } + class C + { + int Z(Func f) + { + return 1; + } - void F() - { - var result = from a in new[] { 1 } - from b in new[] { 2 } - where Z(() => a) > 1 // update - where Z(() => b) > 2 // update - where Z(() => a) > 3 // update - where Z(() => b) > 4 // update - select a; - } -}"; + void F() + { + var result = from a in new[] { 1 } + from b in new[] { 2 } + where Z(() => a) > 0 + where Z(() => b) > 0 + where Z(() => a) > 0 + where Z(() => b) > 0 + select a; + } + } + """; + var src2 = """ + + using System; + using System.Linq; + + class C + { + int Z(Func f) + { + return 1; + } + + void F() + { + var result = from a in new[] { 1 } + from b in new[] { 2 } + where Z(() => a) > 1 // update + where Z(() => b) > 2 // update + where Z(() => a) > 3 // update + where Z(() => b) > 4 // update + select a; + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); @@ -10896,42 +11750,46 @@ where Z(() => b) > 4 // update [Fact] public void Queries_CapturedTransparentIdentifiers_LetClause1() { - var src1 = @" -using System; -using System.Linq; + var src1 = """ -class C -{ - int Z(Func f) - { - return 1; - } + using System; + using System.Linq; - void F() - { - var result = from a in new[] { 1 } - let b = Z(() => a) - select a + b; - } -}"; - var src2 = @" -using System; -using System.Linq; + class C + { + int Z(Func f) + { + return 1; + } -class C -{ - int Z(Func f) - { - return 1; - } + void F() + { + var result = from a in new[] { 1 } + let b = Z(() => a) + select a + b; + } + } + """; + var src2 = """ - void F() - { - var result = from a in new[] { 1 } - let b = Z(() => a + 1) - select a - b; - } -}"; + using System; + using System.Linq; + + class C + { + int Z(Func f) + { + return 1; + } + + void F() + { + var result = from a in new[] { 1 } + let b = Z(() => a + 1) + select a - b; + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); @@ -10940,42 +11798,46 @@ void F() [Fact] public void Queries_CapturedTransparentIdentifiers_JoinClause1() { - var src1 = @" -using System; -using System.Linq; + var src1 = """ -class C -{ - int Z(Func f) - { - return 1; - } + using System; + using System.Linq; - void F() - { - var result = from a in new[] { 1 } - join b in new[] { 3 } on Z(() => a + 1) equals Z(() => b - 1) into g - select Z(() => g.First()); - } -}"; - var src2 = @" -using System; -using System.Linq; + class C + { + int Z(Func f) + { + return 1; + } -class C -{ - int Z(Func f) - { - return 1; - } + void F() + { + var result = from a in new[] { 1 } + join b in new[] { 3 } on Z(() => a + 1) equals Z(() => b - 1) into g + select Z(() => g.First()); + } + } + """; + var src2 = """ - void F() - { - var result = from a in new[] { 1 } - join b in new[] { 3 } on Z(() => a + 1) equals Z(() => b - 1) into g - select Z(() => g.Last()); - } -}"; + using System; + using System.Linq; + + class C + { + int Z(Func f) + { + return 1; + } + + void F() + { + var result = from a in new[] { 1 } + join b in new[] { 3 } on Z(() => a + 1) equals Z(() => b - 1) into g + select Z(() => g.Last()); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); @@ -10984,44 +11846,48 @@ void F() [Fact] public void Queries_CeaseCapturingTransparentIdentifiers1() { - var src1 = @" -using System; -using System.Linq; + var src1 = """ -class C -{ - int Z(Func f) - { - return 1; - } + using System; + using System.Linq; - void F() - { - var result = from a in new[] { 1 } - from b in new[] { 2 } - where Z(() => a + b) > 0 - select a; - } -}"; - var src2 = @" -using System; -using System.Linq; + class C + { + int Z(Func f) + { + return 1; + } -class C -{ - int Z(Func f) - { - return 1; - } + void F() + { + var result = from a in new[] { 1 } + from b in new[] { 2 } + where Z(() => a + b) > 0 + select a; + } + } + """; + var src2 = """ - void F() - { - var result = from a in new[] { 1 } - from b in new[] { 2 } - where Z(() => a + 1) > 0 - select a; - } -}"; + using System; + using System.Linq; + + class C + { + int Z(Func f) + { + return 1; + } + + void F() + { + var result = from a in new[] { 1 } + from b in new[] { 2 } + where Z(() => a + 1) > 0 + select a; + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -11030,44 +11896,48 @@ where Z(() => a + 1) > 0 [Fact] public void Queries_CapturingTransparentIdentifiers1() { - var src1 = @" -using System; -using System.Linq; + var src1 = """ -class C -{ - int Z(Func f) - { - return 1; - } + using System; + using System.Linq; - void F() - { - var result = from a in new[] { 1 } - from b in new[] { 2 } - where Z(() => a + 1) > 0 - select a; - } -}"; - var src2 = @" -using System; -using System.Linq; + class C + { + int Z(Func f) + { + return 1; + } -class C -{ - int Z(Func f) - { - return 1; - } + void F() + { + var result = from a in new[] { 1 } + from b in new[] { 2 } + where Z(() => a + 1) > 0 + select a; + } + } + """; + var src2 = """ - void F() - { - var result = from a in new[] { 1 } - from b in new[] { 2 } - where Z(() => a + b) > 0 - select a; - } -}"; + using System; + using System.Linq; + + class C + { + int Z(Func f) + { + return 1; + } + + void F() + { + var result = from a in new[] { 1 } + from b in new[] { 2 } + where Z(() => a + b) > 0 + select a; + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -11076,38 +11946,42 @@ where Z(() => a + b) > 0 [Fact] public void Queries_AccessingCapturedTransparentIdentifier1() { - var src1 = @" -using System; -using System.Linq; + var src1 = """ -class C -{ - int Z(Func f) => 1; + using System; + using System.Linq; - void F() - { - var result = from a in new[] { 1 } - where Z(() => a) > 0 - select 1; - } -} -"; - var src2 = @" -using System; -using System.Linq; + class C + { + int Z(Func f) => 1; -class C -{ - int Z(Func f) => 1; - - void F() - { - var result = from a in new[] { 1 } - where Z(() => a) > 0 - select a; - } -} -"; + void F() + { + var result = from a in new[] { 1 } + where Z(() => a) > 0 + select 1; + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + + class C + { + int Z(Func f) => 1; + + void F() + { + var result = from a in new[] { 1 } + where Z(() => a) > 0 + select a; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } @@ -11115,40 +11989,44 @@ where Z(() => a) > 0 [Fact] public void Queries_AccessingCapturedTransparentIdentifier2() { - var src1 = @" -using System; -using System.Linq; + var src1 = """ -class C -{ - int Z(Func f) => 1; + using System; + using System.Linq; - void F() - { - var result = from a in new[] { 1 } - from b in new[] { 1 } - where Z(() => a) > 0 - select b; - } -} -"; - var src2 = @" -using System; -using System.Linq; + class C + { + int Z(Func f) => 1; -class C -{ - int Z(Func f) => 1; - - void F() - { - var result = from a in new[] { 1 } - from b in new[] { 1 } - where Z(() => a) > 0 - select a + b; - } -} -"; + void F() + { + var result = from a in new[] { 1 } + from b in new[] { 1 } + where Z(() => a) > 0 + select b; + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + + class C + { + int Z(Func f) => 1; + + void F() + { + var result = from a in new[] { 1 } + from b in new[] { 1 } + where Z(() => a) > 0 + select a + b; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -11157,38 +12035,42 @@ where Z(() => a) > 0 [Fact] public void Queries_AccessingCapturedTransparentIdentifier3() { - var src1 = @" -using System; -using System.Linq; + var src1 = """ -class C -{ - int Z(Func f) => 1; + using System; + using System.Linq; - void F() - { - var result = from a in new[] { 1 } - where Z(() => a) > 0 - select Z(() => 1); - } -} -"; - var src2 = @" -using System; -using System.Linq; + class C + { + int Z(Func f) => 1; -class C -{ - int Z(Func f) => 1; - - void F() - { - var result = from a in new[] { 1 } - where Z(() => a) > 0 - select Z(() => a); - } -} -"; + void F() + { + var result = from a in new[] { 1 } + where Z(() => a) > 0 + select Z(() => 1); + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + + class C + { + int Z(Func f) => 1; + + void F() + { + var result = from a in new[] { 1 } + where Z(() => a) > 0 + select Z(() => a); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -11198,40 +12080,44 @@ where Z(() => a) > 0 [Fact] public void Queries_NotAccessingCapturedTransparentIdentifier1() { - var src1 = @" -using System; -using System.Linq; + var src1 = """ -class C -{ - int Z(Func f) => 1; + using System; + using System.Linq; - void F() - { - var result = from a in new[] { 1 } - from b in new[] { 1 } - where Z(() => a) > 0 - select a + b; - } -} -"; - var src2 = @" -using System; -using System.Linq; + class C + { + int Z(Func f) => 1; -class C -{ - int Z(Func f) => 1; - - void F() - { - var result = from a in new[] { 1 } - from b in new[] { 1 } - where Z(() => a) > 0 - select b; - } -} -"; + void F() + { + var result = from a in new[] { 1 } + from b in new[] { 1 } + where Z(() => a) > 0 + select a + b; + } + } + + """; + var src2 = """ + + using System; + using System.Linq; + + class C + { + int Z(Func f) => 1; + + void F() + { + var result = from a in new[] { 1 } + from b in new[] { 1 } + where Z(() => a) > 0 + select b; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -11240,38 +12126,42 @@ where Z(() => a) > 0 [Fact] public void Queries_NotAccessingCapturedTransparentIdentifier2() { - var src1 = @" -using System; -using System.Linq; + var src1 = """ -class C -{ - int Z(Func f) => 1; + using System; + using System.Linq; + + class C + { + int Z(Func f) => 1; + + void F() + { + var result = from a in new[] { 1 } + where Z(() => a) > 0 + select Z(() => 1); + } + } + + """; + var src2 = """ + + using System; + using System.Linq; - void F() - { - var result = from a in new[] { 1 } - where Z(() => a) > 0 - select Z(() => 1); - } -} -"; - var src2 = @" -using System; -using System.Linq; + class C + { + int Z(Func f) => 1; + + void F() + { + var result = from a in new[] { 1 } + where Z(() => a) > 0 + select Z(() => a); + } + } -class C -{ - int Z(Func f) => 1; - - void F() - { - var result = from a in new[] { 1 } - where Z(() => a) > 0 - select Z(() => a); - } -} -"; + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); @@ -11280,35 +12170,39 @@ where Z(() => a) > 0 [Fact] public void Queries_Insert_Static_First() { - var src1 = @" -using System; -using System.Collections.Generic; -using System.Linq; + var src1 = """ -class C -{ - IEnumerable F() - { - return null; - } -} -"; - var src2 = @" -using System; -using System.Collections.Generic; -using System.Linq; + using System; + using System.Collections.Generic; + using System.Linq; -class C -{ - IEnumerable F() - { - return from x in new[] {1,2,3} - where x > 1 - group x by x + 1 into z - select z.Key; - } -} -"; + class C + { + IEnumerable F() + { + return null; + } + } + + """; + var src2 = """ + + using System; + using System.Collections.Generic; + using System.Linq; + + class C + { + IEnumerable F() + { + return from x in new[] {1,2,3} + where x > 1 + group x by x + 1 into z + select z.Key; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( capabilities: @@ -11328,41 +12222,45 @@ group x by x + 1 into z [Fact] public void Queries_Insert_ThisOnly_Second() { - var src1 = @" -using System; -using System.Collections.Generic; -using System.Linq; + var src1 = """ -class C -{ - int y; + using System; + using System.Collections.Generic; + using System.Linq; - IEnumerable F() - { - var f = () => y; - return null; - } -} -"; - var src2 = @" -using System; -using System.Collections.Generic; -using System.Linq; + class C + { + int y; -class C -{ - int y; + IEnumerable F() + { + var f = () => y; + return null; + } + } - IEnumerable F() - { - var f = () => y; - return from x in new[] {1,2,3} - where x > y - group x by x + y into z - select z.Key + y; - } -} -"; + """; + var src2 = """ + + using System; + using System.Collections.Generic; + using System.Linq; + + class C + { + int y; + + IEnumerable F() + { + var f = () => y; + return from x in new[] {1,2,3} + where x > y + group x by x + y into z + select z.Key + y; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( capabilities: @@ -11382,40 +12280,44 @@ group x by x + y into z [Fact] public void Queries_StackAlloc() { - var src1 = @" -using System; -using System.Collections.Generic; -using System.Linq; + var src1 = """ -class C -{ - IEnumerable F() - { - return from x in new[] {1,2,3} - where G(stackalloc int[1]) > 1 - group G(stackalloc int[2]) by G(stackalloc int[3]) into z - select z.Key + G(stackalloc int[4]); - } - - int G(Span span) => span.Length; -}"; - var src2 = @" -using System; -using System.Collections.Generic; -using System.Linq; + using System; + using System.Collections.Generic; + using System.Linq; -class C -{ - IEnumerable F() - { - return from x in new[] {1,2,3} - where G(stackalloc int[10]) > 1 - group G(stackalloc int[20]) by G(stackalloc int[30]) into z - select z.Key + G(stackalloc int[40]); - } - - int G(Span span) => span.Length; -}"; + class C + { + IEnumerable F() + { + return from x in new[] {1,2,3} + where G(stackalloc int[1]) > 1 + group G(stackalloc int[2]) by G(stackalloc int[3]) into z + select z.Key + G(stackalloc int[4]); + } + + int G(Span span) => span.Length; + } + """; + var src2 = """ + + using System; + using System.Collections.Generic; + using System.Linq; + + class C + { + IEnumerable F() + { + return from x in new[] {1,2,3} + where G(stackalloc int[10]) > 1 + group G(stackalloc int[20]) by G(stackalloc int[30]) into z + select z.Key + G(stackalloc int[40]); + } + + int G(Span span) => span.Length; + } + """; var edits = GetTopEdits(src1, src2); @@ -11433,28 +12335,32 @@ group G(stackalloc int[20]) by G(stackalloc int[30]) into z [Fact] public void Yield_Update1() { - var src1 = @" -class C -{ - static IEnumerable F() - { - yield return 1; - yield return 2; - yield break; - } -} -"; - var src2 = @" -class C -{ - static IEnumerable F() - { - yield return 3; - yield break; - yield return 4; - } -} -"; + var src1 = """ + + class C + { + static IEnumerable F() + { + yield return 1; + yield return 2; + yield break; + } + } + + """; + var src2 = """ + + class C + { + static IEnumerable F() + { + yield return 3; + yield break; + yield return 4; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -11465,15 +12371,19 @@ static IEnumerable F() [Fact] public void Yield_Delete1() { - var src1 = @" -yield return 1; -yield return 2; -yield return 3; -"; - var src2 = @" -yield return 1; -yield return 3; -"; + var src1 = """ + + yield return 1; + yield return 2; + yield return 3; + + """; + var src2 = """ + + yield return 1; + yield return 3; + + """; var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Iterator); @@ -11484,27 +12394,31 @@ public void Yield_Delete1() [Fact] public void Yield_Delete2() { - var src1 = @" -class C -{ - static IEnumerable F() - { - yield return 1; - yield return 2; - yield return 3; - } -} -"; - var src2 = @" -class C -{ - static IEnumerable F() - { - yield return 1; - yield return 3; - } -} -"; + var src1 = """ + + class C + { + static IEnumerable F() + { + yield return 1; + yield return 2; + yield return 3; + } + } + + """; + var src2 = """ + + class C + { + static IEnumerable F() + { + yield return 1; + yield return 3; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -11515,16 +12429,20 @@ static IEnumerable F() [Fact] public void Yield_Insert1() { - var src1 = @" -yield return 1; -yield return 3; -"; - var src2 = @" -yield return 1; -yield return 2; -yield return 3; -yield return 4; -"; + var src1 = """ + + yield return 1; + yield return 3; + + """; + var src2 = """ + + yield return 1; + yield return 2; + yield return 3; + yield return 4; + + """; var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Iterator); @@ -11536,28 +12454,32 @@ public void Yield_Insert1() [Fact] public void Yield_Insert2() { - var src1 = @" -class C -{ - static IEnumerable F() - { - yield return 1; - yield return 3; - } -} -"; - var src2 = @" -class C -{ - static IEnumerable F() - { - yield return 1; - yield return 2; - yield return 3; - yield return 4; - } -} -"; + var src1 = """ + + class C + { + static IEnumerable F() + { + yield return 1; + yield return 3; + } + } + + """; + var src2 = """ + + class C + { + static IEnumerable F() + { + yield return 1; + yield return 2; + yield return 3; + yield return 4; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -11568,24 +12490,28 @@ static IEnumerable F() [Fact] public void Yield_Update_GenericType() { - var src1 = @" -class C -{ - static IEnumerable F() - { - yield return 1; - } -} -"; - var src2 = @" -class C -{ - static IEnumerable F() - { - yield return 2; - } -} -"; + var src1 = """ + + class C + { + static IEnumerable F() + { + yield return 1; + } + } + + """; + var src2 = """ + + class C + { + static IEnumerable F() + { + yield return 2; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -11606,24 +12532,28 @@ static IEnumerable F() [Fact] public void Yield_Update_GenericMethod() { - var src1 = @" -class C -{ - static IEnumerable F() - { - yield return 1; - } -} -"; - var src2 = @" -class C -{ - static IEnumerable F() - { - yield return 2; - } -} -"; + var src1 = """ + + class C + { + static IEnumerable F() + { + yield return 1; + } + } + + """; + var src2 = """ + + class C + { + static IEnumerable F() + { + yield return 2; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -11644,30 +12574,34 @@ static IEnumerable F() [Fact] public void Yield_Update_GenericLocalFunction() { - var src1 = @" -class C -{ - void F() - { - IEnumerable L() - { - yield return 1; - } - } -} -"; - var src2 = @" -class C -{ - void F() - { - IEnumerable L() - { - yield return 2; - } - } -} -"; + var src1 = """ + + class C + { + void F() + { + IEnumerable L() + { + yield return 1; + } + } + } + + """; + var src2 = """ + + class C + { + void F() + { + IEnumerable L() + { + yield return 2; + } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -11688,28 +12622,32 @@ IEnumerable L() [Fact] public void MissingIteratorStateMachineAttribute() { - var src1 = @" -using System.Collections.Generic; + var src1 = """ -class C -{ - static IEnumerable F() - { - yield return 1; - } -} -"; - var src2 = @" -using System.Collections.Generic; + using System.Collections.Generic; -class C -{ - static IEnumerable F() - { - yield return 2; - } -} -"; + class C + { + static IEnumerable F() + { + yield return 1; + } + } + + """; + var src2 = """ + + using System.Collections.Generic; + + class C + { + static IEnumerable F() + { + yield return 2; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -11723,28 +12661,32 @@ static IEnumerable F() [Fact] public void MissingIteratorStateMachineAttribute2() { - var src1 = @" -using System.Collections.Generic; + var src1 = """ -class C -{ - static IEnumerable F() - { - return null; - } -} -"; - var src2 = @" -using System.Collections.Generic; + using System.Collections.Generic; -class C -{ - static IEnumerable F() - { - yield return 2; - } -} -"; + class C + { + static IEnumerable F() + { + return null; + } + } + + """; + var src2 = """ + + using System.Collections.Generic; + + class C + { + static IEnumerable F() + { + yield return 2; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -11777,26 +12719,34 @@ static IEnumerable F() [InlineData("return await F(old);")] public void AwaitSpilling_OK(string oldStatement, string newStatement = null) { - var src1 = @" -class C -{ - static async Task F() - { - " + oldStatement + @" - } -} -"; + var src1 = """ + + class C + { + static async Task F() + { + + """ + oldStatement + """ + + } + } + + """; newStatement ??= oldStatement.Replace("old", "@new"); - var src2 = @" -class C -{ - static async Task F() - { - " + newStatement + @" - } -} -"; + var src2 = """ + + class C + { + static async Task F() + { + + """ + newStatement + """ + + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( capabilities: EditAndContinueCapabilities.AddInstanceFieldToExistingType); @@ -11805,18 +12755,22 @@ static async Task F() [Fact] public void AwaitSpilling_ExpressionBody() { - var src1 = @" -class C -{ - static async Task G() => await F(1); -} -"; - var src2 = @" -class C -{ - static async Task G() => await F(2); -} -"; + var src1 = """ + + class C + { + static async Task G() => await F(1); + } + + """; + var src2 = """ + + class C + { + static async Task G() => await F(2); + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( capabilities: EditAndContinueCapabilities.AddInstanceFieldToExistingType); @@ -11836,26 +12790,34 @@ class C [InlineData("b += await F(old);")] public void AwaitSpilling_Errors(string oldStatement, string[] errorMessages = null) { - var src1 = @" -class C -{ - static async Task F() - { - " + oldStatement + @" - } -} -"; + var src1 = """ + + class C + { + static async Task F() + { + + """ + oldStatement + """ + + } + } + + """; var newStatement = oldStatement.Replace("old", "@new"); - var src2 = @" -class C -{ - static async Task F() - { - " + newStatement + @" - } -} -"; + var src2 = """ + + class C + { + static async Task F() + { + + """ + newStatement + """ + + } + } + + """; var edits = GetTopEdits(src1, src2); // consider: these edits can be allowed if we get more sophisticated @@ -11868,30 +12830,34 @@ static async Task F() [Fact] public void AwaitSpilling_Errors_LocalFunction() { - var src1 = @" -class C -{ - static void F() - { - async Task L() - { - F(old, await F(1)); - } - } -} -"; - var src2 = @" -class C -{ - static void F() - { - async Task L() - { - F(old, await F(2)); - } - } -} -"; + var src1 = """ + + class C + { + static void F() + { + async Task L() + { + F(old, await F(1)); + } + } + } + + """; + var src2 = """ + + class C + { + static void F() + { + async Task L() + { + F(old, await F(2)); + } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -11901,15 +12867,19 @@ async Task L() [Fact] public void Await_Delete1() { - var src1 = @" -await F(1); -await F(2); -await F(3); -"; - var src2 = @" -await F(1); -await F(3); -"; + var src1 = """ + + await F(1); + await F(2); + await F(3); + + """; + var src2 = """ + + await F(1); + await F(3); + + """; var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Async); @@ -11921,32 +12891,36 @@ public void Await_Delete1() [Fact] public void Await_Delete2() { - var src1 = @" -class C -{ - static async Task F() - { - await F(1); - { - await F(2); - } - await F(3); - } -} -"; - var src2 = @" -class C -{ - static async Task F() - { - await F(1); - { - F(2); - } - await F(3); - } -} -"; + var src1 = """ + + class C + { + static async Task F() + { + await F(1); + { + await F(2); + } + await F(3); + } + } + + """; + var src2 = """ + + class C + { + static async Task F() + { + await F(1); + { + F(2); + } + await F(3); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -11957,24 +12931,28 @@ static async Task F() [Fact] public void Await_Delete3() { - var src1 = @" -class C -{ - static async Task F() - { - await F(await F(1)); - } -} -"; - var src2 = @" -class C -{ - static async Task F() - { - await F(1); - } -} -"; + var src1 = """ + + class C + { + static async Task F() + { + await F(await F(1)); + } + } + + """; + var src2 = """ + + class C + { + static async Task F() + { + await F(1); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -11985,18 +12963,22 @@ static async Task F() [Fact] public void Await_Delete4() { - var src1 = @" -class C -{ - static async Task F() => await F(await F(1)); -} -"; - var src2 = @" -class C -{ - static async Task F() => await F(1); -} -"; + var src1 = """ + + class C + { + static async Task F() => await F(await F(1)); + } + + """; + var src2 = """ + + class C + { + static async Task F() => await F(1); + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -12007,18 +12989,22 @@ class C [Fact] public void Await_Delete5() { - var src1 = @" -class C -{ - static async Task F() => await F(1); -} -"; - var src2 = @" -class C -{ - static async Task F() => F(1); -} -"; + var src1 = """ + + class C + { + static async Task F() => await F(1); + } + + """; + var src2 = """ + + class C + { + static async Task F() => F(1); + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -12029,24 +13015,28 @@ class C [Fact] public void AwaitForEach_Delete1() { - var src1 = @" -class C -{ - static async Task F() - { - await foreach (var x in G()) { } - } -} -"; - var src2 = @" -class C -{ - static async Task F() - { - foreach (var x in G()) { } - } -} -"; + var src1 = """ + + class C + { + static async Task F() + { + await foreach (var x in G()) { } + } + } + + """; + var src2 = """ + + class C + { + static async Task F() + { + foreach (var x in G()) { } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -12057,24 +13047,28 @@ static async Task F() [Fact] public void AwaitForEach_Delete2() { - var src1 = @" -class C -{ - static async Task F() - { - await foreach (var (x, y) in G()) { } - } -} -"; - var src2 = @" -class C -{ - static async Task F() - { - foreach (var (x, y) in G()) { } - } -} -"; + var src1 = """ + + class C + { + static async Task F() + { + await foreach (var (x, y) in G()) { } + } + } + + """; + var src2 = """ + + class C + { + static async Task F() + { + foreach (var (x, y) in G()) { } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -12085,23 +13079,27 @@ static async Task F() [Fact] public void AwaitForEach_Delete3() { - var src1 = @" -class C -{ - static async Task F() - { - await foreach (var x in G()) { } - } -} -"; - var src2 = @" -class C -{ - static async Task F() - { - } -} -"; + var src1 = """ + + class C + { + static async Task F() + { + await foreach (var x in G()) { } + } + } + + """; + var src2 = """ + + class C + { + static async Task F() + { + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -12112,24 +13110,28 @@ static async Task F() [Fact] public void AwaitUsing_Delete1() { - var src1 = @" -class C -{ - static async Task F() - { - await using D x = new D(), y = new D(); - } -} -"; - var src2 = @" -class C -{ - static async Task F() - { - await using D x = new D(); - } -} -"; + var src1 = """ + + class C + { + static async Task F() + { + await using D x = new D(), y = new D(); + } + } + + """; + var src2 = """ + + class C + { + static async Task F() + { + await using D x = new D(); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -12140,24 +13142,28 @@ static async Task F() [Fact] public void AwaitUsing_Delete2() { - var src1 = @" -class C -{ - static async Task F() - { - await using D x = new D(), y = new D(); - } -} -"; - var src2 = @" -class C -{ - static async Task F() - { - await using D y = new D(); - } -} -"; + var src1 = """ + + class C + { + static async Task F() + { + await using D x = new D(), y = new D(); + } + } + + """; + var src2 = """ + + class C + { + static async Task F() + { + await using D y = new D(); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -12168,23 +13174,27 @@ static async Task F() [Fact] public void AwaitUsing_Delete3() { - var src1 = @" -class C -{ - static async Task F() - { - await using D x = new D(), y = new D(); - } -} -"; - var src2 = @" -class C -{ - static async Task F() - { - } -} -"; + var src1 = """ + + class C + { + static async Task F() + { + await using D x = new D(), y = new D(); + } + } + + """; + var src2 = """ + + class C + { + static async Task F() + { + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -12195,24 +13205,28 @@ static async Task F() [Fact] public void AwaitUsing_Delete4() { - var src1 = @" -class C -{ - static async Task F() - { - await using D x = new D(), y = new D(); - } -} -"; - var src2 = @" -class C -{ - static async Task F() - { - using D x = new D(), y = new D(); - } -} -"; + var src1 = """ + + class C + { + static async Task F() + { + await using D x = new D(), y = new D(); + } + } + + """; + var src2 = """ + + class C + { + static async Task F() + { + using D x = new D(), y = new D(); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -12223,16 +13237,20 @@ static async Task F() [Fact] public void Await_Insert1() { - var src1 = @" -await F(1); -await F(3); -"; - var src2 = @" -await F(1); -await F(2); -await F(3); -await F(4); -"; + var src1 = """ + + await F(1); + await F(3); + + """; + var src2 = """ + + await F(1); + await F(2); + await F(3); + await F(4); + + """; var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Async); @@ -12246,28 +13264,32 @@ public void Await_Insert1() [Fact] public void Await_Insert2() { - var src1 = @" -class C -{ - static async IEnumerable F() - { - await F(1); - await F(3); - } -} -"; - var src2 = @" -class C -{ - static async IEnumerable F() - { - await F(1); - await F(2); - await F(3); - await F(4); - } -} -"; + var src1 = """ + + class C + { + static async IEnumerable F() + { + await F(1); + await F(3); + } + } + + """; + var src2 = """ + + class C + { + static async IEnumerable F() + { + await F(1); + await F(2); + await F(3); + await F(4); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -12278,26 +13300,30 @@ static async IEnumerable F() [Fact] public void Await_Insert3() { - var src1 = @" -class C -{ - static async IEnumerable F() - { - await F(1); - await F(3); - } -} -"; - var src2 = @" -class C -{ - static async IEnumerable F() - { - await F(await F(1)); - await F(await F(2)); - } -} -"; + var src1 = """ + + class C + { + static async IEnumerable F() + { + await F(1); + await F(3); + } + } + + """; + var src2 = """ + + class C + { + static async IEnumerable F() + { + await F(await F(1)); + await F(await F(2)); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -12308,18 +13334,22 @@ static async IEnumerable F() [Fact] public void Await_Insert4() { - var src1 = @" -class C -{ - static async Task F() => await F(1); -} -"; - var src2 = @" -class C -{ - static async Task F() => await F(await F(1)); -} -"; + var src1 = """ + + class C + { + static async Task F() => await F(1); + } + + """; + var src2 = """ + + class C + { + static async Task F() => await F(await F(1)); + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -12329,45 +13359,53 @@ class C [Fact] public void Await_Insert5() { - var src1 = @" -class C -{ - static Task F() => F(1); -} -"; - var src2 = @" -class C -{ - static async Task F() => await F(1); -} -"; + var src1 = """ + + class C + { + static Task F() => F(1); + } + + """; + var src2 = """ + + class C + { + static async Task F() => await F(1); + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( capabilities: EditAndContinueCapabilities.NewTypeDefinition | EditAndContinueCapabilities.AddExplicitInterfaceImplementation); } - [Fact] - public void AwaitForEach_Insert_Ok() - { - var src1 = @" -class C -{ - static async Task F() - { - foreach (var x in G()) { } - } -} -"; - var src2 = @" -class C -{ - static async Task F() - { - await foreach (var x in G()) { } - } -} -"; + [Fact] + public void AwaitForEach_Insert_Ok() + { + var src1 = """ + + class C + { + static async Task F() + { + foreach (var x in G()) { } + } + } + + """; + var src2 = """ + + class C + { + static async Task F() + { + await foreach (var x in G()) { } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -12377,28 +13415,32 @@ static async Task F() [Fact] public void AwaitForEach_Insert() { - var src1 = @" -class C -{ - static async Task F() - { - await Task.FromResult(1); + var src1 = """ - foreach (var x in G()) { } - } -} -"; - var src2 = @" -class C -{ - static async Task F() - { - await Task.FromResult(1); + class C + { + static async Task F() + { + await Task.FromResult(1); - await foreach (var x in G()) { } - } -} -"; + foreach (var x in G()) { } + } + } + + """; + var src2 = """ + + class C + { + static async Task F() + { + await Task.FromResult(1); + + await foreach (var x in G()) { } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -12409,24 +13451,28 @@ static async Task F() [Fact] public void AwaitUsing_Insert1() { - var src1 = @" -class C -{ - static async Task F() - { - await using D x = new D(); - } -} -"; - var src2 = @" -class C -{ - static async Task F() - { - await using D x = new D(), y = new D(); - } -} -"; + var src1 = """ + + class C + { + static async Task F() + { + await using D x = new D(); + } + } + + """; + var src2 = """ + + class C + { + static async Task F() + { + await using D x = new D(), y = new D(); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -12437,26 +13483,30 @@ static async Task F() [Fact] public void AwaitUsing_Insert2() { - var src1 = @" -class C -{ - static async Task F() - { - await G(); - using D x = new D(); - } -} -"; - var src2 = @" -class C -{ - static async Task F() - { - await G(); - await using D x = new D(); - } -} -"; + var src1 = """ + + class C + { + static async Task F() + { + await G(); + using D x = new D(); + } + } + + """; + var src2 = """ + + class C + { + static async Task F() + { + await G(); + await using D x = new D(); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -12467,35 +13517,39 @@ static async Task F() [Fact] public void Await_Update() { - var src1 = s_asyncIteratorStateMachineAttributeSource + @" -class C -{ - static async IAsyncEnumerable F() - { - await foreach (var x in G()) { } - await Task.FromResult(1); - await Task.FromResult(1); - await Task.FromResult(1); - yield return 1; - yield break; - yield break; - } -} -"; - var src2 = s_asyncIteratorStateMachineAttributeSource + @" -class C -{ - static async IAsyncEnumerable F() - { - await foreach (var (x,y) in G()) { } - await foreach (var x in G()) { } - await using D x = new D(), y = new D(); - await Task.FromResult(1); - await Task.FromResult(1); - yield return 1; - } -} -"; + var src1 = s_asyncIteratorStateMachineAttributeSource + """ + + class C + { + static async IAsyncEnumerable F() + { + await foreach (var x in G()) { } + await Task.FromResult(1); + await Task.FromResult(1); + await Task.FromResult(1); + yield return 1; + yield break; + yield break; + } + } + + """; + var src2 = s_asyncIteratorStateMachineAttributeSource + """ + + class C + { + static async IAsyncEnumerable F() + { + await foreach (var (x,y) in G()) { } + await foreach (var x in G()) { } + await using D x = new D(), y = new D(); + await Task.FromResult(1); + await Task.FromResult(1); + yield return 1; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -12506,24 +13560,28 @@ static async IAsyncEnumerable F() [Fact] public void Await_Update_GenericType() { - var src1 = @" -class C -{ - static async Task F() - { - await Task.FromResult(1); - } -} -"; - var src2 = @" -class C -{ - static async Task F() - { - await Task.FromResult(2); - } -} -"; + var src1 = """ + + class C + { + static async Task F() + { + await Task.FromResult(1); + } + } + + """; + var src2 = """ + + class C + { + static async Task F() + { + await Task.FromResult(2); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -12544,24 +13602,28 @@ static async Task F() [Fact] public void Await_Update_GenericMethod() { - var src1 = @" -class C -{ - static async Task F() - { - await Task.FromResult(1); - } -} -"; - var src2 = @" -class C -{ - static async Task F() - { - await Task.FromResult(2); - } -} -"; + var src1 = """ + + class C + { + static async Task F() + { + await Task.FromResult(1); + } + } + + """; + var src2 = """ + + class C + { + static async Task F() + { + await Task.FromResult(2); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -12582,36 +13644,40 @@ static async Task F() [Fact] public void Await_Update_GenericLocalFunction() { - var src1 = @" -class C -{ - void F() - { - void M() - { - async Task L() + var src1 = """ + + class C { - await Task.FromResult(1); + void F() + { + void M() + { + async Task L() + { + await Task.FromResult(1); + } + } + } } - } - } -} -"; - var src2 = @" -class C -{ - void F() - { - void M() - { - async Task L() + + """; + var src2 = """ + + class C { - await Task.FromResult(2); + void F() + { + void M() + { + async Task L() + { + await Task.FromResult(2); + } + } + } } - } - } -} -"; + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -12632,30 +13698,34 @@ async Task L() [Fact] public void MissingAsyncStateMachineAttribute() { - var src1 = @" -using System.Threading.Tasks; + var src1 = """ -class C -{ - static async Task F() - { - await new Task(); - return 1; - } -} -"; - var src2 = @" -using System.Threading.Tasks; + using System.Threading.Tasks; -class C -{ - static async Task F() - { - await new Task(); - return 2; - } -} -"; + class C + { + static async Task F() + { + await new Task(); + return 1; + } + } + + """; + var src2 = """ + + using System.Threading.Tasks; + + class C + { + static async Task F() + { + await new Task(); + return 2; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -12669,29 +13739,33 @@ static async Task F() [Fact] public void MissingAsyncStateMachineAttribute_MakeMethodAsync() { - var src1 = @" -using System.Threading.Tasks; + var src1 = """ -class C -{ - static Task F() - { - return null; - } -} -"; - var src2 = @" -using System.Threading.Tasks; + using System.Threading.Tasks; -class C -{ - static async Task F() - { - await new Task(); - return 2; - } -} -"; + class C + { + static Task F() + { + return null; + } + } + + """; + var src2 = """ + + using System.Threading.Tasks; + + class C + { + static async Task F() + { + await new Task(); + return 2; + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -12702,36 +13776,40 @@ static async Task F() [Fact] public void MissingAsyncStateMachineAttribute_LocalFunction() { - var src1 = @" -using System.Threading.Tasks; + var src1 = """ -class C -{ - void F() - { - async IAsyncEnumerable L() - { - await new Task(); - yield return 1; - } - } -} -"; - var src2 = @" -using System.Threading.Tasks; + using System.Threading.Tasks; -class C -{ - void F() - { - async IAsyncEnumerable L() - { - await new Task(); - yield return 2; - } - } -} -"; + class C + { + void F() + { + async IAsyncEnumerable L() + { + await new Task(); + yield return 1; + } + } + } + + """; + var src2 = """ + + using System.Threading.Tasks; + + class C + { + void F() + { + async IAsyncEnumerable L() + { + await new Task(); + yield return 2; + } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -12745,36 +13823,40 @@ async IAsyncEnumerable L() [Fact] public void SemanticError_AwaitInPropertyAccessor() { - var src1 = @" -using System.Threading.Tasks; + var src1 = """ -class C -{ - public Task P - { - get - { - await Task.Delay(1); - return 1; - } - } -} -"; - var src2 = @" -using System.Threading.Tasks; + using System.Threading.Tasks; -class C -{ - public Task P - { - get - { - await Task.Delay(2); - return 1; - } - } -} -"; + class C + { + public Task P + { + get + { + await Task.Delay(1); + return 1; + } + } + } + + """; + var src2 = """ + + using System.Threading.Tasks; + + class C + { + public Task P + { + get + { + await Task.Delay(2); + return 1; + } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } @@ -12786,12 +13868,16 @@ public Task P [Fact] public void OutVarType_Update() { - var src1 = @" -M(out var y); -"; - var src2 = @" -M(out int y); -"; + var src1 = """ + + M(out var y); + + """; + var src2 = """ + + M(out int y); + + """; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( @@ -12801,12 +13887,16 @@ public void OutVarType_Update() [Fact] public void OutVarNameAndType_Update() { - var src1 = @" -M(out var y); -"; - var src2 = @" -M(out int z); -"; + var src1 = """ + + M(out var y); + + """; + var src2 = """ + + M(out int z); + + """; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( @@ -12817,12 +13907,16 @@ public void OutVarNameAndType_Update() [Fact] public void OutVar_Insert() { - var src1 = @" -M(); -"; - var src2 = @" -M(out int y); -"; + var src1 = """ + + M(); + + """; + var src2 = """ + + M(out int y); + + """; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( @@ -12833,13 +13927,17 @@ public void OutVar_Insert() [Fact] public void OutVar_Delete() { - var src1 = @" -M(out int y); -"; + var src1 = """ + + M(out int y); + + """; + + var src2 = """ - var src2 = @" -M(); -"; + M(); + + """; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( @@ -12854,15 +13952,19 @@ public void OutVar_Delete() [Fact] public void ConstantPattern_Update() { - var src1 = @" -if ((o is null) && (y == 7)) return 3; -if (a is 7) return 5; -"; + var src1 = """ + + if ((o is null) && (y == 7)) return 3; + if (a is 7) return 5; + + """; + + var src2 = """ - var src2 = @" -if ((o1 is null) && (y == 7)) return 3; -if (a is 77) return 5; -"; + if ((o1 is null) && (y == 7)) return 3; + if (a is 77) return 5; + + """; var edits = GetMethodEdits(src1, src2); @@ -12874,19 +13976,23 @@ public void ConstantPattern_Update() [Fact] public void DeclarationPattern_Update() { - var src1 = @" -if (!(o is int i) && (y == 7)) return; -if (!(a is string s)) return; -if (!(b is string t)) return; -if (!(c is int j)) return; -"; + var src1 = """ + + if (!(o is int i) && (y == 7)) return; + if (!(a is string s)) return; + if (!(b is string t)) return; + if (!(c is int j)) return; + + """; + + var src2 = """ - var src2 = @" -if (!(o1 is int i) && (y == 7)) return; -if (!(a is int s)) return; -if (!(b is string t1)) return; -if (!(c is int)) return; -"; + if (!(o1 is int i) && (y == 7)) return; + if (!(a is int s)) return; + if (!(b is string t1)) return; + if (!(c is int)) return; + + """; var edits = GetMethodEdits(src1, src2); @@ -12914,19 +14020,23 @@ public void DeclarationPattern_Reorder() [Fact] public void VarPattern_Update() { - var src1 = @" -if (o is (var x, var y)) return; -if (o4 is (string a, var (b, c))) return; -if (o2 is var (e, f, g)) return; -if (o3 is var (k, l, m)) return; -"; + var src1 = """ + + if (o is (var x, var y)) return; + if (o4 is (string a, var (b, c))) return; + if (o2 is var (e, f, g)) return; + if (o3 is var (k, l, m)) return; + + """; + + var src2 = """ - var src2 = @" -if (o is (int x, int y1)) return; -if (o1 is (var a, (var b, string c1))) return; -if (o7 is var (g, e, f)) return; -if (o3 is (string k, int l2, int m)) return; -"; + if (o is (int x, int y1)) return; + if (o1 is (var a, (var b, string c1))) return; + if (o7 is var (g, e, f)) return; + if (o3 is (string k, int l2, int m)) return; + + """; var edits = GetMethodEdits(src1, src2); @@ -12978,40 +14088,46 @@ public void PositionalPattern_Update2() [Fact] public void PositionalPattern_Reorder() { - var src1 = @"var r = (x, y, z) switch { -(1, 2, 3) => 0, -(var a, 3, 4) => a, -(0, var b, int c) when c > 1 => 2, -(1, 1, Point { X: 0 } p) => 3, -_ => 4 -}; -"; - - var src2 = @"var r = ((x, y, z)) switch { -(1, 1, Point { X: 0 } p) => 3, -(0, var b, int c) when c > 1 => 2, -(var a, 3, 4) => a, -(1, 2, 3) => 0, -_ => 4 -}; -"; - - var edits = GetMethodEdits(src1, src2); - - edits.VerifyEdits( - @"Update [(x, y, z) switch { -(1, 2, 3) => 0, -(var a, 3, 4) => a, -(0, var b, int c) when c > 1 => 2, -(1, 1, Point { X: 0 } p) => 3, -_ => 4 -}]@10 -> [((x, y, z)) switch { -(1, 1, Point { X: 0 } p) => 3, -(0, var b, int c) when c > 1 => 2, -(var a, 3, 4) => a, -(1, 2, 3) => 0, -_ => 4 -}]@10", + var src1 = """ + var r = (x, y, z) switch { + (1, 2, 3) => 0, + (var a, 3, 4) => a, + (0, var b, int c) when c > 1 => 2, + (1, 1, Point { X: 0 } p) => 3, + _ => 4 + }; + + """; + + var src2 = """ + var r = ((x, y, z)) switch { + (1, 1, Point { X: 0 } p) => 3, + (0, var b, int c) when c > 1 => 2, + (var a, 3, 4) => a, + (1, 2, 3) => 0, + _ => 4 + }; + + """; + + var edits = GetMethodEdits(src1, src2); + + edits.VerifyEdits( + """ + Update [(x, y, z) switch { + (1, 2, 3) => 0, + (var a, 3, 4) => a, + (0, var b, int c) when c > 1 => 2, + (1, 1, Point { X: 0 } p) => 3, + _ => 4 + }]@10 -> [((x, y, z)) switch { + (1, 1, Point { X: 0 } p) => 3, + (0, var b, int c) when c > 1 => 2, + (var a, 3, 4) => a, + (1, 2, 3) => 0, + _ => 4 + }]@10 + """, "Reorder [(var a, 3, 4) => a]@47 -> @100", "Reorder [(0, var b, int c) when c > 1 => 2]@68 -> @64", "Reorder [(1, 1, Point { X: 0 } p) => 3]@104 -> @32"); @@ -13020,17 +14136,21 @@ public void PositionalPattern_Reorder() [Fact] public void PropertyPattern_Update() { - var src1 = @" -if (address is { State: ""WA"" }) return 1; -if (obj is { Color: Color.Purple }) return 2; -if (o is string { Length: 5 } s) return 3; -"; + var src1 = """ - var src2 = @" -if (address is { ZipCode: 98052 }) return 4; -if (obj is { Size: Size.M }) return 2; -if (o is string { Length: 7 } s7) return 5; -"; + if (address is { State: "WA" }) return 1; + if (obj is { Color: Color.Purple }) return 2; + if (o is string { Length: 5 } s) return 3; + + """; + + var src2 = """ + + if (address is { ZipCode: 98052 }) return 4; + if (obj is { Size: Size.M }) return 2; + if (o is string { Length: 7 } s7) return 5; + + """; var edits = GetMethodEdits(src1, src2); @@ -13046,29 +14166,33 @@ public void PropertyPattern_Update() [Fact] public void RecursivePatterns_Reorder() { - var src1 = @"var r = obj switch -{ - string s when s.Length > 0 => (s, obj1) switch - { - (""a"", int i) => i, - _ => 0 - }, - int i => i * i, - _ => -1 -}; -"; + var src1 = """ + var r = obj switch + { + string s when s.Length > 0 => (s, obj1) switch + { + ("a", int i) => i, + _ => 0 + }, + int i => i * i, + _ => -1 + }; - var src2 = @"var r = obj switch -{ - int i => i * i, - string s when s.Length > 0 => (s, obj1) switch - { - (""a"", int i) => i, - _ => 0 - }, - _ => -1 -}; -"; + """; + + var src2 = """ + var r = obj switch + { + int i => i * i, + string s when s.Length > 0 => (s, obj1) switch + { + ("a", int i) => i, + _ => 0 + }, + _ => -1 + }; + + """; var edits = GetMethodEdits(src1, src2); @@ -13081,22 +14205,26 @@ public void RecursivePatterns_Reorder() [Fact] public void CasePattern_UpdateInsert() { - var src1 = @" -switch(shape) -{ - case Circle c: return 1; - default: return 4; -} -"; + var src1 = """ - var src2 = @" -switch(shape) -{ - case Circle c1: return 1; - case Point p: return 0; - default: return 4; -} -"; + switch(shape) + { + case Circle c: return 1; + default: return 4; + } + + """; + + var src2 = """ + + switch(shape) + { + case Circle c1: return 1; + case Point p: return 0; + default: return 4; + } + + """; var edits = GetMethodEdits(src1, src2); @@ -13112,22 +14240,26 @@ public void CasePattern_UpdateInsert() [Fact] public void CasePattern_UpdateDelete() { - var src1 = @" -switch(shape) -{ - case Point p: return 0; - case Circle c: A(c); break; - default: return 4; -} -"; + var src1 = """ - var src2 = @" -switch(shape) -{ - case Circle c1: A(c1); break; - default: return 4; -} -"; + switch(shape) + { + case Point p: return 0; + case Circle c: A(c); break; + default: return 4; + } + + """; + + var src2 = """ + + switch(shape) + { + case Circle c1: A(c1); break; + default: return 4; + } + + """; var edits = GetMethodEdits(src1, src2); @@ -13144,21 +14276,25 @@ public void CasePattern_UpdateDelete() [Fact] public void WhenCondition_Update() { - var src1 = @" -switch(shape) -{ - case Circle c when (c < 10): return 1; - case Circle c when (c > 100): return 2; -} -"; + var src1 = """ - var src2 = @" -switch(shape) -{ - case Circle c when (c < 5): return 1; - case Circle c2 when (c2 > 100): return 2; -} -"; + switch(shape) + { + case Circle c when (c < 10): return 1; + case Circle c when (c > 100): return 2; + } + + """; + + var src2 = """ + + switch(shape) + { + case Circle c when (c < 5): return 1; + case Circle c2 when (c2 > 100): return 2; + } + + """; var edits = GetMethodEdits(src1, src2); @@ -13173,23 +14309,27 @@ public void WhenCondition_Update() [Fact] public void CasePatternWithWhenCondition_UpdateReorder() { - var src1 = @" -switch(shape) -{ - case Rectangle r: return 0; - case Circle c when (c.Radius < 10): return 1; - case Circle c when (c.Radius > 100): return 2; -} -"; + var src1 = """ - var src2 = @" -switch(shape) -{ - case Circle c when (c.Radius > 99): return 2; - case Circle c when (c.Radius < 10): return 1; - case Rectangle r: return 0; -} -"; + switch(shape) + { + case Rectangle r: return 0; + case Circle c when (c.Radius < 10): return 1; + case Circle c when (c.Radius > 100): return 2; + } + + """; + + var src2 = """ + + switch(shape) + { + case Circle c when (c.Radius > 99): return 2; + case Circle c when (c.Radius < 10): return 1; + case Rectangle r: return 0; + } + + """; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( @@ -13208,15 +14348,19 @@ public void CasePatternWithWhenCondition_UpdateReorder() [Fact] public void Ref_Update() { - var src1 = @" -ref int a = ref G(new int[] { 1, 2 }); -ref int G(int[] p) { return ref p[1]; } -"; + var src1 = """ - var src2 = @" -ref int32 a = ref G1(new int[] { 1, 2 }); -ref int G1(int[] p) { return ref p[2]; } -"; + ref int a = ref G(new int[] { 1, 2 }); + ref int G(int[] p) { return ref p[1]; } + + """; + + var src2 = """ + + ref int32 a = ref G1(new int[] { 1, 2 }); + ref int G1(int[] p) { return ref p[2]; } + + """; var edits = GetMethodEdits(src1, src2); @@ -13229,15 +14373,19 @@ public void Ref_Update() [Fact] public void Ref_Insert() { - var src1 = @" -int a = G(new int[] { 1, 2 }); -int G(int[] p) { return p[1]; } -"; + var src1 = """ - var src2 = @" -ref int32 a = ref G1(new int[] { 1, 2 }); -ref int G1(int[] p) { return ref p[2]; } -"; + int a = G(new int[] { 1, 2 }); + int G(int[] p) { return p[1]; } + + """; + + var src2 = """ + + ref int32 a = ref G1(new int[] { 1, 2 }); + ref int G1(int[] p) { return ref p[2]; } + + """; var edits = GetMethodEdits(src1, src2); @@ -13250,15 +14398,19 @@ public void Ref_Insert() [Fact] public void Ref_Delete() { - var src1 = @" -ref int a = ref G(new int[] { 1, 2 }); -ref int G(int[] p) { return ref p[1]; } -"; + var src1 = """ - var src2 = @" -int32 a = G1(new int[] { 1, 2 }); -int G1(int[] p) { return p[2]; } -"; + ref int a = ref G(new int[] { 1, 2 }); + ref int G(int[] p) { return ref p[1]; } + + """; + + var src2 = """ + + int32 a = G1(new int[] { 1, 2 }); + int G1(int[] p) { return p[2]; } + + """; var edits = GetMethodEdits(src1, src2); @@ -13275,17 +14427,21 @@ public void Ref_Delete() [Fact] public void TupleType_LocalVariables() { - var src1 = @" -(int a, string c) x = (a, string2); -(int a, int b) y = (3, 4); -(int a, int b, int c) z = (5, 6, 7); -"; + var src1 = """ - var src2 = @" -(int a, int b) x = (a, string2); -(int a, int b, string c) z1 = (5, 6, 7); -(int a, int b) y2 = (3, 4); -"; + (int a, string c) x = (a, string2); + (int a, int b) y = (3, 4); + (int a, int b, int c) z = (5, 6, 7); + + """; + + var src2 = """ + + (int a, int b) x = (a, string2); + (int a, int b, string c) z1 = (5, 6, 7); + (int a, int b) y2 = (3, 4); + + """; var edits = GetMethodEdits(src1, src2); @@ -13409,16 +14565,20 @@ public void WithExpression_PropertyValueReorder() [Fact] public void TopLevelStatement_Lambda_Update() { - var src1 = @" -using System; + var src1 = """ -var x = new Func(() => 1); -"; - var src2 = @" -using System; + using System; -var x = new Func(() => 2); -"; + var x = new Func(() => 1); + + """; + var src2 = """ + + using System; + + var x = new Func(() => 2); + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.
$"), preserveLocalVariables: true)]); @@ -13427,17 +14587,21 @@ public void TopLevelStatement_Lambda_Update() [Fact] public void TopLevelStatement_Lambda_Insert() { - var src1 = @" -using System; + var src1 = """ -Console.WriteLine(1); -"; - var src2 = @" -using System; + using System; + + Console.WriteLine(1); + + """; + var src2 = """ + + using System; + + Console.WriteLine(1); + var x = new Func(() => 2); -Console.WriteLine(1); -var x = new Func(() => 2); -"; + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.
$"), preserveLocalVariables: true)], @@ -13448,16 +14612,20 @@ public void TopLevelStatement_Lambda_Insert() [Fact] public void TopLevelStatement_Capture_Args() { - var src1 = @" -using System; + var src1 = """ + + using System; + + var x = new Func(() => null); + + """; + var src2 = """ + + using System; -var x = new Func(() => null); -"; - var src2 = @" -using System; + var x = new Func(() => args); -var x = new Func(() => args); -"; + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.
$"), preserveLocalVariables: true)]); @@ -13466,16 +14634,20 @@ public void TopLevelStatement_Capture_Args() [Fact] public void TopLevelStatement_CeaseCapture_Args() { - var src1 = @" -using System; + var src1 = """ + + using System; + + var x = new Func(() => args); + + """; + var src2 = """ + + using System; -var x = new Func(() => args); -"; - var src2 = @" -using System; + var x = new Func(() => null); -var x = new Func(() => null); -"; + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.
$"), preserveLocalVariables: true)); @@ -13484,24 +14656,28 @@ public void TopLevelStatement_CeaseCapture_Args() [Fact] public void TopLevelStatement_CeaseCapture_Args_Closure() { - var src1 = @" -using System; + var src1 = """ -var f1 = new Func(a1 => -{ - var f2 = new Func(a2 => args.Length + a2); - return a1; -}); -"; - var src2 = @" -using System; - -var f1 = new Func(a1 => -{ - var f2 = new Func(a2 => a2); - return a1 + args.Length; -}); -"; + using System; + + var f1 = new Func(a1 => + { + var f2 = new Func(a2 => args.Length + a2); + return a1; + }); + + """; + var src2 = """ + + using System; + + var f1 = new Func(a1 => + { + var f2 = new Func(a2 => a2); + return a1 + args.Length; + }); + + """; var edits = GetTopEdits(src1, src2); // y is no longer captured in f2 diff --git a/src/Features/CSharpTest/EditAndContinue/StatementMatchingTests.cs b/src/Features/CSharpTest/EditAndContinue/StatementMatchingTests.cs index acb9e66a2a28d..68b9e7d307660 100644 --- a/src/Features/CSharpTest/EditAndContinue/StatementMatchingTests.cs +++ b/src/Features/CSharpTest/EditAndContinue/StatementMatchingTests.cs @@ -5,6 +5,7 @@ #nullable disable using System.Collections.Generic; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; @@ -21,15 +22,15 @@ public sealed class StatementMatchingTests : EditingTestBase [Fact] public void KnownMatches() { - var src1 = @" -Console.WriteLine(1)/*1*/; -Console.WriteLine(1)/*2*/; -"; + var src1 = """ + Console.WriteLine(1)/*1*/; + Console.WriteLine(1)/*2*/; + """; - var src2 = @" -Console.WriteLine(1)/*3*/; -Console.WriteLine(1)/*4*/; -"; + var src2 = """ + Console.WriteLine(1)/*3*/; + Console.WriteLine(1)/*4*/; + """; var m1 = MakeMethodBody(src1); var m2 = MakeMethodBody(src2); @@ -71,13 +72,13 @@ public void KnownMatches() [Fact] public void KnownMatches_Root() { - var src1 = @" -Console.WriteLine(1); -"; + var src1 = """ + Console.WriteLine(1); + """; - var src2 = @" -Console.WriteLine(2); -"; + var src2 = """ + Console.WriteLine(2); + """; var m1 = MakeMethodBody(src1); var m2 = MakeMethodBody(src2); @@ -101,33 +102,34 @@ public void KnownMatches_Root() [Fact] public void MiscStatements() { - var src1 = @" -int x = 1; -Console.WriteLine(1); -x++/*1A*/; -Console.WriteLine(2); - -while (true) -{ - x++/*2A*/; -} - -Console.WriteLine(1); -"; - var src2 = @" -int x = 1; -x++/*1B*/; -for (int i = 0; i < 10; i++) {} -y++; -if (x > 1) -{ - while (true) - { - x++/*2B*/; - } - - Console.WriteLine(1); -}"; + var src1 = """ + int x = 1; + Console.WriteLine(1); + x++/*1A*/; + Console.WriteLine(2); + + while (true) + { + x++/*2A*/; + } + + Console.WriteLine(1); + """; + var src2 = """ + int x = 1; + x++/*1B*/; + for (int i = 0; i < 10; i++) {} + y++; + if (x > 1) + { + while (true) + { + x++/*2B*/; + } + + Console.WriteLine(1); + } + """; var match = GetMethodMatch(src1, src2); var actual = ToMatchingPairs(match); @@ -150,15 +152,15 @@ public void MiscStatements() [Fact] public void ThrowException_UpdateInsert() { - var src1 = @" -return a > 3 ? a : throw new Exception(); -return c > 7 ? c : 7; -"; + var src1 = """ + return a > 3 ? a : throw new Exception(); + return c > 7 ? c : 7; + """; - var src2 = @" -return a > 3 ? a : throw new ArgumentException(); -return c > 7 ? c : throw new IndexOutOfRangeException(); -"; + var src2 = """ + return a > 3 ? a : throw new ArgumentException(); + return c > 7 ? c : throw new IndexOutOfRangeException(); + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Regular); var actual = ToMatchingPairs(match); @@ -175,15 +177,15 @@ public void ThrowException_UpdateInsert() [Fact] public void ThrowException_UpdateDelete() { - var src1 = @" -return a > 3 ? a : throw new Exception(); -return b > 5 ? b : throw new OperationCanceledException(); -"; + var src1 = """ + return a > 3 ? a : throw new Exception(); + return b > 5 ? b : throw new OperationCanceledException(); + """; - var src2 = @" -return a > 3 ? a : throw new ArgumentException(); -return b > 5 ? b : 5; -"; + var src2 = """ + return a > 3 ? a : throw new ArgumentException(); + return b > 5 ? b : 5; + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Regular); var actual = ToMatchingPairs(match); @@ -200,23 +202,25 @@ public void ThrowException_UpdateDelete() [Fact] public void Tuple() { - var src1 = @" -return (1, 2); -return (d, 6); -return (10, e, 22); -return (2, () => { - int a = 6; - return 1; -});"; - - var src2 = @" -return (1, 2, 3); -return (d, 5); -return (10, e); -return (2, () => { - int a = 6; - return 5; -});"; + var src1 = """ + return (1, 2); + return (d, 6); + return (10, e, 22); + return (2, () => { + int a = 6; + return 1; + }); + """; + + var src2 = """ + return (1, 2, 3); + return (d, 5); + return (10, e); + return (2, () => { + int a = 6; + return 5; + }); + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Regular); var actual = ToMatchingPairs(match); @@ -246,12 +250,12 @@ public void Tuple() [Fact] public void Locals_Rename() { - var src1 = @" -int x = 1; -"; - var src2 = @" -int y = 1; -"; + var src1 = """ + int x = 1; + """; + var src2 = """ + int y = 1; + """; var match = GetMethodMatch(src1, src2); var actual = ToMatchingPairs(match); @@ -268,12 +272,12 @@ public void Locals_Rename() [Fact] public void Locals_TypeChange() { - var src1 = @" -int x = 1; -"; - var src2 = @" -byte x = 1; -"; + var src1 = """ + int x = 1; + """; + var src2 = """ + byte x = 1; + """; var match = GetMethodMatch(src1, src2); var actual = ToMatchingPairs(match); @@ -290,23 +294,23 @@ public void Locals_TypeChange() [Fact] public void BlocksWithLocals1() { - var src1 = @" -{ - int a = 1; -} -{ - int b = 2; -} -"; - var src2 = @" -{ - int a = 3; - int b = 4; -} -{ - int b = 5; -} -"; + var src1 = """ + { + int a = 1; + } + { + int b = 2; + } + """; + var src2 = """ + { + int a = 3; + int b = 4; + } + { + int b = 5; + } + """; var match = GetMethodMatch(src1, src2); var actual = ToMatchingPairs(match); @@ -328,27 +332,27 @@ public void BlocksWithLocals1() [Fact] public void IfBlocksWithLocals1() { - var src1 = @" -if (X) -{ - int a = 1; -} -if (Y) -{ - int b = 2; -} -"; - var src2 = @" -if (Y) -{ - int a = 3; - int b = 4; -} -if (X) -{ - int b = 5; -} -"; + var src1 = """ + if (X) + { + int a = 1; + } + if (Y) + { + int b = 2; + } + """; + var src2 = """ + if (Y) + { + int a = 3; + int b = 4; + } + if (X) + { + int b = 5; + } + """; var match = GetMethodMatch(src1, src2); var actual = ToMatchingPairs(match); @@ -372,26 +376,26 @@ public void IfBlocksWithLocals1() [Fact] public void BlocksWithLocals2() { - var src1 = @" -{ - int a = 1; -} -{ - { - int b = 2; - } -} -"; - var src2 = @" -{ - int b = 1; -} -{ - { - int a = 2; - } -} -"; + var src1 = """ + { + int a = 1; + } + { + { + int b = 2; + } + } + """; + var src2 = """ + { + int b = 1; + } + { + { + int a = 2; + } + } + """; var match = GetMethodMatch(src1, src2); var actual = ToMatchingPairs(match); @@ -414,34 +418,34 @@ public void BlocksWithLocals2() [Fact] public void BlocksWithLocals3() { - var src1 = @" -{ - int a = 1, b = 2, c = 3; - Console.WriteLine(a + b + c); -} -{ - int c = 4, b = 5, a = 6; - Console.WriteLine(a + b + c); -} -{ - int a = 7, b = 8; - Console.WriteLine(a + b); -} -"; - var src2 = @" -{ - int a = 9, b = 10; - Console.WriteLine(a + b); -} -{ - int c = 11, b = 12, a = 13; - Console.WriteLine(a + b + c); -} -{ - int a = 14, b = 15, c = 16; - Console.WriteLine(a + b + c); -} -"; + var src1 = """ + { + int a = 1, b = 2, c = 3; + Console.WriteLine(a + b + c); + } + { + int c = 4, b = 5, a = 6; + Console.WriteLine(a + b + c); + } + { + int a = 7, b = 8; + Console.WriteLine(a + b); + } + """; + var src2 = """ + { + int a = 9, b = 10; + Console.WriteLine(a + b); + } + { + int c = 11, b = 12, a = 13; + Console.WriteLine(a + b + c); + } + { + int a = 14, b = 15, c = 16; + Console.WriteLine(a + b + c); + } + """; var match = GetMethodMatch(src1, src2); var actual = ToMatchingPairs(match); @@ -475,15 +479,15 @@ public void BlocksWithLocals3() [Fact] public void VariableDesignations() { - var src1 = @" -M(out int z); -N(out var a); -"; + var src1 = """ + M(out int z); + N(out var a); + """; - var src2 = @" -M(out var z); -N(out var b); -"; + var src2 = """ + M(out var z); + N(out var b); + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Regular); var actual = ToMatchingPairs(match); @@ -502,15 +506,15 @@ public void VariableDesignations() [Fact] public void ParenthesizedVariable_Update() { - var src1 = @" -var (x1, (x2, x3, _)) = (1, (2, true, 3)); -var (a1, a2) = (1, () => { return 7; }); -"; + var src1 = """ + var (x1, (x2, x3, _)) = (1, (2, true, 3)); + var (a1, a2) = (1, () => { return 7; }); + """; - var src2 = @" -var (x1, (x3, x4)) = (1, (2, true)); -var (a1, a3) = (1, () => { return 8; }); -"; + var src2 = """ + var (x1, (x3, x4)) = (1, (2, true)); + var (a1, a3) = (1, () => { return 8; }); + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Regular); var actual = ToMatchingPairs(match); @@ -574,21 +578,21 @@ public void ParenthesizedVariable_Delete() [Fact] public void RefVariable() { - var src1 = @" -ref int a = ref G(new int[] { 1, 2 }); - ref int G(int[] p) - { - return ref p[1]; - } -"; - - var src2 = @" -ref int32 a = ref G1(new int[] { 1, 2 }); - ref int G1(int[] p) - { - return ref p[2]; - } -"; + var src1 = """ + ref int a = ref G(new int[] { 1, 2 }); + ref int G(int[] p) + { + return ref p[1]; + } + """; + + var src2 = """ + ref int32 a = ref G1(new int[] { 1, 2 }); + ref int G1(int[] p) + { + return ref p[2]; + } + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Regular); var actual = ToMatchingPairs(match); @@ -635,12 +639,12 @@ public void Lambdas1() [Fact] public void Lambdas2a() { - var src1 = @" -F(x => x + 1, 1, y => y + 1, delegate(int x) { return x; }, async u => u); -"; - var src2 = @" -F(y => y + 1, G(), x => x + 1, (int x) => x, u => u, async (u, v) => u + v); -"; + var src1 = """ + F(x => x + 1, 1, y => y + 1, delegate(int x) { return x; }, async u => u); + """; + var src2 = """ + F(y => y + 1, G(), x => x + 1, (int x) => x, u => u, async (u, v) => u + v); + """; var match = GetMethodMatch(src1, src2); var actual = ToMatchingPairs(match); @@ -664,12 +668,12 @@ public void Lambdas2a() [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/830419")] public void Lambdas2b() { - var src1 = @" -F(delegate { return x; }); -"; - var src2 = @" -F((a) => x, () => x); -"; + var src1 = """ + F(delegate { return x; }); + """; + var src2 = """ + F((a) => x, () => x); + """; var match = GetMethodMatch(src1, src2); var actual = ToMatchingPairs(match); @@ -686,12 +690,12 @@ public void Lambdas2b() [Fact] public void Lambdas3() { - var src1 = @" -a += async u => u; -"; - var src2 = @" -a += u => u; -"; + var src1 = """ + a += async u => u; + """; + var src2 = """ + a += u => u; + """; var match = GetMethodMatch(src1, src2); var actual = ToMatchingPairs(match); @@ -709,18 +713,18 @@ public void Lambdas3() [Fact] public void Lambdas4() { - var src1 = @" -foreach (var a in z) -{ - var e = from q in a.Where(l => l > 10) select q + 1; -} -"; - var src2 = @" -foreach (var a in z) -{ - var e = from q in a.Where(l => l < 0) select q + 1; -} -"; + var src1 = """ + foreach (var a in z) + { + var e = from q in a.Where(l => l > 10) select q + 1; + } + """; + var src2 = """ + foreach (var a in z) + { + var e = from q in a.Where(l => l < 0) select q + 1; + } + """; var match = GetMethodMatch(src1, src2); var actual = ToMatchingPairs(match); @@ -745,12 +749,12 @@ public void Lambdas4() [Fact] public void Lambdas5() { - var src1 = @" -F(a => b => c => d); -"; - var src2 = @" -F(a => b => c => d); -"; + var src1 = """ + F(a => b => c => d); + """; + var src2 = """ + F(a => b => c => d); + """; var matches = GetMethodMatches(src1, src2); var actual = ToMatchingPairs(matches); @@ -772,12 +776,12 @@ public void Lambdas5() [Fact] public void Lambdas6() { - var src1 = @" -F(a => b => c => d); -"; - var src2 = @" -F(a => G(b => H(c => I(d)))); -"; + var src1 = """ + F(a => b => c => d); + """; + var src2 = """ + F(a => G(b => H(c => I(d)))); + """; var matches = GetMethodMatches(src1, src2); var actual = ToMatchingPairs(matches); @@ -799,28 +803,28 @@ public void Lambdas6() [Fact] public void Lambdas7() { - var src1 = @" -F(a => -{ - F(c => /*1*/d); - F((u, v) => - { - F((w) => c => /*2*/d); - F(p => p); - }); -}); -"; - var src2 = @" -F(a => -{ - F(c => /*1*/d + 1); - F((u, v) => - { - F((w) => c => /*2*/d + 1); - F(p => p*2); - }); -}); -"; + var src1 = """ + F(a => + { + F(c => /*1*/d); + F((u, v) => + { + F((w) => c => /*2*/d); + F(p => p); + }); + }); + """; + var src2 = """ + F(a => + { + F(c => /*1*/d + 1); + F((u, v) => + { + F((w) => c => /*2*/d + 1); + F(p => p*2); + }); + }); + """; var matches = GetMethodMatches(src1, src2); var actual = ToMatchingPairs(matches); @@ -971,17 +975,17 @@ public void Lambdas_ParameterToDiscard() [Fact] public void LocalFunctionDefinitions() { - var src1 = @" -(int a, string c) F1(int i) { return null; } -(int a, int b) F2(int i) { return null; } -(int a, int b, int c) F3(int i) { return null; } -"; + var src1 = """ + (int a, string c) F1(int i) { return null; } + (int a, int b) F2(int i) { return null; } + (int a, int b, int c) F3(int i) { return null; } + """; - var src2 = @" -(int a, int b) F1(int i) { return null; } -(int a, int b, string c) F2(int i) { return null; } -(int a, int b) F3(int i) { return null; } -"; + var src2 = """ + (int a, int b) F1(int i) { return null; } + (int a, int b, string c) F2(int i) { return null; } + (int a, int b) F3(int i) { return null; } + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Regular); var actual = ToMatchingPairs(match); @@ -1029,17 +1033,17 @@ public void LocalFunctions1() [Fact] public void LocalFunctions2a() { - var src1 = @" -F(x => x + 1, 1, y => y + 1, delegate(int x) { return x; }, async u => u); -"; - var src2 = @" -int localF1(int y) => y + 1; -int localF2(int x) => x + 1; -int localF3(int x) => x; -int localF4(int u) => u; -async int localF5(int u, int v) => u + v; -F(localF1, localF2, G(), localF2, localF3, localF4, localF5); -"; + var src1 = """ + F(x => x + 1, 1, y => y + 1, delegate(int x) { return x; }, async u => u); + """; + var src2 = """ + int localF1(int y) => y + 1; + int localF2(int x) => x + 1; + int localF3(int x) => x; + int localF4(int u) => u; + async int localF5(int u, int v) => u + v; + F(localF1, localF2, G(), localF2, localF3, localF4, localF5); + """; var match = GetMethodMatch(src1, src2); var actual = ToMatchingPairs(match); @@ -1061,13 +1065,13 @@ public void LocalFunctions2a() [Fact] public void LocalFunctions2b() { - var src1 = @" -F(delegate { return x; }); -"; - var src2 = @" -int localF() => x; -F(localF); -"; + var src1 = """ + F(delegate { return x; }); + """; + var src2 = """ + int localF() => x; + F(localF); + """; var match = GetMethodMatch(src1, src2); var actual = ToMatchingPairs(match); @@ -1084,13 +1088,13 @@ public void LocalFunctions2b() [Fact] public void LocalFunctions3() { - var src1 = @" -a += async u => u; -"; - var src2 = @" -object localF(object u) => u; -a += localF; -"; + var src1 = """ + a += async u => u; + """; + var src2 = """ + object localF(object u) => u; + a += localF; + """; var match = GetMethodMatch(src1, src2); var actual = ToMatchingPairs(match); @@ -1142,43 +1146,43 @@ public void LocalFunctions4() [Fact] public void LocalFunctions5() { - var src1 = @" -void G6(int a) -{ - int G5(int c) => /*1*/d; - F(G5); - - void G4() - { - void G1(int x) => x; - int G3(int w) - { - int G2(int c) => /*2*/d; - return G2(w); - } - F(G3); - F(G1); - }; - F(G4); -} -"; - - var src2 = @" -void G6(int a) -{ - int G5(int c) => /*1*/d + 1;F(G5); - - void G4() - { - int G3(int w) - { - int G2(int c) => /*2*/d + 1; return G2(w); - } - F(G3); F(G1); int G6(int p) => p *2; F(G6); - } - F(G4); -} -"; + var src1 = """ + void G6(int a) + { + int G5(int c) => /*1*/d; + F(G5); + + void G4() + { + void G1(int x) => x; + int G3(int w) + { + int G2(int c) => /*2*/d; + return G2(w); + } + F(G3); + F(G1); + }; + F(G4); + } + """; + + var src2 = """ + void G6(int a) + { + int G5(int c) => /*1*/d + 1;F(G5); + + void G4() + { + int G3(int w) + { + int G2(int c) => /*2*/d + 1; return G2(w); + } + F(G3); F(G1); int G6(int p) => p *2; F(G6); + } + F(G4); + } + """; var matches = GetMethodMatches(src1, src2); var actual = ToMatchingPairs(matches); @@ -1271,18 +1275,18 @@ public void LocalFunctions6Reverse() [Fact] public void Queries1() { - var src1 = @" -var q = from c in cars - from ud in users_details - from bd in bids - select 1; -"; - var src2 = @" -var q = from c in cars - from bd in bids - from ud in users_details - select 2; -"; + var src1 = """ + var q = from c in cars + from ud in users_details + from bd in bids + select 1; + """; + var src2 = """ + var q = from c in cars + from bd in bids + from ud in users_details + select 2; + """; var match = GetMethodMatch(src1, src2); var actual = ToMatchingPairs(match); @@ -1305,36 +1309,36 @@ from ud in users_details [Fact] public void Queries2() { - var src1 = @" -var q = from c in cars - from ud in users_details - from bd in bids - orderby c.listingOption descending - where a.userID == ud.userid - let images = from ai in auction_images - where ai.belongs_to == c.id - select ai - let bid = (from b in bids - orderby b.id descending - where b.carID == c.id - select b.bidamount).FirstOrDefault() - select bid; -"; - var src2 = @" -var q = from c in cars - from ud in users_details - from bd in bids - orderby c.listingOption descending - where a.userID == ud.userid - let images = from ai in auction_images - where ai.belongs_to == c.id2 - select ai + 1 - let bid = (from b in bids - orderby b.id ascending - where b.carID == c.id2 - select b.bidamount).FirstOrDefault() - select bid; -"; + var src1 = """ + var q = from c in cars + from ud in users_details + from bd in bids + orderby c.listingOption descending + where a.userID == ud.userid + let images = from ai in auction_images + where ai.belongs_to == c.id + select ai + let bid = (from b in bids + orderby b.id descending + where b.carID == c.id + select b.bidamount).FirstOrDefault() + select bid; + """; + var src2 = """ + var q = from c in cars + from ud in users_details + from bd in bids + orderby c.listingOption descending + where a.userID == ud.userid + let images = from ai in auction_images + where ai.belongs_to == c.id2 + select ai + 1 + let bid = (from b in bids + orderby b.id ascending + where b.carID == c.id2 + select b.bidamount).FirstOrDefault() + select bid; + """; var match = GetMethodMatches(src1, src2); var actual = ToMatchingPairs(match); @@ -1377,19 +1381,18 @@ orderby b.id ascending [Fact] public void Queries3() { - var src1 = @" -var q = from a in await seq1 - join c in await seq2 on F(u => u) equals G(s => s) into g1 - join l in await seq3 on F(v => v) equals G(t => t) into g2 - select a; - -"; - var src2 = @" -var q = from a in await seq1 - join c in await seq2 on F(u => u + 1) equals G(s => s + 3) into g1 - join c in await seq3 on F(vv => vv + 2) equals G(tt => tt + 4) into g2 - select a + 1; -"; + var src1 = """ + var q = from a in await seq1 + join c in await seq2 on F(u => u) equals G(s => s) into g1 + join l in await seq3 on F(v => v) equals G(t => t) into g2 + select a; + """; + var src2 = """ + var q = from a in await seq1 + join c in await seq2 on F(u => u + 1) equals G(s => s + 3) into g1 + join c in await seq3 on F(vv => vv + 2) equals G(tt => tt + 4) into g2 + select a + 1; + """; var match = GetMethodMatches(src1, src2, MethodKind.Async); var actual = ToMatchingPairs(match); @@ -1474,14 +1477,14 @@ public void Queries5() [Fact] public void Yields() { - var src1 = @" -yield return 0; -yield return 1; -"; - var src2 = @" -yield break; -yield return 1; -"; + var src1 = """ + yield return 0; + yield return 1; + """; + var src2 = """ + yield break; + yield return 1; + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Iterator); var actual = ToMatchingPairs(match); @@ -1498,15 +1501,15 @@ public void Yields() [Fact] public void YieldReturn_Add() { - var src1 = @" -yield return /*1*/ 1; -yield return /*2*/ 2; -"; - var src2 = @" -yield return /*3*/ 3; -yield return /*1*/ 1; -yield return /*2*/ 2; -"; + var src1 = """ + yield return /*1*/ 1; + yield return /*2*/ 2; + """; + var src2 = """ + yield return /*3*/ 3; + yield return /*1*/ 1; + yield return /*2*/ 2; + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Iterator); var actual = ToMatchingPairs(match); @@ -1523,20 +1526,20 @@ public void YieldReturn_Add() [Fact] public void YieldReturn_Swap1() { - var src1 = @" -A(); -yield return /*1*/ 1; -B(); -yield return /*2*/ 2; -C(); -"; - var src2 = @" -B(); -yield return /*2*/ 2; -A(); -yield return /*1*/ 1; -C(); -"; + var src1 = """ + A(); + yield return /*1*/ 1; + B(); + yield return /*2*/ 2; + C(); + """; + var src2 = """ + B(); + yield return /*2*/ 2; + A(); + yield return /*1*/ 1; + C(); + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Iterator); var actual = ToMatchingPairs(match); @@ -1556,20 +1559,20 @@ public void YieldReturn_Swap1() [Fact] public void YieldReturn_Swap2() { - var src1 = @" -yield return /*1*/ 1; + var src1 = """ + yield return /*1*/ 1; -{ - yield return /*2*/ 2; -} + { + yield return /*2*/ 2; + } -foreach (var x in y) { yield return /*3*/ 3; } -"; - var src2 = @" -yield return /*1*/ 1; -yield return /*2*/ 3; -foreach (var x in y) { yield return /*3*/ 2; } -"; + foreach (var x in y) { yield return /*3*/ 3; } + """; + var src2 = """ + yield return /*1*/ 1; + yield return /*2*/ 3; + foreach (var x in y) { yield return /*3*/ 2; } + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Iterator); var actual = ToMatchingPairs(match); @@ -1611,22 +1614,22 @@ public void AwaitExpressions() [Fact] public void Awaits() { - var src1 = @" -await x; -await using (expr) {} -await using (D y = new D()) {} -await using D y = new D(); -await foreach (var z in w) {} -await foreach (var (u, v) in w) {} -"; - var src2 = @" -await foreach (var (u, v) in w) {} -await foreach (var z in w) {} -await using D y = new D(); -await using (D y = new D()) {} -await using (expr) {} -await x; -"; + var src1 = """ + await x; + await using (expr) {} + await using (D y = new D()) {} + await using D y = new D(); + await foreach (var z in w) {} + await foreach (var (u, v) in w) {} + """; + var src2 = """ + await foreach (var (u, v) in w) {} + await foreach (var z in w) {} + await using D y = new D(); + await using (D y = new D()) {} + await using (expr) {} + await x; + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Async); var actual = ToMatchingPairs(match); @@ -1658,12 +1661,12 @@ public void Awaits() [Fact] public void Await_To_AwaitUsingExpression() { - var src1 = @" -await x; -"; - var src2 = @" -await using (expr) {} -"; + var src1 = """ + await x; + """; + var src2 = """ + await using (expr) {} + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Async); var actual = ToMatchingPairs(match); @@ -1676,12 +1679,12 @@ public void Await_To_AwaitUsingExpression() [Fact] public void Await_To_AwaitUsingDecl() { - var src1 = @" -await x; -"; - var src2 = @" -await using D y = new D(); -"; + var src1 = """ + await x; + """; + var src2 = """ + await using D y = new D(); + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Async); var actual = ToMatchingPairs(match); @@ -1695,12 +1698,12 @@ public void Await_To_AwaitUsingDecl() [Fact] public void AwaitUsingDecl_To_AwaitUsingStatement() { - var src1 = @" -await using D y = new D(); -"; - var src2 = @" -await using (D y = new D()) { } -"; + var src1 = """ + await using D y = new D(); + """; + var src2 = """ + await using (D y = new D()) { } + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Async); var actual = ToMatchingPairs(match); @@ -1713,12 +1716,12 @@ public void AwaitUsingDecl_To_AwaitUsingStatement() [Fact] public void AwaitUsingExpression_To_AwaitUsingStatementWithSingleVariable() { - var src1 = @" -await using (y = new D()) { } -"; - var src2 = @" -await using (D y = new D()) { } -"; + var src1 = """ + await using (y = new D()) { } + """; + var src2 = """ + await using (D y = new D()) { } + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Async); var actual = ToMatchingPairs(match); @@ -1736,12 +1739,12 @@ public void AwaitUsingExpression_To_AwaitUsingStatementWithSingleVariable() [Fact] public void AwaitUsingExpression_To_AwaitUsingStatementWithMultipleVariables() { - var src1 = @" -await using (y = new D()) { } -"; - var src2 = @" -await using (D y = new D(), z = new D()) { } -"; + var src1 = """ + await using (y = new D()) { } + """; + var src2 = """ + await using (D y = new D(), z = new D()) { } + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Async); var actual = ToMatchingPairs(match); @@ -1778,12 +1781,12 @@ public void AwaitUsingMatchesUSing() [Fact] public void Await_To_AwaitForeach() { - var src1 = @" -await x; -"; - var src2 = @" -await foreach (var x in y) {} -"; + var src1 = """ + await x; + """; + var src2 = """ + await foreach (var x in y) {} + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Async); var actual = ToMatchingPairs(match); @@ -1797,12 +1800,12 @@ public void Await_To_AwaitForeach() [Fact] public void Await_To_AwaitForeachVar() { - var src1 = @" -await x; -"; - var src2 = @" -await foreach (var (x, y) in z) {} -"; + var src1 = """ + await x; + """; + var src2 = """ + await foreach (var (x, y) in z) {} + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Async); var actual = ToMatchingPairs(match); @@ -1816,12 +1819,12 @@ public void Await_To_AwaitForeachVar() [Fact] public void AwaitForeach_To_AwaitForeachVar() { - var src1 = @" -await foreach (var x in y) {} -"; - var src2 = @" -await foreach (var (u, v) in y) {} -"; + var src1 = """ + await foreach (var x in y) {} + """; + var src2 = """ + await foreach (var (u, v) in y) {} + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Async); var actual = ToMatchingPairs(match); @@ -1866,12 +1869,12 @@ public void AwaitForeachMatchesForeach() [Fact] public void ConstructorWithInitializer1() { - var src1 = @" -(int x = 1) : base(a => a + 1) { Console.WriteLine(1); } -"; - var src2 = @" -(int x = 1) : base(a => a + 1) { Console.WriteLine(1); } -"; + var src1 = """ + (int x = 1) : base(a => a + 1) { Console.WriteLine(1); } + """; + var src2 = """ + (int x = 1) : base(a => a + 1) { Console.WriteLine(1); } + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.ConstructorWithParameters); var actual = ToMatchingPairs(match); @@ -1892,12 +1895,12 @@ public void ConstructorWithInitializer1() [Fact] public void ConstructorWithInitializer2() { - var src1 = @" -() : base(a => a + 1) { Console.WriteLine(1); } -"; - var src2 = @" -() { Console.WriteLine(1); } -"; + var src1 = """ + () : base(a => a + 1) { Console.WriteLine(1); } + """; + var src2 = """ + () { Console.WriteLine(1); } + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.ConstructorWithParameters); var actual = ToMatchingPairs(match); @@ -1919,16 +1922,16 @@ public void ConstructorWithInitializer2() [Fact] public void ExceptionHandlers() { - var src1 = @" -try { throw new InvalidOperationException(1); } -catch (IOException e) when (filter(e)) { Console.WriteLine(2); } -catch (Exception e) when (filter(e)) { Console.WriteLine(3); } -"; - var src2 = @" -try { throw new InvalidOperationException(10); } -catch (IOException e) when (filter(e)) { Console.WriteLine(20); } -catch (Exception e) when (filter(e)) { Console.WriteLine(30); } -"; + var src1 = """ + try { throw new InvalidOperationException(1); } + catch (IOException e) when (filter(e)) { Console.WriteLine(2); } + catch (Exception e) when (filter(e)) { Console.WriteLine(3); } + """; + var src2 = """ + try { throw new InvalidOperationException(10); } + catch (IOException e) when (filter(e)) { Console.WriteLine(20); } + catch (Exception e) when (filter(e)) { Console.WriteLine(30); } + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Regular); var actual = ToMatchingPairs(match); @@ -1960,15 +1963,15 @@ public void ExceptionHandlers() [Fact] public void ForeachVariable_Update1() { - var src1 = @" -foreach (var (a1, a2) in e) { A1(); } -foreach ((var b1, var b2) in e) { A2(); } -"; + var src1 = """ + foreach (var (a1, a2) in e) { A1(); } + foreach ((var b1, var b2) in e) { A2(); } + """; - var src2 = @" -foreach (var (a1, a3) in e) { A1(); } -foreach ((var b3, int b2) in e) { A2(); } -"; + var src2 = """ + foreach (var (a1, a3) in e) { A1(); } + foreach ((var b3, int b2) in e) { A2(); } + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Regular); var actual = ToMatchingPairs(match); @@ -1993,15 +1996,15 @@ public void ForeachVariable_Update1() [Fact] public void ForeachVariable_Update2() { - var src1 = @" -foreach (_ in e2) { } -foreach (_ in e3) { A(); } -"; + var src1 = """ + foreach (_ in e2) { } + foreach (_ in e3) { A(); } + """; - var src2 = @" -foreach (_ in e4) { A(); } -foreach (var b in e2) { } -"; + var src2 = """ + foreach (_ in e4) { A(); } + foreach (var b in e2) { } + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Regular); var actual = ToMatchingPairs(match); @@ -2021,15 +2024,15 @@ public void ForeachVariable_Update2() [Fact] public void ForeachVariable_Insert() { - var src1 = @" -foreach (var ((a3, a4), _) in e) { } -foreach ((var b4, var b5) in e) { } -"; + var src1 = """ + foreach (var ((a3, a4), _) in e) { } + foreach ((var b4, var b5) in e) { } + """; - var src2 = @" -foreach (var ((a3, a5, a4), _) in e) { } -foreach ((var b6, var b4, var b5) in e) { } -"; + var src2 = """ + foreach (var ((a3, a5, a4), _) in e) { } + foreach ((var b6, var b4, var b5) in e) { } + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Regular); var actual = ToMatchingPairs(match); @@ -2052,15 +2055,15 @@ public void ForeachVariable_Insert() [Fact] public void ForeachVariable_Delete() { - var src1 = @" -foreach (var (a11, a12, a13) in e) { A1(); } -foreach ((var b7, var b8, var b9) in e) { A2(); } -"; + var src1 = """ + foreach (var (a11, a12, a13) in e) { A1(); } + foreach ((var b7, var b8, var b9) in e) { A2(); } + """; - var src2 = @" -foreach (var (a12, a13) in e1) { A1(); } -foreach ((var b7, var b9) in e) { A2(); } -"; + var src2 = """ + foreach (var (a12, a13) in e1) { A1(); } + foreach ((var b7, var b9) in e) { A2(); } + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Regular); var actual = ToMatchingPairs(match); @@ -2089,15 +2092,15 @@ public void ForeachVariable_Delete() [Fact] public void ConstantPattern() { - var src1 = @" -if ((o is null) && (y == 7)) return 3; -if (a is 7) return 5; -"; + var src1 = """ + if ((o is null) && (y == 7)) return 3; + if (a is 7) return 5; + """; - var src2 = @" -if ((o1 is null) && (y == 7)) return 3; -if (a is 77) return 5; -"; + var src2 = """ + if ((o1 is null) && (y == 7)) return 3; + if (a is 77) return 5; + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Regular); var actual = ToMatchingPairs(match); @@ -2115,19 +2118,19 @@ public void ConstantPattern() [Fact] public void DeclarationPattern() { - var src1 = @" -if (!(o is int i) && (y == 7)) return; -if (!(a is string s)) return; -if (!(b is string t)) return; -if (!(c is int j)) return; -"; + var src1 = """ + if (!(o is int i) && (y == 7)) return; + if (!(a is string s)) return; + if (!(b is string t)) return; + if (!(c is int j)) return; + """; - var src2 = @" -if (!(b is string t1)) return; -if (!(o1 is int i) && (y == 7)) return; -if (!(c is int)) return; -if (!(a is int s)) return; -"; + var src2 = """ + if (!(b is string t1)) return; + if (!(o1 is int i) && (y == 7)) return; + if (!(c is int)) return; + if (!(a is int s)) return; + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Regular); var actual = ToMatchingPairs(match); @@ -2152,19 +2155,19 @@ public void DeclarationPattern() [Fact] public void VarPattern() { - var src1 = @" -if (!(o is (var x, var y))) return; -if (!(o4 is (string a, var (b, c)))) return; -if (!(o2 is var (e, f, g))) return; -if (!(o3 is var (k, l, m))) return; -"; - - var src2 = @" -if (!(o is (int x, int y1))) return; -if (!(o1 is (var a, (var b, string c1)))) return; -if (!(o7 is var (g, e, f))) return; -if (!(o3 is (string k, int l2, int m))) return; -"; + var src1 = """ + if (!(o is (var x, var y))) return; + if (!(o4 is (string a, var (b, c)))) return; + if (!(o2 is var (e, f, g))) return; + if (!(o3 is var (k, l, m))) return; + """; + + var src2 = """ + if (!(o is (int x, int y1))) return; + if (!(o1 is (var a, (var b, string c1)))) return; + if (!(o7 is var (g, e, f))) return; + if (!(o3 is (string k, int l2, int m))) return; + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Regular); var actual = ToMatchingPairs(match); @@ -2196,23 +2199,25 @@ public void VarPattern() [Fact] public void PositionalPattern() { - var src1 = @"var r = (x, y, z) switch { -(1, 2, 3) => 0, -(var a, 3, 4) => a, -(0, var b, int c) when c > 1 => 2, -(1, 1, Point { X: 0 } p) => 3, -_ => 4 -}; -"; - - var src2 = @"var r = ((x, y, z)) switch { -(1, 2, 3) => 0, -(var a1, 3, 4) => a1 * 2, -(_, int b1, double c1) when c1 > 2 => c1, -(1, 1, Point { Y: 0 } p1) => 3, -_ => 4 -}; -"; + var src1 = """ + var r = (x, y, z) switch { + (1, 2, 3) => 0, + (var a, 3, 4) => a, + (0, var b, int c) when c > 1 => 2, + (1, 1, Point { X: 0 } p) => 3, + _ => 4 + }; + """; + + var src2 = """ + var r = ((x, y, z)) switch { + (1, 2, 3) => 0, + (var a1, 3, 4) => a1 * 2, + (_, int b1, double c1) when c1 > 2 => c1, + (1, 1, Point { Y: 0 } p1) => 3, + _ => 4 + }; + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Regular); var actual = ToMatchingPairs(match); @@ -2240,17 +2245,17 @@ public void PositionalPattern() [Fact] public void PropertyPattern() { - var src1 = @" -if (address is { State: ""WA"" }) return 1; -if (obj is { Color: Color.Purple }) return 2; -if (o is string { Length: 5 } s) return 3; -"; + var src1 = """ + if (address is { State: "WA" }) return 1; + if (obj is { Color: Color.Purple }) return 2; + if (o is string { Length: 5 } s) return 3; + """; - var src2 = @" -if (address is { ZipCode: 98052 }) return 4; -if (obj is { Size: Size.M }) return 2; -if (o is string { Length: 7 } s7) return 5; -"; + var src2 = """ + if (address is { ZipCode: 98052 }) return 4; + if (obj is { Size: Size.M }) return 2; + if (o is string { Length: 7 } s7) return 5; + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Regular); var actual = ToMatchingPairs(match); @@ -2271,31 +2276,33 @@ public void PropertyPattern() [Fact] public void RecursivePatterns() { - var src1 = @"var r = obj switch -{ - string s when s.Length > 0 => (s, obj1) switch - { - (""a"", int i) => i, - ("""", Task t) => await t, - _ => 0 - }, - int i => i * i, - _ => -1 -}; -"; - - var src2 = @"var r = obj switch -{ - string s when s.Length > 0 => (s, obj1) switch - { - (""b"", decimal i1) => i1, - ("""", Task obj2) => await obj2, - _ => 0 - }, - double i => i * i, - _ => -1 -}; -"; + var src1 = """ + var r = obj switch + { + string s when s.Length > 0 => (s, obj1) switch + { + ("a", int i) => i, + ("", Task t) => await t, + _ => 0 + }, + int i => i * i, + _ => -1 + }; + """; + + var src2 = """ + var r = obj switch + { + string s when s.Length > 0 => (s, obj1) switch + { + ("b", decimal i1) => i1, + ("", Task obj2) => await obj2, + _ => 0 + }, + double i => i * i, + _ => -1 + }; + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Async); var actual = ToMatchingPairs(match); @@ -2327,22 +2334,22 @@ public void RecursivePatterns() [Fact] public void CasePattern_UpdateInsert() { - var src1 = @" -switch(shape) -{ - case Circle c: return 1; - default: return 4; -} -"; - - var src2 = @" -switch(shape) -{ - case Circle c1: return 1; - case Point p: return 0; - default: return 4; -} -"; + var src1 = """ + switch(shape) + { + case Circle c: return 1; + default: return 4; + } + """; + + var src2 = """ + switch(shape) + { + case Circle c1: return 1; + case Point p: return 0; + default: return 4; + } + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Regular); var actual = ToMatchingPairs(match); @@ -2363,20 +2370,20 @@ public void CasePattern_UpdateInsert() [Fact] public void CasePattern_UpdateDelete() { - var src1 = @" -switch(shape) -{ - case Point p: return 0; - case Circle c: return 1; -} -"; - - var src2 = @" -switch(shape) -{ - case Circle circle: return 1; -} -"; + var src1 = """ + switch(shape) + { + case Point p: return 0; + case Circle c: return 1; + } + """; + + var src2 = """ + switch(shape) + { + case Circle circle: return 1; + } + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Regular); var actual = ToMatchingPairs(match); @@ -2395,21 +2402,21 @@ public void CasePattern_UpdateDelete() [Fact] public void WhenCondition() { - var src1 = @" -switch(shape) -{ - case Circle c when (c < 10): return 1; - case Circle c when (c > 100): return 2; -} -"; - - var src2 = @" -switch(shape) -{ - case Circle c when (c < 5): return 1; - case Circle c2 when (c2 > 100): return 2; -} -"; + var src1 = """ + switch(shape) + { + case Circle c when (c < 10): return 1; + case Circle c when (c > 100): return 2; + } + """; + + var src2 = """ + switch(shape) + { + case Circle c when (c < 5): return 1; + case Circle c2 when (c2 > 100): return 2; + } + """; var match = GetMethodMatches(src1, src2, kind: MethodKind.Regular); var actual = ToMatchingPairs(match); @@ -2504,30 +2511,30 @@ public void SwitchExpressionArms_NestedDissimilar() [Fact] public void TopLevelStatements() { - var src1 = @" -Console.WriteLine(1); -Console.WriteLine(2); - -var x = 0; -while (true) -{ - x++; -} - -Console.WriteLine(3); -"; - var src2 = @" -Console.WriteLine(4); -Console.WriteLine(5); - -var x = 1; -while (true) -{ - x--; -} - -Console.WriteLine(6); -"; + var src1 = """ + Console.WriteLine(1); + Console.WriteLine(2); + + var x = 0; + while (true) + { + x++; + } + + Console.WriteLine(3); + """; + var src2 = """ + Console.WriteLine(4); + Console.WriteLine(5); + + var x = 1; + while (true) + { + x--; + } + + Console.WriteLine(6); + """; var match = GetTopEdits(src1, src2).Match; var actual = ToMatchingPairs(match); diff --git a/src/Features/CSharpTest/EditAndContinue/SyntaxUtilitiesTests.cs b/src/Features/CSharpTest/EditAndContinue/SyntaxUtilitiesTests.cs index 866c94383dc11..2d1d6a2d34813 100644 --- a/src/Features/CSharpTest/EditAndContinue/SyntaxUtilitiesTests.cs +++ b/src/Features/CSharpTest/EditAndContinue/SyntaxUtilitiesTests.cs @@ -31,77 +31,74 @@ private static void VerifySyntaxMap(string oldSource, string newSource) [Fact] public void FindPartner1() { - var source1 = @" -using System; + VerifySyntaxMap(""" + using System; -class C -{ - static void Main(string[] args) - { - - // sdasd - var b = true; - do - { - Console.WriteLine(""hi""); - } while (b == true); - } -} -"; - - var source2 = @" -using System; + class C + { + static void Main(string[] args) + { + + // sdasd + var b = true; + do + { + Console.WriteLine("hi"); + } while (b == true); + } + } + """, """ + using System; -class C -{ - static void Main(string[] args) - { - var b = true; - do - { - Console.WriteLine(""hi""); - } while (b == true); - } -} -"; - VerifySyntaxMap(source1, source2); + class C + { + static void Main(string[] args) + { + var b = true; + do + { + Console.WriteLine("hi"); + } while (b == true); + } + } + """); } [Fact] public void FindLeafNodeAndPartner1() { - var leftRoot = SyntaxFactory.ParseSyntaxTree(@" -using System; + var leftRoot = SyntaxFactory.ParseSyntaxTree(""" + using System; -class C -{ - public void M() - { - if (0 == 1) - { - Console.WriteLine(0); - } - } -} -").GetRoot(); + class C + { + public void M() + { + if (0 == 1) + { + Console.WriteLine(0); + } + } + } + """).GetRoot(); var leftPosition = leftRoot.DescendantNodes().OfType().ElementAt(2).SpanStart; // 0 within Console.WriteLine(0) - var rightRoot = SyntaxFactory.ParseSyntaxTree(@" -using System; + var rightRoot = SyntaxFactory.ParseSyntaxTree(""" + using System; -class C -{ - public void M() - { - if (0 == 1) - { - if (2 == 3) + class C { - Console.WriteLine(0); + public void M() + { + if (0 == 1) + { + if (2 == 3) + { + Console.WriteLine(0); + } + } + } } - } - } -} -").GetRoot(); + """).GetRoot(); AbstractEditAndContinueAnalyzer.FindLeafNodeAndPartner(leftRoot, leftPosition, rightRoot, out var leftNode, out var rightNodeOpt); Assert.Equal("0", leftNode.ToString()); @@ -113,45 +110,45 @@ public void FindLeafNodeAndPartner2() { // Check that the method does not fail even if the index of the child (4) // is greater than the count of children on the corresponding (from the upper side) node (3). - var leftRoot = SyntaxFactory.ParseSyntaxTree(@" -using System; + var leftRoot = SyntaxFactory.ParseSyntaxTree(""" + using System; -class C -{ - public void M() - { - if (0 == 1) - { - Console.WriteLine(0); - Console.WriteLine(1); - Console.WriteLine(2); - Console.WriteLine(3); - } - } -} -").GetRoot(); + class C + { + public void M() + { + if (0 == 1) + { + Console.WriteLine(0); + Console.WriteLine(1); + Console.WriteLine(2); + Console.WriteLine(3); + } + } + } + """).GetRoot(); var leftPosition = leftRoot.DescendantNodes().OfType().ElementAt(5).SpanStart; // 3 within Console.WriteLine(3) - var rightRoot = SyntaxFactory.ParseSyntaxTree(@" -using System; + var rightRoot = SyntaxFactory.ParseSyntaxTree(""" + using System; -class C -{ - public void M() - { - if (0 == 1) - { - if (2 == 3) + class C { - Console.WriteLine(0); - Console.WriteLine(1); - Console.WriteLine(2); - Console.WriteLine(3); + public void M() + { + if (0 == 1) + { + if (2 == 3) + { + Console.WriteLine(0); + Console.WriteLine(1); + Console.WriteLine(2); + Console.WriteLine(3); + } + } + } } - } - } -} -").GetRoot(); + """).GetRoot(); AbstractEditAndContinueAnalyzer.FindLeafNodeAndPartner(leftRoot, leftPosition, rightRoot, out var leftNode, out var rightNodeOpt); Assert.Equal("3", leftNode.ToString()); @@ -161,25 +158,25 @@ public void M() [Fact] public void IsAsyncDeclaration() { - var tree = SyntaxFactory.ParseSyntaxTree(@" -class C -{ - async Task M0() => 1; - async Task M1() => await Task.FromResult(1); - async Task M2() { return await Task.FromResult(1); } + var tree = SyntaxFactory.ParseSyntaxTree(""" + class C + { + async Task M0() => 1; + async Task M1() => await Task.FromResult(1); + async Task M2() { return await Task.FromResult(1); } - void M3() - { - async Task f1() => await Task.FromResult(1); - async Task f2() { return await Task.FromResult(1); } + void M3() + { + async Task f1() => await Task.FromResult(1); + async Task f2() { return await Task.FromResult(1); } - var l1 = new Func>(async () => await Task.FromResult(1)); - var l2 = new Func>(async () => { return await Task.FromResult(1); }); + var l1 = new Func>(async () => await Task.FromResult(1)); + var l2 = new Func>(async () => { return await Task.FromResult(1); }); - var l3 = new Func>(async delegate () { return await Task.FromResult(1); }); - } -} -"); + var l3 = new Func>(async delegate () { return await Task.FromResult(1); }); + } + } + """); var m0 = tree.GetRoot().DescendantNodes().OfType().Single(m => m.Identifier.ValueText == "M0"); var m1 = tree.GetRoot().DescendantNodes().OfType().Single(m => m.Identifier.ValueText == "M1"); @@ -222,32 +219,32 @@ void M3() [Fact] public void GetSuspensionPoints() { - var tree = SyntaxFactory.ParseSyntaxTree(@" -class C -{ - IEnumerable X = new[] { 1, 2, 3 }; + var tree = SyntaxFactory.ParseSyntaxTree(""" + class C + { + IEnumerable X = new[] { 1, 2, 3 }; - IEnumerable M1() { yield return 1; } - - void M2() - { - IAsyncEnumerable f() - { - yield return 1; + IEnumerable M1() { yield return 1; } - yield break; + void M2() + { + IAsyncEnumerable f() + { + yield return 1; - await Task.FromResult(1); + yield break; - await foreach (var x in F()) { } + await Task.FromResult(1); - await foreach (var (x, y) in F()) { } + await foreach (var x in F()) { } - await using T x1 = F1(), x2 = F2(), x3 = F3(); - } - } -} -"); + await foreach (var (x, y) in F()) { } + + await using T x1 = F1(), x2 = F2(), x3 = F3(); + } + } + } + """); var x = tree.GetRoot().DescendantNodes().OfType().Single(m => m.Identifier.ValueText == "X"); var m1 = tree.GetRoot().DescendantNodes().OfType().Single(m => m.Identifier.ValueText == "M1"); diff --git a/src/Features/CSharpTest/EditAndContinue/TopLevelEditingTests.cs b/src/Features/CSharpTest/EditAndContinue/TopLevelEditingTests.cs index 03bc4fdf81a70..aa73825dbaf69 100644 --- a/src/Features/CSharpTest/EditAndContinue/TopLevelEditingTests.cs +++ b/src/Features/CSharpTest/EditAndContinue/TopLevelEditingTests.cs @@ -24,22 +24,28 @@ namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests; [UseExportProvider] public sealed class TopLevelEditingTests : EditingTestBase { - private static readonly string s_attributeSource = @" -[System.AttributeUsage(System.AttributeTargets.All)]class A : System.Attribute { public A() {} public A(int x) { } } -"; + private static readonly string s_attributeSource = """ + + [System.AttributeUsage(System.AttributeTargets.All)]class A : System.Attribute { public A() {} public A(int x) { } } + + """; #region Usings [Fact] public void Using_Global_Insert1() { - var src1 = @" -using System.Collections.Generic; -"; - var src2 = @" -global using D = System.Diagnostics; -global using System.Collections; -using System.Collections.Generic; -"; + var src1 = """ + + using System.Collections.Generic; + + """; + var src2 = """ + + global using D = System.Diagnostics; + global using System.Collections; + using System.Collections.Generic; + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -52,14 +58,18 @@ public void Using_Global_Insert1() [Fact] public void Using_Global_Insert2() { - var src1 = @" -using unsafe D3 = int*; -"; - var src2 = @" -global using D1 = int; -using D2 = (int, int); -using unsafe D3 = int*; -"; + var src1 = """ + + using unsafe D3 = int*; + + """; + var src2 = """ + + global using D1 = int; + using D2 = (int, int); + using unsafe D3 = int*; + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -72,9 +82,11 @@ public void Using_Global_Insert2() [Fact] public void Using_Delete1() { - var src1 = @" -using System.Diagnostics; -"; + var src1 = """ + + using System.Diagnostics; + + """; var src2 = @""; var edits = GetTopEdits(src1, src2); @@ -86,14 +98,18 @@ public void Using_Delete1() [Fact] public void Using_Delete2() { - var src1 = @" -using D = System.Diagnostics; -using System.Collections; -using System.Collections.Generic; -"; - var src2 = @" -using System.Collections.Generic; -"; + var src1 = """ + + using D = System.Diagnostics; + using System.Collections; + using System.Collections.Generic; + + """; + var src2 = """ + + using System.Collections.Generic; + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -106,14 +122,18 @@ public void Using_Delete2() [Fact] public void Using_Delete3() { - var src1 = @" -global using D1 = int; -using D2 = (int, int); -using unsafe D3 = int*; -"; - var src2 = @" -using D2 = (int, int); -"; + var src1 = """ + + global using D1 = int; + using D2 = (int, int); + using unsafe D3 = int*; + + """; + var src2 = """ + + using D2 = (int, int); + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -126,14 +146,18 @@ public void Using_Delete3() [Fact] public void Using_Insert1() { - var src1 = @" -using System.Collections.Generic; -"; - var src2 = @" -using D = System.Diagnostics; -using System.Collections; -using System.Collections.Generic; -"; + var src1 = """ + + using System.Collections.Generic; + + """; + var src2 = """ + + using D = System.Diagnostics; + using System.Collections; + using System.Collections.Generic; + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -146,15 +170,19 @@ public void Using_Insert1() [Fact] public void Using_Insert2() { - var src1 = @" -using System.Collections.Generic; -"; - var src2 = @" -global using D1 = int; -using D2 = (int, int); -using unsafe D3 = int*; -using System.Collections.Generic; -"; + var src1 = """ + + using System.Collections.Generic; + + """; + var src2 = """ + + global using D1 = int; + using D2 = (int, int); + using unsafe D3 = int*; + using System.Collections.Generic; + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -168,16 +196,20 @@ public void Using_Insert2() [Fact] public void Using_Update1() { - var src1 = @" -using System.Diagnostics; -using System.Collections; -using System.Collections.Generic; -"; - var src2 = @" -using System.Diagnostics; -using X = System.Collections; -using System.Collections.Generic; -"; + var src1 = """ + + using System.Diagnostics; + using System.Collections; + using System.Collections.Generic; + + """; + var src2 = """ + + using System.Diagnostics; + using X = System.Collections; + using System.Collections.Generic; + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -189,16 +221,20 @@ public void Using_Update1() [Fact] public void Using_Update2() { - var src1 = @" -using System.Diagnostics; -using X1 = System.Collections; -using System.Collections.Generic; -"; - var src2 = @" -using System.Diagnostics; -using X2 = System.Collections; -using System.Collections.Generic; -"; + var src1 = """ + + using System.Diagnostics; + using X1 = System.Collections; + using System.Collections.Generic; + + """; + var src2 = """ + + using System.Diagnostics; + using X2 = System.Collections; + using System.Collections.Generic; + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -210,16 +246,20 @@ public void Using_Update2() [Fact] public void Using_Update3() { - var src1 = @" -using System.Diagnostics; -using System.Collections; -using System.Collections.Generic; -"; - var src2 = @" -using System; -using System.Collections; -using System.Collections.Generic; -"; + var src1 = """ + + using System.Diagnostics; + using System.Collections; + using System.Collections.Generic; + + """; + var src2 = """ + + using System; + using System.Collections; + using System.Collections.Generic; + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -231,16 +271,20 @@ public void Using_Update3() [Fact] public void Using_Update4() { - var src1 = @" -using X = int; -using Y = int; -using Z = int; -"; - var src2 = @" -using X = string; -using unsafe Y = int*; -global using Z = int; -"; + var src1 = """ + + using X = int; + using Y = int; + using Z = int; + + """; + var src2 = """ + + using X = string; + using unsafe Y = int*; + global using Z = int; + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -254,16 +298,20 @@ public void Using_Update4() [Fact] public void Using_Reorder1() { - var src1 = @" -using System.Diagnostics; -using System.Collections; -using System.Collections.Generic; -"; - var src2 = @" -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; -"; + var src1 = """ + + using System.Diagnostics; + using System.Collections; + using System.Collections.Generic; + + """; + var src2 = """ + + using System.Collections; + using System.Collections.Generic; + using System.Diagnostics; + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -273,14 +321,18 @@ public void Using_Reorder1() [Fact] public void Using_Reorder2() { - var src1 = @" -using X = int; -using Y = string; -"; - var src2 = @" -using Y = string; -using X = int; -"; + var src1 = """ + + using X = int; + using Y = string; + + """; + var src2 = """ + + using Y = string; + using X = int; + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -290,26 +342,30 @@ public void Using_Reorder2() [Fact] public void Using_InsertDelete1() { - var src1 = @" -namespace N -{ - using System.Collections; -} + var src1 = """ -namespace M -{ -} -"; - var src2 = @" -namespace N -{ -} + namespace N + { + using System.Collections; + } -namespace M -{ - using System.Collections; -} -"; + namespace M + { + } + + """; + var src2 = """ + + namespace N + { + } + + namespace M + { + using System.Collections; + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -320,19 +376,23 @@ namespace M [Fact] public void Using_InsertDelete2() { - var src1 = @" -namespace N -{ - using System.Collections; -} -"; - var src2 = @" -using System.Collections; + var src1 = """ -namespace N -{ -} -"; + namespace N + { + using System.Collections; + } + + """; + var src2 = """ + + using System.Collections; + + namespace N + { + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -346,47 +406,51 @@ public void Using_Delete_ChangesCodeMeaning() // This test specifically validates the scenario we _don't_ support, namely when inserting or deleting // a using directive, if existing code changes in meaning as a result, we don't issue edits for that code. // If this ever regresses then please buy a lottery ticket because the feature has magically fixed itself. - var src1 = @" -using System.IO; -using DirectoryInfo = N.C; + var src1 = """ -namespace N -{ - public class C - { - public C(string a) { } - public FileAttributes Attributes { get; set; } - } + using System.IO; + using DirectoryInfo = N.C; - public class D - { - public void M() - { - var d = new DirectoryInfo(""aa""); - var x = directoryInfo.Attributes; - } - } -}"; - var src2 = @" -using System.IO; + namespace N + { + public class C + { + public C(string a) { } + public FileAttributes Attributes { get; set; } + } -namespace N -{ - public class C - { - public C(string a) { } - public FileAttributes Attributes { get; set; } - } + public class D + { + public void M() + { + var d = new DirectoryInfo("aa"); + var x = directoryInfo.Attributes; + } + } + } + """; + var src2 = """ - public class D - { - public void M() - { - var d = new DirectoryInfo(""aa""); - var x = directoryInfo.Attributes; - } - } -}"; + using System.IO; + + namespace N + { + public class C + { + public C(string a) { } + public FileAttributes Attributes { get; set; } + } + + public class D + { + public void M() + { + var d = new DirectoryInfo("aa"); + var x = directoryInfo.Attributes; + } + } + } + """; var edits = GetTopEdits(src1, src2); @@ -400,29 +464,33 @@ public void Using_Insert_ForNewCode() { // As distinct from the above, this test validates a real world scenario of inserting a using directive // and changing code that utilizes the new directive to some effect. - var src1 = @" -namespace N -{ - class Program - { - static void F() - { - } - } -}"; - var src2 = @" -using System; + var src1 = """ -namespace N -{ - class Program - { - static void F() - { - Console.WriteLine(""Hello World!""); - } - } -}"; + namespace N + { + class Program + { + static void F() + { + } + } + } + """; + var src2 = """ + + using System; + + namespace N + { + class Program + { + static void F() + { + Console.WriteLine("Hello World!"); + } + } + } + """; var edits = GetTopEdits(src1, src2); @@ -432,29 +500,33 @@ static void F() [Fact] public void Using_Delete_ForOldCode() { - var src1 = @" -using System; + var src1 = """ -namespace N -{ - class Program - { - static void F() - { - Console.WriteLine(""Hello World!""); - } - } -}"; - var src2 = @" -namespace N -{ - class Program - { - static void F() - { - } - } -}"; + using System; + + namespace N + { + class Program + { + static void F() + { + Console.WriteLine("Hello World!"); + } + } + } + """; + var src2 = """ + + namespace N + { + class Program + { + static void F() + { + } + } + } + """; var edits = GetTopEdits(src1, src2); @@ -466,41 +538,45 @@ public void Using_Insert_CreatesAmbiguousCode() { // This test validates that we still issue edits for changed valid code, even when unchanged // code has ambiguities after adding a using. - var src1 = @" -using System.Threading; - -namespace N -{ - class C - { - void M() - { - // Timer exists in System.Threading and System.Timers - var t = new Timer(s => System.Console.WriteLine(s)); - } - } -}"; - var src2 = @" -using System.Threading; -using System.Timers; + var src1 = """ -namespace N -{ - class C - { - void M() - { - // Timer exists in System.Threading and System.Timers - var t = new Timer(s => System.Console.WriteLine(s)); - } + using System.Threading; - void M2() - { - // TimersDescriptionAttribute only exists in System.Timers - System.Console.WriteLine(new TimersDescriptionAttribute("""")); - } - } -}"; + namespace N + { + class C + { + void M() + { + // Timer exists in System.Threading and System.Timers + var t = new Timer(s => System.Console.WriteLine(s)); + } + } + } + """; + var src2 = """ + + using System.Threading; + using System.Timers; + + namespace N + { + class C + { + void M() + { + // Timer exists in System.Threading and System.Timers + var t = new Timer(s => System.Console.WriteLine(s)); + } + + void M2() + { + // TimersDescriptionAttribute only exists in System.Timers + System.Console.WriteLine(new TimersDescriptionAttribute("")); + } + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -715,12 +791,10 @@ public void Type_Modifiers_Accessibility_Change(string accessibility) public void Type_Modifiers_Accessibility_Partial(string accessibilityA, string accessibilityB) { var srcA1 = accessibilityA + " partial class C { }"; - var srcB1 = "partial class C { }"; - var srcA2 = "partial class C { }"; var srcB2 = accessibilityB + " partial class C { }"; EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(srcA1, "partial class C { }"), GetTopEdits("partial class C { }", srcB2)], [ DocumentResults(), DocumentResults(), @@ -826,34 +900,38 @@ public void Type_Modifiers_Unsafe_Add() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_Remove() { - var src1 = @" -using System; -unsafe delegate void D(); -class C -{ - unsafe class N { } - public unsafe event Action A { add { } remove { } } - unsafe int F() => 0; - unsafe int X; - unsafe int Y { get; } - unsafe C() {} - unsafe ~C() {} -} -"; - var src2 = @" -using System; -delegate void D(); -class C -{ - class N { } - public event Action A { add { } remove { } } - int F() => 0; - int X; - int Y { get; } - C() {} - ~C() {} -} -"; + var src1 = """ + + using System; + unsafe delegate void D(); + class C + { + unsafe class N { } + public unsafe event Action A { add { } remove { } } + unsafe int F() => 0; + unsafe int X; + unsafe int Y { get; } + unsafe C() {} + unsafe ~C() {} + } + + """; + var src2 = """ + + using System; + delegate void D(); + class C + { + class N { } + public event Action A { add { } remove { } } + int F() => 0; + int X; + int Y { get; } + C() {} + ~C() {} + } + + """; var edits = GetTopEdits(src1, src2); @@ -873,13 +951,8 @@ public event Action A { add { } remove { } } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_DeleteInsert() { - var srcA1 = "partial class C { unsafe void F() { } }"; - var srcB1 = "partial class C { }"; - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { void F() { } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { unsafe void F() { } }", "partial class C { }"), GetTopEdits("partial class C { }", "partial class C { void F() { } }")], [ DocumentResults(), DocumentResults(semanticEdits: @@ -1137,10 +1210,12 @@ public void Type_Attribute_Delete_InlineArray(string keyword) [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1831006")] public void Type_Attribute_Update_Null() { - var attribute = @" -using System; -public class A : Attribute { public A1(int[] array, Type type, Type[] types) {} } -"; + var attribute = """ + + using System; + public class A : Attribute { public A1(int[] array, Type type, Type[] types) {} } + + """; var src1 = attribute + "[A(null, null, new Type[] { typeof(C) })]class C { }"; var src2 = attribute + "[A(null, null, null)]class C { }"; @@ -1155,11 +1230,13 @@ public class A : Attribute { public A1(int[] array, Type type, Type[] types) {} [Fact] public void Type_Attribute_Change_Reloadable() { - var attributeSrc = @" -public class A1 : System.Attribute { } -public class A2 : System.Attribute { } -public class A3 : System.Attribute { } -"; + var attributeSrc = """ + + public class A1 : System.Attribute { } + public class A2 : System.Attribute { } + public class A3 : System.Attribute { } + + """; var src1 = ReloadableAttributeSrc + attributeSrc + "[CreateNewOnMetadataUpdate, A1, A2]class C { }"; var src2 = ReloadableAttributeSrc + attributeSrc + "[CreateNewOnMetadataUpdate, A2, A3]class C { }"; @@ -1247,13 +1324,9 @@ class B : System.Attribute { } """; var srcA1 = attributes + "[CreateNewOnMetadataUpdate]partial class C { }"; - var srcB1 = "partial class C { }"; - var srcA2 = attributes + "[CreateNewOnMetadataUpdate][A]partial class C { }"; - var srcB2 = "[B]partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(srcA1, srcA2), GetTopEdits("partial class C { }", "[B]partial class C { }")], [ DocumentResults(semanticEdits: [ @@ -1660,18 +1733,22 @@ public void Type_BaseInterface_Add() [Fact] public void Type_BaseInterface_Delete_Inherited() { - var src1 = @" -interface B {} -interface A : B {} + var src1 = """ + + interface B {} + interface A : B {} + + class C : A, B {} + + """; + var src2 = """ -class C : A, B {} -"; - var src2 = @" -interface B {} -interface A : B {} + interface B {} + interface A : B {} -class C : A {} -"; + class C : A {} + + """; var edits = GetTopEdits(src1, src2); @@ -1726,18 +1803,15 @@ public void Type_BaseInterface_Update_RuntimeTypeChanged(string oldType, string [Fact] public void Type_Base_Partial() { - var srcA1 = "partial class C : B, I { }"; - var srcB1 = "partial class C : J { }"; - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C : B, I, J { }"; + var srcC = """ - var srcC = @" -class B {} -interface I {} -interface J {}"; + class B {} + interface I {} + interface J {} + """; EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC, srcC)], + [GetTopEdits("partial class C : B, I { }", "partial class C { }"), GetTopEdits("partial class C : J { }", "partial class C : B, I, J { }"), GetTopEdits(srcC, srcC)], [ DocumentResults(), DocumentResults(), @@ -1748,16 +1822,8 @@ interface J {}"; [Fact] public void Type_Base_Partial_InsertDeleteAndUpdate() { - var srcA1 = "partial class C { }"; - var srcB1 = ""; - var srcC1 = "partial class C { }"; - - var srcA2 = ""; - var srcB2 = "partial class C : D { }"; - var srcC2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2)], + [GetTopEdits("partial class C { }", ""), GetTopEdits("", "partial class C : D { }"), GetTopEdits("partial class C { }", "partial class C { }")], [ DocumentResults(), @@ -1771,18 +1837,15 @@ public void Type_Base_Partial_InsertDeleteAndUpdate() [Fact] public void Type_Base_InsertDelete() { - var srcA1 = ""; - var srcB1 = "class C : B, I { }"; - var srcA2 = "class C : B, I { }"; - var srcB2 = ""; + var srcC = """ - var srcC = @" -class B {} -interface I {} -interface J {}"; + class B {} + interface I {} + interface J {} + """; EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC, srcC)], + [GetTopEdits("", "class C : B, I { }"), GetTopEdits("class C : B, I { }", ""), GetTopEdits(srcC, srcC)], [ DocumentResults(), DocumentResults(), @@ -1793,18 +1856,22 @@ interface J {}"; [Fact] public void Type_Reloadable_NotSupportedByRuntime() { - var src1 = ReloadableAttributeSrc + @" -[CreateNewOnMetadataUpdate] -public class C -{ - void F() { System.Console.WriteLine(1); } -}"; - var src2 = ReloadableAttributeSrc + @" -[CreateNewOnMetadataUpdate] -public class C -{ - void F() { System.Console.WriteLine(2); } -}"; + var src1 = ReloadableAttributeSrc + """ + + [CreateNewOnMetadataUpdate] + public class C + { + void F() { System.Console.WriteLine(1); } + } + """; + var src2 = ReloadableAttributeSrc + """ + + [CreateNewOnMetadataUpdate] + public class C + { + void F() { System.Console.WriteLine(2); } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -1816,13 +1883,15 @@ public class C public void Type_Insert_AbstractVirtualOverride() { var src1 = ""; - var src2 = @" -public abstract class C -{ - public abstract void F(); - public virtual void G() {} - public override string ToString() => null; -}"; + var src2 = """ + + public abstract class C + { + public abstract void F(); + public virtual void G() {} + public override string ToString() => null; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -1832,27 +1901,31 @@ public virtual void G() {} [Fact] public void Type_Insert_NotSupportedByRuntime() { - var src1 = @" -public class C -{ - void F() - { - } -}"; - var src2 = @" -public class C -{ - void F() - { - } -} + var src1 = """ -public class D -{ - void M() - { - } -}"; + public class C + { + void F() + { + } + } + """; + var src2 = """ + + public class C + { + void F() + { + } + } + + public class D + { + void M() + { + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -1898,12 +1971,14 @@ class C public void InterfaceInsert() { var src1 = ""; - var src2 = @" -public interface I -{ - void F(); - static void G() {} -}"; + var src2 = """ + + public interface I + { + void F(); + static void G() {} + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -1976,12 +2051,10 @@ public void Struct_ReadonlyModifier_Add() public void Struct_Modifiers_Partial_InsertDelete(string modifier) { var srcA1 = modifier + " partial struct S { }"; - var srcB1 = "partial struct S { }"; - var srcA2 = "partial struct S { }"; var srcB2 = modifier + " partial struct S { }"; EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(srcA1, "partial struct S { }"), GetTopEdits("partial struct S { }", srcB2)], [ DocumentResults(), DocumentResults() @@ -2121,58 +2194,62 @@ class C : I [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37128")] public void Interface_InsertMembers() { - var src1 = @" -using System; -interface I -{ -} -"; - var src2 = @" -using System; -interface I -{ - static int StaticField = 10; - - static void StaticMethod() { } - void VirtualMethod1() { } - virtual void VirtualMethod2() { } - abstract void AbstractMethod(); - sealed void NonVirtualMethod() { } - - public static int operator +(I a, I b) => 1; - - static int StaticProperty1 { get => 1; set { } } - static int StaticProperty2 => 1; - virtual int VirtualProperty1 { get => 1; set { } } - virtual int VirtualProperty2 { get => 1; } - int VirtualProperty3 { get => 1; set { } } - int VirtualProperty4 { get => 1; } - abstract int AbstractProperty1 { get; set; } - abstract int AbstractProperty2 { get; } - sealed int NonVirtualProperty => 1; - - int this[byte virtualIndexer] => 1; - int this[sbyte virtualIndexer] { get => 1; } - virtual int this[ushort virtualIndexer] { get => 1; set {} } - virtual int this[short virtualIndexer] { get => 1; set {} } - abstract int this[uint abstractIndexer] { get; set; } - abstract int this[int abstractIndexer] { get; } - sealed int this[ulong nonVirtualIndexer] { get => 1; set {} } - sealed int this[long nonVirtualIndexer] { get => 1; set {} } - - static event Action StaticEvent; - static event Action StaticEvent2 { add { } remove { } } - - event Action VirtualEvent { add { } remove { } } - abstract event Action AbstractEvent; - sealed event Action NonVirtualEvent { add { } remove { } } - - abstract class C { } - interface J { } - enum E { } - delegate void D(); -} -"; + var src1 = """ + + using System; + interface I + { + } + + """; + var src2 = """ + + using System; + interface I + { + static int StaticField = 10; + + static void StaticMethod() { } + void VirtualMethod1() { } + virtual void VirtualMethod2() { } + abstract void AbstractMethod(); + sealed void NonVirtualMethod() { } + + public static int operator +(I a, I b) => 1; + + static int StaticProperty1 { get => 1; set { } } + static int StaticProperty2 => 1; + virtual int VirtualProperty1 { get => 1; set { } } + virtual int VirtualProperty2 { get => 1; } + int VirtualProperty3 { get => 1; set { } } + int VirtualProperty4 { get => 1; } + abstract int AbstractProperty1 { get; set; } + abstract int AbstractProperty2 { get; } + sealed int NonVirtualProperty => 1; + + int this[byte virtualIndexer] => 1; + int this[sbyte virtualIndexer] { get => 1; } + virtual int this[ushort virtualIndexer] { get => 1; set {} } + virtual int this[short virtualIndexer] { get => 1; set {} } + abstract int this[uint abstractIndexer] { get; set; } + abstract int this[int abstractIndexer] { get; } + sealed int this[ulong nonVirtualIndexer] { get => 1; set {} } + sealed int this[long nonVirtualIndexer] { get => 1; set {} } + + static event Action StaticEvent; + static event Action StaticEvent2 { add { } remove { } } + + event Action VirtualEvent { add { } remove { } } + abstract event Action AbstractEvent; + sealed event Action NonVirtualEvent { add { } remove { } } + + abstract class C { } + interface J { } + enum E { } + delegate void D(); + } + + """; var edits = GetTopEdits(src1, src2); // TODO: InsertIntoInterface errors are reported due to https://github.com/dotnet/roslyn/issues/37128. @@ -2211,25 +2288,28 @@ enum E { } [Fact] public void Interface_InsertDelete() { - var srcA1 = @" -interface I -{ - static void M() { } -} -"; - var srcB1 = @" -"; - - var srcA2 = @" -"; - var srcB2 = @" -interface I -{ - static void M() { } -} -"; EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(""" + + interface I + { + static void M() { } + } + + """, """ + + + """), GetTopEdits(""" + + + """, """ + + interface I + { + static void M() { } + } + + """)], [ DocumentResults(), @@ -2244,37 +2324,41 @@ static void M() { } [Fact] public void Type_Generic_Insert_StatelessMembers() { - var src1 = @" -using System; -class C -{ - int P1 { get => 1; } - int this[string s] { set {} } -} -"; - var src2 = @" -using System; -class C -{ - C(int x) {} - - void M() {} - void G() {} - int P1 { get => 1; set {} } - int P2 { get => 1; set {} } - int this[int i] { set {} get => 1; } - int this[string s] { set {} get => 1; } - event Action E { add {} remove {} } - - enum E {} - interface I {} - interface I {} - class D {} - class D {} - delegate void Del(); - delegate void Del(); -} -"; + var src1 = """ + + using System; + class C + { + int P1 { get => 1; } + int this[string s] { set {} } + } + + """; + var src2 = """ + + using System; + class C + { + C(int x) {} + + void M() {} + void G() {} + int P1 { get => 1; set {} } + int P2 { get => 1; set {} } + int this[int i] { set {} get => 1; } + int this[string s] { set {} get => 1; } + event Action E { add {} remove {} } + + enum E {} + interface I {} + interface I {} + class D {} + class D {} + delegate void Del(); + delegate void Del(); + } + + """; var edits = GetTopEdits(src1, src2); var diagnostics = new[] @@ -2299,22 +2383,26 @@ class D {} [Fact] public void Type_Generic_Insert_DataMembers() { - var src1 = @" -using System; -class C -{ -} -"; - var src2 = @" -using System; -class C -{ - int P { get; set; } - event Action EF; - int F1, F2; - static int SF; -} -"; + var src1 = """ + + using System; + class C + { + } + + """; + var src2 = """ + + using System; + class C + { + int P { get; set; } + event Action EF; + int F1, F2; + static int SF; + } + + """; var edits = GetTopEdits(src1, src2); var nonGenericCapabilities = @@ -2352,25 +2440,29 @@ class C [Fact] public void Type_Generic_Insert_IntoNestedType() { - var src1 = @" -class C -{ - class D - { - } -} -"; - var src2 = @" -class C -{ - class D - { - void F() {} - int X; - static int Y; - } -} -"; + var src1 = """ + + class C + { + class D + { + } + } + + """; + var src2 = """ + + class C + { + class D + { + void F() {} + int X; + static int Y; + } + } + + """; var edits = GetTopEdits(src1, src2); var nonGenericCapabilities = @@ -2394,60 +2486,66 @@ void F() {} [Fact] public void Type_Generic_InsertMembers_Reloadable() { - var src1 = ReloadableAttributeSrc + @" -interface IExplicit -{ - void F() {} -} + var src1 = ReloadableAttributeSrc + """ -[CreateNewOnMetadataUpdate] -class C : IExplicit -{ - void IExplicit.F() {} -} -"; - var src2 = ReloadableAttributeSrc + @" -interface IExplicit -{ - void F() {} -} + interface IExplicit + { + void F() {} + } -[CreateNewOnMetadataUpdate] -class C : IExplicit -{ - void IExplicit.F() {} - - void M() {} - int P1 { get; set; } - int P2 { get => 1; set {} } - int this[int i] { get => 1; set {} } - event System.Action E { add {} remove {} } - event System.Action EF; - int F1, F2; - - enum E {} - interface I {} - class D {} -} -"; - var edits = GetTopEdits(src1, src2); - edits.VerifySemantics( - [SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))], - capabilities: EditAndContinueCapabilities.NewTypeDefinition | EditAndContinueCapabilities.AddExplicitInterfaceImplementation); + [CreateNewOnMetadataUpdate] + class C : IExplicit + { + void IExplicit.F() {} + } - edits.VerifySemanticDiagnostics( - [Diagnostic(RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, "void M()", "CreateNewOnMetadataUpdateAttribute")], - capabilities: EditAndContinueCapabilities.NewTypeDefinition); - } + """; + var src2 = ReloadableAttributeSrc + """ - [Fact] + interface IExplicit + { + void F() {} + } + + [CreateNewOnMetadataUpdate] + class C : IExplicit + { + void IExplicit.F() {} + + void M() {} + int P1 { get; set; } + int P2 { get => 1; set {} } + int this[int i] { get => 1; set {} } + event System.Action E { add {} remove {} } + event System.Action EF; + int F1, F2; + + enum E {} + interface I {} + class D {} + } + + """; + var edits = GetTopEdits(src1, src2); + edits.VerifySemantics( + [SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))], + capabilities: EditAndContinueCapabilities.NewTypeDefinition | EditAndContinueCapabilities.AddExplicitInterfaceImplementation); + + edits.VerifySemanticDiagnostics( + [Diagnostic(RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, "void M()", "CreateNewOnMetadataUpdateAttribute")], + capabilities: EditAndContinueCapabilities.NewTypeDefinition); + } + + [Fact] public void Type_Generic_DeleteInsert() { - var srcA1 = @" -class C { void F() {} } -struct S { void F() {} } -interface I { void F() {} } -"; + var srcA1 = """ + + class C { void F() {} } + struct S { void F() {} } + interface I { void F() {} } + + """; var srcB1 = ""; var srcA2 = srcB1; @@ -2503,14 +2601,13 @@ public void Type_TypeParameter_Insert_Reloadable() [Fact] public void Type_Delete() { - var src1 = @" -class C { void F() {} } -struct S { void F() {} } -interface I { void F() {} } -"; - var src2 = ""; + GetTopEdits(""" - GetTopEdits(src1, src2).VerifySemanticDiagnostics( + class C { void F() {} } + struct S { void F() {} } + interface I { void F() {} } + + """, "").VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C")), Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.struct_, "S")), Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.interface_, "I"))); @@ -2529,13 +2626,8 @@ public void Type_Delete_Reloadable() [Fact] public void Type_Partial_DeleteDeclaration() { - var srcA1 = "partial class C { void F() {} void M() { } }"; - var srcB1 = "partial class C { void G() {} }"; - var srcA2 = ""; - var srcB2 = "partial class C { void G() {} void M() { } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { void F() {} void M() { } }", ""), GetTopEdits("partial class C { void G() {} }", "partial class C { void G() {} void M() { } }")], [ DocumentResults( semanticEdits: @@ -2554,10 +2646,7 @@ public void Type_Partial_DeleteDeclaration() [Fact] public void Type_Partial_InsertFirstDeclaration() { - var src1 = ""; - var src2 = "partial class C { void F() {} }"; - - GetTopEdits(src1, src2).VerifySemantics( + GetTopEdits("", "partial class C { void F() {} }").VerifySemantics( [SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"), preserveLocalVariables: false)], capabilities: EditAndContinueCapabilities.NewTypeDefinition); } @@ -2565,13 +2654,8 @@ public void Type_Partial_InsertFirstDeclaration() [Fact] public void Type_Partial_InsertSecondDeclaration() { - var srcA1 = "partial class C { void F() {} }"; - var srcB1 = ""; - var srcA2 = "partial class C { void F() {} }"; - var srcB2 = "partial class C { void G() {} }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { void F() {} }", "partial class C { void F() {} }"), GetTopEdits("", "partial class C { void G() {} }")], [ DocumentResults(), @@ -2588,12 +2672,9 @@ public void Type_Partial_InsertSecondDeclaration() public void Type_Partial_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { void F() {} }"; - var srcB1 = ""; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { void F() {} }"; - var srcB2 = "partial class C { void G() {} }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(srcA1, srcA2), GetTopEdits("", "partial class C { void G() {} }")], [ DocumentResults(), DocumentResults( @@ -2608,11 +2689,13 @@ public void Type_Partial_Reloadable() [Fact] public void Type_DeleteInsert() { - var srcA1 = @" -class C { void F() {} } -struct S { void F() {} } -interface I { void F() {} } -"; + var srcA1 = """ + + class C { void F() {} } + struct S { void F() {} } + interface I { void F() {} } + + """; var srcB1 = ""; var srcA2 = srcB1; @@ -2637,13 +2720,9 @@ interface I { void F() {} } public void Type_DeleteInsert_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; - var srcB1 = ""; - var srcA2 = ReloadableAttributeSrc; - var srcB2 = "[CreateNewOnMetadataUpdate]class C { void F() {} }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(srcA1, srcA2), GetTopEdits("", "[CreateNewOnMetadataUpdate]class C { void F() {} }")], [ DocumentResults(), DocumentResults( @@ -2658,21 +2737,23 @@ public void Type_DeleteInsert_Reloadable() [Fact] public void Type_NonInsertableMembers_DeleteInsert() { - var srcA1 = @" -abstract class C -{ - public abstract void AbstractMethod(); - public virtual void VirtualMethod() {} - public override string ToString() => null; - public void I.G() {} -} + var srcA1 = """ -interface I -{ - void G(); - void F() {} -} -"; + abstract class C + { + public abstract void AbstractMethod(); + public virtual void VirtualMethod() {} + public override string ToString() => null; + public void I.G() {} + } + + interface I + { + void G(); + void F() {} + } + + """; var srcB1 = ""; var srcA2 = srcB1; @@ -2700,41 +2781,39 @@ void F() {} [Fact] public void Type_Attribute_NonInsertableMembers_DeleteInsert() { - var srcA1 = @" -abstract class C -{ - public abstract void AbstractMethod(); - public virtual void VirtualMethod() {} - public override string ToString() => null; - public void I.G() {} -} + EditAndContinueValidation.VerifySemantics( + [GetTopEdits(""" -interface I -{ - void G(); - void F() {} -} -"; - var srcB1 = ""; + abstract class C + { + public abstract void AbstractMethod(); + public virtual void VirtualMethod() {} + public override string ToString() => null; + public void I.G() {} + } - var srcA2 = ""; - var srcB2 = @" -abstract class C -{ - [System.Obsolete]public abstract void AbstractMethod(); - public virtual void VirtualMethod() {} - public override string ToString() => null; - public void I.G() {} -} + interface I + { + void G(); + void F() {} + } -interface I -{ - [System.Obsolete]void G(); - void F() {} -}"; + """, ""), GetTopEdits("", """ - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + abstract class C + { + [System.Obsolete]public abstract void AbstractMethod(); + public virtual void VirtualMethod() {} + public override string ToString() => null; + public void I.G() {} + } + + interface I + { + [System.Obsolete]void G(); + void F() {} + } + """)], [ DocumentResults(), @@ -2755,29 +2834,28 @@ void F() {} [Fact] public void Type_DeleteInsert_DataMembers() { - var srcA1 = @" -class C -{ - public int x = 1; - public int y = 2; - public int P { get; set; } = 3; - public event System.Action E = new System.Action(null); -} -"; - var srcB1 = ""; - - var srcA2 = ""; - var srcB2 = @" -class C -{ - public int x = 1; - public int y = 2; - public int P { get; set; } = 3; - public event System.Action E = new System.Action(null); -} -"; EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(""" + + class C + { + public int x = 1; + public int y = 2; + public int P { get; set; } = 3; + public event System.Action E = new System.Action(null); + } + + """, ""), GetTopEdits("", """ + + class C + { + public int x = 1; + public int y = 2; + public int P { get; set; } = 3; + public event System.Action E = new System.Action(null); + } + + """)], [ DocumentResults(), @@ -2794,31 +2872,32 @@ class C [Fact] public void Type_DeleteInsert_DataMembers_PartialSplit() { - var srcA1 = @" -class C -{ - public int x = 1; - public int y = 2; - public int P { get; set; } = 3; -} -"; - var srcB1 = ""; - - var srcA2 = @" -partial class C -{ - public int x = 1; - public int y = 2; -} -"; - var srcB2 = @" -partial class C -{ - public int P { get; set; } = 3; -} -"; EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(""" + + class C + { + public int x = 1; + public int y = 2; + public int P { get; set; } = 3; + } + + """, """ + + partial class C + { + public int x = 1; + public int y = 2; + } + + """), GetTopEdits("", """ + + partial class C + { + public int P { get; set; } = 3; + } + + """)], [ DocumentResults(), @@ -2835,33 +2914,35 @@ partial class C [Fact] public void Type_DeleteInsert_DataMembers_PartialMerge() { - var srcA1 = @" -partial class C -{ - public int x = 1; - public int y = 2; -} -"; - var srcB1 = @" -partial class C -{ - public int P { get; set; } = 3; -}"; - - var srcA2 = @" -class C -{ - public int x = 1; - public int y = 2; - public int P { get; set; } = 3; -} -"; - - var srcB2 = @" -"; // note that accessors are not updated since they do not have bodies EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(""" + + partial class C + { + public int x = 1; + public int y = 2; + } + + """, """ + + class C + { + public int x = 1; + public int y = 2; + public int P { get; set; } = 3; + } + + """), GetTopEdits(""" + + partial class C + { + public int P { get; set; } = 3; + } + """, """ + + + """)], [ DocumentResults( semanticEdits: @@ -3027,15 +3108,19 @@ public void RecordStruct_NoModifiers_Insert() [Fact] public void RecordStruct_AddField() { - var src1 = @" -record struct C(int X) -{ -}"; - var src2 = @" -record struct C(int X) -{ - private int _y = 0; -}"; + var src1 = """ + + record struct C(int X) + { + } + """; + var src2 = """ + + record struct C(int X) + { + private int _y = 0; + } + """; var edits = GetTopEdits(src1, src2); @@ -3046,15 +3131,19 @@ record struct C(int X) [Fact] public void RecordStruct_AddProperty() { - var src1 = @" -record struct C(int X) -{ -}"; - var src2 = @" -record struct C(int X) -{ - public int Y { get; set; } = 0; -}"; + var src1 = """ + + record struct C(int X) + { + } + """; + var src2 = """ + + record struct C(int X) + { + public int Y { get; set; } = 0; + } + """; var edits = GetTopEdits(src1, src2); @@ -3177,13 +3266,15 @@ public void Record_BaseInterface_Update3() public void Record_Method_Insert_AbstractVirtualOverride() { var src1 = ""; - var src2 = @" -public abstract record C -{ - public abstract void F(); - public virtual void G() {} - public override void H() {} -}"; + var src2 = """ + + public abstract record C + { + public abstract void F(); + public virtual void G() {} + public override void H() {} + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -3219,11 +3310,13 @@ public void Record_Method_Insert_ReplacingSynthesizedWithCustom_ParameterNameCha public void Record_Method_Insert_ReplacingSynthesizedWithCustom_SemanticError() { var src1 = "record C { }"; - var src2 = @"record C -{ - protected virtual bool PrintMembers(System.Text.StringBuilder sb) => false; - protected virtual bool PrintMembers(System.Text.StringBuilder sb) => false; -}"; + var src2 = """ + record C + { + protected virtual bool PrintMembers(System.Text.StringBuilder sb) => false; + protected virtual bool PrintMembers(System.Text.StringBuilder sb) => false; + } + """; var edits = GetTopEdits(src1, src2); @@ -3348,22 +3441,26 @@ public void Record_Field_Insert() [Fact] public void Record_Field_Insert_WithExplicitMembers() { - var src1 = @" -record C(int X) -{ - public C(C other) - { - } -}"; - var src2 = @" -record C(int X) -{ - private int _y; - - public C(C other) - { - } -}"; + var src1 = """ + + record C(int X) + { + public C(C other) + { + } + } + """; + var src2 = """ + + record C(int X) + { + private int _y; + + public C(C other) + { + } + } + """; var edits = GetTopEdits(src1, src2); @@ -3625,18 +3722,22 @@ public void Record_Property_Delete_Static() [Fact] public void Record_Property_Delete_WithInitializer() { - var src1 = @" -record C(int X) -{ - public int Y { get; set; } = 1; + var src1 = """ - public C(bool b) : this(1) { } -}"; - var src2 = @" -record C(int X) -{ - public C(bool b) : this(1) { } -}"; + record C(int X) + { + public int Y { get; set; } = 1; + + public C(bool b) : this(1) { } + } + """; + var src2 = """ + + record C(int X) + { + public C(bool b) : this(1) { } + } + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -3712,14 +3813,9 @@ public void Record_Property_Delete_ReplacingCustomWithSynthesized_ReadOnlyStruct [InlineData(" = X;")] public void Record_Property_Delete_ReplacingCustomWithSynthesized_Auto_Partial(string initializer) { - var srcA1 = "partial record C(int X);"; var srcB1 = "partial record C { public int X { get; init; }" + initializer + " }"; - - var srcA2 = "partial record C(int X);"; - var srcB2 = "partial record C;"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial record C(int X);", "partial record C(int X);"), GetTopEdits(srcB1, "partial record C;")], [ DocumentResults(), DocumentResults( @@ -3809,17 +3905,13 @@ public void Record_Property_Delete_ReplacingCustomWithSynthesized_WithBodyAndMet [InlineData("get { return 4; } init { }")] public void Record_Property_Delete_ReplacingCustomWithSynthesized_WithBody_Partial(string body) { - var srcA1 = "partial record C(int X);"; var srcB1 = "partial record C { public int X { " + body + " } }"; - var srcA2 = "partial record C(int X);"; - var srcB2 = "partial record C;"; - // The property changes from custom property to field-backed auto-prop. // Methods using backing field must be updated, unless they are explicitly declared. EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial record C(int X);", "partial record C(int X);"), GetTopEdits(srcB1, "partial record C;")], [ DocumentResults(), DocumentResults( @@ -3959,18 +4051,22 @@ public void Record_Property_Insert_Static() [Fact] public void Record_Property_Insert_WithInitializer() { - var src1 = @" -record C(int X) -{ - public C(bool b) : this(1) { } -}"; - var src2 = @" -record C(int X) -{ - public int Y { get; set; } = 1; + var src1 = """ + + record C(int X) + { + public C(bool b) : this(1) { } + } + """; + var src2 = """ - public C(bool b) : this(1) { } -}"; + record C(int X) + { + public int Y { get; set; } = 1; + + public C(bool b) : this(1) { } + } + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -4065,56 +4161,60 @@ public void Record_Property_Insert_ReplacingSynthesizedWithCustom_TypeLayoutChan [Fact] public void Record_Property_Insert_NotPrimary_WithExplicitMembers() { - var src1 = @" -record C(int X) -{ - protected virtual bool PrintMembers(System.Text.StringBuilder builder) - { - return false; - } + var src1 = """ - public override int GetHashCode() - { - return 0; - } + record C(int X) + { + protected virtual bool PrintMembers(System.Text.StringBuilder builder) + { + return false; + } - public virtual bool Equals(C other) - { - return false; - } + public override int GetHashCode() + { + return 0; + } - public C(C original) - { - } -}"; - var src2 = @" -record C(int X) -{ - public int Y { get; set; } + public virtual bool Equals(C other) + { + return false; + } - protected virtual bool PrintMembers(System.Text.StringBuilder builder) - { - return false; - } + public C(C original) + { + } + } + """; + var src2 = """ - public override int GetHashCode() - { - return 0; - } + record C(int X) + { + public int Y { get; set; } - public virtual bool Equals(C other) - { - return false; - } + protected virtual bool PrintMembers(System.Text.StringBuilder builder) + { + return false; + } - public C(C original) - { - } -}"; + public override int GetHashCode() + { + return 0; + } - var edits = GetTopEdits(src1, src2); + public virtual bool Equals(C other) + { + return false; + } - edits.VerifySemantics( + public C(C original) + { + } + } + """; + + var edits = GetTopEdits(src1, src2); + + edits.VerifySemantics( [ SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), ], @@ -4150,14 +4250,10 @@ public void Record_Property_Insert_ReplacingSynthesizedWithCustom_Auto(string in [InlineData(" = X;")] public void Record_Property_Insert_ReplacingSynthesizedWithCustom_Auto_Partial(string initializer) { - var srcA1 = "partial record C(int X);"; - var srcB1 = "partial record C;"; - - var srcA2 = "partial record C(int X);"; var srcB2 = "partial record C { public int X { get; init; }" + initializer + " }"; EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial record C(int X);", "partial record C(int X);"), GetTopEdits("partial record C;", srcB2)], [ DocumentResults(), DocumentResults( @@ -4201,14 +4297,10 @@ public void Record_Property_Insert_ReplacingSynthesizedWithCustom_WithBody(strin [InlineData("get { return 4; } init { }")] public void Record_Property_Insert_ReplacingSynthesizedWithCustom_WithBody_Partial(string body) { - var srcA1 = "partial record C(int X);"; - var srcB1 = "partial record C;"; - - var srcA2 = "partial record C(int X);"; var srcB2 = "partial record C { public int X { " + body + " } }"; EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial record C(int X);", "partial record C(int X);"), GetTopEdits("partial record C;", srcB2)], [ DocumentResults(), DocumentResults( @@ -4281,14 +4373,8 @@ public void Record_Property_Insert_ReplacingSynthesizedWithCustom_WithAttributeO [Fact] public void Record_Property_DeleteInsert() { - var srcA1 = "partial record C(int X) { public int Y { get; init; } }"; - var srcB1 = "partial record C;"; - - var srcA2 = "partial record C(int X);"; - var srcB2 = "partial record C { public int Y { get; init; } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial record C(int X) { public int Y { get; init; } }", "partial record C(int X);"), GetTopEdits("partial record C;", "partial record C { public int Y { get; init; } }")], [ DocumentResults(), DocumentResults( @@ -4415,13 +4501,8 @@ public void Enum_Member_Attribute_Update() [Fact] public void Enum_Member_Attribute_InsertDeleteAndUpdate() { - var srcA1 = ""; - var srcB1 = "enum N { A = 1 }"; - var srcA2 = "enum N { [System.Obsolete]A = 1 }"; - var srcB2 = ""; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("", "enum N { [System.Obsolete]A = 1 }"), GetTopEdits("enum N { A = 1 }", "")], [ DocumentResults(semanticEdits: [ @@ -5654,18 +5735,22 @@ public void NestedType_Insert_Member_Reloadable() [Fact] public void NestedType_InsertMemberWithInitializer1() { - var src1 = @" -class C -{ -}"; - var src2 = @" -class C -{ - private class D - { - public int P = 1; - } -}"; + var src1 = """ + + class C + { + } + """; + var src2 = """ + + class C + { + private class D + { + public int P = 1; + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, @@ -5677,36 +5762,40 @@ private class D [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] public void NestedType_Insert_PInvoke() { - var src1 = @" -using System; -using System.Runtime.InteropServices; + var src1 = """ -class C -{ -}"; - var src2 = @" -using System; -using System.Runtime.InteropServices; + using System; + using System.Runtime.InteropServices; -class C -{ - abstract class D - { - public extern D(); + class C + { + } + """; + var src2 = """ - public static extern int P { [DllImport(""msvcrt.dll"")]get; [DllImport(""msvcrt.dll"")]set; } + using System; + using System.Runtime.InteropServices; + + class C + { + abstract class D + { + public extern D(); - [DllImport(""msvcrt.dll"")] - public static extern int puts(string c); + public static extern int P { [DllImport("msvcrt.dll")]get; [DllImport("msvcrt.dll")]set; } - [DllImport(""msvcrt.dll"")] - public static extern int operator +(D d, D g); + [DllImport("msvcrt.dll")] + public static extern int puts(string c); - [DllImport(""msvcrt.dll"")] - public static extern explicit operator int (D d); - } -} -"; + [DllImport("msvcrt.dll")] + public static extern int operator +(D d, D g); + + [DllImport("msvcrt.dll")] + public static extern explicit operator int (D d); + } + } + + """; var edits = GetTopEdits(src1, src2); // Adding P/Invoke is not supported by the CLR. @@ -5721,32 +5810,36 @@ abstract class D [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] public void NestedType_Insert_VirtualAbstract() { - var src1 = @" -using System; -using System.Runtime.InteropServices; + var src1 = """ -class C -{ -}"; - var src2 = @" -using System; -using System.Runtime.InteropServices; + using System; + using System.Runtime.InteropServices; -class C -{ - abstract class D - { - public abstract int P { get; } - public abstract int this[int i] { get; } - public abstract int puts(string c); + class C + { + } + """; + var src2 = """ - public virtual event Action E { add { } remove { } } - public virtual int Q { get { return 1; } } - public virtual int this[string i] { get { return 1; } } - public virtual int M(string c) { return 1; } - } -} -"; + using System; + using System.Runtime.InteropServices; + + class C + { + abstract class D + { + public abstract int P { get; } + public abstract int this[int i] { get; } + public abstract int puts(string c); + + public virtual event Action E { add { } remove { } } + public virtual int Q { get { return 1; } } + public virtual int this[string i] { get { return 1; } } + public virtual int M(string c) { return 1; } + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); @@ -5812,28 +5905,32 @@ public void NestedType_ClassDeleteInsert() [Fact] public void NestedClassGeneric_Insert() { - var src1 = @" -using System; -class C -{ -} -"; - var src2 = @" -using System; -class C -{ - class D {} - struct S {} - enum N {} - interface I {} - delegate void D(); -} + var src1 = """ -class D -{ - -} -"; + using System; + class C + { + } + + """; + var src2 = """ + + using System; + class C + { + class D {} + struct S {} + enum N {} + interface I {} + delegate void D(); + } + + class D + { + + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( capabilities: EditAndContinueCapabilities.NewTypeDefinition); @@ -5857,13 +5954,8 @@ public void NestedEnum_InsertMember() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDelete() { - var srcA1 = "partial struct S { }"; - var srcB1 = "partial struct S { enum N { A = 1 } }"; - var srcA2 = "partial struct S { enum N { A = 1 } }"; - var srcB2 = "partial struct S { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial struct S { }", "partial struct S { enum N { A = 1 } }"), GetTopEdits("partial struct S { enum N { A = 1 } }", "partial struct S { }")], [ DocumentResults(), DocumentResults() @@ -5873,13 +5965,8 @@ public void NestedEnumInPartialType_InsertDelete() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndUpdateMember() { - var srcA1 = "partial struct S { }"; - var srcB1 = "partial struct S { enum N { A = 1 } }"; - var srcA2 = "partial struct S { enum N { A = 2 } }"; - var srcB2 = "partial struct S { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial struct S { }", "partial struct S { enum N { A = 2 } }"), GetTopEdits("partial struct S { enum N { A = 1 } }", "partial struct S { }")], [ DocumentResults( diagnostics: @@ -5894,13 +5981,8 @@ public void NestedEnumInPartialType_InsertDeleteAndUpdateMember() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndUpdateBase() { - var srcA1 = "partial struct S { }"; - var srcB1 = "partial struct S { enum N : uint { A = 1 } }"; - var srcA2 = "partial struct S { enum N : int { A = 1 } }"; - var srcB2 = "partial struct S { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial struct S { }", "partial struct S { enum N : int { A = 1 } }"), GetTopEdits("partial struct S { enum N : uint { A = 1 } }", "partial struct S { }")], [ DocumentResults( diagnostics: @@ -5915,13 +5997,8 @@ public void NestedEnumInPartialType_InsertDeleteAndUpdateBase() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndInsertMember() { - var srcA1 = "partial struct S { }"; - var srcB1 = "partial struct S { enum N { A = 1 } }"; - var srcA2 = "partial struct S { enum N { A = 1, B = 2 } }"; - var srcB2 = "partial struct S { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial struct S { }", "partial struct S { enum N { A = 1, B = 2 } }"), GetTopEdits("partial struct S { enum N { A = 1 } }", "partial struct S { }")], [ DocumentResults( diagnostics: [Diagnostic(RudeEditKind.Insert, "B = 2", FeaturesResources.enum_value)]), @@ -5933,13 +6010,8 @@ public void NestedEnumInPartialType_InsertDeleteAndInsertMember() [Fact] public void NestedDelegateInPartialType_InsertDelete() { - var srcA1 = "partial struct S { }"; - var srcB1 = "partial struct S { delegate void D(); }"; - var srcA2 = "partial struct S { delegate void D(); }"; - var srcB2 = "partial struct S { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial struct S { }", "partial struct S { delegate void D(); }"), GetTopEdits("partial struct S { delegate void D(); }", "partial struct S { }")], [ DocumentResults( // delegate does not have any user-defined method body and this does not need a PDB update @@ -5952,13 +6024,8 @@ public void NestedDelegateInPartialType_InsertDelete() [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeParameters() { - var srcA1 = "partial struct S { }"; - var srcB1 = "partial struct S { delegate void D(); }"; - var srcA2 = "partial struct S { delegate void D(int x); }"; - var srcB2 = "partial struct S { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial struct S { }", "partial struct S { delegate void D(int x); }"), GetTopEdits("partial struct S { delegate void D(); }", "partial struct S { }")], [ DocumentResults( diagnostics: [Diagnostic(RudeEditKind.TypeUpdate, "delegate void D(int x)", GetResource("delegate"))]), @@ -5970,13 +6037,8 @@ public void NestedDelegateInPartialType_InsertDeleteAndChangeParameters() [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeReturnType() { - var srcA1 = "partial struct S { }"; - var srcB1 = "partial struct S { delegate ref int D(); }"; - var srcA2 = "partial struct S { delegate ref readonly int D(); }"; - var srcB2 = "partial struct S { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial struct S { }", "partial struct S { delegate ref readonly int D(); }"), GetTopEdits("partial struct S { delegate ref int D(); }", "partial struct S { }")], [ DocumentResults( diagnostics: @@ -5991,13 +6053,8 @@ public void NestedDelegateInPartialType_InsertDeleteAndChangeReturnType() [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeOptionalParameterValue() { - var srcA1 = "partial struct S { }"; - var srcB1 = "partial struct S { delegate void D(int x = 1); }"; - var srcA2 = "partial struct S { delegate void D(int x = 2); }"; - var srcB2 = "partial struct S { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial struct S { }", "partial struct S { delegate void D(int x = 2); }"), GetTopEdits("partial struct S { delegate void D(int x = 1); }", "partial struct S { }")], [ DocumentResults( diagnostics: @@ -6012,16 +6069,8 @@ public void NestedDelegateInPartialType_InsertDeleteAndChangeOptionalParameterVa [Fact] public void NestedPartialTypeInPartialType_InsertDeleteAndChange() { - var srcA1 = "partial struct S { partial class C { void F1() {} } }"; - var srcB1 = "partial struct S { partial class C { void F2(byte x) {} } }"; - var srcC1 = "partial struct S { }"; - - var srcA2 = "partial struct S { partial class C { void F1() {} } }"; - var srcB2 = "partial struct S { }"; - var srcC2 = "partial struct S { partial class C { void F2(int x) {} } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2)], + [GetTopEdits("partial struct S { partial class C { void F1() {} } }", "partial struct S { partial class C { void F1() {} } }"), GetTopEdits("partial struct S { partial class C { void F2(byte x) {} } }", "partial struct S { }"), GetTopEdits("partial struct S { }", "partial struct S { partial class C { void F2(int x) {} } }")], [ DocumentResults(), @@ -6040,14 +6089,8 @@ public void NestedPartialTypeInPartialType_InsertDeleteAndChange() [Fact] public void Type_Insert_Partial_Multiple() { - var srcA1 = ""; - var srcB1 = ""; - - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("", "partial class C { }"), GetTopEdits("", "partial class C { }")], [ DocumentResults(semanticEdits: [ @@ -6064,14 +6107,8 @@ public void Type_Insert_Partial_Multiple() [Fact] public void Type_Delete_Partial_Multiple() { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { }"; - - var srcA2 = ""; - var srcB2 = ""; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", ""), GetTopEdits("partial class C { }", "")], [ DocumentResults(diagnostics: [Diagnostic(RudeEditKind.Delete, null, GetResource("class", "C"))]), DocumentResults(diagnostics: [Diagnostic(RudeEditKind.Delete, null, GetResource("class", "C"))]), @@ -6082,16 +6119,8 @@ public void Type_Delete_Partial_Multiple() [Fact] public void Type_Partial_InsertDeleteAndChange_Attribute() { - var srcA1 = "partial class C { }"; - var srcB1 = ""; - var srcC1 = "partial class C { }"; - - var srcA2 = ""; - var srcB2 = "[A]partial class C { }"; - var srcC2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2)], + [GetTopEdits("partial class C { }", ""), GetTopEdits("", "[A]partial class C { }"), GetTopEdits("partial class C { }", "partial class C { }")], [ DocumentResults(), DocumentResults(semanticEdits: @@ -6148,16 +6177,8 @@ public void Type_Partial_InsertDeleteAndChange_TypeParameterAttribute() [Fact] public void Type_Partial_InsertDeleteAndChange_Constraint() { - var srcA1 = "partial class C { }"; - var srcB1 = ""; - var srcC1 = "partial class C { }"; - - var srcA2 = ""; - var srcB2 = "partial class C where T : new() { }"; - var srcC2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2)], + [GetTopEdits("partial class C { }", ""), GetTopEdits("", "partial class C where T : new() { }"), GetTopEdits("partial class C { }", "partial class C { }")], [ DocumentResults(), @@ -6174,20 +6195,10 @@ public void Type_Partial_InsertDeleteAndChange_Constraint() [Fact] public void Type_Partial_InsertDeleteRefactor() { - var srcA1 = "partial class C : I { void F() { } }"; - var srcB1 = "[A][B]partial class C : J { void G() { } }"; - var srcC1 = ""; - var srcD1 = ""; - - var srcA2 = ""; - var srcB2 = ""; - var srcC2 = "[A]partial class C : I, J { void F() { } }"; - var srcD2 = "[B]partial class C { void G() { } }"; - var srcE = "interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2), GetTopEdits(srcE, srcE)], + [GetTopEdits("partial class C : I { void F() { } }", ""), GetTopEdits("[A][B]partial class C : J { void G() { } }", ""), GetTopEdits("", "[A]partial class C : I, J { void F() { } }"), GetTopEdits("", "[B]partial class C { void G() { } }"), GetTopEdits(srcE, srcE)], [ DocumentResults(), DocumentResults(), @@ -6205,19 +6216,17 @@ public void Type_Partial_InsertDeleteRefactor() [Fact] public void Type_Partial_Attribute_AddMultiple() { - var attributes = @" -class A : System.Attribute {} -class B : System.Attribute {} -"; + var attributes = """ - var srcA1 = "partial class C { }" + attributes; - var srcB1 = "partial class C { }"; + class A : System.Attribute {} + class B : System.Attribute {} - var srcA2 = "[A]partial class C { }" + attributes; - var srcB2 = "[B]partial class C { }"; + """; + var srcA1 = "partial class C { }" + attributes; + var srcA2 = "[A]partial class C { }" + attributes; EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(srcA1, srcA2), GetTopEdits("partial class C { }", "[B]partial class C { }")], [ DocumentResults(semanticEdits: [ @@ -6234,18 +6243,8 @@ class B : System.Attribute {} [Fact] public void Type_Partial_InsertDeleteRefactor_AttributeListSplitting() { - var srcA1 = "partial class C { void F() { } }"; - var srcB1 = "[A,B]partial class C { void G() { } }"; - var srcC1 = ""; - var srcD1 = ""; - - var srcA2 = ""; - var srcB2 = ""; - var srcC2 = "[A]partial class C { void F() { } }"; - var srcD2 = "[B]partial class C { void G() { } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2)], + [GetTopEdits("partial class C { void F() { } }", ""), GetTopEdits("[A,B]partial class C { void G() { } }", ""), GetTopEdits("", "[A]partial class C { void F() { } }"), GetTopEdits("", "[B]partial class C { void G() { } }")], [ DocumentResults(), DocumentResults(), @@ -6263,16 +6262,8 @@ public void Type_Partial_InsertDeleteRefactor_AttributeListSplitting() [Fact] public void Type_Partial_InsertDeleteChangeMember() { - var srcA1 = "partial class C { void F(int y = 1) { } }"; - var srcB1 = "partial class C { void G(int x = 1) { } }"; - var srcC1 = ""; - - var srcA2 = ""; - var srcB2 = "partial class C { void G(int x = 2) { } }"; - var srcC2 = "partial class C { void F(int y = 2) { } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2)], + [GetTopEdits("partial class C { void F(int y = 1) { } }", ""), GetTopEdits("partial class C { void G(int x = 1) { } }", "partial class C { void G(int x = 2) { } }"), GetTopEdits("", "partial class C { void F(int y = 2) { } }")], [ DocumentResults(), DocumentResults(diagnostics: [Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter)]), @@ -6283,22 +6274,8 @@ public void Type_Partial_InsertDeleteChangeMember() [Fact] public void NestedPartialTypeInPartialType_InsertDeleteAndInsertVirtual() { - var srcA1 = "partial interface I { partial class C { virtual void F1() {} } }"; - var srcB1 = "partial interface I { partial class C { virtual void F2() {} } }"; - var srcC1 = "partial interface I { partial class C { } }"; - var srcD1 = "partial interface I { partial class C { } }"; - var srcE1 = "partial interface I { }"; - var srcF1 = "partial interface I { }"; - - var srcA2 = "partial interface I { partial class C { } }"; - var srcB2 = ""; - var srcC2 = "partial interface I { partial class C { virtual void F1() {} } }"; // move existing virtual into existing partial decl - var srcD2 = "partial interface I { partial class C { virtual void N1() {} } }"; // insert new virtual into existing partial decl - var srcE2 = "partial interface I { partial class C { virtual void F2() {} } }"; // move existing virtual into a new partial decl - var srcF2 = "partial interface I { partial class C { virtual void N2() {} } }"; // insert new virtual into new partial decl - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2), GetTopEdits(srcE1, srcE2), GetTopEdits(srcF1, srcF2)], + [GetTopEdits("partial interface I { partial class C { virtual void F1() {} } }", "partial interface I { partial class C { } }"), GetTopEdits("partial interface I { partial class C { virtual void F2() {} } }", ""), GetTopEdits("partial interface I { partial class C { } }", "partial interface I { partial class C { virtual void F1() {} } }"), GetTopEdits("partial interface I { partial class C { } }", "partial interface I { partial class C { virtual void N1() {} } }"), GetTopEdits("partial interface I { }", "partial interface I { partial class C { virtual void F2() {} } }"), GetTopEdits("partial interface I { }", "partial interface I { partial class C { virtual void N2() {} } }")], [ // A DocumentResults(), @@ -6740,13 +6717,8 @@ public void Namespace_Update_FileScoped() [Fact] public void Namespace_Update_MultiplePartials1() { - var srcA1 = @"namespace N { partial class/*1*/C {} } namespace N { partial class/*2*/C {} }"; - var srcB1 = @"namespace N { partial class/*3*/C {} } namespace N { partial class/*4*/C {} }"; - var srcA2 = @"namespace N { partial class/*1*/C {} } namespace M { partial class/*2*/C {} }"; - var srcB2 = @"namespace M { partial class/*3*/C {} } namespace N { partial class/*4*/C {} }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(@"namespace N { partial class/*1*/C {} } namespace N { partial class/*2*/C {} }", @"namespace N { partial class/*1*/C {} } namespace M { partial class/*2*/C {} }"), GetTopEdits(@"namespace N { partial class/*3*/C {} } namespace N { partial class/*4*/C {} }", @"namespace M { partial class/*3*/C {} } namespace N { partial class/*4*/C {} }")], [ DocumentResults( semanticEdits: @@ -6765,13 +6737,8 @@ public void Namespace_Update_MultiplePartials1() [Fact] public void Namespace_Update_MultiplePartials2() { - var srcA1 = @"namespace N { partial class/*1*/C {} } namespace N { partial class/*2*/C {} }"; - var srcB1 = @"namespace N { partial class/*3*/C {} } namespace N { partial class/*4*/C {} }"; - var srcA2 = @"namespace M { partial class/*1*/C {} } namespace M { partial class/*2*/C {} }"; - var srcB2 = @"namespace M { partial class/*3*/C {} } namespace M { partial class/*4*/C {} }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(@"namespace N { partial class/*1*/C {} } namespace N { partial class/*2*/C {} }", @"namespace M { partial class/*1*/C {} } namespace M { partial class/*2*/C {} }"), GetTopEdits(@"namespace N { partial class/*3*/C {} } namespace N { partial class/*4*/C {} }", @"namespace M { partial class/*3*/C {} } namespace M { partial class/*4*/C {} }")], [ DocumentResults(diagnostics: [ @@ -6873,45 +6840,49 @@ public void Namespace_Move2() [Fact] public void PartialMember_DeleteInsert_SingleDocument() { - var src1 = @" -using System; + var src1 = """ -partial class C -{ - void M() {} - int P1 { get; set; } - int P2 { get => 1; set {} } - int this[int i] { get => 1; set {} } - int this[byte i] { get => 1; set {} } - event Action E { add {} remove {} } - event Action EF; - int F1; - int F2; -} + using System; -partial class C -{ -} -"; - var src2 = @" -using System; + partial class C + { + void M() {} + int P1 { get; set; } + int P2 { get => 1; set {} } + int this[int i] { get => 1; set {} } + int this[byte i] { get => 1; set {} } + event Action E { add {} remove {} } + event Action EF; + int F1; + int F2; + } -partial class C -{ -} + partial class C + { + } -partial class C -{ - void M() {} - int P1 { get; set; } - int P2 { get => 1; set {} } - int this[int i] { get => 1; set {} } - int this[byte i] { get => 1; set {} } - event Action E { add {} remove {} } - event Action EF; - int F1, F2; -} -"; + """; + var src2 = """ + + using System; + + partial class C + { + } + + partial class C + { + void M() {} + int P1 { get; set; } + int P2 { get => 1; set {} } + int this[int i] { get => 1; set {} } + int this[byte i] { get => 1; set {} } + event Action E { add {} remove {} } + event Action EF; + int F1, F2; + } + + """; var edits = GetTopEdits(src1, src2); @@ -7011,13 +6982,8 @@ event Action E { add {} remove {} } [Fact] public void PartialMember_InsertDelete_MultipleDocuments() { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { void F() {} }"; - var srcA2 = "partial class C { void F() {} }"; - var srcB2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", "partial class C { void F() {} }"), GetTopEdits("partial class C { void F() {} }", "partial class C { }")], [ DocumentResults( semanticEdits: @@ -7032,13 +6998,8 @@ public void PartialMember_InsertDelete_MultipleDocuments() [Fact] public void PartialMember_DeleteInsert_MultipleDocuments() { - var srcA1 = "partial class C { void F() {} }"; - var srcB1 = "partial class C { }"; - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { void F() {} }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { void F() {} }", "partial class C { }"), GetTopEdits("partial class C { }", "partial class C { void F() {} }")], [ DocumentResults(), @@ -7115,13 +7076,8 @@ public void PartialMember_DeleteInsert_GenericType() [Fact] public void PartialMember_DeleteInsert_Destructor() { - var srcA1 = "partial class C { ~C() {} }"; - var srcB1 = "partial class C { }"; - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { ~C() {} }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { ~C() {} }", "partial class C { }"), GetTopEdits("partial class C { }", "partial class C { ~C() {} }")], [ DocumentResults(), @@ -7136,14 +7092,8 @@ public void PartialMember_DeleteInsert_Destructor() [Fact] public void PartialNestedType_InsertDeleteAndChange() { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { class D { void M() {} } interface I { } }"; - - var srcA2 = "partial class C { class D : I { void M() {} } interface I { } }"; - var srcB2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", "partial class C { class D : I { void M() {} } interface I { } }"), GetTopEdits("partial class C { class D { void M() {} } interface I { } }", "partial class C { }")], [ DocumentResults( diagnostics: @@ -7158,13 +7108,8 @@ public void PartialNestedType_InsertDeleteAndChange() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51011")] public void PartialMember_RenameInsertDelete() { - var srcA1 = "partial class C { void F1() {} }"; - var srcB1 = "partial class C { void F2() {} }"; - var srcA2 = "partial class C { void F2() {} }"; - var srcB2 = "partial class C { void F1() {} }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { void F1() {} }", "partial class C { void F2() {} }"), GetTopEdits("partial class C { void F2() {} }", "partial class C { void F1() {} }")], [ DocumentResults(semanticEdits: [ @@ -7217,13 +7162,8 @@ partial class C { void F3(int c) {} } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51011")] public void PartialMember_SignatureChangeInsertDelete() { - var srcA1 = "partial class C { void F(byte x) {} }"; - var srcB1 = "partial class C { void F(char x) {} }"; - var srcA2 = "partial class C { void F(char x) {} }"; - var srcB2 = "partial class C { void F(byte x) {} }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { void F(byte x) {} }", "partial class C { void F(char x) {} }"), GetTopEdits("partial class C { void F(char x) {} }", "partial class C { void F(byte x) {} }")], [ DocumentResults( semanticEdits: [SemanticEdit(SemanticEditKind.Update, c => c.GetMembers("C.F").Single(m => m.Parameters is [{ Type.SpecialType: SpecialType.System_Char }]))]), @@ -7236,13 +7176,8 @@ public void PartialMember_SignatureChangeInsertDelete() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51011")] public void PartialMember_SignatureChangeInsertDelete_Indexer() { - var srcA1 = "partial class C { int this[byte x] { get => 1; set {} } }"; - var srcB1 = "partial class C { int this[char x] { get => 1; set {} } }"; - var srcA2 = "partial class C { int this[char x] { get => 1; set {} } }"; - var srcB2 = "partial class C { int this[byte y] { get => 1; set {} } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { int this[byte x] { get => 1; set {} } }", "partial class C { int this[char x] { get => 1; set {} } }"), GetTopEdits("partial class C { int this[char x] { get => 1; set {} } }", "partial class C { int this[byte y] { get => 1; set {} } }")], [ DocumentResults(semanticEdits: [ @@ -7264,40 +7199,42 @@ public void PartialMember_SignatureChangeInsertDelete_Indexer() [Fact] public void PartialMember_DeleteInsert_UpdateMethodBodyError() { - var srcA1 = @" -using System.Collections.Generic; + EditAndContinueValidation.VerifySemantics( + [GetTopEdits(""" -partial class C -{ - IEnumerable F() { yield return 1; } -} -"; - var srcB1 = @" -using System.Collections.Generic; + using System.Collections.Generic; -partial class C -{ -} -"; + partial class C + { + IEnumerable F() { yield return 1; } + } - var srcA2 = @" -using System.Collections.Generic; + """, """ -partial class C -{ -} -"; - var srcB2 = @" -using System.Collections.Generic; + using System.Collections.Generic; -partial class C -{ - IEnumerable F() { yield return 1; yield return 2; } -} -"; + partial class C + { + } - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + """), GetTopEdits(""" + + using System.Collections.Generic; + + partial class C + { + } + + """, """ + + using System.Collections.Generic; + + partial class C + { + IEnumerable F() { yield return 1; yield return 2; } + } + + """)], [ DocumentResults(), DocumentResults(semanticEdits: @@ -7311,14 +7248,8 @@ partial class C [Fact] public void PartialMember_DeleteInsert_UpdatePropertyAccessors() { - var srcA1 = "partial class C { int P { get => 1; set { Console.WriteLine(1); } } }"; - var srcB1 = "partial class C { }"; - - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { int P { get => 2; set { Console.WriteLine(2); } } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { int P { get => 1; set { Console.WriteLine(1); } } }", "partial class C { }"), GetTopEdits("partial class C { }", "partial class C { int P { get => 2; set { Console.WriteLine(2); } } }")], [ DocumentResults(), DocumentResults(semanticEdits: @@ -7332,14 +7263,8 @@ public void PartialMember_DeleteInsert_UpdatePropertyAccessors() [Fact] public void PartialMember_DeleteInsert_UpdateAutoProperty() { - var srcA1 = "partial class C { int P => 1; }"; - var srcB1 = "partial class C { }"; - - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { int P => 2; }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { int P => 1; }", "partial class C { }"), GetTopEdits("partial class C { }", "partial class C { int P => 2; }")], [ DocumentResults(), DocumentResults(semanticEdits: @@ -7352,14 +7277,8 @@ public void PartialMember_DeleteInsert_UpdateAutoProperty() [Fact] public void PartialMember_DeleteInsert_AddFieldInitializer() { - var srcA1 = "partial class C { int f; }"; - var srcB1 = "partial class C { }"; - - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { int f = 1; }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { int f; }", "partial class C { }"), GetTopEdits("partial class C { }", "partial class C { int f = 1; }")], [ DocumentResults(), DocumentResults(semanticEdits: @@ -7372,14 +7291,8 @@ public void PartialMember_DeleteInsert_AddFieldInitializer() [Fact] public void PartialMember_DeleteInsert_RemoveFieldInitializer() { - var srcA1 = "partial class C { int f = 1; }"; - var srcB1 = "partial class C { }"; - - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { int f; }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { int f = 1; }", "partial class C { }"), GetTopEdits("partial class C { }", "partial class C { int f; }")], [ DocumentResults(), DocumentResults(semanticEdits: @@ -7392,14 +7305,8 @@ public void PartialMember_DeleteInsert_RemoveFieldInitializer() [Fact] public void PartialMember_DeleteInsert_ConstructorWithInitializers() { - var srcA1 = "partial class C { int f = 1; C(int x) { f = x; } }"; - var srcB1 = "partial class C { }"; - - var srcA2 = "partial class C { int f = 1; }"; - var srcB2 = "partial class C { C(int x) { f = x + 1; } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { int f = 1; C(int x) { f = x; } }", "partial class C { int f = 1; }"), GetTopEdits("partial class C { }", "partial class C { C(int x) { f = x + 1; } }")], [ DocumentResults(), DocumentResults(semanticEdits: @@ -7412,13 +7319,8 @@ public void PartialMember_DeleteInsert_ConstructorWithInitializers() [Fact] public void PartialMember_DeleteInsert_MethodAddParameter() { - var srcA1 = "partial struct S { }"; - var srcB1 = "partial struct S { void F() {} }"; - var srcA2 = "partial struct S { void F(int x) {} }"; - var srcB2 = "partial struct S { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial struct S { }", "partial struct S { void F(int x) {} }"), GetTopEdits("partial struct S { void F() {} }", "partial struct S { }")], [ DocumentResults( semanticEdits: @@ -7438,13 +7340,8 @@ public void PartialMember_DeleteInsert_MethodAddParameter() [Fact] public void PartialMember_DeleteInsert_UpdateMethodParameterType() { - var srcA1 = "partial struct S { }"; - var srcB1 = "partial struct S { void F(int x); }"; - var srcA2 = "partial struct S { void F(byte x); }"; - var srcB2 = "partial struct S { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial struct S { }", "partial struct S { void F(byte x); }"), GetTopEdits("partial struct S { void F(int x); }", "partial struct S { }")], [ DocumentResults( semanticEdits: @@ -7464,13 +7361,8 @@ public void PartialMember_DeleteInsert_UpdateMethodParameterType() [Fact] public void PartialMember_DeleteInsert_MethodAddTypeParameter() { - var srcA1 = "partial struct S { }"; - var srcB1 = "partial struct S { void F(); }"; - var srcA2 = "partial struct S { void F(); }"; - var srcB2 = "partial struct S { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial struct S { }", "partial struct S { void F(); }"), GetTopEdits("partial struct S { void F(); }", "partial struct S { }")], [ DocumentResults( semanticEdits: @@ -7553,16 +7445,20 @@ public void Method_NewModifier_Remove() [Fact] public void Method_ReadOnlyModifier_Add_InMutableStruct() { - var src1 = @" -struct S -{ - public int M() => 1; -}"; - var src2 = @" -struct S -{ - public readonly int M() => 1; -}"; + var src1 = """ + + struct S + { + public int M() => 1; + } + """; + var src2 = """ + + struct S + { + public readonly int M() => 1; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("S.M"))); @@ -7571,18 +7467,22 @@ struct S [Fact] public void Method_ReadOnlyModifier_Add_InReadOnlyStruct1() { - var src1 = @" -readonly struct S -{ - public int M() - => 1; -}"; - var src2 = @" -readonly struct S -{ - public readonly int M() - => 1; -}"; + var src1 = """ + + readonly struct S + { + public int M() + => 1; + } + """; + var src2 = """ + + readonly struct S + { + public readonly int M() + => 1; + } + """; var edits = GetTopEdits(src1, src2); @@ -7594,16 +7494,20 @@ public readonly int M() [Fact] public void Method_ReadOnlyModifier_Add_InReadOnlyStruct2() { - var src1 = @" -readonly struct S -{ - public int M() => 1; -}"; - var src2 = @" -struct S -{ - public readonly int M() => 1; -}"; + var src1 = """ + + readonly struct S + { + public int M() => 1; + } + """; + var src2 = """ + + struct S + { + public readonly int M() => 1; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "struct S", "struct")); @@ -7612,22 +7516,26 @@ struct S [Fact] public void Method_AsyncModifier_Remove() { - var src1 = @" -class Test -{ - public async Task WaitAsync() - { - return 1; - } -}"; - var src2 = @" -class Test -{ - public Task WaitAsync() - { - return Task.FromResult(1); - } -}"; + var src1 = """ + + class Test + { + public async Task WaitAsync() + { + return 1; + } + } + """; + var src2 = """ + + class Test + { + public Task WaitAsync() + { + return Task.FromResult(1); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "public Task WaitAsync()", FeaturesResources.method)); @@ -7636,23 +7544,27 @@ public Task WaitAsync() [Fact] public void Method_AsyncModifier_Add() { - var src1 = @" -class Test -{ - public Task WaitAsync() - { - return 1; - } -}"; - var src2 = @" -class Test -{ - public async Task WaitAsync() - { - await Task.Delay(1000); - return 1; - } -}"; + var src1 = """ + + class Test + { + public Task WaitAsync() + { + return 1; + } + } + """; + var src2 = """ + + class Test + { + public async Task WaitAsync() + { + await Task.Delay(1000); + return 1; + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( capabilities: EditAndContinueCapabilities.NewTypeDefinition | EditAndContinueCapabilities.AddExplicitInterfaceImplementation); @@ -7663,23 +7575,27 @@ public async Task WaitAsync() [Fact] public void Method_AsyncModifier_Add_NotSupported() { - var src1 = @" -class Test -{ - public Task WaitAsync() - { - return 1; - } -}"; - var src2 = @" -class Test -{ - public async Task WaitAsync() - { - await Task.Delay(1000); - return 1; - } -}"; + var src1 = """ + + class Test + { + public Task WaitAsync() + { + return 1; + } + } + """; + var src2 = """ + + class Test + { + public async Task WaitAsync() + { + await Task.Delay(1000); + return 1; + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( [Diagnostic(RudeEditKind.MakeMethodAsyncNotSupportedByRuntime, "public async Task WaitAsync()")], @@ -7816,41 +7732,47 @@ public void Method_Update_ReturnType_Tuple_ElementAdd() [Fact] public void Method_Update() { - var src1 = @" -class C -{ - static void F() - { - int a = 1; - int b = 2; - System.Console.WriteLine(a + b); - } -} -"; - var src2 = @" -class C -{ - static void F() - { - int b = 2; - int a = 1; - System.Console.WriteLine(a + b); - } -}"; + var src1 = """ + + class C + { + static void F() + { + int a = 1; + int b = 2; + System.Console.WriteLine(a + b); + } + } + + """; + var src2 = """ + + class C + { + static void F() + { + int b = 2; + int a = 1; + System.Console.WriteLine(a + b); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( - @"Update [static void F() - { - int a = 1; - int b = 2; - System.Console.WriteLine(a + b); - }]@18 -> [static void F() - { - int b = 2; - int a = 1; - System.Console.WriteLine(a + b); - }]@18"); + """ + Update [static void F() + { + int a = 1; + int b = 2; + System.Console.WriteLine(a + b); + }]@18 -> [static void F() + { + int b = 2; + int a = 1; + System.Console.WriteLine(a + b); + }]@18 + """); edits.VerifySemanticDiagnostics(); @@ -7862,19 +7784,23 @@ static void F() [Fact] public void MethodWithExpressionBody_Update() { - var src1 = @" -class C -{ - static int M() => F(1); - static int F(int a) => 1; -} -"; - var src2 = @" -class C -{ - static int M() => F(2); - static int F(int a) => 1; -}"; + var src1 = """ + + class C + { + static int M() => F(1); + static int F(int a) => 1; + } + + """; + var src2 = """ + + class C + { + static int M() => F(2); + static int F(int a) => 1; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -7922,31 +7848,35 @@ public void MethodWithBlockBody_ToExpressionBody() [Fact] public void MethodWithLambda_Update() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static void F() - { - Func a = () => { return 1; }; - Func> b = () => () => { return 1; }; - } -} -"; - var src2 = @" -using System; + using System; -class C -{ - static void F() - { - Func a = () => { return 1; }; - Func> b = () => () => { return 1; }; + class C + { + static void F() + { + Func a = () => { return 1; }; + Func> b = () => () => { return 1; }; + } + } - Console.WriteLine(1); - } -}"; + """; + var src2 = """ + + using System; + + class C + { + static void F() + { + Func a = () => { return 1; }; + Func> b = () => () => { return 1; }; + + Console.WriteLine(1); + } + } + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -7958,52 +7888,62 @@ static void F() [Fact] public void MethodUpdate_LocalVariableDeclaration() { - var src1 = @" -class C -{ - static void F() - { - int x = 1; - Console.WriteLine(x); - } -} -"; - var src2 = @" -class C -{ - static void F() - { - int x = 2; - Console.WriteLine(x); - } -}"; + var src1 = """ + + class C + { + static void F() + { + int x = 1; + Console.WriteLine(x); + } + } + + """; + var src2 = """ + + class C + { + static void F() + { + int x = 2; + Console.WriteLine(x); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( -@"Update [static void F() - { - int x = 1; - Console.WriteLine(x); - }]@18 -> [static void F() - { - int x = 2; - Console.WriteLine(x); - }]@18"); + """ + Update [static void F() + { + int x = 1; + Console.WriteLine(x); + }]@18 -> [static void F() + { + int x = 2; + Console.WriteLine(x); + }]@18 + """); } [Fact] public void Method_Delete() { - var src1 = @" -class C -{ - void goo() { } -} -"; - var src2 = @" -class C -{ -}"; + var src1 = """ + + class C + { + void goo() { } + } + + """; + var src2 = """ + + class C + { + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -8056,16 +7996,20 @@ class C [Fact] public void MethodWithExpressionBody_Delete() { - var src1 = @" -class C -{ - int goo() => 1; -} -"; - var src2 = @" -class C -{ -}"; + var src1 = """ + + class C + { + int goo() => 1; + } + + """; + var src2 = """ + + class C + { + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -8080,22 +8024,28 @@ class C [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] public void MethodDelete_WithParameterAndAttribute() { - var src1 = @" -class C -{ - [Obsolete] - void goo(int a) { } -} -"; - var src2 = @" -class C -{ -}"; + var src1 = """ + + class C + { + [Obsolete] + void goo(int a) { } + } + + """; + var src2 = """ + + class C + { + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( - @"Delete [[Obsolete] - void goo(int a) { }]@18", + """ + Delete [[Obsolete] + void goo(int a) { }]@18 + """, "Delete [(int a)]@42", "Delete [int a]@43"); @@ -8107,31 +8057,37 @@ void goo(int a) { }]@18", [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] public void MethodDelete_PInvoke() { - var src1 = @" -using System; -using System.Runtime.InteropServices; + var src1 = """ -class C -{ - [DllImport(""msvcrt.dll"")] - public static extern int puts(string c); -} -"; - var src2 = @" -using System; -using System.Runtime.InteropServices; + using System; + using System.Runtime.InteropServices; -class C -{ -}"; + class C + { + [DllImport("msvcrt.dll")] + public static extern int puts(string c); + } + + """; + var src2 = """ + + using System; + using System.Runtime.InteropServices; + + class C + { + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( - @"Delete [[DllImport(""msvcrt.dll"")] - public static extern int puts(string c);]@74", - "Delete [(string c)]@134", - "Delete [string c]@135"); + """ + Delete [[DllImport("msvcrt.dll")] + public static extern int puts(string c);]@74 + """, + "Delete [(string c)]@134", + "Delete [string c]@135"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "puts(string c)"))); @@ -8153,25 +8109,29 @@ public void MethodInsert_NotSupportedByRuntime() [Fact] public void PrivateMethodInsert() { - var src1 = @" -class C -{ - static void F() - { - Console.ReadLine(); - } -}"; - var src2 = @" -class C -{ - void goo() { } + var src1 = """ - static void F() - { - Console.ReadLine(); - } -} -"; + class C + { + static void F() + { + Console.ReadLine(); + } + } + """; + var src2 = """ + + class C + { + void goo() { } + + static void F() + { + Console.ReadLine(); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -8185,29 +8145,33 @@ static void F() [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784")] public void PrivateMethodInsert_WithParameters() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static void F() - { - Console.ReadLine(); - } -}"; - var src2 = @" -using System; + using System; -class C -{ - void goo(int a) { } + class C + { + static void F() + { + Console.ReadLine(); + } + } + """; + var src2 = """ - static void F() - { - Console.ReadLine(); - } -} -"; + using System; + + class C + { + void goo(int a) { } + + static void F() + { + Console.ReadLine(); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -8223,31 +8187,37 @@ static void F() [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784")] public void PrivateMethodInsert_WithAttribute() { - var src1 = @" -class C -{ - static void F() - { - Console.ReadLine(); - } -}"; - var src2 = @" -class C -{ - [System.Obsolete] - void goo(int a) { } + var src1 = """ - static void F() - { - Console.ReadLine(); - } -} -"; + class C + { + static void F() + { + Console.ReadLine(); + } + } + """; + var src2 = """ + + class C + { + [System.Obsolete] + void goo(int a) { } + + static void F() + { + Console.ReadLine(); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( - @"Insert [[System.Obsolete] - void goo(int a) { }]@18", + """ + Insert [[System.Obsolete] + void goo(int a) { }]@18 + """, "Insert [(int a)]@49", "Insert [int a]@50"); @@ -8258,16 +8228,20 @@ void goo(int a) { }]@18", [Fact] public void MethodInsert_Virtual() { - var src1 = @" -class C -{ -}"; - var src2 = @" -class C -{ - public virtual void F() {} -} -"; + var src1 = """ + + class C + { + } + """; + var src2 = """ + + class C + { + public virtual void F() {} + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -8277,16 +8251,20 @@ public virtual void F() {} [Fact] public void MethodInsert_Abstract() { - var src1 = @" -abstract class C -{ -}"; - var src2 = @" -abstract class C -{ - public abstract void F(); -} -"; + var src1 = """ + + abstract class C + { + } + """; + var src2 = """ + + abstract class C + { + public abstract void F(); + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -8296,16 +8274,20 @@ abstract class C [Fact] public void MethodInsert_Override() { - var src1 = @" -class C -{ -}"; - var src2 = @" -class C -{ - public override void F() { } -} -"; + var src1 = """ + + class C + { + } + """; + var src2 = """ + + class C + { + public override void F() { } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -8315,28 +8297,34 @@ public override void F() { } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] public void ExternMethod_Insert() { - var src1 = @" -using System; -using System.Runtime.InteropServices; + var src1 = """ -class C -{ -}"; - var src2 = @" -using System; -using System.Runtime.InteropServices; + using System; + using System.Runtime.InteropServices; -class C -{ - [DllImport(""msvcrt.dll"")] - private static extern int puts(string c); -} -"; + class C + { + } + """; + var src2 = """ + + using System; + using System.Runtime.InteropServices; + + class C + { + [DllImport("msvcrt.dll")] + private static extern int puts(string c); + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( - @"Insert [[DllImport(""msvcrt.dll"")] - private static extern int puts(string c);]@74", + """ + Insert [[DllImport("msvcrt.dll")] + private static extern int puts(string c);]@74 + """, "Insert [(string c)]@135", "Insert [string c]@136"); @@ -8348,37 +8336,40 @@ class C [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] public void ExternMethod_DeleteInsert() { - var srcA1 = @" -using System; -using System.Runtime.InteropServices; + // TODO: The method does not need to be updated since there are no sequence points generated for it. + EditAndContinueValidation.VerifySemantics( + [GetTopEdits(""" -class C -{ - [DllImport(""msvcrt.dll"")] - private static extern int puts(string c); -}"; - var srcA2 = @" -using System; -using System.Runtime.InteropServices; -"; + using System; + using System.Runtime.InteropServices; - var srcB1 = @" -using System; -using System.Runtime.InteropServices; -"; - var srcB2 = @" -using System; -using System.Runtime.InteropServices; + class C + { + [DllImport("msvcrt.dll")] + private static extern int puts(string c); + } + """, """ -class C -{ - [DllImport(""msvcrt.dll"")] - private static extern int puts(string c); -} -"; - // TODO: The method does not need to be updated since there are no sequence points generated for it. - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + using System; + using System.Runtime.InteropServices; + + """), GetTopEdits(""" + + using System; + using System.Runtime.InteropServices; + + """, """ + + using System; + using System.Runtime.InteropServices; + + class C + { + [DllImport("msvcrt.dll")] + private static extern int puts(string c); + } + + """)], [ DocumentResults(), DocumentResults(semanticEdits: @@ -8391,37 +8382,40 @@ class C [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] public void ExternMethod_Attribute_DeleteInsert() { - var srcA1 = @" -using System; -using System.Runtime.InteropServices; + EditAndContinueValidation.VerifySemantics( + [GetTopEdits(""" -class C -{ - [DllImport(""msvcrt.dll"")] - private static extern int puts(string c); -}"; - var srcA2 = @" -using System; -using System.Runtime.InteropServices; -"; + using System; + using System.Runtime.InteropServices; - var srcB1 = @" -using System; -using System.Runtime.InteropServices; -"; - var srcB2 = @" -using System; -using System.Runtime.InteropServices; + class C + { + [DllImport("msvcrt.dll")] + private static extern int puts(string c); + } + """, """ -class C -{ - [DllImport(""msvcrt.dll"")] - [Obsolete] - private static extern int puts(string c); -} -"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + using System; + using System.Runtime.InteropServices; + + """), GetTopEdits(""" + + using System; + using System.Runtime.InteropServices; + + """, """ + + using System; + using System.Runtime.InteropServices; + + class C + { + [DllImport("msvcrt.dll")] + [Obsolete] + private static extern int puts(string c); + } + + """)], [ DocumentResults(), DocumentResults(semanticEdits: @@ -8607,22 +8601,26 @@ public void Method_InsertDelete() [Fact] public void Method_Update_Parameter_Insert() { - var src1 = @" -class C -{ - static void F() - { - - } -}"; - var src2 = @" -class C -{ - static void F(int a) - { - - } -}"; + var src1 = """ + + class C + { + static void F() + { + + } + } + """; + var src2 = """ + + class C + { + static void F(int a) + { + + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -8643,23 +8641,27 @@ static void F(int a) [Fact] public void Method_Update_Parameter_Insert_Multiple() { - var src1 = @" -class C -{ - void M(int a) - { - } -}"; - var src2 = @" -class C -{ - void M(int a, int b, int c) - { - } -}"; - var edits = GetTopEdits(src1, src2); + var src1 = """ - edits.VerifySemantics( + class C + { + void M(int a) + { + } + } + """; + var src2 = """ + + class C + { + void M(int a, int b, int c) + { + } + } + """; + var edits = GetTopEdits(src1, src2); + + edits.VerifySemantics( [ SemanticEdit(SemanticEditKind.Delete, c => c.GetMember("C.M"), deletedSymbolContainerProvider: c => c.GetMember("C")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.M")) @@ -8674,24 +8676,28 @@ void M(int a, int b, int c) [Fact] public void Method_Update_Parameter_Insert_Partial() { - var src1 = @" -class C -{ - partial void M(int a); + var src1 = """ - partial void M(int a) - { - } -}"; - var src2 = @" -class C -{ - partial void M(int a, int/*1*/b, int c); + class C + { + partial void M(int a); - partial void M(int a, int/*2*/b, int c) - { - } -}"; + partial void M(int a) + { + } + } + """; + var src2 = """ + + class C + { + partial void M(int a, int/*1*/b, int c); + + partial void M(int a, int/*2*/b, int c) + { + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -8712,22 +8718,26 @@ partial void M(int a, int/*2*/b, int c) [Fact] public void Method_Update_Type() { - var src1 = @" -class C -{ - static void Main(bool x) - { - - } -}"; - var src2 = @" -class C -{ - static void Main(int x) - { - - } -}"; + var src1 = """ + + class C + { + static void Main(bool x) + { + + } + } + """; + var src2 = """ + + class C + { + static void Main(int x) + { + + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -8748,22 +8758,26 @@ static void Main(int x) [Fact] public void Method_Update_Parameter_Type_WithRename() { - var src1 = @" -class C -{ - static void Main(bool someBool) - { - - } -}"; - var src2 = @" -class C -{ - static void Main(int someInt) - { - - } -}"; + var src1 = """ + + class C + { + static void Main(bool someBool) + { + + } + } + """; + var src2 = """ + + class C + { + static void Main(int someInt) + { + + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -8780,22 +8794,26 @@ static void Main(int someInt) [Fact] public void Method_Update_Parameter_Delete() { - var src1 = @" -class C -{ - static void F(int a) - { - - } -}"; - var src2 = @" -class C -{ - static void F() - { - - } -}"; + var src1 = """ + + class C + { + static void F(int a) + { + + } + } + """; + var src2 = """ + + class C + { + static void F() + { + + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -8816,20 +8834,24 @@ static void F() [Fact] public void Method_Update_Parameter_Delete_Multiple() { - var src1 = @" -class C -{ - void M(int a, int b, int c) - { - } -}"; - var src2 = @" -class C -{ - void M(int a) - { - } -}"; + var src1 = """ + + class C + { + void M(int a, int b, int c) + { + } + } + """; + var src2 = """ + + class C + { + void M(int a) + { + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -8849,22 +8871,26 @@ void M(int a) [Fact] public void Method_Update_Parameter_Rename() { - var src1 = @" -class C -{ - static void F(int a) - { - - } -}"; - var src2 = @" -class C -{ - static void F(int b) - { - - } -}"; + var src1 = """ + + class C + { + static void F(int a) + { + + } + } + """; + var src2 = """ + + class C + { + static void F(int b) + { + + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -8884,22 +8910,26 @@ static void F(int b) [Fact] public void Method_Update_Parameter_Rename_WithBodyUpdate() { - var src1 = @" -class C -{ - static void F(int a) - { - - } -}"; - var src2 = @" -class C -{ - static void F(int b) - { - System.Console.Write(1); - } -}"; + var src1 = """ + + class C + { + static void F(int a) + { + + } + } + """; + var src2 = """ + + class C + { + static void F(int b) + { + System.Console.Write(1); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -8975,33 +9005,36 @@ public int F() [Fact] public void Method_Rename() { - var src1 = @" -class C -{ - static void F(int a) - { - - } -}"; - var src2 = @" -class C -{ - static void G(int a) - { - - } -}"; - var edits = GetTopEdits(src1, src2); + var src1 = """ - var expectedEdit = @"Update [static void F(int a) - { - - }]@18 -> [static void G(int a) - { - - }]@18"; + class C + { + static void F(int a) + { + + } + } + """; + var src2 = """ - edits.VerifyEdits(expectedEdit); + class C + { + static void G(int a) + { + + } + } + """; + var edits = GetTopEdits(src1, src2); + edits.VerifyEdits(""" + Update [static void F(int a) + { + + }]@18 -> [static void G(int a) + { + + }]@18 + """); edits.VerifySemantics( [ @@ -9018,20 +9051,24 @@ static void G(int a) [Fact] public void Method_Rename_GenericType() { - var src1 = @" -class C -{ - static void F() - { - } -}"; - var src2 = @" -class C -{ - static void G() - { - } -}"; + var src1 = """ + + class C + { + static void F() + { + } + } + """; + var src2 = """ + + class C + { + static void G() + { + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -9062,20 +9099,24 @@ static void G() [Fact] public void Method_Rename_GenericMethod() { - var src1 = @" -class C -{ - static void F() - { - } -}"; - var src2 = @" -class C -{ - static void G() - { - } -}"; + var src1 = """ + + class C + { + static void F() + { + } + } + """; + var src2 = """ + + class C + { + static void G() + { + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -9146,22 +9187,26 @@ class C [Fact] public void MethodUpdate_AsyncMethod0() { - var src1 = @" -class C -{ - public async Task F() - { - await Task.Delay(1000); - } -}"; - var src2 = @" -class C -{ - public async Task F() - { - await Task.Delay(500); - } -}"; + var src1 = """ + + class C + { + public async Task F() + { + await Task.Delay(1000); + } + } + """; + var src2 = """ + + class C + { + public async Task F() + { + await Task.Delay(500); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -9213,7 +9258,7 @@ public async Task WaitAsync() """; var edits = GetTopEdits(src1, src2); - var expectedEdit = """ + edits.VerifyEdits(""" Update [public async Task WaitAsync() { await Task.Delay(1000); @@ -9223,9 +9268,7 @@ Update [public async Task WaitAsync() await Task.Delay(1000); return "Not Done"; }]@133 - """; - - edits.VerifyEdits(expectedEdit); + """); edits.VerifySemanticDiagnostics( capabilities: EditAndContinueCapabilities.AddInstanceFieldToExistingType); @@ -9234,22 +9277,26 @@ Update [public async Task WaitAsync() [Fact] public void MethodUpdate_AsyncMethod_Generic() { - var src1 = @" -class C -{ - public async Task F() - { - await Task.FromResult(1); - } -}"; - var src2 = @" -class C -{ - public async Task F() - { - await Task.FromResult(2); - } -}"; + var src1 = """ + + class C + { + public async Task F() + { + await Task.FromResult(1); + } + } + """; + var src2 = """ + + class C + { + public async Task F() + { + await Task.FromResult(2); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -9270,37 +9317,43 @@ public async Task F() [Fact] public void MethodUpdate_AddReturnTypeAttribute() { - var src1 = @" -using System; + var src1 = """ -class Test -{ - static void F() - { - System.Console.Write(5); - } -}"; - var src2 = @" -using System; + using System; -class Test -{ - [return: Obsolete] - static void F() - { - System.Console.Write(5); - } -}"; + class Test + { + static void F() + { + System.Console.Write(5); + } + } + """; + var src2 = """ + + using System; + + class Test + { + [return: Obsolete] + static void F() + { + System.Console.Write(5); + } + } + """; var edits = GetTopEdits(src1, src2); - edits.VerifyEdits(@"Update [static void F() - { - System.Console.Write(5); - }]@38 -> [[return: Obsolete] - static void F() - { - System.Console.Write(5); - }]@38"); + edits.VerifyEdits(""" + Update [static void F() + { + System.Console.Write(5); + }]@38 -> [[return: Obsolete] + static void F() + { + System.Console.Write(5); + }]@38 + """); edits.VerifySemanticDiagnostics( [Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void F()", FeaturesResources.method)], @@ -9310,37 +9363,43 @@ static void F() [Fact] public void MethodUpdate_AddAttribute() { - var src1 = @" -using System; + var src1 = """ -class Test -{ - static void F() - { - System.Console.Write(5); - } -}"; - var src2 = @" -using System; + using System; -class Test -{ - [Obsolete] - static void F() - { - System.Console.Write(5); - } -}"; + class Test + { + static void F() + { + System.Console.Write(5); + } + } + """; + var src2 = """ + + using System; + + class Test + { + [Obsolete] + static void F() + { + System.Console.Write(5); + } + } + """; var edits = GetTopEdits(src1, src2); - edits.VerifyEdits(@"Update [static void F() - { - System.Console.Write(5); - }]@38 -> [[Obsolete] - static void F() - { - System.Console.Write(5); - }]@38"); + edits.VerifyEdits(""" + Update [static void F() + { + System.Console.Write(5); + }]@38 -> [[Obsolete] + static void F() + { + System.Console.Write(5); + }]@38 + """); edits.VerifySemanticDiagnostics( [Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void F()", FeaturesResources.method)], @@ -9422,32 +9481,36 @@ static void F() [Fact] public void MethodUpdate_Attribute_ArrayParameter() { - var src1 = @" -class AAttribute : System.Attribute -{ - public AAttribute(int[] nums) { } -} + var src1 = """ -class C -{ - [A(new int[] { 1, 2, 3})] - void M() - { - } -}"; - var src2 = @" -class AAttribute : System.Attribute -{ - public AAttribute(int[] nums) { } -} + class AAttribute : System.Attribute + { + public AAttribute(int[] nums) { } + } -class C -{ - [A(new int[] { 4, 5, 6})] - void M() - { - } -}"; + class C + { + [A(new int[] { 1, 2, 3})] + void M() + { + } + } + """; + var src2 = """ + + class AAttribute : System.Attribute + { + public AAttribute(int[] nums) { } + } + + class C + { + [A(new int[] { 4, 5, 6})] + void M() + { + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -9459,34 +9522,38 @@ void M() [Fact] public void MethodUpdate_Attribute_ArrayParameter_NoChange() { - var src1 = @" -class AAttribute : System.Attribute -{ - public AAttribute(int[] nums) { } -} + var src1 = """ -class C -{ - [A(new int[] { 1, 2, 3})] - void M() - { - var x = 1; - } -}"; - var src2 = @" -class AAttribute : System.Attribute -{ - public AAttribute(int[] nums) { } -} + class AAttribute : System.Attribute + { + public AAttribute(int[] nums) { } + } -class C -{ - [A(new int[] { 1, 2, 3})] - void M() - { - var x = 2; - } -}"; + class C + { + [A(new int[] { 1, 2, 3})] + void M() + { + var x = 1; + } + } + """; + var src2 = """ + + class AAttribute : System.Attribute + { + public AAttribute(int[] nums) { } + } + + class C + { + [A(new int[] { 1, 2, 3})] + void M() + { + var x = 2; + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -9499,28 +9566,32 @@ void M() [Fact] public void MethodUpdate_AddAttribute2() { - var src1 = @" -using System; + var src1 = """ -class Test -{ - [Obsolete] - static void F() - { - System.Console.Write(5); - } -}"; - var src2 = @" -using System; + using System; -class Test -{ - [Obsolete, STAThread] - static void F() - { - System.Console.Write(5); - } -}"; + class Test + { + [Obsolete] + static void F() + { + System.Console.Write(5); + } + } + """; + var src2 = """ + + using System; + + class Test + { + [Obsolete, STAThread] + static void F() + { + System.Console.Write(5); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -9531,29 +9602,33 @@ static void F() [Fact] public void MethodUpdate_AddAttribute3() { - var src1 = @" -using System; + var src1 = """ -class Test -{ - [Obsolete] - static void F() - { - System.Console.Write(5); - } -}"; - var src2 = @" -using System; + using System; -class Test -{ - [Obsolete] - [STAThread] - static void F() - { - System.Console.Write(5); - } -}"; + class Test + { + [Obsolete] + static void F() + { + System.Console.Write(5); + } + } + """; + var src2 = """ + + using System; + + class Test + { + [Obsolete] + [STAThread] + static void F() + { + System.Console.Write(5); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -9564,27 +9639,31 @@ static void F() [Fact] public void MethodUpdate_AddAttribute4() { - var src1 = @" -using System; + var src1 = """ -class Test -{ - static void F() - { - System.Console.Write(5); - } -}"; - var src2 = @" -using System; + using System; -class Test -{ - [Obsolete, STAThread] - static void F() - { - System.Console.Write(5); - } -}"; + class Test + { + static void F() + { + System.Console.Write(5); + } + } + """; + var src2 = """ + + using System; + + class Test + { + [Obsolete, STAThread] + static void F() + { + System.Console.Write(5); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -9595,28 +9674,32 @@ static void F() [Fact] public void MethodUpdate_UpdateAttribute() { - var src1 = @" -using System; + var src1 = """ -class Test -{ - [Obsolete] - static void F() - { - System.Console.Write(5); - } -}"; - var src2 = @" -using System; + using System; -class Test -{ - [Obsolete("""")] - static void F() - { - System.Console.Write(5); - } -}"; + class Test + { + [Obsolete] + static void F() + { + System.Console.Write(5); + } + } + """; + var src2 = """ + + using System; + + class Test + { + [Obsolete("")] + static void F() + { + System.Console.Write(5); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -9627,27 +9710,31 @@ static void F() [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] public void MethodUpdate_DeleteAttribute() { - var src1 = @" -using System; + var src1 = """ -class Test -{ - [Obsolete] - static void F() - { - System.Console.Write(5); - } -}"; - var src2 = @" -using System; + using System; -class Test -{ - static void F() - { - System.Console.Write(5); - } -}"; + class Test + { + [Obsolete] + static void F() + { + System.Console.Write(5); + } + } + """; + var src2 = """ + + using System; + + class Test + { + static void F() + { + System.Console.Write(5); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -9658,28 +9745,32 @@ static void F() [Fact] public void MethodUpdate_DeleteAttribute2() { - var src1 = @" -using System; + var src1 = """ -class Test -{ - [Obsolete, STAThread] - static void F() - { - System.Console.Write(5); - } -}"; - var src2 = @" -using System; + using System; -class Test -{ - [Obsolete] - static void F() - { - System.Console.Write(5); - } -}"; + class Test + { + [Obsolete, STAThread] + static void F() + { + System.Console.Write(5); + } + } + """; + var src2 = """ + + using System; + + class Test + { + [Obsolete] + static void F() + { + System.Console.Write(5); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -9690,29 +9781,33 @@ static void F() [Fact] public void MethodUpdate_DeleteAttribute3() { - var src1 = @" -using System; + var src1 = """ -class Test -{ - [Obsolete] - [STAThread] - static void F() - { - System.Console.Write(5); - } -}"; - var src2 = @" -using System; + using System; -class Test -{ - [Obsolete] - static void F() - { - System.Console.Write(5); - } -}"; + class Test + { + [Obsolete] + [STAThread] + static void F() + { + System.Console.Write(5); + } + } + """; + var src2 = """ + + using System; + + class Test + { + [Obsolete] + static void F() + { + System.Console.Write(5); + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -9723,18 +9818,22 @@ static void F() [Fact] public void MethodUpdate_ExplicitlyImplemented1() { - var src1 = @" -class C : I, J -{ - void I.Goo() { Console.WriteLine(2); } - void J.Goo() { Console.WriteLine(1); } -}"; - var src2 = @" -class C : I, J -{ - void I.Goo() { Console.WriteLine(1); } - void J.Goo() { Console.WriteLine(2); } -}"; + var src1 = """ + + class C : I, J + { + void I.Goo() { Console.WriteLine(2); } + void J.Goo() { Console.WriteLine(1); } + } + """; + var src2 = """ + + class C : I, J + { + void I.Goo() { Console.WriteLine(1); } + void J.Goo() { Console.WriteLine(2); } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -9747,26 +9846,32 @@ class C : I, J [Fact] public void MethodUpdate_ExplicitlyImplemented2() { - var interfaces = @" -interface I { void Goo(); } -interface J { void Goo(); } -"; + var interfaces = """ - var src1 = @" -class C : I, J -{ - void I.Goo() { Console.WriteLine(1); } - void J.Goo() { Console.WriteLine(2); } -} -" + interfaces; + interface I { void Goo(); } + interface J { void Goo(); } - var src2 = @" -class C : I, J -{ - void Goo() { Console.WriteLine(1); } - void J.Goo() { Console.WriteLine(2); } -} -" + interfaces; + """; + + var src1 = """ + + class C : I, J + { + void I.Goo() { Console.WriteLine(1); } + void J.Goo() { Console.WriteLine(2); } + } + + """ + interfaces; + + var src2 = """ + + class C : I, J + { + void Goo() { Console.WriteLine(1); } + void J.Goo() { Console.WriteLine(2); } + } + + """ + interfaces; var edits = GetTopEdits(src1, src2); @@ -9780,32 +9885,36 @@ class C : I, J [Fact] public void MethodUpdate_StackAlloc_Update() { - var src1 = @" -class C -{ - static void Main() - { - int i = 1; - unsafe - { - char* buffer = stackalloc char[16]; - int* px2 = &i; - } - } -}"; - var src2 = @" -class C -{ - static void Main() - { - int i = 2; - unsafe - { - char* buffer = stackalloc char[16]; - int* px2 = &i; - } - } -}"; + var src1 = """ + + class C + { + static void Main() + { + int i = 1; + unsafe + { + char* buffer = stackalloc char[16]; + int* px2 = &i; + } + } + } + """; + var src2 = """ + + class C + { + static void Main() + { + int i = 2; + unsafe + { + char* buffer = stackalloc char[16]; + int* px2 = &i; + } + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -9818,31 +9927,35 @@ static void Main() [Fact] public void MethodUpdate_StackAlloc_Insert() { - var src1 = @" -class C -{ - static void F() - { - int i = 10; - unsafe - { - int* px2 = &i; - } - } -}"; - var src2 = @" -class C -{ - static void F() - { - int i = 10; - unsafe - { - char* buffer = stackalloc char[16]; - int* px2 = &i; - } - } -}"; + var src1 = """ + + class C + { + static void F() + { + int i = 10; + unsafe + { + int* px2 = &i; + } + } + } + """; + var src2 = """ + + class C + { + static void F() + { + int i = 10; + unsafe + { + char* buffer = stackalloc char[16]; + int* px2 = &i; + } + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -9852,31 +9965,35 @@ static void F() [Fact] public void MethodUpdate_StackAlloc_Delete() { - var src1 = @" -class C -{ - static void F() - { - int i = 10; - unsafe - { - char* buffer = stackalloc char[16]; - int* px2 = &i; - } - } -}"; - var src2 = @" -class C -{ - static void F() - { - int i = 10; - unsafe - { - int* px2 = &i; - } - } -}"; + var src1 = """ + + class C + { + static void F() + { + int i = 10; + unsafe + { + char* buffer = stackalloc char[16]; + int* px2 = &i; + } + } + } + """; + var src2 = """ + + class C + { + static void F() + { + int i = 10; + unsafe + { + int* px2 = &i; + } + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -10040,32 +10157,36 @@ public void MethodUpdate_Iterator_YieldBreak() [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087305")] public void MethodUpdate_LabeledStatement() { - var src1 = @" -class C -{ - static void F() - { - goto Label1; - - Label1: - { - Console.WriteLine(1); - } - } -}"; - var src2 = @" -class C -{ - static void F() - { - goto Label1; - - Label1: - { - Console.WriteLine(2); - } - } -}"; + var src1 = """ + + class C + { + static void F() + { + goto Label1; + + Label1: + { + Console.WriteLine(1); + } + } + } + """; + var src2 = """ + + class C + { + static void F() + { + goto Label1; + + Label1: + { + Console.WriteLine(2); + } + } + } + """; var edits = GetTopEdits(src1, src2); @@ -10195,54 +10316,58 @@ public void Method_ReadOnlyRef_ReturnType_Update() [Fact] public void Method_ImplementingInterface_Add() { - var src1 = @" -using System; + var src1 = """ -public interface ISample -{ - string Get(); -} + using System; -public interface IConflict -{ - string Get(); -} + public interface ISample + { + string Get(); + } -public class BaseClass : ISample -{ - public virtual string Get() => string.Empty; -} + public interface IConflict + { + string Get(); + } -public class SubClass : BaseClass, IConflict -{ - public override string Get() => string.Empty; -} -"; - var src2 = @" -using System; + public class BaseClass : ISample + { + public virtual string Get() => string.Empty; + } -public interface ISample -{ - string Get(); -} + public class SubClass : BaseClass, IConflict + { + public override string Get() => string.Empty; + } -public interface IConflict -{ - string Get(); -} + """; + var src2 = """ -public class BaseClass : ISample -{ - public virtual string Get() => string.Empty; -} + using System; -public class SubClass : BaseClass, IConflict -{ - public override string Get() => string.Empty; + public interface ISample + { + string Get(); + } - string IConflict.Get() => String.Empty; -} -"; + public interface IConflict + { + string Get(); + } + + public class BaseClass : ISample + { + public virtual string Get() => string.Empty; + } + + public class SubClass : BaseClass, IConflict + { + public override string Get() => string.Empty; + + string IConflict.Get() => String.Empty; + } + + """; var edits = GetTopEdits(src1, src2); @@ -10257,16 +10382,8 @@ public class SubClass : BaseClass, IConflict [Fact] public void Method_Partial_DeleteInsert_DefinitionPart() { - var srcA1 = "partial class C { partial void F(); }"; - var srcB1 = "partial class C { partial void F() { } }"; - var srcC1 = "partial class C { }"; - - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { partial void F() { } }"; - var srcC2 = "partial class C { partial void F(); }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2)], + [GetTopEdits("partial class C { partial void F(); }", "partial class C { }"), GetTopEdits("partial class C { partial void F() { } }", "partial class C { partial void F() { } }"), GetTopEdits("partial class C { }", "partial class C { partial void F(); }")], [ DocumentResults(), DocumentResults(), @@ -10278,16 +10395,8 @@ public void Method_Partial_DeleteInsert_DefinitionPart() [Fact] public void Method_Partial_DeleteInsert_ImplementationPart() { - var srcA1 = "partial class C { partial void F(); }"; - var srcB1 = "partial class C { partial void F() { } }"; - var srcC1 = "partial class C { }"; - - var srcA2 = "partial class C { partial void F(); }"; - var srcB2 = "partial class C { }"; - var srcC2 = "partial class C { partial void F() { } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2)], + [GetTopEdits("partial class C { partial void F(); }", "partial class C { partial void F(); }"), GetTopEdits("partial class C { partial void F() { } }", "partial class C { }"), GetTopEdits("partial class C { }", "partial class C { partial void F() { } }")], [ DocumentResults(), DocumentResults(), @@ -10299,14 +10408,8 @@ public void Method_Partial_DeleteInsert_ImplementationPart() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51011")] public void Method_Partial_Swap_ImplementationAndDefinitionParts() { - var srcA1 = "partial class C { partial void F(); }"; - var srcB1 = "partial class C { partial void F() { } }"; - - var srcA2 = "partial class C { partial void F() { } }"; - var srcB2 = "partial class C { partial void F(); }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { partial void F(); }", "partial class C { partial void F() { } }"), GetTopEdits("partial class C { partial void F() { } }", "partial class C { partial void F(); }")], [ DocumentResults( semanticEdits: [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F").PartialImplementationPart, partialType: "C")]), @@ -10318,14 +10421,8 @@ public void Method_Partial_Swap_ImplementationAndDefinitionParts() [Fact] public void Method_Partial_DeleteImplementation() { - var srcA1 = "partial class C { partial void F(); }"; - var srcB1 = "partial class C { partial void F() { } }"; - - var srcA2 = "partial class C { partial void F(); }"; - var srcB2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { partial void F(); }", "partial class C { partial void F(); }"), GetTopEdits("partial class C { partial void F() { } }", "partial class C { }")], [ DocumentResults(), @@ -10351,14 +10448,8 @@ public void Method_Partial_DeleteDefinition() [Fact] public void Method_Partial_DeleteBoth() { - var srcA1 = "partial class C { partial void F(); }"; - var srcB1 = "partial class C { partial void F() { } }"; - - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { partial void F(); }", "partial class C { }"), GetTopEdits("partial class C { partial void F() { } }", "partial class C { }")], [ DocumentResults(), DocumentResults( @@ -10369,18 +10460,8 @@ public void Method_Partial_DeleteBoth() [Fact] public void Method_Partial_DeleteInsertBoth() { - var srcA1 = "partial class C { partial void F(); }"; - var srcB1 = "partial class C { partial void F() { } }"; - var srcC1 = "partial class C { }"; - var srcD1 = "partial class C { }"; - - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { }"; - var srcC2 = "partial class C { partial void F(); }"; - var srcD2 = "partial class C { partial void F() { } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2)], + [GetTopEdits("partial class C { partial void F(); }", "partial class C { }"), GetTopEdits("partial class C { partial void F() { } }", "partial class C { }"), GetTopEdits("partial class C { }", "partial class C { partial void F(); }"), GetTopEdits("partial class C { }", "partial class C { partial void F() { } }")], [ DocumentResults(), DocumentResults(), @@ -10394,14 +10475,8 @@ public void Method_Partial_DeleteInsertBoth() [Fact] public void Method_Partial_Insert() { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { }"; - - var srcA2 = "partial class C { partial void F(); }"; - var srcB2 = "partial class C { partial void F() { } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", "partial class C { partial void F(); }"), GetTopEdits("partial class C { }", "partial class C { partial void F() { } }")], [ DocumentResults(), DocumentResults( @@ -10414,13 +10489,9 @@ public void Method_Partial_Insert() public void Method_Partial_Insert_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { }"; - var srcB1 = "partial class C { }"; - var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { partial void F(); }"; - var srcB2 = "partial class C { partial void F() { } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(srcA1, srcA2), GetTopEdits("partial class C { }", "partial class C { partial void F() { } }")], [ DocumentResults( semanticEdits: [SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C")]), @@ -10439,14 +10510,10 @@ public class A : System.Attribute { public A(int x) {} } var srcA1 = attribute + "partial class C { [A(1)]partial void F(); }"; - var srcB1 = "partial class C { partial void F() { } }"; - var srcA2 = attribute + "partial class C { [A(2)]partial void F(); }"; - var srcB2 = "partial class C { partial void F() { } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(srcA1, srcA2), GetTopEdits("partial class C { partial void F() { } }", "partial class C { partial void F() { } }")], [ DocumentResults( semanticEdits: [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F").PartialImplementationPart, partialType: "C")]), @@ -10464,14 +10531,10 @@ public class A : System.Attribute { public A(int x) {} } var srcA1 = attribute + "partial class C { partial void F(); }"; - var srcB1 = "partial class C { [A(1)]partial void F() { } }"; - var srcA2 = attribute + "partial class C { partial void F(); }"; - var srcB2 = "partial class C { [A(2)]partial void F() { } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(srcA1, srcA2), GetTopEdits("partial class C { [A(1)]partial void F() { } }", "partial class C { [A(2)]partial void F() { } }")], [ DocumentResults(), DocumentResults( @@ -10489,14 +10552,10 @@ public class A : System.Attribute { public A(int x) {} } var srcA1 = attribute + "partial class C { [A(1)]partial void F(); }"; - var srcB1 = "partial class C { [A(1)]partial void F() { } }"; - var srcA2 = attribute + "partial class C { [A(2)]partial void F(); }"; - var srcB2 = "partial class C { [A(2)]partial void F() { } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(srcA1, srcA2), GetTopEdits("partial class C { [A(1)]partial void F() { } }", "partial class C { [A(2)]partial void F() { } }")], [ DocumentResults( semanticEdits: [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F").PartialImplementationPart, partialType: "C")]), @@ -10515,14 +10574,10 @@ public class A : System.Attribute {} var srcA1 = attribute + "partial class C { [A]partial void F(); }"; - var srcB1 = "partial class C { partial void F() { } }"; - var srcA2 = attribute + "partial class C { }"; - var srcB2 = "partial class C { partial void F() { } partial void F(); }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(srcA1, srcA2), GetTopEdits("partial class C { partial void F() { } }", "partial class C { partial void F() { } partial void F(); }")], [ DocumentResults(), @@ -10633,24 +10688,28 @@ public void Operator_Conversion_ExternModifiers_Remove() [Fact] public void OperatorInsert() { - var src1 = @" -class C -{ -} -"; - var src2 = @" -class C -{ - public static implicit operator bool (C c) - { - return false; - } + var src1 = """ - public static C operator +(C c, C d) - { - return c; - } -}"; + class C + { + } + + """; + var src2 = """ + + class C + { + public static implicit operator bool (C c) + { + return false; + } + + public static C operator +(C c, C d) + { + return c; + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -10661,24 +10720,28 @@ public static implicit operator bool (C c) [Fact] public void OperatorDelete() { - var src1 = @" -class C -{ - public static implicit operator bool (C c) - { - return false; - } + var src1 = """ - public static C operator +(C c, C d) - { - return c; - } -} -"; - var src2 = @" -class C -{ -}"; + class C + { + public static implicit operator bool (C c) + { + return false; + } + + public static C operator +(C c, C d) + { + return c; + } + } + + """; + var src2 = """ + + class C + { + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -10692,18 +10755,22 @@ class C [Fact] public void OperatorInsertDelete() { - var srcA1 = @" -partial class C -{ - public static implicit operator bool (C c) => false; -} -"; - var srcB1 = @" -partial class C -{ - public static C operator +(C c, C d) => c; -} -"; + var srcA1 = """ + + partial class C + { + public static implicit operator bool (C c) => false; + } + + """; + var srcB1 = """ + + partial class C + { + public static C operator +(C c, C d) => c; + } + + """; var srcA2 = srcB1; var srcB2 = srcA1; @@ -10728,33 +10795,37 @@ partial class C [Fact] public void OperatorUpdate() { - var src1 = @" -class C -{ - public static implicit operator bool (C c) - { - return false; - } + var src1 = """ - public static C operator +(C c, C d) - { - return c; - } -} -"; - var src2 = @" -class C -{ - public static implicit operator bool (C c) - { - return true; - } + class C + { + public static implicit operator bool (C c) + { + return false; + } - public static C operator +(C c, C d) - { - return d; - } -}"; + public static C operator +(C c, C d) + { + return c; + } + } + + """; + var src2 = """ + + class C + { + public static implicit operator bool (C c) + { + return true; + } + + public static C operator +(C c, C d) + { + return d; + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, @@ -10767,19 +10838,23 @@ public static implicit operator bool (C c) [Fact] public void OperatorWithExpressionBody_Update() { - var src1 = @" -class C -{ - public static implicit operator bool (C c) => false; - public static C operator +(C c, C d) => c; -} -"; - var src2 = @" -class C -{ - public static implicit operator bool (C c) => true; - public static C operator +(C c, C d) => d; -}"; + var src1 = """ + + class C + { + public static implicit operator bool (C c) => false; + public static C operator +(C c, C d) => c; + } + + """; + var src2 = """ + + class C + { + public static implicit operator bool (C c) => true; + public static C operator +(C c, C d) => d; + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, @@ -10824,17 +10899,21 @@ public void OperatorWithBlockBody_ToExpressionBody() [Fact] public void Operator_Rename() { - var src1 = @" -class C -{ - public static C operator +(C c, C d) { return c; } -} -"; - var src2 = @" -class C -{ - public static C operator -(C c, C d) { return d; } -}"; + var src1 = """ + + class C + { + public static C operator +(C c, C d) { return c; } + } + + """; + var src2 = """ + + class C + { + public static C operator -(C c, C d) { return d; } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, @@ -10845,22 +10924,26 @@ class C capabilities: EditAndContinueCapabilities.AddMethodToExistingType); } - [Fact] - public void OperatorReorder1() - { - var src1 = @" -class C -{ - public static implicit operator bool (C c) { return false; } - public static implicit operator int (C c) { return 1; } -} -"; - var src2 = @" -class C -{ - public static implicit operator int (C c) { return 1; } - public static implicit operator bool (C c) { return false; } -}"; + [Fact] + public void OperatorReorder1() + { + var src1 = """ + + class C + { + public static implicit operator bool (C c) { return false; } + public static implicit operator int (C c) { return 1; } + } + + """; + var src2 = """ + + class C + { + public static implicit operator int (C c) { return 1; } + public static implicit operator bool (C c) { return false; } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -10872,19 +10955,23 @@ class C [Fact] public void OperatorReorder2() { - var src1 = @" -class C -{ - public static C operator +(C c, C d) { return c; } - public static C operator -(C c, C d) { return d; } -} -"; - var src2 = @" -class C -{ - public static C operator -(C c, C d) { return d; } - public static C operator +(C c, C d) { return c; } -}"; + var src1 = """ + + class C + { + public static C operator +(C c, C d) { return c; } + public static C operator -(C c, C d) { return d; } + } + + """; + var src2 = """ + + class C + { + public static C operator -(C c, C d) { return d; } + public static C operator +(C c, C d) { return c; } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -11126,14 +11213,8 @@ public void Constructor_Parameter_Update_Type_Primary() [Fact] public void Constructor_Parameter_Update_Type_Primary_PartialMove() { - var srcA1 = "partial class C(bool a);"; - var srcB1 = "partial class C;"; - - var srcA2 = "partial class C;"; - var srcB2 = "partial class C(int a);"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C(bool a);", "partial class C;"), GetTopEdits("partial class C;", "partial class C(int a);")], [ DocumentResults( semanticEdits: @@ -11273,16 +11354,20 @@ public void Constructor_Parameter_Delete_Primary_Record() [Fact] public void Constructor_Parameter_Delete_Primary_Record_LayoutClass() { - var src1 = @" -using System.Runtime.InteropServices; -[StructLayoutAttribute(LayoutKind.Sequential)] -record C(int X, int Y); -"; - var src2 = @" -using System.Runtime.InteropServices; -[StructLayoutAttribute(LayoutKind.Sequential)] -record C(int X); -"; + var src1 = """ + + using System.Runtime.InteropServices; + [StructLayoutAttribute(LayoutKind.Sequential)] + record C(int X, int Y); + + """; + var src2 = """ + + using System.Runtime.InteropServices; + [StructLayoutAttribute(LayoutKind.Sequential)] + record C(int X); + + """; var edits = GetTopEdits(src1, src2); // Note: We do not report rude edits when deleting auto-properties of a type with a sequential or explicit layout. @@ -11555,22 +11640,26 @@ public void Constructor_Parameter_Delete_Primary_Record_WithCustomDeconstructor_ [Fact] public void Constructor_Parameter_Delete_Primary_LayoutClass_NotCaptured() { - var src1 = @" -using System.Runtime.InteropServices; + var src1 = """ -[StructLayoutAttribute(LayoutKind.Sequential)] -class C(int x, int y) -{ -} -"; - var src2 = @" -using System.Runtime.InteropServices; + using System.Runtime.InteropServices; -[StructLayoutAttribute(LayoutKind.Sequential)] -class C(int x) -{ -} -"; + [StructLayoutAttribute(LayoutKind.Sequential)] + class C(int x, int y) + { + } + + """; + var src2 = """ + + using System.Runtime.InteropServices; + + [StructLayoutAttribute(LayoutKind.Sequential)] + class C(int x) + { + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -11585,24 +11674,28 @@ class C(int x) [Fact] public void Constructor_Parameter_Delete_Primary_LayoutClass_Captured() { - var src1 = @" -using System.Runtime.InteropServices; + var src1 = """ -[StructLayoutAttribute(LayoutKind.Sequential)] -class C(int x, int y) -{ - public int M() => x + y; -} -"; - var src2 = @" -using System.Runtime.InteropServices; + using System.Runtime.InteropServices; -[StructLayoutAttribute(LayoutKind.Sequential)] -class C(int x) -{ - public int M() => x; -} -"; + [StructLayoutAttribute(LayoutKind.Sequential)] + class C(int x, int y) + { + public int M() => x + y; + } + + """; + var src2 = """ + + using System.Runtime.InteropServices; + + [StructLayoutAttribute(LayoutKind.Sequential)] + class C(int x) + { + public int M() => x; + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -11720,19 +11813,23 @@ public void Constructor_Parameter_Insert_Primary_Record() [Fact] public void Constructor_Parameter_Insert_Primary_Record_ClassWithLayout() { - var src1 = @" -using System.Runtime.InteropServices; + var src1 = """ + + using System.Runtime.InteropServices; + + [StructLayoutAttribute(LayoutKind.Sequential)] + record C(int X) { } + + """; -[StructLayoutAttribute(LayoutKind.Sequential)] -record C(int X) { } -"; + var src2 = """ + + using System.Runtime.InteropServices; - var src2 = @" -using System.Runtime.InteropServices; + [StructLayoutAttribute(LayoutKind.Sequential)] + record C(int X, int Y) { } -[StructLayoutAttribute(LayoutKind.Sequential)] -record C(int X, int Y) { } -"; + """; var edits = GetTopEdits(src1, src2); @@ -11743,16 +11840,20 @@ record C(int X, int Y) { } [Fact] public void Constructor_Parameter_Insert_Primary_Record_Struct() { - var src1 = @" -record struct C(int x) -{ -} -"; - var src2 = @" -record struct C(int x, int y) -{ -} -"; + var src1 = """ + + record struct C(int x) + { + } + + """; + var src2 = """ + + record struct C(int x, int y) + { + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -11898,14 +11999,8 @@ public void Constructor_Parameter_Insert_Primary_Record_WithCustomDeconstructor_ [Fact] public void Constructor_Parameter_Insert_Primary_Record_WithCustomDeconstructor_Delete_Partial() { - var srcA1 = "partial record C(int X ) { public partial void Deconstruct(out int X) => X = 1; }"; - var srcB1 = "partial record C { public partial void Deconstruct(out int X); }"; - - var srcA2 = "partial record C(int X, int Y);"; - var srcB2 = "partial record C;"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial record C(int X ) { public partial void Deconstruct(out int X) => X = 1; }", "partial record C(int X, int Y);"), GetTopEdits("partial record C { public partial void Deconstruct(out int X); }", "partial record C;")], [ DocumentResults( semanticEdits: @@ -11928,22 +12023,26 @@ public void Constructor_Parameter_Insert_Primary_Record_WithCustomDeconstructor_ [Fact] public void Constructor_Parameter_Insert_Primary_IntoLayoutClass_NotLifted() { - var src1 = @" -using System.Runtime.InteropServices; + var src1 = """ -[StructLayoutAttribute(LayoutKind.Sequential)] -class C(int x) -{ -} -"; - var src2 = @" -using System.Runtime.InteropServices; + using System.Runtime.InteropServices; -[StructLayoutAttribute(LayoutKind.Sequential)] -class C(int x, int y) -{ -} -"; + [StructLayoutAttribute(LayoutKind.Sequential)] + class C(int x) + { + } + + """; + var src2 = """ + + using System.Runtime.InteropServices; + + [StructLayoutAttribute(LayoutKind.Sequential)] + class C(int x, int y) + { + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -11958,24 +12057,28 @@ class C(int x, int y) [Fact] public void Constructor_Parameter_Insert_Primary_IntoLayoutClass_Lifted() { - var src1 = @" -using System.Runtime.InteropServices; + var src1 = """ -[StructLayoutAttribute(LayoutKind.Sequential)] -class C(int x) -{ - public int M() => x; -} -"; - var src2 = @" -using System.Runtime.InteropServices; + using System.Runtime.InteropServices; -[StructLayoutAttribute(LayoutKind.Sequential)] -class C(int x, int y) -{ - public int M() => x + y; -} -"; + [StructLayoutAttribute(LayoutKind.Sequential)] + class C(int x) + { + public int M() => x; + } + + """; + var src2 = """ + + using System.Runtime.InteropServices; + + [StructLayoutAttribute(LayoutKind.Sequential)] + class C(int x, int y) + { + public int M() => x + y; + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -11988,26 +12091,30 @@ class C(int x, int y) [Fact] public void Constructor_Parameter_Insert_Primary_IntoLayoutClass_LiftedInLambda() { - var src1 = @" -using System; -using System.Runtime.InteropServices; + var src1 = """ -[StructLayoutAttribute(LayoutKind.Sequential)] -class C(int x) -{ - public Func M() => () => x; -} -"; - var src2 = @" -using System; -using System.Runtime.InteropServices; + using System; + using System.Runtime.InteropServices; -[StructLayoutAttribute(LayoutKind.Sequential)] -class C(int x, int y) -{ - public Func M() => () => x + y; -} -"; + [StructLayoutAttribute(LayoutKind.Sequential)] + class C(int x) + { + public Func M() => () => x; + } + + """; + var src2 = """ + + using System; + using System.Runtime.InteropServices; + + [StructLayoutAttribute(LayoutKind.Sequential)] + class C(int x, int y) + { + public Func M() => () => x + y; + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -12105,18 +12212,22 @@ public void Constructor_Parameter_Reorder_Primary_Lifted_Record() [Fact] public void Constructor_Parameter_Capture_Primary_Class() { - var src1 = @" -class C(int x) -{ - public int M() => 1; -} -"; - var src2 = @" -class C(int x) -{ - public int M() => x; -} -"; + var src1 = """ + + class C(int x) + { + public int M() => 1; + } + + """; + var src2 = """ + + class C(int x) + { + public int M() => x; + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -12126,20 +12237,24 @@ class C(int x) [Fact] public void Constructor_Parameter_Capture_Primary_Struct() { - var src1 = @" -struct C(int x, int y) -{ - public int M1() => 1; - public int M2() => y; -} -"; - var src2 = @" -struct C(int x, int y) -{ - public int M1() => y; - public int M2() => x; -} -"; + var src1 = """ + + struct C(int x, int y) + { + public int M1() => 1; + public int M2() => y; + } + + """; + var src2 = """ + + struct C(int x, int y) + { + public int M1() => y; + public int M2() => x; + } + + """; var edits = GetTopEdits(src1, src2); // note: 'y' is not reported since it is still captured @@ -12150,26 +12265,30 @@ struct C(int x, int y) [Fact] public void Constructor_Parameter_Capture_Primary_ClassWithLayout() { - var src1 = @" -using System.Runtime.InteropServices; + var src1 = """ -[StructLayoutAttribute(LayoutKind.Sequential)] -class C(int x, int y) -{ - public int M1() => 1; - public int M2() => y; -} -"; - var src2 = @" -using System.Runtime.InteropServices; + using System.Runtime.InteropServices; -[StructLayoutAttribute(LayoutKind.Sequential)] -class C(int x, int y) -{ - public int M1() => y; - public int M2() => x; -} -"; + [StructLayoutAttribute(LayoutKind.Sequential)] + class C(int x, int y) + { + public int M1() => 1; + public int M2() => y; + } + + """; + var src2 = """ + + using System.Runtime.InteropServices; + + [StructLayoutAttribute(LayoutKind.Sequential)] + class C(int x, int y) + { + public int M1() => y; + public int M2() => x; + } + + """; var edits = GetTopEdits(src1, src2); // note: 'y' is not reported since it is still captured @@ -12180,22 +12299,26 @@ class C(int x, int y) [Fact] public void Constructor_Parameter_CeaseCapturing_Primary_Struct() { - var src1 = @" -struct C(int x, int y) -{ - public int M1() => 1; - public int M2() => x; - public int M3() => y; -} -"; - var src2 = @" -struct C(int x, int y) -{ - public int M1() => y; - public int M2() => 1; - public int M3() => 2; -} -"; + var src1 = """ + + struct C(int x, int y) + { + public int M1() => 1; + public int M2() => x; + public int M3() => y; + } + + """; + var src2 = """ + + struct C(int x, int y) + { + public int M1() => y; + public int M2() => 1; + public int M3() => 2; + } + + """; var edits = GetTopEdits(src1, src2); // note: 'y' is not reported since it is still captured @@ -12206,28 +12329,32 @@ struct C(int x, int y) [Fact] public void Constructor_Parameter_CeaseCapturing_Primary_ClassWithLayout() { - var src1 = @" -using System.Runtime.InteropServices; + var src1 = """ -[StructLayoutAttribute(LayoutKind.Sequential)] -class C(int x, int y) -{ - public int M1() => 1; - public int M2() => x; - public int M3() => y; -} -"; - var src2 = @" -using System.Runtime.InteropServices; + using System.Runtime.InteropServices; -[StructLayoutAttribute(LayoutKind.Sequential)] -class C(int x, int y) -{ - public int M1() => y; - public int M2() => 1; - public int M3() => 2; -} -"; + [StructLayoutAttribute(LayoutKind.Sequential)] + class C(int x, int y) + { + public int M1() => 1; + public int M2() => x; + public int M3() => y; + } + + """; + var src2 = """ + + using System.Runtime.InteropServices; + + [StructLayoutAttribute(LayoutKind.Sequential)] + class C(int x, int y) + { + public int M1() => y; + public int M2() => 1; + public int M3() => 2; + } + + """; var edits = GetTopEdits(src1, src2); // note: 'y' is not reported since it is still captured @@ -12312,14 +12439,8 @@ public void Constructor_Parameter_DeleteInsert_ReplacingPrimaryWithNonPrimary(st [Fact] public void Constructor_Parameter_DeleteInsert_ReplacingPrimaryWithNonPrimary_Record() { - var srcA1 = "partial record C(int P);"; - var srcB1 = "partial record C;"; - - var srcA2 = "partial record C;"; - var srcB2 = "partial record C { public int P { get; init; } public C(int P) { } public void Deconstruct(out int P) { P = this.P; } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial record C(int P);", "partial record C;"), GetTopEdits("partial record C;", "partial record C { public int P { get; init; } public C(int P) { } public void Deconstruct(out int P) { P = this.P; } }")], [ DocumentResults(), @@ -12341,14 +12462,8 @@ public void Constructor_Parameter_DeleteInsert_ReplacingPrimaryWithNonPrimary_Re [Fact] public void Constructor_Parameter_DeleteInsert_ReplacingNonPrimaryWithPrimary_Record() { - var srcA1 = "partial record C { public int P { get; init; } public C(int P) { } public void Deconstruct(out int P) { P = this.P; } }"; - var srcB1 = "partial record C;"; - - var srcA2 = "partial record C;"; - var srcB2 = "partial record C(int P);"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial record C { public int P { get; init; } public C(int P) { } public void Deconstruct(out int P) { P = this.P; } }", "partial record C;"), GetTopEdits("partial record C;", "partial record C(int P);")], [ DocumentResults(), @@ -12370,14 +12485,8 @@ public void Constructor_Parameter_DeleteInsert_ReplacingNonPrimaryWithPrimary_Re [Fact] public void Constructor_Parameter_DeleteInsert_ReplacingNonPrimaryWithPrimary_WithExplicitPropertyAdded_Record() { - var srcA1 = "partial record C { public int P { get; init; } public C(int P) { } public void Deconstruct(out int P) { P = this.P; } }"; - var srcB1 = "partial record C;"; - - var srcA2 = "partial record C;"; - var srcB2 = "partial record C(int P) { public int P { get; init; } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial record C { public int P { get; init; } public C(int P) { } public void Deconstruct(out int P) { P = this.P; } }", "partial record C;"), GetTopEdits("partial record C;", "partial record C(int P) { public int P { get; init; } }")], [ DocumentResults(), @@ -12399,14 +12508,8 @@ public void Constructor_Parameter_DeleteInsert_ReplacingNonPrimaryWithPrimary_Wi [Fact] public void Constructor_Parameter_DeleteInsert_ReplacingNonPrimaryWithPrimary_WithExplicitFieldAdded_Record() { - var srcA1 = "partial record C { public int P { get; init; } public C(int P) { } public void Deconstruct(out int P) { P = this.P; } }"; - var srcB1 = "partial record C;"; - - var srcA2 = "partial record C;"; - var srcB2 = "partial record C(int P) { public int P; }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial record C { public int P { get; init; } public C(int P) { } public void Deconstruct(out int P) { P = this.P; } }", "partial record C;"), GetTopEdits("partial record C;", "partial record C(int P) { public int P; }")], [ DocumentResults(semanticEdits: [ @@ -12432,15 +12535,9 @@ public void Constructor_Parameter_DeleteInsert_ReplacingNonPrimaryWithPrimary_Wi [Fact] public void Constructor_Parameter_DeleteInsert_SwappingNonPrimaryWithPrimary_Record() - { - var srcA1 = "partial record C(int P) { public C() : this(1) { } }"; - var srcB1 = "partial record C;"; - - var srcA2 = "partial record C;"; - var srcB2 = "partial record C() { public C(int P) : this() { } }"; - + { EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial record C(int P) { public C() : this(1) { } }", "partial record C;"), GetTopEdits("partial record C;", "partial record C() { public C(int P) : this() { } }")], [ DocumentResults( semanticEdits: @@ -12467,14 +12564,8 @@ public void Constructor_Parameter_DeleteInsert_SwappingNonPrimaryWithPrimary_Rec [Fact] public void Constructor_Parameter_DeleteInsert_ReplacingPropertyWithField_Record() { - var srcA1 = "partial record C(int P) { public int P { get; init; } }"; - var srcB1 = "partial record C;"; - - var srcA2 = "partial record C;"; - var srcB2 = "partial record C(int P) { public int P; }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial record C(int P) { public int P { get; init; } }", "partial record C;"), GetTopEdits("partial record C;", "partial record C(int P) { public int P; }")], [ DocumentResults( semanticEdits: @@ -12515,16 +12606,20 @@ public void Constructor_Instance_Update_Primary_Attributes( [Fact] public void Constructor_Instance_Update_Initializer_Update() { - var src1 = @" -class C -{ - public C(int a) : base(a) { } -}"; - var src2 = @" -class C -{ - public C(int a) : base(a + 1) { } -}"; + var src1 = """ + + class C + { + public C(int a) : base(a) { } + } + """; + var src2 = """ + + class C + { + public C(int a) : base(a + 1) { } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -12537,16 +12632,20 @@ public C(int a) : base(a + 1) { } [Fact] public void Constructor_Instance_Update_Initializer_Update_Generic() { - var src1 = @" -class C -{ - public C(int a) : base(a) { } -}"; - var src2 = @" -class C -{ - public C(int a) : base(a + 1) { } -}"; + var src1 = """ + + class C + { + public C(int a) : base(a) { } + } + """; + var src2 = """ + + class C + { + public C(int a) : base(a + 1) { } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -12594,16 +12693,20 @@ public void Constructor_Instance_Update_Initializer_Update_Primary_WithInterface [Fact] public void Constructor_Instance_Update_Initializer_Delete() { - var src1 = @" -class C -{ - public C(int a) : base(a) { } -}"; - var src2 = @" -class C -{ - public C(int a) { } -}"; + var src1 = """ + + class C + { + public C(int a) : base(a) { } + } + """; + var src2 = """ + + class C + { + public C(int a) { } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -12642,16 +12745,20 @@ public void Constructor_Instance_Update_Initializer_Delete_Primary(string keywor [Fact] public void Constructor_Instance_Update_Initializer_Insert() { - var src1 = @" -class C -{ - public C(int a) { } -}"; - var src2 = @" -class C -{ - public C(int a) : base(a) { } -}"; + var src1 = """ + + class C + { + public C(int a) { } + } + """; + var src2 = """ + + class C + { + public C(int a) : base(a) { } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -12742,22 +12849,26 @@ public void Constructor_Instance_Update_AnonymousTypeInMemberInitializer_Field_P [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17681")] public void Constructor_Instance_Update_BlockBodyToExpressionBody() { - var src1 = @" -public class C -{ - private int _value; + var src1 = """ - public C(int value) { _value = value; } -} -"; - var src2 = @" -public class C -{ - private int _value; + public class C + { + private int _value; - public C(int value) => _value = value; -} -"; + public C(int value) { _value = value; } + } + + """; + var src2 = """ + + public class C + { + private int _value; + + public C(int value) => _value = value; + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public C(int value) { _value = value; }]@52 -> [public C(int value) => _value = value;]@52"); @@ -12772,22 +12883,26 @@ public class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17681")] public void Constructor_Instance_Update_BlockBodyToExpressionBody_WithInitializer() { - var src1 = @" -public class B { B(int value) {} } -public class C : B -{ - private int _value; - public C(int value) : base(value) { _value = value; } -} -"; - var src2 = @" -public class B { B(int value) {} } -public class C : B -{ - private int _value; - public C(int value) : base(value) => _value = value; -} -"; + var src1 = """ + + public class B { B(int value) {} } + public class C : B + { + private int _value; + public C(int value) : base(value) { _value = value; } + } + + """; + var src2 = """ + + public class B { B(int value) {} } + public class C : B + { + private int _value; + public C(int value) : base(value) => _value = value; + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public C(int value) : base(value) { _value = value; }]@90 -> [public C(int value) : base(value) => _value = value;]@90"); @@ -12802,22 +12917,26 @@ public class C : B [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17681")] public void Constructor_Instance_Update_ExpressionBodyToBlockBody() { - var src1 = @" -public class C -{ - private int _value; + var src1 = """ - public C(int value) => _value = value; -} -"; - var src2 = @" -public class C -{ - private int _value; + public class C + { + private int _value; - public C(int value) { _value = value; } -} -"; + public C(int value) => _value = value; + } + + """; + var src2 = """ + + public class C + { + private int _value; + + public C(int value) { _value = value; } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [public C(int value) => _value = value;]@52 -> [public C(int value) { _value = value; }]@52"); @@ -12832,22 +12951,26 @@ public class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17681")] public void Constructor_Instance_Update_ExpressionBodyToBlockBody_WithInitializer() { - var src1 = @" -public class B { B(int value) {} } -public class C : B -{ - private int _value; - public C(int value) : base(value) => _value = value; -} -"; - var src2 = @" -public class B { B(int value) {} } -public class C : B -{ - private int _value; - public C(int value) : base(value) { _value = value; } -} -"; + var src1 = """ + + public class B { B(int value) {} } + public class C : B + { + private int _value; + public C(int value) : base(value) => _value = value; + } + + """; + var src2 = """ + + public class B { B(int value) {} } + public class C : B + { + private int _value; + public C(int value) : base(value) { _value = value; } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [public C(int value) : base(value) => _value = value;]@90 -> [public C(int value) : base(value) { _value = value; }]@90"); @@ -12862,34 +12985,38 @@ public class C : B [Fact] public void Constructor_Instance_Update_SemanticError_Partial() { - var src1 = @" -partial class C -{ - partial void C(int x); -} + var src1 = """ -partial class C -{ - partial void C(int x) - { - System.Console.WriteLine(1); - } -} -"; - var src2 = @" -partial class C -{ - partial void C(int x); -} + partial class C + { + partial void C(int x); + } -partial class C -{ - partial void C(int x) - { - System.Console.WriteLine(2); - } -} -"; + partial class C + { + partial void C(int x) + { + System.Console.WriteLine(1); + } + } + + """; + var src2 = """ + + partial class C + { + partial void C(int x); + } + + partial class C + { + partial void C(int x) + { + System.Console.WriteLine(2); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -13053,22 +13180,30 @@ public void Constructor_Instance_Insert_ReplacingDefault_Class_Primary_Record_Ge [InlineData("struct")] public void Constructor_Instance_Insert_ReplacingDefault_Class_WithMemberInitializers(string typeKind) { - var src1 = @" -" + typeKind + @" C -{ - private int a = 10; - private int b; -} -"; - var src2 = @" -" + typeKind + @" C -{ - private int a = 10; - private int b; + var src1 = """ - public C() { b = 3; } -} -"; + + """ + typeKind + """ + C + { + private int a = 10; + private int b; + } + + """; + var src2 = """ + + + """ + typeKind + """ + C + { + private int a = 10; + private int b; + + public C() { b = 3; } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [public C() { b = 3; }]@66", "Insert [()]@74"); @@ -13106,14 +13241,8 @@ public void Constructor_Instance_Insert_ReplacingDefault_WithStackAllocInMemberI [Fact] public void Constructor_Instance_Insert_ReplacingDefault_WithStackAllocInMemberInitializer_Partial() { - var srcA1 = "partial class C { int a = G(stackalloc int[10]); }"; - var srcB1 = "partial class C { static int G(System.Span span) => 1; }"; - - var srcA2 = "partial class C { int a = G(stackalloc int[10]); }"; - var srcB2 = "partial class C { static int G(System.Span span) => 1; public C() { } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { int a = G(stackalloc int[10]); }", "partial class C { int a = G(stackalloc int[10]); }"), GetTopEdits("partial class C { static int G(System.Span span) => 1; }", "partial class C { static int G(System.Span span) => 1; public C() { } }")], [ DocumentResults(), @@ -13128,14 +13257,8 @@ public void Constructor_Instance_Insert_ReplacingDefault_WithStackAllocInMemberI [Fact] public void Constructor_Instance_Delete_ReplacingDefault_Partial() { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { }"; - - var srcA2 = "partial class C { public C(int a) { } }"; - var srcB2 = "partial class C { public C(int a, int b) { } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", "partial class C { public C(int a) { } }"), GetTopEdits("partial class C { }", "partial class C { public C(int a, int b) { } }")], [ DocumentResults( semanticEdits: @@ -13157,14 +13280,8 @@ public void Constructor_Instance_Delete_ReplacingDefault_Partial() [Fact] public void Constructor_Instance_Insert_ReplacingExplicitWithDefault_WithStackAllocInMemberInitializer_Partial() { - var srcA1 = "partial class C { int a = G(stackalloc int[10]); }"; - var srcB1 = "partial class C { static int G(System.Span span) => 1; public C() { } }"; - - var srcA2 = "partial class C { int a = G(stackalloc int[10]); }"; - var srcB2 = "partial class C { static int G(System.Span span) => 1; }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { int a = G(stackalloc int[10]); }", "partial class C { int a = G(stackalloc int[10]); }"), GetTopEdits("partial class C { static int G(System.Span span) => 1; public C() { } }", "partial class C { static int G(System.Span span) => 1; }")], [ DocumentResults(), @@ -13515,22 +13632,26 @@ public void Constructor_Instance_Delete_UpdatingImplicit( [Fact] public void Constructor_Instance_Delete_Parameterless() { - var src1 = @" -class C -{ - private int a = 10; - private int b; + var src1 = """ - public C() { b = 3; } -} -"; - var src2 = @" -class C -{ - private int a = 10; - private int b; -} -"; + class C + { + private int a = 10; + private int b; + + public C() { b = 3; } + } + + """; + var src2 = """ + + class C + { + private int a = 10; + private int b; + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -13620,14 +13741,8 @@ public void Constructor_Instance_Delete_Primary_Struct_CeasingCapture() [Fact] public void Constructor_Instance_Delete_Public_PartialWithInitializerUpdate() { - var srcA1 = "partial class C { public C() { } }"; - var srcB1 = "partial class C { int x = 1; }"; - - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { int x = 2; }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { public C() { } }", "partial class C { }"), GetTopEdits("partial class C { int x = 1; }", "partial class C { int x = 2; }")], [ DocumentResults( semanticEdits: [SemanticEdit(SemanticEditKind.Update, c => c.GetParameterlessConstructor("C"), partialType: "C", preserveLocalVariables: true)]), @@ -13700,14 +13815,8 @@ public void Constructor_Instance_Delete_ReplacingCustomWithSynthesized_AbstractT [Fact] public void Constructor_Instance_Delete_ReplacingCustomWithSynthesized_Partial() { - var srcA1 = "partial class C { public C(int a) { } }"; - var srcB1 = "partial class C { public C(int a, int b) { } }"; - - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { public C(int a) { } }", "partial class C { }"), GetTopEdits("partial class C { public C(int a, int b) { } }", "partial class C { }")], [ DocumentResults( semanticEdits: [SemanticEdit(SemanticEditKind.Delete, c => c.GetMember("C").InstanceConstructors.Single(m => m.Parameters.Length == 1), deletedSymbolContainerProvider: c => c.GetMember("C"))]), @@ -13782,14 +13891,18 @@ public void Constructor_Instance_Delete_Primary_ReplacingWithRegular_AbstractTyp [Fact] public void Constructor_Instance_InsertDelete_Primary_Partial_Class() { - var src1 = @" -partial class C { } -partial class C(int P); -"; - var src2 = @" -partial class C(int P) { } -partial class C; -"; + var src1 = """ + + partial class C { } + partial class C(int P); + + """; + var src2 = """ + + partial class C(int P) { } + partial class C; + + """; var edits = GetTopEdits(src1, src2); @@ -13800,14 +13913,18 @@ partial class C; [Fact] public void Constructor_Instance_InsertDelete_Primary_Partial_Record() { - var src1 = @" -partial record C { } -partial record C(int P); -"; - var src2 = @" -partial record C(int P) { } -partial record C; -"; + var src1 = """ + + partial record C { } + partial record C(int P); + + """; + var src2 = """ + + partial record C(int P) { } + partial record C; + + """; var edits = GetTopEdits(src1, src2); @@ -13820,14 +13937,8 @@ partial record C; [Fact] public void Constructor_Instance_Partial_DeletePrivateInsertPrivate() { - var srcA1 = "partial class C { C() { } }"; - var srcB1 = "partial class C { }"; - - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { C() { } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { C() { } }", "partial class C { }"), GetTopEdits("partial class C { }", "partial class C { C() { } }")], [ // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), @@ -13843,14 +13954,8 @@ public void Constructor_Instance_Partial_DeletePrivateInsertPrivate() [Fact] public void Constructor_Instance_Partial_DeletePublicInsertPublic() { - var srcA1 = "partial class C { public C() { } }"; - var srcB1 = "partial class C { }"; - - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { public C() { } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { public C() { } }", "partial class C { }"), GetTopEdits("partial class C { }", "partial class C { public C() { } }")], [ // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), @@ -13866,14 +13971,8 @@ public void Constructor_Instance_Partial_DeletePublicInsertPublic() [Fact] public void Constructor_Instance_Partial_DeletePrivateInsertPublic() { - var srcA1 = "partial class C { C() { } }"; - var srcB1 = "partial class C { }"; - - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { public C() { } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { C() { } }", "partial class C { }"), GetTopEdits("partial class C { }", "partial class C { public C() { } }")], [ // delete of the constructor in partial part will be reported as rude edit in the other document where it was inserted back with changed accessibility DocumentResults( @@ -13887,14 +13986,8 @@ public void Constructor_Instance_Partial_DeletePrivateInsertPublic() [Fact] public void Constructor_Instance_Partial_InsertPublicDeletePublic() { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { public C() { } }"; - - var srcA2 = "partial class C { public C() { } }"; - var srcB2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", "partial class C { public C() { } }"), GetTopEdits("partial class C { public C() { } }", "partial class C { }")], [ DocumentResults( semanticEdits: @@ -13910,14 +14003,8 @@ public void Constructor_Instance_Partial_InsertPublicDeletePublic() [Fact] public void Constructor_Instance_Partial_InsertPrivateDeletePrivate() { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { private C() { } }"; - - var srcA2 = "partial class C { private C() { } }"; - var srcB2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", "partial class C { private C() { } }"), GetTopEdits("partial class C { private C() { } }", "partial class C { }")], [ DocumentResults( semanticEdits: @@ -13933,14 +14020,8 @@ public void Constructor_Instance_Partial_InsertPrivateDeletePrivate() [Fact] public void Constructor_Instance_Partial_DeleteInternalInsertInternal() { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { internal C() { } }"; - - var srcA2 = "partial class C { internal C() { } }"; - var srcB2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", "partial class C { internal C() { } }"), GetTopEdits("partial class C { internal C() { } }", "partial class C { }")], [ DocumentResults( semanticEdits: @@ -13955,15 +14036,9 @@ public void Constructor_Instance_Partial_DeleteInternalInsertInternal() [Fact] public void Constructor_Instance_Partial_InsertInternalDeleteInternal_WithBody() - { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { internal C() { } }"; - - var srcA2 = "partial class C { internal C() { Console.WriteLine(1); } }"; - var srcB2 = "partial class C { }"; - + { EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", "partial class C { internal C() { Console.WriteLine(1); } }"), GetTopEdits("partial class C { internal C() { } }", "partial class C { }")], [ DocumentResults( semanticEdits: @@ -13979,14 +14054,8 @@ public void Constructor_Instance_Partial_InsertInternalDeleteInternal_WithBody() [Fact] public void Constructor_Instance_Partial_InsertPublicDeletePrivate() { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { private C() { } }"; - - var srcA2 = "partial class C { public C() { } }"; - var srcB2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", "partial class C { public C() { } }"), GetTopEdits("partial class C { private C() { } }", "partial class C { }")], [ DocumentResults( diagnostics: [Diagnostic(RudeEditKind.ChangingAccessibility, "public C()", FeaturesResources.constructor)]), @@ -13999,14 +14068,8 @@ public void Constructor_Instance_Partial_InsertPublicDeletePrivate() [Fact] public void Constructor_Instance_Partial_InsertInternalDeletePrivate() { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { private C() { } }"; - - var srcA2 = "partial class C { internal C() { } }"; - var srcB2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", "partial class C { internal C() { } }"), GetTopEdits("partial class C { private C() { } }", "partial class C { }")], [ DocumentResults( diagnostics: [Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor)]), @@ -14018,46 +14081,50 @@ public void Constructor_Instance_Partial_InsertInternalDeletePrivate() [Fact] public void Constructor_Instance_Partial_Update_LambdaInInitializer1() { - var src1 = @" -using System; + var src1 = """ -partial class C -{ - static int F(Func x) => 1; + using System; - int A = F(a => a + 1); -} + partial class C + { + static int F(Func x) => 1; -partial class C -{ - int B { get; } = F(b => b + 1); + int A = F(a => a + 1); + } - public C() - { - F(c => c + 1); - } -} -"; - var src2 = @" -using System; + partial class C + { + int B { get; } = F(b => b + 1); -partial class C -{ - static int F(Func x) => 1; + public C() + { + F(c => c + 1); + } + } - int A = F(a => a + 1); -} + """; + var src2 = """ -partial class C -{ - int B { get; } = F(b => b + 1); + using System; - public C() - { - F(c => c + 2); - } -} -"; + partial class C + { + static int F(Func x) => 1; + + int A = F(a => a + 1); + } + + partial class C + { + int B { get; } = F(b => b + 1); + + public C() + { + F(c => c + 2); + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -14069,40 +14136,44 @@ partial class C [Fact] public void Constructor_Instance_Partial_Update_LambdaInInitializer_Trivia1() { - var src1 = @" -using System; + var src1 = """ -partial class C -{ - static int F(Func x) => 1; + using System; - int A = F(a => a + 1); -} + partial class C + { + static int F(Func x) => 1; -partial class C -{ - int B { get; } = F(b => b + 1); + int A = F(a => a + 1); + } - public C() { F(c => c + 1); } -} -"; - var src2 = @" -using System; + partial class C + { + int B { get; } = F(b => b + 1); -partial class C -{ - static int F(Func x) => 1; + public C() { F(c => c + 1); } + } - int A = F(a => a + 1); -} + """; + var src2 = """ -partial class C -{ - int B { get; } = F(b => b + 1); + using System; - /*new trivia*/public C() { F(c => c + 1); } -} -"; + partial class C + { + static int F(Func x) => 1; + + int A = F(a => a + 1); + } + + partial class C + { + int B { get; } = F(b => b + 1); + + /*new trivia*/public C() { F(c => c + 1); } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -14114,54 +14185,58 @@ partial class C [Fact] public void Constructor_Instance_Partial_Update_LambdaInInitializer_ExplicitInterfaceImpl1() { - var src1 = @" -using System; + var src1 = """ -public interface I { int B { get; } } -public interface J { int B { get; } } + using System; -partial class C -{ - static int F(Func x) => 1; + public interface I { int B { get; } } + public interface J { int B { get; } } - int A = F(a => a + 1); -} + partial class C + { + static int F(Func x) => 1; -partial class C : I, J -{ - int I.B { get; } = F(ib => ib + 1); - int J.B { get; } = F(jb => jb + 1); + int A = F(a => a + 1); + } - public C() - { - F(c => c + 1); - } -} -"; - var src2 = @" -using System; + partial class C : I, J + { + int I.B { get; } = F(ib => ib + 1); + int J.B { get; } = F(jb => jb + 1); -public interface I { int B { get; } } -public interface J { int B { get; } } + public C() + { + F(c => c + 1); + } + } -partial class C -{ - static int F(Func x) => 1; + """; + var src2 = """ - int A = F(a => a + 1); -} + using System; -partial class C : I, J -{ - int I.B { get; } = F(ib => ib + 1); - int J.B { get; } = F(jb => jb + 1); + public interface I { int B { get; } } + public interface J { int B { get; } } - public C() - { - F(c => c + 2); - } -} -"; + partial class C + { + static int F(Func x) => 1; + + int A = F(a => a + 1); + } + + partial class C : I, J + { + int I.B { get; } = F(ib => ib + 1); + int J.B { get; } = F(jb => jb + 1); + + public C() + { + F(c => c + 2); + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -14173,41 +14248,45 @@ public C() [Fact] public void Constructor_Instance_Partial_Insert_Parameterless_LambdaInInitializer1() { - var src1 = @" -using System; + var src1 = """ -partial class C -{ - static int F(Func x) => 1; + using System; - int A = F(a => a + 1); -} + partial class C + { + static int F(Func x) => 1; -partial class C -{ - int B { get; } = F(b => b + 1); -} -"; - var src2 = @" -using System; + int A = F(a => a + 1); + } -partial class C -{ - static int F(Func x) => 1; + partial class C + { + int B { get; } = F(b => b + 1); + } - int A = F(a => a + 1); -} + """; + var src2 = """ -partial class C -{ - int B { get; } = F(b => b + 1); + using System; - public C() // new ctor - { - F(c => c + 1); - } -} -"; + partial class C + { + static int F(Func x) => 1; + + int A = F(a => a + 1); + } + + partial class C + { + int B { get; } = F(b => b + 1); + + public C() // new ctor + { + F(c => c + 1); + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -14224,41 +14303,45 @@ partial class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2504")] public void Constructor_Instance_Partial_Insert_WithParameters_LambdaInInitializer1() { - var src1 = @" -using System; + var src1 = """ -partial class C -{ - static int F(Func x) => 1; + using System; - int A = F(a => a + 1); -} + partial class C + { + static int F(Func x) => 1; -partial class C -{ - int B { get; } = F(b => b + 1); -} -"; - var src2 = @" -using System; + int A = F(a => a + 1); + } -partial class C -{ - static int F(Func x) => 1; + partial class C + { + int B { get; } = F(b => b + 1); + } - int A = F(a => a + 1); -} + """; + var src2 = """ -partial class C -{ - int B { get; } = F(b => b + 1); + using System; - public C(int x) // new ctor - { - F(c => c + 1); - } -} -"; + partial class C + { + static int F(Func x) => 1; + + int A = F(a => a + 1); + } + + partial class C + { + int B { get; } = F(b => b + 1); + + public C(int x) // new ctor + { + F(c => c + 1); + } + } + + """; var edits = GetTopEdits(src1, src2); _ = GetSyntaxMap(src1, src2); @@ -14274,50 +14357,55 @@ partial class C [Fact] public void Constructor_Instance_Partial_Explicit_Update() { - var srcA1 = @" -using System; + var srcB1 = """ -partial class C -{ - C(int arg) => Console.WriteLine(0); - C(bool arg) => Console.WriteLine(1); -} -"; - var srcB1 = @" -using System; + using System; -partial class C -{ - int a = 1; + partial class C + { + int a = 1; - C(uint arg) => Console.WriteLine(2); -} -"; + C(uint arg) => Console.WriteLine(2); + } - var srcA2 = @" -using System; + """; + var srcB2 = """ -partial class C -{ - C(int arg) => Console.WriteLine(0); - C(bool arg) => Console.WriteLine(1); -} -"; - var srcB2 = @" -using System; + using System; -partial class C -{ - int a = 2; // updated field initializer + partial class C + { + int a = 2; // updated field initializer - C(uint arg) => Console.WriteLine(2); - C(byte arg) => Console.WriteLine(3); // new ctor -} -"; + C(uint arg) => Console.WriteLine(2); + C(byte arg) => Console.WriteLine(3); // new ctor + } + + """; var syntaxMapB = GetSyntaxMap(srcB1, srcB2)[0]; EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(""" + + using System; + + partial class C + { + C(int arg) => Console.WriteLine(0); + C(bool arg) => Console.WriteLine(1); + } + + """, """ + + using System; + + partial class C + { + C(int arg) => Console.WriteLine(0); + C(bool arg) => Console.WriteLine(1); + } + + """), GetTopEdits(srcB1, srcB2)], [ // No changes in document A DocumentResults(), @@ -14337,46 +14425,48 @@ partial class C [Fact] public void Constructor_Instance_Partial_Explicit_Update_SemanticError() { - var srcA1 = @" -using System; + EditAndContinueValidation.VerifySemantics( + [GetTopEdits(""" -partial class C -{ - C(int arg) => Console.WriteLine(0); - C(int arg) => Console.WriteLine(1); -} -"; - var srcB1 = @" -using System; + using System; -partial class C -{ - int a = 1; -} -"; + partial class C + { + C(int arg) => Console.WriteLine(0); + C(int arg) => Console.WriteLine(1); + } - var srcA2 = @" -using System; + """, """ -partial class C -{ - C(int arg) => Console.WriteLine(0); - C(int arg) => Console.WriteLine(1); -} -"; - var srcB2 = @" -using System; + using System; -partial class C -{ - int a = 2; + partial class C + { + C(int arg) => Console.WriteLine(0); + C(int arg) => Console.WriteLine(1); + } - C(int arg) => Console.WriteLine(2); -} -"; + """), GetTopEdits(""" - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + using System; + + partial class C + { + int a = 1; + } + + """, """ + + using System; + + partial class C + { + int a = 2; + + C(int arg) => Console.WriteLine(2); + } + + """)], [ // No changes in document A DocumentResults(), @@ -14390,14 +14480,8 @@ partial class C [Fact] public void Constructor_Instance_Partial_Implicit_Update() { - var srcA1 = "partial class C { int F = 1; }"; - var srcB1 = "partial class C { int G = 1; }"; - - var srcA2 = "partial class C { int F = 2; }"; - var srcB2 = "partial class C { int G = 2; }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { int F = 1; }", "partial class C { int F = 2; }"), GetTopEdits("partial class C { int G = 1; }", "partial class C { int G = 2; }")], [ DocumentResults( semanticEdits: @@ -14415,14 +14499,8 @@ public void Constructor_Instance_Partial_Implicit_Update() [Fact] public void PartialDeclaration_Delete() { - var srcA1 = "partial class C { public C() { } void F() { } }"; - var srcB1 = "partial class C { int x = 1; }"; - - var srcA2 = ""; - var srcB2 = "partial class C { int x = 2; void F() { } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { public C() { } void F() { } }", ""), GetTopEdits("partial class C { int x = 1; }", "partial class C { int x = 2; void F() { } }")], [ DocumentResults( semanticEdits: [SemanticEdit(SemanticEditKind.Update, c => c.GetParameterlessConstructor("C"), partialType: "C", preserveLocalVariables: true)]), @@ -14439,14 +14517,8 @@ public void PartialDeclaration_Delete() [Fact] public void PartialDeclaration_Insert() { - var srcA1 = ""; - var srcB1 = "partial class C { int x = 1; void F() { } }"; - - var srcA2 = "partial class C { public C() { } void F() { } }"; - var srcB2 = "partial class C { int x = 2; }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("", "partial class C { public C() { } void F() { } }"), GetTopEdits("partial class C { int x = 1; void F() { } }", "partial class C { int x = 2; }")], [ DocumentResults( semanticEdits: @@ -14463,14 +14535,11 @@ public void PartialDeclaration_Insert() [Fact] public void PartialDeclaration_Insert_Reloadable() { - var srcA1 = ""; var srcB1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { int x = 1; void F() { } }"; - - var srcA2 = "partial class C { public C() { } void F() { } }"; var srcB2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("", "partial class C { public C() { } void F() { } }"), GetTopEdits(srcB1, srcB2)], [ DocumentResults( semanticEdits: @@ -14540,14 +14609,8 @@ public void Constructor_Static_Insert() [Fact] public void Constructor_Static_Partial_DeleteInsert() { - var srcA1 = "partial class C { static C() { } }"; - var srcB1 = "partial class C { }"; - - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { static C() { } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { static C() { } }", "partial class C { }"), GetTopEdits("partial class C { }", "partial class C { static C() { } }")], [ // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), @@ -14563,14 +14626,8 @@ public void Constructor_Static_Partial_DeleteInsert() [Fact] public void Constructor_Static_Partial_InsertDelete() { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { static C() { } }"; - - var srcA2 = "partial class C { static C() { } }"; - var srcB2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", "partial class C { static C() { } }"), GetTopEdits("partial class C { static C() { } }", "partial class C { }")], [ DocumentResults( semanticEdits: @@ -14625,12 +14682,9 @@ public void DestructorDelete() { var src1 = @"class B { ~B() { } }"; var src2 = @"class B { }"; - - var expectedEdit1 = @"Delete [~B() { }]@10"; - var edits = GetTopEdits(src1, src2); - edits.VerifyEdits(expectedEdit1); + edits.VerifyEdits(@"Delete [~B() { }]@10"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class B", DeletedSymbolDisplay(CSharpFeaturesResources.destructor, "~B()"))); @@ -14657,18 +14711,22 @@ public void DestructorDelete_InsertConstructor() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17681")] public void Destructor_BlockBodyToExpressionBody() { - var src1 = @" -public class C -{ - ~C() { Console.WriteLine(0); } -} -"; - var src2 = @" -public class C -{ - ~C() => Console.WriteLine(0); -} -"; + var src1 = """ + + public class C + { + ~C() { Console.WriteLine(0); } + } + + """; + var src2 = """ + + public class C + { + ~C() => Console.WriteLine(0); + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [~C() { Console.WriteLine(0); }]@25 -> [~C() => Console.WriteLine(0);]@25"); @@ -14683,18 +14741,22 @@ public class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17681")] public void Destructor_ExpressionBodyToBlockBody() { - var src1 = @" -public class C -{ - ~C() => Console.WriteLine(0); -} -"; - var src2 = @" -public class C -{ - ~C() { Console.WriteLine(0); } -} -"; + var src1 = """ + + public class C + { + ~C() => Console.WriteLine(0); + } + + """; + var src2 = """ + + public class C + { + ~C() { Console.WriteLine(0); } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [~C() => Console.WriteLine(0);]@25 -> [~C() { Console.WriteLine(0); }]@25"); @@ -14772,14 +14834,8 @@ public void MemberInitializer_Update_Remove_Field() [Fact] public void MemberInitializer_Update_Remove_Partial_Field() { - var srcA1 = "partial class C { int F = 1; }"; - var srcB1 = "partial class C { }"; - - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { int F ; }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { int F = 1; }", "partial class C { }"), GetTopEdits("partial class C { }", "partial class C { int F ; }")], [ DocumentResults(), DocumentResults( @@ -14793,14 +14849,8 @@ public void MemberInitializer_Update_Remove_Partial_Field() [Fact] public void MemberInitializer_Update_Remove_Partial_Property() { - var srcA1 = "partial class C { int F { get; } = 1; }"; - var srcB1 = "partial class C { }"; - - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { int F { get; } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { int F { get; } = 1; }", "partial class C { }"), GetTopEdits("partial class C { }", "partial class C { int F { get; } }")], [ DocumentResults(), DocumentResults( @@ -14815,14 +14865,8 @@ public void MemberInitializer_Update_Remove_Partial_Property() [Fact] public void MemberInitializer_Update_DeleteInsert_Field() { - var srcA1 = "partial class C { int F = 1; }"; - var srcB1 = "partial class C { }"; - - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { int F = 2; }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { int F = 1; }", "partial class C { }"), GetTopEdits("partial class C { }", "partial class C { int F = 2; }")], [ DocumentResults(), DocumentResults( @@ -14836,14 +14880,8 @@ public void MemberInitializer_Update_DeleteInsert_Field() [Fact] public void MemberInitializer_Update_DeleteInsert_Property() { - var srcA1 = "partial class C { int F { get; } = 1; }"; - var srcB1 = "partial class C { }"; - - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { int F { get; } = 2; }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { int F { get; } = 1; }", "partial class C { }"), GetTopEdits("partial class C { }", "partial class C { int F { get; } = 2; }")], [ DocumentResults(), DocumentResults( @@ -14875,14 +14913,8 @@ public void MemberInitializer_PropertyUpdate2() [Fact] public void MemberInitializer_PropertyInsertDelete() { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { int a { get; } = 1; }"; - - var srcA2 = "partial class C { int a { get { return 1; } } }"; - var srcB2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", "partial class C { int a { get { return 1; } } }"), GetTopEdits("partial class C { int a { get; } = 1; }", "partial class C { }")], [ DocumentResults( semanticEdits: @@ -15814,28 +15846,32 @@ public void MemberInitializer_Update_Lambda(string accessor) [Fact] public void MemberInitializer_Update_Lambda_ImplicitCtor_EditInitializerWithLambda1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static int F(Func x) => 1; + using System; - int A = F(a => a + 1); - int B = F(b => b + 1); -} -"; - var src2 = @" -using System; + class C + { + static int F(Func x) => 1; -class C -{ - static int F(Func x) => 1; + int A = F(a => a + 1); + int B = F(b => b + 1); + } - int A = F(a => a + 1); - int B = F(b => b + 2); -} -"; + """; + var src2 = """ + + using System; + + class C + { + static int F(Func x) => 1; + + int A = F(a => a + 1); + int B = F(b => b + 2); + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -15847,28 +15883,32 @@ class C [Fact] public void MemberInitializer_Update_Lambda_ImplicitCtor_EditInitializerWithoutLambda1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static int F(Func x) => 1; + using System; - int A = 1; - int B = F(b => b + 1); -} -"; - var src2 = @" -using System; + class C + { + static int F(Func x) => 1; -class C -{ - static int F(Func x) => 1; + int A = 1; + int B = F(b => b + 1); + } - int A = 2; - int B = F(b => b + 1); -} -"; + """; + var src2 = """ + + using System; + + class C + { + static int F(Func x) => 1; + + int A = 2; + int B = F(b => b + 1); + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -15880,32 +15920,36 @@ class C [Fact] public void MemberInitializer_Update_Lambda_CtorIncludingInitializers_EditInitializerWithLambda1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static int F(Func x) => 1; + using System; - int A = F(a => a + 1); - int B = F(b => b + 1); + class C + { + static int F(Func x) => 1; - public C() {} -} -"; - var src2 = @" -using System; + int A = F(a => a + 1); + int B = F(b => b + 1); -class C -{ - static int F(Func x) => 1; + public C() {} + } - int A = F(a => a + 1); - int B = F(b => b + 2); + """; + var src2 = """ - public C() {} -} -"; + using System; + + class C + { + static int F(Func x) => 1; + + int A = F(a => a + 1); + int B = F(b => b + 2); + + public C() {} + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -15917,32 +15961,36 @@ class C [Fact] public void MemberInitializer_Update_Lambda_CtorIncludingInitializers_EditInitializerWithoutLambda1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static int F(Func x) => 1; + using System; - int A = 1; - int B = F(b => b + 1); + class C + { + static int F(Func x) => 1; - public C() {} -} -"; - var src2 = @" -using System; + int A = 1; + int B = F(b => b + 1); -class C -{ - static int F(Func x) => 1; + public C() {} + } - int A = 2; - int B = F(b => b + 1); + """; + var src2 = """ - public C() {} -} -"; + using System; + + class C + { + static int F(Func x) => 1; + + int A = 2; + int B = F(b => b + 1); + + public C() {} + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -15954,34 +16002,38 @@ public C() {} [Fact] public void MemberInitializer_Update_Lambda_MultipleCtorsIncludingInitializers_EditInitializerWithLambda1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static int F(Func x) => 1; + using System; - int A = F(a => a + 1); - int B = F(b => b + 1); + class C + { + static int F(Func x) => 1; - public C(int a) {} - public C(bool b) {} -} -"; - var src2 = @" -using System; + int A = F(a => a + 1); + int B = F(b => b + 1); -class C -{ - static int F(Func x) => 1; + public C(int a) {} + public C(bool b) {} + } - int A = F(a => a + 1); - int B = F(b => b + 2); + """; + var src2 = """ - public C(int a) {} - public C(bool b) {} -} -"; + using System; + + class C + { + static int F(Func x) => 1; + + int A = F(a => a + 1); + int B = F(b => b + 2); + + public C(int a) {} + public C(bool b) {} + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -15996,34 +16048,38 @@ public C(bool b) {} [Fact] public void MemberInitializer_Update_Lambda_MultipleCtorsIncludingInitializersContainingLambdas_EditInitializerWithLambda1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static int F(Func x) => 1; + using System; - int A = F(a => a + 1); - int B = F(b => b + 1); + class C + { + static int F(Func x) => 1; - public C(int a) { F(c => c + 1); } - public C(bool b) { F(d => d + 1); } -} -"; - var src2 = @" -using System; + int A = F(a => a + 1); + int B = F(b => b + 1); -class C -{ - static int F(Func x) => 1; + public C(int a) { F(c => c + 1); } + public C(bool b) { F(d => d + 1); } + } - int A = F(a => a + 1); - int B = F(b => b + 2); + """; + var src2 = """ - public C(int a) { F(c => c + 1); } - public C(bool b) { F(d => d + 1); } -} -"; + using System; + + class C + { + static int F(Func x) => 1; + + int A = F(a => a + 1); + int B = F(b => b + 2); + + public C(int a) { F(c => c + 1); } + public C(bool b) { F(d => d + 1); } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -16038,34 +16094,38 @@ class C [Fact] public void MemberInitializer_Update_Lambda_MultipleCtorsIncludingInitializersContainingLambdas_EditInitializerWithLambda_Trivia1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static int F(Func x) => 1; + using System; - int A = F(a => a + 1); - int B = F(b => b + 1); + class C + { + static int F(Func x) => 1; - public C(int a) { F(c => c + 1); } - public C(bool b) { F(d => d + 1); } -} -"; - var src2 = @" -using System; + int A = F(a => a + 1); + int B = F(b => b + 1); -class C -{ - static int F(Func x) => 1; + public C(int a) { F(c => c + 1); } + public C(bool b) { F(d => d + 1); } + } - int A = F(a => a + 1); - int B = F(b => b + 1); + """; + var src2 = """ - public C(int a) { F(c => c + 1); } - public C(bool b) { F(d => d + 1); } -} -"; + using System; + + class C + { + static int F(Func x) => 1; + + int A = F(a => a + 1); + int B = F(b => b + 1); + + public C(int a) { F(c => c + 1); } + public C(bool b) { F(d => d + 1); } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -16077,37 +16137,41 @@ class C ]); } - [Fact] - public void MemberInitializer_Update_Lambda_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithLambda1() - { - var src1 = @" -using System; + [Fact] + public void MemberInitializer_Update_Lambda_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithLambda1() + { + var src1 = """ + + using System; + + class C + { + static int F(Func x) => 1; + + int A = F(a => a + 1); + int B = F(b => b + 1); -class C -{ - static int F(Func x) => 1; + public C(int a) { F(c => c + 1); } + public C(bool b) { F(d => d + 1); } + } - int A = F(a => a + 1); - int B = F(b => b + 1); + """; + var src2 = """ - public C(int a) { F(c => c + 1); } - public C(bool b) { F(d => d + 1); } -} -"; - var src2 = @" -using System; + using System; -class C -{ - static int F(Func x) => 1; + class C + { + static int F(Func x) => 1; - int A = F(a => a + 1); - int B = F(b => b + 1); + int A = F(a => a + 1); + int B = F(b => b + 1); - public C(int a) { F(c => c + 2); } - public C(bool b) { F(d => d + 1); } -} -"; + public C(int a) { F(c => c + 2); } + public C(bool b) { F(d => d + 1); } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -16121,34 +16185,38 @@ class C [Fact] public void MemberInitializer_Update_Lambda_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithLambda_Trivia1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static int F(Func x) => 1; + using System; - int A = F(a => a + 1); - int B = F(b => b + 1); + class C + { + static int F(Func x) => 1; - public C(int a) { F(c => c + 1); } - public C(bool b) { F(d => d + 1); } -} -"; - var src2 = @" -using System; + int A = F(a => a + 1); + int B = F(b => b + 1); -class C -{ - static int F(Func x) => 1; + public C(int a) { F(c => c + 1); } + public C(bool b) { F(d => d + 1); } + } - int A = F(a => a + 1); - int B = F(b => b + 1); + """; + var src2 = """ - public C(int a) { F(c => c + 1); } - public C(bool b) { F(d => d + 1); } -} -"; + using System; + + class C + { + static int F(Func x) => 1; + + int A = F(a => a + 1); + int B = F(b => b + 1); + + public C(int a) { F(c => c + 1); } + public C(bool b) { F(d => d + 1); } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -16162,34 +16230,38 @@ class C [Fact] public void MemberInitializer_Update_Lambda_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithoutLambda1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static int F(Func x) => 1; + using System; - int A = F(a => a + 1); - int B = F(b => b + 1); + class C + { + static int F(Func x) => 1; - public C(int a) { F(c => c + 1); } - public C(bool b) { Console.WriteLine(1); } -} -"; - var src2 = @" -using System; + int A = F(a => a + 1); + int B = F(b => b + 1); -class C -{ - static int F(Func x) => 1; + public C(int a) { F(c => c + 1); } + public C(bool b) { Console.WriteLine(1); } + } - int A = F(a => a + 1); - int B = F(b => b + 1); + """; + var src2 = """ - public C(int a) { F(c => c + 1); } - public C(bool b) { Console.WriteLine(2); } -} -"; + using System; + + class C + { + static int F(Func x) => 1; + + int A = F(a => a + 1); + int B = F(b => b + 1); + + public C(int a) { F(c => c + 1); } + public C(bool b) { Console.WriteLine(2); } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -16203,34 +16275,38 @@ class C [Fact] public void MemberInitializer_Update_Lambda_EditConstructorNotIncludingInitializers() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static int F(Func x) => 1; + using System; - int A = F(a => a + 1); - int B = F(b => b + 1); + class C + { + static int F(Func x) => 1; - public C(int a) { F(c => c + 1); } - public C(bool b) : this(1) { Console.WriteLine(1); } -} -"; - var src2 = @" -using System; + int A = F(a => a + 1); + int B = F(b => b + 1); -class C -{ - static int F(Func x) => 1; + public C(int a) { F(c => c + 1); } + public C(bool b) : this(1) { Console.WriteLine(1); } + } + + """; + var src2 = """ - int A = F(a => a + 1); - int B = F(b => b + 1); + using System; - public C(int a) { F(c => c + 1); } - public C(bool b) : this(1) { Console.WriteLine(2); } -} -"; + class C + { + static int F(Func x) => 1; + + int A = F(a => a + 1); + int B = F(b => b + 1); + + public C(int a) { F(c => c + 1); } + public C(bool b) : this(1) { Console.WriteLine(2); } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -16244,34 +16320,38 @@ class C [Fact] public void MemberInitializer_Update_Lambda_RemoveCtorInitializer1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static int F(Func x) => 1; + using System; - int A = F(a => a + 1); - int B = F(b => b + 1); + class C + { + static int F(Func x) => 1; - unsafe public C(int a) { char* buffer = stackalloc char[16]; F(c => c + 1); } - public C(bool b) : this(1) { Console.WriteLine(1); } -} -"; - var src2 = @" -using System; + int A = F(a => a + 1); + int B = F(b => b + 1); -class C -{ - static int F(Func x) => 1; + unsafe public C(int a) { char* buffer = stackalloc char[16]; F(c => c + 1); } + public C(bool b) : this(1) { Console.WriteLine(1); } + } - int A = F(a => a + 1); - int B = F(b => b + 1); + """; + var src2 = """ - unsafe public C(int a) { char* buffer = stackalloc char[16]; F(c => c + 1); } - public C(bool b) { Console.WriteLine(1); } -} -"; + using System; + + class C + { + static int F(Func x) => 1; + + int A = F(a => a + 1); + int B = F(b => b + 1); + + unsafe public C(int a) { char* buffer = stackalloc char[16]; F(c => c + 1); } + public C(bool b) { Console.WriteLine(1); } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -16285,34 +16365,38 @@ class C [Fact] public void MemberInitializer_Update_Lambda_AddCtorInitializer1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static int F(Func x) => 1; + using System; - int A = F(a => a + 1); - int B = F(b => b + 1); + class C + { + static int F(Func x) => 1; - public C(int a) { F(c => c + 1); } - public C(bool b) { Console.WriteLine(1); } -} -"; - var src2 = @" -using System; + int A = F(a => a + 1); + int B = F(b => b + 1); -class C -{ - static int F(Func x) => 1; + public C(int a) { F(c => c + 1); } + public C(bool b) { Console.WriteLine(1); } + } - int A = F(a => a + 1); - int B = F(b => b + 1); + """; + var src2 = """ - public C(int a) { F(c => c + 1); } - public C(bool b) : this(1) { Console.WriteLine(1); } -} -"; + using System; + + class C + { + static int F(Func x) => 1; + + int A = F(a => a + 1); + int B = F(b => b + 1); + + public C(int a) { F(c => c + 1); } + public C(bool b) : this(1) { Console.WriteLine(1); } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -16325,50 +16409,54 @@ class C [Fact] public void MemberInitializer_Update_Lambda_UpdateBaseCtorInitializerWithLambdas1() { - var src1 = @" -using System; + var src1 = """ -class B -{ - public B(int a) { } -} + using System; -class C : B -{ - static int F(Func x) => 1; + class B + { + public B(int a) { } + } - int A = F(a => a + 1); - int B = F(b => b + 1); + class C : B + { + static int F(Func x) => 1; - public C(bool b) - : base(F(c => c + 1)) - { - F(d => d + 1); - } -} -"; - var src2 = @" -using System; + int A = F(a => a + 1); + int B = F(b => b + 1); -class B -{ - public B(int a) { } -} + public C(bool b) + : base(F(c => c + 1)) + { + F(d => d + 1); + } + } -class C : B -{ - static int F(Func x) => 1; + """; + var src2 = """ - int A = F(a => a + 1); - int B = F(b => b + 1); + using System; - public C(bool b) - : base(F(c => c + 2)) - { - F(d => d + 1); - } -} -"; + class B + { + public B(int a) { } + } + + class C : B + { + static int F(Func x) => 1; + + int A = F(a => a + 1); + int B = F(b => b + 1); + + public C(bool b) + : base(F(c => c + 2)) + { + F(d => d + 1); + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -16398,16 +16486,18 @@ public C() {{initializer}} } } """; - var src2 = @" -using System; + var src2 = """ -class C : B -{ - static int F(Func x) => 1; + using System; - int A = F(a => a + 1); -} -"; + class C : B + { + static int F(Func x) => 1; + + int A = F(a => a + 1); + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -16432,16 +16522,18 @@ class C() : B{{initializer}} int A = F(a => a + 1); } """; - var src2 = @" -using System; + var src2 = """ -class C : B -{ - static int F(Func x) => 1; + using System; - int A = F(a => a + 1); -} -"; + class C : B + { + static int F(Func x) => 1; + + int A = F(a => a + 1); + } + + """; if (isInsert) { (src1, src2) = (src2, src1); @@ -16460,37 +16552,41 @@ class C : B [Fact] public void MemberInitializer_Update_Lambda_PartialDeclarationDelete_SingleDocument() { - var src1 = @" -partial class C -{ - int x = F(a => a + 1); -} + var src1 = """ -partial class C -{ - int y = F(a => a + 10); -} + partial class C + { + int x = F(a => a + 1); + } -partial class C -{ - public C() { } - static int F(Func x) => 1; -} -"; + partial class C + { + int y = F(a => a + 10); + } - var src2 = @" -partial class C -{ - int x = F(a => a + 1); -} + partial class C + { + public C() { } + static int F(Func x) => 1; + } -partial class C -{ - int y = F(a => a + 10); + """; - static int F(Func x) => 1; -} -"; + var src2 = """ + + partial class C + { + int x = F(a => a + 1); + } + + partial class C + { + int y = F(a => a + 10); + + static int F(Func x) => 1; + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -16522,30 +16618,34 @@ public void FieldInitializerUpdate_Lambdas_InsertPrimaryConstructorParameterUse( [Fact] public void MemberInitializer_Update_ActiveStatements1() { - var src1 = @" -using System; + var src1 = """ + + using System; + + class C + { + int A = 1; + int B = 1; + + public C(int a) { Console.WriteLine(1); } + public C(bool b) { Console.WriteLine(1); } + } + + """; + var src2 = """ -class C -{ - int A = 1; - int B = 1; + using System; - public C(int a) { Console.WriteLine(1); } - public C(bool b) { Console.WriteLine(1); } -} -"; - var src2 = @" -using System; + class C + { + int A = 1; + int B = 2; -class C -{ - int A = 1; - int B = 2; + public C(int a) { Console.WriteLine(1); } + public C(bool b) { Console.WriteLine(1); } + } - public C(int a) { Console.WriteLine(1); } - public C(bool b) { Console.WriteLine(1); } -} -"; + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); var activeStatements = GetActiveStatements(src1, src2); @@ -16561,30 +16661,34 @@ class C [Fact] public void MemberInitializer_Update_Partial_SemanticError() { - var src1 = @" -partial class C -{ - partial int P => 1; -} + var src1 = """ -partial class C -{ - partial int P => 1; -} -"; - var src2 = @" -partial class C -{ - partial int P => 1; -} + partial class C + { + partial int P => 1; + } -partial class C -{ - partial int P => 2; + partial class C + { + partial int P => 1; + } - public C() { } -} -"; + """; + var src2 = """ + + partial class C + { + partial int P => 1; + } + + partial class C + { + partial int P => 2; + + public C() { } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -16616,13 +16720,9 @@ public void MemberInitializer_Rename_Property() public void MemberInitializer_Update_Reloadable_Partial() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { int x = 1; }"; - var srcB1 = "partial class C { int y = 1; }"; - var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { int x = 2; }"; - var srcB2 = "partial class C { int y = 2; }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(srcA1, srcA2), GetTopEdits("partial class C { int y = 1; }", "partial class C { int y = 2; }")], [ DocumentResults(semanticEdits: [ @@ -16733,14 +16833,8 @@ public void Field_Modifiers_RemoveModifier_Const() [Fact] public void Field_Modifier_Add_InsertDelete() { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { int F; }"; - - var srcA2 = "partial class C { static int F; }"; - var srcB2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", "partial class C { static int F; }"), GetTopEdits("partial class C { int F; }", "partial class C { }")], [ DocumentResults( diagnostics: @@ -16755,14 +16849,8 @@ public void Field_Modifier_Add_InsertDelete() [Fact] public void Field_Attribute_Add_InsertDelete() { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { int F; }"; - - var srcA2 = "partial class C { [System.Obsolete]int F; }"; - var srcB2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", "partial class C { [System.Obsolete]int F; }"), GetTopEdits("partial class C { int F; }", "partial class C { }")], [ DocumentResults( semanticEdits: @@ -17057,27 +17145,31 @@ public void Field_Insert() [Fact] public void Field_Insert_IntoStruct() { - var src1 = @" -struct S -{ - public int a; + var src1 = """ - public S(int z) { this = default(S); a = z; } -} -"; - var src2 = @" -struct S -{ - public int a; - - private int b; - private static int c; - private static int f = 1; - private event System.Action d; - - public S(int z) { this = default(S); a = z; } -} -"; + struct S + { + public int a; + + public S(int z) { this = default(S); a = z; } + } + + """; + var src2 = """ + + struct S + { + public int a; + + private int b; + private static int c; + private static int f = 1; + private event System.Action d; + + public S(int z) { this = default(S); a = z; } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -17090,27 +17182,31 @@ struct S [Fact] public void Field_Insert_IntoLayoutClass_Auto() { - var src1 = @" -using System.Runtime.InteropServices; + var src1 = """ -[StructLayoutAttribute(LayoutKind.Auto)] -class C -{ - private int a; -} -"; - var src2 = @" -using System.Runtime.InteropServices; - -[StructLayoutAttribute(LayoutKind.Auto)] -class C -{ - private int a; - private int b; - private int c; - private static int d; -} -"; + using System.Runtime.InteropServices; + + [StructLayoutAttribute(LayoutKind.Auto)] + class C + { + private int a; + } + + """; + var src2 = """ + + using System.Runtime.InteropServices; + + [StructLayoutAttribute(LayoutKind.Auto)] + class C + { + private int a; + private int b; + private int c; + private static int d; + } + + """; var edits = GetTopEdits(src1, src2); @@ -17126,34 +17222,38 @@ class C [Fact] public void Field_Insert_IntoLayoutClass_Explicit() { - var src1 = @" -using System.Runtime.InteropServices; + var src1 = """ -[StructLayoutAttribute(LayoutKind.Explicit)] -class C -{ - [FieldOffset(0)] - private int a; -} -"; - var src2 = @" -using System.Runtime.InteropServices; + using System.Runtime.InteropServices; + + [StructLayoutAttribute(LayoutKind.Explicit)] + class C + { + [FieldOffset(0)] + private int a; + } -[StructLayoutAttribute(LayoutKind.Explicit)] -class C -{ - [FieldOffset(0)] - private int a; + """; + var src2 = """ - [FieldOffset(0)] - private int b; + using System.Runtime.InteropServices; - [FieldOffset(4)] - private int c; + [StructLayoutAttribute(LayoutKind.Explicit)] + class C + { + [FieldOffset(0)] + private int a; - private static int d; -} -"; + [FieldOffset(0)] + private int b; + + [FieldOffset(4)] + private int c; + + private static int d; + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -17165,27 +17265,31 @@ class C [Fact] public void Field_Insert_IntoLayoutClass_Sequential() { - var src1 = @" -using System.Runtime.InteropServices; + var src1 = """ -[StructLayoutAttribute(LayoutKind.Sequential)] -class C -{ - private int a; -} -"; - var src2 = @" -using System.Runtime.InteropServices; - -[StructLayoutAttribute(LayoutKind.Sequential)] -class C -{ - private int a; - private int b; - private int c; - private static int d; -} -"; + using System.Runtime.InteropServices; + + [StructLayoutAttribute(LayoutKind.Sequential)] + class C + { + private int a; + } + + """; + var src2 = """ + + using System.Runtime.InteropServices; + + [StructLayoutAttribute(LayoutKind.Sequential)] + class C + { + private int a; + private int b; + private int c; + private static int d; + } + + """; var edits = GetTopEdits(src1, src2); @@ -17198,37 +17302,41 @@ class C [Fact] public void Field_Insert_WithInitializersAndLambdas1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static int F(Func x) => 1; + using System; - int A = F(a => a + 1); + class C + { + static int F(Func x) => 1; - public C() - { - F(c => c + 1); - } -} -"; - var src2 = @" -using System; + int A = F(a => a + 1); -class C -{ - static int F(Func x) => 1; + public C() + { + F(c => c + 1); + } + } - int A = F(a => a + 1); - int B = F(b => b + 1); // new field + """; + var src2 = """ - public C() - { - F(c => c + 1); - } -} -"; + using System; + + class C + { + static int F(Func x) => 1; + + int A = F(a => a + 1); + int B = F(b => b + 1); // new field + + public C() + { + F(c => c + 1); + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -17243,32 +17351,36 @@ public C() [Fact] public void Field_Insert_ConstructorReplacingImplicitConstructor_WithInitializersAndLambdas() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static int F(Func x) => 1; + using System; - int A = F(a => a + 1); -} -"; - var src2 = @" -using System; + class C + { + static int F(Func x) => 1; -class C -{ - static int F(Func x) => 1; + int A = F(a => a + 1); + } - int A = F(a => a + 1); - int B = F(b => b + 1); // new field + """; + var src2 = """ - public C() // new ctor replacing existing implicit constructor - { - F(c => c + 1); - } -} -"; + using System; + + class C + { + static int F(Func x) => 1; + + int A = F(a => a + 1); + int B = F(b => b + 1); // new field + + public C() // new ctor replacing existing implicit constructor + { + F(c => c + 1); + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -17294,35 +17406,39 @@ class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ParameterlessConstructorInsert_WithInitializersAndLambdas() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static int F(Func x) => 1; + using System; - int A = F(a => a + 1); + class C + { + static int F(Func x) => 1; - public C(int x) {} -} -"; - var src2 = @" -using System; + int A = F(a => a + 1); -class C -{ - static int F(Func x) => 1; + public C(int x) {} + } - int A = F(a => a + 1); + """; + var src2 = """ - public C(int x) {} + using System; - public C() // new ctor - { - F(c => c + 1); - } -} -"; + class C + { + static int F(Func x) => 1; + + int A = F(a => a + 1); + + public C(int x) {} + + public C() // new ctor + { + F(c => c + 1); + } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -17341,32 +17457,36 @@ public C(int x) {} [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ConstructorInsert_WithInitializersAndLambdas1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static int F(Func x) => 1; + using System; - int A = F(a => a + 1); -} -"; - var src2 = @" -using System; + class C + { + static int F(Func x) => 1; -class C -{ - static int F(Func x) => 1; + int A = F(a => a + 1); + } - int A = F(a => a + 1); - int B = F(b => b + 1); // new field + """; + var src2 = """ - public C(int x) // new ctor - { - F(c => c + 1); - } -} -"; + using System; + + class C + { + static int F(Func x) => 1; + + int A = F(a => a + 1); + int B = F(b => b + 1); // new field + + public C(int x) // new ctor + { + F(c => c + 1); + } + } + + """; var edits = GetTopEdits(src1, src2); _ = GetSyntaxMap(src1, src2); @@ -17386,32 +17506,36 @@ class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ConstructorInsert_WithInitializersButNoExistingLambdas1() { - var src1 = @" -using System; + var src1 = """ -class C -{ - static int F(Func x) => 1; + using System; - int A = F(null); -} -"; - var src2 = @" -using System; + class C + { + static int F(Func x) => 1; -class C -{ - static int F(Func x) => 1; + int A = F(null); + } - int A = F(null); - int B = F(b => b + 1); // new field + """; + var src2 = """ - public C(int x) // new ctor - { - F(c => c + 1); - } -} -"; + using System; + + class C + { + static int F(Func x) => 1; + + int A = F(null); + int B = F(b => b + 1); // new field + + public C(int x) // new ctor + { + F(c => c + 1); + } + } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -17453,16 +17577,20 @@ public void Field_Insert_Static_NotSupportedByRuntime() [Fact] public void Field_Attribute_Add_NotSupportedByRuntime() { - var src1 = @" -class C -{ - public int a = 1, x = 1; -}"; - var src2 = @" -class C -{ - [System.Obsolete]public int a = 1, x = 1; -}"; + var src1 = """ + + class C + { + public int a = 1, x = 1; + } + """; + var src2 = """ + + class C + { + [System.Obsolete]public int a = 1, x = 1; + } + """; var edits = GetTopEdits(src1, src2); @@ -17480,16 +17608,20 @@ class C [Fact] public void Field_Attribute_Add() { - var src1 = @" -class C -{ - public int a, b; -}"; - var src2 = @" -class C -{ - [System.Obsolete]public int a, b; -}"; + var src1 = """ + + class C + { + public int a, b; + } + """; + var src2 = """ + + class C + { + [System.Obsolete]public int a, b; + } + """; var edits = GetTopEdits(src1, src2); @@ -17505,16 +17637,20 @@ class C [Fact] public void Field_Attribute_Add_WithInitializer() { - var src1 = @" -class C -{ - int a; -}"; - var src2 = @" -class C -{ - [System.Obsolete]int a = 0; -}"; + var src1 = """ + + class C + { + int a; + } + """; + var src2 = """ + + class C + { + [System.Obsolete]int a = 0; + } + """; var edits = GetTopEdits(src1, src2); @@ -17530,14 +17666,8 @@ class C [Fact] public void Field_Attribute_DeleteInsertUpdate_WithInitializer() { - var srcA1 = "partial class C { int a = 1; }"; - var srcB1 = "partial class C { }"; - - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { [System.Obsolete]int a = 2; }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { int a = 1; }", "partial class C { }"), GetTopEdits("partial class C { }", "partial class C { [System.Obsolete]int a = 2; }")], [ DocumentResults(), DocumentResults( @@ -18715,24 +18845,28 @@ public void Property_Insert_Incomplete() [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] public void Property_Insert_PInvoke() { - var src1 = @" -using System; -using System.Runtime.InteropServices; + var src1 = """ -class C -{ -}"; - var src2 = @" -using System; -using System.Runtime.InteropServices; + using System; + using System.Runtime.InteropServices; -class C -{ - private static extern int P1 { [DllImport(""x.dll"")]get; } - private static extern int P2 { [DllImport(""x.dll"")]set; } - private static extern int P3 { [DllImport(""x.dll"")]get; [DllImport(""x.dll"")]set; } -} -"; + class C + { + } + """; + var src2 = """ + + using System; + using System.Runtime.InteropServices; + + class C + { + private static extern int P1 { [DllImport("x.dll")]get; } + private static extern int P2 { [DllImport("x.dll")]set; } + private static extern int P3 { [DllImport("x.dll")]get; [DllImport("x.dll")]set; } + } + + """; var edits = GetTopEdits(src1, src2); // CLR doesn't support methods without a body @@ -18781,29 +18915,33 @@ internal void Property_Insert_TypeLayout(string attribute, string type, RudeEdit [Fact] public void Property_Insert_IntoStruct_Static() { - var src1 = @" -struct S -{ - public int a; - - public S(int z) { a = z; } -} -"; - var src2 = @" -struct S -{ - public int a; - static int c { get; set; } - static int d { get => field; set; } - static int e { get { return 0; } set { } } - static int g { get; } = 1; - static int i { get; set; } = 1; - static int k => 1; - static int l { get => 1; set {} } - static int m { get => 1; set => k; } - public S(int z) { a = z; } -} -"; + var src1 = """ + + struct S + { + public int a; + + public S(int z) { a = z; } + } + + """; + var src2 = """ + + struct S + { + public int a; + static int c { get; set; } + static int d { get => field; set; } + static int e { get { return 0; } set { } } + static int g { get; } = 1; + static int i { get; set; } = 1; + static int k => 1; + static int l { get => 1; set {} } + static int m { get => 1; set => k; } + public S(int z) { a = z; } + } + + """; var edits = GetTopEdits(src1, src2); @@ -19400,14 +19538,8 @@ public void Property_ReadOnlyRef_Update() [Fact] public void Property_Partial_InsertDelete() { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { int P { get => 1; set { } } }"; - - var srcA2 = "partial class C { int P { get => 1; set { } } }"; - var srcB2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", "partial class C { int P { get => 1; set { } } }"), GetTopEdits("partial class C { int P { get => 1; set { } } }", "partial class C { }")], [ DocumentResults( semanticEdits: @@ -19423,14 +19555,8 @@ public void Property_Partial_InsertDelete() [Fact] public void PropertyInit_Partial_InsertDelete() { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { int Q { get => 1; init { } }}"; - - var srcA2 = "partial class C { int Q { get => 1; init { } }}"; - var srcB2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", "partial class C { int Q { get => 1; init { } }}"), GetTopEdits("partial class C { int Q { get => 1; init { } }}", "partial class C { }")], [ DocumentResults( semanticEdits: @@ -19446,16 +19572,11 @@ public void PropertyInit_Partial_InsertDelete() [Fact] public void Property_Auto_Partial_InsertDelete() { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { int P { get; set; } int Q { get; init; } }"; - - var srcA2 = "partial class C { int P { get; set; } int Q { get; init; } }"; - var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", "partial class C { int P { get; set; } int Q { get; init; } }"), GetTopEdits("partial class C { int P { get; set; } int Q { get; init; } }", "partial class C { }")], [ DocumentResults( semanticEdits: @@ -19472,16 +19593,11 @@ public void Property_Auto_Partial_InsertDelete() [Fact] public void Property_AutoWithInitializer_Partial_InsertDelete() { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { int P { get; set; } = 1; }"; - - var srcA2 = "partial class C { int P { get; set; } = 1; }"; - var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", "partial class C { int P { get; set; } = 1; }"), GetTopEdits("partial class C { int P { get; set; } = 1; }", "partial class C { }")], [ DocumentResults( semanticEdits: @@ -19498,14 +19614,8 @@ public void Property_AutoWithInitializer_Partial_InsertDelete() [Fact] public void Property_WithExpressionBody_Partial_InsertDeleteUpdate() { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { int P => 1; }"; - - var srcA2 = "partial class C { int P => 2; }"; - var srcB2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", "partial class C { int P => 2; }"), GetTopEdits("partial class C { int P => 1; }", "partial class C { }")], [ DocumentResults( semanticEdits: [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C").GetMember("P").GetMethod)]), @@ -19517,16 +19627,20 @@ public void Property_WithExpressionBody_Partial_InsertDeleteUpdate() [Fact] public void Property_Auto_ReadOnly_Add() { - var src1 = @" -struct S -{ - int P { get; } -}"; - var src2 = @" -struct S -{ - readonly int P { get; } -}"; + var src1 = """ + + struct S + { + int P { get; } + } + """; + var src2 = """ + + struct S + { + readonly int P { get; } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } @@ -19534,22 +19648,26 @@ struct S [Fact] public void Property_InMutableStruct_ReadOnly_Add() { - var src1 = @" -struct S -{ - int P1 { get => 1; } - int P2 { get => 1; set {}} - int P3 { get => 1; set {}} - int P4 { get => 1; set {}} -}"; - var src2 = @" -struct S -{ - readonly int P1 { get => 1; } - int P2 { readonly get => 1; set {}} - int P3 { get => 1; readonly set {}} - readonly int P4 { get => 1; set {}} -}"; + var src1 = """ + + struct S + { + int P1 { get => 1; } + int P2 { get => 1; set {}} + int P3 { get => 1; set {}} + int P4 { get => 1; set {}} + } + """; + var src2 = """ + + struct S + { + readonly int P1 { get => 1; } + int P2 { readonly get => 1; set {}} + int P3 { get => 1; readonly set {}} + readonly int P4 { get => 1; set {}} + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( [ @@ -19567,22 +19685,26 @@ public void Property_InReadOnlyStruct_ReadOnly_Add() { // indent to align accessor bodies and avoid updates caused by sequence point location changes - var src1 = @" -readonly struct S -{ - int P1 { get => 1; } - int P2 { get => 1; set {}} - int P3 { get => 1; set {}} - int P4 { get => 1; set {}} -}"; - var src2 = @" -readonly struct S -{ - readonly int P1 { get => 1; } - int P2 { readonly get => 1; set {}} - int P3 { get => 1; readonly set {}} - readonly int P4 { get => 1; set {}} -}"; + var src1 = """ + + readonly struct S + { + int P1 { get => 1; } + int P2 { get => 1; set {}} + int P3 { get => 1; set {}} + int P4 { get => 1; set {}} + } + """; + var src2 = """ + + readonly struct S + { + readonly int P1 { get => 1; } + int P2 { readonly get => 1; set {}} + int P3 { get => 1; readonly set {}} + readonly int P4 { get => 1; set {}} + } + """; var edits = GetTopEdits(src1, src2); // updates only for accessors whose modifiers were explicitly updated @@ -19596,22 +19718,26 @@ readonly struct S [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69317")] public void Property_Rename_ShadowingPrimaryParameter() { - var src1 = @" -class C(int A, int B) -{ - public int B { get; init; } + var src1 = """ - public int F() => B; -} -"; - var src2 = @" -class C(int A, int B) -{ - public int D { get; init; } + class C(int A, int B) + { + public int B { get; init; } - public int F() => B; -} -"; + public int F() => B; + } + + """; + var src2 = """ + + class C(int A, int B) + { + public int D { get; init; } + + public int F() => B; + } + + """; var edits = GetTopEdits(src1, src2); // TODO: https://github.com/dotnet/roslyn/issues/69317 @@ -19633,22 +19759,26 @@ class C(int A, int B) [WorkItem("https://github.com/dotnet/roslyn/issues/69216")] public void Property_Rename_ShadowingPrimaryParameter_WithInitializer() { - var src1 = @" -class C(int A, int B) -{ - public int B { get; init; } = B; + var src1 = """ - public int F() => B; -} -"; - var src2 = @" -class C(int A, int B) -{ - public int D { get; init; } = B; + class C(int A, int B) + { + public int B { get; init; } = B; - public int F() => B; -} -"; + public int F() => B; + } + + """; + var src2 = """ + + class C(int A, int B) + { + public int D { get; init; } = B; + + public int F() => B; + } + + """; var edits = GetTopEdits(src1, src2); // TODO: https://github.com/dotnet/roslyn/issues/69317 @@ -19670,16 +19800,8 @@ class C(int A, int B) [Fact] public void Property_Partial_DeleteInsert_DefinitionPart() { - var srcA1 = "partial class C { partial int P { get; } }"; - var srcB1 = "partial class C { partial int P => 1; }"; - var srcC1 = "partial class C { }"; - - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { partial int P => 1; }"; - var srcC2 = "partial class C { partial int P { get; } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2)], + [GetTopEdits("partial class C { partial int P { get; } }", "partial class C { }"), GetTopEdits("partial class C { partial int P => 1; }", "partial class C { partial int P => 1; }"), GetTopEdits("partial class C { }", "partial class C { partial int P { get; } }")], [ DocumentResults(), DocumentResults(), @@ -19691,16 +19813,8 @@ public void Property_Partial_DeleteInsert_DefinitionPart() [Fact] public void Property_Partial_DeleteInsert_ImplementationPart() { - var srcA1 = "partial class C { partial int P { get; } }"; - var srcB1 = "partial class C { partial int P => 1; }"; - var srcC1 = "partial class C { }"; - - var srcA2 = "partial class C { partial int P { get; } }"; - var srcB2 = "partial class C { }"; - var srcC2 = "partial class C { partial int P => 1; }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2)], + [GetTopEdits("partial class C { partial int P { get; } }", "partial class C { partial int P { get; } }"), GetTopEdits("partial class C { partial int P => 1; }", "partial class C { }"), GetTopEdits("partial class C { }", "partial class C { partial int P => 1; }")], [ DocumentResults(), DocumentResults(), @@ -19712,14 +19826,8 @@ public void Property_Partial_DeleteInsert_ImplementationPart() [Fact] public void Property_Partial_Swap_ImplementationAndDefinitionParts() { - var srcA1 = "partial class C { partial int P { get; } }"; - var srcB1 = "partial class C { partial int P => 1; }"; - - var srcA2 = "partial class C { partial int P => 1; }"; - var srcB2 = "partial class C { partial int P { get; } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { partial int P { get; } }", "partial class C { partial int P => 1; }"), GetTopEdits("partial class C { partial int P => 1; }", "partial class C { partial int P { get; } }")], [ DocumentResults( semanticEdits: [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P").PartialImplementationPart, partialType: "C")]), @@ -19730,14 +19838,8 @@ public void Property_Partial_Swap_ImplementationAndDefinitionParts() [Fact] public void Property_Partial_DeleteBoth() { - var srcA1 = "partial class C { partial int P { get; } }"; - var srcB1 = "partial class C { partial int P => 1; }"; - - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { partial int P { get; } }", "partial class C { }"), GetTopEdits("partial class C { partial int P => 1; }", "partial class C { }")], [ DocumentResults(), DocumentResults( @@ -19752,18 +19854,8 @@ public void Property_Partial_DeleteBoth() [Fact] public void Property_Partial_DeleteInsertBoth() { - var srcA1 = "partial class C { partial int P { get; } }"; - var srcB1 = "partial class C { partial int P => 1; }"; - var srcC1 = "partial class C { }"; - var srcD1 = "partial class C { }"; - - var srcA2 = "partial class C { }"; - var srcB2 = "partial class C { }"; - var srcC2 = "partial class C { partial int P { get; } }"; - var srcD2 = "partial class C { partial int P => 1; }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2)], + [GetTopEdits("partial class C { partial int P { get; } }", "partial class C { }"), GetTopEdits("partial class C { partial int P => 1; }", "partial class C { }"), GetTopEdits("partial class C { }", "partial class C { partial int P { get; } }"), GetTopEdits("partial class C { }", "partial class C { partial int P => 1; }")], [ DocumentResults(), DocumentResults(), @@ -19777,14 +19869,8 @@ public void Property_Partial_DeleteInsertBoth() [Fact] public void Property_Partial_Insert() { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { }"; - - var srcA2 = "partial class C { partial int P { get; } }"; - var srcB2 = "partial class C { partial int P => 1; }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", "partial class C { partial int P { get; } }"), GetTopEdits("partial class C { }", "partial class C { partial int P => 1; }")], [ DocumentResults(), DocumentResults( @@ -19797,13 +19883,9 @@ public void Property_Partial_Insert() public void Property_Partial_Insert_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { }"; - var srcB1 = "partial class C { }"; - var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { partial int P { get; } }"; - var srcB2 = "partial class C { partial int P { get => 1; } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(srcA1, srcA2), GetTopEdits("partial class C { }", "partial class C { partial int P { get => 1; } }")], [ DocumentResults( semanticEdits: [SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C")]), @@ -19822,14 +19904,10 @@ public class A : System.Attribute { public A(int x) {} } var srcA1 = attribute + "partial class C { [A(1)]partial int P { get; } }"; - var srcB1 = "partial class C { partial int P => 1; }"; - var srcA2 = attribute + "partial class C { [A(2)]partial int P { get; } }"; - var srcB2 = "partial class C { partial int P => 1; }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(srcA1, srcA2), GetTopEdits("partial class C { partial int P => 1; }", "partial class C { partial int P => 1; }")], [ DocumentResults( semanticEdits: [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.P").PartialImplementationPart, partialType: "C")]), @@ -19847,14 +19925,10 @@ public class A : System.Attribute { public A(int x) {} } var srcA1 = attribute + "partial class C { partial int P { get; } }"; - var srcB1 = "partial class C { [A(1)]partial int P => 1; }"; - var srcA2 = attribute + "partial class C { partial int P { get; } }"; - var srcB2 = "partial class C { [A(2)]partial int P => 1; }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(srcA1, srcA2), GetTopEdits("partial class C { [A(1)]partial int P => 1; }", "partial class C { [A(2)]partial int P => 1; }")], [ DocumentResults(), DocumentResults( @@ -19879,14 +19953,10 @@ public class A : System.Attribute { public A(int x) {} } var srcA1 = attribute + "partial class C { [A(1)]partial int P { get; } }"; - var srcB1 = "partial class C { [A(1)]partial int P => 1; }"; - var srcA2 = attribute + "partial class C { [A(2)]partial int P { get; } }"; - var srcB2 = "partial class C { [A(2)]partial int P => 1; }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(srcA1, srcA2), GetTopEdits("partial class C { [A(1)]partial int P => 1; }", "partial class C { [A(2)]partial int P => 1; }")], [ DocumentResults( semanticEdits: [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.P").PartialImplementationPart, partialType: "C")]), @@ -19909,14 +19979,10 @@ public class A : System.Attribute {} var srcA1 = attribute + "partial class C { [A]partial int P { get; } }"; - var srcB1 = "partial class C { partial int P => 1; }"; - var srcA2 = attribute + "partial class C { }"; - var srcB2 = "partial class C { partial int P => 1; partial int P { get; } }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(srcA1, srcA2), GetTopEdits("partial class C { partial int P => 1; }", "partial class C { partial int P => 1; partial int P { get; } }")], [ DocumentResults(), @@ -20718,22 +20784,26 @@ public void Indexer_Parameter_Delete() [Fact] public void Indexer_Parameter_Reorder_Stackalloc() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int this[int a, byte b] { get { return stackalloc int[1].Length; } } -} -"; - var src2 = @" -using System; + using System; -class C -{ - int this[byte b, int a] { get { return stackalloc int[1].Length; } } -} -"; + class C + { + int this[int a, byte b] { get { return stackalloc int[1].Length; } } + } + + """; + var src2 = """ + + using System; + + class C + { + int this[byte b, int a] { get { return stackalloc int[1].Length; } } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -20744,22 +20814,26 @@ class C [Fact] public void Indexer_Parameter_Reorder_Stackalloc_WithGetter_WithExpressionBody() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int this[int a, byte b] { get => stackalloc int[1].Length; } -} -"; - var src2 = @" -using System; + using System; + + class C + { + int this[int a, byte b] { get => stackalloc int[1].Length; } + } + + """; + var src2 = """ + + using System; + + class C + { + int this[byte b, int a] { get => stackalloc int[1].Length; } + } -class C -{ - int this[byte b, int a] { get => stackalloc int[1].Length; } -} -"; + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -20770,22 +20844,26 @@ class C [Fact] public void Indexer_Parameter_Reorder_Stackalloc_WithExpressionBody() { - var src1 = @" -using System; + var src1 = """ -class C -{ - int this[int a, byte b] => stackalloc int[1].Length; -} -"; - var src2 = @" -using System; + using System; -class C -{ - int this[byte b, int a] => stackalloc int[1].Length; -} -"; + class C + { + int this[int a, byte b] => stackalloc int[1].Length; + } + + """; + var src2 = """ + + using System; + + class C + { + int this[byte b, int a] => stackalloc int[1].Length; + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( @@ -20796,16 +20874,20 @@ class C [Fact] public void Indexer_AddSetAccessor() { - var src1 = @" -class C -{ - public int this[int i] { get { return default; } } -}"; - var src2 = @" -class C -{ - public int this[int i] { get { return default; } set { } } -}"; + var src1 = """ + + class C + { + public int this[int i] { get { return default; } } + } + """; + var src2 = """ + + class C + { + public int this[int i] { get { return default; } set { } } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { }]@67"); @@ -20818,19 +20900,23 @@ class C [Fact] public void Indexer_Delete() { - var src1 = @" -class C -{ - public T this[int i] - { - get { return arr[i]; } - set { arr[i] = value; } - } -}"; - var src2 = @" -class C -{ -}"; + var src1 = """ + + class C + { + public T this[int i] + { + get { return arr[i]; } + set { arr[i] = value; } + } + } + """; + var src2 = """ + + class C + { + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -20845,23 +20931,27 @@ class C [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750109")] public void Indexer_DeleteGetAccessor() { - var src1 = @" -class C -{ - public T this[int i] - { - get { return arr[i]; } - set { arr[i] = value; } - } -}"; - var src2 = @" -class C -{ - public T this[int i] - { - set { arr[i] = value; } - } -}"; + var src1 = """ + + class C + { + public T this[int i] + { + get { return arr[i]; } + set { arr[i] = value; } + } + } + """; + var src2 = """ + + class C + { + public T this[int i] + { + set { arr[i] = value; } + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -20874,16 +20964,20 @@ public T this[int i] [Fact] public void Indexer_DeleteSetAccessor() { - var src1 = @" -class C -{ - public int this[int i] { get { return 0; } set { } } -}"; - var src2 = @" -class C -{ - public int this[int i] { get { return 0; } } -}"; + var src1 = """ + + class C + { + public int this[int i] { get { return 0; } set { } } + } + """; + var src2 = """ + + class C + { + public int this[int i] { get { return 0; } } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( @@ -20989,14 +21083,8 @@ public void Indexer_ReadOnlyRef_ReturnType_Update() [Fact] public void Indexer_Partial_InsertDelete() { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { int this[int x] { get => 1; set { } } }"; - - var srcA2 = "partial class C { int this[int x] { get => 1; set { } } }"; - var srcB2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", "partial class C { int this[int x] { get => 1; set { } } }"), GetTopEdits("partial class C { int this[int x] { get => 1; set { } } }", "partial class C { }")], [ DocumentResults( semanticEdits: @@ -21013,14 +21101,8 @@ public void Indexer_Partial_InsertDelete() [Fact] public void IndexerInit_Partial_InsertDelete() { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { int this[int x] { get => 1; init { } }}"; - - var srcA2 = "partial class C { int this[int x] { get => 1; init { } }}"; - var srcB2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", "partial class C { int this[int x] { get => 1; init { } }}"), GetTopEdits("partial class C { int this[int x] { get => 1; init { } }}", "partial class C { }")], [ DocumentResults( semanticEdits: @@ -21037,16 +21119,11 @@ public void IndexerInit_Partial_InsertDelete() [Fact] public void AutoIndexer_Partial_InsertDelete() { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { int this[int x] { get; set; } }"; - - var srcA2 = "partial class C { int this[int x] { get; set; } }"; - var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", "partial class C { int this[int x] { get; set; } }"), GetTopEdits("partial class C { int this[int x] { get; set; } }", "partial class C { }")], [ DocumentResults( semanticEdits: @@ -21062,16 +21139,20 @@ public void AutoIndexer_Partial_InsertDelete() [Fact] public void AutoIndexer_ReadOnly_Add() { - var src1 = @" -struct S -{ - int this[int x] { get; } -}"; - var src2 = @" -struct S -{ - readonly int this[int x] { get; } -}"; + var src1 = """ + + struct S + { + int this[int x] { get; } + } + """; + var src2 = """ + + struct S + { + readonly int this[int x] { get; } + } + """; var edits = GetTopEdits(src1, src2); // Compiler generated attribute changed, we do not require runtime capability for custom attribute changes. @@ -21086,22 +21167,26 @@ struct S [Fact] public void Indexer_InMutableStruct_ReadOnly_Add() { - var src1 = @" -struct S -{ - int this[int x] { get => 1; } - int this[uint x] { get => 1; set {}} - int this[byte x] { get => 1; set {}} - int this[sbyte x] { get => 1; set {}} -}"; - var src2 = @" -struct S -{ - readonly int this[int x] { get => 1; } - int this[uint x] { readonly get => 1; set {}} - int this[byte x] { get => 1; readonly set {}} - readonly int this[sbyte x] { get => 1; set {}} -}"; + var src1 = """ + + struct S + { + int this[int x] { get => 1; } + int this[uint x] { get => 1; set {}} + int this[byte x] { get => 1; set {}} + int this[sbyte x] { get => 1; set {}} + } + """; + var src2 = """ + + struct S + { + readonly int this[int x] { get => 1; } + int this[uint x] { readonly get => 1; set {}} + int this[byte x] { get => 1; readonly set {}} + readonly int this[sbyte x] { get => 1; set {}} + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMembers("S.this[]").Single(m => m.Parameters is [{ Type.SpecialType: SpecialType.System_Int32 }])), @@ -21117,22 +21202,26 @@ struct S [Fact] public void Indexer_InReadOnlyStruct_ReadOnly_Add() { - var src1 = @" -readonly struct S -{ - int this[int x] { get => 1; } - int this[uint x] { get => 1; set {}} - int this[byte x] { get => 1; set {}} - int this[sbyte x] { get => 1; set {}} -}"; - var src2 = @" -readonly struct S -{ - readonly int this[int x] { get => 1; } - int this[uint x] { readonly get => 1; set {}} - int this[byte x] { get => 1; readonly set {}} - readonly int this[sbyte x] { get => 1; set {}} -}"; + var src1 = """ + + readonly struct S + { + int this[int x] { get => 1; } + int this[uint x] { get => 1; set {}} + int this[byte x] { get => 1; set {}} + int this[sbyte x] { get => 1; set {}} + } + """; + var src2 = """ + + readonly struct S + { + readonly int this[int x] { get => 1; } + int this[uint x] { readonly get => 1; set {}} + int this[byte x] { get => 1; readonly set {}} + readonly int this[sbyte x] { get => 1; set {}} + } + """; var edits = GetTopEdits(src1, src2); // Updates only for accessors whose modifiers were explicitly updated. @@ -21270,25 +21359,29 @@ public void EventField_Delete() [Fact] public void Event_Insert_TypeLayout() { - var src1 = @" -using System; -using System.Runtime.InteropServices; + var src1 = """ -[StructLayoutAttribute(LayoutKind.Sequential)] -class C -{ -} -"; - var src2 = @" -using System; -using System.Runtime.InteropServices; + using System; + using System.Runtime.InteropServices; -[StructLayoutAttribute(LayoutKind.Sequential)] -class C -{ - private event Action c { add { } remove { } } -} -"; + [StructLayoutAttribute(LayoutKind.Sequential)] + class C + { + } + + """; + var src2 = """ + + using System; + using System.Runtime.InteropServices; + + [StructLayoutAttribute(LayoutKind.Sequential)] + class C + { + private event Action c { add { } remove { } } + } + + """; var edits = GetTopEdits(src1, src2); @@ -21298,25 +21391,29 @@ private event Action c { add { } remove { } } [Fact] public void EventField_Insert_TypeLayout() { - var src1 = @" -using System; -using System.Runtime.InteropServices; + var src1 = """ -[StructLayoutAttribute(LayoutKind.Sequential)] -class C -{ -} -"; - var src2 = @" -using System; -using System.Runtime.InteropServices; + using System; + using System.Runtime.InteropServices; -[StructLayoutAttribute(LayoutKind.Sequential)] -class C -{ - private event Action c; -} -"; + [StructLayoutAttribute(LayoutKind.Sequential)] + class C + { + } + + """; + var src2 = """ + + using System; + using System.Runtime.InteropServices; + + [StructLayoutAttribute(LayoutKind.Sequential)] + class C + { + private event Action c; + } + + """; var edits = GetTopEdits(src1, src2); @@ -21328,20 +21425,24 @@ class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17681")] public void Event_ExpressionBodyToBlockBody() { - var src1 = @" -using System; -public class C -{ - event Action E { add => F(); remove => F(); } -} -"; - var src2 = @" -using System; -public class C -{ - event Action E { add { F(); } remove { } } -} -"; + var src1 = """ + + using System; + public class C + { + event Action E { add => F(); remove => F(); } + } + + """; + var src2 = """ + + using System; + public class C + { + event Action E { add { F(); } remove { } } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -21355,20 +21456,24 @@ public class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17681")] public void Event_BlockBodyToExpressionBody() { - var src1 = @" -using System; -public class C -{ - event Action E { add { F(); } remove { } } -} -"; - var src2 = @" -using System; -public class C -{ - event Action E { add => F(); remove => F(); } -} -"; + var src1 = """ + + using System; + public class C + { + event Action E { add { F(); } remove { } } + } + + """; + var src2 = """ + + using System; + public class C + { + event Action E { add => F(); remove => F(); } + } + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -21382,14 +21487,8 @@ public class C [Fact] public void Event_Partial_InsertDelete() { - var srcA1 = "partial class C { }"; - var srcB1 = "partial class C { event int E { add { } remove { } } }"; - - var srcA2 = "partial class C { event int E { add { } remove { } } }"; - var srcB2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { }", "partial class C { event int E { add { } remove { } } }"), GetTopEdits("partial class C { event int E { add { } remove { } } }", "partial class C { }")], [ DocumentResults( semanticEdits: @@ -21405,22 +21504,26 @@ public void Event_Partial_InsertDelete() [Fact] public void Event_InMutableStruct_ReadOnly_Add() { - var src1 = @" -struct S -{ - public event Action E - { - add {} remove {} - } -}"; - var src2 = @" -struct S -{ - public readonly event Action E - { - add {} remove {} - } -}"; + var src1 = """ + + struct S + { + public event Action E + { + add {} remove {} + } + } + """; + var src2 = """ + + struct S + { + public readonly event Action E + { + add {} remove {} + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("S.E")), @@ -21431,22 +21534,26 @@ public readonly event Action E [Fact] public void Event_InReadOnlyStruct_ReadOnly_Add1() { - var src1 = @" -readonly struct S -{ - public event Action E - { - add {} remove {} - } -}"; - var src2 = @" -readonly struct S -{ - public readonly event Action E - { - add {} remove {} - } -}"; + var src1 = """ + + readonly struct S + { + public event Action E + { + add {} remove {} + } + } + """; + var src2 = """ + + readonly struct S + { + public readonly event Action E + { + add {} remove {} + } + } + """; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); @@ -21455,16 +21562,20 @@ public readonly event Action E [Fact] public void EventField_Attribute_Add() { - var src1 = @" -class C -{ - event Action F; -}"; - var src2 = @" -class C -{ - [System.Obsolete]event Action F; -}"; + var src1 = """ + + class C + { + event Action F; + } + """; + var src2 = """ + + class C + { + [System.Obsolete]event Action F; + } + """; var edits = GetTopEdits(src1, src2); @@ -21485,16 +21596,20 @@ class C [Fact] public void Event_Attribute_Add_CustomAccessors() { - var src1 = @" -class C -{ - event Action F { add {} remove {} } -}"; - var src2 = @" -class C -{ - [System.Obsolete]event Action F { add {} remove {} } -}"; + var src1 = """ + + class C + { + event Action F { add {} remove {} } + } + """; + var src2 = """ + + class C + { + [System.Obsolete]event Action F { add {} remove {} } + } + """; var edits = GetTopEdits(src1, src2); @@ -21517,16 +21632,20 @@ [System.Obsolete]event Action F { add {} remove {} } [Fact] public void Event_Accessor_Attribute_Add() { - var src1 = @" -class C -{ - event Action F { add {} remove {} } -}"; - var src2 = @" -class C -{ - event Action F { add {} [System.Obsolete]remove {} } -}"; + var src1 = """ + + class C + { + event Action F { add {} remove {} } + } + """; + var src2 = """ + + class C + { + event Action F { add {} [System.Obsolete]remove {} } + } + """; var edits = GetTopEdits(src1, src2); @@ -21545,16 +21664,20 @@ event Action F { add {} [System.Obsolete]remove {} } [Fact] public void EventField_Attribute_Delete() { - var src1 = @" -class C -{ - [System.Obsolete]event Action F; -}"; - var src2 = @" -class C -{ - event Action F; -}"; + var src1 = """ + + class C + { + [System.Obsolete]event Action F; + } + """; + var src2 = """ + + class C + { + event Action F; + } + """; var edits = GetTopEdits(src1, src2); @@ -21573,16 +21696,20 @@ class C [Fact] public void Event_Attribute_Delete() { - var src1 = @" -class C -{ - [System.Obsolete]event Action F { add {} remove {} } -}"; - var src2 = @" -class C -{ - event Action F { add {} remove {} } -}"; + var src1 = """ + + class C + { + [System.Obsolete]event Action F { add {} remove {} } + } + """; + var src2 = """ + + class C + { + event Action F { add {} remove {} } + } + """; var edits = GetTopEdits(src1, src2); @@ -21605,16 +21732,20 @@ event Action F { add {} remove {} } [Fact] public void Event_Accessor_Attribute_Delete() { - var src1 = @" -class C -{ - event Action F { add {} [System.Obsolete]remove {} } -}"; - var src2 = @" -class C -{ - event Action F { add {} remove {} } -}"; + var src1 = """ + + class C + { + event Action F { add {} [System.Obsolete]remove {} } + } + """; + var src2 = """ + + class C + { + event Action F { add {} remove {} } + } + """; var edits = GetTopEdits(src1, src2); @@ -21893,14 +22024,8 @@ class C [Fact] public void EventField_Partial_InsertDelete() { - var srcA1 = "partial class C { static void F() {} }"; - var srcB1 = "partial class C { event System.Action E = F; }"; - - var srcA2 = "partial class C { static void F() {} event System.Action E = F; }"; - var srcB2 = "partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits("partial class C { static void F() {} }", "partial class C { static void F() {} event System.Action E = F; }"), GetTopEdits("partial class C { event System.Action E = F; }", "partial class C { }")], [ DocumentResults( semanticEdits: @@ -22275,14 +22400,18 @@ public void Parameter_Update_Type_RuntimeTypeUnchanged(string oldType, string ne [Fact] public void Parameter_Update_Type_Nullable() { - var src1 = @" -#nullable enable -class C { static void M(string a) { } } -"; - var src2 = @" -#nullable disable -class C { static void M(string a) { } } -"; + var src1 = """ + + #nullable enable + class C { static void M(string a) { } } + + """; + var src2 = """ + + #nullable disable + class C { static void M(string a) { } } + + """; var edits = GetTopEdits(src1, src2); @@ -22338,14 +22467,8 @@ public void Parameter_Initializer_NaN() [Fact] public void Parameter_Initializer_InsertDeleteUpdate() { - var srcA1 = @"partial class C { }"; - var srcB1 = @"partial class C { public static void F(int x = 1) {} }"; - - var srcA2 = @"partial class C { public static void F(int x = 2) {} }"; - var srcB2 = @"partial class C { }"; - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(@"partial class C { }", @"partial class C { public static void F(int x = 2) {} }"), GetTopEdits(@"partial class C { public static void F(int x = 1) {} }", @"partial class C { }")], [ DocumentResults( diagnostics: @@ -22995,19 +23118,17 @@ public void TypeTypeParameterAttributeUpdate() [Fact] public void TypeTypeParameter_Partial_Attribute_AddMultiple() { - var attributes = @" -class A : System.Attribute {} -class B : System.Attribute {} -"; + var attributes = """ - var srcA1 = "partial class C { }" + attributes; - var srcB1 = "partial class C { }"; + class A : System.Attribute {} + class B : System.Attribute {} - var srcA2 = "partial class C<[A]T> { }" + attributes; - var srcB2 = "partial class C<[B]T> { }"; + """; + var srcA1 = "partial class C { }" + attributes; + var srcA2 = "partial class C<[A]T> { }" + attributes; EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(srcA1, srcA2), GetTopEdits("partial class C { }", "partial class C<[B]T> { }")], [ DocumentResults(diagnostics: [ @@ -23024,19 +23145,17 @@ class B : System.Attribute {} [Fact] public void TypeTypeParameter_Partial_Attribute_AddMultiple_Reloadable() { - var attributes = @" -class A : System.Attribute {} -class B : System.Attribute {} -"; + var attributes = """ - var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { }" + attributes; - var srcB1 = "partial class C { }"; + class A : System.Attribute {} + class B : System.Attribute {} - var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C<[A]T> { }" + attributes; - var srcB2 = "partial class C<[B]T> { }"; + """; + var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { }" + attributes; + var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C<[A]T> { }" + attributes; EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + [GetTopEdits(srcA1, srcA2), GetTopEdits("partial class C { }", "partial class C<[B]T> { }")], [ DocumentResults(semanticEdits: [ @@ -23216,40 +23335,50 @@ public void TypeConstraint_MultipleClauses_UpdateAndReorder() [Fact] public void TopLevelStatements_Update() { - var src1 = @" -using System; + var src1 = """ -Console.WriteLine(""Hello""); -"; - var src2 = @" -using System; + using System; -Console.WriteLine(""Hello World""); -"; + Console.WriteLine("Hello"); + + """; + var src2 = """ + + using System; + + Console.WriteLine("Hello World"); + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Console.WriteLine(\"Hello\");]@19 -> [Console.WriteLine(\"Hello World\");]@19"); edits.VerifySemantics( [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.
$"))], - [Diagnostic(RudeEditKind.UpdateMightNotHaveAnyEffect, @"""Hello World""", GetResource("top-level code"))]); + [Diagnostic(RudeEditKind.UpdateMightNotHaveAnyEffect, """ + "Hello World" + """, GetResource("top-level code"))]); } [Fact] public void TopLevelStatements_InsertAndUpdate() { - var src1 = @" -using System; + var src1 = """ -Console.WriteLine(""Hello""); -"; - var src2 = @" -using System; + using System; + + Console.WriteLine("Hello"); + + """; + var src2 = """ -Console.WriteLine(""Hello World""); -Console.WriteLine(""What is your name?""); -var name = Console.ReadLine(); -"; + using System; + + Console.WriteLine("Hello World"); + Console.WriteLine("What is your name?"); + var name = Console.ReadLine(); + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @@ -23259,20 +23388,26 @@ public void TopLevelStatements_InsertAndUpdate() edits.VerifySemantics( [SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.
$"))], - [Diagnostic(RudeEditKind.UpdateMightNotHaveAnyEffect, @"""Hello World""", GetResource("top-level code"))]); + [Diagnostic(RudeEditKind.UpdateMightNotHaveAnyEffect, """ + "Hello World" + """, GetResource("top-level code"))]); } [Fact] public void TopLevelStatements_Insert_NoImplicitMain() { - var src1 = @" -using System; -"; - var src2 = @" -using System; + var src1 = """ + + using System; + + """; + var src2 = """ -Console.WriteLine(""Hello World""); -"; + using System; + + Console.WriteLine("Hello World"); + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Console.WriteLine(\"Hello World\");]@19"); @@ -23285,17 +23420,21 @@ public void TopLevelStatements_Insert_NoImplicitMain() [Fact] public void TopLevelStatements_Insert_ImplicitMain() { - var src1 = @" -using System; + var src1 = """ -Console.WriteLine(""Hello""); -"; - var src2 = @" -using System; + using System; + + Console.WriteLine("Hello"); + + """; + var src2 = """ -Console.WriteLine(""Hello""); -Console.WriteLine(""World""); -"; + using System; + + Console.WriteLine("Hello"); + Console.WriteLine("World"); + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Console.WriteLine(\"World\");]@48"); @@ -23308,15 +23447,19 @@ public void TopLevelStatements_Insert_ImplicitMain() [Fact] public void TopLevelStatements_Delete_NoImplicitMain() { - var src1 = @" -using System; + var src1 = """ -Console.WriteLine(""Hello World""); -"; - var src2 = @" -using System; + using System; -"; + Console.WriteLine("Hello World"); + + """; + var src2 = """ + + using System; + + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Console.WriteLine(\"Hello World\");]@19"); @@ -23328,17 +23471,21 @@ public void TopLevelStatements_Delete_NoImplicitMain() [Fact] public void TopLevelStatements_Delete_ImplicitMain() { - var src1 = @" -using System; + var src1 = """ -Console.WriteLine(""Hello""); -Console.WriteLine(""World""); -"; - var src2 = @" -using System; + using System; + + Console.WriteLine("Hello"); + Console.WriteLine("World"); + + """; + var src2 = """ -Console.WriteLine(""Hello""); -"; + using System; + + Console.WriteLine("Hello"); + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Console.WriteLine(\"World\");]@48"); @@ -23396,17 +23543,21 @@ public void TopLevelStatements_StackAllocInTopBlock() [Fact] public void TopLevelStatements_VoidToInt1() { - var src1 = @" -using System; + var src1 = """ -Console.Write(1); -"; - var src2 = @" -using System; + using System; -Console.Write(1); -return 1; -"; + Console.Write(1); + + """; + var src2 = """ + + using System; + + Console.Write(1); + return 1; + + """; var edits = GetTopEdits(src1, src2); @@ -23418,19 +23569,23 @@ public void TopLevelStatements_VoidToInt1() [Fact] public void TopLevelStatements_VoidToInt2() { - var src1 = @" -using System; + var src1 = """ -Console.Write(1); + using System; -return; -"; - var src2 = @" -using System; + Console.Write(1); + + return; + + """; + var src2 = """ -Console.Write(1); -return 1; -"; + using System; + + Console.Write(1); + return 1; + + """; var edits = GetTopEdits(src1, src2); @@ -23442,27 +23597,31 @@ public void TopLevelStatements_VoidToInt2() [Fact] public void TopLevelStatements_VoidToInt3() { - var src1 = @" -using System; + var src1 = """ -Console.Write(1); + using System; -int Goo() -{ - return 1; -} -"; - var src2 = @" -using System; + Console.Write(1); -Console.Write(1); -return 1; + int Goo() + { + return 1; + } -int Goo() -{ - return 1; -} -"; + """; + var src2 = """ + + using System; + + Console.Write(1); + return 1; + + int Goo() + { + return 1; + } + + """; var edits = GetTopEdits(src1, src2); @@ -23474,17 +23633,21 @@ int Goo() [Fact] public void TopLevelStatements_Await_Insert_First() { - var src1 = @" -using System.Threading.Tasks; + var src1 = """ + + using System.Threading.Tasks; + + return 1; + + """; + var src2 = """ -return 1; -"; - var src2 = @" -using System.Threading.Tasks; + using System.Threading.Tasks; -await Task.Delay(200); -return 1; -"; + await Task.Delay(200); + return 1; + + """; var edits = GetTopEdits(src1, src2); @@ -23498,17 +23661,21 @@ public void TopLevelStatements_Await_Insert_First() [Fact] public void TopLevelStatements_Await_Insert_Second() { - var src1 = @" -using System.Threading.Tasks; + var src1 = """ + + using System.Threading.Tasks; + + await Task.Delay(100); + + """; + var src2 = """ -await Task.Delay(100); -"; - var src2 = @" -using System.Threading.Tasks; + using System.Threading.Tasks; -await Task.Delay(100); -await Task.Delay(200); -"; + await Task.Delay(100); + await Task.Delay(200); + + """; var edits = GetTopEdits(src1, src2); @@ -23525,20 +23692,24 @@ public void TopLevelStatements_Await_Insert_Second() capabilities: EditAndContinueCapabilities.Baseline); } - [Fact] - public void TopLevelStatements_Await_Delete_Last() - { - var src1 = @" -using System.Threading.Tasks; + [Fact] + public void TopLevelStatements_Await_Delete_Last() + { + var src1 = """ + + using System.Threading.Tasks; + + await Task.Delay(100); + return 1; + + """; + var src2 = """ + + using System.Threading.Tasks; -await Task.Delay(100); -return 1; -"; - var src2 = @" -using System.Threading.Tasks; + return 1; -return 1; -"; + """; var edits = GetTopEdits(src1, src2); @@ -23554,17 +23725,21 @@ public void TopLevelStatements_Await_Delete_Last() [Fact] public void TopLevelStatements_Await_Delete_Second() { - var src1 = @" -using System.Threading.Tasks; + var src1 = """ + + using System.Threading.Tasks; -await Task.Delay(100); -await Task.Delay(200); -"; - var src2 = @" -using System.Threading.Tasks; + await Task.Delay(100); + await Task.Delay(200); -await Task.Delay(100); -"; + """; + var src2 = """ + + using System.Threading.Tasks; + + await Task.Delay(100); + + """; var edits = GetTopEdits(src1, src2); @@ -23584,19 +23759,23 @@ public void TopLevelStatements_Await_Delete_Second() [Fact] public void TopLevelStatements_VoidToTask() { - var src1 = @" -using System; -using System.Threading.Tasks; + var src1 = """ -Console.Write(1); -"; - var src2 = @" -using System; -using System.Threading.Tasks; + using System; + using System.Threading.Tasks; + + Console.Write(1); + + """; + var src2 = """ + + using System; + using System.Threading.Tasks; -await Task.Delay(100); -Console.Write(1); -"; + await Task.Delay(100); + Console.Write(1); + + """; var edits = GetTopEdits(src1, src2); @@ -23608,21 +23787,25 @@ public void TopLevelStatements_VoidToTask() [Fact] public void TopLevelStatements_TaskToTaskInt() { - var src1 = @" -using System; -using System.Threading.Tasks; + var src1 = """ -await Task.Delay(100); -Console.Write(1); -"; - var src2 = @" -using System; -using System.Threading.Tasks; + using System; + using System.Threading.Tasks; + + await Task.Delay(100); + Console.Write(1); + + """; + var src2 = """ + + using System; + using System.Threading.Tasks; -await Task.Delay(100); -Console.Write(1); -return 1; -"; + await Task.Delay(100); + Console.Write(1); + return 1; + + """; var edits = GetTopEdits(src1, src2); @@ -23634,24 +23817,28 @@ public void TopLevelStatements_TaskToTaskInt() [Fact] public void TopLevelStatements_VoidToTaskInt() { - var src1 = @" -using System; -using System.Threading.Tasks; + var src1 = """ -Console.Write(1); -"; - var src2 = @" -using System; -using System.Threading.Tasks; + using System; + using System.Threading.Tasks; -Console.Write(1); -return await GetInt(); + Console.Write(1); -Task GetInt() -{ - return Task.FromResult(1); -} -"; + """; + var src2 = """ + + using System; + using System.Threading.Tasks; + + Console.Write(1); + return await GetInt(); + + Task GetInt() + { + return Task.FromResult(1); + } + + """; var edits = GetTopEdits(src1, src2); @@ -23663,18 +23850,22 @@ Task GetInt() [Fact] public void TopLevelStatements_IntToVoid1() { - var src1 = @" -using System; + var src1 = """ -Console.Write(1); + using System; -return 1; -"; - var src2 = @" -using System; + Console.Write(1); + + return 1; + + """; + var src2 = """ + + using System; -Console.Write(1); -"; + Console.Write(1); + + """; var edits = GetTopEdits(src1, src2); @@ -23686,19 +23877,23 @@ public void TopLevelStatements_IntToVoid1() [Fact] public void TopLevelStatements_IntToVoid2() { - var src1 = @" -using System; + var src1 = """ -Console.Write(1); + using System; -return 1; -"; - var src2 = @" -using System; + Console.Write(1); + + return 1; + + """; + var src2 = """ + + using System; -Console.Write(1); -return; -"; + Console.Write(1); + return; + + """; var edits = GetTopEdits(src1, src2); @@ -23710,27 +23905,31 @@ public void TopLevelStatements_IntToVoid2() [Fact] public void TopLevelStatements_IntToVoid3() { - var src1 = @" -using System; + var src1 = """ -Console.Write(1); -return 1; + using System; -int Goo() -{ - return 1; -} -"; - var src2 = @" -using System; + Console.Write(1); + return 1; -Console.Write(1); + int Goo() + { + return 1; + } -int Goo() -{ - return 1; -} -"; + """; + var src2 = """ + + using System; + + Console.Write(1); + + int Goo() + { + return 1; + } + + """; var edits = GetTopEdits(src1, src2); @@ -23742,33 +23941,37 @@ int Goo() [Fact] public void TopLevelStatements_IntToVoid4() { - var src1 = @" -using System; + var src1 = """ -Console.Write(1); -return 1; + using System; -public class C -{ - public int Goo() - { - return 1; - } -} -"; - var src2 = @" -using System; + Console.Write(1); + return 1; -Console.Write(1); + public class C + { + public int Goo() + { + return 1; + } + } -public class C -{ - public int Goo() - { - return 1; - } -} -"; + """; + var src2 = """ + + using System; + + Console.Write(1); + + public class C + { + public int Goo() + { + return 1; + } + } + + """; var edits = GetTopEdits(src1, src2); @@ -23780,19 +23983,23 @@ public int Goo() [Fact] public void TopLevelStatements_TaskToVoid() { - var src1 = @" -using System; -using System.Threading.Tasks; + var src1 = """ -await Task.Delay(100); -Console.Write(1); -"; - var src2 = @" -using System; -using System.Threading.Tasks; + using System; + using System.Threading.Tasks; + + await Task.Delay(100); + Console.Write(1); + + """; + var src2 = """ -Console.Write(1); -"; + using System; + using System.Threading.Tasks; + + Console.Write(1); + + """; var edits = GetTopEdits(src1, src2); @@ -23805,21 +24012,25 @@ public void TopLevelStatements_TaskToVoid() [Fact] public void TopLevelStatements_TaskIntToTask() { - var src1 = @" -using System; -using System.Threading.Tasks; + var src1 = """ -await Task.Delay(100); -Console.Write(1); -return 1; -"; - var src2 = @" -using System; -using System.Threading.Tasks; + using System; + using System.Threading.Tasks; -await Task.Delay(100); -Console.Write(1); -"; + await Task.Delay(100); + Console.Write(1); + return 1; + + """; + var src2 = """ + + using System; + using System.Threading.Tasks; + + await Task.Delay(100); + Console.Write(1); + + """; var edits = GetTopEdits(src1, src2); @@ -23831,24 +24042,28 @@ public void TopLevelStatements_TaskIntToTask() [Fact] public void TopLevelStatements_TaskIntToVoid() { - var src1 = @" -using System; -using System.Threading.Tasks; + var src1 = """ -Console.Write(1); -return await GetInt(); + using System; + using System.Threading.Tasks; -Task GetInt() -{ - return Task.FromResult(1); -} -"; - var src2 = @" -using System; -using System.Threading.Tasks; + Console.Write(1); + return await GetInt(); + + Task GetInt() + { + return Task.FromResult(1); + } + + """; + var src2 = """ -Console.Write(1); -"; + using System; + using System.Threading.Tasks; + + Console.Write(1); + + """; var edits = GetTopEdits(src1, src2); @@ -23861,20 +24076,24 @@ Task GetInt() [Fact] public void TopLevelStatements_WithLambda_Insert() { - var src1 = @" -using System; + var src1 = """ -Func a = () => { return 1; }; -Func> b = () => () => { return 1; }; -"; - var src2 = @" -using System; + using System; + + Func a = () => { return 1; }; + Func> b = () => () => { return 1; }; + + """; + var src2 = """ -Func a = () => { return 1; }; -Func> b = () => () => { return 1; }; + using System; + + Func a = () => { return 1; }; + Func> b = () => () => { return 1; }; + + Console.WriteLine(1); -Console.WriteLine(1); -"; + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -23886,26 +24105,30 @@ public void TopLevelStatements_WithLambda_Insert() [Fact] public void TopLevelStatements_WithLambda_Update() { - var src1 = @" -using System; + var src1 = """ + + using System; + + Func a = () => { return 1; }; + Func> b = () => () => { return 1; }; -Func a = () => { return 1; }; -Func> b = () => () => { return 1; }; + Console.WriteLine(1); -Console.WriteLine(1); + public class C { } -public class C { } -"; - var src2 = @" -using System; + """; + var src2 = """ + + using System; -Func a = () => { return 1; }; -Func> b = () => () => { return 1; }; + Func a = () => { return 1; }; + Func> b = () => () => { return 1; }; -Console.WriteLine(2); + Console.WriteLine(2); + + public class C { } -public class C { } -"; + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -23917,24 +24140,28 @@ public class C { } [Fact] public void TopLevelStatements_WithLambda_Delete() { - var src1 = @" -using System; + var src1 = """ -Func a = () => { return 1; }; -Func> b = () => () => { return 1; }; + using System; -Console.WriteLine(1); + Func a = () => { return 1; }; + Func> b = () => () => { return 1; }; -public class C { } -"; - var src2 = @" -using System; + Console.WriteLine(1); -Func a = () => { return 1; }; -Func> b = () => () => { return 1; }; + public class C { } -public class C { } -"; + """; + var src2 = """ + + using System; + + Func a = () => { return 1; }; + Func> b = () => () => { return 1; }; + + public class C { } + + """; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); @@ -23946,22 +24173,26 @@ public class C { } [Fact] public void TopLevelStatements_UpdateMultiple() { - var src1 = @" -using System; + var src1 = """ -Console.WriteLine(1); -Console.WriteLine(2); + using System; -public class C { } -"; - var src2 = @" -using System; + Console.WriteLine(1); + Console.WriteLine(2); + + public class C { } + + """; + var src2 = """ + + using System; -Console.WriteLine(3); -Console.WriteLine(4); + Console.WriteLine(3); + Console.WriteLine(4); -public class C { } -"; + public class C { } + + """; var edits = GetTopEdits(src1, src2); // Since each individual statement is a separate update to a separate node, this just validates we correctly @@ -23974,38 +24205,40 @@ public class C { } [Fact] public void TopLevelStatements_MoveToOtherFile() { - var srcA1 = @" -using System; + EditAndContinueValidation.VerifySemantics( + [GetTopEdits(""" -Console.WriteLine(1); + using System; -public class A -{ -}"; - var srcB1 = @" -using System; + Console.WriteLine(1); -public class B -{ -}"; + public class A + { + } + """, """ - var srcA2 = @" -using System; + using System; -public class A -{ -}"; - var srcB2 = @" -using System; + public class A + { + } + """), GetTopEdits(""" -Console.WriteLine(2); + using System; -public class B -{ -}"; + public class B + { + } + """, """ - EditAndContinueValidation.VerifySemantics( - [GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2)], + using System; + + Console.WriteLine(2); + + public class B + { + } + """)], [ DocumentResults(), DocumentResults( @@ -24017,14 +24250,18 @@ public class B [Fact] public void TopLevelStatements_BlockReorder() { - var src1 = @" -{ int a; } -{ int b; } -"; - var src2 = @" -{ int b; } -{ int a; } -"; + var src1 = """ + + { int a; } + { int b; } + + """; + var src2 = """ + + { int b; } + { int a; } + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Reorder [{ int b; }]@14 -> @2"); @@ -24037,14 +24274,18 @@ public void TopLevelStatements_BlockReorder() [Fact] public void TopLevelStatements_Reorder() { - var src1 = @" -System.Console.Write(1); -System.Console.Write(2); -"; - var src2 = @" -System.Console.Write(2); -System.Console.Write(1); -"; + var src1 = """ + + System.Console.Write(1); + System.Console.Write(2); + + """; + var src2 = """ + + System.Console.Write(2); + System.Console.Write(1); + + """; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Reorder [System.Console.Write(2);]@28 -> @2"); diff --git a/src/Features/CSharpTest/EditAndContinue/TrackingSpanTests.cs b/src/Features/CSharpTest/EditAndContinue/TrackingSpanTests.cs index c5e7f2538238c..b2323218f3b75 100644 --- a/src/Features/CSharpTest/EditAndContinue/TrackingSpanTests.cs +++ b/src/Features/CSharpTest/EditAndContinue/TrackingSpanTests.cs @@ -17,28 +17,29 @@ public sealed class TrackingSpanTests : EditingTestBase [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846042")] public void MovedOutsideOfMethod1() { - var src1 = @" -class C -{ - static void F() - { - Goo(1); - } -}"; - var src2 = @" -class C -{ - static void F() - { - } + var src1 = """ + class C + { + static void F() + { + Goo(1); + } + } + """; + var src2 = """ + class C + { + static void F() + { + } - static void Goo() - { - // tracking span moves to another method as the user types around it - Goo(1); - } -} -"; + static void Goo() + { + // tracking span moves to another method as the user types around it + Goo(1); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -50,28 +51,29 @@ static void Goo() [Fact] public void MovedOutsideOfMethod2() { - var src1 = @" -class C -{ - static void F() - { - Goo(1); - } -}"; - var src2 = @" -class C -{ - static void F() - { - Goo(1); - } + var src1 = """ + class C + { + static void F() + { + Goo(1); + } + } + """; + var src2 = """ + class C + { + static void F() + { + Goo(1); + } - static void Goo() - { - Goo(2); - } -} -"; + static void Goo() + { + Goo(2); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -83,24 +85,25 @@ static void Goo() [Fact] public void MovedOutsideOfLambda1() { - var src1 = @" -class C -{ - static void F() - { - Action a = () => { Goo(1); }; - } -}"; - var src2 = @" -class C -{ - static void F() - { - Action a = () => { }; - Goo(1); - } -} -"; + var src1 = """ + class C + { + static void F() + { + Action a = () => { Goo(1); }; + } + } + """; + var src2 = """ + class C + { + static void F() + { + Action a = () => { }; + Goo(1); + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); @@ -110,25 +113,26 @@ static void F() [Fact] public void MovedOutsideOfLambda2() { - var src1 = @" -class C -{ - static void F() - { - Action a = () => { Goo(1); }; - Action b = () => { Goo(2); }; - } -}"; - var src2 = @" -class C -{ - static void F() - { - Action a = () => { Goo(1); }; - Action b = () => { Goo(2); }; - } -} -"; + var src1 = """ + class C + { + static void F() + { + Action a = () => { Goo(1); }; + Action b = () => { Goo(2); }; + } + } + """; + var src2 = """ + class C + { + static void F() + { + Action a = () => { Goo(1); }; + Action b = () => { Goo(2); }; + } + } + """; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); diff --git a/src/Features/CSharpTest/EmbeddedLanguages/JsonStringDetectorTests.cs b/src/Features/CSharpTest/EmbeddedLanguages/JsonStringDetectorTests.cs index 522c50d46eed8..013ff3257397f 100644 --- a/src/Features/CSharpTest/EmbeddedLanguages/JsonStringDetectorTests.cs +++ b/src/Features/CSharpTest/EmbeddedLanguages/JsonStringDetectorTests.cs @@ -19,9 +19,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.EmbeddedLanguages; public sealed class JsonStringDetectorTests { [Fact] - public async Task TestStrict() - { - await new VerifyCS.Test + public Task TestStrict() + => new VerifyCS.Test { TestCode = """ @@ -44,12 +43,10 @@ void Goo() } """, }.RunAsync(); - } [Fact] - public async Task TestNonStrict() - { - await new VerifyCS.Test + public Task TestNonStrict() + => new VerifyCS.Test { TestCode = """ @@ -72,12 +69,10 @@ void Goo() } """, }.RunAsync(); - } [Fact] - public async Task TestNonStrictRawString() - { - await new VerifyCS.Test + public Task TestNonStrictRawString() + => new VerifyCS.Test { TestCode = """" @@ -101,12 +96,12 @@ void Goo() """", LanguageVersion = LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task TestNotWithExistingComment() - { - var code = """ + public Task TestNotWithExistingComment() + => new VerifyCS.Test + { + TestCode = """ class C { void Goo() @@ -114,17 +109,14 @@ void Goo() var j = /*lang=json,strict*/ "{ \"a\": 0 }"; } } - """; - await new VerifyCS.Test - { - TestCode = code, + """, }.RunAsync(); - } [Fact] - public async Task TestNotOnUnlikelyJson() - { - var code = """ + public Task TestNotOnUnlikelyJson() + => new VerifyCS.Test + { + TestCode = """ class C { void Goo() @@ -132,10 +124,6 @@ void Goo() var j = "[1, 2, 3]"; } } - """; - await new VerifyCS.Test - { - TestCode = code, + """, }.RunAsync(); - } } diff --git a/src/Features/CSharpTest/EmbeddedLanguages/ValidateJsonStringTests.cs b/src/Features/CSharpTest/EmbeddedLanguages/ValidateJsonStringTests.cs index 99b6a215c9caf..6dbc2699e10c0 100644 --- a/src/Features/CSharpTest/EmbeddedLanguages/ValidateJsonStringTests.cs +++ b/src/Features/CSharpTest/EmbeddedLanguages/ValidateJsonStringTests.cs @@ -30,9 +30,8 @@ private OptionsCollection OptionOn() => Option(JsonDetectionOptionsStorage.ReportInvalidJsonPatterns, true); [Fact] - public async Task TestWarning1() - { - await TestDiagnosticInfoAsync(""" + public Task TestWarning1() + => TestDiagnosticInfoAsync(""" class Program { void Main() @@ -45,12 +44,10 @@ void Main() diagnosticId: AbstractJsonDiagnosticAnalyzer.DiagnosticId, diagnosticSeverity: DiagnosticSeverity.Warning, diagnosticMessage: string.Format(FeaturesResources.JSON_issue_0, FeaturesResources.Constructors_not_allowed)); - } [Fact] - public async Task TestWarningInRawString1() - { - await TestDiagnosticInfoAsync("""" + public Task TestWarningInRawString1() + => TestDiagnosticInfoAsync("""" class Program { void Main() @@ -63,12 +60,10 @@ void Main() diagnosticId: AbstractJsonDiagnosticAnalyzer.DiagnosticId, diagnosticSeverity: DiagnosticSeverity.Warning, diagnosticMessage: string.Format(FeaturesResources.JSON_issue_0, FeaturesResources.Constructors_not_allowed)); - } [Fact] - public async Task TestWarning2() - { - await TestDiagnosticInfoAsync(""" + public Task TestWarning2() + => TestDiagnosticInfoAsync(""" class Program { void Main() @@ -82,12 +77,10 @@ void Main() diagnosticSeverity: DiagnosticSeverity.Warning, diagnosticMessage: string.Format(FeaturesResources.JSON_issue_0, string.Format(FeaturesResources._0_unexpected, '}'))); - } [Fact] - public async Task TestJsonDocumentWithTrailingComma() - { - await TestDiagnosticInfoAsync(""" + public Task TestJsonDocumentWithTrailingComma() + => TestDiagnosticInfoAsync(""" @@ -109,12 +102,10 @@ void Main() diagnosticSeverity: DiagnosticSeverity.Warning, diagnosticMessage: string.Format(FeaturesResources.JSON_issue_0, FeaturesResources.Trailing_comma_not_allowed)); - } [Fact] - public async Task TestJsonDocumentTrailingCommaDisallowed() - { - await TestDiagnosticInfoAsync(""" + public Task TestJsonDocumentTrailingCommaDisallowed() + => TestDiagnosticInfoAsync(""" @@ -136,12 +127,10 @@ void Main() diagnosticSeverity: DiagnosticSeverity.Warning, diagnosticMessage: string.Format(FeaturesResources.JSON_issue_0, FeaturesResources.Trailing_comma_not_allowed)); - } [Fact] - public async Task TestJsonDocumentTrailingCommaAllowed() - { - await TestDiagnosticMissingAsync(""" + public Task TestJsonDocumentTrailingCommaAllowed() + => TestDiagnosticMissingAsync(""" @@ -158,12 +147,10 @@ void Main() """); - } [Fact] - public async Task TestJsonDocumentTrailingCommaAllowedImplicitObject() - { - await TestDiagnosticMissingAsync(""" + public Task TestJsonDocumentTrailingCommaAllowedImplicitObject() + => TestDiagnosticMissingAsync(""" @@ -180,12 +167,10 @@ void Main() """); - } [Fact] - public async Task TestJsonDocumentWithComments() - { - await TestDiagnosticInfoAsync(""" + public Task TestJsonDocumentWithComments() + => TestDiagnosticInfoAsync(""" @@ -207,12 +192,10 @@ void Main() diagnosticSeverity: DiagnosticSeverity.Warning, diagnosticMessage: string.Format(FeaturesResources.JSON_issue_0, FeaturesResources.Comments_not_allowed)); - } [Fact] - public async Task TestJsonDocumentCommentsDisallowed() - { - await TestDiagnosticInfoAsync(""" + public Task TestJsonDocumentCommentsDisallowed() + => TestDiagnosticInfoAsync(""" @@ -234,12 +217,10 @@ void Main() diagnosticSeverity: DiagnosticSeverity.Warning, diagnosticMessage: string.Format(FeaturesResources.JSON_issue_0, FeaturesResources.Comments_not_allowed)); - } [Fact] - public async Task TestJsonDocumentCommentsAllowed() - { - await TestDiagnosticMissingAsync(""" + public Task TestJsonDocumentCommentsAllowed() + => TestDiagnosticMissingAsync(""" @@ -256,12 +237,10 @@ void Main() """); - } [Fact] - public async Task TestJsonDocumentCommentsAllowedImplicitObject() - { - await TestDiagnosticMissingAsync(""" + public Task TestJsonDocumentCommentsAllowedImplicitObject() + => TestDiagnosticMissingAsync(""" @@ -278,137 +257,134 @@ void Main() """); - } [Fact] - public async Task TestJsonDocumentCommentsDisallowed_StringSyntaxAttribute_NoOptionsProvided() - { - await TestDiagnosticInfoAsync($@" - - -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; - -class Program -{{ - void Main() - {{ - M(@""[1][|/*comment*/|]""); - }} - - void M([StringSyntax(StringSyntaxAttribute.Json)] string p) - {{ - }} -}} -{EmbeddedLanguagesTestConstants.StringSyntaxAttributeCodeCSharpXml} - - -", + public Task TestJsonDocumentCommentsDisallowed_StringSyntaxAttribute_NoOptionsProvided() + => TestDiagnosticInfoAsync($$""" + + + + using System.Diagnostics.CodeAnalysis; + using System.Text.Json; + + class Program + { + void Main() + { + M(@"[1][|/*comment*/|]"); + } + + void M([StringSyntax(StringSyntaxAttribute.Json)] string p) + { + } + } + {{EmbeddedLanguagesTestConstants.StringSyntaxAttributeCodeCSharpXml}} + + + + """, options: OptionOn(), diagnosticId: AbstractJsonDiagnosticAnalyzer.DiagnosticId, diagnosticSeverity: DiagnosticSeverity.Warning, diagnosticMessage: string.Format(FeaturesResources.JSON_issue_0, FeaturesResources.Comments_not_allowed)); - } [Fact] - public async Task TestJsonDocumentCommentsDisallowed_StringSyntaxAttribute_OptionsProvided() - { - await TestDiagnosticInfoAsync($@" - - -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; - -class Program -{{ - void Main() - {{ - M(@""[1][|/*comment*/|]"", new JsonDocumentOptions {{ CommentHandling = JsonCommentHandling.Disallow }}); - }} - - void M([StringSyntax(StringSyntaxAttribute.Json)] string p, JsonDocumentOptions options) - {{ - }} -}} -{EmbeddedLanguagesTestConstants.StringSyntaxAttributeCodeCSharpXml} - - -", + public Task TestJsonDocumentCommentsDisallowed_StringSyntaxAttribute_OptionsProvided() + => TestDiagnosticInfoAsync($$""" + + + + using System.Diagnostics.CodeAnalysis; + using System.Text.Json; + + class Program + { + void Main() + { + M(@"[1][|/*comment*/|]", new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Disallow }); + } + + void M([StringSyntax(StringSyntaxAttribute.Json)] string p, JsonDocumentOptions options) + { + } + } + {{EmbeddedLanguagesTestConstants.StringSyntaxAttributeCodeCSharpXml}} + + + + """, options: OptionOn(), diagnosticId: AbstractJsonDiagnosticAnalyzer.DiagnosticId, diagnosticSeverity: DiagnosticSeverity.Warning, diagnosticMessage: string.Format(FeaturesResources.JSON_issue_0, FeaturesResources.Comments_not_allowed)); - } [Fact] - public async Task TestJsonDocumentCommentsAllowed_StringSyntaxAttribute_OptionsProvided() - { - await TestDiagnosticMissingAsync($@" - - -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; - -class Program -{{ - void Main() - {{ - M(@""[1][|/*comment*/|]"", new JsonDocumentOptions {{ CommentHandling = JsonCommentHandling.Allow }}); - }} - - void M([StringSyntax(StringSyntaxAttribute.Json)] string p, JsonDocumentOptions options) - {{ - }} -}} -{EmbeddedLanguagesTestConstants.StringSyntaxAttributeCodeCSharpXml} - - -"); - } + public Task TestJsonDocumentCommentsAllowed_StringSyntaxAttribute_OptionsProvided() + => TestDiagnosticMissingAsync($$""" + + + + using System.Diagnostics.CodeAnalysis; + using System.Text.Json; + + class Program + { + void Main() + { + M(@"[1][|/*comment*/|]", new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Allow }); + } + + void M([StringSyntax(StringSyntaxAttribute.Json)] string p, JsonDocumentOptions options) + { + } + } + {{EmbeddedLanguagesTestConstants.StringSyntaxAttributeCodeCSharpXml}} + + + + """); [Fact] - public async Task TestNotOnUnlikelyJson() - { - await TestDiagnosticMissingAsync($@" - - - -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; - -class Program -{{ - void Main() - {{ - var v = [|""[1, 2, 3]""|]; - }} -}} - - -"); - } + public Task TestNotOnUnlikelyJson() + => TestDiagnosticMissingAsync($$""" + + + + using System.Diagnostics.CodeAnalysis; + using System.Text.Json; + + class Program + { + void Main() + { + var v = [|"[1, 2, 3]"|]; + } + } + + + + """); [Fact] - public async Task TestNotOnLikelyJson() - { - await TestDiagnosticMissingAsync($@" - - - -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; - -class Program -{{ - void Main() - {{ - var v = [|""{{ prop: 0 }}""|]; - }} -}} - - -"); - } + public Task TestNotOnLikelyJson() + => TestDiagnosticMissingAsync($$""" + + + + using System.Diagnostics.CodeAnalysis; + using System.Text.Json; + + class Program + { + void Main() + { + var v = [|"{ prop: 0 }"|]; + } + } + + + + """); } diff --git a/src/Features/CSharpTest/EmbeddedLanguages/ValidateRegexStringTests.cs b/src/Features/CSharpTest/EmbeddedLanguages/ValidateRegexStringTests.cs index 806c63b4f170b..139f2350c2a5b 100644 --- a/src/Features/CSharpTest/EmbeddedLanguages/ValidateRegexStringTests.cs +++ b/src/Features/CSharpTest/EmbeddedLanguages/ValidateRegexStringTests.cs @@ -30,9 +30,8 @@ private OptionsCollection OptionOn() => Option(RegexOptionsStorage.ReportInvalidRegexPatterns, true); [Fact] - public async Task TestWarning1() - { - await TestDiagnosticInfoAsync(""" + public Task TestWarning1() + => TestDiagnosticInfoAsync(""" using System.Text.RegularExpressions; class Program @@ -47,12 +46,10 @@ void Main() diagnosticId: AbstractRegexDiagnosticAnalyzer.DiagnosticId, diagnosticSeverity: DiagnosticSeverity.Warning, diagnosticMessage: string.Format(FeaturesResources.Regex_issue_0, FeaturesResources.Too_many_close_parens)); - } [Fact] - public async Task TestWarning2() - { - await TestDiagnosticInfoAsync(""" + public Task TestWarning2() + => TestDiagnosticInfoAsync(""" using System.Text.RegularExpressions; class Program @@ -67,12 +64,10 @@ void Main() diagnosticId: AbstractRegexDiagnosticAnalyzer.DiagnosticId, diagnosticSeverity: DiagnosticSeverity.Warning, diagnosticMessage: string.Format(FeaturesResources.Regex_issue_0, FeaturesResources.Too_many_close_parens)); - } [Fact] - public async Task TestWarningMissing1() - { - await TestDiagnosticMissingAsync(""" + public Task TestWarningMissing1() + => TestDiagnosticMissingAsync(""" using System.Text.RegularExpressions; class Program @@ -83,5 +78,4 @@ void Main() } } """); - } } diff --git a/src/Features/CSharpTest/EnableNullable/EnableNullableFixAllTests.cs b/src/Features/CSharpTest/EnableNullable/EnableNullableFixAllTests.cs index 261c1267edfef..677dfdb629fb7 100644 --- a/src/Features/CSharpTest/EnableNullable/EnableNullableFixAllTests.cs +++ b/src/Features/CSharpTest/EnableNullable/EnableNullableFixAllTests.cs @@ -17,132 +17,128 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor => new EnableNullableCodeRefactoringProvider(); [Fact] - public async Task EnableNullable_FixAllInSolution() - { - await TestInRegularAndScriptAsync(@" - - - -{|FixAllInSolution:|}#nullable enable + public Task EnableNullable_FixAllInSolution() + => TestInRegularAndScriptAsync(""" + + + + {|FixAllInSolution:|}#nullable enable -class Example -{ - string? value; -} - - -class Example2 -{ - string value; -} - - - - -class Example3 -{ -#nullable enable - string? value; -#nullable restore -} - - -#nullable disable + class Example + { + string? value; + } + + + class Example2 + { + string value; + } + + + + + class Example3 + { + #nullable enable + string? value; + #nullable restore + } + + + #nullable disable -class Example4 -{ - string value; -} - - - -", @" - - - + class Example4 + { + string value; + } + + + + """, """ + + + -class Example -{ - string? value; -} - - -#nullable disable + class Example + { + string? value; + } + + + #nullable disable -class Example2 -{ - string value; -} - - - - -#nullable disable + class Example2 + { + string value; + } + + + + + #nullable disable -class Example3 -{ -#nullable restore - string? value; -#nullable disable -} - - -#nullable disable + class Example3 + { + #nullable restore + string? value; + #nullable disable + } + + + #nullable disable -class Example4 -{ - string value; -} - - - -"); - } + class Example4 + { + string value; + } + + + + """); [Theory] [InlineData("FixAllInDocument")] [InlineData("FixAllInProject")] [InlineData("FixAllInContainingMember")] [InlineData("FixAllInContainingType")] - public async Task EnableNullable_UnsupportedFixAllScopes(string fixAllScope) - { - await TestMissingInRegularAndScriptAsync($@" - - - -{{|{fixAllScope}:|}}#nullable enable + public Task EnableNullable_UnsupportedFixAllScopes(string fixAllScope) + => TestMissingInRegularAndScriptAsync($$""" + + + + {|{{fixAllScope}}:|}#nullable enable -class Example -{{ - string? value; -}} - - -class Example2 -{{ - string value; -}} - - - - -class Example3 -{{ -#nullable enable - string? value; -#nullable restore -}} - - -#nullable disable + class Example + { + string? value; + } + + + class Example2 + { + string value; + } + + + + + class Example3 + { + #nullable enable + string? value; + #nullable restore + } + + + #nullable disable -class Example4 -{{ - string value; -}} - - - -"); - } + class Example4 + { + string value; + } + + + + """); } diff --git a/src/Features/CSharpTest/EnableNullable/EnableNullableTests.cs b/src/Features/CSharpTest/EnableNullable/EnableNullableTests.cs index 83ad7c8bde7a7..f66a79c99c212 100644 --- a/src/Features/CSharpTest/EnableNullable/EnableNullableTests.cs +++ b/src/Features/CSharpTest/EnableNullable/EnableNullableTests.cs @@ -14,7 +14,6 @@ using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; -using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.EnableNullable; @@ -70,70 +69,86 @@ public sealed class EnableNullableTests [InlineData("#nullable enable$$")] public async Task EnabledOnNullableEnable(string directive) { - var code1 = $@" -{directive} - -class Example -{{ - string? value; -}} -"; - var code2 = @" -class Example2 -{ - string value; -} -"; - var code3 = @" -class Example3 -{ -#nullable enable - string? value; -#nullable restore -} -"; - var code4 = @" -#nullable disable + var code1 = $$""" -class Example4 -{ - string value; -} -"; + {{directive}} - var fixedCode1 = @" + class Example + { + string? value; + } -class Example -{ - string? value; -} -"; - var fixedCode2 = @" -#nullable disable + """; + var code2 = """ -class Example2 -{ - string value; -} -"; - var fixedCode3 = @" -#nullable disable + class Example2 + { + string value; + } -class Example3 -{ -#nullable restore - string? value; -#nullable disable -} -"; - var fixedCode4 = @" -#nullable disable + """; + var code3 = """ -class Example4 -{ - string value; -} -"; + class Example3 + { + #nullable enable + string? value; + #nullable restore + } + + """; + var code4 = """ + + #nullable disable + + class Example4 + { + string value; + } + + """; + + var fixedCode1 = """ + + + class Example + { + string? value; + } + + """; + var fixedCode2 = """ + + #nullable disable + + class Example2 + { + string value; + } + + """; + var fixedCode3 = """ + + #nullable disable + + class Example3 + { + #nullable restore + string? value; + #nullable disable + } + + """; + var fixedCode4 = """ + + #nullable disable + + class Example4 + { + string value; + } + + """; await new VerifyCS.Test { @@ -164,62 +179,74 @@ class Example4 [Fact] public async Task PlacementAfterHeader() { - var code1 = @" -#nullable enable$$ + var code1 = """ -class Example -{ - string? value; -} -"; - var code2 = @"// File header line 1 -// File header line 2 + #nullable enable$$ -class Example2 -{ - string value; -} -"; - var code3 = @"#region File Header -// File header line 1 -// File header line 2 -#endregion + class Example + { + string? value; + } -class Example3 -{ - string value; -} -"; + """; + var code2 = """ + // File header line 1 + // File header line 2 - var fixedCode1 = @" + class Example2 + { + string value; + } -class Example -{ - string? value; -} -"; - var fixedCode2 = @"// File header line 1 -// File header line 2 + """; + var code3 = """ + #region File Header + // File header line 1 + // File header line 2 + #endregion -#nullable disable + class Example3 + { + string value; + } -class Example2 -{ - string value; -} -"; - var fixedCode3 = @"#region File Header -// File header line 1 -// File header line 2 -#endregion + """; -#nullable disable + var fixedCode1 = """ -class Example3 -{ - string value; -} -"; + + class Example + { + string? value; + } + + """; + var fixedCode2 = """ + // File header line 1 + // File header line 2 + + #nullable disable + + class Example2 + { + string value; + } + + """; + var fixedCode3 = """ + #region File Header + // File header line 1 + // File header line 2 + #endregion + + #nullable disable + + class Example3 + { + string value; + } + + """; await new VerifyCS.Test { @@ -248,86 +275,106 @@ class Example3 [Fact] public async Task PlacementBeforeDocComment() { - var code1 = @" -#nullable enable$$ + var code1 = """ -class Example -{ - string? value; -} -"; - var code2 = @"// Line comment -class Example2 -{ - string value; -} -"; - var code3 = @"/* - * Block comment - */ -class Example3 -{ - string value; -} -"; - var code4 = @"/// Single line doc comment -class Example4 -{ - string value; -} -"; - var code5 = @"/** - * Multi-line doc comment - */ -class Example5 -{ - string value; -} -"; + #nullable enable$$ - var fixedCode1 = @" + class Example + { + string? value; + } -class Example -{ - string? value; -} -"; - var fixedCode2 = @"// Line comment -#nullable disable + """; + var code2 = """ + // Line comment + class Example2 + { + string value; + } -class Example2 -{ - string value; -} -"; - var fixedCode3 = @"/* - * Block comment - */ -#nullable disable + """; + var code3 = """ + /* + * Block comment + */ + class Example3 + { + string value; + } -class Example3 -{ - string value; -} -"; - var fixedCode4 = @"#nullable disable + """; + var code4 = """ + /// Single line doc comment + class Example4 + { + string value; + } -/// Single line doc comment -class Example4 -{ - string value; -} -"; - var fixedCode5 = @"#nullable disable + """; + var code5 = """ + /** + * Multi-line doc comment + */ + class Example5 + { + string value; + } -/** - * Multi-line doc comment - */ -class Example5 -{ - string value; -} -"; + """; + + var fixedCode1 = """ + + + class Example + { + string? value; + } + + """; + var fixedCode2 = """ + // Line comment + #nullable disable + + class Example2 + { + string value; + } + + """; + var fixedCode3 = """ + /* + * Block comment + */ + #nullable disable + + class Example3 + { + string value; + } + + """; + var fixedCode4 = """ + #nullable disable + + /// Single line doc comment + class Example4 + { + string value; + } + + """; + var fixedCode5 = """ + #nullable disable + + /** + * Multi-line doc comment + */ + class Example5 + { + string value; + } + + """; await new VerifyCS.Test { @@ -360,73 +407,89 @@ class Example5 [Fact] public async Task OmitLeadingRestore() { - var code1 = @" -#nullable enable$$ + var code1 = """ -class Example -{ - string? value; -} -"; - var code2 = @" -#nullable enable + #nullable enable$$ -class Example2 -{ - string? value; -} -"; - var code3 = @" -#nullable enable warnings + class Example + { + string? value; + } -class Example3 -{ - string value; -} -"; - var code4 = @" -#nullable enable annotations + """; + var code2 = """ -class Example4 -{ - string? value; -} -"; + #nullable enable - var fixedCode1 = @" + class Example2 + { + string? value; + } -class Example -{ - string? value; -} -"; - var fixedCode2 = @" + """; + var code3 = """ -class Example2 -{ - string? value; -} -"; - var fixedCode3 = @" -#nullable disable + #nullable enable warnings -#nullable restore warnings + class Example3 + { + string value; + } -class Example3 -{ - string value; -} -"; - var fixedCode4 = @" -#nullable disable + """; + var code4 = """ -#nullable restore annotations + #nullable enable annotations -class Example4 -{ - string? value; -} -"; + class Example4 + { + string? value; + } + + """; + + var fixedCode1 = """ + + + class Example + { + string? value; + } + + """; + var fixedCode2 = """ + + + class Example2 + { + string? value; + } + + """; + var fixedCode3 = """ + + #nullable disable + + #nullable restore warnings + + class Example3 + { + string value; + } + + """; + var fixedCode4 = """ + + #nullable disable + + #nullable restore annotations + + class Example4 + { + string? value; + } + + """; await new VerifyCS.Test { @@ -457,49 +520,59 @@ class Example4 [Fact] public async Task IgnoreGeneratedCode() { - var code1 = @" -#nullable enable$$ + var code1 = """ -class Example -{ - string? value; -} -"; - var generatedCode1 = @"// + #nullable enable$$ -#nullable enable + class Example + { + string? value; + } -class Example2 -{ - string? value; -} -"; - var generatedCode2 = @"// + """; + var generatedCode1 = """ + // -#nullable disable + #nullable enable -class Example3 -{ - string value; -} -"; - var generatedCode3 = @"// + class Example2 + { + string? value; + } -#nullable restore + """; + var generatedCode2 = """ + // -class Example4 -{ - string {|#0:value|}; -} -"; + #nullable disable - var fixedCode1 = @" + class Example3 + { + string value; + } + + """; + var generatedCode3 = """ + // + + #nullable restore + + class Example4 + { + string {|#0:value|}; + } + + """; + + var fixedCode1 = """ -class Example -{ - string? value; -} -"; + + class Example + { + string? value; + } + + """; await new VerifyCS.Test { @@ -536,15 +609,14 @@ class Example [InlineData(NullableContextOptions.Annotations)] [InlineData(NullableContextOptions.Warnings)] [InlineData(NullableContextOptions.Enable)] - public async Task DisabledIfSetInProject(NullableContextOptions nullableContextOptions) - { - var code = @" -#nullable enable$$ -"; - - await new VerifyCS.Test + public Task DisabledIfSetInProject(NullableContextOptions nullableContextOptions) + => new VerifyCS.Test { - TestCode = code, + TestCode = """ + + #nullable enable$$ + + """, SolutionTransforms = { (solution, projectId) => @@ -554,7 +626,6 @@ public async Task DisabledIfSetInProject(NullableContextOptions nullableContextO }, }, }.RunAsync(); - } [Theory] [InlineData(LanguageVersion.CSharp1)] @@ -569,9 +640,11 @@ public async Task DisabledIfSetInProject(NullableContextOptions nullableContextO [InlineData(LanguageVersion.CSharp7_3)] public async Task DisabledForUnsupportedLanguageVersion(LanguageVersion languageVersion) { - var code = @" -#{|#0:nullable|} enable$$ -"; + var code = """ + + #{|#0:nullable|} enable$$ + + """; var error = languageVersion switch { @@ -615,73 +688,89 @@ public async Task DisabledForUnsupportedLanguageVersion(LanguageVersion language [InlineData("#nullable restore$$")] public async Task EnabledOnNullableRestore(string directive) { - var code1 = $@" -{directive} - -class Example -{{ - string value; -}} -"; - var code2 = @" -class Example2 -{ - string value; -} -"; - var code3 = @" -class Example3 -{ -#nullable enable - string? value; -#nullable restore -} -"; - var code4 = @" -#nullable disable + var code1 = $$""" -class Example4 -{ - string value; -} -"; + {{directive}} + + class Example + { + string value; + } + + """; + var code2 = """ + + class Example2 + { + string value; + } + + """; + var code3 = """ + + class Example3 + { + #nullable enable + string? value; + #nullable restore + } + + """; + var code4 = """ + + #nullable disable + + class Example4 + { + string value; + } + + """; var fixedDirective = directive.Replace("$$", "").Replace("restore", "disable"); - var fixedCode1 = $@" -{fixedDirective} + var fixedCode1 = $$""" -class Example -{{ - string value; -}} -"; - var fixedCode2 = @" -#nullable disable + {{fixedDirective}} -class Example2 -{ - string value; -} -"; - var fixedCode3 = @" -#nullable disable + class Example + { + string value; + } -class Example3 -{ -#nullable restore - string? value; -#nullable disable -} -"; - var fixedCode4 = @" -#nullable disable + """; + var fixedCode2 = """ -class Example4 -{ - string value; -} -"; + #nullable disable + + class Example2 + { + string value; + } + + """; + var fixedCode3 = """ + + #nullable disable + + class Example3 + { + #nullable restore + string? value; + #nullable disable + } + + """; + var fixedCode4 = """ + + #nullable disable + + class Example4 + { + string value; + } + + """; await new VerifyCS.Test { @@ -720,77 +809,93 @@ class Example4 [InlineData("#nullable disable$$")] public async Task EnabledOnNullableDisable(string directive) { - var code1 = $@" -{directive} - -class Example -{{ - string value; -}} - -#nullable restore -"; - var code2 = @" -class Example2 -{ - string value; -} -"; - var code3 = @" -class Example3 -{ -#nullable enable - string? value; -#nullable restore -} -"; - var code4 = @" -#nullable disable + var code1 = $$""" -class Example4 -{ - string value; -} -"; + {{directive}} + + class Example + { + string value; + } + + #nullable restore + + """; + var code2 = """ + + class Example2 + { + string value; + } + + """; + var code3 = """ + + class Example3 + { + #nullable enable + string? value; + #nullable restore + } + + """; + var code4 = """ + + #nullable disable + + class Example4 + { + string value; + } + + """; var fixedDirective = directive.Replace("$$", ""); - var fixedCode1 = $@" -{fixedDirective} + var fixedCode1 = $$""" -class Example -{{ - string value; -}} + {{fixedDirective}} -#nullable disable -"; - var fixedCode2 = @" -#nullable disable + class Example + { + string value; + } -class Example2 -{ - string value; -} -"; - var fixedCode3 = @" -#nullable disable + #nullable disable -class Example3 -{ -#nullable restore - string? value; -#nullable disable -} -"; - var fixedCode4 = @" -#nullable disable + """; + var fixedCode2 = """ -class Example4 -{ - string value; -} -"; + #nullable disable + + class Example2 + { + string value; + } + + """; + var fixedCode3 = """ + + #nullable disable + + class Example3 + { + #nullable restore + string? value; + #nullable disable + } + + """; + var fixedCode4 = """ + + #nullable disable + + class Example4 + { + string value; + } + + """; await new VerifyCS.Test { diff --git a/src/Features/CSharpTest/EncapsulateField/EncapsulateFieldTests.cs b/src/Features/CSharpTest/EncapsulateField/EncapsulateFieldTests.cs index 9c8b82ad9cfcb..975fb42dd0eba 100644 --- a/src/Features/CSharpTest/EncapsulateField/EncapsulateFieldTests.cs +++ b/src/Features/CSharpTest/EncapsulateField/EncapsulateFieldTests.cs @@ -47,9 +47,8 @@ internal Task TestAllOptionsOffAsync( } [Theory, CombinatorialData] - public async Task PrivateFieldToPropertyIgnoringReferences(TestHost host) - { - var text = """ + public Task PrivateFieldToPropertyIgnoringReferences(TestHost host) + => TestAllOptionsOffAsync(host, """ class goo { private int b[|a|]r; @@ -59,9 +58,7 @@ void baz() var q = bar; } } - """; - - var expected = """ + """, """ class goo { private int bar; @@ -84,14 +81,11 @@ void baz() var q = bar; } } - """; - await TestAllOptionsOffAsync(host, text, expected, index: 1); - } + """, index: 1); [Theory, CombinatorialData] - public async Task PrivateNullableFieldToPropertyIgnoringReferences(TestHost host) - { - var text = """ + public Task PrivateNullableFieldToPropertyIgnoringReferences(TestHost host) + => TestAllOptionsOffAsync(host, """ #nullable enable class goo { @@ -102,9 +96,7 @@ void baz() var q = bar; } } - """; - - var expected = """ + """, """ #nullable enable class goo { @@ -128,14 +120,11 @@ void baz() var q = bar; } } - """; - await TestAllOptionsOffAsync(host, text, expected, index: 1); - } + """, index: 1); [Theory, CombinatorialData] - public async Task PrivateFieldToPropertyUpdatingReferences(TestHost host) - { - var text = """ + public Task PrivateFieldToPropertyUpdatingReferences(TestHost host) + => TestAllOptionsOffAsync(host, """ class goo { private int b[|a|]r; @@ -145,9 +134,7 @@ void baz() var q = Bar; } } - """; - - var expected = """ + """, """ class goo { private int bar; @@ -170,14 +157,11 @@ void baz() var q = Bar; } } - """; - await TestAllOptionsOffAsync(host, text, expected, index: 0); - } + """, index: 0); [Theory, CombinatorialData] - public async Task TestCodeStyle1(TestHost host) - { - var text = """ + public Task TestCodeStyle1(TestHost host) + => TestInRegularAndScriptAsync(""" class goo { private int b[|a|]r; @@ -187,9 +171,7 @@ void baz() var q = Bar; } } - """; - - var expected = """ + """, """ class goo { private int bar; @@ -212,20 +194,17 @@ void baz() var q = Bar; } } - """; - await TestInRegularAndScriptAsync(text, expected, + """, options: new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption2.Silent } }, testHost: host); - } [Theory, CombinatorialData] - public async Task TestCodeStyle2(TestHost host) - { - var text = """ + public Task TestCodeStyle2(TestHost host) + => TestInRegularAndScriptAsync(""" class goo { private int b[|a|]r; @@ -235,9 +214,7 @@ void baz() var q = Bar; } } - """; - - var expected = """ + """, """ class goo { private int bar; @@ -249,19 +226,16 @@ void baz() var q = Bar; } } - """; - await TestInRegularAndScriptAsync(text, expected, + """, options: new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement }, }, testHost: host); - } [Theory, CombinatorialData] - public async Task PublicFieldIntoPublicPropertyIgnoringReferences(TestHost host) - { - var text = """ + public Task PublicFieldIntoPublicPropertyIgnoringReferences(TestHost host) + => TestAllOptionsOffAsync(host, """ class goo { public int b[|a|]r; @@ -271,9 +245,7 @@ void baz() var q = bar; } } - """; - - var expected = """ + """, """ class goo { private int bar; @@ -296,14 +268,11 @@ void baz() var q = bar; } } - """; - await TestAllOptionsOffAsync(host, text, expected, index: 1); - } + """, index: 1); [Theory, CombinatorialData] - public async Task PublicFieldIntoPublicPropertyUpdatingReferences(TestHost host) - { - var text = """ + public Task PublicFieldIntoPublicPropertyUpdatingReferences(TestHost host) + => TestAllOptionsOffAsync(host, """ class goo { public int b[|a|]r; @@ -313,9 +282,7 @@ void baz() var q = bar; } } - """; - - var expected = """ + """, """ class goo { private int bar; @@ -338,21 +305,16 @@ void baz() var q = Bar; } } - """; - await TestAllOptionsOffAsync(host, text, expected, index: 0); - } + """, index: 0); [Theory, CombinatorialData] - public async Task StaticPreserved(TestHost host) - { - var text = """ + public Task StaticPreserved(TestHost host) + => TestAllOptionsOffAsync(host, """ class Program { static int [|goo|]; } - """; - - var expected = """ + """, """ class Program { static int goo; @@ -370,22 +332,17 @@ public static int Goo } } } - """; - await TestAllOptionsOffAsync(host, text, expected); - } + """); [Theory, CombinatorialData] - public async Task UniqueNameGenerated(TestHost host) - { - var text = """ + public Task UniqueNameGenerated(TestHost host) + => TestAllOptionsOffAsync(host, """ class Program { [|int goo|]; string Goo; } - """; - - var expected = """ + """, """ class Program { int goo; @@ -404,21 +361,16 @@ public int Goo1 } } } - """; - await TestAllOptionsOffAsync(host, text, expected); - } + """); [Theory, CombinatorialData] - public async Task GenericField(TestHost host) - { - var text = """ + public Task GenericField(TestHost host) + => TestAllOptionsOffAsync(host, """ class C { private [|T goo|]; } - """; - - var expected = """ + """, """ class C { private T goo; @@ -436,22 +388,17 @@ public T Goo } } } - """; - await TestAllOptionsOffAsync(host, text, expected); - } + """); [Theory, CombinatorialData] - public async Task NewFieldNameIsUnique(TestHost host) - { - var text = """ + public Task NewFieldNameIsUnique(TestHost host) + => TestAllOptionsOffAsync(host, """ class goo { public [|int X|]; private string x; } - """; - - var expected = """ + """, """ class goo { private int x1; @@ -470,21 +417,16 @@ public int X } } } - """; - await TestAllOptionsOffAsync(host, text, expected, index: 0); - } + """, index: 0); [Theory, CombinatorialData] - public async Task RespectReadonly(TestHost host) - { - var text = """ + public Task RespectReadonly(TestHost host) + => TestAllOptionsOffAsync(host, """ class goo { private readonly [|int x|]; } - """; - - var expected = """ + """, """ class goo { private readonly int x; @@ -497,14 +439,11 @@ public int X } } } - """; - await TestAllOptionsOffAsync(host, text, expected, index: 0); - } + """, index: 0); [Theory, CombinatorialData] - public async Task PreserveNewAndConsiderBaseMemberNames(TestHost host) - { - var text = """ + public Task PreserveNewAndConsiderBaseMemberNames(TestHost host) + => TestAllOptionsOffAsync(host, """ class c { protected int goo; @@ -516,9 +455,7 @@ class d : c { protected new int [|goo|]; } - """; - - var expected = """ + """, """ class c { protected int goo; @@ -543,14 +480,11 @@ protected int Goo1 } } } - """; - await TestAllOptionsOffAsync(host, text, expected, index: 0); - } + """, index: 0); [Theory, CombinatorialData] - public async Task EncapsulateMultiplePrivateFields(TestHost host) - { - var text = """ + public Task EncapsulateMultiplePrivateFields(TestHost host) + => TestAllOptionsOffAsync(host, """ class goo { private int [|x, y|]; @@ -561,9 +495,7 @@ void bar() y = 2; } } - """; - - var expected = """ + """, """ class goo { private int x, y; @@ -600,14 +532,11 @@ void bar() Y = 2; } } - """; - await TestAllOptionsOffAsync(host, text, expected, index: 0); - } + """, index: 0); [Theory, CombinatorialData] - public async Task EncapsulateMultiplePrivateFields2(TestHost host) - { - var text = """ + public Task EncapsulateMultiplePrivateFields2(TestHost host) + => TestAllOptionsOffAsync(host, """ class goo { [|private int x; @@ -619,9 +548,7 @@ void bar() y = 2; } } - """; - - var expected = """ + """, """ class goo { private int x; @@ -659,14 +586,11 @@ void bar() Y = 2; } } - """; - await TestAllOptionsOffAsync(host, text, expected, index: 0); - } + """, index: 0); [Theory, CombinatorialData] - public async Task EncapsulateSinglePublicFieldInMultipleVariableDeclarationAndUpdateReferences(TestHost host) - { - var text = """ + public Task EncapsulateSinglePublicFieldInMultipleVariableDeclarationAndUpdateReferences(TestHost host) + => TestAllOptionsOffAsync(host, """ class goo { public int [|x|], y; @@ -677,9 +601,7 @@ void bar() y = 2; } } - """; - - var expected = """ + """, """ class goo { public int y; @@ -704,21 +626,16 @@ void bar() y = 2; } } - """; - await TestAllOptionsOffAsync(host, text, expected, index: 0); - } + """, index: 0); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/694057"), CombinatorialData] - public async Task ConstFieldNoGetter(TestHost host) - { - var text = """ + public Task ConstFieldNoGetter(TestHost host) + => TestAllOptionsOffAsync(host, """ class Program { private const int [|bar|] = 3; } - """; - - var expected = """ + """, """ class Program { private const int bar = 3; @@ -731,21 +648,16 @@ public static int Bar } } } - """; - await TestAllOptionsOffAsync(host, text, expected, index: 0); - } + """, index: 0); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/694276"), CombinatorialData] - public async Task EncapsulateFieldNamedValue(TestHost host) - { - var text = """ + public Task EncapsulateFieldNamedValue(TestHost host) + => TestAllOptionsOffAsync(host, """ class Program { private const int [|bar|] = 3; } - """; - - var expected = """ + """, """ class Program { private const int bar = 3; @@ -758,21 +670,16 @@ public static int Bar } } } - """; - await TestAllOptionsOffAsync(host, text, expected, index: 0); - } + """, index: 0); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/694276"), CombinatorialData] - public async Task PublicFieldNamed__(TestHost host) - { - var text = """ + public Task PublicFieldNamed__(TestHost host) + => TestAllOptionsOffAsync(host, """ class Program { public int [|__|]; } - """; - - var expected = """ + """, """ class Program { private int __1; @@ -790,34 +697,25 @@ public int __ } } } - """; - await TestAllOptionsOffAsync(host, text, expected, index: 0); - } + """, index: 0); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/695046"), CombinatorialData] - public async Task AvailableNotJustOnVariableName(TestHost host) - { - var text = """ + public Task AvailableNotJustOnVariableName(TestHost host) + => TestActionCountAsync(""" class Program { pri[||]vate int x; } - """; - - await TestActionCountAsync(text, 2, new TestParameters(testHost: host)); - } + """, 2, new TestParameters(testHost: host)); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/705898"), CombinatorialData] - public async Task CopyFieldAccessibility(TestHost host) - { - var text = """ + public Task CopyFieldAccessibility(TestHost host) + => TestAllOptionsOffAsync(host, """ class Program { protected const int [|bar|] = 3; } - """; - - var expected = """ + """, """ class Program { private const int bar = 3; @@ -830,14 +728,11 @@ protected static int Bar } } } - """; - await TestAllOptionsOffAsync(host, text, expected, index: 0); - } + """, index: 0); [Theory, CombinatorialData] - public async Task UpdateReferencesCrossProject(TestHost host) - { - var text = """ + public Task UpdateReferencesCrossProject(TestHost host) + => TestAllOptionsOffAsync(host, """ @@ -861,9 +756,7 @@ void bar() - """; - - var expected = """ + """, """ @@ -900,21 +793,16 @@ void bar() - """; - await TestAllOptionsOffAsync(host, text, expected, new CodeAnalysis.CSharp.CSharpParseOptions(), TestOptions.ReleaseExe); - } + """, new CodeAnalysis.CSharp.CSharpParseOptions(), TestOptions.ReleaseExe); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/713269"), CombinatorialData] - public async Task PreserveUnsafe(TestHost host) - { - var text = """ + public Task PreserveUnsafe(TestHost host) + => TestAllOptionsOffAsync(host, """ class C { unsafe int* [|goo|]; } - """; - - var expected = """ + """, """ class C { unsafe int* goo; @@ -932,14 +820,11 @@ public unsafe int* Goo } } } - """; - await TestAllOptionsOffAsync(host, text, expected, index: 0); - } + """, index: 0); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/713240"), CombinatorialData] - public async Task ConsiderReturnTypeAccessibility(TestHost host) - { - var text = """ + public Task ConsiderReturnTypeAccessibility(TestHost host) + => TestAllOptionsOffAsync(host, """ public class Program { private State [|state|]; @@ -949,9 +834,7 @@ internal enum State { WA } - """; - - var expected = """ + """, """ public class Program { private State state; @@ -974,14 +857,11 @@ internal enum State { WA } - """; - await TestAllOptionsOffAsync(host, text, expected, index: 0); - } + """, index: 0); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/713191"), CombinatorialData] - public async Task DoNotReferToReadOnlyPropertyInConstructor(TestHost host) - { - var text = """ + public Task DoNotReferToReadOnlyPropertyInConstructor(TestHost host) + => TestAllOptionsOffAsync(host, """ class Program { public readonly int [|Field|]; @@ -991,9 +871,7 @@ public Program(int f) this.Field = f; } } - """; - - var expected = """ + """, """ class Program { private readonly int field; @@ -1011,14 +889,11 @@ public int Field } } } - """; - await TestAllOptionsOffAsync(host, text, expected, index: 0); - } + """, index: 0); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/713191"), CombinatorialData] - public async Task DoNotReferToStaticReadOnlyPropertyInConstructor(TestHost host) - { - var text = """ + public Task DoNotReferToStaticReadOnlyPropertyInConstructor(TestHost host) + => TestAllOptionsOffAsync(host, """ class Program { public static readonly int [|Field|]; @@ -1028,9 +903,7 @@ static Program() Field = 3; } } - """; - - var expected = """ + """, """ class Program { private static readonly int field; @@ -1048,21 +921,17 @@ public static int Field } } } - """; - await TestAllOptionsOffAsync(host, text, expected, index: 0); - } + """, index: 0); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/765959"), CombinatorialData] - public async Task GenerateInTheCorrectPart(TestHost host) - { - var text = """ + public Task GenerateInTheCorrectPart(TestHost host) + => TestAllOptionsOffAsync(host, """ partial class Program {} partial class Program { private int [|x|]; } - """; - var expected = """ + """, """ partial class Program {} partial class Program { @@ -1081,41 +950,30 @@ public int X } } } - """; - await TestAllOptionsOffAsync(host, text, expected); - } + """); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829178"), CombinatorialData] - public async Task ErrorTolerance(TestHost host) - { - var text = """ + public Task ErrorTolerance(TestHost host) + => TestActionCountAsync(""" class Program { a b c [|b|] } - """; - - await TestActionCountAsync(text, count: 2, new TestParameters(testHost: host)); - } + """, count: 2, new TestParameters(testHost: host)); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834072"), CombinatorialData] - public async Task DuplicateFieldErrorTolerance(TestHost host) - { - var text = """ + public Task DuplicateFieldErrorTolerance(TestHost host) + => TestActionCountAsync(""" class Program { public const string [|s|] = "S"; public const string s = "S"; } - """; - - await TestActionCountAsync(text, count: 2, new TestParameters(testHost: host)); - } + """, count: 2, new TestParameters(testHost: host)); [Theory, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/862517"), CombinatorialData] - public async Task Trivia(TestHost host) - { - var text = """ + public Task Trivia(TestHost host) + => TestAllOptionsOffAsync(host, """ namespace ConsoleApplication1 { class Program @@ -1124,9 +982,7 @@ class Program public int myI[||]nt; } } - """; - - var expected = """ + """, """ namespace ConsoleApplication1 { class Program @@ -1148,10 +1004,7 @@ public int MyInt } } } - """; - - await TestAllOptionsOffAsync(host, text, expected); - } + """); [Theory, WorkItem(1096007, "https://github.com/dotnet/roslyn/issues/282"), CombinatorialData] public async Task DoNotEncapsulateOutsideTypeDeclaration(TestHost host) @@ -1347,9 +1200,8 @@ public int Σκύλος } [Theory, CombinatorialData] - public async Task TestEncapsulateEscapedIdentifier(TestHost host) - { - await TestAllOptionsOffAsync(host, """ + public Task TestEncapsulateEscapedIdentifier(TestHost host) + => TestAllOptionsOffAsync(host, """ class C { int [|@class|]; @@ -1373,12 +1225,10 @@ public int Class } } """); - } [Theory, CombinatorialData] - public async Task TestEncapsulateEscapedIdentifierAndQualifiedAccess(TestHost host) - { - await TestAllOptionsOffAsync(host, """ + public Task TestEncapsulateEscapedIdentifierAndQualifiedAccess(TestHost host) + => TestAllOptionsOffAsync(host, """ class C { int [|@class|]; @@ -1402,12 +1252,10 @@ public int Class } } """, options: Option(CodeStyleOptions2.QualifyFieldAccess, true, NotificationOption2.Error)); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/7090"), CombinatorialData] - public async Task ApplyCurrentThisPrefixStyle(TestHost host) - { - await TestAllOptionsOffAsync(host, + public Task ApplyCurrentThisPrefixStyle(TestHost host) + => TestAllOptionsOffAsync(host, """ class C { @@ -1433,12 +1281,10 @@ public int I } } """, options: Option(CodeStyleOptions2.QualifyFieldAccess, true, NotificationOption2.Error)); - } [Theory, CombinatorialData, CompilerTrait(CompilerFeature.Tuples)] - public async Task TestTuple(TestHost host) - { - var text = """ + public Task TestTuple(TestHost host) + => TestAllOptionsOffAsync(host, """ class C { private (int, string) b[|o|]b; @@ -1448,9 +1294,7 @@ void M() var q = bob; } } - """; - - var expected = """ + """, """ class C { private (int, string) bob; @@ -1473,14 +1317,11 @@ void M() var q = bob; } } - """; - await TestAllOptionsOffAsync(host, text, expected, index: 1); - } + """, index: 1); [Theory, CombinatorialData, CompilerTrait(CompilerFeature.Tuples)] - public async Task TupleWithNames(TestHost host) - { - var text = """ + public Task TupleWithNames(TestHost host) + => TestAllOptionsOffAsync(host, """ class C { private (int a, string b) b[|o|]b; @@ -1490,9 +1331,7 @@ void M() var q = bob.b; } } - """; - - var expected = """ + """, """ class C { private (int a, string b) bob; @@ -1515,14 +1354,11 @@ void M() var q = bob.b; } } - """; - await TestAllOptionsOffAsync(host, text, expected, index: 1); - } + """, index: 1); [Theory, CombinatorialData, CompilerTrait(CompilerFeature.FunctionPointers)] - public async Task FunctionPointer(TestHost host) - { - var text = """ + public Task FunctionPointer(TestHost host) + => TestAllOptionsOffAsync(host, """ unsafe class C { private delegate* f[|i|]eld; @@ -1532,9 +1368,7 @@ void M() var q = field; } } - """; - - var expected = """ + """, """ unsafe class C { private delegate* f[|i|]eld; @@ -1557,14 +1391,11 @@ void M() var q = field; } } - """; - await TestAllOptionsOffAsync(host, text, expected, index: 1); - } + """, index: 1); [Theory, CombinatorialData, CompilerTrait(CompilerFeature.FunctionPointers)] - public async Task FunctionPointerWithPrivateTypeParameter(TestHost host) - { - var text = """ + public Task FunctionPointerWithPrivateTypeParameter(TestHost host) + => TestAllOptionsOffAsync(host, """ unsafe class C { private struct S { } @@ -1575,9 +1406,7 @@ void M() var q = field; } } - """; - - var expected = """ + """, """ unsafe class C { private struct S { } @@ -1601,14 +1430,11 @@ void M() var q = field; } } - """; - await TestAllOptionsOffAsync(host, text, expected, index: 1); - } + """, index: 1); [Theory, CombinatorialData, CompilerTrait(CompilerFeature.FunctionPointers)] - public async Task FunctionPointerWithPrivateTypeReturnValue(TestHost host) - { - var text = """ + public Task FunctionPointerWithPrivateTypeReturnValue(TestHost host) + => TestAllOptionsOffAsync(host, """ unsafe class C { private struct S { } @@ -1619,9 +1445,7 @@ void M() var q = field; } } - """; - - var expected = """ + """, """ unsafe class C { private struct S { } @@ -1645,14 +1469,11 @@ void M() var q = field; } } - """; - await TestAllOptionsOffAsync(host, text, expected, index: 1); - } + """, index: 1); [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/75210")] - public async Task PrimaryConstructor(TestHost host, bool andUseProperty) - { - await TestAllOptionsOffAsync(host, """ + public Task PrimaryConstructor(TestHost host, bool andUseProperty) + => TestAllOptionsOffAsync(host, """ public class C(object o) { public readonly int [|A|] = 1; @@ -1672,5 +1493,4 @@ public int A } """, index: andUseProperty ? 0 : 1); - } } diff --git a/src/Features/CSharpTest/ExtractClass/ExtractClassTests.cs b/src/Features/CSharpTest/ExtractClass/ExtractClassTests.cs index f2391000aeadf..e4159d9780417 100644 --- a/src/Features/CSharpTest/ExtractClass/ExtractClassTests.cs +++ b/src/Features/CSharpTest/ExtractClass/ExtractClassTests.cs @@ -57,16 +57,6 @@ protected override Task CreateWorkspaceImplAsync() [Fact] public async Task TestSingleMethod() { - var input = """ - class Test - { - int [||]Method() - { - return 1 + 1; - } - } - """; - var expected1 = """ class Test : MyBase { @@ -84,7 +74,15 @@ int Method() await new Test { - TestCode = input, + TestCode = """ + class Test + { + int [||]Method() + { + return 1 + 1; + } + } + """, FixedState = { Sources = @@ -98,9 +96,10 @@ int Method() } [Fact] - public async Task TestErrorBaseMethod() - { - var input = """ + public Task TestErrorBaseMethod() + => new Test + { + TestCode = """ class ErrorBase { } @@ -112,17 +111,14 @@ class Test : ErrorBase return 1 + 1; } } - """; - await new Test - { - TestCode = input, + """, }.RunAsync(); - } [Fact] - public async Task TestMiscellaneousFiles() - { - var input = """ + public Task TestMiscellaneousFiles() + => new Test + { + TestCode = """ class Test { int [||]Method() @@ -130,8 +126,8 @@ class Test return 1 + 1; } } - """; - var expected = """ + """, + FixedCode = """ internal class MyBase { int Method() @@ -143,15 +139,9 @@ int Method() class Test : MyBase { } - """; - - await new Test - { - TestCode = input, - FixedCode = expected, + """, WorkspaceKind = WorkspaceKind.MiscellaneousFiles }.RunAsync(); - } [Fact] public async Task TestPartialClass() @@ -226,15 +216,6 @@ int Method2() [Fact] public async Task TestRecord_Method() { - var input = """ - record R(string S) - { - void $$M() - { - } - } - """; - var expected1 = """ record R(string S) : MyBase { @@ -253,7 +234,14 @@ void M() await new Test { - TestCode = input, + TestCode = """ + record R(string S) + { + void $$M() + { + } + } + """, LanguageVersion = LanguageVersion.CSharp9, ReferenceAssemblies = ReferenceAssemblies.Net.Net50, FixedState = @@ -271,15 +259,6 @@ void M() [Fact] public async Task TestClass_Method() { - var input = """ - class R(string S) - { - void $$M() - { - } - } - """; - var expected1 = """ class R(string S) : MyBase { @@ -297,7 +276,14 @@ void M() await new Test { - TestCode = input, + TestCode = """ + class R(string S) + { + void $$M() + { + } + } + """, LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net50, FixedState = @@ -315,13 +301,6 @@ void M() [Fact] public async Task TestRecord_Property() { - var input = """ - record R - { - public string $$S { get; set; } - } - """; - var expected1 = """ record R : MyBase { @@ -338,7 +317,12 @@ internal record MyBase await new Test { - TestCode = input, + TestCode = """ + record R + { + public string $$S { get; set; } + } + """, LanguageVersion = LanguageVersion.CSharp9, ReferenceAssemblies = ReferenceAssemblies.Net.Net50, FixedState = @@ -356,13 +340,6 @@ internal record MyBase [Fact(Skip = "https://github.com/dotnet/roslyn/issues/62415")] public async Task TestRecord_PropertyAndImplicitField() { - var input = """ - record R(string S) - { - public string $$S { get; set; } = S; - } - """; - var expected1 = """ record R(string S) : MyBase(S) { @@ -379,7 +356,12 @@ record MyBase(string S) await new Test { - TestCode = input, + TestCode = """ + record R(string S) + { + public string $$S { get; set; } = S; + } + """, LanguageVersion = LanguageVersion.CSharp9, ReferenceAssemblies = ReferenceAssemblies.Net.Net50, FixedState = @@ -396,13 +378,6 @@ record MyBase(string S) [Fact(Skip = "https://github.com/dotnet/roslyn/issues/62415")] public async Task TestClass_PropertyAndImplicitField() { - var input = """ - class R(string S) - { - public string $$S { get; set; } = S; - } - """; - var expected1 = """ class R(string S) : MyBase(S) { @@ -418,7 +393,12 @@ class MyBase(string S) await new Test { - TestCode = input, + TestCode = """ + class R(string S) + { + public string $$S { get; set; } = S; + } + """, LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net50, FixedState = @@ -433,143 +413,101 @@ class MyBase(string S) } [Fact] - public async Task TestRecordParam() - { - // https://github.com/dotnet/roslyn/issues/62415 to make this scenario work - var input = """ + public Task TestRecordParam() + => new Test + { + TestCode = """ record R(string $$S) { } - """; - - await new Test - { - TestCode = input, + """, LanguageVersion = LanguageVersion.CSharp9, ReferenceAssemblies = ReferenceAssemblies.Net.Net50, }.RunAsync(); - } [Fact] - public async Task TestClassParam1() - { - var input = """ + public Task TestClassParam1() + => new Test + { + TestCode = """ class R(string $$S) { } - """; - - await new Test - { - TestCode = input, + """, LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net50, }.RunAsync(); - } [Fact] - public async Task TestClassParam2() - { - var input = """ - class R(string $$S); - """; - - await new Test + public Task TestClassParam2() + => new Test { - TestCode = input, + TestCode = """ + class R(string $$S); + """, LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net50, }.RunAsync(); - } [Fact] - public async Task TestStructParam1() - { - var input = """ + public Task TestStructParam1() + => new Test + { + TestCode = """ struct R(string $$S) { } - """; - - await new Test - { - TestCode = input, + """, LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net50, }.RunAsync(); - } [Fact] - public async Task TestStructParam2() - { - var input = """ - struct R(string $$S); - """; - - await new Test + public Task TestStructParam2() + => new Test { - TestCode = input, + TestCode = """ + struct R(string $$S); + """, LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net50, }.RunAsync(); - } [Fact] - public async Task TestRecordStruct() - { - var input = """ + public Task TestRecordStruct() + => new Test + { + TestCode = """ record struct R(string S) { void $$M() { } } - """; - - await new Test - { - TestCode = input, + """, LanguageVersion = LanguageVersion.CSharp10, ReferenceAssemblies = ReferenceAssemblies.Net.Net50, }.RunAsync(); - } [Fact] - public async Task TestStruct() - { - var input = """ + public Task TestStruct() + => new Test + { + TestCode = """ struct R(string S) { void $$M() { } } - """; - - await new Test - { - TestCode = input, + """, LanguageVersion = LanguageVersion.CSharp12, ReferenceAssemblies = ReferenceAssemblies.Net.Net50, }.RunAsync(); - } [Fact] public async Task TestInNamespace() { - var input = """ - namespace MyNamespace - { - class Test - { - int [||]Method() - { - return 1 + 1; - } - } - } - """; - var expected1 = """ namespace MyNamespace { @@ -593,7 +531,18 @@ int Method() await new Test { - TestCode = input, + TestCode = """ + namespace MyNamespace + { + class Test + { + int [||]Method() + { + return 1 + 1; + } + } + } + """, FixedState = { Sources = @@ -609,19 +558,6 @@ int Method() [Fact] public async Task TestInNamespace_FileScopedNamespace1() { - var input = """ - namespace MyNamespace - { - class Test - { - int [||]Method() - { - return 1 + 1; - } - } - } - """; - var expected1 = """ namespace MyNamespace { @@ -644,7 +580,18 @@ int Method() await new Test { - TestCode = input, + TestCode = """ + namespace MyNamespace + { + class Test + { + int [||]Method() + { + return 1 + 1; + } + } + } + """, FixedState = { Sources = @@ -665,19 +612,6 @@ int Method() [Fact] public async Task TestInNamespace_FileScopedNamespace2() { - var input = """ - namespace MyNamespace - { - class Test - { - int [||]Method() - { - return 1 + 1; - } - } - } - """; - var expected1 = """ namespace MyNamespace { @@ -701,7 +635,18 @@ int Method() await new Test { - TestCode = input, + TestCode = """ + namespace MyNamespace + { + class Test + { + int [||]Method() + { + return 1 + 1; + } + } + } + """, FixedState = { Sources = @@ -722,19 +667,6 @@ int Method() [Fact] public async Task TestInNamespace_FileScopedNamespace3() { - var input = """ - namespace MyNamespace - { - class Test - { - int [||]Method() - { - return 1 + 1; - } - } - } - """; - var expected1 = """ namespace MyNamespace { @@ -758,7 +690,18 @@ int Method() await new Test { - TestCode = input, + TestCode = """ + namespace MyNamespace + { + class Test + { + int [||]Method() + { + return 1 + 1; + } + } + } + """, FixedState = { Sources = @@ -779,16 +722,6 @@ int Method() [Fact] public async Task TestAccessibility() { - var input = """ - public class Test - { - int [||]Method() - { - return 1 + 1; - } - } - """; - var expected1 = """ public class Test : MyBase { @@ -806,8 +739,16 @@ int Method() await new Test { - TestCode = input, - FixedState = + TestCode = """ + public class Test + { + int [||]Method() + { + return 1 + 1; + } + } + """, + FixedState = { Sources = { @@ -822,15 +763,6 @@ int Method() [Fact] public async Task TestEvent() { - var input = """ - using System; - - class Test - { - private event EventHandler [||]Event1; - } - """; - var expected1 = """ using System; @@ -849,7 +781,14 @@ internal class MyBase await new Test { - TestCode = input, + TestCode = """ + using System; + + class Test + { + private event EventHandler [||]Event1; + } + """, FixedState = { Sources = @@ -865,13 +804,6 @@ internal class MyBase [Fact] public async Task TestProperty() { - var input = """ - class Test - { - int [||]MyProperty { get; set; } - } - """; - var expected1 = """ class Test : MyBase { @@ -886,7 +818,12 @@ internal class MyBase await new Test { - TestCode = input, + TestCode = """ + class Test + { + int [||]MyProperty { get; set; } + } + """, FixedState = { Sources = @@ -902,13 +839,6 @@ internal class MyBase [Fact] public async Task TestField() { - var input = """ - class Test - { - int [||]MyField; - } - """; - var expected1 = """ class Test : MyBase { @@ -923,7 +853,12 @@ internal class MyBase await new Test { - TestCode = input, + TestCode = """ + class Test + { + int [||]MyField; + } + """, FixedState = { Sources = @@ -939,13 +874,6 @@ internal class MyBase [Fact] public async Task TestFieldSelectInKeywords() { - var input = """ - class Test - { - priva[||]te int MyField; - } - """; - var expected1 = """ class Test : MyBase { @@ -960,7 +888,12 @@ internal class MyBase await new Test { - TestCode = input, + TestCode = """ + class Test + { + priva[||]te int MyField; + } + """, FixedState = { Sources = @@ -976,13 +909,6 @@ internal class MyBase [Fact] public async Task TestFieldSelectAfterSemicolon() { - var input = """ - class Test - { - private int MyField;[||] - } - """; - var expected1 = """ class Test : MyBase { @@ -997,7 +923,12 @@ internal class MyBase await new Test { - TestCode = input, + TestCode = """ + class Test + { + private int MyField;[||] + } + """, FixedState = { Sources = @@ -1013,13 +944,6 @@ internal class MyBase [Fact] public async Task TestFieldSelectEntireDeclaration() { - var input = """ - class Test - { - [|private int MyField;|] - } - """; - var expected1 = """ class Test : MyBase { @@ -1034,7 +958,12 @@ internal class MyBase await new Test { - TestCode = input, + TestCode = """ + class Test + { + [|private int MyField;|] + } + """, FixedState = { Sources = @@ -1050,13 +979,6 @@ internal class MyBase [Fact] public async Task TestFieldSelectMultipleVariables1() { - var input = """ - class Test - { - [|private int MyField1, MyField2;|] - } - """; - var expected1 = """ class Test : MyBase { @@ -1072,7 +994,12 @@ internal class MyBase await new Test { - TestCode = input, + TestCode = """ + class Test + { + [|private int MyField1, MyField2;|] + } + """, FixedState = { Sources = @@ -1088,13 +1015,6 @@ internal class MyBase [Fact] public async Task TestFieldSelectMultipleVariables2() { - var input = """ - class Test - { - private int MyField1, [|MyField2;|] - } - """; - var expected1 = """ class Test : MyBase { @@ -1110,7 +1030,12 @@ internal class MyBase await new Test { - TestCode = input, + TestCode = """ + class Test + { + private int MyField1, [|MyField2;|] + } + """, FixedState = { Sources = @@ -1126,19 +1051,6 @@ internal class MyBase [Fact] public async Task TestFileHeader_FromExistingFile() { - var input = """ - // this is my document header - // that should be copied over - - class Test - { - int [||]Method() - { - return 1 + 1; - } - } - """; - var expected1 = """ // this is my document header // that should be copied over @@ -1162,7 +1074,18 @@ int Method() await new Test { - TestCode = input, + TestCode = """ + // this is my document header + // that should be copied over + + class Test + { + int [||]Method() + { + return 1 + 1; + } + } + """, FixedState = { Sources = @@ -1178,19 +1101,6 @@ int Method() [Fact] public async Task TestFileHeader_FromOption() { - var input = """ - // this is my document header - // that should be ignored - - class Test - { - int [||]Method() - { - return 1 + 1; - } - } - """; - var expected1 = """ // this is my document header // that should be ignored @@ -1213,7 +1123,18 @@ int Method() await new Test { - TestCode = input, + TestCode = """ + // this is my document header + // that should be ignored + + class Test + { + int [||]Method() + { + return 1 + 1; + } + } + """, FixedState = { Sources = @@ -1233,24 +1154,6 @@ int Method() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/55746")] public async Task TestUsingsInsideNamespace() { - var input = """ - // this is my document header - - using System; - using System.Collections.Generic; - - namespace ConsoleApp185 - { - class Program - { - static void [|Main|](string[] args) - { - Console.WriteLine(new List()); - } - } - } - """; - var expected1 = """ // this is my document header @@ -1284,7 +1187,23 @@ static void Main(string[] args) await new Test { - TestCode = input, + TestCode = """ + // this is my document header + + using System; + using System.Collections.Generic; + + namespace ConsoleApp185 + { + class Program + { + static void [|Main|](string[] args) + { + Console.WriteLine(new List()); + } + } + } + """, FixedState = { Sources = @@ -1306,24 +1225,6 @@ static void Main(string[] args) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/55746")] public async Task TestUsingsInsideNamespace_FileScopedNamespace() { - var input = """ - // this is my document header - - using System; - using System.Collections.Generic; - - namespace ConsoleApp185 - { - class Program - { - static void [|Main|](string[] args) - { - Console.WriteLine(new List()); - } - } - } - """; - var expected1 = """ // this is my document header @@ -1358,7 +1259,23 @@ static void Main(string[] args) await new Test { - TestCode = input, + TestCode = """ + // this is my document header + + using System; + using System.Collections.Generic; + + namespace ConsoleApp185 + { + class Program + { + static void [|Main|](string[] args) + { + Console.WriteLine(new List()); + } + } + } + """, FixedState = { Sources = @@ -1379,19 +1296,6 @@ static void Main(string[] args) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/55746")] public async Task TestUsingsInsideNamespace_NoNamespace() { - var input = """ - using System; - using System.Collections.Generic; - - class Program - { - static void [|Main|](string[] args) - { - Console.WriteLine(new List()); - } - } - """; - var expected1 = """ using System; using System.Collections.Generic; @@ -1416,7 +1320,18 @@ static void Main(string[] args) await new Test { - TestCode = input, + TestCode = """ + using System; + using System.Collections.Generic; + + class Program + { + static void [|Main|](string[] args) + { + Console.WriteLine(new List()); + } + } + """, FixedState = { Sources = @@ -1436,25 +1351,6 @@ static void Main(string[] args) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/55746")] public async Task TestUsingsInsideNamespace_MultipleNamespaces() { - var input = """ - using System; - using System.Collections.Generic; - - namespace N1 - { - namespace N2 - { - class Program - { - static void [|Main|](string[] args) - { - Console.WriteLine(new List()); - } - } - } - } - """; - var expected1 = """ using System; using System.Collections.Generic; @@ -1488,11 +1384,28 @@ static void Main(string[] args) await new Test { - TestCode = input, - FixedState = - { - Sources = - { + TestCode = """ + using System; + using System.Collections.Generic; + + namespace N1 + { + namespace N2 + { + class Program + { + static void [|Main|](string[] args) + { + Console.WriteLine(new List()); + } + } + } + } + """, + FixedState = + { + Sources = + { expected1, expected2, } @@ -1508,21 +1421,6 @@ static void Main(string[] args) [Fact] public async Task TestWithInterface() { - var input = """ - interface ITest - { - int Method(); - } - - class Test : ITest - { - public int [||]Method() - { - return 1 + 1; - } - } - """; - var expected1 = """ interface ITest { @@ -1545,7 +1443,20 @@ public int Method() await new Test { - TestCode = input, + TestCode = """ + interface ITest + { + int Method(); + } + + class Test : ITest + { + public int [||]Method() + { + return 1 + 1; + } + } + """, FixedState = { Sources = @@ -1561,20 +1472,6 @@ public int Method() [ConditionalFact(AlwaysSkip = "https://github.com/dotnet/roslyn/issues/45977")] public async Task TestRegion() { - var input = """ - class Test - { - #region MyRegion - int [||]Method() - { - return 1 + 1; - } - - void OtherMethiod() { } - #endregion - } - """; - var expected1 = """ class Test : MyBase { @@ -1599,7 +1496,19 @@ int Method() await new Test { - TestCode = input, + TestCode = """ + class Test + { + #region MyRegion + int [||]Method() + { + return 1 + 1; + } + + void OtherMethiod() { } + #endregion + } + """, FixedState = { Sources = @@ -1615,16 +1524,6 @@ int Method() [Fact] public async Task TestMakeAbstract_SingleMethod() { - var input = """ - class Test - { - public int [||]Method() - { - return 1 + 1; - } - } - """; - var expected1 = """ class Test : MyBase { @@ -1643,7 +1542,15 @@ internal abstract class MyBase await new Test { - TestCode = input, + TestCode = """ + class Test + { + public int [||]Method() + { + return 1 + 1; + } + } + """, FixedState = { Sources = @@ -1660,19 +1567,6 @@ internal abstract class MyBase [Fact] public async Task TestMakeAbstract_MultipleMethods() { - var input = """ - class Test - { - public int [||]Method() - { - return 1 + 1; - } - - public int Method2() => 2; - public int Method3() => 3; - } - """; - var expected1 = """ class Test : MyBase { @@ -1696,7 +1590,18 @@ internal abstract class MyBase await new Test { - TestCode = input, + TestCode = """ + class Test + { + public int [||]Method() + { + return 1 + 1; + } + + public int Method2() => 2; + public int Method3() => 3; + } + """, FixedState = { Sources = @@ -1713,18 +1618,6 @@ internal abstract class MyBase [Fact] public async Task TestMultipleMethods() { - var input = """ - class Test - { - int [||]Method() - { - return Method2() + 1; - } - - int Method2() => 1; - } - """; - var expected1 = """ class Test : MyBase { @@ -1744,7 +1637,17 @@ int Method() await new Test { - TestCode = input, + TestCode = """ + class Test + { + int [||]Method() + { + return Method2() + 1; + } + + int Method2() => 1; + } + """, FixedState = { Sources = @@ -1761,18 +1664,6 @@ int Method() [Fact] public async Task TestMultipleMethods_SomeSelected() { - var input = """ - class Test - { - int [||]Method() - { - return Method2() + 1; - } - - int Method2() => 1; - } - """; - var expected1 = """ class Test : MyBase { @@ -1792,7 +1683,17 @@ internal class MyBase await new Test { - TestCode = input, + TestCode = """ + class Test + { + int [||]Method() + { + return Method2() + 1; + } + + int Method2() => 1; + } + """, FixedState = { Sources = @@ -1809,19 +1710,6 @@ internal class MyBase [Fact] public async Task TestSelection_CompleteMethodAndComments() { - var input = """ - class Test - { - [|/// - /// this is a test method - /// - int Method() - { - return 1 + 1; - }|] - } - """; - var expected1 = """ class Test : MyBase { @@ -1842,7 +1730,18 @@ int Method() await new Test { - TestCode = input, + TestCode = """ + class Test + { + [|/// + /// this is a test method + /// + int Method() + { + return 1 + 1; + }|] + } + """, FixedState = { Sources = @@ -1858,19 +1757,6 @@ int Method() [Fact] public async Task TestSelection_PartialMethodAndComments() { - var input = """ - class Test - { - [|/// - /// this is a test method - /// - int Method() - {|] - return 1 + 1; - } - } - """; - var expected1 = """ class Test : MyBase { @@ -1891,7 +1777,18 @@ int Method() await new Test { - TestCode = input, + TestCode = """ + class Test + { + [|/// + /// this is a test method + /// + int Method() + {|] + return 1 + 1; + } + } + """, FixedState = { Sources = @@ -1907,19 +1804,6 @@ int Method() [Fact] public async Task TestSelection_PartialMethodAndComments2() { - var input = """ - class Test - { - /// - /// [|this is a test method - /// - int Method() - {|] - return 1 + 1; - } - } - """; - var expected1 = """ class Test : MyBase { @@ -1940,7 +1824,18 @@ int Method() await new Test { - TestCode = input, + TestCode = """ + class Test + { + /// + /// [|this is a test method + /// + int Method() + {|] + return 1 + 1; + } + } + """, FixedState = { Sources = @@ -1956,19 +1851,6 @@ int Method() [Fact] public async Task TestSelection_PartialMethodAndComments3() { - var input = """ - class Test - { - /// - /// [|this is a test method - /// - int Method()|] - { - return 1 + 1; - } - } - """; - var expected1 = """ class Test : MyBase { @@ -1989,7 +1871,18 @@ int Method() await new Test { - TestCode = input, + TestCode = """ + class Test + { + /// + /// [|this is a test method + /// + int Method()|] + { + return 1 + 1; + } + } + """, FixedState = { Sources = @@ -2005,17 +1898,22 @@ int Method() [Fact] public async Task TestAttributes() { - var input = """ + var expected1 = """ using System; class TestAttribute : Attribute { } - class Test + class Test : MyBase + { + } + """; + var expected2 = """ + internal class MyBase { /// /// this is a test method /// - [||][TestAttribute] + [TestAttribute] int Method() { return 1 + 1; @@ -2023,32 +1921,25 @@ int Method() } """; - var expected1 = """ + await new Test + { + TestCode = """ using System; class TestAttribute : Attribute { } - class Test : MyBase - { - } - """; - var expected2 = """ - internal class MyBase + class Test { /// /// this is a test method /// - [TestAttribute] + [||][TestAttribute] int Method() { return 1 + 1; } } - """; - - await new Test - { - TestCode = input, + """, FixedState = { Sources = @@ -2064,18 +1955,23 @@ int Method() [Fact] public async Task TestAttributes2() { - var input = """ + var expected1 = """ using System; class TestAttribute : Attribute { } class TestAttribute2 : Attribute { } - class Test + class Test : MyBase + { + } + """; + var expected2 = """ + internal class MyBase { /// /// this is a test method /// - [||][TestAttribute] + [TestAttribute] [TestAttribute2] int Method() { @@ -2084,34 +1980,27 @@ int Method() } """; - var expected1 = """ + await new Test + { + TestCode = """ using System; class TestAttribute : Attribute { } class TestAttribute2 : Attribute { } - class Test : MyBase - { - } - """; - var expected2 = """ - internal class MyBase + class Test { /// /// this is a test method /// - [TestAttribute] + [||][TestAttribute] [TestAttribute2] int Method() { return 1 + 1; } } - """; - - await new Test - { - TestCode = input, + """, FixedState = { Sources = @@ -2127,19 +2016,25 @@ int Method() [ConditionalFact(AlwaysSkip = "https://github.com/dotnet/roslyn/issues/45987")] public async Task TestAttributes3() { - var input = """ + var expected1 = """ using System; class TestAttribute : Attribute { } - class TestAttribute2 : Attribute { } - class Test + class Test : MyBase + { + } + """; + var expected2 = """ + using System; + + internal class MyBase { /// /// this is a test method /// [TestAttribute] - [||][TestAttribute2] + [TestAttribute2] int Method() { return 1 + 1; @@ -2147,35 +2042,27 @@ int Method() } """; - var expected1 = """ + await new Test + { + TestCode = """ using System; class TestAttribute : Attribute { } + class TestAttribute2 : Attribute { } - class Test : MyBase - { - } - """; - var expected2 = """ - using System; - - internal class MyBase + class Test { /// /// this is a test method /// [TestAttribute] - [TestAttribute2] + [||][TestAttribute2] int Method() { return 1 + 1; } } - """; - - await new Test - { - TestCode = input, + """, FixedState = { Sources = @@ -2190,19 +2077,23 @@ int Method() [ConditionalFact(AlwaysSkip = "https://github.com/dotnet/roslyn/issues/45987")] public async Task TestAttributes4() { - var input = """ + var expected1 = """ using System; class TestAttribute : Attribute { } - class TestAttribute2 : Attribute { } - class Test + class Test : MyBase + { + } + """; + var expected2 = """ + internal class MyBase { /// /// this is a test method /// [TestAttribute] - [TestAttribute2][||] + [TestAttribute2] int Method() { return 1 + 1; @@ -2210,33 +2101,27 @@ int Method() } """; - var expected1 = """ + await new Test + { + TestCode = """ using System; class TestAttribute : Attribute { } + class TestAttribute2 : Attribute { } - class Test : MyBase - { - } - """; - var expected2 = """ - internal class MyBase + class Test { /// /// this is a test method /// [TestAttribute] - [TestAttribute2] + [TestAttribute2][||] int Method() { return 1 + 1; } } - """; - - await new Test - { - TestCode = input, + """, FixedState = { Sources = @@ -2249,17 +2134,18 @@ int Method() } [Fact] - public async Task TestSameFile() - { - var input = """ + public Task TestSameFile() + => new Test + { + TestCode = """ class Test { void Method[||]() { } } - """; - var expected = """ + """, + FixedCode = """ internal class MyBase { void Method() @@ -2270,29 +2156,13 @@ void Method() class Test : MyBase { } - """; - - await new Test - { - TestCode = input, - FixedCode = expected, + """, SameFile = true, }.RunAsync(); - } [Fact] public async Task TestClassDeclaration() { - var input = """ - class Test[||] - { - int Method() - { - return 1 + 1; - } - } - """; - var expected1 = """ class Test : MyBase { @@ -2310,7 +2180,15 @@ int Method() await new Test { - TestCode = input, + TestCode = """ + class Test[||] + { + int Method() + { + return 1 + 1; + } + } + """, FixedState = { Sources = @@ -2327,16 +2205,6 @@ int Method() [Fact] public async Task TestClassDeclaration2() { - var input = """ - class [||]Test - { - int Method() - { - return 1 + 1; - } - } - """; - var expected1 = """ class Test : MyBase { @@ -2354,7 +2222,15 @@ int Method() await new Test { - TestCode = input, + TestCode = """ + class [||]Test + { + int Method() + { + return 1 + 1; + } + } + """, FixedState = { Sources = @@ -2371,16 +2247,6 @@ int Method() [Fact] public async Task TestClassDeclaration3() { - var input = """ - [||]class Test - { - int Method() - { - return 1 + 1; - } - } - """; - var expected1 = """ class Test : MyBase { @@ -2398,7 +2264,15 @@ int Method() await new Test { - TestCode = input, + TestCode = """ + [||]class Test + { + int Method() + { + return 1 + 1; + } + } + """, FixedState = { Sources = @@ -2414,17 +2288,7 @@ int Method() [Fact] public async Task TestClassDeclaration4() - { - var input = """ - class[||] Test - { - int Method() - { - return 1 + 1; - } - } - """; - + { var expected1 = """ class Test : MyBase { @@ -2442,7 +2306,15 @@ int Method() await new Test { - TestCode = input, + TestCode = """ + class[||] Test + { + int Method() + { + return 1 + 1; + } + } + """, FixedState = { Sources = @@ -2459,21 +2331,6 @@ int Method() [Fact] public async Task TestClassDeclaration_Comment() { - var input = """ - using System; - - /// - /// [|This is a test class - /// - class Test|] - { - int Method() - { - return 1 + 1; - } - } - """; - var expected1 = """ using System; @@ -2496,7 +2353,20 @@ int Method() await new Test { - TestCode = input, + TestCode = """ + using System; + + /// + /// [|This is a test class + /// + class Test|] + { + int Method() + { + return 1 + 1; + } + } + """, FixedState = { Sources = @@ -2513,21 +2383,6 @@ int Method() [Fact] public async Task TestClassDeclaration_Comment2() { - var input = """ - using System; - - /// - /// This is a test class - /// [| - class Test|] - { - int Method() - { - return 1 + 1; - } - } - """; - var expected1 = """ using System; @@ -2550,7 +2405,20 @@ int Method() await new Test { - TestCode = input, + TestCode = """ + using System; + + /// + /// This is a test class + /// [| + class Test|] + { + int Method() + { + return 1 + 1; + } + } + """, FixedState = { Sources = @@ -2567,21 +2435,6 @@ int Method() [Fact] public async Task TestClassDeclaration_Comment3() { - var input = """ - using System; - - /// - /// This is a [|test class - /// - class|] Test - { - int Method() - { - return 1 + 1; - } - } - """; - var expected1 = """ using System; @@ -2604,7 +2457,20 @@ int Method() await new Test { - TestCode = input, + TestCode = """ + using System; + + /// + /// This is a [|test class + /// + class|] Test + { + int Method() + { + return 1 + 1; + } + } + """, FixedState = { Sources = @@ -2621,21 +2487,6 @@ int Method() [Fact] public async Task TestClassDeclaration_Attribute() { - var input = """ - using System; - - public class MyAttribute : Attribute { } - - [||][MyAttribute] - class Test - { - int Method() - { - return 1 + 1; - } - } - """; - var expected1 = """ using System; @@ -2659,7 +2510,20 @@ int Method() await new Test { - TestCode = input, + TestCode = """ + using System; + + public class MyAttribute : Attribute { } + + [||][MyAttribute] + class Test + { + int Method() + { + return 1 + 1; + } + } + """, FixedState = { Sources = @@ -2676,16 +2540,6 @@ int Method() [Fact] public async Task TestClassDeclaration_SelectWithMembers() { - var input = """ - [|class Test - { - int Method() - { - return 1 + 1; - } - }|] - """; - var expected1 = """ class Test : MyBase { @@ -2703,7 +2557,15 @@ int Method() await new Test { - TestCode = input, + TestCode = """ + [|class Test + { + int Method() + { + return 1 + 1; + } + }|] + """, FixedState = { Sources = @@ -2720,16 +2582,6 @@ int Method() [Fact] public async Task TestClassDeclaration_SelectWithMembers2() { - var input = """ - [|class Test - { - int Method() - { - return 1 + 1; - }|] - } - """; - var expected1 = """ class Test : MyBase { @@ -2747,7 +2599,15 @@ int Method() await new Test { - TestCode = input, + TestCode = """ + [|class Test + { + int Method() + { + return 1 + 1; + }|] + } + """, FixedState = { Sources = @@ -2764,19 +2624,6 @@ int Method() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/55871")] public async Task TestGenericClass() { - var input = """ - using System.Collections.Generic; - - [|class C - { - public List Field1; - public T2 Field2; - public T3 Method() - { - return default; - }|] - } - """; var expected1 = """ using System.Collections.Generic; @@ -2799,7 +2646,19 @@ public T3 Method() """; await new Test { - TestCode = input, + TestCode = """ + using System.Collections.Generic; + + [|class C + { + public List Field1; + public T2 Field2; + public T3 Method() + { + return default; + }|] + } + """, FixedState = { Sources = @@ -2814,24 +2673,22 @@ public T3 Method() } [Fact] - public async Task TestIncompleteFieldSelection_NoAction1() - { - var input = """ + public Task TestIncompleteFieldSelection_NoAction1() + => new Test + { + TestCode = """ class C { pub[||] {|CS1519:int|} Foo = 0; } - """; - await new Test - { - TestCode = input + """ }.RunAsync(); - } [Fact] - public async Task TestIncompleteMethodSelection_NoAction() - { - var input = """ + public Task TestIncompleteMethodSelection_NoAction() + => new Test + { + TestCode = """ class C { pub[||] {|CS1519:int|} Foo() @@ -2839,42 +2696,26 @@ class C return 5; } } - """; - await new Test - { - TestCode = input + """ }.RunAsync(); - } [Fact] - public async Task TestTopLevelStatementSelection_NoAction() - { - var input = """ - [||]_ = 42; - """; - await new Test + public Task TestTopLevelStatementSelection_NoAction() + => new Test { - TestCode = input, + TestCode = """ + [||]_ = 42; + """, LanguageVersion = LanguageVersion.CSharp10, TestState = { OutputKind = OutputKind.ConsoleApplication } }.RunAsync(); - } [Fact] public async Task TestSealed() { - var input = """ - internal sealed class MyClass - { - public void [||]M() - { - } - } - """; - var expected1 = """ internal sealed class MyClass : MyBase { @@ -2892,7 +2733,14 @@ public void M() await new Test { - TestCode = input, + TestCode = """ + internal sealed class MyClass + { + public void [||]M() + { + } + } + """, FixedState = { Sources = @@ -2906,9 +2754,8 @@ public void M() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63315")] - public async Task TestMethodInsideNamespace_NoException() - { - await new Test() + public Task TestMethodInsideNamespace_NoException() + => new Test() { TestCode = """ namespace N @@ -2972,12 +2819,12 @@ public void N }, FileName = "Test1.cs" }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/55610")] - public async Task TestMultipleMethodsSelected_WithTypeContainingBaseClass() - { - var code = """ + public Task TestMultipleMethodsSelected_WithTypeContainingBaseClass() + => new Test() + { + TestCode = """ class Base { } @@ -2987,18 +2834,14 @@ class Derived : Base [|public void M() { } public void N() { }|] } - """; - - await new Test() - { - TestCode = code + """ }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/55610")] - public async Task TestClassSelected_WithTypeContainingBaseClass() - { - var code = """ + public Task TestClassSelected_WithTypeContainingBaseClass() + => new Test() + { + TestCode = """ class Base { } @@ -3008,26 +2851,12 @@ class $$Derived : Base public void M() { } public void N() { } } - """; - - await new Test() - { - TestCode = code + """ }.RunAsync(); - } [Fact] public async Task TestMultipleMethodsSelected_HighlightedMembersAreSelected() { - var code = """ - class C - { - [|public void M() { } - public void N() { }|] - public void O() { } - } - """; - var expected1 = """ class C : MyBase { @@ -3045,7 +2874,14 @@ public void N() { } await new Test() { - TestCode = code, + TestCode = """ + class C + { + [|public void M() { } + public void N() { }|] + public void O() { } + } + """, FixedState = { Sources = @@ -3061,13 +2897,6 @@ public void N() { } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/55402")] public async Task TestMemberKeyword() { - var code = """ - class C - { - $$public void M() { } - } - """; - var expected1 = """ class C : MyBase { @@ -3083,7 +2912,12 @@ public void M() { } await new Test { - TestCode = code, + TestCode = """ + class C + { + $$public void M() { } + } + """, FixedState = { Sources = diff --git a/src/Features/CSharpTest/ExtractMethod/ExtractLocalFunctionTests.cs b/src/Features/CSharpTest/ExtractMethod/ExtractLocalFunctionTests.cs index c6586b0c3f0e1..a9bb9d4a4062a 100644 --- a/src/Features/CSharpTest/ExtractMethod/ExtractLocalFunctionTests.cs +++ b/src/Features/CSharpTest/ExtractMethod/ExtractLocalFunctionTests.cs @@ -67,9 +67,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor """; [Fact] - public async Task TestPartialSelection_StaticOptionTrue() - { - await TestInRegularAndScript1Async( + public Task TestPartialSelection_StaticOptionTrue() + => TestInRegularAndScript1Async( """ class Program { @@ -95,12 +94,10 @@ static bool NewMethod(bool b) } } """, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOption2.TrueWithSilentEnforcement))); - } [Fact] - public async Task TestPartialSelection_StaticOptionFalse() - { - await TestInRegularAndScript1Async( + public Task TestPartialSelection_StaticOptionFalse() + => TestInRegularAndScript1Async( """ class Program { @@ -126,12 +123,10 @@ bool NewMethod(bool b) } } """, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOption2.FalseWithSilentEnforcement))); - } [Fact] - public async Task TestPartialSelection_StaticOptionDefault() - { - await TestInRegularAndScript1Async( + public Task TestPartialSelection_StaticOptionDefault() + => TestInRegularAndScript1Async( """ class Program { @@ -157,12 +152,10 @@ static bool NewMethod(bool b) } } """, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CSharpCodeStyleOptions.PreferStaticLocalFunction.DefaultValue))); - } [Fact] - public async Task TestUseExpressionBodyWhenPossible() - { - await TestInRegularAndScript1Async( + public Task TestUseExpressionBodyWhenPossible() + => TestInRegularAndScript1Async( """ class Program { @@ -185,12 +178,10 @@ static void Main(string[] args) } } """, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement))); - } [Fact] - public async Task TestUseExpressionWhenOnSingleLine_AndIsOnSingleLine() - { - await TestInRegularAndScript1Async( + public Task TestUseExpressionWhenOnSingleLine_AndIsOnSingleLine() + => TestInRegularAndScript1Async( """ class Program { @@ -213,12 +204,10 @@ static void Main(string[] args) } } """, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); - } [Fact] - public async Task TestUseExpressionWhenOnSingleLine_AndIsOnSingleLine2() - { - await TestInRegularAndScript1Async( + public Task TestUseExpressionWhenOnSingleLine_AndIsOnSingleLine2() + => TestInRegularAndScript1Async( """ class Program { @@ -247,12 +236,10 @@ static void Main(string[] args) } } """, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); - } [Fact] - public async Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine() - { - await TestInRegularAndScript1Async( + public Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine() + => TestInRegularAndScript1Async( """ class Program { @@ -280,12 +267,10 @@ static bool NewMethod(bool b) } } """, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); - } [Fact] - public async Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine2() - { - await TestInRegularAndScript1Async( + public Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine2() + => TestInRegularAndScript1Async( """ class Program { @@ -313,12 +298,10 @@ static bool NewMethod(bool b) } } """, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); - } [Fact] - public async Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine3() - { - await TestInRegularAndScript1Async( + public Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine3() + => TestInRegularAndScript1Async( """ class Program { @@ -346,12 +329,10 @@ static bool NewMethod() } } """, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); - } [Fact] - public async Task TestReadOfDataThatDoesNotFlowIn() - { - await TestInRegularAndScript1Async( + public Task TestReadOfDataThatDoesNotFlowIn() + => TestInRegularAndScript1Async( """ class Program { @@ -389,12 +370,10 @@ private static T fun(T t) } } """, CodeActionIndex); - } [Fact] - public async Task TestOnStatementAfterUnconditionalGoto() - { - await TestInRegularAndScript1Async( + public Task TestOnStatementAfterUnconditionalGoto() + => TestInRegularAndScript1Async( """ delegate int del(int i); @@ -433,12 +412,10 @@ static int NewMethod(int x) } } """, CodeActionIndex); - } [Fact] - public async Task TestOnNamespace() - { - await TestInRegularAndScript1Async( + public Task TestOnNamespace() + => TestInRegularAndScript1Async( """ class Program { @@ -462,12 +439,10 @@ static void NewMethod() } } """, CodeActionIndex); - } [Fact] - public async Task TestOnType() - { - await TestInRegularAndScript1Async( + public Task TestOnType() + => TestInRegularAndScript1Async( """ class Program { @@ -491,12 +466,10 @@ static void NewMethod() } } """, CodeActionIndex); - } [Fact] - public async Task TestOnBase() - { - await TestInRegularAndScript1Async( + public Task TestOnBase() + => TestInRegularAndScript1Async( """ class Program { @@ -520,12 +493,10 @@ void NewMethod() } } """, CodeActionIndex); - } [Fact] - public async Task TestOnActionInvocation() - { - await TestInRegularAndScript1Async( + public Task TestOnActionInvocation() + => TestInRegularAndScript1Async( """ using System; @@ -563,12 +534,10 @@ static Action GetX() } } """, CodeActionIndex); - } [Fact] - public async Task DisambiguateCallSiteIfNecessary1() - { - await TestInRegularAndScript1Async( + public Task DisambiguateCallSiteIfNecessary1() + => TestInRegularAndScript1Async( """ using System; @@ -605,12 +574,10 @@ static Func NewMethod() static void Goo(Func p, Func q, int r, int s) { Console.WriteLine(2); } } """, CodeActionIndex); - } [Fact] - public async Task DisambiguateCallSiteIfNecessary2() - { - await TestInRegularAndScript1Async( + public Task DisambiguateCallSiteIfNecessary2() + => TestInRegularAndScript1Async( """ using System; @@ -647,12 +614,10 @@ static Func NewMethod() static void Goo(Func p, Func q, int r, int s) { Console.WriteLine(2); } } """, CodeActionIndex); - } [Fact] - public async Task DoNotOverParenthesize() - { - await TestAsync( + public Task DoNotOverParenthesize() + => TestAsync( """ using System; @@ -748,12 +713,10 @@ public static void Ex(this int x) """, parseOptions: TestOptions.Regular, index: CodeActionIndex); - } [Fact] - public async Task DoNotOverParenthesizeGenerics() - { - await TestAsync( + public Task DoNotOverParenthesizeGenerics() + => TestAsync( """ using System; @@ -849,12 +812,10 @@ public static void Ex(this int x) """, parseOptions: TestOptions.Regular, index: CodeActionIndex); - } [Fact] - public async Task PreserveCommentsBeforeDeclaration_1() - { - await TestInRegularAndScript1Async( + public Task PreserveCommentsBeforeDeclaration_1() + => TestInRegularAndScript1Async( """ class Construct { @@ -894,12 +855,10 @@ static void NewMethod(out Construct obj1, out Construct obj2) } } """, CodeActionIndex); - } [Fact] - public async Task PreserveCommentsBeforeDeclaration_2() - { - await TestInRegularAndScript1Async( + public Task PreserveCommentsBeforeDeclaration_2() + => TestInRegularAndScript1Async( """ class Construct { @@ -947,12 +906,10 @@ static void NewMethod(out Construct obj1, out Construct obj2, out Construct obj3 } } """, CodeActionIndex); - } [Fact] - public async Task PreserveCommentsBeforeDeclaration_3() - { - await TestInRegularAndScript1Async( + public Task PreserveCommentsBeforeDeclaration_3() + => TestInRegularAndScript1Async( """ class Construct { @@ -997,12 +954,10 @@ static void NewMethod(out Construct obj1, out Construct obj2, out Construct obj3 } } """, CodeActionIndex); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] - public async Task TestTuple() - { - await TestInRegularAndScript1Async( + public Task TestTuple() + => TestInRegularAndScript1Async( """ class Program { @@ -1028,12 +983,10 @@ static void Main(string[] args) } } """ + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] - public async Task TestTupleDeclarationWithNames() - { - await TestInRegularAndScript1Async( + public Task TestTupleDeclarationWithNames() + => TestInRegularAndScript1Async( """ class Program { @@ -1059,12 +1012,10 @@ static void Main(string[] args) } } """ + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] - public async Task TestTupleDeclarationWithSomeNames() - { - await TestInRegularAndScript1Async( + public Task TestTupleDeclarationWithSomeNames() + => TestInRegularAndScript1Async( """ class Program { @@ -1090,12 +1041,10 @@ static void Main(string[] args) } } """ + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] - public async Task TestTupleWith1Arity() - { - await TestInRegularAndScript1Async( + public Task TestTupleWith1Arity() + => TestInRegularAndScript1Async( """ using System; class Program @@ -1123,12 +1072,10 @@ static void NewMethod(ValueTuple y) } } """ + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] - public async Task TestTupleLiteralWithNames() - { - await TestInRegularAndScript1Async( + public Task TestTupleLiteralWithNames() + => TestInRegularAndScript1Async( """ class Program { @@ -1154,12 +1101,10 @@ static void Main(string[] args) } } """ + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] - public async Task TestTupleDeclarationAndLiteralWithNames() - { - await TestInRegularAndScript1Async( + public Task TestTupleDeclarationAndLiteralWithNames() + => TestInRegularAndScript1Async( """ class Program { @@ -1185,12 +1130,10 @@ static void Main(string[] args) } } """ + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] - public async Task TestTupleIntoVar() - { - await TestInRegularAndScript1Async( + public Task TestTupleIntoVar() + => TestInRegularAndScript1Async( """ class Program { @@ -1216,12 +1159,10 @@ static void Main(string[] args) } } """ + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] - public async Task RefactorWithoutSystemValueTuple() - { - await TestInRegularAndScript1Async( + public Task RefactorWithoutSystemValueTuple() + => TestInRegularAndScript1Async( """ class Program { @@ -1247,13 +1188,10 @@ static void Main(string[] args) } } """, CodeActionIndex); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] - public async Task TestTupleWithNestedNamedTuple() - { - // This is not the best refactoring, but this is an edge case - await TestInRegularAndScript1Async( + public Task TestTupleWithNestedNamedTuple() + => TestInRegularAndScript1Async( """ class Program { @@ -1279,12 +1217,10 @@ static void Main(string[] args) } } """ + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] - public async Task TestDeconstruction() - { - await TestInRegularAndScript1Async( + public Task TestDeconstruction() + => TestInRegularAndScript1Async( """ class Program { @@ -1310,12 +1246,10 @@ static void Main(string[] args) } } """ + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] - public async Task TestDeconstruction2() - { - await TestInRegularAndScript1Async( + public Task TestDeconstruction2() + => TestInRegularAndScript1Async( """ class Program { @@ -1343,13 +1277,11 @@ static int NewMethod() } } """ + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); - } [Fact] [CompilerTrait(CompilerFeature.OutVar)] - public async Task TestOutVar() - { - await TestInRegularAndScript1Async( + public Task TestOutVar() + => TestInRegularAndScript1Async( """ class C { @@ -1378,13 +1310,11 @@ static void NewMethod(int i, out int r, out int y) } } """, CodeActionIndex); - } [Fact] [CompilerTrait(CompilerFeature.Patterns)] - public async Task TestIsPattern() - { - await TestInRegularAndScript1Async( + public Task TestIsPattern() + => TestInRegularAndScript1Async( """ class C { @@ -1413,13 +1343,11 @@ static void NewMethod(int i, out int r, out int y) } } """, CodeActionIndex); - } [Fact] [CompilerTrait(CompilerFeature.Patterns)] - public async Task TestOutVarAndIsPattern() - { - await TestInRegularAndScript1Async( + public Task TestOutVarAndIsPattern() + => TestInRegularAndScript1Async( """ class C { @@ -1448,13 +1376,11 @@ static void NewMethod(out int r, out int y, out int z) } } """, CodeActionIndex); - } [Fact] [CompilerTrait(CompilerFeature.Patterns)] - public async Task ConflictingOutVarLocals() - { - await TestInRegularAndScript1Async( + public Task ConflictingOutVarLocals() + => TestInRegularAndScript1Async( """ class C { @@ -1493,13 +1419,11 @@ static void NewMethod(out int r, out int y) } } """, CodeActionIndex); - } [Fact] [CompilerTrait(CompilerFeature.Patterns)] - public async Task ConflictingPatternLocals() - { - await TestInRegularAndScript1Async( + public Task ConflictingPatternLocals() + => TestInRegularAndScript1Async( """ class C { @@ -1538,12 +1462,10 @@ static void NewMethod(out int r, out int y) } } """, CodeActionIndex); - } [Fact] - public async Task TestCancellationTokenGoesLast() - { - await TestInRegularAndScript1Async( + public Task TestCancellationTokenGoesLast() + => TestInRegularAndScript1Async( """ using System; using System.Threading; @@ -1584,12 +1506,10 @@ static void NewMethod(int v, CancellationToken ct) } } """, CodeActionIndex); - } [Fact] - public async Task TestUseVar1() - { - await TestInRegularAndScript1Async( + public Task TestUseVar1() + => TestInRegularAndScript1Async( """ using System; @@ -1635,12 +1555,10 @@ static string NewMethod(int i) } } """, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOption2.TrueWithSuggestionEnforcement))); - } [Fact] - public async Task TestUseVar2() - { - await TestInRegularAndScript1Async( + public Task TestUseVar2() + => TestInRegularAndScript1Async( """ using System; @@ -1686,7 +1604,6 @@ static string NewMethod(int i) } } """, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOption2.TrueWithSuggestionEnforcement))); - } [Fact] public async Task ExtractLocalFunctionCall() @@ -1701,7 +1618,8 @@ void Local() { } } } """; - var expectedCode = """ + await TestExactActionSetOfferedAsync(code, [FeaturesResources.Extract_local_function]); + await TestInRegularAndScript1Async(code, """ class C { public static void Main() @@ -1715,15 +1633,12 @@ void NewMethod() } } } - """; - await TestExactActionSetOfferedAsync(code, [FeaturesResources.Extract_local_function]); - await TestInRegularAndScript1Async(code, expectedCode, CodeActionIndexWhenExtractMethodMissing); + """, CodeActionIndexWhenExtractMethodMissing); } [Fact] - public async Task ExtractLocalFunctionCall_2() - { - await TestInRegularAndScript1Async(""" + public Task ExtractLocalFunctionCall_2() + => TestInRegularAndScript1Async(""" class C { public static void Main() @@ -1747,12 +1662,10 @@ void Local() { } } } """, CodeActionIndex); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39946")] - public async Task ExtractLocalFunctionCall_3() - { - await TestInRegularAndScript1Async(""" + public Task ExtractLocalFunctionCall_3() + => TestInRegularAndScript1Async(""" class C { public static void Main() @@ -1782,12 +1695,10 @@ void Local() { } } } """, CodeActionIndex); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39946")] - public async Task ExtractFunctionUnderLocalFunctionCall() - { - await TestInRegularAndScript1Async(""" + public Task ExtractFunctionUnderLocalFunctionCall() + => TestInRegularAndScript1Async(""" class Test { int Testing; @@ -1837,7 +1748,6 @@ void NewMethod() } } """, CodeActionIndex); - } [Fact] public async Task ExtractLocalFunctionCallWithCapture() @@ -1852,7 +1762,8 @@ public static void Main(string[] args) } } """; - var expectedCode = """ + await TestExactActionSetOfferedAsync(code, [FeaturesResources.Extract_local_function]); + await TestInRegularAndScript1Async(code, """ class C { public static void Main(string[] args) @@ -1866,15 +1777,12 @@ void NewMethod() } } } - """; - await TestExactActionSetOfferedAsync(code, [FeaturesResources.Extract_local_function]); - await TestInRegularAndScript1Async(code, expectedCode, CodeActionIndexWhenExtractMethodMissing); + """, CodeActionIndexWhenExtractMethodMissing); } [Fact] - public async Task ExtractLocalFunctionInterior() - { - await TestInRegularAndScript1Async(""" + public Task ExtractLocalFunctionInterior() + => TestInRegularAndScript1Async(""" class C { public static void Main() @@ -1906,12 +1814,10 @@ static void NewMethod() } } """, CodeActionIndex); - } [Fact] - public async Task ExtractLocalFunctionWithinForLoop() - { - await TestInRegularAndScript1Async(""" + public Task ExtractLocalFunctionWithinForLoop() + => TestInRegularAndScript1Async(""" class Test { void method() @@ -1948,12 +1854,10 @@ static int NewMethod(int v, int i) } } """, CodeActionIndex); - } [Fact] - public async Task ExtractLocalFunctionWithinForLoop2() - { - await TestInRegularAndScript1Async(""" + public Task ExtractLocalFunctionWithinForLoop2() + => TestInRegularAndScript1Async(""" class Test { void method() @@ -1989,12 +1893,10 @@ static int NewMethod(int v, int i) } } """, CodeActionIndex); - } [Fact] - public async Task ExtractLocalFunctionWithinForLoop3() - { - await TestInRegularAndScript1Async(""" + public Task ExtractLocalFunctionWithinForLoop3() + => TestInRegularAndScript1Async(""" class Test { void method() @@ -2030,12 +1932,10 @@ static int NewMethod(ref int v, int i) } } """, CodeActionIndex); - } [Fact] - public async Task TestTupleWithInferredNames() - { - await TestAsync(""" + public Task TestTupleWithInferredNames() + => TestAsync(""" class Program { void M() @@ -2062,12 +1962,10 @@ void M() } } """, TestOptions.Regular7_1, index: CodeActionIndex); - } [Fact] - public async Task TestDeconstruction4() - { - await TestAsync(""" + public Task TestDeconstruction4() + => TestAsync(""" class Program { void M() @@ -2093,12 +1991,10 @@ void NewMethod() } } """, TestOptions.Regular7_1, index: CodeActionIndex); - } [Fact] - public async Task TestDeconstruction5() - { - await TestAsync(""" + public Task TestDeconstruction5() + => TestAsync(""" class Program { void M() @@ -2124,12 +2020,10 @@ void NewMethod() } } """, TestOptions.Regular7_1, index: CodeActionIndex); - } [Fact] - public async Task TestIndexExpression() - { - await TestInRegularAndScript1Async(TestSources.Index + """ + public Task TestIndexExpression() + => TestInRegularAndScript1Async(TestSources.Index + """ class Program { static void Main(string[] args) @@ -2153,12 +2047,10 @@ static System.Index NewMethod() } } """, CodeActionIndex); - } [Fact] - public async Task TestRangeExpression_Empty() - { - await TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + """ + public Task TestRangeExpression_Empty() + => TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + """ class Program { static void Main(string[] args) @@ -2182,12 +2074,10 @@ static System.Range NewMethod() } } """, CodeActionIndex); - } [Fact] - public async Task TestRangeExpression_Left() - { - await TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + """ + public Task TestRangeExpression_Left() + => TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + """ class Program { static void Main(string[] args) @@ -2211,12 +2101,10 @@ static System.Range NewMethod() } } """, CodeActionIndex); - } [Fact] - public async Task TestRangeExpression_Right() - { - await TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + """ + public Task TestRangeExpression_Right() + => TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + """ class Program { static void Main(string[] args) @@ -2240,12 +2128,10 @@ static System.Range NewMethod() } } """, CodeActionIndex); - } [Fact] - public async Task TestRangeExpression_Both() - { - await TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + """ + public Task TestRangeExpression_Both() + => TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + """ class Program { static void Main(string[] args) @@ -2269,7 +2155,6 @@ static System.Range NewMethod() } } """, CodeActionIndex); - } [Fact] public Task TestAnnotatedNullableReturn() @@ -2948,9 +2833,8 @@ static string NewMethod() """, CodeActionIndex); [Fact] - public async Task TestExtractReadOnlyMethod() - { - await TestInRegularAndScript1Async( + public Task TestExtractReadOnlyMethod() + => TestInRegularAndScript1Async( """ struct S1 { @@ -2976,12 +2860,10 @@ readonly void NewMethod() } } """, CodeActionIndex); - } [Fact] - public async Task TestExtractReadOnlyMethodInReadOnlyStruct() - { - await TestInRegularAndScript1Async( + public Task TestExtractReadOnlyMethodInReadOnlyStruct() + => TestInRegularAndScript1Async( """ readonly struct S1 { @@ -3007,12 +2889,10 @@ void NewMethod() } } """, CodeActionIndex); - } [Fact] - public async Task TestExtractNonReadOnlyMethodInReadOnlyMethod() - { - await TestInRegularAndScript1Async( + public Task TestExtractNonReadOnlyMethodInReadOnlyMethod() + => TestInRegularAndScript1Async( """ struct S1 { @@ -3038,7 +2918,6 @@ void NewMethod() } } """, CodeActionIndex); - } [Fact] public Task TestExtractNullableObjectWithExplicitCast() @@ -3380,9 +3259,8 @@ void M() """, CodeActionIndex); [Fact] - public async Task TestExtractLocalFunction_EnsureUniqueFunctionName() - { - await TestInRegularAndScript1Async( + public Task TestExtractLocalFunction_EnsureUniqueFunctionName() + => TestInRegularAndScript1Async( """ class Test { @@ -3416,12 +3294,10 @@ static void NewMethod1() } } """, CodeActionIndex); - } [Fact] - public async Task TestExtractLocalFunctionWithinLocalFunction_EnsureUniqueFunctionName() - { - await TestInRegularAndScript1Async( + public Task TestExtractLocalFunctionWithinLocalFunction_EnsureUniqueFunctionName() + => TestInRegularAndScript1Async( """ class Test { @@ -3463,12 +3339,10 @@ static void NewMethod3() } } """, CodeActionIndex); - } [Fact] - public async Task TestExtractNonStaticLocalMethod_WithDeclaration() - { - await TestInRegularAndScript1Async( + public Task TestExtractNonStaticLocalMethod_WithDeclaration() + => TestInRegularAndScript1Async( """ class Test { @@ -3500,12 +3374,10 @@ void ExistingLocalFunction() } } """, CodeActionIndex); - } [Fact] - public async Task ArgumentlessReturnWithConstIfExpression() - { - await TestInRegularAndScript1Async( + public Task ArgumentlessReturnWithConstIfExpression() + => TestInRegularAndScript1Async( """ using System; @@ -3542,12 +3414,10 @@ static void NewMethod() } } """, CodeActionIndex); - } [Fact] - public async Task TestPartialSelection_StaticOptionTrue_EarlierCSharpVersionShouldBeNonStatic() - { - await TestInRegularAndScript1Async( + public Task TestPartialSelection_StaticOptionTrue_EarlierCSharpVersionShouldBeNonStatic() + => TestInRegularAndScript1Async( """ class Program { @@ -3573,12 +3443,10 @@ bool NewMethod() } } """, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOption2.TrueWithSilentEnforcement), parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_3))); - } [Fact] - public async Task TestPartialSelection_StaticOptionTrue_EarlierCSharpVersionShouldBeNonStatic2() - { - await TestInRegularAndScript1Async( + public Task TestPartialSelection_StaticOptionTrue_EarlierCSharpVersionShouldBeNonStatic2() + => TestInRegularAndScript1Async( """ class Program { @@ -3604,12 +3472,10 @@ bool NewMethod() } } """, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOption2.TrueWithSilentEnforcement), parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7))); - } [Fact] - public async Task TestPartialSelection_StaticOptionTrue_CSharp8AndLaterStaticSupported() - { - await TestInRegularAndScript1Async( + public Task TestPartialSelection_StaticOptionTrue_CSharp8AndLaterStaticSupported() + => TestInRegularAndScript1Async( """ class Program { @@ -3635,12 +3501,10 @@ static bool NewMethod(bool b) } } """, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOption2.TrueWithSilentEnforcement), parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp8))); - } [Fact] - public async Task TestPartialSelection_StaticOptionTrue_CSharp8AndLaterStaticSupported2() - { - await TestInRegularAndScript1Async( + public Task TestPartialSelection_StaticOptionTrue_CSharp8AndLaterStaticSupported2() + => TestInRegularAndScript1Async( """ class Program { @@ -3666,12 +3530,10 @@ static bool NewMethod(bool b) } } """, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOption2.TrueWithSilentEnforcement), parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest))); - } [Fact] - public async Task TestInPropertyInitializer_Get() - { - await TestInRegularAndScript1Async( + public Task TestInPropertyInitializer_Get() + => TestInRegularAndScript1Async( """ using System; @@ -3718,12 +3580,10 @@ double NewMethod() } } """, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOption2.TrueWithSilentEnforcement))); - } [Fact] - public async Task TestInPropertyInitializer_Get2() - { - await TestInRegularAndScript1Async( + public Task TestInPropertyInitializer_Get2() + => TestInRegularAndScript1Async( """ using System; @@ -3770,12 +3630,10 @@ double NewMethod() } } """, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOption2.TrueWithSilentEnforcement))); - } [Fact] - public async Task TestInPropertyInitializer_Set() - { - await TestInRegularAndScript1Async( + public Task TestInPropertyInitializer_Set() + => TestInRegularAndScript1Async( """ using System; @@ -3819,12 +3677,10 @@ static void NewMethod(double value) } } """, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOption2.TrueWithSilentEnforcement))); - } [Fact] - public async Task TestInPropertyInitializer_Set2() - { - await TestInRegularAndScript1Async( + public Task TestInPropertyInitializer_Set2() + => TestInRegularAndScript1Async( """ using System; @@ -3868,12 +3724,10 @@ void NewMethod(double value) } } """, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOption2.TrueWithSilentEnforcement))); - } [Fact] - public async Task TestInIndexer_Get() - { - await TestInRegularAndScript1Async( + public Task TestInIndexer_Get() + => TestInRegularAndScript1Async( """ using System; @@ -3927,12 +3781,10 @@ void NewMethod(int index) } } """, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOption2.TrueWithSilentEnforcement))); - } [Fact] - public async Task TestInIndexer_Get2() - { - await TestInRegularAndScript1Async( + public Task TestInIndexer_Get2() + => TestInRegularAndScript1Async( """ using System; @@ -3986,12 +3838,10 @@ string NewMethod(int index) } } """, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOption2.TrueWithSilentEnforcement))); - } [Fact] - public async Task TestInIndexer_Set() - { - await TestInRegularAndScript1Async( + public Task TestInIndexer_Set() + => TestInRegularAndScript1Async( """ using System; @@ -4045,12 +3895,10 @@ void NewMethod(int index) } } """, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOption2.TrueWithSilentEnforcement))); - } [Fact] - public async Task TestInIndexer_Set2() - { - await TestInRegularAndScript1Async( + public Task TestInIndexer_Set2() + => TestInRegularAndScript1Async( """ using System; @@ -4104,12 +3952,10 @@ void NewMethod(int index, string value) } } """, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOption2.TrueWithSilentEnforcement))); - } [Fact] - public async Task TestPartialSelection_CSharp5NotApplicable() - { - var code = """ + public Task TestPartialSelection_CSharp5NotApplicable() + => TestExactActionSetOfferedAsync(""" class Program { static void Main(string[] args) @@ -4118,14 +3964,11 @@ static void Main(string[] args) System.Console.WriteLine([|b != true|] ? b = true : b = false); } } - """; - await TestExactActionSetOfferedAsync(code, [FeaturesResources.Extract_method], new TestParameters(parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6))); - } + """, [FeaturesResources.Extract_method], new TestParameters(parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6))); [Fact] - public async Task TestPartialSelection_CSharp6NotApplicable() - { - var code = """ + public Task TestPartialSelection_CSharp6NotApplicable() + => TestExactActionSetOfferedAsync(""" class Program { static void Main(string[] args) @@ -4134,14 +3977,11 @@ static void Main(string[] args) System.Console.WriteLine([|b != true|] ? b = true : b = false); } } - """; - await TestExactActionSetOfferedAsync(code, [FeaturesResources.Extract_method], new TestParameters(parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp5))); - } + """, [FeaturesResources.Extract_method], new TestParameters(parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp5))); [Fact] - public async Task TestInIntegerExpression() - { - await TestInRegularAndScript1Async( + public Task TestInIntegerExpression() + => TestInRegularAndScript1Async( """ class MethodExtraction { @@ -4165,12 +4005,10 @@ static int GetA() } } """, CodeActionIndex); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40188")] - public async Task TestEditorconfigSetting_StaticLocalFunction_True() - { - var input = """ + public Task TestEditorconfigSetting_StaticLocalFunction_True() + => TestInRegularAndScript1Async(""" @@ -4188,9 +4026,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -4213,15 +4049,11 @@ static void NewMethod() - """; - - await TestInRegularAndScript1Async(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40188")] - public async Task TestEditorconfigSetting_StaticLocalFunction_False() - { - var input = """ + public Task TestEditorconfigSetting_StaticLocalFunction_False() + => TestInRegularAndScript1Async(""" @@ -4239,9 +4071,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -4264,15 +4094,11 @@ void NewMethod() - """; - - await TestInRegularAndScript1Async(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40188")] - public async Task TestEditorconfigSetting_ExpressionBodiedLocalFunction_True() - { - var input = """ + public Task TestEditorconfigSetting_ExpressionBodiedLocalFunction_True() + => TestInRegularAndScript1Async(""" @@ -4290,9 +4116,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -4312,15 +4136,11 @@ static void Main() - """; - - await TestInRegularAndScript1Async(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40188")] - public async Task TestEditorconfigSetting_ExpressionBodiedLocalFunction_False() - { - var input = """ + public Task TestEditorconfigSetting_ExpressionBodiedLocalFunction_False() + => TestInRegularAndScript1Async(""" @@ -4338,9 +4158,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -4363,10 +4181,7 @@ static bool NewMethod() - """; - - await TestInRegularAndScript1Async(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40209")] public async Task TestNaming_CamelCase() @@ -4624,9 +4439,8 @@ await TestInRegularAndScript1Async(input, expected, CodeActionIndex, [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/40654")] - public async Task TestOnInvalidUsingStatement_MultipleStatements() - { - var input = """ + public Task TestOnInvalidUsingStatement_MultipleStatements() + => TestInRegularAndScript1Async(""" class C { void M() @@ -4635,8 +4449,7 @@ void M() using System;|] } } - """; - var expected = """ + """, """ class C { void M() @@ -4650,15 +4463,12 @@ static void NewMethod() } } } - """; - await TestInRegularAndScript1Async(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/40555")] - public async Task TestOnLocalFunctionHeader_Parameter() - { - var input = """ + public Task TestOnLocalFunctionHeader_Parameter() + => TestInRegularAndScript1Async(""" using System; class C { @@ -4672,8 +4482,7 @@ void F(int [|x|]) }); } } - """; - var expected = """ + """, """ using System; class C { @@ -4692,15 +4501,12 @@ void F(int x) } } } - """; - await TestInRegularAndScript1Async(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/40555")] - public async Task TestOnLocalFunctionHeader_Parameter_ExpressionBody() - { - var input = """ + public Task TestOnLocalFunctionHeader_Parameter_ExpressionBody() + => TestInRegularAndScript1Async(""" using System; class C { @@ -4712,8 +4518,7 @@ void M(Action a) }); } } - """; - var expected = """ + """, """ using System; class C { @@ -4730,15 +4535,12 @@ static Action NewMethod() } } } - """; - await TestInRegularAndScript1Async(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/40555")] - public async Task TestOnLocalFunctionHeader_Identifier() - { - var input = """ + public Task TestOnLocalFunctionHeader_Identifier() + => TestInRegularAndScript1Async(""" using System; class C { @@ -4752,8 +4554,7 @@ void M(Action a) }); } } - """; - var expected = """ + """, """ using System; class C { @@ -4772,15 +4573,12 @@ void F(int x) } } } - """; - await TestInRegularAndScript1Async(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/40555")] - public async Task TestOnLocalFunctionHeader_Identifier_ExpressionBody() - { - var input = """ + public Task TestOnLocalFunctionHeader_Identifier_ExpressionBody() + => TestInRegularAndScript1Async(""" using System; class C { @@ -4792,8 +4590,7 @@ void M(Action a) }); } } - """; - var expected = """ + """, """ using System; class C { @@ -4810,15 +4607,12 @@ static Action NewMethod() } } } - """; - await TestInRegularAndScript1Async(input, expected, CodeActionIndex); - } + """, CodeActionIndex); [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/40654")] - public async Task TestMissingOnUsingStatement() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnUsingStatement() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -4831,12 +4625,10 @@ void L() } } """); - } [Fact] - public async Task TestMissingInLocalFunctionDeclaration_ExpressionBody() - { - await TestMissingInRegularAndScriptAsync(""" + public Task TestMissingInLocalFunctionDeclaration_ExpressionBody() + => TestMissingInRegularAndScriptAsync(""" class C { public static void Main(string[] args) @@ -4846,12 +4638,10 @@ public static void Main(string[] args) } } """, new TestParameters(index: CodeActionIndex)); - } [Fact] - public async Task TestMissingInLocalFunctionDeclaration() - { - await TestMissingInRegularAndScriptAsync(""" + public Task TestMissingInLocalFunctionDeclaration() + => TestMissingInRegularAndScriptAsync(""" class C { public static void Main(string[] args) @@ -4864,12 +4654,10 @@ public static void Main(string[] args) } } """, new TestParameters(index: CodeActionIndex)); - } [Fact] - public async Task TestOnGoto() - { - await TestInRegularAndScriptAsync( + public Task TestOnGoto() + => TestInRegularAndScriptAsync( """ delegate int del(int i); @@ -4908,12 +4696,10 @@ static int NewMethod(int x) } } """, index: CodeActionIndex); - } [Fact] - public async Task TestMissingInFieldInitializer() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingInFieldInitializer() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -4925,12 +4711,10 @@ static void Main(string[] args) } } """, new TestParameters(index: CodeActionIndex)); - } [Fact] - public async Task TestMissingInFieldInitializer_2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingInFieldInitializer_2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -4942,40 +4726,32 @@ static void Main(string[] args) } } """, new TestParameters(index: CodeActionIndex)); - } [Fact] - public async Task TestMissingInExpressionBodyProperty() - { - var code = """ + public Task TestMissingInExpressionBodyProperty() + => TestExactActionSetOfferedAsync(""" class Program { int field; public int Blah => [|this.field|]; } - """; - await TestExactActionSetOfferedAsync(code, [FeaturesResources.Extract_method]); - } + """, [FeaturesResources.Extract_method]); [Fact] - public async Task TestMissingInExpressionBodyIndexer() - { - var code = """ + public Task TestMissingInExpressionBodyIndexer() + => TestExactActionSetOfferedAsync(""" class Program { int field; public int this[int i] => [|this.field|]; } - """; - await TestExactActionSetOfferedAsync(code, [FeaturesResources.Extract_method]); - } + """, [FeaturesResources.Extract_method]); [Fact] - public async Task TestMissingInExpressionBodyPropertyGetAccessor() - { - var code = """ + public Task TestMissingInExpressionBodyPropertyGetAccessor() + => TestExactActionSetOfferedAsync(""" class Program { int field; @@ -4986,14 +4762,11 @@ public int Blah set => field = value; } } - """; - await TestExactActionSetOfferedAsync(code, [FeaturesResources.Extract_method]); - } + """, [FeaturesResources.Extract_method]); [Fact] - public async Task TestMissingInExpressionBodyPropertySetAccessor() - { - var code = """ + public Task TestMissingInExpressionBodyPropertySetAccessor() + => TestExactActionSetOfferedAsync(""" class Program { int field; @@ -5004,14 +4777,11 @@ public int Blah set => field = [|value|]; } } - """; - await TestExactActionSetOfferedAsync(code, [FeaturesResources.Extract_method]); - } + """, [FeaturesResources.Extract_method]); [Fact] - public async Task TestMissingInExpressionBodyIndexerGetAccessor() - { - var code = """ + public Task TestMissingInExpressionBodyIndexerGetAccessor() + => TestExactActionSetOfferedAsync(""" class Program { int field; @@ -5022,14 +4792,11 @@ public int this[int i] set => field = value; } } - """; - await TestExactActionSetOfferedAsync(code, [FeaturesResources.Extract_method]); - } + """, [FeaturesResources.Extract_method]); [Fact] - public async Task TestMissingInExpressionBodyIndexerSetAccessor() - { - var code = """ + public Task TestMissingInExpressionBodyIndexerSetAccessor() + => TestExactActionSetOfferedAsync(""" class Program { int field; @@ -5040,14 +4807,11 @@ public int this[int i] set => field = [|value|]; } } - """; - await TestExactActionSetOfferedAsync(code, [FeaturesResources.Extract_method]); - } + """, [FeaturesResources.Extract_method]); [Fact] - public async Task TestMissingInAttributeInitializer() - { - await TestMissingInRegularAndScriptAsync(""" + public Task TestMissingInAttributeInitializer() + => TestMissingInRegularAndScriptAsync(""" using System; class C @@ -5059,12 +4823,10 @@ public class SampleClass } } """); - } [Fact] - public async Task TestMissingInAttributeInitializerParameter() - { - await TestMissingInRegularAndScriptAsync(""" + public Task TestMissingInAttributeInitializerParameter() + => TestMissingInRegularAndScriptAsync(""" using System.Runtime.InteropServices; class C @@ -5075,12 +4837,10 @@ public class SampleClass } } """); - } [Fact] - public async Task TestMissingInThisConstructorCall() - { - await TestMissingInRegularAndScriptAsync(""" + public Task TestMissingInThisConstructorCall() + => TestMissingInRegularAndScriptAsync(""" class B { protected B(string message) @@ -5102,12 +4862,10 @@ public C(string message, string message2) : base(message) } } """); - } [Fact] - public async Task TestMissingInBaseConstructorCall() - { - await TestMissingInRegularAndScriptAsync(""" + public Task TestMissingInBaseConstructorCall() + => TestMissingInRegularAndScriptAsync(""" class B { protected B(string message) @@ -5129,13 +4887,11 @@ public C(string message, string message2) : [|base(message)|] } } """); - } [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/22150")] - public async Task ExtractLocalFunctionToLocalFunction() - { - var code = """ + public Task ExtractLocalFunctionToLocalFunction() + => TestInRegularAndScript1Async(""" class C { static void Main(string[] args) @@ -5146,8 +4902,7 @@ void Local() { } static void Local() => System.Console.WriteLine(); } - """; - var expected = """ + """, """ class C { static void Main(string[] args) @@ -5163,10 +4918,7 @@ void NewMethod() static void Local() => System.Console.WriteLine(); } - """; - - await TestInRegularAndScript1Async(code, expected); - } + """); [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/56969")] @@ -5175,15 +4927,6 @@ public async Task TopLevelStatement_FullStatement() var code = """ [|System.Console.WriteLine("string");|] """; - var expected = """ - NewMethod(); - - static void NewMethod() - { - System.Console.WriteLine("string"); - } - """; - await new VerifyCS.Test { TestState = @@ -5191,7 +4934,14 @@ static void NewMethod() Sources = { code }, OutputKind = OutputKind.ConsoleApplication, }, - FixedCode = expected, + FixedCode = """ + NewMethod(); + + static void NewMethod() + { + System.Console.WriteLine("string"); + } + """, LanguageVersion = LanguageVersion.CSharp9, CodeActionEquivalenceKey = nameof(FeaturesResources.Extract_local_function), }.RunAsync(); @@ -5209,7 +4959,14 @@ public async Task TopLevelStatement_MultipleStatements() System.Console.WriteLine(x); """; - var expected = """ + await new VerifyCS.Test + { + TestState = + { + Sources = { code }, + OutputKind = OutputKind.ConsoleApplication, + }, + FixedCode = """ System.Console.WriteLine("string"); int x = NewMethod(); @@ -5222,16 +4979,7 @@ static int NewMethod() System.Console.WriteLine(x); return x; } - """; - - await new VerifyCS.Test - { - TestState = - { - Sources = { code }, - OutputKind = OutputKind.ConsoleApplication, - }, - FixedCode = expected, + """, LanguageVersion = LanguageVersion.CSharp9, CodeActionEquivalenceKey = nameof(FeaturesResources.Extract_local_function), }.RunAsync(); @@ -5253,7 +5001,14 @@ public async Task TopLevelStatement_MultipleStatementsWithUsingAndClass() class Ignored { } """; - var expected = """ + await new VerifyCS.Test + { + TestState = + { + Sources = { code }, + OutputKind = OutputKind.ConsoleApplication, + }, + FixedCode = """ using System; Console.WriteLine("string"); @@ -5270,16 +5025,7 @@ static int NewMethod() } class Ignored { } - """; - - await new VerifyCS.Test - { - TestState = - { - Sources = { code }, - OutputKind = OutputKind.ConsoleApplication, - }, - FixedCode = expected, + """, LanguageVersion = LanguageVersion.CSharp9, CodeActionEquivalenceKey = nameof(FeaturesResources.Extract_local_function), }.RunAsync(); @@ -5303,7 +5049,14 @@ class Ignored { } class Ignored2 { } """; - var expected = """ + await new VerifyCS.Test + { + TestState = + { + Sources = { code }, + OutputKind = OutputKind.ConsoleApplication, + }, + FixedCode = """ using System; Console.WriteLine("string"); @@ -5322,16 +5075,7 @@ static int NewMethod() } class Ignored2 { } - """; - - await new VerifyCS.Test - { - TestState = - { - Sources = { code }, - OutputKind = OutputKind.ConsoleApplication, - }, - FixedCode = expected, + """, LanguageVersion = LanguageVersion.CSharp9, CodeActionEquivalenceKey = nameof(FeaturesResources.Extract_local_function), }.RunAsync(); @@ -5344,15 +5088,6 @@ public async Task TopLevelStatement_ArgumentInInvocation() var code = """ System.Console.WriteLine([|"string"|]); """; - var expected = """ - System.Console.WriteLine(NewMethod()); - - static string NewMethod() - { - return "string"; - } - """; - await new VerifyCS.Test { TestState = @@ -5360,7 +5095,14 @@ static string NewMethod() Sources = { code }, OutputKind = OutputKind.ConsoleApplication, }, - FixedCode = expected, + FixedCode = """ + System.Console.WriteLine(NewMethod()); + + static string NewMethod() + { + return "string"; + } + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } @@ -5374,7 +5116,14 @@ public async Task TopLevelStatement_InBlock_ArgumentInInvocation() System.Console.WriteLine([|"string"|]); } """; - var expected = """ + await new VerifyCS.Test + { + TestState = + { + Sources = { code }, + OutputKind = OutputKind.ConsoleApplication, + }, + FixedCode = """ { System.Console.WriteLine(NewMethod()); @@ -5383,16 +5132,7 @@ static string NewMethod() return "string"; } } - """; - - await new VerifyCS.Test - { - TestState = - { - Sources = { code }, - OutputKind = OutputKind.ConsoleApplication, - }, - FixedCode = expected, + """, LanguageVersion = LanguageVersion.CSharp9, CodeActionEquivalenceKey = nameof(FeaturesResources.Extract_local_function), }.RunAsync(); @@ -5400,40 +5140,31 @@ static string NewMethod() [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/44260")] - public async Task TopLevelStatement_ArgumentInInvocation_InInteractive() - { - var code = """ + public Task TopLevelStatement_ArgumentInInvocation_InInteractive() + => TestAsync(""" System.Console.WriteLine([|"string"|]); - """; - var expected = - """ + """, """ System.Console.WriteLine({|Rename:NewMethod|}()); static string NewMethod() { return "string"; } - """; - - await TestAsync(code, expected, TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp9)); - } + """, TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp9)); [Fact] - public async Task TestMissingOnExtractLocalFunctionInNamespace() - { - await TestMissingInRegularAndScriptAsync(""" + public Task TestMissingOnExtractLocalFunctionInNamespace() + => TestMissingInRegularAndScriptAsync(""" namespace C { private bool TestMethod() => [|false|]; } """, codeActionIndex: 1); - } [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/45422")] - public async Task TestOnExtractLocalFunction() - { - await TestInRegularAndScriptAsync(""" + public Task TestOnExtractLocalFunction() + => TestInRegularAndScriptAsync(""" class C { static void M() @@ -5473,13 +5204,11 @@ static void L2() } } """, index: 1); - } [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/45422")] - public async Task TestExtractLocalFunctionWithExtraBrace() - { - await TestInRegularAndScript1Async(""" + public Task TestExtractLocalFunctionWithExtraBrace() + => TestInRegularAndScript1Async(""" class C { static void M() @@ -5517,13 +5246,11 @@ static void L2() } } """, index: 1); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [WorkItem("https://github.com/dotnet/roslyn/issues/55031")] - public async Task TestExtractLocalConst_CSharp7() - { - var code = """ + public Task TestExtractLocalConst_CSharp7() + => TestAsync(""" using NUnit.Framework; public class Tests @@ -5541,9 +5268,7 @@ public void Test1() [|Assert.AreEqual(string.Format(NAME, 0, 0), SomeOtherMethod(j));|] } } - """; - - var expected = """ + """, """ using NUnit.Framework; public class Tests @@ -5566,15 +5291,12 @@ void NewMethod() } } } - """; - await TestAsync(code, expected, TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp7), index: CodeActionIndex); - } + """, TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp7), index: CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [WorkItem("https://github.com/dotnet/roslyn/issues/55031")] - public async Task TestExtractParameter_CSharp7() - { - var code = """ + public Task TestExtractParameter_CSharp7() + => TestAsync(""" using NUnit.Framework; public class Tests @@ -5591,9 +5313,7 @@ public void Test1(string NAME) [|Assert.AreEqual(string.Format(NAME, 0, 0), SomeOtherMethod(j));|] } } - """; - - var expected = """ + """, """ using NUnit.Framework; public class Tests @@ -5615,15 +5335,12 @@ void NewMethod() } } } - """; - await TestAsync(code, expected, TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp7), index: CodeActionIndex); - } + """, TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp7), index: CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [WorkItem("https://github.com/dotnet/roslyn/issues/55031")] - public async Task TestExtractLocal_CSharp7() - { - var code = """ + public Task TestExtractLocal_CSharp7() + => TestAsync(""" using NUnit.Framework; public class Tests @@ -5641,9 +5358,7 @@ public void Test1() [|Assert.AreEqual(string.Format(NAME, 0, 0), SomeOtherMethod(j));|] } } - """; - - var expected = """ + """, """ using NUnit.Framework; public class Tests @@ -5666,15 +5381,12 @@ void NewMethod() } } } - """; - await TestAsync(code, expected, TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp7), index: CodeActionIndex); - } + """, TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp7), index: CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [WorkItem("https://github.com/dotnet/roslyn/issues/55031")] - public async Task TestExtractRangeVariable_CSharp7() - { - var code = """ + public Task TestExtractRangeVariable_CSharp7() + => TestAsync(""" using System.Linq; public class Class @@ -5685,9 +5397,7 @@ public void M() select [|a.ToString()|]; } } - """; - - var expected = """ + """, """ using System.Linq; public class Class @@ -5703,14 +5413,11 @@ string NewMethod(object a) } } } - """; - await TestAsync(code, expected, TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp7), index: CodeActionIndex); - } + """, TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp7), index: CodeActionIndex); [Fact] - public async Task TestExtractLocalFunction_MissingInBaseInitializer() - { - var code = """ + public Task TestExtractLocalFunction_MissingInBaseInitializer() + => TestMissingAsync(""" class Base { private readonly int _x; @@ -5727,15 +5434,11 @@ public C(int y) { } } - """; - - await TestMissingAsync(code, codeActionIndex: CodeActionIndex); - } + """, codeActionIndex: CodeActionIndex); [Fact] - public async Task TestExtractLocalFunction_MissingInThisInitializer() - { - var code = """ + public Task TestExtractLocalFunction_MissingInThisInitializer() + => TestMissingAsync(""" class C { public C(int y) @@ -5747,15 +5450,11 @@ public C(int x, int y) { } } - """; - - await TestMissingAsync(code, codeActionIndex: CodeActionIndex); - } + """, codeActionIndex: CodeActionIndex); [Fact] - public async Task TestExtractLocalFunction_LambdaBlockInitializer() - { - var code = """ + public Task TestExtractLocalFunction_LambdaBlockInitializer() + => TestAsync(""" class C { public C(int y) @@ -5770,9 +5469,7 @@ public C(int x, System.Func modX) { } } - """; - - var expected = """ + """, """ class C { public C(int y) @@ -5792,17 +5489,13 @@ public C(int x, System.Func modX) { } } - """; - - await TestAsync(code, expected, TestOptions.Regular, index: CodeActionIndex); - } + """, TestOptions.Regular, index: CodeActionIndex); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/63917")] [InlineData("true")] [InlineData("false")] - public async Task TestAfterEndif(string ppDirective) - { - var code = $$""" + public Task TestAfterEndif(string ppDirective) + => TestAsync($$""" class C { void M() @@ -5815,9 +5508,7 @@ void M() #endif } } - """; - - var expected = $$""" + """, $$""" class C { void M() @@ -5834,8 +5525,5 @@ static void NewMethod() } } } - """; - - await TestAsync(code, expected, TestOptions.Regular, index: CodeActionIndex); - } + """, TestOptions.Regular, index: CodeActionIndex); } diff --git a/src/Features/CSharpTest/ExtractMethod/ExtractMethodCodeRefactoringTests.cs b/src/Features/CSharpTest/ExtractMethod/ExtractMethodCodeRefactoringTests.cs index f0afa99c65062..6e85218d99331 100644 --- a/src/Features/CSharpTest/ExtractMethod/ExtractMethodCodeRefactoringTests.cs +++ b/src/Features/CSharpTest/ExtractMethod/ExtractMethodCodeRefactoringTests.cs @@ -84,9 +84,8 @@ private OptionsCollection NoBraces() }; [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39946")] - public async Task LocalFuncExtract() - { - await TestInRegularAndScript1Async(""" + public Task LocalFuncExtract() + => TestInRegularAndScript1Async(""" class C { int Testing; @@ -133,12 +132,10 @@ void NewMethod() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540799")] - public async Task TestPartialSelection() - { - await TestInRegularAndScript1Async( + public Task TestPartialSelection() + => TestInRegularAndScript1Async( """ class Program { @@ -164,12 +161,10 @@ private static bool NewMethod(bool b) } } """); - } [Fact] - public async Task TestSelectionOfSwitchExpressionArm() - { - await TestInRegularAndScript1Async( + public Task TestSelectionOfSwitchExpressionArm() + => TestInRegularAndScript1Async( """ class Program { @@ -192,12 +187,10 @@ class Program } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement))); - } [Fact] - public async Task TestSelectionOfSwitchExpressionArmContainingVariables() - { - await TestInRegularAndScript1Async( + public Task TestSelectionOfSwitchExpressionArmContainingVariables() + => TestInRegularAndScript1Async( """ using System; using System.Collections.Generic; @@ -234,12 +227,10 @@ public static T RecursiveExample(IEnumerable sequence) => } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement))); - } [Fact] - public async Task TestUseExpressionBodyWhenPossible() - { - await TestInRegularAndScript1Async( + public Task TestUseExpressionBodyWhenPossible() + => TestInRegularAndScript1Async( """ class Program { @@ -263,12 +254,10 @@ static void Main(string[] args) } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement))); - } [Fact] - public async Task TestUseExpressionWhenOnSingleLine_AndIsOnSingleLine() - { - await TestInRegularAndScript1Async( + public Task TestUseExpressionWhenOnSingleLine_AndIsOnSingleLine() + => TestInRegularAndScript1Async( """ class Program { @@ -292,12 +281,10 @@ static void Main(string[] args) } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); - } [Fact] - public async Task TestUseExpressionWhenOnSingleLine_AndIsOnSingleLine2() - { - await TestInRegularAndScript1Async( + public Task TestUseExpressionWhenOnSingleLine_AndIsOnSingleLine2() + => TestInRegularAndScript1Async( """ class Program { @@ -327,12 +314,10 @@ static void Main(string[] args) } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); - } [Fact] - public async Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine() - { - await TestInRegularAndScript1Async( + public Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine() + => TestInRegularAndScript1Async( """ class Program { @@ -361,12 +346,10 @@ private static bool NewMethod(bool b) } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); - } [Fact] - public async Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine2() - { - await TestInRegularAndScript1Async( + public Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine2() + => TestInRegularAndScript1Async( """ class Program { @@ -395,12 +378,10 @@ private static bool NewMethod(bool b) } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); - } [Fact] - public async Task TestExtractMethodInCtorInit() - { - await TestInRegularAndScript1Async( + public Task TestExtractMethodInCtorInit() + => TestInRegularAndScript1Async( """ class Goo { @@ -420,12 +401,10 @@ public Goo(int i) : this({|Rename:NewMethod|}(i), 2) } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); - } [Fact] - public async Task TestExtractMethodInCtorInitWithOutVar() - { - await TestInRegularAndScript1Async( + public Task TestExtractMethodInCtorInitWithOutVar() + => TestInRegularAndScript1Async( """ class Goo { @@ -445,12 +424,10 @@ public Goo(int i, out int q) : this({|Rename:NewMethod|}(i, out q), 2) } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); - } [Fact] - public async Task TestExtractMethodInCtorInitWithByRefVar() - { - await TestInRegularAndScript1Async( + public Task TestExtractMethodInCtorInitWithByRefVar() + => TestInRegularAndScript1Async( """ using System; using System.Collections.Generic; @@ -556,12 +533,10 @@ static void Main() } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); - } [Fact] - public async Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine3() - { - await TestInRegularAndScript1Async( + public Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine3() + => TestInRegularAndScript1Async( """ class Program { @@ -590,12 +565,10 @@ private static bool NewMethod() } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540796")] - public async Task TestReadOfDataThatDoesNotFlowIn() - { - await TestInRegularAndScript1Async( + public Task TestReadOfDataThatDoesNotFlowIn() + => TestInRegularAndScript1Async( """ class Program { @@ -633,12 +606,10 @@ private static T fun(T t) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540819")] - public async Task TestOnGoto() - { - await TestInRegularAndScriptAsync( + public Task TestOnGoto() + => TestInRegularAndScriptAsync( """ delegate int del(int i); @@ -677,12 +648,10 @@ private static int NewMethod(int x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540819")] - public async Task TestOnStatementAfterUnconditionalGoto() - { - await TestInRegularAndScript1Async( + public Task TestOnStatementAfterUnconditionalGoto() + => TestInRegularAndScript1Async( """ delegate int del(int i); @@ -721,12 +690,10 @@ private static int NewMethod(int x) } } """); - } [Fact] - public async Task TestMissingOnNamespace() - { - await TestInRegularAndScript1Async( + public Task TestMissingOnNamespace() + => TestInRegularAndScript1Async( """ class Program { @@ -750,12 +717,10 @@ private static void NewMethod() } } """); - } [Fact] - public async Task TestMissingOnType() - { - await TestInRegularAndScript1Async( + public Task TestMissingOnType() + => TestInRegularAndScript1Async( """ class Program { @@ -779,12 +744,10 @@ private static void NewMethod() } } """); - } [Fact] - public async Task TestMissingOnBase() - { - await TestInRegularAndScript1Async( + public Task TestMissingOnBase() + => TestInRegularAndScript1Async( """ class Program { @@ -808,12 +771,10 @@ private void NewMethod() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545623")] - public async Task TestOnActionInvocation() - { - await TestInRegularAndScript1Async( + public Task TestOnActionInvocation() + => TestInRegularAndScript1Async( """ using System; @@ -851,12 +812,10 @@ private static Action GetX() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529841"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/714632")] - public async Task DisambiguateCallSiteIfNecessary1() - { - await TestInRegularAndScript1Async( + public Task DisambiguateCallSiteIfNecessary1() + => TestInRegularAndScript1Async( """ using System; @@ -893,12 +852,10 @@ private static Func NewMethod() static void Goo(Func p, Func q, int r, int s) { Console.WriteLine(2); } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529841"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/714632")] - public async Task DisambiguateCallSiteIfNecessary2() - { - await TestInRegularAndScript1Async( + public Task DisambiguateCallSiteIfNecessary2() + => TestInRegularAndScript1Async( """ using System; @@ -935,13 +892,11 @@ private static Func NewMethod() static void Goo(Func p, Func q, int r, int s) { Console.WriteLine(2); } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530709")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632182")] - public async Task DoNotOverparenthesize() - { - await TestAsync( + public Task DoNotOverparenthesize() + => TestAsync( """ using System; @@ -1038,12 +993,10 @@ public static void Ex(this int x) """, parseOptions: TestOptions.Regular); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632182")] - public async Task DoNotOverparenthesizeGenerics() - { - await TestAsync( + public Task DoNotOverparenthesizeGenerics() + => TestAsync( """ using System; @@ -1140,12 +1093,10 @@ public static void Ex(this int x) """, parseOptions: TestOptions.Regular); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984831")] - public async Task PreserveCommentsBeforeDeclaration_1() - { - await TestInRegularAndScript1Async( + public Task PreserveCommentsBeforeDeclaration_1() + => TestInRegularAndScript1Async( """ class Construct { @@ -1185,12 +1136,10 @@ private static void NewMethod(out Construct obj1, out Construct obj2) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984831")] - public async Task PreserveCommentsBeforeDeclaration_2() - { - await TestInRegularAndScript1Async( + public Task PreserveCommentsBeforeDeclaration_2() + => TestInRegularAndScript1Async( """ class Construct { @@ -1238,12 +1187,10 @@ private static void NewMethod(out Construct obj1, out Construct obj2, out Constr } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984831")] - public async Task PreserveCommentsBeforeDeclaration_3() - { - await TestInRegularAndScript1Async( + public Task PreserveCommentsBeforeDeclaration_3() + => TestInRegularAndScript1Async( """ class Construct { @@ -1288,13 +1235,11 @@ private static void NewMethod(out Construct obj1, out Construct obj2, out Constr } } """); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] [WorkItem("https://github.com/dotnet/roslyn/issues/11196")] - public async Task TestTuple() - { - await TestInRegularAndScript1Async( + public Task TestTuple() + => TestInRegularAndScript1Async( """ class Program { @@ -1320,13 +1265,11 @@ private static (int, int) NewMethod() } } """ + TestResources.NetFX.ValueTuple.tuplelib_cs); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] [WorkItem("https://github.com/dotnet/roslyn/issues/11196")] - public async Task TestTupleDeclarationWithNames() - { - await TestInRegularAndScript1Async( + public Task TestTupleDeclarationWithNames() + => TestInRegularAndScript1Async( """ class Program { @@ -1352,13 +1295,11 @@ private static (int a, int b) NewMethod() } } """ + TestResources.NetFX.ValueTuple.tuplelib_cs); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] [WorkItem("https://github.com/dotnet/roslyn/issues/11196")] - public async Task TestTupleDeclarationWithSomeNames() - { - await TestInRegularAndScript1Async( + public Task TestTupleDeclarationWithSomeNames() + => TestInRegularAndScript1Async( """ class Program { @@ -1384,13 +1325,11 @@ private static (int a, int) NewMethod() } } """ + TestResources.NetFX.ValueTuple.tuplelib_cs); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] [WorkItem("https://github.com/dotnet/roslyn/issues/18311")] - public async Task TestTupleWith1Arity() - { - await TestInRegularAndScript1Async( + public Task TestTupleWith1Arity() + => TestInRegularAndScript1Async( """ using System; class Program @@ -1418,13 +1357,11 @@ private static void NewMethod(ValueTuple y) } } """ + TestResources.NetFX.ValueTuple.tuplelib_cs); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] [WorkItem("https://github.com/dotnet/roslyn/issues/11196")] - public async Task TestTupleLiteralWithNames() - { - await TestInRegularAndScript1Async( + public Task TestTupleLiteralWithNames() + => TestInRegularAndScript1Async( """ class Program { @@ -1450,13 +1387,11 @@ private static (int, int) NewMethod() } } """ + TestResources.NetFX.ValueTuple.tuplelib_cs); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] [WorkItem("https://github.com/dotnet/roslyn/issues/11196")] - public async Task TestTupleDeclarationAndLiteralWithNames() - { - await TestInRegularAndScript1Async( + public Task TestTupleDeclarationAndLiteralWithNames() + => TestInRegularAndScript1Async( """ class Program { @@ -1482,13 +1417,11 @@ private static (int a, int b) NewMethod() } } """ + TestResources.NetFX.ValueTuple.tuplelib_cs); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] [WorkItem("https://github.com/dotnet/roslyn/issues/11196")] - public async Task TestTupleIntoVar() - { - await TestInRegularAndScript1Async( + public Task TestTupleIntoVar() + => TestInRegularAndScript1Async( """ class Program { @@ -1514,13 +1447,11 @@ private static (int c, int d) NewMethod() } } """ + TestResources.NetFX.ValueTuple.tuplelib_cs); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] [WorkItem("https://github.com/dotnet/roslyn/issues/11196")] - public async Task RefactorWithoutSystemValueTuple() - { - await TestInRegularAndScript1Async( + public Task RefactorWithoutSystemValueTuple() + => TestInRegularAndScript1Async( """ class Program { @@ -1546,14 +1477,11 @@ private static (int c, int d) NewMethod() } } """); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] [WorkItem("https://github.com/dotnet/roslyn/issues/11196")] - public async Task TestTupleWithNestedNamedTuple() - { - // This is not the best refactoring, but this is an edge case - await TestInRegularAndScript1Async( + public Task TestTupleWithNestedNamedTuple() + => TestInRegularAndScript1Async( """ class Program { @@ -1579,12 +1507,10 @@ private static (int, int, int, int, int, int, int, string, string) NewMethod() } } """ + TestResources.NetFX.ValueTuple.tuplelib_cs); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] - public async Task TestDeconstruction() - { - await TestInRegularAndScript1Async( + public Task TestDeconstruction() + => TestInRegularAndScript1Async( """ class Program { @@ -1610,12 +1536,10 @@ private static (int, int) NewMethod() } } """ + TestResources.NetFX.ValueTuple.tuplelib_cs); - } [Fact, CompilerTrait(CompilerFeature.Tuples)] - public async Task TestDeconstruction2() - { - await TestInRegularAndScript1Async( + public Task TestDeconstruction2() + => TestInRegularAndScript1Async( """ class Program { @@ -1643,13 +1567,11 @@ private static int NewMethod() } } """ + TestResources.NetFX.ValueTuple.tuplelib_cs); - } [Fact] [CompilerTrait(CompilerFeature.OutVar)] - public async Task TestOutVar() - { - await TestInRegularAndScript1Async( + public Task TestOutVar() + => TestInRegularAndScript1Async( """ class C { @@ -1678,13 +1600,11 @@ private static void NewMethod(int i, out int r, out int y) } } """); - } [Fact] [CompilerTrait(CompilerFeature.Patterns)] - public async Task TestIsPattern() - { - await TestInRegularAndScript1Async( + public Task TestIsPattern() + => TestInRegularAndScript1Async( """ class C { @@ -1713,13 +1633,11 @@ private static void NewMethod(int i, out int r, out int y) } } """); - } [Fact] [CompilerTrait(CompilerFeature.Patterns)] - public async Task TestOutVarAndIsPattern() - { - await TestInRegularAndScript1Async( + public Task TestOutVarAndIsPattern() + => TestInRegularAndScript1Async( """ class C { @@ -1748,13 +1666,11 @@ private static void NewMethod(out int r, out int y, out int z) } } """); - } [Fact] [CompilerTrait(CompilerFeature.Patterns)] - public async Task ConflictingOutVarLocals() - { - await TestInRegularAndScript1Async( + public Task ConflictingOutVarLocals() + => TestInRegularAndScript1Async( """ class C { @@ -1793,13 +1709,11 @@ private static void NewMethod(out int r, out int y) } } """); - } [Fact] [CompilerTrait(CompilerFeature.Patterns)] - public async Task ConflictingPatternLocals() - { - await TestInRegularAndScript1Async( + public Task ConflictingPatternLocals() + => TestInRegularAndScript1Async( """ class C { @@ -1838,12 +1752,10 @@ private static void NewMethod(out int r, out int y) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15218")] - public async Task TestCancellationTokenGoesLast() - { - await TestInRegularAndScript1Async( + public Task TestCancellationTokenGoesLast() + => TestInRegularAndScript1Async( """ using System; using System.Threading; @@ -1884,12 +1796,10 @@ private static void NewMethod(int v, CancellationToken ct) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15219")] - public async Task TestUseVar1() - { - await TestInRegularAndScript1Async( + public Task TestUseVar1() + => TestInRegularAndScript1Async( """ using System; @@ -1935,12 +1845,10 @@ private static string NewMethod(int i) } } """, new TestParameters(options: Option(CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOption2.TrueWithSuggestionEnforcement))); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15219")] - public async Task TestUseVar2() - { - await TestInRegularAndScript1Async( + public Task TestUseVar2() + => TestInRegularAndScript1Async( """ using System; @@ -1986,12 +1894,10 @@ private static string NewMethod(int i) } } """, new TestParameters(options: Option(CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOption2.TrueWithSuggestionEnforcement))); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15532")] - public async Task ExtractLocalFunctionCall() - { - var code = """ + public Task ExtractLocalFunctionCall() + => TestExactActionSetOfferedAsync(""" class C { public static void Main() @@ -2000,14 +1906,11 @@ void Local() { } [|Local();|] } } - """; - await TestExactActionSetOfferedAsync(code, [FeaturesResources.Extract_local_function]); - } + """, [FeaturesResources.Extract_local_function]); [Fact] - public async Task ExtractLocalFunctionCall_2() - { - await TestInRegularAndScript1Async(""" + public Task ExtractLocalFunctionCall_2() + => TestInRegularAndScript1Async(""" class C { public static void Main() @@ -2031,12 +1934,10 @@ void Local() { } } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15532")] - public async Task ExtractLocalFunctionCallWithCapture() - { - var code = """ + public Task ExtractLocalFunctionCallWithCapture() + => TestExactActionSetOfferedAsync(""" class C { public static void Main(string[] args) @@ -2045,14 +1946,11 @@ public static void Main(string[] args) [|Local();|] } } - """; - await TestExactActionSetOfferedAsync(code, [FeaturesResources.Extract_local_function]); - } + """, [FeaturesResources.Extract_local_function]); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15532")] - public async Task ExtractLocalFunctionDeclaration() - { - await TestMissingInRegularAndScriptAsync(""" + public Task ExtractLocalFunctionDeclaration() + => TestMissingInRegularAndScriptAsync(""" class C { public static void Main() @@ -2062,12 +1960,10 @@ public static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15532")] - public async Task ExtractLocalFunctionInterior() - { - await TestInRegularAndScript1Async(""" + public Task ExtractLocalFunctionInterior() + => TestInRegularAndScript1Async(""" class C { public static void Main() @@ -2099,12 +1995,10 @@ private static void NewMethod() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538229")] - public async Task Bug3790() - { - await TestInRegularAndScript1Async(""" + public Task Bug3790() + => TestInRegularAndScript1Async(""" class Test { void method() @@ -2141,12 +2035,10 @@ private static int NewMethod(int v, int i) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538229")] - public async Task Bug3790_1() - { - await TestInRegularAndScript1Async(""" + public Task Bug3790_1() + => TestInRegularAndScript1Async(""" class Test { void method() @@ -2182,12 +2074,10 @@ private static int NewMethod(int v, int i) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538229")] - public async Task Bug3790_2() - { - await TestInRegularAndScript1Async(""" + public Task Bug3790_2() + => TestInRegularAndScript1Async(""" class Test { void method() @@ -2223,12 +2113,10 @@ private static int NewMethod(ref int v, int i) } } """); - } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=392560")] - public async Task TestExpressionBodyProperty() - { - await TestInRegularAndScript1Async(""" + public Task TestExpressionBodyProperty() + => TestInRegularAndScript1Async(""" class Program { int field; @@ -2249,12 +2137,10 @@ private int GetField() } } """); - } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=392560")] - public async Task TestExpressionBodyIndexer() - { - await TestInRegularAndScript1Async(""" + public Task TestExpressionBodyIndexer() + => TestInRegularAndScript1Async(""" class Program { int field; @@ -2275,12 +2161,10 @@ private int GetField() } } """); - } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=392560")] - public async Task TestExpressionBodyPropertyGetAccessor() - { - await TestInRegularAndScript1Async(""" + public Task TestExpressionBodyPropertyGetAccessor() + => TestInRegularAndScript1Async(""" class Program { int field; @@ -2309,12 +2193,10 @@ private int GetField() } } """); - } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=392560")] - public async Task TestExpressionBodyPropertySetAccessor() - { - await TestInRegularAndScript1Async(""" + public Task TestExpressionBodyPropertySetAccessor() + => TestInRegularAndScript1Async(""" class Program { int field; @@ -2343,12 +2225,10 @@ private static int GetValue(int value) } } """); - } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=392560")] - public async Task TestExpressionBodyIndexerGetAccessor() - { - await TestInRegularAndScript1Async(""" + public Task TestExpressionBodyIndexerGetAccessor() + => TestInRegularAndScript1Async(""" class Program { int field; @@ -2377,12 +2257,10 @@ private int GetField() } } """); - } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=392560")] - public async Task TestExpressionBodyIndexerSetAccessor() - { - await TestInRegularAndScript1Async(""" + public Task TestExpressionBodyIndexerSetAccessor() + => TestInRegularAndScript1Async(""" class Program { int field; @@ -2411,12 +2289,10 @@ private static int GetValue(int value) } } """); - } [Fact] - public async Task TestTupleWithInferredNames() - { - await TestAsync(""" + public Task TestTupleWithInferredNames() + => TestAsync(""" class Program { void M() @@ -2443,12 +2319,10 @@ private static (int a, int b) GetT(int a) } } """, TestOptions.Regular7_1); - } [Fact] - public async Task TestDeconstruction4() - { - await TestAsync(""" + public Task TestDeconstruction4() + => TestAsync(""" class Program { void M() @@ -2474,12 +2348,10 @@ private static void NewMethod(out int x, out int y) } } """, TestOptions.Regular7_1); - } [Fact] - public async Task TestDeconstruction5() - { - await TestAsync(""" + public Task TestDeconstruction5() + => TestAsync(""" class Program { void M() @@ -2505,12 +2377,10 @@ private static void NewMethod(out int x, out int y) } } """, TestOptions.Regular7_1); - } [Fact] - public async Task TestIndexExpression() - { - await TestInRegularAndScript1Async(TestSources.Index + """ + public Task TestIndexExpression() + => TestInRegularAndScript1Async(TestSources.Index + """ class Program { static void Main(string[] args) @@ -2534,12 +2404,10 @@ private static System.Index NewMethod() } } """); - } [Fact] - public async Task TestRangeExpression_Empty() - { - await TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + """ + public Task TestRangeExpression_Empty() + => TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + """ class Program { static void Main(string[] args) @@ -2563,12 +2431,10 @@ private static System.Range NewMethod() } } """); - } [Fact] - public async Task TestRangeExpression_Left() - { - await TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + """ + public Task TestRangeExpression_Left() + => TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + """ class Program { static void Main(string[] args) @@ -2592,12 +2458,10 @@ private static System.Range NewMethod() } } """); - } [Fact] - public async Task TestRangeExpression_Right() - { - await TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + """ + public Task TestRangeExpression_Right() + => TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + """ class Program { static void Main(string[] args) @@ -2621,12 +2485,10 @@ private static System.Range NewMethod() } } """); - } [Fact] - public async Task TestRangeExpression_Both() - { - await TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + """ + public Task TestRangeExpression_Both() + => TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + """ class Program { static void Main(string[] args) @@ -2650,7 +2512,6 @@ private static System.Range NewMethod() } } """); - } [Fact] public Task TestAnnotatedNullableReturn() @@ -3329,9 +3190,8 @@ private static string NewMethod() """); [Fact] - public async Task TestExtractReadOnlyMethod() - { - await TestInRegularAndScript1Async( + public Task TestExtractReadOnlyMethod() + => TestInRegularAndScript1Async( """ struct S1 { @@ -3357,12 +3217,10 @@ private readonly void NewMethod() } } """); - } [Fact] - public async Task TestExtractReadOnlyMethodInReadOnlyStruct() - { - await TestInRegularAndScript1Async( + public Task TestExtractReadOnlyMethodInReadOnlyStruct() + => TestInRegularAndScript1Async( """ readonly struct S1 { @@ -3388,12 +3246,10 @@ private void NewMethod() } } """); - } [Fact] - public async Task TestExtractNonReadOnlyMethodInReadOnlyMethod() - { - await TestInRegularAndScript1Async( + public Task TestExtractNonReadOnlyMethodInReadOnlyMethod() + => TestInRegularAndScript1Async( """ struct S1 { @@ -3419,7 +3275,6 @@ private void NewMethod() } } """); - } [Fact] public Task TestExtractNullableObjectWithExplicitCast() @@ -3806,9 +3661,8 @@ class C """); [Fact] - public async Task EnsureStaticLocalFunctionOptionHasNoEffect() - { - await TestInRegularAndScript1Async( + public Task EnsureStaticLocalFunctionOptionHasNoEffect() + => TestInRegularAndScript1Async( """ class Program { @@ -3834,12 +3688,10 @@ private static bool NewMethod(bool b) } } """, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOption2.FalseWithSuggestionEnforcement))); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39946")] - public async Task ExtractLocalFunctionCallAndDeclaration() - { - await TestInRegularAndScript1Async(""" + public Task ExtractLocalFunctionCallAndDeclaration() + => TestInRegularAndScript1Async(""" class C { public static void Main() @@ -3869,12 +3721,10 @@ void Local() { } } } """); - } [Fact] - public async Task TestMissingWhenOnlyLocalFunctionCallSelected() - { - var code = """ + public Task TestMissingWhenOnlyLocalFunctionCallSelected() + => TestExactActionSetOfferedAsync(""" class Program { static void Main(string[] args) @@ -3885,14 +3735,11 @@ static void Local() } } } - """; - await TestExactActionSetOfferedAsync(code, [FeaturesResources.Extract_local_function]); - } + """, [FeaturesResources.Extract_local_function]); [Fact] - public async Task TestOfferedWhenBothLocalFunctionCallAndDeclarationSelected() - { - await TestInRegularAndScript1Async(""" + public Task TestOfferedWhenBothLocalFunctionCallAndDeclarationSelected() + => TestInRegularAndScript1Async(""" class Program { static void Main(string[] args) @@ -3922,12 +3769,10 @@ static void Local() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38529")] - public async Task TestExtractNonAsyncMethodWithAsyncLocalFunction() - { - await TestInRegularAndScript1Async( + public Task TestExtractNonAsyncMethodWithAsyncLocalFunction() + => TestInRegularAndScript1Async( """ class C { @@ -3953,12 +3798,10 @@ private static void NewMethod() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38529")] - public async Task TestExtractAsyncMethodWithConfigureAwaitFalse() - { - await TestInRegularAndScript1Async( + public Task TestExtractAsyncMethodWithConfigureAwaitFalse() + => TestInRegularAndScript1Async( """ class C { @@ -3982,12 +3825,10 @@ private static async System.Threading.Tasks.Task NewMethod(TimeSpan dura } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38529")] - public async Task TestExtractAsyncMethodWithConfigureAwaitFalseNamedParameter() - { - await TestInRegularAndScript1Async( + public Task TestExtractAsyncMethodWithConfigureAwaitFalseNamedParameter() + => TestInRegularAndScript1Async( """ class C { @@ -4011,12 +3852,10 @@ private static async System.Threading.Tasks.Task NewMethod(TimeSpan dura } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38529")] - public async Task TestExtractAsyncMethodWithConfigureAwaitFalseOnNonTask() - { - await TestInRegularAndScript1Async( + public Task TestExtractAsyncMethodWithConfigureAwaitFalseOnNonTask() + => TestInRegularAndScript1Async( """ using System.Threading.Tasks @@ -4044,12 +3883,10 @@ private static async Task NewMethod() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38529")] - public async Task TestExtractAsyncMethodWithConfigureAwaitTrue() - { - await TestInRegularAndScript1Async( + public Task TestExtractAsyncMethodWithConfigureAwaitTrue() + => TestInRegularAndScript1Async( """ class C { @@ -4073,12 +3910,10 @@ private static async System.Threading.Tasks.Task NewMethod(TimeSpan dura } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38529")] - public async Task TestExtractAsyncMethodWithConfigureAwaitNonLiteral() - { - await TestInRegularAndScript1Async( + public Task TestExtractAsyncMethodWithConfigureAwaitNonLiteral() + => TestInRegularAndScript1Async( """ class C { @@ -4102,12 +3937,10 @@ private static async System.Threading.Tasks.Task NewMethod(TimeSpan dura } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38529")] - public async Task TestExtractAsyncMethodWithNoConfigureAwait() - { - await TestInRegularAndScript1Async( + public Task TestExtractAsyncMethodWithNoConfigureAwait() + => TestInRegularAndScript1Async( """ class C { @@ -4131,12 +3964,10 @@ private static async System.Threading.Tasks.Task NewMethod(TimeSpan dura } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38529")] - public async Task TestExtractAsyncMethodWithConfigureAwaitFalseInLambda() - { - await TestInRegularAndScript1Async( + public Task TestExtractAsyncMethodWithConfigureAwaitFalseInLambda() + => TestInRegularAndScript1Async( """ class C { @@ -4160,12 +3991,10 @@ private static async System.Threading.Tasks.Task NewMethod(TimeSpan dura } } """); - } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/38529")] - public async Task TestExtractAsyncMethodWithConfigureAwaitFalseInLocalMethod(bool includeUsing) - { - await TestInRegularAndScript1Async( + public Task TestExtractAsyncMethodWithConfigureAwaitFalseInLocalMethod(bool includeUsing) + => TestInRegularAndScript1Async( $$""" {{(includeUsing ? SystemThreadingTasksUsing : "")}} @@ -4195,12 +4024,10 @@ async Task MyDelay(TimeSpan duration) } } """); - } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/38529")] - public async Task TestExtractAsyncMethodWithConfigureAwaitMixture1(bool includeUsing) - { - await TestInRegularAndScript1Async( + public Task TestExtractAsyncMethodWithConfigureAwaitMixture1(bool includeUsing) + => TestInRegularAndScript1Async( $$""" {{(includeUsing ? SystemThreadingTasksUsing : "")}} @@ -4230,12 +4057,10 @@ async Task MyDelay(TimeSpan duration) } } """); - } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/38529")] - public async Task TestExtractAsyncMethodWithConfigureAwaitMixture2(bool includeUsing) - { - await TestInRegularAndScript1Async( + public Task TestExtractAsyncMethodWithConfigureAwaitMixture2(bool includeUsing) + => TestInRegularAndScript1Async( $$""" {{(includeUsing ? SystemThreadingTasksUsing : "")}} @@ -4265,12 +4090,10 @@ async Task MyDelay(TimeSpan duration) } } """); - } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/38529")] - public async Task TestExtractAsyncMethodWithConfigureAwaitMixture3(bool includeUsing) - { - await TestInRegularAndScript1Async( + public Task TestExtractAsyncMethodWithConfigureAwaitMixture3(bool includeUsing) + => TestInRegularAndScript1Async( $$""" {{(includeUsing ? SystemThreadingTasksUsing : "")}} @@ -4300,12 +4123,10 @@ async Task MyDelay(TimeSpan duration) } } """); - } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/38529")] - public async Task TestExtractAsyncMethodWithConfigureAwaitFalseOutsideSelection(bool includeUsing) - { - await TestInRegularAndScript1Async( + public Task TestExtractAsyncMethodWithConfigureAwaitFalseOutsideSelection(bool includeUsing) + => TestInRegularAndScript1Async( $$""" {{(includeUsing ? SystemThreadingTasksUsing : "")}} @@ -4335,12 +4156,10 @@ async Task MyDelay(TimeSpan duration) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40188")] - public async Task TestEditorconfigSetting_ExpressionBodiedLocalFunction_True() - { - var input = """ + public Task TestEditorconfigSetting_ExpressionBodiedLocalFunction_True() + => TestInRegularAndScript1Async(""" @@ -4358,9 +4177,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -4380,15 +4197,11 @@ static void Main() - """; - - await TestInRegularAndScript1Async(input, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40188")] - public async Task TestEditorconfigSetting_ExpressionBodiedLocalFunction_False() - { - var input = """ + public Task TestEditorconfigSetting_ExpressionBodiedLocalFunction_False() + => TestInRegularAndScript1Async(""" @@ -4406,9 +4219,7 @@ static void Main() - """; - - var expected = """ + """, """ @@ -4431,10 +4242,7 @@ private static bool NewMethod() - """; - - await TestInRegularAndScript1Async(input, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40209")] public async Task TestNaming_CamelCase_VerifyLocalFunctionSettingsDoNotApply() @@ -4537,9 +4345,8 @@ private static int GetA() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40654")] - public async Task TestOnInvalidUsingStatement_MultipleStatements() - { - var input = """ + public Task TestOnInvalidUsingStatement_MultipleStatements() + => TestInRegularAndScript1Async(""" class C { void M() @@ -4548,8 +4355,7 @@ void M() using System;|] } } - """; - var expected = """ + """, """ class C { void M() @@ -4563,14 +4369,11 @@ private static void NewMethod() using System; } } - """; - await TestInRegularAndScript1Async(input, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40654")] - public async Task TestMissingOnInvalidUsingStatement() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnInvalidUsingStatement() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -4580,12 +4383,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19461")] - public async Task TestLocalFunction() - { - await TestInRegularAndScript1Async(""" + public Task TestLocalFunction() + => TestInRegularAndScript1Async(""" using System; class Program @@ -4623,12 +4424,10 @@ int local() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43834")] - public async Task TestRecursivePatternRewrite() - { - await TestInRegularAndScript1Async(""" + public Task TestRecursivePatternRewrite() + => TestInRegularAndScript1Async(""" using System; namespace N { @@ -4684,12 +4483,10 @@ private static Action NewMethod() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41895")] - public async Task TestConditionalAccess1() - { - await TestInRegularAndScript1Async(""" + public Task TestConditionalAccess1() + => TestInRegularAndScript1Async(""" using System; using System.Collections.Generic; class C @@ -4719,12 +4516,10 @@ private static string NewMethod(List b) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41895")] - public async Task TestConditionalAccess2() - { - await TestInRegularAndScript1Async(""" + public Task TestConditionalAccess2() + => TestInRegularAndScript1Async(""" using System; using System.Collections.Generic; class C @@ -4754,12 +4549,10 @@ void Test() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41895")] - public async Task TestConditionalAccess3() - { - await TestInRegularAndScript1Async(""" + public Task TestConditionalAccess3() + => TestInRegularAndScript1Async(""" using System; using System.Collections.Generic; class C @@ -4789,12 +4582,10 @@ private static string NewMethod(List b) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41895")] - public async Task TestConditionalAccess4() - { - await TestInRegularAndScript1Async(""" + public Task TestConditionalAccess4() + => TestInRegularAndScript1Async(""" using System; using System.Collections.Generic; class C @@ -4824,12 +4615,10 @@ private static string NewMethod(List b) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41895")] - public async Task TestConditionalAccess5() - { - await TestInRegularAndScript1Async(""" + public Task TestConditionalAccess5() + => TestInRegularAndScript1Async(""" using System; using System.Collections.Generic; class C @@ -4859,12 +4648,10 @@ private static string NewMethod(List b) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41895")] - public async Task TestConditionalAccess6() - { - await TestInRegularAndScript1Async(""" + public Task TestConditionalAccess6() + => TestInRegularAndScript1Async(""" using System; using System.Collections.Generic; class C @@ -4894,12 +4681,10 @@ private static string NewMethod(List b) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41895")] - public async Task TestConditionalAccess7() - { - await TestInRegularAndScript1Async(""" + public Task TestConditionalAccess7() + => TestInRegularAndScript1Async(""" using System; using System.Collections.Generic; class C @@ -4929,38 +4714,36 @@ void Test() } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/48453")] [InlineData("record")] [InlineData("record class")] - public async Task TestInRecord(string record) - { - await TestInRegularAndScript1Async($@" -{record} Program -{{ - int field; - - public int this[int i] => [|this.field|]; -}}", -$@" -{record} Program -{{ - int field; - - public int this[int i] => {{|Rename:GetField|}}(); - - private int GetField() - {{ - return this.field; - }} -}}"); - } + public Task TestInRecord(string record) + => TestInRegularAndScript1Async($$""" + {{record}} Program + { + int field; + + public int this[int i] => [|this.field|]; + } + """, + $$""" + {{record}} Program + { + int field; + + public int this[int i] => {|Rename:GetField|}(); + + private int GetField() + { + return this.field; + } + } + """); [Fact] - public async Task TestInRecordStruct() - { - await TestInRegularAndScript1Async(""" + public Task TestInRecordStruct() + => TestInRegularAndScript1Async(""" record struct Program { int field; @@ -4981,23 +4764,19 @@ private readonly int GetField() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53031")] - public async Task TestMethodInNamespace() - { - await TestMissingInRegularAndScriptAsync(""" + public Task TestMethodInNamespace() + => TestMissingInRegularAndScriptAsync(""" namespace TestNamespace { private bool TestMethod() => [|false|]; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53031")] - public async Task TestMethodInInterface() - { - await TestInRegularAndScript1Async(""" + public Task TestMethodInInterface() + => TestInRegularAndScript1Async(""" interface TestInterface { bool TestMethod() => [|false|]; @@ -5014,12 +4793,10 @@ bool NewMethod() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53031")] - public async Task TestStaticMethodInInterface() - { - await TestInRegularAndScript1Async(""" + public Task TestStaticMethodInInterface() + => TestInRegularAndScript1Async(""" interface TestInterface { static bool TestMethod() => [|false|]; @@ -5036,7 +4813,6 @@ static bool NewMethod() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] [WorkItem("https://github.com/dotnet/roslyn/issues/56969")] @@ -5200,9 +4976,8 @@ class Ignored2 { } } [Fact, WorkItem(56969, "https://github.com/dotnet/roslyn/issues/58013")] - public async Task TopLevelMethod_StaticMethod() - { - await TestInRegularAndScript1Async(""" + public Task TopLevelMethod_StaticMethod() + => TestInRegularAndScript1Async(""" static void X(string s) { [|s = s.Trim();|] @@ -5220,12 +4995,10 @@ static string NewMethod(string s) return s; } """, parameters: new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9))); - } [Fact, WorkItem(56969, "https://github.com/dotnet/roslyn/issues/58013")] - public async Task StaticMethod_ExtractStatementContainingParameter() - { - await TestInRegularAndScript1Async(""" + public Task StaticMethod_ExtractStatementContainingParameter() + => TestInRegularAndScript1Async(""" public class Class { static void X(string s) @@ -5249,12 +5022,10 @@ private static string NewMethod(string s) } } """, parameters: new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9))); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57428")] - public async Task AttributeArgumentWithLambdaBody() - { - await TestInRegularAndScript1Async( + public Task AttributeArgumentWithLambdaBody() + => TestInRegularAndScript1Async( """ using System.Runtime.InteropServices; class Program @@ -5278,7 +5049,6 @@ private static object NewMethod() } } """); - } [Fact] public Task ExtractMethod_InsideBaseInitializer() @@ -6056,9 +5826,8 @@ struct S1 } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38087")] - public async Task TestPartialSelectionOfArithmeticExpression() - { - await TestInRegularAndScript1Async( + public Task TestPartialSelectionOfArithmeticExpression() + => TestInRegularAndScript1Async( """ class C { @@ -6084,12 +5853,10 @@ private static int NewMethod(int i, int j) } } """); - } [Fact] - public async Task TestFlowControl_BreakAndBreak() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_BreakAndBreak() + => TestInRegularAndScript1Async( """ class C { @@ -6134,12 +5901,10 @@ private static void NewMethod(int v) } } """); - } [Fact] - public async Task TestFlowControl_BreakAndContinue() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_BreakAndContinue() + => TestInRegularAndScript1Async( """ class C { @@ -6191,12 +5956,10 @@ private static bool NewMethod(int v) } } """); - } [Fact] - public async Task TestFlowControl_BreakAndReturn() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_BreakAndReturn() + => TestInRegularAndScript1Async( """ class C { @@ -6248,12 +6011,10 @@ private static (bool flowControl, int value) NewMethod(int v) } } """); - } [Fact] - public async Task TestFlowControl_BreakAndFallThrough() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_BreakAndFallThrough() + => TestInRegularAndScript1Async( """ class C { @@ -6299,12 +6060,10 @@ private static bool NewMethod(int v) } } """); - } [Fact] - public async Task TestFlowControl_ContinueAndBreak() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_ContinueAndBreak() + => TestInRegularAndScript1Async( """ class C { @@ -6356,12 +6115,10 @@ private static bool NewMethod(int v) } } """); - } [Fact] - public async Task TestFlowControl_ContinueAndContinue() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_ContinueAndContinue() + => TestInRegularAndScript1Async( """ class C { @@ -6406,12 +6163,10 @@ private static void NewMethod(int v) } } """); - } [Fact] - public async Task TestFlowControl_ContinueAndReturn() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_ContinueAndReturn() + => TestInRegularAndScript1Async( """ class C { @@ -6460,12 +6215,10 @@ private static (bool flowControl, int value) NewMethod(int v) } } """); - } [Fact] - public async Task TestFlowControl_ContinueAndFallThrough() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_ContinueAndFallThrough() + => TestInRegularAndScript1Async( """ class C { @@ -6511,12 +6264,10 @@ private static bool NewMethod(int v) } } """); - } [Fact] - public async Task TestFlowControl_ReturnAndBreak() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_ReturnAndBreak() + => TestInRegularAndScript1Async( """ class C { @@ -6568,12 +6319,10 @@ private static (bool flowControl, int value) NewMethod(int v) } } """); - } [Fact] - public async Task TestFlowControl_ReturnAndContinue() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_ReturnAndContinue() + => TestInRegularAndScript1Async( """ class C { @@ -6622,12 +6371,10 @@ private static (bool flowControl, int value) NewMethod(int v) } } """); - } [Fact] - public async Task TestFlowControl_ReturnAndReturn() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_ReturnAndReturn() + => TestInRegularAndScript1Async( """ class C { @@ -6671,12 +6418,10 @@ private static int NewMethod(int v) } } """); - } [Fact] - public async Task TestFlowControl_ReturnAndFallThrough() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_ReturnAndFallThrough() + => TestInRegularAndScript1Async( """ class C { @@ -6722,12 +6467,10 @@ private static (bool flowControl, int value) NewMethod(int v) } } """); - } [Fact] - public async Task TestFlowControl_BreakAndContinueAndReturn() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_BreakAndContinueAndReturn() + => TestInRegularAndScript1Async( """ class C { @@ -6793,12 +6536,10 @@ private static (bool? flowControl, int value) NewMethod(int v) } } """); - } [Fact] - public async Task TestFlowControl_BreakAndContinueAndFallThrough() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_BreakAndContinueAndFallThrough() + => TestInRegularAndScript1Async( """ class C { @@ -6858,12 +6599,10 @@ private int Repro(int[] x) } } """); - } [Fact] - public async Task TestFlowControl_ContinueAndReturnAndFallThrough() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_ContinueAndReturnAndFallThrough() + => TestInRegularAndScript1Async( """ class C { @@ -6920,12 +6659,10 @@ private static (bool? flowControl, int value) NewMethod(int v) } } """); - } [Fact] - public async Task TestFlowControl_BreakAndContinueAndReturnAndFallThrough() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_BreakAndContinueAndReturnAndFallThrough() + => TestInRegularAndScript1Async( """ class C { @@ -6999,12 +6736,10 @@ private static (int flowControl, string value) NewMethod(int v) } } """); - } [Fact] - public async Task TestFlowControl_BreakAndBreak_AllowVar() - { - await TestInRegularAndScriptAsync( + public Task TestFlowControl_BreakAndBreak_AllowVar() + => TestInRegularAndScriptAsync( """ class C { @@ -7050,12 +6785,10 @@ private static void NewMethod(int v) } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task TestFlowControl_BreakAndContinue_AllowVar() - { - await TestInRegularAndScriptAsync( + public Task TestFlowControl_BreakAndContinue_AllowVar() + => TestInRegularAndScriptAsync( """ class C { @@ -7108,12 +6841,10 @@ private static bool NewMethod(int v) } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task TestFlowControl_BreakAndReturn_AllowVar() - { - await TestInRegularAndScriptAsync( + public Task TestFlowControl_BreakAndReturn_AllowVar() + => TestInRegularAndScriptAsync( """ class C { @@ -7166,12 +6897,10 @@ private static (bool flowControl, int value) NewMethod(int v) } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task TestFlowControl_BreakAndFallThrough_AllowVar() - { - await TestInRegularAndScriptAsync( + public Task TestFlowControl_BreakAndFallThrough_AllowVar() + => TestInRegularAndScriptAsync( """ class C { @@ -7218,12 +6947,10 @@ private static bool NewMethod(int v) } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task TestFlowControl_ContinueAndBreak_AllowVar() - { - await TestInRegularAndScriptAsync( + public Task TestFlowControl_ContinueAndBreak_AllowVar() + => TestInRegularAndScriptAsync( """ class C { @@ -7276,12 +7003,10 @@ private static bool NewMethod(int v) } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task TestFlowControl_ContinueAndContinue_AllowVar() - { - await TestInRegularAndScriptAsync( + public Task TestFlowControl_ContinueAndContinue_AllowVar() + => TestInRegularAndScriptAsync( """ class C { @@ -7327,12 +7052,10 @@ private static void NewMethod(int v) } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task TestFlowControl_ContinueAndReturn_AllowVar() - { - await TestInRegularAndScriptAsync( + public Task TestFlowControl_ContinueAndReturn_AllowVar() + => TestInRegularAndScriptAsync( """ class C { @@ -7382,12 +7105,10 @@ private static (bool flowControl, int value) NewMethod(int v) } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task TestFlowControl_ContinueAndFallThrough_AllowVar() - { - await TestInRegularAndScriptAsync( + public Task TestFlowControl_ContinueAndFallThrough_AllowVar() + => TestInRegularAndScriptAsync( """ class C { @@ -7434,12 +7155,10 @@ private static bool NewMethod(int v) } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task TestFlowControl_ReturnAndBreak_AllowVar() - { - await TestInRegularAndScriptAsync( + public Task TestFlowControl_ReturnAndBreak_AllowVar() + => TestInRegularAndScriptAsync( """ class C { @@ -7492,12 +7211,10 @@ private static (bool flowControl, int value) NewMethod(int v) } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task TestFlowControl_ReturnAndContinue_AllowVar() - { - await TestInRegularAndScriptAsync( + public Task TestFlowControl_ReturnAndContinue_AllowVar() + => TestInRegularAndScriptAsync( """ class C { @@ -7547,12 +7264,10 @@ private static (bool flowControl, int value) NewMethod(int v) } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task TestFlowControl_ReturnAndReturn_AllowVar() - { - await TestInRegularAndScriptAsync( + public Task TestFlowControl_ReturnAndReturn_AllowVar() + => TestInRegularAndScriptAsync( """ class C { @@ -7597,12 +7312,10 @@ private static int NewMethod(int v) } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task TestFlowControl_ReturnAndFallThrough_AllowVar() - { - await TestInRegularAndScriptAsync( + public Task TestFlowControl_ReturnAndFallThrough_AllowVar() + => TestInRegularAndScriptAsync( """ class C { @@ -7649,12 +7362,10 @@ private static (bool flowControl, int value) NewMethod(int v) } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task TestFlowControl_BreakAndContinueAndReturn_AllowVar() - { - await TestInRegularAndScriptAsync( + public Task TestFlowControl_BreakAndContinueAndReturn_AllowVar() + => TestInRegularAndScriptAsync( """ class C { @@ -7721,12 +7432,10 @@ private static (bool? flowControl, int value) NewMethod(int v) } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task TestFlowControl_BreakAndContinueAndFallThrough_AllowVar() - { - await TestInRegularAndScriptAsync( + public Task TestFlowControl_BreakAndContinueAndFallThrough_AllowVar() + => TestInRegularAndScriptAsync( """ class C { @@ -7787,12 +7496,10 @@ private int Repro(int[] x) } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task TestFlowControl_ContinueAndReturnAndFallThrough_AllowVar() - { - await TestInRegularAndScriptAsync( + public Task TestFlowControl_ContinueAndReturnAndFallThrough_AllowVar() + => TestInRegularAndScriptAsync( """ class C { @@ -7850,12 +7557,10 @@ private static (bool? flowControl, int value) NewMethod(int v) } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task TestFlowControl_BreakAndContinueAndReturnAndFallThrough_AllowVar() - { - await TestInRegularAndScriptAsync(""" + public Task TestFlowControl_BreakAndContinueAndReturnAndFallThrough_AllowVar() + => TestInRegularAndScriptAsync(""" class C { private string Repro(int[] x) @@ -7929,12 +7634,10 @@ private static (int flowControl, string value) NewMethod(int v) } """, options: ImplicitTypeEverywhere()); - } [Fact] - public async Task TestFlowControl_BreakAndBreak_Async() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_BreakAndBreak_Async() + => TestInRegularAndScript1Async( """ using System.Threading.Tasks; class C @@ -7981,12 +7684,10 @@ private static async Task NewMethod(int v) } } """); - } [Fact] - public async Task TestFlowControl_BreakAndContinue_Async() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_BreakAndContinue_Async() + => TestInRegularAndScript1Async( """ using System.Threading.Tasks; class C @@ -8040,12 +7741,10 @@ private static async Task NewMethod(int v) } } """); - } [Fact] - public async Task TestFlowControl_BreakAndReturn_Async() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_BreakAndReturn_Async() + => TestInRegularAndScript1Async( """ using System.Threading.Tasks; class C @@ -8099,12 +7798,10 @@ private async Task Repro(int[] x) } } """); - } [Fact] - public async Task TestFlowControl_BreakAndFallThrough_Async() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_BreakAndFallThrough_Async() + => TestInRegularAndScript1Async( """ using System.Threading.Tasks; class C @@ -8153,12 +7850,10 @@ private static async Task NewMethod(int v) } } """); - } [Fact] - public async Task TestFlowControl_ContinueAndBreak_Async() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_ContinueAndBreak_Async() + => TestInRegularAndScript1Async( """ using System.Threading.Tasks; class C @@ -8212,12 +7907,10 @@ private static async Task NewMethod(int v) } } """); - } [Fact] - public async Task TestFlowControl_ContinueAndContinue_Async() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_ContinueAndContinue_Async() + => TestInRegularAndScript1Async( """ using System.Threading.Tasks; class C @@ -8264,12 +7957,10 @@ private static async Task NewMethod(int v) } } """); - } [Fact] - public async Task TestFlowControl_ContinueAndReturn_Async() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_ContinueAndReturn_Async() + => TestInRegularAndScript1Async( """ using System.Threading.Tasks; class C @@ -8320,12 +8011,10 @@ private async Task Repro(int[] x) } } """); - } [Fact] - public async Task TestFlowControl_ContinueAndFallThrough_Async() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_ContinueAndFallThrough_Async() + => TestInRegularAndScript1Async( """ using System.Threading.Tasks; class C @@ -8374,12 +8063,10 @@ private static async Task NewMethod(int v) } } """); - } [Fact] - public async Task TestFlowControl_ReturnAndBreak_Async() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_ReturnAndBreak_Async() + => TestInRegularAndScript1Async( """ using System.Threading.Tasks; class C @@ -8433,12 +8120,10 @@ private async Task Repro(int[] x) } } """); - } [Fact] - public async Task TestFlowControl_ReturnAndContinue_Async() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_ReturnAndContinue_Async() + => TestInRegularAndScript1Async( """ using System.Threading.Tasks; class C @@ -8489,12 +8174,10 @@ private async Task Repro(int[] x) } } """); - } [Fact] - public async Task TestFlowControl_ReturnAndReturn_Async() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_ReturnAndReturn_Async() + => TestInRegularAndScript1Async( """ using System.Threading.Tasks; class C @@ -8540,12 +8223,10 @@ private static async Task NewMethod(int v) } } """); - } [Fact] - public async Task TestFlowControl_ReturnAndFallThrough_Async() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_ReturnAndFallThrough_Async() + => TestInRegularAndScript1Async( """ using System.Threading.Tasks; class C @@ -8594,12 +8275,10 @@ private async Task Repro(int[] x) } } """); - } [Fact] - public async Task TestFlowControl_BreakAndContinueAndReturn_Async() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_BreakAndContinueAndReturn_Async() + => TestInRegularAndScript1Async( """ using System.Threading.Tasks; class C @@ -8667,12 +8346,10 @@ private async Task Repro(int[] x) } } """); - } [Fact] - public async Task TestFlowControl_BreakAndContinueAndFallThrough_Async() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_BreakAndContinueAndFallThrough_Async() + => TestInRegularAndScript1Async( """ using System.Threading.Tasks; class C @@ -8735,12 +8412,10 @@ private async Task Repro(int[] x) } } """); - } [Fact] - public async Task TestFlowControl_ContinueAndReturnAndFallThrough_Async() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_ContinueAndReturnAndFallThrough_Async() + => TestInRegularAndScript1Async( """ using System.Threading.Tasks; class C @@ -8800,12 +8475,10 @@ private async Task Repro(int[] x) } } """); - } [Fact] - public async Task TestFlowControl_BreakAndContinueAndReturnAndFallThrough_Async() - { - await TestInRegularAndScript1Async( + public Task TestFlowControl_BreakAndContinueAndReturnAndFallThrough_Async() + => TestInRegularAndScript1Async( """ using System.Threading.Tasks; class C @@ -8882,12 +8555,10 @@ private async Task Repro(int[] x) } } """); - } [Fact] - public async Task TestFlowControl_BreakAndBreak_NoBraces() - { - await TestInRegularAndScriptAsync( + public Task TestFlowControl_BreakAndBreak_NoBraces() + => TestInRegularAndScriptAsync( """ class C { @@ -8933,12 +8604,10 @@ private static void NewMethod(int v) } """, options: NoBraces()); - } [Fact] - public async Task TestFlowControl_BreakAndContinue_NoBraces() - { - await TestInRegularAndScriptAsync( + public Task TestFlowControl_BreakAndContinue_NoBraces() + => TestInRegularAndScriptAsync( """ class C { @@ -8987,12 +8656,10 @@ private static bool NewMethod(int v) } """, options: NoBraces()); - } [Fact] - public async Task TestFlowControl_BreakAndReturn_NoBraces() - { - await TestInRegularAndScriptAsync( + public Task TestFlowControl_BreakAndReturn_NoBraces() + => TestInRegularAndScriptAsync( """ class C { @@ -9041,12 +8708,10 @@ private static (bool flowControl, int value) NewMethod(int v) } """, options: NoBraces()); - } [Fact] - public async Task TestFlowControl_BreakAndFallThrough_NoBraces() - { - await TestInRegularAndScriptAsync( + public Task TestFlowControl_BreakAndFallThrough_NoBraces() + => TestInRegularAndScriptAsync( """ class C { @@ -9091,12 +8756,10 @@ private static bool NewMethod(int v) } """, options: NoBraces()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22597")] - public async Task TestFullyExtractedTypeParameter() - { - await TestInRegularAndScriptAsync( + public Task TestFullyExtractedTypeParameter() + => TestInRegularAndScriptAsync( """ class C { @@ -9122,5 +8785,4 @@ private static void NewMethod() } } """); - } } diff --git a/src/Features/CSharpTest/FullyQualify/FullyQualifyTests.cs b/src/Features/CSharpTest/FullyQualify/FullyQualifyTests.cs index 4ce6190134706..4862b01199fcf 100644 --- a/src/Features/CSharpTest/FullyQualify/FullyQualifyTests.cs +++ b/src/Features/CSharpTest/FullyQualify/FullyQualifyTests.cs @@ -32,1402 +32,1474 @@ protected override ImmutableArray MassageActions(ImmutableArray FlattenActions(actions); [Theory, CombinatorialData] - public async Task TestTypeFromMultipleNamespaces1(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"class Class -{ - [|IDictionary|] Method() - { - Goo(); - } -}", -@"class Class -{ - System.Collections.IDictionary Method() - { - Goo(); - } -}", testHost: testHost); - } + public Task TestTypeFromMultipleNamespaces1(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + class Class + { + [|IDictionary|] Method() + { + Goo(); + } + } + """, + """ + class Class + { + System.Collections.IDictionary Method() + { + Goo(); + } + } + """, testHost: testHost); [Theory, CombinatorialData] - public async Task TestTypeFromMultipleNamespaces2(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"class Class -{ - [|IDictionary|] Method() - { - Goo(); - } -}", -@"class Class -{ - System.Collections.Generic.IDictionary Method() - { - Goo(); - } -}", + public Task TestTypeFromMultipleNamespaces2(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + class Class + { + [|IDictionary|] Method() + { + Goo(); + } + } + """, + """ + class Class + { + System.Collections.Generic.IDictionary Method() + { + Goo(); + } + } + """, index: 1, testHost: testHost); - } [Theory, CombinatorialData] [WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1889385")] - public async Task TestPreservesIncorrectIndentation1(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"class Class -{ - [|IDictionary|] Method() - { - Goo(); - } -}", -@"class Class -{ - System.Collections.IDictionary Method() - { - Goo(); - } -}", testHost: testHost); - } + public Task TestPreservesIncorrectIndentation1(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + class Class + { + [|IDictionary|] Method() + { + Goo(); + } + } + """, + """ + class Class + { + System.Collections.IDictionary Method() + { + Goo(); + } + } + """, testHost: testHost); [Theory, CombinatorialData] [WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1889385")] - public async Task TestPreservesIncorrectIndentation2(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"class Class -{ -\t[|IDictionary|] Method() - { - Goo(); - } -}".Replace(@"\t", "\t"), -@"class Class -{ -\tSystem.Collections.IDictionary Method() - { - Goo(); - } -}".Replace(@"\t", "\t"), testHost: testHost); - } + public Task TestPreservesIncorrectIndentation2(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + class Class + { + \t[|IDictionary|] Method() + { + Goo(); + } + } + """.Replace(@"\t", "\t"), + """ + class Class + { + \tSystem.Collections.IDictionary Method() + { + Goo(); + } + } + """.Replace(@"\t", "\t"), testHost: testHost); [Theory, CombinatorialData] - public async Task TestGenericWithNoArgs(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"class Class -{ - [|List|] Method() - { - Goo(); - } -}", -@"class Class -{ - System.Collections.Generic.List Method() - { - Goo(); - } -}", testHost: testHost); - } + public Task TestGenericWithNoArgs(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + class Class + { + [|List|] Method() + { + Goo(); + } + } + """, + """ + class Class + { + System.Collections.Generic.List Method() + { + Goo(); + } + } + """, testHost: testHost); [Theory, CombinatorialData] - public async Task TestGenericWithCorrectArgs(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"class Class -{ - [|List|] Method() - { - Goo(); - } -}", -@"class Class -{ - System.Collections.Generic.List Method() - { - Goo(); - } -}", testHost: testHost); - } + public Task TestGenericWithCorrectArgs(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + class Class + { + [|List|] Method() + { + Goo(); + } + } + """, + """ + class Class + { + System.Collections.Generic.List Method() + { + Goo(); + } + } + """, testHost: testHost); [Theory, CombinatorialData] - public async Task TestSmartTagDisplayText(TestHost testHost) - { - await TestSmartTagTextAsync( -@"class Class -{ - [|List|] Method() - { - Goo(); - } -}", + public Task TestSmartTagDisplayText(TestHost testHost) + => TestSmartTagTextAsync( + """ + class Class + { + [|List|] Method() + { + Goo(); + } + } + """, "System.Collections.Generic.List", new TestParameters(testHost: testHost)); - } [Theory, CombinatorialData] - public async Task TestGenericWithWrongArgs(TestHost testHost) - { - await TestMissingInRegularAndScriptAsync( -@"class Class -{ - [|List|] Method() - { - Goo(); - } -}", new TestParameters(testHost: testHost)); - } + public Task TestGenericWithWrongArgs(TestHost testHost) + => TestMissingInRegularAndScriptAsync( + """ + class Class + { + [|List|] Method() + { + Goo(); + } + } + """, new TestParameters(testHost: testHost)); [Theory, CombinatorialData] - public async Task TestNotOnVar1(TestHost testHost) - { - await TestMissingInRegularAndScriptAsync( -@"namespace N -{ - class var { } -} - -class C -{ - void M() - { - [|var|] - } -} -", new TestParameters(testHost: testHost)); - } + public Task TestNotOnVar1(TestHost testHost) + => TestMissingInRegularAndScriptAsync( + """ + namespace N + { + class var { } + } + + class C + { + void M() + { + [|var|] + } + } + """, new TestParameters(testHost: testHost)); [Theory, CombinatorialData] - public async Task TestNotOnVar2(TestHost testHost) - { - await TestMissingInRegularAndScriptAsync( -@"namespace N -{ - class Bar { } -} - -class C -{ - void M() - { - [|var|] - } -} -", new TestParameters(testHost: testHost)); - } + public Task TestNotOnVar2(TestHost testHost) + => TestMissingInRegularAndScriptAsync( + """ + namespace N + { + class Bar { } + } + + class C + { + void M() + { + [|var|] + } + } + """, new TestParameters(testHost: testHost)); [Theory, CombinatorialData] - public async Task TestGenericInLocalDeclaration(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"class Class -{ - void Goo() - { - [|List|] a = new List(); - } -}", -@"class Class -{ - void Goo() - { - System.Collections.Generic.List a = new List(); - } -}", testHost: testHost); - } + public Task TestGenericInLocalDeclaration(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + class Class + { + void Goo() + { + [|List|] a = new List(); + } + } + """, + """ + class Class + { + void Goo() + { + System.Collections.Generic.List a = new List(); + } + } + """, testHost: testHost); [Theory, CombinatorialData] - public async Task TestGenericItemType(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"using System.Collections.Generic; - -class Class -{ - List<[|Int32|]> l; -}", -@"using System.Collections.Generic; - -class Class -{ - List l; -}", testHost: testHost); - } + public Task TestGenericItemType(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + using System.Collections.Generic; + + class Class + { + List<[|Int32|]> l; + } + """, + """ + using System.Collections.Generic; + + class Class + { + List l; + } + """, testHost: testHost); [Theory, CombinatorialData] - public async Task TestGenerateWithExistingUsings(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"using System; - -class Class -{ - [|List|] Method() - { - Goo(); - } -}", -@"using System; - -class Class -{ - System.Collections.Generic.List Method() - { - Goo(); - } -}", testHost: testHost); - } + public Task TestGenerateWithExistingUsings(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + using System; + + class Class + { + [|List|] Method() + { + Goo(); + } + } + """, + """ + using System; + + class Class + { + System.Collections.Generic.List Method() + { + Goo(); + } + } + """, testHost: testHost); [Theory, CombinatorialData] - public async Task TestGenerateInNamespace(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"namespace N -{ - class Class - { - [|List|] Method() - { - Goo(); - } - } -}", -@"namespace N -{ - class Class - { - System.Collections.Generic.List Method() - { - Goo(); - } - } -}", testHost: testHost); - } + public Task TestGenerateInNamespace(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + namespace N + { + class Class + { + [|List|] Method() + { + Goo(); + } + } + } + """, + """ + namespace N + { + class Class + { + System.Collections.Generic.List Method() + { + Goo(); + } + } + } + """, testHost: testHost); [Theory, CombinatorialData] - public async Task TestGenerateInNamespaceWithUsings(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"namespace N -{ - using System; - - class Class - { - [|List|] Method() - { - Goo(); - } - } -}", -@"namespace N -{ - using System; - - class Class - { - System.Collections.Generic.List Method() - { - Goo(); - } - } -}", testHost: testHost); - } + public Task TestGenerateInNamespaceWithUsings(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + namespace N + { + using System; + + class Class + { + [|List|] Method() + { + Goo(); + } + } + } + """, + """ + namespace N + { + using System; + + class Class + { + System.Collections.Generic.List Method() + { + Goo(); + } + } + } + """, testHost: testHost); [Theory, CombinatorialData] public async Task TestExistingUsing(TestHost testHost) { await TestActionCountAsync( -@"using System.Collections.Generic; - -class Class -{ - [|IDictionary|] Method() - { - Goo(); - } -}", + """ + using System.Collections.Generic; + + class Class + { + [|IDictionary|] Method() + { + Goo(); + } + } + """, count: 1, new TestParameters(testHost: testHost)); await TestInRegularAndScriptAsync( -@"using System.Collections.Generic; - -class Class -{ - [|IDictionary|] Method() - { - Goo(); - } -}", -@"using System.Collections.Generic; - -class Class -{ - System.Collections.IDictionary Method() - { - Goo(); - } -}", testHost: testHost); - } - - [Theory, CombinatorialData] - public async Task TestMissingIfUniquelyBound(TestHost testHost) - { - await TestMissingInRegularAndScriptAsync( -@"using System; - -class Class -{ - [|String|] Method() - { - Goo(); - } -}", new TestParameters(testHost: testHost)); - } - - [Theory, CombinatorialData] - public async Task TestMissingIfUniquelyBoundGeneric(TestHost testHost) - { - await TestMissingInRegularAndScriptAsync( -@"using System.Collections.Generic; - -class Class -{ - [|List|] Method() - { - Goo(); - } -}", new TestParameters(testHost: testHost)); + """ + using System.Collections.Generic; + + class Class + { + [|IDictionary|] Method() + { + Goo(); + } + } + """, + """ + using System.Collections.Generic; + + class Class + { + System.Collections.IDictionary Method() + { + Goo(); + } + } + """, testHost: testHost); } [Theory, CombinatorialData] - public async Task TestOnEnum(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"class Class -{ - void Goo() - { - var a = [|Colors|].Red; - } -} - -namespace A -{ - enum Colors - { - Red, - Green, - Blue - } -}", -@"class Class -{ - void Goo() - { - var a = A.Colors.Red; - } -} - -namespace A -{ - enum Colors - { - Red, - Green, - Blue - } -}", testHost: testHost); - } + public Task TestMissingIfUniquelyBound(TestHost testHost) + => TestMissingInRegularAndScriptAsync( + """ + using System; + + class Class + { + [|String|] Method() + { + Goo(); + } + } + """, new TestParameters(testHost: testHost)); [Theory, CombinatorialData] - public async Task TestOnClassInheritance(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"class Class : [|Class2|] -{ -} - -namespace A -{ - class Class2 - { - } -}", -@"class Class : A.Class2 -{ -} - -namespace A -{ - class Class2 - { - } -}", testHost: testHost); - } + public Task TestMissingIfUniquelyBoundGeneric(TestHost testHost) + => TestMissingInRegularAndScriptAsync( + """ + using System.Collections.Generic; + + class Class + { + [|List|] Method() + { + Goo(); + } + } + """, new TestParameters(testHost: testHost)); [Theory, CombinatorialData] - public async Task TestOnImplementedInterface(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"class Class : [|IGoo|] -{ -} - -namespace A -{ - interface IGoo - { - } -}", -@"class Class : A.IGoo -{ -} - -namespace A -{ - interface IGoo - { - } -}", testHost: testHost); - } + public Task TestOnEnum(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + class Class + { + void Goo() + { + var a = [|Colors|].Red; + } + } + + namespace A + { + enum Colors + { + Red, + Green, + Blue + } + } + """, + """ + class Class + { + void Goo() + { + var a = A.Colors.Red; + } + } + + namespace A + { + enum Colors + { + Red, + Green, + Blue + } + } + """, testHost: testHost); [Theory, CombinatorialData] - public async Task TestAllInBaseList(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"class Class : [|IGoo|], Class2 -{ -} - -namespace A -{ - class Class2 - { - } -} - -namespace B -{ - interface IGoo - { - } -}", -@"class Class : B.IGoo, Class2 -{ -} - -namespace A -{ - class Class2 - { - } -} - -namespace B -{ - interface IGoo - { - } -}", testHost: testHost); - - await TestInRegularAndScriptAsync( -@"class Class : B.IGoo, [|Class2|] -{ -} - -namespace A -{ - class Class2 - { - } -} - -namespace B -{ - interface IGoo - { - } -}", -@"class Class : B.IGoo, A.Class2 -{ -} - -namespace A -{ - class Class2 - { - } -} - -namespace B -{ - interface IGoo - { - } -}", testHost: testHost); - } - - [Theory, CombinatorialData] - public async Task TestAttributeUnexpanded(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"[[|Obsolete|]] -class Class -{ -}", -@"[System.Obsolete] -class Class -{ -}", testHost: testHost); - } - - [Theory, CombinatorialData] - public async Task TestAttributeExpanded(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"[[|ObsoleteAttribute|]] -class Class -{ -}", -@"[System.ObsoleteAttribute] -class Class -{ -}", testHost: testHost); - } - - [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527360")] - public async Task TestExtensionMethods(TestHost testHost) - { - await TestMissingInRegularAndScriptAsync( -@"using System.Collections.Generic; - -class Goo -{ - void Bar() - { - var values = new List() { 1, 2, 3 }; - values.[|Where|](i => i > 1); - } -}", new TestParameters(testHost: testHost)); - } - - [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538018")] - public async Task TestAfterNew(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"class Class -{ - void Goo() - { - List l; - l = new [|List|](); - } -}", -@"class Class -{ - void Goo() - { - List l; - l = new System.Collections.Generic.List(); - } -}", testHost: testHost); - } - - [Theory, CombinatorialData] - public async Task TestArgumentsInMethodCall(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"class Class -{ - void Test() - { - Console.WriteLine([|DateTime|].Today); - } -}", -@"class Class -{ - void Test() - { - Console.WriteLine(System.DateTime.Today); - } -}", testHost: testHost); - } - - [Theory, CombinatorialData] - public async Task TestCallSiteArgs(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"class Class -{ - void Test([|DateTime|] dt) - { - } -}", -@"class Class -{ - void Test(System.DateTime dt) - { - } -}", testHost: testHost); - } - - [Theory, CombinatorialData] - public async Task TestUsePartialClass(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"namespace A -{ - public class Class - { - [|PClass|] c; - } -} - -namespace B -{ - public partial class PClass - { - } -}", -@"namespace A -{ - public class Class - { - B.PClass c; - } -} - -namespace B -{ - public partial class PClass - { - } -}", testHost: testHost); - } - - [Theory, CombinatorialData] - public async Task TestGenericClassInNestedNamespace(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"namespace A -{ - namespace B - { - class GenericClass - { - } - } -} - -namespace C -{ - class Class - { - [|GenericClass|] c; - } -}", -@"namespace A -{ - namespace B - { - class GenericClass - { - } - } -} - -namespace C -{ - class Class - { - A.B.GenericClass c; - } -}", testHost: testHost); - } - - [Theory, CombinatorialData] - public async Task TestBeforeStaticMethod(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"class Class -{ - void Test() - { - [|Math|].Sqrt(); - }", -@"class Class -{ - void Test() - { - System.Math.Sqrt(); - }", testHost: testHost); - } - - [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538136")] - public async Task TestBeforeNamespace(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"namespace A -{ - class Class - { - [|C|].Test t; - } -} - -namespace B -{ - namespace C - { - class Test - { - } - } -}", -@"namespace A -{ - class Class - { - B.C.Test t; - } -} - -namespace B -{ - namespace C - { - class Test - { - } - } -}", testHost: testHost); - } - - [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527395")] - public async Task TestSimpleNameWithLeadingTrivia(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"class Class { void Test() { /*goo*/[|Int32|] i; } }", -@"class Class { void Test() { /*goo*/System.Int32 i; } }", testHost: testHost); - } - - [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527395")] - public async Task TestGenericNameWithLeadingTrivia(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"class Class { void Test() { /*goo*/[|List|] l; } }", -@"class Class { void Test() { /*goo*/System.Collections.Generic.List l; } }", testHost: testHost); - } - - [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538740")] - public async Task TestFullyQualifyTypeName(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"public class Program -{ - public class Inner - { - } -} - -class Test -{ - [|Inner|] i; -}", -@"public class Program -{ - public class Inner - { - } -} - -class Test -{ - Program.Inner i; -}", testHost: testHost); - } - - [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/26887")] - public async Task TestFullyQualifyUnboundIdentifier3(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"public class Program -{ - public class Inner - { - } -} - -class Test -{ - public [|Inner|] Name -}", -@"public class Program -{ - public class Inner - { - } -} - -class Test -{ - public Program.Inner Name -}", testHost: testHost); - } - - [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538740")] - public async Task TestFullyQualifyTypeName_NotForGenericType(TestHost testHost) - { - await TestMissingInRegularAndScriptAsync( -@"class Program -{ - public class Inner - { - } -} - -class Test -{ - [|Inner|] i; -}", new TestParameters(testHost: testHost)); - } - - [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538764")] - public async Task TestFullyQualifyThroughAlias(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"using Alias = System; - -class C -{ - [|Int32|] i; -}", -@"using Alias = System; - -class C -{ - Alias.Int32 i; -}", testHost: testHost); - } - - [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538763")] - public async Task TestFullyQualifyPrioritizeTypesOverNamespaces1(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"namespace Outer -{ - namespace C - { - class C - { - } - } -} - -class Test -{ - [|C|] c; -}", -@"namespace Outer -{ - namespace C - { - class C - { - } - } -} - -class Test -{ - Outer.C.C c; -}", testHost: testHost); - } - - [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538763")] - public async Task TestFullyQualifyPrioritizeTypesOverNamespaces2(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"namespace Outer -{ - namespace C - { - class C - { - } - } -} - -class Test -{ - [|C|] c; -}", -@"namespace Outer -{ - namespace C - { - class C - { - } - } -} - -class Test -{ - Outer.C c; -}", -index: 1, testHost: testHost); - } - - [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539853")] - public async Task BugFix5950(TestHost testHost) - { - await TestAsync( -@"using System.Console; WriteLine([|Expression|].Constant(123));", -@"using System.Console; WriteLine(System.Linq.Expressions.Expression.Constant(123));", -parseOptions: GetScriptOptions(), testHost: testHost); - } - - [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540318")] - public async Task TestAfterAlias(TestHost testHost) - { - await TestMissingInRegularAndScriptAsync( -@"using System; -using System.Collections.Generic; -using System.Linq; - -class Program -{ - static void Main(string[] args) - { - System::[|Console|] :: WriteLine(""TEST""); - } -}", new TestParameters(testHost: testHost)); - } - - [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540942")] - public async Task TestMissingOnIncompleteStatement(TestHost testHost) - { - await TestMissingInRegularAndScriptAsync( -@"using System; -using System.IO; - -class C -{ - static void Main(string[] args) - { - [|Path|] } -}", new TestParameters(testHost: testHost)); - } - - [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542643")] - public async Task TestAssemblyAttribute(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"[assembly: [|InternalsVisibleTo|](""Project"")]", -@"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project"")]", testHost: testHost); - } - - [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543388")] - public async Task TestMissingOnAliasName(TestHost testHost) - { - await TestMissingInRegularAndScriptAsync( -@"using [|GIBBERISH|] = Goo.GIBBERISH; - -class Program -{ - static void Main(string[] args) - { - GIBBERISH x; - } -} - -namespace Goo -{ - public class GIBBERISH - { - } -}", new TestParameters(testHost: testHost)); - } - - [Theory, CombinatorialData] - public async Task TestMissingOnAttributeOverloadResolutionError(TestHost testHost) - { - await TestMissingInRegularAndScriptAsync( -@"using System.Runtime.InteropServices; - -class M -{ - [[|DllImport|]()] - static extern int? My(); -}", new TestParameters(testHost: testHost)); - } - - [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544950")] - public async Task TestNotOnAbstractConstructor(TestHost testHost) - { - await TestMissingInRegularAndScriptAsync( -@"using System.IO; - -class Program -{ - static void Main(string[] args) - { - var s = new [|Stream|](); - } -}", new TestParameters(testHost: testHost)); - } - - [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")] - public async Task TestAttributeCount(TestHost testHost) - { - await TestActionCountAsync(@"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ", 2, new TestParameters(testHost: testHost)); - } - - [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")] - public async Task TestAttribute(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ", -@"[ assembly : System.Runtime.InteropServices.Guid ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ", testHost: testHost); - } - - [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546027")] - public async Task TestGeneratePropertyFromAttribute(TestHost testHost) - { - await TestMissingInRegularAndScriptAsync( -@"using System; - -[AttributeUsage(AttributeTargets.Class)] -class MyAttrAttribute : Attribute -{ -} - -[MyAttr(123, [|Version|] = 1)] -class D -{ -}", new TestParameters(testHost: testHost)); - } - - [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775448")] - public async Task ShouldTriggerOnCS0308(TestHost testHost) - { - // CS0308: The non-generic type 'A' cannot be used with type arguments - await TestInRegularAndScriptAsync( -@"using System.Collections; - -class Test -{ - static void Main(string[] args) - { - [|IEnumerable|] f; - } -}", -@"using System.Collections; - -class Test -{ - static void Main(string[] args) - { - System.Collections.Generic.IEnumerable f; - } -}", testHost: testHost); - } + public Task TestOnClassInheritance(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + class Class : [|Class2|] + { + } + + namespace A + { + class Class2 + { + } + } + """, + """ + class Class : A.Class2 + { + } + + namespace A + { + class Class2 + { + } + } + """, testHost: testHost); - [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947579")] - public async Task AmbiguousTypeFix(TestHost testHost) + [Theory, CombinatorialData] + public Task TestOnImplementedInterface(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + class Class : [|IGoo|] + { + } + + namespace A + { + interface IGoo + { + } + } + """, + """ + class Class : A.IGoo + { + } + + namespace A + { + interface IGoo + { + } + } + """, testHost: testHost); + + [Theory, CombinatorialData] + public async Task TestAllInBaseList(TestHost testHost) { await TestInRegularAndScriptAsync( -@"using n1; -using n2; + """ + class Class : [|IGoo|], Class2 + { + } + + namespace A + { + class Class2 + { + } + } + + namespace B + { + interface IGoo + { + } + } + """, + """ + class Class : B.IGoo, Class2 + { + } + + namespace A + { + class Class2 + { + } + } + + namespace B + { + interface IGoo + { + } + } + """, testHost: testHost); -class B -{ - void M1() - { - [|var a = new A();|] + await TestInRegularAndScriptAsync( + """ + class Class : B.IGoo, [|Class2|] + { + } + + namespace A + { + class Class2 + { + } + } + + namespace B + { + interface IGoo + { + } + } + """, + """ + class Class : B.IGoo, A.Class2 + { + } + + namespace A + { + class Class2 + { + } + } + + namespace B + { + interface IGoo + { + } + } + """, testHost: testHost); } -} -namespace n1 -{ - class A - { - } -} + [Theory, CombinatorialData] + public Task TestAttributeUnexpanded(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + [[|Obsolete|]] + class Class + { + } + """, + """ + [System.Obsolete] + class Class + { + } + """, testHost: testHost); -namespace n2 -{ - class A - { - } -}", -@"using n1; -using n2; + [Theory, CombinatorialData] + public Task TestAttributeExpanded(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + [[|ObsoleteAttribute|]] + class Class + { + } + """, + """ + [System.ObsoleteAttribute] + class Class + { + } + """, testHost: testHost); -class B -{ - void M1() - { - var a = new n1.A(); - } -} + [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527360")] + public Task TestExtensionMethods(TestHost testHost) + => TestMissingInRegularAndScriptAsync( + """ + using System.Collections.Generic; + + class Goo + { + void Bar() + { + var values = new List() { 1, 2, 3 }; + values.[|Where|](i => i > 1); + } + } + """, new TestParameters(testHost: testHost)); -namespace n1 -{ - class A - { - } -} + [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538018")] + public Task TestAfterNew(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + class Class + { + void Goo() + { + List l; + l = new [|List|](); + } + } + """, + """ + class Class + { + void Goo() + { + List l; + l = new System.Collections.Generic.List(); + } + } + """, testHost: testHost); -namespace n2 -{ - class A - { - } -}", testHost: testHost); - } + [Theory, CombinatorialData] + public Task TestArgumentsInMethodCall(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + class Class + { + void Test() + { + Console.WriteLine([|DateTime|].Today); + } + } + """, + """ + class Class + { + void Test() + { + Console.WriteLine(System.DateTime.Today); + } + } + """, testHost: testHost); - [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995857")] - public async Task NonPublicNamespaces(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"namespace MS.Internal.Xaml -{ - private class A - { - } -} + [Theory, CombinatorialData] + public Task TestCallSiteArgs(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + class Class + { + void Test([|DateTime|] dt) + { + } + } + """, + """ + class Class + { + void Test(System.DateTime dt) + { + } + } + """, testHost: testHost); -namespace System.Xaml -{ - public class A - { - } -} + [Theory, CombinatorialData] + public Task TestUsePartialClass(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + namespace A + { + public class Class + { + [|PClass|] c; + } + } + + namespace B + { + public partial class PClass + { + } + } + """, + """ + namespace A + { + public class Class + { + B.PClass c; + } + } + + namespace B + { + public partial class PClass + { + } + } + """, testHost: testHost); -public class Program -{ - static void M() - { - [|Xaml|] - } -}", -@"namespace MS.Internal.Xaml -{ - private class A - { - } -} + [Theory, CombinatorialData] + public Task TestGenericClassInNestedNamespace(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + namespace A + { + namespace B + { + class GenericClass + { + } + } + } + + namespace C + { + class Class + { + [|GenericClass|] c; + } + } + """, + """ + namespace A + { + namespace B + { + class GenericClass + { + } + } + } + + namespace C + { + class Class + { + A.B.GenericClass c; + } + } + """, testHost: testHost); -namespace System.Xaml -{ - public class A - { - } -} + [Theory, CombinatorialData] + public Task TestBeforeStaticMethod(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + class Class + { + void Test() + { + [|Math|].Sqrt(); + } + """, + """ + class Class + { + void Test() + { + System.Math.Sqrt(); + } + """, testHost: testHost); -public class Program -{ - static void M() - { - System.Xaml - } -}", testHost: testHost); + [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538136")] + public Task TestBeforeNamespace(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + namespace A + { + class Class + { + [|C|].Test t; + } + } + + namespace B + { + namespace C + { + class Test + { + } + } + } + """, + """ + namespace A + { + class Class + { + B.C.Test t; + } + } + + namespace B + { + namespace C + { + class Test + { + } + } + } + """, testHost: testHost); - await TestInRegularAndScriptAsync( -@"namespace MS.Internal.Xaml -{ - public class A - { - } -} + [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527395")] + public Task TestSimpleNameWithLeadingTrivia(TestHost testHost) + => TestInRegularAndScriptAsync( +@"class Class { void Test() { /*goo*/[|Int32|] i; } }", +@"class Class { void Test() { /*goo*/System.Int32 i; } }", testHost: testHost); -namespace System.Xaml -{ - public class A - { - } -} + [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527395")] + public Task TestGenericNameWithLeadingTrivia(TestHost testHost) + => TestInRegularAndScriptAsync( +@"class Class { void Test() { /*goo*/[|List|] l; } }", +@"class Class { void Test() { /*goo*/System.Collections.Generic.List l; } }", testHost: testHost); -public class Program -{ - static void M() - { - [|Xaml|] - } -}", -@"namespace MS.Internal.Xaml -{ - public class A - { - } -} + [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538740")] + public Task TestFullyQualifyTypeName(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + public class Program + { + public class Inner + { + } + } + + class Test + { + [|Inner|] i; + } + """, + """ + public class Program + { + public class Inner + { + } + } + + class Test + { + Program.Inner i; + } + """, testHost: testHost); -namespace System.Xaml -{ - public class A - { - } -} + [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/26887")] + public Task TestFullyQualifyUnboundIdentifier3(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + public class Program + { + public class Inner + { + } + } + + class Test + { + public [|Inner|] Name + } + """, + """ + public class Program + { + public class Inner + { + } + } + + class Test + { + public Program.Inner Name + } + """, testHost: testHost); -public class Program -{ - static void M() - { - MS.Internal.Xaml - } -}", index: 1, testHost: testHost); - } + [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538740")] + public Task TestFullyQualifyTypeName_NotForGenericType(TestHost testHost) + => TestMissingInRegularAndScriptAsync( + """ + class Program + { + public class Inner + { + } + } + + class Test + { + [|Inner|] i; + } + """, new TestParameters(testHost: testHost)); - [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/11071")] - public async Task AmbiguousFixOrdering(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"using n1; -using n2; + [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538764")] + public Task TestFullyQualifyThroughAlias(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + using Alias = System; + + class C + { + [|Int32|] i; + } + """, + """ + using Alias = System; + + class C + { + Alias.Int32 i; + } + """, testHost: testHost); -[[|Inner|].C] -class B -{ -} + [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538763")] + public Task TestFullyQualifyPrioritizeTypesOverNamespaces1(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + namespace Outer + { + namespace C + { + class C + { + } + } + } + + class Test + { + [|C|] c; + } + """, + """ + namespace Outer + { + namespace C + { + class C + { + } + } + } + + class Test + { + Outer.C.C c; + } + """, testHost: testHost); -namespace n1 -{ - namespace Inner - { - } -} + [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538763")] + public Task TestFullyQualifyPrioritizeTypesOverNamespaces2(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + namespace Outer + { + namespace C + { + class C + { + } + } + } + + class Test + { + [|C|] c; + } + """, + """ + namespace Outer + { + namespace C + { + class C + { + } + } + } + + class Test + { + Outer.C c; + } + """, +index: 1, testHost: testHost); -namespace n2 -{ - namespace Inner - { - class CAttribute - { - } - } -}", -@"using n1; -using n2; + [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539853")] + public Task BugFix5950(TestHost testHost) + => TestAsync( +@"using System.Console; WriteLine([|Expression|].Constant(123));", +@"using System.Console; WriteLine(System.Linq.Expressions.Expression.Constant(123));", +parseOptions: GetScriptOptions(), testHost: testHost); -[n2.Inner.C] -class B -{ -} + [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540318")] + public Task TestAfterAlias(TestHost testHost) + => TestMissingInRegularAndScriptAsync( + """ + using System; + using System.Collections.Generic; + using System.Linq; + + class Program + { + static void Main(string[] args) + { + System::[|Console|] :: WriteLine("TEST"); + } + } + """, new TestParameters(testHost: testHost)); -namespace n1 -{ - namespace Inner - { - } -} + [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540942")] + public Task TestMissingOnIncompleteStatement(TestHost testHost) + => TestMissingInRegularAndScriptAsync( + """ + using System; + using System.IO; + + class C + { + static void Main(string[] args) + { + [|Path|] } + } + """, new TestParameters(testHost: testHost)); -namespace n2 -{ - namespace Inner - { - class CAttribute - { - } - } -}", testHost: testHost); - } + [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542643")] + public Task TestAssemblyAttribute(TestHost testHost) + => TestInRegularAndScriptAsync( +@"[assembly: [|InternalsVisibleTo|](""Project"")]", +@"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project"")]", testHost: testHost); + + [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543388")] + public Task TestMissingOnAliasName(TestHost testHost) + => TestMissingInRegularAndScriptAsync( + """ + using [|GIBBERISH|] = Goo.GIBBERISH; + + class Program + { + static void Main(string[] args) + { + GIBBERISH x; + } + } + + namespace Goo + { + public class GIBBERISH + { + } + } + """, new TestParameters(testHost: testHost)); [Theory, CombinatorialData] - public async Task TupleTest(TestHost testHost) + public Task TestMissingOnAttributeOverloadResolutionError(TestHost testHost) + => TestMissingInRegularAndScriptAsync( + """ + using System.Runtime.InteropServices; + + class M + { + [[|DllImport|]()] + static extern int? My(); + } + """, new TestParameters(testHost: testHost)); + + [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544950")] + public Task TestNotOnAbstractConstructor(TestHost testHost) + => TestMissingInRegularAndScriptAsync( + """ + using System.IO; + + class Program + { + static void Main(string[] args) + { + var s = new [|Stream|](); + } + } + """, new TestParameters(testHost: testHost)); + + [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")] + public Task TestAttributeCount(TestHost testHost) + => TestActionCountAsync(@"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ", 2, new TestParameters(testHost: testHost)); + + [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")] + public Task TestAttribute(TestHost testHost) + => TestInRegularAndScriptAsync( +@"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ", +@"[ assembly : System.Runtime.InteropServices.Guid ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ", testHost: testHost); + + [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546027")] + public Task TestGeneratePropertyFromAttribute(TestHost testHost) + => TestMissingInRegularAndScriptAsync( + """ + using System; + + [AttributeUsage(AttributeTargets.Class)] + class MyAttrAttribute : Attribute + { + } + + [MyAttr(123, [|Version|] = 1)] + class D + { + } + """, new TestParameters(testHost: testHost)); + + [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775448")] + public Task ShouldTriggerOnCS0308(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + using System.Collections; + + class Test + { + static void Main(string[] args) + { + [|IEnumerable|] f; + } + } + """, + """ + using System.Collections; + + class Test + { + static void Main(string[] args) + { + System.Collections.Generic.IEnumerable f; + } + } + """, testHost: testHost); + + [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947579")] + public Task AmbiguousTypeFix(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + using n1; + using n2; + + class B + { + void M1() + { + [|var a = new A();|] + } + } + + namespace n1 + { + class A + { + } + } + + namespace n2 + { + class A + { + } + } + """, + """ + using n1; + using n2; + + class B + { + void M1() + { + var a = new n1.A(); + } + } + + namespace n1 + { + class A + { + } + } + + namespace n2 + { + class A + { + } + } + """, testHost: testHost); + + [Theory, CombinatorialData, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995857")] + public async Task NonPublicNamespaces(TestHost testHost) { await TestInRegularAndScriptAsync( -@"class Class -{ - ([|IDictionary|], string) Method() - { - Goo(); - } -}", -@"class Class -{ - (System.Collections.IDictionary, string) Method() - { - Goo(); - } -}", testHost: testHost); - } + """ + namespace MS.Internal.Xaml + { + private class A + { + } + } + + namespace System.Xaml + { + public class A + { + } + } + + public class Program + { + static void M() + { + [|Xaml|] + } + } + """, + """ + namespace MS.Internal.Xaml + { + private class A + { + } + } + + namespace System.Xaml + { + public class A + { + } + } + + public class Program + { + static void M() + { + System.Xaml + } + } + """, testHost: testHost); - [Theory, CombinatorialData] - public async Task TupleWithOneName(TestHost testHost) - { await TestInRegularAndScriptAsync( -@"class Class -{ - ([|IDictionary|] a, string) Method() - { - Goo(); - } -}", -@"class Class -{ - (System.Collections.IDictionary a, string) Method() - { - Goo(); - } -}", testHost: testHost); + """ + namespace MS.Internal.Xaml + { + public class A + { + } + } + + namespace System.Xaml + { + public class A + { + } + } + + public class Program + { + static void M() + { + [|Xaml|] + } + } + """, + """ + namespace MS.Internal.Xaml + { + public class A + { + } + } + + namespace System.Xaml + { + public class A + { + } + } + + public class Program + { + static void M() + { + MS.Internal.Xaml + } + } + """, index: 1, testHost: testHost); } - [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/18275")] - public async Task TestContextualKeyword1(TestHost testHost) - { - await TestMissingInRegularAndScriptAsync( -@" -namespace N -{ - class nameof - { - } -} + [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/11071")] + public Task AmbiguousFixOrdering(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + using n1; + using n2; + + [[|Inner|].C] + class B + { + } + + namespace n1 + { + namespace Inner + { + } + } + + namespace n2 + { + namespace Inner + { + class CAttribute + { + } + } + } + """, + """ + using n1; + using n2; + + [n2.Inner.C] + class B + { + } + + namespace n1 + { + namespace Inner + { + } + } + + namespace n2 + { + namespace Inner + { + class CAttribute + { + } + } + } + """, testHost: testHost); -class C -{ - void M() - { - [|nameof|] - } -}", new TestParameters(testHost: testHost)); - } + [Theory, CombinatorialData] + public Task TupleTest(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + class Class + { + ([|IDictionary|], string) Method() + { + Goo(); + } + } + """, + """ + class Class + { + (System.Collections.IDictionary, string) Method() + { + Goo(); + } + } + """, testHost: testHost); + + [Theory, CombinatorialData] + public Task TupleWithOneName(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + class Class + { + ([|IDictionary|] a, string) Method() + { + Goo(); + } + } + """, + """ + class Class + { + (System.Collections.IDictionary a, string) Method() + { + Goo(); + } + } + """, testHost: testHost); + + [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/18275")] + public Task TestContextualKeyword1(TestHost testHost) + => TestMissingInRegularAndScriptAsync( + """ + namespace N + { + class nameof + { + } + } + + class C + { + void M() + { + [|nameof|] + } + } + """, new TestParameters(testHost: testHost)); [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/18623")] - public async Task TestDoNotQualifyToTheSameTypeToFixWrongArity(TestHost testHost) - { - await TestMissingInRegularAndScriptAsync( -@" -using System.Collections.Generic; + public Task TestDoNotQualifyToTheSameTypeToFixWrongArity(TestHost testHost) + => TestMissingInRegularAndScriptAsync( + """ + using System.Collections.Generic; -class Program : [|IReadOnlyCollection|] -{ -}", new TestParameters(testHost: testHost)); - } + class Program : [|IReadOnlyCollection|] + { + } + """, new TestParameters(testHost: testHost)); [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/19575")] public async Task TestNoNonGenericsWithGenericCodeParsedAsExpression(TestHost testHost) { - var code = @" -class C -{ - private void GetEvaluationRuleNames() - { - [|IEnumerable|] < Int32 > - return ImmutableArray.CreateRange(); - } -}"; + var code = """ + class C + { + private void GetEvaluationRuleNames() + { + [|IEnumerable|] < Int32 > + return ImmutableArray.CreateRange(); + } + } + """; await TestActionCountAsync(code, count: 1, new TestParameters(testHost: testHost)); await TestInRegularAndScriptAsync( code, -@" +""" class C { private void GetEvaluationRuleNames() @@ -1435,120 +1507,122 @@ private void GetEvaluationRuleNames() System.Collections.Generic.IEnumerable < Int32 > return ImmutableArray.CreateRange(); } -}", testHost: testHost); +} +""", testHost: testHost); } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/49986")] - public async Task TestInUsingContext_Type(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"using [|Math|]; - -class Class -{ - void Test() - { - Sqrt(1); - }", -@"using static System.Math; - -class Class -{ - void Test() - { - Sqrt(1); - }", testHost: testHost); - } + public Task TestInUsingContext_Type(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + using [|Math|]; + + class Class + { + void Test() + { + Sqrt(1); + } + """, + """ + using static System.Math; + + class Class + { + void Test() + { + Sqrt(1); + } + """, testHost: testHost); [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/49986")] - public async Task TestInUsingContext_Namespace(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"using [|Collections|]; - -class Class -{ - void Test() - { - Sqrt(1); - }", -@"using System.Collections; - -class Class -{ - void Test() - { - Sqrt(1); - }", testHost: testHost); - } + public Task TestInUsingContext_Namespace(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + using [|Collections|]; + + class Class + { + void Test() + { + Sqrt(1); + } + """, + """ + using System.Collections; + + class Class + { + void Test() + { + Sqrt(1); + } + """, testHost: testHost); [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/49986")] - public async Task TestInUsingContext_UsingStatic(TestHost testHost) - { - await TestInRegularAndScriptAsync( -@"using static [|Math|]; - -class Class -{ - void Test() - { - Sqrt(1); - }", -@"using static System.Math; - -class Class -{ - void Test() - { - Sqrt(1); - }", testHost: testHost); - } + public Task TestInUsingContext_UsingStatic(TestHost testHost) + => TestInRegularAndScriptAsync( + """ + using static [|Math|]; + + class Class + { + void Test() + { + Sqrt(1); + } + """, + """ + using static System.Math; + + class Class + { + void Test() + { + Sqrt(1); + } + """, testHost: testHost); [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/51274")] - public async Task TestInUsingContext_UsingAlias(TestHost testHost) - { - await TestInRegularAndScriptAsync( + public Task TestInUsingContext_UsingAlias(TestHost testHost) + => TestInRegularAndScriptAsync( @"using M = [|Math|]", @"using M = System.Math", testHost: testHost); - } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/54544")] public async Task TestAddUsingsEditorBrowsableNeverSameProject(TestHost testHost) { - const string InitialWorkspace = @" - - - -using System.ComponentModel; -namespace ProjectLib -{ - [EditorBrowsable(EditorBrowsableState.Never)] - public class Project - { - } -} - - -class Program -{ - static void Main(string[] args) - { - Project p = new [|Project()|]; - } -} - - -"; - - const string ExpectedDocumentText = @" -class Program -{ - static void Main(string[] args) - { - Project p = new [|ProjectLib.Project()|]; - } -} -"; + const string InitialWorkspace = """ + + + using System.ComponentModel; + namespace ProjectLib + { + [EditorBrowsable(EditorBrowsableState.Never)] + public class Project + { + } + } + class Program + { + static void Main(string[] args) + { + Project p = new [|Project()|]; + } + } + + + """; + + const string ExpectedDocumentText = """ + class Program + { + static void Main(string[] args) + { + Project p = new [|ProjectLib.Project()|]; + } + } + """; await TestInRegularAndScript1Async(InitialWorkspace, ExpectedDocumentText, new TestParameters(testHost: testHost)); } @@ -1556,106 +1630,103 @@ static void Main(string[] args) [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/54544")] public async Task TestAddUsingsEditorBrowsableNeverDifferentProject(TestHost testHost) { - const string InitialWorkspace = @" - - - -imports System.ComponentModel -namespace ProjectLib - <EditorBrowsable(EditorBrowsableState.Never)> - public class Project - end class -end namespace - - - - lib - -class Program -{ - static void Main(string[] args) - { - [|Project|] p = new Project(); - } -} - - -"; + const string InitialWorkspace = """ + + + + imports System.ComponentModel + namespace ProjectLib + <EditorBrowsable(EditorBrowsableState.Never)> + public class Project + end class + end namespace + + + + lib + + class Program + { + static void Main(string[] args) + { + [|Project|] p = new Project(); + } + } + + + + """; await TestMissingAsync(InitialWorkspace, new TestParameters(testHost: testHost)); } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/54544")] public async Task TestAddUsingsEditorBrowsableAdvancedDifferentProjectOptionOn(TestHost testHost) { - const string InitialWorkspace = @" - - - -imports System.ComponentModel -namespace ProjectLib - <EditorBrowsable(EditorBrowsableState.Advanced)> - public class Project - end class -end namespace - - - - lib - -class Program -{ - static void Main(string[] args) - { - [|Project|] p = new Project(); - } -} - - -"; - - const string ExpectedDocumentText = @" -class Program -{ - static void Main(string[] args) - { - ProjectLib.Project p = new Project(); - } -} -"; + const string InitialWorkspace = """ + + + + imports System.ComponentModel + namespace ProjectLib + <EditorBrowsable(EditorBrowsableState.Advanced)> + public class Project + end class + end namespace + + + + lib + class Program + { + static void Main(string[] args) + { + [|Project|] p = new Project(); + } + } + + + """; + + const string ExpectedDocumentText = """ + class Program + { + static void Main(string[] args) + { + ProjectLib.Project p = new Project(); + } + } + """; await TestInRegularAndScript1Async(InitialWorkspace, ExpectedDocumentText, new TestParameters(testHost: testHost)); } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/54544")] - public async Task TestAddUsingsEditorBrowsableAdvancedDifferentProjectOptionOff(TestHost testHost) - { - var initialWorkspace = @" - - - -imports System.ComponentModel -namespace ProjectLib - <EditorBrowsable(EditorBrowsableState.Advanced)> - public class Project - end class -end namespace - - - - lib - -class Program -{ - static void Main(string[] args) - { - [|Project|] p = new Project(); - } -} - - -"; - - await TestMissingAsync(initialWorkspace, new TestParameters( + public Task TestAddUsingsEditorBrowsableAdvancedDifferentProjectOptionOff(TestHost testHost) + => TestMissingAsync(""" + + + + imports System.ComponentModel + namespace ProjectLib + <EditorBrowsable(EditorBrowsableState.Advanced)> + public class Project + end class + end namespace + + + + lib + + class Program + { + static void Main(string[] args) + { + [|Project|] p = new Project(); + } + } + + + + """, new TestParameters( options: Option(MemberDisplayOptionsStorage.HideAdvancedMembers, true), testHost: testHost)); - } } diff --git a/src/Features/CSharpTest/FullyQualify/FullyQualifyUnboundIdentifierTests.cs b/src/Features/CSharpTest/FullyQualify/FullyQualifyUnboundIdentifierTests.cs index fa8d15bec5f2f..0d1b80f88ae4b 100644 --- a/src/Features/CSharpTest/FullyQualify/FullyQualifyUnboundIdentifierTests.cs +++ b/src/Features/CSharpTest/FullyQualify/FullyQualifyUnboundIdentifierTests.cs @@ -32,58 +32,62 @@ protected override ImmutableArray MassageActions(ImmutableArray FlattenActions(actions); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26887")] - public async Task TestFullyQualifyUnboundIdentifier1() - { - await TestInRegularAndScriptAsync( -@"public class Program -{ - public class Inner - { - } -} + public Task TestFullyQualifyUnboundIdentifier1() + => TestInRegularAndScriptAsync( + """ + public class Program + { + public class Inner + { + } + } -class Test -{ - [|Inner|] -}", -@"public class Program -{ - public class Inner - { - } -} + class Test + { + [|Inner|] + } + """, + """ + public class Program + { + public class Inner + { + } + } -class Test -{ - Program.Inner -}"); - } + class Test + { + Program.Inner + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26887")] - public async Task TestFullyQualifyUnboundIdentifier2() - { - await TestInRegularAndScriptAsync( -@"public class Program -{ - public class Inner - { - } -} + public Task TestFullyQualifyUnboundIdentifier2() + => TestInRegularAndScriptAsync( + """ + public class Program + { + public class Inner + { + } + } -class Test -{ - public [|Inner|] -}", -@"public class Program -{ - public class Inner - { - } -} + class Test + { + public [|Inner|] + } + """, + """ + public class Program + { + public class Inner + { + } + } -class Test -{ - public Program.Inner -}"); - } + class Test + { + public Program.Inner + } + """); } diff --git a/src/Features/CSharpTest/GenerateComparisonOperators/GenerateComparisonOperatorsTests.cs b/src/Features/CSharpTest/GenerateComparisonOperators/GenerateComparisonOperatorsTests.cs index 9d79e97e583a3..3263b9dcd5040 100644 --- a/src/Features/CSharpTest/GenerateComparisonOperators/GenerateComparisonOperatorsTests.cs +++ b/src/Features/CSharpTest/GenerateComparisonOperators/GenerateComparisonOperatorsTests.cs @@ -7,22 +7,23 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; +using Microsoft.CodeAnalysis.GenerateComparisonOperators; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; -using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeRefactoringVerifier< - Microsoft.CodeAnalysis.GenerateComparisonOperators.GenerateComparisonOperatorsCodeRefactoringProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.GenerateComparisonOperators; +using VerifyCS = CSharpCodeRefactoringVerifier< + GenerateComparisonOperatorsCodeRefactoringProvider>; + [UseExportProvider] [Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public sealed class GenerateComparisonOperatorsTests { [Fact] - public async Task TestClass() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestClass() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -59,12 +60,10 @@ class C : IComparable } } """); - } [Fact] - public async Task TestPreferExpressionBodies() - { - await new VerifyCS.Test + public Task TestPreferExpressionBodies() + => new VerifyCS.Test { TestCode = """ @@ -95,12 +94,10 @@ class C : IComparable { CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement }, }), }.RunAsync(); - } [Fact] - public async Task TestExplicitImpl() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestExplicitImpl() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -137,12 +134,10 @@ class C : IComparable } } """); - } [Fact] - public async Task TestOnInterface() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestOnInterface() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -179,12 +174,10 @@ class C : IComparable } } """); - } [Fact] - public async Task TestAtEndOfInterface() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestAtEndOfInterface() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -221,12 +214,10 @@ class C : IComparable } } """); - } [Fact] - public async Task TestInBody() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestInBody() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -265,7 +256,6 @@ class C : IComparable } } """); - } [Fact] public async Task TestMissingWithoutCompareMethod() @@ -338,9 +328,8 @@ class C : IComparable } [Fact] - public async Task TestWithExistingOperator() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestWithExistingOperator() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -384,7 +373,6 @@ class C : IComparable } } """); - } [Fact] public async Task TestMultipleInterfaces() @@ -451,9 +439,8 @@ class C : IComparable, IComparable // TODO: Enable test on .NET Core // https://github.com/dotnet/roslyn/issues/71625 [ConditionalFact(typeof(DesktopOnly))] - public async Task TestInInterfaceWithDefaultImpl() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestInInterfaceWithDefaultImpl() + => VerifyCS.VerifyRefactoringAsync( """ using System; @@ -492,6 +479,5 @@ interface C : IComparable } } """); - } } diff --git a/src/Features/CSharpTest/GenerateFromMembers/AddConstructorParametersFromMembers/AddConstructorParametersFromMembersTests.cs b/src/Features/CSharpTest/GenerateFromMembers/AddConstructorParametersFromMembers/AddConstructorParametersFromMembersTests.cs index 19d2ad1c3f12e..d2f4a47296b0c 100644 --- a/src/Features/CSharpTest/GenerateFromMembers/AddConstructorParametersFromMembers/AddConstructorParametersFromMembersTests.cs +++ b/src/Features/CSharpTest/GenerateFromMembers/AddConstructorParametersFromMembers/AddConstructorParametersFromMembersTests.cs @@ -55,9 +55,8 @@ public sealed class AddConstructorParametersFromMembersTests [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33603")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/308077")] - public async Task TestAdd1() - { - await new VerifyCS.Test + public Task TestAdd1() + => new VerifyCS.Test { TestCode = """ @@ -92,12 +91,10 @@ public Program(int i, string s) """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(FeaturesResources.Add_parameters_to_0, "Program(int i)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58040")] - public async Task TestProperlyWrapParameters1() - { - await new VerifyCS.Test + public Task TestProperlyWrapParameters1() + => new VerifyCS.Test { TestCode = """ @@ -134,12 +131,10 @@ public Program( """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(FeaturesResources.Add_parameters_to_0, "Program(int i)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58040")] - public async Task TestProperlyWrapParameters2() - { - await new VerifyCS.Test + public Task TestProperlyWrapParameters2() + => new VerifyCS.Test { TestCode = """ @@ -183,12 +178,10 @@ public Program( """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(FeaturesResources.Add_parameters_to_0, "Program(int i, string s)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58040")] - public async Task TestProperlyWrapParameters3() - { - await new VerifyCS.Test + public Task TestProperlyWrapParameters3() + => new VerifyCS.Test { TestCode = """ @@ -230,12 +223,10 @@ public Program(int i, """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(FeaturesResources.Add_parameters_to_0, "Program(int i, string s)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58040")] - public async Task TestProperlyWrapParameters4() - { - await new VerifyCS.Test + public Task TestProperlyWrapParameters4() + => new VerifyCS.Test { TestCode = """ @@ -277,13 +268,11 @@ public Program(int i, """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(FeaturesResources.Add_parameters_to_0, "Program(int i, string s)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33603")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/308077")] - public async Task TestAddOptional1() - { - await new VerifyCS.Test() + public Task TestAddOptional1() + => new VerifyCS.Test() { TestCode = """ @@ -319,14 +308,11 @@ public Program(int i, string s = null) CodeActionIndex = 1, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(FeaturesResources.Add_optional_parameters_to_0, "Program(int i)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33603")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/308077")] - public async Task TestAddToConstructorWithMostMatchingParameters1() - { - // behavior change with 33603, now all constructors offered - await new VerifyCS.Test() + public Task TestAddToConstructorWithMostMatchingParameters1() + => new VerifyCS.Test() { TestCode = """ @@ -374,14 +360,11 @@ public Program(int i, string s, bool b) : this(i) CodeActionIndex = 1, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(CodeFixesResources.Add_to_0, "Program(int i, string s)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33603")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/308077")] - public async Task TestAddOptionalToConstructorWithMostMatchingParameters1() - { - // Behavior change with #33603, now all constructors are offered - await new VerifyCS.Test() + public Task TestAddOptionalToConstructorWithMostMatchingParameters1() + => new VerifyCS.Test() { TestCode = """ @@ -429,12 +412,10 @@ public Program(int i, string s, bool b = false) : this(i) CodeActionIndex = 3, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(CodeFixesResources.Add_to_0, "Program(int i, string s)"), codeAction.Title) }.RunAsync(); - } [Fact] - public async Task TestSmartTagDisplayText1() - { - await new VerifyCS.Test + public Task TestSmartTagDisplayText1() + => new VerifyCS.Test { TestCode = """ @@ -469,12 +450,10 @@ public Program(bool b, HashSet s) """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(FeaturesResources.Add_parameters_to_0, "Program(bool b)"), codeAction.Title) }.RunAsync(); - } [Fact] - public async Task TestSmartTagDisplayText2() - { - await new VerifyCS.Test + public Task TestSmartTagDisplayText2() + => new VerifyCS.Test { TestCode = """ @@ -510,12 +489,10 @@ public Program(bool b, HashSet s = null) CodeActionIndex = 1, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(FeaturesResources.Add_optional_parameters_to_0, "Program(bool b)"), codeAction.Title) }.RunAsync(); - } [Fact] - public async Task TestTuple() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestTuple() + => VerifyCS.VerifyRefactoringAsync( """ class Program { @@ -541,12 +518,10 @@ public Program((int, string) i, (string, int) s) } } """); - } [Fact] - public async Task TestTupleWithNames() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestTupleWithNames() + => VerifyCS.VerifyRefactoringAsync( """ class Program { @@ -572,12 +547,10 @@ public Program((int a, string b) i, (string c, int d) s) } } """); - } [Fact] - public async Task TestTupleWithDifferentNames() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestTupleWithDifferentNames() + => VerifyCS.VerifyRefactoringAsync( """ class Program { @@ -603,12 +576,10 @@ public Program((int e, string f) i, (string c, int d) s) } } """); - } [Fact] - public async Task TestTupleOptionalCSharp7() - { - await new VerifyCS.Test + public Task TestTupleOptionalCSharp7() + => new VerifyCS.Test { TestCode = """ @@ -640,12 +611,10 @@ class Program CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp7 }.RunAsync(); - } [Fact] - public async Task TestTupleOptional() - { - await new VerifyCS.Test + public Task TestTupleOptional() + => new VerifyCS.Test { TestCode = """ @@ -676,12 +645,10 @@ public Program((int, string) i, (string, int) s = default) """, CodeActionIndex = 1 }.RunAsync(); - } [Fact] - public async Task TestTupleOptionalWithNames_CSharp7() - { - await new VerifyCS.Test + public Task TestTupleOptionalWithNames_CSharp7() + => new VerifyCS.Test { TestCode = """ @@ -713,12 +680,10 @@ class Program LanguageVersion = LanguageVersion.CSharp7, CodeActionIndex = 1 }.RunAsync(); - } [Fact] - public async Task TestTupleOptionalWithNamesCSharp7() - { - await new VerifyCS.Test + public Task TestTupleOptionalWithNamesCSharp7() + => new VerifyCS.Test { TestCode = """ @@ -750,12 +715,10 @@ class Program CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp7 }.RunAsync(); - } [Fact] - public async Task TestTupleOptionalWithNames() - { - await new VerifyCS.Test + public Task TestTupleOptionalWithNames() + => new VerifyCS.Test { TestCode = """ @@ -786,12 +749,10 @@ public Program((int a, string b) i, (string c, int d) s = default) """, CodeActionIndex = 1 }.RunAsync(); - } [Fact] - public async Task TestTupleOptionalWithDifferentNames() - { - await new VerifyCS.Test + public Task TestTupleOptionalWithDifferentNames() + => new VerifyCS.Test { TestCode = """ @@ -822,12 +783,10 @@ public Program((int e, string f) i, (string c, int d) s = default) """, CodeActionIndex = 1 }.RunAsync(); - } [Fact] - public async Task TestTupleWithNullable() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestTupleWithNullable() + => VerifyCS.VerifyRefactoringAsync( """ class Program { @@ -853,12 +812,10 @@ public Program((int?, bool?) i, (byte?, long?) s) } } """); - } [Fact] - public async Task TestTupleWithGenericss() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestTupleWithGenericss() + => VerifyCS.VerifyRefactoringAsync( """ using System.Collections.Generic; @@ -888,12 +845,10 @@ public Program((List, List) i, (List, List) s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28775")] - public async Task TestAddParamtersToConstructorBySelectOneMember() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestAddParamtersToConstructorBySelectOneMember() + => VerifyCS.VerifyRefactoringAsync( """ using System.Collections.Generic; @@ -927,12 +882,10 @@ public C(int i, int j, (List, List) s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28775")] - public async Task TestParametersAreStillRightIfMembersAreOutOfOrder() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestParametersAreStillRightIfMembersAreOutOfOrder() + => VerifyCS.VerifyRefactoringAsync( """ class C { @@ -962,7 +915,6 @@ public C(int i, int j, int k) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28775")] public async Task TestMissingIfFieldsAlreadyExistingInConstructor() @@ -999,9 +951,8 @@ public C(string bar, int helloWorld) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28775")] - public async Task TestNormalProperty() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestNormalProperty() + => VerifyCS.VerifyRefactoringAsync( """ class C { @@ -1024,12 +975,10 @@ public C(int i, int hello) } """ ); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33602")] - public async Task TestConstructorWithNoParameters() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestConstructorWithNoParameters() + => VerifyCS.VerifyRefactoringAsync( """ class C { @@ -1053,7 +1002,6 @@ public C(int i, int hello) } """ ); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33602")] public async Task TestDefaultConstructor() @@ -1070,9 +1018,8 @@ class C } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33601")] - public async Task TestPartialSelected() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestPartialSelected() + => VerifyCS.VerifyRefactoringAsync( """ class C { @@ -1095,12 +1042,10 @@ public C(int i, int j) } """ ); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33601")] - public async Task TestPartialMultipleSelected() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestPartialMultipleSelected() + => VerifyCS.VerifyRefactoringAsync( """ class C { @@ -1126,12 +1071,10 @@ public C(int i, int j, int k) } """ ); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33601")] - public async Task TestPartialMultipleSelected2() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestPartialMultipleSelected2() + => VerifyCS.VerifyRefactoringAsync( """ class C { @@ -1156,12 +1099,10 @@ public C(int i, int j) } """ ); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33603")] - public async Task TestMultipleConstructors_FirstofThree() - { - await new VerifyCS.Test + public Task TestMultipleConstructors_FirstofThree() + => new VerifyCS.Test { TestCode = """ @@ -1198,13 +1139,12 @@ public C(int i, int j, int k) """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(CodeFixesResources.Add_to_0, "C(int i)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33603")] - public async Task TestMultipleConstructors_SecondOfThree() - { - var source = - """ + public Task TestMultipleConstructors_SecondOfThree() + => new VerifyCS.Test + { + TestCode = """ class C { int [|l|]; @@ -1218,9 +1158,8 @@ public C(int i, int j, int k) { } } - """; - var expected = - """ + """, + FixedCode = """ class C { int l; @@ -1235,21 +1174,16 @@ public C(int i, int j, int l) { } } - """; - await new VerifyCS.Test - { - TestCode = source, - FixedCode = expected, + """, CodeActionIndex = 1, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(CodeFixesResources.Add_to_0, "C(int i, int j)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33603")] - public async Task TestMultipleConstructors_ThirdOfThree() - { - var source = - """ + public Task TestMultipleConstructors_ThirdOfThree() + => new VerifyCS.Test + { + TestCode = """ class C { int [|l|]; @@ -1263,10 +1197,8 @@ public C(int i, int j, int k) { } } - """; - - var expected = - """ + """, + FixedCode = """ class C { int l; @@ -1281,21 +1213,16 @@ public C(int i, int j, int k, int l) this.l = l; } } - """; - await new VerifyCS.Test - { - TestCode = source, - FixedCode = expected, + """, CodeActionIndex = 2, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(CodeFixesResources.Add_to_0, "C(int i, int j, int k)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33603")] - public async Task TestMultipleConstructors_FirstOptionalOfThree() - { - var source = - """ + public Task TestMultipleConstructors_FirstOptionalOfThree() + => new VerifyCS.Test + { + TestCode = """ class C { int [|l|]; @@ -1309,9 +1236,8 @@ public C(int i, int j, int k) { } } - """; - var expected = - """ + """, + FixedCode = """ class C { int l; @@ -1326,21 +1252,16 @@ public C(int i, int j, int k) { } } - """; - await new VerifyCS.Test - { - TestCode = source, - FixedCode = expected, + """, CodeActionIndex = 3, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(CodeFixesResources.Add_to_0, "C(int i)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33603")] - public async Task TestMultipleConstructors_SecondOptionalOfThree() - { - var source = - """ + public Task TestMultipleConstructors_SecondOptionalOfThree() + => new VerifyCS.Test + { + TestCode = """ class C { int [|l|]; @@ -1354,9 +1275,8 @@ public C(int i, int j, int k) { } } - """; - var expected = - """ + """, + FixedCode = """ class C { int [|l|]; @@ -1371,22 +1291,16 @@ public C(int i, int j, int l = 0) { } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = expected, + """, CodeActionIndex = 4, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(CodeFixesResources.Add_to_0, "C(int i, int j)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33603")] - public async Task TestMultipleConstructors_ThirdOptionalOfThree() - { - var source = - """ + public Task TestMultipleConstructors_ThirdOptionalOfThree() + => new VerifyCS.Test + { + TestCode = """ class C { int [|l|]; @@ -1400,9 +1314,8 @@ public C(int i, int j, int k) { } } - """; - var expected = - """ + """, + FixedCode = """ class C { int [|l|]; @@ -1417,21 +1330,16 @@ public C(int i, int j, int k, int l = 0) this.l = l; } } - """; - await new VerifyCS.Test - { - TestCode = source, - FixedCode = expected, + """, CodeActionIndex = 5, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(CodeFixesResources.Add_to_0, "C(int i, int j, int k)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33603")] - public async Task TestMultipleConstructors_OneMustBeOptional() - { - var source = - """ + public Task TestMultipleConstructors_OneMustBeOptional() + => new VerifyCS.Test + { + TestCode = """ class C { int [|l|]; @@ -1453,9 +1361,8 @@ public C(int i, double j, int k) { } } - """; - var expected = - """ + """, + FixedCode = """ class C { int [|l|]; @@ -1478,21 +1385,16 @@ public C(int i, double j, int k, int l) this.l = l; } } - """; - await new VerifyCS.Test - { - TestCode = source, - FixedCode = expected, + """, CodeActionIndex = 1, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(CodeFixesResources.Add_to_0, "C(int i, double j, int k)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33603")] - public async Task TestMultipleConstructors_OneMustBeOptional2() - { - var source = - """ + public Task TestMultipleConstructors_OneMustBeOptional2() + => new VerifyCS.Test + { + TestCode = """ class C { int [|l|]; @@ -1512,9 +1414,8 @@ public C(int i, double j, int k) { } } - """; - var expected = - """ + """, + FixedCode = """ class C { int [|l|]; @@ -1535,20 +1436,14 @@ public C(int i, double j = 0, int l = 0) { } } - """; - await new VerifyCS.Test - { - TestCode = source, - FixedCode = expected, + """, CodeActionIndex = 3, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(CodeFixesResources.Add_to_0, "C(int i, double j)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33603")] - public async Task TestMultipleConstructors_AllMustBeOptional() - { - await new VerifyCS.Test + public Task TestMultipleConstructors_AllMustBeOptional() + => new VerifyCS.Test { TestCode = """ @@ -1585,13 +1480,12 @@ public C(int l, double m, int n = 0) """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(CodeFixesResources.Add_to_0, "C(int i)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33603")] - public async Task TestMultipleConstructors_AllMustBeOptional2() - { - var source = - """ + public Task TestMultipleConstructors_AllMustBeOptional2() + => new VerifyCS.Test + { + TestCode = """ class C { int [|p|]; @@ -1605,9 +1499,8 @@ public C(int l, double m, int n = 0) { } } - """; - var expected = - """ + """, + FixedCode = """ class C { int [|p|]; @@ -1622,15 +1515,10 @@ public C(int l, double m, int n = 0, int p = 0) this.p = p; } } - """; - await new VerifyCS.Test - { - TestCode = source, - FixedCode = expected, + """, CodeActionIndex = 2, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(CodeFixesResources.Add_to_0, "C(int l, double m, int n)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33623")] public async Task TestDeserializationConstructor() @@ -1653,10 +1541,10 @@ private C(SerializationInfo info, StreamingContext context) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35775")] - public async Task TestNoFieldNamingStyle_ParameterPrefixAndSuffix() - { - var source = - """ + public Task TestNoFieldNamingStyle_ParameterPrefixAndSuffix() + => new VerifyCS.Test + { + TestCode = """ class C { private int [|v|]; @@ -1664,10 +1552,8 @@ public C() { } } - """; - - var expected = - """ + """, + FixedCode = """ class C { private int v; @@ -1676,20 +1562,15 @@ public C(int p_v_End) v = p_v_End; } } - """; - await new VerifyCS.Test - { - TestCode = source, - FixedCode = expected, + """, EditorConfig = ParameterNamesCamelCaseWithPUnderscorePrefixEndUnderscoreSuffixEditorConfig }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35775")] - public async Task TestCommonFieldNamingStyle() - { - var source = - """ + public Task TestCommonFieldNamingStyle() + => new VerifyCS.Test + { + TestCode = """ class C { private int [|t_v|]; @@ -1697,10 +1578,8 @@ public C() { } } - """; - - var expected = - """ + """, + FixedCode = """ class C { private int t_v; @@ -1709,20 +1588,15 @@ public C(int p_v) t_v = p_v; } } - """; - await new VerifyCS.Test - { - TestCode = source, - FixedCode = expected, + """, EditorConfig = ParameterNamesCamelCaseWithPUnderscorePrefixEditorConfig }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35775")] - public async Task TestSpecifiedFieldNamingStyle() - { - var source = - """ + public Task TestSpecifiedFieldNamingStyle() + => new VerifyCS.Test + { + TestCode = """ class C { private int [|field_v|]; @@ -1730,10 +1604,8 @@ public C() { } } - """; - - var expected = - """ + """, + FixedCode = """ class C { private int field_v; @@ -1742,20 +1614,15 @@ public C(int p_v) field_v = p_v; } } - """; - await new VerifyCS.Test - { - TestCode = source, - FixedCode = expected, + """, EditorConfig = FieldNamesCamelCaseWithFieldUnderscorePrefixEditorConfig + ParameterNamesCamelCaseWithPUnderscorePrefixEditorConfig }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35775")] - public async Task TestSpecifiedAndCommonFieldNamingStyle() - { - var source = - """ + public Task TestSpecifiedAndCommonFieldNamingStyle() + => new VerifyCS.Test + { + TestCode = """ class C { private int [|field_s_v|]; @@ -1763,10 +1630,8 @@ public C() { } } - """; - - var expected = - """ + """, + FixedCode = """ class C { private int field_s_v; @@ -1775,21 +1640,15 @@ public C(int p_v) field_s_v = p_v; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = expected, + """, EditorConfig = FieldNamesCamelCaseWithFieldUnderscorePrefixEditorConfig + ParameterNamesCamelCaseWithPUnderscorePrefixEditorConfig }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35775")] - public async Task TestSpecifiedAndCommonFieldNamingStyle2() - { - var source = - """ + public Task TestSpecifiedAndCommonFieldNamingStyle2() + => new VerifyCS.Test + { + TestCode = """ class C { private int [|s_field_v|]; @@ -1797,10 +1656,8 @@ public C() { } } - """; - - var expected = - """ + """, + FixedCode = """ class C { private int s_field_v; @@ -1809,20 +1666,15 @@ public C(int p_v) s_field_v = p_v; } } - """; - await new VerifyCS.Test - { - TestCode = source, - FixedCode = expected, + """, EditorConfig = FieldNamesCamelCaseWithFieldUnderscorePrefixEditorConfig + ParameterNamesCamelCaseWithPUnderscorePrefixEditorConfig }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35775")] - public async Task TestBaseNameEmpty() - { - var source = - """ + public Task TestBaseNameEmpty() + => new VerifyCS.Test + { + TestCode = """ class C { private int [|field__End|]; @@ -1830,20 +1682,15 @@ public C() { } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, EditorConfig = FieldNamesCamelCaseWithFieldUnderscorePrefixEndUnderscoreSuffixEditorConfig }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35775")] - public async Task TestSomeBaseNamesAreEmpty() - { - var source = - """ + public Task TestSomeBaseNamesAreEmpty() + => new VerifyCS.Test + { + TestCode = """ class C { private int [|field_test_End; @@ -1852,10 +1699,8 @@ public C() { } } - """; - - var expected = - """ + """, + FixedCode = """ class C { private int field_test_End; @@ -1865,21 +1710,15 @@ public C(int p_test) field_test_End = p_test; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = expected, + """, EditorConfig = FieldNamesCamelCaseWithFieldUnderscorePrefixEndUnderscoreSuffixEditorConfig + ParameterNamesCamelCaseWithPUnderscorePrefixEditorConfig }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35775")] - public async Task TestManyCommonPrefixes() - { - var source = - """ + public Task TestManyCommonPrefixes() + => new VerifyCS.Test + { + TestCode = """ class C { private int [|______test|]; @@ -1887,10 +1726,8 @@ public C() { } } - """; - - var expected = - """ + """, + FixedCode = """ class C { private int ______test; @@ -1899,20 +1736,13 @@ public C(int p_test) ______test = p_test; } } - """; - - await new VerifyCS.Test - { - TestCode = source, - FixedCode = expected, + """, EditorConfig = ParameterNamesCamelCaseWithPUnderscorePrefixEditorConfig }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23271")] - public async Task TestNonSelection1() - { - await new VerifyCS.Test + public Task TestNonSelection1() + => new VerifyCS.Test { TestCode = """ @@ -1947,12 +1777,10 @@ public Program(int i, string s) """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(FeaturesResources.Add_parameters_to_0, "Program(int i)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23271")] - public async Task TestNonSelection2() - { - await new VerifyCS.Test + public Task TestNonSelection2() + => new VerifyCS.Test { TestCode = """ @@ -1987,12 +1815,10 @@ public Program(int i, string s) """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(FeaturesResources.Add_parameters_to_0, "Program(int i)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23271")] - public async Task TestNonSelection3() - { - await new VerifyCS.Test + public Task TestNonSelection3() + => new VerifyCS.Test { TestCode = """ @@ -2027,12 +1853,10 @@ public Program(int i, string s) """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(FeaturesResources.Add_parameters_to_0, "Program(int i)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23271")] - public async Task TestNonSelection4() - { - await new VerifyCS.Test + public Task TestNonSelection4() + => new VerifyCS.Test { TestCode = """ @@ -2067,12 +1891,10 @@ public Program(int i, string s) """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(FeaturesResources.Add_parameters_to_0, "Program(int i)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23271")] - public async Task TestNonSelection5() - { - await new VerifyCS.Test + public Task TestNonSelection5() + => new VerifyCS.Test { TestCode = """ @@ -2107,12 +1929,10 @@ public Program(int i, string s) """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(FeaturesResources.Add_parameters_to_0, "Program(int i)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23271")] - public async Task TestNonSelection6() - { - await new VerifyCS.Test + public Task TestNonSelection6() + => new VerifyCS.Test { TestCode = """ @@ -2147,12 +1967,10 @@ public Program(int i, string s) """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(FeaturesResources.Add_parameters_to_0, "Program(int i)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23271")] - public async Task TestNonSelectionMultiVar1() - { - await new VerifyCS.Test + public Task TestNonSelectionMultiVar1() + => new VerifyCS.Test { TestCode = """ @@ -2188,12 +2006,10 @@ public Program(int i, string s, string t) """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(FeaturesResources.Add_parameters_to_0, "Program(int i)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23271")] - public async Task TestNonSelectionMultiVar2() - { - await new VerifyCS.Test + public Task TestNonSelectionMultiVar2() + => new VerifyCS.Test { TestCode = """ @@ -2229,12 +2045,10 @@ public Program(int i, string s, string t) """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(FeaturesResources.Add_parameters_to_0, "Program(int i)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23271")] - public async Task TestNonSelectionMultiVar3() - { - await new VerifyCS.Test + public Task TestNonSelectionMultiVar3() + => new VerifyCS.Test { TestCode = """ @@ -2269,12 +2083,10 @@ public Program(int i, string s) """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(FeaturesResources.Add_parameters_to_0, "Program(int i)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23271")] - public async Task TestNonSelectionMultiVar4() - { - await new VerifyCS.Test + public Task TestNonSelectionMultiVar4() + => new VerifyCS.Test { TestCode = """ @@ -2309,12 +2121,10 @@ public Program(int i, string s) """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(FeaturesResources.Add_parameters_to_0, "Program(int i)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23271")] - public async Task TestNonSelectionMultiVar5() - { - await new VerifyCS.Test + public Task TestNonSelectionMultiVar5() + => new VerifyCS.Test { TestCode = """ @@ -2349,12 +2159,10 @@ public Program(int i, string t) """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(FeaturesResources.Add_parameters_to_0, "Program(int i)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23271")] - public async Task TestNonSelectionMultiVar6() - { - await new VerifyCS.Test + public Task TestNonSelectionMultiVar6() + => new VerifyCS.Test { TestCode = """ @@ -2389,7 +2197,6 @@ public Program(int i, string t) """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(FeaturesResources.Add_parameters_to_0, "Program(int i)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23271")] public async Task TestNonSelectionMissing1() @@ -2477,9 +2284,8 @@ public Program(int i) } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/59292")] - public async Task TestPartialClass1() - { - await new VerifyCS.Test + public Task TestPartialClass1() + => new VerifyCS.Test { TestState = { @@ -2523,12 +2329,10 @@ public C(int v) } } }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/59292")] - public async Task TestPartialClass2() - { - await new VerifyCS.Test + public Task TestPartialClass2() + => new VerifyCS.Test { TestState = { @@ -2581,12 +2385,10 @@ public C(object goo, int v) }, CodeActionIndex = 1 }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/59292")] - public async Task TestPartialClass3() - { - await new VerifyCS.Test + public Task TestPartialClass3() + => new VerifyCS.Test { TestState = { @@ -2631,12 +2433,10 @@ public C(int v = 0) }, CodeActionIndex = 1 }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60816")] - public async Task TestAddMultipleParametersWithWrapping() - { - await new VerifyCS.Test + public Task TestAddMultipleParametersWithWrapping() + => new VerifyCS.Test { TestCode = """ @@ -2692,12 +2492,10 @@ public C( """, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(string.Format(FeaturesResources.Add_parameters_to_0, "C(int original, int original2)"), codeAction.Title) }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49112")] - public async Task TestAddParameterToExpressionBodiedConstructor() - { - await new VerifyCS.Test + public Task TestAddParameterToExpressionBodiedConstructor() + => new VerifyCS.Test { TestCode = """ @@ -2728,5 +2526,4 @@ public C(int x, int y) } """, }.RunAsync(); - } } diff --git a/src/Features/CSharpTest/GenerateOverrides/GenerateOverridesTests.cs b/src/Features/CSharpTest/GenerateOverrides/GenerateOverridesTests.cs index 11a267bb91bfc..6e6d09d346933 100644 --- a/src/Features/CSharpTest/GenerateOverrides/GenerateOverridesTests.cs +++ b/src/Features/CSharpTest/GenerateOverrides/GenerateOverridesTests.cs @@ -21,9 +21,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor => new GenerateOverridesCodeRefactoringProvider((IPickMembersService)parameters.fixProviderData); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] - public async Task Test1() - { - await TestWithPickMembersDialogAsync( + public Task Test1() + => TestWithPickMembersDialogAsync( """ class C { @@ -49,13 +48,11 @@ public override string ToString() } } """, ["Equals", "GetHashCode", "ToString"]); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] [WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestAtEndOfFile() - { - await TestWithPickMembersDialogAsync( + public Task TestAtEndOfFile() + => TestWithPickMembersDialogAsync( """ class C[||] """, @@ -79,13 +76,11 @@ public override string ToString() } """, ["Equals", "GetHashCode", "ToString"]); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] [WorkItem("https://github.com/dotnet/roslyn/issues/48295")] - public async Task TestOnRecordWithSemiColon() - { - await TestWithPickMembersDialogAsync(""" + public Task TestOnRecordWithSemiColon() + => TestWithPickMembersDialogAsync(""" record C[||]; """, """ record C @@ -102,13 +97,11 @@ public override string ToString() } """, ["GetHashCode", "ToString"]); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] [WorkItem("https://github.com/dotnet/roslyn/issues/17698")] - public async Task TestRefReturns() - { - await TestWithPickMembersDialogAsync( + public Task TestRefReturns() + => TestWithPickMembersDialogAsync( """ using System; @@ -150,12 +143,10 @@ public override ref int X() } } """, ["X", "Y", "this[]"]); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] - public async Task TestInitOnlyProperty() - { - await TestWithPickMembersDialogAsync( + public Task TestInitOnlyProperty() + => TestWithPickMembersDialogAsync( """ class Base { @@ -178,12 +169,10 @@ class Derived : Base public override int Property { init => base.Property = value; } } """, ["Property"]); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] - public async Task TestInitOnlyIndexer() - { - await TestWithPickMembersDialogAsync( + public Task TestInitOnlyIndexer() + => TestWithPickMembersDialogAsync( """ class Base { @@ -206,39 +195,33 @@ class Derived : Base public override int this[int i] { init => base[i] = value; } } """, ["this[]"]); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] [WorkItem("https://github.com/dotnet/roslyn/issues/21601")] - public async Task TestMissingInStaticClass1() - { - await TestMissingAsync( + public Task TestMissingInStaticClass1() + => TestMissingAsync( """ static class C { [||] } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] [WorkItem("https://github.com/dotnet/roslyn/issues/21601")] - public async Task TestMissingInStaticClass2() - { - await TestMissingAsync( + public Task TestMissingInStaticClass2() + => TestMissingAsync( """ static class [||]C { } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] [WorkItem("https://github.com/dotnet/roslyn/issues/53012")] - public async Task TestNullableTypeParameter() - { - await TestWithPickMembersDialogAsync( + public Task TestNullableTypeParameter() + => TestWithPickMembersDialogAsync( """ class C { @@ -266,12 +249,10 @@ public override void M(T1? a, T2 b, T1? c, T3? d) } } """, ["M"]); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] - public async Task TestRequiredProperty() - { - await TestWithPickMembersDialogAsync( + public Task TestRequiredProperty() + => TestWithPickMembersDialogAsync( """ class Base { @@ -294,5 +275,4 @@ class Derived : Base public override required int Property { get => base.Property; set => base.Property = value; } } """, ["Property"]); - } } diff --git a/src/Features/CSharpTest/GenerateVariable/GenerateVariableTests.cs b/src/Features/CSharpTest/GenerateVariable/GenerateVariableTests.cs index ae11956e5cffa..224c5691e417c 100644 --- a/src/Features/CSharpTest/GenerateVariable/GenerateVariableTests.cs +++ b/src/Features/CSharpTest/GenerateVariable/GenerateVariableTests.cs @@ -49,9 +49,8 @@ protected override ImmutableArray MassageActions(ImmutableArray FlattenActions(actions); [Fact] - public async Task TestSimpleLowercaseIdentifier1() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleLowercaseIdentifier1() + => TestInRegularAndScriptAsync( """ class Class { @@ -72,12 +71,10 @@ void Method() } } """); - } [Fact] - public async Task TestSimpleLowercaseIdentifierAllOptionsOffered() - { - await TestExactActionSetOfferedAsync( + public Task TestSimpleLowercaseIdentifierAllOptionsOffered() + => TestExactActionSetOfferedAsync( """ class Class { @@ -94,12 +91,10 @@ void Method() string.Format(CodeFixesResources.Generate_local_0, "goo"), string.Format(CodeFixesResources.Generate_parameter_0, "goo"), ]); - } [Fact] - public async Task TestUnderscorePrefixAllOptionsOffered() - { - await TestExactActionSetOfferedAsync( + public Task TestUnderscorePrefixAllOptionsOffered() + => TestExactActionSetOfferedAsync( """ class Class { @@ -113,12 +108,10 @@ void Method() string.Format(CodeFixesResources.Generate_field_0, "_goo"), string.Format(CodeFixesResources.Generate_read_only_field_0, "_goo"), ]); - } [Fact] - public async Task TestSimpleLowercaseIdentifier2() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleLowercaseIdentifier2() + => TestInRegularAndScriptAsync( """ class Class { @@ -139,13 +132,11 @@ void Method() } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact] - public async Task TestTestSimpleLowercaseIdentifier3() - { - await TestInRegularAndScriptAsync( + public Task TestTestSimpleLowercaseIdentifier3() + => TestInRegularAndScriptAsync( """ class Class { @@ -166,13 +157,11 @@ void Method() } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact] - public async Task TestSimpleUppercaseIdentifier1() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleUppercaseIdentifier1() + => TestInRegularAndScriptAsync( """ class Class { @@ -193,12 +182,10 @@ void Method() } } """); - } [Fact] - public async Task TestSimpleUppercaseIdentifier2() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleUppercaseIdentifier2() + => TestInRegularAndScriptAsync( """ class Class { @@ -219,13 +206,11 @@ void Method() } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact] - public async Task TestSimpleUppercaseIdentifier3() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleUppercaseIdentifier3() + => TestInRegularAndScriptAsync( """ class Class { @@ -246,13 +231,11 @@ void Method() } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact] - public async Task TestSimpleRead1() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleRead1() + => TestInRegularAndScriptAsync( """ class Class { @@ -273,12 +256,10 @@ void Method(int i) } } """); - } [Fact] - public async Task TestSimpleReadWithTopLevelNullability() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleReadWithTopLevelNullability() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -303,12 +284,10 @@ void Method(string? s) } } """); - } [Fact] - public async Task TestSimpleReadWithNestedNullability() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleReadWithNestedNullability() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -337,12 +316,10 @@ void Method(IEnumerable s) } } """); - } [Fact] - public async Task TestSimpleWriteCount() - { - await TestExactActionSetOfferedAsync( + public Task TestSimpleWriteCount() + => TestExactActionSetOfferedAsync( """ class Class { @@ -352,13 +329,11 @@ void Method(int i) } } """, -[string.Format(CodeFixesResources.Generate_field_0, "goo"), string.Format(CodeFixesResources.Generate_property_0, "goo"), string.Format(CodeFixesResources.Generate_local_0, "goo"), string.Format(CodeFixesResources.Generate_parameter_0, "goo")]); - } + [string.Format(CodeFixesResources.Generate_field_0, "goo"), string.Format(CodeFixesResources.Generate_property_0, "goo"), string.Format(CodeFixesResources.Generate_local_0, "goo"), string.Format(CodeFixesResources.Generate_parameter_0, "goo")]); [Fact] - public async Task TestSimpleWriteInOverrideCount() - { - await TestExactActionSetOfferedAsync( + public Task TestSimpleWriteInOverrideCount() + => TestExactActionSetOfferedAsync( """ abstract class Base { @@ -373,13 +348,11 @@ public override void Method(int i) } } """, -[string.Format(CodeFixesResources.Generate_field_0, "goo"), string.Format(CodeFixesResources.Generate_property_0, "goo"), string.Format(CodeFixesResources.Generate_local_0, "goo"), string.Format(CodeFixesResources.Generate_parameter_0, "goo"), string.Format(CodeFixesResources.Generate_parameter_0_and_overrides_implementations, "goo")]); - } + [string.Format(CodeFixesResources.Generate_field_0, "goo"), string.Format(CodeFixesResources.Generate_property_0, "goo"), string.Format(CodeFixesResources.Generate_local_0, "goo"), string.Format(CodeFixesResources.Generate_parameter_0, "goo"), string.Format(CodeFixesResources.Generate_parameter_0_and_overrides_implementations, "goo")]); [Fact] - public async Task TestSimpleWrite1() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleWrite1() + => TestInRegularAndScriptAsync( """ class Class { @@ -400,12 +373,10 @@ void Method(int i) } } """); - } [Fact] - public async Task TestSimpleWrite2() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleWrite2() + => TestInRegularAndScriptAsync( """ class Class { @@ -426,13 +397,11 @@ void Method(int i) } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact] - public async Task TestGenerateFieldInRef() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInRef() + => TestInRegularAndScriptAsync( """ class Class { @@ -453,12 +422,10 @@ void Method(ref int i) } } """); - } [Fact] - public async Task TestGeneratePropertyInRef() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyInRef() + => TestInRegularAndScriptAsync( """ using System; class Class @@ -481,12 +448,10 @@ void Method(ref int i) } } """, index: ReadonlyFieldIndex); - } [Fact] - public async Task TestGeneratePropertyInIn() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyInIn() + => TestInRegularAndScriptAsync( """ using System; class Class @@ -509,12 +474,10 @@ void Method(in int i) } } """, index: PropertyIndex); - } [Fact] - public async Task TestInRef1() - { - await TestInRegularAndScriptAsync( + public Task TestInRef1() + => TestInRegularAndScriptAsync( """ class Class { @@ -535,12 +498,10 @@ void Method(ref int i) } } """); - } [Fact] - public async Task TestInOutCodeActionCount() - { - await TestExactActionSetOfferedAsync( + public Task TestInOutCodeActionCount() + => TestExactActionSetOfferedAsync( """ class Class { @@ -550,13 +511,11 @@ void Method(out int i) } } """, -[string.Format(CodeFixesResources.Generate_field_0, "goo"), string.Format(CodeFixesResources.Generate_local_0, "goo"), string.Format(CodeFixesResources.Generate_parameter_0, "goo")]); - } + [string.Format(CodeFixesResources.Generate_field_0, "goo"), string.Format(CodeFixesResources.Generate_local_0, "goo"), string.Format(CodeFixesResources.Generate_parameter_0, "goo")]); [Fact] - public async Task TestInOut1() - { - await TestInRegularAndScriptAsync( + public Task TestInOut1() + => TestInRegularAndScriptAsync( """ class Class { @@ -577,12 +536,10 @@ void Method(out int i) } } """); - } [Fact] - public async Task TestGenerateInStaticMember1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInStaticMember1() + => TestInRegularAndScriptAsync( """ class Class { @@ -603,12 +560,10 @@ static void Method() } } """); - } [Fact] - public async Task TestGenerateInStaticMember2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInStaticMember2() + => TestInRegularAndScriptAsync( """ class Class { @@ -629,13 +584,11 @@ static void Method() } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact] - public async Task TestGenerateInStaticMember3() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInStaticMember3() + => TestInRegularAndScriptAsync( """ class Class { @@ -656,13 +609,11 @@ static void Method() } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact] - public async Task TestGenerateOffInstance1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateOffInstance1() + => TestInRegularAndScriptAsync( """ class Class { @@ -683,12 +634,10 @@ void Method() } } """); - } [Fact] - public async Task TestGenerateOffInstance2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateOffInstance2() + => TestInRegularAndScriptAsync( """ class Class { @@ -709,13 +658,11 @@ void Method() } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact] - public async Task TestGenerateOffInstance3() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateOffInstance3() + => TestInRegularAndScriptAsync( """ class Class { @@ -736,13 +683,11 @@ void Method() } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact] - public async Task TestGenerateOffWrittenInstance1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateOffWrittenInstance1() + => TestInRegularAndScriptAsync( """ class Class { @@ -763,12 +708,10 @@ void Method() } } """); - } [Fact] - public async Task TestGenerateOffWrittenInstance2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateOffWrittenInstance2() + => TestInRegularAndScriptAsync( """ class Class { @@ -789,13 +732,11 @@ void Method() } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact] - public async Task TestGenerateOffStatic1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateOffStatic1() + => TestInRegularAndScriptAsync( """ class Class { @@ -816,12 +757,10 @@ void Method() } } """); - } [Fact] - public async Task TestGenerateOffStatic2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateOffStatic2() + => TestInRegularAndScriptAsync( """ class Class { @@ -842,13 +781,11 @@ void Method() } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact] - public async Task TestGenerateOffStatic3() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateOffStatic3() + => TestInRegularAndScriptAsync( """ class Class { @@ -869,13 +806,11 @@ void Method() } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact] - public async Task TestGenerateOffWrittenStatic1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateOffWrittenStatic1() + => TestInRegularAndScriptAsync( """ class Class { @@ -896,12 +831,10 @@ void Method() } } """); - } [Fact] - public async Task TestGenerateOffWrittenStatic2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateOffWrittenStatic2() + => TestInRegularAndScriptAsync( """ class Class { @@ -922,13 +855,11 @@ void Method() } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact] - public async Task TestGenerateInstanceIntoSibling1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInstanceIntoSibling1() + => TestInRegularAndScriptAsync( """ class Class { @@ -956,12 +887,10 @@ class D internal object goo; } """); - } [Fact] - public async Task TestGenerateInstanceIntoOuter1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInstanceIntoOuter1() + => TestInRegularAndScriptAsync( """ class Outer { @@ -988,12 +917,10 @@ void Method() } } """); - } [Fact] - public async Task TestGenerateInstanceIntoDerived1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInstanceIntoDerived1() + => TestInRegularAndScriptAsync( """ class Class : Base { @@ -1021,12 +948,10 @@ class Base internal object goo; } """); - } [Fact] - public async Task TestGenerateStaticIntoDerived1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateStaticIntoDerived1() + => TestInRegularAndScriptAsync( """ class Class : Base { @@ -1054,12 +979,10 @@ class Base protected static object goo; } """); - } [Fact] - public async Task TestGenerateIntoInterfaceFixCount() - { - await TestActionCountAsync( + public Task TestGenerateIntoInterfaceFixCount() + => TestActionCountAsync( """ class Class { @@ -1073,13 +996,11 @@ interface I { } """, -count: 2); - } + count: 2); [Fact] - public async Task TestGenerateIntoInterface1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateIntoInterface1() + => TestInRegularAndScriptAsync( """ class Class { @@ -1107,12 +1028,10 @@ interface I object Goo { get; set; } } """, index: ReadonlyFieldIndex); - } [Fact] - public async Task TestGenerateIntoInterface2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateIntoInterface2() + => TestInRegularAndScriptAsync( """ class Class { @@ -1140,12 +1059,10 @@ interface I object Goo { get; } } """); - } [Fact] - public async Task TestGenerateStaticIntoInterfaceMissing() - { - await TestMissingInRegularAndScriptAsync( + public Task TestGenerateStaticIntoInterfaceMissing() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -1159,12 +1076,10 @@ interface I { } """); - } [Fact] - public async Task TestGenerateWriteIntoInterfaceFixCount() - { - await TestActionCountAsync( + public Task TestGenerateWriteIntoInterfaceFixCount() + => TestActionCountAsync( """ class Class { @@ -1178,13 +1093,11 @@ interface I { } """, -count: 1); - } + count: 1); [Fact] - public async Task TestGenerateWriteIntoInterface1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateWriteIntoInterface1() + => TestInRegularAndScriptAsync( """ class Class { @@ -1212,12 +1125,10 @@ interface I int Goo { get; set; } } """); - } [Fact] - public async Task TestGenerateInGenericType() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInGenericType() + => TestInRegularAndScriptAsync( """ class Class { @@ -1238,12 +1149,10 @@ void Method(T t) } } """); - } [Fact] - public async Task TestGenerateInGenericMethod1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInGenericMethod1() + => TestInRegularAndScriptAsync( """ class Class { @@ -1264,12 +1173,10 @@ void Method(T t) } } """); - } [Fact] - public async Task TestGenerateInGenericMethod2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInGenericMethod2() + => TestInRegularAndScriptAsync( """ class Class { @@ -1290,12 +1197,10 @@ void Method(IList t) } } """); - } [Fact] - public async Task TestGenerateFieldBeforeFirstField() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldBeforeFirstField() + => TestInRegularAndScriptAsync( """ class Class { @@ -1319,12 +1224,10 @@ void Method() } } """); - } [Fact] - public async Task TestGenerateFieldAfterLastField() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldAfterLastField() + => TestInRegularAndScriptAsync( """ class Class { @@ -1348,12 +1251,10 @@ void Method() private object goo; } """); - } [Fact] - public async Task TestGeneratePropertyAfterLastField1() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyAfterLastField1() + => TestInRegularAndScriptAsync( """ class Class { @@ -1378,12 +1279,10 @@ void Method() } } """); - } [Fact] - public async Task TestGeneratePropertyAfterLastField2() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyAfterLastField2() + => TestInRegularAndScriptAsync( """ class Class { @@ -1408,12 +1307,10 @@ void Method() public object Goo { get; private set; } } """); - } [Fact] - public async Task TestGeneratePropertyBeforeFirstProperty() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyBeforeFirstProperty() + => TestInRegularAndScriptAsync( """ class Class { @@ -1437,12 +1334,10 @@ void Method() } } """); - } [Fact] - public async Task TestGeneratePropertyBeforeFirstPropertyEvenWithField1() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyBeforeFirstPropertyEvenWithField1() + => TestInRegularAndScriptAsync( """ class Class { @@ -1470,12 +1365,10 @@ void Method() } } """); - } [Fact] - public async Task TestGeneratePropertyAfterLastPropertyEvenWithField2() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyAfterLastPropertyEvenWithField2() + => TestInRegularAndScriptAsync( """ class Class { @@ -1503,12 +1396,10 @@ void Method() } } """); - } [Fact] - public async Task TestMissingInInvocation() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingInInvocation() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -1518,12 +1409,10 @@ void Method() } } """); - } [Fact] - public async Task TestMissingInObjectCreation() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingInObjectCreation() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -1533,7 +1422,6 @@ void Method() } } """); - } [Fact] public async Task TestMissingInTypeDeclaration() @@ -1785,9 +1673,8 @@ void M() } [Fact] - public async Task TestGenerateFieldInSimpleLambda() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInSimpleLambda() + => TestInRegularAndScriptAsync( """ using System; @@ -1812,12 +1699,10 @@ static void Main(string[] args) } } """, FieldIndex); - } [Fact] - public async Task TestGenerateFieldInParenthesizedLambda() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInParenthesizedLambda() + => TestInRegularAndScriptAsync( """ using System; @@ -1842,12 +1727,10 @@ static void Main(string[] args) } } """, FieldIndex); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30232")] - public async Task TestGenerateFieldInAsyncTaskOfTSimpleLambda() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInAsyncTaskOfTSimpleLambda() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1874,12 +1757,10 @@ static void Main(string[] args) } } """, FieldIndex); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30232")] - public async Task TestGenerateFieldInAsyncTaskOfTParenthesizedLambda() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInAsyncTaskOfTParenthesizedLambda() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -1906,12 +1787,10 @@ static void Main(string[] args) } } """, FieldIndex); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539427")] - public async Task TestGenerateFromLambda() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFromLambda() + => TestInRegularAndScriptAsync( """ class Class { @@ -1936,13 +1815,11 @@ void Method(int i) } } """); - } // TODO: Move to TypeInferrer.InferTypes, or something [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539466")] - public async Task TestGenerateInMethodOverload1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInMethodOverload1() + => TestInRegularAndScriptAsync( """ class Class { @@ -1963,13 +1840,11 @@ void Method(int i) } } """); - } // TODO: Move to TypeInferrer.InferTypes, or something [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539466")] - public async Task TestGenerateInMethodOverload2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInMethodOverload2() + => TestInRegularAndScriptAsync( """ class Class { @@ -1990,12 +1865,10 @@ void Method(int i) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539468")] - public async Task TestExplicitProperty1() - { - await TestInRegularAndScriptAsync( + public Task TestExplicitProperty1() + => TestInRegularAndScriptAsync( """ class Class : ITest { @@ -2017,12 +1890,10 @@ interface ITest bool SomeProp { get; set; } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539468")] - public async Task TestExplicitProperty2() - { - await TestInRegularAndScriptAsync( + public Task TestExplicitProperty2() + => TestInRegularAndScriptAsync( """ class Class : ITest { @@ -2044,12 +1915,10 @@ interface ITest bool SomeProp { get; set; } } """, index: ReadonlyFieldIndex); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539468")] - public async Task TestExplicitProperty3() - { - await TestInRegularAndScriptAsync( + public Task TestExplicitProperty3() + => TestInRegularAndScriptAsync( """ class Class : ITest { @@ -2071,12 +1940,10 @@ interface ITest bool SomeProp { get; } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539468")] - public async Task TestExplicitProperty4() - { - await TestMissingInRegularAndScriptAsync( + public Task TestExplicitProperty4() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -2087,12 +1954,10 @@ interface ITest { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539468")] - public async Task TestExplicitProperty5() - { - await TestMissingInRegularAndScriptAsync( + public Task TestExplicitProperty5() + => TestMissingInRegularAndScriptAsync( """ class Class : ITest { @@ -2104,12 +1969,10 @@ interface ITest bool SomeProp { get; } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] - public async Task TestEscapedName() - { - await TestInRegularAndScriptAsync( + public Task TestEscapedName() + => TestInRegularAndScriptAsync( """ class Class { @@ -2130,12 +1993,10 @@ void Method() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] - public async Task TestEscapedKeyword() - { - await TestInRegularAndScriptAsync( + public Task TestEscapedKeyword() + => TestInRegularAndScriptAsync( """ class Class { @@ -2156,12 +2017,10 @@ void Method() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539529")] - public async Task TestRefLambda() - { - await TestInRegularAndScriptAsync( + public Task TestRefLambda() + => TestInRegularAndScriptAsync( """ class Class { @@ -2182,12 +2041,10 @@ void Method() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539595")] - public async Task TestNotOnError() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOnError() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -2197,12 +2054,10 @@ void F(U u1, V v1) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539571")] - public async Task TestNameSimplification() - { - await TestInRegularAndScriptAsync( + public Task TestNameSimplification() + => TestInRegularAndScriptAsync( """ namespace TestNs { @@ -2235,12 +2090,10 @@ void Meth() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539717")] - public async Task TestPostIncrement() - { - await TestInRegularAndScriptAsync( + public Task TestPostIncrement() + => TestInRegularAndScriptAsync( """ class Program { @@ -2261,12 +2114,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539717")] - public async Task TestPreDecrement() - { - await TestInRegularAndScriptAsync( + public Task TestPreDecrement() + => TestInRegularAndScriptAsync( """ class Program { @@ -2287,12 +2138,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539738")] - public async Task TestGenerateIntoScript() - { - await TestAsync( + public Task TestGenerateIntoScript() + => TestAsync( """ using C; @@ -2312,13 +2161,11 @@ static class C C.i ++ ; """, -parseOptions: Options.Script); - } + parseOptions: Options.Script); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539558")] - public async Task BugFix5565() - { - await TestInRegularAndScriptAsync( + public Task BugFix5565() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -2347,13 +2194,11 @@ static void Main(string[] args) } } """); - } [Fact(Skip = "Tuples")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539536")] - public async Task BugFix5538() - { - await TestInRegularAndScriptAsync( + public Task BugFix5538() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -2382,13 +2227,11 @@ static void Main(string[] args) } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539665")] - public async Task BugFix5697() - { - await TestInRegularAndScriptAsync( + public Task BugFix5697() + => TestInRegularAndScriptAsync( """ class C { } class D @@ -2412,7 +2255,6 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539793")] public async Task TestIncrement() @@ -2427,7 +2269,7 @@ static void Main() } } """, -[string.Format(CodeFixesResources.Generate_field_0, "p"), string.Format(CodeFixesResources.Generate_property_0, "p"), string.Format(CodeFixesResources.Generate_local_0, "p"), string.Format(CodeFixesResources.Generate_parameter_0, "p")]); + [string.Format(CodeFixesResources.Generate_field_0, "p"), string.Format(CodeFixesResources.Generate_property_0, "p"), string.Format(CodeFixesResources.Generate_local_0, "p"), string.Format(CodeFixesResources.Generate_parameter_0, "p")]); await TestInRegularAndScriptAsync( """ @@ -2454,9 +2296,8 @@ static void Main() [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539834")] - public async Task TestNotInGoto() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotInGoto() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -2466,12 +2307,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539826")] - public async Task TestOnLeftOfDot() - { - await TestInRegularAndScriptAsync( + public Task TestOnLeftOfDot() + => TestInRegularAndScriptAsync( """ class Program { @@ -2492,12 +2331,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539840")] - public async Task TestNotBeforeAlias() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotBeforeAlias() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -2511,12 +2348,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539871")] - public async Task TestMissingOnGenericName() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnGenericName() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2528,12 +2363,10 @@ static void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539934")] - public async Task TestOnDelegateAddition() - { - await TestAsync( + public Task TestOnDelegateAddition() + => TestAsync( """ class C { @@ -2558,13 +2391,11 @@ void M() } } """, -parseOptions: null); - } + parseOptions: null); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539986")] - public async Task TestReferenceTypeParameter1() - { - await TestInRegularAndScriptAsync( + public Task TestReferenceTypeParameter1() + => TestInRegularAndScriptAsync( """ class C { @@ -2592,12 +2423,10 @@ class A public static C M { get; internal set; } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539986")] - public async Task TestReferenceTypeParameter2() - { - await TestInRegularAndScriptAsync( + public Task TestReferenceTypeParameter2() + => TestInRegularAndScriptAsync( """ class C { @@ -2625,7 +2454,6 @@ class A } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540159")] public async Task TestEmptyIdentifierName() @@ -2651,9 +2479,8 @@ static void M() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541194")] - public async Task TestForeachVar() - { - await TestInRegularAndScriptAsync( + public Task TestForeachVar() + => TestInRegularAndScriptAsync( """ class C { @@ -2680,12 +2507,10 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541265")] - public async Task TestExtensionMethodUsedAsInstance() - { - await TestAsync( + public Task TestExtensionMethodUsedAsInstance() + => TestAsync( """ using System; @@ -2728,13 +2553,11 @@ public static int ExtensionMethod(this String s) } } """, -parseOptions: null); - } + parseOptions: null); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541549")] - public async Task TestDelegateInvoke() - { - await TestInRegularAndScriptAsync( + public Task TestDelegateInvoke() + => TestInRegularAndScriptAsync( """ using System; @@ -2761,12 +2584,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541597")] - public async Task TestComplexAssign1() - { - await TestInRegularAndScriptAsync( + public Task TestComplexAssign1() + => TestInRegularAndScriptAsync( """ class Program { @@ -2787,12 +2608,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541597")] - public async Task TestComplexAssign2() - { - await TestInRegularAndScriptAsync( + public Task TestComplexAssign2() + => TestInRegularAndScriptAsync( """ class Program { @@ -2813,12 +2632,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541659")] - public async Task TestTypeNamedVar() - { - await TestInRegularAndScriptAsync( + public Task TestTypeNamedVar() + => TestInRegularAndScriptAsync( """ using System; @@ -2851,12 +2668,10 @@ class var { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541675")] - public async Task TestStaticExtensionMethodArgument() - { - await TestInRegularAndScriptAsync( + public Task TestStaticExtensionMethodArgument() + => TestInRegularAndScriptAsync( """ using System; @@ -2897,24 +2712,20 @@ public static int ExMethod(this string s) } } """); - } [Fact] - public async Task SpeakableTopLevelStatementType() - { - await TestMissingAsync(""" + public Task SpeakableTopLevelStatementType() + => TestMissingAsync(""" [|P|] = 10; partial class Program { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539675")] - public async Task AddBlankLineBeforeCommentBetweenMembers1() - { - await TestInRegularAndScriptAsync( + public Task AddBlankLineBeforeCommentBetweenMembers1() + => TestInRegularAndScriptAsync( """ class Program { @@ -2937,12 +2748,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539675")] - public async Task AddBlankLineBeforeCommentBetweenMembers2() - { - await TestInRegularAndScriptAsync( + public Task AddBlankLineBeforeCommentBetweenMembers2() + => TestInRegularAndScriptAsync( """ class Program { @@ -2965,13 +2774,11 @@ static void Main(string[] args) } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543813")] - public async Task AddBlankLineBetweenMembers1() - { - await TestInRegularAndScriptAsync( + public Task AddBlankLineBetweenMembers1() + => TestInRegularAndScriptAsync( """ class Program { @@ -2992,13 +2799,11 @@ static void Main(string[] args) } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543813")] - public async Task AddBlankLineBetweenMembers2() - { - await TestInRegularAndScriptAsync( + public Task AddBlankLineBetweenMembers2() + => TestInRegularAndScriptAsync( """ class Program { @@ -3019,13 +2824,11 @@ static void Main(string[] args) } } """, -index: 0); - } + index: 0); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543813")] - public async Task DoNotAddBlankLineBetweenFields() - { - await TestInRegularAndScriptAsync( + public Task DoNotAddBlankLineBetweenFields() + => TestInRegularAndScriptAsync( """ class Program { @@ -3051,13 +2854,11 @@ static void Main(string[] args) } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543813")] - public async Task DoNotAddBlankLineBetweenAutoProperties() - { - await TestInRegularAndScriptAsync( + public Task DoNotAddBlankLineBetweenAutoProperties() + => TestInRegularAndScriptAsync( """ class Program { @@ -3083,13 +2884,11 @@ static void Main(string[] args) } } """, -index: 0); - } + index: 0); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539665")] - public async Task TestIntoEmptyClass() - { - await TestInRegularAndScriptAsync( + public Task TestIntoEmptyClass() + => TestInRegularAndScriptAsync( """ class C { } class D @@ -3113,12 +2912,10 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540595")] - public async Task TestGeneratePropertyInScript() - { - await TestAsync( + public Task TestGeneratePropertyInScript() + => TestAsync( @"[|Goo|]", """ object Goo { get; private set; } @@ -3126,7 +2923,6 @@ await TestAsync( Goo """, parseOptions: Options.Script); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542535")] public async Task TestConstantInParameterValue() @@ -3158,9 +2954,8 @@ public void Goo ( bool x = undeclared ) { } } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542900")] - public async Task TestGenerateFromAttributeNamedArgument1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFromAttributeNamedArgument1() + => TestInRegularAndScriptAsync( """ using System; @@ -3185,12 +2980,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542900")] - public async Task TestGenerateFromAttributeNamedArgument2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFromAttributeNamedArgument2() + => TestInRegularAndScriptAsync( """ using System; @@ -3215,13 +3008,11 @@ static void Main(string[] args) } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] - public async Task TestMinimalAccessibility1_InternalPrivate() - { - await TestAsync( + public Task TestMinimalAccessibility1_InternalPrivate() + => TestAsync( """ class Program { @@ -3250,13 +3041,11 @@ private class C } } """, -parseOptions: null); - } + parseOptions: null); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] - public async Task TestMinimalAccessibility2_InternalProtected() - { - await TestAsync( + public Task TestMinimalAccessibility2_InternalProtected() + => TestAsync( """ class Program { @@ -3285,13 +3074,11 @@ protected class C } } """, -parseOptions: null); - } + parseOptions: null); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] - public async Task TestMinimalAccessibility3_InternalInternal() - { - await TestAsync( + public Task TestMinimalAccessibility3_InternalInternal() + => TestAsync( """ class Program { @@ -3320,13 +3107,11 @@ internal class C } } """, -parseOptions: null); - } + parseOptions: null); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] - public async Task TestMinimalAccessibility4_InternalProtectedInternal() - { - await TestAsync( + public Task TestMinimalAccessibility4_InternalProtectedInternal() + => TestAsync( """ class Program { @@ -3355,13 +3140,11 @@ protected internal class C } } """, -parseOptions: null); - } + parseOptions: null); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] - public async Task TestMinimalAccessibility5_InternalPublic() - { - await TestAsync( + public Task TestMinimalAccessibility5_InternalPublic() + => TestAsync( """ class Program { @@ -3390,13 +3173,11 @@ public class C } } """, -parseOptions: null); - } + parseOptions: null); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] - public async Task TestMinimalAccessibility6_PublicInternal() - { - await TestAsync( + public Task TestMinimalAccessibility6_PublicInternal() + => TestAsync( """ public class Program { @@ -3425,13 +3206,11 @@ internal class C } } """, -parseOptions: null); - } + parseOptions: null); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] - public async Task TestMinimalAccessibility7_PublicProtectedInternal() - { - await TestAsync( + public Task TestMinimalAccessibility7_PublicProtectedInternal() + => TestAsync( """ public class Program { @@ -3460,13 +3239,11 @@ protected internal class C } } """, -parseOptions: null); - } + parseOptions: null); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] - public async Task TestMinimalAccessibility8_PublicProtected() - { - await TestAsync( + public Task TestMinimalAccessibility8_PublicProtected() + => TestAsync( """ public class Program { @@ -3495,13 +3272,11 @@ protected class C } } """, -parseOptions: null); - } + parseOptions: null); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] - public async Task TestMinimalAccessibility9_PublicPrivate() - { - await TestAsync( + public Task TestMinimalAccessibility9_PublicPrivate() + => TestAsync( """ public class Program { @@ -3530,13 +3305,11 @@ private class C } } """, -parseOptions: null); - } + parseOptions: null); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] - public async Task TestMinimalAccessibility10_PrivatePrivate() - { - await TestAsync( + public Task TestMinimalAccessibility10_PrivatePrivate() + => TestAsync( """ class outer { @@ -3571,13 +3344,11 @@ private class C } } """, -parseOptions: null); - } + parseOptions: null); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] - public async Task TestMinimalAccessibility11_PrivateProtected() - { - await TestAsync( + public Task TestMinimalAccessibility11_PrivateProtected() + => TestAsync( """ class outer { @@ -3612,13 +3383,11 @@ protected class C } } """, -parseOptions: null); - } + parseOptions: null); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] - public async Task TestMinimalAccessibility12_PrivateProtectedInternal() - { - await TestAsync( + public Task TestMinimalAccessibility12_PrivateProtectedInternal() + => TestAsync( """ class outer { @@ -3653,13 +3422,11 @@ protected internal class C } } """, -parseOptions: null); - } + parseOptions: null); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] - public async Task TestMinimalAccessibility13_PrivateInternal() - { - await TestAsync( + public Task TestMinimalAccessibility13_PrivateInternal() + => TestAsync( """ class outer { @@ -3694,13 +3461,11 @@ internal class C } } """, -parseOptions: null); - } + parseOptions: null); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] - public async Task TestMinimalAccessibility14_ProtectedPrivate() - { - await TestAsync( + public Task TestMinimalAccessibility14_ProtectedPrivate() + => TestAsync( """ class outer { @@ -3735,13 +3500,11 @@ private class C } } """, -parseOptions: null); - } + parseOptions: null); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] - public async Task TestMinimalAccessibility15_ProtectedInternal() - { - await TestAsync( + public Task TestMinimalAccessibility15_ProtectedInternal() + => TestAsync( """ class outer { @@ -3776,13 +3539,11 @@ internal class C } } """, -parseOptions: null); - } + parseOptions: null); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] - public async Task TestMinimalAccessibility16_ProtectedInternalProtected() - { - await TestAsync( + public Task TestMinimalAccessibility16_ProtectedInternalProtected() + => TestAsync( """ class outer { @@ -3817,13 +3578,11 @@ protected class C } } """, -parseOptions: null); - } + parseOptions: null); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] - public async Task TestMinimalAccessibility17_ProtectedInternalInternal() - { - await TestAsync( + public Task TestMinimalAccessibility17_ProtectedInternalInternal() + => TestAsync( """ class outer { @@ -3858,13 +3617,11 @@ internal class C } } """, -parseOptions: null); - } + parseOptions: null); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543153")] - public async Task TestAnonymousObjectInitializer1() - { - await TestInRegularAndScriptAsync( + public Task TestAnonymousObjectInitializer1() + => TestInRegularAndScriptAsync( """ class C { @@ -3887,13 +3644,11 @@ void M() } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543124")] - public async Task TestNoGenerationIntoAnonymousType() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNoGenerationIntoAnonymousType() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -3904,12 +3659,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543543")] - public async Task TestNotOfferedForBoundParametersOfOperators() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOfferedForBoundParametersOfOperators() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -3928,12 +3681,10 @@ public static implicit operator Program(string str) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544175")] - public async Task TestNotOnNamedParameterName1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOnNamedParameterName1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -3949,12 +3700,10 @@ public string Goo(int x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544271")] - public async Task TestNotOnNamedParameterName2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOnNamedParameterName2() + => TestMissingInRegularAndScriptAsync( """ class Goo { @@ -3970,12 +3719,10 @@ public DogBed(int b) : base([|a|]: b) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544164")] - public async Task TestPropertyOnObjectInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestPropertyOnObjectInitializer() + => TestInRegularAndScriptAsync( """ class Goo { @@ -4003,12 +3750,10 @@ void goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49294")] - public async Task TestPropertyInWithInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestPropertyInWithInitializer() + => TestInRegularAndScriptAsync( """ record Goo { @@ -4036,12 +3781,10 @@ void goo(Goo g) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/13166")] - public async Task TestPropertyOnNestedObjectInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestPropertyOnNestedObjectInitializer() + => TestInRegularAndScriptAsync( """ public class Inner { @@ -4067,12 +3810,10 @@ public class Outer public static Outer X() => new Outer { Inner = { InnerValue = 5 } }; } """); - } [Fact] - public async Task TestPropertyOnObjectInitializer1() - { - await TestInRegularAndScriptAsync( + public Task TestPropertyOnObjectInitializer1() + => TestInRegularAndScriptAsync( """ class Goo { @@ -4100,12 +3841,10 @@ void goo() } } """); - } [Fact] - public async Task TestPropertyOnObjectInitializer2() - { - await TestInRegularAndScriptAsync( + public Task TestPropertyOnObjectInitializer2() + => TestInRegularAndScriptAsync( """ class Goo { @@ -4134,12 +3873,10 @@ void goo() } } """); - } [Fact] - public async Task TestFieldOnObjectInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestFieldOnObjectInitializer() + => TestInRegularAndScriptAsync( """ class Goo { @@ -4167,13 +3904,11 @@ void goo() } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact] - public async Task TestFieldOnObjectInitializer1() - { - await TestInRegularAndScriptAsync( + public Task TestFieldOnObjectInitializer1() + => TestInRegularAndScriptAsync( """ class Goo { @@ -4201,13 +3936,11 @@ void goo() } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact] - public async Task TestFieldOnObjectInitializer2() - { - await TestInRegularAndScriptAsync( + public Task TestFieldOnObjectInitializer2() + => TestInRegularAndScriptAsync( """ class Goo { @@ -4236,13 +3969,11 @@ void goo() } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact] - public async Task TestOnlyPropertyAndFieldOfferedForObjectInitializer() - { - await TestActionCountAsync( + public Task TestOnlyPropertyAndFieldOfferedForObjectInitializer() + => TestActionCountAsync( """ class Goo { @@ -4256,13 +3987,11 @@ void goo() } } """, -2); - } + 2); [Fact] - public async Task TestGenerateLocalInObjectInitializerValue() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateLocalInObjectInitializerValue() + => TestInRegularAndScriptAsync( """ class Goo { @@ -4290,13 +4019,11 @@ void goo() } } """, -index: LocalIndex); - } + index: LocalIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544319")] - public async Task TestNotOnIncompleteMember1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOnIncompleteMember1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4304,12 +4031,10 @@ class Class1 { Console.[|WriteLine|](); } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544319")] - public async Task TestNotOnIncompleteMember2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOnIncompleteMember2() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4317,12 +4042,10 @@ class Class1 { [|WriteLine|](); } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544319")] - public async Task TestNotOnIncompleteMember3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOnIncompleteMember3() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4331,12 +4054,10 @@ class Class1 [|WriteLine|] } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544384")] - public async Task TestPointerType() - { - await TestInRegularAndScriptAsync( + public Task TestPointerType() + => TestInRegularAndScriptAsync( """ class Program { @@ -4382,19 +4103,15 @@ static unsafe void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544510")] - public async Task TestNotOnUsingAlias() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOnUsingAlias() + => TestMissingInRegularAndScriptAsync( @"using [|S|] = System ; S . Console . WriteLine ( ""hello world"" ) ; "); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544907")] - public async Task TestExpressionTLambda() - { - await TestInRegularAndScriptAsync( + public Task TestExpressionTLambda() + => TestInRegularAndScriptAsync( """ using System; using System.Linq.Expressions; @@ -4421,12 +4138,10 @@ static void Main() } } """); - } [Fact] - public async Task TestNoGenerationIntoEntirelyHiddenType() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNoGenerationIntoEntirelyHiddenType() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -4442,12 +4157,10 @@ class D } #line default """); - } [Fact] - public async Task TestInReturnStatement() - { - await TestInRegularAndScriptAsync( + public Task TestInReturnStatement() + => TestInRegularAndScriptAsync( """ class Program { @@ -4468,12 +4181,10 @@ void Main() } } """); - } [Fact] - public async Task TestLocal1() - { - await TestInRegularAndScriptAsync( + public Task TestLocal1() + => TestInRegularAndScriptAsync( """ class Program { @@ -4501,13 +4212,11 @@ static void Goo(int i) } } """, -index: LocalIndex); - } + index: LocalIndex); [Fact] - public async Task TestLocalTopLevelNullability() - { - await TestInRegularAndScriptAsync( + public Task TestLocalTopLevelNullability() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -4539,13 +4248,11 @@ static void Goo(string? s) } } """, -index: LocalIndex); - } + index: LocalIndex); [Fact] - public async Task TestLocalNestedNullability() - { - await TestInRegularAndScriptAsync( + public Task TestLocalNestedNullability() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -4577,13 +4284,11 @@ static void Goo(IEnumerable s) } } """, -index: LocalIndex); - } + index: LocalIndex); [Fact] - public async Task TestOutLocal1() - { - await TestInRegularAndScriptAsync( + public Task TestOutLocal1() + => TestInRegularAndScriptAsync( """ class Program { @@ -4611,13 +4316,11 @@ static void Goo(out int i) } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/809542")] - public async Task TestLocalBeforeComment() - { - await TestInRegularAndScriptAsync( + public Task TestLocalBeforeComment() + => TestInRegularAndScriptAsync( """ class Program { @@ -4645,13 +4348,11 @@ void Main() } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/809542")] - public async Task TestLocalAfterComment() - { - await TestInRegularAndScriptAsync( + public Task TestLocalAfterComment() + => TestInRegularAndScriptAsync( """ class Program { @@ -4681,13 +4382,11 @@ void Main() } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact] - public async Task TestGenerateIntoVisiblePortion() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateIntoVisiblePortion() + => TestInRegularAndScriptAsync( """ using System; @@ -4716,12 +4415,10 @@ void Main() public static object X { get; private set; } } """); - } [Fact] - public async Task TestMissingWhenNoAvailableRegionToGenerateInto() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWhenNoAvailableRegionToGenerateInto() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4739,12 +4436,10 @@ void Main() } #line default """); - } [Fact] - public async Task TestGenerateLocalAvailableIfBlockIsNotHidden() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateLocalAvailableIfBlockIsNotHidden() + => TestInRegularAndScriptAsync( """ using System; @@ -4776,12 +4471,10 @@ void Main() } #line default """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545217")] - public async Task TestGenerateLocalNameSimplificationCSharp7() - { - await TestAsync( + public Task TestGenerateLocalNameSimplificationCSharp7() + => TestAsync( """ class Program { @@ -4817,13 +4510,11 @@ void bar(sfoo x) } } """, -index: 3, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp7)); - } + index: 3, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp7)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545217")] - public async Task TestGenerateLocalNameSimplification() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateLocalNameSimplification() + => TestInRegularAndScriptAsync( """ class Program { @@ -4859,13 +4550,11 @@ void bar(sfoo x) } } """, -index: LocalIndex); - } + index: LocalIndex); [Fact] - public async Task TestParenthesizedExpression() - { - await TestInRegularAndScriptAsync( + public Task TestParenthesizedExpression() + => TestInRegularAndScriptAsync( """ class Program { @@ -4886,12 +4575,10 @@ void Main() } } """); - } [Fact] - public async Task TestInSelect() - { - await TestInRegularAndScriptAsync( + public Task TestInSelect() + => TestInRegularAndScriptAsync( """ using System.Linq; @@ -4918,12 +4605,10 @@ void Main(string[] args) } } """); - } [Fact] - public async Task TestInChecked() - { - await TestInRegularAndScriptAsync( + public Task TestInChecked() + => TestInRegularAndScriptAsync( """ class Program { @@ -4946,12 +4631,10 @@ void Main() } } """); - } [Fact] - public async Task TestInArrayRankSpecifier() - { - await TestInRegularAndScriptAsync( + public Task TestInArrayRankSpecifier() + => TestInRegularAndScriptAsync( """ class Program { @@ -4972,12 +4655,10 @@ void Main() } } """); - } [Fact] - public async Task TestInConditional1() - { - await TestInRegularAndScriptAsync( + public Task TestInConditional1() + => TestInRegularAndScriptAsync( """ class Program { @@ -4998,12 +4679,10 @@ static void Main() } } """); - } [Fact] - public async Task TestInConditional2() - { - await TestInRegularAndScriptAsync( + public Task TestInConditional2() + => TestInRegularAndScriptAsync( """ class Program { @@ -5024,12 +4703,10 @@ static void Main() } } """); - } [Fact] - public async Task TestInConditional3() - { - await TestInRegularAndScriptAsync( + public Task TestInConditional3() + => TestInRegularAndScriptAsync( """ class Program { @@ -5050,12 +4727,10 @@ static void Main() } } """); - } [Fact] - public async Task TestInCast() - { - await TestInRegularAndScriptAsync( + public Task TestInCast() + => TestInRegularAndScriptAsync( """ class Program { @@ -5076,12 +4751,10 @@ void Main() } } """); - } [Fact] - public async Task TestInIf() - { - await TestInRegularAndScriptAsync( + public Task TestInIf() + => TestInRegularAndScriptAsync( """ class Program { @@ -5106,12 +4779,10 @@ void Main() } } """); - } [Fact] - public async Task TestInSwitch() - { - await TestInRegularAndScriptAsync( + public Task TestInSwitch() + => TestInRegularAndScriptAsync( """ class Program { @@ -5136,12 +4807,10 @@ void Main() } } """); - } [Fact] - public async Task TestMissingOnNamespace() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnNamespace() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -5151,12 +4820,10 @@ void Main() } } """); - } [Fact] - public async Task TestMissingOnType() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnType() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -5166,12 +4833,10 @@ void Main() } } """); - } [Fact] - public async Task TestMissingOnBase() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnBase() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -5181,12 +4846,10 @@ void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545273")] - public async Task TestGenerateFromAssign1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFromAssign1() + => TestInRegularAndScriptAsync( """ class Program { @@ -5205,13 +4868,11 @@ void Main() } } """, -index: PropertyIndex, options: ImplicitTypingEverywhere()); - } + index: PropertyIndex, options: ImplicitTypingEverywhere()); [Fact] - public async Task TestFuncAssignment() - { - await TestInRegularAndScriptAsync( + public Task TestFuncAssignment() + => TestInRegularAndScriptAsync( """ class Program { @@ -5230,13 +4891,11 @@ void Main() } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545273")] - public async Task TestGenerateFromAssign1NotAsVar() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFromAssign1NotAsVar() + => TestInRegularAndScriptAsync( """ class Program { @@ -5255,13 +4914,11 @@ void Main() } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545273")] - public async Task TestGenerateFromAssign2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFromAssign2() + => TestInRegularAndScriptAsync( """ class Program { @@ -5280,13 +4937,11 @@ void Main() } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545269")] - public async Task TestGenerateInVenus1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestGenerateInVenus1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -5299,7 +4954,6 @@ void Goo() #line hidden } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545269")] public async Task TestGenerateInVenus2() @@ -5334,9 +4988,8 @@ void Goo() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546027")] - public async Task TestGeneratePropertyFromAttribute() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyFromAttribute() + => TestInRegularAndScriptAsync( """ using System; @@ -5364,12 +5017,10 @@ class D { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545232")] - public async Task TestNewLinePreservationBeforeInsertingLocal() - { - await TestInRegularAndScriptAsync( + public Task TestNewLinePreservationBeforeInsertingLocal() + => TestInRegularAndScriptAsync( """ using System; namespace CSharpDemoApp @@ -5409,13 +5060,11 @@ static void Calculate(double multiplier = Math.PI) } } """, -index: LocalIndex); - } + index: LocalIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/863346")] - public async Task TestGenerateInGenericMethod_Local() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInGenericMethod_Local() + => TestInRegularAndScriptAsync( """ using System; class TestClass @@ -5451,13 +5100,11 @@ private static T WrapFunc(Func function) } } """, -index: LocalIndex); - } + index: LocalIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/863346")] - public async Task TestGenerateInGenericMethod_Property() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateInGenericMethod_Property() + => TestInRegularAndScriptAsync( """ using System; class TestClass @@ -5494,12 +5141,10 @@ private static T WrapFunc(Func function) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/865067")] - public async Task TestWithYieldReturnInMethod() - { - await TestInRegularAndScriptAsync( + public Task TestWithYieldReturnInMethod() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -5526,12 +5171,10 @@ IEnumerable Goo() } } """); - } [Fact] - public async Task TestWithYieldReturnInAsyncMethod() - { - await TestInRegularAndScriptAsync( + public Task TestWithYieldReturnInAsyncMethod() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -5558,12 +5201,10 @@ async IAsyncEnumerable Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30235")] - public async Task TestWithYieldReturnInLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestWithYieldReturnInLocalFunction() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -5596,12 +5237,10 @@ IEnumerable F() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/877580")] - public async Task TestWithThrow() - { - await TestInRegularAndScriptAsync( + public Task TestWithThrow() + => TestInRegularAndScriptAsync( """ using System; @@ -5626,12 +5265,10 @@ void Goo() } } """, index: ReadonlyFieldIndex); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] - public async Task TestUnsafeField() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafeField() + => TestInRegularAndScriptAsync( """ class Class { @@ -5652,12 +5289,10 @@ void Method() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] - public async Task TestUnsafeField2() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafeField2() + => TestInRegularAndScriptAsync( """ class Class { @@ -5678,12 +5313,10 @@ void Method() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] - public async Task TestUnsafeFieldInUnsafeClass() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafeFieldInUnsafeClass() + => TestInRegularAndScriptAsync( """ unsafe class Class { @@ -5704,12 +5337,10 @@ void Method() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] - public async Task TestUnsafeFieldInNestedClass() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafeFieldInNestedClass() + => TestInRegularAndScriptAsync( """ unsafe class Class { @@ -5736,12 +5367,10 @@ void Method() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] - public async Task TestUnsafeFieldInNestedClass2() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafeFieldInNestedClass2() + => TestInRegularAndScriptAsync( """ class Class { @@ -5768,12 +5397,10 @@ void Method() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] - public async Task TestUnsafeReadOnlyField() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafeReadOnlyField() + => TestInRegularAndScriptAsync( """ class Class { @@ -5794,13 +5421,11 @@ void Method() } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] - public async Task TestUnsafeReadOnlyField2() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafeReadOnlyField2() + => TestInRegularAndScriptAsync( """ class Class { @@ -5821,13 +5446,11 @@ void Method() } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] - public async Task TestUnsafeReadOnlyFieldInUnsafeClass() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafeReadOnlyFieldInUnsafeClass() + => TestInRegularAndScriptAsync( """ unsafe class Class { @@ -5848,13 +5471,11 @@ void Method() } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] - public async Task TestUnsafeReadOnlyFieldInNestedClass() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafeReadOnlyFieldInNestedClass() + => TestInRegularAndScriptAsync( """ unsafe class Class { @@ -5881,13 +5502,11 @@ void Method() } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] - public async Task TestUnsafeReadOnlyFieldInNestedClass2() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafeReadOnlyFieldInNestedClass2() + => TestInRegularAndScriptAsync( """ class Class { @@ -5914,13 +5533,11 @@ void Method() } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] - public async Task TestUnsafeProperty() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafeProperty() + => TestInRegularAndScriptAsync( """ class Class { @@ -5941,13 +5558,11 @@ void Method() } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] - public async Task TestUnsafeProperty2() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafeProperty2() + => TestInRegularAndScriptAsync( """ class Class { @@ -5968,13 +5583,11 @@ void Method() } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] - public async Task TestUnsafePropertyInUnsafeClass() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafePropertyInUnsafeClass() + => TestInRegularAndScriptAsync( """ unsafe class Class { @@ -5995,13 +5608,11 @@ void Method() } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] - public async Task TestUnsafePropertyInNestedClass() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafePropertyInNestedClass() + => TestInRegularAndScriptAsync( """ unsafe class Class { @@ -6028,13 +5639,11 @@ void Method() } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] - public async Task TestUnsafePropertyInNestedClass2() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafePropertyInNestedClass2() + => TestInRegularAndScriptAsync( """ class Class { @@ -6061,13 +5670,11 @@ void Method() } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestInsideNameOfProperty() - { - await TestInRegularAndScriptAsync( + public Task TestInsideNameOfProperty() + => TestInRegularAndScriptAsync( """ class C { @@ -6088,12 +5695,10 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestInsideNameOfField() - { - await TestInRegularAndScriptAsync( + public Task TestInsideNameOfField() + => TestInRegularAndScriptAsync( """ class C { @@ -6114,13 +5719,11 @@ void M() } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestInsideNameOfReadonlyField() - { - await TestInRegularAndScriptAsync( + public Task TestInsideNameOfReadonlyField() + => TestInRegularAndScriptAsync( """ class C { @@ -6141,13 +5744,11 @@ void M() } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestInsideNameOfLocal() - { - await TestInRegularAndScriptAsync( + public Task TestInsideNameOfLocal() + => TestInRegularAndScriptAsync( """ class C { @@ -6167,13 +5768,11 @@ void M() } } """, -index: LocalIndex); - } + index: LocalIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestInsideNameOfProperty2() - { - await TestInRegularAndScriptAsync( + public Task TestInsideNameOfProperty2() + => TestInRegularAndScriptAsync( """ class C { @@ -6194,12 +5793,10 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestInsideNameOfField2() - { - await TestInRegularAndScriptAsync( + public Task TestInsideNameOfField2() + => TestInRegularAndScriptAsync( """ class C { @@ -6220,13 +5817,11 @@ void M() } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestInsideNameOfReadonlyField2() - { - await TestInRegularAndScriptAsync( + public Task TestInsideNameOfReadonlyField2() + => TestInRegularAndScriptAsync( """ class C { @@ -6247,13 +5842,11 @@ void M() } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestInsideNameOfLocal2() - { - await TestInRegularAndScriptAsync( + public Task TestInsideNameOfLocal2() + => TestInRegularAndScriptAsync( """ class C { @@ -6273,13 +5866,11 @@ void M() } } """, -index: LocalIndex); - } + index: LocalIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestInsideNameOfProperty3() - { - await TestInRegularAndScriptAsync( + public Task TestInsideNameOfProperty3() + => TestInRegularAndScriptAsync( """ class C { @@ -6300,12 +5891,10 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestInsideNameOfField3() - { - await TestInRegularAndScriptAsync( + public Task TestInsideNameOfField3() + => TestInRegularAndScriptAsync( """ class C { @@ -6326,13 +5915,11 @@ void M() } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestInsideNameOfReadonlyField3() - { - await TestInRegularAndScriptAsync( + public Task TestInsideNameOfReadonlyField3() + => TestInRegularAndScriptAsync( """ class C { @@ -6353,13 +5940,11 @@ void M() } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestInsideNameOfLocal3() - { - await TestInRegularAndScriptAsync( + public Task TestInsideNameOfLocal3() + => TestInRegularAndScriptAsync( """ class C { @@ -6379,13 +5964,11 @@ void M() } } """, -index: LocalIndex); - } + index: LocalIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestInsideNameOfMissing() - { - await TestMissingInRegularAndScriptAsync( + public Task TestInsideNameOfMissing() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -6395,12 +5978,10 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestInsideNameOfMissing2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestInsideNameOfMissing2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -6411,12 +5992,10 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestInsideNameOfMissing3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestInsideNameOfMissing3() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -6428,12 +6007,10 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestInsideNameOfProperty4() - { - await TestInRegularAndScriptAsync( + public Task TestInsideNameOfProperty4() + => TestInRegularAndScriptAsync( """ class C { @@ -6454,13 +6031,11 @@ void M() } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestInsideNameOfField4() - { - await TestInRegularAndScriptAsync( + public Task TestInsideNameOfField4() + => TestInRegularAndScriptAsync( """ class C { @@ -6481,12 +6056,10 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestInsideNameOfReadonlyField4() - { - await TestInRegularAndScriptAsync( + public Task TestInsideNameOfReadonlyField4() + => TestInRegularAndScriptAsync( """ class C { @@ -6507,13 +6080,11 @@ void M() } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestInsideNameOfLocal4() - { - await TestInRegularAndScriptAsync( + public Task TestInsideNameOfLocal4() + => TestInRegularAndScriptAsync( """ class C { @@ -6533,13 +6104,11 @@ void M() } } """, -index: LocalIndex); - } + index: LocalIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestInsideNameOfProperty5() - { - await TestInRegularAndScriptAsync( + public Task TestInsideNameOfProperty5() + => TestInRegularAndScriptAsync( """ class C { @@ -6570,13 +6139,11 @@ private object nameof(object y) } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestInsideNameOfField5() - { - await TestInRegularAndScriptAsync( + public Task TestInsideNameOfField5() + => TestInRegularAndScriptAsync( """ class C { @@ -6607,12 +6174,10 @@ private object nameof(object y) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestInsideNameOfReadonlyField5() - { - await TestInRegularAndScriptAsync( + public Task TestInsideNameOfReadonlyField5() + => TestInRegularAndScriptAsync( """ class C { @@ -6643,13 +6208,11 @@ private object nameof(object y) } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] - public async Task TestInsideNameOfLocal5() - { - await TestInRegularAndScriptAsync( + public Task TestInsideNameOfLocal5() + => TestInRegularAndScriptAsync( """ class C { @@ -6679,13 +6242,11 @@ private object nameof(object y) } } """, -index: LocalIndex); - } + index: LocalIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestConditionalAccessProperty() - { - await TestInRegularAndScriptAsync( + public Task TestConditionalAccessProperty() + => TestInRegularAndScriptAsync( """ class C { @@ -6706,12 +6267,10 @@ void Main(C a) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestConditionalAccessField() - { - await TestInRegularAndScriptAsync( + public Task TestConditionalAccessField() + => TestInRegularAndScriptAsync( """ class C { @@ -6732,13 +6291,11 @@ void Main(C a) } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestConditionalAccessReadonlyField() - { - await TestInRegularAndScriptAsync( + public Task TestConditionalAccessReadonlyField() + => TestInRegularAndScriptAsync( """ class C { @@ -6759,13 +6316,11 @@ void Main(C a) } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestConditionalAccessVarProperty() - { - await TestInRegularAndScriptAsync( + public Task TestConditionalAccessVarProperty() + => TestInRegularAndScriptAsync( """ class C { @@ -6786,12 +6341,10 @@ void Main(C a) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestConditionalAccessVarField() - { - await TestInRegularAndScriptAsync( + public Task TestConditionalAccessVarField() + => TestInRegularAndScriptAsync( """ class C { @@ -6812,13 +6365,11 @@ void Main(C a) } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestConditionalAccessVarReadOnlyField() - { - await TestInRegularAndScriptAsync( + public Task TestConditionalAccessVarReadOnlyField() + => TestInRegularAndScriptAsync( """ class C { @@ -6839,13 +6390,11 @@ void Main(C a) } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestConditionalAccessNullableProperty() - { - await TestInRegularAndScriptAsync( + public Task TestConditionalAccessNullableProperty() + => TestInRegularAndScriptAsync( """ class C { @@ -6866,12 +6415,10 @@ void Main(C a) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestConditionalAccessNullableField() - { - await TestInRegularAndScriptAsync( + public Task TestConditionalAccessNullableField() + => TestInRegularAndScriptAsync( """ class C { @@ -6892,13 +6439,11 @@ void Main(C a) } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestConditionalAccessNullableReadonlyField() - { - await TestInRegularAndScriptAsync( + public Task TestConditionalAccessNullableReadonlyField() + => TestInRegularAndScriptAsync( """ class C { @@ -6919,13 +6464,11 @@ void Main(C a) } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestGeneratePropertyInConditionalAccessExpression() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyInConditionalAccessExpression() + => TestInRegularAndScriptAsync( """ class C { @@ -6957,12 +6500,10 @@ public class E } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestGeneratePropertyInConditionalAccessExpression2() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyInConditionalAccessExpression2() + => TestInRegularAndScriptAsync( """ class C { @@ -6994,12 +6535,10 @@ public class E } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestGeneratePropertyInConditionalAccessExpression3() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyInConditionalAccessExpression3() + => TestInRegularAndScriptAsync( """ class C { @@ -7031,12 +6570,10 @@ public class E } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestGeneratePropertyInConditionalAccessExpression4() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyInConditionalAccessExpression4() + => TestInRegularAndScriptAsync( """ class C { @@ -7068,12 +6605,10 @@ public class E } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestGenerateFieldInConditionalAccessExpression() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInConditionalAccessExpression() + => TestInRegularAndScriptAsync( """ class C { @@ -7105,13 +6640,11 @@ public class E } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestGenerateFieldInConditionalAccessExpression2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInConditionalAccessExpression2() + => TestInRegularAndScriptAsync( """ class C { @@ -7143,13 +6676,11 @@ public class E } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestGenerateFieldInConditionalAccessExpression3() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInConditionalAccessExpression3() + => TestInRegularAndScriptAsync( """ class C { @@ -7181,13 +6712,11 @@ public class E } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestGenerateFieldInConditionalAccessExpression4() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInConditionalAccessExpression4() + => TestInRegularAndScriptAsync( """ class C { @@ -7219,13 +6748,11 @@ public class E } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestGenerateReadonlyFieldInConditionalAccessExpression() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateReadonlyFieldInConditionalAccessExpression() + => TestInRegularAndScriptAsync( """ class C { @@ -7257,13 +6784,11 @@ public class E } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestGenerateReadonlyFieldInConditionalAccessExpression2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateReadonlyFieldInConditionalAccessExpression2() + => TestInRegularAndScriptAsync( """ class C { @@ -7295,13 +6820,11 @@ public class E } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestGenerateReadonlyFieldInConditionalAccessExpression3() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateReadonlyFieldInConditionalAccessExpression3() + => TestInRegularAndScriptAsync( """ class C { @@ -7333,13 +6856,11 @@ public class E } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] - public async Task TestGenerateReadonlyFieldInConditionalAccessExpression4() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateReadonlyFieldInConditionalAccessExpression4() + => TestInRegularAndScriptAsync( """ class C { @@ -7371,13 +6892,11 @@ public class E } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact] - public async Task TestGenerateFieldInPropertyInitializers() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInPropertyInitializers() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -7402,12 +6921,10 @@ class Program public int MyProperty { get; } = y; } """); - } [Fact] - public async Task TestGenerateReadonlyFieldInPropertyInitializers() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateReadonlyFieldInPropertyInitializers() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -7432,13 +6949,11 @@ class Program public int MyProperty { get; } = y; } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact] - public async Task TestGeneratePropertyInPropertyInitializers() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyInPropertyInitializers() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -7462,13 +6977,11 @@ class Program public int MyProperty { get; } = y; } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact] - public async Task TestGenerateFieldInExpressionBodiedProperty() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInExpressionBodiedProperty() + => TestInRegularAndScriptAsync( """ class Program { @@ -7483,12 +6996,10 @@ class Program public int Y => y; } """); - } [Fact] - public async Task TestGenerateReadonlyFieldInExpressionBodiedProperty() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateReadonlyFieldInExpressionBodiedProperty() + => TestInRegularAndScriptAsync( """ class Program { @@ -7503,13 +7014,11 @@ class Program public int Y => y; } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact] - public async Task TestGeneratePropertyInExpressionBodiedProperty() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyInExpressionBodiedProperty() + => TestInRegularAndScriptAsync( """ class Program { @@ -7524,13 +7033,11 @@ class Program public int y { get; private set; } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact] - public async Task TestGenerateFieldInExpressionBodiedOperator() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInExpressionBodiedOperator() + => TestInRegularAndScriptAsync( """ class C { @@ -7545,12 +7052,10 @@ class C public static C operator --(C p) => x; } """); - } [Fact] - public async Task TestGenerateReadOnlyFieldInExpressionBodiedOperator() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateReadOnlyFieldInExpressionBodiedOperator() + => TestInRegularAndScriptAsync( """ class C { @@ -7565,13 +7070,11 @@ class C public static C operator --(C p) => x; } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact] - public async Task TestGeneratePropertyInExpressionBodiedOperator() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyInExpressionBodiedOperator() + => TestInRegularAndScriptAsync( """ class C { @@ -7586,13 +7089,11 @@ class C public static C operator --(C p) => x; } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact] - public async Task TestGenerateFieldInExpressionBodiedMethod() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInExpressionBodiedMethod() + => TestInRegularAndScriptAsync( """ class C { @@ -7607,12 +7108,10 @@ class C public static C GetValue(C p) => x; } """); - } [Fact] - public async Task TestGenerateReadOnlyFieldInExpressionBodiedMethod() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateReadOnlyFieldInExpressionBodiedMethod() + => TestInRegularAndScriptAsync( """ class C { @@ -7627,13 +7126,11 @@ class C public static C GetValue(C p) => x; } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact] - public async Task TestGeneratePropertyInExpressionBodiedMethod() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyInExpressionBodiedMethod() + => TestInRegularAndScriptAsync( """ class C { @@ -7648,13 +7145,11 @@ class C public static C GetValue(C p) => x; } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27647")] - public async Task TestGeneratePropertyInExpressionBodiedAsyncTaskOfTMethod() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyInExpressionBodiedAsyncTaskOfTMethod() + => TestInRegularAndScriptAsync( """ class C { @@ -7669,13 +7164,11 @@ class C public static async System.Threading.Tasks.Task GetValue(C p) => x; } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact] - public async Task TestGenerateFieldInDictionaryInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInDictionaryInitializer() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -7700,12 +7193,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestGeneratePropertyInDictionaryInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyInDictionaryInitializer() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -7730,12 +7221,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestGenerateFieldInDictionaryInitializer2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInDictionaryInitializer2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -7760,12 +7249,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestGenerateReadOnlyFieldInDictionaryInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateReadOnlyFieldInDictionaryInitializer() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -7790,13 +7277,11 @@ static void Main(string[] args) } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact] - public async Task TestGenerateFieldInDictionaryInitializer3() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInDictionaryInitializer3() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -7821,13 +7306,11 @@ static void Main(string[] args) } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact] - public async Task TestGenerateReadOnlyFieldInDictionaryInitializer2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateReadOnlyFieldInDictionaryInitializer2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -7852,13 +7335,11 @@ static void Main(string[] args) } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact] - public async Task TestGeneratePropertyInDictionaryInitializer2() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyInDictionaryInitializer2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -7883,13 +7364,11 @@ static void Main(string[] args) } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact] - public async Task TestGenerateReadOnlyFieldInDictionaryInitializer3() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateReadOnlyFieldInDictionaryInitializer3() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -7914,13 +7393,11 @@ static void Main(string[] args) } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact] - public async Task TestGeneratePropertyInDictionaryInitializer3() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyInDictionaryInitializer3() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -7945,13 +7422,11 @@ static void Main(string[] args) } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact] - public async Task TestGenerateLocalInDictionaryInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateLocalInDictionaryInitializer() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -7975,13 +7450,11 @@ static void Main(string[] args) } } """, -index: LocalIndex); - } + index: LocalIndex); [Fact] - public async Task TestGenerateLocalInDictionaryInitializer2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateLocalInDictionaryInitializer2() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -8005,13 +7478,11 @@ static void Main(string[] args) } } """, -index: LocalIndex); - } + index: LocalIndex); [Fact] - public async Task TestGenerateLocalInDictionaryInitializer3() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateLocalInDictionaryInitializer3() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -8035,13 +7506,11 @@ static void Main(string[] args) } } """, -index: LocalIndex); - } + index: LocalIndex); [Fact] - public async Task TestGenerateVariableFromLambda() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateVariableFromLambda() + => TestInRegularAndScriptAsync( """ using System; @@ -8070,12 +7539,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestGenerateVariableFromLambda2() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateVariableFromLambda2() + => TestInRegularAndScriptAsync( """ using System; @@ -8104,13 +7571,11 @@ static void Main(string[] args) } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact] - public async Task TestGenerateVariableFromLambda3() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateVariableFromLambda3() + => TestInRegularAndScriptAsync( """ using System; @@ -8138,13 +7603,11 @@ static void Main(string[] args) } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8010")] - public async Task TestGenerationFromStaticProperty_Field() - { - await TestInRegularAndScriptAsync( + public Task TestGenerationFromStaticProperty_Field() + => TestInRegularAndScriptAsync( """ using System; @@ -8175,12 +7638,10 @@ public static int Property1 } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8010")] - public async Task TestGenerationFromStaticProperty_ReadonlyField() - { - await TestInRegularAndScriptAsync( + public Task TestGenerationFromStaticProperty_ReadonlyField() + => TestInRegularAndScriptAsync( """ using System; @@ -8211,13 +7672,11 @@ public static int Property1 } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8010")] - public async Task TestGenerationFromStaticProperty_Property() - { - await TestInRegularAndScriptAsync( + public Task TestGenerationFromStaticProperty_Property() + => TestInRegularAndScriptAsync( """ using System; @@ -8248,13 +7707,11 @@ public static int Property1 public static int goo { get; private set; } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8010")] - public async Task TestGenerationFromStaticProperty_Local() - { - await TestInRegularAndScriptAsync( + public Task TestGenerationFromStaticProperty_Local() + => TestInRegularAndScriptAsync( """ using System; @@ -8284,13 +7741,11 @@ public static int Property1 } } """, -index: LocalIndex); - } + index: LocalIndex); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8358")] - public async Task TestSameNameAsInstanceVariableInContainingType() - { - await TestInRegularAndScriptAsync( + public Task TestSameNameAsInstanceVariableInContainingType() + => TestInRegularAndScriptAsync( """ class Outer { @@ -8321,12 +7776,10 @@ public Inner(int field) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8358")] - public async Task TestNotOnStaticWithExistingInstance1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOnStaticWithExistingInstance1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -8338,12 +7791,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8358")] - public async Task TestNotOnStaticWithExistingInstance2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOnStaticWithExistingInstance2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -8355,12 +7806,10 @@ static C() } } """); - } [Fact] - public async Task TupleRead() - { - await TestInRegularAndScriptAsync( + public Task TupleRead() + => TestInRegularAndScriptAsync( """ class Class { @@ -8381,12 +7830,10 @@ void Method((int, string) i) } } """); - } [Fact] - public async Task TupleWithOneNameRead() - { - await TestInRegularAndScriptAsync( + public Task TupleWithOneNameRead() + => TestInRegularAndScriptAsync( """ class Class { @@ -8407,12 +7854,10 @@ void Method((int a, string) i) } } """); - } [Fact] - public async Task TupleWrite() - { - await TestInRegularAndScriptAsync( + public Task TupleWrite() + => TestInRegularAndScriptAsync( """ class Class { @@ -8433,12 +7878,10 @@ void Method() } } """); - } [Fact] - public async Task TupleWithOneNameWrite() - { - await TestInRegularAndScriptAsync( + public Task TupleWithOneNameWrite() + => TestInRegularAndScriptAsync( """ class Class { @@ -8459,12 +7902,10 @@ void Method() } } """); - } [Fact] - public async Task TupleRefReturnProperties() - { - await TestInRegularAndScriptAsync( + public Task TupleRefReturnProperties() + => TestInRegularAndScriptAsync( """ using System; class C @@ -8487,12 +7928,10 @@ public void Goo() } } """); - } [Fact] - public async Task TupleRefWithField() - { - await TestInRegularAndScriptAsync( + public Task TupleRefWithField() + => TestInRegularAndScriptAsync( """ using System; class C @@ -8515,12 +7954,10 @@ public void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17621")] - public async Task TestWithMatchingTypeName1() - { - await TestInRegularAndScript1Async( + public Task TestWithMatchingTypeName1() + => TestInRegularAndScript1Async( """ using System; @@ -8545,12 +7982,10 @@ public Goo(String goo) public string String { get; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17621")] - public async Task TestWithMatchingTypeName2() - { - await TestInRegularAndScript1Async( + public Task TestWithMatchingTypeName2() + => TestInRegularAndScript1Async( """ using System; @@ -8575,12 +8010,10 @@ public Goo(String goo) public string String { get; private set; } } """, index: ReadonlyFieldIndex); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18275")] - public async Task TestContextualKeyword1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestContextualKeyword1() + => TestMissingInRegularAndScriptAsync( """ namespace N { @@ -8597,12 +8030,10 @@ void M() } } """); - } [Fact] - public async Task TestPreferReadOnlyIfAfterReadOnlyAssignment() - { - await TestInRegularAndScriptAsync( + public Task TestPreferReadOnlyIfAfterReadOnlyAssignment() + => TestInRegularAndScriptAsync( """ class Class { @@ -8628,12 +8059,10 @@ public Class() } } """); - } [Fact] - public async Task TestPreferReadOnlyIfBeforeReadOnlyAssignment() - { - await TestInRegularAndScriptAsync( + public Task TestPreferReadOnlyIfBeforeReadOnlyAssignment() + => TestInRegularAndScriptAsync( """ class Class { @@ -8659,12 +8088,10 @@ public Class() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19239")] - public async Task TestGenerateReadOnlyPropertyInConstructor() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateReadOnlyPropertyInConstructor() + => TestInRegularAndScriptAsync( """ class Class { @@ -8685,12 +8112,10 @@ public Class() public int Bar { get; } } """); - } [Fact] - public async Task TestPlaceFieldBasedOnSurroundingStatements() - { - await TestInRegularAndScriptAsync( + public Task TestPlaceFieldBasedOnSurroundingStatements() + => TestInRegularAndScriptAsync( """ class Class { @@ -8720,12 +8145,10 @@ public Class() } } """); - } [Fact] - public async Task TestPlaceFieldBasedOnSurroundingStatements2() - { - await TestInRegularAndScriptAsync( + public Task TestPlaceFieldBasedOnSurroundingStatements2() + => TestInRegularAndScriptAsync( """ class Class { @@ -8755,12 +8178,10 @@ public Class() } } """); - } [Fact] - public async Task TestPlacePropertyBasedOnSurroundingStatements() - { - await TestInRegularAndScriptAsync( + public Task TestPlacePropertyBasedOnSurroundingStatements() + => TestInRegularAndScriptAsync( """ class Class { @@ -8790,12 +8211,10 @@ public Class() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19575")] - public async Task TestNotOnGenericCodeParsedAsExpression() - { - await TestMissingAsync(""" + public Task TestNotOnGenericCodeParsedAsExpression() + => TestMissingAsync(""" class C { private void GetEvaluationRuleNames() @@ -8805,12 +8224,10 @@ private void GetEvaluationRuleNames() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19575")] - public async Task TestOnNonGenericExpressionWithLessThan() - { - await TestInRegularAndScriptAsync(""" + public Task TestOnNonGenericExpressionWithLessThan() + => TestInRegularAndScriptAsync(""" class C { private void GetEvaluationRuleNames() @@ -8832,12 +8249,10 @@ private void GetEvaluationRuleNames() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18988")] - public async Task GroupNonReadonlyFieldsTogether() - { - await TestInRegularAndScriptAsync(""" + public Task GroupNonReadonlyFieldsTogether() + => TestInRegularAndScriptAsync(""" class C { public bool isDisposed; @@ -8865,12 +8280,10 @@ public C() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18988")] - public async Task GroupReadonlyFieldsTogether() - { - await TestInRegularAndScriptAsync(""" + public Task GroupReadonlyFieldsTogether() + => TestInRegularAndScriptAsync(""" class C { public readonly int x; @@ -8898,12 +8311,10 @@ public C() } } """, index: ReadonlyFieldIndex); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20791")] - public async Task TestWithOutOverload1() - { - await TestInRegularAndScriptAsync( + public Task TestWithOutOverload1() + => TestInRegularAndScriptAsync( """ class Class { @@ -8930,12 +8341,10 @@ void Goo(int i) { } void Goo(out bool b) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20791")] - public async Task TestWithOutOverload2() - { - await TestInRegularAndScriptAsync( + public Task TestWithOutOverload2() + => TestInRegularAndScriptAsync( """ class Class { @@ -8962,12 +8371,10 @@ void Goo(out bool b) { } void Goo(int i) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20791")] - public async Task TestWithRefOverload1() - { - await TestInRegularAndScriptAsync( + public Task TestWithRefOverload1() + => TestInRegularAndScriptAsync( """ class Class { @@ -8994,12 +8401,10 @@ void Goo(int i) { } void Goo(ref bool b) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20791")] - public async Task TestWithRefOverload2() - { - await TestInRegularAndScriptAsync( + public Task TestWithRefOverload2() + => TestInRegularAndScriptAsync( """ class Class { @@ -9026,12 +8431,10 @@ void Goo(ref bool b) { } void Goo(int i) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26993")] - public async Task TestGenerateFieldInExpressionBodiedGetter() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInExpressionBodiedGetter() + => TestInRegularAndScriptAsync( """ class Program { @@ -9052,12 +8455,10 @@ public int Property } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26993")] - public async Task TestGenerateFieldInExpressionBodiedGetterWithDifferentAccessibility() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInExpressionBodiedGetterWithDifferentAccessibility() + => TestInRegularAndScriptAsync( """ class Program { @@ -9080,12 +8481,10 @@ public int Property } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26993")] - public async Task TestGenerateReadonlyFieldInExpressionBodiedGetter() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateReadonlyFieldInExpressionBodiedGetter() + => TestInRegularAndScriptAsync( """ class Program { @@ -9106,13 +8505,11 @@ public int Property } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26993")] - public async Task TestGeneratePropertyInExpressionBodiedGetter() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyInExpressionBodiedGetter() + => TestInRegularAndScriptAsync( """ class Program { @@ -9132,13 +8529,11 @@ public int Property public int prop { get; private set; } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26993")] - public async Task TestGenerateFieldInExpressionBodiedSetterInferredFromType() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInExpressionBodiedSetterInferredFromType() + => TestInRegularAndScriptAsync( """ class Program { @@ -9159,12 +8554,10 @@ public int Property } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26993")] - public async Task TestGenerateFieldInExpressionBodiedLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInExpressionBodiedLocalFunction() + => TestInRegularAndScriptAsync( """ class Program { @@ -9185,12 +8578,10 @@ public void Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26993")] - public async Task TestGenerateReadonlyFieldInExpressionBodiedLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateReadonlyFieldInExpressionBodiedLocalFunction() + => TestInRegularAndScriptAsync( """ class Program { @@ -9211,13 +8602,11 @@ public void Method() } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26993")] - public async Task TestGeneratePropertyInExpressionBodiedLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyInExpressionBodiedLocalFunction() + => TestInRegularAndScriptAsync( """ class Program { @@ -9238,13 +8627,11 @@ public void Method() } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27647")] - public async Task TestGeneratePropertyInExpressionBodiedAsyncTaskOfTLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyInExpressionBodiedAsyncTaskOfTLocalFunction() + => TestInRegularAndScriptAsync( """ class Program { @@ -9265,13 +8652,11 @@ public void Method() } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26993")] - public async Task TestGenerateFieldInExpressionBodiedLocalFunctionInferredFromType() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInExpressionBodiedLocalFunctionInferredFromType() + => TestInRegularAndScriptAsync( """ class Program { @@ -9292,12 +8677,10 @@ public void Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26993")] - public async Task TestGenerateFieldInBlockBodiedLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInBlockBodiedLocalFunction() + => TestInRegularAndScriptAsync( """ class Program { @@ -9324,12 +8707,10 @@ int Local() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26993")] - public async Task TestGenerateReadonlyFieldInBlockBodiedLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateReadonlyFieldInBlockBodiedLocalFunction() + => TestInRegularAndScriptAsync( """ class Program { @@ -9356,13 +8737,11 @@ int Local() } } """, -index: ReadonlyFieldIndex); - } + index: ReadonlyFieldIndex); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26993")] - public async Task TestGeneratePropertyInBlockBodiedLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyInBlockBodiedLocalFunction() + => TestInRegularAndScriptAsync( """ class Program { @@ -9389,13 +8768,11 @@ int Local() } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact] - public async Task TestGeneratePropertyInBlockBodiedAsyncTaskOfTLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertyInBlockBodiedAsyncTaskOfTLocalFunction() + => TestInRegularAndScriptAsync( """ class Program { @@ -9422,13 +8799,11 @@ async System.Threading.Tasks.Task Local() } } """, -index: PropertyIndex); - } + index: PropertyIndex); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26993")] - public async Task TestGenerateFieldInBlockBodiedLocalFunctionInferredFromType() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInBlockBodiedLocalFunctionInferredFromType() + => TestInRegularAndScriptAsync( """ class Program { @@ -9455,12 +8830,10 @@ int Local() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26993")] - public async Task TestGenerateFieldInBlockBodiedLocalFunctionInsideLambdaExpression() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInBlockBodiedLocalFunctionInsideLambdaExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -9497,12 +8870,10 @@ int Local() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26993")] - public async Task TestGenerateFieldInExpressionBodiedLocalFunctionInsideLambdaExpression() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateFieldInExpressionBodiedLocalFunctionInsideLambdaExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -9533,12 +8904,10 @@ public void Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26406")] - public async Task TestIdentifierInsideLock1() - { - await TestInRegularAndScriptAsync( + public Task TestIdentifierInsideLock1() + => TestInRegularAndScriptAsync( """ class Class { @@ -9563,12 +8932,10 @@ void Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26406")] - public async Task TestIdentifierInsideLock2() - { - await TestInRegularAndScriptAsync( + public Task TestIdentifierInsideLock2() + => TestInRegularAndScriptAsync( """ class Class { @@ -9593,12 +8960,10 @@ void Method() } } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26406")] - public async Task TestIdentifierInsideLock3() - { - await TestInRegularAndScriptAsync( + public Task TestIdentifierInsideLock3() + => TestInRegularAndScriptAsync( """ class Class { @@ -9623,12 +8988,10 @@ void Method() } } """, index: 2); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/9090")] - public async Task TestPropertyPatternInIsPattern1() - { - await TestInRegularAndScriptAsync( + public Task TestPropertyPatternInIsPattern1() + => TestInRegularAndScriptAsync( """ class C { @@ -9662,12 +9025,10 @@ class Blah } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/9090")] - public async Task TestPropertyPatternInIsPattern2() - { - await TestInRegularAndScriptAsync( + public Task TestPropertyPatternInIsPattern2() + => TestInRegularAndScriptAsync( """ class C { @@ -9701,12 +9062,10 @@ class Blah } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/9090")] - public async Task TestPropertyPatternInIsPattern3() - { - await TestInRegularAndScriptAsync( + public Task TestPropertyPatternInIsPattern3() + => TestInRegularAndScriptAsync( """ class C { @@ -9750,12 +9109,10 @@ class Blah } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/9090")] - public async Task TestPropertyPatternInIsPattern4() - { - await TestInRegularAndScriptAsync( + public Task TestPropertyPatternInIsPattern4() + => TestInRegularAndScriptAsync( """ class C { @@ -9789,12 +9146,10 @@ class Blah } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/9090")] - public async Task TestPropertyPatternInIsPattern5() - { - await TestInRegularAndScriptAsync( + public Task TestPropertyPatternInIsPattern5() + => TestInRegularAndScriptAsync( """ class C { @@ -9836,12 +9191,10 @@ class Frob } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/9090")] - public async Task TestPropertyPatternInIsPattern6() - { - await TestInRegularAndScriptAsync( + public Task TestPropertyPatternInIsPattern6() + => TestInRegularAndScriptAsync( """ class C { @@ -9875,12 +9228,10 @@ class Blah } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/9090")] - public async Task TestPropertyPatternInIsPattern7() - { - await TestInRegularAndScriptAsync( + public Task TestPropertyPatternInIsPattern7() + => TestInRegularAndScriptAsync( """ class C { @@ -9914,12 +9265,10 @@ class Blah } } """ + TestResources.NetFX.ValueTuple.tuplelib_cs); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/9090")] - public async Task TestPropertyPatternInIsPattern8() - { - await TestInRegularAndScriptAsync( + public Task TestPropertyPatternInIsPattern8() + => TestInRegularAndScriptAsync( """ class C { @@ -9953,12 +9302,10 @@ class Blah } } """); - } [Fact] - public async Task TestExtendedPropertyPatternInIsPattern() - { - await TestInRegularAndScriptAsync( + public Task TestExtendedPropertyPatternInIsPattern() + => TestInRegularAndScriptAsync( """ class C { @@ -9996,12 +9343,10 @@ class Blah } } """ + TestResources.NetFX.ValueTuple.tuplelib_cs, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp12)); - } [Fact] - public async Task TestConstantPatternInPropertyPattern() - { - await TestInRegularAndScriptAsync( + public Task TestConstantPatternInPropertyPattern() + => TestInRegularAndScriptAsync( """ class C { @@ -10040,12 +9385,10 @@ class Blah } } """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp12)); - } [Fact] - public async Task TestConstantPatternInExtendedPropertyPattern() - { - await TestInRegularAndScriptAsync( + public Task TestConstantPatternInExtendedPropertyPattern() + => TestInRegularAndScriptAsync( """ class C { @@ -10086,12 +9429,10 @@ class Blah } } """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp12)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/9090")] - public async Task TestPropertyPatternInIsPattern9() - { - await TestInRegularAndScriptAsync( + public Task TestPropertyPatternInIsPattern9() + => TestInRegularAndScriptAsync( """ class C { @@ -10125,12 +9466,10 @@ class Blah } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/9090")] - public async Task TestPropertyPatternInIsPattern10() - { - await TestInRegularAndScriptAsync( + public Task TestPropertyPatternInIsPattern10() + => TestInRegularAndScriptAsync( """ class C { @@ -10164,12 +9503,10 @@ class Blah } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/9090")] - public async Task TestPropertyPatternInIsPatternWithNullablePattern() - { - await TestInRegularAndScriptAsync( + public Task TestPropertyPatternInIsPatternWithNullablePattern() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -10209,12 +9546,10 @@ class Blah } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/9090")] - public async Task TestPropertyPatternInCasePattern1() - { - await TestInRegularAndScriptAsync( + public Task TestPropertyPatternInCasePattern1() + => TestInRegularAndScriptAsync( """ class C { @@ -10252,12 +9587,10 @@ class Blah } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/9090")] - public async Task TestPropertyPatternInCasePattern2() - { - await TestInRegularAndScriptAsync( + public Task TestPropertyPatternInCasePattern2() + => TestInRegularAndScriptAsync( """ class C { @@ -10295,12 +9628,10 @@ class Blah } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/9090")] - public async Task TestPropertyPatternInIsSwitchExpression1() - { - await TestInRegularAndScriptAsync( + public Task TestPropertyPatternInIsSwitchExpression1() + => TestInRegularAndScriptAsync( """ class C { @@ -10330,12 +9661,10 @@ class Blah } } """); - } [Fact] - public async Task TestPropertyPatternGenerateConstant() - { - await TestInRegularAndScriptAsync( + public Task TestPropertyPatternGenerateConstant() + => TestInRegularAndScriptAsync( """ class C { @@ -10368,12 +9697,10 @@ class Blah } } """); - } [Fact] - public async Task TestAddParameter() - { - await TestInRegularAndScriptAsync( + public Task TestAddParameter() + => TestInRegularAndScriptAsync( """ class Class { @@ -10392,12 +9719,10 @@ void Method(object goo) } } """, index: Parameter); - } [Fact] - public async Task TestAddParameter_DoesntAddToInterface() - { - await TestInRegularAndScriptAsync( + public Task TestAddParameter_DoesntAddToInterface() + => TestInRegularAndScriptAsync( """ interface Interface { @@ -10426,12 +9751,10 @@ public void Method(object goo) } } """, index: Parameter); - } [Fact] - public async Task TestAddParameterAndOverrides_AddsToInterface() - { - await TestInRegularAndScriptAsync( + public Task TestAddParameterAndOverrides_AddsToInterface() + => TestInRegularAndScriptAsync( """ interface Interface { @@ -10460,12 +9783,10 @@ public void Method(object goo) } } """, index: ParameterAndOverrides); - } [Fact] - public async Task TestAddParameterIsOfCorrectType() - { - await TestInRegularAndScriptAsync( + public Task TestAddParameterIsOfCorrectType() + => TestInRegularAndScriptAsync( """ class Class { @@ -10488,12 +9809,10 @@ void Method(int goo) void M1(int a); } """, index: Parameter); - } [Fact] - public async Task TestAddParameterAndOverrides_IsOfCorrectType() - { - await TestInRegularAndScriptAsync( + public Task TestAddParameterAndOverrides_IsOfCorrectType() + => TestInRegularAndScriptAsync( """ interface Interface { @@ -10526,12 +9845,10 @@ public void Method(int goo) void M1(int a); } """, index: ParameterAndOverrides); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26502")] - public async Task TestNoReadOnlyMembersWhenInLambdaInConstructor() - { - await TestExactActionSetOfferedAsync( + public Task TestNoReadOnlyMembersWhenInLambdaInConstructor() + => TestExactActionSetOfferedAsync( """ using System; @@ -10550,12 +9867,10 @@ public C() string.Format(CodeFixesResources.Generate_property_0, "Field"), string.Format(CodeFixesResources.Generate_field_0, "Field"), ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26502")] - public async Task TestNoReadOnlyMembersWhenInLocalFunctionInConstructor() - { - await TestExactActionSetOfferedAsync( + public Task TestNoReadOnlyMembersWhenInLocalFunctionInConstructor() + => TestExactActionSetOfferedAsync( """ using System; @@ -10574,12 +9889,10 @@ void Goo() string.Format(CodeFixesResources.Generate_property_0, "Field"), string.Format(CodeFixesResources.Generate_field_0, "Field"), ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45367")] - public async Task DoNotOfferPropertyOrFieldInNamespace() - { - await TestExactActionSetOfferedAsync( + public Task DoNotOfferPropertyOrFieldInNamespace() + => TestExactActionSetOfferedAsync( """ using System; @@ -10597,18 +9910,14 @@ internal MyException(int error, int offset, string message) : base(message) string.Format(CodeFixesResources.Generate_local_0, "Error", "MyException"), string.Format(CodeFixesResources.Generate_parameter_0, "Error", "MyException"), ]); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48172")] - public async Task TestMissingOfferParameterInTopLevel() - { - await TestMissingAsync("[|Console|].WriteLine();", new TestParameters(Options.Regular)); - } + public Task TestMissingOfferParameterInTopLevel() + => TestMissingAsync("[|Console|].WriteLine();", new TestParameters(Options.Regular)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47586")] - public async Task TestGenerateParameterFromLambda() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateParameterFromLambda() + => TestInRegularAndScriptAsync( """ using System; using System.Diagnostics; @@ -10633,12 +9942,10 @@ private static void AssertSomething(bool expected) } } """, index: Parameter); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47586")] - public async Task TestGenerateParameterFromLambdaInLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateParameterFromLambdaInLocalFunction() + => TestInRegularAndScriptAsync( """ using System; using System.Diagnostics; @@ -10669,7 +9976,6 @@ void M(bool expected) } } """, index: Parameter); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/27646")] [InlineData("yield")] @@ -10711,26 +10017,28 @@ void M(bool expected) [InlineData("managed")] [InlineData("unmanaged")] [InlineData("dynamic")] - public async Task TestContextualKeywordsThatDoNotProbablyStartSyntacticConstructs_ReturnStatement(string keyword) - { - await TestInRegularAndScriptAsync( -$@"class C -{{ - int M() - {{ - [|return {keyword}|]; - }} -}}", -$@"class C -{{ - private int {keyword}; - - int M() - {{ - return {keyword}; - }} -}}"); - } + public Task TestContextualKeywordsThatDoNotProbablyStartSyntacticConstructs_ReturnStatement(string keyword) + => TestInRegularAndScriptAsync( + $$""" + class C + { + int M() + { + [|return {{keyword}}|]; + } + } + """, + $$""" + class C + { + private int {{keyword}}; + + int M() + { + return {{keyword}}; + } + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/27646")] [InlineData("from")] @@ -10738,17 +10046,17 @@ int M() [InlineData("async")] [InlineData("await")] [InlineData("var")] - public async Task TestContextualKeywordsThatCanProbablyStartSyntacticConstructs_ReturnStatement(string keyword) - { - await TestMissingInRegularAndScriptAsync( -$@"class C -{{ - int M() - {{ - [|return {keyword}|]; - }} -}}"); - } + public Task TestContextualKeywordsThatCanProbablyStartSyntacticConstructs_ReturnStatement(string keyword) + => TestMissingInRegularAndScriptAsync( + $$""" + class C + { + int M() + { + [|return {{keyword}}|]; + } + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/27646")] [InlineData("from")] @@ -10756,17 +10064,17 @@ int M() [InlineData("async")] [InlineData("await")] [InlineData("var")] - public async Task TestContextualKeywordsThatCanProbablyStartSyntacticConstructs_OnTheirOwn(string keyword) - { - await TestMissingInRegularAndScriptAsync( -$@"class C -{{ - int M() - {{ - [|{keyword}|] - }} -}}"); - } + public Task TestContextualKeywordsThatCanProbablyStartSyntacticConstructs_OnTheirOwn(string keyword) + => TestMissingInRegularAndScriptAsync( + $$""" + class C + { + int M() + { + [|{{keyword}}|] + } + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/27646")] [InlineData("from")] @@ -10774,21 +10082,20 @@ int M() [InlineData("async")] [InlineData("await")] [InlineData("var")] - public async Task TestContextualKeywordsThatCanProbablyStartSyntacticConstructs_Local(string keyword) - { - await TestMissingInRegularAndScriptAsync( -$@"class Program -{{ - void Main() - {{ - var x = [|{keyword}|]; - }}"); - } + public Task TestContextualKeywordsThatCanProbablyStartSyntacticConstructs_Local(string keyword) + => TestMissingInRegularAndScriptAsync( + $$""" + class Program + { + void Main() + { + var x = [|{{keyword}}|]; + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60842")] - public async Task TestGenerateParameterBeforeCancellationToken_OneParameter() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateParameterBeforeCancellationToken_OneParameter() + => TestInRegularAndScriptAsync( """ using System.Threading; using System.Threading.Tasks; @@ -10813,12 +10120,10 @@ public async Task M(System.TimeSpan time, CancellationToken cancellationToken) } } """, index: 4); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60842")] - public async Task TestGenerateParameterBeforeCancellationToken_SeveralParameters() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateParameterBeforeCancellationToken_SeveralParameters() + => TestInRegularAndScriptAsync( """ using System.Threading; using System.Threading.Tasks; @@ -10843,12 +10148,10 @@ public async Task M(string someParameter, System.TimeSpan time, CancellationToke } } """, index: 4); - } [Fact] - public async Task TestGenerateParameterBeforeCancellationTokenAndOptionalParameter() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateParameterBeforeCancellationTokenAndOptionalParameter() + => TestInRegularAndScriptAsync( """ using System.Threading; using System.Threading.Tasks; @@ -10873,12 +10176,10 @@ public async Task M(System.TimeSpan time, bool someParameter = true, Cancellatio } } """, index: 4); - } [Fact] - public async Task TestGenerateParameterBeforeCancellationTokenAndOptionalParameter_MultipleParameters() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateParameterBeforeCancellationTokenAndOptionalParameter_MultipleParameters() + => TestInRegularAndScriptAsync( """ using System.Threading; using System.Threading.Tasks; @@ -10903,12 +10204,10 @@ public async Task M(int value, System.TimeSpan time, bool someParameter = true, } } """, index: 4); - } [Fact] - public async Task TestGenerateParameterBeforeOptionalParameter() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateParameterBeforeOptionalParameter() + => TestInRegularAndScriptAsync( """ using System.Threading; using System.Threading.Tasks; @@ -10933,12 +10232,10 @@ public async Task M(System.TimeSpan time, bool someParameter = true) } } """, index: 4); - } [Fact] - public async Task TestGenerateParameterBeforeParamsParameter() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateParameterBeforeParamsParameter() + => TestInRegularAndScriptAsync( """ using System.Threading; using System.Threading.Tasks; @@ -10963,12 +10260,10 @@ public async Task M(System.TimeSpan time, params double[] x) } } """, index: 4); - } [Fact] - public async Task TestGenerateParameterBeforeThisParameter() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateParameterBeforeThisParameter() + => TestInRegularAndScriptAsync( """ using System.Threading; using System.Threading.Tasks; @@ -10993,12 +10288,10 @@ public static int Method(this CancellationToken cancellationToken, int test) } } """, index: 4); - } [Fact] - public async Task TestGenerateParameterBeforeAssortmentOfExceptions() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateParameterBeforeAssortmentOfExceptions() + => TestInRegularAndScriptAsync( """ using System.Threading; using System.Threading.Tasks; @@ -11023,12 +10316,10 @@ public static int Method(this CancellationToken cancellationToken, int test, out } } """, index: 4); - } [Fact] - public async Task TestGenerateParameterBeforeMultipleExceptions_BetweenOutParams() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateParameterBeforeMultipleExceptions_BetweenOutParams() + => TestInRegularAndScriptAsync( """ using System.Threading; using System.Threading.Tasks; @@ -11053,12 +10344,10 @@ public async Task M(out int x, int y, System.TimeSpan time, out int z, params do } } """, index: 4); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50764")] - public async Task TestMissingWhenGeneratingFunctionPointer() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWhenGeneratingFunctionPointer() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -11070,12 +10359,10 @@ public static ZZZ() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68322")] - public async Task TestImplicitObjectCreationExpression() - { - await TestInRegularAndScriptAsync( + public Task TestImplicitObjectCreationExpression() + => TestInRegularAndScriptAsync( """ class Example { @@ -11100,12 +10387,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68322")] - public async Task TestImplicitCollectionCreationExpression() - { - await TestInRegularAndScriptAsync( + public Task TestImplicitCollectionCreationExpression() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -11130,12 +10415,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58491")] - public async Task TestGeneratePropertiesFromTopLevel() - { - await TestInRegularAndScriptAsync( + public Task TestGeneratePropertiesFromTopLevel() + => TestInRegularAndScriptAsync( """ var x = new Test() { [|A|] = 1, B = 1 }; class Test @@ -11149,12 +10432,10 @@ class Test public int A { get; internal set; } } """); - } [Fact] - public async Task TestNullConditionalAssignment1() - { - await TestInRegularAndScriptAsync( + public Task TestNullConditionalAssignment1() + => TestInRegularAndScriptAsync( """ class Class { @@ -11175,12 +10456,10 @@ void Method(Class c) } } """); - } [Fact] - public async Task TestNullConditionalAssignment2() - { - await TestInRegularAndScriptAsync( + public Task TestNullConditionalAssignment2() + => TestInRegularAndScriptAsync( """ class Class { @@ -11201,12 +10480,10 @@ void Method(Class c) } } """); - } [Fact] - public async Task TestNullConditionalAssignment3() - { - await TestInRegularAndScriptAsync( + public Task TestNullConditionalAssignment3() + => TestInRegularAndScriptAsync( """ class Class { @@ -11234,12 +10511,10 @@ class D public int Goo { get; internal set; } } """); - } [Fact] - public async Task TestNullConditionalAssignment4() - { - await TestInRegularAndScriptAsync( + public Task TestNullConditionalAssignment4() + => TestInRegularAndScriptAsync( """ class Class { @@ -11267,5 +10542,4 @@ struct D public int Goo { get; internal set; } } """); - } } diff --git a/src/Features/CSharpTest/InlineTemporary/InlineTemporaryTests.cs b/src/Features/CSharpTest/InlineTemporary/InlineTemporaryTests.cs index cce147aef8d77..592fee800724d 100644 --- a/src/Features/CSharpTest/InlineTemporary/InlineTemporaryTests.cs +++ b/src/Features/CSharpTest/InlineTemporary/InlineTemporaryTests.cs @@ -53,9 +53,8 @@ public async Task NotOnSecondWithNoInitializer() => await TestMissingInRegularAndScriptAsync(GetTreeText(@"{ int x = 42, [||]y; System.Console.WriteLine(y); }")); [Fact] - public async Task NotOnField() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnField() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -67,12 +66,10 @@ void M() } } """); - } [Fact] - public async Task WithRefInitializer1() - { - await TestMissingInRegularAndScriptAsync( + public Task WithRefInitializer1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -84,7 +81,6 @@ ref int M() } } """); - } [Fact] public async Task SingleStatement() @@ -103,9 +99,8 @@ public async Task MultipleDeclarators_Last() => await TestMissingInRegularAndScriptAsync(GetTreeText(@"{ int x = 0, y = 1, [||]z = 2; }")); [Fact] - public async Task Escaping1() - { - await TestFixOneAsync( + public Task Escaping1() + => TestFixOneAsync( """ { int [||]x = 0; @@ -115,12 +110,10 @@ await TestFixOneAsync( { Console.WriteLine(0); } """); - } [Fact] - public async Task Escaping2() - { - await TestFixOneAsync( + public Task Escaping2() + => TestFixOneAsync( """ { int [||]@x = 0; @@ -130,12 +123,10 @@ await TestFixOneAsync( { Console.WriteLine(0); } """); - } [Fact] - public async Task Escaping3() - { - await TestFixOneAsync( + public Task Escaping3() + => TestFixOneAsync( """ { int [||]@x = 0; @@ -145,12 +136,10 @@ await TestFixOneAsync( { Console.WriteLine(0); } """); - } [Fact] - public async Task Escaping4() - { - await TestFixOneAsync( + public Task Escaping4() + => TestFixOneAsync( """ { int [||]x = 0; @@ -160,12 +149,10 @@ await TestFixOneAsync( { Console.WriteLine(0); } """); - } [Fact] - public async Task Escaping5() - { - var code = """ + public Task Escaping5() + => TestInRegularAndScriptAsync(""" using System.Linq; class C { @@ -175,9 +162,7 @@ static void Main() var q = from e in "" let a = new { @where } select a; } } - """; - - var expected = """ + """, """ using System.Linq; class C { @@ -186,15 +171,11 @@ static void Main() var q = from e in "" let a = new { @where = 0 } select a; } } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task Call() - { - var code = """ + public Task Call() + => TestInRegularAndScriptAsync(""" using System; class C { @@ -204,9 +185,7 @@ public void M() x.ToString(); } } - """; - - var expected = """ + """, """ using System; class C { @@ -215,15 +194,11 @@ public void M() (1 + 1).ToString(); } } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task Conversion_NoChange() - { - var code = """ + public Task Conversion_NoChange() + => TestInRegularAndScriptAsync(""" using System; class C { @@ -233,9 +208,7 @@ public void M() x.ToString(); } } - """; - - var expected = """ + """, """ using System; class C { @@ -244,15 +217,11 @@ public void M() ((double)3).ToString(); } } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task Conversion_NoConversion() - { - await TestAsync( + public Task Conversion_NoConversion() + => TestAsync( """ class C { @@ -269,12 +238,10 @@ void F(){ } """, CSharpParseOptions.Default); - } [Fact] - public async Task Conversion_DifferentOverload() - { - await TestInRegularAndScriptAsync( + public Task Conversion_DifferentOverload() + => TestInRegularAndScriptAsync( """ using System; class C @@ -297,12 +264,10 @@ void M() } } """); - } [Fact] - public async Task Conversion_DifferentMethod() - { - await TestInRegularAndScriptAsync( + public Task Conversion_DifferentMethod() + => TestInRegularAndScriptAsync( """ class Base { @@ -339,12 +304,10 @@ void F() } } """); - } [Fact] - public async Task Conversion_SameMethod() - { - await TestInRegularAndScriptAsync( + public Task Conversion_SameMethod() + => TestInRegularAndScriptAsync( """ class Base { @@ -381,14 +344,12 @@ void F() } } """); - } [Theory] [InlineData(LanguageVersion.CSharp8)] [InlineData(LanguageVersion.CSharp9)] - public async Task Conversion_NonTargetTypedConditionalExpression(LanguageVersion languageVersion) - { - await TestInRegularAndScriptAsync( + public Task Conversion_NonTargetTypedConditionalExpression(LanguageVersion languageVersion) + => TestInRegularAndScriptAsync( """ class C { @@ -409,14 +370,12 @@ void F() } } """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(languageVersion)); - } [Theory] [InlineData(LanguageVersion.CSharp8, " (int?)42")] [InlineData(LanguageVersion.CSharp9, " 42")] // In C# 9, target-typed conditionals makes this work - public async Task Conversion_TargetTypedConditionalExpression(LanguageVersion languageVersion, string expectedSubstitution) - { - await TestInRegularAndScriptAsync( + public Task Conversion_TargetTypedConditionalExpression(LanguageVersion languageVersion, string expectedSubstitution) + => TestInRegularAndScriptAsync( """ class C { @@ -439,12 +398,10 @@ void F() } } """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(languageVersion)); - } [Fact] - public async Task NoCastOnVar() - { - await TestFixOneAsync( + public Task NoCastOnVar() + => TestFixOneAsync( """ { var [||]x = 0; @@ -454,12 +411,10 @@ await TestFixOneAsync( { Console.WriteLine(0); } """); - } [Fact] - public async Task DoubleAssignment() - { - var code = """ + public Task DoubleAssignment() + => TestMissingAsync(""" class C { void M() @@ -468,37 +423,29 @@ void M() int y = x; } } - """; - - await TestMissingAsync(code); - } + """); [Fact] - public async Task TestAnonymousType1() - { - await TestFixOneAsync( + public Task TestAnonymousType1() + => TestFixOneAsync( """ { int [||]x = 42; var a = new { x }; } """, - @"{ var a = new { x = 42 }; }"); - } + @"{ var a = new { x = 42 }; }"); [Fact] - public async Task TestParenthesizedAtReference_Case3() - { - await TestFixOneAsync( + public Task TestParenthesizedAtReference_Case3() + => TestFixOneAsync( """ { int [||]x = 1 + 1; int y = x * 2; } """, - @"{ int y = (1 + 1) * 2; }"); - } + @"{ int y = (1 + 1) * 2; }"); [Fact] - public async Task DoNotBreakOverloadResolution_Case5() - { - var code = """ + public Task DoNotBreakOverloadResolution_Case5() + => TestInRegularAndScriptAsync(""" class C { void Goo(object o) { } @@ -510,9 +457,7 @@ void M() Goo(x); } } - """; - - var expected = """ + """, """ class C { void Goo(object o) { } @@ -523,15 +468,11 @@ void M() Goo((object)(1 + 1)); } } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task DoNotTouchUnrelatedBlocks() - { - var code = """ + public Task DoNotTouchUnrelatedBlocks() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -541,9 +482,7 @@ void M() Goo(x); } } - """; - - var expected = """ + """, """ class C { void M() @@ -552,15 +491,11 @@ void M() Goo(1); } } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task TestLambdaParenthesizeAndCast_Case7() - { - var code = """ + public Task TestLambdaParenthesizeAndCast_Case7() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -569,9 +504,7 @@ void M() int y = x(); } } - """; - - var expected = """ + """, """ class C { void M() @@ -579,15 +512,11 @@ void M() int y = ((System.Func)(() => 1))(); } } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538094")] - public async Task ParseAmbiguity1() - { - await TestInRegularAndScriptAsync( + public Task ParseAmbiguity1() + => TestInRegularAndScriptAsync( """ class C { @@ -611,12 +540,10 @@ void F(object a, object b) int f = 0; } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538094"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541462")] - public async Task ParseAmbiguity2() - { - await TestInRegularAndScriptAsync( + public Task ParseAmbiguity2() + => TestInRegularAndScriptAsync( """ class C { @@ -640,12 +567,10 @@ void F(object a, object b) int f = 0; } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538094")] - public async Task ParseAmbiguity3() - { - await TestInRegularAndScriptAsync( + public Task ParseAmbiguity3() + => TestInRegularAndScriptAsync( """ class C { @@ -669,12 +594,10 @@ void F(object a, object b) int f = 0; } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544924")] - public async Task ParseAmbiguity4() - { - await TestInRegularAndScriptAsync( + public Task ParseAmbiguity4() + => TestInRegularAndScriptAsync( """ class Program { @@ -704,12 +627,10 @@ static void Bar(object a, object b) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544613")] - public async Task ParseAmbiguity5() - { - await TestInRegularAndScriptAsync( + public Task ParseAmbiguity5() + => TestInRegularAndScriptAsync( """ class Program { @@ -731,12 +652,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538131")] - public async Task TestArrayInitializer() - { - await TestFixOneAsync( + public Task TestArrayInitializer() + => TestFixOneAsync( """ { int[] [||]x = { 3, @@ -753,12 +672,10 @@ await TestFixOneAsync( 5 }, 3); } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545657")] - public async Task TestArrayInitializer2() - { - var initial = """ + public Task TestArrayInitializer2() + => TestInRegularAndScriptAsync(""" class Program { static void Main() @@ -767,9 +684,7 @@ static void Main() System.Array a = x; } } - """; - - var expected = """ + """, """ class Program { static void Main() @@ -777,15 +692,11 @@ static void Main() System.Array a = new int[] { 3, 4, 5 }; } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545657")] - public async Task TestArrayInitializer3() - { - var initial = """ + public Task TestArrayInitializer3() + => TestInRegularAndScriptAsync(""" class Program { static void Main() @@ -798,9 +709,7 @@ static void Main() System.Array a = x; } } - """; - - var expected = """ + """, """ class Program { static void Main() @@ -812,16 +721,11 @@ static void Main() }; } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestConflict_RefParameter1() - { - var initial = - """ + public Task TestConflict_RefParameter1() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -840,10 +744,7 @@ void Goo(ref int x) { } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -862,16 +763,11 @@ void Goo(ref int x) { } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestConflict_RefParameter2() - { - var initial = - """ + public Task TestConflict_RefParameter2() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -885,10 +781,7 @@ void Goo(int x, ref int y) { } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -902,16 +795,11 @@ void Goo(int x, ref int y) { } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestConflict_AssignExpression() - { - var initial = - """ + public Task TestConflict_AssignExpression() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -922,10 +810,7 @@ void Main() Console.WriteLine(i); } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -936,16 +821,11 @@ void Main() Console.WriteLine(1); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestConflict_AddAssignExpression1() - { - var initial = - """ + public Task TestConflict_AddAssignExpression1() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -956,10 +836,7 @@ void Main() Console.WriteLine(i); } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -970,16 +847,11 @@ void Main() Console.WriteLine(1); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestConflict_AddAssignExpression2() - { - var initial = - """ + public Task TestConflict_AddAssignExpression2() + => TestMissingAsync(""" using System; class C { @@ -991,16 +863,11 @@ static void M() int y = x; } } - """; - - await TestMissingAsync(initial); - } + """); [Fact] - public async Task TestConflict_SubtractAssignExpression() - { - var initial = - """ + public Task TestConflict_SubtractAssignExpression() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -1011,10 +878,7 @@ void Main() Console.WriteLine(i); } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -1025,16 +889,11 @@ void Main() Console.WriteLine(1); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestConflict_MultiplyAssignExpression() - { - var initial = - """ + public Task TestConflict_MultiplyAssignExpression() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -1045,10 +904,7 @@ void Main() Console.WriteLine(i); } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -1059,16 +915,11 @@ void Main() Console.WriteLine(1); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestConflict_DivideAssignExpression() - { - var initial = - """ + public Task TestConflict_DivideAssignExpression() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -1079,10 +930,7 @@ void Main() Console.WriteLine(i); } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -1093,16 +941,11 @@ void Main() Console.WriteLine(1); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestConflict_ModuloAssignExpression() - { - var initial = - """ + public Task TestConflict_ModuloAssignExpression() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -1113,10 +956,7 @@ void Main() Console.WriteLine(i); } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -1127,16 +967,11 @@ void Main() Console.WriteLine(1); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestConflict_AndAssignExpression() - { - var initial = - """ + public Task TestConflict_AndAssignExpression() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -1147,10 +982,7 @@ void Main() Console.WriteLine(i); } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -1161,16 +993,11 @@ void Main() Console.WriteLine(1); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestConflict_OrAssignExpression() - { - var initial = - """ + public Task TestConflict_OrAssignExpression() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -1181,10 +1008,7 @@ void Main() Console.WriteLine(i); } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -1195,16 +1019,11 @@ void Main() Console.WriteLine(1); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestConflict_ExclusiveOrAssignExpression() - { - var initial = - """ + public Task TestConflict_ExclusiveOrAssignExpression() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -1215,10 +1034,7 @@ void Main() Console.WriteLine(i); } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -1229,16 +1045,11 @@ void Main() Console.WriteLine(1); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestConflict_LeftShiftAssignExpression() - { - var initial = - """ + public Task TestConflict_LeftShiftAssignExpression() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -1249,10 +1060,7 @@ void Main() Console.WriteLine(i); } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -1263,16 +1071,11 @@ void Main() Console.WriteLine(1); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestConflict_RightShiftAssignExpression() - { - var initial = - """ + public Task TestConflict_RightShiftAssignExpression() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -1283,10 +1086,7 @@ void Main() Console.WriteLine(i); } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -1297,16 +1097,11 @@ void Main() Console.WriteLine(1); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestConflict_PostIncrementExpression() - { - var initial = - """ + public Task TestConflict_PostIncrementExpression() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -1317,10 +1112,7 @@ void Main() Console.WriteLine(i); } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -1331,16 +1123,11 @@ void Main() Console.WriteLine(1); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestConflict_PreIncrementExpression() - { - var initial = - """ + public Task TestConflict_PreIncrementExpression() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -1351,10 +1138,7 @@ void Main() Console.WriteLine(i); } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -1365,16 +1149,11 @@ void Main() Console.WriteLine(1); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestConflict_PostDecrementExpression() - { - var initial = - """ + public Task TestConflict_PostDecrementExpression() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -1385,10 +1164,7 @@ void Main() Console.WriteLine(i); } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -1399,16 +1175,11 @@ void Main() Console.WriteLine(1); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestConflict_PreDecrementExpression() - { - var initial = - """ + public Task TestConflict_PreDecrementExpression() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -1419,10 +1190,7 @@ void Main() Console.WriteLine(i); } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -1433,15 +1201,11 @@ void Main() Console.WriteLine(1); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task TestConflict_AddressOfExpression() - { - var initial = """ + public Task TestConflict_AddressOfExpression() + => TestInRegularAndScriptAsync(""" class C { unsafe void M() @@ -1451,9 +1215,7 @@ unsafe void M() var z = &y; } } - """; - - var expected = """ + """, """ class C { unsafe void M() @@ -1463,16 +1225,11 @@ unsafe void M() var z = &{|Conflict:y|}; } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545342")] - public async Task TestConflict_UsedBeforeDeclaration() - { - var initial = - """ + public Task TestConflict_UsedBeforeDeclaration() + => TestInRegularAndScriptAsync(""" class Program { static void Main(string[] args) @@ -1481,10 +1238,7 @@ static void Main(string[] args) var y[||] = 45; } } - """; - - var expected = - """ + """, """ class Program { static void Main(string[] args) @@ -1493,15 +1247,11 @@ static void Main(string[] args) var y = 45; } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact] - public async Task Preprocessor1() - { - await TestFixOneAsync(""" + public Task Preprocessor1() + => TestFixOneAsync(""" { int [||]x = 1, #if true @@ -1523,12 +1273,10 @@ await TestFixOneAsync(""" int a = 1; } """); - } [Fact] - public async Task Preprocessor2() - { - await TestFixOneAsync(""" + public Task Preprocessor2() + => TestFixOneAsync(""" { int y, #if true @@ -1550,12 +1298,10 @@ await TestFixOneAsync(""" int a = 1; } """); - } [Fact] - public async Task Preprocessor3() - { - await TestFixOneAsync(""" + public Task Preprocessor3() + => TestFixOneAsync(""" { int y, #if true @@ -1577,13 +1323,10 @@ await TestFixOneAsync(""" int a = 1; } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540164")] - public async Task TriviaOnArrayInitializer() - { - var initial = - """ + public Task TriviaOnArrayInitializer() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -1592,10 +1335,7 @@ void M() Goo(a); } } - """; - - var expected = - """ + """, """ class C { void M() @@ -1603,16 +1343,11 @@ void M() Goo(new int[]/**/{ 1 }); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540156")] - public async Task ProperlyFormatWhenRemovingDeclarator1() - { - var initial = - """ + public Task ProperlyFormatWhenRemovingDeclarator1() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -1621,10 +1356,7 @@ void M() System.Console.Write(i); } } - """; - - var expected = - """ + """, """ class C { void M() @@ -1633,16 +1365,11 @@ void M() System.Console.Write(1); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540156")] - public async Task ProperlyFormatWhenRemovingDeclarator2() - { - var initial = - """ + public Task ProperlyFormatWhenRemovingDeclarator2() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -1651,10 +1378,7 @@ void M() System.Console.Write(j); } } - """; - - var expected = - """ + """, """ class C { void M() @@ -1663,16 +1387,11 @@ void M() System.Console.Write(2); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540156")] - public async Task ProperlyFormatWhenRemovingDeclarator3() - { - var initial = - """ + public Task ProperlyFormatWhenRemovingDeclarator3() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -1681,10 +1400,7 @@ void M() System.Console.Write(k); } } - """; - - var expected = - """ + """, """ class C { void M() @@ -1693,16 +1409,11 @@ void M() System.Console.Write(3); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540186")] - public async Task ProperlyFormatAnonymousTypeMember() - { - var initial = - """ + public Task ProperlyFormatAnonymousTypeMember() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -1711,10 +1422,7 @@ void M() var y = new { x }; } } - """; - - var expected = - """ + """, """ class C { void M() @@ -1722,16 +1430,11 @@ void M() var y = new { x = 123 }; } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact, WorkItem(6356, "DevDiv_Projects/Roslyn")] - public async Task InlineToAnonymousTypeProperty() - { - var initial = - """ + public Task InlineToAnonymousTypeProperty() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -1740,10 +1443,7 @@ void M() var y = new { x = x }; } } - """; - - var expected = - """ + """, """ class C { void M() @@ -1751,16 +1451,11 @@ void M() var y = new { x = 123 }; } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528075")] - public async Task InlineIntoDelegateInvocation() - { - var initial = - """ + public Task InlineIntoDelegateInvocation() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -1770,10 +1465,7 @@ static void Main(string[] args) del(null); } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -1782,16 +1474,11 @@ static void Main(string[] args) ((Action)Main)(null); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541341")] - public async Task InlineAnonymousMethodIntoNullCoalescingExpression() - { - var initial = - """ + public Task InlineAnonymousMethodIntoNullCoalescingExpression() + => TestInRegularAndScriptAsync(""" using System; class Program @@ -1802,10 +1489,7 @@ static void Main() Action y = x ?? null; } } - """; - - var expected = - """ + """, """ using System; class Program @@ -1815,16 +1499,11 @@ static void Main() Action y = (Action)delegate { } ?? null; } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541341")] - public async Task InlineLambdaIntoNullCoalescingExpression() - { - var initial = - """ + public Task InlineLambdaIntoNullCoalescingExpression() + => TestInRegularAndScriptAsync(""" using System; class Program @@ -1835,10 +1514,7 @@ static void Main() Action y = x ?? null; } } - """; - - var expected = - """ + """, """ using System; class Program @@ -1848,16 +1524,11 @@ static void Main() Action y = (Action)(() => { }) ?? null; } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538079")] - public async Task InsertCastForBoxingOperation1() - { - var initial = - """ + public Task InsertCastForBoxingOperation1() + => TestInRegularAndScriptAsync(""" using System; class A { @@ -1868,10 +1539,7 @@ static void Main() Console.WriteLine((long)z); } } - """; - - var expected = - """ + """, """ using System; class A { @@ -1881,16 +1549,11 @@ static void Main() Console.WriteLine((long)z); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538079")] - public async Task InsertCastForBoxingOperation2() - { - var initial = - """ + public Task InsertCastForBoxingOperation2() + => TestInRegularAndScriptAsync(""" using System; class A { @@ -1902,10 +1565,7 @@ static void Main() Console.WriteLine((long)z); } } - """; - - var expected = - """ + """, """ using System; class A { @@ -1916,16 +1576,11 @@ static void Main() Console.WriteLine((long)z); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538079")] - public async Task InsertCastForBoxingOperation3() - { - var initial = - """ + public Task InsertCastForBoxingOperation3() + => TestInRegularAndScriptAsync(""" using System; class A { @@ -1936,10 +1591,7 @@ static void Main() Console.WriteLine((byte)z); } } - """; - - var expected = - """ + """, """ using System; class A { @@ -1949,16 +1601,11 @@ static void Main() Console.WriteLine((byte)z); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538079")] - public async Task InsertCastForBoxingOperation4() - { - var initial = - """ + public Task InsertCastForBoxingOperation4() + => TestInRegularAndScriptAsync(""" using System; class A { @@ -1969,10 +1616,7 @@ static void Main() Console.WriteLine((sbyte)z); } } - """; - - var expected = - """ + """, """ using System; class A { @@ -1982,16 +1626,11 @@ static void Main() Console.WriteLine((sbyte)z); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538079")] - public async Task InsertCastForBoxingOperation5() - { - var initial = - """ + public Task InsertCastForBoxingOperation5() + => TestInRegularAndScriptAsync(""" using System; class A { @@ -2002,10 +1641,7 @@ static void Main() Console.WriteLine((short)z); } } - """; - - var expected = - """ + """, """ using System; class A { @@ -2015,15 +1651,11 @@ static void Main() Console.WriteLine((short)z); } } - """; - - await TestInRegularAndScriptAsync(initial, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540278")] - public async Task TestLeadingTrivia() - { - await TestInRegularAndScriptAsync( + public Task TestLeadingTrivia() + => TestInRegularAndScriptAsync( """ class Program { @@ -2047,12 +1679,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540278")] - public async Task TestLeadingAndTrailingTrivia() - { - await TestInRegularAndScriptAsync( + public Task TestLeadingAndTrailingTrivia() + => TestInRegularAndScriptAsync( """ class Program { @@ -2077,12 +1707,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540278")] - public async Task TestTrailingTrivia() - { - await TestInRegularAndScriptAsync( + public Task TestTrailingTrivia() + => TestInRegularAndScriptAsync( """ class Program { @@ -2105,12 +1733,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540278")] - public async Task TestPreprocessor() - { - await TestInRegularAndScriptAsync( + public Task TestPreprocessor() + => TestInRegularAndScriptAsync( """ class Program { @@ -2136,12 +1762,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540277")] - public async Task TestFormatting() - { - await TestInRegularAndScriptAsync( + public Task TestFormatting() + => TestInRegularAndScriptAsync( """ class Program { @@ -2162,12 +1786,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541694")] - public async Task TestSwitchSection() - { - await TestInRegularAndScriptAsync( + public Task TestSwitchSection() + => TestInRegularAndScriptAsync( """ using System; class C @@ -2199,12 +1821,10 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542647")] - public async Task UnparenthesizeExpressionIfNeeded1() - { - await TestInRegularAndScriptAsync( + public Task UnparenthesizeExpressionIfNeeded1() + => TestInRegularAndScriptAsync( """ using System; class C @@ -2229,12 +1849,10 @@ static void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545619")] - public async Task UnparenthesizeExpressionIfNeeded2() - { - await TestInRegularAndScriptAsync( + public Task UnparenthesizeExpressionIfNeeded2() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -2259,12 +1877,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542656")] - public async Task ParenthesizeIfNecessary1() - { - await TestInRegularAndScriptAsync( + public Task ParenthesizeIfNecessary1() + => TestInRegularAndScriptAsync( """ using System; using System.Collections; @@ -2296,12 +1912,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544626")] - public async Task ParenthesizeIfNecessary2() - { - await TestInRegularAndScriptAsync( + public Task ParenthesizeIfNecessary2() + => TestInRegularAndScriptAsync( """ using System; class C @@ -2329,12 +1943,10 @@ static void Main() static void Goo(T y) { } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544415")] - public async Task ParenthesizeAddressOf1() - { - await TestInRegularAndScriptAsync( + public Task ParenthesizeAddressOf1() + => TestInRegularAndScriptAsync( """ using System; unsafe class C @@ -2358,12 +1970,10 @@ static void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544922")] - public async Task ParenthesizeAddressOf2() - { - await TestInRegularAndScriptAsync( + public Task ParenthesizeAddressOf2() + => TestInRegularAndScriptAsync( """ using System; unsafe class C @@ -2387,12 +1997,10 @@ static void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544921")] - public async Task ParenthesizePointerIndirection1() - { - await TestInRegularAndScriptAsync( + public Task ParenthesizePointerIndirection1() + => TestInRegularAndScriptAsync( """ using System; unsafe class C @@ -2416,12 +2024,10 @@ static void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544614")] - public async Task ParenthesizePointerIndirection2() - { - await TestInRegularAndScriptAsync( + public Task ParenthesizePointerIndirection2() + => TestInRegularAndScriptAsync( """ using System; unsafe class C @@ -2445,12 +2051,10 @@ static void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544563")] - public async Task DoNotInlineStackAlloc() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotInlineStackAlloc() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2465,12 +2069,10 @@ static void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543744")] - public async Task InlineTempLambdaExpressionCastingError() - { - await TestInRegularAndScriptAsync( + public Task InlineTempLambdaExpressionCastingError() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -2493,12 +2095,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task InsertCastForNull() - { - await TestInRegularAndScriptAsync( + public Task InsertCastForNull() + => TestInRegularAndScriptAsync( """ using System; class C @@ -2521,12 +2121,10 @@ void M() } } """); - } [Fact] - public async Task InsertCastIfNeeded1() - { - await TestInRegularAndScriptAsync( + public Task InsertCastIfNeeded1() + => TestInRegularAndScriptAsync( """ class C { @@ -2546,12 +2144,10 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545161")] - public async Task InsertCastIfNeeded2() - { - await TestInRegularAndScriptAsync( + public Task InsertCastIfNeeded2() + => TestInRegularAndScriptAsync( """ using System; @@ -2580,12 +2176,10 @@ static void Goo(Action x) { } static void Goo(Action x) { } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544612")] - public async Task InlineIntoBracketedList() - { - await TestInRegularAndScriptAsync( + public Task InlineIntoBracketedList() + => TestInRegularAndScriptAsync( """ class C { @@ -2612,12 +2206,10 @@ void M() int this[object x] { set { } } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542648")] - public async Task ParenthesizeAfterCastIfNeeded() - { - await TestAsync( + public Task ParenthesizeAfterCastIfNeeded() + => TestAsync( """ using System; @@ -2647,12 +2239,10 @@ static void Main() } """, parseOptions: null); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544635")] - public async Task InsertCastForEnumZeroIfBoxed() - { - await TestAsync( + public Task InsertCastForEnumZeroIfBoxed() + => TestAsync( """ using System; class Program @@ -2678,13 +2268,11 @@ static void M() } """, parseOptions: null); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554010")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544636")] - public async Task InsertCastForMethodGroupIfNeeded1() - { - await TestAsync( + public Task InsertCastForMethodGroupIfNeeded1() + => TestAsync( """ using System; class Program @@ -2708,13 +2296,11 @@ static void M() } """, parseOptions: null); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554010")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544978")] - public async Task InsertCastForMethodGroupIfNeeded2() - { - await TestAsync( + public Task InsertCastForMethodGroupIfNeeded2() + => TestAsync( """ using System; class Program @@ -2738,12 +2324,10 @@ static void Main() } """, parseOptions: null); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545103")] - public async Task DoNotInsertCastForTypeThatNoLongerBindsToTheSameType() - { - await TestAsync( + public Task DoNotInsertCastForTypeThatNoLongerBindsToTheSameType() + => TestAsync( """ class A { @@ -2773,13 +2357,11 @@ static void Goo() } """, parseOptions: null); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/56938")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545170")] - public async Task InsertCorrectCastForDelegateCreationExpression() - { - await TestInRegularAndScriptAsync( + public Task InsertCorrectCastForDelegateCreationExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -2804,12 +2386,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545523")] - public async Task DoNotInsertCastForObjectCreationIfUnneeded() - { - await TestInRegularAndScriptAsync( + public Task DoNotInsertCastForObjectCreationIfUnneeded() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -2832,12 +2412,10 @@ static void Main() } } """); - } [Fact] - public async Task DoNotInsertCastInForeachIfUnneeded01() - { - await TestInRegularAndScriptAsync( + public Task DoNotInsertCastInForeachIfUnneeded01() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -2866,12 +2444,10 @@ static void Main() } } """); - } [Fact] - public async Task InsertCastInForeachIfNeeded01() - { - await TestInRegularAndScriptAsync( + public Task InsertCastInForeachIfNeeded01() + => TestInRegularAndScriptAsync( """ using System; using System.Collections; @@ -2900,12 +2476,10 @@ static void Main() } } """); - } [Fact] - public async Task InsertCastInForeachIfNeeded02() - { - await TestInRegularAndScriptAsync( + public Task InsertCastInForeachIfNeeded02() + => TestInRegularAndScriptAsync( """ using System; using System.Collections; @@ -2934,12 +2508,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545601")] - public async Task InsertCastToKeepGenericMethodInference() - { - await TestInRegularAndScriptAsync( + public Task InsertCastToKeepGenericMethodInference() + => TestInRegularAndScriptAsync( """ using System; class C @@ -2966,12 +2538,10 @@ static void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545601")] - public async Task InsertCastForKeepImplicitArrayInference() - { - await TestInRegularAndScriptAsync( + public Task InsertCastForKeepImplicitArrayInference() + => TestInRegularAndScriptAsync( """ class C { @@ -2998,12 +2568,10 @@ static void M() static void Goo(object[] o) { } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545601")] - public async Task InsertASingleCastToNotBreakOverloadResolution() - { - await TestInRegularAndScriptAsync( + public Task InsertASingleCastToNotBreakOverloadResolution() + => TestInRegularAndScriptAsync( """ class C { @@ -3030,12 +2598,10 @@ static void Goo(int x, int y) { } static void Goo(long x, long y) { } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545601")] - public async Task InsertASingleCastToNotBreakOverloadResolutionInLambdas() - { - await TestInRegularAndScriptAsync( + public Task InsertASingleCastToNotBreakOverloadResolutionInLambdas() + => TestInRegularAndScriptAsync( """ using System; class C @@ -3064,12 +2630,10 @@ static void Goo(Func x, Func y) { } static void Goo(Func x, Func y) { } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545601")] - public async Task InsertASingleCastToNotBreakResolutionOfOperatorOverloads() - { - await TestInRegularAndScriptAsync( + public Task InsertASingleCastToNotBreakResolutionOfOperatorOverloads() + => TestInRegularAndScriptAsync( """ using System; class C @@ -3130,12 +2694,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545561")] - public async Task InsertCastToNotBreakOverloadResolutionInUncheckedContext() - { - await TestInRegularAndScriptAsync( + public Task InsertCastToNotBreakOverloadResolutionInUncheckedContext() + => TestInRegularAndScriptAsync( """ using System; @@ -3174,12 +2736,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545564")] - public async Task InsertCastToNotBreakOverloadResolutionInUnsafeContext() - { - await TestInRegularAndScriptAsync( + public Task InsertCastToNotBreakOverloadResolutionInUnsafeContext() + => TestInRegularAndScriptAsync( """ using System; @@ -3222,12 +2782,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545783")] - public async Task InsertCastToNotBreakOverloadResolutionInNestedLambdas() - { - await TestInRegularAndScriptAsync( + public Task InsertCastToNotBreakOverloadResolutionInNestedLambdas() + => TestInRegularAndScriptAsync( """ using System; @@ -3264,12 +2822,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546069")] - public async Task TestBrokenVariableDeclarator() - { - await TestMissingInRegularAndScriptAsync( + public Task TestBrokenVariableDeclarator() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -3283,12 +2839,10 @@ static void M() } } """); - } [Fact] - public async Task TestHiddenRegion1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestHiddenRegion1() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -3302,12 +2856,10 @@ void Main() } } """); - } [Fact] - public async Task TestHiddenRegion2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestHiddenRegion2() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -3321,12 +2873,10 @@ void Main() } } """); - } [Fact] - public async Task TestHiddenRegion3() - { - await TestInRegularAndScriptAsync( + public Task TestHiddenRegion3() + => TestInRegularAndScriptAsync( """ #line default class Program @@ -3356,12 +2906,10 @@ void Main() } } """); - } [Fact] - public async Task TestHiddenRegion4() - { - await TestInRegularAndScriptAsync( + public Task TestHiddenRegion4() + => TestInRegularAndScriptAsync( """ #line default class Program @@ -3393,12 +2941,10 @@ void Main() } } """); - } [Fact] - public async Task TestHiddenRegion5() - { - await TestMissingInRegularAndScriptAsync( + public Task TestHiddenRegion5() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -3413,12 +2959,10 @@ void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530743")] - public async Task InlineFromLabeledStatement() - { - await TestInRegularAndScriptAsync( + public Task InlineFromLabeledStatement() + => TestInRegularAndScriptAsync( """ using System; @@ -3447,12 +2991,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529698")] - public async Task InlineCompoundAssignmentIntoInitializer() - { - await TestInRegularAndScriptAsync( + public Task InlineCompoundAssignmentIntoInitializer() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3479,12 +3021,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609497")] - public async Task Bugfix_609497() - { - await TestInRegularAndScriptAsync( + public Task Bugfix_609497() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3509,12 +3049,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636319")] - public async Task Bugfix_636319() - { - await TestInRegularAndScriptAsync( + public Task Bugfix_636319() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3539,12 +3077,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609492")] - public async Task Bugfix_609492() - { - await TestInRegularAndScriptAsync( + public Task Bugfix_609492() + => TestInRegularAndScriptAsync( """ using System; @@ -3569,12 +3105,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529950")] - public async Task InlineTempDoesNotInsertUnnecessaryExplicitTypeInLambdaParameter() - { - await TestInRegularAndScript1Async( + public Task InlineTempDoesNotInsertUnnecessaryExplicitTypeInLambdaParameter() + => TestInRegularAndScript1Async( """ using System; @@ -3612,12 +3146,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/619425")] - public async Task Bugfix_619425_RestrictedSimpleNameExpansion() - { - await TestInRegularAndScriptAsync( + public Task Bugfix_619425_RestrictedSimpleNameExpansion() + => TestInRegularAndScriptAsync( """ class A { @@ -3650,12 +3182,10 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529840")] - public async Task Bugfix_529840_DetectSemanticChangesAtInlineSite() - { - await TestInRegularAndScriptAsync( + public Task Bugfix_529840_DetectSemanticChangesAtInlineSite() + => TestInRegularAndScriptAsync( """ using System; @@ -3711,12 +3241,10 @@ public static explicit operator long (A x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091946")] - public async Task TestConditionalAccessWithConversion() - { - await TestInRegularAndScriptAsync( + public Task TestConditionalAccessWithConversion() + => TestInRegularAndScriptAsync( """ class A { @@ -3736,12 +3264,10 @@ bool M(string[] args) } } """); - } [Fact] - public async Task TestSimpleConditionalAccess() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleConditionalAccess() + => TestInRegularAndScriptAsync( """ class A { @@ -3761,12 +3287,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestConditionalAccessWithConditionalExpression() - { - await TestInRegularAndScriptAsync( + public Task TestConditionalAccessWithConditionalExpression() + => TestInRegularAndScriptAsync( """ class A { @@ -3786,12 +3310,10 @@ void M(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2593")] - public async Task TestConditionalAccessWithExtensionMethodInvocation() - { - await TestInRegularAndScriptAsync( + public Task TestConditionalAccessWithExtensionMethodInvocation() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -3845,12 +3367,10 @@ private object GetAssemblyIdentity(IEnumerable types) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2593")] - public async Task TestConditionalAccessWithExtensionMethodInvocation_2() - { - await TestInRegularAndScriptAsync( + public Task TestConditionalAccessWithExtensionMethodInvocation_2() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -3914,12 +3434,10 @@ private object GetAssemblyIdentity(IEnumerable types) } } """); - } [Fact] - public async Task TestAliasQualifiedNameIntoInterpolation() - { - await TestInRegularAndScriptAsync( + public Task TestAliasQualifiedNameIntoInterpolation() + => TestInRegularAndScriptAsync( """ class A { @@ -3939,12 +3457,10 @@ void M() } } """); - } [Fact] - public async Task TestConditionalExpressionIntoInterpolation() - { - await TestInRegularAndScriptAsync( + public Task TestConditionalExpressionIntoInterpolation() + => TestInRegularAndScriptAsync( """ class A { @@ -3964,12 +3480,10 @@ bool M(bool b) } } """); - } [Fact] - public async Task TestConditionalExpressionIntoInterpolationWithFormatClause() - { - await TestInRegularAndScriptAsync( + public Task TestConditionalExpressionIntoInterpolationWithFormatClause() + => TestInRegularAndScriptAsync( """ class A { @@ -3989,12 +3503,10 @@ bool M(bool b) } } """); - } [Fact] - public async Task TestInvocationExpressionIntoInterpolation() - { - await TestInRegularAndScriptAsync( + public Task TestInvocationExpressionIntoInterpolation() + => TestInRegularAndScriptAsync( """ class A { @@ -4014,12 +3526,10 @@ public static void M(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4583")] - public async Task DoNotParenthesizeInterpolatedStringWithNoInterpolation_CSharp7() - { - await TestInRegularAndScriptAsync( + public Task DoNotParenthesizeInterpolatedStringWithNoInterpolation_CSharp7() + => TestInRegularAndScriptAsync( """ class C { @@ -4039,13 +3549,11 @@ public void M() } } """, parseOptions: TestOptions.Regular7); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33108")] [WorkItem("https://github.com/dotnet/roslyn/issues/4583")] - public async Task CastInterpolatedStringWhenInliningIntoInvalidCall() - { - await TestInRegularAndScriptAsync( + public Task CastInterpolatedStringWhenInliningIntoInvalidCall() + => TestInRegularAndScriptAsync( """ class C { @@ -4065,13 +3573,11 @@ public void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33108")] [WorkItem("https://github.com/dotnet/roslyn/issues/4583")] - public async Task DoNotCastInterpolatedStringWhenInliningIntoValidCall() - { - await TestInRegularAndScriptAsync( + public Task DoNotCastInterpolatedStringWhenInliningIntoValidCall() + => TestInRegularAndScriptAsync( """ class C { @@ -4095,12 +3601,10 @@ public void M() void Replace(string s1, string s2) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4583")] - public async Task DoNotParenthesizeInterpolatedStringWithInterpolation_CSharp7() - { - await TestInRegularAndScriptAsync( + public Task DoNotParenthesizeInterpolatedStringWithInterpolation_CSharp7() + => TestInRegularAndScriptAsync( """ class C { @@ -4120,13 +3624,11 @@ public void M(int x) } } """, parseOptions: TestOptions.Regular7); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/33108")] [WorkItem("https://github.com/dotnet/roslyn/issues/4583")] - public async Task DoNotParenthesizeInterpolatedStringWithInterpolation() - { - await TestInRegularAndScriptAsync( + public Task DoNotParenthesizeInterpolatedStringWithInterpolation() + => TestInRegularAndScriptAsync( """ class C { @@ -4146,12 +3648,10 @@ public void M(int x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15530")] - public async Task PArenthesizeAwaitInlinedIntoReducedExtensionMethod() - { - await TestInRegularAndScriptAsync( + public Task PArenthesizeAwaitInlinedIntoReducedExtensionMethod() + => TestInRegularAndScriptAsync( """ using System.Linq; using System.Threading.Tasks; @@ -4177,7 +3677,6 @@ async Task M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4583")] public async Task InlineFormattableStringIntoCallSiteRequiringFormattableString() @@ -4298,9 +3797,9 @@ static void N() [Theory] [InlineData(LanguageVersion.CSharp6)] [InlineData(LanguageVersion.CSharp12)] - public async Task Tuples(LanguageVersion version) - { - var code = """ + public Task Tuples(LanguageVersion version) + => TestInRegularAndScript1Async( + """ using System; class C { @@ -4310,9 +3809,8 @@ public void M() x.ToString(); } } - """; - - var expected = """ + """, + """ using System; class C { @@ -4321,18 +3819,12 @@ public void M() (1, "hello").ToString(); } } - """; - - await TestInRegularAndScript1Async( - code, - expected, + """, new TestParameters(parseOptions: TestOptions.Regular.WithLanguageVersion(version))); - } [Fact] - public async Task TuplesWithNames() - { - var code = """ + public Task TuplesWithNames() + => TestInRegularAndScriptAsync(""" using System; class C { @@ -4342,9 +3834,7 @@ public void M() x.ToString(); } } - """; - - var expected = """ + """, """ using System; class C { @@ -4353,15 +3843,11 @@ public void M() (a: 1, b: "hello").ToString(); } } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11028")] - public async Task TuplesWithDifferentNames() - { - var code = """ + public Task TuplesWithDifferentNames() + => TestInRegularAndScriptAsync(""" class C { public void M() @@ -4370,9 +3856,7 @@ public void M() x.a.ToString(); } } - """; - - var expected = """ + """, """ class C { public void M() @@ -4380,15 +3864,11 @@ public void M() (((int a, string b))(c: 1, d: "hello")).a.ToString(); } } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task Deconstruction() - { - var code = """ + public Task Deconstruction() + => TestInRegularAndScriptAsync(""" using System; class C { @@ -4399,9 +3879,7 @@ public void M() var x3 = temp; } } - """; - - var expected = """ + """, """ using System; class C { @@ -4411,15 +3889,11 @@ public void M() var x3 = new C(); } } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/12802")] - public async Task Deconstruction2() - { - var code = """ + public Task Deconstruction2() + => TestInRegularAndScriptAsync(""" class Program { static void Main() @@ -4436,9 +3910,7 @@ public class KVP { public void Deconstruct(out T1 item1, out T2 item2) { item1 = default(T1); item2 = default(T2); } } - """; - - var expected = """ + """, """ class Program { static void Main() @@ -4454,15 +3926,11 @@ public class KVP { public void Deconstruct(out T1 item1, out T2 item2) { item1 = default(T1); item2 = default(T2); } } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11958")] - public async Task EnsureParenthesesInStringConcatenation() - { - var code = """ + public Task EnsureParenthesesInStringConcatenation() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -4471,9 +3939,7 @@ void M() string s = "a" + i; } } - """; - - var expected = """ + """, """ class C { void M() @@ -4481,15 +3947,11 @@ void M() string s = "a" + (1 + 2); } } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task ExplicitTupleNameAdded() - { - var code = """ + public Task ExplicitTupleNameAdded() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -4498,9 +3960,7 @@ void M() var t = (i, 3); } } - """; - - var expected = """ + """, """ class C { void M() @@ -4508,15 +3968,11 @@ void M() var t = (i: 1 + 2, 3); } } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task ExplicitTupleNameAdded_Trivia() - { - var code = """ + public Task ExplicitTupleNameAdded_Trivia() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -4525,9 +3981,7 @@ void M() var t = ( /*comment*/ i, 3); } } - """; - - var expected = """ + """, """ class C { void M() @@ -4535,15 +3989,11 @@ void M() var t = ( /*comment*/ i: 1 + 2, 3); } } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task ExplicitTupleNameAdded_Trivia2() - { - var code = """ + public Task ExplicitTupleNameAdded_Trivia2() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -4555,9 +4005,7 @@ void M() ); } } - """; - - var expected = """ + """, """ class C { void M() @@ -4568,15 +4016,11 @@ void M() ); } } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task ExplicitTupleNameAdded_NoDuplicateNames() - { - var code = """ + public Task ExplicitTupleNameAdded_NoDuplicateNames() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -4585,9 +4029,7 @@ void M() var t = (i, i); } } - """; - - var expected = """ + """, """ class C { void M() @@ -4595,14 +4037,11 @@ void M() var t = (1 + 2, 1 + 2); } } - """; - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19047")] - public async Task ExplicitTupleNameAdded_DeconstructionDeclaration() - { - var code = """ + public Task ExplicitTupleNameAdded_DeconstructionDeclaration() + => TestInRegularAndScriptAsync(""" class C { static int y = 1; @@ -4612,8 +4051,7 @@ void M() var t = ((i, (i, _)) = (1, (i, 3))); } } - """; - var expected = """ + """, """ class C { static int y = 1; @@ -4623,14 +4061,11 @@ void M() var t = (({|Conflict:i|}, ({|Conflict:i|}, _)) = (1, (i: C.y, 3))); } } - """; - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19047")] - public async Task ExplicitTupleNameAdded_DeconstructionDeclaration2() - { - var code = """ + public Task ExplicitTupleNameAdded_DeconstructionDeclaration2() + => TestInRegularAndScriptAsync(""" class C { static int y = 1; @@ -4640,8 +4075,7 @@ void M() var t = ((i, _) = (1, 2)); } } - """; - var expected = """ + """, """ class C { static int y = 1; @@ -4651,14 +4085,11 @@ void M() var t = (({|Conflict:i|}, _) = (1, 2)); } } - """; - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task ExplicitTupleNameAdded_NoReservedNames() - { - var code = """ + public Task ExplicitTupleNameAdded_NoReservedNames() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -4667,9 +4098,7 @@ void M() var t = (Rest, 3); } } - """; - - var expected = """ + """, """ class C { void M() @@ -4677,14 +4106,11 @@ void M() var t = (1 + 2, 3); } } - """; - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task ExplicitTupleNameAdded_NoReservedNames2() - { - var code = """ + public Task ExplicitTupleNameAdded_NoReservedNames2() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -4693,9 +4119,7 @@ void M() var t = (Item1, 3); } } - """; - - var expected = """ + """, """ class C { void M() @@ -4703,14 +4127,11 @@ void M() var t = (1 + 2, 3); } } - """; - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task ExplicitTupleNameAdded_EscapeKeywords() - { - var code = """ + public Task ExplicitTupleNameAdded_EscapeKeywords() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -4719,9 +4140,7 @@ void M() var t = (@int, 3); } } - """; - - var expected = """ + """, """ class C { void M() @@ -4729,14 +4148,11 @@ void M() var t = (@int: 1 + 2, 3); } } - """; - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task ExplicitTupleNameAdded_KeepEscapedName() - { - var code = """ + public Task ExplicitTupleNameAdded_KeepEscapedName() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -4745,9 +4161,7 @@ void M() var t = (@where, 3); } } - """; - - var expected = """ + """, """ class C { void M() @@ -4755,14 +4169,11 @@ void M() var t = (@where: 1 + 2, 3); } } - """; - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task ExplicitAnonymousTypeMemberNameAdded_DuplicateNames() - { - var code = """ + public Task ExplicitAnonymousTypeMemberNameAdded_DuplicateNames() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -4771,9 +4182,7 @@ void M() var t = new { i, i }; // error already } } - """; - - var expected = """ + """, """ class C { void M() @@ -4781,14 +4190,11 @@ void M() var t = new { i = 1 + 2, i = 1 + 2 }; // error already } } - """; - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task ExplicitAnonymousTypeMemberNameAdded_AssignmentEpression() - { - var code = """ + public Task ExplicitAnonymousTypeMemberNameAdded_AssignmentEpression() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -4798,9 +4204,7 @@ void M() var t = new { i, k = 3 }; } } - """; - - var expected = """ + """, """ class C { void M() @@ -4809,14 +4213,11 @@ void M() var t = new { i = j = 1, k = 3 }; } } - """; - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task ExplicitAnonymousTypeMemberNameAdded_Comment() - { - var code = """ + public Task ExplicitAnonymousTypeMemberNameAdded_Comment() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -4825,9 +4226,7 @@ void M() var t = new { /*comment*/ i, j = 3 }; } } - """; - - var expected = """ + """, """ class C { void M() @@ -4835,14 +4234,11 @@ void M() var t = new { /*comment*/ i = 1 + 2, j = 3 }; } } - """; - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task ExplicitAnonymousTypeMemberNameAdded_Comment2() - { - var code = """ + public Task ExplicitAnonymousTypeMemberNameAdded_Comment2() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -4854,9 +4250,7 @@ void M() }; } } - """; - - var expected = """ + """, """ class C { void M() @@ -4867,14 +4261,11 @@ void M() }; } } - """; - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19247")] - public async Task InlineTemporary_LocalFunction() - { - await TestInRegularAndScriptAsync( + public Task InlineTemporary_LocalFunction() + => TestInRegularAndScriptAsync( """ using System; class C @@ -4907,12 +4298,10 @@ void expand(string str) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11712")] - public async Task InlineTemporary_RefParams() - { - await TestInRegularAndScriptAsync( + public Task InlineTemporary_RefParams() + => TestInRegularAndScriptAsync( """ class C { @@ -4933,12 +4322,10 @@ bool M(ref T x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11712")] - public async Task InlineTemporary_OutParams() - { - await TestInRegularAndScriptAsync( + public Task InlineTemporary_OutParams() + => TestInRegularAndScriptAsync( """ class C { @@ -4959,12 +4346,10 @@ bool M(out T x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24791")] - public async Task InlineVariableDoesNotAddUnnecessaryCast() - { - await TestInRegularAndScriptAsync( + public Task InlineVariableDoesNotAddUnnecessaryCast() + => TestInRegularAndScriptAsync( """ class C { @@ -4986,12 +4371,10 @@ bool M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16819")] - public async Task InlineVariableDoesNotAddsDuplicateCast() - { - await TestInRegularAndScriptAsync( + public Task InlineVariableDoesNotAddsDuplicateCast() + => TestInRegularAndScriptAsync( """ using System; @@ -5015,12 +4398,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30903")] - public async Task InlineVariableContainsAliasOfValueTupleType() - { - await TestInRegularAndScriptAsync( + public Task InlineVariableContainsAliasOfValueTupleType() + => TestInRegularAndScriptAsync( """ using X = System.ValueTuple; @@ -5044,12 +4425,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/30903")] - public async Task InlineVariableContainsAliasOfMixedValueTupleType() - { - await TestInRegularAndScriptAsync( + public Task InlineVariableContainsAliasOfMixedValueTupleType() + => TestInRegularAndScriptAsync( """ using X = System.ValueTuple; @@ -5073,12 +4452,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35645")] - public async Task UsingDeclaration() - { - var code = """ + public Task UsingDeclaration() + => TestMissingInRegularAndScriptAsync(""" using System; class C : IDisposable { @@ -5089,15 +4466,11 @@ public void M() } public void Dispose() { } } - """; - - await TestMissingInRegularAndScriptAsync(code, new TestParameters(parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp8))); - } + """, new TestParameters(parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp8))); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task Selections1() - { - await TestFixOneAsync( + public Task Selections1() + => TestFixOneAsync( """ { [|int x = 0;|] @@ -5107,12 +4480,10 @@ await TestFixOneAsync( { Console.WriteLine(0); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task Selections2() - { - await TestFixOneAsync( + public Task Selections2() + => TestFixOneAsync( """ { int [|x = 0|], y = 1; @@ -5124,12 +4495,10 @@ await TestFixOneAsync( Console.WriteLine(0); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task Selections3() - { - await TestFixOneAsync( + public Task Selections3() + => TestFixOneAsync( """ { int x = 0, [|y = 1|], z = 2; @@ -5141,12 +4510,10 @@ await TestFixOneAsync( Console.WriteLine(1); } """); - } [Fact] - public async Task WarnOnInlineIntoConditional1() - { - await TestFixOneAsync( + public Task WarnOnInlineIntoConditional1() + => TestFixOneAsync( """ { var [|x = true|]; @@ -5156,12 +4523,10 @@ await TestFixOneAsync( { {|Warning:System.Diagnostics.Debug.Assert(true)|}; } """); - } [Fact] - public async Task WarnOnInlineIntoConditional2() - { - await TestFixOneAsync( + public Task WarnOnInlineIntoConditional2() + => TestFixOneAsync( """ { var [|x = true|]; @@ -5171,12 +4536,10 @@ await TestFixOneAsync( { {|Warning:System.Diagnostics.Debug.Assert(true == true)|}; } """); - } [Fact] - public async Task WarnOnInlineIntoMultipleConditionalLocations() - { - await TestInRegularAndScriptAsync( + public Task WarnOnInlineIntoMultipleConditionalLocations() + => TestInRegularAndScriptAsync( """ class C { @@ -5198,12 +4561,10 @@ void M() } } """); - } [Fact] - public async Task OnlyWarnOnConditionalLocations() - { - await TestInRegularAndScriptAsync( + public Task OnlyWarnOnConditionalLocations() + => TestInRegularAndScriptAsync( """ using System; @@ -5229,12 +4590,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40201")] - public async Task TestUnaryNegationOfDeclarationPattern() - { - await TestInRegularAndScriptAsync( + public Task TestUnaryNegationOfDeclarationPattern() + => TestInRegularAndScriptAsync( """ using System.Threading; @@ -5262,12 +4621,10 @@ void Test() object Helper(CancellationToken ct) { return null; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18322")] - public async Task TestInlineIntoExtensionMethodInvokedOnThis() - { - await TestInRegularAndScriptAsync( + public Task TestInlineIntoExtensionMethodInvokedOnThis() + => TestInRegularAndScriptAsync( """ public class Class1 { @@ -5291,12 +4648,10 @@ void M() public static class Class1Extensions { public static void DoStuff(this Class1 c, int x) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8716")] - public async Task DoNotQualifyInlinedLocalFunction() - { - await TestInRegularAndScriptAsync(""" + public Task DoNotQualifyInlinedLocalFunction() + => TestInRegularAndScriptAsync(""" using System; class C { @@ -5325,12 +4680,10 @@ void LocalFunc() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22540")] - public async Task DoNotQualifyWhenInliningIntoPattern_01() - { - await TestInRegularAndScriptAsync(""" + public Task DoNotQualifyWhenInliningIntoPattern_01() + => TestInRegularAndScriptAsync(""" using Syntax; namespace Syntax @@ -5371,12 +4724,10 @@ static void Bar(AwaitExpressionSyntax awaitExpression) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45661")] - public async Task DoNotQualifyWhenInliningIntoPattern_02() - { - await TestInRegularAndScriptAsync(""" + public Task DoNotQualifyWhenInliningIntoPattern_02() + => TestInRegularAndScriptAsync(""" using Syntax; namespace Syntax @@ -5417,12 +4768,10 @@ static void Bar(AwaitExpressionSyntax awaitExpression) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42835")] - public async Task WarnWhenPossibleChangeInSemanticMeaning() - { - await TestInRegularAndScriptAsync(""" + public Task WarnWhenPossibleChangeInSemanticMeaning() + => TestInRegularAndScriptAsync(""" class C { int P { get; set; } @@ -5447,12 +4796,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42835")] - public async Task WarnWhenPossibleChangeInSemanticMeaning_IgnoreParentheses() - { - await TestInRegularAndScriptAsync(""" + public Task WarnWhenPossibleChangeInSemanticMeaning_IgnoreParentheses() + => TestInRegularAndScriptAsync(""" class C { int P { get; set; } @@ -5477,12 +4824,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42835")] - public async Task WarnWhenPossibleChangeInSemanticMeaning_MethodInvocation() - { - await TestInRegularAndScriptAsync(""" + public Task WarnWhenPossibleChangeInSemanticMeaning_MethodInvocation() + => TestInRegularAndScriptAsync(""" class C { int P { get; set; } @@ -5517,12 +4862,10 @@ C M2() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42835")] - public async Task WarnWhenPossibleChangeInSemanticMeaning_MethodInvocation2() - { - await TestInRegularAndScriptAsync(""" + public Task WarnWhenPossibleChangeInSemanticMeaning_MethodInvocation2() + => TestInRegularAndScriptAsync(""" class C { int P { get; set; } @@ -5557,12 +4900,10 @@ void M2() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42835")] - public async Task WarnWhenPossibleChangeInSemanticMeaning_NestedObjectInitialization() - { - await TestInRegularAndScriptAsync(""" + public Task WarnWhenPossibleChangeInSemanticMeaning_NestedObjectInitialization() + => TestInRegularAndScriptAsync(""" class C { int P { get; set; } @@ -5587,12 +4928,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42835")] - public async Task WarnWhenPossibleChangeInSemanticMeaning_NestedMethodCall() - { - await TestInRegularAndScriptAsync(""" + public Task WarnWhenPossibleChangeInSemanticMeaning_NestedMethodCall() + => TestInRegularAndScriptAsync(""" class C { int P { get; set; } @@ -5629,12 +4968,10 @@ C M2() } } """); - } [Fact] - public async Task InlineIntoWithExpression() - { - await TestInRegularAndScriptAsync(""" + public Task InlineIntoWithExpression() + => TestInRegularAndScriptAsync(""" record Person(string Name) { void M(Person p) @@ -5667,54 +5004,34 @@ public sealed class IsExternalInit } } """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44263")] - public async Task Call_TopLevelStatement() - { - var code = """ + public Task Call_TopLevelStatement() + => TestAsync(""" using System; int [||]x = 1 + 1; x.ToString(); - """; - - var expected = """ + """, """ using System; (1 + 1).ToString(); - """; - - // Global statements in regular code are local variables, so Inline Temporary works. Script code is not - // tested because global statements in script code are field declarations, which are not considered - // temporary. - await TestAsync(code, expected, TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9)); - } + """, TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44263")] - public async Task TopLevelStatement() - { - var code = """ + public Task TopLevelStatement() + => TestAsync(""" int val = 0; int [||]val2 = val + 1; System.Console.WriteLine(val2); - """; - - var expected = """ + """, """ int val = 0; System.Console.WriteLine(val + 1); - """; - - // Global statements in regular code are local variables, so Inline Temporary works. Script code is not - // tested because global statements in script code are field declarations, which are not considered - // temporary. - await TestAsync(code, expected, TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9)); - } + """, TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44263")] - public async Task TopLevelStatement_InScope() - { - await TestAsync(""" + public Task TopLevelStatement_InScope() + => TestAsync(""" { int val = 0; int [||]val2 = val + 1; @@ -5728,12 +5045,10 @@ await TestAsync(""" } """, TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9)); - } [Fact] - public async Task TestWithLinkedFile() - { - await TestInRegularAndScript1Async( + public Task TestWithLinkedFile() + => TestInRegularAndScript1Async( """ @@ -5781,12 +5096,10 @@ public void Bar() """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50207")] - public async Task TestImplicitObjectCreation() - { - var code = """ + public Task TestImplicitObjectCreation() + => TestInRegularAndScriptAsync(""" class MyClass { void Test() @@ -5795,9 +5108,7 @@ void Test() myClass.ToString(); } } - """; - - var expected = """ + """, """ class MyClass { void Test() @@ -5805,15 +5116,11 @@ void Test() new MyClass().ToString(); } } - """; - - await TestInRegularAndScriptAsync(code, expected, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); - } + """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34143")] - public async Task TestPreserveDestinationTrivia1() - { - var code = """ + public Task TestPreserveDestinationTrivia1() + => TestInRegularAndScriptAsync(""" class MyClass { void Goo(bool b) @@ -5825,9 +5132,7 @@ void Goo(bool b) void SomeMethod(string _) { } } - """; - - var expected = """ + """, """ class MyClass { void Goo(bool b) @@ -5838,15 +5143,11 @@ void Goo(bool b) void SomeMethod(string _) { } } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/60552")] - public async Task TestNullable1() - { - var code = """ + public Task TestNullable1() + => TestInRegularAndScriptAsync(""" #nullable enable public class C @@ -5862,9 +5163,7 @@ public string M() return a; } } - """; - - var expected = """ + """, """ #nullable enable public class C @@ -5880,15 +5179,11 @@ public string M() return "" + s; } } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69869")] - public async Task InlineTemporaryNoNeededVariable() - { - await TestInRegularAndScriptAsync( + public Task InlineTemporaryNoNeededVariable() + => TestInRegularAndScriptAsync( """ using System; class A @@ -5910,12 +5205,10 @@ void M(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73148")] - public async Task InlineCollectionIntoSpread() - { - await TestInRegularAndScriptAsync( + public Task InlineCollectionIntoSpread() + => TestInRegularAndScriptAsync( """ using System; class A @@ -5948,5 +5241,4 @@ void M(string[] args) } } """); - } } diff --git a/src/Features/CSharpTest/IntroduceParameter/IntroduceParameterTests.cs b/src/Features/CSharpTest/IntroduceParameter/IntroduceParameterTests.cs index 8196aec006d9f..c56b55e290cdd 100644 --- a/src/Features/CSharpTest/IntroduceParameter/IntroduceParameterTests.cs +++ b/src/Features/CSharpTest/IntroduceParameter/IntroduceParameterTests.cs @@ -29,10 +29,8 @@ private OptionsCollection UseExpressionBody => Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement); [Fact] - public async Task TestExpressionWithNoMethodCallsCase() - { - var code = - """ + public Task TestExpressionWithNoMethodCallsCase() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -41,10 +39,7 @@ void M(int x, int y, int z) int m = [|x * y * z;|] } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -52,16 +47,11 @@ void M(int x, int y, int z, int m) { } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 0); - } + """, index: 0); [Fact] - public async Task TestExpressionCaseWithLocal() - { - var code = - """ + public Task TestExpressionCaseWithLocal() + => TestMissingInRegularAndScriptAsync(""" using System; class TestClass { @@ -71,16 +61,11 @@ void M(int x, int y, int z) int m = [|l * y * z;|] } } - """; - - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task TestBasicComplexExpressionCase() - { - var code = - """ + public Task TestBasicComplexExpressionCase() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -94,10 +79,7 @@ void M1(string y) M(y, 5, 2); } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -110,16 +92,11 @@ void M1(string y) M(y, 5, 2, y.Length * 5 * 2); } } - """; - - await TestInRegularAndScriptAsync(code, expected, 0); - } + """, 0); [Fact] - public async Task TestExpressionCaseWithSingleMethodCall() - { - var code = - """ + public Task TestExpressionCaseWithSingleMethodCall() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -133,10 +110,7 @@ void M1(int x, int y, int z) M(z, x, z); } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -149,16 +123,11 @@ void M1(int x, int y, int z) M(z, x, z, z * z * z); } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 0); - } + """, index: 0); [Fact] - public async Task TestLocalDeclarationMultipleDeclarators() - { - var code = - """ + public Task TestLocalDeclarationMultipleDeclarators() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -172,10 +141,7 @@ void M1(int x, int y, int z) M(z, x, z); } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -189,16 +155,11 @@ void M1(int x, int y, int z) M(z, x, z, z * z * z); } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 0); - } + """, index: 0); [Fact] - public async Task TestDeclarationInForLoop() - { - var code = - """ + public Task TestDeclarationInForLoop() + => TestMissingAsync(""" using System; class TestClass { @@ -210,16 +171,11 @@ void M(int a, int b) }; } } - """; - - await TestMissingAsync(code); - } + """); [Fact] - public async Task TestExpressionCaseWithSingleMethodCallInLocalFunction() - { - var code = - """ + public Task TestExpressionCaseWithSingleMethodCallInLocalFunction() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -234,10 +190,7 @@ int M2(int x, int y) } } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -251,16 +204,11 @@ int M2(int x, int y, int val) } } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 0); - } + """, index: 0); [Fact] - public async Task TestExpressionCaseWithSingleMethodCallInStaticLocalFunction() - { - var code = - """ + public Task TestExpressionCaseWithSingleMethodCallInStaticLocalFunction() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -275,10 +223,7 @@ static int M2(int x, int y) } } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -292,16 +237,11 @@ static int M2(int x, int y, int val) } } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 0); - } + """, index: 0); [Fact] - public async Task TestHighlightIncompleteExpressionCaseWithSingleMethodCall() - { - var code = - """ + public Task TestHighlightIncompleteExpressionCaseWithSingleMethodCall() + => TestMissingInRegularAndScriptAsync(""" using System; class TestClass { @@ -315,16 +255,11 @@ void M1(int x, int y, int z) M(z, y, x); } } - """; - - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task TestExpressionCaseWithMultipleMethodCall() - { - var code = - """ + public Task TestExpressionCaseWithMultipleMethodCall() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -339,10 +274,7 @@ void M1(int x, int y, int z) M(z, y, x); } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -356,16 +288,11 @@ void M1(int x, int y, int z) M(z, y, x, z * y * x); } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 0); - } + """, index: 0); [Fact] - public async Task TestExpressionAllOccurrences() - { - var code = - """ + public Task TestExpressionAllOccurrences() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -380,10 +307,7 @@ void M1(int x, int y, int z) M(a + b, 5, x); } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -397,16 +321,11 @@ void M1(int x, int y, int z) M(a + b, 5, x, (a + b) * 5 * x); } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 3); - } + """, index: 3); [Fact] - public async Task TestxpressionWithNoMethodCallTrampoline() - { - var code = - """ + public Task TestxpressionWithNoMethodCallTrampoline() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -415,10 +334,7 @@ void M(int x, int y, int z) int m = [|x * y * z;|] } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -431,16 +347,11 @@ void M(int x, int y, int z, int m) { } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); - } + """, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); [Fact] - public async Task TestExpressionWithSingleMethodCallTrampoline() - { - var code = - """ + public Task TestExpressionWithSingleMethodCallTrampoline() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -454,10 +365,7 @@ void M1(int x, int y, int z) M(z, y, x); } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -475,16 +383,11 @@ void M1(int x, int y, int z) M(z, y, x, GetM(z, y)); } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); - } + """, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); [Fact] - public async Task TestExpressionWithSingleMethodCallAndAccessorsTrampoline() - { - var code = - """ + public Task TestExpressionWithSingleMethodCallAndAccessorsTrampoline() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -498,10 +401,7 @@ void M1(int x, int y, int z) this.M(z, y, x); } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -519,16 +419,11 @@ void M1(int x, int y, int z) this.M(z, y, x, GetM(z, y)); } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); - } + """, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); [Fact] - public async Task TestExpressionWithSingleMethodCallAndAccessorsConditionalTrampoline() - { - var code = - """ + public Task TestExpressionWithSingleMethodCallAndAccessorsConditionalTrampoline() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -542,10 +437,7 @@ void M1(int x, int y, int z) this?.M(z, y, x); } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -563,16 +455,11 @@ void M1(int x, int y, int z) this?.M(z, y, x, this?.GetM(z, y)); } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); - } + """, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); [Fact] - public async Task TestExpressionWithSingleMethodCallMultipleAccessorsTrampoline() - { - var code = - """ + public Task TestExpressionWithSingleMethodCallMultipleAccessorsTrampoline() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -595,10 +482,7 @@ public int ComputeAge(int x, int y) return age; } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -625,16 +509,11 @@ public int ComputeAge(int x, int y, int age) return age; } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); - } + """, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); [Fact] - public async Task TestExpressionWithSingleMethodCallMultipleAccessorsConditionalTrampoline() - { - var code = - """ + public Task TestExpressionWithSingleMethodCallMultipleAccessorsConditionalTrampoline() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -657,10 +536,7 @@ public int ComputeAge(int x, int y) return age; } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -687,16 +563,11 @@ public int ComputeAge(int x, int y, int age) return age; } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); - } + """, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); [Fact] - public async Task TestExpressionWithSingleMethodCallAccessorsMixedConditionalTrampoline() - { - var code = - """ + public Task TestExpressionWithSingleMethodCallAccessorsMixedConditionalTrampoline() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -719,10 +590,7 @@ public int ComputeAge(int x, int y) return age; } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -749,16 +617,11 @@ public int ComputeAge(int x, int y, int age) return age; } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); - } + """, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); [Fact] - public async Task TestExpressionWithSingleMethodCallTrampolineAllOccurrences() - { - var code = - """ + public Task TestExpressionWithSingleMethodCallTrampolineAllOccurrences() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -773,10 +636,7 @@ void M1(int x, int y, int z) M(z, y, x); } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -795,15 +655,11 @@ void M1(int x, int y, int z) M(z, y, x, GetM(z, y, x)); } } - """; - await TestInRegularAndScriptAsync(code, expected, index: 4, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); - } + """, index: 4, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); [Fact] - public async Task TestExpressionWithNoMethodCallOverload() - { - var code = - """ + public Task TestExpressionWithNoMethodCallOverload() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -812,10 +668,7 @@ void M(int x, int y, int z) int m = [|x * y * z;|] } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -828,16 +681,11 @@ void M(int x, int y, int z, int m) { } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 2, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); - } + """, index: 2, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); [Fact] - public async Task TestExpressionWithSingleMethodCallOverload() - { - var code = - """ + public Task TestExpressionWithSingleMethodCallOverload() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -851,10 +699,7 @@ void M1(int x, int y, int z) M(z, y, x); } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -872,15 +717,11 @@ void M1(int x, int y, int z) M(z, y, x); } } - """; - await TestInRegularAndScriptAsync(code, expected, index: 2, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); - } + """, index: 2, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); [Fact] - public async Task TestExpressionBodiedMemberOverload() - { - var code = - """ + public Task TestExpressionBodiedMemberOverload() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -891,10 +732,7 @@ void M1(int x, int y, int z) int prod = M(z, y, x); } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -906,16 +744,11 @@ void M1(int x, int y, int z) int prod = M(z, y, x); } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 2, options: UseExpressionBody, parseOptions: CSharpParseOptions.Default); - } + """, index: 2, options: UseExpressionBody, parseOptions: CSharpParseOptions.Default); [Fact] - public async Task TestExpressionBodiedMemberTrampoline() - { - var code = - """ + public Task TestExpressionBodiedMemberTrampoline() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -926,10 +759,7 @@ void M1(int x, int y, int z) int prod = M(z, y, x); } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -945,16 +775,11 @@ void M1(int x, int y, int z) int prod = M(z, y, x, GetV(z, y, x)); } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); - } + """, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); [Fact] - public async Task TestExpressionCaseWithRecursiveCall() - { - var code = - """ + public Task TestExpressionCaseWithRecursiveCall() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -964,10 +789,7 @@ int M(int x, int y, int z) return M(x, x, z); } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -976,15 +798,11 @@ int M(int x, int y, int z, int m) return M(x, x, z, x * x * z); } } - """; - await TestInRegularAndScriptAsync(code, expected, index: 0); - } + """, index: 0); [Fact] - public async Task TestExpressionCaseWithNestedRecursiveCall() - { - var code = - """ + public Task TestExpressionCaseWithNestedRecursiveCall() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -994,10 +812,7 @@ int M(int x, int y, int z) return M(x, x, M(x, y, z)); } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -1006,15 +821,11 @@ int M(int x, int y, int z, int m) return M(x, x, M(x, y, z, x * y * z), x * x * M(x, y, z, x * y * z)); } } - """; - await TestInRegularAndScriptAsync(code, expected, index: 0); - } + """, index: 0); [Fact] - public async Task TestExpressionCaseWithParamsArg() - { - var code = - """ + public Task TestExpressionCaseWithParamsArg() + => TestMissingInRegularAndScriptAsync(""" using System; class TestClass { @@ -1029,15 +840,11 @@ void M1() M(5, 6, 7); } } - """; - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task TestExpressionCaseWithOptionalParameters() - { - var code = - """ + public Task TestExpressionCaseWithOptionalParameters() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -1052,10 +859,7 @@ void M1() M(5, 3); } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -1069,15 +873,11 @@ void M1() M(5, 5 * 3, 3); } } - """; - await TestInRegularAndScriptAsync(code, expected, index: 0); - } + """, index: 0); [Fact] - public async Task TestExpressionCaseWithOptionalParametersUsed() - { - var code = - """ + public Task TestExpressionCaseWithOptionalParametersUsed() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -1092,10 +892,7 @@ void M1() M(7); } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -1109,15 +906,11 @@ void M1() M(7, 7 * 5); } } - """; - await TestInRegularAndScriptAsync(code, expected, index: 0); - } + """, index: 0); [Fact] - public async Task TestExpressionCaseWithOptionalParametersUsedOverload() - { - var code = - """ + public Task TestExpressionCaseWithOptionalParametersUsedOverload() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -1132,10 +925,7 @@ void M1() M(7); } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -1154,15 +944,11 @@ void M1() M(7); } } - """; - await TestInRegularAndScriptAsync(code, expected, index: 2); - } + """, index: 2); [Fact] - public async Task TestExpressionCaseWithOptionalParametersUsedTrampoline() - { - var code = - """ + public Task TestExpressionCaseWithOptionalParametersUsedTrampoline() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -1177,10 +963,7 @@ void M1() M(7); } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -1199,15 +982,11 @@ void M1() M(7, GetM(7)); } } - """; - await TestInRegularAndScriptAsync(code, expected, index: 1); - } + """, index: 1); [Fact] - public async Task TestExpressionCaseWithOptionalParametersUnusedTrampoline() - { - var code = - """ + public Task TestExpressionCaseWithOptionalParametersUnusedTrampoline() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -1222,10 +1001,7 @@ void M1() M(7, 2); } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -1244,15 +1020,11 @@ void M1() M(7, GetM(7, 2), 2); } } - """; - await TestInRegularAndScriptAsync(code, expected, index: 1); - } + """, index: 1); [Fact] - public async Task TestExpressionCaseWithCancellationToken() - { - var code = - """ + public Task TestExpressionCaseWithCancellationToken() + => TestInRegularAndScriptAsync(""" using System; using System.Threading; class TestClass @@ -1268,10 +1040,7 @@ void M1(CancellationToken cancellationToken) M(7, cancellationToken); } } - """; - - var expected = - """ + """, """ using System; using System.Threading; class TestClass @@ -1286,15 +1055,11 @@ void M1(CancellationToken cancellationToken) M(7, 7 * 7, cancellationToken); } } - """; - await TestInRegularAndScriptAsync(code, expected, index: 0); - } + """, index: 0); [Fact] - public async Task TestExpressionCaseWithRecursiveCallTrampoline() - { - var code = - """ + public Task TestExpressionCaseWithRecursiveCallTrampoline() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -1304,10 +1069,7 @@ int M(int x, int y, int z) return M(x, x, z); } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -1321,15 +1083,11 @@ int M(int x, int y, int z, int m) return M(x, x, z, GetM(x, x, z)); } } - """; - await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); - } + """, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); [Fact] - public async Task TestExpressionCaseWithNestedRecursiveCallTrampoline() - { - var code = - """ + public Task TestExpressionCaseWithNestedRecursiveCallTrampoline() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -1339,10 +1097,7 @@ int M(int x, int y, int z) return M(x, x, M(x, y, x)); } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -1356,15 +1111,11 @@ int M(int x, int y, int z, int m) return M(x, x, M(x, y, x, GetM(x, y, x)), GetM(x, x, M(x, y, x, GetM(x, y, x)))); } } - """; - await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); - } + """, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default); [Fact] - public async Task TestExpressionCaseInConstructor() - { - var code = - """ + public Task TestExpressionCaseInConstructor() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -1378,9 +1129,7 @@ void TestMethod() var test = new TestClass(5, 6); } } - """; - var expected = - """ + """, """ using System; class TestClass { @@ -1394,87 +1143,58 @@ void TestMethod() var test = new TestClass(5, 6, 5 + 6); } } - """; - - await TestInRegularAndScriptAsync(code, expected, 0); - } + """, 0); [Fact] - public async Task TestLambdaCaseNormal() - { - var code = - """ + public Task TestLambdaCaseNormal() + => TestMissingInRegularAndScriptAsync(""" using System; class TestClass { Func mult = (x, y) => [|x * y|]; } - """; - - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task TestLambdaCaseTrampoline() - { - var code = - """ + public Task TestLambdaCaseTrampoline() + => TestMissingInRegularAndScriptAsync(""" using System; class TestClass { Func mult = (x, y) => [|x * y|]; } - """; - - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task TestLambdaCaseOverload() - { - var code = - """ + public Task TestLambdaCaseOverload() + => TestMissingInRegularAndScriptAsync(""" using System; class TestClass { Func mult = (x, y) => [|x * y|]; } - """; - - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task TestTopLevelStatements() - { - var code = - """ + public Task TestTopLevelStatements() + => TestMissingInRegularAndScriptAsync(""" using System; Math.Max(5 + 5, [|6 + 7|]); - """; - - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task TestFieldInitializer() - { - var code = - """ + public Task TestFieldInitializer() + => TestMissingInRegularAndScriptAsync(""" using System; class TestClass { int a = [|5 + 3|]; } - """; - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task TestIndexer() - { - var code = - """ + public Task TestIndexer() + => TestMissingInRegularAndScriptAsync(""" using System; class SampleCollection { @@ -1482,15 +1202,11 @@ class SampleCollection public T this[int i] => arr[[|i + 5|]]; } - """; - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task TestPropertyGetter() - { - var code = - """ + public Task TestPropertyGetter() + => TestMissingInRegularAndScriptAsync(""" using System; class TimePeriod @@ -1502,15 +1218,11 @@ public double Hours get { return [|_seconds / 3600|]; } } } - """; - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task TestPropertySetter() - { - var code = - """ + public Task TestPropertySetter() + => TestMissingInRegularAndScriptAsync(""" using System; class TimePeriod @@ -1524,15 +1236,11 @@ public double Hours } } } - """; - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task TestDestructor() - { - var code = - """ + public Task TestDestructor() + => TestMissingInRegularAndScriptAsync(""" using System; class TestClass { @@ -1541,15 +1249,11 @@ class TestClass Math.Max([|5 + 5|], 5 * 5); } } - """; - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task TestExpressionInParameter() - { - var code = - """ + public Task TestExpressionInParameter() + => TestMissingInRegularAndScriptAsync(""" using System; class TestClass { @@ -1557,15 +1261,11 @@ public void M(int x = [|5 * 5|]) { } } - """; - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task TestCrossLanguageInvocations() - { - var code = - """ + public Task TestCrossLanguageInvocations() + => TestInRegularAndScriptAsync(""" @@ -1599,10 +1299,7 @@ End Class - """; - - var expected = - """ + """, """ @@ -1635,15 +1332,11 @@ End Class - """; - await TestInRegularAndScriptAsync(code, expected, 0); - } + """, 0); [Fact] - public async Task TestConvertedTypeInExpression() - { - var code = - """ + public Task TestConvertedTypeInExpression() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -1652,10 +1345,7 @@ void M(double x, double y) int m = [|(int)(x * y);|] } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -1663,16 +1353,11 @@ void M(double x, double y, int m) { } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 0); - } + """, index: 0); [Fact] - public async Task TestConvertedTypeInExpressionTrampoline() - { - var code = - """ + public Task TestConvertedTypeInExpressionTrampoline() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -1681,10 +1366,7 @@ void M(double x, double y) int m = [|(int)(x * y);|] } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -1697,16 +1379,11 @@ void M(double x, double y, int m) { } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1); - } + """, index: 1); [Fact] - public async Task TestThisKeywordInExpression() - { - var code = - """ + public Task TestThisKeywordInExpression() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -1721,10 +1398,7 @@ public int M(int x, int y) return m; } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -1743,16 +1417,11 @@ public int M(int x, int y, int m) return m; } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 0); - } + """, index: 0); [Fact] - public async Task TestThisImplicitInExpression() - { - var code = - """ + public Task TestThisImplicitInExpression() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -1767,10 +1436,7 @@ public int M(int x, int y) return m; } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -1789,16 +1455,11 @@ public int M(int x, int y, int m) return m; } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 0); - } + """, index: 0); [Fact] - public async Task TestStaticMethodCallInExpression() - { - var code = - """ + public Task TestStaticMethodCallInExpression() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -1813,10 +1474,7 @@ public int M(int x, int y) return m; } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -1830,16 +1488,11 @@ public int M(int x, int y, int m) return m; } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 0); - } + """, index: 0); [Fact] - public async Task TestBaseKeywordInExpression() - { - var code = - """ + public Task TestBaseKeywordInExpression() + => TestInRegularAndScriptAsync(""" using System; class Net { @@ -1855,10 +1508,7 @@ public void Write() int x = [|base._value + 1;|] } } - """; - - var expected = - """ + """, """ using System; class Net { @@ -1878,16 +1528,11 @@ public void Write(int x) { } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 0); - } + """, index: 0); [Fact] - public async Task TestFieldReferenceInOptionalParameter() - { - var code = - """ + public Task TestFieldReferenceInOptionalParameter() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -1902,10 +1547,7 @@ void M1() M(7); } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -1919,15 +1561,11 @@ void M1() M(7, 7 * int.MaxValue); } } - """; - await TestInRegularAndScriptAsync(code, expected, index: 0); - } + """, index: 0); [Fact] - public async Task TestNamedParameterNecessary() - { - var code = - """ + public Task TestNamedParameterNecessary() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -1942,10 +1580,7 @@ void M1() M(z: 0, y: 2); } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -1959,15 +1594,11 @@ void M1() M(z: 0, m: 0 * 2, y: 2); } } - """; - await TestInRegularAndScriptAsync(code, expected, index: 0); - } + """, index: 0); [Fact] - public async Task TestHighlightReturnType() - { - var code = - """ + public Task TestHighlightReturnType() + => TestMissingInRegularAndScriptAsync(""" using System; class TestClass { @@ -1981,15 +1612,11 @@ void M1() M(5); } } - """; - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task TestTypeOfOnString() - { - var code = - """ + public Task TestTypeOfOnString() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -1998,10 +1625,7 @@ void M() var x = [|typeof(string);|] } } - """; - - var expected = - """ + """, """ using System; class TestClass { @@ -2009,16 +1633,11 @@ void M(Type x) { } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 0); - } + """, index: 0); [Fact] - public async Task TestClassObject() - { - var code = - """ + public Task TestClassObject() + => TestMissingInRegularAndScriptAsync(""" class F { public int x; @@ -2043,16 +1662,11 @@ void M() N(new F(1, 2)); } } - """; - - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task TestReferenceInDifferentDocumentWithUsings() - { - var code = - """ + public Task TestReferenceInDifferentDocumentWithUsings() + => TestInRegularAndScriptAsync(""" @@ -2087,10 +1701,7 @@ public Program(int x) - """; - - var expected = - """ + """, """ @@ -2124,15 +1735,11 @@ public Program(int x) - """; - await TestInRegularAndScriptAsync(code, expected, 0); - } + """, 0); [Fact] - public async Task TestIntroduceParameterOnParameter() - { - var code = - """ + public Task TestIntroduceParameterOnParameter() + => TestMissingInRegularAndScriptAsync(""" using System; class Program @@ -2142,16 +1749,11 @@ public static void Main(string[] args) Console.WriteLine([|args|]); } } - """; - - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task TestIntroduceParameterOnExpressionContainingParameter() - { - var code = - """ + public Task TestIntroduceParameterOnExpressionContainingParameter() + => TestInRegularAndScriptAsync(""" public class C { public void M(string s) @@ -2164,10 +1766,7 @@ void localFunction() } } } - """; - - var expected = - """ + """, """ public class C { public void M(string s) @@ -2180,34 +1779,21 @@ void localFunction(string s) } } } - """; - - await TestInRegularAndScriptAsync(code, expected, 0); - } + """, 0); [Fact] - public async Task TestIntroduceParameterOnOverload() - { - var code = - """ + public Task TestIntroduceParameterOnOverload() + => TestInRegularAndScriptAsync(""" M(); int M(int _) => M([|1234|]); - """; - - var expected = - """ + """, """ M(); int M(int _, int v) => M({|Rename:v|}, 1234); - """; - - await TestInRegularAndScriptAsync(code, expected, 0); - } + """, 0); [Fact] - public async Task TestIntroduceParameterOnAttributeArgument() - { - var code = - """ + public Task TestIntroduceParameterOnAttributeArgument() + => TestMissingInRegularAndScriptAsync(""" public class C { [Theory] @@ -2216,8 +1802,20 @@ public void Test(string s) { } } - """; + """); + + [Fact] + public Task TestNotOnNamedType1() + => TestMissingInRegularAndScriptAsync( + """ + using System; - await TestMissingInRegularAndScriptAsync(code); - } + class C + { + void M() + { + [||]Console.WriteLine(); + } + } + """); } diff --git a/src/Features/CSharpTest/IntroduceUsingStatement/IntroduceUsingStatementTests.cs b/src/Features/CSharpTest/IntroduceUsingStatement/IntroduceUsingStatementTests.cs index 880df2377d19f..3f2c43f0ef2e6 100644 --- a/src/Features/CSharpTest/IntroduceUsingStatement/IntroduceUsingStatementTests.cs +++ b/src/Features/CSharpTest/IntroduceUsingStatement/IntroduceUsingStatementTests.cs @@ -53,9 +53,8 @@ private Task TestAsync( [InlineData("var name = disposable[||];")] [InlineData("var name = disposable;[||]")] [InlineData("var name = disposable[||]")] - public async Task RefactoringIsAvailableForSelection(string declaration) - { - await TestAsync( + public Task RefactoringIsAvailableForSelection(string declaration) + => TestAsync( """ class C { @@ -76,12 +75,10 @@ void M(System.IDisposable disposable) } } """); - } [Fact] - public async Task RefactoringIsAvailableForVerticalSelection() - { - await TestAsync( + public Task RefactoringIsAvailableForVerticalSelection() + => TestAsync( """ class C { @@ -103,12 +100,10 @@ void M(System.IDisposable disposable) } } """); - } [Fact] - public async Task RefactoringIsAvailableForSelectionAtStartOfStatementWithPrecedingDeclaration() - { - await TestAsync( + public Task RefactoringIsAvailableForSelectionAtStartOfStatementWithPrecedingDeclaration() + => TestAsync( """ class C { @@ -131,12 +126,10 @@ void M(System.IDisposable disposable) } } """); - } [Fact] - public async Task RefactoringIsAvailableForSelectionAtStartOfLineWithPrecedingDeclaration() - { - await TestAsync( + public Task RefactoringIsAvailableForSelectionAtStartOfLineWithPrecedingDeclaration() + => TestAsync( """ class C { @@ -159,12 +152,10 @@ void M(System.IDisposable disposable) } } """); - } [Fact] - public async Task RefactoringIsAvailableForSelectionAtEndOfStatementWithFollowingDeclaration() - { - await TestAsync( + public Task RefactoringIsAvailableForSelectionAtEndOfStatementWithFollowingDeclaration() + => TestAsync( """ class C { @@ -188,12 +179,10 @@ void M(System.IDisposable disposable) } } """); - } [Fact] - public async Task RefactoringIsAvailableForSelectionAtEndOfLineWithFollowingDeclaration() - { - await TestAsync( + public Task RefactoringIsAvailableForSelectionAtEndOfLineWithFollowingDeclaration() + => TestAsync( """ class C { @@ -217,15 +206,13 @@ void M(System.IDisposable disposable) } } """); - } [Theory] [InlineData("var name = d[||]isposable;")] [InlineData("var name = disposabl[||]e;")] [InlineData("var name=[|disposable|];")] - public async Task RefactoringIsNotAvailableForSelection(string declaration) - { - await TestMissingInRegularAndScriptAsync( + public Task RefactoringIsNotAvailableForSelection(string declaration) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -235,12 +222,10 @@ void M(System.IDisposable disposable) } } """); - } [Fact] - public async Task RefactoringIsNotAvailableForDeclarationMissingInitializerExpression() - { - await TestMissingInRegularAndScriptAsync( + public Task RefactoringIsNotAvailableForDeclarationMissingInitializerExpression() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -250,12 +235,10 @@ void M(System.IDisposable disposable) } } """); - } [Fact] - public async Task RefactoringIsNotAvailableForUsingStatementDeclaration() - { - await TestMissingInRegularAndScriptAsync( + public Task RefactoringIsNotAvailableForUsingStatementDeclaration() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -267,16 +250,14 @@ void M(System.IDisposable 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( + public Task RefactoringIsNotAvailableForMultiVariableDeclaration(string declaration) + => TestMissingInRegularAndScriptAsync( """ class C { @@ -286,12 +267,10 @@ void M(System.IDisposable disposable) } } """); - } [Fact] - public async Task RefactoringIsAvailableForConstrainedGenericTypeParameter() - { - await TestAsync( + public Task RefactoringIsAvailableForConstrainedGenericTypeParameter() + => TestAsync( """ class C where T : System.IDisposable { @@ -312,12 +291,10 @@ void M(T disposable) } } """); - } [Fact] - public async Task RefactoringIsNotAvailableForUnconstrainedGenericTypeParameter() - { - await TestMissingAsync( + public Task RefactoringIsNotAvailableForUnconstrainedGenericTypeParameter() + => TestMissingAsync( """ class C { @@ -327,12 +304,10 @@ void M(T disposable) } } """); - } [Fact] - public async Task LeadingCommentTriviaIsPlacedOnUsingStatement() - { - await TestAsync( + public Task LeadingCommentTriviaIsPlacedOnUsingStatement() + => TestAsync( """ class C { @@ -355,12 +330,10 @@ void M(System.IDisposable disposable) } } """); - } [Fact] - public async Task CommentOnTheSameLineStaysOnTheSameLine() - { - await TestAsync( + public Task CommentOnTheSameLineStaysOnTheSameLine() + => TestAsync( """ class C { @@ -381,12 +354,10 @@ void M(System.IDisposable disposable) } } """); - } [Fact] - public async Task TrailingCommentTriviaOnNextLineGoesAfterBlock() - { - await TestAsync( + public Task TrailingCommentTriviaOnNextLineGoesAfterBlock() + => TestAsync( """ class C { @@ -409,12 +380,10 @@ void M(System.IDisposable disposable) } } """); - } [Fact] - public async Task ValidPreprocessorStaysValid() - { - await TestAsync( + public Task ValidPreprocessorStaysValid() + => TestAsync( """ class C { @@ -439,12 +408,10 @@ void M(System.IDisposable disposable) } } """); - } [Fact] - public async Task InvalidPreprocessorStaysInvalid() - { - await TestAsync( + public Task InvalidPreprocessorStaysInvalid() + => TestAsync( """ class C { @@ -471,12 +438,10 @@ void M(System.IDisposable disposable) } } """); - } [Fact] - public async Task InvalidPreprocessorStaysInvalid_CSharp8() - { - await TestAsync( + public Task InvalidPreprocessorStaysInvalid_CSharp8() + => TestAsync( """ class C { @@ -501,12 +466,10 @@ void M(System.IDisposable disposable) } } """, LanguageVersion.CSharp8); - } [Fact] - public async Task StatementsAreSurroundedByMinimalScope() - { - await TestAsync( + public Task StatementsAreSurroundedByMinimalScope() + => TestAsync( """ class C { @@ -536,12 +499,10 @@ void M(System.IDisposable disposable) } } """); - } [Fact] - public async Task CommentsAreSurroundedExceptLinesFollowingLastUsage() - { - await TestAsync( + public Task CommentsAreSurroundedExceptLinesFollowingLastUsage() + => TestAsync( """ class C { @@ -568,12 +529,10 @@ void M(System.IDisposable disposable) } } """); - } [Fact] - public async Task WorksInSwitchSections() - { - await TestAsync( + public Task WorksInSwitchSections() + => TestAsync( """ class C { @@ -607,12 +566,10 @@ void M(System.IDisposable disposable) } } """); - } [Fact] - public async Task WorksOnStatementWithInvalidEmbeddingInIf() - { - await TestAsync( + public Task WorksOnStatementWithInvalidEmbeddingInIf() + => TestAsync( """ class C { @@ -635,12 +592,10 @@ void M(System.IDisposable disposable) } } """); - } [Fact] - public async Task RefactoringIsNotAvailableOnStatementWithInvalidEmbeddingInLambda() - { - await TestMissingInRegularAndScriptAsync( + public Task RefactoringIsNotAvailableOnStatementWithInvalidEmbeddingInLambda() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -650,12 +605,10 @@ void M(System.IDisposable disposable) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35237")] - public async Task ExpandsToIncludeSurroundedVariableDeclarations() - { - await TestAsync( + public Task ExpandsToIncludeSurroundedVariableDeclarations() + => TestAsync( """ using System.IO; @@ -687,12 +640,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35237")] - public async Task ExpandsToIncludeSurroundedOutVariableDeclarations() - { - await TestAsync( + public Task ExpandsToIncludeSurroundedOutVariableDeclarations() + => TestAsync( """ using System.IO; @@ -734,12 +685,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35237")] - public async Task ExpandsToIncludeSurroundedPatternVariableDeclarations() - { - await TestAsync( + public Task ExpandsToIncludeSurroundedPatternVariableDeclarations() + => TestAsync( """ using System.IO; @@ -781,12 +730,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35237")] - public async Task ExpandsToIncludeSurroundedMultiVariableDeclarations() - { - await TestAsync( + public Task ExpandsToIncludeSurroundedMultiVariableDeclarations() + => TestAsync( """ using System.IO; @@ -820,12 +767,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43001")] - public async Task ConsumeFollowingTryStatement1() - { - await TestAsync( + public Task ConsumeFollowingTryStatement1() + => TestAsync( """ using System.IO; @@ -865,12 +810,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43001")] - public async Task ConsumeFollowingTryStatement2() - { - await TestAsync( + public Task ConsumeFollowingTryStatement2() + => TestAsync( """ using System; using System.IO; @@ -925,12 +868,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43001")] - public async Task ConsumeFollowingTryStatement3() - { - await TestAsync( + public Task ConsumeFollowingTryStatement3() + => TestAsync( """ using System; using System.IO; @@ -977,12 +918,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43001")] - public async Task ConsumeFollowingTryStatement4() - { - await TestAsync( + public Task ConsumeFollowingTryStatement4() + => TestAsync( """ using System; using System.IO; @@ -1031,12 +970,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43001")] - public async Task ConsumeFollowingTryStatement5() - { - await TestAsync( + public Task ConsumeFollowingTryStatement5() + => TestAsync( """ using System; using System.IO; @@ -1085,12 +1022,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43001")] - public async Task ConsumeFollowingTryStatement6() - { - await TestAsync( + public Task ConsumeFollowingTryStatement6() + => TestAsync( """ using System; using System.IO; @@ -1139,12 +1074,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43001")] - public async Task ConsumeFollowingTryStatement7() - { - await TestAsync( + public Task ConsumeFollowingTryStatement7() + => TestAsync( """ using System; using System.IO; @@ -1193,12 +1126,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43001")] - public async Task ConsumeFollowingTryStatement8() - { - await TestAsync( + public Task ConsumeFollowingTryStatement8() + => TestAsync( """ using System; using System.IO; @@ -1247,12 +1178,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33699")] - public async Task StatementsAreSurroundedByMinimalScope1_CSharp8() - { - await TestAsync( + public Task StatementsAreSurroundedByMinimalScope1_CSharp8() + => TestAsync( """ class C { @@ -1282,12 +1211,10 @@ void M(System.IDisposable disposable) } } """, LanguageVersion.CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33699")] - public async Task StatementsAreSurroundedByMinimalScope2_CSharp8() - { - await TestAsync( + public Task StatementsAreSurroundedByMinimalScope2_CSharp8() + => TestAsync( """ class C { @@ -1312,12 +1239,10 @@ void M(System.IDisposable disposable) } } """, LanguageVersion.CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33699")] - public async Task StatementsAreSurroundedByMinimalScope3_CSharp8() - { - await TestAsync( + public Task StatementsAreSurroundedByMinimalScope3_CSharp8() + => TestAsync( """ class C { @@ -1344,12 +1269,10 @@ void M(System.IDisposable disposable) } } """, LanguageVersion.CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33699")] - public async Task StatementsAreSurroundedByMinimalScope4_CSharp8() - { - await TestAsync( + public Task StatementsAreSurroundedByMinimalScope4_CSharp8() + => TestAsync( """ class C { @@ -1388,12 +1311,10 @@ void M(System.IDisposable disposable) } } """, LanguageVersion.CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33699")] - public async Task StatementsAreSurroundedByMinimalScope5_CSharp8() - { - await TestAsync( + public Task StatementsAreSurroundedByMinimalScope5_CSharp8() + => TestAsync( """ class C { @@ -1434,12 +1355,10 @@ void M(System.IDisposable disposable) } } """, LanguageVersion.CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37260")] - public async Task TestExpressionStatement() - { - await TestAsync( + public Task TestExpressionStatement() + => TestAsync( """ using System; @@ -1470,12 +1389,10 @@ void M() IDisposable MethodThatReturnsDisposableThing() => null; } """, options: DoNotPreferSimpleUsingStatement); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37260")] - public async Task TestExpressionStatement_PreferSimpleUsingStatement1() - { - await TestAsync( + public Task TestExpressionStatement_PreferSimpleUsingStatement1() + => TestAsync( """ using System; @@ -1504,12 +1421,10 @@ void M() IDisposable MethodThatReturnsDisposableThing() => null; } """, options: PreferSimpleUsingStatement); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37260")] - public async Task TestExpressionStatement_PreferSimpleUsingStatement2() - { - await TestAsync( + public Task TestExpressionStatement_PreferSimpleUsingStatement2() + => TestAsync( """ using System; @@ -1540,5 +1455,4 @@ void M() IDisposable MethodThatReturnsDisposableThing() => null; } """, options: PreferSimpleUsingStatement); - } } diff --git a/src/Features/CSharpTest/IntroduceVariable/InteractiveIntroduceVariableTests.cs b/src/Features/CSharpTest/IntroduceVariable/InteractiveIntroduceVariableTests.cs index 300feb3e6307e..0c74a73db3bbf 100644 --- a/src/Features/CSharpTest/IntroduceVariable/InteractiveIntroduceVariableTests.cs +++ b/src/Features/CSharpTest/IntroduceVariable/InteractiveIntroduceVariableTests.cs @@ -27,190 +27,190 @@ protected Task TestAsync(string initial, string expected, int index = 0) => TestAsync(initial, expected, TestOptions.Script, null, index); [Fact] - public async Task TestMethodFix1() - { - await TestAsync( -@"void Goo() -{ - Bar([|1 + 1|]); - Bar(1 + 1); -}", -@"void Goo() -{ - const int {|Rename:V|} = 1 + 1; - Bar(V); - Bar(1 + 1); -}", + public Task TestMethodFix1() + => TestAsync( + """ + void Goo() + { + Bar([|1 + 1|]); + Bar(1 + 1); + } + """, + """ + void Goo() + { + const int {|Rename:V|} = 1 + 1; + Bar(V); + Bar(1 + 1); + } + """, index: 2); - } [Fact] - public async Task TestMethodFix2() - { - await TestAsync( -@"void Goo() -{ - Bar([|1 + 1|]); - Bar(1 + 1); -}", -@"void Goo() -{ - const int {|Rename:V|} = 1 + 1; - Bar(V); - Bar(V); -}", + public Task TestMethodFix2() + => TestAsync( + """ + void Goo() + { + Bar([|1 + 1|]); + Bar(1 + 1); + } + """, + """ + void Goo() + { + const int {|Rename:V|} = 1 + 1; + Bar(V); + Bar(V); + } + """, index: 3); - } [Fact] - public async Task TestFieldFix1() - { - var code = -@"int i = ([|1 + 1|]) + (1 + 1);"; - - var expected = -@"private const int {|Rename:V|} = 1 + 1; -int i = V + (1 + 1);"; - - await TestAsync(code, expected, index: 0); - } + public Task TestFieldFix1() + => TestAsync(@"int i = ([|1 + 1|]) + (1 + 1);", """ + private const int {|Rename:V|} = 1 + 1; + int i = V + (1 + 1); + """, index: 0); [Fact] - public async Task TestFieldFix2() - { - var code = -@"int i = ([|1 + 1|]) + (1 + 1);"; - - var expected = -@"private const int {|Rename:V|} = 1 + 1; -int i = V + V;"; - - await TestAsync(code, expected, index: 1); - } + public Task TestFieldFix2() + => TestAsync(@"int i = ([|1 + 1|]) + (1 + 1);", """ + private const int {|Rename:V|} = 1 + 1; + int i = V + V; + """, index: 1); [Fact] - public async Task TestParameterFix1() - { - await TestAsync( -@"void Bar(int i = [|1 + 1|], int j = 1 + 1) -{ -}", -@"private const int {|Rename:V|} = 1 + 1; - -void Bar(int i = V, int j = 1 + 1) -{ -}", + public Task TestParameterFix1() + => TestAsync( + """ + void Bar(int i = [|1 + 1|], int j = 1 + 1) + { + } + """, + """ + private const int {|Rename:V|} = 1 + 1; + + void Bar(int i = V, int j = 1 + 1) + { + } + """, index: 0); - } [Fact] - public async Task TestParameterFix2() - { - await TestAsync( -@"void Bar(int i = [|1 + 1|], int j = 1 + 1) -{ -}", -@"private const int {|Rename:V|} = 1 + 1; - -void Bar(int i = V, int j = V) -{ -}", + public Task TestParameterFix2() + => TestAsync( + """ + void Bar(int i = [|1 + 1|], int j = 1 + 1) + { + } + """, + """ + private const int {|Rename:V|} = 1 + 1; + + void Bar(int i = V, int j = V) + { + } + """, index: 1); - } [Fact] - public async Task TestAttributeFix1() - { - await TestAsync( -@"[Goo([|1 + 1|], 1 + 1)] -void Bar() -{ -}", -@"private const int {|Rename:V|} = 1 + 1; - -[Goo(V, 1 + 1)] -void Bar() -{ -}", + public Task TestAttributeFix1() + => TestAsync( + """ + [Goo([|1 + 1|], 1 + 1)] + void Bar() + { + } + """, + """ + private const int {|Rename:V|} = 1 + 1; + + [Goo(V, 1 + 1)] + void Bar() + { + } + """, index: 0); - } [Fact] - public async Task TestAttributeFix2() - { - await TestAsync( -@"[Goo([|1 + 1|], 1 + 1)] -void Bar() -{ -}", -@"private const int {|Rename:V|} = 1 + 1; - -[Goo(V, V)] -void Bar() -{ -}", + public Task TestAttributeFix2() + => TestAsync( + """ + [Goo([|1 + 1|], 1 + 1)] + void Bar() + { + } + """, + """ + private const int {|Rename:V|} = 1 + 1; + + [Goo(V, V)] + void Bar() + { + } + """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541287")] - public async Task TestBlockFormatting() - { - await TestAsync( -@"using System; - -class C -{ - public static void Main() - { - for (int i = 0; i < 10; i++) - Console.WriteLine([|i+1|]); - } -} -", -@"using System; - -class C -{ - public static void Main() - { - for (int i = 0; i < 10; i++) - { - int {|Rename:value|} = i + 1; - Console.WriteLine(value); - } - } -} -", + public Task TestBlockFormatting() + => TestAsync( + """ + using System; + + class C + { + public static void Main() + { + for (int i = 0; i < 10; i++) + Console.WriteLine([|i+1|]); + } + } + """, + """ + using System; + + class C + { + public static void Main() + { + for (int i = 0; i < 10; i++) + { + int {|Rename:value|} = i + 1; + Console.WriteLine(value); + } + } + } + """, index: 1); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546465")] - public async Task TestPreserveTrivia() - { - await TestAsync( -@"class C -{ - void M(params string[] args) - { - M( - ""a"", - [|""b""|], - ""c""); - } -} -", -@"class C -{ - private const string {|Rename:V|} = ""b""; - - void M(params string[] args) - { - M( - ""a"", - V, - ""c""); - } -} -"); - } + public Task TestPreserveTrivia() + => TestAsync( + """ + class C + { + void M(params string[] args) + { + M( + "a", + [|"b"|], + "c"); + } + } + """, + """ + class C + { + private const string {|Rename:V|} = "b"; + + void M(params string[] args) + { + M( + "a", + V, + "c"); + } + } + """); } diff --git a/src/Features/CSharpTest/IntroduceVariable/IntroduceLocalForExpressionTests.cs b/src/Features/CSharpTest/IntroduceVariable/IntroduceLocalForExpressionTests.cs index ff30bb0af001c..35f2dd28987f7 100644 --- a/src/Features/CSharpTest/IntroduceVariable/IntroduceLocalForExpressionTests.cs +++ b/src/Features/CSharpTest/IntroduceVariable/IntroduceLocalForExpressionTests.cs @@ -57,9 +57,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor => new CSharpIntroduceLocalForExpressionCodeRefactoringProvider(); [Fact] - public async Task IntroduceLocal_NoSemicolon() - { - await TestInRegularAndScriptAsync( + public Task IntroduceLocal_NoSemicolon() + => TestInRegularAndScriptAsync( """ using System; @@ -82,12 +81,10 @@ void M() } } """); - } [Fact] - public async Task IntroduceLocal_NoSemicolon_BlankLineAfter() - { - await TestInRegularAndScriptAsync( + public Task IntroduceLocal_NoSemicolon_BlankLineAfter() + => TestInRegularAndScriptAsync( """ using System; @@ -112,12 +109,10 @@ void M() } } """); - } [Fact] - public async Task IntroduceLocal_NoSemicolon_SelectExpression() - { - await TestInRegularAndScriptAsync( + public Task IntroduceLocal_NoSemicolon_SelectExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -140,12 +135,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task IntroduceLocal_Inside_Expression() - { - await TestInRegularAndScriptAsync( + public Task IntroduceLocal_Inside_Expression() + => TestInRegularAndScriptAsync( """ using System; @@ -168,12 +161,10 @@ void M() } } """); - } [Fact] - public async Task IntroduceLocal_Semicolon() - { - await TestInRegularAndScriptAsync( + public Task IntroduceLocal_Semicolon() + => TestInRegularAndScriptAsync( """ using System; @@ -196,12 +187,10 @@ void M() } } """); - } [Fact] - public async Task IntroduceLocal_Semicolon_BlankLineAfter() - { - await TestInRegularAndScriptAsync( + public Task IntroduceLocal_Semicolon_BlankLineAfter() + => TestInRegularAndScriptAsync( """ using System; @@ -226,12 +215,10 @@ void M() } } """); - } [Fact] - public async Task IntroduceLocal_Semicolon_SelectExpression() - { - await TestInRegularAndScriptAsync( + public Task IntroduceLocal_Semicolon_SelectExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -254,12 +241,10 @@ void M() } } """); - } [Fact] - public async Task IntroduceLocal_Semicolon_SelectStatement() - { - await TestInRegularAndScriptAsync( + public Task IntroduceLocal_Semicolon_SelectStatement() + => TestInRegularAndScriptAsync( """ using System; @@ -282,12 +267,10 @@ void M() } } """); - } [Fact] - public async Task MissingOnAssignmentExpressionStatement() - { - await TestMissingInRegularAndScriptAsync( + public Task MissingOnAssignmentExpressionStatement() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -300,12 +283,10 @@ void M() } } """); - } [Fact] - public async Task IntroduceLocal_Space() - { - await TestInRegularAndScriptAsync( + public Task IntroduceLocal_Space() + => TestInRegularAndScriptAsync( """ using System; @@ -328,12 +309,10 @@ void M() } } """); - } [Fact] - public async Task IntroduceLocal_LeadingTrivia() - { - await TestInRegularAndScriptAsync( + public Task IntroduceLocal_LeadingTrivia() + => TestInRegularAndScriptAsync( """ using System; @@ -358,12 +337,10 @@ void M() } } """); - } [Fact] - public async Task IntroduceLocal_PreferVar() - { - await TestInRegularAndScriptAsync( + public Task IntroduceLocal_PreferVar() + => TestInRegularAndScriptAsync( """ using System; @@ -390,12 +367,10 @@ void M() { CSharpCodeStyleOptions.VarElsewhere, CodeStyleOption2.TrueWithSuggestionEnforcement }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOption2.TrueWithSuggestionEnforcement }, }); - } [Fact] - public async Task MissingOnVoidCall() - { - await TestMissingInRegularAndScriptAsync( + public Task MissingOnVoidCall() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -407,12 +382,10 @@ void M() } } """); - } [Fact] - public async Task MissingOnDeclaration() - { - await TestMissingInRegularAndScriptAsync( + public Task MissingOnDeclaration() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -424,12 +397,10 @@ void M() } } """); - } [Fact] - public async Task IntroduceLocal_ArithmeticExpression() - { - await TestInRegularAndScriptAsync( + public Task IntroduceLocal_ArithmeticExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -452,12 +423,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39537")] - public async Task IntroduceDeconstruction1_A() - { - await TestInRegularAndScriptAsync( + public Task IntroduceDeconstruction1_A() + => TestInRegularAndScriptAsync( """ using System; @@ -484,12 +453,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39537")] - public async Task IntroduceDeconstruction1_B() - { - await TestInRegularAndScriptAsync( + public Task IntroduceDeconstruction1_B() + => TestInRegularAndScriptAsync( """ using System; @@ -516,12 +483,10 @@ void M() } } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39537")] - public async Task IntroduceDeconstruction1_C() - { - await TestInRegularAndScriptAsync( + public Task IntroduceDeconstruction1_C() + => TestInRegularAndScriptAsync( """ using System; @@ -548,12 +513,10 @@ void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39537")] - public async Task IntroduceDeconstruction2_A() - { - await TestInRegularAndScriptAsync( + public Task IntroduceDeconstruction2_A() + => TestInRegularAndScriptAsync( """ using System; @@ -580,12 +543,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39537")] - public async Task IntroduceDeconstruction2_B() - { - await TestInRegularAndScriptAsync( + public Task IntroduceDeconstruction2_B() + => TestInRegularAndScriptAsync( """ using System; @@ -612,12 +573,10 @@ void M() } } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39537")] - public async Task IntroduceDeconstruction2_C() - { - await TestInRegularAndScriptAsync( + public Task IntroduceDeconstruction2_C() + => TestInRegularAndScriptAsync( """ using System; @@ -644,12 +603,10 @@ void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39537")] - public async Task IntroduceDeconstruction3_A() - { - await TestInRegularAndScriptAsync( + public Task IntroduceDeconstruction3_A() + => TestInRegularAndScriptAsync( """ using System; @@ -680,12 +637,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39537")] - public async Task IntroduceDeconstruction3_B() - { - await TestInRegularAndScriptAsync( + public Task IntroduceDeconstruction3_B() + => TestInRegularAndScriptAsync( """ using System; @@ -716,12 +671,10 @@ void M() } } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39537")] - public async Task IntroduceDeconstruction3_C() - { - await TestInRegularAndScriptAsync( + public Task IntroduceDeconstruction3_C() + => TestInRegularAndScriptAsync( """ using System; @@ -752,12 +705,10 @@ void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39537")] - public async Task IntroduceDeconstruction4_A() - { - await TestInRegularAndScriptAsync( + public Task IntroduceDeconstruction4_A() + => TestInRegularAndScriptAsync( """ using System; @@ -784,12 +735,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39537")] - public async Task IntroduceDeconstruction4_B() - { - await TestInRegularAndScriptAsync( + public Task IntroduceDeconstruction4_B() + => TestInRegularAndScriptAsync( """ using System; @@ -816,12 +765,10 @@ void M() } } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39537")] - public async Task IntroduceDeconstruction4_C() - { - await TestInRegularAndScriptAsync( + public Task IntroduceDeconstruction4_C() + => TestInRegularAndScriptAsync( """ using System; @@ -848,12 +795,10 @@ void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39537")] - public async Task IntroduceDeconstruction5_A() - { - await TestInRegularAndScriptAsync( + public Task IntroduceDeconstruction5_A() + => TestInRegularAndScriptAsync( """ using System; @@ -880,12 +825,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39537")] - public async Task IntroduceDeconstruction5_B() - { - await TestInRegularAndScriptAsync( + public Task IntroduceDeconstruction5_B() + => TestInRegularAndScriptAsync( """ using System; @@ -912,12 +855,10 @@ void M() } } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39537")] - public async Task IntroduceDeconstruction5_C() - { - await TestInRegularAndScriptAsync( + public Task IntroduceDeconstruction5_C() + => TestInRegularAndScriptAsync( """ using System; @@ -944,12 +885,10 @@ void M() } } """, options: ImplicitTypeEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39537")] - public async Task IntroduceDeconstruction_ImplicitTypeForIntrinsics1() - { - await TestInRegularAndScriptAsync( + public Task IntroduceDeconstruction_ImplicitTypeForIntrinsics1() + => TestInRegularAndScriptAsync( """ using System; @@ -976,12 +915,10 @@ void M() } } """, options: ImplicitTypeForIntrinsics()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39537")] - public async Task IntroduceDeconstruction_ImplicitTypeForIntrinsics2() - { - await TestInRegularAndScriptAsync( + public Task IntroduceDeconstruction_ImplicitTypeForIntrinsics2() + => TestInRegularAndScriptAsync( """ using System; @@ -1010,12 +947,10 @@ void M() } } """, options: ImplicitTypeForIntrinsics()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39537")] - public async Task IntroduceDeconstruction_ImplicitTypeWhenApparent1() - { - await TestInRegularAndScriptAsync( + public Task IntroduceDeconstruction_ImplicitTypeWhenApparent1() + => TestInRegularAndScriptAsync( """ using System; @@ -1042,12 +977,10 @@ void M() } } """, options: ImplicitTypeForApparent()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39537")] - public async Task IntroduceDeconstruction_ImplicitTypeWhenApparent2() - { - await TestInRegularAndScriptAsync( + public Task IntroduceDeconstruction_ImplicitTypeWhenApparent2() + => TestInRegularAndScriptAsync( """ using System; @@ -1072,12 +1005,10 @@ void M() } } """, options: ImplicitTypeForApparent()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39537")] - public async Task IntroduceDeconstruction_ImplicitTypeWhenApparentAndBuiltIn1() - { - await TestInRegularAndScriptAsync( + public Task IntroduceDeconstruction_ImplicitTypeWhenApparentAndBuiltIn1() + => TestInRegularAndScriptAsync( """ using System; @@ -1102,5 +1033,4 @@ void M() } } """, options: ImplicitTypeForApparentAndBuiltIn()); - } } diff --git a/src/Features/CSharpTest/IntroduceVariable/IntroduceVariableTests.cs b/src/Features/CSharpTest/IntroduceVariable/IntroduceVariableTests.cs index c0fc56fb1ba84..d93e478aac9b9 100644 --- a/src/Features/CSharpTest/IntroduceVariable/IntroduceVariableTests.cs +++ b/src/Features/CSharpTest/IntroduceVariable/IntroduceVariableTests.cs @@ -54,9 +54,8 @@ public struct ValueTask { } """; [Fact] - public async Task TestEmptySpan1() - { - await TestInRegularAndScriptAsync( + public Task TestEmptySpan1() + => TestInRegularAndScriptAsync( """ using System; class C @@ -78,12 +77,10 @@ void M(Action action) } } """); - } [Fact] - public async Task TestEmptySpan2() - { - await TestInRegularAndScriptAsync( + public Task TestEmptySpan2() + => TestInRegularAndScriptAsync( """ using System; class C @@ -105,12 +102,10 @@ void M(int a, int b) } } """); - } [Fact] - public async Task TestEmptySpan3() - { - await TestMissingAsync( + public Task TestEmptySpan3() + => TestMissingAsync( """ using System; class C @@ -121,12 +116,10 @@ void M(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestEmptySpan4() - { - await TestInRegularAndScriptAsync( + public Task TestEmptySpan4() + => TestInRegularAndScriptAsync( """ using System; class C @@ -148,12 +141,10 @@ void M(Action action) } } """); - } [Fact] - public async Task TestMethodFix1() - { - await TestInRegularAndScriptAsync( + public Task TestMethodFix1() + => TestInRegularAndScriptAsync( """ class C { @@ -176,12 +167,10 @@ void Goo() } """, index: 2); - } [Fact] - public async Task TestMethodFix2() - { - await TestInRegularAndScriptAsync( + public Task TestMethodFix2() + => TestInRegularAndScriptAsync( """ class C { @@ -204,13 +193,10 @@ void Goo() } """, index: 3); - } [Fact] - public async Task TestMethodFix3() - { - var code = - """ + public Task TestMethodFix3() + => TestInRegularAndScriptAsync(""" class C { void Goo() @@ -219,10 +205,7 @@ void Goo() Bar((1 + 1)); } } - """; - - var expected = - """ + """, """ class C { void Goo() @@ -232,16 +215,11 @@ void Goo() Bar((1 + 1)); } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } + """, index: 2); [Fact] - public async Task TestMethodFix4() - { - var code = - """ + public Task TestMethodFix4() + => TestInRegularAndScriptAsync(""" class C { void Goo() @@ -250,10 +228,7 @@ void Goo() Bar((1 + 1)); } } - """; - - var expected = - """ + """, """ class C { void Goo() @@ -263,16 +238,11 @@ void Goo() Bar(V); } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 3); - } + """, index: 3); [Fact] - public async Task TestThrowExpression() - { - var code = - """ + public Task TestThrowExpression() + => TestActionCountAsync(""" class C { void M(bool b) @@ -280,14 +250,11 @@ void M(bool b) var x = b ? 1 : [|throw null|]; } } - """; - await TestActionCountAsync(code, count: 0); - } + """, count: 0); [Fact] - public async Task TestThrowExpression2() - { - await TestInRegularAndScriptAsync( + public Task TestThrowExpression2() + => TestInRegularAndScriptAsync( """ class C { @@ -308,13 +275,10 @@ void M(bool b) } """, index: 1); - } [Fact] - public async Task TestThrowStatement() - { - var code = - """ + public Task TestThrowStatement() + => TestActionCountAsync(""" class C { void M() @@ -322,152 +286,101 @@ void M() [|throw null|]; } } - """; - await TestActionCountAsync(code, count: 0); - } + """, count: 0); [Fact] - public async Task TestFieldFix1() - { - var code = - """ + public Task TestFieldFix1() + => TestInRegularAndScriptAsync(""" class C { int i = ([|1 + 1|]) + (1 + 1); } - """; - - var expected = - """ + """, """ class C { private const int {|Rename:V|} = 1 + 1; int i = V + (1 + 1); } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task TestFieldFix2() - { - var code = - """ + public Task TestFieldFix2() + => TestInRegularAndScriptAsync(""" class C { int i = ([|1 + 1|]) + (1 + 1); } - """; - - var expected = - """ + """, """ class C { private const int {|Rename:V|} = 1 + 1; int i = V + V; } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1); - } + """, index: 1); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21747")] - public async Task TestTriviaFieldFix1() - { - var code = - """ + public Task TestTriviaFieldFix1() + => TestInRegularAndScriptAsync(""" class C { int i = (/* CommentLeading */ [|1 + 1|] /* CommentTrailing */) + (1 + 1); } - """; - - var expected = - """ + """, """ class C { private const int {|Rename:V|} = 1 + 1; int i = /* CommentLeading */ V /* CommentTrailing */ + V; } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1); - } + """, index: 1); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21747")] - public async Task TestTriviaFieldFix2() - { - var code = - """ + public Task TestTriviaFieldFix2() + => TestInRegularAndScriptAsync(""" class C { int i = (/* CommentLeading */ [|1 + /*CommentEmbedded*/ 1|] /* CommentTrailing */) + (1 + 1); } - """; - - var expected = - """ + """, """ class C { private const int {|Rename:V|} = 1 + /*CommentEmbedded*/ 1; int i = /* CommentLeading */ V /* CommentTrailing */ + V; } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1); - } + """, index: 1); [Fact] - public async Task TestConstFieldFix1() - { - var code = - """ + public Task TestConstFieldFix1() + => TestInRegularAndScriptAsync(""" class C { const int i = ([|1 + 1|]) + (1 + 1); } - """; - - var expected = - """ + """, """ class C { private const int {|Rename:V|} = 1 + 1; const int i = V + (1 + 1); } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task TestConstFieldFix2() - { - var code = - """ + public Task TestConstFieldFix2() + => TestInRegularAndScriptAsync(""" class C { const int i = ([|1 + 1|]) + (1 + 1); } - """; - - var expected = - """ + """, """ class C { private const int {|Rename:V|} = 1 + 1; const int i = V + V; } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1); - } + """, index: 1); [Fact] - public async Task TestConstructorFix1() - { - await TestInRegularAndScriptAsync( + public Task TestConstructorFix1() + => TestInRegularAndScriptAsync( """ class C { @@ -487,12 +400,10 @@ public C() : this(V, 1 + 1) } """, index: 0); - } [Fact] - public async Task TestConstructorFix2() - { - await TestInRegularAndScriptAsync( + public Task TestConstructorFix2() + => TestInRegularAndScriptAsync( """ class C { @@ -512,12 +423,10 @@ public C() : this(V, V) } """, index: 1); - } [Fact] - public async Task TestParameterFix1() - { - await TestInRegularAndScriptAsync( + public Task TestParameterFix1() + => TestInRegularAndScriptAsync( """ class C { @@ -537,12 +446,10 @@ void Bar(int i = V, int j = 1 + 1) } """, index: 0); - } [Fact] - public async Task TestParameterFix2() - { - await TestInRegularAndScriptAsync( + public Task TestParameterFix2() + => TestInRegularAndScriptAsync( """ class C { @@ -562,12 +469,10 @@ void Bar(int i = V, int j = V) } """, index: 1); - } [Fact] - public async Task TestAttributeFix1() - { - await TestInRegularAndScriptAsync( + public Task TestAttributeFix1() + => TestInRegularAndScriptAsync( """ class C { @@ -589,12 +494,10 @@ void Bar() } """, index: 0); - } [Fact] - public async Task TestAttributeFix2() - { - await TestInRegularAndScriptAsync( + public Task TestAttributeFix2() + => TestInRegularAndScriptAsync( """ class C { @@ -616,12 +519,10 @@ void Bar() } """, index: 1); - } [Fact] - public async Task TestMethodFixExistingName1() - { - await TestInRegularAndScriptAsync( + public Task TestMethodFixExistingName1() + => TestInRegularAndScriptAsync( """ class C { @@ -646,12 +547,10 @@ void Goo() } """, index: 2); - } [Fact] - public async Task TestFieldExistingName1() - { - var code = + public Task TestFieldExistingName1() + => TestInRegularAndScriptAsync( """ class C { @@ -659,9 +558,7 @@ class C int V1; int i = ([|1 + 1|]) + (1 + 1); } - """; - - var expected = + """, """ class C { @@ -670,18 +567,12 @@ class C int V1; int i = V2 + (1 + 1); } - """; - - await TestInRegularAndScriptAsync( - code, - expected, + """, index: 0); - } [Fact] - public async Task TestMethodFixComplexName1() - { - await TestInRegularAndScriptAsync( + public Task TestMethodFixComplexName1() + => TestInRegularAndScriptAsync( """ class C { @@ -709,12 +600,10 @@ void Goo() """, index: 0, options: ImplicitTypingEverywhere()); - } [Fact] - public async Task TestMethodFixComplexName1NotVar() - { - await TestInRegularAndScriptAsync( + public Task TestMethodFixComplexName1NotVar() + => TestInRegularAndScriptAsync( """ class C { @@ -741,12 +630,10 @@ void Goo() } """, index: 0); - } [Fact] - public async Task TestNameConflict1() - { - await TestInRegularAndScriptAsync( + public Task TestNameConflict1() + => TestInRegularAndScriptAsync( """ class C { @@ -766,12 +653,10 @@ public C(int V) : this(C.V) } """, index: 0); - } [Fact] - public async Task TestNameConflict2() - { - await TestInRegularAndScriptAsync( + public Task TestNameConflict2() + => TestInRegularAndScriptAsync( """ using System; @@ -805,13 +690,11 @@ static void Main(string[] args) } } """, -options: ImplicitTypingEverywhere()); - } + options: ImplicitTypingEverywhere()); [Fact] - public async Task TestNameConflict2NotVar() - { - await TestInRegularAndScriptAsync( + public Task TestNameConflict2NotVar() + => TestInRegularAndScriptAsync( """ using System; @@ -845,12 +728,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestNameVerbatimIdentifier1() - { - await TestInRegularAndScriptAsync( + public Task TestNameVerbatimIdentifier1() + => TestInRegularAndScriptAsync( """ static class G { @@ -892,13 +773,11 @@ static void Main() } } """, -options: ImplicitTypingEverywhere()); - } + options: ImplicitTypingEverywhere()); [Fact] - public async Task TestNameVerbatimIdentifier1NoVar() - { - await TestInRegularAndScriptAsync( + public Task TestNameVerbatimIdentifier1NoVar() + => TestInRegularAndScriptAsync( """ static class G { @@ -940,12 +819,10 @@ static void Main() } } """); - } [Fact] - public async Task TestNameVerbatimIdentifier1NoVar_1() - { - await TestInRegularAndScriptAsync( + public Task TestNameVerbatimIdentifier1NoVar_1() + => TestInRegularAndScriptAsync( """ static class G { @@ -990,12 +867,10 @@ static void Main() { { CSharpCodeStyleOptions.ImplicitObjectCreationWhenTypeIsApparent, CodeStyleOption2.FalseWithSilentEnforcement } }); - } [Fact] - public async Task TestNameVerbatimIdentifier2() - { - await TestInRegularAndScriptAsync( + public Task TestNameVerbatimIdentifier2() + => TestInRegularAndScriptAsync( """ static class G { @@ -1031,13 +906,11 @@ static void Main() } } """, -options: ImplicitTypingEverywhere()); - } + options: ImplicitTypingEverywhere()); [Fact] - public async Task TestNameVerbatimIdentifier2NoVar() - { - await TestInRegularAndScriptAsync( + public Task TestNameVerbatimIdentifier2NoVar() + => TestInRegularAndScriptAsync( """ static class G { @@ -1073,12 +946,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540078")] - public async Task TestConstantField1() - { - await TestInRegularAndScriptAsync( + public Task TestConstantField1() + => TestInRegularAndScriptAsync( """ class C { @@ -1092,12 +963,10 @@ class C int[] array = new int[V]; } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540079")] - public async Task TestFormattingOfReplacedExpression1() - { - await TestInRegularAndScriptAsync( + public Task TestFormattingOfReplacedExpression1() + => TestInRegularAndScriptAsync( """ class C { @@ -1117,13 +986,11 @@ void M() } } """, -index: 2); - } + index: 2); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540468")] - public async Task TestCantExtractMethodTypeParameterToField() - { - await TestInRegularAndScriptAsync( + public Task TestCantExtractMethodTypeParameterToField() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -1151,13 +1018,11 @@ static void Main(string[] args) } } """, -options: ImplicitTypingEverywhere()); - } + options: ImplicitTypingEverywhere()); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540468")] - public async Task TestCantExtractMethodTypeParameterToFieldCount() - { - await TestActionCountAsync( + public Task TestCantExtractMethodTypeParameterToFieldCount() + => TestActionCountAsync( """ using System; using System.Collections.Generic; @@ -1171,15 +1036,13 @@ static void Main(string[] args) } } """, -count: 2); - } + count: 2); [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552389")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540482")] [Fact(Skip = "552389")] - public async Task TestConstantForFixedBufferInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestConstantForFixedBufferInitializer() + => TestInRegularAndScriptAsync( """ unsafe struct S { @@ -1193,12 +1056,10 @@ unsafe struct S fixed int buffer[p]; } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540486")] - public async Task TestFormattingOfIntroduceLocal() - { - await TestInRegularAndScriptAsync( + public Task TestFormattingOfIntroduceLocal() + => TestInRegularAndScriptAsync( """ class C { @@ -1218,13 +1079,11 @@ void M() } } """, -index: 2); - } + index: 2); [Fact] - public async Task TestLocalConstant() - { - await TestInRegularAndScriptAsync( + public Task TestLocalConstant() + => TestInRegularAndScriptAsync( """ class Program { @@ -1244,13 +1103,11 @@ static void Main(string[] args) } } """, -index: 2); - } + index: 2); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542699")] - public async Task TestFieldConstant() - { - await TestInRegularAndScriptAsync( + public Task TestFieldConstant() + => TestInRegularAndScriptAsync( """ [Goo(2 + 3 + 4)] class Program @@ -1280,13 +1137,11 @@ public GooAttribute(int x) } } """, -index: 1); - } + index: 1); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542781")] - public async Task TestMissingOnExpressionStatement() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnExpressionStatement() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -1298,12 +1153,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542780")] - public async Task TestSingleQueryClause() - { - await TestInRegularAndScriptAsync( + public Task TestSingleQueryClause() + => TestInRegularAndScriptAsync( """ using System.Linq; @@ -1335,12 +1188,10 @@ void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542780")] - public async Task TestSingleQuerySelectOrGroupByClause() - { - await TestInRegularAndScriptAsync( + public Task TestSingleQuerySelectOrGroupByClause() + => TestInRegularAndScriptAsync( """ using System.Linq; @@ -1374,12 +1225,10 @@ where v > 5 } } """); - } [Fact] - public async Task TestLinqQuery() - { - await TestInRegularAndScriptAsync( + public Task TestLinqQuery() + => TestInRegularAndScriptAsync( """ using System.Linq; @@ -1415,13 +1264,11 @@ where v > 5 } } """, -index: 1); - } + index: 1); [Fact] - public async Task TestSingleQueryReplaceAll() - { - await TestInRegularAndScriptAsync( + public Task TestSingleQueryReplaceAll() + => TestInRegularAndScriptAsync( """ using System.Linq; @@ -1457,13 +1304,11 @@ where v > 5 } } """, -index: 1); - } + index: 1); [Fact] - public async Task TestNestedQueryReplaceOne1() - { - await TestInRegularAndScriptAsync( + public Task TestNestedQueryReplaceOne1() + => TestInRegularAndScriptAsync( """ using System.Linq; @@ -1509,12 +1354,10 @@ void Main() } } """); - } [Fact] - public async Task TestNestedQueryReplaceAll1() - { - await TestInRegularAndScriptAsync( + public Task TestNestedQueryReplaceAll1() + => TestInRegularAndScriptAsync( """ using System.Linq; @@ -1560,13 +1403,11 @@ void Main() } } """, -index: 1); - } + index: 1); [Fact] - public async Task TestNestedQueryReplaceOne2() - { - await TestInRegularAndScriptAsync( + public Task TestNestedQueryReplaceOne2() + => TestInRegularAndScriptAsync( """ using System.Linq; @@ -1612,12 +1453,10 @@ void Main() } } """); - } [Fact] - public async Task TestNestedQueryReplaceAll2() - { - await TestInRegularAndScriptAsync( + public Task TestNestedQueryReplaceAll2() + => TestInRegularAndScriptAsync( """ using System.Linq; @@ -1663,13 +1502,11 @@ void Main() } } """, -index: 1); - } + index: 1); [Fact, WorkItem(10742, "DevDiv_Projects/Roslyn")] - public async Task TestAnonymousTypeMemberAssignment() - { - await TestMissingInRegularAndScriptAsync( + public Task TestAnonymousTypeMemberAssignment() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1679,12 +1516,10 @@ void M() } } """); - } [Fact, WorkItem(10743, "DevDiv_Projects/Roslyn")] - public async Task TestAnonymousTypeBody() - { - await TestInRegularAndScriptAsync( + public Task TestAnonymousTypeBody() + => TestInRegularAndScriptAsync( """ class Program { @@ -1704,12 +1539,10 @@ void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543477")] - public async Task TestImplicitlyTypedArraysUsedInCheckedExpression() - { - await TestInRegularAndScriptAsync( + public Task TestImplicitlyTypedArraysUsedInCheckedExpression() + => TestInRegularAndScriptAsync( """ class Program { @@ -1731,13 +1564,11 @@ static void Main(string[] args) } } """, -options: ImplicitTypingEverywhere()); - } + options: ImplicitTypingEverywhere()); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543832")] - public async Task TestMissingOnGenericTypeParameter() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnGenericTypeParameter() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1752,12 +1583,10 @@ R F(T arg1) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543941")] - public async Task TestAnonymousType1() - { - await TestInRegularAndScriptAsync( + public Task TestAnonymousType1() + => TestInRegularAndScriptAsync( """ class Program { @@ -1777,12 +1606,10 @@ void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544099")] - public async Task TestMissingOnAttributeNameEquals() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnAttributeNameEquals() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Runtime.InteropServices; @@ -1793,12 +1620,10 @@ class M public static extern IntPtr FindWindow(string className, string windowTitle); } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544162")] - public async Task TestMissingOnRightOfDot() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnRightOfDot() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Runtime.InteropServices; @@ -1809,12 +1634,10 @@ class M public static extern IntPtr FindWindow(string className, string windowTitle); } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544209")] - public async Task TestMissingOnAttributeNamedParameter() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnAttributeNamedParameter() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1830,12 +1653,10 @@ class Goo { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544264")] - public async Task TestMissingOnVariableWrite() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnVariableWrite() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -1846,13 +1667,11 @@ void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544577")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/909152")] - public async Task TestExpressionTLambda() - { - await TestMissingInRegularAndScriptAsync( + public Task TestExpressionTLambda() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Linq.Expressions; @@ -1862,12 +1681,10 @@ class Program static Expression> e1 = c => [|null|]; } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544915")] - public async Task TestMissingOnTypeSyntax() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnTypeSyntax() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1879,12 +1696,10 @@ void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544610")] - public async Task ParenthesizeIfParseChanges() - { - var code = """ + public Task ParenthesizeIfParseChanges() + => TestInRegularAndScriptAsync(""" class C { static void M() @@ -1893,9 +1708,7 @@ static void M() Bar(x < [|1|], x > (2 + 3)); } } - """; - - var expected = """ + """, """ class C { static void M() @@ -1905,15 +1718,11 @@ static void M() Bar(x < (V), x > (2 + 3)); } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } + """, index: 2); [Fact] - public async Task TestInPartiallyHiddenMethod() - { - await TestInRegularAndScript1Async( + public Task TestInPartiallyHiddenMethod() + => TestInRegularAndScript1Async( """ class Program { @@ -1938,12 +1747,10 @@ void Main() private const int {|Rename:V|} = 1 + 1; } """, parameters: new TestParameters(TestOptions.Regular)); - } [Fact] - public async Task TestInVisibleMethod() - { - await TestInRegularAndScriptAsync( + public Task TestInVisibleMethod() + => TestInRegularAndScriptAsync( """ #line hidden class Program @@ -1971,12 +1778,10 @@ void Main() } #line default """); - } [Fact] - public async Task TestMissingInFieldInPartiallyHiddenType() - { - await TestMissingAsync( + public Task TestMissingInFieldInPartiallyHiddenType() + => TestMissingAsync( """ class Program { @@ -1986,12 +1791,10 @@ class Program } #line default """, new TestParameters(TestOptions.Regular)); - } [Fact] - public async Task TestMissingInAttributeInPartiallyHiddenType() - { - await TestMissingAsync( + public Task TestMissingInAttributeInPartiallyHiddenType() + => TestMissingAsync( """ [Goo([|1 + 1|])] class Program @@ -2000,12 +1803,10 @@ class Program } #line default """, new TestParameters(TestOptions.Regular)); - } [Fact] - public async Task TestMissingInConstructorInitializerInPartiallyHiddenType() - { - await TestMissingAsync( + public Task TestMissingInConstructorInitializerInPartiallyHiddenType() + => TestMissingAsync( """ class Program { @@ -2017,12 +1818,10 @@ public Program() : this([|1 + 1|]) } #line default """, new TestParameters(TestOptions.Regular)); - } [Fact] - public async Task TestMissingInParameterInPartiallyHiddenType() - { - await TestMissingAsync( + public Task TestMissingInParameterInPartiallyHiddenType() + => TestMissingAsync( """ class Program { @@ -2034,12 +1833,10 @@ public Program(int i = [|1 + 1|]) } #line default """, new TestParameters(TestOptions.Regular)); - } [Fact] - public async Task TestMissingInQueryInPartiallyHiddenType() - { - await TestMissingAsync( + public Task TestMissingInQueryInPartiallyHiddenType() + => TestMissingAsync( """ using System.Linq; @@ -2055,12 +1852,10 @@ public Program(string[] args) } } """, new TestParameters(TestOptions.Regular)); - } [Fact] - public async Task TestInVisibleQueryInHiddenType() - { - await TestAsync( + public Task TestInVisibleQueryInHiddenType() + => TestAsync( """ #line hidden using System.Linq; @@ -2098,13 +1893,11 @@ from x in args } #line default """, -parseOptions: TestOptions.Regular); - } + parseOptions: TestOptions.Regular); [Fact] - public async Task TestMissingOnNamespace() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnNamespace() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -2114,12 +1907,10 @@ void Main() } } """); - } [Fact] - public async Task TestMissingOnType() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnType() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -2129,12 +1920,10 @@ void Main() } } """); - } [Fact] - public async Task TestMissingOnBase() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnBase() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -2144,12 +1933,10 @@ void Main() } } """); - } [Fact] - public async Task TestVenusGeneration1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestVenusGeneration1() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -2162,7 +1949,6 @@ void Main() } } """); - } [Fact] public async Task TestVenusGeneration2() @@ -2206,10 +1992,8 @@ void Main ( ) } [Fact] - public async Task TestVenusGeneration3() - { - var code = - """ + public Task TestVenusGeneration3() + => TestExactActionSetOfferedAsync(""" class Program { #line 1 "goo" @@ -2223,16 +2007,12 @@ void Main ( ) #line default #line hidden } - """; - - await TestExactActionSetOfferedAsync(code, + """, [string.Format(FeaturesResources.Introduce_local_constant_for_0, "5"), string.Format(FeaturesResources.Introduce_local_constant_for_all_occurrences_of_0, "5")]); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529795")] - public async Task TestMissingOnNegatedLiteral() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnNegatedLiteral() + => TestMissingInRegularAndScriptAsync( """ class A { @@ -2242,24 +2022,20 @@ void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546091")] - public async Task TestNotOnInterfaceAttribute() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOnInterfaceAttribute() + => TestMissingInRegularAndScriptAsync( """ [GuidAttribute([|"1A585C4D-3371-48dc-AF8A-AFFECC1B0967"|])] public interface I { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546095")] - public async Task TestNotOnTypeOfInAttribute() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOnTypeOfInAttribute() + => TestMissingInRegularAndScriptAsync( """ using System.Runtime.InteropServices; @@ -2268,12 +2044,10 @@ public class Button { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530109")] - public async Task TestPreferGenerateConstantField1() - { - await TestInRegularAndScriptAsync( + public Task TestPreferGenerateConstantField1() + => TestInRegularAndScriptAsync( """ class C { @@ -2294,12 +2068,10 @@ void goo(string s = "Hello") } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530109")] - public async Task TestPreferGenerateConstantField2() - { - await TestInRegularAndScriptAsync( + public Task TestPreferGenerateConstantField2() + => TestInRegularAndScriptAsync( """ class C { @@ -2320,13 +2092,11 @@ void goo(string s = V) } } """, -index: 1); - } + index: 1); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530109")] - public async Task TestPreferGenerateConstantField3() - { - await TestInRegularAndScriptAsync( + public Task TestPreferGenerateConstantField3() + => TestInRegularAndScriptAsync( """ class C { @@ -2346,13 +2116,11 @@ void goo(string s = "Hello") } } """, -index: 2); - } + index: 2); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530109")] - public async Task TestPreferGenerateConstantField4() - { - await TestInRegularAndScriptAsync( + public Task TestPreferGenerateConstantField4() + => TestInRegularAndScriptAsync( """ class C { @@ -2372,13 +2140,11 @@ void goo(string s = "Hello") } } """, -index: 3); - } + index: 3); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530109")] - public async Task TestNoGenerateConstantFieldIfAccessingLocal1() - { - await TestInRegularAndScriptAsync( + public Task TestNoGenerateConstantFieldIfAccessingLocal1() + => TestInRegularAndScriptAsync( """ class C { @@ -2400,12 +2166,10 @@ void goo(string s = "Hello") } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530109")] - public async Task TestNoGenerateConstantFieldIfAccessingLocal2() - { - await TestInRegularAndScriptAsync( + public Task TestNoGenerateConstantFieldIfAccessingLocal2() + => TestInRegularAndScriptAsync( """ class C { @@ -2427,13 +2191,11 @@ void goo(string s = "Hello") } } """, -index: 1); - } + index: 1); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530109")] - public async Task TestNoGenerateConstantFieldIfNotAccessingLocal1() - { - await TestInRegularAndScriptAsync( + public Task TestNoGenerateConstantFieldIfNotAccessingLocal1() + => TestInRegularAndScriptAsync( """ class C { @@ -2457,12 +2219,10 @@ void goo(string s = "Hello") } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530109")] - public async Task TestNoGenerateConstantFieldIfNotAccessingLocal2() - { - await TestInRegularAndScriptAsync( + public Task TestNoGenerateConstantFieldIfNotAccessingLocal2() + => TestInRegularAndScriptAsync( """ class C { @@ -2486,13 +2246,11 @@ void goo(string s = "Hello") } } """, -index: 1); - } + index: 1); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530109")] - public async Task TestNoGenerateConstantFieldIfNotAccessingLocal3() - { - await TestInRegularAndScriptAsync( + public Task TestNoGenerateConstantFieldIfNotAccessingLocal3() + => TestInRegularAndScriptAsync( """ class C { @@ -2516,13 +2274,11 @@ void goo(string s = "Hello") } } """, -index: 2); - } + index: 2); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530109")] - public async Task TestNoGenerateConstantFieldIfNotAccessingLocal4() - { - await TestInRegularAndScriptAsync( + public Task TestNoGenerateConstantFieldIfNotAccessingLocal4() + => TestInRegularAndScriptAsync( """ class C { @@ -2546,13 +2302,11 @@ void goo(string s = "Hello") } } """, -index: 3); - } + index: 3); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/606347")] - public async Task InsertNeededCast1() - { - await TestInRegularAndScriptAsync( + public Task InsertNeededCast1() + => TestInRegularAndScriptAsync( """ using System; @@ -2596,12 +2350,10 @@ static void Main() """, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/606347")] - public async Task InsertNeededCast1NotVar() - { - await TestInRegularAndScriptAsync( + public Task InsertNeededCast1NotVar() + => TestInRegularAndScriptAsync( """ using System; @@ -2643,12 +2395,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/606347"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/714632")] - public async Task InsertNeededCast2() - { - await TestInRegularAndScriptAsync( + public Task InsertNeededCast2() + => TestInRegularAndScriptAsync( """ using System; @@ -2681,12 +2431,10 @@ static void Main() static void Goo(Func p, Func q, int r, int s) { Console.WriteLine(2); } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546512")] - public async Task TestInSwitchSection() - { - await TestInRegularAndScriptAsync( + public Task TestInSwitchSection() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -2718,13 +2466,11 @@ int Main(int i) } } """, -index: 2); - } + index: 2); [Fact] - public async Task TestInSwitchSection_AllOccurencesMultiStatement() - { - await TestInRegularAndScriptAsync( + public Task TestInSwitchSection_AllOccurencesMultiStatement() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -2760,13 +2506,11 @@ int Main(int i) } } """, -index: 3); - } + index: 3); [Fact] - public async Task TestInSwitchSection_AllOccurencesDifferentSections() - { - await TestInRegularAndScriptAsync( + public Task TestInSwitchSection_AllOccurencesDifferentSections() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -2802,13 +2546,11 @@ int Main(int i) } } """, -index: 3); - } + index: 3); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530480")] - public async Task TestLambdaParameter1() - { - await TestInRegularAndScriptAsync( + public Task TestLambdaParameter1() + => TestInRegularAndScriptAsync( """ using System; @@ -2835,13 +2577,11 @@ static void Main(string[] args) } } """, -options: ImplicitTypingEverywhere()); - } + options: ImplicitTypingEverywhere()); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530480")] - public async Task TestLambdaParameter2() - { - await TestInRegularAndScriptAsync( + public Task TestLambdaParameter2() + => TestInRegularAndScriptAsync( """ using System; @@ -2868,13 +2608,11 @@ static void Main(string[] args) } } """, -options: ImplicitTypingEverywhere()); - } + options: ImplicitTypingEverywhere()); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530480")] - public async Task TestLambdaParameter3() - { - await TestInRegularAndScriptAsync( + public Task TestLambdaParameter3() + => TestInRegularAndScriptAsync( """ using System; @@ -2901,13 +2639,11 @@ static void Main(string[] args) } } """, -options: ImplicitTypingEverywhere()); - } + options: ImplicitTypingEverywhere()); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530480")] - public async Task TestLambdaParameter4() - { - await TestInRegularAndScriptAsync( + public Task TestLambdaParameter4() + => TestInRegularAndScriptAsync( """ using System; @@ -2934,12 +2670,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530480")] - public async Task TestLambdaParameter5() - { - await TestInRegularAndScriptAsync( + public Task TestLambdaParameter5() + => TestInRegularAndScriptAsync( """ using System; @@ -2966,12 +2700,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530721")] - public async Task TestIntroVarInAction1() - { - await TestInRegularAndScriptAsync( + public Task TestIntroVarInAction1() + => TestInRegularAndScriptAsync( """ using System; @@ -2997,12 +2729,10 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530919")] - public async Task TestNullableOfPointerType() - { - await TestInRegularAndScriptAsync( + public Task TestNullableOfPointerType() + => TestInRegularAndScriptAsync( """ using System; @@ -3026,13 +2756,11 @@ static void Main() } } """, -options: ImplicitTypingEverywhere()); - } + options: ImplicitTypingEverywhere()); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530919")] - public async Task TestNullableOfPointerTypeNotVar() - { - await TestInRegularAndScriptAsync( + public Task TestNullableOfPointerTypeNotVar() + => TestInRegularAndScriptAsync( """ using System; @@ -3056,12 +2784,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/830885")] - public async Task TestIntroduceLocalRemovesUnnecessaryCast() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceLocalRemovesUnnecessaryCast() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -3087,13 +2813,11 @@ static void Main(string[] args) } } """, -options: ImplicitTypingEverywhere()); - } + options: ImplicitTypingEverywhere()); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/655498")] - public async Task HandleParenthesizedExpression() - { - await TestInRegularAndScriptAsync( + public Task HandleParenthesizedExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -3122,12 +2846,10 @@ void Goo() static Action Bar; } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682683")] - public async Task DoNotRemoveParenthesesIfOperatorPrecedenceWouldBeBroken() - { - await TestInRegularAndScriptAsync( + public Task DoNotRemoveParenthesesIfOperatorPrecedenceWouldBeBroken() + => TestInRegularAndScriptAsync( """ using System; @@ -3152,13 +2874,11 @@ static void Main() } } """, -index: 2); - } + index: 2); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/828108")] - public async Task UseNewSemanticModelForSimplification() - { - await TestInRegularAndScriptAsync( + public Task UseNewSemanticModelForSimplification() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -3191,13 +2911,11 @@ static void Main(string[] args) } } """, -options: ImplicitTypingEverywhere()); - } + options: ImplicitTypingEverywhere()); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/884961")] - public async Task TestInCollectionInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestInCollectionInitializer() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -3221,13 +2939,11 @@ void M() } } """, -options: ImplicitTypingEverywhere()); - } + options: ImplicitTypingEverywhere()); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/884961")] - public async Task TestInCollectionInitializerNoVar() - { - await TestInRegularAndScriptAsync( + public Task TestInCollectionInitializerNoVar() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -3251,12 +2967,10 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854662")] - public async Task TestInNestedCollectionInitializers() - { - await TestInRegularAndScriptAsync( + public Task TestInNestedCollectionInitializers() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -3284,13 +2998,11 @@ static int Main(string[] args) } } """, -options: ImplicitTypingEverywhere()); - } + options: ImplicitTypingEverywhere()); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/884961")] - public async Task TestInArrayInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestInArrayInitializer() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -3314,13 +3026,11 @@ void M() } } """, -options: ImplicitTypingEverywhere()); - } + options: ImplicitTypingEverywhere()); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/884961")] - public async Task TestInArrayInitializerWithoutVar() - { - await TestInRegularAndScriptAsync( + public Task TestInArrayInitializerWithoutVar() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -3344,12 +3054,10 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1022447")] - public async Task TestFormattingOfIntroduceLocal2() - { - await TestInRegularAndScriptAsync( + public Task TestFormattingOfIntroduceLocal2() + => TestInRegularAndScriptAsync( """ using System; class C @@ -3381,15 +3089,12 @@ void M() } } """, -index: 1, -options: ImplicitTypingEverywhere()); - } + index: 1, + options: ImplicitTypingEverywhere()); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939259")] - public async Task TestIntroduceLocalWithTriviaInMultiLineStatements() - { - var code = -""" + public Task TestIntroduceLocalWithTriviaInMultiLineStatements() + => TestInRegularAndScriptAsync(""" class C { void Goo() @@ -3399,10 +3104,7 @@ void Goo() : 2; } } -"""; - - var expected = -""" +""", """ class C { void Goo() @@ -3413,16 +3115,11 @@ void Goo() : 2; } } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 3); - } +""", index: 3); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939259")] - public async Task TestIntroduceLocalWithTriviaInMultiLineStatements2() - { - var code = -""" + public Task TestIntroduceLocalWithTriviaInMultiLineStatements2() + => TestInRegularAndScriptAsync(""" class C { void Goo() @@ -3432,10 +3129,7 @@ void Goo() : [|2|]; // TODO: comment } } -"""; - - var expected = -""" +""", """ class C { void Goo() @@ -3446,16 +3140,11 @@ void Goo() : V; // TODO: comment } } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 3); - } +""", index: 3); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064803")] - public async Task TestIntroduceLocalInStringInterpolation() - { - var code = -""" + public Task TestIntroduceLocalInStringInterpolation() + => TestInRegularAndScriptAsync(""" class C { void Goo() @@ -3463,10 +3152,7 @@ void Goo() var s = $"Alpha Beta { [|int.Parse("12345")|] } Gamma"; } } -"""; - - var expected = -""" +""", """ class C { void Goo() @@ -3475,15 +3161,11 @@ void Goo() var s = $"Alpha Beta { v } Gamma"; } } -"""; - - await TestInRegularAndScriptAsync(code, expected, options: ImplicitTypingEverywhere()); - } +""", options: ImplicitTypingEverywhere()); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1037057")] - public async Task TestIntroduceLocalWithBlankLine() - { - await TestInRegularAndScriptAsync(""" + public Task TestIntroduceLocalWithBlankLine() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -3507,12 +3189,10 @@ void M() } } """, options: ImplicitTypingEverywhere()); - } [Fact] - public async Task TestIntroduceLocalWithBlankLine_AllOccurencesMultiStatement() - { - await TestInRegularAndScriptAsync(""" + public Task TestIntroduceLocalWithBlankLine_AllOccurencesMultiStatement() + => TestInRegularAndScriptAsync(""" class C { void M() @@ -3538,7 +3218,6 @@ void M() } } """, options: ImplicitTypingEverywhere(), index: 1); - } [Fact] public Task TestIntroduceLocal_NullableType_FlowStateNonNull() @@ -3611,9 +3290,8 @@ void M2(string? s) """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1065661")] - public async Task TestIntroduceVariableTextDoesntSpanLines1() - { - await TestSmartTagTextAsync( + public Task TestIntroduceVariableTextDoesntSpanLines1() + => TestSmartTagTextAsync( """ class C { @@ -3629,13 +3307,11 @@ void M() string.Format(FeaturesResources.Introduce_local_constant_for_0, """ @"a b c" """), -index: 2); - } + index: 2); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1065661")] - public async Task TestIntroduceVariableTextDoesntSpanLines2() - { - await TestSmartTagTextAsync( + public Task TestIntroduceVariableTextDoesntSpanLines2() + => TestSmartTagTextAsync( """ class C { @@ -3651,13 +3327,10 @@ void M() string.Format(FeaturesResources.Introduce_constant_for_0, """ $@"a b c" """)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097147")] - public async Task TestSmartNameForNullablesInConditionalAccessExpressionContext() - { - var code = -""" + public Task TestSmartNameForNullablesInConditionalAccessExpressionContext() + => TestInRegularAndScriptAsync(""" using System; class C { @@ -3666,10 +3339,7 @@ static void Goo(string s) var l = [|s?.Length|] ?? 0; } } -"""; - - var expected = -""" +""", """ using System; class C { @@ -3679,16 +3349,11 @@ static void Goo(string s) var l = length ?? 0; } } -"""; - - await TestInRegularAndScriptAsync(code, expected, options: ImplicitTypingEverywhere()); - } +""", options: ImplicitTypingEverywhere()); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097147")] - public async Task TestSmartNameForNullablesInConditionalAccessExpressionContext2() - { - var code = -""" + public Task TestSmartNameForNullablesInConditionalAccessExpressionContext2() + => TestInRegularAndScriptAsync(""" using System; class C { @@ -3697,10 +3362,7 @@ static void Goo(string s) var l = [|s?.ToLower()|] ?? string.Empty; } } -"""; - - var expected = -""" +""", """ using System; class C { @@ -3710,16 +3372,11 @@ static void Goo(string s) var l = v ?? string.Empty; } } -"""; - - await TestInRegularAndScriptAsync(code, expected, options: ImplicitTypingEverywhere()); - } +""", options: ImplicitTypingEverywhere()); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097147")] - public async Task TestSmartNameForNullablesInConditionalAccessExpressionContext3() - { - var code = -""" + public Task TestSmartNameForNullablesInConditionalAccessExpressionContext3() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -3737,10 +3394,7 @@ class B { public int Length { get; set; } } -"""; - - var expected = -""" +""", """ using System; class Program { @@ -3759,16 +3413,11 @@ class B { public int Length { get; set; } } -"""; - - await TestInRegularAndScriptAsync(code, expected, options: ImplicitTypingEverywhere()); - } +""", options: ImplicitTypingEverywhere()); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097147")] - public async Task TestSmartNameForNullablesInConditionalAccessExpressionContext4() - { - var code = -""" + public Task TestSmartNameForNullablesInConditionalAccessExpressionContext4() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -3787,10 +3436,7 @@ class B int age; public int GetAge() { return age; } } -"""; - - var expected = -""" +""", """ using System; class Program { @@ -3810,26 +3456,18 @@ class B int age; public int GetAge() { return age; } } -"""; - - await TestInRegularAndScriptAsync(code, expected, options: ImplicitTypingEverywhere()); - } +""", options: ImplicitTypingEverywhere()); [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/528")] - public async Task TestIntroduceFieldInExpressionBodiedMethod() - { - var code = -""" + public Task TestIntroduceFieldInExpressionBodiedMethod() + => TestInRegularAndScriptAsync(""" using System; class T { int m; int M1() => [|1|] + 2 + 3 + m; } -"""; - - var expected = -""" +""", """ using System; class T { @@ -3837,26 +3475,18 @@ class T int m; int M1() => V + 2 + 3 + m; } -"""; - - await TestInRegularAndScriptAsync(code, expected); - } +"""); [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/528")] - public async Task TestIntroduceLocalInExpressionBodiedNonVoidMethod() - { - var code = -""" + public Task TestIntroduceLocalInExpressionBodiedNonVoidMethod() + => TestInRegularAndScriptAsync(""" using System; class T { int m; int M1() => [|1|] + 2 + 3 + m; } -"""; - - var expected = -""" +""", """ using System; class T { @@ -3867,16 +3497,11 @@ int M1() return V + 2 + 3 + m; } } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } +""", index: 2); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31012")] - public async Task TestIntroduceLocalInArgumentList() - { - var code = - """ + public Task TestIntroduceLocalInArgumentList() + => TestInRegularAndScriptAsync(""" using System; public interface IResolver { int Resolve(); } public class Test @@ -3887,10 +3512,7 @@ private void test(Func factory) [|x.Resolve()|] )); } - """; - - var expected = - """ + """, """ using System; public interface IResolver { int Resolve(); } public class Test @@ -3905,26 +3527,18 @@ private void test(Func factory) ); }); } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 0); - } + """, index: 0); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24807")] - public async Task TestIntroduceLocalInExpressionBodiedVoidMethod() - { - var code = -""" + public Task TestIntroduceLocalInExpressionBodiedVoidMethod() + => TestInRegularAndScriptAsync(""" using System; class T { int m; void M1() => Console.WriteLine([|1|] + 2 + 3 + m); } -"""; - - var expected = -""" +""", """ using System; class T { @@ -3935,26 +3549,18 @@ void M1() Console.WriteLine(V + 2 + 3 + m); } } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } +""", index: 2); [Fact] - public async Task TestIntroduceFieldInExpressionBodiedConstructor() - { - var code = -""" + public Task TestIntroduceFieldInExpressionBodiedConstructor() + => TestInRegularAndScriptAsync(""" using System; class T { int m; T() => Console.WriteLine([|1|] + 2 + 3 + m); } -"""; - - var expected = -""" +""", """ using System; class T { @@ -3962,26 +3568,18 @@ class T int m; T() => Console.WriteLine(V + 2 + 3 + m); } -"""; - - await TestInRegularAndScriptAsync(code, expected); - } +"""); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24807")] - public async Task TestIntroduceLocalInExpressionBodiedConstructor() - { - var code = -""" + public Task TestIntroduceLocalInExpressionBodiedConstructor() + => TestInRegularAndScriptAsync(""" using System; class T { int m; T() => Console.WriteLine([|1|] + 2 + 3 + m); } -"""; - - var expected = -""" +""", """ using System; class T { @@ -3992,26 +3590,18 @@ class T Console.WriteLine(V + 2 + 3 + m); } } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } +""", index: 2); [Fact] - public async Task TestIntroduceFieldInExpressionBodiedDestructor() - { - var code = -""" + public Task TestIntroduceFieldInExpressionBodiedDestructor() + => TestInRegularAndScriptAsync(""" using System; class T { int m; ~T() => Console.WriteLine([|1|] + 2 + 3 + m); } -"""; - - var expected = -""" +""", """ using System; class T { @@ -4019,26 +3609,18 @@ class T int m; ~T() => Console.WriteLine(V + 2 + 3 + m); } -"""; - - await TestInRegularAndScriptAsync(code, expected); - } +"""); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/24807")] - public async Task TestIntroduceLocalInExpressionBodiedDestructor() - { - var code = -""" + public Task TestIntroduceLocalInExpressionBodiedDestructor() + => TestInRegularAndScriptAsync(""" using System; class T { int m; ~T() => Console.WriteLine([|1|] + 2 + 3 + m); } -"""; - - var expected = -""" +""", """ using System; class T { @@ -4049,16 +3631,11 @@ class T Console.WriteLine(V + 2 + 3 + m); } } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } +""", index: 2); [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/528")] - public async Task TestIntroduceFieldInExpressionBodiedOperator() - { - var code = -""" + public Task TestIntroduceFieldInExpressionBodiedOperator() + => TestInRegularAndScriptAsync(""" using System; class Complex { @@ -4070,10 +3647,7 @@ private Complex Add(int b) throw new NotImplementedException(); } } -"""; - - var expected = -""" +""", """ using System; class Complex { @@ -4086,16 +3660,11 @@ private Complex Add(int b) throw new NotImplementedException(); } } -"""; - - await TestInRegularAndScriptAsync(code, expected); - } +"""); [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/528")] - public async Task TestIntroduceLocalInExpressionBodiedOperator() - { - var code = -""" + public Task TestIntroduceLocalInExpressionBodiedOperator() + => TestInRegularAndScriptAsync(""" using System; class Complex { @@ -4107,10 +3676,7 @@ private Complex Add(int b) throw new NotImplementedException(); } } -"""; - - var expected = -""" +""", """ using System; class Complex { @@ -4126,16 +3692,11 @@ private Complex Add(int b) throw new NotImplementedException(); } } -"""; - - await TestInRegularAndScriptAsync(code, expected, options: ImplicitTypingEverywhere()); - } +""", options: ImplicitTypingEverywhere()); [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/528")] - public async Task TestIntroduceFieldInExpressionBodiedConversionOperator() - { - var code = -""" + public Task TestIntroduceFieldInExpressionBodiedConversionOperator() + => TestInRegularAndScriptAsync(""" using System; public struct DBBool { @@ -4149,10 +3710,7 @@ public struct DBBool public static implicit operator DBBool(bool x) => x ? new DBBool([|1|]) : dbFalse; } -"""; - - var expected = -""" +""", """ using System; public struct DBBool { @@ -4167,16 +3725,11 @@ public struct DBBool public static implicit operator DBBool(bool x) => x ? new DBBool(Value) : dbFalse; } -"""; - - await TestInRegularAndScriptAsync(code, expected); - } +"""); [Fact] - public async Task TestIntroduceLocalInExpressionBodiedConversionOperator() - { - var code = -""" + public Task TestIntroduceLocalInExpressionBodiedConversionOperator() + => TestInRegularAndScriptAsync(""" using System; public struct DBBool { @@ -4190,10 +3743,7 @@ public struct DBBool public static implicit operator DBBool(bool x) => x ? new DBBool([|1|]) : dbFalse; } -"""; - - var expected = -""" +""", """ using System; public struct DBBool { @@ -4211,25 +3761,17 @@ public static implicit operator DBBool(bool x) return x ? new DBBool(Value) : dbFalse; } } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } +""", index: 2); [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/528")] - public async Task TestIntroduceFieldInExpressionBodiedProperty() - { - var code = -""" + public Task TestIntroduceFieldInExpressionBodiedProperty() + => TestInRegularAndScriptAsync(""" using System; class T { int M1 => [|1|] + 2; } -"""; - - var expected = -""" +""", """ using System; class T { @@ -4237,25 +3779,17 @@ class T int M1 => V + 2; } -"""; - - await TestInRegularAndScriptAsync(code, expected); - } +"""); [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/528")] - public async Task TestIntroduceLocalInExpressionBodiedProperty() - { - var code = -""" + public Task TestIntroduceLocalInExpressionBodiedProperty() + => TestInRegularAndScriptAsync(""" using System; class T { int M1 => [|1|] + 2; } -"""; - - var expected = -""" +""", """ using System; class T { @@ -4268,26 +3802,18 @@ int M1 } } } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } +""", index: 2); [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/528")] - public async Task TestIntroduceFieldInExpressionBodiedIndexer() - { - var code = -""" + public Task TestIntroduceFieldInExpressionBodiedIndexer() + => TestInRegularAndScriptAsync(""" using System; class SampleCollection { private T[] arr = new T[100]; public T this[int i] => i > [|0|] ? arr[i + 1] : arr[i + 2]; } -"""; - - var expected = -""" +""", """ using System; class SampleCollection { @@ -4295,26 +3821,18 @@ class SampleCollection private T[] arr = new T[100]; public T this[int i] => i > V ? arr[i + 1] : arr[i + 2]; } -"""; - - await TestInRegularAndScriptAsync(code, expected); - } +"""); [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/528")] - public async Task TestIntroduceLocalInExpressionBodiedIndexer() - { - var code = -""" + public Task TestIntroduceLocalInExpressionBodiedIndexer() + => TestInRegularAndScriptAsync(""" using System; class SampleCollection { private T[] arr = new T[100]; public T this[int i] => i > 0 ? arr[[|i + 1|]] : arr[i + 2]; } -"""; - - var expected = -""" +""", """ using System; class SampleCollection { @@ -4328,16 +3846,11 @@ public T this[int i] } } } -"""; - - await TestInRegularAndScriptAsync(code, expected, options: ImplicitTypingEverywhere()); - } +""", options: ImplicitTypingEverywhere()); [Fact] - public async Task TestIntroduceLocalWithTargetTypedNew1() - { - var code = - """ + public Task TestIntroduceLocalWithTargetTypedNew1() + => TestInRegularAndScriptAsync(""" using System; class SampleType { @@ -4353,10 +3866,7 @@ private int Sum(Numbers numbers) private class Numbers {} } - """; - - var expected = - """ + """, """ using System; class SampleType { @@ -4373,19 +3883,14 @@ private int Sum(Numbers numbers) private class Numbers {} } - """; - - await TestInRegularAndScriptAsync(code, expected, options: new(GetLanguage()) + """, options: new(GetLanguage()) { { CSharpCodeStyleOptions.ImplicitObjectCreationWhenTypeIsApparent, new CodeStyleOption2(true, NotificationOption2.Warning) }, }); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/77276")] - public async Task TestIntroduceLocalWithTargetTypedNew2() - { - var code = - """ + public Task TestIntroduceLocalWithTargetTypedNew2() + => TestInRegularAndScriptAsync(""" public static class Demo { public static void Test() @@ -4398,10 +3903,7 @@ public sealed class Class1 { public int Value { get; set; } } - """; - - var expected = - """ + """, """ public static class Demo { public static void Test() @@ -4415,18 +3917,14 @@ public sealed class Class1 { public int Value { get; set; } } - """; - - await TestInRegularAndScriptAsync(code, expected, options: new(GetLanguage()) + """, options: new(GetLanguage()) { { CSharpCodeStyleOptions.ImplicitObjectCreationWhenTypeIsApparent, new CodeStyleOption2(true, NotificationOption2.Warning) }, }); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/77428")] - public async Task TestIntroduceLocalWithTargetTypedNew1_CSharp8() - { - var code = + public Task TestIntroduceLocalWithTargetTypedNew1_CSharp8() + => TestInRegularAndScriptAsync( """ using System; class SampleType @@ -4443,10 +3941,7 @@ private int Sum(Numbers numbers) private class Numbers {} } - """; - - var expected = - """ + """, """ using System; class SampleType { @@ -4463,22 +3958,16 @@ private int Sum(Numbers numbers) private class Numbers {} } - """; - - await TestInRegularAndScriptAsync( - code, expected, + """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8), options: new(GetLanguage()) { { CSharpCodeStyleOptions.ImplicitObjectCreationWhenTypeIsApparent, new CodeStyleOption2(true, NotificationOption2.Warning) }, }); - } [Fact] - public async Task TestIntroduceFieldInExpressionBodiedPropertyGetter() - { - var code = -""" + public Task TestIntroduceFieldInExpressionBodiedPropertyGetter() + => TestInRegularAndScriptAsync(""" using System; class T { @@ -4487,10 +3976,7 @@ int M1 get => [|1|] + 2; } } -"""; - - var expected = -""" +""", """ using System; class T { @@ -4501,16 +3987,11 @@ int M1 get => V + 2; } } -"""; - - await TestInRegularAndScriptAsync(code, expected); - } +"""); [Fact] - public async Task TestIntroduceLocalInExpressionBodiedPropertyGetter() - { - var code = -""" + public Task TestIntroduceLocalInExpressionBodiedPropertyGetter() + => TestInRegularAndScriptAsync(""" using System; class T { @@ -4519,10 +4000,7 @@ int M1 get => [|1|] + 2; } } -"""; - - var expected = -""" +""", """ using System; class T { @@ -4535,16 +4013,11 @@ int M1 } } } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } +""", index: 2); [Fact] - public async Task TestIntroduceFieldInExpressionBodiedPropertySetter() - { - var code = -""" + public Task TestIntroduceFieldInExpressionBodiedPropertySetter() + => TestInRegularAndScriptAsync(""" using System; class T { @@ -4553,10 +4026,7 @@ int M1 set => Console.WriteLine([|1|] + 2); } } -"""; - - var expected = -""" +""", """ using System; class T { @@ -4567,16 +4037,11 @@ int M1 set => Console.WriteLine(V + 2); } } -"""; - - await TestInRegularAndScriptAsync(code, expected); - } +"""); [Fact] - public async Task TestIntroduceLocalInExpressionBodiedPropertySetter() - { - var code = -""" + public Task TestIntroduceLocalInExpressionBodiedPropertySetter() + => TestInRegularAndScriptAsync(""" using System; class T { @@ -4585,10 +4050,7 @@ int M1 set => Console.WriteLine([|1|] + 2); } } -"""; - - var expected = -""" +""", """ using System; class T { @@ -4601,16 +4063,11 @@ int M1 } } } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } +""", index: 2); [Fact] - public async Task TestIntroduceFieldInExpressionBodiedIndexerGetter() - { - var code = -""" + public Task TestIntroduceFieldInExpressionBodiedIndexerGetter() + => TestInRegularAndScriptAsync(""" using System; class T { @@ -4619,10 +4076,7 @@ int this[int i] get => [|1|] + 2; } } -"""; - - var expected = -""" +""", """ using System; class T { @@ -4633,16 +4087,11 @@ int this[int i] get => V + 2; } } -"""; - - await TestInRegularAndScriptAsync(code, expected); - } +"""); [Fact] - public async Task TestIntroduceLocalInExpressionBodiedIndexerGetter() - { - var code = -""" + public Task TestIntroduceLocalInExpressionBodiedIndexerGetter() + => TestInRegularAndScriptAsync(""" using System; class T { @@ -4651,10 +4100,7 @@ int this[int i] get => [|1|] + 2; } } -"""; - - var expected = -""" +""", """ using System; class T { @@ -4667,16 +4113,11 @@ int this[int i] } } } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } +""", index: 2); [Fact] - public async Task TestIntroduceFieldInExpressionBodiedIndexerSetter() - { - var code = -""" + public Task TestIntroduceFieldInExpressionBodiedIndexerSetter() + => TestInRegularAndScriptAsync(""" using System; class T { @@ -4685,10 +4126,7 @@ int this[int i] set => Console.WriteLine([|1|] + 2); } } -"""; - - var expected = -""" +""", """ using System; class T { @@ -4699,16 +4137,11 @@ int this[int i] set => Console.WriteLine(V + 2); } } -"""; - - await TestInRegularAndScriptAsync(code, expected); - } +"""); [Fact] - public async Task TestIntroduceLocalInExpressionBodiedIndexerSetter() - { - var code = -""" + public Task TestIntroduceLocalInExpressionBodiedIndexerSetter() + => TestInRegularAndScriptAsync(""" using System; class T { @@ -4717,10 +4150,7 @@ int this[int i] set => Console.WriteLine([|1|] + 2); } } -"""; - - var expected = -""" +""", """ using System; class T { @@ -4733,16 +4163,11 @@ int this[int i] } } } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } +""", index: 2); [Fact] - public async Task TestIntroduceFieldInExpressionBodiedEventAdder() - { - var code = -""" + public Task TestIntroduceFieldInExpressionBodiedEventAdder() + => TestInRegularAndScriptAsync(""" using System; class T { @@ -4752,10 +4177,7 @@ event EventHandler E remove { } } } -"""; - - var expected = -""" +""", """ using System; class T { @@ -4767,16 +4189,11 @@ event EventHandler E remove { } } } -"""; - - await TestInRegularAndScriptAsync(code, expected); - } +"""); [Fact] - public async Task TestIntroduceLocalInExpressionBodiedEventAdder() - { - var code = -""" + public Task TestIntroduceLocalInExpressionBodiedEventAdder() + => TestInRegularAndScriptAsync(""" using System; class T { @@ -4786,10 +4203,7 @@ event EventHandler E remove { } } } -"""; - - var expected = -""" +""", """ using System; class T { @@ -4803,16 +4217,11 @@ event EventHandler E remove { } } } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } +""", index: 2); [Fact] - public async Task TestIntroduceFieldInExpressionBodiedEventRemover() - { - var code = -""" + public Task TestIntroduceFieldInExpressionBodiedEventRemover() + => TestInRegularAndScriptAsync(""" using System; class T { @@ -4822,10 +4231,7 @@ event EventHandler E remove => Console.WriteLine([|1|] + 2); } } -"""; - - var expected = -""" +""", """ using System; class T { @@ -4837,16 +4243,11 @@ event EventHandler E remove => Console.WriteLine(V + 2); } } -"""; - - await TestInRegularAndScriptAsync(code, expected); - } +"""); [Fact] - public async Task TestIntroduceLocalInExpressionBodiedEventRemover() - { - var code = -""" + public Task TestIntroduceLocalInExpressionBodiedEventRemover() + => TestInRegularAndScriptAsync(""" using System; class T { @@ -4856,10 +4257,7 @@ event EventHandler E remove => Console.WriteLine([|1|] + 2); } } -"""; - - var expected = -""" +""", """ using System; class T { @@ -4873,16 +4271,11 @@ event EventHandler E } } } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } +""", index: 2); [Fact] - public async Task TestIntroduceFieldInExpressionBodiedLocalFunction() - { - var code = -""" + public Task TestIntroduceFieldInExpressionBodiedLocalFunction() + => TestInRegularAndScriptAsync(""" using System; class T { @@ -4891,10 +4284,7 @@ void M() int F() => [|1|] + 2; } } -"""; - - var expected = -""" +""", """ using System; class T { @@ -4905,16 +4295,11 @@ void M() int F() => V + 2; } } -"""; - - await TestInRegularAndScriptAsync(code, expected); - } +"""); [Fact] - public async Task TestIntroduceLocalInExpressionBodiedNonVoidLocalFunction() - { - var code = -""" + public Task TestIntroduceLocalInExpressionBodiedNonVoidLocalFunction() + => TestInRegularAndScriptAsync(""" using System; class T { @@ -4923,10 +4308,7 @@ void M() int F() => [|1|] + 2; } } -"""; - - var expected = -""" +""", """ using System; class T { @@ -4939,16 +4321,11 @@ int F() } } } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } +""", index: 2); [Fact] - public async Task TestIntroduceLocalInExpressionBodiedVoidLocalFunction() - { - var code = -""" + public Task TestIntroduceLocalInExpressionBodiedVoidLocalFunction() + => TestInRegularAndScriptAsync(""" using System; class T { @@ -4957,10 +4334,7 @@ void M() void F() => Console.WriteLine([|1|] + 2); } } -"""; - - var expected = -""" +""", """ using System; class T { @@ -4973,16 +4347,11 @@ void F() } } } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } +""", index: 2); [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/528")] - public async Task TestTrailingTriviaOnExpressionBodiedMethodRewrites() - { - var code = -""" + public Task TestTrailingTriviaOnExpressionBodiedMethodRewrites() + => TestInRegularAndScriptAsync(""" using System; class T { @@ -4991,10 +4360,7 @@ class T // rewrite should preserve newline above this. void Cat() { } } -"""; - - var expected = -""" +""", """ using System; class T { @@ -5007,26 +4373,18 @@ int M1() // rewrite should preserve newline above this. void Cat() { } } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } +""", index: 2); [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/528")] - public async Task TestLeadingTriviaOnExpressionBodiedMethodRewrites() - { - var code = -""" + public Task TestLeadingTriviaOnExpressionBodiedMethodRewrites() + => TestInRegularAndScriptAsync(""" using System; class T { /*not moved*/ int M1() => 1 + 2 + /*not moved*/ [|3|]; } -"""; - - var expected = -""" +""", """ using System; class T { @@ -5037,26 +4395,18 @@ int M1() return 1 + 2 + /*not moved*/ V; } } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } +""", index: 2); [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/528")] - public async Task TestTriviaAroundArrowTokenInExpressionBodiedMemberSyntax() - { - var code = -""" + public Task TestTriviaAroundArrowTokenInExpressionBodiedMemberSyntax() + => TestInRegularAndScriptAsync(""" using System; class T { // comment int M1() /*c1*/ => /*c2*/ 1 + 2 + /*c3*/ [|3|]; } -"""; - - var expected = -""" +""", """ using System; class T { @@ -5067,17 +4417,12 @@ int M1() /*c1*/ /*c2*/ return 1 + 2 + /*c3*/ V; } } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } +""", index: 2); [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/528")] [WorkItem("http://github.com/dotnet/roslyn/issues/971")] - public async Task TestIntroduceLocalInExpressionBodiedMethodWithBlockBodiedAnonymousMethodExpression() - { - var code = -""" + public Task TestIntroduceLocalInExpressionBodiedMethodWithBlockBodiedAnonymousMethodExpression() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -5086,10 +4431,7 @@ Func Y() => delegate (int x) return [|9|]; }; } -"""; - - var expected = -""" +""", """ using System; class TestClass { @@ -5099,42 +4441,29 @@ Func Y() => delegate (int x) return V; }; } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } +""", index: 2); [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/528")] [WorkItem("http://github.com/dotnet/roslyn/issues/971")] - public async Task TestIntroduceLocalInExpressionBodiedMethodWithSingleLineBlockBodiedAnonymousMethodExpression() - { - var code = -""" + public Task TestIntroduceLocalInExpressionBodiedMethodWithSingleLineBlockBodiedAnonymousMethodExpression() + => TestInRegularAndScriptAsync(""" using System; class TestClass { Func Y() => delegate (int x) { return [|9|]; }; } -"""; - - var expected = -""" +""", """ using System; class TestClass { Func Y() => delegate (int x) { const int {|Rename:V|} = 9; return V; }; } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } +""", index: 2); [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/528")] [WorkItem("http://github.com/dotnet/roslyn/issues/971")] - public async Task TestIntroduceLocalInExpressionBodiedMethodWithBlockBodiedSimpleLambdaExpression() - { - var code = -""" + public Task TestIntroduceLocalInExpressionBodiedMethodWithBlockBodiedSimpleLambdaExpression() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -5143,10 +4472,7 @@ Func Y() => f => return f * [|9|]; }; } -"""; - - var expected = -""" +""", """ using System; class TestClass { @@ -5156,25 +4482,17 @@ Func Y() => f => return f * V; }; } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } +""", index: 2); [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/528")] - public async Task TestIntroduceLocalInExpressionBodiedMethodWithExpressionBodiedSimpleLambdaExpression() - { - var code = -""" + public Task TestIntroduceLocalInExpressionBodiedMethodWithExpressionBodiedSimpleLambdaExpression() + => TestInRegularAndScriptAsync(""" using System; class TestClass { Func Y() => f => f * [|9|]; } -"""; - - var expected = -""" +""", """ using System; class TestClass { @@ -5184,17 +4502,12 @@ Func Y() => f => return f * V; }; } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } +""", index: 2); [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/528")] [WorkItem("http://github.com/dotnet/roslyn/issues/971")] - public async Task TestIntroduceLocalInExpressionBodiedMethodWithBlockBodiedParenthesizedLambdaExpression() - { - var code = -""" + public Task TestIntroduceLocalInExpressionBodiedMethodWithBlockBodiedParenthesizedLambdaExpression() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -5203,10 +4516,7 @@ Func Y() => (f) => return f * [|9|]; }; } -"""; - - var expected = -""" +""", """ using System; class TestClass { @@ -5216,25 +4526,17 @@ Func Y() => (f) => return f * V; }; } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } +""", index: 2); [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/528")] - public async Task TestIntroduceLocalInExpressionBodiedMethodWithExpressionBodiedParenthesizedLambdaExpression() - { - var code = -""" + public Task TestIntroduceLocalInExpressionBodiedMethodWithExpressionBodiedParenthesizedLambdaExpression() + => TestInRegularAndScriptAsync(""" using System; class TestClass { Func Y() => (f) => f * [|9|]; } -"""; - - var expected = -""" +""", """ using System; class TestClass { @@ -5244,17 +4546,12 @@ Func Y() => (f) => return f * V; }; } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } +""", index: 2); [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/528")] [WorkItem("http://github.com/dotnet/roslyn/issues/971")] - public async Task TestIntroduceLocalInExpressionBodiedMethodWithBlockBodiedAnonymousMethodExpressionInMethodArgs() - { - var code = -""" + public Task TestIntroduceLocalInExpressionBodiedMethodWithBlockBodiedAnonymousMethodExpressionInMethodArgs() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -5263,10 +4560,7 @@ class TestClass return [|8|]; }); } -"""; - - var expected = -""" +""", """ using System; class TestClass { @@ -5276,16 +4570,11 @@ class TestClass return V; }); } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 2); - } +""", index: 2); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/976")] - public async Task TestNoConstantForInterpolatedStrings() - { - var code = -""" + public Task TestNoConstantForInterpolatedStrings() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -5294,10 +4583,7 @@ static void Test(string[] args) Console.WriteLine([|$"{DateTime.Now.ToString()}Text{args[0]}"|]); } } -"""; - - var expected = -""" +""", """ using System; class TestClass { @@ -5307,16 +4593,11 @@ static void Test(string[] args) Console.WriteLine(value); } } -"""; - - await TestInRegularAndScriptAsync(code, expected, options: ImplicitTypingEverywhere()); - } +""", options: ImplicitTypingEverywhere()); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/976")] - public async Task TestConstantForInterpolatedStrings() - { - var code = -""" + public Task TestConstantForInterpolatedStrings() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -5326,10 +4607,7 @@ static void Test(string[] args) Console.WriteLine($"Text{{s}}"); } } -"""; - - var expected = -""" +""", """ using System; class TestClass { @@ -5341,16 +4619,11 @@ static void Test(string[] args) Console.WriteLine(Value); } } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 1, options: ImplicitTypingEverywhere()); - } +""", index: 1, options: ImplicitTypingEverywhere()); [Fact] - public async Task TestConstantForInterpolatedStringsNested() - { - var code = - """ + public Task TestConstantForInterpolatedStringsNested() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -5360,10 +4633,7 @@ static void Test(string[] args) Console.WriteLine($"{"Level 5"} {"Number 3"}"); } } - """; - - var expected = -""" + """, """ using System; class TestClass { @@ -5375,16 +4645,11 @@ static void Test(string[] args) Console.WriteLine(Value); } } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 1, options: ImplicitTypingEverywhere()); - } +""", index: 1, options: ImplicitTypingEverywhere()); [Fact] - public async Task TestConstantForInterpolatedStringsInvalid() - { - var code = -""" + public Task TestConstantForInterpolatedStringsInvalid() + => TestInRegularAndScriptAsync(""" using System; class TestClass { @@ -5394,10 +4659,7 @@ static void Test(string[] args) Console.WriteLine($"Text{0}"); } } -"""; - - var expected = -""" +""", """ using System; class TestClass { @@ -5408,15 +4670,11 @@ static void Test(string[] args) Console.WriteLine(value); } } -"""; - - await TestInRegularAndScriptAsync(code, expected, index: 1, options: ImplicitTypingEverywhere()); - } +""", index: 1, options: ImplicitTypingEverywhere()); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/909152")] - public async Task TestMissingOnNullLiteral() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnNullLiteral() + => TestMissingInRegularAndScriptAsync( """ class C1 { @@ -5435,13 +4693,10 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130990")] - public async Task InParentConditionalAccessExpressions() - { - var code = -""" + public Task InParentConditionalAccessExpressions() + => TestInRegularAndScriptAsync(""" using System; class C { @@ -5451,10 +4706,7 @@ public T F(T x) return x; } } -"""; - - var expected = -""" +""", """ using System; class C { @@ -5465,16 +4717,11 @@ public T F(T x) return x; } } -"""; - - await TestInRegularAndScriptAsync(code, expected, options: ImplicitTypingEverywhere()); - } +""", options: ImplicitTypingEverywhere()); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130990")] - public async Task InParentConditionalAccessExpression2() - { - var code = -""" + public Task InParentConditionalAccessExpression2() + => TestInRegularAndScriptAsync(""" using System; class C { @@ -5484,10 +4731,7 @@ public T F(T x) return x; } } -"""; - - var expected = -""" +""", """ using System; class C { @@ -5498,16 +4742,12 @@ public T F(T x) return x; } } -"""; - - await TestInRegularAndScriptAsync(code, expected, options: ImplicitTypingEverywhere()); - } +""", options: ImplicitTypingEverywhere()); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130990")] [WorkItem("https://github.com/dotnet/roslyn/issues/3110")] - public async Task MissingAcrossMultipleParentConditionalAccessExpressions() - { - await TestMissingInRegularAndScriptAsync( + public Task MissingAcrossMultipleParentConditionalAccessExpressions() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5520,12 +4760,10 @@ public T F(T x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130990")] - public async Task MissingOnInvocationExpressionInParentConditionalAccessExpressions() - { - await TestMissingInRegularAndScriptAsync( + public Task MissingOnInvocationExpressionInParentConditionalAccessExpressions() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5538,12 +4776,10 @@ public T F(T x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130990")] - public async Task MissingOnMemberBindingExpressionInParentConditionalAccessExpressions() - { - await TestMissingInRegularAndScriptAsync( + public Task MissingOnMemberBindingExpressionInParentConditionalAccessExpressions() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -5555,7 +4791,6 @@ static void Test(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/3147")] public async Task HandleFormattableStringTargetTyping1() @@ -5634,18 +4869,14 @@ void M(IFormattable f) {} } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/936")] - public async Task InAutoPropertyInitializer() - { - var code = - """ + public Task InAutoPropertyInitializer() + => TestInRegularAndScriptAsync(""" using System; class C { int Prop1 { get; } = [|1 + 2|]; } - """; - var expected = - """ + """, """ using System; class C { @@ -5653,23 +4884,17 @@ class C int Prop1 { get; } = V; } - """; - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/936")] - public async Task InAutoPropertyInitializer2() - { - var code = - """ + public Task InAutoPropertyInitializer2() + => TestInRegularAndScriptAsync(""" using System; class C { public DateTime TimeStamp { get; } = [|DateTime.UtcNow|]; } - """; - var expected = - """ + """, """ using System; class C { @@ -5677,193 +4902,129 @@ class C public DateTime TimeStamp { get; } = utcNow; } - """; - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/936")] - public async Task BlockContextPreferredOverAutoPropertyInitializerContext() - { - var code = - """ + public Task BlockContextPreferredOverAutoPropertyInitializerContext() + => TestInRegularAndScriptAsync(""" using System; class C { Func X { get; } = a => { return [|7|]; }; } - """; - var expected = - """ + """, """ using System; class C { Func X { get; } = a => { const int {|Rename:V|} = 7; return V; }; } - """; - await TestInRegularAndScriptAsync(code, expected, index: 2); - } + """, index: 2); [Fact] - public async Task Tuple_TuplesDisabled() - { - var code = - """ + public Task Tuple_TuplesDisabled() + => TestAsync(""" class C { var i = [|(1, "hello")|].ToString(); } - """; - - var expected = - """ + """, """ class C { private static readonly (int, string) {|Rename:value|} = (1, "hello"); var i = value.ToString(); } - """; - - await TestAsync(code, expected, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); - } + """, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); [Fact] - public async Task ElementOfTuple() - { - var code = + public Task ElementOfTuple() + => TestInRegularAndScriptAsync( """ class C { var i = (1, [|"hello"|]).ToString(); } - """; - - var expected = - """ + """, """ class C { private const string {|Rename:V|} = "hello"; var i = (1, V).ToString(); } - """; - - await TestInRegularAndScriptAsync( - code, expected); - } + """); [Fact] - public async Task Tuple_IntroduceConstant() - { - var code = - """ + public Task Tuple_IntroduceConstant() + => TestInRegularAndScriptAsync(""" class C { var i = [|(1, "hello")|].ToString(); } - """; - - var expected = - """ + """, """ class C { private static readonly (int, string) {|Rename:value|} = (1, "hello"); var i = value.ToString(); } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task TupleWithNames_IntroduceConstant() - { - var code = - """ + public Task TupleWithNames_IntroduceConstant() + => TestInRegularAndScriptAsync(""" class C { var i = [|(a: 1, b: "hello")|].ToString(); } - """; - - var expected = - """ + """, """ class C { private static readonly (int a, string b) {|Rename:value|} = (a: 1, b: "hello"); var i = value.ToString(); } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task Tuple_IntroduceConstantForAllOccurrences() - { - var code = - """ + public Task Tuple_IntroduceConstantForAllOccurrences() + => TestInRegularAndScriptAsync(""" class C { var i = [|(1, "hello")|].ToString() + (1, "hello").ToString(); } - """; - - var expected = - """ + """, """ class C { private static readonly (int, string) {|Rename:value|} = (1, "hello"); var i = value.ToString() + value.ToString(); } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1); - } + """, index: 1); [Fact] - public async Task TupleWithNames_IntroduceConstantForAllOccurrences() - { - var code = - """ + public Task TupleWithNames_IntroduceConstantForAllOccurrences() + => TestInRegularAndScriptAsync(""" class C { var i = [|(a: 1, b: "hello")|].ToString() + (a: 1, b: "hello").ToString(); } - """; - - var expected = - """ + """, """ class C { private static readonly (int a, string b) {|Rename:value|} = (a: 1, b: "hello"); var i = value.ToString() + value.ToString(); } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1); - } + """, index: 1); [Fact] - public async Task TupleWithDifferentNames_IntroduceConstantForAllOccurrences() - { - var code = - """ + public Task TupleWithDifferentNames_IntroduceConstantForAllOccurrences() + => TestInRegularAndScriptAsync(""" class C { var i = [|(a: 1, b: "hello")|].ToString() + (c: 1, d: "hello").ToString(); } - """; - - var expected = - """ + """, """ class C { private static readonly (int a, string b) {|Rename:value|} = (a: 1, b: "hello"); var i = value.ToString() + (c: 1, d: "hello").ToString(); } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1); - } + """, index: 1); [Fact] public async Task TupleWithOneName_IntroduceConstantForAllOccurrences() @@ -5875,27 +5036,21 @@ class C var i = [|(a: 1, "hello")|].ToString() + (a: 1, "hello").ToString(); } """; - - var expected = - """ + await TestInRegularAndScriptAsync(code, """ class C { private static readonly (int a, string) {|Rename:value|} = (a: 1, "hello"); var i = value.ToString() + value.ToString(); } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1); + """, index: 1); // no third action available await TestActionCountAsync(code, count: 2, parameters: new TestParameters(TestOptions.Regular)); } [Fact] - public async Task Tuple_IntroduceLocalForAllOccurrences() - { - // Cannot refactor tuple as local constant - await TestActionCountAsync( + public Task Tuple_IntroduceLocalForAllOccurrences() + => TestActionCountAsync( """ class C { @@ -5906,12 +5061,10 @@ void Goo() } } """, count: 2); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11777")] - public async Task TestGenerateLocalConflictingName1() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateLocalConflictingName1() + => TestInRegularAndScriptAsync( """ class Program { @@ -5943,13 +5096,10 @@ void Method(MySpan span) } } """); - } [Fact] - public async Task TupleWithInferredName_LeaveExplicitName() - { - var code = - """ + public Task TupleWithInferredName_LeaveExplicitName() + => TestAsync(""" class C { static int y = 2; @@ -5959,10 +5109,7 @@ void M() var t = (a, x: [|C.y|]); } } - """; - - var expected = - """ + """, """ class C { static int y = 2; @@ -5973,16 +5120,11 @@ void M() var t = (a, x: y1); } } - """; - - await TestAsync(code, expected, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest)); - } + """, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest)); [Fact] - public async Task TupleWithInferredName_InferredNameBecomesExplicit() - { - var code = - """ + public Task TupleWithInferredName_InferredNameBecomesExplicit() + => TestAsync(""" class C { static int y = 2; @@ -5992,10 +5134,7 @@ void M() var t = (x, [|C.y|]); } } - """; - - var expected = - """ + """, """ class C { static int y = 2; @@ -6006,16 +5145,11 @@ void M() var t = (x, y: y1); } } - """; - - await TestAsync(code, expected, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest)); - } + """, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest)); [Fact] - public async Task TupleWithInferredName_AllOccurrences() - { - var code = - """ + public Task TupleWithInferredName_AllOccurrences() + => TestAsync(""" class C { static int y = 2; @@ -6026,10 +5160,7 @@ void M() var t2 = (C.y, x); } } - """; - - var expected = - """ + """, """ class C { static int y = 2; @@ -6041,15 +5172,11 @@ void M() var t2 = (y: y1, x); } } - """; - await TestAsync(code, expected, index: 1, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest)); - } + """, index: 1, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest)); [Fact] - public async Task TupleWithInferredName_NoDuplicateNames() - { - var code = - """ + public Task TupleWithInferredName_NoDuplicateNames() + => TestInRegularAndScriptAsync(""" class C { static int y = 2; @@ -6059,10 +5186,7 @@ void M() var t = (C.y, [|C.y|]); } } - """; - - var expected = - """ + """, """ class C { static int y = 2; @@ -6073,15 +5197,11 @@ void M() var t = (y: y1, y: y1); } } - """; - await TestInRegularAndScriptAsync(code, expected, index: 1); - } + """, index: 1); [Fact] - public async Task AnonymousTypeWithInferredName_LeaveExplicitName() - { - var code = - """ + public Task AnonymousTypeWithInferredName_LeaveExplicitName() + => TestInRegularAndScriptAsync(""" class C { static int y = 2; @@ -6091,10 +5211,7 @@ void M() var t = new { a, x= [|C.y|] }; } } - """; - - var expected = - """ + """, """ class C { static int y = 2; @@ -6105,16 +5222,11 @@ void M() var t = new { a, x= y1 }; } } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task AnonymousTypeWithInferredName_InferredNameBecomesExplicit() - { - var code = - """ + public Task AnonymousTypeWithInferredName_InferredNameBecomesExplicit() + => TestInRegularAndScriptAsync(""" class C { static int y = 2; @@ -6124,10 +5236,7 @@ void M() var t = new { x, [|C.y|] }; } } - """; - - var expected = - """ + """, """ class C { static int y = 2; @@ -6138,16 +5247,11 @@ void M() var t = new { x, y = y1 }; } } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact] - public async Task AnonymousTypeWithInferredName_NoDuplicatesAllowed() - { - var code = - """ + public Task AnonymousTypeWithInferredName_NoDuplicatesAllowed() + => TestInRegularAndScriptAsync(""" class C { static int y = 2; @@ -6157,10 +5261,7 @@ void M() var t = new { C.y, [|C.y|] }; // this is an error already } } - """; - - var expected = - """ + """, """ class C { static int y = 2; @@ -6170,17 +5271,12 @@ void M() int {|Rename:y1|} = C.y; var t = new { y = y1, y = y1 }; // this is an error already } - } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1); - } + } + """, index: 1); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31795")] - public async Task TestInAnonymousObjectMemberDeclaratorWithInferredType() - { - var code = - """ + public Task TestInAnonymousObjectMemberDeclaratorWithInferredType() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -6195,10 +5291,7 @@ void Test(Dictionary> d) }; } } - """; - - var expected = - """ + """, """ using System; using System.Collections.Generic; using System.Linq; @@ -6214,15 +5307,11 @@ void Test(Dictionary> d) }; } } - """; - - await TestInRegularAndScriptAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2423")] - public async Task TestPickNameBasedOnArgument1() - { - await TestInRegularAndScriptAsync( + public Task TestPickNameBasedOnArgument1() + => TestInRegularAndScriptAsync( """ class C { @@ -6258,12 +5347,10 @@ public TextSpan(int start, int length) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2423")] - public async Task TestPickNameBasedOnArgument2() - { - await TestInRegularAndScriptAsync( + public Task TestPickNameBasedOnArgument2() + => TestInRegularAndScriptAsync( """ class C { @@ -6299,12 +5386,10 @@ public TextSpan(int start, int length) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21665")] - public async Task TestPickNameBasedOnValueTupleFieldName1() - { - await TestAsync( + public Task TestPickNameBasedOnValueTupleFieldName1() + => TestAsync( """ using System; @@ -6328,12 +5413,10 @@ public C(string a, string b) } } """, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21665")] - public async Task TestPickNameBasedOnValueTupleFieldName2() - { - await TestAsync( + public Task TestPickNameBasedOnValueTupleFieldName2() + => TestAsync( """ using System; @@ -6358,12 +5441,10 @@ public C() } } """, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest), index: 0); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21665")] - public async Task TestPickNameBasedOnValueTupleFieldName3() - { - await TestAsync( + public Task TestPickNameBasedOnValueTupleFieldName3() + => TestAsync( """ using System; @@ -6387,12 +5468,10 @@ public C() } } """, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest), index: 2); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21373")] - public async Task TestInAttribute() - { - await TestInRegularAndScriptAsync( + public Task TestInAttribute() + => TestInRegularAndScriptAsync( """ public class C { @@ -6413,12 +5492,10 @@ public class C public string Bar { get; set; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21687")] - public async Task TestIfClassHasSameNameAsNamespace() - { - await TestInRegularAndScriptAsync( + public Task TestIfClassHasSameNameAsNamespace() + => TestInRegularAndScriptAsync( """ namespace C { @@ -6445,12 +5522,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/10123")] - public async Task TestSimpleParameterName() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleParameterName() + => TestInRegularAndScriptAsync( """ class C { @@ -6470,12 +5545,10 @@ void M(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/10123")] - public async Task TestSimpleParamterName_EmptySelection() - { - await TestMissingAsync( + public Task TestSimpleParamterName_EmptySelection() + => TestMissingAsync( """ class C { @@ -6485,13 +5558,11 @@ void M(int a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/10123")] [WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestSimpleParamterName_SmallSelection() - { - await TestInRegularAndScriptAsync( + public Task TestSimpleParamterName_SmallSelection() + => TestInRegularAndScriptAsync( """ class C { @@ -6511,12 +5582,10 @@ void M(int parameter) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/10123")] - public async Task TestFieldName_QualifiedWithThis() - { - await TestInRegularAndScriptAsync( + public Task TestFieldName_QualifiedWithThis() + => TestInRegularAndScriptAsync( """ class C { @@ -6538,12 +5607,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/10123")] - public async Task TestFieldName_QualifiedWithType() - { - await TestInRegularAndScriptAsync( + public Task TestFieldName_QualifiedWithType() + => TestInRegularAndScriptAsync( """ class C { @@ -6565,14 +5632,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/10123")] - public async Task TestFieldName_QualifiedWithType_TinySelection1() - { - // While one might argue that offering the refactoring in this case is not strictly correct the selection expression is - // unambiguous and there will be no other refactorings offered. Thus the cost of offering it very virtually non-existent. - await TestInRegularAndScriptAsync( + public Task TestFieldName_QualifiedWithType_TinySelection1() + => TestInRegularAndScriptAsync( """ class C { @@ -6594,12 +5657,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/10123")] - public async Task TestFieldName_QualifiedWithType_TinySelection2() - { - await TestMissingAsync( + public Task TestFieldName_QualifiedWithType_TinySelection2() + => TestMissingAsync( """ class C { @@ -6610,12 +5671,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/10123")] - public async Task TestFieldName_QualifiedWithType_TinySelection3() - { - await TestMissingAsync( + public Task TestFieldName_QualifiedWithType_TinySelection3() + => TestMissingAsync( """ class C { @@ -6626,12 +5685,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/10123")] - public async Task TestFieldName_QualifiedWithType_EmptySelection() - { - await TestMissingAsync( + public Task TestFieldName_QualifiedWithType_EmptySelection() + => TestMissingAsync( """ class C { @@ -6642,12 +5699,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25990")] - public async Task TestWithLineBreak() - { - await TestInRegularAndScriptAsync( + public Task TestWithLineBreak() + => TestInRegularAndScriptAsync( """ class C { @@ -6672,12 +5727,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25990")] - public async Task TestWithLineBreak_AfterExpression() - { - await TestInRegularAndScriptAsync( + public Task TestWithLineBreak_AfterExpression() + => TestInRegularAndScriptAsync( """ class C { @@ -6702,12 +5755,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25990")] - public async Task TestWithLineBreak_WithMultiLineComment() - { - await TestMissingAsync( + public Task TestWithLineBreak_WithMultiLineComment() + => TestMissingAsync( """ class C { @@ -6719,13 +5770,11 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25990")] [WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestWithLineBreak_WithSingleLineComments() - { - await TestInRegularAndScriptAsync( + public Task TestWithLineBreak_WithSingleLineComments() + => TestInRegularAndScriptAsync( """ class C { @@ -6751,14 +5800,10 @@ void M() } """ ); - } [Fact] - public async Task TestIntroduceLocalInCallRefExpression() - { - // This test indicates that ref-expressions are l-values and - // introduce local still introduces a local, not a ref-local. - await TestInRegularAndScriptAsync(""" + public Task TestIntroduceLocalInCallRefExpression() + => TestInRegularAndScriptAsync(""" class C { void M(int x) @@ -6780,13 +5825,10 @@ void M(int x) void M2(int p) { } } """); - } [Fact] - public async Task TestIntroduceLocalInRefCallRefExpression() - { - // Cannot extract expressions passed by ref - await TestMissingInRegularAndScriptAsync(""" + public Task TestIntroduceLocalInRefCallRefExpression() + => TestMissingInRegularAndScriptAsync(""" class C { void M(int x) @@ -6797,12 +5839,10 @@ void M(int x) void M2(ref int p) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28266")] - public async Task TestCaretAtEndOfExpression1() - { - await TestInRegularAndScriptAsync( + public Task TestCaretAtEndOfExpression1() + => TestInRegularAndScriptAsync( """ class C { @@ -6823,12 +5863,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28266")] - public async Task TestCaretAtEndOfExpression2() - { - await TestInRegularAndScriptAsync( + public Task TestCaretAtEndOfExpression2() + => TestInRegularAndScriptAsync( """ class C { @@ -6849,12 +5887,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28266")] - public async Task TestCaretAtEndOfExpression3() - { - await TestInRegularAndScriptAsync( + public Task TestCaretAtEndOfExpression3() + => TestInRegularAndScriptAsync( """ class C { @@ -6875,12 +5911,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28266")] - public async Task TestCaretAtEndOfExpression4() - { - await TestInRegularAndScriptAsync( + public Task TestCaretAtEndOfExpression4() + => TestInRegularAndScriptAsync( """ class C { @@ -6901,23 +5935,19 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27949")] - public async Task TestWhitespaceSpanInAssignment() - { - await TestMissingAsync(""" + public Task TestWhitespaceSpanInAssignment() + => TestMissingAsync(""" class C { int x = [| |] 0; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28665")] - public async Task TestWhitespaceSpanInAttribute() - { - await TestMissingAsync(""" + public Task TestWhitespaceSpanInAttribute() + => TestMissingAsync(""" class C { [Example( [| |] )] @@ -6926,12 +5956,10 @@ public void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28941")] - public async Task TestElementAccessExpression() - { - await TestInRegularAndScriptAsync( + public Task TestElementAccessExpression() + => TestInRegularAndScriptAsync( """ using System; class C @@ -6955,7 +5983,6 @@ void test() } } """); - } [Fact] public async Task TestIndexExpression() @@ -7093,10 +6120,8 @@ static void Main(string[] args) } [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/30207")] - public async Task TestImplicitRecursiveInstanceMemberAccess_ForAllOccurrences() - { - var code = - """ + public Task TestImplicitRecursiveInstanceMemberAccess_ForAllOccurrences() + => TestInRegularAndScriptAsync(""" class C { C c; @@ -7105,10 +6130,7 @@ void Test() var x = [|c|].c.c; } } - """; - - var expected = - """ + """, """ class C { C c; @@ -7118,16 +6140,11 @@ void Test() var x = c1.c.c; } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1); - } + """, index: 1); [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/30207")] - public async Task TestExplicitRecursiveInstanceMemberAccess_ForAllOccurrences() - { - var code = - """ + public Task TestExplicitRecursiveInstanceMemberAccess_ForAllOccurrences() + => TestInRegularAndScriptAsync(""" class C { C c; @@ -7136,10 +6153,7 @@ void Test() var x = [|this.c|].c.c; } } - """; - - var expected = - """ + """, """ class C { C c; @@ -7149,16 +6163,11 @@ void Test() var x = c1.c.c; } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1); - } + """, index: 1); [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/30207")] - public async Task TestExplicitInstanceMemberAccess_ForAllOccurrences() - { - var code = - """ + public Task TestExplicitInstanceMemberAccess_ForAllOccurrences() + => TestInRegularAndScriptAsync(""" class C { C c; @@ -7167,10 +6176,7 @@ void Test(C arg) var x = [|this.c|].Test(this.c); } } - """; - - var expected = - """ + """, """ class C { C c; @@ -7180,16 +6186,11 @@ void Test(C arg) var x = c1.Test(c1); } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1); - } + """, index: 1); [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/30207")] - public async Task TestImplicitInstanceMemberAccess_ForAllOccurrences() - { - var code = - """ + public Task TestImplicitInstanceMemberAccess_ForAllOccurrences() + => TestInRegularAndScriptAsync(""" class C { C c; @@ -7198,10 +6199,7 @@ void Test(C arg) var x = [|c|].Test(c); } } - """; - - var expected = - """ + """, """ class C { C c; @@ -7211,16 +6209,11 @@ void Test(C arg) var x = c1.Test(c1); } } - """; - - await TestInRegularAndScriptAsync(code, expected, index: 1); - } + """, index: 1); [Fact, WorkItem("http://github.com/dotnet/roslyn/issues/30207")] - public async Task TestExpressionOfUndeclaredType() - { - var code = - """ + public Task TestExpressionOfUndeclaredType() + => TestMissingAsync(""" class C { void Test() @@ -7231,14 +6224,11 @@ void Test() } } } - """; - await TestMissingAsync(code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40209")] - public async Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_Method() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_Method() + => TestInRegularAndScriptAsync( """ class Program { @@ -7270,12 +6260,10 @@ void Local() } } """, index: 1, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40209")] - public async Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_Property() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_Property() + => TestInRegularAndScriptAsync( """ class Program { @@ -7317,12 +6305,10 @@ void Local() } } """, index: 1, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40209")] - public async Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_ForLoop() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_ForLoop() + => TestInRegularAndScriptAsync( """ class Program { @@ -7370,12 +6356,10 @@ void Local() } } """, index: 1, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40209")] - public async Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_NestedLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_NestedLocalFunction() + => TestInRegularAndScriptAsync( """ class Program { @@ -7415,12 +6399,10 @@ void Local() } } """, index: 1, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40209")] - public async Task TestIntroduceFromStaticLocalFunction_AllOccurences_NestedLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceFromStaticLocalFunction_AllOccurences_NestedLocalFunction() + => TestInRegularAndScriptAsync( """ class Program { @@ -7460,12 +6442,10 @@ static void Local() } } """, index: 1, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40209")] - public async Task TestIntroduceFromStaticLocalFunction_AllOccurences_Method() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceFromStaticLocalFunction_AllOccurences_Method() + => TestInRegularAndScriptAsync( """ using System; @@ -7511,12 +6491,10 @@ private static object Foo() } } """, index: 1, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40209")] - public async Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_SingleMatch() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_SingleMatch() + => TestInRegularAndScriptAsync( """ class Program { @@ -7546,12 +6524,10 @@ void Local() } } """, index: 1, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40209")] - public async Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_MultipleMatches() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_MultipleMatches() + => TestInRegularAndScriptAsync( """ class Program { @@ -7583,12 +6559,10 @@ void Local() } } """, index: 1, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40209")] - public async Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_MultipleMatches2() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_MultipleMatches2() + => TestInRegularAndScriptAsync( """ class Program { @@ -7620,12 +6594,10 @@ void Local() } } """, index: 1, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40374")] - public async Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_LocalFunctionCall() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_LocalFunctionCall() + => TestInRegularAndScriptAsync( """ using System; class Bug @@ -7669,12 +6641,10 @@ private static object Foo() } } """, index: 1, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40374")] - public async Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_LocalFunctionCall2() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_LocalFunctionCall2() + => TestInRegularAndScriptAsync( """ using System; class Bug @@ -7718,12 +6688,10 @@ private static object Foo() } } """, index: 1, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40374")] - public async Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_LocalFunctionCall3() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_LocalFunctionCall3() + => TestInRegularAndScriptAsync( """ using System; class Bug @@ -7771,12 +6739,10 @@ private static object Foo() } } """, index: 1, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40374")] - public async Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_MultipleLocalFunctionCalls() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_MultipleLocalFunctionCalls() + => TestInRegularAndScriptAsync( """ using System; class Bug @@ -7826,12 +6792,10 @@ private static object Foo() } } """, index: 1, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40374")] - public async Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_NestedLocalFunctionCalls() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_NestedLocalFunctionCalls() + => TestInRegularAndScriptAsync( """ using System; class Bug @@ -7887,12 +6851,10 @@ private static object Foo() } } """, index: 1, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40374")] - public async Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_MultipleLocalFunctions() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_MultipleLocalFunctions() + => TestInRegularAndScriptAsync( """ using System; class Bug @@ -7956,12 +6918,10 @@ private static object Foo() } } """, index: 1, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40374")] - public async Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_MultipleLocalFunctions2() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_MultipleLocalFunctions2() + => TestInRegularAndScriptAsync( """ using System; class Bug @@ -8021,12 +6981,10 @@ private static object Foo() } } """, index: 1, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40374")] - public async Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_NoLocalFunctionCall() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_NoLocalFunctionCall() + => TestInRegularAndScriptAsync( """ using System; class Bug @@ -8072,12 +7030,10 @@ private static object Foo() } } """, index: 1, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40374")] - public async Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_ExpressionBodiedLocalFunction() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_ExpressionBodiedLocalFunction() + => TestInRegularAndScriptAsync( """ using System; class Bug @@ -8119,12 +7075,10 @@ private static object Foo() } } """, index: 1, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40374")] - public async Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_ExpressionBodiedLocalFunction2() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_ExpressionBodiedLocalFunction2() + => TestInRegularAndScriptAsync( """ using System; class Bug @@ -8166,12 +7120,10 @@ private static object Foo() } } """, index: 1, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40374")] - public async Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_SameMethodNames() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceFromNonStaticLocalFunction_AllOccurences_SameMethodNames() + => TestInRegularAndScriptAsync( """ using System; class Bug @@ -8245,12 +7197,10 @@ class C public void Local() { } } """, index: 1, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40381")] - public async Task TestIntroduceFromMethod_AllOccurences_DoNotIncludeStaticLocalFunctionReferences() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceFromMethod_AllOccurences_DoNotIncludeStaticLocalFunctionReferences() + => TestInRegularAndScriptAsync( """ using System; class Bug @@ -8294,12 +7244,10 @@ private static object Foo() } } """, index: 1, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40381")] - public async Task TestIntroduceFromMethod_AllOccurences_DoNotIncludeStaticLocalFunctionReferences2() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceFromMethod_AllOccurences_DoNotIncludeStaticLocalFunctionReferences2() + => TestInRegularAndScriptAsync( """ using System; class Bug @@ -8341,12 +7289,10 @@ private static object Foo() } } """, index: 1, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40381")] - public async Task TestIntroduceFromMethod_AllOccurences_IncludeNonStaticLocalFunctionReferences() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceFromMethod_AllOccurences_IncludeNonStaticLocalFunctionReferences() + => TestInRegularAndScriptAsync( """ using System; class Bug @@ -8390,12 +7336,10 @@ private static object Foo() } } """, index: 1, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/561")] - public async Task DoNotGenerateBetweenElseAndIf() - { - await TestInRegularAndScriptAsync( + public Task DoNotGenerateBetweenElseAndIf() + => TestInRegularAndScriptAsync( """ class C { @@ -8425,12 +7369,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/12591")] - public async Task TestWhitespaceSelection1() - { - await TestInRegularAndScriptAsync( + public Task TestWhitespaceSelection1() + => TestInRegularAndScriptAsync( """ public class Class1 { @@ -8466,12 +7408,10 @@ private object Bar() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56")] - public async Task TestGenerateNameForForeachExpression() - { - await TestInRegularAndScriptAsync( + public Task TestGenerateNameForForeachExpression() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -8511,12 +7451,10 @@ static IEnumerable GetNumbers() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15770")] - public async Task TestKeepReplacementIndentation1() - { - await TestInRegularAndScriptAsync( + public Task TestKeepReplacementIndentation1() + => TestInRegularAndScriptAsync( """ class D { @@ -8539,12 +7477,10 @@ void C(int a) } """, index: 3); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40745")] - public async Task TestKeepExistingNonTrivialCodeInLambda() - { - await TestInRegularAndScriptAsync( + public Task TestKeepExistingNonTrivialCodeInLambda() + => TestInRegularAndScriptAsync( """ using System.IO; using System.Threading.Tasks; @@ -8573,12 +7509,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40745")] - public async Task TestIntroVarInActionSelectingInsideParens() - { - await TestInRegularAndScriptAsync( + public Task TestIntroVarInActionSelectingInsideParens() + => TestInRegularAndScriptAsync( """ using System; @@ -8604,12 +7538,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40745")] - public async Task TestIntroVarInActionSelectingParens() - { - await TestInRegularAndScriptAsync( + public Task TestIntroVarInActionSelectingParens() + => TestInRegularAndScriptAsync( """ using System; @@ -8635,12 +7567,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40745")] - public async Task TestMissingReturnStatementInAsyncTaskMethod() - { - await TestInRegularAndScriptAsync( + public Task TestMissingReturnStatementInAsyncTaskMethod() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -8677,12 +7607,10 @@ async Task M2() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40745")] - public async Task TestMissingReturnStatementInAsyncValueTaskMethod() - { - await TestInRegularAndScriptAsync( + public Task TestMissingReturnStatementInAsyncValueTaskMethod() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -8731,12 +7659,10 @@ async ValueTask M2() } } """); - } [Fact] - public async Task TestReturnStatementInAsyncTaskTypeMethod() - { - await TestInRegularAndScriptAsync( + public Task TestReturnStatementInAsyncTaskTypeMethod() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -8775,12 +7701,10 @@ async Task M2() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40745")] - public async Task TestReturnStatementInAsyncValueTaskTypeMethod() - { - await TestInRegularAndScriptAsync( + public Task TestReturnStatementInAsyncValueTaskTypeMethod() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -8831,12 +7755,10 @@ async ValueTask M2() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44291")] - public async Task TestIntroduceWithAmbiguousExtensionClass() - { - await TestInRegularAndScriptAsync( + public Task TestIntroduceWithAmbiguousExtensionClass() + => TestInRegularAndScriptAsync( """ @@ -8879,12 +7801,10 @@ public void M(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44656")] - public async Task ImplicitObjectCreation() - { - await TestInRegularAndScriptAsync(""" + public Task ImplicitObjectCreation() + => TestInRegularAndScriptAsync(""" class A { public void Create(A a, B b) @@ -8916,12 +7836,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52833")] - public async Task UniqueParameterName() - { - await TestInRegularAndScriptAsync(""" + public Task UniqueParameterName() + => TestInRegularAndScriptAsync(""" using System.IO; public class SomeClass @@ -8954,12 +7872,10 @@ public void Other(string path) } } """, 2); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47772")] - public async Task DoNotIntroduceConstantForConstant_Local() - { - await TestMissingAsync( + public Task DoNotIntroduceConstantForConstant_Local() + => TestMissingAsync( """ class C { @@ -8969,36 +7885,30 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47772")] - public async Task DoNotIntroduceConstantForConstant_Member() - { - await TestMissingAsync( + public Task DoNotIntroduceConstantForConstant_Member() + => TestMissingAsync( """ class C { const int foo = [|10|]; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47772")] - public async Task DoNotIntroduceConstantForConstant_Parentheses() - { - await TestMissingAsync( + public Task DoNotIntroduceConstantForConstant_Parentheses() + => TestMissingAsync( """ class C { const int foo = ([|10|]); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47772")] - public async Task DoNotIntroduceConstantForConstant_NotForSubExpression() - { - await TestInRegularAndScriptAsync( + public Task DoNotIntroduceConstantForConstant_NotForSubExpression() + => TestInRegularAndScriptAsync( """ class C { @@ -9018,16 +7928,14 @@ void M() } } """, - index: 2); - } + index: 2); [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] [WorkItem("https://github.com/dotnet/roslyn/issues/61796")] [InlineData("Task")] [InlineData("ValueTask")] - public async Task IntroduceLocal_DoNotReturnForVoidTaskLikeTypes(string taskType) - { - await TestInRegularAndScriptAsync( + public Task IntroduceLocal_DoNotReturnForVoidTaskLikeTypes(string taskType) + => TestInRegularAndScriptAsync( $$""" using System; using System.Threading.Tasks; @@ -9064,12 +7972,10 @@ internal class Example1 } } """ + ValueTaskDeclaration); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28730")] - public async Task TestOnThis1() - { - await TestMissingAsync( + public Task TestOnThis1() + => TestMissingAsync( """ sealed class C { readonly string s; @@ -9078,12 +7984,10 @@ public C(string s) { } } """); - } [Fact] - public async Task Lambda_OptionalParameters() - { - await TestInRegularAndScriptAsync( + public Task Lambda_OptionalParameters() + => TestInRegularAndScriptAsync( """ using System; @@ -9111,12 +8015,10 @@ void M() static void H(Delegate d) { } } """); - } [Fact] - public async Task Lambda_ParamsArray() - { - await TestInRegularAndScriptAsync( + public Task Lambda_ParamsArray() + => TestInRegularAndScriptAsync( """ using System; @@ -9144,12 +8046,10 @@ void M() static void H(Delegate d) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71042")] - public async Task TestNotForArrayInAttribute() - { - await TestMissingAsync( + public Task TestNotForArrayInAttribute() + => TestMissingAsync( """ public class C { @@ -9159,12 +8059,10 @@ public class C public string Bar { get; set; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71042")] - public async Task TestNotForTypeofInAttribute() - { - await TestMissingAsync( + public Task TestNotForTypeofInAttribute() + => TestMissingAsync( """ public class C { @@ -9174,12 +8072,10 @@ public class C public string Bar { get; set; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21602")] - public async Task DetermineNameFromAnonymousObjectMember() - { - await TestInRegularAndScriptAsync( + public Task DetermineNameFromAnonymousObjectMember() + => TestInRegularAndScriptAsync( """ using System; @@ -9203,12 +8099,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67270")] - public async Task TestTopLevel1() - { - await TestAsync( + public Task TestTopLevel1() + => TestAsync( """ using System; @@ -9223,12 +8117,10 @@ await TestAsync( var v1 = random.Next(); var v2 = random.Next(); """, index: 1, parseOptions: CSharpParseOptions.Default, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67270")] - public async Task TestTopLevel2() - { - await TestAsync( + public Task TestTopLevel2() + => TestAsync( """ using System; @@ -9253,12 +8145,10 @@ void Local() var v3 = random.Next(); } """, index: 1, parseOptions: CSharpParseOptions.Default, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67270")] - public async Task TestTopLevel3() - { - await TestAsync( + public Task TestTopLevel3() + => TestAsync( """ using System; @@ -9289,12 +8179,10 @@ void Local() } } """, index: 1, parseOptions: CSharpParseOptions.Default, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67270")] - public async Task TestTopLevel4() - { - await TestAsync( + public Task TestTopLevel4() + => TestAsync( """ using System; @@ -9325,12 +8213,10 @@ void Local() } } """, index: 1, parseOptions: CSharpParseOptions.Default, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67270")] - public async Task TestTopLevel5() - { - await TestAsync( + public Task TestTopLevel5() + => TestAsync( """ using System; @@ -9355,12 +8241,10 @@ static void Local() var v3 = new Random().Next(); } """, index: 1, parseOptions: CSharpParseOptions.Default, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67270")] - public async Task TestTopLevel6() - { - await TestAsync( + public Task TestTopLevel6() + => TestAsync( """ using System; @@ -9385,12 +8269,10 @@ void Local() var v3 = random.Next(); } """, index: 1, parseOptions: CSharpParseOptions.Default, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67270")] - public async Task TestTopLevel7() - { - await TestAsync( + public Task TestTopLevel7() + => TestAsync( """ using System; @@ -9414,12 +8296,10 @@ static void Local() var v3 = random.Next(); } """, index: 1, parseOptions: CSharpParseOptions.Default, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47277")] - public async Task TestPreserveIndentationInLambda1() - { - await TestInRegularAndScriptAsync( + public Task TestPreserveIndentationInLambda1() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -9457,12 +8337,10 @@ void M() } } """, index: 0, options: ImplicitTypingEverywhere()); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47277")] - public async Task TestPreserveIndentationInLambda2() - { - await TestInRegularAndScriptAsync( + public Task TestPreserveIndentationInLambda2() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -9502,30 +8380,26 @@ void M() } } """, index: 0, options: ImplicitTypingEverywhere()); - } [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/78204")] [WorkItem("https://github.com/dotnet/roslyn/issues/77559")] [WorkItem("https://github.com/dotnet/roslyn/issues/77147")] - public async Task TestInTopLevelStatement() - { - await TestMissingAsync( + public Task TestInTopLevelStatement() + => TestMissingAsync( """ void M() { _ = ([|long|])0; } """); - } [Fact] [WorkItem("https://github.com/dotnet/roslyn/issues/78204")] [WorkItem("https://github.com/dotnet/roslyn/issues/77559")] [WorkItem("https://github.com/dotnet/roslyn/issues/77147")] - public async Task TestInClassDeclaration() - { - await TestMissingAsync( + public Task TestInClassDeclaration() + => TestMissingAsync( """ public class C { void M() @@ -9534,12 +8408,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/78680")] - public async Task FixReferenceInMemberAccessNameInTopLevel() - { - await TestAsync( + public Task FixReferenceInMemberAccessNameInTopLevel() + => TestAsync( """ C c = null; C d = null; @@ -9567,5 +8439,28 @@ class C """, parseOptions: null, index: 1); - } + + [Fact] + public Task TestNotOnNamedType1() + => TestMissingInRegularAndScriptAsync( + """ + using System; + + class C + { + void M() + { + [||]Console.WriteLine(); + } + } + """); + + [Fact] + public Task TestNotOnNamedType2() + => TestMissingInRegularAndScriptAsync( + """ + using System; + + [||]Console.WriteLine(); + """); } diff --git a/src/Features/CSharpTest/InvertConditional/InvertConditionalTests.cs b/src/Features/CSharpTest/InvertConditional/InvertConditionalTests.cs index 33d2eb2bab66f..92eb2f999fc18 100644 --- a/src/Features/CSharpTest/InvertConditional/InvertConditionalTests.cs +++ b/src/Features/CSharpTest/InvertConditional/InvertConditionalTests.cs @@ -21,9 +21,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor => new CSharpInvertConditionalCodeRefactoringProvider(); [Fact] - public async Task InvertConditional1() - { - await TestInRegularAndScriptAsync( + public Task InvertConditional1() + => TestInRegularAndScriptAsync( """ class C { @@ -42,12 +41,10 @@ void M(bool x, int a, int b) } } """); - } [Fact] - public async Task InvertConditional2() - { - await TestInRegularAndScriptAsync( + public Task InvertConditional2() + => TestInRegularAndScriptAsync( """ class C { @@ -66,12 +63,10 @@ void M(bool x, int a, int b) } } """); - } [Fact] - public async Task TestTrivia() - { - await TestInRegularAndScriptAsync( + public Task TestTrivia() + => TestInRegularAndScriptAsync( """ class C { @@ -94,12 +89,10 @@ void M(bool x, int a, int b) } } """); - } [Fact] - public async Task TestTrivia1() - { - await TestInRegularAndScriptAsync( + public Task TestTrivia1() + => TestInRegularAndScriptAsync( """ class C { @@ -122,15 +115,10 @@ void M(bool x, int a, int b) } } """); - } [Fact] - public async Task TestTrivia2() - { - // We currently do not move trivia along with the true/false parts. We could consider - // trying to intelligently do that in the future. It would require moving the comments, - // but preserving the whitespace/newlines. - await TestInRegularAndScriptAsync( + public Task TestTrivia2() + => TestInRegularAndScriptAsync( """ class C { @@ -153,12 +141,10 @@ void M(bool x, int a, int b) } } """); - } [Fact] - public async Task TestStartOfConditional() - { - await TestInRegularAndScriptAsync( + public Task TestStartOfConditional() + => TestInRegularAndScriptAsync( """ class C { @@ -177,12 +163,10 @@ void M(bool x, int a, int b) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestAfterCondition() - { - await TestInRegularAndScriptAsync( + public Task TestAfterCondition() + => TestInRegularAndScriptAsync( """ class C { @@ -201,5 +185,4 @@ void M(bool x, int a, int b) } } """); - } } diff --git a/src/Features/CSharpTest/InvertIf/InvertIfTests.Elseless.cs b/src/Features/CSharpTest/InvertIf/InvertIfTests.Elseless.cs index 0a67c6411816b..90778951feb3a 100644 --- a/src/Features/CSharpTest/InvertIf/InvertIfTests.Elseless.cs +++ b/src/Features/CSharpTest/InvertIf/InvertIfTests.Elseless.cs @@ -11,9 +11,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InvertIf; public sealed partial class InvertIfTests { [Fact] - public async Task IfWithoutElse_MoveIfBodyToElseClause1() - { - await TestAsync(""" + public Task IfWithoutElse_MoveIfBodyToElseClause1() + => TestAsync(""" class C { void M() @@ -55,12 +54,10 @@ void M() } } """); - } [Fact] - public async Task IfWithoutElse_MoveIfBodyToElseClause2() - { - await TestAsync(""" + public Task IfWithoutElse_MoveIfBodyToElseClause2() + => TestAsync(""" class C { void M() @@ -100,12 +97,10 @@ void M() } } """); - } [Fact] - public async Task IfWithoutElse_MoveIfBodyToElseClause3() - { - await TestAsync(""" + public Task IfWithoutElse_MoveIfBodyToElseClause3() + => TestAsync(""" class C { void M() @@ -135,12 +130,10 @@ void M() } } """); - } [Fact] - public async Task IfWithoutElse_MoveIfBodyToElseClause4() - { - await TestAsync(""" + public Task IfWithoutElse_MoveIfBodyToElseClause4() + => TestAsync(""" class C { bool M() @@ -176,12 +169,10 @@ bool M() } } """); - } [Fact] - public async Task IfWithoutElse_MoveIfBodyToElseClause5() - { - await TestAsync(""" + public Task IfWithoutElse_MoveIfBodyToElseClause5() + => TestAsync(""" class C { void M() @@ -213,12 +204,10 @@ void M() } } """); - } [Fact] - public async Task IfWithoutElse_MoveIfBodyToElseClause6() - { - await TestAsync(""" + public Task IfWithoutElse_MoveIfBodyToElseClause6() + => TestAsync(""" class C { void M() @@ -266,12 +255,10 @@ void M() } } """); - } [Fact] - public async Task IfWithoutElse_MoveIfBodyToElseClause7() - { - await TestAsync(""" + public Task IfWithoutElse_MoveIfBodyToElseClause7() + => TestAsync(""" class C { void M() @@ -319,12 +306,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40909")] - public async Task IfWithoutElse_MoveIfBodyToElseClause8() - { - await TestAsync(""" + public Task IfWithoutElse_MoveIfBodyToElseClause8() + => TestAsync(""" using System.Diagnostics; class C { @@ -360,12 +345,10 @@ private static bool IsFalse(bool val) } } """); - } [Fact] - public async Task IfWithoutElse_MoveSubsequentStatementsToIfBody1() - { - await TestAsync(""" + public Task IfWithoutElse_MoveSubsequentStatementsToIfBody1() + => TestAsync(""" class C { void M() @@ -397,12 +380,10 @@ void M() } } """); - } [Fact] - public async Task IfWithoutElse_MoveSubsequentStatementsToIfBody2() - { - await TestAsync(""" + public Task IfWithoutElse_MoveSubsequentStatementsToIfBody2() + => TestAsync(""" class C { void M() @@ -440,12 +421,10 @@ void M() } } """); - } [Fact] - public async Task IfWithoutElse_MoveSubsequentStatementsToIfBody3() - { - await TestAsync(""" + public Task IfWithoutElse_MoveSubsequentStatementsToIfBody3() + => TestAsync(""" class C { void M() @@ -481,12 +460,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73917")] - public async Task IfWithoutElse_MoveSubsequentStatementsToIfBody4() - { - await TestAsync(""" + public Task IfWithoutElse_MoveSubsequentStatementsToIfBody4() + => TestAsync(""" public void SomeMethod() { object something = null; @@ -513,12 +490,10 @@ public void SomeMethod() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73917")] - public async Task IfWithoutElse_MoveSubsequentStatementsToIfBody5() - { - await TestAsync(""" + public Task IfWithoutElse_MoveSubsequentStatementsToIfBody5() + => TestAsync(""" switch (o) { case 1: @@ -551,12 +526,10 @@ await TestAsync(""" return; } """); - } [Fact] - public async Task IfWithoutElse_SwapIfBodyWithSubsequentStatements1() - { - await TestAsync(""" + public Task IfWithoutElse_SwapIfBodyWithSubsequentStatements1() + => TestAsync(""" class C { void M() @@ -583,12 +556,10 @@ void M() } } """); - } [Fact] - public async Task IfWithoutElse_SwapIfBodyWithSubsequentStatements2() - { - await TestAsync(""" + public Task IfWithoutElse_SwapIfBodyWithSubsequentStatements2() + => TestAsync(""" class C { void M() @@ -619,12 +590,10 @@ void M() } } """); - } [Fact] - public async Task IfWithoutElse_WithElseClause1() - { - await TestAsync(""" + public Task IfWithoutElse_WithElseClause1() + => TestAsync(""" class C { void M() @@ -652,12 +621,10 @@ void M() } } """); - } [Fact] - public async Task IfWithoutElse_WithNegatedCondition1() - { - await TestAsync(""" + public Task IfWithoutElse_WithNegatedCondition1() + => TestAsync(""" class C { void M() @@ -674,12 +641,10 @@ void M() } } """); - } [Fact] - public async Task IfWithoutElse_WithNearmostJumpStatement1() - { - await TestAsync(""" + public Task IfWithoutElse_WithNearmostJumpStatement1() + => TestAsync(""" class C { void M() @@ -709,12 +674,10 @@ void M() } } """); - } [Fact] - public async Task IfWithoutElse_WithNearmostJumpStatement2() - { - await TestAsync(""" + public Task IfWithoutElse_WithNearmostJumpStatement2() + => TestAsync(""" class C { void M() @@ -748,12 +711,10 @@ void M() } } """); - } [Fact] - public async Task IfWithoutElse_WithNearmostJumpStatement3() - { - await TestAsync(""" + public Task IfWithoutElse_WithNearmostJumpStatement3() + => TestAsync(""" class C { void M() @@ -777,12 +738,10 @@ void M() } } """); - } [Fact] - public async Task IfWithoutElse_WithNearmostJumpStatement4() - { - await TestAsync(""" + public Task IfWithoutElse_WithNearmostJumpStatement4() + => TestAsync(""" class C { void M() @@ -812,12 +771,10 @@ void M() } } """); - } [Fact] - public async Task IfWithoutElse_WithSubsequentExitPointStatement1() - { - await TestAsync(""" + public Task IfWithoutElse_WithSubsequentExitPointStatement1() + => TestAsync(""" class C { void M() @@ -853,12 +810,10 @@ void M() } } """); - } [Fact] - public async Task IfWithoutElse_WithSubsequentExitPointStatement2() - { - await TestAsync(""" + public Task IfWithoutElse_WithSubsequentExitPointStatement2() + => TestAsync(""" class C { void M() @@ -900,15 +855,13 @@ void M() } } """); - } [Theory] [InlineData("get")] [InlineData("set")] [InlineData("init")] - public async Task IfWithoutElse_InPropertyAccessors(string accessor) - { - await TestAsync($$""" + public Task IfWithoutElse_InPropertyAccessors(string accessor) + => TestAsync($$""" class C { private bool _b; @@ -946,5 +899,4 @@ public string Prop } } """); - } } diff --git a/src/Features/CSharpTest/InvertIf/InvertIfTests.cs b/src/Features/CSharpTest/InvertIf/InvertIfTests.cs index 89466d05bea77..72d5181740513 100644 --- a/src/Features/CSharpTest/InvertIf/InvertIfTests.cs +++ b/src/Features/CSharpTest/InvertIf/InvertIfTests.cs @@ -41,325 +41,246 @@ void Goo() } } - private static async Task TestAsync(string initial, string expected, LanguageVersion languageVersion = LanguageVersion.Latest) - { - await new CSharpCodeRefactoringVerifier.Test + private static Task TestAsync(string initial, string expected, LanguageVersion languageVersion = LanguageVersion.Latest) + => new CSharpCodeRefactoringVerifier.Test { TestCode = initial, FixedCode = expected, LanguageVersion = languageVersion, CompilerDiagnostics = CompilerDiagnostics.None, }.RunAsync(); - } [Fact] - public async Task TestSingleLine_Identifier() - { - await TestInsideMethodAsync( + public Task TestSingleLine_Identifier() + => TestInsideMethodAsync( @"[||]if (a) { a(); } else { b(); }", @"if (!a) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_IdentifierWithTrivia() - { - await TestInsideMethodAsync( + public Task TestSingleLine_IdentifierWithTrivia() + => TestInsideMethodAsync( @"[||]if /*0*/(/*1*/a/*2*/)/*3*/ { a(); } else { b(); }", @"if /*0*/(/*1*/!a/*2*/)/*3*/ { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_NotIdentifier() - { - await TestInsideMethodAsync( + public Task TestSingleLine_NotIdentifier() + => TestInsideMethodAsync( @"[||]if (!a) { a(); } else { b(); }", @"if (a) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_NotIdentifierWithTrivia() - { - await TestInsideMethodAsync( + public Task TestSingleLine_NotIdentifierWithTrivia() + => TestInsideMethodAsync( @"[||]if /*0*/(/*1*/!/*1b*/a/*2*/)/*3*/ { a(); } else { b(); }", @"if /*0*/(/*1*/a/*2*/)/*3*/ { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_EqualsEquals() - { - await TestInsideMethodAsync( + public Task TestSingleLine_EqualsEquals() + => TestInsideMethodAsync( @"[||]if (a == b) { a(); } else { b(); }", @"if (a != b) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_NotEquals() - { - await TestInsideMethodAsync( + public Task TestSingleLine_NotEquals() + => TestInsideMethodAsync( @"[||]if (a != b) { a(); } else { b(); }", @"if (a == b) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_GreaterThan() - { - await TestInsideMethodAsync( + public Task TestSingleLine_GreaterThan() + => TestInsideMethodAsync( @"[||]if (a > b) { a(); } else { b(); }", @"if (a <= b) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_GreaterThanEquals() - { - await TestInsideMethodAsync( + public Task TestSingleLine_GreaterThanEquals() + => TestInsideMethodAsync( @"[||]if (a >= b) { a(); } else { b(); }", @"if (a < b) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_LessThan() - { - await TestInsideMethodAsync( + public Task TestSingleLine_LessThan() + => TestInsideMethodAsync( @"[||]if (a < b) { a(); } else { b(); }", @"if (a >= b) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_LessThanEquals() - { - await TestInsideMethodAsync( + public Task TestSingleLine_LessThanEquals() + => TestInsideMethodAsync( @"[||]if (a <= b) { a(); } else { b(); }", @"if (a > b) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_DoubleParentheses() - { - await TestInsideMethodAsync( + public Task TestSingleLine_DoubleParentheses() + => TestInsideMethodAsync( @"[||]if ((a)) { a(); } else { b(); }", @"if (!a) { b(); } else { a(); }"); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/26427")] - public async Task TestSingleLine_DoubleParenthesesWithInnerTrivia() - { - await TestInsideMethodAsync( + public Task TestSingleLine_DoubleParenthesesWithInnerTrivia() + => TestInsideMethodAsync( @"[||]if ((/*1*/a/*2*/)) { a(); } else { b(); }", @"if (/*1*/!a/*2*/) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_DoubleParenthesesWithMiddleTrivia() - { - await TestInsideMethodAsync( + public Task TestSingleLine_DoubleParenthesesWithMiddleTrivia() + => TestInsideMethodAsync( @"[||]if (/*1*/(a)/*2*/) { a(); } else { b(); }", @"if (/*1*/!a/*2*/) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_DoubleParenthesesWithOutsideTrivia() - { - await TestInsideMethodAsync( + public Task TestSingleLine_DoubleParenthesesWithOutsideTrivia() + => TestInsideMethodAsync( @"[||]if /*before*/((a))/*after*/ { a(); } else { b(); }", @"if /*before*/(!a)/*after*/ { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_Is() - { - await TestInsideMethodAsync( + public Task TestSingleLine_Is() + => TestInsideMethodAsync( @"[||]if (a is Goo) { a(); } else { b(); }", @"if (a is not Goo) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_MethodCall() - { - await TestInsideMethodAsync( + public Task TestSingleLine_MethodCall() + => TestInsideMethodAsync( @"[||]if (a.Goo()) { a(); } else { b(); }", @"if (!a.Goo()) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_Or() - { - await TestInsideMethodAsync( + public Task TestSingleLine_Or() + => TestInsideMethodAsync( @"[||]if (a || b) { a(); } else { b(); }", @"if (!a && !b) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_Or2() - { - await TestInsideMethodAsync( + public Task TestSingleLine_Or2() + => TestInsideMethodAsync( @"[||]if (!a || !b) { a(); } else { b(); }", @"if (a && b) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_Or3() - { - await TestInsideMethodAsync( + public Task TestSingleLine_Or3() + => TestInsideMethodAsync( @"[||]if (!a || b) { a(); } else { b(); }", @"if (a && !b) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_Or4() - { - await TestInsideMethodAsync( + public Task TestSingleLine_Or4() + => TestInsideMethodAsync( @"[||]if (a | b) { a(); } else { b(); }", @"if (!a & !b) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_And() - { - await TestInsideMethodAsync( + public Task TestSingleLine_And() + => TestInsideMethodAsync( @"[||]if (a && b) { a(); } else { b(); }", @"if (!a || !b) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_And2() - { - await TestInsideMethodAsync( + public Task TestSingleLine_And2() + => TestInsideMethodAsync( @"[||]if (!a && !b) { a(); } else { b(); }", @"if (a || b) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_And3() - { - await TestInsideMethodAsync( + public Task TestSingleLine_And3() + => TestInsideMethodAsync( @"[||]if (!a && b) { a(); } else { b(); }", @"if (a || !b) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_And4() - { - await TestInsideMethodAsync( + public Task TestSingleLine_And4() + => TestInsideMethodAsync( @"[||]if (a & b) { a(); } else { b(); }", @"if (!a | !b) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_ParenthesizeAndForPrecedence() - { - await TestInsideMethodAsync( + public Task TestSingleLine_ParenthesizeAndForPrecedence() + => TestInsideMethodAsync( @"[||]if (a && b || c) { a(); } else { b(); }", @"if ((!a || !b) && !c) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_Plus() - { - await TestInsideMethodAsync( + public Task TestSingleLine_Plus() + => TestInsideMethodAsync( @"[||]if (a + b) { a(); } else { b(); }", @"if (!(a + b)) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_True() - { - await TestInsideMethodAsync( + public Task TestSingleLine_True() + => TestInsideMethodAsync( @"[||]if (true) { a(); } else { b(); }", @"if (false) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_TrueWithTrivia() - { - await TestInsideMethodAsync( + public Task TestSingleLine_TrueWithTrivia() + => TestInsideMethodAsync( @"[||]if (/*1*/true/*2*/) { a(); } else { b(); }", @"if (/*1*/false/*2*/) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_False() - { - await TestInsideMethodAsync( + public Task TestSingleLine_False() + => TestInsideMethodAsync( @"[||]if (false) { a(); } else { b(); }", @"if (true) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_OtherLiteralExpression() - { - await TestInsideMethodAsync( + public Task TestSingleLine_OtherLiteralExpression() + => TestInsideMethodAsync( @"[||]if (literalexpression) { a(); } else { b(); }", @"if (!literalexpression) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_TrueAndFalse() - { - await TestInsideMethodAsync( + public Task TestSingleLine_TrueAndFalse() + => TestInsideMethodAsync( @"[||]if (true && false) { a(); } else { b(); }", @"if (false || true) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_NoCurlyBraces() - { - await TestInsideMethodAsync( + public Task TestSingleLine_NoCurlyBraces() + => TestInsideMethodAsync( @"[||]if (a) a(); else b();", @"if (!a) b(); else a();"); - } [Fact] - public async Task TestSingleLine_CurlyBracesOnIf() - { - await TestInsideMethodAsync( + public Task TestSingleLine_CurlyBracesOnIf() + => TestInsideMethodAsync( @"[||]if (a) { a(); } else b();", @"if (!a) b(); else { a(); }"); - } [Fact] - public async Task TestSingleLine_CurlyBracesOnElse() - { - await TestInsideMethodAsync( + public Task TestSingleLine_CurlyBracesOnElse() + => TestInsideMethodAsync( @"[||]if (a) a(); else { b(); }", @"if (!a) { b(); } else a();"); - } [Fact] - public async Task TestSingleLine_IfElseIf() - { - await TestInsideMethodAsync( + public Task TestSingleLine_IfElseIf() + => TestInsideMethodAsync( @"[||]if (a) { a(); } else if (b) { b(); }", @"if (!a) { if (b) { b(); } } else { a(); }"); - } [Fact] - public async Task TestSingleLine_IfElseIfElse() - { - await TestInsideMethodAsync( + public Task TestSingleLine_IfElseIfElse() + => TestInsideMethodAsync( @"[||]if (a) { a(); } else if (b) { b(); } else { c(); }", @"if (!a) { if (b) { b(); } else { c(); } } else { a(); }"); - } [Fact] - public async Task TestSingleLine_CompoundConditional() - { - await TestInsideMethodAsync( + public Task TestSingleLine_CompoundConditional() + => TestInsideMethodAsync( @"[||]if (((a == b) && (c != d)) || ((e < f) && (!g))) { a(); } else { b(); }", @"if ((a != b || c == d) && (e >= f || g)) { b(); } else { a(); }"); - } [Fact] - public async Task TestSingleLine_Trivia() - { - await TestInsideMethodAsync( + public Task TestSingleLine_Trivia() + => TestInsideMethodAsync( @"[||]if /*1*/ (a) /*2*/ { /*3*/ a() /*4*/; /*5*/ } /*6*/ else if /*7*/ (b) /*8*/ { /*9*/ b(); /*10*/ } /*11*/ else /*12*/ { /*13*/ c(); /*14*/} /*15*/", @"if /*1*/ (!a) /*2*/ { if /*7*/ (b) /*8*/ { /*9*/ b(); /*10*/ } /*11*/ else /*12*/ { /*13*/ c(); /*14*/} /*6*/ } else { /*3*/ a() /*4*/; /*5*/ } /*15*/"); - } [Fact] - public async Task TestKeepTriviaWithinExpression_BrokenCode() - { - await TestAsync(""" + public Task TestKeepTriviaWithinExpression_BrokenCode() + => TestAsync(""" class A { void Goo() @@ -396,12 +317,10 @@ void Goo() } } """); - } [Fact] - public async Task TestKeepTriviaWithinExpression() - { - await TestAsync(""" + public Task TestKeepTriviaWithinExpression() + => TestAsync(""" class A { void Goo() @@ -448,12 +367,10 @@ void Goo() } } """); - } [Fact] - public async Task TestMultiline_IfElseIfElse() - { - await TestAsync(""" + public Task TestMultiline_IfElseIfElse() + => TestAsync(""" class A { void Goo() @@ -495,12 +412,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMultiline_IfElseIfElseSelection1() - { - await TestAsync(""" + public Task TestMultiline_IfElseIfElseSelection1() + => TestAsync(""" class A { void Goo() @@ -542,12 +457,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestMultiline_IfElseIfElseSelection2() - { - await TestAsync(""" + public Task TestMultiline_IfElseIfElseSelection2() + => TestAsync(""" class A { void Goo() @@ -589,7 +502,6 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMultilineMissing_IfElseIfElseSubSelection() @@ -619,9 +531,8 @@ void Goo() } [Fact] - public async Task TestMultiline_IfElse() - { - await TestAsync(""" + public Task TestMultiline_IfElse() + => TestAsync(""" class A { void Goo() @@ -648,12 +559,10 @@ void Goo() } } """); - } [Fact] - public async Task TestMultiline_OpenCloseBracesSameLine() - { - await TestAsync(""" + public Task TestMultiline_OpenCloseBracesSameLine() + => TestAsync(""" class A { void Goo() @@ -685,12 +594,10 @@ void Goo() } } """); - } [Fact] - public async Task TestMultiline_Trivia() - { - await TestAsync(""" + public Task TestMultiline_Trivia() + => TestAsync(""" class A { void Goo() @@ -746,7 +653,6 @@ void Goo() } } """); - } [Fact] public async Task TestOverlapsHiddenPosition1() @@ -874,9 +780,8 @@ void F() } [Fact] - public async Task TestOverlapsHiddenPosition6() - { - await TestAsync(""" + public Task TestOverlapsHiddenPosition6() + => TestAsync(""" #line hidden class C { @@ -912,12 +817,9 @@ void F() } """); - } - [Fact] - public async Task TestOverlapsHiddenPosition7() - { - await TestAsync(""" + public Task TestOverlapsHiddenPosition7() + => TestAsync(""" #line hidden class C { @@ -956,132 +858,100 @@ void F() } #line default """); - } [Fact] - public async Task TestSingleLine_SimplifyToLengthEqualsZero() - { - await TestInsideMethodAsync( + public Task TestSingleLine_SimplifyToLengthEqualsZero() + => TestInsideMethodAsync( @"string x; [||]if (x.Length > 0) { GreaterThanZero(); } else { EqualsZero(); } } } ", @"string x; if (x.Length == 0) { EqualsZero(); } else { GreaterThanZero(); } } } "); - } [Fact] - public async Task TestSingleLine_SimplifyToLengthEqualsZero2() - { - await TestInsideMethodAsync( + public Task TestSingleLine_SimplifyToLengthEqualsZero2() + => TestInsideMethodAsync( @"string[] x; [||]if (x.Length > 0) { GreaterThanZero(); } else { EqualsZero(); } } } ", @"string[] x; if (x.Length == 0) { EqualsZero(); } else { GreaterThanZero(); } } } "); - } [Fact] - public async Task TestSingleLine_SimplifyToLengthEqualsZero3() - { - await TestInsideMethodAsync( + public Task TestSingleLine_SimplifyToLengthEqualsZero3() + => TestInsideMethodAsync( @"string x; [||]if (x.Length > 0x0) { a(); } else { b(); } } } ", @"string x; if (x.Length == 0x0) { b(); } else { a(); } } } "); - } [Fact] - public async Task TestSingleLine_SimplifyToLengthEqualsZero4() - { - await TestInsideMethodAsync( + public Task TestSingleLine_SimplifyToLengthEqualsZero4() + => TestInsideMethodAsync( @"string x; [||]if (0 < x.Length) { a(); } else { b(); } } } ", @"string x; if (0 == x.Length) { b(); } else { a(); } } } "); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] - public async Task TestSingleLine_SimplifyToEqualsZero1() - { - await TestInsideMethodAsync( + public Task TestSingleLine_SimplifyToEqualsZero1() + => TestInsideMethodAsync( @"byte x = 1; [||]if (0 < x) { a(); } else { b(); } } } ", @"byte x = 1; if (0 == x) { b(); } else { a(); } } } "); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] - public async Task TestSingleLine_SimplifyToEqualsZero2() - { - await TestInsideMethodAsync( + public Task TestSingleLine_SimplifyToEqualsZero2() + => TestInsideMethodAsync( @"ushort x = 1; [||]if (0 < x) { a(); } else { b(); } } } ", @"ushort x = 1; if (0 == x) { b(); } else { a(); } } } "); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] - public async Task TestSingleLine_SimplifyToEqualsZero3() - { - await TestInsideMethodAsync( + public Task TestSingleLine_SimplifyToEqualsZero3() + => TestInsideMethodAsync( @"uint x = 1; [||]if (0 < x) { a(); } else { b(); } } } ", @"uint x = 1; if (0 == x) { b(); } else { a(); } } } "); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] - public async Task TestSingleLine_SimplifyToEqualsZero4() - { - await TestInsideMethodAsync( + public Task TestSingleLine_SimplifyToEqualsZero4() + => TestInsideMethodAsync( @"ulong x = 1; [||]if (x > 0) { a(); } else { b(); } } } ", @"ulong x = 1; if (x == 0) { b(); } else { a(); } } } "); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] - public async Task TestSingleLine_SimplifyToNotEqualsZero1() - { - await TestInsideMethodAsync( + public Task TestSingleLine_SimplifyToNotEqualsZero1() + => TestInsideMethodAsync( @"ulong x = 1; [||]if (0 == x) { a(); } else { b(); } } } ", @"ulong x = 1; if (0 != x) { b(); } else { a(); } } } "); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] - public async Task TestSingleLine_SimplifyToNotEqualsZero2() - { - await TestInsideMethodAsync( + public Task TestSingleLine_SimplifyToNotEqualsZero2() + => TestInsideMethodAsync( @"ulong x = 1; [||]if (x == 0) { a(); } else { b(); } } } ", @"ulong x = 1; if (x != 0) { b(); } else { a(); } } } "); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530505")] - public async Task TestSingleLine_SimplifyLongLengthEqualsZero() - { - await TestInsideMethodAsync( + public Task TestSingleLine_SimplifyLongLengthEqualsZero() + => TestInsideMethodAsync( @"string[] x; [||]if (x.LongLength > 0) { GreaterThanZero(); } else { EqualsZero(); } } } ", @"string[] x; if (x.LongLength == 0) { EqualsZero(); } else { GreaterThanZero(); } } } "); - } [Fact] - public async Task TestSingleLine_DoesNotSimplifyToLengthEqualsZero() - { - await TestInsideMethodAsync( + public Task TestSingleLine_DoesNotSimplifyToLengthEqualsZero() + => TestInsideMethodAsync( @"string x; [||]if (x.Length >= 0) { a(); } else { b(); } } } ", @"string x; if (x.Length < 0) { b(); } else { a(); } } } "); - } [Fact] - public async Task TestSingleLine_DoesNotSimplifyToLengthEqualsZero2() - { - await TestInsideMethodAsync( + public Task TestSingleLine_DoesNotSimplifyToLengthEqualsZero2() + => TestInsideMethodAsync( @"string x; [||]if (x.Length > 0.0f) { GreaterThanZero(); } else { EqualsZero(); } } } ", @"string x; if (x.Length <= 0.0f) { EqualsZero(); } else { GreaterThanZero(); } } } "); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29434")] - public async Task TestIsExpression() - { - await TestAsync( + public Task TestIsExpression() + => TestAsync( @"class C { void M(object o) { [||]if (o is C) { a(); } else { } } }", @"class C { void M(object o) { if (o is not C) { } else { a(); } } }"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43224")] - public async Task TestEmptyIf() - { - await TestAsync( + public Task TestEmptyIf() + => TestAsync( @"class C { void M(string s){ [||]if (s == ""a""){}else{ s = ""b""}}}", @"class C { void M(string s){ if (s != ""a"") { s = ""b""}}}"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43224")] - public async Task TestOnlySingleLineCommentIf() - { - await TestAsync(""" + public Task TestOnlySingleLineCommentIf() + => TestAsync(""" class C { void M(string s) @@ -1112,12 +982,10 @@ void M(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/43224")] - public async Task TestOnlyMultilineLineCommentIf() - { - await TestAsync(""" + public Task TestOnlyMultilineLineCommentIf() + => TestAsync(""" class C { void M(string s) @@ -1160,12 +1028,10 @@ void M(string s) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51359")] - public async Task TestIsCheck_CSharp6() - { - await TestAsync(""" + public Task TestIsCheck_CSharp6() + => TestAsync(""" class C { int M() @@ -1196,12 +1062,10 @@ int M() } } """, LanguageVersion.CSharp6); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51359")] - public async Task TestIsCheck_CSharp8() - { - await TestAsync(""" + public Task TestIsCheck_CSharp8() + => TestAsync(""" class C { int M() @@ -1232,12 +1096,10 @@ int M() } } """, LanguageVersion.CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51359")] - public async Task TestIsCheck_CSharp9() - { - await TestAsync(""" + public Task TestIsCheck_CSharp9() + => TestAsync(""" class C { int M() @@ -1268,15 +1130,10 @@ int M() } } """, LanguageVersion.CSharp9); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51359")] - public async Task TestIsNotObjectCheck_CSharp8() - { - // Not terrific. But the starting code is not legal C#8 either. In this case because we don't even support - // 'not' patterns wee don't bother diving into the pattern to negate it, and we instead just negate the - // expression. - await TestAsync(""" + public Task TestIsNotObjectCheck_CSharp8() + => TestAsync(""" class C { int M() @@ -1307,12 +1164,10 @@ int M() } } """, LanguageVersion.CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51359")] - public async Task TestIsNotObjectCheck_CSharp9() - { - await TestAsync(""" + public Task TestIsNotObjectCheck_CSharp9() + => TestAsync(""" class C { int M() @@ -1343,12 +1198,10 @@ int M() } } """, LanguageVersion.CSharp9); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63311")] - public async Task TestLiftedNullable_GreaterThan() - { - await TestAsync(""" + public Task TestLiftedNullable_GreaterThan() + => TestAsync(""" class C { void M(int? p) @@ -1372,12 +1225,10 @@ void M(int? p) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63311")] - public async Task TestLiftedNullable_GreaterThanOrEqual() - { - await TestAsync(""" + public Task TestLiftedNullable_GreaterThanOrEqual() + => TestAsync(""" class C { void M(int? p) @@ -1401,12 +1252,10 @@ void M(int? p) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63311")] - public async Task TestLiftedNullable_LessThan() - { - await TestAsync(""" + public Task TestLiftedNullable_LessThan() + => TestAsync(""" class C { void M(int? p) @@ -1430,12 +1279,10 @@ void M(int? p) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63311")] - public async Task TestLiftedNullable_LessThanOrEqual() - { - await TestAsync(""" + public Task TestLiftedNullable_LessThanOrEqual() + => TestAsync(""" class C { void M(int? p) @@ -1459,12 +1306,10 @@ void M(int? p) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63311")] - public async Task TestNullableReference_GreaterThan() - { - await TestAsync(""" + public Task TestNullableReference_GreaterThan() + => TestAsync(""" #nullable enable using System; class C @@ -1502,12 +1347,10 @@ void M(C? p) public static bool operator >=(C? left, C? right) => throw new NotImplementedException(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40585")] - public async Task TestYieldBreak() - { - await TestAsync(""" + public Task TestYieldBreak() + => TestAsync(""" using System.Collections; class Program @@ -1535,12 +1378,10 @@ public static IEnumerable Method(bool condition) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42715")] - public async Task PreserveSpacing() - { - await TestAsync(""" + public Task PreserveSpacing() + => TestAsync(""" class C { string? M(string s) @@ -1573,12 +1414,10 @@ class C } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42715")] - public async Task PreserveSpacing_WithComments() - { - await TestAsync(""" + public Task PreserveSpacing_WithComments() + => TestAsync(""" class C { string? M(string s) @@ -1619,12 +1458,10 @@ class C } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42715")] - public async Task PreserveSpacing_NoTrivia() - { - await TestAsync(""" + public Task PreserveSpacing_NoTrivia() + => TestAsync(""" class C { string? M(bool b) @@ -1637,5 +1474,4 @@ class C { if (!b) { return (false); } return (true); } } """); - } } diff --git a/src/Features/CSharpTest/InvertLogical/InvertLogicalTests.cs b/src/Features/CSharpTest/InvertLogical/InvertLogicalTests.cs index a999df69c425b..f01075444a506 100644 --- a/src/Features/CSharpTest/InvertLogical/InvertLogicalTests.cs +++ b/src/Features/CSharpTest/InvertLogical/InvertLogicalTests.cs @@ -24,9 +24,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor => new CSharpInvertLogicalCodeRefactoringProvider(); [Fact] - public async Task InvertLogical1() - { - await TestInRegularAndScriptAsync( + public Task InvertLogical1() + => TestInRegularAndScriptAsync( """ class C { @@ -45,12 +44,10 @@ void M(bool x, int a, int b) } } """); - } [Fact] - public async Task InvertLogical2() - { - await TestInRegularAndScriptAsync( + public Task InvertLogical2() + => TestInRegularAndScriptAsync( """ class C { @@ -69,12 +66,10 @@ void M(bool x, int a, int b) } } """); - } [Fact] - public async Task TestTrivia1() - { - await TestInRegularAndScriptAsync( + public Task TestTrivia1() + => TestInRegularAndScriptAsync( """ class C { @@ -95,12 +90,10 @@ void M(bool x, int a, int b) } } """); - } [Fact] - public async Task TestTrivia2() - { - await TestInRegularAndScriptAsync( + public Task TestTrivia2() + => TestInRegularAndScriptAsync( """ class C { @@ -123,12 +116,10 @@ void M(bool x, int a, int b, int c) } } """); - } [Fact] - public async Task InvertMultiConditional1() - { - await TestInRegularAndScriptAsync( + public Task InvertMultiConditional1() + => TestInRegularAndScriptAsync( """ class C { @@ -147,12 +138,10 @@ void M(int a, int b, int c) } } """); - } [Fact] - public async Task InvertMultiConditional2() - { - await TestInRegularAndScriptAsync( + public Task InvertMultiConditional2() + => TestInRegularAndScriptAsync( """ class C { @@ -171,12 +160,10 @@ void M(int a, int b, int c) } } """); - } [Fact] - public async Task InvertMultiConditional3() - { - await TestInRegularAndScriptAsync( + public Task InvertMultiConditional3() + => TestInRegularAndScriptAsync( """ class C { @@ -195,12 +182,10 @@ void M(int a, int b, int c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task InverSelection() - { - await TestInRegularAndScriptAsync( + public Task InverSelection() + => TestInRegularAndScriptAsync( """ class C { @@ -219,15 +204,10 @@ void M(int a, int b, int c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task MissingInverSelection1() - { - // Can't convert selected partial subtrees - // -> see comment at AbstractInvertLogicalCodeRefactoringProvider::ComputeRefactoringsAsync - // -> "expected" result commented out & TestMissingXXX method used in the meantime - await TestMissingInRegularAndScriptAsync( + public Task MissingInverSelection1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -244,12 +224,10 @@ void M(int a, int b, int c) var x = !(!(a > 10 || b < 20) && c != 30); } }"*/); - } [Fact] - public async Task InvertMultiConditional4() - { - await TestInRegularAndScriptAsync( + public Task InvertMultiConditional4() + => TestInRegularAndScriptAsync( """ class C { @@ -268,12 +246,10 @@ void M(int a, int b, int c) } } """); - } [Fact] - public async Task TestMissingOnShortCircuitAnd() - { - await TestMissingAsync( + public Task TestMissingOnShortCircuitAnd() + => TestMissingAsync( """ class C { @@ -283,12 +259,10 @@ void M(bool x, int a, int b) } } """); - } [Fact] - public async Task TestMissingOnShortCircuitOr() - { - await TestMissingAsync( + public Task TestMissingOnShortCircuitOr() + => TestMissingAsync( """ class C { @@ -298,12 +272,10 @@ void M(bool x, int a, int b) } } """); - } [Fact] - public async Task TestSelectedOperator() - { - await TestInRegularAndScriptAsync( + public Task TestSelectedOperator() + => TestInRegularAndScriptAsync( """ class C { @@ -322,12 +294,10 @@ void M(bool x, int a, int b) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task MissingSelectedSubtree() - { - await TestMissingInRegularAndScriptAsync( + public Task MissingSelectedSubtree() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -337,12 +307,10 @@ void M(int a, int b, int c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertIsTypePattern1_CSharp8() - { - await TestInRegularAndScriptAsync( + public Task InvertIsTypePattern1_CSharp8() + => TestInRegularAndScriptAsync( """ class C { @@ -361,12 +329,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertIsTypePattern1_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task InvertIsTypePattern1_CSharp9() + => TestInRegularAndScriptAsync( """ class C { @@ -385,14 +351,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp9); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertIsNotTypePattern1_CSharp8() - { - // Note: this is not legal (since it's a 'not' pattern being used in C# 8). - // This test just makes sure we don't crash in cases like that. - await TestInRegularAndScriptAsync( + public Task InvertIsNotTypePattern1_CSharp8() + => TestInRegularAndScriptAsync( """ class C { @@ -411,12 +373,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertIsNotTypePattern1_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task InvertIsNotTypePattern1_CSharp9() + => TestInRegularAndScriptAsync( """ class C { @@ -435,12 +395,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp9); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertIsNullPattern1_CSharp8() - { - await TestInRegularAndScriptAsync( + public Task InvertIsNullPattern1_CSharp8() + => TestInRegularAndScriptAsync( """ class C { @@ -459,12 +417,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertIsNullPattern1_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task InvertIsNullPattern1_CSharp9() + => TestInRegularAndScriptAsync( """ class C { @@ -483,13 +439,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp9); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertIsNotNullPattern1_CSharp6() - { - // Result is illegal (uses a constant pattern in c# 6), but the original code was illegal as well. - await TestInRegularAndScriptAsync( + public Task InvertIsNotNullPattern1_CSharp6() + => TestInRegularAndScriptAsync( """ class C { @@ -508,12 +461,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp6); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertIsNotNullPattern1_CSharp8() - { - await TestInRegularAndScriptAsync( + public Task InvertIsNotNullPattern1_CSharp8() + => TestInRegularAndScriptAsync( """ class C { @@ -532,12 +483,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertIsNotNullPattern1_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task InvertIsNotNullPattern1_CSharp9() + => TestInRegularAndScriptAsync( """ class C { @@ -556,12 +505,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp9); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertIsTruePattern1_CSharp8() - { - await TestInRegularAndScriptAsync( + public Task InvertIsTruePattern1_CSharp8() + => TestInRegularAndScriptAsync( """ class C { @@ -580,12 +527,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertBooleanIsTruePattern1_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task InvertBooleanIsTruePattern1_CSharp9() + => TestInRegularAndScriptAsync( """ class C { @@ -604,12 +549,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp9); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64292")] - public async Task InvertNonBooleanIsTruePattern1_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task InvertNonBooleanIsTruePattern1_CSharp9() + => TestInRegularAndScriptAsync( """ class C { @@ -628,12 +571,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp9); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertIsFalsePattern1_CSharp8() - { - await TestInRegularAndScriptAsync( + public Task InvertIsFalsePattern1_CSharp8() + => TestInRegularAndScriptAsync( """ class C { @@ -652,12 +593,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertBooleanIsFalsePattern1_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task InvertBooleanIsFalsePattern1_CSharp9() + => TestInRegularAndScriptAsync( """ class C { @@ -676,12 +615,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp9); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64292")] - public async Task InvertNonBooleanIsFalsePattern1_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task InvertNonBooleanIsFalsePattern1_CSharp9() + => TestInRegularAndScriptAsync( """ class C { @@ -700,12 +637,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp9); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64558")] - public async Task InvertNumericIsGreaterThanPattern1_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task InvertNumericIsGreaterThanPattern1_CSharp9() + => TestInRegularAndScriptAsync( """ class C { @@ -724,12 +659,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp9); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64558")] - public async Task InvertNullableNumericIsGreaterThanPattern1_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task InvertNullableNumericIsGreaterThanPattern1_CSharp9() + => TestInRegularAndScriptAsync( """ class C { @@ -748,12 +681,10 @@ void M(bool x, int? a, object b) } } """, parseOptions: CSharp9); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64558")] - public async Task InvertNonNumericIsGreaterThanPattern1_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task InvertNonNumericIsGreaterThanPattern1_CSharp9() + => TestInRegularAndScriptAsync( """ class C { @@ -772,12 +703,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp9); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64558")] - public async Task InvertInvalidEqualsPattern1_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task InvertInvalidEqualsPattern1_CSharp9() + => TestInRegularAndScriptAsync( """ class C { @@ -796,12 +725,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp9); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertIsAndPattern1_CSharp8() - { - await TestInRegularAndScriptAsync( + public Task InvertIsAndPattern1_CSharp8() + => TestInRegularAndScriptAsync( """ class C { @@ -820,12 +747,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertIsAndPattern1_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task InvertIsAndPattern1_CSharp9() + => TestInRegularAndScriptAsync( """ class C { @@ -844,12 +769,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp9); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertIsOrPattern1_CSharp8() - { - await TestInRegularAndScriptAsync( + public Task InvertIsOrPattern1_CSharp8() + => TestInRegularAndScriptAsync( """ class C { @@ -868,12 +791,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertIsOrPattern1_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task InvertIsOrPattern1_CSharp9() + => TestInRegularAndScriptAsync( """ class C { @@ -892,12 +813,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp9); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertIsTypeWithDesignationPattern1_CSharp8() - { - await TestInRegularAndScriptAsync( + public Task InvertIsTypeWithDesignationPattern1_CSharp8() + => TestInRegularAndScriptAsync( """ class C { @@ -916,12 +835,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertIsTypeWithDesignationPattern1_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task InvertIsTypeWithDesignationPattern1_CSharp9() + => TestInRegularAndScriptAsync( """ class C { @@ -940,12 +857,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp9); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertIsVarPattern1_CSharp8() - { - await TestInRegularAndScriptAsync( + public Task InvertIsVarPattern1_CSharp8() + => TestInRegularAndScriptAsync( """ class C { @@ -964,12 +879,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertIsVarPattern1_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task InvertIsVarPattern1_CSharp9() + => TestInRegularAndScriptAsync( """ class C { @@ -988,12 +901,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp9); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertIsAndWithDesignationPattern1_CSharp8() - { - await TestInRegularAndScriptAsync( + public Task InvertIsAndWithDesignationPattern1_CSharp8() + => TestInRegularAndScriptAsync( """ class C { @@ -1012,12 +923,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertIsAndWithDesignationPattern1_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task InvertIsAndWithDesignationPattern1_CSharp9() + => TestInRegularAndScriptAsync( """ class C { @@ -1036,12 +945,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp9); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertIsAndWithDesignationPattern2_CSharp8() - { - await TestInRegularAndScriptAsync( + public Task InvertIsAndWithDesignationPattern2_CSharp8() + => TestInRegularAndScriptAsync( """ class C { @@ -1060,12 +967,10 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp8); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42368")] - public async Task InvertIsAndWithDesignationPattern2_CSharp9() - { - await TestInRegularAndScriptAsync( + public Task InvertIsAndWithDesignationPattern2_CSharp9() + => TestInRegularAndScriptAsync( """ class C { @@ -1084,5 +989,4 @@ void M(bool x, int a, object b) } } """, parseOptions: CSharp9); - } } diff --git a/src/Features/CSharpTest/MakeLocalFunctionStatic/MakeLocalFunctionStaticRefactoringTests.cs b/src/Features/CSharpTest/MakeLocalFunctionStatic/MakeLocalFunctionStaticRefactoringTests.cs index 59f420c0791e4..a01f9e48a1466 100644 --- a/src/Features/CSharpTest/MakeLocalFunctionStatic/MakeLocalFunctionStaticRefactoringTests.cs +++ b/src/Features/CSharpTest/MakeLocalFunctionStatic/MakeLocalFunctionStaticRefactoringTests.cs @@ -23,9 +23,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor private static readonly ParseOptions CSharp8ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8); [Fact] - public async Task ShouldNotTriggerForCSharp7() - { - await TestMissingAsync( + public Task ShouldNotTriggerForCSharp7() + => TestMissingAsync( """ class C { @@ -40,12 +39,10 @@ int N(int x) } } """, parameters: new TestParameters(parseOptions: CSharp72ParseOptions)); - } [Fact] - public async Task ShouldNotTriggerIfNoCaptures() - { - await TestMissingAsync( + public Task ShouldNotTriggerIfNoCaptures() + => TestMissingAsync( """ class C { @@ -60,12 +57,10 @@ int N(int x) } } """, parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); - } [Fact] - public async Task ShouldNotTriggerIfAlreadyStatic() - { - await TestMissingAsync( + public Task ShouldNotTriggerIfAlreadyStatic() + => TestMissingAsync( """ class C { @@ -80,12 +75,10 @@ int N(int x) } } """, parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); - } [Fact] - public async Task ShouldNotTriggerIfAlreadyStaticWithError() - { - await TestMissingAsync( + public Task ShouldNotTriggerIfAlreadyStaticWithError() + => TestMissingAsync( """ class C { @@ -100,12 +93,10 @@ int N(int x) } } """, parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38734")] - public async Task ShouldTriggerIfCapturesThisParameter1() - { - await TestInRegularAndScriptAsync( + public Task ShouldTriggerIfCapturesThisParameter1() + => TestInRegularAndScriptAsync( """ class C { @@ -138,12 +129,10 @@ static int AddLocal(C @this) } } """, parseOptions: CSharp8ParseOptions); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38734")] - public async Task ShouldTriggerIfCapturesThisParameter2() - { - await TestInRegularAndScriptAsync( + public Task ShouldTriggerIfCapturesThisParameter2() + => TestInRegularAndScriptAsync( """ class C { @@ -176,12 +165,10 @@ int N() } } """, parseOptions: CSharp8ParseOptions); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38734")] - public async Task ShouldTriggerIfCapturesThisParameter3() - { - await TestInRegularAndScriptAsync( + public Task ShouldTriggerIfCapturesThisParameter3() + => TestInRegularAndScriptAsync( """ class C { @@ -214,12 +201,10 @@ int N() } } """, parseOptions: CSharp8ParseOptions); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38734")] - public async Task ShouldTriggerIfCapturesThisParameter4() - { - await TestInRegularAndScriptAsync( + public Task ShouldTriggerIfCapturesThisParameter4() + => TestInRegularAndScriptAsync( """ class C { @@ -252,12 +237,10 @@ static int AddLocal(C @this, C c) } } """, parseOptions: CSharp8ParseOptions); - } [Fact] - public async Task ShouldTriggerIfExplicitlyPassedInThisParameter() - { - await TestInRegularAndScriptAsync( + public Task ShouldTriggerIfExplicitlyPassedInThisParameter() + => TestInRegularAndScriptAsync( """ class C { @@ -292,12 +275,10 @@ int N() } } """, parseOptions: CSharp8ParseOptions); - } [Fact] - public async Task ShouldTriggerForCSharp8() - { - await TestInRegularAndScriptAsync( + public Task ShouldTriggerForCSharp8() + => TestInRegularAndScriptAsync( """ class C { @@ -326,13 +307,11 @@ static int AddLocal(int x) } } """, -parseOptions: CSharp8ParseOptions); - } + parseOptions: CSharp8ParseOptions); [Fact] - public async Task TestMultipleVariables() - { - await TestInRegularAndScriptAsync( + public Task TestMultipleVariables() + => TestInRegularAndScriptAsync( """ class C { @@ -363,12 +342,10 @@ static int AddLocal(int x, int y) } } """, parseOptions: CSharp8ParseOptions); - } [Fact] - public async Task TestMultipleCalls() - { - await TestInRegularAndScriptAsync( + public Task TestMultipleCalls() + => TestInRegularAndScriptAsync( """ class C { @@ -400,12 +377,10 @@ static int AddLocal(int x, int y) } """ , parseOptions: CSharp8ParseOptions); - } [Fact] - public async Task TestMultipleCallsWithExistingParameters() - { - await TestInRegularAndScriptAsync( + public Task TestMultipleCallsWithExistingParameters() + => TestInRegularAndScriptAsync( """ class C { @@ -439,12 +414,10 @@ static int AddLocal(int a, int b, int x, int y) } """ , parseOptions: CSharp8ParseOptions); - } [Fact] - public async Task TestRecursiveCall() - { - await TestInRegularAndScriptAsync( + public Task TestRecursiveCall() + => TestInRegularAndScriptAsync( """ class C { @@ -477,12 +450,10 @@ static int AddLocal(int a, int b, int x, int y) } } """, parseOptions: CSharp8ParseOptions); - } [Fact] - public async Task TestCallInArgumentList() - { - await TestInRegularAndScriptAsync( + public Task TestCallInArgumentList() + => TestInRegularAndScriptAsync( """ class C { @@ -513,12 +484,10 @@ static int AddLocal(int a, int b, int x, int y) } } """, parseOptions: CSharp8ParseOptions); - } [Fact] - public async Task TestCallsWithNamedArguments() - { - await TestInRegularAndScriptAsync( + public Task TestCallsWithNamedArguments() + => TestInRegularAndScriptAsync( """ class C { @@ -552,12 +521,10 @@ static int AddLocal(int a, int b, int x, int y) } """ , parseOptions: CSharp8ParseOptions); - } [Fact] - public async Task TestCallsWithDafaultValue() - { - await TestInRegularAndScriptAsync( + public Task TestCallsWithDafaultValue() + => TestInRegularAndScriptAsync( """ class C { @@ -591,12 +558,10 @@ static int AddLocal(int a = 0, int b = 0, int x = 0, string y = null) } """ , parseOptions: CSharp8ParseOptions); - } [Fact] - public async Task TestWarningAnnotation() - { - await TestInRegularAndScriptAsync( + public Task TestWarningAnnotation() + => TestInRegularAndScriptAsync( """ class C { @@ -625,13 +590,11 @@ void N(int x) } } """, -parseOptions: CSharp8ParseOptions); - } + parseOptions: CSharp8ParseOptions); [Fact] - public async Task TestNonCamelCaseCapture() - { - await TestInRegularAndScriptAsync( + public Task TestNonCamelCaseCapture() + => TestInRegularAndScriptAsync( """ class C { @@ -662,13 +625,11 @@ static int AddLocal(int @static) } } """, -parseOptions: CSharp8ParseOptions); - } + parseOptions: CSharp8ParseOptions); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46858")] - public async Task ShouldNotTriggerIfCallsOtherLocalFunction() - { - await TestMissingAsync( + public Task ShouldNotTriggerIfCallsOtherLocalFunction() + => TestMissingAsync( """ class C { @@ -688,12 +649,10 @@ void B() } } """, parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); - } [Fact] - public async Task TestCallingStaticLocationFunction() - { - await TestInRegularAndScriptAsync( + public Task TestCallingStaticLocationFunction() + => TestInRegularAndScriptAsync( """ class C { @@ -732,13 +691,11 @@ static void B() } } """, -parseOptions: CSharp8ParseOptions); - } + parseOptions: CSharp8ParseOptions); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53179")] - public async Task TestLocalFunctionAsTopLevelStatement() - { - await TestAsync(""" + public Task TestLocalFunctionAsTopLevelStatement() + => TestAsync(""" int y = 10; return AddLocal(); @@ -755,6 +712,5 @@ static int AddLocal(int y) return y; } """, parseOptions: CSharp8ParseOptions); - } } diff --git a/src/Features/CSharpTest/MakeLocalFunctionStatic/PassInCapturedVariablesAsArgumentsCodeFixProviderTests.cs b/src/Features/CSharpTest/MakeLocalFunctionStatic/PassInCapturedVariablesAsArgumentsCodeFixProviderTests.cs index c4d44eb1d7110..e483b47705968 100644 --- a/src/Features/CSharpTest/MakeLocalFunctionStatic/PassInCapturedVariablesAsArgumentsCodeFixProviderTests.cs +++ b/src/Features/CSharpTest/MakeLocalFunctionStatic/PassInCapturedVariablesAsArgumentsCodeFixProviderTests.cs @@ -30,9 +30,8 @@ internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProvide private static readonly ParseOptions CSharp8ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8); [Fact] - public async Task TestMissingInCSharp7() - { - await TestMissingAsync( + public Task TestMissingInCSharp7() + => TestMissingAsync( """ class C { @@ -47,12 +46,10 @@ static int AddLocal() } } """, parameters: new TestParameters(parseOptions: CSharp72ParseOptions)); - } [Fact] - public async Task TestMissingIfNoDiagnostic() - { - await TestMissingAsync( + public Task TestMissingIfNoDiagnostic() + => TestMissingAsync( """ class C { @@ -67,12 +64,10 @@ int AddLocal() } } """, parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38734")] - public async Task TestAvailableIfCapturesThisParameter1() - { - await TestInRegularAndScriptAsync( + public Task TestAvailableIfCapturesThisParameter1() + => TestInRegularAndScriptAsync( """ class C { @@ -105,12 +100,10 @@ static int AddLocal(C @this, int x) } } """, parseOptions: CSharp8ParseOptions); - } [Fact] - public async Task ShouldTriggerForCSharp8() - { - await TestInRegularAndScriptAsync( + public Task ShouldTriggerForCSharp8() + => TestInRegularAndScriptAsync( """ class C { @@ -139,13 +132,11 @@ static int AddLocal(int x) } } """, -parseOptions: CSharp8ParseOptions); - } + parseOptions: CSharp8ParseOptions); [Fact] - public async Task TestMultipleVariables() - { - await TestInRegularAndScriptAsync( + public Task TestMultipleVariables() + => TestInRegularAndScriptAsync( """ class C { @@ -176,12 +167,10 @@ static int AddLocal(int x, int y) } } """, parseOptions: CSharp8ParseOptions); - } [Fact] - public async Task TestMultipleCalls() - { - await TestInRegularAndScriptAsync( + public Task TestMultipleCalls() + => TestInRegularAndScriptAsync( """ class C { @@ -213,12 +202,10 @@ static int AddLocal(int x, int y) } """ , parseOptions: CSharp8ParseOptions); - } [Fact] - public async Task TestMultipleCallsWithExistingParameters() - { - await TestInRegularAndScriptAsync( + public Task TestMultipleCallsWithExistingParameters() + => TestInRegularAndScriptAsync( """ class C { @@ -252,12 +239,10 @@ static int AddLocal(int a, int b, int x, int y) } """ , parseOptions: CSharp8ParseOptions); - } [Fact] - public async Task TestRecursiveCall() - { - await TestInRegularAndScriptAsync( + public Task TestRecursiveCall() + => TestInRegularAndScriptAsync( """ class C { @@ -290,12 +275,10 @@ static int AddLocal(int a, int b, int x, int y) } } """, parseOptions: CSharp8ParseOptions); - } [Fact] - public async Task TestCallInArgumentList() - { - await TestInRegularAndScriptAsync( + public Task TestCallInArgumentList() + => TestInRegularAndScriptAsync( """ class C { @@ -326,12 +309,10 @@ static int AddLocal(int a, int b, int x, int y) } } """, parseOptions: CSharp8ParseOptions); - } [Fact] - public async Task TestCallsWithNamedArguments() - { - await TestInRegularAndScriptAsync( + public Task TestCallsWithNamedArguments() + => TestInRegularAndScriptAsync( """ class C { @@ -365,12 +346,10 @@ static int AddLocal(int a, int b, int x, int y) } """ , parseOptions: CSharp8ParseOptions); - } [Fact] - public async Task TestCallsWithDafaultValue() - { - await TestInRegularAndScriptAsync( + public Task TestCallsWithDafaultValue() + => TestInRegularAndScriptAsync( """ class C { @@ -404,12 +383,10 @@ static int AddLocal(int a = 0, int b = 0, int x = 0, string y = null) } """ , parseOptions: CSharp8ParseOptions); - } [Fact] - public async Task TestWarningAnnotation() - { - await TestInRegularAndScriptAsync( + public Task TestWarningAnnotation() + => TestInRegularAndScriptAsync( """ class C { @@ -438,13 +415,11 @@ void N(int x) } } """, -parseOptions: CSharp8ParseOptions); - } + parseOptions: CSharp8ParseOptions); [Fact] - public async Task TestNonCamelCaseCapture() - { - await TestInRegularAndScriptAsync( + public Task TestNonCamelCaseCapture() + => TestInRegularAndScriptAsync( """ class C { @@ -475,13 +450,11 @@ static int AddLocal(int @static) } } """, -parseOptions: CSharp8ParseOptions); - } + parseOptions: CSharp8ParseOptions); [Fact] - public async Task TestFixAll() - { - await TestInRegularAndScriptAsync( + public Task TestFixAll() + => TestInRegularAndScriptAsync( """ class C { @@ -536,6 +509,5 @@ static int AddLocal(int a, int b, int x, int y) } } """, parseOptions: CSharp8ParseOptions); - } } diff --git a/src/Features/CSharpTest/MoveDeclarationNearReference/MoveDeclarationNearReferenceTests.cs b/src/Features/CSharpTest/MoveDeclarationNearReference/MoveDeclarationNearReferenceTests.cs index 149a187747c88..3bceb47c417e8 100644 --- a/src/Features/CSharpTest/MoveDeclarationNearReference/MoveDeclarationNearReferenceTests.cs +++ b/src/Features/CSharpTest/MoveDeclarationNearReference/MoveDeclarationNearReferenceTests.cs @@ -22,9 +22,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor => new CSharpMoveDeclarationNearReferenceCodeRefactoringProvider(); [Fact] - public async Task TestMove1() - { - await TestInRegularAndScriptAsync( + public Task TestMove1() + => TestInRegularAndScriptAsync( """ class C { @@ -49,12 +48,10 @@ void M() } } """); - } [Fact] - public async Task TestMove1_TopLevelStatement() - { - await TestAsync( + public Task TestMove1_TopLevelStatement() + => TestAsync( """ int [||]x; { @@ -68,12 +65,10 @@ await TestAsync( } """, TestOptions.Regular); - } [Fact] - public async Task TestMove2() - { - await TestInRegularAndScriptAsync( + public Task TestMove2() + => TestInRegularAndScriptAsync( """ class C { @@ -96,12 +91,10 @@ void M() } } """); - } [Fact] - public async Task TestMove2_TopLevelStatement() - { - await TestAsync( + public Task TestMove2_TopLevelStatement() + => TestAsync( """ int [||]x; Console.WriteLine(); @@ -113,12 +106,10 @@ await TestAsync( Console.WriteLine(x); """, TestOptions.Regular); - } [Fact] - public async Task TestMove3() - { - await TestInRegularAndScriptAsync( + public Task TestMove3() + => TestInRegularAndScriptAsync( """ class C { @@ -151,12 +142,10 @@ void M() } } """); - } [Fact] - public async Task TestMove3_TopLevelStatement() - { - await TestAsync( + public Task TestMove3_TopLevelStatement() + => TestAsync( """ int [||]x; Console.WriteLine(); @@ -180,12 +169,10 @@ await TestAsync( } """, TestOptions.Regular); - } [Fact] - public async Task TestMove4() - { - await TestInRegularAndScriptAsync( + public Task TestMove4() + => TestInRegularAndScriptAsync( """ class C { @@ -210,12 +197,10 @@ void M() } } """); - } [Fact] - public async Task TestMove4_TopLevelStatement() - { - await TestAsync( + public Task TestMove4_TopLevelStatement() + => TestAsync( """ int [||]x; Console.WriteLine(); @@ -231,12 +216,10 @@ await TestAsync( } """, TestOptions.Regular); - } [Fact] - public async Task TestAssign1() - { - await TestInRegularAndScriptAsync( + public Task TestAssign1() + => TestInRegularAndScriptAsync( """ class C { @@ -262,12 +245,10 @@ void M() } } """); - } [Fact] - public async Task TestAssign2() - { - await TestInRegularAndScriptAsync( + public Task TestAssign2() + => TestInRegularAndScriptAsync( """ class C { @@ -293,12 +274,10 @@ void M() } } """); - } [Fact] - public async Task TestAssign3() - { - await TestInRegularAndScriptAsync( + public Task TestAssign3() + => TestInRegularAndScriptAsync( """ class C { @@ -325,12 +304,10 @@ void M() } } """); - } [Fact] - public async Task TestMissing1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissing1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -341,22 +318,18 @@ void M() } } """); - } [Fact] - public async Task TestMissing1_TopLevelStatement() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissing1_TopLevelStatement() + => TestMissingInRegularAndScriptAsync( """ int [||]x; Console.WriteLine(x); """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538424")] - public async Task TestMissingWhenReferencedInDeclaration() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWhenReferencedInDeclaration() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -369,12 +342,10 @@ static void Main() } } """); - } [Fact] - public async Task TestMissingWhenInDeclarationGroup() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWhenInDeclarationGroup() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -386,23 +357,19 @@ static void Main() } } """); - } [Fact] - public async Task TestMissingWhenInDeclarationGroup_TopLevelStatement() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWhenInDeclarationGroup_TopLevelStatement() + => TestMissingInRegularAndScriptAsync( """ int [||]i = 5; int j = 10; Console.WriteLine(i); """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541475")] - public async Task Regression8190() - { - await TestMissingInRegularAndScriptAsync( + public Task Regression8190() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -414,12 +381,10 @@ void M() } } """); - } [Fact] - public async Task TestFormatting() - { - await TestInRegularAndScriptAsync( + public Task TestFormatting() + => TestInRegularAndScriptAsync( """ class Program { @@ -440,12 +405,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestFormatting_TopLevelStatement() - { - await TestAsync( + public Task TestFormatting_TopLevelStatement() + => TestAsync( """ int [||]i = 5; Console.WriteLine(); Console.Write(i); @@ -455,12 +418,10 @@ await TestAsync( int i = 5; Console.Write(i); """, TestOptions.Regular); - } [Fact] - public async Task TestMissingInHiddenBlock1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingInHiddenBlock1() + => TestMissingInRegularAndScriptAsync( """ #line default class Program @@ -475,12 +436,10 @@ void Main() #line default } """); - } [Fact] - public async Task TestMissingInHiddenBlock2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingInHiddenBlock2() + => TestMissingInRegularAndScriptAsync( """ #line default class Program @@ -496,12 +455,10 @@ void Main() } } """); - } [Fact] - public async Task TestMissingInHiddenBlock2_TopLevelStatement() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingInHiddenBlock2_TopLevelStatement() + => TestMissingInRegularAndScriptAsync( """ #line default @@ -512,12 +469,10 @@ await TestMissingInRegularAndScriptAsync( #line default Bar(x); """); - } [Fact] - public async Task TestAvailableInNonHiddenBlock1() - { - await TestInRegularAndScriptAsync( + public Task TestAvailableInNonHiddenBlock1() + => TestInRegularAndScriptAsync( """ #line default class Program @@ -546,12 +501,10 @@ void Main() #line default } """); - } [Fact] - public async Task TestAvailableInNonHiddenBlock2() - { - await TestInRegularAndScriptAsync( + public Task TestAvailableInNonHiddenBlock2() + => TestInRegularAndScriptAsync( """ #line default class Program @@ -584,12 +537,10 @@ void Main() } } """); - } [Fact] - public async Task TestAvailableInNonHiddenBlock2_TopLevelStatement() - { - await TestAsync( + public Task TestAvailableInNonHiddenBlock2_TopLevelStatement() + => TestAsync( """ #line default @@ -615,12 +566,10 @@ await TestAsync( Bar(x); """, TestOptions.Regular); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545435")] - public async Task TestWarnOnChangingScopes1() - { - await TestInRegularAndScriptAsync( + public Task TestWarnOnChangingScopes1() + => TestInRegularAndScriptAsync( """ using System.Linq; @@ -655,12 +604,10 @@ void Main() } """, title: FeaturesResources.Move_declaration_near_reference_may_change_semantics); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545435")] - public async Task TestWarnOnChangingScopes1_TopLevelStatement() - { - await TestAsync( + public Task TestWarnOnChangingScopes1_TopLevelStatement() + => TestAsync( """ using System.Linq; @@ -684,12 +631,10 @@ await TestAsync( }); """, TestOptions.Regular); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545435")] - public async Task TestWarnOnChangingScopes2() - { - await TestInRegularAndScriptAsync( + public Task TestWarnOnChangingScopes2() + => TestInRegularAndScriptAsync( """ using System; using System.Linq; @@ -724,12 +669,10 @@ void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545435")] - public async Task TestWarnOnChangingScopes2_TopLevelStatement() - { - await TestAsync( + public Task TestWarnOnChangingScopes2_TopLevelStatement() + => TestAsync( """ using System; using System.Linq; @@ -754,12 +697,10 @@ await TestAsync( } """, TestOptions.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/pull/44664")] - public async Task TestWarnOnChangingScopes3() - { - await TestInRegularAndScriptAsync( + public Task TestWarnOnChangingScopes3() + => TestInRegularAndScriptAsync( """ using System; using System.Linq; @@ -794,12 +735,10 @@ void LocalFunction() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/pull/44664")] - public async Task TestWarnOnChangingScopes3_TopLevelStatement() - { - await TestAsync( + public Task TestWarnOnChangingScopes3_TopLevelStatement() + => TestAsync( """ using System; using System.Linq; @@ -824,12 +763,10 @@ void LocalFunction() } """, TestOptions.Regular); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545840")] - public async Task InsertCastIfNecessary1() - { - await TestInRegularAndScriptAsync( + public Task InsertCastIfNecessary1() + => TestInRegularAndScriptAsync( """ using System; @@ -873,12 +810,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545835")] - public async Task InsertCastIfNecessary2() - { - await TestInRegularAndScriptAsync( + public Task InsertCastIfNecessary2() + => TestInRegularAndScriptAsync( """ using System; @@ -918,12 +853,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546267")] - public async Task MissingIfNotInDeclarationSpan() - { - await TestMissingInRegularAndScriptAsync( + public Task MissingIfNotInDeclarationSpan() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -946,12 +879,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task Tuple() - { - await TestInRegularAndScriptAsync( + public Task Tuple() + => TestInRegularAndScriptAsync( """ class C { @@ -976,12 +907,10 @@ void M() } } """); - } [Fact] - public async Task TupleWithNames() - { - await TestInRegularAndScriptAsync( + public Task TupleWithNames() + => TestInRegularAndScriptAsync( """ class C { @@ -1006,12 +935,10 @@ void M() } } """); - } [Fact] - public async Task TestComments01() - { - await TestInRegularAndScriptAsync( + public Task TestComments01() + => TestInRegularAndScriptAsync( """ class Program { @@ -1038,12 +965,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestComments02() - { - await TestInRegularAndScriptAsync( + public Task TestComments02() + => TestInRegularAndScriptAsync( """ class Program { @@ -1074,12 +999,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestComments03() - { - await TestInRegularAndScriptAsync( + public Task TestComments03() + => TestInRegularAndScriptAsync( """ class Program { @@ -1108,12 +1031,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestComments04() - { - await TestInRegularAndScriptAsync( + public Task TestComments04() + => TestInRegularAndScriptAsync( """ class Program { @@ -1146,12 +1067,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestComments05() - { - await TestInRegularAndScriptAsync( + public Task TestComments05() + => TestInRegularAndScriptAsync( """ class Program { @@ -1187,12 +1106,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestComments06() - { - await TestInRegularAndScriptAsync( + public Task TestComments06() + => TestInRegularAndScriptAsync( """ class Program { @@ -1232,12 +1149,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestComments07() - { - await TestInRegularAndScriptAsync( + public Task TestComments07() + => TestInRegularAndScriptAsync( """ class Program { @@ -1275,12 +1190,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestComments08() - { - await TestInRegularAndScriptAsync( + public Task TestComments08() + => TestInRegularAndScriptAsync( """ class Program { @@ -1322,12 +1235,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestMergeComments01() - { - await TestInRegularAndScriptAsync( + public Task TestMergeComments01() + => TestInRegularAndScriptAsync( """ class Program { @@ -1355,12 +1266,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestMergeComments02() - { - await TestInRegularAndScriptAsync( + public Task TestMergeComments02() + => TestInRegularAndScriptAsync( """ class Program { @@ -1392,12 +1301,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestMergeComments03() - { - await TestInRegularAndScriptAsync( + public Task TestMergeComments03() + => TestInRegularAndScriptAsync( """ class Program { @@ -1427,12 +1334,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestMergeComments04() - { - await TestInRegularAndScriptAsync( + public Task TestMergeComments04() + => TestInRegularAndScriptAsync( """ class Program { @@ -1466,12 +1371,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestMergeComments05() - { - await TestInRegularAndScriptAsync( + public Task TestMergeComments05() + => TestInRegularAndScriptAsync( """ class Program { @@ -1507,12 +1410,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestMergeComments06() - { - await TestInRegularAndScriptAsync( + public Task TestMergeComments06() + => TestInRegularAndScriptAsync( """ class Program { @@ -1552,12 +1453,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestMergeComments07() - { - await TestInRegularAndScriptAsync( + public Task TestMergeComments07() + => TestInRegularAndScriptAsync( """ class Program { @@ -1595,12 +1494,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestMergeComments07_TopLevelStatement() - { - await TestAsync( + public Task TestMergeComments07_TopLevelStatement() + => TestAsync( """ if (true) { @@ -1627,12 +1524,10 @@ await TestAsync( Console.Write(i); """, TestOptions.Regular); - } [Fact] - public async Task TestMergeComments08() - { - await TestInRegularAndScriptAsync( + public Task TestMergeComments08() + => TestInRegularAndScriptAsync( """ class Program { @@ -1674,12 +1569,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestMergeComments08_TopLevelStatement() - { - await TestAsync( + public Task TestMergeComments08_TopLevelStatement() + => TestAsync( """ if (true) { @@ -1710,12 +1603,10 @@ await TestAsync( } """, TestOptions.Regular); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21907")] - public async Task TestMissingOnCrossFunction1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnCrossFunction1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1740,12 +1631,10 @@ void Local() public static void Out(out T t) => t = default; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21907")] - public async Task TestMissingOnCrossFunction2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnCrossFunction2() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1773,12 +1662,10 @@ void InnerLocal() public static void Out(out T t) => t = default; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21907")] - public async Task TestMissingOnCrossFunction3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnCrossFunction3() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1805,12 +1692,10 @@ void Local() public static void Out(out T t) => t = default; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21907")] - public async Task TestMissingOnCrossFunction4() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnCrossFunction4() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1839,12 +1724,10 @@ void Local() public static void Out(out T t) => t = default; } """); - } [Fact] - public async Task TestMoveInsideSwitchSection() - { - await TestInRegularAndScriptAsync( + public Task TestMoveInsideSwitchSection() + => TestInRegularAndScriptAsync( """ class C { @@ -1877,12 +1760,10 @@ void M() } } """); - } [Fact] - public async Task TestMoveIntoSwitchSection() - { - await TestInRegularAndScriptAsync( + public Task TestMoveIntoSwitchSection() + => TestInRegularAndScriptAsync( """ class C { @@ -1912,12 +1793,10 @@ void M() } } """); - } [Fact] - public async Task TestMoveIntoSwitchSection_TopLevelStatement() - { - await TestAsync( + public Task TestMoveIntoSwitchSection_TopLevelStatement() + => TestAsync( """ int [||]x; switch (true) @@ -1936,12 +1815,10 @@ await TestAsync( } """, TestOptions.Regular); - } [Fact] - public async Task TestUsedInMultipleSwitchSections_MoveToSwitchStatement() - { - await TestInRegularAndScriptAsync( + public Task TestUsedInMultipleSwitchSections_MoveToSwitchStatement() + => TestInRegularAndScriptAsync( """ class C { @@ -1980,12 +1857,10 @@ void M() } } """); - } [Fact] - public async Task TestUsedInMultipleSwitchSections_TopLevelStatement_MoveToSwitchStatement() - { - await TestAsync( + public Task TestUsedInMultipleSwitchSections_TopLevelStatement_MoveToSwitchStatement() + => TestAsync( """ int [||]x; System.Console.WriteLine(); @@ -2013,12 +1888,10 @@ await TestAsync( } """, TestOptions.Regular); - } [Fact] - public async Task TestUsedInMultipleSwitchSections_CannotMove() - { - await TestMissingInRegularAndScriptAsync( + public Task TestUsedInMultipleSwitchSections_CannotMove() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2037,12 +1910,10 @@ void M() } } """); - } [Fact] - public async Task TestUsedInMultipleSwitchSections_TopLevelStatement_CannotMove() - { - await TestMissingInRegularAndScriptAsync( + public Task TestUsedInMultipleSwitchSections_TopLevelStatement_CannotMove() + => TestMissingInRegularAndScriptAsync( """ int [||]x; switch (true) @@ -2055,5 +1926,4 @@ await TestMissingInRegularAndScriptAsync( break; } """); - } } diff --git a/src/Features/CSharpTest/NameTupleElement/NameTupleElementTests.cs b/src/Features/CSharpTest/NameTupleElement/NameTupleElementTests.cs index c7eab8d158907..ccd428b4039dc 100644 --- a/src/Features/CSharpTest/NameTupleElement/NameTupleElementTests.cs +++ b/src/Features/CSharpTest/NameTupleElement/NameTupleElementTests.cs @@ -21,218 +21,206 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor => new CSharpNameTupleElementCodeRefactoringProvider(); [Fact] - public async Task TestInCall_FirstElement() - { - await TestInRegularAndScript1Async( + public Task TestInCall_FirstElement() + => TestInRegularAndScript1Async( @"class C { void M((int arg1, int arg2) x) => M(([||]1, 2)); }", @"class C { void M((int arg1, int arg2) x) => M((arg1: 1, 2)); }"); - } [Fact] - public async Task TestInCall_Deep() - { - await TestInRegularAndScript1Async( -@"class C -{ - void M((int arg1, int arg2) x) => M((Method([||]1), 2)); - int Method(int x) => throw null; -}", -@"class C -{ - void M((int arg1, int arg2) x) => M((arg1: Method(1), 2)); - int Method(int x) => throw null; -}"); - } - - [Fact] - public async Task TestInCall_Deep2() - { - await TestInRegularAndScript1Async( -@"class C -{ - void M((int arg1, int arg2) x) => M((1, Method(1[||], 2))); - int Method((int arg3, int arg4) x) => throw null; -}", -@"class C -{ - void M((int arg1, int arg2) x) => M((1, arg2: Method(1, 2))); - int Method((int arg3, int arg4) x) => throw null; -}"); - } - - [Fact] - public async Task TestInCall_Deep3() - { - await TestInRegularAndScript1Async( -@"class C -{ - void M((int arg1, int arg2) x) => M((1, Method[||](1, 2))); - int Method((int arg3, int arg4) x) => throw null; -}", -@"class C -{ - void M((int arg1, int arg2) x) => M((1, arg2: Method(1, 2))); - int Method((int arg3, int arg4) x) => throw null; -}"); - } - - [Fact] - public async Task TestInCall_FirstElement_EscapedNamed() - { - await TestInRegularAndScript1Async( + public Task TestInCall_Deep() + => TestInRegularAndScript1Async( + """ + class C + { + void M((int arg1, int arg2) x) => M((Method([||]1), 2)); + int Method(int x) => throw null; + } + """, + """ + class C + { + void M((int arg1, int arg2) x) => M((arg1: Method(1), 2)); + int Method(int x) => throw null; + } + """); + + [Fact] + public Task TestInCall_Deep2() + => TestInRegularAndScript1Async( + """ + class C + { + void M((int arg1, int arg2) x) => M((1, Method(1[||], 2))); + int Method((int arg3, int arg4) x) => throw null; + } + """, + """ + class C + { + void M((int arg1, int arg2) x) => M((1, arg2: Method(1, 2))); + int Method((int arg3, int arg4) x) => throw null; + } + """); + + [Fact] + public Task TestInCall_Deep3() + => TestInRegularAndScript1Async( + """ + class C + { + void M((int arg1, int arg2) x) => M((1, Method[||](1, 2))); + int Method((int arg3, int arg4) x) => throw null; + } + """, + """ + class C + { + void M((int arg1, int arg2) x) => M((1, arg2: Method(1, 2))); + int Method((int arg3, int arg4) x) => throw null; + } + """); + + [Fact] + public Task TestInCall_FirstElement_EscapedNamed() + => TestInRegularAndScript1Async( @"class C { void M((int @int, int arg2) x) => M(([||]1, 2)); }", @"class C { void M((int @int, int arg2) x) => M((@int: 1, 2)); }"); - } [Fact] public async Task TestInCall_FirstElement_AlreadyNamed() => await TestMissingAsync(@"class C { void M((int arg1, int arg2) x) => M(([||]arg1: 1, 2)); }"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35157")] - public async Task TestUntypedTuple() - { - await TestMissingAsync( -@"class C -{ - void M() - { - _ = ([||]null, 2); - } -}"); - } - - [Fact] - public async Task TestInvocationArgument() - { - await TestMissingAsync( -@"class C -{ - void M(string arg1, int arg2) - { - M([||]null, 2); - } -}"); - } + public Task TestUntypedTuple() + => TestMissingAsync( + """ + class C + { + void M() + { + _ = ([||]null, 2); + } + } + """); + + [Fact] + public Task TestInvocationArgument() + => TestMissingAsync( + """ + class C + { + void M(string arg1, int arg2) + { + M([||]null, 2); + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestWithSelection() - { - await TestInRegularAndScript1Async( + public Task TestWithSelection() + => TestInRegularAndScript1Async( @"class C { void M((int arg1, int arg2) x) => M(([|1|], 2)); }", @"class C { void M((int arg1, int arg2) x) => M((arg1: 1, 2)); }"); - } [Fact] - public async Task TestWithConversion() - { - await TestMissingAsync( -@"class C -{ - void M(C x) => M(([|1|], 2)); - public static implicit operator C((int arg1, int arg2) x) => throw null; -}"); - } + public Task TestWithConversion() + => TestMissingAsync( + """ + class C + { + void M(C x) => M(([|1|], 2)); + public static implicit operator C((int arg1, int arg2) x) => throw null; + } + """); [Fact] - public async Task TestInCall_FirstElement_WithTrivia() - { - await TestInRegularAndScript1Async( + public Task TestInCall_FirstElement_WithTrivia() + => TestInRegularAndScript1Async( @"class C { void M((int arg1, int arg2) x) => M((/*before*/ [||]1 /*after*/, 2)); }", @"class C { void M((int arg1, int arg2) x) => M((/*before*/ arg1: 1 /*after*/, 2)); }"); - } [Fact] - public async Task TestInCall_FirstElement_Nested() - { - await TestInRegularAndScript1Async( -@"class C -{ - int M((int arg1, int arg2) x) - => M((M(([||]1, 2)), 3)); -}", -@"class C -{ - int M((int arg1, int arg2) x) - => M((M((arg1: 1, 2)), 3)); -}"); - } - - [Fact] - public async Task TestInCall_FirstComma() - { - await TestInRegularAndScript1Async( + public Task TestInCall_FirstElement_Nested() + => TestInRegularAndScript1Async( + """ + class C + { + int M((int arg1, int arg2) x) + => M((M(([||]1, 2)), 3)); + } + """, + """ + class C + { + int M((int arg1, int arg2) x) + => M((M((arg1: 1, 2)), 3)); + } + """); + + [Fact] + public Task TestInCall_FirstComma() + => TestInRegularAndScript1Async( @"class C { void M((int arg1, int arg2) x) => M((1[||], 2)); }", @"class C { void M((int arg1, int arg2) x) => M((arg1: 1, 2)); }"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestInCall_FirstComma2() - { - await TestInRegularAndScript1Async( + public Task TestInCall_FirstComma2() + => TestInRegularAndScript1Async( @"class C { void M((int arg1, int arg2) x) => M((1,[||] 2)); }", @"class C { void M((int arg1, int arg2) x) => M((1, arg2: 2)); }"); - } [Fact] - public async Task TestInCall_SecondElement() - { - await TestInRegularAndScript1Async( + public Task TestInCall_SecondElement() + => TestInRegularAndScript1Async( @"class C { void M((int arg1, int arg2) x) => M((1, [||]2)); }", @"class C { void M((int arg1, int arg2) x) => M((1, arg2: 2)); }"); - } [Fact] - public async Task TestInCall_CloseParen() - { - await TestInRegularAndScript1Async( + public Task TestInCall_CloseParen() + => TestInRegularAndScript1Async( @"class C { void M((int arg1, int arg2) x) => M((1, 2[||])); }", @"class C { void M((int arg1, int arg2) x) => M((1, arg2: 2)); }"); - } [Fact] public async Task TestUnnamedTuple() => await TestMissingAsync(@"class C { void M((int, int) x) => M(([||]1, 2)); }"); [Fact] - public async Task TestArrowReturnedTuple() - { - await TestInRegularAndScript1Async( + public Task TestArrowReturnedTuple() + => TestInRegularAndScript1Async( @"class C { (int arg1, int arg2, int arg3) M() => ([||]1, 2); }", @"class C { (int arg1, int arg2, int arg3) M() => (arg1: 1, 2); }"); - } - - [Fact] - public async Task TestArrowReturnedTuple_LocalFunction() - { - await TestInRegularAndScript1Async( -@"class C -{ - void M() - { - (int arg1, int arg2, int arg3) local() => ([||]1, 2); - } -}", -@"class C -{ - void M() - { - (int arg1, int arg2, int arg3) local() => (arg1: 1, 2); - } -}"); - } [Fact] - public async Task TestReturnedTuple() - { - await TestInRegularAndScript1Async( + public Task TestArrowReturnedTuple_LocalFunction() + => TestInRegularAndScript1Async( + """ + class C + { + void M() + { + (int arg1, int arg2, int arg3) local() => ([||]1, 2); + } + } + """, + """ + class C + { + void M() + { + (int arg1, int arg2, int arg3) local() => (arg1: 1, 2); + } + } + """); + + [Fact] + public Task TestReturnedTuple() + => TestInRegularAndScript1Async( @"class C { (int arg1, int arg2, int arg3) M() { return ([||]1, 2); } }", @"class C { (int arg1, int arg2, int arg3) M() { return (arg1: 1, 2); } }"); - } [Fact] - public async Task TestReturnedTuple_LongerTuple() - { - await TestMissingAsync( + public Task TestReturnedTuple_LongerTuple() + => TestMissingAsync( @"class C { (int arg1, int arg2) M() => (1, 2, [||]3); }"); - } } diff --git a/src/Features/CSharpTest/OrganizeImports/CSharpOrganizeImportsCodeRefactoringProviderTests.cs b/src/Features/CSharpTest/OrganizeImports/CSharpOrganizeImportsCodeRefactoringProviderTests.cs new file mode 100644 index 0000000000000..72650e5a4a904 --- /dev/null +++ b/src/Features/CSharpTest/OrganizeImports/CSharpOrganizeImportsCodeRefactoringProviderTests.cs @@ -0,0 +1,67 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; +using Microsoft.CodeAnalysis.OrganizeImports; +using Microsoft.CodeAnalysis.Test.Utilities; +using Xunit; + +namespace Microsoft.CodeAnalysis.CSharp.UnitTests.OrganizeImports; + +using VerifyCS = CSharpCodeRefactoringVerifier; + +[UseExportProvider, Trait(Traits.Feature, Traits.Features.CodeActionsOrganizeImports)] +public sealed class CSharpOrganizeImportsCodeRefactoringProviderTests +{ + [Fact] + public Task Test1() + => new VerifyCS.Test + { + TestCode = """ + [||]using System.Collections; + using System; + + """, + FixedCode = """ + using System; + using System.Collections; + + """, + }.RunAsync(); + + [Fact] + public Task TestWithinNamespace() + => new VerifyCS.Test + { + TestCode = """ + namespace N + { + [||]using System.Collections; + using System; + } + """, + FixedCode = """ + namespace N + { + using System; + using System.Collections; + } + """, + }.RunAsync(); + + [Fact] + public Task TestNotWhenAlreadySorted() + => new VerifyCS.Test + { + TestCode = """ + [||]using System; + using System.Collections; + """, + FixedCode = """ + using System; + using System.Collections; + """, + }.RunAsync(); +} diff --git a/src/Features/CSharpTest/PreferFrameworkType/PreferFrameworkTypeTests.cs b/src/Features/CSharpTest/PreferFrameworkType/PreferFrameworkTypeTests.cs index c418e9939d5b9..517d68aa799bc 100644 --- a/src/Features/CSharpTest/PreferFrameworkType/PreferFrameworkTypeTests.cs +++ b/src/Features/CSharpTest/PreferFrameworkType/PreferFrameworkTypeTests.cs @@ -56,9 +56,8 @@ private OptionsCollection FrameworkTypeInMemberAccess }; [Fact] - public async Task NotWhenOptionsAreNotSet() - { - await TestMissingInRegularAndScriptAsync( + public Task NotWhenOptionsAreNotSet() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -70,12 +69,10 @@ void Method() } } """, new TestParameters(options: NoFrameworkType)); - } [Fact] - public async Task NotOnDynamic() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnDynamic() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -87,12 +84,10 @@ void Method() } } """, new TestParameters(options: FrameworkTypeInDeclaration)); - } [Fact] - public async Task NotOnSystemVoid() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnSystemVoid() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -103,12 +98,10 @@ class Program } } """, new TestParameters(options: FrameworkTypeEverywhere)); - } [Fact] - public async Task NotOnUserdefinedType() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnUserdefinedType() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -120,12 +113,10 @@ void Method() } } """, new TestParameters(options: FrameworkTypeEverywhere)); - } [Fact] - public async Task NotOnFrameworkType() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnFrameworkType() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -137,12 +128,10 @@ void Method() } } """, new TestParameters(options: FrameworkTypeInDeclaration)); - } [Fact] - public async Task NotOnQualifiedTypeSyntax() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnQualifiedTypeSyntax() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -152,12 +141,10 @@ void Method() } } """, new TestParameters(options: FrameworkTypeInDeclaration)); - } [Fact] - public async Task NotOnFrameworkTypeWithNoPredefinedKeywordEquivalent() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnFrameworkTypeWithNoPredefinedKeywordEquivalent() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -169,12 +156,10 @@ void Method() } } """, new TestParameters(options: FrameworkTypeInDeclaration)); - } [Fact] - public async Task NotOnIdentifierThatIsNotTypeSyntax() - { - await TestMissingInRegularAndScriptAsync( + public Task NotOnIdentifierThatIsNotTypeSyntax() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -186,57 +171,40 @@ void Method() } } """, new TestParameters(options: FrameworkTypeInDeclaration)); - } [Fact] - public async Task QualifiedReplacementWhenNoUsingFound() - { - var code = - """ + public Task QualifiedReplacementWhenNoUsingFound() + => TestInRegularAndScriptAsync(""" class Program { [|string|] _myfield = 5; } - """; - - var expected = - """ + """, """ class Program { System.String _myfield = 5; } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); [Fact] - public async Task FieldDeclaration() - { - var code = - """ + public Task FieldDeclaration() + => TestInRegularAndScriptAsync(""" using System; class Program { [|int|] _myfield; } - """; - - var expected = - """ + """, """ using System; class Program { Int32 _myfield; } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); [Fact] - public async Task TestNint_WithNumericIntPtr_CSharp11() - { - var code = - """ + public Task TestNint_WithNumericIntPtr_CSharp11() + => TestInRegularAndScriptAsync(""" using System; @@ -246,24 +214,17 @@ class Program } - """; - - var expected = - """ + """, """ using System; class Program { IntPtr _myfield; } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); [Fact] - public async Task TestNint_WithNumericIntPtr_CSharp8() - { - var code = - """ + public Task TestNint_WithNumericIntPtr_CSharp8() + => TestMissingInRegularAndScriptAsync(""" using System; @@ -273,16 +234,13 @@ class Program } - """; - await TestMissingInRegularAndScriptAsync(code, new TestParameters(options: FrameworkTypeInDeclaration)); - } + """, new TestParameters(options: FrameworkTypeInDeclaration)); [Theory] [InlineData("CommonReferences")] [InlineData("CommonReferencesNet7")] - public async Task TestNint_WithoutNumericIntPtr_CSharp10(string references) - { - var code = $$""" + public Task TestNint_WithoutNumericIntPtr_CSharp10(string references) + => TestMissingInRegularAndScriptAsync($$""" using System; @@ -292,16 +250,13 @@ class Program } - """; - await TestMissingInRegularAndScriptAsync(code, new TestParameters(options: FrameworkTypeInDeclaration)); - } + """, new TestParameters(options: FrameworkTypeInDeclaration)); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/74973")] [InlineData(LanguageVersion.CSharp10)] [InlineData(LanguageVersion.CSharp11)] - public async Task TestNint_WithoutNumericIntPtr(LanguageVersion version) - { - await TestMissingInRegularAndScriptAsync($$""" + public Task TestNint_WithoutNumericIntPtr(LanguageVersion version) + => TestMissingInRegularAndScriptAsync($$""" using System; @@ -312,201 +267,142 @@ class Program """, new TestParameters(options: FrameworkTypeInDeclaration)); - } [Fact] - public async Task FieldDeclarationWithInitializer() - { - var code = - """ + public Task FieldDeclarationWithInitializer() + => TestInRegularAndScriptAsync(""" using System; class Program { [|string|] _myfield = 5; } - """; - - var expected = - """ + """, """ using System; class Program { String _myfield = 5; } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); [Fact] - public async Task DelegateDeclaration() - { - var code = - """ + public Task DelegateDeclaration() + => TestInRegularAndScriptAsync(""" using System; class Program { public delegate [|int|] PerformCalculation(int x, int y); } - """; - - var expected = - """ + """, """ using System; class Program { public delegate Int32 PerformCalculation(int x, int y); } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); [Fact] - public async Task PropertyDeclaration() - { - var code = - """ + public Task PropertyDeclaration() + => TestInRegularAndScriptAsync(""" using System; class Program { public [|long|] MyProperty { get; set; } } - """; - - var expected = - """ + """, """ using System; class Program { public Int64 MyProperty { get; set; } } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); [Fact] - public async Task GenericPropertyDeclaration() - { - var code = - """ + public Task GenericPropertyDeclaration() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; class Program { public List<[|long|]> MyProperty { get; set; } } - """; - - var expected = - """ + """, """ using System; using System.Collections.Generic; class Program { public List MyProperty { get; set; } } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); [Fact] - public async Task QualifiedReplacementInGenericTypeParameter() - { - var code = - """ + public Task QualifiedReplacementInGenericTypeParameter() + => TestInRegularAndScriptAsync(""" using System.Collections.Generic; class Program { public List<[|long|]> MyProperty { get; set; } } - """; - - var expected = - """ + """, """ using System.Collections.Generic; class Program { public List MyProperty { get; set; } } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); [Fact] - public async Task MethodDeclarationReturnType() - { - var code = - """ + public Task MethodDeclarationReturnType() + => TestInRegularAndScriptAsync(""" using System; class Program { public [|long|] Method() { } } - """; - - var expected = - """ + """, """ using System; class Program { public Int64 Method() { } } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); [Fact] - public async Task MethodDeclarationParameters() - { - var code = - """ + public Task MethodDeclarationParameters() + => TestInRegularAndScriptAsync(""" using System; class Program { public void Method([|double|] d) { } } - """; - - var expected = - """ + """, """ using System; class Program { public void Method(Double d) { } } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); [Fact] - public async Task GenericMethodInvocation() - { - var code = - """ + public Task GenericMethodInvocation() + => TestInRegularAndScriptAsync(""" using System; class Program { public void Method() { } public void Test() { Method<[|int|]>(); } } - """; - - var expected = - """ + """, """ using System; class Program { public void Method() { } public void Test() { Method(); } } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); [Fact] - public async Task LocalDeclaration() - { - var code = - """ + public Task LocalDeclaration() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -515,10 +411,7 @@ void Method() [|int|] f = 5; } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -527,15 +420,11 @@ void Method() Int32 f = 5; } } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); [Fact] - public async Task MemberAccess() - { - var code = - """ + public Task MemberAccess() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -544,10 +433,7 @@ void Method() Console.Write([|int|].MaxValue); } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -556,15 +442,11 @@ void Method() Console.Write(Int32.MaxValue); } } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInMemberAccess); - } + """, options: FrameworkTypeInMemberAccess); [Fact] - public async Task MemberAccess2() - { - var code = - """ + public Task MemberAccess2() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -573,10 +455,7 @@ void Method() var x = [|int|].Parse("1"); } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -585,15 +464,11 @@ void Method() var x = Int32.Parse("1"); } } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInMemberAccess); - } + """, options: FrameworkTypeInMemberAccess); [Fact] - public async Task DocCommentTriviaCrefExpression() - { - var code = - """ + public Task DocCommentTriviaCrefExpression() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -602,10 +477,7 @@ void Method() { } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -614,15 +486,11 @@ void Method() { } } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInMemberAccess); - } + """, options: FrameworkTypeInMemberAccess); [Fact] - public async Task DefaultExpression() - { - var code = - """ + public Task DefaultExpression() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -631,10 +499,7 @@ void Method() var v = default([|int|]); } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -643,15 +508,11 @@ void Method() var v = default(Int32); } } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); [Fact] - public async Task TypeOfExpression() - { - var code = - """ + public Task TypeOfExpression() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -660,10 +521,7 @@ void Method() var v = typeof([|int|]); } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -672,15 +530,11 @@ void Method() var v = typeof(Int32); } } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); [Fact] - public async Task NameOfExpression() - { - var code = - """ + public Task NameOfExpression() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -689,10 +543,7 @@ void Method() var v = nameof([|int|]); } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -701,15 +552,11 @@ void Method() var v = nameof(Int32); } } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); [Fact] - public async Task FormalParametersWithinLambdaExression() - { - var code = - """ + public Task FormalParametersWithinLambdaExression() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -718,10 +565,7 @@ void Method() Func func3 = ([|int|] z) => z + 1; } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -730,15 +574,11 @@ void Method() Func func3 = (Int32 z) => z + 1; } } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); [Fact] - public async Task DelegateMethodExpression() - { - var code = - """ + public Task DelegateMethodExpression() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -747,10 +587,7 @@ void Method() Func func7 = delegate ([|int|] dx) { return dx + 1; }; } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -759,15 +596,11 @@ void Method() Func func7 = delegate (Int32 dx) { return dx + 1; }; } } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); [Fact] - public async Task ObjectCreationExpression() - { - var code = - """ + public Task ObjectCreationExpression() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -776,10 +609,7 @@ void Method() string s2 = new [|string|]('c', 1); } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -788,15 +618,11 @@ void Method() string s2 = new String('c', 1); } } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); [Fact] - public async Task ArrayDeclaration() - { - var code = - """ + public Task ArrayDeclaration() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -805,10 +631,7 @@ void Method() [|int|][] k = new int[4]; } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -817,15 +640,11 @@ void Method() Int32[] k = new int[4]; } } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); [Fact] - public async Task ArrayInitializer() - { - var code = - """ + public Task ArrayInitializer() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -834,10 +653,7 @@ void Method() int[] k = new [|int|][] { 1, 2, 3 }; } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -846,15 +662,11 @@ void Method() int[] k = new Int32[] { 1, 2, 3 }; } } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); [Fact] - public async Task MultiDimentionalArrayAsGenericTypeParameter() - { - var code = - """ + public Task MultiDimentionalArrayAsGenericTypeParameter() + => TestInRegularAndScriptAsync(""" using System; using System.Collections.Generic; class Program @@ -864,10 +676,7 @@ void Method() List<[|string|][][,][,,,]> a; } } - """; - - var expected = - """ + """, """ using System; using System.Collections.Generic; class Program @@ -877,15 +686,11 @@ void Method() List a; } } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); [Fact] - public async Task ForStatement() - { - var code = - """ + public Task ForStatement() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -894,10 +699,7 @@ void Method() for ([|int|] j = 0; j < 4; j++) { } } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -906,15 +708,11 @@ void Method() for (Int32 j = 0; j < 4; j++) { } } } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); [Fact] - public async Task ForeachStatement() - { - var code = - """ + public Task ForeachStatement() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -923,10 +721,7 @@ void Method() foreach ([|int|] item in new int[] { 1, 2, 3 }) { } } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -935,15 +730,11 @@ void Method() foreach (Int32 item in new int[] { 1, 2, 3 }) { } } } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); [Fact] - public async Task LeadingTrivia() - { - var code = - """ + public Task LeadingTrivia() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -953,10 +744,7 @@ void Method() [|int|] x = 5; } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -966,15 +754,11 @@ void Method() Int32 x = 5; } } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); [Fact] - public async Task TrailingTrivia() - { - var code = - """ + public Task TrailingTrivia() + => TestInRegularAndScriptAsync(""" using System; class Program { @@ -983,10 +767,7 @@ void Method() [|int|] /* 2 */ x = 5; } } - """; - - var expected = - """ + """, """ using System; class Program { @@ -995,7 +776,5 @@ void Method() Int32 /* 2 */ x = 5; } } - """; - await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); - } + """, options: FrameworkTypeInDeclaration); } diff --git a/src/Features/CSharpTest/PreferFrameworkType/PreferFrameworkTypeTests_FixAllTests.cs b/src/Features/CSharpTest/PreferFrameworkType/PreferFrameworkTypeTests_FixAllTests.cs index 8cf1dc4036f26..baf85d0134d3f 100644 --- a/src/Features/CSharpTest/PreferFrameworkType/PreferFrameworkTypeTests_FixAllTests.cs +++ b/src/Features/CSharpTest/PreferFrameworkType/PreferFrameworkTypeTests_FixAllTests.cs @@ -15,467 +15,452 @@ public partial class PreferFrameworkTypeTests : AbstractCSharpDiagnosticProvider [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInDocument_DeclarationContext() - { - var input = @" - - - -using System; - -class Program -{ - static int F(int x, System.Int16 y) - { - {|FixAllInDocument:int|} i1 = 0; - System.Int16 s1 = 0; - int i2 = 0; - return i1 + s1 + i2; - } -} - - -using System; - -class Program2 -{ - static System.Int32 F(System.Int32 x, System.Int16 y) - { - System.Int32 i1 = 0; - System.Int16 s1 = 0; - System.Int32 i2 = 0; - return i1 + s1 + i2; - } -} - - - - -using System; - -class Program2 -{ - static System.Int32 F(System.Int32 x, System.Int16 y) - { - System.Int32 i1 = 0; - System.Int16 s1 = 0; - System.Int32 i2 = 0; - return i1 + s1 + i2; - } -} - - -"; - - var expected = @" - - - -using System; - -class Program -{ - static Int32 F(Int32 x, System.Int16 y) - { - Int32 i1 = 0; - System.Int16 s1 = 0; - Int32 i2 = 0; - return i1 + s1 + i2; - } -} - - -using System; - -class Program2 -{ - static System.Int32 F(System.Int32 x, System.Int16 y) - { - System.Int32 i1 = 0; - System.Int16 s1 = 0; - System.Int32 i2 = 0; - return i1 + s1 + i2; - } -} - - - - -using System; - -class Program2 -{ - static System.Int32 F(System.Int32 x, System.Int16 y) - { - System.Int32 i1 = 0; - System.Int16 s1 = 0; - System.Int32 i2 = 0; - return i1 + s1 + i2; - } -} - - -"; - - await TestInRegularAndScriptAsync(input, expected, options: FrameworkTypeEverywhere); - } + public Task TestFixAllInDocument_DeclarationContext() + => TestInRegularAndScriptAsync(""" + + + + using System; + + class Program + { + static int F(int x, System.Int16 y) + { + {|FixAllInDocument:int|} i1 = 0; + System.Int16 s1 = 0; + int i2 = 0; + return i1 + s1 + i2; + } + } + + + using System; + + class Program2 + { + static System.Int32 F(System.Int32 x, System.Int16 y) + { + System.Int32 i1 = 0; + System.Int16 s1 = 0; + System.Int32 i2 = 0; + return i1 + s1 + i2; + } + } + + + + + using System; + + class Program2 + { + static System.Int32 F(System.Int32 x, System.Int16 y) + { + System.Int32 i1 = 0; + System.Int16 s1 = 0; + System.Int32 i2 = 0; + return i1 + s1 + i2; + } + } + + + + """, """ + + + + using System; + + class Program + { + static Int32 F(Int32 x, System.Int16 y) + { + Int32 i1 = 0; + System.Int16 s1 = 0; + Int32 i2 = 0; + return i1 + s1 + i2; + } + } + + + using System; + + class Program2 + { + static System.Int32 F(System.Int32 x, System.Int16 y) + { + System.Int32 i1 = 0; + System.Int16 s1 = 0; + System.Int32 i2 = 0; + return i1 + s1 + i2; + } + } + + + + + using System; + + class Program2 + { + static System.Int32 F(System.Int32 x, System.Int16 y) + { + System.Int32 i1 = 0; + System.Int16 s1 = 0; + System.Int32 i2 = 0; + return i1 + s1 + i2; + } + } + + + + """, options: FrameworkTypeEverywhere); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInProject_DeclarationContext() - { - var input = @" - - - -using System; - -class Program -{ - static int F(int x, System.Int16 y) - { - {|FixAllInProject:int|} i1 = 0; - System.Int16 s1 = 0; - int i2 = 0; - return i1 + s1 + i2; - } -} - - -using System; - -class Program2 -{ - static int F(int x, System.Int16 y) - { - int i1 = 0; - System.Int16 s1 = 0; - int i2 = 0; - return i1 + s1 + i2; - } -} - - - - -using System; - -class Program2 -{ - static System.Int32 F(System.Int32 x, System.Int16 y) - { - System.Int32 i1 = 0; - System.Int16 s1 = 0; - System.Int32 i2 = 0; - return i1 + s1 + i2; - } -} - - -"; - - var expected = @" - - - -using System; - -class Program -{ - static Int32 F(Int32 x, System.Int16 y) - { - Int32 i1 = 0; - System.Int16 s1 = 0; - Int32 i2 = 0; - return i1 + s1 + i2; - } -} - - -using System; - -class Program2 -{ - static Int32 F(Int32 x, System.Int16 y) - { - Int32 i1 = 0; - System.Int16 s1 = 0; - Int32 i2 = 0; - return i1 + s1 + i2; - } -} - - - - -using System; - -class Program2 -{ - static System.Int32 F(System.Int32 x, System.Int16 y) - { - System.Int32 i1 = 0; - System.Int16 s1 = 0; - System.Int32 i2 = 0; - return i1 + s1 + i2; - } -} - - -"; - - await TestInRegularAndScriptAsync(input, expected, options: FrameworkTypeEverywhere); - } + public Task TestFixAllInProject_DeclarationContext() + => TestInRegularAndScriptAsync(""" + + + + using System; + + class Program + { + static int F(int x, System.Int16 y) + { + {|FixAllInProject:int|} i1 = 0; + System.Int16 s1 = 0; + int i2 = 0; + return i1 + s1 + i2; + } + } + + + using System; + + class Program2 + { + static int F(int x, System.Int16 y) + { + int i1 = 0; + System.Int16 s1 = 0; + int i2 = 0; + return i1 + s1 + i2; + } + } + + + + + using System; + + class Program2 + { + static System.Int32 F(System.Int32 x, System.Int16 y) + { + System.Int32 i1 = 0; + System.Int16 s1 = 0; + System.Int32 i2 = 0; + return i1 + s1 + i2; + } + } + + + + """, """ + + + + using System; + + class Program + { + static Int32 F(Int32 x, System.Int16 y) + { + Int32 i1 = 0; + System.Int16 s1 = 0; + Int32 i2 = 0; + return i1 + s1 + i2; + } + } + + + using System; + + class Program2 + { + static Int32 F(Int32 x, System.Int16 y) + { + Int32 i1 = 0; + System.Int16 s1 = 0; + Int32 i2 = 0; + return i1 + s1 + i2; + } + } + + + + + using System; + + class Program2 + { + static System.Int32 F(System.Int32 x, System.Int16 y) + { + System.Int32 i1 = 0; + System.Int16 s1 = 0; + System.Int32 i2 = 0; + return i1 + s1 + i2; + } + } + + + + """, options: FrameworkTypeEverywhere); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInSolution_DeclarationContext() - { - var input = @" - - - -using System; - -class Program -{ - static int F(int x, System.Int16 y) - { - {|FixAllInSolution:int|} i1 = 0; - System.Int16 s1 = 0; - int i2 = 0; - return i1 + s1 + i2; - } -} - - -using System; - -class Program2 -{ - static int F(int x, System.Int16 y) - { - int i1 = 0; - System.Int16 s1 = 0; - int i2 = 0; - return i1 + s1 + i2; - } -} - - - - -using System; - -class Program2 -{ - static int F(int x, System.Int16 y) - { - int i1 = 0; - System.Int16 s1 = 0; - int i2 = 0; - return i1 + s1 + i2; - } -} - - -"; - - var expected = @" - - - -using System; - -class Program -{ - static Int32 F(Int32 x, System.Int16 y) - { - Int32 i1 = 0; - System.Int16 s1 = 0; - Int32 i2 = 0; - return i1 + s1 + i2; - } -} - - -using System; - -class Program2 -{ - static Int32 F(Int32 x, System.Int16 y) - { - Int32 i1 = 0; - System.Int16 s1 = 0; - Int32 i2 = 0; - return i1 + s1 + i2; - } -} - - - - -using System; - -class Program2 -{ - static Int32 F(Int32 x, System.Int16 y) - { - Int32 i1 = 0; - System.Int16 s1 = 0; - Int32 i2 = 0; - return i1 + s1 + i2; - } -} - - -"; - - await TestInRegularAndScriptAsync(input, expected, options: FrameworkTypeEverywhere); - } + public Task TestFixAllInSolution_DeclarationContext() + => TestInRegularAndScriptAsync(""" + + + + using System; + + class Program + { + static int F(int x, System.Int16 y) + { + {|FixAllInSolution:int|} i1 = 0; + System.Int16 s1 = 0; + int i2 = 0; + return i1 + s1 + i2; + } + } + + + using System; + + class Program2 + { + static int F(int x, System.Int16 y) + { + int i1 = 0; + System.Int16 s1 = 0; + int i2 = 0; + return i1 + s1 + i2; + } + } + + + + + using System; + + class Program2 + { + static int F(int x, System.Int16 y) + { + int i1 = 0; + System.Int16 s1 = 0; + int i2 = 0; + return i1 + s1 + i2; + } + } + + + + """, """ + + + + using System; + + class Program + { + static Int32 F(Int32 x, System.Int16 y) + { + Int32 i1 = 0; + System.Int16 s1 = 0; + Int32 i2 = 0; + return i1 + s1 + i2; + } + } + + + using System; + + class Program2 + { + static Int32 F(Int32 x, System.Int16 y) + { + Int32 i1 = 0; + System.Int16 s1 = 0; + Int32 i2 = 0; + return i1 + s1 + i2; + } + } + + + + + using System; + + class Program2 + { + static Int32 F(Int32 x, System.Int16 y) + { + Int32 i1 = 0; + System.Int16 s1 = 0; + Int32 i2 = 0; + return i1 + s1 + i2; + } + } + + + + """, options: FrameworkTypeEverywhere); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInSolution_MemberAccessContext() - { - var input = @" - - - -using System; -class ProgramA -{ - private int x = 0; - private int y = 0; - private int z = 0; - - private System.Int32 F(System.Int32 p1, System.Int16 p2) - { - System.Int32 i1 = this.x; - System.Int16 s1 = this.y; - System.Int32 i2 = this.z; - {|FixAllInSolution:int|}.Parse(i1 + s1 + i2); - int.Parse(i1 + s1 + i2); - System.Exception ex = null; - return i1 + s1 + i2; - } -} - - -using System; -class ProgramA2 -{ - private int x = 0; - private int y = 0; - private int z = 0; - - private System.Int32 F(System.Int32 p1, System.Int16 p2) - { - System.Int32 i1 = this.x; - System.Int16 s1 = this.y; - System.Int32 i2 = this.z; - int.Parse(i1 + s1 + i2); - int.Parse(i1 + s1 + i2); - System.Exception ex = null; - return i1 + s1 + i2; - } -} - - - - -using System; -class ProgramA3 -{ - private int x = 0; - private int y = 0; - private int z = 0; - - private System.Int32 F(System.Int32 p1, System.Int16 p2) - { - System.Int32 i1 = this.x; - System.Int16 s1 = this.y; - System.Int32 i2 = this.z; - int.Parse(i1 + s1 + i2); - int.Parse(i1 + s1 + i2); - System.Exception ex = null; - return i1 + s1 + i2; - } -} - - -"; - - var expected = @" - - - -using System; -class ProgramA -{ - private Int32 x = 0; - private Int32 y = 0; - private Int32 z = 0; - - private System.Int32 F(System.Int32 p1, System.Int16 p2) - { - System.Int32 i1 = this.x; - System.Int16 s1 = this.y; - System.Int32 i2 = this.z; - Int32.Parse(i1 + s1 + i2); - Int32.Parse(i1 + s1 + i2); - System.Exception ex = null; - return i1 + s1 + i2; - } -} - - -using System; -class ProgramA2 -{ - private Int32 x = 0; - private Int32 y = 0; - private Int32 z = 0; - - private System.Int32 F(System.Int32 p1, System.Int16 p2) - { - System.Int32 i1 = this.x; - System.Int16 s1 = this.y; - System.Int32 i2 = this.z; - Int32.Parse(i1 + s1 + i2); - Int32.Parse(i1 + s1 + i2); - System.Exception ex = null; - return i1 + s1 + i2; - } -} - - - - -using System; -class ProgramA3 -{ - private Int32 x = 0; - private Int32 y = 0; - private Int32 z = 0; - - private System.Int32 F(System.Int32 p1, System.Int16 p2) - { - System.Int32 i1 = this.x; - System.Int16 s1 = this.y; - System.Int32 i2 = this.z; - Int32.Parse(i1 + s1 + i2); - Int32.Parse(i1 + s1 + i2); - System.Exception ex = null; - return i1 + s1 + i2; - } -} - - -"; - await TestInRegularAndScriptAsync(input, expected, options: FrameworkTypeEverywhere); - } + public Task TestFixAllInSolution_MemberAccessContext() + => TestInRegularAndScriptAsync(""" + + + + using System; + class ProgramA + { + private int x = 0; + private int y = 0; + private int z = 0; + + private System.Int32 F(System.Int32 p1, System.Int16 p2) + { + System.Int32 i1 = this.x; + System.Int16 s1 = this.y; + System.Int32 i2 = this.z; + {|FixAllInSolution:int|}.Parse(i1 + s1 + i2); + int.Parse(i1 + s1 + i2); + System.Exception ex = null; + return i1 + s1 + i2; + } + } + + + using System; + class ProgramA2 + { + private int x = 0; + private int y = 0; + private int z = 0; + + private System.Int32 F(System.Int32 p1, System.Int16 p2) + { + System.Int32 i1 = this.x; + System.Int16 s1 = this.y; + System.Int32 i2 = this.z; + int.Parse(i1 + s1 + i2); + int.Parse(i1 + s1 + i2); + System.Exception ex = null; + return i1 + s1 + i2; + } + } + + + + + using System; + class ProgramA3 + { + private int x = 0; + private int y = 0; + private int z = 0; + + private System.Int32 F(System.Int32 p1, System.Int16 p2) + { + System.Int32 i1 = this.x; + System.Int16 s1 = this.y; + System.Int32 i2 = this.z; + int.Parse(i1 + s1 + i2); + int.Parse(i1 + s1 + i2); + System.Exception ex = null; + return i1 + s1 + i2; + } + } + + + + """, """ + + + + using System; + class ProgramA + { + private Int32 x = 0; + private Int32 y = 0; + private Int32 z = 0; + + private System.Int32 F(System.Int32 p1, System.Int16 p2) + { + System.Int32 i1 = this.x; + System.Int16 s1 = this.y; + System.Int32 i2 = this.z; + Int32.Parse(i1 + s1 + i2); + Int32.Parse(i1 + s1 + i2); + System.Exception ex = null; + return i1 + s1 + i2; + } + } + + + using System; + class ProgramA2 + { + private Int32 x = 0; + private Int32 y = 0; + private Int32 z = 0; + + private System.Int32 F(System.Int32 p1, System.Int16 p2) + { + System.Int32 i1 = this.x; + System.Int16 s1 = this.y; + System.Int32 i2 = this.z; + Int32.Parse(i1 + s1 + i2); + Int32.Parse(i1 + s1 + i2); + System.Exception ex = null; + return i1 + s1 + i2; + } + } + + + + + using System; + class ProgramA3 + { + private Int32 x = 0; + private Int32 y = 0; + private Int32 z = 0; + + private System.Int32 F(System.Int32 p1, System.Int16 p2) + { + System.Int32 i1 = this.x; + System.Int16 s1 = this.y; + System.Int32 i2 = this.z; + Int32.Parse(i1 + s1 + i2); + Int32.Parse(i1 + s1 + i2); + System.Exception ex = null; + return i1 + s1 + i2; + } + } + + + + """, options: FrameworkTypeEverywhere); } diff --git a/src/Features/CSharpTest/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests_AsTests.cs b/src/Features/CSharpTest/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests_AsTests.cs index 736ebcf12b3ce..76e5cc0477cd4 100644 --- a/src/Features/CSharpTest/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests_AsTests.cs +++ b/src/Features/CSharpTest/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests_AsTests.cs @@ -29,9 +29,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider => (new CSharpRemoveUnnecessaryCastDiagnosticAnalyzer(), new CSharpRemoveUnnecessaryCastCodeFixProvider()); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545979")] - public async Task DoNotRemoveCastToErrorType() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastToErrorType() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -44,12 +43,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545146")] - public async Task ParenthesizeToKeepParseTheSame2() - { - await TestInRegularAndScriptAsync( + public Task ParenthesizeToKeepParseTheSame2() + => TestInRegularAndScriptAsync( """ using System; @@ -75,12 +72,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545138")] - public async Task DoNotRemoveTypeParameterCastToObject() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveTypeParameterCastToObject() + => TestMissingInRegularAndScriptAsync( """ class С { @@ -90,12 +85,10 @@ void Goo(T obj) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545139")] - public async Task DoNotRemoveCastInIsTest() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastInIsTest() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -109,12 +102,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545142")] - public async Task DoNotRemoveCastNeedForUserDefinedOperator() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastNeedForUserDefinedOperator() + => TestMissingInRegularAndScriptAsync( """ class A { @@ -132,12 +123,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545143")] - public async Task DoNotRemovePointerCast1() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemovePointerCast1() + => TestMissingInRegularAndScriptAsync( """ unsafe class C { @@ -147,15 +136,10 @@ static unsafe void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545144")] - public async Task DoNotRemoveCastToObjectFromDelegateComparison() - { - // The cast below can't be removed because it would result in the Delegate - // op_Equality operator overload being used over reference equality. - - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastToObjectFromDelegateComparison() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -169,12 +153,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545145")] - public async Task DoNotRemoveCastToAnonymousMethodWhenOnLeftOfAsCast() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastToAnonymousMethodWhenOnLeftOfAsCast() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -189,12 +171,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545157")] - public async Task DoNotRemoveIdentityCastWhichAffectsOverloadResolution1() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveIdentityCastWhichAffectsOverloadResolution1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -214,12 +194,10 @@ static void Goo(Func x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545158")] - public async Task DoNotRemoveIdentityCastWhichAffectsOverloadResolution2() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveIdentityCastWhichAffectsOverloadResolution2() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -240,12 +218,10 @@ static void Goo(int x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545158")] - public async Task DoNotRemoveIdentityCastWhichAffectsOverloadResolution3() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveIdentityCastWhichAffectsOverloadResolution3() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -267,12 +243,10 @@ static void Goo(int x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545747")] - public async Task DoNotRemoveCastWhichChangesTypeOfInferredLocal() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastWhichChangesTypeOfInferredLocal() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -282,12 +256,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545159")] - public async Task DoNotRemoveNeededCastToIListOfObject() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveNeededCastToIListOfObject() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -308,12 +280,10 @@ static void Goo(Action[] x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545287"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/880752")] - public async Task RemoveUnneededCastInParameterDefaultValue() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnneededCastInParameterDefaultValue() + => TestInRegularAndScriptAsync( """ class Program { @@ -331,12 +301,10 @@ static void M1(string i1 = null) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545289")] - public async Task RemoveUnneededCastInReturnStatement() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnneededCastInReturnStatement() + => TestInRegularAndScriptAsync( """ class Program { @@ -356,12 +324,10 @@ static string M2() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545288")] - public async Task RemoveUnneededCastInLambda1() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnneededCastInLambda1() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -383,12 +349,10 @@ static void M1() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545288")] - public async Task RemoveUnneededCastInLambda2() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnneededCastInLambda2() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -410,12 +374,10 @@ static void M1() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545288")] - public async Task RemoveUnneededCastInLambda3() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnneededCastInLambda3() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -437,12 +399,10 @@ static void M1() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545288")] - public async Task RemoveUnneededCastInLambda4() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnneededCastInLambda4() + => TestInRegularAndScriptAsync( """ using System; class Program @@ -464,12 +424,10 @@ static void M1() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545291")] - public async Task RemoveUnneededCastInConditionalExpression1() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnneededCastInConditionalExpression1() + => TestInRegularAndScriptAsync( """ class Test { @@ -493,12 +451,10 @@ public static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545291")] - public async Task RemoveUnneededCastInConditionalExpression2() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnneededCastInConditionalExpression2() + => TestInRegularAndScriptAsync( """ class Test { @@ -522,12 +478,10 @@ public static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545291")] - public async Task DoNotRemoveNeededCastInConditionalExpression() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveNeededCastInConditionalExpression() + => TestMissingInRegularAndScriptAsync( """ class Test { @@ -538,12 +492,10 @@ public static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545459")] - public async Task DoNotRemoveIllegalAsCastInsideADelegateConstructor() - { - await TestMissingAsync( + public Task DoNotRemoveIllegalAsCastInsideADelegateConstructor() + => TestMissingAsync( """ using System; class Test @@ -558,12 +510,10 @@ static void Main(string[] args) public static void M1(int i) { } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545422")] - public async Task RemoveUnneededCastInsideCaseLabel() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnneededCastInsideCaseLabel() + => TestInRegularAndScriptAsync( """ class Test { @@ -591,13 +541,11 @@ static void Main() } } """); - } [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545595")] [Fact(Skip = "529787")] - public async Task RemoveUnneededCastInCollectionInitializer() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnneededCastInCollectionInitializer() + => TestInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -621,13 +569,11 @@ static void Main() } } """); - } [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529787")] [Fact(Skip = "529787")] - public async Task DoNotRemoveNecessaryCastWhichInCollectionInitializer1() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveNecessaryCastWhichInCollectionInitializer1() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -650,13 +596,11 @@ static void Main() } } """); - } [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529787")] [Fact(Skip = "529787")] - public async Task DoNotRemoveNecessaryCastWhichInCollectionInitializer2() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveNecessaryCastWhichInCollectionInitializer2() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -679,12 +623,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545607")] - public async Task RemoveUnneededCastInArrayInitializer() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnneededCastInArrayInitializer() + => TestInRegularAndScriptAsync( """ class X { @@ -706,12 +648,10 @@ static void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545608")] - public async Task DoNotRemoveNecessaryCastWithImplicitUserDefinedConversion() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveNecessaryCastWithImplicitUserDefinedConversion() + => TestMissingInRegularAndScriptAsync( """ class X { @@ -727,16 +667,10 @@ public static implicit operator string(X x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545941")] - public async Task DoNotRemoveNecessaryCastWithImplicitConversionInThrow() - { - // The cast below can't be removed because the throw statement expects - // an expression of type Exception -- not an expression convertible to - // Exception. - - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveNecessaryCastWithImplicitConversionInThrow() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -753,16 +687,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545981")] - public async Task DoNotRemoveNecessaryCastInThrow() - { - // The cast below can't be removed because the throw statement expects - // an expression of type Exception -- not an expression convertible to - // Exception. - - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveNecessaryCastInThrow() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -775,12 +703,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545941")] - public async Task RemoveUnnecessaryCastInThrow() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnnecessaryCastInThrow() + => TestInRegularAndScriptAsync( """ using System; @@ -804,12 +730,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545945")] - public async Task DoNotRemoveNecessaryDowncast() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveNecessaryDowncast() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -819,12 +743,10 @@ void Goo(object y) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545606")] - public async Task DoNotRemoveNecessaryCastFromNullToTypeParameter() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveNecessaryCastFromNullToTypeParameter() + => TestMissingInRegularAndScriptAsync( """ class X { @@ -834,12 +756,10 @@ static void Goo() where T : class, S } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545744")] - public async Task DoNotRemoveNecessaryCastInImplicitlyTypedArray() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveNecessaryCastInImplicitlyTypedArray() + => TestMissingInRegularAndScriptAsync( """ class X { @@ -851,12 +771,10 @@ static void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545750")] - public async Task RemoveUnnecessaryCastToBaseType() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnnecessaryCastToBaseType() + => TestInRegularAndScriptAsync( """ class X { @@ -886,12 +804,10 @@ public override string ToString() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545855")] - public async Task DoRemoveIllegalAsCastOnLambda() - { - await TestMissingInRegularAndScriptAsync( + public Task DoRemoveIllegalAsCastOnLambda() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -916,12 +832,10 @@ static bool Any(this ICollection s, Func predicate) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529816")] - public async Task RemoveUnnecessaryCastInQueryExpression() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnnecessaryCastInQueryExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -949,12 +863,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529816")] - public async Task DoNotRemoveNecessaryCastInQueryExpression() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveNecessaryCastInQueryExpression() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -977,12 +889,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529831")] - public async Task DoNotRemoveNecessaryCastFromTypeParameterToInterface() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveNecessaryCastFromTypeParameterToInterface() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1032,12 +942,10 @@ static void Goo(TAny x, TClass y) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529831")] - public async Task RemoveUnnecessaryCastFromTypeParameterToInterface() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnnecessaryCastFromTypeParameterToInterface() + => TestInRegularAndScriptAsync( """ using System; @@ -1118,12 +1026,10 @@ static void Goo(TAny x, TClass y) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545877")] - public async Task DoNotCrashOnIncompleteMethodDeclaration() - { - await TestInRegularAndScriptAsync( + public Task DoNotCrashOnIncompleteMethodDeclaration() + => TestInRegularAndScriptAsync( """ using System; @@ -1156,12 +1062,10 @@ static void Goo(T x, ) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529791")] - public async Task RemoveUnnecessaryCastToNullable1() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnnecessaryCastToNullable1() + => TestInRegularAndScriptAsync( """ class X { @@ -1183,12 +1087,10 @@ static void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545850")] - public async Task RemoveSurroundingParentheses() - { - await TestInRegularAndScriptAsync( + public Task RemoveSurroundingParentheses() + => TestInRegularAndScriptAsync( """ class Program { @@ -1210,12 +1112,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529846")] - public async Task DoNotRemoveNecessaryCastFromTypeParameterToObject() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveNecessaryCastFromTypeParameterToObject() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1227,12 +1127,10 @@ static void Goo(T x, object y) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545858")] - public async Task DoNotRemoveNecessaryCastFromDelegateTypeToMulticastDelegate() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveNecessaryCastFromDelegateTypeToMulticastDelegate() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1246,12 +1144,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529842")] - public async Task DoNotRemoveNecessaryCastInTernaryExpression() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveNecessaryCastInTernaryExpression() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1270,12 +1166,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545882"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/880752")] - public async Task RemoveCastInConstructorInitializer1() - { - await TestInRegularAndScriptAsync( + public Task RemoveCastInConstructorInitializer1() + => TestInRegularAndScriptAsync( """ class C { @@ -1291,12 +1185,10 @@ class C C() : this("") { } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545958"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/880752")] - public async Task RemoveCastInConstructorInitializer2() - { - await TestInRegularAndScriptAsync( + public Task RemoveCastInConstructorInitializer2() + => TestInRegularAndScriptAsync( """ using System.Collections; @@ -1318,12 +1210,10 @@ class C C() : this("") { } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545957")] - public async Task DoNotRemoveCastInConstructorInitializer3() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastInConstructorInitializer3() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1336,12 +1226,10 @@ class C } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545842")] - public async Task RemoveCastToNullableInArithmeticExpression() - { - await TestInRegularAndScriptAsync( + public Task RemoveCastToNullableInArithmeticExpression() + => TestInRegularAndScriptAsync( """ static class C { @@ -1365,12 +1253,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545942")] - public async Task DoNotRemoveCastFromStringTypeToObjectInReferenceEquality() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastFromStringTypeToObjectInReferenceEquality() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1383,14 +1269,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545962")] - public async Task DoNotRemoveCastWhenExpressionDoesntBind() - { - // Note: The cast below can't be removed because its expression doesn't bind. - - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastWhenExpressionDoesntBind() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1402,30 +1284,20 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545944")] - public async Task DoNotRemoveNecessaryCastBeforePointerDereference1() - { - // Note: The cast below can't be removed because it would result in *null, - // which is illegal. - - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveNecessaryCastBeforePointerDereference1() + => TestMissingInRegularAndScriptAsync( """ unsafe class C { int x = *([|null as int*|]); } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545978")] - public async Task DoNotRemoveNecessaryCastBeforePointerDereference2() - { - // Note: The cast below can't be removed because it would result in dereferencing - // void*, which is illegal. - - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveNecessaryCastBeforePointerDereference2() + => TestMissingInRegularAndScriptAsync( """ unsafe class C { @@ -1436,12 +1308,10 @@ static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26640")] - public async Task DoNotRemoveCastToByteFromIntInConditionalExpression_CSharp8() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastToByteFromIntInConditionalExpression_CSharp8() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1451,12 +1321,10 @@ object M1(bool b) } } """, new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26640")] - public async Task DoNotRemoveCastToByteFromIntInConditionalExpression_CSharp9() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastToByteFromIntInConditionalExpression_CSharp9() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1466,16 +1334,12 @@ object M1(bool b) } } """, new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9))); - } #region Interface Casts [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545889")] - public async Task DoNotRemoveCastToInterfaceForUnsealedType() - { - // Note: The cast below can't be removed because X is not sealed. - - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastToInterfaceForUnsealedType() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1501,12 +1365,10 @@ void IDisposable.Dispose() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545890")] - public async Task DoRemoveCastToInterfaceForSealedType1() - { - await TestInRegularAndScriptAsync( + public Task DoRemoveCastToInterfaceForSealedType1() + => TestInRegularAndScriptAsync( """ using System; @@ -1549,12 +1411,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545890")] - public async Task DoRemoveCastToInterfaceForSealedType2() - { - await TestInRegularAndScriptAsync( + public Task DoRemoveCastToInterfaceForSealedType2() + => TestInRegularAndScriptAsync( """ using System; @@ -1603,12 +1463,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545890")] - public async Task DoNotRemoveCastToInterfaceForSealedType3() - { - await TestMissingAsync( + public Task DoNotRemoveCastToInterfaceForSealedType3() + => TestMissingAsync( """ using System; @@ -1635,15 +1493,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545890")] - public async Task DoNotRemoveCastToInterfaceForSealedType4() - { - // Note: The cast below can't be removed (even though C is sealed) - // because the unspecified optional parameter default values differ. - - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastToInterfaceForSealedType4() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1665,12 +1518,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545890")] - public async Task DoRemoveCastToInterfaceForSealedTypeWhenDefaultValuesAreDifferentButParameterIsPassed() - { - await TestInRegularAndScriptAsync( + public Task DoRemoveCastToInterfaceForSealedTypeWhenDefaultValuesAreDifferentButParameterIsPassed() + => TestInRegularAndScriptAsync( """ using System; @@ -1713,16 +1564,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545888")] - public async Task DoNotRemoveCastToInterfaceForSealedType6() - { - // Note: The cast below can't be removed (even though C is sealed) - // because the specified named arguments refer to parameters that - // appear at different positions in the member signatures. - - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastToInterfaceForSealedType6() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1744,12 +1589,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545888")] - public async Task DoNotRemoveCastToInterfaceForSealedType7() - { - await TestMissingAsync( + public Task DoNotRemoveCastToInterfaceForSealedType7() + => TestMissingAsync( """ using System; @@ -1774,16 +1617,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545888")] - public async Task DoNotRemoveCastToInterfaceForSealedType8() - { - // Note: The cast below can't be removed (even though C is sealed) - // because the specified named arguments refer to parameters that - // appear at different positions in the member signatures. - - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastToInterfaceForSealedType8() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1808,16 +1645,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545883")] - public async Task DoNotRemoveCastToInterfaceForSealedType9() - { - // Note: The cast below can't be removed (even though C is sealed) - // because it would result in binding to a Dispose method that doesn't - // implement IDisposable.Dispose(). - - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastToInterfaceForSealedType9() + => TestMissingInRegularAndScriptAsync( """ using System; using System.IO; @@ -1836,15 +1667,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545887")] - public async Task DoNotRemoveCastToInterfaceForStruct1() - { - // Note: The cast below can't be removed because the cast boxes 's' and - // unboxing would change program behavior. - - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastToInterfaceForStruct1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1872,15 +1698,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545834")] - public async Task RemoveCastToInterfaceForStruct2() - { - // Note: The cast below can be removed because we are sure to have - // a fresh copy of the struct from the GetEnumerator() method. - - await TestInRegularAndScriptAsync( + public Task RemoveCastToInterfaceForStruct2() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -1918,15 +1739,10 @@ static List.Enumerator GetEnumerator() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544655")] - public async Task RemoveCastToICloneableForDelegate() - { - // Note: The cast below can be removed because delegates are implicitly - // sealed. - - await TestInRegularAndScriptAsync( + public Task RemoveCastToICloneableForDelegate() + => TestInRegularAndScriptAsync( """ using System; @@ -1952,15 +1768,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545926")] - public async Task RemoveCastToICloneableForArray() - { - // Note: The cast below can be removed because arrays are implicitly - // sealed. - - await TestInRegularAndScriptAsync( + public Task RemoveCastToICloneableForArray() + => TestInRegularAndScriptAsync( """ using System; @@ -1986,15 +1797,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529897")] - public async Task RemoveCastToIConvertibleForEnum() - { - // Note: The cast below can be removed because enums are implicitly - // sealed. - - await TestInRegularAndScriptAsync( + public Task RemoveCastToIConvertibleForEnum() + => TestInRegularAndScriptAsync( """ using System; @@ -2020,16 +1826,14 @@ static void Main() } } """); - } #endregion #region ParamArray Parameter Casts [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545141")] - public async Task DoNotRemoveCastToObjectInParamArrayArg1() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastToObjectInParamArrayArg1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2046,12 +1850,10 @@ static void Goo(params object[] x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529911")] - public async Task DoNotRemoveCastToIntArrayInParamArrayArg2() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastToIntArrayInParamArrayArg2() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2068,12 +1870,10 @@ static void Goo(params object[] x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529911")] - public async Task DoNotRemoveCastToObjectArrayInParamArrayArg3() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastToObjectArrayInParamArrayArg3() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2090,12 +1890,10 @@ static void Goo(params object[][] x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529911")] - public async Task RemoveCastToObjectArrayInParamArrayArg1() - { - await TestInRegularAndScriptAsync( + public Task RemoveCastToObjectArrayInParamArrayArg1() + => TestInRegularAndScriptAsync( """ class C { @@ -2119,12 +1917,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529911")] - public async Task RemoveCastToStringArrayInParamArrayArg2() - { - await TestInRegularAndScriptAsync( + public Task RemoveCastToStringArrayInParamArrayArg2() + => TestInRegularAndScriptAsync( """ class C { @@ -2148,12 +1944,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529911")] - public async Task RemoveCastToIntArrayInParamArrayArg3() - { - await TestInRegularAndScriptAsync( + public Task RemoveCastToIntArrayInParamArrayArg3() + => TestInRegularAndScriptAsync( """ class C { @@ -2177,12 +1971,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529911")] - public async Task RemoveCastToObjectArrayInParamArrayArg4() - { - await TestInRegularAndScriptAsync( + public Task RemoveCastToObjectArrayInParamArrayArg4() + => TestInRegularAndScriptAsync( """ class C { @@ -2206,12 +1998,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529911")] - public async Task RemoveCastToObjectInParamArrayArg5() - { - await TestInRegularAndScriptAsync( + public Task RemoveCastToObjectInParamArrayArg5() + => TestInRegularAndScriptAsync( """ class C { @@ -2235,12 +2025,10 @@ static void Main() } } """); - } [Fact] - public async Task RemoveCastToObjectArrayInParamArrayWithNamedArgument() - { - await TestInRegularAndScriptAsync( + public Task RemoveCastToObjectArrayInParamArrayWithNamedArgument() + => TestInRegularAndScriptAsync( """ class C { @@ -2263,19 +2051,14 @@ static void Main() static void Goo(params object[] x) { } } """); - } #endregion #region ForEach Statements [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545961")] - public async Task DoNotRemoveNecessaryCastInForEach1() - { - // The cast below can't be removed because it would result an error - // in the foreach statement. - - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveNecessaryCastInForEach1() + => TestMissingInRegularAndScriptAsync( """ using System.Collections; @@ -2290,15 +2073,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545961")] - public async Task DoNotRemoveNecessaryCastInForEach2() - { - // The cast below can't be removed because it would result an error - // in the foreach statement. - - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveNecessaryCastInForEach2() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; @@ -2313,16 +2091,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545961")] - public async Task DoNotRemoveNecessaryCastInForEach3() - { - // The cast below can't be removed because it would result an error - // in the foreach statement since C doesn't contain a GetEnumerator() - // method. - - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveNecessaryCastInForEach3() + => TestMissingInRegularAndScriptAsync( """ using System.Collections; @@ -2350,15 +2122,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545961")] - public async Task DoNotRemoveNecessaryCastInForEach4() - { - // The cast below can't be removed because it would result in - // C.GetEnumerator() being called rather than D.GetEnumerator(). - - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveNecessaryCastInForEach4() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections; @@ -2393,15 +2160,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545961")] - public async Task DoNotRemoveNecessaryCastInForEach5() - { - // The cast below can't be removed because it would change the - // type of 'x'. - - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveNecessaryCastInForEach5() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2420,17 +2182,12 @@ static void Main() } } """); - } #endregion [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545925")] - public async Task DoNotRemoveCastIfOverriddenMethodHasIncompatibleParameterList() - { - // Note: The cast below can't be removed because the parameter list - // of Goo and its override have different default values. - - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastIfOverriddenMethodHasIncompatibleParameterList() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2452,15 +2209,10 @@ public override void Goo(int x = 2) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545925")] - public async Task RemoveCastIfOverriddenMethodHaveCompatibleParameterList() - { - // Note: The cast below can be removed because the parameter list - // of Goo and its override have the same default values. - - await TestInRegularAndScriptAsync( + public Task RemoveCastIfOverriddenMethodHaveCompatibleParameterList() + => TestInRegularAndScriptAsync( """ using System; @@ -2504,15 +2256,10 @@ public override void Goo(int x = 1) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529916")] - public async Task RemoveCastInReceiverForMethodGroup() - { - // Note: The cast below can be removed because the it results in - // the same method group. - - await TestInRegularAndScriptAsync( + public Task RemoveCastInReceiverForMethodGroup() + => TestInRegularAndScriptAsync( """ using System; @@ -2540,12 +2287,10 @@ static void Main() static void Goo(this string x) { } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609497")] - public async Task Bugfix_609497() - { - await TestMissingInRegularAndScriptAsync( + public Task Bugfix_609497() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -2564,13 +2309,11 @@ static async Task Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624252")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608180")] - public async Task DoNotRemoveCastIfArgumentIsRestricted_TypedReference() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastIfArgumentIsRestricted_TypedReference() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2591,12 +2334,10 @@ static void dd(object obj, TypedReference d) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627107")] - public async Task DoNotRemoveCastOnArgumentsWithOtherDynamicArguments() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastOnArgumentsWithOtherDynamicArguments() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2630,12 +2371,10 @@ static bool Goo(long x, object y, object z) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627107")] - public async Task DoNotRemoveCastOnArgumentsWithOtherDynamicArguments_Bracketed() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastOnArgumentsWithOtherDynamicArguments_Bracketed() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2681,12 +2420,10 @@ void Goo(dynamic xx) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627107")] - public async Task DoNotRemoveCastOnArgumentsWithDynamicReceiverOpt() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastOnArgumentsWithDynamicReceiverOpt() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2697,12 +2434,10 @@ static bool Goo(dynamic d) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627107")] - public async Task DoNotRemoveCastOnArgumentsWithDynamicReceiverOpt_1() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastOnArgumentsWithDynamicReceiverOpt_1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2713,12 +2448,10 @@ static bool Goo(dynamic d) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627107")] - public async Task DoNotRemoveCastOnArgumentsWithDynamicReceiverOpt_2() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastOnArgumentsWithDynamicReceiverOpt_2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2729,12 +2462,10 @@ static bool Goo(dynamic d) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627107")] - public async Task DoNotRemoveCastOnArgumentsWithDynamicReceiverOpt_3() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastOnArgumentsWithDynamicReceiverOpt_3() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2745,12 +2476,10 @@ static bool Goo(dynamic d) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627107")] - public async Task DoNotRemoveCastOnArgumentsWithOtherDynamicArguments_1() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastOnArgumentsWithOtherDynamicArguments_1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2784,12 +2513,10 @@ static bool Goo(object y, long x, object z) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529846")] - public async Task DoNotUnnecessaryCastFromTypeParameterToObject() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotUnnecessaryCastFromTypeParameterToObject() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2801,12 +2528,10 @@ static void Goo(T x, object y) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/640136")] - public async Task RemoveUnnecessaryCastAndParseCorrect() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnnecessaryCastAndParseCorrect() + => TestInRegularAndScriptAsync( """ using System; using System.Threading.Tasks; @@ -2832,12 +2557,10 @@ void Goo(Task x) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/626026")] - public async Task DoNotRemoveCastIfUserDefinedExplicitCast() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastIfUserDefinedExplicitCast() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -2860,12 +2583,10 @@ public struct B { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770187")] - public async Task DoNotRemoveNecessaryCastInSwitchExpression() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveNecessaryCastInSwitchExpression() + => TestMissingInRegularAndScriptAsync( """ namespace ConsoleApplication23 { @@ -2891,13 +2612,11 @@ enum E } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2761")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844482")] - public async Task DoNotRemoveCastFromBaseToDerivedWithExplicitReference() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastFromBaseToDerivedWithExplicitReference() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -2917,12 +2636,10 @@ class D : C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/3254")] - public async Task DoNotRemoveCastToTypeParameterWithExceptionConstraint() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastToTypeParameterWithExceptionConstraint() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2937,12 +2654,10 @@ private static void RequiresCondition(bool condition, string message } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/3254")] - public async Task DoNotRemoveCastToTypeParameterWithExceptionSubTypeConstraint() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastToTypeParameterWithExceptionSubTypeConstraint() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -2957,12 +2672,10 @@ private static void RequiresCondition(bool condition, string message } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8111")] - public async Task DoNotRemoveCastThatChangesShapeOfAnonymousTypeObject() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastThatChangesShapeOfAnonymousTypeObject() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -2972,12 +2685,10 @@ static void Main(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/8111")] - public async Task RemoveCastThatDoesntChangeShapeOfAnonymousTypeObject() - { - await TestInRegularAndScriptAsync( + public Task RemoveCastThatDoesntChangeShapeOfAnonymousTypeObject() + => TestInRegularAndScriptAsync( """ class Program { @@ -2997,12 +2708,10 @@ static void Main(string o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18978")] - public async Task DoNotRemoveCastOnCallToMethodWithParamsArgs() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastOnCallToMethodWithParamsArgs() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -3018,12 +2727,10 @@ private static void TakesParams(params object[] goo) } } """); - } [Fact] - public async Task DoRemoveCastOnCallToMethodWithIncorrectParamsArgs() - { - await TestInRegularAndScript1Async( + public Task DoRemoveCastOnCallToMethodWithIncorrectParamsArgs() + => TestInRegularAndScript1Async( """ class Program { @@ -3052,12 +2759,10 @@ private static void TakesParams(params string wrongDefined) } } """); - } [Fact] - public async Task DoNotRemoveCastOnCallToMethodWithCorrectParamsArgs() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastOnCallToMethodWithCorrectParamsArgs() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -3072,12 +2777,10 @@ private static void TakesParams(params string[] wrongDefined) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18978")] - public async Task RemoveCastOnCallToMethodWithParamsArgsIfImplicitConversionExists() - { - await TestInRegularAndScriptAsync( + public Task RemoveCastOnCallToMethodWithParamsArgsIfImplicitConversionExists() + => TestInRegularAndScriptAsync( """ class Program { @@ -3108,12 +2811,10 @@ private static void TakesParams(params object[] goo) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20630")] - public async Task DoNotRemoveCastOnCallToAttributeWithParamsArgs() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastOnCallToAttributeWithParamsArgs() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Reflection; @@ -3135,12 +2836,10 @@ static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29264")] - public async Task RemoveCastOnDictionaryIndexer() - { - await TestInRegularAndScriptAsync( + public Task RemoveCastOnDictionaryIndexer() + => TestInRegularAndScriptAsync( """ using System; using System.Reflection; @@ -3173,12 +2872,10 @@ static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20630")] - public async Task DoNotRemoveCastOnCallToAttributeWithParamsArgsAndProperty() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastOnCallToAttributeWithParamsArgsAndProperty() + => TestMissingInRegularAndScriptAsync( """ using System; sealed class MarkAttribute : Attribute @@ -3194,12 +2891,10 @@ static class Program { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20630")] - public async Task DoNotRemoveCastOnCallToAttributeWithParamsArgsPropertyAndOtherArg() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastOnCallToAttributeWithParamsArgsPropertyAndOtherArg() + => TestMissingInRegularAndScriptAsync( """ using System; sealed class MarkAttribute : Attribute @@ -3215,12 +2910,10 @@ static class Program { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20630")] - public async Task DoNotRemoveCastOnCallToAttributeWithParamsArgsNamedArgsAndProperty() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotRemoveCastOnCallToAttributeWithParamsArgsNamedArgsAndProperty() + => TestMissingInRegularAndScriptAsync( """ using System; sealed class MarkAttribute : Attribute @@ -3236,12 +2929,10 @@ static class Program { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20630")] - public async Task DoRemoveCastOnCallToAttributeWithInvalidParamsArgs() - { - await TestInRegularAndScript1Async( + public Task DoRemoveCastOnCallToAttributeWithInvalidParamsArgs() + => TestInRegularAndScript1Async( """ using System; sealed class MarkAttribute : Attribute @@ -3272,12 +2963,10 @@ static class Program { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20630")] - public async Task DoNotRemoveCastOfNullToParamsArg() - { - await TestMissingAsync( + public Task DoNotRemoveCastOfNullToParamsArg() + => TestMissingAsync( """ using System; using System.Reflection; @@ -3297,12 +2986,10 @@ static class Program { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20630")] - public async Task RemoveCastOnCallToAttributeWithParamsArgsWithImplicitCast() - { - await TestInRegularAndScriptAsync( + public Task RemoveCastOnCallToAttributeWithParamsArgsWithImplicitCast() + => TestInRegularAndScriptAsync( """ using System; sealed class MarkAttribute : Attribute @@ -3333,12 +3020,10 @@ static class Program { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25456#issuecomment-373549735")] - public async Task DoNotIntroduceDefaultLiteralInSwitchCase() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotIntroduceDefaultLiteralInSwitchCase() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -3352,12 +3037,10 @@ void M() } } """, parameters: new TestParameters(new CSharpParseOptions(LanguageVersion.CSharp7_1))); - } [Fact] - public async Task DoNotIntroduceDefaultLiteralInSwitchCase_CastInsideParentheses() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotIntroduceDefaultLiteralInSwitchCase_CastInsideParentheses() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -3371,12 +3054,10 @@ void M() } } """, parameters: new TestParameters(new CSharpParseOptions(LanguageVersion.CSharp7_1))); - } [Fact] - public async Task DoNotIntroduceDefaultLiteralInSwitchCase_DefaultInsideParentheses() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotIntroduceDefaultLiteralInSwitchCase_DefaultInsideParentheses() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -3390,12 +3071,10 @@ void M() } } """, parameters: new TestParameters(new CSharpParseOptions(LanguageVersion.CSharp7_1))); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27239")] - public async Task DoNotOfferToRemoveCastWhereNoConversionExists() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotOfferToRemoveCastWhereNoConversionExists() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -3408,12 +3087,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28412")] - public async Task DoNotOfferToRemoveCastWhenAccessingHiddenProperty() - { - await TestMissingInRegularAndScriptAsync(""" + public Task DoNotOfferToRemoveCastWhenAccessingHiddenProperty() + => TestMissingInRegularAndScriptAsync(""" using System.Collections.Generic; class Fruit { @@ -3432,5 +3109,4 @@ public void Test() } } """); - } } diff --git a/src/Features/CSharpTest/RemoveUnusedVariable/RemoveUnusedVariableTests.cs b/src/Features/CSharpTest/RemoveUnusedVariable/RemoveUnusedVariableTests.cs index 037e48c9ae109..25cbbef5c5038 100644 --- a/src/Features/CSharpTest/RemoveUnusedVariable/RemoveUnusedVariableTests.cs +++ b/src/Features/CSharpTest/RemoveUnusedVariable/RemoveUnusedVariableTests.cs @@ -29,9 +29,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider => (null, new CSharpRemoveUnusedVariableCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] - public async Task RemoveUnusedVariable() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnusedVariable() + => TestInRegularAndScriptAsync( """ class Class { @@ -49,12 +48,10 @@ void Method() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] - public async Task RemoveUnusedVariable1() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnusedVariable1() + => TestInRegularAndScriptAsync( """ class Class { @@ -76,12 +73,10 @@ void Method() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] - public async Task RemoveUnusedVariable3() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnusedVariable3() + => TestInRegularAndScriptAsync( """ class Class { @@ -99,12 +94,10 @@ void Method() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] - public async Task RemoveUnusedVariableMultipleOnLine() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnusedVariableMultipleOnLine() + => TestInRegularAndScriptAsync( """ class Class { @@ -123,12 +116,10 @@ void Method() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] - public async Task RemoveUnusedVariableMultipleOnLine1() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnusedVariableMultipleOnLine1() + => TestInRegularAndScriptAsync( """ class Class { @@ -147,12 +138,10 @@ void Method() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] - public async Task RemoveUnusedVariableFixAll() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnusedVariableFixAll() + => TestInRegularAndScriptAsync( """ class Class { @@ -171,12 +160,10 @@ void Method() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] - public async Task RemoveUnusedVariableFixAll1() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnusedVariableFixAll1() + => TestInRegularAndScriptAsync( """ class Class { @@ -195,12 +182,10 @@ void Method() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] - public async Task RemoveUnusedVariableFixAll2() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnusedVariableFixAll2() + => TestInRegularAndScriptAsync( """ class Class { @@ -218,13 +203,11 @@ void Method() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] [WorkItem("https://github.com/dotnet/roslyn/issues/20466")] - public async Task RemoveUnusedCatchVariable() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnusedCatchVariable() + => TestInRegularAndScriptAsync( """ class Class { @@ -253,13 +236,11 @@ void Method() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] [WorkItem("https://github.com/dotnet/roslyn/issues/20987")] - public async Task LeadingDirectives() - { - await TestInRegularAndScriptAsync( + public Task LeadingDirectives() + => TestInRegularAndScriptAsync( """ #define DIRECTIVE1 @@ -305,13 +286,11 @@ public static string GetText() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] [WorkItem("https://github.com/dotnet/roslyn/issues/20942")] - public async Task TestWhitespaceBetweenStatements1() - { - await TestInRegularAndScriptAsync( + public Task TestWhitespaceBetweenStatements1() + => TestInRegularAndScriptAsync( """ class Test { @@ -335,13 +314,11 @@ bool TrySomething() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] [WorkItem("https://github.com/dotnet/roslyn/issues/20942")] - public async Task TestWhitespaceBetweenStatements2() - { - await TestInRegularAndScriptAsync( + public Task TestWhitespaceBetweenStatements2() + => TestInRegularAndScriptAsync( """ class Test { @@ -362,12 +339,10 @@ bool TrySomething() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] - public async Task TestWhitespaceBetweenStatementsInSwitchSection1() - { - await TestInRegularAndScriptAsync( + public Task TestWhitespaceBetweenStatementsInSwitchSection1() + => TestInRegularAndScriptAsync( """ class Test { @@ -399,12 +374,10 @@ bool TrySomething() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] - public async Task TestWhitespaceBetweenStatementsInSwitchSection2() - { - await TestInRegularAndScriptAsync( + public Task TestWhitespaceBetweenStatementsInSwitchSection2() + => TestInRegularAndScriptAsync( """ class Test { @@ -433,12 +406,10 @@ bool TrySomething() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] - public async Task RemoveVariableAndComment() - { - await TestInRegularAndScriptAsync( + public Task RemoveVariableAndComment() + => TestInRegularAndScriptAsync( """ class C { @@ -456,12 +427,10 @@ void M() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] - public async Task RemoveVariableAndAssgnment() - { - await TestInRegularAndScriptAsync( + public Task RemoveVariableAndAssgnment() + => TestInRegularAndScriptAsync( """ class C { @@ -480,12 +449,10 @@ void M() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] - public async Task JointDeclarationRemoveFirst() - { - await TestInRegularAndScriptAsync( + public Task JointDeclarationRemoveFirst() + => TestInRegularAndScriptAsync( """ class C { @@ -506,12 +473,10 @@ int M() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] - public async Task JointDeclarationRemoveSecond() - { - await TestInRegularAndScriptAsync( + public Task JointDeclarationRemoveSecond() + => TestInRegularAndScriptAsync( """ class C { @@ -532,12 +497,10 @@ int M() } } """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/23322"), Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] - public async Task JointAssignmentRemoveFirst() - { - await TestInRegularAndScriptAsync( + public Task JointAssignmentRemoveFirst() + => TestInRegularAndScriptAsync( """ class C { @@ -561,12 +524,10 @@ int M() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] - public async Task JointAssignmentRemoveSecond() - { - await TestInRegularAndScriptAsync( + public Task JointAssignmentRemoveSecond() + => TestInRegularAndScriptAsync( """ class C { @@ -590,12 +551,10 @@ int M() } } """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/22921"), Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] - public async Task RemoveUnusedLambda() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnusedLambda() + => TestInRegularAndScriptAsync( """ class C { @@ -618,14 +577,12 @@ int M() } } """); - } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task JointDeclarationRemoveBoth() - { - var input = """ + public Task JointDeclarationRemoveBoth() + => TestInRegularAndScriptAsync(""" @@ -640,9 +597,7 @@ int M() - """; - - var expected = """ + """, """ @@ -656,17 +611,13 @@ int M() - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task JointAssignment() - { - var input = """ + public Task JointAssignment() + => TestInRegularAndScriptAsync(""" @@ -683,9 +634,7 @@ int M() - """; - - var expected = """ + """, """ @@ -701,16 +650,12 @@ int M() - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] [WorkItem("https://github.com/dotnet/roslyn/issues/40336")] - public async Task RemoveUnusedVariableDeclaredInForStatement() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnusedVariableDeclaredInForStatement() + => TestInRegularAndScriptAsync( """ class Class { @@ -735,13 +680,11 @@ void Method() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] [WorkItem("https://github.com/dotnet/roslyn/issues/40336")] - public async Task RemoveUnusedVariableJointDeclaredInForStatement() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnusedVariableJointDeclaredInForStatement() + => TestInRegularAndScriptAsync( """ class Class { @@ -766,25 +709,21 @@ void Method() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] [WorkItem("https://github.com/dotnet/roslyn/issues/44273")] - public async Task TopLevelStatement() - { - await TestAsync(""" + public Task TopLevelStatement() + => TestAsync(""" [|int i = 0|]; """, """ """, TestOptions.Regular); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] [WorkItem("https://github.com/dotnet/roslyn/issues/49827")] - public async Task RemoveUnusedVariableJointDeclaredInForStatementInsideIfStatement() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnusedVariableJointDeclaredInForStatementInsideIfStatement() + => TestInRegularAndScriptAsync( """ class Class { @@ -811,13 +750,11 @@ void Method() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] [WorkItem("https://github.com/dotnet/roslyn/issues/49827")] - public async Task DoNotCrashOnDeclarationInsideIfStatement() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotCrashOnDeclarationInsideIfStatement() + => TestMissingInRegularAndScriptAsync( """ class Class { @@ -830,13 +767,11 @@ void Method(bool test) } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)] [WorkItem("https://github.com/dotnet/roslyn/issues/56924")] - public async Task RemoveUnusedVariableInCatchInsideBadLocalDeclaration() - { - await TestInRegularAndScriptAsync( + public Task RemoveUnusedVariableInCatchInsideBadLocalDeclaration() + => TestInRegularAndScriptAsync( """ class Class { @@ -861,13 +796,11 @@ void Method(bool test) } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] [WorkItem("https://github.com/dotnet/roslyn/issues/51737")] - public async Task RemoveUnusedVariableTopLevel() - { - await TestAsync( + public Task RemoveUnusedVariableTopLevel() + => TestAsync( """ [|int i = 1|]; i = 2; @@ -875,5 +808,4 @@ await TestAsync( """ """, CSharpParseOptions.Default); - } } diff --git a/src/Features/CSharpTest/ReplaceConditionalWithStatements/ReplaceConditionalWithStatementsTests.cs b/src/Features/CSharpTest/ReplaceConditionalWithStatements/ReplaceConditionalWithStatementsTests.cs index 2349228809c5e..7a7af2fb4829b 100644 --- a/src/Features/CSharpTest/ReplaceConditionalWithStatements/ReplaceConditionalWithStatementsTests.cs +++ b/src/Features/CSharpTest/ReplaceConditionalWithStatements/ReplaceConditionalWithStatementsTests.cs @@ -16,9 +16,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ReplaceConditionalWithS public sealed class ReplaceConditionalWithStatementsTests { [Fact] - public async Task TestAssignment_ObjectType() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestAssignment_ObjectType() + => VerifyCS.VerifyRefactoringAsync( """ class C { @@ -46,12 +45,10 @@ void M(bool b) } } """); - } [Fact] - public async Task TestAssignment_ObjectType_OnAssigment() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestAssignment_ObjectType_OnAssigment() + => VerifyCS.VerifyRefactoringAsync( """ class C { @@ -79,12 +76,10 @@ void M(bool b) } } """); - } [Fact] - public async Task TestAssignment_SameType() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestAssignment_SameType() + => VerifyCS.VerifyRefactoringAsync( """ class C { @@ -112,12 +107,10 @@ void M(bool b) } } """); - } [Fact] - public async Task TestAssignment_RefConditional() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestAssignment_RefConditional() + => VerifyCS.VerifyRefactoringAsync( """ #nullable enable @@ -149,12 +142,10 @@ void M(bool b, ref C? x) } } """); - } [Fact] - public async Task TestAssignment_Discard() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestAssignment_Discard() + => VerifyCS.VerifyRefactoringAsync( """ class C { @@ -180,12 +171,10 @@ void M(bool b) } } """); - } [Fact] - public async Task TestAssignment_GlobalStatement() - { - await new VerifyCS.Test + public Task TestAssignment_GlobalStatement() + => new VerifyCS.Test { LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, @@ -209,12 +198,10 @@ public async Task TestAssignment_GlobalStatement() } """ }.RunAsync(); - } [Fact] - public async Task TestAssignment_GlobalStatement_OnAssignment() - { - await new VerifyCS.Test + public Task TestAssignment_GlobalStatement_OnAssignment() + => new VerifyCS.Test { LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, TestState = { OutputKind = OutputKind.ConsoleApplication }, @@ -238,7 +225,6 @@ public async Task TestAssignment_GlobalStatement_OnAssignment() } """ }.RunAsync(); - } [Fact] public async Task TestRefLocalDeclaration1() @@ -276,9 +262,8 @@ void M(bool b, IDisposable d1, IDisposable d2) } [Fact] - public async Task TestCompoundAssignment() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestCompoundAssignment() + => VerifyCS.VerifyRefactoringAsync( """ class C { @@ -306,12 +291,10 @@ void M(bool b) } } """); - } [Fact] - public async Task TestWithExpression() - { - await new VerifyCS.Test + public Task TestWithExpression() + => new VerifyCS.Test { LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp10, TestCode = @@ -356,12 +339,10 @@ public sealed class IsExternalInit } """ }.RunAsync(); - } [Fact] - public async Task TestLocalDeclarationStatement1() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestLocalDeclarationStatement1() + => VerifyCS.VerifyRefactoringAsync( """ class C { @@ -388,12 +369,10 @@ void M(bool b) } } """); - } [Fact] - public async Task TestLocalDeclarationStatement1_OnDeclaration() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestLocalDeclarationStatement1_OnDeclaration() + => VerifyCS.VerifyRefactoringAsync( """ class C { @@ -420,12 +399,10 @@ void M(bool b) } } """); - } [Fact] - public async Task TestLocalDeclarationStatement_WithVar() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestLocalDeclarationStatement_WithVar() + => VerifyCS.VerifyRefactoringAsync( """ class C { @@ -452,12 +429,10 @@ void M(bool b) } } """); - } [Fact] - public async Task TestLocalDeclarationStatement_ThrowExpression() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestLocalDeclarationStatement_ThrowExpression() + => VerifyCS.VerifyRefactoringAsync( """ using System; class C @@ -490,12 +465,10 @@ void M(bool b) int N(int v) => v; } """); - } [Fact] - public async Task TestLocalDeclarationStatement_TopLevel1() - { - await new VerifyCS.Test + public Task TestLocalDeclarationStatement_TopLevel1() + => new VerifyCS.Test { LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp10, TestState = { OutputKind = OutputKind.ConsoleApplication }, @@ -519,12 +492,10 @@ public async Task TestLocalDeclarationStatement_TopLevel1() } """ }.RunAsync(); - } [Fact] - public async Task TestLocalDeclarationStatement_TopLevel_OnDeclaration1() - { - await new VerifyCS.Test + public Task TestLocalDeclarationStatement_TopLevel_OnDeclaration1() + => new VerifyCS.Test { LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp10, TestState = { OutputKind = OutputKind.ConsoleApplication }, @@ -548,12 +519,10 @@ public async Task TestLocalDeclarationStatement_TopLevel_OnDeclaration1() } """ }.RunAsync(); - } [Fact] - public async Task TestLocalDeclarationStatement_TopLevel_WithVar1() - { - await new VerifyCS.Test + public Task TestLocalDeclarationStatement_TopLevel_WithVar1() + => new VerifyCS.Test { LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp10, TestState = { OutputKind = OutputKind.ConsoleApplication }, @@ -577,12 +546,10 @@ public async Task TestLocalDeclarationStatement_TopLevel_WithVar1() } """ }.RunAsync(); - } [Fact] - public async Task TestReturnStatement_ObjectReturn() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestReturnStatement_ObjectReturn() + => VerifyCS.VerifyRefactoringAsync( """ class C { @@ -608,12 +575,10 @@ object M(bool b) } } """); - } [Fact] - public async Task TestReturnStatement_ObjectReturn_OnReturn() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestReturnStatement_ObjectReturn_OnReturn() + => VerifyCS.VerifyRefactoringAsync( """ class C { @@ -639,12 +604,10 @@ object M(bool b) } } """); - } [Fact] - public async Task TestReturnStatement_AcualTypeReturn() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestReturnStatement_AcualTypeReturn() + => VerifyCS.VerifyRefactoringAsync( """ class C { @@ -670,12 +633,10 @@ long M(bool b) } } """); - } [Fact] - public async Task TestExpressionStatement_SimpleInvocationArgument() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestExpressionStatement_SimpleInvocationArgument() + => VerifyCS.VerifyRefactoringAsync( """ using System; class C @@ -703,12 +664,10 @@ void M(bool b) } } """); - } [Fact] - public async Task TestExpressionStatement_NestedInvocationArgument_Outer() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestExpressionStatement_NestedInvocationArgument_Outer() + => VerifyCS.VerifyRefactoringAsync( """ using System; class C @@ -736,12 +695,10 @@ void M(bool b, bool c) } } """); - } [Fact] - public async Task TestExpressionStatement_NestedInvocationArgument_Inner1() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestExpressionStatement_NestedInvocationArgument_Inner1() + => VerifyCS.VerifyRefactoringAsync( """ using System; class C @@ -769,12 +726,10 @@ void M(bool b, bool c) } } """); - } [Fact] - public async Task TestExpressionStatement_NestedInvocationArgument_Inner22() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestExpressionStatement_NestedInvocationArgument_Inner22() + => VerifyCS.VerifyRefactoringAsync( """ using System; class C @@ -802,12 +757,10 @@ void M(bool b, bool c) } } """); - } [Fact] - public async Task TestExpressionStatement_InvocationWithInference1() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestExpressionStatement_InvocationWithInference1() + => VerifyCS.VerifyRefactoringAsync( """ using System; class C @@ -839,12 +792,10 @@ void M(bool b) void F(T value) => Console.WriteLine(typeof(T)); } """); - } [Fact(Skip = "Causes assert in compiler layer")] - public async Task TestExpressionStatement_InvocationWithSimpleObjectCreation() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestExpressionStatement_InvocationWithSimpleObjectCreation() + => VerifyCS.VerifyRefactoringAsync( """ using System; class C @@ -877,12 +828,10 @@ void M(bool b) void F(object value) => Console.WriteLine(value.GetType()); } """); - } [Fact] - public async Task TestExpressionStatement_SimpleInvocationArgument_OnStatement() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestExpressionStatement_SimpleInvocationArgument_OnStatement() + => VerifyCS.VerifyRefactoringAsync( """ using System; class C @@ -910,12 +859,10 @@ void M(bool b) } } """); - } [Fact] - public async Task TestExpressionStatement_SecondInvocationArgument() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestExpressionStatement_SecondInvocationArgument() + => VerifyCS.VerifyRefactoringAsync( """ using System; class C @@ -943,12 +890,10 @@ void M(bool b) } } """); - } [Fact] - public async Task TestExpressionStatement_NestedInvocationArgument() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestExpressionStatement_NestedInvocationArgument() + => VerifyCS.VerifyRefactoringAsync( """ using System; class C @@ -978,12 +923,10 @@ bool M(bool b) } } """); - } [Fact] - public async Task TestAwaitExpression1() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestAwaitExpression1() + => VerifyCS.VerifyRefactoringAsync( """ using System; using System.Threading.Tasks; @@ -1013,12 +956,10 @@ async void M(bool b, Task x, Task y) } } """); - } [Fact] - public async Task TestAwaitExpression_OnAwait() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestAwaitExpression_OnAwait() + => VerifyCS.VerifyRefactoringAsync( """ using System; using System.Threading.Tasks; @@ -1048,12 +989,10 @@ async void M(bool b, Task x, Task y) } } """); - } [Fact] - public async Task TestThrowStatement1() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestThrowStatement1() + => VerifyCS.VerifyRefactoringAsync( """ using System; class C @@ -1081,12 +1020,10 @@ void M(bool b) } } """); - } [Fact] - public async Task TestThrowStatement_OnThrow1() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestThrowStatement_OnThrow1() + => VerifyCS.VerifyRefactoringAsync( """ using System; class C @@ -1114,12 +1051,10 @@ void M(bool b) } } """); - } [Fact] - public async Task TestDeepThrowOnOneSide() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestDeepThrowOnOneSide() + => VerifyCS.VerifyRefactoringAsync( """ using System; class C @@ -1151,12 +1086,10 @@ int M(bool b) int N(int v) => v; } """); - } [Fact] - public async Task TestDeepThrowOnOneSide_LocalDeclaration() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestDeepThrowOnOneSide_LocalDeclaration() + => VerifyCS.VerifyRefactoringAsync( """ using System; class C @@ -1189,12 +1122,10 @@ void M(bool b) int N(int v) => v; } """); - } [Fact] - public async Task TestYieldReturn1() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestYieldReturn1() + => VerifyCS.VerifyRefactoringAsync( """ using System; using System.Collections.Generic; @@ -1224,12 +1155,10 @@ IEnumerable M(bool b) } } """); - } [Fact] - public async Task TestYieldReturn_OnYield1() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestYieldReturn_OnYield1() + => VerifyCS.VerifyRefactoringAsync( """ using System; using System.Collections.Generic; @@ -1259,5 +1188,4 @@ IEnumerable M(bool b) } } """); - } } diff --git a/src/Features/CSharpTest/ReplaceDocCommentTextWithTag/ReplaceDocCommentTextWithTagTests.cs b/src/Features/CSharpTest/ReplaceDocCommentTextWithTag/ReplaceDocCommentTextWithTagTests.cs index ce2c2869dba5a..a88edf99c9706 100644 --- a/src/Features/CSharpTest/ReplaceDocCommentTextWithTag/ReplaceDocCommentTextWithTagTests.cs +++ b/src/Features/CSharpTest/ReplaceDocCommentTextWithTag/ReplaceDocCommentTextWithTagTests.cs @@ -19,9 +19,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor => new CSharpReplaceDocCommentTextWithTagCodeRefactoringProvider(); [Fact] - public async Task TestStartOfKeyword() - { - await TestInRegularAndScriptAsync( + public Task TestStartOfKeyword() + => TestInRegularAndScriptAsync( """ /// Testing keyword [||]null. class C @@ -35,12 +34,10 @@ class C { } """); - } [Fact] - public async Task TestEndOfKeyword() - { - await TestInRegularAndScriptAsync( + public Task TestEndOfKeyword() + => TestInRegularAndScriptAsync( """ /// Testing keyword abstract[||]. class C @@ -54,12 +51,10 @@ class C { } """); - } [Fact] - public async Task TestEndOfKeyword_NewLineFollowing() - { - await TestInRegularAndScriptAsync( + public Task TestEndOfKeyword_NewLineFollowing() + => TestInRegularAndScriptAsync( """ /// Testing keyword static[||] class C @@ -73,12 +68,10 @@ class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76548")] - public async Task TestEndOfKeyword_XmlCloseTagFollowing() - { - await TestInRegularAndScriptAsync( + public Task TestEndOfKeyword_XmlCloseTagFollowing() + => TestInRegularAndScriptAsync( """ /// Testing keyword null[||] class C @@ -92,12 +85,10 @@ class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76548")] - public async Task TestEndOfKeyword_XmlOpenTagPreceding() - { - await TestInRegularAndScriptAsync( + public Task TestEndOfKeyword_XmlOpenTagPreceding() + => TestInRegularAndScriptAsync( """ /// [||]null is an option. class C @@ -111,12 +102,10 @@ class C { } """); - } [Fact] - public async Task TestSelectedKeyword() - { - await TestInRegularAndScriptAsync( + public Task TestSelectedKeyword() + => TestInRegularAndScriptAsync( """ /// Testing keyword [|abstract|]. class C @@ -130,12 +119,10 @@ class C { } """); - } [Fact] - public async Task TestInsideKeyword() - { - await TestInRegularAndScriptAsync( + public Task TestInsideKeyword() + => TestInRegularAndScriptAsync( """ /// Testing keyword asy[||]nc. class C @@ -149,24 +136,20 @@ class C { } """); - } [Fact] - public async Task TestNotInsideKeywordIfNonEmptySpan() - { - await TestMissingAsync( + public Task TestNotInsideKeywordIfNonEmptySpan() + => TestMissingAsync( """ /// TKey must implement the System.IDisposable int[|erf|]ace class C { } """); - } [Fact] - public async Task TestStartOfFullyQualifiedTypeName_Start() - { - await TestInRegularAndScriptAsync( + public Task TestStartOfFullyQualifiedTypeName_Start() + => TestInRegularAndScriptAsync( """ /// TKey must implement the [||]System.IDisposable interface. class C @@ -180,12 +163,10 @@ class C { } """); - } [Fact] - public async Task TestStartOfFullyQualifiedTypeName_Mid1() - { - await TestInRegularAndScriptAsync( + public Task TestStartOfFullyQualifiedTypeName_Mid1() + => TestInRegularAndScriptAsync( """ /// TKey must implement the System[||].IDisposable interface. class C @@ -199,12 +180,10 @@ class C { } """); - } [Fact] - public async Task TestStartOfFullyQualifiedTypeName_Mid2() - { - await TestInRegularAndScriptAsync( + public Task TestStartOfFullyQualifiedTypeName_Mid2() + => TestInRegularAndScriptAsync( """ /// TKey must implement the System.[||]IDisposable interface. class C @@ -218,12 +197,10 @@ class C { } """); - } [Fact] - public async Task TestStartOfFullyQualifiedTypeName_End() - { - await TestInRegularAndScriptAsync( + public Task TestStartOfFullyQualifiedTypeName_End() + => TestInRegularAndScriptAsync( """ /// TKey must implement the System.IDisposable[||] interface. class C @@ -237,12 +214,10 @@ class C { } """); - } [Fact] - public async Task TestStartOfFullyQualifiedTypeName_Selected() - { - await TestInRegularAndScriptAsync( + public Task TestStartOfFullyQualifiedTypeName_Selected() + => TestInRegularAndScriptAsync( """ /// TKey must implement the [|System.IDisposable|] interface. class C @@ -256,12 +231,10 @@ class C { } """); - } [Fact] - public async Task TestTypeParameterReference() - { - await TestInRegularAndScriptAsync( + public Task TestTypeParameterReference() + => TestInRegularAndScriptAsync( """ /// [||]TKey must implement the System.IDisposable interface. class C @@ -275,12 +248,10 @@ class C { } """); - } [Fact] - public async Task TestTypeParameterReference_EmptyClassBody() - { - await TestInRegularAndScriptAsync( + public Task TestTypeParameterReference_EmptyClassBody() + => TestInRegularAndScriptAsync( """ /// [||]TKey must implement the System.IDisposable interface. class C{} @@ -290,12 +261,10 @@ class C{} /// must implement the System.IDisposable interface. class C{} """); - } [Fact] - public async Task TestCanSeeInnerMethod() - { - await TestInRegularAndScriptAsync( + public Task TestCanSeeInnerMethod() + => TestInRegularAndScriptAsync( """ /// Use WriteLine[||] as a Console.WriteLine replacement class C @@ -311,12 +280,10 @@ class C void WriteLine(TKey value) { } } """); - } [Fact] - public async Task TestNotOnMispelledName() - { - await TestMissingAsync( + public Task TestNotOnMispelledName() + => TestMissingAsync( """ /// Use WriteLine1[||] as a Console.WriteLine replacement class C @@ -324,12 +291,10 @@ class C void WriteLine(TKey value) { } } """); - } [Fact] - public async Task TestMethodTypeParameterSymbol() - { - await TestInRegularAndScriptAsync( + public Task TestMethodTypeParameterSymbol() + => TestInRegularAndScriptAsync( """ class C { @@ -345,12 +310,10 @@ class C void WriteLine(TKey value) { } } """); - } [Fact] - public async Task TestMethodTypeParameterSymbol_EmptyBody() - { - await TestInRegularAndScriptAsync( + public Task TestMethodTypeParameterSymbol_EmptyBody() + => TestInRegularAndScriptAsync( """ class C { @@ -366,12 +329,10 @@ class C void WriteLine(TKey value){} } """); - } [Fact] - public async Task TestMethodTypeParameterSymbol_ExpressionBody() - { - await TestInRegularAndScriptAsync( + public Task TestMethodTypeParameterSymbol_ExpressionBody() + => TestInRegularAndScriptAsync( """ class C { @@ -387,12 +348,10 @@ class C object WriteLine(TKey value) => null; } """); - } [Fact] - public async Task TestMethodTypeParameter_SemicolonBody() - { - await TestInRegularAndScriptAsync( + public Task TestMethodTypeParameter_SemicolonBody() + => TestInRegularAndScriptAsync( """ class C { @@ -408,12 +367,10 @@ class C void WriteLine(TKey value); } """); - } [Fact] - public async Task TestMethodParameterSymbol() - { - await TestInRegularAndScriptAsync( + public Task TestMethodParameterSymbol() + => TestInRegularAndScriptAsync( """ class C { @@ -429,12 +386,10 @@ class C void WriteLine(TKey value) { } } """); - } [Fact] - public async Task TestMethodParameterSymbol_EmptyBody() - { - await TestInRegularAndScriptAsync( + public Task TestMethodParameterSymbol_EmptyBody() + => TestInRegularAndScriptAsync( """ class C { @@ -450,12 +405,10 @@ class C void WriteLine(TKey value){} } """); - } [Fact] - public async Task TestMethodParameterSymbol_ExpressionBody() - { - await TestInRegularAndScriptAsync( + public Task TestMethodParameterSymbol_ExpressionBody() + => TestInRegularAndScriptAsync( """ class C { @@ -471,12 +424,10 @@ class C object WriteLine(TKey value) => null; } """); - } [Fact] - public async Task TestMethodParameterSymbol_SemicolonBody() - { - await TestInRegularAndScriptAsync( + public Task TestMethodParameterSymbol_SemicolonBody() + => TestInRegularAndScriptAsync( """ class C { @@ -492,13 +443,11 @@ class C void WriteLine(TKey value); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22278")] [WorkItem("https://github.com/dotnet/roslyn/issues/31208")] - public async Task TestApplicableKeyword() - { - await TestInRegularAndScript1Async( + public Task TestApplicableKeyword() + => TestInRegularAndScript1Async( """ /// Testing keyword interfa[||]ce. class C @@ -511,12 +460,10 @@ class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22278")] - public async Task TestInXMLAttribute() - { - await TestMissingAsync( + public Task TestInXMLAttribute() + => TestMissingAsync( """ /// Testing keyword inside class C @@ -524,12 +471,10 @@ class C void WriteLine(TKey value) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22278")] - public async Task TestInXMLAttribute2() - { - await TestMissingAsync( + public Task TestInXMLAttribute2() + => TestMissingAsync( """ /// Testing keyword inside (TKey value) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38370")] - public async Task TestBaseKeyword() - { - await TestInRegularAndScriptAsync( + public Task TestBaseKeyword() + => TestInRegularAndScriptAsync( """ /// Testing keyword [||]base. class C @@ -556,12 +499,10 @@ class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38370")] - public async Task TestThisKeyword() - { - await TestInRegularAndScriptAsync( + public Task TestThisKeyword() + => TestInRegularAndScriptAsync( """ /// Testing keyword [||]this. class C @@ -575,12 +516,10 @@ class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31208")] - public async Task TestArbitraryKeyword() - { - await TestInRegularAndScriptAsync( + public Task TestArbitraryKeyword() + => TestInRegularAndScriptAsync( """ /// Testing keyword [||]delegate. class C @@ -594,12 +533,10 @@ class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31208")] - public async Task TestContextualKeyword() - { - await TestInRegularAndScriptAsync( + public Task TestContextualKeyword() + => TestInRegularAndScriptAsync( """ /// Testing keyword [||]yield. class C @@ -613,5 +550,4 @@ class C { } """); - } } diff --git a/src/Features/CSharpTest/ReplaceMethodWithProperty/ReplaceMethodWithPropertyTests.cs b/src/Features/CSharpTest/ReplaceMethodWithProperty/ReplaceMethodWithPropertyTests.cs index fa021ef3e571b..654bdecbcb838 100644 --- a/src/Features/CSharpTest/ReplaceMethodWithProperty/ReplaceMethodWithPropertyTests.cs +++ b/src/Features/CSharpTest/ReplaceMethodWithProperty/ReplaceMethodWithPropertyTests.cs @@ -20,15 +20,13 @@ public sealed class ReplaceMethodWithPropertyTests : AbstractCSharpCodeActionTes protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWorkspace workspace, TestParameters parameters) => new ReplaceMethodWithPropertyCodeRefactoringProvider(); - private async Task TestWithAllCodeStyleOff( + private Task TestWithAllCodeStyleOff( string initialMarkup, string expectedMarkup, ParseOptions? parseOptions = null, int index = 0) - { - await TestAsync( + => TestAsync( initialMarkup, expectedMarkup, parseOptions, index: index, options: AllCodeStyleOff); - } private OptionsCollection AllCodeStyleOff => new(GetLanguage()) @@ -59,9 +57,8 @@ private OptionsCollection PreferExpressionBodiedAccessorsAndProperties }; [Fact] - public async Task TestMethodWithGetName() - { - await TestWithAllCodeStyleOff( + public Task TestMethodWithGetName() + => TestWithAllCodeStyleOff( """ class C { @@ -81,12 +78,10 @@ int Goo } } """); - } [Fact] - public async Task TestMethodWithoutGetName() - { - await TestWithAllCodeStyleOff( + public Task TestMethodWithoutGetName() + => TestWithAllCodeStyleOff( """ class C { @@ -106,12 +101,10 @@ int Goo } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/6034")] - public async Task TestMethodWithArrowBody() - { - await TestWithAllCodeStyleOff( + public Task TestMethodWithArrowBody() + => TestWithAllCodeStyleOff( """ class C { @@ -130,12 +123,10 @@ int Goo } } """); - } [Fact] - public async Task TestMethodWithoutBody() - { - await TestWithAllCodeStyleOff( + public Task TestMethodWithoutBody() + => TestWithAllCodeStyleOff( """ class C { @@ -148,12 +139,10 @@ class C int Goo { get; } } """); - } [Fact] - public async Task TestMethodWithModifiers() - { - await TestWithAllCodeStyleOff( + public Task TestMethodWithModifiers() + => TestWithAllCodeStyleOff( """ class C { @@ -173,12 +162,10 @@ public static int Goo } } """); - } [Fact] - public async Task TestMethodWithAttributes() - { - await TestWithAllCodeStyleOff( + public Task TestMethodWithAttributes() + => TestWithAllCodeStyleOff( """ class C { @@ -200,12 +187,10 @@ int Goo } } """); - } [Fact] - public async Task TestMethodWithTrivia_1() - { - await TestWithAllCodeStyleOff( + public Task TestMethodWithTrivia_1() + => TestWithAllCodeStyleOff( """ class C { @@ -227,12 +212,10 @@ int Goo } } """); - } [Fact] - public async Task TestMethodWithTrailingTrivia() - { - await TestWithAllCodeStyleOff( + public Task TestMethodWithTrailingTrivia() + => TestWithAllCodeStyleOff( """ class C { @@ -254,12 +237,10 @@ bool M() } } """); - } [Fact] - public async Task TestDelegateWithTrailingTrivia() - { - await TestWithAllCodeStyleOff( + public Task TestDelegateWithTrailingTrivia() + => TestWithAllCodeStyleOff( """ delegate int Mdelegate(); class C @@ -290,12 +271,10 @@ void M() } } """); - } [Fact] - public async Task TestIndentation() - { - await TestWithAllCodeStyleOff( + public Task TestIndentation() + => TestWithAllCodeStyleOff( """ class C { @@ -327,12 +306,10 @@ int Goo } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21460")] - public async Task TestIfDefMethod1() - { - await TestWithAllCodeStyleOff( + public Task TestIfDefMethod1() + => TestWithAllCodeStyleOff( """ class C { @@ -356,12 +333,10 @@ int Goo #endif } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21460")] - public async Task TestIfDefMethod2() - { - await TestWithAllCodeStyleOff( + public Task TestIfDefMethod2() + => TestWithAllCodeStyleOff( """ class C { @@ -393,12 +368,10 @@ void SetGoo(int val) #endif } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21460")] - public async Task TestIfDefMethod3() - { - await TestWithAllCodeStyleOff( + public Task TestIfDefMethod3() + => TestWithAllCodeStyleOff( """ class C { @@ -430,12 +403,10 @@ int Goo #endif } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21460")] - public async Task TestIfDefMethod4() - { - await TestWithAllCodeStyleOff( + public Task TestIfDefMethod4() + => TestWithAllCodeStyleOff( """ class C { @@ -467,12 +438,10 @@ int Goo #endif } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21460")] - public async Task TestIfDefMethod5() - { - await TestWithAllCodeStyleOff( + public Task TestIfDefMethod5() + => TestWithAllCodeStyleOff( """ class C { @@ -506,12 +475,10 @@ int Goo #endif } """, index: 1); - } [Fact] - public async Task TestMethodWithTrivia_2() - { - await TestWithAllCodeStyleOff( + public Task TestMethodWithTrivia_2() + => TestWithAllCodeStyleOff( """ class C { @@ -542,13 +509,11 @@ int Goo } } """, -index: 1); - } + index: 1); [Fact] - public async Task TestExplicitInterfaceMethod_1() - { - await TestWithAllCodeStyleOff( + public Task TestExplicitInterfaceMethod_1() + => TestWithAllCodeStyleOff( """ class C { @@ -568,12 +533,10 @@ int I.Goo } } """); - } [Fact] - public async Task TestExplicitInterfaceMethod_2() - { - await TestWithAllCodeStyleOff( + public Task TestExplicitInterfaceMethod_2() + => TestWithAllCodeStyleOff( """ interface I { @@ -603,12 +566,10 @@ int I.Goo } } """); - } [Fact] - public async Task TestExplicitInterfaceMethod_3() - { - await TestWithAllCodeStyleOff( + public Task TestExplicitInterfaceMethod_3() + => TestWithAllCodeStyleOff( """ interface I { @@ -638,12 +599,10 @@ int I.Goo } } """); - } [Fact] - public async Task TestInAttribute() - { - await TestMissingInRegularAndScriptAsync( + public Task TestInAttribute() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -653,12 +612,10 @@ int GetGoo() } } """); - } [Fact] - public async Task TestInMethod() - { - await TestMissingInRegularAndScriptAsync( + public Task TestInMethod() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -668,12 +625,10 @@ int GetGoo() } } """); - } [Fact] - public async Task TestVoidMethod() - { - await TestMissingInRegularAndScriptAsync( + public Task TestVoidMethod() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -682,12 +637,10 @@ class C } } """); - } [Fact] - public async Task TestAsyncMethod() - { - await TestMissingInRegularAndScriptAsync( + public Task TestAsyncMethod() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -696,12 +649,10 @@ class C } } """); - } [Fact] - public async Task TestGenericMethod() - { - await TestMissingInRegularAndScriptAsync( + public Task TestGenericMethod() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -710,12 +661,10 @@ class C } } """); - } [Fact] - public async Task TestExtensionMethod() - { - await TestMissingInRegularAndScriptAsync( + public Task TestExtensionMethod() + => TestMissingInRegularAndScriptAsync( """ static class C { @@ -724,12 +673,10 @@ static class C } } """); - } [Fact] - public async Task TestMethodWithParameters_1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMethodWithParameters_1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -738,12 +685,10 @@ class C } } """); - } [Fact] - public async Task TestMethodWithParameters_2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMethodWithParameters_2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -752,12 +697,10 @@ class C } } """); - } [Fact] - public async Task TestNotInSignature_1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotInSignature_1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -767,12 +710,10 @@ int GetGoo() } } """); - } [Fact] - public async Task TestNotInSignature_2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotInSignature_2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -782,12 +723,10 @@ int GetGoo() } } """); - } [Fact] - public async Task TestUpdateGetReferenceNotInMethod() - { - await TestWithAllCodeStyleOff( + public Task TestUpdateGetReferenceNotInMethod() + => TestWithAllCodeStyleOff( """ class C { @@ -817,12 +756,10 @@ void Bar() } } """); - } [Fact] - public async Task TestUpdateGetReferenceSimpleInvocation() - { - await TestWithAllCodeStyleOff( + public Task TestUpdateGetReferenceSimpleInvocation() + => TestWithAllCodeStyleOff( """ class C { @@ -852,12 +789,10 @@ void Bar() } } """); - } [Fact] - public async Task TestUpdateGetReferenceMemberAccessInvocation() - { - await TestWithAllCodeStyleOff( + public Task TestUpdateGetReferenceMemberAccessInvocation() + => TestWithAllCodeStyleOff( """ class C { @@ -887,12 +822,10 @@ void Bar() } } """); - } [Fact] - public async Task TestUpdateGetReferenceBindingMemberInvocation() - { - await TestWithAllCodeStyleOff( + public Task TestUpdateGetReferenceBindingMemberInvocation() + => TestWithAllCodeStyleOff( """ class C { @@ -924,12 +857,10 @@ void Bar() } } """); - } [Fact] - public async Task TestUpdateGetReferenceInMethod() - { - await TestWithAllCodeStyleOff( + public Task TestUpdateGetReferenceInMethod() + => TestWithAllCodeStyleOff( """ class C { @@ -951,12 +882,10 @@ int Goo } } """); - } [Fact] - public async Task TestOverride() - { - await TestWithAllCodeStyleOff( + public Task TestOverride() + => TestWithAllCodeStyleOff( """ class C { @@ -993,12 +922,10 @@ public override int Goo } } """); - } [Fact] - public async Task TestUpdateGetReference_NonInvoked() - { - await TestWithAllCodeStyleOff( + public Task TestUpdateGetReference_NonInvoked() + => TestWithAllCodeStyleOff( """ using System; @@ -1032,12 +959,10 @@ void Bar() } } """); - } [Fact] - public async Task TestUpdateGetReference_ImplicitReference() - { - await TestWithAllCodeStyleOff( + public Task TestUpdateGetReference_ImplicitReference() + => TestWithAllCodeStyleOff( """ using System.Collections; @@ -1075,12 +1000,10 @@ void Bar() } } """); - } [Fact] - public async Task TestUpdateGetSet() - { - await TestWithAllCodeStyleOff( + public Task TestUpdateGetSet() + => TestWithAllCodeStyleOff( """ using System; @@ -1112,13 +1035,11 @@ int Goo } } """, -index: 1); - } + index: 1); [Fact] - public async Task TestUpdateGetSetReference_NonInvoked() - { - await TestWithAllCodeStyleOff( + public Task TestUpdateGetSetReference_NonInvoked() + => TestWithAllCodeStyleOff( """ using System; @@ -1160,13 +1081,11 @@ void Bar() } } """, -index: 1); - } + index: 1); [Fact] - public async Task TestUpdateGetSet_SetterAccessibility() - { - await TestWithAllCodeStyleOff( + public Task TestUpdateGetSet_SetterAccessibility() + => TestWithAllCodeStyleOff( """ using System; @@ -1198,13 +1117,11 @@ private set } } """, -index: 1); - } + index: 1); [Fact] - public async Task TestUpdateGetSet_ExpressionBodies() - { - await TestWithAllCodeStyleOff( + public Task TestUpdateGetSet_ExpressionBodies() + => TestWithAllCodeStyleOff( """ using System; @@ -1233,13 +1150,11 @@ int Goo } } """, -index: 1); - } + index: 1); [Fact] - public async Task TestUpdateGetSet_GetInSetReference() - { - await TestWithAllCodeStyleOff( + public Task TestUpdateGetSet_GetInSetReference() + => TestWithAllCodeStyleOff( """ using System; @@ -1281,13 +1196,11 @@ void Bar() } } """, -index: 1); - } + index: 1); [Fact] - public async Task TestUpdateGetSet_UpdateSetParameterName_1() - { - await TestWithAllCodeStyleOff( + public Task TestUpdateGetSet_UpdateSetParameterName_1() + => TestWithAllCodeStyleOff( """ using System; @@ -1321,13 +1234,11 @@ int Goo } } """, -index: 1); - } + index: 1); [Fact] - public async Task TestUpdateGetSet_UpdateSetParameterName_2() - { - await TestWithAllCodeStyleOff( + public Task TestUpdateGetSet_UpdateSetParameterName_2() + => TestWithAllCodeStyleOff( """ using System; @@ -1361,13 +1272,11 @@ int Goo } } """, -index: 1); - } + index: 1); [Fact] - public async Task TestUpdateGetSet_SetReferenceInSetter() - { - await TestWithAllCodeStyleOff( + public Task TestUpdateGetSet_SetReferenceInSetter() + => TestWithAllCodeStyleOff( """ using System; @@ -1401,13 +1310,11 @@ int Goo } } """, -index: 1); - } + index: 1); [Fact] - public async Task TestVirtualGetWithOverride_1() - { - await TestWithAllCodeStyleOff( + public Task TestVirtualGetWithOverride_1() + => TestWithAllCodeStyleOff( """ class C { @@ -1444,13 +1351,11 @@ protected override int Goo } } """, -index: 0); - } + index: 0); [Fact] - public async Task TestVirtualGetWithOverride_2() - { - await TestWithAllCodeStyleOff( + public Task TestVirtualGetWithOverride_2() + => TestWithAllCodeStyleOff( """ class C { @@ -1489,13 +1394,11 @@ protected override int Goo } } """, -index: 0); - } + index: 0); [Fact] - public async Task TestGetWithInterface() - { - await TestWithAllCodeStyleOff( + public Task TestGetWithInterface() + => TestWithAllCodeStyleOff( """ interface I { @@ -1525,13 +1428,11 @@ public int Goo } } """, -index: 0); - } + index: 0); [Fact] - public async Task TestWithPartialClasses() - { - await TestWithAllCodeStyleOff( + public Task TestWithPartialClasses() + => TestWithAllCodeStyleOff( """ partial class C { @@ -1566,13 +1467,11 @@ partial class C { } """, -index: 1); - } + index: 1); [Fact] - public async Task TestUpdateGetSetCaseInsensitive() - { - await TestWithAllCodeStyleOff( + public Task TestUpdateGetSetCaseInsensitive() + => TestWithAllCodeStyleOff( """ using System; @@ -1604,13 +1503,11 @@ int Goo } } """, -index: 1); - } + index: 1); [Fact] - public async Task Tuple() - { - await TestWithAllCodeStyleOff( + public Task Tuple() + => TestWithAllCodeStyleOff( """ class C { @@ -1630,12 +1527,10 @@ class C } } """); - } [Fact] - public async Task Tuple_GetAndSet() - { - await TestWithAllCodeStyleOff( + public Task Tuple_GetAndSet() + => TestWithAllCodeStyleOff( """ using System; @@ -1668,12 +1563,10 @@ class C } """ + TestResources.NetFX.ValueTuple.tuplelib_cs, index: 1); - } [Fact] - public async Task TupleWithNames_GetAndSet() - { - await TestWithAllCodeStyleOff( + public Task TupleWithNames_GetAndSet() + => TestWithAllCodeStyleOff( """ using System; @@ -1706,13 +1599,10 @@ class C } """ + TestResources.NetFX.ValueTuple.tuplelib_cs, index: 1); - } [Fact] - public async Task TupleWithDifferentNames_GetAndSet() - { - // Cannot refactor tuples with different names together - await TestActionCountAsync( + public Task TupleWithDifferentNames_GetAndSet() + => TestActionCountAsync( """ using System; @@ -1727,13 +1617,11 @@ void setGoo((int c, string d) i) } } """, -count: 1, new TestParameters(options: AllCodeStyleOff)); - } + count: 1, new TestParameters(options: AllCodeStyleOff)); [Fact] - public async Task TestOutVarDeclaration_1() - { - await TestWithAllCodeStyleOff( + public Task TestOutVarDeclaration_1() + => TestWithAllCodeStyleOff( """ class C { @@ -1774,13 +1662,11 @@ void Test() } } """, -index: 0); - } + index: 0); [Fact] - public async Task TestOutVarDeclaration_2() - { - await TestWithAllCodeStyleOff( + public Task TestOutVarDeclaration_2() + => TestWithAllCodeStyleOff( """ class C { @@ -1821,13 +1707,11 @@ void Test() } } """, -index: 1); - } + index: 1); [Fact] - public async Task TestOutVarDeclaration_3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestOutVarDeclaration_3() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1847,12 +1731,10 @@ void Test() } } """); - } [Fact] - public async Task TestOutVarDeclaration_4() - { - await TestMissingInRegularAndScriptAsync( + public Task TestOutVarDeclaration_4() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -1872,12 +1754,10 @@ void Test() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14327")] - public async Task TestUpdateChainedGet1() - { - await TestWithAllCodeStyleOff( + public Task TestUpdateChainedGet1() + => TestWithAllCodeStyleOff( """ public class Goo { @@ -1909,12 +1789,10 @@ public Goo Value } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16980")] - public async Task TestCodeStyle1() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle1() + => TestInRegularAndScriptAsync( """ class C { @@ -1930,12 +1808,10 @@ class C int Goo { get => 1; } } """, options: PreferExpressionBodiedAccessors); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16980")] - public async Task TestCodeStyle2() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle2() + => TestInRegularAndScriptAsync( """ class C { @@ -1951,12 +1827,10 @@ class C int Goo => 1; } """, options: PreferExpressionBodiedProperties); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16980")] - public async Task TestCodeStyle3() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle3() + => TestInRegularAndScriptAsync( """ class C { @@ -1972,12 +1846,10 @@ class C int Goo => 1; } """, options: PreferExpressionBodiedAccessorsAndProperties); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16980")] - public async Task TestCodeStyle4() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle4() + => TestInRegularAndScriptAsync( """ class C { @@ -1998,14 +1870,12 @@ class C int Goo { get => 1; set => _i = value; } } """, -index: 1, -options: PreferExpressionBodiedAccessors); - } + index: 1, + options: PreferExpressionBodiedAccessors); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16980")] - public async Task TestCodeStyle5() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle5() + => TestInRegularAndScriptAsync( """ class C { @@ -2037,14 +1907,12 @@ int Goo } } """, -index: 1, -options: PreferExpressionBodiedProperties); - } + index: 1, + options: PreferExpressionBodiedProperties); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16980")] - public async Task TestCodeStyle6() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle6() + => TestInRegularAndScriptAsync( """ class C { @@ -2065,14 +1933,12 @@ class C int Goo { get => 1; set => _i = value; } } """, -index: 1, -options: PreferExpressionBodiedAccessorsAndProperties); - } + index: 1, + options: PreferExpressionBodiedAccessorsAndProperties); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16980")] - public async Task TestCodeStyle7() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle7() + => TestInRegularAndScriptAsync( """ class C { @@ -2085,12 +1951,10 @@ class C int Goo => 0; } """, options: PreferExpressionBodiedProperties); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16980")] - public async Task TestCodeStyle8() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle8() + => TestInRegularAndScriptAsync( """ class C { @@ -2103,12 +1967,10 @@ class C int Goo { get => 0; } } """, options: PreferExpressionBodiedAccessors); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16980")] - public async Task TestCodeStyle9() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle9() + => TestInRegularAndScriptAsync( """ class C { @@ -2121,12 +1983,10 @@ class C int Goo { get => throw e; } } """, options: PreferExpressionBodiedAccessors); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16980")] - public async Task TestCodeStyle10() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle10() + => TestInRegularAndScriptAsync( """ class C { @@ -2139,12 +1999,10 @@ class C int Goo => throw e; } """, options: PreferExpressionBodiedProperties); - } [Fact] - public async Task TestUseExpressionBodyWhenOnSingleLine_AndIsSingleLine() - { - await TestInRegularAndScriptAsync( + public Task TestUseExpressionBodyWhenOnSingleLine_AndIsSingleLine() + => TestInRegularAndScriptAsync( """ class C { @@ -2157,12 +2015,10 @@ class C int Goo => throw e; } """, options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement)); - } [Fact] - public async Task TestUseExpressionBodyWhenOnSingleLine_AndIsNotSingleLine() - { - await TestInRegularAndScriptAsync( + public Task TestUseExpressionBodyWhenOnSingleLine_AndIsNotSingleLine() + => TestInRegularAndScriptAsync( """ class C { @@ -2187,12 +2043,10 @@ int Goo { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement }, }); - } [Fact] - public async Task TestExplicitInterfaceImplementation() - { - await TestWithAllCodeStyleOff( + public Task TestExplicitInterfaceImplementation() + => TestWithAllCodeStyleOff( """ interface IGoo { @@ -2224,12 +2078,10 @@ int IGoo.Goo } } """); - } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=443523")] - public async Task TestSystemObjectMetadataOverride() - { - await TestMissingAsync( + public Task TestSystemObjectMetadataOverride() + => TestMissingAsync( """ class C { @@ -2238,12 +2090,10 @@ class C } } """); - } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=443523")] - public async Task TestMetadataOverride() - { - await TestWithAllCodeStyleOff( + public Task TestMetadataOverride() + => TestWithAllCodeStyleOff( """ class C : System.Type { @@ -2263,12 +2113,10 @@ class C : System.Type } } """); - } [Fact] - public async Task IgnoreIfTopLevelNullableIsDifferent_GetterNullable() - { - await TestInRegularAndScriptAsync( + public Task IgnoreIfTopLevelNullableIsDifferent_GetterNullable() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -2302,12 +2150,10 @@ public void SetName(string name) public string? Name => this.name; } """); - } [Fact] - public async Task IgnoreIfTopLevelNullableIsDifferent_SetterNullable() - { - await TestInRegularAndScriptAsync( + public Task IgnoreIfTopLevelNullableIsDifferent_SetterNullable() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -2341,12 +2187,10 @@ public void SetName(string? name) public string Name => this.name ?? ""; } """); - } [Fact] - public async Task IgnoreIfNestedNullableIsDifferent_GetterNullable() - { - await TestInRegularAndScriptAsync( + public Task IgnoreIfNestedNullableIsDifferent_GetterNullable() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -2380,12 +2224,10 @@ public void SetNames(IEnumerable names) public IEnumerable Names => this.names; } """); - } [Fact] - public async Task IgnoreIfNestedNullableIsDifferent_SetterNullable() - { - await TestInRegularAndScriptAsync( + public Task IgnoreIfNestedNullableIsDifferent_SetterNullable() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -2423,12 +2265,10 @@ public void SetNames(IEnumerable names) public IEnumerable Names => this.names.Where(n => n is object); } """); - } [Fact] - public async Task NullabilityOfFieldDifferentThanProperty() - { - await TestInRegularAndScriptAsync( + public Task NullabilityOfFieldDifferentThanProperty() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -2452,12 +2292,10 @@ class C public string? Name => name; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38379")] - public async Task TestUnsafeGetter() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafeGetter() + => TestInRegularAndScriptAsync( """ class C { @@ -2481,12 +2319,10 @@ public unsafe int P } } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38379")] - public async Task TestUnsafeSetter() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafeSetter() + => TestInRegularAndScriptAsync( """ class C { @@ -2510,12 +2346,10 @@ public unsafe int P } } """, index: 1); - } [Fact] - public async Task TestAtStartOfMethod() - { - await TestWithAllCodeStyleOff( + public Task TestAtStartOfMethod() + => TestWithAllCodeStyleOff( """ class C { @@ -2535,12 +2369,10 @@ int Goo } } """); - } [Fact] - public async Task TestBeforeStartOfMethod_OnSameLine() - { - await TestWithAllCodeStyleOff( + public Task TestBeforeStartOfMethod_OnSameLine() + => TestWithAllCodeStyleOff( """ class C { @@ -2560,12 +2392,10 @@ int Goo } } """); - } [Fact] - public async Task TestBeforeStartOfMethod_OnPreviousLine() - { - await TestWithAllCodeStyleOff( + public Task TestBeforeStartOfMethod_OnPreviousLine() + => TestWithAllCodeStyleOff( """ class C { @@ -2587,12 +2417,10 @@ int Goo } } """); - } [Fact] - public async Task TestBeforeStartOfMethod_NotMultipleLinesPrior() - { - await TestMissingInRegularAndScriptAsync( + public Task TestBeforeStartOfMethod_NotMultipleLinesPrior() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2603,12 +2431,10 @@ int GetGoo() } } """); - } [Fact] - public async Task TestBeforeStartOfMethod_NotBeforeAttributes() - { - await TestInRegularAndScript1Async( + public Task TestBeforeStartOfMethod_NotBeforeAttributes() + => TestInRegularAndScript1Async( """ class C { @@ -2630,12 +2456,10 @@ int Goo } } """); - } [Fact] - public async Task TestBeforeStartOfMethod_NotBeforeComments() - { - await TestMissingInRegularAndScriptAsync( + public Task TestBeforeStartOfMethod_NotBeforeComments() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2645,12 +2469,10 @@ int GetGoo() } } """); - } [Fact] - public async Task TestBeforeStartOfMethod_NotInComment() - { - await TestMissingInRegularAndScriptAsync( + public Task TestBeforeStartOfMethod_NotInComment() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -2660,12 +2482,10 @@ int GetGoo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42699")] - public async Task TestSameNameMemberAsProperty() - { - await TestInRegularAndScript1Async( + public Task TestSameNameMemberAsProperty() + => TestInRegularAndScript1Async( """ class C { @@ -2687,12 +2507,10 @@ int Goo1 } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42698")] - public async Task TestMethodWithTrivia_3() - { - await TestInRegularAndScript1Async( + public Task TestMethodWithTrivia_3() + => TestInRegularAndScript1Async( """ class C { @@ -2709,12 +2527,10 @@ class C int Goo => 1; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42698")] - public async Task TestMethodWithTrivia_4() - { - await TestWithAllCodeStyleOff( + public Task TestMethodWithTrivia_4() + => TestWithAllCodeStyleOff( """ class C { @@ -2743,14 +2559,12 @@ int Goo } } """, -index: 1); - } + index: 1); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] [WorkItem("https://github.com/dotnet/roslyn/issues/57769")] - public async Task TestInLinkedFile() - { - await TestInRegularAndScriptAsync( + public Task TestInLinkedFile() + => TestInRegularAndScriptAsync( """ @@ -2790,12 +2604,10 @@ bool M() """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37991")] - public async Task AllowIfNestedNullableIsSame() - { - await TestInRegularAndScriptAsync( + public Task AllowIfNestedNullableIsSame() + => TestInRegularAndScriptAsync( """ #nullable enable @@ -2828,12 +2640,10 @@ class C public IEnumerable Names { get => this.names.Where(n => n is object); set => this.names = value; } } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37991")] - public async Task TestGetSetWithGeneric() - { - await TestInRegularAndScriptAsync( + public Task TestGetSetWithGeneric() + => TestInRegularAndScriptAsync( """ using System.Threading.Tasks; @@ -2862,12 +2672,10 @@ class C public Task SomeTask { get => this.someTask; set => this.someTask = value; } } """, index: 1); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40758")] - public async Task TestReferenceTrivia1() - { - await TestInRegularAndScriptAsync( + public Task TestReferenceTrivia1() + => TestInRegularAndScriptAsync( """ class Class { @@ -2894,12 +2702,10 @@ static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40758")] - public async Task TestReferenceTrivia2() - { - await TestInRegularAndScriptAsync( + public Task TestReferenceTrivia2() + => TestInRegularAndScriptAsync( """ class Class { @@ -2926,12 +2732,10 @@ static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40758")] - public async Task TestReferenceTrivia3() - { - await TestInRegularAndScriptAsync( + public Task TestReferenceTrivia3() + => TestInRegularAndScriptAsync( """ class Class { @@ -2954,12 +2758,10 @@ static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40758")] - public async Task TestReferenceTrivia4() - { - await TestInRegularAndScriptAsync( + public Task TestReferenceTrivia4() + => TestInRegularAndScriptAsync( """ class Class { @@ -2982,12 +2784,10 @@ static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72035")] - public async Task TestUpdateGetReferenceGeneratedPart() - { - await TestInRegularAndScript1Async( + public Task TestUpdateGetReferenceGeneratedPart() + => TestInRegularAndScript1Async( """ @@ -3020,12 +2820,10 @@ int Goo } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61161")] - public async Task TestEndOfLineTrivia1() - { - await TestInRegularAndScriptAsync( + public Task TestEndOfLineTrivia1() + => TestInRegularAndScriptAsync( """ class C { @@ -3040,12 +2838,10 @@ class C public void Test2() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61161")] - public async Task TestEndOfLineTrivia2() - { - await TestInRegularAndScriptAsync( + public Task TestEndOfLineTrivia2() + => TestInRegularAndScriptAsync( """ class C { @@ -3062,5 +2858,4 @@ class C public void Test2() { } } """); - } } diff --git a/src/Features/CSharpTest/ReplacePropertyWithMethods/ReplacePropertyWithMethodsTests.cs b/src/Features/CSharpTest/ReplacePropertyWithMethods/ReplacePropertyWithMethodsTests.cs index 58fb340e90059..721cef60b837d 100644 --- a/src/Features/CSharpTest/ReplacePropertyWithMethods/ReplacePropertyWithMethodsTests.cs +++ b/src/Features/CSharpTest/ReplacePropertyWithMethods/ReplacePropertyWithMethodsTests.cs @@ -24,9 +24,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor => new ReplacePropertyWithMethodsCodeRefactoringProvider(); [Fact] - public async Task TestGetWithBody() - { - await TestInRegularAndScriptAsync( + public Task TestGetWithBody() + => TestInRegularAndScriptAsync( """ class C { @@ -48,12 +47,10 @@ private int GetProp() } } """); - } [Fact] - public async Task TestPublicProperty() - { - await TestInRegularAndScriptAsync( + public Task TestPublicProperty() + => TestInRegularAndScriptAsync( """ class C { @@ -75,12 +72,10 @@ public int GetProp() } } """); - } [Fact] - public async Task TestAnonyousType1() - { - await TestInRegularAndScriptAsync( + public Task TestAnonyousType1() + => TestInRegularAndScriptAsync( """ class C { @@ -110,12 +105,10 @@ public void M() var v = new { P = this.GetProp() } } } """); - } [Fact] - public async Task TestAnonyousType2() - { - await TestInRegularAndScriptAsync( + public Task TestAnonyousType2() + => TestInRegularAndScriptAsync( """ class C { @@ -145,12 +138,10 @@ public void M() var v = new { Prop = this.GetProp() } } } """); - } [Fact] - public async Task TestPassedToRef1() - { - await TestInRegularAndScriptAsync( + public Task TestPassedToRef1() + => TestInRegularAndScriptAsync( """ class C { @@ -190,12 +181,10 @@ public void M() } } """); - } [Fact] - public async Task TestPassedToOut1() - { - await TestInRegularAndScriptAsync( + public Task TestPassedToOut1() + => TestInRegularAndScriptAsync( """ class C { @@ -235,12 +224,10 @@ public void M() } } """); - } [Fact] - public async Task TestUsedInAttribute1() - { - await TestInRegularAndScriptAsync( + public Task TestUsedInAttribute1() + => TestInRegularAndScriptAsync( """ using System; @@ -276,12 +263,10 @@ class D { } """); - } [Fact] - public async Task TestSetWithBody1() - { - await TestInRegularAndScriptAsync( + public Task TestSetWithBody1() + => TestInRegularAndScriptAsync( """ class C { @@ -303,12 +288,10 @@ private void SetProp(int value) } } """); - } [Fact] - public async Task TestSetReference1() - { - await TestInRegularAndScriptAsync( + public Task TestSetReference1() + => TestInRegularAndScriptAsync( """ class C { @@ -340,12 +323,10 @@ void M() } } """); - } [Fact] - public async Task TestGetterAndSetter() - { - await TestInRegularAndScriptAsync( + public Task TestGetterAndSetter() + => TestInRegularAndScriptAsync( """ class C { @@ -377,12 +358,10 @@ private void SetProp(int value) } } """); - } [Fact] - public async Task TestGetterAndSetterAccessibilityChange() - { - await TestInRegularAndScriptAsync( + public Task TestGetterAndSetterAccessibilityChange() + => TestInRegularAndScriptAsync( """ class C { @@ -414,12 +393,10 @@ private void SetProp(int value) } } """); - } [Fact] - public async Task TestIncrement1() - { - await TestInRegularAndScriptAsync( + public Task TestIncrement1() + => TestInRegularAndScriptAsync( """ class C { @@ -461,12 +438,10 @@ void M() } } """); - } [Fact] - public async Task TestDecrement2() - { - await TestInRegularAndScriptAsync( + public Task TestDecrement2() + => TestInRegularAndScriptAsync( """ class C { @@ -508,12 +483,10 @@ void M() } } """); - } [Fact] - public async Task TestRecursiveGet() - { - await TestInRegularAndScriptAsync( + public Task TestRecursiveGet() + => TestInRegularAndScriptAsync( """ class C { @@ -535,12 +508,10 @@ private int GetProp() } } """); - } [Fact] - public async Task TestRecursiveSet() - { - await TestInRegularAndScriptAsync( + public Task TestRecursiveSet() + => TestInRegularAndScriptAsync( """ class C { @@ -562,12 +533,10 @@ private void SetProp(int value) } } """); - } [Fact] - public async Task TestCompoundAssign1() - { - await TestInRegularAndScriptAsync( + public Task TestCompoundAssign1() + => TestInRegularAndScriptAsync( """ class C { @@ -609,12 +578,10 @@ void M() } } """); - } [Fact] - public async Task TestCompoundAssign2() - { - await TestInRegularAndScriptAsync( + public Task TestCompoundAssign2() + => TestInRegularAndScriptAsync( """ class C { @@ -656,12 +623,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41159")] - public async Task TestCompoundAssign3() - { - await TestInRegularAndScriptAsync( + public Task TestCompoundAssign3() + => TestInRegularAndScriptAsync( """ class C { @@ -703,12 +668,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41159")] - public async Task TestCompoundAssign4() - { - await TestInRegularAndScriptAsync( + public Task TestCompoundAssign4() + => TestInRegularAndScriptAsync( """ class C { @@ -750,12 +713,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41159")] - public async Task TestCompoundAssign5() - { - await TestInRegularAndScriptAsync( + public Task TestCompoundAssign5() + => TestInRegularAndScriptAsync( """ class C { @@ -797,12 +758,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingAccessors() - { - await TestInRegularAndScriptAsync( + public Task TestMissingAccessors() + => TestInRegularAndScriptAsync( """ class C { @@ -824,12 +783,10 @@ void M() } } """); - } [Fact] - public async Task TestComputedProp() - { - await TestInRegularAndScriptAsync( + public Task TestComputedProp() + => TestInRegularAndScriptAsync( """ class C { @@ -845,12 +802,10 @@ private int GetProp() } } """); - } [Fact] - public async Task TestComputedPropWithTrailingTrivia() - { - await TestInRegularAndScriptAsync( + public Task TestComputedPropWithTrailingTrivia() + => TestInRegularAndScriptAsync( """ class C { @@ -866,12 +821,10 @@ private int GetProp() } } """); - } [Fact] - public async Task TestIndentation() - { - await TestInRegularAndScriptAsync( + public Task TestIndentation() + => TestInRegularAndScriptAsync( """ class C { @@ -903,12 +856,10 @@ private int GetGoo() } } """); - } [Fact] - public async Task TestComputedPropWithTrailingTriviaAfterArrow() - { - await TestInRegularAndScriptAsync( + public Task TestComputedPropWithTrailingTriviaAfterArrow() + => TestInRegularAndScriptAsync( """ class C { @@ -925,12 +876,10 @@ public int GetProp() } } """); - } [Fact] - public async Task TestAbstractProperty() - { - await TestInRegularAndScriptAsync( + public Task TestAbstractProperty() + => TestInRegularAndScriptAsync( """ class C { @@ -951,12 +900,10 @@ public void M() var v = new { P = this.GetProp() } } } """); - } [Fact] - public async Task TestVirtualProperty() - { - await TestInRegularAndScriptAsync( + public Task TestVirtualProperty() + => TestInRegularAndScriptAsync( """ class C { @@ -986,12 +933,10 @@ public void M() var v = new { P = this.GetProp() } } } """); - } [Fact] - public async Task TestInterfaceProperty() - { - await TestInRegularAndScriptAsync( + public Task TestInterfaceProperty() + => TestInRegularAndScriptAsync( """ interface I { @@ -1004,12 +949,10 @@ interface I int GetProp(); } """); - } [Fact] - public async Task TestAutoProperty1() - { - await TestInRegularAndScriptAsync( + public Task TestAutoProperty1() + => TestInRegularAndScriptAsync( """ class C { @@ -1027,12 +970,10 @@ public int GetProp() } } """); - } [Fact] - public async Task TestAutoProperty2() - { - await TestInRegularAndScriptAsync( + public Task TestAutoProperty2() + => TestInRegularAndScriptAsync( """ class C { @@ -1060,12 +1001,10 @@ public C() } } """); - } [Fact] - public async Task TestAutoProperty3() - { - await TestInRegularAndScriptAsync( + public Task TestAutoProperty3() + => TestInRegularAndScriptAsync( """ class C { @@ -1093,12 +1032,10 @@ public C() } } """); - } [Fact] - public async Task TestAutoProperty4() - { - await TestInRegularAndScriptAsync( + public Task TestAutoProperty4() + => TestInRegularAndScriptAsync( """ class C { @@ -1116,12 +1053,10 @@ public int GetProp() } } """); - } [Fact] - public async Task TestAutoProperty5() - { - await TestInRegularAndScriptAsync( + public Task TestAutoProperty5() + => TestInRegularAndScriptAsync( """ class C { @@ -1142,12 +1077,10 @@ public int GetProp() } } """); - } [Fact] - public async Task TestAutoProperty6() - { - await TestInRegularAndScriptAsync( + public Task TestAutoProperty6() + => TestInRegularAndScriptAsync( """ class C { @@ -1165,12 +1098,10 @@ public int GetPascalCase() } } """); - } [Fact] - public async Task TestUniqueName1() - { - await TestInRegularAndScriptAsync( + public Task TestUniqueName1() + => TestInRegularAndScriptAsync( """ class C { @@ -1196,12 +1127,10 @@ public int GetProp1() public abstract int GetProp(); } """); - } [Fact] - public async Task TestUniqueName2() - { - await TestInRegularAndScriptAsync( + public Task TestUniqueName2() + => TestInRegularAndScriptAsync( """ class C { @@ -1225,12 +1154,10 @@ public void SetProp1(int value) public abstract void SetProp(int i); } """); - } [Fact] - public async Task TestUniqueName3() - { - await TestInRegularAndScriptAsync( + public Task TestUniqueName3() + => TestInRegularAndScriptAsync( """ class C { @@ -1254,12 +1181,10 @@ public void SetProp1(object value) public abstract void SetProp(dynamic i); } """); - } [Fact] - public async Task TestTrivia1() - { - await TestInRegularAndScriptAsync( + public Task TestTrivia1() + => TestInRegularAndScriptAsync( """ class C { @@ -1294,12 +1219,10 @@ void M() } } """); - } [Fact] - public async Task TestTrivia2() - { - await TestInRegularAndScriptAsync( + public Task TestTrivia2() + => TestInRegularAndScriptAsync( """ class C { @@ -1334,12 +1257,10 @@ void M() } } """); - } [Fact] - public async Task TestTrivia3() - { - await TestInRegularAndScriptAsync( + public Task TestTrivia3() + => TestInRegularAndScriptAsync( """ class C { @@ -1374,12 +1295,10 @@ void M() } } """); - } [Fact] - public async Task ReplaceReadInsideWrite1() - { - await TestInRegularAndScriptAsync( + public Task ReplaceReadInsideWrite1() + => TestInRegularAndScriptAsync( """ class C { @@ -1412,12 +1331,10 @@ void M() } } """); - } [Fact] - public async Task ReplaceReadInsideWrite2() - { - await TestInRegularAndScriptAsync( + public Task ReplaceReadInsideWrite2() + => TestInRegularAndScriptAsync( """ class C { @@ -1450,12 +1367,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16157")] - public async Task TestWithConditionalBinding1() - { - await TestInRegularAndScriptAsync( + public Task TestWithConditionalBinding1() + => TestInRegularAndScriptAsync( """ public class Goo { @@ -1485,12 +1400,10 @@ public static void Bar() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16980")] - public async Task TestCodeStyle1() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle1() + => TestInRegularAndScriptAsync( """ class C { @@ -1509,12 +1422,10 @@ class C private int GetProp() => 0; } """, options: PreferExpressionBodiedMethods); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16980")] - public async Task TestCodeStyle2() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle2() + => TestInRegularAndScriptAsync( """ class C { @@ -1539,12 +1450,10 @@ class C private void SetProp(int value) => throw e; } """, options: PreferExpressionBodiedMethods); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16980")] - public async Task TestCodeStyle3() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle3() + => TestInRegularAndScriptAsync( """ class C { @@ -1563,12 +1472,10 @@ class C private void SetProp(int value) => throw e; } """, options: PreferExpressionBodiedMethods); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16980")] - public async Task TestCodeStyle4() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle4() + => TestInRegularAndScriptAsync( """ class C { @@ -1581,12 +1488,10 @@ class C private int GetProp() => 0; } """, options: PreferExpressionBodiedMethods); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16980")] - public async Task TestCodeStyle5() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle5() + => TestInRegularAndScriptAsync( """ class C { @@ -1601,12 +1506,10 @@ class C private int GetProp() => prop; } """, options: PreferExpressionBodiedMethods); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16980")] - public async Task TestCodeStyle6() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle6() + => TestInRegularAndScriptAsync( """ class C { @@ -1622,12 +1525,10 @@ class C private void SetProp(int value) => prop = value; } """, options: PreferExpressionBodiedMethods); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/16980")] - public async Task TestCodeStyle7() - { - await TestInRegularAndScriptAsync( + public Task TestCodeStyle7() + => TestInRegularAndScriptAsync( """ class C { @@ -1651,12 +1552,10 @@ private int GetProp() } } """, options: PreferExpressionBodiedMethods); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18234")] - public async Task TestDocumentationComment1() - { - await TestInRegularAndScriptAsync( + public Task TestDocumentationComment1() + => TestInRegularAndScriptAsync( """ internal interface ILanguageServiceHost { @@ -1684,12 +1583,10 @@ internal interface ILanguageServiceHost object GetActiveProjectContext(); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18234")] - public async Task TestDocumentationComment2() - { - await TestInRegularAndScriptAsync( + public Task TestDocumentationComment2() + => TestInRegularAndScriptAsync( """ internal interface ILanguageServiceHost { @@ -1717,12 +1614,10 @@ internal interface ILanguageServiceHost void SetActiveProjectContext(object value); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18234")] - public async Task TestDocumentationComment3() - { - await TestInRegularAndScriptAsync( + public Task TestDocumentationComment3() + => TestInRegularAndScriptAsync( """ internal interface ILanguageServiceHost { @@ -1751,12 +1646,10 @@ internal interface ILanguageServiceHost void SetActiveProjectContext(object value); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18234")] - public async Task TestDocumentationComment4() - { - await TestInRegularAndScriptAsync( + public Task TestDocumentationComment4() + => TestInRegularAndScriptAsync( """ internal interface ILanguageServiceHost { @@ -1790,12 +1683,10 @@ internal struct AStruct private int x; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18234")] - public async Task TestDocumentationComment5() - { - await TestInRegularAndScriptAsync( + public Task TestDocumentationComment5() + => TestInRegularAndScriptAsync( """ internal interface ILanguageServiceHost { @@ -1830,12 +1721,10 @@ internal struct AStruct private int x; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18234")] - public async Task TestDocumentationComment6() - { - await TestInRegularAndScriptAsync( + public Task TestDocumentationComment6() + => TestInRegularAndScriptAsync( """ internal interface ISomeInterface { @@ -1863,12 +1752,10 @@ internal struct AStruct private int x; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19235")] - public async Task TestWithDirectives1() - { - await TestInRegularAndScriptAsync( + public Task TestWithDirectives1() + => TestInRegularAndScriptAsync( """ class C { @@ -1898,12 +1785,10 @@ private int GetProp() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19235")] - public async Task TestWithDirectives2() - { - await TestInRegularAndScriptAsync( + public Task TestWithDirectives2() + => TestInRegularAndScriptAsync( """ class C { @@ -1931,13 +1816,11 @@ private int GetProp() => #endif } """, -options: PreferExpressionBodiedMethods); - } + options: PreferExpressionBodiedMethods); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19235")] - public async Task TestWithDirectives3() - { - await TestInRegularAndScriptAsync( + public Task TestWithDirectives3() + => TestInRegularAndScriptAsync( """ class C { @@ -1960,12 +1843,10 @@ private int GetProp() => #endif } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19235")] - public async Task TestWithDirectives4() - { - await TestInRegularAndScriptAsync( + public Task TestWithDirectives4() + => TestInRegularAndScriptAsync( """ class C { @@ -1988,13 +1869,11 @@ private int GetProp() => #endif } """, -options: PreferExpressionBodiedMethods); - } + options: PreferExpressionBodiedMethods); [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/440371")] - public async Task TestExplicitInterfaceImplementation() - { - await TestInRegularAndScriptAsync( + public Task TestExplicitInterfaceImplementation() + => TestInRegularAndScriptAsync( """ interface IGoo { @@ -2037,12 +1916,10 @@ void IGoo.SetGoo(int value) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38379")] - public async Task TestUnsafeExpressionBody() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafeExpressionBody() + => TestInRegularAndScriptAsync( """ class C { @@ -2058,12 +1935,10 @@ class C } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38379")] - public async Task TestUnsafeAutoProperty() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafeAutoProperty() + => TestInRegularAndScriptAsync( """ class C { @@ -2086,12 +1961,10 @@ public unsafe void SetPointer(void* value) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38379")] - public async Task TestUnsafeSafeType() - { - await TestInRegularAndScriptAsync( + public Task TestUnsafeSafeType() + => TestInRegularAndScriptAsync( """ class C { @@ -2114,12 +1987,10 @@ public unsafe void SetP(int value) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22760")] - public async Task QualifyFieldAccessWhenNecessary1() - { - await TestInRegularAndScriptAsync( + public Task QualifyFieldAccessWhenNecessary1() + => TestInRegularAndScriptAsync( """ class C { @@ -2147,12 +2018,10 @@ public C(int value) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22760")] - public async Task QualifyFieldAccessWhenNecessary2() - { - await TestInRegularAndScriptAsync( + public Task QualifyFieldAccessWhenNecessary2() + => TestInRegularAndScriptAsync( """ class C { @@ -2180,12 +2049,10 @@ public C(int value) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22760")] - public async Task QualifyFieldAccessWhenNecessary3() - { - await TestInRegularAndScriptAsync( + public Task QualifyFieldAccessWhenNecessary3() + => TestInRegularAndScriptAsync( """ class C { @@ -2213,12 +2080,10 @@ public static void Set(int value) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45171")] - public async Task TestReferenceInObjectInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestReferenceInObjectInitializer() + => TestInRegularAndScriptAsync( """ public class Tweet { @@ -2260,12 +2125,10 @@ void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45171")] - public async Task TestReferenceInImplicitObjectInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestReferenceInImplicitObjectInitializer() + => TestInRegularAndScriptAsync( """ public class Tweet { @@ -2307,12 +2170,10 @@ void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45171")] - public async Task TestReferenceInWithInitializer() - { - await TestInRegularAndScriptAsync( + public Task TestReferenceInWithInitializer() + => TestInRegularAndScriptAsync( """ public class Tweet { @@ -2354,12 +2215,10 @@ void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57376")] - public async Task TestInLinkedFile() - { - await TestInRegularAndScriptAsync( + public Task TestInLinkedFile() + => TestInRegularAndScriptAsync( """ @@ -2409,12 +2268,10 @@ void M() """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25367")] - public async Task TestAccessorAttributes1() - { - await TestInRegularAndScriptAsync( + public Task TestAccessorAttributes1() + => TestInRegularAndScriptAsync( """ using System; using System.Runtime.CompilerServices; @@ -2445,12 +2302,10 @@ private static int GetSomeValue() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25367")] - public async Task TestAccessorAttributes2() - { - await TestInRegularAndScriptAsync( + public Task TestAccessorAttributes2() + => TestInRegularAndScriptAsync( """ using System; using System.Runtime.CompilerServices; @@ -2488,12 +2343,10 @@ private static void SetSomeValue(int value) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75135")] - public async Task TestMatchInPropertyPattern() - { - await TestInRegularAndScriptAsync(""" + public Task TestMatchInPropertyPattern() + => TestInRegularAndScriptAsync(""" class C { public int [||]Property { get { return 0; } } @@ -2513,12 +2366,10 @@ public bool M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75999")] - public async Task TestInterfacePropertyWithImplementation() - { - await TestInRegularAndScriptAsync( + public Task TestInterfacePropertyWithImplementation() + => TestInRegularAndScriptAsync( """ interface I { @@ -2540,12 +2391,10 @@ public virtual string GetName() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75186")] - public async Task DoNotDuplicatePreprocessorDirective1() - { - await TestInRegularAndScriptAsync(""" + public Task DoNotDuplicatePreprocessorDirective1() + => TestInRegularAndScriptAsync(""" class A { #region @@ -2565,12 +2414,10 @@ private static bool GetB() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75186")] - public async Task DoNotDuplicatePreprocessorDirective2() - { - await TestInRegularAndScriptAsync(""" + public Task DoNotDuplicatePreprocessorDirective2() + => TestInRegularAndScriptAsync(""" class A { #region @@ -2591,12 +2438,10 @@ private static void SetB(bool value) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75186")] - public async Task DoNotDuplicatePreprocessorDirective3() - { - await TestInRegularAndScriptAsync(""" + public Task DoNotDuplicatePreprocessorDirective3() + => TestInRegularAndScriptAsync(""" class A { #region @@ -2617,12 +2462,10 @@ private static bool GetB() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75186")] - public async Task DoNotDuplicatePreprocessorDirective4() - { - await TestInRegularAndScriptAsync(""" + public Task DoNotDuplicatePreprocessorDirective4() + => TestInRegularAndScriptAsync(""" class A { #region @@ -2648,5 +2491,4 @@ private static void SetB(bool value) } } """); - } } diff --git a/src/Features/CSharpTest/ReverseForStatement/ReverseForStatementTests.cs b/src/Features/CSharpTest/ReverseForStatement/ReverseForStatementTests.cs index 31af789befeb6..77823e5a2fbdb 100644 --- a/src/Features/CSharpTest/ReverseForStatement/ReverseForStatementTests.cs +++ b/src/Features/CSharpTest/ReverseForStatement/ReverseForStatementTests.cs @@ -20,9 +20,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor => new CSharpReverseForStatementCodeRefactoringProvider(); [Fact] - public async Task TestMissingWithoutInitializer() - { - await TestMissingAsync( + public Task TestMissingWithoutInitializer() + => TestMissingAsync( """ class C { @@ -34,12 +33,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestMissingWithoutCondition() - { - await TestMissingAsync( + public Task TestMissingWithoutCondition() + => TestMissingAsync( """ class C { @@ -51,12 +48,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestMissingWithoutIncrementor() - { - await TestMissingAsync( + public Task TestMissingWithoutIncrementor() + => TestMissingAsync( """ class C { @@ -68,12 +63,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestMissingWithoutVariableReferencedInCondition() - { - await TestMissingAsync( + public Task TestMissingWithoutVariableReferencedInCondition() + => TestMissingAsync( """ class C { @@ -85,12 +78,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestMissingWithoutVariableReferencedInIncrementor() - { - await TestMissingAsync( + public Task TestMissingWithoutVariableReferencedInIncrementor() + => TestMissingAsync( """ class C { @@ -102,12 +93,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestMissingWithoutVariableInitializer() - { - await TestMissingAsync( + public Task TestMissingWithoutVariableInitializer() + => TestMissingAsync( """ class C { @@ -119,12 +108,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestMissingWithMismatchedConditionAndIncrementor1() - { - await TestMissingAsync( + public Task TestMissingWithMismatchedConditionAndIncrementor1() + => TestMissingAsync( """ class C { @@ -136,12 +123,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestMissingWithMismatchedConditionAndIncrementor2() - { - await TestMissingAsync( + public Task TestMissingWithMismatchedConditionAndIncrementor2() + => TestMissingAsync( """ class C { @@ -153,12 +138,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestPostIncrement1() - { - await TestInRegularAndScriptAsync( + public Task TestPostIncrement1() + => TestInRegularAndScriptAsync( """ class C { @@ -181,12 +164,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestPostIncrementConstants1() - { - await TestInRegularAndScriptAsync( + public Task TestPostIncrementConstants1() + => TestInRegularAndScriptAsync( """ class C { @@ -209,12 +190,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestPostDecrementConstants1() - { - await TestInRegularAndScriptAsync( + public Task TestPostDecrementConstants1() + => TestInRegularAndScriptAsync( """ class C { @@ -237,12 +216,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestIncrementPreIncrement() - { - await TestInRegularAndScriptAsync( + public Task TestIncrementPreIncrement() + => TestInRegularAndScriptAsync( """ class C { @@ -265,12 +242,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestIncrementAddAssignment() - { - await TestInRegularAndScriptAsync( + public Task TestIncrementAddAssignment() + => TestInRegularAndScriptAsync( """ class C { @@ -293,12 +268,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestMissingWithNonOneIncrementValue() - { - await TestMissingAsync( + public Task TestMissingWithNonOneIncrementValue() + => TestMissingAsync( """ class C { @@ -310,12 +283,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestPostDecrement() - { - await TestInRegularAndScriptAsync( + public Task TestPostDecrement() + => TestInRegularAndScriptAsync( """ class C { @@ -338,12 +309,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestPostIncrementEquals1() - { - await TestInRegularAndScriptAsync( + public Task TestPostIncrementEquals1() + => TestInRegularAndScriptAsync( """ class C { @@ -366,12 +335,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestPostDecrementEquals() - { - await TestInRegularAndScriptAsync( + public Task TestPostDecrementEquals() + => TestInRegularAndScriptAsync( """ class C { @@ -394,12 +361,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestTrivia1() - { - await TestInRegularAndScriptAsync( + public Task TestTrivia1() + => TestInRegularAndScriptAsync( """ class C { @@ -422,12 +387,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestPostIncrementSwappedConditions() - { - await TestInRegularAndScriptAsync( + public Task TestPostIncrementSwappedConditions() + => TestInRegularAndScriptAsync( """ class C { @@ -450,12 +413,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestPostIncrementEqualsSwappedConditions() - { - await TestInRegularAndScriptAsync( + public Task TestPostIncrementEqualsSwappedConditions() + => TestInRegularAndScriptAsync( """ class C { @@ -478,12 +439,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestByteOneMin() - { - await TestInRegularAndScript1Async( + public Task TestByteOneMin() + => TestInRegularAndScript1Async( """ class C { @@ -506,12 +465,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestUInt16OneMin() - { - await TestInRegularAndScript1Async( + public Task TestUInt16OneMin() + => TestInRegularAndScript1Async( """ class C { @@ -534,12 +491,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestUInt32OneMin() - { - await TestInRegularAndScript1Async( + public Task TestUInt32OneMin() + => TestInRegularAndScript1Async( """ class C { @@ -562,12 +517,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestUInt64OneMin() - { - await TestInRegularAndScript1Async( + public Task TestUInt64OneMin() + => TestInRegularAndScript1Async( """ class C { @@ -590,12 +543,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestByteZeroMin() - { - await TestMissingAsync( + public Task TestByteZeroMin() + => TestMissingAsync( """ class C { @@ -607,12 +558,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestUInt16ZeroMin() - { - await TestMissingAsync( + public Task TestUInt16ZeroMin() + => TestMissingAsync( """ class C { @@ -624,12 +573,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestUInt32ZeroMin() - { - await TestMissingAsync( + public Task TestUInt32ZeroMin() + => TestMissingAsync( """ class C { @@ -641,12 +588,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestUInt64ZeroMin() - { - await TestMissingAsync( + public Task TestUInt64ZeroMin() + => TestMissingAsync( """ class C { @@ -658,12 +603,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestByteMax() - { - await TestMissingAsync( + public Task TestByteMax() + => TestMissingAsync( """ class C { @@ -675,12 +618,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestUInt16Max() - { - await TestMissingAsync( + public Task TestUInt16Max() + => TestMissingAsync( """ class C { @@ -692,12 +633,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestUInt32Max() - { - await TestMissingAsync( + public Task TestUInt32Max() + => TestMissingAsync( """ class C { @@ -709,12 +648,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestUInt64Max() - { - await TestMissingAsync( + public Task TestUInt64Max() + => TestMissingAsync( """ class C { @@ -726,12 +663,10 @@ void M(string[] args) } } """); - } [Fact] - public async Task TestByteZeroMinReverse() - { - await TestMissingAsync( + public Task TestByteZeroMinReverse() + => TestMissingAsync( """ class C { @@ -743,5 +678,4 @@ void M(string[] args) } } """); - } } diff --git a/src/Features/CSharpTest/SemanticSearch/CSharpSemanticSearchServiceTests.cs b/src/Features/CSharpTest/SemanticSearch/CSharpSemanticSearchServiceTests.cs index 9747ebb970aa4..cb02a1c94f0ed 100644 --- a/src/Features/CSharpTest/SemanticSearch/CSharpSemanticSearchServiceTests.cs +++ b/src/Features/CSharpTest/SemanticSearch/CSharpSemanticSearchServiceTests.cs @@ -90,60 +90,48 @@ private static async Task VerifyCompileAndExecuteQueryAsync( public async Task CompilationQuery() { using var workspace = TestWorkspace.Create(DefaultWorkspaceXml, composition: FeaturesTestCompositions.Features); - - var query = """ + await VerifyCompileAndExecuteQueryAsync(workspace, """ static IEnumerable Find(Compilation compilation) { return compilation.GlobalNamespace.GetMembers("N"); } - """; - - await VerifyCompileAndExecuteQueryAsync(workspace, query, ["namespace N"]); + """, ["namespace N"]); } [ConditionalFact(typeof(CoreClrOnly))] public async Task NamespaceQuery() { using var workspace = TestWorkspace.Create(DefaultWorkspaceXml, composition: FeaturesTestCompositions.Features); - - var query = """ + await VerifyCompileAndExecuteQueryAsync(workspace, """ static IEnumerable Find(INamespaceSymbol n) { return n.GetMembers("C"); } - """; - - await VerifyCompileAndExecuteQueryAsync(workspace, query, ["class C"]); + """, ["class C"]); } [ConditionalFact(typeof(CoreClrOnly))] public async Task NamedTypeQuery() { using var workspace = TestWorkspace.Create(DefaultWorkspaceXml, composition: FeaturesTestCompositions.Features); - - var query = """ + await VerifyCompileAndExecuteQueryAsync(workspace, """ static IEnumerable Find(INamedTypeSymbol type) { return type.GetMembers("F"); } - """; - - await VerifyCompileAndExecuteQueryAsync(workspace, query, ["int C.F"]); + """, ["int C.F"]); } [ConditionalFact(typeof(CoreClrOnly))] public async Task MethodQuery() { using var workspace = TestWorkspace.Create(DefaultWorkspaceXml, composition: FeaturesTestCompositions.Features); - - var query = """ + await VerifyCompileAndExecuteQueryAsync(workspace, """ static IEnumerable Find(IMethodSymbol method) { return [method]; } - """; - - await VerifyCompileAndExecuteQueryAsync(workspace, query, + """, [ "C.C()", "int C.P.get", @@ -157,15 +145,12 @@ await VerifyCompileAndExecuteQueryAsync(workspace, query, public async Task FieldQuery() { using var workspace = TestWorkspace.Create(DefaultWorkspaceXml, composition: FeaturesTestCompositions.Features); - - var query = """ + await VerifyCompileAndExecuteQueryAsync(workspace, """ static IEnumerable Find(IFieldSymbol field) { return [field]; } - """; - - await VerifyCompileAndExecuteQueryAsync(workspace, query, + """, [ "int C.F", "readonly int C.P.field", @@ -176,15 +161,12 @@ await VerifyCompileAndExecuteQueryAsync(workspace, query, public async Task PropertyQuery() { using var workspace = TestWorkspace.Create(DefaultWorkspaceXml, composition: FeaturesTestCompositions.Features); - - var query = """ + await VerifyCompileAndExecuteQueryAsync(workspace, """ static IEnumerable Find(IPropertySymbol prop) { return [prop]; } - """; - - await VerifyCompileAndExecuteQueryAsync(workspace, query, + """, [ "int C.P { get; }" ]); @@ -194,15 +176,12 @@ await VerifyCompileAndExecuteQueryAsync(workspace, query, public async Task EventQuery() { using var workspace = TestWorkspace.Create(DefaultWorkspaceXml, composition: FeaturesTestCompositions.Features); - - var query = """ + await VerifyCompileAndExecuteQueryAsync(workspace, """ static IEnumerable Find(IEventSymbol e) { return [e]; } - """; - - await VerifyCompileAndExecuteQueryAsync(workspace, query, + """, [ "event Action C.E" ]); @@ -231,8 +210,7 @@ class D """, composition: FeaturesTestCompositions.Features); - - var query = """ + await VerifyCompileAndExecuteQueryAsync(workspace, """ static async IAsyncEnumerable Find(IMethodSymbol e) { if (e.Name != "F") @@ -246,9 +224,7 @@ static async IAsyncEnumerable Find(IMethodSymbol e) yield return model.GetEnclosingSymbol(node.SpanStart); } } - """; - - await VerifyCompileAndExecuteQueryAsync(workspace, query, + """, [ "void D.R1()", "void D.R2()" @@ -259,15 +235,12 @@ await VerifyCompileAndExecuteQueryAsync(workspace, query, public async Task NullReturn() { using var workspace = TestWorkspace.Create(DefaultWorkspaceXml, composition: FeaturesTestCompositions.Features); - - var query = """ + await VerifyCompileAndExecuteQueryAsync(workspace, """ static IEnumerable Find(Compilation compilation) { return null; } - """; - - await VerifyCompileAndExecuteQueryAsync(workspace, query, expectedItems: []); + """, expectedItems: []); } [ConditionalFact(typeof(CoreClrOnly))] diff --git a/src/Features/CSharpTest/SimplifyPropertyPattern/SimplifyPropertyPatternTests.cs b/src/Features/CSharpTest/SimplifyPropertyPattern/SimplifyPropertyPatternTests.cs index 820c0734f1818..ab1769f2475fe 100644 --- a/src/Features/CSharpTest/SimplifyPropertyPattern/SimplifyPropertyPatternTests.cs +++ b/src/Features/CSharpTest/SimplifyPropertyPattern/SimplifyPropertyPatternTests.cs @@ -21,9 +21,10 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SimplifyPropertyPattern public sealed class SimplifyPropertyPatternTests { [Fact] - public async Task NotInCSharp9() - { - var code = """ + public Task NotInCSharp9() + => new VerifyCS.Test + { + TestCode = """ using System; using System.Reflection; @@ -37,19 +38,13 @@ void S(Type t) } } } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); - } [Fact] - public async Task InCSharp10() - { - await new VerifyCS.Test + public Task InCSharp10() + => new VerifyCS.Test { TestCode = """ using System; @@ -83,12 +78,12 @@ void S(Type t) """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task TestNotWithoutPropertyPattern1() - { - var testCode = """ + public Task TestNotWithoutPropertyPattern1() + => new VerifyCS.Test + { + TestCode = """ using System; using System.Reflection; @@ -102,19 +97,15 @@ void S(Type t) } } } - """; - - await new VerifyCS.Test - { - TestCode = testCode, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task TestNotWithoutPropertyPattern2() - { - var testCode = """ + public Task TestNotWithoutPropertyPattern2() + => new VerifyCS.Test + { + TestCode = """ using System; using System.Reflection; @@ -128,18 +119,15 @@ void S(Type t) } } } - """; - await new VerifyCS.Test - { - TestCode = testCode, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task TestNotWithTypePatterm() - { - var testCode = """ + public Task TestNotWithTypePatterm() + => new VerifyCS.Test + { + TestCode = """ using System; using System.Reflection; @@ -153,18 +141,15 @@ void S(Type t) } } } - """; - await new VerifyCS.Test - { - TestCode = testCode, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task TestNotWithOuterDesignation() - { - var testCode = """ + public Task TestNotWithOuterDesignation() + => new VerifyCS.Test + { + TestCode = """ using System; using System.Reflection; @@ -178,18 +163,15 @@ void S(Type t) } } } - """; - await new VerifyCS.Test - { - TestCode = testCode, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task TestNotWithoutInnerSubpatterns() - { - var testCode = """ + public Task TestNotWithoutInnerSubpatterns() + => new VerifyCS.Test + { + TestCode = """ using System; using System.Reflection; @@ -203,18 +185,15 @@ void S(Type t) } } } - """; - await new VerifyCS.Test - { - TestCode = testCode, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task TestNotWithMultipleInnerSubpatterns() - { - var testCode = """ + public Task TestNotWithMultipleInnerSubpatterns() + => new VerifyCS.Test + { + TestCode = """ using System; using System.Reflection; @@ -228,18 +207,13 @@ void S(Type t) } } } - """; - await new VerifyCS.Test - { - TestCode = testCode, + """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task TestWithInnerDesignation() - { - await new VerifyCS.Test + public Task TestWithInnerDesignation() + => new VerifyCS.Test { TestCode = """ using System; @@ -273,12 +247,10 @@ void S(Type t) """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task Test_Permutation1() - { - await new VerifyCS.Test + public Task Test_Permutation1() + => new VerifyCS.Test { TestCode = """ using System; @@ -310,12 +282,10 @@ void S(Type t) """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task Test_Permutation2() - { - await new VerifyCS.Test + public Task Test_Permutation2() + => new VerifyCS.Test { TestCode = """ using System; @@ -347,12 +317,10 @@ void S(Type t) """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task Test_Permutation3() - { - await new VerifyCS.Test + public Task Test_Permutation3() + => new VerifyCS.Test { TestCode = """ using System; @@ -384,12 +352,10 @@ void S(Type t) """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task Test_Permutation4() - { - await new VerifyCS.Test + public Task Test_Permutation4() + => new VerifyCS.Test { TestCode = """ using System; @@ -421,12 +387,10 @@ void S(Type t) """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task Test_Permutation5() - { - await new VerifyCS.Test + public Task Test_Permutation5() + => new VerifyCS.Test { TestCode = """ using System; @@ -458,12 +422,10 @@ void S(Type t) """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task Test_Permutation6() - { - await new VerifyCS.Test + public Task Test_Permutation6() + => new VerifyCS.Test { TestCode = """ using System; @@ -495,12 +457,10 @@ void S(Type t) """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task Test_Permutation7() - { - await new VerifyCS.Test + public Task Test_Permutation7() + => new VerifyCS.Test { TestCode = """ using System; @@ -532,12 +492,10 @@ void S(Type t) """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task TestMultiLine1() - { - await new VerifyCS.Test + public Task TestMultiLine1() + => new VerifyCS.Test { TestCode = """ using System; @@ -582,12 +540,10 @@ void S(Type t) """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task TestFixAll1() - { - await new VerifyCS.Test + public Task TestFixAll1() + => new VerifyCS.Test { TestCode = """ using System; @@ -631,12 +587,10 @@ void S(Type t) """, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); - } [Fact] - public async Task TestOuterDiagnostic() - { - await new VerifyCS.Test + public Task TestOuterDiagnostic() + => new VerifyCS.Test { TestCode = """ using System; @@ -672,12 +626,10 @@ void S(Type t) CodeFixTestBehaviors = Testing.CodeFixTestBehaviors.FixOne, DiagnosticSelector = ds => ds[0], }.RunAsync(); - } [Fact] - public async Task TestInnerDiagnostic() - { - await new VerifyCS.Test + public Task TestInnerDiagnostic() + => new VerifyCS.Test { TestCode = """ using System; @@ -724,12 +676,12 @@ void S(Type t) CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne | CodeFixTestBehaviors.SkipFixAllCheck, DiagnosticSelector = ds => ds[1], }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57674")] - public async Task TestTuplePattern() - { - var testCode = """ + public Task TestTuplePattern() + => new VerifyCS.Test + { + TestCode = """ record R(int Prop); class C @@ -739,19 +691,16 @@ void S(R r) _ = (A: r, r) is (A: { Prop: { } }, _); } } - """; - await new VerifyCS.Test - { - TestCode = testCode, + """, LanguageVersion = LanguageVersion.CSharp10, ReferenceAssemblies = ReferenceAssemblies.Net.Net50, }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57674")] - public async Task TestPositionalPattern() - { - var testCode = """ + public Task TestPositionalPattern() + => new VerifyCS.Test + { + TestCode = """ record R(R Child, int Value); class C @@ -761,12 +710,8 @@ void S(R r) _ = r is R(Child: { Child: { } }, _); } } - """; - await new VerifyCS.Test - { - TestCode = testCode, + """, LanguageVersion = LanguageVersion.CSharp10, ReferenceAssemblies = ReferenceAssemblies.Net.Net50, }.RunAsync(); - } } diff --git a/src/Features/CSharpTest/SimplifyThisOrMe/SimplifyThisOrMeTests.cs b/src/Features/CSharpTest/SimplifyThisOrMe/SimplifyThisOrMeTests.cs index 45166a030f3bf..661e5b1e301bd 100644 --- a/src/Features/CSharpTest/SimplifyThisOrMe/SimplifyThisOrMeTests.cs +++ b/src/Features/CSharpTest/SimplifyThisOrMe/SimplifyThisOrMeTests.cs @@ -29,9 +29,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider => (new CSharpSimplifyThisOrMeDiagnosticAnalyzer(), new CSharpSimplifyThisOrMeCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] - public async Task TestSimplifyDiagnosticId() - { - await TestInRegularAndScriptAsync( + public Task TestSimplifyDiagnosticId() + => TestInRegularAndScriptAsync( """ using System; @@ -56,13 +55,11 @@ public void z() } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] [WorkItem("https://github.com/dotnet/roslyn/issues/6682")] - public async Task TestThisWithNoType() - { - await TestInRegularAndScriptAsync( + public Task TestThisWithNoType() + => TestInRegularAndScriptAsync( """ class Program { @@ -85,12 +82,10 @@ static void Main(string[] args) } } """); - } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] - public async Task TestAppropriateDiagnosticOnMissingQualifier() - { - await TestDiagnosticInfoAsync( + public Task TestAppropriateDiagnosticOnMissingQualifier() + => TestDiagnosticInfoAsync( """ class C { @@ -105,14 +100,12 @@ void M() options: Option(CodeStyleOptions2.QualifyPropertyAccess, false, NotificationOption2.Warning), diagnosticId: IDEDiagnosticIds.RemoveThisOrMeQualificationDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Warning); - } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInSolution_RemoveThis() - { - var input = """ + public Task TestFixAllInSolution_RemoveThis() + => TestInRegularAndScriptAsync(""" @@ -233,9 +226,7 @@ private System.Int32 F(System.Int32 p1, System.Int16 p2) - """; - - var expected = """ + """, """ @@ -356,17 +347,22 @@ private System.Int32 F(System.Int32 p1, System.Int16 p2) - """; - - await TestInRegularAndScriptAsync(input, expected); - } + """); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution_RemoveMemberAccessQualification() { - var input = """ + var options = + new OptionsCollection(GetLanguage()) + { + { CodeStyleOptions2.QualifyPropertyAccess, false, NotificationOption2.Suggestion }, + { CodeStyleOptions2.QualifyFieldAccess, true, NotificationOption2.Suggestion }, + }; + + await TestInRegularAndScriptAsync( + initialMarkup: """ @@ -401,9 +397,8 @@ void N() - """; - - var expected = """ + """, + expectedMarkup: """ @@ -438,18 +433,7 @@ void N() - """; - - var options = - new OptionsCollection(GetLanguage()) - { - { CodeStyleOptions2.QualifyPropertyAccess, false, NotificationOption2.Suggestion }, - { CodeStyleOptions2.QualifyFieldAccess, true, NotificationOption2.Suggestion }, - }; - - await TestInRegularAndScriptAsync( - initialMarkup: input, - expectedMarkup: expected, + """, options: options); } } diff --git a/src/Features/CSharpTest/SimplifyTypeNames/SimplifyTypeNamesTests.cs b/src/Features/CSharpTest/SimplifyTypeNames/SimplifyTypeNamesTests.cs index d989652ea0ebd..a048f755257c4 100644 --- a/src/Features/CSharpTest/SimplifyTypeNames/SimplifyTypeNamesTests.cs +++ b/src/Features/CSharpTest/SimplifyTypeNames/SimplifyTypeNamesTests.cs @@ -27,9 +27,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider => (new CSharpSimplifyTypeNamesDiagnosticAnalyzer(), new SimplifyTypeNamesCodeFixProvider()); [Fact] - public async Task SimplifyGenericName() - { - await TestInRegularAndScriptAsync( + public Task SimplifyGenericName() + => TestInRegularAndScriptAsync( """ using System; @@ -62,12 +61,10 @@ static void M() } } """); - } [Fact] - public async Task UseAlias0() - { - await TestWithPredefinedTypeOptionsAsync( + public Task UseAlias0() + => TestWithPredefinedTypeOptionsAsync( """ using Goo = System; @@ -98,12 +95,10 @@ class B } } """); - } [Fact] - public async Task UseAlias00() - { - await TestInRegularAndScriptAsync( + public Task UseAlias00() + => TestInRegularAndScriptAsync( """ namespace Root { @@ -126,12 +121,10 @@ class A } } """); - } [Fact] - public async Task UseGlobalAlias00() - { - await TestInRegularAndScriptAsync( + public Task UseGlobalAlias00() + => TestInRegularAndScriptAsync( """ global using MyType = System.IO.File; @@ -154,12 +147,10 @@ class A } } """); - } [Fact] - public async Task UseGlobalAlias01() - { - await TestInRegularAndScriptAsync( + public Task UseGlobalAlias01() + => TestInRegularAndScriptAsync( """ @@ -187,12 +178,10 @@ class A } } """); - } [Fact] - public async Task UseAlias00_FileScopedNamespace() - { - await TestInRegularAndScriptAsync( + public Task UseAlias00_FileScopedNamespace() + => TestInRegularAndScriptAsync( """ namespace Root; @@ -213,7 +202,6 @@ class A MyType c; } """); - } [Fact] public async Task UseAlias() @@ -251,9 +239,8 @@ class A } [Fact] - public async Task UseAlias1() - { - await TestInRegularAndScriptAsync( + public Task UseAlias1() + => TestInRegularAndScriptAsync( """ namespace Root { @@ -276,12 +263,10 @@ class A } } """); - } [Fact] - public async Task UseAlias2() - { - await TestInRegularAndScriptAsync( + public Task UseAlias2() + => TestInRegularAndScriptAsync( """ using MyType = System.Exception; @@ -304,12 +289,10 @@ class A } } """); - } [Fact] - public async Task UseAlias3() - { - await TestInRegularAndScriptAsync( + public Task UseAlias3() + => TestInRegularAndScriptAsync( """ using MyType = System.Exception; @@ -338,12 +321,10 @@ class A } } """); - } [Fact] - public async Task UseAlias4() - { - await TestInRegularAndScriptAsync( + public Task UseAlias4() + => TestInRegularAndScriptAsync( """ using MyType = System.Exception; @@ -360,12 +341,10 @@ class A MyType c; } """); - } [Fact] - public async Task UseAlias5() - { - await TestInRegularAndScriptAsync( + public Task UseAlias5() + => TestInRegularAndScriptAsync( """ namespace Root { @@ -388,12 +367,10 @@ class A } } """); - } [Fact] - public async Task UseAlias6() - { - await TestInRegularAndScriptAsync( + public Task UseAlias6() + => TestInRegularAndScriptAsync( """ using MyType = System.Exception; @@ -416,12 +393,10 @@ class A } } """); - } [Fact] - public async Task UseAlias7() - { - await TestInRegularAndScriptAsync( + public Task UseAlias7() + => TestInRegularAndScriptAsync( """ using MyType = System.Exception; @@ -450,12 +425,10 @@ class A } } """); - } [Fact] - public async Task UseAlias8() - { - await TestInRegularAndScriptAsync( + public Task UseAlias8() + => TestInRegularAndScriptAsync( """ using Goo = System.Int32; @@ -484,12 +457,10 @@ class A } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21449")] - public async Task DoNotChangeToAliasInNameOfIfItChangesNameOfName() - { - await TestInRegularAndScript1Async( + public Task DoNotChangeToAliasInNameOfIfItChangesNameOfName() + => TestInRegularAndScript1Async( """ using System; using Foo = SimplifyInsideNameof.Program; @@ -520,13 +491,11 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21449")] [WorkItem("https://github.com/dotnet/roslyn/issues/40972")] - public async Task DoChangeToAliasInNameOfIfItDoesNotAffectName1() - { - await TestInRegularAndScriptAsync( + public Task DoChangeToAliasInNameOfIfItDoesNotAffectName1() + => TestInRegularAndScriptAsync( """ using System; using Goo = SimplifyInsideNameof.Program; @@ -557,12 +526,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21449")] - public async Task DoChangeToAliasInNameOfIfItDoesNotAffectName2() - { - await TestInRegularAndScriptAsync( + public Task DoChangeToAliasInNameOfIfItDoesNotAffectName2() + => TestInRegularAndScriptAsync( """ using System; using Goo = N.Goo; @@ -601,12 +568,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TwoAliases() - { - await TestInRegularAndScriptAsync( + public Task TwoAliases() + => TestInRegularAndScriptAsync( """ using MyType1 = System.Exception; @@ -633,12 +598,10 @@ class A } } """); - } [Fact] - public async Task TwoAliases2() - { - await TestInRegularAndScriptAsync( + public Task TwoAliases2() + => TestInRegularAndScriptAsync( """ using MyType1 = System.Exception; @@ -665,12 +628,10 @@ class A } } """); - } [Fact] - public async Task TwoAliasesConflict() - { - await TestMissingInRegularAndScriptAsync( + public Task TwoAliasesConflict() + => TestMissingInRegularAndScriptAsync( """ using MyType = System.Exception; @@ -684,12 +645,10 @@ class A } } """); - } [Fact] - public async Task DoNotChangeToAliasIfConflict1() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotChangeToAliasIfConflict1() + => TestMissingInRegularAndScriptAsync( """ using MyType = System.ConsoleColor; @@ -706,12 +665,10 @@ void M() } } """); - } [Fact] - public async Task DoNotChangeToAliasIfConflict2() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotChangeToAliasIfConflict2() + => TestMissingInRegularAndScriptAsync( """ using MyType = System.ConsoleColor; @@ -728,12 +685,10 @@ void M() } } """); - } [Fact] - public async Task DoChangeToAliasIfTypesMatch1() - { - await TestInRegularAndScriptAsync( + public Task DoChangeToAliasIfTypesMatch1() + => TestInRegularAndScriptAsync( """ using MyType = System.ConsoleColor; @@ -766,12 +721,10 @@ void M() } } """); - } [Fact] - public async Task DoChangeToAliasIfTypesMatch2() - { - await TestInRegularAndScriptAsync( + public Task DoChangeToAliasIfTypesMatch2() + => TestInRegularAndScriptAsync( """ using MyType = System.ConsoleColor; @@ -804,12 +757,10 @@ void M() } } """); - } [Fact] - public async Task DoChangeToAliasIfTypesMatch3() - { - await TestInRegularAndScriptAsync( + public Task DoChangeToAliasIfTypesMatch3() + => TestInRegularAndScriptAsync( """ using MyType = System.ConsoleColor; @@ -838,12 +789,10 @@ void M(System.ConsoleColor MyType) } } """); - } [Fact] - public async Task DoNotChangeToNamespaceAliasIfConflict() - { - await TestInRegularAndScriptAsync( + public Task DoNotChangeToNamespaceAliasIfConflict() + => TestInRegularAndScriptAsync( """ using MyType = Root.Inner.Inner2; @@ -902,12 +851,10 @@ void M() } } """); - } [Fact] - public async Task DoChangeToNamespaceAliasIfNoConflict() - { - await TestInRegularAndScriptAsync( + public Task DoChangeToNamespaceAliasIfNoConflict() + => TestInRegularAndScriptAsync( """ using MyType = Root.Inner.Inner2; @@ -962,12 +909,10 @@ void M() } } """); - } [Fact] - public async Task DoChangeToAliasIfConflictIsntType() - { - await TestInRegularAndScriptAsync( + public Task DoChangeToAliasIfConflictIsntType() + => TestInRegularAndScriptAsync( """ using MyType = System.ConsoleColor; @@ -994,12 +939,10 @@ class A } } """); - } [Fact] - public async Task TwoMissingOnAmbiguousCref1() - { - await TestMissingInRegularAndScriptAsync( + public Task TwoMissingOnAmbiguousCref1() + => TestMissingInRegularAndScriptAsync( """ class Example { @@ -1014,12 +957,10 @@ void Method() public string ToString(string format, IFormatProvider formatProvider) => throw null; } """); - } [Fact] - public async Task TwoMissingOnAmbiguousCref2() - { - await TestMissingInRegularAndScriptAsync( + public Task TwoMissingOnAmbiguousCref2() + => TestMissingInRegularAndScriptAsync( """ class Example { @@ -1034,12 +975,10 @@ void Method() public string ToString(string format, IFormatProvider formatProvider) => throw null; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40972")] - public async Task TwoMissingInNameofMemberGroup() - { - await TestInRegularAndScript1Async( + public Task TwoMissingInNameofMemberGroup() + => TestInRegularAndScript1Async( """ class Example { @@ -1064,12 +1003,10 @@ public static void Goo() { } public static void Goo(int i) { } } """); - } [Fact] - public async Task TwoAliasesConflict2() - { - await TestInRegularAndScriptAsync( + public Task TwoAliasesConflict2() + => TestInRegularAndScriptAsync( """ using MyType = System.Exception; @@ -1096,13 +1033,10 @@ class A } } """); - } [Fact] - public async Task AliasInSiblingNamespace() - { - var content = - """ + public Task AliasInSiblingNamespace() + => TestMissingInRegularAndScriptAsync(""" [|namespace Root { namespace Sibling @@ -1115,9 +1049,7 @@ class A System.Exception c; } }|] - """; - await TestMissingInRegularAndScriptAsync(content); - } + """); [Fact] public async Task KeywordInt32() @@ -1186,10 +1118,8 @@ class A } [Fact] - public async Task SimplifyTypeName() - { - var content = - """ + public Task SimplifyTypeName() + => TestMissingInRegularAndScriptAsync(""" namespace Root { class A @@ -1197,9 +1127,7 @@ class A [|System.Exception|] c; } } - """; - await TestMissingInRegularAndScriptAsync(content); - } + """); [Fact] public async Task SimplifyTypeName1() @@ -1285,9 +1213,8 @@ class A } [Fact] - public async Task SimplifyTypeName2() - { - await TestInRegularAndScriptAsync( + public Task SimplifyTypeName2() + => TestInRegularAndScriptAsync( """ namespace System { @@ -1306,12 +1233,10 @@ class A } } """); - } [Fact] - public async Task SimplifyTypeName3() - { - await TestInRegularAndScriptAsync( + public Task SimplifyTypeName3() + => TestInRegularAndScriptAsync( """ namespace N1 { @@ -1344,13 +1269,10 @@ public class A2 } } """); - } [Fact] - public async Task SimplifyTypeName4() - { - // this is failing since we can't speculatively bind namespace yet - await TestInRegularAndScriptAsync( + public Task SimplifyTypeName4() + => TestInRegularAndScriptAsync( """ namespace N1 { @@ -1383,12 +1305,10 @@ public class A2 } } """); - } [Fact] - public async Task SimplifyTypeName5() - { - await TestInRegularAndScriptAsync( + public Task SimplifyTypeName5() + => TestInRegularAndScriptAsync( """ namespace N1 { @@ -1421,13 +1341,10 @@ public class A2 } } """); - } [Fact] - public async Task SimplifyTypeName6() - { - var content = - """ + public Task SimplifyTypeName6() + => TestMissingInRegularAndScriptAsync(""" namespace N1 { public class A1 { } @@ -1442,9 +1359,7 @@ public class A2 } } } - """; - await TestMissingInRegularAndScriptAsync(content); - } + """); [Fact] public async Task SimplifyTypeName7() @@ -1485,10 +1400,8 @@ public class A1 { } } [Fact] - public async Task SimplifyGenericTypeName1() - { - var content = - """ + public Task SimplifyGenericTypeName1() + => TestMissingInRegularAndScriptAsync(""" namespace N1 { public class A1 @@ -1496,9 +1409,7 @@ public class A1 [|System.EventHandler|] a; } } - """; - await TestMissingInRegularAndScriptAsync(content); - } + """); [Fact] public async Task SimplifyGenericTypeName2() @@ -1534,9 +1445,8 @@ public class A1 [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9877")] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task SimplifyGenericTypeName3() - { - await TestInRegularAndScriptAsync( + public Task SimplifyGenericTypeName3() + => TestInRegularAndScriptAsync( """ using System; @@ -1559,13 +1469,10 @@ public class A1 } } """); - } [Fact] - public async Task SimplifyGenericTypeName4() - { - var content = - """ + public Task SimplifyGenericTypeName4() + => TestMissingInRegularAndScriptAsync(""" using MyHandler = System.EventHandler; namespace N1 @@ -1575,9 +1482,7 @@ public class A1 [|System.EventHandler>|] a; } } - """; - await TestMissingInRegularAndScriptAsync(content); - } + """); [Fact] public async Task SimplifyGenericTypeName5() @@ -1623,9 +1528,8 @@ public class A1 } [Fact] - public async Task SimplifyGenericTypeName6() - { - await TestInRegularAndScriptAsync( + public Task SimplifyGenericTypeName6() + => TestInRegularAndScriptAsync( """ using System; @@ -1666,13 +1570,11 @@ class Test } } """); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9877")] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task SimplifyGenericTypeName7() - { - await TestInRegularAndScriptAsync( + public Task SimplifyGenericTypeName7() + => TestInRegularAndScriptAsync( """ using System; @@ -1713,12 +1615,10 @@ class Test } } """); - } [Fact] - public async Task Array1() - { - await TestWithPredefinedTypeOptionsAsync( + public Task Array1() + => TestWithPredefinedTypeOptionsAsync( """ using System.Collections.Generic; @@ -1742,33 +1642,9 @@ class Test } """); - // TODO: The below test is currently disabled due to restrictions of the test framework, this needs to be fixed. - - //// Test( - //// @"using System.Collections.Generic; - - ////namespace N1 - ////{ - //// class Test - //// { - //// System.Collections.Generic.List<[|System.String|][]> a; - //// } - ////}", @" - ////using System.Collections.Generic; - - ////namespace N1 - ////{ - //// class Test - //// { - //// System.Collections.Generic.List a; - //// } - ////}"); - } - [Fact] - public async Task Array2() - { - await TestWithPredefinedTypeOptionsAsync( + public Task Array2() + => TestWithPredefinedTypeOptionsAsync( """ using System.Collections.Generic; @@ -1791,12 +1667,10 @@ class Test } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995168"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073099")] - public async Task SimplifyToPredefinedTypeNameShouldNotBeOfferedInsideNameOf1() - { - await TestMissingInRegularAndScriptAsync( + public Task SimplifyToPredefinedTypeNameShouldNotBeOfferedInsideNameOf1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1808,12 +1682,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995168")] - public async Task SimplifyToPredefinedTypeNameShouldNotBeOfferedInsideNameOf2() - { - await TestMissingInRegularAndScriptAsync( + public Task SimplifyToPredefinedTypeNameShouldNotBeOfferedInsideNameOf2() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -1823,12 +1695,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995168"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073099")] - public async Task SimplifyToPredefinedTypeNameShouldNotBeOfferedInsideNameOf3() - { - await TestMissingInRegularAndScriptAsync( + public Task SimplifyToPredefinedTypeNameShouldNotBeOfferedInsideNameOf3() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -1840,12 +1710,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995168"), WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073099")] - public async Task SimplifyToPredefinedTypeNameShouldBeOfferedInsideFunctionCalledNameOf() - { - await TestInRegularAndScriptAsync( + public Task SimplifyToPredefinedTypeNameShouldBeOfferedInsideFunctionCalledNameOf() + => TestInRegularAndScriptAsync( """ using System; @@ -1878,12 +1746,10 @@ static string nameof(Type t) } } """); - } [Fact] - public async Task SimplifyTypeNameInsideNameOf() - { - await TestInRegularAndScriptAsync( + public Task SimplifyTypeNameInsideNameOf() + => TestInRegularAndScriptAsync( """ using System; @@ -1906,12 +1772,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995168")] - public async Task SimplifyCrefAliasPredefinedType() - { - await TestInRegularAndScriptAsync( + public Task SimplifyCrefAliasPredefinedType() + => TestInRegularAndScriptAsync( """ namespace N1 { @@ -1936,13 +1800,10 @@ public C1() } } """, options: PreferIntrinsicTypeEverywhere); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538727")] - public async Task SimplifyAlias1() - { - var content = - """ + public Task SimplifyAlias1() + => TestMissingInRegularAndScriptAsync(""" using I64 = [|System.Int64|]; namespace N1 @@ -1951,15 +1812,11 @@ class Test { } } - """; - - await TestMissingInRegularAndScriptAsync(content); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538727")] - public async Task SimplifyAlias2() - { - await TestWithPredefinedTypeOptionsAsync( + public Task SimplifyAlias2() + => TestWithPredefinedTypeOptionsAsync( """ using I64 = System.Int64; using Goo = System.Collections.Generic.IList<[|System.Int64|]>; @@ -1982,12 +1839,10 @@ class Test } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538727")] - public async Task SimplifyAlias3() - { - await TestWithPredefinedTypeOptionsAsync( + public Task SimplifyAlias3() + => TestWithPredefinedTypeOptionsAsync( """ namespace Outer { @@ -2016,12 +1871,10 @@ class Test } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538727")] - public async Task SimplifyAlias4() - { - await TestWithPredefinedTypeOptionsAsync( + public Task SimplifyAlias4() + => TestWithPredefinedTypeOptionsAsync( """ using I64 = System.Int64; @@ -2052,37 +1905,28 @@ class Test } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544631")] - public async Task SimplifyAlias5() - { - var content = - """ + public Task SimplifyAlias5() + => TestInRegularAndScriptAsync(""" using System; namespace N { using X = [|System.Nullable|]; } - """; - - var result = - """ + """, """ using System; namespace N { using X = Nullable; } - """; - await TestInRegularAndScriptAsync(content, result); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/919815")] - public async Task SimplifyReturnTypeOnMethodCallToAlias() - { - await TestInRegularAndScriptAsync( + public Task SimplifyReturnTypeOnMethodCallToAlias() + => TestInRegularAndScriptAsync( """ using alias1 = A; @@ -2105,12 +1949,10 @@ public alias1 M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538949")] - public async Task SimplifyComplexGeneric1() - { - await TestMissingInRegularAndScriptAsync( + public Task SimplifyComplexGeneric1() + => TestMissingInRegularAndScriptAsync( """ class A { @@ -2127,12 +1969,10 @@ interface I { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538949")] - public async Task SimplifyComplexGeneric2() - { - await TestMissingInRegularAndScriptAsync( + public Task SimplifyComplexGeneric2() + => TestMissingInRegularAndScriptAsync( """ class A { @@ -2149,27 +1989,19 @@ interface I { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538991")] - public async Task SimplifyMissingOnGeneric() - { - var content = - """ + public Task SimplifyMissingOnGeneric() + => TestMissingInRegularAndScriptAsync(""" class A { class B : [|A|] { } } - """; - - await TestMissingInRegularAndScriptAsync(content); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539000")] - public async Task SimplifyMissingOnUnmentionableTypeParameter1() - { - var content = - """ + public Task SimplifyMissingOnUnmentionableTypeParameter1() + => TestMissingInRegularAndScriptAsync(""" class A { class D : A { } @@ -2180,15 +2012,11 @@ class C D.B x = new [|D.B|](); } } - """; - - await TestMissingInRegularAndScriptAsync(content); - } + """); [Fact] - public async Task SimplifyErrorTypeParameter() - { - await TestMissingInRegularAndScriptAsync( + public Task SimplifyErrorTypeParameter() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; using M = System.Collections.Generic.IList<[|System.Collections.Generic.IList<>|]>; @@ -2197,13 +2025,11 @@ class C { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539000")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/838109")] - public async Task SimplifyUnmentionableTypeParameter2() - { - await TestMissingInRegularAndScriptAsync( + public Task SimplifyUnmentionableTypeParameter2() + => TestMissingInRegularAndScriptAsync( """ class A { @@ -2221,12 +2047,10 @@ class C } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539000")] - public async Task SimplifyUnmentionableTypeParameter2_1() - { - await TestMissingInRegularAndScriptAsync( + public Task SimplifyUnmentionableTypeParameter2_1() + => TestMissingInRegularAndScriptAsync( """ class A { @@ -2244,12 +2068,10 @@ class C } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75026")] - public async Task SimplifyUnmentionableTypeParameter3() - { - await TestMissingInRegularAndScriptAsync( + public Task SimplifyUnmentionableTypeParameter3() + => TestMissingInRegularAndScriptAsync( """ public class C; @@ -2258,12 +2080,10 @@ public class D : C<[|D.E|]> public class E; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75026")] - public async Task SimplifyUnmentionableTypeParameter3_PrimaryCtor() - { - await TestMissingInRegularAndScriptAsync( + public Task SimplifyUnmentionableTypeParameter3_PrimaryCtor() + => TestMissingInRegularAndScriptAsync( """ public class C; @@ -2272,12 +2092,10 @@ public class D() : C<[|D.E|]>() public class E; } """); - } [Fact] - public async Task TestGlobalAlias() - { - await TestWithPredefinedTypeOptionsAsync( + public Task TestGlobalAlias() + => TestWithPredefinedTypeOptionsAsync( """ using System; using System.Collections.Generic; @@ -2304,21 +2122,17 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541748")] - public async Task TestOnErrorInScript() - { - await TestMissingAsync( + public Task TestOnErrorInScript() + => TestMissingAsync( @"[|Console.WrieLine();|]", new TestParameters(Options.Script)); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9877")] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestConflicts() - { - await TestInRegularAndScriptAsync( + public Task TestConflicts() + => TestInRegularAndScriptAsync( """ namespace OuterNamespace { @@ -2473,14 +2287,12 @@ InnerNamespace.InnerClass1 M3() } } """, -index: 1); - } + index: 1); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40633")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542100")] - public async Task TestPreventSimplificationToNameInCurrentScope() - { - await TestInRegularAndScript1Async( + public Task TestPreventSimplificationToNameInCurrentScope() + => TestInRegularAndScript1Async( """ namespace N { @@ -2522,13 +2334,11 @@ static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40633")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542100")] - public async Task TestPreventSimplificationToNameInCurrentScope2() - { - await TestInRegularAndScript1Async( + public Task TestPreventSimplificationToNameInCurrentScope2() + => TestInRegularAndScript1Async( """ namespace N { @@ -2568,13 +2378,11 @@ static void Main(int Goo) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40633")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542100")] - public async Task TestAllowSimplificationToNameInNestedScope() - { - await TestInRegularAndScriptAsync( + public Task TestAllowSimplificationToNameInNestedScope() + => TestInRegularAndScriptAsync( """ namespace N { @@ -2619,13 +2427,11 @@ static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40633")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542100")] - public async Task TestAllowSimplificationToNameInNestedScope1() - { - await TestInRegularAndScriptAsync( + public Task TestAllowSimplificationToNameInNestedScope1() + => TestInRegularAndScriptAsync( """ using System.Linq; @@ -2670,12 +2476,10 @@ static void Main(int[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] - public async Task TestOnOpenType1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestOnOpenType1() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -2688,12 +2492,10 @@ void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] - public async Task TestOnOpenType2() - { - await TestInRegularAndScriptAsync( + public Task TestOnOpenType2() + => TestInRegularAndScriptAsync( """ class Program { @@ -2718,12 +2520,10 @@ void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] - public async Task TestOnOpenType3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestOnOpenType3() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -2736,12 +2536,10 @@ void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] - public async Task TestOnOpenType4() - { - await TestMissingInRegularAndScriptAsync( + public Task TestOnOpenType4() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -2754,12 +2552,10 @@ void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] - public async Task TestOnOpenType5() - { - await TestMissingInRegularAndScriptAsync( + public Task TestOnOpenType5() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -2772,12 +2568,10 @@ void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] - public async Task TestOnOpenType6() - { - await TestMissingInRegularAndScriptAsync( + public Task TestOnOpenType6() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -2790,12 +2584,10 @@ void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] - public async Task TestOnNonOpenType1() - { - await TestInRegularAndScriptAsync( + public Task TestOnNonOpenType1() + => TestInRegularAndScriptAsync( """ class Program { @@ -2820,12 +2612,10 @@ void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] - public async Task TestOnNonOpenType2() - { - await TestInRegularAndScriptAsync( + public Task TestOnNonOpenType2() + => TestInRegularAndScriptAsync( """ class Program { @@ -2850,12 +2640,10 @@ void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] - public async Task TestOnNonOpenType3() - { - await TestInRegularAndScriptAsync( + public Task TestOnNonOpenType3() + => TestInRegularAndScriptAsync( """ class Program { @@ -2880,12 +2668,10 @@ void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] - public async Task TestOnNonOpenType4() - { - await TestInRegularAndScriptAsync( + public Task TestOnNonOpenType4() + => TestInRegularAndScriptAsync( """ class Program { @@ -2910,12 +2696,10 @@ void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] - public async Task TestOnNonOpenType5() - { - await TestInRegularAndScriptAsync( + public Task TestOnNonOpenType5() + => TestInRegularAndScriptAsync( """ class Program { @@ -2940,12 +2724,10 @@ void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] - public async Task TestOnNonOpenType6() - { - await TestMissingInRegularAndScriptAsync( + public Task TestOnNonOpenType6() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -2958,12 +2740,10 @@ void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542650")] - public async Task TestWithInterleavedDirective1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestWithInterleavedDirective1() + => TestMissingInRegularAndScriptAsync( """ #if true class A @@ -2986,12 +2766,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542719")] - public async Task TestGlobalMissing1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestGlobalMissing1() + => TestMissingInRegularAndScriptAsync( """ class Program { @@ -3008,12 +2786,10 @@ void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544615")] - public async Task TestMissingOnAmbiguousCast() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnAmbiguousCast() + => TestMissingInRegularAndScriptAsync( """ enum E { @@ -3027,12 +2803,10 @@ void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544616")] - public async Task ParenthesizeIfParseChanges() - { - await TestInRegularAndScriptAsync( + public Task ParenthesizeIfParseChanges() + => TestInRegularAndScriptAsync( """ using System; class C @@ -3055,12 +2829,10 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544974")] - public async Task TestNullableSimplification1() - { - await TestInRegularAndScriptAsync( + public Task TestNullableSimplification1() + => TestInRegularAndScriptAsync( """ class C { @@ -3079,12 +2851,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544974")] - public async Task TestNullableSimplification3() - { - await TestInRegularAndScriptAsync( + public Task TestNullableSimplification3() + => TestInRegularAndScriptAsync( """ class C { @@ -3101,12 +2871,10 @@ static void Main(int? i) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544974")] - public async Task TestNullableSimplification4() - { - await TestWithPredefinedTypeOptionsAsync( + public Task TestNullableSimplification4() + => TestWithPredefinedTypeOptionsAsync( """ class C { @@ -3123,12 +2891,10 @@ static void Main(int? i) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544977")] - public async Task TestNullableSimplification5() - { - await TestInRegularAndScriptAsync( + public Task TestNullableSimplification5() + => TestInRegularAndScriptAsync( """ using System; @@ -3151,12 +2917,10 @@ static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29")] - public async Task TestMissingNullableSimplificationInsideCref() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingNullableSimplificationInsideCref() + => TestMissingInRegularAndScriptAsync( """ using System; /// @@ -3166,12 +2930,10 @@ class A { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29")] - public async Task TestMissingNullableSimplificationInsideCref2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingNullableSimplificationInsideCref2() + => TestMissingInRegularAndScriptAsync( """ /// /// @@ -3180,12 +2942,10 @@ class A { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29")] - public async Task TestMissingNullableSimplificationInsideCref3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingNullableSimplificationInsideCref3() + => TestMissingInRegularAndScriptAsync( """ /// /// @@ -3194,12 +2954,10 @@ class A { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29")] - public async Task TestNullableInsideCref_AllowedIfReferencingActualTypeParameter() - { - await TestInRegularAndScriptAsync( + public Task TestNullableInsideCref_AllowedIfReferencingActualTypeParameter() + => TestInRegularAndScriptAsync( """ using System; /// @@ -3218,12 +2976,10 @@ class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29")] - public async Task TestMissingNullableSimplificationInsideCref5() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingNullableSimplificationInsideCref5() + => TestMissingInRegularAndScriptAsync( """ /// /// @@ -3235,13 +2991,11 @@ public void M() where U : struct } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29")] [WorkItem("https://github.com/dotnet/roslyn/issues/40664")] - public async Task TestNullableInsideCref_NotAllowedAtTopLevel() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNullableInsideCref_NotAllowedAtTopLevel() + => TestMissingInRegularAndScriptAsync( """ using System; /// @@ -3251,13 +3005,11 @@ class A { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29")] [WorkItem("https://github.com/dotnet/roslyn/issues/40664")] - public async Task TestNullableInsideCref_TopLevel2() - { - await TestInRegularAndScript1Async( + public Task TestNullableInsideCref_TopLevel2() + => TestInRegularAndScript1Async( """ using System; /// @@ -3276,14 +3028,10 @@ class A { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29")] - public async Task TestNullableInsideCref_AllowedIfReferencingActualType_AsTypeArgument() - { - // Both the 'original' and 'fixed' code here are incorrect as doc comments do not allow - // actual type-references in a type-arg list. - await TestInRegularAndScriptAsync( + public Task TestNullableInsideCref_AllowedIfReferencingActualType_AsTypeArgument() + => TestInRegularAndScriptAsync( """ using System; /// @@ -3302,12 +3050,10 @@ class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29")] - public async Task TestNullableInsideCref_AllowedIfReferencingActualType_InParameterList() - { - await TestInRegularAndScriptAsync( + public Task TestNullableInsideCref_AllowedIfReferencingActualType_InParameterList() + => TestInRegularAndScriptAsync( """ using System; /// @@ -3328,12 +3074,10 @@ class C void Goo(int? i) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29")] - public async Task TestMissingNullableSimplificationInsideCref8() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingNullableSimplificationInsideCref8() + => TestMissingInRegularAndScriptAsync( """ /// /// @@ -3345,12 +3089,10 @@ public void M() where U : struct } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29")] - public async Task TestNullableSimplificationInsideCref_Indirect() - { - await TestInRegularAndScriptAsync( + public Task TestNullableSimplificationInsideCref_Indirect() + => TestInRegularAndScriptAsync( """ /// /// @@ -3373,12 +3115,10 @@ public void M(A? x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29")] - public async Task TestNullableSimplificationInsideCref_Direct() - { - await TestInRegularAndScriptAsync( + public Task TestNullableSimplificationInsideCref_Direct() + => TestInRegularAndScriptAsync( """ /// /// @@ -3401,12 +3141,10 @@ public void M(A? x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29")] - public async Task TestNullableSimplificationInsideCref2() - { - await TestInRegularAndScriptAsync( + public Task TestNullableSimplificationInsideCref2() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -3433,12 +3171,10 @@ public void M(List x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29")] - public async Task TestNullableSimplificationInsideCref3() - { - await TestInRegularAndScriptAsync( + public Task TestNullableSimplificationInsideCref3() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -3465,12 +3201,10 @@ public void M(List x) where U : struct } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29")] - public async Task TestNullableSimplificationInsideCref4() - { - await TestInRegularAndScriptAsync( + public Task TestNullableSimplificationInsideCref4() + => TestInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -3497,12 +3231,10 @@ public void M(List x, U? y) where U : struct } } """); - } [Fact] - public async Task TestColorColorCase1() - { - await TestInRegularAndScriptAsync( + public Task TestColorColorCase1() + => TestInRegularAndScriptAsync( """ using N; @@ -3557,12 +3289,10 @@ void Main() } } """); - } [Fact] - public async Task TestColorColorCase2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestColorColorCase2() + => TestMissingInRegularAndScriptAsync( """ using N; @@ -3590,12 +3320,10 @@ void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40632")] - public async Task TestColorColorCase3() - { - await TestInRegularAndScriptAsync( + public Task TestColorColorCase3() + => TestInRegularAndScriptAsync( """ namespace N { @@ -3634,12 +3362,10 @@ class Program } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40632")] - public async Task TestColorColorCase4() - { - await TestInRegularAndScriptAsync( + public Task TestColorColorCase4() + => TestInRegularAndScriptAsync( """ namespace N { @@ -3680,12 +3406,10 @@ class Program } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40632")] - public async Task TestColorColorCase5() - { - await TestMissingAsync( + public Task TestColorColorCase5() + => TestMissingAsync( """ using A; @@ -3703,12 +3427,10 @@ class Color } } """); - } [Fact] - public async Task TestColorColorCase6() - { - await TestMissingAsync( + public Task TestColorColorCase6() + => TestMissingAsync( """ using System.Reflection.Metadata; using Microsoft.Cci; @@ -3744,7 +3466,6 @@ Cci.PrimitiveTypeCode TypeCode } } """); - } [Fact] public async Task TestAliasQualifiedType() @@ -3774,9 +3495,8 @@ static void Main() } [Fact] - public async Task TestSimplifyExpression() - { - await TestInRegularAndScriptAsync( + public Task TestSimplifyExpression() + => TestInRegularAndScriptAsync( """ using System; @@ -3799,13 +3519,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040")] - public async Task TestSimplifyStaticMemberAccess() - { - var source = - """ + public Task TestSimplifyStaticMemberAccess() + => TestInRegularAndScriptAsync(""" class Preserve { public static int Y; @@ -3822,8 +3539,7 @@ public static void Main() int k = [|Z.Y|]; } } - """; - await TestInRegularAndScriptAsync(source, + """, """ class Preserve { @@ -3842,13 +3558,10 @@ public static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040")] - public async Task TestSimplifyNestedType() - { - var source = - """ + public Task TestSimplifyNestedType() + => TestInRegularAndScriptAsync(""" class Preserve { public class X @@ -3868,8 +3581,7 @@ public static void Main() int k = [|Z.X|].Y; } } - """; - await TestInRegularAndScriptAsync(source, + """, """ class Preserve { @@ -3891,13 +3603,10 @@ public static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568043")] - public async Task DoNotSimplifyNamesWhenThereAreParseErrors() - { - var markup = - """ + public Task DoNotSimplifyNamesWhenThereAreParseErrors() + => TestMissingInRegularAndScriptAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -3910,15 +3619,11 @@ static void Main(string[] args) Console.[||] } } - """; - - await TestMissingInRegularAndScriptAsync(markup); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/566749")] - public async Task TestMethodGroups1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMethodGroups1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -3930,12 +3635,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/566749")] - public async Task TestMethodGroups2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMethodGroups2() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -3947,12 +3650,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554010")] - public async Task TestMethodGroups3() - { - await TestInRegularAndScriptAsync( + public Task TestMethodGroups3() + => TestInRegularAndScriptAsync( """ using System; @@ -3975,12 +3676,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578686")] - public async Task FixAllOccurrences1() - { - await TestInRegularAndScriptAsync( + public Task FixAllOccurrences1() + => TestInRegularAndScriptAsync( """ using goo = A.B; using bar = C.D; @@ -4035,12 +3734,10 @@ class D } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578686")] - public async Task DoNotUseAlias1() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotUseAlias1() + => TestMissingInRegularAndScriptAsync( """ using System.Collections.Generic; using System.Linq; @@ -4083,12 +3780,10 @@ class Goo } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/577169")] - public async Task SuitablyReplaceNullables1() - { - await TestMissingInRegularAndScriptAsync( + public Task SuitablyReplaceNullables1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4100,12 +3795,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/577169")] - public async Task SuitablyReplaceNullables2() - { - await TestMissingInRegularAndScriptAsync( + public Task SuitablyReplaceNullables2() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4117,12 +3810,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608190")] - public async Task Bugfix_608190() - { - await TestMissingInRegularAndScriptAsync( + public Task Bugfix_608190() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4146,12 +3837,10 @@ struct S static bool Equals(S s, object y) => false; } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608190")] - public async Task Bugfix_608190_1() - { - await TestMissingInRegularAndScriptAsync( + public Task Bugfix_608190_1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4173,12 +3862,10 @@ struct S } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608932")] - public async Task Bugfix_608932() - { - await TestMissingInRegularAndScriptAsync( + public Task Bugfix_608932() + => TestMissingInRegularAndScriptAsync( """ using S = X; @@ -4203,12 +3890,10 @@ class C } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635933")] - public async Task Bugfix_635933() - { - await TestMissingInRegularAndScriptAsync( + public Task Bugfix_635933() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4241,12 +3926,10 @@ public static string Goo(int x, T y) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547246")] - public async Task CodeIssueAtRightSpan() - { - await TestSpansAsync(""" + public Task CodeIssueAtRightSpan() + => TestSpansAsync(""" using goo = System.Console; class Program { @@ -4256,12 +3939,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579172")] - public async Task Bugfix_579172() - { - await TestMissingInRegularAndScriptAsync( + public Task Bugfix_579172() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -4270,12 +3951,10 @@ class D : C<[|D.D|], D.D.D> } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633182")] - public async Task Bugfix_633182() - { - await TestMissingInRegularAndScriptAsync( + public Task Bugfix_633182() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -4285,12 +3964,10 @@ void Goo() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627102")] - public async Task Bugfix_627102() - { - await TestMissingInRegularAndScriptAsync( + public Task Bugfix_627102() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4319,7 +3996,6 @@ public static string Goo(int x, T y) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/629572")] public async Task DoNotIncludeAliasNameIfLastTargetNameIsTheSame_1() @@ -4396,9 +4072,8 @@ static void Main(string[] args) } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/736377")] - public async Task DoNotSimplifyTypeNameBrokenCode() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotSimplifyTypeNameBrokenCode() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -4414,12 +4089,10 @@ public static ISet GetAllFilesInSolution() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813385")] - public async Task DoNotSimplifyAliases() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotSimplifyAliases() + => TestMissingInRegularAndScriptAsync( """ using Goo = System.Int32; @@ -4428,12 +4101,10 @@ class C [|Goo|] f; } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825541")] - public async Task ShowOnlyRelevantSpanForReductionOfGenericName() - { - await TestSpansAsync(""" + public Task ShowOnlyRelevantSpanForReductionOfGenericName() + => TestSpansAsync(""" namespace A { class Program @@ -4453,24 +4124,20 @@ class OtherClass } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/878773")] - public async Task DoNotSimplifyAttributeNameWithJustAttribute() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotSimplifyAttributeNameWithJustAttribute() + => TestMissingInRegularAndScriptAsync( """ [[|Attribute|]] class Attribute : System.Attribute { } """); - } [Fact] - public async Task ThisQualificationOnFieldOption() - { - await TestMissingInRegularAndScriptAsync( + public Task ThisQualificationOnFieldOption() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -4482,12 +4149,10 @@ public void z() } } """, new TestParameters(options: Option(CodeStyleOptions2.QualifyFieldAccess, true, NotificationOption2.Error))); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] - public async Task TestIntrinsicTypesInLocalDeclarationDefaultValue1() - { - await TestWithPredefinedTypeOptionsAsync( + public Task TestIntrinsicTypesInLocalDeclarationDefaultValue1() + => TestWithPredefinedTypeOptionsAsync( """ class C { @@ -4508,12 +4173,10 @@ public void z() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] - public async Task TestIntrinsicTypesInLocalDeclarationDefaultValue2() - { - await TestInRegularAndScriptAsync( + public Task TestIntrinsicTypesInLocalDeclarationDefaultValue2() + => TestInRegularAndScriptAsync( """ class C { @@ -4531,12 +4194,10 @@ public void z() } } """, options: PreferIntrinsicTypeEverywhere); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] - public async Task TestIntrinsicTypesInsideCref_Default_1() - { - await TestInRegularAndScriptAsync( + public Task TestIntrinsicTypesInsideCref_Default_1() + => TestInRegularAndScriptAsync( """ using System; class C @@ -4556,12 +4217,10 @@ public void z() } } """, options: PreferIntrinsicTypeInMemberAccess); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] - public async Task TestIntrinsicTypesInsideCref_Default_2() - { - await TestInRegularAndScriptAsync( + public Task TestIntrinsicTypesInsideCref_Default_2() + => TestInRegularAndScriptAsync( """ class C { @@ -4579,12 +4238,10 @@ public void z() } } """, options: PreferIntrinsicTypeEverywhere); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] - public async Task TestIntrinsicTypesInsideCref_Default_3() - { - await TestInRegularAndScriptAsync( + public Task TestIntrinsicTypesInsideCref_Default_3() + => TestInRegularAndScriptAsync( """ using System; class C @@ -4604,13 +4261,11 @@ public void z() } } """, options: PreferIntrinsicTypeEverywhere); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954536")] - public async Task TestIntrinsicTypesInsideCref_NonDefault_1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestIntrinsicTypesInsideCref_NonDefault_1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4622,13 +4277,11 @@ public void z() } } """, new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption2.Error))); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954536")] - public async Task TestIntrinsicTypesInsideCref_NonDefault_2() - { - await TestInRegularAndScriptAsync( + public Task TestIntrinsicTypesInsideCref_NonDefault_2() + => TestInRegularAndScriptAsync( """ using System; @@ -4651,13 +4304,11 @@ public void z() } } """, options: PreferIntrinsicTypeInMemberAccess); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954536")] - public async Task TestIntrinsicTypesInsideCref_NonDefault_3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestIntrinsicTypesInsideCref_NonDefault_3() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4669,12 +4320,10 @@ public void z() } } """, new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption2.Error))); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954536")] - public async Task TestIntrinsicTypesInsideCref_NonDefault_4() - { - await TestInRegularAndScriptAsync( + public Task TestIntrinsicTypesInsideCref_NonDefault_4() + => TestInRegularAndScriptAsync( """ using System; @@ -4697,13 +4346,11 @@ public void z() } } """, -options: PreferIntrinsicTypeInMemberAccess); - } + options: PreferIntrinsicTypeInMemberAccess); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954536")] - public async Task TestIntrinsicTypesInsideCref_NonDefault_5() - { - await TestMissingInRegularAndScriptAsync( + public Task TestIntrinsicTypesInsideCref_NonDefault_5() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -4713,12 +4360,10 @@ public void z() } } """, new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption2.Error))); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954536")] - public async Task TestIntrinsicTypesInsideCref_NonDefault_6_PreferMemberAccess() - { - await TestInRegularAndScriptAsync( + public Task TestIntrinsicTypesInsideCref_NonDefault_6_PreferMemberAccess() + => TestInRegularAndScriptAsync( """ class C { @@ -4737,13 +4382,11 @@ public void z() } } """, -options: PreferIntrinsicTypeInMemberAccess); - } + options: PreferIntrinsicTypeInMemberAccess); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954536")] - public async Task TestIntrinsicTypesInsideCref_NonDefault_6_PreferDeclaration() - { - await TestMissingAsync( + public Task TestIntrinsicTypesInsideCref_NonDefault_6_PreferDeclaration() + => TestMissingAsync( """ class C { @@ -4753,12 +4396,10 @@ public void z() } } """, new TestParameters(options: PreferIntrinsicTypeInDeclaration)); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] - public async Task TestIntrinsicTypesInLocalDeclarationNonDefaultValue_1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestIntrinsicTypesInLocalDeclarationNonDefaultValue_1() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -4770,12 +4411,10 @@ public void z(System.Int32 y) } } """, new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Error))); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] - public async Task TestIntrinsicTypesInLocalDeclarationNonDefaultValue_2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestIntrinsicTypesInLocalDeclarationNonDefaultValue_2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -4787,12 +4426,10 @@ public void z([|System.Int32|] y) } } """, new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Error))); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] - public async Task TestIntrinsicTypesInLocalDeclarationNonDefaultValue_3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestIntrinsicTypesInLocalDeclarationNonDefaultValue_3() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -4804,12 +4441,10 @@ public void z(System.Int32 y) } } """, new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Error))); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] - public async Task TestIntrinsicTypesInMemberAccess_Default_1() - { - await TestInRegularAndScriptAsync( + public Task TestIntrinsicTypesInMemberAccess_Default_1() + => TestInRegularAndScriptAsync( """ class C { @@ -4828,12 +4463,10 @@ public void z() } } """, options: PreferIntrinsicTypeInMemberAccess); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] - public async Task TestIntrinsicTypesInMemberAccess_Default_2() - { - await TestInRegularAndScriptAsync( + public Task TestIntrinsicTypesInMemberAccess_Default_2() + => TestInRegularAndScriptAsync( """ using System; @@ -4856,12 +4489,10 @@ public void z() } } """, options: PreferIntrinsicTypeInMemberAccess); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/956667")] - public async Task TestIntrinsicTypesInMemberAccess_Default_3() - { - await TestMissingInRegularAndScriptAsync( + public Task TestIntrinsicTypesInMemberAccess_Default_3() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4878,12 +4509,10 @@ class C2 public static int Memb; } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] - public async Task TestIntrinsicTypesInMemberAccess_NonDefault_1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestIntrinsicTypesInMemberAccess_NonDefault_1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -4895,12 +4524,10 @@ public void z() } } """, new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption2.Error))); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] - public async Task TestIntrinsicTypesInMemberAccess_NonDefault_2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestIntrinsicTypesInMemberAccess_NonDefault_2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -4910,7 +4537,6 @@ public void z() } } """, new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption2.Error))); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/965208")] public async Task TestSimplifyDiagnosticId() @@ -4965,9 +4591,8 @@ public void z() } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1019276")] - public async Task TestSimplifyTypeNameDoesNotAddUnnecessaryParens() - { - await TestWithPredefinedTypeOptionsAsync( + public Task TestSimplifyTypeNameDoesNotAddUnnecessaryParens() + => TestWithPredefinedTypeOptionsAsync( """ using System; @@ -4996,12 +4621,10 @@ static void F() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068445")] - public async Task TestSimplifyTypeNameInPropertyLambda() - { - await TestWithPredefinedTypeOptionsAsync( + public Task TestSimplifyTypeNameInPropertyLambda() + => TestWithPredefinedTypeOptionsAsync( """ namespace ClassLibrary2 { @@ -5020,12 +4643,10 @@ public class Class1 } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068445")] - public async Task TestSimplifyTypeNameInMethodLambda() - { - await TestWithPredefinedTypeOptionsAsync( + public Task TestSimplifyTypeNameInMethodLambda() + => TestWithPredefinedTypeOptionsAsync( """ class C { @@ -5038,12 +4659,10 @@ class C public string Goo() => (string)"; } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068445")] - public async Task TestSimplifyTypeNameInIndexerLambda() - { - await TestWithPredefinedTypeOptionsAsync( + public Task TestSimplifyTypeNameInIndexerLambda() + => TestWithPredefinedTypeOptionsAsync( """ class C { @@ -5056,12 +4675,10 @@ class C public int this[int index] => (int)0; } """); - } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=388744")] - public async Task SimplifyTypeNameWithOutDiscard() - { - await TestAsync( + public Task SimplifyTypeNameWithOutDiscard() + => TestAsync( """ class C { @@ -5089,12 +4706,10 @@ static void G(out object o) } """, parseOptions: CSharpParseOptions.Default); - } [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=388744")] - public async Task SimplifyTypeNameWithOutDiscard_FeatureDisabled() - { - await TestAsync( + public Task SimplifyTypeNameWithOutDiscard_FeatureDisabled() + => TestAsync( """ class C { @@ -5122,12 +4737,10 @@ static void G(out object o) } """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15996")] - public async Task TestMemberOfBuiltInType1() - { - await TestAsync( + public Task TestMemberOfBuiltInType1() + => TestAsync( """ using System; class C @@ -5150,12 +4763,10 @@ void Main() """, parseOptions: CSharpParseOptions.Default, options: PreferIntrinsicTypeInDeclaration); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15996")] - public async Task TestMemberOfBuiltInType2() - { - await TestAsync( + public Task TestMemberOfBuiltInType2() + => TestAsync( """ using System; class C @@ -5178,12 +4789,10 @@ void Main() """, parseOptions: CSharpParseOptions.Default, options: PreferIntrinsicTypeInMemberAccess); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15996")] - public async Task TestMemberOfBuiltInType3() - { - await TestAsync( + public Task TestMemberOfBuiltInType3() + => TestAsync( """ using System; class C @@ -5206,12 +4815,10 @@ void Main() """, parseOptions: CSharpParseOptions.Default, options: PreferIntrinsicTypeInMemberAccess); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26923")] - public async Task NoSuggestionOnForeachCollectionExpression() - { - await TestMissingInRegularAndScriptAsync( + public Task NoSuggestionOnForeachCollectionExpression() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -5227,12 +4834,10 @@ static void Main(string[] args) } } """, new TestParameters(options: PreferImplicitTypeEverywhere)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26923")] - public async Task NoSuggestionOnForeachType() - { - await TestMissingInRegularAndScriptAsync( + public Task NoSuggestionOnForeachType() + => TestMissingInRegularAndScriptAsync( """ using System; using System.Collections.Generic; @@ -5248,12 +4853,10 @@ static void Main(string[] args) } } """, new TestParameters(options: PreferImplicitTypeEverywhere)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31849")] - public async Task NoSuggestionOnNestedNullabilityRequired() - { - await TestMissingInRegularAndScriptAsync( + public Task NoSuggestionOnNestedNullabilityRequired() + => TestMissingInRegularAndScriptAsync( """ #nullable enable using System.Threading.Tasks; @@ -5266,7 +4869,6 @@ class C } } """); - } [Theory] [InlineData(0)] @@ -5276,9 +4878,8 @@ class C [InlineData(4)] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [WorkItem("https://github.com/dotnet/roslyn/issues/20377")] - public async Task TestWarningLevel(int warningLevel) - { - await TestInRegularAndScriptAsync( + public Task TestWarningLevel(int warningLevel) + => TestInRegularAndScriptAsync( """ using System; @@ -5301,15 +4902,12 @@ class A } } """, compilationOptions: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, warningLevel: warningLevel)); - } [Fact] - public async Task TestGlobalAliasSimplifiesInUsingDirective() - { - await TestInRegularAndScriptAsync( + public Task TestGlobalAliasSimplifiesInUsingDirective() + => TestInRegularAndScriptAsync( "using [|global::System.IO|];", "using System.IO;"); - } [Theory] [InlineData("Boolean")] @@ -5325,25 +4923,20 @@ await TestInRegularAndScriptAsync( [InlineData("UInt64")] [InlineData("Float32")] [InlineData("Float64")] - public async Task TestGlobalAliasSimplifiesInUsingAliasDirective(string typeName) - { - await TestInRegularAndScriptAsync( + public Task TestGlobalAliasSimplifiesInUsingAliasDirective(string typeName) + => TestInRegularAndScriptAsync( $"using My{typeName} = [|global::System.{typeName}|];", $"using My{typeName} = System.{typeName};"); - } [Fact] - public async Task TestGlobalAliasSimplifiesInUsingStaticDirective() - { - await TestInRegularAndScriptAsync( + public Task TestGlobalAliasSimplifiesInUsingStaticDirective() + => TestInRegularAndScriptAsync( "using static [|global::System.Math|];", "using static System.Math;"); - } [Fact] - public async Task TestGlobalAliasSimplifiesInUsingDirectiveInNamespace() - { - await TestInRegularAndScriptAsync( + public Task TestGlobalAliasSimplifiesInUsingDirectiveInNamespace() + => TestInRegularAndScriptAsync( """ using System; namespace N @@ -5358,12 +4951,10 @@ namespace N using System.IO; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40639")] - public async Task TestCrefIdAtTopLevel() - { - await TestDiagnosticInfoAsync( + public Task TestCrefIdAtTopLevel() + => TestDiagnosticInfoAsync( """ /// /// @@ -5372,12 +4963,10 @@ class Base { } """, IDEDiagnosticIds.PreferBuiltInOrFrameworkTypeDiagnosticId, DiagnosticSeverity.Hidden); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40639")] - public async Task TestCrefIdAtNestedLevel() - { - await TestDiagnosticInfoAsync( + public Task TestCrefIdAtNestedLevel() + => TestDiagnosticInfoAsync( """ /// /// @@ -5387,7 +4976,6 @@ class Base public void Foo(string s) { } } """, IDEDiagnosticIds.PreferBuiltInOrFrameworkTypeDiagnosticId, DiagnosticSeverity.Hidden); - } [Theory] [InlineData("Boolean")] @@ -5399,45 +4987,48 @@ public void Foo(string s) { } [InlineData("UInt32")] [InlineData("Int64")] [InlineData("UInt64")] - public async Task TestGlobalAliasSimplifiesInUsingAliasDirectiveWithinNamespace(string typeName) - { - await TestInRegularAndScriptAsync( -$@"using System; -namespace N -{{ - using My{typeName} = [|global::System.{typeName}|]; -}}", -$@"using System; -namespace N -{{ - using My{typeName} = {typeName}; -}}"); - } + public Task TestGlobalAliasSimplifiesInUsingAliasDirectiveWithinNamespace(string typeName) + => TestInRegularAndScriptAsync( + $$""" + using System; + namespace N + { + using My{{typeName}} = [|global::System.{{typeName}}|]; + } + """, + $$""" + using System; + namespace N + { + using My{{typeName}} = {{typeName}}; + } + """); [Theory] [InlineData("Int8")] [InlineData("UInt8")] [InlineData("Float32")] [InlineData("Float64")] - public async Task TestGlobalAliasSimplifiesInUsingAliasDirectiveWithinNamespace_UnboundName(string typeName) - { - await TestInRegularAndScriptAsync( -$@"using System; -namespace N -{{ - using My{typeName} = [|global::System.{typeName}|]; -}}", -$@"using System; -namespace N -{{ - using My{typeName} = System.{typeName}; -}}"); - } + public Task TestGlobalAliasSimplifiesInUsingAliasDirectiveWithinNamespace_UnboundName(string typeName) + => TestInRegularAndScriptAsync( + $$""" + using System; + namespace N + { + using My{{typeName}} = [|global::System.{{typeName}}|]; + } + """, + $$""" + using System; + namespace N + { + using My{{typeName}} = System.{{typeName}}; + } + """); [Fact] - public async Task TestGlobalAliasSimplifiesInUsingStaticDirectiveInNamespace() - { - await TestInRegularAndScriptAsync( + public Task TestGlobalAliasSimplifiesInUsingStaticDirectiveInNamespace() + => TestInRegularAndScriptAsync( """ using System; namespace N @@ -5452,12 +5043,10 @@ namespace N using static System.Math; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27819")] - public async Task DoNotSimplifyToVar_EvenIfVarIsPreferred() - { - await TestInRegularAndScriptAsync( + public Task DoNotSimplifyToVar_EvenIfVarIsPreferred() + => TestInRegularAndScriptAsync( """ class C { @@ -5476,12 +5065,10 @@ void Goo() } } """, options: PreferImplicitTypeEverywhere); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27819")] - public async Task DoNotSimplifyToVar_EvenIfVarIsPreferred_2() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotSimplifyToVar_EvenIfVarIsPreferred_2() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -5491,12 +5078,10 @@ void Goo() } } """, new TestParameters(options: PreferImplicitTypeEverywhere)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40647")] - public async Task SimplifyMemberAccessOverPredefinedType() - { - await TestInRegularAndScript1Async( + public Task SimplifyMemberAccessOverPredefinedType() + => TestInRegularAndScript1Async( """ using System; @@ -5513,12 +5098,10 @@ class Base public void Goo(object o1, object o2) => ReferenceEquals(o1, o2); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40649")] - public async Task SimplifyAliasToGeneric1() - { - await TestInRegularAndScript1Async( + public Task SimplifyAliasToGeneric1() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; using MyList = System.Collections.Generic.List; @@ -5537,12 +5120,10 @@ class Base public MyList Goo; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40649")] - public async Task SimplifyAliasToGeneric2() - { - await TestInRegularAndScript1Async( + public Task SimplifyAliasToGeneric2() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; using MyList = System.Collections.Generic.List; @@ -5561,12 +5142,10 @@ class Base public MyList Goo; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40649")] - public async Task SimplifyAliasToGeneric3() - { - await TestInRegularAndScript1Async( + public Task SimplifyAliasToGeneric3() + => TestInRegularAndScript1Async( """ using System.Collections.Generic; using MyList = System.Collections.Generic.List; @@ -5585,12 +5164,10 @@ class Base public MyList Goo; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40649")] - public async Task DoNotSimplifyIncorrectInstantiation() - { - await TestMissingAsync( + public Task DoNotSimplifyIncorrectInstantiation() + => TestMissingAsync( """ using System.Collections.Generic; using MyList = System.Collections.Generic.List; @@ -5600,12 +5177,10 @@ class Base public [|List|] Goo; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40663")] - public async Task SimplifyInTypeOf() - { - await TestInRegularAndScriptAsync( + public Task SimplifyInTypeOf() + => TestInRegularAndScriptAsync( """ using System; @@ -5628,12 +5203,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40876")] - public async Task SimplifyPredefinedTypeInUsingDirective1() - { - await TestWithPredefinedTypeOptionsAsync( + public Task SimplifyPredefinedTypeInUsingDirective1() + => TestWithPredefinedTypeOptionsAsync( """ using System; @@ -5661,12 +5234,10 @@ class C } } """); - } [Fact] - public async Task TestSimplifyTopLevelOfCrefOnly1() - { - await TestInRegularAndScriptAsync( + public Task TestSimplifyTopLevelOfCrefOnly1() + => TestInRegularAndScriptAsync( """ using System; @@ -5693,12 +5264,10 @@ class X } } """); - } [Fact] - public async Task TestSimplifyTopLevelOfCrefOnly2() - { - await TestSpansAsync( + public Task TestSimplifyTopLevelOfCrefOnly2() + => TestSpansAsync( """ using System; @@ -5712,12 +5281,10 @@ class X } } """); - } [Fact] - public async Task TestSimplifyTopLevelOfCrefOnly4() - { - await TestInRegularAndScriptAsync( + public Task TestSimplifyTopLevelOfCrefOnly4() + => TestInRegularAndScriptAsync( """ using System; @@ -5746,12 +5313,10 @@ void Y(X x) { } } } """); - } [Fact] - public async Task TestSimplifyTopLevelOfCrefOnly5() - { - await TestInRegularAndScriptAsync( + public Task TestSimplifyTopLevelOfCrefOnly5() + => TestInRegularAndScriptAsync( """ using System; @@ -5780,7 +5345,6 @@ void Y(X x) { } } } """); - } [Theory] [InlineData("Boolean")] @@ -5796,15 +5360,15 @@ void Y(X x) { } [InlineData("UInt64")] [InlineData("Float32")] [InlineData("Float64")] - public async Task TestDoesNotSimplifyUsingAliasDirectiveToPrimitiveType(string typeName) - { - await TestMissingAsync( -$@"using System; -namespace N -{{ - using My{typeName} = [|{typeName}|]; -}}"); - } + public Task TestDoesNotSimplifyUsingAliasDirectiveToPrimitiveType(string typeName) + => TestMissingAsync( + $$""" + using System; + namespace N + { + using My{{typeName}} = [|{{typeName}}|]; + } + """); [Theory] [InlineData("Boolean")] @@ -5816,40 +5380,41 @@ namespace N [InlineData("UInt32")] [InlineData("Int64")] [InlineData("UInt64")] - public async Task TestSimplifyUsingAliasDirectiveToQualifiedBuiltInType(string typeName) - { - await TestInRegularAndScript1Async( -$@"using System; -namespace N -{{ - using My{typeName} = [|System.{typeName}|]; -}}", -$@"using System; -namespace N -{{ - using My{typeName} = {typeName}; -}}"); - } + public Task TestSimplifyUsingAliasDirectiveToQualifiedBuiltInType(string typeName) + => TestInRegularAndScript1Async( + $$""" + using System; + namespace N + { + using My{{typeName}} = [|System.{{typeName}}|]; + } + """, + $$""" + using System; + namespace N + { + using My{{typeName}} = {{typeName}}; + } + """); [Theory] [InlineData("Int8")] [InlineData("UInt8")] [InlineData("Float32")] [InlineData("Float64")] - public async Task TestDoesNotSimplifyUsingAliasWithUnboundTypes(string typeName) - { - await TestMissingInRegularAndScriptAsync( -$@"using System; -namespace N -{{ - using My{typeName} = [|System.{typeName}|]; -}}"); - } + public Task TestDoesNotSimplifyUsingAliasWithUnboundTypes(string typeName) + => TestMissingInRegularAndScriptAsync( + $$""" + using System; + namespace N + { + using My{{typeName}} = [|System.{{typeName}}|]; + } + """); [Fact] - public async Task SimplifyMemberAccessOffOfObjectKeyword() - { - await TestInRegularAndScriptAsync( + public Task SimplifyMemberAccessOffOfObjectKeyword() + => TestInRegularAndScriptAsync( """ using System; @@ -5872,12 +5437,10 @@ bool Goo() } } """); - } [Fact] - public async Task DoNotSimplifyBaseCallToVirtualInNonSealedClass() - { - await TestMissingAsync( + public Task DoNotSimplifyBaseCallToVirtualInNonSealedClass() + => TestMissingAsync( """ using System; @@ -5889,12 +5452,10 @@ void Goo() } } """); - } [Fact] - public async Task DoSimplifyBaseCallToVirtualInSealedClass() - { - await TestInRegularAndScript1Async( + public Task DoSimplifyBaseCallToVirtualInSealedClass() + => TestInRegularAndScript1Async( """ using System; @@ -5917,12 +5478,10 @@ void Goo() } } """); - } [Fact] - public async Task DoSimplifyBaseCallToVirtualInStruct() - { - await TestInRegularAndScript1Async( + public Task DoSimplifyBaseCallToVirtualInStruct() + => TestInRegularAndScript1Async( """ using System; @@ -5945,12 +5504,10 @@ void Goo() } } """); - } [Fact] - public async Task DoNotSimplifyBaseCallToVirtualWithOverride() - { - await TestMissingAsync( + public Task DoNotSimplifyBaseCallToVirtualWithOverride() + => TestMissingAsync( """ using System; @@ -5964,12 +5521,10 @@ void Goo() public override int GetHashCode() => 0; } """); - } [Fact] - public async Task DoSimplifyBaseCallToNonVirtual() - { - await TestInRegularAndScript1Async( + public Task DoSimplifyBaseCallToNonVirtual() + => TestInRegularAndScript1Async( """ using System; @@ -6002,12 +5557,10 @@ void Goo() } } """); - } [Fact] - public async Task DoNotSimplifyBaseCallIfOverloadChanges() - { - await TestMissingAsync( + public Task DoNotSimplifyBaseCallIfOverloadChanges() + => TestMissingAsync( """ using System; @@ -6026,12 +5579,10 @@ void Goo() public int Baz(int o) => 0; } """); - } [Fact] - public async Task DoNotSimplifyInsideNameof() - { - await TestMissingAsync( + public Task DoNotSimplifyInsideNameof() + => TestMissingAsync( """ using System; @@ -6044,12 +5595,10 @@ public int Baz(string type) }; } """); - } [Fact] - public async Task DoSimplifyInferrableTypeArgumentList() - { - await TestInRegularAndScript1Async( + public Task DoSimplifyInferrableTypeArgumentList() + => TestInRegularAndScript1Async( """ using System; @@ -6068,12 +5617,10 @@ class Base public void Bar(T t) => default; } """); - } [Fact] - public async Task DoNotSimplifyNonInferrableTypeArgumentList() - { - await TestMissingAsync( + public Task DoNotSimplifyNonInferrableTypeArgumentList() + => TestMissingAsync( """ using System; @@ -6083,12 +5630,10 @@ class Base public void Bar() => default; } """); - } [Fact] - public async Task SimplifyEnumMemberReferenceInsideEnum() - { - await TestInRegularAndScript1Async( + public Task SimplifyEnumMemberReferenceInsideEnum() + => TestInRegularAndScript1Async( """ enum E { @@ -6103,12 +5648,10 @@ enum E Bar = Goo, } """); - } [Fact] - public async Task SimplifyEnumMemberReferenceInsideEnumDocComment() - { - await TestInRegularAndScript1Async( + public Task SimplifyEnumMemberReferenceInsideEnumDocComment() + => TestInRegularAndScript1Async( """ /// /// @@ -6127,12 +5670,10 @@ enum E Goo = 1, } """); - } [Fact] - public async Task TestInstanceMemberReferenceInCref1() - { - await TestInRegularAndScriptAsync( + public Task TestInstanceMemberReferenceInCref1() + => TestInRegularAndScriptAsync( """ class C { @@ -6150,12 +5691,10 @@ public void z() } } """); - } [Fact] - public async Task SimplifyAttributeReference1() - { - await TestInRegularAndScript1Async( + public Task SimplifyAttributeReference1() + => TestInRegularAndScript1Async( """ using System; @@ -6180,12 +5719,10 @@ class Bar { } """); - } [Fact] - public async Task SimplifyAttributeReference2() - { - await TestInRegularAndScript1Async( + public Task SimplifyAttributeReference2() + => TestInRegularAndScript1Async( """ using System; @@ -6210,12 +5747,10 @@ class Bar { } """); - } [Fact] - public async Task SimplifyGenericAttributeReference1() - { - await TestInRegularAndScript1Async( + public Task SimplifyGenericAttributeReference1() + => TestInRegularAndScript1Async( """ using System; @@ -6240,12 +5775,10 @@ class Bar { } """); - } [Fact] - public async Task SimplifyGenericAttributeReference2() - { - await TestInRegularAndScript1Async( + public Task SimplifyGenericAttributeReference2() + => TestInRegularAndScript1Async( """ using System; @@ -6270,12 +5803,10 @@ class Bar { } """); - } [Fact] - public async Task SimplifyGenericAttributeReference3() - { - await TestInRegularAndScript1Async( + public Task SimplifyGenericAttributeReference3() + => TestInRegularAndScript1Async( """ using System; @@ -6302,12 +5833,10 @@ class Bar { } """); - } [Fact] - public async Task SimplifyGenericAttributeReference4() - { - await TestInRegularAndScript1Async( + public Task SimplifyGenericAttributeReference4() + => TestInRegularAndScript1Async( """ using System; @@ -6334,12 +5863,10 @@ class Bar { } """); - } [Fact] - public async Task DoNotSimplifyNestedInsideGenericAttributeReference1() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotSimplifyNestedInsideGenericAttributeReference1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -6353,12 +5880,10 @@ class Bar { } """); - } [Fact] - public async Task DoNotSimplifyNestedInsideGenericAttributeReference2() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotSimplifyNestedInsideGenericAttributeReference2() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -6372,12 +5897,10 @@ class Bar { } """); - } [Fact] - public async Task DoNotSimplifyNestedInsideGenericAttributeReference3() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotSimplifyNestedInsideGenericAttributeReference3() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -6391,12 +5914,10 @@ class Bar { } """); - } [Fact] - public async Task DoNotSimplifyNestedInsideGenericAttributeReference4() - { - await TestMissingInRegularAndScriptAsync( + public Task DoNotSimplifyNestedInsideGenericAttributeReference4() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -6410,12 +5931,10 @@ class Bar { } """); - } [Fact] - public async Task SimplifyAttributeReference3() - { - await TestInRegularAndScript1Async( + public Task SimplifyAttributeReference3() + => TestInRegularAndScript1Async( """ using System; @@ -6446,12 +5965,10 @@ class Bar { } """); - } [Fact] - public async Task SimplifyAttributeReference4() - { - await TestInRegularAndScript1Async( + public Task SimplifyAttributeReference4() + => TestInRegularAndScript1Async( """ using System; @@ -6482,12 +5999,10 @@ class Bar { } """); - } [Fact] - public async Task SimplifySystemAttribute() - { - await TestInRegularAndScript1Async( + public Task SimplifySystemAttribute() + => TestInRegularAndScript1Async( """ using System; using System.Runtime.Serialization; @@ -6512,13 +6027,11 @@ public struct ClassifiedToken } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40633")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542100")] - public async Task TestAllowSimplificationThatWouldNotCauseConflict1() - { - await TestInRegularAndScriptAsync( + public Task TestAllowSimplificationThatWouldNotCauseConflict1() + => TestInRegularAndScriptAsync( """ namespace N { @@ -6563,12 +6076,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542100")] - public async Task TestAllowSimplificationThatWouldNotCauseConflict2() - { - await TestInRegularAndScriptAsync( + public Task TestAllowSimplificationThatWouldNotCauseConflict2() + => TestInRegularAndScriptAsync( """ namespace N { @@ -6613,12 +6124,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542100")] - public async Task TestPreventSimplificationThatWouldCauseConflict1() - { - await TestInRegularAndScript1Async( + public Task TestPreventSimplificationThatWouldCauseConflict1() + => TestInRegularAndScript1Async( """ namespace N { @@ -6659,12 +6168,10 @@ static void Main() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542100")] - public async Task TestPreventSimplificationThatWouldCauseConflict2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestPreventSimplificationThatWouldCauseConflict2() + => TestMissingInRegularAndScriptAsync( """ namespace N { @@ -6685,12 +6192,10 @@ static void Main(int[] args) } } """); - } [Fact] - public async Task TestSimplifyPredefinedTypeMemberAccessThatIsInScope() - { - await TestInRegularAndScript1Async( + public Task TestSimplifyPredefinedTypeMemberAccessThatIsInScope() + => TestInRegularAndScript1Async( """ using static System.Int32; @@ -6713,7 +6218,6 @@ public void Bar(string a) } } """); - } [Theory] [InlineData("Boolean")] @@ -6725,25 +6229,26 @@ public void Bar(string a) [InlineData("UInt32")] [InlineData("Int64")] [InlineData("UInt64")] - public async Task TestDoesNotSimplifyUsingAliasDirectiveToBuiltInType(string typeName) - { - await TestInRegularAndScript1Async( -$@"using System; -namespace N -{{ - using My{typeName} = [|System.{typeName}|]; -}}", -$@"using System; -namespace N -{{ - using My{typeName} = {typeName}; -}}"); - } + public Task TestDoesNotSimplifyUsingAliasDirectiveToBuiltInType(string typeName) + => TestInRegularAndScript1Async( + $$""" + using System; + namespace N + { + using My{{typeName}} = [|System.{{typeName}}|]; + } + """, + $$""" + using System; + namespace N + { + using My{{typeName}} = {{typeName}}; + } + """); [Fact] - public async Task TestDoNotSimplifyIfItWouldIntroduceAmbiguity() - { - await TestMissingInRegularAndScriptAsync( + public Task TestDoNotSimplifyIfItWouldIntroduceAmbiguity() + => TestMissingInRegularAndScriptAsync( """ using A; using B; @@ -6766,12 +6271,10 @@ void Bar(object o) } } """); - } [Fact] - public async Task TestDoNotSimplifyIfItWouldIntroduceAmbiguity2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestDoNotSimplifyIfItWouldIntroduceAmbiguity2() + => TestMissingInRegularAndScriptAsync( """ using A; @@ -6798,12 +6301,10 @@ void Bar(object o) } } """); - } [Fact] - public async Task TestAllowSimplificationWithoutAmbiguity2() - { - await TestInRegularAndScript1Async( + public Task TestAllowSimplificationWithoutAmbiguity2() + => TestInRegularAndScript1Async( """ using A; @@ -6856,12 +6357,10 @@ void Bar(object o) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995168")] - public async Task SimplifyCrefAliasPredefinedType_OnClass() - { - await TestInRegularAndScriptAsync( + public Task SimplifyCrefAliasPredefinedType_OnClass() + => TestInRegularAndScriptAsync( """ namespace N1 { @@ -6886,13 +6385,10 @@ public C1() } } """, options: PreferIntrinsicTypeEverywhere); - } [Fact] - public async Task TestMissingOnInstanceMemberAccessOfOtherValue() - { - var content = - """ + public Task TestMissingOnInstanceMemberAccessOfOtherValue() + => TestMissingInRegularAndScriptAsync(""" using System; internal struct BitVector : IEquatable @@ -6911,16 +6407,11 @@ public override bool Equals(object obj) return [|left|].Equals(right); } } - """; - - await TestMissingInRegularAndScriptAsync(content); - } + """); [Fact] - public async Task TestSimplifyStaticMemberAccessThroughDerivedType() - { - var source = - """ + public Task TestSimplifyStaticMemberAccessThroughDerivedType() + => TestInRegularAndScriptAsync(""" class Base { public static int Y; @@ -6937,8 +6428,7 @@ public static void Main() int k = [|Derived|].Y; } } - """; - await TestInRegularAndScriptAsync(source, + """, """ class Base { @@ -6957,12 +6447,10 @@ public static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22493")] - public async Task TestSimplifyCallWithDynamicArg() - { - await TestInRegularAndScriptAsync( + public Task TestSimplifyCallWithDynamicArg() + => TestInRegularAndScriptAsync( """ using System; @@ -6987,12 +6475,10 @@ public static void Main() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22493")] - public async Task TestDoSimplifyCallWithDynamicArgWhenCallingThroughDerivedClass() - { - await TestMissingInRegularAndScriptAsync( + public Task TestDoSimplifyCallWithDynamicArgWhenCallingThroughDerivedClass() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -7014,12 +6500,10 @@ public static void Main() } } """); - } [Fact] - public async Task TestNameofReportsSimplifyMemberAccess() - { - await TestDiagnosticInfoAsync( + public Task TestNameofReportsSimplifyMemberAccess() + => TestDiagnosticInfoAsync( """ using System; @@ -7031,12 +6515,10 @@ void Goo() } } """, IDEDiagnosticIds.SimplifyMemberAccessDiagnosticId, DiagnosticSeverity.Hidden); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40972")] - public async Task TestNameofReportsSimplifyMemberAccessForMemberGroup1() - { - await TestInRegularAndScript1Async( + public Task TestNameofReportsSimplifyMemberAccessForMemberGroup1() + => TestInRegularAndScript1Async( """ using System; @@ -7059,12 +6541,10 @@ void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40972")] - public async Task TestNameofReportsSimplifyMemberAccessForMemberGroup2() - { - await TestInRegularAndScript1Async( + public Task TestNameofReportsSimplifyMemberAccessForMemberGroup2() + => TestInRegularAndScript1Async( """ using System; @@ -7087,12 +6567,10 @@ static void Goo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40972")] - public async Task TestNameofReportsSimplifyMemberAccessForMemberGroup3() - { - await TestInRegularAndScript1Async( + public Task TestNameofReportsSimplifyMemberAccessForMemberGroup3() + => TestInRegularAndScript1Async( """ using System; @@ -7119,12 +6597,10 @@ void Goo() void Goo(int i) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40972")] - public async Task TestNameofReportsSimplifyMemberAccessForMemberGroup4() - { - await TestInRegularAndScript1Async( + public Task TestNameofReportsSimplifyMemberAccessForMemberGroup4() + => TestInRegularAndScript1Async( """ using System; @@ -7151,12 +6627,10 @@ static void Goo() static void Goo(int i) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11380")] - public async Task TestNotOnIllegalInstanceCall() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOnIllegalInstanceCall() + => TestMissingInRegularAndScriptAsync( """ using System; class Program @@ -7167,12 +6641,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57767")] - public async Task TestInvocationOffOfFunctionPointerInvocationResult1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestInvocationOffOfFunctionPointerInvocationResult1() + => TestMissingInRegularAndScriptAsync( """ using System.Runtime.CompilerServices; @@ -7193,12 +6665,10 @@ public void Dispose() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57767")] - public async Task TestInvocationOffOfFunctionPointerInvocationResult2() - { - await TestMissingInRegularAndScriptAsync( + public Task TestInvocationOffOfFunctionPointerInvocationResult2() + => TestMissingInRegularAndScriptAsync( """ public struct A { @@ -7217,21 +6687,18 @@ public void Dispose() } } """); - } [Fact] public async Task TestNint1_NoNumericIntPtr_CSharp10_NoRuntimeSupport() { - var source = + var featureOptions = PreferIntrinsicTypeEverywhere; + await TestMissingInRegularAndScriptAsync( """ class A { [|System.IntPtr|] i; } - """; - var featureOptions = PreferIntrinsicTypeEverywhere; - await TestMissingInRegularAndScriptAsync( - source, new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10), options: featureOptions)); + """, new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10), options: featureOptions)); } [Fact] @@ -7278,9 +6745,8 @@ await TestMissingInRegularAndScriptAsync( [InlineData(LanguageVersion.CSharp9)] [InlineData(LanguageVersion.CSharp10)] [InlineData(LanguageVersion.CSharp11)] - public async Task TestNint1_WithNumericIntPtr_NoRuntimeSupport(LanguageVersion version) - { - await TestMissingInRegularAndScriptAsync($$""" + public Task TestNint1_WithNumericIntPtr_NoRuntimeSupport(LanguageVersion version) + => TestMissingInRegularAndScriptAsync($$""" class A @@ -7290,21 +6756,18 @@ await TestMissingInRegularAndScriptAsync($$""" """, new TestParameters(options: PreferIntrinsicTypeEverywhere)); - } [Fact] public async Task TestNUint1_NoNumericIntPtr_CSharp10_NoRuntimeSupport() { - var source = + var featureOptions = PreferIntrinsicTypeEverywhere; + await TestMissingInRegularAndScriptAsync( """ class A { [|System.UIntPtr|] i; } - """; - var featureOptions = PreferIntrinsicTypeEverywhere; - await TestMissingInRegularAndScriptAsync( - source, new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10), options: featureOptions)); + """, new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10), options: featureOptions)); } [Fact] @@ -7348,9 +6811,8 @@ await TestMissingInRegularAndScriptAsync( } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75162")] - public async Task TestEditorBrowsable1() - { - await TestMissingInRegularAndScriptAsync(""" + public Task TestEditorBrowsable1() + => TestMissingInRegularAndScriptAsync(""" using System.ComponentModel; [EditorBrowsable(EditorBrowsableState.Never)] @@ -7369,7 +6831,6 @@ void M() } } """); - } private async Task TestWithPredefinedTypeOptionsAsync(string code, string expected, int index = 0) => await TestInRegularAndScript1Async(code, expected, index, new TestParameters(options: PreferIntrinsicTypeEverywhere)); diff --git a/src/Features/CSharpTest/SimplifyTypeNames/SimplifyTypeNamesTests_FixAllTests.cs b/src/Features/CSharpTest/SimplifyTypeNames/SimplifyTypeNamesTests_FixAllTests.cs index 66f53a4525808..7992b4676cddb 100644 --- a/src/Features/CSharpTest/SimplifyTypeNames/SimplifyTypeNamesTests_FixAllTests.cs +++ b/src/Features/CSharpTest/SimplifyTypeNames/SimplifyTypeNamesTests_FixAllTests.cs @@ -18,578 +18,562 @@ public partial class SimplifyTypeNamesTests : AbstractCSharpDiagnosticProviderBa [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInDocument() - { - var input = @" - - - -using System; - -class Program -{ - static System.Int32 F(System.Int32 x, System.Int16 y) - { - {|FixAllInDocument:System.Int32|} i1 = 0; - System.Int16 s1 = 0; - System.Int32 i2 = 0; - return i1 + s1 + i2; - } -} - - -using System; - -class Program2 -{ - static System.Int32 F(System.Int32 x, System.Int16 y) - { - System.Int32 i1 = 0; - System.Int16 s1 = 0; - System.Int32 i2 = 0; - return i1 + s1 + i2; - } -} - - - - -using System; - -class Program2 -{ - static System.Int32 F(System.Int32 x, System.Int16 y) - { - System.Int32 i1 = 0; - System.Int16 s1 = 0; - System.Int32 i2 = 0; - return i1 + s1 + i2; - } -} - - -"; - - var expected = @" - - - -using System; - -class Program -{ - static int F(int x, short y) - { - int i1 = 0; - short s1 = 0; - int i2 = 0; - return i1 + s1 + i2; - } -} - - -using System; - -class Program2 -{ - static System.Int32 F(System.Int32 x, System.Int16 y) - { - System.Int32 i1 = 0; - System.Int16 s1 = 0; - System.Int32 i2 = 0; - return i1 + s1 + i2; - } -} - - - - -using System; - -class Program2 -{ - static System.Int32 F(System.Int32 x, System.Int16 y) - { - System.Int32 i1 = 0; - System.Int16 s1 = 0; - System.Int32 i2 = 0; - return i1 + s1 + i2; - } -} - - -"; - - await TestInRegularAndScriptAsync(input, expected, options: PreferIntrinsicTypeEverywhere); - } + public Task TestFixAllInDocument() + => TestInRegularAndScriptAsync(""" + + + + using System; + + class Program + { + static System.Int32 F(System.Int32 x, System.Int16 y) + { + {|FixAllInDocument:System.Int32|} i1 = 0; + System.Int16 s1 = 0; + System.Int32 i2 = 0; + return i1 + s1 + i2; + } + } + + + using System; + + class Program2 + { + static System.Int32 F(System.Int32 x, System.Int16 y) + { + System.Int32 i1 = 0; + System.Int16 s1 = 0; + System.Int32 i2 = 0; + return i1 + s1 + i2; + } + } + + + + + using System; + + class Program2 + { + static System.Int32 F(System.Int32 x, System.Int16 y) + { + System.Int32 i1 = 0; + System.Int16 s1 = 0; + System.Int32 i2 = 0; + return i1 + s1 + i2; + } + } + + + + """, """ + + + + using System; + + class Program + { + static int F(int x, short y) + { + int i1 = 0; + short s1 = 0; + int i2 = 0; + return i1 + s1 + i2; + } + } + + + using System; + + class Program2 + { + static System.Int32 F(System.Int32 x, System.Int16 y) + { + System.Int32 i1 = 0; + System.Int16 s1 = 0; + System.Int32 i2 = 0; + return i1 + s1 + i2; + } + } + + + + + using System; + + class Program2 + { + static System.Int32 F(System.Int32 x, System.Int16 y) + { + System.Int32 i1 = 0; + System.Int16 s1 = 0; + System.Int32 i2 = 0; + return i1 + s1 + i2; + } + } + + + + """, options: PreferIntrinsicTypeEverywhere); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInProject() - { - var input = @" - - - -using System; - -class Program -{ - static System.Int32 F(System.Int32 x, System.Int16 y) - { - {|FixAllInProject:System.Int32|} i1 = 0; - System.Int16 s1 = 0; - System.Int32 i2 = 0; - return i1 + s1 + i2; - } -} - - -using System; - -class Program2 -{ - static System.Int32 F(System.Int32 x, System.Int16 y) - { - System.Int32 i1 = 0; - System.Int16 s1 = 0; - System.Int32 i2 = 0; - return i1 + s1 + i2; - } -} - - - - -using System; - -class Program2 -{ - static System.Int32 F(System.Int32 x, System.Int16 y) - { - System.Int32 i1 = 0; - System.Int16 s1 = 0; - System.Int32 i2 = 0; - return i1 + s1 + i2; - } -} - - -"; - - var expected = @" - - - -using System; - -class Program -{ - static int F(int x, short y) - { - int i1 = 0; - short s1 = 0; - int i2 = 0; - return i1 + s1 + i2; - } -} - - -using System; - -class Program2 -{ - static int F(int x, short y) - { - int i1 = 0; - short s1 = 0; - int i2 = 0; - return i1 + s1 + i2; - } -} - - - - -using System; - -class Program2 -{ - static System.Int32 F(System.Int32 x, System.Int16 y) - { - System.Int32 i1 = 0; - System.Int16 s1 = 0; - System.Int32 i2 = 0; - return i1 + s1 + i2; - } -} - - -"; - - await TestInRegularAndScriptAsync(input, expected, options: PreferIntrinsicTypeEverywhere); - } + public Task TestFixAllInProject() + => TestInRegularAndScriptAsync(""" + + + + using System; + + class Program + { + static System.Int32 F(System.Int32 x, System.Int16 y) + { + {|FixAllInProject:System.Int32|} i1 = 0; + System.Int16 s1 = 0; + System.Int32 i2 = 0; + return i1 + s1 + i2; + } + } + + + using System; + + class Program2 + { + static System.Int32 F(System.Int32 x, System.Int16 y) + { + System.Int32 i1 = 0; + System.Int16 s1 = 0; + System.Int32 i2 = 0; + return i1 + s1 + i2; + } + } + + + + + using System; + + class Program2 + { + static System.Int32 F(System.Int32 x, System.Int16 y) + { + System.Int32 i1 = 0; + System.Int16 s1 = 0; + System.Int32 i2 = 0; + return i1 + s1 + i2; + } + } + + + + """, """ + + + + using System; + + class Program + { + static int F(int x, short y) + { + int i1 = 0; + short s1 = 0; + int i2 = 0; + return i1 + s1 + i2; + } + } + + + using System; + + class Program2 + { + static int F(int x, short y) + { + int i1 = 0; + short s1 = 0; + int i2 = 0; + return i1 + s1 + i2; + } + } + + + + + using System; + + class Program2 + { + static System.Int32 F(System.Int32 x, System.Int16 y) + { + System.Int32 i1 = 0; + System.Int16 s1 = 0; + System.Int32 i2 = 0; + return i1 + s1 + i2; + } + } + + + + """, options: PreferIntrinsicTypeEverywhere); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInSolution() - { - var input = @" - - - -using System; - -class Program -{ - static System.Int32 F(System.Int32 x, System.Int16 y) - { - {|FixAllInSolution:System.Int32|} i1 = 0; - System.Int16 s1 = 0; - System.Int32 i2 = 0; - return i1 + s1 + i2; - } -} - - -using System; - -class Program2 -{ - static System.Int32 F(System.Int32 x, System.Int16 y) - { - System.Int32 i1 = 0; - System.Int16 s1 = 0; - System.Int32 i2 = 0; - return i1 + s1 + i2; - } -} - - - - -using System; - -class Program2 -{ - static System.Int32 F(System.Int32 x, System.Int16 y) - { - System.Int32 i1 = 0; - System.Int16 s1 = 0; - System.Int32 i2 = 0; - return i1 + s1 + i2; - } -} - - -"; - - var expected = @" - - - -using System; - -class Program -{ - static int F(int x, short y) - { - int i1 = 0; - short s1 = 0; - int i2 = 0; - return i1 + s1 + i2; - } -} - - -using System; - -class Program2 -{ - static int F(int x, short y) - { - int i1 = 0; - short s1 = 0; - int i2 = 0; - return i1 + s1 + i2; - } -} - - - - -using System; - -class Program2 -{ - static int F(int x, short y) - { - int i1 = 0; - short s1 = 0; - int i2 = 0; - return i1 + s1 + i2; - } -} - - -"; - - await TestInRegularAndScriptAsync(input, expected, options: PreferIntrinsicTypeEverywhere); - } + public Task TestFixAllInSolution() + => TestInRegularAndScriptAsync(""" + + + + using System; + + class Program + { + static System.Int32 F(System.Int32 x, System.Int16 y) + { + {|FixAllInSolution:System.Int32|} i1 = 0; + System.Int16 s1 = 0; + System.Int32 i2 = 0; + return i1 + s1 + i2; + } + } + + + using System; + + class Program2 + { + static System.Int32 F(System.Int32 x, System.Int16 y) + { + System.Int32 i1 = 0; + System.Int16 s1 = 0; + System.Int32 i2 = 0; + return i1 + s1 + i2; + } + } + + + + + using System; + + class Program2 + { + static System.Int32 F(System.Int32 x, System.Int16 y) + { + System.Int32 i1 = 0; + System.Int16 s1 = 0; + System.Int32 i2 = 0; + return i1 + s1 + i2; + } + } + + + + """, """ + + + + using System; + + class Program + { + static int F(int x, short y) + { + int i1 = 0; + short s1 = 0; + int i2 = 0; + return i1 + s1 + i2; + } + } + + + using System; + + class Program2 + { + static int F(int x, short y) + { + int i1 = 0; + short s1 = 0; + int i2 = 0; + return i1 + s1 + i2; + } + } + + + + + using System; + + class Program2 + { + static int F(int x, short y) + { + int i1 = 0; + short s1 = 0; + int i2 = 0; + return i1 + s1 + i2; + } + } + + + + """, options: PreferIntrinsicTypeEverywhere); [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] - public async Task TestFixAllInSolution_SimplifyMemberAccess() - { - var input = @" - - - -using System; -class ProgramA -{ - private int x = 0; - private int y = 0; - private int z = 0; - - private System.Int32 F(System.Int32 p1, System.Int16 p2) - { - System.Int32 i1 = this.x; - System.Int16 s1 = this.y; - System.Int32 i2 = this.z; - {|FixAllInSolution:System.Console.Write|}(i1 + s1 + i2); - System.Console.WriteLine(i1 + s1 + i2); - System.Exception ex = null; - return i1 + s1 + i2; - } -} - -class ProgramB -{ - private int x2 = 0; - private int y2 = 0; - private int z2 = 0; - - private System.Int32 F(System.Int32 p1, System.Int16 p2) - { - System.Int32 i1 = this.x2; - System.Int16 s1 = this.y2; - System.Int32 i2 = this.z2; - System.Console.Write(i1 + s1 + i2); - System.Console.WriteLine(i1 + s1 + i2); - System.Exception ex = null; - return i1 + s1 + i2; - } -} - - -using System; -class ProgramA2 -{ - private int x = 0; - private int y = 0; - private int z = 0; - - private System.Int32 F(System.Int32 p1, System.Int16 p2) - { - System.Int32 i1 = this.x; - System.Int16 s1 = this.y; - System.Int32 i2 = this.z; - System.Console.Write(i1 + s1 + i2); - System.Console.WriteLine(i1 + s1 + i2); - System.Exception ex = null; - return i1 + s1 + i2; - } -} - -class ProgramB2 -{ - private int x2 = 0; - private int y2 = 0; - private int z2 = 0; - - private System.Int32 F(System.Int32 p1, System.Int16 p2) - { - System.Int32 i1 = this.x2; - System.Int16 s1 = this.y2; - System.Int32 i2 = this.z2; - System.Console.Write(i1 + s1 + i2); - System.Console.WriteLine(i1 + s1 + i2); - System.Exception ex = null; - return i1 + s1 + i2; - } -} - - - - -using System; -class ProgramA3 -{ - private int x = 0; - private int y = 0; - private int z = 0; - - private System.Int32 F(System.Int32 p1, System.Int16 p2) - { - System.Int32 i1 = this.x; - System.Int16 s1 = this.y; - System.Int32 i2 = this.z; - System.Console.Write(i1 + s1 + i2); - System.Console.WriteLine(i1 + s1 + i2); - System.Exception ex = null; - return i1 + s1 + i2; - } -} - -class ProgramB3 -{ - private int x2 = 0; - private int y2 = 0; - private int z2 = 0; - - private System.Int32 F(System.Int32 p1, System.Int16 p2) - { - System.Int32 i1 = this.x2; - System.Int16 s1 = this.y2; - System.Int32 i2 = this.z2; - System.Console.Write(i1 + s1 + i2); - System.Console.WriteLine(i1 + s1 + i2); - System.Exception ex = null; - return i1 + s1 + i2; - } -} - - -"; - - var expected = @" - - - -using System; -class ProgramA -{ - private int x = 0; - private int y = 0; - private int z = 0; - - private System.Int32 F(System.Int32 p1, System.Int16 p2) - { - System.Int32 i1 = this.x; - System.Int16 s1 = this.y; - System.Int32 i2 = this.z; - Console.Write(i1 + s1 + i2); - Console.WriteLine(i1 + s1 + i2); - System.Exception ex = null; - return i1 + s1 + i2; - } -} - -class ProgramB -{ - private int x2 = 0; - private int y2 = 0; - private int z2 = 0; - - private System.Int32 F(System.Int32 p1, System.Int16 p2) - { - System.Int32 i1 = this.x2; - System.Int16 s1 = this.y2; - System.Int32 i2 = this.z2; - Console.Write(i1 + s1 + i2); - Console.WriteLine(i1 + s1 + i2); - System.Exception ex = null; - return i1 + s1 + i2; - } -} - - -using System; -class ProgramA2 -{ - private int x = 0; - private int y = 0; - private int z = 0; - - private System.Int32 F(System.Int32 p1, System.Int16 p2) - { - System.Int32 i1 = this.x; - System.Int16 s1 = this.y; - System.Int32 i2 = this.z; - Console.Write(i1 + s1 + i2); - Console.WriteLine(i1 + s1 + i2); - System.Exception ex = null; - return i1 + s1 + i2; - } -} - -class ProgramB2 -{ - private int x2 = 0; - private int y2 = 0; - private int z2 = 0; - - private System.Int32 F(System.Int32 p1, System.Int16 p2) - { - System.Int32 i1 = this.x2; - System.Int16 s1 = this.y2; - System.Int32 i2 = this.z2; - Console.Write(i1 + s1 + i2); - Console.WriteLine(i1 + s1 + i2); - System.Exception ex = null; - return i1 + s1 + i2; - } -} - - - - -using System; -class ProgramA3 -{ - private int x = 0; - private int y = 0; - private int z = 0; - - private System.Int32 F(System.Int32 p1, System.Int16 p2) - { - System.Int32 i1 = this.x; - System.Int16 s1 = this.y; - System.Int32 i2 = this.z; - Console.Write(i1 + s1 + i2); - Console.WriteLine(i1 + s1 + i2); - System.Exception ex = null; - return i1 + s1 + i2; - } -} - -class ProgramB3 -{ - private int x2 = 0; - private int y2 = 0; - private int z2 = 0; - - private System.Int32 F(System.Int32 p1, System.Int16 p2) - { - System.Int32 i1 = this.x2; - System.Int16 s1 = this.y2; - System.Int32 i2 = this.z2; - Console.Write(i1 + s1 + i2); - Console.WriteLine(i1 + s1 + i2); - System.Exception ex = null; - return i1 + s1 + i2; - } -} - - -"; - - await TestInRegularAndScriptAsync(input, expected); - } + public Task TestFixAllInSolution_SimplifyMemberAccess() + => TestInRegularAndScriptAsync(""" + + + + using System; + class ProgramA + { + private int x = 0; + private int y = 0; + private int z = 0; + + private System.Int32 F(System.Int32 p1, System.Int16 p2) + { + System.Int32 i1 = this.x; + System.Int16 s1 = this.y; + System.Int32 i2 = this.z; + {|FixAllInSolution:System.Console.Write|}(i1 + s1 + i2); + System.Console.WriteLine(i1 + s1 + i2); + System.Exception ex = null; + return i1 + s1 + i2; + } + } + + class ProgramB + { + private int x2 = 0; + private int y2 = 0; + private int z2 = 0; + + private System.Int32 F(System.Int32 p1, System.Int16 p2) + { + System.Int32 i1 = this.x2; + System.Int16 s1 = this.y2; + System.Int32 i2 = this.z2; + System.Console.Write(i1 + s1 + i2); + System.Console.WriteLine(i1 + s1 + i2); + System.Exception ex = null; + return i1 + s1 + i2; + } + } + + + using System; + class ProgramA2 + { + private int x = 0; + private int y = 0; + private int z = 0; + + private System.Int32 F(System.Int32 p1, System.Int16 p2) + { + System.Int32 i1 = this.x; + System.Int16 s1 = this.y; + System.Int32 i2 = this.z; + System.Console.Write(i1 + s1 + i2); + System.Console.WriteLine(i1 + s1 + i2); + System.Exception ex = null; + return i1 + s1 + i2; + } + } + + class ProgramB2 + { + private int x2 = 0; + private int y2 = 0; + private int z2 = 0; + + private System.Int32 F(System.Int32 p1, System.Int16 p2) + { + System.Int32 i1 = this.x2; + System.Int16 s1 = this.y2; + System.Int32 i2 = this.z2; + System.Console.Write(i1 + s1 + i2); + System.Console.WriteLine(i1 + s1 + i2); + System.Exception ex = null; + return i1 + s1 + i2; + } + } + + + + + using System; + class ProgramA3 + { + private int x = 0; + private int y = 0; + private int z = 0; + + private System.Int32 F(System.Int32 p1, System.Int16 p2) + { + System.Int32 i1 = this.x; + System.Int16 s1 = this.y; + System.Int32 i2 = this.z; + System.Console.Write(i1 + s1 + i2); + System.Console.WriteLine(i1 + s1 + i2); + System.Exception ex = null; + return i1 + s1 + i2; + } + } + + class ProgramB3 + { + private int x2 = 0; + private int y2 = 0; + private int z2 = 0; + + private System.Int32 F(System.Int32 p1, System.Int16 p2) + { + System.Int32 i1 = this.x2; + System.Int16 s1 = this.y2; + System.Int32 i2 = this.z2; + System.Console.Write(i1 + s1 + i2); + System.Console.WriteLine(i1 + s1 + i2); + System.Exception ex = null; + return i1 + s1 + i2; + } + } + + + + """, """ + + + + using System; + class ProgramA + { + private int x = 0; + private int y = 0; + private int z = 0; + + private System.Int32 F(System.Int32 p1, System.Int16 p2) + { + System.Int32 i1 = this.x; + System.Int16 s1 = this.y; + System.Int32 i2 = this.z; + Console.Write(i1 + s1 + i2); + Console.WriteLine(i1 + s1 + i2); + System.Exception ex = null; + return i1 + s1 + i2; + } + } + + class ProgramB + { + private int x2 = 0; + private int y2 = 0; + private int z2 = 0; + + private System.Int32 F(System.Int32 p1, System.Int16 p2) + { + System.Int32 i1 = this.x2; + System.Int16 s1 = this.y2; + System.Int32 i2 = this.z2; + Console.Write(i1 + s1 + i2); + Console.WriteLine(i1 + s1 + i2); + System.Exception ex = null; + return i1 + s1 + i2; + } + } + + + using System; + class ProgramA2 + { + private int x = 0; + private int y = 0; + private int z = 0; + + private System.Int32 F(System.Int32 p1, System.Int16 p2) + { + System.Int32 i1 = this.x; + System.Int16 s1 = this.y; + System.Int32 i2 = this.z; + Console.Write(i1 + s1 + i2); + Console.WriteLine(i1 + s1 + i2); + System.Exception ex = null; + return i1 + s1 + i2; + } + } + + class ProgramB2 + { + private int x2 = 0; + private int y2 = 0; + private int z2 = 0; + + private System.Int32 F(System.Int32 p1, System.Int16 p2) + { + System.Int32 i1 = this.x2; + System.Int16 s1 = this.y2; + System.Int32 i2 = this.z2; + Console.Write(i1 + s1 + i2); + Console.WriteLine(i1 + s1 + i2); + System.Exception ex = null; + return i1 + s1 + i2; + } + } + + + + + using System; + class ProgramA3 + { + private int x = 0; + private int y = 0; + private int z = 0; + + private System.Int32 F(System.Int32 p1, System.Int16 p2) + { + System.Int32 i1 = this.x; + System.Int16 s1 = this.y; + System.Int32 i2 = this.z; + Console.Write(i1 + s1 + i2); + Console.WriteLine(i1 + s1 + i2); + System.Exception ex = null; + return i1 + s1 + i2; + } + } + + class ProgramB3 + { + private int x2 = 0; + private int y2 = 0; + private int z2 = 0; + + private System.Int32 F(System.Int32 p1, System.Int16 p2) + { + System.Int32 i1 = this.x2; + System.Int16 s1 = this.y2; + System.Int32 i2 = this.z2; + Console.Write(i1 + s1 + i2); + Console.WriteLine(i1 + s1 + i2); + System.Exception ex = null; + return i1 + s1 + i2; + } + } + + + + """); #endregion } diff --git a/src/Features/CSharpTest/Snippets/AbstractCSharpAutoPropertySnippetProviderTests.cs b/src/Features/CSharpTest/Snippets/AbstractCSharpAutoPropertySnippetProviderTests.cs index 81c5812d9be3a..2be24b3abdbae 100644 --- a/src/Features/CSharpTest/Snippets/AbstractCSharpAutoPropertySnippetProviderTests.cs +++ b/src/Features/CSharpTest/Snippets/AbstractCSharpAutoPropertySnippetProviderTests.cs @@ -16,70 +16,58 @@ public abstract class AbstractCSharpAutoPropertySnippetProviderTests : AbstractC protected abstract string DefaultPropertyBlockText { get; } [Fact] - public async Task NoSnippetInBlockNamespaceTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoSnippetInBlockNamespaceTest() + => VerifySnippetIsAbsentAsync(""" namespace Namespace { $$ } """); - } [Fact] - public async Task NoSnippetInFileScopedNamespaceTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoSnippetInFileScopedNamespaceTest() + => VerifySnippetIsAbsentAsync(""" namespace Namespace $$ """); - } [Fact] - public async Task NoSnippetInTopLevelContextTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoSnippetInTopLevelContextTest() + => VerifySnippetIsAbsentAsync(""" System.Console.WriteLine(); $$ """); - } [Fact] - public async Task InsertSnippetInClassTest() - { - await VerifyDefaultPropertyAsync(""" + public Task InsertSnippetInClassTest() + => VerifyDefaultPropertyAsync(""" class MyClass { $$ } """); - } [Theory] [InlineData("record")] [InlineData("record struct")] [InlineData("record class")] - public async Task InsertSnippetInRecordTest(string recordType) - { - await VerifyDefaultPropertyAsync($$""" + public Task InsertSnippetInRecordTest(string recordType) + => VerifyDefaultPropertyAsync($$""" {{recordType}} MyRecord { $$ } """); - } [Fact] - public async Task InsertSnippetInStructTest() - { - await VerifyDefaultPropertyAsync(""" + public Task InsertSnippetInStructTest() + => VerifyDefaultPropertyAsync(""" struct MyStruct { $$ } """); - } [Fact] public abstract Task InsertSnippetInReadonlyStructTest(); @@ -96,32 +84,27 @@ struct MyStruct public abstract Task VerifySnippetInInterfaceTest(); [Fact] - public async Task InsertSnippetNamingTest() - { - await VerifyDefaultPropertyAsync(""" + public Task InsertSnippetNamingTest() + => VerifyDefaultPropertyAsync(""" class MyClass { public int MyProperty { get; set; } $$ } """, "MyProperty1"); - } [Fact] - public async Task NoSnippetInEnumTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoSnippetInEnumTest() + => VerifySnippetIsAbsentAsync(""" enum MyEnum { $$ } """); - } [Fact] - public async Task NoSnippetInMethodTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoSnippetInMethodTest() + => VerifySnippetIsAbsentAsync(""" class Program { public void Method() @@ -130,12 +113,10 @@ public void Method() } } """); - } [Fact] - public async Task NoSnippetInConstructorTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoSnippetInConstructorTest() + => VerifySnippetIsAbsentAsync(""" class Program { public Program() @@ -144,17 +125,14 @@ public Program() } } """); - } - public virtual async Task InsertSnippetAfterAllowedAccessibilityModifierTest(string modifier) - { - await VerifyPropertyAsync($$""" + public virtual Task InsertSnippetAfterAllowedAccessibilityModifierTest(string modifier) + => VerifyPropertyAsync($$""" class Program { {{modifier}} $$ } """, $$"""{|0:int|} {|1:MyProperty|} {{DefaultPropertyBlockText}}"""); - } protected async Task VerifyPropertyAsync([StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string markup, string propertyMarkup) { diff --git a/src/Features/CSharpTest/Snippets/AbstractCSharpConditionalBlockSnippetProviderTests.cs b/src/Features/CSharpTest/Snippets/AbstractCSharpConditionalBlockSnippetProviderTests.cs index 1e17af2b5fce3..befbdfa297970 100644 --- a/src/Features/CSharpTest/Snippets/AbstractCSharpConditionalBlockSnippetProviderTests.cs +++ b/src/Features/CSharpTest/Snippets/AbstractCSharpConditionalBlockSnippetProviderTests.cs @@ -13,9 +13,8 @@ namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Snippets; public abstract class AbstractCSharpConditionalBlockSnippetProviderTests : AbstractCSharpSnippetProviderTests { [Fact] - public async Task InsertSnippetInMethodTest() - { - await VerifySnippetAsync(""" + public Task InsertSnippetInMethodTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -35,12 +34,10 @@ public void Method() } } """); - } [Fact] - public async Task InsertSnippetInGlobalContextTest() - { - await VerifySnippetAsync(""" + public Task InsertSnippetInGlobalContextTest() + => VerifySnippetAsync(""" $$ """, $$""" {{SnippetIdentifier}} ({|0:true|}) @@ -48,33 +45,27 @@ await VerifySnippetAsync(""" $$ } """); - } [Fact] - public async Task NoSnippetInBlockNamespaceTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoSnippetInBlockNamespaceTest() + => VerifySnippetIsAbsentAsync(""" namespace Namespace { $$ } """); - } [Fact] - public async Task NoSnippetInFileScopedNamespaceTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoSnippetInFileScopedNamespaceTest() + => VerifySnippetIsAbsentAsync(""" namespace Namespace; $$ """); - } [Fact] - public async Task InsertSnippetInConstructorTest() - { - await VerifySnippetAsync(""" + public Task InsertSnippetInConstructorTest() + => VerifySnippetAsync(""" class Program { public Program() @@ -96,12 +87,10 @@ public Program() } } """); - } [Fact] - public async Task InsertSnippetInLocalFunctionTest() - { - await VerifySnippetAsync(""" + public Task InsertSnippetInLocalFunctionTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -129,12 +118,10 @@ void LocalMethod() } } """); - } [Fact] - public async Task InsertSnippetInAnonymousFunctionTest() - { - await VerifySnippetAsync(""" + public Task InsertSnippetInAnonymousFunctionTest() + => VerifySnippetAsync(""" public delegate void Print(int value); static void Main(string[] args) @@ -160,12 +147,10 @@ static void Main(string[] args) } """); - } [Fact] - public async Task InsertSnippetInParenthesizedLambdaExpressionTest() - { - await VerifySnippetAsync(""" + public Task InsertSnippetInParenthesizedLambdaExpressionTest() + => VerifySnippetAsync(""" using System; Func testForEquality = (x, y) => @@ -185,12 +170,10 @@ await VerifySnippetAsync(""" return x == y; }; """); - } [Fact] - public async Task NoSnippetInSwitchExpression() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoSnippetInSwitchExpression() + => VerifySnippetIsAbsentAsync(""" class Program { public void Method() @@ -208,12 +191,10 @@ public void Method() } } """); - } [Fact] - public async Task NoSnippetInSingleLambdaExpression() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoSnippetInSingleLambdaExpression() + => VerifySnippetIsAbsentAsync(""" using System; class Program @@ -224,12 +205,10 @@ public void Method() } } """); - } [Fact] - public async Task NoSnippetInStringTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoSnippetInStringTest() + => VerifySnippetIsAbsentAsync(""" class Program { public void Method() @@ -238,12 +217,10 @@ public void Method() } } """); - } [Fact] - public async Task NoSnippetInConstructorArgumentsTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoSnippetInConstructorArgumentsTest() + => VerifySnippetIsAbsentAsync(""" class Program { public void Method() @@ -259,12 +236,10 @@ public Test(string val) } } """); - } [Fact] - public async Task NoSnippetInParameterListTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoSnippetInParameterListTest() + => VerifySnippetIsAbsentAsync(""" class Program { public void Method(int x, $$) @@ -272,12 +247,10 @@ public void Method(int x, $$) } } """); - } [Fact] - public async Task NoSnippetInRecordDeclarationTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoSnippetInRecordDeclarationTest() + => VerifySnippetIsAbsentAsync(""" public record Person { $$ @@ -285,12 +258,10 @@ public record Person public string LastName { get; init; } }; """); - } [Fact] - public async Task NoSnippetInVariableDeclarationTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoSnippetInVariableDeclarationTest() + => VerifySnippetIsAbsentAsync(""" class Program { public void Method() @@ -299,12 +270,10 @@ public void Method() } } """); - } [Fact] - public async Task InsertInlineSnippetForCorrectTypeTest() - { - await VerifySnippetAsync(""" + public Task InsertInlineSnippetForCorrectTypeTest() + => VerifySnippetAsync(""" class Program { void M(bool arg) @@ -324,12 +293,10 @@ void M(bool arg) } } """); - } [Fact] - public async Task NoInlineSnippetForIncorrectTypeTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInlineSnippetForIncorrectTypeTest() + => VerifySnippetIsAbsentAsync(""" class Program { void M(int arg) @@ -338,12 +305,10 @@ void M(int arg) } } """); - } [Fact] - public async Task NoInlineSnippetWhenNotDirectlyExpressionStatementTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInlineSnippetWhenNotDirectlyExpressionStatementTest() + => VerifySnippetIsAbsentAsync(""" class Program { void M(bool arg) @@ -352,15 +317,13 @@ void M(bool arg) } } """); - } [Theory] [InlineData("// comment")] [InlineData("/* comment */")] [InlineData("#region test")] - public async Task CorrectlyDealWithLeadingTriviaInInlineSnippetInMethodTest1(string trivia) - { - await VerifySnippetAsync($$""" + public Task CorrectlyDealWithLeadingTriviaInInlineSnippetInMethodTest1(string trivia) + => VerifySnippetAsync($$""" class Program { void M(bool arg) @@ -382,15 +345,13 @@ void M(bool arg) } } """); - } [Theory] [InlineData("#if true")] [InlineData("#pragma warning disable CS0108")] [InlineData("#nullable enable")] - public async Task CorrectlyDealWithLeadingTriviaInInlineSnippetInMethodTest2(string trivia) - { - await VerifySnippetAsync($$""" + public Task CorrectlyDealWithLeadingTriviaInInlineSnippetInMethodTest2(string trivia) + => VerifySnippetAsync($$""" class Program { void M(bool arg) @@ -412,14 +373,12 @@ void M(bool arg) } } """); - } [Theory] [InlineData("// comment")] [InlineData("/* comment */")] - public async Task CorrectlyDealWithLeadingTriviaInInlineSnippetInGlobalStatementTest1(string trivia) - { - await VerifySnippetAsync($""" + public Task CorrectlyDealWithLeadingTriviaInInlineSnippetInGlobalStatementTest1(string trivia) + => VerifySnippetAsync($""" {trivia} true.$$ """, $$""" @@ -429,16 +388,14 @@ await VerifySnippetAsync($""" $$ } """); - } [Theory] [InlineData("#region test")] [InlineData("#if true")] [InlineData("#pragma warning disable CS0108")] [InlineData("#nullable enable")] - public async Task CorrectlyDealWithLeadingTriviaInInlineSnippetInGlobalStatementTest2(string trivia) - { - await VerifySnippetAsync($""" + public Task CorrectlyDealWithLeadingTriviaInInlineSnippetInGlobalStatementTest2(string trivia) + => VerifySnippetAsync($""" {trivia} true.$$ """, $$""" @@ -449,12 +406,10 @@ await VerifySnippetAsync($""" $$ } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69598")] - public async Task InsertInlineSnippetWhenDottingBeforeContextualKeywordTest1() - { - await VerifySnippetAsync(""" + public Task InsertInlineSnippetWhenDottingBeforeContextualKeywordTest1() + => VerifySnippetAsync(""" class C { void M(bool flag) @@ -476,12 +431,10 @@ void M(bool flag) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69598")] - public async Task InsertInlineSnippetWhenDottingBeforeContextualKeywordTest2() - { - await VerifySnippetAsync(""" + public Task InsertInlineSnippetWhenDottingBeforeContextualKeywordTest2() + => VerifySnippetAsync(""" class C { async void M(bool flag, Task t) @@ -503,15 +456,13 @@ async void M(bool flag, Task t) } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/69598")] [InlineData("Task")] [InlineData("Task")] [InlineData("System.Threading.Tasks.Task")] - public async Task InsertInlineSnippetWhenDottingBeforeNameSyntaxTest(string nameSyntax) - { - await VerifySnippetAsync($$""" + public Task InsertInlineSnippetWhenDottingBeforeNameSyntaxTest(string nameSyntax) + => VerifySnippetAsync($$""" using System.Threading.Tasks; class C @@ -537,12 +488,10 @@ void M(bool flag) } } """); - } [Fact] - public async Task InsertInlineSnippetWhenDottingBeforeMemberAccessExpressionOnTheNextLineTest() - { - await VerifySnippetAsync(""" + public Task InsertInlineSnippetWhenDottingBeforeMemberAccessExpressionOnTheNextLineTest() + => VerifySnippetAsync(""" using System; class C @@ -568,12 +517,10 @@ void M(bool flag) } } """); - } [Fact] - public async Task NoInlineSnippetWhenDottingBeforeMemberAccessExpressionOnTheSameLineTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInlineSnippetWhenDottingBeforeMemberAccessExpressionOnTheSameLineTest() + => VerifySnippetIsAbsentAsync(""" class C { void M(bool flag) @@ -582,12 +529,10 @@ void M(bool flag) } } """); - } [Fact] - public async Task NoInlineSnippetWhenDottingBeforeContextualKeywordOnTheSameLineTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInlineSnippetWhenDottingBeforeContextualKeywordOnTheSameLineTest() + => VerifySnippetIsAbsentAsync(""" class C { void M(bool flag) @@ -596,12 +541,10 @@ void M(bool flag) } } """); - } [Fact] - public async Task NoInlineSnippetForTypeItselfTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInlineSnippetForTypeItselfTest() + => VerifySnippetIsAbsentAsync(""" class C { void M() @@ -610,12 +553,10 @@ void M() } } """); - } [Fact] - public async Task NoInlineSnippetForTypeItselfTest_Parenthesized() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInlineSnippetForTypeItselfTest_Parenthesized() + => VerifySnippetIsAbsentAsync(""" class C { void M() @@ -624,12 +565,10 @@ void M() } } """); - } [Fact] - public async Task NoInlineSnippetForTypeItselfTest_BeforeContextualKeyword() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInlineSnippetForTypeItselfTest_BeforeContextualKeyword() + => VerifySnippetIsAbsentAsync(""" using System.Threading.Tasks; class C @@ -641,5 +580,4 @@ async void M() } } """); - } } diff --git a/src/Features/CSharpTest/Snippets/CSharpClassSnippetProviderTests.cs b/src/Features/CSharpTest/Snippets/CSharpClassSnippetProviderTests.cs index 605189a8b6fea..e32c70cd92c87 100644 --- a/src/Features/CSharpTest/Snippets/CSharpClassSnippetProviderTests.cs +++ b/src/Features/CSharpTest/Snippets/CSharpClassSnippetProviderTests.cs @@ -15,9 +15,8 @@ public sealed class CSharpClassSnippetProviderTests : AbstractCSharpSnippetProvi protected override string SnippetIdentifier => "class"; [Fact] - public async Task InsertClassSnippetInBlockNamespaceTest() - { - await VerifySnippetAsync(""" + public Task InsertClassSnippetInBlockNamespaceTest() + => VerifySnippetAsync(""" namespace Namespace { $$ @@ -31,12 +30,10 @@ class {|0:MyClass|} } } """); - } [Fact] - public async Task InsertClassSnippetInFileScopedNamespaceTest() - { - await VerifySnippetAsync(""" + public Task InsertClassSnippetInFileScopedNamespaceTest() + => VerifySnippetAsync(""" namespace Namespace; $$ @@ -48,12 +45,10 @@ class {|0:MyClass|} $$ } """); - } [Fact] - public async Task InsertClassSnippetTest() - { - await VerifySnippetAsync(""" + public Task InsertClassSnippetTest() + => VerifySnippetAsync(""" $$ """, """ class {|0:MyClass|} @@ -61,12 +56,10 @@ class {|0:MyClass|} $$ } """); - } [Fact] - public async Task InsertClassTopLevelSnippetTest() - { - await VerifySnippetAsync(""" + public Task InsertClassTopLevelSnippetTest() + => VerifySnippetAsync(""" System.Console.WriteLine(); $$ """, """ @@ -76,12 +69,10 @@ class {|0:MyClass|} $$ } """); - } [Fact] - public async Task InsertClassSnippetInClassTest() - { - await VerifySnippetAsync(""" + public Task InsertClassSnippetInClassTest() + => VerifySnippetAsync(""" class MyClass { $$ @@ -95,12 +86,10 @@ class {|0:MyClass1|} } } """); - } [Fact] - public async Task InsertClassSnippetInRecordTest() - { - await VerifySnippetAsync(""" + public Task InsertClassSnippetInRecordTest() + => VerifySnippetAsync(""" record MyRecord { $$ @@ -114,12 +103,10 @@ class {|0:MyClass|} } } """); - } [Fact] - public async Task InsertClassSnippetInStructTest() - { - await VerifySnippetAsync(""" + public Task InsertClassSnippetInStructTest() + => VerifySnippetAsync(""" struct MyStruct { $$ @@ -133,12 +120,10 @@ class {|0:MyClass|} } } """); - } [Fact] - public async Task InsertClassSnippetInInterfaceTest() - { - await VerifySnippetAsync(""" + public Task InsertClassSnippetInInterfaceTest() + => VerifySnippetAsync(""" interface MyInterface { $$ @@ -152,12 +137,10 @@ class {|0:MyClass|} } } """); - } [Fact] - public async Task InsertClassSnippetWithModifiersTest() - { - await VerifySnippetAsync(""" + public Task InsertClassSnippetWithModifiersTest() + => VerifySnippetAsync(""" $$ """, """ public class {|0:MyClass|} @@ -171,23 +154,19 @@ public class {|0:MyClass|} [*] dotnet_style_require_accessibility_modifiers = always """); - } [Fact] - public async Task NoClassSnippetInEnumTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoClassSnippetInEnumTest() + => VerifySnippetIsAbsentAsync(""" enum MyEnum { $$ } """); - } [Fact] - public async Task NoClassSnippetInMethodTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoClassSnippetInMethodTest() + => VerifySnippetIsAbsentAsync(""" class Program { public void Method() @@ -196,12 +175,10 @@ public void Method() } } """); - } [Fact] - public async Task NoClassSnippetInConstructorTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoClassSnippetInConstructorTest() + => VerifySnippetIsAbsentAsync(""" class Program { public Program() @@ -210,13 +187,11 @@ public Program() } } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.AllAccessibilityModifiers), MemberType = typeof(CommonSnippetTestData))] - public async Task InsertClassSnippetAfterAccessibilityModifier(string modifier) - { - await VerifySnippetAsync($""" + public Task InsertClassSnippetAfterAccessibilityModifier(string modifier) + => VerifySnippetAsync($""" {modifier} $$ """, $$""" {{modifier}} class {|0:MyClass|} @@ -224,13 +199,11 @@ await VerifySnippetAsync($""" $$ } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.AllAccessibilityModifiers), MemberType = typeof(CommonSnippetTestData))] - public async Task InsertClassSnippetAfterAccessibilityModifier_RequireAccessibilityModifiers(string modifier) - { - await VerifySnippetAsync($""" + public Task InsertClassSnippetAfterAccessibilityModifier_RequireAccessibilityModifiers(string modifier) + => VerifySnippetAsync($""" {modifier} $$ """, $$""" {{modifier}} class {|0:MyClass|} @@ -244,16 +217,14 @@ await VerifySnippetAsync($""" [*] dotnet_style_require_accessibility_modifiers = always """); - } [Theory] [InlineData("abstract")] [InlineData("sealed")] [InlineData("static")] [InlineData("unsafe")] - public async Task InsertClassSnippetAfterValidModifiersTest(string modifier) - { - await VerifySnippetAsync($""" + public Task InsertClassSnippetAfterValidModifiersTest(string modifier) + => VerifySnippetAsync($""" {modifier} $$ """, $$""" {{modifier}} class {|0:MyClass|} @@ -261,23 +232,19 @@ await VerifySnippetAsync($""" $$ } """); - } [Theory] [InlineData("ref")] [InlineData("readonly")] - public async Task NoClassSnippetAfterInvalidModifiersTest(string modifier) - { - await VerifySnippetIsAbsentAsync($""" + public Task NoClassSnippetAfterInvalidModifiersTest(string modifier) + => VerifySnippetIsAbsentAsync($""" {modifier} $$ """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/69600")] [MemberData(nameof(CommonSnippetTestData.AllAccessibilityModifiers), MemberType = typeof(CommonSnippetTestData))] - public async Task NoAdditionalAccessibilityModifiersIfAfterPartialKeywordTest(string modifier) - { - await VerifySnippetAsync($""" + public Task NoAdditionalAccessibilityModifiersIfAfterPartialKeywordTest(string modifier) + => VerifySnippetAsync($""" {modifier} partial $$ """, $$""" {{modifier}} partial class {|0:MyClass|} @@ -291,12 +258,10 @@ await VerifySnippetAsync($""" [*] dotnet_style_require_accessibility_modifiers = always """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69600")] - public async Task EnsureCorrectModifierOrderAfterPartialKeywordTest() - { - await VerifySnippetAsync(""" + public Task EnsureCorrectModifierOrderAfterPartialKeywordTest() + => VerifySnippetAsync(""" partial $$ """, """ public partial class {|0:MyClass|} @@ -310,12 +275,10 @@ public partial class {|0:MyClass|} [*] dotnet_style_require_accessibility_modifiers = always """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69600")] - public async Task EnsureCorrectModifierOrderAfterPartialKeywordTest_InvalidPreferredModifiersList() - { - await VerifySnippetAsync(""" + public Task EnsureCorrectModifierOrderAfterPartialKeywordTest_InvalidPreferredModifiersList() + => VerifySnippetAsync(""" partial $$ """, """ public partial class {|0:MyClass|} @@ -331,12 +294,10 @@ public partial class {|0:MyClass|} csharp_preferred_modifier_order = invalid! """); - } [Fact] - public async Task EnsureCorrectModifierOrderFromOptionsTest_PublicModifierBeforeAllOthers() - { - await VerifySnippetAsync(""" + public Task EnsureCorrectModifierOrderFromOptionsTest_PublicModifierBeforeAllOthers() + => VerifySnippetAsync(""" sealed unsafe $$ """, """ public sealed unsafe class {|0:MyClass|} @@ -352,12 +313,10 @@ public sealed unsafe class {|0:MyClass|} csharp_preferred_modifier_order = public,sealed,unsafe """); - } [Fact] - public async Task EnsureCorrectModifierOrderFromOptionsTest_PublicModifierBeforeAllOthers_NotAllModifiersInTheList() - { - await VerifySnippetAsync(""" + public Task EnsureCorrectModifierOrderFromOptionsTest_PublicModifierBeforeAllOthers_NotAllModifiersInTheList() + => VerifySnippetAsync(""" sealed unsafe $$ """, """ public sealed unsafe class {|0:MyClass|} @@ -373,12 +332,10 @@ public sealed unsafe class {|0:MyClass|} csharp_preferred_modifier_order = public,sealed """); - } [Fact] - public async Task EnsureCorrectModifierOrderFromOptionsTest_PublicModifierBetweenOthers() - { - await VerifySnippetAsync(""" + public Task EnsureCorrectModifierOrderFromOptionsTest_PublicModifierBetweenOthers() + => VerifySnippetAsync(""" sealed unsafe $$ """, """ sealed public unsafe class {|0:MyClass|} @@ -394,12 +351,10 @@ sealed public unsafe class {|0:MyClass|} csharp_preferred_modifier_order = sealed,public,unsafe """); - } [Fact] - public async Task EnsureCorrectModifierOrderFromOptionsTest_PublicModifierAfterAllOthers() - { - await VerifySnippetAsync(""" + public Task EnsureCorrectModifierOrderFromOptionsTest_PublicModifierAfterAllOthers() + => VerifySnippetAsync(""" sealed unsafe $$ """, """ sealed unsafe public class {|0:MyClass|} @@ -415,5 +370,4 @@ sealed unsafe public class {|0:MyClass|} csharp_preferred_modifier_order = sealed,unsafe,public """); - } } diff --git a/src/Features/CSharpTest/Snippets/CSharpConsoleSnippetProviderTests.cs b/src/Features/CSharpTest/Snippets/CSharpConsoleSnippetProviderTests.cs index a62d6aa39cfef..35d80003b78bb 100644 --- a/src/Features/CSharpTest/Snippets/CSharpConsoleSnippetProviderTests.cs +++ b/src/Features/CSharpTest/Snippets/CSharpConsoleSnippetProviderTests.cs @@ -15,9 +15,8 @@ public sealed class CSharpConsoleSnippetProviderTests : AbstractCSharpSnippetPro protected override string SnippetIdentifier => "cw"; [Fact] - public async Task InsertConsoleSnippetInMethodTest() - { - await VerifySnippetAsync(""" + public Task InsertConsoleSnippetInMethodTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -36,12 +35,10 @@ public void Method() } } """); - } [Fact] - public async Task InsertNormalConsoleSnippetInAsyncContextTest() - { - await VerifySnippetAsync(""" + public Task InsertNormalConsoleSnippetInAsyncContextTest() + => VerifySnippetAsync(""" using System.Threading.Tasks; class Program @@ -63,45 +60,37 @@ public async Task MethodAsync() } } """); - } [Fact] - public async Task InsertConsoleSnippetInGlobalContextTest() - { - await VerifySnippetAsync(""" + public Task InsertConsoleSnippetInGlobalContextTest() + => VerifySnippetAsync(""" $$ """, """ using System; Console.WriteLine($$); """); - } [Fact] - public async Task NoConsoleSnippetInBlockNamespaceTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoConsoleSnippetInBlockNamespaceTest() + => VerifySnippetIsAbsentAsync(""" namespace Namespace { $$ } """); - } [Fact] - public async Task NoConsoleSnippetInFileScopedNamespaceTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoConsoleSnippetInFileScopedNamespaceTest() + => VerifySnippetIsAbsentAsync(""" namespace Namespace; $$ """); - } [Fact] - public async Task InsertConsoleSnippetInConstructorTest() - { - await VerifySnippetAsync(""" + public Task InsertConsoleSnippetInConstructorTest() + => VerifySnippetAsync(""" class Program { public Program() @@ -122,12 +111,10 @@ public Program() } } """); - } [Fact] - public async Task InsertConsoleSnippetInLocalFunctionTest() - { - await VerifySnippetAsync(""" + public Task InsertConsoleSnippetInLocalFunctionTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -154,12 +141,10 @@ void LocalMethod() } } """); - } [Fact] - public async Task InsertConsoleSnippetInAnonymousFunctionTest() - { - await VerifySnippetAsync(""" + public Task InsertConsoleSnippetInAnonymousFunctionTest() + => VerifySnippetAsync(""" public delegate void Print(int value); static void Main(string[] args) @@ -184,12 +169,10 @@ static void Main(string[] args) } """); - } [Fact] - public async Task InsertConsoleSnippetInParenthesizedLambdaExpressionTest() - { - await VerifySnippetAsync(""" + public Task InsertConsoleSnippetInParenthesizedLambdaExpressionTest() + => VerifySnippetAsync(""" using System; Func testForEquality = (x, y) => @@ -206,12 +189,10 @@ await VerifySnippetAsync(""" return x == y; }; """); - } [Fact] - public async Task NoConsoleSnippetInSwitchExpressionTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoConsoleSnippetInSwitchExpressionTest() + => VerifySnippetIsAbsentAsync(""" class Program { public void Method() @@ -229,12 +210,10 @@ public void Method() } } """); - } [Fact] - public async Task NoConsoleSnippetInStringTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoConsoleSnippetInStringTest() + => VerifySnippetIsAbsentAsync(""" class Program { public void Method() @@ -243,12 +222,10 @@ public void Method() } } """); - } [Fact] - public async Task NoConsoleSnippetInConstructorArgumentsTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoConsoleSnippetInConstructorArgumentsTest() + => VerifySnippetIsAbsentAsync(""" class Program { public void Method() @@ -264,12 +241,10 @@ public Test(string val) } } """); - } [Fact] - public async Task NoConsoleSnippetInParameterListTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoConsoleSnippetInParameterListTest() + => VerifySnippetIsAbsentAsync(""" class Program { public void Method(int x, $$) @@ -277,12 +252,10 @@ public void Method(int x, $$) } } """); - } [Fact] - public async Task NoConsoleSnippetInRecordDeclarationTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoConsoleSnippetInRecordDeclarationTest() + => VerifySnippetIsAbsentAsync(""" public record Person { $$ @@ -290,12 +263,10 @@ public record Person public string LastName { get; init; } }; """); - } [Fact] - public async Task NoConsoleSnippetInVariableDeclarationTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoConsoleSnippetInVariableDeclarationTest() + => VerifySnippetIsAbsentAsync(""" class Program { public void Method() @@ -304,16 +275,14 @@ public void Method() } } """); - } /// /// We want to fix this case and insert the fully qualified namespace /// in a future fix. /// [Fact] - public async Task InsertConsoleSnippetWithPropertyNamedConsoleTest() - { - await VerifySnippetAsync(""" + public Task InsertConsoleSnippetWithPropertyNamedConsoleTest() + => VerifySnippetAsync(""" class Program { public int Console { get; set; } @@ -336,12 +305,10 @@ public void Method() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72266")] - public async Task InsertConsoleSnippetInVoidReturningLambdaTest1() - { - await VerifySnippetAsync(""" + public Task InsertConsoleSnippetInVoidReturningLambdaTest1() + => VerifySnippetAsync(""" using System; M(() => $$); @@ -358,12 +325,10 @@ void M(Action a) { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72266")] - public async Task InsertConsoleSnippetInVoidReturningLambdaTest2() - { - await VerifySnippetAsync(""" + public Task InsertConsoleSnippetInVoidReturningLambdaTest2() + => VerifySnippetAsync(""" using System; Action action = () => $$ @@ -372,12 +337,10 @@ await VerifySnippetAsync(""" Action action = () => Console.WriteLine($$) """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72266")] - public async Task InsertConsoleSnippetInVoidReturningLambdaTest_TypeInference() - { - await VerifySnippetAsync(""" + public Task InsertConsoleSnippetInVoidReturningLambdaTest_TypeInference() + => VerifySnippetAsync(""" using System; var action = () => $$ @@ -386,12 +349,10 @@ await VerifySnippetAsync(""" var action = () => Console.WriteLine($$) """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72266")] - public async Task NoConsoleSnippetInNonVoidReturningLambdaTest1() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoConsoleSnippetInNonVoidReturningLambdaTest1() + => VerifySnippetIsAbsentAsync(""" using System; M(() => $$); @@ -400,15 +361,12 @@ void M(Func f) { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72266")] - public async Task NoConsoleSnippetInNonVoidReturningLambdaTest2() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoConsoleSnippetInNonVoidReturningLambdaTest2() + => VerifySnippetIsAbsentAsync(""" using System; Func f = () => $$ """); - } } diff --git a/src/Features/CSharpTest/Snippets/CSharpConstructorSnippetProviderTests.cs b/src/Features/CSharpTest/Snippets/CSharpConstructorSnippetProviderTests.cs index e5cc0a8775b09..6f1e1922b7eaf 100644 --- a/src/Features/CSharpTest/Snippets/CSharpConstructorSnippetProviderTests.cs +++ b/src/Features/CSharpTest/Snippets/CSharpConstructorSnippetProviderTests.cs @@ -15,39 +15,32 @@ public sealed class CSharpConstructorSnippetProviderTests : AbstractCSharpSnippe protected override string SnippetIdentifier => "ctor"; [Fact] - public async Task ConstructorSnippetMissingInNamespace() - { - await VerifySnippetIsAbsentAsync(""" + public Task ConstructorSnippetMissingInNamespace() + => VerifySnippetIsAbsentAsync(""" namespace Namespace { $$ } """); - } [Fact] - public async Task ConstructorSnippetMissingInFileScopedNamespace() - { - await VerifySnippetIsAbsentAsync(""" + public Task ConstructorSnippetMissingInFileScopedNamespace() + => VerifySnippetIsAbsentAsync(""" namespace Namespace; $$ """); - } [Fact] - public async Task ConstructorSnippetMissingInTopLevelContext() - { - await VerifySnippetIsAbsentAsync(""" + public Task ConstructorSnippetMissingInTopLevelContext() + => VerifySnippetIsAbsentAsync(""" System.Console.WriteLine(); $$ """); - } [Fact] - public async Task InsertConstructorSnippetInClassTest() - { - await VerifySnippetAsync(""" + public Task InsertConstructorSnippetInClassTest() + => VerifySnippetAsync(""" class MyClass { $$ @@ -61,12 +54,10 @@ public MyClass() } } """); - } [Fact] - public async Task InsertConstructorSnippetInAbstractClassTest() - { - await VerifySnippetAsync(""" + public Task InsertConstructorSnippetInAbstractClassTest() + => VerifySnippetAsync(""" abstract class MyClass { $$ @@ -80,12 +71,10 @@ protected MyClass() } } """); - } [Fact] - public async Task InsertConstructorSnippetInAbstractClassTest_AbstractModifierInOtherPartialDeclaration() - { - await VerifySnippetAsync(""" + public Task InsertConstructorSnippetInAbstractClassTest_AbstractModifierInOtherPartialDeclaration() + => VerifySnippetAsync(""" partial class MyClass { $$ @@ -107,12 +96,10 @@ abstract partial class MyClass { } """); - } [Fact] - public async Task InsertConstructorSnippetInNestedAbstractClassTest() - { - await VerifySnippetAsync(""" + public Task InsertConstructorSnippetInNestedAbstractClassTest() + => VerifySnippetAsync(""" class MyClass { abstract class NestedClass @@ -132,12 +119,10 @@ protected NestedClass() } } """); - } [Fact] - public async Task InsertConstructorSnippetInStructTest() - { - await VerifySnippetAsync(""" + public Task InsertConstructorSnippetInStructTest() + => VerifySnippetAsync(""" struct MyStruct { $$ @@ -151,12 +136,10 @@ public MyStruct() } } """); - } [Fact] - public async Task InsertConstructorSnippetInRecordTest() - { - await VerifySnippetAsync(""" + public Task InsertConstructorSnippetInRecordTest() + => VerifySnippetAsync(""" record MyRecord { $$ @@ -170,23 +153,19 @@ public MyRecord() } } """); - } [Fact] - public async Task ConstructorSnippetMissingInInterface() - { - await VerifySnippetIsAbsentAsync(""" + public Task ConstructorSnippetMissingInInterface() + => VerifySnippetIsAbsentAsync(""" interface MyInterface { $$ } """); - } [Fact] - public async Task InsertConstructorSnippetInNestedClassTest() - { - await VerifySnippetAsync(""" + public Task InsertConstructorSnippetInNestedClassTest() + => VerifySnippetAsync(""" class MyClass { class MyClass1 @@ -206,14 +185,12 @@ public MyClass1() } } """); - } [Theory] [InlineData("static")] [MemberData(nameof(CommonSnippetTestData.AllAccessibilityModifiers), MemberType = typeof(CommonSnippetTestData))] - public async Task InsertConstructorSnippetAfterValidModifiersTest(string modifiers) - { - await VerifySnippetAsync($$""" + public Task InsertConstructorSnippetAfterValidModifiersTest(string modifiers) + => VerifySnippetAsync($$""" class MyClass { {{modifiers}} $$ @@ -227,7 +204,6 @@ class MyClass } } """); - } [Theory] [InlineData("abstract")] @@ -237,32 +213,27 @@ class MyClass [InlineData("readonly")] [InlineData("new")] [InlineData("file")] - public async Task ConstructorSnippetMissingAfterInvalidModifierTest(string modifier) - { - await VerifySnippetIsAbsentAsync($$""" + public Task ConstructorSnippetMissingAfterInvalidModifierTest(string modifier) + => VerifySnippetIsAbsentAsync($$""" class MyClass { {{modifier}} $$ } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.AllAccessibilityModifiers), MemberType = typeof(CommonSnippetTestData))] - public async Task ConstructorSnippetMissingAfterBothAccessibilityModifierAndStaticKeywordTest(string accessibilityModifier) - { - await VerifySnippetIsAbsentAsync($$""" + public Task ConstructorSnippetMissingAfterBothAccessibilityModifierAndStaticKeywordTest(string accessibilityModifier) + => VerifySnippetIsAbsentAsync($$""" class MyClass { {{accessibilityModifier}} static $$ } """); - } [Fact] - public async Task InsertConstructorSnippetAfterAccessibilityModifierBeforeOtherMemberTest() - { - await VerifySnippetAsync(""" + public Task InsertConstructorSnippetAfterAccessibilityModifierBeforeOtherMemberTest() + => VerifySnippetAsync(""" class C { private $$ @@ -278,12 +249,10 @@ private C() readonly int Value = 3; } """); - } [Fact] - public async Task InsertConstructorSnippetBetweenAccessibilityModifiersBeforeOtherMemberTest() - { - await VerifySnippetAsync(""" + public Task InsertConstructorSnippetBetweenAccessibilityModifiersBeforeOtherMemberTest() + => VerifySnippetAsync(""" class C { protected $$ @@ -299,12 +268,10 @@ protected C() internal int Value = 3; } """); - } [Fact] - public async Task InsertConstructorSnippetAfterAccessibilityModifierBeforeOtherStaticMemberTest() - { - await VerifySnippetAsync(""" + public Task InsertConstructorSnippetAfterAccessibilityModifierBeforeOtherStaticMemberTest() + => VerifySnippetAsync(""" class C { internal $$ @@ -320,12 +287,10 @@ internal C() static int Value = 3; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68176")] - public async Task InsertCorrectConstructorSnippetInNestedTypeTest_CtorBeforeNestedType() - { - await VerifySnippetAsync(""" + public Task InsertCorrectConstructorSnippetInNestedTypeTest_CtorBeforeNestedType() + => VerifySnippetAsync(""" class Outer { $$ @@ -345,12 +310,10 @@ class Inner } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68176")] - public async Task InsertCorrectConstructorSnippetInNestedTypeTest_CtorAfterNestedType() - { - await VerifySnippetAsync(""" + public Task InsertCorrectConstructorSnippetInNestedTypeTest_CtorAfterNestedType() + => VerifySnippetAsync(""" class Outer { class Inner @@ -370,5 +333,4 @@ public Outer() } } """); - } } diff --git a/src/Features/CSharpTest/Snippets/CSharpDoSnippetProviderTests.cs b/src/Features/CSharpTest/Snippets/CSharpDoSnippetProviderTests.cs index 2a183f2d66730..164d9a8f86526 100644 --- a/src/Features/CSharpTest/Snippets/CSharpDoSnippetProviderTests.cs +++ b/src/Features/CSharpTest/Snippets/CSharpDoSnippetProviderTests.cs @@ -15,9 +15,8 @@ public sealed class CSharpDoSnippetProviderTests : AbstractCSharpSnippetProvider protected override string SnippetIdentifier => "do"; [Fact] - public async Task InsertDoSnippetInMethodTest() - { - await VerifySnippetAsync(""" + public Task InsertDoSnippetInMethodTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -38,12 +37,10 @@ public void Method() } } """); - } [Fact] - public async Task InsertDoSnippetInGlobalContextTest() - { - await VerifySnippetAsync(""" + public Task InsertDoSnippetInGlobalContextTest() + => VerifySnippetAsync(""" $$ """, """ do @@ -52,33 +49,27 @@ await VerifySnippetAsync(""" } while ({|0:true|}); """); - } [Fact] - public async Task NoDoSnippetInBlockNamespaceTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoDoSnippetInBlockNamespaceTest() + => VerifySnippetIsAbsentAsync(""" namespace Namespace { $$ } """); - } [Fact] - public async Task NoDoSnippetInFileScopedNamespaceTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoDoSnippetInFileScopedNamespaceTest() + => VerifySnippetIsAbsentAsync(""" namespace Namespace; $$ """); - } [Fact] - public async Task InsertDoSnippetInConstructorTest() - { - await VerifySnippetAsync(""" + public Task InsertDoSnippetInConstructorTest() + => VerifySnippetAsync(""" class Program { public Program() @@ -101,12 +92,10 @@ public Program() } } """); - } [Fact] - public async Task InsertDoSnippetInLocalFunctionTest() - { - await VerifySnippetAsync(""" + public Task InsertDoSnippetInLocalFunctionTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -135,12 +124,10 @@ void LocalMethod() } } """); - } [Fact] - public async Task InsertDoSnippetInAnonymousFunctionTest() - { - await VerifySnippetAsync(""" + public Task InsertDoSnippetInAnonymousFunctionTest() + => VerifySnippetAsync(""" public delegate void Print(int value); static void Main(string[] args) @@ -167,12 +154,10 @@ static void Main(string[] args) } """); - } [Fact] - public async Task InsertDoSnippetInParenthesizedLambdaExpressionTest() - { - await VerifySnippetAsync(""" + public Task InsertDoSnippetInParenthesizedLambdaExpressionTest() + => VerifySnippetAsync(""" using System; Func testForEquality = (x, y) => @@ -193,12 +178,10 @@ await VerifySnippetAsync(""" return x == y; }; """); - } [Fact] - public async Task NoDoSnippetInSwitchExpression() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoDoSnippetInSwitchExpression() + => VerifySnippetIsAbsentAsync(""" class Program { public void Method() @@ -216,12 +199,10 @@ public void Method() } } """); - } [Fact] - public async Task NoDoSnippetInSingleLambdaExpression() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoDoSnippetInSingleLambdaExpression() + => VerifySnippetIsAbsentAsync(""" using System; class Program @@ -232,12 +213,10 @@ public void Method() } } """); - } [Fact] - public async Task NoDoSnippetInStringTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoDoSnippetInStringTest() + => VerifySnippetIsAbsentAsync(""" class Program { public void Method() @@ -246,12 +225,10 @@ public void Method() } } """); - } [Fact] - public async Task NoDoSnippetInConstructorArgumentsTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoDoSnippetInConstructorArgumentsTest() + => VerifySnippetIsAbsentAsync(""" class Program { public void Method() @@ -267,12 +244,10 @@ public Test(string val) } } """); - } [Fact] - public async Task NoDoSnippetInParameterListTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoDoSnippetInParameterListTest() + => VerifySnippetIsAbsentAsync(""" class Program { public void Method(int x, $$) @@ -280,12 +255,10 @@ public void Method(int x, $$) } } """); - } [Fact] - public async Task NoDoSnippetInRecordDeclarationTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoDoSnippetInRecordDeclarationTest() + => VerifySnippetIsAbsentAsync(""" public record Person { $$ @@ -293,12 +266,10 @@ public record Person public string LastName { get; init; } }; """); - } [Fact] - public async Task NoDoSnippetInVariableDeclarationTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoDoSnippetInVariableDeclarationTest() + => VerifySnippetIsAbsentAsync(""" class Program { public void Method() @@ -307,12 +278,10 @@ public void Method() } } """); - } [Fact] - public async Task InsertInlineDoSnippetForCorrectTypeTest() - { - await VerifySnippetAsync(""" + public Task InsertInlineDoSnippetForCorrectTypeTest() + => VerifySnippetAsync(""" class Program { void M(bool arg) @@ -333,12 +302,10 @@ void M(bool arg) } } """); - } [Fact] - public async Task NoInlineDoSnippetForIncorrectTypeTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInlineDoSnippetForIncorrectTypeTest() + => VerifySnippetIsAbsentAsync(""" class Program { void M(int arg) @@ -347,12 +314,10 @@ void M(int arg) } } """); - } [Fact] - public async Task NoInlineDoSnippetWhenNotDirectlyExpressionStatementTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInlineDoSnippetWhenNotDirectlyExpressionStatementTest() + => VerifySnippetIsAbsentAsync(""" class Program { void M(bool arg) @@ -361,15 +326,13 @@ void M(bool arg) } } """); - } [Theory] [InlineData("// comment")] [InlineData("/* comment */")] [InlineData("#region test")] - public async Task CorrectlyDealWithLeadingTriviaInInlineSnippetInMethodTest1(string trivia) - { - await VerifySnippetAsync($$""" + public Task CorrectlyDealWithLeadingTriviaInInlineSnippetInMethodTest1(string trivia) + => VerifySnippetAsync($$""" class Program { void M(bool arg) @@ -392,15 +355,13 @@ void M(bool arg) } } """); - } [Theory] [InlineData("#if true")] [InlineData("#pragma warning disable CS0108")] [InlineData("#nullable enable")] - public async Task CorrectlyDealWithLeadingTriviaInInlineSnippetInMethodTest2(string trivia) - { - await VerifySnippetAsync($$""" + public Task CorrectlyDealWithLeadingTriviaInInlineSnippetInMethodTest2(string trivia) + => VerifySnippetAsync($$""" class Program { void M(bool arg) @@ -423,14 +384,12 @@ void M(bool arg) } } """); - } [Theory] [InlineData("// comment")] [InlineData("/* comment */")] - public async Task CorrectlyDealWithLeadingTriviaInInlineSnippetInGlobalStatementTest1(string trivia) - { - await VerifySnippetAsync($""" + public Task CorrectlyDealWithLeadingTriviaInInlineSnippetInGlobalStatementTest1(string trivia) + => VerifySnippetAsync($""" {trivia} true.$$ """, $$""" @@ -441,16 +400,14 @@ await VerifySnippetAsync($""" } while (true); """); - } [Theory] [InlineData("#region test")] [InlineData("#if true")] [InlineData("#pragma warning disable CS0108")] [InlineData("#nullable enable")] - public async Task CorrectlyDealWithLeadingTriviaInInlineSnippetInGlobalStatementTest2(string trivia) - { - await VerifySnippetAsync($""" + public Task CorrectlyDealWithLeadingTriviaInInlineSnippetInGlobalStatementTest2(string trivia) + => VerifySnippetAsync($""" {trivia} true.$$ """, $$""" @@ -462,12 +419,10 @@ await VerifySnippetAsync($""" } while (true); """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69598")] - public async Task InsertInlineSnippetWhenDottingBeforeContextualKeywordTest1() - { - await VerifySnippetAsync(""" + public Task InsertInlineSnippetWhenDottingBeforeContextualKeywordTest1() + => VerifySnippetAsync(""" class C { void M(bool flag) @@ -490,12 +445,10 @@ void M(bool flag) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69598")] - public async Task InsertInlineSnippetWhenDottingBeforeContextualKeywordTest2() - { - await VerifySnippetAsync(""" + public Task InsertInlineSnippetWhenDottingBeforeContextualKeywordTest2() + => VerifySnippetAsync(""" class C { async void M(bool flag, Task t) @@ -518,15 +471,13 @@ async void M(bool flag, Task t) } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/69598")] [InlineData("Task")] [InlineData("Task")] [InlineData("System.Threading.Tasks.Task")] - public async Task InsertInlineSnippetWhenDottingBeforeNameSyntaxTest(string nameSyntax) - { - await VerifySnippetAsync($$""" + public Task InsertInlineSnippetWhenDottingBeforeNameSyntaxTest(string nameSyntax) + => VerifySnippetAsync($$""" using System.Threading.Tasks; class C @@ -553,12 +504,10 @@ void M(bool flag) } } """); - } [Fact] - public async Task InsertInlineDoSnippetWhenDottingBeforeMemberAccessExpressionOnTheNextLineTest() - { - await VerifySnippetAsync(""" + public Task InsertInlineDoSnippetWhenDottingBeforeMemberAccessExpressionOnTheNextLineTest() + => VerifySnippetAsync(""" using System; class C @@ -585,12 +534,10 @@ void M(bool flag) } } """); - } [Fact] - public async Task NoInlineDoSnippetWhenDottingBeforeMemberAccessExpressionOnTheSameLineTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInlineDoSnippetWhenDottingBeforeMemberAccessExpressionOnTheSameLineTest() + => VerifySnippetIsAbsentAsync(""" class C { void M(bool flag) @@ -599,12 +546,10 @@ void M(bool flag) } } """); - } [Fact] - public async Task NoInlineDoSnippetWhenDottingBeforeContextualKeywordOnTheSameLineTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInlineDoSnippetWhenDottingBeforeContextualKeywordOnTheSameLineTest() + => VerifySnippetIsAbsentAsync(""" class C { void M(bool flag) @@ -613,12 +558,10 @@ void M(bool flag) } } """); - } [Fact] - public async Task NoInlineDoSnippetForTypeItselfTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInlineDoSnippetForTypeItselfTest() + => VerifySnippetIsAbsentAsync(""" class C { void M() @@ -627,12 +570,10 @@ void M() } } """); - } [Fact] - public async Task NoInlineDoSnippetForTypeItselfTest_Parenthesized() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInlineDoSnippetForTypeItselfTest_Parenthesized() + => VerifySnippetIsAbsentAsync(""" class C { void M() @@ -641,12 +582,10 @@ void M() } } """); - } [Fact] - public async Task NoInlineDoSnippetForTypeItselfTest_BeforeContextualKeyword() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInlineDoSnippetForTypeItselfTest_BeforeContextualKeyword() + => VerifySnippetIsAbsentAsync(""" using System.Threading.Tasks; class C @@ -658,5 +597,4 @@ async void M() } } """); - } } diff --git a/src/Features/CSharpTest/Snippets/CSharpElseSnippetProviderTests.cs b/src/Features/CSharpTest/Snippets/CSharpElseSnippetProviderTests.cs index 6dbd4f8352b6d..ad908c58ec340 100644 --- a/src/Features/CSharpTest/Snippets/CSharpElseSnippetProviderTests.cs +++ b/src/Features/CSharpTest/Snippets/CSharpElseSnippetProviderTests.cs @@ -14,9 +14,8 @@ public sealed class CSharpElseSnippetProviderTests : AbstractCSharpSnippetProvid protected override string SnippetIdentifier => "else"; [Fact] - public async Task InsertElseSnippetInMethodTest() - { - await VerifySnippetAsync(""" + public Task InsertElseSnippetInMethodTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -42,12 +41,10 @@ public void Method() } } """); - } [Fact] - public async Task NoElseSnippetInMethodWithoutIfStatementTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoElseSnippetInMethodWithoutIfStatementTest() + => VerifySnippetIsAbsentAsync(""" class Program { public void Method() @@ -56,12 +53,10 @@ public void Method() } } """); - } [Fact] - public async Task InsertElseSnippetGlobalTest() - { - await VerifySnippetAsync(""" + public Task InsertElseSnippetGlobalTest() + => VerifySnippetAsync(""" if (true) { } @@ -75,12 +70,10 @@ await VerifySnippetAsync(""" $$ } """); - } [Fact] - public async Task NoElseSnippetInBlockNamespaceTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoElseSnippetInBlockNamespaceTest() + => VerifySnippetIsAbsentAsync(""" namespace Namespace { if (true) @@ -89,24 +82,20 @@ namespace Namespace $$ } """); - } [Fact] - public async Task NoElseSnippetInFileScopedNamespaceTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoElseSnippetInFileScopedNamespaceTest() + => VerifySnippetIsAbsentAsync(""" namespace Namespace; if (true) { } $$ """); - } [Fact] - public async Task InsertElseSnippetInConstructorTest() - { - await VerifySnippetAsync(""" + public Task InsertElseSnippetInConstructorTest() + => VerifySnippetAsync(""" class Program { public Program() @@ -132,12 +121,10 @@ public Program() } } """); - } [Fact] - public async Task InsertElseSnippetInLocalFunctionTest() - { - await VerifySnippetAsync(""" + public Task InsertElseSnippetInLocalFunctionTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -173,12 +160,10 @@ void LocalMethod() } } """); - } [Fact] - public async Task InsertElseSnippetSingleLineIfWithBlockTest() - { - await VerifySnippetAsync(""" + public Task InsertElseSnippetSingleLineIfWithBlockTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -200,12 +185,10 @@ public void Method() } } """); - } [Fact] - public async Task InsertElseSnippetSingleLineIfTest() - { - await VerifySnippetAsync(""" + public Task InsertElseSnippetSingleLineIfTest() + => VerifySnippetAsync(""" using System; class Program @@ -231,12 +214,10 @@ public void Method() } } """); - } [Fact] - public async Task InsertElseSnippetNestedIfTest() - { - await VerifySnippetAsync(""" + public Task InsertElseSnippetNestedIfTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -268,5 +249,4 @@ public void Method() } } """); - } } diff --git a/src/Features/CSharpTest/Snippets/CSharpEnumSnippetProviderTests.cs b/src/Features/CSharpTest/Snippets/CSharpEnumSnippetProviderTests.cs index dc880015a72b4..c925ea6af7279 100644 --- a/src/Features/CSharpTest/Snippets/CSharpEnumSnippetProviderTests.cs +++ b/src/Features/CSharpTest/Snippets/CSharpEnumSnippetProviderTests.cs @@ -14,9 +14,8 @@ public sealed class CSharpEnumSnippetProviderTests : AbstractCSharpSnippetProvid protected override string SnippetIdentifier => "enum"; [Fact] - public async Task InsertEnumSnippetInBlockNamespaceTest() - { - await VerifySnippetAsync(""" + public Task InsertEnumSnippetInBlockNamespaceTest() + => VerifySnippetAsync(""" namespace Namespace { $$ @@ -30,12 +29,10 @@ enum {|0:MyEnum|} } } """); - } [Fact] - public async Task InsertEnumSnippetInFileScopedNamespaceTest() - { - await VerifySnippetAsync(""" + public Task InsertEnumSnippetInFileScopedNamespaceTest() + => VerifySnippetAsync(""" namespace Namespace; $$ @@ -47,12 +44,10 @@ enum {|0:MyEnum|} $$ } """); - } [Fact] - public async Task InsertEnumSnippetTest() - { - await VerifySnippetAsync(""" + public Task InsertEnumSnippetTest() + => VerifySnippetAsync(""" $$ """, """ enum {|0:MyEnum|} @@ -60,12 +55,10 @@ enum {|0:MyEnum|} $$ } """); - } [Fact] - public async Task InsertEnumTopLevelSnippetTest() - { - await VerifySnippetAsync(""" + public Task InsertEnumTopLevelSnippetTest() + => VerifySnippetAsync(""" System.Console.WriteLine(); $$ """, """ @@ -75,12 +68,10 @@ enum {|0:MyEnum|} $$ } """); - } [Fact] - public async Task InsertEnumSnippetInClassTest() - { - await VerifySnippetAsync(""" + public Task InsertEnumSnippetInClassTest() + => VerifySnippetAsync(""" class MyClass { $$ @@ -94,12 +85,10 @@ enum {|0:MyEnum|} } } """); - } [Fact] - public async Task InsertEnumSnippetInRecordTest() - { - await VerifySnippetAsync(""" + public Task InsertEnumSnippetInRecordTest() + => VerifySnippetAsync(""" record MyRecord { $$ @@ -113,12 +102,10 @@ enum {|0:MyEnum|} } } """); - } [Fact] - public async Task InsertEnumSnippetInStructTest() - { - await VerifySnippetAsync(""" + public Task InsertEnumSnippetInStructTest() + => VerifySnippetAsync(""" struct MyStruct { $$ @@ -132,12 +119,10 @@ enum {|0:MyEnum|} } } """); - } [Fact] - public async Task InsertEnumSnippetInInterfaceTest() - { - await VerifySnippetAsync(""" + public Task InsertEnumSnippetInInterfaceTest() + => VerifySnippetAsync(""" interface MyInterface { $$ @@ -151,12 +136,10 @@ enum {|0:MyEnum|} } } """); - } [Fact] - public async Task InsertEnumSnippetWithModifiersTest() - { - await VerifySnippetAsync(""" + public Task InsertEnumSnippetWithModifiersTest() + => VerifySnippetAsync(""" $$ """, """ public enum {|0:MyEnum|} @@ -170,23 +153,19 @@ public enum {|0:MyEnum|} [*] dotnet_style_require_accessibility_modifiers = always """); - } [Fact] - public async Task NoEnumSnippetInEnumTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoEnumSnippetInEnumTest() + => VerifySnippetIsAbsentAsync(""" enum MyEnum { $$ } """); - } [Fact] - public async Task NoEnumSnippetInMethodTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoEnumSnippetInMethodTest() + => VerifySnippetIsAbsentAsync(""" class Program { public void Method() @@ -195,12 +174,10 @@ public void Method() } } """); - } [Fact] - public async Task NoEnumSnippetInConstructorTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoEnumSnippetInConstructorTest() + => VerifySnippetIsAbsentAsync(""" class Program { public Program() @@ -209,13 +186,11 @@ public Program() } } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.AllAccessibilityModifiers), MemberType = typeof(CommonSnippetTestData))] - public async Task InsertEnumSnippetAfterAccessibilityModifier(string modifier) - { - await VerifySnippetAsync($""" + public Task InsertEnumSnippetAfterAccessibilityModifier(string modifier) + => VerifySnippetAsync($""" {modifier} $$ """, $$""" {{modifier}} enum {|0:MyEnum|} @@ -223,13 +198,11 @@ await VerifySnippetAsync($""" $$ } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.AllAccessibilityModifiers), MemberType = typeof(CommonSnippetTestData))] - public async Task InsertEnumSnippetAfterAccessibilityModifier_RequireAccessibilityModifiers(string modifier) - { - await VerifySnippetAsync($""" + public Task InsertEnumSnippetAfterAccessibilityModifier_RequireAccessibilityModifiers(string modifier) + => VerifySnippetAsync($""" {modifier} $$ """, $$""" {{modifier}} enum {|0:MyEnum|} @@ -243,7 +216,6 @@ await VerifySnippetAsync($""" [*] dotnet_style_require_accessibility_modifiers = always """); - } [Theory] [InlineData("abstract")] @@ -253,10 +225,8 @@ await VerifySnippetAsync($""" [InlineData("ref")] [InlineData("readonly")] [InlineData("unsafe")] - public async Task NoEnumSnippetAfterInvalidModifiersTest(string modifier) - { - await VerifySnippetIsAbsentAsync($""" + public Task NoEnumSnippetAfterInvalidModifiersTest(string modifier) + => VerifySnippetIsAbsentAsync($""" {modifier} $$ """); - } } diff --git a/src/Features/CSharpTest/Snippets/CSharpForEachSnippetProviderTests.cs b/src/Features/CSharpTest/Snippets/CSharpForEachSnippetProviderTests.cs index 2c92199bfcce0..f1f45abd47e17 100644 --- a/src/Features/CSharpTest/Snippets/CSharpForEachSnippetProviderTests.cs +++ b/src/Features/CSharpTest/Snippets/CSharpForEachSnippetProviderTests.cs @@ -16,9 +16,8 @@ public sealed class CSharpForEachSnippetProviderTests : AbstractCSharpSnippetPro protected override string SnippetIdentifier => "foreach"; [Fact] - public async Task InsertForEachSnippetInMethodTest() - { - await VerifySnippetAsync(""" + public Task InsertForEachSnippetInMethodTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -38,12 +37,10 @@ public void Method() } } """); - } [Fact] - public async Task InsertForEachSnippetInMethodItemUsedTest() - { - await VerifySnippetAsync(""" + public Task InsertForEachSnippetInMethodItemUsedTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -65,12 +62,10 @@ public void Method() } } """); - } [Fact] - public async Task InsertForEachSnippetInGlobalContextTest() - { - await VerifySnippetAsync(""" + public Task InsertForEachSnippetInGlobalContextTest() + => VerifySnippetAsync(""" $$ """, """ foreach (var {|0:item|} in {|1:collection|}) @@ -78,12 +73,10 @@ await VerifySnippetAsync(""" $$ } """); - } [Fact] - public async Task InsertForEachSnippetInConstructorTest() - { - await VerifySnippetAsync(""" + public Task InsertForEachSnippetInConstructorTest() + => VerifySnippetAsync(""" class Program { public Program() @@ -103,12 +96,10 @@ public Program() } } """); - } [Fact] - public async Task InsertForEachSnippetWithCollectionTest() - { - await VerifySnippetAsync(""" + public Task InsertForEachSnippetWithCollectionTest() + => VerifySnippetAsync(""" using System.Collections.Generic; class Program @@ -134,12 +125,10 @@ public Program() } } """); - } [Fact] - public async Task InsertForEachSnippetInLocalFunctionTest() - { - await VerifySnippetAsync(""" + public Task InsertForEachSnippetInLocalFunctionTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -167,12 +156,10 @@ void LocalMethod() } } """); - } [Fact] - public async Task InsertForEachSnippetInAnonymousFunctionTest() - { - await VerifySnippetAsync(""" + public Task InsertForEachSnippetInAnonymousFunctionTest() + => VerifySnippetAsync(""" public delegate void Print(int value); static void Main(string[] args) @@ -196,12 +183,10 @@ static void Main(string[] args) }; } """); - } [Fact] - public async Task InsertForEachSnippetInParenthesizedLambdaExpressionTest() - { - await VerifySnippetAsync(""" + public Task InsertForEachSnippetInParenthesizedLambdaExpressionTest() + => VerifySnippetAsync(""" using System; Func testForEquality = (x, y) => @@ -221,13 +206,11 @@ await VerifySnippetAsync(""" return x == y; }; """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.CommonEnumerableTypes), MemberType = typeof(CommonSnippetTestData))] - public async Task InsertInlineForEachSnippetForCorrectTypeTest(string collectionType) - { - await VerifySnippetAsync($$""" + public Task InsertInlineForEachSnippetForCorrectTypeTest(string collectionType) + => VerifySnippetAsync($$""" class C { void M({{collectionType}} enumerable) @@ -247,12 +230,10 @@ void M({{collectionType}} enumerable) } } """); - } [Fact] - public async Task NoInlineForEachSnippetForIncorrectTypeTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInlineForEachSnippetForIncorrectTypeTest() + => VerifySnippetIsAbsentAsync(""" class Program { void M(int arg) @@ -261,12 +242,10 @@ void M(int arg) } } """); - } [Fact] - public async Task NoInlineForEachSnippetWhenNotDirectlyExpressionStatementTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInlineForEachSnippetWhenNotDirectlyExpressionStatementTest() + => VerifySnippetIsAbsentAsync(""" using System; using System.Collections.Generic; @@ -278,15 +257,13 @@ void M(List list) } } """); - } [Theory] [InlineData("// comment")] [InlineData("/* comment */")] [InlineData("#region test")] - public async Task CorrectlyDealWithLeadingTriviaInInlineSnippetInMethodTest1(string trivia) - { - await VerifySnippetAsync($$""" + public Task CorrectlyDealWithLeadingTriviaInInlineSnippetInMethodTest1(string trivia) + => VerifySnippetAsync($$""" class Program { void M(int[] arr) @@ -308,15 +285,13 @@ void M(int[] arr) } } """); - } [Theory] [InlineData("#if true")] [InlineData("#pragma warning disable CS0108")] [InlineData("#nullable enable")] - public async Task CorrectlyDealWithLeadingTriviaInInlineSnippetInMethodTest2(string trivia) - { - await VerifySnippetAsync($$""" + public Task CorrectlyDealWithLeadingTriviaInInlineSnippetInMethodTest2(string trivia) + => VerifySnippetAsync($$""" class Program { void M(int[] arr) @@ -338,14 +313,12 @@ void M(int[] arr) } } """); - } [Theory] [InlineData("// comment")] [InlineData("/* comment */")] - public async Task CorrectlyDealWithLeadingTriviaInInlineSnippetInGlobalStatementTest1(string trivia) - { - await VerifySnippetAsync($$""" + public Task CorrectlyDealWithLeadingTriviaInInlineSnippetInGlobalStatementTest1(string trivia) + => VerifySnippetAsync($$""" {{trivia}} (new int[10]).$$ """, $$""" @@ -355,16 +328,14 @@ await VerifySnippetAsync($$""" $$ } """); - } [Theory] [InlineData("#region test")] [InlineData("#if true")] [InlineData("#pragma warning disable CS0108")] [InlineData("#nullable enable")] - public async Task CorrectlyDealWithLeadingTriviaInInlineSnippetInGlobalStatementTest2(string trivia) - { - await VerifySnippetAsync($$""" + public Task CorrectlyDealWithLeadingTriviaInInlineSnippetInGlobalStatementTest2(string trivia) + => VerifySnippetAsync($$""" {{trivia}} (new int[10]).$$ """, $$""" @@ -375,14 +346,12 @@ await VerifySnippetAsync($$""" $$ } """); - } [Theory] [InlineData("")] [InlineData("async ")] - public async Task InsertForEachSnippetAfterSingleAwaitKeywordInMethodBodyTest(string asyncKeyword) - { - await VerifySnippetAsync($$""" + public Task InsertForEachSnippetAfterSingleAwaitKeywordInMethodBodyTest(string asyncKeyword) + => VerifySnippetAsync($$""" class C { {{asyncKeyword}}void M() @@ -403,12 +372,10 @@ class C } """, referenceAssemblies: ReferenceAssemblies.Net.Net70); - } [Fact] - public async Task InsertForEachSnippetAfterSingleAwaitKeywordInGlobalStatementTest() - { - await VerifySnippetAsync(""" + public Task InsertForEachSnippetAfterSingleAwaitKeywordInGlobalStatementTest() + => VerifySnippetAsync(""" await $$ """, """ await foreach (var {|0:item|} in {|1:collection|}) @@ -417,23 +384,19 @@ await VerifySnippetAsync(""" } """, referenceAssemblies: ReferenceAssemblies.Net.Net70); - } [Fact] - public async Task NoForEachStatementAfterAwaitKeywordWhenWontResultInStatementTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoForEachStatementAfterAwaitKeywordWhenWontResultInStatementTest() + => VerifySnippetIsAbsentAsync(""" var result = await $$ """, referenceAssemblies: ReferenceAssemblies.Net.Net70); - } [Theory] [InlineData("")] [InlineData("async ")] - public async Task PreferAsyncEnumerableVariableInScopeForAwaitForEachTest(string asyncKeyword) - { - await VerifySnippetAsync($$""" + public Task PreferAsyncEnumerableVariableInScopeForAwaitForEachTest(string asyncKeyword) + => VerifySnippetAsync($$""" using System.Collections.Generic; class C @@ -464,14 +427,12 @@ class C } """, referenceAssemblies: ReferenceAssemblies.Net.Net70); - } [Theory] [InlineData("")] [InlineData("async ")] - public async Task InsertAwaitForEachSnippetForPostfixAsyncEnumerableTest(string asyncKeyword) - { - await VerifySnippetAsync($$""" + public Task InsertAwaitForEachSnippetForPostfixAsyncEnumerableTest(string asyncKeyword) + => VerifySnippetAsync($$""" using System.Collections.Generic; class C @@ -496,12 +457,10 @@ class C } """, referenceAssemblies: ReferenceAssemblies.Net.Net70); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69598")] - public async Task InsertInlineForEachSnippetWhenDottingBeforeContextualKeywordTest1() - { - await VerifySnippetAsync(""" + public Task InsertInlineForEachSnippetWhenDottingBeforeContextualKeywordTest1() + => VerifySnippetAsync(""" using System.Collections.Generic; class C @@ -527,12 +486,10 @@ void M(IEnumerable ints) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69598")] - public async Task InsertInlineForEachSnippetWhenDottingBeforeContextualKeywordTest2() - { - await VerifySnippetAsync(""" + public Task InsertInlineForEachSnippetWhenDottingBeforeContextualKeywordTest2() + => VerifySnippetAsync(""" using System.Threading.Tasks; using System.Collections.Generic; @@ -560,15 +517,13 @@ async void M(IEnumerable ints, Task t) } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/69598")] [InlineData("Task")] [InlineData("Task")] [InlineData("System.Threading.Tasks.Task")] - public async Task InsertInlineForEachSnippetWhenDottingBeforeNameSyntaxTest(string nameSyntax) - { - await VerifySnippetAsync($$""" + public Task InsertInlineForEachSnippetWhenDottingBeforeNameSyntaxTest(string nameSyntax) + => VerifySnippetAsync($$""" using System.Threading.Tasks; using System.Collections.Generic; @@ -596,12 +551,10 @@ void M(IEnumerable ints) } } """); - } [Fact] - public async Task InsertInlineForEachSnippetWhenDottingBeforeMemberAccessExpressionOnTheNextLineTest() - { - await VerifySnippetAsync(""" + public Task InsertInlineForEachSnippetWhenDottingBeforeMemberAccessExpressionOnTheNextLineTest() + => VerifySnippetAsync(""" using System; class C @@ -627,12 +580,10 @@ void M(int[] ints) } } """); - } [Fact] - public async Task NoInlineForEachSnippetWhenDottingBeforeMemberAccessExpressionOnTheSameLineTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInlineForEachSnippetWhenDottingBeforeMemberAccessExpressionOnTheSameLineTest() + => VerifySnippetIsAbsentAsync(""" using System; class C @@ -643,12 +594,10 @@ void M(int[] ints) } } """); - } [Fact] - public async Task NoInlineForEachSnippetWhenDottingBeforeContextualKeywordOnTheSameLineTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInlineForEachSnippetWhenDottingBeforeContextualKeywordOnTheSameLineTest() + => VerifySnippetIsAbsentAsync(""" using System; class C @@ -659,12 +608,10 @@ void M(int[] ints) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69598")] - public async Task InsertInlineAwaitForEachSnippetWhenDottingBeforeContextualKeywordTest1() - { - await VerifySnippetAsync(""" + public Task InsertInlineAwaitForEachSnippetWhenDottingBeforeContextualKeywordTest1() + => VerifySnippetAsync(""" using System.Collections.Generic; class C @@ -691,12 +638,10 @@ void M(IAsyncEnumerable asyncInts) } """, referenceAssemblies: ReferenceAssemblies.Net.Net70); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69598")] - public async Task InsertInlineAwaitForEachSnippetWhenDottingBeforeContextualKeywordTest2() - { - await VerifySnippetAsync(""" + public Task InsertInlineAwaitForEachSnippetWhenDottingBeforeContextualKeywordTest2() + => VerifySnippetAsync(""" using System.Threading.Tasks; using System.Collections.Generic; @@ -725,15 +670,13 @@ async void M(IAsyncEnumerable asyncInts, Task t) } """, referenceAssemblies: ReferenceAssemblies.Net.Net70); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/69598")] [InlineData("Task")] [InlineData("Task")] [InlineData("System.Threading.Tasks.Task")] - public async Task InsertInlineAwaitForEachSnippetWhenDottingBeforeNameSyntaxTest(string nameSyntax) - { - await VerifySnippetAsync($$""" + public Task InsertInlineAwaitForEachSnippetWhenDottingBeforeNameSyntaxTest(string nameSyntax) + => VerifySnippetAsync($$""" using System.Threading.Tasks; using System.Collections.Generic; @@ -762,12 +705,10 @@ void M(IAsyncEnumerable asyncInts) } """, referenceAssemblies: ReferenceAssemblies.Net.Net70); - } [Fact] - public async Task InsertInlineAwaitForEachSnippetWhenDottingBeforeMemberAccessExpressionOnTheNextLineTest() - { - await VerifySnippetAsync(""" + public Task InsertInlineAwaitForEachSnippetWhenDottingBeforeMemberAccessExpressionOnTheNextLineTest() + => VerifySnippetAsync(""" using System; using System.Collections.Generic; @@ -796,12 +737,10 @@ void M(IAsyncEnumerable ints) } """, referenceAssemblies: ReferenceAssemblies.Net.Net80); - } [Fact] - public async Task NoInlineAwaitForEachSnippetWhenDottingBeforeMemberAccessExpressionOnTheSameLineTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInlineAwaitForEachSnippetWhenDottingBeforeMemberAccessExpressionOnTheSameLineTest() + => VerifySnippetIsAbsentAsync(""" using System.Collections.Generic; class C @@ -813,12 +752,10 @@ void M(IAsyncEnumerable ints) } """, referenceAssemblies: ReferenceAssemblies.Net.Net80); - } [Fact] - public async Task NoInlineAwaitForEachSnippetWhenDottingBeforeContextualKeywordOnTheSameLineTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInlineAwaitForEachSnippetWhenDottingBeforeContextualKeywordOnTheSameLineTest() + => VerifySnippetIsAbsentAsync(""" using System.Collections.Generic; class C @@ -830,13 +767,11 @@ void M(IAsyncEnumerable ints) } """, referenceAssemblies: ReferenceAssemblies.Net.Net80); - } [Theory] [MemberData(nameof(CommonSnippetTestData.CommonEnumerableTypes), MemberType = typeof(CommonSnippetTestData))] - public async Task NoInlineForEachSnippetForTypeItselfTest(string collectionType) - { - await VerifySnippetIsAbsentAsync($$""" + public Task NoInlineForEachSnippetForTypeItselfTest(string collectionType) + => VerifySnippetIsAbsentAsync($$""" class C { void M() @@ -845,13 +780,11 @@ void M() } } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.CommonEnumerableTypes), MemberType = typeof(CommonSnippetTestData))] - public async Task NoInlineForEachSnippetForTypeItselfTest_Parenthesized(string collectionType) - { - await VerifySnippetIsAbsentAsync($$""" + public Task NoInlineForEachSnippetForTypeItselfTest_Parenthesized(string collectionType) + => VerifySnippetIsAbsentAsync($$""" class C { void M() @@ -860,13 +793,11 @@ void M() } } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.CommonEnumerableTypes), MemberType = typeof(CommonSnippetTestData))] - public async Task NoInlineForEachSnippetForTypeItselfTest_BeforeContextualKeyword(string collectionType) - { - await VerifySnippetIsAbsentAsync($$""" + public Task NoInlineForEachSnippetForTypeItselfTest_BeforeContextualKeyword(string collectionType) + => VerifySnippetIsAbsentAsync($$""" using System.Threading.Tasks; class C @@ -878,15 +809,13 @@ async void M() } } """); - } [Theory] [InlineData("ArrayList")] [InlineData("IEnumerable")] [InlineData("MyCollection")] - public async Task InsertInlineForEachSnippetForVariableNamedLikeTypeTest(string typeAndVariableName) - { - await VerifySnippetAsync($$""" + public Task InsertInlineForEachSnippetForVariableNamedLikeTypeTest(string typeAndVariableName) + => VerifySnippetAsync($$""" using System.Collections; using System.Collections.Generic; @@ -926,5 +855,4 @@ class MyCollection : IEnumerable IEnumerator IEnumerable.GetEnumerator() = null; } """); - } } diff --git a/src/Features/CSharpTest/Snippets/CSharpForSnippetProviderTests.cs b/src/Features/CSharpTest/Snippets/CSharpForSnippetProviderTests.cs index 2363ffcb65836..aa99707842ec6 100644 --- a/src/Features/CSharpTest/Snippets/CSharpForSnippetProviderTests.cs +++ b/src/Features/CSharpTest/Snippets/CSharpForSnippetProviderTests.cs @@ -16,9 +16,8 @@ public sealed class CSharpForSnippetProviderTests : AbstractCSharpSnippetProvide protected override string SnippetIdentifier => "for"; [Fact] - public async Task InsertForSnippetInMethodTest() - { - await VerifySnippetAsync(""" + public Task InsertForSnippetInMethodTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -38,12 +37,10 @@ public void Method() } } """); - } [Fact] - public async Task InsertForSnippetInMethodUsedIncrementorTest() - { - await VerifySnippetAsync(""" + public Task InsertForSnippetInMethodUsedIncrementorTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -65,12 +62,10 @@ public void Method() } } """); - } [Fact] - public async Task InsertForSnippetInMethodUsedIncrementorsTest() - { - await VerifySnippetAsync(""" + public Task InsertForSnippetInMethodUsedIncrementorsTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -92,12 +87,10 @@ public void Method() } } """); - } [Fact] - public async Task InsertForSnippetInGlobalContextTest() - { - await VerifySnippetAsync(""" + public Task InsertForSnippetInGlobalContextTest() + => VerifySnippetAsync(""" $$ """, """ for (int {|0:i|} = 0; {|0:i|} < {|1:length|}; {|0:i|}++) @@ -105,12 +98,10 @@ await VerifySnippetAsync(""" $$ } """); - } [Fact] - public async Task InsertForSnippetInConstructorTest() - { - await VerifySnippetAsync(""" + public Task InsertForSnippetInConstructorTest() + => VerifySnippetAsync(""" class Program { public Program() @@ -130,13 +121,10 @@ public Program() } } """); - } [Fact] - public async Task InsertForSnippetInLocalFunctionTest() - { - // TODO: fix this test when bug with simplifier failing to find correct node is fixed - await VerifySnippetAsync(""" + public Task InsertForSnippetInLocalFunctionTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -162,13 +150,10 @@ void LocalFunction() } } """); - } [Fact] - public async Task InsertForSnippetInAnonymousFunctionTest() - { - // TODO: fix this test when bug with simplifier failing to find correct node is fixed - await VerifySnippetAsync(""" + public Task InsertForSnippetInAnonymousFunctionTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -194,13 +179,10 @@ public void Method() } } """); - } [Fact] - public async Task InsertForSnippetInParenthesizedLambdaExpressionTest() - { - // TODO: fix this test when bug with simplifier failing to find correct node is fixed - await VerifySnippetAsync(""" + public Task InsertForSnippetInParenthesizedLambdaExpressionTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -226,12 +208,10 @@ public void Method() } } """); - } [Fact] - public async Task ProduceVarWithSpecificCodeStyleTest() - { - await VerifySnippetAsync(""" + public Task ProduceVarWithSpecificCodeStyleTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -257,13 +237,11 @@ public void Method() [*] csharp_style_var_for_built_in_types = true """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.IntegerTypes), MemberType = typeof(CommonSnippetTestData))] - public async Task InsertInlineForSnippetInMethodTest(string inlineExpressionType) - { - await VerifySnippetAsync($$""" + public Task InsertInlineForSnippetInMethodTest(string inlineExpressionType) + => VerifySnippetAsync($$""" class Program { public void Method({{inlineExpressionType}} l) @@ -283,13 +261,11 @@ public void Method({{inlineExpressionType}} l) } } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.IntegerTypes), MemberType = typeof(CommonSnippetTestData))] - public async Task InsertInlineForSnippetInGlobalContextTest(string inlineExpressionType) - { - await VerifySnippetAsync($$""" + public Task InsertInlineForSnippetInGlobalContextTest(string inlineExpressionType) + => VerifySnippetAsync($$""" {{inlineExpressionType}} l; l.$$ """, $$""" @@ -299,13 +275,11 @@ await VerifySnippetAsync($$""" $$ } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.NotIntegerTypesWithoutLengthOrCountProperty), MemberType = typeof(CommonSnippetTestData))] - public async Task NoInlineForSnippetForIncorrectTypeInMethodTest(string inlineExpressionType) - { - await VerifySnippetIsAbsentAsync($$""" + public Task NoInlineForSnippetForIncorrectTypeInMethodTest(string inlineExpressionType) + => VerifySnippetIsAbsentAsync($$""" class Program { public void Method({{inlineExpressionType}} l) @@ -314,22 +288,18 @@ public void Method({{inlineExpressionType}} l) } } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.NotIntegerTypesWithoutLengthOrCountProperty), MemberType = typeof(CommonSnippetTestData))] - public async Task NoInlineForSnippetForIncorrectTypeInGlobalContextTest(string inlineExpressionType) - { - await VerifySnippetIsAbsentAsync($$""" + public Task NoInlineForSnippetForIncorrectTypeInGlobalContextTest(string inlineExpressionType) + => VerifySnippetIsAbsentAsync($$""" {{inlineExpressionType}} l; l.$$ """); - } [Fact] - public async Task ProduceVarWithSpecificCodeStyleForInlineSnippetTest() - { - await VerifySnippetAsync(""" + public Task ProduceVarWithSpecificCodeStyleForInlineSnippetTest() + => VerifySnippetAsync(""" class Program { public void Method(int l) @@ -355,12 +325,10 @@ public void Method(int l) [*] csharp_style_var_for_built_in_types = true """); - } [Fact] - public async Task NoInlineForSnippetNotDirectlyExpressionStatementTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInlineForSnippetNotDirectlyExpressionStatementTest() + => VerifySnippetIsAbsentAsync(""" class Program { public void Method(int l) @@ -369,15 +337,13 @@ public void Method(int l) } } """); - } [Theory] [InlineData("// comment")] [InlineData("/* comment */")] [InlineData("#region test")] - public async Task CorrectlyDealWithLeadingTriviaInInlineSnippetInMethodTest1(string trivia) - { - await VerifySnippetAsync($$""" + public Task CorrectlyDealWithLeadingTriviaInInlineSnippetInMethodTest1(string trivia) + => VerifySnippetAsync($$""" class Program { void M(int len) @@ -399,15 +365,13 @@ void M(int len) } } """); - } [Theory] [InlineData("#if true")] [InlineData("#pragma warning disable CS0108")] [InlineData("#nullable enable")] - public async Task CorrectlyDealWithLeadingTriviaInInlineSnippetInMethodTest2(string trivia) - { - await VerifySnippetAsync($$""" + public Task CorrectlyDealWithLeadingTriviaInInlineSnippetInMethodTest2(string trivia) + => VerifySnippetAsync($$""" class Program { void M(int len) @@ -429,14 +393,12 @@ void M(int len) } } """); - } [Theory] [InlineData("// comment")] [InlineData("/* comment */")] - public async Task CorrectlyDealWithLeadingTriviaInInlineSnippetInGlobalStatementTest1(string trivia) - { - await VerifySnippetAsync($$""" + public Task CorrectlyDealWithLeadingTriviaInInlineSnippetInGlobalStatementTest1(string trivia) + => VerifySnippetAsync($$""" {{trivia}} 10.$$ """, $$""" @@ -446,16 +408,14 @@ await VerifySnippetAsync($$""" $$ } """); - } [Theory] [InlineData("#region test")] [InlineData("#if true")] [InlineData("#pragma warning disable CS0108")] [InlineData("#nullable enable")] - public async Task CorrectlyDealWithLeadingTriviaInInlineSnippetInGlobalStatementTest2(string trivia) - { - await VerifySnippetAsync($$""" + public Task CorrectlyDealWithLeadingTriviaInInlineSnippetInGlobalStatementTest2(string trivia) + => VerifySnippetAsync($$""" {{trivia}} 10.$$ """, $$""" @@ -466,13 +426,11 @@ await VerifySnippetAsync($$""" $$ } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/69598")] [MemberData(nameof(CommonSnippetTestData.IntegerTypes), MemberType = typeof(CommonSnippetTestData))] - public async Task InsertInlineForSnippetWhenDottingBeforeContextualKeywordTest1(string intType) - { - await VerifySnippetAsync($$""" + public Task InsertInlineForSnippetWhenDottingBeforeContextualKeywordTest1(string intType) + => VerifySnippetAsync($$""" using System.Collections.Generic; class C @@ -498,13 +456,11 @@ void M({{intType}} @int) } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/69598")] [MemberData(nameof(CommonSnippetTestData.IntegerTypes), MemberType = typeof(CommonSnippetTestData))] - public async Task InsertInlineForSnippetWhenDottingBeforeContextualKeywordTest2(string intType) - { - await VerifySnippetAsync($$""" + public Task InsertInlineForSnippetWhenDottingBeforeContextualKeywordTest2(string intType) + => VerifySnippetAsync($$""" using System.Collections.Generic; class C @@ -530,15 +486,13 @@ async void M({{intType}} @int, Task t) } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/69598")] [InlineData("Task")] [InlineData("Task")] [InlineData("System.Threading.Tasks.Task")] - public async Task InsertInlineForSnippetWhenDottingBeforeNameSyntaxTest(string nameSyntax) - { - await VerifySnippetAsync($$""" + public Task InsertInlineForSnippetWhenDottingBeforeNameSyntaxTest(string nameSyntax) + => VerifySnippetAsync($$""" using System.Threading.Tasks; using System.Collections.Generic; @@ -566,13 +520,11 @@ void M(int @int) } } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.IntegerTypes), MemberType = typeof(CommonSnippetTestData))] - public async Task InsertInlineForSnippetWhenDottingBeforeMemberAccessExpressionOnTheNextLineTest(string intType) - { - await VerifySnippetAsync($$""" + public Task InsertInlineForSnippetWhenDottingBeforeMemberAccessExpressionOnTheNextLineTest(string intType) + => VerifySnippetAsync($$""" using System; class C @@ -598,13 +550,11 @@ void M({{intType}} @int) } } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.IntegerTypes), MemberType = typeof(CommonSnippetTestData))] - public async Task NoInlineForSnippetWhenDottingBeforeMemberAccessExpressionOnTheSameLineTest(string intType) - { - await VerifySnippetIsAbsentAsync($$""" + public Task NoInlineForSnippetWhenDottingBeforeMemberAccessExpressionOnTheSameLineTest(string intType) + => VerifySnippetIsAbsentAsync($$""" class C { void M({{intType}} @int) @@ -613,13 +563,11 @@ void M({{intType}} @int) } } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.IntegerTypes), MemberType = typeof(CommonSnippetTestData))] - public async Task NoInlineForSnippetWhenDottingBeforeContextualKeywordOnTheSameLineTest(string intType) - { - await VerifySnippetIsAbsentAsync($$""" + public Task NoInlineForSnippetWhenDottingBeforeContextualKeywordOnTheSameLineTest(string intType) + => VerifySnippetIsAbsentAsync($$""" class C { void M({{intType}} @int) @@ -628,7 +576,6 @@ void M({{intType}} @int) } } """); - } [Theory] [InlineData("int[]", "Length")] @@ -639,9 +586,8 @@ void M({{intType}} @int) [InlineData("HashSet", "Count")] [InlineData("Dictionary", "Count")] [InlineData("ImmutableList", "Count")] - public async Task InsertInlineForSnippetForCommonTypesWithLengthOrCountPropertyTest(string type, string propertyName) - { - await VerifySnippetAsync($$""" + public Task InsertInlineForSnippetForCommonTypesWithLengthOrCountPropertyTest(string type, string propertyName) + => VerifySnippetAsync($$""" using System; using System.Collections.Generic; using System.Collections.Immutable; @@ -670,15 +616,13 @@ void M({{type}} type) } """, referenceAssemblies: ReferenceAssemblies.Net.Net80); - } [Theory] [CombinatorialData] - public async Task InsertInlineForSnippetForTypeWithAccessibleLengthOrCountPropertyTest( + public Task InsertInlineForSnippetForTypeWithAccessibleLengthOrCountPropertyTest( [CombinatorialValues("public", "internal", "protected internal")] string propertyAccessibility, [CombinatorialValues("Length", "Count")] string propertyName) - { - await VerifySnippetAsync($$""" + => VerifySnippetAsync($$""" class C { void M(MyType type) @@ -708,15 +652,13 @@ public class MyType {{propertyAccessibility}} int {{propertyName}} { get; } } """); - } [Theory] [CombinatorialData] - public async Task InsertInlineForSnippetForTypeWithAccessibleLengthOrCountPropertyGetterTest( + public Task InsertInlineForSnippetForTypeWithAccessibleLengthOrCountPropertyGetterTest( [CombinatorialValues("", "internal", "protected internal")] string getterAccessibility, [CombinatorialValues("Length", "Count")] string propertyName) - { - await VerifySnippetAsync($$""" + => VerifySnippetAsync($$""" class C { void M(MyType type) @@ -746,15 +688,13 @@ public class MyType public int {{propertyName}} { {{getterAccessibility}} get; } } """); - } [Theory] [CombinatorialData] - public async Task InsertInlineForSnippetForTypesWithLengthOrCountPropertyOfDifferentIntegerTypesTest( + public Task InsertInlineForSnippetForTypesWithLengthOrCountPropertyOfDifferentIntegerTypesTest( [CombinatorialValues("byte", "sbyte", "short", "ushort", "int", "uint", "long", "ulong", "nint", "nuint")] string integerType, [CombinatorialValues("Length", "Count")] string propertyName) - { - await VerifySnippetAsync($$""" + => VerifySnippetAsync($$""" class C { void M(MyType type) @@ -784,14 +724,12 @@ public class MyType public {{integerType}} {{propertyName}} { get; } } """); - } [Theory] [InlineData("Length")] [InlineData("Count")] - public async Task InsertInlineForSnippetForTypeWithLengthOrCountPropertyInBaseClassTest(string propertyName) - { - await VerifySnippetAsync($$""" + public Task InsertInlineForSnippetForTypeWithLengthOrCountPropertyInBaseClassTest(string propertyName) + => VerifySnippetAsync($$""" class C { void M(MyType type) @@ -829,14 +767,12 @@ public class MyTypeBase public int {{propertyName}} { get; } } """); - } [Theory] [InlineData("Length")] [InlineData("Count")] - public async Task NoInlineForSnippetWhenLengthOrCountPropertyHasNoGetterTest(string propertyName) - { - await VerifySnippetIsAbsentAsync($$""" + public Task NoInlineForSnippetWhenLengthOrCountPropertyHasNoGetterTest(string propertyName) + => VerifySnippetIsAbsentAsync($$""" class C { void M(MyType type) @@ -850,15 +786,13 @@ public class MyType public int {{propertyName}} { set { } } } """); - } [Theory] [CombinatorialData] - public async Task NoInlineForSnippetForInaccessibleLengthPropertyTest( + public Task NoInlineForSnippetForInaccessibleLengthPropertyTest( [CombinatorialValues("private", "protected", "private protected")] string propertyAccessibility, [CombinatorialValues("Length", "Count")] string propertyName) - { - await VerifySnippetIsAbsentAsync($$""" + => VerifySnippetIsAbsentAsync($$""" class C { void M(MyType type) @@ -872,15 +806,13 @@ public class MyType {{propertyAccessibility}} int {{propertyName}} { get; } } """); - } [Theory] [CombinatorialData] - public async Task NoInlineForSnippetForInaccessibleLengthOrCountPropertyGetterTest( + public Task NoInlineForSnippetForInaccessibleLengthOrCountPropertyGetterTest( [CombinatorialValues("private", "protected", "private protected")] string getterAccessibility, [CombinatorialValues("Length", "Count")] string propertyName) - { - await VerifySnippetIsAbsentAsync($$""" + => VerifySnippetIsAbsentAsync($$""" class C { void M(MyType type) @@ -894,15 +826,13 @@ public class MyType public int {{propertyName}} { {{getterAccessibility}} get; } } """); - } [Theory] [CombinatorialData] - public async Task NoInlineForSnippetForLengthPropertyOfIncorrectTypeTest( + public Task NoInlineForSnippetForLengthPropertyOfIncorrectTypeTest( [CombinatorialValues("object", "string", "System.DateTime", "System.Action")] string notIntegerType, [CombinatorialValues("Length", "Count")] string propertyName) - { - await VerifySnippetIsAbsentAsync($$""" + => VerifySnippetIsAbsentAsync($$""" class C { void M(MyType type) @@ -916,12 +846,10 @@ public class MyType public {{notIntegerType}} {{propertyName}} { get; } } """); - } [Fact] - public async Task NoInlineForSnippetForTypeWithBothLengthAndCountPropertyTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInlineForSnippetForTypeWithBothLengthAndCountPropertyTest() + => VerifySnippetIsAbsentAsync(""" class C { void M(MyType type) @@ -936,14 +864,12 @@ public class MyType public int Count { get; } } """); - } [Theory] [InlineData("MyType")] [MemberData(nameof(CommonSnippetTestData.IntegerTypes), MemberType = typeof(CommonSnippetTestData))] - public async Task NoInlineForSnippetForTypeItselfTest(string validTypes) - { - await VerifySnippetIsAbsentAsync($$""" + public Task NoInlineForSnippetForTypeItselfTest(string validTypes) + => VerifySnippetIsAbsentAsync($$""" class C { void M() @@ -957,14 +883,12 @@ class MyType public int Count => 0; } """); - } [Theory] [InlineData("MyType")] [MemberData(nameof(CommonSnippetTestData.IntegerTypes), MemberType = typeof(CommonSnippetTestData))] - public async Task NoInlineForSnippetForTypeItselfTest_Parenthesized(string validTypes) - { - await VerifySnippetIsAbsentAsync($$""" + public Task NoInlineForSnippetForTypeItselfTest_Parenthesized(string validTypes) + => VerifySnippetIsAbsentAsync($$""" class C { void M() @@ -978,14 +902,12 @@ class MyType public int Count => 0; } """); - } [Theory] [InlineData("MyType")] [MemberData(nameof(CommonSnippetTestData.IntegerTypes), MemberType = typeof(CommonSnippetTestData))] - public async Task NoInlineForSnippetForTypeItselfTest_BeforeContextualKeyword(string validTypes) - { - await VerifySnippetIsAbsentAsync($$""" + public Task NoInlineForSnippetForTypeItselfTest_BeforeContextualKeyword(string validTypes) + => VerifySnippetIsAbsentAsync($$""" using System.Threading.Tasks; class C @@ -1002,12 +924,10 @@ class MyType public int Count => 0; } """); - } [Fact] - public async Task InsertInlineForSnippetForVariableNamedLikeTypeTest() - { - await VerifySnippetAsync(""" + public Task InsertInlineForSnippetForVariableNamedLikeTypeTest() + => VerifySnippetAsync(""" class C { void M() @@ -1039,5 +959,4 @@ class MyType public int Length => 0; } """); - } } diff --git a/src/Features/CSharpTest/Snippets/CSharpIntMainSnippetProviderTests.cs b/src/Features/CSharpTest/Snippets/CSharpIntMainSnippetProviderTests.cs index 55b046b1ae38e..05e85b6fe47b1 100644 --- a/src/Features/CSharpTest/Snippets/CSharpIntMainSnippetProviderTests.cs +++ b/src/Features/CSharpTest/Snippets/CSharpIntMainSnippetProviderTests.cs @@ -14,34 +14,28 @@ public sealed class CSharpIntMainSnippetProviderTests : AbstractCSharpSnippetPro protected override string SnippetIdentifier => "sim"; [Fact] - public async Task TestMissingInBlockNamespace() - { - await VerifySnippetIsAbsentAsync(""" + public Task TestMissingInBlockNamespace() + => VerifySnippetIsAbsentAsync(""" namespace Test { $$ } """); - } [Fact] - public async Task TestMissingInFileScopedNamespace() - { - await VerifySnippetIsAbsentAsync(""" + public Task TestMissingInFileScopedNamespace() + => VerifySnippetIsAbsentAsync(""" namespace Test; $$ """); - } [Fact] - public async Task TestMissingInTopLevelContext() - { - await VerifySnippetIsAbsentAsync(""" + public Task TestMissingInTopLevelContext() + => VerifySnippetIsAbsentAsync(""" System.Console.WriteLine(); $$ """); - } [Theory] [InlineData("class")] @@ -50,9 +44,8 @@ await VerifySnippetIsAbsentAsync(""" [InlineData("record")] [InlineData("record class")] [InlineData("record struct")] - public async Task TestInsertSnippetInType(string type) - { - await VerifySnippetAsync($$""" + public Task TestInsertSnippetInType(string type) + => VerifySnippetAsync($$""" {{type}} Program { $$ @@ -67,23 +60,19 @@ static int Main(string[] args) } } """); - } [Fact] - public async Task TestMissingInEnum() - { - await VerifySnippetIsAbsentAsync(""" + public Task TestMissingInEnum() + => VerifySnippetIsAbsentAsync(""" enum MyEnum { $$ } """); - } [Fact] - public async Task TestMissingInMethod() - { - await VerifySnippetIsAbsentAsync(""" + public Task TestMissingInMethod() + => VerifySnippetIsAbsentAsync(""" class Program { void M() @@ -92,12 +81,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingInConstructor() - { - await VerifySnippetIsAbsentAsync(""" + public Task TestMissingInConstructor() + => VerifySnippetIsAbsentAsync(""" class Program { public Program() @@ -106,13 +93,11 @@ public Program() } } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.AllAccessibilityModifiers), MemberType = typeof(CommonSnippetTestData))] - public async Task TestInsertSnippetAfterAccessibilityModifier(string modifier) - { - await VerifySnippetAsync($$""" + public Task TestInsertSnippetAfterAccessibilityModifier(string modifier) + => VerifySnippetAsync($$""" class Program { {{modifier}} $$ @@ -127,7 +112,6 @@ class Program } } """); - } [Theory] [InlineData("static")] @@ -135,20 +119,17 @@ class Program [InlineData("abstract")] [InlineData("override")] [InlineData("file")] - public async Task TestMissingAfterIncorrectModifiers(string modifier) - { - await VerifySnippetIsAbsentAsync($$""" + public Task TestMissingAfterIncorrectModifiers(string modifier) + => VerifySnippetIsAbsentAsync($$""" class Program { {{modifier}} $$ } """); - } [Fact] - public async Task TestMissingIfAnotherMemberWithNameMainExists() - { - await VerifySnippetIsAbsentAsync(""" + public Task TestMissingIfAnotherMemberWithNameMainExists() + => VerifySnippetIsAbsentAsync(""" class Program { public int Main => 0; @@ -156,12 +137,10 @@ class Program $$ } """); - } [Fact] - public async Task TestMissingIfTopLevelStatementsArePresent() - { - await VerifySnippetIsAbsentAsync(""" + public Task TestMissingIfTopLevelStatementsArePresent() + => VerifySnippetIsAbsentAsync(""" System.Console.WriteLine(); class Program @@ -169,5 +148,4 @@ class Program $$ } """); - } } diff --git a/src/Features/CSharpTest/Snippets/CSharpInterfaceSnippetProviderTests.cs b/src/Features/CSharpTest/Snippets/CSharpInterfaceSnippetProviderTests.cs index d7f11f78611cc..fd32dba504fec 100644 --- a/src/Features/CSharpTest/Snippets/CSharpInterfaceSnippetProviderTests.cs +++ b/src/Features/CSharpTest/Snippets/CSharpInterfaceSnippetProviderTests.cs @@ -15,9 +15,8 @@ public sealed class CSharpInterfaceSnippetProviderTests : AbstractCSharpSnippetP protected override string SnippetIdentifier => "interface"; [Fact] - public async Task InsertInterfaceSnippetInBlockNamespaceTest() - { - await VerifySnippetAsync(""" + public Task InsertInterfaceSnippetInBlockNamespaceTest() + => VerifySnippetAsync(""" namespace Namespace { $$ @@ -31,12 +30,10 @@ interface {|0:MyInterface|} } } """); - } [Fact] - public async Task InsertInterfaceSnippetInFileScopedNamespaceTest() - { - await VerifySnippetAsync(""" + public Task InsertInterfaceSnippetInFileScopedNamespaceTest() + => VerifySnippetAsync(""" namespace Namespace; $$ @@ -48,12 +45,10 @@ interface {|0:MyInterface|} $$ } """); - } [Fact] - public async Task InsertInterfaceSnippetTest() - { - await VerifySnippetAsync(""" + public Task InsertInterfaceSnippetTest() + => VerifySnippetAsync(""" $$ """, """ interface {|0:MyInterface|} @@ -61,12 +56,10 @@ interface {|0:MyInterface|} $$ } """); - } [Fact] - public async Task InsertInterfaceTopLevelSnippetTest() - { - await VerifySnippetAsync(""" + public Task InsertInterfaceTopLevelSnippetTest() + => VerifySnippetAsync(""" System.Console.WriteLine(); $$ """, """ @@ -76,12 +69,10 @@ interface {|0:MyInterface|} $$ } """); - } [Fact] - public async Task InsertInterfaceSnippetInClassTest() - { - await VerifySnippetAsync(""" + public Task InsertInterfaceSnippetInClassTest() + => VerifySnippetAsync(""" class MyClass { $$ @@ -95,12 +86,10 @@ interface {|0:MyInterface|} } } """); - } [Fact] - public async Task InsertInterfaceSnippetInRecordTest() - { - await VerifySnippetAsync(""" + public Task InsertInterfaceSnippetInRecordTest() + => VerifySnippetAsync(""" record MyRecord { $$ @@ -114,12 +103,10 @@ interface {|0:MyInterface|} } } """); - } [Fact] - public async Task InsertInterfaceSnippetInStructTest() - { - await VerifySnippetAsync(""" + public Task InsertInterfaceSnippetInStructTest() + => VerifySnippetAsync(""" struct MyStruct { $$ @@ -133,12 +120,10 @@ interface {|0:MyInterface|} } } """); - } [Fact] - public async Task InsertInterfaceSnippetInInterfaceTest() - { - await VerifySnippetAsync(""" + public Task InsertInterfaceSnippetInInterfaceTest() + => VerifySnippetAsync(""" interface MyInterface { $$ @@ -152,12 +137,10 @@ interface {|0:MyInterface1|} } } """); - } [Fact] - public async Task InsertInterfaceSnippetWithModifiersTest() - { - await VerifySnippetAsync(""" + public Task InsertInterfaceSnippetWithModifiersTest() + => VerifySnippetAsync(""" $$ """, """ public interface {|0:MyInterface|} @@ -171,23 +154,19 @@ public interface {|0:MyInterface|} [*] dotnet_style_require_accessibility_modifiers = always """); - } [Fact] - public async Task NoInterfaceSnippetInEnumTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInterfaceSnippetInEnumTest() + => VerifySnippetIsAbsentAsync(""" enum MyEnum { $$ } """); - } [Fact] - public async Task NoInterfaceSnippetInMethodTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInterfaceSnippetInMethodTest() + => VerifySnippetIsAbsentAsync(""" class Program { public void Method() @@ -196,12 +175,10 @@ public void Method() } } """); - } [Fact] - public async Task NoInterfaceSnippetInConstructorTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInterfaceSnippetInConstructorTest() + => VerifySnippetIsAbsentAsync(""" class Program { public Program() @@ -210,13 +187,11 @@ public Program() } } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.AllAccessibilityModifiers), MemberType = typeof(CommonSnippetTestData))] - public async Task InsertInterfaceSnippetAfterAccessibilityModifier(string modifier) - { - await VerifySnippetAsync($""" + public Task InsertInterfaceSnippetAfterAccessibilityModifier(string modifier) + => VerifySnippetAsync($""" {modifier} $$ """, $$""" {{modifier}} interface {|0:MyInterface|} @@ -224,13 +199,11 @@ await VerifySnippetAsync($""" $$ } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.AllAccessibilityModifiers), MemberType = typeof(CommonSnippetTestData))] - public async Task InsertInterfaceSnippetAfterAccessibilityModifier_RequireAccessibilityModifiers(string modifier) - { - await VerifySnippetAsync($""" + public Task InsertInterfaceSnippetAfterAccessibilityModifier_RequireAccessibilityModifiers(string modifier) + => VerifySnippetAsync($""" {modifier} $$ """, $$""" {{modifier}} interface {|0:MyInterface|} @@ -244,13 +217,11 @@ await VerifySnippetAsync($""" [*] dotnet_style_require_accessibility_modifiers = always """); - } [Theory] [InlineData("unsafe")] - public async Task InsertInterfaceSnippetAfterValidModifiersTest(string modifier) - { - await VerifySnippetAsync($""" + public Task InsertInterfaceSnippetAfterValidModifiersTest(string modifier) + => VerifySnippetAsync($""" {modifier} $$ """, $$""" {{modifier}} interface {|0:MyInterface|} @@ -258,7 +229,6 @@ await VerifySnippetAsync($""" $$ } """); - } [Theory] [InlineData("abstract")] @@ -266,18 +236,15 @@ await VerifySnippetAsync($""" [InlineData("static")] [InlineData("ref")] [InlineData("readonly")] - public async Task NoInterfaceSnippetAfterInvalidModifiersTest(string modifier) - { - await VerifySnippetIsAbsentAsync($""" + public Task NoInterfaceSnippetAfterInvalidModifiersTest(string modifier) + => VerifySnippetIsAbsentAsync($""" {modifier} $$ """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/69600")] [MemberData(nameof(CommonSnippetTestData.AllAccessibilityModifiers), MemberType = typeof(CommonSnippetTestData))] - public async Task NoAdditionalAccessibilityModifiersIfAfterPartialKeywordTest(string modifier) - { - await VerifySnippetAsync($""" + public Task NoAdditionalAccessibilityModifiersIfAfterPartialKeywordTest(string modifier) + => VerifySnippetAsync($""" {modifier} partial $$ """, $$""" {{modifier}} partial interface {|0:MyInterface|} @@ -291,12 +258,10 @@ await VerifySnippetAsync($""" [*] dotnet_style_require_accessibility_modifiers = always """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69600")] - public async Task EnsureCorrectModifierOrderAfterPartialKeywordTest() - { - await VerifySnippetAsync(""" + public Task EnsureCorrectModifierOrderAfterPartialKeywordTest() + => VerifySnippetAsync(""" partial $$ """, """ public partial interface {|0:MyInterface|} @@ -310,5 +275,4 @@ public partial interface {|0:MyInterface|} [*] dotnet_style_require_accessibility_modifiers = always """); - } } diff --git a/src/Features/CSharpTest/Snippets/CSharpLockSnippetProviderTests.cs b/src/Features/CSharpTest/Snippets/CSharpLockSnippetProviderTests.cs index 41e9169b6b948..d9cdcb48d4b09 100644 --- a/src/Features/CSharpTest/Snippets/CSharpLockSnippetProviderTests.cs +++ b/src/Features/CSharpTest/Snippets/CSharpLockSnippetProviderTests.cs @@ -14,9 +14,8 @@ public sealed class CSharpLockSnippetProviderTests : AbstractCSharpSnippetProvid protected override string SnippetIdentifier => "lock"; [Fact] - public async Task InsertLockSnippetInMethodTest() - { - await VerifySnippetAsync(""" + public Task InsertLockSnippetInMethodTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -36,12 +35,10 @@ public void Method() } } """); - } [Fact] - public async Task InsertLockSnippetInGlobalContextTest() - { - await VerifySnippetAsync(""" + public Task InsertLockSnippetInGlobalContextTest() + => VerifySnippetAsync(""" $$ """, """ lock ({|0:this|}) @@ -49,32 +46,26 @@ await VerifySnippetAsync(""" $$ } """); - } [Fact] - public async Task NoLockSnippetInBlockNamespaceTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoLockSnippetInBlockNamespaceTest() + => VerifySnippetIsAbsentAsync(""" namespace Namespace { $$ } """); - } [Fact] - public async Task NoLockSnippetInFileScopedNamespaceTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoLockSnippetInFileScopedNamespaceTest() + => VerifySnippetIsAbsentAsync(""" namespace Namespace; $$ """); - } [Fact] - public async Task InsertLockSnippetInConstructorTest() - { - await VerifySnippetAsync(""" + public Task InsertLockSnippetInConstructorTest() + => VerifySnippetAsync(""" class Program { public Program() @@ -94,23 +85,19 @@ public Program() } } """); - } [Fact] - public async Task NoLockSnippetInTypeBodyTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoLockSnippetInTypeBodyTest() + => VerifySnippetIsAbsentAsync(""" class Program { $$ } """); - } [Fact] - public async Task InsertLockSnippetInLocalFunctionTest() - { - await VerifySnippetAsync(""" + public Task InsertLockSnippetInLocalFunctionTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -136,12 +123,10 @@ void LocalFunction() } } """); - } [Fact] - public async Task InsertLockSnippetInAnonymousFunctionTest() - { - await VerifySnippetAsync(""" + public Task InsertLockSnippetInAnonymousFunctionTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -167,12 +152,10 @@ public void Method() } } """); - } [Fact] - public async Task InsertLockSnippetInParenthesizedLambdaExpressionTest() - { - await VerifySnippetAsync(""" + public Task InsertLockSnippetInParenthesizedLambdaExpressionTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -198,5 +181,4 @@ public void Method() } } """); - } } diff --git a/src/Features/CSharpTest/Snippets/CSharpPropSnippetProviderTests.cs b/src/Features/CSharpTest/Snippets/CSharpPropSnippetProviderTests.cs index 5b13ab35d4a6e..23148b8fb88d9 100644 --- a/src/Features/CSharpTest/Snippets/CSharpPropSnippetProviderTests.cs +++ b/src/Features/CSharpTest/Snippets/CSharpPropSnippetProviderTests.cs @@ -13,21 +13,16 @@ public sealed class CSharpPropSnippetProviderTests : AbstractCSharpAutoPropertyS protected override string DefaultPropertyBlockText => "{ get; set; }"; - public override async Task InsertSnippetInReadonlyStructTest() - { - // Ensure we don't generate redundant `set` accessor when executed in readonly struct - await VerifyPropertyAsync(""" + public override Task InsertSnippetInReadonlyStructTest() + => VerifyPropertyAsync(""" readonly struct MyStruct { $$ } """, "public {|0:int|} {|1:MyProperty|} { get; }"); - } - public override async Task InsertSnippetInReadonlyStructTest_ReadonlyModifierInOtherPartialDeclaration() - { - // Ensure we don't generate redundant `set` accessor when executed in readonly struct - await VerifyPropertyAsync(""" + public override Task InsertSnippetInReadonlyStructTest_ReadonlyModifierInOtherPartialDeclaration() + => VerifyPropertyAsync(""" partial struct MyStruct { $$ @@ -37,15 +32,9 @@ readonly partial struct MyStruct { } """, "public {|0:int|} {|1:MyProperty|} { get; }"); - } - public override async Task InsertSnippetInReadonlyStructTest_ReadonlyModifierInOtherPartialDeclaration_MissingPartialModifier() - { - // Even though there is no `partial` modifier on the first declaration - // compiler still treats the whole type as partial since it is more likely that - // the user's intent was to have a partial type and they just forgot the modifier. - // Thus we still recognize that as `readonly` context and don't generate a setter - await VerifyPropertyAsync(""" + public override Task InsertSnippetInReadonlyStructTest_ReadonlyModifierInOtherPartialDeclaration_MissingPartialModifier() + => VerifyPropertyAsync(""" struct MyStruct { $$ @@ -55,17 +44,14 @@ readonly partial struct MyStruct { } """, "public {|0:int|} {|1:MyProperty|} { get; }"); - } - public override async Task VerifySnippetInInterfaceTest() - { - await VerifyDefaultPropertyAsync(""" + public override Task VerifySnippetInInterfaceTest() + => VerifyDefaultPropertyAsync(""" interface MyInterface { $$ } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.AllAccessibilityModifiers), MemberType = typeof(CommonSnippetTestData))] diff --git a/src/Features/CSharpTest/Snippets/CSharpPropgSnippetProviderTests.cs b/src/Features/CSharpTest/Snippets/CSharpPropgSnippetProviderTests.cs index 2f4a46a5ea84d..00c331badd041 100644 --- a/src/Features/CSharpTest/Snippets/CSharpPropgSnippetProviderTests.cs +++ b/src/Features/CSharpTest/Snippets/CSharpPropgSnippetProviderTests.cs @@ -13,21 +13,16 @@ public sealed class CSharpPropgSnippetProviderTests : AbstractCSharpAutoProperty protected override string DefaultPropertyBlockText => "{ get; private set; }"; - public override async Task InsertSnippetInReadonlyStructTest() - { - // Ensure we don't generate redundant `set` accessor when executed in readonly struct - await VerifyPropertyAsync(""" + public override Task InsertSnippetInReadonlyStructTest() + => VerifyPropertyAsync(""" readonly struct MyStruct { $$ } """, "public {|0:int|} {|1:MyProperty|} { get; }"); - } - public override async Task InsertSnippetInReadonlyStructTest_ReadonlyModifierInOtherPartialDeclaration() - { - // Ensure we don't generate redundant `set` accessor when executed in readonly struct - await VerifyPropertyAsync(""" + public override Task InsertSnippetInReadonlyStructTest_ReadonlyModifierInOtherPartialDeclaration() + => VerifyPropertyAsync(""" partial struct MyStruct { $$ @@ -37,15 +32,9 @@ readonly partial struct MyStruct { } """, "public {|0:int|} {|1:MyProperty|} { get; }"); - } - public override async Task InsertSnippetInReadonlyStructTest_ReadonlyModifierInOtherPartialDeclaration_MissingPartialModifier() - { - // Even though there is no `partial` modifier on the first declaration - // compiler still treats the whole type as partial since it is more likely that - // the user's intent was to have a partial type and they just forgot the modifier. - // Thus we still recognize that as `readonly` context and don't generate a setter - await VerifyPropertyAsync(""" + public override Task InsertSnippetInReadonlyStructTest_ReadonlyModifierInOtherPartialDeclaration_MissingPartialModifier() + => VerifyPropertyAsync(""" struct MyStruct { $$ @@ -55,18 +44,14 @@ readonly partial struct MyStruct { } """, "public {|0:int|} {|1:MyProperty|} { get; }"); - } - public override async Task VerifySnippetInInterfaceTest() - { - // Ensure we don't generate redundant `set` accessor when executed in interface - await VerifyPropertyAsync(""" + public override Task VerifySnippetInInterfaceTest() + => VerifyPropertyAsync(""" interface MyInterface { $$ } """, "public {|0:int|} {|1:MyProperty|} { get; }"); - } [Theory] [MemberData(nameof(CommonSnippetTestData.AllAccessibilityModifiers), MemberType = typeof(CommonSnippetTestData))] diff --git a/src/Features/CSharpTest/Snippets/CSharpPropiSnippetProviderTests.cs b/src/Features/CSharpTest/Snippets/CSharpPropiSnippetProviderTests.cs index 38ab037b43245..0850ef516d660 100644 --- a/src/Features/CSharpTest/Snippets/CSharpPropiSnippetProviderTests.cs +++ b/src/Features/CSharpTest/Snippets/CSharpPropiSnippetProviderTests.cs @@ -13,19 +13,16 @@ public sealed class CSharpPropiSnippetProviderTests : AbstractCSharpAutoProperty protected override string DefaultPropertyBlockText => "{ get; init; }"; - public override async Task InsertSnippetInReadonlyStructTest() - { - await VerifyDefaultPropertyAsync(""" + public override Task InsertSnippetInReadonlyStructTest() + => VerifyDefaultPropertyAsync(""" readonly struct MyStruct { $$ } """); - } - public override async Task InsertSnippetInReadonlyStructTest_ReadonlyModifierInOtherPartialDeclaration() - { - await VerifyDefaultPropertyAsync(""" + public override Task InsertSnippetInReadonlyStructTest_ReadonlyModifierInOtherPartialDeclaration() + => VerifyDefaultPropertyAsync(""" partial struct MyStruct { $$ @@ -35,11 +32,9 @@ readonly partial struct MyStruct { } """); - } - public override async Task InsertSnippetInReadonlyStructTest_ReadonlyModifierInOtherPartialDeclaration_MissingPartialModifier() - { - await VerifyDefaultPropertyAsync(""" + public override Task InsertSnippetInReadonlyStructTest_ReadonlyModifierInOtherPartialDeclaration_MissingPartialModifier() + => VerifyDefaultPropertyAsync(""" struct MyStruct { $$ @@ -49,17 +44,14 @@ readonly partial struct MyStruct { } """); - } - public override async Task VerifySnippetInInterfaceTest() - { - await VerifyDefaultPropertyAsync(""" + public override Task VerifySnippetInInterfaceTest() + => VerifyDefaultPropertyAsync(""" interface MyInterface { $$ } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.AllAccessibilityModifiers), MemberType = typeof(CommonSnippetTestData))] diff --git a/src/Features/CSharpTest/Snippets/CSharpProprSnippetProviderTests.cs b/src/Features/CSharpTest/Snippets/CSharpProprSnippetProviderTests.cs index e905241afd8f4..c1eed413d6c5a 100644 --- a/src/Features/CSharpTest/Snippets/CSharpProprSnippetProviderTests.cs +++ b/src/Features/CSharpTest/Snippets/CSharpProprSnippetProviderTests.cs @@ -14,21 +14,16 @@ public sealed class CSharpProprSnippetProviderTests : AbstractCSharpAutoProperty protected override string DefaultPropertyBlockText => "{ get; set; }"; - public override async Task InsertSnippetInReadonlyStructTest() - { - // Ensure we don't generate redundant `set` accessor when executed in readonly struct - await VerifyPropertyAsync(""" + public override Task InsertSnippetInReadonlyStructTest() + => VerifyPropertyAsync(""" readonly struct MyStruct { $$ } """, "public required {|0:int|} {|1:MyProperty|} { get; }"); - } - public override async Task InsertSnippetInReadonlyStructTest_ReadonlyModifierInOtherPartialDeclaration() - { - // Ensure we don't generate redundant `set` accessor when executed in readonly struct - await VerifyPropertyAsync(""" + public override Task InsertSnippetInReadonlyStructTest_ReadonlyModifierInOtherPartialDeclaration() + => VerifyPropertyAsync(""" partial struct MyStruct { $$ @@ -38,15 +33,9 @@ readonly partial struct MyStruct { } """, "public required {|0:int|} {|1:MyProperty|} { get; }"); - } - public override async Task InsertSnippetInReadonlyStructTest_ReadonlyModifierInOtherPartialDeclaration_MissingPartialModifier() - { - // Even though there is no `partial` modifier on the first declaration - // compiler still treats the whole type as partial since it is more likely that - // the user's intent was to have a partial type and they just forgot the modifier. - // Thus we still recognize that as `readonly` context and don't generate a setter - await VerifyPropertyAsync(""" + public override Task InsertSnippetInReadonlyStructTest_ReadonlyModifierInOtherPartialDeclaration_MissingPartialModifier() + => VerifyPropertyAsync(""" struct MyStruct { $$ @@ -56,45 +45,38 @@ readonly partial struct MyStruct { } """, "public required {|0:int|} {|1:MyProperty|} { get; }"); - } - public override async Task VerifySnippetInInterfaceTest() - { - await VerifySnippetIsAbsentAsync(""" + public override Task VerifySnippetInInterfaceTest() + => VerifySnippetIsAbsentAsync(""" interface MyInterface { $$ } """); - } [Theory] [InlineData("public")] [InlineData("internal")] [InlineData("protected internal")] - public override async Task InsertSnippetAfterAllowedAccessibilityModifierTest(string modifier) - { - await VerifyPropertyAsync($$""" + public override Task InsertSnippetAfterAllowedAccessibilityModifierTest(string modifier) + => VerifyPropertyAsync($$""" class Program { {{modifier}} $$ } """, $$"""required {|0:int|} {|1:MyProperty|} {{DefaultPropertyBlockText}}"""); - } [Theory] [InlineData("private")] [InlineData("protected")] [InlineData("private protected")] - public async Task NoSnippetAfterWrongAccessibilityModifierTest(string modifier) - { - await VerifySnippetIsAbsentAsync($$""" + public Task NoSnippetAfterWrongAccessibilityModifierTest(string modifier) + => VerifySnippetIsAbsentAsync($$""" class Program { {{modifier}} $$ } """); - } protected override Task VerifyDefaultPropertyAsync([StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string markup, string propertyName = "MyProperty") => VerifyPropertyAsync(markup, $$"""public required {|0:int|} {|1:{{propertyName}}|} {{DefaultPropertyBlockText}}"""); diff --git a/src/Features/CSharpTest/Snippets/CSharpReversedForSnippetProviderTests.cs b/src/Features/CSharpTest/Snippets/CSharpReversedForSnippetProviderTests.cs index c29a2e87b6e79..ed56c20ff0255 100644 --- a/src/Features/CSharpTest/Snippets/CSharpReversedForSnippetProviderTests.cs +++ b/src/Features/CSharpTest/Snippets/CSharpReversedForSnippetProviderTests.cs @@ -16,9 +16,8 @@ public sealed class CSharpReversedForSnippetProviderTests : AbstractCSharpSnippe protected override string SnippetIdentifier => "forr"; [Fact] - public async Task InsertReversedForSnippetInMethodTest() - { - await VerifySnippetAsync(""" + public Task InsertReversedForSnippetInMethodTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -38,12 +37,10 @@ public void Method() } } """); - } [Fact] - public async Task InsertReversedForSnippetInMethodUsedIncrementorTest() - { - await VerifySnippetAsync(""" + public Task InsertReversedForSnippetInMethodUsedIncrementorTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -65,12 +62,10 @@ public void Method() } } """); - } [Fact] - public async Task InsertReversedForSnippetInMethodUsedIncrementorsTest() - { - await VerifySnippetAsync(""" + public Task InsertReversedForSnippetInMethodUsedIncrementorsTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -92,12 +87,10 @@ public void Method() } } """); - } [Fact] - public async Task InsertReversedForSnippetInGlobalContextTest() - { - await VerifySnippetAsync(""" + public Task InsertReversedForSnippetInGlobalContextTest() + => VerifySnippetAsync(""" $$ """, """ for (int {|0:i|} = {|1:length|} - 1; {|0:i|} >= 0; {|0:i|}--) @@ -105,12 +98,10 @@ await VerifySnippetAsync(""" $$ } """); - } [Fact] - public async Task InsertReversedForSnippetInConstructorTest() - { - await VerifySnippetAsync(""" + public Task InsertReversedForSnippetInConstructorTest() + => VerifySnippetAsync(""" class Program { public Program() @@ -130,13 +121,10 @@ public Program() } } """); - } [Fact] - public async Task InsertReversedForSnippetInLocalFunctionTest() - { - // TODO: fix this test when bug with simplifier failing to find correct node is fixed - await VerifySnippetAsync(""" + public Task InsertReversedForSnippetInLocalFunctionTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -162,13 +150,10 @@ void LocalFunction() } } """); - } [Fact] - public async Task InsertReversedForSnippetInAnonymousFunctionTest() - { - // TODO: fix this test when bug with simplifier failing to find correct node is fixed - await VerifySnippetAsync(""" + public Task InsertReversedForSnippetInAnonymousFunctionTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -194,13 +179,10 @@ public void Method() } } """); - } [Fact] - public async Task InsertReversedForSnippetInParenthesizedLambdaExpressionTest() - { - // TODO: fix this test when bug with simplifier failing to find correct node is fixed - await VerifySnippetAsync(""" + public Task InsertReversedForSnippetInParenthesizedLambdaExpressionTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -226,14 +208,10 @@ public void Method() } } """); - } [Fact] - public async Task TryToProduceVarWithSpecificCodeStyleTest() - { - // In non-inline reversed for snippet type of expression `length - 1` is unknown, - // so it cannot be simplified to `var`. Therefore having explicit `int` type here is expected - await VerifySnippetAsync(""" + public Task TryToProduceVarWithSpecificCodeStyleTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -259,13 +237,11 @@ public void Method() [*] csharp_style_var_for_built_in_types = true """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.IntegerTypes), MemberType = typeof(CommonSnippetTestData))] - public async Task InsertInlineReversedForSnippetInMethodTest(string inlineExpressionType) - { - await VerifySnippetAsync($$""" + public Task InsertInlineReversedForSnippetInMethodTest(string inlineExpressionType) + => VerifySnippetAsync($$""" class Program { public void Method({{inlineExpressionType}} l) @@ -285,13 +261,11 @@ public void Method({{inlineExpressionType}} l) } } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.IntegerTypes), MemberType = typeof(CommonSnippetTestData))] - public async Task InsertInlineReversedForSnippetInGlobalContextTest(string inlineExpressionType) - { - await VerifySnippetAsync($$""" + public Task InsertInlineReversedForSnippetInGlobalContextTest(string inlineExpressionType) + => VerifySnippetAsync($$""" {{inlineExpressionType}} l; l.$$ """, $$""" @@ -301,13 +275,11 @@ await VerifySnippetAsync($$""" $$ } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.NotIntegerTypesWithoutLengthOrCountProperty), MemberType = typeof(CommonSnippetTestData))] - public async Task NoInlineReversedForSnippetForIncorrectTypeInMethodTest(string inlineExpressionType) - { - await VerifySnippetIsAbsentAsync($$""" + public Task NoInlineReversedForSnippetForIncorrectTypeInMethodTest(string inlineExpressionType) + => VerifySnippetIsAbsentAsync($$""" class Program { public void Method({{inlineExpressionType}} l) @@ -316,22 +288,18 @@ public void Method({{inlineExpressionType}} l) } } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.NotIntegerTypesWithoutLengthOrCountProperty), MemberType = typeof(CommonSnippetTestData))] - public async Task NoInlineReversedForSnippetForIncorrectTypeInGlobalContextTest(string inlineExpressionType) - { - await VerifySnippetIsAbsentAsync($$""" + public Task NoInlineReversedForSnippetForIncorrectTypeInGlobalContextTest(string inlineExpressionType) + => VerifySnippetIsAbsentAsync($$""" {{inlineExpressionType}} l; l.$$ """); - } [Fact] - public async Task ProduceVarWithSpecificCodeStyleForInlineSnippetTest() - { - await VerifySnippetAsync(""" + public Task ProduceVarWithSpecificCodeStyleForInlineSnippetTest() + => VerifySnippetAsync(""" class Program { public void Method(int l) @@ -357,12 +325,10 @@ public void Method(int l) [*] csharp_style_var_for_built_in_types = true """); - } [Fact] - public async Task NoInlineReversedForSnippetNotDirectlyExpressionStatementTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInlineReversedForSnippetNotDirectlyExpressionStatementTest() + => VerifySnippetIsAbsentAsync(""" class Program { public void Method(int l) @@ -371,15 +337,13 @@ public void Method(int l) } } """); - } [Theory] [InlineData("// comment")] [InlineData("/* comment */")] [InlineData("#region test")] - public async Task CorrectlyDealWithLeadingTriviaInInlineSnippetInMethodTest1(string trivia) - { - await VerifySnippetAsync($$""" + public Task CorrectlyDealWithLeadingTriviaInInlineSnippetInMethodTest1(string trivia) + => VerifySnippetAsync($$""" class Program { void M(int len) @@ -401,15 +365,13 @@ void M(int len) } } """); - } [Theory] [InlineData("#if true")] [InlineData("#pragma warning disable CS0108")] [InlineData("#nullable enable")] - public async Task CorrectlyDealWithLeadingTriviaInInlineSnippetInMethodTest2(string trivia) - { - await VerifySnippetAsync($$""" + public Task CorrectlyDealWithLeadingTriviaInInlineSnippetInMethodTest2(string trivia) + => VerifySnippetAsync($$""" class Program { void M(int len) @@ -431,14 +393,12 @@ void M(int len) } } """); - } [Theory] [InlineData("// comment")] [InlineData("/* comment */")] - public async Task CorrectlyDealWithLeadingTriviaInInlineSnippetInGlobalStatementTest1(string trivia) - { - await VerifySnippetAsync($$""" + public Task CorrectlyDealWithLeadingTriviaInInlineSnippetInGlobalStatementTest1(string trivia) + => VerifySnippetAsync($$""" {{trivia}} 10.$$ """, $$""" @@ -448,16 +408,14 @@ await VerifySnippetAsync($$""" $$ } """); - } [Theory] [InlineData("#region test")] [InlineData("#if true")] [InlineData("#pragma warning disable CS0108")] [InlineData("#nullable enable")] - public async Task CorrectlyDealWithLeadingTriviaInInlineSnippetInGlobalStatementTest2(string trivia) - { - await VerifySnippetAsync($$""" + public Task CorrectlyDealWithLeadingTriviaInInlineSnippetInGlobalStatementTest2(string trivia) + => VerifySnippetAsync($$""" {{trivia}} 10.$$ """, $$""" @@ -468,13 +426,11 @@ await VerifySnippetAsync($$""" $$ } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/69598")] [MemberData(nameof(CommonSnippetTestData.IntegerTypes), MemberType = typeof(CommonSnippetTestData))] - public async Task InsertInlineReversedForSnippetWhenDottingBeforeContextualKeywordTest1(string intType) - { - await VerifySnippetAsync($$""" + public Task InsertInlineReversedForSnippetWhenDottingBeforeContextualKeywordTest1(string intType) + => VerifySnippetAsync($$""" using System.Collections.Generic; class C @@ -500,13 +456,11 @@ void M({{intType}} @int) } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/69598")] [MemberData(nameof(CommonSnippetTestData.IntegerTypes), MemberType = typeof(CommonSnippetTestData))] - public async Task InsertInlineReversedForSnippetWhenDottingBeforeContextualKeywordTest2(string intType) - { - await VerifySnippetAsync($$""" + public Task InsertInlineReversedForSnippetWhenDottingBeforeContextualKeywordTest2(string intType) + => VerifySnippetAsync($$""" using System.Collections.Generic; class C @@ -532,15 +486,13 @@ async void M({{intType}} @int, Task t) } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/69598")] [InlineData("Task")] [InlineData("Task")] [InlineData("System.Threading.Tasks.Task")] - public async Task InsertInlineReversedForSnippetWhenDottingBeforeNameSyntaxTest(string nameSyntax) - { - await VerifySnippetAsync($$""" + public Task InsertInlineReversedForSnippetWhenDottingBeforeNameSyntaxTest(string nameSyntax) + => VerifySnippetAsync($$""" using System.Threading.Tasks; using System.Collections.Generic; @@ -568,13 +520,11 @@ void M(int @int) } } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.IntegerTypes), MemberType = typeof(CommonSnippetTestData))] - public async Task InsertInlineReversedForSnippetWhenDottingBeforeMemberAccessExpressionOnTheNextLineTest(string intType) - { - await VerifySnippetAsync($$""" + public Task InsertInlineReversedForSnippetWhenDottingBeforeMemberAccessExpressionOnTheNextLineTest(string intType) + => VerifySnippetAsync($$""" using System; class C @@ -600,13 +550,11 @@ void M({{intType}} @int) } } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.IntegerTypes), MemberType = typeof(CommonSnippetTestData))] - public async Task NoInlineReversedForSnippetWhenDottingBeforeMemberAccessExpressionOnTheSameLineTest(string intType) - { - await VerifySnippetIsAbsentAsync($$""" + public Task NoInlineReversedForSnippetWhenDottingBeforeMemberAccessExpressionOnTheSameLineTest(string intType) + => VerifySnippetIsAbsentAsync($$""" class C { void M({{intType}} @int) @@ -615,13 +563,11 @@ void M({{intType}} @int) } } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.IntegerTypes), MemberType = typeof(CommonSnippetTestData))] - public async Task NoInlineReversedForSnippetWhenDottingBeforeContextualKeywordOnTheSameLineTest(string intType) - { - await VerifySnippetIsAbsentAsync($$""" + public Task NoInlineReversedForSnippetWhenDottingBeforeContextualKeywordOnTheSameLineTest(string intType) + => VerifySnippetIsAbsentAsync($$""" class C { void M({{intType}} @int) @@ -630,7 +576,6 @@ void M({{intType}} @int) } } """); - } [Theory] [InlineData("int[]", "Length")] @@ -641,9 +586,8 @@ void M({{intType}} @int) [InlineData("HashSet", "Count")] [InlineData("Dictionary", "Count")] [InlineData("ImmutableList", "Count")] - public async Task InsertInlineReversedForSnippetForCommonTypesWithLengthOrCountPropertyTest(string type, string propertyName) - { - await VerifySnippetAsync($$""" + public Task InsertInlineReversedForSnippetForCommonTypesWithLengthOrCountPropertyTest(string type, string propertyName) + => VerifySnippetAsync($$""" using System; using System.Collections.Generic; using System.Collections.Immutable; @@ -672,15 +616,13 @@ void M({{type}} type) } """, referenceAssemblies: ReferenceAssemblies.Net.Net80); - } [Theory] [CombinatorialData] - public async Task InsertInlineReversedForSnippetForTypeWithAccessibleLengthOrCountPropertyTest( + public Task InsertInlineReversedForSnippetForTypeWithAccessibleLengthOrCountPropertyTest( [CombinatorialValues("public", "internal", "protected internal")] string propertyAccessibility, [CombinatorialValues("Length", "Count")] string propertyName) - { - await VerifySnippetAsync($$""" + => VerifySnippetAsync($$""" class C { void M(MyType type) @@ -710,15 +652,13 @@ public class MyType {{propertyAccessibility}} int {{propertyName}} { get; } } """); - } [Theory] [CombinatorialData] - public async Task InsertInlineReversedForSnippetForTypeWithAccessibleLengthOrCountPropertyGetterTest( + public Task InsertInlineReversedForSnippetForTypeWithAccessibleLengthOrCountPropertyGetterTest( [CombinatorialValues("", "internal", "protected internal")] string getterAccessibility, [CombinatorialValues("Length", "Count")] string propertyName) - { - await VerifySnippetAsync($$""" + => VerifySnippetAsync($$""" class C { void M(MyType type) @@ -748,15 +688,13 @@ public class MyType public int {{propertyName}} { {{getterAccessibility}} get; } } """); - } [Theory] [CombinatorialData] - public async Task InsertInlineReversedForSnippetForTypesWithLengthOrCountPropertyOfDifferentIntegerTypesTest( + public Task InsertInlineReversedForSnippetForTypesWithLengthOrCountPropertyOfDifferentIntegerTypesTest( [CombinatorialValues("byte", "sbyte", "short", "ushort", "int", "uint", "long", "ulong", "nint", "nuint")] string integerType, [CombinatorialValues("Length", "Count")] string propertyName) - { - await VerifySnippetAsync($$""" + => VerifySnippetAsync($$""" class C { void M(MyType type) @@ -786,14 +724,12 @@ public class MyType public {{integerType}} {{propertyName}} { get; } } """); - } [Theory] [InlineData("Length")] [InlineData("Count")] - public async Task InsertInlineReversedForSnippetForTypeWithLengthOrCountPropertyInBaseClassTest(string propertyName) - { - await VerifySnippetAsync($$""" + public Task InsertInlineReversedForSnippetForTypeWithLengthOrCountPropertyInBaseClassTest(string propertyName) + => VerifySnippetAsync($$""" class C { void M(MyType type) @@ -831,14 +767,12 @@ public class MyTypeBase public int {{propertyName}} { get; } } """); - } [Theory] [InlineData("Length")] [InlineData("Count")] - public async Task NoInlineReversedForSnippetWhenLengthOrCountPropertyHasNoGetterTest(string propertyName) - { - await VerifySnippetIsAbsentAsync($$""" + public Task NoInlineReversedForSnippetWhenLengthOrCountPropertyHasNoGetterTest(string propertyName) + => VerifySnippetIsAbsentAsync($$""" class C { void M(MyType type) @@ -852,15 +786,13 @@ public class MyType public int {{propertyName}} { set { } } } """); - } [Theory] [CombinatorialData] - public async Task NoInlineReversedForSnippetForInaccessibleLengthPropertyTest( + public Task NoInlineReversedForSnippetForInaccessibleLengthPropertyTest( [CombinatorialValues("private", "protected", "private protected")] string propertyAccessibility, [CombinatorialValues("Length", "Count")] string propertyName) - { - await VerifySnippetIsAbsentAsync($$""" + => VerifySnippetIsAbsentAsync($$""" class C { void M(MyType type) @@ -874,15 +806,13 @@ public class MyType {{propertyAccessibility}} int {{propertyName}} { get; } } """); - } [Theory] [CombinatorialData] - public async Task NoInlineReversedForSnippetForInaccessibleLengthOrCountPropertyGetterTest( + public Task NoInlineReversedForSnippetForInaccessibleLengthOrCountPropertyGetterTest( [CombinatorialValues("private", "protected", "private protected")] string getterAccessibility, [CombinatorialValues("Length", "Count")] string propertyName) - { - await VerifySnippetIsAbsentAsync($$""" + => VerifySnippetIsAbsentAsync($$""" class C { void M(MyType type) @@ -896,15 +826,13 @@ public class MyType public int {{propertyName}} { {{getterAccessibility}} get; } } """); - } [Theory] [CombinatorialData] - public async Task NoInlineReversedForSnippetForLengthPropertyOfIncorrectTypeTest( + public Task NoInlineReversedForSnippetForLengthPropertyOfIncorrectTypeTest( [CombinatorialValues("object", "string", "System.DateTime", "System.Action")] string notIntegerType, [CombinatorialValues("Length", "Count")] string propertyName) - { - await VerifySnippetIsAbsentAsync($$""" + => VerifySnippetIsAbsentAsync($$""" class C { void M(MyType type) @@ -918,12 +846,10 @@ public class MyType public {{notIntegerType}} {{propertyName}} { get; } } """); - } [Fact] - public async Task NoInlineReversedForSnippetForTypeWithBothLengthAndCountPropertyTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoInlineReversedForSnippetForTypeWithBothLengthAndCountPropertyTest() + => VerifySnippetIsAbsentAsync(""" class C { void M(MyType type) @@ -938,14 +864,12 @@ public class MyType public int Count { get; } } """); - } [Theory] [InlineData("MyType")] [MemberData(nameof(CommonSnippetTestData.IntegerTypes), MemberType = typeof(CommonSnippetTestData))] - public async Task NoInlineReversedForSnippetForTypeItselfTest(string validTypes) - { - await VerifySnippetIsAbsentAsync($$""" + public Task NoInlineReversedForSnippetForTypeItselfTest(string validTypes) + => VerifySnippetIsAbsentAsync($$""" class C { void M() @@ -959,14 +883,12 @@ class MyType public int Count => 0; } """); - } [Theory] [InlineData("MyType")] [MemberData(nameof(CommonSnippetTestData.IntegerTypes), MemberType = typeof(CommonSnippetTestData))] - public async Task NoInlineReversedForSnippetForTypeItselfTest_Parenthesized(string validTypes) - { - await VerifySnippetIsAbsentAsync($$""" + public Task NoInlineReversedForSnippetForTypeItselfTest_Parenthesized(string validTypes) + => VerifySnippetIsAbsentAsync($$""" class C { void M() @@ -980,14 +902,12 @@ class MyType public int Count => 0; } """); - } [Theory] [InlineData("MyType")] [MemberData(nameof(CommonSnippetTestData.IntegerTypes), MemberType = typeof(CommonSnippetTestData))] - public async Task NoInlineReversedForSnippetForTypeItselfTest_BeforeContextualKeyword(string validTypes) - { - await VerifySnippetIsAbsentAsync($$""" + public Task NoInlineReversedForSnippetForTypeItselfTest_BeforeContextualKeyword(string validTypes) + => VerifySnippetIsAbsentAsync($$""" using System.Threading.Tasks; class C @@ -1004,12 +924,10 @@ class MyType public int Count => 0; } """); - } [Fact] - public async Task InsertInlineReversedForSnippetForVariableNamedLikeTypeTest() - { - await VerifySnippetAsync(""" + public Task InsertInlineReversedForSnippetForVariableNamedLikeTypeTest() + => VerifySnippetAsync(""" class C { void M() @@ -1041,5 +959,4 @@ class MyType public int Length => 0; } """); - } } diff --git a/src/Features/CSharpTest/Snippets/CSharpStructSnippetProviderTests.cs b/src/Features/CSharpTest/Snippets/CSharpStructSnippetProviderTests.cs index 39200d76aeefc..f94aaac814071 100644 --- a/src/Features/CSharpTest/Snippets/CSharpStructSnippetProviderTests.cs +++ b/src/Features/CSharpTest/Snippets/CSharpStructSnippetProviderTests.cs @@ -15,9 +15,8 @@ public sealed class CSharpStructSnippetProviderTests : AbstractCSharpSnippetProv protected override string SnippetIdentifier => "struct"; [Fact] - public async Task InsertStructSnippetInBlockNamespaceTest() - { - await VerifySnippetAsync(""" + public Task InsertStructSnippetInBlockNamespaceTest() + => VerifySnippetAsync(""" namespace Namespace { $$ @@ -31,12 +30,10 @@ struct {|0:MyStruct|} } } """); - } [Fact] - public async Task InsertStructSnippetInFileScopedNamespaceTest() - { - await VerifySnippetAsync(""" + public Task InsertStructSnippetInFileScopedNamespaceTest() + => VerifySnippetAsync(""" namespace Namespace; $$ @@ -48,12 +45,10 @@ struct {|0:MyStruct|} $$ } """); - } [Fact] - public async Task InsertStructSnippetTest() - { - await VerifySnippetAsync(""" + public Task InsertStructSnippetTest() + => VerifySnippetAsync(""" $$ """, """ struct {|0:MyStruct|} @@ -61,12 +56,10 @@ struct {|0:MyStruct|} $$ } """); - } [Fact] - public async Task InsertStructTopLevelSnippetTest() - { - await VerifySnippetAsync(""" + public Task InsertStructTopLevelSnippetTest() + => VerifySnippetAsync(""" System.Console.WriteLine(); $$ """, """ @@ -76,12 +69,10 @@ struct {|0:MyStruct|} $$ } """); - } [Fact] - public async Task InsertStructSnippetInClassTest() - { - await VerifySnippetAsync(""" + public Task InsertStructSnippetInClassTest() + => VerifySnippetAsync(""" class MyClass { $$ @@ -95,12 +86,10 @@ struct {|0:MyStruct|} } } """); - } [Fact] - public async Task InsertStructSnippetInRecordTest() - { - await VerifySnippetAsync(""" + public Task InsertStructSnippetInRecordTest() + => VerifySnippetAsync(""" record MyRecord { $$ @@ -114,12 +103,10 @@ struct {|0:MyStruct|} } } """); - } [Fact] - public async Task InsertStructSnippetInStructTest() - { - await VerifySnippetAsync(""" + public Task InsertStructSnippetInStructTest() + => VerifySnippetAsync(""" struct MyStruct { $$ @@ -133,12 +120,10 @@ struct {|0:MyStruct1|} } } """); - } [Fact] - public async Task InsertStructSnippetInInterfaceTest() - { - await VerifySnippetAsync(""" + public Task InsertStructSnippetInInterfaceTest() + => VerifySnippetAsync(""" interface MyInterface { $$ @@ -152,12 +137,10 @@ struct {|0:MyStruct|} } } """); - } [Fact] - public async Task InsertStructSnippetWithModifiersTest() - { - await VerifySnippetAsync(""" + public Task InsertStructSnippetWithModifiersTest() + => VerifySnippetAsync(""" $$ """, """ public struct {|0:MyStruct|} @@ -171,23 +154,19 @@ public struct {|0:MyStruct|} [*] dotnet_style_require_accessibility_modifiers = always """); - } [Fact] - public async Task NoStructSnippetInEnumTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoStructSnippetInEnumTest() + => VerifySnippetIsAbsentAsync(""" enum MyEnum { $$ } """); - } [Fact] - public async Task NoStructSnippetInMethodTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoStructSnippetInMethodTest() + => VerifySnippetIsAbsentAsync(""" struct Program { public void Method() @@ -196,12 +175,10 @@ public void Method() } } """); - } [Fact] - public async Task NoStructSnippetInConstructorTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoStructSnippetInConstructorTest() + => VerifySnippetIsAbsentAsync(""" struct Program { public Program() @@ -210,13 +187,11 @@ public Program() } } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.AllAccessibilityModifiers), MemberType = typeof(CommonSnippetTestData))] - public async Task InsertStructSnippetAfterAccessibilityModifier(string modifier) - { - await VerifySnippetAsync($""" + public Task InsertStructSnippetAfterAccessibilityModifier(string modifier) + => VerifySnippetAsync($""" {modifier} $$ """, $$""" {{modifier}} struct {|0:MyStruct|} @@ -224,13 +199,11 @@ await VerifySnippetAsync($""" $$ } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.AllAccessibilityModifiers), MemberType = typeof(CommonSnippetTestData))] - public async Task InsertStructSnippetAfterAccessibilityModifier_RequireAccessibilityModifiers(string modifier) - { - await VerifySnippetAsync($""" + public Task InsertStructSnippetAfterAccessibilityModifier_RequireAccessibilityModifiers(string modifier) + => VerifySnippetAsync($""" {modifier} $$ """, $$""" {{modifier}} struct {|0:MyStruct|} @@ -244,15 +217,13 @@ await VerifySnippetAsync($""" [*] dotnet_style_require_accessibility_modifiers = always """); - } [Theory] [InlineData("ref")] [InlineData("readonly")] [InlineData("unsafe")] - public async Task InsertStructSnippetAfterValidModifiersTest(string modifier) - { - await VerifySnippetAsync($""" + public Task InsertStructSnippetAfterValidModifiersTest(string modifier) + => VerifySnippetAsync($""" {modifier} $$ """, $$""" {{modifier}} struct {|0:MyStruct|} @@ -260,24 +231,20 @@ await VerifySnippetAsync($""" $$ } """); - } [Theory] [InlineData("abstract")] [InlineData("sealed")] [InlineData("static")] - public async Task NoStructSnippetAfterInvalidModifiersTest(string modifier) - { - await VerifySnippetIsAbsentAsync($""" + public Task NoStructSnippetAfterInvalidModifiersTest(string modifier) + => VerifySnippetIsAbsentAsync($""" {modifier} $$ """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/69600")] [MemberData(nameof(CommonSnippetTestData.AllAccessibilityModifiers), MemberType = typeof(CommonSnippetTestData))] - public async Task NoAdditionalAccessibilityModifiersIfAfterPartialKeywordTest(string modifier) - { - await VerifySnippetAsync($""" + public Task NoAdditionalAccessibilityModifiersIfAfterPartialKeywordTest(string modifier) + => VerifySnippetAsync($""" {modifier} partial $$ """, $$""" {{modifier}} partial struct {|0:MyStruct|} @@ -291,12 +258,10 @@ await VerifySnippetAsync($""" [*] dotnet_style_require_accessibility_modifiers = always """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69600")] - public async Task EnsureCorrectModifierOrderAfterPartialKeywordTest() - { - await VerifySnippetAsync(""" + public Task EnsureCorrectModifierOrderAfterPartialKeywordTest() + => VerifySnippetAsync(""" partial $$ """, """ public partial struct {|0:MyStruct|} @@ -310,12 +275,10 @@ public partial struct {|0:MyStruct|} [*] dotnet_style_require_accessibility_modifiers = always """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69600")] - public async Task EnsureCorrectModifierOrderAfterPartialKeywordTest_InvalidPreferredModifiersList() - { - await VerifySnippetAsync(""" + public Task EnsureCorrectModifierOrderAfterPartialKeywordTest_InvalidPreferredModifiersList() + => VerifySnippetAsync(""" partial $$ """, """ public partial struct {|0:MyStruct|} @@ -331,12 +294,10 @@ public partial struct {|0:MyStruct|} csharp_preferred_modifier_order = invalid! """); - } [Fact] - public async Task EnsureCorrectModifierOrderFromOptionsTest_PublicModifierBeforeAllOthers() - { - await VerifySnippetAsync(""" + public Task EnsureCorrectModifierOrderFromOptionsTest_PublicModifierBeforeAllOthers() + => VerifySnippetAsync(""" readonly ref $$ """, """ public readonly ref struct {|0:MyStruct|} @@ -352,12 +313,10 @@ readonly ref $$ csharp_preferred_modifier_order = public,readonly,ref """); - } [Fact] - public async Task EnsureCorrectModifierOrderFromOptionsTest_PublicModifierBeforeAllOthers_NotAllModifiersInTheList() - { - await VerifySnippetAsync(""" + public Task EnsureCorrectModifierOrderFromOptionsTest_PublicModifierBeforeAllOthers_NotAllModifiersInTheList() + => VerifySnippetAsync(""" readonly ref $$ """, """ public readonly ref struct {|0:MyStruct|} @@ -373,12 +332,10 @@ readonly ref $$ csharp_preferred_modifier_order = public,readonly """); - } [Fact] - public async Task EnsureCorrectModifierOrderFromOptionsTest_PublicModifierBetweenOthers() - { - await VerifySnippetAsync(""" + public Task EnsureCorrectModifierOrderFromOptionsTest_PublicModifierBetweenOthers() + => VerifySnippetAsync(""" readonly ref $$ """, """ readonly public ref struct {|0:MyStruct|} @@ -394,12 +351,10 @@ readonly ref $$ csharp_preferred_modifier_order = readonly,public,ref """); - } [Fact] - public async Task EnsureCorrectModifierOrderFromOptionsTest_PublicModifierAfterAllOthers() - { - await VerifySnippetAsync(""" + public Task EnsureCorrectModifierOrderFromOptionsTest_PublicModifierAfterAllOthers() + => VerifySnippetAsync(""" readonly ref $$ """, """ readonly ref public struct {|0:MyStruct|} @@ -415,5 +370,4 @@ readonly ref $$ csharp_preferred_modifier_order = readonly,ref,public """); - } } diff --git a/src/Features/CSharpTest/Snippets/CSharpUsingSnippetProviderTests.cs b/src/Features/CSharpTest/Snippets/CSharpUsingSnippetProviderTests.cs index 3cc449347bab4..492e5677fbbfc 100644 --- a/src/Features/CSharpTest/Snippets/CSharpUsingSnippetProviderTests.cs +++ b/src/Features/CSharpTest/Snippets/CSharpUsingSnippetProviderTests.cs @@ -14,9 +14,8 @@ public sealed class CSharpUsingSnippetProviderTests : AbstractCSharpSnippetProvi protected override string SnippetIdentifier => "using"; [Fact] - public async Task InsertUsingSnippetInMethodTest() - { - await VerifySnippetAsync(""" + public Task InsertUsingSnippetInMethodTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -36,12 +35,10 @@ public void Method() } } """); - } [Fact] - public async Task InsertUsingSnippetInGlobalContextTest() - { - await VerifySnippetAsync(""" + public Task InsertUsingSnippetInGlobalContextTest() + => VerifySnippetAsync(""" $$ """, """ using ({|0:resource|}) @@ -49,32 +46,26 @@ await VerifySnippetAsync(""" $$ } """); - } [Fact] - public async Task NoUsingSnippetInBusingNamespaceTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoUsingSnippetInBusingNamespaceTest() + => VerifySnippetIsAbsentAsync(""" namespace Namespace { $$ } """); - } [Fact] - public async Task NoUsingSnippetInFileScopedNamespaceTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoUsingSnippetInFileScopedNamespaceTest() + => VerifySnippetIsAbsentAsync(""" namespace Namespace; $$ """); - } [Fact] - public async Task InsertUsingSnippetInConstructorTest() - { - await VerifySnippetAsync(""" + public Task InsertUsingSnippetInConstructorTest() + => VerifySnippetAsync(""" class Program { public Program() @@ -94,23 +85,19 @@ public Program() } } """); - } [Fact] - public async Task NoUsingSnippetInTypeBodyTest() - { - await VerifySnippetIsAbsentAsync(""" + public Task NoUsingSnippetInTypeBodyTest() + => VerifySnippetIsAbsentAsync(""" class Program { $$ } """); - } [Fact] - public async Task InsertUsingSnippetInLocalFunctionTest() - { - await VerifySnippetAsync(""" + public Task InsertUsingSnippetInLocalFunctionTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -136,12 +123,10 @@ void LocalFunction() } } """); - } [Fact] - public async Task InsertUsingSnippetInAnonymousFunctionTest() - { - await VerifySnippetAsync(""" + public Task InsertUsingSnippetInAnonymousFunctionTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -167,12 +152,10 @@ public void Method() } } """); - } [Fact] - public async Task InsertUsingSnippetInParenthesizedLambdaExpressionTest() - { - await VerifySnippetAsync(""" + public Task InsertUsingSnippetInParenthesizedLambdaExpressionTest() + => VerifySnippetAsync(""" class Program { public void Method() @@ -198,5 +181,4 @@ public void Method() } } """); - } } diff --git a/src/Features/CSharpTest/Snippets/CSharpVoidMainSnippetProviderTests.cs b/src/Features/CSharpTest/Snippets/CSharpVoidMainSnippetProviderTests.cs index 1303b298e4f97..1e696ec41d144 100644 --- a/src/Features/CSharpTest/Snippets/CSharpVoidMainSnippetProviderTests.cs +++ b/src/Features/CSharpTest/Snippets/CSharpVoidMainSnippetProviderTests.cs @@ -14,34 +14,28 @@ public sealed class CSharpVoidMainSnippetProviderTests : AbstractCSharpSnippetPr protected override string SnippetIdentifier => "svm"; [Fact] - public async Task TestMissingInBlockNamespace() - { - await VerifySnippetIsAbsentAsync(""" + public Task TestMissingInBlockNamespace() + => VerifySnippetIsAbsentAsync(""" namespace Test { $$ } """); - } [Fact] - public async Task TestMissingInFileScopedNamespace() - { - await VerifySnippetIsAbsentAsync(""" + public Task TestMissingInFileScopedNamespace() + => VerifySnippetIsAbsentAsync(""" namespace Test; $$ """); - } [Fact] - public async Task TestMissingInTopLevelContext() - { - await VerifySnippetIsAbsentAsync(""" + public Task TestMissingInTopLevelContext() + => VerifySnippetIsAbsentAsync(""" System.Console.WriteLine(); $$ """); - } [Theory] [InlineData("class")] @@ -50,9 +44,8 @@ await VerifySnippetIsAbsentAsync(""" [InlineData("record")] [InlineData("record class")] [InlineData("record struct")] - public async Task TestInsertSnippetInType(string type) - { - await VerifySnippetAsync($$""" + public Task TestInsertSnippetInType(string type) + => VerifySnippetAsync($$""" {{type}} Program { $$ @@ -66,23 +59,19 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task TestMissingInEnum() - { - await VerifySnippetIsAbsentAsync(""" + public Task TestMissingInEnum() + => VerifySnippetIsAbsentAsync(""" enum MyEnum { $$ } """); - } [Fact] - public async Task TestMissingInMethod() - { - await VerifySnippetIsAbsentAsync(""" + public Task TestMissingInMethod() + => VerifySnippetIsAbsentAsync(""" class Program { void M() @@ -91,12 +80,10 @@ void M() } } """); - } [Fact] - public async Task TestMissingInConstructor() - { - await VerifySnippetIsAbsentAsync(""" + public Task TestMissingInConstructor() + => VerifySnippetIsAbsentAsync(""" class Program { public Program() @@ -105,13 +92,11 @@ public Program() } } """); - } [Theory] [MemberData(nameof(CommonSnippetTestData.AllAccessibilityModifiers), MemberType = typeof(CommonSnippetTestData))] - public async Task TestInsertSnippetAfterAccessibilityModifier(string modifier) - { - await VerifySnippetAsync($$""" + public Task TestInsertSnippetAfterAccessibilityModifier(string modifier) + => VerifySnippetAsync($$""" class Program { {{modifier}} $$ @@ -125,7 +110,6 @@ class Program } } """); - } [Theory] [InlineData("static")] @@ -133,20 +117,17 @@ class Program [InlineData("abstract")] [InlineData("override")] [InlineData("file")] - public async Task TestMissingAfterIncorrectModifiers(string modifier) - { - await VerifySnippetIsAbsentAsync($$""" + public Task TestMissingAfterIncorrectModifiers(string modifier) + => VerifySnippetIsAbsentAsync($$""" class Program { {{modifier}} $$ } """); - } [Fact] - public async Task TestMissingIfAnotherMemberWithNameMainExists() - { - await VerifySnippetIsAbsentAsync(""" + public Task TestMissingIfAnotherMemberWithNameMainExists() + => VerifySnippetIsAbsentAsync(""" class Program { public int Main => 0; @@ -154,12 +135,10 @@ class Program $$ } """); - } [Fact] - public async Task TestMissingIfTopLevelStatementsArePresent() - { - await VerifySnippetIsAbsentAsync(""" + public Task TestMissingIfTopLevelStatementsArePresent() + => VerifySnippetIsAbsentAsync(""" System.Console.WriteLine(); class Program @@ -167,5 +146,4 @@ class Program $$ } """); - } } diff --git a/src/Features/CSharpTest/SolutionExplorer/CSharpSolutionExplorerSymbolTreeItemProviderTests.cs b/src/Features/CSharpTest/SolutionExplorer/CSharpSolutionExplorerSymbolTreeItemProviderTests.cs index 8cf2b5896f5d8..519c8494c2362 100644 --- a/src/Features/CSharpTest/SolutionExplorer/CSharpSolutionExplorerSymbolTreeItemProviderTests.cs +++ b/src/Features/CSharpTest/SolutionExplorer/CSharpSolutionExplorerSymbolTreeItemProviderTests.cs @@ -28,27 +28,22 @@ private Task TestCompilationUnit( } [Fact] - public async Task TestEmptyFile() - { - await TestCompilationUnit("", ""); - } + public Task TestEmptyFile() + => TestCompilationUnit("", ""); [Fact] - public async Task TestTopLevelClass() - { - await TestCompilationUnit(""" + public Task TestTopLevelClass() + => TestCompilationUnit(""" class [|C|] { } """, """ Name="C" Glyph=ClassInternal HasItems=False """); - } [Fact] - public async Task TestTwoTopLevelTypes() - { - await TestCompilationUnit(""" + public Task TestTwoTopLevelTypes() + => TestCompilationUnit(""" class [|C|] { } @@ -60,12 +55,10 @@ class [|D|] Name="C" Glyph=ClassInternal HasItems=False Name="D" Glyph=ClassInternal HasItems=False """); - } [Fact] - public async Task TestDelegatesAndEnums() - { - await TestCompilationUnit(""" + public Task TestDelegatesAndEnums() + => TestCompilationUnit(""" delegate string [|D|](int x); enum [|E|] @@ -75,12 +68,10 @@ enum [|E|] Name="D(int) : string" Glyph=DelegateInternal HasItems=False Name="E" Glyph=EnumInternal HasItems=False """); - } [Fact] - public async Task TestTypesInBlockNamespace() - { - await TestCompilationUnit(""" + public Task TestTypesInBlockNamespace() + => TestCompilationUnit(""" namespace N { class [|C|] @@ -95,12 +86,10 @@ class [|D|] Name="C" Glyph=ClassInternal HasItems=False Name="D" Glyph=ClassInternal HasItems=False """); - } [Fact] - public async Task TestTypesInFileScopedNamespace() - { - await TestCompilationUnit(""" + public Task TestTypesInFileScopedNamespace() + => TestCompilationUnit(""" namespace N; class [|C|] @@ -114,12 +103,10 @@ class [|D|] Name="C" Glyph=ClassInternal HasItems=False Name="D" Glyph=ClassInternal HasItems=False """); - } [Fact] - public async Task TestTypesAcrossNamespaces() - { - await TestCompilationUnit(""" + public Task TestTypesAcrossNamespaces() + => TestCompilationUnit(""" class [|C|] { } @@ -134,27 +121,23 @@ class [|D|] Name="C" Glyph=ClassInternal HasItems=False Name="D" Glyph=ClassInternal HasItems=False """); - } [Theory, CombinatorialData] - public async Task TestTypePermutations( + public Task TestTypePermutations( [CombinatorialValues("Public", "Private", "Protected", "Internal")] string accessibility, [CombinatorialValues("Record", "Class", "Interface", "Struct")] string type) - { - await TestCompilationUnit($$""" + => TestCompilationUnit($$""" {{accessibility.ToLowerInvariant()}} {{type.ToLowerInvariant()}} [|C|] { } """, $$""" Name="C" Glyph={{type switch { "Record" => "Class", "Struct" => "Structure", _ => type }}}{{accessibility}} HasItems=False """); - } [Theory, CombinatorialData] - public async Task TestTypeHasItems( + public Task TestTypeHasItems( [CombinatorialValues("Record", "Class", "Interface", "Struct")] string type) - { - await TestCompilationUnit($$""" + => TestCompilationUnit($$""" {{type.ToLowerInvariant()}} [|C|] { int i; @@ -162,12 +145,10 @@ await TestCompilationUnit($$""" """, $$""" Name="C" Glyph={{type switch { "Record" => "Class", "Struct" => "Structure", _ => type }}}Internal HasItems=True """); - } [Fact] - public async Task TestEnumHasItems() - { - await TestCompilationUnit(""" + public Task TestEnumHasItems() + => TestCompilationUnit(""" enum [|E|] { A, @@ -177,7 +158,6 @@ enum [|E|] """, """ Name="E" Glyph=EnumInternal HasItems=True """); - } [Theory] [InlineData("int", "int")] @@ -194,42 +174,35 @@ enum [|E|] [InlineData("A::B.C", "C")] [InlineData("A", "A")] [InlineData("A.B>", "B>")] - public async Task TestTypes( + public Task TestTypes( string parameterType, string resultType) - { - await TestCompilationUnit($$""" + => TestCompilationUnit($$""" delegate void [|D|]({{parameterType}} x); """, $$""" Name="D({{resultType}}) : void" Glyph=DelegateInternal HasItems=False """); - } [Fact] - public async Task TestGenericClass() - { - await TestCompilationUnit(""" + public Task TestGenericClass() + => TestCompilationUnit(""" class [|C|] { } """, """ Name="C" Glyph=ClassInternal HasItems=False """); - } [Fact] - public async Task TestGenericDelegate() - { - await TestCompilationUnit(""" + public Task TestGenericDelegate() + => TestCompilationUnit(""" delegate void [|D|](); """, """ Name="D() : void" Glyph=DelegateInternal HasItems=False """); - } [Fact] - public async Task TestEnumMembers() - { - await TestNode(""" + public Task TestEnumMembers() + => TestNode(""" enum E { [|A|], [|B|], [|C|] @@ -239,12 +212,10 @@ enum E Name="B" Glyph=EnumMemberPublic HasItems=False Name="C" Glyph=EnumMemberPublic HasItems=False """); - } [Fact] - public async Task TestClassMembers() - { - await TestNode(""" + public Task TestClassMembers() + => TestNode(""" class C { private int [|a|], [|b|]; @@ -278,12 +249,10 @@ private event Action [|A|] { } Name="operator +(C, int) : C" Glyph=OperatorPublic HasItems=False Name="implicit operator int(C)" Glyph=OperatorInternal HasItems=False """); - } [Fact] - public async Task TestExtension1() - { - await TestNode(""" + public Task TestExtension1() + => TestNode(""" static class C { [|extension|](int i) @@ -296,12 +265,10 @@ static class C Name="extension(int)" Glyph=ClassPublic HasItems=False Name="M(int) : void" Glyph=ExtensionMethodPublic HasItems=False """); - } [Fact] - public async Task TestExtension2() - { - await TestNode(""" + public Task TestExtension2() + => TestNode(""" static class C { extension(int i) @@ -312,5 +279,4 @@ static class C """, """ Name="M() : void" Glyph=ExtensionMethodPublic HasItems=False """); - } } diff --git a/src/Features/CSharpTest/SpellCheck/SpellCheckTests.cs b/src/Features/CSharpTest/SpellCheck/SpellCheckTests.cs index 485c5f9027b3e..20dbe2a4d5349 100644 --- a/src/Features/CSharpTest/SpellCheck/SpellCheckTests.cs +++ b/src/Features/CSharpTest/SpellCheck/SpellCheckTests.cs @@ -33,630 +33,585 @@ protected override ImmutableArray MassageActions(ImmutableArray FlattenActions(actions); [Fact] - public async Task TestNoSpellcheckForIfOnly2Characters() - { - var text = -@"class Goo -{ - void Bar() - { - var a = new [|Fo|] - } -}"; - await TestMissingInRegularAndScriptAsync(text); - } + public Task TestNoSpellcheckForIfOnly2Characters() + => TestMissingInRegularAndScriptAsync(""" + class Goo + { + void Bar() + { + var a = new [|Fo|] + } + } + """); [Fact] - public async Task TestAfterNewExpression() - { - var text = -@"class Goo -{ - void Bar() - { - void a = new [|Gooa|].ToString(); - } -}"; - - await TestExactActionSetOfferedAsync(text, [String.Format(FeaturesResources.Change_0_to_1, "Gooa", "Goo")]); - } + public Task TestAfterNewExpression() + => TestExactActionSetOfferedAsync(""" + class Goo + { + void Bar() + { + void a = new [|Gooa|].ToString(); + } + } + """, [String.Format(FeaturesResources.Change_0_to_1, "Gooa", "Goo")]); [Fact] - public async Task TestInLocalType() - { - var text = @"class Foo -{ - void Bar() - { - [|Foa|] a; - } -}"; - - await TestExactActionSetOfferedAsync(text, + public Task TestInLocalType() + => TestExactActionSetOfferedAsync(""" + class Foo + { + void Bar() + { + [|Foa|] a; + } + } + """, [ String.Format(FeaturesResources.Change_0_to_1, "Foa", "Foo"), String.Format(FeaturesResources.Change_0_to_1, "Foa", "for") ]); - } [Fact] - public async Task TestInFunc() - { - var text = @" -using System; - -class Goo -{ - void Bar(Func<[|Goa|]> f) - { - } -}"; - await TestExactActionSetOfferedAsync(text, + public Task TestInFunc() + => TestExactActionSetOfferedAsync(""" + using System; + + class Goo + { + void Bar(Func<[|Goa|]> f) + { + } + } + """, [String.Format(FeaturesResources.Change_0_to_1, "Goa", "Goo")]); - } [Fact] - public async Task TestInExpression() - { - var text = @"class Program -{ - void Main(string[] args) - { - var zzz = 2; - var y = 2 + [|zza|]; - } -}"; - await TestExactActionSetOfferedAsync(text, [String.Format(FeaturesResources.Change_0_to_1, "zza", "zzz")]); - } + public Task TestInExpression() + => TestExactActionSetOfferedAsync(""" + class Program + { + void Main(string[] args) + { + var zzz = 2; + var y = 2 + [|zza|]; + } + } + """, [String.Format(FeaturesResources.Change_0_to_1, "zza", "zzz")]); [Fact] - public async Task TestInTypeOfIsExpression() - { - var text = @"using System; -public class Class1 -{ - void F() - { - if (x is [|Boolea|]) {} - } -}"; - await TestExactActionSetOfferedAsync(text, + public Task TestInTypeOfIsExpression() + => TestExactActionSetOfferedAsync(""" + using System; + public class Class1 + { + void F() + { + if (x is [|Boolea|]) {} + } + } + """, [ String.Format(FeaturesResources.Change_0_to_1, "Boolea", "Boolean"), String.Format(FeaturesResources.Change_0_to_1, "Boolea", "bool") ]); - } [Fact] - public async Task TestInvokeCorrectIdentifier() - { - var text = @"class Program -{ - void Main(string[] args) - { - var zzz = 2; - var y = 2 + [|zza|]; - } -}"; - - var expected = @"class Program -{ - void Main(string[] args) - { - var zzz = 2; - var y = 2 + zzz; - } -}"; - - await TestInRegularAndScriptAsync(text, expected); - } + public Task TestInvokeCorrectIdentifier() + => TestInRegularAndScriptAsync(""" + class Program + { + void Main(string[] args) + { + var zzz = 2; + var y = 2 + [|zza|]; + } + } + """, """ + class Program + { + void Main(string[] args) + { + var zzz = 2; + var y = 2 + zzz; + } + } + """); [Fact] - public async Task TestAfterDot() - { - var text = @"class Program -{ - static void Main(string[] args) - { - Program.[|Mair|] - } -}"; - - var expected = @"class Program -{ - static void Main(string[] args) - { - Program.Main - } -}"; - - await TestInRegularAndScriptAsync(text, expected); - } + public Task TestAfterDot() + => TestInRegularAndScriptAsync(""" + class Program + { + static void Main(string[] args) + { + Program.[|Mair|] + } + } + """, """ + class Program + { + static void Main(string[] args) + { + Program.Main + } + } + """); [Fact] - public async Task TestNotInaccessibleProperty() - { - var text = @"class Program -{ - void Main(string[] args) - { - var z = new c().[|membr|] - } -} - -class c -{ - protected int member { get; } -}"; - - await TestMissingInRegularAndScriptAsync(text); - } + public Task TestNotInaccessibleProperty() + => TestMissingInRegularAndScriptAsync(""" + class Program + { + void Main(string[] args) + { + var z = new c().[|membr|] + } + } + + class c + { + protected int member { get; } + } + """); [Fact] - public async Task TestGenericName1() - { - var text = @"class Goo -{ - private [|Goo2|] x; -}"; - - var expected = @"class Goo -{ - private Goo x; -}"; - - await TestInRegularAndScriptAsync(text, expected); - } + public Task TestGenericName1() + => TestInRegularAndScriptAsync(""" + class Goo + { + private [|Goo2|] x; + } + """, """ + class Goo + { + private Goo x; + } + """); [Fact] - public async Task TestGenericName2() - { - var text = @"class Goo -{ - private [|Goo2|] x; -}"; - - var expected = @"class Goo -{ - private Goo x; -}"; - - await TestInRegularAndScriptAsync(text, expected); - } + public Task TestGenericName2() + => TestInRegularAndScriptAsync(""" + class Goo + { + private [|Goo2|] x; + } + """, """ + class Goo + { + private Goo x; + } + """); [Fact] - public async Task TestQualifiedName1() - { - var text = @"class Program -{ - private object x = new [|Goo2|].Bar -} - -class Goo -{ - class Bar - { - } -}"; - - var expected = @"class Program -{ - private object x = new Goo.Bar -} - -class Goo -{ - class Bar - { - } -}"; - - await TestInRegularAndScriptAsync(text, expected); - } + public Task TestQualifiedName1() + => TestInRegularAndScriptAsync(""" + class Program + { + private object x = new [|Goo2|].Bar + } + + class Goo + { + class Bar + { + } + } + """, """ + class Program + { + private object x = new Goo.Bar + } + + class Goo + { + class Bar + { + } + } + """); [Fact] - public async Task TestQualifiedName2() - { - var text = @"class Program -{ - private object x = new Goo.[|Ba2|] -} - -class Goo -{ - public class Bar - { - } -}"; - - var expected = @"class Program -{ - private object x = new Goo.Bar -} - -class Goo -{ - public class Bar - { - } -}"; - - await TestInRegularAndScriptAsync(text, expected); - } + public Task TestQualifiedName2() + => TestInRegularAndScriptAsync(""" + class Program + { + private object x = new Goo.[|Ba2|] + } + + class Goo + { + public class Bar + { + } + } + """, """ + class Program + { + private object x = new Goo.Bar + } + + class Goo + { + public class Bar + { + } + } + """); [Fact] - public async Task TestMiddleOfDottedExpression() - { - var text = @"class Program -{ - void Main(string[] args) - { - var z = new c().[|membr|].ToString(); - } -} - -class c -{ - public int member { get; } -}"; - - var expected = @"class Program -{ - void Main(string[] args) - { - var z = new c().member.ToString(); - } -} - -class c -{ - public int member { get; } -}"; - - await TestInRegularAndScriptAsync(text, expected); - } + public Task TestMiddleOfDottedExpression() + => TestInRegularAndScriptAsync(""" + class Program + { + void Main(string[] args) + { + var z = new c().[|membr|].ToString(); + } + } + + class c + { + public int member { get; } + } + """, """ + class Program + { + void Main(string[] args) + { + var z = new c().member.ToString(); + } + } + + class c + { + public int member { get; } + } + """); [Fact] - public async Task TestNotForOverloadResolutionFailure() - { - var text = @"class Program -{ - void Main(string[] args) - { - } - - void Goo() - { - [|Method|](); - } - - int Method(int argument) - { - } -}"; - - await TestMissingInRegularAndScriptAsync(text); - } + public Task TestNotForOverloadResolutionFailure() + => TestMissingInRegularAndScriptAsync(""" + class Program + { + void Main(string[] args) + { + } + + void Goo() + { + [|Method|](); + } + + int Method(int argument) + { + } + } + """); [Fact] - public async Task TestHandlePredefinedTypeKeywordCorrectly() - { - var text = @" -using System; -using System.Collections.Generic; -using System.Linq; - -class Program -{ - void Main(string[] args) - { - [|Int3|] i; - } -}"; - - var expected = @" -using System; -using System.Collections.Generic; -using System.Linq; - -class Program -{ - void Main(string[] args) - { - int i; - } -}"; - - await TestInRegularAndScriptAsync(text, expected); - } + public Task TestHandlePredefinedTypeKeywordCorrectly() + => TestInRegularAndScriptAsync(""" + using System; + using System.Collections.Generic; + using System.Linq; + + class Program + { + void Main(string[] args) + { + [|Int3|] i; + } + } + """, """ + using System; + using System.Collections.Generic; + using System.Linq; + + class Program + { + void Main(string[] args) + { + int i; + } + } + """); [Fact] - public async Task TestHandlePredefinedTypeKeywordCorrectly1() - { - var text = @" -using System; -using System.Collections.Generic; -using System.Linq; - -class Program -{ - void Main(string[] args) - { - [|Int3|] i; - } -}"; - - var expected = @" -using System; -using System.Collections.Generic; -using System.Linq; - -class Program -{ - void Main(string[] args) - { - Int32 i; - } -}"; - - await TestInRegularAndScriptAsync(text, expected, index: 1); - } + public Task TestHandlePredefinedTypeKeywordCorrectly1() + => TestInRegularAndScriptAsync(""" + using System; + using System.Collections.Generic; + using System.Linq; + + class Program + { + void Main(string[] args) + { + [|Int3|] i; + } + } + """, """ + using System; + using System.Collections.Generic; + using System.Linq; + + class Program + { + void Main(string[] args) + { + Int32 i; + } + } + """, index: 1); [Fact] - public async Task TestOnGeneric() - { - var text = @" -interface Enumerable -{ -} - -class C -{ - void Main(string[] args) - { - [|IEnumerable|] x; - } -}"; - - var expected = @" -interface Enumerable -{ -} - -class C -{ - void Main(string[] args) - { - Enumerable x; - } -}"; - - await TestInRegularAndScriptAsync(text, expected); - } + public Task TestOnGeneric() + => TestInRegularAndScriptAsync(""" + interface Enumerable + { + } + + class C + { + void Main(string[] args) + { + [|IEnumerable|] x; + } + } + """, """ + interface Enumerable + { + } + + class C + { + void Main(string[] args) + { + Enumerable x; + } + } + """); [Fact] - public async Task TestTestObjectConstruction() - { - await TestInRegularAndScriptAsync( -@"class AwesomeClass -{ - void M() - { - var goo = new [|AwesomeClas()|]; - } -}", -@"class AwesomeClass -{ - void M() - { - var goo = new AwesomeClass(); - } -}"); - } + public Task TestTestObjectConstruction() + => TestInRegularAndScriptAsync( + """ + class AwesomeClass + { + void M() + { + var goo = new [|AwesomeClas()|]; + } + } + """, + """ + class AwesomeClass + { + void M() + { + var goo = new AwesomeClass(); + } + } + """); [Fact] - public async Task TestTestMissingName() - { - await TestMissingInRegularAndScriptAsync( + public Task TestTestMissingName() + => TestMissingInRegularAndScriptAsync( @"[assembly: Microsoft.CodeAnalysis.[||]]"); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/12990")] - public async Task TestTrivia1() - { - var text = @" -using System.Text; -class C -{ - void M() - { - /*leading*/ [|stringbuilder|] /*trailing*/ sb = null; - } -}"; - - var expected = @" -using System.Text; -class C -{ - void M() - { - /*leading*/ StringBuilder /*trailing*/ sb = null; - } -}"; - - await TestInRegularAndScriptAsync(text, expected); - } + public Task TestTrivia1() + => TestInRegularAndScriptAsync(""" + using System.Text; + class C + { + void M() + { + /*leading*/ [|stringbuilder|] /*trailing*/ sb = null; + } + } + """, """ + using System.Text; + class C + { + void M() + { + /*leading*/ StringBuilder /*trailing*/ sb = null; + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/13345")] - public async Task TestNotMissingOnKeywordWhichIsAlsoASnippet() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M() - { - // here 'for' is a keyword and snippet, so we should offer to spell check to it. - [|foo|]; - } -}", -@"class C -{ - void M() - { - // here 'for' is a keyword and snippet, so we should offer to spell check to it. - for; - } -}"); - } + public Task TestNotMissingOnKeywordWhichIsAlsoASnippet() + => TestInRegularAndScriptAsync( + """ + class C + { + void M() + { + // here 'for' is a keyword and snippet, so we should offer to spell check to it. + [|foo|]; + } + } + """, + """ + class C + { + void M() + { + // here 'for' is a keyword and snippet, so we should offer to spell check to it. + for; + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18626")] - public async Task TestForExplicitInterfaceTypeName() - { - await TestInRegularAndScriptAsync( -@"interface IProjectConfigurationsService -{ - void Method(); -} - -class Program : IProjectConfigurationsService -{ - void [|IProjectConfigurationService|].Method() - { - - } -}", -@"interface IProjectConfigurationsService -{ - void Method(); -} - -class Program : IProjectConfigurationsService -{ - void IProjectConfigurationsService.Method() - { - - } -}"); - } + public Task TestForExplicitInterfaceTypeName() + => TestInRegularAndScriptAsync( + """ + interface IProjectConfigurationsService + { + void Method(); + } + + class Program : IProjectConfigurationsService + { + void [|IProjectConfigurationService|].Method() + { + + } + } + """, + """ + interface IProjectConfigurationsService + { + void Method(); + } + + class Program : IProjectConfigurationsService + { + void IProjectConfigurationsService.Method() + { + + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/13345")] - public async Task TestMissingOnKeywordWhichIsOnlyASnippet() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M() - { - // here 'for' is *only* a snippet, and we should not offer to spell check to it. - var v = [|goo|]; - } -}"); - } + public Task TestMissingOnKeywordWhichIsOnlyASnippet() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M() + { + // here 'for' is *only* a snippet, and we should not offer to spell check to it. + var v = [|goo|]; + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/15733")] - public async Task TestMissingOnVar() - { - await TestMissingInRegularAndScriptAsync( -@" -namespace bar { } - -class C -{ - void M() - { - var y = - [|var|] - } -}"); - } + public Task TestMissingOnVar() + => TestMissingInRegularAndScriptAsync( + """ + namespace bar { } + + class C + { + void M() + { + var y = + [|var|] + } + } + """); [Fact] - public async Task TestUnmanagedConstraint() - { - await TestInRegularAndScriptAsync( -@"class C where T : [|umanaged|] -{ -}", -@"class C where T : unmanaged -{ -}"); - } + public Task TestUnmanagedConstraint() + => TestInRegularAndScriptAsync( + """ + class C where T : [|umanaged|] + { + } + """, + """ + class C where T : unmanaged + { + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28244")] - public async Task TestMisspelledConstructor() - { - await TestInRegularAndScriptAsync( -@"public class SomeClass -{ - public [|SomeClss|]() { } -}", -@"public class SomeClass -{ - public SomeClass() { } -}"); - } + public Task TestMisspelledConstructor() + => TestInRegularAndScriptAsync( + """ + public class SomeClass + { + public [|SomeClss|]() { } + } + """, + """ + public class SomeClass + { + public SomeClass() { } + } + """); [Fact] - public async Task TestInExplicitInterfaceImplementation1() - { - var text = @" -using System; - -class Program : IDisposable -{ - void IDisposable.[|Dspose|] -}"; + public Task TestInExplicitInterfaceImplementation1() + => TestMissingInRegularAndScriptAsync(""" + using System; - await TestMissingInRegularAndScriptAsync(text); - } + class Program : IDisposable + { + void IDisposable.[|Dspose|] + } + """); [Fact] - public async Task TestInExplicitInterfaceImplementation2() - { - var text = @" -using System; + public Task TestInExplicitInterfaceImplementation2() + => TestMissingInRegularAndScriptAsync(""" + using System; -interface IInterface -{ - void Generic(); -} - -class Program : IInterface -{ - void IInterface.[|Generi|] -}"; + interface IInterface + { + void Generic(); + } - await TestMissingInRegularAndScriptAsync(text); - } + class Program : IInterface + { + void IInterface.[|Generi|] + } + """); [Fact] - public async Task TestInExplicitInterfaceImplementation3() - { - var text = @" -using System; - -interface IInterface -{ - int this[int i] { get; } -} + public Task TestInExplicitInterfaceImplementation3() + => TestMissingInRegularAndScriptAsync(""" + using System; -class Program : IInterface -{ - void IInterface.[|thi|] -}"; + interface IInterface + { + int this[int i] { get; } + } - await TestMissingInRegularAndScriptAsync(text); - } + class Program : IInterface + { + void IInterface.[|thi|] + } + """); [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1640728")] - public async Task TestMisspelledWordThatIsAlsoSnippetName() - { - await TestInRegularAndScriptAsync( -@"public [|interfacce|] IWhatever -{ -}", -@"public interface IWhatever -{ -}"); - } + public Task TestMisspelledWordThatIsAlsoSnippetName() + => TestInRegularAndScriptAsync( + """ + public [|interfacce|] IWhatever + { + } + """, + """ + public interface IWhatever + { + } + """); } diff --git a/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_ElseIf_WithNext.cs b/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_ElseIf_WithNext.cs index df0af25c1d8d8..3b316b83052ab 100644 --- a/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_ElseIf_WithNext.cs +++ b/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_ElseIf_WithNext.cs @@ -19,208 +19,218 @@ public sealed partial class MergeConsecutiveIfStatementsTests [InlineData("if (a)[||]")] [InlineData("[|if|] (a)")] [InlineData("[|if (a)|]")] - public async Task MergedOnIfSpans(string ifLine) - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - " + ifLine + @" - { - } - else if (b) - { - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - { - } - } -}"); - } + public Task MergedOnIfSpans(string ifLine) + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + + """ + ifLine + """ + + { + } + else if (b) + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + { + } + } + } + """); [Fact] - public async Task MergedOnIfExtendedHeaderSelection() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { -[| if (a) -|] { - } - else if (b) - { - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - { - } - } -}"); - } + public Task MergedOnIfExtendedHeaderSelection() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + [| if (a) + |] { + } + else if (b) + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + { + } + } + } + """); [Fact] - public async Task MergedOnIfFullSelectionWithoutElseIfClause() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - [|if (a) - { - }|] - else if (b) - { - } - else - { - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - { - } - else - { - } - } -}"); - } + public Task MergedOnIfFullSelectionWithoutElseIfClause() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + [|if (a) + { + }|] + else if (b) + { + } + else + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + { + } + else + { + } + } + } + """); [Fact] - public async Task MergedOnIfExtendedFullSelectionWithoutElseIfClause() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { -[| if (a) - { - } -|] else if (b) - { - } - else - { - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - { - } - else - { - } - } -}"); - } + public Task MergedOnIfExtendedFullSelectionWithoutElseIfClause() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + [| if (a) + { + } + |] else if (b) + { + } + else + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + { + } + else + { + } + } + } + """); [Fact] - public async Task NotMergedOnIfFullSelectionWithElseIfClause() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - [|if (a) - { - } - else if (b) - { - }|] - else - { - } - } -}"); - } + public Task NotMergedOnIfFullSelectionWithElseIfClause() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + [|if (a) + { + } + else if (b) + { + }|] + else + { + } + } + } + """); [Fact] - public async Task NotMergedOnIfExtendedFullSelectionWithElseIfClause() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { -[| if (a) - { - } - else if (b) - { - } -|] else - { - } - } -}"); - } + public Task NotMergedOnIfExtendedFullSelectionWithElseIfClause() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + [| if (a) + { + } + else if (b) + { + } + |] else + { + } + } + } + """); [Fact] - public async Task NotMergedOnIfFullSelectionWithElseIfElseClauses() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - [|if (a) - { - } - else if (b) - { - } - else - { - }|] - } -}"); - } + public Task NotMergedOnIfFullSelectionWithElseIfElseClauses() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + [|if (a) + { + } + else if (b) + { + } + else + { + }|] + } + } + """); [Fact] - public async Task NotMergedOnIfExtendedFullSelectionWithElseIfElseClauses() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { -[| if (a) - { - } - else if (b) - { - } - else - { - } -|] } -}"); - } + public Task NotMergedOnIfExtendedFullSelectionWithElseIfElseClauses() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + [| if (a) + { + } + else if (b) + { + } + else + { + } + |] } + } + """); [Theory] [InlineData("if ([||]a)")] @@ -230,110 +240,112 @@ void M(bool a, bool b) [InlineData("if (a[|)|]")] [InlineData("if ([|a|])")] [InlineData("if [|(a)|]")] - public async Task NotMergedOnIfSpans(string ifLine) - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - " + ifLine + @" - { - } - else if (b) - { - } - } -}"); - } + public Task NotMergedOnIfSpans(string ifLine) + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + + """ + ifLine + """ + + { + } + else if (b) + { + } + } + } + """); [Fact] - public async Task NotMergedOnIfOverreachingSelection1() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - [|if (a) - |]{ - } - else if (b) - { - } - } -}"); - } + public Task NotMergedOnIfOverreachingSelection1() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + [|if (a) + |]{ + } + else if (b) + { + } + } + } + """); [Fact] - public async Task NotMergedOnIfOverreachingSelection2() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - [|if (a) - {|] - } - else if (b) - { - } - } -}"); - } + public Task NotMergedOnIfOverreachingSelection2() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + [|if (a) + {|] + } + else if (b) + { + } + } + } + """); [Fact] - public async Task NotMergedOnIfBodySelection() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - [|{ - }|] - else if (b) - { - } - } -}"); - } + public Task NotMergedOnIfBodySelection() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + [|{ + }|] + else if (b) + { + } + } + } + """); [Fact] - public async Task NotMergedOnIfBodyCaret1() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - [||]{ - } - else if (b) - { - } - } -}"); - } + public Task NotMergedOnIfBodyCaret1() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + [||]{ + } + else if (b) + { + } + } + } + """); [Fact] - public async Task NotMergedOnIfBodyCaret2() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - }[||] - else if (b) - { - } - } -}"); - } + public Task NotMergedOnIfBodyCaret2() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + }[||] + else if (b) + { + } + } + } + """); } diff --git a/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_ElseIf_WithPrevious.cs b/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_ElseIf_WithPrevious.cs index fdd04ef678be2..adb92e2342e18 100644 --- a/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_ElseIf_WithPrevious.cs +++ b/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_ElseIf_WithPrevious.cs @@ -31,166 +31,176 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor [InlineData("else [|if|] (b)")] [InlineData("else [|if (b)|]")] [InlineData("[|else if (b)|]")] - public async Task MergedOnElseIfSpans(string elseIfLine) - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - } - " + elseIfLine + @" - { - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - { - } - } -}"); - } + public Task MergedOnElseIfSpans(string elseIfLine) + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + } + + """ + elseIfLine + """ + + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + { + } + } + } + """); [Fact] - public async Task MergedOnElseIfExtendedHeaderSelection() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - } -[| else if (b) -|] { - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - { - } - } -}"); - } + public Task MergedOnElseIfExtendedHeaderSelection() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + } + [| else if (b) + |] { + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + { + } + } + } + """); [Fact] - public async Task MergedOnElseIfFullSelectionWithoutElseClause() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - } - else [|if (b) - { - }|] - else - { - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - { - } - else - { - } - } -}"); - } + public Task MergedOnElseIfFullSelectionWithoutElseClause() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + } + else [|if (b) + { + }|] + else + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + { + } + else + { + } + } + } + """); [Fact] - public async Task MergedOnElseIfExtendedFullSelectionWithoutElseClause() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - } -[| else if (b) - { - } -|] else - { - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - { - } - else - { - } - } -}"); - } + public Task MergedOnElseIfExtendedFullSelectionWithoutElseClause() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + } + [| else if (b) + { + } + |] else + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + { + } + else + { + } + } + } + """); [Fact] - public async Task NotMergedOnElseIfFullSelectionWithElseClause() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - } - else [|if (b) - { - } - else - { - }|] - } -}"); - } + public Task NotMergedOnElseIfFullSelectionWithElseClause() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + } + else [|if (b) + { + } + else + { + }|] + } + } + """); [Fact] - public async Task NotMergedOnElseIfExtendedFullSelectionWithElseClause() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - } -[| else if (b) - { - } - else - { - } -|] } -}"); - } + public Task NotMergedOnElseIfExtendedFullSelectionWithElseClause() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + } + [| else if (b) + { + } + else + { + } + |] } + } + """); [Theory] [InlineData("else if ([||]b)")] @@ -202,645 +212,678 @@ void M(bool a, bool b) [InlineData("else if (b[|)|]")] [InlineData("else if ([|b|])")] [InlineData("else if [|(b)|]")] - public async Task NotMergedOnElseIfSpans(string elseIfLine) - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - } - " + elseIfLine + @" - { - } - } -}"); - } + public Task NotMergedOnElseIfSpans(string elseIfLine) + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + } + + """ + elseIfLine + """ + + { + } + } + } + """); [Fact] - public async Task NotMergedOnElseIfOverreachingSelection1() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - } - else [|if (b) - |]{ - } - } -}"); - } + public Task NotMergedOnElseIfOverreachingSelection1() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + } + else [|if (b) + |]{ + } + } + } + """); [Fact] - public async Task NotMergedOnElseIfOverreachingSelection2() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - } - [|else if (b) - {|] - } - } -}"); - } + public Task NotMergedOnElseIfOverreachingSelection2() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + } + [|else if (b) + {|] + } + } + } + """); [Fact] - public async Task NotMergedOnElseIfBodySelection() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - } - else if (b) - [|{ - }|] - } -}"); - } + public Task NotMergedOnElseIfBodySelection() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + } + else if (b) + [|{ + }|] + } + } + """); [Fact] - public async Task NotMergedOnElseIfBodyCaret1() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - } - else if (b) - [||]{ - } - } -}"); - } + public Task NotMergedOnElseIfBodyCaret1() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + } + else if (b) + [||]{ + } + } + } + """); [Fact] - public async Task NotMergedOnElseIfBodyCaret2() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - } - else if (b) - { - }[||] - } -}"); - } + public Task NotMergedOnElseIfBodyCaret2() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + } + else if (b) + { + }[||] + } + } + """); [Fact] - public async Task NotMergedOnSingleIf() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - [||]if (b) - { - } - } -}"); - } + public Task NotMergedOnSingleIf() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + [||]if (b) + { + } + } + } + """); [Fact] - public async Task MergedWithOrExpressions() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a || b) - { - } - else [||]if (c || d) - { - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a || b || c || d) - { - } - } -}"); - } + public Task MergedWithOrExpressions() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a || b) + { + } + else [||]if (c || d) + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a || b || c || d) + { + } + } + } + """); [Fact] - public async Task MergedWithAndExpressionNotParenthesized1() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a && b) - { - } - else [||]if (c || d) - { - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a && b || c || d) - { - } - } -}"); - } + public Task MergedWithAndExpressionNotParenthesized1() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a && b) + { + } + else [||]if (c || d) + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a && b || c || d) + { + } + } + } + """); [Fact] - public async Task MergedWithAndExpressionNotParenthesized2() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a || b) - { - } - else [||]if (c && d) - { - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a || b || c && d) - { - } - } -}"); - } + public Task MergedWithAndExpressionNotParenthesized2() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a || b) + { + } + else [||]if (c && d) + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a || b || c && d) + { + } + } + } + """); [Fact] - public async Task MergedWithConditionalExpressionParenthesized1() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (true ? a : b) - { - } - else [||]if (c == d) - { - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if ((true ? a : b) || c == d) - { - } - } -}"); - } + public Task MergedWithConditionalExpressionParenthesized1() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (true ? a : b) + { + } + else [||]if (c == d) + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if ((true ? a : b) || c == d) + { + } + } + } + """); [Fact] - public async Task MergedWithConditionalExpressionParenthesized2() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a == b) - { - } - else [||]if (true ? c : d) - { - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a == b || (true ? c : d)) - { - } - } -}"); - } + public Task MergedWithConditionalExpressionParenthesized2() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a == b) + { + } + else [||]if (true ? c : d) + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a == b || (true ? c : d)) + { + } + } + } + """); [Fact] - public async Task MergedIntoParentWithStatementInsideBlock() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - System.Console.WriteLine(a || b); - } - else [||]if (b) - { - System.Console.WriteLine(a || b); - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - { - System.Console.WriteLine(a || b); - } - } -}"); - } + public Task MergedIntoParentWithStatementInsideBlock() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + System.Console.WriteLine(a || b); + } + else [||]if (b) + { + System.Console.WriteLine(a || b); + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + { + System.Console.WriteLine(a || b); + } + } + } + """); [Fact] - public async Task MergedIntoParentWithStatementWithoutBlock() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - System.Console.WriteLine(a || b); - else [||]if (b) - System.Console.WriteLine(a || b); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - System.Console.WriteLine(a || b); - } -}"); - } + public Task MergedIntoParentWithStatementWithoutBlock() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + System.Console.WriteLine(a || b); + else [||]if (b) + System.Console.WriteLine(a || b); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + System.Console.WriteLine(a || b); + } + } + """); [Fact] - public async Task MergedIntoParentWithDifferenceInBlocks1() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - System.Console.WriteLine(a || b); - else [||]if (b) - { - System.Console.WriteLine(a || b); - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - System.Console.WriteLine(a || b); - } -}"); - } + public Task MergedIntoParentWithDifferenceInBlocks1() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + System.Console.WriteLine(a || b); + else [||]if (b) + { + System.Console.WriteLine(a || b); + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + System.Console.WriteLine(a || b); + } + } + """); [Fact] - public async Task MergedIntoParentWithDifferenceInBlocks2() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - System.Console.WriteLine(a || b); - } - else [||]if (b) - System.Console.WriteLine(a || b); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - { - System.Console.WriteLine(a || b); - } - } -}"); - } + public Task MergedIntoParentWithDifferenceInBlocks2() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + System.Console.WriteLine(a || b); + } + else [||]if (b) + System.Console.WriteLine(a || b); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + { + System.Console.WriteLine(a || b); + } + } + } + """); [Fact] - public async Task MergedIntoParentWithDifferenceInBlocks3() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - System.Console.WriteLine(a || b); - } - else [||]if (b) - { - { - System.Console.WriteLine(a || b); - } - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - { - System.Console.WriteLine(a || b); - } - } -}"); - } + public Task MergedIntoParentWithDifferenceInBlocks3() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + System.Console.WriteLine(a || b); + } + else [||]if (b) + { + { + System.Console.WriteLine(a || b); + } + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + { + System.Console.WriteLine(a || b); + } + } + } + """); [Fact] - public async Task NotMergedIntoParentWithUnmatchingStatements1() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - System.Console.WriteLine(a || b); - } - else [||]if (b) - { - System.Console.WriteLine(a || a); - } - } -}"); - } + public Task NotMergedIntoParentWithUnmatchingStatements1() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + System.Console.WriteLine(a || b); + } + else [||]if (b) + { + System.Console.WriteLine(a || a); + } + } + } + """); [Fact] - public async Task NotMergedIntoParentWithUnmatchingStatements2() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - System.Console.WriteLine(a || b); - else [||]if (b) - System.Console.WriteLine(a || a); - } -}"); - } + public Task NotMergedIntoParentWithUnmatchingStatements2() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + System.Console.WriteLine(a || b); + else [||]if (b) + System.Console.WriteLine(a || a); + } + } + """); [Fact] - public async Task NotMergedIntoParentWithUnmatchingStatements3() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - System.Console.WriteLine(a); - } - else [||]if (b) - System.Console.WriteLine(b); - } -}"); - } + public Task NotMergedIntoParentWithUnmatchingStatements3() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + System.Console.WriteLine(a); + } + else [||]if (b) + System.Console.WriteLine(b); + } + } + """); [Fact] - public async Task NotMergedIntoParentWithUnmatchingStatements4() - { - // Do not consider the using statement to be a simple block (as might be suggested by some language-agnostic helpers). - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - System.Console.WriteLine(a); - } - else [||]if (b) - using (null) - System.Console.WriteLine(a); - } -}"); - } + public Task NotMergedIntoParentWithUnmatchingStatements4() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + System.Console.WriteLine(a); + } + else [||]if (b) + using (null) + System.Console.WriteLine(a); + } + } + """); [Fact] - public async Task MergedIntoParentWithElseStatementInsideBlock() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - System.Console.WriteLine(); - else [||]if (b) - System.Console.WriteLine(); - else - { - System.Console.WriteLine(a || b); - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - System.Console.WriteLine(); - else - { - System.Console.WriteLine(a || b); - } - } -}"); - } + public Task MergedIntoParentWithElseStatementInsideBlock() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + System.Console.WriteLine(); + else [||]if (b) + System.Console.WriteLine(); + else + { + System.Console.WriteLine(a || b); + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + System.Console.WriteLine(); + else + { + System.Console.WriteLine(a || b); + } + } + } + """); [Fact] - public async Task MergedIntoParentWithElseStatementWithoutBlock() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - System.Console.WriteLine(); - else [||]if (b) - System.Console.WriteLine(); - else - System.Console.WriteLine(a || b); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - System.Console.WriteLine(); - else - System.Console.WriteLine(a || b); - } -}"); - } + public Task MergedIntoParentWithElseStatementWithoutBlock() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + System.Console.WriteLine(); + else [||]if (b) + System.Console.WriteLine(); + else + System.Console.WriteLine(a || b); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + System.Console.WriteLine(); + else + System.Console.WriteLine(a || b); + } + } + """); [Fact] - public async Task MergedIntoParentWithElseNestedIfStatement() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - System.Console.WriteLine(); - else [||]if (b) - System.Console.WriteLine(); - else if (true) { } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - System.Console.WriteLine(); - else if (true) { } - } -}"); - } + public Task MergedIntoParentWithElseNestedIfStatement() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + System.Console.WriteLine(); + else [||]if (b) + System.Console.WriteLine(); + else if (true) { } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + System.Console.WriteLine(); + else if (true) { } + } + } + """); [Fact] - public async Task MergedIntoParentWithElseIfElse() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - System.Console.WriteLine(); - else [||]if (b) - System.Console.WriteLine(); - else if (a) - System.Console.WriteLine(a); - else - System.Console.WriteLine(b); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - System.Console.WriteLine(); - else if (a) - System.Console.WriteLine(a); - else - System.Console.WriteLine(b); - } -}"); - } + public Task MergedIntoParentWithElseIfElse() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + System.Console.WriteLine(); + else [||]if (b) + System.Console.WriteLine(); + else if (a) + System.Console.WriteLine(a); + else + System.Console.WriteLine(b); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + System.Console.WriteLine(); + else if (a) + System.Console.WriteLine(a); + else + System.Console.WriteLine(b); + } + } + """); [Fact] - public async Task MergedIntoParentPartOfElseIf() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - System.Console.WriteLine(); - else if (b) - System.Console.WriteLine(a); - else [||]if (a) - System.Console.WriteLine(a); - else - System.Console.WriteLine(b); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - System.Console.WriteLine(); - else if (b || a) - System.Console.WriteLine(a); - else - System.Console.WriteLine(b); - } -}"); - } + public Task MergedIntoParentPartOfElseIf() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + System.Console.WriteLine(); + else if (b) + System.Console.WriteLine(a); + else [||]if (a) + System.Console.WriteLine(a); + else + System.Console.WriteLine(b); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + System.Console.WriteLine(); + else if (b || a) + System.Console.WriteLine(a); + else + System.Console.WriteLine(b); + } + } + """); [Fact] - public async Task MergedWithPreservedSingleLineFormatting() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) System.Console.WriteLine(); - else [||]if (b) System.Console.WriteLine(); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) System.Console.WriteLine(); - } -}"); - } + public Task MergedWithPreservedSingleLineFormatting() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) System.Console.WriteLine(); + else [||]if (b) System.Console.WriteLine(); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) System.Console.WriteLine(); + } + } + """); } diff --git a/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_Statements_Middle.cs b/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_Statements_Middle.cs index 2d490959ed901..ffb8b0d31a3de 100644 --- a/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_Statements_Middle.cs +++ b/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_Statements_Middle.cs @@ -15,33 +15,37 @@ public sealed partial class MergeConsecutiveIfStatementsTests public async Task MergedIntoStatementOnMiddleIfMergableWithNextOnly() { const string Initial = -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a) - return; - else - return; - [||]if (b) - return; - if (c) - return; - } -}"; + """ + class C + { + void M(bool a, bool b, bool c) + { + if (a) + return; + else + return; + [||]if (b) + return; + if (c) + return; + } + } + """; const string Expected = -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a) - return; - else - return; - if (b || c) - return; - } -}"; + """ + class C + { + void M(bool a, bool b, bool c) + { + if (a) + return; + else + return; + if (b || c) + return; + } + } + """; await TestActionCountAsync(Initial, 1); await TestInRegularAndScriptAsync(Initial, Expected); @@ -51,33 +55,37 @@ void M(bool a, bool b, bool c) public async Task MergedIntoStatementOnMiddleIfMergableWithPreviousOnly() { const string Initial = -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a) - return; - [||]if (b) - return; - else - return; - if (c) - return; - } -}"; + """ + class C + { + void M(bool a, bool b, bool c) + { + if (a) + return; + [||]if (b) + return; + else + return; + if (c) + return; + } + } + """; const string Expected = -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a || b) - return; - else - return; - if (c) - return; - } -}"; + """ + class C + { + void M(bool a, bool b, bool c) + { + if (a || b) + return; + else + return; + if (c) + return; + } + } + """; await TestActionCountAsync(Initial, 1); await TestInRegularAndScriptAsync(Initial, Expected); @@ -87,40 +95,46 @@ void M(bool a, bool b, bool c) public async Task MergedIntoStatementOnMiddleIfMergableWithBoth() { const string Initial = -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a) - return; - [||]if (b) - return; - if (c) - return; - } -}"; + """ + class C + { + void M(bool a, bool b, bool c) + { + if (a) + return; + [||]if (b) + return; + if (c) + return; + } + } + """; const string Expected1 = -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a || b) - return; - if (c) - return; - } -}"; + """ + class C + { + void M(bool a, bool b, bool c) + { + if (a || b) + return; + if (c) + return; + } + } + """; const string Expected2 = -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a) - return; - if (b || c) - return; - } -}"; + """ + class C + { + void M(bool a, bool b, bool c) + { + if (a) + return; + if (b || c) + return; + } + } + """; await TestActionCountAsync(Initial, 2); await TestInRegularAndScriptAsync(Initial, Expected1, index: 0); diff --git a/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_Statements_WithNext.cs b/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_Statements_WithNext.cs index edec7edd3f5a8..e2142243358f8 100644 --- a/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_Statements_WithNext.cs +++ b/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_Statements_WithNext.cs @@ -19,100 +19,110 @@ public sealed partial class MergeConsecutiveIfStatementsTests [InlineData("if (a)[||]")] [InlineData("[|if|] (a)")] [InlineData("[|if (a)|]")] - public async Task MergedIntoNextStatementOnIfSpans(string ifLine) - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - " + ifLine + @" - return; - if (b) - return; - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - return; - } -}"); - } + public Task MergedIntoNextStatementOnIfSpans(string ifLine) + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + + """ + ifLine + """ + + return; + if (b) + return; + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + return; + } + } + """); [Fact] - public async Task MergedIntoNextStatementOnIfExtendedHeaderSelection() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { -[| if (a) - return; -|] if (b) - return; - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - return; - } -}"); - } + public Task MergedIntoNextStatementOnIfExtendedHeaderSelection() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + [| if (a) + return; + |] if (b) + return; + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + return; + } + } + """); [Fact] - public async Task MergedIntoNextStatementOnIfFullSelection() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - [|if (a) - return;|] - if (b) - return; - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - return; - } -}"); - } + public Task MergedIntoNextStatementOnIfFullSelection() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + [|if (a) + return;|] + if (b) + return; + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + return; + } + } + """); [Fact] - public async Task MergedIntoNextStatementOnIfExtendedFullSelection() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { -[| if (a) - return; -|] if (b) - return; - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - return; - } -}"); - } + public Task MergedIntoNextStatementOnIfExtendedFullSelection() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + [| if (a) + return; + |] if (b) + return; + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + return; + } + } + """); [Theory] [InlineData("if ([||]a)")] @@ -122,50 +132,52 @@ void M(bool a, bool b) [InlineData("if (a[|)|]")] [InlineData("if ([|a|])")] [InlineData("if [|(a)|]")] - public async Task NotMergedIntoNextStatementOnIfSpans(string ifLine) - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - " + ifLine + @" - return; - if (b) - return; - } -}"); - } + public Task NotMergedIntoNextStatementOnIfSpans(string ifLine) + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + + """ + ifLine + """ + + return; + if (b) + return; + } + } + """); [Fact] - public async Task NotMergedIntoNextStatementOnIfOverreachingSelection() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - [|if (a) - |] return; - if (b) - return; - } -}"); - } + public Task NotMergedIntoNextStatementOnIfOverreachingSelection() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + [|if (a) + |] return; + if (b) + return; + } + } + """); [Fact] - public async Task NotMergedIntoNextStatementOnIfBodySelection() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - [|return;|] - if (b) - return; - } -}"); - } + public Task NotMergedIntoNextStatementOnIfBodySelection() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + [|return;|] + if (b) + return; + } + } + """); } diff --git a/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_Statements_WithPrevious.cs b/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_Statements_WithPrevious.cs index 45fe61eccab6a..bdd978eb4d1f8 100644 --- a/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_Statements_WithPrevious.cs +++ b/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_Statements_WithPrevious.cs @@ -19,198 +19,210 @@ public sealed partial class MergeConsecutiveIfStatementsTests [InlineData("if (b)[||]")] [InlineData("[|if|] (b)")] [InlineData("[|if (b)|]")] - public async Task MergedIntoPreviousStatementOnIfSpans(string ifLine) - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - return; - " + ifLine + @" - return; - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - return; - } -}"); - } + public Task MergedIntoPreviousStatementOnIfSpans(string ifLine) + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + return; + """ + ifLine + """ + return; + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + return; + } + } + """); [Fact] - public async Task MergedIntoPreviousStatementOnIfExtendedHeaderSelection() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - return; -[| if (b) -|] return; - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - return; - } -}"); - } + public Task MergedIntoPreviousStatementOnIfExtendedHeaderSelection() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + return; + [| if (b) + |] return; + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + return; + } + } + """); [Fact] - public async Task MergedIntoPreviousStatementOnIfFullSelection() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - return; - [|if (b) - return;|] - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - return; - } -}"); - } + public Task MergedIntoPreviousStatementOnIfFullSelection() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + return; + [|if (b) + return;|] + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + return; + } + } + """); [Fact] - public async Task MergedIntoPreviousStatementOnIfExtendedFullSelection() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - return; -[| if (b) - return; -|] } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - return; - } -}"); - } + public Task MergedIntoPreviousStatementOnIfExtendedFullSelection() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + return; + [| if (b) + return; + |] } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + return; + } + } + """); [Fact] - public async Task MergedIntoPreviousStatementOnIfFullSelectionWithoutElseClause() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - return; - [|if (b) - return;|] - else - { - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - return; - else - { - } - } -}"); - } + public Task MergedIntoPreviousStatementOnIfFullSelectionWithoutElseClause() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + return; + [|if (b) + return;|] + else + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + return; + else + { + } + } + } + """); [Fact] - public async Task MergedIntoPreviousStatementOnIfExtendedFullSelectionWithoutElseClause() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - return; -[| if (b) - return; -|] else - { - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - return; - else - { - } - } -}"); - } + public Task MergedIntoPreviousStatementOnIfExtendedFullSelectionWithoutElseClause() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + return; + [| if (b) + return; + |] else + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + return; + else + { + } + } + } + """); [Fact] - public async Task NotMergedIntoPreviousStatementOnIfFullSelectionWithElseClause() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - return; - [|if (b) - return; - else - { - }|] - } -}"); - } + public Task NotMergedIntoPreviousStatementOnIfFullSelectionWithElseClause() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + return; + [|if (b) + return; + else + { + }|] + } + } + """); [Fact] - public async Task NotMergedIntoPreviousStatementOnIfExtendedFullSelectionWithElseClause() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - return; -[| if (b) - return; - else - { - } -|] } -}"); - } + public Task NotMergedIntoPreviousStatementOnIfExtendedFullSelectionWithElseClause() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + return; + [| if (b) + return; + else + { + } + |] } + } + """); [Theory] [InlineData("if ([||]b)")] @@ -220,567 +232,584 @@ void M(bool a, bool b) [InlineData("if (b[|)|]")] [InlineData("if ([|b|])")] [InlineData("if [|(b)|]")] - public async Task NotMergedIntoPreviousStatementOnIfSpans(string ifLine) - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - return; - " + ifLine + @" - return; - } -}"); - } - - [Fact] - public async Task NotMergedIntoPreviousStatementOnIfOverreachingSelection() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - return; - [|if (b) - |]return; - } -}"); - } + public Task NotMergedIntoPreviousStatementOnIfSpans(string ifLine) + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + return; + """ + ifLine + """ + return; + } + } + """); [Fact] - public async Task NotMergedIntoPreviousStatementOnIfBodySelection() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - return; - if (b) - [|return;|] - } -}"); - } + public Task NotMergedIntoPreviousStatementOnIfOverreachingSelection() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + return; + [|if (b) + |]return; + } + } + """); [Fact] - public async Task MergedIntoPreviousStatementIfControlFlowQuits1() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - return; - [||]if (b) - return; - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - return; - } -}"); - } + public Task NotMergedIntoPreviousStatementOnIfBodySelection() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + return; + if (b) + [|return;|] + } + } + """); [Fact] - public async Task MergedIntoPreviousStatementIfControlFlowQuits2() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - throw new System.Exception(); - [||]if (b) - throw new System.Exception(); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - throw new System.Exception(); - } -}"); - } + public Task MergedIntoPreviousStatementIfControlFlowQuits1() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + return; + [||]if (b) + return; + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + return; + } + } + """); [Fact] - public async Task MergedIntoPreviousStatementIfControlFlowQuits3() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - while (true) - { - if (a) - continue; - [||]if (b) - continue; - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - while (true) - { - if (a || b) - continue; - } - } -}"); - } + public Task MergedIntoPreviousStatementIfControlFlowQuits2() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + throw new System.Exception(); + [||]if (b) + throw new System.Exception(); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + throw new System.Exception(); + } + } + """); [Fact] - public async Task MergedIntoPreviousStatementIfControlFlowQuits4() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - while (true) - { - if (a) + public Task MergedIntoPreviousStatementIfControlFlowQuits3() + => TestInRegularAndScriptAsync( + """ + class C { - if (a) - continue; - else - break; + void M(bool a, bool b) + { + while (true) + { + if (a) + continue; + [||]if (b) + continue; + } + } } - - [||]if (b) + """, + """ + class C { - if (a) - continue; - else - break; + void M(bool a, bool b) + { + while (true) + { + if (a || b) + continue; + } + } } - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - while (true) - { - if (a || b) - { - if (a) - continue; - else - break; - } - } - } -}"); - } + """); [Fact] - public async Task MergedIntoPreviousStatementIfControlFlowQuits5() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - while (true) - { - if (a) - switch (a) + public Task MergedIntoPreviousStatementIfControlFlowQuits4() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + while (true) + { + if (a) + { + if (a) + continue; + else + break; + } + + [||]if (b) + { + if (a) + continue; + else + break; + } + } + } + } + """, + """ + class C + { + void M(bool a, bool b) { - default: - continue; + while (true) + { + if (a || b) + { + if (a) + continue; + else + break; + } + } } + } + """); - [||]if (b) - switch (a) + [Fact] + public Task MergedIntoPreviousStatementIfControlFlowQuits5() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) { - default: - continue; + while (true) + { + if (a) + switch (a) + { + default: + continue; + } + + [||]if (b) + switch (a) + { + default: + continue; + } + } } - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - while (true) - { - if (a || b) - switch (a) + } + """, + """ + class C + { + void M(bool a, bool b) { - default: - continue; + while (true) + { + if (a || b) + switch (a) + { + default: + continue; + } + } } - } - } -}"); - } + } + """); [Fact] - public async Task MergedIntoPreviousStatementIfControlFlowQuitsInSwitchSection() - { - // Switch sections are interesting in that they are blocks of statements that aren't BlockSyntax. - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - switch (a) - { - case true: - if (a) - break; - [||]if (b) - break; - break; - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - switch (a) - { - case true: - if (a || b) - break; - break; - } - } -}"); - } + public Task MergedIntoPreviousStatementIfControlFlowQuitsInSwitchSection() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + switch (a) + { + case true: + if (a) + break; + [||]if (b) + break; + break; + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + switch (a) + { + case true: + if (a || b) + break; + break; + } + } + } + """); [Fact] - public async Task MergedIntoPreviousStatementIfControlFlowQuitsWithDifferenceInBlocks() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { + public Task MergedIntoPreviousStatementIfControlFlowQuitsWithDifferenceInBlocks() + => TestInRegularAndScriptAsync( + """ + class C { - return; + void M(bool a, bool b) + { + if (a) + { + { + return; + } + } + + [||]if (b) + return; + } } - } - - [||]if (b) - return; - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - { + """, + """ + class C { - return; + void M(bool a, bool b) + { + if (a || b) + { + { + return; + } + } + } } - } - } -}"); - } + """); [Fact] - public async Task MergedIntoPreviousStatementIncludingElseClauseIfControlFlowQuits() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - return; - [||]if (b) - return; - else - System.Console.WriteLine(); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - return; - else - System.Console.WriteLine(); - } -}"); - } + public Task MergedIntoPreviousStatementIncludingElseClauseIfControlFlowQuits() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + return; + [||]if (b) + return; + else + System.Console.WriteLine(); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + return; + else + System.Console.WriteLine(); + } + } + """); [Fact] - public async Task MergedIntoPreviousStatementIncludingElseIfClauseIfControlFlowQuits() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - return; - [||]if (b) - return; - else if (a && b) - System.Console.WriteLine(); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - return; - else if (a && b) - System.Console.WriteLine(); - } -}"); - } + public Task MergedIntoPreviousStatementIncludingElseIfClauseIfControlFlowQuits() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + return; + [||]if (b) + return; + else if (a && b) + System.Console.WriteLine(); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + return; + else if (a && b) + System.Console.WriteLine(); + } + } + """); [Fact] - public async Task MergedIntoPreviousStatementIfControlFlowQuitsWithPreservedSingleLineFormatting() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) return; - [||]if (b) return; - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) return; - } -}"); - } + public Task MergedIntoPreviousStatementIfControlFlowQuitsWithPreservedSingleLineFormatting() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) return; + [||]if (b) return; + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) return; + } + } + """); [Fact] - public async Task NotMergedIntoPreviousStatementIfControlFlowContinues1() - { - // Even though there are no statements inside, we still can't merge these into one statement - // because it would change the semantics from always evaluating the second condition to short-circuiting. - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - } - - [||]if (b) - { - } - } -}"); - } + public Task NotMergedIntoPreviousStatementIfControlFlowContinues1() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + } - [Fact] - public async Task NotMergedIntoPreviousStatementIfControlFlowContinues2() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - System.Console.WriteLine(); - [||]if (b) - System.Console.WriteLine(); - } -}"); - } + [||]if (b) + { + } + } + } + """); [Fact] - public async Task NotMergedIntoPreviousStatementIfControlFlowContinues3() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - if (a) - return; - } - - [||]if (b) - { - if (a) - return; - } - } -}"); - } + public Task NotMergedIntoPreviousStatementIfControlFlowContinues2() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + System.Console.WriteLine(); + [||]if (b) + System.Console.WriteLine(); + } + } + """); [Fact] - public async Task NotMergedIntoPreviousStatementIfControlFlowContinues4() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - while (a) + public Task NotMergedIntoPreviousStatementIfControlFlowContinues3() + => TestMissingInRegularAndScriptAsync( + """ + class C { - break; + void M(bool a, bool b) + { + if (a) + { + if (a) + return; + } + + [||]if (b) + { + if (a) + return; + } + } } + """); - [||]if (b) - while (a) + [Fact] + public Task NotMergedIntoPreviousStatementIfControlFlowContinues4() + => TestMissingInRegularAndScriptAsync( + """ + class C { - break; + void M(bool a, bool b) + { + if (a) + while (a) + { + break; + } + + [||]if (b) + while (a) + { + break; + } + } } - } -}"); - } + """); [Fact] - public async Task NotMergedIntoPreviousStatementIfControlFlowContinues5() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - while (true) - { - if (a) - switch (a) + public Task NotMergedIntoPreviousStatementIfControlFlowContinues5() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) { - default: - break; + while (true) + { + if (a) + switch (a) + { + default: + break; + } + + [||]if (b) + switch (a) + { + default: + break; + } + } } + } + """); - [||]if (b) - switch (a) + [Fact] + public Task NotMergedIntoPreviousStatementWithUnmatchingStatementsIfControlFlowQuits() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) { - default: - break; + if (a) + return; + [||]if (b) + throw new System.Exception(); } - } - } -}"); - } + } + """); [Fact] - public async Task NotMergedIntoPreviousStatementWithUnmatchingStatementsIfControlFlowQuits() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - return; - [||]if (b) - throw new System.Exception(); - } -}"); - } + public Task NotMergedIntoPreviousStatementThatHasElseClauseIfControlFlowQuits1() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + return; + else + return; - [Fact] - public async Task NotMergedIntoPreviousStatementThatHasElseClauseIfControlFlowQuits1() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - return; - else - return; - - [||]if (b) - return; - } -}"); - } + [||]if (b) + return; + } + } + """); [Fact] - public async Task NotMergedIntoPreviousStatementThatHasElseClauseIfControlFlowQuits2() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - return; - else - return; - - [||]if (b) - return; - else - return; - } -}"); - } + public Task NotMergedIntoPreviousStatementThatHasElseClauseIfControlFlowQuits2() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + return; + else + return; + + [||]if (b) + return; + else + return; + } + } + """); [Fact] - public async Task NotMergedIntoPreviousStatementAsEmbeddedStatementIfControlFlowQuits1() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - return; - - while (a) - [||]if (b) - return; - } -}"); - } + public Task NotMergedIntoPreviousStatementAsEmbeddedStatementIfControlFlowQuits1() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + return; + + while (a) + [||]if (b) + return; + } + } + """); [Fact] - public async Task NotMergedIntoPreviousStatementAsEmbeddedStatementIfControlFlowQuits2() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - return; - - if (a) - { - } - else [||]if (b) - return; - } -}"); - } + public Task NotMergedIntoPreviousStatementAsEmbeddedStatementIfControlFlowQuits2() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + return; + + if (a) + { + } + else [||]if (b) + return; + } + } + """); } diff --git a/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeNestedIfStatementsTests_WithNested.cs b/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeNestedIfStatementsTests_WithNested.cs index c94a22de9b8de..77512aba1c142 100644 --- a/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeNestedIfStatementsTests_WithNested.cs +++ b/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeNestedIfStatementsTests_WithNested.cs @@ -13,54 +13,58 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SplitOrMergeIfStatement public sealed partial class MergeNestedIfStatementsTests { [Fact] - public async Task MergedOnOuterIf() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - [||]if (a) - { - if (b) + public Task MergedOnOuterIf() + => TestInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b) + { + [||]if (a) + { + if (b) + { + } + } + } } - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - { - } - } -}"); - } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a && b) + { + } + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/55563")] - public async Task MergedOnOuterIf_TopLevelStatements() - { - await TestInRegularAndScriptAsync( -@"var a = true; -var b = true; + public Task MergedOnOuterIf_TopLevelStatements() + => TestInRegularAndScriptAsync( + """ + var a = true; + var b = true; -[||]if (a) -{ - if (b) - { - } -} -", -@"var a = true; -var b = true; + [||]if (a) + { + if (b) + { + } + } -if (a && b) -{ -} -"); - } + """, + """ + var a = true; + var b = true; + + if (a && b) + { + } + + """); [Theory] [InlineData("[||]else if (a)")] @@ -74,199 +78,209 @@ await TestInRegularAndScriptAsync( [InlineData("else [|if|] (a)")] [InlineData("else [|if (a)|]")] [InlineData("[|else if (a)|]")] - public async Task MergedOnOuterElseIfSpans(string elseIfLine) - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (true) - { - } - " + elseIfLine + @" - { - if (b) + public Task MergedOnOuterElseIfSpans(string elseIfLine) + => TestInRegularAndScriptAsync( + """ + class C { - } - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (true) - { - } - else if (a && b) - { - } - } -}"); - } + void M(bool a, bool b) + { + if (true) + { + } + + """ + elseIfLine + """ - [Fact] - public async Task MergedOnOuterElseIfExtendedHeaderSelection() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (true) - { - } -[| else if (a) -|] { - if (b) + { + if (b) + { + } + } + } + } + """, + """ + class C { + void M(bool a, bool b) + { + if (true) + { + } + else if (a && b) + { + } + } } - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (true) - { - } - else if (a && b) - { - } - } -}"); - } + """); [Fact] - public async Task MergedOnOuterElseIfFullSelection() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (true) - { - } -[| else if (a) - { - if (b) + public Task MergedOnOuterElseIfExtendedHeaderSelection() + => TestInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b) + { + if (true) + { + } + [| else if (a) + |] { + if (b) + { + } + } + } } - } -|] } -}", -@"class C -{ - void M(bool a, bool b) - { - if (true) - { - } - else if (a && b) - { - } - } -}"); - } + """, + """ + class C + { + void M(bool a, bool b) + { + if (true) + { + } + else if (a && b) + { + } + } + } + """); [Fact] - public async Task MergedOnOuterElseIfFullSelectionWithElseClause() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (true) - { - } - [|else if (a) - { - if (b) + public Task MergedOnOuterElseIfFullSelection() + => TestInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b) + { + if (true) + { + } + [| else if (a) + { + if (b) + { + } + } + |] } } - else + """, + """ + class C { + void M(bool a, bool b) + { + if (true) + { + } + else if (a && b) + { + } + } } - } - else - { - }|] - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (true) - { - } - else if (a && b) - { - } - else - { - } - } -}"); - } + """); [Fact] - public async Task NotMergedOnOuterElseIfFullSelectionWithoutElseClause() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (true) - { - } - [|else if (a) - { - if (b) + public Task MergedOnOuterElseIfFullSelectionWithElseClause() + => TestInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b) + { + if (true) + { + } + [|else if (a) + { + if (b) + { + } + else + { + } + } + else + { + }|] + } } - else + """, + """ + class C { + void M(bool a, bool b) + { + if (true) + { + } + else if (a && b) + { + } + else + { + } + } } - }|] - else - { - } - } -}"); - } + """); [Fact] - public async Task NotMergedOnOuterElseIfFullSelectionWithParentIf() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - [|if (true) - { - } - else if (a) - { - if (b) + public Task NotMergedOnOuterElseIfFullSelectionWithoutElseClause() + => TestMissingInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b) + { + if (true) + { + } + [|else if (a) + { + if (b) + { + } + else + { + } + }|] + else + { + } + } } - else + """); + + [Fact] + public Task NotMergedOnOuterElseIfFullSelectionWithParentIf() + => TestMissingInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b) + { + [|if (true) + { + } + else if (a) + { + if (b) + { + } + else + { + } + } + else + { + }|] + } } - } - else - { - }|] - } -}"); - } + """); [Theory] [InlineData("else if ([||]a)")] @@ -279,169 +293,175 @@ void M(bool a, bool b) [InlineData("else if (a[|)|]")] [InlineData("else if ([|a|])")] [InlineData("else if [|(a)|]")] - public async Task NotMergedOnOuterElseIfSpans(string elseIfLine) - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (true) - { - } - " + elseIfLine + @" - { - if (b) + public Task NotMergedOnOuterElseIfSpans(string elseIfLine) + => TestMissingInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b) + { + if (true) + { + } + + """ + elseIfLine + """ + + { + if (b) + { + } + } + } } - } - } -}"); - } + """); [Fact] - public async Task NotMergedOnOuterElseIfOverreachingSelection1() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (true) - { - } - [|else if (a) - |]{ - if (b) + public Task NotMergedOnOuterElseIfOverreachingSelection1() + => TestMissingInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b) + { + if (true) + { + } + [|else if (a) + |]{ + if (b) + { + } + } + } } - } - } -}"); - } + """); [Fact] - public async Task NotMergedOnOuterElseIfOverreachingSelection2() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (true) - { - } - [|else if (a) - {|] - if (b) + public Task NotMergedOnOuterElseIfOverreachingSelection2() + => TestMissingInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b) + { + if (true) + { + } + [|else if (a) + {|] + if (b) + { + } + } + } } - } - } -}"); - } + """); [Fact] - public async Task NotMergedOnOuterElseIfBodySelection() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (true) - { - } - else if (a) - [|{ - if (b) + public Task NotMergedOnOuterElseIfBodySelection() + => TestMissingInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b) + { + if (true) + { + } + else if (a) + [|{ + if (b) + { + } + }|] + } } - }|] - } -}"); - } + """); [Fact] - public async Task NotMergedOnOuterElseIfBodyCaret1() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (true) - { - } - else if (a) - [||]{ - if (b) + public Task NotMergedOnOuterElseIfBodyCaret1() + => TestMissingInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b) + { + if (true) + { + } + else if (a) + [||]{ + if (b) + { + } + } + } } - } - } -}"); - } + """); [Fact] - public async Task NotMergedOnOuterElseIfBodyCaret2() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (true) - { - } - else if (a) - { - if (b) + public Task NotMergedOnOuterElseIfBodyCaret2() + => TestMissingInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b) + { + if (true) + { + } + else if (a) + { + if (b) + { + } + }[||] + } } - }[||] - } -}"); - } + """); [Fact] public async Task MergedOnMiddleIfMergableWithNestedOnly() { const string Initial = -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a) - { - [||]if (b) + """ + class C { - if (c) + void M(bool a, bool b, bool c) { - System.Console.WriteLine(); + if (a) + { + [||]if (b) + { + if (c) + { + System.Console.WriteLine(); + } + } + + return; + } } } - - return; - } - } -}"; + """; const string Expected = -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a) - { - if (b && c) + """ + class C { - System.Console.WriteLine(); - } + void M(bool a, bool b, bool c) + { + if (a) + { + if (b && c) + { + System.Console.WriteLine(); + } - return; - } - } -}"; + return; + } + } + } + """; await TestActionCountAsync(Initial, 1); await TestInRegularAndScriptAsync(Initial, Expected); @@ -451,40 +471,44 @@ void M(bool a, bool b, bool c) public async Task MergedOnMiddleIfMergableWithOuterOnly() { const string Initial = -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a) - { - [||]if (b) + """ + class C { - if (c) + void M(bool a, bool b, bool c) { - System.Console.WriteLine(); - } + if (a) + { + [||]if (b) + { + if (c) + { + System.Console.WriteLine(); + } - return; + return; + } + } + } } - } - } -}"; + """; const string Expected = -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a && b) - { - if (c) + """ + class C { - System.Console.WriteLine(); - } + void M(bool a, bool b, bool c) + { + if (a && b) + { + if (c) + { + System.Console.WriteLine(); + } - return; - } - } -}"; + return; + } + } + } + """; await TestActionCountAsync(Initial, 1); await TestInRegularAndScriptAsync(Initial, Expected); @@ -494,50 +518,56 @@ void M(bool a, bool b, bool c) public async Task MergedOnMiddleIfMergableWithBoth() { const string Initial = -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a) - { - [||]if (b) + """ + class C { - if (c) + void M(bool a, bool b, bool c) { - System.Console.WriteLine(); + if (a) + { + [||]if (b) + { + if (c) + { + System.Console.WriteLine(); + } + } + } } } - } - } -}"; + """; const string Expected1 = -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a && b) - { - if (c) + """ + class C { - System.Console.WriteLine(); + void M(bool a, bool b, bool c) + { + if (a && b) + { + if (c) + { + System.Console.WriteLine(); + } + } + } } - } - } -}"; + """; const string Expected2 = -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a) - { - if (b && c) + """ + class C { - System.Console.WriteLine(); + void M(bool a, bool b, bool c) + { + if (a) + { + if (b && c) + { + System.Console.WriteLine(); + } + } + } } - } - } -}"; + """; await TestActionCountAsync(Initial, 2); await TestInRegularAndScriptAsync(Initial, Expected1, index: 0); diff --git a/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeNestedIfStatementsTests_WithOuter.cs b/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeNestedIfStatementsTests_WithOuter.cs index 6e3c6a17aad2c..2effd9f08db47 100644 --- a/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeNestedIfStatementsTests_WithOuter.cs +++ b/src/Features/CSharpTest/SplitOrMergeIfStatements/MergeNestedIfStatementsTests_WithOuter.cs @@ -27,145 +27,153 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor [InlineData("if (b)[||]")] [InlineData("[|if|] (b)")] [InlineData("[|if (b)|]")] - public async Task MergedOnNestedIfSpans(string ifLine) - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - " + ifLine + @" + public Task MergedOnNestedIfSpans(string ifLine) + => TestInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b) + { + if (a) + { + """ + ifLine + """ + { + } + } + } } - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - { - } - } -}"); - } - - [Fact] - public async Task MergedOnNestedIfExtendedHeaderSelection() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { -[| if (b) -|] { - } - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - { - } - } -}"); - } - - [Fact] - public async Task MergedOnNestedIfFullSelection() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { -[| if (b) + """, + """ + class C { + void M(bool a, bool b) + { + if (a && b) + { + } + } } -|] } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - { - } - } -}"); - } - - [Fact] - public async Task MergedOnNestedIfFullSelectionWithElseClause() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [|if (b) + """); + + [Fact] + public Task MergedOnNestedIfExtendedHeaderSelection() + => TestInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b) + { + if (a) + { + [| if (b) + |] { + } + } + } } - else + """, + """ + class C { - }|] - } - else - { - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - { - } - else - { - } - } -}"); - } - - [Fact] - public async Task NotMergedOnNestedIfFullSelectionWithoutElseClause() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [|if (b) + void M(bool a, bool b) + { + if (a && b) + { + } + } + } + """); + + [Fact] + public Task MergedOnNestedIfFullSelection() + => TestInRegularAndScriptAsync( + """ + class C { - }|] - else + void M(bool a, bool b) + { + if (a) + { + [| if (b) + { + } + |] } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a && b) + { + } + } + } + """); + + [Fact] + public Task MergedOnNestedIfFullSelectionWithElseClause() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [|if (b) + { + } + else + { + }|] + } + else + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a && b) + { + } + else + { + } + } + } + """); + + [Fact] + public Task NotMergedOnNestedIfFullSelectionWithoutElseClause() + => TestMissingInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b) + { + if (a) + { + [|if (b) + { + }|] + else + { + } + } + else + { + } + } } - } - else - { - } - } -}"); - } + """); [Theory] [InlineData("if ([||]b)")] @@ -175,1972 +183,2088 @@ void M(bool a, bool b) [InlineData("if (b[|)|]")] [InlineData("if ([|b|])")] [InlineData("if [|(b)|]")] - public async Task NotMergedOnNestedIfSpans(string ifLine) - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - " + ifLine + @" + public Task NotMergedOnNestedIfSpans(string ifLine) + => TestMissingInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b) + { + if (a) + { + """ + ifLine + """ + { + } + } + } } - } - } -}"); - } + """); [Fact] - public async Task NotMergedOnNestedIfOverreachingSelection1() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [|if (b) - |]{ - } - } - } -}"); - } - - [Fact] - public async Task NotMergedOnNestedIfOverreachingSelection2() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [|if (b) - {|] - } - } - } -}"); - } - - [Fact] - public async Task NotMergedOnNestedIfBodySelection() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - if (b) - [|{ - }|] - } - } -}"); - } - - [Fact] - public async Task NotMergedOnNestedIfBodyCaret1() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - if (b) - [||]{ - } - } - } -}"); - } - - [Fact] - public async Task NotMergedOnNestedIfBodyCaret2() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - if (b) - { - }[||] - } - } -}"); - } - - [Fact] - public async Task NotMergedOnSingleIfInsideBlock() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - { - [||]if (b) + public Task NotMergedOnNestedIfOverreachingSelection1() + => TestMissingInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b) + { + if (a) + { + [|if (b) + |]{ + } + } + } } - } - } -}"); - } + """); [Fact] - public async Task NotMergedOnSingleIf() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - [||]if (b) - { - } - } -}"); - } - - [Fact] - public async Task MergedWithAndExpressions() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a && b) - { - [||]if (c && d) + public Task NotMergedOnNestedIfOverreachingSelection2() + => TestMissingInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b) + { + if (a) + { + [|if (b) + {|] + } + } + } } - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a && b && c && d) - { - } - } -}"); - } - - [Fact] - public async Task MergedWithOrExpressionParenthesized1() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a || b) - { - [||]if (c && d) + """); + + [Fact] + public Task NotMergedOnNestedIfBodySelection() + => TestMissingInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b) + { + if (a) + { + if (b) + [|{ + }|] + } + } } - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if ((a || b) && c && d) - { - } - } -}"); - } - - [Fact] - public async Task MergedWithOrExpressionParenthesized2() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a && b) - { - [||]if (c || d) + """); + + [Fact] + public Task NotMergedOnNestedIfBodyCaret1() + => TestMissingInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b) + { + if (a) + { + if (b) + [||]{ + } + } + } } - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a && b && (c || d)) - { - } - } -}"); - } - - [Fact] - public async Task MergedWithBitwiseOrExpressionNotParenthesized1() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a | b) - { - [||]if (c && d) + """); + + [Fact] + public Task NotMergedOnNestedIfBodyCaret2() + => TestMissingInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b) + { + if (a) + { + if (b) + { + }[||] + } + } } - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a | b && c && d) - { - } - } -}"); - } - - [Fact] - public async Task MergedWithBitwiseOrExpressionNotParenthesized2() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a && b) - { - [||]if (c | d) + """); + + [Fact] + public Task NotMergedOnSingleIfInsideBlock() + => TestMissingInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b) + { + { + [||]if (b) + { + } + } + } } - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a && b && c | d) - { - } - } -}"); - } - - [Fact] - public async Task MergedWithMixedExpressions1() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a || b && c) - { - [||]if (c == d) + """); + + [Fact] + public Task NotMergedOnSingleIf() + => TestMissingInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b) + { + [||]if (b) + { + } + } } - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if ((a || b && c) && c == d) - { - } - } -}"); - } - - [Fact] - public async Task MergedWithMixedExpressions2() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a == b) - { - [||]if (b && c || d) + """); + + [Fact] + public Task MergedWithAndExpressions() + => TestInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b, bool c, bool d) + { + if (a && b) + { + [||]if (c && d) + { + } + } + } } - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a == b && (b && c || d)) - { - } - } -}"); - } - - [Fact] - public async Task NotMergedWithNestedIfInsideWhileLoop() - { - // Do not consider the while loop to be a simple block (as might be suggested by some language-agnostic helpers). - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - while (true) - [||]if (b) + """, + """ + class C + { + void M(bool a, bool b, bool c, bool d) { + if (a && b && c && d) + { + } } - } -}"); - } + } + """); [Fact] - public async Task NotMergedWithNestedIfInsideBlockInsideUsingStatement() - { - // Do not consider the using statement to be a simple block (as might be suggested by some language-agnostic helpers). - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - using (null) + public Task MergedWithOrExpressionParenthesized1() + => TestInRegularAndScriptAsync( + """ + class C { - [||]if (b) + void M(bool a, bool b, bool c, bool d) { + if (a || b) + { + [||]if (c && d) + { + } + } } } - } -}"); - } - - [Fact] - public async Task NotMergedWithNestedIfInsideUsingStatementInsideBlock() - { - // Do not consider the using statement to be a simple block (as might be suggested by some language-agnostic helpers). - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - using (null) - [||]if (b) + """, + """ + class C + { + void M(bool a, bool b, bool c, bool d) { + if ((a || b) && c && d) + { + } } - } - } -}"); - } + } + """); [Fact] - public async Task MergedWithNestedIfInsideNestedBlockStatementInsideBlock() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { + public Task MergedWithOrExpressionParenthesized2() + => TestInRegularAndScriptAsync( + """ + class C { - [||]if (b) + void M(bool a, bool b, bool c, bool d) { - System.Console.WriteLine(a && b); + if (a && b) + { + [||]if (c || d) + { + } + } } } - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - { - System.Console.WriteLine(a && b); - } - } -}"); - } - - [Fact] - public async Task MergedWithNestedIfInsideNestedBlockStatementWithoutBlock() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { + """, + """ + class C { - [||]if (b) - System.Console.WriteLine(a && b); + void M(bool a, bool b, bool c, bool d) + { + if (a && b && (c || d)) + { + } + } } - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - System.Console.WriteLine(a && b); - } -}"); - } - - [Fact] - public async Task MergedWithNestedIfInsideBlockStatementInsideBlock() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) + """); + + [Fact] + public Task MergedWithBitwiseOrExpressionNotParenthesized1() + => TestInRegularAndScriptAsync( + """ + class C { - System.Console.WriteLine(a && b); + void M(bool a, bool b, bool c, bool d) + { + if (a | b) + { + [||]if (c && d) + { + } + } + } } - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - { - System.Console.WriteLine(a && b); - } - } -}"); - } - - [Fact] - public async Task MergedWithNestedIfInsideBlockStatementWithoutBlock() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - System.Console.WriteLine(a && b); - } -}"); - } - - [Fact] - public async Task MergedWithNestedIfWithoutBlockStatementInsideBlock() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - [||]if (b) + """, + """ + class C { - System.Console.WriteLine(a && b); + void M(bool a, bool b, bool c, bool d) + { + if (a | b && c && d) + { + } + } } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - { - System.Console.WriteLine(a && b); - } - } -}"); - } - - [Fact] - public async Task MergedWithNestedIfWithoutBlockStatementWithoutBlock() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - [||]if (b) - System.Console.WriteLine(a && b); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - System.Console.WriteLine(a && b); - } -}"); - } - - [Fact] - public async Task NotMergedWithUnmatchingElseClauseOnNestedIf() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(); - } - } -}"); - } - - [Fact] - public async Task NotMergedWithUnmatchingElseIfClauseOnNestedIf() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else if (a) - System.Console.WriteLine(a); - } - } -}"); - } - - [Fact] - public async Task NotMergedWithUnmatchingElseIfElseClausesOnNestedIf() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else if (a) - System.Console.WriteLine(a); - else - System.Console.WriteLine(); - } - } -}"); - } - - [Fact] - public async Task NotMergedWithUnmatchingElseClauseOnOuterIf() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - } - else - System.Console.WriteLine(); - } -}"); - } - - [Fact] - public async Task NotMergedWithUnmatchingElseIfClauseOnOuterIf() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - } - else if (a) - System.Console.WriteLine(a); - } -}"); - } - - [Fact] - public async Task NotMergedWithUnmatchingElseIfElseClausesOnOuterIf() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - } - else if (a) - System.Console.WriteLine(a); - else - System.Console.WriteLine(); - } -}"); - } + """); [Fact] - public async Task NotMergedWithUnmatchingElseIfElseClauses1() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else if (a) - System.Console.WriteLine(); - } - else - System.Console.WriteLine(); - } -}"); - } + public Task MergedWithBitwiseOrExpressionNotParenthesized2() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a && b) + { + [||]if (c | d) + { + } + } + } + } + """, + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a && b && c | d) + { + } + } + } + """); [Fact] - public async Task NotMergedWithUnmatchingElseIfElseClauses2() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(); - } - else if (a) - System.Console.WriteLine(); - } -}"); - } + public Task MergedWithMixedExpressions1() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a || b && c) + { + [||]if (c == d) + { + } + } + } + } + """, + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if ((a || b && c) && c == d) + { + } + } + } + """); [Fact] - public async Task NotMergedWithUnmatchingElseIfClauses1() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else if (a) - System.Console.WriteLine(); - } - else if (b) - System.Console.WriteLine(); - } -}"); - } + public Task MergedWithMixedExpressions2() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a == b) + { + [||]if (b && c || d) + { + } + } + } + } + """, + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a == b && (b && c || d)) + { + } + } + } + """); [Fact] - public async Task NotMergedWithUnmatchingElseIfClauses2() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else if (a) - System.Console.WriteLine(a); - } - else if (a) - System.Console.WriteLine(b); - } -}"); - } - - [Fact] - public async Task NotMergedWithUnmatchingElseIfClauses3() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else if (a) + public Task NotMergedWithNestedIfInsideWhileLoop() + => TestMissingInRegularAndScriptAsync( + """ + class C { - System.Console.WriteLine(a); + void M(bool a, bool b) + { + if (a) + while (true) + [||]if (b) + { + } + } } - } - else if (a) - { - System.Console.WriteLine(b); - } - } -}"); - } + """); [Fact] - public async Task NotMergedWithUnmatchingElseIfClauses4() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else if (a) + public Task NotMergedWithNestedIfInsideBlockInsideUsingStatement() + => TestMissingInRegularAndScriptAsync( + """ + class C { - System.Console.WriteLine(a); + void M(bool a, bool b) + { + if (a) + using (null) + { + [||]if (b) + { + } + } + } } - } - else if (a) - System.Console.WriteLine(b); - } -}"); - } + """); [Fact] - public async Task NotMergedWithUnmatchingElseClauses1() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else + public Task NotMergedWithNestedIfInsideUsingStatementInsideBlock() + => TestMissingInRegularAndScriptAsync( + """ + class C { - System.Console.WriteLine(a); + void M(bool a, bool b) + { + if (a) + { + using (null) + [||]if (b) + { + } + } + } } - } - else - { - System.Console.WriteLine(b); - } - } -}"); - } + """); [Fact] - public async Task NotMergedWithUnmatchingElseClauses2() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); - } - else - System.Console.WriteLine(b); - } -}"); - } - - [Fact] - public async Task NotMergedWithUnmatchingElseClauses3() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else + public Task MergedWithNestedIfInsideNestedBlockStatementInsideBlock() + => TestInRegularAndScriptAsync( + """ + class C { - System.Console.WriteLine(a); + void M(bool a, bool b) + { + if (a) + { + { + [||]if (b) + { + System.Console.WriteLine(a && b); + } + } + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a && b) + { + System.Console.WriteLine(a && b); + } + } } - } - else - System.Console.WriteLine(b); - } -}"); - } + """); [Fact] - public async Task NotMergedWithUnmatchingElseClauses4() - { - // Do not consider the using statement to be a simple block (as might be suggested by some language-agnostic helpers). - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else + public Task MergedWithNestedIfInsideNestedBlockStatementWithoutBlock() + => TestInRegularAndScriptAsync( + """ + class C { - System.Console.WriteLine(a); + void M(bool a, bool b) + { + if (a) + { + { + [||]if (b) + System.Console.WriteLine(a && b); + } + } + } } - } - else - using (null) - System.Console.WriteLine(a); - } -}"); - } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a && b) + System.Console.WriteLine(a && b); + } + } + """); [Fact] - public async Task NotMergedIntoElseIfWithUnmatchingElseClauses1() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - System.Console.WriteLine(); - else if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else + public Task MergedWithNestedIfInsideBlockStatementInsideBlock() + => TestInRegularAndScriptAsync( + """ + class C { - System.Console.WriteLine(a); + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + { + System.Console.WriteLine(a && b); + } + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a && b) + { + System.Console.WriteLine(a && b); + } + } } - } - else - { - System.Console.WriteLine(b); - } - } -}"); - } + """); [Fact] - public async Task NotMergedIntoElseIfWithUnmatchingElseClauses2() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - System.Console.WriteLine(); - else if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); - } - else - System.Console.WriteLine(b); - } -}"); - } - - [Fact] - public async Task NotMergedIntoElseIfWithUnmatchingElseClauses3() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - System.Console.WriteLine(); - else if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else + public Task MergedWithNestedIfInsideBlockStatementWithoutBlock() + => TestInRegularAndScriptAsync( + """ + class C { - System.Console.WriteLine(a); + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + } + } } - } - else - System.Console.WriteLine(b); - } -}"); - } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a && b) + System.Console.WriteLine(a && b); + } + } + """); [Fact] - public async Task NotMergedIntoElseIfWithUnmatchingElseClauses4() - { - // Do not consider the using statement to be a simple block (as might be suggested by some language-agnostic helpers). - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - System.Console.WriteLine(); - else if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else + public Task MergedWithNestedIfWithoutBlockStatementInsideBlock() + => TestInRegularAndScriptAsync( + """ + class C { - System.Console.WriteLine(a); + void M(bool a, bool b) + { + if (a) + [||]if (b) + { + System.Console.WriteLine(a && b); + } + } } - } - else - using (null) - System.Console.WriteLine(a); - } -}"); - } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a && b) + { + System.Console.WriteLine(a && b); + } + } + } + """); [Fact] - public async Task MergedWithMatchingElseClauses1() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); - } - else - System.Console.WriteLine(a); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); - } -}"); - } - - [Fact] - public async Task MergedWithMatchingElseClauses2() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else + public Task MergedWithNestedIfWithoutBlockStatementWithoutBlock() + => TestInRegularAndScriptAsync( + """ + class C { - System.Console.WriteLine(a); + void M(bool a, bool b) + { + if (a) + [||]if (b) + System.Console.WriteLine(a && b); + } } - } - else - { - System.Console.WriteLine(a); - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - System.Console.WriteLine(a && b); - else - { - System.Console.WriteLine(a); - } - } -}"); - } - - [Fact] - public async Task MergedWithMatchingElseIfClauses() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else if (a) - System.Console.WriteLine(a); - } - else if (a) - System.Console.WriteLine(a); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - System.Console.WriteLine(a && b); - else if (a) - System.Console.WriteLine(a); - } -}"); - } - - [Fact] - public async Task MergedWithMatchingElseIfElseClauses() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else if (a) - System.Console.WriteLine(a); - else - System.Console.WriteLine(a); - } - else if (a) - System.Console.WriteLine(a); - else - System.Console.WriteLine(a); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - System.Console.WriteLine(a && b); - else if (a) - System.Console.WriteLine(a); - else - System.Console.WriteLine(a); - } -}"); - } - - [Fact] - public async Task MergedWithMatchingElseClausesWithDifferenceInBlocks1() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else + """, + """ + class C { - System.Console.WriteLine(a); + void M(bool a, bool b) + { + if (a && b) + System.Console.WriteLine(a && b); + } } - } - else - System.Console.WriteLine(a); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); - } -}"); - } - - [Fact] - public async Task MergedWithMatchingElseClausesWithDifferenceInBlocks2() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); - } - else - { - System.Console.WriteLine(a); - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - System.Console.WriteLine(a && b); - else - { - System.Console.WriteLine(a); - } - } -}"); - } - - [Fact] - public async Task MergedWithMatchingElseClausesWithDifferenceInBlocks3() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else + """); + + [Fact] + public Task NotMergedWithUnmatchingElseClauseOnNestedIf() + => TestMissingInRegularAndScriptAsync( + """ + class C { - System.Console.WriteLine(a); + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(); + } + } } - } - else - { + """); + + [Fact] + public Task NotMergedWithUnmatchingElseIfClauseOnNestedIf() + => TestMissingInRegularAndScriptAsync( + """ + class C { - System.Console.WriteLine(a); + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else if (a) + System.Console.WriteLine(a); + } + } } - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - System.Console.WriteLine(a && b); - else - { + """); + + [Fact] + public Task NotMergedWithUnmatchingElseIfElseClausesOnNestedIf() + => TestMissingInRegularAndScriptAsync( + """ + class C { - System.Console.WriteLine(a); + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else if (a) + System.Console.WriteLine(a); + else + System.Console.WriteLine(); + } + } } - } - } -}"); - } + """); [Fact] - public async Task MergedWithMatchingElseIfClausesWithDifferenceInBlocks() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else if (a) + public Task NotMergedWithUnmatchingElseClauseOnOuterIf() + => TestMissingInRegularAndScriptAsync( + """ + class C { - System.Console.WriteLine(a); + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + } + else + System.Console.WriteLine(); + } } - } - else if (a) - System.Console.WriteLine(a); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - System.Console.WriteLine(a && b); - else if (a) - System.Console.WriteLine(a); - } -}"); - } - - [Fact] - public async Task MergedWithMatchingElseIfElseClausesWithDifferenceInBlocks() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else if (a) + """); + + [Fact] + public Task NotMergedWithUnmatchingElseIfClauseOnOuterIf() + => TestMissingInRegularAndScriptAsync( + """ + class C { - System.Console.WriteLine(a); + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + } + else if (a) + System.Console.WriteLine(a); + } } - else - System.Console.WriteLine(); - } - else if (a) - System.Console.WriteLine(a); - else - { - System.Console.WriteLine(); - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - System.Console.WriteLine(a && b); - else if (a) - System.Console.WriteLine(a); - else - { - System.Console.WriteLine(); - } - } -}"); - } + """); [Fact] - public async Task MergedIntoElseIfWithMatchingElseClauses1() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - System.Console.WriteLine(); - else if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); - } - else - System.Console.WriteLine(a); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - System.Console.WriteLine(); - else if (a && b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); - } -}"); - } - - [Fact] - public async Task MergedIntoElseIfWithMatchingElseClauses2() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - System.Console.WriteLine(); - else if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else + public Task NotMergedWithUnmatchingElseIfElseClausesOnOuterIf() + => TestMissingInRegularAndScriptAsync( + """ + class C { - System.Console.WriteLine(a); + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + } + else if (a) + System.Console.WriteLine(a); + else + System.Console.WriteLine(); + } } - } - else - { - System.Console.WriteLine(a); - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - System.Console.WriteLine(); - else if (a && b) - System.Console.WriteLine(a && b); - else - { - System.Console.WriteLine(a); - } - } -}"); - } - - [Fact] - public async Task NotMergedWithUnmatchingElseClauseOnNestedIfWithoutBlock() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - [||]if (b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(); - } -}"); - } + """); [Fact] - public async Task NotMergedWithUnmatchingElseClausesForNestedIfWithoutBlock() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - [||]if (b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); - else - System.Console.WriteLine(b); - } -}"); - } + public Task NotMergedWithUnmatchingElseIfElseClauses1() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else if (a) + System.Console.WriteLine(); + } + else + System.Console.WriteLine(); + } + } + """); [Fact] - public async Task MergedWithMatchingElseClausesForNestedIfWithoutBlock() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - [||]if (b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); - else - System.Console.WriteLine(a); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); - } -}"); - } - - [Fact] - public async Task MergedWithSingleLineFormatting() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) System.Console.WriteLine(); - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - System.Console.WriteLine(); - } -}"); - } + public Task NotMergedWithUnmatchingElseIfElseClauses2() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(); + } + else if (a) + System.Console.WriteLine(); + } + } + """); [Fact] - public async Task NotMergedWithExtraUnmatchingStatementBelowNestedIf() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); + public Task NotMergedWithUnmatchingElseIfClauses1() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else if (a) + System.Console.WriteLine(); + } + else if (b) + System.Console.WriteLine(); + } + } + """); - System.Console.WriteLine(b); - } - else - System.Console.WriteLine(a); - } -}"); - } + [Fact] + public Task NotMergedWithUnmatchingElseIfClauses2() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else if (a) + System.Console.WriteLine(a); + } + else if (a) + System.Console.WriteLine(b); + } + } + """); [Fact] - public async Task MergedWithExtraUnmatchingStatementBelowOuterIf() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); - } - else - System.Console.WriteLine(a); - - System.Console.WriteLine(b); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); - - System.Console.WriteLine(b); - } -}"); - } - - [Fact] - public async Task NotMergedWithExtraUnmatchingStatementsIfControlFlowContinues() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); + public Task NotMergedWithUnmatchingElseIfClauses3() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else if (a) + { + System.Console.WriteLine(a); + } + } + else if (a) + { + System.Console.WriteLine(b); + } + } + } + """); + + [Fact] + public Task NotMergedWithUnmatchingElseIfClauses4() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else if (a) + { + System.Console.WriteLine(a); + } + } + else if (a) + System.Console.WriteLine(b); + } + } + """); + + [Fact] + public Task NotMergedWithUnmatchingElseClauses1() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + { + System.Console.WriteLine(a); + } + } + else + { + System.Console.WriteLine(b); + } + } + } + """); + + [Fact] + public Task NotMergedWithUnmatchingElseClauses2() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + } + else + System.Console.WriteLine(b); + } + } + """); + + [Fact] + public Task NotMergedWithUnmatchingElseClauses3() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + { + System.Console.WriteLine(a); + } + } + else + System.Console.WriteLine(b); + } + } + """); + + [Fact] + public Task NotMergedWithUnmatchingElseClauses4() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + { + System.Console.WriteLine(a); + } + } + else + using (null) + System.Console.WriteLine(a); + } + } + """); + + [Fact] + public Task NotMergedIntoElseIfWithUnmatchingElseClauses1() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + System.Console.WriteLine(); + else if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + { + System.Console.WriteLine(a); + } + } + else + { + System.Console.WriteLine(b); + } + } + } + """); + + [Fact] + public Task NotMergedIntoElseIfWithUnmatchingElseClauses2() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + System.Console.WriteLine(); + else if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + } + else + System.Console.WriteLine(b); + } + } + """); + + [Fact] + public Task NotMergedIntoElseIfWithUnmatchingElseClauses3() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + System.Console.WriteLine(); + else if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + { + System.Console.WriteLine(a); + } + } + else + System.Console.WriteLine(b); + } + } + """); + + [Fact] + public Task NotMergedIntoElseIfWithUnmatchingElseClauses4() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + System.Console.WriteLine(); + else if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + { + System.Console.WriteLine(a); + } + } + else + using (null) + System.Console.WriteLine(a); + } + } + """); + + [Fact] + public Task MergedWithMatchingElseClauses1() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + } + else + System.Console.WriteLine(a); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a && b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + } + } + """); + + [Fact] + public Task MergedWithMatchingElseClauses2() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + { + System.Console.WriteLine(a); + } + } + else + { + System.Console.WriteLine(a); + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a && b) + System.Console.WriteLine(a && b); + else + { + System.Console.WriteLine(a); + } + } + } + """); + + [Fact] + public Task MergedWithMatchingElseIfClauses() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else if (a) + System.Console.WriteLine(a); + } + else if (a) + System.Console.WriteLine(a); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a && b) + System.Console.WriteLine(a && b); + else if (a) + System.Console.WriteLine(a); + } + } + """); + + [Fact] + public Task MergedWithMatchingElseIfElseClauses() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else if (a) + System.Console.WriteLine(a); + else + System.Console.WriteLine(a); + } + else if (a) + System.Console.WriteLine(a); + else + System.Console.WriteLine(a); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a && b) + System.Console.WriteLine(a && b); + else if (a) + System.Console.WriteLine(a); + else + System.Console.WriteLine(a); + } + } + """); + + [Fact] + public Task MergedWithMatchingElseClausesWithDifferenceInBlocks1() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + { + System.Console.WriteLine(a); + } + } + else + System.Console.WriteLine(a); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a && b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + } + } + """); + + [Fact] + public Task MergedWithMatchingElseClausesWithDifferenceInBlocks2() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + } + else + { + System.Console.WriteLine(a); + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a && b) + System.Console.WriteLine(a && b); + else + { + System.Console.WriteLine(a); + } + } + } + """); - System.Console.WriteLine(a); - System.Console.WriteLine(b); - } - else - System.Console.WriteLine(a); + [Fact] + public Task MergedWithMatchingElseClausesWithDifferenceInBlocks3() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + { + System.Console.WriteLine(a); + } + } + else + { + { + System.Console.WriteLine(a); + } + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a && b) + System.Console.WriteLine(a && b); + else + { + { + System.Console.WriteLine(a); + } + } + } + } + """); - System.Console.WriteLine(b); - System.Console.WriteLine(a); - } -}"); - } + [Fact] + public Task MergedWithMatchingElseIfClausesWithDifferenceInBlocks() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else if (a) + { + System.Console.WriteLine(a); + } + } + else if (a) + System.Console.WriteLine(a); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a && b) + System.Console.WriteLine(a && b); + else if (a) + System.Console.WriteLine(a); + } + } + """); + + [Fact] + public Task MergedWithMatchingElseIfElseClausesWithDifferenceInBlocks() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else if (a) + { + System.Console.WriteLine(a); + } + else + System.Console.WriteLine(); + } + else if (a) + System.Console.WriteLine(a); + else + { + System.Console.WriteLine(); + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a && b) + System.Console.WriteLine(a && b); + else if (a) + System.Console.WriteLine(a); + else + { + System.Console.WriteLine(); + } + } + } + """); + + [Fact] + public Task MergedIntoElseIfWithMatchingElseClauses1() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + System.Console.WriteLine(); + else if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + } + else + System.Console.WriteLine(a); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + System.Console.WriteLine(); + else if (a && b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + } + } + """); + + [Fact] + public Task MergedIntoElseIfWithMatchingElseClauses2() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + System.Console.WriteLine(); + else if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + { + System.Console.WriteLine(a); + } + } + else + { + System.Console.WriteLine(a); + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + System.Console.WriteLine(); + else if (a && b) + System.Console.WriteLine(a && b); + else + { + System.Console.WriteLine(a); + } + } + } + """); + + [Fact] + public Task NotMergedWithUnmatchingElseClauseOnNestedIfWithoutBlock() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(); + } + } + """); + + [Fact] + public Task NotMergedWithUnmatchingElseClausesForNestedIfWithoutBlock() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + else + System.Console.WriteLine(b); + } + } + """); + + [Fact] + public Task MergedWithMatchingElseClausesForNestedIfWithoutBlock() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + else + System.Console.WriteLine(a); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a && b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + } + } + """); + + [Fact] + public Task MergedWithSingleLineFormatting() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) System.Console.WriteLine(); + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a && b) + System.Console.WriteLine(); + } + } + """); [Fact] - public async Task NotMergedWithExtraUnmatchingStatementsIfControlFlowQuits() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); - - throw new System.Exception(); - } - else - System.Console.WriteLine(a); - - return; - } -}"); - } + public Task NotMergedWithExtraUnmatchingStatementBelowNestedIf() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + + System.Console.WriteLine(b); + } + else + System.Console.WriteLine(a); + } + } + """); [Fact] - public async Task NotMergedWithExtraPrecedingMatchingStatementsIfControlFlowQuits() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - return; - - if (a) - { - return; - - [||]if (b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); - } - else - System.Console.WriteLine(a); - } -}"); - } - - [Fact] - public async Task NotMergedWithExtraMatchingStatementsIfControlFlowContinues1() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); - - System.Console.WriteLine(a); - System.Console.WriteLine(b); - } - else - System.Console.WriteLine(a); + public Task MergedWithExtraUnmatchingStatementBelowOuterIf() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + } + else + System.Console.WriteLine(a); + + System.Console.WriteLine(b); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a && b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); - System.Console.WriteLine(a); - System.Console.WriteLine(b); - } -}"); - } + System.Console.WriteLine(b); + } + } + """); [Fact] - public async Task NotMergedWithExtraMatchingStatementsIfControlFlowContinues2() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); - - if (a) - return; - } - else - System.Console.WriteLine(a); - - if (a) - return; - } -}"); - } - - [Fact] - public async Task NotMergedWithExtraMatchingStatementsIfControlFlowContinues3() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - while (a != b) - { - if (a) + public Task NotMergedWithExtraUnmatchingStatementsIfControlFlowContinues() + => TestMissingInRegularAndScriptAsync( + """ + class C { - [||]if (b) - System.Console.WriteLine(a && b); - else + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + + System.Console.WriteLine(a); + System.Console.WriteLine(b); + } + else + System.Console.WriteLine(a); + + System.Console.WriteLine(b); System.Console.WriteLine(a); + } + } + """); - switch (a) + [Fact] + public Task NotMergedWithExtraUnmatchingStatementsIfControlFlowQuits() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) { - default: - break; + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + + throw new System.Exception(); + } + else + System.Console.WriteLine(a); + + return; } } - else - System.Console.WriteLine(a); + """); - switch (a) + [Fact] + public Task NotMergedWithExtraPrecedingMatchingStatementsIfControlFlowQuits() + => TestMissingInRegularAndScriptAsync( + """ + class C { - default: - break; + void M(bool a, bool b) + { + return; + + if (a) + { + return; + + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + } + else + System.Console.WriteLine(a); + } } - } - } -}"); - } + """); [Fact] - public async Task NotMergedWithExtraMatchingStatementsIfControlFlowContinues4() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - while (a != b) - { - if (a) + public Task NotMergedWithExtraMatchingStatementsIfControlFlowContinues1() + => TestMissingInRegularAndScriptAsync( + """ + class C { - [||]if (b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + + System.Console.WriteLine(a); + System.Console.WriteLine(b); + } + else + System.Console.WriteLine(a); - while (a != b) - continue; + System.Console.WriteLine(a); + System.Console.WriteLine(b); + } } - else - System.Console.WriteLine(a); + """); - while (a != b) - continue; - } - } -}"); - } + [Fact] + public Task NotMergedWithExtraMatchingStatementsIfControlFlowContinues2() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + + if (a) + return; + } + else + System.Console.WriteLine(a); + + if (a) + return; + } + } + """); [Fact] - public async Task NotMergedIntoElseIfWithExtraMatchingStatementsIfControlFlowContinues() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a == b) - { - } - else if (a || b) - { - } - else if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); + public Task NotMergedWithExtraMatchingStatementsIfControlFlowContinues3() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + while (a != b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + + switch (a) + { + default: + break; + } + } + else + System.Console.WriteLine(a); + + switch (a) + { + default: + break; + } + } + } + } + """); - System.Console.WriteLine(); - } - else - System.Console.WriteLine(a); + [Fact] + public Task NotMergedWithExtraMatchingStatementsIfControlFlowContinues4() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + while (a != b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + + while (a != b) + continue; + } + else + System.Console.WriteLine(a); + + while (a != b) + continue; + } + } + } + """); - System.Console.WriteLine(); - } -}"); - } + [Fact] + public Task NotMergedIntoElseIfWithExtraMatchingStatementsIfControlFlowContinues() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a == b) + { + } + else if (a || b) + { + } + else if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + + System.Console.WriteLine(); + } + else + System.Console.WriteLine(a); + + System.Console.WriteLine(); + } + } + """); [Fact] - public async Task MergedWithExtraMatchingStatementsIfControlFlowQuits1() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); + public Task MergedWithExtraMatchingStatementsIfControlFlowQuits1() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + + return; + } + else + System.Console.WriteLine(a); + + return; + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a && b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); - return; - } - else - System.Console.WriteLine(a); + return; + } + } + """); - return; - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); - - return; - } -}"); - } - - [Fact] - public async Task MergedWithExtraMatchingStatementsIfControlFlowQuits2() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); + [Fact] + public Task MergedWithExtraMatchingStatementsIfControlFlowQuits2() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + + System.Console.WriteLine(a); + throw new System.Exception(); + } + else + System.Console.WriteLine(a); - System.Console.WriteLine(a); - throw new System.Exception(); - } - else - System.Console.WriteLine(a); - - System.Console.WriteLine(a); - throw new System.Exception(); - System.Console.WriteLine(b); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); - - System.Console.WriteLine(a); - throw new System.Exception(); - System.Console.WriteLine(b); - } -}"); - } - - [Fact] - public async Task MergedWithExtraMatchingStatementsIfControlFlowQuits3() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - while (a != b) - { - if (a) + System.Console.WriteLine(a); + throw new System.Exception(); + System.Console.WriteLine(b); + } + } + """, + """ + class C { - [||]if (b) - System.Console.WriteLine(a && b); - else + void M(bool a, bool b) + { + if (a && b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + System.Console.WriteLine(a); + throw new System.Exception(); + System.Console.WriteLine(b); + } + } + """); - switch (a) + [Fact] + public Task MergedWithExtraMatchingStatementsIfControlFlowQuits3() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) { - default: - continue; + while (a != b) + { + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + + switch (a) + { + default: + continue; + } + } + else + System.Console.WriteLine(a); + + switch (a) + { + default: + continue; + } + } } } - else - System.Console.WriteLine(a); - - switch (a) + """, + """ + class C { - default: - continue; + void M(bool a, bool b) + { + while (a != b) + { + if (a && b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + + switch (a) + { + default: + continue; + } + } + } } - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - while (a != b) - { - if (a && b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); + """); - switch (a) + [Fact] + public Task MergedWithExtraMatchingStatementsIfControlFlowQuits4() + => TestInRegularAndScriptAsync( + """ + class C { - default: - continue; + void M(bool a, bool b) + { + while (a != b) + { + System.Console.WriteLine(); + + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + + if (a) + continue; + else + break; + } + else + System.Console.WriteLine(a); + + if (a) + continue; + else + break; + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + while (a != b) + { + System.Console.WriteLine(); + + if (a && b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + + if (a) + continue; + else + break; + } + } } - } - } -}"); - } + """); [Fact] - public async Task MergedWithExtraMatchingStatementsIfControlFlowQuits4() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - while (a != b) - { - System.Console.WriteLine(); - - if (a) + public Task MergedWithExtraMatchingStatementsIfControlFlowQuits5() + => TestInRegularAndScriptAsync( + """ + class C { - [||]if (b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); - - if (a) - continue; - else - break; + void M(bool a, bool b) + { + while (a != b) + { + System.Console.WriteLine(); + + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + + switch (a) + { + default: + continue; + } + } + else + System.Console.WriteLine(a); + + switch (a) + { + default: + continue; + } + } + } } - else - System.Console.WriteLine(a); - - if (a) - continue; - else - break; - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - while (a != b) - { - System.Console.WriteLine(); - - if (a && b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); - - if (a) - continue; - else - break; - } - } -}"); - } + """, + """ + class C + { + void M(bool a, bool b) + { + while (a != b) + { + System.Console.WriteLine(); + + if (a && b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + + switch (a) + { + default: + continue; + } + } + } + } + """); [Fact] - public async Task MergedWithExtraMatchingStatementsIfControlFlowQuits5() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - while (a != b) - { + public Task MergedWithExtraMatchingStatementsIfControlFlowQuits6() + => TestInRegularAndScriptAsync( + """ + bool a = bool.Parse(""); + bool b = bool.Parse(""); + + start: System.Console.WriteLine(); if (a) @@ -2153,7 +2277,7 @@ void M(bool a, bool b) switch (a) { default: - continue; + goto start; } } else @@ -2162,17 +2286,14 @@ void M(bool a, bool b) switch (a) { default: - continue; + goto start; } - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - while (a != b) - { + """, + """ + bool a = bool.Parse(""); + bool b = bool.Parse(""); + + start: System.Console.WriteLine(); if (a && b) @@ -2183,256 +2304,207 @@ void M(bool a, bool b) switch (a) { default: - continue; + goto start; } - } - } -}"); - } + """); [Fact] - public async Task MergedWithExtraMatchingStatementsIfControlFlowQuits6() - { - await TestInRegularAndScriptAsync( -@"bool a = bool.Parse(""""); -bool b = bool.Parse(""""); - -start: -System.Console.WriteLine(); + public Task MergedWithExtraMatchingStatementsIfControlFlowQuitsInSwitchSection() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + switch (a) + { + case true: + System.Console.WriteLine(); -if (a) -{ - [||]if (b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); - - switch (a) - { - default: - goto start; - } -} -else - System.Console.WriteLine(a); + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); -switch (a) -{ - default: - goto start; -} -", -@"bool a = bool.Parse(""""); -bool b = bool.Parse(""""); + break; + } -start: -System.Console.WriteLine(); + break; + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + switch (a) + { + case true: + System.Console.WriteLine(); -if (a && b) - System.Console.WriteLine(a && b); -else - System.Console.WriteLine(a); + if (a && b) + System.Console.WriteLine(a && b); -switch (a) -{ - default: - goto start; -} -"); - } + break; + } + } + } + """); [Fact] - public async Task MergedWithExtraMatchingStatementsIfControlFlowQuitsInSwitchSection() - { - // Switch sections are interesting in that they are blocks of statements that aren't BlockSyntax. - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - switch (a) - { - case true: - System.Console.WriteLine(); - - if (a) + public Task MergedIntoElseIfWithExtraMatchingStatementsIfControlFlowQuits() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) { - [||]if (b) + if (a == b) + { + } + else if (a || b) + { + } + else if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); + + return; + } + else + System.Console.WriteLine(a); + + return; + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a == b) + { + } + else if (a || b) + { + } + else if (a && b) System.Console.WriteLine(a && b); + else + System.Console.WriteLine(a); - break; + return; } - - break; - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - switch (a) - { - case true: - System.Console.WriteLine(); - - if (a && b) - System.Console.WriteLine(a && b); - - break; - } - } -}"); - } + } + """); [Fact] - public async Task MergedIntoElseIfWithExtraMatchingStatementsIfControlFlowQuits() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a == b) - { - } - else if (a || b) - { - } - else if (a) - { - [||]if (b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); - - return; - } - else - System.Console.WriteLine(a); - - return; - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a == b) - { - } - else if (a || b) - { - } - else if (a && b) - System.Console.WriteLine(a && b); - else - System.Console.WriteLine(a); - - return; - } -}"); - } - - [Fact] - public async Task NotMergedWithExtraMatchingStatementsInsideExtraBlockIfControlFlowQuits() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { + public Task NotMergedWithExtraMatchingStatementsInsideExtraBlockIfControlFlowQuits() + => TestMissingInRegularAndScriptAsync( + """ + class C { - [||]if (b) - System.Console.WriteLine(a && b); - } + void M(bool a, bool b) + { + if (a) + { + { + [||]if (b) + System.Console.WriteLine(a && b); + } - return; - } + return; + } - return; - } -}"); - } + return; + } + } + """); [Fact] - public async Task MergedWithExtraMatchingStatementsInsideInnermostBlockIfControlFlowQuits() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - { + public Task MergedWithExtraMatchingStatementsInsideInnermostBlockIfControlFlowQuits() + => TestInRegularAndScriptAsync( + """ + class C { - [||]if (b) - System.Console.WriteLine(a && b); + void M(bool a, bool b) + { + if (a) + { + { + [||]if (b) + System.Console.WriteLine(a && b); - return; - } - } + return; + } + } - return; - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - System.Console.WriteLine(a && b); + return; + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a && b) + System.Console.WriteLine(a && b); - return; - } -}"); - } + return; + } + } + """); [Fact] - public async Task NotMergedWithExtraMatchingStatementInOuterScopeOfEmbeddedStatementIfControlFlowQuits() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - using (null) - if (a) + public Task NotMergedWithExtraMatchingStatementInOuterScopeOfEmbeddedStatementIfControlFlowQuits() + => TestMissingInRegularAndScriptAsync( + """ + class C { - [||]if (b) - System.Console.WriteLine(a && b); + void M(bool a, bool b) + { + using (null) + if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); - return; - } + return; + } - return; - } -}"); - } + return; + } + } + """); [Fact] - public async Task NotMergedIntoElseIfWithExtraMatchingStatementInOuterScopeOfEmbeddedStatementIfControlFlowQuits() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - using (null) - if (a || b) - System.Console.WriteLine(a); - else if (a) + public Task NotMergedIntoElseIfWithExtraMatchingStatementInOuterScopeOfEmbeddedStatementIfControlFlowQuits() + => TestMissingInRegularAndScriptAsync( + """ + class C { - [||]if (b) - System.Console.WriteLine(a && b); - - return; + void M(bool a, bool b) + { + using (null) + if (a || b) + System.Console.WriteLine(a); + else if (a) + { + [||]if (b) + System.Console.WriteLine(a && b); + + return; + } + + return; + } } - - return; - } -}"); - } + """); } diff --git a/src/Features/CSharpTest/SplitOrMergeIfStatements/SplitIntoConsecutiveIfStatementsTests.cs b/src/Features/CSharpTest/SplitOrMergeIfStatements/SplitIntoConsecutiveIfStatementsTests.cs index beb72af360633..2f7b881cff256 100644 --- a/src/Features/CSharpTest/SplitOrMergeIfStatements/SplitIntoConsecutiveIfStatementsTests.cs +++ b/src/Features/CSharpTest/SplitOrMergeIfStatements/SplitIntoConsecutiveIfStatementsTests.cs @@ -24,1306 +24,1383 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor [InlineData("a |[||]| b")] [InlineData("a ||[||] b")] [InlineData("a [||||] b")] - public async Task SplitOnOrOperatorSpans(string condition) - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (" + condition + @") - { - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - } - else if (b) - { - } - } -}"); - } + public Task SplitOnOrOperatorSpans(string condition) + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if ( + """ + condition + """ + ) + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + } + else if (b) + { + } + } + } + """); [Theory] [InlineData("a [|||]| b")] [InlineData("a[| |||] b")] [InlineData("a[||] || b")] - public async Task NotSplitOnOrOperatorSpans(string condition) - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (" + condition + @") - { - } - } -}"); - } - - [Fact] - public async Task NotSplitOnIfKeyword() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - [||]if (a || b) - { - } - } -}"); - } - - [Fact] - public async Task NotSplitOnAndOperator() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]&& b) - { - } - } -}"); - } + public Task NotSplitOnOrOperatorSpans(string condition) + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if ( + """ + condition + """ + ) + { + } + } + } + """); [Fact] - public async Task NotSplitOnBitwiseOrOperator() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]| b) - { - } - } -}"); - } + public Task NotSplitOnIfKeyword() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + [||]if (a || b) + { + } + } + } + """); [Fact] - public async Task NotSplitOnOrOperatorOutsideIfStatement() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - var v = a [||]|| b; - } -}"); - } + public Task NotSplitOnAndOperator() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]&& b) + { + } + } + } + """); [Fact] - public async Task NotSplitOnOrOperatorInIfStatementBody() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a || b) - a [||]|| b; - } -}"); - } + public Task NotSplitOnBitwiseOrOperator() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]| b) + { + } + } + } + """); [Fact] - public async Task SplitWithChainedOrExpression1() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a [||]|| b || c || d) - { - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a) - { - } - else if (b || c || d) - { - } - } -}"); - } + public Task NotSplitOnOrOperatorOutsideIfStatement() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + var v = a [||]|| b; + } + } + """); [Fact] - public async Task SplitWithChainedOrExpression2() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a || b [||]|| c || d) - { - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a || b) - { - } - else if (c || d) - { - } - } -}"); - } + public Task NotSplitOnOrOperatorInIfStatementBody() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a || b) + a [||]|| b; + } + } + """); [Fact] - public async Task SplitWithChainedOrExpression3() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a || b || c [||]|| d) - { - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a || b || c) - { - } - else if (d) - { - } - } -}"); - } + public Task SplitWithChainedOrExpression1() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a [||]|| b || c || d) + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a) + { + } + else if (b || c || d) + { + } + } + } + """); [Fact] - public async Task NotSplitInsideParentheses1() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if ((a [||]|| b) || c || d) - { - } - } -}"); - } + public Task SplitWithChainedOrExpression2() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a || b [||]|| c || d) + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a || b) + { + } + else if (c || d) + { + } + } + } + """); [Fact] - public async Task NotSplitInsideParentheses2() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a || b || (c [||]|| d)) - { - } - } -}"); - } + public Task SplitWithChainedOrExpression3() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a || b || c [||]|| d) + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a || b || c) + { + } + else if (d) + { + } + } + } + """); [Fact] - public async Task NotSplitInsideParentheses3() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if ((a || b [||]|| c || d)) - { - } - } -}"); - } + public Task NotSplitInsideParentheses1() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if ((a [||]|| b) || c || d) + { + } + } + } + """); [Fact] - public async Task SplitWithOtherExpressionInsideParentheses1() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a [||]|| (b || c) || d) - { - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a) - { - } - else if ((b || c) || d) - { - } - } -}"); - } + public Task NotSplitInsideParentheses2() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a || b || (c [||]|| d)) + { + } + } + } + """); [Fact] - public async Task SplitWithOtherExpressionInsideParentheses2() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a || (b || c) [||]|| d) - { - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a || (b || c)) - { - } - else if (d) - { - } - } -}"); - } + public Task NotSplitInsideParentheses3() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if ((a || b [||]|| c || d)) + { + } + } + } + """); [Fact] - public async Task SplitWithMixedAndExpression1() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a [||]|| b && c) - { - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a) - { - } - else if (b && c) - { - } - } -}"); - } + public Task SplitWithOtherExpressionInsideParentheses1() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a [||]|| (b || c) || d) + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a) + { + } + else if ((b || c) || d) + { + } + } + } + """); [Fact] - public async Task SplitWithMixedAndExpression2() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a && b [||]|| c) - { - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a && b) - { - } - else if (c) - { - } - } -}"); - } + public Task SplitWithOtherExpressionInsideParentheses2() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a || (b || c) [||]|| d) + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a || (b || c)) + { + } + else if (d) + { + } + } + } + """); [Fact] - public async Task NotSplitWithMixedConditionalExpression1() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a [||]|| b ? c : c) - { - } - } -}"); - } + public Task SplitWithMixedAndExpression1() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c) + { + if (a [||]|| b && c) + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b, bool c) + { + if (a) + { + } + else if (b && c) + { + } + } + } + """); [Fact] - public async Task NotSplitWithMixedConditionalExpression2() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a ? b : b [||]|| c) - { - } - } -}"); - } + public Task SplitWithMixedAndExpression2() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c) + { + if (a && b [||]|| c) + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b, bool c) + { + if (a && b) + { + } + else if (c) + { + } + } + } + """); [Fact] - public async Task SplitWithMixedConditionalExpressionInsideParentheses1() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a [||]|| (b ? c : c)) - { - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a) - { - } - else if ((b ? c : c)) - { - } - } -}"); - } + public Task NotSplitWithMixedConditionalExpression1() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c) + { + if (a [||]|| b ? c : c) + { + } + } + } + """); [Fact] - public async Task SplitWithMixedConditionalExpressionInsideParentheses2() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c) - { - if ((a ? b : b) [||]|| c) - { - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c) - { - if ((a ? b : b)) - { - } - else if (c) - { - } - } -}"); - } + public Task NotSplitWithMixedConditionalExpression2() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c) + { + if (a ? b : b [||]|| c) + { + } + } + } + """); [Fact] - public async Task SplitWithStatementInsideBlock() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]|| b) - { - System.Console.WriteLine(a || b); - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - System.Console.WriteLine(a || b); - } - else if (b) - { - System.Console.WriteLine(a || b); - } - } -}"); - } + public Task SplitWithMixedConditionalExpressionInsideParentheses1() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c) + { + if (a [||]|| (b ? c : c)) + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b, bool c) + { + if (a) + { + } + else if ((b ? c : c)) + { + } + } + } + """); [Fact] - public async Task SplitWithStatementWithoutBlock() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]|| b) - System.Console.WriteLine(a || b); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - System.Console.WriteLine(a || b); - else if (b) - System.Console.WriteLine(a || b); - } -}"); - } + public Task SplitWithMixedConditionalExpressionInsideParentheses2() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c) + { + if ((a ? b : b) [||]|| c) + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b, bool c) + { + if ((a ? b : b)) + { + } + else if (c) + { + } + } + } + """); [Fact] - public async Task SplitWithNestedIfStatement() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]|| b) - if (true) { } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - if (true) { } - } - else if (b) - if (true) { } - } -}"); - } + public Task SplitWithStatementInsideBlock() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]|| b) + { + System.Console.WriteLine(a || b); + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + System.Console.WriteLine(a || b); + } + else if (b) + { + System.Console.WriteLine(a || b); + } + } + } + """); [Fact] - public async Task SplitWithNestedIfStatementInWhileLoop() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]|| b) - while (a) - if (true) - using (null) { } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - while (a) - if (true) - using (null) { } - } - else if (b) - while (a) - if (true) - using (null) { } - } -}"); - } + public Task SplitWithStatementWithoutBlock() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]|| b) + System.Console.WriteLine(a || b); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + System.Console.WriteLine(a || b); + else if (b) + System.Console.WriteLine(a || b); + } + } + """); [Fact] - public async Task SplitWithNestedIfStatementInsideBlockInWhileLoop() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]|| b) - while (a) + public Task SplitWithNestedIfStatement() + => TestInRegularAndScriptAsync( + """ + class C { - if (true) - using (null) { } + void M(bool a, bool b) + { + if (a [||]|| b) + if (true) { } + } } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - while (a) + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + if (true) { } + } + else if (b) + if (true) { } + } + } + """); + + [Fact] + public Task SplitWithNestedIfStatementInWhileLoop() + => TestInRegularAndScriptAsync( + """ + class C { - if (true) - using (null) { } + void M(bool a, bool b) + { + if (a [||]|| b) + while (a) + if (true) + using (null) { } + } } - else if (b) - while (a) + """, + """ + class C { - if (true) - using (null) { } + void M(bool a, bool b) + { + if (a) + { + while (a) + if (true) + using (null) { } + } + else if (b) + while (a) + if (true) + using (null) { } + } } - } -}"); - } + """); [Fact] - public async Task SplitWithNestedIfStatementInsideBlock() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]|| b) - { - if (true) { } - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - if (true) { } - } - else if (b) - { - if (true) { } - } - } -}"); - } + public Task SplitWithNestedIfStatementInsideBlockInWhileLoop() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]|| b) + while (a) + { + if (true) + using (null) { } + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + while (a) + { + if (true) + using (null) { } + } + else if (b) + while (a) + { + if (true) + using (null) { } + } + } + } + """); [Fact] - public async Task SplitWithMissingStatement() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]|| b) - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) -else if (b) - } -}"); - } + public Task SplitWithNestedIfStatementInsideBlock() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]|| b) + { + if (true) { } + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + if (true) { } + } + else if (b) + { + if (true) { } + } + } + } + """); [Fact] - public async Task SplitWithElseStatementInsideBlock() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]|| b) - System.Console.WriteLine(); - else - { - System.Console.WriteLine(a || b); - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - System.Console.WriteLine(); - else if (b) - System.Console.WriteLine(); - else - { - System.Console.WriteLine(a || b); - } - } -}"); - } + public Task SplitWithMissingStatement() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]|| b) + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + else if (b) + } + } + """); [Fact] - public async Task SplitWithElseStatementWithoutBlock() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]|| b) - System.Console.WriteLine(); - else - System.Console.WriteLine(a || b); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - System.Console.WriteLine(); - else if (b) - System.Console.WriteLine(); - else - System.Console.WriteLine(a || b); - } -}"); - } + public Task SplitWithElseStatementInsideBlock() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]|| b) + System.Console.WriteLine(); + else + { + System.Console.WriteLine(a || b); + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + System.Console.WriteLine(); + else if (b) + System.Console.WriteLine(); + else + { + System.Console.WriteLine(a || b); + } + } + } + """); [Fact] - public async Task SplitWithElseNestedIfStatement() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]|| b) - System.Console.WriteLine(); - else if (true) { } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - System.Console.WriteLine(); - else if (b) - System.Console.WriteLine(); - else if (true) { } - } -}"); - } + public Task SplitWithElseStatementWithoutBlock() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]|| b) + System.Console.WriteLine(); + else + System.Console.WriteLine(a || b); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + System.Console.WriteLine(); + else if (b) + System.Console.WriteLine(); + else + System.Console.WriteLine(a || b); + } + } + """); [Fact] - public async Task SplitWithElseIfElse() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]|| b) - System.Console.WriteLine(); - else if (a) - System.Console.WriteLine(a); - else - System.Console.WriteLine(b); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - System.Console.WriteLine(); - else if (b) - System.Console.WriteLine(); - else if (a) - System.Console.WriteLine(a); - else - System.Console.WriteLine(b); - } -}"); - } + public Task SplitWithElseNestedIfStatement() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]|| b) + System.Console.WriteLine(); + else if (true) { } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + System.Console.WriteLine(); + else if (b) + System.Console.WriteLine(); + else if (true) { } + } + } + """); [Fact] - public async Task SplitAsPartOfElseIfElse() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (true) - System.Console.WriteLine(); - else if (a [||]|| b) - System.Console.WriteLine(a); - else - System.Console.WriteLine(b); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (true) - System.Console.WriteLine(); - else if (a) - System.Console.WriteLine(a); - else if (b) - System.Console.WriteLine(a); - else - System.Console.WriteLine(b); - } -}"); - } + public Task SplitWithElseIfElse() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]|| b) + System.Console.WriteLine(); + else if (a) + System.Console.WriteLine(a); + else + System.Console.WriteLine(b); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + System.Console.WriteLine(); + else if (b) + System.Console.WriteLine(); + else if (a) + System.Console.WriteLine(a); + else + System.Console.WriteLine(b); + } + } + """); [Fact] - public async Task SplitWithMissingElseStatement() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]|| b) - System.Console.WriteLine(); - else - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - System.Console.WriteLine(); - else if (b) - System.Console.WriteLine(); - else - } -}"); - } + public Task SplitAsPartOfElseIfElse() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (true) + System.Console.WriteLine(); + else if (a [||]|| b) + System.Console.WriteLine(a); + else + System.Console.WriteLine(b); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (true) + System.Console.WriteLine(); + else if (a) + System.Console.WriteLine(a); + else if (b) + System.Console.WriteLine(a); + else + System.Console.WriteLine(b); + } + } + """); [Fact] - public async Task SplitWithPreservedSingleLineFormatting() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]|| b) System.Console.WriteLine(); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) System.Console.WriteLine(); - else if (b) System.Console.WriteLine(); - } -}"); - } + public Task SplitWithMissingElseStatement() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]|| b) + System.Console.WriteLine(); + else + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + System.Console.WriteLine(); + else if (b) + System.Console.WriteLine(); + else + } + } + """); [Fact] - public async Task SplitIntoSeparateStatementsIfControlFlowQuits1() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]|| b) - return; - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - return; - if (b) - return; - } -}"); - } + public Task SplitWithPreservedSingleLineFormatting() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]|| b) System.Console.WriteLine(); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) System.Console.WriteLine(); + else if (b) System.Console.WriteLine(); + } + } + """); [Fact] - public async Task SplitIntoSeparateStatementsIfControlFlowQuits2() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]|| b) - throw new System.Exception(); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - throw new System.Exception(); - if (b) - throw new System.Exception(); - } -}"); - } + public Task SplitIntoSeparateStatementsIfControlFlowQuits1() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]|| b) + return; + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + return; + if (b) + return; + } + } + """); [Fact] - public async Task SplitIntoSeparateStatementsIfControlFlowQuits3() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - while (true) - { - if (a [||]|| b) - continue; - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - while (true) - { - if (a) - continue; - if (b) - continue; - } - } -}"); - } + public Task SplitIntoSeparateStatementsIfControlFlowQuits2() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]|| b) + throw new System.Exception(); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + throw new System.Exception(); + if (b) + throw new System.Exception(); + } + } + """); [Fact] - public async Task SplitIntoSeparateStatementsIfControlFlowQuits4() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - while (true) - { - if (a [||]|| b) - { - if (a) - continue; - else - break; - } - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - while (true) - { - if (a) + public Task SplitIntoSeparateStatementsIfControlFlowQuits3() + => TestInRegularAndScriptAsync( + """ + class C { - if (a) - continue; - else - break; + void M(bool a, bool b) + { + while (true) + { + if (a [||]|| b) + continue; + } + } } - - if (b) + """, + """ + class C { - if (a) - continue; - else - break; + void M(bool a, bool b) + { + while (true) + { + if (a) + continue; + if (b) + continue; + } + } } - } - } -}"); - } + """); [Fact] - public async Task SplitIntoSeparateStatementsIfControlFlowQuits5() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - while (true) - { - if (a [||]|| b) - switch (a) - { - default: - continue; - } - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - while (true) - { - if (a) - switch (a) + public Task SplitIntoSeparateStatementsIfControlFlowQuits4() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) { - default: - continue; + while (true) + { + if (a [||]|| b) + { + if (a) + continue; + else + break; + } + } } - - if (b) - switch (a) + } + """, + """ + class C + { + void M(bool a, bool b) { - default: - continue; + while (true) + { + if (a) + { + if (a) + continue; + else + break; + } + + if (b) + { + if (a) + continue; + else + break; + } + } } - } - } -}"); - } + } + """); [Fact] - public async Task SplitIntoSeparateStatementsIfControlFlowQuitsInSwitchSection() - { - // Switch sections are interesting in that they are blocks of statements that aren't BlockSyntax. - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - switch (a) - { - case true: - if (a [||]|| b) - break; - break; - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - switch (a) - { - case true: - if (a) - break; - if (b) - break; - break; - } - } -}"); - } + public Task SplitIntoSeparateStatementsIfControlFlowQuits5() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + while (true) + { + if (a [||]|| b) + switch (a) + { + default: + continue; + } + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + while (true) + { + if (a) + switch (a) + { + default: + continue; + } + + if (b) + switch (a) + { + default: + continue; + } + } + } + } + """); [Fact] - public async Task SplitIntoSeparateStatementsIfControlFlowQuitsWithNestedIfStatement() - { - // No need to create a block if we're not adding an else clause. - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]|| b) - if (true) - return; - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - if (true) - return; - if (b) - if (true) - return; - } -}"); - } + public Task SplitIntoSeparateStatementsIfControlFlowQuitsInSwitchSection() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + switch (a) + { + case true: + if (a [||]|| b) + break; + break; + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + switch (a) + { + case true: + if (a) + break; + if (b) + break; + break; + } + } + } + """); [Fact] - public async Task SplitIntoSeparateStatementsIfControlFlowQuitsWithPreservedSingleLineFormatting() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]|| b) return; - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) return; - if (b) return; - } -}"); - } + public Task SplitIntoSeparateStatementsIfControlFlowQuitsWithNestedIfStatement() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]|| b) + if (true) + return; + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + if (true) + return; + if (b) + if (true) + return; + } + } + """); [Fact] - public async Task SplitNotIntoSeparateStatementsIfControlFlowContinues1() - { - // Even though there are no statements inside, we still can't split this into separate statements - // because it would change the semantics from short-circuiting to always evaluating the second condition, - // breaking code like 'if (a == null || a.InstanceMethod())'. - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]|| b) - { - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - } - else if (b) - { - } - } -}"); - } + public Task SplitIntoSeparateStatementsIfControlFlowQuitsWithPreservedSingleLineFormatting() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]|| b) return; + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) return; + if (b) return; + } + } + """); [Fact] - public async Task SplitNotIntoSeparateStatementsIfControlFlowContinues2() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]|| b) - { - if (a) - return; - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - if (a) - return; - } - else if (b) - { - if (a) - return; - } - } -}"); - } + public Task SplitNotIntoSeparateStatementsIfControlFlowContinues1() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]|| b) + { + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + } + else if (b) + { + } + } + } + """); [Fact] - public async Task SplitNotIntoSeparateStatementsIfControlFlowContinues3() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]|| b) - while (a) + public Task SplitNotIntoSeparateStatementsIfControlFlowContinues2() + => TestInRegularAndScriptAsync( + """ + class C { - break; + void M(bool a, bool b) + { + if (a [||]|| b) + { + if (a) + return; + } + } } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - while (a) + """, + """ + class C { - break; + void M(bool a, bool b) + { + if (a) + { + if (a) + return; + } + else if (b) + { + if (a) + return; + } + } } - else if (b) - while (a) + """); + + [Fact] + public Task SplitNotIntoSeparateStatementsIfControlFlowContinues3() + => TestInRegularAndScriptAsync( + """ + class C { - break; + void M(bool a, bool b) + { + if (a [||]|| b) + while (a) + { + break; + } + } } - } -}"); - } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + while (a) + { + break; + } + else if (b) + while (a) + { + break; + } + } + } + """); [Fact] - public async Task SplitNotIntoSeparateStatementsIfControlFlowContinues4() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - while (true) - { - if (a [||]|| b) - switch (a) - { - default: - break; - } - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - while (true) - { - if (a) - switch (a) + public Task SplitNotIntoSeparateStatementsIfControlFlowContinues4() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) { - default: - break; + while (true) + { + if (a [||]|| b) + switch (a) + { + default: + break; + } + } } - else if (b) - switch (a) + } + """, + """ + class C + { + void M(bool a, bool b) { - default: - break; + while (true) + { + if (a) + switch (a) + { + default: + break; + } + else if (b) + switch (a) + { + default: + break; + } + } } - } - } -}"); - } + } + """); [Fact] - public async Task SplitNotIntoSeparateStatementsWithElseIfControlFlowQuits() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]|| b) - return; - else - return; - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - return; - else if (b) - return; - else - return; - } -}"); - } + public Task SplitNotIntoSeparateStatementsWithElseIfControlFlowQuits() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]|| b) + return; + else + return; + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + return; + else if (b) + return; + else + return; + } + } + """); [Fact] - public async Task SplitIntoSeparateStatementsAsEmbeddedStatementIfControlFlowQuits() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - while (a) - if (a [||]|| b) - return; - } -}", -@"class C -{ - void M(bool a, bool b) - { - while (a) - { - if (a) - return; - if (b) - return; - } - } -}"); - } + public Task SplitIntoSeparateStatementsAsEmbeddedStatementIfControlFlowQuits() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + while (a) + if (a [||]|| b) + return; + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + while (a) + { + if (a) + return; + if (b) + return; + } + } + } + """); [Fact] - public async Task SplitNotIntoSeparateStatementsAsElseIfIfControlFlowQuits() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a) - return; - else if (a [||]|| b) - return; - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - return; - else if (a) - return; - else if (b) - return; - } -}"); - } + public Task SplitNotIntoSeparateStatementsAsElseIfIfControlFlowQuits() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a) + return; + else if (a [||]|| b) + return; + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + return; + else if (a) + return; + else if (b) + return; + } + } + """); } diff --git a/src/Features/CSharpTest/SplitOrMergeIfStatements/SplitIntoNestedIfStatementsTests.cs b/src/Features/CSharpTest/SplitOrMergeIfStatements/SplitIntoNestedIfStatementsTests.cs index 2f820016ea1e2..c450e8c4a936b 100644 --- a/src/Features/CSharpTest/SplitOrMergeIfStatements/SplitIntoNestedIfStatementsTests.cs +++ b/src/Features/CSharpTest/SplitOrMergeIfStatements/SplitIntoNestedIfStatementsTests.cs @@ -24,758 +24,804 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor [InlineData("a &[||]& b")] [InlineData("a &&[||] b")] [InlineData("a [|&&|] b")] - public async Task SplitOnAndOperatorSpans(string condition) - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (" + condition + @") - { - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - if (b) + public Task SplitOnAndOperatorSpans(string condition) + => TestInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b) + { + if ( + """ + condition + """ + ) + { + } + } } - } - } -}"); - } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + if (b) + { + } + } + } + } + """); [Theory] [InlineData("a [|&|]& b")] [InlineData("a[| &&|] b")] [InlineData("a[||] && b")] - public async Task NotSplitOnAndOperatorSpans(string condition) - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (" + condition + @") - { - } - } -}"); - } + public Task NotSplitOnAndOperatorSpans(string condition) + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if ( + """ + condition + """ + ) + { + } + } + } + """); [Fact] - public async Task NotSplitOnIfKeyword() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - [||]if (a && b) - { - } - } -}"); - } + public Task NotSplitOnIfKeyword() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + [||]if (a && b) + { + } + } + } + """); [Fact] - public async Task NotSplitOnOrOperator() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]|| b) - { - } - } -}"); - } + public Task NotSplitOnOrOperator() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]|| b) + { + } + } + } + """); [Fact] - public async Task NotSplitOnBitwiseAndOperator() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]& b) - { - } - } -}"); - } + public Task NotSplitOnBitwiseAndOperator() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]& b) + { + } + } + } + """); [Fact] - public async Task NotSplitOnAndOperatorOutsideIfStatement() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - var v = a [||]&& b; - } -}"); - } + public Task NotSplitOnAndOperatorOutsideIfStatement() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + var v = a [||]&& b; + } + } + """); [Fact] - public async Task NotSplitOnAndOperatorInIfStatementBody() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a && b) - a [||]&& b; - } -}"); - } + public Task NotSplitOnAndOperatorInIfStatementBody() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a && b) + a [||]&& b; + } + } + """); [Fact] - public async Task SplitWithChainedAndExpression1() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a [||]&& b && c && d) - { - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a) - { - if (b && c && d) + public Task SplitWithChainedAndExpression1() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a [||]&& b && c && d) + { + } + } + } + """, + """ + class C { + void M(bool a, bool b, bool c, bool d) + { + if (a) + { + if (b && c && d) + { + } + } + } } - } - } -}"); - } + """); [Fact] - public async Task SplitWithChainedAndExpression2() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a && b [||]&& c && d) - { - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a && b) - { - if (c && d) + public Task SplitWithChainedAndExpression2() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a && b [||]&& c && d) + { + } + } + } + """, + """ + class C { + void M(bool a, bool b, bool c, bool d) + { + if (a && b) + { + if (c && d) + { + } + } + } } - } - } -}"); - } + """); [Fact] - public async Task SplitWithChainedAndExpression3() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a && b && c [||]&& d) - { - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a && b && c) - { - if (d) + public Task SplitWithChainedAndExpression3() + => TestInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b, bool c, bool d) + { + if (a && b && c [||]&& d) + { + } + } } - } - } -}"); - } + """, + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a && b && c) + { + if (d) + { + } + } + } + } + """); [Fact] - public async Task NotSplitInsideParentheses1() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if ((a [||]&& b) && c && d) - { - } - } -}"); - } + public Task NotSplitInsideParentheses1() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if ((a [||]&& b) && c && d) + { + } + } + } + """); [Fact] - public async Task NotSplitInsideParentheses2() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a && b && (c [||]&& d)) - { - } - } -}"); - } + public Task NotSplitInsideParentheses2() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a && b && (c [||]&& d)) + { + } + } + } + """); [Fact] - public async Task NotSplitInsideParentheses3() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if ((a && b [||]&& c && d)) - { - } - } -}"); - } + public Task NotSplitInsideParentheses3() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if ((a && b [||]&& c && d)) + { + } + } + } + """); [Fact] - public async Task SplitWithOtherExpressionInsideParentheses1() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a [||]&& (b && c) && d) - { - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a) - { - if ((b && c) && d) + public Task SplitWithOtherExpressionInsideParentheses1() + => TestInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b, bool c, bool d) + { + if (a [||]&& (b && c) && d) + { + } + } } - } - } -}"); - } + """, + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a) + { + if ((b && c) && d) + { + } + } + } + } + """); [Fact] - public async Task SplitWithOtherExpressionInsideParentheses2() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a && (b && c) [||]&& d) - { - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c, bool d) - { - if (a && (b && c)) - { - if (d) + public Task SplitWithOtherExpressionInsideParentheses2() + => TestInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b, bool c, bool d) + { + if (a && (b && c) [||]&& d) + { + } + } } - } - } -}"); - } + """, + """ + class C + { + void M(bool a, bool b, bool c, bool d) + { + if (a && (b && c)) + { + if (d) + { + } + } + } + } + """); [Fact] - public async Task NotSplitWithMixedOrExpression1() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a [||]&& b || c) - { - } - } -}"); - } + public Task NotSplitWithMixedOrExpression1() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c) + { + if (a [||]&& b || c) + { + } + } + } + """); [Fact] - public async Task NotSplitWithMixedOrExpression2() - { - await TestMissingInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a || b [||]&& c) - { - } - } -}"); - } + public Task NotSplitWithMixedOrExpression2() + => TestMissingInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b, bool c) + { + if (a || b [||]&& c) + { + } + } + } + """); [Fact] - public async Task SplitWithMixedOrExpressionInsideParentheses1() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a [||]&& (b || c)) - { - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a) - { - if ((b || c)) + public Task SplitWithMixedOrExpressionInsideParentheses1() + => TestInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b, bool c) + { + if (a [||]&& (b || c)) + { + } + } } - } - } -}"); - } + """, + """ + class C + { + void M(bool a, bool b, bool c) + { + if (a) + { + if ((b || c)) + { + } + } + } + } + """); [Fact] - public async Task SplitWithMixedOrExpressionInsideParentheses2() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c) - { - if ((a || b) [||]&& c) - { - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c) - { - if ((a || b)) - { - if (c) + public Task SplitWithMixedOrExpressionInsideParentheses2() + => TestInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b, bool c) + { + if ((a || b) [||]&& c) + { + } + } } - } - } -}"); - } + """, + """ + class C + { + void M(bool a, bool b, bool c) + { + if ((a || b)) + { + if (c) + { + } + } + } + } + """); [Fact] - public async Task SplitWithMixedBitwiseOrExpression1() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a [||]&& b | c) - { - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a) - { - if (b | c) + public Task SplitWithMixedBitwiseOrExpression1() + => TestInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b, bool c) + { + if (a [||]&& b | c) + { + } + } } - } - } -}"); - } + """, + """ + class C + { + void M(bool a, bool b, bool c) + { + if (a) + { + if (b | c) + { + } + } + } + } + """); [Fact] - public async Task SplitWithMixedBitwiseOrExpression2() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a | b [||]&& c) - { - } - } -}", -@"class C -{ - void M(bool a, bool b, bool c) - { - if (a | b) - { - if (c) + public Task SplitWithMixedBitwiseOrExpression2() + => TestInRegularAndScriptAsync( + """ + class C { + void M(bool a, bool b, bool c) + { + if (a | b [||]&& c) + { + } + } } - } - } -}"); - } + """, + """ + class C + { + void M(bool a, bool b, bool c) + { + if (a | b) + { + if (c) + { + } + } + } + } + """); [Fact] - public async Task SplitWithStatementInsideBlock() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]&& b) - { - System.Console.WriteLine(a && b); - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - if (b) + public Task SplitWithStatementInsideBlock() + => TestInRegularAndScriptAsync( + """ + class C { - System.Console.WriteLine(a && b); + void M(bool a, bool b) + { + if (a [||]&& b) + { + System.Console.WriteLine(a && b); + } + } } - } - } -}"); - } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + if (b) + { + System.Console.WriteLine(a && b); + } + } + } + } + """); [Fact] - public async Task SplitWithStatementWithoutBlock() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]&& b) - System.Console.WriteLine(a && b); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - if (b) - System.Console.WriteLine(a && b); - } - } -}"); - } + public Task SplitWithStatementWithoutBlock() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]&& b) + System.Console.WriteLine(a && b); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + if (b) + System.Console.WriteLine(a && b); + } + } + } + """); [Fact] - public async Task SplitWithNestedIfStatement() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]&& b) - if (true) { } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - if (b) - if (true) { } - } - } -}"); - } + public Task SplitWithNestedIfStatement() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]&& b) + if (true) { } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + if (b) + if (true) { } + } + } + } + """); [Fact] - public async Task SplitWithMissingStatement() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]&& b) - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - if (b) -} - } -}"); - } + public Task SplitWithMissingStatement() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]&& b) + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + if (b) + } + } + } + """); [Fact] - public async Task SplitWithElseStatementInsideBlock() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]&& b) - System.Console.WriteLine(); - else - { - System.Console.WriteLine(a && b); - } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - if (b) - System.Console.WriteLine(); - else - { - System.Console.WriteLine(a && b); - } - } - else - { - System.Console.WriteLine(a && b); - } - } -}"); - } + public Task SplitWithElseStatementInsideBlock() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]&& b) + System.Console.WriteLine(); + else + { + System.Console.WriteLine(a && b); + } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + if (b) + System.Console.WriteLine(); + else + { + System.Console.WriteLine(a && b); + } + } + else + { + System.Console.WriteLine(a && b); + } + } + } + """); [Fact] - public async Task SplitWithElseStatementWithoutBlock() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]&& b) - System.Console.WriteLine(); - else - System.Console.WriteLine(a && b); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - if (b) - System.Console.WriteLine(); - else - System.Console.WriteLine(a && b); - } - else - System.Console.WriteLine(a && b); - } -}"); - } + public Task SplitWithElseStatementWithoutBlock() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]&& b) + System.Console.WriteLine(); + else + System.Console.WriteLine(a && b); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + if (b) + System.Console.WriteLine(); + else + System.Console.WriteLine(a && b); + } + else + System.Console.WriteLine(a && b); + } + } + """); [Fact] - public async Task SplitWithElseNestedIfStatement() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]&& b) - System.Console.WriteLine(); - else if (true) { } - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - if (b) - System.Console.WriteLine(); - else if (true) { } - } - else if (true) { } - } -}"); - } + public Task SplitWithElseNestedIfStatement() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]&& b) + System.Console.WriteLine(); + else if (true) { } + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + if (b) + System.Console.WriteLine(); + else if (true) { } + } + else if (true) { } + } + } + """); [Fact] - public async Task SplitWithElseIfElse() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]&& b) - System.Console.WriteLine(); - else if (a) - System.Console.WriteLine(a); - else - System.Console.WriteLine(b); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - if (b) - System.Console.WriteLine(); - else if (a) - System.Console.WriteLine(a); - else - System.Console.WriteLine(b); - } - else if (a) - System.Console.WriteLine(a); - else - System.Console.WriteLine(b); - } -}"); - } + public Task SplitWithElseIfElse() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]&& b) + System.Console.WriteLine(); + else if (a) + System.Console.WriteLine(a); + else + System.Console.WriteLine(b); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + if (b) + System.Console.WriteLine(); + else if (a) + System.Console.WriteLine(a); + else + System.Console.WriteLine(b); + } + else if (a) + System.Console.WriteLine(a); + else + System.Console.WriteLine(b); + } + } + """); [Fact] - public async Task SplitAsPartOfElseIfElse() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (true) - System.Console.WriteLine(); - else if (a [||]&& b) - System.Console.WriteLine(a); - else - System.Console.WriteLine(b); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (true) - System.Console.WriteLine(); - else if (a) - { - if (b) - System.Console.WriteLine(a); - else - System.Console.WriteLine(b); - } - else - System.Console.WriteLine(b); - } -}"); - } + public Task SplitAsPartOfElseIfElse() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (true) + System.Console.WriteLine(); + else if (a [||]&& b) + System.Console.WriteLine(a); + else + System.Console.WriteLine(b); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (true) + System.Console.WriteLine(); + else if (a) + { + if (b) + System.Console.WriteLine(a); + else + System.Console.WriteLine(b); + } + else + System.Console.WriteLine(b); + } + } + """); [Fact] - public async Task SplitWithMissingElseStatement() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]&& b) - System.Console.WriteLine(); - else - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - if (b) - System.Console.WriteLine(); - else -} - else - } -}"); - } + public Task SplitWithMissingElseStatement() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]&& b) + System.Console.WriteLine(); + else + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + if (b) + System.Console.WriteLine(); + else + } + else + } + } + """); [Fact] - public async Task SplitWithPreservedSingleLineFormatting() - { - await TestInRegularAndScriptAsync( -@"class C -{ - void M(bool a, bool b) - { - if (a [||]&& b) System.Console.WriteLine(); - } -}", -@"class C -{ - void M(bool a, bool b) - { - if (a) - { - if (b) System.Console.WriteLine(); - } - } -}"); - } + public Task SplitWithPreservedSingleLineFormatting() + => TestInRegularAndScriptAsync( + """ + class C + { + void M(bool a, bool b) + { + if (a [||]&& b) System.Console.WriteLine(); + } + } + """, + """ + class C + { + void M(bool a, bool b) + { + if (a) + { + if (b) System.Console.WriteLine(); + } + } + } + """); } diff --git a/src/Features/CSharpTest/Testing/CSharpTestMethodFinderTests.cs b/src/Features/CSharpTest/Testing/CSharpTestMethodFinderTests.cs index fd90ea078b046..efe606a0b36a0 100644 --- a/src/Features/CSharpTest/Testing/CSharpTestMethodFinderTests.cs +++ b/src/Features/CSharpTest/Testing/CSharpTestMethodFinderTests.cs @@ -22,23 +22,19 @@ public sealed class CSharpTestMethodFinderTests #region Xunit [Fact] - public async Task TestFindsXUnitFactMethod() - { - var code = """ + public Task TestFindsXUnitFactMethod() + => TestXunitAsync(""" using Xunit; public class TestClass { [Fact] public void Test$$Method1() { } } - """; - await TestXunitAsync(code, "TestMethod1"); - } + """, "TestMethod1"); [Fact] - public async Task TestMatchesXUnitFactInInnerClassMethod() - { - var code = """ + public Task TestMatchesXUnitFactInInnerClassMethod() + => TestXunitMatchAsync(""" using Xunit; public class OuterClass { @@ -51,14 +47,11 @@ public class InnerClass public void Test$$Method2() { } } } - """; - await TestXunitMatchAsync(code, "OuterClass+InnerClass.TestMethod2"); - } + """, "OuterClass+InnerClass.TestMethod2"); [Fact] - public async Task TestMatchesXUnitFactInOuterClassMethod() - { - var code = """ + public Task TestMatchesXUnitFactInOuterClassMethod() + => TestXunitMatchAsync(""" using Xunit; public class OuterClass { @@ -71,56 +64,44 @@ public class InnerClass public void TestMethod2() { } } } - """; - await TestXunitMatchAsync(code, "OuterClass.TestMethod1"); - } + """, "OuterClass.TestMethod1"); [Fact] - public async Task TestFindsXUnitFactAttributeMethod() - { - var code = """ + public Task TestFindsXUnitFactAttributeMethod() + => TestXunitAsync(""" using Xunit; public class TestClass { [FactAttribute] public void Test$$Method1() { } } - """; - await TestXunitAsync(code, "TestMethod1"); - } + """, "TestMethod1"); [Fact] - public async Task TestFindsXUnitTheoryMethod() - { - var code = """ + public Task TestFindsXUnitTheoryMethod() + => TestXunitAsync(""" using Xunit; public class TestClass { [Theory] public void Test$$Method1() { } } - """; - await TestXunitAsync(code, "TestMethod1"); - } + """, "TestMethod1"); [Fact] - public async Task TestFindsXUnitTheoryAttributeMethod() - { - var code = """ + public Task TestFindsXUnitTheoryAttributeMethod() + => TestXunitAsync(""" using Xunit; public class TestClass { [TheoryAttribute] public void Test$$Method1() { } } - """; - await TestXunitAsync(code, "TestMethod1"); - } + """, "TestMethod1"); [Fact] - public async Task TestFindsXUnitAliasedFactMethod() - { - var code = """ + public Task TestFindsXUnitAliasedFactMethod() + => TestXunitAsync(""" using Xunit; using test = Xunit.FactAttribute; public class TestClass @@ -128,16 +109,11 @@ public class TestClass [test] public void Test$$Method1() { } } - """; - - // This asserts that we cannot find test methods with aliased attributes because we only do syntactic checks. - await TestXunitAsync(code); - } + """); [Fact] - public async Task TestFindsXUnitFactOnlySelectedMethod() - { - var code = """ + public Task TestFindsXUnitFactOnlySelectedMethod() + => TestXunitAsync(""" using Xunit; public class TestClass { @@ -149,14 +125,11 @@ public void TestMethod2() { } public void NotTestMethod() { } } - """; - await TestXunitAsync(code, "TestMethod1"); - } + """, "TestMethod1"); [Fact] - public async Task TestFindsXunitMethodsInClassMethod() - { - var code = """ + public Task TestFindsXunitMethodsInClassMethod() + => TestXunitAsync(""" using Xunit; public class Test$$Class { @@ -171,27 +144,21 @@ public void TestMethod3() { } public void NotTestMethod() { } } - """; - await TestXunitAsync(code, "TestMethod1", "TestMethod2", "TestMethod3"); - } + """, "TestMethod1", "TestMethod2", "TestMethod3"); [Fact] - public async Task TestXunitNoMethodsInClass() - { - var code = """ + public Task TestXunitNoMethodsInClass() + => TestXunitAsync(""" using Xunit; public class Test$$Class { public void NotTestMethod() { } } - """; - await TestXunitAsync(code); - } + """); [Fact] - public async Task TestFindsSelectedXunitMethods() - { - var code = """ + public Task TestFindsSelectedXunitMethods() + => TestXunitAsync(""" using Xunit; public class TestClass { @@ -206,102 +173,81 @@ public void TestMethod3() { } public void NotTestMethod() { } } - """; - await TestXunitAsync(code, "TestMethod1", "TestMethod2"); - } + """, "TestMethod1", "TestMethod2"); #endregion #region NUnit [Fact] - public async Task TestFindsNUnitTestMethod() - { - var code = """ + public Task TestFindsNUnitTestMethod() + => TestNUnitAsync(""" using NUnit.Framework; public class TestClass { [Test] public void Test$$Method1() { } } - """; - await TestNUnitAsync(code, "TestMethod1"); - } + """, "TestMethod1"); [Fact] - public async Task TestFindsNUnitTestAttributeMethod() - { - var code = """ + public Task TestFindsNUnitTestAttributeMethod() + => TestNUnitAsync(""" using NUnit.Framework; public class TestClass { [TestAttribute] public void Test$$Method1() { } } - """; - await TestNUnitAsync(code, "TestMethod1"); - } + """, "TestMethod1"); [Fact] - public async Task TestFindsNUnitTheoryMethod() - { - var code = """ + public Task TestFindsNUnitTheoryMethod() + => TestNUnitAsync(""" using NUnit.Framework; public class TestClass { [Theory] public void Test$$Method1() { } } - """; - await TestNUnitAsync(code, "TestMethod1"); - } + """, "TestMethod1"); [Fact] - public async Task TestFindsNUnitTheoryAttributeMethod() - { - var code = """ + public Task TestFindsNUnitTheoryAttributeMethod() + => TestNUnitAsync(""" using NUnit.Framework; public class TestClass { [TheoryAttribute] public void Test$$Method1() { } } - """; - await TestNUnitAsync(code, "TestMethod1"); - } + """, "TestMethod1"); [Fact] - public async Task TestFindsNUnitTestCaseMethod() - { - var code = """ + public Task TestFindsNUnitTestCaseMethod() + => TestNUnitAsync(""" using NUnit.Framework; public class TestClass { [TestCase] public void Test$$Method1() { } } - """; - await TestNUnitAsync(code, "TestMethod1"); - } + """, "TestMethod1"); [Fact] - public async Task TestFindsNUnitTestCaseAttributeMethod() - { - var code = """ + public Task TestFindsNUnitTestCaseAttributeMethod() + => TestNUnitAsync(""" using NUnit.Framework; public class TestClass { [TestCaseAttribute] public void Test$$Method1() { } } - """; - await TestNUnitAsync(code, "TestMethod1"); - } + """, "TestMethod1"); [Fact] - public async Task TestFindsNUnitTestCaseSourceMethod() - { - var code = """ + public Task TestFindsNUnitTestCaseSourceMethod() + => TestNUnitAsync(""" using NUnit.Framework; public class TestClass { @@ -309,14 +255,11 @@ public class TestClass [TestCaseSource(nameof(s_s))] public void Test$$Method1() { } } - """; - await TestNUnitAsync(code, "TestMethod1"); - } + """, "TestMethod1"); [Fact] - public async Task TestFindsNUnitTestCaseSourceAttributeMethod() - { - var code = """ + public Task TestFindsNUnitTestCaseSourceAttributeMethod() + => TestNUnitAsync(""" using NUnit.Framework; public class TestClass { @@ -324,14 +267,11 @@ public class TestClass [TestCaseSourceAttribute(nameof(s_s))] public void Test$$Method1() { } } - """; - await TestNUnitAsync(code, "TestMethod1"); - } + """, "TestMethod1"); [Fact] - public async Task TestFindsNUnitMethodsInClass() - { - var code = """ + public Task TestFindsNUnitMethodsInClass() + => TestNUnitAsync(""" using NUnit.Framework; public class Test$$Class { @@ -350,18 +290,15 @@ public void TestMethod4() { } public void NotTestMethod() { } } - """; - await TestNUnitAsync(code, "TestMethod1", "TestMethod2", "TestMethod3", "TestMethod4"); - } + """, "TestMethod1", "TestMethod2", "TestMethod3", "TestMethod4"); #endregion #region MSTest [Fact] - public async Task TestFindsMSTestTestMethod() - { - var code = """ + public Task TestFindsMSTestTestMethod() + => TestMSTestAsync(""" using Microsoft.VisualStudio.TestTools.UnitTesting; public class TestClass { @@ -369,14 +306,11 @@ public class TestClass public void Test$$Method1() { } } - """; - await TestMSTestAsync(code, "TestMethod1"); - } + """, "TestMethod1"); [Fact] - public async Task TestFindsMSTestTestMethodAttribute() - { - var code = """ + public Task TestFindsMSTestTestMethodAttribute() + => TestMSTestAsync(""" using Microsoft.VisualStudio.TestTools.UnitTesting; public class TestClass { @@ -384,14 +318,11 @@ public class TestClass public void Test$$Method1() { } } - """; - await TestMSTestAsync(code, "TestMethod1"); - } + """, "TestMethod1"); [Fact] - public async Task TestFindsMSTestMethodsInClass() - { - var code = """ + public Task TestFindsMSTestMethodsInClass() + => TestMSTestAsync(""" using Microsoft.VisualStudio.TestTools.UnitTesting; public class Test$$Class { @@ -403,16 +334,13 @@ public void TestMethod2() { } public void NotTestMethod() { } } - """; - await TestMSTestAsync(code, "TestMethod1", "TestMethod2"); - } + """, "TestMethod1", "TestMethod2"); #endregion [Fact] - public async Task TestFindsTestMethodInBlockScopedNamespace() - { - var code = """ + public Task TestFindsTestMethodInBlockScopedNamespace() + => TestXunitAsync(""" namespace BlockScoped { using Xunit; @@ -422,14 +350,11 @@ public class TestClass public void Test$$Method1() { } } } - """; - await TestXunitAsync(code, "TestMethod1"); - } + """, "TestMethod1"); [Fact] - public async Task TestFindsTestMethodInFileScopedNamespace() - { - var code = """ + public Task TestFindsTestMethodInFileScopedNamespace() + => TestXunitAsync(""" namespace FileScoped; using Xunit; public class TestClass @@ -437,28 +362,22 @@ public class TestClass [Fact] public void Test$$Method1() { } } - """; - await TestXunitAsync(code, "TestMethod1"); - } + """, "TestMethod1"); [Fact] - public async Task TestFindsTestMethodInStruct() - { - var code = """ + public Task TestFindsTestMethodInStruct() + => TestXunitAsync(""" using Xunit; public struct TestClass { [Fact] public void Test$$Method1() { } } - """; - await TestXunitAsync(code, "TestMethod1"); - } + """, "TestMethod1"); [Fact] - public async Task TestFindsTestMethodInPartialClass() - { - var code = """ + public Task TestFindsTestMethodInPartialClass() + => TestXunitAsync(""" using Xunit; public partial class PartialClass { @@ -471,13 +390,11 @@ public partial class PartialClass [Fact] public void TestMethod2() { } } - """; - await TestXunitAsync(code, "TestMethod1"); - } + """, "TestMethod1"); private static Task TestXunitAsync(string code, params string[] expectedTestNames) { - var xunitDefinitions = """ + return TestAsync(code, """ using System; namespace Xunit { @@ -487,14 +404,12 @@ public class FactAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public class TheoryAttribute : FactAttribute { } } - """; - - return TestAsync(code, xunitDefinitions, expectedTestNames); + """, expectedTestNames); } private static Task TestXunitMatchAsync(string code, params string[] expectedQualifiedTestNames) { - var xunitDefinitions = """ + return TestMatchAsync(code, """ using System; namespace Xunit { @@ -504,14 +419,12 @@ public class FactAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public class TheoryAttribute : FactAttribute { } } - """; - - return TestMatchAsync(code, xunitDefinitions, expectedQualifiedTestNames); + """, expectedQualifiedTestNames); } private static Task TestNUnitAsync(string code, params string[] expectedTestNames) { - var nunitDefinitions = """ + return TestAsync(code, """ using System; namespace NUnit.Framework { @@ -530,21 +443,19 @@ public class TestCaseSourceAttribute : Attribute public TestCaseSourceAttribute(string sourceName) { } } } - """; - return TestAsync(code, nunitDefinitions, expectedTestNames); + """, expectedTestNames); } private static Task TestMSTestAsync(string code, params string[] expectedTestNames) { - var nunitDefinitions = """ + return TestAsync(code, """ using System; namespace Microsoft.VisualStudio.TestTools.UnitTesting { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public class TestMethodAttribute : Attribute { } } - """; - return TestAsync(code, nunitDefinitions, expectedTestNames); + """, expectedTestNames); } private static async Task TestAsync(string code, string testAttributeDefinitionsCode, params string[] expectedTestNames) diff --git a/src/Features/CSharpTest/UseExplicitOrImplicitType/UseExplicitTypeRefactoringTests.cs b/src/Features/CSharpTest/UseExplicitOrImplicitType/UseExplicitTypeRefactoringTests.cs index 47dafdb88bbf3..c2c46f2609715 100644 --- a/src/Features/CSharpTest/UseExplicitOrImplicitType/UseExplicitTypeRefactoringTests.cs +++ b/src/Features/CSharpTest/UseExplicitOrImplicitType/UseExplicitTypeRefactoringTests.cs @@ -19,9 +19,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor => new UseExplicitTypeCodeRefactoringProvider(); [Fact] - public async Task TestIntLocalDeclaration() - { - var code = """ + public Task TestIntLocalDeclaration() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -29,9 +28,7 @@ static void Main() var[||] i = 0; } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -39,15 +36,11 @@ static void Main() int i = 0; } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestForeachInsideLocalDeclaration() - { - var code = """ + public Task TestForeachInsideLocalDeclaration() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -55,9 +48,7 @@ static void Main() System.Action notThisLocal = () => { foreach (var[||] i in new int[0]) { } }; } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -65,15 +56,11 @@ static void Main() System.Action notThisLocal = () => { foreach (int[||] i in new int[0]) { } }; } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestInVarPattern() - { - var code = """ + public Task TestInVarPattern() + => TestMissingInRegularAndScriptAsync(""" class C { static void Main() @@ -81,15 +68,11 @@ static void Main() _ = 0 is var[||] i; } } - """; - - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task TestIntLocalDeclaration_Multiple() - { - var code = """ + public Task TestIntLocalDeclaration_Multiple() + => TestMissingInRegularAndScriptAsync(""" class C { static void Main() @@ -97,15 +80,11 @@ static void Main() var[||] i = 0, j = j; } } - """; - - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task TestIntLocalDeclaration_NoInitializer() - { - var code = """ + public Task TestIntLocalDeclaration_NoInitializer() + => TestMissingInRegularAndScriptAsync(""" class C { static void Main() @@ -113,15 +92,11 @@ static void Main() var[||] i; } } - """; - - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task TestIntForLoop() - { - var code = """ + public Task TestIntForLoop() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -129,9 +104,7 @@ static void Main() for (var[||] i = 0;;) { } } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -139,15 +112,11 @@ static void Main() for (int i = 0;;) { } } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestInDispose() - { - var code = """ + public Task TestInDispose() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C : System.IDisposable { static void Main() @@ -155,9 +124,7 @@ static void Main() using (var[||] c = new C()) { } } } - """; - - var expected = """ + """, """ class C : System.IDisposable { static void Main() @@ -165,15 +132,11 @@ static void Main() using (C c = new C()) { } } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestTypelessVarLocalDeclaration() - { - var code = """ + public Task TestTypelessVarLocalDeclaration() + => TestMissingInRegularAndScriptAsync(""" class var { static void Main() @@ -181,14 +144,11 @@ static void Main() var[||] i = null; } } - """; - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task TestIntForeachLoop() - { - var code = """ + public Task TestIntForeachLoop() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -196,9 +156,7 @@ static void Main() foreach (var[||] i in new[] { 0 }) { } } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -206,15 +164,11 @@ static void Main() foreach (int i in new[] { 0 }) { } } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestIntDeconstruction() - { - var code = """ + public Task TestIntDeconstruction() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -222,9 +176,7 @@ static void Main() var[||] (i, j) = (0, 1); } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -232,15 +184,11 @@ static void Main() (int i, int j) = (0, 1); } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestIntDeconstruction2() - { - var code = """ + public Task TestIntDeconstruction2() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -248,9 +196,7 @@ static void Main() (var[||] i, var j) = (0, 1); } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -258,15 +204,11 @@ static void Main() (int i, var j) = (0, 1); } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestWithAnonymousType() - { - var code = """ + public Task TestWithAnonymousType() + => TestMissingInRegularAndScriptAsync(""" class C { static void Main() @@ -274,15 +216,11 @@ static void Main() [|var|] x = new { Amount = 108, Message = "Hello" }; } } - """; - - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26923")] - public async Task NoSuggestionOnForeachCollectionExpression() - { - var code = """ + public Task NoSuggestionOnForeachCollectionExpression() + => TestMissingInRegularAndScriptAsync(""" using System; using System.Collections.Generic; @@ -296,17 +234,11 @@ void Method(List var) } } } - """; - - // We never want to get offered here under any circumstances. - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task NotOnConstVar() - { - // This error case is handled by a separate code fix (UseExplicitTypeForConst). - await TestMissingInRegularAndScriptAsync( + public Task NotOnConstVar() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -316,12 +248,10 @@ void M() } } """); - } [Fact] - public async Task TestWithTopLevelNullability() - { - var code = """ + public Task TestWithTopLevelNullability() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" #nullable enable class C @@ -333,9 +263,7 @@ static void Main() var[||] v = s_data; } } - """; - - var expected = """ + """, """ #nullable enable class C @@ -347,15 +275,11 @@ static void Main() string? v = s_data; } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestWithTopLevelAndNestedArrayNullability1() - { - var code = """ + public Task TestWithTopLevelAndNestedArrayNullability1() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" #nullable enable class C @@ -367,9 +291,7 @@ static void Main() var[||] v = s_data; } } - """; - - var expected = """ + """, """ #nullable enable class C @@ -381,15 +303,11 @@ static void Main() string?[]?[,]? v = s_data; } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestWithTopLevelAndNestedArrayNullability2() - { - var code = """ + public Task TestWithTopLevelAndNestedArrayNullability2() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" #nullable enable class C @@ -401,9 +319,7 @@ static void Main() var[||] v = s_data; } } - """; - - var expected = """ + """, """ #nullable enable class C @@ -415,15 +331,11 @@ static void Main() string?[][,]? v = s_data; } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestWithTopLevelAndNestedArrayNullability3() - { - var code = """ + public Task TestWithTopLevelAndNestedArrayNullability3() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" #nullable enable class C @@ -435,9 +347,7 @@ static void Main() var[||] v = s_data; } } - """; - - var expected = """ + """, """ #nullable enable class C @@ -449,15 +359,11 @@ static void Main() string?[]?[,][,,]? v = s_data; } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestNullabilityAssignment1() - { - var code = """ + public Task TestNullabilityAssignment1() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" #nullable enable class C @@ -469,9 +375,7 @@ static void Main() var[||] v = s_data; } } - """; - - var expected = """ + """, """ #nullable enable class C @@ -483,15 +387,11 @@ static void Main() string v = s_data; } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestNullabilityAssignment2() - { - var code = """ + public Task TestNullabilityAssignment2() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" #nullable enable class C @@ -504,9 +404,7 @@ static void Main() v = null; } } - """; - - var expected = """ + """, """ #nullable enable class C @@ -519,15 +417,11 @@ static void Main() v = null; } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestNullabilityAssignment3() - { - var code = """ + public Task TestNullabilityAssignment3() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" #nullable enable class C @@ -542,9 +436,7 @@ static void Main() static string? GetNullableString() => null; } - """; - - var expected = """ + """, """ #nullable enable class C @@ -559,15 +451,11 @@ static void Main() static string? GetNullableString() => null; } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestNullabilityAssignment_Foreach1() - { - var code = """ + public Task TestNullabilityAssignment_Foreach1() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" #nullable enable using System.Collections; @@ -581,9 +469,7 @@ static void Main() } } } - """; - - var expected = """ + """, """ #nullable enable using System.Collections; @@ -597,15 +483,11 @@ static void Main() } } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestNullabilityAssignment_Foreach2() - { - var code = """ + public Task TestNullabilityAssignment_Foreach2() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" #nullable enable using System.Collections; @@ -619,9 +501,7 @@ static void Main() } } } - """; - - var expected = """ + """, """ #nullable enable using System.Collections; @@ -635,15 +515,11 @@ static void Main() } } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestNullabilityAssignment_Lambda1() - { - var code = """ + public Task TestNullabilityAssignment_Lambda1() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" #nullable enable using System; @@ -662,9 +538,7 @@ static void Main() static string? GetNullableString() => null; } - """; - - var expected = """ + """, """ #nullable enable using System; @@ -683,15 +557,11 @@ static void Main() static string? GetNullableString() => null; } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestNullabilityAssignment_Lambda2() - { - var code = """ + public Task TestNullabilityAssignment_Lambda2() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" #nullable enable using System; @@ -708,9 +578,7 @@ static void Main() static string GetString() => ""; } - """; - - var expected = """ + """, """ #nullable enable using System; @@ -727,15 +595,11 @@ static void Main() static string GetString() => ""; } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestNullabilityAssignment_Lambda3() - { - var code = """ + public Task TestNullabilityAssignment_Lambda3() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" #nullable enable using System; @@ -752,9 +616,7 @@ static void Main() static string GetString() => ""; } - """; - - var expected = """ + """, """ #nullable enable using System; @@ -771,15 +633,11 @@ static void Main() static string GetString() => ""; } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestNullabilityAssignment_Lambda4() - { - var code = """ + public Task TestNullabilityAssignment_Lambda4() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" #nullable enable using System; @@ -796,9 +654,7 @@ static void Main() static string? GetString() => null; } - """; - - var expected = """ + """, """ #nullable enable using System; @@ -815,15 +671,11 @@ static void Main() static string? GetString() => null; } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestNullabilityAssignment_Property1() - { - var code = """ + public Task TestNullabilityAssignment_Property1() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" #nullable enable using System; @@ -846,9 +698,7 @@ static void Main() static string GetString() => ""; } - """; - - var expected = """ + """, """ #nullable enable using System; @@ -871,15 +721,11 @@ static void Main() static string GetString() => ""; } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestNullabilityAssignment_Property2() - { - var code = """ + public Task TestNullabilityAssignment_Property2() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" #nullable enable using System; @@ -902,9 +748,7 @@ static void Main() static string? GetString() => null; } - """; - - var expected = """ + """, """ #nullable enable using System; @@ -927,15 +771,11 @@ static void Main() static string? GetString() => null; } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42880")] - public async Task TestRefLocal1() - { - var code = """ + public Task TestRefLocal1() + => TestMissingAsync(""" class C { static void Main() @@ -945,15 +785,11 @@ static void Main() [||]ref var rStr1 = ref str; } } - """; - - await TestMissingAsync(code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42880")] - public async Task TestRefLocal2() - { - var code = """ + public Task TestRefLocal2() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -963,9 +799,7 @@ static void Main() ref [||]var rStr1 = ref str; } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -975,15 +809,11 @@ static void Main() ref string rStr1 = ref str; } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42880")] - public async Task TestRefLocal3() - { - var code = """ + public Task TestRefLocal3() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -993,9 +823,7 @@ static void Main() ref var [||]rStr1 = ref str; } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -1005,15 +833,11 @@ static void Main() ref string rStr1 = ref str; } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42880")] - public async Task TestRefReadonlyLocal1() - { - var code = """ + public Task TestRefReadonlyLocal1() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -1023,9 +847,7 @@ static void Main() ref readonly [||]var rStr1 = ref str; } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -1035,15 +857,11 @@ static void Main() ref readonly string rStr1 = ref str; } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42880")] - public async Task TestRefReadonlyLocal2() - { - var code = """ + public Task TestRefReadonlyLocal2() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -1053,9 +871,7 @@ static void Main() ref readonly var[||] rStr1 = ref str; } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -1065,10 +881,7 @@ static void Main() ref readonly string rStr1 = ref str; } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); private async Task TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(string initialMarkup, string expectedMarkup) { diff --git a/src/Features/CSharpTest/UseExplicitOrImplicitType/UseImplicitTypeRefactoringTests.cs b/src/Features/CSharpTest/UseExplicitOrImplicitType/UseImplicitTypeRefactoringTests.cs index 33c81b48493b7..44d80ee43b06e 100644 --- a/src/Features/CSharpTest/UseExplicitOrImplicitType/UseImplicitTypeRefactoringTests.cs +++ b/src/Features/CSharpTest/UseExplicitOrImplicitType/UseImplicitTypeRefactoringTests.cs @@ -21,9 +21,8 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor => new UseImplicitTypeCodeRefactoringProvider(); [Fact] - public async Task TestIntLocalDeclaration() - { - var code = """ + public Task TestIntLocalDeclaration() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -31,9 +30,7 @@ static void Main() int[||] i = 0; } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -41,15 +38,11 @@ static void Main() var i = 0; } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestSelection1() - { - var code = """ + public Task TestSelection1() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -57,9 +50,7 @@ static void Main() [|int i = 0;|] } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -67,15 +58,11 @@ static void Main() var i = 0; } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task TestSelection2() - { - var code = """ + public Task TestSelection2() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -83,9 +70,7 @@ static void Main() [|int|] i = 0; } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -93,16 +78,12 @@ static void Main() var i = 0; } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] [WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestSelectionNotType() - { - var code = """ + public Task TestSelectionNotType() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -110,9 +91,7 @@ static void Main() int [|i|] = 0; } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -120,15 +99,11 @@ static void Main() var i = 0; } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestForeachInsideLocalDeclaration() - { - var code = """ + public Task TestForeachInsideLocalDeclaration() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -136,9 +111,7 @@ static void Main() System.Action notThisLocal = () => { foreach (int[||] i in new int[0]) { } }; } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -146,15 +119,11 @@ static void Main() System.Action notThisLocal = () => { foreach (var[||] i in new int[0]) { } }; } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestInIntPattern() - { - var code = """ + public Task TestInIntPattern() + => TestMissingInRegularAndScriptAsync(""" class C { static void Main() @@ -162,15 +131,11 @@ static void Main() _ = 0 is int[||] i; } } - """; - - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task TestIntLocalDeclaration_Multiple() - { - var code = """ + public Task TestIntLocalDeclaration_Multiple() + => TestMissingInRegularAndScriptAsync(""" class C { static void Main() @@ -178,15 +143,11 @@ static void Main() int[||] i = 0, j = j; } } - """; - - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task TestIntLocalDeclaration_NoInitializer() - { - var code = """ + public Task TestIntLocalDeclaration_NoInitializer() + => TestMissingInRegularAndScriptAsync(""" class C { static void Main() @@ -194,15 +155,11 @@ static void Main() int[||] i; } } - """; - - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact] - public async Task TestIntForLoop() - { - var code = """ + public Task TestIntForLoop() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -210,9 +167,7 @@ static void Main() for (int[||] i = 0;;) { } } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -220,15 +175,11 @@ static void Main() for (var i = 0;;) { } } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestInDispose() - { - var code = """ + public Task TestInDispose() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C : System.IDisposable { static void Main() @@ -236,9 +187,7 @@ static void Main() using (C[||] c = new C()) { } } } - """; - - var expected = """ + """, """ class C : System.IDisposable { static void Main() @@ -246,15 +195,11 @@ static void Main() using (var c = new C()) { } } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestIntForeachLoop() - { - var code = """ + public Task TestIntForeachLoop() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -262,9 +207,7 @@ static void Main() foreach (int[||] i in new[] { 0 }) { } } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -272,15 +215,11 @@ static void Main() foreach (var i in new[] { 0 }) { } } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestIntForeachLoop2() - { - var code = """ + public Task TestIntForeachLoop2() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -288,9 +227,7 @@ static void Main() foreach ([|int|] i in new[] { 0 }) { } } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -298,15 +235,11 @@ static void Main() foreach (var i in new[] { 0 }) { } } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestIntForeachLoop3() - { - var code = """ + public Task TestIntForeachLoop3() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -314,9 +247,7 @@ static void Main() foreach (int [|i|] in new[] { 0 }) { } } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -324,15 +255,11 @@ static void Main() foreach (var i in new[] { 0 }) { } } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestIntForeachLoop4() - { - var code = """ + public Task TestIntForeachLoop4() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -340,9 +267,7 @@ static void Main() foreach ([|object|] i in new[] { new object() }) { } } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -350,15 +275,11 @@ static void Main() foreach (var i in new[] { new object() }) { } } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestIntDeconstruction() - { - var code = """ + public Task TestIntDeconstruction() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -366,9 +287,7 @@ static void Main() (int[||] i, var j) = (0, 1); } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -376,15 +295,11 @@ static void Main() (var i, var j) = (0, 1); } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact] - public async Task TestIntDeconstruction2() - { - var code = """ + public Task TestIntDeconstruction2() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -392,9 +307,7 @@ static void Main() (int[||] i, var j) = (0, 1); } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -402,15 +315,11 @@ static void Main() (var i, var j) = (0, 1); } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26923")] - public async Task NoSuggestionOnForeachCollectionExpression() - { - var code = """ + public Task NoSuggestionOnForeachCollectionExpression() + => TestMissingInRegularAndScriptAsync(""" using System; using System.Collections.Generic; @@ -424,16 +333,11 @@ static void Main(string[] args) } } } - """; - - // We never want to get offered here under any circumstances. - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35180")] - public async Task NoSuggestionWithinAnExpression() - { - var code = """ + public Task NoSuggestionWithinAnExpression() + => TestMissingInRegularAndScriptAsync(""" using System; using System; @@ -444,16 +348,11 @@ static void Main(string[] args) int a = 40 [||]+ 2; } } - """; - - // We never want to get offered here under any circumstances. - await TestMissingInRegularAndScriptAsync(code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42880")] - public async Task TestRefLocal1() - { - var code = """ + public Task TestRefLocal1() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -463,8 +362,7 @@ static void Main() [||]ref string rStr1 = ref str; } } - """; - var expected = """ + """, """ class C { static void Main() @@ -474,15 +372,11 @@ static void Main() ref var rStr1 = ref str; } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42880")] - public async Task TestRefLocal2() - { - var code = """ + public Task TestRefLocal2() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -492,9 +386,7 @@ static void Main() ref [||]string rStr1 = ref str; } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -504,15 +396,11 @@ static void Main() ref var rStr1 = ref str; } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42880")] - public async Task TestRefLocal3() - { - var code = """ + public Task TestRefLocal3() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -522,9 +410,7 @@ static void Main() ref string [||]rStr1 = ref str; } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -534,15 +420,11 @@ static void Main() ref var rStr1 = ref str; } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42880")] - public async Task TestRefReadonlyLocal1() - { - var code = """ + public Task TestRefReadonlyLocal1() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -552,9 +434,7 @@ static void Main() ref readonly [||]string rStr1 = ref str; } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -564,15 +444,11 @@ static void Main() ref readonly var rStr1 = ref str; } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42880")] - public async Task TestRefReadonlyLocal2() - { - var code = """ + public Task TestRefReadonlyLocal2() + => TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(""" class C { static void Main() @@ -582,9 +458,7 @@ static void Main() ref readonly string[||] rStr1 = ref str; } } - """; - - var expected = """ + """, """ class C { static void Main() @@ -594,10 +468,7 @@ static void Main() ref readonly var rStr1 = ref str; } } - """; - - await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); - } + """); private async Task TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(string initialMarkup, string expectedMarkup) { diff --git a/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyFixAllTests.cs b/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyFixAllTests.cs index 0f23cfbea386c..e9b5e055820d0 100644 --- a/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyFixAllTests.cs +++ b/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyFixAllTests.cs @@ -31,334 +31,344 @@ private OptionsCollection UseBlockBodyForMethodsAndAccessorsAndProperties }; [Fact] - public async Task FixAllInDocument() - { - await TestInRegularAndScript1Async( -@"class C -{ - void M1() - { - {|FixAllInDocument:|}Bar(); - } - - void M2() - { - Bar(); - } -}", -@"class C -{ - void M1() => Bar(); - - void M2() => Bar(); -}", parameters: new TestParameters(options: UseBlockBody)); - } + public Task FixAllInDocument() + => TestInRegularAndScript1Async( + """ + class C + { + void M1() + { + {|FixAllInDocument:|}Bar(); + } + + void M2() + { + Bar(); + } + } + """, + """ + class C + { + void M1() => Bar(); + + void M2() => Bar(); + } + """, parameters: new TestParameters(options: UseBlockBody)); [Fact] - public async Task FixAllInProject() - { - await TestInRegularAndScript1Async( -@" - - - -class C -{ - void M1() - { - {|FixAllInProject:|}Bar(); - } - - void M2() - { - Bar(); - } -} - - -class C2 -{ - void M3() - { - Bar(); - } -} - - - - -class C3 -{ - void M4() - { - Bar(); - } -} - - -", -@" - - - -class C -{ - void M1() => Bar(); - - void M2() => Bar(); -} - - -class C2 -{ - void M3() => Bar(); -} - - - - -class C3 -{ - void M4() - { - Bar(); - } -} - - -", parameters: new TestParameters(options: UseBlockBody)); - } + public Task FixAllInProject() + => TestInRegularAndScript1Async( + """ + + + + class C + { + void M1() + { + {|FixAllInProject:|}Bar(); + } + + void M2() + { + Bar(); + } + } + + + class C2 + { + void M3() + { + Bar(); + } + } + + + + + class C3 + { + void M4() + { + Bar(); + } + } + + + + """, + """ + + + + class C + { + void M1() => Bar(); + + void M2() => Bar(); + } + + + class C2 + { + void M3() => Bar(); + } + + + + + class C3 + { + void M4() + { + Bar(); + } + } + + + + """, parameters: new TestParameters(options: UseBlockBody)); [Fact] - public async Task FixAllInSolution() - { - await TestInRegularAndScript1Async( -@" - - - -class C -{ - void M1() - { - {|FixAllInSolution:|}Bar(); - } - - void M2() - { - Bar(); - } -} - - -class C2 -{ - void M3() - { - Bar(); - } -} - - - - -class C3 -{ - void M4() - { - Bar(); - } -} - - -", -@" - - - -class C -{ - void M1() => Bar(); - - void M2() => Bar(); -} - - -class C2 -{ - void M3() => Bar(); -} - - - - -class C3 -{ - void M4() => Bar(); -} - - -", parameters: new TestParameters(options: UseBlockBody)); - } + public Task FixAllInSolution() + => TestInRegularAndScript1Async( + """ + + + + class C + { + void M1() + { + {|FixAllInSolution:|}Bar(); + } + + void M2() + { + Bar(); + } + } + + + class C2 + { + void M3() + { + Bar(); + } + } + + + + + class C3 + { + void M4() + { + Bar(); + } + } + + + + """, + """ + + + + class C + { + void M1() => Bar(); + + void M2() => Bar(); + } + + + class C2 + { + void M3() => Bar(); + } + + + + + class C3 + { + void M4() => Bar(); + } + + + + """, parameters: new TestParameters(options: UseBlockBody)); [Fact] - public async Task FixAllInContainingMember() - { - await TestInRegularAndScript1Async( -@"class C -{ - void M1() - { - {|FixAllInContainingMember:|}Bar(); - } - - void M2() - { - Bar(); - } -} - -class C2 -{ - void M3() - { - Bar(); - } -}", -@"class C -{ - void M1() => Bar(); - - void M2() - { - Bar(); - } -} - -class C2 -{ - void M3() - { - Bar(); - } -}", parameters: new TestParameters(options: UseBlockBody)); - } + public Task FixAllInContainingMember() + => TestInRegularAndScript1Async( + """ + class C + { + void M1() + { + {|FixAllInContainingMember:|}Bar(); + } + + void M2() + { + Bar(); + } + } + + class C2 + { + void M3() + { + Bar(); + } + } + """, + """ + class C + { + void M1() => Bar(); + + void M2() + { + Bar(); + } + } + + class C2 + { + void M3() + { + Bar(); + } + } + """, parameters: new TestParameters(options: UseBlockBody)); [Fact] - public async Task FixAllInContainingType() - { - await TestInRegularAndScript1Async( -@"class C -{ - void M1() - { - {|FixAllInContainingType:|}Bar(); - } - - void M2() - { - Bar(); - } -} - -class C2 -{ - void M3() - { - Bar(); - } -}", -@"class C -{ - void M1() => Bar(); - - void M2() => Bar(); -} - -class C2 -{ - void M3() - { - Bar(); - } -}", parameters: new TestParameters(options: UseBlockBody)); - } + public Task FixAllInContainingType() + => TestInRegularAndScript1Async( + """ + class C + { + void M1() + { + {|FixAllInContainingType:|}Bar(); + } + + void M2() + { + Bar(); + } + } + + class C2 + { + void M3() + { + Bar(); + } + } + """, + """ + class C + { + void M1() => Bar(); + + void M2() => Bar(); + } + + class C2 + { + void M3() + { + Bar(); + } + } + """, parameters: new TestParameters(options: UseBlockBody)); [Theory, CombinatorialData] public async Task FixAllDoesNotFixDifferentSymbolKinds(bool forMethods) { var fixAllAnnotationForMethods = forMethods ? "{|FixAllInDocument:|}" : string.Empty; var fixAllAnnotationForProperties = forMethods ? string.Empty : "{|FixAllInDocument:|}"; - - var source = @$"class C -{{ - void M1() - {{ - {fixAllAnnotationForMethods}Bar(); - }} - - void M2() - {{ - Bar(); - }} - - int P1 - {{ - get - {{ - {fixAllAnnotationForProperties}return 0; - }} - }} - - int P2 - {{ - get - {{ - return 0; - }} - }} -}}"; - var fixedCodeForMethods = @"class C -{ - void M1() => Bar(); - - void M2() => Bar(); - - int P1 - { - get - { - return 0; - } - } - - int P2 - { - get - { - return 0; - } - } -}"; - var fixedCodeForProperties = @"class C -{ - void M1() - { - Bar(); - } - - void M2() - { - Bar(); - } - - int P1 => 0; - - int P2 => 0; -}"; + var fixedCodeForMethods = """ + class C + { + void M1() => Bar(); + + void M2() => Bar(); + + int P1 + { + get + { + return 0; + } + } + + int P2 + { + get + { + return 0; + } + } + } + """; + var fixedCodeForProperties = """ + class C + { + void M1() + { + Bar(); + } + + void M2() + { + Bar(); + } + + int P1 => 0; + + int P2 => 0; + } + """; var fixedCode = forMethods ? fixedCodeForMethods : fixedCodeForProperties; - await TestInRegularAndScript1Async(source, fixedCode, + await TestInRegularAndScript1Async($$""" + class C + { + void M1() + { + {{fixAllAnnotationForMethods}}Bar(); + } + + void M2() + { + Bar(); + } + + int P1 + { + get + { + {{fixAllAnnotationForProperties}}return 0; + } + } + + int P2 + { + get + { + return 0; + } + } + } + """, fixedCode, parameters: new TestParameters(options: UseBlockBodyForMethodsAndAccessorsAndProperties)); } } diff --git a/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForAccessorsRefactoringTests.cs b/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForAccessorsRefactoringTests.cs index 72809b1d75087..efe0e09214c24 100644 --- a/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForAccessorsRefactoringTests.cs +++ b/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForAccessorsRefactoringTests.cs @@ -80,9 +80,8 @@ private OptionsCollection UseBlockBodyForAccessors_BlockBodyForProperties_Disabl }; [Fact] - public async Task TestUpdatePropertyIfPropertyWantsBlockAndAccessorWantsExpression() - { - await TestInRegularAndScript1Async( + public Task TestUpdatePropertyIfPropertyWantsBlockAndAccessorWantsExpression() + => TestInRegularAndScript1Async( """ class C { @@ -102,12 +101,10 @@ class C } """, parameters: new TestParameters(options: UseExpressionBodyForAccessors_BlockBodyForProperties)); - } [Fact] - public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody2() - { - await TestMissingAsync( + public Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody2() + => TestMissingAsync( """ class C { @@ -121,12 +118,10 @@ int Goo } """, parameters: new TestParameters(options: UseExpressionBodyForAccessors_ExpressionBodyForProperties)); - } [Fact] - public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() + => TestInRegularAndScript1Async( """ class C { @@ -146,12 +141,10 @@ class C } """, parameters: new TestParameters(options: UseExpressionBodyForAccessors_BlockBodyForProperties_DisabledDiagnostic)); - } [Fact] - public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody2() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody2() + => TestInRegularAndScript1Async( """ class C { @@ -171,12 +164,10 @@ class C } """, parameters: new TestParameters(options: UseExpressionBodyForAccessors_ExpressionBodyForProperties_DisabledDiagnostic)); - } [Fact] - public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() + => TestInRegularAndScript1Async( """ class C { @@ -199,12 +190,10 @@ int Goo } """, parameters: new TestParameters(options: UseBlockBodyForAccessors_ExpressionBodyForProperties)); - } [Fact] - public async Task TestOfferExpressionBodyForPropertyIfPropertyAndAccessorBothPreferExpressions() - { - await TestInRegularAndScript1Async( + public Task TestOfferExpressionBodyForPropertyIfPropertyAndAccessorBothPreferExpressions() + => TestInRegularAndScript1Async( """ class C { @@ -224,12 +213,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBodyForAccessors_BlockBodyForProperties)); - } [Fact] - public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() - { - await TestMissingAsync( + public Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() + => TestMissingAsync( """ class C { @@ -237,12 +224,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBodyForAccessors_ExpressionBodyForProperties)); - } [Fact] - public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() + => TestInRegularAndScript1Async( """ class C { @@ -257,12 +242,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBodyForAccessors_BlockBodyForProperties_DisabledDiagnostic)); - } [Fact] - public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody2() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody2() + => TestInRegularAndScript1Async( """ class C { @@ -277,12 +260,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBodyForAccessors_ExpressionBodyForProperties_DisabledDiagnostic)); - } [Fact] - public async Task TestOfferedForPropertyIfUserPrefersBlockPropertiesAndHasBlockProperty() - { - await TestInRegularAndScript1Async( + public Task TestOfferedForPropertyIfUserPrefersBlockPropertiesAndHasBlockProperty() + => TestInRegularAndScript1Async( """ class C { @@ -297,12 +278,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBodyForAccessors_BlockBodyForProperties)); - } [Fact] - public async Task TestOfferForPropertyIfPropertyPrefersBlockButCouldBecomeExpressionBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferForPropertyIfPropertyPrefersBlockButCouldBecomeExpressionBody() + => TestInRegularAndScript1Async( """ class C { @@ -316,12 +295,10 @@ class C } """, parameters: new TestParameters(options: UseExpressionBodyForAccessors_BlockBodyForProperties)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20350")] - public async Task TestAccessorListFormatting() - { - await TestInRegularAndScript1Async( + public Task TestAccessorListFormatting() + => TestInRegularAndScript1Async( """ class C { @@ -341,12 +318,10 @@ int Goo } """, parameters: new TestParameters(options: UseExpressionBodyForAccessors_ExpressionBodyForProperties)); - } [Fact] - public async Task TestOfferedWithSelectionInsideExpressionBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedWithSelectionInsideExpressionBody() + => TestInRegularAndScript1Async( """ class C { @@ -369,12 +344,10 @@ int Goo } """, parameters: new TestParameters(options: UseBlockBodyForAccessors_ExpressionBodyForProperties)); - } [Fact] - public async Task TestNotOfferedWithSelectionOutsideExpressionBody() - { - await TestMissingAsync( + public Task TestNotOfferedWithSelectionOutsideExpressionBody() + => TestMissingAsync( """ class C { @@ -388,5 +361,4 @@ int Goo } """, parameters: new TestParameters(options: UseBlockBodyForAccessors_ExpressionBodyForProperties)); - } } diff --git a/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForConstructorsRefactoringTests.cs b/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForConstructorsRefactoringTests.cs index 08972dba997e6..696ac7a168395 100644 --- a/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForConstructorsRefactoringTests.cs +++ b/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForConstructorsRefactoringTests.cs @@ -35,9 +35,8 @@ private OptionsCollection UseBlockBodyDisabledDiagnostic => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.None)); [Fact] - public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() - { - await TestMissingAsync( + public Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() + => TestMissingAsync( """ class C { @@ -48,12 +47,10 @@ public C() } """, parameters: new TestParameters(options: UseExpressionBody)); - } [Fact] - public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() + => TestInRegularAndScript1Async( """ class C { @@ -70,12 +67,10 @@ class C } """, parameters: new TestParameters(options: UseExpressionBodyDisabledDiagnostic)); - } [Fact] - public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() + => TestInRegularAndScript1Async( """ class C { @@ -92,12 +87,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestNotOfferedInLambda() - { - await TestMissingAsync( + public Task TestNotOfferedInLambda() + => TestMissingAsync( """ class C { @@ -108,12 +101,10 @@ public C() } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() - { - await TestMissingAsync( + public Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() + => TestMissingAsync( """ class C { @@ -121,12 +112,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() + => TestInRegularAndScript1Async( """ class C { @@ -143,12 +132,10 @@ public C() } """, parameters: new TestParameters(options: UseBlockBodyDisabledDiagnostic)); - } [Fact] - public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() + => TestInRegularAndScript1Async( """ class C { @@ -165,12 +152,10 @@ public C() } """, parameters: new TestParameters(options: UseExpressionBody)); - } [Fact] - public async Task TestOfferedWithSelectionInsideExpressionBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedWithSelectionInsideExpressionBody() + => TestInRegularAndScript1Async( """ class C { @@ -187,12 +172,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestNotOfferedWithSelectionOutsideExpressionBody() - { - await TestMissingAsync( + public Task TestNotOfferedWithSelectionOutsideExpressionBody() + => TestMissingAsync( """ class C { @@ -203,5 +186,4 @@ public C() }|] """, parameters: new TestParameters(options: UseBlockBody)); - } } diff --git a/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForConversionOperatorsRefactoringTests.cs b/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForConversionOperatorsRefactoringTests.cs index ae2b785b46e51..b44c45f33b1e4 100644 --- a/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForConversionOperatorsRefactoringTests.cs +++ b/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForConversionOperatorsRefactoringTests.cs @@ -35,9 +35,8 @@ private OptionsCollection UseBlockBodyDisabledDiagnostic => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.None)); [Fact] - public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() - { - await TestMissingAsync( + public Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() + => TestMissingAsync( """ class C { @@ -48,12 +47,10 @@ public static implicit operator bool(C c1) } """, parameters: new TestParameters(options: UseExpressionBody)); - } [Fact] - public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() + => TestInRegularAndScript1Async( """ class C { @@ -70,12 +67,10 @@ class C } """, parameters: new TestParameters(options: UseExpressionBodyDisabledDiagnostic)); - } [Fact] - public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() + => TestInRegularAndScript1Async( """ class C { @@ -92,12 +87,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestNotOfferedInLambda() - { - await TestMissingAsync( + public Task TestNotOfferedInLambda() + => TestMissingAsync( """ class C { @@ -108,12 +101,10 @@ public static implicit operator bool(C c1) } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() - { - await TestMissingAsync( + public Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() + => TestMissingAsync( """ class C { @@ -121,12 +112,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() + => TestInRegularAndScript1Async( """ class C { @@ -143,12 +132,10 @@ public static implicit operator bool(C c1) } """, parameters: new TestParameters(options: UseBlockBodyDisabledDiagnostic)); - } [Fact] - public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() + => TestInRegularAndScript1Async( """ class C { @@ -165,12 +152,10 @@ public static implicit operator bool(C c1) } """, parameters: new TestParameters(options: UseExpressionBody)); - } [Fact] - public async Task TestOfferedWithSelectionInsideBlockBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedWithSelectionInsideBlockBody() + => TestInRegularAndScript1Async( """ class C { @@ -187,12 +172,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestNotOfferedWithSelectionOutsideBlockBody() - { - await TestMissingAsync( + public Task TestNotOfferedWithSelectionOutsideBlockBody() + => TestMissingAsync( """ class C { @@ -203,5 +186,4 @@ public static implicit operator bool(C c1) }|] """, parameters: new TestParameters(options: UseBlockBody)); - } } diff --git a/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForIndexersRefactoringTests.cs b/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForIndexersRefactoringTests.cs index e4de1cd487d02..8cf105eb75be6 100644 --- a/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForIndexersRefactoringTests.cs +++ b/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForIndexersRefactoringTests.cs @@ -36,9 +36,8 @@ private OptionsCollection UseBlockBodyDisabledDiagnostic => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.None)); [Fact] - public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() - { - await TestMissingAsync( + public Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() + => TestMissingAsync( """ class C { @@ -52,12 +51,10 @@ int this[int i] } """, parameters: new TestParameters(options: UseExpressionBody)); - } [Fact] - public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() + => TestInRegularAndScript1Async( """ class C { @@ -77,12 +74,10 @@ class C } """, parameters: new TestParameters(options: UseExpressionBodyDisabledDiagnostic)); - } [Fact] - public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() + => TestInRegularAndScript1Async( """ class C { @@ -102,12 +97,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestNotOfferedInLambda() - { - await TestMissingAsync( + public Task TestNotOfferedInLambda() + => TestMissingAsync( """ class C { @@ -121,12 +114,10 @@ Action Goo[int i] } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() - { - await TestMissingAsync( + public Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() + => TestMissingAsync( """ class C { @@ -134,12 +125,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() + => TestInRegularAndScript1Async( """ class C { @@ -159,12 +148,10 @@ int this[int i] } """, parameters: new TestParameters(options: UseBlockBodyDisabledDiagnostic)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20363")] - public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() + => TestInRegularAndScript1Async( """ class C { @@ -184,12 +171,10 @@ int this[int i] } """, parameters: new TestParameters(options: UseExpressionBody)); - } [Fact] - public async Task TestOfferedWithSelectionInsideBlockBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedWithSelectionInsideBlockBody() + => TestInRegularAndScript1Async( """ class C { @@ -209,12 +194,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestNotOfferedWithSelectionOutsideBlockBody() - { - await TestMissingAsync( + public Task TestNotOfferedWithSelectionOutsideBlockBody() + => TestMissingAsync( """ class C { @@ -228,5 +211,4 @@ int this[int i] }|] """, parameters: new TestParameters(options: UseBlockBody)); - } } diff --git a/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForLocalFunctionsRefactoringTests.cs b/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForLocalFunctionsRefactoringTests.cs index a5959fe2d9b27..21b15543956ec 100644 --- a/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForLocalFunctionsRefactoringTests.cs +++ b/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForLocalFunctionsRefactoringTests.cs @@ -35,9 +35,8 @@ private OptionsCollection UseBlockBodyDisabledDiagnostic => Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.None)); [Fact] - public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() - { - await TestMissingAsync( + public Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() + => TestMissingAsync( """ class C { @@ -51,12 +50,10 @@ void Bar() } """, parameters: new TestParameters(options: UseExpressionBody)); - } [Fact] - public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() + => TestInRegularAndScript1Async( """ class C { @@ -79,12 +76,10 @@ void Goo() } """, parameters: new TestParameters(options: UseExpressionBodyDisabledDiagnostic)); - } [Fact] - public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() + => TestInRegularAndScript1Async( """ class C { @@ -107,12 +102,10 @@ void Goo() } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() - { - await TestMissingAsync( + public Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() + => TestMissingAsync( """ class C { @@ -123,12 +116,10 @@ void Goo() } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() + => TestInRegularAndScript1Async( """ class C { @@ -151,12 +142,10 @@ void Bar() } """, parameters: new TestParameters(options: UseBlockBodyDisabledDiagnostic)); - } [Fact] - public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() + => TestInRegularAndScript1Async( """ class C { @@ -179,12 +168,10 @@ void Bar() } """, parameters: new TestParameters(options: UseExpressionBody)); - } [Fact] - public async Task TestOfferedWithSelectionInsideBlockBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedWithSelectionInsideBlockBody() + => TestInRegularAndScript1Async( """ class C { @@ -207,12 +194,10 @@ void Goo() } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestNotOfferedWithSelectionOutsideBlockBody() - { - await TestMissingAsync( + public Task TestNotOfferedWithSelectionOutsideBlockBody() + => TestMissingAsync( """ class C { @@ -226,5 +211,4 @@ void Bar() } """, parameters: new TestParameters(options: UseBlockBody)); - } } diff --git a/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForMethodsRefactoringTests.cs b/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForMethodsRefactoringTests.cs index f4d5d8b20b738..d3eaaf23076c1 100644 --- a/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForMethodsRefactoringTests.cs +++ b/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForMethodsRefactoringTests.cs @@ -34,9 +34,8 @@ private OptionsCollection UseBlockBodyDisabledDiagnostic => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.None)); [Fact] - public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() - { - await TestMissingAsync( + public Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() + => TestMissingAsync( """ class C { @@ -47,12 +46,10 @@ void Goo() } """, parameters: new TestParameters(options: UseExpressionBody)); - } [Fact] - public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() + => TestInRegularAndScript1Async( """ class C { @@ -69,12 +66,10 @@ class C } """, parameters: new TestParameters(options: UseExpressionBodyDisabledDiagnostic)); - } [Fact] - public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() + => TestInRegularAndScript1Async( """ class C { @@ -91,12 +86,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestNotOfferedInLambda() - { - await TestMissingAsync( + public Task TestNotOfferedInLambda() + => TestMissingAsync( """ class C { @@ -107,12 +100,10 @@ Action Goo() } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() - { - await TestMissingAsync( + public Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() + => TestMissingAsync( """ class C { @@ -120,12 +111,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() + => TestInRegularAndScript1Async( """ class C { @@ -142,12 +131,10 @@ void Goo() } """, parameters: new TestParameters(options: UseBlockBodyDisabledDiagnostic)); - } [Fact] - public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() + => TestInRegularAndScript1Async( """ class C { @@ -164,12 +151,10 @@ void Goo() } """, parameters: new TestParameters(options: UseExpressionBody)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25501")] - public async Task TestOfferedAtStartOfMethod() - { - await TestInRegularAndScript1Async( + public Task TestOfferedAtStartOfMethod() + => TestInRegularAndScript1Async( """ class C { @@ -186,12 +171,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25501")] - public async Task TestOfferedBeforeMethodOnSameLine() - { - await TestInRegularAndScript1Async( + public Task TestOfferedBeforeMethodOnSameLine() + => TestInRegularAndScript1Async( """ class C { @@ -208,12 +191,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25501")] - public async Task TestOfferedBeforeAttributes() - { - await TestInRegularAndScript1Async( + public Task TestOfferedBeforeAttributes() + => TestInRegularAndScript1Async( """ class C { @@ -232,12 +213,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25501")] - public async Task TestNotOfferedBeforeComments() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOfferedBeforeComments() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -249,12 +228,10 @@ void Goo() } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/25501")] - public async Task TestNotOfferedInComments() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOfferedInComments() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -266,12 +243,10 @@ void Goo() } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/53532")] - public async Task TestTriviaOnArrow1() - { - await TestInRegularAndScript1Async( + public Task TestTriviaOnArrow1() + => TestInRegularAndScript1Async( """ class C { @@ -291,12 +266,10 @@ void M() } """, parameters: new TestParameters(options: UseExpressionBody)); - } [Fact] - public async Task TestOfferedWithSelectionInsideBlockBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedWithSelectionInsideBlockBody() + => TestInRegularAndScript1Async( """ class C { @@ -313,12 +286,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestNotOfferedWithSelectionOutsideBlockBody() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOfferedWithSelectionOutsideBlockBody() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -329,12 +300,10 @@ void Goo() }|] """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestOfferedWithSelectionInsideExpressionBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedWithSelectionInsideExpressionBody() + => TestInRegularAndScript1Async( """ class C { @@ -351,12 +320,10 @@ void Goo() } """, parameters: new TestParameters(options: UseExpressionBody)); - } [Fact] - public async Task TestNotOfferedWithSelectionOutsideExpressionBody() - { - await TestMissingInRegularAndScriptAsync( + public Task TestNotOfferedWithSelectionOutsideExpressionBody() + => TestMissingInRegularAndScriptAsync( """ class C { @@ -364,5 +331,4 @@ class C }|] """, parameters: new TestParameters(options: UseExpressionBody)); - } } diff --git a/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForOperatorsRefactoringTests.cs b/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForOperatorsRefactoringTests.cs index 2fc88cbefe201..f13173df5d874 100644 --- a/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForOperatorsRefactoringTests.cs +++ b/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForOperatorsRefactoringTests.cs @@ -35,9 +35,8 @@ private OptionsCollection UseBlockBodyDisabledDiagnostic => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.None)); [Fact] - public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() - { - await TestMissingAsync( + public Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() + => TestMissingAsync( """ class C { @@ -48,12 +47,10 @@ class C } """, parameters: new TestParameters(options: UseExpressionBody)); - } [Fact] - public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() + => TestInRegularAndScript1Async( """ class C { @@ -70,12 +67,10 @@ class C } """, parameters: new TestParameters(options: UseExpressionBodyDisabledDiagnostic)); - } [Fact] - public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() + => TestInRegularAndScript1Async( """ class C { @@ -92,12 +87,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestNotOfferedInLambda() - { - await TestMissingAsync( + public Task TestNotOfferedInLambda() + => TestMissingAsync( """ class C { @@ -108,12 +101,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() - { - await TestMissingAsync( + public Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() + => TestMissingAsync( """ class C { @@ -121,12 +112,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() + => TestInRegularAndScript1Async( """ class C { @@ -143,12 +132,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBodyDisabledDiagnostic)); - } [Fact] - public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() + => TestInRegularAndScript1Async( """ class C { @@ -165,12 +152,10 @@ class C } """, parameters: new TestParameters(options: UseExpressionBody)); - } [Fact] - public async Task TestOfferedWithSelectionInsideBlockBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedWithSelectionInsideBlockBody() + => TestInRegularAndScript1Async( """ class C { @@ -187,12 +172,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestNotOfferedWithSelectionOutsideBlockBody() - { - await TestMissingAsync( + public Task TestNotOfferedWithSelectionOutsideBlockBody() + => TestMissingAsync( """ class C { @@ -203,5 +186,4 @@ class C }|] """, parameters: new TestParameters(options: UseBlockBody)); - } } diff --git a/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForPropertiesRefactoringTests.cs b/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForPropertiesRefactoringTests.cs index 6a66c9abc35ae..498159419df1b 100644 --- a/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForPropertiesRefactoringTests.cs +++ b/src/Features/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForPropertiesRefactoringTests.cs @@ -74,9 +74,8 @@ private OptionsCollection UseBlockBodyForAccessors_BlockBodyForProperties_Disabl }; [Fact] - public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() - { - await TestMissingAsync( + public Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() + => TestMissingAsync( """ class C { @@ -90,12 +89,10 @@ int Goo } """, parameters: new TestParameters(options: UseExpressionBodyForAccessors_ExpressionBodyForProperties)); - } [Fact] - public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() + => TestInRegularAndScript1Async( """ class C { @@ -115,12 +112,10 @@ class C } """, parameters: new TestParameters(options: UseExpressionBodyForAccessors_ExpressionBodyForProperties_DisabledDiagnostic)); - } [Fact] - public async Task TestUpdateAccessorIfAccessWantsBlockAndPropertyWantsExpression() - { - await TestInRegularAndScript1Async( + public Task TestUpdateAccessorIfAccessWantsBlockAndPropertyWantsExpression() + => TestInRegularAndScript1Async( """ class C { @@ -143,12 +138,10 @@ int Goo } """, parameters: new TestParameters(options: UseBlockBodyForAccessors_ExpressionBodyForProperties)); - } [Fact] - public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() + => TestInRegularAndScript1Async( """ class C { @@ -168,12 +161,10 @@ class C } """, parameters: new TestParameters(options: UseExpressionBodyForAccessors_BlockBodyForProperties)); - } [Fact] - public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody2() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody2() + => TestInRegularAndScript1Async( """ class C { @@ -193,12 +184,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBodyForAccessors_BlockBodyForProperties)); - } [Fact] - public async Task TestNotOfferedInLambda() - { - await TestMissingAsync( + public Task TestNotOfferedInLambda() + => TestMissingAsync( """ class C { @@ -212,12 +201,10 @@ Action Goo } """, parameters: new TestParameters(options: UseBlockBodyForAccessors_BlockBodyForProperties)); - } [Fact] - public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() - { - await TestMissingAsync( + public Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() + => TestMissingAsync( """ class C { @@ -225,12 +212,10 @@ class C } """, parameters: new TestParameters(options: UseExpressionBodyForAccessors_BlockBodyForProperties)); - } [Fact] - public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody2() - { - await TestMissingAsync( + public Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody2() + => TestMissingAsync( """ class C { @@ -238,12 +223,10 @@ class C } """, parameters: new TestParameters(options: UseBlockBodyForAccessors_BlockBodyForProperties)); - } [Fact] - public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() + => TestInRegularAndScript1Async( """ class C { @@ -263,12 +246,10 @@ int Goo } """, parameters: new TestParameters(options: UseExpressionBodyForAccessors_BlockBodyForProperties_DisabledDiagnostic)); - } [Fact] - public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody2() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody2() + => TestInRegularAndScript1Async( """ class C { @@ -288,12 +269,10 @@ int Goo } """, parameters: new TestParameters(options: UseBlockBodyForAccessors_BlockBodyForProperties_DisabledDiagnostic)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20363")] - public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() + => TestInRegularAndScript1Async( """ class C { @@ -313,12 +292,10 @@ int Goo } """, parameters: new TestParameters(options: UseExpressionBodyForAccessors_ExpressionBodyForProperties)); - } [Fact] - public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody2() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody2() + => TestInRegularAndScript1Async( """ class C { @@ -338,12 +315,10 @@ int Goo } """, parameters: new TestParameters(options: UseBlockBodyForAccessors_ExpressionBodyForProperties)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20360")] - public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody_CSharp6() - { - await TestAsync( + public Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody_CSharp6() + => TestAsync( """ class C { @@ -364,12 +339,10 @@ int Goo """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6), options: UseExpressionBodyForAccessors_ExpressionBodyForProperties); - } [Fact] - public async Task TestOfferedWithSelectionInsideBlockBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedWithSelectionInsideBlockBody() + => TestInRegularAndScript1Async( """ class C { @@ -389,12 +362,10 @@ class C } """, parameters: new TestParameters(options: UseExpressionBodyForAccessors_BlockBodyForProperties)); - } [Fact] - public async Task TestNotOfferedWithSelectionOutsideBlockBody() - { - await TestMissingAsync( + public Task TestNotOfferedWithSelectionOutsideBlockBody() + => TestMissingAsync( """ class C { @@ -408,5 +379,4 @@ int Goo }|] """, parameters: new TestParameters(options: UseExpressionBodyForAccessors_BlockBodyForProperties)); - } } diff --git a/src/Features/CSharpTest/UseExpressionBodyForLambda/UseExpressionBodyForLambdasRefactoringTests.cs b/src/Features/CSharpTest/UseExpressionBodyForLambda/UseExpressionBodyForLambdasRefactoringTests.cs index fed4ea0b006aa..c8f6ab596247d 100644 --- a/src/Features/CSharpTest/UseExpressionBodyForLambda/UseExpressionBodyForLambdasRefactoringTests.cs +++ b/src/Features/CSharpTest/UseExpressionBodyForLambda/UseExpressionBodyForLambdasRefactoringTests.cs @@ -35,9 +35,8 @@ private OptionsCollection UseBlockBodyDisabledDiagnostic => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedLambdas, CSharpCodeStyleOptions.NeverWithSilentEnforcement); [Fact] - public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() - { - await TestMissingAsync( + public Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() + => TestMissingAsync( """ using System; @@ -52,12 +51,10 @@ void Goo() } } """, parameters: new TestParameters(options: UseExpressionBody)); - } [Fact] - public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() + => TestInRegularAndScript1Async( """ using System; @@ -83,12 +80,10 @@ void Goo() } } """, parameters: new TestParameters(options: UseExpressionBodyDisabledDiagnostic)); - } [Fact] - public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() + => TestInRegularAndScript1Async( """ using System; @@ -114,12 +109,10 @@ void Goo() } } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestNotOfferedInMethod() - { - await TestMissingAsync( + public Task TestNotOfferedInMethod() + => TestMissingAsync( """ class C { @@ -129,12 +122,10 @@ class C } } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() - { - await TestMissingAsync( + public Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() + => TestMissingAsync( """ using System; @@ -146,12 +137,10 @@ void Goo() } } """, parameters: new TestParameters(options: UseBlockBody)); - } [Fact] - public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() + => TestInRegularAndScript1Async( """ using System; @@ -177,12 +166,10 @@ void Goo() } } """, parameters: new TestParameters(options: UseBlockBodyDisabledDiagnostic)); - } [Fact] - public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() - { - await TestInRegularAndScript1Async( + public Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() + => TestInRegularAndScript1Async( """ using System; @@ -208,12 +195,10 @@ void Goo() } } """, parameters: new TestParameters(options: UseExpressionBody)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/74137")] - public async Task TestNotWithPreprocessorDirectives() - { - await TestMissingAsync( + public Task TestNotWithPreprocessorDirectives() + => TestMissingAsync( """ app.UseSwaggerUI(c [||]=> { @@ -224,5 +209,4 @@ await TestMissingAsync( #endif }); """, parameters: new TestParameters(options: UseExpressionBodyDisabledDiagnostic)); - } } diff --git a/src/Features/CSharpTest/UseNamedArguments/UseNamedArgumentsTests.cs b/src/Features/CSharpTest/UseNamedArguments/UseNamedArgumentsTests.cs index f30b9d432e41e..2371035098a33 100644 --- a/src/Features/CSharpTest/UseNamedArguments/UseNamedArgumentsTests.cs +++ b/src/Features/CSharpTest/UseNamedArguments/UseNamedArgumentsTests.cs @@ -56,182 +56,135 @@ private static Task TestWithCSharp7_3(string initialMarkup, string expectedMarku } [Fact] - public async Task TestFirstArgument() - { - await TestWithCSharp7( + public Task TestFirstArgument() + => TestWithCSharp7( @"class C { void M(int arg1, int arg2) => M([||]1, 2); }", @"class C { void M(int arg1, int arg2) => M(arg1: 1, arg2: 2); }"); - } [Fact] - public async Task TestFirstArgument_CSharp7_2_FirstOption() - { - // First option only adds the named argument to the specific parameter you're on. - await TestWithCSharp7_2( + public Task TestFirstArgument_CSharp7_2_FirstOption() + => TestWithCSharp7_2( @"class C { void M(int arg1, int arg2) => M([||]1, 2); }", @"class C { void M(int arg1, int arg2) => M(arg1: 1, 2); }"); - } [Fact] - public async Task TestFirstArgument_CSharp7_2_SecondOption() - { - // Second option only adds the named argument to parameter you're on and all trailing parameters. - await TestWithCSharp7_2( + public Task TestFirstArgument_CSharp7_2_SecondOption() + => TestWithCSharp7_2( @"class C { void M(int arg1, int arg2) => M([||]1, 2); }", @"class C { void M(int arg1, int arg2) => M(arg1: 1, arg2: 2); }", index: 1); - } [Fact] - public async Task TestNonFirstArgument() - { - await TestWithCSharp7( + public Task TestNonFirstArgument() + => TestWithCSharp7( @"class C { void M(int arg1, int arg2) => M(1, [||]2); }", @"class C { void M(int arg1, int arg2) => M(1, arg2: 2); }"); - } [Fact] - public async Task TestNonFirstArgument_CSharp_7_2() - { - // Because we're on the last argument, we should only offer one refactoring to the user. - var initialMarkup = @"class C { void M(int arg1, int arg2) => M(1, [||]2); }"; - await new VerifyCS.Test + public Task TestNonFirstArgument_CSharp_7_2() + => new VerifyCS.Test { - TestCode = initialMarkup, + TestCode = @"class C { void M(int arg1, int arg2) => M(1, [||]2); }", FixedCode = @"class C { void M(int arg1, int arg2) => M(1, arg2: 2); }", LanguageVersion = LanguageVersion.CSharp7_2, ExactActionSetOffered = [string.Format(FeaturesResources.Add_argument_name_0, "arg2")], }.RunAsync(); - } [Fact] - public async Task TestDelegate() - { - await TestWithCSharp7( + public Task TestDelegate() + => TestWithCSharp7( @"class C { void M(System.Action f) => f([||]1); }", @"class C { void M(System.Action f) => f(obj: 1); }"); - } [Fact] - public async Task TestConditionalMethod() - { - await TestWithCSharp7( + public Task TestConditionalMethod() + => TestWithCSharp7( @"class C { void M(int arg1, int arg2) => this?.M([||]1, 2); }", @"class C { void M(int arg1, int arg2) => this?.M(arg1: 1, arg2: 2); }"); - } [Fact] - public async Task TestConditionalIndexer() - { - await TestWithCSharp7( + public Task TestConditionalIndexer() + => TestWithCSharp7( @"class C { int? this[int arg1, int arg2] => this?[[||]1, 2]; }", @"class C { int? this[int arg1, int arg2] => this?[arg1: 1, arg2: 2]; }"); - } [Fact] - public async Task TestThisConstructorInitializer() - { - await TestWithCSharp7( + public Task TestThisConstructorInitializer() + => TestWithCSharp7( @"class C { C(int arg1, int arg2) {} C() : this([||]1, 2) {} }", @"class C { C(int arg1, int arg2) {} C() : this(arg1: 1, arg2: 2) {} }"); - } [Fact] - public async Task TestBaseConstructorInitializer() - { - await TestWithCSharp7( + public Task TestBaseConstructorInitializer() + => TestWithCSharp7( @"class C { public C(int arg1, int arg2) {} } class D : C { D() : base([||]1, 2) {} }", @"class C { public C(int arg1, int arg2) {} } class D : C { D() : base(arg1: 1, arg2: 2) {} }"); - } [Fact] - public async Task TestConstructor() - { - await TestWithCSharp7( + public Task TestConstructor() + => TestWithCSharp7( @"class C { C(int arg1, int arg2) { new C([||]1, 2); } }", @"class C { C(int arg1, int arg2) { new C(arg1: 1, arg2: 2); } }"); - } [Fact] - public async Task TestIndexer() - { - await TestWithCSharp7( + public Task TestIndexer() + => TestWithCSharp7( @"class C { char M(string arg1) => arg1[[||]0]; }", @"class C { char M(string arg1) => arg1[index: 0]; }"); - } [Fact] - public async Task TestMissingOnArrayIndexer() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnArrayIndexer() + => TestMissingInRegularAndScriptAsync( @"class C { int M(int[] arg1) => arg1[[||]0]; }"); - } [Fact] - public async Task TestMissingOnConditionalArrayIndexer() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnConditionalArrayIndexer() + => TestMissingInRegularAndScriptAsync( @"class C { int? M(int[] arg1) => arg1?[[||]0]; }"); - } [Fact] - public async Task TestMissingOnEmptyArgumentList() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnEmptyArgumentList() + => TestMissingInRegularAndScriptAsync( @"class C { void M() => M([||]); }"); - } [Fact] - public async Task TestMissingOnExistingArgumentName() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnExistingArgumentName() + => TestMissingInRegularAndScriptAsync( @"class C { void M(int arg) => M([||]arg: 1); }"); - } [Fact] - public async Task TestEmptyParams() - { - await TestWithCSharp7( + public Task TestEmptyParams() + => TestWithCSharp7( @"class C { void M(int arg1, params int[] arg2) => M([||]1); }", @"class C { void M(int arg1, params int[] arg2) => M(arg1: 1); }"); - } [Fact] - public async Task TestSingleParams() - { - await TestWithCSharp7( + public Task TestSingleParams() + => TestWithCSharp7( @"class C { void M(int arg1, params int[] arg2) => M([||]1, 2); }", @"class C { void M(int arg1, params int[] arg2) => M(arg1: 1, arg2: 2); }"); - } [Fact] - public async Task TestNamedParams() - { - await TestWithCSharp7( + public Task TestNamedParams() + => TestWithCSharp7( @"class C { void M(int arg1, params int[] arg2) => M([||]1, arg2: new int[0]); }", @"class C { void M(int arg1, params int[] arg2) => M(arg1: 1, arg2: new int[0]); }"); - } [Fact] - public async Task TestExistingArgumentNames() - { - await TestWithCSharp7( + public Task TestExistingArgumentNames() + => TestWithCSharp7( @"class C { void M(int arg1, int arg2) => M([||]1, arg2: 2); }", @"class C { void M(int arg1, int arg2) => M(arg1: 1, arg2: 2); }"); - } [Fact] - public async Task TestExistingUnorderedArgumentNames() - { - await TestWithCSharp7( + public Task TestExistingUnorderedArgumentNames() + => TestWithCSharp7( @"class C { void M(int arg1, int arg2, int arg3) => M([||]1, arg3: 3, arg2: 2); }", @"class C { void M(int arg1, int arg2, int arg3) => M(arg1: 1, arg3: 3, arg2: 2); }"); - } [Fact] - public async Task TestPreserveTrivia() - { - await TestWithCSharp7( + public Task TestPreserveTrivia() + => TestWithCSharp7( """ class C { void M(int arg1, ref int arg2) => M( @@ -250,19 +203,15 @@ class C { void M(int arg1, ref int arg2) => M( ); } """); - } [Fact] - public async Task TestMissingOnNameOf() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingOnNameOf() + => TestMissingInRegularAndScriptAsync( @"class C { string M() => nameof([||]M); }"); - } [Fact] - public async Task TestAttribute() - { - await TestWithCSharp7( + public Task TestAttribute() + => TestWithCSharp7( """ [C([||]1, 2)] class C : System.Attribute { public C(int arg1, int arg2) {} } @@ -271,12 +220,10 @@ class C : System.Attribute { public C(int arg1, int arg2) {} } [C(arg1: 1, arg2: 2)] class C : System.Attribute { public C(int arg1, int arg2) {} } """); - } [Fact] - public async Task TestAttributeWithNamedProperties() - { - await TestWithCSharp7( + public Task TestAttributeWithNamedProperties() + => TestWithCSharp7( """ [C([||]1, P = 2)] class C : System.Attribute { public C(int arg1) {} public int P { get; set; } } @@ -285,12 +232,10 @@ class C : System.Attribute { public C(int arg1) {} public int P { get; set; } } [C(arg1: 1, P = 2)] class C : System.Attribute { public C(int arg1) {} public int P { get; set; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35525")] - public async Task TestAvailableOnSelectionOfArgument1() - { - await TestWithCSharp7( + public Task TestAvailableOnSelectionOfArgument1() + => TestWithCSharp7( """ class C { @@ -305,12 +250,10 @@ void M(int arg1, int arg2) => M(arg1: 1 + 2, arg2: 2); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18848")] - public async Task TestAvailableOnFirstTokenOfArgument1() - { - await TestWithCSharp7( + public Task TestAvailableOnFirstTokenOfArgument1() + => TestWithCSharp7( """ class C { @@ -325,12 +268,10 @@ void M(int arg1, int arg2) => M(arg1: 1 + 2, arg2: 2); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18848")] - public async Task TestAvailableOnFirstTokenOfArgument2() - { - await TestWithCSharp7( + public Task TestAvailableOnFirstTokenOfArgument2() + => TestWithCSharp7( """ class C { @@ -345,12 +286,10 @@ void M(int arg1, int arg2) => M(arg1: 1 + 2, arg2: 2); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18848")] - public async Task TestNotMissingWhenInsideSingleLineArgument1() - { - await TestWithCSharp7( + public Task TestNotMissingWhenInsideSingleLineArgument1() + => TestWithCSharp7( """ using System; @@ -369,12 +308,10 @@ void M(Action arg1, int arg2) => M(arg1: () => { }, arg2: 2); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18848")] - public async Task TestNotMissingWhenInsideSingleLineArgument2_CSharp7() - { - await TestWithCSharp7( + public Task TestNotMissingWhenInsideSingleLineArgument2_CSharp7() + => TestWithCSharp7( """ class C { @@ -389,12 +326,10 @@ void M(int arg1, int arg2) => M(arg1: 1 + 2, arg2: 2); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18848")] - public async Task TestNotMissingWhenInsideSingleLineArgument2() - { - await TestWithCSharp7_3( + public Task TestNotMissingWhenInsideSingleLineArgument2() + => TestWithCSharp7_3( """ class C { @@ -409,12 +344,10 @@ void M(int arg1, int arg2) => M(arg1: 1 + 2, 2); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18848")] - public async Task TestNotMissingWhenInsideSingleLineArgument3() - { - await TestWithCSharp7( + public Task TestNotMissingWhenInsideSingleLineArgument3() + => TestWithCSharp7( """ using System; @@ -433,12 +366,10 @@ void M(Action arg1, int arg2) => M(arg1: () => { }, arg2: 2); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18848")] - public async Task TestNotMissingWhenInsideSingleLineArgument4() - { - await TestWithCSharp7( + public Task TestNotMissingWhenInsideSingleLineArgument4() + => TestWithCSharp7( """ class C { @@ -453,12 +384,10 @@ void M(int arg1, int arg2) => M(arg1: 1 + 2, arg2: 2); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18848")] - public async Task TestMissingNotOnStartingLineOfArgument1() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingNotOnStartingLineOfArgument1() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -470,12 +399,10 @@ void M(Action arg1, int arg2) }, 2); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/18848")] - public async Task TestMissingWithSelection() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingWithSelection() + => TestMissingInRegularAndScriptAsync( """ using System; @@ -485,12 +412,10 @@ void M(Action arg1, int arg2) => M([|{|CS1503:1 + 2|}|], 3); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19175")] - public async Task TestCaretPositionAtTheEnd1() - { - await TestWithCSharp7( + public Task TestCaretPositionAtTheEnd1() + => TestWithCSharp7( """ class C { @@ -503,12 +428,10 @@ class C void M(int arg1) => M(arg1: arg1); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19175")] - public async Task TestCaretPositionAtTheEnd2() - { - await TestWithCSharp7( + public Task TestCaretPositionAtTheEnd2() + => TestWithCSharp7( """ class C { @@ -521,12 +444,10 @@ class C void M(int arg1, int arg2) => M(arg1: arg1, arg2: arg2); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19758")] - public async Task TestOnTuple() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestOnTuple() + => VerifyCS.VerifyRefactoringAsync( """ using System.Linq; class C @@ -541,12 +462,10 @@ class C void M(int[] arr) => arr.Zip(arr, resultSelector: (p1, p2) => (p1, p2)); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23269")] - public async Task TestCharacterEscape1() - { - await TestWithCSharp7( + public Task TestCharacterEscape1() + => TestWithCSharp7( """ class C { @@ -559,12 +478,10 @@ class C void M(int @default, int @params) => M(@default: 1, @params: 2); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/23269")] - public async Task TestCharacterEscape2() - { - await TestWithCSharp7( + public Task TestCharacterEscape2() + => TestWithCSharp7( """ [C([||]1, 2)] class C : System.Attribute @@ -579,26 +496,20 @@ class C : System.Attribute public C(int @default, int @params) {} } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39852")] - public async Task TestMissingForImplicitRangeIndexer() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingForImplicitRangeIndexer() + => TestMissingInRegularAndScriptAsync( @"class C { string M(string arg1) => arg1[[||]1..^1]; }" + TestSources.Range + TestSources.Index); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39852")] - public async Task TestMissingForImplicitIndexIndexer() - { - await TestMissingInRegularAndScriptAsync( + public Task TestMissingForImplicitIndexIndexer() + => TestMissingInRegularAndScriptAsync( @"class C { string M(string arg1) => {|CS0029:arg1[[||]^1]|}; }" + TestSources.Index); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39852")] - public async Task TestForRealRangeIndexer() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestForRealRangeIndexer() + => VerifyCS.VerifyRefactoringAsync( """ using System; class C { @@ -613,12 +524,10 @@ class C { int M(C arg1) => arg1[range: 1..^1]; } """ + TestSources.Range + TestSources.Index); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39852")] - public async Task TestForRealIndexIndexer() - { - await VerifyCS.VerifyRefactoringAsync( + public Task TestForRealIndexIndexer() + => VerifyCS.VerifyRefactoringAsync( """ using System; class C { @@ -633,25 +542,19 @@ class C { int M(C arg1) => arg1[index: ^1]; } """ + TestSources.Index); - } [Fact] - public async Task TestNoTrailingArgumentsToName() - { - // Because we're on the last argument that doesn't have a name, we should only offer one refactoring to the user. - var initialMarkup = @"class C { void M(int arg1, int arg2, int arg3) => M(1, [||]2, arg3: 3); }"; - await new VerifyCS.Test + public Task TestNoTrailingArgumentsToName() + => new VerifyCS.Test { - TestCode = initialMarkup, + TestCode = @"class C { void M(int arg1, int arg2, int arg3) => M(1, [||]2, arg3: 3); }", FixedCode = @"class C { void M(int arg1, int arg2, int arg3) => M(1, arg2: 2, arg3: 3); }", ExactActionSetOffered = [string.Format(FeaturesResources.Add_argument_name_0, "arg2")], }.RunAsync(); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63362")] - public async Task TestTrivia() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task TestTrivia() + => VerifyCS.VerifyRefactoringAsync(""" class C { static void F(string x, string y) @@ -678,12 +581,10 @@ static void F(string x, string y) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63362")] - public async Task TestTrivia_Attribute() - { - await VerifyCS.VerifyRefactoringAsync(""" + public Task TestTrivia_Attribute() + => VerifyCS.VerifyRefactoringAsync(""" [My( // Comment [||]null/*comment2*/, @@ -702,5 +603,4 @@ class MyAttribute : System.Attribute public MyAttribute(string x, string y) { } } """); - } } diff --git a/src/Features/CSharpTest/UseNameofInAttribute/UseNameofInAttributeTests.cs b/src/Features/CSharpTest/UseNameofInAttribute/UseNameofInAttributeTests.cs index ef566b7315788..ee607474e09d1 100644 --- a/src/Features/CSharpTest/UseNameofInAttribute/UseNameofInAttributeTests.cs +++ b/src/Features/CSharpTest/UseNameofInAttribute/UseNameofInAttributeTests.cs @@ -19,9 +19,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseNameofInAttribute; public sealed class UseNameofInAttributeTests { [Fact] - public async Task TestOnMethod() - { - await new VerifyCS.Test + public Task TestOnMethod() + => new VerifyCS.Test { TestCode = """ using System.Diagnostics.CodeAnalysis; @@ -44,12 +43,10 @@ class C LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact] - public async Task TestWithInterpolation() - { - await new VerifyCS.Test + public Task TestWithInterpolation() + => new VerifyCS.Test { TestCode = """ using System.Diagnostics.CodeAnalysis; @@ -72,12 +69,10 @@ class C LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact] - public async Task TestTrivia() - { - await new VerifyCS.Test + public Task TestTrivia() + => new VerifyCS.Test { TestCode = """ using System.Diagnostics.CodeAnalysis; @@ -100,12 +95,10 @@ class C LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact] - public async Task TestFullAttributeName() - { - await new VerifyCS.Test + public Task TestFullAttributeName() + => new VerifyCS.Test { TestCode = """ using System.Diagnostics.CodeAnalysis; @@ -128,12 +121,10 @@ class C LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact] - public async Task TestNamedArg() - { - await new VerifyCS.Test + public Task TestNamedArg() + => new VerifyCS.Test { TestCode = """ using System.Diagnostics.CodeAnalysis; @@ -156,12 +147,12 @@ class C LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact] - public async Task NotBeforeCSharp11() - { - var code = """ + public Task NotBeforeCSharp11() + => new VerifyCS.Test + { + TestCode = """ using System.Diagnostics.CodeAnalysis; #nullable enable class C @@ -169,20 +160,16 @@ class C [return: NotNullIfNotNull("input")] string? M(string? input) => input; } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp10, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact] - public async Task NotOnIncorrectAttributeName() - { - var code = """ + public Task NotOnIncorrectAttributeName() + => new VerifyCS.Test + { + TestCode = """ using System.Diagnostics.CodeAnalysis; #nullable enable class C @@ -190,20 +177,16 @@ class C [return: {|CS0246:{|CS0246:NotNullIfNotNull1|}|}("input")] string? M(string? input) => input; } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact] - public async Task TestNotWhenMissingArguments() - { - var code = """ + public Task TestNotWhenMissingArguments() + => new VerifyCS.Test + { + TestCode = """ using System.Diagnostics.CodeAnalysis; #nullable enable class C @@ -211,20 +194,16 @@ class C [return: {|CS7036:NotNullIfNotNull|}] string? M(string? input) => input; } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact] - public async Task NotOnIncorrectReferencedName() - { - var code = """ + public Task NotOnIncorrectReferencedName() + => new VerifyCS.Test + { + TestCode = """ using System.Diagnostics.CodeAnalysis; #nullable enable class C @@ -232,20 +211,14 @@ class C [return: NotNullIfNotNull("input1")] string? M(string? input) => input; } - """; - - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact] - public async Task TestOnParameter() - { - await new VerifyCS.Test + public Task TestOnParameter() + => new VerifyCS.Test { TestCode = """ using System.Diagnostics.CodeAnalysis; @@ -266,12 +239,10 @@ void M([NotNullIfNotNull(nameof(input))] string? input) { } LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact] - public async Task TestForProperty() - { - await new VerifyCS.Test + public Task TestForProperty() + => new VerifyCS.Test { TestCode = """ using System.Diagnostics.CodeAnalysis; @@ -312,12 +283,10 @@ bool IsInitialized LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact] - public async Task TestMultipleArguments() - { - await new VerifyCS.Test + public Task TestMultipleArguments() + => new VerifyCS.Test { TestCode = """ using System.Diagnostics.CodeAnalysis; @@ -362,12 +331,10 @@ bool IsInitialized LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact] - public async Task TestCallerArgumentExpression1() - { - await new VerifyCS.Test + public Task TestCallerArgumentExpression1() + => new VerifyCS.Test { TestCode = """ using System.Runtime.CompilerServices; @@ -388,12 +355,10 @@ void M(string s1, [CallerArgumentExpression(nameof(s1))] string? s2 = null) { } LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } [Fact] - public async Task TestCallerArgumentExpression2() - { - await new VerifyCS.Test + public Task TestCallerArgumentExpression2() + => new VerifyCS.Test { TestCode = """ using System.Runtime.CompilerServices; @@ -414,5 +379,4 @@ void M(string s1, [CallerArgumentExpressionAttribute(nameof(s1))] string? s2 = n LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.Net.Net60, }.RunAsync(); - } } diff --git a/src/Features/CSharpTest/UsePatternCombinators/CSharpUsePatternCombinatorsDiagnosticAnalyzerTests.cs b/src/Features/CSharpTest/UsePatternCombinators/CSharpUsePatternCombinatorsDiagnosticAnalyzerTests.cs index a6606911cbac4..5eb3db36997f5 100644 --- a/src/Features/CSharpTest/UsePatternCombinators/CSharpUsePatternCombinatorsDiagnosticAnalyzerTests.cs +++ b/src/Features/CSharpTest/UsePatternCombinators/CSharpUsePatternCombinatorsDiagnosticAnalyzerTests.cs @@ -97,10 +97,8 @@ static void Test(Func b) {} [InlineData("!(o is null)")] [InlineData("o is int ii || o is long jj")] [Theory] - public async Task TestMissingOnExpression(string expression) - { - await TestAllMissingOnExpressionAsync(expression); - } + public Task TestMissingOnExpression(string expression) + => TestAllMissingOnExpressionAsync(expression); [InlineData("i == default || i > default(int)", "i is default(int) or > default(int)")] [InlineData("!(o is C c)", "o is not C c")] @@ -121,34 +119,25 @@ public async Task TestMissingOnExpression(string expression) [InlineData("ch < ' ' || ch >= 0x100 || 'a' == ch", "ch is < ' ' or >= (char)0x100 or 'a'")] [InlineData("ch == 'a' || 'b' == ch", "ch is 'a' or 'b'")] [Theory] - public async Task TestOnExpression(string expression, string expected) - { - await TestAllOnExpressionAsync(expression, expected); - } + public Task TestOnExpression(string expression, string expected) + => TestAllOnExpressionAsync(expression, expected); [InlineData("nullable == 1 || 2 == nullable", "nullable is 1 or 2")] [Theory] - public async Task TestOnNullableExpression(string expression, string expected) - { - await TestAllOnExpressionAsync(expression, expected); - } + public Task TestOnNullableExpression(string expression, string expected) + => TestAllOnExpressionAsync(expression, expected); [Fact] - public async Task TestMissingIfDisabled() - { - await TestAllMissingOnExpressionAsync("o == 1 || o == 2", enabled: false); - } + public Task TestMissingIfDisabled() + => TestAllMissingOnExpressionAsync("o == 1 || o == 2", enabled: false); [Fact] - public async Task TestMissingOnCSharp8() - { - await TestAllMissingOnExpressionAsync("o == 1 || o == 2", parseOptions: TestOptions.Regular8); - } + public Task TestMissingOnCSharp8() + => TestAllMissingOnExpressionAsync("o == 1 || o == 2", parseOptions: TestOptions.Regular8); [Fact] - public async Task TestMultilineTrivia_01() - { - await TestAllAsync( + public Task TestMultilineTrivia_01() + => TestAllAsync( """ class C { @@ -183,12 +172,10 @@ not 1 and /*2*/ } } """); - } [Fact] - public async Task TestMultilineTrivia_02() - { - await TestAllAsync( + public Task TestMultilineTrivia_02() + => TestAllAsync( """ class C { @@ -223,12 +210,10 @@ and not 1 /*2*/ } } """); - } [Fact] - public async Task TestParenthesized() - { - await TestAllAsync( + public Task TestParenthesized() + => TestAllAsync( """ class C { @@ -255,12 +240,10 @@ bool M1(int v) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66787")] - public async Task TestConvertedConstants() - { - await TestAllAsync( + public Task TestConvertedConstants() + => TestAllAsync( """ class C { @@ -279,12 +262,10 @@ bool M(long l) } } """); - } [Fact] - public async Task TestMissingInExpressionTree() - { - await TestMissingAsync( + public Task TestMissingInExpressionTree() + => TestMissingAsync( """ using System.Linq; class C @@ -295,12 +276,10 @@ void M0(IQueryable q) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52397")] - public async Task TestMissingInPropertyAccess_NullCheckOnLeftSide() - { - await TestMissingAsync( + public Task TestMissingInPropertyAccess_NullCheckOnLeftSide() + => TestMissingAsync( """ using System; @@ -318,12 +297,10 @@ public void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52397")] - public async Task TestMissingInPropertyAccess_NullCheckOnRightSide() - { - await TestMissingAsync( + public Task TestMissingInPropertyAccess_NullCheckOnRightSide() + => TestMissingAsync( """ using System; @@ -341,89 +318,87 @@ public void M() } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/51691")] [InlineData("&&")] [InlineData("||")] - public async Task TestMissingInPropertyAccess_EnumCheckAndNullCheck(string logicalOperator) - { - await TestMissingAsync( -$@"using System.Diagnostics; - -public class C -{{ - public void M() - {{ - var p = default(Process); - if (p.StartInfo.WindowStyle == ProcessWindowStyle.Hidden [|{logicalOperator}|] p.StartInfo != null) - {{ - }} - }} -}}"); - } + public Task TestMissingInPropertyAccess_EnumCheckAndNullCheck(string logicalOperator) + => TestMissingAsync( + $$""" + using System.Diagnostics; + + public class C + { + public void M() + { + var p = default(Process); + if (p.StartInfo.WindowStyle == ProcessWindowStyle.Hidden [|{{logicalOperator}}|] p.StartInfo != null) + { + } + } + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/51691")] [InlineData("&&")] [InlineData("||")] - public async Task TestMissingInPropertyAccess_EnumCheckAndNullCheckOnOtherType(string logicalOperator) - { - await TestMissingAsync( -$@"using System.Diagnostics; - -public class C -{{ - public void M() - {{ - var p = default(Process); - if (p.StartInfo.WindowStyle == ProcessWindowStyle.Hidden [|{logicalOperator}|] this != null) - {{ - }} - }} -}}"); - } + public Task TestMissingInPropertyAccess_EnumCheckAndNullCheckOnOtherType(string logicalOperator) + => TestMissingAsync( + $$""" + using System.Diagnostics; + + public class C + { + public void M() + { + var p = default(Process); + if (p.StartInfo.WindowStyle == ProcessWindowStyle.Hidden [|{{logicalOperator}}|] this != null) + { + } + } + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/51693")] [InlineData("&&")] [InlineData("||")] - public async Task TestMissingInPropertyAccess_IsCheckAndNullCheck(string logicalOperator) - { - await TestMissingAsync( -$@"using System; - -public class C -{{ - public void M() - {{ - var o1 = new object(); - if (o1 is IAsyncResult ar [|{logicalOperator}|] ar.AsyncWaitHandle != null) - {{ - }} - }} -}}"); - } + public Task TestMissingInPropertyAccess_IsCheckAndNullCheck(string logicalOperator) + => TestMissingAsync( + $$""" + using System; + + public class C + { + public void M() + { + var o1 = new object(); + if (o1 is IAsyncResult ar [|{{logicalOperator}}|] ar.AsyncWaitHandle != null) + { + } + } + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/52573")] [InlineData("&&")] [InlineData("||")] - public async Task TestMissingIntegerAndStringIndex(string logicalOperator) - { - await TestMissingAsync( -$@"using System; - -public class C -{{ - private static bool IsS(char[] ch, int count) - {{ - return count == 1 [|{logicalOperator}|] ch[0] == 'S'; - }} -}}"); - } + public Task TestMissingIntegerAndStringIndex(string logicalOperator) + => TestMissingAsync( + $$""" + using System; + + public class C + { + private static bool IsS(char[] ch, int count) + { + return count == 1 [|{{logicalOperator}}|] ch[0] == 'S'; + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66787")] - public async Task TestMissingForImplicitUserDefinedCasts1() - { - await TestMissingAsync( + public Task TestMissingForImplicitUserDefinedCasts1() + => TestMissingAsync( """ using System; class C @@ -436,12 +411,10 @@ void M0(Int128 i) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66787")] - public async Task TestMissingForImplicitUserDefinedCasts2() - { - await TestMissingAsync( + public Task TestMissingForImplicitUserDefinedCasts2() + => TestMissingAsync( """ using System; class C @@ -454,12 +427,10 @@ void M0(Int128 i) } } """); - } [Fact] - public async Task TestOnSideEffects1() - { - await TestInRegularAndScriptAsync( + public Task TestOnSideEffects1() + => TestInRegularAndScriptAsync( """ class C { @@ -503,12 +474,10 @@ void M(char c) } } """); - } [Fact] - public async Task TestOnSideEffects2() - { - await TestInRegularAndScriptAsync( + public Task TestOnSideEffects2() + => TestInRegularAndScriptAsync( """ class C { @@ -552,12 +521,10 @@ void M(char c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57199")] - public async Task TestMissingInNonConvertibleTypePattern1() - { - await TestMissingAsync( + public Task TestMissingInNonConvertibleTypePattern1() + => TestMissingAsync( """ static class C { @@ -572,12 +539,10 @@ class Test bool P => [|C is C.S1 || C is C.S2|]; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57199")] - public async Task TestMissingInNonConvertibleTypePattern2() - { - await TestMissingAsync( + public Task TestMissingInNonConvertibleTypePattern2() + => TestMissingAsync( """ class Goo { @@ -595,12 +560,10 @@ private void M(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57199")] - public async Task TestMissingInNonConvertibleTypePattern3() - { - await TestMissingAsync( + public Task TestMissingInNonConvertibleTypePattern3() + => TestMissingAsync( """ class Goo { @@ -616,12 +579,10 @@ private void M(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57199")] - public async Task TestInConvertibleTypePattern() - { - await TestInRegularAndScriptAsync( + public Task TestInConvertibleTypePattern() + => TestInRegularAndScriptAsync( """ static class C { @@ -649,12 +610,10 @@ class Test bool P => C is C.S1 or C.S2; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/57199")] - public async Task TestInConvertibleTypePattern2() - { - await TestInRegularAndScriptAsync( + public Task TestInConvertibleTypePattern2() + => TestInRegularAndScriptAsync( """ public class Goo { @@ -692,12 +651,10 @@ private void M(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/75122")] - public async Task TestNotWithMultipleCallsToInvocationWithRefArgument() - { - await TestMissingAsync( + public Task TestNotWithMultipleCallsToInvocationWithRefArgument() + => TestMissingAsync( """ using System; @@ -722,12 +679,10 @@ public void Main(byte[] bytes) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76730")] - public async Task TestLogicalAndPatternNot() - { - await TestInRegularAndScript1Async( + public Task TestLogicalAndPatternNot() + => TestInRegularAndScript1Async( """ class C { @@ -754,5 +709,4 @@ static void Main() } } """); - } } diff --git a/src/Features/CSharpTest/UsePatternMatching/CSharpIsAndCastCheckWithoutNameDiagnosticAnalyzerTests.cs b/src/Features/CSharpTest/UsePatternMatching/CSharpIsAndCastCheckWithoutNameDiagnosticAnalyzerTests.cs index a8c784ecf67a7..57a77705ccce5 100644 --- a/src/Features/CSharpTest/UsePatternMatching/CSharpIsAndCastCheckWithoutNameDiagnosticAnalyzerTests.cs +++ b/src/Features/CSharpTest/UsePatternMatching/CSharpIsAndCastCheckWithoutNameDiagnosticAnalyzerTests.cs @@ -23,9 +23,8 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider => (new CSharpIsAndCastCheckWithoutNameDiagnosticAnalyzer(), new CSharpIsAndCastCheckWithoutNameCodeFixProvider()); [Fact] - public async Task TestBinaryExpression() - { - await TestInRegularAndScript1Async( + public Task TestBinaryExpression() + => TestInRegularAndScript1Async( """ class TestFile { @@ -46,12 +45,10 @@ bool M(object obj) } } """); - } [Fact] - public async Task TestNotInCSharp6() - { - await TestMissingAsync( + public Task TestNotInCSharp6() + => TestMissingAsync( """ class TestFile { @@ -62,12 +59,10 @@ bool M(object obj) } } """, parameters: new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); - } [Fact] - public async Task TestExpressionBody() - { - await TestInRegularAndScript1Async( + public Task TestExpressionBody() + => TestInRegularAndScript1Async( """ class TestFile { @@ -85,12 +80,10 @@ bool M(object obj) => obj is TestFile {|Rename:file|} && file.i > 0; } """); - } [Fact] - public async Task TestField() - { - await TestInRegularAndScript1Async( + public Task TestField() + => TestInRegularAndScript1Async( """ class TestFile { @@ -110,12 +103,10 @@ class TestFile bool M = obj is TestFile {|Rename:file|} && file.i > 0; } """); - } [Fact] - public async Task TestLambdaBody() - { - await TestInRegularAndScript1Async( + public Task TestLambdaBody() + => TestInRegularAndScript1Async( """ using System; @@ -142,12 +133,10 @@ bool M(object obj) => Goo(() => obj is TestFile {|Rename:file|} && file.i > 0, () => obj is TestFile && ((TestFile)obj).i > 0); } """); - } [Fact] - public async Task TestDefiniteAssignment1() - { - await TestInRegularAndScript1Async( + public Task TestDefiniteAssignment1() + => TestInRegularAndScript1Async( """ class TestFile { @@ -186,12 +175,10 @@ bool M(object obj) } } """); - } [Fact] - public async Task TestDefiniteAssignment2() - { - await TestInRegularAndScript1Async( + public Task TestDefiniteAssignment2() + => TestInRegularAndScript1Async( """ class TestFile { @@ -230,12 +217,10 @@ bool M(object obj) } } """); - } [Fact] - public async Task TestNotOnAnalyzerMatch() - { - await TestMissingAsync( + public Task TestNotOnAnalyzerMatch() + => TestMissingAsync( """ class TestFile { @@ -248,12 +233,10 @@ bool M(object obj) } } """); - } [Fact] - public async Task TestNotOnNullable() - { - await TestMissingAsync( + public Task TestNotOnNullable() + => TestMissingAsync( """ struct TestFile { @@ -266,12 +249,10 @@ bool M(object obj) } } """); - } [Fact] - public async Task TestComplexMatch() - { - await TestInRegularAndScript1Async( + public Task TestComplexMatch() + => TestInRegularAndScript1Async( """ class TestFile { @@ -293,12 +274,10 @@ bool M(object obj) } } """); - } [Fact] - public async Task TestTrivia() - { - await TestInRegularAndScript1Async( + public Task TestTrivia() + => TestInRegularAndScript1Async( """ class TestFile { @@ -320,12 +299,10 @@ bool M(object obj) } } """); - } [Fact] - public async Task TestFixOnlyAfterIsCheck() - { - await TestInRegularAndScript1Async( + public Task TestFixOnlyAfterIsCheck() + => TestInRegularAndScript1Async( """ class TestFile { @@ -347,12 +324,10 @@ bool M(object obj) } } """); - } [Fact] - public async Task TestArrayNaming() - { - await TestInRegularAndScript1Async( + public Task TestArrayNaming() + => TestInRegularAndScript1Async( """ class TestFile { @@ -374,12 +349,10 @@ bool M(object obj) } } """); - } [Fact] - public async Task TestNamingConflict1() - { - await TestInRegularAndScript1Async( + public Task TestNamingConflict1() + => TestInRegularAndScript1Async( """ class TestFile { @@ -403,12 +376,10 @@ bool M(object obj) } } """); - } [Fact] - public async Task TestNamingConflict2() - { - await TestInRegularAndScript1Async( + public Task TestNamingConflict2() + => TestInRegularAndScript1Async( """ class TestFile { @@ -437,12 +408,10 @@ bool M(object obj) } } """); - } [Fact] - public async Task TestNamingNoConflict1() - { - await TestInRegularAndScript1Async( + public Task TestNamingNoConflict1() + => TestInRegularAndScript1Async( """ class TestFile { @@ -471,12 +440,10 @@ bool M(object obj) } } """); - } [Fact] - public async Task TestNamingNoConflict2() - { - await TestInRegularAndScript1Async( + public Task TestNamingNoConflict2() + => TestInRegularAndScript1Async( """ class TestFile { @@ -505,12 +472,10 @@ bool M(object obj) } } """); - } [Fact] - public async Task TestNamingNoConflict3() - { - await TestInRegularAndScript1Async( + public Task TestNamingNoConflict3() + => TestInRegularAndScript1Async( """ class X { public int file; } @@ -543,12 +508,10 @@ bool M(object obj, X x) } } """); - } [Fact] - public async Task TestNamingNoConflict4() - { - await TestInRegularAndScript1Async( + public Task TestNamingNoConflict4() + => TestInRegularAndScript1Async( """ class X { public int file; } @@ -581,12 +544,10 @@ bool M(object obj, X x) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51340")] - public async Task TestNoDiagnosticWhenCS0103Happens() - { - await TestDiagnosticMissingAsync( + public Task TestNoDiagnosticWhenCS0103Happens() + => TestDiagnosticMissingAsync( """ using System.Linq; class Bar @@ -606,24 +567,20 @@ class SpecificThingType public SpecificThingType Prop { get; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58558")] - public async Task TestInExpressionTree1() - { - await TestMissingAsync( + public Task TestInExpressionTree1() + => TestMissingAsync( """ using System.Linq.Expressions; object? o = null; Expression> test = () => [||]o is int && (int)o > 5; """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/58558")] - public async Task TestInExpressionTree2() - { - await TestMissingAsync( + public Task TestInExpressionTree2() + => TestMissingAsync( """ using System.Linq.Expressions; @@ -636,12 +593,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68051")] - public async Task TestNotWhenCrossingStaticLambda() - { - await TestMissingAsync( + public Task TestNotWhenCrossingStaticLambda() + => TestMissingAsync( """ using System; @@ -662,12 +617,10 @@ private void M(Action value) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68051")] - public async Task TestNotWhenCrossingInstanceLambdaThatReferencesDifferentVariable() - { - await TestMissingAsync( + public Task TestNotWhenCrossingInstanceLambdaThatReferencesDifferentVariable() + => TestMissingAsync( """ using System; @@ -688,5 +641,4 @@ private void M(Action value) } } """); - } } diff --git a/src/Features/CSharpTest/UseRecursivePatterns/UseRecursivePatternsRefactoringFixAllTests.cs b/src/Features/CSharpTest/UseRecursivePatterns/UseRecursivePatternsRefactoringFixAllTests.cs index 73f9a92257ca4..e3924a8c9536f 100644 --- a/src/Features/CSharpTest/UseRecursivePatterns/UseRecursivePatternsRefactoringFixAllTests.cs +++ b/src/Features/CSharpTest/UseRecursivePatterns/UseRecursivePatternsRefactoringFixAllTests.cs @@ -18,674 +18,672 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWor => new UseRecursivePatternsCodeRefactoringProvider(); [Fact] - public async Task UseRecursivePatterns_FixAllInDocument() - { - await TestInRegularAndScriptAsync(@" -namespace NS -{ - class C : B - { - void M1() - { - if (n == a.b.c.d {|FixAllInDocument:|}&& a.b.c.a == n) - { - } - - if (this.P1 < 1 && 2 >= this.P2) - { - } - - if (!B1 && B2) - { - } - } - } - - class D : C - { - void M2() - { - _ = this switch - { - { a: var x } when x is { b: n } => 0 - }; - - switch (this) - { - case { a: var x } when x is { b: n }: - break; - } - } - } - - class B - { - public const C n = null; - public C a, b, c, d; - public int P1, P2, P3; - public bool B1, B2; - public C CP1, CP2; - public static C SCP1, SCP2; - public static int SP1, SP2; - public C m() { return null; } - } -}", @" -namespace NS -{ - class C : B - { - void M1() - { - if (a.b.c is { d: n, a: n }) - { - } - - if (this is { P1: < 1, P2: <= 2 }) - { - } - - if (this is { B1: false, B2: true }) - { - } - } - } - - class D : C - { - void M2() - { - _ = this switch - { - { a: { b: n } x } => 0 - }; - - switch (this) - { - case { a: { b: n } x }: - break; - } - } - } - - class B - { - public const C n = null; - public C a, b, c, d; - public int P1, P2, P3; - public bool B1, B2; - public C CP1, CP2; - public static C SCP1, SCP2; - public static int SP1, SP2; - public C m() { return null; } - } -}"); - } + public Task UseRecursivePatterns_FixAllInDocument() + => TestInRegularAndScriptAsync(""" + namespace NS + { + class C : B + { + void M1() + { + if (n == a.b.c.d {|FixAllInDocument:|}&& a.b.c.a == n) + { + } + + if (this.P1 < 1 && 2 >= this.P2) + { + } + + if (!B1 && B2) + { + } + } + } + + class D : C + { + void M2() + { + _ = this switch + { + { a: var x } when x is { b: n } => 0 + }; + + switch (this) + { + case { a: var x } when x is { b: n }: + break; + } + } + } + + class B + { + public const C n = null; + public C a, b, c, d; + public int P1, P2, P3; + public bool B1, B2; + public C CP1, CP2; + public static C SCP1, SCP2; + public static int SP1, SP2; + public C m() { return null; } + } + } + """, """ + namespace NS + { + class C : B + { + void M1() + { + if (a.b.c is { d: n, a: n }) + { + } + + if (this is { P1: < 1, P2: <= 2 }) + { + } + + if (this is { B1: false, B2: true }) + { + } + } + } + + class D : C + { + void M2() + { + _ = this switch + { + { a: { b: n } x } => 0 + }; + + switch (this) + { + case { a: { b: n } x }: + break; + } + } + } + + class B + { + public const C n = null; + public C a, b, c, d; + public int P1, P2, P3; + public bool B1, B2; + public C CP1, CP2; + public static C SCP1, SCP2; + public static int SP1, SP2; + public C m() { return null; } + } + } + """); [Fact] - public async Task UseRecursivePatterns_FixAllInProject() - { - await TestInRegularAndScriptAsync(@" - - - -namespace NS -{ - class C : B - { - void M1() - { - _ = this switch - { - { a: var x } {|FixAllInProject:|}when x is { b: n } => 0 - }; - - switch (this) - { - case { a: var x } when x is { b: n }: - break; - } - } - } -} - - -namespace NS -{ - class D : C - { - void M2() - { - _ = this switch - { - { a: var x } when x is { b: n } => 0 - }; - - switch (this) - { - case { a: var x } when x is { b: n }: - break; - } - } - } -} - - -namespace NS -{ - class B - { - public const C n = null; - public C a, b, c, d; - public int P1, P2, P3; - public bool B1, B2; - public C CP1, CP2; - public static C SCP1, SCP2; - public static int SP1, SP2; - public C m() { return null; } - } -} - - - - -namespace NS -{ - class E : C - { - void M3() - { - _ = this switch - { - { a: var x } when x is { b: n } => 0 - }; - - switch (this) - { - case { a: var x } when x is { b: n }: - break; - } - } - } -} - - - -", @" - - - -namespace NS -{ - class C : B - { - void M1() - { - _ = this switch - { - { a: { b: n } x } => 0 - }; - - switch (this) - { - case { a: { b: n } x }: - break; - } - } - } -} - - -namespace NS -{ - class D : C - { - void M2() - { - _ = this switch - { - { a: { b: n } x } => 0 - }; - - switch (this) - { - case { a: { b: n } x }: - break; - } - } - } -} - - -namespace NS -{ - class B - { - public const C n = null; - public C a, b, c, d; - public int P1, P2, P3; - public bool B1, B2; - public C CP1, CP2; - public static C SCP1, SCP2; - public static int SP1, SP2; - public C m() { return null; } - } -} - - - - -namespace NS -{ - class E : C - { - void M3() - { - _ = this switch - { - { a: var x } when x is { b: n } => 0 - }; - - switch (this) - { - case { a: var x } when x is { b: n }: - break; - } - } - } -} - - -"); - } + public Task UseRecursivePatterns_FixAllInProject() + => TestInRegularAndScriptAsync(""" + + + + namespace NS + { + class C : B + { + void M1() + { + _ = this switch + { + { a: var x } {|FixAllInProject:|}when x is { b: n } => 0 + }; + + switch (this) + { + case { a: var x } when x is { b: n }: + break; + } + } + } + } + + + namespace NS + { + class D : C + { + void M2() + { + _ = this switch + { + { a: var x } when x is { b: n } => 0 + }; + + switch (this) + { + case { a: var x } when x is { b: n }: + break; + } + } + } + } + + + namespace NS + { + class B + { + public const C n = null; + public C a, b, c, d; + public int P1, P2, P3; + public bool B1, B2; + public C CP1, CP2; + public static C SCP1, SCP2; + public static int SP1, SP2; + public C m() { return null; } + } + } + + + + + namespace NS + { + class E : C + { + void M3() + { + _ = this switch + { + { a: var x } when x is { b: n } => 0 + }; + + switch (this) + { + case { a: var x } when x is { b: n }: + break; + } + } + } + } + + + + """, """ + + + + namespace NS + { + class C : B + { + void M1() + { + _ = this switch + { + { a: { b: n } x } => 0 + }; + + switch (this) + { + case { a: { b: n } x }: + break; + } + } + } + } + + + namespace NS + { + class D : C + { + void M2() + { + _ = this switch + { + { a: { b: n } x } => 0 + }; + + switch (this) + { + case { a: { b: n } x }: + break; + } + } + } + } + + + namespace NS + { + class B + { + public const C n = null; + public C a, b, c, d; + public int P1, P2, P3; + public bool B1, B2; + public C CP1, CP2; + public static C SCP1, SCP2; + public static int SP1, SP2; + public C m() { return null; } + } + } + + + + + namespace NS + { + class E : C + { + void M3() + { + _ = this switch + { + { a: var x } when x is { b: n } => 0 + }; + + switch (this) + { + case { a: var x } when x is { b: n }: + break; + } + } + } + } + + + + """); [Fact] - public async Task UseRecursivePatterns_FixAllInSolution() - { - await TestInRegularAndScriptAsync(@" - - - -namespace NS -{ - class C : B - { - void M1() - { - _ = this switch - { - { a: var x } {|FixAllInSolution:|}when x is { b: n } => 0 - }; - - switch (this) - { - case { a: var x } when x is { b: n }: - break; - } - } - } -} - - -namespace NS -{ - class D : C - { - void M2() - { - _ = this switch - { - { a: var x } when x is { b: n } => 0 - }; - - switch (this) - { - case { a: var x } when x is { b: n }: - break; - } - } - } -} - - -namespace NS -{ - class B - { - public const C n = null; - public C a, b, c, d; - public int P1, P2, P3; - public bool B1, B2; - public C CP1, CP2; - public static C SCP1, SCP2; - public static int SP1, SP2; - public C m() { return null; } - } -} - - - - -namespace NS -{ - class E : C - { - void M3() - { - _ = this switch - { - { a: var x } when x is { b: n } => 0 - }; - - switch (this) - { - case { a: var x } when x is { b: n }: - break; - } - } - } -} - - - -", @" - - - -namespace NS -{ - class C : B - { - void M1() - { - _ = this switch - { - { a: { b: n } x } => 0 - }; - - switch (this) - { - case { a: { b: n } x }: - break; - } - } - } -} - - -namespace NS -{ - class D : C - { - void M2() - { - _ = this switch - { - { a: { b: n } x } => 0 - }; - - switch (this) - { - case { a: { b: n } x }: - break; - } - } - } -} - - -namespace NS -{ - class B - { - public const C n = null; - public C a, b, c, d; - public int P1, P2, P3; - public bool B1, B2; - public C CP1, CP2; - public static C SCP1, SCP2; - public static int SP1, SP2; - public C m() { return null; } - } -} - - - - -namespace NS -{ - class E : C - { - void M3() - { - _ = this switch - { - { a: { b: n } x } => 0 - }; - - switch (this) - { - case { a: { b: n } x }: - break; - } - } - } -} - - -"); - } + public Task UseRecursivePatterns_FixAllInSolution() + => TestInRegularAndScriptAsync(""" + + + + namespace NS + { + class C : B + { + void M1() + { + _ = this switch + { + { a: var x } {|FixAllInSolution:|}when x is { b: n } => 0 + }; + + switch (this) + { + case { a: var x } when x is { b: n }: + break; + } + } + } + } + + + namespace NS + { + class D : C + { + void M2() + { + _ = this switch + { + { a: var x } when x is { b: n } => 0 + }; + + switch (this) + { + case { a: var x } when x is { b: n }: + break; + } + } + } + } + + + namespace NS + { + class B + { + public const C n = null; + public C a, b, c, d; + public int P1, P2, P3; + public bool B1, B2; + public C CP1, CP2; + public static C SCP1, SCP2; + public static int SP1, SP2; + public C m() { return null; } + } + } + + + + + namespace NS + { + class E : C + { + void M3() + { + _ = this switch + { + { a: var x } when x is { b: n } => 0 + }; + + switch (this) + { + case { a: var x } when x is { b: n }: + break; + } + } + } + } + + + + """, """ + + + + namespace NS + { + class C : B + { + void M1() + { + _ = this switch + { + { a: { b: n } x } => 0 + }; + + switch (this) + { + case { a: { b: n } x }: + break; + } + } + } + } + + + namespace NS + { + class D : C + { + void M2() + { + _ = this switch + { + { a: { b: n } x } => 0 + }; + + switch (this) + { + case { a: { b: n } x }: + break; + } + } + } + } + + + namespace NS + { + class B + { + public const C n = null; + public C a, b, c, d; + public int P1, P2, P3; + public bool B1, B2; + public C CP1, CP2; + public static C SCP1, SCP2; + public static int SP1, SP2; + public C m() { return null; } + } + } + + + + + namespace NS + { + class E : C + { + void M3() + { + _ = this switch + { + { a: { b: n } x } => 0 + }; + + switch (this) + { + case { a: { b: n } x }: + break; + } + } + } + } + + + + """); [Fact] - public async Task UseRecursivePatterns_FixAllInContainingMember() - { - await TestInRegularAndScriptAsync(@" -namespace NS -{ - class C : B - { - void M1() - { - if (n == a.b.c.d {|FixAllInContainingMember:|}&& a.b.c.a == n) - { - } - - if (this.P1 < 1 && 2 >= this.P2) - { - } - - if (!B1 && B2) - { - } - } - } - - class D : C - { - void M2() - { - _ = this switch - { - { a: var x } when x is { b: n } => 0 - }; - - switch (this) - { - case { a: var x } when x is { b: n }: - break; - } - } - } - - class B - { - public const C n = null; - public C a, b, c, d; - public int P1, P2, P3; - public bool B1, B2; - public C CP1, CP2; - public static C SCP1, SCP2; - public static int SP1, SP2; - public C m() { return null; } - } -}", @" -namespace NS -{ - class C : B - { - void M1() - { - if (a.b.c is { d: n, a: n }) - { - } - - if (this is { P1: < 1, P2: <= 2 }) - { - } - - if (this is { B1: false, B2: true }) - { - } - } - } - - class D : C - { - void M2() - { - _ = this switch - { - { a: var x } when x is { b: n } => 0 - }; - - switch (this) - { - case { a: var x } when x is { b: n }: - break; - } - } - } - - class B - { - public const C n = null; - public C a, b, c, d; - public int P1, P2, P3; - public bool B1, B2; - public C CP1, CP2; - public static C SCP1, SCP2; - public static int SP1, SP2; - public C m() { return null; } - } -}"); - } + public Task UseRecursivePatterns_FixAllInContainingMember() + => TestInRegularAndScriptAsync(""" + namespace NS + { + class C : B + { + void M1() + { + if (n == a.b.c.d {|FixAllInContainingMember:|}&& a.b.c.a == n) + { + } + + if (this.P1 < 1 && 2 >= this.P2) + { + } + + if (!B1 && B2) + { + } + } + } + + class D : C + { + void M2() + { + _ = this switch + { + { a: var x } when x is { b: n } => 0 + }; + + switch (this) + { + case { a: var x } when x is { b: n }: + break; + } + } + } + + class B + { + public const C n = null; + public C a, b, c, d; + public int P1, P2, P3; + public bool B1, B2; + public C CP1, CP2; + public static C SCP1, SCP2; + public static int SP1, SP2; + public C m() { return null; } + } + } + """, """ + namespace NS + { + class C : B + { + void M1() + { + if (a.b.c is { d: n, a: n }) + { + } + + if (this is { P1: < 1, P2: <= 2 }) + { + } + + if (this is { B1: false, B2: true }) + { + } + } + } + + class D : C + { + void M2() + { + _ = this switch + { + { a: var x } when x is { b: n } => 0 + }; + + switch (this) + { + case { a: var x } when x is { b: n }: + break; + } + } + } + + class B + { + public const C n = null; + public C a, b, c, d; + public int P1, P2, P3; + public bool B1, B2; + public C CP1, CP2; + public static C SCP1, SCP2; + public static int SP1, SP2; + public C m() { return null; } + } + } + """); [Fact] - public async Task UseRecursivePatterns_FixAllInContainingType() - { - await TestInRegularAndScriptAsync(@" -namespace NS -{ - class C : B - { - void M1() - { - if (n == a.b.c.d {|FixAllInContainingType:|}&& a.b.c.a == n) - { - } - } - - void M2() - { - if (this.P1 < 1 && 2 >= this.P2) - { - } - - if (!B1 && B2) - { - } - } - } - - class D : C - { - void M3() - { - _ = this switch - { - { a: var x } when x is { b: n } => 0 - }; - - switch (this) - { - case { a: var x } when x is { b: n }: - break; - } - } - } - - class B - { - public const C n = null; - public C a, b, c, d; - public int P1, P2, P3; - public bool B1, B2; - public C CP1, CP2; - public static C SCP1, SCP2; - public static int SP1, SP2; - public C m() { return null; } - } -}", @" -namespace NS -{ - class C : B - { - void M1() - { - if (a.b.c is { d: n, a: n }) - { - } - } - - void M2() - { - if (this is { P1: < 1, P2: <= 2 }) - { - } - - if (this is { B1: false, B2: true }) - { - } - } - } - - class D : C - { - void M3() - { - _ = this switch - { - { a: var x } when x is { b: n } => 0 - }; - - switch (this) - { - case { a: var x } when x is { b: n }: - break; - } - } - } - - class B - { - public const C n = null; - public C a, b, c, d; - public int P1, P2, P3; - public bool B1, B2; - public C CP1, CP2; - public static C SCP1, SCP2; - public static int SP1, SP2; - public C m() { return null; } - } -}"); - } + public Task UseRecursivePatterns_FixAllInContainingType() + => TestInRegularAndScriptAsync(""" + namespace NS + { + class C : B + { + void M1() + { + if (n == a.b.c.d {|FixAllInContainingType:|}&& a.b.c.a == n) + { + } + } + + void M2() + { + if (this.P1 < 1 && 2 >= this.P2) + { + } + + if (!B1 && B2) + { + } + } + } + + class D : C + { + void M3() + { + _ = this switch + { + { a: var x } when x is { b: n } => 0 + }; + + switch (this) + { + case { a: var x } when x is { b: n }: + break; + } + } + } + + class B + { + public const C n = null; + public C a, b, c, d; + public int P1, P2, P3; + public bool B1, B2; + public C CP1, CP2; + public static C SCP1, SCP2; + public static int SP1, SP2; + public C m() { return null; } + } + } + """, """ + namespace NS + { + class C : B + { + void M1() + { + if (a.b.c is { d: n, a: n }) + { + } + } + + void M2() + { + if (this is { P1: < 1, P2: <= 2 }) + { + } + + if (this is { B1: false, B2: true }) + { + } + } + } + + class D : C + { + void M3() + { + _ = this switch + { + { a: var x } when x is { b: n } => 0 + }; + + switch (this) + { + case { a: var x } when x is { b: n }: + break; + } + } + } + + class B + { + public const C n = null; + public C a, b, c, d; + public int P1, P2, P3; + public bool B1, B2; + public C CP1, CP2; + public static C SCP1, SCP2; + public static int SP1, SP2; + public C m() { return null; } + } + } + """); } diff --git a/src/Features/CSharpTest/UseRecursivePatterns/UseRecursivePatternsRefactoringTests.cs b/src/Features/CSharpTest/UseRecursivePatterns/UseRecursivePatternsRefactoringTests.cs index 2e7a222de03d1..ce52b6c35a99a 100644 --- a/src/Features/CSharpTest/UseRecursivePatterns/UseRecursivePatternsRefactoringTests.cs +++ b/src/Features/CSharpTest/UseRecursivePatterns/UseRecursivePatternsRefactoringTests.cs @@ -95,10 +95,8 @@ private static Task VerifyMissingAsync(string initialMarkup) [InlineData("a?.m().c?.d && a?.m().a", "a?.m() is { c: { d: n }, a: n }")] [InlineData("a?.m()?.c.d && a?.m().a", "a?.m() is { c: { d: n }, a: n }")] [InlineData("a?.m()?.c?.d && a?.m().a", "a?.m() is { c: { d: n }, a: n }")] - public async Task TestLogicalAndExpression_Receiver(string actual, string expected, LanguageVersion languageVersion = LanguageVersion.CSharp9) - { - await VerifyAsync(WrapInIfStatement("n == " + actual + " == n", "&&"), WrapInIfStatement(expected), languageVersion: languageVersion); - } + public Task TestLogicalAndExpression_Receiver(string actual, string expected, LanguageVersion languageVersion = LanguageVersion.CSharp9) + => VerifyAsync(WrapInIfStatement("n == " + actual + " == n", "&&"), WrapInIfStatement(expected), languageVersion: languageVersion); [Theory] [InlineData("this.P1 < 1 && 2 >= this.P2", "this is { P1: < 1, P2: <= 2 }")] @@ -110,18 +108,14 @@ public async Task TestLogicalAndExpression_Receiver(string actual, string expect [InlineData("this.CP1?.P1 > 1 && 2 <= this.CP2.P2", "this is { CP1: { P1: > 1 }, CP2: { P2: >= 2 } }")] [InlineData("this.CP1.P1 <= 1 && 2 > this.CP2?.P2", "this is { CP1: { P1: <= 1 }, CP2: { P2: < 2 } }")] [InlineData("this.CP1.P1 >= 1 && 2 < this.CP2?.P2", "this is { CP1: { P1: >= 1 }, CP2: { P2: > 2 } }")] - public async Task TestLogicalAndExpression_Relational(string actual, string expected) - { - await VerifyAsync(WrapInIfStatement(actual, "&&"), WrapInIfStatement(expected)); - } + public Task TestLogicalAndExpression_Relational(string actual, string expected) + => VerifyAsync(WrapInIfStatement(actual, "&&"), WrapInIfStatement(expected)); [Theory] [InlineData("!B1 && B2", "this is { B1: false, B2: true }")] [InlineData("CP1.B1 && !CP2.B2", "this is { CP1: { B1: true }, CP2: { B2: false } }")] - public async Task TestLogicalAndExpression_Boolean(string actual, string expected) - { - await VerifyAsync(WrapInIfStatement(actual, "&&"), WrapInIfStatement(expected, "&&")); - } + public Task TestLogicalAndExpression_Boolean(string actual, string expected) + => VerifyAsync(WrapInIfStatement(actual, "&&"), WrapInIfStatement(expected, "&&")); [Theory] [InlineData("this.P1 == 1 && 2 == this.P2", "this is { P1: 1, P2: 2 }")] @@ -130,36 +124,28 @@ public async Task TestLogicalAndExpression_Boolean(string actual, string expecte [InlineData("this.P1 != 1 && 2 != this.P2", "this is { P1: not 1, P2: not 2 }")] [InlineData("this.CP1.P1 == 1 && 2 == this.CP2.P2", "this is { CP1: { P1: 1 }, CP2: { P2: 2 } }")] [InlineData("this.CP1.P1 != 1 && 2 != this.CP2.P2", "this is { CP1: { P1: not 1 }, CP2: { P2: not 2 } }")] - public async Task TestLogicalAndExpression_Equality(string actual, string expected) - { - await VerifyAsync(WrapInIfStatement(actual, "&&"), WrapInIfStatement(expected, "&&")); - } + public Task TestLogicalAndExpression_Equality(string actual, string expected) + => VerifyAsync(WrapInIfStatement(actual, "&&"), WrapInIfStatement(expected, "&&")); [Theory] [InlineData("NS.C.SCP1.P1 == 1 && NS.C.SCP1.P2 == 2", "NS.C.SCP1 is { P1: 1, P2: 2 }")] [InlineData("NS.C.SCP1.CP1.P1 == 1 && NS.C.SCP1.CP2.P2 == 2", "NS.C.SCP1 is { CP1: { P1: 1 }, CP2: { P2: 2 } }")] - public async Task TestLogicalAndExpression_StaticMembers(string actual, string expected) - { - await VerifyAsync(WrapInIfStatement(actual, "&&"), WrapInIfStatement(expected, "&&")); - } + public Task TestLogicalAndExpression_StaticMembers(string actual, string expected) + => VerifyAsync(WrapInIfStatement(actual, "&&"), WrapInIfStatement(expected, "&&")); [Theory] [InlineData("this.B1 && this.CP1.P1 == 1 [||]&& this.CP1.CP2.P3 == 3 && B2", "this.B1 && this.CP1 is { P1: 1, CP2: { P3: 3 } } && B2")] [InlineData("this.B1 || this.CP1.P1 == 1 [||]&& this.CP1.CP2.P3 == 3 || B2", "this.B1 || this.CP1 is { P1: 1, CP2: { P3: 3 } } || B2")] - public async Task TestLogicalAndExpression_Chain(string actual, string expected) - { - await VerifyAsync(WrapInIfStatement(actual, entry: null), WrapInIfStatement(expected, entry: null)); - } + public Task TestLogicalAndExpression_Chain(string actual, string expected) + => VerifyAsync(WrapInIfStatement(actual, entry: null), WrapInIfStatement(expected, entry: null)); [Theory] [InlineData("NS.C.SCP1 == null && NS.C.SCP2 == null")] [InlineData("NS.C.SCP1.P1 == 1 && NS.C.SCP2.P1 == 2")] [InlineData("base.P1 == 1 && base.P2 == 2")] [InlineData("base.B1 && base.B2")] - public async Task TestLogicalAndExpression_Invalid(string actual) - { - await VerifyMissingAsync(WrapInIfStatement(actual, "&&")); - } + public Task TestLogicalAndExpression_Invalid(string actual) + => VerifyMissingAsync(WrapInIfStatement(actual, "&&")); [Theory] [InlineData("{ a: var x }", "x is { b: n }", "{ a: { b: n } x }")] @@ -192,67 +178,83 @@ Task ValidateAsync(string initialMarkup, string expectedMarkup) private static string WrapInIfStatement(string actual, string? entry = null) { var markup = -@" - if (" + actual + @") {} -"; + """ + + if ( + """ + actual + """ + ) {} + + """; return CreateMarkup(markup, entry); } private static string WrapInSwitchArm(string actual, string? entry = null) { var markup = -@" - _ = this switch - { - " + actual + @" => 0 - }; -"; + """ + + _ = this switch + { + + """ + actual + """ + => 0 + }; + + """; return CreateMarkup(markup, entry); } private static string WrapInSwitchLabel(string actual, string? entry = null) { var markup = -@" - switch (this) - { - case " + actual + @": - break; - }; -"; + """ + + switch (this) + { + case + """ + actual + """ + : + break; + }; + + """; return CreateMarkup(markup, entry); } private static string CreateMarkup(string actual, string? entry = null) { - var markup = @" -namespace NS -{ - class C : B - { - void Test() - { - " + actual + @" - } - } - class B - { - public const C n = null; - public C a, b, c, d; - public int P1, P2, P3; - public bool B1, B2; - public C CP1, CP2; - public static C SCP1, SCP2; - public static int SP1, SP2; - public C m() { return null; } - public D cf = null; - } + var markup = """ - class D - { - public int C = 0; - } -}"; + namespace NS + { + class C : B + { + void Test() + { + + """ + actual + """ + + } + } + class B + { + public const C n = null; + public C a, b, c, d; + public int P1, P2, P3; + public bool B1, B2; + public C CP1, CP2; + public static C SCP1, SCP2; + public static int SP1, SP2; + public C m() { return null; } + public D cf = null; + } + + class D + { + public int C = 0; + } + } + """; return entry is null ? markup : markup.Replace(entry, "[||]" + entry); } } diff --git a/src/Features/CSharpTest/Wrapping/ArgumentWrappingTests.cs b/src/Features/CSharpTest/Wrapping/ArgumentWrappingTests.cs index f107fc6bfdbf9..ffb783ac2c445 100644 --- a/src/Features/CSharpTest/Wrapping/ArgumentWrappingTests.cs +++ b/src/Features/CSharpTest/Wrapping/ArgumentWrappingTests.cs @@ -15,9 +15,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Wrapping; public sealed class ArgumentWrappingTests : AbstractWrappingTests { [Fact] - public async Task TestMissingWithSyntaxError() - { - await TestMissingAsync( + public Task TestMissingWithSyntaxError() + => TestMissingAsync( """ class C { void Bar() { @@ -25,12 +24,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestMissingWithSelection() - { - await TestMissingAsync( + public Task TestMissingWithSelection() + => TestMissingAsync( """ class C { void Bar() { @@ -38,12 +35,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestMissingBeforeName() - { - await TestMissingAsync( + public Task TestMissingBeforeName() + => TestMissingAsync( """ class C { void Bar() { @@ -51,12 +46,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestMissingWithSingleParameter() - { - await TestMissingAsync( + public Task TestMissingWithSingleParameter() + => TestMissingAsync( """ class C { void Bar() { @@ -64,12 +57,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestMissingWithMultiLineParameter() - { - await TestMissingAsync( + public Task TestMissingWithMultiLineParameter() + => TestMissingAsync( """ class C { void Bar() { @@ -78,12 +69,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestMissingWithMultiLineParameter2() - { - await TestMissingAsync( + public Task TestMissingWithMultiLineParameter2() + => TestMissingAsync( """ class C { void Bar() { @@ -92,12 +81,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestInHeader1() - { - await TestInRegularAndScript1Async( + public Task TestInHeader1() + => TestInRegularAndScript1Async( """ class C { void Bar() { @@ -113,12 +100,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestInHeader2() - { - await TestInRegularAndScript1Async( + public Task TestInHeader2() + => TestInRegularAndScript1Async( """ class C { void Bar() { @@ -134,12 +119,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestInHeader4() - { - await TestInRegularAndScript1Async( + public Task TestInHeader4() + => TestInRegularAndScript1Async( """ class C { void Bar() { @@ -155,12 +138,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestTwoParamWrappingCases() - { - await TestAllWrappingCasesAsync( + public Task TestTwoParamWrappingCases() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -201,12 +182,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestThreeParamWrappingCases() - { - await TestAllWrappingCasesAsync( + public Task TestThreeParamWrappingCases() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -250,12 +229,10 @@ void Bar() { } } """); - } [Fact] - public async Task Test_AllOptions_NoInitialMatches() - { - await TestAllWrappingCasesAsync( + public Task Test_AllOptions_NoInitialMatches() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -309,12 +286,10 @@ void Bar() { } } """); - } [Fact] - public async Task Test_LongWrapping_ShortIds() - { - await TestAllWrappingCasesAsync( + public Task Test_LongWrapping_ShortIds() + => TestAllWrappingCasesAsync( """ class C { void Goo() { @@ -324,7 +299,7 @@ void Goo() { } } """, -GetIndentionColumn(30), + GetIndentionColumn(30), """ class C { void Goo() { @@ -412,12 +387,10 @@ void Goo() { } } """); - } [Fact] - public async Task Test_LongWrapping_VariadicLengthIds() - { - await TestAllWrappingCasesAsync( + public Task Test_LongWrapping_VariadicLengthIds() + => TestAllWrappingCasesAsync( """ class C { void Goo() { @@ -427,7 +400,7 @@ void Goo() { } } """, -GetIndentionColumn(30), + GetIndentionColumn(30), """ class C { void Goo() { @@ -512,12 +485,10 @@ void Goo() { } } """); - } [Fact] - public async Task Test_DoNotOfferLongWrappingOptionThatAlreadyAppeared() - { - await TestAllWrappingCasesAsync( + public Task Test_DoNotOfferLongWrappingOptionThatAlreadyAppeared() + => TestAllWrappingCasesAsync( """ class C { void Goo() { @@ -527,7 +498,7 @@ void Goo() { } } """, -GetIndentionColumn(25), + GetIndentionColumn(25), """ class C { void Goo() { @@ -600,12 +571,10 @@ void Goo() { } } """); - } [Fact] - public async Task Test_DoNotOfferAllLongWrappingOptionThatAlreadyAppeared() - { - await TestAllWrappingCasesAsync( + public Task Test_DoNotOfferAllLongWrappingOptionThatAlreadyAppeared() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -615,7 +584,7 @@ void Bar() { } } """, -GetIndentionColumn(20), + GetIndentionColumn(20), """ class C { void Bar() { @@ -668,12 +637,10 @@ void Bar() { } } """); - } [Fact] - public async Task Test_LongWrapping_VariadicLengthIds2() - { - await TestAllWrappingCasesAsync( + public Task Test_LongWrapping_VariadicLengthIds2() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -683,7 +650,7 @@ void Bar() { } } """, -GetIndentionColumn(30), + GetIndentionColumn(30), """ class C { void Bar() { @@ -761,12 +728,10 @@ void Bar() { } } """); - } [Fact] - public async Task Test_DoNotOfferExistingOption1() - { - await TestAllWrappingCasesAsync( + public Task Test_DoNotOfferExistingOption1() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -779,7 +744,7 @@ void Bar() { } } """, -GetIndentionColumn(30), + GetIndentionColumn(30), """ class C { void Bar() { @@ -848,12 +813,10 @@ void Bar() { } } """); - } [Fact] - public async Task Test_DoNotOfferExistingOption2() - { - await TestAllWrappingCasesAsync( + public Task Test_DoNotOfferExistingOption2() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -867,7 +830,7 @@ void Bar() { } } """, -GetIndentionColumn(30), + GetIndentionColumn(30), """ class C { void Bar() { @@ -932,12 +895,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestInElementAccess1() - { - await TestInRegularAndScript1Async( + public Task TestInElementAccess1() + => TestInRegularAndScript1Async( """ class C { void Goo() { @@ -954,12 +915,10 @@ void Goo() { } } """); - } [Fact] - public async Task TestInElementAccess2() - { - await TestInRegularAndScript1Async( + public Task TestInElementAccess2() + => TestInRegularAndScript1Async( """ class C { void Goo() { @@ -976,12 +935,10 @@ void Goo() { } } """); - } [Fact] - public async Task TestInObjectCreation1() - { - await TestInRegularAndScript1Async( + public Task TestInObjectCreation1() + => TestInRegularAndScript1Async( """ class C { void Goo() { @@ -998,12 +955,10 @@ void Goo() { } } """); - } [Fact] - public async Task TestInObjectCreation2() - { - await TestInRegularAndScript1Async( + public Task TestInObjectCreation2() + => TestInRegularAndScript1Async( """ class C { void Goo() { @@ -1020,12 +975,10 @@ void Goo() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50104")] - public async Task TestInImplicitObjectCreation() - { - await TestInRegularAndScript1Async( + public Task TestInImplicitObjectCreation() + => TestInRegularAndScript1Async( """ class Program { @@ -1049,12 +1002,10 @@ static void Main(string[] args) public Program(object o1, object o2) { } } """); - } [Fact] - public async Task TestInConstructorInitializer1() - { - await TestInRegularAndScript1Async( + public Task TestInConstructorInitializer1() + => TestInRegularAndScript1Async( """ class C { public C() : base([||]a, b, c) { @@ -1069,12 +1020,10 @@ public C() : base(a, } } """); - } [Fact] - public async Task TestInConstructorInitializer2() - { - await TestInRegularAndScript1Async( + public Task TestInConstructorInitializer2() + => TestInRegularAndScript1Async( """ class C { public C() : [||]base(a, b, c) { @@ -1089,12 +1038,10 @@ public C() : base(a, } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63732")] - public async Task TestMissingStartToken1() - { - await TestMissingAsync( + public Task TestMissingStartToken1() + => TestMissingAsync( """ class C { void Bar() { @@ -1102,12 +1049,10 @@ void Bar() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63732")] - public async Task TestMissingStartToken2() - { - await TestMissingAsync( + public Task TestMissingStartToken2() + => TestMissingAsync( """ class C { void Bar() { @@ -1115,12 +1060,10 @@ void Bar() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63732")] - public async Task TestMissingEndToken1() - { - await TestMissingAsync( + public Task TestMissingEndToken1() + => TestMissingAsync( """ class C { void Bar() { @@ -1128,12 +1071,10 @@ void Bar() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63732")] - public async Task TestMissingEndToken2() - { - await TestMissingAsync( + public Task TestMissingEndToken2() + => TestMissingAsync( """ class C { void Bar() { @@ -1141,5 +1082,4 @@ void Bar() { } } """); - } } diff --git a/src/Features/CSharpTest/Wrapping/BinaryExpressionWrappingTests.cs b/src/Features/CSharpTest/Wrapping/BinaryExpressionWrappingTests.cs index 4742a756333fb..752c8966ba95e 100644 --- a/src/Features/CSharpTest/Wrapping/BinaryExpressionWrappingTests.cs +++ b/src/Features/CSharpTest/Wrapping/BinaryExpressionWrappingTests.cs @@ -28,9 +28,8 @@ private Task TestBeginningOfLine(string markup, string expected) => TestInRegularAndScript1Async(markup, expected, BeginningOfLine); [Fact] - public async Task TestMissingWithSyntaxError() - { - await TestMissingAsync( + public Task TestMissingWithSyntaxError() + => TestMissingAsync( """ class C { void Bar() { @@ -38,12 +37,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestMissingWithSelection() - { - await TestMissingAsync( + public Task TestMissingWithSelection() + => TestMissingAsync( """ class C { void Bar() { @@ -52,12 +49,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestMissingBeforeExpr() - { - await TestMissingAsync( + public Task TestMissingBeforeExpr() + => TestMissingAsync( """ class C { void Bar() { @@ -66,12 +61,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestMissingWithSingleExpr() - { - await TestMissingAsync( + public Task TestMissingWithSingleExpr() + => TestMissingAsync( """ class C { void Bar() { @@ -80,12 +73,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestMissingWithMultiLineExpression() - { - await TestMissingAsync( + public Task TestMissingWithMultiLineExpression() + => TestMissingAsync( """ class C { void Bar() { @@ -95,12 +86,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestMissingWithMultiLineExpr2() - { - await TestMissingAsync( + public Task TestMissingWithMultiLineExpr2() + => TestMissingAsync( """ class C { void Bar() { @@ -110,12 +99,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestInIf() - { - await TestEndOfLine( + public Task TestInIf() + => TestEndOfLine( """ class C { void Bar() { @@ -133,12 +120,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestInIf_IncludingOp() - { - await TestBeginningOfLine( + public Task TestInIf_IncludingOp() + => TestBeginningOfLine( """ class C { void Bar() { @@ -156,12 +141,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestInIf2() - { - await TestEndOfLine( + public Task TestInIf2() + => TestEndOfLine( """ class C { void Bar() { @@ -179,12 +162,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestInIf3() - { - await TestEndOfLine( + public Task TestInIf3() + => TestEndOfLine( """ class C { void Bar() { @@ -202,12 +183,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestInIf4() - { - await TestEndOfLine( + public Task TestInIf4() + => TestEndOfLine( """ class C { void Bar() { @@ -225,12 +204,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestInIf5() - { - await TestEndOfLine( + public Task TestInIf5() + => TestEndOfLine( """ class C { void Bar() { @@ -248,12 +225,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestTwoExprWrappingCases_End() - { - await TestAllWrappingCasesAsync( + public Task TestTwoExprWrappingCases_End() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -262,7 +237,7 @@ void Bar() { } } """, -EndOfLine, + EndOfLine, """ class C { void Bar() { @@ -272,12 +247,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestTwoExprWrappingCases_Beginning() - { - await TestAllWrappingCasesAsync( + public Task TestTwoExprWrappingCases_Beginning() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -286,7 +259,7 @@ void Bar() { } } """, -BeginningOfLine, + BeginningOfLine, """ class C { void Bar() { @@ -296,12 +269,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestThreeExprWrappingCases_End() - { - await TestAllWrappingCasesAsync( + public Task TestThreeExprWrappingCases_End() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -310,7 +281,7 @@ void Bar() { } } """, -EndOfLine, + EndOfLine, """ class C { void Bar() { @@ -321,12 +292,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestThreeExprWrappingCases_Beginning() - { - await TestAllWrappingCasesAsync( + public Task TestThreeExprWrappingCases_Beginning() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -335,7 +304,7 @@ void Bar() { } } """, -BeginningOfLine, + BeginningOfLine, """ class C { void Bar() { @@ -346,12 +315,10 @@ void Bar() { } } """); - } [Fact] - public async Task Test_AllOptions_NoInitialMatches_End() - { - await TestAllWrappingCasesAsync( + public Task Test_AllOptions_NoInitialMatches_End() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -363,7 +330,7 @@ void Bar() { } } """, -EndOfLine, + EndOfLine, """ class C { void Bar() { @@ -384,12 +351,10 @@ void Bar() { } } """); - } [Fact] - public async Task Test_AllOptions_NoInitialMatches_Beginning() - { - await TestAllWrappingCasesAsync( + public Task Test_AllOptions_NoInitialMatches_Beginning() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -401,7 +366,7 @@ void Bar() { } } """, -BeginningOfLine, + BeginningOfLine, """ class C { void Bar() { @@ -422,12 +387,10 @@ void Bar() { } } """); - } [Fact] - public async Task Test_DoNotOfferExistingOption1() - { - await TestAllWrappingCasesAsync( + public Task Test_DoNotOfferExistingOption1() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -454,12 +417,10 @@ void Bar() { } } """); - } [Fact] - public async Task Test_DoNotOfferExistingOption2_End() - { - await TestAllWrappingCasesAsync( + public Task Test_DoNotOfferExistingOption2_End() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -469,7 +430,7 @@ void Bar() { } } """, -EndOfLine, + EndOfLine, """ class C { void Bar() { @@ -487,12 +448,10 @@ void Bar() { } } """); - } [Fact] - public async Task Test_DoNotOfferExistingOption2_Beginning() - { - await TestAllWrappingCasesAsync( + public Task Test_DoNotOfferExistingOption2_Beginning() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -502,7 +461,7 @@ void Bar() { } } """, -BeginningOfLine, + BeginningOfLine, """ class C { void Bar() { @@ -511,12 +470,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestInLocalInitializer_Beginning() - { - await TestAllWrappingCasesAsync( + public Task TestInLocalInitializer_Beginning() + => TestAllWrappingCasesAsync( """ class C { void Goo() { @@ -524,7 +481,7 @@ void Goo() { } } """, -BeginningOfLine, + BeginningOfLine, """ class C { void Goo() { @@ -543,12 +500,10 @@ void Goo() { } } """); - } [Fact] - public async Task TestInLocalInitializer_End() - { - await TestAllWrappingCasesAsync( + public Task TestInLocalInitializer_End() + => TestAllWrappingCasesAsync( """ class C { void Goo() { @@ -556,7 +511,7 @@ void Goo() { } } """, -EndOfLine, + EndOfLine, """ class C { void Goo() { @@ -575,18 +530,16 @@ void Goo() { } } """); - } [Fact] - public async Task TestInField_Beginning() - { - await TestAllWrappingCasesAsync( + public Task TestInField_Beginning() + => TestAllWrappingCasesAsync( """ class C { bool v = [||]a && b && c; } """, -BeginningOfLine, + BeginningOfLine, """ class C { bool v = a @@ -601,18 +554,16 @@ class C { && c; } """); - } [Fact] - public async Task TestInField_End() - { - await TestAllWrappingCasesAsync( + public Task TestInField_End() + => TestAllWrappingCasesAsync( """ class C { bool v = [||]a && b && c; } """, -EndOfLine, + EndOfLine, """ class C { bool v = a && @@ -627,12 +578,10 @@ class C { c; } """); - } [Fact] - public async Task TestAddition_End() - { - await TestAllWrappingCasesAsync( + public Task TestAddition_End() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -640,7 +589,7 @@ void Bar() { } } """, -EndOfLine, + EndOfLine, """ class C { void Bar() { @@ -661,12 +610,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestAddition_Beginning() - { - await TestAllWrappingCasesAsync( + public Task TestAddition_Beginning() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -674,7 +621,7 @@ void Bar() { } } """, -BeginningOfLine, + BeginningOfLine, """ class C { void Bar() { @@ -695,12 +642,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestUnderscoreName_End() - { - await TestEndOfLine( + public Task TestUnderscoreName_End() + => TestEndOfLine( """ class C { void Bar() { @@ -718,12 +663,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestUnderscoreName_Beginning() - { - await TestBeginningOfLine( + public Task TestUnderscoreName_Beginning() + => TestBeginningOfLine( """ class C { void Bar() { @@ -741,19 +684,17 @@ void Bar() { } } """); - } [Fact] - public async Task TestInField_Already_Wrapped_Beginning() - { - await TestAllWrappingCasesAsync( + public Task TestInField_Already_Wrapped_Beginning() + => TestAllWrappingCasesAsync( """ class C { bool v = [||]a && b && c; } """, -BeginningOfLine, + BeginningOfLine, """ class C { bool v = @@ -762,19 +703,17 @@ class C { && c; } """); - } [Fact] - public async Task TestInField_Already_Wrapped_End() - { - await TestAllWrappingCasesAsync( + public Task TestInField_Already_Wrapped_End() + => TestAllWrappingCasesAsync( """ class C { bool v = [||]a && b && c; } """, -EndOfLine, + EndOfLine, """ class C { bool v = @@ -783,19 +722,17 @@ class C { c; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34127")] - public async Task TestWrapLowerPrecedenceInLargeBinary() - { - await TestAllWrappingCasesAsync( + public Task TestWrapLowerPrecedenceInLargeBinary() + => TestAllWrappingCasesAsync( """ class C { bool v = [||]a + b + c + d == x * y * z; } """, -EndOfLine, + EndOfLine, """ class C { @@ -810,5 +747,4 @@ class C x * y * z; } """); - } } diff --git a/src/Features/CSharpTest/Wrapping/ChainedExpressionWrappingTests.cs b/src/Features/CSharpTest/Wrapping/ChainedExpressionWrappingTests.cs index 2ed2e7a7911c3..0ae50112612cd 100644 --- a/src/Features/CSharpTest/Wrapping/ChainedExpressionWrappingTests.cs +++ b/src/Features/CSharpTest/Wrapping/ChainedExpressionWrappingTests.cs @@ -14,9 +14,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Wrapping; public sealed class ChainedExpressionWrappingTests : AbstractWrappingTests { [Fact] - public async Task TestMissingWithSyntaxError() - { - await TestMissingAsync( + public Task TestMissingWithSyntaxError() + => TestMissingAsync( """ class C { void Bar() { @@ -24,12 +23,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestMissingWithoutEnoughChunks() - { - await TestMissingAsync( + public Task TestMissingWithoutEnoughChunks() + => TestMissingAsync( """ class C { void Bar() { @@ -37,12 +34,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestWithEnoughChunks() - { - await TestAllWrappingCasesAsync( + public Task TestWithEnoughChunks() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -66,12 +61,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestGenericNames() - { - await TestAllWrappingCasesAsync( + public Task TestGenericNames() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -95,12 +88,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestElementAccess() - { - await TestAllWrappingCasesAsync( + public Task TestElementAccess() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -124,12 +115,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestUnwrap() - { - await TestAllWrappingCasesAsync( + public Task TestUnwrap() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -153,12 +142,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestWrapAndUnwrap() - { - await TestAllWrappingCasesAsync( + public Task TestWrapAndUnwrap() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -191,12 +178,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestChunkMustHaveDottedSection() - { - await TestAllWrappingCasesAsync( + public Task TestChunkMustHaveDottedSection() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -220,12 +205,10 @@ void Bar() { } } """); - } [Fact] - public async Task TrailingNonCallIsNotWrapped() - { - await TestAllWrappingCasesAsync( + public Task TrailingNonCallIsNotWrapped() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -249,12 +232,10 @@ void Bar() { } } """); - } [Fact] - public async Task TrailingLongWrapping1() - { - await TestAllWrappingCasesAsync( + public Task TrailingLongWrapping1() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -262,7 +243,7 @@ void Bar() { } } """, -GetIndentionColumn(35), + GetIndentionColumn(35), """ class C { void Bar() { @@ -304,12 +285,10 @@ void Bar() { } } """); - } [Fact] - public async Task TrailingLongWrapping2() - { - await TestAllWrappingCasesAsync( + public Task TrailingLongWrapping2() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -317,7 +296,7 @@ void Bar() { } } """, -GetIndentionColumn(40), + GetIndentionColumn(40), """ class C { void Bar() { @@ -358,12 +337,10 @@ void Bar() { } } """); - } [Fact] - public async Task TrailingLongWrapping3() - { - await TestAllWrappingCasesAsync( + public Task TrailingLongWrapping3() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -371,7 +348,7 @@ void Bar() { } } """, -GetIndentionColumn(60), + GetIndentionColumn(60), """ class C { void Bar() { @@ -410,12 +387,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestInConditionalAccess() - { - await TestAllWrappingCasesAsync( + public Task TestInConditionalAccess() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -439,12 +414,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestInConditionalAccess2() - { - await TestAllWrappingCasesAsync( + public Task TestInConditionalAccess2() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -468,12 +441,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestInConditionalAccess3() - { - await TestAllWrappingCasesAsync( + public Task TestInConditionalAccess3() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -497,12 +468,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestInConditionalAccess4() - { - await TestAllWrappingCasesAsync( + public Task TestInConditionalAccess4() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -519,5 +488,4 @@ void Bar() { } } """); - } } diff --git a/src/Features/CSharpTest/Wrapping/CollectionExpressionWrappingTests.cs b/src/Features/CSharpTest/Wrapping/CollectionExpressionWrappingTests.cs index 951d1980835b8..8320416ae5eb9 100644 --- a/src/Features/CSharpTest/Wrapping/CollectionExpressionWrappingTests.cs +++ b/src/Features/CSharpTest/Wrapping/CollectionExpressionWrappingTests.cs @@ -13,9 +13,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Wrapping; public sealed class CollectionExpressionWrappingTests : AbstractWrappingTests { [Fact] - public async Task TestNoWrappingSuggestions() - { - await TestMissingAsync( + public Task TestNoWrappingSuggestions() + => TestMissingAsync( """ class C { void Bar() { @@ -23,12 +22,10 @@ void Bar() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/59624")] - public async Task TestNoWrappingSuggestions_TrailingComma() - { - await TestMissingAsync( + public Task TestNoWrappingSuggestions_TrailingComma() + => TestMissingAsync( """ class C { void Bar() { @@ -36,12 +33,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestWrappingShortInitializerExpression() - { - await TestAllWrappingCasesAsync( + public Task TestWrappingShortInitializerExpression() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -70,12 +65,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestSpreads1() - { - await TestAllWrappingCasesAsync( + public Task TestSpreads1() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -105,12 +98,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestSpreads2() - { - await TestAllWrappingCasesAsync( + public Task TestSpreads2() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -140,12 +131,10 @@ void Bar() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/59624")] - public async Task TestWrappingShortInitializerExpression_TrailingComma1() - { - await TestAllWrappingCasesAsync( + public Task TestWrappingShortInitializerExpression_TrailingComma1() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -174,12 +163,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestWrappingLongInitializerExpression() - { - await TestAllWrappingCasesAsync( + public Task TestWrappingLongInitializerExpression() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -215,12 +202,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestWrappingMultiLineLongInitializerExpression() - { - await TestAllWrappingCasesAsync( + public Task TestWrappingMultiLineLongInitializerExpression() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -276,12 +261,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestShortInitializerExpressionRefactorings() - { - await TestAllWrappingCasesAsync( + public Task TestShortInitializerExpressionRefactorings() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -310,12 +293,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestLongInitializerExpressionRefactorings() - { - await TestAllWrappingCasesAsync( + public Task TestLongInitializerExpressionRefactorings() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -351,12 +332,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestObjectWrappingInitializerExpression() - { - await TestAllWrappingCasesAsync( + public Task TestObjectWrappingInitializerExpression() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -386,12 +365,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestWrappedObjectInitializerExpression() - { - await TestAllWrappingCasesAsync( + public Task TestWrappedObjectInitializerExpression() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -421,12 +398,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestReturnInitializerExpression() - { - await TestAllWrappingCasesAsync( + public Task TestReturnInitializerExpression() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -463,12 +438,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestWrappedReturnInitializerExpression() - { - await TestAllWrappingCasesAsync( + public Task TestWrappedReturnInitializerExpression() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -505,12 +478,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestClassPropertyInitializerExpressionRefactorings() - { - await TestAllWrappingCasesAsync( + public Task TestClassPropertyInitializerExpressionRefactorings() + => TestAllWrappingCasesAsync( """ public class C { public List B => [||][0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; @@ -541,12 +512,10 @@ public class C { ]; } """); - } [Fact] - public async Task TestWrappedClassPropertyInitializerExpressionRefactorings() - { - await TestAllWrappingCasesAsync( + public Task TestWrappedClassPropertyInitializerExpressionRefactorings() + => TestAllWrappingCasesAsync( """ public class C { public List B => @@ -577,12 +546,10 @@ public class C { ]; } """); - } [Fact] - public async Task TestArgumentInitializerExpressionRefactorings() - { - await TestAllWrappingCasesAsync( + public Task TestArgumentInitializerExpressionRefactorings() + => TestAllWrappingCasesAsync( """ public void F() { var result = fakefunction([||][0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); @@ -613,12 +580,10 @@ public void F() { ]); } """); - } [Fact] - public async Task TestWrappedArgumentInitializerExpressionRefactorings() - { - await TestAllWrappingCasesAsync( + public Task TestWrappedArgumentInitializerExpressionRefactorings() + => TestAllWrappingCasesAsync( """ public void F() { var result = fakefunction( @@ -649,12 +614,10 @@ public void F() { ]); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63732")] - public async Task TestMissingStartToken() - { - await TestMissingAsync( + public Task TestMissingStartToken() + => TestMissingAsync( """ class C { void Bar() { @@ -662,12 +625,10 @@ void Bar() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63732")] - public async Task TestMissingEndToken1() - { - await TestMissingAsync( + public Task TestMissingEndToken1() + => TestMissingAsync( """ class C { void Bar() { @@ -676,12 +637,10 @@ void Bar() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63732")] - public async Task TestMissingEndToken2() - { - await TestMissingAsync( + public Task TestMissingEndToken2() + => TestMissingAsync( """ class C { void Bar() { @@ -689,5 +648,4 @@ void Bar() { } } """); - } } diff --git a/src/Features/CSharpTest/Wrapping/InitializerExpressionWrappingTests.cs b/src/Features/CSharpTest/Wrapping/InitializerExpressionWrappingTests.cs index 15d0563ec4d82..51e77a9b1ba80 100644 --- a/src/Features/CSharpTest/Wrapping/InitializerExpressionWrappingTests.cs +++ b/src/Features/CSharpTest/Wrapping/InitializerExpressionWrappingTests.cs @@ -13,9 +13,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Wrapping; public sealed class InitializerExpressionWrappingTests : AbstractWrappingTests { [Fact] - public async Task TestNoWrappingSuggestions() - { - await TestMissingAsync( + public Task TestNoWrappingSuggestions() + => TestMissingAsync( """ class C { void Bar() { @@ -23,12 +22,10 @@ void Bar() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/59624")] - public async Task TestNoWrappingSuggestions_TrailingComma() - { - await TestMissingAsync( + public Task TestNoWrappingSuggestions_TrailingComma() + => TestMissingAsync( """ class C { void Bar() { @@ -36,12 +33,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestWrappingShortInitializerExpression() - { - await TestAllWrappingCasesAsync( + public Task TestWrappingShortInitializerExpression() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -70,12 +65,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestWrappingNakedArrayInitializer() - { - await TestAllWrappingCasesAsync( + public Task TestWrappingNakedArrayInitializer() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -104,12 +97,10 @@ void Bar() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/59624")] - public async Task TestWrappingShortInitializerExpression_TrailingComma() - { - await TestAllWrappingCasesAsync( + public Task TestWrappingShortInitializerExpression_TrailingComma() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -138,12 +129,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestWrappingLongInitializerExpression() - { - await TestAllWrappingCasesAsync( + public Task TestWrappingLongInitializerExpression() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -179,12 +168,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestWrappingMultiLineLongInitializerExpression() - { - await TestAllWrappingCasesAsync( + public Task TestWrappingMultiLineLongInitializerExpression() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -240,12 +227,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestShortInitializerExpressionRefactorings() - { - await TestAllWrappingCasesAsync( + public Task TestShortInitializerExpressionRefactorings() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -274,12 +259,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestLongInitializerExpressionRefactorings() - { - await TestAllWrappingCasesAsync( + public Task TestLongInitializerExpressionRefactorings() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -315,12 +298,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestListWrappingInitializerExpression() - { - await TestAllWrappingCasesAsync( + public Task TestListWrappingInitializerExpression() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -357,12 +338,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestWrappedListInitializerExpression() - { - await TestAllWrappingCasesAsync( + public Task TestWrappedListInitializerExpression() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -399,12 +378,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestObjectWrappingInitializerExpression() - { - await TestAllWrappingCasesAsync( + public Task TestObjectWrappingInitializerExpression() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -434,12 +411,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestWrappedObjectInitializerExpression() - { - await TestAllWrappingCasesAsync( + public Task TestWrappedObjectInitializerExpression() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -469,12 +444,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestReturnInitializerExpression() - { - await TestAllWrappingCasesAsync( + public Task TestReturnInitializerExpression() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -511,12 +484,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestWrappedReturnInitializerExpression() - { - await TestAllWrappingCasesAsync( + public Task TestWrappedReturnInitializerExpression() + => TestAllWrappingCasesAsync( """ class C { void Bar() { @@ -553,12 +524,10 @@ void Bar() { } } """); - } [Fact] - public async Task TestClassPropertyInitializerExpressionRefactorings() - { - await TestAllWrappingCasesAsync( + public Task TestClassPropertyInitializerExpressionRefactorings() + => TestAllWrappingCasesAsync( """ public class C { public List B => new List [||]{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; @@ -589,12 +558,10 @@ public class C { }; } """); - } [Fact] - public async Task TestWrappedClassPropertyInitializerExpressionRefactorings() - { - await TestAllWrappingCasesAsync( + public Task TestWrappedClassPropertyInitializerExpressionRefactorings() + => TestAllWrappingCasesAsync( """ public class C { public List B => new List @@ -625,12 +592,10 @@ public class C { }; } """); - } [Fact] - public async Task TestArgumentInitializerExpressionRefactorings() - { - await TestAllWrappingCasesAsync( + public Task TestArgumentInitializerExpressionRefactorings() + => TestAllWrappingCasesAsync( """ public void F() { var result = fakefunction(new List [||]{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); @@ -661,12 +626,10 @@ public void F() { }); } """); - } [Fact] - public async Task TestWrappedArgumentInitializerExpressionRefactorings() - { - await TestAllWrappingCasesAsync( + public Task TestWrappedArgumentInitializerExpressionRefactorings() + => TestAllWrappingCasesAsync( """ public void F() { var result = fakefunction(new List @@ -697,12 +660,10 @@ public void F() { }); } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63732")] - public async Task TestMissingStartToken() - { - await TestMissingAsync( + public Task TestMissingStartToken() + => TestMissingAsync( """ class C { void Bar() { @@ -710,12 +671,10 @@ void Bar() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63732")] - public async Task TestMissingEndToken1() - { - await TestMissingAsync( + public Task TestMissingEndToken1() + => TestMissingAsync( """ class C { void Bar() { @@ -724,12 +683,10 @@ void Bar() { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63732")] - public async Task TestMissingEndToken2() - { - await TestMissingAsync( + public Task TestMissingEndToken2() + => TestMissingAsync( """ class C { void Bar() { @@ -737,5 +694,4 @@ void Bar() { } } """); - } } diff --git a/src/Features/CSharpTest/Wrapping/ParameterWrappingTests.cs b/src/Features/CSharpTest/Wrapping/ParameterWrappingTests.cs index 15cd11c57f3aa..aabfe5912420a 100644 --- a/src/Features/CSharpTest/Wrapping/ParameterWrappingTests.cs +++ b/src/Features/CSharpTest/Wrapping/ParameterWrappingTests.cs @@ -16,45 +16,38 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Wrapping; public sealed class ParameterWrappingTests : AbstractWrappingTests { [Fact] - public async Task TestMissingWithSyntaxError() - { - await TestMissingAsync( + public Task TestMissingWithSyntaxError() + => TestMissingAsync( """ class C { void Goo([||]int i, int j { } } """); - } [Fact] - public async Task TestMissingWithSelection() - { - await TestMissingAsync( + public Task TestMissingWithSelection() + => TestMissingAsync( """ class C { void Goo([|int|] i, int j) { } } """); - } [Fact] - public async Task TestMissingInBody() - { - await TestMissingAsync( + public Task TestMissingInBody() + => TestMissingAsync( """ class C { void Goo(int i, int j) {[||] } } """); - } [Fact] - public async Task TestMissingInAttributes() - { - await TestMissingAsync( + public Task TestMissingInAttributes() + => TestMissingAsync( """ class C { [||][Attr] @@ -62,24 +55,20 @@ void Goo(int i, int j) { } } """); - } [Fact] - public async Task TestMissingWithOpenTokenTrailingComment() - { - await TestMissingAsync( + public Task TestMissingWithOpenTokenTrailingComment() + => TestMissingAsync( """ class C { void Goo([||]/**/int i, int j) { } } """); - } [Fact] - public async Task TestMissingWithItemLeadingComment() - { - await TestMissingAsync( + public Task TestMissingWithItemLeadingComment() + => TestMissingAsync( """ class C { void Goo([||] @@ -87,12 +76,10 @@ void Goo([||] } } """); - } [Fact] - public async Task TestMissingWithItemTrailingComment() - { - await TestMissingAsync( + public Task TestMissingWithItemTrailingComment() + => TestMissingAsync( """ class C { void Goo([||] @@ -100,12 +87,10 @@ void Goo([||] } } """); - } [Fact] - public async Task TestMissingWithCommaTrailingComment() - { - await TestMissingAsync( + public Task TestMissingWithCommaTrailingComment() + => TestMissingAsync( """ class C { void Goo([||] @@ -113,12 +98,10 @@ void Goo([||] } } """); - } [Fact] - public async Task TestMissingWithLastItemTrailingComment() - { - await TestMissingAsync( + public Task TestMissingWithLastItemTrailingComment() + => TestMissingAsync( """ class C { void Goo([||] @@ -127,12 +110,10 @@ void Goo([||] } } """); - } [Fact] - public async Task TestMissingWithCloseTokenLeadingComment() - { - await TestMissingAsync( + public Task TestMissingWithCloseTokenLeadingComment() + => TestMissingAsync( """ class C { void Goo([||] @@ -141,12 +122,10 @@ void Goo([||] } } """); - } [Fact] - public async Task TestWithOpenTokenLeadingComment() - { - await TestInRegularAndScript1Async( + public Task TestWithOpenTokenLeadingComment() + => TestInRegularAndScript1Async( """ class C { void Goo/**/([||]int i, int j) { @@ -161,12 +140,10 @@ class C { } } """); - } [Fact] - public async Task TestWithCloseTokenTrailingComment() - { - await TestInRegularAndScript1Async( + public Task TestWithCloseTokenTrailingComment() + => TestInRegularAndScript1Async( """ class C { void Goo([||]int i, int j)/**/ { @@ -181,24 +158,20 @@ void Goo(int i, } } """); - } [Fact] - public async Task TestMissingWithSingleParameter() - { - await TestMissingAsync( + public Task TestMissingWithSingleParameter() + => TestMissingAsync( """ class C { void Goo([||]int i) { } } """); - } [Fact] - public async Task TestMissingWithMultiLineParameter() - { - await TestMissingAsync( + public Task TestMissingWithMultiLineParameter() + => TestMissingAsync( """ class C { void Goo([||]int i, int j = @@ -206,12 +179,10 @@ void Goo([||]int i, int j = } } """); - } [Fact] - public async Task TestInHeader1() - { - await TestInRegularAndScript1Async( + public Task TestInHeader1() + => TestInRegularAndScript1Async( """ class C { [||]void Goo(int i, int j) { @@ -225,12 +196,10 @@ void Goo(int i, } } """); - } [Fact] - public async Task TestInHeader2() - { - await TestInRegularAndScript1Async( + public Task TestInHeader2() + => TestInRegularAndScript1Async( """ class C { void [||]Goo(int i, int j) { @@ -244,12 +213,10 @@ void Goo(int i, } } """); - } [Fact] - public async Task TestInHeader3() - { - await TestInRegularAndScript1Async( + public Task TestInHeader3() + => TestInRegularAndScript1Async( """ class C { [||]public void Goo(int i, int j) { @@ -263,12 +230,10 @@ public void Goo(int i, } } """); - } [Fact] - public async Task TestInHeader4() - { - await TestInRegularAndScript1Async( + public Task TestInHeader4() + => TestInRegularAndScript1Async( """ class C { public void Goo(int i, int j)[||] { @@ -282,12 +247,10 @@ public void Goo(int i, } } """); - } [Fact] - public async Task TestTwoParamWrappingCases() - { - await TestAllWrappingCasesAsync( + public Task TestTwoParamWrappingCases() + => TestAllWrappingCasesAsync( """ class C { void Goo([||]int i, int j) { @@ -323,12 +286,10 @@ void Goo( } } """); - } [Fact] - public async Task TestThreeParamWrappingCases() - { - await TestAllWrappingCasesAsync( + public Task TestThreeParamWrappingCases() + => TestAllWrappingCasesAsync( """ class C { void Goo([||]int i, int j, int k) { @@ -367,12 +328,10 @@ void Goo( } } """); - } [Fact] - public async Task Test_AllOptions_NoInitialMatches() - { - await TestAllWrappingCasesAsync( + public Task Test_AllOptions_NoInitialMatches() + => TestAllWrappingCasesAsync( """ class C { void Goo([||] @@ -420,12 +379,10 @@ void Goo( } } """); - } [Fact] - public async Task Test_LongWrapping_ShortIds() - { - await TestAllWrappingCasesAsync( + public Task Test_LongWrapping_ShortIds() + => TestAllWrappingCasesAsync( """ class C { void Goo([||] @@ -434,7 +391,7 @@ void Goo([||] } } """, -GetIndentionColumn(30), + GetIndentionColumn(30), """ class C { void Goo(int i, @@ -506,12 +463,10 @@ void Goo(int i, int j, } } """); - } [Fact] - public async Task Test_LongWrapping_VariadicLengthIds() - { - await TestAllWrappingCasesAsync( + public Task Test_LongWrapping_VariadicLengthIds() + => TestAllWrappingCasesAsync( """ class C { void Goo([||] @@ -520,7 +475,7 @@ void Goo([||] } } """, -GetIndentionColumn(30), + GetIndentionColumn(30), """ class C { void Goo(int i, @@ -597,12 +552,10 @@ void Goo(int i, int jj, } } """); - } [Fact] - public async Task Test_DoNotOfferLongWrappingOptionThatAlreadyAppeared() - { - await TestAllWrappingCasesAsync( + public Task Test_DoNotOfferLongWrappingOptionThatAlreadyAppeared() + => TestAllWrappingCasesAsync( """ class C { void Goo([||] @@ -611,7 +564,7 @@ void Goo([||] } } """, -GetIndentionColumn(30), + GetIndentionColumn(30), """ class C { void Goo(int iiiii, @@ -677,12 +630,10 @@ void Goo(int iiiii, } } """); - } [Fact] - public async Task Test_DoNotOfferAllLongWrappingOptionThatAlreadyAppeared() - { - await TestAllWrappingCasesAsync( + public Task Test_DoNotOfferAllLongWrappingOptionThatAlreadyAppeared() + => TestAllWrappingCasesAsync( """ class C { void Goo([||] @@ -691,7 +642,7 @@ void Goo([||] } } """, -GetIndentionColumn(20), + GetIndentionColumn(20), """ class C { void Goo(int iiiii, @@ -739,12 +690,10 @@ void Goo( } } """); - } [Fact] - public async Task Test_LongWrapping_VariadicLengthIds2() - { - await TestAllWrappingCasesAsync( + public Task Test_LongWrapping_VariadicLengthIds2() + => TestAllWrappingCasesAsync( """ class C { void Goo([||] @@ -753,7 +702,7 @@ void Goo([||] } } """, -GetIndentionColumn(30), + GetIndentionColumn(30), """ class C { void Goo(int i, @@ -826,12 +775,10 @@ void Goo(int i, int jj, } } """); - } [Fact] - public async Task Test_DoNotOfferExistingOption1() - { - await TestAllWrappingCasesAsync( + public Task Test_DoNotOfferExistingOption1() + => TestAllWrappingCasesAsync( """ class C { void Goo([||]int i, @@ -843,7 +790,7 @@ void Goo([||]int i, } } """, -GetIndentionColumn(30), + GetIndentionColumn(30), """ class C { void Goo( @@ -905,12 +852,10 @@ void Goo(int i, int jj, } } """); - } [Fact] - public async Task Test_DoNotOfferExistingOption2() - { - await TestAllWrappingCasesAsync( + public Task Test_DoNotOfferExistingOption2() + => TestAllWrappingCasesAsync( """ class C { void Goo([||] @@ -923,7 +868,7 @@ void Goo([||] } } """, -GetIndentionColumn(30), + GetIndentionColumn(30), """ class C { void Goo(int i, @@ -984,12 +929,10 @@ void Goo(int i, int jj, } } """); - } [Fact] - public async Task TestInConstructor() - { - await TestInRegularAndScript1Async( + public Task TestInConstructor() + => TestInRegularAndScript1Async( """ class C { public [||]C(int i, int j) { @@ -1003,12 +946,10 @@ public C(int i, } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38986")] - public async Task TestInConstructorWithSyntaxErrorAfter() - { - await TestInRegularAndScript1Async( + public Task TestInConstructorWithSyntaxErrorAfter() + => TestInRegularAndScript1Async( """ class C { public [||]C(int i, int j) : base(,) { @@ -1022,12 +963,10 @@ public C(int i, } } """); - } [Fact] - public async Task TestInIndexer() - { - await TestInRegularAndScript1Async( + public Task TestInIndexer() + => TestInRegularAndScript1Async( """ class C { public int [||]this[int i, int j] => 0; @@ -1039,12 +978,10 @@ class C { int j] => 0; } """); - } [Fact] - public async Task TestInOperator() - { - await TestInRegularAndScript1Async( + public Task TestInOperator() + => TestInRegularAndScript1Async( """ class C { public shared int operator [||]+(C c1, C c2) => 0; @@ -1056,12 +993,10 @@ class C { C c2) => 0; } """); - } [Fact] - public async Task TestInDelegate() - { - await TestInRegularAndScript1Async( + public Task TestInDelegate() + => TestInRegularAndScript1Async( """ class C { public delegate int [||]D(C c1, C c2); @@ -1073,12 +1008,10 @@ public delegate int D(C c1, C c2); } """); - } [Fact] - public async Task TestInParenthesizedLambda() - { - await TestInRegularAndScript1Async( + public Task TestInParenthesizedLambda() + => TestInRegularAndScript1Async( """ class C { void Goo() @@ -1098,12 +1031,10 @@ void Goo() } } """); - } [Fact] - public async Task TestInParenthesizedLambda2() - { - await TestInRegularAndScript1Async( + public Task TestInParenthesizedLambda2() + => TestInRegularAndScript1Async( """ class C { void Goo() @@ -1123,12 +1054,10 @@ void Goo() } } """); - } [Fact] - public async Task TestNotOnSimpleLambda() - { - await TestMissingAsync( + public Task TestNotOnSimpleLambda() + => TestMissingAsync( """ class C { void Goo() @@ -1138,12 +1067,10 @@ void Goo() } } """); - } [Fact] - public async Task TestLocalFunction() - { - await TestInRegularAndScript1Async( + public Task TestLocalFunction() + => TestInRegularAndScript1Async( """ class C { void Goo() @@ -1163,170 +1090,139 @@ void Local(C c, } } """); - } [Fact] - public async Task TestRecord_Semicolon() - { - await TestInRegularAndScript1Async( + public Task TestRecord_Semicolon() + => TestInRegularAndScript1Async( "record R([||]int I, string S);", """ record R(int I, string S); """); - } [Fact] - public async Task TestClass_Semicolon() - { - await TestInRegularAndScript1Async( + public Task TestClass_Semicolon() + => TestInRegularAndScript1Async( "class R([||]int I, string S);", """ class R(int I, string S); """); - } [Fact] - public async Task TestInterface_Semicolon() - { - await TestInRegularAndScript1Async( + public Task TestInterface_Semicolon() + => TestInRegularAndScript1Async( "interface R([||]int I, string S);", """ interface R(int I, string S); """); - } [Fact] - public async Task TestRecord_Braces() - { - await TestInRegularAndScript1Async( + public Task TestRecord_Braces() + => TestInRegularAndScript1Async( "record R([||]int I, string S) { }", """ record R(int I, string S) { } """); - } [Fact] - public async Task TestClass_Braces() - { - await TestInRegularAndScript1Async( + public Task TestClass_Braces() + => TestInRegularAndScript1Async( "class R([||]int I, string S) { }", """ class R(int I, string S) { } """); - } [Fact] - public async Task TestInterface_Braces() - { - await TestInRegularAndScript1Async( + public Task TestInterface_Braces() + => TestInRegularAndScript1Async( "interface R([||]int I, string S) { }", """ interface R(int I, string S) { } """); - } [Fact] - public async Task TestRecordStruct_Semicolon() - { - await TestInRegularAndScript1Async( + public Task TestRecordStruct_Semicolon() + => TestInRegularAndScript1Async( "record struct R([||]int I, string S);", """ record struct R(int I, string S); """, new TestParameters(TestOptions.RegularPreview)); - } [Fact] - public async Task TestStruct_Semicolon() - { - await TestInRegularAndScript1Async( + public Task TestStruct_Semicolon() + => TestInRegularAndScript1Async( "struct R([||]int I, string S);", """ struct R(int I, string S); """, new TestParameters(TestOptions.RegularPreview)); - } [Fact] - public async Task TestRecordStruct_Braces() - { - await TestInRegularAndScript1Async( + public Task TestRecordStruct_Braces() + => TestInRegularAndScript1Async( "record struct R([||]int I, string S) { }", """ record struct R(int I, string S) { } """, new TestParameters(TestOptions.RegularPreview)); - } [Fact] - public async Task TestStruct_Braces() - { - await TestInRegularAndScript1Async( + public Task TestStruct_Braces() + => TestInRegularAndScript1Async( "struct R([||]int I, string S) { }", """ struct R(int I, string S) { } """, new TestParameters(TestOptions.RegularPreview)); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61362")] - public async Task TestWithMissingParameterList() - { - await TestMissingAsync( + public Task TestWithMissingParameterList() + => TestMissingAsync( """ class C { public void UpsertRecord[||] } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63732")] - public async Task TestWithMissingStartToken1() - { - await TestMissingAsync( + public Task TestWithMissingStartToken1() + => TestMissingAsync( """ class C { public void UpsertRecord[||]) } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63732")] - public async Task TestWithMissingStartToken2() - { - await TestMissingAsync( + public Task TestWithMissingStartToken2() + => TestMissingAsync( """ class C { public void UpsertRecord[||] int i, int j) } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63732")] - public async Task TestWithMissingEndToken1() - { - await TestMissingAsync( + public Task TestWithMissingEndToken1() + => TestMissingAsync( """ class C { public void UpsertRecord([||] } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/63732")] - public async Task TestWithMissingEndToken2() - { - await TestMissingAsync( + public Task TestWithMissingEndToken2() + => TestMissingAsync( """ class C { public void UpsertRecord([||]int i, int j } """); - } } diff --git a/src/Features/Core/Portable/AddConstructorParametersFromMembers/AddConstructorParametersFromMembersCodeRefactoringProvider.AddConstructorParametersCodeAction.cs b/src/Features/Core/Portable/AddConstructorParametersFromMembers/AddConstructorParametersFromMembersCodeRefactoringProvider.AddConstructorParametersCodeAction.cs index f20653115d902..87f23c9c66b50 100644 --- a/src/Features/Core/Portable/AddConstructorParametersFromMembers/AddConstructorParametersFromMembersCodeRefactoringProvider.AddConstructorParametersCodeAction.cs +++ b/src/Features/Core/Portable/AddConstructorParametersFromMembers/AddConstructorParametersFromMembersCodeRefactoringProvider.AddConstructorParametersCodeAction.cs @@ -15,7 +15,6 @@ using Microsoft.CodeAnalysis.GenerateFromMembers; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Shared.Extensions; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddConstructorParametersFromMembers; diff --git a/src/Features/Core/Portable/AddConstructorParametersFromMembers/AddConstructorParametersFromMembersCodeRefactoringProvider.cs b/src/Features/Core/Portable/AddConstructorParametersFromMembers/AddConstructorParametersFromMembersCodeRefactoringProvider.cs index 08d856ae664ba..f5e063a49567d 100644 --- a/src/Features/Core/Portable/AddConstructorParametersFromMembers/AddConstructorParametersFromMembersCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/AddConstructorParametersFromMembers/AddConstructorParametersFromMembersCodeRefactoringProvider.cs @@ -17,7 +17,6 @@ using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddConstructorParametersFromMembers; @@ -183,7 +182,7 @@ public async Task> ComputeIntentAsync( { // Intents currently have no way to report progress. var changedSolution = await action.GetChangedSolutionInternalAsync( - priorDocument.Project.Solution, CodeAnalysisProgress.None, postProcessChanges: true, cancellationToken).ConfigureAwait(false); + priorDocument.Project.Solution, CodeAnalysisProgress.None, cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(changedSolution); var intent = new IntentProcessorResult(changedSolution, [priorDocument.Id], action.Title, action.ActionName); results.Add(intent); diff --git a/src/Features/Core/Portable/AddImport/CodeActions/AssemblyReferenceCodeAction.cs b/src/Features/Core/Portable/AddImport/CodeActions/AssemblyReferenceCodeAction.cs index 878c5030c5afa..1403c022fbd82 100644 --- a/src/Features/Core/Portable/AddImport/CodeActions/AssemblyReferenceCodeAction.cs +++ b/src/Features/Core/Portable/AddImport/CodeActions/AssemblyReferenceCodeAction.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; diff --git a/src/Features/Core/Portable/AddImport/CodeActions/MetadataSymbolReferenceCodeAction.cs b/src/Features/Core/Portable/AddImport/CodeActions/MetadataSymbolReferenceCodeAction.cs index c1cee271e6915..e2e3601ee0b2c 100644 --- a/src/Features/Core/Portable/AddImport/CodeActions/MetadataSymbolReferenceCodeAction.cs +++ b/src/Features/Core/Portable/AddImport/CodeActions/MetadataSymbolReferenceCodeAction.cs @@ -7,7 +7,6 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Shared.Extensions; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddImport; diff --git a/src/Features/Core/Portable/AddImport/References/AssemblyReference.cs b/src/Features/Core/Portable/AddImport/References/AssemblyReference.cs index 1e2d8a87aed22..ac3e03fcd632b 100644 --- a/src/Features/Core/Portable/AddImport/References/AssemblyReference.cs +++ b/src/Features/Core/Portable/AddImport/References/AssemblyReference.cs @@ -4,6 +4,7 @@ #nullable disable +using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeCleanup; diff --git a/src/Features/Core/Portable/AddImport/SymbolReferenceFinder.cs b/src/Features/Core/Portable/AddImport/SymbolReferenceFinder.cs index a49e720541646..01fc2d7372b0b 100644 --- a/src/Features/Core/Portable/AddImport/SymbolReferenceFinder.cs +++ b/src/Features/Core/Portable/AddImport/SymbolReferenceFinder.cs @@ -227,7 +227,7 @@ private async Task> GetReferencesForMatchingType var typeReferences = typesContainedDirectlyInTypes.SelectAsArray( r => searchScope.CreateReference(r.WithSymbol(r.Symbol.ContainingType))); - return namespaceReferences.Concat(typeReferences); + return [.. namespaceReferences, .. typeReferences]; } private bool ArityAccessibilityAndAttributeContextAreCorrect( diff --git a/src/Features/Core/Portable/AddMissingReference/AbstractAddMissingReferenceCodeFixProvider.cs b/src/Features/Core/Portable/AddMissingReference/AbstractAddMissingReferenceCodeFixProvider.cs index 1893de04d1020..5719f27e6fc6a 100644 --- a/src/Features/Core/Portable/AddMissingReference/AbstractAddMissingReferenceCodeFixProvider.cs +++ b/src/Features/Core/Portable/AddMissingReference/AbstractAddMissingReferenceCodeFixProvider.cs @@ -9,6 +9,7 @@ using Microsoft.CodeAnalysis.AddPackage; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; diff --git a/src/Features/Core/Portable/AddPackage/AbstractAddPackageCodeFixProvider.cs b/src/Features/Core/Portable/AddPackage/AbstractAddPackageCodeFixProvider.cs index 2cdf37758dd8d..5b8e84897f73a 100644 --- a/src/Features/Core/Portable/AddPackage/AbstractAddPackageCodeFixProvider.cs +++ b/src/Features/Core/Portable/AddPackage/AbstractAddPackageCodeFixProvider.cs @@ -9,6 +9,7 @@ using Microsoft.CodeAnalysis.AddImport; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.SymbolSearch; diff --git a/src/Features/Core/Portable/CodeFixes/FixAllOccurrences/FixMultipleCodeAction.cs b/src/Features/Core/Portable/CodeFixes/FixAllOccurrences/FixMultipleCodeAction.cs index 8e9a1aa4b3cea..0f0822011eae3 100644 --- a/src/Features/Core/Portable/CodeFixes/FixAllOccurrences/FixMultipleCodeAction.cs +++ b/src/Features/Core/Portable/CodeFixes/FixAllOccurrences/FixMultipleCodeAction.cs @@ -11,10 +11,7 @@ internal sealed partial class FixMultipleCodeAction( string title, string computingFixWaitDialogMessage) : AbstractFixAllCodeFixCodeAction(fixAllState, showPreviewChangesDialog: false) { - private readonly string _title = title; - private readonly string _computingFixWaitDialogMessage = computingFixWaitDialogMessage; + public override string Title => title; - public override string Title => _title; - - internal override string Message => _computingFixWaitDialogMessage; + internal override string Message => computingFixWaitDialogMessage; } diff --git a/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.GlobalSuppressMessageFixAllCodeAction.cs b/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.GlobalSuppressMessageFixAllCodeAction.cs index 18811bd6f4d5a..d32c1f1e9e1df 100644 --- a/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.GlobalSuppressMessageFixAllCodeAction.cs +++ b/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.GlobalSuppressMessageFixAllCodeAction.cs @@ -55,7 +55,7 @@ internal static CodeAction Create(string title, AbstractSuppressionCodeFixProvid private sealed class GlobalSuppressionSolutionChangeAction( string title, Func, CancellationToken, Task> createChangedSolution, - string equivalenceKey) : SolutionChangeAction(title, createChangedSolution, equivalenceKey) + string equivalenceKey) : SolutionChangeAction(title, createChangedSolution, equivalenceKey, CodeActionPriority.Default, CodeActionCleanup.Default) { protected override Task PostProcessChangesAsync(Document document, CancellationToken cancellationToken) { @@ -210,7 +210,7 @@ private static IEnumerable>> Cr var builder = new List>>(); foreach (var (symbol, diagnostics) in diagnosticsMapBuilder) - builder.Add(KeyValuePairUtil.Create(symbol, GetUniqueDiagnostics(diagnostics))); + builder.Add(KeyValuePair.Create(symbol, GetUniqueDiagnostics(diagnostics))); return builder.OrderBy(kvp => kvp.Key.GetDocumentationCommentId() ?? string.Empty); } diff --git a/src/Features/Core/Portable/CodeFixes/Suppression/SuppressionHelpers.cs b/src/Features/Core/Portable/CodeFixes/Suppression/SuppressionHelpers.cs index 5840abac92c73..50b9c327a87f9 100644 --- a/src/Features/Core/Portable/CodeFixes/Suppression/SuppressionHelpers.cs +++ b/src/Features/Core/Portable/CodeFixes/Suppression/SuppressionHelpers.cs @@ -4,6 +4,7 @@ using System.Collections.Immutable; using System.Globalization; +using System.Linq; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Shared.Extensions; diff --git a/src/Features/Core/Portable/CodeFixesAndRefactorings/AbstractFixAllCodeAction.cs b/src/Features/Core/Portable/CodeFixesAndRefactorings/AbstractFixAllCodeAction.cs index cb9287f68011d..7d712ec0dab45 100644 --- a/src/Features/Core/Portable/CodeFixesAndRefactorings/AbstractFixAllCodeAction.cs +++ b/src/Features/Core/Portable/CodeFixesAndRefactorings/AbstractFixAllCodeAction.cs @@ -15,18 +15,15 @@ namespace Microsoft.CodeAnalysis.CodeFixesAndRefactorings; /// Fix all code action for a code action registered by /// a or a . /// -internal abstract class AbstractFixAllCodeAction : CodeAction +internal abstract class AbstractFixAllCodeAction( + IFixAllState fixAllState, bool showPreviewChangesDialog) : CodeAction { - private bool _showPreviewChangesDialog; + private bool _showPreviewChangesDialog = showPreviewChangesDialog; - public IFixAllState FixAllState { get; } + public IFixAllState FixAllState { get; } = fixAllState; - protected AbstractFixAllCodeAction( - IFixAllState fixAllState, bool showPreviewChangesDialog) - { - FixAllState = fixAllState; - _showPreviewChangesDialog = showPreviewChangesDialog; - } + // We don't need to post process changes here as the inner code action created for Fix multiple code fix already executes. + internal sealed override CodeActionCleanup Cleanup => CodeActionCleanup.None; /// /// Determine if the is an internal first-party provider or not. diff --git a/src/Features/Core/Portable/CodeFixesAndRefactorings/AbstractFixAllGetFixesService.cs b/src/Features/Core/Portable/CodeFixesAndRefactorings/AbstractFixAllGetFixesService.cs index 6618465af1541..c503e2c8be38f 100644 --- a/src/Features/Core/Portable/CodeFixesAndRefactorings/AbstractFixAllGetFixesService.cs +++ b/src/Features/Core/Portable/CodeFixesAndRefactorings/AbstractFixAllGetFixesService.cs @@ -27,11 +27,11 @@ internal abstract class AbstractFixAllGetFixesService : IFixAllGetFixesService var codeAction = await GetFixAllCodeActionAsync(fixAllContext).ConfigureAwait(false); if (codeAction == null) { - return fixAllContext.Solution; + return fixAllContext.State.Solution; } fixAllContext.CancellationToken.ThrowIfCancellationRequested(); - return await codeAction.GetChangedSolutionInternalAsync(fixAllContext.Solution, fixAllContext.Progress, cancellationToken: fixAllContext.CancellationToken).ConfigureAwait(false); + return await codeAction.GetChangedSolutionInternalAsync(fixAllContext.State.Solution, fixAllContext.Progress, fixAllContext.CancellationToken).ConfigureAwait(false); } public async Task> GetFixAllOperationsAsync( @@ -47,7 +47,7 @@ public async Task> GetFixAllOperationsAsync( codeAction, showPreviewChangesDialog, fixAllContext.Progress, fixAllContext.State, fixAllContext.CancellationToken).ConfigureAwait(false); } - protected async Task> GetFixAllOperationsAsync( + private async Task> GetFixAllOperationsAsync( CodeAction codeAction, bool showPreviewChangesDialog, IProgress progressTracker, @@ -69,7 +69,7 @@ protected async Task> GetFixAllOperationsAsy cancellationToken.ThrowIfCancellationRequested(); var newSolution = await codeAction.GetChangedSolutionInternalAsync( - fixAllState.Solution, progressTracker, cancellationToken: cancellationToken).ConfigureAwait(false); + fixAllState.Solution, progressTracker, cancellationToken).ConfigureAwait(false); if (newSolution is null) { @@ -175,7 +175,7 @@ protected async Task> GetFixAllOperationsAsy CodeAction? action = null; try { - action = await fixAllContext.FixAllProvider.GetFixAsync(fixAllContext).ConfigureAwait(false); + action = await fixAllContext.State.FixAllProvider.GetFixAsync(fixAllContext).ConfigureAwait(false); } catch (OperationCanceledException) { @@ -197,7 +197,7 @@ protected async Task> GetFixAllOperationsAsy } } - protected static ImmutableArray GetNewFixAllOperations(ImmutableArray operations, Solution newSolution, CancellationToken cancellationToken) + private static ImmutableArray GetNewFixAllOperations(ImmutableArray operations, Solution newSolution, CancellationToken cancellationToken) { using var _ = ArrayBuilder.GetInstance(operations.Length, out var result); var foundApplyChanges = false; diff --git a/src/Features/Core/Portable/CodeRefactorings/CodeRefactoringService.cs b/src/Features/Core/Portable/CodeRefactorings/CodeRefactoringService.cs index d3e5e55563c40..9b2ea5350c88e 100644 --- a/src/Features/Core/Portable/CodeRefactorings/CodeRefactoringService.cs +++ b/src/Features/Core/Portable/CodeRefactorings/CodeRefactoringService.cs @@ -35,7 +35,7 @@ internal sealed class CodeRefactoringService( ImmutableDictionary.CreateRange( DistributeLanguagesAndDocuments(providers) .GroupBy(lz => new ProviderKey(lz.Metadata.Language, lz.Metadata.DocumentKind, lz.Metadata.DocumentExtension)) - .Select(grp => KeyValuePairUtil.Create(grp.Key, + .Select(grp => KeyValuePair.Create(grp.Key, new Lazy>(() => [.. ExtensionOrderer.Order(grp).Select(lz => lz.Value)]))))); private readonly Lazy> _lazyRefactoringToMetadataMap = new(() => providers.Where(provider => provider.IsValueCreated).ToImmutableDictionary(provider => provider.Value, provider => provider.Metadata)); diff --git a/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.MoveTypeEditor.cs b/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.MoveTypeEditor.cs index 2bd31a250ab03..7aed47af6ea10 100644 --- a/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.MoveTypeEditor.cs +++ b/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.MoveTypeEditor.cs @@ -6,12 +6,12 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; -using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.AddFileBanner; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageService; diff --git a/src/Features/Core/Portable/CodeRefactorings/PredefinedCodeRefactoringProviderNames.cs b/src/Features/Core/Portable/CodeRefactorings/PredefinedCodeRefactoringProviderNames.cs index 559eb5f952faa..c6e7daf484e8d 100644 --- a/src/Features/Core/Portable/CodeRefactorings/PredefinedCodeRefactoringProviderNames.cs +++ b/src/Features/Core/Portable/CodeRefactorings/PredefinedCodeRefactoringProviderNames.cs @@ -69,6 +69,7 @@ internal static class PredefinedCodeRefactoringProviderNames public const string MoveToNamespace = "Move To Namespace Code Action Provider"; public const string MoveTypeToFile = "Move Type To File Code Action Provider"; public const string NameTupleElement = nameof(NameTupleElement); + public const string OrganizeImports = nameof(OrganizeImports); public const string PullMemberUp = "Pull Member Up Code Action Provider"; public const string RenameTracking = nameof(RenameTracking); public const string ReplaceConditionalWithStatements = nameof(ReplaceConditionalWithStatements); diff --git a/src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractChangeNamespaceService.cs b/src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractChangeNamespaceService.cs index 2684264135022..657bb59378a74 100644 --- a/src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractChangeNamespaceService.cs +++ b/src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractChangeNamespaceService.cs @@ -15,6 +15,7 @@ using Microsoft.CodeAnalysis.CodeCleanup; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CodeRefactorings.SyncNamespace; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.FindSymbols; diff --git a/src/Features/Core/Portable/Completion/CommonCompletionItem.cs b/src/Features/Core/Portable/Completion/CommonCompletionItem.cs index 271e8fafee92b..b5a8d0cfdd3c5 100644 --- a/src/Features/Core/Portable/Completion/CommonCompletionItem.cs +++ b/src/Features/Core/Portable/Completion/CommonCompletionItem.cs @@ -44,7 +44,7 @@ public static CompletionItem Create( if (!description.IsDefault && description.Length > 0) { - properties = properties.NullToEmpty().Add(KeyValuePairUtil.Create(DescriptionProperty, EncodeDescription(description.ToTaggedText()))); + properties = properties.NullToEmpty().Add(KeyValuePair.Create(DescriptionProperty, EncodeDescription(description.ToTaggedText()))); } return CompletionItem.CreateInternal( diff --git a/src/Features/Core/Portable/Completion/CompletionContext.cs b/src/Features/Core/Portable/Completion/CompletionContext.cs index 65f4c8946ff1c..417f03181edbc 100644 --- a/src/Features/Core/Portable/Completion/CompletionContext.cs +++ b/src/Features/Core/Portable/Completion/CompletionContext.cs @@ -22,9 +22,6 @@ public sealed class CompletionContext { private readonly SegmentedList _items = []; - private CompletionItem? _suggestionModeItem; - private bool _isExclusive; - internal CompletionProvider Provider { get; } /// @@ -89,7 +86,7 @@ public bool IsExclusive { get { - return _isExclusive && !Provider.IsExpandItemProvider; + return field && !Provider.IsExpandItemProvider; } set @@ -97,7 +94,7 @@ public bool IsExclusive if (value) Debug.Assert(!Provider.IsExpandItemProvider); - _isExclusive = value; + field = value; } } @@ -198,10 +195,7 @@ public void AddItems(IEnumerable items) /// public CompletionItem? SuggestionModeItem { - get - { - return _suggestionModeItem; - } + get; set { @@ -210,7 +204,7 @@ public CompletionItem? SuggestionModeItem value = FixItem(value); } - _suggestionModeItem = value; + field = value; } } diff --git a/src/Features/Core/Portable/Completion/CompletionDescription.cs b/src/Features/Core/Portable/Completion/CompletionDescription.cs index 3ea4c0833efda..361eec8156721 100644 --- a/src/Features/Core/Portable/Completion/CompletionDescription.cs +++ b/src/Features/Core/Portable/Completion/CompletionDescription.cs @@ -13,7 +13,6 @@ namespace Microsoft.CodeAnalysis.Completion; /// public sealed class CompletionDescription { - private string? _text; /// /// The used when there is no description. @@ -63,12 +62,14 @@ public string Text { get { - if (_text == null) + if (field == null) { - Interlocked.CompareExchange(ref _text, string.Concat(TaggedParts.Select(p => p.Text)), null); + Interlocked.CompareExchange(ref field, string.Concat(TaggedParts.Select(p => p.Text)), null); } - return _text; + return field; } + + private set; } } diff --git a/src/Features/Core/Portable/Completion/CompletionItem.cs b/src/Features/Core/Portable/Completion/CompletionItem.cs index 4b46cd8aeeeea..67f8022167034 100644 --- a/src/Features/Core/Portable/Completion/CompletionItem.cs +++ b/src/Features/Core/Portable/Completion/CompletionItem.cs @@ -460,7 +460,7 @@ internal CompletionItem WithProperties(ImmutableArray with the specified property. /// public CompletionItem AddProperty(string name, string value) - => With(properties: GetProperties().Add(KeyValuePairUtil.Create(name, value))); + => With(properties: GetProperties().Add(KeyValuePair.Create(name, value))); /// /// Creates a copy of this with the property changed. diff --git a/src/Features/Core/Portable/Completion/Providers/AbstractAwaitCompletionProvider.cs b/src/Features/Core/Portable/Completion/Providers/AbstractAwaitCompletionProvider.cs index 4d81d2c136d3a..1eda836e2222f 100644 --- a/src/Features/Core/Portable/Completion/Providers/AbstractAwaitCompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/Providers/AbstractAwaitCompletionProvider.cs @@ -7,6 +7,7 @@ using System.Diagnostics; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.PooledObjects; @@ -96,16 +97,16 @@ public sealed override async Task ProvideCompletionsAsync(CompletionContext cont using var builder = TemporaryArray>.Empty; - builder.Add(KeyValuePairUtil.Create(Position, position.ToString())); - builder.Add(KeyValuePairUtil.Create(LeftTokenPosition, leftToken.SpanStart.ToString())); + builder.Add(KeyValuePair.Create(Position, position.ToString())); + builder.Add(KeyValuePair.Create(LeftTokenPosition, leftToken.SpanStart.ToString())); var makeContainerAsync = declaration is not null && !SyntaxGenerator.GetGenerator(document).GetModifiers(declaration).IsAsync; if (makeContainerAsync) - builder.Add(KeyValuePairUtil.Create(MakeContainerAsync, string.Empty)); + builder.Add(KeyValuePair.Create(MakeContainerAsync, string.Empty)); if (isAwaitKeywordContext) { - builder.Add(KeyValuePairUtil.Create(AddAwaitAtCurrentPosition, string.Empty)); + builder.Add(KeyValuePair.Create(AddAwaitAtCurrentPosition, string.Empty)); var properties = builder.ToImmutableAndClear(); context.AddItem(CreateCompletionItem( @@ -130,7 +131,7 @@ public sealed override async Task ProvideCompletionsAsync(CompletionContext cont if (dotAwaitContext == DotAwaitContext.AwaitAndConfigureAwait) { // add the `awaitf` option to do the same, but also add .ConfigureAwait(false); - properties = properties.Add(KeyValuePairUtil.Create(AppendConfigureAwait, string.Empty)); + properties = properties.Add(KeyValuePair.Create(AppendConfigureAwait, string.Empty)); context.AddItem(CreateCompletionItem( properties, _awaitfDisplayText, _awaitfFilterText, string.Format(FeaturesResources.Await_the_preceding_expression_and_add_ConfigureAwait_0, _falseKeyword), diff --git a/src/Features/Core/Portable/Completion/Providers/AbstractInternalsVisibleToCompletionProvider.cs b/src/Features/Core/Portable/Completion/Providers/AbstractInternalsVisibleToCompletionProvider.cs index 3df4ba0713845..1e87d2e73c39d 100644 --- a/src/Features/Core/Portable/Completion/Providers/AbstractInternalsVisibleToCompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/Providers/AbstractInternalsVisibleToCompletionProvider.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Runtime.CompilerServices; using System.Threading; @@ -12,7 +13,6 @@ using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers; @@ -157,7 +157,7 @@ private async Task AddAssemblyCompletionItemsAsync(CompletionContext context, Ca displayTextSuffix: "", rules: CompletionItemRules.Default, glyph: project.GetGlyph(), - properties: [KeyValuePairUtil.Create(ProjectGuidKey, projectGuid)]); + properties: [KeyValuePair.Create(ProjectGuidKey, projectGuid)]); context.AddItem(completionItem); } diff --git a/src/Features/Core/Portable/Completion/Providers/AbstractPreprocessorCompletionProvider.cs b/src/Features/Core/Portable/Completion/Providers/AbstractPreprocessorCompletionProvider.cs index 659df9d8e314f..7581b5670c6c8 100644 --- a/src/Features/Core/Portable/Completion/Providers/AbstractPreprocessorCompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/Providers/AbstractPreprocessorCompletionProvider.cs @@ -3,9 +3,9 @@ // See the LICENSE file in the project root for more information. using System.Collections.Generic; -using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; diff --git a/src/Features/Core/Portable/Completion/Providers/AbstractSymbolCompletionProvider.cs b/src/Features/Core/Portable/Completion/Providers/AbstractSymbolCompletionProvider.cs index 7134c0ef26f72..2bf2bbb952136 100644 --- a/src/Features/Core/Portable/Completion/Providers/AbstractSymbolCompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/Providers/AbstractSymbolCompletionProvider.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageService; diff --git a/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractTypeImportCompletionService.cs b/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractTypeImportCompletionService.cs index 2cd5b3307c193..9b8993e106f9c 100644 --- a/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractTypeImportCompletionService.cs +++ b/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractTypeImportCompletionService.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System; -using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.IO; @@ -19,7 +18,6 @@ using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; using Roslyn.Utilities; - using static Microsoft.CodeAnalysis.Shared.Utilities.EditorBrowsableHelpers; namespace Microsoft.CodeAnalysis.Completion.Providers; diff --git a/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/ExtensionMethodImportCompletionHelper.SymbolComputer.cs b/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/ExtensionMethodImportCompletionHelper.SymbolComputer.cs index 34a71d8cdeb63..6a9abb891ada1 100644 --- a/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/ExtensionMethodImportCompletionHelper.SymbolComputer.cs +++ b/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/ExtensionMethodImportCompletionHelper.SymbolComputer.cs @@ -9,6 +9,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; diff --git a/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/ExtensionMethodImportCompletionHelper.cs b/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/ExtensionMethodImportCompletionHelper.cs index 25dc6b650aa9c..d3a6593c388c7 100644 --- a/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/ExtensionMethodImportCompletionHelper.cs +++ b/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/ExtensionMethodImportCompletionHelper.cs @@ -6,11 +6,9 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; -using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Collections; -using Microsoft.CodeAnalysis.Completion.Log; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/ImportCompletionItem.cs b/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/ImportCompletionItem.cs index 1b740b06cdcad..9c6ba981cc49c 100644 --- a/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/ImportCompletionItem.cs +++ b/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/ImportCompletionItem.cs @@ -47,19 +47,19 @@ public static CompletionItem Create( if (extensionMethodData.HasValue) { - builder.Add(KeyValuePairUtil.Create(MethodKey, extensionMethodData.Value.methodSymbolKey)); - builder.Add(KeyValuePairUtil.Create(ReceiverKey, extensionMethodData.Value.receiverTypeSymbolKey)); + builder.Add(KeyValuePair.Create(MethodKey, extensionMethodData.Value.methodSymbolKey)); + builder.Add(KeyValuePair.Create(ReceiverKey, extensionMethodData.Value.receiverTypeSymbolKey)); if (extensionMethodData.Value.overloadCount > 0) { - builder.Add(KeyValuePairUtil.Create(OverloadCountKey, extensionMethodData.Value.overloadCount.ToString())); + builder.Add(KeyValuePair.Create(OverloadCountKey, extensionMethodData.Value.overloadCount.ToString())); } } else { // We don't need arity to recover symbol if we already have SymbolKeyData or it's 0. // (but it still needed below to decide whether to show generic suffix) - builder.Add(KeyValuePairUtil.Create(TypeAritySuffixName, ArityUtilities.GetMetadataAritySuffix(arity))); + builder.Add(KeyValuePair.Create(TypeAritySuffixName, ArityUtilities.GetMetadataAritySuffix(arity))); } properties = builder.ToImmutable(); @@ -100,7 +100,7 @@ public static CompletionItem CreateAttributeItemWithoutSuffix(CompletionItem att // Remember the full type name so we can get the symbol when description is displayed. var builder = new FixedSizeArrayBuilder>(attributeItems.Length + 1); builder.AddRange(attributeItems); - builder.Add(KeyValuePairUtil.Create(AttributeFullName, attributeItem.DisplayText)); + builder.Add(KeyValuePair.Create(AttributeFullName, attributeItem.DisplayText)); var sortTextBuilder = PooledStringBuilder.GetInstance(); sortTextBuilder.Builder.AppendFormat(GetSortTextFormatString(attributeItem.InlineDescription), attributeNameWithoutSuffix, attributeItem.InlineDescription); @@ -218,7 +218,7 @@ private static (ISymbol? symbol, int overloadCount) GetSymbolAndOverloadCount(Co public static CompletionItem MarkItemToAlwaysFullyQualify(CompletionItem item) { var itemProperties = item.GetProperties(); - ImmutableArray> properties = [.. itemProperties, KeyValuePairUtil.Create(AlwaysFullyQualifyKey, AlwaysFullyQualifyKey)]; + ImmutableArray> properties = [.. itemProperties, KeyValuePair.Create(AlwaysFullyQualifyKey, AlwaysFullyQualifyKey)]; return item.WithProperties(properties); } diff --git a/src/Features/Core/Portable/Completion/Providers/MemberInsertingCompletionItem.cs b/src/Features/Core/Portable/Completion/Providers/MemberInsertingCompletionItem.cs index 652a2c1bf1535..4d814c1d3091c 100644 --- a/src/Features/Core/Portable/Completion/Providers/MemberInsertingCompletionItem.cs +++ b/src/Features/Core/Portable/Completion/Providers/MemberInsertingCompletionItem.cs @@ -2,11 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageService; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers; @@ -28,9 +28,9 @@ public static CompletionItem Create( symbols: [symbol], contextPosition: descriptionPosition, properties: [ - KeyValuePairUtil.Create("Line", line.ToString()), - KeyValuePairUtil.Create("Modifiers", modifiers.ToString()), - KeyValuePairUtil.Create("TokenSpanEnd", token.Span.End.ToString())], + KeyValuePair.Create("Line", line.ToString()), + KeyValuePair.Create("Modifiers", modifiers.ToString()), + KeyValuePair.Create("TokenSpanEnd", token.Span.End.ToString())], rules: rules, isComplexTextEdit: true); } diff --git a/src/Features/Core/Portable/Completion/Providers/Scripting/AbstractDirectivePathCompletionProvider.cs b/src/Features/Core/Portable/Completion/Providers/Scripting/AbstractDirectivePathCompletionProvider.cs index 3ebcf6c66c0cc..50d4e8e80ace7 100644 --- a/src/Features/Core/Portable/Completion/Providers/Scripting/AbstractDirectivePathCompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/Providers/Scripting/AbstractDirectivePathCompletionProvider.cs @@ -4,15 +4,15 @@ using System; using System.Collections.Immutable; +using System.Diagnostics; using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis.Options; -using Microsoft.CodeAnalysis.Text; -using Roslyn.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; -using System.Diagnostics; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Scripting.Hosting; using Microsoft.CodeAnalysis.Shared.Extensions; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers; diff --git a/src/Features/Core/Portable/Completion/Providers/Scripting/AbstractLoadDirectiveCompletionProvider.cs b/src/Features/Core/Portable/Completion/Providers/Scripting/AbstractLoadDirectiveCompletionProvider.cs index 72bc45690570d..75ca7bb970242 100644 --- a/src/Features/Core/Portable/Completion/Providers/Scripting/AbstractLoadDirectiveCompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/Providers/Scripting/AbstractLoadDirectiveCompletionProvider.cs @@ -4,6 +4,7 @@ using System.Collections.Immutable; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Collections; using Roslyn.Utilities; diff --git a/src/Features/Core/Portable/Completion/Providers/Scripting/AbstractReferenceDirectiveCompletionProvider.cs b/src/Features/Core/Portable/Completion/Providers/Scripting/AbstractReferenceDirectiveCompletionProvider.cs index b1b4b2e362558..ed54e2ab0d2f3 100644 --- a/src/Features/Core/Portable/Completion/Providers/Scripting/AbstractReferenceDirectiveCompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/Providers/Scripting/AbstractReferenceDirectiveCompletionProvider.cs @@ -4,6 +4,7 @@ #nullable disable +using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Features/Core/Portable/Completion/Providers/Snippets/SnippetCompletionItem.cs b/src/Features/Core/Portable/Completion/Providers/Snippets/SnippetCompletionItem.cs index f8da6b9a4831c..434f2bdc94851 100644 --- a/src/Features/Core/Portable/Completion/Providers/Snippets/SnippetCompletionItem.cs +++ b/src/Features/Core/Portable/Completion/Providers/Snippets/SnippetCompletionItem.cs @@ -3,7 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; -using Roslyn.Utilities; +using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Completion.Providers.Snippets; @@ -31,8 +31,8 @@ public static CompletionItem Create( sortText: snippetIdentifier + " ", filterText: snippetIdentifier, properties: [ - KeyValuePairUtil.Create("Position", position.ToString()), - KeyValuePairUtil.Create(SnippetIdentifierKey, snippetIdentifier)], + KeyValuePair.Create("Position", position.ToString()), + KeyValuePair.Create(SnippetIdentifierKey, snippetIdentifier)], isComplexTextEdit: true, inlineDescription: inlineDescription, rules: CompletionItemRules.Default) diff --git a/src/Features/Core/Portable/Completion/Providers/SymbolCompletionItem.cs b/src/Features/Core/Portable/Completion/Providers/SymbolCompletionItem.cs index 0d8ad3bde2e12..0d2060c7d402c 100644 --- a/src/Features/Core/Portable/Completion/Providers/SymbolCompletionItem.cs +++ b/src/Features/Core/Portable/Completion/Providers/SymbolCompletionItem.cs @@ -50,9 +50,9 @@ private static CompletionItem CreateWorker( builder.AddRange(properties); if (insertionText != null) - builder.Add(KeyValuePairUtil.Create(InsertionTextProperty, insertionText)); + builder.Add(KeyValuePair.Create(InsertionTextProperty, insertionText)); - builder.Add(KeyValuePairUtil.Create("ContextPosition", contextPosition.ToString())); + builder.Add(KeyValuePair.Create("ContextPosition", contextPosition.ToString())); AddSupportedPlatforms(builder, supportedPlatforms); symbolEncoder(symbols, builder); @@ -79,17 +79,17 @@ private static CompletionItem CreateWorker( } private static void AddSymbolEncoding(ImmutableArray symbols, ArrayBuilder> properties) - => properties.Add(KeyValuePairUtil.Create("Symbols", EncodeSymbols(symbols))); + => properties.Add(KeyValuePair.Create("Symbols", EncodeSymbols(symbols))); private static void AddSymbolInfo(ImmutableArray symbols, ArrayBuilder> properties) { var symbol = symbols[0]; var isGeneric = symbol.GetArity() > 0; - properties.Add(KeyValuePairUtil.Create("SymbolKind", SmallNumberFormatter.ToString((int)symbol.Kind))); - properties.Add(KeyValuePairUtil.Create("SymbolName", symbol.Name)); + properties.Add(KeyValuePair.Create("SymbolKind", SmallNumberFormatter.ToString((int)symbol.Kind))); + properties.Add(KeyValuePair.Create("SymbolName", symbol.Name)); if (isGeneric) - properties.Add(KeyValuePairUtil.Create("IsGeneric", isGeneric.ToString())); + properties.Add(KeyValuePair.Create("IsGeneric", isGeneric.ToString())); } public static CompletionItem AddShouldProvideParenthesisCompletion(CompletionItem item) @@ -224,8 +224,8 @@ private static void AddSupportedPlatforms(ArrayBuilder id.Id)))); - properties.Add(KeyValuePairUtil.Create("CandidateProjects", string.Join(";", supportedPlatforms.CandidateProjects.Select(id => id.Id)))); + properties.Add(KeyValuePair.Create("InvalidProjects", string.Join(";", supportedPlatforms.InvalidProjects.Select(id => id.Id)))); + properties.Add(KeyValuePair.Create("CandidateProjects", string.Join(";", supportedPlatforms.CandidateProjects.Select(id => id.Id)))); } } diff --git a/src/Features/Core/Portable/Completion/Providers/XmlDocCommentCompletionItem.cs b/src/Features/Core/Portable/Completion/Providers/XmlDocCommentCompletionItem.cs index f35a7520ef974..28f52bcc76388 100644 --- a/src/Features/Core/Portable/Completion/Providers/XmlDocCommentCompletionItem.cs +++ b/src/Features/Core/Portable/Completion/Providers/XmlDocCommentCompletionItem.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Roslyn.Utilities; +using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Completion.Providers; @@ -23,8 +23,8 @@ public static CompletionItem Create(string displayText, string beforeCaretText, displayTextSuffix: "", glyph: Glyph.Keyword, properties: [ - KeyValuePairUtil.Create(BeforeCaretText, beforeCaretText), - KeyValuePairUtil.Create(AfterCaretText, afterCaretText)], + KeyValuePair.Create(BeforeCaretText, beforeCaretText), + KeyValuePair.Create(AfterCaretText, afterCaretText)], rules: rules, isComplexTextEdit: true); } diff --git a/src/Features/Core/Portable/Completion/Utilities.cs b/src/Features/Core/Portable/Completion/Utilities.cs index ca694d75aac45..370628f2d5a39 100644 --- a/src/Features/Core/Portable/Completion/Utilities.cs +++ b/src/Features/Core/Portable/Completion/Utilities.cs @@ -3,13 +3,13 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; -using Roslyn.Utilities; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Text; -using Microsoft.CodeAnalysis.Shared.Extensions; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion; diff --git a/src/Features/Core/Portable/Contracts/EditAndContinue/ManagedHotReloadUpdate.cs b/src/Features/Core/Portable/Contracts/EditAndContinue/ManagedHotReloadUpdate.cs index 634d3beb09340..b6bd26ed71d95 100644 --- a/src/Features/Core/Portable/Contracts/EditAndContinue/ManagedHotReloadUpdate.cs +++ b/src/Features/Core/Portable/Contracts/EditAndContinue/ManagedHotReloadUpdate.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Runtime.Serialization; using System; using System.Collections.Immutable; +using System.Runtime.Serialization; namespace Microsoft.CodeAnalysis.Contracts.EditAndContinue; diff --git a/src/Features/Core/Portable/Contracts/EditAndContinue/ManagedInstructionId.cs b/src/Features/Core/Portable/Contracts/EditAndContinue/ManagedInstructionId.cs index a8d27b42a3eeb..529d222a1f4f3 100644 --- a/src/Features/Core/Portable/Contracts/EditAndContinue/ManagedInstructionId.cs +++ b/src/Features/Core/Portable/Contracts/EditAndContinue/ManagedInstructionId.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Runtime.Serialization; using System; using System.Diagnostics; +using System.Runtime.Serialization; namespace Microsoft.CodeAnalysis.Contracts.EditAndContinue; diff --git a/src/Features/Core/Portable/Contracts/EditAndContinue/ManagedMethodId.cs b/src/Features/Core/Portable/Contracts/EditAndContinue/ManagedMethodId.cs index 3e82d40699cdf..09ee56fd88114 100644 --- a/src/Features/Core/Portable/Contracts/EditAndContinue/ManagedMethodId.cs +++ b/src/Features/Core/Portable/Contracts/EditAndContinue/ManagedMethodId.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Runtime.Serialization; using System; using System.Diagnostics; +using System.Runtime.Serialization; namespace Microsoft.CodeAnalysis.Contracts.EditAndContinue; diff --git a/src/Features/Core/Portable/Contracts/EditAndContinue/ManagedModuleMethodId.cs b/src/Features/Core/Portable/Contracts/EditAndContinue/ManagedModuleMethodId.cs index 351f59fd7fb90..d612fe20e2609 100644 --- a/src/Features/Core/Portable/Contracts/EditAndContinue/ManagedModuleMethodId.cs +++ b/src/Features/Core/Portable/Contracts/EditAndContinue/ManagedModuleMethodId.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Runtime.Serialization; using System; using System.Diagnostics; +using System.Runtime.Serialization; namespace Microsoft.CodeAnalysis.Contracts.EditAndContinue; diff --git a/src/Features/Core/Portable/Contracts/EditAndContinue/SequencePointUpdates.cs b/src/Features/Core/Portable/Contracts/EditAndContinue/SequencePointUpdates.cs index b4f96d8db5b61..6fafce2ed9a9e 100644 --- a/src/Features/Core/Portable/Contracts/EditAndContinue/SequencePointUpdates.cs +++ b/src/Features/Core/Portable/Contracts/EditAndContinue/SequencePointUpdates.cs @@ -2,8 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Runtime.Serialization; using System.Collections.Immutable; +using System.Runtime.Serialization; namespace Microsoft.CodeAnalysis.Contracts.EditAndContinue; diff --git a/src/Features/Core/Portable/Contracts/EditAndContinue/SourceLineUpdate.cs b/src/Features/Core/Portable/Contracts/EditAndContinue/SourceLineUpdate.cs index 18e140c7e3078..04b1f033186ff 100644 --- a/src/Features/Core/Portable/Contracts/EditAndContinue/SourceLineUpdate.cs +++ b/src/Features/Core/Portable/Contracts/EditAndContinue/SourceLineUpdate.cs @@ -2,8 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Runtime.Serialization; using System; +using System.Runtime.Serialization; namespace Microsoft.CodeAnalysis.Contracts.EditAndContinue; diff --git a/src/Features/Core/Portable/Contracts/EditAndContinue/SourceSpan.cs b/src/Features/Core/Portable/Contracts/EditAndContinue/SourceSpan.cs index 4c1fd7aeb6adc..fc91e027e737c 100644 --- a/src/Features/Core/Portable/Contracts/EditAndContinue/SourceSpan.cs +++ b/src/Features/Core/Portable/Contracts/EditAndContinue/SourceSpan.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Runtime.Serialization; using System; using System.Diagnostics; +using System.Runtime.Serialization; namespace Microsoft.CodeAnalysis.Contracts.EditAndContinue; diff --git a/src/Features/Core/Portable/ConvertIfToSwitch/AbstractConvertIfToSwitchCodeRefactoringProvider.Analyzer.cs b/src/Features/Core/Portable/ConvertIfToSwitch/AbstractConvertIfToSwitchCodeRefactoringProvider.Analyzer.cs index e9e407707f585..c57f80b7da3a0 100644 --- a/src/Features/Core/Portable/ConvertIfToSwitch/AbstractConvertIfToSwitchCodeRefactoringProvider.Analyzer.cs +++ b/src/Features/Core/Portable/ConvertIfToSwitch/AbstractConvertIfToSwitchCodeRefactoringProvider.Analyzer.cs @@ -56,7 +56,8 @@ internal abstract class Analyzer(ISyntaxFacts syntaxFacts, AbstractConvertIfToSw /// /// Note that this is initially unset until we find a non-constant expression. /// - private SyntaxNode _switchTargetExpression = null!; + private TExpressionSyntax _switchTargetExpression = null!; + /// /// Holds the type of the /// @@ -68,7 +69,7 @@ internal abstract class Analyzer(ISyntaxFacts syntaxFacts, AbstractConvertIfToSw public bool Supports(Feature feature) => (Features & feature) != 0; - public (ImmutableArray, SyntaxNode TargetExpression) AnalyzeIfStatementSequence(ReadOnlySpan operations) + public (ImmutableArray, TExpressionSyntax TargetExpression) AnalyzeIfStatementSequence(ReadOnlySpan operations) { using var _ = ArrayBuilder.GetInstance(out var sections); if (!ParseIfStatementSequence(operations, sections, topLevel: true, out var defaultBodyOpt)) @@ -450,7 +451,9 @@ private bool CheckTargetExpression(IOperation operation) { operation = operation.WalkDownConversion(); - var expression = operation.Syntax; + if (operation.Syntax is not TExpressionSyntax expression) + return false; + // If we have not figured the switch expression yet, // we will assume that the first expression is the one. if (_switchTargetExpression is null) diff --git a/src/Features/Core/Portable/ConvertIfToSwitch/AbstractConvertIfToSwitchCodeRefactoringProvider.Rewriting.cs b/src/Features/Core/Portable/ConvertIfToSwitch/AbstractConvertIfToSwitchCodeRefactoringProvider.Rewriting.cs index 458ef2e30fbe1..3819ae7b88b6b 100644 --- a/src/Features/Core/Portable/ConvertIfToSwitch/AbstractConvertIfToSwitchCodeRefactoringProvider.Rewriting.cs +++ b/src/Features/Core/Portable/ConvertIfToSwitch/AbstractConvertIfToSwitchCodeRefactoringProvider.Rewriting.cs @@ -12,22 +12,21 @@ using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ConvertIfToSwitch; internal abstract partial class AbstractConvertIfToSwitchCodeRefactoringProvider< TIfStatementSyntax, TExpressionSyntax, TIsExpressionSyntax, TPatternSyntax> { - public abstract SyntaxNode CreateSwitchExpressionStatement(SyntaxNode target, ImmutableArray sections, Feature feature); - public abstract SyntaxNode CreateSwitchStatement(TIfStatementSyntax ifStatement, SyntaxNode target, IEnumerable sectionList); + public abstract SyntaxNode CreateSwitchExpressionStatement(TExpressionSyntax target, ImmutableArray sections, Feature feature); + public abstract SyntaxNode CreateSwitchStatement(TIfStatementSyntax ifStatement, TExpressionSyntax target, IEnumerable sectionList); public abstract IEnumerable AsSwitchSectionStatements(IOperation operation); public abstract SyntaxNode AsSwitchLabelSyntax(AnalyzedSwitchLabel label, Feature feature); protected abstract SyntaxTriviaList GetLeadingTriviaToTransfer(SyntaxNode syntaxToRemove); private async Task UpdateDocumentAsync( Document document, - SyntaxNode target, + TExpressionSyntax target, TIfStatementSyntax ifStatement, ImmutableArray sections, Feature feature, @@ -47,8 +46,7 @@ private async Task UpdateDocumentAsync( @switch = @switch .WithLeadingTrivia(ifStatement.GetLeadingTrivia()) .WithTrailingTrivia(lastNode.GetTrailingTrivia()) - .WithAdditionalAnnotations(Formatter.Annotation) - .WithAdditionalAnnotations(Simplifier.Annotation); + .WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation); var nodesToRemove = sections.Skip(1).Select(s => s.SyntaxToRemove).Where(s => s.Parent == ifStatement.Parent); root = root.RemoveNodes(nodesToRemove, SyntaxRemoveOptions.KeepNoTrivia); diff --git a/src/Features/Core/Portable/ConvertIfToSwitch/AbstractConvertIfToSwitchCodeRefactoringProvider.cs b/src/Features/Core/Portable/ConvertIfToSwitch/AbstractConvertIfToSwitchCodeRefactoringProvider.cs index 2b215f791388a..2723f8b73cfb1 100644 --- a/src/Features/Core/Portable/ConvertIfToSwitch/AbstractConvertIfToSwitchCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/ConvertIfToSwitch/AbstractConvertIfToSwitchCodeRefactoringProvider.cs @@ -42,7 +42,9 @@ public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContex var ifStatement = await context.TryGetRelevantNodeAsync().ConfigureAwait(false); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxFactsService = document.GetRequiredLanguageService(); - if (!ShouldOfferRefactoring(ifStatement, semanticModel, syntaxFactsService, out var analyzer, out var sections, out var target)) + if (!ShouldOfferRefactoring( + ifStatement, semanticModel, syntaxFactsService, + out var analyzer, out var sections, out var target)) { return; } @@ -72,7 +74,7 @@ private bool ShouldOfferRefactoring( ISyntaxFactsService syntaxFactsService, [NotNullWhen(true)] out Analyzer? analyzer, [NotNullWhen(true)] out ImmutableArray sections, - [NotNullWhen(true)] out SyntaxNode? target) + [NotNullWhen(true)] out TExpressionSyntax? target) { analyzer = null; sections = default; diff --git a/src/Features/Core/Portable/ConvertNumericLiteral/AbstractConvertNumericLiteralCodeRefactoringProvider.cs b/src/Features/Core/Portable/ConvertNumericLiteral/AbstractConvertNumericLiteralCodeRefactoringProvider.cs index 9232c9c2e6f46..4bcc920a74e59 100644 --- a/src/Features/Core/Portable/ConvertNumericLiteral/AbstractConvertNumericLiteralCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/ConvertNumericLiteral/AbstractConvertNumericLiteralCodeRefactoringProvider.cs @@ -7,6 +7,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Shared.Collections; diff --git a/src/Features/Core/Portable/ConvertToInterpolatedString/AbstractConvertPlaceholderToInterpolatedStringRefactoringProvider.cs b/src/Features/Core/Portable/ConvertToInterpolatedString/AbstractConvertPlaceholderToInterpolatedStringRefactoringProvider.cs index 45f15e9dc395f..f6dd0b180b2f2 100644 --- a/src/Features/Core/Portable/ConvertToInterpolatedString/AbstractConvertPlaceholderToInterpolatedStringRefactoringProvider.cs +++ b/src/Features/Core/Portable/ConvertToInterpolatedString/AbstractConvertPlaceholderToInterpolatedStringRefactoringProvider.cs @@ -369,7 +369,7 @@ ImmutableArray GetReorderedArgumentsAfterPlaceholderArgument() }); } - return unnamedArguments.Concat(namedAndUnnamedArguments); + return [.. unnamedArguments, .. namedAndUnnamedArguments]; } ImmutableArray ExpandArgumentExpressions(ImmutableArray argumentsAfterPlaceholder) diff --git a/src/Features/Core/Portable/ConvertTupleToStruct/AbstractConvertTupleToStructCodeRefactoringProvider.cs b/src/Features/Core/Portable/ConvertTupleToStruct/AbstractConvertTupleToStructCodeRefactoringProvider.cs index 2547e03fcc758..5b00e0e45a849 100644 --- a/src/Features/Core/Portable/ConvertTupleToStruct/AbstractConvertTupleToStructCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/ConvertTupleToStruct/AbstractConvertTupleToStructCodeRefactoringProvider.cs @@ -13,6 +13,7 @@ using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CodeRefactorings; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; diff --git a/src/Features/Core/Portable/Copilot/ICopilotChangeAnalysisService.cs b/src/Features/Core/Portable/Copilot/ICopilotChangeAnalysisService.cs index 9187b29aa4500..b3a6f8379ec96 100644 --- a/src/Features/Core/Portable/Copilot/ICopilotChangeAnalysisService.cs +++ b/src/Features/Core/Portable/Copilot/ICopilotChangeAnalysisService.cs @@ -11,6 +11,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; diff --git a/src/Features/Core/Portable/Copilot/ICopilotOptionsService.cs b/src/Features/Core/Portable/Copilot/ICopilotOptionsService.cs index fce617f51ef5b..d76f285fb7b5c 100644 --- a/src/Features/Core/Portable/Copilot/ICopilotOptionsService.cs +++ b/src/Features/Core/Portable/Copilot/ICopilotOptionsService.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; diff --git a/src/Features/Core/Portable/Copilot/IRemoteCopilotChangeAnalysisService.cs b/src/Features/Core/Portable/Copilot/IRemoteCopilotChangeAnalysisService.cs index d7cb6a1305e19..185b9de3eb944 100644 --- a/src/Features/Core/Portable/Copilot/IRemoteCopilotChangeAnalysisService.cs +++ b/src/Features/Core/Portable/Copilot/IRemoteCopilotChangeAnalysisService.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; diff --git a/src/Features/Core/Portable/DesignerAttribute/IDesignerAttributeDiscoveryService.cs b/src/Features/Core/Portable/DesignerAttribute/IDesignerAttributeDiscoveryService.cs index 4bb68520a5e95..58ff3949d9e0d 100644 --- a/src/Features/Core/Portable/DesignerAttribute/IDesignerAttributeDiscoveryService.cs +++ b/src/Features/Core/Portable/DesignerAttribute/IDesignerAttributeDiscoveryService.cs @@ -11,7 +11,7 @@ namespace Microsoft.CodeAnalysis.DesignerAttribute; internal partial interface IDesignerAttributeDiscoveryService : IWorkspaceService { - public interface ICallback + interface ICallback { ValueTask ReportDesignerAttributeDataAsync(ImmutableArray data, CancellationToken cancellationToken); } diff --git a/src/Features/Core/Portable/Diagnostics/CodeAnalysisDiagnosticAnalyzerService.cs b/src/Features/Core/Portable/Diagnostics/CodeAnalysisDiagnosticAnalyzerService.cs index f8d4fc175748f..62ccb84a89d9c 100644 --- a/src/Features/Core/Portable/Diagnostics/CodeAnalysisDiagnosticAnalyzerService.cs +++ b/src/Features/Core/Portable/Diagnostics/CodeAnalysisDiagnosticAnalyzerService.cs @@ -6,7 +6,6 @@ using System.Collections.Concurrent; using System.Collections.Immutable; using System.Composition; -using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; diff --git a/src/Features/Core/Portable/Diagnostics/DiagnosticAnalyzerTelemetry.cs b/src/Features/Core/Portable/Diagnostics/DiagnosticAnalyzerTelemetry.cs index 3348521b037fb..4baf8b6e363d6 100644 --- a/src/Features/Core/Portable/Diagnostics/DiagnosticAnalyzerTelemetry.cs +++ b/src/Features/Core/Portable/Diagnostics/DiagnosticAnalyzerTelemetry.cs @@ -5,6 +5,7 @@ #nullable disable using System; +using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Diagnostics.Telemetry; using Microsoft.CodeAnalysis.Internal.Log; diff --git a/src/Features/Core/Portable/Diagnostics/Service/DocumentAnalysisExecutor_Helpers.cs b/src/Features/Core/Portable/Diagnostics/Service/DocumentAnalysisExecutor_Helpers.cs index 1806d26f3783f..5ce05265a3edd 100644 --- a/src/Features/Core/Portable/Diagnostics/Service/DocumentAnalysisExecutor_Helpers.cs +++ b/src/Features/Core/Portable/Diagnostics/Service/DocumentAnalysisExecutor_Helpers.cs @@ -9,7 +9,6 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.SolutionCrawler; -using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics; diff --git a/src/Features/Core/Portable/Diagnostics/Service/EngineV2/DiagnosticIncrementalAnalyzer.Executor.cs b/src/Features/Core/Portable/Diagnostics/Service/EngineV2/DiagnosticIncrementalAnalyzer.Executor.cs index 160f549217975..1314e1f71d2d5 100644 --- a/src/Features/Core/Portable/Diagnostics/Service/EngineV2/DiagnosticIncrementalAnalyzer.Executor.cs +++ b/src/Features/Core/Portable/Diagnostics/Service/EngineV2/DiagnosticIncrementalAnalyzer.Executor.cs @@ -3,15 +3,14 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections.Generic; using System.Collections.Immutable; -using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics.Telemetry; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; -using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Workspaces.Diagnostics; using Roslyn.Utilities; diff --git a/src/Features/Core/Portable/Diagnostics/Service/EngineV2/DiagnosticIncrementalAnalyzer_IncrementalAnalyzer.cs b/src/Features/Core/Portable/Diagnostics/Service/EngineV2/DiagnosticIncrementalAnalyzer_IncrementalAnalyzer.cs index 9c703208bb56d..f017acab6d9ca 100644 --- a/src/Features/Core/Portable/Diagnostics/Service/EngineV2/DiagnosticIncrementalAnalyzer_IncrementalAnalyzer.cs +++ b/src/Features/Core/Portable/Diagnostics/Service/EngineV2/DiagnosticIncrementalAnalyzer_IncrementalAnalyzer.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Immutable; +using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; diff --git a/src/Features/Core/Portable/DocumentHighlighting/AbstractDocumentHighlightsService.cs b/src/Features/Core/Portable/DocumentHighlighting/AbstractDocumentHighlightsService.cs index f4075ce374447..80242ba5df545 100644 --- a/src/Features/Core/Portable/DocumentHighlighting/AbstractDocumentHighlightsService.cs +++ b/src/Features/Core/Portable/DocumentHighlighting/AbstractDocumentHighlightsService.cs @@ -53,7 +53,7 @@ public async Task> GetDocumentHighlightsAsync return []; } - return await result.Value.SelectAsArrayAsync(h => h.RehydrateAsync(solution)).ConfigureAwait(false); + return await result.Value.SelectAsArrayAsync(h => h.RehydrateAsync(solution, cancellationToken)).ConfigureAwait(false); } return await GetDocumentHighlightsInCurrentProcessAsync( diff --git a/src/Features/Core/Portable/DocumentHighlighting/IRemoteDocumentHighlightsService.cs b/src/Features/Core/Portable/DocumentHighlighting/IRemoteDocumentHighlightsService.cs index 5570bbf6403af..532f609e63372 100644 --- a/src/Features/Core/Portable/DocumentHighlighting/IRemoteDocumentHighlightsService.cs +++ b/src/Features/Core/Portable/DocumentHighlighting/IRemoteDocumentHighlightsService.cs @@ -25,8 +25,8 @@ internal readonly struct SerializableDocumentHighlights(DocumentId documentId, I [DataMember(Order = 1)] public readonly ImmutableArray HighlightSpans = highlightSpans; - public async ValueTask RehydrateAsync(Solution solution) - => new(await solution.GetRequiredDocumentAsync(DocumentId, includeSourceGenerated: true).ConfigureAwait(false), HighlightSpans); + public async ValueTask RehydrateAsync(Solution solution, CancellationToken cancellationToken) + => new(await solution.GetRequiredDocumentAsync(DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false), HighlightSpans); public static SerializableDocumentHighlights Dehydrate(DocumentHighlights highlights) => new(highlights.Document.Id, highlights.HighlightSpans); diff --git a/src/Features/Core/Portable/EditAndContinue/AbstractEditAndContinueAnalyzer.ActiveMembersBuilder.cs b/src/Features/Core/Portable/EditAndContinue/AbstractEditAndContinueAnalyzer.ActiveMembersBuilder.cs index 8e50c08b0bef0..5a45c7fe745e0 100644 --- a/src/Features/Core/Portable/EditAndContinue/AbstractEditAndContinueAnalyzer.ActiveMembersBuilder.cs +++ b/src/Features/Core/Portable/EditAndContinue/AbstractEditAndContinueAnalyzer.ActiveMembersBuilder.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Features/Core/Portable/EditAndContinue/AbstractEditAndContinueAnalyzer.cs b/src/Features/Core/Portable/EditAndContinue/AbstractEditAndContinueAnalyzer.cs index 2f5081583c8c9..9e6c0d9456a22 100644 --- a/src/Features/Core/Portable/EditAndContinue/AbstractEditAndContinueAnalyzer.cs +++ b/src/Features/Core/Portable/EditAndContinue/AbstractEditAndContinueAnalyzer.cs @@ -1623,7 +1623,7 @@ private void ReportStateMachineBodyUpdateRudeEdits( if (activeNode.NewTrackedNode != null) { lazyKnownMatches ??= []; - lazyKnownMatches.Add(KeyValuePairUtil.Create(activeNode.OldNode, activeNode.NewTrackedNode)); + lazyKnownMatches.Add(KeyValuePair.Create(activeNode.OldNode, activeNode.NewTrackedNode)); } } diff --git a/src/Features/Core/Portable/EditAndContinue/AbstractSimpleMemberBody.cs b/src/Features/Core/Portable/EditAndContinue/AbstractSimpleMemberBody.cs index 1d1e312a973e2..cbce99bce2639 100644 --- a/src/Features/Core/Portable/EditAndContinue/AbstractSimpleMemberBody.cs +++ b/src/Features/Core/Portable/EditAndContinue/AbstractSimpleMemberBody.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/Features/Core/Portable/EditAndContinue/ActiveStatement.cs b/src/Features/Core/Portable/EditAndContinue/ActiveStatement.cs index e30af136737aa..2e0da080312af 100644 --- a/src/Features/Core/Portable/EditAndContinue/ActiveStatement.cs +++ b/src/Features/Core/Portable/EditAndContinue/ActiveStatement.cs @@ -3,8 +3,8 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; -using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Contracts.EditAndContinue; +using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.EditAndContinue; diff --git a/src/Features/Core/Portable/EditAndContinue/ActiveStatementsMap.cs b/src/Features/Core/Portable/EditAndContinue/ActiveStatementsMap.cs index 1d41e2e28ecd3..606ee12ec6797 100644 --- a/src/Features/Core/Portable/EditAndContinue/ActiveStatementsMap.cs +++ b/src/Features/Core/Portable/EditAndContinue/ActiveStatementsMap.cs @@ -9,9 +9,9 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; -using Microsoft.CodeAnalysis.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue; diff --git a/src/Features/Core/Portable/EditAndContinue/CommittedSolution.cs b/src/Features/Core/Portable/EditAndContinue/CommittedSolution.cs index c23829e2ebc11..301b470b4adb4 100644 --- a/src/Features/Core/Portable/EditAndContinue/CommittedSolution.cs +++ b/src/Features/Core/Portable/EditAndContinue/CommittedSolution.cs @@ -11,6 +11,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Shared.Extensions; @@ -433,7 +434,7 @@ await TryGetMatchingSourceTextAsync(log, sourceText, sourceFilePath, currentDocu var documentIdArrays = await Task.WhenAll(projectTasks).ConfigureAwait(false); - return documentIdArrays.SelectMany(ids => ids.WhereNotNull()).Select(id => KeyValuePairUtil.Create(id, DocumentState.MatchesBuildOutput)); + return documentIdArrays.SelectMany(ids => ids.WhereNotNull()).Select(id => KeyValuePair.Create(id, DocumentState.MatchesBuildOutput)); } private static DebugInformationReaderProvider? GetMethodDebugInfoReader(TraceLog log, CompilationOutputs compilationOutputs, string projectName) diff --git a/src/Features/Core/Portable/EditAndContinue/DeclarationBody.cs b/src/Features/Core/Portable/EditAndContinue/DeclarationBody.cs index da56617d2ed87..838c0ec66d988 100644 --- a/src/Features/Core/Portable/EditAndContinue/DeclarationBody.cs +++ b/src/Features/Core/Portable/EditAndContinue/DeclarationBody.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Differencing; using Roslyn.Utilities; diff --git a/src/Features/Core/Portable/EditAndContinue/DeclarationBodyMap.cs b/src/Features/Core/Portable/EditAndContinue/DeclarationBodyMap.cs index 7055fe2c49956..ea00a15f7d5a5 100644 --- a/src/Features/Core/Portable/EditAndContinue/DeclarationBodyMap.cs +++ b/src/Features/Core/Portable/EditAndContinue/DeclarationBodyMap.cs @@ -6,7 +6,6 @@ using System.Collections.Immutable; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Differencing; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue; diff --git a/src/Features/Core/Portable/EditAndContinue/EditSession.cs b/src/Features/Core/Portable/EditAndContinue/EditSession.cs index c503af3bb49f7..e0f2065908a86 100644 --- a/src/Features/Core/Portable/EditAndContinue/EditSession.cs +++ b/src/Features/Core/Portable/EditAndContinue/EditSession.cs @@ -943,7 +943,7 @@ void UpdateChangedDocumentsStaleness(bool isStale) if (mvid == Guid.Empty) { - Log.Write($"Changes not applied to {newProject.Name} '{newProject.FilePath}': project not built"); + Log.Write($"Changes not applied to {newProject.GetLogDisplay()}: project not built"); UpdateChangedDocumentsStaleness(isStale: true); continue; } @@ -970,7 +970,7 @@ void UpdateChangedDocumentsStaleness(bool isStale) { // The project is considered stale as long as it has at least one document that is out-of-sync. // Treat the project the same as if it hasn't been built. We won't produce delta for it until it gets rebuilt. - Log.Write($"Changes not applied to {newProject.Name} '{newProject.FilePath}': binaries not up-to-date"); + Log.Write($"Changes not applied to {newProject.GetLogDisplay()}: binaries not up-to-date"); projectsToStale.Add(newProject.Id); UpdateChangedDocumentsStaleness(isStale: true); @@ -999,7 +999,7 @@ void UpdateChangedDocumentsStaleness(bool isStale) } var projectSummary = GetProjectAnalysisSummary(changedDocumentAnalyses); - Log.Write($"Project summary for {newProject.Name} '{newProject.FilePath}': {projectSummary}"); + Log.Write($"Project summary for {newProject.GetLogDisplay()}: {projectSummary}"); if (projectSummary is ProjectAnalysisSummary.NoChanges or ProjectAnalysisSummary.ValidInsignificantChanges) { @@ -1050,7 +1050,7 @@ void UpdateChangedDocumentsStaleness(bool isStale) continue; } - Log.Write($"Emitting update of {newProject.Name} '{newProject.FilePath}': project not built"); + Log.Write($"Emitting update of {newProject.GetLogDisplay()}"); var newCompilation = await newProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Features/Core/Portable/EditAndContinue/EditSessionTelemetry.cs b/src/Features/Core/Portable/EditAndContinue/EditSessionTelemetry.cs index 33aad51f75d98..ac882f11e9447 100644 --- a/src/Features/Core/Portable/EditAndContinue/EditSessionTelemetry.cs +++ b/src/Features/Core/Portable/EditAndContinue/EditSessionTelemetry.cs @@ -6,7 +6,6 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue; diff --git a/src/Features/Core/Portable/EditAndContinue/EmitSolutionUpdateResults.cs b/src/Features/Core/Portable/EditAndContinue/EmitSolutionUpdateResults.cs index 9ddbacc71d766..60c4a97edd8d0 100644 --- a/src/Features/Core/Portable/EditAndContinue/EmitSolutionUpdateResults.cs +++ b/src/Features/Core/Portable/EditAndContinue/EmitSolutionUpdateResults.cs @@ -7,6 +7,7 @@ using System.Diagnostics; using System.Linq; using System.Runtime.Serialization; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; @@ -432,7 +433,7 @@ public ImmutableArray GetPersistentDiagnostics() { if (!diagnostic.IsEncDiagnostic()) { - result.AddRange(diagnostics); + result.Add(diagnostic); } } } diff --git a/src/Features/Core/Portable/EditAndContinue/ProjectChanges.cs b/src/Features/Core/Portable/EditAndContinue/ProjectChanges.cs index d9b5c6a00baee..a206915616ad0 100644 --- a/src/Features/Core/Portable/EditAndContinue/ProjectChanges.cs +++ b/src/Features/Core/Portable/EditAndContinue/ProjectChanges.cs @@ -4,8 +4,8 @@ using System.Collections.Immutable; using System.Diagnostics; -using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Contracts.EditAndContinue; +using Microsoft.CodeAnalysis.Emit; namespace Microsoft.CodeAnalysis.EditAndContinue; diff --git a/src/Features/Core/Portable/EditAndContinue/Remote/IRemoteEditAndContinueService.cs b/src/Features/Core/Portable/EditAndContinue/Remote/IRemoteEditAndContinueService.cs index 806734d41b877..5f6b14203f2e5 100644 --- a/src/Features/Core/Portable/EditAndContinue/Remote/IRemoteEditAndContinueService.cs +++ b/src/Features/Core/Portable/EditAndContinue/Remote/IRemoteEditAndContinueService.cs @@ -6,10 +6,10 @@ using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; -using Microsoft.CodeAnalysis.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue; diff --git a/src/Features/Core/Portable/EditAndContinue/Remote/RemoteDebuggingSessionProxy.cs b/src/Features/Core/Portable/EditAndContinue/Remote/RemoteDebuggingSessionProxy.cs index 2fa9e13776ec6..a460d799beef7 100644 --- a/src/Features/Core/Portable/EditAndContinue/Remote/RemoteDebuggingSessionProxy.cs +++ b/src/Features/Core/Portable/EditAndContinue/Remote/RemoteDebuggingSessionProxy.cs @@ -4,10 +4,8 @@ using System; using System.Collections.Immutable; -using System.Linq; using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Remote; diff --git a/src/Features/Core/Portable/EditAndContinue/RudeEditDiagnostic.cs b/src/Features/Core/Portable/EditAndContinue/RudeEditDiagnostic.cs index 34e38bee9de28..7d628d36c994d 100644 --- a/src/Features/Core/Portable/EditAndContinue/RudeEditDiagnostic.cs +++ b/src/Features/Core/Portable/EditAndContinue/RudeEditDiagnostic.cs @@ -2,11 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Linq; -using System.Collections.Generic; using System.Runtime.Serialization; using Microsoft.CodeAnalysis.Text; -using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.EditAndContinue; diff --git a/src/Features/Core/Portable/EditAndContinue/RudeEditDiagnosticsBuilder.cs b/src/Features/Core/Portable/EditAndContinue/RudeEditDiagnosticsBuilder.cs index b9f1d5723ee15..c0c37364579a3 100644 --- a/src/Features/Core/Portable/EditAndContinue/RudeEditDiagnosticsBuilder.cs +++ b/src/Features/Core/Portable/EditAndContinue/RudeEditDiagnosticsBuilder.cs @@ -3,8 +3,8 @@ // See the LICENSE file in the project root for more information. using System; -using System.Linq; using System.Collections.Immutable; +using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.EditAndContinue; diff --git a/src/Features/Core/Portable/EditAndContinue/Utilities/BidirectionalMap.cs b/src/Features/Core/Portable/EditAndContinue/Utilities/BidirectionalMap.cs index 7a9c419522d0c..678662c6fcb83 100644 --- a/src/Features/Core/Portable/EditAndContinue/Utilities/BidirectionalMap.cs +++ b/src/Features/Core/Portable/EditAndContinue/Utilities/BidirectionalMap.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Differencing; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue; diff --git a/src/Features/Core/Portable/EditAndContinue/Utilities/Extensions.cs b/src/Features/Core/Portable/EditAndContinue/Utilities/Extensions.cs index 5df8e5934181a..e0eb40acb4b27 100644 --- a/src/Features/Core/Portable/EditAndContinue/Utilities/Extensions.cs +++ b/src/Features/Core/Portable/EditAndContinue/Utilities/Extensions.cs @@ -74,7 +74,7 @@ void LogReason(string message) public static string GetLogDisplay(this Project project) => project.FilePath != null - ? $"'{project.FilePath}' ('{project.State.NameAndFlavor.flavor}')" + ? $"'{project.FilePath}'" + (project.State.NameAndFlavor.flavor is { } flavor ? $" ('{flavor}')" : "") : $"'{project.Name}' ('{project.Id.DebugName}'"; public static bool SupportsEditAndContinue(this TextDocumentState textDocumentState) diff --git a/src/Features/Core/Portable/EmbeddedLanguages/Classification/AbstractFallbackEmbeddedLanguageClassifier.cs b/src/Features/Core/Portable/EmbeddedLanguages/Classification/AbstractFallbackEmbeddedLanguageClassifier.cs index fd14266a8d1b8..4e88e2544259e 100644 --- a/src/Features/Core/Portable/EmbeddedLanguages/Classification/AbstractFallbackEmbeddedLanguageClassifier.cs +++ b/src/Features/Core/Portable/EmbeddedLanguages/Classification/AbstractFallbackEmbeddedLanguageClassifier.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.EmbeddedLanguages; using Microsoft.CodeAnalysis.Shared.Collections; diff --git a/src/Features/Core/Portable/EmbeddedLanguages/DateAndTime/LanguageServices/DateAndTimeLanguageDetector.cs b/src/Features/Core/Portable/EmbeddedLanguages/DateAndTime/LanguageServices/DateAndTimeLanguageDetector.cs index 7235c88b6fe82..ac98e96d93c9d 100644 --- a/src/Features/Core/Portable/EmbeddedLanguages/DateAndTime/LanguageServices/DateAndTimeLanguageDetector.cs +++ b/src/Features/Core/Portable/EmbeddedLanguages/DateAndTime/LanguageServices/DateAndTimeLanguageDetector.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Immutable; using System.Diagnostics; +using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.EmbeddedLanguages; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; diff --git a/src/Features/Core/Portable/EmbeddedLanguages/EmbeddedLanguageInfo.cs b/src/Features/Core/Portable/EmbeddedLanguages/EmbeddedLanguageInfo.cs index 41a9a81237ecc..4ba71c7a0bcf6 100644 --- a/src/Features/Core/Portable/EmbeddedLanguages/EmbeddedLanguageInfo.cs +++ b/src/Features/Core/Portable/EmbeddedLanguages/EmbeddedLanguageInfo.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Shared.Collections; diff --git a/src/Features/Core/Portable/EmbeddedLanguages/Json/JsonNodes.cs b/src/Features/Core/Portable/EmbeddedLanguages/Json/JsonNodes.cs index 53f0d98bed80f..a0d3a936f3f86 100644 --- a/src/Features/Core/Portable/EmbeddedLanguages/Json/JsonNodes.cs +++ b/src/Features/Core/Portable/EmbeddedLanguages/Json/JsonNodes.cs @@ -10,8 +10,8 @@ namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages.Json; using JsonNodeOrToken = EmbeddedSyntaxNodeOrToken; -using JsonToken = EmbeddedSyntaxToken; using JsonSeparatedList = EmbeddedSeparatedSyntaxNodeList; +using JsonToken = EmbeddedSyntaxToken; internal sealed class JsonCompilationUnit : JsonNode { diff --git a/src/Features/Core/Portable/EmbeddedLanguages/Json/JsonParser.cs b/src/Features/Core/Portable/EmbeddedLanguages/Json/JsonParser.cs index 75ce0a69046bb..36be3ff23992f 100644 --- a/src/Features/Core/Portable/EmbeddedLanguages/Json/JsonParser.cs +++ b/src/Features/Core/Portable/EmbeddedLanguages/Json/JsonParser.cs @@ -16,11 +16,10 @@ namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages.Json; using static EmbeddedSyntaxHelpers; using static JsonHelpers; - using JsonNodeOrToken = EmbeddedSyntaxNodeOrToken; +using JsonSeparatedList = EmbeddedSeparatedSyntaxNodeList; using JsonToken = EmbeddedSyntaxToken; using JsonTrivia = EmbeddedSyntaxTrivia; -using JsonSeparatedList = EmbeddedSeparatedSyntaxNodeList; /// /// Parser used for reading in a sequence of s, and producing a ; using RegexNodeOrToken = EmbeddedSyntaxNodeOrToken; using RegexToken = EmbeddedSyntaxToken; -using RegexAlternatingSequenceList = EmbeddedSeparatedSyntaxNodeList; internal sealed class RegexCompilationUnit : RegexNode { diff --git a/src/Features/Core/Portable/EncapsulateField/AbstractEncapsulateFieldService.cs b/src/Features/Core/Portable/EncapsulateField/AbstractEncapsulateFieldService.cs index 64d8bcaba5598..b0dabbaddca9f 100644 --- a/src/Features/Core/Portable/EncapsulateField/AbstractEncapsulateFieldService.cs +++ b/src/Features/Core/Portable/EncapsulateField/AbstractEncapsulateFieldService.cs @@ -11,6 +11,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; diff --git a/src/Features/Core/Portable/Extensions/ExtensionFolder.cs b/src/Features/Core/Portable/Extensions/ExtensionFolder.cs index 0b99cc162aff4..b74d5e37a0ac1 100644 --- a/src/Features/Core/Portable/Extensions/ExtensionFolder.cs +++ b/src/Features/Core/Portable/Extensions/ExtensionFolder.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; diff --git a/src/Features/Core/Portable/Extensions/ExtensionMessageHandlerService.cs b/src/Features/Core/Portable/Extensions/ExtensionMessageHandlerService.cs index 773f0cf334557..bbbbdb6ce1450 100644 --- a/src/Features/Core/Portable/Extensions/ExtensionMessageHandlerService.cs +++ b/src/Features/Core/Portable/Extensions/ExtensionMessageHandlerService.cs @@ -15,8 +15,8 @@ namespace Microsoft.CodeAnalysis.Extensions; -using HandlerWrappers = ImmutableArray; using CachedHandlers = Dictionary>>; +using HandlerWrappers = ImmutableArray; internal sealed partial class ExtensionMessageHandlerServiceFactory { diff --git a/src/Features/Core/Portable/ExternalAccess/UnitTesting/API/UnitTestingHotReloadService.cs b/src/Features/Core/Portable/ExternalAccess/UnitTesting/API/UnitTestingHotReloadService.cs index d246d2b462606..22fe63ad40680 100644 --- a/src/Features/Core/Portable/ExternalAccess/UnitTesting/API/UnitTestingHotReloadService.cs +++ b/src/Features/Core/Portable/ExternalAccess/UnitTesting/API/UnitTestingHotReloadService.cs @@ -6,9 +6,9 @@ using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Host; -using Microsoft.CodeAnalysis.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api; diff --git a/src/Workspaces/Core/Portable/Notification/AbstractGlobalOperationNotificationService.GlobalOperationRegistration.cs b/src/Features/Core/Portable/ExternalAccess/UnitTesting/Notification/AbstractGlobalOperationNotificationService.GlobalOperationRegistration.cs similarity index 88% rename from src/Workspaces/Core/Portable/Notification/AbstractGlobalOperationNotificationService.GlobalOperationRegistration.cs rename to src/Features/Core/Portable/ExternalAccess/UnitTesting/Notification/AbstractGlobalOperationNotificationService.GlobalOperationRegistration.cs index 834def7386a04..4dcd7ed20151d 100644 --- a/src/Workspaces/Core/Portable/Notification/AbstractGlobalOperationNotificationService.GlobalOperationRegistration.cs +++ b/src/Features/Core/Portable/ExternalAccess/UnitTesting/Notification/AbstractGlobalOperationNotificationService.GlobalOperationRegistration.cs @@ -4,7 +4,7 @@ using System; -namespace Microsoft.CodeAnalysis.Notification; +namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Notification; internal partial class AbstractGlobalOperationNotificationService { diff --git a/src/Workspaces/Core/Portable/Notification/AbstractGlobalOperationNotificationService.cs b/src/Features/Core/Portable/ExternalAccess/UnitTesting/Notification/AbstractGlobalOperationNotificationService.cs similarity index 97% rename from src/Workspaces/Core/Portable/Notification/AbstractGlobalOperationNotificationService.cs rename to src/Features/Core/Portable/ExternalAccess/UnitTesting/Notification/AbstractGlobalOperationNotificationService.cs index c8a88b0ac843d..7db4b6d79c0a3 100644 --- a/src/Workspaces/Core/Portable/Notification/AbstractGlobalOperationNotificationService.cs +++ b/src/Features/Core/Portable/ExternalAccess/UnitTesting/Notification/AbstractGlobalOperationNotificationService.cs @@ -11,7 +11,7 @@ using Microsoft.CodeAnalysis.Threading; using Roslyn.Utilities; -namespace Microsoft.CodeAnalysis.Notification; +namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Notification; internal abstract partial class AbstractGlobalOperationNotificationService : IGlobalOperationNotificationService { diff --git a/src/Workspaces/Core/Portable/Notification/IGlobalOperationNotificationService.cs b/src/Features/Core/Portable/ExternalAccess/UnitTesting/Notification/IGlobalOperationNotificationService.cs similarity index 91% rename from src/Workspaces/Core/Portable/Notification/IGlobalOperationNotificationService.cs rename to src/Features/Core/Portable/ExternalAccess/UnitTesting/Notification/IGlobalOperationNotificationService.cs index 8e0e83c30ff95..9b3b4b165c15f 100644 --- a/src/Workspaces/Core/Portable/Notification/IGlobalOperationNotificationService.cs +++ b/src/Features/Core/Portable/ExternalAccess/UnitTesting/Notification/IGlobalOperationNotificationService.cs @@ -4,7 +4,7 @@ using System; -namespace Microsoft.CodeAnalysis.Notification; +namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Notification; /// /// Optional interface that can be used to hear about when expensive global operations (like a 'build') occur in the diff --git a/src/Features/Core/Portable/ExternalAccess/UnitTesting/SolutionCrawler/UnitTestingGlobalOperationAwareIdleProcessor.cs b/src/Features/Core/Portable/ExternalAccess/UnitTesting/SolutionCrawler/UnitTestingGlobalOperationAwareIdleProcessor.cs index 239d19b5815d1..e87a2e6c9fac6 100644 --- a/src/Features/Core/Portable/ExternalAccess/UnitTesting/SolutionCrawler/UnitTestingGlobalOperationAwareIdleProcessor.cs +++ b/src/Features/Core/Portable/ExternalAccess/UnitTesting/SolutionCrawler/UnitTestingGlobalOperationAwareIdleProcessor.cs @@ -4,7 +4,7 @@ using System; using System.Threading; -using Microsoft.CodeAnalysis.Notification; +using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Notification; using Microsoft.CodeAnalysis.Shared.TestHooks; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.SolutionCrawler; diff --git a/src/Features/Core/Portable/ExternalAccess/UnitTesting/SolutionCrawler/UnitTestingWorkCoordinator.AbstractUnitTestingPriorityProcessor.cs b/src/Features/Core/Portable/ExternalAccess/UnitTesting/SolutionCrawler/UnitTestingWorkCoordinator.AbstractUnitTestingPriorityProcessor.cs index 826660ba0a116..3448fa733e8a1 100644 --- a/src/Features/Core/Portable/ExternalAccess/UnitTesting/SolutionCrawler/UnitTestingWorkCoordinator.AbstractUnitTestingPriorityProcessor.cs +++ b/src/Features/Core/Portable/ExternalAccess/UnitTesting/SolutionCrawler/UnitTestingWorkCoordinator.AbstractUnitTestingPriorityProcessor.cs @@ -6,8 +6,8 @@ using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Notification; using Microsoft.CodeAnalysis.Internal.Log; -using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.TestHooks; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.SolutionCrawler; diff --git a/src/Features/Core/Portable/ExternalAccess/UnitTesting/SolutionCrawler/UnitTestingWorkCoordinator.UnitTestingIncrementalAnalyzerProcessor.cs b/src/Features/Core/Portable/ExternalAccess/UnitTesting/SolutionCrawler/UnitTestingWorkCoordinator.UnitTestingIncrementalAnalyzerProcessor.cs index c53d53d313e8e..5d733356017bf 100644 --- a/src/Features/Core/Portable/ExternalAccess/UnitTesting/SolutionCrawler/UnitTestingWorkCoordinator.UnitTestingIncrementalAnalyzerProcessor.cs +++ b/src/Features/Core/Portable/ExternalAccess/UnitTesting/SolutionCrawler/UnitTestingWorkCoordinator.UnitTestingIncrementalAnalyzerProcessor.cs @@ -10,10 +10,10 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api; +using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Notification; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageService; -using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; diff --git a/src/Features/Core/Portable/ExternalAccess/UnitTesting/SolutionCrawler/UnitTestingWorkCoordinator.UnitTestingLowPriorityProcessor.cs b/src/Features/Core/Portable/ExternalAccess/UnitTesting/SolutionCrawler/UnitTestingWorkCoordinator.UnitTestingLowPriorityProcessor.cs index 4d63273c453cd..ad2226f356bf8 100644 --- a/src/Features/Core/Portable/ExternalAccess/UnitTesting/SolutionCrawler/UnitTestingWorkCoordinator.UnitTestingLowPriorityProcessor.cs +++ b/src/Features/Core/Portable/ExternalAccess/UnitTesting/SolutionCrawler/UnitTestingWorkCoordinator.UnitTestingLowPriorityProcessor.cs @@ -8,8 +8,8 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; +using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Notification; using Microsoft.CodeAnalysis.Internal.Log; -using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.TestHooks; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.SolutionCrawler; diff --git a/src/Features/Core/Portable/ExternalAccess/UnitTesting/SolutionCrawler/UnitTestingWorkCoordinator.UnitTestingNormalPriorityProcessor.cs b/src/Features/Core/Portable/ExternalAccess/UnitTesting/SolutionCrawler/UnitTestingWorkCoordinator.UnitTestingNormalPriorityProcessor.cs index 1fe3c323fddc9..de906318b9248 100644 --- a/src/Features/Core/Portable/ExternalAccess/UnitTesting/SolutionCrawler/UnitTestingWorkCoordinator.UnitTestingNormalPriorityProcessor.cs +++ b/src/Features/Core/Portable/ExternalAccess/UnitTesting/SolutionCrawler/UnitTestingWorkCoordinator.UnitTestingNormalPriorityProcessor.cs @@ -10,11 +10,11 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; -using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api; +using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Notification; #if DEBUG using System.Diagnostics; diff --git a/src/Features/Core/Portable/ExternalAccess/VSTypeScript/Api/VSTypeScriptCompletionServiceWithProviders.cs b/src/Features/Core/Portable/ExternalAccess/VSTypeScript/Api/VSTypeScriptCompletionServiceWithProviders.cs index 52b300e02775f..92b46be1f5e5b 100644 --- a/src/Features/Core/Portable/ExternalAccess/VSTypeScript/Api/VSTypeScriptCompletionServiceWithProviders.cs +++ b/src/Features/Core/Portable/ExternalAccess/VSTypeScript/Api/VSTypeScriptCompletionServiceWithProviders.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; diff --git a/src/Features/Core/Portable/ExternalAccess/VSTypeScript/VSTypeScriptCommentSelectionService.cs b/src/Features/Core/Portable/ExternalAccess/VSTypeScript/VSTypeScriptCommentSelectionService.cs index 7b4675dde2770..1d2f818cef885 100644 --- a/src/Features/Core/Portable/ExternalAccess/VSTypeScript/VSTypeScriptCommentSelectionService.cs +++ b/src/Features/Core/Portable/ExternalAccess/VSTypeScript/VSTypeScriptCommentSelectionService.cs @@ -4,7 +4,6 @@ using System; using System.Composition; -using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CommentSelection; using Microsoft.CodeAnalysis.Host.Mef; diff --git a/src/Features/Core/Portable/ExternalAccess/Watch/Api/WatchHotReloadService.cs b/src/Features/Core/Portable/ExternalAccess/Watch/Api/WatchHotReloadService.cs index c356ee7dbf091..bcdf7bdbdf077 100644 --- a/src/Features/Core/Portable/ExternalAccess/Watch/Api/WatchHotReloadService.cs +++ b/src/Features/Core/Portable/ExternalAccess/Watch/Api/WatchHotReloadService.cs @@ -10,9 +10,9 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Host; -using Microsoft.CodeAnalysis.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; @@ -209,14 +209,14 @@ public async Task GetUpdatesAsync(Solution solution, ImmutableDictiona static e => new EditAndContinue.RunningProjectInfo() { RestartWhenChangesHaveNoEffect = e.Value.RestartWhenChangesHaveNoEffect, - AllowPartialUpdate = true + AllowPartialUpdate = RequireCommit }); var results = await _encService.EmitSolutionUpdateAsync(sessionId, solution, runningProjectsImpl, s_solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); // If the changes fail to apply dotnet-watch fails. // We don't support discarding the changes and letting the user retry. - if (!RequireCommit && results.ModuleUpdates.Status is ModuleUpdateStatus.Ready) + if (!RequireCommit && results.ModuleUpdates.Status is ModuleUpdateStatus.Ready && results.ProjectsToRebuild.IsEmpty) { _encService.CommitSolutionUpdate(sessionId); } diff --git a/src/Features/Core/Portable/ExtractInterface/AbstractExtractInterfaceService.cs b/src/Features/Core/Portable/ExtractInterface/AbstractExtractInterfaceService.cs index a764882369862..3ed38cf3fcb7d 100644 --- a/src/Features/Core/Portable/ExtractInterface/AbstractExtractInterfaceService.cs +++ b/src/Features/Core/Portable/ExtractInterface/AbstractExtractInterfaceService.cs @@ -140,7 +140,7 @@ public async Task ExtractInterfaceFromAnalyzedTypeAsync( var extractedInterfaceSymbol = CodeGenerationSymbolFactory.CreateNamedTypeSymbol( attributes: default, accessibility: ShouldIncludeAccessibilityModifier(refactoringResult.TypeNode) ? refactoringResult.TypeToExtractFrom.DeclaredAccessibility : Accessibility.NotApplicable, - modifiers: new DeclarationModifiers(), + modifiers: DeclarationModifiers.None, typeKind: TypeKind.Interface, name: extractInterfaceOptions.InterfaceName, typeParameters: ExtractTypeHelpers.GetRequiredTypeParametersForMembers(refactoringResult.TypeToExtractFrom, extractInterfaceOptions.IncludedMembers), diff --git a/src/Features/Core/Portable/ExtractInterface/ExtractInterfaceCodeAction.cs b/src/Features/Core/Portable/ExtractInterface/ExtractInterfaceCodeAction.cs index 6a9033a83cacc..16c2624fe1710 100644 --- a/src/Features/Core/Portable/ExtractInterface/ExtractInterfaceCodeAction.cs +++ b/src/Features/Core/Portable/ExtractInterface/ExtractInterfaceCodeAction.cs @@ -8,7 +8,6 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Collections; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractInterface; diff --git a/src/Features/Core/Portable/ExtractInterface/ExtractInterfaceTypeAnalysisResult.cs b/src/Features/Core/Portable/ExtractInterface/ExtractInterfaceTypeAnalysisResult.cs index 9b2631a36edff..fb574c46f1fe2 100644 --- a/src/Features/Core/Portable/ExtractInterface/ExtractInterfaceTypeAnalysisResult.cs +++ b/src/Features/Core/Portable/ExtractInterface/ExtractInterfaceTypeAnalysisResult.cs @@ -4,7 +4,6 @@ #nullable disable -using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Formatting; diff --git a/src/Features/Core/Portable/ExtractMethod/MethodExtractor.Analyzer.cs b/src/Features/Core/Portable/ExtractMethod/MethodExtractor.Analyzer.cs index 63bef091ccac2..a61907085fa0d 100644 --- a/src/Features/Core/Portable/ExtractMethod/MethodExtractor.Analyzer.cs +++ b/src/Features/Core/Portable/ExtractMethod/MethodExtractor.Analyzer.cs @@ -7,6 +7,7 @@ using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; diff --git a/src/Features/Core/Portable/ExtractMethod/OperationStatus.cs b/src/Features/Core/Portable/ExtractMethod/OperationStatus.cs index b727c06ebaaec..50449e5e7376b 100644 --- a/src/Features/Core/Portable/ExtractMethod/OperationStatus.cs +++ b/src/Features/Core/Portable/ExtractMethod/OperationStatus.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using System.Linq; namespace Microsoft.CodeAnalysis.ExtractMethod; @@ -31,12 +32,9 @@ public OperationStatus With(bool succeeded, string reason) } public OperationStatus With(OperationStatus operationStatus) - { - var newSucceeded = Succeeded && operationStatus.Succeeded; - - var reasons = Reasons.Concat(operationStatus.Reasons); - return new OperationStatus(newSucceeded, reasons); - } + => new( + Succeeded && operationStatus.Succeeded, + [.. Reasons, .. operationStatus.Reasons]); public OperationStatus MakeFail() => new(succeeded: false, Reasons); diff --git a/src/Features/Core/Portable/FeaturesResources.resx b/src/Features/Core/Portable/FeaturesResources.resx index 4d6a7ef70fc7d..139d6ea4d4075 100644 --- a/src/Features/Core/Portable/FeaturesResources.resx +++ b/src/Features/Core/Portable/FeaturesResources.resx @@ -2513,6 +2513,9 @@ Zero-width positive lookbehind assertions are typically used at the beginning of '{0}' may be null here. + + '{0}' is not nullable aware. + <infer> diff --git a/src/Features/Core/Portable/FindUsages/AbstractFindUsagesService_FindImplementations.cs b/src/Features/Core/Portable/FindUsages/AbstractFindUsagesService_FindImplementations.cs index 5e1d3263967f6..b95a8f8192b66 100644 --- a/src/Features/Core/Portable/FindUsages/AbstractFindUsagesService_FindImplementations.cs +++ b/src/Features/Core/Portable/FindUsages/AbstractFindUsagesService_FindImplementations.cs @@ -8,6 +8,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; diff --git a/src/Features/Core/Portable/FindUsages/DefinitionItem.DetachedDefinitionItem.cs b/src/Features/Core/Portable/FindUsages/DefinitionItem.DetachedDefinitionItem.cs index f2e11fef96097..a9048d00bf1e5 100644 --- a/src/Features/Core/Portable/FindUsages/DefinitionItem.DetachedDefinitionItem.cs +++ b/src/Features/Core/Portable/FindUsages/DefinitionItem.DetachedDefinitionItem.cs @@ -9,6 +9,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Collections; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.FindUsages.DefinitionItem; diff --git a/src/Features/Core/Portable/FindUsages/DefinitionItemFactory.cs b/src/Features/Core/Portable/FindUsages/DefinitionItemFactory.cs index c50d0c0763b54..07c34ced94b4f 100644 --- a/src/Features/Core/Portable/FindUsages/DefinitionItemFactory.cs +++ b/src/Features/Core/Portable/FindUsages/DefinitionItemFactory.cs @@ -8,6 +8,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Features.RQName; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.FindSymbols.Finders; diff --git a/src/Features/Core/Portable/FullyQualify/AbstractFullyQualifyService.cs b/src/Features/Core/Portable/FullyQualify/AbstractFullyQualifyService.cs index e743bde9072fe..d6a053af82ca8 100644 --- a/src/Features/Core/Portable/FullyQualify/AbstractFullyQualifyService.cs +++ b/src/Features/Core/Portable/FullyQualify/AbstractFullyQualifyService.cs @@ -86,7 +86,7 @@ internal abstract partial class AbstractFullyQualifyService : var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var options = await document.GetMemberDisplayOptionsAsync(cancellationToken).ConfigureAwait(false); - var matchingTypeSearchResults = GetTypeSearchResults(semanticModel, simpleName, options.HideAdvancedMembers, matchingTypes.Concat(matchingAttributeTypes)); + var matchingTypeSearchResults = GetTypeSearchResults(semanticModel, simpleName, options.HideAdvancedMembers, [.. matchingTypes, .. matchingAttributeTypes]); var matchingNamespaceSearchResults = GetNamespaceSearchResults(semanticModel, simpleName, matchingNamespaces); if (matchingTypeSearchResults.IsEmpty && matchingNamespaceSearchResults.IsEmpty) return null; diff --git a/src/Features/Core/Portable/GenerateComparisonOperators/GenerateComparisonOperatorsCodeRefactoringProvider.cs b/src/Features/Core/Portable/GenerateComparisonOperators/GenerateComparisonOperatorsCodeRefactoringProvider.cs index eedf9f85b4836..3eab31892e73a 100644 --- a/src/Features/Core/Portable/GenerateComparisonOperators/GenerateComparisonOperatorsCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/GenerateComparisonOperators/GenerateComparisonOperatorsCodeRefactoringProvider.cs @@ -119,7 +119,7 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte private static IMethodSymbol? TryGetCompareMethodImpl(INamedTypeSymbol containingType, ITypeSymbol comparableType) { - foreach (var member in comparableType.GetMembers(nameof(IComparable.CompareTo))) + foreach (var member in comparableType.GetMembers(nameof(IComparable<>.CompareTo))) { if (member is IMethodSymbol method) return (IMethodSymbol?)containingType.FindImplementationForInterfaceMember(method); diff --git a/src/Features/Core/Portable/GenerateConstructors/AbstractGenerateConstructorsCodeRefactoringProvider.ConstructorDelegatingCodeAction.cs b/src/Features/Core/Portable/GenerateConstructors/AbstractGenerateConstructorsCodeRefactoringProvider.ConstructorDelegatingCodeAction.cs index 07117719bc0ec..c5a49046d12df 100644 --- a/src/Features/Core/Portable/GenerateConstructors/AbstractGenerateConstructorsCodeRefactoringProvider.ConstructorDelegatingCodeAction.cs +++ b/src/Features/Core/Portable/GenerateConstructors/AbstractGenerateConstructorsCodeRefactoringProvider.ConstructorDelegatingCodeAction.cs @@ -90,7 +90,7 @@ protected override async Task GetChangedDocumentAsync(CancellationToke CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default, accessibility: _state.ContainingType.IsAbstractClass() ? Accessibility.Protected : Accessibility.Public, - modifiers: new DeclarationModifiers(), + modifiers: DeclarationModifiers.None, typeName: _state.ContainingType.Name, parameters: _state.Parameters, statements: statements, diff --git a/src/Features/Core/Portable/GenerateConstructors/AbstractGenerateConstructorsCodeRefactoringProvider.cs b/src/Features/Core/Portable/GenerateConstructors/AbstractGenerateConstructorsCodeRefactoringProvider.cs index 35781bdd95f0f..67e88355afbd3 100644 --- a/src/Features/Core/Portable/GenerateConstructors/AbstractGenerateConstructorsCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/GenerateConstructors/AbstractGenerateConstructorsCodeRefactoringProvider.cs @@ -10,6 +10,7 @@ using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CodeRefactorings; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Features.Intents; using Microsoft.CodeAnalysis.GenerateDefaultConstructors; using Microsoft.CodeAnalysis.GenerateFromMembers; diff --git a/src/Features/Core/Portable/GenerateOverrides/GenerateOverridesWithDialogCodeAction.cs b/src/Features/Core/Portable/GenerateOverrides/GenerateOverridesWithDialogCodeAction.cs index bd8c52909be04..049fbf52bbe4c 100644 --- a/src/Features/Core/Portable/GenerateOverrides/GenerateOverridesWithDialogCodeAction.cs +++ b/src/Features/Core/Portable/GenerateOverrides/GenerateOverridesWithDialogCodeAction.cs @@ -102,10 +102,7 @@ private sealed class ChangeOptionValueOperation(bool selectedAll) : CodeActionOp public override void Apply(Workspace workspace, CancellationToken cancellationToken) { var service = workspace.Services.GetService(); - if (service != null) - { - service.GenerateOverrides = _selectedAll; - } + service?.GenerateOverrides = _selectedAll; } } } diff --git a/src/Features/Core/Portable/GenerateType/AbstractGenerateTypeService.CodeAction.cs b/src/Features/Core/Portable/GenerateType/AbstractGenerateTypeService.CodeAction.cs index 62bb1ce329226..26841fcfa8791 100644 --- a/src/Features/Core/Portable/GenerateType/AbstractGenerateTypeService.CodeAction.cs +++ b/src/Features/Core/Portable/GenerateType/AbstractGenerateTypeService.CodeAction.cs @@ -13,7 +13,6 @@ using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.ProjectManagement; using Microsoft.CodeAnalysis.Shared.Extensions; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateType; diff --git a/src/Features/Core/Portable/GenerateType/AbstractGenerateTypeService.cs b/src/Features/Core/Portable/GenerateType/AbstractGenerateTypeService.cs index 0ebac83ad0f28..2309c81eb50e6 100644 --- a/src/Features/Core/Portable/GenerateType/AbstractGenerateTypeService.cs +++ b/src/Features/Core/Portable/GenerateType/AbstractGenerateTypeService.cs @@ -13,6 +13,7 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.PooledObjects; @@ -100,7 +101,7 @@ private ImmutableArray GetActions( State state, CancellationToken cancellationToken) { - using var _ = ArrayBuilder.GetInstance(out var result); + using var result = TemporaryArray.Empty; var generateNewTypeInDialog = false; if (state.NamespaceToGenerateInOpt != null) diff --git a/src/Features/Core/Portable/Highlighting/Keywords/AbstractKeywordHighlighter.cs b/src/Features/Core/Portable/Highlighting/Keywords/AbstractKeywordHighlighter.cs index 5b08b2849c7d9..0e03acb5db164 100644 --- a/src/Features/Core/Portable/Highlighting/Keywords/AbstractKeywordHighlighter.cs +++ b/src/Features/Core/Portable/Highlighting/Keywords/AbstractKeywordHighlighter.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; diff --git a/src/Features/Core/Portable/InheritanceMargin/AbstractInheritanceMarginService.cs b/src/Features/Core/Portable/InheritanceMargin/AbstractInheritanceMarginService.cs index b203e0c5db249..b305684aa8128 100644 --- a/src/Features/Core/Portable/InheritanceMargin/AbstractInheritanceMarginService.cs +++ b/src/Features/Core/Portable/InheritanceMargin/AbstractInheritanceMarginService.cs @@ -10,6 +10,7 @@ using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.InheritanceMargin; + internal abstract partial class AbstractInheritanceMarginService : IInheritanceMarginService { /// diff --git a/src/Features/Core/Portable/InheritanceMargin/AbstractInheritanceMarginService_Helpers.cs b/src/Features/Core/Portable/InheritanceMargin/AbstractInheritanceMarginService_Helpers.cs index 6cb7cdce24f2a..a943c9fcfd612 100644 --- a/src/Features/Core/Portable/InheritanceMargin/AbstractInheritanceMarginService_Helpers.cs +++ b/src/Features/Core/Portable/InheritanceMargin/AbstractInheritanceMarginService_Helpers.cs @@ -432,7 +432,7 @@ private static async ValueTask AddInheritanceMemberItemsForMembersAsync( topLevelDisplayText: null, FindUsagesHelpers.GetDisplayParts(interfaceSymbol), interfaceSymbol.GetGlyph(), - nonNullBaseSymbolItems.Concat(nonNullDerivedTypeItems)); + [.. nonNullBaseSymbolItems, .. nonNullDerivedTypeItems]); } private static async ValueTask CreateInheritanceMemberItemForInterfaceMemberAsync( @@ -499,7 +499,7 @@ private static async ValueTask AddInheritanceMemberItemsForMembersAsync( topLevelDisplayText: null, FindUsagesHelpers.GetDisplayParts(memberSymbol), memberSymbol.GetGlyph(), - nonNullBaseSymbolItems.Concat(nonNullDerivedTypeItems)); + [.. nonNullBaseSymbolItems, .. nonNullDerivedTypeItems]); } private static async ValueTask CreateInheritanceMemberItemForClassOrStructMemberAsync( @@ -550,7 +550,7 @@ private static async ValueTask AddInheritanceMemberItemsForMembersAsync( topLevelDisplayText: null, FindUsagesHelpers.GetDisplayParts(memberSymbol), memberSymbol.GetGlyph(), - nonNullImplementedMemberItems.Concat(nonNullOverriddenMemberItems, nonNullOverridingMemberItems)); + [.. nonNullImplementedMemberItems, .. nonNullOverriddenMemberItems, .. nonNullOverridingMemberItems]); } private static async ValueTask CreateInheritanceItemAsync( @@ -692,7 +692,7 @@ private static async Task> GetDerivedTypesAndIm solution, transitive: true, cancellationToken: cancellationToken).ConfigureAwait(false); - return allDerivedInterfaces.Concat(allImplementations); + return [.. allDerivedInterfaces, .. allImplementations]; } else { diff --git a/src/Features/Core/Portable/InitializeParameter/AbstractAddParameterCheckCodeRefactoringProvider.cs b/src/Features/Core/Portable/InitializeParameter/AbstractAddParameterCheckCodeRefactoringProvider.cs index eae201a5192da..01023eefb1bb0 100644 --- a/src/Features/Core/Portable/InitializeParameter/AbstractAddParameterCheckCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/InitializeParameter/AbstractAddParameterCheckCodeRefactoringProvider.cs @@ -11,6 +11,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Operations; diff --git a/src/Features/Core/Portable/InitializeParameter/AbstractInitializeMemberFromParameterCodeRefactoringProviderMemberCreation.cs b/src/Features/Core/Portable/InitializeParameter/AbstractInitializeMemberFromParameterCodeRefactoringProviderMemberCreation.cs index 4b5762bc1cdef..947ae6b37ea81 100644 --- a/src/Features/Core/Portable/InitializeParameter/AbstractInitializeMemberFromParameterCodeRefactoringProviderMemberCreation.cs +++ b/src/Features/Core/Portable/InitializeParameter/AbstractInitializeMemberFromParameterCodeRefactoringProviderMemberCreation.cs @@ -337,7 +337,7 @@ private IPropertySymbol CreateProperty( return CodeGenerationSymbolFactory.CreatePropertySymbol( default, accessibilityLevel, - new DeclarationModifiers(), + DeclarationModifiers.None, parameter.Type, RefKind.None, explicitInterfaceImplementations: default, diff --git a/src/Features/Core/Portable/InitializeParameter/AbstractInitializeParameterCodeRefactoringProvider.cs b/src/Features/Core/Portable/InitializeParameter/AbstractInitializeParameterCodeRefactoringProvider.cs index db0c1cebd3b5b..5aca841f9d528 100644 --- a/src/Features/Core/Portable/InitializeParameter/AbstractInitializeParameterCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/InitializeParameter/AbstractInitializeParameterCodeRefactoringProvider.cs @@ -18,6 +18,7 @@ using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.InitializeParameter; + internal abstract partial class AbstractInitializeParameterCodeRefactoringProvider< TTypeDeclarationSyntax, TParameterSyntax, diff --git a/src/Features/Core/Portable/InlineHints/AbstractInlineHintsService.cs b/src/Features/Core/Portable/InlineHints/AbstractInlineHintsService.cs index 9b2d174fb5522..c42d65e701c76 100644 --- a/src/Features/Core/Portable/InlineHints/AbstractInlineHintsService.cs +++ b/src/Features/Core/Portable/InlineHints/AbstractInlineHintsService.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; @@ -27,6 +28,6 @@ public async Task> GetInlineHintsAsync( ? [] : await inlineTypeService.GetInlineHintsAsync(document, textSpan, options.TypeOptions, options.DisplayOptions, displayAllOverride, cancellationToken).ConfigureAwait(false); - return parameters.Concat(types); + return [.. parameters, .. types]; } } diff --git a/src/Features/Core/Portable/InlineMethod/AbstractInlineMethodRefactoringProvider.cs b/src/Features/Core/Portable/InlineMethod/AbstractInlineMethodRefactoringProvider.cs index 9ab398938b2d9..0f41b5f02ad22 100644 --- a/src/Features/Core/Portable/InlineMethod/AbstractInlineMethodRefactoringProvider.cs +++ b/src/Features/Core/Portable/InlineMethod/AbstractInlineMethodRefactoringProvider.cs @@ -580,10 +580,26 @@ private async Task GetChangedCallerAsync(Document document, return declaredSymbol; } - if (IsFieldDeclarationSyntax(node) - && semanticModel.GetAllDeclaredSymbols(node, cancellationToken).SingleOrDefault() is IFieldSymbol fieldSymbol) + if (IsFieldDeclarationSyntax(node)) { - return fieldSymbol; + foreach (var declarator in node.DescendantNodes().OfType() + .Where(n => _syntaxFacts.IsVariableDeclarator(n))) + { + var initializer = _syntaxFacts.GetInitializerOfVariableDeclarator(declarator); + if (initializer?.DescendantNodesAndSelf().Contains(calleeMethodInvocationNode) is true) + { + if (semanticModel.GetDeclaredSymbol(declarator, cancellationToken) is IFieldSymbol fieldSymbol) + { + return fieldSymbol; + } + } + } + + // Fall back to the current approach for the VB case + if (semanticModel.GetAllDeclaredSymbols(node, cancellationToken).SingleOrDefault() is IFieldSymbol fieldSymbolFallBack) + { + return fieldSymbolFallBack; + } } if (_syntaxFacts.IsAnonymousFunctionExpression(node)) diff --git a/src/Features/Core/Portable/Intents/IIntentProviderMetadata.cs b/src/Features/Core/Portable/Intents/IIntentProviderMetadata.cs index 9a62d58225514..45be8e946df21 100644 --- a/src/Features/Core/Portable/Intents/IIntentProviderMetadata.cs +++ b/src/Features/Core/Portable/Intents/IIntentProviderMetadata.cs @@ -6,6 +6,6 @@ namespace Microsoft.CodeAnalysis.Features.Intents; internal interface IIntentProviderMetadata { - public string IntentName { get; } - public string LanguageName { get; } + string IntentName { get; } + string LanguageName { get; } } diff --git a/src/Features/Core/Portable/IntroduceParameter/AbstractIntroduceParameterCodeRefactoringProvider.cs b/src/Features/Core/Portable/IntroduceParameter/AbstractIntroduceParameterCodeRefactoringProvider.cs index 4a44639ecacef..f692e8bcb23fe 100644 --- a/src/Features/Core/Portable/IntroduceParameter/AbstractIntroduceParameterCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/IntroduceParameter/AbstractIntroduceParameterCodeRefactoringProvider.cs @@ -10,6 +10,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageService; @@ -78,6 +79,11 @@ public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContex if (expressionSymbol is IParameterSymbol parameterSymbol && parameterSymbol.ContainingSymbol.Equals(containingSymbol)) return; + // Direct reference to named type or type parameter. e.g. `$$Console.WriteLine()` or `T.Add(...)`. These + // are effectively statics (not values) and cannot become parameter. + if (expressionSymbol is INamedTypeSymbol or ITypeParameterSymbol) + return; + // Code actions for trampoline and overloads will not be offered if the method is a constructor. // Code actions for overloads will not be offered if the method if the method is a local function. var methodKind = methodSymbol.MethodKind; diff --git a/src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.AbstractSymbolDescriptionBuilder.cs b/src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.AbstractSymbolDescriptionBuilder.cs index 6e19bbea189a5..069f77473ce90 100644 --- a/src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.AbstractSymbolDescriptionBuilder.cs +++ b/src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.AbstractSymbolDescriptionBuilder.cs @@ -9,6 +9,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.AnonymousTypes.cs b/src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.AnonymousTypes.cs index ce9f5bfeb1b03..91405a4dc2354 100644 --- a/src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.AnonymousTypes.cs +++ b/src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.AnonymousTypes.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; diff --git a/src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.cs b/src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.cs index 60c3add045008..682affaf181a4 100644 --- a/src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.cs +++ b/src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.cs @@ -8,7 +8,6 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Host; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageService; diff --git a/src/Features/Core/Portable/MetadataAsSource/MetadataAsSourceFileService.cs b/src/Features/Core/Portable/MetadataAsSource/MetadataAsSourceFileService.cs index e21821dd8852a..c741b9f3745aa 100644 --- a/src/Features/Core/Portable/MetadataAsSource/MetadataAsSourceFileService.cs +++ b/src/Features/Core/Portable/MetadataAsSource/MetadataAsSourceFileService.cs @@ -47,7 +47,9 @@ internal sealed class MetadataAsSourceFileService : IMetadataAsSourceFileService /// We create a mutex so other processes can see if our directory is still alive. As long as we own the mutex, no /// other VS instance will try to delete our _rootTemporaryPathWithGuid folder. /// +#pragma warning disable IDE0052 // Remove unread private members. Used to communicate with other VS instances. private readonly Mutex _mutex; +#pragma warning restore IDE0052 // Remove unread private members private readonly string _rootTemporaryPathWithGuid; private readonly string _rootTemporaryPath = Path.Combine(Path.GetTempPath(), MetadataAsSource); diff --git a/src/Features/Core/Portable/Microsoft.CodeAnalysis.Features.csproj b/src/Features/Core/Portable/Microsoft.CodeAnalysis.Features.csproj index 1fe725f9f372e..869a972ba0c00 100644 --- a/src/Features/Core/Portable/Microsoft.CodeAnalysis.Features.csproj +++ b/src/Features/Core/Portable/Microsoft.CodeAnalysis.Features.csproj @@ -18,7 +18,6 @@ - diff --git a/src/Features/Core/Portable/NavigateTo/AbstractNavigateToSearchService.InProcess.cs b/src/Features/Core/Portable/NavigateTo/AbstractNavigateToSearchService.InProcess.cs index 8736055214edf..34a904f09457c 100644 --- a/src/Features/Core/Portable/NavigateTo/AbstractNavigateToSearchService.InProcess.cs +++ b/src/Features/Core/Portable/NavigateTo/AbstractNavigateToSearchService.InProcess.cs @@ -9,6 +9,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.PatternMatching; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Features/Core/Portable/NavigateTo/AbstractNavigateToSearchService.cs b/src/Features/Core/Portable/NavigateTo/AbstractNavigateToSearchService.cs index 30d264e854da2..1225c41a4620b 100644 --- a/src/Features/Core/Portable/NavigateTo/AbstractNavigateToSearchService.cs +++ b/src/Features/Core/Portable/NavigateTo/AbstractNavigateToSearchService.cs @@ -7,9 +7,9 @@ using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Threading; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.NavigateTo; diff --git a/src/Features/Core/Portable/NavigateTo/IRemoteNavigateToSearchService.cs b/src/Features/Core/Portable/NavigateTo/IRemoteNavigateToSearchService.cs index 2b1d14b7578a3..b135fc895a199 100644 --- a/src/Features/Core/Portable/NavigateTo/IRemoteNavigateToSearchService.cs +++ b/src/Features/Core/Portable/NavigateTo/IRemoteNavigateToSearchService.cs @@ -25,7 +25,7 @@ internal interface IRemoteNavigateToSearchService ValueTask HydrateAsync(Checksum solutionChecksum, CancellationToken cancellationToken); - public interface ICallback + interface ICallback { ValueTask OnItemsFoundAsync(RemoteServiceCallbackId callbackId, ImmutableArray items); ValueTask OnProjectCompletedAsync(RemoteServiceCallbackId callbackId); diff --git a/src/Features/Core/Portable/NavigateTo/NavigateToSearcher.cs b/src/Features/Core/Portable/NavigateTo/NavigateToSearcher.cs index 0af4241b615a4..e7db2e18fe975 100644 --- a/src/Features/Core/Portable/NavigateTo/NavigateToSearcher.cs +++ b/src/Features/Core/Portable/NavigateTo/NavigateToSearcher.cs @@ -10,6 +10,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; diff --git a/src/Features/Core/Portable/Navigation/INavigableItem.cs b/src/Features/Core/Portable/Navigation/INavigableItem.cs index e27b14d99846f..400ce104d8afd 100644 --- a/src/Features/Core/Portable/Navigation/INavigableItem.cs +++ b/src/Features/Core/Portable/Navigation/INavigableItem.cs @@ -48,7 +48,7 @@ internal interface INavigableItem ImmutableArray ChildItems { get; } - public sealed record NavigableDocument(NavigableProject Project, string Name, string? FilePath, IReadOnlyList Folders, DocumentId Id, SourceGeneratedDocumentIdentity? SourceGeneratedDocumentIdentity, Workspace? Workspace) + sealed record NavigableDocument(NavigableProject Project, string Name, string? FilePath, IReadOnlyList Folders, DocumentId Id, SourceGeneratedDocumentIdentity? SourceGeneratedDocumentIdentity, Workspace? Workspace) { public static NavigableDocument FromDocument(Document document) => new( @@ -87,7 +87,7 @@ internal async ValueTask GetTextAsync(Solution solution, Cancellatio } } - public record struct NavigableProject(string Name, ProjectId Id) + record struct NavigableProject(string Name, ProjectId Id) { public static NavigableProject FromProject(Project project) => new(project.Name, project.Id); diff --git a/src/Features/Core/Portable/Options/EditorConfig/IEditorConfigOptionsEnumerator.cs b/src/Features/Core/Portable/Options/EditorConfig/IEditorConfigOptionsEnumerator.cs index f2689a2ce5971..562c07ffc4920 100644 --- a/src/Features/Core/Portable/Options/EditorConfig/IEditorConfigOptionsEnumerator.cs +++ b/src/Features/Core/Portable/Options/EditorConfig/IEditorConfigOptionsEnumerator.cs @@ -13,5 +13,5 @@ internal interface IEditorConfigOptionsEnumerator /// Returns all editorconfig options defined by the implementing language, grouped by feature. /// /// True to include undocumented options that the user can set in editorconfig file but we provide no support for them. - public abstract IEnumerable<(string feature, ImmutableArray options)> GetOptions(bool includeUnsupported); + IEnumerable<(string feature, ImmutableArray options)> GetOptions(bool includeUnsupported); } diff --git a/src/Features/Core/Portable/OrganizeImports/OrganizeImportsCodeRefactoringProvider.cs b/src/Features/Core/Portable/OrganizeImports/OrganizeImportsCodeRefactoringProvider.cs new file mode 100644 index 0000000000000..53c832fc62345 --- /dev/null +++ b/src/Features/Core/Portable/OrganizeImports/OrganizeImportsCodeRefactoringProvider.cs @@ -0,0 +1,94 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Immutable; +using System.Composition; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CodeRefactorings; +using Microsoft.CodeAnalysis.Editing; +using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.LanguageService; +using Microsoft.CodeAnalysis.Shared.Extensions; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.OrganizeImports; + +[ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeRefactoringProviderNames.OrganizeImports), Shared] +[method: ImportingConstructor] +[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] +internal sealed class OrganizeImportsCodeRefactoringProvider() : SyntaxEditorBasedCodeRefactoringProvider +{ + protected override ImmutableArray SupportedFixAllScopes => [FixAllScope.Project, FixAllScope.Solution]; + + /// + /// Matches 'remove unnecessary imports' code fix. This way we don't show 'sort imports' above it. + /// + protected override CodeActionRequestPriority ComputeRequestPriority() + => CodeActionRequestPriority.Low; + + /// + /// This refactoring provider touches syntax only. So we can speed up fix all by having it only clean syntax + /// and not semantics. + /// + protected override CodeActionCleanup Cleanup => CodeActionCleanup.SyntaxOnly; + + private static async Task<(SyntaxNode oldRoot, SyntaxNode newRoot)> RemoveImportsAsync( + Document document, CancellationToken cancellationToken) + { + var organizeImportsService = document.GetRequiredLanguageService(); + var oldRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + + var options = await document.GetOrganizeImportsOptionsAsync(cancellationToken).ConfigureAwait(false); + var newDocument = await organizeImportsService.OrganizeImportsAsync(document, options, cancellationToken).ConfigureAwait(false); + var newRoot = await newDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + + return (oldRoot, newRoot); + } + + protected override async Task FixAllAsync( + Document document, ImmutableArray fixAllSpans, SyntaxEditor editor, string? equivalenceKey, CancellationToken cancellationToken) + { + var (oldRoot, newRoot) = await RemoveImportsAsync(document, cancellationToken).ConfigureAwait(false); + + // If no changes were made, then we don't need to do anything. + if (oldRoot == newRoot) + return; + + editor.ReplaceNode(oldRoot, newRoot); + } + + public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) + { + var (document, span, cancellationToken) = context; + + var oldRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + var token = oldRoot.FindToken(span.Start); + + var syntaxFacts = document.GetRequiredLanguageService(); + var importNode = token.GetAncestors().FirstOrDefault(syntaxFacts.IsUsingOrExternOrImport); + if (importNode is null) + return; + + var (_, newRoot) = await RemoveImportsAsync(document, cancellationToken).ConfigureAwait(false); + + // If no changes were made, then we don't need to do anything. + if (oldRoot == newRoot) + return; + + // Find the containing namespace/compilation unit of this import. We'll use that to determine the span + // this refactoring applies to. + var ancestor = importNode.Ancestors().FirstOrDefault(syntaxFacts.IsBaseNamespaceDeclaration) ?? oldRoot; + var imports = ancestor.ChildNodes().Where(syntaxFacts.IsUsingOrExternOrImport); + + context.RegisterRefactoring(CodeAction.Create( + document.GetRequiredLanguageService().SortImportsDisplayStringWithoutAccelerator, + cancellationToken => Task.FromResult(document.WithSyntaxRoot(newRoot))), + applicableToSpan: imports.GetContainedSpan()); + } +} diff --git a/src/Features/Core/Portable/PullMemberUp/MemberAndDestinationValidator.cs b/src/Features/Core/Portable/PullMemberUp/MemberAndDestinationValidator.cs index cf6ad9acab75f..019465ca56017 100644 --- a/src/Features/Core/Portable/PullMemberUp/MemberAndDestinationValidator.cs +++ b/src/Features/Core/Portable/PullMemberUp/MemberAndDestinationValidator.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Shared.Extensions; diff --git a/src/Features/Core/Portable/PullMemberUp/MembersPuller.cs b/src/Features/Core/Portable/PullMemberUp/MembersPuller.cs index d5730b8c1d9b8..188b74f3b691c 100644 --- a/src/Features/Core/Portable/PullMemberUp/MembersPuller.cs +++ b/src/Features/Core/Portable/PullMemberUp/MembersPuller.cs @@ -12,6 +12,7 @@ using Microsoft.CodeAnalysis.AddImport; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageService; diff --git a/src/Features/Core/Portable/QuickInfo/CommonQuickInfoProvider.cs b/src/Features/Core/Portable/QuickInfo/CommonQuickInfoProvider.cs index aba2a6c5f5a46..78ca4e480cc04 100644 --- a/src/Features/Core/Portable/QuickInfo/CommonQuickInfoProvider.cs +++ b/src/Features/Core/Portable/QuickInfo/CommonQuickInfoProvider.cs @@ -4,6 +4,7 @@ using System.Collections.Immutable; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; diff --git a/src/Features/Core/Portable/QuickInfo/CommonSemanticQuickInfoProvider.TokenInfo.cs b/src/Features/Core/Portable/QuickInfo/CommonSemanticQuickInfoProvider.TokenInfo.cs index d6cee9eddc130..8a3dbdc0ae987 100644 --- a/src/Features/Core/Portable/QuickInfo/CommonSemanticQuickInfoProvider.TokenInfo.cs +++ b/src/Features/Core/Portable/QuickInfo/CommonSemanticQuickInfoProvider.TokenInfo.cs @@ -8,7 +8,7 @@ namespace Microsoft.CodeAnalysis.QuickInfo; internal abstract partial class CommonSemanticQuickInfoProvider { - public readonly struct TokenInformation(ImmutableArray symbols, bool showAwaitReturn = false, NullableFlowState nullableFlowState = NullableFlowState.None) + public readonly struct TokenInformation(ImmutableArray symbols, bool showAwaitReturn = false, (NullableAnnotation, NullableFlowState) nullabilityInfo = default) { public ImmutableArray Symbols => symbols.NullToEmpty(); @@ -19,8 +19,8 @@ public readonly struct TokenInformation(ImmutableArray symbols, bool sh public readonly bool ShowAwaitReturn = showAwaitReturn; /// - /// The nullable flow state to show in Quick Info; will be to show nothing. + /// The nullability info to show in Quick Info; will have to show nothing. /// - public readonly NullableFlowState NullableFlowState = nullableFlowState; + public readonly (NullableAnnotation, NullableFlowState) NullabilityInfo = nullabilityInfo; } } diff --git a/src/Features/Core/Portable/QuickInfo/CommonSemanticQuickInfoProvider.cs b/src/Features/Core/Portable/QuickInfo/CommonSemanticQuickInfoProvider.cs index 7b981048d818c..7a257df0e8910 100644 --- a/src/Features/Core/Portable/QuickInfo/CommonSemanticQuickInfoProvider.cs +++ b/src/Features/Core/Portable/QuickInfo/CommonSemanticQuickInfoProvider.cs @@ -176,7 +176,7 @@ protected static Task CreateContentAsync( return QuickInfoUtilities.CreateQuickInfoItemAsync( services, semanticModel, token.Span, symbols, supportedPlatforms, - tokenInformation.ShowAwaitReturn, tokenInformation.NullableFlowState, options, onTheFlyDocsInfo, cancellationToken); + tokenInformation.ShowAwaitReturn, tokenInformation.NullabilityInfo, options, onTheFlyDocsInfo, cancellationToken); } protected abstract bool GetBindableNodeForTokenIndicatingLambda(SyntaxToken token, [NotNullWhen(returnValue: true)] out SyntaxNode? found); @@ -186,7 +186,7 @@ protected static Task CreateContentAsync( protected virtual Task GetOnTheFlyDocsInfoAsync(QuickInfoContext context, CancellationToken cancellationToken) => Task.FromResult(null); - protected virtual NullableFlowState GetNullabilityAnalysis(SemanticModel semanticModel, ISymbol symbol, SyntaxNode node, CancellationToken cancellationToken) => NullableFlowState.None; + protected virtual (NullableAnnotation, NullableFlowState) GetNullabilityAnalysis(SemanticModel semanticModel, ISymbol symbol, SyntaxNode node, CancellationToken cancellationToken) => default; private TokenInformation BindToken( SolutionServices services, SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) @@ -206,13 +206,11 @@ private TokenInformation BindToken( if (filteredSymbols is [var firstSymbol, ..]) { var isAwait = syntaxFacts.IsAwaitKeyword(token); - var nullableFlowState = NullableFlowState.None; - if (bindableParent != null) - { - nullableFlowState = GetNullabilityAnalysis(semanticModel, firstSymbol, bindableParent, cancellationToken); - } + var nullabilityInfo = bindableParent != null + ? GetNullabilityAnalysis(semanticModel, firstSymbol, bindableParent, cancellationToken) + : default; - return new TokenInformation(filteredSymbols.ToImmutableAndClear(), isAwait, nullableFlowState); + return new TokenInformation(filteredSymbols.ToImmutableAndClear(), isAwait, nullabilityInfo); } // Couldn't bind the token to specific symbols. If it's an operator, see if we can at diff --git a/src/Features/Core/Portable/QuickInfo/IndentationHelper.cs b/src/Features/Core/Portable/QuickInfo/IndentationHelper.cs index c3ae1d1aa73e7..9b98805905a42 100644 --- a/src/Features/Core/Portable/QuickInfo/IndentationHelper.cs +++ b/src/Features/Core/Portable/QuickInfo/IndentationHelper.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Classification; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; diff --git a/src/Features/Core/Portable/QuickInfo/Presentation/QuickInfoContentBuilder.cs b/src/Features/Core/Portable/QuickInfo/Presentation/QuickInfoContentBuilder.cs index 06d398e237e5d..fa5cc81edaac8 100644 --- a/src/Features/Core/Portable/QuickInfo/Presentation/QuickInfoContentBuilder.cs +++ b/src/Features/Core/Portable/QuickInfo/Presentation/QuickInfoContentBuilder.cs @@ -8,6 +8,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Collections; namespace Microsoft.CodeAnalysis.QuickInfo.Presentation; diff --git a/src/Features/Core/Portable/QuickInfo/Presentation/TaggedTextExtensions.cs b/src/Features/Core/Portable/QuickInfo/Presentation/TaggedTextExtensions.cs index 1bea570041ff1..9082510445d41 100644 --- a/src/Features/Core/Portable/QuickInfo/Presentation/TaggedTextExtensions.cs +++ b/src/Features/Core/Portable/QuickInfo/Presentation/TaggedTextExtensions.cs @@ -6,6 +6,7 @@ using System.Collections.Immutable; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.Classification; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Collections; namespace Microsoft.CodeAnalysis.QuickInfo.Presentation; diff --git a/src/Features/Core/Portable/QuickInfo/QuickInfoSection.cs b/src/Features/Core/Portable/QuickInfo/QuickInfoSection.cs index f50fcf11795b5..e021c16491134 100644 --- a/src/Features/Core/Portable/QuickInfo/QuickInfoSection.cs +++ b/src/Features/Core/Portable/QuickInfo/QuickInfoSection.cs @@ -37,8 +37,6 @@ private QuickInfoSection(string? kind, ImmutableArray taggedParts) public static QuickInfoSection Create(string? kind, ImmutableArray taggedParts) => new(kind, taggedParts); - private string? _text; - /// /// The text of the section without tags. /// @@ -46,19 +44,21 @@ public string Text { get { - if (_text == null) + if (field == null) { if (TaggedParts.Length == 0) { - _text = string.Empty; + field = string.Empty; } else { - Interlocked.CompareExchange(ref _text, string.Concat(TaggedParts.Select(t => t.Text)), null); + Interlocked.CompareExchange(ref field, string.Concat(TaggedParts.Select(t => t.Text)), null); } } - return _text; + return field; } + + private set; } } diff --git a/src/Features/Core/Portable/QuickInfo/QuickInfoUtilities.cs b/src/Features/Core/Portable/QuickInfo/QuickInfoUtilities.cs index fdb53dfa525e5..a2a2490d683aa 100644 --- a/src/Features/Core/Portable/QuickInfo/QuickInfoUtilities.cs +++ b/src/Features/Core/Portable/QuickInfo/QuickInfoUtilities.cs @@ -24,7 +24,7 @@ internal static class QuickInfoUtilities private static readonly SymbolDisplayFormat s_nullableDisplayFormat = new SymbolDisplayFormat(); public static Task CreateQuickInfoItemAsync(SolutionServices services, SemanticModel semanticModel, TextSpan span, ImmutableArray symbols, SymbolDescriptionOptions options, CancellationToken cancellationToken) - => CreateQuickInfoItemAsync(services, semanticModel, span, symbols, supportedPlatforms: null, showAwaitReturn: false, flowState: NullableFlowState.None, options, onTheFlyDocsInfo: null, cancellationToken); + => CreateQuickInfoItemAsync(services, semanticModel, span, symbols, supportedPlatforms: null, showAwaitReturn: false, nullabilityInfo: default, options, onTheFlyDocsInfo: null, cancellationToken); public static async Task CreateQuickInfoItemAsync( SolutionServices services, @@ -33,7 +33,7 @@ public static async Task CreateQuickInfoItemAsync( ImmutableArray symbols, SupportedPlatformData? supportedPlatforms, bool showAwaitReturn, - NullableFlowState flowState, + (NullableAnnotation, NullableFlowState) nullabilityInfo, SymbolDescriptionOptions options, OnTheFlyDocsInfo? onTheFlyDocsInfo, CancellationToken cancellationToken) @@ -77,10 +77,7 @@ public static async Task CreateQuickInfoItemAsync( if (groups.TryGetValue(SymbolDescriptionGroups.Documentation, out var docParts) && !docParts.IsDefaultOrEmpty) { AddSection(QuickInfoSectionKinds.DocumentationComments, docParts); - if (onTheFlyDocsInfo != null) - { - onTheFlyDocsInfo.HasComments = true; - } + onTheFlyDocsInfo?.HasComments = true; } if (options.QuickInfoOptions.ShowRemarksInQuickInfo && @@ -139,10 +136,12 @@ public static async Task CreateQuickInfoItemAsync( if (usageTextBuilder.Count > 0) AddSection(QuickInfoSectionKinds.Usage, usageTextBuilder.ToImmutable()); - var nullableMessage = flowState switch + var nullableMessage = nullabilityInfo switch { - NullableFlowState.MaybeNull => string.Format(FeaturesResources._0_may_be_null_here, symbol.ToDisplayString(s_nullableDisplayFormat)), - NullableFlowState.NotNull => string.Format(FeaturesResources._0_is_not_null_here, symbol.ToDisplayString(s_nullableDisplayFormat)), + (_, NullableFlowState.None) => null, + (NullableAnnotation.None, _) => string.Format(FeaturesResources._0_is_not_nullable_aware, symbol.ToDisplayString(s_nullableDisplayFormat)), + (_, NullableFlowState.MaybeNull) => string.Format(FeaturesResources._0_may_be_null_here, symbol.ToDisplayString(s_nullableDisplayFormat)), + (_, NullableFlowState.NotNull) => string.Format(FeaturesResources._0_is_not_null_here, symbol.ToDisplayString(s_nullableDisplayFormat)), _ => null }; diff --git a/src/Features/Core/Portable/Rename/SymbolicRenameInfo.cs b/src/Features/Core/Portable/Rename/SymbolicRenameInfo.cs index 1f49befebaadc..6e5c1a2542f6d 100644 --- a/src/Features/Core/Portable/Rename/SymbolicRenameInfo.cs +++ b/src/Features/Core/Portable/Rename/SymbolicRenameInfo.cs @@ -111,13 +111,13 @@ public string GetFinalSymbolName(string replacementText) } public static async Task GetRenameInfoAsync( - Document document, int position, CancellationToken cancellationToken) + Document document, int position, bool includeSourceGenerated, CancellationToken cancellationToken) { var triggerToken = await GetTriggerTokenAsync(document, position, cancellationToken).ConfigureAwait(false); if (triggerToken == default) return new SymbolicRenameInfo(FeaturesResources.You_must_rename_an_identifier); - return await GetRenameInfoAsync(document, triggerToken, cancellationToken).ConfigureAwait(false); + return await GetRenameInfoAsync(document, triggerToken, includeSourceGenerated, cancellationToken).ConfigureAwait(false); } private static async Task GetTriggerTokenAsync(Document document, int position, CancellationToken cancellationToken) @@ -131,6 +131,7 @@ private static async Task GetTriggerTokenAsync(Document document, i private static async Task GetRenameInfoAsync( Document document, SyntaxToken triggerToken, + bool includeSourceGenerated, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService(); @@ -221,7 +222,7 @@ private static async Task GetRenameInfoAsync( var solution = document.Project.Solution; var sourceDocument = solution.GetRequiredDocument(location.SourceTree); - if (sourceDocument is SourceGeneratedDocument) + if (!includeSourceGenerated && sourceDocument is SourceGeneratedDocument) { // The file is generated so doesn't count towards valid spans // we can edit. diff --git a/src/Features/Core/Portable/ReplaceMethodWithProperty/AbstractReplaceMethodWithPropertyService.cs b/src/Features/Core/Portable/ReplaceMethodWithProperty/AbstractReplaceMethodWithPropertyService.cs index ee3b5332292fc..feefc8960ade8 100644 --- a/src/Features/Core/Portable/ReplaceMethodWithProperty/AbstractReplaceMethodWithPropertyService.cs +++ b/src/Features/Core/Portable/ReplaceMethodWithProperty/AbstractReplaceMethodWithPropertyService.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using System.Collections.Generic; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.LanguageService; diff --git a/src/Features/Core/Portable/ReplacePropertyWithMethods/AbstractReplacePropertyWithMethodsService.cs b/src/Features/Core/Portable/ReplacePropertyWithMethods/AbstractReplacePropertyWithMethodsService.cs index e1fc1c8eaf8e0..aeeacc44d025c 100644 --- a/src/Features/Core/Portable/ReplacePropertyWithMethods/AbstractReplacePropertyWithMethodsService.cs +++ b/src/Features/Core/Portable/ReplacePropertyWithMethods/AbstractReplacePropertyWithMethodsService.cs @@ -14,7 +14,6 @@ using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ReplacePropertyWithMethods; diff --git a/src/Features/Core/Portable/ReplacePropertyWithMethods/ReplacePropertyWithMethodsCodeRefactoringProvider.cs b/src/Features/Core/Portable/ReplacePropertyWithMethods/ReplacePropertyWithMethodsCodeRefactoringProvider.cs index ccd8de0608582..53ef252db13b6 100644 --- a/src/Features/Core/Portable/ReplacePropertyWithMethods/ReplacePropertyWithMethodsCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/ReplacePropertyWithMethods/ReplacePropertyWithMethodsCodeRefactoringProvider.cs @@ -263,13 +263,10 @@ private async Task ReplaceReferencesAsync( editor.ReplaceNode(parent, parent.WithAdditionalAnnotations( ConflictAnnotation.Create(FeaturesResources.Property_referenced_implicitly))); } - else if (syntaxFacts.IsMemberInitializerNamedAssignmentIdentifier(parent)) - { - editor.ReplaceNode(parent, parent.WithAdditionalAnnotations( - ConflictAnnotation.Create(FeaturesResources.Property_reference_cannot_be_updated))); - } - else if (syntaxFacts.IsNameOfSubpattern(parent)) + else if (IsInNonUpdatableLocation(syntaxFacts, parent)) { + // If the property is in a location where it cannot be updated, then just + // replace it with a warning. editor.ReplaceNode(parent, parent.WithAdditionalAnnotations( ConflictAnnotation.Create(FeaturesResources.Property_reference_cannot_be_updated))); } @@ -284,6 +281,13 @@ await service.ReplaceReferenceAsync( } } } + + static bool IsInNonUpdatableLocation(ISyntaxFacts syntaxFacts, SyntaxNode parent) + { + return syntaxFacts.IsMemberInitializerNamedAssignmentIdentifier(parent) || + syntaxFacts.IsNameOfSubpattern(parent) || + syntaxFacts.IsInNamespaceOrTypeContext(parent); + } } private static async Task ReplaceDefinitionsWithMethodsAsync( diff --git a/src/Features/Core/Portable/SemanticSearch/SemanticSearchUtilities.cs b/src/Features/Core/Portable/SemanticSearch/SemanticSearchUtilities.cs index 57f78cb94034e..7572d7de9c6a6 100644 --- a/src/Features/Core/Portable/SemanticSearch/SemanticSearchUtilities.cs +++ b/src/Features/Core/Portable/SemanticSearch/SemanticSearchUtilities.cs @@ -5,12 +5,12 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Text; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; -using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Shared.Extensions; -using System.Linq; +using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.SemanticSearch; diff --git a/src/Features/Core/Portable/Shared/Extensions/DocumentExtensions.cs b/src/Features/Core/Portable/Shared/Extensions/DocumentExtensions.cs index 236e180050fdd..cba2c0d972d21 100644 --- a/src/Features/Core/Portable/Shared/Extensions/DocumentExtensions.cs +++ b/src/Features/Core/Portable/Shared/Extensions/DocumentExtensions.cs @@ -8,9 +8,9 @@ using System.Diagnostics; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; -using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.CodeAnalysis.Shared.Extensions; @@ -104,7 +104,7 @@ public static async Task GetApplicableNamingRuleAsync(this Document } public static async Task GetApplicableNamingRuleAsync( - this Document document, SymbolKindOrTypeKind kind, DeclarationModifiers modifiers, Accessibility? accessibility, CancellationToken cancellationToken) + this Document document, SymbolKindOrTypeKind kind, Modifiers modifiers, Accessibility? accessibility, CancellationToken cancellationToken) { var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false); foreach (var rule in rules) diff --git a/src/Features/Core/Portable/SimplifyTypeNames/AbstractSimplifyTypeNamesCodeFixProvider.cs b/src/Features/Core/Portable/SimplifyTypeNames/AbstractSimplifyTypeNamesCodeFixProvider.cs index 63b2d66662bb7..8b8794ef049bc 100644 --- a/src/Features/Core/Portable/SimplifyTypeNames/AbstractSimplifyTypeNamesCodeFixProvider.cs +++ b/src/Features/Core/Portable/SimplifyTypeNames/AbstractSimplifyTypeNamesCodeFixProvider.cs @@ -12,8 +12,8 @@ using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageService; -using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Shared.Extensions; +using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.SimplifyTypeNames; diff --git a/src/Features/Core/Portable/Snippets/SnippetFunctionService.cs b/src/Features/Core/Portable/Snippets/SnippetFunctionService.cs index eae43c8abd010..05b25558232b3 100644 --- a/src/Features/Core/Portable/Snippets/SnippetFunctionService.cs +++ b/src/Features/Core/Portable/Snippets/SnippetFunctionService.cs @@ -14,6 +14,7 @@ using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis; + internal abstract class SnippetFunctionService : ILanguageService { /// diff --git a/src/Features/Core/Portable/Snippets/SnippetUtilities.cs b/src/Features/Core/Portable/Snippets/SnippetUtilities.cs index c8f9105313e1a..87ed0ca895043 100644 --- a/src/Features/Core/Portable/Snippets/SnippetUtilities.cs +++ b/src/Features/Core/Portable/Snippets/SnippetUtilities.cs @@ -2,11 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Microsoft.CodeAnalysis.Text; -using Microsoft.CodeAnalysis.LanguageService; using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.LanguageService; +using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis; + internal sealed class SnippetUtilities { public static bool TryGetWordOnLeft(int position, SourceText currentText, ISyntaxFactsService syntaxFactsService, [NotNullWhen(true)] out TextSpan? wordSpan) diff --git a/src/Features/Core/Portable/StackTraceExplorer/StackTraceExplorerUtilities.cs b/src/Features/Core/Portable/StackTraceExplorer/StackTraceExplorerUtilities.cs index 5b9b8e8b4c3f1..3df2afe735704 100644 --- a/src/Features/Core/Portable/StackTraceExplorer/StackTraceExplorerUtilities.cs +++ b/src/Features/Core/Portable/StackTraceExplorer/StackTraceExplorerUtilities.cs @@ -47,6 +47,8 @@ internal static class StackTraceExplorerUtilities using var _ = PooledObjects.ArrayBuilder.GetInstance(out var candidateProjects); foreach (var project in solution.Projects) { + cancellationToken.ThrowIfCancellationRequested(); + if (!project.SupportsCompilation) { continue; @@ -116,6 +118,8 @@ DefinitionItem GetDefinition(IMethodSymbol method) foreach (var resolver in _resolvers) { + cancellationToken.ThrowIfCancellationRequested(); + var matchingMethod = await resolver.TryGetBestMatchAsync(project, type, methodNode, methodArguments, methodTypeArguments, cancellationToken).ConfigureAwait(false); if (matchingMethod is not null) { diff --git a/src/Features/Core/Portable/StackTraceExplorer/VSDebugCallstackParser.cs b/src/Features/Core/Portable/StackTraceExplorer/VSDebugCallstackParser.cs index c07608b466601..8b6ae39d0eae3 100644 --- a/src/Features/Core/Portable/StackTraceExplorer/VSDebugCallstackParser.cs +++ b/src/Features/Core/Portable/StackTraceExplorer/VSDebugCallstackParser.cs @@ -3,9 +3,9 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; -using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.EmbeddedLanguages.StackFrame; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; +using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.StackTraceExplorer; diff --git a/src/Features/Core/Portable/Structure/BlockStructureServiceWithProviders.cs b/src/Features/Core/Portable/Structure/BlockStructureServiceWithProviders.cs index 3767a03b45039..61f1faf074310 100644 --- a/src/Features/Core/Portable/Structure/BlockStructureServiceWithProviders.cs +++ b/src/Features/Core/Portable/Structure/BlockStructureServiceWithProviders.cs @@ -21,7 +21,7 @@ internal abstract class BlockStructureServiceWithProviders : BlockStructureServi protected BlockStructureServiceWithProviders(SolutionServices services) { _services = services; - _providers = GetBuiltInProviders().Concat(GetImportedProviders()); + _providers = [.. GetBuiltInProviders(), .. GetImportedProviders()]; } /// diff --git a/src/Features/Core/Portable/SymbolSearch/Windows/IFileDownloaderFactory.cs b/src/Features/Core/Portable/SymbolSearch/Windows/IFileDownloaderFactory.cs index 988909b50fa4c..b6a97f3c5d0b5 100644 --- a/src/Features/Core/Portable/SymbolSearch/Windows/IFileDownloaderFactory.cs +++ b/src/Features/Core/Portable/SymbolSearch/Windows/IFileDownloaderFactory.cs @@ -18,5 +18,5 @@ internal interface IFileDownloaderFactory internal interface IFileDownloader : IDisposable { - public Task ReadFileAsync(); + Task ReadFileAsync(); } diff --git a/src/Features/Core/Portable/SymbolSearch/Windows/SymbolSearchUpdateEngine.cs b/src/Features/Core/Portable/SymbolSearch/Windows/SymbolSearchUpdateEngine.cs index 3c358e1fcccfa..83919042a66ce 100644 --- a/src/Features/Core/Portable/SymbolSearch/Windows/SymbolSearchUpdateEngine.cs +++ b/src/Features/Core/Portable/SymbolSearch/Windows/SymbolSearchUpdateEngine.cs @@ -12,6 +12,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddImport; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Elfie.Model; using Microsoft.CodeAnalysis.Elfie.Model.Structures; using Microsoft.CodeAnalysis.Elfie.Model.Tree; diff --git a/src/Features/Core/Portable/Testing/TestFrameworks/ITestFrameworkMetadata.cs b/src/Features/Core/Portable/Testing/TestFrameworks/ITestFrameworkMetadata.cs index 7b301c7cd5971..2e9e85cebe490 100644 --- a/src/Features/Core/Portable/Testing/TestFrameworks/ITestFrameworkMetadata.cs +++ b/src/Features/Core/Portable/Testing/TestFrameworks/ITestFrameworkMetadata.cs @@ -9,5 +9,5 @@ internal interface ITestFrameworkMetadata /// /// Determines if the input attribute token name matches known test method attribute names. /// - public bool MatchesAttributeSyntacticName(string attributeSyntacticName); + bool MatchesAttributeSyntacticName(string attributeSyntacticName); } diff --git a/src/Features/Core/Portable/UnusedReferences/ProjectAssets/ProjectAssetsReader.cs b/src/Features/Core/Portable/UnusedReferences/ProjectAssets/ProjectAssetsReader.cs index 9857f19b92c8d..92c24663fbfb0 100644 --- a/src/Features/Core/Portable/UnusedReferences/ProjectAssets/ProjectAssetsReader.cs +++ b/src/Features/Core/Portable/UnusedReferences/ProjectAssets/ProjectAssetsReader.cs @@ -6,6 +6,7 @@ using System.Collections.Immutable; using System.IO; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UnusedReferences.ProjectAssets; diff --git a/src/Features/Core/Portable/UnusedReferences/UnusedReferencesRemover.cs b/src/Features/Core/Portable/UnusedReferences/UnusedReferencesRemover.cs index 92722b2a2f169..154a5de5ccd75 100644 --- a/src/Features/Core/Portable/UnusedReferences/UnusedReferencesRemover.cs +++ b/src/Features/Core/Portable/UnusedReferences/UnusedReferencesRemover.cs @@ -9,6 +9,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UnusedReferences; diff --git a/src/Features/Core/Portable/UseAutoProperty/AbstractUseAutoPropertyCodeFixProvider.cs b/src/Features/Core/Portable/UseAutoProperty/AbstractUseAutoPropertyCodeFixProvider.cs index 841532b9e395e..07ee9af1d1592 100644 --- a/src/Features/Core/Portable/UseAutoProperty/AbstractUseAutoPropertyCodeFixProvider.cs +++ b/src/Features/Core/Portable/UseAutoProperty/AbstractUseAutoPropertyCodeFixProvider.cs @@ -12,6 +12,7 @@ using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeCleanup; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ErrorReporting; diff --git a/src/Features/Core/Portable/UseAutoProperty/UseAutoPropertyFixAllProvider.cs b/src/Features/Core/Portable/UseAutoProperty/UseAutoPropertyFixAllProvider.cs index 122e14bff5003..3b8ef0d21672e 100644 --- a/src/Features/Core/Portable/UseAutoProperty/UseAutoPropertyFixAllProvider.cs +++ b/src/Features/Core/Portable/UseAutoProperty/UseAutoPropertyFixAllProvider.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; diff --git a/src/Features/Core/Portable/ValueTracking/ValueTracker.FindReferencesProgress.cs b/src/Features/Core/Portable/ValueTracking/ValueTracker.FindReferencesProgress.cs index 72dc6f8effc3c..102388d9a576e 100644 --- a/src/Features/Core/Portable/ValueTracking/ValueTracker.FindReferencesProgress.cs +++ b/src/Features/Core/Portable/ValueTracking/ValueTracker.FindReferencesProgress.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; diff --git a/src/Features/Core/Portable/Workspace/CompileTimeSolutionProvider.cs b/src/Features/Core/Portable/Workspace/CompileTimeSolutionProvider.cs index f665a3de9e192..ccb9b65717804 100644 --- a/src/Features/Core/Portable/Workspace/CompileTimeSolutionProvider.cs +++ b/src/Features/Core/Portable/Workspace/CompileTimeSolutionProvider.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.IO; @@ -11,6 +12,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; diff --git a/src/Features/Core/Portable/Wrapping/AbstractCodeActionComputer.cs b/src/Features/Core/Portable/Wrapping/AbstractCodeActionComputer.cs index 0d3f57f717f90..02caaf4eeca29 100644 --- a/src/Features/Core/Portable/Wrapping/AbstractCodeActionComputer.cs +++ b/src/Features/Core/Portable/Wrapping/AbstractCodeActionComputer.cs @@ -9,6 +9,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Formatting; diff --git a/src/Features/Core/Portable/Wrapping/AbstractWrapper.cs b/src/Features/Core/Portable/Wrapping/AbstractWrapper.cs index 460ab32b6d4d3..704c959cc679c 100644 --- a/src/Features/Core/Portable/Wrapping/AbstractWrapper.cs +++ b/src/Features/Core/Portable/Wrapping/AbstractWrapper.cs @@ -2,13 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Linq; -using Microsoft.CodeAnalysis.Indentation; -using Microsoft.CodeAnalysis.Text; using System.Collections.Generic; +using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Indentation; using Microsoft.CodeAnalysis.Shared.Extensions; +using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Wrapping; diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.cs.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.cs.xlf index fa5e9d4402d48..f03c674e673be 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.cs.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.cs.xlf @@ -3260,6 +3260,11 @@ Pozitivní kontrolní výrazy zpětného vyhledávání s nulovou délkou se obv {0} tady není null. + + '{0}' is not nullable aware. + '{0}' is not nullable aware. + + '{0}' items in cache Počet položek v mezipaměti: {0} diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.de.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.de.xlf index 0b5eace09efa2..20c77de3dee62 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.de.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.de.xlf @@ -3260,6 +3260,11 @@ Positive Lookbehindassertionen mit Nullbreite werden normalerweise am Anfang reg "{0}" ist hier nicht NULL. + + '{0}' is not nullable aware. + '{0}' is not nullable aware. + + '{0}' items in cache {0} Elemente im Cache diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.es.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.es.xlf index 09e6c259b2320..f09a4f939619a 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.es.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.es.xlf @@ -3260,6 +3260,11 @@ Las aserciones de búsqueda retrasada (lookbehind) positivas de ancho cero se us "{0}" no es NULL aquí. + + '{0}' is not nullable aware. + '{0}' is not nullable aware. + + '{0}' items in cache "{0}" elementos en caché diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.fr.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.fr.xlf index 1a377151be2b4..cb28a6e18d4d2 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.fr.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.fr.xlf @@ -3260,6 +3260,11 @@ Les assertions arrière positives de largeur nulle sont généralement utilisée '{0}' n'a pas une valeur null ici. + + '{0}' is not nullable aware. + '{0}' is not nullable aware. + + '{0}' items in cache '{0}' éléments dans le cache diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.it.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.it.xlf index 880fa4389d189..35c70870dc3ec 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.it.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.it.xlf @@ -3260,6 +3260,11 @@ Le asserzioni lookbehind positive di larghezza zero vengono usate in genere all' '{0}' non è Null in questo punto. + + '{0}' is not nullable aware. + '{0}' is not nullable aware. + + '{0}' items in cache '{0}' elementi nella cache diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.ja.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.ja.xlf index 239f4544c29b1..8af8702ddeb58 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.ja.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.ja.xlf @@ -3260,6 +3260,11 @@ Zero-width positive lookbehind assertions are typically used at the beginning of ここでは、'{0}' は null ではありません。 + + '{0}' is not nullable aware. + '{0}' is not nullable aware. + + '{0}' items in cache キャッシュ内の '{0}' 個の項目 diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.ko.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.ko.xlf index bb34ab410c646..2824699a97b37 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.ko.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.ko.xlf @@ -3260,6 +3260,11 @@ Zero-width positive lookbehind assertions are typically used at the beginning of '{0}'은(는) 여기에서 null이 아닙니다. + + '{0}' is not nullable aware. + '{0}' is not nullable aware. + + '{0}' items in cache 캐시의 '{0}'개 항목 diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.pl.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.pl.xlf index bbf4ab1933685..7111aa3e62acd 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.pl.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.pl.xlf @@ -3260,6 +3260,11 @@ Pozytywne asercje wsteczne o zerowej szerokości są zwykle używane na początk Element „{0}” nie ma wartości null w tym miejscu. + + '{0}' is not nullable aware. + '{0}' is not nullable aware. + + '{0}' items in cache Elementy w pamięci podręcznej: „{0}” diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.pt-BR.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.pt-BR.xlf index 6b21337d1f1ed..3eaf8d35ad45c 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.pt-BR.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.pt-BR.xlf @@ -3260,6 +3260,11 @@ As declarações de lookbehind positivas de largura zero normalmente são usadas '{0}' não é nulo aqui. + + '{0}' is not nullable aware. + '{0}' is not nullable aware. + + '{0}' items in cache '{0}' itens no cache diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.ru.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.ru.xlf index 0a1baaa9c8064..d09cff14956fe 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.ru.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.ru.xlf @@ -3260,6 +3260,11 @@ Zero-width positive lookbehind assertions are typically used at the beginning of Здесь "{0}" имеет значение, отличное от NULL. + + '{0}' is not nullable aware. + '{0}' is not nullable aware. + + '{0}' items in cache Элементов в кэше: "{0}" diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.tr.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.tr.xlf index 54bc1368d36c9..d7943aef7b3e7 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.tr.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.tr.xlf @@ -3260,6 +3260,11 @@ Sıfır genişlikli pozitif geri yönlü onaylamalar genellikle normal ifadeleri '{0}' burada null değil. + + '{0}' is not nullable aware. + '{0}' is not nullable aware. + + '{0}' items in cache Önbellekteki '{0}' öğe diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hans.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hans.xlf index 4122150e427ed..c4751ccee9ab3 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hans.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hans.xlf @@ -3260,6 +3260,11 @@ Zero-width positive lookbehind assertions are typically used at the beginning of “{0}”在此处不为 null。 + + '{0}' is not nullable aware. + '{0}' is not nullable aware. + + '{0}' items in cache 缓存中的 {0} 项 diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hant.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hant.xlf index bc1483d57f47e..dc551e792c74a 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hant.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hant.xlf @@ -3260,6 +3260,11 @@ Zero-width positive lookbehind assertions are typically used at the beginning of '{0}' 在此不是 null。 + + '{0}' is not nullable aware. + '{0}' is not nullable aware. + + '{0}' items in cache 快取中有 '{0}' 個項目 diff --git a/src/Features/DiagnosticsTestUtilities/CodeActions/CSharpCodeRefactoringVerifier`1+Test.cs b/src/Features/DiagnosticsTestUtilities/CodeActions/CSharpCodeRefactoringVerifier`1+Test.cs index 4d8718e73eb58..0473efa36bac4 100644 --- a/src/Features/DiagnosticsTestUtilities/CodeActions/CSharpCodeRefactoringVerifier`1+Test.cs +++ b/src/Features/DiagnosticsTestUtilities/CodeActions/CSharpCodeRefactoringVerifier`1+Test.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; using System.Net; using System.Threading; using System.Threading.Tasks; @@ -11,7 +12,6 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Testing; using Microsoft.CodeAnalysis.Testing; -using System.Diagnostics.CodeAnalysis; #if !CODE_STYLE using System; diff --git a/src/Features/DiagnosticsTestUtilities/CodeActionsLegacy/AbstractCodeActionOrUserDiagnosticTest_NoEditor.cs b/src/Features/DiagnosticsTestUtilities/CodeActionsLegacy/AbstractCodeActionOrUserDiagnosticTest_NoEditor.cs index e972df207517c..5cfc7cc45b15e 100644 --- a/src/Features/DiagnosticsTestUtilities/CodeActionsLegacy/AbstractCodeActionOrUserDiagnosticTest_NoEditor.cs +++ b/src/Features/DiagnosticsTestUtilities/CodeActionsLegacy/AbstractCodeActionOrUserDiagnosticTest_NoEditor.cs @@ -42,8 +42,8 @@ namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; #if CODE_STYLE using OptionsCollectionAlias = CODESTYLE_UTILITIES::Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.OptionsCollection; #else -using OptionsCollectionAlias = OptionsCollection; using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; +using OptionsCollectionAlias = OptionsCollection; #endif [UseExportProvider] @@ -862,14 +862,17 @@ static void VerifyCodeAction( { var messageSuffix = codeAction.EquivalenceKey != null ? string.Empty - : @" -Consider using the title as the equivalence key instead of 'null'"; - - Assert.False(true, @$"Expected different 'CodeAction.EquivalenceKey' for code actions registered for same diagnostic: -- Name: '{provider.GetType().Name}' -- Title 1: '{codeAction.Title}' -- Title 2: '{existingTitle}' -- Shared equivalence key: '{codeAction.EquivalenceKey ?? ""}'{messageSuffix}"); + : """ + Consider using the title as the equivalence key instead of 'null' + """; + + Assert.False(true, $""" + Expected different 'CodeAction.EquivalenceKey' for code actions registered for same diagnostic: + - Name: '{provider.GetType().Name}' + - Title 1: '{codeAction.Title}' + - Title 2: '{existingTitle}' + - Shared equivalence key: '{codeAction.EquivalenceKey ?? ""}'{messageSuffix} + """); } } } diff --git a/src/Features/DiagnosticsTestUtilities/CodeActionsLegacy/AbstractCodeActionTest_NoEditor.cs b/src/Features/DiagnosticsTestUtilities/CodeActionsLegacy/AbstractCodeActionTest_NoEditor.cs index 887450a6e6f1a..12d8bd9c7eb01 100644 --- a/src/Features/DiagnosticsTestUtilities/CodeActionsLegacy/AbstractCodeActionTest_NoEditor.cs +++ b/src/Features/DiagnosticsTestUtilities/CodeActionsLegacy/AbstractCodeActionTest_NoEditor.cs @@ -174,10 +174,7 @@ internal static void EnableOptions( internal static void EnableOption(ImmutableArray options, string id) { var option = options.FirstOrDefault(o => o.Id == id); - if (option != null) - { - option.Value = true; - } + option?.Value = true; } internal Task TestWithPickMembersDialogAsync( diff --git a/src/Features/DiagnosticsTestUtilities/Diagnostics/AbstractUnncessarySuppressionDiagnosticTest.cs b/src/Features/DiagnosticsTestUtilities/Diagnostics/AbstractUnncessarySuppressionDiagnosticTest.cs index 92bd025d50898..e470e2f03b11b 100644 --- a/src/Features/DiagnosticsTestUtilities/Diagnostics/AbstractUnncessarySuppressionDiagnosticTest.cs +++ b/src/Features/DiagnosticsTestUtilities/Diagnostics/AbstractUnncessarySuppressionDiagnosticTest.cs @@ -18,13 +18,8 @@ namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; -public abstract class AbstractUnncessarySuppressionDiagnosticTest : AbstractUserDiagnosticTest_NoEditor +public abstract class AbstractUnnecessarySuppressionDiagnosticTest(ITestOutputHelper logger) : AbstractUserDiagnosticTest_NoEditor(logger) { - protected AbstractUnncessarySuppressionDiagnosticTest(ITestOutputHelper logger) - : base(logger) - { - } - internal abstract CodeFixProvider CodeFixProvider { get; } internal abstract AbstractRemoveUnnecessaryInlineSuppressionsDiagnosticAnalyzer SuppressionAnalyzer { get; } internal abstract ImmutableArray OtherAnalyzers { get; } diff --git a/src/Features/DiagnosticsTestUtilities/Diagnostics/AbstractUserDiagnosticTest_NoEditor.cs b/src/Features/DiagnosticsTestUtilities/Diagnostics/AbstractUserDiagnosticTest_NoEditor.cs index 3e772ddc467e8..4447194010cdf 100644 --- a/src/Features/DiagnosticsTestUtilities/Diagnostics/AbstractUserDiagnosticTest_NoEditor.cs +++ b/src/Features/DiagnosticsTestUtilities/Diagnostics/AbstractUserDiagnosticTest_NoEditor.cs @@ -209,7 +209,7 @@ private static FixAllState GetFixAllState( if (scope == FixAllScope.Custom) { // Bulk fixing diagnostics in selected scope. - var diagnosticsToFix = ImmutableDictionary.CreateRange([KeyValuePairUtil.Create(document, diagnostics.ToImmutableArray())]); + var diagnosticsToFix = ImmutableDictionary.CreateRange([KeyValuePair.Create(document, diagnostics.ToImmutableArray())]); return FixAllState.Create(fixAllProvider, diagnosticsToFix, fixer, equivalenceKey); } diff --git a/src/Features/DiagnosticsTestUtilities/NamingStyles/NamingStylesTestOptionSets.cs b/src/Features/DiagnosticsTestUtilities/NamingStyles/NamingStylesTestOptionSets.cs index 0e281a477693b..b6e3fafdda8fe 100644 --- a/src/Features/DiagnosticsTestUtilities/NamingStyles/NamingStylesTestOptionSets.cs +++ b/src/Features/DiagnosticsTestUtilities/NamingStyles/NamingStylesTestOptionSets.cs @@ -12,7 +12,6 @@ using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.NamingStyles; using Microsoft.CodeAnalysis.Options; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.NamingStyles; diff --git a/src/Features/ExternalAccess/AspNetCore/EmbeddedLanguages/BraceMatching/AspNetCoreBraceMatcherExtensionProvider.cs b/src/Features/ExternalAccess/AspNetCore/EmbeddedLanguages/BraceMatching/AspNetCoreBraceMatcherExtensionProvider.cs index 028bc45061256..c505867d861f5 100644 --- a/src/Features/ExternalAccess/AspNetCore/EmbeddedLanguages/BraceMatching/AspNetCoreBraceMatcherExtensionProvider.cs +++ b/src/Features/ExternalAccess/AspNetCore/EmbeddedLanguages/BraceMatching/AspNetCoreBraceMatcherExtensionProvider.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Immutable; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ExternalAccess.AspNetCore.EmbeddedLanguages; -using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.ExternalAccess.AspNetCore.Internal.EmbeddedLanguages; diff --git a/src/Features/ExternalAccess/AspNetCore/EmbeddedLanguages/Classification/AspNetCoreClassifierExtensionProvider.cs b/src/Features/ExternalAccess/AspNetCore/EmbeddedLanguages/Classification/AspNetCoreClassifierExtensionProvider.cs index 2d2d84de6d42c..1a7a0be3b456f 100644 --- a/src/Features/ExternalAccess/AspNetCore/EmbeddedLanguages/Classification/AspNetCoreClassifierExtensionProvider.cs +++ b/src/Features/ExternalAccess/AspNetCore/EmbeddedLanguages/Classification/AspNetCoreClassifierExtensionProvider.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Immutable; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ExternalAccess.AspNetCore.EmbeddedLanguages; -using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.ExternalAccess.AspNetCore.Internal.EmbeddedLanguages; diff --git a/src/Features/ExternalAccess/AspNetCore/EmbeddedLanguages/DocumentHighlighting/AspNetCoreClassifierExtensionProvider.cs b/src/Features/ExternalAccess/AspNetCore/EmbeddedLanguages/DocumentHighlighting/AspNetCoreClassifierExtensionProvider.cs index b45e45c75c774..7b7b465aee9a7 100644 --- a/src/Features/ExternalAccess/AspNetCore/EmbeddedLanguages/DocumentHighlighting/AspNetCoreClassifierExtensionProvider.cs +++ b/src/Features/ExternalAccess/AspNetCore/EmbeddedLanguages/DocumentHighlighting/AspNetCoreClassifierExtensionProvider.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Immutable; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ExternalAccess.AspNetCore.EmbeddedLanguages; -using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.ExternalAccess.AspNetCore.Internal.EmbeddedLanguages; diff --git a/src/Features/ExternalAccess/Copilot/Internal/SemanticSearch/SemanticSearchCopilotServiceWrapper.cs b/src/Features/ExternalAccess/Copilot/Internal/SemanticSearch/SemanticSearchCopilotServiceWrapper.cs index accb6ead3824b..472cbc8d06f63 100644 --- a/src/Features/ExternalAccess/Copilot/Internal/SemanticSearch/SemanticSearchCopilotServiceWrapper.cs +++ b/src/Features/ExternalAccess/Copilot/Internal/SemanticSearch/SemanticSearchCopilotServiceWrapper.cs @@ -6,8 +6,8 @@ using System.Composition; using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.ExternalAccess.Copilot.SemanticSearch; +using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.SemanticSearch; namespace Microsoft.CodeAnalysis.ExternalAccess.Copilot.Internal.SemanticSearch; diff --git a/src/Features/ExternalAccess/OmniSharp.CSharp/Formatting/OmniSharpSyntaxFormattingOptionsFactory.cs b/src/Features/ExternalAccess/OmniSharp.CSharp/Formatting/OmniSharpSyntaxFormattingOptionsFactory.cs index ddc3c01118b3c..e93a03dbba70a 100644 --- a/src/Features/ExternalAccess/OmniSharp.CSharp/Formatting/OmniSharpSyntaxFormattingOptionsFactory.cs +++ b/src/Features/ExternalAccess/OmniSharp.CSharp/Formatting/OmniSharpSyntaxFormattingOptionsFactory.cs @@ -108,7 +108,7 @@ public static OmniSharpSyntaxFormattingOptionsWrapper Create( (spaceBeforeComma ? SpacePlacement.BeforeComma : 0) | (spaceAfterDot ? SpacePlacement.AfterDot : 0) | (spaceBeforeDot ? SpacePlacement.BeforeDot : 0), - SpacingAroundBinaryOperator = (BinaryOperatorSpacingOptions)spacingAroundBinaryOperator, + SpacingAroundBinaryOperator = (BinaryOperatorSpacingOptionsInternal)spacingAroundBinaryOperator, NewLines = (newLineForMembersInObjectInit ? NewLinePlacement.BeforeMembersInObjectInitializers : 0) | (newLineForMembersInAnonymousTypes ? NewLinePlacement.BeforeMembersInAnonymousTypes : 0) | @@ -125,7 +125,7 @@ public static OmniSharpSyntaxFormattingOptionsWrapper Create( (newLinesForBracesInLambdaExpressionBody ? NewLinePlacement.BeforeOpenBraceInLambdaExpressionBody : 0) | (newLinesForBracesInControlBlocks ? NewLinePlacement.BeforeOpenBraceInControlBlocks : 0) | (newLineForClausesInQuery ? NewLinePlacement.BetweenQueryExpressionClauses : 0), - LabelPositioning = (LabelPositionOptions)labelPositioning, + LabelPositioning = (LabelPositionOptionsInternal)labelPositioning, Indentation = (indentBraces ? IndentationPlacement.Braces : 0) | (indentBlock ? IndentationPlacement.BlockContents : 0) | diff --git a/src/Features/ExternalAccess/OmniSharp/Structure/OmniSharpBlockStructureService.cs b/src/Features/ExternalAccess/OmniSharp/Structure/OmniSharpBlockStructureService.cs index 3dffb3fde4851..6ea97c5f1b252 100644 --- a/src/Features/ExternalAccess/OmniSharp/Structure/OmniSharpBlockStructureService.cs +++ b/src/Features/ExternalAccess/OmniSharp/Structure/OmniSharpBlockStructureService.cs @@ -4,8 +4,8 @@ using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Shared.Extensions; +using Microsoft.CodeAnalysis.Structure; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Structure; diff --git a/src/Features/Lsif/Directory.Build.props b/src/Features/Lsif/Directory.Build.props deleted file mode 100644 index 9dd0ddea9df26..0000000000000 --- a/src/Features/Lsif/Directory.Build.props +++ /dev/null @@ -1,6 +0,0 @@ - - - - true - - diff --git a/src/Features/Lsif/Generator/.editorconfig b/src/Features/Lsif/Generator/.editorconfig deleted file mode 100644 index fde40e9afdecd..0000000000000 --- a/src/Features/Lsif/Generator/.editorconfig +++ /dev/null @@ -1,8 +0,0 @@ -# This .editorconfig customizes some diagnostic rules that are specific to this project. - -[*.cs] -dotnet_diagnostic.CA2007.severity = none # Disable warnings about ConfigureAwait, since this is a console app -dotnet_diagnostic.VSTHRD111.severity = none # Disable warnings about ConfigureAwait, since this is a console app - -# CA2016: Forward the 'CancellationToken' parameter to methods -dotnet_diagnostic.CA2016.severity = warning diff --git a/src/Features/Lsif/Generator/App.config b/src/Features/Lsif/Generator/App.config deleted file mode 100644 index 807677b3b6af2..0000000000000 --- a/src/Features/Lsif/Generator/App.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/src/Features/Lsif/Generator/CompilerInvocation.cs b/src/Features/Lsif/Generator/CompilerInvocation.cs deleted file mode 100644 index ade3ffbddd8e2..0000000000000 --- a/src/Features/Lsif/Generator/CompilerInvocation.cs +++ /dev/null @@ -1,197 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Host; -using Microsoft.CodeAnalysis.Shared.Extensions; -using Newtonsoft.Json; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator; - -internal static class CompilerInvocation -{ - public static async Task CreateFromJsonAsync(string jsonContents) - { - var invocationInfo = JsonConvert.DeserializeObject(jsonContents); - Assumes.Present(invocationInfo); - return await CreateFromInvocationInfoAsync(invocationInfo); - } - - public static async Task CreateFromInvocationInfoAsync(CompilerInvocationInfo invocationInfo) - { - // We will use a Workspace to simplify the creation of the compilation, but will be careful not to return the Workspace instance from this class. - // We will still provide the language services which are used by the generator itself, but we don't tie it to a Workspace object so we can - // run this as an in-proc source generator if one day desired. - var workspace = new AdhocWorkspace(await Composition.CreateHostServicesAsync()); - - var languageName = GetLanguageName(invocationInfo); - var languageServices = workspace.Services.GetLanguageServices(languageName).LanguageServices; - - var mapPath = GetPathMapper(invocationInfo); - - var splitCommandLine = CommandLineParser.SplitCommandLineIntoArguments(invocationInfo.Arguments, removeHashComments: false).ToList(); - - // Unfortunately for us there are a few paths that get directly read by the command line parse which we need to remap, - // such as /ruleset files. So let's go through and process them now. - for (var i = 0; i < splitCommandLine.Count; i++) - { - const string RuleSetSwitch = "/ruleset:"; - - if (splitCommandLine[i].StartsWith(RuleSetSwitch, StringComparison.Ordinal)) - { - var rulesetPath = splitCommandLine[i][RuleSetSwitch.Length..]; - - var quoted = rulesetPath is ['"', _, .., '"']; - if (quoted) - { - rulesetPath = rulesetPath[1..^1]; - } - - rulesetPath = mapPath(rulesetPath); - - if (quoted) - { - rulesetPath = "\"" + rulesetPath + "\""; - } - - splitCommandLine[i] = RuleSetSwitch + rulesetPath; - } - } - - var documentationProvider = workspace.Services.GetRequiredService(); - var commandLineParserService = languageServices.GetRequiredService(); - var parsedCommandLine = commandLineParserService.Parse(splitCommandLine, Path.GetDirectoryName(invocationInfo.ProjectFilePath), isInteractive: false, sdkDirectory: null); - - var analyzerLoader = new AnalyzerAssemblyLoader(); - - var projectId = ProjectId.CreateNewId(invocationInfo.ProjectFilePath); - - var projectInfo = ProjectInfo.Create( - new ProjectInfo.ProjectAttributes( - id: projectId, - version: VersionStamp.Default, - name: Path.GetFileNameWithoutExtension(invocationInfo.ProjectFilePath), - assemblyName: parsedCommandLine.CompilationName!, - language: languageName, - compilationOutputInfo: new CompilationOutputInfo( - assemblyPath: parsedCommandLine.OutputFileName != null ? Path.Combine(parsedCommandLine.OutputDirectory, parsedCommandLine.OutputFileName) : null, - generatedFilesOutputDirectory: parsedCommandLine.GeneratedFilesOutputDirectory), - checksumAlgorithm: parsedCommandLine.ChecksumAlgorithm, - filePath: invocationInfo.ProjectFilePath, - outputRefFilePath: parsedCommandLine.OutputRefFilePath), - parsedCommandLine.CompilationOptions, - parsedCommandLine.ParseOptions, - parsedCommandLine.SourceFiles.Select(s => CreateDocumentInfo(unmappedPath: s.Path)), - projectReferences: null, - metadataReferences: parsedCommandLine.MetadataReferences.Select( - r => - { - var mappedPath = mapPath(r.Reference); - return MetadataReference.CreateFromFile(mappedPath, r.Properties, documentationProvider.GetDocumentationProvider(mappedPath)); - }), - additionalDocuments: parsedCommandLine.AdditionalFiles.Select(f => CreateDocumentInfo(unmappedPath: f.Path)), - analyzerReferences: parsedCommandLine.AnalyzerReferences.Select(r => new AnalyzerFileReference(r.FilePath, analyzerLoader)), - analyzerConfigDocuments: parsedCommandLine.AnalyzerConfigPaths.Select(CreateDocumentInfo), - hostObjectType: null); - - var solution = workspace.CurrentSolution.AddProject(projectInfo); - return solution.GetRequiredProject(projectId); - - // Local methods: - DocumentInfo CreateDocumentInfo(string unmappedPath) - { - var mappedPath = mapPath(unmappedPath); - return DocumentInfo.Create( - DocumentId.CreateNewId(projectId, mappedPath), - name: mappedPath, - filePath: mappedPath, - loader: new WorkspaceFileTextLoader(languageServices.SolutionServices, mappedPath, parsedCommandLine.Encoding)); - } - } - - private static string GetLanguageName(CompilerInvocationInfo invocationInfo) - { - return invocationInfo.Tool switch - { - "csc" => LanguageNames.CSharp, - "vbc" => LanguageNames.VisualBasic, - _ => throw new NotSupportedException($"Tool '{invocationInfo.Tool}' is not supported."), - }; - } - - /// - /// Given the JSON description, returns a function that will map paths from the original paths to the current paths. - /// - /// - /// The compiler invocation JSON input is allowed to specify a map of file paths. The scenario here is to allow us to - /// do LSIF indexing on another machine than an original build might have been done on. For example, say the main build process - /// for a repository has the source synchronized to the S:\source1, but we want to do analysis on a different machine which has - /// the source in a folder S:\source2. If we have the original compilation command line when it was built under S:\source1, and - /// know that any time we see S:\source1 we should actually read the file out of S:\source2, then we analyze on a separate machine. - /// - /// This is used to enable some internal-to-Microsoft build environments which have a mechanism to run "analysis" passes like - /// the LSIF tool independent from the main build machines, and can restore source and build artifacts to provide the environment - /// that is close enough to match the original. - /// - private static Func GetPathMapper(CompilerInvocationInfo invocationInfo) - { - return unmappedPath => - { - foreach (var potentialPathMapping in invocationInfo.PathMappings) - { - // If it's just a file name being mapped, just a direct map - if (unmappedPath.Equals(potentialPathMapping.From, StringComparison.OrdinalIgnoreCase)) - { - return potentialPathMapping.To; - } - - // Map arbitrary contents under subdirectories - var fromWithDirectorySuffix = AddDirectorySuffixIfMissing(potentialPathMapping.From); - - if (unmappedPath.StartsWith(fromWithDirectorySuffix, StringComparison.OrdinalIgnoreCase)) - { - // Trim off any leading \, which would happen if you have a path like C:\Directory\\File.cs with a double slash, and happen to be - // mapping C:\Directory somewhere. - var relativePath = unmappedPath[fromWithDirectorySuffix.Length..].TrimStart('\\'); - - return Path.Combine(AddDirectorySuffixIfMissing(potentialPathMapping.To), relativePath); - } - } - - return unmappedPath; - }; - - static string AddDirectorySuffixIfMissing(string path) - { - return path.EndsWith("\\", StringComparison.OrdinalIgnoreCase) ? path : path + "\\"; - } - } - - /// - /// A simple data class that represents the schema for JSON serialization. - /// - public sealed class CompilerInvocationInfo - { -#nullable disable // this class is used for deserialization by Newtonsoft.Json, so we don't really need warnings about this class itself - - public string Tool { get; set; } - - public string Arguments { get; set; } - - public string ProjectFilePath { get; set; } - - public List PathMappings { get; set; } = []; - - public sealed class PathMapping - { - public string From { get; set; } - public string To { get; set; } - } - } -} diff --git a/src/Features/Lsif/Generator/Composition.cs b/src/Features/Lsif/Generator/Composition.cs deleted file mode 100644 index 332cc25ab912c..0000000000000 --- a/src/Features/Lsif/Generator/Composition.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Immutable; -using System.Reflection; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis.Host; -using Microsoft.CodeAnalysis.Host.Mef; -using Microsoft.CodeAnalysis.LanguageServer; -using Microsoft.VisualStudio.Composition; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator; - -internal static class Composition -{ - public static readonly ImmutableArray MefCompositionAssemblies = - MSBuildMefHostServices.DefaultAssemblies.Add(typeof(RoslynLanguageServer).Assembly); - - public static async Task CreateHostServicesAsync() - { - var discovery = new AttributedPartDiscovery(Resolver.DefaultInstance, isNonPublicSupported: true); - - var catalog = ComposableCatalog.Create(Resolver.DefaultInstance) - .AddParts(await discovery.CreatePartsAsync(MefCompositionAssemblies)) - .WithCompositionService(); // Makes an ICompositionService export available to MEF parts to import - - var config = CompositionConfiguration.Create(catalog); - - var exportProvider = config.CreateExportProviderFactory().CreateExportProvider(); - return VisualStudioMefHostServices.Create(exportProvider); - } -} diff --git a/src/Features/Lsif/Generator/Generator.cs b/src/Features/Lsif/Generator/Generator.cs deleted file mode 100644 index 1c714a8e9fc13..0000000000000 --- a/src/Features/Lsif/Generator/Generator.cs +++ /dev/null @@ -1,531 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis.LanguageServer; -using Microsoft.CodeAnalysis.LanguageServer.Handler; -using Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens; -using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; -using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.ResultSetTracking; -using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing; -using Microsoft.CodeAnalysis.LanguageService; -using Microsoft.CodeAnalysis.Shared.Extensions; -using Microsoft.CodeAnalysis.Text; -using Microsoft.Extensions.Logging; -using Roslyn.LanguageServer.Protocol; -using Roslyn.Utilities; -using LspProtocol = Roslyn.LanguageServer.Protocol; -using Methods = Roslyn.LanguageServer.Protocol.Methods; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator; - -internal sealed class Generator -{ - // LSIF generator capabilities. See https://github.com/microsoft/lsif-node/blob/main/protocol/src/protocol.ts#L925 for details. - private const bool HoverProvider = true; - private const bool DeclarationProvider = false; - private const bool DefinitionProvider = true; - private const bool ReferencesProvider = true; - private const bool TypeDefinitionProvider = false; - private const bool DocumentSymbolProvider = true; - private const bool FoldingRangeProvider = true; - private const bool DiagnosticProvider = false; - - private static readonly LspProtocol.ClientCapabilities LspClientCapabilities = new() - { - TextDocument = new LspProtocol.TextDocumentClientCapabilities() - { - Hover = new LspProtocol.HoverSetting() - { - ContentFormat = - [ - LspProtocol.MarkupKind.PlainText, - LspProtocol.MarkupKind.Markdown, - ] - } - } - }; - - private readonly ILsifJsonWriter _lsifJsonWriter; - private readonly ILogger _logger; - private readonly IdFactory _idFactory = new IdFactory(); - - private Generator(ILsifJsonWriter lsifJsonWriter, ILogger logger) - { - _lsifJsonWriter = lsifJsonWriter; - _logger = logger; - } - - public static Generator CreateAndWriteCapabilitiesVertex(ILsifJsonWriter lsifJsonWriter, ILogger logger) - { - var generator = new Generator(lsifJsonWriter, logger); - - // Pass the set of supported SemanticTokenTypes. Order must match the order used for serialization of - // semantic tokens array. This array is analogous to the equivalent array in - // https://microsoft.github.io/language-server-protocol/specifications/lsp/3.18/specification/#textDocument_semanticTokens. - // - // Ideally semantic tokens support would use the well-known, common set of token types specified in LSP's - // SemanticTokenTypes to reduce the number of tokens a particular LSIF consumer must understand, but Roslyn - // currently employs a large number of custom token types that aren't yet standardized in LSP or LSIF's - // well-known set so we will pass both LSP and Roslyn custom token types for now. - var capabilitiesVertex = new Capabilities( - generator._idFactory, - HoverProvider, - DeclarationProvider, - DefinitionProvider, - ReferencesProvider, - TypeDefinitionProvider, - DocumentSymbolProvider, - FoldingRangeProvider, - DiagnosticProvider, - new SemanticTokensCapabilities(SemanticTokensSchema.LegacyTokensSchemaForLSIF.AllTokenTypes, [SemanticTokenModifiers.Static, SemanticTokenModifiers.Deprecated])); - generator._lsifJsonWriter.Write(capabilitiesVertex); - return generator; - } - - public async Task GenerateForProjectAsync( - Project project, - GeneratorOptions options, - CancellationToken cancellationToken) - { - var compilation = await project.GetRequiredCompilationAsync(cancellationToken); - var projectPath = project.FilePath; - Contract.ThrowIfNull(projectPath); - - var projectVertex = new Graph.LsifProject( - kind: GetLanguageKind(compilation.Language), - ProtocolConversions.CreateAbsoluteUri(projectPath), - Path.GetFileNameWithoutExtension(projectPath), - _idFactory); - - _lsifJsonWriter.Write(projectVertex); - _lsifJsonWriter.Write(new Event(Event.EventKind.Begin, projectVertex.GetId(), _idFactory)); - - var documentIds = new ConcurrentBag>(); - - // We create a ResultSetTracker to track all top-level symbols in the project. We don't want all writes to immediately go to - // the JSON file -- we support parallel processing, so we'll accumulate them and then apply at once to avoid a lot - // of contention on shared locks. - var topLevelSymbolsWriter = new BatchingLsifJsonWriter(_lsifJsonWriter); - var topLevelSymbolsResultSetTracker = new SymbolHoldingResultSetTracker(topLevelSymbolsWriter, compilation, _idFactory); - - // Disable navigation hints in quick info as computing them both takes too long, and they're never - // even emitted in the final lsif hover information. - options = options with - { - SymbolDescriptionOptions = options.SymbolDescriptionOptions with - { - QuickInfoOptions = options.SymbolDescriptionOptions.QuickInfoOptions with - { - IncludeNavigationHintsInQuickInfo = false - } - } - }; - - var documents = new List(); - await foreach (var document in project.GetAllRegularAndSourceGeneratedDocumentsAsync(cancellationToken)) - documents.Add(document); - - var tasks = new List(); - foreach (var document in documents) - { - // Add a task for each document -- we'll keep them 1:1 for exception reporting later. - tasks.Add(Task.Run(async () => - { - // We generate the document contents into an in-memory copy, and then write that out at once at the end. This - // allows us to collect everything and avoid a lot of fine-grained contention on the write to the single - // LSIF file. Because of the rule that vertices must be written before they're used by an edge, we'll flush any top- - // level symbol result sets made first, since the document contents will point to that. Parallel calls to CopyAndEmpty - // are allowed and might flush other unrelated stuff at the same time, but there's no harm -- the "causality" ordering - // is preserved. - var documentWriter = new BatchingLsifJsonWriter(_lsifJsonWriter); - var documentId = await GenerateForDocumentAsync( - document, options, topLevelSymbolsResultSetTracker, documentWriter, _idFactory, cancellationToken); - topLevelSymbolsWriter.FlushToUnderlyingAndEmpty(); - documentWriter.FlushToUnderlyingAndEmpty(); - - documentIds.Add(documentId); - }, cancellationToken)); - } - - try - { - await Task.WhenAll(tasks); - } - catch - { - // We ran into some exceptions while processing documents, let's log it along with the document that failed - var exceptions = new List(); - - for (var i = 0; i < documents.Count; i++) - { - if (tasks[i].IsFaulted) - { - var documentExceptionMessage = $"Exception while processing {documents[i].FilePath}"; - var exception = tasks[i].Exception!.InnerExceptions.Single(); - exceptions.Add(new Exception(documentExceptionMessage, exception)); - - _logger.LogError(exception, documentExceptionMessage); - } - } - - // Rethrow so we properly report this as a top-level failure - throw new AggregateException($"Exceptions were thrown while processing documents in {project.FilePath}", exceptions); - } - finally - { - _lsifJsonWriter.Write(Edge.Create("contains", projectVertex.GetId(), documentIds.ToArray(), _idFactory)); - _lsifJsonWriter.Write(new Event(Event.EventKind.End, projectVertex.GetId(), _idFactory)); - } - } - - /// - /// Generates the LSIF content for a single document. - /// - /// The ID of the outputted Document vertex. - /// - /// The high level algorithm here is we are going to walk across each token, produce a for that token's span, - /// bind that token, and then link up the various features. So we'll link that range to the symbols it defines or references, - /// will link it to results like Quick Info, and more. This method has a that - /// lets us link symbols across files, and will only talk about "top level" symbols that aren't things like locals that can't - /// leak outside a file. - /// - private static async Task> GenerateForDocumentAsync( - Document document, - GeneratorOptions options, - IResultSetTracker topLevelSymbolsResultSetTracker, - ILsifJsonWriter lsifJsonWriter, - IdFactory idFactory, - CancellationToken cancellationToken) - { - // Create and keep the semantic model alive for this document. That way all work/services we kick off that - // use this document can benefit from that single shared model. - var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken); - - var contentBase64Encoded = await GetBase64EncodedContentAsync(document, cancellationToken); - - var documentVertex = new Graph.LsifDocument(document.GetURI().GetRequiredParsedUri(), GetLanguageKind(semanticModel.Language), contentBase64Encoded, idFactory); - lsifJsonWriter.Write(documentVertex); - lsifJsonWriter.Write(new Event(Event.EventKind.Begin, documentVertex.GetId(), idFactory)); - - // We will walk the file token-by-token, making a range for each one and then attaching information for it - var rangeVertices = new List>(); - var documentSymbols = new List(); - await GenerateDocumentRangesAndLinks(document, documentVertex, options, topLevelSymbolsResultSetTracker, lsifJsonWriter, idFactory, rangeVertices, documentSymbols, cancellationToken); - lsifJsonWriter.Write(Edge.Create("contains", documentVertex.GetId(), rangeVertices, idFactory)); - await GenerateDocumentFoldingRangesAsync(document, documentVertex, options, lsifJsonWriter, idFactory, cancellationToken).ConfigureAwait(false); - await GenerateSemanticTokensAsync(document, lsifJsonWriter, idFactory, documentVertex); - GenerateDocumentSymbols(documentSymbols, lsifJsonWriter, idFactory, documentVertex); - - lsifJsonWriter.Write(new Event(Event.EventKind.End, documentVertex.GetId(), idFactory)); - - GC.KeepAlive(semanticModel); - - return documentVertex.GetId(); - } - - private static async Task GenerateDocumentFoldingRangesAsync( - Document document, - LsifDocument documentVertex, - GeneratorOptions options, - ILsifJsonWriter lsifJsonWriter, - IdFactory idFactory, - CancellationToken cancellationToken) - { - var foldingRanges = await FoldingRangesHandler.GetFoldingRangesAsync( - document, options.BlockStructureOptions, cancellationToken); - var foldingRangeResult = new FoldingRangeResult(foldingRanges, idFactory); - lsifJsonWriter.Write(foldingRangeResult); - lsifJsonWriter.Write(Edge.Create(Methods.TextDocumentFoldingRangeName, documentVertex.GetId(), foldingRangeResult.GetId(), idFactory)); - } - - private static async Task GenerateDocumentRangesAndLinks( - Document document, - LsifDocument documentVertex, - GeneratorOptions options, - IResultSetTracker topLevelSymbolsResultSetTracker, - ILsifJsonWriter lsifJsonWriter, - IdFactory idFactory, - List> rangeVertices, - List documentSymbols, - CancellationToken cancellationToken) - { - var languageServices = document.Project.Services; - - var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken); - - var syntaxTree = semanticModel.SyntaxTree; - var sourceText = semanticModel.SyntaxTree.GetText(cancellationToken); - var syntaxFactsService = languageServices.GetRequiredService(); - var semanticFactsService = languageServices.GetRequiredService(); - - // As we are processing this file, we are going to encounter symbols that have a shared resultSet with other documents like types - // or methods. We're also going to encounter locals that never leave this document. We don't want those locals being held by - // the topLevelSymbolsResultSetTracker, so we'll make another tracker for document local symbols, and then have a delegating - // one that picks the correct one of the two. - var documentLocalSymbolsResultSetTracker = new SymbolHoldingResultSetTracker(lsifJsonWriter, semanticModel.Compilation, idFactory); - var symbolResultsTracker = new DelegatingResultSetTracker(symbol => - { - if (symbol.Kind is SymbolKind.Local or - SymbolKind.RangeVariable or - SymbolKind.Label) - { - // These symbols can go in the document local one because they can't escape methods - return documentLocalSymbolsResultSetTracker; - } - else if (symbol.ContainingType != null && symbol.DeclaredAccessibility == Accessibility.Private && symbol.ContainingType.Locations.Length == 1) - { - // This is a private member in a class that isn't partial, so it can't escape the file - return documentLocalSymbolsResultSetTracker; - } - else - { - return topLevelSymbolsResultSetTracker; - } - }); - - foreach (var syntaxToken in syntaxTree.GetRoot(cancellationToken).DescendantTokens(descendIntoTrivia: true)) - { - var declaredSymbol = semanticFactsService.GetDeclaredSymbol(semanticModel, syntaxToken, cancellationToken); - - // We'll only create the Range vertex once it's needed, but any number of bits of code might create it first, - // so we'll just make it Lazy. - var lazyRangeVertex = new Lazy(() => - { - var tagAndFullRangeSpan = declaredSymbol != null ? CreateRangeTagAndContainingSpanForDeclaredSymbol(declaredSymbol, syntaxToken, syntaxTree, syntaxFactsService, cancellationToken) : null; - var rangeVertex = Graph.Range.FromTextSpan(syntaxToken.Span, sourceText, tagAndFullRangeSpan?.tag, idFactory); - - lsifJsonWriter.Write(rangeVertex); - rangeVertices.Add(rangeVertex.GetId()); - - if (tagAndFullRangeSpan is not null) - { - var newDocumentSymbol = new RangeBasedDocumentSymbol(rangeVertex.GetId(), tagAndFullRangeSpan.Value.fullRange); - RangeBasedDocumentSymbol.AddNestedFromDocumentOrderTraversal(documentSymbols, newDocumentSymbol); - } - - return rangeVertex; - }, LazyThreadSafetyMode.None); - - ISymbol? referencedSymbol = null; - - if (syntaxFactsService.IsBindableToken(semanticModel, syntaxToken)) - { - var bindableParent = syntaxFactsService.TryGetBindableParent(syntaxToken); - - if (bindableParent != null) - { - var symbolInfo = semanticModel.GetSymbolInfo(bindableParent, cancellationToken); - if (symbolInfo.Symbol != null && IncludeSymbolInReferences(symbolInfo.Symbol)) - { - referencedSymbol = symbolInfo.Symbol; - } - } - } - - if (declaredSymbol != null || referencedSymbol != null) - { - // For now, we will link the range to the original definition, preferring the definition, as this is the symbol - // that would be used if we invoke a feature on this range. This is analogous to the logic in - // SymbolFinder.FindSymbolAtPositionAsync where if a token is both a reference and definition we'll prefer the - // definition. Once we start supporting hover we'll have to remove the "original definition" part of this, since - // since we show different contents for different constructed types there. - var symbolForLinkedResultSet = (declaredSymbol ?? referencedSymbol)!.GetOriginalUnreducedDefinition(); - var symbolForLinkedResultSetId = symbolResultsTracker.GetResultSetIdForSymbol(symbolForLinkedResultSet); - lsifJsonWriter.Write(Edge.Create("next", lazyRangeVertex.Value.GetId(), symbolForLinkedResultSetId, idFactory)); - - if (declaredSymbol != null) - { - var definitionResultsId = symbolResultsTracker.GetResultIdForSymbol(declaredSymbol, Methods.TextDocumentDefinitionName, static idFactory => new DefinitionResult(idFactory)); - lsifJsonWriter.Write(new Item(definitionResultsId.As(), lazyRangeVertex.Value.GetId(), documentVertex.GetId(), idFactory)); - - // If this declared symbol also implements an interface member, we count this as a definition of the interface member as well. - // Note in C# there are estoeric cases where a method can implement an interface member even though the containing type does not - // implement the interface, for example in this case: - // - // interface I { void M(); } - // class Base { public void M() { } } - // class Derived : Base, I { } - // - // We don't worry about supporting these cases here. - var implementedMembers = declaredSymbol.ExplicitOrImplicitInterfaceImplementations(); - - foreach (var implementedMember in implementedMembers) - MarkImplementationOfSymbol(implementedMember); - - // If this overrides a method, we'll also mark it the same way. We want to chase to the base virtual method, skipping over intermediate - // methods so that way all overrides of the same method point to the same virtual method - if (declaredSymbol.IsOverride) - { - var overridenMember = declaredSymbol.GetOverriddenMember(); - - while (overridenMember?.GetOverriddenMember() != null) - overridenMember = overridenMember.GetOverriddenMember(); - - if (overridenMember != null) - MarkImplementationOfSymbol(overridenMember); - } - - void MarkImplementationOfSymbol(ISymbol baseMember) - { - // First we create a definition link for the reference results for the base member - var referenceResultsId = symbolResultsTracker.GetResultSetReferenceResultId(baseMember.OriginalDefinition); - lsifJsonWriter.Write(new Item(referenceResultsId.As(), lazyRangeVertex.Value.GetId(), documentVertex.GetId(), idFactory, property: "definitions")); - - // Then also link the result set for the method to the moniker that it implements - referenceResultsId = symbolResultsTracker.GetResultSetReferenceResultId(declaredSymbol.OriginalDefinition); - var implementedMemberMoniker = symbolResultsTracker.GetMoniker(baseMember.OriginalDefinition, semanticModel.Compilation); - lsifJsonWriter.Write(new Item(referenceResultsId.As(), implementedMemberMoniker, documentVertex.GetId(), idFactory, property: "referenceLinks")); - } - } - - if (referencedSymbol != null) - { - // Create the link from the references back to this range. Note: this range can be reference to a - // symbol but the range can point a different symbol's resultSet. This can happen if the token is - // both a definition of a symbol (where we will point to the definition) but also a reference to some - // other symbol. - var referenceResultsId = symbolResultsTracker.GetResultSetReferenceResultId(referencedSymbol.GetOriginalUnreducedDefinition()); - lsifJsonWriter.Write(new Item(referenceResultsId.As(), lazyRangeVertex.Value.GetId(), documentVertex.GetId(), idFactory, property: "references")); - } - - // Write hover information for the symbol, if edge has not already been added. - // 'textDocument/hover' edge goes from the symbol ResultSet vertex to the hover result - // See https://github.com/Microsoft/language-server-protocol/blob/main/indexFormat/specification.md#resultset for an example. - if (symbolResultsTracker.ResultSetNeedsInformationalEdgeAdded(symbolForLinkedResultSet, Methods.TextDocumentHoverName)) - { - var hover = await HoverHandler.GetHoverAsync( - document, syntaxToken.SpanStart, options.SymbolDescriptionOptions, LspClientCapabilities, cancellationToken); - if (hover != null) - { - var hoverResult = new HoverResult(hover, idFactory); - lsifJsonWriter.Write(hoverResult); - lsifJsonWriter.Write(Edge.Create(Methods.TextDocumentHoverName, symbolForLinkedResultSetId, hoverResult.GetId(), idFactory)); - } - } - } - } - } - - private static (DefinitionRangeTag tag, TextSpan fullRange)? CreateRangeTagAndContainingSpanForDeclaredSymbol(ISymbol declaredSymbol, SyntaxToken syntaxToken, SyntaxTree syntaxTree, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken) - { - // Tuples fields and anonymous type are considered as declaring something, but we don't want to create document symbols for them - if (declaredSymbol.IsTupleField() || declaredSymbol.IsAnonymousTypeProperty()) - return null; - - // Find the syntax node that declared the symbol in the tree we're processing - var syntaxReference = declaredSymbol.DeclaringSyntaxReferences.FirstOrDefault(static (r, arg) => r.SyntaxTree == arg.syntaxTree && r.Span.Contains(arg.SpanStart), arg: (syntaxTree, syntaxToken.SpanStart)); - var syntaxNode = syntaxReference?.GetSyntax(cancellationToken); - - if (syntaxNode is null) - return null; - - // The containing range is supposed to be "the full range of the declaration not including leading/trailing whitespace, but everything else, - // e.g. comments and code", so produce our start/end points looking through trivia - var firstNonWhitespaceTrivia = syntaxNode.GetLeadingTrivia().FirstOrNull(static (t, syntaxFacts) => !syntaxFacts.IsWhitespaceOrEndOfLineTrivia(t), syntaxFacts); - var fullRangeStart = firstNonWhitespaceTrivia?.SpanStart ?? syntaxNode.SpanStart; - - var lastNonWhitespaceTrivia = syntaxNode.GetTrailingTrivia().Reverse().FirstOrNull(static (t, syntaxFacts) => !syntaxFacts.IsWhitespaceOrEndOfLineTrivia(t), syntaxFacts); - var fullRangeEnd = lastNonWhitespaceTrivia?.Span.End ?? syntaxNode.Span.End; - - var fullRangeSpan = TextSpan.FromBounds(fullRangeStart, fullRangeEnd); - var fullRange = ProtocolConversions.TextSpanToRange(fullRangeSpan, syntaxTree.GetText(cancellationToken)); - var symbolKind = ProtocolConversions.GlyphToSymbolKind(declaredSymbol.GetGlyph()); - - return (new DefinitionRangeTag(syntaxToken.Text, symbolKind, fullRange), fullRangeSpan); - } - - private static async Task GetBase64EncodedContentAsync( - Document document, CancellationToken cancellationToken) - { - if (document is SourceGeneratedDocument) - { - var text = await document.GetValueTextAsync(cancellationToken); - - // We always use UTF-8 encoding when writing out file contents, as that's expected by LSIF implementations. - // TODO: when we move to .NET Core, is there a way to reduce allocations here? - return Convert.ToBase64String(Encoding.UTF8.GetBytes(text.ToString())); - } - else - { - return null; - } - } - - private static async Task GenerateSemanticTokensAsync( - Document document, - ILsifJsonWriter lsifJsonWriter, - IdFactory idFactory, - LsifDocument documentVertex) - { - var cancellationToken = CancellationToken.None; - - // Compute colorization data. - // - // Unlike the mainline LSP scenario, where we control both the syntactic colorizer (in-proc syntax tagger) - // and the semantic colorizer (LSP semantic tokens) LSIF is more likely to be consumed by clients which may - // have different syntactic classification behavior than us, resulting in missing colors. To avoid this, we - // include syntax tokens in the generated data. - var text = await document.GetTextAsync(cancellationToken); - var data = await SemanticTokensHelpers.ComputeSemanticTokensDataAsync( - // Just get the pure-lsp semantic tokens here. - document, - spans: [text.Lines.GetLinePositionSpan(new TextSpan(0, text.Length))], - supportsVisualStudioExtensions: true, - options: Classification.ClassificationOptions.Default, - cancellationToken); - - var semanticTokensResult = new SemanticTokensResult(new SemanticTokens { Data = data }, idFactory); - var semanticTokensEdge = Edge.Create(Methods.TextDocumentSemanticTokensFullName, documentVertex.GetId(), semanticTokensResult.GetId(), idFactory); - lsifJsonWriter.Write(semanticTokensResult); - lsifJsonWriter.Write(semanticTokensEdge); - } - - private static void GenerateDocumentSymbols( - List documentSymbols, - ILsifJsonWriter lsifJsonWriter, - IdFactory idFactory, - LsifDocument documentVertex) - { - var documentSymbolResult = new DocumentSymbolResult(documentSymbols, idFactory); - lsifJsonWriter.Write(documentSymbolResult); - lsifJsonWriter.Write(Edge.Create(Methods.TextDocumentDocumentSymbolName, documentVertex.GetId(), documentSymbolResult.GetId(), idFactory)); - } - - private static bool IncludeSymbolInReferences(ISymbol symbol) - { - // Skip some type of symbols that don't really make sense - if (symbol.Kind is SymbolKind.ArrayType or - SymbolKind.Discard or - SymbolKind.ErrorType) - { - return false; - } - - // If it's a built-in operator, just skip it - if (symbol is IMethodSymbol { MethodKind: MethodKind.BuiltinOperator }) - { - return false; - } - - return true; - } - - private static string GetLanguageKind(string languageName) - { - return languageName switch - { - LanguageNames.CSharp => "csharp", - LanguageNames.VisualBasic => "vb", - _ => throw new NotSupportedException(languageName), - }; - } -} diff --git a/src/Features/Lsif/Generator/GeneratorOptions.cs b/src/Features/Lsif/Generator/GeneratorOptions.cs deleted file mode 100644 index f08da19dd26af..0000000000000 --- a/src/Features/Lsif/Generator/GeneratorOptions.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Microsoft.CodeAnalysis.LanguageService; -using Microsoft.CodeAnalysis.Structure; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator; - -internal readonly record struct GeneratorOptions( - SymbolDescriptionOptions SymbolDescriptionOptions, - BlockStructureOptions BlockStructureOptions) -{ - public static readonly GeneratorOptions Default = - new(SymbolDescriptionOptions.Default, - BlockStructureOptions.Default); -} diff --git a/src/Features/Lsif/Generator/Graph/Capabilities.cs b/src/Features/Lsif/Generator/Graph/Capabilities.cs deleted file mode 100644 index dc12c75072a99..0000000000000 --- a/src/Features/Lsif/Generator/Graph/Capabilities.cs +++ /dev/null @@ -1,64 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Newtonsoft.Json; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -/// -/// Represents a single Capabilities vertex for serialization. See https://github.com/microsoft/lsif-node/blob/main/protocol/src/protocol.ts#L973 for further details. -/// -internal sealed class Capabilities : Vertex -{ - [JsonProperty("hoverProvider")] - public bool HoverProvider { get; } - - [JsonProperty("declarationProvider")] - public bool DeclarationProvider { get; } - - [JsonProperty("definitionProvider")] - public bool DefinitionProvider { get; } - - [JsonProperty("referencesProvider")] - public bool ReferencesProvider { get; } - - [JsonProperty("typeDefinitionProvider")] - public bool TypeDefinitionProvider { get; } - - [JsonProperty("documentSymbolProvider")] - public bool DocumentSymbolProvider { get; } - - [JsonProperty("foldingRangeProvider")] - public bool FoldingRangeProvider { get; } - - [JsonProperty("diagnosticProvider")] - public bool DiagnosticProvider { get; } - - [JsonProperty("semanticTokensProvider")] - public SemanticTokensCapabilities SemanticTokensProvider { get; } - - public Capabilities( - IdFactory idFactory, - bool hoverProvider, - bool declarationProvider, - bool definitionProvider, - bool referencesProvider, - bool typeDefinitionProvider, - bool documentSymbolProvider, - bool foldingRangeProvider, - bool diagnosticProvider, - SemanticTokensCapabilities semanticTokensProvider) - : base(label: "capabilities", idFactory) - { - HoverProvider = hoverProvider; - DeclarationProvider = declarationProvider; - DefinitionProvider = definitionProvider; - ReferencesProvider = referencesProvider; - TypeDefinitionProvider = typeDefinitionProvider; - DocumentSymbolProvider = documentSymbolProvider; - FoldingRangeProvider = foldingRangeProvider; - DiagnosticProvider = diagnosticProvider; - SemanticTokensProvider = semanticTokensProvider; - } -} diff --git a/src/Features/Lsif/Generator/Graph/DefinitionRangeTag.cs b/src/Features/Lsif/Generator/Graph/DefinitionRangeTag.cs deleted file mode 100644 index 34597d894776b..0000000000000 --- a/src/Features/Lsif/Generator/Graph/DefinitionRangeTag.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using LSP = Roslyn.LanguageServer.Protocol; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -internal sealed class DefinitionRangeTag : RangeTag -{ - public DefinitionRangeTag(string text, LSP.SymbolKind kind, LSP.Range fullRange) - : base(type: "definition", text) - { - Kind = kind; - FullRange = fullRange; - } - - public LSP.SymbolKind Kind { get; } - - // Note: this is not a Range vertex here, since it doesn't have an ID or labels, but just the LSP Range type. - public LSP.Range FullRange { get; } -} diff --git a/src/Features/Lsif/Generator/Graph/DefinitionResult.cs b/src/Features/Lsif/Generator/Graph/DefinitionResult.cs deleted file mode 100644 index 4900354abb79d..0000000000000 --- a/src/Features/Lsif/Generator/Graph/DefinitionResult.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -/// -/// Represents a definitionResult vertex for serialization. See https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#request-textdocumentdefinition for further details. -/// -internal sealed class DefinitionResult : Vertex -{ - public DefinitionResult(IdFactory idFactory) - : base(label: "definitionResult", idFactory) - { - } -} diff --git a/src/Features/Lsif/Generator/Graph/DocumentSymbolResult.cs b/src/Features/Lsif/Generator/Graph/DocumentSymbolResult.cs deleted file mode 100644 index 0f8e07b4a6072..0000000000000 --- a/src/Features/Lsif/Generator/Graph/DocumentSymbolResult.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Generic; -using Newtonsoft.Json; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -/// -/// Represents a documentSymbolResult vertex for serialization. See https://microsoft.github.io/language-server-protocol/specifications/lsif/0.6.0/specification/#documentSymbol for further details. -/// -internal sealed class DocumentSymbolResult : Vertex -{ - // The specification allows us to output either range based document symbols, or regular LSP symbols. We choose the former. - [JsonProperty("result")] - public List Result { get; } - - public DocumentSymbolResult(List result, IdFactory idFactory) - : base(label: "documentSymbolResult", idFactory) - { - Result = result; - } -} diff --git a/src/Features/Lsif/Generator/Graph/Edge.cs b/src/Features/Lsif/Generator/Graph/Edge.cs deleted file mode 100644 index bc487f9b23a20..0000000000000 --- a/src/Features/Lsif/Generator/Graph/Edge.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Generic; -using Newtonsoft.Json; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -/// -/// Represents an edge from one vertex to another. -/// -internal class Edge : Element -{ - [JsonProperty("outV")] - public Id OutVertex { get; } - - // LSIF edges can have either an inV for a one-to-one edge, or an inVs for a one-to-many edge. We'll represent - // this by having two properties here, and exactly one of them will always be non-null. - - [JsonProperty("inV", NullValueHandling = NullValueHandling.Ignore)] - public Id? InVertex { get; } - - [JsonProperty("inVs", NullValueHandling = NullValueHandling.Ignore)] - public Id[]? InVertices { get; } - - public IEnumerable> GetInVerticies() => InVertices ?? [InVertex!.Value]; - - public Edge(string label, Id outVertex, Id inVertex, IdFactory idFactory) - : base(type: "edge", label: label, idFactory) - { - // We'll be strict and assert that label types that are one-to-many must always use inVs - Contract.ThrowIfTrue(IsEdgeLabelOneToMany(label)); - OutVertex = outVertex; - InVertex = inVertex; - } - - public Edge(string label, Id outVertex, Id[] inVertices, IdFactory idFactory) - : base(type: "edge", label: label, idFactory) - { - Contract.ThrowIfFalse(IsEdgeLabelOneToMany(label)); - OutVertex = outVertex; - InVertices = inVertices; - } - - private static bool IsEdgeLabelOneToMany(string label) => label is "contains" or "item"; - - public static Edge Create(string label, Id outVertex, Id inVertex, IdFactory idFactory) where TOutVertex : Vertex where TInVertex : Vertex - { - return new Edge(label, outVertex.As(), inVertex.As(), idFactory); - } - - public static Edge Create(string label, Id outVertex, IList> inVertices, IdFactory idFactory) where TOutVertex : Vertex where TInVertex : Vertex - { - var inVerticesArray = new Id[inVertices.Count]; - - // Note: this is ultimately just an array copy, but in a strongly-typed way. The JIT might see through this as a memory copy, - // but might require some more explicit code if not. - for (var i = 0; i < inVertices.Count; i++) - { - inVerticesArray[i] = inVertices[i].As(); - } - - return new Edge(label, outVertex.As(), inVerticesArray, idFactory); - } - - public override string ToString() - { - return $"{Label} edge from {OutVertex} to {string.Join(", ", GetInVerticies())}"; - } -} diff --git a/src/Features/Lsif/Generator/Graph/Element.cs b/src/Features/Lsif/Generator/Graph/Element.cs deleted file mode 100644 index 1da79a0d22873..0000000000000 --- a/src/Features/Lsif/Generator/Graph/Element.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -/// -/// The base class of an element in the LSIF format. -/// -internal abstract class Element -{ - public Id Id { get; } - public string Type { get; } - public string Label { get; } - - protected Element(string type, string label, IdFactory idFactory) - { - this.Id = idFactory.Create(); - this.Label = label; - this.Type = type; - } -} diff --git a/src/Features/Lsif/Generator/Graph/Event.cs b/src/Features/Lsif/Generator/Graph/Event.cs deleted file mode 100644 index edc3d38a8ffc9..0000000000000 --- a/src/Features/Lsif/Generator/Graph/Event.cs +++ /dev/null @@ -1,41 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -/// -/// Represents an event vertex for serialization. See https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#events for further details. -/// -internal sealed class Event : Vertex -{ - public string Kind { get; } - public string Scope { get; } - public Id Data { get; } - - private Event(EventKind kind, string scope, Id data, IdFactory idFactory) - : base(label: "$event", idFactory) - { - this.Kind = kind switch { EventKind.Begin => "begin", EventKind.End => "end", _ => throw new ArgumentException(nameof(kind)) }; - this.Scope = scope; - this.Data = data; - } - - public Event(EventKind kind, Id data, IdFactory idFactory) - : this(kind, "project", data.As(), idFactory) - { - } - - public Event(EventKind kind, Id data, IdFactory idFactory) - : this(kind, "document", data.As(), idFactory) - { - } - - public enum EventKind - { - Begin, - End - } -} diff --git a/src/Features/Lsif/Generator/Graph/FoldingRangeResult.cs b/src/Features/Lsif/Generator/Graph/FoldingRangeResult.cs deleted file mode 100644 index f966c32af4f84..0000000000000 --- a/src/Features/Lsif/Generator/Graph/FoldingRangeResult.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Roslyn.LanguageServer.Protocol; -using Newtonsoft.Json; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -/// -/// Represents a foldingRangeResult vertex for serialization. See https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#request-textdocumentfoldingrange for further details. -/// -internal sealed class FoldingRangeResult : Vertex -{ - [JsonProperty("result")] - public FoldingRange[] Result { get; } - - public FoldingRangeResult(FoldingRange[] result, IdFactory idFactory) - : base(label: "foldingRangeResult", idFactory) - { - Result = result; - } -} diff --git a/src/Features/Lsif/Generator/Graph/HoverResult.cs b/src/Features/Lsif/Generator/Graph/HoverResult.cs deleted file mode 100644 index ee66fcddec80d..0000000000000 --- a/src/Features/Lsif/Generator/Graph/HoverResult.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Roslyn.LanguageServer.Protocol; -using Newtonsoft.Json; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -/// -/// Represents a hoverResult vertex for serialization. See https://github.com/Microsoft/language-server-protocol/blob/main/indexFormat/specification.md#more-about-request-textdocumenthover for further details. -/// -internal sealed class HoverResult : Vertex -{ - [JsonProperty("result")] - public Hover Result { get; } - - public HoverResult(Hover result, IdFactory idFactory) - : base(label: "hoverResult", idFactory) - { - Result = result; - } -} diff --git a/src/Features/Lsif/Generator/Graph/Id.cs b/src/Features/Lsif/Generator/Graph/Id.cs deleted file mode 100644 index 1eaeb1909e4eb..0000000000000 --- a/src/Features/Lsif/Generator/Graph/Id.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -/// -/// Represents an ID of a vertex or edge. -/// -/// Used to distinguish what type of object this ID applies to. This is dropped in serialization, but simply helps -/// to ensure type safety in the code so we don't cross IDs of different types. -internal readonly record struct Id(int NumericId) : ISerializableId where T : Element; - -internal interface ISerializableId -{ - public int NumericId { get; } -} - -internal static class IdExtensions -{ - /// - /// "Casts" a strongly type ID representing a derived type to a base type. - /// - public static Id As(this Id id) where TOut : Element where TIn : TOut - { - return new Id(id.NumericId); - } - - /// - /// Fetches a strongly-typed for a given element. - /// - public static Id GetId(this T element) where T : Element - { - return new Id(element.Id.NumericId); - } -} diff --git a/src/Features/Lsif/Generator/Graph/IdFactory.cs b/src/Features/Lsif/Generator/Graph/IdFactory.cs deleted file mode 100644 index cc28f5f1e9177..0000000000000 --- a/src/Features/Lsif/Generator/Graph/IdFactory.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Threading; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -/// -/// A little class which holds onto the next ID to be produced. Avoids static state in unit testing. -/// -internal sealed class IdFactory -{ - /// - /// The next numberic ID that will be used for an object. Accessed only with Interlocked.Increment. - /// - private int _globalId = 0; - - public Id Create() where T : Element - { - var id = Interlocked.Increment(ref _globalId); - return new Id(id); - } -} diff --git a/src/Features/Lsif/Generator/Graph/Item.cs b/src/Features/Lsif/Generator/Graph/Item.cs deleted file mode 100644 index a04e2b9ec0883..0000000000000 --- a/src/Features/Lsif/Generator/Graph/Item.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -/// -/// Represents a single item that points to a range or moniker from a result. See https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#request-textdocumentreferences -/// for an example of item edges. -/// -internal sealed class Item : Edge -{ - public Id Shard { get; } - public string? Property { get; } - - public Item(Id outVertex, Id range, Id document, IdFactory idFactory, string? property = null) - : base(label: "item", outVertex, [range.As()], idFactory) - { - Shard = document; - Property = property; - } - - public Item(Id outVertex, Id moniker, Id document, IdFactory idFactory, string? property = null) - : base(label: "item", outVertex, [moniker.As()], idFactory) - { - Shard = document; - Property = property; - } -} diff --git a/src/Features/Lsif/Generator/Graph/LsifDocument.cs b/src/Features/Lsif/Generator/Graph/LsifDocument.cs deleted file mode 100644 index e500e3b6172e3..0000000000000 --- a/src/Features/Lsif/Generator/Graph/LsifDocument.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using Roslyn.LanguageServer.Protocol; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -/// -/// Represents the document vertex that contains all the s. See https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#ranges for examples. -/// -internal sealed class LsifDocument : Vertex -{ - public Uri Uri { get; } - public string LanguageId { get; } - - /// - /// The base-64 encoded contents of the file. - /// - /// - /// We only include this for generated files. - /// - public string? Contents { get; } - - public LsifDocument(Uri uri, string languageId, string? contents, IdFactory idFactory) - : base(label: "document", idFactory) - { - this.Uri = uri; - this.LanguageId = languageId; - this.Contents = contents; - } -} diff --git a/src/Features/Lsif/Generator/Graph/LsifProject.cs b/src/Features/Lsif/Generator/Graph/LsifProject.cs deleted file mode 100644 index 69de2a285604d..0000000000000 --- a/src/Features/Lsif/Generator/Graph/LsifProject.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using Roslyn.LanguageServer.Protocol; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -/// -/// Represents a top-level project. See https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#the-project-vertex for further details. -/// -internal sealed class LsifProject : Vertex -{ - public string Kind { get; } - public Uri? Resource { get; } - public string Name { get; } - - public LsifProject(string kind, Uri? resource, string name, IdFactory idFactory) - : base(label: "project", idFactory) - { - Kind = kind; - Resource = resource; - Name = name; - } -} diff --git a/src/Features/Lsif/Generator/Graph/Moniker.cs b/src/Features/Lsif/Generator/Graph/Moniker.cs deleted file mode 100644 index 895cda54c031b..0000000000000 --- a/src/Features/Lsif/Generator/Graph/Moniker.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -internal sealed class Moniker : Vertex -{ - public string Scheme { get; } - public string Identifier { get; } - public string? Kind { get; } - - /// - /// Corresponds to the uniqueness level of a moniker, per https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#uniquenessLevel. - /// - public string? Unique { get; } - - public Moniker(string scheme, string identifier, string? kind, string? unique, IdFactory idFactory) - : base(label: "moniker", idFactory) - { - Scheme = scheme; - Identifier = identifier; - Kind = kind; - Unique = unique; - } -} diff --git a/src/Features/Lsif/Generator/Graph/Range.cs b/src/Features/Lsif/Generator/Graph/Range.cs deleted file mode 100644 index 132cca25bedf3..0000000000000 --- a/src/Features/Lsif/Generator/Graph/Range.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Microsoft.CodeAnalysis.Text; -using Roslyn.LanguageServer.Protocol; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -/// -/// Represents a Range for serialization. See https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#ranges for further details. -/// -internal sealed class Range : Vertex -{ - public Position Start { get; } - public Position End { get; } - public RangeTag? Tag { get; } - - public Range(Position start, Position end, RangeTag? tag, IdFactory idFactory) - : base(label: "range", idFactory) - { - Start = start; - End = end; - Tag = tag; - } - - public static Range FromTextSpan(TextSpan textSpan, SourceText sourceText, RangeTag? tag, IdFactory idFactory) - { - var linePositionSpan = sourceText.Lines.GetLinePositionSpan(textSpan); - - return new Range(start: ConvertLinePositionToPosition(linePositionSpan.Start), end: ConvertLinePositionToPosition(linePositionSpan.End), tag, idFactory); - } - - internal static Position ConvertLinePositionToPosition(LinePosition linePosition) - { - return new Position { Line = linePosition.Line, Character = linePosition.Character }; - } -} diff --git a/src/Features/Lsif/Generator/Graph/RangeBasedDocumentSymbol.cs b/src/Features/Lsif/Generator/Graph/RangeBasedDocumentSymbol.cs deleted file mode 100644 index 2e55b2cd33773..0000000000000 --- a/src/Features/Lsif/Generator/Graph/RangeBasedDocumentSymbol.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Generic; -using Microsoft.CodeAnalysis.Text; -using Newtonsoft.Json; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -internal sealed class RangeBasedDocumentSymbol(Id id, TextSpan span) -{ - [JsonProperty("id")] - public Id Id { get; } = id; - - /// - /// The Roslyn of the symbol, which is used only to produce the structure easily. Not serialized. - /// - [JsonIgnore] - public TextSpan Span { get; } = span; - - [JsonProperty("children")] - public List? Children { get; internal set; } - - public static void AddNestedFromDocumentOrderTraversal(List list, RangeBasedDocumentSymbol symbol) - { - // If this is the first entry, just add it - if (list.Count == 0) - { - list.Add(symbol); - } - else - { - // We are producing the symbols in document order, so we know that the new symbol is either inside the previous one, - // or is after that one. As a result we'll check the last one only. - var last = list[^1]; - - Contract.ThrowIfTrue(symbol.Span.Start < last.Span.Start, "We didn't produce symbols in document order, so we're not going to correctly structure the result."); - - if (last.Span.Contains(symbol.Span)) - { - last.Children ??= []; - AddNestedFromDocumentOrderTraversal(last.Children, symbol); - } - else - { - list.Add(symbol); - } - } - } -} diff --git a/src/Features/Lsif/Generator/Graph/RangeTag.cs b/src/Features/Lsif/Generator/Graph/RangeTag.cs deleted file mode 100644 index 4e956aaf1a95f..0000000000000 --- a/src/Features/Lsif/Generator/Graph/RangeTag.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -internal abstract class RangeTag(string type, string text) -{ - public string Type { get; } = type; - public string Text { get; } = text; -} diff --git a/src/Features/Lsif/Generator/Graph/ReferenceResult.cs b/src/Features/Lsif/Generator/Graph/ReferenceResult.cs deleted file mode 100644 index 689bc277a22e2..0000000000000 --- a/src/Features/Lsif/Generator/Graph/ReferenceResult.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -/// -/// Represents a referenceResult vertex for serialization. See https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#request-textdocumentreferences for further details. -/// -internal sealed class ReferenceResult : Vertex -{ - public ReferenceResult(IdFactory idFactory) - : base(label: "referenceResult", idFactory) - { - } -} diff --git a/src/Features/Lsif/Generator/Graph/ResultSet.cs b/src/Features/Lsif/Generator/Graph/ResultSet.cs deleted file mode 100644 index aaba35ab09c0b..0000000000000 --- a/src/Features/Lsif/Generator/Graph/ResultSet.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -/// -/// Represents a single ResultSet for serialization. See https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#result-set for further details. -/// -internal sealed class ResultSet : Vertex -{ - public ResultSet(IdFactory idFactory) - : base(label: "resultSet", idFactory) - { - } -} diff --git a/src/Features/Lsif/Generator/Graph/SemanticTokensCapabilities.cs b/src/Features/Lsif/Generator/Graph/SemanticTokensCapabilities.cs deleted file mode 100644 index 44e4585069c77..0000000000000 --- a/src/Features/Lsif/Generator/Graph/SemanticTokensCapabilities.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -using System.Collections.Generic; -using Newtonsoft.Json; - -internal sealed class SemanticTokensCapabilities -{ - public SemanticTokensCapabilities( - IReadOnlyList? tokenTypes, - IReadOnlyList? tokenModifiers) - { - this.TokenTypes = tokenTypes; - this.TokenModifiers = tokenModifiers; - } - - [JsonProperty("tokenTypes")] - public IReadOnlyList? TokenTypes { get; } - - [JsonProperty("tokenModifiers")] - public IReadOnlyList? TokenModifiers { get; } -} diff --git a/src/Features/Lsif/Generator/Graph/SemanticTokensResult.cs b/src/Features/Lsif/Generator/Graph/SemanticTokensResult.cs deleted file mode 100644 index ef73139bf19d5..0000000000000 --- a/src/Features/Lsif/Generator/Graph/SemanticTokensResult.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Roslyn.LanguageServer.Protocol; -using Newtonsoft.Json; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -/// -/// Represents a semantic tokens vertex for serialization. See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#semanticTokens for further details. -/// -internal sealed class SemanticTokensResult : Vertex -{ - [JsonProperty("result")] - public SemanticTokens Result { get; } - - public SemanticTokensResult(SemanticTokens result, IdFactory idFactory) - : base(label: "semanticTokensResult", idFactory) - { - Result = result; - } -} diff --git a/src/Features/Lsif/Generator/Graph/Vertex.cs b/src/Features/Lsif/Generator/Graph/Vertex.cs deleted file mode 100644 index cbcff42a7def7..0000000000000 --- a/src/Features/Lsif/Generator/Graph/Vertex.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -/// -/// The base class of any vertex in the graph that we serialize. -/// -internal abstract class Vertex : Element -{ - protected Vertex(string label, IdFactory idFactory) - : base(type: "vertex", label, idFactory) - { - } - - public override string ToString() - { - return $"{Label} vertex with ID {Id}"; - } -} diff --git a/src/Features/Lsif/Generator/Logging/LsifFormatLogger.cs b/src/Features/Lsif/Generator/Logging/LsifFormatLogger.cs deleted file mode 100644 index 60fa93ff1ffd6..0000000000000 --- a/src/Features/Lsif/Generator/Logging/LsifFormatLogger.cs +++ /dev/null @@ -1,56 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.IO; -using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Logging; - -internal sealed class LsifFormatLogger : ILogger -{ - private readonly TextWriter _writer; - private readonly object _writerGate = new object(); - - public LsifFormatLogger(TextWriter writer) - { - _writer = writer; - } - - public IDisposable BeginScope(TState state) where TState : notnull - { - throw new NotImplementedException(); - } - - public bool IsEnabled(LogLevel logLevel) - { - return logLevel >= LogLevel.Information; - } - - public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) - { - var message = formatter(state, exception); - - var severity = logLevel switch { LogLevel.Information => "Info", LogLevel.Warning => "Warning", LogLevel.Error => "Error", LogLevel.Critical => "Critical", _ => throw ExceptionUtilities.UnexpectedValue(logLevel) }; - - var command = new CommandWithParameters("log", - new LogCommandParameters(severity, message, exception?.Message, exception?.GetType().ToString(), exception?.StackTrace)); - var serializedCommand = JsonConvert.SerializeObject(command, LineModeLsifJsonWriter.SerializerSettings); - - lock (_writerGate) - { - _writer.Write(serializedCommand); - } - } - - private sealed record CommandWithParameters(string Command, object Parameters); - private sealed record LogCommandParameters( - string Severity, - string Message, - string? ExceptionMessage, - string? ExceptionType, - string? CallStack); -} diff --git a/src/Features/Lsif/Generator/Logging/PlainTextLogger.cs b/src/Features/Lsif/Generator/Logging/PlainTextLogger.cs deleted file mode 100644 index d881c6ea450c0..0000000000000 --- a/src/Features/Lsif/Generator/Logging/PlainTextLogger.cs +++ /dev/null @@ -1,45 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.IO; -using Microsoft.Extensions.Logging; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Logging; - -internal sealed class PlainTextLogger : ILogger -{ - private readonly TextWriter _writer; - private readonly object _gate = new object(); - - public PlainTextLogger(TextWriter writer) - { - _writer = writer; - } - - public IDisposable BeginScope(TState state) where TState : notnull - { - throw new NotImplementedException(); - } - - public bool IsEnabled(LogLevel logLevel) - { - return true; - } - - public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) - { - // Not all formatters will actually include the exception even if we pass it through, so include it here. - var message = formatter(state, exception); - var exceptionString = exception?.ToString(); - - lock (_gate) - { - _writer.WriteLine(message); - - if (exceptionString != null) - _writer.WriteLine(exceptionString); - } - } -} diff --git a/src/Features/Lsif/Generator/Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.csproj b/src/Features/Lsif/Generator/Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.csproj deleted file mode 100644 index 1b6c512bb1cfb..0000000000000 --- a/src/Features/Lsif/Generator/Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.csproj +++ /dev/null @@ -1,96 +0,0 @@ - - - - - Exe - Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator - $(NetRoslyn);net472 - $(RoslynPortableRuntimeIdentifiers) - - - true - true - false - tools - $(TargetsForTfmSpecificContentInPackage);_GetFilesToPackage - true - - - $(NoWarn);NU5128 - - - <_ResolveReferenceDependencies>true - - Microsoft.CodeAnalysis.Lsif.Generator - A tool to consume projects and compilations and emit an LSIF-compatible output that provides information about definitions, references and more. - For more information about LSIF, see https://code.visualstudio.com/blogs/2019/02/19/lsif - - false - - - en - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Features/Lsif/Generator/Program.cs b/src/Features/Lsif/Generator/Program.cs deleted file mode 100644 index 8d32b07de419a..0000000000000 --- a/src/Features/Lsif/Generator/Program.cs +++ /dev/null @@ -1,270 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Immutable; -using System.CommandLine; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Logging; -using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing; -using Microsoft.CodeAnalysis.MSBuild; -using Microsoft.CodeAnalysis.Shared.Extensions; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Abstractions; -using Roslyn.Utilities; -using CompilerInvocationsReader = Microsoft.Build.Logging.StructuredLogger.CompilerInvocationsReader; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator; - -internal static class Program -{ - public static Task Main(string[] args) - { - var solution = new Option("--solution") { Description = "input solution file" }.AcceptExistingOnly(); - var project = new Option("--project") { Description = "input project file" }.AcceptExistingOnly(); - var compilerInvocation = new Option("--compiler-invocation") { Description = "path to a .json file that contains the information for a csc/vbc invocation" }.AcceptExistingOnly(); - var binLog = new Option("--binlog") { Description = "path to a MSBuild binlog that csc/vbc invocations will be extracted from" }.AcceptExistingOnly(); - var output = new Option("--output") { Description = "file to write the LSIF output to, instead of the console", DefaultValueFactory = _ => null }; - output.AcceptLegalFilePathsOnly(); - var outputFormat = new Option("--output-format") { Description = "format of LSIF output", DefaultValueFactory = _ => LsifFormat.Line }; - var log = new Option("--log") { Description = "file to write a log to", DefaultValueFactory = _ => null }; - log.AcceptLegalFilePathsOnly(); - - var generateCommand = new RootCommand("generates an LSIF file") - { - solution, - project, - compilerInvocation, - binLog, - output, - outputFormat, - log - }; - - generateCommand.SetAction((parseResult, cancellationToken) => - { - return GenerateAsync( - solution: parseResult.GetValue(solution), - project: parseResult.GetValue(project), - compilerInvocation: parseResult.GetValue(compilerInvocation), - binLog: parseResult.GetValue(binLog), - outputFileName: parseResult.GetValue(output), - outputFormat: parseResult.GetValue(outputFormat), - logFileName: parseResult.GetValue(log), - cancellationToken); - }); - - return generateCommand.Parse(args).InvokeAsync(CancellationToken.None); - } - - private static async Task GenerateAsync( - FileInfo? solution, - FileInfo? project, - FileInfo? compilerInvocation, - FileInfo? binLog, - string? outputFileName, - LsifFormat outputFormat, - string? logFileName, - CancellationToken cancellationToken) - { - // If we have an output file, we'll write to that, else we'll use Console.Out - using var outputFile = outputFileName != null ? new StreamWriter(outputFileName, append: false, Encoding.UTF8) : null; - TextWriter outputWriter; - - if (outputFile is null) - { - Console.OutputEncoding = Encoding.UTF8; - outputWriter = Console.Out; - } - else - { - outputWriter = outputFile; - } - - ILsifJsonWriter lsifWriter = outputFormat switch - { - LsifFormat.Json => new JsonModeLsifJsonWriter(outputWriter), - LsifFormat.Line => new LineModeLsifJsonWriter(outputWriter), - _ => throw new NotImplementedException() - }; - - using var logFile = logFileName is not null and not "stderr" ? new StreamWriter(logFileName) { AutoFlush = true } : null; - - ILogger logger; - if (logFile is not null) - logger = new PlainTextLogger(logFile); - else if (logFileName == "stderr") - logger = new LsifFormatLogger(Console.Error); - else - logger = NullLogger.Instance; - - var totalExecutionTime = Stopwatch.StartNew(); - - try - { - // Exactly one of "solution", or "project" or "compilerInvocation" should be specified - var fileInputs = new[] { solution, project, compilerInvocation, binLog }; - var nonNullFileInputs = fileInputs.Count(p => p is not null); - - if (nonNullFileInputs != 1) - { - throw new Exception("Exactly one of either a solution path, project path or a compiler invocation path should be supplied."); - } - - if (solution != null) - { - await GenerateFromSolutionAsync(solution, lsifWriter, logger, cancellationToken); - } - else if (project != null) - { - await GenerateFromProjectAsync(project, lsifWriter, logger, cancellationToken); - } - else if (compilerInvocation != null) - { - await GenerateFromCompilerInvocationAsync(compilerInvocation, lsifWriter, logger, cancellationToken); - } - else - { - Contract.ThrowIfNull(binLog); - await GenerateFromBinaryLogAsync(binLog, lsifWriter, logger, cancellationToken); - } - } - catch (Exception e) - { - // If it failed, write out to the logs, but propagate the error too - var message = "Unhandled exception: " + e.ToString(); - logger.LogCritical(e, message); - // System.CommandLine is going to catch the exception and log it in standard error - throw; - } - - (lsifWriter as IDisposable)?.Dispose(); - logger.LogInformation($"Generation complete. Total execution time: {totalExecutionTime.Elapsed.ToDisplayString()}"); - } - - private static async Task GenerateFromProjectAsync( - FileInfo projectFile, ILsifJsonWriter lsifWriter, ILogger logger, CancellationToken cancellationToken) - { - await GenerateWithMSBuildWorkspaceAsync( - projectFile, lsifWriter, logger, - async (workspace, cancellationToken) => - { - var project = await workspace.OpenProjectAsync(projectFile.FullName, cancellationToken: cancellationToken); - return project.Solution; - }, - cancellationToken); - } - - private static async Task GenerateFromSolutionAsync( - FileInfo solutionFile, ILsifJsonWriter lsifWriter, ILogger logger, CancellationToken cancellationToken) - { - await GenerateWithMSBuildWorkspaceAsync( - solutionFile, lsifWriter, logger, - (workspace, cancellationToken) => workspace.OpenSolutionAsync(solutionFile.FullName, cancellationToken: cancellationToken), - cancellationToken); - } - - private static async Task GenerateWithMSBuildWorkspaceAsync( - FileInfo solutionOrProjectFile, - ILsifJsonWriter lsifWriter, - ILogger logger, - Func> openAsync, - CancellationToken cancellationToken) - { - logger.LogInformation($"Loading {solutionOrProjectFile.FullName}..."); - - var solutionLoadStopwatch = Stopwatch.StartNew(); - - using var msbuildWorkspace = MSBuildWorkspace.Create(await Composition.CreateHostServicesAsync()); - _ = msbuildWorkspace.RegisterWorkspaceFailedHandler((e) => logger.Log(e.Diagnostic.Kind == WorkspaceDiagnosticKind.Failure ? LogLevel.Error : LogLevel.Warning, "Problem while loading: " + e.Diagnostic.Message)); - - var solution = await openAsync(msbuildWorkspace, cancellationToken); - - var options = GeneratorOptions.Default; - - logger.LogInformation($"Load completed in {solutionLoadStopwatch.Elapsed.ToDisplayString()}."); - var lsifGenerator = Generator.CreateAndWriteCapabilitiesVertex(lsifWriter, logger); - - var totalTimeInGenerationAndCompilationFetchStopwatch = Stopwatch.StartNew(); - var totalTimeInGenerationPhase = TimeSpan.Zero; - - foreach (var project in solution.Projects) - { - if (project.SupportsCompilation && project.FilePath != null) - { - var compilationCreationStopwatch = Stopwatch.StartNew(); - var compilation = await project.GetRequiredCompilationAsync(cancellationToken); - - logger.LogInformation($"Fetch of compilation for {project.FilePath} completed in {compilationCreationStopwatch.Elapsed.ToDisplayString()}."); - - var generationForProjectStopwatch = Stopwatch.StartNew(); - await lsifGenerator.GenerateForProjectAsync(project, options, cancellationToken); - generationForProjectStopwatch.Stop(); - - totalTimeInGenerationPhase += generationForProjectStopwatch.Elapsed; - - logger.LogInformation($"Generation for {project.FilePath} completed in {generationForProjectStopwatch.Elapsed.ToDisplayString()}."); - } - } - - logger.LogInformation($"Total time spent in the generation phase for all projects, excluding compilation fetch time: {totalTimeInGenerationPhase.ToDisplayString()}"); - logger.LogInformation($"Total time spent in the generation phase for all projects, including compilation fetch time: {totalTimeInGenerationAndCompilationFetchStopwatch.Elapsed.ToDisplayString()}"); - } - - private static async Task GenerateFromCompilerInvocationAsync( - FileInfo compilerInvocationFile, ILsifJsonWriter lsifWriter, ILogger logger, CancellationToken cancellationToken) - { - logger.LogInformation($"Processing compiler invocation from {compilerInvocationFile.FullName}..."); - - var compilerInvocationLoadStopwatch = Stopwatch.StartNew(); - var project = await CompilerInvocation.CreateFromJsonAsync(File.ReadAllText(compilerInvocationFile.FullName)); - logger.LogInformation($"Load of the project completed in {compilerInvocationLoadStopwatch.Elapsed.ToDisplayString()}."); - - var generationStopwatch = Stopwatch.StartNew(); - var lsifGenerator = Generator.CreateAndWriteCapabilitiesVertex(lsifWriter, logger); - - await lsifGenerator.GenerateForProjectAsync(project, GeneratorOptions.Default, cancellationToken); - logger.LogInformation($"Generation for {project.FilePath} completed in {generationStopwatch.Elapsed.ToDisplayString()}."); - } - - private static async Task GenerateFromBinaryLogAsync( - FileInfo binLog, ILsifJsonWriter lsifWriter, ILogger logger, CancellationToken cancellationToken) - { - logger.LogInformation($"Reading binlog {binLog.FullName}..."); - var msbuildInvocations = CompilerInvocationsReader.ReadInvocations(binLog.FullName).ToImmutableArray(); - - logger.LogInformation($"Load of the binlog complete; {msbuildInvocations.Length} invocations were found."); - - var lsifGenerator = Generator.CreateAndWriteCapabilitiesVertex(lsifWriter, logger); - using var workspace = new AdhocWorkspace(await Composition.CreateHostServicesAsync()); - - foreach (var msbuildInvocation in msbuildInvocations) - { - var projectInfo = CommandLineProject.CreateProjectInfo( - Path.GetFileNameWithoutExtension(msbuildInvocation.ProjectFilePath), - msbuildInvocation.Language == Microsoft.Build.Logging.StructuredLogger.CompilerInvocation.CSharp ? LanguageNames.CSharp : LanguageNames.VisualBasic, - msbuildInvocation.CommandLineArguments, - msbuildInvocation.ProjectDirectory, - workspace) - .WithFilePath(msbuildInvocation.ProjectFilePath); - - workspace.OnProjectAdded(projectInfo); - - var project = workspace.CurrentSolution.Projects.Single(); - - var generationStopwatch = Stopwatch.StartNew(); - await lsifGenerator.GenerateForProjectAsync(project, GeneratorOptions.Default, cancellationToken); - logger.LogInformation($"Generation for {project.FilePath} completed in {generationStopwatch.Elapsed.ToDisplayString()}."); - - // Remove the project from the workspace; we reuse the same workspace object to ensure that some workspace-level services (like the IMetadataService - // or IDocumentationProviderService) are kept around allowing their caches to be reused. - workspace.OnProjectRemoved(project.Id); - } - } -} diff --git a/src/Features/Lsif/Generator/README.md b/src/Features/Lsif/Generator/README.md deleted file mode 100644 index 27f9b6ab715e4..0000000000000 --- a/src/Features/Lsif/Generator/README.md +++ /dev/null @@ -1,24 +0,0 @@ -This tool consumes a project or solution and generates a Language Server Index Format file per the -[LSIF specification](https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md). - -# Command Line Switches -## Specifying the Project to Process -### `--solution` -The path to the Visual Studio Solution file to process. The LSIF graph for all projects will be outputted. - -### `--compiler-invocation` -Specifies a path to a JSON file that contains the information of a compiler invocation. This JSON file includes the compiler that was ran, the command string passed, and path information. This allows you to generate an LSIF file that -matches the same setup as an actual build without the tool having to run MSBuild itself to regreate the compiler command line string. - -## Output Files - -### `--output` -Accepts a file path, and writes the results to that file instead of the console output. - -## `--output-format` -Either "Line" (the default) to write out the LSIF where each line in the text is a separate JSON object, or -"JSON" where the LSIF is written out as a single large JSON array. - -### `--log` -Accepts a file path where a log file is written to. The log file contains information regarding how long various -parts of the LSIF generation took. \ No newline at end of file diff --git a/src/Features/Lsif/Generator/ResultSetTracking/DelegatingResultSetTracker.cs b/src/Features/Lsif/Generator/ResultSetTracking/DelegatingResultSetTracker.cs deleted file mode 100644 index aef93b7b42de5..0000000000000 --- a/src/Features/Lsif/Generator/ResultSetTracking/DelegatingResultSetTracker.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.ResultSetTracking; - -internal sealed class DelegatingResultSetTracker : IResultSetTracker -{ - private readonly Func _chooseTrackerForSymbol; - - public DelegatingResultSetTracker(Func chooseTrackerForSymbol) - { - _chooseTrackerForSymbol = chooseTrackerForSymbol; - } - - public Id GetResultIdForSymbol(ISymbol symbol, string edgeKind, Func vertexCreator) where T : Vertex - { - return _chooseTrackerForSymbol(symbol).GetResultIdForSymbol(symbol, edgeKind, vertexCreator); - } - - public Id GetResultSetIdForSymbol(ISymbol symbol) - { - return _chooseTrackerForSymbol(symbol).GetResultSetIdForSymbol(symbol); - } - - public bool ResultSetNeedsInformationalEdgeAdded(ISymbol symbol, string edgeKind) - { - return _chooseTrackerForSymbol(symbol).ResultSetNeedsInformationalEdgeAdded(symbol, edgeKind); - } -} diff --git a/src/Features/Lsif/Generator/ResultSetTracking/IResultSetTracker.cs b/src/Features/Lsif/Generator/ResultSetTracking/IResultSetTracker.cs deleted file mode 100644 index 933d9a8c4b4c3..0000000000000 --- a/src/Features/Lsif/Generator/ResultSetTracking/IResultSetTracker.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.ResultSetTracking; - -/// -/// An object that tracks a mapping from symbols to the result sets that have information about those symbols. -/// -internal interface IResultSetTracker -{ - /// - /// Returns the ID of the that represents a symbol. - /// - Id GetResultSetIdForSymbol(ISymbol symbol); - - /// - /// Returns an ID of a vertex that is linked from a result set. For example, a has an edge that points to a , and - /// item edges from that are the references for the range. This gives you the ID of the in this case. - /// - Id GetResultIdForSymbol(ISymbol symbol, string edgeKind, Func vertexCreator) where T : Vertex; - - /// - /// Similar to , but instead of creating the vertex (if needed) and adding an edge, this - /// simply tracks that this method has been called, and it's up to the caller that got a true return value to create and add the vertex themselves. This is handy - /// when the actual identity of the node isn't needed by any other consumers, or the vertex creation is expensive and we don't want it running under the lock that - /// would have to take. - /// - bool ResultSetNeedsInformationalEdgeAdded(ISymbol symbol, string edgeKind); -} diff --git a/src/Features/Lsif/Generator/ResultSetTracking/IResultSetTrackerExtensions.cs b/src/Features/Lsif/Generator/ResultSetTracking/IResultSetTrackerExtensions.cs deleted file mode 100644 index d6fe30bb3a0b8..0000000000000 --- a/src/Features/Lsif/Generator/ResultSetTracking/IResultSetTrackerExtensions.cs +++ /dev/null @@ -1,47 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; -using Roslyn.LanguageServer.Protocol; -using Moniker = Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph.Moniker; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.ResultSetTracking; - -internal static class IResultSetTrackerExtensions -{ - /// - /// Returns the ID of the for a . - /// - public static Id GetResultSetReferenceResultId(this IResultSetTracker tracker, ISymbol symbol) - => tracker.GetResultIdForSymbol(symbol, Methods.TextDocumentReferencesName, static idFactory => new ReferenceResult(idFactory)); - - /// - /// Fetches the moniker node for a symbol; this should only be called on symbols where returns true. - /// - public static Id GetMoniker(this IResultSetTracker tracker, ISymbol symbol, Compilation sourceCompilation) - { - return tracker.GetResultIdForSymbol(symbol, "moniker", idFactory => - { - var moniker = SymbolMoniker.Create(symbol); - - string? kind; - - if (symbol.Kind == SymbolKind.Namespace) - { - kind = null; - } - else if (symbol.ContainingAssembly.Equals(sourceCompilation.Assembly)) - { - kind = "export"; - } - else - { - kind = "import"; - } - - // Since we fully qualify everything, all monitors are unique within the scheme - return new Moniker(moniker.Scheme, moniker.Identifier, kind, unique: "scheme", idFactory); - }); - } -} diff --git a/src/Features/Lsif/Generator/ResultSetTracking/SymbolHoldingResultSetTracker.cs b/src/Features/Lsif/Generator/ResultSetTracking/SymbolHoldingResultSetTracker.cs deleted file mode 100644 index 2dd24e1a4f062..0000000000000 --- a/src/Features/Lsif/Generator/ResultSetTracking/SymbolHoldingResultSetTracker.cs +++ /dev/null @@ -1,170 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Threading; -using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; -using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing; -using Roslyn.Utilities; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.ResultSetTracking; - -internal sealed class SymbolHoldingResultSetTracker : IResultSetTracker -{ - private readonly Dictionary _symbolToResultSetId = []; - private readonly ReaderWriterLockSlim _readerWriterLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); - private readonly ILsifJsonWriter _lsifJsonWriter; - private readonly IdFactory _idFactory; - - /// - /// The compilation which we are analyzing. When we make ResultSets, we attach monikers to them, and those - /// monikers express an import/export concept for symbols being consumed from another project. We must distinguish - /// from source symbols that come from the project being analyzed versus symbols from referenced compilations, so - /// we can't just use to make the determination. - /// - private readonly Compilation _sourceCompilation; - - public SymbolHoldingResultSetTracker(ILsifJsonWriter lsifJsonWriter, Compilation sourceCompilation, IdFactory idFactory) - { - _lsifJsonWriter = lsifJsonWriter; - _sourceCompilation = sourceCompilation; - _idFactory = idFactory; - } - - private TrackedResultSet GetTrackedResultSet(ISymbol symbol) - { - TrackedResultSet? trackedResultSet; - - // First acquire a simple read lock to see if we already have a result set; we do this with - // just a read lock to ensure we aren't contending a lot if the symbol already exists which - // is the most common case. - using (_readerWriterLock.DisposableRead()) - { - if (_symbolToResultSetId.TryGetValue(symbol, out trackedResultSet)) - { - return trackedResultSet; - } - } - - using (var upgradeableReadLock = _readerWriterLock.DisposableUpgradeableRead()) - { - // Check a second for the result set since a request could have gotten between us - if (_symbolToResultSetId.TryGetValue(symbol, out trackedResultSet)) - { - return trackedResultSet; - } - - // We still don't have it, so we have to start writing now - upgradeableReadLock.EnterWrite(); - - var resultSet = new ResultSet(_idFactory); - _lsifJsonWriter.Write(resultSet); - trackedResultSet = new TrackedResultSet(resultSet.GetId()); - _symbolToResultSetId.Add(symbol, trackedResultSet); - } - - // Since we're creating a ResultSet for a symbol for the first time, let's also attach the moniker. We only generate - // monikers for original definitions as we don't have a moniker system for those, but also because the place where - // monikers are needed -- cross-solution find references and go to definition -- only operates on original definitions - // anyways. - // - // This we do outside the lock -- whichever thread was the one to create this was the one that - // gets to write out the moniker, but others can use the ResultSet Id at this point. - if (SymbolMoniker.HasMoniker(symbol)) - { - _ = this.GetMoniker(symbol, _sourceCompilation); - } - - return trackedResultSet; - } - - public Id GetResultSetIdForSymbol(ISymbol symbol) - { - return GetTrackedResultSet(symbol).Id; - } - - public Id GetResultIdForSymbol(ISymbol symbol, string edgeKind, Func vertexCreator) where T : Vertex - { - return GetTrackedResultSet(symbol).GetResultId(edgeKind, vertexCreator, _lsifJsonWriter, _idFactory); - } - - public bool ResultSetNeedsInformationalEdgeAdded(ISymbol symbol, string edgeKind) - { - return GetTrackedResultSet(symbol).ResultSetNeedsInformationalEdgeAdded(edgeKind); - } - - private sealed class TrackedResultSet - { - public Id Id { get; } - - /// - /// A map which holds the per-symbol results that are linked from the resultSet. The value will be null if the entry was - /// added via . Concurrent acecss is guarded with a monitor lock - /// on this field itself, with the belief that concurrent access for a single symbol is relatively rare. - /// - /// - /// This class assumes that we more or less have two kinds of edges in the LSIF world: - /// - /// 1. the resultSet might point to a node that doesn't really have any data, but simply points to other data like referenceResults. - /// In this case, it's important for clients to get to that Id. - /// 2. the resultSet points to a node that itself has data, but nobody needs to know the ID, like a hover result. In this case, those results - /// are often expensive to compute, but we do want to record that somebody is adding them somewhere. - /// - /// We record the first kind of this in this dictionary with a non-null Id, and the second kind with a null ID. We could conceptually store - /// two dictionaries for this, but that will add memory pressure and also limit the catching of mistakes if people cross these two APIs. - /// - private readonly Dictionary?> _edgeKindToVertexId = []; - - public TrackedResultSet(Id id) - { - Id = id; - } - - public Id GetResultId(string edgeLabel, Func vertexCreator, ILsifJsonWriter lsifJsonWriter, IdFactory idFactory) where T : Vertex - { - lock (_edgeKindToVertexId) - { - if (_edgeKindToVertexId.TryGetValue(edgeLabel, out var existingId)) - { - if (!existingId.HasValue) - { - throw new Exception($"This ResultSet already has an edge of {edgeLabel} as {nameof(ResultSetNeedsInformationalEdgeAdded)} was called with this edge label."); - } - - // TODO: this is a violation of the type system here, really: we're assuming that all calls to this function with the same edge kind - // will have the same type parameter. If that's violated, the Id returned here isn't really the right type. - return new Id(existingId.Value.NumericId); - } - - var vertex = vertexCreator(idFactory); - _edgeKindToVertexId.Add(edgeLabel, vertex.GetId().As()); - - lsifJsonWriter.Write(vertex); - lsifJsonWriter.Write(Edge.Create(edgeLabel, Id, vertex.GetId(), idFactory)); - - return vertex.GetId(); - } - } - - public bool ResultSetNeedsInformationalEdgeAdded(string edgeKind) - { - lock (_edgeKindToVertexId) - { - if (_edgeKindToVertexId.TryGetValue(edgeKind, out var existingId)) - { - if (existingId.HasValue) - { - throw new InvalidOperationException($"This edge kind was already called with a call to {nameof(GetResultId)} which would imply we are mixing edge types incorrectly."); - } - - return false; - } - - _edgeKindToVertexId.Add(edgeKind, null); - return true; - } - } - } -} diff --git a/src/Features/Lsif/Generator/Utilities.cs b/src/Features/Lsif/Generator/Utilities.cs deleted file mode 100644 index 4d5c426a71d41..0000000000000 --- a/src/Features/Lsif/Generator/Utilities.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator; - -internal static class Utilities -{ - public static string ToDisplayString(this TimeSpan timeSpan) - { - return timeSpan.TotalSeconds.ToString("N2") + " seconds"; - } -} diff --git a/src/Features/Lsif/Generator/Writing/BatchingLsifJsonWriter.cs b/src/Features/Lsif/Generator/Writing/BatchingLsifJsonWriter.cs deleted file mode 100644 index 09d90f1109cc3..0000000000000 --- a/src/Features/Lsif/Generator/Writing/BatchingLsifJsonWriter.cs +++ /dev/null @@ -1,83 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Generic; -using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing; - -/// -/// An that lets us batch up a bunch of elements and -/// write them at once. This allows for less contention on shared locks since we can have -/// multiple parallel tasks producing items, and then only at the end contribute items into -/// the final file. -/// -internal sealed class BatchingLsifJsonWriter : ILsifJsonWriter -{ - /// - /// A lock that must be held when adding elements to . - /// - private readonly object _elementsGate = new object(); - private List _elements = []; - - /// - /// A lock held when writing to ensure that we maintain ordering of elements across multiple threads. - /// - /// - /// The LSIF file format requires that any vertices referenced by an edge must be written before - /// the edges that use that vertex. This creates some complexity because we want to be able to batch - /// writes to the JSON as much as possible to avoid a lot of locking overhead. There's some shared state - /// that we must track for global symbols, like IDs of various reference lists, and for us to add - /// reference to those we need to ensure that shared state is flushed before we can write per-document state. - /// - /// This lock is acquired during the entirety of a call to . That - /// method wants to hold for a short as possible, to allow other threads - /// producing new (unrelated) work to not be blocked behind us writing to the output. But if multiple threads - /// are trying to flush the same thing, only one thread is going to acquire the list of items to flush. - /// However, all threads need to wait until that flushing is complete before they can continue to write - /// to the shared output. By having two locks, this lets us release as soon - /// as we have the list of items, but we can still ensure that all callers to - /// have waited for what they needed done. - /// - private readonly object _writingGate = new object(); - - private readonly ILsifJsonWriter _underlyingWriter; - - public BatchingLsifJsonWriter(ILsifJsonWriter underlyingWriter) - { - _underlyingWriter = underlyingWriter; - } - - public void Write(Element element) - { - lock (_elementsGate) - { - _elements.Add(element); - } - } - - public void WriteAll(List elements) - { - lock (_elementsGate) - { - _elements.AddRange(elements); - } - } - - public void FlushToUnderlyingAndEmpty() - { - lock (_writingGate) - { - List localElements; - - lock (_elementsGate) - { - localElements = _elements; - _elements = []; - } - - _underlyingWriter.WriteAll(localElements); - } - } -} diff --git a/src/Features/Lsif/Generator/Writing/ILsifJsonWriter.cs b/src/Features/Lsif/Generator/Writing/ILsifJsonWriter.cs deleted file mode 100644 index a5d8ee59df0b0..0000000000000 --- a/src/Features/Lsif/Generator/Writing/ILsifJsonWriter.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Generic; -using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing; - -internal interface ILsifJsonWriter -{ - void Write(Element element); - void WriteAll(List elements); -} diff --git a/src/Features/Lsif/Generator/Writing/JsonModeLsifJsonWriter.cs b/src/Features/Lsif/Generator/Writing/JsonModeLsifJsonWriter.cs deleted file mode 100644 index 30fff046177e8..0000000000000 --- a/src/Features/Lsif/Generator/Writing/JsonModeLsifJsonWriter.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.IO; -using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing; - -/// -/// An that writes in . -/// -internal sealed class JsonModeLsifJsonWriter : ILsifJsonWriter, IDisposable -{ - private readonly JsonTextWriter _jsonTextWriter; - private readonly JsonSerializer _jsonSerializer; - private readonly object _writeGate = new object(); - - public JsonModeLsifJsonWriter(TextWriter outputWriter) - { - var settings = new JsonSerializerSettings - { - Formatting = Newtonsoft.Json.Formatting.Indented, - NullValueHandling = NullValueHandling.Ignore, - ContractResolver = new CamelCasePropertyNamesContractResolver(), - TypeNameHandling = TypeNameHandling.None, - Converters = new[] { new LsifConverter() } - }; - - _jsonSerializer = JsonSerializer.Create(settings); - - _jsonTextWriter = new JsonTextWriter(outputWriter); - _jsonTextWriter.WriteStartArray(); - } - - public void Write(Element element) - { - lock (_writeGate) - { - _jsonSerializer.Serialize(_jsonTextWriter, element); - } - } - - public void WriteAll(List elements) - { - lock (_writeGate) - { - foreach (var element in elements) - _jsonSerializer.Serialize(_jsonTextWriter, element); - } - } - - public void Dispose() - { - _jsonTextWriter.WriteWhitespace(Environment.NewLine); - _jsonTextWriter.WriteEndArray(); - _jsonTextWriter.Close(); - } -} diff --git a/src/Features/Lsif/Generator/Writing/LineModeLsifJsonWriter.cs b/src/Features/Lsif/Generator/Writing/LineModeLsifJsonWriter.cs deleted file mode 100644 index 2b463d2fe12fc..0000000000000 --- a/src/Features/Lsif/Generator/Writing/LineModeLsifJsonWriter.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Generic; -using System.IO; -using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing; - -/// -/// An that writes in . -/// -internal sealed partial class LineModeLsifJsonWriter : ILsifJsonWriter -{ - public static readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings - { - Formatting = Newtonsoft.Json.Formatting.None, - NullValueHandling = NullValueHandling.Ignore, - ContractResolver = new CamelCasePropertyNamesContractResolver(), - TypeNameHandling = TypeNameHandling.None, - Converters = new[] { new LsifConverter() } - }; - - private readonly object _writeGate = new object(); - private readonly TextWriter _outputWriter; - - public LineModeLsifJsonWriter(TextWriter outputWriter) - { - _outputWriter = outputWriter; - } - - public void Write(Element element) - { - var line = JsonConvert.SerializeObject(element, SerializerSettings); - - lock (_writeGate) - { - _outputWriter.WriteLine(line); - } - } - - public void WriteAll(List elements) - { - var lines = new List(); - foreach (var element in elements) - lines.Add(JsonConvert.SerializeObject(element, SerializerSettings)); - - lock (_writeGate) - { - foreach (var line in lines) - _outputWriter.WriteLine(line); - } - } -} diff --git a/src/Features/Lsif/Generator/Writing/LsifConverter.cs b/src/Features/Lsif/Generator/Writing/LsifConverter.cs deleted file mode 100644 index 2559fd46ec464..0000000000000 --- a/src/Features/Lsif/Generator/Writing/LsifConverter.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Linq; -using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; -using Newtonsoft.Json; - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing; - -internal sealed class LsifConverter : JsonConverter -{ - public override bool CanConvert(Type objectType) - { - if (typeof(ISerializableId).IsAssignableFrom(objectType) || - objectType == typeof(Uri)) - { - return true; - } - - if (objectType.IsConstructedGenericType && objectType.GetGenericTypeDefinition() == typeof(Nullable<>)) - { - return CanConvert(objectType.GenericTypeArguments.Single()); - } - - return false; - } - - public override object ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) - { - throw new NotImplementedException(); - } - - public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) - { - switch (value) - { - case ISerializableId id: - writer.WriteValue(id.NumericId); - break; - - case Uri uri: - writer.WriteValue(uri.ToString()); - break; - - default: - throw new NotSupportedException(); - } - } -} diff --git a/src/Features/Lsif/Generator/Writing/LsifFormat.cs b/src/Features/Lsif/Generator/Writing/LsifFormat.cs deleted file mode 100644 index b43a6fc66c637..0000000000000 --- a/src/Features/Lsif/Generator/Writing/LsifFormat.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing; - -internal enum LsifFormat -{ - /// - /// Line format, where each line is a JSON object. - /// - Line, - - /// - /// JSON format, where the entire output is a single JSON array. - /// - Json -} diff --git a/src/Features/Lsif/GeneratorTest/CompilerInvocationTests.vb b/src/Features/Lsif/GeneratorTest/CompilerInvocationTests.vb index 59b7e24433769..afc954718d36a 100644 --- a/src/Features/Lsif/GeneratorTest/CompilerInvocationTests.vb +++ b/src/Features/Lsif/GeneratorTest/CompilerInvocationTests.vb @@ -2,6 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests diff --git a/src/Features/Lsif/GeneratorTest/DocumentSymbolTests.vb b/src/Features/Lsif/GeneratorTest/DocumentSymbolTests.vb deleted file mode 100644 index e9d5d9d8bf287..0000000000000 --- a/src/Features/Lsif/GeneratorTest/DocumentSymbolTests.vb +++ /dev/null @@ -1,103 +0,0 @@ -' Licensed to the .NET Foundation under one or more agreements. -' The .NET Foundation licenses this file to you under the MIT license. -' See the LICENSE file in the project root for more information. - -Imports Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Roslyn.Test.Utilities -Imports LSP = Roslyn.LanguageServer.Protocol - -Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests - - Public Class DocumentSymbolTests - - - - - - - - - Public Async Function TestDefinition(code As String, expectedSymbolKindInt As Integer, expectedText As String) As Task - Dim expectedSymbolKind = CType(expectedSymbolKindInt, LSP.SymbolKind) - Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( - - - - <%= code %> - - - ) - - ' Assert the specific range is what we expected - Dim selectedRange = Await lsif.GetSelectedRangeAsync() - Assert.NotNull(selectedRange) - Dim definitionTag = Assert.IsType(Of DefinitionRangeTag)(selectedRange.Tag) - Assert.Equal(expectedSymbolKind, definitionTag.Kind) - - Dim expectedFullRange = Await lsif.GetAnnotatedLspRangeAsync("fullRange") - Assert.Equal(expectedFullRange, definitionTag.FullRange) - - Assert.Equal(expectedText, definitionTag.Text) - - ' We also output the overall hierarchy of document symbols as a document request; ensure that contains all the ranges - Dim document = lsif.Vertices.OfType(Of LsifDocument).Single() - Dim documentSymbolResult = Assert.Single(lsif.GetLinkedVertices(Of DocumentSymbolResult)(document, LSP.Methods.TextDocumentDocumentSymbolName)) - Dim allDocumentSymbolRangeVertices = GetDocumentSymbolRangeIds(documentSymbolResult.Result) - Dim allRangeVertices = lsif.Vertices.OfType(Of Range).Where(Function(r) TypeOf r.Tag Is DefinitionRangeTag) - - AssertEx.SetEqual(allRangeVertices.Select(Function(r) r.GetId()), allDocumentSymbolRangeVertices) - - For Each documentSymbol In documentSymbolResult.Result - AssertDocumentSymbolContainsChildren(documentSymbol) - Next - End Function - - ''' - ''' This tests symbols that might be considered "definitions" in the C#/Roslyn sense, but don't make sense to emit as a document symbol. - ''' - - - - - Public Async Function TestIsNotDefinition(code As String) As Task - Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( - - - - <%= code %> - - - ) - - ' Assert the specific range is what we expected - Dim selectedRange = Await lsif.GetSelectedRangeAsync() - Assert.NotNull(selectedRange) - Assert.Null(selectedRange.Tag) - End Function - - Private Shared Function GetDocumentSymbolRangeIds(result As List(Of RangeBasedDocumentSymbol)) As IEnumerable(Of Id(Of Range)) - If result Is Nothing Then - Return Array.Empty(Of Id(Of Range)) - End If - - Return result.SelectMany(Iterator Function(documentSymbol) - Yield documentSymbol.Id - - For Each childId In GetDocumentSymbolRangeIds(documentSymbol.Children) - Yield childId - Next - End Function) - End Function - - Private Shared Sub AssertDocumentSymbolContainsChildren(documentSymbol As RangeBasedDocumentSymbol) - If documentSymbol.Children IsNot Nothing Then - For Each child In documentSymbol.Children - Assert.True(documentSymbol.Span.Contains(child.Span)) - - AssertDocumentSymbolContainsChildren(child) - Next - End If - End Sub - End Class -End Namespace diff --git a/src/Features/Lsif/GeneratorTest/FoldingRangeTests.vb b/src/Features/Lsif/GeneratorTest/FoldingRangeTests.vb deleted file mode 100644 index 07ab30c4f4720..0000000000000 --- a/src/Features/Lsif/GeneratorTest/FoldingRangeTests.vb +++ /dev/null @@ -1,79 +0,0 @@ -' Licensed to the .NET Foundation under one or more agreements. -' The .NET Foundation licenses this file to you under the MIT license. -' See the LICENSE file in the project root for more information. - -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Roslyn.LanguageServer.Protocol -Imports Roslyn.Test.Utilities - -Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests - - Public NotInheritable Class FoldingRangeTests - Private Const TestProjectAssemblyName As String = "TestProject" - - ' Expected 'FoldingRangeKind' argument would likely change for some of the tests when - ' https://github.com/dotnet/roslyn/projects/45#card-20049168 is implemented. - - - - - - - - Public Async Function TestFoldingRanges(code As String, collapsedText As String) As Task - Using workspace = EditorTestWorkspace.CreateWorkspace( - - FilePath="Z:\TestProject.csproj" CommonReferences="true"> - - <%= code %> - - - , openDocuments:=False, composition:=TestLsifOutput.TestComposition) - Dim annotatedLocations = Await AbstractLanguageServerProtocolTests.GetAnnotatedLocationsAsync(workspace, workspace.CurrentSolution) - Dim expectedRanges = annotatedLocations.SelectMany(Function(kvp) kvp.Value.Select(Function(location) CreateFoldingRange(kvp.Key, location.Range, collapsedText))).OrderByDescending(Function(range) range.StartLine).ToArray() - - Dim document = workspace.CurrentSolution.Projects.Single().Documents.Single() - Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync(workspace) - Dim actualRanges = lsif.GetFoldingRanges(document) - - AbstractLanguageServerProtocolTests.AssertJsonEquals(expectedRanges, actualRanges) - End Using - End Function - - Private Shared Function CreateFoldingRange(kind As String, range As Range, collapsedText As String) As FoldingRange - Dim foldingRange As FoldingRange = New FoldingRange() With - { - .StartCharacter = range.Start.Character, - .EndCharacter = range.End.Character, - .StartLine = range.Start.Line, - .EndLine = range.End.Line, - .CollapsedText = collapsedText - } - If kind IsNot Nothing AndAlso kind <> "foldingRange" Then - foldingRange.Kind = New FoldingRangeKind(kind) - End If - Return foldingRange - End Function - End Class -End Namespace diff --git a/src/Features/Lsif/GeneratorTest/HoverTests.vb b/src/Features/Lsif/GeneratorTest/HoverTests.vb deleted file mode 100644 index ea85e9660d473..0000000000000 --- a/src/Features/Lsif/GeneratorTest/HoverTests.vb +++ /dev/null @@ -1,207 +0,0 @@ -' Licensed to the .NET Foundation under one or more agreements. -' The .NET Foundation licenses this file to you under the MIT license. -' See the LICENSE file in the project root for more information. - -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Roslyn.LanguageServer.Protocol - -Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests - - Public NotInheritable Class HoverTests - Private Const TestProjectAssemblyName As String = "TestProject" - - - - - - - - Doc Comment - void [|M|]() { } -}")> - Public Async Function TestDefinition(code As String) As Task - Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( - - FilePath="Z:\TestProject.csproj" CommonReferences="true"> - - <%= code %> - - - ) - - Dim rangeVertex = Await lsif.GetSelectedRangeAsync() - Dim resultSetVertex = lsif.GetLinkedVertices(Of Graph.ResultSet)(rangeVertex, "next").Single() - Dim hoverVertex = lsif.GetLinkedVertices(Of Graph.HoverResult)(resultSetVertex, Methods.TextDocumentHoverName).SingleOrDefault() - Dim hoverMarkupContent = DirectCast(hoverVertex.Result.Contents.Fourth, MarkupContent) - - Dim expectedHoverContents As String - Select Case code - Case "class [|C|] { string s; }" - expectedHoverContents = "```csharp -class C -``` - " - Case "class C { void [|M|]() { } }" - expectedHoverContents = "```csharp -void C.M() -``` - " - Case "class C { string [|s|]; }" - expectedHoverContents = $"```csharp -({FeaturesResources.field}) string C.s -``` - " - Case "class C { void M(string [|s|]) { M(s); } }" - expectedHoverContents = $"```csharp -({FeaturesResources.parameter}) string s -``` - " - Case "class C { void M(string s) { string [|local|] = """"; } }" - expectedHoverContents = $"```csharp -({FeaturesResources.local_variable}) string local -``` - " - Case " -class C -{ - /// Doc Comment - void [|M|]() { } -}" - expectedHoverContents = "```csharp -void C.M() -``` - -Doc Comment " - Case Else - Throw TestExceptionUtilities.UnexpectedValue(code) - End Select - - Assert.Equal(MarkupKind.Markdown, hoverMarkupContent.Kind) - Assert.Equal(expectedHoverContents + Environment.NewLine, hoverMarkupContent.Value) - End Function - - - - - - - - - - void M() { } -}")> - Public Async Function TestReference(code As String) As Task - Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( - - FilePath="Z:\TestProject.csproj" CommonReferences="true"> - - <%= code %> - - - ) - - Dim rangeVertex = Await lsif.GetSelectedRangeAsync() - Dim resultSetVertex = lsif.GetLinkedVertices(Of Graph.ResultSet)(rangeVertex, "next").Single() - Dim hoverVertex = lsif.GetLinkedVertices(Of Graph.HoverResult)(resultSetVertex, Methods.TextDocumentHoverName).SingleOrDefault() - Dim hoverMarkupContent = DirectCast(hoverVertex.Result.Contents.Fourth, MarkupContent) - - Dim expectedHoverContents As String - Select Case code - Case "class C { [|string|] s; }" - expectedHoverContents = "```csharp -class System.String -``` - " - Case "class C { void M() { [|M|](); } }" - expectedHoverContents = "```csharp -void C.M() -``` - " - Case "class C { void M(string s) { M([|s|]); } }" - expectedHoverContents = $"```csharp -({FeaturesResources.parameter}) string s -``` - " - Case "class C { void M(string s) { string local = """"; M([|local|]); } }" - expectedHoverContents = $"```csharp -({FeaturesResources.local_variable}) string local -``` - " - Case "using [|S|] = System.String;" - expectedHoverContents = "```csharp -class System.String -``` - " - Case "class C { [|global|]::System.String s; }" - expectedHoverContents = "```csharp - -``` - " - Case " -class C -{ - /// - void M() { } -}" - expectedHoverContents = "```csharp -void C.M() -``` - " - Case Else - Throw TestExceptionUtilities.UnexpectedValue(code) - End Select - - Assert.Equal(MarkupKind.Markdown, hoverMarkupContent.Kind) - Assert.Equal(expectedHoverContents + Environment.NewLine, hoverMarkupContent.Value) - End Function - - - Public Async Function ToplevelResultsInMultipleFiles() As Task - Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( - - FilePath="Z:\TestProject.csproj" CommonReferences="true"> - - class A { [|string|] s; } - - - class B { [|string|] s; } - - - class C { [|string|] s; } - - - class D { [|string|] s; } - - - class E { [|string|] s; } - - - ) - - Dim hoverVertex As Graph.HoverResult = Nothing - For Each rangeVertex In Await lsif.GetSelectedRangesAsync() - Dim resultSetVertex = lsif.GetLinkedVertices(Of Graph.ResultSet)(rangeVertex, "next").Single() - Dim vertex = lsif.GetLinkedVertices(Of Graph.HoverResult)(resultSetVertex, Methods.TextDocumentHoverName).Single() - If hoverVertex Is Nothing Then - hoverVertex = vertex - Else - Assert.Same(hoverVertex, vertex) - End If - Next - - Dim hoverMarkupContent = DirectCast(hoverVertex.Result.Contents.Fourth, MarkupContent) - Assert.Equal(MarkupKind.Markdown, hoverMarkupContent.Kind) - Assert.Equal("```csharp -class System.String -``` - " + Environment.NewLine, hoverMarkupContent.Value) - End Function - End Class -End Namespace diff --git a/src/Features/Lsif/GeneratorTest/LsifFormatLoggerTests.vb b/src/Features/Lsif/GeneratorTest/LsifFormatLoggerTests.vb deleted file mode 100644 index 221a623226b34..0000000000000 --- a/src/Features/Lsif/GeneratorTest/LsifFormatLoggerTests.vb +++ /dev/null @@ -1,35 +0,0 @@ -' Licensed to the .NET Foundation under one or more agreements. -' The .NET Foundation licenses this file to you under the MIT license. -' See the LICENSE file in the project root for more information. - -Imports System.IO -Imports Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Logging -Imports Microsoft.Extensions.Logging - -Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests - Public Class LsifFormatLoggerTests - - - - - - Public Sub TestSimpleMessage(logLevel As LogLevel, expectedSeverity As String) - Dim writer = New StringWriter - Dim logger = New LsifFormatLogger(writer) - - logger.Log(logLevel, "Test message") - - Assert.Equal("{""command"":""log"",""parameters"":{""severity"":""" + expectedSeverity + """,""message"":""Test message""}}", writer.ToString()) - End Sub - - - Public Sub TestException() - Dim writer = New StringWriter - Dim logger = New LsifFormatLogger(writer) - - logger.LogError(New Exception("Exception!"), "An exception was thrown") - - Assert.Equal("{""command"":""log"",""parameters"":{""severity"":""Error"",""message"":""An exception was thrown"",""exceptionMessage"":""Exception!"",""exceptionType"":""System.Exception""}}", writer.ToString()) - End Sub - End Class -End Namespace diff --git a/src/Features/Lsif/GeneratorTest/Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests.vbproj b/src/Features/Lsif/GeneratorTest/Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests.vbproj deleted file mode 100644 index db60f32e576d8..0000000000000 --- a/src/Features/Lsif/GeneratorTest/Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests.vbproj +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - net472 - Library - - UnitTest - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Features/Lsif/GeneratorTest/OutputFormatTests.vb b/src/Features/Lsif/GeneratorTest/OutputFormatTests.vb deleted file mode 100644 index bf8c20bd1e9ba..0000000000000 --- a/src/Features/Lsif/GeneratorTest/OutputFormatTests.vb +++ /dev/null @@ -1,287 +0,0 @@ -' Licensed to the .NET Foundation under one or more agreements. -' The .NET Foundation licenses this file to you under the MIT license. -' See the LICENSE file in the project root for more information. - -Imports System.IO -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Roslyn.Test.Utilities - -Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests - - Public NotInheritable Class OutputFormatTests - - Public Async Function TestLineModeOutput() As Task - Dim stringWriter = New StringWriter() - Dim jsonWriter = New LineModeLsifJsonWriter(stringWriter) - - Dim dir = "Z:\" & ChrW(&HE25B) - - Await TestLsifOutput.GenerateForWorkspaceAsync( - EditorTestWorkspace.CreateWorkspace( - - > - /> - - , openDocuments:=False, composition:=TestLsifOutput.TestComposition), jsonWriter) - - AssertEx.EqualOrDiff( -"{""hoverProvider"":true,""declarationProvider"":false,""definitionProvider"":true,""referencesProvider"":true,""typeDefinitionProvider"":false,""documentSymbolProvider"":true,""foldingRangeProvider"":true,""diagnosticProvider"":false,""semanticTokensProvider"":{""tokenTypes"":[""namespace"",""type"",""class"",""enum"",""interface"",""struct"",""typeParameter"",""parameter"",""variable"",""property"",""enumMember"",""event"",""function"",""method"",""macro"",""keyword"",""modifier"",""comment"",""string"",""number"",""regexp"",""operator"",""decorator"",""class name"",""constant name"",""delegate name"",""enum member name"",""enum name"",""event name"",""excluded code"",""extension method name"",""field name"",""interface name"",""json - array"",""json - comment"",""json - constructor name"",""json - keyword"",""json - number"",""json - object"",""json - operator"",""json - property name"",""json - punctuation"",""json - string"",""json - text"",""keyword - control"",""label name"",""local name"",""method name"",""module name"",""namespace name"",""operator - overloaded"",""parameter name"",""preprocessor keyword"",""preprocessor text"",""property name"",""punctuation"",""record class name"",""record struct name"",""regex - alternation"",""regex - anchor"",""regex - character class"",""regex - comment"",""regex - grouping"",""regex - other escape"",""regex - quantifier"",""regex - self escaped character"",""regex - text"",""roslyn test code markdown"",""string - escape character"",""string - verbatim"",""struct name"",""text"",""type parameter name"",""whitespace"",""xml doc comment - attribute name"",""xml doc comment - attribute quotes"",""xml doc comment - attribute value"",""xml doc comment - cdata section"",""xml doc comment - comment"",""xml doc comment - delimiter"",""xml doc comment - entity reference"",""xml doc comment - name"",""xml doc comment - processing instruction"",""xml doc comment - text"",""xml literal - attribute name"",""xml literal - attribute quotes"",""xml literal - attribute value"",""xml literal - cdata section"",""xml literal - comment"",""xml literal - delimiter"",""xml literal - embedded expression"",""xml literal - entity reference"",""xml literal - name"",""xml literal - processing instruction"",""xml literal - text""],""tokenModifiers"":[""static"",""deprecated""]},""id"":1,""type"":""vertex"",""label"":""capabilities""} -{""kind"":""csharp"",""resource"":""file:///Z:/%EE%89%9B/TestProject.csproj"",""name"":""TestProject"",""id"":2,""type"":""vertex"",""label"":""project""} -{""kind"":""begin"",""scope"":""project"",""data"":2,""id"":3,""type"":""vertex"",""label"":""$event""} -{""uri"":""file:///Z:/%EE%89%9B/a.cs"",""languageId"":""csharp"",""id"":4,""type"":""vertex"",""label"":""document""} -{""kind"":""begin"",""scope"":""document"",""data"":4,""id"":5,""type"":""vertex"",""label"":""$event""} -{""outV"":4,""inVs"":[],""id"":6,""type"":""edge"",""label"":""contains""} -{""result"":[],""id"":7,""type"":""vertex"",""label"":""foldingRangeResult""} -{""outV"":4,""inV"":7,""id"":8,""type"":""edge"",""label"":""textDocument/foldingRange""} -{""result"":{""data"":[]},""id"":9,""type"":""vertex"",""label"":""semanticTokensResult""} -{""outV"":4,""inV"":9,""id"":10,""type"":""edge"",""label"":""textDocument/semanticTokens/full""} -{""result"":[],""id"":11,""type"":""vertex"",""label"":""documentSymbolResult""} -{""outV"":4,""inV"":11,""id"":12,""type"":""edge"",""label"":""textDocument/documentSymbol""} -{""kind"":""end"",""scope"":""document"",""data"":4,""id"":13,""type"":""vertex"",""label"":""$event""} -{""outV"":2,""inVs"":[4],""id"":14,""type"":""edge"",""label"":""contains""} -{""kind"":""end"",""scope"":""project"",""data"":2,""id"":15,""type"":""vertex"",""label"":""$event""} -", stringWriter.ToString()) - End Function - - - Public Async Function TestJsonModeOutput() As Task - Dim stringWriter = New StringWriter() - Using jsonWriter = New JsonModeLsifJsonWriter(stringWriter) - - Await TestLsifOutput.GenerateForWorkspaceAsync( - EditorTestWorkspace.CreateWorkspace( - - - - - , openDocuments:=False, composition:=TestLsifOutput.TestComposition), jsonWriter) - End Using - - AssertEx.EqualOrDiff( - "[ - { - ""hoverProvider"": true, - ""declarationProvider"": false, - ""definitionProvider"": true, - ""referencesProvider"": true, - ""typeDefinitionProvider"": false, - ""documentSymbolProvider"": true, - ""foldingRangeProvider"": true, - ""diagnosticProvider"": false, - ""semanticTokensProvider"": { - ""tokenTypes"": [ - ""namespace"", - ""type"", - ""class"", - ""enum"", - ""interface"", - ""struct"", - ""typeParameter"", - ""parameter"", - ""variable"", - ""property"", - ""enumMember"", - ""event"", - ""function"", - ""method"", - ""macro"", - ""keyword"", - ""modifier"", - ""comment"", - ""string"", - ""number"", - ""regexp"", - ""operator"", - ""decorator"", - ""class name"", - ""constant name"", - ""delegate name"", - ""enum member name"", - ""enum name"", - ""event name"", - ""excluded code"", - ""extension method name"", - ""field name"", - ""interface name"", - ""json - array"", - ""json - comment"", - ""json - constructor name"", - ""json - keyword"", - ""json - number"", - ""json - object"", - ""json - operator"", - ""json - property name"", - ""json - punctuation"", - ""json - string"", - ""json - text"", - ""keyword - control"", - ""label name"", - ""local name"", - ""method name"", - ""module name"", - ""namespace name"", - ""operator - overloaded"", - ""parameter name"", - ""preprocessor keyword"", - ""preprocessor text"", - ""property name"", - ""punctuation"", - ""record class name"", - ""record struct name"", - ""regex - alternation"", - ""regex - anchor"", - ""regex - character class"", - ""regex - comment"", - ""regex - grouping"", - ""regex - other escape"", - ""regex - quantifier"", - ""regex - self escaped character"", - ""regex - text"", - ""roslyn test code markdown"", - ""string - escape character"", - ""string - verbatim"", - ""struct name"", - ""text"", - ""type parameter name"", - ""whitespace"", - ""xml doc comment - attribute name"", - ""xml doc comment - attribute quotes"", - ""xml doc comment - attribute value"", - ""xml doc comment - cdata section"", - ""xml doc comment - comment"", - ""xml doc comment - delimiter"", - ""xml doc comment - entity reference"", - ""xml doc comment - name"", - ""xml doc comment - processing instruction"", - ""xml doc comment - text"", - ""xml literal - attribute name"", - ""xml literal - attribute quotes"", - ""xml literal - attribute value"", - ""xml literal - cdata section"", - ""xml literal - comment"", - ""xml literal - delimiter"", - ""xml literal - embedded expression"", - ""xml literal - entity reference"", - ""xml literal - name"", - ""xml literal - processing instruction"", - ""xml literal - text"" - ], - ""tokenModifiers"": [ - ""static"", - ""deprecated"" - ] - }, - ""id"": 1, - ""type"": ""vertex"", - ""label"": ""capabilities"" - }, - { - ""kind"": ""csharp"", - ""resource"": ""file:///Z:/TestProject.csproj"", - ""name"": ""TestProject"", - ""id"": 2, - ""type"": ""vertex"", - ""label"": ""project"" - }, - { - ""kind"": ""begin"", - ""scope"": ""project"", - ""data"": 2, - ""id"": 3, - ""type"": ""vertex"", - ""label"": ""$event"" - }, - { - ""uri"": ""file:///Z:/A.cs"", - ""languageId"": ""csharp"", - ""id"": 4, - ""type"": ""vertex"", - ""label"": ""document"" - }, - { - ""kind"": ""begin"", - ""scope"": ""document"", - ""data"": 4, - ""id"": 5, - ""type"": ""vertex"", - ""label"": ""$event"" - }, - { - ""outV"": 4, - ""inVs"": [], - ""id"": 6, - ""type"": ""edge"", - ""label"": ""contains"" - }, - { - ""result"": [], - ""id"": 7, - ""type"": ""vertex"", - ""label"": ""foldingRangeResult"" - }, - { - ""outV"": 4, - ""inV"": 7, - ""id"": 8, - ""type"": ""edge"", - ""label"": ""textDocument/foldingRange"" - }, - { - ""result"": { - ""data"": [] - }, - ""id"": 9, - ""type"": ""vertex"", - ""label"": ""semanticTokensResult"" - }, - { - ""outV"": 4, - ""inV"": 9, - ""id"": 10, - ""type"": ""edge"", - ""label"": ""textDocument/semanticTokens/full"" - }, - { - ""result"": [], - ""id"": 11, - ""type"": ""vertex"", - ""label"": ""documentSymbolResult"" - }, - { - ""outV"": 4, - ""inV"": 11, - ""id"": 12, - ""type"": ""edge"", - ""label"": ""textDocument/documentSymbol"" - }, - { - ""kind"": ""end"", - ""scope"": ""document"", - ""data"": 4, - ""id"": 13, - ""type"": ""vertex"", - ""label"": ""$event"" - }, - { - ""outV"": 2, - ""inVs"": [ - 4 - ], - ""id"": 14, - ""type"": ""edge"", - ""label"": ""contains"" - }, - { - ""kind"": ""end"", - ""scope"": ""project"", - ""data"": 2, - ""id"": 15, - ""type"": ""vertex"", - ""label"": ""$event"" - } -]", stringWriter.ToString()) - End Function - End Class -End Namespace diff --git a/src/Features/Lsif/GeneratorTest/ProjectStructureTests.vb b/src/Features/Lsif/GeneratorTest/ProjectStructureTests.vb index 07854f60ea5c3..1348efb2fbee3 100644 --- a/src/Features/Lsif/GeneratorTest/ProjectStructureTests.vb +++ b/src/Features/Lsif/GeneratorTest/ProjectStructureTests.vb @@ -4,6 +4,7 @@ Imports System.IO Imports System.Text +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.LanguageServer Imports Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing Imports Microsoft.CodeAnalysis.Test.Utilities diff --git a/src/Features/Lsif/GeneratorTest/RangeResultSetTests.vb b/src/Features/Lsif/GeneratorTest/RangeResultSetTests.vb deleted file mode 100644 index 49cb55c5f5bf2..0000000000000 --- a/src/Features/Lsif/GeneratorTest/RangeResultSetTests.vb +++ /dev/null @@ -1,249 +0,0 @@ -' Licensed to the .NET Foundation under one or more agreements. -' The .NET Foundation licenses this file to you under the MIT license. -' See the LICENSE file in the project root for more information. - -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Roslyn.LanguageServer.Protocol -Imports Roslyn.Test.Utilities - -Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests - - Public NotInheritable Class RangeResultSetTests - Private Const TestProjectAssemblyName As String = "TestProject" - - - - - - - - - - ", WellKnownSymbolMonikerSchemes.DotnetNamespace)> - Public Async Function ReferenceMoniker(code As String, expectedMoniker As String, expectedMonikerScheme As String) As Task - Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( - - FilePath="Z:\TestProject.csproj" CommonReferences="true"> - - <%= code %> - - - ) - - Dim rangeVertex = Await lsif.GetSelectedRangeAsync() - Dim resultSetVertex = lsif.GetLinkedVertices(Of Graph.ResultSet)(rangeVertex, "next").Single() - Dim monikerVertex = lsif.GetLinkedVertices(Of Graph.Moniker)(resultSetVertex, "moniker").SingleOrDefault() - - Assert.Equal(expectedMoniker, monikerVertex?.Identifier) - Assert.Equal(expectedMonikerScheme, monikerVertex?.Scheme) - - If monikerVertex IsNot Nothing Then - Assert.Equal("scheme", monikerVertex.Unique) - End If - End Function - - - - - Public Async Function NoRangesAtAll(code As String) As Task - Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( - - FilePath="Z:\TestProject.csproj" CommonReferences="true"> - - <%= code %> - - ReferencedWithAlias - - - ) - - Assert.Empty(lsif.Vertices.OfType(Of Graph.Range)) - End Function - - - Public Async Function DefinitionIncludedInDefinitionResult() As Task - Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( - - FilePath="Z:\TestProject.csproj" CommonReferences="true"> - - class [|C|] { } - - - ) - - Dim rangeVertex = Await lsif.GetSelectedRangeAsync() - Dim resultSetVertex = lsif.GetLinkedVertices(Of Graph.ResultSet)(rangeVertex, "next").Single() - Dim definitionsVertex = lsif.GetLinkedVertices(Of Graph.DefinitionResult)(resultSetVertex, Methods.TextDocumentDefinitionName).Single() - - ' The definition vertex should point back to our range - Dim referencedRange = Assert.Single(lsif.GetLinkedVertices(Of Graph.Range)(definitionsVertex, "item")) - Assert.Same(rangeVertex, referencedRange) - End Function - - - Public Async Function ReferenceIncludedInReferenceResult() As Task - Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( - - FilePath="Z:\TestProject.csproj" CommonReferences="true"> - - class C { [|string|] s; } - - - ) - - Dim rangeVertex = Await lsif.GetSelectedRangeAsync() - Dim resultSetVertex = lsif.GetLinkedVertices(Of Graph.ResultSet)(rangeVertex, "next").Single() - Dim referencesVertex = lsif.GetLinkedVertices(Of Graph.ReferenceResult)(resultSetVertex, Methods.TextDocumentReferencesName).Single() - - ' The references vertex should point back to our range - Dim referencedRange = Assert.Single(lsif.GetLinkedVertices(Of Graph.Range)(referencesVertex, "item")) - Assert.Same(rangeVertex, referencedRange) - End Function - - - Public Async Function ReferenceIncludedInSameReferenceResultForMultipleFiles() As Task - Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( - - FilePath="Z:\TestProject.csproj" CommonReferences="true"> - - class A { [|string|] s; } - - - class B { [|string|] s; } - - - class C { [|string|] s; } - - - class D { [|string|] s; } - - - class E { [|string|] s; } - - - ) - - For Each rangeVertex In Await lsif.GetSelectedRangesAsync() - Dim resultSetVertex = lsif.GetLinkedVertices(Of Graph.ResultSet)(rangeVertex, "next").Single() - Dim referencesVertex = lsif.GetLinkedVertices(Of Graph.ReferenceResult)(resultSetVertex, Methods.TextDocumentReferencesName).Single() - - ' The references vertex should point back to our range - Dim referencedRanges = lsif.GetLinkedVertices(Of Graph.Range)(referencesVertex, "item") - Assert.Contains(rangeVertex, referencedRanges) - Next - End Function - - - ' case for built-in operators - - public void M2() { } - }")> ' case for crefs - Public Async Function NoCrossDocumentReferencesWithoutAMoniker(file1 As String, file2 As String) As Task - Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( - - FilePath="Z:\TestProject.csproj" CommonReferences="true"> - <%= file1 %> - <%= file2 %> - - ) - - ' If we ever emit a result set that doesn't have a moniker, some LSIF importers will make up a moniker - ' for us when they're importing, which can be based on the first range that they see. This is problematic if - ' the result set crosses multiple files, because there's no very stable moniker they can easily pick that won't - ' change if unrelated documents change. - For Each resultSetVertex In lsif.Vertices.OfType(Of Graph.ResultSet) - Dim monikerVertex = lsif.GetLinkedVertices(Of Graph.Moniker)(resultSetVertex, "moniker").SingleOrDefault() - - ' If it's got a moniker, then no concerns - If monikerVertex IsNot Nothing Then - Continue For - End If - - Dim documents As New HashSet(Of Graph.LsifDocument) - - ' Let's now enumerate all the documents and ranges to see which documents contain a range that links to - ' this resultSet - For Each document In lsif.Vertices.OfType(Of Graph.LsifDocument) - For Each range In lsif.GetLinkedVertices(Of Graph.Range)(document, "contains") - If lsif.GetLinkedVertices(Of Graph.ResultSet)(range, "next").Contains(resultSetVertex) Then - documents.Add(document) - End If - Next - Next - - If documents.Count > 0 Then - Assert.Single(documents) - End If - Next - End Function - - - Public Async Function InterfaceImplementation() As Task - Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( - - FilePath="Z:\TestProject.csproj" CommonReferences="true"> - -interface I { void {|Base:M|}(); } -class C : I { public void {|Implementation:M|}() { } } - - - ) - - Await AssertImplementationCorrectlyLinked(lsif) - End Function - - - Public Async Function [Overrides]() As Task - Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( - - FilePath="Z:\TestProject.csproj" CommonReferences="true"> - -class C { public virtual void {|Base:M|}() { } } -class D : C { public override void {|Implementation:M|}() { } } - - - ) - - Await AssertImplementationCorrectlyLinked(lsif) - End Function - - - Public Async Function OverridesAlwaysPointsToInitialVirtualMethod() As Task - Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( - - FilePath="Z:\TestProject.csproj" CommonReferences="true"> - -class C { public virtual void {|Base:M|}() { } } -class D : C { public override void {|Implementation:M|}() { } } -class E : D { public override void {|Implementation:M|}() { } } - - - ) - - Await AssertImplementationCorrectlyLinked(lsif) - End Function - - Private Shared Async Function AssertImplementationCorrectlyLinked(lsif As TestLsifOutput) As Task - Dim interfaceMethodRange = Await lsif.GetAnnotatedRangeAsync("Base") - Dim implementationRanges = Await lsif.GetAnnotatedRangesAsync("Implementation") - - ' The references vertex should have a definition items pointing ot the implementations - Dim resultSetVertex = lsif.GetLinkedVertices(Of Graph.ResultSet)(interfaceMethodRange, "next").Single() - Dim expectedMoniker = lsif.GetLinkedVertices(Of Graph.Moniker)(resultSetVertex, "moniker").Single() - Dim referencesVertex = lsif.GetLinkedVertices(Of Graph.ReferenceResult)(resultSetVertex, Methods.TextDocumentReferencesName).Single() - Dim definitionRangesForImplementingMethods = lsif.GetLinkedVertices(Of Graph.Range)(referencesVertex, Function(e) DirectCast(e, Graph.Item).Property = "definitions") - AssertEx.SetEqual(implementationRanges, definitionRangesForImplementingMethods) - - ' The result set for the implementation method should point to the moniker of the base - For Each implementationRange In implementationRanges - resultSetVertex = lsif.GetLinkedVertices(Of Graph.ResultSet)(implementationRange, "next").Single() - referencesVertex = lsif.GetLinkedVertices(Of Graph.ReferenceResult)(resultSetVertex, Methods.TextDocumentReferencesName).Single() - Dim moniker = lsif.GetLinkedVertices(Of Graph.Moniker)(referencesVertex, Function(e) DirectCast(e, Graph.Item).Property = "referenceLinks").Single() - Assert.Same(expectedMoniker, moniker) - Next - End Function - End Class -End Namespace diff --git a/src/Features/Lsif/GeneratorTest/SemanticTokensTests.vb b/src/Features/Lsif/GeneratorTest/SemanticTokensTests.vb deleted file mode 100644 index 445cdebfd6a2f..0000000000000 --- a/src/Features/Lsif/GeneratorTest/SemanticTokensTests.vb +++ /dev/null @@ -1,54 +0,0 @@ -' Licensed to the .NET Foundation under one or more agreements. -' The .NET Foundation licenses this file to you under the MIT license. -' See the LICENSE file in the project root for more information. - -Imports System.Linq -Imports System.Text.Json -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph -Imports Microsoft.CodeAnalysis.Test.Utilities - -Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests - - - Public NotInheritable Class SemanticTokensTests - Private Const TestProjectAssemblyName As String = "TestProject" - - - - - - - Public Async Function TestSemanticTokensData(code As String, expectedTokens As String) As Task - ' This test performs LSIF specific validation of the semantic tokens output. As of this writing - ' this feature is based on the same code path used to generate semantic tokens information in LSP - ' so it is assumed that exhaustive test coverage comes from that scenario. - ' - ' LSIF Cases of interest: - ' - Empty file - generates empty data - ' - Single line - ' - Multi-line - ' - Roslyn custom token type ('x' in 'int x' uses a Roslyn custom token type). - ' - Token in last line with no trailing newline (ensure sufficient range was passed to LSP generator). - - Using semanticTokensWorkspace = EditorTestWorkspace.CreateWorkspace( - - FilePath="Z:\TestProject.csproj" CommonReferences="true"> - - <%= code %> - - - , openDocuments:=False, composition:=TestLsifOutput.TestComposition) - - Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync(semanticTokensWorkspace) - Dim document = semanticTokensWorkspace.CurrentSolution.Projects.Single().Documents.Single() - - Dim tokens = lsif.GetSemanticTokens(document) - Dim serializedTokens = JsonSerializer.Serialize(tokens) - - Assert.Equal(expectedTokens, serializedTokens) - End Using - End Function - End Class - -End Namespace diff --git a/src/Features/Lsif/GeneratorTest/Utilities/TestLsifJsonWriter.vb b/src/Features/Lsif/GeneratorTest/Utilities/TestLsifJsonWriter.vb deleted file mode 100644 index ac8cf92577a13..0000000000000 --- a/src/Features/Lsif/GeneratorTest/Utilities/TestLsifJsonWriter.vb +++ /dev/null @@ -1,115 +0,0 @@ -' Licensed to the .NET Foundation under one or more agreements. -' The .NET Foundation licenses this file to you under the MIT license. -' See the LICENSE file in the project root for more information. - -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph -Imports Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing - -Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests.Utilities - ''' - ''' A implementation of for use in unit tests. It does additional validation of the - ''' correctness of the output, And stores the entire output And offers useful helpers to inspect the result. - ''' - Friend Class TestLsifJsonWriter - Implements ILsifJsonWriter - - Private ReadOnly _gate As Object = New Object() - Private ReadOnly _elementsById As Dictionary(Of Id(Of Element), Element) = New Dictionary(Of Id(Of Element), Element) - Private ReadOnly _edgesByOutVertex As Dictionary(Of Vertex, List(Of Edge)) = New Dictionary(Of Vertex, List(Of Edge)) - - Private Sub ILsifJsonWriter_WriteAll(elements As List(Of Element)) Implements ILsifJsonWriter.WriteAll - For Each element In elements - ILsifJsonWriter_Write(element) - Next - End Sub - - Private Sub ILsifJsonWriter_Write(element As Element) Implements ILsifJsonWriter.Write - SyncLock _gate - ' We intentionally use Add so it'll throw if we have a duplicate ID. - _elementsById.Add(element.Id, element) - - Dim edge = TryCast(element, Edge) - - If edge IsNot Nothing Then - ' Fetch all the out And in vertices, which validates they exist. This ensures we satisfy the rule - ' that an edge can only be written after all the vertices it writes to already exist. - Dim outVertex = GetElementById(edge.OutVertex) - - For Each inVertexId In edge.GetInVerticies() - ' We are ignoring the return, but this call implicitly validates the element - ' exists and is of the correct type. - GetElementById(inVertexId) - Next - - ' Record the edge in a map of edges exiting this outVertex. We could do a nested Dictionary - ' for this but that seems a bit expensive when many nodes may only have one item. - Dim edgesForOutVertex As List(Of Edge) = Nothing - If Not _edgesByOutVertex.TryGetValue(outVertex, edgesForOutVertex) Then - edgesForOutVertex = New List(Of Edge)(capacity:=1) - _edgesByOutVertex.Add(outVertex, edgesForOutVertex) - End If - - ' It's possible to have more than one item edge, but for anything else we really only expect one. - If edge.Label <> "item" Then - If (edgesForOutVertex.Any(Function(e) e.Label = edge.Label)) Then - Throw New InvalidOperationException($"The outVertex {outVertex} already has an edge with label {edge.Label}.") - End If - End If - - edgesForOutVertex.Add(edge) - End If - End SyncLock - End Sub - - ''' - ''' Returns all the vertices linked to the given vertex by the edge type. - ''' - Public Function GetLinkedVertices(Of T As Vertex)(vertex As Graph.Vertex, edgeLabel As String) As ImmutableArray(Of T) - Return GetLinkedVertices(Of T)(vertex, Function(e) e.Label = edgeLabel) - End Function - - ''' - ''' Returns all the vertices linked to the given vertex by the edge predicate. - ''' - Public Function GetLinkedVertices(Of T As Vertex)(vertex As Graph.Vertex, predicate As Func(Of Edge, Boolean)) As ImmutableArray(Of T) - SyncLock _gate - Dim builder = ImmutableArray.CreateBuilder(Of T) - - Dim edges As List(Of Edge) = Nothing - If _edgesByOutVertex.TryGetValue(vertex, edges) Then - Dim inVerticesId = edges.Where(predicate).SelectMany(Function(e) e.GetInVerticies()) - - For Each inVertexId In inVerticesId - ' This is an unsafe "cast" if you will converting the ID to the expected type; - ' GetElementById checks the real vertex type so thta will stay safe in the end. - builder.Add(GetElementById(Of T)(New Id(Of T)(inVertexId.NumericId))) - Next - End If - - Return builder.ToImmutable() - End SyncLock - End Function - - Public ReadOnly Property Vertices As ImmutableArray(Of Vertex) - Get - SyncLock _gate - Return _elementsById.Values.OfType(Of Vertex).ToImmutableArray() - End SyncLock - End Get - End Property - - Public Function GetElementById(Of T As Element)(id As Id(Of T)) As T - SyncLock _gate - Dim element As Element = Nothing - - ' TODO: why am I unable to use the extension method As here? - If Not _elementsById.TryGetValue(New Id(Of Element)(id.NumericId), element) Then - Throw New Exception($"Element {id} could not be found.") - End If - - Return Assert.IsAssignableFrom(Of T)(element) - End SyncLock - End Function - End Class -End Namespace diff --git a/src/Features/Lsif/GeneratorTest/Utilities/TestLsifOutput.vb b/src/Features/Lsif/GeneratorTest/Utilities/TestLsifOutput.vb deleted file mode 100644 index c058f5fa0309d..0000000000000 --- a/src/Features/Lsif/GeneratorTest/Utilities/TestLsifOutput.vb +++ /dev/null @@ -1,184 +0,0 @@ -' Licensed to the .NET Foundation under one or more agreements. -' The .NET Foundation licenses this file to you under the MIT license. -' See the LICENSE file in the project root for more information. - -Imports System.Collections.Concurrent -Imports System.Collections.Immutable -Imports System.Threading -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.LanguageServer -Imports Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph -Imports Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing -Imports Microsoft.CodeAnalysis.Shared.Extensions -Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.Extensions.Logging -Imports Roslyn.Utilities -Imports LSP = Roslyn.LanguageServer.Protocol - -Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests.Utilities - Friend Class TestLsifOutput - Private ReadOnly _testLsifJsonWriter As TestLsifJsonWriter - Private ReadOnly _workspace As EditorTestWorkspace - - ''' - ''' A MEF composition that matches the exact same MEF composition that will be used in the actual LSIF tool. - ''' - Public Shared ReadOnly TestComposition As TestComposition = TestComposition.Empty.AddAssemblies(Composition.MefCompositionAssemblies) - - Public Sub New(testLsifJsonWriter As TestLsifJsonWriter, workspace As EditorTestWorkspace) - _testLsifJsonWriter = testLsifJsonWriter - _workspace = workspace - End Sub - - Public Shared Function GenerateForWorkspaceAsync(workspaceElement As XElement) As Task(Of TestLsifOutput) - Dim workspace = EditorTestWorkspace.CreateWorkspace(workspaceElement, openDocuments:=False, composition:=TestComposition) - Return GenerateForWorkspaceAsync(workspace) - End Function - - Public Shared Async Function GenerateForWorkspaceAsync(workspace As EditorTestWorkspace) As Task(Of TestLsifOutput) - Dim testLsifJsonWriter = New TestLsifJsonWriter() - - Await GenerateForWorkspaceAsync(workspace, testLsifJsonWriter) - - Return New TestLsifOutput(testLsifJsonWriter, workspace) - End Function - - Public Shared Async Function GenerateForWorkspaceAsync(workspace As EditorTestWorkspace, jsonWriter As ILsifJsonWriter) As Task - ' We always want to assert that we're running with the correct composition, or otherwise the test doesn't reflect the real - ' world function of the indexer. - Assert.Equal(workspace.Composition, TestComposition) - - Dim logger = New TestLogger() - Dim lsifGenerator = Generator.CreateAndWriteCapabilitiesVertex(jsonWriter, logger) - - For Each project In workspace.CurrentSolution.Projects - Dim compilation = Await project.GetCompilationAsync() - - ' Assert we don't have any errors to prevent any typos in the tests - Assert.Empty(compilation.GetDiagnostics().Where(Function(d) d.Severity = DiagnosticSeverity.Error)) - - Await lsifGenerator.GenerateForProjectAsync(project, GeneratorOptions.Default, CancellationToken.None) - Next - - ' The only things would have logged were an error, so this should be empty - Assert.Empty(logger.LoggedMessages) - End Function - - Private Class TestLogger - Implements ILogger - - Public ReadOnly LoggedMessages As New ConcurrentBag(Of String) - - Public Sub Log(Of TState)(logLevel As LogLevel, eventId As EventId, state As TState, exception As Exception, formatter As Func(Of TState, Exception, String)) Implements ILogger.Log - Dim message = formatter(state, exception) - LoggedMessages.Add(message) - End Sub - - Public Function IsEnabled(logLevel As LogLevel) As Boolean Implements ILogger.IsEnabled - Return True - End Function - - Public Function BeginScope(Of TState)(state As TState) As IDisposable Implements ILogger.BeginScope - Throw New NotImplementedException() - End Function - End Class - - Public Function GetElementById(Of T As Element)(id As Id(Of T)) As T - Return _testLsifJsonWriter.GetElementById(id) - End Function - - Public Function GetLinkedVertices(Of T As Vertex)(vertex As Graph.Vertex, predicate As Func(Of Edge, Boolean)) As ImmutableArray(Of T) - Return _testLsifJsonWriter.GetLinkedVertices(Of T)(vertex, predicate) - End Function - - ''' - ''' Returns all the vertices linked to the given vertex by the edge type. - ''' - Public Function GetLinkedVertices(Of T As Vertex)(vertex As Graph.Vertex, edgeLabel As String) As ImmutableArray(Of T) - Return _testLsifJsonWriter.GetLinkedVertices(Of T)(vertex, edgeLabel) - End Function - - Public ReadOnly Property Vertices As IEnumerable(Of Vertex) - Get - Return _testLsifJsonWriter.Vertices - End Get - End Property - - Private Async Function GetRangesAsync(selector As Func(Of TestHostDocument, IEnumerable(Of TextSpan))) As Task(Of IEnumerable(Of Graph.Range)) - Dim builder = ImmutableArray.CreateBuilder(Of Range) - - For Each testDocument In _workspace.Documents - Dim documentVertex = _testLsifJsonWriter.Vertices _ - .OfType(Of Graph.LsifDocument) _ - .Where(Function(d) d.Uri.LocalPath = testDocument.FilePath) _ - .Single() - Dim rangeVertices = GetLinkedVertices(Of Range)(documentVertex, "contains") - - For Each selectedSpan In selector(testDocument) - Dim document = _workspace.CurrentSolution.GetDocument(testDocument.Id) - Dim text = Await document.GetTextAsync() - Dim linePositionSpan = text.Lines.GetLinePositionSpan(selectedSpan) - Dim positionStart = Range.ConvertLinePositionToPosition(linePositionSpan.Start) - Dim positionEnd = Range.ConvertLinePositionToPosition(linePositionSpan.End) - - builder.Add(rangeVertices.Where(Function(r) r.Start = positionStart AndAlso - r.End = positionEnd) _ - .Single()) - Next - Next - - Return builder.ToImmutable() - End Function - - ''' - ''' Returns the vertices in the output that corresponds to the selected range in the . - ''' - Public Function GetSelectedRangesAsync() As Task(Of IEnumerable(Of Graph.Range)) - Return GetRangesAsync(Function(testDocument) testDocument.SelectedSpans) - End Function - - Public Async Function GetSelectedRangeAsync() As Task(Of Graph.Range) - Return (Await GetSelectedRangesAsync()).Single() - End Function - - Public Function GetAnnotatedRangesAsync(annotation As String) As Task(Of IEnumerable(Of Graph.Range)) - Return GetRangesAsync(Function(testDocument) testDocument.AnnotatedSpans.GetValueOrDefault(annotation)) - End Function - - Public Async Function GetAnnotatedRangeAsync(annotation As String) As Task(Of Graph.Range) - Return (Await GetAnnotatedRangesAsync(annotation)).Single() - End Function - - ''' - ''' Returns an LSP Range type for the text span annotated with the given name. This is distinct from returning an LSIF Range vertex, which is what does. - ''' - Public Async Function GetAnnotatedLspRangeAsync(annotation As String) As Task(Of LSP.Range) - Dim annotatedDocument = _workspace.Documents.Single(Function(d) d.AnnotatedSpans.ContainsKey(annotation)) - Dim annotatedSpan = annotatedDocument.AnnotatedSpans(annotation).Single() - - Dim text = Await _workspace.CurrentSolution.GetRequiredDocument(annotatedDocument.Id).GetTextAsync() - Dim linePositionSpan = text.Lines.GetLinePositionSpan(annotatedSpan) - Return ProtocolConversions.LinePositionToRange(linePositionSpan) - End Function - - Public Function GetFoldingRanges(document As Document) As LSP.FoldingRange() - Dim documentVertex = _testLsifJsonWriter.Vertices. - OfType(Of LsifDocument). - Where(Function(d) d.Uri.LocalPath = document.FilePath). - Single() - Dim foldingRangeVertex = GetLinkedVertices(Of FoldingRangeResult)(documentVertex, "textDocument/foldingRange").Single() - Return foldingRangeVertex.Result - End Function - - Public Function GetSemanticTokens(document As Document) As LSP.SemanticTokens - Dim documentVertex = _testLsifJsonWriter.Vertices. - OfType(Of LsifDocument). - Where(Function(d) d.Uri.LocalPath = document.FilePath). - Single() - - Dim semanticTokensVertex = GetLinkedVertices(Of SemanticTokensResult)(documentVertex, "textDocument/semanticTokens/full").Single() - Return semanticTokensVertex.Result - End Function - End Class -End Namespace diff --git a/src/Features/Test/EditAndContinue/ActiveStatementsMapTests.cs b/src/Features/Test/EditAndContinue/ActiveStatementsMapTests.cs index 611af807d139b..204ee9b1f5f12 100644 --- a/src/Features/Test/EditAndContinue/ActiveStatementsMapTests.cs +++ b/src/Features/Test/EditAndContinue/ActiveStatementsMapTests.cs @@ -92,26 +92,28 @@ public async Task Ordering() { using var workspace = new TestWorkspace(composition: FeaturesTestCompositions.Features); - var source = @" -class C -{ - void F() - { -#line 2 ""x"" -S1(); -S2(); -S3(); -#line 1 ""x"" -S0(); -S1(); -S2(); -#line 5 ""x"" -S4(); -S5(); -S5(); -#line default - } -}"; + var source = """ + + class C + { + void F() + { + #line 2 "x" + S1(); + S2(); + S3(); + #line 1 "x" + S0(); + S1(); + S2(); + #line 5 "x" + S4(); + S5(); + S5(); + #line default + } + } + """; var solution = workspace.CurrentSolution .AddProject("proj", "proj", LanguageNames.CSharp) @@ -159,14 +161,16 @@ public async Task InvalidActiveStatements() { using var workspace = new TestWorkspace(composition: FeaturesTestCompositions.Features); - var source = @" -class C -{ - void F() - { -S1(); - } -}"; + var source = """ + + class C + { + void F() + { + S1(); + } + } + """; var solution = workspace.CurrentSolution .AddProject("proj", "proj", LanguageNames.CSharp) @@ -200,24 +204,26 @@ public void ExpandMultiLineSpan() { using var workspace = new TestWorkspace(composition: FeaturesTestCompositions.Features); - var source = @" -using System; + var source = """ -class C -{ - void F() - { - G(x => x switch - { - _ => 0, - }); - } + using System; - static void G(Func a) - { - a(1); - } -}"; + class C + { + void F() + { + G(x => x switch + { + _ => 0, + }); + } + + static void G(Func a) + { + a(1); + } + } + """; var solution = workspace.CurrentSolution .AddProject("proj", "proj", LanguageNames.CSharp) @@ -266,22 +272,24 @@ SourceFileSpan Span(int startLine, int startColumn, int endLine, int endColumn) public void NonRemappableRegionOrdering(bool reverse) { var source1 = -@"class C -{ - static void M() - { - try - { - } - catch - { - - - - M(); - } - } -}"; + """ + class C + { + static void M() + { + try + { + } + catch + { + + + + M(); + } + } + } + """; var unmappedActiveStatements = GetUnmappedActiveStatementsCSharp( [source1], flags: [ActiveStatementFlags.LeafFrame]); @@ -315,13 +323,15 @@ static void M() public void SubSpan(bool reverse) { var source1 = -@"class C -{ - static void M() - { - var x = y switch { 1 => 0, _ => 1 }; - } -}"; + """ + class C + { + static void M() + { + var x = y switch { 1 => 0, _ => 1 }; + } + } + """; var unmappedActiveStatements = GetUnmappedActiveStatementsCSharp( [source1], flags: [ActiveStatementFlags.LeafFrame, ActiveStatementFlags.LeafFrame]); diff --git a/src/Features/Test/EditAndContinue/CompileTimeSolutionProviderTests.cs b/src/Features/Test/EditAndContinue/CompileTimeSolutionProviderTests.cs index 3ec85b5262ca9..3445b1f1c688b 100644 --- a/src/Features/Test/EditAndContinue/CompileTimeSolutionProviderTests.cs +++ b/src/Features/Test/EditAndContinue/CompileTimeSolutionProviderTests.cs @@ -105,9 +105,6 @@ public async Task GeneratorOutputCachedBetweenAcrossCompileTimeSolutions() var analyzerConfigId = DocumentId.CreateNewId(projectId); var additionalDocumentId = DocumentId.CreateNewId(projectId); - - var analyzerConfigText = "is_global = true\r\nbuild_property.SuppressRazorSourceGenerator = true"; - workspace.SetCurrentSolution(s => s .AddProject(ProjectInfo.Create(projectId, VersionStamp.Default, "proj", "proj", LanguageNames.CSharp)) .WithProjectCompilationOutputInfo(projectId, new CompilationOutputInfo( @@ -115,7 +112,7 @@ public async Task GeneratorOutputCachedBetweenAcrossCompileTimeSolutions() generatedFilesOutputDirectory: null)) .AddAnalyzerReference(projectId, new TestGeneratorReference(generator)) .AddAdditionalDocument(additionalDocumentId, "additional", SourceText.From(""), filePath: "additional.razor") - .AddAnalyzerConfigDocument(analyzerConfigId, "config", SourceText.From(analyzerConfigText), filePath: "Z:\\RazorSourceGenerator.razorencconfig"), + .AddAnalyzerConfigDocument(analyzerConfigId, "config", SourceText.From("is_global = true\r\nbuild_property.SuppressRazorSourceGenerator = true"), filePath: "Z:\\RazorSourceGenerator.razorencconfig"), WorkspaceChangeKind.SolutionAdded); // Fetch a compilation first for the base solution; we're doing this because currently if we try to move the diff --git a/src/Features/Test/EditAndContinue/EditAndContinueDiagnosticDescriptorsTests.cs b/src/Features/Test/EditAndContinue/EditAndContinueDiagnosticDescriptorsTests.cs index f174069ae4d15..404dbb89f2106 100644 --- a/src/Features/Test/EditAndContinue/EditAndContinueDiagnosticDescriptorsTests.cs +++ b/src/Features/Test/EditAndContinue/EditAndContinueDiagnosticDescriptorsTests.cs @@ -6,8 +6,8 @@ using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; -using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Contracts.EditAndContinue; +using Microsoft.CodeAnalysis.Diagnostics; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests; diff --git a/src/Features/Test/EditAndContinue/EditAndContinueMethodDebugInfoReaderTests.cs b/src/Features/Test/EditAndContinue/EditAndContinueMethodDebugInfoReaderTests.cs index 87d2fe3c387b5..d6f61a735cca2 100644 --- a/src/Features/Test/EditAndContinue/EditAndContinueMethodDebugInfoReaderTests.cs +++ b/src/Features/Test/EditAndContinue/EditAndContinueMethodDebugInfoReaderTests.cs @@ -47,19 +47,21 @@ public void Create_Errors() [InlineData(DebugInformationFormat.Pdb, true)] public void DebugInfo(DebugInformationFormat format, bool useSymReader) { - var source = @" -using System; -delegate void D(); -class C -{ - public static void Main() - { - int x = 1; - D d = () => Console.Write(x); - d(); - } -} -"; + var source = """ + + using System; + delegate void D(); + class C + { + public static void Main() + { + int x = 1; + D d = () => Console.Write(x); + d(); + } + } + + """; var tree = CSharpTestSource.Parse(source, path: "/a/c.cs", options: TestOptions.Regular.WithNoRefSafetyRulesAttribute(), checksumAlgorithm: SourceHashAlgorithm.Sha1); var compilation = CSharpTestBase.CreateCompilationWithMscorlib40AndSystemCore(tree, options: TestOptions.DebugDll); diff --git a/src/Features/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs b/src/Features/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs index aee2f7829455a..e0273bb6ac70e 100644 --- a/src/Features/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs +++ b/src/Features/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs @@ -48,8 +48,6 @@ public async Task StartDebuggingSession_CapturingDocuments(bool captureAllDocume var sourceA1 = "class A {}"; var sourceB1 = "class B { int F() => 1; }"; - var sourceB2 = "class B { int F() => 2; }"; - var sourceB3 = "class B { int F() => 3; }"; var sourceC1 = "class C { const char L = 'ワ'; }"; var sourceD1 = "dummy code"; var sourceE1 = "class E { }"; @@ -76,7 +74,7 @@ public async Task StartDebuggingSession_CapturingDocuments(bool captureAllDocume EmitLibrary(projectPId, compilation); // change content of B on disk: - sourceFileB.WriteAllText(sourceB2, encodingB); + sourceFileB.WriteAllText("class B { int F() => 2; }", encodingB); // prepare workspace as if it was loaded from project files: using var _ = CreateWorkspace(out var solution, out var service, [typeof(NoCompilationLanguageService)]); @@ -149,7 +147,7 @@ public async Task StartDebuggingSession_CapturingDocuments(bool captureAllDocume ], matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); // change content of B on disk again: - sourceFileB.WriteAllText(sourceB3, encodingB); + sourceFileB.WriteAllText("class B { int F() => 3; }", encodingB); solution = solution.WithDocumentTextLoader(documentIdB, new WorkspaceFileTextLoader(solution.Services, sourceFileB.Path, encodingB), PreservationMode.PreserveValue); EnterBreakState(debuggingSession); @@ -268,22 +266,14 @@ public async Task ProjectThatDoesNotSupportEnC(bool breakMode) [Fact] public async Task ProjectWithoutEffectiveGeneratedFilesOutputDirectory() { - var sourceV1 = """ - /* GENERATE: class G { int F(int x) => 1; } */ - - class C { int Y => 1; } - """; - - var sourceV2 = """ - /* GENERATE: class G { int F() => 1; } */ - - class C { int Y => 2; } - """; - var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); - (solution, var document) = AddDefaultTestProject(solution, sourceV1, generator: generator); + (solution, var document) = AddDefaultTestProject(solution, """ + /* GENERATE: class G { int F(int x) => 1; } */ + + class C { int Y => 1; } + """, generator: generator); solution = solution.WithProjectCompilationOutputInfo(document.Project.Id, new CompilationOutputInfo(assemblyPath: null, generatedFilesOutputDirectory: null)); var debuggingSession = await StartDebuggingSessionAsync(service, solution); @@ -291,7 +281,11 @@ class C { int Y => 2; } // change the source: var document1 = solution.Projects.Single().Documents.Single(); - solution = solution.WithDocumentText(document1.Id, CreateText(sourceV2)); + solution = solution.WithDocumentText(document1.Id, CreateText(""" + /* GENERATE: class G { int F() => 1; } */ + + class C { int Y => 2; } + """)); var generatedDocument = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync()).Single(); @@ -497,11 +491,10 @@ public async Task ErrorReadingModuleFile(bool breakMode) expectedErrorMessage = e.Message; } - var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; using var _w = CreateWorkspace(out var solution, out var service); - (solution, var document1) = AddDefaultTestProject(solution, source1); + (solution, var document1) = AddDefaultTestProject(solution, "class C { void M() { System.Console.WriteLine(1); } }"); var projectId = document1.Project.Id; _mockCompilationOutputs.Add(projectId, new CompilationOutputFiles(moduleFile.Path)); @@ -914,32 +907,21 @@ public async Task ModuleDisallowsEditAndContinue_SourceGenerator_NoChanges() public async Task ModuleDisallowsEditAndContinue() { var moduleId = Guid.NewGuid(); - - var source1 = @" -class C1 -{ - void M() - { - System.Console.WriteLine(1); - System.Console.WriteLine(2); - System.Console.WriteLine(3); - } -}"; - var source2 = @" -class C1 -{ - void M() - { - System.Console.WriteLine(9); - System.Console.WriteLine(); - System.Console.WriteLine(30); - } -}"; - var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); - (solution, var document) = AddDefaultTestProject(solution, source1, generator: generator); + (solution, var document) = AddDefaultTestProject(solution, """ + + class C1 + { + void M() + { + System.Console.WriteLine(1); + System.Console.WriteLine(2); + System.Console.WriteLine(3); + } + } + """, generator: generator); _mockCompilationOutputs.Add(document.Project.Id, new MockCompilationOutputs(moduleId)); @@ -951,7 +933,18 @@ void M() // change the source: var document1 = solution.Projects.Single().Documents.Single(); - solution = solution.WithDocumentText(document1.Id, CreateText(source2)); + solution = solution.WithDocumentText(document1.Id, CreateText(""" + + class C1 + { + void M() + { + System.Console.WriteLine(9); + System.Console.WriteLine(); + System.Console.WriteLine(30); + } + } + """)); var document2 = solution.GetDocument(document1.Id); // We do not report module diagnostics until emit. @@ -1034,13 +1027,10 @@ public async Task Encodings() [Theory, CombinatorialData] public async Task RudeEdits(bool breakMode) { - var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; - var source2 = "class C1 { void M() { System.Console.WriteLine(1); } }"; - var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); - (solution, var document) = AddDefaultTestProject(solution, source1); + (solution, var document) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputs.Add(document.Project.Id, new MockCompilationOutputs(moduleId)); @@ -1053,7 +1043,7 @@ public async Task RudeEdits(bool breakMode) // change the source (rude edit): var document1 = solution.Projects.Single().Documents.Single(); - solution = solution.WithDocumentText(document1.Id, CreateText(source2)); + solution = solution.WithDocumentText(document1.Id, CreateText("class C1 { void M() { System.Console.WriteLine(1); } }")); var document2 = solution.GetDocument(document1.Id); var docDiagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); @@ -1170,21 +1160,16 @@ public async Task DeferredApplyChangeWithActiveStatementRudeEdits() [Fact] public async Task RudeEdits_SourceGenerators() { - var sourceV1 = @" -/* GENERATE: class G { int X1() => 1; } */ + var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; -class C { int Y => 1; } -"; - var sourceV2 = @" -/* GENERATE: class G { int X1() => 1; } */ + using var _ = CreateWorkspace(out var solution, out var service); + (solution, var document) = AddDefaultTestProject(solution, """ -class C { int Y => 2; } -"; + /* GENERATE: class G { int X1() => 1; } */ - var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; + class C { int Y => 1; } - using var _ = CreateWorkspace(out var solution, out var service); - (solution, var document) = AddDefaultTestProject(solution, sourceV1, generator: generator); + """, generator: generator); // mock project build: _mockCompilationOutputs.Add(document.Project.Id, new MockCompilationOutputs(Guid.NewGuid())); @@ -1194,7 +1179,13 @@ class C { int Y => 2; } // change the source: var document1 = solution.Projects.Single().Documents.Single(); - solution = solution.WithDocumentText(document1.Id, CreateText(sourceV2)); + solution = solution.WithDocumentText(document1.Id, CreateText(""" + + /* GENERATE: class G { int X1() => 1; } */ + + class C { int Y => 2; } + + """)); var generatedDocument = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync()).Single(); @@ -1216,8 +1207,6 @@ public async Task RudeEdits_DocumentOutOfSync(bool breakMode) { var source0 = "class C1 { void M() { System.Console.WriteLine(0); } }"; var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; - var source2 = "class C1 { void M() { System.Console.WriteLine(1); } }"; - var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs"); @@ -1246,7 +1235,7 @@ public async Task RudeEdits_DocumentOutOfSync(bool breakMode) } // change the source (rude edit): - solution = solution.WithDocumentText(documentId, CreateText(source2)); + solution = solution.WithDocumentText(documentId, CreateText("class C1 { void M() { System.Console.WriteLine(1); } }")); var document2 = solution.GetDocument(documentId); // no Rude Edits, since the document is out-of-sync @@ -1423,15 +1412,11 @@ public async Task RudeEdits_DelayLoadedModule() [CombinatorialData] public async Task RudeEdits_UpdateBaseline(bool validChangeBeforeRudeEdit, bool allowPartialUpdates) { - var source1 = "abstract class C { }"; - var source2 = "abstract class C { void F() {} }"; var source3 = "abstract class C { void F() {} public abstract void G(); }"; - var source4 = "abstract class C { void F() {} public abstract void G(); void H() {} }"; - var projectDir = Temp.CreateDirectory(); using var _ = CreateWorkspace(out var solution, out var service); - (solution, var document) = AddDefaultTestProject(solution, source1, projectDir); + (solution, var document) = AddDefaultTestProject(solution, "abstract class C { }", projectDir); var documentId = document.Id; var projectId = document.Project.Id; @@ -1446,7 +1431,7 @@ public async Task RudeEdits_UpdateBaseline(bool validChangeBeforeRudeEdit, bool // change the source (valid edit): if (validChangeBeforeRudeEdit) { - solution = solution.WithDocumentText(documentId, CreateText(source2)); + solution = solution.WithDocumentText(documentId, CreateText("abstract class C { void F() {} }")); results = await EmitSolutionUpdateAsync(debuggingSession, solution, allowPartialUpdates); Assert.Equal(ModuleUpdateStatus.Ready, results.ModuleUpdates.Status); @@ -1513,7 +1498,7 @@ public async Task RudeEdits_UpdateBaseline(bool validChangeBeforeRudeEdit, bool Assert.Empty(await service.GetDocumentDiagnosticsAsync(solution.GetRequiredDocument(documentId), s_noActiveSpans, CancellationToken.None)); // change the source (valid edit): - solution = solution.WithDocumentText(documentId, CreateText(source4)); + solution = solution.WithDocumentText(documentId, CreateText("abstract class C { void F() {} public abstract void G(); void H() {} }")); // no rude edits: Assert.Empty(await service.GetDocumentDiagnosticsAsync(solution.GetRequiredDocument(documentId), s_noActiveSpans, CancellationToken.None)); @@ -1978,8 +1963,6 @@ public async Task Project_Add() // Additional documents added to B: var sourceB2 = "class B { int G() => 1; }"; - var sourceB3 = "class B { int F() => 2; }"; - var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("a.cs").WriteAllText(sourceA1, Encoding.UTF8); var sourceFileB = dir.CreateFile("b.cs").WriteAllText(sourceB1, Encoding.UTF8); @@ -2048,7 +2031,7 @@ public async Task Project_Add() Assert.Empty(diagnostics); // update document with a valid change: - solution = solution.WithDocumentText(documentB2.Id, CreateText(sourceB3)); + solution = solution.WithDocumentText(documentB2.Id, CreateText("class B { int F() => 2; }")); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); @@ -2065,8 +2048,6 @@ public async Task Project_Add() public async Task Capabilities(bool breakState) { var source1 = "class C { void M() { } }"; - var source2 = "[System.Obsolete]class C { void M() { } }"; - using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, [source1]); var documentId = solution.Projects.Single().Documents.Single().Id; @@ -2080,7 +2061,7 @@ public async Task Capabilities(bool breakState) var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update document: - solution = solution.WithDocumentText(documentId, CreateText(source2)); + solution = solution.WithDocumentText(documentId, CreateText("[System.Obsolete]class C { void M() { } }")); var diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); @@ -2154,30 +2135,19 @@ public async Task Capabilities(bool breakState) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56431")] public async Task Capabilities_NoTypesEmitted() { - var sourceV1 = @" -/* GENERATE: -class G -{ - int M() - { - return 1; - } -} -*/ -"; - var sourceV2 = @" -/* GENERATE: -class G -{ - // a change that won't cause a type to be emitted - int M() - { - return 1; - } -} -*/ -"; + var sourceV1 = """ + /* GENERATE: + class G + { + int M() + { + return 1; + } + } + */ + + """; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); @@ -2192,7 +2162,20 @@ int M() var debuggingSession = await StartDebuggingSessionAsync(service, solution); // change the source - solution = solution.WithDocumentText(document1.Id, CreateText(sourceV2)); + solution = solution.WithDocumentText(document1.Id, CreateText(""" + + /* GENERATE: + class G + { + // a change that won't cause a type to be emitted + int M() + { + return 1; + } + } + */ + + """)); // validate solution update status and emit var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); @@ -2211,8 +2194,6 @@ int M() public async Task Capabilities_SynthesizedNewType() { var source1 = "class C { void M() { } }"; - var source2 = "class C { void M() { var x = new { Goo = 1 }; } }"; - using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, [source1]); var project = solution.Projects.Single(); @@ -2228,7 +2209,7 @@ public async Task Capabilities_SynthesizedNewType() var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update document: - solution = solution.WithDocumentText(documentId, CreateText(source2)); + solution = solution.WithDocumentText(documentId, CreateText("class C { void M() { var x = new { Goo = 1 }; } }")); var document2 = solution.Projects.Single().Documents.Single(); // These errors aren't reported as document diagnostics @@ -2403,8 +2384,6 @@ public async Task ValidSignificantChange_FileUpdateNotObservedBeforeDebuggingSes var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; - var source3 = "class C1 { void M() { System.Console.WriteLine(3); } }"; - var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source2, Encoding.UTF8); @@ -2427,7 +2406,7 @@ public async Task ValidSignificantChange_FileUpdateNotObservedBeforeDebuggingSes EnterBreakState(debuggingSession); // user edits the file: - solution = solution.WithDocumentText(documentId, CreateText(source3)); + solution = solution.WithDocumentText(documentId, CreateText("class C1 { void M() { System.Console.WriteLine(3); } }")); var document3 = solution.Projects.Single().Documents.Single(); // EnC service queries for a document, but the source file on disk doesn't match the PDB @@ -2590,8 +2569,6 @@ public async Task ValidSignificantChange_DocumentOutOfSync(bool delayLoad) public async Task ValidSignificantChange_EmitSuccessful(bool breakMode, bool commitUpdate) { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; - var sourceV2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; - using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); @@ -2605,7 +2582,7 @@ public async Task ValidSignificantChange_EmitSuccessful(bool breakMode, bool com } // change the source (valid edit): - solution = solution.WithDocumentText(document1.Id, CreateText(sourceV2)); + solution = solution.WithDocumentText(document1.Id, CreateText("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); @@ -2822,32 +2799,22 @@ public async Task ValidSignificantChange_EmitSuccessful_UpdateDeferred(bool comm [Fact] public async Task ValidSignificantChange_PartialTypes() { - var sourceA1 = @" -partial class C { int X = 1; void F() { X = 1; } } + var sourceA1 = """ -partial class D { int U = 1; public D() { } } -partial class D { int W = 1; } + partial class C { int X = 1; void F() { X = 1; } } -partial class E { int A; public E(int a) { A = a; } } -"; - var sourceB1 = @" -partial class C { int Y = 1; } -partial class E { int B; public E(int a, int b) { A = a; B = new System.Func(() => b)(); } } -"; + partial class D { int U = 1; public D() { } } + partial class D { int W = 1; } - var sourceA2 = @" -partial class C { int X = 2; void F() { X = 2; } } + partial class E { int A; public E(int a) { A = a; } } -partial class D { int U = 2; } -partial class D { int W = 2; public D() { } } + """; + var sourceB1 = """ -partial class E { int A = 1; public E(int a) { A = a; } } -"; - var sourceB2 = @" -partial class C { int Y = 2; } -partial class E { int B = 2; public E(int a, int b) { A = a; B = new System.Func(() => b)(); } } -"; + partial class C { int Y = 1; } + partial class E { int B; public E(int a, int b) { A = a; B = new System.Func(() => b)(); } } + """; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, [sourceA1, sourceB1]); var project = solution.Projects.Single(); @@ -2861,8 +2828,22 @@ partial class C { int Y = 2; } // change the source (valid edit): var documentA = project.Documents.First(); var documentB = project.Documents.Skip(1).First(); - solution = solution.WithDocumentText(documentA.Id, CreateText(sourceA2)); - solution = solution.WithDocumentText(documentB.Id, CreateText(sourceB2)); + solution = solution.WithDocumentText(documentA.Id, CreateText(""" + + partial class C { int X = 2; void F() { X = 2; } } + + partial class D { int U = 2; } + partial class D { int W = 2; public D() { } } + + partial class E { int A = 1; public E(int a) { A = a; } } + + """)); + solution = solution.WithDocumentText(documentB.Id, CreateText(""" + + partial class C { int Y = 2; } + partial class E { int B = 2; public E(int a, int b) { A = a; B = new System.Func(() => b)(); } } + + """)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); @@ -2887,7 +2868,11 @@ partial class C { int Y = 2; } [WorkItem("https://github.com/dotnet/roslyn/issues/78244")] public async Task MultiProjectUpdates_ValidSignificantChange_RudeEdit(bool allowPartialUpdate) { - var sourceA1 = """ + using var _ = CreateWorkspace(out var solution, out var service); + + solution = solution + .AddTestProject("A", out var projectAId) + .AddTestDocument(""" using System; class A @@ -2897,17 +2882,24 @@ static void F() Console.WriteLine(1); } } - """; - - var sourceB1 = """ + """, "A.cs", out var documentAId).Project.Solution + .AddTestProject("B", out var projectBId) + .AddTestDocument(""" using System; interface I { } - """; + """, "B.cs", out var documentBId).Project.Solution; + + EmitAndLoadLibraryToDebuggee(solution.GetRequiredDocument(documentAId)); + EmitAndLoadLibraryToDebuggee(solution.GetRequiredDocument(documentBId)); + + var debuggingSession = await StartDebuggingSessionAsync(service, solution); - var sourceA2 = """ + // change the source (valid edit in A and rude edit in B): + solution = solution + .WithDocumentText(documentAId, CreateText(""" using System; class A { @@ -2916,34 +2908,15 @@ static void F() Console.WriteLine(2); } } - """; - - var sourceB2 = """ + """)) + .WithDocumentText(documentBId, CreateText(""" using System; interface I { void F() {} } - """; - - using var _ = CreateWorkspace(out var solution, out var service); - - solution = solution - .AddTestProject("A", out var projectAId) - .AddTestDocument(sourceA1, "A.cs", out var documentAId).Project.Solution - .AddTestProject("B", out var projectBId) - .AddTestDocument(sourceB1, "B.cs", out var documentBId).Project.Solution; - - EmitAndLoadLibraryToDebuggee(solution.GetRequiredDocument(documentAId)); - EmitAndLoadLibraryToDebuggee(solution.GetRequiredDocument(documentBId)); - - var debuggingSession = await StartDebuggingSessionAsync(service, solution); - - // change the source (valid edit in A and rude edit in B): - solution = solution - .WithDocumentText(documentAId, CreateText(sourceA2)) - .WithDocumentText(documentBId, CreateText(sourceB2)); + """)); // Rude Edit reported: var documentB = solution.GetRequiredDocument(documentBId); @@ -2986,7 +2959,11 @@ void F() {} [WorkItem("https://github.com/dotnet/roslyn/issues/78244")] public async Task MultiProjectUpdates_ValidSignificantChange_NoEffectEdit() { - var sourceA1 = """ + using var _ = CreateWorkspace(out var solution, out var service); + + solution = solution + .AddTestProject("A", out var projectAId) + .AddTestDocument(""" class A { static void F() @@ -2994,9 +2971,9 @@ static void F() System.Console.WriteLine(1); } } - """; - - var sourceB1 = """ + """, "A.cs", out var documentAId).Project.Solution + .AddTestProject("B", out var projectBId) + .AddTestDocument(""" class B { static B() @@ -3004,9 +2981,16 @@ static B() System.Console.WriteLine(10); } } - """; + """, "B.cs", out var documentBId).Project.Solution; - var sourceA2 = """ + EmitAndLoadLibraryToDebuggee(solution.GetRequiredDocument(documentAId)); + EmitAndLoadLibraryToDebuggee(solution.GetRequiredDocument(documentBId)); + + var debuggingSession = await StartDebuggingSessionAsync(service, solution); + + // change the source (valid edit in A and no-effect edit in B): + solution = solution + .WithDocumentText(documentAId, CreateText(""" class A { static void F() @@ -3014,9 +2998,8 @@ static void F() System.Console.WriteLine(2); } } - """; - - var sourceB2 = """ + """)) + .WithDocumentText(documentBId, CreateText(""" class B { static B() @@ -3024,25 +3007,7 @@ static B() System.Console.WriteLine(20); } } - """; - - using var _ = CreateWorkspace(out var solution, out var service); - - solution = solution - .AddTestProject("A", out var projectAId) - .AddTestDocument(sourceA1, "A.cs", out var documentAId).Project.Solution - .AddTestProject("B", out var projectBId) - .AddTestDocument(sourceB1, "B.cs", out var documentBId).Project.Solution; - - EmitAndLoadLibraryToDebuggee(solution.GetRequiredDocument(documentAId)); - EmitAndLoadLibraryToDebuggee(solution.GetRequiredDocument(documentBId)); - - var debuggingSession = await StartDebuggingSessionAsync(service, solution); - - // change the source (valid edit in A and no-effect edit in B): - solution = solution - .WithDocumentText(documentAId, CreateText(sourceA2)) - .WithDocumentText(documentBId, CreateText(sourceB2)); + """)); // no-effect warning reported: var documentB = solution.GetRequiredDocument(documentBId); @@ -3080,17 +3045,13 @@ static B() [WorkItem("https://github.com/dotnet/roslyn/issues/72331")] internal async Task ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate(SourceGeneratorExecutionPreference executionPreference) { - var sourceV1 = @" -/* GENERATE: file class G { int X => 1; } */ + var sourceV1 = """ -class C { int Y => 1; } -"; - var sourceV2 = @" -/* GENERATE: file class G { int X => 2; } */ + /* GENERATE: file class G { int X => 1; } */ -class C { int Y => 2; } -"; + class C { int Y => 1; } + """; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var workspace = CreateWorkspace(out var solution, out var service); @@ -3113,7 +3074,13 @@ class C { int Y => 2; } EnterBreakState(debuggingSession); // change the source (valid edit) - solution = solution.WithDocumentText(document1.Id, CreateText(sourceV2)); + solution = solution.WithDocumentText(document1.Id, CreateText(""" + + /* GENERATE: file class G { int X => 2; } */ + + class C { int Y => 2; } + + """)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); @@ -3141,13 +3108,6 @@ internal async Task RudeEdit_SourceGenerators_DocumentUpdate_GeneratedDocumentAd var sourceV1 = """ class C { int Y => 1; } """; - - var sourceV2 = """ - /* GENERATE: [assembly: System.Reflection.AssemblyMetadata("X", "Y")] */ - - class C { int Y => 2; } - """; - var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var workspace = CreateWorkspace(out var solution, out var service); @@ -3171,7 +3131,11 @@ class C { int Y => 2; } EnterBreakState(debuggingSession); // change the source (valid edit) - solution = solution.WithDocumentText(document1.Id, CreateText(sourceV2)); + solution = solution.WithDocumentText(document1.Id, CreateText(""" + /* GENERATE: [assembly: System.Reflection.AssemblyMetadata("X", "Y")] */ + + class C { int Y => 2; } + """)); // validate solution update status and emit: var results = await EmitSolutionUpdateAsync(debuggingSession, solution, allowPartialUpdate: false); @@ -3192,30 +3156,19 @@ class C { int Y => 2; } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate_LineChanges() { - var sourceV1 = @" -/* GENERATE: -class G -{ - int M() - { - return 1; - } -} -*/ -"; - var sourceV2 = @" -/* GENERATE: -class G -{ + var sourceV1 = """ - int M() - { - return 1; - } -} -*/ -"; + /* GENERATE: + class G + { + int M() + { + return 1; + } + } + */ + """; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); @@ -3229,7 +3182,20 @@ int M() EnterBreakState(debuggingSession); // change the source (valid edit): - solution = solution.WithDocumentText(document1.Id, CreateText(sourceV2)); + solution = solution.WithDocumentText(document1.Id, CreateText(""" + + /* GENERATE: + class G + { + + int M() + { + return 1; + } + } + */ + + """)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); @@ -3255,15 +3221,11 @@ int M() [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentInsert() { - var sourceV1 = @" -partial class C { int X = 1; } -"; - var sourceV2 = @" -/* GENERATE: partial class C { int Y = 2; } */ + var sourceV1 = """ -partial class C { int X = 1; } -"; + partial class C { int X = 1; } + """; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); @@ -3277,7 +3239,13 @@ partial class C { int X = 1; } EnterBreakState(debuggingSession); // change the source (valid edit): - solution = solution.WithDocumentText(document1.Id, CreateText(sourceV2)); + solution = solution.WithDocumentText(document1.Id, CreateText(""" + + /* GENERATE: partial class C { int Y = 2; } */ + + partial class C { int X = 1; } + + """)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); @@ -3300,17 +3268,17 @@ partial class C { int X = 1; } [Fact] public async Task ValidSignificantChange_SourceGenerators_AdditionalDocumentUpdate() { - var source = @" -class C { int Y => 1; } -"; + var source = """ + + class C { int Y => 1; } + + """; + + var additionalSourceV1 = """ - var additionalSourceV1 = @" -/* GENERATE: class G { int X => 1; } */ -"; - var additionalSourceV2 = @" -/* GENERATE: class G { int X => 2; } */ -"; + /* GENERATE: class G { int X => 1; } */ + """; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); @@ -3325,7 +3293,11 @@ class C { int Y => 1; } // change the additional source (valid edit): var additionalDocument1 = solution.Projects.Single().AdditionalDocuments.Single(); - solution = solution.WithAdditionalDocumentText(additionalDocument1.Id, CreateText(additionalSourceV2)); + solution = solution.WithAdditionalDocumentText(additionalDocument1.Id, CreateText(""" + + /* GENERATE: class G { int X => 2; } */ + + """)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); @@ -3348,9 +3320,11 @@ class C { int Y => 1; } [Fact] public async Task ValidSignificantChange_SourceGenerators_AnalyzerConfigUpdate() { - var source = @" -class C { int Y => 1; } -"; + var source = """ + + class C { int Y => 1; } + + """; var configV1 = new[] { ("enc_generator_output", "1") }; var configV2 = new[] { ("enc_generator_output", "2") }; @@ -3471,8 +3445,6 @@ public async Task ValidInsignificantChange() public async Task RudeEdit() { var source1 = "class C { void M() { } }"; - var source2 = "class C { void M() { var x = new { Goo = 1 }; } }"; - using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, [source1]); var project = solution.Projects.Single(); @@ -3488,7 +3460,7 @@ public async Task RudeEdit() var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update document: - solution = solution.WithDocumentText(documentId, CreateText(source2)); + solution = solution.WithDocumentText(documentId, CreateText("class C { void M() { var x = new { Goo = 1 }; } }")); var document2 = solution.Projects.Single().Documents.Single(); // These errors aren't reported as document diagnostics @@ -4078,11 +4050,13 @@ public async Task ActiveStatements_LinkedDocuments() { var markedSources = new[] { -@"class Test1 -{ - static void Main() => Project2::Test1.F(); - static void F() => Project4::Test2.M(); -}", + """ + class Test1 + { + static void Main() => Project2::Test1.F(); + static void F() => Project4::Test2.M(); + } + """, @"class Test2 { static void M() => Console.WriteLine(); }" }; @@ -4173,35 +4147,21 @@ DocumentId AddProjectAndLinkDocument(string projectName, Document doc, SourceTex public async Task ActiveStatements_OutOfSyncDocuments() { var markedSource1 = -@"class C -{ - static void M() - { - try - { - } - catch (Exception e) - { - M(); - } - } -}"; - var source2 = -@"class C -{ - static void M() - { - try - { - } - catch (Exception e) - { - - M(); - } - } -}"; - + """ + class C + { + static void M() + { + try + { + } + catch (Exception e) + { + M(); + } + } + } + """; var markedSources = new[] { markedSource1 }; var thread1 = Guid.NewGuid(); @@ -4226,7 +4186,22 @@ static void M() EnterBreakState(debuggingSession, debugInfos); // update document to test a changed solution - solution = solution.WithDocumentText(document.Id, CreateText(source2)); + solution = solution.WithDocumentText(document.Id, CreateText(""" + class C + { + static void M() + { + try + { + } + catch (Exception e) + { + + M(); + } + } + } + """)); document = solution.GetDocument(document.Id); var baseActiveStatementMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); @@ -4262,38 +4237,44 @@ static void M() [Fact] public async Task ActiveStatements_SourceGeneratedDocuments_LineDirectives() { - var markedSource1 = @" -/* GENERATE: -class C -{ - void F() - { -#line 1 ""a.razor"" - F(); -#line default - } -} -*/ -"; - var markedSource2 = @" -/* GENERATE: -class C -{ - void F() - { -#line 2 ""a.razor"" - F(); -#line default - } -} -*/ -"; + var markedSource1 = """ + + /* GENERATE: + class C + { + void F() + { + #line 1 "a.razor" + F(); + #line default + } + } + */ + + """; + var markedSource2 = """ + + /* GENERATE: + class C + { + void F() + { + #line 2 "a.razor" + F(); + #line default + } + } + */ + + """; var source1 = SourceMarkers.Clear(markedSource1); var source2 = SourceMarkers.Clear(markedSource2); - var additionalFileSourceV1 = @" - xxxxxxxxxxxxxxxxx -"; + var additionalFileSourceV1 = """ + + xxxxxxxxxxxxxxxxx + + """; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; @@ -4347,38 +4328,42 @@ void F() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/54347")] public async Task ActiveStatements_EncSessionFollowedByHotReload() { - var markedSource1 = @" -class C -{ - int F() - { - try - { - return 0; - } - catch - { - return 1; - } - } -} -"; - var markedSource2 = @" -class C -{ - int F() - { - try - { - return 0; - } - catch - { - return 2; - } - } -} -"; + var markedSource1 = """ + + class C + { + int F() + { + try + { + return 0; + } + catch + { + return 1; + } + } + } + + """; + var markedSource2 = """ + + class C + { + int F() + { + try + { + return 0; + } + catch + { + return 2; + } + } + } + + """; var source1 = SourceMarkers.Clear(markedSource1); var source2 = SourceMarkers.Clear(markedSource2); @@ -4450,18 +4435,20 @@ int F() public async Task BreakStateRemappingFollowedUpByRunStateUpdate() { var markedSourceV1 = -@"class Test -{ - static bool B() => true; + """ + class Test + { + static bool B() => true; - static void G() { while (B()); } + static void G() { while (B()); } - static void F() - { - /*insert1[1]*/B();/*insert2[5]*/B();/*insert3[10]*/B(); - G(); - } -}"; + static void F() + { + /*insert1[1]*/B();/*insert2[5]*/B();/*insert3[10]*/B(); + G(); + } + } + """; var markedSourceV2 = Update(markedSourceV1, marker: "1"); var markedSourceV3 = Update(markedSourceV2, marker: "2"); var markedSourceV4 = Update(markedSourceV3, marker: "3"); @@ -4573,44 +4560,18 @@ static void F() public async Task BreakInPresenceOfUnappliedChanges() { var markedSource1 = -@"class Test -{ - static bool B() => true; - static void G() { while (B()); } - - static void F() - { - G(); - } -}"; - - var markedSource2 = -@"class Test -{ - static bool B() => true; - static void G() { while (B()); } - - static void F() - { - B(); - G(); - } -}"; - - var markedSource3 = -@"class Test -{ - static bool B() => true; - static void G() { while (B()); } - - static void F() - { - B(); - B(); - G(); - } -}"; + """ + class Test + { + static bool B() => true; + static void G() { while (B()); } + static void F() + { + G(); + } + } + """; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, SourceMarkers.Clear(markedSource1)); var documentId = document.Id; @@ -4621,7 +4582,19 @@ static void F() // Update to snapshot 2, but don't apply - solution = solution.WithDocumentText(documentId, CreateText(SourceMarkers.Clear(markedSource2))); + solution = solution.WithDocumentText(documentId, CreateText(SourceMarkers.Clear(""" + class Test + { + static bool B() => true; + static void G() { while (B()); } + + static void F() + { + B(); + G(); + } + } + """))); // EnC update F v2 -> v3 @@ -4647,7 +4620,20 @@ static void F() new ActiveStatementSpan(new ActiveStatementId(1), expectedSpanF1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.NonLeafFrame, documentId) ], spans); - solution = solution.WithDocumentText(documentId, CreateText(SourceMarkers.Clear(markedSource3))); + solution = solution.WithDocumentText(documentId, CreateText(SourceMarkers.Clear(""" + class Test + { + static bool B() => true; + static void G() { while (B()); } + + static void F() + { + B(); + B(); + G(); + } + } + """))); // check that the active statement is mapped correctly to snapshot v3: var expectedSpanG2 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); @@ -4693,28 +4679,18 @@ static void F() public async Task BreakAfterRunModeChangeDeletesNonLeafActiveStatement() { var markedSource1 = -@"class Test -{ - static bool B() => true; - static void G() { while (B()); } - - static void F() - { - G(); - } -}"; - - var markedSource2 = -@"class Test -{ - static bool B() => true; - static void G() { while (B()); } - - static void F() - { - } -}"; + """ + class Test + { + static bool B() => true; + static void G() { while (B()); } + static void F() + { + G(); + } + } + """; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, SourceMarkers.Clear(markedSource1)); var documentId = document.Id; @@ -4725,7 +4701,17 @@ static void F() // Apply update: F v1 -> v2. - solution = solution.WithDocumentText(documentId, CreateText(SourceMarkers.Clear(markedSource2))); + solution = solution.WithDocumentText(documentId, CreateText(SourceMarkers.Clear(""" + class Test + { + static bool B() => true; + static void G() { while (B()); } + + static void F() + { + } + } + """))); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); @@ -4941,14 +4927,6 @@ public class C public int F() => 2; } """; - - var libSource3 = """ - public class C - { - public int F() => 3; - } - """; - using var workspace = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, libSource1); @@ -4989,7 +4967,12 @@ public class C var libMvid2 = EmitAndLoadLibraryToDebuggee(oldProject.Id, libSource2); // lib source is updated: - solution = solution.WithDocumentText(documentId, CreateText(libSource3)); + solution = solution.WithDocumentText(documentId, CreateText(""" + public class C + { + public int F() => 3; + } + """)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); diff --git a/src/Features/Test/EditAndContinue/EditSessionActiveStatementsTests.cs b/src/Features/Test/EditAndContinue/EditSessionActiveStatementsTests.cs index 0110da0cb3c78..c5055ec37bdb9 100644 --- a/src/Features/Test/EditAndContinue/EditSessionActiveStatementsTests.cs +++ b/src/Features/Test/EditAndContinue/EditSessionActiveStatementsTests.cs @@ -92,48 +92,51 @@ public async Task BaseActiveStatementsAndExceptionRegions1() { var markedSources = new[] { -@"class Test1 -{ - static void M1() - { - try { } finally { F1(); } - } - - static void F1() - { - Console.WriteLine(1); - } -}", -@"class Test2 -{ - static void M2() - { - try - { - try - { - F2(); - } - catch (Exception1 e1) - { - } - } - catch (Exception2 e2) - { - } - } - - static void F2() - { - Test1.M1() - } - - static void Main() - { - try { M2(); } finally { } - } -} -" + """ + class Test1 + { + static void M1() + { + try { } finally { F1(); } + } + + static void F1() + { + Console.WriteLine(1); + } + } + """, + """ + class Test2 + { + static void M2() + { + try + { + try + { + F2(); + } + catch (Exception1 e1) + { + } + } + catch (Exception2 e2) + { + } + } + + static void F2() + { + Test1.M1() + } + + static void Main() + { + try { M2(); } finally { } + } + } + """ }; var module1 = new Guid("11111111-1111-1111-1111-111111111111"); @@ -302,27 +305,29 @@ static void Main() public async Task BaseActiveStatementsAndExceptionRegions2() { var baseSource = -@"class Test -{ - static void F1() - { - try - { - F2(); - } - catch (Exception) { - Console.WriteLine(1); - Console.WriteLine(2); - Console.WriteLine(3); - } - /*insert1[1]*/ - } - - static void F2() - { - throw new Exception(); - } -}"; + """ + class Test + { + static void F1() + { + try + { + F2(); + } + catch (Exception) { + Console.WriteLine(1); + Console.WriteLine(2); + Console.WriteLine(3); + } + /*insert1[1]*/ + } + + static void F2() + { + throw new Exception(); + } + } + """; var updatedSource = Update(baseSource, marker: "1"); var module1 = new Guid("11111111-1111-1111-1111-111111111111"); @@ -410,66 +415,68 @@ static void F2() public async Task BaseActiveStatementsAndExceptionRegions_WithInitialNonRemappableRegions() { var markedSourceV1 = -@"class Test -{ - static void F1() - { - try - { - M(); - } - catch - { - } - } - - static void F2() - { /*delete2 - */try - { - } - catch - { - M(); - }/*insert2[1]*/ - } - - static void F3() - { - try - { - try - { /*delete1 - */M();/*insert1[3]*/ - } - finally - { - } - } - catch - { - } -/*delete1 - -*/ } - - static void F4() - { /*insert1[1]*//*insert2[2]*/ - try - { - try + """ + class Test { + static void F1() + { + try + { + M(); + } + catch + { + } + } + + static void F2() + { /*delete2 + */try + { + } + catch + { + M(); + }/*insert2[1]*/ + } + + static void F3() + { + try + { + try + { /*delete1 + */M();/*insert1[3]*/ + } + finally + { + } + } + catch + { + } + /*delete1 + + */ } + + static void F4() + { /*insert1[1]*//*insert2[2]*/ + try + { + try + { + } + catch + { + M(); + } + } + catch + { + } + } } - catch - { - M(); - } - } - catch - { - } - } -}"; + """; var markedSourceV2 = Update(markedSourceV1, marker: "1"); var markedSourceV3 = Update(markedSourceV2, marker: "2"); @@ -620,24 +627,26 @@ public async Task BaseActiveStatementsAndExceptionRegions_Recursion() { var markedSources = new[] { -@"class C -{ - static void M() - { - try - { - M(); - } - catch (Exception e) - { - } - } - - static void F() - { - M(); - } -}" + """ + class C + { + static void M() + { + try + { + M(); + } + catch (Exception e) + { + } + } + + static void F() + { + M(); + } + } + """ }; var thread1 = Guid.NewGuid(); diff --git a/src/Features/Test/EditAndContinue/RemoteEditAndContinueServiceTests.cs b/src/Features/Test/EditAndContinue/RemoteEditAndContinueServiceTests.cs index a2c51883bcb7d..943282d04a608 100644 --- a/src/Features/Test/EditAndContinue/RemoteEditAndContinueServiceTests.cs +++ b/src/Features/Test/EditAndContinue/RemoteEditAndContinueServiceTests.cs @@ -154,7 +154,7 @@ await localWorkspace.ChangeSolutionAsync(localWorkspace.CurrentSolution // BreakStateChanged - mockEncService.BreakStateOrCapabilitiesChangedImpl = (bool? inBreakState) => + mockEncService.BreakStateOrCapabilitiesChangedImpl = inBreakState => { Assert.True(inBreakState); }; diff --git a/src/Features/Test/EditAndContinue/UnitTestingHotReloadServiceTests.cs b/src/Features/Test/EditAndContinue/UnitTestingHotReloadServiceTests.cs index 6e8d9dc3b68d4..e98c2eaeb878a 100644 --- a/src/Features/Test/EditAndContinue/UnitTestingHotReloadServiceTests.cs +++ b/src/Features/Test/EditAndContinue/UnitTestingHotReloadServiceTests.cs @@ -23,10 +23,6 @@ public sealed class UnitTestingHotReloadServiceTests : EditAndContinueWorkspaceT public async Task Test() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; - var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; - var source3 = "class C { void M() { System.Console.WriteLine(2); } }"; - var source4 = "class C { void M() { System.Console.WriteLine(2)/* missing semicolon */ }"; - var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1, Encoding.UTF8); @@ -60,13 +56,13 @@ public async Task Test() ], matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); // Valid change - solution = solution.WithDocumentText(documentIdA, CreateText(source2)); + solution = solution.WithDocumentText(documentIdA, CreateText("class C { void M() { System.Console.WriteLine(2); } }")); var result = await hotReload.EmitSolutionUpdateAsync(solution, commitUpdates: true, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); - solution = solution.WithDocumentText(documentIdA, CreateText(source3)); + solution = solution.WithDocumentText(documentIdA, CreateText("class C { void M() { System.Console.WriteLine(2); } }")); // Rude edit result = await hotReload.EmitSolutionUpdateAsync(solution, commitUpdates: true, CancellationToken.None); @@ -77,7 +73,7 @@ public async Task Test() Assert.Empty(result.updates); // Syntax error is reported in the diagnostics: - solution = solution.WithDocumentText(documentIdA, CreateText(source4)); + solution = solution.WithDocumentText(documentIdA, CreateText("class C { void M() { System.Console.WriteLine(2)/* missing semicolon */ }")); result = await hotReload.EmitSolutionUpdateAsync(solution, commitUpdates: true, CancellationToken.None); Assert.Equal(1, result.diagnostics.Length); diff --git a/src/Features/Test/EditAndContinue/WatchHotReloadServiceTests.cs b/src/Features/Test/EditAndContinue/WatchHotReloadServiceTests.cs index c9912a0979d53..028161f3b8df0 100644 --- a/src/Features/Test/EditAndContinue/WatchHotReloadServiceTests.cs +++ b/src/Features/Test/EditAndContinue/WatchHotReloadServiceTests.cs @@ -5,6 +5,7 @@ #if NET using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; @@ -12,7 +13,6 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExternalAccess.Watch.Api; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; @@ -27,6 +27,16 @@ namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests; [UseExportProvider] public sealed class WatchHotReloadServiceTests : EditAndContinueWorkspaceTestBase { + private static Task GetCommittedDocumentTextAsync(WatchHotReloadService service, DocumentId documentId) + => ((EditAndContinueService)service.GetTestAccessor().EncService) + .GetTestAccessor() + .GetActiveDebuggingSessions() + .Single() + .LastCommittedSolution + .GetRequiredProject(documentId.ProjectId) + .GetRequiredDocument(documentId) + .GetTextAsync(); + [Theory] [CombinatorialData] public async Task Test(bool requireCommit) @@ -39,10 +49,6 @@ public async Task Test(bool requireCommit) var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); /*2*/} }"; var source3 = "class C { void M() { System.Console.WriteLine(2); /*3*/} }"; - var source4 = "class C { void M() { System.Console.WriteLine(2); } }"; - var source5 = "class C { void M() { System.Console.WriteLine(2)/* missing semicolon */ }"; - var source6 = "class C { void M() { Unknown(); } }"; - var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1, Encoding.UTF8); @@ -79,6 +85,7 @@ public async Task Test(bool requireCommit) var result = await hotReload.GetUpdatesAsync(solution, runningProjects: ImmutableDictionary.Empty, CancellationToken.None); Assert.Empty(result.CompilationDiagnostics); + Assert.Empty(result.RudeEdits); Assert.Equal(1, result.ProjectUpdates.Length); AssertEx.Equal([0x02000002], result.ProjectUpdates[0].UpdatedTypes); @@ -87,36 +94,32 @@ public async Task Test(bool requireCommit) hotReload.CommitUpdate(); } + var updatedText = await GetCommittedDocumentTextAsync(hotReload, documentIdA); + Assert.Equal(source2, updatedText.ToString()); + // Insignificant change: solution = solution.WithDocumentText(documentIdA, CreateText(source3)); result = await hotReload.GetUpdatesAsync(solution, runningProjects: ImmutableDictionary.Empty, CancellationToken.None); Assert.Empty(result.CompilationDiagnostics); - Assert.Empty(result.CompilationDiagnostics); + Assert.Empty(result.RudeEdits); Assert.Empty(result.ProjectUpdates); Assert.Equal(WatchHotReloadService.Status.NoChangesToApply, result.Status); - var updatedText = await ((EditAndContinueService)hotReload.GetTestAccessor().EncService) - .GetTestAccessor() - .GetActiveDebuggingSessions() - .Single() - .LastCommittedSolution - .GetRequiredProject(documentIdA.ProjectId) - .GetRequiredDocument(documentIdA) - .GetTextAsync(); - + updatedText = await GetCommittedDocumentTextAsync(hotReload, documentIdA); Assert.Equal(source3, updatedText.ToString()); // Rude edit: - solution = solution.WithDocumentText(documentIdA, CreateText(source4)); + solution = solution.WithDocumentText(documentIdA, CreateText("class C { void M() { System.Console.WriteLine(2); } }")); var runningProjects = ImmutableDictionary.Empty - .Add(projectId, new WatchHotReloadService.RunningProjectInfo() { RestartWhenChangesHaveNoEffect = false }); + .Add(projectId, new WatchHotReloadService.RunningProjectInfo() { RestartWhenChangesHaveNoEffect = true }); result = await hotReload.GetUpdatesAsync(solution, runningProjects, CancellationToken.None); + Assert.Empty(result.CompilationDiagnostics); AssertEx.Equal( - ["P: ENC0110: " + string.Format(FeaturesResources.Changing_the_signature_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.method)], - result.RudeEdits.SelectMany(re => re.diagnostics.Select(d => $"{re.project.DebugName}: {d.Id}: {d.GetMessage()}"))); + [$"P: {sourceFileA.Path}: (0,17)-(0,18): Error ENC0110: {string.Format(FeaturesResources.Changing_the_signature_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.method)}"], + InspectDiagnostics(result.RudeEdits)); Assert.Empty(result.ProjectUpdates); AssertEx.SetEqual(["P"], result.ProjectsToRestart.Select(p => solution.GetRequiredProject(p.Key).Name)); AssertEx.SetEqual(["P"], result.ProjectsToRebuild.Select(p => solution.GetRequiredProject(p).Name)); @@ -128,24 +131,40 @@ public async Task Test(bool requireCommit) hotReload.DiscardUpdate(); } + updatedText = await GetCommittedDocumentTextAsync(hotReload, documentIdA); + Assert.Equal(source3, updatedText.ToString()); + // Syntax error: - solution = solution.WithDocumentText(documentIdA, CreateText(source5)); + solution = solution.WithDocumentText(documentIdA, CreateText("class C { void M() { System.Console.WriteLine(2)/* missing semicolon */ }")); result = await hotReload.GetUpdatesAsync(solution, runningProjects, CancellationToken.None); AssertEx.Equal( - ["CS1002: " + CSharpResources.ERR_SemicolonExpected], - result.CompilationDiagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); + [$"{sourceFileA.Path}: (0,72)-(0,73): Error CS1002: {CSharpResources.ERR_SemicolonExpected}"], + InspectDiagnostics(result.CompilationDiagnostics)); Assert.Empty(result.ProjectUpdates); Assert.Empty(result.ProjectsToRestart); Assert.Empty(result.ProjectsToRebuild); - // Semantic error: - solution = solution.WithDocumentText(documentIdA, CreateText(source6)); + updatedText = await GetCommittedDocumentTextAsync(hotReload, documentIdA); + Assert.Equal(source3, updatedText.ToString()); + + // Semantic diagnostics and no-effect edit: + solution = solution.WithDocumentText(documentIdA, CreateText("class C { void M() { Unknown(); } static C() { int x = 1; } }")); result = await hotReload.GetUpdatesAsync(solution, runningProjects, CancellationToken.None); AssertEx.Equal( - ["CS0103: " + string.Format(CSharpResources.ERR_NameNotInContext, "Unknown")], - result.CompilationDiagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); + [ + $"{sourceFileA.Path}: (0,21)-(0,28): Error CS0103: {string.Format(CSharpResources.ERR_NameNotInContext, "Unknown")}", + $"{sourceFileA.Path}: (0,51)-(0,52): Warning CS0219: {string.Format(CSharpResources.WRN_UnreferencedVarAssg, "x")}", + ], InspectDiagnostics(result.CompilationDiagnostics)); + + // TODO: https://github.com/dotnet/roslyn/issues/79017 + //AssertEx.Equal( + //[ + // $"P: {sourceFileA.Path}: (0,34)-(0,44): Warning ENC0118: {string.Format(FeaturesResources.Changing_0_might_not_have_any_effect_until_the_application_is_restarted, FeaturesResources.static_constructor)}", + //], InspectDiagnostics(result.RudeEdits)); + AssertEx.Empty(result.RudeEdits); + Assert.Empty(result.ProjectUpdates); Assert.Empty(result.ProjectsToRestart); Assert.Empty(result.ProjectsToRebuild); diff --git a/src/Features/Test/FindUsages/DefinitionItemFactoryTests.cs b/src/Features/Test/FindUsages/DefinitionItemFactoryTests.cs index b7d74dd35a852..875eeb89e99e9 100644 --- a/src/Features/Test/FindUsages/DefinitionItemFactoryTests.cs +++ b/src/Features/Test/FindUsages/DefinitionItemFactoryTests.cs @@ -36,7 +36,9 @@ private static string InspectFlags(TEnum e) where TEnum : Enum => string.Join(" | ", e.ToString().Split(',').Select(s => $"{typeof(TEnum).Name}.{s.Trim()}")); private static string Inspect(string? str) - => (str == null) ? "null" : $"\"{str.Replace(@"\", @"\\").Replace("\"", "\\\"")}\""; + => (str == null) ? "null" : $""" + "{str.Replace(@"\", @"\\").Replace("\"", "\\\"")}" + """; private static string InspectValueAsExpression(string? value, IReadOnlyDictionary expressionMap) => value != null && expressionMap.TryGetValue(value, out var syntax) ? syntax : Inspect(value); diff --git a/src/Features/TestUtilities/BrokeredServices/MockServiceBroker.cs b/src/Features/TestUtilities/BrokeredServices/MockServiceBroker.cs index 6ce21479f9f66..bb3e31e579a57 100644 --- a/src/Features/TestUtilities/BrokeredServices/MockServiceBroker.cs +++ b/src/Features/TestUtilities/BrokeredServices/MockServiceBroker.cs @@ -3,10 +3,10 @@ // See the LICENSE file in the project root for more information. using System; -using Microsoft.ServiceHub.Framework; -using System.Threading.Tasks; using System.IO.Pipelines; using System.Threading; +using System.Threading.Tasks; +using Microsoft.ServiceHub.Framework; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.BrokeredServices.UnitTests; diff --git a/src/Features/TestUtilities/EditAndContinue/ActiveStatementTestHelpers.cs b/src/Features/TestUtilities/EditAndContinue/ActiveStatementTestHelpers.cs index 8ada5b0597279..dd3e0379b33b1 100644 --- a/src/Features/TestUtilities/EditAndContinue/ActiveStatementTestHelpers.cs +++ b/src/Features/TestUtilities/EditAndContinue/ActiveStatementTestHelpers.cs @@ -6,11 +6,11 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; -using Microsoft.CodeAnalysis.Text; -using Roslyn.Utilities; +using System.Text; using Microsoft.CodeAnalysis.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.CSharp; -using System.Text; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests; diff --git a/src/Features/TestUtilities/EditAndContinue/EditAndContinueWorkspaceTestBase.cs b/src/Features/TestUtilities/EditAndContinue/EditAndContinueWorkspaceTestBase.cs index 993d3b16806f2..3f55d58c5b4ac 100644 --- a/src/Features/TestUtilities/EditAndContinue/EditAndContinueWorkspaceTestBase.cs +++ b/src/Features/TestUtilities/EditAndContinue/EditAndContinueWorkspaceTestBase.cs @@ -267,6 +267,9 @@ internal static string InspectDiagnostic(DiagnosticData diagnostic) internal static IEnumerable InspectDiagnostics(ImmutableArray actual) => actual.SelectMany(pd => pd.Diagnostics.Select(d => $"{pd.ProjectId.DebugName}: {InspectDiagnostic(d)}")); + internal static IEnumerable InspectDiagnostics(ImmutableArray<(ProjectId project, ImmutableArray diagnostics)> diagnostics) + => diagnostics.SelectMany(pd => pd.diagnostics.Select(d => $"{pd.project.DebugName}: {InspectDiagnostic(d)}")); + internal static string InspectDiagnostic(Diagnostic actual) => $"{Inspect(actual.Location)}: {actual.Severity} {actual.Id}: {actual.GetMessage()}"; diff --git a/src/Features/TestUtilities/EditAndContinue/EditScriptDescription.cs b/src/Features/TestUtilities/EditAndContinue/EditScriptDescription.cs index 457be67c50916..ddb568447c334 100644 --- a/src/Features/TestUtilities/EditAndContinue/EditScriptDescription.cs +++ b/src/Features/TestUtilities/EditAndContinue/EditScriptDescription.cs @@ -29,7 +29,9 @@ public void VerifyEdits() => VerifyEdits(Array.Empty()); public void VerifyEdits(params string[] expected) - => AssertEx.Equal(expected, Edits.Select(e => e.GetDebuggerDisplay()), itemSeparator: ",\r\n", itemInspector: s => $"\"{s}\""); + => AssertEx.Equal(expected, Edits.Select(e => e.GetDebuggerDisplay()), itemSeparator: ",\r\n", itemInspector: s => $""" + "{s}" + """); public void VerifyEdits(params EditKind[] expected) => AssertEx.Equal(expected, Edits.Select(e => e.Kind)); diff --git a/src/Features/TestUtilities/EditAndContinue/MatchingPair.cs b/src/Features/TestUtilities/EditAndContinue/MatchingPair.cs index ab1153826e628..0410d74b8a0a3 100644 --- a/src/Features/TestUtilities/EditAndContinue/MatchingPair.cs +++ b/src/Features/TestUtilities/EditAndContinue/MatchingPair.cs @@ -16,7 +16,21 @@ public struct MatchingPair public string New; public override readonly string ToString() - => "{ \"" + Old.Replace("\"", "\\\"") + "\", \"" + New.Replace("\"", "\\\"") + "\" }"; + => """ + { " + """ + Old.Replace(""" + " + """, """ + \" + """) + """ + ", " + """ + New.Replace(""" + " + """, """ + \" + """) + """ + " } + """; } public class MatchingPairs : IEnumerable diff --git a/src/Features/TestUtilities/EditAndContinue/RudeEditDiagnosticDescription.cs b/src/Features/TestUtilities/EditAndContinue/RudeEditDiagnosticDescription.cs index deda0fdf026a3..d4d73a359cc4b 100644 --- a/src/Features/TestUtilities/EditAndContinue/RudeEditDiagnosticDescription.cs +++ b/src/Features/TestUtilities/EditAndContinue/RudeEditDiagnosticDescription.cs @@ -54,10 +54,16 @@ public string ToString(Func? tryGetResource) var formattedSquiggle = _squiggle is null ? "null" : _squiggle.IndexOfAny(['\r', '\n']) >= 0 - ? $"\"\"\"{Environment.NewLine}{_squiggle}{Environment.NewLine}\"\"\"" - : $"\"{_squiggle}\""; + ? $"""" + """{Environment.NewLine}{_squiggle}{Environment.NewLine}""" + """" + : $""" + "{_squiggle}" + """; - string[] arguments = [formattedSquiggle, .. _arguments.Select(a => tryGetResource?.Invoke(a) is { } ? $"GetResource(\"{a}\")" : $"\"{a}\"")]; + string[] arguments = [formattedSquiggle, .. _arguments.Select(a => tryGetResource?.Invoke(a) is { } ? $"GetResource(\"{a}\")" : $""" + "{a}" + """)]; var withLine = (FirstLine != null) ? $".WithFirstLine(\"{FirstLine}\")" : null; return $"Diagnostic(RudeEditKind.{RudeEditKind}, {string.Join(", ", arguments)}){withLine}"; diff --git a/src/Features/TestUtilities/EditAndContinue/SourceMarkers.cs b/src/Features/TestUtilities/EditAndContinue/SourceMarkers.cs index 531d2c714271d..7dccf3a31e6a9 100644 --- a/src/Features/TestUtilities/EditAndContinue/SourceMarkers.cs +++ b/src/Features/TestUtilities/EditAndContinue/SourceMarkers.cs @@ -20,15 +20,19 @@ internal static class SourceMarkers "[<] (?/?) (?(AS|ER|N|S|TS))[:] (?[.0-9,]+) (?/?) [>]", RegexOptions.IgnorePatternWhitespace); public static readonly Regex ExceptionRegionPattern = new( - @"[<]ER[:] (?(?:[0-9]+[.][0-9]+[,]?)+) [>] - (?.*) - [<][/]ER[:] (\k) [>]", + """ + [<]ER[:] (?(?:[0-9]+[.][0-9]+[,]?)+) [>] + (?.*) + [<][/]ER[:] (\k) [>] + """, RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline); private static readonly Regex s_trackingStatementPattern = new( - @"[<]TS[:] (?[0-9,]+) [>] - (?.*) - [<][/]TS[:] (\k) [>]", + """ + [<]TS[:] (?[0-9,]+) [>] + (?.*) + [<][/]TS[:] (\k) [>] + """, RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline); internal static string Clear(string source) diff --git a/src/Features/VisualBasic/Portable/ChangeSignature/VisualBasicChangeSignatureService.vb b/src/Features/VisualBasic/Portable/ChangeSignature/VisualBasicChangeSignatureService.vb index 76d9f7d6778df..ec9df4bad7035 100644 --- a/src/Features/VisualBasic/Portable/ChangeSignature/VisualBasicChangeSignatureService.vb +++ b/src/Features/VisualBasic/Portable/ChangeSignature/VisualBasicChangeSignatureService.vb @@ -7,7 +7,6 @@ Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.ChangeSignature -Imports Microsoft.CodeAnalysis.EditAndContinue Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.FindSymbols Imports Microsoft.CodeAnalysis.Formatting diff --git a/src/Features/VisualBasic/Portable/CodeFixes/GenerateType/GenerateTypeCodeFixProvider.vb b/src/Features/VisualBasic/Portable/CodeFixes/GenerateType/GenerateTypeCodeFixProvider.vb index 5ed4108e524b2..a71c85b53e08a 100644 --- a/src/Features/VisualBasic/Portable/CodeFixes/GenerateType/GenerateTypeCodeFixProvider.vb +++ b/src/Features/VisualBasic/Portable/CodeFixes/GenerateType/GenerateTypeCodeFixProvider.vb @@ -9,7 +9,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeFixes.GenerateMember -Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.GenerateType Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/CodeFixes/OverloadBase/OverloadBaseCodeFixProvider.AddKeywordAction.vb b/src/Features/VisualBasic/Portable/CodeFixes/OverloadBase/OverloadBaseCodeFixProvider.AddKeywordAction.vb index 7291ecdb0064c..dda4e9160d273 100644 --- a/src/Features/VisualBasic/Portable/CodeFixes/OverloadBase/OverloadBaseCodeFixProvider.AddKeywordAction.vb +++ b/src/Features/VisualBasic/Portable/CodeFixes/OverloadBase/OverloadBaseCodeFixProvider.AddKeywordAction.vb @@ -6,9 +6,7 @@ Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeCleanup -Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Formatting -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.OverloadBase diff --git a/src/Features/VisualBasic/Portable/CodeFixes/OverloadBase/OverloadBaseCodeFixProvider.vb b/src/Features/VisualBasic/Portable/CodeFixes/OverloadBase/OverloadBaseCodeFixProvider.vb index 124357f4926d8..09fcf69cb6a26 100644 --- a/src/Features/VisualBasic/Portable/CodeFixes/OverloadBase/OverloadBaseCodeFixProvider.vb +++ b/src/Features/VisualBasic/Portable/CodeFixes/OverloadBase/OverloadBaseCodeFixProvider.vb @@ -4,9 +4,7 @@ Imports System.Collections.Immutable Imports System.Composition -Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/CodeFixes/Suppression/VisualBasicSuppressionCodeFixProvider.vb b/src/Features/VisualBasic/Portable/CodeFixes/Suppression/VisualBasicSuppressionCodeFixProvider.vb index a91c330364e8c..05008865f80a0 100644 --- a/src/Features/VisualBasic/Portable/CodeFixes/Suppression/VisualBasicSuppressionCodeFixProvider.vb +++ b/src/Features/VisualBasic/Portable/CodeFixes/Suppression/VisualBasicSuppressionCodeFixProvider.vb @@ -12,7 +12,6 @@ Imports Microsoft.CodeAnalysis.CodeFixes.Suppression Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Simplification -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.Suppression diff --git a/src/Features/VisualBasic/Portable/CodeRefactorings/InlineTemporary/VisualBasicInlineTemporaryCodeRefactoringProvider.vb b/src/Features/VisualBasic/Portable/CodeRefactorings/InlineTemporary/VisualBasicInlineTemporaryCodeRefactoringProvider.vb index 2d0d7cf1d82f4..87e1ada09d9be 100644 --- a/src/Features/VisualBasic/Portable/CodeRefactorings/InlineTemporary/VisualBasicInlineTemporaryCodeRefactoringProvider.vb +++ b/src/Features/VisualBasic/Portable/CodeRefactorings/InlineTemporary/VisualBasicInlineTemporaryCodeRefactoringProvider.vb @@ -8,7 +8,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.FindSymbols Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.InlineTemporary Imports Microsoft.CodeAnalysis.Simplification diff --git a/src/Features/VisualBasic/Portable/Completion/CompletionProviders/CompletionUtilities.vb b/src/Features/VisualBasic/Portable/Completion/CompletionProviders/CompletionUtilities.vb index 0741c14bf9416..0048296dacb8c 100644 --- a/src/Features/VisualBasic/Portable/Completion/CompletionProviders/CompletionUtilities.vb +++ b/src/Features/VisualBasic/Portable/Completion/CompletionProviders/CompletionUtilities.vb @@ -5,7 +5,6 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.Text diff --git a/src/Features/VisualBasic/Portable/Completion/CompletionProviders/CrefCompletionProvider.vb b/src/Features/VisualBasic/Portable/Completion/CompletionProviders/CrefCompletionProvider.vb index 8734d2fae1426..77fca419508ee 100644 --- a/src/Features/VisualBasic/Portable/Completion/CompletionProviders/CrefCompletionProvider.vb +++ b/src/Features/VisualBasic/Portable/Completion/CompletionProviders/CrefCompletionProvider.vb @@ -12,7 +12,6 @@ Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.ErrorReporting Imports Microsoft.CodeAnalysis.Host.Mef -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax @@ -261,7 +260,6 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers End Function Private Shared ReadOnly s_WithoutOpenParen As CharacterSetModificationRule = CharacterSetModificationRule.Create(CharacterSetModificationKind.Remove, "("c) - Private Shared ReadOnly s_WithoutSpace As CharacterSetModificationRule = CharacterSetModificationRule.Create(CharacterSetModificationKind.Remove, " "c) Private Shared ReadOnly s_defaultRules As CompletionItemRules = CompletionItemRules.Default diff --git a/src/Features/VisualBasic/Portable/Completion/CompletionProviders/EnumCompletionProvider.vb b/src/Features/VisualBasic/Portable/Completion/CompletionProviders/EnumCompletionProvider.vb index ba05e293c4fb3..fbdd93ecd0aab 100644 --- a/src/Features/VisualBasic/Portable/Completion/CompletionProviders/EnumCompletionProvider.vb +++ b/src/Features/VisualBasic/Portable/Completion/CompletionProviders/EnumCompletionProvider.vb @@ -87,14 +87,6 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers Public Overrides ReadOnly Property TriggerCharacters As ImmutableHashSet(Of Char) = ImmutableHashSet.Create(" "c, "("c, "="c) - Private Shared Function GetTypeFromSymbol(symbol As ISymbol) As ITypeSymbol - Dim symbolType = If(TryCast(symbol, IFieldSymbol)?.Type, - If(TryCast(symbol, ILocalSymbol)?.Type, - If(TryCast(symbol, IParameterSymbol)?.Type, - TryCast(symbol, IPropertySymbol)?.Type))) - Return symbolType - End Function - ' PERF: Cached values for GetDisplayAndInsertionText. Cuts down on the number of calls to ToMinimalDisplayString for large enums. Private ReadOnly _gate As New Object() Private _cachedDisplayAndInsertionTextContainingType As INamedTypeSymbol diff --git a/src/Features/VisualBasic/Portable/Completion/CompletionProviders/HandlesClauseCompletionProvider.vb b/src/Features/VisualBasic/Portable/Completion/CompletionProviders/HandlesClauseCompletionProvider.vb index c2752f062ff20..611c6b7916c2f 100644 --- a/src/Features/VisualBasic/Portable/Completion/CompletionProviders/HandlesClauseCompletionProvider.vb +++ b/src/Features/VisualBasic/Portable/Completion/CompletionProviders/HandlesClauseCompletionProvider.vb @@ -4,12 +4,10 @@ Imports System.Collections.Immutable Imports System.Composition -Imports System.Runtime.CompilerServices Imports System.Threading Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.Host.Mef -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Completion/CompletionProviders/ImplementsClauseCompletionProvider.vb b/src/Features/VisualBasic/Portable/Completion/CompletionProviders/ImplementsClauseCompletionProvider.vb index b2d4c7e1e9671..856c6054635a7 100644 --- a/src/Features/VisualBasic/Portable/Completion/CompletionProviders/ImplementsClauseCompletionProvider.vb +++ b/src/Features/VisualBasic/Portable/Completion/CompletionProviders/ImplementsClauseCompletionProvider.vb @@ -9,7 +9,6 @@ Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.Host.Mef -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Symbols diff --git a/src/Features/VisualBasic/Portable/Completion/CompletionProviders/ImportCompletionProvider/TypeImportCompletionServiceFactory.vb b/src/Features/VisualBasic/Portable/Completion/CompletionProviders/ImportCompletionProvider/TypeImportCompletionServiceFactory.vb index 583f92982649d..09ecf86392ec8 100644 --- a/src/Features/VisualBasic/Portable/Completion/CompletionProviders/ImportCompletionProvider/TypeImportCompletionServiceFactory.vb +++ b/src/Features/VisualBasic/Portable/Completion/CompletionProviders/ImportCompletionProvider/TypeImportCompletionServiceFactory.vb @@ -6,7 +6,6 @@ Imports System.Composition Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef -Imports Microsoft.CodeAnalysis.Shared.TestHooks Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers diff --git a/src/Features/VisualBasic/Portable/Completion/CompletionProviders/KeywordCompletionProvider.vb b/src/Features/VisualBasic/Portable/Completion/CompletionProviders/KeywordCompletionProvider.vb index 1ed17e4e364a5..4b0be866f0358 100644 --- a/src/Features/VisualBasic/Portable/Completion/CompletionProviders/KeywordCompletionProvider.vb +++ b/src/Features/VisualBasic/Portable/Completion/CompletionProviders/KeywordCompletionProvider.vb @@ -5,7 +5,6 @@ Imports System.Threading Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Completion.Providers -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.Completion diff --git a/src/Features/VisualBasic/Portable/Completion/CompletionProviders/NamedParameterCompletionProvider.vb b/src/Features/VisualBasic/Portable/Completion/CompletionProviders/NamedParameterCompletionProvider.vb index 2ffacc9fe1727..f3bbf314786be 100644 --- a/src/Features/VisualBasic/Portable/Completion/CompletionProviders/NamedParameterCompletionProvider.vb +++ b/src/Features/VisualBasic/Portable/Completion/CompletionProviders/NamedParameterCompletionProvider.vb @@ -11,7 +11,6 @@ Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.ErrorReporting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageService -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax @@ -195,39 +194,6 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers Return Nothing End Function - Private Shared Sub GetInvocableNode(token As SyntaxToken, ByRef invocableNode As SyntaxNode, ByRef argumentList As ArgumentListSyntax) - Dim current = token.Parent - - While current IsNot Nothing - If TypeOf current Is AttributeSyntax Then - invocableNode = current - argumentList = (DirectCast(current, AttributeSyntax)).ArgumentList - Return - End If - - If TypeOf current Is InvocationExpressionSyntax Then - invocableNode = current - argumentList = (DirectCast(current, InvocationExpressionSyntax)).ArgumentList - Return - End If - - If TypeOf current Is ObjectCreationExpressionSyntax Then - invocableNode = current - argumentList = (DirectCast(current, ObjectCreationExpressionSyntax)).ArgumentList - Return - End If - - If TypeOf current Is TypeArgumentListSyntax Then - Exit While - End If - - current = current.Parent - End While - - invocableNode = Nothing - argumentList = Nothing - End Sub - Protected Overrides Function GetTextChangeAsync(selectedItem As CompletionItem, ch As Char?, cancellationToken As CancellationToken) As Task(Of TextChange?) Dim symbolItem = selectedItem Dim insertionText = SymbolCompletionItem.GetInsertionText(selectedItem) diff --git a/src/Features/VisualBasic/Portable/Completion/CompletionProviders/ObjectCreationCompletionProvider.vb b/src/Features/VisualBasic/Portable/Completion/CompletionProviders/ObjectCreationCompletionProvider.vb index c4595d57183a5..161d73e43142a 100644 --- a/src/Features/VisualBasic/Portable/Completion/CompletionProviders/ObjectCreationCompletionProvider.vb +++ b/src/Features/VisualBasic/Portable/Completion/CompletionProviders/ObjectCreationCompletionProvider.vb @@ -8,7 +8,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.Host.Mef -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Completion/CompletionProviders/OverrideCompletionProvider.vb b/src/Features/VisualBasic/Portable/Completion/CompletionProviders/OverrideCompletionProvider.vb index 0214f41b3aa66..5567a3b9396ae 100644 --- a/src/Features/VisualBasic/Portable/Completion/CompletionProviders/OverrideCompletionProvider.vb +++ b/src/Features/VisualBasic/Portable/Completion/CompletionProviders/OverrideCompletionProvider.vb @@ -10,7 +10,6 @@ Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Host.Mef -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Completion/CompletionProviders/PartialTypeCompletionProvider.vb b/src/Features/VisualBasic/Portable/Completion/CompletionProviders/PartialTypeCompletionProvider.vb index 5ead5159d1946..f1512b867c252 100644 --- a/src/Features/VisualBasic/Portable/Completion/CompletionProviders/PartialTypeCompletionProvider.vb +++ b/src/Features/VisualBasic/Portable/Completion/CompletionProviders/PartialTypeCompletionProvider.vb @@ -8,7 +8,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.Host.Mef -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Completion/CompletionProviders/PreprocessorCompletionProvider.vb b/src/Features/VisualBasic/Portable/Completion/CompletionProviders/PreprocessorCompletionProvider.vb index 645ae8b8c826c..864c3ae4e82e7 100644 --- a/src/Features/VisualBasic/Portable/Completion/CompletionProviders/PreprocessorCompletionProvider.vb +++ b/src/Features/VisualBasic/Portable/Completion/CompletionProviders/PreprocessorCompletionProvider.vb @@ -7,7 +7,6 @@ Imports System.Composition Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.Host.Mef -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers diff --git a/src/Features/VisualBasic/Portable/Completion/VisualBasicCompletionService.vb b/src/Features/VisualBasic/Portable/Completion/VisualBasicCompletionService.vb index ea8dbe26a9745..035d97877517a 100644 --- a/src/Features/VisualBasic/Portable/Completion/VisualBasicCompletionService.vb +++ b/src/Features/VisualBasic/Portable/Completion/VisualBasicCompletionService.vb @@ -7,7 +7,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.CodeAnalysis.Tags Imports Microsoft.CodeAnalysis.Text diff --git a/src/Features/VisualBasic/Portable/ConvertForToForEach/VisualBasicConvertForToForEachCodeRefactoringProvider.vb b/src/Features/VisualBasic/Portable/ConvertForToForEach/VisualBasicConvertForToForEachCodeRefactoringProvider.vb index cd1196a835eed..017dccf1a11a5 100644 --- a/src/Features/VisualBasic/Portable/ConvertForToForEach/VisualBasicConvertForToForEachCodeRefactoringProvider.vb +++ b/src/Features/VisualBasic/Portable/ConvertForToForEach/VisualBasicConvertForToForEachCodeRefactoringProvider.vb @@ -7,7 +7,6 @@ Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.ConvertForToForEach -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertForToForEach diff --git a/src/Features/VisualBasic/Portable/ConvertIfToSwitch/VisualBasicConvertIfToSwitchCodeRefactoringProvider.Rewriting.vb b/src/Features/VisualBasic/Portable/ConvertIfToSwitch/VisualBasicConvertIfToSwitchCodeRefactoringProvider.Rewriting.vb index c80d4ba0c1b45..1e8872e650b97 100644 --- a/src/Features/VisualBasic/Portable/ConvertIfToSwitch/VisualBasicConvertIfToSwitchCodeRefactoringProvider.Rewriting.vb +++ b/src/Features/VisualBasic/Portable/ConvertIfToSwitch/VisualBasicConvertIfToSwitchCodeRefactoringProvider.Rewriting.vb @@ -20,11 +20,11 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertIfToSwitch {BinaryOperatorKind.GreaterThanOrEqual, (SyntaxKind.CaseGreaterThanOrEqualClause, SyntaxKind.GreaterThanEqualsToken)} } - Public Overrides Function CreateSwitchExpressionStatement(target As SyntaxNode, sections As ImmutableArray(Of AnalyzedSwitchSection), feature As Feature) As SyntaxNode + Public Overrides Function CreateSwitchExpressionStatement(target As ExpressionSyntax, sections As ImmutableArray(Of AnalyzedSwitchSection), feature As Feature) As SyntaxNode Throw ExceptionUtilities.Unreachable End Function - Public Overrides Function CreateSwitchStatement(ifStatement As ExecutableStatementSyntax, expression As SyntaxNode, sectionList As IEnumerable(Of SyntaxNode)) As SyntaxNode + Public Overrides Function CreateSwitchStatement(ifStatement As ExecutableStatementSyntax, expression As ExpressionSyntax, sectionList As IEnumerable(Of SyntaxNode)) As SyntaxNode Return VisualBasicSyntaxGenerator.Instance.SwitchStatement(expression, sectionList) End Function diff --git a/src/Features/VisualBasic/Portable/Diagnostics/Analyzers/TypeSyntaxSimplifierWalker.vb b/src/Features/VisualBasic/Portable/Diagnostics/Analyzers/TypeSyntaxSimplifierWalker.vb index 2d4058c1dda9e..6781dabc047f9 100644 --- a/src/Features/VisualBasic/Portable/Diagnostics/Analyzers/TypeSyntaxSimplifierWalker.vb +++ b/src/Features/VisualBasic/Portable/Diagnostics/Analyzers/TypeSyntaxSimplifierWalker.vb @@ -5,9 +5,7 @@ Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Shared.Collections -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Diagnostics/Analyzers/VisualBasicSimplifyTypeNamesDiagnosticAnalyzer.vb b/src/Features/VisualBasic/Portable/Diagnostics/Analyzers/VisualBasicSimplifyTypeNamesDiagnosticAnalyzer.vb index 36f180f698934..67c79aae2001f 100644 --- a/src/Features/VisualBasic/Portable/Diagnostics/Analyzers/VisualBasicSimplifyTypeNamesDiagnosticAnalyzer.vb +++ b/src/Features/VisualBasic/Portable/Diagnostics/Analyzers/VisualBasicSimplifyTypeNamesDiagnosticAnalyzer.vb @@ -6,7 +6,6 @@ Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Shared.Collections Imports Microsoft.CodeAnalysis.SimplifyTypeNames Imports Microsoft.CodeAnalysis.Text diff --git a/src/Features/VisualBasic/Portable/EditAndContinue/DeclarationBody/FieldOrPropertyDeclarationBody.vb b/src/Features/VisualBasic/Portable/EditAndContinue/DeclarationBody/FieldOrPropertyDeclarationBody.vb index e7e60eabb1585..e5d3b5808641d 100644 --- a/src/Features/VisualBasic/Portable/EditAndContinue/DeclarationBody/FieldOrPropertyDeclarationBody.vb +++ b/src/Features/VisualBasic/Portable/EditAndContinue/DeclarationBody/FieldOrPropertyDeclarationBody.vb @@ -5,6 +5,7 @@ Imports System.Collections.Immutable Imports System.Diagnostics.CodeAnalysis Imports System.Linq.Expressions +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Differencing Imports Microsoft.CodeAnalysis.EditAndContinue Imports Microsoft.CodeAnalysis.Text diff --git a/src/Features/VisualBasic/Portable/EditAndContinue/DeclarationBody/FieldWithMultipleAsNewClauseDeclarationBody.vb b/src/Features/VisualBasic/Portable/EditAndContinue/DeclarationBody/FieldWithMultipleAsNewClauseDeclarationBody.vb index 08fa51f407f37..8de8526f2af8b 100644 --- a/src/Features/VisualBasic/Portable/EditAndContinue/DeclarationBody/FieldWithMultipleAsNewClauseDeclarationBody.vb +++ b/src/Features/VisualBasic/Portable/EditAndContinue/DeclarationBody/FieldWithMultipleAsNewClauseDeclarationBody.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.EditAndContinue Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/EditAndContinue/DeclarationBody/PropertyWithInitializerDeclarationBody.vb b/src/Features/VisualBasic/Portable/EditAndContinue/DeclarationBody/PropertyWithInitializerDeclarationBody.vb index 5385782b62afc..1f61a43696d2c 100644 --- a/src/Features/VisualBasic/Portable/EditAndContinue/DeclarationBody/PropertyWithInitializerDeclarationBody.vb +++ b/src/Features/VisualBasic/Portable/EditAndContinue/DeclarationBody/PropertyWithInitializerDeclarationBody.vb @@ -2,9 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Collections -Imports Microsoft.CodeAnalysis.EditAndContinue Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/EditAndContinue/DeclarationBody/VisualBasicLambdaBody.vb b/src/Features/VisualBasic/Portable/EditAndContinue/DeclarationBody/VisualBasicLambdaBody.vb index 518681667c72f..71a8f1115fe53 100644 --- a/src/Features/VisualBasic/Portable/EditAndContinue/DeclarationBody/VisualBasicLambdaBody.vb +++ b/src/Features/VisualBasic/Portable/EditAndContinue/DeclarationBody/VisualBasicLambdaBody.vb @@ -4,6 +4,7 @@ Imports System.Collections.Immutable Imports System.Diagnostics.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Differencing Imports Microsoft.CodeAnalysis.EditAndContinue Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/EditAndContinue/VisualBasicEditAndContinueAnalyzer.vb b/src/Features/VisualBasic/Portable/EditAndContinue/VisualBasicEditAndContinueAnalyzer.vb index 9909c246d1d95..3d92612f56957 100644 --- a/src/Features/VisualBasic/Portable/EditAndContinue/VisualBasicEditAndContinueAnalyzer.vb +++ b/src/Features/VisualBasic/Portable/EditAndContinue/VisualBasicEditAndContinueAnalyzer.vb @@ -6,12 +6,11 @@ Imports System.Collections.Immutable Imports System.Composition Imports System.Runtime.InteropServices Imports System.Threading +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Differencing Imports Microsoft.CodeAnalysis.EditAndContinue -Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.Shared.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.Analyzer.vb b/src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.Analyzer.vb index a56efd86a0e58..c17d5db3deebd 100644 --- a/src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.Analyzer.vb +++ b/src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.Analyzer.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.ExtractMethod diff --git a/src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.TriviaResult.vb b/src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.TriviaResult.vb index 13887b9b99572..e73cc88ae3b96 100644 --- a/src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.TriviaResult.vb +++ b/src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.TriviaResult.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.ExtractMethod diff --git a/src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicSyntaxTriviaService.vb b/src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicSyntaxTriviaService.vb index d842859e01178..6e265c3a08b36 100644 --- a/src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicSyntaxTriviaService.vb +++ b/src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicSyntaxTriviaService.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.ExtractMethod -Imports Microsoft.CodeAnalysis.VisualBasic.LanguageService Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod Friend Class VisualBasicSyntaxTriviaService diff --git a/src/Features/VisualBasic/Portable/FullyQualify/VisualBasicFullyQualifyService.vb b/src/Features/VisualBasic/Portable/FullyQualify/VisualBasicFullyQualifyService.vb index b48bdfc1b8be3..f61acfbfaf48b 100644 --- a/src/Features/VisualBasic/Portable/FullyQualify/VisualBasicFullyQualifyService.vb +++ b/src/Features/VisualBasic/Portable/FullyQualify/VisualBasicFullyQualifyService.vb @@ -8,7 +8,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CaseCorrection Imports Microsoft.CodeAnalysis.CodeFixes.FullyQualify -Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/GenerateMember/GenerateVariable/VisualBasicGenerateVariableService.vb b/src/Features/VisualBasic/Portable/GenerateMember/GenerateVariable/VisualBasicGenerateVariableService.vb index 4f6c25c4e8500..807453707d9c9 100644 --- a/src/Features/VisualBasic/Portable/GenerateMember/GenerateVariable/VisualBasicGenerateVariableService.vb +++ b/src/Features/VisualBasic/Portable/GenerateMember/GenerateVariable/VisualBasicGenerateVariableService.vb @@ -7,7 +7,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.GenerateMember.GenerateVariable Imports Microsoft.CodeAnalysis.Host.Mef -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/GenerateType/VisualBasicGenerateTypeService.vb b/src/Features/VisualBasic/Portable/GenerateType/VisualBasicGenerateTypeService.vb index 045323189d8d5..8d01aaf3e7c67 100644 --- a/src/Features/VisualBasic/Portable/GenerateType/VisualBasicGenerateTypeService.vb +++ b/src/Features/VisualBasic/Portable/GenerateType/VisualBasicGenerateTypeService.vb @@ -14,7 +14,6 @@ Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/InheritanceMargin/VisualBasicInheritanceMarginService.vb b/src/Features/VisualBasic/Portable/InheritanceMargin/VisualBasicInheritanceMarginService.vb index 006670e618174..2806869875b6c 100644 --- a/src/Features/VisualBasic/Portable/InheritanceMargin/VisualBasicInheritanceMarginService.vb +++ b/src/Features/VisualBasic/Portable/InheritanceMargin/VisualBasicInheritanceMarginService.vb @@ -7,7 +7,6 @@ Imports System.Composition Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.InheritanceMargin Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.InheritanceMarginService diff --git a/src/Features/VisualBasic/Portable/InitializeParameter/VisualBasicInitializeMemberFromParameterCodeRefactoringProvider.vb b/src/Features/VisualBasic/Portable/InitializeParameter/VisualBasicInitializeMemberFromParameterCodeRefactoringProvider.vb index 0190078af6fc7..49f758bd9efb4 100644 --- a/src/Features/VisualBasic/Portable/InitializeParameter/VisualBasicInitializeMemberFromParameterCodeRefactoringProvider.vb +++ b/src/Features/VisualBasic/Portable/InitializeParameter/VisualBasicInitializeMemberFromParameterCodeRefactoringProvider.vb @@ -4,7 +4,6 @@ Imports System.Composition Imports System.Diagnostics.CodeAnalysis -Imports System.Threading Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.InitializeParameter Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/InlineHints/VisualBasicInlineParameterNameHintsService.vb b/src/Features/VisualBasic/Portable/InlineHints/VisualBasicInlineParameterNameHintsService.vb index 0947303ee0d7c..d0b01a49d5456 100644 --- a/src/Features/VisualBasic/Portable/InlineHints/VisualBasicInlineParameterNameHintsService.vb +++ b/src/Features/VisualBasic/Portable/InlineHints/VisualBasicInlineParameterNameHintsService.vb @@ -7,7 +7,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.InlineHints Imports Microsoft.CodeAnalysis.LanguageService -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/IntroduceVariable/VisualBasicIntroduceLocalForExpressionCodeRefactoringProvider.vb b/src/Features/VisualBasic/Portable/IntroduceVariable/VisualBasicIntroduceLocalForExpressionCodeRefactoringProvider.vb index 5f3a1ce573cfe..880700f2c2f48 100644 --- a/src/Features/VisualBasic/Portable/IntroduceVariable/VisualBasicIntroduceLocalForExpressionCodeRefactoringProvider.vb +++ b/src/Features/VisualBasic/Portable/IntroduceVariable/VisualBasicIntroduceLocalForExpressionCodeRefactoringProvider.vb @@ -2,11 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading -Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.IntroduceVariable Imports Microsoft.CodeAnalysis.Text diff --git a/src/Features/VisualBasic/Portable/LanguageServices/VisualBasicSymbolDisplayService.SymbolDescriptionBuilder.vb b/src/Features/VisualBasic/Portable/LanguageServices/VisualBasicSymbolDisplayService.SymbolDescriptionBuilder.vb index 88528f629ff94..2f45f4a385428 100644 --- a/src/Features/VisualBasic/Portable/LanguageServices/VisualBasicSymbolDisplayService.SymbolDescriptionBuilder.vb +++ b/src/Features/VisualBasic/Portable/LanguageServices/VisualBasicSymbolDisplayService.SymbolDescriptionBuilder.vb @@ -5,7 +5,6 @@ Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Classification -Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/LanguageServices/VisualBasicSymbolDisplayService.vb b/src/Features/VisualBasic/Portable/LanguageServices/VisualBasicSymbolDisplayService.vb index 778d4fee695b2..9f075efe0ddf3 100644 --- a/src/Features/VisualBasic/Portable/LanguageServices/VisualBasicSymbolDisplayService.vb +++ b/src/Features/VisualBasic/Portable/LanguageServices/VisualBasicSymbolDisplayService.vb @@ -3,8 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading -Imports Microsoft.CodeAnalysis.Classification.Classifiers -Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.LanguageService Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LanguageServices diff --git a/src/Features/VisualBasic/Portable/MetadataAsSource/VisualBasicMetadataAsSourceService.vb b/src/Features/VisualBasic/Portable/MetadataAsSource/VisualBasicMetadataAsSourceService.vb index 0d6a04128eb5a..2bcde7aad3044 100644 --- a/src/Features/VisualBasic/Portable/MetadataAsSource/VisualBasicMetadataAsSourceService.vb +++ b/src/Features/VisualBasic/Portable/MetadataAsSource/VisualBasicMetadataAsSourceService.vb @@ -11,7 +11,6 @@ Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.MetadataAsSource Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.ChangeSignature Imports Microsoft.CodeAnalysis.VisualBasic.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/NavigationBar/VisualBasicNavigationBarItemService.vb b/src/Features/VisualBasic/Portable/NavigationBar/VisualBasicNavigationBarItemService.vb index 63c4c4033703e..8ca4f2a6c4c45 100644 --- a/src/Features/VisualBasic/Portable/NavigationBar/VisualBasicNavigationBarItemService.vb +++ b/src/Features/VisualBasic/Portable/NavigationBar/VisualBasicNavigationBarItemService.vb @@ -12,11 +12,9 @@ Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.NavigationBar.RoslynNavigationBarItem Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.NavigationBar diff --git a/src/Features/VisualBasic/Portable/QuickInfo/VisualBasicSemanticQuickInfoProvider.vb b/src/Features/VisualBasic/Portable/QuickInfo/VisualBasicSemanticQuickInfoProvider.vb index a279801a7ba31..ba863e8c3d8a1 100644 --- a/src/Features/VisualBasic/Portable/QuickInfo/VisualBasicSemanticQuickInfoProvider.vb +++ b/src/Features/VisualBasic/Portable/QuickInfo/VisualBasicSemanticQuickInfoProvider.vb @@ -4,7 +4,6 @@ Imports System.Collections.Immutable Imports System.Composition -Imports System.Diagnostics.CodeAnalysis Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis diff --git a/src/Features/VisualBasic/Portable/ReplaceConditionalWithStatementsCodeRefactoringProvider/VisualBasicReplaceConditionalWithStatementsCodeRefactoringProvider.vb b/src/Features/VisualBasic/Portable/ReplaceConditionalWithStatementsCodeRefactoringProvider/VisualBasicReplaceConditionalWithStatementsCodeRefactoringProvider.vb index fcfb609bda81d..2918ed0656ec0 100644 --- a/src/Features/VisualBasic/Portable/ReplaceConditionalWithStatementsCodeRefactoringProvider/VisualBasicReplaceConditionalWithStatementsCodeRefactoringProvider.vb +++ b/src/Features/VisualBasic/Portable/ReplaceConditionalWithStatementsCodeRefactoringProvider/VisualBasicReplaceConditionalWithStatementsCodeRefactoringProvider.vb @@ -2,11 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System Imports System.Composition -Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.VisualBasic.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Host.Mef diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/AccessorDeclarationStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/AccessorDeclarationStructureProvider.vb index 7503eb4c94722..6cab8aff56407 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/AccessorDeclarationStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/AccessorDeclarationStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/CompilationUnitStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/CompilationUnitStructureProvider.vb index 3eeb0a464ef06..792a1d6354e42 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/CompilationUnitStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/CompilationUnitStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/ConstructorDeclarationStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/ConstructorDeclarationStructureProvider.vb index dc913f7c978ea..ccfce55980215 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/ConstructorDeclarationStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/ConstructorDeclarationStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/DisabledTextTriviaStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/DisabledTextTriviaStructureProvider.vb index 7e34ae199554b..bc015631fe792 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/DisabledTextTriviaStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/DisabledTextTriviaStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.Text diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/DoLoopBlockStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/DoLoopBlockStructureProvider.vb index 5b2450693a35a..f3673581b48fa 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/DoLoopBlockStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/DoLoopBlockStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/DocumentationCommentStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/DocumentationCommentStructureProvider.vb index 0ba7f6e19e8b0..8f1c0acded6d7 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/DocumentationCommentStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/DocumentationCommentStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.LanguageService diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/EnumDeclarationStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/EnumDeclarationStructureProvider.vb index 0209d7791950f..67dbefdbc8287 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/EnumDeclarationStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/EnumDeclarationStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/EventDeclarationStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/EventDeclarationStructureProvider.vb index 57242308f18a6..b133c58f76a9b 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/EventDeclarationStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/EventDeclarationStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/ForBlockStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/ForBlockStructureProvider.vb index 6c77c281595f1..14fce9eeaeda3 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/ForBlockStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/ForBlockStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/ForEachBlockStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/ForEachBlockStructureProvider.vb index 3ee935ce92775..09c797e450ae1 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/ForEachBlockStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/ForEachBlockStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/MethodDeclarationStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/MethodDeclarationStructureProvider.vb index de808bcce7245..cd93196da4632 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/MethodDeclarationStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/MethodDeclarationStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/MultiLineIfBlockStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/MultiLineIfBlockStructureProvider.vb index 5ee042b81cc5e..0b08243199640 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/MultiLineIfBlockStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/MultiLineIfBlockStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/MultilineLambdaStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/MultilineLambdaStructureProvider.vb index ed268aeb2ada1..437b25494b49e 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/MultilineLambdaStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/MultilineLambdaStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/NamespaceDeclarationStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/NamespaceDeclarationStructureProvider.vb index 1b6be20eac78b..4affcfa1fea6c 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/NamespaceDeclarationStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/NamespaceDeclarationStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/OperatorDeclarationStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/OperatorDeclarationStructureProvider.vb index 36af439f9edfe..4515baa9c2fda 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/OperatorDeclarationStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/OperatorDeclarationStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/PropertyDeclarationStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/PropertyDeclarationStructureProvider.vb index 2a96c12a29798..b857b73e74655 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/PropertyDeclarationStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/PropertyDeclarationStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/RegionDirectiveStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/RegionDirectiveStructureProvider.vb index 3254a1baad003..bc3aa5c44b34d 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/RegionDirectiveStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/RegionDirectiveStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/SelectBlockStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/SelectBlockStructureProvider.vb index 81761336d54b1..18b43e0db1ddd 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/SelectBlockStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/SelectBlockStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/SyncLockBlockStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/SyncLockBlockStructureProvider.vb index 71b5d3cd90075..8645b7a7daffc 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/SyncLockBlockStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/SyncLockBlockStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/TryBlockStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/TryBlockStructureProvider.vb index b923e6092aeb7..93914a3dafcfa 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/TryBlockStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/TryBlockStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/TypeDeclarationStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/TypeDeclarationStructureProvider.vb index 1075d024d6ebc..1eb172614378f 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/TypeDeclarationStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/TypeDeclarationStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/UsingBlockStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/UsingBlockStructureProvider.vb index 91ade5ad536c8..80706ed31745f 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/UsingBlockStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/UsingBlockStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/WhileBlockStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/WhileBlockStructureProvider.vb index 369f9d9e2cfa0..5abc2065fd560 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/WhileBlockStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/WhileBlockStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/WithBlockStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/WithBlockStructureProvider.vb index 017c4f4f83b38..07676ea7983bc 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/WithBlockStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/WithBlockStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.Shared.Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Structure/Providers/XmlExpressionStructureProvider.vb b/src/Features/VisualBasic/Portable/Structure/Providers/XmlExpressionStructureProvider.vb index 31e9db9919c3b..4b56bf43373e1 100644 --- a/src/Features/VisualBasic/Portable/Structure/Providers/XmlExpressionStructureProvider.vb +++ b/src/Features/VisualBasic/Portable/Structure/Providers/XmlExpressionStructureProvider.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.Shared.Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Structure/VisualBasicStructureHelpers.vb b/src/Features/VisualBasic/Portable/Structure/VisualBasicStructureHelpers.vb index 3552e95a582eb..a3ad144c90c48 100644 --- a/src/Features/VisualBasic/Portable/Structure/VisualBasicStructureHelpers.vb +++ b/src/Features/VisualBasic/Portable/Structure/VisualBasicStructureHelpers.vb @@ -5,7 +5,6 @@ Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects -Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasic/Portable/Wrapping/VisualBasicSyntaxWrappingOptions.vb b/src/Features/VisualBasic/Portable/Wrapping/VisualBasicSyntaxWrappingOptions.vb index 208eb02146516..692258d749a44 100644 --- a/src/Features/VisualBasic/Portable/Wrapping/VisualBasicSyntaxWrappingOptions.vb +++ b/src/Features/VisualBasic/Portable/Wrapping/VisualBasicSyntaxWrappingOptions.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.Formatting diff --git a/src/Features/VisualBasic/Portable/Wrapping/VisualBasicWrappingCodeRefactoringProvider.vb b/src/Features/VisualBasic/Portable/Wrapping/VisualBasicWrappingCodeRefactoringProvider.vb index ffa3ba31ba2f3..6dad584bdf892 100644 --- a/src/Features/VisualBasic/Portable/Wrapping/VisualBasicWrappingCodeRefactoringProvider.vb +++ b/src/Features/VisualBasic/Portable/Wrapping/VisualBasicWrappingCodeRefactoringProvider.vb @@ -5,9 +5,7 @@ Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.Wrapping.BinaryExpression Imports Microsoft.CodeAnalysis.VisualBasic.Wrapping.ChainedExpression diff --git a/src/Features/VisualBasicTest/AddAwait/AddAwaitTests.vb b/src/Features/VisualBasicTest/AddAwait/AddAwaitTests.vb index 6b169707d3187..1d4a06badc926 100644 --- a/src/Features/VisualBasicTest/AddAwait/AddAwaitTests.vb +++ b/src/Features/VisualBasicTest/AddAwait/AddAwaitTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings.AddAwait Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings.AddAwait diff --git a/src/Features/VisualBasicTest/AddFileBanner/AddFileBannerTests.vb b/src/Features/VisualBasicTest/AddFileBanner/AddFileBannerTests.vb index 7c94261af5de3..8fbc850716377 100644 --- a/src/Features/VisualBasicTest/AddFileBanner/AddFileBannerTests.vb +++ b/src/Features/VisualBasicTest/AddFileBanner/AddFileBannerTests.vb @@ -2,13 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.VisualBasic.AddFileBanner Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings -Imports Roslyn.Test.Utilities -Imports Xunit -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces +Imports Microsoft.CodeAnalysis.VisualBasic.AddFileBanner Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AddFileBanner diff --git a/src/Features/VisualBasicTest/CodeActions/AbstractVisualBasicCodeActionTest_NoEditor.vb b/src/Features/VisualBasicTest/CodeActions/AbstractVisualBasicCodeActionTest_NoEditor.vb index 3373cd2cba8f3..d708b0fd47e28 100644 --- a/src/Features/VisualBasicTest/CodeActions/AbstractVisualBasicCodeActionTest_NoEditor.vb +++ b/src/Features/VisualBasicTest/CodeActions/AbstractVisualBasicCodeActionTest_NoEditor.vb @@ -2,9 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings diff --git a/src/Features/VisualBasicTest/ConvertAnonymousType/ConvertAnonymousTypeToClassTests.vb b/src/Features/VisualBasicTest/ConvertAnonymousType/ConvertAnonymousTypeToClassTests.vb index 942b7f492b408..aac7dd9656e9f 100644 --- a/src/Features/VisualBasicTest/ConvertAnonymousType/ConvertAnonymousTypeToClassTests.vb +++ b/src/Features/VisualBasicTest/ConvertAnonymousType/ConvertAnonymousTypeToClassTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.ConvertAnonymousType diff --git a/src/Features/VisualBasicTest/ConvertAnonymousType/ConvertAnonymousTypeToTupleTests.vb b/src/Features/VisualBasicTest/ConvertAnonymousType/ConvertAnonymousTypeToTupleTests.vb index ebc4d009d7fad..d5f8210db221a 100644 --- a/src/Features/VisualBasicTest/ConvertAnonymousType/ConvertAnonymousTypeToTupleTests.vb +++ b/src/Features/VisualBasicTest/ConvertAnonymousType/ConvertAnonymousTypeToTupleTests.vb @@ -5,7 +5,6 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.ConvertAnonymousTypeToTuple diff --git a/src/Features/VisualBasicTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests.vb b/src/Features/VisualBasicTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests.vb index 797c8dd9d8aa7..9c6a5ea59ad05 100644 --- a/src/Features/VisualBasicTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests.vb +++ b/src/Features/VisualBasicTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.ConvertAutoPropertyToFullProperty diff --git a/src/Features/VisualBasicTest/ConvertForEachToFor/ConvertForEachToForTests.vb b/src/Features/VisualBasicTest/ConvertForEachToFor/ConvertForEachToForTests.vb index bfa9b53d17290..02a2cbf438701 100644 --- a/src/Features/VisualBasicTest/ConvertForEachToFor/ConvertForEachToForTests.vb +++ b/src/Features/VisualBasicTest/ConvertForEachToFor/ConvertForEachToForTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.ConvertForEachToFor diff --git a/src/Features/VisualBasicTest/ConvertForToForEach/ConvertForToForEachTests.vb b/src/Features/VisualBasicTest/ConvertForToForEach/ConvertForToForEachTests.vb index 8934355a40b6b..43f9db6f3c63c 100644 --- a/src/Features/VisualBasicTest/ConvertForToForEach/ConvertForToForEachTests.vb +++ b/src/Features/VisualBasicTest/ConvertForToForEach/ConvertForToForEachTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.ConvertForToForEach diff --git a/src/Features/VisualBasicTest/ConvertIfToSwitch/ConvertIfToSwitchFixAllTests.vb b/src/Features/VisualBasicTest/ConvertIfToSwitch/ConvertIfToSwitchFixAllTests.vb index cbe2521ea5b3e..f0eee23d898dd 100644 --- a/src/Features/VisualBasicTest/ConvertIfToSwitch/ConvertIfToSwitchFixAllTests.vb +++ b/src/Features/VisualBasicTest/ConvertIfToSwitch/ConvertIfToSwitchFixAllTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.ConvertIfToSwitch diff --git a/src/Features/VisualBasicTest/ConvertIfToSwitch/ConvertIfToSwitchTests.vb b/src/Features/VisualBasicTest/ConvertIfToSwitch/ConvertIfToSwitchTests.vb index bc12b78fe257e..b99e0d41cffba 100644 --- a/src/Features/VisualBasicTest/ConvertIfToSwitch/ConvertIfToSwitchTests.vb +++ b/src/Features/VisualBasicTest/ConvertIfToSwitch/ConvertIfToSwitchTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.ConvertIfToSwitch diff --git a/src/Features/VisualBasicTest/ConvertNumericLiteral/ConvertNumericLiteralTests.vb b/src/Features/VisualBasicTest/ConvertNumericLiteral/ConvertNumericLiteralTests.vb index cacae58c3d80a..fc3812c43f6dc 100644 --- a/src/Features/VisualBasicTest/ConvertNumericLiteral/ConvertNumericLiteralTests.vb +++ b/src/Features/VisualBasicTest/ConvertNumericLiteral/ConvertNumericLiteralTests.vb @@ -5,7 +5,6 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.ConvertNumericLiteral diff --git a/src/Features/VisualBasicTest/ConvertToInterpolatedString/ConvertPlaceholderToInterpolatedStringTests.vb b/src/Features/VisualBasicTest/ConvertToInterpolatedString/ConvertPlaceholderToInterpolatedStringTests.vb index 624f6c7d9a8fb..6ad1f418868aa 100644 --- a/src/Features/VisualBasicTest/ConvertToInterpolatedString/ConvertPlaceholderToInterpolatedStringTests.vb +++ b/src/Features/VisualBasicTest/ConvertToInterpolatedString/ConvertPlaceholderToInterpolatedStringTests.vb @@ -2,9 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.ConvertToInterpolatedString diff --git a/src/Features/VisualBasicTest/ConvertToInterpolatedString/ConvertRegularStringToInterpolatedStringTests.vb b/src/Features/VisualBasicTest/ConvertToInterpolatedString/ConvertRegularStringToInterpolatedStringTests.vb index 6866aba463770..046b73453da71 100644 --- a/src/Features/VisualBasicTest/ConvertToInterpolatedString/ConvertRegularStringToInterpolatedStringTests.vb +++ b/src/Features/VisualBasicTest/ConvertToInterpolatedString/ConvertRegularStringToInterpolatedStringTests.vb @@ -4,7 +4,6 @@ Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.ConvertToInterpolatedString -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertToInterpolatedString diff --git a/src/Features/VisualBasicTest/ConvertTupleToStruct/ConvertTupleToStructTests.vb b/src/Features/VisualBasicTest/ConvertTupleToStruct/ConvertTupleToStructTests.vb index 57e7d0e7e247e..aa718a75e3cbf 100644 --- a/src/Features/VisualBasicTest/ConvertTupleToStruct/ConvertTupleToStructTests.vb +++ b/src/Features/VisualBasicTest/ConvertTupleToStruct/ConvertTupleToStructTests.vb @@ -8,12 +8,12 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.ConvertTupleToStruct Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.VisualBasic.ConvertTupleToStruct - Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeRefactoringVerifier(Of Microsoft.CodeAnalysis.VisualBasic.ConvertTupleToStruct.VisualBasicConvertTupleToStructCodeRefactoringProvider) diff --git a/src/Features/VisualBasicTest/Diagnostics/AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest_NoEditor.vb b/src/Features/VisualBasicTest/Diagnostics/AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest_NoEditor.vb index 279b58ab310ff..839245c93915a 100644 --- a/src/Features/VisualBasicTest/Diagnostics/AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest_NoEditor.vb +++ b/src/Features/VisualBasicTest/Diagnostics/AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest_NoEditor.vb @@ -2,9 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions +Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics Imports Xunit.Abstractions Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics diff --git a/src/Features/VisualBasicTest/Diagnostics/Configuration/ConfigureCodeStyle/BooleanCodeStyleOptionConfigurationTests.vb b/src/Features/VisualBasicTest/Diagnostics/Configuration/ConfigureCodeStyle/BooleanCodeStyleOptionConfigurationTests.vb index 23ac7f30e5f73..be9f093872c78 100644 --- a/src/Features/VisualBasicTest/Diagnostics/Configuration/ConfigureCodeStyle/BooleanCodeStyleOptionConfigurationTests.vb +++ b/src/Features/VisualBasicTest/Diagnostics/Configuration/ConfigureCodeStyle/BooleanCodeStyleOptionConfigurationTests.vb @@ -6,7 +6,6 @@ Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureCodeStyle Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.VisualBasic.UseObjectInitializer Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.Configuration.ConfigureCodeStyle diff --git a/src/Features/VisualBasicTest/Diagnostics/Configuration/ConfigureSeverity/CodeStyleOptionBasedSeverityConfigurationTests.vb b/src/Features/VisualBasicTest/Diagnostics/Configuration/ConfigureSeverity/CodeStyleOptionBasedSeverityConfigurationTests.vb index f68d01eb5ef52..378bc4d26aa4d 100644 --- a/src/Features/VisualBasicTest/Diagnostics/Configuration/ConfigureSeverity/CodeStyleOptionBasedSeverityConfigurationTests.vb +++ b/src/Features/VisualBasicTest/Diagnostics/Configuration/ConfigureSeverity/CodeStyleOptionBasedSeverityConfigurationTests.vb @@ -6,7 +6,6 @@ Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureSeverity Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.VisualBasic.UseObjectInitializer Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.Configuration.ConfigureSeverity diff --git a/src/Features/VisualBasicTest/Diagnostics/Configuration/ConfigureSeverity/DotNetDiagnosticSeverityBasedSeverityConfigurationTests.vb b/src/Features/VisualBasicTest/Diagnostics/Configuration/ConfigureSeverity/DotNetDiagnosticSeverityBasedSeverityConfigurationTests.vb index a106c95ff945d..c58fb95fd0023 100644 --- a/src/Features/VisualBasicTest/Diagnostics/Configuration/ConfigureSeverity/DotNetDiagnosticSeverityBasedSeverityConfigurationTests.vb +++ b/src/Features/VisualBasicTest/Diagnostics/Configuration/ConfigureSeverity/DotNetDiagnosticSeverityBasedSeverityConfigurationTests.vb @@ -7,7 +7,6 @@ Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureSeverity Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.Configuration.ConfigureSeverity Partial Public MustInherit Class DotNetDiagnosticSeverityBasedSeverityConfigurationTests diff --git a/src/Features/VisualBasicTest/Diagnostics/Suppression/RemoveUnnecessaryPragmaSuppressionsTests.vb b/src/Features/VisualBasicTest/Diagnostics/Suppression/RemoveUnnecessaryPragmaSuppressionsTests.vb index 869f3d47f3494..fec5ba16b52df 100644 --- a/src/Features/VisualBasicTest/Diagnostics/Suppression/RemoveUnnecessaryPragmaSuppressionsTests.vb +++ b/src/Features/VisualBasicTest/Diagnostics/Suppression/RemoveUnnecessaryPragmaSuppressionsTests.vb @@ -8,7 +8,6 @@ Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Diagnostics.VisualBasic Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions Imports Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessarySuppressions @@ -19,7 +18,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.Remove Public NotInheritable Class RemoveUnnecessaryInlineSuppressionsTests - Inherits AbstractUnncessarySuppressionDiagnosticTest + Inherits AbstractUnnecessarySuppressionDiagnosticTest Public Sub New(logger As ITestOutputHelper) MyBase.New(logger) diff --git a/src/Features/VisualBasicTest/Diagnostics/Suppression/SuppressionAllCodeTests.vb b/src/Features/VisualBasicTest/Diagnostics/Suppression/SuppressionAllCodeTests.vb index 56ec53542f7ee..d9f591d49ebaa 100644 --- a/src/Features/VisualBasicTest/Diagnostics/Suppression/SuppressionAllCodeTests.vb +++ b/src/Features/VisualBasicTest/Diagnostics/Suppression/SuppressionAllCodeTests.vb @@ -4,9 +4,7 @@ Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.Suppression Imports Microsoft.CodeAnalysis.VisualBasic.LanguageService Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasicTest/Diagnostics/Suppression/SuppressionTests.vb b/src/Features/VisualBasicTest/Diagnostics/Suppression/SuppressionTests.vb index a6740f8e05a34..760033ffa241f 100644 --- a/src/Features/VisualBasicTest/Diagnostics/Suppression/SuppressionTests.vb +++ b/src/Features/VisualBasicTest/Diagnostics/Suppression/SuppressionTests.vb @@ -7,7 +7,6 @@ Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.SimplifyTypeNames Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.Suppression Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Features/VisualBasicTest/EditAndContinue/BreakpointSpansTests.vb b/src/Features/VisualBasicTest/EditAndContinue/BreakpointSpansTests.vb index 03605baee15d8..554a69d70d2d1 100644 --- a/src/Features/VisualBasicTest/EditAndContinue/BreakpointSpansTests.vb +++ b/src/Features/VisualBasicTest/EditAndContinue/BreakpointSpansTests.vb @@ -4,7 +4,6 @@ Imports System.Collections.Immutable Imports System.Threading -Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Text diff --git a/src/Features/VisualBasicTest/EditAndContinue/Helpers/EditAndContinueValidation.vb b/src/Features/VisualBasicTest/EditAndContinue/Helpers/EditAndContinueValidation.vb index da54fa31538ff..d7610a2cede50 100644 --- a/src/Features/VisualBasicTest/EditAndContinue/Helpers/EditAndContinueValidation.vb +++ b/src/Features/VisualBasicTest/EditAndContinue/Helpers/EditAndContinueValidation.vb @@ -4,9 +4,8 @@ Imports System.Collections.Immutable Imports System.Runtime.CompilerServices -Imports Microsoft.CodeAnalysis.Differencing -Imports Microsoft.CodeAnalysis.EditAndContinue Imports Microsoft.CodeAnalysis.Contracts.EditAndContinue +Imports Microsoft.CodeAnalysis.EditAndContinue Imports Microsoft.CodeAnalysis.EditAndContinue.UnitTests Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EditAndContinue diff --git a/src/Features/VisualBasicTest/EditAndContinue/Helpers/EditingTestBase.vb b/src/Features/VisualBasicTest/EditAndContinue/Helpers/EditingTestBase.vb index 25da7ef68dae2..3b5dcd8fa1ef6 100644 --- a/src/Features/VisualBasicTest/EditAndContinue/Helpers/EditingTestBase.vb +++ b/src/Features/VisualBasicTest/EditAndContinue/Helpers/EditingTestBase.vb @@ -2,17 +2,13 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.Immutable Imports System.IO +Imports Microsoft.CodeAnalysis.Contracts.EditAndContinue Imports Microsoft.CodeAnalysis.Differencing Imports Microsoft.CodeAnalysis.EditAndContinue -Imports Microsoft.CodeAnalysis.Contracts.EditAndContinue Imports Microsoft.CodeAnalysis.EditAndContinue.UnitTests -Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EditAndContinue Imports Microsoft.CodeAnalysis.Emit -Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue.UnitTests diff --git a/src/Features/VisualBasicTest/EditAndContinue/LineEditTests.vb b/src/Features/VisualBasicTest/EditAndContinue/LineEditTests.vb index 48948bf401f1d..25ba90fd229e6 100644 --- a/src/Features/VisualBasicTest/EditAndContinue/LineEditTests.vb +++ b/src/Features/VisualBasicTest/EditAndContinue/LineEditTests.vb @@ -3,9 +3,8 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.Xml.Linq -Imports Microsoft.CodeAnalysis.EditAndContinue Imports Microsoft.CodeAnalysis.Contracts.EditAndContinue +Imports Microsoft.CodeAnalysis.EditAndContinue Imports Microsoft.CodeAnalysis.EditAndContinue.UnitTests Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols diff --git a/src/Features/VisualBasicTest/EditAndContinue/StatementMatchingTests.vb b/src/Features/VisualBasicTest/EditAndContinue/StatementMatchingTests.vb index 30e564337e52e..26dfeea02d19d 100644 --- a/src/Features/VisualBasicTest/EditAndContinue/StatementMatchingTests.vb +++ b/src/Features/VisualBasicTest/EditAndContinue/StatementMatchingTests.vb @@ -2,11 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.EditAndContinue Imports Microsoft.CodeAnalysis.EditAndContinue.UnitTests -Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EditAndContinue -Imports Microsoft.CodeAnalysis.Emit -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue.UnitTests diff --git a/src/Features/VisualBasicTest/EditAndContinue/SyntaxUtilitiesTests.vb b/src/Features/VisualBasicTest/EditAndContinue/SyntaxUtilitiesTests.vb index d919d44b32ec1..100eeccfdc4c0 100644 --- a/src/Features/VisualBasicTest/EditAndContinue/SyntaxUtilitiesTests.vb +++ b/src/Features/VisualBasicTest/EditAndContinue/SyntaxUtilitiesTests.vb @@ -4,7 +4,6 @@ Imports Microsoft.CodeAnalysis.EditAndContinue Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Imports SyntaxUtilities = Microsoft.CodeAnalysis.VisualBasic.EditAndContinue.SyntaxUtilities Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EditAndContinue diff --git a/src/Features/VisualBasicTest/EditAndContinue/TopLevelEditingTests.vb b/src/Features/VisualBasicTest/EditAndContinue/TopLevelEditingTests.vb index 3f44ab0582d53..6d5344244252e 100644 --- a/src/Features/VisualBasicTest/EditAndContinue/TopLevelEditingTests.vb +++ b/src/Features/VisualBasicTest/EditAndContinue/TopLevelEditingTests.vb @@ -2,6 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Differencing Imports Microsoft.CodeAnalysis.EditAndContinue Imports Microsoft.CodeAnalysis.EditAndContinue.UnitTests diff --git a/src/Features/VisualBasicTest/EditAndContinue/VisualBasicEditAndContinueAnalyzerTests.vb b/src/Features/VisualBasicTest/EditAndContinue/VisualBasicEditAndContinueAnalyzerTests.vb index f1ead256fbb56..2782938711522 100644 --- a/src/Features/VisualBasicTest/EditAndContinue/VisualBasicEditAndContinueAnalyzerTests.vb +++ b/src/Features/VisualBasicTest/EditAndContinue/VisualBasicEditAndContinueAnalyzerTests.vb @@ -4,7 +4,6 @@ Imports System.Collections.Immutable Imports System.IO -Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis.Contracts.EditAndContinue Imports Microsoft.CodeAnalysis.Differencing @@ -88,7 +87,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue.UnitTests source.IndexOf(s_endSpanMark, start, length, StringComparison.Ordinal)) End If - Yield KeyValuePairUtil.Create(position, span) + Yield KeyValuePair.Create(position, span) i = [end] + 1 End While End Function @@ -481,7 +480,7 @@ End Class Dim baseActiveStatements = New ActiveStatementsMap( ImmutableDictionary.CreateRange( { - KeyValuePairUtil.Create(newDocument.FilePath, ImmutableArray.Create( + KeyValuePair.Create(newDocument.FilePath, ImmutableArray.Create( New ActiveStatement( New ActiveStatementId(0), ActiveStatementFlags.LeafFrame, diff --git a/src/Features/VisualBasicTest/EncapsulateField/EncapsulateFieldTests.vb b/src/Features/VisualBasicTest/EncapsulateField/EncapsulateFieldTests.vb index 56ae723fecad2..cdaf3da746fa3 100644 --- a/src/Features/VisualBasicTest/EncapsulateField/EncapsulateFieldTests.vb +++ b/src/Features/VisualBasicTest/EncapsulateField/EncapsulateFieldTests.vb @@ -5,7 +5,6 @@ Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.EncapsulateField Imports Microsoft.CodeAnalysis.Remote.Testing diff --git a/src/Features/VisualBasicTest/GenerateComparisonOperators/GenerateComparisonOperatorsTests.vb b/src/Features/VisualBasicTest/GenerateComparisonOperators/GenerateComparisonOperatorsTests.vb index 98f00a94878af..12987f0d95b1b 100644 --- a/src/Features/VisualBasicTest/GenerateComparisonOperators/GenerateComparisonOperatorsTests.vb +++ b/src/Features/VisualBasicTest/GenerateComparisonOperators/GenerateComparisonOperatorsTests.vb @@ -5,7 +5,6 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.GenerateComparisonOperators diff --git a/src/Features/VisualBasicTest/GenerateEndConstruct/GenerateEndConstructTests.vb b/src/Features/VisualBasicTest/GenerateEndConstruct/GenerateEndConstructTests.vb index f9cf9a606858f..eb89679cfba6d 100644 --- a/src/Features/VisualBasicTest/GenerateEndConstruct/GenerateEndConstructTests.vb +++ b/src/Features/VisualBasicTest/GenerateEndConstruct/GenerateEndConstructTests.vb @@ -3,8 +3,8 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateEndConstruct Imports Microsoft.CodeAnalysis.Diagnostics +Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateEndConstruct Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.GenerateEndConstruct diff --git a/src/Features/VisualBasicTest/GenerateEvent/GenerateEventTests.vb b/src/Features/VisualBasicTest/GenerateEvent/GenerateEventTests.vb index 3c38ce5545504..d1159fceb74f8 100644 --- a/src/Features/VisualBasicTest/GenerateEvent/GenerateEventTests.vb +++ b/src/Features/VisualBasicTest/GenerateEvent/GenerateEventTests.vb @@ -2,10 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateEvent Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions +Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateEvent Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.GenerateEvent diff --git a/src/Features/VisualBasicTest/GenerateMethod/GenerateMethodTests.vb b/src/Features/VisualBasicTest/GenerateMethod/GenerateMethodTests.vb index 1a3b7dab5f8b6..16a3419d88e40 100644 --- a/src/Features/VisualBasicTest/GenerateMethod/GenerateMethodTests.vb +++ b/src/Features/VisualBasicTest/GenerateMethod/GenerateMethodTests.vb @@ -3,8 +3,8 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateMethod Imports Microsoft.CodeAnalysis.Diagnostics +Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateMethod Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.GenerateMethod diff --git a/src/Features/VisualBasicTest/GenerateVariable/GenerateVariableTests.vb b/src/Features/VisualBasicTest/GenerateVariable/GenerateVariableTests.vb index ff58f72d0e3ca..98cd44d1cfff9 100644 --- a/src/Features/VisualBasicTest/GenerateVariable/GenerateVariableTests.vb +++ b/src/Features/VisualBasicTest/GenerateVariable/GenerateVariableTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics diff --git a/src/Features/VisualBasicTest/InlineTemporary/InlineTemporaryTests.vb b/src/Features/VisualBasicTest/InlineTemporary/InlineTemporaryTests.vb index b9ffc5c84c440..753a4d401f7a4 100644 --- a/src/Features/VisualBasicTest/InlineTemporary/InlineTemporaryTests.vb +++ b/src/Features/VisualBasicTest/InlineTemporary/InlineTemporaryTests.vb @@ -3,8 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.CSharp.UnitTests -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.UnitTests Imports Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings.InlineTemporary diff --git a/src/Features/VisualBasicTest/IntroduceParameter/IntroduceParameterTests.vb b/src/Features/VisualBasicTest/IntroduceParameter/IntroduceParameterTests.vb index 38b472581cd5c..7d1ec1acd0635 100644 --- a/src/Features/VisualBasicTest/IntroduceParameter/IntroduceParameterTests.vb +++ b/src/Features/VisualBasicTest/IntroduceParameter/IntroduceParameterTests.vb @@ -2,11 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis.CodeActions -Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.VisualBasic.IntroduceVariable - Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeRefactoringVerifier(Of Microsoft.CodeAnalysis.VisualBasic.IntroduceParameter.VisualBasicIntroduceParameterCodeRefactoringProvider) diff --git a/src/Features/VisualBasicTest/IntroduceVariable/IntroduceLocalForExpressionTests.vb b/src/Features/VisualBasicTest/IntroduceVariable/IntroduceLocalForExpressionTests.vb index a4f1cf1c9c93f..29199eee59f8f 100644 --- a/src/Features/VisualBasicTest/IntroduceVariable/IntroduceLocalForExpressionTests.vb +++ b/src/Features/VisualBasicTest/IntroduceVariable/IntroduceLocalForExpressionTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.IntroduceVariable diff --git a/src/Features/VisualBasicTest/IntroduceVariable/IntroduceVariableTests.vb b/src/Features/VisualBasicTest/IntroduceVariable/IntroduceVariableTests.vb index 36a3b3f1c196a..b1f7be828262d 100644 --- a/src/Features/VisualBasicTest/IntroduceVariable/IntroduceVariableTests.vb +++ b/src/Features/VisualBasicTest/IntroduceVariable/IntroduceVariableTests.vb @@ -5,7 +5,6 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.IntroduceVariable Imports Microsoft.CodeAnalysis.UnitTests diff --git a/src/Features/VisualBasicTest/InvertConditional/InvertConditionalTests.vb b/src/Features/VisualBasicTest/InvertConditional/InvertConditionalTests.vb index a7d0e1424be25..425e19b6dc5de 100644 --- a/src/Features/VisualBasicTest/InvertConditional/InvertConditionalTests.vb +++ b/src/Features/VisualBasicTest/InvertConditional/InvertConditionalTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.InvertConditional diff --git a/src/Features/VisualBasicTest/InvertLogical/InvertLogicalTests.vb b/src/Features/VisualBasicTest/InvertLogical/InvertLogicalTests.vb index cdb5d3c2b57f4..95135d3950387 100644 --- a/src/Features/VisualBasicTest/InvertLogical/InvertLogicalTests.vb +++ b/src/Features/VisualBasicTest/InvertLogical/InvertLogicalTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.InvertLogical diff --git a/src/Features/VisualBasicTest/MoveDeclarationNearReference/MoveDeclarationNearReferenceTests.vb b/src/Features/VisualBasicTest/MoveDeclarationNearReference/MoveDeclarationNearReferenceTests.vb index 1f27f756f3196..3f0a990a2f1d5 100644 --- a/src/Features/VisualBasicTest/MoveDeclarationNearReference/MoveDeclarationNearReferenceTests.vb +++ b/src/Features/VisualBasicTest/MoveDeclarationNearReference/MoveDeclarationNearReferenceTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.MoveDeclarationNearReference diff --git a/src/Features/VisualBasicTest/NameTupleElement/NameTupleElementTests.vb b/src/Features/VisualBasicTest/NameTupleElement/NameTupleElementTests.vb index ea14b6c140afa..75bdb36ad61ed 100644 --- a/src/Features/VisualBasicTest/NameTupleElement/NameTupleElementTests.vb +++ b/src/Features/VisualBasicTest/NameTupleElement/NameTupleElementTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.NameTupleElement diff --git a/src/Features/VisualBasicTest/ReplaceConditionalWithStatements/ReplaceConditionalWithStatementsTests.vb b/src/Features/VisualBasicTest/ReplaceConditionalWithStatements/ReplaceConditionalWithStatementsTests.vb index c94569a532656..72dff8016e031 100644 --- a/src/Features/VisualBasicTest/ReplaceConditionalWithStatements/ReplaceConditionalWithStatementsTests.vb +++ b/src/Features/VisualBasicTest/ReplaceConditionalWithStatements/ReplaceConditionalWithStatementsTests.vb @@ -2,15 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System -Imports System.Collections.Generic -Imports System.Linq -Imports System.Text -Imports System.Threading.Tasks -Imports Microsoft.CodeAnalysis.VisualBasic.ReplaceConditionalWithStatements -Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions -Imports Xunit - Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeRefactoringVerifier(Of Microsoft.CodeAnalysis.VisualBasic.ReplaceConditionalWithStatements.VisualBasicReplaceConditionalWithStatementsCodeRefactoringProvider) diff --git a/src/Features/VisualBasicTest/ReplaceDocCommentTextWithTag/ReplaceDocCommentTextWithTagTests.vb b/src/Features/VisualBasicTest/ReplaceDocCommentTextWithTag/ReplaceDocCommentTextWithTagTests.vb index 949483900a25d..46f613507a3c0 100644 --- a/src/Features/VisualBasicTest/ReplaceDocCommentTextWithTag/ReplaceDocCommentTextWithTagTests.vb +++ b/src/Features/VisualBasicTest/ReplaceDocCommentTextWithTag/ReplaceDocCommentTextWithTagTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.ReplaceDocCommentTextWithTag diff --git a/src/Features/VisualBasicTest/ReplaceMethodWithProperty/ReplaceMethodWithPropertyTests.vb b/src/Features/VisualBasicTest/ReplaceMethodWithProperty/ReplaceMethodWithPropertyTests.vb index d5a9b7974cc84..537eb48f42844 100644 --- a/src/Features/VisualBasicTest/ReplaceMethodWithProperty/ReplaceMethodWithPropertyTests.vb +++ b/src/Features/VisualBasicTest/ReplaceMethodWithProperty/ReplaceMethodWithPropertyTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.ReplaceMethodWithProperty diff --git a/src/Features/VisualBasicTest/ReplacePropertyWithMethods/ReplacePropertyWithMethodsTests.vb b/src/Features/VisualBasicTest/ReplacePropertyWithMethods/ReplacePropertyWithMethodsTests.vb index f8708bdae47ea..fe7c9d8b76edf 100644 --- a/src/Features/VisualBasicTest/ReplacePropertyWithMethods/ReplacePropertyWithMethodsTests.vb +++ b/src/Features/VisualBasicTest/ReplacePropertyWithMethods/ReplacePropertyWithMethodsTests.vb @@ -3,13 +3,12 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.ReplacePropertyWithMethods Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeActions.ReplacePropertyWithMethods - Public Class ReplacePropertyWithMethodsTests + Public NotInheritable Class ReplacePropertyWithMethodsTests Inherits AbstractVisualBasicCodeActionTest_NoEditor Protected Overrides Function CreateCodeRefactoringProvider(workspace As TestWorkspace, parameters As TestParameters) As CodeRefactoringProvider @@ -699,5 +698,24 @@ Class C End Sub End Class") End Function + + + Public Async Function TestPropertyNameReferencedInAsClause() As Task + Await TestInRegularAndScriptAsync( +"class C + property [||]Goo as Goo +end class", +"class C + Private _Goo As Goo + + Public Function GetGoo() As Goo + Return _Goo + End Function + + Public Sub SetGoo(AutoPropertyValue As Goo) + _Goo = AutoPropertyValue + End Sub +end class") + End Function End Class End Namespace diff --git a/src/Features/VisualBasicTest/SimplifyTypeNames/SimplifyTypeNamesTests.vb b/src/Features/VisualBasicTest/SimplifyTypeNames/SimplifyTypeNamesTests.vb index 9ee02703f1680..e017f9b785165 100644 --- a/src/Features/VisualBasicTest/SimplifyTypeNames/SimplifyTypeNamesTests.vb +++ b/src/Features/VisualBasicTest/SimplifyTypeNames/SimplifyTypeNamesTests.vb @@ -6,8 +6,6 @@ Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.SimplifyTypeNames diff --git a/src/Features/VisualBasicTest/SimplifyTypeNames/SimplifyTypeNamesTests_FixAllTests.vb b/src/Features/VisualBasicTest/SimplifyTypeNames/SimplifyTypeNamesTests_FixAllTests.vb index 760b28960848c..948f21a7bad03 100644 --- a/src/Features/VisualBasicTest/SimplifyTypeNames/SimplifyTypeNamesTests_FixAllTests.vb +++ b/src/Features/VisualBasicTest/SimplifyTypeNames/SimplifyTypeNamesTests_FixAllTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SimplifyTypeNames diff --git a/src/Features/VisualBasicTest/SpellCheck/SpellCheckTests.vb b/src/Features/VisualBasicTest/SpellCheck/SpellCheckTests.vb index 6f226acee74f7..09f9bd6ffc877 100644 --- a/src/Features/VisualBasicTest/SpellCheck/SpellCheckTests.vb +++ b/src/Features/VisualBasicTest/SpellCheck/SpellCheckTests.vb @@ -7,8 +7,8 @@ Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions -Imports Microsoft.CodeAnalysis.VisualBasic.SpellCheck Imports Microsoft.CodeAnalysis.VisualBasic.Diagnostics +Imports Microsoft.CodeAnalysis.VisualBasic.SpellCheck Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.Spellcheck diff --git a/src/Features/VisualBasicTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_ElseIf_WithPrevious.vb b/src/Features/VisualBasicTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_ElseIf_WithPrevious.vb index 671b4bc50ed0f..4d1c9a6c324a6 100644 --- a/src/Features/VisualBasicTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_ElseIf_WithPrevious.vb +++ b/src/Features/VisualBasicTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_ElseIf_WithPrevious.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.SplitOrMergeIfStatements diff --git a/src/Features/VisualBasicTest/SplitOrMergeIfStatements/MergeNestedIfStatementsTests_WithOuter.vb b/src/Features/VisualBasicTest/SplitOrMergeIfStatements/MergeNestedIfStatementsTests_WithOuter.vb index 04b6e8d4db85a..a21877d6492d8 100644 --- a/src/Features/VisualBasicTest/SplitOrMergeIfStatements/MergeNestedIfStatementsTests_WithOuter.vb +++ b/src/Features/VisualBasicTest/SplitOrMergeIfStatements/MergeNestedIfStatementsTests_WithOuter.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.SplitOrMergeIfStatements diff --git a/src/Features/VisualBasicTest/SplitOrMergeIfStatements/SplitIntoConsecutiveIfStatementsTests.vb b/src/Features/VisualBasicTest/SplitOrMergeIfStatements/SplitIntoConsecutiveIfStatementsTests.vb index 8f394a3efd897..048f606226c51 100644 --- a/src/Features/VisualBasicTest/SplitOrMergeIfStatements/SplitIntoConsecutiveIfStatementsTests.vb +++ b/src/Features/VisualBasicTest/SplitOrMergeIfStatements/SplitIntoConsecutiveIfStatementsTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.SplitOrMergeIfStatements diff --git a/src/Features/VisualBasicTest/SplitOrMergeIfStatements/SplitIntoNestedIfStatementsTests.vb b/src/Features/VisualBasicTest/SplitOrMergeIfStatements/SplitIntoNestedIfStatementsTests.vb index 34f255733bd80..46173a302d010 100644 --- a/src/Features/VisualBasicTest/SplitOrMergeIfStatements/SplitIntoNestedIfStatementsTests.vb +++ b/src/Features/VisualBasicTest/SplitOrMergeIfStatements/SplitIntoNestedIfStatementsTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.SplitOrMergeIfStatements diff --git a/src/Features/VisualBasicTest/UseNamedArguments/UseNamedArgumentsTests.vb b/src/Features/VisualBasicTest/UseNamedArguments/UseNamedArgumentsTests.vb index 1dacca7333231..7e4c7e20705f2 100644 --- a/src/Features/VisualBasicTest/UseNamedArguments/UseNamedArgumentsTests.vb +++ b/src/Features/VisualBasicTest/UseNamedArguments/UseNamedArgumentsTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.UseNamedArguments diff --git a/src/Features/VisualBasicTest/Wrapping/AbstractParameterWrappingTests.vb b/src/Features/VisualBasicTest/Wrapping/AbstractParameterWrappingTests.vb index d08fdb3a78705..ceabfb177b9ac 100644 --- a/src/Features/VisualBasicTest/Wrapping/AbstractParameterWrappingTests.vb +++ b/src/Features/VisualBasicTest/Wrapping/AbstractParameterWrappingTests.vb @@ -5,7 +5,6 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.VisualBasic.Wrapping diff --git a/src/Features/VisualBasicTest/Wrapping/ArgumentWrappingTests.vb b/src/Features/VisualBasicTest/Wrapping/ArgumentWrappingTests.vb index ac1f558262953..bf9dd82ceb1a9 100644 --- a/src/Features/VisualBasicTest/Wrapping/ArgumentWrappingTests.vb +++ b/src/Features/VisualBasicTest/Wrapping/ArgumentWrappingTests.vb @@ -2,10 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.VisualBasic.Wrapping - Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Wrapping Public Class ArgumentWrappingTests diff --git a/src/Features/VisualBasicTest/Wrapping/BinaryExpressionWrappingTests.vb b/src/Features/VisualBasicTest/Wrapping/BinaryExpressionWrappingTests.vb index 8b6a429e88a83..65f6bb2209d43 100644 --- a/src/Features/VisualBasicTest/Wrapping/BinaryExpressionWrappingTests.vb +++ b/src/Features/VisualBasicTest/Wrapping/BinaryExpressionWrappingTests.vb @@ -2,11 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.CodeStyle -Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.VisualBasic.Wrapping Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Wrapping diff --git a/src/Features/VisualBasicTest/Wrapping/ChainedExpressionWrappingTests.vb b/src/Features/VisualBasicTest/Wrapping/ChainedExpressionWrappingTests.vb index 659f4ab04dc2b..06908f8f38b85 100644 --- a/src/Features/VisualBasicTest/Wrapping/ChainedExpressionWrappingTests.vb +++ b/src/Features/VisualBasicTest/Wrapping/ChainedExpressionWrappingTests.vb @@ -2,10 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.VisualBasic.Wrapping - Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Wrapping Public Class ChainedExpressionWrappingTests diff --git a/src/Features/VisualBasicTest/Wrapping/InitializerExpressionWrappingTests.vb b/src/Features/VisualBasicTest/Wrapping/InitializerExpressionWrappingTests.vb index 43b24bbee1e2b..0a8b3d6a60f49 100644 --- a/src/Features/VisualBasicTest/Wrapping/InitializerExpressionWrappingTests.vb +++ b/src/Features/VisualBasicTest/Wrapping/InitializerExpressionWrappingTests.vb @@ -2,10 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.VisualBasic.Wrapping - Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Wrapping Public Class InitializerExpressionWrappingTests diff --git a/src/Features/VisualBasicTest/Wrapping/ParameterWrappingTests.vb b/src/Features/VisualBasicTest/Wrapping/ParameterWrappingTests.vb index aafb6f1d9d915..2d50253fea809 100644 --- a/src/Features/VisualBasicTest/Wrapping/ParameterWrappingTests.vb +++ b/src/Features/VisualBasicTest/Wrapping/ParameterWrappingTests.vb @@ -2,10 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces -Imports Microsoft.CodeAnalysis.VisualBasic.Wrapping - Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Wrapping Public Class ParameterWrappingTests diff --git a/src/Interactive/Host/Interactive/Core/InteractiveHost.LazyRemoteService.cs b/src/Interactive/Host/Interactive/Core/InteractiveHost.LazyRemoteService.cs index 459fee6a16281..17ba392a529d8 100644 --- a/src/Interactive/Host/Interactive/Core/InteractiveHost.LazyRemoteService.cs +++ b/src/Interactive/Host/Interactive/Core/InteractiveHost.LazyRemoteService.cs @@ -3,9 +3,7 @@ // See the LICENSE file in the project root for more information. extern alias Scripting; - using System; -using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO.Pipes; @@ -13,8 +11,8 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Roslyn.Utilities; -using StreamJsonRpc; using Scripting::Microsoft.CodeAnalysis.Scripting.Hosting; +using StreamJsonRpc; namespace Microsoft.CodeAnalysis.Interactive { diff --git a/src/Interactive/Host/Interactive/Core/InteractiveHost.cs b/src/Interactive/Host/Interactive/Core/InteractiveHost.cs index 89981183368e8..2468faab696af 100644 --- a/src/Interactive/Host/Interactive/Core/InteractiveHost.cs +++ b/src/Interactive/Host/Interactive/Core/InteractiveHost.cs @@ -11,7 +11,6 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Newtonsoft.Json; -using Roslyn.Utilities; using StreamJsonRpc; namespace Microsoft.CodeAnalysis.Interactive diff --git a/src/Interactive/Host/Interactive/Core/InteractiveHostOptions.cs b/src/Interactive/Host/Interactive/Core/InteractiveHostOptions.cs index 3ecfbc9c8465c..a6e6a4c1cd175 100644 --- a/src/Interactive/Host/Interactive/Core/InteractiveHostOptions.cs +++ b/src/Interactive/Host/Interactive/Core/InteractiveHostOptions.cs @@ -4,7 +4,6 @@ using System.Globalization; using System.IO; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Interactive { diff --git a/src/Interactive/Host/Interactive/Core/RemoteExecutionResult.cs b/src/Interactive/Host/Interactive/Core/RemoteExecutionResult.cs index 095c037b07198..c34bc56ae9a15 100644 --- a/src/Interactive/Host/Interactive/Core/RemoteExecutionResult.cs +++ b/src/Interactive/Host/Interactive/Core/RemoteExecutionResult.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; -using System.Linq; namespace Microsoft.CodeAnalysis.Interactive { diff --git a/src/Interactive/Host/Interactive/Core/RemoteInitializationResult.cs b/src/Interactive/Host/Interactive/Core/RemoteInitializationResult.cs index f08abbf15a830..262b305dca95c 100644 --- a/src/Interactive/Host/Interactive/Core/RemoteInitializationResult.cs +++ b/src/Interactive/Host/Interactive/Core/RemoteInitializationResult.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; -using System.Linq; namespace Microsoft.CodeAnalysis.Interactive { diff --git a/src/Interactive/HostProcess/InteractiveHostEntryPoint.cs b/src/Interactive/HostProcess/InteractiveHostEntryPoint.cs index b764739020b61..75003e62bccb3 100644 --- a/src/Interactive/HostProcess/InteractiveHostEntryPoint.cs +++ b/src/Interactive/HostProcess/InteractiveHostEntryPoint.cs @@ -9,7 +9,6 @@ using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.CodeAnalysis.ErrorReporting; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Interactive { diff --git a/src/Interactive/HostTest/AbstractInteractiveHostTests.cs b/src/Interactive/HostTest/AbstractInteractiveHostTests.cs index a733de3dad070..ea9e007039da0 100644 --- a/src/Interactive/HostTest/AbstractInteractiveHostTests.cs +++ b/src/Interactive/HostTest/AbstractInteractiveHostTests.cs @@ -22,6 +22,7 @@ namespace Microsoft.CodeAnalysis.UnitTests.Interactive { using InteractiveHost::Microsoft.CodeAnalysis.Interactive; + using Xunit.Abstractions; public abstract class AbstractInteractiveHostTests : CSharpTestBase, IAsyncLifetime { @@ -30,6 +31,7 @@ public abstract class AbstractInteractiveHostTests : CSharpTestBase, IAsyncLifet private int[] _outputReadPosition = [0, 0]; internal readonly InteractiveHost Host; + internal readonly ITestOutputHelper TestOutputHelper; // DOTNET_ROOT must be set in order to run host process on .NET Core on machines (like CI) // that do not have the required version of the runtime installed globally. @@ -57,12 +59,13 @@ static AbstractInteractiveHostTests() } } - protected AbstractInteractiveHostTests() + protected AbstractInteractiveHostTests(ITestOutputHelper testOutputHelper) { + TestOutputHelper = testOutputHelper; Host = new InteractiveHost(typeof(CSharpReplServiceProvider), ".", millisecondsTimeout: -1, joinOutputWritingThreadsOnDisposal: true); Host.InteractiveHostProcessCreationFailed += (exception, exitCode) => - Assert.False(true, (exception?.Message ?? "Host process terminated unexpectedly.") + $" Exit code: {exitCode?.ToString() ?? ""}"); + testOutputHelper.WriteLine((exception?.Message ?? "Host process terminated unexpectedly.") + $" Exit code: {exitCode?.ToString() ?? ""}"); RedirectOutput(); } diff --git a/src/Interactive/HostTest/InteractiveHostCoreInitTests.cs b/src/Interactive/HostTest/InteractiveHostCoreInitTests.cs index 6dff687d2e2e2..a635abd68b5cb 100644 --- a/src/Interactive/HostTest/InteractiveHostCoreInitTests.cs +++ b/src/Interactive/HostTest/InteractiveHostCoreInitTests.cs @@ -14,9 +14,10 @@ namespace Microsoft.CodeAnalysis.UnitTests.Interactive { using InteractiveHost::Microsoft.CodeAnalysis.Interactive; + using Xunit.Abstractions; [Trait(Traits.Feature, Traits.Features.InteractiveHost)] - public sealed class InteractiveHostCoreInitTests : AbstractInteractiveHostTests + public sealed class InteractiveHostCoreInitTests(ITestOutputHelper testOutputHelper) : AbstractInteractiveHostTests(testOutputHelper) { internal override InteractiveHostPlatform DefaultPlatform => InteractiveHostPlatform.Core; internal override bool UseDefaultInitializationFile => true; diff --git a/src/Interactive/HostTest/InteractiveHostCoreTests.cs b/src/Interactive/HostTest/InteractiveHostCoreTests.cs index 39a0bc1148f13..4ca3b11379eb2 100644 --- a/src/Interactive/HostTest/InteractiveHostCoreTests.cs +++ b/src/Interactive/HostTest/InteractiveHostCoreTests.cs @@ -10,9 +10,10 @@ namespace Microsoft.CodeAnalysis.UnitTests.Interactive { using InteractiveHost::Microsoft.CodeAnalysis.Interactive; + using Xunit.Abstractions; [Trait(Traits.Feature, Traits.Features.InteractiveHost)] - public sealed class InteractiveHostCoreTests : AbstractInteractiveHostTests + public sealed class InteractiveHostCoreTests(ITestOutputHelper testOutputHelper) : AbstractInteractiveHostTests(testOutputHelper) { internal override InteractiveHostPlatform DefaultPlatform => InteractiveHostPlatform.Core; internal override bool UseDefaultInitializationFile => false; diff --git a/src/Interactive/HostTest/InteractiveHostDesktopInitTests.cs b/src/Interactive/HostTest/InteractiveHostDesktopInitTests.cs index 3db92fbef3a10..7749771c81cff 100644 --- a/src/Interactive/HostTest/InteractiveHostDesktopInitTests.cs +++ b/src/Interactive/HostTest/InteractiveHostDesktopInitTests.cs @@ -13,9 +13,10 @@ namespace Microsoft.CodeAnalysis.UnitTests.Interactive { using InteractiveHost::Microsoft.CodeAnalysis.Interactive; + using Xunit.Abstractions; [Trait(Traits.Feature, Traits.Features.InteractiveHost)] - public sealed class InteractiveHostDesktopInitTests : AbstractInteractiveHostTests + public sealed class InteractiveHostDesktopInitTests(ITestOutputHelper testOutputHelper) : AbstractInteractiveHostTests(testOutputHelper) { internal override InteractiveHostPlatform DefaultPlatform => InteractiveHostPlatform.Desktop32; internal override bool UseDefaultInitializationFile => true; diff --git a/src/Interactive/HostTest/InteractiveHostDesktopTests.cs b/src/Interactive/HostTest/InteractiveHostDesktopTests.cs index eda6c32516ddf..e25a04752fea6 100644 --- a/src/Interactive/HostTest/InteractiveHostDesktopTests.cs +++ b/src/Interactive/HostTest/InteractiveHostDesktopTests.cs @@ -18,9 +18,10 @@ namespace Microsoft.CodeAnalysis.UnitTests.Interactive { using InteractiveHost::Microsoft.CodeAnalysis.Interactive; + using Xunit.Abstractions; [Trait(Traits.Feature, Traits.Features.InteractiveHost)] - public sealed class InteractiveHostDesktopTests : AbstractInteractiveHostTests + public sealed class InteractiveHostDesktopTests(ITestOutputHelper testOutputHelper) : AbstractInteractiveHostTests(testOutputHelper) { internal override InteractiveHostPlatform DefaultPlatform => InteractiveHostPlatform.Desktop64; internal override bool UseDefaultInitializationFile => false; diff --git a/src/LanguageServer/ExternalAccess/VisualDiagnostics/Internal/VisualDiagnosticsServiceFactory.cs b/src/LanguageServer/ExternalAccess/VisualDiagnostics/Internal/VisualDiagnosticsServiceFactory.cs index ce9a367059a7d..7a1cce089f89a 100644 --- a/src/LanguageServer/ExternalAccess/VisualDiagnostics/Internal/VisualDiagnosticsServiceFactory.cs +++ b/src/LanguageServer/ExternalAccess/VisualDiagnostics/Internal/VisualDiagnosticsServiceFactory.cs @@ -14,7 +14,6 @@ using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.ServiceHub.Framework; using Roslyn.LanguageServer.Protocol; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.VisualDiagnostics; diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/LspFileChangeWatcherTests.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/LspFileChangeWatcherTests.cs index eb00f3ba78fd8..64fa762c9d53e 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/LspFileChangeWatcherTests.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/LspFileChangeWatcherTests.cs @@ -102,10 +102,8 @@ public async Task CreatingFileWatchRequestsFileWatch() Assert.Empty(dynamicCapabilitiesRpcTarget.Registrations); } - private static async Task WaitForFileWatcherAsync(TestLspServer testLspServer) - { - await testLspServer.ExportProvider.GetExportedValue().GetWaiter(FeatureAttribute.Workspace).ExpeditedWaitAsync(); - } + private static Task WaitForFileWatcherAsync(TestLspServer testLspServer) + => testLspServer.ExportProvider.GetExportedValue().GetWaiter(FeatureAttribute.Workspace).ExpeditedWaitAsync(); private static FileSystemWatcher GetSingleFileWatcher(DynamicCapabilitiesRpcTarget dynamicCapabilities) { diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Services/ExtractRefactoringTests.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Services/ExtractRefactoringTests.cs index dfdaee88a9ab0..983c4e73d7446 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Services/ExtractRefactoringTests.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Services/ExtractRefactoringTests.cs @@ -25,8 +25,10 @@ public void M() } } """; - var expected = - """ + await using var testLspServer = await CreateCSharpLanguageServerAsync(markup, includeDevKitComponents); + var caretLocation = testLspServer.GetLocations("caret").Single(); + + await TestCodeActionAsync(testLspServer, caretLocation, "Extract base class...", """ internal class NewBaseType { public void M() @@ -37,12 +39,7 @@ public void M() class A : NewBaseType { } - """; - - await using var testLspServer = await CreateCSharpLanguageServerAsync(markup, includeDevKitComponents); - var caretLocation = testLspServer.GetLocations("caret").Single(); - - await TestCodeActionAsync(testLspServer, caretLocation, "Extract base class...", expected); + """); } [Theory] @@ -58,8 +55,10 @@ public void M() } } """; - var expected = - """ + await using var testLspServer = await CreateCSharpLanguageServerAsync(markup, includeDevKitComponents); + var caretLocation = testLspServer.GetLocations("caret").Single(); + + await TestCodeActionAsync(testLspServer, caretLocation, "Extract interface...", """ interface IA { void M(); @@ -71,12 +70,7 @@ public void M() { } } - """; - - await using var testLspServer = await CreateCSharpLanguageServerAsync(markup, includeDevKitComponents); - var caretLocation = testLspServer.GetLocations("caret").Single(); - - await TestCodeActionAsync(testLspServer, caretLocation, "Extract interface...", expected); + """); } private static async Task TestCodeActionAsync( diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/AbstractLanguageServerClientTests.TestLspClient.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/AbstractLanguageServerClientTests.TestLspClient.cs index 6c316b120015e..245c5a42c390b 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/AbstractLanguageServerClientTests.TestLspClient.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/AbstractLanguageServerClientTests.TestLspClient.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Collections.Immutable; using System.Diagnostics; using System.IO.Pipes; using System.Runtime.InteropServices; @@ -162,7 +161,7 @@ Action GetMessageLogger(string method) { var logger = _loggerFactory.CreateLogger($"LSP {method}"); - return (int type, string message) => + return (type, message) => { var logLevel = (MessageType)type switch { diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/AbstractLanguageServerClientTests.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/AbstractLanguageServerClientTests.cs index cf2a6c5e807cb..3a10d43b220f9 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/AbstractLanguageServerClientTests.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/AbstractLanguageServerClientTests.cs @@ -4,6 +4,7 @@ using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.LanguageServer.HostWorkspace; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/AbstractLanguageServerHostTests.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/AbstractLanguageServerHostTests.cs index 7d6f5476c8cc1..9693b017fb9e0 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/AbstractLanguageServerHostTests.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/AbstractLanguageServerHostTests.cs @@ -42,8 +42,6 @@ protected sealed class TestLspServer : ILspClient, IAsyncDisposable private readonly Task _languageServerHostCompletionTask; private readonly JsonRpc _clientRpc; - private ServerCapabilities? _serverCapabilities; - internal static async Task CreateAsync(ClientCapabilities clientCapabilities, ILoggerFactory loggerFactory, string cacheDirectory, bool includeDevKitComponents = true, string[]? extensionPaths = null) { var (exportProvider, assemblyLoader) = await LanguageServerTestComposition.CreateExportProviderAsync( @@ -51,7 +49,7 @@ internal static async Task CreateAsync(ClientCapabilities clientC var testLspServer = new TestLspServer(exportProvider, loggerFactory, assemblyLoader); var initializeResponse = await testLspServer.ExecuteRequestAsync(Methods.InitializeName, new InitializeParams { Capabilities = clientCapabilities }, CancellationToken.None); Assert.NotNull(initializeResponse?.Capabilities); - testLspServer._serverCapabilities = initializeResponse!.Capabilities; + testLspServer.ServerCapabilities = initializeResponse!.Capabilities; await testLspServer.ExecuteRequestAsync(Methods.InitializedName, new InitializedParams(), CancellationToken.None); @@ -61,7 +59,7 @@ internal static async Task CreateAsync(ClientCapabilities clientC internal LanguageServerHost LanguageServerHost { get; } public ExportProvider ExportProvider { get; } - internal ServerCapabilities ServerCapabilities => _serverCapabilities ?? throw new InvalidOperationException("Initialize has not been called"); + internal ServerCapabilities ServerCapabilities { get => field ?? throw new InvalidOperationException("Initialize has not been called"); private set; } private TestLspServer(ExportProvider exportProvider, ILoggerFactory loggerFactory, IAssemblyLoader assemblyLoader) { diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/LanguageServerTestComposition.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/LanguageServerTestComposition.cs index 54e0171976633..bce854d90bd4c 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/LanguageServerTestComposition.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/LanguageServerTestComposition.cs @@ -24,7 +24,6 @@ internal sealed class LanguageServerTestComposition SessionId: null, ExtensionAssemblyPaths: extensionPaths ?? [], DevKitDependencyPath: devKitDependencyPath, - RazorSourceGenerator: null, RazorDesignTimePath: null, ExtensionLogDirectory: string.Empty, ServerPipeName: null, diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/LspClientExtensions.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/LspClientExtensions.cs index c06d676760157..b0829330d0230 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/LspClientExtensions.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/LspClientExtensions.cs @@ -9,20 +9,16 @@ namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests; internal static class LspClientExtensions { - public static async Task Initialized(this ILspClient lspClient) - { - await lspClient.ExecuteRequestAsync(Methods.InitializedName, new InitializedParams(), CancellationToken.None); - } + public static Task Initialized(this ILspClient lspClient) + => lspClient.ExecuteRequestAsync(Methods.InitializedName, new InitializedParams(), CancellationToken.None); public static async Task Initialize(this ILspClient lspClient, ClientCapabilities clientCapabilities) { return await lspClient.ExecuteRequestAsync(Methods.InitializeName, new InitializeParams { Capabilities = clientCapabilities }, CancellationToken.None); } - public static async Task OpenProjectsAsync(this ILspClient lspClient, Uri[] projects) - { - await lspClient.ExecuteNotificationAsync(OpenProjectHandler.OpenProjectName, new() { Projects = projects }); - } + public static Task OpenProjectsAsync(this ILspClient lspClient, Uri[] projects) + => lspClient.ExecuteNotificationAsync(OpenProjectHandler.OpenProjectName, new() { Projects = projects }); public static async Task RunGetCodeActionsAsync( this ILspClient lspClient, diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/VirtualProjectXmlProviderTests.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/VirtualProjectXmlProviderTests.cs index b439d7672ad3d..09b63ac338ae5 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/VirtualProjectXmlProviderTests.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/VirtualProjectXmlProviderTests.cs @@ -7,10 +7,8 @@ //#define RoslynTestRunApi using System.Text; -using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.LanguageServer.FileBasedPrograms; using Microsoft.Extensions.Logging; -using Roslyn.LanguageServer.Protocol; using Roslyn.Test.Utilities; using Xunit.Abstractions; @@ -32,6 +30,7 @@ public VirtualProjectXmlProviderTests(ITestOutputHelper testOutputHelper) : base private class EnableRunApiTests : ExecutionCondition { + // https://github.com/dotnet/roslyn/issues/78879: Enable these tests unconditionally public override bool ShouldSkip => #if RoslynTestRunApi false; @@ -69,7 +68,7 @@ await appFile.WriteAllTextAsync(""" } """)); - var contentNullable = await projectProvider.GetVirtualProjectContentAsync(appFile.Path, CancellationToken.None); + var contentNullable = await projectProvider.GetVirtualProjectContentAsync(appFile.Path, LoggerFactory.CreateLogger(), CancellationToken.None); Assert.Null(contentNullable); } @@ -93,10 +92,11 @@ await globalJsonFile.WriteAllTextAsync(""" } """); - var contentNullable = await projectProvider.GetVirtualProjectContentAsync(appFile.Path, CancellationToken.None); + var logger = LoggerFactory.CreateLogger(); + var contentNullable = await projectProvider.GetVirtualProjectContentAsync(appFile.Path, logger, CancellationToken.None); var content = contentNullable.Value; var virtualProjectXml = content.VirtualProjectXml; - LoggerFactory.CreateLogger().LogTrace(virtualProjectXml); + logger.LogTrace(virtualProjectXml); Assert.Contains("net10.0", virtualProjectXml); Assert.Contains("", virtualProjectXml); @@ -125,7 +125,7 @@ await globalJsonFile.WriteAllTextAsync(""" } """); - var contentNullable = await projectProvider.GetVirtualProjectContentAsync(appFile.Path, CancellationToken.None); + var contentNullable = await projectProvider.GetVirtualProjectContentAsync(appFile.Path, LoggerFactory.CreateLogger(), CancellationToken.None); var content = contentNullable.Value; LoggerFactory.CreateLogger().LogTrace(content.VirtualProjectXml); @@ -150,7 +150,7 @@ await globalJsonFile.WriteAllTextAsync(""" } """); - var content = await projectProvider.GetVirtualProjectContentAsync(Path.Combine(tempDir.Path, "BAD"), CancellationToken.None); + var content = await projectProvider.GetVirtualProjectContentAsync(Path.Combine(tempDir.Path, "BAD"), LoggerFactory.CreateLogger(), CancellationToken.None); Assert.Null(content); } @@ -176,7 +176,7 @@ await globalJsonFile.WriteAllTextAsync(""" } """); - var contentNullable = await projectProvider.GetVirtualProjectContentAsync(appFile.Path, CancellationToken.None); + var contentNullable = await projectProvider.GetVirtualProjectContentAsync(appFile.Path, LoggerFactory.CreateLogger(), CancellationToken.None); var content = contentNullable.Value; var diagnostic = content.Diagnostics.Single(); Assert.Contains("Unrecognized directive 'BAD'", diagnostic.Message); diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/BrokeredServices/BrokeredServiceContainer.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/BrokeredServices/BrokeredServiceContainer.cs index e1eafc7a08326..088d183bc6701 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/BrokeredServices/BrokeredServiceContainer.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/BrokeredServices/BrokeredServiceContainer.cs @@ -12,6 +12,7 @@ using Microsoft.VisualStudio.Utilities.ServiceBroker; namespace Microsoft.CodeAnalysis.LanguageServer.BrokeredServices; + internal sealed class BrokeredServiceContainer : GlobalBrokeredServiceContainer { public BrokeredServiceContainer(TraceSource traceSource) diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/DotnetCliHelper.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/DotnetCliHelper.cs index 3b9d6766e950b..8d03e0374cb5f 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/DotnetCliHelper.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/DotnetCliHelper.cs @@ -5,6 +5,7 @@ using System.Composition; using System.Diagnostics; using System.Text; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.Extensions.Logging; using Roslyn.Utilities; @@ -68,15 +69,15 @@ private async Task GetDotnetSdkFolderFromDotnetExecutableAsync(string pr return dotnetSdkFolderPath; } - public Process Run(string[] arguments, string? workingDirectory, bool shouldLocalizeOutput, bool redirectStandardInput = false) + public Process Run(string[] arguments, string? workingDirectory, bool shouldLocalizeOutput, bool keepStandardInputOpen = false) { - _logger.LogDebug($"Running dotnet CLI command at {_dotnetExecutablePath.Value} in directory {workingDirectory} with arguments {arguments}"); + _logger.LogDebug($"Running dotnet CLI command at {_dotnetExecutablePath.Value} in directory {workingDirectory} with arguments '{string.Join(' ', arguments)}'"); var startInfo = new ProcessStartInfo(_dotnetExecutablePath.Value) { CreateNoWindow = true, UseShellExecute = false, - RedirectStandardInput = redirectStandardInput, + RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, }; @@ -106,6 +107,9 @@ public Process Run(string[] arguments, string? workingDirectory, bool shouldLoca var process = Process.Start(startInfo); Contract.ThrowIfNull(process, $"Unable to start dotnet CLI at {_dotnetExecutablePath.Value} with arguments {arguments} in directory {workingDirectory}"); + if (!keepStandardInputOpen) + process.StandardInput.Close(); + return process; } diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/FileBasedProgramsProjectSystem.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/FileBasedProgramsProjectSystem.cs index 1d284207fb741..01f6754bd709f 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/FileBasedProgramsProjectSystem.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/FileBasedProgramsProjectSystem.cs @@ -2,11 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Collections.Immutable; -using System.Security; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Features.Workspaces; -using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServer.HostWorkspace; using Microsoft.CodeAnalysis.LanguageServer.HostWorkspace.ProjectTelemetry; using Microsoft.CodeAnalysis.MetadataAsSource; @@ -16,12 +13,9 @@ using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; -using Microsoft.CodeAnalysis.Workspaces.ProjectSystem; using Microsoft.CommonLanguageServerProtocol.Framework; using Microsoft.Extensions.Logging; -using Microsoft.VisualStudio.Composition; using Roslyn.LanguageServer.Protocol; -using Roslyn.Utilities; using static Microsoft.CodeAnalysis.MSBuild.BuildHostProcessManager; namespace Microsoft.CodeAnalysis.LanguageServer.FileBasedPrograms; @@ -33,6 +27,7 @@ internal sealed class FileBasedProgramsProjectSystem : LanguageServerProjectLoad private readonly ILogger _logger; private readonly IMetadataAsSourceFileService _metadataAsSourceFileService; private readonly VirtualProjectXmlProvider _projectXmlProvider; + private readonly LanguageServerWorkspaceFactory _workspaceFactory; public FileBasedProgramsProjectSystem( ILspServices lspServices, @@ -47,7 +42,6 @@ public FileBasedProgramsProjectSystem( ServerConfigurationFactory serverConfigurationFactory, IBinLogPathProvider binLogPathProvider) : base( - workspaceFactory.FileBasedProgramsProjectFactory, workspaceFactory.TargetFrameworkManager, workspaceFactory.ProjectSystemHostInfo, fileChangeWatcher, @@ -62,12 +56,20 @@ public FileBasedProgramsProjectSystem( _logger = loggerFactory.CreateLogger(); _metadataAsSourceFileService = metadataAsSourceFileService; _projectXmlProvider = projectXmlProvider; + _workspaceFactory = workspaceFactory; } - public Workspace Workspace => ProjectFactory.Workspace; - private string GetDocumentFilePath(DocumentUri uri) => uri.ParsedUri is { } parsedUri ? ProtocolConversions.GetDocumentFilePathFromUri(parsedUri) : uri.UriString; + public async ValueTask IsMiscellaneousFilesDocumentAsync(TextDocument document, CancellationToken cancellationToken) + { + // There are two cases here: if it's a primordial document, it'll be in the MiscellaneousFilesWorkspace and thus we definitely know it's + // a miscellaneous file. Otherwise, it might be a file-based program that we loaded in the main workspace; in this case, the project's path + // is also the source file path, and that's what we consider the 'project' path that is loaded. + return document.Project.Solution.Workspace == _workspaceFactory.MiscellaneousFilesWorkspaceProjectFactory.Workspace || + document.Project.FilePath is not null && await IsProjectLoadedAsync(document.Project.FilePath, cancellationToken); + } + public async ValueTask AddMiscellaneousDocumentAsync(DocumentUri uri, SourceText documentText, string languageId, ILspLogger logger) { var documentFilePath = GetDocumentFilePath(uri); @@ -86,7 +88,7 @@ public FileBasedProgramsProjectSystem( var doDesignTimeBuild = uri.ParsedUri?.IsFile is true && primordialDoc.Project.Language == LanguageNames.CSharp && GlobalOptionService.GetOption(LanguageServerProjectSystemOptionsStorage.EnableFileBasedPrograms); - await BeginLoadingProjectWithPrimordialAsync(primordialDoc.FilePath, primordialProjectId: primordialDoc.Project.Id, doDesignTimeBuild); + await BeginLoadingProjectWithPrimordialAsync(primordialDoc.FilePath, _workspaceFactory.MiscellaneousFilesWorkspaceProjectFactory, primordialProjectId: primordialDoc.Project.Id, doDesignTimeBuild); return primordialDoc; @@ -98,12 +100,12 @@ TextDocument AddPrimordialDocument(DocumentUri uri, SourceText documentText, str Contract.Fail($"Could not find language information for {uri} with absolute path {documentFilePath}"); } - var workspace = Workspace; + var workspace = _workspaceFactory.MiscellaneousFilesWorkspaceProjectFactory.Workspace; var sourceTextLoader = new SourceTextLoader(documentText, documentFilePath); var projectInfo = MiscellaneousFileUtilities.CreateMiscellaneousProjectInfoForDocument( workspace, documentFilePath, sourceTextLoader, languageInformation, documentText.ChecksumAlgorithm, workspace.Services.SolutionServices, []); - ProjectFactory.ApplyChangeToWorkspace(workspace => workspace.OnProjectAdded(projectInfo)); + _workspaceFactory.MiscellaneousFilesWorkspaceProjectFactory.ApplyChangeToWorkspace(workspace => workspace.OnProjectAdded(projectInfo)); // https://github.com/dotnet/roslyn/pull/78267 // Work around an issue where opening a Razor file in the misc workspace causes a crash. @@ -132,7 +134,7 @@ public async ValueTask TryRemoveMiscellaneousDocumentAsync(DocumentUri uri, bool protected override async Task TryLoadProjectInMSBuildHostAsync( BuildHostProcessManager buildHostProcessManager, string documentPath, CancellationToken cancellationToken) { - var content = await _projectXmlProvider.GetVirtualProjectContentAsync(documentPath, cancellationToken); + var content = await _projectXmlProvider.GetVirtualProjectContentAsync(documentPath, _logger, cancellationToken); if (content is not var (virtualProjectContent, diagnostics)) { // https://github.com/dotnet/roslyn/issues/78618: falling back to this until dotnet run-api is more widely available @@ -151,13 +153,21 @@ public async ValueTask TryRemoveMiscellaneousDocumentAsync(DocumentUri uri, bool // This is necessary in order to get msbuild to apply the standard c# props/targets to the project. var virtualProjectPath = VirtualProjectXmlProvider.GetVirtualProjectPath(documentPath); - var loader = ProjectFactory.CreateFileTextLoader(documentPath); + var loader = _workspaceFactory.MiscellaneousFilesWorkspaceProjectFactory.CreateFileTextLoader(documentPath); var textAndVersion = await loader.LoadTextAsync(new LoadTextOptions(SourceHashAlgorithms.Default), cancellationToken); var isFileBasedProgram = VirtualProjectXmlProvider.IsFileBasedProgram(documentPath, textAndVersion.Text); const BuildHostProcessKind buildHostKind = BuildHostProcessKind.NetCore; var buildHost = await buildHostProcessManager.GetBuildHostAsync(buildHostKind, cancellationToken); var loadedFile = await buildHost.LoadProjectAsync(virtualProjectPath, virtualProjectContent, languageName: LanguageNames.CSharp, cancellationToken); - return new RemoteProjectLoadResult(loadedFile, HasAllInformation: isFileBasedProgram, Preferred: buildHostKind, Actual: buildHostKind); + + return new RemoteProjectLoadResult( + loadedFile, + // If it's a proper file based program, we'll put it in the main host workspace factory since we want cross-project references to work. + // Otherwise, we'll keep it in miscellaneous files. + ProjectFactory: isFileBasedProgram ? _workspaceFactory.HostProjectFactory : _workspaceFactory.MiscellaneousFilesWorkspaceProjectFactory, + IsMiscellaneousFile: !isFileBasedProgram, + Preferred: buildHostKind, + Actual: buildHostKind); } } diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/RunApiModels.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/RunApiModels.cs index 91dfc531e14e2..5d59892adcdbd 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/RunApiModels.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/RunApiModels.cs @@ -2,13 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Collections.Generic; using System.Collections.Immutable; -using System.Linq; -using System.Text; using System.Text.Json.Serialization; -using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.LanguageServer.FileBasedPrograms diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/VirtualProjectXmlProvider.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/VirtualProjectXmlProvider.cs index 4bf41b8251798..a5143086c4046 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/VirtualProjectXmlProvider.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/VirtualProjectXmlProvider.cs @@ -21,14 +21,12 @@ namespace Microsoft.CodeAnalysis.LanguageServer.FileBasedPrograms; [Export(typeof(VirtualProjectXmlProvider)), Shared] [method: ImportingConstructor] [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] -internal class VirtualProjectXmlProvider(DotnetCliHelper dotnetCliHelper, ILoggerFactory loggerFactory) +internal class VirtualProjectXmlProvider(DotnetCliHelper dotnetCliHelper) { - private readonly ILogger _logger = loggerFactory.CreateLogger(); - - internal async Task<(string VirtualProjectXml, ImmutableArray Diagnostics)?> GetVirtualProjectContentAsync(string documentFilePath, CancellationToken cancellationToken) + internal async Task<(string VirtualProjectXml, ImmutableArray Diagnostics)?> GetVirtualProjectContentAsync(string documentFilePath, ILogger logger, CancellationToken cancellationToken) { var workingDirectory = Path.GetDirectoryName(documentFilePath); - var process = dotnetCliHelper.Run(["run-api"], workingDirectory, shouldLocalizeOutput: true, redirectStandardInput: true); + var process = dotnetCliHelper.Run(["run-api"], workingDirectory, shouldLocalizeOutput: true, keepStandardInputOpen: true); cancellationToken.Register(() => { @@ -42,7 +40,7 @@ internal class VirtualProjectXmlProvider(DotnetCliHelper dotnetCliHelper, ILogge // Debug severity is used for these because we think it will be common for the user environment to have too old of an SDK for the call to work. // Rather than representing a hard error condition, it represents a condition where we need to gracefully downgrade the experience. - process.ErrorDataReceived += (sender, args) => _logger.LogDebug($"dotnet run-api: {args.Data}"); + process.ErrorDataReceived += (sender, args) => logger.LogDebug($"[stderr] dotnet run-api: {args.Data}"); process.BeginErrorReadLine(); var responseJson = await process.StandardOutput.ReadLineAsync(cancellationToken); @@ -50,13 +48,13 @@ internal class VirtualProjectXmlProvider(DotnetCliHelper dotnetCliHelper, ILogge if (process.ExitCode != 0) { - _logger.LogDebug($"dotnet run-api exited with exit code '{process.ExitCode}'."); + logger.LogDebug($"dotnet run-api exited with exit code '{process.ExitCode}'."); return null; } if (string.IsNullOrWhiteSpace(responseJson)) { - _logger.LogError($"dotnet run-api exited with exit code 0, but did not return any response."); + logger.LogError($"dotnet run-api exited with exit code 0, but did not return any response."); return null; } @@ -65,17 +63,13 @@ internal class VirtualProjectXmlProvider(DotnetCliHelper dotnetCliHelper, ILogge var response = JsonSerializer.Deserialize(responseJson, RunFileApiJsonSerializerContext.Default.RunApiOutput); if (response is RunApiOutput.Error error) { - _logger.LogError($"dotnet run-api version: {error.Version}. Latest known version: {RunApiOutput.LatestKnownVersion}"); - _logger.LogError($"dotnet run-api returned error: '{error.Message}'"); + logger.LogError($"dotnet run-api version: {error.Version}. Latest known version: {RunApiOutput.LatestKnownVersion}"); + logger.LogError($"dotnet run-api returned error: '{error.Message}'"); return null; } if (response is RunApiOutput.Project project) { - if (project.Version > RunApiOutput.LatestKnownVersion) - { - _logger.LogWarning($"'dotnet run-api' version '{project.Version}' is newer than latest known version {RunApiOutput.LatestKnownVersion}"); - } return (project.Content, project.Diagnostics); } @@ -85,7 +79,11 @@ internal class VirtualProjectXmlProvider(DotnetCliHelper dotnetCliHelper, ILogge catch (JsonException ex) { // In this case, run-api returned 0 exit code, but gave us back JSON that we don't know how to parse. - _logger.LogError(ex, "Could not deserialize run-api response."); + logger.LogError(ex, "Could not deserialize run-api response."); + logger.LogTrace($""" + Full run-api response: + {responseJson} + """); return null; } } @@ -99,7 +97,7 @@ internal static string GetVirtualProjectPath(string documentFilePath) internal static bool IsFileBasedProgram(string documentFilePath, SourceText text) { - // TODO: this needs to be adjusted to be more sustainable. + // https://github.com/dotnet/roslyn/issues/78878: this needs to be adjusted to be more sustainable. // When we adopt the dotnet run-api, we need to get rid of this or adjust it to be more sustainable (e.g. using the appropriate document to get a syntax tree) var tree = CSharpSyntaxTree.ParseText(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview), path: documentFilePath); var root = tree.GetRoot(); diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/HostDiagnosticAnalyzerProvider.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/HostDiagnosticAnalyzerProvider.cs deleted file mode 100644 index f5e96d6685eff..0000000000000 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/HostDiagnosticAnalyzerProvider.cs +++ /dev/null @@ -1,45 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Immutable; -using System.Diagnostics; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.ExternalAccess.Razor; -using Microsoft.CodeAnalysis.Workspaces.ProjectSystem; - -namespace Microsoft.CodeAnalysis.LanguageServer.HostWorkspace; - -internal sealed class HostDiagnosticAnalyzerProvider(string? razorSourceGenerator) : IHostDiagnosticAnalyzerProvider -{ - public ImmutableArray<(AnalyzerFileReference reference, string extensionId)> GetAnalyzerReferencesInExtensions() => []; - - public ImmutableArray<(string path, string extensionId)> GetRazorAssembliesInExtensions() - { - if (File.Exists(razorSourceGenerator)) - { - // we also have to redirect the utilities and object pool assemblies - var razorDir = Path.GetDirectoryName(razorSourceGenerator) ?? ""; - var razorUtilities = GetDependency(razorDir, RazorAnalyzerAssemblyResolver.RazorUtilsAssemblyName); - var objectPool = GetDependency(razorDir, RazorAnalyzerAssemblyResolver.ObjectPoolAssemblyName); - - return - [ - (razorSourceGenerator, ProjectSystemProject.RazorVsixExtensionId), - (razorUtilities, ProjectSystemProject.RazorVsixExtensionId), - (objectPool, ProjectSystemProject.RazorVsixExtensionId) - ]; - } - return []; - - static string GetDependency(string razorDir, string dependencyName) - { - var dependency = Path.Combine(razorDir, dependencyName + ".dll"); - if (!File.Exists(dependency)) - { - throw new FileNotFoundException($"Could not find razor dependency {dependency}"); - } - return dependency; - } - } -} diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerProjectLoader.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerProjectLoader.cs index 3b4f7d4ce7044..5dbc51ba3f3de 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerProjectLoader.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerProjectLoader.cs @@ -2,14 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Collections.Concurrent; using System.Collections.Immutable; using System.Diagnostics; -using System.IO; -using System.Threading; -using System.Threading.Tasks; using Microsoft.CodeAnalysis.Collections; -using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServer.Handler.DebugConfiguration; using Microsoft.CodeAnalysis.LanguageServer.HostWorkspace.ProjectTelemetry; @@ -21,7 +16,6 @@ using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Shared.Utilities; -using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Threading; using Microsoft.CodeAnalysis.Workspaces.ProjectSystem; using Microsoft.Extensions.Logging; @@ -35,7 +29,6 @@ internal abstract class LanguageServerProjectLoader { private readonly AsyncBatchingWorkQueue _projectsToReload; - protected readonly ProjectSystemProjectFactory ProjectFactory; private readonly ProjectTargetFrameworkManager _targetFrameworkManager; private readonly ProjectSystemHostInfo _projectSystemHostInfo; private readonly IFileChangeWatcher _fileChangeWatcher; @@ -72,11 +65,15 @@ private ProjectLoadState() { } /// Represents a project which has not yet had a design-time build performed for it, /// and which has an associated "primordial project" in the workspace. /// + /// + /// The project factory for the workspace that the primordial project lives within. This + /// factory was not used to create the project, but still needs to be used during removal to avoid locking issues. + /// /// /// ID of the project which LSP uses to fulfill requests until the first design-time build is complete. /// The project with this ID is removed from the workspace when unloading or when transitioning to state. /// - public sealed record Primordial(ProjectId PrimordialProjectId) : ProjectLoadState; + public sealed record Primordial(ProjectSystemProjectFactory PrimordialProjectFactory, ProjectId PrimordialProjectId) : ProjectLoadState; /// /// Represents a project for which we have loaded zero or more targets. @@ -89,7 +86,6 @@ public sealed record LoadedTargets(ImmutableArray LoadedProjectTa } protected LanguageServerProjectLoader( - ProjectSystemProjectFactory projectFactory, ProjectTargetFrameworkManager targetFrameworkManager, ProjectSystemHostInfo projectSystemHostInfo, IFileChangeWatcher fileChangeWatcher, @@ -100,7 +96,6 @@ protected LanguageServerProjectLoader( ServerConfigurationFactory serverConfigurationFactory, IBinLogPathProvider binLogPathProvider) { - ProjectFactory = projectFactory; _targetFrameworkManager = targetFrameworkManager; _projectSystemHostInfo = projectSystemHostInfo; _fileChangeWatcher = fileChangeWatcher; @@ -109,7 +104,6 @@ protected LanguageServerProjectLoader( _logger = loggerFactory.CreateLogger(nameof(LanguageServerProjectLoader)); _projectLoadTelemetryReporter = projectLoadTelemetry; _binLogPathProvider = binLogPathProvider; - var workspace = projectFactory.Workspace; var razorDesignTimePath = serverConfigurationFactory.ServerConfiguration?.RazorDesignTimePath; AdditionalProperties = razorDesignTimePath is null @@ -180,7 +174,7 @@ private async ValueTask ReloadProjectsAsync(ImmutableSegmentedListLoads a project in the MSBuild host. /// Caller needs to catch exceptions to avoid bringing down the project loader queue. @@ -215,7 +209,7 @@ private async Task ReloadProjectAsync(ProjectToLoad projectToLoad, ToastEr return false; } - (RemoteProjectFile remoteProjectFile, bool hasAllInformation, BuildHostProcessKind preferredBuildHostKind, BuildHostProcessKind actualBuildHostKind) = remoteProjectLoadResult; + (RemoteProjectFile remoteProjectFile, ProjectSystemProjectFactory projectFactory, bool isMiscellaneousFile, BuildHostProcessKind preferredBuildHostKind, BuildHostProcessKind actualBuildHostKind) = remoteProjectLoadResult; if (preferredBuildHostKind != actualBuildHostKind) preferredBuildHostKindThatWeDidNotGet = preferredBuildHostKind; @@ -232,7 +226,7 @@ private async Task ReloadProjectAsync(ProjectToLoad projectToLoad, ToastEr // The out-of-proc build host supports more languages than we may actually have Workspace binaries for, so ensure we can actually process that // language in-process. var projectLanguage = loadedProjectInfos.FirstOrDefault()?.Language; - if (projectLanguage != null && ProjectFactory.Workspace.Services.GetLanguageService(projectLanguage) == null) + if (projectLanguage != null && projectFactory.Workspace.Services.GetLanguageService(projectLanguage) == null) { return false; } @@ -252,10 +246,10 @@ private async Task ReloadProjectAsync(ProjectToLoad projectToLoad, ToastEr var newProjectTargetsBuilder = ArrayBuilder.GetInstance(loadedProjectInfos.Length); foreach (var loadedProjectInfo in loadedProjectInfos) { - var (target, targetAlreadyExists) = await GetOrCreateProjectTargetAsync(previousProjectTargets, loadedProjectInfo); + var (target, targetAlreadyExists) = await GetOrCreateProjectTargetAsync(previousProjectTargets, projectFactory, loadedProjectInfo); newProjectTargetsBuilder.Add(target); - var (targetTelemetryInfo, targetNeedsRestore) = await target.UpdateWithNewProjectInfoAsync(loadedProjectInfo, hasAllInformation, _logger); + var (targetTelemetryInfo, targetNeedsRestore) = await target.UpdateWithNewProjectInfoAsync(loadedProjectInfo, isMiscellaneousFile, _logger); needsRestore |= targetNeedsRestore; if (!targetAlreadyExists) { @@ -278,15 +272,19 @@ private async Task ReloadProjectAsync(ProjectToLoad projectToLoad, ToastEr await _projectLoadTelemetryReporter.ReportProjectLoadTelemetryAsync(telemetryInfos, projectToLoad, cancellationToken); } - if (currentLoadState is ProjectLoadState.Primordial(var projectId)) + if (currentLoadState is ProjectLoadState.Primordial(var primordialProjectFactory, var projectId)) { // Remove the primordial project now that the design-time build pass is finished. This ensures that // we have the new project in place before we remove the primordial project; otherwise for // Miscellaneous Files we could have a case where we'd get another request to create a project // for the project we're currently processing. - await ProjectFactory.ApplyChangeToWorkspaceAsync(workspace => workspace.OnProjectRemoved(projectId), cancellationToken); + await primordialProjectFactory.ApplyChangeToWorkspaceAsync(workspace => workspace.OnProjectRemoved(projectId), cancellationToken); } + // At this point we expect that all the loaded projects are now in the project factory returned, and any previous ones have been removed. + // this is a Debug.Assert() because if this expectation fails, the user's probably still in a state where things will work just fine; + // throwing here would mean we don't remember the LoadedProjects we created, and the next update will create more and things will get really broken. + Debug.Assert(newProjectTargets.All(target => target.ProjectFactory == projectFactory)); _loadedProjects[projectPath] = new ProjectLoadState.LoadedTargets(newProjectTargets); } @@ -312,9 +310,9 @@ private async Task ReloadProjectAsync(ProjectToLoad projectToLoad, ToastEr return false; } - async Task<(LoadedProject, bool alreadyExists)> GetOrCreateProjectTargetAsync(ImmutableArray previousProjectTargets, ProjectFileInfo loadedProjectInfo) + async Task<(LoadedProject, bool alreadyExists)> GetOrCreateProjectTargetAsync(ImmutableArray previousProjectTargets, ProjectSystemProjectFactory projectFactory, ProjectFileInfo loadedProjectInfo) { - var existingProject = previousProjectTargets.FirstOrDefault(p => p.GetTargetFramework() == loadedProjectInfo.TargetFramework); + var existingProject = previousProjectTargets.FirstOrDefault(p => p.GetTargetFramework() == loadedProjectInfo.TargetFramework && p.ProjectFactory == projectFactory); if (existingProject != null) { return (existingProject, alreadyExists: true); @@ -330,13 +328,13 @@ private async Task ReloadProjectAsync(ProjectToLoad projectToLoad, ToastEr CompilationOutputAssemblyFilePath = loadedProjectInfo.IntermediateOutputFilePath, }; - var projectSystemProject = await ProjectFactory.CreateAndAddToWorkspaceAsync( + var projectSystemProject = await projectFactory.CreateAndAddToWorkspaceAsync( projectSystemName, loadedProjectInfo.Language, projectCreationInfo, _projectSystemHostInfo); - var loadedProject = new LoadedProject(projectSystemProject, ProjectFactory.Workspace.Services.SolutionServices, _fileChangeWatcher, _targetFrameworkManager); + var loadedProject = new LoadedProject(projectSystemProject, projectFactory, _fileChangeWatcher, _targetFrameworkManager); loadedProject.NeedsReload += (_, _) => _projectsToReload.AddWork(projectToLoad with { ReportTelemetry = false }); return (loadedProject, alreadyExists: false); } @@ -364,6 +362,14 @@ async Task LogDiagnosticsAsync(ImmutableArray diagnosticLogIt } } + protected async ValueTask IsProjectLoadedAsync(string projectPath, CancellationToken cancellationToken) + { + using (await _gate.DisposableWaitAsync(cancellationToken)) + { + return _loadedProjects.ContainsKey(projectPath); + } + } + /// /// Begins loading a project with an associated primordial project. Must not be called for a project which has already begun loading. /// @@ -371,7 +377,7 @@ async Task LogDiagnosticsAsync(ImmutableArray diagnosticLogIt /// If , initiates a design-time build now, and starts file watchers to repeat the design-time build on relevant changes. /// If , only tracks the primordial project. /// - protected async ValueTask BeginLoadingProjectWithPrimordialAsync(string projectPath, ProjectId primordialProjectId, bool doDesignTimeBuild) + protected async ValueTask BeginLoadingProjectWithPrimordialAsync(string projectPath, ProjectSystemProjectFactory primordialProjectFactory, ProjectId primordialProjectId, bool doDesignTimeBuild) { using (await _gate.DisposableWaitAsync(CancellationToken.None)) { @@ -383,7 +389,7 @@ protected async ValueTask BeginLoadingProjectWithPrimordialAsync(string projectP Contract.Fail($"Cannot begin loading project '{projectPath}' because it has already begun loading."); } - _loadedProjects.Add(projectPath, new ProjectLoadState.Primordial(primordialProjectId)); + _loadedProjects.Add(projectPath, new ProjectLoadState.Primordial(primordialProjectFactory, primordialProjectId)); if (doDesignTimeBuild) { _projectsToReload.AddWork(new ProjectToLoad(projectPath, ProjectGuid: null, ReportTelemetry: true)); @@ -422,9 +428,9 @@ protected async ValueTask UnloadProjectAsync(string projectPath) return; } - if (loadState is ProjectLoadState.Primordial(var projectId)) + if (loadState is ProjectLoadState.Primordial(var projectFactory, var projectId)) { - await ProjectFactory.ApplyChangeToWorkspaceAsync(workspace => workspace.OnProjectRemoved(projectId)); + await projectFactory.ApplyChangeToWorkspaceAsync(workspace => workspace.OnProjectRemoved(projectId)); } else if (loadState is ProjectLoadState.LoadedTargets(var existingProjects)) { diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerProjectSystem.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerProjectSystem.cs index 0b1f6e306d66b..7e86d7845f54d 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerProjectSystem.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerProjectSystem.cs @@ -4,13 +4,13 @@ using System.Collections.Immutable; using System.Composition; -using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer.HostWorkspace.ProjectTelemetry; using Microsoft.CodeAnalysis.MSBuild; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.ProjectSystem; using Microsoft.CodeAnalysis.Shared.TestHooks; +using Microsoft.CodeAnalysis.Workspaces.ProjectSystem; using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.Composition; using Roslyn.Utilities; @@ -23,6 +23,7 @@ internal sealed class LanguageServerProjectSystem : LanguageServerProjectLoader { private readonly ILogger _logger; private readonly ProjectFileExtensionRegistry _projectFileExtensionRegistry; + private readonly ProjectSystemProjectFactory _hostProjectFactory; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] @@ -36,7 +37,6 @@ public LanguageServerProjectSystem( ServerConfigurationFactory serverConfigurationFactory, IBinLogPathProvider binLogPathProvider) : base( - workspaceFactory.HostProjectFactory, workspaceFactory.TargetFrameworkManager, workspaceFactory.ProjectSystemHostInfo, fileChangeWatcher, @@ -48,14 +48,15 @@ public LanguageServerProjectSystem( binLogPathProvider) { _logger = loggerFactory.CreateLogger(nameof(LanguageServerProjectSystem)); - var workspace = ProjectFactory.Workspace; + _hostProjectFactory = workspaceFactory.HostProjectFactory; + var workspace = workspaceFactory.HostWorkspace; _projectFileExtensionRegistry = new ProjectFileExtensionRegistry(workspace.CurrentSolution.Services, new DiagnosticReporter(workspace)); } public async Task OpenSolutionAsync(string solutionFilePath) { _logger.LogInformation(string.Format(LanguageServerResources.Loading_0, solutionFilePath)); - ProjectFactory.SolutionPath = solutionFilePath; + _hostProjectFactory.SolutionPath = solutionFilePath; var (_, projects) = await SolutionFileReader.ReadSolutionFileAsync(solutionFilePath, DiagnosticReportingMode.Throw, CancellationToken.None); foreach (var (path, guid) in projects) @@ -89,6 +90,6 @@ public async Task OpenProjectsAsync(ImmutableArray projectFilePaths) var (buildHost, actualBuildHostKind) = await buildHostProcessManager.GetBuildHostWithFallbackAsync(preferredBuildHostKind, projectPath, cancellationToken); var loadedFile = await buildHost.LoadProjectFileAsync(projectPath, languageName, cancellationToken); - return new RemoteProjectLoadResult(loadedFile, HasAllInformation: true, preferredBuildHostKind, actualBuildHostKind); + return new RemoteProjectLoadResult(loadedFile, _hostProjectFactory, IsMiscellaneousFile: false, preferredBuildHostKind, actualBuildHostKind); } } diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerWorkspaceFactory.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerWorkspaceFactory.cs index e00375533db78..d373b8aedc89b 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerWorkspaceFactory.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerWorkspaceFactory.cs @@ -10,6 +10,7 @@ using Microsoft.CodeAnalysis.LanguageServer.Handler.DebugConfiguration; using Microsoft.CodeAnalysis.LanguageServer.Services; using Microsoft.CodeAnalysis.ProjectSystem; +using Microsoft.CodeAnalysis.Workspaces.AnalyzerRedirecting; using Microsoft.CodeAnalysis.Workspaces.ProjectSystem; using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.Composition; @@ -30,8 +31,8 @@ public LanguageServerWorkspaceFactory( IFileChangeWatcher fileChangeWatcher, [ImportMany] IEnumerable> dynamicFileInfoProviders, ProjectTargetFrameworkManager projectTargetFrameworkManager, - ServerConfigurationFactory serverConfigurationFactory, ExtensionAssemblyManager extensionManager, + [ImportMany] IEnumerable assemblyRedirectors, ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger(nameof(LanguageServerWorkspaceFactory)); @@ -55,18 +56,16 @@ public LanguageServerWorkspaceFactory( // https://github.com/dotnet/roslyn/issues/78560: Move this workspace creation to 'FileBasedProgramsWorkspaceProviderFactory'. // 'CreateSolutionLevelAnalyzerReferencesForWorkspace' needs to be broken out into its own service for us to be able to move this. - var fileBasedProgramsWorkspace = new LanguageServerWorkspace(hostServicesProvider.HostServices, WorkspaceKind.MiscellaneousFiles); - fileBasedProgramsWorkspace.SetCurrentSolution(s => s.WithAnalyzerReferences(CreateSolutionLevelAnalyzerReferencesForWorkspace(fileBasedProgramsWorkspace)), WorkspaceChangeKind.SolutionChanged); + var miscellaneousFilesWorkspace = new LanguageServerWorkspace(hostServicesProvider.HostServices, WorkspaceKind.MiscellaneousFiles); + miscellaneousFilesWorkspace.SetCurrentSolution(s => s.WithAnalyzerReferences(CreateSolutionLevelAnalyzerReferencesForWorkspace(miscellaneousFilesWorkspace)), WorkspaceChangeKind.SolutionChanged); - FileBasedProgramsProjectFactory = new ProjectSystemProjectFactory( - fileBasedProgramsWorkspace, fileChangeWatcher, static (_, _) => Task.CompletedTask, _ => { }, CancellationToken.None); - fileBasedProgramsWorkspace.ProjectSystemProjectFactory = FileBasedProgramsProjectFactory; + MiscellaneousFilesWorkspaceProjectFactory = new ProjectSystemProjectFactory( + miscellaneousFilesWorkspace, fileChangeWatcher, static (_, _) => Task.CompletedTask, _ => { }, CancellationToken.None); + miscellaneousFilesWorkspace.ProjectSystemProjectFactory = MiscellaneousFilesWorkspaceProjectFactory; - var razorSourceGenerator = serverConfigurationFactory?.ServerConfiguration?.RazorSourceGenerator; ProjectSystemHostInfo = new ProjectSystemHostInfo( DynamicFileInfoProviders: [.. dynamicFileInfoProviders], - new HostDiagnosticAnalyzerProvider(razorSourceGenerator), - AnalyzerAssemblyRedirectors: []); + AnalyzerAssemblyRedirectors: [.. assemblyRedirectors]); TargetFrameworkManager = projectTargetFrameworkManager; } @@ -74,7 +73,7 @@ public LanguageServerWorkspaceFactory( public Workspace HostWorkspace => HostProjectFactory.Workspace; public ProjectSystemProjectFactory HostProjectFactory { get; } - public ProjectSystemProjectFactory FileBasedProgramsProjectFactory { get; } + public ProjectSystemProjectFactory MiscellaneousFilesWorkspaceProjectFactory { get; } public ProjectSystemHostInfo ProjectSystemHostInfo { get; } public ProjectTargetFrameworkManager TargetFrameworkManager { get; } diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LoadedProject.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LoadedProject.cs index 7a2c74612d7ad..01ec48364d582 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LoadedProject.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LoadedProject.cs @@ -5,6 +5,7 @@ using System.Collections.Immutable; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServer.Handler.DebugConfiguration; +using Microsoft.CodeAnalysis.LanguageServer.HostWorkspace.FileWatching; using Microsoft.CodeAnalysis.LanguageServer.HostWorkspace.ProjectTelemetry; using Microsoft.CodeAnalysis.MSBuild; using Microsoft.CodeAnalysis.ProjectSystem; @@ -24,8 +25,10 @@ internal sealed class LoadedProject : IDisposable private readonly string _projectDirectory; private readonly ProjectSystemProject _projectSystemProject; + public ProjectSystemProjectFactory ProjectFactory { get; } private readonly ProjectSystemProjectOptionsProcessor _optionsProcessor; - private readonly IFileChangeContext _fileChangeContext; + private readonly IFileChangeContext _sourceFileChangeContext; + private readonly IFileChangeContext _projectFileChangeContext; private readonly ProjectTargetFrameworkManager _targetFrameworkManager; /// @@ -40,35 +43,30 @@ internal sealed class LoadedProject : IDisposable private ImmutableArray _mostRecentMetadataReferences = []; private ImmutableArray _mostRecentAnalyzerReferences = []; - public LoadedProject(ProjectSystemProject projectSystemProject, SolutionServices solutionServices, IFileChangeWatcher fileWatcher, ProjectTargetFrameworkManager targetFrameworkManager) + public LoadedProject(ProjectSystemProject projectSystemProject, ProjectSystemProjectFactory projectFactory, IFileChangeWatcher fileWatcher, ProjectTargetFrameworkManager targetFrameworkManager) { Contract.ThrowIfNull(projectSystemProject.FilePath); _projectFilePath = projectSystemProject.FilePath; _projectSystemProject = projectSystemProject; - _optionsProcessor = new ProjectSystemProjectOptionsProcessor(projectSystemProject, solutionServices); + ProjectFactory = projectFactory; + _optionsProcessor = new ProjectSystemProjectOptionsProcessor(projectSystemProject, projectFactory.Workspace.CurrentSolution.Services); _targetFrameworkManager = targetFrameworkManager; // We'll watch the directory for all source file changes // TODO: we only should listen for add/removals here, but we can't specify such a filter now _projectDirectory = Path.GetDirectoryName(_projectFilePath)!; - _fileChangeContext = fileWatcher.CreateContext([new(_projectDirectory, [".cs", ".cshtml", ".razor"])]); - _fileChangeContext.FileChanged += FileChangedContext_FileChanged; + _sourceFileChangeContext = fileWatcher.CreateContext([new(_projectDirectory, [".cs", ".cshtml", ".razor"])]); + _sourceFileChangeContext.FileChanged += SourceFileChangeContext_FileChanged; - // Start watching for file changes for the project file as well - _fileChangeContext.EnqueueWatchingFile(_projectFilePath); + _projectFileChangeContext = fileWatcher.CreateContext([]); + _projectFileChangeContext.FileChanged += ProjectFileChangeContext_FileChanged; + _projectFileChangeContext.EnqueueWatchingFile(_projectFilePath); } - private void FileChangedContext_FileChanged(object? sender, string filePath) + private void SourceFileChangeContext_FileChanged(object? sender, string filePath) { - // If the project file itself changed, we almost certainly need to reload the project. - if (string.Equals(filePath, _projectFilePath, StringComparison.OrdinalIgnoreCase)) - { - NeedsReload?.Invoke(this, EventArgs.Empty); - return; - } - var matchers = _mostRecentFileMatchers?.Value; if (matchers is null) { @@ -92,6 +90,11 @@ private void FileChangedContext_FileChanged(object? sender, string filePath) } } + private void ProjectFileChangeContext_FileChanged(object? sender, string filePath) + { + NeedsReload?.Invoke(this, EventArgs.Empty); + } + public event EventHandler? NeedsReload; public string? GetTargetFramework() @@ -105,12 +108,13 @@ private void FileChangedContext_FileChanged(object? sender, string filePath) /// public void Dispose() { - _fileChangeContext.Dispose(); + _sourceFileChangeContext.Dispose(); + _projectFileChangeContext.Dispose(); _optionsProcessor.Dispose(); _projectSystemProject.RemoveFromWorkspace(); } - public async ValueTask<(ProjectLoadTelemetryReporter.TelemetryInfo, bool NeedsRestore)> UpdateWithNewProjectInfoAsync(ProjectFileInfo newProjectInfo, bool hasAllInformation, ILogger logger) + public async ValueTask<(ProjectLoadTelemetryReporter.TelemetryInfo, bool NeedsRestore)> UpdateWithNewProjectInfoAsync(ProjectFileInfo newProjectInfo, bool isMiscellaneousFile, ILogger logger) { if (_mostRecentFileInfo != null) { @@ -122,15 +126,11 @@ public void Dispose() var disposableBatchScope = await _projectSystemProject.CreateBatchScopeAsync(CancellationToken.None).ConfigureAwait(false); await using var _ = disposableBatchScope.ConfigureAwait(false); - var projectDisplayName = Path.GetFileNameWithoutExtension(newProjectInfo.FilePath)!; - var projectFullPathWithTargetFramework = newProjectInfo.FilePath; - - if (newProjectInfo.TargetFramework != null) - { - var targetFrameworkSuffix = " (" + newProjectInfo.TargetFramework + ")"; - projectDisplayName += targetFrameworkSuffix; - projectFullPathWithTargetFramework += targetFrameworkSuffix; - } + var targetFrameworkSuffix = newProjectInfo.TargetFramework != null ? " (" + newProjectInfo.TargetFramework + ")" : ""; + var projectDisplayName = isMiscellaneousFile + ? FeaturesResources.Miscellaneous_Files + : Path.GetFileNameWithoutExtension(newProjectInfo.FilePath) + targetFrameworkSuffix; + var projectFullPathWithTargetFramework = newProjectInfo.FilePath + targetFrameworkSuffix; _projectSystemProject.DisplayName = projectDisplayName; _projectSystemProject.OutputFilePath = newProjectInfo.OutputFilePath; @@ -138,7 +138,7 @@ public void Dispose() _projectSystemProject.GeneratedFilesOutputDirectory = newProjectInfo.GeneratedFilesOutputDirectory; _projectSystemProject.CompilationOutputAssemblyFilePath = newProjectInfo.IntermediateOutputFilePath; _projectSystemProject.DefaultNamespace = newProjectInfo.DefaultNamespace; - _projectSystemProject.HasAllInformation = hasAllInformation; + _projectSystemProject.HasAllInformation = !isMiscellaneousFile; if (newProjectInfo.TargetFrameworkIdentifier != null) { @@ -221,7 +221,7 @@ public void Dispose() document => _projectSystemProject.RemoveDynamicSourceFile(document.FilePath), "Project {0} now has {1} dynamic file(s)."); - WatchProjectAssetsFile(newProjectInfo, _fileChangeContext); + WatchProjectAssetsFile(newProjectInfo); var needsRestore = ProjectDependencyHelper.NeedsRestore(newProjectInfo, _mostRecentFileInfo, logger); @@ -272,7 +272,7 @@ void UpdateProjectSystemProjectCollection(IEnumerable loadedCollection, IE logger.LogTrace(logMessage, projectFullPathWithTargetFramework, newItems.Count); } - void WatchProjectAssetsFile(ProjectFileInfo currentProjectInfo, IFileChangeContext fileChangeContext) + void WatchProjectAssetsFile(ProjectFileInfo currentProjectInfo) { if (_mostRecentFileInfo?.ProjectAssetsFilePath == currentProjectInfo.ProjectAssetsFilePath) { @@ -282,14 +282,9 @@ void WatchProjectAssetsFile(ProjectFileInfo currentProjectInfo, IFileChangeConte // Dispose of the last once since we're changing the file we're watching. _mostRecentProjectAssetsFileWatcher?.Dispose(); - - IWatchedFile? currentWatcher = null; - if (currentProjectInfo.ProjectAssetsFilePath != null) - { - currentWatcher = fileChangeContext.EnqueueWatchingFile(currentProjectInfo.ProjectAssetsFilePath); - } - - _mostRecentProjectAssetsFileWatcher = currentWatcher; + _mostRecentProjectAssetsFileWatcher = currentProjectInfo.ProjectAssetsFilePath is { } assetsFilePath + ? _projectFileChangeContext.EnqueueWatchingFile(assetsFilePath) + : null; } } diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/ProjectDependencyHelper.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/ProjectDependencyHelper.cs index 8d229e510681b..aa88faf77a0c3 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/ProjectDependencyHelper.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/ProjectDependencyHelper.cs @@ -13,6 +13,7 @@ using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServer.HostWorkspace; + internal static class ProjectDependencyHelper { internal const string ProjectNeedsRestoreName = "workspace/_roslyn_projectNeedsRestore"; diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/RazorClientLanguageServerManagerFactory.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/RazorClientLanguageServerManagerFactory.cs index 826e3a39d1456..29e9a42863ccf 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/RazorClientLanguageServerManagerFactory.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/RazorClientLanguageServerManagerFactory.cs @@ -5,7 +5,6 @@ using System.Composition; using Microsoft.CodeAnalysis.ExternalAccess.Razor; using Microsoft.CodeAnalysis.Host.Mef; -using Microsoft.CodeAnalysis.LanguageServer; namespace Microsoft.CodeAnalysis.LanguageServer.HostWorkspace.Razor; diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/RazorDynamicFileInfoProvider.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/RazorDynamicFileInfoProvider.cs index 6eb90d6d0efba..37a86c3fe05dd 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/RazorDynamicFileInfoProvider.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/RazorDynamicFileInfoProvider.cs @@ -19,7 +19,7 @@ namespace Microsoft.CodeAnalysis.LanguageServer.HostWorkspace.Razor; [ExportMetadata("Extensions", new string[] { "cshtml", "razor", })] [method: ImportingConstructor] [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] -internal sealed partial class RazorDynamicFileInfoProvider(Lazy workspaceFactory, ILoggerFactory loggerFactory) : IDynamicFileInfoProvider, ILspService, IOnInitialized +internal sealed partial class RazorDynamicFileInfoProvider(Lazy workspaceFactory, ILoggerFactory loggerFactory) : IDynamicFileInfoProvider, ILspService, IOnInitialized, IDisposable { private RazorWorkspaceService? _razorWorkspaceService; private RazorLspDynamicFileInfoProvider? _dynamicFileInfoProvider; @@ -80,4 +80,11 @@ public async Task RemoveDynamicFileInfoAsync(ProjectId projectId, string? projec await _dynamicFileInfoProvider.RemoveDynamicFileInfoAsync(workspaceFactory.Value.HostWorkspace, projectId, projectFilePath, filePath, cancellationToken).ConfigureAwait(false); } + + public void Dispose() + { + // Dispose is called when the LSP server is being shut down. Clear the dynamic file provider in case a workspace + // event is raised after, as the actual provider will try to make LSP requests. + _dynamicFileInfoProvider = null; + } } diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/RazorInitializer.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/RazorInitializer.cs new file mode 100644 index 0000000000000..6773f0c322a8f --- /dev/null +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/RazorInitializer.cs @@ -0,0 +1,39 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Composition; +using Microsoft.CodeAnalysis.Contracts.Telemetry; +using Microsoft.CodeAnalysis.ExternalAccess.Razor.Features; +using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.LanguageServer.Handler; +using Roslyn.LanguageServer.Protocol; + +namespace Microsoft.CodeAnalysis.LanguageServer.HostWorkspace.Razor; + +[Shared] +[ExportRazorStatelessLspService(typeof(RazorInitializer))] +[method: ImportingConstructor] +[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] +internal sealed class RazorInitializer(Lazy workspaceFactory, [Import(AllowDefault = true)] ITelemetryReporter? telemetryReporter) : ILspService, IOnInitialized +{ + public Task OnInitializedAsync(ClientCapabilities clientCapabilities, RequestContext context, CancellationToken cancellationToken) + { + var razorInitializerService = context.GetService(); + if (razorInitializerService is null) + { + // No initializer service registered, nothing to do. + return Task.CompletedTask; + } + + razorInitializerService.Initialize(workspaceFactory.Value.HostWorkspace); + + var razorTelemetryReporter = context.GetService(); + if (telemetryReporter is not null && razorTelemetryReporter is not null) + { + razorTelemetryReporter.Initialize(new TelemetryReporterWrapper(telemetryReporter)); + } + + return Task.CompletedTask; + } +} diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/TelemetryReporterWrapper.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/TelemetryReporterWrapper.cs new file mode 100644 index 0000000000000..707a31dc6339f --- /dev/null +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/TelemetryReporterWrapper.cs @@ -0,0 +1,16 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Microsoft.CodeAnalysis.Contracts.Telemetry; +using Microsoft.CodeAnalysis.ExternalAccess.Razor.Features; + +namespace Microsoft.CodeAnalysis.LanguageServer.HostWorkspace.Razor; + +internal class TelemetryReporterWrapper(ITelemetryReporter telemetryReporter) : ILanguageServerTelemetryReporterWrapper +{ + public void ReportEvent(string name, List> properties) + { + telemetryReporter.Log(name, properties); + } +} diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/WorkspaceProjectFactoryService.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/WorkspaceProjectFactoryService.cs index 90b2b00d53ab2..267e4a7006e69 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/WorkspaceProjectFactoryService.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/WorkspaceProjectFactoryService.cs @@ -11,34 +11,29 @@ using Microsoft.VisualStudio.Shell.ServiceBroker; namespace Microsoft.CodeAnalysis.LanguageServer.HostWorkspace; + #pragma warning disable RS0030 // This is intentionally using System.ComponentModel.Composition for compatibility with MEF service broker. + /// /// An implementation of the brokered service that just maps calls to the underlying project system. /// [ExportBrokeredService("Microsoft.VisualStudio.LanguageServices.WorkspaceProjectFactoryService", null, Audience = ServiceAudience.Local)] -internal sealed class WorkspaceProjectFactoryService : IWorkspaceProjectFactoryService, IExportedBrokeredService +[method: ImportingConstructor] +[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] +internal sealed class WorkspaceProjectFactoryService( + LanguageServerWorkspaceFactory workspaceFactory, + ProjectInitializationHandler projectInitializationHandler, + ILoggerFactory loggerFactory) : IWorkspaceProjectFactoryService, IExportedBrokeredService { - private readonly LanguageServerWorkspaceFactory _workspaceFactory; - private readonly ProjectInitializationHandler _projectInitializationHandler; - private readonly ILogger _logger; - private readonly ILoggerFactory _loggerFactory; - - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public WorkspaceProjectFactoryService(LanguageServerWorkspaceFactory workspaceFactory, ProjectInitializationHandler projectInitializationHandler, ILoggerFactory loggerFactory) - { - _workspaceFactory = workspaceFactory; - _projectInitializationHandler = projectInitializationHandler; - _loggerFactory = loggerFactory; - _logger = loggerFactory.CreateLogger(nameof(WorkspaceProjectFactoryService)); - } + private readonly LanguageServerWorkspaceFactory _workspaceFactory = workspaceFactory; + private readonly ProjectInitializationHandler _projectInitializationHandler = projectInitializationHandler; + private readonly ILogger _logger = loggerFactory.CreateLogger(nameof(WorkspaceProjectFactoryService)); + private readonly ILoggerFactory _loggerFactory = loggerFactory; ServiceRpcDescriptor IExportedBrokeredService.Descriptor => WorkspaceProjectFactoryServiceDescriptor.ServiceDescriptor; - async Task IExportedBrokeredService.InitializeAsync(CancellationToken cancellationToken) - { - await _projectInitializationHandler.SubscribeToInitializationCompleteAsync(cancellationToken); - } + Task IExportedBrokeredService.InitializeAsync(CancellationToken cancellationToken) + => _projectInitializationHandler.SubscribeToInitializationCompleteAsync(cancellationToken); public async Task CreateAndAddProjectAsync(WorkspaceProjectCreationInfo creationInfo, CancellationToken _) { diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/Restore/RestoreHandler.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/Restore/RestoreHandler.cs index e419f2ee621c1..5de95267c4daf 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/Restore/RestoreHandler.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/Restore/RestoreHandler.cs @@ -5,6 +5,7 @@ using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.Extensions.Logging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServer.Handler; @@ -17,7 +18,7 @@ namespace Microsoft.CodeAnalysis.LanguageServer.Handler; [Method(MethodName)] [method: ImportingConstructor] [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] -internal sealed class RestoreHandler(DotnetCliHelper dotnetCliHelper) : ILspServiceRequestHandler +internal sealed class RestoreHandler(DotnetCliHelper dotnetCliHelper, ILoggerFactory loggerFactory) : ILspServiceRequestHandler { internal const string MethodName = "workspace/_roslyn_restore"; @@ -25,6 +26,8 @@ internal sealed class RestoreHandler(DotnetCliHelper dotnetCliHelper) : ILspServ public bool RequiresLSPSolution => true; + private readonly ILogger _logger = loggerFactory.CreateLogger(); + public async Task HandleRequestAsync(RestoreParams request, RequestContext context, CancellationToken cancellationToken) { Contract.ThrowIfNull(context.Solution); @@ -35,18 +38,31 @@ public async Task HandleRequestAsync(RestoreParams reque var restorePaths = GetRestorePaths(request, context.Solution, context); if (restorePaths.IsEmpty) { + _logger.LogDebug($"Restore was requested but no paths were provided."); progress.Report(new RestorePartialResult(LanguageServerResources.Restore, LanguageServerResources.Nothing_found_to_restore)); return progress.GetValues() ?? []; } - await RestoreAsync(restorePaths, progress, cancellationToken); + _logger.LogDebug($"Running restore on {restorePaths.Length} paths, starting with '{restorePaths.First()}'."); + bool success = await RestoreAsync(restorePaths, progress, cancellationToken); progress.Report(new RestorePartialResult(LanguageServerResources.Restore, $"{LanguageServerResources.Restore_complete}{Environment.NewLine}")); + if (success) + { + _logger.LogDebug($"Restore completed successfully."); + } + else + { + _logger.LogError($"Restore completed with errors. See '.NET NuGet Restore' output window for more details."); + } + return progress.GetValues() ?? []; } - private async Task RestoreAsync(ImmutableArray pathsToRestore, BufferedProgress progress, CancellationToken cancellationToken) + /// True if all restore invocations exited with code 0. Otherwise, false. + private async Task RestoreAsync(ImmutableArray pathsToRestore, BufferedProgress progress, CancellationToken cancellationToken) { + bool success = true; foreach (var path in pathsToRestore) { var arguments = new string[] { "restore", path }; @@ -71,9 +87,12 @@ private async Task RestoreAsync(ImmutableArray pathsToRestore, BufferedP if (process.ExitCode != 0) { ReportProgress(progress, stageName, string.Format(LanguageServerResources.Failed_to_run_restore_on_0, path)); + success = false; } } + return success; + static void ReportProgress(BufferedProgress progress, string stage, string? restoreOutput) { if (restoreOutput != null) diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/RazorDynamicDocumentSyncRegistration.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/RazorDynamicDocumentSyncRegistration.cs index 8dc138c0af942..8dc4944473c18 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/RazorDynamicDocumentSyncRegistration.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/RazorDynamicDocumentSyncRegistration.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Composition; +using System.Text.Json.Nodes; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.Options; @@ -18,19 +19,22 @@ internal sealed class RazorDynamicDocumentSyncRegistration(IGlobalOptionService public ILspService CreateILspService(LspServices lspServices, WellKnownLspServerKinds serverKind) => new OnInitialized(globalOptionService); - public sealed class OnInitialized : IOnInitialized, ILspService + public sealed class OnInitialized(IGlobalOptionService globalOptionService) : IOnInitialized, ILspService { - private readonly IGlobalOptionService _globalOptionService; - - public OnInitialized(IGlobalOptionService globalOptionService) - { - _globalOptionService = globalOptionService; - } - public async Task OnInitializedAsync(ClientCapabilities clientCapabilities, RequestContext context, CancellationToken cancellationToken) { // Hot reload only works in devkit scenarios. Without, there is no need to register for dynamic document sync. - if (!_globalOptionService.GetOption(LspOptionsStorage.LspUsingDevkitFeatures)) + if (!globalOptionService.GetOption(LspOptionsStorage.LspUsingDevkitFeatures)) + { + return; + } + + var languageServerManager = context.GetRequiredLspService(); + + // We know devkit is enabled, but we need to check cohosting too. Cohosting will register for document sync, and if we do + // it here as well, VS Code will send us duplicate open/close/change events for the same file, corrupting our documents. + if (clientCapabilities.Workspace?.Configuration == true && + await IsCohostingEnabledAsync(languageServerManager, cancellationToken).ConfigureAwait(false)) { return; } @@ -40,8 +44,6 @@ public async Task OnInitializedAsync(ClientCapabilities clientCapabilities, Requ // the contents. if (clientCapabilities.TextDocument?.Synchronization?.DynamicRegistration is true) { - var languageServerManager = context.GetRequiredLspService(); - var documentFilters = new[] { new DocumentFilter() { Pattern = "**/*.{razor, cshtml}", Language = "aspnetcorerazor" } }; var registrationOptions = new TextDocumentRegistrationOptions() { @@ -79,6 +81,26 @@ await languageServerManager.SendRequestAsync(Methods.ClientRegisterCapabilityNam cancellationToken).ConfigureAwait(false); } } + + private static async Task IsCohostingEnabledAsync(IClientLanguageServerManager languageServerManager, CancellationToken cancellationToken) + { + var configurationParams = new ConfigurationParams() + { + Items = [ + // Roslyn's typescript config handler will convert underscores to camelcase, so this checking + // the 'razor.languageServer.cohostingEnabled' option + new ConfigurationItem { Section = "razor.language_server.cohosting_enabled" }, + ] + }; + + var options = await languageServerManager.SendRequestAsync( + Methods.WorkspaceConfigurationName, + configurationParams, + cancellationToken).ConfigureAwait(false); + + return options is [{ } result] && + result.ToString() == "true"; + } } } diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/Logging/LspLogMessageLoggerProvider.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/Logging/LspLogMessageLoggerProvider.cs index 45e1524a510de..4961b162a56f9 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/Logging/LspLogMessageLoggerProvider.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/Logging/LspLogMessageLoggerProvider.cs @@ -6,6 +6,7 @@ using Microsoft.Extensions.Logging; namespace Microsoft.CodeAnalysis.LanguageServer.Logging; + internal sealed class LspLogMessageLoggerProvider(ILoggerFactory fallbackLoggerFactory, ServerConfiguration serverConfiguration) : ILoggerProvider, ISupportExternalScope { private readonly ConcurrentDictionary _loggers = new(StringComparer.OrdinalIgnoreCase); diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/Microsoft.CodeAnalysis.LanguageServer.csproj b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/Microsoft.CodeAnalysis.LanguageServer.csproj index d1e49ba706322..c32f01a669587 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/Microsoft.CodeAnalysis.LanguageServer.csproj +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/Microsoft.CodeAnalysis.LanguageServer.csproj @@ -45,13 +45,13 @@ $(ArtifactsDir)/LanguageServer/$(Configuration)/$(TargetFramework)/neutral - $(TargetRid) - $(BaseRid) - win-x64;win-arm64;linux-x64;linux-arm64;linux-musl-x64;linux-musl-arm64;osx-x64;osx-arm64 + $(PortableTargetRid) + win-x64;win-arm64;linux-x64;linux-arm64;linux-musl-x64;linux-musl-arm64;osx-x64;osx-arm64 false diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/Program.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/Program.cs index b8cc22db39030..a0660a5fe4844 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/Program.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/Program.cs @@ -273,7 +273,6 @@ static CommandLineConfiguration CreateCommandLineParser() var sessionId = parseResult.GetValue(sessionIdOption); var extensionAssemblyPaths = parseResult.GetValue(extensionAssemblyPathsOption) ?? []; var devKitDependencyPath = parseResult.GetValue(devKitDependencyPathOption); - var razorSourceGenerator = parseResult.GetValue(razorSourceGeneratorOption); var razorDesignTimePath = parseResult.GetValue(razorDesignTimePathOption); var extensionLogDirectory = parseResult.GetValue(extensionLogDirectoryOption)!; var serverPipeName = parseResult.GetValue(serverPipeNameOption); @@ -287,7 +286,6 @@ static CommandLineConfiguration CreateCommandLineParser() SessionId: sessionId, ExtensionAssemblyPaths: extensionAssemblyPaths, DevKitDependencyPath: devKitDependencyPath, - RazorSourceGenerator: razorSourceGenerator, RazorDesignTimePath: razorDesignTimePath, ServerPipeName: serverPipeName, UseStdIo: useStdIo, diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/ServerConfigurationFactory.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/ServerConfigurationFactory.cs index 97de814c384c1..2688be1c7aade 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/ServerConfigurationFactory.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/ServerConfigurationFactory.cs @@ -48,7 +48,6 @@ internal sealed record class ServerConfiguration( string? SessionId, IEnumerable ExtensionAssemblyPaths, string? DevKitDependencyPath, - string? RazorSourceGenerator, string? RazorDesignTimePath, string? ServerPipeName, bool UseStdIo, diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/Services/ExtensionAssemblyManagerProvider.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/Services/ExtensionAssemblyManagerProvider.cs index b28dc2fd495ff..f9dadd6f613d0 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/Services/ExtensionAssemblyManagerProvider.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/Services/ExtensionAssemblyManagerProvider.cs @@ -14,8 +14,6 @@ namespace Microsoft.CodeAnalysis.LanguageServer.Services; [Export, Shared] internal sealed class ExtensionAssemblyManagerMefProvider { - private ExtensionAssemblyManager? _extensionAssemblyManager; - [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ExtensionAssemblyManagerMefProvider() @@ -23,10 +21,10 @@ public ExtensionAssemblyManagerMefProvider() } [Export] - public ExtensionAssemblyManager ExtensionAssemblyManager => _extensionAssemblyManager ?? throw new InvalidOperationException($"{nameof(ExtensionAssemblyManager)} is not initialized"); + public ExtensionAssemblyManager ExtensionAssemblyManager { get => field ?? throw new InvalidOperationException($"{nameof(ExtensionAssemblyManager)} is not initialized"); private set; } public void SetMefExtensionAssemblyManager(ExtensionAssemblyManager extensionAssemblyManager) { - _extensionAssemblyManager = extensionAssemblyManager; + ExtensionAssemblyManager = extensionAssemblyManager; } } diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/Services/StarredCompletions/StarredCompletionsAssemblyHelper.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/Services/StarredCompletions/StarredCompletionsAssemblyHelper.cs index 9702b71d27f11..d535fbfade194 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/Services/StarredCompletions/StarredCompletionsAssemblyHelper.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/Services/StarredCompletions/StarredCompletionsAssemblyHelper.cs @@ -11,6 +11,7 @@ using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServer.StarredSuggestions; + internal static class StarredCompletionAssemblyHelper { private const string CompletionsDllName = "Microsoft.VisualStudio.IntelliCode.CSharp.dll"; diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/Testing/TestRunner.TestRunHandler.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/Testing/TestRunner.TestRunHandler.cs index 2cc948741a56a..ee15168da275d 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/Testing/TestRunner.TestRunHandler.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/Testing/TestRunner.TestRunHandler.cs @@ -7,7 +7,6 @@ using System.Text; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.LanguageServer.Handler.Testing; -using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; diff --git a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.UnitTests/TestExampleLanguageServer.cs b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.UnitTests/TestExampleLanguageServer.cs index 2b9685daab706..864b196093d55 100644 --- a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.UnitTests/TestExampleLanguageServer.cs +++ b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.UnitTests/TestExampleLanguageServer.cs @@ -41,10 +41,8 @@ public async Task ExecuteRequestAsync(string met return result; } - internal async Task ExecuteNotificationAsync(string methodName, CancellationToken _) - { - await _clientRpc.NotifyAsync(methodName); - } + internal Task ExecuteNotificationAsync(string methodName, CancellationToken _) + => _clientRpc.NotifyAsync(methodName); protected override ILifeCycleManager GetLifeCycleManager() { @@ -143,10 +141,8 @@ internal static TestExampleLanguageServer CreateLanguageServer(ILspLogger logger return server; } - internal async Task ShutdownServerAsync() - { - await ExecuteNotificationAsync(Methods.ShutdownName, CancellationToken.None); - } + internal Task ShutdownServerAsync() + => ExecuteNotificationAsync(Methods.ShutdownName, CancellationToken.None); internal async Task InitializeServerAsync() { diff --git a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/AbstractRequestScope.cs b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/AbstractRequestScope.cs index a676aca30b044..cba82de331629 100644 --- a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/AbstractRequestScope.cs +++ b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/AbstractRequestScope.cs @@ -8,6 +8,7 @@ using System; namespace Microsoft.CommonLanguageServerProtocol.Framework; + internal abstract class AbstractRequestScope(string name) : IDisposable { public string Name { get; } = name; diff --git a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/BannedSymbols.txt b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/BannedSymbols.txt index 3860919601f36..42fd708fa29ec 100644 --- a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/BannedSymbols.txt +++ b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/BannedSymbols.txt @@ -70,11 +70,4 @@ M:Microsoft.CodeAnalysis.CodeActions.CodeAction.GetPreviewOperationsAsync(System M:Microsoft.CodeAnalysis.CodeActions.CodeAction.ComputeOperationsAsync(System.Threading.CancellationToken); Use overload that takes progress M:Microsoft.CodeAnalysis.CodeActions.CodeAction.GetChangedSolutionAsync(CSystem.Threading.CancellationToken); Use overload that takes progress M:Microsoft.CodeAnalysis.CodeActions.CodeAction.GetChangedDocumentAsync(CancellationToken); Use overload that takes progress -M:System.Diagnostics.Tracing.EventSource.WriteEvent(System.Int32,System.Object[]); Use WriteEventCore instead -E:Microsoft.CodeAnalysis.Workspace.WorkspaceChanged; Use RegisterWorkspaceChangedHandler instead -E:Microsoft.CodeAnalysis.Workspace.WorkspaceFailed; Use RegisterWorkspaceFailedHandler instead -E:Microsoft.CodeAnalysis.Workspace.DocumentOpened; Use RegisterDocumentOpenedHandler instead -E:Microsoft.CodeAnalysis.Workspace.TextDocumentOpened; Use RegisterTextDocumentOpenedHandler instead -E:Microsoft.CodeAnalysis.Workspace.DocumentClosed; Use RegisterDocumentClosedHandler instead -E:Microsoft.CodeAnalysis.Workspace.TextDocumentClosed; Use RegisterTextDocumentClosedHandler instead -E:Microsoft.CodeAnalysis.Workspace.DocumentActiveContextChanged; Use RegisterDocumentActiveContextChangedHandler instead \ No newline at end of file +M:System.Diagnostics.Tracing.EventSource.WriteEvent(System.Int32,System.Object[]); Use WriteEventCore instead \ No newline at end of file diff --git a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/IRequestHandler.cs b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/IRequestHandler.cs index 7d58b68427183..d6513086a1ac1 100644 --- a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/IRequestHandler.cs +++ b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/IRequestHandler.cs @@ -9,6 +9,7 @@ using System.Threading.Tasks; namespace Microsoft.CommonLanguageServerProtocol.Framework; + internal interface IRequestHandler : IMethodHandler { /// diff --git a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/MethodHandlerDetails.cs b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/MethodHandlerDetails.cs index 83f087cb0eb3e..62d8c66ad2c36 100644 --- a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/MethodHandlerDetails.cs +++ b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/MethodHandlerDetails.cs @@ -115,9 +115,9 @@ private static (string name, IEnumerable languages) GetRequestHandlerMet static LanguageServerEndpointAttribute? GetMethodAttributeFromHandlerMethod(Type handlerType, Type? requestType, Type contextType, Type? responseType) { - const string HandleRequestName = nameof(IRequestHandler.HandleRequestAsync); + const string HandleRequestName = nameof(IRequestHandler<,,>.HandleRequestAsync); const string HandleRequestSuffix = "." + HandleRequestName; - const string HandleNotificationName = nameof(INotificationHandler.HandleNotificationAsync); + const string HandleNotificationName = nameof(INotificationHandler<,>.HandleNotificationAsync); const string HandleNotificationSuffix = "." + HandleNotificationName; foreach (var methodInfo in handlerType.GetRuntimeMethods()) diff --git a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/RequestExecutionQueue.cs b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/RequestExecutionQueue.cs index a45651f422bab..f8f0cb307fb63 100644 --- a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/RequestExecutionQueue.cs +++ b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/RequestExecutionQueue.cs @@ -55,7 +55,7 @@ namespace Microsoft.CommonLanguageServerProtocol.Framework; internal class RequestExecutionQueue : IRequestExecutionQueue { private static readonly MethodInfo s_processQueueCoreAsync = typeof(RequestExecutionQueue) - .GetMethod(nameof(RequestExecutionQueue.ProcessQueueCoreAsync), BindingFlags.NonPublic | BindingFlags.Instance)!; + .GetMethod(nameof(RequestExecutionQueue<>.ProcessQueueCoreAsync), BindingFlags.NonPublic | BindingFlags.Instance)!; protected readonly ILspLogger _logger; protected readonly AbstractHandlerProvider _handlerProvider; diff --git a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/RequestShutdownEventArgs.cs b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/RequestShutdownEventArgs.cs index 2351cf23539f9..14a0e1e11fdcf 100644 --- a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/RequestShutdownEventArgs.cs +++ b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/RequestShutdownEventArgs.cs @@ -8,6 +8,7 @@ using System; namespace Microsoft.CommonLanguageServerProtocol.Framework; + internal sealed class RequestShutdownEventArgs : EventArgs { public string Message { get; } diff --git a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/TypeRef.cs b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/TypeRef.cs index cad8ecf214836..07ab59a9d145d 100644 --- a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/TypeRef.cs +++ b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/TypeRef.cs @@ -17,8 +17,6 @@ internal sealed partial class TypeRef : IEquatable { private static readonly ConcurrentDictionary<(string TypeName, string AssemblyName, string? CodeBase), TypeRef> s_cache = []; - private string? _assemblyQualifiedName; - private TypeRef(string typeName, string assemblyName, string? codeBase = null) { TypeName = typeName ?? throw new ArgumentNullException(nameof(typeName)); @@ -44,8 +42,7 @@ private TypeRef(string typeName, string assemblyName, string? codeBase = null) /// /// Returns the assembly-qualified name of this type. /// - public string AssemblyQualifiedName - => _assemblyQualifiedName ??= $"{TypeName}, {AssemblyName}"; + public string AssemblyQualifiedName { get => field ??= $"{TypeName}, {AssemblyName}"; private set; } public override bool Equals(object? obj) => Equals(obj as TypeRef); diff --git a/src/LanguageServer/Protocol.TestUtilities/Diagnostics/TestDiagnosticAnalyzerDriver.cs b/src/LanguageServer/Protocol.TestUtilities/Diagnostics/TestDiagnosticAnalyzerDriver.cs index dcfbef292e3f7..8db65c18438a3 100644 --- a/src/LanguageServer/Protocol.TestUtilities/Diagnostics/TestDiagnosticAnalyzerDriver.cs +++ b/src/LanguageServer/Protocol.TestUtilities/Diagnostics/TestDiagnosticAnalyzerDriver.cs @@ -11,7 +11,6 @@ using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Shared.Extensions; -using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; diff --git a/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs b/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs index a887ae34e8a51..2db0568718b2c 100644 --- a/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs +++ b/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs @@ -14,8 +14,8 @@ using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.LanguageServer.Handler; diff --git a/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLspBuildOnlyDiagnosticsTests.cs b/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLspBuildOnlyDiagnosticsTests.cs index fac39c6d25119..9856d91ddaeaa 100644 --- a/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLspBuildOnlyDiagnosticsTests.cs +++ b/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLspBuildOnlyDiagnosticsTests.cs @@ -36,7 +36,9 @@ public void TestExportedDiagnosticIds() var enumMembers = ErrorCodeType.GetFields(BindingFlags.Public | BindingFlags.Static); var enumMember = enumMembers.First(m => Convert.ToInt32(m.GetValue(null)) == codeValue); - errorMessage.AppendLine($@"Missing: ""{missingItem}, // {ErrorCodeType.Name}.{enumMember.Name}"""); + errorMessage.AppendLine($""" + Missing: "{missingItem}, // {ErrorCodeType.Name}.{enumMember.Name}" + """); } var extra = actualDiagnosticCodes.Except(ExpectedDiagnosticCodes); diff --git a/src/LanguageServer/Protocol/Extensions/ProtocolConversions.cs b/src/LanguageServer/Protocol/Extensions/ProtocolConversions.cs index 314b72bf01c0d..9c4c254d8ee7a 100644 --- a/src/LanguageServer/Protocol/Extensions/ProtocolConversions.cs +++ b/src/LanguageServer/Protocol/Extensions/ProtocolConversions.cs @@ -7,7 +7,6 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text.Json; using System.Text.RegularExpressions; @@ -21,6 +20,7 @@ using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.NavigateTo; using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SpellCheck; using Microsoft.CodeAnalysis.Tags; using Microsoft.CodeAnalysis.Text; @@ -389,15 +389,15 @@ public static LSP.Range TextSpanToRange(TextSpan textSpan, SourceText text) /// Compute all the for the input list of changed documents. /// Additionally maps the locations of the changed documents if necessary. /// - public static async Task ChangedDocumentsToTextDocumentEditsAsync(IEnumerable changedDocuments, Func getNewDocumentFunc, - Func getOldDocumentFunc, IDocumentTextDifferencingService? textDiffService, CancellationToken cancellationToken) where T : TextDocument + public static async Task ChangedDocumentsToTextDocumentEditsAsync(IEnumerable changedDocuments, Solution newSolution, + Solution oldSolution, IDocumentTextDifferencingService? textDiffService, CancellationToken cancellationToken) { using var _ = ArrayBuilder<(DocumentUri Uri, LSP.TextEdit TextEdit)>.GetInstance(out var uriToTextEdits); foreach (var docId in changedDocuments) { - var newDocument = getNewDocumentFunc(docId); - var oldDocument = getOldDocumentFunc(docId); + var newDocument = await newSolution.GetRequiredDocumentAsync(docId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); + var oldDocument = await oldSolution.GetRequiredDocumentAsync(docId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var oldText = await oldDocument.GetValueTextAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/LanguageServer/Protocol/ExternalAccess/Razor/FormatNewFileHandler.cs b/src/LanguageServer/Protocol/ExternalAccess/Razor/FormatNewFileHandler.cs index 9f1e7ce63a1be..2c6e24f6bbfe8 100644 --- a/src/LanguageServer/Protocol/ExternalAccess/Razor/FormatNewFileHandler.cs +++ b/src/LanguageServer/Protocol/ExternalAccess/Razor/FormatNewFileHandler.cs @@ -15,7 +15,6 @@ using Microsoft.CodeAnalysis.RemoveUnnecessaryImports; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; -using Roslyn.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.ExternalAccess.Razor; diff --git a/src/LanguageServer/Protocol/Features/CodeCleanup/DiagnosticSet.cs b/src/LanguageServer/Protocol/Features/CodeCleanup/DiagnosticSet.cs index 2696479ea11fa..c63daa770b413 100644 --- a/src/LanguageServer/Protocol/Features/CodeCleanup/DiagnosticSet.cs +++ b/src/LanguageServer/Protocol/Features/CodeCleanup/DiagnosticSet.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CodeCleanup; diff --git a/src/LanguageServer/Protocol/Features/DecompiledSource/AssemblyResolver.cs b/src/LanguageServer/Protocol/Features/DecompiledSource/AssemblyResolver.cs index d34ce538af13b..da70d86cc57ee 100644 --- a/src/LanguageServer/Protocol/Features/DecompiledSource/AssemblyResolver.cs +++ b/src/LanguageServer/Protocol/Features/DecompiledSource/AssemblyResolver.cs @@ -14,7 +14,6 @@ using System.Text; using System.Threading.Tasks; using ICSharpCode.Decompiler.Metadata; -using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.DecompiledSource; diff --git a/src/LanguageServer/Protocol/Features/Diagnostics/DiagnosticDataExtensions.cs b/src/LanguageServer/Protocol/Features/Diagnostics/DiagnosticDataExtensions.cs index 668de389af191..baa4f69547e7d 100644 --- a/src/LanguageServer/Protocol/Features/Diagnostics/DiagnosticDataExtensions.cs +++ b/src/LanguageServer/Protocol/Features/Diagnostics/DiagnosticDataExtensions.cs @@ -2,17 +2,18 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Microsoft.CodeAnalysis.ErrorReporting; +using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.Serialization.Json; using System.Text; -using System; using Microsoft.CodeAnalysis.Diagnostics; -using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.ErrorReporting; namespace Microsoft.CodeAnalysis.LanguageServer.Features.Diagnostics; + internal static class DiagnosticDataExtensions { internal static bool TryGetUnnecessaryDataLocations(this DiagnosticData diagnosticData, [NotNullWhen(true)] out ImmutableArray? unnecessaryLocations) diff --git a/src/LanguageServer/Protocol/Features/Options/FindUsagesOptionsStorage.cs b/src/LanguageServer/Protocol/Features/Options/FindUsagesOptionsStorage.cs index e4b6a7d415c7d..bd3b9f57f2ca1 100644 --- a/src/LanguageServer/Protocol/Features/Options/FindUsagesOptionsStorage.cs +++ b/src/LanguageServer/Protocol/Features/Options/FindUsagesOptionsStorage.cs @@ -2,8 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Classification; +using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.FindUsages; diff --git a/src/LanguageServer/Protocol/Features/Options/WorkspaceConfigurationService.cs b/src/LanguageServer/Protocol/Features/Options/WorkspaceConfigurationService.cs index d89464da63ae2..d7706018e0e00 100644 --- a/src/LanguageServer/Protocol/Features/Options/WorkspaceConfigurationService.cs +++ b/src/LanguageServer/Protocol/Features/Options/WorkspaceConfigurationService.cs @@ -4,27 +4,22 @@ using System; using System.Composition; +using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Host; [ExportWorkspaceService(typeof(IWorkspaceConfigurationService), ServiceLayer.Host), Shared] -internal sealed class WorkspaceConfigurationService : IWorkspaceConfigurationService +[method: ImportingConstructor] +[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] +internal sealed class WorkspaceConfigurationService(IGlobalOptionService globalOptions) : IWorkspaceConfigurationService { - private readonly IGlobalOptionService _globalOptions; - private WorkspaceConfigurationOptions? _lazyOptions; + private readonly IGlobalOptionService _globalOptions = globalOptions; - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public WorkspaceConfigurationService(IGlobalOptionService globalOptions) - { - _globalOptions = globalOptions; - } - - public WorkspaceConfigurationOptions Options - => _lazyOptions ??= _globalOptions.GetWorkspaceConfigurationOptions(); + [AllowNull] + public WorkspaceConfigurationOptions Options { get => field ??= _globalOptions.GetWorkspaceConfigurationOptions(); private set; } internal void Clear() - => _lazyOptions = null; + => Options = null; } diff --git a/src/LanguageServer/Protocol/Features/UnifiedSuggestions/UnifiedSuggestedActionsSource.cs b/src/LanguageServer/Protocol/Features/UnifiedSuggestions/UnifiedSuggestedActionsSource.cs index c0e3fea2f6f27..147461645c514 100644 --- a/src/LanguageServer/Protocol/Features/UnifiedSuggestions/UnifiedSuggestedActionsSource.cs +++ b/src/LanguageServer/Protocol/Features/UnifiedSuggestions/UnifiedSuggestedActionsSource.cs @@ -677,7 +677,7 @@ private static ImmutableArray GetInitiallyOrderedActi // There was a selection. Treat refactorings as more important than fixes. // Note: we still will sort after this. So any high pri fixes will come to the // front. Any low-pri refactorings will go to the end. - return refactorings.Concat(fixes); + return [.. refactorings, .. fixes]; } else { @@ -697,7 +697,7 @@ private static ImmutableArray GetInitiallyOrderedActi var highPriFixes = fixes.WhereAsArray(s => s.Priority == CodeActionPriority.High); var nonHighPriFixes = fixes.WhereAsArray(s => s.Priority != CodeActionPriority.High); - return highPriFixes.Concat(highPriRefactorings).Concat(nonHighPriFixes).Concat(nonHighPriRefactorings); + return [.. highPriFixes, .. highPriRefactorings, .. nonHighPriFixes, .. nonHighPriRefactorings]; } } diff --git a/src/LanguageServer/Protocol/Handler/CodeActions/CodeActionResolveHelper.cs b/src/LanguageServer/Protocol/Handler/CodeActions/CodeActionResolveHelper.cs index a7bfd10318aeb..43b9ed45e3b73 100644 --- a/src/LanguageServer/Protocol/Handler/CodeActions/CodeActionResolveHelper.cs +++ b/src/LanguageServer/Protocol/Handler/CodeActions/CodeActionResolveHelper.cs @@ -9,6 +9,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; diff --git a/src/LanguageServer/Protocol/Handler/CodeLens/CodeLensHandler.cs b/src/LanguageServer/Protocol/Handler/CodeLens/CodeLensHandler.cs index 116e30bea6158..490e9e35c41ff 100644 --- a/src/LanguageServer/Protocol/Handler/CodeLens/CodeLensHandler.cs +++ b/src/LanguageServer/Protocol/Handler/CodeLens/CodeLensHandler.cs @@ -15,8 +15,8 @@ using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; -using LSP = Roslyn.LanguageServer.Protocol; using Microsoft.CodeAnalysis.Text; +using LSP = Roslyn.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.CodeLens; diff --git a/src/LanguageServer/Protocol/Handler/Completion/CompletionResultFactory.cs b/src/LanguageServer/Protocol/Handler/Completion/CompletionResultFactory.cs index 9dc762e8063fa..d2f72643fcbcd 100644 --- a/src/LanguageServer/Protocol/Handler/Completion/CompletionResultFactory.cs +++ b/src/LanguageServer/Protocol/Handler/Completion/CompletionResultFactory.cs @@ -10,6 +10,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers.Snippets; using Microsoft.CodeAnalysis.ErrorReporting; diff --git a/src/LanguageServer/Protocol/Handler/Configuration/DidChangeConfigurationNotificationHandler.cs b/src/LanguageServer/Protocol/Handler/Configuration/DidChangeConfigurationNotificationHandler.cs index 0fc92f10bfef3..0b2189c6711ad 100644 --- a/src/LanguageServer/Protocol/Handler/Configuration/DidChangeConfigurationNotificationHandler.cs +++ b/src/LanguageServer/Protocol/Handler/Configuration/DidChangeConfigurationNotificationHandler.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.Linq; using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; @@ -104,7 +105,7 @@ private async Task RefreshOptionsAsync(CancellationToken cancellationToken) { if (option.Definition.Serializer.TryParse(valueFromClient, out var parsedValue)) { - optionsToUpdate.Add(KeyValuePairUtil.Create(new OptionKey2(option, language: languageName), parsedValue)); + optionsToUpdate.Add(KeyValuePair.Create(new OptionKey2(option, language: languageName), parsedValue)); } else { diff --git a/src/LanguageServer/Protocol/Handler/Configuration/DidChangeConfigurationNotificationHandler_OptionList.cs b/src/LanguageServer/Protocol/Handler/Configuration/DidChangeConfigurationNotificationHandler_OptionList.cs index 89fa870411f15..1f5f594cec1d6 100644 --- a/src/LanguageServer/Protocol/Handler/Configuration/DidChangeConfigurationNotificationHandler_OptionList.cs +++ b/src/LanguageServer/Protocol/Handler/Configuration/DidChangeConfigurationNotificationHandler_OptionList.cs @@ -6,7 +6,6 @@ using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.DocumentHighlighting; using Microsoft.CodeAnalysis.Formatting; -using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.ImplementType; using Microsoft.CodeAnalysis.InlineHints; using Microsoft.CodeAnalysis.LanguageServer.HostWorkspace; diff --git a/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractDocumentPullDiagnosticHandler.cs b/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractDocumentPullDiagnosticHandler.cs index f9919ddd6afab..a6ac09fcfea3c 100644 --- a/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractDocumentPullDiagnosticHandler.cs +++ b/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractDocumentPullDiagnosticHandler.cs @@ -34,16 +34,16 @@ protected override ValueTask> GetOrderedDiagno // // Only consider open documents here (and only closed ones in the WorkspacePullDiagnosticHandler). Each // handler treats those as separate worlds that they are responsible for. - var textDocument = context.TextDocument; - if (textDocument is null) + var identifier = GetTextDocumentIdentifier(diagnosticsParams); + if (identifier is null || context.Document is null) { context.TraceDebug("Ignoring diagnostics request because no text document was provided"); return new([]); } - if (!context.IsTracking(textDocument.GetURI())) + if (!context.IsTracking(identifier.DocumentUri)) { - context.TraceWarning($"Ignoring diagnostics request for untracked document: {textDocument.GetURI()}"); + context.TraceWarning($"Ignoring diagnostics request for untracked document: {identifier.DocumentUri}"); return new([]); } diff --git a/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSourceProviders/DocumentSyntaxAndSemanticDiagnosticSourceProvider.cs b/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSourceProviders/DocumentSyntaxAndSemanticDiagnosticSourceProvider.cs index 3216b53f46d1d..e7be797f951aa 100644 --- a/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSourceProviders/DocumentSyntaxAndSemanticDiagnosticSourceProvider.cs +++ b/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSourceProviders/DocumentSyntaxAndSemanticDiagnosticSourceProvider.cs @@ -24,12 +24,7 @@ internal abstract class AbstractDocumentSyntaxAndSemanticDiagnosticSourceProvide public ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) { - if (context.GetTrackedDocument() is { } document) - { - return new([new DocumentDiagnosticSource(kind, document)]); - } - - return new([]); + return new([new DocumentDiagnosticSource(kind, context.GetRequiredDocument())]); } [Export(typeof(IDiagnosticSourceProvider)), Shared] diff --git a/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticsRefreshQueue.cs b/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticsRefreshQueue.cs index 0157e87911c49..fa10d0c7d0dfe 100644 --- a/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticsRefreshQueue.cs +++ b/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticsRefreshQueue.cs @@ -4,7 +4,6 @@ using System; using System.Composition; -using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.TestHooks; diff --git a/src/LanguageServer/Protocol/Handler/Diagnostics/Public/PublicDocumentNonLocalDiagnosticSourceProvider.cs b/src/LanguageServer/Protocol/Handler/Diagnostics/Public/PublicDocumentNonLocalDiagnosticSourceProvider.cs index 064d4761e82ab..dd616a4051063 100644 --- a/src/LanguageServer/Protocol/Handler/Diagnostics/Public/PublicDocumentNonLocalDiagnosticSourceProvider.cs +++ b/src/LanguageServer/Protocol/Handler/Diagnostics/Public/PublicDocumentNonLocalDiagnosticSourceProvider.cs @@ -31,11 +31,10 @@ internal sealed class PublicDocumentNonLocalDiagnosticSourceProvider( public ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) { // Non-local document diagnostics are reported only when full solution analysis is enabled for analyzer execution. - if (context.GetTrackedDocument() is { } textDocument && - globalOptions.GetBackgroundAnalysisScope(textDocument.Project.Language) == BackgroundAnalysisScope.FullSolution) + if (globalOptions.GetBackgroundAnalysisScope(context.GetRequiredDocument().Project.Language) == BackgroundAnalysisScope.FullSolution) { // NOTE: Compiler does not report any non-local diagnostics, so we bail out for compiler analyzer. - return new([new NonLocalDocumentDiagnosticSource(textDocument, a => !a.IsCompilerAnalyzer())]); + return new([new NonLocalDocumentDiagnosticSource(context.GetRequiredDocument(), a => !a.IsCompilerAnalyzer())]); } return new([]); diff --git a/src/LanguageServer/Protocol/Handler/EditAndContinue/DocumentEditAndContinueDiagnosticSourceProvider.cs b/src/LanguageServer/Protocol/Handler/EditAndContinue/DocumentEditAndContinueDiagnosticSourceProvider.cs index 5f66ca41cdddb..a7a223a8e77c4 100644 --- a/src/LanguageServer/Protocol/Handler/EditAndContinue/DocumentEditAndContinueDiagnosticSourceProvider.cs +++ b/src/LanguageServer/Protocol/Handler/EditAndContinue/DocumentEditAndContinueDiagnosticSourceProvider.cs @@ -25,11 +25,6 @@ internal sealed class DocumentEditAndContinueDiagnosticSourceProvider() : IDiagn public ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) { - if (context.GetTrackedDocument() is { } document) - { - return new([EditAndContinueDiagnosticSource.CreateOpenDocumentSource(document)]); - } - - return new([]); + return new([EditAndContinueDiagnosticSource.CreateOpenDocumentSource(context.GetRequiredDocument())]); } } diff --git a/src/LanguageServer/Protocol/Handler/Extensions/DispatchWorkspaceExtensionMessageParams.cs b/src/LanguageServer/Protocol/Handler/Extensions/DispatchWorkspaceExtensionMessageParams.cs index e3b7d10ecfba0..30c5630faf9dd 100644 --- a/src/LanguageServer/Protocol/Handler/Extensions/DispatchWorkspaceExtensionMessageParams.cs +++ b/src/LanguageServer/Protocol/Handler/Extensions/DispatchWorkspaceExtensionMessageParams.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Text.Json.Serialization; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.Extensions; diff --git a/src/LanguageServer/Protocol/Handler/Formatting/AbstractFormatDocumentHandlerBase.cs b/src/LanguageServer/Protocol/Handler/Formatting/AbstractFormatDocumentHandlerBase.cs index 02940fd506389..a9a1c8b311170 100644 --- a/src/LanguageServer/Protocol/Handler/Formatting/AbstractFormatDocumentHandlerBase.cs +++ b/src/LanguageServer/Protocol/Handler/Formatting/AbstractFormatDocumentHandlerBase.cs @@ -12,7 +12,6 @@ using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; -using Roslyn.Utilities; using LSP = Roslyn.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler; diff --git a/src/LanguageServer/Protocol/Handler/InlineCompletions/InlineCompletionsHandler.cs b/src/LanguageServer/Protocol/Handler/InlineCompletions/InlineCompletionsHandler.cs index d621d57370022..cc794f09e0589 100644 --- a/src/LanguageServer/Protocol/Handler/InlineCompletions/InlineCompletionsHandler.cs +++ b/src/LanguageServer/Protocol/Handler/InlineCompletions/InlineCompletionsHandler.cs @@ -22,8 +22,8 @@ using Microsoft.CommonLanguageServerProtocol.Framework; using Roslyn.LanguageServer.Protocol; using Roslyn.Utilities; -using LSP = Roslyn.LanguageServer.Protocol; using static Microsoft.CodeAnalysis.LanguageServer.Handler.InlineCompletions.XmlSnippetParser; +using LSP = Roslyn.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.InlineCompletions; diff --git a/src/LanguageServer/Protocol/Handler/Rename/PrepareRenameHandler.cs b/src/LanguageServer/Protocol/Handler/Rename/PrepareRenameHandler.cs index 829c4dba5ba40..0e3eb9b0cc8d5 100644 --- a/src/LanguageServer/Protocol/Handler/Rename/PrepareRenameHandler.cs +++ b/src/LanguageServer/Protocol/Handler/Rename/PrepareRenameHandler.cs @@ -33,7 +33,7 @@ public LSP.TextDocumentIdentifier GetTextDocumentIdentifier(LSP.PrepareRenamePar var position = await document.GetPositionFromLinePositionAsync(linePosition, cancellationToken).ConfigureAwait(false); var symbolicRenameInfo = await SymbolicRenameInfo.GetRenameInfoAsync( - document, position, cancellationToken).ConfigureAwait(false); + document, position, includeSourceGenerated: false, cancellationToken).ConfigureAwait(false); if (symbolicRenameInfo.IsError) return null; diff --git a/src/LanguageServer/Protocol/Handler/Rename/RenameHandler.cs b/src/LanguageServer/Protocol/Handler/Rename/RenameHandler.cs index 63504a054152d..5f4062dfd243a 100644 --- a/src/LanguageServer/Protocol/Handler/Rename/RenameHandler.cs +++ b/src/LanguageServer/Protocol/Handler/Rename/RenameHandler.cs @@ -12,7 +12,6 @@ using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.LanguageServer.Protocol; -using Roslyn.Utilities; using LSP = Roslyn.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler; @@ -29,23 +28,24 @@ internal sealed class RenameHandler() : ILspServiceDocumentRequestHandler request.TextDocument; public Task HandleRequestAsync(RenameParams request, RequestContext context, CancellationToken cancellationToken) - => GetRenameEditAsync(context.GetRequiredDocument(), ProtocolConversions.PositionToLinePosition(request.Position), request.NewName, cancellationToken); + => GetRenameEditAsync(context.GetRequiredDocument(), ProtocolConversions.PositionToLinePosition(request.Position), request.NewName, includeSourceGenerated: false, cancellationToken); - internal static async Task GetRenameEditAsync(Document document, LinePosition linePosition, string newName, CancellationToken cancellationToken) + internal static async Task GetRenameEditAsync(Document document, LinePosition linePosition, string newName, bool includeSourceGenerated, CancellationToken cancellationToken) { var oldSolution = document.Project.Solution; var position = await document.GetPositionFromLinePositionAsync(linePosition, cancellationToken).ConfigureAwait(false); var symbolicRenameInfo = await SymbolicRenameInfo.GetRenameInfoAsync( - document, position, cancellationToken).ConfigureAwait(false); + document, position, includeSourceGenerated, cancellationToken).ConfigureAwait(false); if (symbolicRenameInfo.IsError) return null; var options = new SymbolRenameOptions( - RenameOverloads: false, - RenameInStrings: false, - RenameInComments: false, - RenameFile: false); + renameOverloads: false, + renameInStrings: false, + renameInComments: false, + renameFile: false, + renameInSourceGeneratedDocuments: includeSourceGenerated); var renameLocationSet = await Renamer.FindRenameLocationsAsync( oldSolution, @@ -71,14 +71,18 @@ internal sealed class RenameHandler() : ILspServiceDocumentRequestHandler p.GetChangedDocuments(onlyGetDocumentsWithTextChanges: true)) - .GroupBy(docId => renamedSolution.GetRequiredDocument(docId).FilePath, StringComparer.OrdinalIgnoreCase).Select(group => group.First()); + .GroupBy(docId => renamedSolution.GetRequiredDocument(docId).FilePath, StringComparer.OrdinalIgnoreCase).Select(group => group.First()) + .Concat(solutionChanges.GetExplicitlyChangedSourceGeneratedDocuments()); var textDiffService = renamedSolution.Services.GetRequiredService(); - var documentEdits = await ProtocolConversions.ChangedDocumentsToTextDocumentEditsAsync(changedDocuments, renamedSolution.GetRequiredDocument, oldSolution.GetRequiredDocument, + var documentEdits = await ProtocolConversions.ChangedDocumentsToTextDocumentEditsAsync(changedDocuments, renamedSolution, oldSolution, textDiffService, cancellationToken).ConfigureAwait(false); return new WorkspaceEdit { DocumentChanges = documentEdits }; diff --git a/src/LanguageServer/Protocol/Handler/RequestContext.cs b/src/LanguageServer/Protocol/Handler/RequestContext.cs index 59f2e94a7c2b4..c5639e2e42568 100644 --- a/src/LanguageServer/Protocol/Handler/RequestContext.cs +++ b/src/LanguageServer/Protocol/Handler/RequestContext.cs @@ -55,7 +55,7 @@ internal readonly struct RequestContext /// private readonly StrongBox<(Workspace Workspace, Solution Solution, TextDocument? Document)>? _lspSolution; - public ILspLogger Logger => _logger; + public ILspLogger Logger { get; } /// /// The workspace this request is for, if applicable. This will be present if is @@ -162,11 +162,6 @@ public TextDocument? TextDocument public readonly CancellationToken QueueCancellationToken; - /// - /// Tracing object that can be used to log information about the status of requests. - /// - private readonly ILspLogger _logger; - public RequestContext( Workspace? workspace, Solution? solution, @@ -197,7 +192,7 @@ public RequestContext( ServerKind = serverKind; SupportedLanguages = supportedLanguages; _documentChangeTracker = documentChangeTracker; - _logger = logger; + Logger = logger; _trackedDocuments = trackedDocuments; _lspServices = lspServices; QueueCancellationToken = queueCancellationToken; @@ -320,29 +315,6 @@ public SourceText GetTrackedDocumentSourceText(DocumentUri documentUri) return _trackedDocuments[documentUri].Text; } - public TDocument? GetTrackedDocument() where TDocument : TextDocument - { - // Note: context.Document may be null in the case where the client is asking about a document that we have - // since removed from the workspace. In this case, we don't really have anything to process. - // GetPreviousResults will be used to properly realize this and notify the client that the doc is gone. - // - // Only consider open documents here (and only closed ones in the WorkspacePullDiagnosticHandler). Each - // handler treats those as separate worlds that they are responsible for. - if (TextDocument is not TDocument document) - { - TraceDebug($"Ignoring diagnostics request because no {typeof(TDocument).Name} was provided"); - return null; - } - - if (!IsTracking(document.GetURI())) - { - TraceDebug($"Ignoring diagnostics request for untracked document: {document.GetURI()}"); - return null; - } - - return document; - } - /// /// Allows a mutating request to close a document and stop it being tracked. /// Mutating requests are serialized by the execution queue in order to prevent concurrent access. @@ -362,22 +334,22 @@ public void ClearSolutionContext() } public void TraceDebug(string message) - => _logger.LogDebug(message); + => Logger.LogDebug(message); /// /// Logs an informational message. /// public void TraceInformation(string message) - => _logger.LogInformation(message); + => Logger.LogInformation(message); public void TraceWarning(string message) - => _logger.LogWarning(message); + => Logger.LogWarning(message); public void TraceError(string message) - => _logger.LogError(message); + => Logger.LogError(message); public void TraceException(Exception exception) - => _logger.LogException(exception); + => Logger.LogException(exception); public T GetRequiredLspService() where T : class, ILspService { diff --git a/src/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensHelpers.cs b/src/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensHelpers.cs index cdc848e2f1521..d81dbe025b6b2 100644 --- a/src/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensHelpers.cs +++ b/src/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensHelpers.cs @@ -127,12 +127,35 @@ private static async Task GetClassifiedSpansForDocumentAsync( var spans = await ClassifierHelper.GetClassifiedSpansAsync( document, textSpans, options, includeAdditiveSpans: true, cancellationToken).ConfigureAwait(false); - // The spans returned to us may include some empty spans, which we don't care about. We also don't care - // about the 'text' classification. It's added for everything between real classifications (including + // Some classified spans may not be relevant and should be filtered out before we convert to tokens. + var filteredSpans = spans.Where(s => !ShouldFilterClassification(s)); + + classifiedSpans.AddRange(filteredSpans); + } + + private static bool ShouldFilterClassification(ClassifiedSpan s) + { + // The spans returned to us may include some empty spans, which we don't care about. + if (s.TextSpan.IsEmpty) + { + return true; + } + + // We also don't care about the 'text' classification. It's added for everything between real classifications (including // whitespace), and just means 'don't classify this'. No need for us to actually include that in // semantic tokens as it just wastes space in the result. - var nonEmptySpans = spans.Where(s => !s.TextSpan.IsEmpty && s.ClassificationType != ClassificationTypeNames.Text); - classifiedSpans.AddRange(nonEmptySpans); + if (s.ClassificationType == ClassificationTypeNames.Text) + { + return true; + } + + // Additive classification types that are mapped to TokenModifiers.None are not rendered by the client and do not need to be included. + if (SemanticTokensSchema.AdditiveClassificationTypeToTokenModifier.TryGetValue(s.ClassificationType, out var modifier) && modifier == TokenModifiers.None) + { + return true; + } + + return false; } private static void ConvertMultiLineToSingleLineSpans(SourceText text, SegmentedList classifiedSpans, SegmentedList updatedClassifiedSpans) @@ -288,8 +311,6 @@ private static int ComputeNextToken( var tokenLength = originalTextSpan.Length; Contract.ThrowIfFalse(tokenLength > 0); - // We currently only have one modifier (static). The logic below will need to change in the future if other - // modifiers are added in the future. var modifierBits = TokenModifiers.None; var tokenTypeIndex = 0; @@ -297,28 +318,14 @@ private static int ComputeNextToken( while (classifiedSpans[currentClassifiedSpanIndex].TextSpan == originalTextSpan) { var classificationType = classifiedSpans[currentClassifiedSpanIndex].ClassificationType; - if (classificationType == ClassificationTypeNames.StaticSymbol) - { - // 4. Token modifiers - each set bit will be looked up in SemanticTokensLegend.tokenModifiers - modifierBits |= TokenModifiers.Static; - } - else if (classificationType == ClassificationTypeNames.ReassignedVariable) - { - // 5. Token modifiers - each set bit will be looked up in SemanticTokensLegend.tokenModifiers - modifierBits |= TokenModifiers.ReassignedVariable; - } - else if (classificationType == ClassificationTypeNames.ObsoleteSymbol) - { - // 6. Token modifiers - each set bit will be looked up in SemanticTokensLegend.tokenModifiers - modifierBits |= TokenModifiers.Deprecated; - } - else if (classificationType == ClassificationTypeNames.TestCode) + + if (SemanticTokensSchema.AdditiveClassificationTypeToTokenModifier.TryGetValue(classificationType, out var modifier)) { - // Skip additive types that are not being converted to token modifiers. + modifierBits |= modifier; } else { - // 7. Token type - looked up in SemanticTokensLegend.tokenTypes (language server defined mapping + // 5. Token type - looked up in SemanticTokensLegend.tokenTypes (language server defined mapping // from integer to LSP token types). tokenTypeIndex = GetTokenTypeIndex(classificationType); } diff --git a/src/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensRefreshQueue.cs b/src/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensRefreshQueue.cs index 9f9b69b81d98d..5ab208da751dc 100644 --- a/src/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensRefreshQueue.cs +++ b/src/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensRefreshQueue.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Collections.Generic; using System.IO; using System.Threading; diff --git a/src/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensSchema.cs b/src/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensSchema.cs index c4a59b3fe9fc1..afb4a27b58244 100644 --- a/src/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensSchema.cs +++ b/src/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensSchema.cs @@ -75,6 +75,17 @@ internal readonly struct SemanticTokensSchema classificationTypeName => classificationTypeName, classificationTypeName => IDictionaryExtensions.GetValueOrDefault(s_pureLspDirectTypeMap, classificationTypeName) ?? CustomLspSemanticTokenNames.ClassificationTypeNameToCustomTokenName[classificationTypeName])); + /// + /// Mapping from additive classification type names to LSP token modifiers. + /// + public static readonly ImmutableDictionary AdditiveClassificationTypeToTokenModifier = new Dictionary() + { + [ClassificationTypeNames.StaticSymbol] = SemanticTokens.TokenModifiers.Static, + [ClassificationTypeNames.ReassignedVariable] = SemanticTokens.TokenModifiers.ReassignedVariable, + [ClassificationTypeNames.ObsoleteSymbol] = SemanticTokens.TokenModifiers.Deprecated, + [ClassificationTypeNames.TestCode] = SemanticTokens.TokenModifiers.None, + }.ToImmutableDictionary(); + /// /// Mapping from roslyn to the LSP token name. This is either a standard /// or a custom token name. diff --git a/src/LanguageServer/Protocol/Handler/Symbols/DocumentSymbolsHandler.cs b/src/LanguageServer/Protocol/Handler/Symbols/DocumentSymbolsHandler.cs index 7d1dff87ea08a..3451f3d860d8e 100644 --- a/src/LanguageServer/Protocol/Handler/Symbols/DocumentSymbolsHandler.cs +++ b/src/LanguageServer/Protocol/Handler/Symbols/DocumentSymbolsHandler.cs @@ -14,7 +14,6 @@ using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.LanguageServer.Protocol; -using Roslyn.Utilities; using LSP = Roslyn.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler; diff --git a/src/LanguageServer/Protocol/Handler/Symbols/RoslynDocumentSymbol.cs b/src/LanguageServer/Protocol/Handler/Symbols/RoslynDocumentSymbol.cs index 3d8187fe2cd2f..aa20b58a0cb5f 100644 --- a/src/LanguageServer/Protocol/Handler/Symbols/RoslynDocumentSymbol.cs +++ b/src/LanguageServer/Protocol/Handler/Symbols/RoslynDocumentSymbol.cs @@ -2,8 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Roslyn.LanguageServer.Protocol; using System.Text.Json.Serialization; +using Roslyn.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler; diff --git a/src/LanguageServer/Protocol/Handler/Tasks/DocumentTaskDiagnosticSourceProvider.cs b/src/LanguageServer/Protocol/Handler/Tasks/DocumentTaskDiagnosticSourceProvider.cs index 5e78b219c22f3..09804a1157f42 100644 --- a/src/LanguageServer/Protocol/Handler/Tasks/DocumentTaskDiagnosticSourceProvider.cs +++ b/src/LanguageServer/Protocol/Handler/Tasks/DocumentTaskDiagnosticSourceProvider.cs @@ -25,12 +25,7 @@ internal sealed class DocumentTaskDiagnosticSourceProvider([Import] IGlobalOptio public ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) { - if (context.GetTrackedDocument() is { } document) - { - return new([new TaskListDiagnosticSource(document, globalOptions)]); - } - - return new([]); + return new([new TaskListDiagnosticSource(context.GetRequiredDocument(), globalOptions)]); } } diff --git a/src/LanguageServer/Protocol/ILanguageInfoProvider.cs b/src/LanguageServer/Protocol/ILanguageInfoProvider.cs index d861c8a520a7d..aaaf8fd6f90ab 100644 --- a/src/LanguageServer/Protocol/ILanguageInfoProvider.cs +++ b/src/LanguageServer/Protocol/ILanguageInfoProvider.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Features.Workspaces; using Roslyn.LanguageServer.Protocol; diff --git a/src/LanguageServer/Protocol/LanguageInfoProvider.cs b/src/LanguageServer/Protocol/LanguageInfoProvider.cs index 1e93679364d80..4dac847388244 100644 --- a/src/LanguageServer/Protocol/LanguageInfoProvider.cs +++ b/src/LanguageServer/Protocol/LanguageInfoProvider.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; diff --git a/src/LanguageServer/Protocol/Protocol/ConfigurationItem.cs b/src/LanguageServer/Protocol/Protocol/ConfigurationItem.cs index 4dab90d5e4e39..7499395d5d4d1 100644 --- a/src/LanguageServer/Protocol/Protocol/ConfigurationItem.cs +++ b/src/LanguageServer/Protocol/Protocol/ConfigurationItem.cs @@ -4,7 +4,6 @@ namespace Roslyn.LanguageServer.Protocol; -using System; using System.Text.Json.Serialization; /// diff --git a/src/LanguageServer/Protocol/Protocol/Converters/SumConverter.cs b/src/LanguageServer/Protocol/Protocol/Converters/SumConverter.cs index 8e3089cc915c3..8c766764a6fbe 100644 --- a/src/LanguageServer/Protocol/Protocol/Converters/SumConverter.cs +++ b/src/LanguageServer/Protocol/Protocol/Converters/SumConverter.cs @@ -13,6 +13,7 @@ using Microsoft.CodeAnalysis.LanguageServer; namespace Roslyn.LanguageServer.Protocol; + internal sealed class SumConverter : JsonConverterFactory { public override bool CanConvert(Type typeToConvert) diff --git a/src/LanguageServer/Protocol/Protocol/Converters/TextDocumentSyncConverter.cs b/src/LanguageServer/Protocol/Protocol/Converters/TextDocumentSyncConverter.cs index e09da17edc1b6..8fcd7928086dc 100644 --- a/src/LanguageServer/Protocol/Protocol/Converters/TextDocumentSyncConverter.cs +++ b/src/LanguageServer/Protocol/Protocol/Converters/TextDocumentSyncConverter.cs @@ -9,6 +9,7 @@ using Microsoft.CodeAnalysis.LanguageServer; namespace Roslyn.LanguageServer.Protocol; + internal sealed class TextDocumentSyncConverter : JsonConverter { public override TextDocumentSyncOptions Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) diff --git a/src/LanguageServer/Protocol/Protocol/FileOperations/FileCreate.cs b/src/LanguageServer/Protocol/Protocol/FileOperations/FileCreate.cs index 85a7a960584b7..08c1237860b6b 100644 --- a/src/LanguageServer/Protocol/Protocol/FileOperations/FileCreate.cs +++ b/src/LanguageServer/Protocol/Protocol/FileOperations/FileCreate.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Text.Json.Serialization; namespace Roslyn.LanguageServer.Protocol; diff --git a/src/LanguageServer/Protocol/Protocol/FileOperations/FileDelete.cs b/src/LanguageServer/Protocol/Protocol/FileOperations/FileDelete.cs index 2a7c3c861444d..0883b2b5aaa13 100644 --- a/src/LanguageServer/Protocol/Protocol/FileOperations/FileDelete.cs +++ b/src/LanguageServer/Protocol/Protocol/FileOperations/FileDelete.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Text.Json.Serialization; namespace Roslyn.LanguageServer.Protocol; diff --git a/src/LanguageServer/Protocol/Protocol/FileOperations/FileEvent.cs b/src/LanguageServer/Protocol/Protocol/FileOperations/FileEvent.cs index 8ae8e18844317..7d3bfe0a00ad1 100644 --- a/src/LanguageServer/Protocol/Protocol/FileOperations/FileEvent.cs +++ b/src/LanguageServer/Protocol/Protocol/FileOperations/FileEvent.cs @@ -4,7 +4,6 @@ namespace Roslyn.LanguageServer.Protocol; -using System; using System.Text.Json.Serialization; /// diff --git a/src/LanguageServer/Protocol/Protocol/FileOperations/FileRename.cs b/src/LanguageServer/Protocol/Protocol/FileOperations/FileRename.cs index d8a224b809168..5beabd7944497 100644 --- a/src/LanguageServer/Protocol/Protocol/FileOperations/FileRename.cs +++ b/src/LanguageServer/Protocol/Protocol/FileOperations/FileRename.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Text.Json.Serialization; namespace Roslyn.LanguageServer.Protocol; diff --git a/src/LanguageServer/Protocol/Protocol/FileOperations/RelativePattern.cs b/src/LanguageServer/Protocol/Protocol/FileOperations/RelativePattern.cs index aecd6ff0db9a2..0b8af13f8e384 100644 --- a/src/LanguageServer/Protocol/Protocol/FileOperations/RelativePattern.cs +++ b/src/LanguageServer/Protocol/Protocol/FileOperations/RelativePattern.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Text.Json.Serialization; namespace Roslyn.LanguageServer.Protocol; diff --git a/src/LanguageServer/Protocol/Protocol/Internal/Converters/ClassifiedTextElementConverter.cs b/src/LanguageServer/Protocol/Protocol/Internal/Converters/ClassifiedTextElementConverter.cs index 12ad171c556f5..24a18c9b1d1d2 100644 --- a/src/LanguageServer/Protocol/Protocol/Internal/Converters/ClassifiedTextElementConverter.cs +++ b/src/LanguageServer/Protocol/Protocol/Internal/Converters/ClassifiedTextElementConverter.cs @@ -9,6 +9,7 @@ using Roslyn.Text.Adornments; namespace Roslyn.LanguageServer.Protocol; + internal sealed class ClassifiedTextElementConverter : JsonConverter { public static readonly ClassifiedTextElementConverter Instance = new(); diff --git a/src/LanguageServer/Protocol/Protocol/Internal/Converters/ClassifiedTextRunConverter.cs b/src/LanguageServer/Protocol/Protocol/Internal/Converters/ClassifiedTextRunConverter.cs index 33d033ae1c029..29c4ce255bddf 100644 --- a/src/LanguageServer/Protocol/Protocol/Internal/Converters/ClassifiedTextRunConverter.cs +++ b/src/LanguageServer/Protocol/Protocol/Internal/Converters/ClassifiedTextRunConverter.cs @@ -8,6 +8,7 @@ using Roslyn.Text.Adornments; namespace Roslyn.LanguageServer.Protocol; + internal sealed class ClassifiedTextRunConverter : JsonConverter { public static readonly ClassifiedTextRunConverter Instance = new(); diff --git a/src/LanguageServer/Protocol/Protocol/Internal/VSInternalCompletionItem.cs b/src/LanguageServer/Protocol/Protocol/Internal/VSInternalCompletionItem.cs index 4029fef8729e7..701a58bf385df 100644 --- a/src/LanguageServer/Protocol/Protocol/Internal/VSInternalCompletionItem.cs +++ b/src/LanguageServer/Protocol/Protocol/Internal/VSInternalCompletionItem.cs @@ -4,8 +4,8 @@ namespace Roslyn.LanguageServer.Protocol; -using Roslyn.Text.Adornments; using System.Text.Json.Serialization; +using Roslyn.Text.Adornments; /// /// Extension class for CompletionItem with fields specific to Visual Studio functionalities. diff --git a/src/LanguageServer/Protocol/Protocol/Internal/VSInternalInlineCompletionOptions.cs b/src/LanguageServer/Protocol/Protocol/Internal/VSInternalInlineCompletionOptions.cs index 8987fe0993b49..c432d1f53cf63 100644 --- a/src/LanguageServer/Protocol/Protocol/Internal/VSInternalInlineCompletionOptions.cs +++ b/src/LanguageServer/Protocol/Protocol/Internal/VSInternalInlineCompletionOptions.cs @@ -4,8 +4,8 @@ namespace Roslyn.LanguageServer.Protocol; -using System.Text.RegularExpressions; using System.Text.Json.Serialization; +using System.Text.RegularExpressions; /// /// The options for inline completion. diff --git a/src/LanguageServer/Protocol/Protocol/Internal/VSInternalLocation.cs b/src/LanguageServer/Protocol/Protocol/Internal/VSInternalLocation.cs index d21b28b2aed11..6f02d0ce409ef 100644 --- a/src/LanguageServer/Protocol/Protocol/Internal/VSInternalLocation.cs +++ b/src/LanguageServer/Protocol/Protocol/Internal/VSInternalLocation.cs @@ -5,8 +5,8 @@ namespace Roslyn.LanguageServer.Protocol; using System; -using Roslyn.Text.Adornments; using System.Text.Json.Serialization; +using Roslyn.Text.Adornments; /// /// Extension class for . Used to relay reference text information with colorization. diff --git a/src/LanguageServer/Protocol/Protocol/Internal/VSInternalReferenceItem.cs b/src/LanguageServer/Protocol/Protocol/Internal/VSInternalReferenceItem.cs index 4b17e54d7c97b..ff5901884a173 100644 --- a/src/LanguageServer/Protocol/Protocol/Internal/VSInternalReferenceItem.cs +++ b/src/LanguageServer/Protocol/Protocol/Internal/VSInternalReferenceItem.cs @@ -5,8 +5,8 @@ namespace Roslyn.LanguageServer.Protocol; using System; -using Roslyn.Text.Adornments; using System.Text.Json.Serialization; +using Roslyn.Text.Adornments; /// /// Class which represents references information. diff --git a/src/LanguageServer/Protocol/Protocol/Internal/VSInternalSignatureInformation.cs b/src/LanguageServer/Protocol/Protocol/Internal/VSInternalSignatureInformation.cs index 740c0bc5720df..3dcc1417766b1 100644 --- a/src/LanguageServer/Protocol/Protocol/Internal/VSInternalSignatureInformation.cs +++ b/src/LanguageServer/Protocol/Protocol/Internal/VSInternalSignatureInformation.cs @@ -4,8 +4,8 @@ namespace Roslyn.LanguageServer.Protocol; -using Roslyn.Text.Adornments; using System.Text.Json.Serialization; +using Roslyn.Text.Adornments; /// /// Extension class for signature help information which contains colorized label information. diff --git a/src/LanguageServer/Protocol/Protocol/Navigation/CallHierarchyItem.cs b/src/LanguageServer/Protocol/Protocol/Navigation/CallHierarchyItem.cs index e7f2910f3ac81..e9bded94bffbd 100644 --- a/src/LanguageServer/Protocol/Protocol/Navigation/CallHierarchyItem.cs +++ b/src/LanguageServer/Protocol/Protocol/Navigation/CallHierarchyItem.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Text.Json.Serialization; namespace Roslyn.LanguageServer.Protocol; diff --git a/src/LanguageServer/Protocol/Protocol/Navigation/TypeHierarchyItem.cs b/src/LanguageServer/Protocol/Protocol/Navigation/TypeHierarchyItem.cs index c61c1a00294f9..6eaa7dbc6479d 100644 --- a/src/LanguageServer/Protocol/Protocol/Navigation/TypeHierarchyItem.cs +++ b/src/LanguageServer/Protocol/Protocol/Navigation/TypeHierarchyItem.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Text.Json.Serialization; namespace Roslyn.LanguageServer.Protocol; diff --git a/src/LanguageServer/Protocol/Protocol/Notebook/NotebookCell.cs b/src/LanguageServer/Protocol/Protocol/Notebook/NotebookCell.cs index d90dbc4c7f6cb..dd168a8b07a44 100644 --- a/src/LanguageServer/Protocol/Protocol/Notebook/NotebookCell.cs +++ b/src/LanguageServer/Protocol/Protocol/Notebook/NotebookCell.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Text.Json.Serialization; namespace Roslyn.LanguageServer.Protocol; diff --git a/src/LanguageServer/Protocol/Protocol/PreviousResultId.cs b/src/LanguageServer/Protocol/Protocol/PreviousResultId.cs index c145702b90126..ca975cb66731e 100644 --- a/src/LanguageServer/Protocol/Protocol/PreviousResultId.cs +++ b/src/LanguageServer/Protocol/Protocol/PreviousResultId.cs @@ -4,7 +4,6 @@ namespace Roslyn.LanguageServer.Protocol; -using System; using System.Text.Json.Serialization; /// diff --git a/src/LanguageServer/Protocol/Protocol/PublishDiagnosticParams.cs b/src/LanguageServer/Protocol/Protocol/PublishDiagnosticParams.cs index c55e662c28d81..373b014cc8eb0 100644 --- a/src/LanguageServer/Protocol/Protocol/PublishDiagnosticParams.cs +++ b/src/LanguageServer/Protocol/Protocol/PublishDiagnosticParams.cs @@ -4,7 +4,6 @@ namespace Roslyn.LanguageServer.Protocol; -using System; using System.Text.Json.Serialization; /// diff --git a/src/LanguageServer/Protocol/Protocol/WorkspaceDiagnosticReport.cs b/src/LanguageServer/Protocol/Protocol/WorkspaceDiagnosticReport.cs index 27ba0b8d988a5..67ab89ae95ae6 100644 --- a/src/LanguageServer/Protocol/Protocol/WorkspaceDiagnosticReport.cs +++ b/src/LanguageServer/Protocol/Protocol/WorkspaceDiagnosticReport.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. namespace Roslyn.LanguageServer.Protocol; + using System.Text.Json.Serialization; /// diff --git a/src/LanguageServer/Protocol/Protocol/WorkspaceDiagnosticReportPartialResult.cs b/src/LanguageServer/Protocol/Protocol/WorkspaceDiagnosticReportPartialResult.cs index 49e3baa1bfe3f..64190a9850cc1 100644 --- a/src/LanguageServer/Protocol/Protocol/WorkspaceDiagnosticReportPartialResult.cs +++ b/src/LanguageServer/Protocol/Protocol/WorkspaceDiagnosticReportPartialResult.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. namespace Roslyn.LanguageServer.Protocol; + using System.Text.Json.Serialization; /// diff --git a/src/LanguageServer/Protocol/Protocol/WorkspaceFullDocumentDiagnosticReport.cs b/src/LanguageServer/Protocol/Protocol/WorkspaceFullDocumentDiagnosticReport.cs index 29e4bc9b53bb6..fcd919eaa135e 100644 --- a/src/LanguageServer/Protocol/Protocol/WorkspaceFullDocumentDiagnosticReport.cs +++ b/src/LanguageServer/Protocol/Protocol/WorkspaceFullDocumentDiagnosticReport.cs @@ -4,7 +4,6 @@ namespace Roslyn.LanguageServer.Protocol; -using System; using System.Text.Json.Serialization; /// diff --git a/src/LanguageServer/Protocol/Protocol/WorkspaceSymbolLocation.cs b/src/LanguageServer/Protocol/Protocol/WorkspaceSymbolLocation.cs index 87eafb8705eb8..e0b1c090acf3d 100644 --- a/src/LanguageServer/Protocol/Protocol/WorkspaceSymbolLocation.cs +++ b/src/LanguageServer/Protocol/Protocol/WorkspaceSymbolLocation.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Text.Json.Serialization; namespace Roslyn.LanguageServer.Protocol; diff --git a/src/LanguageServer/Protocol/Protocol/WorkspaceUnchangedDocumentDiagnosticReport.cs b/src/LanguageServer/Protocol/Protocol/WorkspaceUnchangedDocumentDiagnosticReport.cs index 126b6d32d6036..7b76565a1d7f1 100644 --- a/src/LanguageServer/Protocol/Protocol/WorkspaceUnchangedDocumentDiagnosticReport.cs +++ b/src/LanguageServer/Protocol/Protocol/WorkspaceUnchangedDocumentDiagnosticReport.cs @@ -4,7 +4,6 @@ namespace Roslyn.LanguageServer.Protocol; -using System; using System.Text.Json.Serialization; /// diff --git a/src/LanguageServer/Protocol/Workspaces/ILspMiscellaneousFilesWorkspaceProvider.cs b/src/LanguageServer/Protocol/Workspaces/ILspMiscellaneousFilesWorkspaceProvider.cs index 6635fd32f127c..e31acc207ddf3 100644 --- a/src/LanguageServer/Protocol/Workspaces/ILspMiscellaneousFilesWorkspaceProvider.cs +++ b/src/LanguageServer/Protocol/Workspaces/ILspMiscellaneousFilesWorkspaceProvider.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Microsoft.CommonLanguageServerProtocol.Framework; @@ -10,12 +10,19 @@ namespace Microsoft.CodeAnalysis.LanguageServer; +/// +/// Allows the LSP server to create miscellaneous files documents. +/// +/// +/// No methods will be called concurrently, since we are dispatching LSP requests one at a time in the core dispatching loop. +/// This does mean methods should be reasonably fast since they will block the LSP server from processing other requests while they are running. +/// internal interface ILspMiscellaneousFilesWorkspaceProvider : ILspService { /// - /// Returns the actual workspace that the documents are added to or removed from. + /// Returns whether the document is one that came from a previous call to . /// - Workspace Workspace { get; } + ValueTask IsMiscellaneousFilesDocumentAsync(TextDocument document, CancellationToken cancellationToken); /// /// Adds a document to the workspace. Note that the implementation of this method should not depend on anything expensive such as RPC calls. diff --git a/src/LanguageServer/Protocol/Workspaces/ILspWorkspace.cs b/src/LanguageServer/Protocol/Workspaces/ILspWorkspace.cs index 519ed552fb875..d706d4abcd73d 100644 --- a/src/LanguageServer/Protocol/Workspaces/ILspWorkspace.cs +++ b/src/LanguageServer/Protocol/Workspaces/ILspWorkspace.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Microsoft.CodeAnalysis.Text; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Text; using LSP = Roslyn.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer; diff --git a/src/LanguageServer/Protocol/Workspaces/LspMiscellaneousFilesWorkspaceProvider.cs b/src/LanguageServer/Protocol/Workspaces/LspMiscellaneousFilesWorkspaceProvider.cs index d8ead3e1210c1..da46a5825a2b6 100644 --- a/src/LanguageServer/Protocol/Workspaces/LspMiscellaneousFilesWorkspaceProvider.cs +++ b/src/LanguageServer/Protocol/Workspaces/LspMiscellaneousFilesWorkspaceProvider.cs @@ -31,8 +31,11 @@ internal sealed class LspMiscellaneousFilesWorkspaceProvider(ILspServices lspSer { public bool SupportsMutation => true; - // For this implementation, it's easiest to just have it inherit from Workspace, so we'll just return this. - public Workspace Workspace => this; + public ValueTask IsMiscellaneousFilesDocumentAsync(TextDocument document, CancellationToken cancellationToken) + { + // In this case, the only documents ever created live in the Miscellaneous Files workspace (which is this object directly), so we can just compare to 'this'. + return ValueTaskFactory.FromResult(document.Project.Solution.Workspace == this); + } /// /// Takes in a file URI and text and creates a misc project and document for the file. diff --git a/src/LanguageServer/Protocol/Workspaces/LspWorkspaceManager.cs b/src/LanguageServer/Protocol/Workspaces/LspWorkspaceManager.cs index 22e3c092dbbc9..a23b3e4bb0693 100644 --- a/src/LanguageServer/Protocol/Workspaces/LspWorkspaceManager.cs +++ b/src/LanguageServer/Protocol/Workspaces/LspWorkspaceManager.cs @@ -260,21 +260,18 @@ public void UpdateTrackedDocument(DocumentUri uri, SourceText newSourceText) _requestTelemetryLogger.UpdateUsedForkedSolutionCounter(isForked); _logger.LogDebug($"{document.FilePath} found in workspace {workspaceKind}"); - // As we found the document in a non-misc workspace, also attempt to remove it from the misc workspace + // If we found the document in a non-misc workspace, also attempt to remove it from the misc workspace // if it happens to be in there as well. - if (workspace != _lspMiscellaneousFilesWorkspaceProvider?.Workspace) + if (_lspMiscellaneousFilesWorkspaceProvider is not null && !await _lspMiscellaneousFilesWorkspaceProvider.IsMiscellaneousFilesDocumentAsync(document, cancellationToken).ConfigureAwait(false)) { - if (_lspMiscellaneousFilesWorkspaceProvider is not null) + try { - try - { - // Do not attempt to remove the file from the metadata workspace (the document is still open). - await _lspMiscellaneousFilesWorkspaceProvider.TryRemoveMiscellaneousDocumentAsync(uri, removeFromMetadataWorkspace: false).ConfigureAwait(false); - } - catch (Exception ex) when (FatalError.ReportAndCatch(ex)) - { - _logger.LogException(ex); - } + // Do not attempt to remove the file from the metadata workspace (the document is still open). + await _lspMiscellaneousFilesWorkspaceProvider.TryRemoveMiscellaneousDocumentAsync(uri, removeFromMetadataWorkspace: false).ConfigureAwait(false); + } + catch (Exception ex) when (FatalError.ReportAndCatch(ex)) + { + _logger.LogException(ex); } } @@ -569,7 +566,9 @@ public TestAccessor(LspWorkspaceManager manager) public Workspace? GetLspMiscellaneousFilesWorkspace() { - return _manager._lspMiscellaneousFilesWorkspaceProvider?.Workspace; + // For purposes of testing, we test against the implementation that is also a Workspace. + // TODO: once we also test the FileBasedPrograms implementation, we need to do something else here. + return _manager._lspMiscellaneousFilesWorkspaceProvider as Workspace; } public bool IsWorkspaceRegistered(Workspace workspace) diff --git a/src/LanguageServer/ProtocolUnitTests/CodeActions/CodeActionResolveTests.cs b/src/LanguageServer/ProtocolUnitTests/CodeActions/CodeActionResolveTests.cs index 65eddc8a20079..b2d1efa507486 100644 --- a/src/LanguageServer/ProtocolUnitTests/CodeActions/CodeActionResolveTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/CodeActions/CodeActionResolveTests.cs @@ -27,13 +27,15 @@ public CodeActionResolveTests(ITestOutputHelper testOutputHelper) : base(testOut public async Task TestCodeActionResolveHandlerAsync(bool mutatingLspWorkspace) { var initialMarkup = -@"class A -{ - void M() - { - {|caret:|}int i = 1; - } -}"; + """ + class A + { + void M() + { + {|caret:|}int i = 1; + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(initialMarkup, mutatingLspWorkspace); var titlePath = new string[] { CSharpAnalyzersResources.Use_implicit_type }; var unresolvedCodeAction = CodeActionsTests.CreateCodeAction( @@ -78,13 +80,15 @@ void M() public async Task TestCodeActionResolveHandlerAsync_NestedAction(bool mutatingLspWorkspace) { var initialMarkup = -@"class A -{ - void M() - { - int {|caret:|}i = 1; - } -}"; + """ + class A + { + void M() + { + int {|caret:|}i = 1; + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(initialMarkup, mutatingLspWorkspace); var titlePath = new string[] { FeaturesResources.Introduce_constant, string.Format(FeaturesResources.Introduce_constant_for_0, "1") }; var unresolvedCodeAction = CodeActionsTests.CreateCodeAction( @@ -111,9 +115,11 @@ void M() // } var expectedTextEdits = new SumType[] { - GenerateTextEdit(@"private const int V = 1; + GenerateTextEdit(""" + private const int V = 1; + -", new LSP.Range { Start = new Position(2, 4), End = new Position(2, 4) }), + """, new LSP.Range { Start = new Position(2, 4), End = new Position(2, 4) }), GenerateTextEdit("V", new LSP.Range { Start = new Position(4, 16), End = new Position(4, 17) }) }; @@ -138,10 +144,12 @@ void M() [Theory, CombinatorialData] public async Task TestRename(bool mutatingLspWorkspace) { - var markUp = @" -class {|caret:ABC|} -{ -}"; + var markUp = """ + + class {|caret:ABC|} + { + } + """; await using var testLspServer = await CreateTestLspServerAsync(markUp, mutatingLspWorkspace, new InitializationOptions { @@ -214,16 +222,6 @@ class C """; - - var expectedText = """ - class C - { - private static readonly int value = 10; - - public static int Value => value; - } - """; - await using var testLspServer = await CreateXmlTestLspServerAsync(xmlWorkspace, mutatingLspWorkspace); var titlePath = new string[] { string.Format(FeaturesResources.Encapsulate_field_colon_0_and_use_property, "_value") }; var unresolvedCodeAction = CodeActionsTests.CreateCodeAction( @@ -246,20 +244,29 @@ class C var originalText = await testLspServer.GetDocumentTextAsync(textDocumentEdit[0].TextDocument.DocumentUri); var edits = textDocumentEdit[0].Edits.Select(e => (LSP.TextEdit)e.Value!).ToArray(); var updatedText = ApplyTextEdits(edits, originalText); - Assert.Equal(expectedText, updatedText); + Assert.Equal(""" + class C + { + private static readonly int value = 10; + + public static int Value => value; + } + """, updatedText); } [Theory, CombinatorialData] public async Task TestMoveTypeToDifferentFile(bool mutatingLspWorkspace) { - var markUp = @" -class {|caret:ABC|} -{ -} -class BCD -{ -}"; + var markUp = """ + + class {|caret:ABC|} + { + } + class BCD + { + } + """; await using var testLspServer = await CreateTestLspServerAsync(markUp, mutatingLspWorkspace, new InitializationOptions { @@ -321,10 +328,12 @@ class BCD Character = 0 } }, - NewText = @"class ABC -{ -} -" + NewText = """ + class ABC + { + } + + """ } ] }, @@ -376,12 +385,14 @@ class BCD public async Task TestMoveTypeToDifferentFileInDirectory(bool mutatingLspWorkspace) { var markup = -@"class ABC -{ -} -class {|caret:BCD|} -{ -}"; + """ + class ABC + { + } + class {|caret:BCD|} + { + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, new InitializationOptions { @@ -448,9 +459,11 @@ class {|caret:BCD|} Character = 0 } }, - NewText = @"class BCD -{ -}" + NewText = """ + class BCD + { + } + """ } ] }, diff --git a/src/LanguageServer/ProtocolUnitTests/CodeActions/CodeActionsTests.cs b/src/LanguageServer/ProtocolUnitTests/CodeActions/CodeActionsTests.cs index 19e58be47f208..6f38e8f3557f4 100644 --- a/src/LanguageServer/ProtocolUnitTests/CodeActions/CodeActionsTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/CodeActions/CodeActionsTests.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Linq; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; @@ -14,7 +15,6 @@ using Xunit; using Xunit.Abstractions; using LSP = Roslyn.LanguageServer.Protocol; -using System.Text.Json; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.CodeActions; diff --git a/src/LanguageServer/ProtocolUnitTests/CodeActions/RunCodeActionsTests.cs b/src/LanguageServer/ProtocolUnitTests/CodeActions/RunCodeActionsTests.cs index 65b93acd76529..43a1a37b2ceb0 100644 --- a/src/LanguageServer/ProtocolUnitTests/CodeActions/RunCodeActionsTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/CodeActions/RunCodeActionsTests.cs @@ -26,21 +26,14 @@ public RunCodeActionsTests(ITestOutputHelper testOutputHelper) : base(testOutput public async Task TestRunCodeActions(bool mutatingLspWorkspace) { var markup = -@"class A -{ - class {|caret:|}B - { - } -}"; - - var expectedTextForB = -@"partial class A -{ - class B - { - } -}"; - + """ + class A + { + class {|caret:|}B + { + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var caretLocation = testLspServer.GetLocations("caret").Single(); var documentId = new LSP.TextDocumentIdentifier @@ -55,7 +48,14 @@ class B var documentForB = testLspServer.TestWorkspace.CurrentSolution.Projects.Single().Documents.Single(doc => doc.Name.Equals("B.cs", StringComparison.OrdinalIgnoreCase)); var textForB = await documentForB.GetTextAsync(); - Assert.Equal(expectedTextForB, textForB.ToString()); + Assert.Equal(""" + partial class A + { + class B + { + } + } + """, textForB.ToString()); } private static async Task ExecuteRunCodeActionCommandAsync( diff --git a/src/LanguageServer/ProtocolUnitTests/CodeLens/CSharpCodeLensTests.cs b/src/LanguageServer/ProtocolUnitTests/CodeLens/CSharpCodeLensTests.cs index 960a77edb1eef..f4da20cb30dae 100644 --- a/src/LanguageServer/ProtocolUnitTests/CodeLens/CSharpCodeLensTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/CodeLens/CSharpCodeLensTests.cs @@ -24,12 +24,14 @@ public CSharpCodeLensTests(ITestOutputHelper? testOutputHelper) : base(testOutpu public async Task TestNoReferenceAsync(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void {|codeLens:M|}() - { - } -}"; + """ + class A + { + void {|codeLens:M|}() + { + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, CapabilitiesWithVSExtensions); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -38,17 +40,19 @@ public async Task TestNoReferenceAsync(bool mutatingLspWorkspace) public async Task TestOneReferenceAsync(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void {|codeLens:M|}() - { - } - - void UseM() - { - M(); - } -}"; + """ + class A + { + void {|codeLens:M|}() + { + } + + void UseM() + { + M(); + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, CapabilitiesWithVSExtensions); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 1); } @@ -57,18 +61,20 @@ void UseM() public async Task TestMultipleReferencesAsync(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void {|codeLens:M|}() - { - } - - void UseM() - { - M(); - M(); - } -}"; + """ + class A + { + void {|codeLens:M|}() + { + } + + void UseM() + { + M(); + M(); + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, CapabilitiesWithVSExtensions); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 2); } @@ -77,21 +83,23 @@ void UseM() public async Task TestMultipleReferencesCappedAsync(bool lspMutatingWorkspace) { var markup = -@"class A -{ - void {|codeLens:M|}() - { - } - - void UseM() - { - M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M(); - M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M(); - M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M(); - M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M(); - M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M(); - } -}"; + """ + class A + { + void {|codeLens:M|}() + { + } + + void UseM() + { + M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M(); + M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M(); + M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M(); + M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M(); + M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M();M(); + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, lspMutatingWorkspace, CapabilitiesWithVSExtensions); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 100, isCapped: true); } @@ -100,12 +108,14 @@ void UseM() public async Task TestClassDeclarationAsync(bool lspMutatingWorkspace) { var markup = -@"class {|codeLens:A|} -{ - void M(A a) - { - } -}"; + """ + class {|codeLens:A|} + { + void M(A a) + { + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, lspMutatingWorkspace, CapabilitiesWithVSExtensions); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 1); } @@ -114,9 +124,11 @@ void M(A a) public async Task TestInterfaceDeclarationAsync(bool lspMutatingWorkspace) { var markup = -@"interface {|codeLens:A|} -{ -}"; + """ + interface {|codeLens:A|} + { + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, lspMutatingWorkspace, CapabilitiesWithVSExtensions); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -125,10 +137,12 @@ public async Task TestInterfaceDeclarationAsync(bool lspMutatingWorkspace) public async Task TestEnumDeclarationAsync(bool lspMutatingWorkspace) { var markup = -@"enum {|codeLens:A|} -{ - One -}"; + """ + enum {|codeLens:A|} + { + One + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, lspMutatingWorkspace, CapabilitiesWithVSExtensions); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -138,10 +152,12 @@ public async Task TestEnumDeclarationAsync(bool lspMutatingWorkspace) public async Task TestEnumMemberDeclarationAsync(bool lspMutatingWorkspace) { var markup = -@"enum A -{ - {|codeLens:One|} -}"; + """ + enum A + { + {|codeLens:One|} + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, lspMutatingWorkspace, CapabilitiesWithVSExtensions); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -150,10 +166,12 @@ public async Task TestEnumMemberDeclarationAsync(bool lspMutatingWorkspace) public async Task TestPropertyDeclarationAsync(bool lspMutatingWorkspace) { var markup = -@"class A -{ - public int {|codeLens:I|} { get; set; } -}"; + """ + class A + { + public int {|codeLens:I|} { get; set; } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, lspMutatingWorkspace, CapabilitiesWithVSExtensions); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -163,10 +181,12 @@ public async Task TestPropertyDeclarationAsync(bool lspMutatingWorkspace) public async Task TestEventDeclarationAsync(bool lspMutatingWorkspace) { var markup = -@"class A -{ - public event System.EventHandler {|codeLens:I|} { add { } remove { } } -}"; + """ + class A + { + public event System.EventHandler {|codeLens:I|} { add { } remove { } } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, lspMutatingWorkspace, CapabilitiesWithVSExtensions); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -176,10 +196,12 @@ public async Task TestEventDeclarationAsync(bool lspMutatingWorkspace) public async Task TestEventFieldDeclaration1Async(bool lspMutatingWorkspace) { var markup = -@"class A -{ - public event System.EventHandler {|codeLens:I|}; -}"; + """ + class A + { + public event System.EventHandler {|codeLens:I|}; + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, lspMutatingWorkspace, CapabilitiesWithVSExtensions); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -189,10 +211,12 @@ public async Task TestEventFieldDeclaration1Async(bool lspMutatingWorkspace) public async Task TestEventFieldDeclaration2Async(bool lspMutatingWorkspace) { var markup = -@"class A -{ - public event System.EventHandler {|codeLens:I|}, I2; -}"; + """ + class A + { + public event System.EventHandler {|codeLens:I|}, I2; + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, lspMutatingWorkspace, CapabilitiesWithVSExtensions); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -202,10 +226,12 @@ public async Task TestEventFieldDeclaration2Async(bool lspMutatingWorkspace) public async Task TestEventFieldDeclaration3Async(bool lspMutatingWorkspace) { var markup = -@"class A -{ - public event System.EventHandler I, {|codeLens:I2|}; -}"; + """ + class A + { + public event System.EventHandler I, {|codeLens:I2|}; + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, lspMutatingWorkspace, CapabilitiesWithVSExtensions); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -215,10 +241,12 @@ public async Task TestEventFieldDeclaration3Async(bool lspMutatingWorkspace) public async Task TestFieldDeclaration1Async(bool lspMutatingWorkspace) { var markup = -@"class A -{ - public int {|codeLens:I|}; -}"; + """ + class A + { + public int {|codeLens:I|}; + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, lspMutatingWorkspace, CapabilitiesWithVSExtensions); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -228,10 +256,12 @@ public async Task TestFieldDeclaration1Async(bool lspMutatingWorkspace) public async Task TestFieldDeclaration2Async(bool lspMutatingWorkspace) { var markup = -@"class A -{ - public int {|codeLens:I|}, I2; -}"; + """ + class A + { + public int {|codeLens:I|}, I2; + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, lspMutatingWorkspace, CapabilitiesWithVSExtensions); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -241,10 +271,12 @@ public async Task TestFieldDeclaration2Async(bool lspMutatingWorkspace) public async Task TestFieldDeclaration3Async(bool lspMutatingWorkspace) { var markup = -@"class A -{ - public int I, {|codeLens:I2|}; -}"; + """ + class A + { + public int I, {|codeLens:I2|}; + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, lspMutatingWorkspace, CapabilitiesWithVSExtensions); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -254,10 +286,12 @@ public async Task TestFieldDeclaration3Async(bool lspMutatingWorkspace) public async Task TestConstantDeclaration1Async(bool lspMutatingWorkspace) { var markup = -@"class A -{ - public const int {|codeLens:I|} = 0; -}"; + """ + class A + { + public const int {|codeLens:I|} = 0; + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, lspMutatingWorkspace, CapabilitiesWithVSExtensions); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -267,10 +301,12 @@ public async Task TestConstantDeclaration1Async(bool lspMutatingWorkspace) public async Task TestConstantDeclaration2Async(bool lspMutatingWorkspace) { var markup = -@"class A -{ - public const int {|codeLens:I|} = 0, I2 = 0; -}"; + """ + class A + { + public const int {|codeLens:I|} = 0, I2 = 0; + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, lspMutatingWorkspace, CapabilitiesWithVSExtensions); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -280,10 +316,12 @@ public async Task TestConstantDeclaration2Async(bool lspMutatingWorkspace) public async Task TestConstantDeclaration3Async(bool lspMutatingWorkspace) { var markup = -@"class A -{ - public const int I = 0, {|codeLens:I2|} = 0; -}"; + """ + class A + { + public const int I = 0, {|codeLens:I2|} = 0; + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, lspMutatingWorkspace, CapabilitiesWithVSExtensions); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -292,12 +330,14 @@ public async Task TestConstantDeclaration3Async(bool lspMutatingWorkspace) public async Task TestMethodDeclarationAsync(bool lspMutatingWorkspace) { var markup = -@"class A -{ - public int {|codeLens:M|}() - { - } -}"; + """ + class A + { + public int {|codeLens:M|}() + { + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, lspMutatingWorkspace, CapabilitiesWithVSExtensions); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -306,9 +346,11 @@ public async Task TestMethodDeclarationAsync(bool lspMutatingWorkspace) public async Task TestStructDeclarationAsync(bool lspMutatingWorkspace) { var markup = -@"struct {|codeLens:A|} -{ -}"; + """ + struct {|codeLens:A|} + { + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, lspMutatingWorkspace, CapabilitiesWithVSExtensions); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -327,12 +369,14 @@ public async Task TestDelegateDeclarationAsync(bool lspMutatingWorkspace) public async Task TestConstructorDeclarationAsync(bool lspMutatingWorkspace) { var markup = -@"class A -{ - public {|codeLens:A|}() - { - } -}"; + """ + class A + { + public {|codeLens:A|}() + { + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, lspMutatingWorkspace, CapabilitiesWithVSExtensions); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -342,12 +386,14 @@ public async Task TestConstructorDeclarationAsync(bool lspMutatingWorkspace) public async Task TestDestructorDeclarationAsync(bool lspMutatingWorkspace) { var markup = -@"class A -{ - ~{|codeLens:A|}() - { - } -}"; + """ + class A + { + ~{|codeLens:A|}() + { + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, lspMutatingWorkspace, CapabilitiesWithVSExtensions); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -365,17 +411,19 @@ public async Task TestRecordDeclarationAsync(bool lspMutatingWorkspace) public async Task TestDoesNotCrashWhenSyntaxVersionsMismatch(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void {|codeLens:M|}() - { - } - - void UseM() - { - M(); - } -}"; + """ + class A + { + void {|codeLens:M|}() + { + } + + void UseM() + { + M(); + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); @@ -403,12 +451,14 @@ void UseM() public async Task TestNoCodeLensWhenReferencesDisabledAsync(bool lspMutatingWorkspace) { var markup = -@"class {|codeLens:A|} -{ - void M(A a) - { - } -}"; + """ + class {|codeLens:A|} + { + void M(A a) + { + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, lspMutatingWorkspace, new InitializationOptions { ClientCapabilities = CapabilitiesWithVSExtensions, @@ -422,24 +472,25 @@ void M(A a) public async Task TestHasTestsCommandAsync(bool mutatingLspWorkspace) { var markup = -@"using System; -namespace Xunit -{ - [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] - public class FactAttribute : Attribute { } -} -namespace Test -{ - using Xunit; - class A - { - [Fact] - public void {|codeLens:M|}() - { - } - } -} -"; + """ + using System; + namespace Xunit + { + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] + public class FactAttribute : Attribute { } + } + namespace Test + { + using Xunit; + class A + { + [Fact] + public void {|codeLens:M|}() + { + } + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, new InitializationOptions { ClientCapabilities = CapabilitiesWithVSExtensions, @@ -452,24 +503,25 @@ class A public async Task TestHasAllTestsCommandAsync(bool mutatingLspWorkspace) { var markup = -@"using System; -namespace Xunit -{ - [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] - public class FactAttribute : Attribute { } -} -namespace Test -{ - using Xunit; - class {|codeLens:A|} - { - [Fact] - public void M() - { - } - } -} -"; + """ + using System; + namespace Xunit + { + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] + public class FactAttribute : Attribute { } + } + namespace Test + { + using Xunit; + class {|codeLens:A|} + { + [Fact] + public void M() + { + } + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, new InitializationOptions { ClientCapabilities = CapabilitiesWithVSExtensions, @@ -482,24 +534,25 @@ public void M() public async Task TestDoesNotHaveTestCommandWhenInDevkitAsync(bool mutatingLspWorkspace) { var markup = -@"using System; -namespace Xunit -{ - [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] - public class FactAttribute : Attribute { } -} -namespace Test -{ - using Xunit; - class A - { - [Fact] - public void {|codeLens:M|}() - { - } - } -} -"; + """ + using System; + namespace Xunit + { + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] + public class FactAttribute : Attribute { } + } + namespace Test + { + using Xunit; + class A + { + [Fact] + public void {|codeLens:M|}() + { + } + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, new InitializationOptions { ClientCapabilities = CapabilitiesWithVSExtensions, @@ -512,24 +565,25 @@ class A public async Task TestDoesNotHaveTestCommandWhenDisabledAsync(bool mutatingLspWorkspace) { var markup = -@"using System; -namespace Xunit -{ - [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] - public class FactAttribute : Attribute { } -} -namespace Test -{ - using Xunit; - class A - { - [Fact] - public void {|codeLens:M|}() - { - } - } -} -"; + """ + using System; + namespace Xunit + { + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] + public class FactAttribute : Attribute { } + } + namespace Test + { + using Xunit; + class A + { + [Fact] + public void {|codeLens:M|}() + { + } + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, new InitializationOptions { ClientCapabilities = CapabilitiesWithVSExtensions, diff --git a/src/LanguageServer/ProtocolUnitTests/CodeLens/VisualBasicCodeLensTests.cs b/src/LanguageServer/ProtocolUnitTests/CodeLens/VisualBasicCodeLensTests.cs index 206901c6a26ca..ae4d7c27ca5c0 100644 --- a/src/LanguageServer/ProtocolUnitTests/CodeLens/VisualBasicCodeLensTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/CodeLens/VisualBasicCodeLensTests.cs @@ -19,10 +19,12 @@ public VisualBasicCodeLensTests(ITestOutputHelper? testOutputHelper) : base(test public async Task TestNoReferenceAsync(bool mutatingLspWorkspace) { var markup = -@"Class A - Sub {|codeLens:M|}() - End Sub -End Class"; + """ + Class A + Sub {|codeLens:M|}() + End Sub + End Class + """; await using var testLspServer = await CreateVisualBasicTestLspServerAsync(markup, mutatingLspWorkspace); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -31,11 +33,13 @@ End Sub public async Task TestOneReferenceAsync(bool mutatingLspWorkspace) { var markup = -@"Class A - Sub {|codeLens:M|}() - M() - End Sub -End Class"; + """ + Class A + Sub {|codeLens:M|}() + M() + End Sub + End Class + """; await using var testLspServer = await CreateVisualBasicTestLspServerAsync(markup, mutatingLspWorkspace); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 1); } @@ -44,12 +48,14 @@ End Sub public async Task TestMultipleReferencesAsync(bool mutatingLspWorkspace) { var markup = -@"Class A - Sub {|codeLens:M|}() - M() - M() - End Sub -End Class"; + """ + Class A + Sub {|codeLens:M|}() + M() + M() + End Sub + End Class + """; await using var testLspServer = await CreateVisualBasicTestLspServerAsync(markup, mutatingLspWorkspace); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 2); } @@ -58,8 +64,10 @@ End Sub public async Task TestClassDeclarationAsync(bool mutatingLspWorkspace) { var markup = -@"Class {|codeLens:A|} -End Class"; + """ + Class {|codeLens:A|} + End Class + """; await using var testLspServer = await CreateVisualBasicTestLspServerAsync(markup, mutatingLspWorkspace); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -68,8 +76,10 @@ public async Task TestClassDeclarationAsync(bool mutatingLspWorkspace) public async Task TestInterfaceDeclarationAsync(bool mutatingLspWorkspace) { var markup = -@"Interface {|codeLens:A|} -End Interface"; + """ + Interface {|codeLens:A|} + End Interface + """; await using var testLspServer = await CreateVisualBasicTestLspServerAsync(markup, mutatingLspWorkspace); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -78,9 +88,11 @@ public async Task TestInterfaceDeclarationAsync(bool mutatingLspWorkspace) public async Task TestEnumDeclarationAsync(bool mutatingLspWorkspace) { var markup = -@"Enum {|codeLens:A|} - One -End Enum"; + """ + Enum {|codeLens:A|} + One + End Enum + """; await using var testLspServer = await CreateVisualBasicTestLspServerAsync(markup, mutatingLspWorkspace); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -90,9 +102,11 @@ public async Task TestEnumDeclarationAsync(bool mutatingLspWorkspace) public async Task TestEnumMemberDeclarationAsync(bool mutatingLspWorkspace) { var markup = -@"Enum A - {|codeLens:One|} -End Enum"; + """ + Enum A + {|codeLens:One|} + End Enum + """; await using var testLspServer = await CreateVisualBasicTestLspServerAsync(markup, mutatingLspWorkspace); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -102,9 +116,11 @@ public async Task TestEnumMemberDeclarationAsync(bool mutatingLspWorkspace) public async Task TestFieldDeclaration1Async(bool mutatingLspWorkspace) { var markup = -@"Class A - Public {|codeLens:One|} As Integer -End Class"; + """ + Class A + Public {|codeLens:One|} As Integer + End Class + """; await using var testLspServer = await CreateVisualBasicTestLspServerAsync(markup, mutatingLspWorkspace); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -114,9 +130,11 @@ public async Task TestFieldDeclaration1Async(bool mutatingLspWorkspace) public async Task TestFieldDeclaration2Async(bool mutatingLspWorkspace) { var markup = -@"Class A - Public {|codeLens:One|}, Two As Integer -End Class"; + """ + Class A + Public {|codeLens:One|}, Two As Integer + End Class + """; await using var testLspServer = await CreateVisualBasicTestLspServerAsync(markup, mutatingLspWorkspace); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -126,9 +144,11 @@ public async Task TestFieldDeclaration2Async(bool mutatingLspWorkspace) public async Task TestFieldDeclaration3Async(bool mutatingLspWorkspace) { var markup = -@"Class A - Public One, {|codeLens:Two|} As Integer -End Class"; + """ + Class A + Public One, {|codeLens:Two|} As Integer + End Class + """; await using var testLspServer = await CreateVisualBasicTestLspServerAsync(markup, mutatingLspWorkspace); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -138,9 +158,11 @@ public async Task TestFieldDeclaration3Async(bool mutatingLspWorkspace) public async Task TestFieldDeclaration4Async(bool mutatingLspWorkspace) { var markup = -@"Class A - Public {|codeLens:One|} As Integer, Two As Integer -End Class"; + """ + Class A + Public {|codeLens:One|} As Integer, Two As Integer + End Class + """; await using var testLspServer = await CreateVisualBasicTestLspServerAsync(markup, mutatingLspWorkspace); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -150,9 +172,11 @@ public async Task TestFieldDeclaration4Async(bool mutatingLspWorkspace) public async Task TestFieldDeclaration5Async(bool mutatingLspWorkspace) { var markup = -@"Class A - Public One As Integer, {|codeLens:Two|} As Integer -End Class"; + """ + Class A + Public One As Integer, {|codeLens:Two|} As Integer + End Class + """; await using var testLspServer = await CreateVisualBasicTestLspServerAsync(markup, mutatingLspWorkspace); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -162,9 +186,11 @@ public async Task TestFieldDeclaration5Async(bool mutatingLspWorkspace) public async Task TestEventDeclarationAsync(bool mutatingLspWorkspace) { var markup = -@"Class A - Public Event {|codeLens:One|} As System.EventHandler -End Class"; + """ + Class A + Public Event {|codeLens:One|} As System.EventHandler + End Class + """; await using var testLspServer = await CreateVisualBasicTestLspServerAsync(markup, mutatingLspWorkspace); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -173,9 +199,11 @@ public async Task TestEventDeclarationAsync(bool mutatingLspWorkspace) public async Task TestPropertyDeclarationAsync(bool mutatingLspWorkspace) { var markup = -@"Class A - Property {|codeLens:SomeString|} As String -End Class"; + """ + Class A + Property {|codeLens:SomeString|} As String + End Class + """; await using var testLspServer = await CreateVisualBasicTestLspServerAsync(markup, mutatingLspWorkspace); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -184,10 +212,12 @@ public async Task TestPropertyDeclarationAsync(bool mutatingLspWorkspace) public async Task TestSubDeclarationAsync(bool mutatingLspWorkspace) { var markup = -@"Class A - Sub {|codeLens:M|}() - End Sub -End Class"; + """ + Class A + Sub {|codeLens:M|}() + End Sub + End Class + """; await using var testLspServer = await CreateVisualBasicTestLspServerAsync(markup, mutatingLspWorkspace); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -197,9 +227,11 @@ End Sub public async Task TestDelegateSubDeclarationAsync(bool mutatingLspWorkspace) { var markup = -@"Class A - Delegate Sub {|codeLens:M|}() -End Class"; + """ + Class A + Delegate Sub {|codeLens:M|}() + End Class + """; await using var testLspServer = await CreateVisualBasicTestLspServerAsync(markup, mutatingLspWorkspace); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -208,10 +240,12 @@ public async Task TestDelegateSubDeclarationAsync(bool mutatingLspWorkspace) public async Task TestFunctionDeclarationAsync(bool mutatingLspWorkspace) { var markup = -@"Class A - Function {|codeLens:M|}() - End Function -End Class"; + """ + Class A + Function {|codeLens:M|}() + End Function + End Class + """; await using var testLspServer = await CreateVisualBasicTestLspServerAsync(markup, mutatingLspWorkspace); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -221,9 +255,11 @@ End Function public async Task TestDelegateFunctionDeclarationAsync(bool mutatingLspWorkspace) { var markup = -@"Class A - Delegate Function {|codeLens:M|}() As Integer -End Class"; + """ + Class A + Delegate Function {|codeLens:M|}() As Integer + End Class + """; await using var testLspServer = await CreateVisualBasicTestLspServerAsync(markup, mutatingLspWorkspace); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -232,8 +268,10 @@ public async Task TestDelegateFunctionDeclarationAsync(bool mutatingLspWorkspace public async Task TestStructDeclarationAsync(bool mutatingLspWorkspace) { var markup = -@"Structure {|codeLens:A|} -End Structure"; + """ + Structure {|codeLens:A|} + End Structure + """; await using var testLspServer = await CreateVisualBasicTestLspServerAsync(markup, mutatingLspWorkspace); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -242,10 +280,12 @@ public async Task TestStructDeclarationAsync(bool mutatingLspWorkspace) public async Task TestSubNewDeclarationAsync(bool mutatingLspWorkspace) { var markup = -@"Class A - Sub {|codeLens:New|}() - End Sub -End Class"; + """ + Class A + Sub {|codeLens:New|}() + End Sub + End Class + """; await using var testLspServer = await CreateVisualBasicTestLspServerAsync(markup, mutatingLspWorkspace); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -255,10 +295,12 @@ End Sub public async Task TestDestructorDeclarationAsync(bool mutatingLspWorkspace) { var markup = -@"Class A - Protected Overrides Sub {|codeLens:Finalize|}() - End Sub -End Class"; + """ + Class A + Protected Overrides Sub {|codeLens:Finalize|}() + End Sub + End Class + """; await using var testLspServer = await CreateVisualBasicTestLspServerAsync(markup, mutatingLspWorkspace); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } @@ -267,8 +309,10 @@ End Sub public async Task TestModuleDeclarationAsync(bool mutatingLspWorkspace) { var markup = -@"Module {|codeLens:A|} -End Module"; + """ + Module {|codeLens:A|} + End Module + """; await using var testLspServer = await CreateVisualBasicTestLspServerAsync(markup, mutatingLspWorkspace); await VerifyCodeLensAsync(testLspServer, expectedNumberOfReferences: 0); } diff --git a/src/LanguageServer/ProtocolUnitTests/Commands/ExecuteWorkspaceCommandTests.cs b/src/LanguageServer/ProtocolUnitTests/Commands/ExecuteWorkspaceCommandTests.cs index 7dc1146708bee..6595db73e8c26 100644 --- a/src/LanguageServer/ProtocolUnitTests/Commands/ExecuteWorkspaceCommandTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Commands/ExecuteWorkspaceCommandTests.cs @@ -18,6 +18,7 @@ using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Commands; + public sealed class ExecuteWorkspaceCommandTests : AbstractLanguageServerProtocolTests { protected override TestComposition Composition => base.Composition.AddParts( @@ -34,7 +35,7 @@ public async Task TestExecuteWorkspaceCommand(bool mutatingLspWorkspace) var request = new ExecuteCommandParams() { - Arguments = new object[] { JsonSerializer.Serialize(new TextDocumentIdentifier { DocumentUri = ProtocolConversions.CreateAbsoluteDocumentUri(@"C:\someFile.cs") }) }, + Arguments = [JsonSerializer.Serialize(new TextDocumentIdentifier { DocumentUri = ProtocolConversions.CreateAbsoluteDocumentUri(@"C:\someFile.cs") })], Command = TestWorkspaceCommandHandler.CommandName }; var response = await server.ExecuteRequestAsync(Methods.WorkspaceExecuteCommandName, request, CancellationToken.None); diff --git a/src/LanguageServer/ProtocolUnitTests/Completion/CompletionFeaturesTests.cs b/src/LanguageServer/ProtocolUnitTests/Completion/CompletionFeaturesTests.cs index 87a59e7148e13..af1aaba629419 100644 --- a/src/LanguageServer/ProtocolUnitTests/Completion/CompletionFeaturesTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Completion/CompletionFeaturesTests.cs @@ -64,17 +64,19 @@ public CompletionFeaturesTests(ITestOutputHelper testOutputHelper) : base(testOu public async Task TestDoesNotThrowInComplexEditWhenDisplayTextShorterThanDefaultSpanAsync(bool mutatingLspWorkspace) { var markup = -@" -using System; -using System.Text; + """ -public class A -{ - public int M() - { - return{|caret:|} - } -}"; + using System; + using System.Text; + + public class A + { + public int M() + { + return{|caret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, DefaultClientCapabilities); var caret = testLspServer.GetLocations("caret").Single(); var completionParams = new LSP.CompletionParams() @@ -100,14 +102,16 @@ public async Task TestImportCompletionForType(bool mutatingLspWorkspace, bool is { var markup = isInUsingStatement ? @"global using static Task{|caret:|}" - : @" -class A -{ - void M() - { - Task{|caret:|} - } -}"; + : """ + + class A + { + void M() + { + Task{|caret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, DefaultClientCapabilities); var completionParams = CreateCompletionParams( testLspServer.GetLocations("caret").Single(), @@ -174,25 +178,27 @@ void M() public async Task TestImportCompletionForExtensionMethod(bool mutatingLspWorkspace) { var markup = -@" -namespace NS2 -{ - public static class ExtensionClass - { - public static bool ExtensionMethod(this object o) => true; - } -} + """ -namespace NS1 -{ - class Program - { - void M(object o) - { - o.{|caret:|} - } - } -}"; + namespace NS2 + { + public static class ExtensionClass + { + public static bool ExtensionMethod(this object o) => true; + } + } + + namespace NS1 + { + class Program + { + void M(object o) + { + o.{|caret:|} + } + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, DefaultClientCapabilities); var completionParams = CreateCompletionParams( testLspServer.GetLocations("caret").Single(), @@ -255,9 +261,11 @@ void M(object o) public async Task TestResolveComplexEdit(bool mutatingLspWorkspace) { var markup = -@" -/// myList) - { - var foo = myList.Where(i{|caret:|}) - } -}"; + """ + + using System.Collections.Generic; + using System.Linq; + public class C + { + public Foo(List myList) + { + var foo = myList.Where(i{|caret:|}) + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, DefaultClientCapabilities); var caret = testLspServer.GetLocations("caret").Single(); var completionParams = new LSP.CompletionParams() @@ -813,15 +831,17 @@ public async Task TestSoftSelectionWhenFilterTextIsEmptyForPreselectItemAsync(bo public async Task TestSoftSelectionForDiscardAsync(bool mutatingLspWorkspace) { var markup = -@" -public class A -{ - public void M() - { - var _someDiscard = 1; - _{|caret:|} - } -}"; + """ + + public class A + { + public void M() + { + var _someDiscard = 1; + _{|caret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, DefaultClientCapabilities); var caretLocation = testLspServer.GetLocations("caret").Single(); @@ -1049,15 +1069,17 @@ public class MyClass : BaseClass public async Task FilteringShouldBeDoneByTextBeforeCursorLocation(bool mutatingLspWorkspace) { var markup = -@" -public class Z -{ - public int M() - { - int ia, ib, ic, ifa, ifb, ifc; - i{|caret:|}Exception - } -}"; + """ + + public class Z + { + public int M() + { + int ia, ib, ic, ifa, ifb, ifc; + i{|caret:|}Exception + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, DefaultClientCapabilities); var caret = testLspServer.GetLocations("caret").Single(); await testLspServer.OpenDocumentAsync(caret.DocumentUri); diff --git a/src/LanguageServer/ProtocolUnitTests/Completion/CompletionResolveTests.cs b/src/LanguageServer/ProtocolUnitTests/Completion/CompletionResolveTests.cs index 358352ca33d3e..c60c51ae06e2c 100644 --- a/src/LanguageServer/ProtocolUnitTests/Completion/CompletionResolveTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Completion/CompletionResolveTests.cs @@ -9,7 +9,6 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; -using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServer.Handler.Completion; using Microsoft.CodeAnalysis.LanguageService; @@ -35,13 +34,15 @@ public CompletionResolveTests(ITestOutputHelper testOutputHelper) : base(testOut public async Task TestResolveCompletionItemFromListAsync(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void M() - { - {|caret:|} - } -}"; + """ + class A + { + void M() + { + {|caret:|} + } + } + """; var clientCapabilities = new LSP.VSInternalClientCapabilities { @@ -75,13 +76,15 @@ void M() public async Task TestResolveCompletionItemAsync(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void M() - { - {|caret:|} - } -}"; + """ + class A + { + void M() + { + {|caret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, new LSP.VSInternalClientCapabilities { SupportsVisualStudioExtensions = true }); var clientCompletionItem = await GetCompletionItemToResolveAsync(testLspServer, label: "A").ConfigureAwait(false); @@ -97,15 +100,17 @@ void M() public async Task TestResolveOverridesCompletionItemAsync(bool mutatingLspWorkspace) { var markup = -@"abstract class A -{ - public abstract void M(); -} + """ + abstract class A + { + public abstract void M(); + } -class B : A -{ - override {|caret:|} -}"; + class B : A + { + override {|caret:|} + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, new LSP.VSInternalClientCapabilities { SupportsVisualStudioExtensions = true }); var clientCompletionItem = await GetCompletionItemToResolveAsync(testLspServer, label: "M()").ConfigureAwait(false); var results = (LSP.VSInternalCompletionItem)await RunResolveCompletionItemAsync( @@ -113,25 +118,29 @@ class B : A Assert.NotNull(results.TextEdit); Assert.Null(results.InsertText); - Assert.Equal(@"public override void M() - { - throw new System.NotImplementedException(); - }", results.TextEdit.Value.First.NewText); + Assert.Equal(""" + public override void M() + { + throw new System.NotImplementedException(); + } + """, results.TextEdit.Value.First.NewText); } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/51125")] public async Task TestResolveOverridesCompletionItem_SnippetsEnabledAsync(bool mutatingLspWorkspace) { var markup = -@"abstract class A -{ - public abstract void M(); -} + """ + abstract class A + { + public abstract void M(); + } -class B : A -{ - override {|caret:|} -}"; + class B : A + { + override {|caret:|} + } + """; // Explicitly enable snippets. This allows us to set the cursor with $0. Currently only applies to C# in Razor docs. var clientCapabilities = new LSP.VSInternalClientCapabilities @@ -158,25 +167,29 @@ class B : A Assert.NotNull(results.TextEdit); Assert.Null(results.InsertText); - Assert.Equal(@"public override void M() - { - throw new System.NotImplementedException();$0 - }", results.TextEdit.Value.First.NewText); + Assert.Equal(""" + public override void M() + { + throw new System.NotImplementedException();$0 + } + """, results.TextEdit.Value.First.NewText); } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/51125")] public async Task TestResolveOverridesCompletionItem_SnippetsEnabled_CaretOutOfSnippetScopeAsync(bool mutatingLspWorkspace) { var markup = -@"abstract class A -{ - public abstract void M(); -} + """ + abstract class A + { + public abstract void M(); + } -class B : A -{ - override {|caret:|} -}"; + class B : A + { + override {|caret:|} + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); @@ -185,48 +198,52 @@ class B : A var (textEdit, _, _) = await CompletionResultFactory.GenerateComplexTextEditAsync( document, new TestCaretOutOfScopeCompletionService(testLspServer.TestWorkspace.Services.SolutionServices), selectedItem, snippetsSupported: true, insertNewPositionPlaceholder: true, CancellationToken.None).ConfigureAwait(false); - Assert.Equal(@"public override void M() - { - throw new System.NotImplementedException(); - }", textEdit.NewText); + Assert.Equal(""" + public override void M() + { + throw new System.NotImplementedException(); + } + """, textEdit.NewText); } [Theory, CombinatorialData] public async Task TestResolveCompletionItemWithMarkupContentAsync(bool mutatingLspWorkspace) { var markup = -@" -class A -{ - /// - /// A cref - ///
- /// strong text - ///
- /// italic text - ///
- /// underline text - /// - /// - /// - /// Item 1. - /// - /// - /// Item 2. - /// - /// - /// link text - /// - ///
- void AMethod(int i) - { - } + """ - void M() - { - AMet{|caret:|} - } -}"; + class A + { + /// + /// A cref + ///
+ /// strong text + ///
+ /// italic text + ///
+ /// underline text + /// + /// + /// + /// Item 1. + /// + /// + /// Item 2. + /// + /// + /// link text + /// + ///
+ void AMethod(int i) + { + } + + void M() + { + AMet{|caret:|} + } + } + """; var clientCapabilities = new ClientCapabilities { TextDocument = new TextDocumentClientCapabilities @@ -244,97 +261,99 @@ void M() var clientCompletionItem = await GetCompletionItemToResolveAsync( testLspServer, label: "AMethod").ConfigureAwait(false); - - var expected = @"```csharp -void A.AMethod(int i) -``` - -A cref A\.AMethod\(int\) -**strong text** -_italic text_ -underline text - -• Item 1\. -• Item 2\. - -[link text](https://google.com)"; - var results = await RunResolveCompletionItemAsync( testLspServer, clientCompletionItem).ConfigureAwait(false); - Assert.Equal(expected, results.Documentation.Value.Second.Value); + Assert.Equal(""" + ```csharp + void A.AMethod(int i) + ``` + + A cref A\.AMethod\(int\) + **strong text** + _italic text_ + underline text + + • Item 1\. + • Item 2\. + + [link text](https://google.com) + """, results.Documentation.Value.Second.Value); } [Theory, CombinatorialData] public async Task TestResolveCompletionItemWithPlainTextAsync(bool mutatingLspWorkspace) { var markup = -@" -class A -{ - /// - /// A cref - ///
- /// strong text - ///
- /// italic text - ///
- /// underline text - /// - /// - /// - /// Item 1. - /// - /// - /// Item 2. - /// - /// - /// link text - /// - ///
- void AMethod(int i) - { - } + """ - void M() - { - AMet{|caret:|} - } -}"; + class A + { + /// + /// A cref + ///
+ /// strong text + ///
+ /// italic text + ///
+ /// underline text + /// + /// + /// + /// Item 1. + /// + /// + /// Item 2. + /// + /// + /// link text + /// + ///
+ void AMethod(int i) + { + } + + void M() + { + AMet{|caret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var clientCompletionItem = await GetCompletionItemToResolveAsync( testLspServer, label: "AMethod").ConfigureAwait(false); - - var expected = @"void A.AMethod(int i) -A cref A.AMethod(int) -strong text -italic text -underline text - -• Item 1. -• Item 2. - -link text"; - var results = await RunResolveCompletionItemAsync( testLspServer, clientCompletionItem).ConfigureAwait(false); - Assert.Equal(expected, results.Documentation.Value.Second.Value); + Assert.Equal(""" + void A.AMethod(int i) + A cref A.AMethod(int) + strong text + italic text + underline text + + • Item 1. + • Item 2. + + link text + """, results.Documentation.Value.Second.Value); } [Theory, CombinatorialData] public async Task TestResolveCompletionItemWithPrefixSuffixAsync(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void M() - { - var a = 10; - a.{|caret:|} - } -}"; + """ + class A + { + void M() + { + var a = 10; + a.{|caret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, new LSP.VSInternalClientCapabilities { SupportsVisualStudioExtensions = true }); var clientCompletionItem = await GetCompletionItemToResolveAsync(testLspServer, label: "(byte)").ConfigureAwait(false); @@ -500,10 +519,12 @@ public override Task GetChangeAsync( char? commitCharacter = null, CancellationToken cancellationToken = default) { - var textChange = new TextChange(span: new TextSpan(start: 77, length: 9), newText: @"public override void M() - { - throw new System.NotImplementedException(); - }"); + var textChange = new TextChange(span: new TextSpan(start: 77, length: 9), newText: """ + public override void M() + { + throw new System.NotImplementedException(); + } + """); return Task.FromResult(CompletionChange.Create(textChange, newPosition: 0)); } diff --git a/src/LanguageServer/ProtocolUnitTests/Completion/CompletionTests.cs b/src/LanguageServer/ProtocolUnitTests/Completion/CompletionTests.cs index 6a1b74784b9d8..7c574eee947ce 100644 --- a/src/LanguageServer/ProtocolUnitTests/Completion/CompletionTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Completion/CompletionTests.cs @@ -74,13 +74,15 @@ public async Task TestGetCompletionsAsync_PromotesCommitCharactersToListAsync(bo } }; var markup = -@"class A -{ - void M() - { - {|caret:|} - } -}"; + """ + class A + { + void M() + { + {|caret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, clientCapabilities); var completionParams = CreateCompletionParams( testLspServer.GetLocations("caret").Single(), @@ -129,9 +131,11 @@ public async Task TestGetCompletions_PromotesNothingWhenNoCommitCharactersAsync( } }; var markup = -@"namespace M -{{|caret:|} -}"; + """ + namespace M + {{|caret:|} + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, clientCapabilities); var completionParams = CreateCompletionParams( testLspServer.GetLocations("caret").Single(), @@ -158,13 +162,15 @@ public async Task TestGetCompletions_PromotesNothingWhenNoCommitCharactersAsync( public async Task TestGetCompletionsAsync(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void M() - { - {|caret:|} - } -}"; + """ + class A + { + void M() + { + {|caret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var completionParams = CreateCompletionParams( testLspServer.GetLocations("caret").Single(), @@ -186,19 +192,20 @@ void M() public async Task TestGetExtensionMethodCoreLsp(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void M(A a) - { - a.{|caret:|} - } -} + """ + class A + { + void M(A a) + { + a.{|caret:|} + } + } -static class Extensions -{ - public static void Goo(this A a) { } -} -"; + static class Extensions + { + public static void Goo(this A a) { } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var completionParams = CreateCompletionParams( testLspServer.GetLocations("caret").Single(), @@ -220,19 +227,20 @@ public static void Goo(this A a) { } public async Task TestGetExtensionMethodCoreVSLsp(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void M(A a) - { - a.{|caret:|} - } -} + """ + class A + { + void M(A a) + { + a.{|caret:|} + } + } -static class Extensions -{ - public static void Goo(this A a) { } -} -"; + static class Extensions + { + public static void Goo(this A a) { } + } + """; // If the client supports more completion kinds, then we can give a more precise answer. var capabilities = CreateCoreCompletionCapabilities(); @@ -259,13 +267,15 @@ public static void Goo(this A a) { } public async Task TestGetCompletionsTypingAsync(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void M() - { - A{|caret:|} - } -}"; + """ + class A + { + void M() + { + A{|caret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var completionParams = CreateCompletionParams( testLspServer.GetLocations("caret").Single(), @@ -286,13 +296,15 @@ void M() public async Task TestGetCompletionsDoesNotIncludeUnimportedTypesAsync(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void M() - { - {|caret:|} - } -}"; + """ + class A + { + void M() + { + {|caret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var solution = testLspServer.TestWorkspace.CurrentSolution; @@ -314,10 +326,12 @@ void M() public async Task TestGetCompletionsUsesSnippetOptionAsync(bool mutatingLspWorkspace) { var markup = -@"class A -{ - {|caret:|} -}"; + """ + class A + { + {|caret:|} + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); @@ -337,13 +351,15 @@ public async Task TestGetCompletionsUsesSnippetOptionAsync(bool mutatingLspWorks public async Task TestGetCompletionsWithPreselectAsync(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void M() - { - A classA = new {|caret:|} - } -}"; + """ + class A + { + void M() + { + A classA = new {|caret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var completionParams = CreateCompletionParams( testLspServer.GetLocations("caret").Single(), @@ -364,20 +380,21 @@ void M() public async Task TestGetCompletionsIsInSuggestionMode(bool mutatingLspWorkspace) { var markup = -@" -using System.Collections.Generic; -using System.Linq; -namespace M -{ - class Item - { - void M() - { - var items = new List(); - items.Count(i{|caret:|} - } - } -}"; + """ + using System.Collections.Generic; + using System.Linq; + namespace M + { + class Item + { + void M() + { + var items = new List(); + items.Count(i{|caret:|} + } + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var completionParams = CreateCompletionParams( testLspServer.GetLocations("caret").Single(), @@ -394,19 +411,23 @@ void M() public async Task TestGetDateAndTimeCompletionsAsync(bool mutatingLspWorkspace) { var markup = -@"using System; -class A -{ - void M() - { - DateTime.Now.ToString(""{|caret:|}); - } -}"; + """ + using System; + class A + { + void M() + { + DateTime.Now.ToString("{|caret:|}); + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var completionParams = CreateCompletionParams( testLspServer.GetLocations("caret").Single(), invokeKind: LSP.VSInternalCompletionInvokeKind.Typing, - triggerCharacter: "\"", + triggerCharacter: """ + " + """, triggerKind: LSP.CompletionTriggerKind.TriggerCharacter); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); @@ -423,19 +444,23 @@ void M() public async Task TestGetDateAndTimeCompletionOnGuid(bool mutatingLspWorkspace) { var markup = -@"using System; -class A -{ - void M() - { - Guid.NewGuid().ToString(""{|caret:|}); - } -}"; + """ + using System; + class A + { + void M() + { + Guid.NewGuid().ToString("{|caret:|}); + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var completionParams = CreateCompletionParams( testLspServer.GetLocations("caret").Single(), invokeKind: LSP.VSInternalCompletionInvokeKind.Typing, - triggerCharacter: "\"", + triggerCharacter: """ + " + """, triggerKind: LSP.CompletionTriggerKind.TriggerCharacter); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); @@ -448,14 +473,16 @@ void M() public async Task TestGetRegexCompletionsAsync(bool mutatingLspWorkspace) { var markup = -@"using System.Text.RegularExpressions; -class A -{ - void M() - { - new Regex(""{|caret:|}""); - } -}"; + """ + using System.Text.RegularExpressions; + class A + { + void M() + { + new Regex("{|caret:|}"); + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var completionParams = CreateCompletionParams( testLspServer.GetLocations("caret").Single(), @@ -485,14 +512,16 @@ void M() public async Task TestGetRegexLiteralCompletionsAsync(bool mutatingLspWorkspace) { var markup = -@"using System.Text.RegularExpressions; -class A -{ - void M() - { - new Regex(@""\{|caret:|}""); - } -}"; + """ + using System.Text.RegularExpressions; + class A + { + void M() + { + new Regex(@"\{|caret:|}"); + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var completionParams = CreateCompletionParams( testLspServer.GetLocations("caret").Single(), @@ -522,14 +551,16 @@ void M() public async Task TestGetRegexCompletionsReplaceTextAsync(bool mutatingLspWorkspace) { var markup = -@"using System.Text.RegularExpressions; -class A -{ - void M() - { - Regex r = new(""\\{|caret:|}""); - } -}"; + """ + using System.Text.RegularExpressions; + class A + { + void M() + { + Regex r = new("\\{|caret:|}"); + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var completionParams = CreateCompletionParams( testLspServer.GetLocations("caret").Single(), @@ -580,14 +611,16 @@ public async Task TestGetRegexCompletionsWithoutItemDefaultSupportAsync(bool mut }; var markup = -@"using System.Text.RegularExpressions; -class A -{ - void M() - { - new Regex(""{|caret:|}""); - } -}"; + """ + using System.Text.RegularExpressions; + class A + { + void M() + { + new Regex("{|caret:|}"); + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, clientCapabilities); var completionParams = CreateCompletionParams( testLspServer.GetLocations("caret").Single(), @@ -613,13 +646,15 @@ void M() public async Task TestCompletionListCacheAsync(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void M() - { - {|caret:|} - } -}"; + """ + class A + { + void M() + { + {|caret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var cache = GetCompletionListCache(testLspServer); Assert.NotNull(cache); @@ -676,13 +711,15 @@ void M() public async Task TestGetCompletionsWithDeletionInvokeKindAsync(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void M() - { - {|caret:|} - } -}"; + """ + class A + { + void M() + { + {|caret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var completionParams = CreateCompletionParams( testLspServer.GetLocations("caret").Single(), @@ -705,15 +742,17 @@ void M() public async Task TestDoNotProvideOverrideTextEditsOrInsertTextAsync(bool mutatingLspWorkspace) { var markup = -@"abstract class A -{ - public abstract void M(); -} + """ + abstract class A + { + public abstract void M(); + } -class B : A -{ - override {|caret:|} -}"; + class B : A + { + override {|caret:|} + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var completionParams = CreateCompletionParams( testLspServer.GetLocations("caret").Single(), @@ -733,15 +772,17 @@ class B : A public async Task TestDoNotProvidePartialMethodTextEditsOrInsertTextAsync(bool mutatingLspWorkspace) { var markup = -@"partial class C -{ - partial void Method(); -} + """ + partial class C + { + partial void Method(); + } -partial class C -{ - partial {|caret:|} -}"; + partial class C + { + partial {|caret:|} + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var completionParams = CreateCompletionParams( testLspServer.GetLocations("caret").Single(), @@ -760,14 +801,16 @@ partial class C public async Task TestSoftSelectedItemsHaveNoCommitCharactersWithoutVSCapabilityAsync(bool mutatingLspWorkspace) { var markup = -@"using System.Text.RegularExpressions; -class A -{ - void M() - { - new Regex(""[{|caret:|}"") - } -}"; + """ + using System.Text.RegularExpressions; + class A + { + void M() + { + new Regex("[{|caret:|}") + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var completionParams = CreateCompletionParams( testLspServer.GetLocations("caret").Single(), @@ -787,39 +830,41 @@ void M() public async Task TestLargeCompletionListIsMarkedIncompleteAsync(bool mutatingLspWorkspace) { var markup = -@"using System; -using System.Buffers; -using System.Buffers.Binary; -using System.Buffers.Text; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.ComponentModel.Design; -using System.Configuration; -using System.Data; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Drawing; -using System.Dynamic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Media; -using System.Net; -using System.Net.Http; -using System.Net.Http.Json; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -class A -{ - void M() - { - T{|caret:|} - } -}"; + """ + using System; + using System.Buffers; + using System.Buffers.Binary; + using System.Buffers.Text; + using System.Collections; + using System.Collections.Generic; + using System.Collections.Immutable; + using System.Collections.ObjectModel; + using System.ComponentModel; + using System.ComponentModel.Design; + using System.Configuration; + using System.Data; + using System.Diagnostics; + using System.Diagnostics.CodeAnalysis; + using System.Drawing; + using System.Dynamic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Media; + using System.Net; + using System.Net.Http; + using System.Net.Http.Json; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + class A + { + void M() + { + T{|caret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var completionParams = CreateCompletionParams( testLspServer.GetLocations("caret").Single(), @@ -836,42 +881,44 @@ void M() public async Task TestIncompleteCompletionListContainsPreselectedItemAsync(bool mutatingLspWorkspace) { var markup = -@"using System; -using System.Buffers; -using System.Buffers.Binary; -using System.Buffers.Text; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.ComponentModel.Design; -using System.Configuration; -using System.Data; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Drawing; -using System.Dynamic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Media; -using System.Net; -using System.Net.Http; -using System.Net.Http.Json; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -class A -{ - class W - { - } - void M() - { - W someW = new {|caret:|} - } -}"; + """ + using System; + using System.Buffers; + using System.Buffers.Binary; + using System.Buffers.Text; + using System.Collections; + using System.Collections.Generic; + using System.Collections.Immutable; + using System.Collections.ObjectModel; + using System.ComponentModel; + using System.ComponentModel.Design; + using System.Configuration; + using System.Data; + using System.Diagnostics; + using System.Diagnostics.CodeAnalysis; + using System.Drawing; + using System.Dynamic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Media; + using System.Net; + using System.Net.Http; + using System.Net.Http.Json; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + class A + { + class W + { + } + void M() + { + W someW = new {|caret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var caretLocation = testLspServer.GetLocations("caret").Single(); @@ -892,39 +939,41 @@ void M() public async Task TestRequestForIncompleteListIsFilteredDownAsync(bool mutatingLspWorkspace) { var markup = -@"using System; -using System.Buffers; -using System.Buffers.Binary; -using System.Buffers.Text; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.ComponentModel.Design; -using System.Configuration; -using System.Data; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Drawing; -using System.Dynamic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Media; -using System.Net; -using System.Net.Http; -using System.Net.Http.Json; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -class A -{ - void M() - { - T{|caret:|} - } -}"; + """ + using System; + using System.Buffers; + using System.Buffers.Binary; + using System.Buffers.Text; + using System.Collections; + using System.Collections.Generic; + using System.Collections.Immutable; + using System.Collections.ObjectModel; + using System.ComponentModel; + using System.ComponentModel.Design; + using System.Configuration; + using System.Data; + using System.Diagnostics; + using System.Diagnostics.CodeAnalysis; + using System.Drawing; + using System.Dynamic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Media; + using System.Net; + using System.Net.Http; + using System.Net.Http.Json; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + class A + { + void M() + { + T{|caret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var caretLocation = testLspServer.GetLocations("caret").Single(); await testLspServer.OpenDocumentAsync(caretLocation.DocumentUri); @@ -958,39 +1007,41 @@ void M() public async Task TestIncompleteCompletionListFiltersWithPatternMatchingAsync(bool mutatingLspWorkspace) { var markup = -@"using System; -using System.Buffers; -using System.Buffers.Binary; -using System.Buffers.Text; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.ComponentModel.Design; -using System.Configuration; -using System.Data; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Drawing; -using System.Dynamic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Media; -using System.Net; -using System.Net.Http; -using System.Net.Http.Json; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -class A -{ - void M() - { - T{|caret:|} - } -}"; + """ + using System; + using System.Buffers; + using System.Buffers.Binary; + using System.Buffers.Text; + using System.Collections; + using System.Collections.Generic; + using System.Collections.Immutable; + using System.Collections.ObjectModel; + using System.ComponentModel; + using System.ComponentModel.Design; + using System.Configuration; + using System.Data; + using System.Diagnostics; + using System.Diagnostics.CodeAnalysis; + using System.Drawing; + using System.Dynamic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Media; + using System.Net; + using System.Net.Http; + using System.Net.Http.Json; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + class A + { + void M() + { + T{|caret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var caretLocation = testLspServer.GetLocations("caret").Single(); await testLspServer.OpenDocumentAsync(caretLocation.DocumentUri); @@ -1024,39 +1075,41 @@ void M() public async Task TestIncompleteCompletionListWithDeletionAsync(bool mutatingLspWorkspace) { var markup = -@"using System; -using System.Buffers; -using System.Buffers.Binary; -using System.Buffers.Text; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.ComponentModel.Design; -using System.Configuration; -using System.Data; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Drawing; -using System.Dynamic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Media; -using System.Net; -using System.Net.Http; -using System.Net.Http.Json; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -class A -{ - void M() - { - T{|caret:|} - } -}"; + """ + using System; + using System.Buffers; + using System.Buffers.Binary; + using System.Buffers.Text; + using System.Collections; + using System.Collections.Generic; + using System.Collections.Immutable; + using System.Collections.ObjectModel; + using System.ComponentModel; + using System.ComponentModel.Design; + using System.Configuration; + using System.Data; + using System.Diagnostics; + using System.Diagnostics.CodeAnalysis; + using System.Drawing; + using System.Dynamic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Media; + using System.Net; + using System.Net.Http; + using System.Net.Http.Json; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + class A + { + void M() + { + T{|caret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var caretLocation = testLspServer.GetLocations("caret").Single(); await testLspServer.OpenDocumentAsync(caretLocation.DocumentUri); @@ -1114,44 +1167,46 @@ void M() public async Task TestNewCompletionRequestDoesNotUseIncompleteListAsync(bool mutatingLspWorkspace) { var markup = -@"using System; -using System.Buffers; -using System.Buffers.Binary; -using System.Buffers.Text; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.ComponentModel.Design; -using System.Configuration; -using System.Data; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Drawing; -using System.Dynamic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Media; -using System.Net; -using System.Net.Http; -using System.Net.Http.Json; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -class A -{ - void M() - { - T{|firstCaret:|} - } + """ + using System; + using System.Buffers; + using System.Buffers.Binary; + using System.Buffers.Text; + using System.Collections; + using System.Collections.Generic; + using System.Collections.Immutable; + using System.Collections.ObjectModel; + using System.ComponentModel; + using System.ComponentModel.Design; + using System.Configuration; + using System.Data; + using System.Diagnostics; + using System.Diagnostics.CodeAnalysis; + using System.Drawing; + using System.Dynamic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Media; + using System.Net; + using System.Net.Http; + using System.Net.Http.Json; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + class A + { + void M() + { + T{|firstCaret:|} + } - void M2() - { - Console.WH{|secondCaret:|} - } -}"; + void M2() + { + Console.WH{|secondCaret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var firstCaret = testLspServer.GetLocations("firstCaret").Single(); await testLspServer.OpenDocumentAsync(firstCaret.DocumentUri); @@ -1183,39 +1238,41 @@ void M2() public async Task TestRequestForIncompleteListWhenMissingCachedListAsync(bool mutatingLspWorkspace) { var markup = -@"using System; -using System.Buffers; -using System.Buffers.Binary; -using System.Buffers.Text; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.ComponentModel.Design; -using System.Configuration; -using System.Data; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Drawing; -using System.Dynamic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Media; -using System.Net; -using System.Net.Http; -using System.Net.Http.Json; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -class A -{ - void M() - { - Ta{|caret:|} - } -}"; + """ + using System; + using System.Buffers; + using System.Buffers.Binary; + using System.Buffers.Text; + using System.Collections; + using System.Collections.Generic; + using System.Collections.Immutable; + using System.Collections.ObjectModel; + using System.ComponentModel; + using System.ComponentModel.Design; + using System.Configuration; + using System.Data; + using System.Diagnostics; + using System.Diagnostics.CodeAnalysis; + using System.Drawing; + using System.Dynamic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Media; + using System.Net; + using System.Net.Http; + using System.Net.Http.Json; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + class A + { + void M() + { + Ta{|caret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var caretLocation = testLspServer.GetLocations("caret").Single(); @@ -1235,46 +1292,48 @@ void M() public async Task TestRequestForIncompleteListUsesCorrectCachedListAsync(bool mutatingLspWorkspace) { var markup = -@"using System; -using System.Buffers; -using System.Buffers.Binary; -using System.Buffers.Text; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.ComponentModel.Design; -using System.Configuration; -using System.Data; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Drawing; -using System.Dynamic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Media; -using System.Net; -using System.Net.Http; -using System.Net.Http.Json; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -class A -{ - void M1() - { - int Taaa = 1; - T{|firstCaret:|} - } + """ + using System; + using System.Buffers; + using System.Buffers.Binary; + using System.Buffers.Text; + using System.Collections; + using System.Collections.Generic; + using System.Collections.Immutable; + using System.Collections.ObjectModel; + using System.ComponentModel; + using System.ComponentModel.Design; + using System.Configuration; + using System.Data; + using System.Diagnostics; + using System.Diagnostics.CodeAnalysis; + using System.Drawing; + using System.Dynamic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Media; + using System.Net; + using System.Net.Http; + using System.Net.Http.Json; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + class A + { + void M1() + { + int Taaa = 1; + T{|firstCaret:|} + } - void M2() - { - int Saaa = 1; - {|secondCaret:|} - } -}"; + void M2() + { + int Saaa = 1; + {|secondCaret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var firstCaretLocation = testLspServer.GetLocations("firstCaret").Single(); await testLspServer.OpenDocumentAsync(firstCaretLocation.DocumentUri); @@ -1330,13 +1389,15 @@ void M2() public async Task TestCompletionRequestRespectsListSizeOptionAsync(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void M() - { - {|caret:|} - } -}"; + """ + class A + { + void M() + { + {|caret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var completionParams = CreateCompletionParams( testLspServer.GetLocations("caret").Single(), @@ -1358,39 +1419,41 @@ void M() public async Task TestRequestForIncompleteListFiltersDownToEmptyAsync(bool mutatingLspWorkspace) { var markup = -@"using System; -using System.Buffers; -using System.Buffers.Binary; -using System.Buffers.Text; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.ComponentModel.Design; -using System.Configuration; -using System.Data; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Drawing; -using System.Dynamic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Media; -using System.Net; -using System.Net.Http; -using System.Net.Http.Json; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -class A -{ - void M() - { - T{|caret:|} - } -}"; + """ + using System; + using System.Buffers; + using System.Buffers.Binary; + using System.Buffers.Text; + using System.Collections; + using System.Collections.Generic; + using System.Collections.Immutable; + using System.Collections.ObjectModel; + using System.ComponentModel; + using System.ComponentModel.Design; + using System.Configuration; + using System.Data; + using System.Diagnostics; + using System.Diagnostics.CodeAnalysis; + using System.Drawing; + using System.Dynamic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Media; + using System.Net; + using System.Net.Http; + using System.Net.Http.Json; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + class A + { + void M() + { + T{|caret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var caretLocation = testLspServer.GetLocations("caret").Single(); await testLspServer.OpenDocumentAsync(caretLocation.DocumentUri); @@ -1423,14 +1486,16 @@ void M() public async Task TestHasSuggestionModeItemAsync(bool mutatingLspWorkspace) { var markup = -@"using System.Threading.Tasks; -class A -{ - void M() - { - Task.Run(abcdefg{|caret:|} - } -}"; + """ + using System.Threading.Tasks; + class A + { + void M() + { + Task.Run(abcdefg{|caret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var completionParams = CreateCompletionParams( testLspServer.GetLocations("caret").Single(), @@ -1451,9 +1516,11 @@ void M() public async Task EditRangeShouldNotEndAtCursorPosition(bool mutatingLspWorkspace) { var markup = -@"public class C1 {} + """ + public class C1 {} -pub{|caret:|}class"; + pub{|caret:|}class + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, s_vsCompletionCapabilities); var caret = testLspServer.GetLocations("caret").Single(); @@ -1475,13 +1542,15 @@ public async Task EditRangeShouldNotEndAtCursorPosition(bool mutatingLspWorkspac public async Task TestHasInsertTextModeIfSupportedAsync(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void M() - { - {|caret:|} - } -}"; + """ + class A + { + void M() + { + {|caret:|} + } + } + """; var capabilities = CreateCoreCompletionCapabilities(); capabilities.TextDocument.Completion.CompletionItem = new LSP.CompletionItemSetting { @@ -1503,13 +1572,15 @@ void M() public async Task TestDoesNotHaveInsertTextModeIfNotSupportedAsync(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void M() - { - {|caret:|} - } -}"; + """ + class A + { + void M() + { + {|caret:|} + } + } + """; var capabilities = CreateCoreCompletionCapabilities(); capabilities.TextDocument.Completion.CompletionItem = new LSP.CompletionItemSetting { diff --git a/src/LanguageServer/ProtocolUnitTests/Configuration/DidChangeConfigurationNotificationHandlerTest.cs b/src/LanguageServer/ProtocolUnitTests/Configuration/DidChangeConfigurationNotificationHandlerTest.cs index b69153c799cf7..1db1afc269c3b 100644 --- a/src/LanguageServer/ProtocolUnitTests/Configuration/DidChangeConfigurationNotificationHandlerTest.cs +++ b/src/LanguageServer/ProtocolUnitTests/Configuration/DidChangeConfigurationNotificationHandlerTest.cs @@ -33,9 +33,6 @@ public DidChangeConfigurationNotificationHandlerTest(ITestOutputHelper? testOutp [Theory, CombinatorialData] public async Task VerifyNoRequestToClientWithoutCapability(bool mutatingLspWorkspace) { - var markup = @" -public class B { }"; - var clientCapabilities = new ClientCapabilities() { Workspace = new WorkspaceClientCapabilities() @@ -55,15 +52,18 @@ public class B { }"; }; await CreateTestLspServerAsync( - markup, mutatingLspWorkspace, initializationOptions); + """ + public class B { } + """, mutatingLspWorkspace, initializationOptions); Assert.False(clientCallbackTarget.ReceivedWorkspaceConfigurationRequest); } [Theory, CombinatorialData] public async Task VerifyWorkflow(bool mutatingLspWorkspace) { - var markup = @" -public class A { }"; + var markup = """ + public class A { } + """; var clientCapabilities = new ClientCapabilities() { diff --git a/src/LanguageServer/ProtocolUnitTests/Definitions/GoToDefinitionTests.cs b/src/LanguageServer/ProtocolUnitTests/Definitions/GoToDefinitionTests.cs index 7bda18323bc8c..b9d5731e0dd29 100644 --- a/src/LanguageServer/ProtocolUnitTests/Definitions/GoToDefinitionTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Definitions/GoToDefinitionTests.cs @@ -26,14 +26,16 @@ public GoToDefinitionTests(ITestOutputHelper testOutputHelper) : base(testOutput public async Task TestGotoDefinitionAsync(bool mutatingLspWorkspace) { var markup = -@"class A -{ - string {|definition:aString|} = 'hello'; - void M() - { - var len = {|caret:|}aString.Length; - } -}"; + """ + class A + { + string {|definition:aString|} = 'hello'; + void M() + { + var len = {|caret:|}aString.Length; + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var results = await RunGotoDefinitionAsync(testLspServer, testLspServer.GetLocations("caret").Single()); @@ -47,20 +49,24 @@ public async Task TestGotoDefinitionAsync_DifferentDocument(bool mutatingLspWork { var markups = new string[] { -@"namespace One -{ - class A - { - public static int {|definition:aInt|} = 1; - } -}", -@"namespace One -{ - class B - { - int bInt = One.A.{|caret:|}aInt; - } -}" + """ + namespace One + { + class A + { + public static int {|definition:aInt|} = 1; + } + } + """, + """ + namespace One + { + class B + { + int bInt = One.A.{|caret:|}aInt; + } + } + """ }; await using var testLspServer = await CreateTestLspServerAsync(markups, mutatingLspWorkspace); @@ -72,18 +78,18 @@ class B [Theory, CombinatorialData] public async Task TestGotoDefinitionAsync_MappedFile(bool mutatingLspWorkspace) { - var markup = -@"class A -{ - string aString = 'hello'; - void M() - { - var len = aString.Length; - } -}"; await using var testLspServer = await CreateTestLspServerAsync(string.Empty, mutatingLspWorkspace); - AddMappedDocument(testLspServer.TestWorkspace, markup); + AddMappedDocument(testLspServer.TestWorkspace, """ + class A + { + string aString = 'hello'; + void M() + { + var len = aString.Length; + } + } + """); var position = new LSP.Position { Line = 5, Character = 18 }; var results = await RunGotoDefinitionAsync(testLspServer, new LSP.Location @@ -98,13 +104,15 @@ void M() public async Task TestGotoDefinitionAsync_InvalidLocation(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void M() - {{|caret:|} - var len = aString.Length; - } -}"; + """ + class A + { + void M() + {{|caret:|} + var len = aString.Length; + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var results = await RunGotoDefinitionAsync(testLspServer, testLspServer.GetLocations("caret").Single()); @@ -115,12 +123,14 @@ void M() public async Task TestGotoDefinitionAsync_NoResultsOnNamespace(bool mutatingLspWorkspace) { var markup = -@"namespace {|caret:M|} -{ - class A - { - } -}"; + """ + namespace {|caret:M|} + { + class A + { + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var results = await RunGotoDefinitionAsync(testLspServer, testLspServer.GetLocations("caret").Single()); @@ -131,23 +141,25 @@ class A public async Task TestGotoDefinitionCrossLanguage(bool mutatingLspWorkspace) { var markup = -@" - - - public class {|definition:A|} - { - } - - - - Definition - - Class C - Dim a As {|caret:A|} - End Class - - -"; + """ + + + + public class {|definition:A|} + { + } + + + + Definition + + Class C + Dim a As {|caret:A|} + End Class + + + + """; await using var testLspServer = await CreateXmlTestLspServerAsync(markup, mutatingLspWorkspace); var results = await RunGotoDefinitionAsync(testLspServer, testLspServer.GetLocations("caret").Single()); @@ -285,18 +297,15 @@ class A } } """; - var generated = - """ + await using var testLspServer = await CreateTestLspServerAsync(source, mutatingLspWorkspace); + await AddGeneratorAsync(new SingleFileTestGenerator(""" namespace M { class B { } } - """; - - await using var testLspServer = await CreateTestLspServerAsync(source, mutatingLspWorkspace); - await AddGeneratorAsync(new SingleFileTestGenerator(generated), testLspServer.TestWorkspace); + """), testLspServer.TestWorkspace); var results = await RunGotoDefinitionAsync(testLspServer, testLspServer.GetLocations("caret").Single()); var result = Assert.Single(results); diff --git a/src/LanguageServer/ProtocolUnitTests/Definitions/GoToTypeDefinitionTests.cs b/src/LanguageServer/ProtocolUnitTests/Definitions/GoToTypeDefinitionTests.cs index 61a6bb0462c18..05abdac7a225c 100644 --- a/src/LanguageServer/ProtocolUnitTests/Definitions/GoToTypeDefinitionTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Definitions/GoToTypeDefinitionTests.cs @@ -4,7 +4,6 @@ #nullable disable -using System; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -27,13 +26,15 @@ public GoToTypeDefinitionTests(ITestOutputHelper testOutputHelper) : base(testOu public async Task TestGotoTypeDefinitionAsync_WithTypeSymbol(bool mutatingLspWorkspace) { var markup = -@"class {|definition:A|} -{ -} -class B -{ - {|caret:|}A classA; -}"; + """ + class {|definition:A|} + { + } + class B + { + {|caret:|}A classA; + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var results = await RunGotoTypeDefinitionAsync(testLspServer, testLspServer.GetLocations("caret").Single()); @@ -44,13 +45,15 @@ class B public async Task TestGotoTypeDefinitionAsync_WithPropertySymbol(bool mutatingLspWorkspace) { var markup = -@"class {|definition:A|} -{ -} -class B -{ - A class{|caret:|}A {; -}"; + """ + class {|definition:A|} + { + } + class B + { + A class{|caret:|}A {; + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var results = await RunGotoTypeDefinitionAsync(testLspServer, testLspServer.GetLocations("caret").Single()); @@ -61,13 +64,15 @@ class B public async Task TestGotoTypeDefinitionAsync_WithFieldSymbol(bool mutatingLspWorkspace) { var markup = -@"class {|definition:A|} -{ -} -class B -{ - A class{|caret:|}A; -}"; + """ + class {|definition:A|} + { + } + class B + { + A class{|caret:|}A; + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var results = await RunGotoTypeDefinitionAsync(testLspServer, testLspServer.GetLocations("caret").Single()); @@ -78,16 +83,18 @@ class B public async Task TestGotoTypeDefinitionAsync_WithLocalSymbol(bool mutatingLspWorkspace) { var markup = -@"class {|definition:A|} -{ -} -class B -{ - void Method() - { - var class{|caret:|}A = new A(); - } -}"; + """ + class {|definition:A|} + { + } + class B + { + void Method() + { + var class{|caret:|}A = new A(); + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var results = await RunGotoTypeDefinitionAsync(testLspServer, testLspServer.GetLocations("caret").Single()); @@ -98,15 +105,17 @@ void Method() public async Task TestGotoTypeDefinitionAsync_WithParameterSymbol(bool mutatingLspWorkspace) { var markup = -@"class {|definition:A|} -{ -} -class B -{ - void Method(A class{|caret:|}A) - { - } -}"; + """ + class {|definition:A|} + { + } + class B + { + void Method(A class{|caret:|}A) + { + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var results = await RunGotoTypeDefinitionAsync(testLspServer, testLspServer.GetLocations("caret").Single()); @@ -118,19 +127,23 @@ public async Task TestGotoTypeDefinitionAsync_DifferentDocument(bool mutatingLsp { var markups = new string[] { -@"namespace One -{ - class {|definition:A|} - { - } -}", -@"namespace One -{ - class B - { - A class{|caret:|}A; - } -}" + """ + namespace One + { + class {|definition:A|} + { + } + } + """, + """ + namespace One + { + class B + { + A class{|caret:|}A; + } + } + """ }; await using var testLspServer = await CreateTestLspServerAsync(markups, mutatingLspWorkspace); @@ -143,14 +156,16 @@ class B public async Task TestGotoTypeDefinitionAsync_InvalidLocation(bool mutatingLspWorkspace) { var markup = -@"class {|definition:A|} -{ -} -class B -{ - A classA; - {|caret:|} -}"; + """ + class {|definition:A|} + { + } + class B + { + A classA; + {|caret:|} + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var results = await RunGotoTypeDefinitionAsync(testLspServer, testLspServer.GetLocations("caret").Single()); @@ -170,19 +185,16 @@ class A } } """; - var mapped = - """ + await using var testLspServer = await CreateTestLspServerAsync(source, mutatingLspWorkspace); + + AddMappedDocument(testLspServer.TestWorkspace, """ namespace M { class B { } } - """; - - await using var testLspServer = await CreateTestLspServerAsync(source, mutatingLspWorkspace); - - AddMappedDocument(testLspServer.TestWorkspace, mapped); + """); var results = await RunGotoTypeDefinitionAsync(testLspServer, testLspServer.GetLocations("caret").Single()); var result = Assert.Single(results); @@ -202,18 +214,15 @@ class A } } """; - var generated = - """ + await using var testLspServer = await CreateTestLspServerAsync(source, mutatingLspWorkspace); + await AddGeneratorAsync(new SingleFileTestGenerator(""" namespace M { class B { } } - """; - - await using var testLspServer = await CreateTestLspServerAsync(source, mutatingLspWorkspace); - await AddGeneratorAsync(new SingleFileTestGenerator(generated), testLspServer.TestWorkspace); + """), testLspServer.TestWorkspace); var results = await RunGotoTypeDefinitionAsync(testLspServer, testLspServer.GetLocations("caret").Single()); var result = Assert.Single(results); @@ -251,23 +260,25 @@ void Rethrow(NotImplementedException exception) public async Task TestGotoTypeDefinitionAsync_CrossLanguage(bool mutatingLspWorkspace) { var markup = -@" - - - public class {|definition:A|} - { - } - - - - Definition - - Class C - Dim {|caret:a|} As A - End Class - - -"; + """ + + + + public class {|definition:A|} + { + } + + + + Definition + + Class C + Dim {|caret:a|} As A + End Class + + + + """; await using var testLspServer = await CreateXmlTestLspServerAsync(markup, mutatingLspWorkspace); var results = await RunGotoTypeDefinitionAsync(testLspServer, testLspServer.GetLocations("caret").Single()); diff --git a/src/LanguageServer/ProtocolUnitTests/Diagnostics/AdditionalFileDiagnosticsTests.cs b/src/LanguageServer/ProtocolUnitTests/Diagnostics/AdditionalFileDiagnosticsTests.cs index cd4ebfc7a2f03..1552f098d01fa 100644 --- a/src/LanguageServer/ProtocolUnitTests/Diagnostics/AdditionalFileDiagnosticsTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Diagnostics/AdditionalFileDiagnosticsTests.cs @@ -15,6 +15,7 @@ using LSP = Roslyn.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Diagnostics; + public sealed class AdditionalFileDiagnosticsTests : AbstractPullDiagnosticTestsBase { public AdditionalFileDiagnosticsTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) @@ -25,12 +26,14 @@ public AdditionalFileDiagnosticsTests(ITestOutputHelper testOutputHelper) : base public async Task TestWorkspaceDiagnosticsReportsAdditionalFileDiagnostic(bool useVSDiagnostics, bool mutatingLspWorkspace) { var workspaceXml = -@$" - - - - -"; + $""" + + + + + + + """; await using var testLspServer = await CreateTestWorkspaceFromXmlAsync(workspaceXml, mutatingLspWorkspace, BackgroundAnalysisScope.FullSolution, useVSDiagnostics); @@ -51,12 +54,14 @@ public async Task TestWorkspaceDiagnosticsReportsAdditionalFileDiagnostic(bool u public async Task TestWorkspaceDiagnosticsWithRemovedAdditionalFile(bool useVSDiagnostics, bool mutatingLspWorkspace) { var workspaceXml = -@$" - - - - -"; + $""" + + + + + + + """; await using var testLspServer = await CreateTestWorkspaceFromXmlAsync(workspaceXml, mutatingLspWorkspace, BackgroundAnalysisScope.FullSolution, useVSDiagnostics); @@ -84,16 +89,18 @@ public async Task TestWorkspaceDiagnosticsWithRemovedAdditionalFile(bool useVSDi public async Task TestWorkspaceDiagnosticsWithAdditionalFileInMultipleProjects(bool mutatingLspWorkspace) { var workspaceXml = -@$" - - - - - - - - -"; + $""" + + + + + + + + + + + """; await using var testLspServer = await CreateTestWorkspaceFromXmlAsync(workspaceXml, mutatingLspWorkspace, BackgroundAnalysisScope.FullSolution, useVSDiagnostics: true); diff --git a/src/LanguageServer/ProtocolUnitTests/Diagnostics/BuildOnlyDiagnosticIdsHandlerTests.cs b/src/LanguageServer/ProtocolUnitTests/Diagnostics/BuildOnlyDiagnosticIdsHandlerTests.cs index 12fb33549c62a..3f1c7968f9806 100644 --- a/src/LanguageServer/ProtocolUnitTests/Diagnostics/BuildOnlyDiagnosticIdsHandlerTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Diagnostics/BuildOnlyDiagnosticIdsHandlerTests.cs @@ -36,9 +36,10 @@ public async Task TestCSharpBuildOnlyDiagnosticIdsAsync(bool mutatingLspWorkspac [WorkItem("https://github.com/dotnet/vscode-csharp/issues/5728")] public async Task TestVisualBasicBuildOnlyDiagnosticIdsAsync(bool mutatingLspWorkspace) { - await using var testLspServer = await CreateVisualBasicTestLspServerAsync(markup: @" -Class C -End Class", mutatingLspWorkspace); + await using var testLspServer = await CreateVisualBasicTestLspServerAsync(markup: """ + Class C + End Class + """, mutatingLspWorkspace); var result = await testLspServer.ExecuteRequest0Async(BuildOnlyDiagnosticIdsHandler.BuildOnlyDiagnosticIdsMethodName, CancellationToken.None); diff --git a/src/LanguageServer/ProtocolUnitTests/Diagnostics/DiagnosticsPullCacheTests.cs b/src/LanguageServer/ProtocolUnitTests/Diagnostics/DiagnosticsPullCacheTests.cs index c643aa923d554..1017a75137049 100644 --- a/src/LanguageServer/ProtocolUnitTests/Diagnostics/DiagnosticsPullCacheTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Diagnostics/DiagnosticsPullCacheTests.cs @@ -19,6 +19,7 @@ using LSP = Roslyn.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Diagnostics; + public sealed class DiagnosticsPullCacheTests(ITestOutputHelper testOutputHelper) : AbstractPullDiagnosticTestsBase(testOutputHelper) { diff --git a/src/LanguageServer/ProtocolUnitTests/Diagnostics/PullDiagnosticTests.cs b/src/LanguageServer/ProtocolUnitTests/Diagnostics/PullDiagnosticTests.cs index cffdff4781ab0..d8d0c218a7c00 100644 --- a/src/LanguageServer/ProtocolUnitTests/Diagnostics/PullDiagnosticTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Diagnostics/PullDiagnosticTests.cs @@ -935,6 +935,37 @@ class A Assert.Equal(LSP.DiagnosticSeverity.Information, results.Single().Diagnostics!.Single().Severity); } + [ConditionalTheory(typeof(UnixLikeOnly)), CombinatorialData] + public async Task TestDocumentDiagnosticsWhenClientRequestsWithDifferentCasing(bool useVSDiagnostics, bool mutatingLspWorkspace) + { + var markup = @"class A {"; + + var workspaceXml = + $""" + + + {markup} + + + """; + + await using var testLspServer = await CreateTestWorkspaceFromXmlAsync(workspaceXml, mutatingLspWorkspace, BackgroundAnalysisScope.OpenFiles, useVSDiagnostics); + + var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); + + var loweredUri = ProtocolConversions.CreateAbsoluteDocumentUri(document.FilePath!.ToLowerInvariant()); + await testLspServer.OpenDocumentAsync(loweredUri); + + var results = await RunGetDocumentPullDiagnosticsAsync( + testLspServer, loweredUri, useVSDiagnostics); + + // When looking up the document based on a URI, the workspace ignores casing differences and can open the document with different casing. + // When diagnostics checks if the document is open, it should also be able to tell that the document is open, even though the URI casing is different from the file path. + + Assert.Equal("CS1513", results.Single().Diagnostics!.Single().Code); + Assert.NotNull(results.Single().Diagnostics!.Single().CodeDescription!.Href.ParsedUri); + } + #endregion #region Workspace Diagnostics diff --git a/src/LanguageServer/ProtocolUnitTests/Diagnostics/WorkspaceProjectDiagnosticsTests.cs b/src/LanguageServer/ProtocolUnitTests/Diagnostics/WorkspaceProjectDiagnosticsTests.cs index d7168da599f4e..e3a9aa893d258 100644 --- a/src/LanguageServer/ProtocolUnitTests/Diagnostics/WorkspaceProjectDiagnosticsTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Diagnostics/WorkspaceProjectDiagnosticsTests.cs @@ -14,6 +14,7 @@ using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Diagnostics; + public sealed class WorkspaceProjectDiagnosticsTests : AbstractPullDiagnosticTestsBase { public WorkspaceProjectDiagnosticsTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) diff --git a/src/LanguageServer/ProtocolUnitTests/DocumentChanges/DocumentChangesTests.LinkedDocuments.cs b/src/LanguageServer/ProtocolUnitTests/DocumentChanges/DocumentChangesTests.LinkedDocuments.cs index 5084d841dc6ac..0f0902375fec0 100644 --- a/src/LanguageServer/ProtocolUnitTests/DocumentChanges/DocumentChangesTests.LinkedDocuments.cs +++ b/src/LanguageServer/ProtocolUnitTests/DocumentChanges/DocumentChangesTests.LinkedDocuments.cs @@ -2,12 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.LanguageServer.Protocol; -using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.DocumentChanges; @@ -19,14 +17,16 @@ public async Task LinkedDocuments_AllTracked(bool mutatingLspWorkspace) { var documentText = "class C { }"; var workspaceXml = -@$" - - {documentText}{{|caret:|}} - - - - -"; + $$""" + + + {{documentText}}{|caret:|} + + + + + + """; await using var testLspServer = await CreateXmlTestLspServerAsync(workspaceXml, mutatingLspWorkspace); var caretLocation = testLspServer.GetLocations("caret").Single(); @@ -52,35 +52,29 @@ public async Task LinkedDocuments_AllTracked(bool mutatingLspWorkspace) public async Task LinkedDocuments_AllTextChanged(bool mutatingLspWorkspace) { var initialText = -@"class A -{ - void M() - { - {|caret:|} - } -}"; + """ + class A + { + void M() + { + {|caret:|} + } + } + """; var workspaceXml = -@$" - - {initialText} - - - - -"; + $""" + + + {initialText} + + + + + + """; await using var testLspServer = await CreateXmlTestLspServerAsync(workspaceXml, mutatingLspWorkspace); var caretLocation = testLspServer.GetLocations("caret").Single(); - - var updatedText = -@"class A -{ - void M() - { - // hi there - } -}"; - await DidOpen(testLspServer, caretLocation.DocumentUri); Assert.Equal(1, testLspServer.GetTrackedTexts().Length); @@ -91,7 +85,15 @@ void M() foreach (var document in solution.Projects.First().Documents) { - Assert.Equal(updatedText, document.GetTextSynchronously(CancellationToken.None).ToString()); + Assert.Equal(""" + class A + { + void M() + { + // hi there + } + } + """, document.GetTextSynchronously(CancellationToken.None).ToString()); } await DidClose(testLspServer, caretLocation.DocumentUri); diff --git a/src/LanguageServer/ProtocolUnitTests/DocumentChanges/DocumentChangesTests.WithFindAllReferences.cs b/src/LanguageServer/ProtocolUnitTests/DocumentChanges/DocumentChangesTests.WithFindAllReferences.cs index 23dc511af4f2c..2bf502b329218 100644 --- a/src/LanguageServer/ProtocolUnitTests/DocumentChanges/DocumentChangesTests.WithFindAllReferences.cs +++ b/src/LanguageServer/ProtocolUnitTests/DocumentChanges/DocumentChangesTests.WithFindAllReferences.cs @@ -14,22 +14,21 @@ public sealed partial class DocumentChangesTests [Theory, CombinatorialData] public async Task FindReferencesInChangingDocument(bool mutatingLspWorkspace) { - var source = -@"class A -{ - public int {|type:|}someInt = 1; - void M() - { - } -} -class B -{ - void M2() - { - } -}"; - - var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(source, mutatingLspWorkspace); + var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(""" + class A + { + public int {|type:|}someInt = 1; + void M() + { + } + } + class B + { + void M2() + { + } + } + """, mutatingLspWorkspace); await using (testLspServer) { diff --git a/src/LanguageServer/ProtocolUnitTests/DocumentChanges/DocumentChangesTests.cs b/src/LanguageServer/ProtocolUnitTests/DocumentChanges/DocumentChangesTests.cs index d9a4e4e11c902..364dec55b7228 100644 --- a/src/LanguageServer/ProtocolUnitTests/DocumentChanges/DocumentChangesTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/DocumentChanges/DocumentChangesTests.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServer.Handler.DocumentChanges; @@ -23,23 +22,15 @@ public DocumentChangesTests(ITestOutputHelper testOutputHelper) : base(testOutpu [Theory, CombinatorialData] public async Task DocumentChanges_EndToEnd(bool mutatingLspWorkspace) { - var source = -@"class A -{ - void M() - { - {|type:|} - } -}"; - var expected = -@"class A -{ - void M() - { - // hi there - } -}"; - var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source, mutatingLspWorkspace); + var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(""" + class A + { + void M() + { + {|type:|} + } + } + """, mutatingLspWorkspace); await using (testLspServer) { @@ -55,7 +46,15 @@ void M() await DidChange(testLspServer, locationTyped.DocumentUri, (4, 8, "// hi there")); document = testLspServer.GetTrackedTexts().Single(); - Assert.Equal(expected, document.ToString()); + Assert.Equal(""" + class A + { + void M() + { + // hi there + } + } + """, document.ToString()); await DidClose(testLspServer, locationTyped.DocumentUri); @@ -66,15 +65,15 @@ void M() [Theory, CombinatorialData] public async Task DidOpen_DocumentIsTracked(bool mutatingLspWorkspace) { - var source = -@"class A -{ - void M() - { - {|type:|} - } -}"; - var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source, mutatingLspWorkspace); + var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(""" + class A + { + void M() + { + {|type:|} + } + } + """, mutatingLspWorkspace); await using (testLspServer) { @@ -90,15 +89,15 @@ void M() [Theory, CombinatorialData] public async Task MultipleDidOpen_Errors(bool mutatingLspWorkspace) { - var source = -@"class A -{ - void M() - { - {|type:|} - } -}"; - var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source, mutatingLspWorkspace); + var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(""" + class A + { + void M() + { + {|type:|} + } + } + """, mutatingLspWorkspace); await using (testLspServer) { @@ -112,15 +111,15 @@ void M() [Theory, CombinatorialData] public async Task DidCloseWithoutDidOpen_Errors(bool mutatingLspWorkspace) { - var source = -@"class A -{ - void M() - { - {|type:|} - } -}"; - var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source, mutatingLspWorkspace); + var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(""" + class A + { + void M() + { + {|type:|} + } + } + """, mutatingLspWorkspace); await using (testLspServer) { @@ -132,15 +131,15 @@ void M() [Theory, CombinatorialData] public async Task DidChangeWithoutDidOpen_Errors(bool mutatingLspWorkspace) { - var source = -@"class A -{ - void M() - { - {|type:|} - } -}"; - var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source, mutatingLspWorkspace); + var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(""" + class A + { + void M() + { + {|type:|} + } + } + """, mutatingLspWorkspace); await using (testLspServer) { @@ -152,16 +151,15 @@ void M() [Theory, CombinatorialData] public async Task DidClose_StopsTrackingDocument(bool mutatingLspWorkspace) { - var source = -@"class A -{ - void M() - { - {|type:|} - } -}"; - - var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(source, mutatingLspWorkspace); + var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(""" + class A + { + void M() + { + {|type:|} + } + } + """, mutatingLspWorkspace); await using (testLspServer) { @@ -176,24 +174,15 @@ void M() [Theory, CombinatorialData] public async Task DidChange_AppliesChanges(bool mutatingLspWorkspace) { - var source = -@"class A -{ - void M() - { - {|type:|} - } -}"; - var expected = -@"class A -{ - void M() - { - // hi there - } -}"; - - var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(source, mutatingLspWorkspace); + var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(""" + class A + { + void M() + { + {|type:|} + } + } + """, mutatingLspWorkspace); await using (testLspServer) { @@ -204,31 +193,30 @@ void M() var document = testLspServer.GetTrackedTexts().FirstOrDefault(); AssertEx.NotNull(document); - Assert.Equal(expected, document.ToString()); + Assert.Equal(""" + class A + { + void M() + { + // hi there + } + } + """, document.ToString()); } } [Theory, CombinatorialData] public async Task DidChange_DoesntUpdateWorkspace(bool mutatingLspWorkspace) { - var source = -@"class A -{ - void M() - { - {|type:|} - } -}"; - var expected = -@"class A -{ - void M() - { - // hi there - } -}"; - - var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source, mutatingLspWorkspace); + var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(""" + class A + { + void M() + { + {|type:|} + } + } + """, mutatingLspWorkspace); await using (testLspServer) { @@ -242,15 +230,22 @@ void M() Assert.Equal(documentText, documentTextFromWorkspace); // Just to ensure this test breaks if didChange stops working for some reason - Assert.NotEqual(expected, documentTextFromWorkspace); + Assert.NotEqual(""" + class A + { + void M() + { + // hi there + } + } + """, documentTextFromWorkspace); } } [Theory, CombinatorialData] public async Task DidChange_MultipleChanges_ForwardOrder(bool mutatingLspWorkspace) { - var source = - """ + var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(""" class A { void M() @@ -258,20 +253,7 @@ void M() {|type:|} } } - """; - var expected = - """ - class A - { - void M() - { - // hi there - // this builds on that - } - } - """; - - var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(source, mutatingLspWorkspace); + """, mutatingLspWorkspace); await using (testLspServer) { @@ -282,15 +264,23 @@ void M() var document = testLspServer.GetTrackedTexts().FirstOrDefault(); AssertEx.NotNull(document); - Assert.Equal(expected, document.ToString()); + Assert.Equal(""" + class A + { + void M() + { + // hi there + // this builds on that + } + } + """, document.ToString()); } } [Theory, CombinatorialData] public async Task DidChange_MultipleChanges_Overlapping(bool mutatingLspWorkspace) { - var source = - """ + var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(""" class A { void M() @@ -298,19 +288,7 @@ void M() {|type:|} } } - """; - var expected = - """ - class A - { - void M() - { - // hi there - } - } - """; - - var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(source, mutatingLspWorkspace); + """, mutatingLspWorkspace); await using (testLspServer) { @@ -321,15 +299,22 @@ void M() var document = testLspServer.GetTrackedTexts().FirstOrDefault(); AssertEx.NotNull(document); - Assert.Equal(expected, document.ToString()); + Assert.Equal(""" + class A + { + void M() + { + // hi there + } + } + """, document.ToString()); } } [Theory, CombinatorialData] public async Task DidChange_MultipleChanges_ReverseOrder(bool mutatingLspWorkspace) { - var source = - """ + var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(""" class A { void M() @@ -337,20 +322,7 @@ void M() {|type:|} } } - """; - var expected = - """ - class A - { - void M() - { - // hi there - // this builds on that - } - } - """; - - var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(source, mutatingLspWorkspace); + """, mutatingLspWorkspace); await using (testLspServer) { @@ -361,7 +333,16 @@ void M() var document = testLspServer.GetTrackedTexts().FirstOrDefault(); AssertEx.NotNull(document); - Assert.Equal(expected, document.ToString()); + Assert.Equal(""" + class A + { + void M() + { + // hi there + // this builds on that + } + } + """, document.ToString()); } } @@ -411,8 +392,7 @@ public void DidChange_AreChangesInReverseOrder_Overlapping() [Theory, CombinatorialData] public async Task DidChange_MultipleRequests(bool mutatingLspWorkspace) { - var source = - """ + var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(""" class A { void M() @@ -420,20 +400,7 @@ void M() {|type:|} } } - """; - var expected = - """ - class A - { - void M() - { - // hi there - // this builds on that - } - } - """; - - var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(source, mutatingLspWorkspace); + """, mutatingLspWorkspace); await using (testLspServer) { @@ -445,7 +412,16 @@ void M() var document = testLspServer.GetTrackedTexts().FirstOrDefault(); AssertEx.NotNull(document); - Assert.Equal(expected, document.ToString()); + Assert.Equal(""" + class A + { + void M() + { + // hi there + // this builds on that + } + } + """, document.ToString()); } } diff --git a/src/LanguageServer/ProtocolUnitTests/FoldingRanges/FoldingRangesTests.cs b/src/LanguageServer/ProtocolUnitTests/FoldingRanges/FoldingRangesTests.cs index 08dafd4843853..4fb10c9fe770c 100644 --- a/src/LanguageServer/ProtocolUnitTests/FoldingRanges/FoldingRangesTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/FoldingRanges/FoldingRangesTests.cs @@ -21,54 +21,37 @@ public FoldingRangesTests(ITestOutputHelper testOutputHelper) : base(testOutputH } [Theory, CombinatorialData] - public async Task TestGetFoldingRangeAsync_Imports(bool mutatingLspWorkspace) - { - var markup = - """ + public Task TestGetFoldingRangeAsync_Imports(bool mutatingLspWorkspace) + => AssertFoldingRanges(mutatingLspWorkspace, """ using {|imports:System; using System.Linq;|} - """; - await AssertFoldingRanges(mutatingLspWorkspace, markup); - } + """); [Theory(Skip = "GetFoldingRangeAsync does not yet support comments."), CombinatorialData] - public async Task TestGetFoldingRangeAsync_Comments(bool mutatingLspWorkspace) - { - var markup = - """ + public Task TestGetFoldingRangeAsync_Comments(bool mutatingLspWorkspace) + => AssertFoldingRanges(mutatingLspWorkspace, """ {|foldingRange:// A comment|} {|foldingRange:/* A multiline comment */|} - """; - await AssertFoldingRanges(mutatingLspWorkspace, markup); - } + """); [Theory, CombinatorialData] - public async Task TestGetFoldingRangeAsync_Regions(bool mutatingLspWorkspace) - { - var markup = - """ + public Task TestGetFoldingRangeAsync_Regions(bool mutatingLspWorkspace) + => AssertFoldingRanges(mutatingLspWorkspace, """ {|region:#region ARegion #endregion|} - """; - await AssertFoldingRanges(mutatingLspWorkspace, markup, "ARegion"); - } + """, "ARegion"); [Theory, CombinatorialData] - public async Task TestGetFoldingRangeAsync_Members(bool mutatingLspWorkspace) - { - var markup = - """ + public Task TestGetFoldingRangeAsync_Members(bool mutatingLspWorkspace) + => AssertFoldingRanges(mutatingLspWorkspace, """ class C{|foldingRange: { public void M(){|implementation: { }|} }|} - """; - - await AssertFoldingRanges(mutatingLspWorkspace, markup); - } + """); private async Task AssertFoldingRanges(bool mutatingLspWorkspace, string markup, string collapsedText = null) { diff --git a/src/LanguageServer/ProtocolUnitTests/FormatNewFile/FormatNewFileTests.cs b/src/LanguageServer/ProtocolUnitTests/FormatNewFile/FormatNewFileTests.cs index 9ac2af9cc4561..1023ad10c2397 100644 --- a/src/LanguageServer/ProtocolUnitTests/FormatNewFile/FormatNewFileTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/FormatNewFile/FormatNewFileTests.cs @@ -8,7 +8,6 @@ using Microsoft.CodeAnalysis.LanguageServer.ExternalAccess.Razor; using Roslyn.LanguageServer.Protocol; using Roslyn.Test.Utilities; -using Roslyn.Utilities; using Xunit; using Xunit.Abstractions; @@ -45,8 +44,12 @@ public partial class MyComponent { } """; + await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); + + var newFilePath = "C:\\MyComponent.razor.cs"; - var expected = """ + var result = await RunHandlerAsync(testLspServer, newFilePath, input); + AssertEx.EqualOrDiff(""" // This is a file header namespace test @@ -55,14 +58,7 @@ public partial class MyComponent { } } - """; - - await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); - - var newFilePath = "C:\\MyComponent.razor.cs"; - - var result = await RunHandlerAsync(testLspServer, newFilePath, input); - AssertEx.EqualOrDiff(expected, result); + """, result); } private static async Task RunHandlerAsync(TestLspServer testLspServer, string newFilePath, string input) diff --git a/src/LanguageServer/ProtocolUnitTests/Formatting/FormatDocumentOnTypeTests.cs b/src/LanguageServer/ProtocolUnitTests/Formatting/FormatDocumentOnTypeTests.cs index ff924df053087..9594294894ba7 100644 --- a/src/LanguageServer/ProtocolUnitTests/Formatting/FormatDocumentOnTypeTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Formatting/FormatDocumentOnTypeTests.cs @@ -33,8 +33,9 @@ void M() } } """; - var expected = - """ + await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); + var locationTyped = testLspServer.GetLocations("type").Single(); + await AssertFormatDocumentOnTypeAsync(testLspServer, ";", locationTyped, """ class A { void M() @@ -43,11 +44,7 @@ void M() { } } - """; - await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); - var characterTyped = ";"; - var locationTyped = testLspServer.GetLocations("type").Single(); - await AssertFormatDocumentOnTypeAsync(testLspServer, characterTyped, locationTyped, expected); + """); } [Theory, CombinatorialData] @@ -64,8 +61,9 @@ void M() } } """; - var expected = - """ + await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); + var locationTyped = testLspServer.GetLocations("type").Single(); + await AssertFormatDocumentOnTypeAsync(testLspServer, ";", locationTyped, """ class A { void M() @@ -74,11 +72,7 @@ void M() { } } - """; - await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); - var characterTyped = ";"; - var locationTyped = testLspServer.GetLocations("type").Single(); - await AssertFormatDocumentOnTypeAsync(testLspServer, characterTyped, locationTyped, expected, insertSpaces: false, tabSize: 4); + """, insertSpaces: false, tabSize: 4); } [Theory, CombinatorialData] @@ -93,8 +87,9 @@ void M() { } } """; - var expected = - """ + await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); + var locationTyped = testLspServer.GetLocations("type").Single(); + await AssertFormatDocumentOnTypeAsync(testLspServer, "\n", locationTyped, """ class A { void M() @@ -102,11 +97,7 @@ void M() } } - """; - await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); - var characterTyped = "\n"; - var locationTyped = testLspServer.GetLocations("type").Single(); - await AssertFormatDocumentOnTypeAsync(testLspServer, characterTyped, locationTyped, expected); + """); } private static async Task AssertFormatDocumentOnTypeAsync( diff --git a/src/LanguageServer/ProtocolUnitTests/Formatting/FormatDocumentRangeTests.cs b/src/LanguageServer/ProtocolUnitTests/Formatting/FormatDocumentRangeTests.cs index ea8962004af3d..cd8b7470604b8 100644 --- a/src/LanguageServer/ProtocolUnitTests/Formatting/FormatDocumentRangeTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Formatting/FormatDocumentRangeTests.cs @@ -24,56 +24,60 @@ public FormatDocumentRangeTests(ITestOutputHelper testOutputHelper) : base(testO public async Task TestFormatDocumentRangeAsync(bool mutatingLspWorkspace) { var markup = -@"class A -{ -{|format:void|} M() -{ - int i = 1; - } -}"; - var expected = -@"class A -{ - void M() -{ - int i = 1; - } -}"; + """ + class A + { + {|format:void|} M() + { + int i = 1; + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var rangeToFormat = testLspServer.GetLocations("format").Single(); var documentText = await testLspServer.GetDocumentTextAsync(rangeToFormat.DocumentUri); var results = await RunFormatDocumentRangeAsync(testLspServer, rangeToFormat); var actualText = ApplyTextEdits(results, documentText); - Assert.Equal(expected, actualText); + Assert.Equal(""" + class A + { + void M() + { + int i = 1; + } + } + """, actualText); } [Theory, CombinatorialData] public async Task TestFormatDocumentRange_UseTabsAsync(bool mutatingLspWorkspace) { var markup = -@"class A -{ -{|format:void|} M() -{ - int i = 1; - } -}"; - var expected = -@"class A -{ - void M() -{ - int i = 1; - } -}"; + """ + class A + { + {|format:void|} M() + { + int i = 1; + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var rangeToFormat = testLspServer.GetLocations("format").Single(); var documentText = await testLspServer.GetDocumentTextAsync(rangeToFormat.DocumentUri); var results = await RunFormatDocumentRangeAsync(testLspServer, rangeToFormat, insertSpaces: false, tabSize: 4); var actualText = ApplyTextEdits(results, documentText); - Assert.Equal(expected, actualText); + Assert.Equal(""" + class A + { + void M() + { + int i = 1; + } + } + """, actualText); } private static async Task RunFormatDocumentRangeAsync( diff --git a/src/LanguageServer/ProtocolUnitTests/Formatting/FormatDocumentTests.cs b/src/LanguageServer/ProtocolUnitTests/Formatting/FormatDocumentTests.cs index c2d126efc857e..834a9909f24c5 100644 --- a/src/LanguageServer/ProtocolUnitTests/Formatting/FormatDocumentTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Formatting/FormatDocumentTests.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; @@ -34,8 +33,9 @@ void M() } } """; - var expected = - """ + await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); + var documentURI = testLspServer.GetLocations("caret").Single().DocumentUri; + await AssertFormatDocumentAsync(testLspServer, documentURI, """ class A { void M() @@ -43,10 +43,7 @@ void M() int i = 1; } } - """; - await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); - var documentURI = testLspServer.GetLocations("caret").Single().DocumentUri; - await AssertFormatDocumentAsync(testLspServer, documentURI, expected); + """); } [Theory, CombinatorialData] @@ -61,16 +58,6 @@ class A{|caret:|} { } """; - var expected = - """ - using System; - using System.Collections; - - class A - { - } - """; - var options = new InitializationOptions { OptionUpdater = globalOptions => @@ -81,7 +68,14 @@ class A await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, options); var documentURI = testLspServer.GetLocations("caret").Single().DocumentUri; - await AssertFormatDocumentAsync(testLspServer, documentURI, expected); + await AssertFormatDocumentAsync(testLspServer, documentURI, """ + using System; + using System.Collections; + + class A + { + } + """); } [Theory, CombinatorialData] @@ -96,16 +90,6 @@ class A{|caret:|} { } """; - var expected = - """ - using System; - using System.Collections; - - class A - { - } - """; - var options = new InitializationOptions { OptionUpdater = globalOptions => @@ -116,7 +100,14 @@ class A await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, options); var documentURI = testLspServer.GetLocations("caret").Single().DocumentUri; - await AssertFormatDocumentAsync(testLspServer, documentURI, expected); + await AssertFormatDocumentAsync(testLspServer, documentURI, """ + using System; + using System.Collections; + + class A + { + } + """); } [Theory, CombinatorialData] @@ -131,16 +122,6 @@ class A{|caret:|} { } """; - var expected = - """ - using System; - using System.Collections; - - class A - { - } - """; - var options = new InitializationOptions { OptionUpdater = globalOptions => @@ -151,7 +132,14 @@ class A await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, options); var documentURI = testLspServer.GetLocations("caret").Single().DocumentUri; - await AssertFormatDocumentAsync(testLspServer, documentURI, expected); + await AssertFormatDocumentAsync(testLspServer, documentURI, """ + using System; + using System.Collections; + + class A + { + } + """); } [Theory, CombinatorialData] @@ -166,16 +154,6 @@ class A{|caret:|} { } """; - var expected = - """ - using System; - using System.Collections; - - class A - { - } - """; - var options = new InitializationOptions { OptionUpdater = globalOptions => @@ -186,7 +164,14 @@ class A await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, options); var documentURI = testLspServer.GetLocations("caret").Single().DocumentUri; - await AssertFormatDocumentAsync(testLspServer, documentURI, expected); + await AssertFormatDocumentAsync(testLspServer, documentURI, """ + using System; + using System.Collections; + + class A + { + } + """); } [Theory, CombinatorialData] @@ -205,20 +190,6 @@ void M() } } """; - var expected = - """ - using System; - using System.Collections; - - class A - { - void M() - { - int i = 1; - } - } - """; - var options = new InitializationOptions { OptionUpdater = globalOptions => @@ -229,7 +200,18 @@ void M() await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, options); var documentURI = testLspServer.GetLocations("caret").Single().DocumentUri; - await AssertFormatDocumentAsync(testLspServer, documentURI, expected); + await AssertFormatDocumentAsync(testLspServer, documentURI, """ + using System; + using System.Collections; + + class A + { + void M() + { + int i = 1; + } + } + """); } [Theory, CombinatorialData] @@ -244,19 +226,16 @@ class A{|caret:|} { } """; - var expected = - """ + await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); + var documentURI = testLspServer.GetLocations("caret").Single().DocumentUri; + await AssertFormatDocumentAsync(testLspServer, documentURI, """ using System.Collections; using System; class A { } - """; - - await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); - var documentURI = testLspServer.GetLocations("caret").Single().DocumentUri; - await AssertFormatDocumentAsync(testLspServer, documentURI, expected); + """); } [Theory, CombinatorialData] @@ -272,8 +251,9 @@ void M() } } """; - var expected = - """ + await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); + var documentURI = testLspServer.GetLocations("caret").Single().DocumentUri; + await AssertFormatDocumentAsync(testLspServer, documentURI, """ class A { void M() @@ -281,10 +261,7 @@ void M() int i = 1; } } - """; - await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); - var documentURI = testLspServer.GetLocations("caret").Single().DocumentUri; - await AssertFormatDocumentAsync(testLspServer, documentURI, expected, insertSpaces: false, tabSize: 4); + """, insertSpaces: false, tabSize: 4); } [Theory, CombinatorialData] @@ -300,8 +277,9 @@ void M() } } """; - var expected = - """ + await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); + var documentURI = testLspServer.GetLocations("caret").Single().DocumentUri; + await AssertFormatDocumentAsync(testLspServer, documentURI, """ class A { void M() @@ -309,10 +287,7 @@ void M() int i = 1; } } - """; - await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); - var documentURI = testLspServer.GetLocations("caret").Single().DocumentUri; - await AssertFormatDocumentAsync(testLspServer, documentURI, expected, insertSpaces: true, tabSize: 2); + """, insertSpaces: true, tabSize: 2); } private static async Task AssertFormatDocumentAsync( diff --git a/src/LanguageServer/ProtocolUnitTests/HandlerTests.cs b/src/LanguageServer/ProtocolUnitTests/HandlerTests.cs index 0585ecea6f238..a117815191a4d 100644 --- a/src/LanguageServer/ProtocolUnitTests/HandlerTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/HandlerTests.cs @@ -110,12 +110,9 @@ public async Task CanExecuteLanguageSpecificHandlerWithDifferentRequestTypes(boo } [Theory, CombinatorialData] - public async Task ThrowsOnInvalidLanguageSpecificHandler(bool mutatingLspWorkspace) - { - // Arrange - await Assert.ThrowsAsync(async () => await CreateTestLspServerAsync("", mutatingLspWorkspace, + public Task ThrowsOnInvalidLanguageSpecificHandler(bool mutatingLspWorkspace) + => Assert.ThrowsAsync(async () => await CreateTestLspServerAsync("", mutatingLspWorkspace, composition: Composition.AddParts(typeof(TestDuplicateLanguageSpecificHandler)))); - } [Theory, CombinatorialData] public async Task ThrowsIfDeserializationFails(bool mutatingLspWorkspace) diff --git a/src/LanguageServer/ProtocolUnitTests/Highlights/DocumentHighlightTests.cs b/src/LanguageServer/ProtocolUnitTests/Highlights/DocumentHighlightTests.cs index 1d58b5b22d602..b935492779f1a 100644 --- a/src/LanguageServer/ProtocolUnitTests/Highlights/DocumentHighlightTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Highlights/DocumentHighlightTests.cs @@ -25,18 +25,20 @@ public DocumentHighlightTests(ITestOutputHelper testOutputHelper) : base(testOut public async Task TestGetDocumentHighlightAsync(bool lspMutatingWorkspace) { var markup = -@"class B -{ -} -class A -{ - B {|text:classB|}; - void M() - { - var someVar = {|read:classB|}; - {|caret:|}{|write:classB|} = new B(); - } -}"; + """ + class B + { + } + class A + { + B {|text:classB|}; + void M() + { + var someVar = {|read:classB|}; + {|caret:|}{|write:classB|} = new B(); + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, lspMutatingWorkspace); var expected = new LSP.DocumentHighlight[] { @@ -53,15 +55,17 @@ void M() public async Task TestGetDocumentHighlightAsync_Keywords(bool lspMutatingWorkspace) { var markup = -@"using System.Threading.Tasks; -class A -{ - {|text:async|} Task MAsync() - { - {|text:await|} Task.Delay(100); - {|caret:|}{|text:await|} Task.Delay(100); - } -}"; + """ + using System.Threading.Tasks; + class A + { + {|text:async|} Task MAsync() + { + {|text:await|} Task.Delay(100); + {|caret:|}{|text:await|} Task.Delay(100); + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, lspMutatingWorkspace); var expectedLocations = testLspServer.GetLocations("text"); @@ -79,13 +83,15 @@ class A public async Task TestGetDocumentHighlightAsync_InvalidLocation(bool lspMutatingWorkspace) { var markup = -@"class A -{ - void M() - { - {|caret:|} - } -}"; + """ + class A + { + void M() + { + {|caret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, lspMutatingWorkspace); var results = await RunGetDocumentHighlightAsync(testLspServer, testLspServer.GetLocations("caret").Single()); diff --git a/src/LanguageServer/ProtocolUnitTests/Hover/HoverTests.cs b/src/LanguageServer/ProtocolUnitTests/Hover/HoverTests.cs index 7c51e7df39f74..3875323771865 100644 --- a/src/LanguageServer/ProtocolUnitTests/Hover/HoverTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Hover/HoverTests.cs @@ -236,8 +236,10 @@ public async Task TestGetHoverAsync_UsingMarkupContent(bool mutatingLspWorkspace }; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, clientCapabilities); var expectedLocation = testLspServer.GetLocations("caret").Single(); - - var expectedMarkdown = @$"```csharp + var results = await RunGetHoverAsync( + testLspServer, + expectedLocation).ConfigureAwait(false); + Assert.Equal(@$"```csharp void A.AMethod(int i) ``` @@ -258,12 +260,7 @@ Remarks are cool too\. {WorkspacesResources.Exceptions_colon}   System\.NullReferenceException -"; - - var results = await RunGetHoverAsync( - testLspServer, - expectedLocation).ConfigureAwait(false); - Assert.Equal(expectedMarkdown, results.Contents.Fourth.Value); +", results.Contents.Fourth.Value); } [Theory, CombinatorialData] @@ -306,8 +303,10 @@ public async Task TestGetHoverAsync_WithoutMarkdownClientSupport(bool mutatingLs }"; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var expectedLocation = testLspServer.GetLocations("caret").Single(); - - var expectedText = @$"void A.AMethod(int i) + var results = await RunGetHoverAsync( + testLspServer, + expectedLocation).ConfigureAwait(false); + Assert.Equal(@$"void A.AMethod(int i) A cref A.AMethod(int) strong text italic text @@ -325,12 +324,7 @@ a string {WorkspacesResources.Exceptions_colon} System.NullReferenceException -"; - - var results = await RunGetHoverAsync( - testLspServer, - expectedLocation).ConfigureAwait(false); - Assert.Equal(expectedText, results.Contents.Fourth.Value); +", results.Contents.Fourth.Value); } [Theory, CombinatorialData] @@ -366,8 +360,10 @@ public async Task TestGetHoverAsync_UsingMarkupContentProperlyEscapes(bool mutat }; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, clientCapabilities); var expectedLocation = testLspServer.GetLocations("caret").Single(); - - var expectedMarkdown = @"```csharp + var results = await RunGetHoverAsync( + testLspServer, + expectedLocation).ConfigureAwait(false); + Assert.Equal(@"```csharp void A.AMethod(int i) ``` @@ -379,12 +375,7 @@ void A.AMethod(int i) **strong\\\*\* text** _italic\_ \*\*text\*\*_ [closing\] link](https://google.com) -"; - - var results = await RunGetHoverAsync( - testLspServer, - expectedLocation).ConfigureAwait(false); - Assert.Equal(expectedMarkdown, results.Contents.Fourth.Value); +", results.Contents.Fourth.Value); } [Theory, CombinatorialData] @@ -410,18 +401,15 @@ public async Task TestGetHoverAsync_UsingMarkupContentDoesNotEscapeCode(bool mut }; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, clientCapabilities); var expectedLocation = testLspServer.GetLocations("caret").Single(); - - var expectedMarkdown = @"```csharp + var results = await RunGetHoverAsync( + testLspServer, + expectedLocation).ConfigureAwait(false); + Assert.Equal(@"```csharp void A.AMethod(int i) ``` `if (true) { Console.WriteLine(""hello""); }` -"; - - var results = await RunGetHoverAsync( - testLspServer, - expectedLocation).ConfigureAwait(false); - Assert.Equal(expectedMarkdown, results.Contents.Fourth.Value); +", results.Contents.Fourth.Value); } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/roslyn/issues/75181")] @@ -447,8 +435,10 @@ public async Task TestGetHoverAsync_UsingMarkupContentDoesNotEscapeCodeBlock(boo }; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, clientCapabilities); var expectedLocation = testLspServer.GetLocations("caret").Single(); - - var expectedMarkdown = @"```csharp + var results = await RunGetHoverAsync( + testLspServer, + expectedLocation).ConfigureAwait(false); + Assert.Equal(@"```csharp void A.AMethod(int i) ``` @@ -458,12 +448,7 @@ void A.AMethod(int i) Console.WriteLine(""hello""); } ``` -"; - - var results = await RunGetHoverAsync( - testLspServer, - expectedLocation).ConfigureAwait(false); - Assert.Equal(expectedMarkdown, results.Contents.Fourth.Value); +", results.Contents.Fourth.Value); } [Theory, CombinatorialData, WorkItem("https://github.com/microsoft/vscode-dotnettools/issues/1499")] @@ -485,18 +470,15 @@ public async Task TestGetHoverAsync_UsingMarkupContentEscapesBacktickInCode(bool }; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, clientCapabilities); var expectedLocation = testLspServer.GetLocations("caret").Single(); - - var expectedMarkdown = @"```csharp + var results = await RunGetHoverAsync( + testLspServer, + expectedLocation).ConfigureAwait(false); + Assert.Equal(@"```csharp void A.AMethod(int i) ``` Hello ``A`1[B,C]`` -"; - - var results = await RunGetHoverAsync( - testLspServer, - expectedLocation).ConfigureAwait(false); - Assert.Equal(expectedMarkdown, results.Contents.Fourth.Value); +", results.Contents.Fourth.Value); } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/vscode-csharp/issues/6577")] @@ -517,14 +499,11 @@ public async Task DoAsync() }; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, clientCapabilities); var expectedLocation = testLspServer.GetLocations("caret").Single(); - - var expectedMarkdown = $@"{string.Format(FeaturesResources.Awaited_task_returns_0, "`class System.String`")} -"; - var results = await RunGetHoverAsync( testLspServer, expectedLocation).ConfigureAwait(false); - Assert.Equal(expectedMarkdown, results.Contents.Fourth.Value); + Assert.Equal($@"{string.Format(FeaturesResources.Awaited_task_returns_0, "`class System.String`")} +", results.Contents.Fourth.Value); } [Theory, CombinatorialData] @@ -558,20 +537,6 @@ static void Main(string[] args) """; - - var expectedMarkdown = $""" - ```csharp - ({FeaturesResources.constant}) string WithConstant.Target = "Target in net472" - ``` - - -     {string.Format(FeaturesResources._0_1, "Net472", FeaturesResources.Available).Replace("-", "\\-")} -     {string.Format(FeaturesResources._0_1, "NetCoreApp3", FeaturesResources.Not_Available).Replace("-", "\\-")} - - {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts.Replace(".", "\\.")} - - """; - var clientCapabilities = new LSP.ClientCapabilities { TextDocument = new LSP.TextDocumentClientCapabilities { Hover = new LSP.HoverSetting { ContentFormat = [LSP.MarkupKind.Markdown] } } @@ -583,7 +548,18 @@ static void Main(string[] args) var result = await RunGetHoverAsync(testLspServer, location, project.Id); AssertEx.NotNull(result); - Assert.Equal(expectedMarkdown, result.Contents.Fourth.Value); + Assert.Equal($""" + ```csharp + ({FeaturesResources.constant}) string WithConstant.Target = "Target in net472" + ``` + + +     {string.Format(FeaturesResources._0_1, "Net472", FeaturesResources.Available).Replace("-", "\\-")} +     {string.Format(FeaturesResources._0_1, "NetCoreApp3", FeaturesResources.Not_Available).Replace("-", "\\-")} + + {FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts.Replace(".", "\\.")} + + """, result.Contents.Fourth.Value); } [Theory, CombinatorialData, WorkItem("https://github.com/dotnet/vscode-csharp/issues/6577")] @@ -609,8 +585,10 @@ private async Task>> GetData() }; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, clientCapabilities); var expectedLocation = testLspServer.GetLocations("caret").Single(); - - var expectedMarkdown = """ + var results = await RunGetHoverAsync( + testLspServer, + expectedLocation).ConfigureAwait(false); + Assert.Equal(""" ```csharp interface System.Collections.Generic.IDictionary ``` @@ -619,12 +597,7 @@ interface System.Collections.Generic.IDictionary TKey is string TValue is ImmutableArray\ - """; - - var results = await RunGetHoverAsync( - testLspServer, - expectedLocation).ConfigureAwait(false); - Assert.Equal(expectedMarkdown, results.Contents.Fourth.Value); + """, results.Contents.Fourth.Value); } private static async Task RunGetHoverAsync( diff --git a/src/LanguageServer/ProtocolUnitTests/InlayHint/CSharpInlayHintTests.cs b/src/LanguageServer/ProtocolUnitTests/InlayHint/CSharpInlayHintTests.cs index a85c0710b4804..f16eba198977a 100644 --- a/src/LanguageServer/ProtocolUnitTests/InlayHint/CSharpInlayHintTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/InlayHint/CSharpInlayHintTests.cs @@ -3,17 +3,17 @@ // See the LICENSE file in the project root for more information. using System.Linq; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.InlineHints; -using Roslyn.LanguageServer.Protocol; using Microsoft.CodeAnalysis.LanguageServer.Handler.InlayHint; using Microsoft.CodeAnalysis.Text; +using Roslyn.LanguageServer.Protocol; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using LSP = Roslyn.LanguageServer.Protocol; -using System.Text.Json; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.InlayHint; @@ -24,96 +24,88 @@ public CSharpInlayHintTests(ITestOutputHelper? testOutputHelper) : base(testOutp } [Theory, CombinatorialData] - public async Task TestOneInlayParameterHintAsync(bool mutatingLspWorkspace) - { - var markup = -@"class A -{ - void M(int x) - { - } + public Task TestOneInlayParameterHintAsync(bool mutatingLspWorkspace) + => RunVerifyInlayHintAsync(""" + class A + { + void M(int x) + { + } - void M2() - { - M({|x:|}5); - } -}"; - await RunVerifyInlayHintAsync(markup, mutatingLspWorkspace); - } + void M2() + { + M({|x:|}5); + } + } + """, mutatingLspWorkspace); [Theory, CombinatorialData] - public async Task TestMultipleInlayParameterHintsAsync(bool mutatingLspWorkspace) - { - var markup = -@"class A -{ - void M(int a, double b, bool c) - { - } + public Task TestMultipleInlayParameterHintsAsync(bool mutatingLspWorkspace) + => RunVerifyInlayHintAsync(""" + class A + { + void M(int a, double b, bool c) + { + } - void M2() - { - M({|a:|}5, {|b:|}5.5, {|c:|}true); - } -}"; - await RunVerifyInlayHintAsync(markup, mutatingLspWorkspace); - } + void M2() + { + M({|a:|}5, {|b:|}5.5, {|c:|}true); + } + } + """, mutatingLspWorkspace); [Theory, CombinatorialData] - public async Task TestOneInlayTypeHintAsync(bool mutatingLspWorkspace) - { - var markup = -@"class A -{ - void M() - { - var {|int:|}x = 5; - } -}"; - await RunVerifyInlayHintAsync(markup, mutatingLspWorkspace); - } + public Task TestOneInlayTypeHintAsync(bool mutatingLspWorkspace) + => RunVerifyInlayHintAsync(""" + class A + { + void M() + { + var {|int:|}x = 5; + } + } + """, mutatingLspWorkspace); [Theory, CombinatorialData] - public async Task TestMultipleInlayTypeHintsAsync(bool mutatingLspWorkspace) - { - var markup = -@"using System; -class A -{ - void M() - { - var {|int:|}x = 5; - var {|object:|}obj = new Object(); - } -}"; - await RunVerifyInlayHintAsync(markup, mutatingLspWorkspace); - } + public Task TestMultipleInlayTypeHintsAsync(bool mutatingLspWorkspace) + => RunVerifyInlayHintAsync(""" + using System; + class A + { + void M() + { + var {|int:|}x = 5; + var {|object:|}obj = new Object(); + } + } + """, mutatingLspWorkspace); [Theory, CombinatorialData] - public async Task TestInlayTypeHintsDeconstructAsync(bool mutatingLspWorkspace) - { - var markup = -@"class A -{ - void X((int, bool) d) - { - var (i, b) = d; - } -}"; - await RunVerifyInlayHintAsync(markup, mutatingLspWorkspace, hasTextEdits: false); - } + public Task TestInlayTypeHintsDeconstructAsync(bool mutatingLspWorkspace) + => RunVerifyInlayHintAsync(""" + class A + { + void X((int, bool) d) + { + var (i, b) = d; + } + } + """, mutatingLspWorkspace, hasTextEdits: false); [Theory, CombinatorialData] public async Task TestReturnsInlayHintsEvenIfCacheMisses(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void M() - { - var {|int:|}x = 5; - } -}"; + """ + class A + { + void M() + { + var {|int:|}x = 5; + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, CapabilitiesWithVSExtensions); testLspServer.TestWorkspace.GlobalOptions.SetGlobalOption(InlineHintsOptionsStorage.EnabledForParameters, LanguageNames.CSharp, true); testLspServer.TestWorkspace.GlobalOptions.SetGlobalOption(InlineHintsOptionsStorage.EnabledForTypes, LanguageNames.CSharp, true); diff --git a/src/LanguageServer/ProtocolUnitTests/InlayHint/VisualBasicInlayHintTests.cs b/src/LanguageServer/ProtocolUnitTests/InlayHint/VisualBasicInlayHintTests.cs index 628d7cb28b833..b9a0549d02d4f 100644 --- a/src/LanguageServer/ProtocolUnitTests/InlayHint/VisualBasicInlayHintTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/InlayHint/VisualBasicInlayHintTests.cs @@ -18,34 +18,30 @@ public VisualBasicInlayHintTests(ITestOutputHelper? testOutputHelper) : base(tes } [Theory, CombinatorialData] - public async Task TestOneInlayParameterHintAsync(bool mutatingLspWorkspace) - { - var markup = -@"Class A - Sub M(x As Integer) - End Sub + public Task TestOneInlayParameterHintAsync(bool mutatingLspWorkspace) + => RunVerifyInlayHintAsync(""" + Class A + Sub M(x As Integer) + End Sub - Sub M2() - M({|x:|}5) - End Sub -End Class"; - await RunVerifyInlayHintAsync(markup, mutatingLspWorkspace); - } + Sub M2() + M({|x:|}5) + End Sub + End Class + """, mutatingLspWorkspace); [Theory, CombinatorialData] - public async Task TestMultipleInlayParameterHintsAsync(bool mutatingLspWorkspace) - { - var markup = -@"Class A - Sub M(x As Integer, y As Boolean) - End Sub + public Task TestMultipleInlayParameterHintsAsync(bool mutatingLspWorkspace) + => RunVerifyInlayHintAsync(""" + Class A + Sub M(x As Integer, y As Boolean) + End Sub - Sub M2() - M({|x:|}5, {|y:|}True) - End Sub -End Class"; - await RunVerifyInlayHintAsync(markup, mutatingLspWorkspace); - } + Sub M2() + M({|x:|}5, {|y:|}True) + End Sub + End Class + """, mutatingLspWorkspace); private async Task RunVerifyInlayHintAsync(string markup, bool mutatingLspWorkspace) { diff --git a/src/LanguageServer/ProtocolUnitTests/InlineCompletions/InlineCompletionsTests.cs b/src/LanguageServer/ProtocolUnitTests/InlineCompletions/InlineCompletionsTests.cs index 1012538901672..1c86f5cf56a9f 100644 --- a/src/LanguageServer/ProtocolUnitTests/InlineCompletions/InlineCompletionsTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/InlineCompletions/InlineCompletionsTests.cs @@ -24,225 +24,195 @@ public InlineCompletionsTests(ITestOutputHelper testOutputHelper) : base(testOut .AddParts(typeof(TestSnippetInfoService)); [Theory, CombinatorialData] - public async Task TestSimpleSnippet(bool mutatingLspWorkspace) - { - var markup = -@"class A -{ - void M() - { - if{|tab:|} - } -}"; - var expectedSnippet = -@"if (${1:true}) - { - $0 - }"; - - await VerifyMarkupAndExpected(markup, expectedSnippet, mutatingLspWorkspace); - } + public Task TestSimpleSnippet(bool mutatingLspWorkspace) + => VerifyMarkupAndExpected(""" + class A + { + void M() + { + if{|tab:|} + } + } + """, """ + if (${1:true}) + { + $0 + } + """, mutatingLspWorkspace); [Theory, CombinatorialData] - public async Task TestSnippetIgnoresCase(bool mutatingLspWorkspace) - { - var markup = -@"class A -{ - void M() - { - If{|tab:|} - } -}"; - var expectedSnippet = -@"if (${1:true}) - { - $0 - }"; - - await VerifyMarkupAndExpected(markup, expectedSnippet, mutatingLspWorkspace); - } + public Task TestSnippetIgnoresCase(bool mutatingLspWorkspace) + => VerifyMarkupAndExpected(""" + class A + { + void M() + { + If{|tab:|} + } + } + """, """ + if (${1:true}) + { + $0 + } + """, mutatingLspWorkspace); [Theory, CombinatorialData] - public async Task TestSnippetUsesOptionsFromRequest(bool mutatingLspWorkspace) - { - var markup = -@"class A -{ - void M() - { - if{|tab:|} - } -}"; - var expectedSnippet = -@"if (${1:true}) - { - $0 - }"; - - await VerifyMarkupAndExpected(markup, expectedSnippet, mutatingLspWorkspace, options: new LSP.FormattingOptions { TabSize = 1, InsertSpaces = true }); - } + public Task TestSnippetUsesOptionsFromRequest(bool mutatingLspWorkspace) + => VerifyMarkupAndExpected(""" + class A + { + void M() + { + if{|tab:|} + } + } + """, """ + if (${1:true}) + { + $0 + } + """, mutatingLspWorkspace, options: new LSP.FormattingOptions { TabSize = 1, InsertSpaces = true }); [Theory, CombinatorialData] - public async Task TestSnippetWithMultipleDeclarations(bool mutatingLspWorkspace) - { - var markup = -@"class A -{ - void M() - { - for{|tab:|} - } -}"; - var expectedSnippet = -@"for (int ${1:i} = 0; ${1:i} < ${2:length}; ${1:i}++) - { - $0 - }"; - - await VerifyMarkupAndExpected(markup, expectedSnippet, mutatingLspWorkspace); - } + public Task TestSnippetWithMultipleDeclarations(bool mutatingLspWorkspace) + => VerifyMarkupAndExpected(""" + class A + { + void M() + { + for{|tab:|} + } + } + """, """ + for (int ${1:i} = 0; ${1:i} < ${2:length}; ${1:i}++) + { + $0 + } + """, mutatingLspWorkspace); [Theory, CombinatorialData] - public async Task TestSnippetWithSimpleTypeNameFunctionFullyQualifies(bool mutatingLspWorkspace) - { - var markup = -@"class A -{ - void M() - { - cw{|tab:|} - } -}"; - var expectedSnippet = @"System.Console.WriteLine($0);"; - - await VerifyMarkupAndExpected(markup, expectedSnippet, mutatingLspWorkspace); - } + public Task TestSnippetWithSimpleTypeNameFunctionFullyQualifies(bool mutatingLspWorkspace) + => VerifyMarkupAndExpected(""" + class A + { + void M() + { + cw{|tab:|} + } + } + """, @"System.Console.WriteLine($0);", mutatingLspWorkspace); [Theory, CombinatorialData] - public async Task TestSnippetWithSimpleTypeNameFunctionWithUsing(bool mutatingLspWorkspace) - { - var markup = -@"using System; -class A -{ - void M() - { - cw{|tab:|} - } -}"; - var expectedSnippet = @"Console.WriteLine($0);"; - - await VerifyMarkupAndExpected(markup, expectedSnippet, mutatingLspWorkspace); - } + public Task TestSnippetWithSimpleTypeNameFunctionWithUsing(bool mutatingLspWorkspace) + => VerifyMarkupAndExpected(""" + using System; + class A + { + void M() + { + cw{|tab:|} + } + } + """, @"Console.WriteLine($0);", mutatingLspWorkspace); [Theory, CombinatorialData] - public async Task TestSnippetWithClassNameFunction(bool mutatingLspWorkspace) - { - var markup = -@"class A -{ - ctor{|tab:|} -}"; - var expectedSnippet = -@"public A() - { - $0 - }"; - - await VerifyMarkupAndExpected(markup, expectedSnippet, mutatingLspWorkspace); - } + public Task TestSnippetWithClassNameFunction(bool mutatingLspWorkspace) + => VerifyMarkupAndExpected(""" + class A + { + ctor{|tab:|} + } + """, """ + public A() + { + $0 + } + """, mutatingLspWorkspace); [Theory, CombinatorialData] - public async Task TestSnippetWithClassNameFunctionOutsideOfClass(bool mutatingLspWorkspace) - { - var markup = -@"ctor{|tab:|}"; - var expectedSnippet = -@"public ClassNamePlaceholder () -{ - $0 -}"; - - await VerifyMarkupAndExpected(markup, expectedSnippet, mutatingLspWorkspace); - } + public Task TestSnippetWithClassNameFunctionOutsideOfClass(bool mutatingLspWorkspace) + => VerifyMarkupAndExpected(@"ctor{|tab:|}", """ + public ClassNamePlaceholder () + { + $0 + } + """, mutatingLspWorkspace); [Theory, CombinatorialData] - public async Task TestSnippetWithSwitchFunctionOnlyGeneratesDefault(bool mutatingLspWorkspace) - { - var markup = -@"class A -{ - void M() - { - switch{|tab:|} - } -}"; - var expectedSnippet = -@"switch (${1:switch_on}) - { - default: - }$0"; - - await VerifyMarkupAndExpected(markup, expectedSnippet, mutatingLspWorkspace); - } + public Task TestSnippetWithSwitchFunctionOnlyGeneratesDefault(bool mutatingLspWorkspace) + => VerifyMarkupAndExpected(""" + class A + { + void M() + { + switch{|tab:|} + } + } + """, """ + switch (${1:switch_on}) + { + default: + }$0 + """, mutatingLspWorkspace); [Theory, CombinatorialData] - public async Task TestSnippetWithNoEditableFields(bool mutatingLspWorkspace) - { - var markup = -@"class A -{ - equals{|tab:|} -}"; - var expectedSnippet = -@"// override object.Equals - public override bool Equals(object obj) - { - // - // See the full list of guidelines at - // http://go.microsoft.com/fwlink/?LinkID=85237 - // and also the guidance for operator== at - // http://go.microsoft.com/fwlink/?LinkId=85238 - // - - if (obj == null || GetType() != obj.GetType()) - { - return false; - } - - // TODO: write your implementation of Equals() here - throw new System.NotImplementedException(); - return base.Equals(obj);$0 - } - - // override object.GetHashCode - public override int GetHashCode() - { - // TODO: write your implementation of GetHashCode() here - throw new System.NotImplementedException(); - return base.GetHashCode(); - }"; - - await VerifyMarkupAndExpected(markup, expectedSnippet, mutatingLspWorkspace); - } + public Task TestSnippetWithNoEditableFields(bool mutatingLspWorkspace) + => VerifyMarkupAndExpected(""" + class A + { + equals{|tab:|} + } + """, """ + // override object.Equals + public override bool Equals(object obj) + { + // + // See the full list of guidelines at + // http://go.microsoft.com/fwlink/?LinkID=85237 + // and also the guidance for operator== at + // http://go.microsoft.com/fwlink/?LinkId=85238 + // + + if (obj == null || GetType() != obj.GetType()) + { + return false; + } + + // TODO: write your implementation of Equals() here + throw new System.NotImplementedException(); + return base.Equals(obj);$0 + } + + // override object.GetHashCode + public override int GetHashCode() + { + // TODO: write your implementation of GetHashCode() here + throw new System.NotImplementedException(); + return base.GetHashCode(); + } + """, mutatingLspWorkspace); [Theory, CombinatorialData] public async Task TestSnippetCached(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void M() - { - if{|tab:|} - } -}"; + """ + class A + { + void M() + { + if{|tab:|} + } + } + """; var expectedSnippet = -@"if (${1:true}) - { - $0 - }"; + """ + if (${1:true}) + { + $0 + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var locationTyped = testLspServer.GetLocations("tab").Single(); diff --git a/src/LanguageServer/ProtocolUnitTests/MapCode/MapCodeTests.cs b/src/LanguageServer/ProtocolUnitTests/MapCode/MapCodeTests.cs index db39d420042c3..8cd32466ff723 100644 --- a/src/LanguageServer/ProtocolUnitTests/MapCode/MapCodeTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/MapCode/MapCodeTests.cs @@ -76,20 +76,6 @@ static void Main(string[] args) """; var codeBlock = @"Console.WriteLine(string.Join("", "", args));"; - - var expected = """ - namespace ConsoleApp1 - { - class Program - { - static void Main(string[] args) - { - Console.WriteLine(string.Join(", ", args)); - } - } - } - """; - await using var testLspServer = await CreateTestLspServerAsync(code, mutatingLspWorkspace, CreateClientCapabilities(supportDocumentChanges)); var ranges = testLspServer.GetLocations("range").ToArray(); var documentUri = ranges.Single().DocumentUri; @@ -135,6 +121,17 @@ static void Main(string[] args) var documentText = await document.GetTextAsync(); var actualText = ApplyTextEdits(edits, documentText); - Assert.Equal(expected, actualText); + Assert.Equal(""" + namespace ConsoleApp1 + { + class Program + { + static void Main(string[] args) + { + Console.WriteLine(string.Join(", ", args)); + } + } + } + """, actualText); } } diff --git a/src/LanguageServer/ProtocolUnitTests/Metadata/LspMetadataAsSourceWorkspaceTests.cs b/src/LanguageServer/ProtocolUnitTests/Metadata/LspMetadataAsSourceWorkspaceTests.cs index c7df1d9fa6554..31001ce1d526c 100644 --- a/src/LanguageServer/ProtocolUnitTests/Metadata/LspMetadataAsSourceWorkspaceTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Metadata/LspMetadataAsSourceWorkspaceTests.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -72,17 +71,6 @@ void M() } """; - var metadataSource = - """ - namespace System - { - public class Console - { - public static void WriteLine(string value) {} - } - } - """; - // Create a server with LSP misc file workspace and metadata service. await using var testLspServer = await CreateTestLspServerAsync(source, mutatingLspWorkspace, new InitializationOptions { ServerKind = WellKnownLspServerKinds.CSharpVisualBasicLspServer }); @@ -94,7 +82,15 @@ public static void WriteLine(string value) {} // Open the metadata file and verify it gets added to the metadata workspace. // We don't have the real metadata source, so just populate it with our fake metadata source. - await testLspServer.OpenDocumentAsync(definition.Single().DocumentUri, text: metadataSource).ConfigureAwait(false); + await testLspServer.OpenDocumentAsync(definition.Single().DocumentUri, text: """ + namespace System + { + public class Console + { + public static void WriteLine(string value) {} + } + } + """).ConfigureAwait(false); var workspaceForDocument = await GetWorkspaceForDocument(testLspServer, definition.Single().DocumentUri); Assert.Equal(WorkspaceKind.MetadataAsSource, workspaceForDocument.Kind); AssertMiscFileWorkspaceEmpty(testLspServer); diff --git a/src/LanguageServer/ProtocolUnitTests/Miscellaneous/LspMiscellaneousFilesWorkspaceTests.cs b/src/LanguageServer/ProtocolUnitTests/Miscellaneous/LspMiscellaneousFilesWorkspaceTests.cs index a84712ec05391..7319ac6a09ab2 100644 --- a/src/LanguageServer/ProtocolUnitTests/Miscellaneous/LspMiscellaneousFilesWorkspaceTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Miscellaneous/LspMiscellaneousFilesWorkspaceTests.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -23,13 +22,6 @@ public LspMiscellaneousFilesWorkspaceTests(ITestOutputHelper testOutputHelper) : [Theory, CombinatorialData] public async Task TestLooseFile_Opened(bool mutatingLspWorkspace) { - var source = -@"class A -{ - void M() - { - } -}"; // Create a server that supports LSP misc files and verify no misc files present. await using var testLspServer = await CreateTestLspServerAsync(string.Empty, mutatingLspWorkspace, new InitializationOptions { ServerKind = WellKnownLspServerKinds.CSharpVisualBasicLspServer }); @@ -37,7 +29,14 @@ void M() // Open an empty loose file and make a request to verify it gets added to the misc workspace. var looseFileUri = ProtocolConversions.CreateAbsoluteDocumentUri(@"C:\SomeFile.cs"); - await testLspServer.OpenDocumentAsync(looseFileUri, source).ConfigureAwait(false); + await testLspServer.OpenDocumentAsync(looseFileUri, """ + class A + { + void M() + { + } + } + """).ConfigureAwait(false); // Verify file is added to the misc file workspace. await AssertFileInMiscWorkspaceAsync(testLspServer, looseFileUri).ConfigureAwait(false); @@ -46,13 +45,6 @@ void M() [Theory, CombinatorialData] public async Task TestLooseFile_Changed(bool mutatingLspWorkspace) { - var source = -@"class A -{ - void M() - { - } -}"; // Create a server that supports LSP misc files and verify no misc files present. await using var testLspServer = await CreateTestLspServerAsync(string.Empty, mutatingLspWorkspace, new InitializationOptions { ServerKind = WellKnownLspServerKinds.CSharpVisualBasicLspServer }); @@ -73,7 +65,14 @@ void M() Assert.Empty(miscWorkspaceText.ToString()); // Make a text change to the loose file and verify requests appropriately reflect the changes. - await testLspServer.InsertTextAsync(looseFileUri, (0, 0, source)).ConfigureAwait(false); + await testLspServer.InsertTextAsync(looseFileUri, (0, 0, """ + class A + { + void M() + { + } + } + """)).ConfigureAwait(false); var caret = new LSP.Location { Range = new() { Start = new(0, 6), End = new(0, 7) }, DocumentUri = looseFileUri }; var hover = await RunGetHoverAsync(testLspServer, caret).ConfigureAwait(false); Assert.Contains("class A", hover.Contents.Fourth.Value); @@ -87,13 +86,6 @@ void M() [Theory, CombinatorialData] public async Task TestLooseFile_Closed(bool mutatingLspWorkspace) { - var source = -@"class A -{ - void M() - { - } -}"; // Create a server that supports LSP misc files and verify no misc files present. await using var testLspServer = await CreateTestLspServerAsync(string.Empty, mutatingLspWorkspace, new InitializationOptions { ServerKind = WellKnownLspServerKinds.CSharpVisualBasicLspServer }); @@ -101,7 +93,14 @@ void M() // Open an empty loose file and make a request to verify it gets added to the misc workspace. var looseFileUri = ProtocolConversions.CreateAbsoluteDocumentUri(@"C:\SomeFile.cs"); - await testLspServer.OpenDocumentAsync(looseFileUri, source).ConfigureAwait(false); + await testLspServer.OpenDocumentAsync(looseFileUri, """ + class A + { + void M() + { + } + } + """).ConfigureAwait(false); await AssertFileInMiscWorkspaceAsync(testLspServer, looseFileUri).ConfigureAwait(false); // Verify the loose file is removed from the misc workspace on close. @@ -113,12 +112,14 @@ void M() public async Task TestFileInRegisteredWorkspace_Opened(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void M() - { - } -}"; + """ + class A + { + void M() + { + } + } + """; // Create a server that supports LSP misc files and verify no misc files present. await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, new InitializationOptions { ServerKind = WellKnownLspServerKinds.CSharpVisualBasicLspServer }); @@ -134,12 +135,14 @@ void M() public async Task TestLooseFile_MovedToRegisteredWorkspace(bool mutatingLspWorkspace) { var source = -@"class A -{ - void M() - { - } -}"; + """ + class A + { + void M() + { + } + } + """; // Create a server that supports LSP misc files and verify no misc files present. await using var testLspServer = await CreateTestLspServerAsync(string.Empty, mutatingLspWorkspace, new InitializationOptions { ServerKind = WellKnownLspServerKinds.CSharpVisualBasicLspServer }); @@ -184,7 +187,6 @@ void M() [Theory, CombinatorialData] public async Task TestLooseFile_RazorFile(bool mutatingLspWorkspace) { - var source = "
"; // Create a server that supports LSP misc files and verify no misc files present. await using var testLspServer = await CreateTestLspServerAsync(string.Empty, mutatingLspWorkspace, new InitializationOptions { ServerKind = WellKnownLspServerKinds.CSharpVisualBasicLspServer }); @@ -193,7 +195,7 @@ public async Task TestLooseFile_RazorFile(bool mutatingLspWorkspace) // Open an empty loose file and make a request to verify it gets added to the misc workspace. var looseFileUri = ProtocolConversions.CreateAbsoluteDocumentUri(@"C:\SomeFile.razor"); - await testLspServer.OpenDocumentAsync(looseFileUri, source).ConfigureAwait(false); + await testLspServer.OpenDocumentAsync(looseFileUri, "
").ConfigureAwait(false); // Trigger a request and assert we got a file in the misc workspace. await AssertFileInMiscWorkspaceAsync(testLspServer, looseFileUri).ConfigureAwait(false); @@ -212,13 +214,6 @@ public async Task TestLooseFile_RazorFile(bool mutatingLspWorkspace) [Theory, CombinatorialData] public async Task TestLooseFile_RequestedTwiceAndClosed(bool mutatingLspWorkspace) { - var source = -@"class A -{ - void M() - { - } -}"; // Create a server that supports LSP misc files and verify no misc files present. await using var testLspServer = await CreateTestLspServerAsync(string.Empty, mutatingLspWorkspace, new InitializationOptions { ServerKind = WellKnownLspServerKinds.CSharpVisualBasicLspServer }); @@ -226,7 +221,14 @@ void M() // Open an empty loose file and make a request to verify it gets added to the misc workspace. var looseFileUri = ProtocolConversions.CreateAbsoluteDocumentUri(@"C:\SomeFile.cs"); - await testLspServer.OpenDocumentAsync(looseFileUri, source).ConfigureAwait(false); + await testLspServer.OpenDocumentAsync(looseFileUri, """ + class A + { + void M() + { + } + } + """).ConfigureAwait(false); // Trigger a request and assert we got a file in the misc workspace. await AssertFileInMiscWorkspaceAsync(testLspServer, looseFileUri).ConfigureAwait(false); @@ -241,15 +243,6 @@ void M() [Theory, CombinatorialData] public async Task TestLooseFile_OpenedWithLanguageId(bool mutatingLspWorkspace) { - var source = - """ - class A - { - void M() - { - } - } - """; // Create a server that supports LSP misc files and verify no misc files present. await using var testLspServer = await CreateTestLspServerAsync(string.Empty, mutatingLspWorkspace, new InitializationOptions { ServerKind = WellKnownLspServerKinds.CSharpVisualBasicLspServer }); @@ -259,7 +252,14 @@ void M() var looseFileUri = new DocumentUri("untitled:untitledFile"); - await testLspServer.OpenDocumentAsync(looseFileUri, source, languageId: "csharp").ConfigureAwait(false); + await testLspServer.OpenDocumentAsync(looseFileUri, """ + class A + { + void M() + { + } + } + """, languageId: "csharp").ConfigureAwait(false); // Verify file is added to the misc file workspace. await AssertFileInMiscWorkspaceAsync(testLspServer, looseFileUri).ConfigureAwait(false); @@ -271,16 +271,6 @@ void M() [Theory, CombinatorialData] public async Task TestLooseFile_OpenedWithLanguageIdWithSubsequentRequest(bool mutatingLspWorkspace) { - var source = - """ - class A - { - void M() - { - A a = new A(); - } - } - """; // Create a server that supports LSP misc files and verify no misc files present. await using var testLspServer = await CreateTestLspServerAsync(string.Empty, mutatingLspWorkspace, new InitializationOptions { ServerKind = WellKnownLspServerKinds.CSharpVisualBasicLspServer }); @@ -290,7 +280,15 @@ void M() var looseFileUri = new DocumentUri("untitled:untitledFile"); - await testLspServer.OpenDocumentAsync(looseFileUri, source, languageId: "csharp").ConfigureAwait(false); + await testLspServer.OpenDocumentAsync(looseFileUri, """ + class A + { + void M() + { + A a = new A(); + } + } + """, languageId: "csharp").ConfigureAwait(false); // Make an immediate followup request as soon as we queue the didOpen. // This should succeed and use the language from the didOpen. var result = await testLspServer.ExecuteRequestAsync(LSP.Methods.TextDocumentDefinitionName, diff --git a/src/LanguageServer/ProtocolUnitTests/OnAutoInsert/OnAutoInsertTests.cs b/src/LanguageServer/ProtocolUnitTests/OnAutoInsert/OnAutoInsertTests.cs index f46df97f98259..57d6382135971 100644 --- a/src/LanguageServer/ProtocolUnitTests/OnAutoInsert/OnAutoInsertTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/OnAutoInsert/OnAutoInsertTests.cs @@ -22,359 +22,313 @@ public OnAutoInsertTests(ITestOutputHelper testOutputHelper) : base(testOutputHe } [Theory, CombinatorialData] - public async Task OnAutoInsert_CommentCharacter(bool mutatingLspWorkspace) - { - var markup = -@"class A -{ - ///{|type:|} - void M() - { - } -}"; - var expected = -@"class A -{ - /// -/// $0 -/// - void M() - { - } -}"; - await VerifyMarkupAndExpected("/", markup, expected, mutatingLspWorkspace); - } + public Task OnAutoInsert_CommentCharacter(bool mutatingLspWorkspace) + => VerifyMarkupAndExpected("/", """ + class A + { + ///{|type:|} + void M() + { + } + } + """, """ + class A + { + /// + /// $0 + /// + void M() + { + } + } + """, mutatingLspWorkspace); [Theory, CombinatorialData] - public async Task OnAutoInsert_CommentCharacter_WithComment(bool mutatingLspWorkspace) - { - var markup = -@"class A -{ - ///{|type:|} This is an existing comment - void M() - { - } -}"; - var expected = -@"class A -{ - /// -/// $0This is an existing comment -/// - void M() - { - } -}"; - await VerifyMarkupAndExpected("/", markup, expected, mutatingLspWorkspace); - } + public Task OnAutoInsert_CommentCharacter_WithComment(bool mutatingLspWorkspace) + => VerifyMarkupAndExpected("/", """ + class A + { + ///{|type:|} This is an existing comment + void M() + { + } + } + """, """ + class A + { + /// + /// $0This is an existing comment + /// + void M() + { + } + } + """, mutatingLspWorkspace); [Theory, CombinatorialData] - public async Task OnAutoInsert_CommentCharacter_WithComment_NoSpace(bool mutatingLspWorkspace) - { - var markup = -@"class A -{ - ///{|type:|}This is an existing comment - void M() - { - } -}"; - var expected = -@"class A -{ - /// -/// $0This is an existing comment -/// - void M() - { - } -}"; - await VerifyMarkupAndExpected("/", markup, expected, mutatingLspWorkspace); - } + public Task OnAutoInsert_CommentCharacter_WithComment_NoSpace(bool mutatingLspWorkspace) + => VerifyMarkupAndExpected("/", """ + class A + { + ///{|type:|}This is an existing comment + void M() + { + } + } + """, """ + class A + { + /// + /// $0This is an existing comment + /// + void M() + { + } + } + """, mutatingLspWorkspace); [Theory, CombinatorialData] - public async Task OnAutoInsert_CommentCharacter_VB(bool mutatingLspWorkspace) - { - var markup = -@"Class A - '''{|type:|} - Sub M() - End Sub -End Class"; - var expected = -@"Class A - ''' -''' $0 -''' - Sub M() - End Sub -End Class"; - await VerifyMarkupAndExpected("'", markup, expected, mutatingLspWorkspace, languageName: LanguageNames.VisualBasic); - } + public Task OnAutoInsert_CommentCharacter_VB(bool mutatingLspWorkspace) + => VerifyMarkupAndExpected("'", """ + Class A + '''{|type:|} + Sub M() + End Sub + End Class + """, """ + Class A + ''' + ''' $0 + ''' + Sub M() + End Sub + End Class + """, mutatingLspWorkspace, languageName: LanguageNames.VisualBasic); [Theory, CombinatorialData] - public async Task OnAutoInsert_ParametersAndReturns(bool mutatingLspWorkspace) - { - var markup = -@"class A -{ - ///{|type:|} - string M(int foo, bool bar) - { - } -}"; - var expected = -@"class A -{ - /// -/// $0 -/// -/// -/// -/// - string M(int foo, bool bar) - { - } -}"; - await VerifyMarkupAndExpected("/", markup, expected, mutatingLspWorkspace); - } + public Task OnAutoInsert_ParametersAndReturns(bool mutatingLspWorkspace) + => VerifyMarkupAndExpected("/", """ + class A + { + ///{|type:|} + string M(int foo, bool bar) + { + } + } + """, """ + class A + { + /// + /// $0 + /// + /// + /// + /// + string M(int foo, bool bar) + { + } + } + """, mutatingLspWorkspace); [Theory, CombinatorialData] - public async Task OnAutoInsert_CommentCharacterInsideMethod_Ignored(bool mutatingLspWorkspace) - { - var markup = -@"class A -{ - void M() - { - ///{|type:|} - } -}"; - await VerifyNoResult("/", markup, mutatingLspWorkspace); - } + public Task OnAutoInsert_CommentCharacterInsideMethod_Ignored(bool mutatingLspWorkspace) + => VerifyNoResult("/", """ + class A + { + void M() + { + ///{|type:|} + } + } + """, mutatingLspWorkspace); [Theory, CombinatorialData] - public async Task OnAutoInsert_VisualBasicCommentCharacter_Ignored(bool mutatingLspWorkspace) - { - var markup = -@"class A -{ - '''{|type:|} - void M() - { - } -}"; - await VerifyNoResult("'", markup, mutatingLspWorkspace); - } + public Task OnAutoInsert_VisualBasicCommentCharacter_Ignored(bool mutatingLspWorkspace) + => VerifyNoResult("'", """ + class A + { + '''{|type:|} + void M() + { + } + } + """, mutatingLspWorkspace); [Theory, CombinatorialData] - public async Task OnAutoInsert_EnterKey(bool mutatingLspWorkspace) - { - var markup = -@"class A -{ - /// - /// Foo - /// -{|type:|} - void M() - { - } -}"; - var expected = -@"class A -{ - /// - /// Foo - /// - /// $0 - void M() - { - } -}"; - await VerifyMarkupAndExpected("\n", markup, expected, mutatingLspWorkspace); - } + public Task OnAutoInsert_EnterKey(bool mutatingLspWorkspace) + => VerifyMarkupAndExpected("\n", """ + class A + { + /// + /// Foo + /// + {|type:|} + void M() + { + } + } + """, """ + class A + { + /// + /// Foo + /// + /// $0 + void M() + { + } + } + """, mutatingLspWorkspace); [Theory, CombinatorialData] - public async Task OnAutoInsert_EnterKey2(bool mutatingLspWorkspace) - { - var markup = -@"class A -{ - /// - /// Foo -{|type:|} - /// - void M() - { - } -}"; - var expected = -@"class A -{ - /// - /// Foo - /// $0 - /// - void M() - { - } -}"; - await VerifyMarkupAndExpected("\n", markup, expected, mutatingLspWorkspace); - } + public Task OnAutoInsert_EnterKey2(bool mutatingLspWorkspace) + => VerifyMarkupAndExpected("\n", """ + class A + { + /// + /// Foo + {|type:|} + /// + void M() + { + } + } + """, """ + class A + { + /// + /// Foo + /// $0 + /// + void M() + { + } + } + """, mutatingLspWorkspace); [Theory, CombinatorialData] - public async Task OnAutoInsert_EnterKey3(bool mutatingLspWorkspace) - { - var markup = -@"class A -{ - /// -{|type:|} - string M(int foo, bool bar) - { - } -}"; - var expected = -@"class A -{ - /// - /// $0 - /// - /// - /// - /// - string M(int foo, bool bar) - { - } -}"; - await VerifyMarkupAndExpected("\n", markup, expected, mutatingLspWorkspace); - } + public Task OnAutoInsert_EnterKey3(bool mutatingLspWorkspace) + => VerifyMarkupAndExpected("\n", """ + class A + { + /// + {|type:|} + string M(int foo, bool bar) + { + } + } + """, """ + class A + { + /// + /// $0 + /// + /// + /// + /// + string M(int foo, bool bar) + { + } + } + """, mutatingLspWorkspace); [Theory, CombinatorialData] - public async Task OnAutoInsert_BraceFormatting(bool mutatingLspWorkspace) - { - // The test starts with the closing brace already on a new line. - // In LSP, hitting enter will first trigger a didChange event for the new line character - // (bringing the server text to the form below) and then trigger OnAutoInsert - // for the new line character. - var markup = -@"class A -{ - void M() {{|type:|} - } -}"; - var expected = -@"class A -{ - void M() - { - $0 - } -}"; - await VerifyMarkupAndExpected("\n", markup, expected, mutatingLspWorkspace, serverKind: WellKnownLspServerKinds.RazorLspServer); - } + public Task OnAutoInsert_BraceFormatting(bool mutatingLspWorkspace) + => VerifyMarkupAndExpected("\n", """ + class A + { + void M() {{|type:|} + } + } + """, """ + class A + { + void M() + { + $0 + } + } + """, mutatingLspWorkspace, serverKind: WellKnownLspServerKinds.RazorLspServer); [Theory, CombinatorialData] - public async Task OnAutoInsert_BraceFormattingWithTabs(bool mutatingLspWorkspace) - { - var markup = -@"class A -{ - void M() {{|type:|} - } -}"; - // Use show whitespace when modifying the expected value. - // The method braces and caret location should be indented with tabs. - var expected = -@"class A -{ - void M() - { - $0 - } -}"; - await VerifyMarkupAndExpected("\n", markup, expected, mutatingLspWorkspace, insertSpaces: false, tabSize: 4, serverKind: WellKnownLspServerKinds.RazorLspServer); - } + public Task OnAutoInsert_BraceFormattingWithTabs(bool mutatingLspWorkspace) + => VerifyMarkupAndExpected("\n", """ + class A + { + void M() {{|type:|} + } + } + """, """ + class A + { + void M() + { + $0 + } + } + """, mutatingLspWorkspace, insertSpaces: false, tabSize: 4, serverKind: WellKnownLspServerKinds.RazorLspServer); [Theory, CombinatorialData] - public async Task OnAutoInsert_BraceFormattingInsideMethod(bool mutatingLspWorkspace) - { - var markup = -@"class A -{ - void M() - { - if (true) {{|type:|} - } - } -}"; - var expected = -@"class A -{ - void M() - { - if (true) - { - $0 - } - } -}"; - await VerifyMarkupAndExpected("\n", markup, expected, mutatingLspWorkspace, serverKind: WellKnownLspServerKinds.RazorLspServer); - } + public Task OnAutoInsert_BraceFormattingInsideMethod(bool mutatingLspWorkspace) + => VerifyMarkupAndExpected("\n", """ + class A + { + void M() + { + if (true) {{|type:|} + } + } + } + """, """ + class A + { + void M() + { + if (true) + { + $0 + } + } + } + """, mutatingLspWorkspace, serverKind: WellKnownLspServerKinds.RazorLspServer); [Theory, CombinatorialData] - public async Task OnAutoInsert_BraceFormattingNoResultInInterpolation(bool mutatingLspWorkspace) - { - var markup = -@"class A -{ - void M() - { - var s = $""Hello {{|type:|} - } -}"; - await VerifyNoResult("\n", markup, mutatingLspWorkspace); - } + public Task OnAutoInsert_BraceFormattingNoResultInInterpolation(bool mutatingLspWorkspace) + => VerifyNoResult("\n", """ + class A + { + void M() + { + var s = $"Hello {{|type:|} + } + } + """, mutatingLspWorkspace); [Theory, CombinatorialData, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1260219")] - public async Task OnAutoInsert_BraceFormattingDoesNotInsertExtraEmptyLines(bool mutatingLspWorkspace) - { - // The test starts with the closing brace already on a new line. - // In LSP, hitting enter will first trigger a didChange event for the new line character - // (bringing the server text to the form below) and then trigger OnAutoInsert - // for the new line character. - var markup = -@"class A -{ - void M() - { - - {|type:|} - } -}"; - await VerifyNoResult("\n", markup, mutatingLspWorkspace); - } + public Task OnAutoInsert_BraceFormattingDoesNotInsertExtraEmptyLines(bool mutatingLspWorkspace) + => VerifyNoResult("\n", """ + class A + { + void M() + { + + {|type:|} + } + } + """, mutatingLspWorkspace); [Theory, CombinatorialData, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1260219")] - public async Task OnAutoInsert_BraceFormattingDoesNotMoveCaretOnEnterInsideBraces(bool mutatingLspWorkspace) - { - // The test starts with the closing brace already on a new line. - // In LSP, hitting enter will first trigger a didChange event for the new line character - // (bringing the server text to the form below) and then trigger OnAutoInsert - // for the new line character. - var markup = -@"class A -{ - void M() - {{|type:|} + public Task OnAutoInsert_BraceFormattingDoesNotMoveCaretOnEnterInsideBraces(bool mutatingLspWorkspace) + => VerifyNoResult("\n", """ + class A + { + void M() + {{|type:|} - } -}"; - await VerifyNoResult("\n", markup, mutatingLspWorkspace); - } + } + } + """, mutatingLspWorkspace); private async Task VerifyMarkupAndExpected( string characterTyped, diff --git a/src/LanguageServer/ProtocolUnitTests/Ordering/RequestOrderingTests.cs b/src/LanguageServer/ProtocolUnitTests/Ordering/RequestOrderingTests.cs index 541af789c375e..0eebd77b0a512 100644 --- a/src/LanguageServer/ProtocolUnitTests/Ordering/RequestOrderingTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Ordering/RequestOrderingTests.cs @@ -10,7 +10,6 @@ using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.LanguageServer.Protocol; using Roslyn.Test.Utilities; -using Roslyn.Utilities; using Xunit; using Xunit.Abstractions; using LSP = Roslyn.LanguageServer.Protocol; diff --git a/src/LanguageServer/ProtocolUnitTests/ProjectContext/GetTextDocumentWithContextHandlerTests.cs b/src/LanguageServer/ProtocolUnitTests/ProjectContext/GetTextDocumentWithContextHandlerTests.cs index 56479be597e6e..c0177488c4230 100644 --- a/src/LanguageServer/ProtocolUnitTests/ProjectContext/GetTextDocumentWithContextHandlerTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/ProjectContext/GetTextDocumentWithContextHandlerTests.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -24,11 +23,13 @@ public GetTextDocumentWithContextHandlerTests(ITestOutputHelper testOutputHelper public async Task SingleDocumentReturnsSingleContext(bool mutatingLspWorkspace) { var workspaceXml = -@" - - {|caret:|} - -"; + """ + + + {|caret:|} + + + """; await using var testLspServer = await CreateXmlTestLspServerAsync(workspaceXml, mutatingLspWorkspace); var documentUri = testLspServer.GetLocations("caret").Single().DocumentUri; @@ -47,14 +48,16 @@ public async Task SingleDocumentReturnsSingleContext(bool mutatingLspWorkspace) public async Task MultipleDocumentsReturnsMultipleContexts(bool mutatingLspWorkspace) { var workspaceXml = -@" - - {|caret:|} - - - {|caret:|} - -"; + """ + + + {|caret:|} + + + {|caret:|} + + + """; await using var testLspServer = await CreateXmlTestLspServerAsync(workspaceXml, mutatingLspWorkspace); var documentUri = testLspServer.GetLocations("caret").Single().DocumentUri; @@ -71,14 +74,16 @@ public async Task MultipleDocumentsReturnsMultipleContexts(bool mutatingLspWorks public async Task SwitchingContextsChangesDefaultContext(bool mutatingLspWorkspace) { var workspaceXml = -@" - - {|caret:|} - - - - -"; + """ + + + {|caret:|} + + + + + + """; await using var testLspServer = await CreateXmlTestLspServerAsync(workspaceXml, mutatingLspWorkspace); diff --git a/src/LanguageServer/ProtocolUnitTests/ProtocolConversionsTests.cs b/src/LanguageServer/ProtocolUnitTests/ProtocolConversionsTests.cs index 5c3f6c389e87b..3429e371b80e3 100644 --- a/src/LanguageServer/ProtocolUnitTests/ProtocolConversionsTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/ProtocolConversionsTests.cs @@ -229,11 +229,13 @@ public void RangeToTextSpanLineEndOfDocument() public void RangeToTextSpanLineEndOfDocumentWithEndOfLineChars() { var markup = -@"void M() -{ - var x = 5; -} -"; // add additional end line + """ + void M() + { + var x = 5; + } + + """; // add additional end line var sourceText = SourceText.From(markup); @@ -277,10 +279,12 @@ private static string GetTestMarkup() */ var markup = -@"void M() -{ - var x = 5; -}"; + """ + void M() + { + var x = 5; + } + """; return markup; } @@ -311,21 +315,20 @@ void M() [Theory, CombinatorialData] public async Task ProjectToProjectContext_MiscellaneousFilesWorkspace(bool mutatingLspWorkspace) { - var source = """ - class A - { - void M() - { - } - } - """; // Create a server that supports LSP misc files. await using var testLspServer = await CreateTestLspServerAsync(string.Empty, mutatingLspWorkspace, new InitializationOptions { ServerKind = WellKnownLspServerKinds.CSharpVisualBasicLspServer }); // Open an empty loose file. var looseFileUri = ProtocolConversions.CreateAbsoluteDocumentUri(@"C:\SomeFile.cs"); - await testLspServer.OpenDocumentAsync(looseFileUri, source).ConfigureAwait(false); + await testLspServer.OpenDocumentAsync(looseFileUri, """ + class A + { + void M() + { + } + } + """).ConfigureAwait(false); var document = await GetTextDocumentAsync(testLspServer, looseFileUri); Assert.NotNull(document); diff --git a/src/LanguageServer/ProtocolUnitTests/References/FindAllReferencesHandlerFeaturesTests.cs b/src/LanguageServer/ProtocolUnitTests/References/FindAllReferencesHandlerFeaturesTests.cs index d57d43540f495..20b8eaf3cbbb8 100644 --- a/src/LanguageServer/ProtocolUnitTests/References/FindAllReferencesHandlerFeaturesTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/References/FindAllReferencesHandlerFeaturesTests.cs @@ -11,6 +11,7 @@ using LSP = Roslyn.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.References; + public sealed class FindAllReferencesHandlerFeaturesTests(ITestOutputHelper? testOutputHelper) : AbstractLanguageServerProtocolTests(testOutputHelper) { diff --git a/src/LanguageServer/ProtocolUnitTests/References/FindAllReferencesHandlerTests.cs b/src/LanguageServer/ProtocolUnitTests/References/FindAllReferencesHandlerTests.cs index 46891215ce8f5..ac634aebb0e1c 100644 --- a/src/LanguageServer/ProtocolUnitTests/References/FindAllReferencesHandlerTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/References/FindAllReferencesHandlerTests.cs @@ -27,22 +27,24 @@ public sealed class FindAllReferencesHandlerTests(ITestOutputHelper testOutputHe public async Task TestFindAllReferencesAsync(bool mutatingLspWorkspace) { var markup = -@"class A -{ - public int {|reference:someInt|} = 1; - void M() - { - var i = {|reference:someInt|} + 1; - } -} -class B -{ - int someInt = A.{|reference:someInt|} + 1; - void M2() - { - var j = someInt + A.{|caret:|}{|reference:someInt|}; - } -}"; + """ + class A + { + public int {|reference:someInt|} = 1; + void M() + { + var i = {|reference:someInt|} + 1; + } + } + class B + { + int someInt = A.{|reference:someInt|} + 1; + void M2() + { + var j = someInt + A.{|caret:|}{|reference:someInt|}; + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, CapabilitiesWithVSExtensions); var results = await RunFindAllReferencesAsync(testLspServer, testLspServer.GetLocations("caret").First()); @@ -61,22 +63,24 @@ void M2() public async Task TestFindAllReferencesAsync_Streaming(bool mutatingLspWorkspace) { var markup = -@"class A -{ - public static int {|reference:someInt|} = 1; - void M() - { - var i = {|reference:someInt|} + 1; - } -} -class B -{ - int someInt = A.{|reference:someInt|} + 1; - void M2() - { - var j = someInt + A.{|caret:|}{|reference:someInt|}; - } -}"; + """ + class A + { + public static int {|reference:someInt|} = 1; + void M() + { + var i = {|reference:someInt|} + 1; + } + } + class B + { + int someInt = A.{|reference:someInt|} + 1; + void M2() + { + var j = someInt + A.{|caret:|}{|reference:someInt|}; + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, CapabilitiesWithVSExtensions); using var progress = BufferedProgress.Create(null); @@ -101,22 +105,24 @@ void M2() public async Task TestFindAllReferencesAsync_Class(bool mutatingLspWorkspace) { var markup = -@"class {|reference:A|} -{ - public static int someInt = 1; - void M() - { - var i = someInt + 1; - } -} -class B -{ - int someInt = {|reference:A|}.someInt + 1; - void M2() - { - var j = someInt + {|caret:|}{|reference:A|}.someInt; - } -}"; + """ + class {|reference:A|} + { + public static int someInt = 1; + void M() + { + var i = someInt + 1; + } + } + class B + { + int someInt = {|reference:A|}.someInt + 1; + void M2() + { + var j = someInt + {|caret:|}{|reference:A|}.someInt; + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, CapabilitiesWithVSExtensions); var results = await RunFindAllReferencesAsync(testLspServer, testLspServer.GetLocations("caret").First()); @@ -140,22 +146,26 @@ void M2() public async Task TestFindAllReferencesAsync_MultipleDocuments(bool mutatingLspWorkspace) { var markups = new string[] { -@"class A -{ - public static int {|reference:someInt|} = 1; - void M() - { - var i = {|reference:someInt|} + 1; - } -}", -@"class B -{ - int someInt = A.{|reference:someInt|} + 1; - void M2() - { - var j = someInt + A.{|caret:|}{|reference:someInt|}; - } -}" + """ + class A + { + public static int {|reference:someInt|} = 1; + void M() + { + var i = {|reference:someInt|} + 1; + } + } + """, + """ + class B + { + int someInt = A.{|reference:someInt|} + 1; + void M2() + { + var j = someInt + A.{|caret:|}{|reference:someInt|}; + } + } + """ }; await using var testLspServer = await CreateTestLspServerAsync(markups, mutatingLspWorkspace, new InitializationOptions { ClientCapabilities = CapabilitiesWithVSExtensions }); @@ -176,10 +186,12 @@ void M2() public async Task TestFindAllReferencesAsync_InvalidLocation(bool mutatingLspWorkspace) { var markup = -@"class A -{ - {|caret:|} -}"; + """ + class A + { + {|caret:|} + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, CapabilitiesWithVSExtensions); var results = await RunFindAllReferencesAsync(testLspServer, testLspServer.GetLocations("caret").First()); @@ -190,15 +202,17 @@ public async Task TestFindAllReferencesAsync_InvalidLocation(bool mutatingLspWor public async Task TestFindAllReferencesMetadataDefinitionAsync(bool mutatingLspWorkspace) { var markup = -@"using System; + """ + using System; -class A -{ - void M() - { - Console.{|caret:|}{|reference:WriteLine|}(""text""); - } -}"; + class A + { + void M() + { + Console.{|caret:|}{|reference:WriteLine|}("text"); + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, CapabilitiesWithVSExtensions); var results = await RunFindAllReferencesAsync(testLspServer, testLspServer.GetLocations("caret").First()); @@ -210,17 +224,18 @@ void M() public async Task TestFindAllReferencesAsync_Namespace(bool mutatingLspWorkspace) { var markup = -@"namespace {|caret:|}{|reference:N|} -{ - class C - { - void M() - { - var x = new {|reference:N|}.C(); - } - } -} -"; + """ + namespace {|caret:|}{|reference:N|} + { + class C + { + void M() + { + var x = new {|reference:N|}.C(); + } + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, CapabilitiesWithVSExtensions); var results = await RunFindAllReferencesAsync(testLspServer, testLspServer.GetLocations("caret").First()); @@ -236,18 +251,19 @@ void M() public async Task TestFindAllReferencesAsync_Highlights(bool mutatingLspWorkspace) { var markup = -@"using System; + """ + using System; -class C -{ - void M() - { - var {|caret:|}{|reference:x|} = 1; - Console.WriteLine({|reference:x|}); - {|reference:x|} = 2; - } -} -"; + class C + { + void M() + { + var {|caret:|}{|reference:x|} = 1; + Console.WriteLine({|reference:x|}); + {|reference:x|} = 2; + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, CapabilitiesWithVSExtensions); var results = await RunFindAllReferencesAsync(testLspServer, testLspServer.GetLocations("caret").First()); @@ -258,8 +274,9 @@ void M() public async Task TestFindAllReferencesAsync_StaticClassification(bool mutatingLspWorkspace) { var markup = -@"static class {|caret:|}{|reference:C|} { } -"; + """ + static class {|caret:|}{|reference:C|} { } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace, CapabilitiesWithVSExtensions); var results = await RunFindAllReferencesAsync(testLspServer, testLspServer.GetLocations("caret").First()); diff --git a/src/LanguageServer/ProtocolUnitTests/References/FindImplementationsTests.cs b/src/LanguageServer/ProtocolUnitTests/References/FindImplementationsTests.cs index 3409f41ed31ee..e72b7d5afa3c7 100644 --- a/src/LanguageServer/ProtocolUnitTests/References/FindImplementationsTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/References/FindImplementationsTests.cs @@ -24,16 +24,18 @@ public FindImplementationsTests(ITestOutputHelper testOutputHelper) : base(testO public async Task TestFindImplementationAsync(bool mutatingLspWorkspace) { var markup = -@"interface IA -{ - void {|caret:|}M(); -} -class A : IA -{ - void IA.{|implementation:M|}() - { - } -}"; + """ + interface IA + { + void {|caret:|}M(); + } + class A : IA + { + void IA.{|implementation:M|}() + { + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var results = await RunFindImplementationAsync(testLspServer, testLspServer.GetLocations("caret").Single()); @@ -45,22 +47,26 @@ public async Task TestFindImplementationAsync_DifferentDocument(bool mutatingLsp { var markups = new string[] { -@"namespace One -{ - interface IA - { - void {|caret:|}M(); - } -}", -@"namespace One -{ - class A : IA - { - void IA.{|implementation:M|}() - { - } - } -}" + """ + namespace One + { + interface IA + { + void {|caret:|}M(); + } + } + """, + """ + namespace One + { + class A : IA + { + void IA.{|implementation:M|}() + { + } + } + } + """ }; await using var testLspServer = await CreateTestLspServerAsync(markups, mutatingLspWorkspace); @@ -72,20 +78,20 @@ class A : IA [Theory, CombinatorialData] public async Task TestFindImplementationAsync_MappedFile(bool mutatingLspWorkspace) { - var markup = -@"interface IA -{ - void M(); -} -class A : IA -{ - void IA.M() - { - } -}"; await using var testLspServer = await CreateTestLspServerAsync(string.Empty, mutatingLspWorkspace); - AddMappedDocument(testLspServer.TestWorkspace, markup); + AddMappedDocument(testLspServer.TestWorkspace, """ + interface IA + { + void M(); + } + class A : IA + { + void IA.M() + { + } + } + """); var position = new LSP.Position { Line = 2, Character = 9 }; var results = await RunFindImplementationAsync(testLspServer, new LSP.Location @@ -100,13 +106,15 @@ void IA.M() public async Task TestFindImplementationAsync_InvalidLocation(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void M() - { - {|caret:|} - } -}"; + """ + class A + { + void M() + { + {|caret:|} + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var results = await RunFindImplementationAsync(testLspServer, testLspServer.GetLocations("caret").Single()); @@ -117,11 +125,13 @@ void M() public async Task TestFindImplementationAsync_MultipleLocations(bool mutatingLspWorkspace) { var markup = -@"class {|caret:|}A { } + """ + class {|caret:|}A { } -class {|implementation:B|} : A { } + class {|implementation:B|} : A { } -class {|implementation:C|} : A { }"; + class {|implementation:C|} : A { } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var results = await RunFindImplementationAsync(testLspServer, testLspServer.GetLocations("caret").Single()); @@ -131,16 +141,17 @@ class {|implementation:C|} : A { }"; [Theory, CombinatorialData] public async Task TestFindImplementationAsync_NoMetadataResults(bool mutatingLspWorkspace) { - var markup = @" -using System; -class C : IDisposable -{ - public void {|implementation:Dispose|}() - { - IDisposable d; - d.{|caret:|}Dispose(); - } -}"; + var markup = """ + using System; + class C : IDisposable + { + public void {|implementation:Dispose|}() + { + IDisposable d; + d.{|caret:|}Dispose(); + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var results = await RunFindImplementationAsync(testLspServer, testLspServer.GetLocations("caret").Single()); diff --git a/src/LanguageServer/ProtocolUnitTests/RelatedDocuments/RelatedDocumentsTests.cs b/src/LanguageServer/ProtocolUnitTests/RelatedDocuments/RelatedDocumentsTests.cs index a45a552c66a5e..bab8d67a22b6c 100644 --- a/src/LanguageServer/ProtocolUnitTests/RelatedDocuments/RelatedDocumentsTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/RelatedDocuments/RelatedDocumentsTests.cs @@ -189,18 +189,15 @@ class A } } """; - var generated = - """ + await using var testLspServer = await CreateTestLspServerAsync(source, mutatingLspWorkspace); + await AddGeneratorAsync(new SingleFileTestGenerator(""" namespace M { class B { } } - """; - - await using var testLspServer = await CreateTestLspServerAsync(source, mutatingLspWorkspace); - await AddGeneratorAsync(new SingleFileTestGenerator(generated), testLspServer.TestWorkspace); + """), testLspServer.TestWorkspace); var project = testLspServer.TestWorkspace.CurrentSolution.Projects.Single(); var results = await RunGetRelatedDocumentsAsync( diff --git a/src/LanguageServer/ProtocolUnitTests/Rename/PrepareRenameTests.cs b/src/LanguageServer/ProtocolUnitTests/Rename/PrepareRenameTests.cs index 8c13aabe0c85a..6ef1e4b9acfe5 100644 --- a/src/LanguageServer/ProtocolUnitTests/Rename/PrepareRenameTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Rename/PrepareRenameTests.cs @@ -18,12 +18,14 @@ public sealed class PrepareRenameTests(ITestOutputHelper testOutputHelper) : Abs public async Task TestPrepareRenameValidLocationAsync(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void {|caret:|}{|range:M|}() - { - } -}"; + """ + class A + { + void {|caret:|}{|range:M|}() + { + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var renameLocation = testLspServer.GetLocations("caret").First(); @@ -35,12 +37,14 @@ public async Task TestPrepareRenameValidLocationAsync(bool mutatingLspWorkspace) public async Task TestPrepareRenameAfterMethodNameAsync(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void {|range:M|}{|caret:|}() - { - } -}"; + """ + class A + { + void {|range:M|}{|caret:|}() + { + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var renameLocation = testLspServer.GetLocations("caret").First(); @@ -52,13 +56,15 @@ public async Task TestPrepareRenameAfterMethodNameAsync(bool mutatingLspWorkspac public async Task TestPrepareRenameWithAtSymbolAsync(bool mutatingLspWorkspace) { var markup = -@"class A -{ - void M() - { - var {|caret:|}{|range:@foo|} = 1; - } -}"; + """ + class A + { + void M() + { + var {|caret:|}{|range:@foo|} = 1; + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var renameLocation = testLspServer.GetLocations("caret").First(); @@ -70,13 +76,15 @@ void M() public async Task TestPrepareRenameInvalidLocationAsync(bool mutatingLspWorkspace) { var markup = -@"class A -{ - // Cannot rename {|caret:|}inside a comment. - void M() - { - } -}"; + """ + class A + { + // Cannot rename {|caret:|}inside a comment. + void M() + { + } + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var renameLocation = testLspServer.GetLocations("caret").First(); diff --git a/src/LanguageServer/ProtocolUnitTests/Rename/RenameTests.cs b/src/LanguageServer/ProtocolUnitTests/Rename/RenameTests.cs index 8b91d83e8184e..2e344bb92fbc6 100644 --- a/src/LanguageServer/ProtocolUnitTests/Rename/RenameTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Rename/RenameTests.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.LanguageServer.Handler; using Roslyn.LanguageServer.Protocol; using Roslyn.Test.Utilities; using Xunit; @@ -16,27 +17,23 @@ namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Rename; -public sealed class RenameTests : AbstractLanguageServerProtocolTests +public sealed class RenameTests(ITestOutputHelper testOutputHelper) : AbstractLanguageServerProtocolTests(testOutputHelper) { - public RenameTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { - } - [Theory, CombinatorialData] public async Task TestRenameAsync(bool mutatingLspWorkspace) { - var markup = -@"class A -{ - void {|caret:|}{|renamed:M|}() - { - } - void M2() - { - {|renamed:M|}() - } -}"; - await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); + await using var testLspServer = await CreateTestLspServerAsync(""" + class A + { + void {|caret:|}{|renamed:M|}() + { + } + void M2() + { + {|renamed:M|}() + } + } + """, mutatingLspWorkspace); var renameLocation = testLspServer.GetLocations("caret").First(); var renameValue = "RENAME"; var expectedEdits = testLspServer.GetLocations("renamed").Select(location => new LSP.TextEdit() { NewText = renameValue, Range = location.Range }); @@ -48,18 +45,18 @@ void M2() [Theory, CombinatorialData] public async Task TestRename_InvalidIdentifierAsync(bool mutatingLspWorkspace) { - var markup = -@"class A -{ - void {|caret:|}{|renamed:M|}() - { - } - void M2() - { - {|renamed:M|}() - } -}"; - await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); + await using var testLspServer = await CreateTestLspServerAsync(""" + class A + { + void {|caret:|}{|renamed:M|}() + { + } + void M2() + { + {|renamed:M|}() + } + } + """, mutatingLspWorkspace); var renameLocation = testLspServer.GetLocations("caret").First(); var renameValue = "$RENAMED$"; @@ -70,29 +67,28 @@ void M2() [Theory, CombinatorialData] public async Task TestRename_WithLinkedFilesAsync(bool mutatingLspWorkspace) { - var markup = -@"class A -{ - void {|caret:|}{|renamed:M|}() - { - } - void M2() - { - {|renamed:M|}() - } -}"; - - var workspaceXml = -$@" - - - - - - -"; - - await using var testLspServer = await CreateXmlTestLspServerAsync(workspaceXml, mutatingLspWorkspace); + var markup = """ + class A + { + void {|caret:|}{|renamed:M|}() + { + } + void M2() + { + {|renamed:M|}() + } + } + """; + await using var testLspServer = await CreateXmlTestLspServerAsync($""" + + + + + + + + + """, mutatingLspWorkspace); var renameLocation = testLspServer.GetLocations("caret").First(); var renameValue = "RENAME"; var expectedEdits = testLspServer.GetLocations("renamed").Select(location => new LSP.TextEdit() { NewText = renameValue, Range = location.Range }); @@ -104,41 +100,40 @@ void M2() [Theory, CombinatorialData] public async Task TestRename_WithLinkedFilesAndPreprocessorAsync(bool mutatingLspWorkspace) { - var markup = -@"class A -{ - void {|caret:|}{|renamed:M|}() - { - } - void M2() - { - {|renamed:M|}() - } - void M3() - { -#if Proj1 - {|renamed:M|}() -#endif - } - void M4() - { -#if Proj2 - {|renamed:M|}() -#endif - } -}"; - - var workspaceXml = -$@" - - - - - - -"; - - await using var testLspServer = await CreateXmlTestLspServerAsync(workspaceXml, mutatingLspWorkspace); + var markup = """ + class A + { + void {|caret:|}{|renamed:M|}() + { + } + void M2() + { + {|renamed:M|}() + } + void M3() + { + #if Proj1 + {|renamed:M|}() + #endif + } + void M4() + { + #if Proj2 + {|renamed:M|}() + #endif + } + } + """; + await using var testLspServer = await CreateXmlTestLspServerAsync($""" + + + + + + + + + """, mutatingLspWorkspace); var renameLocation = testLspServer.GetLocations("caret").First(); var renameValue = "RENAME"; var expectedEdits = testLspServer.GetLocations("renamed").Select(location => new LSP.TextEdit() { NewText = renameValue, Range = location.Range }); @@ -150,20 +145,20 @@ void M4() [Theory, CombinatorialData] public async Task TestRename_WithMappedFileAsync(bool mutatingLspWorkspace) { - var markup = -@"class A -{ - void M() - { - } - void M2() - { - M() - } -}"; await using var testLspServer = await CreateTestLspServerAsync(string.Empty, mutatingLspWorkspace); - AddMappedDocument(testLspServer.TestWorkspace, markup); + AddMappedDocument(testLspServer.TestWorkspace, """ + class A + { + void M() + { + } + void M2() + { + M() + } + } + """); var startPosition = new LSP.Position { Line = 2, Character = 9 }; var endPosition = new LSP.Position { Line = 2, Character = 10 }; @@ -186,6 +181,92 @@ void M2() Assert.True(documentEdit.Edits.All(edit => edit.Unify().NewText == renameText)); } + [Theory, CombinatorialData] + public async Task TestRename_WithSourceGeneratedFile(bool mutatingLspWorkspace) + { + var generatedMarkup = """ + class B + { + void M() + { + new A().{|renamed:M|}(); + + var a = new A(); + a.{|renamed:M|}(); + } + } + """; + await using var testLspServer = await CreateTestLspServerAsync(""" + public class A + { + public void {|caret:|}{|renamed:M|}() + { + } + + void M2() + { + {|renamed:M|}() + } + } + """, mutatingLspWorkspace, + new InitializationOptions() + { + SourceGeneratedMarkups = [generatedMarkup] + }); + + var renameLocation = testLspServer.GetLocations("caret").First(); + var renamePosition = ProtocolConversions.PositionToLinePosition(renameLocation.Range.Start); + var document = await testLspServer.GetDocumentAsync(renameLocation.DocumentUri); + var renameValue = "RENAME"; + var expectedEdits = testLspServer.GetLocations("renamed").Select(location => new LSP.TextEdit() { NewText = renameValue, Range = location.Range }); + + var results = await RenameHandler.GetRenameEditAsync(document, renamePosition, renameValue, includeSourceGenerated: true, CancellationToken.None); + AssertJsonEquals(expectedEdits, ((TextDocumentEdit[])results.DocumentChanges).SelectMany(e => e.Edits)); + } + + [Theory, CombinatorialData] + public async Task TestRename_OriginateInSourceGeneratedFile(bool mutatingLspWorkspace) + { + var generatedMarkup = """ + class B + { + void M() + { + new A().{|caret:|}{|renamed:M|}(); + + var a = new A(); + a.{|renamed:M|}(); + } + } + """; + await using var testLspServer = await CreateTestLspServerAsync(""" + public class A + { + public void {|renamed:M|}() + { + } + + void M2() + { + {|renamed:M|}() + } + } + """, mutatingLspWorkspace, + new InitializationOptions() + { + SourceGeneratedMarkups = [generatedMarkup] + }); + + var renameLocation = testLspServer.GetLocations("caret").First(); + var renamePosition = ProtocolConversions.PositionToLinePosition(renameLocation.Range.Start); + var document = await testLspServer.GetDocumentAsync(renameLocation.DocumentUri); + var renameValue = "RENAME"; + var expectedEdits = testLspServer.GetLocations("renamed").Select(location => new LSP.TextEdit() { NewText = renameValue, Range = location.Range }); + + var results = await RenameHandler.GetRenameEditAsync(document, renamePosition, renameValue, includeSourceGenerated: true, CancellationToken.None); + AssertJsonEquals(expectedEdits, ((TextDocumentEdit[])results.DocumentChanges).SelectMany(e => e.Edits)); + } + private static LSP.RenameParams CreateRenameParams(LSP.Location location, string newName) => new LSP.RenameParams() { diff --git a/src/LanguageServer/ProtocolUnitTests/SemanticTokens/AbstractSemanticTokensTests.cs b/src/LanguageServer/ProtocolUnitTests/SemanticTokens/AbstractSemanticTokensTests.cs index b712f2cd50e83..2392c4ad04330 100644 --- a/src/LanguageServer/ProtocolUnitTests/SemanticTokens/AbstractSemanticTokensTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/SemanticTokens/AbstractSemanticTokensTests.cs @@ -11,7 +11,6 @@ using Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens; using Roslyn.LanguageServer.Protocol; using Roslyn.Test.Utilities; -using Roslyn.Utilities; using Xunit; using Xunit.Abstractions; using LSP = Roslyn.LanguageServer.Protocol; diff --git a/src/LanguageServer/ProtocolUnitTests/SemanticTokens/SemanticTokensRangeTests.cs b/src/LanguageServer/ProtocolUnitTests/SemanticTokens/SemanticTokensRangeTests.cs index 35637b0e0b66c..fbdc1a5b01cf2 100644 --- a/src/LanguageServer/ProtocolUnitTests/SemanticTokens/SemanticTokensRangeTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/SemanticTokens/SemanticTokensRangeTests.cs @@ -635,54 +635,222 @@ class C { { expectedResults.Data = [ - // Line | Char | Len | Token type | Modifier - 4, 8, 15, tokenTypeToIndex[SemanticTokenTypes.Comment], 0, - 1, 8, 5, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, - 0, 6, 6, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, - 0, 7, 4, tokenTypeToIndex[ClassificationTypeNames.ConstantName], 1, - 0, 5, 1, tokenTypeToIndex[SemanticTokenTypes.Operator], 0, - 0, 2, 2, tokenTypeToIndex[ClassificationTypeNames.VerbatimStringLiteral],0, - 1, 0, 17, tokenTypeToIndex[SemanticTokenTypes.Namespace], 0, - 0, 8, 5, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, - 0, 5, 1, tokenTypeToIndex[ClassificationTypeNames.VerbatimStringLiteral],0, - 0, 1, 1, tokenTypeToIndex[ClassificationTypeNames.ClassName], 0, - 0, 1, 1, tokenTypeToIndex[ClassificationTypeNames.VerbatimStringLiteral],0, - 0, 1, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, - 1, 0, 12, tokenTypeToIndex[ClassificationTypeNames.VerbatimStringLiteral],0, - 0, 0, 14, tokenTypeToIndex[SemanticTokenTypes.Namespace], 0, - 0, 12, 2, tokenTypeToIndex[SemanticTokenTypes.Comment], 0, - 1, 0, 8, tokenTypeToIndex[ClassificationTypeNames.VerbatimStringLiteral],0, - 0, 0, 9, tokenTypeToIndex[SemanticTokenTypes.Namespace], 0, - 0, 8, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, - 0, 1, 1, tokenTypeToIndex[ClassificationTypeNames.VerbatimStringLiteral],0, - 0, 1, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, + // Line | Char | Len | Token type | Modifier + 4, 8, 15, tokenTypeToIndex[SemanticTokenTypes.Comment], 0, + 1, 8, 5, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 6, 6, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 7, 4, tokenTypeToIndex[ClassificationTypeNames.ConstantName], 1, + 0, 5, 1, tokenTypeToIndex[SemanticTokenTypes.Operator], 0, + 0, 2, 2, tokenTypeToIndex[ClassificationTypeNames.VerbatimStringLiteral], 0, + 1, 8, 5, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 5, 1, tokenTypeToIndex[ClassificationTypeNames.VerbatimStringLiteral], 0, + 0, 1, 1, tokenTypeToIndex[ClassificationTypeNames.ClassName], 0, + 0, 1, 1, tokenTypeToIndex[ClassificationTypeNames.VerbatimStringLiteral], 0, + 0, 1, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, + 1, 0, 12, tokenTypeToIndex[ClassificationTypeNames.VerbatimStringLiteral], 0, + 0, 12, 2, tokenTypeToIndex[SemanticTokenTypes.Comment], 0, + 1, 0, 8, tokenTypeToIndex[ClassificationTypeNames.VerbatimStringLiteral], 0, + 0, 8, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, + 0, 1, 1, tokenTypeToIndex[ClassificationTypeNames.VerbatimStringLiteral], 0, + 0, 1, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, ]; } else { expectedResults.Data = [ - // Line | Char | Len | Token type | Modifier - 4, 8, 15, tokenTypeToIndex[SemanticTokenTypes.Comment], 0, - 1, 8, 5, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, - 0, 6, 6, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, - 0, 7, 4, tokenTypeToIndex[CustomLspSemanticTokenNames.ConstantName], 1, - 0, 5, 1, tokenTypeToIndex[SemanticTokenTypes.Operator], 0, - 0, 2, 2, tokenTypeToIndex[CustomLspSemanticTokenNames.StringVerbatim],0, - 1, 0, 17, tokenTypeToIndex[SemanticTokenTypes.Namespace], 0, - 0, 8, 5, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, - 0, 5, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.StringVerbatim],0, - 0, 1, 1, tokenTypeToIndex[SemanticTokenTypes.Class], 0, - 0, 1, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.StringVerbatim],0, - 0, 1, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, - 1, 0, 12, tokenTypeToIndex[CustomLspSemanticTokenNames.StringVerbatim],0, - 0, 0, 14, tokenTypeToIndex[SemanticTokenTypes.Namespace], 0, - 0, 12, 2, tokenTypeToIndex[SemanticTokenTypes.Comment], 0, - 1, 0, 8, tokenTypeToIndex[CustomLspSemanticTokenNames.StringVerbatim],0, - 0, 0, 9, tokenTypeToIndex[SemanticTokenTypes.Namespace], 0, - 0, 8, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, - 0, 1, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.StringVerbatim],0, - 0, 1, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, + // Line | Char | Len | Token type | Modifier + 4, 8, 15, tokenTypeToIndex[SemanticTokenTypes.Comment], 0, + 1, 8, 5, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 6, 6, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 7, 4, tokenTypeToIndex[CustomLspSemanticTokenNames.ConstantName], 1, + 0, 5, 1, tokenTypeToIndex[SemanticTokenTypes.Operator], 0, + 0, 2, 2, tokenTypeToIndex[CustomLspSemanticTokenNames.StringVerbatim], 0, + 1, 8, 5, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 5, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.StringVerbatim], 0, + 0, 1, 1, tokenTypeToIndex[SemanticTokenTypes.Class], 0, + 0, 1, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.StringVerbatim], 0, + 0, 1, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.Punctuation], 0, + 1, 0, 12, tokenTypeToIndex[CustomLspSemanticTokenNames.StringVerbatim], 0, + 0, 12, 2, tokenTypeToIndex[SemanticTokenTypes.Comment], 0, + 1, 0, 8, tokenTypeToIndex[CustomLspSemanticTokenNames.StringVerbatim], 0, + 0, 8, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.Punctuation], 0, + 0, 1, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.StringVerbatim], 0, + 0, 1, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.Punctuation], 0, + ]; + } + + await VerifyBasicInvariantsAndNoMultiLineTokens(testLspServer, results.Data).ConfigureAwait(false); + AssertEx.Equal(ConvertToReadableFormat(testLspServer.ClientCapabilities, expectedResults.Data), ConvertToReadableFormat(testLspServer.ClientCapabilities, results.Data)); + } + + [Theory, CombinatorialData] + [WorkItem("https://github.com/dotnet/roslyn/issues/74435")] + public async Task TestGetSemanticTokensRange_AdditiveTestCodeClassification(bool mutatingLspWorkspace, bool isVS) + { + var markup = + """" + // lang=c#-test + var code2 = {|range:""" + using System; + namespace Test; + public class Program + { + public static void Main(string[] args) + { + return; + } + } + public struct Person {} + public interface ICan {} + """;|} + """"; + await using var testLspServer = await CreateTestLspServerAsync( + markup, mutatingLspWorkspace, GetCapabilities(isVS)); + + var location = testLspServer.GetLocations("range").Single(); + var results = await RunGetSemanticTokensRangeAsync(testLspServer, location); + + var expectedResults = new LSP.SemanticTokens(); + var tokenTypeToIndex = GetTokenTypeToIndex(testLspServer); + if (isVS) + { + expectedResults.Data = + [ + // Line | Char | Len | Token type | Modifier + 1, 12, 3, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 1, 0, 4, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 4, 5, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 5, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 6, tokenTypeToIndex[ClassificationTypeNames.NamespaceName], 0, + 0, 6, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, + 1, 0, 4, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 4, 9, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 9, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 4, tokenTypeToIndex[ClassificationTypeNames.NamespaceName], 0, + 0, 4, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, + 1, 0, 4, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 4, 6, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 6, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 5, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 5, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 7, tokenTypeToIndex[ClassificationTypeNames.ClassName], 0, + 1, 0, 4, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 4, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, + 1, 0, 4, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 8, 6, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 6, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 6, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 6, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 4, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 4, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 4, tokenTypeToIndex[ClassificationTypeNames.MethodName], 1, + 0, 4, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, + 0, 1, 6, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 6, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, + 0, 1, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, + 0, 1, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 4, tokenTypeToIndex[ClassificationTypeNames.ParameterName], 0, + 0, 4, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, + 1, 0, 4, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 8, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, + 1, 0, 4, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 12, 6, tokenTypeToIndex[ClassificationTypeNames.ControlKeyword], 0, + 0, 6, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, + 1, 0, 4, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 8, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, + 1, 0, 4, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 4, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, + 1, 0, 4, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 4, 6, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 6, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 6, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 6, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 6, tokenTypeToIndex[ClassificationTypeNames.StructName], 0, + 0, 6, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, + 0, 1, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, + 1, 0, 4, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 4, 6, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 6, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 9, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 9, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 4, tokenTypeToIndex[ClassificationTypeNames.InterfaceName], 0, + 0, 4, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, + 0, 1, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, + 1, 0, 7, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 7, 1, tokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, + ]; + } + else + { + expectedResults.Data = + [ + // Line | Char | Len | Token type | Modifier + 1, 12, 3, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 1, 0, 4, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 4, 5, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 5, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 6, tokenTypeToIndex[SemanticTokenTypes.Namespace], 0, + 0, 6, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.Punctuation], 0, + 1, 0, 4, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 4, 9, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 9, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 4, tokenTypeToIndex[SemanticTokenTypes.Namespace], 0, + 0, 4, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.Punctuation], 0, + 1, 0, 4, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 4, 6, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 6, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 5, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 5, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 7, tokenTypeToIndex[SemanticTokenTypes.Class], 0, + 1, 0, 4, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 4, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.Punctuation], 0, + 1, 0, 4, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 8, 6, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 6, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 6, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 6, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 4, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 4, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 4, tokenTypeToIndex[SemanticTokenTypes.Method], 1, + 0, 4, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.Punctuation], 0, + 0, 1, 6, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 6, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.Punctuation], 0, + 0, 1, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.Punctuation], 0, + 0, 1, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 4, tokenTypeToIndex[SemanticTokenTypes.Parameter], 0, + 0, 4, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.Punctuation], 0, + 1, 0, 4, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 8, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.Punctuation], 0, + 1, 0, 4, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 12, 6, tokenTypeToIndex[CustomLspSemanticTokenNames.KeywordControl], 0, + 0, 6, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.Punctuation], 0, + 1, 0, 4, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 8, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.Punctuation], 0, + 1, 0, 4, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 4, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.Punctuation], 0, + 1, 0, 4, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 4, 6, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 6, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 6, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 6, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 6, tokenTypeToIndex[SemanticTokenTypes.Struct], 0, + 0, 6, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.Punctuation], 0, + 0, 1, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.Punctuation], 0, + 1, 0, 4, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 4, 6, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 6, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 9, tokenTypeToIndex[SemanticTokenTypes.Keyword], 0, + 0, 9, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 4, tokenTypeToIndex[SemanticTokenTypes.Interface], 0, + 0, 4, 1, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 1, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.Punctuation], 0, + 0, 1, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.Punctuation], 0, + 1, 0, 7, tokenTypeToIndex[SemanticTokenTypes.String], 0, + 0, 7, 1, tokenTypeToIndex[CustomLspSemanticTokenNames.Punctuation], 0, ]; } diff --git a/src/LanguageServer/ProtocolUnitTests/SemanticTokens/SemanticTokensSchemaTests.cs b/src/LanguageServer/ProtocolUnitTests/SemanticTokens/SemanticTokensSchemaTests.cs new file mode 100644 index 0000000000000..2025ce1d864e8 --- /dev/null +++ b/src/LanguageServer/ProtocolUnitTests/SemanticTokens/SemanticTokensSchemaTests.cs @@ -0,0 +1,21 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Microsoft.CodeAnalysis.Classification; +using Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens; +using Xunit; + +namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.SemanticTokens; + +public class SemanticTokensSchemaTests +{ + [Fact] + public void TestAllAdditiveClassificationsMappedToTokenModifiers() + { + foreach (var additiveClassification in ClassificationTypeNames.AdditiveTypeNames) + { + Assert.True(SemanticTokensSchema.AdditiveClassificationTypeToTokenModifier.ContainsKey(additiveClassification), $"Modifier '{additiveClassification}' is not mapped to a {nameof(TokenModifiers)}"); + } + } +} diff --git a/src/LanguageServer/ProtocolUnitTests/SimplifyMethod/SimplifyMethodTests.cs b/src/LanguageServer/ProtocolUnitTests/SimplifyMethod/SimplifyMethodTests.cs index 2bcb3db2248ba..5dcebdca29568 100644 --- a/src/LanguageServer/ProtocolUnitTests/SimplifyMethod/SimplifyMethodTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/SimplifyMethod/SimplifyMethodTests.cs @@ -24,14 +24,15 @@ public SimplifyMethodTests(ITestOutputHelper? testOutputHelper) : base(testOutpu public async Task TestGetSimplifyMethodAsync(bool mutatingLspWorkspace) { var markup = -@" -using System; -using System.Threading.Tasks; -namespace test; -class A -{ -{|caret:|} -}"; + """ + using System; + using System.Threading.Tasks; + namespace test; + class A + { + {|caret:|} + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var methodInsertionLocation = testLspServer.GetLocations("caret").First(); var method = "private global::System.Threading.Tasks.Task test() => throw new global::System.NotImplementedException();"; diff --git a/src/LanguageServer/ProtocolUnitTests/SpellCheck/SpellCheckTests.cs b/src/LanguageServer/ProtocolUnitTests/SpellCheck/SpellCheckTests.cs index 62f545adec200..487c954e110ed 100644 --- a/src/LanguageServer/ProtocolUnitTests/SpellCheck/SpellCheckTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/SpellCheck/SpellCheckTests.cs @@ -29,9 +29,11 @@ public sealed class SpellCheckTests(ITestOutputHelper testOutputHelper) public async Task TestNoDocumentResultsForClosedFiles(bool mutatingLspWorkspace) { var markup = -@"class A -{ -}"; + """ + class A + { + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); @@ -44,9 +46,11 @@ public async Task TestNoDocumentResultsForClosedFiles(bool mutatingLspWorkspace) public async Task TestDocumentResultsForOpenFiles(bool mutatingLspWorkspace) { var markup = -@"class {|Identifier:A|} -{ -}"; + """ + class {|Identifier:A|} + { + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var testDocument = testLspServer.TestWorkspace.Documents.Single(); @@ -106,9 +110,11 @@ class {|Identifier:A{{v}}|} public async Task TestDocumentResultsForRemovedDocument(bool mutatingLspWorkspace) { var markup = -@"class {|Identifier:A|} -{ -}"; + """ + class {|Identifier:A|} + { + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var workspace = testLspServer.TestWorkspace; @@ -143,9 +149,11 @@ public async Task TestDocumentResultsForRemovedDocument(bool mutatingLspWorkspac public async Task TestNoChangeIfDocumentResultsCalledTwice(bool mutatingLspWorkspace) { var markup = -@"class {|Identifier:A|} -{ -}"; + """ + class {|Identifier:A|} + { + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); @@ -174,11 +182,13 @@ public async Task TestNoChangeIfDocumentResultsCalledTwice(bool mutatingLspWorks public async Task TestDocumentResultChangedAfterEntityAdded(bool mutatingLspWorkspace) { var markup = -@"class {|Identifier:A|} -{ -} + """ + class {|Identifier:A|} + { + } + -"; + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); @@ -202,11 +212,13 @@ public async Task TestDocumentResultChangedAfterEntityAdded(bool mutatingLspWork results = await RunGetDocumentSpellCheckSpansAsync(testLspServer, document.GetURI(), results.Single().ResultId); MarkupTestFile.GetSpans( -@"class {|Identifier:A|} -{ -} + """ + class {|Identifier:A|} + { + } -{|Comment:// comment|}", out _, out IDictionary> annotatedSpans); + {|Comment:// comment|} + """, out _, out IDictionary> annotatedSpans); sourceText = await document.GetTextAsync(); Assert.Single(results); @@ -221,9 +233,11 @@ public async Task TestDocumentResultChangedAfterEntityAdded(bool mutatingLspWork public async Task TestDocumentResultIdSameAfterIrrelevantEdit(bool mutatingLspWorkspace) { var markup = -@"class {|Identifier:A|} -{ -}"; + """ + class {|Identifier:A|} + { + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); @@ -257,10 +271,12 @@ public async Task TestDocumentResultIdSameAfterIrrelevantEdit(bool mutatingLspWo public async Task TestDocumentResultsAreNotMapped(bool mutatingLspWorkspace) { var markup = -@"#line 4 ""test.txt"" -class {|Identifier:A|} -{ -}"; + """ + #line 4 "test.txt" + class {|Identifier:A|} + { + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); @@ -282,9 +298,11 @@ class {|Identifier:A|} public async Task TestStreamingDocumentDiagnostics(bool mutatingLspWorkspace) { var markup = -@"class {|Identifier:A|} -{ -}"; + """ + class {|Identifier:A|} + { + } + """; await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); @@ -310,9 +328,11 @@ public async Task TestStreamingDocumentDiagnostics(bool mutatingLspWorkspace) public async Task TestWorkspaceResultsForClosedFiles(bool mutatingLspWorkspace) { var markup1 = -@"class {|Identifier:A|} -{ -}"; + """ + class {|Identifier:A|} + { + } + """; var markup2 = ""; await using var testLspServer = await CreateTestLspServerAsync([markup1, markup2], mutatingLspWorkspace); @@ -339,14 +359,16 @@ public async Task TestNoWorkspaceDiagnosticsForClosedFilesInProjectsWithIncorrec var typeScriptMarkup = "???"; var workspaceXml = -@$" - - {csharpMarkup} - - - {typeScriptMarkup} - - "; + $""" + + + {csharpMarkup} + + + {typeScriptMarkup} + + + """; await using var testLspServer = await CreateXmlTestLspServerAsync(workspaceXml, mutatingLspWorkspace); @@ -383,9 +405,11 @@ public async Task TestNoWorkspaceDiagnosticsForClosedFilesInProjectsWithIncorrec public async Task TestWorkspaceResultsForRemovedDocument(bool mutatingLspWorkspace) { var markup1 = -@"class {|Identifier:A|} -{ -}"; + """ + class {|Identifier:A|} + { + } + """; var markup2 = ""; await using var testLspServer = await CreateTestLspServerAsync([markup1, markup2], mutatingLspWorkspace); @@ -421,9 +445,11 @@ public async Task TestWorkspaceResultsForRemovedDocument(bool mutatingLspWorkspa public async Task TestNoChangeIfWorkspaceResultsCalledTwice(bool mutatingLspWorkspace) { var markup1 = -@"class {|Identifier:A|} -{ -}"; + """ + class {|Identifier:A|} + { + } + """; var markup2 = ""; await using var testLspServer = await CreateTestLspServerAsync([markup1, markup2], mutatingLspWorkspace); @@ -455,11 +481,13 @@ public async Task TestNoChangeIfWorkspaceResultsCalledTwice(bool mutatingLspWork public async Task TestWorkspaceResultUpdatedAfterEdit(bool mutatingLspWorkspace) { var markup1 = -@"class {|Identifier:A|} -{ -} + """ + class {|Identifier:A|} + { + } -"; + + """; var markup2 = ""; await using var testLspServer = await CreateTestLspServerAsync([markup1, markup2], mutatingLspWorkspace); @@ -487,11 +515,13 @@ public async Task TestWorkspaceResultUpdatedAfterEdit(bool mutatingLspWorkspace) sourceText = await document.GetTextAsync(); MarkupTestFile.GetSpans( -@"class {|Identifier:A|} -{ -} + """ + class {|Identifier:A|} + { + } -{|Comment:// comment|}", out _, out IDictionary> annotatedSpans); + {|Comment:// comment|} + """, out _, out IDictionary> annotatedSpans); AssertJsonEquals(results2[0], new VSInternalWorkspaceSpellCheckableReport { @@ -509,9 +539,11 @@ public async Task TestWorkspaceResultUpdatedAfterEdit(bool mutatingLspWorkspace) public async Task TestStreamingWorkspaceResults(bool mutatingLspWorkspace) { var markup1 = -@"class {|Identifier:A|} -{ -}"; + """ + class {|Identifier:A|} + { + } + """; var markup2 = ""; await using var testLspServer = await CreateTestLspServerAsync([markup1, markup2], mutatingLspWorkspace); diff --git a/src/LanguageServer/ProtocolUnitTests/UriTests.cs b/src/LanguageServer/ProtocolUnitTests/UriTests.cs index b188ccf5bdd86..03030c16a44fa 100644 --- a/src/LanguageServer/ProtocolUnitTests/UriTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/UriTests.cs @@ -33,13 +33,6 @@ public UriTests(ITestOutputHelper? testOutputHelper) : base(testOutputHelper) [WorkItem("https://github.com/dotnet/runtime/issues/89538")] public async Task TestMiscDocument_WithFileScheme(bool mutatingLspWorkspace) { - var source = -@"class A -{ - void M() - { - } -}"; var filePath = "C:\\\ud86d\udeac\ue25b.txt"; // Create a server that supports LSP misc files and verify no misc files present. @@ -47,7 +40,14 @@ void M() // Open an empty loose file with a file URI. var looseFileUri = ProtocolConversions.CreateAbsoluteDocumentUri(filePath); - await testLspServer.OpenDocumentAsync(looseFileUri, source, languageId: "csharp").ConfigureAwait(false); + await testLspServer.OpenDocumentAsync(looseFileUri, """ + class A + { + void M() + { + } + } + """, languageId: "csharp").ConfigureAwait(false); // Verify file is added to the misc file workspace. var (workspace, _, document) = await testLspServer.GetManager().GetLspDocumentInfoAsync(new LSP.TextDocumentIdentifier { DocumentUri = looseFileUri }, CancellationToken.None); @@ -60,20 +60,20 @@ void M() [Theory, CombinatorialData] public async Task TestMiscDocument_WithOtherScheme(bool mutatingLspWorkspace) { - var source = -@"class A -{ - void M() - { - } -}"; // Create a server that supports LSP misc files and verify no misc files present. await using var testLspServer = await CreateTestLspServerAsync(string.Empty, mutatingLspWorkspace, new InitializationOptions { ServerKind = WellKnownLspServerKinds.CSharpVisualBasicLspServer }); // Open an empty loose file that hasn't been saved with a name. var looseFileUri = ProtocolConversions.CreateAbsoluteDocumentUri(@"untitled:untitledFile"); - await testLspServer.OpenDocumentAsync(looseFileUri, source, languageId: "csharp").ConfigureAwait(false); + await testLspServer.OpenDocumentAsync(looseFileUri, """ + class A + { + void M() + { + } + } + """, languageId: "csharp").ConfigureAwait(false); // Verify file is added to the misc file workspace. var (workspace, _, document) = await testLspServer.GetManager().GetLspDocumentInfoAsync(new LSP.TextDocumentIdentifier { DocumentUri = looseFileUri }, CancellationToken.None); diff --git a/src/LanguageServer/ProtocolUnitTests/Workspaces/LspWorkspaceManagerTests.cs b/src/LanguageServer/ProtocolUnitTests/Workspaces/LspWorkspaceManagerTests.cs index 7914fe15a7c82..e661f144a2c14 100644 --- a/src/LanguageServer/ProtocolUnitTests/Workspaces/LspWorkspaceManagerTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Workspaces/LspWorkspaceManagerTests.cs @@ -281,18 +281,22 @@ public async Task TestLspTransfersDocumentToNewWorkspaceAsync(bool mutatingLspWo public async Task TestUsesRegisteredHostWorkspace(bool mutatingLspWorkspace) { var firstWorkspaceXml = -@$" - - FirstWorkspace - -"; + $""" + + + FirstWorkspace + + + """; var secondWorkspaceXml = -@$" - - SecondWorkspace - -"; + $""" + + + SecondWorkspace + + + """; await using var testLspServer = await CreateXmlTestLspServerAsync(firstWorkspaceXml, mutatingLspWorkspace); // Verify 1 workspace registered to start with. @@ -324,11 +328,13 @@ public async Task TestUsesRegisteredHostWorkspace(bool mutatingLspWorkspace) public async Task TestWorkspaceRequestFailsWhenHostWorkspaceMissing(bool mutatingLspWorkspace) { var firstWorkspaceXml = -@$" - - FirstWorkspace - -"; + $""" + + + FirstWorkspace + + + """; await using var testLspServer = await CreateXmlTestLspServerAsync(firstWorkspaceXml, mutatingLspWorkspace, workspaceKind: WorkspaceKind.MiscellaneousFiles); var exportProvider = testLspServer.TestWorkspace.ExportProvider; @@ -347,23 +353,23 @@ public async Task TestWorkspaceRequestFailsWhenHostWorkspaceMissing(bool mutatin public async Task TestLspUpdatesCorrectWorkspaceWithMultipleWorkspacesAsync(bool mutatingLspWorkspace) { var firstWorkspaceXml = -@$" - - FirstWorkspace - -"; - - var secondWorkspaceXml = -@$" - - SecondWorkspace - -"; - + $""" + + + FirstWorkspace + + + """; await using var testLspServer = await CreateXmlTestLspServerAsync(firstWorkspaceXml, mutatingLspWorkspace); using var testWorkspaceTwo = CreateWorkspace(options: null, WorkspaceKind.MSBuild, mutatingLspWorkspace); - testWorkspaceTwo.InitializeDocuments(XElement.Parse(secondWorkspaceXml)); + testWorkspaceTwo.InitializeDocuments(XElement.Parse($""" + + + SecondWorkspace + + + """)); // Wait for workspace creation operations to complete for the second workspace. await WaitForWorkspaceOperationsAsync(testWorkspaceTwo); @@ -406,23 +412,23 @@ public async Task TestLspUpdatesCorrectWorkspaceWithMultipleWorkspacesAsync(bool public async Task TestWorkspaceEventUpdatesCorrectWorkspaceWithMultipleWorkspacesAsync(bool mutatingLspWorkspace) { var firstWorkspaceXml = -@$" - - FirstWorkspace - -"; - - var secondWorkspaceXml = -@$" - - SecondWorkspace - -"; - + $""" + + + FirstWorkspace + + + """; await using var testLspServer = await CreateXmlTestLspServerAsync(firstWorkspaceXml, mutatingLspWorkspace); using var testWorkspaceTwo = CreateWorkspace(options: null, workspaceKind: WorkspaceKind.MSBuild, mutatingLspWorkspace); - testWorkspaceTwo.InitializeDocuments(XElement.Parse(secondWorkspaceXml)); + testWorkspaceTwo.InitializeDocuments(XElement.Parse($""" + + + SecondWorkspace + + + """)); // Wait for workspace operations to complete for the second workspace. await WaitForWorkspaceOperationsAsync(testWorkspaceTwo); @@ -460,15 +466,14 @@ public async Task TestWorkspaceEventUpdatesCorrectWorkspaceWithMultipleWorkspace [Theory, CombinatorialData] public async Task TestSeparateWorkspaceManagerPerServerAsync(bool mutatingLspWorkspace) { - var workspaceXml = -@$" - - Original text - -"; - using var testWorkspace = CreateWorkspace(options: null, workspaceKind: null, mutatingLspWorkspace); - testWorkspace.InitializeDocuments(XElement.Parse(workspaceXml)); + testWorkspace.InitializeDocuments(XElement.Parse($""" + + + Original text + + + """)); await using var testLspServerOne = await TestLspServer.CreateAsync(testWorkspace, new InitializationOptions(), TestOutputLspLogger); await using var testLspServerTwo = await TestLspServer.CreateAsync(testWorkspace, new InitializationOptions(), TestOutputLspLogger); @@ -713,10 +718,9 @@ public async Task TestDoesNotUseForkForUnchangedGeneratedFileAsync(bool mutating [Theory, CombinatorialData] public async Task TestForksWithDifferentGeneratedContentsAsync(bool mutatingLspWorkspace) { - var workspaceGeneratedText = "// Hello World!"; var lspGeneratedText = "// Hello LSP!"; await using var testLspServer = await CreateTestLspServerAsync(string.Empty, mutatingLspWorkspace); - await AddGeneratorAsync(new SingleFileTestGenerator(workspaceGeneratedText), testLspServer.TestWorkspace); + await AddGeneratorAsync(new SingleFileTestGenerator("// Hello World!"), testLspServer.TestWorkspace); var sourceGeneratedDocuments = await testLspServer.GetCurrentSolution().Projects.Single().GetSourceGeneratedDocumentsAsync(); var sourceGeneratedDocumentIdentity = sourceGeneratedDocuments.Single().Identity; diff --git a/src/LanguageServer/ProtocolUnitTests/Workspaces/LspWorkspaceRegistrationServiceTests.cs b/src/LanguageServer/ProtocolUnitTests/Workspaces/LspWorkspaceRegistrationServiceTests.cs index 06697e444956a..c6aef2d8d05ea 100644 --- a/src/LanguageServer/ProtocolUnitTests/Workspaces/LspWorkspaceRegistrationServiceTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Workspaces/LspWorkspaceRegistrationServiceTests.cs @@ -8,6 +8,7 @@ using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Workspaces; + public sealed class LspWorkspaceRegistrationServiceTests : AbstractLanguageServerProtocolTests { public LspWorkspaceRegistrationServiceTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) @@ -17,9 +18,8 @@ public LspWorkspaceRegistrationServiceTests(ITestOutputHelper testOutputHelper) [Theory, CombinatorialData] public async Task TestDisposedWorkspaceDeregistered(bool mutatingLspWorkspace) { - var markup = ""; TestWorkspaceRegistrationService registrationService; - await using (var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace)) + await using (var testLspServer = await CreateTestLspServerAsync("", mutatingLspWorkspace)) { registrationService = (TestWorkspaceRegistrationService)testLspServer.TestWorkspace.ExportProvider.GetExportedValue(); } diff --git a/src/NuGet/Microsoft.CodeAnalysis.BuildClient.Package/Microsoft.CodeAnalysis.BuildClient.Package.csproj b/src/NuGet/Microsoft.CodeAnalysis.BuildClient.Package/Microsoft.CodeAnalysis.BuildClient.Package.csproj new file mode 100644 index 0000000000000..140c6b85b08c9 --- /dev/null +++ b/src/NuGet/Microsoft.CodeAnalysis.BuildClient.Package/Microsoft.CodeAnalysis.BuildClient.Package.csproj @@ -0,0 +1,21 @@ + + + + + + $(NetRoslynSourceBuild) + + + true + true + Microsoft.CodeAnalysis.BuildClient + false + + Package containing sources of Microsoft .NET Compiler Platform ("Roslyn") build client API. For internal use only. + Relying on APIs from this package is explicitly not supported, they can and will break on a regular basis. + + + + + + diff --git a/src/NuGet/Microsoft.CodeAnalysis.BuildClient.Package/Microsoft.CodeAnalysis.BuildClient.targets b/src/NuGet/Microsoft.CodeAnalysis.BuildClient.Package/Microsoft.CodeAnalysis.BuildClient.targets new file mode 100644 index 0000000000000..d98ead6380e82 --- /dev/null +++ b/src/NuGet/Microsoft.CodeAnalysis.BuildClient.Package/Microsoft.CodeAnalysis.BuildClient.targets @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/src/NuGet/Microsoft.Net.Compilers.Toolset/AnyCpu/Microsoft.Net.Compilers.Toolset.Package.csproj b/src/NuGet/Microsoft.Net.Compilers.Toolset/AnyCpu/Microsoft.Net.Compilers.Toolset.Package.csproj index 54016ae2414da..d89d733ec99d6 100644 --- a/src/NuGet/Microsoft.Net.Compilers.Toolset/AnyCpu/Microsoft.Net.Compilers.Toolset.Package.csproj +++ b/src/NuGet/Microsoft.Net.Compilers.Toolset/AnyCpu/Microsoft.Net.Compilers.Toolset.Package.csproj @@ -62,9 +62,11 @@ + - + + diff --git a/src/NuGet/Microsoft.Net.Compilers.Toolset/Framework/build/Microsoft.Net.Compilers.Toolset.Framework.Core.props b/src/NuGet/Microsoft.Net.Compilers.Toolset/Framework/build/Microsoft.Net.Compilers.Toolset.Framework.Core.props index 90ad67b5feb6d..192ae2959ec21 100644 --- a/src/NuGet/Microsoft.Net.Compilers.Toolset/Framework/build/Microsoft.Net.Compilers.Toolset.Framework.Core.props +++ b/src/NuGet/Microsoft.Net.Compilers.Toolset/Framework/build/Microsoft.Net.Compilers.Toolset.Framework.Core.props @@ -4,6 +4,7 @@ <_RoslynTargetDirectoryName>net472 <_RoslynTasksDirectory>$(MSBuildThisFileDirectory)..\tasks\$(_RoslynTargetDirectoryName)\ + Custom $(_RoslynTasksDirectory)Microsoft.Build.Tasks.CodeAnalysis.dll true $(_RoslynTasksDirectory)Microsoft.CSharp.Core.targets diff --git a/src/NuGet/Microsoft.Net.Compilers.Toolset/arm64/build/Microsoft.Net.Compilers.Toolset.Arm64.props b/src/NuGet/Microsoft.Net.Compilers.Toolset/arm64/build/Microsoft.Net.Compilers.Toolset.Arm64.props index ea3dd999eb8c4..499e9baaebbae 100644 --- a/src/NuGet/Microsoft.Net.Compilers.Toolset/arm64/build/Microsoft.Net.Compilers.Toolset.Arm64.props +++ b/src/NuGet/Microsoft.Net.Compilers.Toolset/arm64/build/Microsoft.Net.Compilers.Toolset.Arm64.props @@ -3,6 +3,7 @@ <_RoslynTasksDirectory>$(MSBuildThisFileDirectory)..\tasks\net472\ + Custom $(_RoslynTasksDirectory)Microsoft.Build.Tasks.CodeAnalysis.dll true $(_RoslynTasksDirectory)Microsoft.CSharp.Core.targets diff --git a/src/RoslynAnalyzers/Directory.Build.props b/src/RoslynAnalyzers/Directory.Build.props index ea2ea42b260c8..78d2d29712108 100644 --- a/src/RoslynAnalyzers/Directory.Build.props +++ b/src/RoslynAnalyzers/Directory.Build.props @@ -8,6 +8,12 @@ true + + true + + + + $(DefineConstants),ROSLYN_4_12_OR_LOWER @@ -22,6 +28,12 @@ $(DefineConstants),LEGACY_CODE_METRICS_MODE + + + + $(NoWarn);IDE0079 + + diff --git a/src/RoslynAnalyzers/Directory.Packages.props b/src/RoslynAnalyzers/Directory.Packages.props new file mode 100644 index 0000000000000..8e8a44277bc94 --- /dev/null +++ b/src/RoslynAnalyzers/Directory.Packages.props @@ -0,0 +1,11 @@ + + + + + + false + + \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.AnalyzerUtilities/Microsoft.CodeAnalysis.AnalyzerUtilities.csproj b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.AnalyzerUtilities/Microsoft.CodeAnalysis.AnalyzerUtilities.csproj index b40dc54b328b5..0f01b40f158f7 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.AnalyzerUtilities/Microsoft.CodeAnalysis.AnalyzerUtilities.csproj +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.AnalyzerUtilities/Microsoft.CodeAnalysis.AnalyzerUtilities.csproj @@ -11,15 +11,27 @@ true true - true + Microsoft.CodeAnalysis $(NoWarn);RS0026 - $(MicrosoftCodeAnalysisVersionForCodeAnalysisAnalyzers) - + + + + + + + + + + + + + + @@ -29,4 +41,12 @@ + + + + + + + + diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/CSharp/MetaAnalyzers/CSharpSymbolIsBannedInAnalyzersAnalyzer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/CSharp/MetaAnalyzers/CSharpSymbolIsBannedInAnalyzersAnalyzer.cs index e49f2edefac9a..3224024b6332f 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/CSharp/MetaAnalyzers/CSharpSymbolIsBannedInAnalyzersAnalyzer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/CSharp/MetaAnalyzers/CSharpSymbolIsBannedInAnalyzersAnalyzer.cs @@ -2,12 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Analyzers; -using System.Collections.Immutable; using System.Collections.Generic; +using System.Collections.Immutable; using System.Linq; +using Microsoft.CodeAnalysis.Analyzers; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.Analyzers { diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/CSharp/Microsoft.CodeAnalysis.CSharp.Analyzers.csproj b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/CSharp/Microsoft.CodeAnalysis.CSharp.Analyzers.csproj index 7d0923c75f7b9..07ca685101455 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/CSharp/Microsoft.CodeAnalysis.CSharp.Analyzers.csproj +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/CSharp/Microsoft.CodeAnalysis.CSharp.Analyzers.csproj @@ -2,7 +2,6 @@ netstandard2.0 - $(MicrosoftCodeAnalysisVersionForCodeAnalysisAnalyzers) @@ -10,10 +9,22 @@ - - - - - - + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/CodeAnalysisDiagnosticsResources.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/CodeAnalysisDiagnosticsResources.cs index de19b7ca8b41c..62ea7fa5a6f73 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/CodeAnalysisDiagnosticsResources.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/CodeAnalysisDiagnosticsResources.cs @@ -4,7 +4,7 @@ using System; -namespace Microsoft.CodeAnalysis.Analyzers +namespace Microsoft.CodeAnalysis { internal static partial class CodeAnalysisDiagnosticsResources { diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/FixAnalyzers/FixerWithFixAllAnalyzer.Fixer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/FixAnalyzers/FixerWithFixAllAnalyzer.Fixer.cs index 0cd3fcd00830b..df6b3a3c7b287 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/FixAnalyzers/FixerWithFixAllAnalyzer.Fixer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/FixAnalyzers/FixerWithFixAllAnalyzer.Fixer.cs @@ -14,6 +14,7 @@ using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editing; +using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers.Fixers { @@ -25,7 +26,7 @@ namespace Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers.Fixers [method: Obsolete("This exported object must be obtained through the MEF export provider.", error: true)] public sealed class FixerWithFixAllFix() : CodeFixProvider { - public sealed override ImmutableArray FixableDiagnosticIds { get; } = ImmutableArray.Create(DiagnosticIds.OverrideGetFixAllProviderRuleId); + public sealed override ImmutableArray FixableDiagnosticIds { get; } = [DiagnosticIds.OverrideGetFixAllProviderRuleId]; public sealed override FixAllProvider GetFixAllProvider() { @@ -34,15 +35,15 @@ public sealed override FixAllProvider GetFixAllProvider() public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { - SyntaxNode root = await context.Document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); - SyntaxToken token = root.FindToken(context.Span.Start); + var root = await context.Document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); + var token = root.FindToken(context.Span.Start); if (!token.Span.IntersectsWith(context.Span)) { return; } - SyntaxGenerator generator = SyntaxGenerator.GetGenerator(context.Document); - SyntaxNode classDecl = generator.GetDeclaration(token.Parent); + var generator = SyntaxGenerator.GetGenerator(context.Document); + var classDecl = generator.GetDeclaration(token.Parent); if (classDecl == null) { return; @@ -61,8 +62,8 @@ private static async Task AddMethodAsync(Document document, SyntaxNode var model = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var typeIsSealed = ((INamedTypeSymbol)model.GetDeclaredSymbol(classDecl, cancellationToken)!).IsSealed; - INamedTypeSymbol? codeFixProviderSymbol = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftCodeAnalysisCodeFixesCodeFixProvider); - IMethodSymbol? getFixAllProviderMethod = codeFixProviderSymbol?.GetMembers(FixerWithFixAllAnalyzer.GetFixAllProviderMethodName).OfType().FirstOrDefault(); + var codeFixProviderSymbol = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftCodeAnalysisCodeFixesCodeFixProvider); + var getFixAllProviderMethod = codeFixProviderSymbol?.GetMembers(FixerWithFixAllAnalyzer.GetFixAllProviderMethodName).OfType().FirstOrDefault(); if (getFixAllProviderMethod == null) { return document; diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/FixAnalyzers/FixerWithFixAllAnalyzer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/FixAnalyzers/FixerWithFixAllAnalyzer.cs index b73d3a4da535b..d5203bf1141d8 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/FixAnalyzers/FixerWithFixAllAnalyzer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/FixAnalyzers/FixerWithFixAllAnalyzer.cs @@ -11,6 +11,7 @@ using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; +using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Analyzers.FixAnalyzers { diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/ImmutableObjectMethodAnalyzer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/ImmutableObjectMethodAnalyzer.cs index 8119c169b0f7b..44886af66ae55 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/ImmutableObjectMethodAnalyzer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/ImmutableObjectMethodAnalyzer.cs @@ -9,6 +9,7 @@ using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; +using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Analyzers { diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAPIUsageAnalyzer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAPIUsageAnalyzer.cs index 7d16388a11d73..8953c845e6a19 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAPIUsageAnalyzer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAPIUsageAnalyzer.cs @@ -11,10 +11,10 @@ using System.Threading; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; -using Analyzer.Utilities.PooledObjects; using Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers.Helpers; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; +using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers { @@ -161,22 +161,22 @@ public override void Initialize(AnalysisContext context) { // Change diagnostic analyzer type '{0}' to remove all direct accesses to type(s) '{1}' rule = DoNotUseTypesFromAssemblyDirectRule; - args = new[] - { + args = + [ declaredType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), string.Join(", ", violatingTypeNamesBuilder) - }; + ]; } else { // Change diagnostic analyzer type '{0}' to remove all direct and/or indirect accesses to type(s) '{1}', which access type(s) '{2}' rule = DoNotUseTypesFromAssemblyIndirectRule; - args = new[] - { + args = + [ declaredType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), string.Join(", ", violatingUsedTypeNamesBuilder), string.Join(", ", violatingTypeNamesBuilder) - }; + ]; } Diagnostic diagnostic = declaredType.CreateDiagnostic(rule, args); diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAttributeAnalyzer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAttributeAnalyzer.cs index f865e9b9b83b0..ccc234eb46566 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAttributeAnalyzer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAttributeAnalyzer.cs @@ -7,6 +7,7 @@ using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis.Diagnostics; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers { diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerCorrectnessAnalyzer.DiagnosticAnalyzerSymbolAnalyzer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerCorrectnessAnalyzer.DiagnosticAnalyzerSymbolAnalyzer.cs index 4c2adf1539b6b..16ebbab6e83b1 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerCorrectnessAnalyzer.DiagnosticAnalyzerSymbolAnalyzer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerCorrectnessAnalyzer.DiagnosticAnalyzerSymbolAnalyzer.cs @@ -5,6 +5,7 @@ using System.Linq; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers { diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerFieldsAnalyzer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerFieldsAnalyzer.cs index 8275a93af46e3..7121f75e0e386 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerFieldsAnalyzer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerFieldsAnalyzer.cs @@ -9,6 +9,7 @@ using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers.Helpers; using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers { diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzer.cs index e53b2175eb017..3a0e9f12b3246 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzer.cs @@ -14,19 +14,22 @@ using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Analyzer.Utilities.PooledObjects; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers.Helpers; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.ReleaseTracking; +using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers { using static CodeAnalysisDiagnosticsResources; + using PooledFieldToCustomTagsConcurrentDictionary = PooledConcurrentDictionary>; + using PooledFieldToResourceNameAndFileNameConcurrentDictionary = PooledConcurrentDictionary; using PooledLocalizabeStringsConcurrentDictionary = PooledConcurrentDictionary>; using PooledResourcesDataValueConcurrentDictionary = PooledConcurrentDictionary>; - using PooledFieldToResourceNameAndFileNameConcurrentDictionary = PooledConcurrentDictionary; - using PooledFieldToCustomTagsConcurrentDictionary = PooledConcurrentDictionary>; /// /// RS1007 @@ -677,8 +680,7 @@ private static void ReportDefineDiagnosticArgumentCorrectlyDiagnostic( else { var span = fixLocation.SourceSpan; - var locationInfo = $"{span.Start}{AdditionalDocumentLocationInfoSeparator}{span.Length}{AdditionalDocumentLocationInfoSeparator}{fixLocation.GetLineSpan().Path}"; - properties = properties.Add(DefineDescriptorArgumentCorrectlyFixAdditionalDocumentLocationInfo, locationInfo); + properties = properties.Add(DefineDescriptorArgumentCorrectlyFixAdditionalDocumentLocationInfo, $"{span.Start}{AdditionalDocumentLocationInfoSeparator}{span.Length}{AdditionalDocumentLocationInfoSeparator}{fixLocation.GetLineSpan().Path}"); } reportDiagnostic(argumentOperation.CreateDiagnostic(descriptor, additionalLocations, properties)); @@ -700,7 +702,7 @@ DiagnosticIds.DefineDiagnosticMessageCorrectlyRuleId or return false; } - var parts = locationInfo.Split(new[] { AdditionalDocumentLocationInfoSeparator }, StringSplitOptions.None); + var parts = locationInfo.Split([AdditionalDocumentLocationInfoSeparator], StringSplitOptions.None); if (parts.Length != 3 || !int.TryParse(parts[0], out var spanSpart) || !int.TryParse(parts[1], out var spanLength)) @@ -979,7 +981,7 @@ private static string FixLineReturns(string s, bool allowMultisentences) { Debug.Assert(ContainsLineReturn(s)); - var parts = s.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries); + var parts = s.Split(["\r\n", "\r", "\n"], StringSplitOptions.RemoveEmptyEntries); if (!allowMultisentences) { return parts[0]; diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzer_IdRangeAndCategoryValidation.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzer_IdRangeAndCategoryValidation.cs index ea7fdc52b3f35..b19ae7c4890b5 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzer_IdRangeAndCategoryValidation.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzer_IdRangeAndCategoryValidation.cs @@ -16,6 +16,7 @@ using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers { diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzer_ReleaseTracking.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzer_ReleaseTracking.cs index d2dccdaf75f58..c4c6f7e1397e4 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzer_ReleaseTracking.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzer_ReleaseTracking.cs @@ -14,8 +14,10 @@ using Analyzer.Utilities.PooledObjects; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; +using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.ReleaseTracking; using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; using static Microsoft.CodeAnalysis.ReleaseTracking.ReleaseTrackingHelper; namespace Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers @@ -177,7 +179,7 @@ private static bool TryGetReleaseTrackingData( } var diagnostics = new List(); - using var reportedInvalidLines = PooledHashSet.GetInstance(); + using var _ = PooledHashSet.GetInstance(out var reportedInvalidLines); shippedData = ReadReleaseTrackingData(shippedText.Path, shippedText.GetTextOrEmpty(cancellationToken), OnDuplicateEntryInRelease, OnInvalidEntry, isShippedFile: true); unshippedData = ReadReleaseTrackingData(unshippedText.Path, unshippedText.GetTextOrEmpty(cancellationToken), OnDuplicateEntryInRelease, OnInvalidEntry, isShippedFile: false); @@ -410,7 +412,7 @@ private static void ReportAnalyzerReleaseTrackingDiagnostics( } // Map to track and report duplicate entries for same rule ID. - using var lastEntriesByRuleMap = PooledDictionary.GetInstance(); + using var _ = PooledDictionary.GetInstance(out var lastEntriesByRuleMap); // Process each entry in unshipped file to flag rules which are not seen. foreach (var (ruleId, releaseTrackingDataForRule) in unshippedData.ReleaseTrackingDataByRuleIdMap) diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/AnalyzerReleaseTrackingFix.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/AnalyzerReleaseTrackingFix.cs index b6743840d5549..25ec18d52c2e1 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/AnalyzerReleaseTrackingFix.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/AnalyzerReleaseTrackingFix.cs @@ -18,6 +18,7 @@ using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.ReleaseTracking; using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers.Fixers { @@ -28,7 +29,7 @@ namespace Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers.Fixers public sealed partial class AnalyzerReleaseTrackingFix() : CodeFixProvider { private const string EntryFieldSeparator = "|"; - private static readonly string[] s_entryFieldSeparators = new[] { EntryFieldSeparator }; + private static readonly string[] s_entryFieldSeparators = [EntryFieldSeparator]; internal const string ShippedAnalyzerReleaseTrackingFileDefaultContent = @"; Shipped analyzer releases " + CommonAnalyzerReleaseTrackingContent; diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ApplyDiagnosticAnalyzerAttributeFix.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ApplyDiagnosticAnalyzerAttributeFix.cs index d30b46da16277..1cb707aa50379 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ApplyDiagnosticAnalyzerAttributeFix.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ApplyDiagnosticAnalyzerAttributeFix.cs @@ -9,24 +9,25 @@ using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editing; +using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers.Fixers { public abstract class ApplyDiagnosticAnalyzerAttributeFix : CodeFixProvider { - public sealed override ImmutableArray FixableDiagnosticIds { get; } = ImmutableArray.Create(DiagnosticIds.MissingDiagnosticAnalyzerAttributeRuleId); + public sealed override ImmutableArray FixableDiagnosticIds { get; } = [DiagnosticIds.MissingDiagnosticAnalyzerAttributeRuleId]; public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { - SyntaxNode root = await context.Document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); - SyntaxToken token = root.FindToken(context.Span.Start); + var root = await context.Document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); + var token = root.FindToken(context.Span.Start); if (!token.Span.IntersectsWith(context.Span)) { return; } - SyntaxGenerator generator = SyntaxGenerator.GetGenerator(context.Document); - SyntaxNode classDecl = generator.GetDeclaration(token.Parent); + var generator = SyntaxGenerator.GetGenerator(context.Document); + var classDecl = generator.GetDeclaration(token.Parent); if (classDecl == null) { return; @@ -35,7 +36,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) // Register fixes. // 1) Apply C# DiagnosticAnalyzerAttribute. - string title = string.Format(CultureInfo.CurrentCulture, CodeAnalysisDiagnosticsResources.ApplyDiagnosticAnalyzerAttribute_1, LanguageNames.CSharp); + var title = string.Format(CultureInfo.CurrentCulture, CodeAnalysisDiagnosticsResources.ApplyDiagnosticAnalyzerAttribute_1, LanguageNames.CSharp); AddFix(title, context, root, classDecl, generator, LanguageNames.CSharp); // 2) Apply VB DiagnosticAnalyzerAttribute. @@ -60,20 +61,20 @@ private void AddFix(string codeFixTitle, CodeFixContext context, SyntaxNode root private Task GetFixAsync(Document document, SyntaxNode root, SyntaxNode classDecl, SyntaxGenerator generator, params string[] languages) { - string languageNamesFullName = typeof(LanguageNames).FullName; + var languageNamesFullName = typeof(LanguageNames).FullName; var arguments = new SyntaxNode[languages.Length]; - for (int i = 0; i < languages.Length; i++) + for (var i = 0; i < languages.Length; i++) { - string language = languages[i] == LanguageNames.CSharp ? nameof(LanguageNames.CSharp) : nameof(LanguageNames.VisualBasic); - string expressionToParse = languageNamesFullName + "." + language; - SyntaxNode parsedExpression = ParseExpression(expressionToParse); + var language = languages[i] == LanguageNames.CSharp ? nameof(LanguageNames.CSharp) : nameof(LanguageNames.VisualBasic); + var expressionToParse = languageNamesFullName + "." + language; + var parsedExpression = ParseExpression(expressionToParse); arguments[i] = generator.AttributeArgument(parsedExpression); } - SyntaxNode attribute = generator.Attribute(WellKnownTypeNames.MicrosoftCodeAnalysisDiagnosticsDiagnosticAnalyzerAttribute, arguments); - SyntaxNode newClassDecl = generator.AddAttributes(classDecl, attribute); - SyntaxNode newRoot = root.ReplaceNode(classDecl, newClassDecl); + var attribute = generator.Attribute(WellKnownTypeNames.MicrosoftCodeAnalysisDiagnosticsDiagnosticAnalyzerAttribute, arguments); + var newClassDecl = generator.AddAttributes(classDecl, attribute); + var newRoot = root.ReplaceNode(classDecl, newClassDecl); return Task.FromResult(document.WithSyntaxRoot(newRoot)); } diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/CompareSymbolsCorrectlyFix.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/CompareSymbolsCorrectlyFix.cs index f1f80bf8c27ea..829ec829b11cf 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/CompareSymbolsCorrectlyFix.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/CompareSymbolsCorrectlyFix.cs @@ -14,6 +14,7 @@ using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Operations; +using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers.Fixers @@ -21,7 +22,7 @@ namespace Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers.Fixers public abstract class CompareSymbolsCorrectlyFix : CodeFixProvider { public sealed override ImmutableArray FixableDiagnosticIds { get; } = - ImmutableArray.Create(DiagnosticIds.CompareSymbolsCorrectlyRuleId); + [DiagnosticIds.CompareSymbolsCorrectlyRuleId]; protected abstract SyntaxNode CreateConditionalAccessExpression(SyntaxNode expression, SyntaxNode whenNotNull); @@ -91,7 +92,7 @@ private async Task CallOverloadWithEqualityComparerAsync(Document docu return rawOperation switch { - IObjectCreationOperation objectCreation => + IObjectCreationOperation objectCreation when objectCreation.Type != null => await CallOverloadWithEqualityComparerAsync( document, objectCreation.Syntax, objectCreation.Constructor, objectCreation.Arguments, isUsedAsExtensionMethod: false, (generator, args) => generator.ObjectCreationExpression(objectCreation.Type, args), iEqualityComparer, cancellationToken) @@ -243,7 +244,7 @@ private IEnumerable GetNewInvocationArguments(IInvocationOperation i ? CreateConditionalAccessExpression(conditionalAccessMembers[1], conditionalAccessMembers[0]) : conditionalAccessMembers[0]; - for (int i = 2; i < conditionalAccessMembers.Count - 1; i++) + for (var i = 2; i < conditionalAccessMembers.Count - 1; i++) { currentExpression = CreateConditionalAccessExpression(conditionalAccessMembers[i], currentExpression); } diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ConfigureGeneratedCodeAnalysisFix.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ConfigureGeneratedCodeAnalysisFix.cs index 0dc933b4d7378..fb253eb9fc60c 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ConfigureGeneratedCodeAnalysisFix.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ConfigureGeneratedCodeAnalysisFix.cs @@ -13,13 +13,14 @@ using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; +using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers.Fixers { public abstract class ConfigureGeneratedCodeAnalysisFix : CodeFixProvider { - public override ImmutableArray FixableDiagnosticIds { get; } = ImmutableArray.Create(ConfigureGeneratedCodeAnalysisAnalyzer.Rule.Id); + public override ImmutableArray FixableDiagnosticIds { get; } = [ConfigureGeneratedCodeAnalysisAnalyzer.Rule.Id]; public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/DefineDiagnosticDescriptorArgumentsCorrectlyFix.CustomFixAllProvider.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/DefineDiagnosticDescriptorArgumentsCorrectlyFix.CustomFixAllProvider.cs index 38405672e7ee1..ec6c6a9827065 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/DefineDiagnosticDescriptorArgumentsCorrectlyFix.CustomFixAllProvider.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/DefineDiagnosticDescriptorArgumentsCorrectlyFix.CustomFixAllProvider.cs @@ -9,10 +9,11 @@ using System.Threading; using System.Threading.Tasks; using Analyzer.Utilities; -using Analyzer.Utilities.PooledObjects; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers.Fixers { @@ -128,8 +129,8 @@ public FixAllAdditionalDocumentChangeAction(FixAllScope fixAllScope, Solution so var fixInfos = kvp.Value; var text = await additionalDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); - using var textChanges = ArrayBuilder.GetInstance(fixInfos.Count); - using var seenInputSpansToFix = PooledHashSet.GetInstance(); + using var _1 = ArrayBuilder.GetInstance(fixInfos.Count, out var textChanges); + using var _2 = PooledHashSet.GetInstance(out var seenInputSpansToFix); foreach (var fixInfo in fixInfos) { var inputSpanToFix = fixInfo.AdditionalDocumentSpanToFix!.Value; diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/DefineDiagnosticDescriptorArgumentsCorrectlyFix.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/DefineDiagnosticDescriptorArgumentsCorrectlyFix.cs index 8d476ef883ab0..b6d0f5a5d9823 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/DefineDiagnosticDescriptorArgumentsCorrectlyFix.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/DefineDiagnosticDescriptorArgumentsCorrectlyFix.cs @@ -9,12 +9,13 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using Analyzer.Utilities; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Operations; +using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers.Fixers { @@ -27,9 +28,11 @@ public sealed partial class DefineDiagnosticDescriptorArgumentsCorrectlyFix() : private const string AdditionalDocumentEquivalenceKeySuffix = nameof(AdditionalDocumentEquivalenceKeySuffix); public override ImmutableArray FixableDiagnosticIds { get; } = - ImmutableArray.Create(DiagnosticIds.DefineDiagnosticTitleCorrectlyRuleId, - DiagnosticIds.DefineDiagnosticMessageCorrectlyRuleId, - DiagnosticIds.DefineDiagnosticDescriptionCorrectlyRuleId); + [ + DiagnosticIds.DefineDiagnosticTitleCorrectlyRuleId, + DiagnosticIds.DefineDiagnosticMessageCorrectlyRuleId, + DiagnosticIds.DefineDiagnosticDescriptionCorrectlyRuleId, + ]; public override FixAllProvider GetFixAllProvider() => CustomFixAllProvider.Instance; diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/EnableConcurrentExecutionFix.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/EnableConcurrentExecutionFix.cs index bf82669cf1def..bd56a0fd5dade 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/EnableConcurrentExecutionFix.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/EnableConcurrentExecutionFix.cs @@ -12,13 +12,14 @@ using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; +using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers.Fixers { public abstract class EnableConcurrentExecutionFix : CodeFixProvider { - public override ImmutableArray FixableDiagnosticIds { get; } = ImmutableArray.Create(EnableConcurrentExecutionAnalyzer.Rule.Id); + public override ImmutableArray FixableDiagnosticIds { get; } = [EnableConcurrentExecutionAnalyzer.Rule.Id]; public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Helpers/DiagnosticWellKnownNames.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Helpers/DiagnosticWellKnownNames.cs index 1cf75aeaeaf68..922f3132c659f 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Helpers/DiagnosticWellKnownNames.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Helpers/DiagnosticWellKnownNames.cs @@ -11,7 +11,7 @@ internal static class DiagnosticWellKnownNames internal const string RegisterSyntaxNodeActionName = nameof(AnalysisContext.RegisterSyntaxNodeAction); internal const string RegisterSymbolActionName = nameof(AnalysisContext.RegisterSymbolAction); internal const string RegisterCodeBlockStartActionName = nameof(AnalysisContext.RegisterCodeBlockStartAction); - internal const string RegisterCodeBlockEndActionName = nameof(CodeBlockStartAnalysisContext.RegisterCodeBlockEndAction); + internal const string RegisterCodeBlockEndActionName = nameof(CodeBlockStartAnalysisContext<>.RegisterCodeBlockEndAction); internal const string RegisterCodeBlockActionName = nameof(AnalysisContext.RegisterCodeBlockAction); internal const string RegisterOperationBlockStartActionName = nameof(AnalysisContext.RegisterOperationBlockStartAction); internal const string RegisterOperationBlockEndActionName = nameof(OperationBlockStartAnalysisContext.RegisterOperationBlockEndAction); diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/ReleaseTrackingHelper.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/ReleaseTrackingHelper.cs index 5638ee77500c7..ef32e70bf359a 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/ReleaseTrackingHelper.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/ReleaseTrackingHelper.cs @@ -10,8 +10,9 @@ using System.Linq; using System.Text.RegularExpressions; using Analyzer.Utilities; -using Analyzer.Utilities.PooledObjects; +using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; #if MICROSOFT_CODEANALYSIS_ANALYZERS using Analyzer.Utilities.Extensions; @@ -51,7 +52,7 @@ internal static ReleaseTrackingData ReadReleaseTrackingData( var currentVersion = UnshippedVersion; ReleaseTrackingHeaderKind? expectedHeaderKind = isShippedFile ? ReleaseTrackingHeaderKind.ReleaseHeader : ReleaseTrackingHeaderKind.TableHeaderTitle; ReleaseTrackingRuleEntryKind? currentRuleEntryKind = null; - using var versionsBuilder = PooledHashSet.GetInstance(); + using var _ = PooledHashSet.GetInstance(out var versionsBuilder); foreach (TextLine line in sourceText.Lines) { @@ -247,7 +248,7 @@ internal static ReleaseTrackingData ReadReleaseTrackingData( builder.Add(ruleId, releaseTrackingDataForRule); } - return new ReleaseTrackingData(builder.ToImmutable(), versionsBuilder.ToImmutable()); + return new ReleaseTrackingData(builder.ToImmutable(), [.. versionsBuilder]); // Local functions void OnInvalidEntry(TextLine line, InvalidEntryKind invalidEntryKind) diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/ReportDiagnosticAnalyzer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/ReportDiagnosticAnalyzer.cs index 33010ebba2241..042df3d01f23d 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/ReportDiagnosticAnalyzer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/ReportDiagnosticAnalyzer.cs @@ -12,6 +12,7 @@ using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers.Helpers; using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers { diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/SymbolIsBannedInAnalyzersAnalyzer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/SymbolIsBannedInAnalyzersAnalyzer.cs index f5c7367e1f5e3..8a66d413ad1c0 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/SymbolIsBannedInAnalyzersAnalyzer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/SymbolIsBannedInAnalyzersAnalyzer.cs @@ -88,7 +88,7 @@ void analyzePossibleAnalyzerOrGenerator(SymbolAnalysisContext symbolAnalysisCont if (propertyValue != "true") return null; - const string fileName = "Microsoft.CodeAnalysis.Analyzers.AnalyzerBannedSymbols.txt"; + const string fileName = "Microsoft.CodeAnalysis.AnalyzerBannedSymbols.txt"; using var stream = typeof(SymbolIsBannedInAnalyzersAnalyzer<>).Assembly.GetManifestResourceStream(fileName); var source = SourceText.From(stream); diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/Microsoft.CodeAnalysis.Analyzers.csproj b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/Microsoft.CodeAnalysis.Analyzers.csproj index f98d0063fd11f..9e24594133662 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/Microsoft.CodeAnalysis.Analyzers.csproj +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/Microsoft.CodeAnalysis.Analyzers.csproj @@ -8,12 +8,22 @@ Restore would conclude that there is a cyclic dependency between Microsoft.CodeAnalysis and Microsoft.CodeAnalysis.Analyzers. --> *$(MSBuildProjectFile)* - $(MicrosoftCodeAnalysisVersionForCodeAnalysisAnalyzers) + Microsoft.CodeAnalysis - - - - + + + + + + + + + + + + + + @@ -32,4 +42,13 @@ + + + + + + + + + diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/UpgradeMSBuildWorkspaceAnalyzer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/UpgradeMSBuildWorkspaceAnalyzer.cs index 8fd52640db656..7c61b7d6b9ed7 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/UpgradeMSBuildWorkspaceAnalyzer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/UpgradeMSBuildWorkspaceAnalyzer.cs @@ -5,9 +5,10 @@ using System.Collections.Immutable; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; +using Microsoft.CodeAnalysis.Analyzers; using Microsoft.CodeAnalysis.Diagnostics; -namespace Microsoft.CodeAnalysis.Analyzers +namespace Microsoft.CodeAnalysis { using static CodeAnalysisDiagnosticsResources; diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/FixAnalyzers/FixerWithFixAllAnalyzerTests.Fixer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/FixAnalyzers/FixerWithFixAllAnalyzerTests.Fixer.cs index fcb42175bea21..7b25abe6b58ff 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/FixAnalyzers/FixerWithFixAllAnalyzerTests.Fixer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/FixAnalyzers/FixerWithFixAllAnalyzerTests.Fixer.cs @@ -18,566 +18,538 @@ public class FixerWithFixAllFixerTests #region CSharp tests [Fact] - public async Task CSharp_VerifyFix_NonSealedTypeAsync() - { - var source = @" -using System; -using System.Collections.Immutable; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CodeActions; - -[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C1))] -class {|RS1016:C1|} : CodeFixProvider -{ - public override ImmutableArray FixableDiagnosticIds - { - get - { - throw new NotImplementedException(); - } - } - - public override Task RegisterCodeFixesAsync(CodeFixContext context) - { - var codeAction1_1 = CodeAction.Create(""Title1_1"", _ => Task.FromResult(context.Document)); - return null; - } -} -"; - var fixedSource = @" -using System; -using System.Collections.Immutable; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CodeActions; - -[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C1))] -class C1 : CodeFixProvider -{ - public override ImmutableArray FixableDiagnosticIds - { - get - { - throw new NotImplementedException(); - } - } - - public override Task RegisterCodeFixesAsync(CodeFixContext context) - { - var codeAction1_1 = {|RS1010:CodeAction.Create(""Title1_1"", _ => Task.FromResult(context.Document))|}; - return null; - } - - public sealed override FixAllProvider GetFixAllProvider() - { - return WellKnownFixAllProviders.BatchFixer; - } -} -"; - - await VerifyCS.VerifyCodeFixAsync(source, fixedSource); - } + public Task CSharp_VerifyFix_NonSealedTypeAsync() + => VerifyCS.VerifyCodeFixAsync(""" + using System; + using System.Collections.Immutable; + using System.Threading.Tasks; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CodeActions; + + [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C1))] + class {|RS1016:C1|} : CodeFixProvider + { + public override ImmutableArray FixableDiagnosticIds + { + get + { + throw new NotImplementedException(); + } + } + + public override Task RegisterCodeFixesAsync(CodeFixContext context) + { + var codeAction1_1 = CodeAction.Create("Title1_1", _ => Task.FromResult(context.Document)); + return null; + } + } + """, """ + using System; + using System.Collections.Immutable; + using System.Threading.Tasks; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CodeActions; + + [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C1))] + class C1 : CodeFixProvider + { + public override ImmutableArray FixableDiagnosticIds + { + get + { + throw new NotImplementedException(); + } + } + + public override Task RegisterCodeFixesAsync(CodeFixContext context) + { + var codeAction1_1 = {|RS1010:CodeAction.Create("Title1_1", _ => Task.FromResult(context.Document))|}; + return null; + } + + public sealed override FixAllProvider GetFixAllProvider() + { + return WellKnownFixAllProviders.BatchFixer; + } + } + """); [Fact] - public async Task CSharp_VerifyFix_SealedTypeAsync() - { - var source = @" -using System; -using System.Collections.Immutable; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CodeActions; - -[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C1))] -sealed class {|RS1016:C1|} : CodeFixProvider -{ - public override ImmutableArray FixableDiagnosticIds - { - get - { - throw new NotImplementedException(); - } - } - - public override Task RegisterCodeFixesAsync(CodeFixContext context) - { - var codeAction1_1 = CodeAction.Create(""Title1_1"", _ => Task.FromResult(context.Document)); - return null; - } -} -"; - var fixedSource = @" -using System; -using System.Collections.Immutable; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CodeActions; - -[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C1))] -sealed class C1 : CodeFixProvider -{ - public override ImmutableArray FixableDiagnosticIds - { - get - { - throw new NotImplementedException(); - } - } - - public override Task RegisterCodeFixesAsync(CodeFixContext context) - { - var codeAction1_1 = {|RS1010:CodeAction.Create(""Title1_1"", _ => Task.FromResult(context.Document))|}; - return null; - } - - public override FixAllProvider GetFixAllProvider() - { - return WellKnownFixAllProviders.BatchFixer; - } -} -"; - - await VerifyCS.VerifyCodeFixAsync(source, fixedSource); - } + public Task CSharp_VerifyFix_SealedTypeAsync() + => VerifyCS.VerifyCodeFixAsync(""" + using System; + using System.Collections.Immutable; + using System.Threading.Tasks; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CodeActions; + + [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C1))] + sealed class {|RS1016:C1|} : CodeFixProvider + { + public override ImmutableArray FixableDiagnosticIds + { + get + { + throw new NotImplementedException(); + } + } + + public override Task RegisterCodeFixesAsync(CodeFixContext context) + { + var codeAction1_1 = CodeAction.Create("Title1_1", _ => Task.FromResult(context.Document)); + return null; + } + } + """, """ + using System; + using System.Collections.Immutable; + using System.Threading.Tasks; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CodeActions; + + [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C1))] + sealed class C1 : CodeFixProvider + { + public override ImmutableArray FixableDiagnosticIds + { + get + { + throw new NotImplementedException(); + } + } + + public override Task RegisterCodeFixesAsync(CodeFixContext context) + { + var codeAction1_1 = {|RS1010:CodeAction.Create("Title1_1", _ => Task.FromResult(context.Document))|}; + return null; + } + + public override FixAllProvider GetFixAllProvider() + { + return WellKnownFixAllProviders.BatchFixer; + } + } + """); [Fact] public async Task CSharp_NoDiagnosticAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CodeActions; - -[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C1))] -class C1 : CodeFixProvider -{ - public override ImmutableArray FixableDiagnosticIds - { - get - { - throw new NotImplementedException(); - } - } - - public override FixAllProvider GetFixAllProvider() - { - return WellKnownFixAllProviders.BatchFixer; - } - - public override Task RegisterCodeFixesAsync(CodeFixContext context) - { - var codeAction1_1 = {|RS1010:CodeAction.Create(""Title1_1"", _ => Task.FromResult(context.Document))|}; - return null; - } -} - -[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C2))] -class C2 : CodeFixProvider -{ - public override ImmutableArray FixableDiagnosticIds - { - get - { - throw new NotImplementedException(); - } - } - - public override FixAllProvider GetFixAllProvider() - { - return null; - } - - public override Task RegisterCodeFixesAsync(CodeFixContext context) - { - var codeAction1_1 = {|RS1010:CodeAction.Create(""Title1_1"", _ => Task.FromResult(context.Document))|}; - return null; - } -} -"; + var source = """ + using System; + using System.Collections.Immutable; + using System.Threading.Tasks; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CodeActions; + + [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C1))] + class C1 : CodeFixProvider + { + public override ImmutableArray FixableDiagnosticIds + { + get + { + throw new NotImplementedException(); + } + } + + public override FixAllProvider GetFixAllProvider() + { + return WellKnownFixAllProviders.BatchFixer; + } + + public override Task RegisterCodeFixesAsync(CodeFixContext context) + { + var codeAction1_1 = {|RS1010:CodeAction.Create("Title1_1", _ => Task.FromResult(context.Document))|}; + return null; + } + } + + [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C2))] + class C2 : CodeFixProvider + { + public override ImmutableArray FixableDiagnosticIds + { + get + { + throw new NotImplementedException(); + } + } + + public override FixAllProvider GetFixAllProvider() + { + return null; + } + + public override Task RegisterCodeFixesAsync(CodeFixContext context) + { + var codeAction1_1 = {|RS1010:CodeAction.Create("Title1_1", _ => Task.FromResult(context.Document))|}; + return null; + } + } + """; await VerifyCS.VerifyCodeFixAsync(source, source); } [Fact] - public async Task CSharp_VerifyFixAllAsync() - { - var source = @" -using System; -using System.Collections.Immutable; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CodeActions; - -[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C1))] -sealed class {|RS1016:C1|} : CodeFixProvider -{ - public override ImmutableArray FixableDiagnosticIds - { - get - { - throw new NotImplementedException(); - } - } - - public override Task RegisterCodeFixesAsync(CodeFixContext context) - { - var codeAction1_1 = CodeAction.Create(""Title1_1"", _ => Task.FromResult(context.Document)); - return null; - } -} - -[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C2))] -sealed class {|RS1016:C2|} : CodeFixProvider -{ - public override ImmutableArray FixableDiagnosticIds - { - get - { - throw new NotImplementedException(); - } - } - - public override Task RegisterCodeFixesAsync(CodeFixContext context) - { - var codeAction1_1 = CodeAction.Create(""Title1_1"", _ => Task.FromResult(context.Document)); - return null; - } -} -"; - var fixedSource = @" -using System; -using System.Collections.Immutable; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CodeActions; - -[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C1))] -sealed class C1 : CodeFixProvider -{ - public override ImmutableArray FixableDiagnosticIds - { - get - { - throw new NotImplementedException(); - } - } - - public override Task RegisterCodeFixesAsync(CodeFixContext context) - { - var codeAction1_1 = {|RS1010:CodeAction.Create(""Title1_1"", _ => Task.FromResult(context.Document))|}; - return null; - } - - public override FixAllProvider GetFixAllProvider() - { - return WellKnownFixAllProviders.BatchFixer; - } -} - -[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C2))] -sealed class C2 : CodeFixProvider -{ - public override ImmutableArray FixableDiagnosticIds - { - get - { - throw new NotImplementedException(); - } - } - - public override Task RegisterCodeFixesAsync(CodeFixContext context) - { - var codeAction1_1 = {|RS1010:CodeAction.Create(""Title1_1"", _ => Task.FromResult(context.Document))|}; - return null; - } - - public override FixAllProvider GetFixAllProvider() - { - return WellKnownFixAllProviders.BatchFixer; - } -} -"; - - await VerifyCS.VerifyCodeFixAsync(source, fixedSource); - } + public Task CSharp_VerifyFixAllAsync() + => VerifyCS.VerifyCodeFixAsync(""" + using System; + using System.Collections.Immutable; + using System.Threading.Tasks; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CodeActions; + + [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C1))] + sealed class {|RS1016:C1|} : CodeFixProvider + { + public override ImmutableArray FixableDiagnosticIds + { + get + { + throw new NotImplementedException(); + } + } + + public override Task RegisterCodeFixesAsync(CodeFixContext context) + { + var codeAction1_1 = CodeAction.Create("Title1_1", _ => Task.FromResult(context.Document)); + return null; + } + } + + [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C2))] + sealed class {|RS1016:C2|} : CodeFixProvider + { + public override ImmutableArray FixableDiagnosticIds + { + get + { + throw new NotImplementedException(); + } + } + + public override Task RegisterCodeFixesAsync(CodeFixContext context) + { + var codeAction1_1 = CodeAction.Create("Title1_1", _ => Task.FromResult(context.Document)); + return null; + } + } + """, """ + using System; + using System.Collections.Immutable; + using System.Threading.Tasks; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CodeActions; + + [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C1))] + sealed class C1 : CodeFixProvider + { + public override ImmutableArray FixableDiagnosticIds + { + get + { + throw new NotImplementedException(); + } + } + + public override Task RegisterCodeFixesAsync(CodeFixContext context) + { + var codeAction1_1 = {|RS1010:CodeAction.Create("Title1_1", _ => Task.FromResult(context.Document))|}; + return null; + } + + public override FixAllProvider GetFixAllProvider() + { + return WellKnownFixAllProviders.BatchFixer; + } + } + + [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C2))] + sealed class C2 : CodeFixProvider + { + public override ImmutableArray FixableDiagnosticIds + { + get + { + throw new NotImplementedException(); + } + } + + public override Task RegisterCodeFixesAsync(CodeFixContext context) + { + var codeAction1_1 = {|RS1010:CodeAction.Create("Title1_1", _ => Task.FromResult(context.Document))|}; + return null; + } + + public override FixAllProvider GetFixAllProvider() + { + return WellKnownFixAllProviders.BatchFixer; + } + } + """); #endregion #region VisualBasic tests [Fact()] - public async Task VisualBasic_VerifyFix_NonSealedTypeAsync() - { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports System.Threading.Tasks -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.CodeActions - - -Class {|RS1016:C1|} - Inherits CodeFixProvider - Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task - ' Regular cases. - Dim codeAction1_1 = CodeAction.Create(""Title1_1"", Function(x) Task.FromResult(context.Document)) - Return Nothing - End Function -End Class -"; - var fixedSource = @" -Imports System -Imports System.Collections.Immutable -Imports System.Threading.Tasks -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.CodeActions - - -Class C1 - Inherits CodeFixProvider - Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task - ' Regular cases. - Dim codeAction1_1 = {|RS1010:CodeAction.Create(""Title1_1"", Function(x) Task.FromResult(context.Document))|} - Return Nothing - End Function - - Public NotOverridable Overrides Function GetFixAllProvider() As FixAllProvider - Return WellKnownFixAllProviders.BatchFixer - End Function -End Class -"; - await VerifyVB.VerifyCodeFixAsync(source, fixedSource); - } + public Task VisualBasic_VerifyFix_NonSealedTypeAsync() + => VerifyVB.VerifyCodeFixAsync(""" + Imports System + Imports System.Collections.Immutable + Imports System.Threading.Tasks + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.CodeFixes + Imports Microsoft.CodeAnalysis.CodeActions + + + Class {|RS1016:C1|} + Inherits CodeFixProvider + Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task + ' Regular cases. + Dim codeAction1_1 = CodeAction.Create("Title1_1", Function(x) Task.FromResult(context.Document)) + Return Nothing + End Function + End Class + """, """ + Imports System + Imports System.Collections.Immutable + Imports System.Threading.Tasks + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.CodeFixes + Imports Microsoft.CodeAnalysis.CodeActions + + + Class C1 + Inherits CodeFixProvider + Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task + ' Regular cases. + Dim codeAction1_1 = {|RS1010:CodeAction.Create("Title1_1", Function(x) Task.FromResult(context.Document))|} + Return Nothing + End Function + + Public NotOverridable Overrides Function GetFixAllProvider() As FixAllProvider + Return WellKnownFixAllProviders.BatchFixer + End Function + End Class + """); [Fact] - public async Task VisualBasic_VerifyFix_SealedTypeAsync() - { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports System.Threading.Tasks -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.CodeActions - - -NotInheritable Class {|RS1016:C1|} - Inherits CodeFixProvider - Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task - ' Regular cases. - Dim codeAction1_1 = CodeAction.Create(""Title1_1"", Function(x) Task.FromResult(context.Document)) - Return Nothing - End Function -End Class -"; - var fixedSource = @" -Imports System -Imports System.Collections.Immutable -Imports System.Threading.Tasks -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.CodeActions - - -NotInheritable Class C1 - Inherits CodeFixProvider - Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task - ' Regular cases. - Dim codeAction1_1 = {|RS1010:CodeAction.Create(""Title1_1"", Function(x) Task.FromResult(context.Document))|} - Return Nothing - End Function - - Public Overrides Function GetFixAllProvider() As FixAllProvider - Return WellKnownFixAllProviders.BatchFixer - End Function -End Class -"; - await VerifyVB.VerifyCodeFixAsync(source, fixedSource); - } + public Task VisualBasic_VerifyFix_SealedTypeAsync() + => VerifyVB.VerifyCodeFixAsync(""" + Imports System + Imports System.Collections.Immutable + Imports System.Threading.Tasks + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.CodeFixes + Imports Microsoft.CodeAnalysis.CodeActions + + + NotInheritable Class {|RS1016:C1|} + Inherits CodeFixProvider + Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task + ' Regular cases. + Dim codeAction1_1 = CodeAction.Create("Title1_1", Function(x) Task.FromResult(context.Document)) + Return Nothing + End Function + End Class + """, """ + Imports System + Imports System.Collections.Immutable + Imports System.Threading.Tasks + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.CodeFixes + Imports Microsoft.CodeAnalysis.CodeActions + + + NotInheritable Class C1 + Inherits CodeFixProvider + Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task + ' Regular cases. + Dim codeAction1_1 = {|RS1010:CodeAction.Create("Title1_1", Function(x) Task.FromResult(context.Document))|} + Return Nothing + End Function + + Public Overrides Function GetFixAllProvider() As FixAllProvider + Return WellKnownFixAllProviders.BatchFixer + End Function + End Class + """); [Fact] public async Task VisualBasic_NoDiagnosticAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports System.Threading.Tasks -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.CodeActions - - -Class C1 - Inherits CodeFixProvider - Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task - ' Regular cases. - Dim codeAction1_1 = {|RS1010:CodeAction.Create(""Title1_1"", Function(x) Task.FromResult(context.Document))|} - Return Nothing - End Function - - Public Overrides Function GetFixAllProvider() As FixAllProvider - Return WellKnownFixAllProviders.BatchFixer - End Function -End Class - - -Class C2 - Inherits CodeFixProvider - Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task - ' Regular cases. - Dim codeAction1_1 = {|RS1010:CodeAction.Create(""Title1_1"", Function(x) Task.FromResult(context.Document))|} - Return Nothing - End Function - - Public Overrides Function GetFixAllProvider() As FixAllProvider - Return Nothing - End Function -End Class -"; + var source = """ + Imports System + Imports System.Collections.Immutable + Imports System.Threading.Tasks + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.CodeFixes + Imports Microsoft.CodeAnalysis.CodeActions + + + Class C1 + Inherits CodeFixProvider + Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task + ' Regular cases. + Dim codeAction1_1 = {|RS1010:CodeAction.Create("Title1_1", Function(x) Task.FromResult(context.Document))|} + Return Nothing + End Function + + Public Overrides Function GetFixAllProvider() As FixAllProvider + Return WellKnownFixAllProviders.BatchFixer + End Function + End Class + + + Class C2 + Inherits CodeFixProvider + Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task + ' Regular cases. + Dim codeAction1_1 = {|RS1010:CodeAction.Create("Title1_1", Function(x) Task.FromResult(context.Document))|} + Return Nothing + End Function + + Public Overrides Function GetFixAllProvider() As FixAllProvider + Return Nothing + End Function + End Class + """; await VerifyVB.VerifyCodeFixAsync(source, source); } [Fact] - public async Task VisualBasic_VerifyFixAllAsync() - { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports System.Threading.Tasks -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.CodeActions - - -NotInheritable Class {|RS1016:C1|} - Inherits CodeFixProvider - Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task - ' Regular cases. - Dim codeAction1_1 = CodeAction.Create(""Title1_1"", Function(x) Task.FromResult(context.Document)) - Return Nothing - End Function -End Class - - -NotInheritable Class {|RS1016:C2|} - Inherits CodeFixProvider - Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task - ' Regular cases. - Dim codeAction1_1 = CodeAction.Create(""Title1_1"", Function(x) Task.FromResult(context.Document)) - Return Nothing - End Function -End Class -"; - var fixedSource = @" -Imports System -Imports System.Collections.Immutable -Imports System.Threading.Tasks -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.CodeActions - - -NotInheritable Class C1 - Inherits CodeFixProvider - Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task - ' Regular cases. - Dim codeAction1_1 = {|RS1010:CodeAction.Create(""Title1_1"", Function(x) Task.FromResult(context.Document))|} - Return Nothing - End Function - - Public Overrides Function GetFixAllProvider() As FixAllProvider - Return WellKnownFixAllProviders.BatchFixer - End Function -End Class - - -NotInheritable Class C2 - Inherits CodeFixProvider - Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task - ' Regular cases. - Dim codeAction1_1 = {|RS1010:CodeAction.Create(""Title1_1"", Function(x) Task.FromResult(context.Document))|} - Return Nothing - End Function - - Public Overrides Function GetFixAllProvider() As FixAllProvider - Return WellKnownFixAllProviders.BatchFixer - End Function -End Class -"; - - await VerifyVB.VerifyCodeFixAsync(source, fixedSource); - } + public Task VisualBasic_VerifyFixAllAsync() + => VerifyVB.VerifyCodeFixAsync(""" + Imports System + Imports System.Collections.Immutable + Imports System.Threading.Tasks + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.CodeFixes + Imports Microsoft.CodeAnalysis.CodeActions + + + NotInheritable Class {|RS1016:C1|} + Inherits CodeFixProvider + Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task + ' Regular cases. + Dim codeAction1_1 = CodeAction.Create("Title1_1", Function(x) Task.FromResult(context.Document)) + Return Nothing + End Function + End Class + + + NotInheritable Class {|RS1016:C2|} + Inherits CodeFixProvider + Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task + ' Regular cases. + Dim codeAction1_1 = CodeAction.Create("Title1_1", Function(x) Task.FromResult(context.Document)) + Return Nothing + End Function + End Class + """, """ + Imports System + Imports System.Collections.Immutable + Imports System.Threading.Tasks + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.CodeFixes + Imports Microsoft.CodeAnalysis.CodeActions + + + NotInheritable Class C1 + Inherits CodeFixProvider + Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task + ' Regular cases. + Dim codeAction1_1 = {|RS1010:CodeAction.Create("Title1_1", Function(x) Task.FromResult(context.Document))|} + Return Nothing + End Function + + Public Overrides Function GetFixAllProvider() As FixAllProvider + Return WellKnownFixAllProviders.BatchFixer + End Function + End Class + + + NotInheritable Class C2 + Inherits CodeFixProvider + Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task + ' Regular cases. + Dim codeAction1_1 = {|RS1010:CodeAction.Create("Title1_1", Function(x) Task.FromResult(context.Document))|} + Return Nothing + End Function + + Public Overrides Function GetFixAllProvider() As FixAllProvider + Return WellKnownFixAllProviders.BatchFixer + End Function + End Class + """); #endregion } diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/FixAnalyzers/FixerWithFixAllAnalyzerTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/FixAnalyzers/FixerWithFixAllAnalyzerTests.cs index 2390c083e2d81..3f4e771bc0e5a 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/FixAnalyzers/FixerWithFixAllAnalyzerTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/FixAnalyzers/FixerWithFixAllAnalyzerTests.cs @@ -22,70 +22,76 @@ public class FixerWithFixAllAnalyzerTests { #region CSharp tests - private const string CSharpCustomCodeActions = @" -public class MyCodeActionNoEquivalenceKey : CodeAction -{ - public override string Title - { - get - { - throw new NotImplementedException(); - } - } -} + private const string CSharpCustomCodeActions = """ -public class MyCodeActionWithEquivalenceKey : CodeAction -{ - public override string Title - { - get - { - throw new NotImplementedException(); - } - } + public class MyCodeActionNoEquivalenceKey : CodeAction + { + public override string Title + { + get + { + throw new NotImplementedException(); + } + } + } - public override string EquivalenceKey - { - get - { - return ""DummyEquivalenceKey""; - } - } -} + public class MyCodeActionWithEquivalenceKey : CodeAction + { + public override string Title + { + get + { + throw new NotImplementedException(); + } + } -public abstract class MyAbstractCodeActionWithEquivalenceKey : CodeAction -{ - public override string Title - { - get - { - throw new NotImplementedException(); - } - } + public override string EquivalenceKey + { + get + { + return "DummyEquivalenceKey"; + } + } + } - public override string EquivalenceKey - { - get - { - return ""DummyEquivalenceKey""; - } - } -} + public abstract class MyAbstractCodeActionWithEquivalenceKey : CodeAction + { + public override string Title + { + get + { + throw new NotImplementedException(); + } + } -public class MyDerivedCodeActionWithEquivalenceKey : MyAbstractCodeActionWithEquivalenceKey -{ -} -"; + public override string EquivalenceKey + { + get + { + return "DummyEquivalenceKey"; + } + } + } + + public class MyDerivedCodeActionWithEquivalenceKey : MyAbstractCodeActionWithEquivalenceKey + { + } + + """; private async Task TestCSharpCoreAsync(string source, DiagnosticResult missingGetFixAllProviderOverrideDiagnostic, bool withCustomCodeActions = false, params DiagnosticResult[] expected) { - var fixAllProviderString = @"public override FixAllProvider GetFixAllProvider() - { - return WellKnownFixAllProviders.BatchFixer; - }"; + var fixAllProviderString = """ + public override FixAllProvider GetFixAllProvider() + { + return WellKnownFixAllProviders.BatchFixer; + } + """; + + var sourceSuffix = """ - var sourceSuffix = @" -}"; + } + """; if (withCustomCodeActions) { @@ -96,48 +102,13 @@ private async Task TestCSharpCoreAsync(string source, DiagnosticResult missingGe await VerifyCS.VerifyAnalyzerAsync(source + fixAllProviderString + sourceSuffix, expected); // Verify RS1016 (OverrideGetFixAllProviderRule) diagnostic for fixer that does not support FixAllProvider. - expected = new[] { missingGetFixAllProviderOverrideDiagnostic }; + expected = [missingGetFixAllProviderOverrideDiagnostic]; await VerifyCS.VerifyAnalyzerAsync(source + sourceSuffix, expected); } [Fact] public async Task CSharp_CodeActionCreate_VerifyDiagnosticsAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CodeActions; - -[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C1))] -class C1 : CodeFixProvider -{ - public override ImmutableArray FixableDiagnosticIds - { - get - { - throw new NotImplementedException(); - } - } - - public override Task RegisterCodeFixesAsync(CodeFixContext context) - { - // Regular cases. - var codeAction1_1 = CodeAction.Create(""Title1_1"", _ => Task.FromResult(context.Document)); - var codeAction1_2 = CodeAction.Create(""Title1_2"", createChangedDocument: _ => Task.FromResult(context.Document)); - var codeAction1_3 = CodeAction.Create(createChangedDocument: _ => Task.FromResult(context.Document), title: ""Title1_3""); - - // Null argument for equivalenceKey. - var codeAction2_1 = CodeAction.Create(""Title2_1"", _ => Task.FromResult(context.Document), null); - var codeAction2_2 = CodeAction.Create(createChangedDocument: _ => Task.FromResult(context.Document), equivalenceKey: null, title: ""Title2_2""); - var codeAction2_3 = CodeAction.Create(""Title2_3"", _ => Task.FromResult(context.Document), equivalenceKey: null); - - return null; - } -"; - var expected = new[] { // Test0.cs(23,29): warning RS1010: Provide an explicit argument for optional parameter 'equivalenceKey', which is non-null and unique across all code actions created by this fixer. @@ -156,105 +127,112 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) // Test0.cs(10,7): warning RS1016: 'C1' registers one or more code fixes, but does not override the method 'CodeFixProvider.GetFixAllProvider'. Override this method and provide a non-null FixAllProvider for FixAll support, potentially 'WellKnownFixAllProviders.BatchFixer', or 'null' to explicitly disable FixAll support. var missingGetFixAllProviderOverrideDiagnostic = GetCSharpOverrideGetFixAllProviderExpectedDiagnostic(10, 7, "C1"); - await TestCSharpCoreAsync(source, missingGetFixAllProviderOverrideDiagnostic, expected: expected); + await TestCSharpCoreAsync(""" + + using System; + using System.Collections.Immutable; + using System.Threading.Tasks; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CodeActions; + + [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C1))] + class C1 : CodeFixProvider + { + public override ImmutableArray FixableDiagnosticIds + { + get + { + throw new NotImplementedException(); + } + } + + public override Task RegisterCodeFixesAsync(CodeFixContext context) + { + // Regular cases. + var codeAction1_1 = CodeAction.Create("Title1_1", _ => Task.FromResult(context.Document)); + var codeAction1_2 = CodeAction.Create("Title1_2", createChangedDocument: _ => Task.FromResult(context.Document)); + var codeAction1_3 = CodeAction.Create(createChangedDocument: _ => Task.FromResult(context.Document), title: "Title1_3"); + + // Null argument for equivalenceKey. + var codeAction2_1 = CodeAction.Create("Title2_1", _ => Task.FromResult(context.Document), null); + var codeAction2_2 = CodeAction.Create(createChangedDocument: _ => Task.FromResult(context.Document), equivalenceKey: null, title: "Title2_2"); + var codeAction2_3 = CodeAction.Create("Title2_3", _ => Task.FromResult(context.Document), equivalenceKey: null); + + return null; + } + + """, missingGetFixAllProviderOverrideDiagnostic, expected: expected); } [Fact] public async Task CSharp_CodeActionCreate_NoDiagnosticsAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CodeActions; - -[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C1))] -class C1 : CodeFixProvider -{ - public override ImmutableArray FixableDiagnosticIds - { - get - { - throw new NotImplementedException(); - } - } - - public override Task RegisterCodeFixesAsync(CodeFixContext context) - { - // Overload resolution failure cases. - var codeAction1_1 = CodeAction.{|CS1501:Create|}(""Title1_1""); - var codeAction1_2 = CodeAction.{|CS7036:Create|}(createChangedDocument: _ => Task.FromResult(context.Document), equivalenceKey: null); - - // Correct non-null arguments - var equivalenceKey = ""equivalenceKey""; - var codeAction2_1 = CodeAction.Create(""Title2_1"", _ => Task.FromResult(context.Document), equivalenceKey); - var codeAction2_2 = CodeAction.Create(title: ""Title2_2"", createChangedDocument: _ => Task.FromResult(context.Document), equivalenceKey: equivalenceKey); - var codeAction2_3 = CodeAction.Create(equivalenceKey: equivalenceKey, title: ""Title2_3"", createChangedDocument: _ => Task.FromResult(context.Document)); - - // Conservative no diagnostic cases. - string nullKey = null; - var codeAction3_1 = CodeAction.Create(""Title3_1"", _ => Task.FromResult(context.Document), nullKey); - var codeAction3_2 = CodeAction.Create(""Title3_1"", _ => Task.FromResult(context.Document), GetKey()); - - context.RegisterCodeFix(codeAction1_1, context.Diagnostics); - context.RegisterCodeFix(codeAction1_2, context.Diagnostics); - - context.RegisterCodeFix(codeAction2_1, context.Diagnostics); - context.RegisterCodeFix(codeAction2_2, context.Diagnostics); - context.RegisterCodeFix(codeAction2_3, context.Diagnostics); - - context.RegisterCodeFix(codeAction3_1, context.Diagnostics); - context.RegisterCodeFix(codeAction3_2, context.Diagnostics); - - return null; - } - - private string GetKey() - { - return null; - } -"; // Test0.cs(10,7): warning RS1016: 'C1' registers one or more code fixes, but does not override the method 'CodeFixProvider.GetFixAllProvider'. Override this method and provide a non-null FixAllProvider for FixAll support, potentially 'WellKnownFixAllProviders.BatchFixer', or 'null' to explicitly disable FixAll support. var missingGetFixAllProviderOverrideDiagnostic = GetCSharpOverrideGetFixAllProviderExpectedDiagnostic(10, 7, "C1"); - await TestCSharpCoreAsync(source, missingGetFixAllProviderOverrideDiagnostic); + await TestCSharpCoreAsync(""" + + using System; + using System.Collections.Immutable; + using System.Threading.Tasks; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CodeActions; + + [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C1))] + class C1 : CodeFixProvider + { + public override ImmutableArray FixableDiagnosticIds + { + get + { + throw new NotImplementedException(); + } + } + + public override Task RegisterCodeFixesAsync(CodeFixContext context) + { + // Overload resolution failure cases. + var codeAction1_1 = CodeAction.{|CS1501:Create|}("Title1_1"); + var codeAction1_2 = CodeAction.{|CS7036:Create|}(createChangedDocument: _ => Task.FromResult(context.Document), equivalenceKey: null); + + // Correct non-null arguments + var equivalenceKey = "equivalenceKey"; + var codeAction2_1 = CodeAction.Create("Title2_1", _ => Task.FromResult(context.Document), equivalenceKey); + var codeAction2_2 = CodeAction.Create(title: "Title2_2", createChangedDocument: _ => Task.FromResult(context.Document), equivalenceKey: equivalenceKey); + var codeAction2_3 = CodeAction.Create(equivalenceKey: equivalenceKey, title: "Title2_3", createChangedDocument: _ => Task.FromResult(context.Document)); + + // Conservative no diagnostic cases. + string nullKey = null; + var codeAction3_1 = CodeAction.Create("Title3_1", _ => Task.FromResult(context.Document), nullKey); + var codeAction3_2 = CodeAction.Create("Title3_1", _ => Task.FromResult(context.Document), GetKey()); + + context.RegisterCodeFix(codeAction1_1, context.Diagnostics); + context.RegisterCodeFix(codeAction1_2, context.Diagnostics); + + context.RegisterCodeFix(codeAction2_1, context.Diagnostics); + context.RegisterCodeFix(codeAction2_2, context.Diagnostics); + context.RegisterCodeFix(codeAction2_3, context.Diagnostics); + + context.RegisterCodeFix(codeAction3_1, context.Diagnostics); + context.RegisterCodeFix(codeAction3_2, context.Diagnostics); + + return null; + } + + private string GetKey() + { + return null; + } + + """, missingGetFixAllProviderOverrideDiagnostic); } [Fact] public async Task CSharp_CodeActionCreate_DiagnosticsOnExportedCodeFixProviderTypeAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CodeActions; - -[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C2))] -class C2 : C1 -{ -} - -abstract class C1 : CodeFixProvider -{ - public override ImmutableArray FixableDiagnosticIds - { - get - { - throw new NotImplementedException(); - } - } - - public override Task RegisterCodeFixesAsync(CodeFixContext context) - { - var codeAction1_1 = CodeAction.Create(""Title1_1"", _ => Task.FromResult(context.Document)); - return null; - } -"; var expected = new[] { // Test0.cs(26,29): warning RS1010: Provide an explicit argument for optional parameter 'equivalenceKey', which is non-null and unique across all code actions created by this fixer. @@ -264,38 +242,42 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) // Test0.cs(10,16): warning RS1016: 'C1' registers one or more code fixes, but does not override the method 'CodeFixProvider.GetFixAllProvider'. Override this method and provide a non-null FixAllProvider for FixAll support, potentially 'WellKnownFixAllProviders.BatchFixer', or 'null' to explicitly disable FixAll support. var missingGetFixAllProviderOverrideDiagnostic = GetCSharpOverrideGetFixAllProviderExpectedDiagnostic(10, 7, "C2"); - await TestCSharpCoreAsync(source, missingGetFixAllProviderOverrideDiagnostic, expected: expected); + await TestCSharpCoreAsync(""" + + using System; + using System.Collections.Immutable; + using System.Threading.Tasks; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CodeActions; + + [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C2))] + class C2 : C1 + { + } + + abstract class C1 : CodeFixProvider + { + public override ImmutableArray FixableDiagnosticIds + { + get + { + throw new NotImplementedException(); + } + } + + public override Task RegisterCodeFixesAsync(CodeFixContext context) + { + var codeAction1_1 = CodeAction.Create("Title1_1", _ => Task.FromResult(context.Document)); + return null; + } + + """, missingGetFixAllProviderOverrideDiagnostic, expected: expected); } [Fact] public async Task CSharp_CustomCodeAction_VerifyDiagnosticsAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CodeActions; - -[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C1))] -class C1 : CodeFixProvider -{ - public override ImmutableArray FixableDiagnosticIds - { - get - { - throw new NotImplementedException(); - } - } - - public override Task RegisterCodeFixesAsync(CodeFixContext context) - { - var codeAction = new MyCodeActionNoEquivalenceKey(); - return null; - } -"; - var expected = new[] { // Test0.cs(22,26): warning RS1011: 'MyCodeActionNoEquivalenceKey' has the default value of 'null' for property 'EquivalenceKey'. Either override this property on 'MyCodeActionNoEquivalenceKey' to return a non-null and unique value across all code actions per-fixer or use such an existing code action. @@ -305,171 +287,204 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) // Test0.cs(10,7): warning RS1016: 'C1' registers one or more code fixes, but does not override the method 'CodeFixProvider.GetFixAllProvider'. Override this method and provide a non-null FixAllProvider for FixAll support, potentially 'WellKnownFixAllProviders.BatchFixer', or 'null' to explicitly disable FixAll support. var missingGetFixAllProviderOverrideDiagnostic = GetCSharpOverrideGetFixAllProviderExpectedDiagnostic(10, 7, "C1"); - await TestCSharpCoreAsync(source, missingGetFixAllProviderOverrideDiagnostic, withCustomCodeActions: true, expected: expected); + await TestCSharpCoreAsync(""" + + using System; + using System.Collections.Immutable; + using System.Threading.Tasks; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CodeActions; + + [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C1))] + class C1 : CodeFixProvider + { + public override ImmutableArray FixableDiagnosticIds + { + get + { + throw new NotImplementedException(); + } + } + + public override Task RegisterCodeFixesAsync(CodeFixContext context) + { + var codeAction = new MyCodeActionNoEquivalenceKey(); + return null; + } + + """, missingGetFixAllProviderOverrideDiagnostic, withCustomCodeActions: true, expected: expected); } [Fact] public async Task CSharp_CustomCodeAction_NoDiagnosticsAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CodeActions; - -[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C1))] -class C1 : CodeFixProvider -{ - public override ImmutableArray FixableDiagnosticIds - { - get - { - throw new NotImplementedException(); - } - } - - public override Task RegisterCodeFixesAsync(CodeFixContext context) - { - CodeAction codeAction = new MyCodeActionWithEquivalenceKey(); - context.RegisterCodeFix(codeAction, context.Diagnostics); - - codeAction = new MyDerivedCodeActionWithEquivalenceKey(); - context.RegisterCodeFix(codeAction, context.Diagnostics); - return null; - } - - private string GetKey() - { - return null; - } -"; // Test0.cs(10,7): warning RS1016: 'C1' registers one or more code fixes, but does not override the method 'CodeFixProvider.GetFixAllProvider'. Override this method and provide a non-null FixAllProvider for FixAll support, potentially 'WellKnownFixAllProviders.BatchFixer', or 'null' to explicitly disable FixAll support. var missingGetFixAllProviderOverrideDiagnostic = GetCSharpOverrideGetFixAllProviderExpectedDiagnostic(10, 7, "C1"); - await TestCSharpCoreAsync(source, missingGetFixAllProviderOverrideDiagnostic, withCustomCodeActions: true); + await TestCSharpCoreAsync(""" + + using System; + using System.Collections.Immutable; + using System.Threading.Tasks; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CodeActions; + + [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C1))] + class C1 : CodeFixProvider + { + public override ImmutableArray FixableDiagnosticIds + { + get + { + throw new NotImplementedException(); + } + } + + public override Task RegisterCodeFixesAsync(CodeFixContext context) + { + CodeAction codeAction = new MyCodeActionWithEquivalenceKey(); + context.RegisterCodeFix(codeAction, context.Diagnostics); + + codeAction = new MyDerivedCodeActionWithEquivalenceKey(); + context.RegisterCodeFix(codeAction, context.Diagnostics); + return null; + } + + private string GetKey() + { + return null; + } + + """, missingGetFixAllProviderOverrideDiagnostic, withCustomCodeActions: true); } [Fact, WorkItem(3475, "https://github.com/dotnet/roslyn-analyzers/issues/3475")] - public async Task CSharp_CodeActionCreateNestedActions_NoDiagnosticsAsync() - { - await new VerifyCS.Test + public Task CSharp_CodeActionCreateNestedActions_NoDiagnosticsAsync() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Default.AddPackages(ImmutableArray.Create(new PackageIdentity("Microsoft.CodeAnalysis", "3.3.0"))), - TestCode = @" -using System; -using System.Collections.Immutable; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CodeActions; - -[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C1))] -class C1 : CodeFixProvider -{ - public override ImmutableArray FixableDiagnosticIds - { - get - { - throw new NotImplementedException(); - } - } + TestCode = """ - public override FixAllProvider GetFixAllProvider() - { - throw new NotImplementedException(); - } + using System; + using System.Collections.Immutable; + using System.Threading.Tasks; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CodeActions; - public override Task RegisterCodeFixesAsync(CodeFixContext context) - { - var c1 = CodeAction.Create( - ""Title1"", - ImmutableArray.Create( - CodeAction.Create(""Title1_1"", _ => Task.FromResult(context.Document), equivalenceKey: ""Title1_1""), - {|#0:CodeAction.Create(""Title1_2"", _ => Task.FromResult(context.Document))|} - ), - false); - - var c2 = CodeAction.Create( - ""Title2"", - ImmutableArray.Create( - CodeAction.Create(""Title2_1"", _ => Task.FromResult(context.Document), equivalenceKey: ""Title2_1""), - {|#1:CodeAction.Create(""Title2_2"", _ => Task.FromResult(context.Document))|} - ), - true); - - return null; - } -}", + [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(C1))] + class C1 : CodeFixProvider + { + public override ImmutableArray FixableDiagnosticIds + { + get + { + throw new NotImplementedException(); + } + } + + public override FixAllProvider GetFixAllProvider() + { + throw new NotImplementedException(); + } + + public override Task RegisterCodeFixesAsync(CodeFixContext context) + { + var c1 = CodeAction.Create( + "Title1", + ImmutableArray.Create( + CodeAction.Create("Title1_1", _ => Task.FromResult(context.Document), equivalenceKey: "Title1_1"), + {|#0:CodeAction.Create("Title1_2", _ => Task.FromResult(context.Document))|} + ), + false); + + var c2 = CodeAction.Create( + "Title2", + ImmutableArray.Create( + CodeAction.Create("Title2_1", _ => Task.FromResult(context.Document), equivalenceKey: "Title2_1"), + {|#1:CodeAction.Create("Title2_2", _ => Task.FromResult(context.Document))|} + ), + true); + + return null; + } + } + """, ExpectedDiagnostics = { VerifyCS.Diagnostic(FixerWithFixAllAnalyzer.CreateCodeActionEquivalenceKeyRule).WithLocation(0).WithArguments("equivalenceKey"), VerifyCS.Diagnostic(FixerWithFixAllAnalyzer.CreateCodeActionEquivalenceKeyRule).WithLocation(1).WithArguments("equivalenceKey"), } }.RunAsync(); - } #endregion #region VisualBasic tests - private const string VisualBasicCustomCodeActions = @" - -Public Class MyCodeActionNoEquivalenceKey - Inherits CodeAction - Public Overrides ReadOnly Property Title() As String - Get - Throw New NotImplementedException() - End Get - End Property -End Class - -Public Class MyCodeActionWithEquivalenceKey - Inherits CodeAction - Public Overrides ReadOnly Property Title() As String - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides ReadOnly Property EquivalenceKey() As String - Get - Return ""DummyEquivalenceKey"" - End Get - End Property -End Class - -Public MustInherit Class MyAbstractCodeActionWithEquivalenceKey - Inherits CodeAction - Public Overrides ReadOnly Property Title() As String - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides ReadOnly Property EquivalenceKey() As String - Get - Return ""DummyEquivalenceKey"" - End Get - End Property -End Class - -Public Class MyDerivedCodeActionWithEquivalenceKey - Inherits MyAbstractCodeActionWithEquivalenceKey -End Class -"; + private const string VisualBasicCustomCodeActions = """ + + + Public Class MyCodeActionNoEquivalenceKey + Inherits CodeAction + Public Overrides ReadOnly Property Title() As String + Get + Throw New NotImplementedException() + End Get + End Property + End Class + + Public Class MyCodeActionWithEquivalenceKey + Inherits CodeAction + Public Overrides ReadOnly Property Title() As String + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides ReadOnly Property EquivalenceKey() As String + Get + Return "DummyEquivalenceKey" + End Get + End Property + End Class + + Public MustInherit Class MyAbstractCodeActionWithEquivalenceKey + Inherits CodeAction + Public Overrides ReadOnly Property Title() As String + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides ReadOnly Property EquivalenceKey() As String + Get + Return "DummyEquivalenceKey" + End Get + End Property + End Class + + Public Class MyDerivedCodeActionWithEquivalenceKey + Inherits MyAbstractCodeActionWithEquivalenceKey + End Class + + """; private async Task TestBasicCoreAsync(string source, DiagnosticResult missingGetFixAllProviderOverrideDiagnostic, bool withCustomCodeActions = false, params DiagnosticResult[] expected) { - var fixAllProviderString = @"Public Overrides Function GetFixAllProvider() As FixAllProvider - Return WellKnownFixAllProviders.BatchFixer -End Function -"; + var fixAllProviderString = """ + Public Overrides Function GetFixAllProvider() As FixAllProvider + Return WellKnownFixAllProviders.BatchFixer + End Function + + """; - var sourceSuffix = @" -End Class -"; + var sourceSuffix = """ + + End Class + + """; if (withCustomCodeActions) { @@ -480,45 +495,13 @@ End Class await VerifyVB.VerifyAnalyzerAsync(source + fixAllProviderString + sourceSuffix, expected); // Verify RS1016 (OverrideGetFixAllProviderRule) diagnostic for fixer that does not support FixAllProvider. - expected = new[] { missingGetFixAllProviderOverrideDiagnostic }; + expected = [missingGetFixAllProviderOverrideDiagnostic]; await VerifyVB.VerifyAnalyzerAsync(source + sourceSuffix, expected); } [Fact] public async Task VisualBasic_CodeActionCreate_VerifyDiagnosticsAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports System.Threading.Tasks -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.CodeActions - - -Class C1 - Inherits CodeFixProvider - Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task - ' Regular cases. - Dim codeAction1_1 = CodeAction.Create(""Title1_1"", Function(x) Task.FromResult(context.Document)) - Dim codeAction1_2 = CodeAction.Create(""Title1_2"", createChangedDocument := Function(x) Task.FromResult(context.Document)) - Dim codeAction1_3 = CodeAction.Create(createChangedDocument := Function(x) Task.FromResult(context.Document), title := ""Title1_3"") - - ' Null argument for equivalenceKey. - Dim codeAction2_1 = CodeAction.Create(""Title2_1"", Function(x) Task.FromResult(context.Document), Nothing) - Dim codeAction2_2 = CodeAction.Create(createChangedDocument := Function(x) Task.FromResult(context.Document), equivalenceKey := Nothing, title := ""Title2_2"") - Dim codeAction2_3 = CodeAction.Create(""Title2_3"", Function(x) Task.FromResult(context.Document), equivalenceKey := Nothing) - - Return Nothing - End Function -"; - var expected = new[] { // Test0.vb(20,23): warning RS1010: Provide an explicit argument for optional parameter 'equivalenceKey', which is non-null and unique across all code actions created by this fixer. @@ -538,101 +521,104 @@ End Function // Test0.vb(10,7): warning RS1016: 'C1' registers one or more code fixes, but does not override the method 'CodeFixProvider.GetFixAllProvider'. Override this method and provide a non-null FixAllProvider for FixAll support, potentially 'WellKnownFixAllProviders.BatchFixer', or 'null' to explicitly disable FixAll support. var missingGetFixAllProviderOverrideDiagnostic = GetBasicOverrideGetFixAllProviderExpectedDiagnostic(10, 7, "C1"); - await TestBasicCoreAsync(source, missingGetFixAllProviderOverrideDiagnostic, expected: expected); + await TestBasicCoreAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports System.Threading.Tasks + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.CodeFixes + Imports Microsoft.CodeAnalysis.CodeActions + + + Class C1 + Inherits CodeFixProvider + Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task + ' Regular cases. + Dim codeAction1_1 = CodeAction.Create("Title1_1", Function(x) Task.FromResult(context.Document)) + Dim codeAction1_2 = CodeAction.Create("Title1_2", createChangedDocument := Function(x) Task.FromResult(context.Document)) + Dim codeAction1_3 = CodeAction.Create(createChangedDocument := Function(x) Task.FromResult(context.Document), title := "Title1_3") + + ' Null argument for equivalenceKey. + Dim codeAction2_1 = CodeAction.Create("Title2_1", Function(x) Task.FromResult(context.Document), Nothing) + Dim codeAction2_2 = CodeAction.Create(createChangedDocument := Function(x) Task.FromResult(context.Document), equivalenceKey := Nothing, title := "Title2_2") + Dim codeAction2_3 = CodeAction.Create("Title2_3", Function(x) Task.FromResult(context.Document), equivalenceKey := Nothing) + + Return Nothing + End Function + + """, missingGetFixAllProviderOverrideDiagnostic, expected: expected); } [Fact] public async Task VisualBasic_CodeActionCreate_NoDiagnosticsAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports System.Threading.Tasks -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.CodeActions - - -Class C1 - Inherits CodeFixProvider - Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task - ' Overload resolution failure cases. - Dim codeAction1_1 = CodeAction.{|BC30516:Create|}(""Title1_1"") - Dim codeAction1_2 = CodeAction.{|BC30518:Create|}(createChangedDocument := Function(x) Task.FromResult(context.Document), equivalenceKey := Nothing) - - ' Correct non-null arguments - Dim equivalenceKey = ""equivalenceKey"" - Dim codeAction2_1 = CodeAction.Create(""Title2_1"", Function(x) Task.FromResult(context.Document), equivalenceKey) - Dim codeAction2_2 = CodeAction.Create(title := ""Title2_2"", createChangedDocument := Function(x) Task.FromResult(context.Document), equivalenceKey := equivalenceKey) - Dim codeAction2_3 = CodeAction.Create(equivalenceKey := equivalenceKey, title := ""Title2_3"", createChangedDocument := Function(x) Task.FromResult(context.Document)) - - ' Conservative no diagnostic cases. - Dim nullKey As String = Nothing - Dim codeAction3_1 = CodeAction.Create(""Title3_1"", Function(x) Task.FromResult(context.Document), nullKey) - Dim codeAction3_2 = CodeAction.Create(""Title3_1"", Function(x) Task.FromResult(context.Document), GetKey()) - - context.RegisterCodeFix(codeAction1_1, context.Diagnostics) - context.RegisterCodeFix(codeAction1_2, context.Diagnostics) - - context.RegisterCodeFix(codeAction2_1, context.Diagnostics) - context.RegisterCodeFix(codeAction2_2, context.Diagnostics) - context.RegisterCodeFix(codeAction2_3, context.Diagnostics) - - context.RegisterCodeFix(codeAction3_1, context.Diagnostics) - context.RegisterCodeFix(codeAction3_2, context.Diagnostics) - - Return Nothing - End Function - - Private Function GetKey() As String - Return Nothing - End Function -"; // Test0.vb(10,7): warning RS1016: 'C1' registers one or more code fixes, but does not override the method 'CodeFixProvider.GetFixAllProvider'. Override this method and provide a non-null FixAllProvider for FixAll support, potentially 'WellKnownFixAllProviders.BatchFixer', or 'null' to explicitly disable FixAll support. var missingGetFixAllProviderOverrideDiagnostic = GetBasicOverrideGetFixAllProviderExpectedDiagnostic(10, 7, "C1"); - await TestBasicCoreAsync(source, missingGetFixAllProviderOverrideDiagnostic); + await TestBasicCoreAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports System.Threading.Tasks + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.CodeFixes + Imports Microsoft.CodeAnalysis.CodeActions + + + Class C1 + Inherits CodeFixProvider + Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task + ' Overload resolution failure cases. + Dim codeAction1_1 = CodeAction.{|BC30516:Create|}("Title1_1") + Dim codeAction1_2 = CodeAction.{|BC30518:Create|}(createChangedDocument := Function(x) Task.FromResult(context.Document), equivalenceKey := Nothing) + + ' Correct non-null arguments + Dim equivalenceKey = "equivalenceKey" + Dim codeAction2_1 = CodeAction.Create("Title2_1", Function(x) Task.FromResult(context.Document), equivalenceKey) + Dim codeAction2_2 = CodeAction.Create(title := "Title2_2", createChangedDocument := Function(x) Task.FromResult(context.Document), equivalenceKey := equivalenceKey) + Dim codeAction2_3 = CodeAction.Create(equivalenceKey := equivalenceKey, title := "Title2_3", createChangedDocument := Function(x) Task.FromResult(context.Document)) + + ' Conservative no diagnostic cases. + Dim nullKey As String = Nothing + Dim codeAction3_1 = CodeAction.Create("Title3_1", Function(x) Task.FromResult(context.Document), nullKey) + Dim codeAction3_2 = CodeAction.Create("Title3_1", Function(x) Task.FromResult(context.Document), GetKey()) + + context.RegisterCodeFix(codeAction1_1, context.Diagnostics) + context.RegisterCodeFix(codeAction1_2, context.Diagnostics) + + context.RegisterCodeFix(codeAction2_1, context.Diagnostics) + context.RegisterCodeFix(codeAction2_2, context.Diagnostics) + context.RegisterCodeFix(codeAction2_3, context.Diagnostics) + + context.RegisterCodeFix(codeAction3_1, context.Diagnostics) + context.RegisterCodeFix(codeAction3_2, context.Diagnostics) + + Return Nothing + End Function + + Private Function GetKey() As String + Return Nothing + End Function + + """, missingGetFixAllProviderOverrideDiagnostic); } [Fact] public async Task VisualBasic_CodeActionCreate_DiagnosticsOnExportedCodeFixProviderTypeAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports System.Threading.Tasks -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.CodeActions - - -Class C2 - Inherits C1 -End Class - -MustInherit Class C1 - Inherits CodeFixProvider - Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task - Dim codeAction1_1 = CodeAction.Create(""Title1_1"", Function(x) Task.FromResult(context.Document)) - Return Nothing - End Function - - Private Function GetKey() As String - Return Nothing - End Function -"; var expected = new[] { // Test0.vb(23,23): warning RS1010: Provide an explicit argument for optional parameter 'equivalenceKey', which is non-null and unique across all code actions created by this fixer. @@ -642,35 +628,43 @@ End Function // Test0.vb(10,7): warning RS1016: 'C1' registers one or more code fixes, but does not override the method 'CodeFixProvider.GetFixAllProvider'. Override this method and provide a non-null FixAllProvider for FixAll support, potentially 'WellKnownFixAllProviders.BatchFixer', or 'null' to explicitly disable FixAll support. var missingGetFixAllProviderOverrideDiagnostic = GetBasicOverrideGetFixAllProviderExpectedDiagnostic(10, 7, "C2"); - await TestBasicCoreAsync(source, missingGetFixAllProviderOverrideDiagnostic, expected: expected); + await TestBasicCoreAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports System.Threading.Tasks + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.CodeFixes + Imports Microsoft.CodeAnalysis.CodeActions + + + Class C2 + Inherits C1 + End Class + + MustInherit Class C1 + Inherits CodeFixProvider + Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task + Dim codeAction1_1 = CodeAction.Create("Title1_1", Function(x) Task.FromResult(context.Document)) + Return Nothing + End Function + + Private Function GetKey() As String + Return Nothing + End Function + + """, missingGetFixAllProviderOverrideDiagnostic, expected: expected); } [Fact] public async Task VisualBasic_CustomCodeAction_VerifyDiagnosticsAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports System.Threading.Tasks -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.CodeActions - - -Class C1 - Inherits CodeFixProvider - Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task - Dim codeAction = New MyCodeActionNoEquivalenceKey() - Return Nothing - End Function -"; - var expected = new[] { // Test0.vb(19,20): warning RS1011: 'MyCodeActionNoEquivalenceKey' has the default value of 'null' for property 'EquivalenceKey'. Either override this property on 'MyCodeActionNoEquivalenceKey' to return a non-null and unique value across all code actions per-fixer or use such an existing code action. @@ -680,47 +674,71 @@ End Function // Test0.vb(10,7): warning RS1016: 'C1' registers one or more code fixes, but does not override the method 'CodeFixProvider.GetFixAllProvider'. Override this method and provide a non-null FixAllProvider for FixAll support, potentially 'WellKnownFixAllProviders.BatchFixer', or 'null' to explicitly disable FixAll support. var missingGetFixAllProviderOverrideDiagnostic = GetBasicOverrideGetFixAllProviderExpectedDiagnostic(10, 7, "C1"); - await TestBasicCoreAsync(source, missingGetFixAllProviderOverrideDiagnostic, withCustomCodeActions: true, expected: expected); + await TestBasicCoreAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports System.Threading.Tasks + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.CodeFixes + Imports Microsoft.CodeAnalysis.CodeActions + + + Class C1 + Inherits CodeFixProvider + Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task + Dim codeAction = New MyCodeActionNoEquivalenceKey() + Return Nothing + End Function + + """, missingGetFixAllProviderOverrideDiagnostic, withCustomCodeActions: true, expected: expected); } [Fact] public async Task VisualBasic_CustomCodeAction_NoDiagnosticsAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports System.Threading.Tasks -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.CodeActions - - -Class C1 - Inherits CodeFixProvider - Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task - Dim codeAction As CodeAction = New MyCodeActionWithEquivalenceKey() - context.RegisterCodeFix(codeAction, context.Diagnostics) - - codeAction = New MyDerivedCodeActionWithEquivalenceKey() - context.RegisterCodeFix(codeAction, context.Diagnostics) - - Return Nothing - End Function - - Private Function GetKey() As String - Return Nothing - End Function -"; // Test0.vb(10,7): warning RS1016: 'C1' registers one or more code fixes, but does not override the method 'CodeFixProvider.GetFixAllProvider'. Override this method and provide a non-null FixAllProvider for FixAll support, potentially 'WellKnownFixAllProviders.BatchFixer', or 'null' to explicitly disable FixAll support. var missingGetFixAllProviderOverrideDiagnostic = GetBasicOverrideGetFixAllProviderExpectedDiagnostic(10, 7, "C1"); - await TestBasicCoreAsync(source, missingGetFixAllProviderOverrideDiagnostic, withCustomCodeActions: true); + await TestBasicCoreAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports System.Threading.Tasks + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.CodeFixes + Imports Microsoft.CodeAnalysis.CodeActions + + + Class C1 + Inherits CodeFixProvider + Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task + Dim codeAction As CodeAction = New MyCodeActionWithEquivalenceKey() + context.RegisterCodeFix(codeAction, context.Diagnostics) + + codeAction = New MyDerivedCodeActionWithEquivalenceKey() + context.RegisterCodeFix(codeAction, context.Diagnostics) + + Return Nothing + End Function + + Private Function GetKey() As String + Return Nothing + End Function + + """, missingGetFixAllProviderOverrideDiagnostic, withCustomCodeActions: true); } #endregion diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/ImplementationIsObsoleteAnalyzerTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/ImplementationIsObsoleteAnalyzerTests.cs index 683644ee00a8e..a80257a2f4ab2 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/ImplementationIsObsoleteAnalyzerTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/ImplementationIsObsoleteAnalyzerTests.cs @@ -233,15 +233,15 @@ Inherits IMyInterface End Interface """; - var source2 = @" -Class SomeClass - Implements IMyInterface -End Class - -Class SomeOtherClass - Implements IMyOtherInterface -End Class -"; + var source2 = """ + Class SomeClass + Implements IMyInterface + End Class + + Class SomeOtherClass + Implements IMyOtherInterface + End Class + """; // Verify no diagnostic since interface is in a friend assembly. await new VerifyVB.Test diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/InternalImplementationOnlyTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/InternalImplementationOnlyTests.cs index b13dd2114a491..a1edf7362edd3 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/InternalImplementationOnlyTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/InternalImplementationOnlyTests.cs @@ -13,22 +13,26 @@ namespace Microsoft.CodeAnalysis.Analyzers.UnitTests { public class InternalImplementationOnlyTests { - private const string AttributeStringCSharp = @" -namespace System.Runtime.CompilerServices -{ - internal class InternalImplementationOnlyAttribute : System.Attribute {} -} -"; + private const string AttributeStringCSharp = """ + + namespace System.Runtime.CompilerServices + { + internal class InternalImplementationOnlyAttribute : System.Attribute {} + } + + """; [Fact] public async Task CSharp_VerifySameAssemblyAsync() { - string source = AttributeStringCSharp + @" + string source = AttributeStringCSharp + """ + -[System.Runtime.CompilerServices.InternalImplementationOnly] -public interface IMyInterface { } + [System.Runtime.CompilerServices.InternalImplementationOnly] + public interface IMyInterface { } -class SomeClass : IMyInterface { } -"; + class SomeClass : IMyInterface { } + + """; // Verify no diagnostic since interface is in the same assembly. await new VerifyCS.Test @@ -41,18 +45,22 @@ class SomeClass : IMyInterface { } [Fact] public async Task CSharp_VerifyDifferentAssemblyAsync() { - string source1 = AttributeStringCSharp + @" + string source1 = AttributeStringCSharp + """ + + + [System.Runtime.CompilerServices.InternalImplementationOnly] + public interface IMyInterface { } -[System.Runtime.CompilerServices.InternalImplementationOnly] -public interface IMyInterface { } + public interface IMyOtherInterface : IMyInterface { } -public interface IMyOtherInterface : IMyInterface { } -"; + """; - var source2 = @" -class SomeClass : IMyInterface { } + var source2 = """ -class SomeOtherClass : IMyOtherInterface { }"; + class SomeClass : IMyInterface { } + + class SomeOtherClass : IMyOtherInterface { } + """; // Verify errors since interface is not in a friend assembly. await new VerifyCS.Test @@ -83,20 +91,26 @@ class SomeOtherClass : IMyOtherInterface { }"; [Fact] public async Task CSharp_VerifyDifferentFriendAssemblyAsync() { - string source1 = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""TestProject"")] -" + AttributeStringCSharp + @" + string source1 = """ + + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("TestProject")] -[System.Runtime.CompilerServices.InternalImplementationOnly] -public interface IMyInterface { } + """ + AttributeStringCSharp + """ -public interface IMyOtherInterface : IMyInterface { } -"; - var source2 = @" -class SomeClass : IMyInterface { } + [System.Runtime.CompilerServices.InternalImplementationOnly] + public interface IMyInterface { } -class SomeOtherClass : IMyOtherInterface { }"; + public interface IMyOtherInterface : IMyInterface { } + + """; + + var source2 = """ + + class SomeClass : IMyInterface { } + + class SomeOtherClass : IMyOtherInterface { } + """; // Verify no diagnostic since interface is in a friend assembly. await new VerifyCS.Test @@ -120,11 +134,13 @@ class SomeOtherClass : IMyOtherInterface { }"; [Fact] public async Task CSharp_VerifyISymbolAsync() { - var source = @" -// Causes many compile errors, because not all members are implemented. -class SomeClass : Microsoft.CodeAnalysis.ISymbol { } -class SomeOtherClass : Microsoft.CodeAnalysis.IAssemblySymbol { } -"; + var source = """ + + // Causes many compile errors, because not all members are implemented. + class SomeClass : Microsoft.CodeAnalysis.ISymbol { } + class SomeOtherClass : Microsoft.CodeAnalysis.IAssemblySymbol { } + + """; // Verify that ISymbol is not implementable. await new VerifyCS.Test @@ -300,11 +316,13 @@ class SomeOtherClass : Microsoft.CodeAnalysis.IAssemblySymbol { } [Fact] public async Task CSharp_VerifyIOperationAsync() { - var source = @" -// Causes many compile errors, because not all members are implemented. -class SomeClass : Microsoft.CodeAnalysis.IOperation { } -class SomeOtherClass : Microsoft.CodeAnalysis.Operations.IInvocationOperation { } -"; + var source = """ + + // Causes many compile errors, because not all members are implemented. + class SomeClass : Microsoft.CodeAnalysis.IOperation { } + class SomeOtherClass : Microsoft.CodeAnalysis.Operations.IInvocationOperation { } + + """; // Verify that IOperation is not implementable. await new VerifyCS.Test @@ -375,27 +393,31 @@ class SomeOtherClass : Microsoft.CodeAnalysis.Operations.IInvocationOperation { }.RunAsync(); } - private const string AttributeStringBasic = @" -Namespace System.Runtime.CompilerServices - Friend Class InternalImplementationOnlyAttribute - Inherits System.Attribute - End Class -End Namespace -"; + private const string AttributeStringBasic = """ + + Namespace System.Runtime.CompilerServices + Friend Class InternalImplementationOnlyAttribute + Inherits System.Attribute + End Class + End Namespace + + """; [Fact] public async Task Basic_VerifySameAssemblyAsync() { - string source = AttributeStringBasic + @" + string source = AttributeStringBasic + """ - -Public Interface IMyInterface -End Interface -Class SomeClass - Implements IMyInterface -End Class -"; + + Public Interface IMyInterface + End Interface + + Class SomeClass + Implements IMyInterface + End Class + + """; // Verify no diagnostic since interface is in the same assembly. await new VerifyVB.Test @@ -408,26 +430,30 @@ End Class [Fact] public async Task Basic_VerifyDifferentAssemblyAsync() { - string source1 = AttributeStringBasic + @" + string source1 = AttributeStringBasic + """ + + + + Public Interface IMyInterface + End Interface + + Public Interface IMyOtherInterface + Inherits IMyInterface + End Interface - -Public Interface IMyInterface -End Interface + """; -Public Interface IMyOtherInterface - Inherits IMyInterface -End Interface -"; + var source2 = """ - var source2 = @" -Class SomeClass - Implements IMyInterface -End Class + Class SomeClass + Implements IMyInterface + End Class -Class SomeOtherClass - Implements IMyOtherInterface -End Class -"; + Class SomeOtherClass + Implements IMyOtherInterface + End Class + + """; // Verify errors since interface is not in a friend assembly. await new VerifyVB.Test @@ -458,28 +484,34 @@ End Class [Fact] public async Task Basic_VerifyDifferentFriendAssemblyAsync() { - string source1 = @" - -" + AttributeStringBasic + @" + string source1 = """ + + + + """ + AttributeStringBasic + """ + + + + Public Interface IMyInterface + End Interface - -Public Interface IMyInterface -End Interface + Public Interface IMyOtherInterface + Inherits IMyInterface + End Interface -Public Interface IMyOtherInterface - Inherits IMyInterface -End Interface -"; + """; - var source2 = @" -Class SomeClass - Implements IMyInterface -End Class + var source2 = """ -Class SomeOtherClass - Implements IMyOtherInterface -End Class -"; + Class SomeClass + Implements IMyInterface + End Class + + Class SomeOtherClass + Implements IMyOtherInterface + End Class + + """; // Verify no diagnostic since interface is in a friend assembly. await new VerifyVB.Test @@ -501,20 +533,18 @@ End Class } [Fact] - public async Task Basic_VerifyISymbolAsync() - { - var source = @" -' Causes many compile errors, because not all members are implemented. -Class C1 - Implements Microsoft.CodeAnalysis.ISymbol -End Class -Class C2 - Implements Microsoft.CodeAnalysis.IAssemblySymbol -End Class -"; - - // Verify that ISymbol is not implementable. - await VerifyVB.VerifyAnalyzerAsync(source, + public Task Basic_VerifyISymbolAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + + ' Causes many compile errors, because not all members are implemented. + Class C1 + Implements Microsoft.CodeAnalysis.ISymbol + End Class + Class C2 + Implements Microsoft.CodeAnalysis.IAssemblySymbol + End Class + + """, // Test0.vb(3,7): error RS1009: Type C1 cannot implement interface ISymbol because ISymbol is not available for public implementation. VerifyVB.Diagnostic().WithSpan(3, 7, 3, 9).WithArguments("C1", "ISymbol"), // Test0.vb(4) : error BC30149: Class 'C1' must implement 'Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult' for interface 'ISymbol'. @@ -674,23 +704,20 @@ await VerifyVB.VerifyAnalyzerAsync(source, // Test0.vb(7) : error BC30149: Class 'C2' must implement 'Sub Accept(visitor As SymbolVisitor)' for interface 'ISymbol'. DiagnosticResult.CompilerError("BC30149").WithSpan(7, 16, 7, 54).WithArguments("Class", "C2", "Sub Accept(visitor As Microsoft.CodeAnalysis.SymbolVisitor)", "ISymbol") ); - } [Fact] - public async Task Basic_VerifyIOperationAsync() - { - var source = @" -' Causes many compile errors, because not all members are implemented. -Class C1 - Implements Microsoft.CodeAnalysis.IOperation -End Class -Class C2 - Implements Microsoft.CodeAnalysis.Operations.IInvocationOperation -End Class -"; - - // Verify that IOperation is not implementable. - await VerifyVB.VerifyAnalyzerAsync(source, + public Task Basic_VerifyIOperationAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + + ' Causes many compile errors, because not all members are implemented. + Class C1 + Implements Microsoft.CodeAnalysis.IOperation + End Class + Class C2 + Implements Microsoft.CodeAnalysis.Operations.IInvocationOperation + End Class + + """, // Test0.vb(3,7): error RS1009: Type C1 cannot implement interface IOperation because IOperation is not available for public implementation. VerifyVB.Diagnostic().WithSpan(3, 7, 3, 9).WithArguments("C1", "IOperation"), // Test0.vb(4) : error BC30149: Class 'C1' must implement 'Function Accept(Of TArgument, TResult)(visitor As OperationVisitor(Of TArgument, TResult), argument As TArgument) As TResult' for interface 'IOperation'. @@ -748,6 +775,5 @@ await VerifyVB.VerifyAnalyzerAsync(source, // Test0.vb(7) : error BC30149: Class 'C2' must implement 'Sub Accept(visitor As OperationVisitor)' for interface 'IOperation'. DiagnosticResult.CompilerError("BC30149").WithSpan(7, 16, 7, 70).WithArguments("Class", "C2", "Sub Accept(visitor As Microsoft.CodeAnalysis.Operations.OperationVisitor)", "IOperation") ); - } } } diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/AddLanguageSupportToAnalyzerRuleTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/AddLanguageSupportToAnalyzerRuleTests.cs index 2344993ef8173..2abb8ab6b7bcd 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/AddLanguageSupportToAnalyzerRuleTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/AddLanguageSupportToAnalyzerRuleTests.cs @@ -21,28 +21,29 @@ public class AddLanguageSupportToAnalyzerRuleTests [Fact] public async Task CSharp_VerifyDiagnosticAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp, ""MyLanguage"")] -class MyAnalyzer : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics - { - get - { - throw new NotImplementedException(); - } - } - - public override void Initialize(AnalysisContext context) - { - } -}"; - DiagnosticResult expected = GetCSharpExpectedDiagnostic(7, 2, "MyAnalyzer", missingLanguageName: LanguageNames.VisualBasic); + var source = """ + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp, "MyLanguage")] + class MyAnalyzer : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """; + DiagnosticResult expected = GetCSharpExpectedDiagnostic(6, 2, "MyAnalyzer", missingLanguageName: LanguageNames.VisualBasic); // Verify diagnostic if analyzer assembly doesn't reference C# code analysis assembly. await new VerifyCS.Test @@ -62,26 +63,26 @@ public override void Initialize(AnalysisContext context) [Fact] public async Task VisualBasic_VerifyDiagnosticAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -"; - DiagnosticResult expected = GetBasicExpectedDiagnostic(7, 2, "MyAnalyzer", missingLanguageName: LanguageNames.CSharp); + var source = """ + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + """; + DiagnosticResult expected = GetBasicExpectedDiagnostic(6, 2, "MyAnalyzer", missingLanguageName: LanguageNames.CSharp); // Verify diagnostic if analyzer assembly doesn't reference VB code analysis assembly. await new VerifyVB.Test @@ -101,49 +102,49 @@ End Class [Fact] public async Task CSharp_NoDiagnosticCasesAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(""MyLanguage"")] -class MyAnalyzerWithCustomLanguageAttribute : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics - { - get - { - throw new NotImplementedException(); - } - } - - public override void Initialize(AnalysisContext context) - { - } -} - -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzerWithBothLanguages : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics - { - get - { - throw new NotImplementedException(); - } - } - - public override void Initialize(AnalysisContext context) - { - } -} - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public abstract class MyAbstractAnalyzer : DiagnosticAnalyzer -{ -} -"; + var source = """ + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer("MyLanguage")] + class MyAnalyzerWithCustomLanguageAttribute : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzerWithBothLanguages : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public abstract class MyAbstractAnalyzer : DiagnosticAnalyzer + { + } + """; await new VerifyCS.Test { ReferenceAssemblies = AdditionalMetadataReferences.DefaultWithoutRoslynSymbols, @@ -156,43 +157,43 @@ public abstract class MyAbstractAnalyzer : DiagnosticAnalyzer [Fact] public async Task VisualBasic_NoDiagnosticCasesAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzerWithCustomLanguageAttribute - Inherits DiagnosticAnalyzer - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class - - -Class MyAnalyzerWithBothLanguages - Inherits DiagnosticAnalyzer - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class - - -Public MustInherit Class MyAbstractAnalyzer - Inherits DiagnosticAnalyzer -End Class -"; + var source = """ + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzerWithCustomLanguageAttribute + Inherits DiagnosticAnalyzer + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + + Class MyAnalyzerWithBothLanguages + Inherits DiagnosticAnalyzer + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + + Public MustInherit Class MyAbstractAnalyzer + Inherits DiagnosticAnalyzer + End Class + """; await new VerifyVB.Test { ReferenceAssemblies = AdditionalMetadataReferences.DefaultWithoutRoslynSymbols, diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/ClassIsNotDiagnosticAnalyzerTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/ClassIsNotDiagnosticAnalyzerTests.cs index 28b738e7a13a1..343a1360de5bb 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/ClassIsNotDiagnosticAnalyzerTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/ClassIsNotDiagnosticAnalyzerTests.cs @@ -18,155 +18,163 @@ public class ClassIsNotDiagnosticAnalyzerTests [Fact] public async Task ClassNotDiagnosticAnalyzer_DiagnosticAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -namespace RoslynSandbox -{ - using Microsoft.CodeAnalysis; - using Microsoft.CodeAnalysis.Diagnostics; - - [DiagnosticAnalyzer(LanguageNames.CSharp)] - internal class NotAnAnalyzer - { - } -}", + await VerifyCS.VerifyAnalyzerAsync(""" + namespace RoslynSandbox + { + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + internal class NotAnAnalyzer + { + } + } + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic().WithLocation(8, 20).WithArguments("NotAnAnalyzer")); + VerifyCS.Diagnostic().WithLocation(7, 20).WithArguments("NotAnAnalyzer")); #pragma warning restore RS0030 // Do not use banned APIs - await VerifyVB.VerifyAnalyzerAsync(@" -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics + await VerifyVB.VerifyAnalyzerAsync(""" + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics -Namespace RoslynSandbox - - Friend Class NotAnAnalyzer - End Class -End Namespace", + Namespace RoslynSandbox + + Friend Class NotAnAnalyzer + End Class + End Namespace + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyVB.Diagnostic().WithLocation(7, 18).WithArguments("NotAnAnalyzer")); + VerifyVB.Diagnostic().WithLocation(6, 18).WithArguments("NotAnAnalyzer")); #pragma warning restore RS0030 // Do not use banned APIs } [Fact] public async Task StaticClassNotDiagnosticAnalyzer_DiagnosticAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -namespace RoslynSandbox -{ - using Microsoft.CodeAnalysis; - using Microsoft.CodeAnalysis.Diagnostics; - - [DiagnosticAnalyzer(LanguageNames.CSharp)] - internal static class NotAnAnalyzer - { - } -}", + await VerifyCS.VerifyAnalyzerAsync(""" + namespace RoslynSandbox + { + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + internal static class NotAnAnalyzer + { + } + } + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic().WithLocation(8, 27).WithArguments("NotAnAnalyzer")); + VerifyCS.Diagnostic().WithLocation(7, 27).WithArguments("NotAnAnalyzer")); #pragma warning restore RS0030 // Do not use banned APIs - await VerifyVB.VerifyAnalyzerAsync(@" -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics + await VerifyVB.VerifyAnalyzerAsync(""" + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics -Namespace RoslynSandbox - - Friend Module NotAnAnalyzer - End Module -End Namespace"); + Namespace RoslynSandbox + + Friend Module NotAnAnalyzer + End Module + End Namespace + """); } [Fact] public async Task ClassDiagnosticAnalyzer_NoDiagnosticAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -namespace RoslynSandbox -{ - using System.Collections.Immutable; - using Microsoft.CodeAnalysis; - using Microsoft.CodeAnalysis.Diagnostics; - - [DiagnosticAnalyzer(LanguageNames.CSharp)] - internal class SomeAnalyzer : DiagnosticAnalyzer - { - public override ImmutableArray SupportedDiagnostics => throw new System.NotImplementedException(); - - public override void Initialize(AnalysisContext context) => throw new System.NotImplementedException(); - } -}"); - - await VerifyVB.VerifyAnalyzerAsync(@" -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - -Namespace RoslynSandbox - - Friend Class SomeAnalyzer - Inherits DiagnosticAnalyzer - - Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New System.NotImplementedException() - End Get - End Property - - Public Overrides Sub Initialize(ByVal context As AnalysisContext) - Throw New System.NotImplementedException() - End Sub - End Class -End Namespace"); + await VerifyCS.VerifyAnalyzerAsync(""" + namespace RoslynSandbox + { + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + internal class SomeAnalyzer : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics => throw new System.NotImplementedException(); + + public override void Initialize(AnalysisContext context) => throw new System.NotImplementedException(); + } + } + """); + + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + Namespace RoslynSandbox + + Friend Class SomeAnalyzer + Inherits DiagnosticAnalyzer + + Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New System.NotImplementedException() + End Get + End Property + + Public Overrides Sub Initialize(ByVal context As AnalysisContext) + Throw New System.NotImplementedException() + End Sub + End Class + End Namespace + """); } [Fact] public async Task ClassInheritsClassDiagnosticAnalyzer_NoDiagnosticAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -namespace RoslynSandbox -{ - using System.Collections.Immutable; - using Microsoft.CodeAnalysis; - using Microsoft.CodeAnalysis.Diagnostics; - - internal abstract class SomeAnalyzerBase : DiagnosticAnalyzer - { - public override ImmutableArray SupportedDiagnostics => throw new System.NotImplementedException(); - - public override void Initialize(AnalysisContext context) => throw new System.NotImplementedException(); - } - - [DiagnosticAnalyzer(LanguageNames.CSharp)] - internal class SomeAnalyzer : SomeAnalyzerBase - { - } -}"); - - await VerifyVB.VerifyAnalyzerAsync(@" -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - -Namespace RoslynSandbox - Friend MustInherit Class SomeAnalyzerBase - Inherits DiagnosticAnalyzer - - Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New System.NotImplementedException() - End Get - End Property - - Public Overrides Sub Initialize(ByVal context As AnalysisContext) - Throw New System.NotImplementedException() - End Sub - End Class - - - - Friend Class SomeAnalyzer - Inherits SomeAnalyzerBase - End Class -End Namespace"); + await VerifyCS.VerifyAnalyzerAsync(""" + namespace RoslynSandbox + { + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + internal abstract class SomeAnalyzerBase : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics => throw new System.NotImplementedException(); + + public override void Initialize(AnalysisContext context) => throw new System.NotImplementedException(); + } + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + internal class SomeAnalyzer : SomeAnalyzerBase + { + } + } + """); + + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + Namespace RoslynSandbox + Friend MustInherit Class SomeAnalyzerBase + Inherits DiagnosticAnalyzer + + Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New System.NotImplementedException() + End Get + End Property + + Public Overrides Sub Initialize(ByVal context As AnalysisContext) + Throw New System.NotImplementedException() + End Sub + End Class + + + + Friend Class SomeAnalyzer + Inherits SomeAnalyzerBase + End Class + End Namespace + """); } } } diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/CompareSymbolsCorrectlyTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/CompareSymbolsCorrectlyTests.cs index 6f17d05eb0d45..1c072e1e1e6ed 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/CompareSymbolsCorrectlyTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/CompareSymbolsCorrectlyTests.cs @@ -18,209 +18,211 @@ namespace Microsoft.CodeAnalysis.Analyzers.UnitTests.MetaAnalyzers { public class CompareSymbolsCorrectlyTests { - private const string MinimalSymbolImplementationCSharp = @" -using System; -using System.Collections.Immutable; -using System.Globalization; -using System.Threading; -using Microsoft.CodeAnalysis; - -class Symbol : ISymbol { - public SymbolKind Kind => throw new NotImplementedException(); - public string Language => throw new NotImplementedException(); - public string Name => throw new NotImplementedException(); - public string MetadataName => throw new NotImplementedException(); - public ISymbol ContainingSymbol => throw new NotImplementedException(); - public IAssemblySymbol ContainingAssembly => throw new NotImplementedException(); - public IModuleSymbol ContainingModule => throw new NotImplementedException(); - public INamedTypeSymbol ContainingType => throw new NotImplementedException(); - public INamespaceSymbol ContainingNamespace => throw new NotImplementedException(); - public bool IsDefinition => throw new NotImplementedException(); - public bool IsStatic => throw new NotImplementedException(); - public bool IsVirtual => throw new NotImplementedException(); - public bool IsOverride => throw new NotImplementedException(); - public bool IsAbstract => throw new NotImplementedException(); - public bool IsSealed => throw new NotImplementedException(); - public bool IsExtern => throw new NotImplementedException(); - public bool IsImplicitlyDeclared => throw new NotImplementedException(); - public bool CanBeReferencedByName => throw new NotImplementedException(); - public ImmutableArray Locations => throw new NotImplementedException(); - public ImmutableArray DeclaringSyntaxReferences => throw new NotImplementedException(); - public Accessibility DeclaredAccessibility => throw new NotImplementedException(); - public ISymbol OriginalDefinition => throw new NotImplementedException(); - public bool HasUnsupportedMetadata => throw new NotImplementedException(); - - public void Accept(SymbolVisitor visitor) => throw new NotImplementedException(); - public TResult Accept(SymbolVisitor visitor) => throw new NotImplementedException(); - public bool Equals(ISymbol other) => throw new NotImplementedException(); - public ImmutableArray GetAttributes() => throw new NotImplementedException(); - public string GetDocumentationCommentId() => throw new NotImplementedException(); - public string GetDocumentationCommentXml(CultureInfo preferredCulture, bool expandIncludes, CancellationToken cancellationToken) => throw new NotImplementedException(); - public ImmutableArray ToDisplayParts(SymbolDisplayFormat format) => throw new NotImplementedException(); - public string ToDisplayString(SymbolDisplayFormat format) => throw new NotImplementedException(); - public ImmutableArray ToMinimalDisplayParts(SemanticModel semanticModel, int position, SymbolDisplayFormat format) => throw new NotImplementedException(); - public string ToMinimalDisplayString(SemanticModel semanticModel, int position, SymbolDisplayFormat format) => throw new NotImplementedException(); - - public static bool operator ==(Symbol left, Symbol right) => throw new NotImplementedException(); - public static bool operator !=(Symbol left, Symbol right) => throw new NotImplementedException(); -} -"; - private const string MinimalSymbolImplementationVisualBasic = @" -Imports System -Imports System.Collections.Immutable -Imports System.Globalization -Imports System.Threading -Imports Microsoft.CodeAnalysis - -Class Symbol - Implements ISymbol - - Public ReadOnly Property Kind As SymbolKind Implements ISymbol.Kind - Public ReadOnly Property Language As String Implements ISymbol.Language - Public ReadOnly Property Name As String Implements ISymbol.Name - Public ReadOnly Property MetadataName As String Implements ISymbol.MetadataName - Public ReadOnly Property ContainingSymbol As ISymbol Implements ISymbol.ContainingSymbol - Public ReadOnly Property ContainingAssembly As IAssemblySymbol Implements ISymbol.ContainingAssembly - Public ReadOnly Property ContainingModule As IModuleSymbol Implements ISymbol.ContainingModule - Public ReadOnly Property ContainingType As INamedTypeSymbol Implements ISymbol.ContainingType - Public ReadOnly Property ContainingNamespace As INamespaceSymbol Implements ISymbol.ContainingNamespace - Public ReadOnly Property IsDefinition As Boolean Implements ISymbol.IsDefinition - Public ReadOnly Property IsStatic As Boolean Implements ISymbol.IsStatic - Public ReadOnly Property IsVirtual As Boolean Implements ISymbol.IsVirtual - Public ReadOnly Property IsOverride As Boolean Implements ISymbol.IsOverride - Public ReadOnly Property IsAbstract As Boolean Implements ISymbol.IsAbstract - Public ReadOnly Property IsSealed As Boolean Implements ISymbol.IsSealed - Public ReadOnly Property IsExtern As Boolean Implements ISymbol.IsExtern - Public ReadOnly Property IsImplicitlyDeclared As Boolean Implements ISymbol.IsImplicitlyDeclared - Public ReadOnly Property CanBeReferencedByName As Boolean Implements ISymbol.CanBeReferencedByName - Public ReadOnly Property Locations As ImmutableArray(Of Location) Implements ISymbol.Locations - Public ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Implements ISymbol.DeclaringSyntaxReferences - Public ReadOnly Property DeclaredAccessibility As Accessibility Implements ISymbol.DeclaredAccessibility - Public ReadOnly Property OriginalDefinition As ISymbol Implements ISymbol.OriginalDefinition - Public ReadOnly Property HasUnsupportedMetadata As Boolean Implements ISymbol.HasUnsupportedMetadata - - Public Sub Accept(visitor As SymbolVisitor) Implements ISymbol.Accept - Throw New NotImplementedException() - End Sub - - Public Function GetAttributes() As ImmutableArray(Of AttributeData) Implements ISymbol.GetAttributes - Throw New NotImplementedException() - End Function - - Public Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult Implements ISymbol.Accept - Throw New NotImplementedException() - End Function - - Public Function GetDocumentationCommentId() As String Implements ISymbol.GetDocumentationCommentId - Throw New NotImplementedException() - End Function - - Public Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String Implements ISymbol.GetDocumentationCommentXml - Throw New NotImplementedException() - End Function - - Public Function ToDisplayString(Optional format As SymbolDisplayFormat = Nothing) As String Implements ISymbol.ToDisplayString - Throw New NotImplementedException() - End Function - - Public Function ToDisplayParts(Optional format As SymbolDisplayFormat = Nothing) As ImmutableArray(Of SymbolDisplayPart) Implements ISymbol.ToDisplayParts - Throw New NotImplementedException() - End Function - - Public Function ToMinimalDisplayString(semanticModel As SemanticModel, position As Integer, Optional format As SymbolDisplayFormat = Nothing) As String Implements ISymbol.ToMinimalDisplayString - Throw New NotImplementedException() - End Function - - Public Function ToMinimalDisplayParts(semanticModel As SemanticModel, position As Integer, Optional format As SymbolDisplayFormat = Nothing) As ImmutableArray(Of SymbolDisplayPart) Implements ISymbol.ToMinimalDisplayParts - Throw New NotImplementedException() - End Function - - Public Function Equals(other As ISymbol) As Boolean Implements IEquatable(Of ISymbol).Equals - Throw New NotImplementedException() - End Function - - Public Shared Operator =(left As Symbol, right As Symbol) As Boolean - Throw New NotImplementedException() - End Operator - - Public Shared Operator <>(left As Symbol, right As Symbol) As Boolean - Throw New NotImplementedException() - End Operator -End Class -"; + private const string MinimalSymbolImplementationCSharp = """ + using System; + using System.Collections.Immutable; + using System.Globalization; + using System.Threading; + using Microsoft.CodeAnalysis; + + class Symbol : ISymbol { + public SymbolKind Kind => throw new NotImplementedException(); + public string Language => throw new NotImplementedException(); + public string Name => throw new NotImplementedException(); + public string MetadataName => throw new NotImplementedException(); + public ISymbol ContainingSymbol => throw new NotImplementedException(); + public IAssemblySymbol ContainingAssembly => throw new NotImplementedException(); + public IModuleSymbol ContainingModule => throw new NotImplementedException(); + public INamedTypeSymbol ContainingType => throw new NotImplementedException(); + public INamespaceSymbol ContainingNamespace => throw new NotImplementedException(); + public bool IsDefinition => throw new NotImplementedException(); + public bool IsStatic => throw new NotImplementedException(); + public bool IsVirtual => throw new NotImplementedException(); + public bool IsOverride => throw new NotImplementedException(); + public bool IsAbstract => throw new NotImplementedException(); + public bool IsSealed => throw new NotImplementedException(); + public bool IsExtern => throw new NotImplementedException(); + public bool IsImplicitlyDeclared => throw new NotImplementedException(); + public bool CanBeReferencedByName => throw new NotImplementedException(); + public ImmutableArray Locations => throw new NotImplementedException(); + public ImmutableArray DeclaringSyntaxReferences => throw new NotImplementedException(); + public Accessibility DeclaredAccessibility => throw new NotImplementedException(); + public ISymbol OriginalDefinition => throw new NotImplementedException(); + public bool HasUnsupportedMetadata => throw new NotImplementedException(); + + public void Accept(SymbolVisitor visitor) => throw new NotImplementedException(); + public TResult Accept(SymbolVisitor visitor) => throw new NotImplementedException(); + public bool Equals(ISymbol other) => throw new NotImplementedException(); + public ImmutableArray GetAttributes() => throw new NotImplementedException(); + public string GetDocumentationCommentId() => throw new NotImplementedException(); + public string GetDocumentationCommentXml(CultureInfo preferredCulture, bool expandIncludes, CancellationToken cancellationToken) => throw new NotImplementedException(); + public ImmutableArray ToDisplayParts(SymbolDisplayFormat format) => throw new NotImplementedException(); + public string ToDisplayString(SymbolDisplayFormat format) => throw new NotImplementedException(); + public ImmutableArray ToMinimalDisplayParts(SemanticModel semanticModel, int position, SymbolDisplayFormat format) => throw new NotImplementedException(); + public string ToMinimalDisplayString(SemanticModel semanticModel, int position, SymbolDisplayFormat format) => throw new NotImplementedException(); + + public static bool operator ==(Symbol left, Symbol right) => throw new NotImplementedException(); + public static bool operator !=(Symbol left, Symbol right) => throw new NotImplementedException(); + } + """; + private const string MinimalSymbolImplementationVisualBasic = """ + Imports System + Imports System.Collections.Immutable + Imports System.Globalization + Imports System.Threading + Imports Microsoft.CodeAnalysis + + Class Symbol + Implements ISymbol + + Public ReadOnly Property Kind As SymbolKind Implements ISymbol.Kind + Public ReadOnly Property Language As String Implements ISymbol.Language + Public ReadOnly Property Name As String Implements ISymbol.Name + Public ReadOnly Property MetadataName As String Implements ISymbol.MetadataName + Public ReadOnly Property ContainingSymbol As ISymbol Implements ISymbol.ContainingSymbol + Public ReadOnly Property ContainingAssembly As IAssemblySymbol Implements ISymbol.ContainingAssembly + Public ReadOnly Property ContainingModule As IModuleSymbol Implements ISymbol.ContainingModule + Public ReadOnly Property ContainingType As INamedTypeSymbol Implements ISymbol.ContainingType + Public ReadOnly Property ContainingNamespace As INamespaceSymbol Implements ISymbol.ContainingNamespace + Public ReadOnly Property IsDefinition As Boolean Implements ISymbol.IsDefinition + Public ReadOnly Property IsStatic As Boolean Implements ISymbol.IsStatic + Public ReadOnly Property IsVirtual As Boolean Implements ISymbol.IsVirtual + Public ReadOnly Property IsOverride As Boolean Implements ISymbol.IsOverride + Public ReadOnly Property IsAbstract As Boolean Implements ISymbol.IsAbstract + Public ReadOnly Property IsSealed As Boolean Implements ISymbol.IsSealed + Public ReadOnly Property IsExtern As Boolean Implements ISymbol.IsExtern + Public ReadOnly Property IsImplicitlyDeclared As Boolean Implements ISymbol.IsImplicitlyDeclared + Public ReadOnly Property CanBeReferencedByName As Boolean Implements ISymbol.CanBeReferencedByName + Public ReadOnly Property Locations As ImmutableArray(Of Location) Implements ISymbol.Locations + Public ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Implements ISymbol.DeclaringSyntaxReferences + Public ReadOnly Property DeclaredAccessibility As Accessibility Implements ISymbol.DeclaredAccessibility + Public ReadOnly Property OriginalDefinition As ISymbol Implements ISymbol.OriginalDefinition + Public ReadOnly Property HasUnsupportedMetadata As Boolean Implements ISymbol.HasUnsupportedMetadata + + Public Sub Accept(visitor As SymbolVisitor) Implements ISymbol.Accept + Throw New NotImplementedException() + End Sub + + Public Function GetAttributes() As ImmutableArray(Of AttributeData) Implements ISymbol.GetAttributes + Throw New NotImplementedException() + End Function + + Public Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult Implements ISymbol.Accept + Throw New NotImplementedException() + End Function + + Public Function GetDocumentationCommentId() As String Implements ISymbol.GetDocumentationCommentId + Throw New NotImplementedException() + End Function + + Public Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String Implements ISymbol.GetDocumentationCommentXml + Throw New NotImplementedException() + End Function + + Public Function ToDisplayString(Optional format As SymbolDisplayFormat = Nothing) As String Implements ISymbol.ToDisplayString + Throw New NotImplementedException() + End Function + + Public Function ToDisplayParts(Optional format As SymbolDisplayFormat = Nothing) As ImmutableArray(Of SymbolDisplayPart) Implements ISymbol.ToDisplayParts + Throw New NotImplementedException() + End Function + + Public Function ToMinimalDisplayString(semanticModel As SemanticModel, position As Integer, Optional format As SymbolDisplayFormat = Nothing) As String Implements ISymbol.ToMinimalDisplayString + Throw New NotImplementedException() + End Function + + Public Function ToMinimalDisplayParts(semanticModel As SemanticModel, position As Integer, Optional format As SymbolDisplayFormat = Nothing) As ImmutableArray(Of SymbolDisplayPart) Implements ISymbol.ToMinimalDisplayParts + Throw New NotImplementedException() + End Function + + Public Function Equals(other As ISymbol) As Boolean Implements IEquatable(Of ISymbol).Equals + Throw New NotImplementedException() + End Function + + Public Shared Operator =(left As Symbol, right As Symbol) As Boolean + Throw New NotImplementedException() + End Operator + + Public Shared Operator <>(left As Symbol, right As Symbol) As Boolean + Throw New NotImplementedException() + End Operator + End Class + """; private const string SymbolEqualityComparerStubVisualBasic = -@" -Imports System.Collections.Generic + """ + Imports System.Collections.Generic -Namespace Microsoft - Namespace CodeAnalysis - Public Class SymbolEqualityComparer - Implements IEqualityComparer(Of ISymbol) + Namespace Microsoft + Namespace CodeAnalysis + Public Class SymbolEqualityComparer + Implements IEqualityComparer(Of ISymbol) - Public Shared ReadOnly [Default] As SymbolEqualityComparer = New SymbolEqualityComparer() + Public Shared ReadOnly [Default] As SymbolEqualityComparer = New SymbolEqualityComparer() - Private Sub New() - End Sub + Private Sub New() + End Sub - Public Function Equals(x As ISymbol, y As ISymbol) As Boolean Implements IEqualityComparer(Of ISymbol).Equals - Throw New System.NotImplementedException() - End Function + Public Function Equals(x As ISymbol, y As ISymbol) As Boolean Implements IEqualityComparer(Of ISymbol).Equals + Throw New System.NotImplementedException() + End Function - Public Function GetHashCode(obj As ISymbol) As Integer Implements IEqualityComparer(Of ISymbol).GetHashCode - Throw New System.NotImplementedException() - End Function - End Class - End Namespace -End Namespace"; + Public Function GetHashCode(obj As ISymbol) As Integer Implements IEqualityComparer(Of ISymbol).GetHashCode + Throw New System.NotImplementedException() + End Function + End Class + End Namespace + End Namespace + """; private const string SymbolEqualityComparerStubCSharp = -@" -using System.Collections.Generic; + """ + using System.Collections.Generic; -namespace Microsoft.CodeAnalysis -{ - public class SymbolEqualityComparer : IEqualityComparer - { - public static readonly SymbolEqualityComparer Default = new SymbolEqualityComparer(); + namespace Microsoft.CodeAnalysis + { + public class SymbolEqualityComparer : IEqualityComparer + { + public static readonly SymbolEqualityComparer Default = new SymbolEqualityComparer(); - private SymbolEqualityComparer() - { - } + private SymbolEqualityComparer() + { + } - public bool Equals(ISymbol x, ISymbol y) - { - throw new System.NotImplementedException(); - } + public bool Equals(ISymbol x, ISymbol y) + { + throw new System.NotImplementedException(); + } - public int GetHashCode(ISymbol obj) - { - throw new System.NotImplementedException(); - } - } -}"; + public int GetHashCode(ISymbol obj) + { + throw new System.NotImplementedException(); + } + } + } + """; [Theory] [InlineData(nameof(ISymbol))] [InlineData(nameof(INamedTypeSymbol))] public async Task CompareTwoSymbolsEquals_CSharpAsync(string symbolType) { - var source = $@" -using Microsoft.CodeAnalysis; -class TestClass {{ - bool Method({symbolType} x, {symbolType} y) {{ - return [|x == y|]; - }} -}} -"; - var fixedSource = $@" -using Microsoft.CodeAnalysis; -class TestClass {{ - bool Method({symbolType} x, {symbolType} y) {{ - return SymbolEqualityComparer.Default.Equals(x, y); - }} -}} -"; + var source = $$""" + using Microsoft.CodeAnalysis; + class TestClass { + bool Method({{symbolType}} x, {{symbolType}} y) { + return [|x == y|]; + } + } + """; + var fixedSource = $$""" + using Microsoft.CodeAnalysis; + class TestClass { + bool Method({{symbolType}} x, {{symbolType}} y) { + return SymbolEqualityComparer.Default.Equals(x, y); + } + } + """; await new VerifyCS.Test { TestState = { Sources = { source, SymbolEqualityComparerStubCSharp } }, @@ -231,62 +233,54 @@ bool Method({symbolType} x, {symbolType} y) {{ [Theory] [InlineData(nameof(ISymbol))] [InlineData(nameof(INamedTypeSymbol))] - public async Task CompareTwoSymbolsEquals_NoComparer_CSharpAsync(string symbolType) - { - var source = $@" -using Microsoft.CodeAnalysis; -class TestClass {{ - bool Method({symbolType} x, {symbolType} y) {{ - return [|x == y|]; - }} -}} -"; - var fixedSource = $@" -using Microsoft.CodeAnalysis; -class TestClass {{ - bool Method({symbolType} x, {symbolType} y) {{ - return Equals(x, y); - }} -}} -"; - await VerifyCS.VerifyCodeFixAsync(source, fixedSource); - } + public Task CompareTwoSymbolsEquals_NoComparer_CSharpAsync(string symbolType) + => VerifyCS.VerifyCodeFixAsync($$""" + using Microsoft.CodeAnalysis; + class TestClass { + bool Method({{symbolType}} x, {{symbolType}} y) { + return [|x == y|]; + } + } + """, $$""" + using Microsoft.CodeAnalysis; + class TestClass { + bool Method({{symbolType}} x, {{symbolType}} y) { + return Equals(x, y); + } + } + """); [Theory] [WorkItem(2335, "https://github.com/dotnet/roslyn-analyzers/issues/2335")] [InlineData(nameof(ISymbol))] [InlineData(nameof(INamedTypeSymbol))] - public async Task CompareTwoSymbolsByIdentity_CSharpAsync(string symbolType) - { - var source = $@" -using Microsoft.CodeAnalysis; -class TestClass {{ - bool Method1({symbolType} x, {symbolType} y) {{ - return (object)x == y; - }} - bool Method2({symbolType} x, {symbolType} y) {{ - return x == (object)y; - }} - bool Method3({symbolType} x, {symbolType} y) {{ - return (object)x == (object)y; - }} -}} -"; - - await VerifyCS.VerifyAnalyzerAsync(source); - } + public Task CompareTwoSymbolsByIdentity_CSharpAsync(string symbolType) + => VerifyCS.VerifyAnalyzerAsync($$""" + using Microsoft.CodeAnalysis; + class TestClass { + bool Method1({{symbolType}} x, {{symbolType}} y) { + return (object)x == y; + } + bool Method2({{symbolType}} x, {{symbolType}} y) { + return x == (object)y; + } + bool Method3({{symbolType}} x, {{symbolType}} y) { + return (object)x == (object)y; + } + } + """); [Fact] [WorkItem(2336, "https://github.com/dotnet/roslyn-analyzers/issues/2336")] public async Task CompareTwoSymbolImplementations_CSharpAsync() { - var source = $@" -class TestClass {{ - bool Method(Symbol x, Symbol y) {{ - return x == y; - }} -}} -"; + var source = $$""" + class TestClass { + bool Method(Symbol x, Symbol y) { + return x == y; + } + } + """; await new VerifyCS.Test { @@ -300,22 +294,22 @@ bool Method(Symbol x, Symbol y) {{ [InlineData(nameof(INamedTypeSymbol))] public async Task CompareSymbolImplementationWithInterface_CSharpAsync(string symbolType) { - var source = $@" -using Microsoft.CodeAnalysis; -class TestClass {{ - bool Method(Symbol x, {symbolType} y) {{ - return [|x == y|]; - }} -}} -"; - var fixedSource = $@" -using Microsoft.CodeAnalysis; -class TestClass {{ - bool Method(Symbol x, {symbolType} y) {{ - return SymbolEqualityComparer.Default.Equals(x, y); - }} -}} -"; + var source = $$""" + using Microsoft.CodeAnalysis; + class TestClass { + bool Method(Symbol x, {{symbolType}} y) { + return [|x == y|]; + } + } + """; + var fixedSource = $$""" + using Microsoft.CodeAnalysis; + class TestClass { + bool Method(Symbol x, {{symbolType}} y) { + return SymbolEqualityComparer.Default.Equals(x, y); + } + } + """; await new VerifyCS.Test { @@ -329,22 +323,22 @@ bool Method(Symbol x, {symbolType} y) {{ [InlineData(nameof(INamedTypeSymbol))] public async Task CompareSymbolImplementationWithInterface_NoComparer_CSharpAsync(string symbolType) { - var source = $@" -using Microsoft.CodeAnalysis; -class TestClass {{ - bool Method(Symbol x, {symbolType} y) {{ - return [|x == y|]; - }} -}} -"; - var fixedSource = $@" -using Microsoft.CodeAnalysis; -class TestClass {{ - bool Method(Symbol x, {symbolType} y) {{ - return Equals(x, y); - }} -}} -"; + var source = $$""" + using Microsoft.CodeAnalysis; + class TestClass { + bool Method(Symbol x, {{symbolType}} y) { + return [|x == y|]; + } + } + """; + var fixedSource = $$""" + using Microsoft.CodeAnalysis; + class TestClass { + bool Method(Symbol x, {{symbolType}} y) { + return Equals(x, y); + } + } + """; await new VerifyCS.Test { @@ -355,65 +349,57 @@ bool Method(Symbol x, {symbolType} y) {{ [Theory] [CombinatorialData] - public async Task CompareSymbolWithNull_CSharpAsync( + public Task CompareSymbolWithNull_CSharpAsync( [CombinatorialValues(nameof(ISymbol), nameof(INamedTypeSymbol))] string symbolType, [CombinatorialValues("==", "!=")] string @operator, [CombinatorialValues("null", "default", "default(ISymbol)")] string value) - { - var source = $@" -using Microsoft.CodeAnalysis; -class TestClass {{ - bool Method1({symbolType} x) {{ - return x {@operator} {value}; - }} - - bool Method2({symbolType} x) {{ - return {value} {@operator} x; - }} -}} -"; - - await VerifyCS.VerifyAnalyzerAsync(source); - } + => VerifyCS.VerifyAnalyzerAsync($$""" + using Microsoft.CodeAnalysis; + class TestClass { + bool Method1({{symbolType}} x) { + return x {{@operator}} {{value}}; + } + + bool Method2({{symbolType}} x) { + return {{value}} {{@operator}} x; + } + } + """); [Theory] [InlineData(nameof(ISymbol))] [InlineData(nameof(INamedTypeSymbol))] - public async Task CompareSymbolWithNullPattern_CSharpAsync(string symbolType) - { - var source = $@" -using Microsoft.CodeAnalysis; -class TestClass {{ - bool Method1({symbolType} x) {{ - return x is null; - }} -}} -"; - - await VerifyCS.VerifyAnalyzerAsync(source); - } + public Task CompareSymbolWithNullPattern_CSharpAsync(string symbolType) + => VerifyCS.VerifyAnalyzerAsync($$""" + using Microsoft.CodeAnalysis; + class TestClass { + bool Method1({{symbolType}} x) { + return x is null; + } + } + """); [Theory] [InlineData(nameof(ISymbol))] [InlineData(nameof(INamedTypeSymbol))] public async Task CompareTwoSymbolsEquals_VisualBasicAsync(string symbolType) { - var source = $@" -Imports Microsoft.CodeAnalysis -Class TestClass - Function Method(x As {symbolType}, y As {symbolType}) As Boolean - Return [|x Is y|] - End Function -End Class -"; - var fixedSource = $@" -Imports Microsoft.CodeAnalysis -Class TestClass - Function Method(x As {symbolType}, y As {symbolType}) As Boolean - Return SymbolEqualityComparer.Default.Equals(x, y) - End Function -End Class -"; + var source = $""" + Imports Microsoft.CodeAnalysis + Class TestClass + Function Method(x As {symbolType}, y As {symbolType}) As Boolean + Return [|x Is y|] + End Function + End Class + """; + var fixedSource = $""" + Imports Microsoft.CodeAnalysis + Class TestClass + Function Method(x As {symbolType}, y As {symbolType}) As Boolean + Return SymbolEqualityComparer.Default.Equals(x, y) + End Function + End Class + """; await new VerifyVB.Test { @@ -425,45 +411,36 @@ End Class [Theory] [InlineData(nameof(ISymbol))] [InlineData(nameof(INamedTypeSymbol))] - public async Task CompareTwoSymbolsEquals_NoComparer_VisualBasicAsync(string symbolType) - { - var source = $@" -Imports Microsoft.CodeAnalysis -Class TestClass - Function Method(x As {symbolType}, y As {symbolType}) As Boolean - Return [|x Is y|] - End Function -End Class -"; - var fixedSource = $@" -Imports Microsoft.CodeAnalysis -Class TestClass - Function Method(x As {symbolType}, y As {symbolType}) As Boolean - Return Equals(x, y) - End Function -End Class -"; - - await VerifyVB.VerifyCodeFixAsync(source, fixedSource); - } + public Task CompareTwoSymbolsEquals_NoComparer_VisualBasicAsync(string symbolType) + => VerifyVB.VerifyCodeFixAsync($""" + Imports Microsoft.CodeAnalysis + Class TestClass + Function Method(x As {symbolType}, y As {symbolType}) As Boolean + Return [|x Is y|] + End Function + End Class + """, $""" + Imports Microsoft.CodeAnalysis + Class TestClass + Function Method(x As {symbolType}, y As {symbolType}) As Boolean + Return Equals(x, y) + End Function + End Class + """); [Theory] [WorkItem(2335, "https://github.com/dotnet/roslyn-analyzers/issues/2335")] [InlineData(nameof(ISymbol))] [InlineData(nameof(INamedTypeSymbol))] - public async Task CompareTwoSymbolsByIdentity_VisualBasicAsync(string symbolType) - { - var source = $@" -Imports Microsoft.CodeAnalysis -Class TestClass - Function Method(x As {symbolType}, y As {symbolType}) As Boolean - Return DirectCast(x, Object) Is y - End Function -End Class -"; - - await VerifyVB.VerifyAnalyzerAsync(source); - } + public Task CompareTwoSymbolsByIdentity_VisualBasicAsync(string symbolType) + => VerifyVB.VerifyAnalyzerAsync($""" + Imports Microsoft.CodeAnalysis + Class TestClass + Function Method(x As {symbolType}, y As {symbolType}) As Boolean + Return DirectCast(x, Object) Is y + End Function + End Class + """); [Theory] [WorkItem(2336, "https://github.com/dotnet/roslyn-analyzers/issues/2336")] @@ -472,18 +449,18 @@ public async Task CompareTwoSymbolImplementations_VisualBasicAsync( [CombinatorialValues("Symbol", nameof(ISymbol), nameof(INamedTypeSymbol))] string symbolType, [CombinatorialValues("=", "<>", "Is", "IsNot")] string @operator) { - var source = $@" -Imports Microsoft.CodeAnalysis -Class TestClass - Function Method1(x As Symbol, y As {symbolType}) As Boolean - Return x {@operator} y - End Function - - Function Method2(x As Symbol, y As {symbolType}) As Boolean - Return y {@operator} x - End Function -End Class -"; + var source = $""" + Imports Microsoft.CodeAnalysis + Class TestClass + Function Method1(x As Symbol, y As {symbolType}) As Boolean + Return x {@operator} y + End Function + + Function Method2(x As Symbol, y As {symbolType}) As Boolean + Return y {@operator} x + End Function + End Class + """; await new VerifyVB.Test { @@ -493,25 +470,21 @@ End Class [Theory] [CombinatorialData] - public async Task CompareSymbolWithNull_VisualBasicAsync( + public Task CompareSymbolWithNull_VisualBasicAsync( [CombinatorialValues(nameof(ISymbol), nameof(INamedTypeSymbol))] string symbolType, [CombinatorialValues("Is", "IsNot")] string @operator) - { - var source = $@" -Imports Microsoft.CodeAnalysis -Class TestClass - Function Method1(x As {symbolType}) As Boolean - Return x {@operator} Nothing - End Function - - Function Method2(x As {symbolType}) As Boolean - Return Nothing {@operator} x - End Function -End Class -"; - - await VerifyVB.VerifyAnalyzerAsync(source); - } + => VerifyVB.VerifyAnalyzerAsync($""" + Imports Microsoft.CodeAnalysis + Class TestClass + Function Method1(x As {symbolType}) As Boolean + Return x {@operator} Nothing + End Function + + Function Method2(x As {symbolType}) As Boolean + Return Nothing {@operator} x + End Function + End Class + """); [Theory] [CombinatorialData] @@ -519,23 +492,23 @@ public async Task CompareSymbolFromInstanceEquals_VisualBasicAsync( [CombinatorialValues(nameof(ISymbol), nameof(INamedTypeSymbol))] string symbolType, [CombinatorialValues("", "Not ")] string @operator) { - var source = $@" -Imports Microsoft.CodeAnalysis -Class TestClass - Sub Method1(x As {symbolType}, y As {symbolType}) - If {@operator}[|x.Equals(y)|] Then Exit Sub - End Sub -End Class -"; - - var fixedSource = $@" -Imports Microsoft.CodeAnalysis -Class TestClass - Sub Method1(x As {symbolType}, y As {symbolType}) - If {@operator}SymbolEqualityComparer.Default.Equals(x, y) Then Exit Sub - End Sub -End Class -"; + var source = $""" + Imports Microsoft.CodeAnalysis + Class TestClass + Sub Method1(x As {symbolType}, y As {symbolType}) + If {@operator}[|x.Equals(y)|] Then Exit Sub + End Sub + End Class + """; + + var fixedSource = $""" + Imports Microsoft.CodeAnalysis + Class TestClass + Sub Method1(x As {symbolType}, y As {symbolType}) + If {@operator}SymbolEqualityComparer.Default.Equals(x, y) Then Exit Sub + End Sub + End Class + """; await new VerifyVB.Test { @@ -550,27 +523,27 @@ public async Task CompareSymbolFromInstanceEquals_CSharpAsync( [CombinatorialValues(nameof(ISymbol), nameof(INamedTypeSymbol))] string symbolType, [CombinatorialValues("", "!")] string @operator) { - var source = $@" -using Microsoft.CodeAnalysis; -class TestClass -{{ - void Method1({symbolType} x , {symbolType} y) - {{ - if ({@operator}[|x.Equals(y)|]) return; - }} -}} -"; - - var fixedSource = $@" -using Microsoft.CodeAnalysis; -class TestClass -{{ - void Method1({symbolType} x , {symbolType} y) - {{ - if ({@operator}SymbolEqualityComparer.Default.Equals(x, y)) return; - }} -}} -"; + var source = $$""" + using Microsoft.CodeAnalysis; + class TestClass + { + void Method1({{symbolType}} x , {{symbolType}} y) + { + if ({{@operator}}[|x.Equals(y)|]) return; + } + } + """; + + var fixedSource = $$""" + using Microsoft.CodeAnalysis; + class TestClass + { + void Method1({{symbolType}} x , {{symbolType}} y) + { + if ({{@operator}}SymbolEqualityComparer.Default.Equals(x, y)) return; + } + } + """; await new VerifyCS.Test { @@ -582,23 +555,23 @@ void Method1({symbolType} x , {symbolType} y) [Fact] public async Task CompareSymbolFromInstanceEqualsWithConditionalAccess_VisualBasicAsync() { - var source = @" -Imports Microsoft.CodeAnalysis -Class TestClass - Sub Method1(x As ISymbol, y As ISymbol) - If x?[|.Equals(y)|] Then Exit Sub - End Sub -End Class -"; - - var fixedSource = @" -Imports Microsoft.CodeAnalysis -Class TestClass - Sub Method1(x As ISymbol, y As ISymbol) - If SymbolEqualityComparer.Default.Equals(x, y) Then Exit Sub - End Sub -End Class -"; + var source = """ + Imports Microsoft.CodeAnalysis + Class TestClass + Sub Method1(x As ISymbol, y As ISymbol) + If x?[|.Equals(y)|] Then Exit Sub + End Sub + End Class + """; + + var fixedSource = """ + Imports Microsoft.CodeAnalysis + Class TestClass + Sub Method1(x As ISymbol, y As ISymbol) + If SymbolEqualityComparer.Default.Equals(x, y) Then Exit Sub + End Sub + End Class + """; await new VerifyVB.Test { @@ -610,27 +583,27 @@ End Class [Fact] public async Task CompareSymbolFromInstanceEqualsWithNullConditionalAccess_CSharpAsync() { - var source = @" -using Microsoft.CodeAnalysis; -class TestClass -{ - void Method1(ISymbol x, ISymbol y) - { - if (x?[|.Equals(y)|] == true) return; - } -} -"; + var source = """ + using Microsoft.CodeAnalysis; + class TestClass + { + void Method1(ISymbol x, ISymbol y) + { + if (x?[|.Equals(y)|] == true) return; + } + } + """; - var fixedSource = @" -using Microsoft.CodeAnalysis; -class TestClass -{ - void Method1(ISymbol x, ISymbol y) - { - if (SymbolEqualityComparer.Default.Equals(x, y) == true) return; - } -} -"; + var fixedSource = """ + using Microsoft.CodeAnalysis; + class TestClass + { + void Method1(ISymbol x, ISymbol y) + { + if (SymbolEqualityComparer.Default.Equals(x, y) == true) return; + } + } + """; await new VerifyCS.Test { @@ -642,43 +615,43 @@ void Method1(ISymbol x, ISymbol y) [Fact] public async Task CompareSymbolFromInstanceEqualsWithChainConditionalAccess_VisualBasicAsync() { - var source = @" -Imports Microsoft.CodeAnalysis - -Class A - Public b As B -End Class - -Class B - Public s As ISymbol -End Class - -Class TestClass - Sub Method1(a As A, b As B, s As ISymbol) - If a?.b?.s?[|.Equals(s)|] Then Exit Sub - If b?.s?[|.Equals(s)|] Then Exit Sub - End Sub -End Class -"; - - var fixedSource = @" -Imports Microsoft.CodeAnalysis - -Class A - Public b As B -End Class - -Class B - Public s As ISymbol -End Class - -Class TestClass - Sub Method1(a As A, b As B, s As ISymbol) - If SymbolEqualityComparer.Default.Equals(a?.b?.s, s) Then Exit Sub - If SymbolEqualityComparer.Default.Equals(b?.s, s) Then Exit Sub - End Sub -End Class -"; + var source = """ + Imports Microsoft.CodeAnalysis + + Class A + Public b As B + End Class + + Class B + Public s As ISymbol + End Class + + Class TestClass + Sub Method1(a As A, b As B, s As ISymbol) + If a?.b?.s?[|.Equals(s)|] Then Exit Sub + If b?.s?[|.Equals(s)|] Then Exit Sub + End Sub + End Class + """; + + var fixedSource = """ + Imports Microsoft.CodeAnalysis + + Class A + Public b As B + End Class + + Class B + Public s As ISymbol + End Class + + Class TestClass + Sub Method1(a As A, b As B, s As ISymbol) + If SymbolEqualityComparer.Default.Equals(a?.b?.s, s) Then Exit Sub + If SymbolEqualityComparer.Default.Equals(b?.s, s) Then Exit Sub + End Sub + End Class + """; await new VerifyVB.Test { @@ -690,51 +663,51 @@ End Class [Fact] public async Task CompareSymbolFromInstanceEqualsWithChainNullConditionalAccess_CSharpAsync() { - var source = @" -using Microsoft.CodeAnalysis; + var source = """ + using Microsoft.CodeAnalysis; -class A -{ - public B b; -} + class A + { + public B b; + } -class B -{ - public ISymbol s; -} + class B + { + public ISymbol s; + } -class TestClass -{ - void Method1(A a, B b, ISymbol s) - { - if (a?.b?.s?[|.Equals(s)|] == true) return; - if (b?.s?[|.Equals(s)|] == true) return; - } -} -"; + class TestClass + { + void Method1(A a, B b, ISymbol s) + { + if (a?.b?.s?[|.Equals(s)|] == true) return; + if (b?.s?[|.Equals(s)|] == true) return; + } + } + """; - var fixedSource = @" -using Microsoft.CodeAnalysis; + var fixedSource = """ + using Microsoft.CodeAnalysis; -class A -{ - public B b; -} + class A + { + public B b; + } -class B -{ - public ISymbol s; -} + class B + { + public ISymbol s; + } -class TestClass -{ - void Method1(A a, B b, ISymbol s) - { - if (SymbolEqualityComparer.Default.Equals(a?.b?.s, s) == true) return; - if (SymbolEqualityComparer.Default.Equals(b?.s, s) == true) return; - } -} -"; + class TestClass + { + void Method1(A a, B b, ISymbol s) + { + if (SymbolEqualityComparer.Default.Equals(a?.b?.s, s) == true) return; + if (SymbolEqualityComparer.Default.Equals(b?.s, s) == true) return; + } + } + """; await new VerifyCS.Test { @@ -746,53 +719,55 @@ void Method1(A a, B b, ISymbol s) [Fact] public async Task CompareSymbolFromInstanceEqualsWithChain_CSharpAsync() { - var source = @" -using Microsoft.CodeAnalysis; + var source = """ + using Microsoft.CodeAnalysis; -class A -{ - public B b; - public B GetB() => null; -} + class A + { + public B b; + public B GetB() => null; + } -class B -{ - public ISymbol s; - public ISymbol GetS() => null; -} + class B + { + public ISymbol s; + public ISymbol GetS() => null; + } -class TestClass -{ - void Method1(A a, ISymbol symbol) - { - if ([|a.b.s.Equals(symbol)|] == true) return; - if ([|a.GetB().GetS().Equals(symbol)|] == true) return; - } -}"; + class TestClass + { + void Method1(A a, ISymbol symbol) + { + if ([|a.b.s.Equals(symbol)|] == true) return; + if ([|a.GetB().GetS().Equals(symbol)|] == true) return; + } + } + """; - var fixedSource = @" -using Microsoft.CodeAnalysis; + var fixedSource = """ + using Microsoft.CodeAnalysis; -class A -{ - public B b; - public B GetB() => null; -} + class A + { + public B b; + public B GetB() => null; + } -class B -{ - public ISymbol s; - public ISymbol GetS() => null; -} + class B + { + public ISymbol s; + public ISymbol GetS() => null; + } -class TestClass -{ - void Method1(A a, ISymbol symbol) - { - if (SymbolEqualityComparer.Default.Equals(a.b.s, symbol) == true) return; - if (SymbolEqualityComparer.Default.Equals(a.GetB().GetS(), symbol) == true) return; - } -}"; + class TestClass + { + void Method1(A a, ISymbol symbol) + { + if (SymbolEqualityComparer.Default.Equals(a.b.s, symbol) == true) return; + if (SymbolEqualityComparer.Default.Equals(a.GetB().GetS(), symbol) == true) return; + } + } + """; await new VerifyCS.Test { @@ -806,22 +781,22 @@ void Method1(A a, ISymbol symbol) [InlineData(nameof(INamedTypeSymbol))] public async Task CompareSymbolImplementationWithInterface_EqualsComparison_CSharpAsync(string symbolType) { - var source = $@" -using Microsoft.CodeAnalysis; -class TestClass {{ - bool Method(ISymbol x, {symbolType} y) {{ - return [|Equals(x, y)|]; - }} -}} -"; - var fixedSource = $@" -using Microsoft.CodeAnalysis; -class TestClass {{ - bool Method(ISymbol x, {symbolType} y) {{ - return SymbolEqualityComparer.Default.Equals(x, y); - }} -}} -"; + var source = $$""" + using Microsoft.CodeAnalysis; + class TestClass { + bool Method(ISymbol x, {{symbolType}} y) { + return [|Equals(x, y)|]; + } + } + """; + var fixedSource = $$""" + using Microsoft.CodeAnalysis; + class TestClass { + bool Method(ISymbol x, {{symbolType}} y) { + return SymbolEqualityComparer.Default.Equals(x, y); + } + } + """; await new VerifyCS.Test { @@ -833,24 +808,26 @@ bool Method(ISymbol x, {symbolType} y) {{ [Fact, WorkItem(2493, "https://github.com/dotnet/roslyn-analyzers/issues/2493")] public async Task GetHashCode_DiagnosticAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -using Microsoft.CodeAnalysis; -public class C -{ - public int M(ISymbol symbol, INamedTypeSymbol namedType) - { - return [|symbol.GetHashCode()|] + [|namedType.GetHashCode()|]; - } -}"); + await VerifyCS.VerifyAnalyzerAsync(""" + using Microsoft.CodeAnalysis; + public class C + { + public int M(ISymbol symbol, INamedTypeSymbol namedType) + { + return [|symbol.GetHashCode()|] + [|namedType.GetHashCode()|]; + } + } + """); - await VerifyVB.VerifyAnalyzerAsync(@" -Imports Microsoft.CodeAnalysis + await VerifyVB.VerifyAnalyzerAsync(""" + Imports Microsoft.CodeAnalysis -Public Class C - Public Function M(ByVal symbol As ISymbol, ByVal namedType As INamedTypeSymbol) As Integer - Return [|symbol.GetHashCode()|] + [|namedType.GetHashCode()|] - End Function -End Class"); + Public Class C + Public Function M(ByVal symbol As ISymbol, ByVal namedType As INamedTypeSymbol) As Integer + Return [|symbol.GetHashCode()|] + [|namedType.GetHashCode()|] + End Function + End Class + """); } [Fact, WorkItem(2493, "https://github.com/dotnet/roslyn-analyzers/issues/2493")] @@ -863,41 +840,42 @@ public async Task CollectionConstructorsKnownToRequireComparer_DiagnosticAsync() ReferenceAssemblies = CreateNetCoreReferenceAssemblies(), Sources = { - @" -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using Microsoft.CodeAnalysis; - -public class C -{ - public void MethodWithDiagnostics(IEnumerable symbols) - { - var kvps = symbols.Select(s => new KeyValuePair(s, 0)); - - [|new Dictionary()|]; - [|new Dictionary(42)|]; - [|new Dictionary(capacity: 42)|]; - [|new Dictionary(kvps)|]; - - [|new HashSet()|]; - [|new HashSet(42)|]; - [|new HashSet(symbols)|]; - - [|new ConcurrentDictionary()|]; - [|new ConcurrentDictionary(kvps)|]; - [|new ConcurrentDictionary(1, 42)|]; - } - - public void MethodWithoutDiagnostics() - { - new Dictionary(); - new HashSet(); - new ConcurrentDictionary(); - - new Dictionary(SymbolEqualityComparer.Default); - } -}", + """ + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Linq; + using Microsoft.CodeAnalysis; + + public class C + { + public void MethodWithDiagnostics(IEnumerable symbols) + { + var kvps = symbols.Select(s => new KeyValuePair(s, 0)); + + [|new Dictionary()|]; + [|new Dictionary(42)|]; + [|new Dictionary(capacity: 42)|]; + [|new Dictionary(kvps)|]; + + [|new HashSet()|]; + [|new HashSet(42)|]; + [|new HashSet(symbols)|]; + + [|new ConcurrentDictionary()|]; + [|new ConcurrentDictionary(kvps)|]; + [|new ConcurrentDictionary(1, 42)|]; + } + + public void MethodWithoutDiagnostics() + { + new Dictionary(); + new HashSet(); + new ConcurrentDictionary(); + + new Dictionary(SymbolEqualityComparer.Default); + } + } + """, SymbolEqualityComparerStubCSharp, }, }, @@ -905,41 +883,42 @@ public void MethodWithoutDiagnostics() { Sources = { - @" -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using Microsoft.CodeAnalysis; - -public class C -{ - public void MethodWithDiagnostics(IEnumerable symbols) - { - var kvps = symbols.Select(s => new KeyValuePair(s, 0)); - - new Dictionary(SymbolEqualityComparer.Default); - new Dictionary(42, SymbolEqualityComparer.Default); - new Dictionary(capacity: 42, SymbolEqualityComparer.Default); - new Dictionary(kvps, SymbolEqualityComparer.Default); - - new HashSet(SymbolEqualityComparer.Default); - new HashSet(42, SymbolEqualityComparer.Default); - new HashSet(symbols, SymbolEqualityComparer.Default); - - new ConcurrentDictionary(SymbolEqualityComparer.Default); - new ConcurrentDictionary(kvps, SymbolEqualityComparer.Default); - new ConcurrentDictionary(1, 42, SymbolEqualityComparer.Default); - } - - public void MethodWithoutDiagnostics() - { - new Dictionary(); - new HashSet(); - new ConcurrentDictionary(); - - new Dictionary(SymbolEqualityComparer.Default); - } -}", + """ + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Linq; + using Microsoft.CodeAnalysis; + + public class C + { + public void MethodWithDiagnostics(IEnumerable symbols) + { + var kvps = symbols.Select(s => new KeyValuePair(s, 0)); + + new Dictionary(SymbolEqualityComparer.Default); + new Dictionary(42, SymbolEqualityComparer.Default); + new Dictionary(capacity: 42, SymbolEqualityComparer.Default); + new Dictionary(kvps, SymbolEqualityComparer.Default); + + new HashSet(SymbolEqualityComparer.Default); + new HashSet(42, SymbolEqualityComparer.Default); + new HashSet(symbols, SymbolEqualityComparer.Default); + + new ConcurrentDictionary(SymbolEqualityComparer.Default); + new ConcurrentDictionary(kvps, SymbolEqualityComparer.Default); + new ConcurrentDictionary(1, 42, SymbolEqualityComparer.Default); + } + + public void MethodWithoutDiagnostics() + { + new Dictionary(); + new HashSet(); + new ConcurrentDictionary(); + + new Dictionary(SymbolEqualityComparer.Default); + } + } + """, SymbolEqualityComparerStubCSharp, } } @@ -952,37 +931,38 @@ public void MethodWithoutDiagnostics() ReferenceAssemblies = CreateNetCoreReferenceAssemblies(), Sources = { - @" -Imports System.Collections.Concurrent -Imports System.Collections.Generic -Imports System.Linq -Imports Microsoft.CodeAnalysis - -Public Class C - Public Sub MethodWithDiagnostics(symbols As IEnumerable(Of ISymbol)) - Dim kvps = symbols.[Select](Function(s) New KeyValuePair(Of ISymbol, Integer)(s, 0)) - - Dim x11 = [|New Dictionary(Of ISymbol, Integer)()|] - Dim x12 = [|New Dictionary(Of ISymbol, Integer)(42)|] - Dim x13 = [|New Dictionary(Of ISymbol, Integer)(kvps)|] - - Dim x21 = [|New HashSet(Of ISymbol)()|] - Dim x22 = [|New HashSet(Of ISymbol)(42)|] - Dim x23 = [|New HashSet(Of ISymbol)(symbols)|] - - Dim x31 = [|New ConcurrentDictionary(Of ISymbol, Integer)()|] - Dim x32 = [|New ConcurrentDictionary(Of ISymbol, Integer)(kvps)|] - Dim x33 = [|New ConcurrentDictionary(Of ISymbol, Integer)(1, 42)|] - End Sub - - Public Sub MethodWithoutDiagnostics() - Dim x1 = New Dictionary(Of Integer, ISymbol)() - Dim x2 = New HashSet(Of String)() - Dim x3 = New ConcurrentDictionary(Of Integer, ISymbol)() - - Dim x4 = New Dictionary(Of ISymbol, Integer)(SymbolEqualityComparer.Default) - End Sub -End Class", + """ + Imports System.Collections.Concurrent + Imports System.Collections.Generic + Imports System.Linq + Imports Microsoft.CodeAnalysis + + Public Class C + Public Sub MethodWithDiagnostics(symbols As IEnumerable(Of ISymbol)) + Dim kvps = symbols.[Select](Function(s) New KeyValuePair(Of ISymbol, Integer)(s, 0)) + + Dim x11 = [|New Dictionary(Of ISymbol, Integer)()|] + Dim x12 = [|New Dictionary(Of ISymbol, Integer)(42)|] + Dim x13 = [|New Dictionary(Of ISymbol, Integer)(kvps)|] + + Dim x21 = [|New HashSet(Of ISymbol)()|] + Dim x22 = [|New HashSet(Of ISymbol)(42)|] + Dim x23 = [|New HashSet(Of ISymbol)(symbols)|] + + Dim x31 = [|New ConcurrentDictionary(Of ISymbol, Integer)()|] + Dim x32 = [|New ConcurrentDictionary(Of ISymbol, Integer)(kvps)|] + Dim x33 = [|New ConcurrentDictionary(Of ISymbol, Integer)(1, 42)|] + End Sub + + Public Sub MethodWithoutDiagnostics() + Dim x1 = New Dictionary(Of Integer, ISymbol)() + Dim x2 = New HashSet(Of String)() + Dim x3 = New ConcurrentDictionary(Of Integer, ISymbol)() + + Dim x4 = New Dictionary(Of ISymbol, Integer)(SymbolEqualityComparer.Default) + End Sub + End Class + """, SymbolEqualityComparerStubVisualBasic, }, }, @@ -990,37 +970,38 @@ End Sub { Sources = { - @" -Imports System.Collections.Concurrent -Imports System.Collections.Generic -Imports System.Linq -Imports Microsoft.CodeAnalysis - -Public Class C - Public Sub MethodWithDiagnostics(symbols As IEnumerable(Of ISymbol)) - Dim kvps = symbols.[Select](Function(s) New KeyValuePair(Of ISymbol, Integer)(s, 0)) - - Dim x11 = New Dictionary(Of ISymbol, Integer)(SymbolEqualityComparer.Default) - Dim x12 = New Dictionary(Of ISymbol, Integer)(42, SymbolEqualityComparer.Default) - Dim x13 = New Dictionary(Of ISymbol, Integer)(kvps, SymbolEqualityComparer.Default) - - Dim x21 = New HashSet(Of ISymbol)(SymbolEqualityComparer.Default) - Dim x22 = New HashSet(Of ISymbol)(42, SymbolEqualityComparer.Default) - Dim x23 = New HashSet(Of ISymbol)(symbols, SymbolEqualityComparer.Default) - - Dim x31 = New ConcurrentDictionary(Of ISymbol, Integer)(SymbolEqualityComparer.Default) - Dim x32 = New ConcurrentDictionary(Of ISymbol, Integer)(kvps, SymbolEqualityComparer.Default) - Dim x33 = New ConcurrentDictionary(Of ISymbol, Integer)(1, 42, SymbolEqualityComparer.Default) - End Sub - - Public Sub MethodWithoutDiagnostics() - Dim x1 = New Dictionary(Of Integer, ISymbol)() - Dim x2 = New HashSet(Of String)() - Dim x3 = New ConcurrentDictionary(Of Integer, ISymbol)() - - Dim x4 = New Dictionary(Of ISymbol, Integer)(SymbolEqualityComparer.Default) - End Sub -End Class", + """ + Imports System.Collections.Concurrent + Imports System.Collections.Generic + Imports System.Linq + Imports Microsoft.CodeAnalysis + + Public Class C + Public Sub MethodWithDiagnostics(symbols As IEnumerable(Of ISymbol)) + Dim kvps = symbols.[Select](Function(s) New KeyValuePair(Of ISymbol, Integer)(s, 0)) + + Dim x11 = New Dictionary(Of ISymbol, Integer)(SymbolEqualityComparer.Default) + Dim x12 = New Dictionary(Of ISymbol, Integer)(42, SymbolEqualityComparer.Default) + Dim x13 = New Dictionary(Of ISymbol, Integer)(kvps, SymbolEqualityComparer.Default) + + Dim x21 = New HashSet(Of ISymbol)(SymbolEqualityComparer.Default) + Dim x22 = New HashSet(Of ISymbol)(42, SymbolEqualityComparer.Default) + Dim x23 = New HashSet(Of ISymbol)(symbols, SymbolEqualityComparer.Default) + + Dim x31 = New ConcurrentDictionary(Of ISymbol, Integer)(SymbolEqualityComparer.Default) + Dim x32 = New ConcurrentDictionary(Of ISymbol, Integer)(kvps, SymbolEqualityComparer.Default) + Dim x33 = New ConcurrentDictionary(Of ISymbol, Integer)(1, 42, SymbolEqualityComparer.Default) + End Sub + + Public Sub MethodWithoutDiagnostics() + Dim x1 = New Dictionary(Of Integer, ISymbol)() + Dim x2 = New HashSet(Of String)() + Dim x3 = New ConcurrentDictionary(Of Integer, ISymbol)() + + Dim x4 = New Dictionary(Of ISymbol, Integer)(SymbolEqualityComparer.Default) + End Sub + End Class + """, SymbolEqualityComparerStubVisualBasic, }, } @@ -1036,65 +1017,66 @@ public async Task CollectionMethodsKnownToRequireComparer_DiagnosticAsync() { Sources = { - @" -using System; -using System.Collections.Immutable; -using System.Collections.Generic; -using System.Linq; -using Microsoft.CodeAnalysis; -public class C -{ - public void MethodWithDiagnostics(IEnumerable> kvps, IEnumerable symbols, IEnumerable symbols2, ISymbol symbol) - { - [|ImmutableHashSet.Create()|]; - [|ImmutableHashSet.CreateBuilder()|]; - [|ImmutableHashSet.CreateRange(symbols)|]; - [|symbols.ToImmutableHashSet()|]; - - [|ImmutableDictionary.Create()|]; - [|ImmutableDictionary.CreateBuilder()|]; - [|ImmutableDictionary.CreateRange(kvps)|]; - [|kvps.ToImmutableDictionary()|]; - - [|symbols.Contains(symbol)|]; - [|symbols.Distinct()|]; - [|symbols.GroupBy(x => x)|]; - [|symbols.GroupJoin(symbols2, x => x, x => x, (x, y) => x)|]; - [|symbols.Intersect(symbols2)|]; - [|symbols.Join(symbols2, x => x, x => x, (x, y) => x)|]; - [|symbols.SequenceEqual(symbols2)|]; - [|symbols.ToDictionary(x => x)|]; - [|symbols.ToLookup(x => x)|]; - [|symbols.Union(symbols2)|]; - - [|ImmutableHashSet.ToImmutableHashSet(symbols)|]; - symbols?[|.ToImmutableHashSet()|]; - } - - public void MethodWithoutDiagnostics(IEnumerable> kvps, IEnumerable integers, int integer) - { - ImmutableHashSet.Create(); - ImmutableHashSet.CreateBuilder(); - ImmutableHashSet.CreateRange(integers); - integers.ToImmutableHashSet(); - - ImmutableDictionary.Create(); - ImmutableDictionary.CreateBuilder(); - ImmutableDictionary.CreateRange(kvps); - kvps.ToImmutableDictionary(); - - integers.Contains(integer); - integers.Distinct(); - integers.GroupBy(x => x); - integers.GroupJoin(integers, x => x, x => x, (x, y) => x); - integers.Intersect(integers); - integers.Join(integers, x => x, x => x, (x, y) => x); - integers.SequenceEqual(integers); - integers.ToDictionary(x => x); - integers.ToLookup(x => x); - integers.Union(integers); - } -}", + """ + using System; + using System.Collections.Immutable; + using System.Collections.Generic; + using System.Linq; + using Microsoft.CodeAnalysis; + public class C + { + public void MethodWithDiagnostics(IEnumerable> kvps, IEnumerable symbols, IEnumerable symbols2, ISymbol symbol) + { + [|ImmutableHashSet.Create()|]; + [|ImmutableHashSet.CreateBuilder()|]; + [|ImmutableHashSet.CreateRange(symbols)|]; + [|symbols.ToImmutableHashSet()|]; + + [|ImmutableDictionary.Create()|]; + [|ImmutableDictionary.CreateBuilder()|]; + [|ImmutableDictionary.CreateRange(kvps)|]; + [|kvps.ToImmutableDictionary()|]; + + [|symbols.Contains(symbol)|]; + [|symbols.Distinct()|]; + [|symbols.GroupBy(x => x)|]; + [|symbols.GroupJoin(symbols2, x => x, x => x, (x, y) => x)|]; + [|symbols.Intersect(symbols2)|]; + [|symbols.Join(symbols2, x => x, x => x, (x, y) => x)|]; + [|symbols.SequenceEqual(symbols2)|]; + [|symbols.ToDictionary(x => x)|]; + [|symbols.ToLookup(x => x)|]; + [|symbols.Union(symbols2)|]; + + [|ImmutableHashSet.ToImmutableHashSet(symbols)|]; + symbols?[|.ToImmutableHashSet()|]; + } + + public void MethodWithoutDiagnostics(IEnumerable> kvps, IEnumerable integers, int integer) + { + ImmutableHashSet.Create(); + ImmutableHashSet.CreateBuilder(); + ImmutableHashSet.CreateRange(integers); + integers.ToImmutableHashSet(); + + ImmutableDictionary.Create(); + ImmutableDictionary.CreateBuilder(); + ImmutableDictionary.CreateRange(kvps); + kvps.ToImmutableDictionary(); + + integers.Contains(integer); + integers.Distinct(); + integers.GroupBy(x => x); + integers.GroupJoin(integers, x => x, x => x, (x, y) => x); + integers.Intersect(integers); + integers.Join(integers, x => x, x => x, (x, y) => x); + integers.SequenceEqual(integers); + integers.ToDictionary(x => x); + integers.ToLookup(x => x); + integers.Union(integers); + } + } + """, SymbolEqualityComparerStubCSharp, }, }, @@ -1102,65 +1084,66 @@ public void MethodWithoutDiagnostics(IEnumerable> kvp { Sources = { - @" -using System; -using System.Collections.Immutable; -using System.Collections.Generic; -using System.Linq; -using Microsoft.CodeAnalysis; -public class C -{ - public void MethodWithDiagnostics(IEnumerable> kvps, IEnumerable symbols, IEnumerable symbols2, ISymbol symbol) - { - ImmutableHashSet.Create(SymbolEqualityComparer.Default); - ImmutableHashSet.CreateBuilder(SymbolEqualityComparer.Default); - ImmutableHashSet.CreateRange(SymbolEqualityComparer.Default, symbols); - symbols.ToImmutableHashSet(SymbolEqualityComparer.Default); - - ImmutableDictionary.Create(SymbolEqualityComparer.Default); - ImmutableDictionary.CreateBuilder(SymbolEqualityComparer.Default); - ImmutableDictionary.CreateRange(SymbolEqualityComparer.Default, kvps); - kvps.ToImmutableDictionary(SymbolEqualityComparer.Default); - - symbols.Contains(symbol, SymbolEqualityComparer.Default); - symbols.Distinct(SymbolEqualityComparer.Default); - symbols.GroupBy(x => x, SymbolEqualityComparer.Default); - symbols.GroupJoin(symbols2, x => x, x => x, (x, y) => x, SymbolEqualityComparer.Default); - symbols.Intersect(symbols2, SymbolEqualityComparer.Default); - symbols.Join(symbols2, x => x, x => x, (x, y) => x, SymbolEqualityComparer.Default); - symbols.SequenceEqual(symbols2, SymbolEqualityComparer.Default); - symbols.ToDictionary(x => x, SymbolEqualityComparer.Default); - symbols.ToLookup(x => x, SymbolEqualityComparer.Default); - symbols.Union(symbols2, SymbolEqualityComparer.Default); - - ImmutableHashSet.ToImmutableHashSet(symbols, SymbolEqualityComparer.Default); - symbols?.ToImmutableHashSet(SymbolEqualityComparer.Default); - } - - public void MethodWithoutDiagnostics(IEnumerable> kvps, IEnumerable integers, int integer) - { - ImmutableHashSet.Create(); - ImmutableHashSet.CreateBuilder(); - ImmutableHashSet.CreateRange(integers); - integers.ToImmutableHashSet(); - - ImmutableDictionary.Create(); - ImmutableDictionary.CreateBuilder(); - ImmutableDictionary.CreateRange(kvps); - kvps.ToImmutableDictionary(); - - integers.Contains(integer); - integers.Distinct(); - integers.GroupBy(x => x); - integers.GroupJoin(integers, x => x, x => x, (x, y) => x); - integers.Intersect(integers); - integers.Join(integers, x => x, x => x, (x, y) => x); - integers.SequenceEqual(integers); - integers.ToDictionary(x => x); - integers.ToLookup(x => x); - integers.Union(integers); - } -}", + """ + using System; + using System.Collections.Immutable; + using System.Collections.Generic; + using System.Linq; + using Microsoft.CodeAnalysis; + public class C + { + public void MethodWithDiagnostics(IEnumerable> kvps, IEnumerable symbols, IEnumerable symbols2, ISymbol symbol) + { + ImmutableHashSet.Create(SymbolEqualityComparer.Default); + ImmutableHashSet.CreateBuilder(SymbolEqualityComparer.Default); + ImmutableHashSet.CreateRange(SymbolEqualityComparer.Default, symbols); + symbols.ToImmutableHashSet(SymbolEqualityComparer.Default); + + ImmutableDictionary.Create(SymbolEqualityComparer.Default); + ImmutableDictionary.CreateBuilder(SymbolEqualityComparer.Default); + ImmutableDictionary.CreateRange(SymbolEqualityComparer.Default, kvps); + kvps.ToImmutableDictionary(SymbolEqualityComparer.Default); + + symbols.Contains(symbol, SymbolEqualityComparer.Default); + symbols.Distinct(SymbolEqualityComparer.Default); + symbols.GroupBy(x => x, SymbolEqualityComparer.Default); + symbols.GroupJoin(symbols2, x => x, x => x, (x, y) => x, SymbolEqualityComparer.Default); + symbols.Intersect(symbols2, SymbolEqualityComparer.Default); + symbols.Join(symbols2, x => x, x => x, (x, y) => x, SymbolEqualityComparer.Default); + symbols.SequenceEqual(symbols2, SymbolEqualityComparer.Default); + symbols.ToDictionary(x => x, SymbolEqualityComparer.Default); + symbols.ToLookup(x => x, SymbolEqualityComparer.Default); + symbols.Union(symbols2, SymbolEqualityComparer.Default); + + ImmutableHashSet.ToImmutableHashSet(symbols, SymbolEqualityComparer.Default); + symbols?.ToImmutableHashSet(SymbolEqualityComparer.Default); + } + + public void MethodWithoutDiagnostics(IEnumerable> kvps, IEnumerable integers, int integer) + { + ImmutableHashSet.Create(); + ImmutableHashSet.CreateBuilder(); + ImmutableHashSet.CreateRange(integers); + integers.ToImmutableHashSet(); + + ImmutableDictionary.Create(); + ImmutableDictionary.CreateBuilder(); + ImmutableDictionary.CreateRange(kvps); + kvps.ToImmutableDictionary(); + + integers.Contains(integer); + integers.Distinct(); + integers.GroupBy(x => x); + integers.GroupJoin(integers, x => x, x => x, (x, y) => x); + integers.Intersect(integers); + integers.Join(integers, x => x, x => x, (x, y) => x); + integers.SequenceEqual(integers); + integers.ToDictionary(x => x); + integers.ToLookup(x => x); + integers.Union(integers); + } + } + """, SymbolEqualityComparerStubCSharp, }, } @@ -1172,62 +1155,63 @@ public void MethodWithoutDiagnostics(IEnumerable> kvp { Sources = { - @" -Imports System -Imports System.Collections.Immutable -Imports System.Collections.Generic -Imports System.Linq -Imports Microsoft.CodeAnalysis - -Public Class C - Public Sub MethodWithDiagnostics(kvps As IEnumerable(Of KeyValuePair(Of ISymbol, Integer)), symbols As IEnumerable(Of ISymbol), symbols2 As IEnumerable(Of ISymbol), symbol As ISymbol) - Dim x1 = [|ImmutableHashSet.Create(Of ISymbol)()|] - Dim x2 = [|ImmutableHashSet.CreateBuilder(Of ISymbol)()|] - Dim x3 = [|ImmutableHashSet.CreateRange(symbols)|] - Dim x4 = [|symbols.ToImmutableHashSet()|] - - Dim x5 = [|ImmutableDictionary.Create(Of ISymbol, Integer)()|] - Dim x6 = [|ImmutableDictionary.CreateBuilder(Of ISymbol, Integer)()|] - Dim x7 = [|ImmutableDictionary.CreateRange(kvps)|] - Dim x8 = [|kvps.ToImmutableDictionary()|] - - Dim x9 = [|symbols.Contains(symbol)|] - Dim x10 = [|symbols.Distinct()|] - Dim x11 = [|symbols.GroupBy(Function(x) x)|] - Dim x12 = [|symbols.GroupJoin(symbols2, Function(x) x, Function(x) x, Function(x, y) x)|] - Dim x13 = [|symbols.Intersect(symbols2)|] - Dim x14 = [|symbols.Join(symbols2, Function(x) x, Function(x) x, Function(x, y) x)|] - Dim x15 = [|symbols.SequenceEqual(symbols2)|] - Dim x16 = [|symbols.ToDictionary(Function(x) x)|] - Dim x17 = [|symbols.ToLookup(Function(x) x)|] - Dim x18 = [|symbols.Union(symbols2)|] - - Dim x19 = [|ImmutableHashSet.ToImmutableHashSet(symbols)|] - End Sub - - Public Sub MethodWithoutDiagnostics(kvps As IEnumerable(Of KeyValuePair(Of Integer, ISymbol)), integers As IEnumerable(Of Integer), i As Integer) - Dim x1 = ImmutableHashSet.Create(Of Integer)() - Dim x2 = ImmutableHashSet.CreateBuilder(Of Integer)() - Dim x3 = ImmutableHashSet.CreateRange(integers) - Dim x4 = integers.ToImmutableHashSet() - - Dim x5 = ImmutableDictionary.Create(Of Integer, ISymbol)() - Dim x6 = ImmutableDictionary.CreateBuilder(Of Integer, ISymbol)() - Dim x7 = ImmutableDictionary.CreateRange(kvps) - Dim x8 = kvps.ToImmutableDictionary() - - Dim x9 = integers.Contains(i) - Dim x10 = integers.Distinct() - Dim x11 = integers.GroupBy(Function(x) x) - Dim x12 = integers.GroupJoin(integers, Function(x) x, Function(x) x, Function(x, y) x) - Dim x13 = integers.Intersect(integers) - Dim x14 = integers.Join(integers, Function(x) x, Function(x) x, Function(x, y) x) - Dim x15 = integers.SequenceEqual(integers) - Dim x16 = integers.ToDictionary(Function(x) x) - Dim x17 = integers.ToLookup(Function(x) x) - Dim x18 = integers.Union(integers) - End Sub -End Class", + """ + Imports System + Imports System.Collections.Immutable + Imports System.Collections.Generic + Imports System.Linq + Imports Microsoft.CodeAnalysis + + Public Class C + Public Sub MethodWithDiagnostics(kvps As IEnumerable(Of KeyValuePair(Of ISymbol, Integer)), symbols As IEnumerable(Of ISymbol), symbols2 As IEnumerable(Of ISymbol), symbol As ISymbol) + Dim x1 = [|ImmutableHashSet.Create(Of ISymbol)()|] + Dim x2 = [|ImmutableHashSet.CreateBuilder(Of ISymbol)()|] + Dim x3 = [|ImmutableHashSet.CreateRange(symbols)|] + Dim x4 = [|symbols.ToImmutableHashSet()|] + + Dim x5 = [|ImmutableDictionary.Create(Of ISymbol, Integer)()|] + Dim x6 = [|ImmutableDictionary.CreateBuilder(Of ISymbol, Integer)()|] + Dim x7 = [|ImmutableDictionary.CreateRange(kvps)|] + Dim x8 = [|kvps.ToImmutableDictionary()|] + + Dim x9 = [|symbols.Contains(symbol)|] + Dim x10 = [|symbols.Distinct()|] + Dim x11 = [|symbols.GroupBy(Function(x) x)|] + Dim x12 = [|symbols.GroupJoin(symbols2, Function(x) x, Function(x) x, Function(x, y) x)|] + Dim x13 = [|symbols.Intersect(symbols2)|] + Dim x14 = [|symbols.Join(symbols2, Function(x) x, Function(x) x, Function(x, y) x)|] + Dim x15 = [|symbols.SequenceEqual(symbols2)|] + Dim x16 = [|symbols.ToDictionary(Function(x) x)|] + Dim x17 = [|symbols.ToLookup(Function(x) x)|] + Dim x18 = [|symbols.Union(symbols2)|] + + Dim x19 = [|ImmutableHashSet.ToImmutableHashSet(symbols)|] + End Sub + + Public Sub MethodWithoutDiagnostics(kvps As IEnumerable(Of KeyValuePair(Of Integer, ISymbol)), integers As IEnumerable(Of Integer), i As Integer) + Dim x1 = ImmutableHashSet.Create(Of Integer)() + Dim x2 = ImmutableHashSet.CreateBuilder(Of Integer)() + Dim x3 = ImmutableHashSet.CreateRange(integers) + Dim x4 = integers.ToImmutableHashSet() + + Dim x5 = ImmutableDictionary.Create(Of Integer, ISymbol)() + Dim x6 = ImmutableDictionary.CreateBuilder(Of Integer, ISymbol)() + Dim x7 = ImmutableDictionary.CreateRange(kvps) + Dim x8 = kvps.ToImmutableDictionary() + + Dim x9 = integers.Contains(i) + Dim x10 = integers.Distinct() + Dim x11 = integers.GroupBy(Function(x) x) + Dim x12 = integers.GroupJoin(integers, Function(x) x, Function(x) x, Function(x, y) x) + Dim x13 = integers.Intersect(integers) + Dim x14 = integers.Join(integers, Function(x) x, Function(x) x, Function(x, y) x) + Dim x15 = integers.SequenceEqual(integers) + Dim x16 = integers.ToDictionary(Function(x) x) + Dim x17 = integers.ToLookup(Function(x) x) + Dim x18 = integers.Union(integers) + End Sub + End Class + """, SymbolEqualityComparerStubVisualBasic, }, }, @@ -1235,62 +1219,63 @@ End Sub { Sources = { - @" -Imports System -Imports System.Collections.Immutable -Imports System.Collections.Generic -Imports System.Linq -Imports Microsoft.CodeAnalysis - -Public Class C - Public Sub MethodWithDiagnostics(kvps As IEnumerable(Of KeyValuePair(Of ISymbol, Integer)), symbols As IEnumerable(Of ISymbol), symbols2 As IEnumerable(Of ISymbol), symbol As ISymbol) - Dim x1 = ImmutableHashSet.Create(Of ISymbol)(SymbolEqualityComparer.Default) - Dim x2 = ImmutableHashSet.CreateBuilder(Of ISymbol)(SymbolEqualityComparer.Default) - Dim x3 = ImmutableHashSet.CreateRange(SymbolEqualityComparer.Default, symbols) - Dim x4 = symbols.ToImmutableHashSet(SymbolEqualityComparer.Default) - - Dim x5 = ImmutableDictionary.Create(Of ISymbol, Integer)(SymbolEqualityComparer.Default) - Dim x6 = ImmutableDictionary.CreateBuilder(Of ISymbol, Integer)(SymbolEqualityComparer.Default) - Dim x7 = ImmutableDictionary.CreateRange(SymbolEqualityComparer.Default, kvps) - Dim x8 = kvps.ToImmutableDictionary(SymbolEqualityComparer.Default) - - Dim x9 = symbols.Contains(symbol, SymbolEqualityComparer.Default) - Dim x10 = symbols.Distinct(SymbolEqualityComparer.Default) - Dim x11 = symbols.GroupBy(Function(x) x, SymbolEqualityComparer.Default) - Dim x12 = symbols.GroupJoin(symbols2, Function(x) x, Function(x) x, Function(x, y) x, SymbolEqualityComparer.Default) - Dim x13 = symbols.Intersect(symbols2, SymbolEqualityComparer.Default) - Dim x14 = symbols.Join(symbols2, Function(x) x, Function(x) x, Function(x, y) x, SymbolEqualityComparer.Default) - Dim x15 = symbols.SequenceEqual(symbols2, SymbolEqualityComparer.Default) - Dim x16 = symbols.ToDictionary(Function(x) x, SymbolEqualityComparer.Default) - Dim x17 = symbols.ToLookup(Function(x) x, SymbolEqualityComparer.Default) - Dim x18 = symbols.Union(symbols2, SymbolEqualityComparer.Default) - - Dim x19 = ImmutableHashSet.ToImmutableHashSet(symbols, SymbolEqualityComparer.Default) - End Sub - - Public Sub MethodWithoutDiagnostics(kvps As IEnumerable(Of KeyValuePair(Of Integer, ISymbol)), integers As IEnumerable(Of Integer), i As Integer) - Dim x1 = ImmutableHashSet.Create(Of Integer)() - Dim x2 = ImmutableHashSet.CreateBuilder(Of Integer)() - Dim x3 = ImmutableHashSet.CreateRange(integers) - Dim x4 = integers.ToImmutableHashSet() - - Dim x5 = ImmutableDictionary.Create(Of Integer, ISymbol)() - Dim x6 = ImmutableDictionary.CreateBuilder(Of Integer, ISymbol)() - Dim x7 = ImmutableDictionary.CreateRange(kvps) - Dim x8 = kvps.ToImmutableDictionary() - - Dim x9 = integers.Contains(i) - Dim x10 = integers.Distinct() - Dim x11 = integers.GroupBy(Function(x) x) - Dim x12 = integers.GroupJoin(integers, Function(x) x, Function(x) x, Function(x, y) x) - Dim x13 = integers.Intersect(integers) - Dim x14 = integers.Join(integers, Function(x) x, Function(x) x, Function(x, y) x) - Dim x15 = integers.SequenceEqual(integers) - Dim x16 = integers.ToDictionary(Function(x) x) - Dim x17 = integers.ToLookup(Function(x) x) - Dim x18 = integers.Union(integers) - End Sub -End Class", + """ + Imports System + Imports System.Collections.Immutable + Imports System.Collections.Generic + Imports System.Linq + Imports Microsoft.CodeAnalysis + + Public Class C + Public Sub MethodWithDiagnostics(kvps As IEnumerable(Of KeyValuePair(Of ISymbol, Integer)), symbols As IEnumerable(Of ISymbol), symbols2 As IEnumerable(Of ISymbol), symbol As ISymbol) + Dim x1 = ImmutableHashSet.Create(Of ISymbol)(SymbolEqualityComparer.Default) + Dim x2 = ImmutableHashSet.CreateBuilder(Of ISymbol)(SymbolEqualityComparer.Default) + Dim x3 = ImmutableHashSet.CreateRange(SymbolEqualityComparer.Default, symbols) + Dim x4 = symbols.ToImmutableHashSet(SymbolEqualityComparer.Default) + + Dim x5 = ImmutableDictionary.Create(Of ISymbol, Integer)(SymbolEqualityComparer.Default) + Dim x6 = ImmutableDictionary.CreateBuilder(Of ISymbol, Integer)(SymbolEqualityComparer.Default) + Dim x7 = ImmutableDictionary.CreateRange(SymbolEqualityComparer.Default, kvps) + Dim x8 = kvps.ToImmutableDictionary(SymbolEqualityComparer.Default) + + Dim x9 = symbols.Contains(symbol, SymbolEqualityComparer.Default) + Dim x10 = symbols.Distinct(SymbolEqualityComparer.Default) + Dim x11 = symbols.GroupBy(Function(x) x, SymbolEqualityComparer.Default) + Dim x12 = symbols.GroupJoin(symbols2, Function(x) x, Function(x) x, Function(x, y) x, SymbolEqualityComparer.Default) + Dim x13 = symbols.Intersect(symbols2, SymbolEqualityComparer.Default) + Dim x14 = symbols.Join(symbols2, Function(x) x, Function(x) x, Function(x, y) x, SymbolEqualityComparer.Default) + Dim x15 = symbols.SequenceEqual(symbols2, SymbolEqualityComparer.Default) + Dim x16 = symbols.ToDictionary(Function(x) x, SymbolEqualityComparer.Default) + Dim x17 = symbols.ToLookup(Function(x) x, SymbolEqualityComparer.Default) + Dim x18 = symbols.Union(symbols2, SymbolEqualityComparer.Default) + + Dim x19 = ImmutableHashSet.ToImmutableHashSet(symbols, SymbolEqualityComparer.Default) + End Sub + + Public Sub MethodWithoutDiagnostics(kvps As IEnumerable(Of KeyValuePair(Of Integer, ISymbol)), integers As IEnumerable(Of Integer), i As Integer) + Dim x1 = ImmutableHashSet.Create(Of Integer)() + Dim x2 = ImmutableHashSet.CreateBuilder(Of Integer)() + Dim x3 = ImmutableHashSet.CreateRange(integers) + Dim x4 = integers.ToImmutableHashSet() + + Dim x5 = ImmutableDictionary.Create(Of Integer, ISymbol)() + Dim x6 = ImmutableDictionary.CreateBuilder(Of Integer, ISymbol)() + Dim x7 = ImmutableDictionary.CreateRange(kvps) + Dim x8 = kvps.ToImmutableDictionary() + + Dim x9 = integers.Contains(i) + Dim x10 = integers.Distinct() + Dim x11 = integers.GroupBy(Function(x) x) + Dim x12 = integers.GroupJoin(integers, Function(x) x, Function(x) x, Function(x, y) x) + Dim x13 = integers.Intersect(integers) + Dim x14 = integers.Join(integers, Function(x) x, Function(x) x, Function(x, y) x) + Dim x15 = integers.SequenceEqual(integers) + Dim x16 = integers.ToDictionary(Function(x) x) + Dim x17 = integers.ToLookup(Function(x) x) + Dim x18 = integers.Union(integers) + End Sub + End Class + """, SymbolEqualityComparerStubVisualBasic, }, } @@ -1298,180 +1283,177 @@ End Sub } [Fact, WorkItem(4469, "https://github.com/dotnet/roslyn-analyzers/issues/4469")] - public async Task RS1024_SymbolEqualityComparerDefaultAsync() - { - await new VerifyCS.Test + public Task RS1024_SymbolEqualityComparerDefaultAsync() + => new VerifyCS.Test { TestState = { Sources = { - @" -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.CodeAnalysis; - -public class C -{ - public void M(IEnumerable e, ISymbol symbol, INamedTypeSymbol type) - { - e.Contains(symbol, SymbolEqualityComparer.Default); - - var asyncMethods = type.GetMembers() - .OfType() - .Where(x => x.IsAsync) - .ToLookup(x => x.ContainingType, x => x, SymbolEqualityComparer.Default); - } -}", + """ + using System; + using System.Collections.Generic; + using System.Linq; + using Microsoft.CodeAnalysis; + + public class C + { + public void M(IEnumerable e, ISymbol symbol, INamedTypeSymbol type) + { + e.Contains(symbol, SymbolEqualityComparer.Default); + + var asyncMethods = type.GetMembers() + .OfType() + .Where(x => x.IsAsync) + .ToLookup(x => x.ContainingType, x => x, SymbolEqualityComparer.Default); + } + } + """, SymbolEqualityComparerStubCSharp, }, }, }.RunAsync(); - } [Fact] [WorkItem(4470, "https://github.com/dotnet/roslyn-analyzers/issues/4470")] [WorkItem(4568, "https://github.com/dotnet/roslyn-analyzers/issues/4568")] - public async Task RS1024_InvocationArgumentTypeIsNullAsync() - { - await new VerifyCS.Test + public Task RS1024_InvocationArgumentTypeIsNullAsync() + => new VerifyCS.Test { TestState = { Sources = { - @" -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.CodeAnalysis; - -public class C -{ - private readonly HashSet _types = new HashSet(SymbolEqualityComparer.Default); -}", + """ + using System; + using System.Collections.Generic; + using System.Linq; + using Microsoft.CodeAnalysis; + + public class C + { + private readonly HashSet _types = new HashSet(SymbolEqualityComparer.Default); + } + """, SymbolEqualityComparerStubCSharp, }, }, }.RunAsync(); - } [Fact, WorkItem(4413, "https://github.com/dotnet/roslyn-analyzers/issues/4413")] - public async Task RS1024_SourceCollectionIsSymbolButLambdaIsNotAsync() - { - await new VerifyCS.Test + public Task RS1024_SourceCollectionIsSymbolButLambdaIsNotAsync() + => new VerifyCS.Test { TestState = { Sources = { - @" -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.CodeAnalysis; - -public class C -{ - public void M1(IFieldSymbol[] fields) - { - var result = fields.ToLookup(f => f.Name); - } - - public void M2(IEnumerable source, IEnumerable destination) - { - var result = source.Join(destination, p => (p.Name, p.Type.Name), p => (p.Name, p.Type.Name), (p1, p2) => p1.Name); - } -}", + """ + using System; + using System.Collections.Generic; + using System.Linq; + using Microsoft.CodeAnalysis; + + public class C + { + public void M1(IFieldSymbol[] fields) + { + var result = fields.ToLookup(f => f.Name); + } + + public void M2(IEnumerable source, IEnumerable destination) + { + var result = source.Join(destination, p => (p.Name, p.Type.Name), p => (p.Name, p.Type.Name), (p1, p2) => p1.Name); + } + } + """, SymbolEqualityComparerStubCSharp, }, }, }.RunAsync(); - } [Fact, WorkItem(4956, "https://github.com/dotnet/roslyn-analyzers/issues/4956")] - public async Task RS1024_StringGetHashCodeAsync() - { - await new VerifyCS.Test + public Task RS1024_StringGetHashCodeAsync() + => new VerifyCS.Test { TestState = { Sources = { -@" -using System; - -class C -{ - void M() - { - ReadOnlySpan testROS = default; - int hashCode = string.GetHashCode(testROS, StringComparison.OrdinalIgnoreCase); - } -}" + """ + using System; + + class C + { + void M() + { + ReadOnlySpan testROS = default; + int hashCode = string.GetHashCode(testROS, StringComparison.OrdinalIgnoreCase); + } + } + """ , SymbolEqualityComparerStubCSharp }, ReferenceAssemblies = CreateNetCoreReferenceAssemblies() } }.RunAsync(); - } [Fact] public async Task RS1024_GetHashCodeOnInt64Async() { - var code = @" -using System; -using Microsoft.CodeAnalysis; - -static class HashCodeHelper -{ - public static Int32 GetHashCode(Int64 x) => 0; - public static Int32 GetHashCode(ISymbol symbol) => [|symbol.GetHashCode()|]; -} - -public class C -{ - public int GetHashCode(Int64 obj) - { - return HashCodeHelper.GetHashCode(obj); - } - - public int GetHashCode(ISymbol symbol) - { - return HashCodeHelper.GetHashCode(symbol); - } + var code = """ + using System; + using Microsoft.CodeAnalysis; - public int GetHashCode(object o) - { - if (o is ISymbol symbol) - { - return [|HashCode.Combine(symbol)|]; - } + static class HashCodeHelper + { + public static Int32 GetHashCode(Int64 x) => 0; + public static Int32 GetHashCode(ISymbol symbol) => [|symbol.GetHashCode()|]; + } - return HashCode.Combine(o); - } + public class C + { + public int GetHashCode(Int64 obj) + { + return HashCodeHelper.GetHashCode(obj); + } - public int GetHashCode(object o1, object o2) - { - if (o1 is ISymbol symbol1 && o2 is ISymbol symbol2) - { - return [|HashCode.Combine(symbol1, symbol2)|]; - } + public int GetHashCode(ISymbol symbol) + { + return HashCodeHelper.GetHashCode(symbol); + } - if (o1 is ISymbol symbolFirst) - { - return [|HashCode.Combine(symbolFirst, o2)|]; - } + public int GetHashCode(object o) + { + if (o is ISymbol symbol) + { + return [|HashCode.Combine(symbol)|]; + } - if (o2 is ISymbol symbolSecond) - { - return [|HashCode.Combine(o1, symbolSecond)|]; - } + return HashCode.Combine(o); + } - return HashCode.Combine(o1, o2); - } -}"; + public int GetHashCode(object o1, object o2) + { + if (o1 is ISymbol symbol1 && o2 is ISymbol symbol2) + { + return [|HashCode.Combine(symbol1, symbol2)|]; + } + + if (o1 is ISymbol symbolFirst) + { + return [|HashCode.Combine(symbolFirst, o2)|]; + } + + if (o2 is ISymbol symbolSecond) + { + return [|HashCode.Combine(o1, symbolSecond)|]; + } + + return HashCode.Combine(o1, o2); + } + } + """; await new VerifyCS.Test { @@ -1498,32 +1480,32 @@ public int GetHashCode(object o1, object o2) [WorkItem(5715, "https://github.com/dotnet/roslyn-analyzers/issues/5715")] public async Task RS1024_CustomComparer_Instance_Is_InterfaceAsync() { - var csCode = @" -using System.Collections.Generic; -using System.Linq; -using Microsoft.CodeAnalysis; + var csCode = """ + using System.Collections.Generic; + using System.Linq; + using Microsoft.CodeAnalysis; -public class C -{ - public void M(IEnumerable symbols) - { - _ = new HashSet(SymbolNameComparer.Instance); - _ = symbols.ToDictionary(s => s, s => s.ToDisplayString(), SymbolNameComparer.Instance); - _ = symbols.ToDictionary(s => s, s => s.ToDisplayString(), SymbolEqualityComparer.Default); - } -} + public class C + { + public void M(IEnumerable symbols) + { + _ = new HashSet(SymbolNameComparer.Instance); + _ = symbols.ToDictionary(s => s, s => s.ToDisplayString(), SymbolNameComparer.Instance); + _ = symbols.ToDictionary(s => s, s => s.ToDisplayString(), SymbolEqualityComparer.Default); + } + } -internal sealed class SymbolNameComparer : EqualityComparer -{ - private SymbolNameComparer() { } + internal sealed class SymbolNameComparer : EqualityComparer + { + private SymbolNameComparer() { } - internal static IEqualityComparer Instance { get; } = new SymbolNameComparer(); + internal static IEqualityComparer Instance { get; } = new SymbolNameComparer(); - public override bool Equals(ISymbol x, ISymbol y) => true; + public override bool Equals(ISymbol x, ISymbol y) => true; - public override int GetHashCode(ISymbol obj) => 0; -} -"; + public override int GetHashCode(ISymbol obj) => 0; + } + """; await new VerifyCS.Test { @@ -1533,37 +1515,37 @@ private SymbolNameComparer() { } }.RunAsync(); - var vbCode = @" -Imports System.Collections.Generic -Imports System.Linq -Imports Microsoft.CodeAnalysis + var vbCode = """ + Imports System.Collections.Generic + Imports System.Linq + Imports Microsoft.CodeAnalysis -Public Class C + Public Class C - Public Sub M(symbols As IEnumerable(Of ITypeSymbol)) - Dim x As New HashSet(Of ISymbol)(SymbolNameComparer.Instance) - Dim y = symbols.ToDictionary(Function(s) s, Function(s) s.ToDisplayString(), SymbolNameComparer.Instance) - Dim z = symbols.ToDictionary(Function(s) s, Function(s) s.ToDisplayString(), SymbolEqualityComparer.Default) - End Sub -End Class + Public Sub M(symbols As IEnumerable(Of ITypeSymbol)) + Dim x As New HashSet(Of ISymbol)(SymbolNameComparer.Instance) + Dim y = symbols.ToDictionary(Function(s) s, Function(s) s.ToDisplayString(), SymbolNameComparer.Instance) + Dim z = symbols.ToDictionary(Function(s) s, Function(s) s.ToDisplayString(), SymbolEqualityComparer.Default) + End Sub + End Class -Class SymbolNameComparer - Inherits EqualityComparer(Of ISymbol) + Class SymbolNameComparer + Inherits EqualityComparer(Of ISymbol) - Private Sub New() - End Sub + Private Sub New() + End Sub - Friend Shared Property Instance As IEqualityComparer(Of ISymbol) = New SymbolNameComparer() + Friend Shared Property Instance As IEqualityComparer(Of ISymbol) = New SymbolNameComparer() - Public Overrides Function Equals(x As ISymbol, y As ISymbol) As Boolean - Return True - End Function + Public Overrides Function Equals(x As ISymbol, y As ISymbol) As Boolean + Return True + End Function - Public Overrides Function GetHashCode(obj As ISymbol) As Integer - Return 0 - End Function -End Class -"; + Public Overrides Function GetHashCode(obj As ISymbol) As Integer + Return 0 + End Function + End Class + """; await new VerifyVB.Test { @@ -1578,32 +1560,32 @@ End Class [WorkItem(5715, "https://github.com/dotnet/roslyn-analyzers/issues/5715")] public async Task RS1024_CustomComparer_Instance_Is_TypeAsync() { - var csCode = @" -using System.Collections.Generic; -using System.Linq; -using Microsoft.CodeAnalysis; + var csCode = """ + using System.Collections.Generic; + using System.Linq; + using Microsoft.CodeAnalysis; -public class C -{ - public void M(IEnumerable symbols) - { - _ = new HashSet(SymbolNameComparer.Instance); - _ = symbols.ToDictionary(s => s, s => s.ToDisplayString(), SymbolNameComparer.Instance); - _ = symbols.ToDictionary(s => s, s => s.ToDisplayString(), SymbolEqualityComparer.Default); - } -} + public class C + { + public void M(IEnumerable symbols) + { + _ = new HashSet(SymbolNameComparer.Instance); + _ = symbols.ToDictionary(s => s, s => s.ToDisplayString(), SymbolNameComparer.Instance); + _ = symbols.ToDictionary(s => s, s => s.ToDisplayString(), SymbolEqualityComparer.Default); + } + } -internal sealed class SymbolNameComparer : EqualityComparer -{ - private SymbolNameComparer() { } + internal sealed class SymbolNameComparer : EqualityComparer + { + private SymbolNameComparer() { } - internal static SymbolNameComparer Instance { get; } = new SymbolNameComparer(); + internal static SymbolNameComparer Instance { get; } = new SymbolNameComparer(); - public override bool Equals(ISymbol x, ISymbol y) => true; + public override bool Equals(ISymbol x, ISymbol y) => true; - public override int GetHashCode(ISymbol obj) => 0; -} -"; + public override int GetHashCode(ISymbol obj) => 0; + } + """; await new VerifyCS.Test { @@ -1613,36 +1595,36 @@ private SymbolNameComparer() { } }.RunAsync(); - var vbCode = @" -Imports System.Collections.Generic -Imports System.Linq -Imports Microsoft.CodeAnalysis + var vbCode = """ + Imports System.Collections.Generic + Imports System.Linq + Imports Microsoft.CodeAnalysis -Public Class C - Public Sub M(symbols As IEnumerable(Of ITypeSymbol)) - Dim x As New HashSet(Of ISymbol)(SymbolNameComparer.Instance) - Dim y = symbols.ToDictionary(Function(s) s, Function(s) s.ToDisplayString(), SymbolNameComparer.Instance) - Dim z = symbols.ToDictionary(Function(s) s, Function(s) s.ToDisplayString(), SymbolEqualityComparer.Default) - End Sub -End Class + Public Class C + Public Sub M(symbols As IEnumerable(Of ITypeSymbol)) + Dim x As New HashSet(Of ISymbol)(SymbolNameComparer.Instance) + Dim y = symbols.ToDictionary(Function(s) s, Function(s) s.ToDisplayString(), SymbolNameComparer.Instance) + Dim z = symbols.ToDictionary(Function(s) s, Function(s) s.ToDisplayString(), SymbolEqualityComparer.Default) + End Sub + End Class -Class SymbolNameComparer - Inherits EqualityComparer(Of ISymbol) + Class SymbolNameComparer + Inherits EqualityComparer(Of ISymbol) - Private Sub New() - End Sub + Private Sub New() + End Sub - Friend Shared Property Instance As SymbolNameComparer = New SymbolNameComparer() + Friend Shared Property Instance As SymbolNameComparer = New SymbolNameComparer() - Public Overrides Function Equals(x As ISymbol, y As ISymbol) As Boolean - Return True - End Function + Public Overrides Function Equals(x As ISymbol, y As ISymbol) As Boolean + Return True + End Function - Public Overrides Function GetHashCode(obj As ISymbol) As Integer - Return 0 - End Function -End Class -"; + Public Overrides Function GetHashCode(obj As ISymbol) As Integer + Return 0 + End Function + End Class + """; await new VerifyVB.Test { diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/CompilerExtensionStrictApiAnalyzerTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/CompilerExtensionStrictApiAnalyzerTests.cs index 6d2dcba5a316e..bcdbf3845ab6e 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/CompilerExtensionStrictApiAnalyzerTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/CompilerExtensionStrictApiAnalyzerTests.cs @@ -44,15 +44,13 @@ public enum CompilerFeature [Theory] [CombinatorialData] - public async Task CSharpFeatureDefinedWithCommonReference(CompilerFeature feature, SupportedLanguage supportedLanguage) - { - await new VerifyCS.Test + public Task CSharpFeatureDefinedWithCommonReference(CompilerFeature feature, SupportedLanguage supportedLanguage) + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard20.AddPackages(ImmutableArray.Create( new PackageIdentity("Microsoft.CodeAnalysis.Common", CompilerReferenceVersion))), TestCode = DefineFeature(ImplementationLanguage.CSharp, feature, supportedLanguage), }.RunAsync(); - } [Theory] [CombinatorialData] @@ -128,15 +126,13 @@ public async Task CSharpFeatureDefinedWithMismatchedLanguageReference(CompilerFe [Theory] [CombinatorialData] - public async Task VisualBasicFeatureDefinedWithCommonReference(CompilerFeature feature, SupportedLanguage supportedLanguage) - { - await new VerifyVB.Test + public Task VisualBasicFeatureDefinedWithCommonReference(CompilerFeature feature, SupportedLanguage supportedLanguage) + => new VerifyVB.Test { ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard20.AddPackages(ImmutableArray.Create( new PackageIdentity("Microsoft.CodeAnalysis.Common", CompilerReferenceVersion))), TestCode = DefineFeature(ImplementationLanguage.VisualBasic, feature, supportedLanguage), }.RunAsync(); - } [Theory] [CombinatorialData] diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/CompilerExtensionTargetFrameworkAnalyzerTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/CompilerExtensionTargetFrameworkAnalyzerTests.cs index c90d13c793cc0..9bc658c6553da 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/CompilerExtensionTargetFrameworkAnalyzerTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/CompilerExtensionTargetFrameworkAnalyzerTests.cs @@ -63,9 +63,8 @@ public enum UnsupportedTargetFramework [Theory] [CombinatorialData] - public async Task CSharpAnalyzerDefinedWithSupportedFramework(SupportedTargetFramework supportedFramework) - { - await new VerifyCS.Test + public Task CSharpAnalyzerDefinedWithSupportedFramework(SupportedTargetFramework supportedFramework) + => new VerifyCS.Test { ReferenceAssemblies = GetReferenceAssembliesForTargetFramework(supportedFramework).AddPackages(ImmutableArray.Create( new PackageIdentity("Microsoft.CodeAnalysis.Common", GetCodeAnalysisPackageVersion(supportedFramework)))), @@ -78,13 +77,11 @@ public async Task CSharpAnalyzerDefinedWithSupportedFramework(SupportedTargetFra }, }, }.RunAsync(); - } [Theory] [CombinatorialData] - public async Task CSharpFeatureDefinedWithSupportedFramework(CompilerFeature feature) - { - await new VerifyCS.Test + public Task CSharpFeatureDefinedWithSupportedFramework(CompilerFeature feature) + => new VerifyCS.Test { ReferenceAssemblies = GetReferenceAssembliesForTargetFramework(SupportedTargetFramework.NetStandard2_0).AddPackages(ImmutableArray.Create( new PackageIdentity("Microsoft.CodeAnalysis.Common", GetCodeAnalysisPackageVersion(SupportedTargetFramework.NetStandard2_0)))), @@ -97,13 +94,11 @@ public async Task CSharpFeatureDefinedWithSupportedFramework(CompilerFeature fea }, }, }.RunAsync(); - } [Theory] [CombinatorialData] - public async Task CSharpFeatureDefinedWithUnsupportedFramework(CompilerFeature feature, UnsupportedTargetFramework framework) - { - await new VerifyCS.Test + public Task CSharpFeatureDefinedWithUnsupportedFramework(CompilerFeature feature, UnsupportedTargetFramework framework) + => new VerifyCS.Test { ReferenceAssemblies = GetReferenceAssembliesForTargetFramework(framework).AddPackages(ImmutableArray.Create( new PackageIdentity("Microsoft.CodeAnalysis.Common", GetCodeAnalysisPackageVersion(framework)))), @@ -120,13 +115,11 @@ public async Task CSharpFeatureDefinedWithUnsupportedFramework(CompilerFeature f VerifyCS.Diagnostic().WithLocation(0).WithArguments(GetDisplayName(framework)), }, }.RunAsync(); - } [Theory] [CombinatorialData] - public async Task VisualBasicAnalyzerDefinedWithSupportedFramework(SupportedTargetFramework supportedFramework) - { - await new VerifyVB.Test + public Task VisualBasicAnalyzerDefinedWithSupportedFramework(SupportedTargetFramework supportedFramework) + => new VerifyVB.Test { ReferenceAssemblies = GetReferenceAssembliesForTargetFramework(supportedFramework).AddPackages(ImmutableArray.Create( new PackageIdentity("Microsoft.CodeAnalysis.Common", GetCodeAnalysisPackageVersion(supportedFramework)))), @@ -139,13 +132,11 @@ public async Task VisualBasicAnalyzerDefinedWithSupportedFramework(SupportedTarg }, }, }.RunAsync(); - } [Theory] [CombinatorialData] - public async Task VisualBasicFeatureDefinedWithSupportedFramework(CompilerFeature feature) - { - await new VerifyVB.Test + public Task VisualBasicFeatureDefinedWithSupportedFramework(CompilerFeature feature) + => new VerifyVB.Test { ReferenceAssemblies = GetReferenceAssembliesForTargetFramework(SupportedTargetFramework.NetStandard2_0).AddPackages(ImmutableArray.Create( new PackageIdentity("Microsoft.CodeAnalysis.Common", GetCodeAnalysisPackageVersion(SupportedTargetFramework.NetStandard2_0)))), @@ -158,13 +149,11 @@ public async Task VisualBasicFeatureDefinedWithSupportedFramework(CompilerFeatur }, }, }.RunAsync(); - } [Theory] [CombinatorialData] - public async Task VisualBasicFeatureDefinedWithUnsupportedFramework(CompilerFeature feature, UnsupportedTargetFramework framework) - { - await new VerifyVB.Test + public Task VisualBasicFeatureDefinedWithUnsupportedFramework(CompilerFeature feature, UnsupportedTargetFramework framework) + => new VerifyVB.Test { ReferenceAssemblies = GetReferenceAssembliesForTargetFramework(framework).AddPackages(ImmutableArray.Create( new PackageIdentity("Microsoft.CodeAnalysis.Common", GetCodeAnalysisPackageVersion(framework)))), @@ -181,7 +170,6 @@ public async Task VisualBasicFeatureDefinedWithUnsupportedFramework(CompilerFeat VerifyVB.Diagnostic().WithLocation(0).WithArguments(GetDisplayName(framework)), }, }.RunAsync(); - } private static ReferenceAssemblies GetReferenceAssembliesForTargetFramework(SupportedTargetFramework framework) { diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/ConfigureGeneratedCodeAnalysisAnalyzerTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/ConfigureGeneratedCodeAnalysisAnalyzerTests.cs index 0606aa0fca6e8..a68f1c06a137e 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/ConfigureGeneratedCodeAnalysisAnalyzerTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/ConfigureGeneratedCodeAnalysisAnalyzerTests.cs @@ -17,164 +17,141 @@ namespace Microsoft.CodeAnalysis.Analyzers.UnitTests.MetaAnalyzers public class ConfigureGeneratedCodeAnalysisAnalyzerTests { [Fact] - public async Task TestSimpleCase_CSharpAsync() - { - var code = @" -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -class Analyzer : DiagnosticAnalyzer { - public override ImmutableArray SupportedDiagnostics => throw null; - public override void Initialize(AnalysisContext [|context|]) - { - } -} -"; - var fixedCode = @" -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -class Analyzer : DiagnosticAnalyzer { - public override ImmutableArray SupportedDiagnostics => throw null; - public override void Initialize(AnalysisContext context) - { - context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); - } -} -"; - - await VerifyCS.VerifyCodeFixAsync(code, fixedCode); - } + public Task TestSimpleCase_CSharpAsync() + => VerifyCS.VerifyCodeFixAsync(""" + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + class Analyzer : DiagnosticAnalyzer { + public override ImmutableArray SupportedDiagnostics => throw null; + public override void Initialize(AnalysisContext [|context|]) + { + } + } + """, """ + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + class Analyzer : DiagnosticAnalyzer { + public override ImmutableArray SupportedDiagnostics => throw null; + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + } + } + """); [Fact] - public async Task TestSimpleCase_VisualBasicAsync() - { - var code = @" -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - -Class Analyzer - Inherits DiagnosticAnalyzer - - Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New System.Exception - End Get - End Property - - Public Overrides Sub Initialize([|context|] As AnalysisContext) - End Sub -End Class -"; - var fixedCode = @" -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - -Class Analyzer - Inherits DiagnosticAnalyzer - - Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New System.Exception - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze Or GeneratedCodeAnalysisFlags.ReportDiagnostics) - End Sub -End Class -"; - - await VerifyVB.VerifyCodeFixAsync(code, fixedCode); - } + public Task TestSimpleCase_VisualBasicAsync() + => VerifyVB.VerifyCodeFixAsync(""" + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + Class Analyzer + Inherits DiagnosticAnalyzer + + Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New System.Exception + End Get + End Property + + Public Overrides Sub Initialize([|context|] As AnalysisContext) + End Sub + End Class + """, """ + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + Class Analyzer + Inherits DiagnosticAnalyzer + + Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New System.Exception + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze Or GeneratedCodeAnalysisFlags.ReportDiagnostics) + End Sub + End Class + """); [Fact] - public async Task RenamedMethod_CSharpAsync() - { - var code = @" -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -class Analyzer : DiagnosticAnalyzer { - public override ImmutableArray SupportedDiagnostics => throw null; - public override void Initialize(AnalysisContext context) - { - context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); - } - - public void NotInitialize(AnalysisContext context) - { - } -} -"; - - await VerifyCS.VerifyAnalyzerAsync(code); - } + public Task RenamedMethod_CSharpAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + class Analyzer : DiagnosticAnalyzer { + public override ImmutableArray SupportedDiagnostics => throw null; + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + } + + public void NotInitialize(AnalysisContext context) + { + } + } + """); [Fact] - public async Task RenamedMethod_VisualBasicAsync() - { - var code = @" -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - -Class Analyzer - Inherits DiagnosticAnalyzer - - Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New System.Exception - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze Or GeneratedCodeAnalysisFlags.ReportDiagnostics) - End Sub - - Public Sub NotInitialize(context As AnalysisContext) - End Sub -End Class -"; - - await VerifyVB.VerifyAnalyzerAsync(code); - } + public Task RenamedMethod_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + Class Analyzer + Inherits DiagnosticAnalyzer + + Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New System.Exception + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze Or GeneratedCodeAnalysisFlags.ReportDiagnostics) + End Sub + + Public Sub NotInitialize(context As AnalysisContext) + End Sub + End Class + """); [Fact, WorkItem(2698, "https://github.com/dotnet/roslyn-analyzers/issues/2698")] - public async Task RS1025_ExpressionBodiedMethodAsync() - { - var code = @" -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -class Analyzer : DiagnosticAnalyzer { - public override ImmutableArray SupportedDiagnostics => throw null; - public override void Initialize(AnalysisContext [|context|]) - => context.RegisterCompilationAction(x => { }); -} -"; - var fixedCode = @" -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -class Analyzer : DiagnosticAnalyzer { - public override ImmutableArray SupportedDiagnostics => throw null; - public override void Initialize(AnalysisContext context) - { - context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); - context.RegisterCompilationAction(x => { }); - } -} -"; - - await VerifyCS.VerifyCodeFixAsync(code, fixedCode); - } + public Task RS1025_ExpressionBodiedMethodAsync() + => VerifyCS.VerifyCodeFixAsync(""" + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + class Analyzer : DiagnosticAnalyzer { + public override ImmutableArray SupportedDiagnostics => throw null; + public override void Initialize(AnalysisContext [|context|]) + => context.RegisterCompilationAction(x => { }); + } + """, """ + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + class Analyzer : DiagnosticAnalyzer { + public override ImmutableArray SupportedDiagnostics => throw null; + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + context.RegisterCompilationAction(x => { }); + } + } + """); } } diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DiagnosticAnalyzerApiUsageAnalyzerTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DiagnosticAnalyzerApiUsageAnalyzerTests.cs index 28245b9c3561c..0fa1b576d7f29 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DiagnosticAnalyzerApiUsageAnalyzerTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DiagnosticAnalyzerApiUsageAnalyzerTests.cs @@ -67,96 +67,97 @@ private static async Task VerifyVisualBasicAnalyzerAsync(string source, params D [Fact] public async Task NoDiagnosticCasesAsync() { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpAnalyzerAsync(""" + using System; + using System.Collections.Generic; + using System.Collections.Immutable; + using System.Threading.Tasks; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; -interface I { } + interface I { } -internal delegate void MyDelegateGlobal(); + internal delegate void MyDelegateGlobal(); -class MyAnalyzer : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics=> throw new NotImplementedException(); + class MyAnalyzer : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics=> throw new NotImplementedException(); - internal delegate void MyDelegateInType(); + internal delegate void MyDelegateInType(); - public override void Initialize(AnalysisContext context) - { - var x = typeof(I<>); - } -} + public override void Initialize(AnalysisContext context) + { + var x = typeof(I<>); + } + } -class MyFixer : CodeFixProvider -{ - public sealed override ImmutableArray FixableDiagnosticIds => throw new NotImplementedException(); + class MyFixer : CodeFixProvider + { + public sealed override ImmutableArray FixableDiagnosticIds => throw new NotImplementedException(); - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) - { - return null; - } -} + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + { + return null; + } + } -class MyFixer2 : I -{ - Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider field; -}"); - - await VerifyVisualBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Generic -Imports System.Collections.Immutable -Imports System.Threading.Tasks -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic - -Interface I(Of T) -End Interface - -Friend Delegate Sub MyDelegateGlobal() - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - Friend Delegate Sub MyDelegateInType() - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class - -Class MyFixer - Inherits CodeFixProvider - - Public NotOverridable Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) - Get - Throw New NotImplementedException() - End Get - End Property - - Public NotOverridable Overrides Function RegisterCodeFixesAsync(ByVal context As CodeFixContext) As Task - Return Nothing - End Function -End Class - -Class MyFixer2 - Implements I(Of CodeFixProvider) - - Dim field As Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider -End Class -"); + class MyFixer2 : I + { + Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider field; + } + """); + + await VerifyVisualBasicAnalyzerAsync(""" + Imports System + Imports System.Collections.Generic + Imports System.Collections.Immutable + Imports System.Threading.Tasks + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.CodeFixes + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.VisualBasic + + Interface I(Of T) + End Interface + + Friend Delegate Sub MyDelegateGlobal() + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + Friend Delegate Sub MyDelegateInType() + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + Class MyFixer + Inherits CodeFixProvider + + Public NotOverridable Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) + Get + Throw New NotImplementedException() + End Get + End Property + + Public NotOverridable Overrides Function RegisterCodeFixesAsync(ByVal context As CodeFixContext) As Task + Return Nothing + End Function + End Class + + Class MyFixer2 + Implements I(Of CodeFixProvider) + + Dim field As Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider + End Class + """); } [Theory] @@ -169,24 +170,25 @@ public async Task DirectlyAccessedType_InDeclaration_DiagnosticAsync(bool relaxe { Sources = { - @" -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; - -interface I { } - -class {|#0:MyAnalyzer|} : DiagnosticAnalyzer, I -{ - public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); - - public override void Initialize(AnalysisContext context) - { - } -}", + """ + using System; + using System.Collections.Generic; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + + interface I { } + + class {|#0:MyAnalyzer|} : DiagnosticAnalyzer, I + { + public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); + + public override void Initialize(AnalysisContext context) + { + } + } + """, }, } }; @@ -213,31 +215,31 @@ public override void Initialize(AnalysisContext context) { Sources = { - @" -Imports System -Imports System.Collections.Generic -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic - -Interface I(Of T) -End Interface - -Class {|#0:MyAnalyzer|} - Inherits DiagnosticAnalyzer - Implements I(Of Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider) - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", + """ + Imports System + Imports System.Collections.Generic + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.VisualBasic + + Interface I(Of T) + End Interface + + Class {|#0:MyAnalyzer|} + Inherits DiagnosticAnalyzer + Implements I(Of Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider) + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + """, }, } }; @@ -262,59 +264,60 @@ End Class [Fact] public async Task DirectlyAccessedType_InMemberDeclaration_DiagnosticAsync() { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; - -class {|#0:MyAnalyzer|} : DiagnosticAnalyzer -{ - private readonly CodeFixProvider field; - FixAllContext Method(FixAllProvider param) - { - return null; - } + await VerifyCSharpAnalyzerAsync(""" + using System; + using System.Collections.Generic; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + + class {|#0:MyAnalyzer|} : DiagnosticAnalyzer + { + private readonly CodeFixProvider field; + FixAllContext Method(FixAllProvider param) + { + return null; + } - public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); + public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); - public override void Initialize(AnalysisContext context) - { - } -}", + public override void Initialize(AnalysisContext context) + { + } + } + """, // Test0.cs(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct accesses to type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllContext, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider'. GetCSharpExpectedDiagnostic(0, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllContext, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider")); - await VerifyVisualBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Generic -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic - -Class {|#0:MyAnalyzer|} - Inherits DiagnosticAnalyzer - - Dim field As CodeFixProvider - Function Method(param As FixAllProvider) As FixAllContext - Return Nothing - End Function - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", + await VerifyVisualBasicAnalyzerAsync(""" + Imports System + Imports System.Collections.Generic + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.CodeFixes + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.VisualBasic + + Class {|#0:MyAnalyzer|} + Inherits DiagnosticAnalyzer + + Dim field As CodeFixProvider + Function Method(param As FixAllProvider) As FixAllContext + Return Nothing + End Function + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + """, // Test0.vb(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct accesses to type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllContext, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider'. GetBasicExpectedDiagnostic(0, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllContext, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider")); @@ -323,57 +326,58 @@ End Class [Fact] public async Task DirectlyAccessedType_InMemberBody_DiagnosticAsync() { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; - -class {|#0:MyAnalyzer|} : DiagnosticAnalyzer -{ - void Method() - { - CodeFixProvider c = null; - } + await VerifyCSharpAnalyzerAsync(""" + using System; + using System.Collections.Generic; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + + class {|#0:MyAnalyzer|} : DiagnosticAnalyzer + { + void Method() + { + CodeFixProvider c = null; + } - public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); + public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); - public override void Initialize(AnalysisContext context) - { - } -}", + public override void Initialize(AnalysisContext context) + { + } + } + """, // Test0.cs(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct accesses to type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider'. GetCSharpExpectedDiagnostic(0, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); - await VerifyVisualBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Generic -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic - -Class {|#0:MyAnalyzer|} - Inherits DiagnosticAnalyzer - - Sub Method() - Dim c As CodeFixProvider = Nothing - End Sub - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", + await VerifyVisualBasicAnalyzerAsync(""" + Imports System + Imports System.Collections.Generic + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.CodeFixes + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.VisualBasic + + Class {|#0:MyAnalyzer|} + Inherits DiagnosticAnalyzer + + Sub Method() + Dim c As CodeFixProvider = Nothing + End Sub + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + """, // Test0.vb(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct accesses to type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider'. GetBasicExpectedDiagnostic(0, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); @@ -382,59 +386,60 @@ End Class [Fact] public async Task DirectlyAccessedType_StaticMember_DiagnosticAsync() { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; -using static Microsoft.CodeAnalysis.CodeActions.WarningAnnotation; - -class {|#0:MyAnalyzer|} : DiagnosticAnalyzer -{ - void Method() - { - var c = Kind; - } + await VerifyCSharpAnalyzerAsync(""" + using System; + using System.Collections.Generic; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + using static Microsoft.CodeAnalysis.CodeActions.WarningAnnotation; + + class {|#0:MyAnalyzer|} : DiagnosticAnalyzer + { + void Method() + { + var c = Kind; + } - public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); + public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); - public override void Initialize(AnalysisContext context) - { - } -}", + public override void Initialize(AnalysisContext context) + { + } + } + """, // Test0.cs(11,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct accesses to type(s) 'Microsoft.CodeAnalysis.CodeActions.WarningAnnotation'. GetCSharpExpectedDiagnostic(0, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeActions.WarningAnnotation")); - await VerifyVisualBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Generic -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic -Imports WarningAnnotation = Microsoft.CodeAnalysis.CodeActions.WarningAnnotation - -Class {|#0:MyAnalyzer|} - Inherits DiagnosticAnalyzer - - Sub Method() - Dim c = WarningAnnotation.Kind - End Sub - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", + await VerifyVisualBasicAnalyzerAsync(""" + Imports System + Imports System.Collections.Generic + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.CodeFixes + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.VisualBasic + Imports WarningAnnotation = Microsoft.CodeAnalysis.CodeActions.WarningAnnotation + + Class {|#0:MyAnalyzer|} + Inherits DiagnosticAnalyzer + + Sub Method() + Dim c = WarningAnnotation.Kind + End Sub + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + """, // Test0.vb(11,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct accesses to type(s) 'Microsoft.CodeAnalysis.CodeActions.WarningAnnotation'. GetBasicExpectedDiagnostic(0, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeActions.WarningAnnotation")); } @@ -442,59 +447,60 @@ End Class [Fact] public async Task DirectlyAccessedType_StaticMember_02_DiagnosticAsync() { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; -using static Microsoft.CodeAnalysis.CodeFixes.WellKnownFixAllProviders; - -class {|#0:MyAnalyzer|} : DiagnosticAnalyzer -{ - void Method() - { - var c = BatchFixer; - } + await VerifyCSharpAnalyzerAsync(""" + using System; + using System.Collections.Generic; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + using static Microsoft.CodeAnalysis.CodeFixes.WellKnownFixAllProviders; + + class {|#0:MyAnalyzer|} : DiagnosticAnalyzer + { + void Method() + { + var c = BatchFixer; + } - public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); + public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); - public override void Initialize(AnalysisContext context) - { - } -}", + public override void Initialize(AnalysisContext context) + { + } + } + """, // Test0.cs(11,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct accesses to type(s) 'Microsoft.CodeAnalysis.CodeFixes.FixAllProvider, Microsoft.CodeAnalysis.CodeFixes.WellKnownFixAllProviders'. GetCSharpExpectedDiagnostic(0, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.FixAllProvider, Microsoft.CodeAnalysis.CodeFixes.WellKnownFixAllProviders")); - await VerifyVisualBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Generic -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic -Imports WellKnownFixAllProviders = Microsoft.CodeAnalysis.CodeFixes.WellKnownFixAllProviders - -Class {|#0:MyAnalyzer|} - Inherits DiagnosticAnalyzer - - Sub Method() - Dim c = WellKnownFixAllProviders.BatchFixer - End Sub - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", + await VerifyVisualBasicAnalyzerAsync(""" + Imports System + Imports System.Collections.Generic + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.CodeFixes + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.VisualBasic + Imports WellKnownFixAllProviders = Microsoft.CodeAnalysis.CodeFixes.WellKnownFixAllProviders + + Class {|#0:MyAnalyzer|} + Inherits DiagnosticAnalyzer + + Sub Method() + Dim c = WellKnownFixAllProviders.BatchFixer + End Sub + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + """, // Test0.vb(11,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct accesses to type(s) 'Microsoft.CodeAnalysis.CodeFixes.FixAllProvider, Microsoft.CodeAnalysis.CodeFixes.WellKnownFixAllProviders'. GetBasicExpectedDiagnostic(0, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.FixAllProvider, Microsoft.CodeAnalysis.CodeFixes.WellKnownFixAllProviders")); } @@ -502,178 +508,177 @@ End Class [Fact] public async Task DirectlyAccessedType_CastAndTypeCheck_DiagnosticAsync() { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; - -class {|#0:MyAnalyzer|} : DiagnosticAnalyzer -{ - void Method(object o) - { - var c = (CodeFixProvider)o; - var c2 = o is FixAllProvider; - } + await VerifyCSharpAnalyzerAsync(""" + using System; + using System.Collections.Generic; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + + class {|#0:MyAnalyzer|} : DiagnosticAnalyzer + { + void Method(object o) + { + var c = (CodeFixProvider)o; + var c2 = o is FixAllProvider; + } - public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); + public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); - public override void Initialize(AnalysisContext context) - { - } -}", + public override void Initialize(AnalysisContext context) + { + } + } + """, // Test0.cs(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct accesses to type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider'. GetCSharpExpectedDiagnostic(0, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider")); - await VerifyVisualBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Generic -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic - -Class {|#0:MyAnalyzer|} - Inherits DiagnosticAnalyzer - - Sub Method(o As Object) - Dim c = DirectCast(o, CodeFixProvider) - Dim c2 = TypeOf o Is FixAllProvider - End Sub - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", + await VerifyVisualBasicAnalyzerAsync(""" + Imports System + Imports System.Collections.Generic + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.CodeFixes + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.VisualBasic + + Class {|#0:MyAnalyzer|} + Inherits DiagnosticAnalyzer + + Sub Method(o As Object) + Dim c = DirectCast(o, CodeFixProvider) + Dim c2 = TypeOf o Is FixAllProvider + End Sub + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + """, // Test0.vb(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct accesses to type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider'. GetBasicExpectedDiagnostic(0, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider")); } [Fact] - public async Task IndirectlyAccessedType_StaticMember_DiagnosticAsync() - { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; -using static Fixer; - -class {|#0:MyAnalyzer|} : DiagnosticAnalyzer -{ - private string Value => FixerValue; + public Task IndirectlyAccessedType_StaticMember_DiagnosticAsync() + => VerifyCSharpAnalyzerAsync(""" + using System; + using System.Collections.Generic; + using System.Collections.Immutable; + using System.Threading.Tasks; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + using static Fixer; + + class {|#0:MyAnalyzer|} : DiagnosticAnalyzer + { + private string Value => FixerValue; - public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); + public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); - public override void Initialize(AnalysisContext context) - { - } -} + public override void Initialize(AnalysisContext context) + { + } + } -class Fixer : CodeFixProvider -{ - internal static readonly string FixerValue = ""something""; + class Fixer : CodeFixProvider + { + internal static readonly string FixerValue = "something"; - public sealed override ImmutableArray FixableDiagnosticIds => throw new NotImplementedException(); + public sealed override ImmutableArray FixableDiagnosticIds => throw new NotImplementedException(); - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) - { - return null; - } + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + { + return null; + } -} -", + } + """, // Test0.cs(12,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct and/or indirect accesses to type(s) 'Fixer', which access type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixContext, Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider'. GetCSharpExpectedDiagnostic(0, "MyAnalyzer", "Fixer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixContext, Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); - } [Fact] public async Task IndirectlyAccessedType_ExtensionMethod_DiagnosticAsync() { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; -using static FixerExtensions; - -class {|#0:MyAnalyzer|} : DiagnosticAnalyzer -{ - void M() - { - this.ExtensionMethod(); - } + await VerifyCSharpAnalyzerAsync(""" + using System; + using System.Collections.Generic; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + using static FixerExtensions; + + class {|#0:MyAnalyzer|} : DiagnosticAnalyzer + { + void M() + { + this.ExtensionMethod(); + } - public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); + public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); - public override void Initialize(AnalysisContext context) - { - } -} + public override void Initialize(AnalysisContext context) + { + } + } -public static class FixerExtensions -{ - public static void ExtensionMethod(this DiagnosticAnalyzer analyzer) - { - CodeFixProvider c = null; - } -} -", + public static class FixerExtensions + { + public static void ExtensionMethod(this DiagnosticAnalyzer analyzer) + { + CodeFixProvider c = null; + } + } + """, // Test0.cs(11,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct and/or indirect accesses to type(s) 'FixerExtensions', which access type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider'. GetCSharpExpectedDiagnostic(0, "MyAnalyzer", "FixerExtensions", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); - await VerifyVisualBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Generic -Imports System.Collections.Immutable -Imports System.Runtime.CompilerServices -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic -Imports FixerExtensions - -Class {|#0:MyAnalyzer|} - Inherits DiagnosticAnalyzer - - Private Sub M() - Me.ExtensionMethod() - End Sub - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class - -Module FixerExtensions - - Sub ExtensionMethod(analyzer As DiagnosticAnalyzer) - Dim c As CodeFixProvider = Nothing - End Sub -End Module -", + await VerifyVisualBasicAnalyzerAsync(""" + Imports System + Imports System.Collections.Generic + Imports System.Collections.Immutable + Imports System.Runtime.CompilerServices + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.CodeFixes + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.VisualBasic + Imports FixerExtensions + + Class {|#0:MyAnalyzer|} + Inherits DiagnosticAnalyzer + + Private Sub M() + Me.ExtensionMethod() + End Sub + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + Module FixerExtensions + + Sub ExtensionMethod(analyzer As DiagnosticAnalyzer) + Dim c As CodeFixProvider = Nothing + End Sub + End Module + """, // Test0.vb(12,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct and/or indirect accesses to type(s) 'FixerExtensions', which access type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider'. GetBasicExpectedDiagnostic(0, "MyAnalyzer", "FixerExtensions", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); } @@ -681,72 +686,72 @@ End Module [Fact] public async Task IndirectlyAccessedType_InvokedFromAnalyzer_DiagnosticAsync() { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; - -class {|#0:MyAnalyzer|} : DiagnosticAnalyzer -{ - void Method(Class2 c) - { - c.M(); - } + await VerifyCSharpAnalyzerAsync(""" + using System; + using System.Collections.Generic; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + + class {|#0:MyAnalyzer|} : DiagnosticAnalyzer + { + void Method(Class2 c) + { + c.M(); + } - public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); + public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); - public override void Initialize(AnalysisContext context) - { - } -} + public override void Initialize(AnalysisContext context) + { + } + } -class Class2 -{ - public void M() - { - CodeFixProvider c = null; - } -} -", + class Class2 + { + public void M() + { + CodeFixProvider c = null; + } + } + """, // Test0.cs(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct and/or indirect accesses to type(s) 'Class2', which access type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider'. GetCSharpExpectedDiagnostic(0, "MyAnalyzer", "Class2", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); - await VerifyVisualBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Generic -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic - -Class {|#0:MyAnalyzer|} - Inherits DiagnosticAnalyzer - - Sub Method(c As Class2) - c.M() - End Sub - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class - -Class Class2 - Sub M() - Dim c As CodeFixProvider = Nothing - End Sub -End Class -", + await VerifyVisualBasicAnalyzerAsync(""" + Imports System + Imports System.Collections.Generic + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.CodeFixes + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.VisualBasic + + Class {|#0:MyAnalyzer|} + Inherits DiagnosticAnalyzer + + Sub Method(c As Class2) + c.M() + End Sub + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + Class Class2 + Sub M() + Dim c As CodeFixProvider = Nothing + End Sub + End Class + """, // Test0.vb(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct and/or indirect accesses to type(s) 'Class2', which access type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider'. GetBasicExpectedDiagnostic(0, "MyAnalyzer", "Class2", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); @@ -758,94 +763,94 @@ public async Task IndirectlyAccessedType_NotInvokedFromAnalyzer_DiagnosticAsync( // We report diagnostic if there is a transitive access to a type referencing something from Workspaces. // This is regardless of whether the transitive access is actually reachable from a possible code path or not. - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpAnalyzerAsync(""" + using System; + using System.Collections.Generic; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; -class {|#0:MyAnalyzer|} : DiagnosticAnalyzer -{ - void Method(Class2 c2, Class3 c3) - { - c2.M2(); - } + class {|#0:MyAnalyzer|} : DiagnosticAnalyzer + { + void Method(Class2 c2, Class3 c3) + { + c2.M2(); + } - public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); + public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); - public override void Initialize(AnalysisContext context) - { - } -} + public override void Initialize(AnalysisContext context) + { + } + } -class Class2 -{ - public void M() - { - CodeFixProvider c = null; - } + class Class2 + { + public void M() + { + CodeFixProvider c = null; + } - - public void M2() - { - } -} -class Class3 -{ - public void M() - { - FixAllProvider c = null; - } -} -", + public void M2() + { + } + } + + class Class3 + { + public void M() + { + FixAllProvider c = null; + } + } + """, // Test0.cs(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct and/or indirect accesses to type(s) 'Class2, Class3', which access type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider'. GetCSharpExpectedDiagnostic(0, "MyAnalyzer", "Class2, Class3", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider")); - await VerifyVisualBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Generic -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic - -Class {|#0:MyAnalyzer|} - Inherits DiagnosticAnalyzer - - Sub Method(c2 As Class2, c3 As Class3) - c2.M2() - End Sub - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class - -Class Class2 - Sub M() - Dim c As CodeFixProvider = Nothing - End Sub - - Sub M2() - End Sub -End Class - -Class Class3 - Sub M() - Dim c As FixAllProvider = Nothing - End Sub -End Class -", + await VerifyVisualBasicAnalyzerAsync(""" + Imports System + Imports System.Collections.Generic + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.CodeFixes + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.VisualBasic + + Class {|#0:MyAnalyzer|} + Inherits DiagnosticAnalyzer + + Sub Method(c2 As Class2, c3 As Class3) + c2.M2() + End Sub + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + Class Class2 + Sub M() + Dim c As CodeFixProvider = Nothing + End Sub + + Sub M2() + End Sub + End Class + + Class Class3 + Sub M() + Dim c As FixAllProvider = Nothing + End Sub + End Class + """, // Test0.vb(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct and/or indirect accesses to type(s) 'Class2, Class3', which access type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider'. GetBasicExpectedDiagnostic(0, "MyAnalyzer", "Class2, Class3", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider")); } @@ -853,82 +858,82 @@ End Class [Fact] public async Task IndirectlyAccessedType_Transitive_DiagnosticAsync() { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; - -class {|#0:MyAnalyzer|} : DiagnosticAnalyzer -{ - void Method(Class2 c2) - { - } + await VerifyCSharpAnalyzerAsync(""" + using System; + using System.Collections.Generic; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + + class {|#0:MyAnalyzer|} : DiagnosticAnalyzer + { + void Method(Class2 c2) + { + } - public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); + public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); - public override void Initialize(AnalysisContext context) - { - } -} + public override void Initialize(AnalysisContext context) + { + } + } -class Class2 -{ - public void M2(Class3 c3) - { - } -} + class Class2 + { + public void M2(Class3 c3) + { + } + } -class Class3 -{ - public void M() - { - CodeFixProvider c = null; - } -} -", + class Class3 + { + public void M() + { + CodeFixProvider c = null; + } + } + """, // Test0.cs(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct and/or indirect accesses to type(s) 'Class3', which access type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider'. GetCSharpExpectedDiagnostic(0, "MyAnalyzer", "Class3", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); - await VerifyVisualBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Generic -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic - -Class {|#0:MyAnalyzer|} - Inherits DiagnosticAnalyzer - - Sub Method(c2 As Class2) - End Sub - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class - -Class Class2 - Sub M2(c3 As Class3) - End Sub -End Class - -Class Class3 - Sub M() - Dim c As CodeFixProvider = Nothing - End Sub -End Class -", + await VerifyVisualBasicAnalyzerAsync(""" + Imports System + Imports System.Collections.Generic + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.CodeFixes + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.VisualBasic + + Class {|#0:MyAnalyzer|} + Inherits DiagnosticAnalyzer + + Sub Method(c2 As Class2) + End Sub + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + Class Class2 + Sub M2(c3 As Class3) + End Sub + End Class + + Class Class3 + Sub M() + Dim c As CodeFixProvider = Nothing + End Sub + End Class + """, // Test0.vb(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct and/or indirect accesses to type(s) 'Class3', which access type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider'. GetBasicExpectedDiagnostic(0, "MyAnalyzer", "Class3", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); } @@ -936,91 +941,91 @@ End Class [Fact] public async Task TypeDependencyGraphWithCycles_DiagnosticAsync() { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; - -class {|#0:MyAnalyzer|} : DiagnosticAnalyzer -{ - void Method(Class2 c2, Class3 c3) - { - } + await VerifyCSharpAnalyzerAsync(""" + using System; + using System.Collections.Generic; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CodeFixes; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + + class {|#0:MyAnalyzer|} : DiagnosticAnalyzer + { + void Method(Class2 c2, Class3 c3) + { + } - public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); + public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); - public override void Initialize(AnalysisContext context) - { - } -} + public override void Initialize(AnalysisContext context) + { + } + } -class Class2 -{ - public void M() - { - CodeFixProvider c = null; - } - - public void M2(Class3 c3) - { - } -} + class Class2 + { + public void M() + { + CodeFixProvider c = null; + } -class Class3 -{ - public void M(Class2 c2) - { - FixAllProvider c = null; - } -} -", + public void M2(Class3 c3) + { + } + } + + class Class3 + { + public void M(Class2 c2) + { + FixAllProvider c = null; + } + } + """, // Test0.cs(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct and/or indirect accesses to type(s) 'Class2, Class3', which access type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider'. GetCSharpExpectedDiagnostic(0, "MyAnalyzer", "Class2, Class3", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider")); - await VerifyVisualBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Generic -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeFixes -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic - -Class {|#0:MyAnalyzer|} - Inherits DiagnosticAnalyzer - - Sub Method(c2 As Class2, c3 As Class3) - End Sub - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class - -Class Class2 - Sub M() - Dim c As CodeFixProvider = Nothing - End Sub - - Sub M2(c3 As Class3) - End Sub -End Class - -Class Class3 - Sub M(c2 As Class2) - Dim c As FixAllProvider = Nothing - End Sub -End Class -", + await VerifyVisualBasicAnalyzerAsync(""" + Imports System + Imports System.Collections.Generic + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.CodeFixes + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.VisualBasic + + Class {|#0:MyAnalyzer|} + Inherits DiagnosticAnalyzer + + Sub Method(c2 As Class2, c3 As Class3) + End Sub + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + Class Class2 + Sub M() + Dim c As CodeFixProvider = Nothing + End Sub + + Sub M2(c3 As Class3) + End Sub + End Class + + Class Class3 + Sub M(c2 As Class2) + Dim c As FixAllProvider = Nothing + End Sub + End Class + """, // Test0.vb(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct and/or indirect accesses to type(s) 'Class2, Class3', which access type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider'. GetBasicExpectedDiagnostic(0, "MyAnalyzer", "Class2, Class3", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider")); } diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzerTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzerTests.cs index 809bd19d4d42d..b6ac459d99e6d 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzerTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzerTests.cs @@ -23,580 +23,580 @@ public class DiagnosticDescriptorCreationAnalyzerTests #region RS1007 (UseLocalizableStringsInDescriptorRuleId) and RS1015 (ProvideHelpUriInDescriptorRuleId) [Fact] - public async Task RS1007_RS1015_CSharp_VerifyDiagnosticAsync() - { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + public Task RS1007_RS1015_CSharp_VerifyDiagnosticAsync() + => VerifyCSharpAnalyzerAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor = - {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true)|}; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor); - } - } + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor = + {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true)|}; - public override void Initialize(AnalysisContext context) - { - } -}", + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """, GetRS1007ExpectedDiagnostic(0), GetRS1015ExpectedDiagnostic(0), GetRS1028ResultAt(0)); - } [Fact] - public async Task RS1007_RS1015_VisualBasic_VerifyDiagnosticAsync() - { - await VerifyBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - Private Shared ReadOnly descriptor As DiagnosticDescriptor = {|#0:new {|#1:DiagnosticDescriptor|}(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault:= true)|} - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", + public Task RS1007_RS1015_VisualBasic_VerifyDiagnosticAsync() + => VerifyBasicAnalyzerAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + Private Shared ReadOnly descriptor As DiagnosticDescriptor = {|#0:new {|#1:DiagnosticDescriptor|}("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault:= true)|} + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """, GetRS1007ExpectedDiagnostic(0), GetRS1015ExpectedDiagnostic(1), GetRS1028ResultAt(1)); - } [Fact] - public async Task RS1007_RS1015_CSharp_VerifyDiagnostic_NamedArgumentCasesAsync() - { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + public Task RS1007_RS1015_CSharp_VerifyDiagnostic_NamedArgumentCasesAsync() + => VerifyCSharpAnalyzerAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor = - {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", messageFormat: ""MyDiagnosticMessage"", title: ""MyDiagnosticTitle"", {|#2:helpLinkUri: null|}, category: ""MyDiagnosticCategory"", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true)|}; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - private static readonly DiagnosticDescriptor descriptor2 = - {|#3:new DiagnosticDescriptor(""MyDiagnosticId"", messageFormat: ""MyDiagnosticMessage"", title: ""MyDiagnosticTitle"", category: ""MyDiagnosticCategory"", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true)|}; + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor = + {|#0:new DiagnosticDescriptor("MyDiagnosticId", messageFormat: "MyDiagnosticMessage", title: "MyDiagnosticTitle", {|#2:helpLinkUri: null|}, category: "MyDiagnosticCategory", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true)|}; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor); - } - } + private static readonly DiagnosticDescriptor descriptor2 = + {|#3:new DiagnosticDescriptor("MyDiagnosticId", messageFormat: "MyDiagnosticMessage", title: "MyDiagnosticTitle", category: "MyDiagnosticCategory", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true)|}; - public override void Initialize(AnalysisContext context) - { - } -}", + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """, GetRS1007ExpectedDiagnostic(0), GetRS1028ResultAt(0), GetRS1015ExpectedDiagnostic(2), GetRS1007ExpectedDiagnostic(3), GetRS1015ExpectedDiagnostic(3), GetRS1028ResultAt(3)); - } [Fact] - public async Task RS1007_RS1015_VisualBasic_VerifyDiagnostic_NamedArgumentCasesAsync() - { - await VerifyBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - Private Shared ReadOnly descriptor As DiagnosticDescriptor = {|#0:new {|#1:DiagnosticDescriptor|}(""MyDiagnosticId"", title:=""MyDiagnosticTitle"", {|#2:helpLinkUri:=Nothing|}, messageFormat:=""MyDiagnosticMessage"", category:=""MyDiagnosticCategory"", defaultSeverity:=DiagnosticSeverity.Warning, isEnabledByDefault:= true)|} - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#3:new {|#4:DiagnosticDescriptor|}(""MyDiagnosticId"", title:=""MyDiagnosticTitle"", messageFormat:=""MyDiagnosticMessage"", category:=""MyDiagnosticCategory"", defaultSeverity:=DiagnosticSeverity.Warning, isEnabledByDefault:= true)|} - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", + public Task RS1007_RS1015_VisualBasic_VerifyDiagnostic_NamedArgumentCasesAsync() + => VerifyBasicAnalyzerAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + Private Shared ReadOnly descriptor As DiagnosticDescriptor = {|#0:new {|#1:DiagnosticDescriptor|}("MyDiagnosticId", title:="MyDiagnosticTitle", {|#2:helpLinkUri:=Nothing|}, messageFormat:="MyDiagnosticMessage", category:="MyDiagnosticCategory", defaultSeverity:=DiagnosticSeverity.Warning, isEnabledByDefault:= true)|} + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#3:new {|#4:DiagnosticDescriptor|}("MyDiagnosticId", title:="MyDiagnosticTitle", messageFormat:="MyDiagnosticMessage", category:="MyDiagnosticCategory", defaultSeverity:=DiagnosticSeverity.Warning, isEnabledByDefault:= true)|} + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """, GetRS1007ExpectedDiagnostic(0), GetRS1028ResultAt(1), GetRS1015ExpectedDiagnostic(2), GetRS1007ExpectedDiagnostic(3), GetRS1015ExpectedDiagnostic(4), GetRS1028ResultAt(4)); - } [Fact] - public async Task RS1007_RS1015_CSharp_NoDiagnosticCasesAsync() - { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + public Task RS1007_RS1015_CSharp_NoDiagnosticCasesAsync() + => VerifyCSharpAnalyzerAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static LocalizableString dummyLocalizableTitle = new LocalizableResourceString(""dummyName"", null, null); + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - private static readonly DiagnosticDescriptor descriptor = - {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static LocalizableString dummyLocalizableTitle = new LocalizableResourceString("dummyName", null, null); - private static readonly DiagnosticDescriptor descriptor2 = - {|#1:new DiagnosticDescriptor(""MyDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, true, ""MyDiagnosticDescription."", ""HelpLink"")|}; + private static readonly DiagnosticDescriptor descriptor = + {|#0:new DiagnosticDescriptor("MyDiagnosticId", dummyLocalizableTitle, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; - private static readonly DiagnosticDescriptor descriptor3 = - {|#2:new DiagnosticDescriptor(helpLinkUri: ""HelpLink"", id: ""MyDiagnosticId"", messageFormat:""MyDiagnosticMessage"", title: dummyLocalizableTitle, category: ""MyDiagnosticCategory"", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true)|}; + private static readonly DiagnosticDescriptor descriptor2 = + {|#1:new DiagnosticDescriptor("MyDiagnosticId", dummyLocalizableTitle, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, true, "MyDiagnosticDescription.", "HelpLink")|}; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor); - } - } + private static readonly DiagnosticDescriptor descriptor3 = + {|#2:new DiagnosticDescriptor(helpLinkUri: "HelpLink", id: "MyDiagnosticId", messageFormat:"MyDiagnosticMessage", title: dummyLocalizableTitle, category: "MyDiagnosticCategory", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true)|}; - public override void Initialize(AnalysisContext context) - { - } -} -", + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + + """, GetRS1028ResultAt(0), GetRS1028ResultAt(1), GetRS1028ResultAt(2)); - } [Fact] - public async Task RS1007_RS1015_VisualBasic_NoDiagnosticCasesAsync() - { - await VerifyBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly dummyLocalizableTitle As LocalizableString = new LocalizableResourceString(""dummyName"", Nothing, Nothing) - Private Shared ReadOnly descriptor As DiagnosticDescriptor = new {|#0:DiagnosticDescriptor|}(""MyDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault:=true, helpLinkUri:=""HelpLink"") - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = new {|#1:DiagnosticDescriptor|}(""MyDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""MyDiagnosticDescription."", ""HelpLink"") - Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = new {|#2:DiagnosticDescriptor|}(helpLinkUri:=""HelpLink"", id:=""MyDiagnosticId"", title:=dummyLocalizableTitle, messageFormat:=""MyDiagnosticMessage"", category:=""MyDiagnosticCategory"", defaultSeverity:=DiagnosticSeverity.Warning, isEnabledByDefault:=true) - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", + public Task RS1007_RS1015_VisualBasic_NoDiagnosticCasesAsync() + => VerifyBasicAnalyzerAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly dummyLocalizableTitle As LocalizableString = new LocalizableResourceString("dummyName", Nothing, Nothing) + Private Shared ReadOnly descriptor As DiagnosticDescriptor = new {|#0:DiagnosticDescriptor|}("MyDiagnosticId", dummyLocalizableTitle, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault:=true, helpLinkUri:="HelpLink") + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = new {|#1:DiagnosticDescriptor|}("MyDiagnosticId", dummyLocalizableTitle, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "MyDiagnosticDescription.", "HelpLink") + Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = new {|#2:DiagnosticDescriptor|}(helpLinkUri:="HelpLink", id:="MyDiagnosticId", title:=dummyLocalizableTitle, messageFormat:="MyDiagnosticMessage", category:="MyDiagnosticCategory", defaultSeverity:=DiagnosticSeverity.Warning, isEnabledByDefault:=true) + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """, GetRS1028ResultAt(0), GetRS1028ResultAt(1), GetRS1028ResultAt(2)); - } #endregion #region RS1017 (DiagnosticIdMustBeAConstantRuleId) and RS1019 (UseUniqueDiagnosticIdRuleId) [Fact] - public async Task RS1017_RS1019_CSharp_VerifyDiagnosticAsync() - { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + public Task RS1017_RS1019_CSharp_VerifyDiagnosticAsync() + => VerifyCSharpAnalyzerAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly string NonConstantDiagnosticId = ""NonConstantDiagnosticId""; - private static LocalizableResourceString dummyLocalizableTitle = null; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - private static readonly DiagnosticDescriptor descriptor = - {|#0:new DiagnosticDescriptor({|#1:NonConstantDiagnosticId|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly string NonConstantDiagnosticId = "NonConstantDiagnosticId"; + private static LocalizableResourceString dummyLocalizableTitle = null; - private static readonly DiagnosticDescriptor descriptor2 = - {|#2:new DiagnosticDescriptor(""DuplicateDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; + private static readonly DiagnosticDescriptor descriptor = + {|#0:new DiagnosticDescriptor({|#1:NonConstantDiagnosticId|}, dummyLocalizableTitle, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor, descriptor2); - } - } + private static readonly DiagnosticDescriptor descriptor2 = + {|#2:new DiagnosticDescriptor("DuplicateDiagnosticId", dummyLocalizableTitle, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; - public override void Initialize(AnalysisContext context) - { - } -} + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor, descriptor2); + } + } -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer2 : DiagnosticAnalyzer -{ - private static LocalizableString dummyLocalizableTitle = null; + public override void Initialize(AnalysisContext context) + { + } + } - private static readonly DiagnosticDescriptor descriptor = - {|#3:new DiagnosticDescriptor({|#4:""DuplicateDiagnosticId""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer2 : DiagnosticAnalyzer + { + private static LocalizableString dummyLocalizableTitle = null; + private static readonly DiagnosticDescriptor descriptor = + {|#3:new DiagnosticDescriptor({|#4:"DuplicateDiagnosticId"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor); - } - } - public override void Initialize(AnalysisContext context) - { - } -}", + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """, GetRS1028ResultAt(0), GetRS1017ExpectedDiagnostic(1, "descriptor"), GetRS1028ResultAt(2), GetRS1028ResultAt(3), GetRS1019ExpectedDiagnostic(4, "DuplicateDiagnosticId", "MyAnalyzer")); - } [Fact] - public async Task RS1017_RS1019_CSharp_VerifyDiagnostic_CreateHelperAsync() - { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + public Task RS1017_RS1019_CSharp_VerifyDiagnostic_CreateHelperAsync() + => VerifyCSharpAnalyzerAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly string NonConstantDiagnosticId = ""NonConstantDiagnosticId""; - private static LocalizableResourceString dummyLocalizableTitle = null; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - private static readonly DiagnosticDescriptor descriptor = - DiagnosticDescriptorHelper.Create({|#0:NonConstantDiagnosticId|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory""); + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly string NonConstantDiagnosticId = "NonConstantDiagnosticId"; + private static LocalizableResourceString dummyLocalizableTitle = null; - private static readonly DiagnosticDescriptor descriptor2 = - DiagnosticDescriptorHelper.Create(""DuplicateDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory""); + private static readonly DiagnosticDescriptor descriptor = + DiagnosticDescriptorHelper.Create({|#0:NonConstantDiagnosticId|}, dummyLocalizableTitle, "MyDiagnosticMessage", "MyDiagnosticCategory"); - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor, descriptor2); - } - } + private static readonly DiagnosticDescriptor descriptor2 = + DiagnosticDescriptorHelper.Create("DuplicateDiagnosticId", dummyLocalizableTitle, "MyDiagnosticMessage", "MyDiagnosticCategory"); - public override void Initialize(AnalysisContext context) - { - } -} + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor, descriptor2); + } + } -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer2 : DiagnosticAnalyzer -{ - private static LocalizableString dummyLocalizableTitle = null; + public override void Initialize(AnalysisContext context) + { + } + } - private static readonly DiagnosticDescriptor descriptor = - DiagnosticDescriptorHelper.Create({|#1:""DuplicateDiagnosticId""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory""); + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer2 : DiagnosticAnalyzer + { + private static LocalizableString dummyLocalizableTitle = null; + private static readonly DiagnosticDescriptor descriptor = + DiagnosticDescriptorHelper.Create({|#1:"DuplicateDiagnosticId"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "MyDiagnosticCategory"); - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor); - } - } - public override void Initialize(AnalysisContext context) - { - } -}" + CSharpDiagnosticDescriptorCreationHelper, + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """ + CSharpDiagnosticDescriptorCreationHelper, GetRS1017ExpectedDiagnostic(0, "descriptor"), GetRS1019ExpectedDiagnostic(1, "DuplicateDiagnosticId", "MyAnalyzer")); - } [Fact] - public async Task RS1017_RS1019_VisualBasic_VerifyDiagnosticAsync() - { - await VerifyBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - Private Shared ReadOnly NonConstantDiagnosticId = ""NonConstantDiagnosticId"" - Private Shared ReadOnly dummyLocalizableTitle As LocalizableString = Nothing - Private Shared ReadOnly descriptor As DiagnosticDescriptor = new {|#0:DiagnosticDescriptor|}({|#1:NonConstantDiagnosticId|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault:=true, helpLinkUri:=""HelpLink"") - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = new {|#2:DiagnosticDescriptor|}(""DuplicateDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault:=true, helpLinkUri:=""HelpLink"") - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor, descriptor2) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class - - -Class MyAnalyzer2 - Inherits DiagnosticAnalyzer - Private Shared ReadOnly dummyLocalizableTitle As LocalizableString = Nothing - Private Shared ReadOnly descriptor As DiagnosticDescriptor = new {|#3:DiagnosticDescriptor|}({|#4:""DuplicateDiagnosticId""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault:=true, helpLinkUri:=""HelpLink"") - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", + public Task RS1017_RS1019_VisualBasic_VerifyDiagnosticAsync() + => VerifyBasicAnalyzerAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + Private Shared ReadOnly NonConstantDiagnosticId = "NonConstantDiagnosticId" + Private Shared ReadOnly dummyLocalizableTitle As LocalizableString = Nothing + Private Shared ReadOnly descriptor As DiagnosticDescriptor = new {|#0:DiagnosticDescriptor|}({|#1:NonConstantDiagnosticId|}, dummyLocalizableTitle, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault:=true, helpLinkUri:="HelpLink") + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = new {|#2:DiagnosticDescriptor|}("DuplicateDiagnosticId", dummyLocalizableTitle, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault:=true, helpLinkUri:="HelpLink") + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor, descriptor2) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + + Class MyAnalyzer2 + Inherits DiagnosticAnalyzer + Private Shared ReadOnly dummyLocalizableTitle As LocalizableString = Nothing + Private Shared ReadOnly descriptor As DiagnosticDescriptor = new {|#3:DiagnosticDescriptor|}({|#4:"DuplicateDiagnosticId"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault:=true, helpLinkUri:="HelpLink") + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """, GetRS1028ResultAt(0), GetRS1017ExpectedDiagnostic(1, "descriptor"), GetRS1028ResultAt(2), GetRS1028ResultAt(3), GetRS1019ExpectedDiagnostic(4, "DuplicateDiagnosticId", "MyAnalyzer")); - } [Fact] - public async Task RS1017_RS1019_VisualBasic_VerifyDiagnostic_CreateHelperAsync() - { - await VerifyBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - Private Shared ReadOnly NonConstantDiagnosticId = ""NonConstantDiagnosticId"" - Private Shared ReadOnly dummyLocalizableTitle As LocalizableString = Nothing - Private Shared ReadOnly descriptor As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create({|#0:NonConstantDiagnosticId|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"") - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create(""DuplicateDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"") - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor, descriptor2) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class - - -Class MyAnalyzer2 - Inherits DiagnosticAnalyzer - Private Shared ReadOnly dummyLocalizableTitle As LocalizableString = Nothing - Private Shared ReadOnly descriptor As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create({|#1:""DuplicateDiagnosticId""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"") - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -" + VisualBasicDiagnosticDescriptorCreationHelper, + public Task RS1017_RS1019_VisualBasic_VerifyDiagnostic_CreateHelperAsync() + => VerifyBasicAnalyzerAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + Private Shared ReadOnly NonConstantDiagnosticId = "NonConstantDiagnosticId" + Private Shared ReadOnly dummyLocalizableTitle As LocalizableString = Nothing + Private Shared ReadOnly descriptor As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create({|#0:NonConstantDiagnosticId|}, dummyLocalizableTitle, "MyDiagnosticMessage", "MyDiagnosticCategory") + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create("DuplicateDiagnosticId", dummyLocalizableTitle, "MyDiagnosticMessage", "MyDiagnosticCategory") + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor, descriptor2) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + + Class MyAnalyzer2 + Inherits DiagnosticAnalyzer + Private Shared ReadOnly dummyLocalizableTitle As LocalizableString = Nothing + Private Shared ReadOnly descriptor As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create({|#1:"DuplicateDiagnosticId"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "MyDiagnosticCategory") + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """ + VisualBasicDiagnosticDescriptorCreationHelper, GetRS1017ExpectedDiagnostic(0, "descriptor"), GetRS1019ExpectedDiagnostic(1, "DuplicateDiagnosticId", "MyAnalyzer")); - } [Fact] - public async Task RS1017_RS1019_CSharp_NoDiagnosticCasesAsync() - { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + public Task RS1017_RS1019_CSharp_NoDiagnosticCasesAsync() + => VerifyCSharpAnalyzerAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private const string ConstantDiagnosticId = ""ConstantDiagnosticId""; - private static LocalizableString dummyLocalizableTitle = null; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - private static readonly DiagnosticDescriptor descriptor = - {|#0:new DiagnosticDescriptor(ConstantDiagnosticId, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private const string ConstantDiagnosticId = "ConstantDiagnosticId"; + private static LocalizableString dummyLocalizableTitle = null; - private static readonly DiagnosticDescriptor descriptor2 = - {|#1:new DiagnosticDescriptor(""DuplicateDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; + private static readonly DiagnosticDescriptor descriptor = + {|#0:new DiagnosticDescriptor(ConstantDiagnosticId, dummyLocalizableTitle, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; - // Allow multiple descriptors with same rule ID in the same analyzer. - private static readonly DiagnosticDescriptor descriptor3 = - {|#2:new DiagnosticDescriptor(""DuplicateDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage2"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; + private static readonly DiagnosticDescriptor descriptor2 = + {|#1:new DiagnosticDescriptor("DuplicateDiagnosticId", dummyLocalizableTitle, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor, descriptor2, descriptor3); - } - } + // Allow multiple descriptors with same rule ID in the same analyzer. + private static readonly DiagnosticDescriptor descriptor3 = + {|#2:new DiagnosticDescriptor("DuplicateDiagnosticId", dummyLocalizableTitle, "MyDiagnosticMessage2", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; - public override void Initialize(AnalysisContext context) - { - } -} -", + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor, descriptor2, descriptor3); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + + """, GetRS1028ResultAt(0), GetRS1028ResultAt(1), GetRS1028ResultAt(2)); - } [Fact] - public async Task RS1017_RS1019_CSharp_NoDiagnosticCases_CreateHelperAsync() - { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + public Task RS1017_RS1019_CSharp_NoDiagnosticCases_CreateHelperAsync() + => VerifyCSharpAnalyzerAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private const string ConstantDiagnosticId = ""ConstantDiagnosticId""; - private static LocalizableString dummyLocalizableTitle = null; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - private static readonly DiagnosticDescriptor descriptor = - DiagnosticDescriptorHelper.Create(ConstantDiagnosticId, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory""); + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private const string ConstantDiagnosticId = "ConstantDiagnosticId"; + private static LocalizableString dummyLocalizableTitle = null; - private static readonly DiagnosticDescriptor descriptor2 = - DiagnosticDescriptorHelper.Create(""DuplicateDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory""); + private static readonly DiagnosticDescriptor descriptor = + DiagnosticDescriptorHelper.Create(ConstantDiagnosticId, dummyLocalizableTitle, "MyDiagnosticMessage", "MyDiagnosticCategory"); - // Allow multiple descriptors with same rule ID in the same analyzer. - private static readonly DiagnosticDescriptor descriptor3 = - DiagnosticDescriptorHelper.Create(""DuplicateDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage2"", ""MyDiagnosticCategory""); + private static readonly DiagnosticDescriptor descriptor2 = + DiagnosticDescriptorHelper.Create("DuplicateDiagnosticId", dummyLocalizableTitle, "MyDiagnosticMessage", "MyDiagnosticCategory"); - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor, descriptor2, descriptor3); - } - } + // Allow multiple descriptors with same rule ID in the same analyzer. + private static readonly DiagnosticDescriptor descriptor3 = + DiagnosticDescriptorHelper.Create("DuplicateDiagnosticId", dummyLocalizableTitle, "MyDiagnosticMessage2", "MyDiagnosticCategory"); - public override void Initialize(AnalysisContext context) - { - } -} -" + CSharpDiagnosticDescriptorCreationHelper); - } + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor, descriptor2, descriptor3); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + + """ + CSharpDiagnosticDescriptorCreationHelper); [Fact] - public async Task RS1017_RS1019_VisualBasic_NoDiagnosticCasesAsync() - { - await VerifyBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - Const ConstantDiagnosticId As String = ""ConstantDiagnosticId"" - Private Shared ReadOnly dummyLocalizableTitle As LocalizableString = Nothing - Private Shared ReadOnly descriptor As DiagnosticDescriptor = new {|#0:DiagnosticDescriptor|}(ConstantDiagnosticId, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault:=true, helpLinkUri:=""HelpLink"") - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = new {|#1:DiagnosticDescriptor|}(""DuplicateDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault:=true, helpLinkUri:=""HelpLink"") - ' Allow multiple descriptors with same rule ID in the same analyzer. - Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = new {|#2:DiagnosticDescriptor|}(""DuplicateDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage2"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault:=true, helpLinkUri:=""HelpLink"") - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor, descriptor2, descriptor3) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", + public Task RS1017_RS1019_VisualBasic_NoDiagnosticCasesAsync() + => VerifyBasicAnalyzerAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + Const ConstantDiagnosticId As String = "ConstantDiagnosticId" + Private Shared ReadOnly dummyLocalizableTitle As LocalizableString = Nothing + Private Shared ReadOnly descriptor As DiagnosticDescriptor = new {|#0:DiagnosticDescriptor|}(ConstantDiagnosticId, dummyLocalizableTitle, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault:=true, helpLinkUri:="HelpLink") + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = new {|#1:DiagnosticDescriptor|}("DuplicateDiagnosticId", dummyLocalizableTitle, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault:=true, helpLinkUri:="HelpLink") + ' Allow multiple descriptors with same rule ID in the same analyzer. + Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = new {|#2:DiagnosticDescriptor|}("DuplicateDiagnosticId", dummyLocalizableTitle, "MyDiagnosticMessage2", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault:=true, helpLinkUri:="HelpLink") + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor, descriptor2, descriptor3) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """, GetRS1028ResultAt(0), GetRS1028ResultAt(1), GetRS1028ResultAt(2)); - } [Fact] - public async Task RS1017_RS1019_VisualBasic_NoDiagnosticCases_CreateHelperAsync() - { - await VerifyBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - Const ConstantDiagnosticId As String = ""ConstantDiagnosticId"" - Private Shared ReadOnly dummyLocalizableTitle As LocalizableString = Nothing - Private Shared ReadOnly descriptor As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create(ConstantDiagnosticId, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"") - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create(""DuplicateDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"") - ' Allow multiple descriptors with same rule ID in the same analyzer. - Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create(""DuplicateDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage2"", ""MyDiagnosticCategory"") - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor, descriptor2, descriptor3) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -" + VisualBasicDiagnosticDescriptorCreationHelper); - } + public Task RS1017_RS1019_VisualBasic_NoDiagnosticCases_CreateHelperAsync() + => VerifyBasicAnalyzerAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + Const ConstantDiagnosticId As String = "ConstantDiagnosticId" + Private Shared ReadOnly dummyLocalizableTitle As LocalizableString = Nothing + Private Shared ReadOnly descriptor As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create(ConstantDiagnosticId, dummyLocalizableTitle, "MyDiagnosticMessage", "MyDiagnosticCategory") + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create("DuplicateDiagnosticId", dummyLocalizableTitle, "MyDiagnosticMessage", "MyDiagnosticCategory") + ' Allow multiple descriptors with same rule ID in the same analyzer. + Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create("DuplicateDiagnosticId", dummyLocalizableTitle, "MyDiagnosticMessage2", "MyDiagnosticCategory") + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor, descriptor2, descriptor3) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """ + VisualBasicDiagnosticDescriptorCreationHelper); #endregion @@ -605,65 +605,67 @@ End Class [Fact] public async Task RS1018_RS1020_CSharp_VerifyDiagnosticAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + var source = """ -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static LocalizableResourceString dummyLocalizableTitle = null; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - private static readonly DiagnosticDescriptor descriptor = - {|#0:new DiagnosticDescriptor(""Id1"", dummyLocalizableTitle, ""MyDiagnosticMessage"", {|#1:""NotAllowedCategory""|}, DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static LocalizableResourceString dummyLocalizableTitle = null; - private static readonly DiagnosticDescriptor descriptor2 = - {|#2:new DiagnosticDescriptor({|#3:""DifferentPrefixId""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefix"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; + private static readonly DiagnosticDescriptor descriptor = + {|#0:new DiagnosticDescriptor("Id1", dummyLocalizableTitle, "MyDiagnosticMessage", {|#1:"NotAllowedCategory"|}, DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; - private static readonly DiagnosticDescriptor descriptor3 = - {|#4:new DiagnosticDescriptor({|#5:""Prefix200""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithRange"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; + private static readonly DiagnosticDescriptor descriptor2 = + {|#2:new DiagnosticDescriptor({|#3:"DifferentPrefixId"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefix", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; - private static readonly DiagnosticDescriptor descriptor4 = - {|#6:new DiagnosticDescriptor({|#7:""Prefix101""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithId"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; + private static readonly DiagnosticDescriptor descriptor3 = + {|#4:new DiagnosticDescriptor({|#5:"Prefix200"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithRange", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; - private static readonly DiagnosticDescriptor descriptor5 = - {|#8:new DiagnosticDescriptor({|#9:""MySecondPrefix400""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; + private static readonly DiagnosticDescriptor descriptor4 = + {|#6:new DiagnosticDescriptor({|#7:"Prefix101"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithId", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; - private static readonly DiagnosticDescriptor descriptor6 = - {|#10:new DiagnosticDescriptor({|#11:""MyThirdPrefix""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; + private static readonly DiagnosticDescriptor descriptor5 = + {|#8:new DiagnosticDescriptor({|#9:"MySecondPrefix400"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefixRangeAndId", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor, descriptor2, descriptor3, descriptor4, descriptor5, descriptor6); - } - } + private static readonly DiagnosticDescriptor descriptor6 = + {|#10:new DiagnosticDescriptor({|#11:"MyThirdPrefix"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefixRangeAndId", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; - public override void Initialize(AnalysisContext context) - { - } -} -"; - string additionalText = @" -# FORMAT: -# 'Category': Comma separate list of 'StartId-EndId' or 'Id' or 'Prefix' - -CategoryWithNoIdRangeOrFormat -CategoryWithPrefix: Prefix -CategoryWithRange: Prefix000-Prefix099 -CategoryWithId: Prefix100 -CategoryWithPrefixRangeAndId: MyFirstPrefix, MySecondPrefix000-MySecondPrefix099, MySecondPrefix300 -"; + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor, descriptor2, descriptor3, descriptor4, descriptor5, descriptor6); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """; await new VerifyCS.Test { TestState = { Sources = { source }, - AdditionalFiles = { (AdditionalFileName, additionalText) }, + AdditionalFiles = { (AdditionalFileName, """ + + # FORMAT: + # 'Category': Comma separate list of 'StartId-EndId' or 'Id' or 'Prefix' + + CategoryWithNoIdRangeOrFormat + CategoryWithPrefix: Prefix + CategoryWithRange: Prefix000-Prefix099 + CategoryWithId: Prefix100 + CategoryWithPrefixRangeAndId: MyFirstPrefix, MySecondPrefix000-MySecondPrefix099, MySecondPrefix300 + + """) }, ExpectedDiagnostics = { GetRS1028ResultAt(0), @@ -687,65 +689,66 @@ public override void Initialize(AnalysisContext context) [Fact] public async Task RS1018_RS1020_CSharp_VerifyDiagnostic_CreateHelperAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + var source = """ -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static LocalizableResourceString dummyLocalizableTitle = null; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - private static readonly DiagnosticDescriptor descriptor = - DiagnosticDescriptorHelper.Create(""Id1"", dummyLocalizableTitle, ""MyDiagnosticMessage"", {|#0:""NotAllowedCategory""|}); + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static LocalizableResourceString dummyLocalizableTitle = null; - private static readonly DiagnosticDescriptor descriptor2 = - DiagnosticDescriptorHelper.Create({|#1:""DifferentPrefixId""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefix""); + private static readonly DiagnosticDescriptor descriptor = + DiagnosticDescriptorHelper.Create("Id1", dummyLocalizableTitle, "MyDiagnosticMessage", {|#0:"NotAllowedCategory"|}); - private static readonly DiagnosticDescriptor descriptor3 = - DiagnosticDescriptorHelper.Create({|#2:""Prefix200""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithRange""); + private static readonly DiagnosticDescriptor descriptor2 = + DiagnosticDescriptorHelper.Create({|#1:"DifferentPrefixId"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefix"); - private static readonly DiagnosticDescriptor descriptor4 = - DiagnosticDescriptorHelper.Create({|#3:""Prefix101""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithId""); + private static readonly DiagnosticDescriptor descriptor3 = + DiagnosticDescriptorHelper.Create({|#2:"Prefix200"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithRange"); - private static readonly DiagnosticDescriptor descriptor5 = - DiagnosticDescriptorHelper.Create({|#4:""MySecondPrefix400""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId""); + private static readonly DiagnosticDescriptor descriptor4 = + DiagnosticDescriptorHelper.Create({|#3:"Prefix101"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithId"); - private static readonly DiagnosticDescriptor descriptor6 = - DiagnosticDescriptorHelper.Create({|#5:""MyThirdPrefix""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId""); + private static readonly DiagnosticDescriptor descriptor5 = + DiagnosticDescriptorHelper.Create({|#4:"MySecondPrefix400"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefixRangeAndId"); - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor, descriptor2, descriptor3, descriptor4, descriptor5, descriptor6); - } - } + private static readonly DiagnosticDescriptor descriptor6 = + DiagnosticDescriptorHelper.Create({|#5:"MyThirdPrefix"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefixRangeAndId"); - public override void Initialize(AnalysisContext context) - { - } -}" + CSharpDiagnosticDescriptorCreationHelper; - - string additionalText = @" -# FORMAT: -# 'Category': Comma separate list of 'StartId-EndId' or 'Id' or 'Prefix' - -CategoryWithNoIdRangeOrFormat -CategoryWithPrefix: Prefix -CategoryWithRange: Prefix000-Prefix099 -CategoryWithId: Prefix100 -CategoryWithPrefixRangeAndId: MyFirstPrefix, MySecondPrefix000-MySecondPrefix099, MySecondPrefix300 -"; + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor, descriptor2, descriptor3, descriptor4, descriptor5, descriptor6); + } + } + public override void Initialize(AnalysisContext context) + { + } + } + """ + CSharpDiagnosticDescriptorCreationHelper; await new VerifyCS.Test { TestState = { Sources = { source }, - AdditionalFiles = { (AdditionalFileName, additionalText) }, + AdditionalFiles = { (AdditionalFileName, """ + + # FORMAT: + # 'Category': Comma separate list of 'StartId-EndId' or 'Id' or 'Prefix' + + CategoryWithNoIdRangeOrFormat + CategoryWithPrefix: Prefix + CategoryWithRange: Prefix000-Prefix099 + CategoryWithId: Prefix100 + CategoryWithPrefixRangeAndId: MyFirstPrefix, MySecondPrefix000-MySecondPrefix099, MySecondPrefix300 + + """) }, ExpectedDiagnostics = { GetRS1020ExpectedDiagnostic(0, "NotAllowedCategory", AdditionalFileName), @@ -763,51 +766,53 @@ public override void Initialize(AnalysisContext context) [Fact] public async Task RS1018_RS1020_VisualBasic_VerifyDiagnosticAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared dummyLocalizableTitle As LocalizableResourceString = Nothing - Private Shared ReadOnly descriptor As DiagnosticDescriptor = New {|#0:DiagnosticDescriptor|}(""Id1"", dummyLocalizableTitle, ""MyDiagnosticMessage"", {|#1:""NotAllowedCategory""|}, DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = New {|#2:DiagnosticDescriptor|}({|#3:""DifferentPrefixId""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefix"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") - Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = New {|#4:DiagnosticDescriptor|}({|#5:""Prefix200""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithRange"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") - Private Shared ReadOnly descriptor4 As DiagnosticDescriptor = New {|#6:DiagnosticDescriptor|}({|#7:""Prefix101""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithId"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") - Private Shared ReadOnly descriptor5 As DiagnosticDescriptor = New {|#8:DiagnosticDescriptor|}({|#9:""MySecondPrefix400""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") - Private Shared ReadOnly descriptor6 As DiagnosticDescriptor = New {|#10:DiagnosticDescriptor|}({|#11:""MyThirdPrefix""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor, descriptor2, descriptor3, descriptor4, descriptor5, descriptor6) - End Get - End Property - - Public Overrides Sub Initialize(ByVal context As AnalysisContext) - End Sub -End Class -"; - string additionalText = @" -# FORMAT: -# 'Category': Comma separate list of 'StartId-EndId' or 'Id' or 'Prefix' - -CategoryWithNoIdRangeOrFormat -CategoryWithPrefix: Prefix -CategoryWithRange: Prefix000-Prefix099 -CategoryWithId: Prefix100 -CategoryWithPrefixRangeAndId: MyFirstPrefix, MySecondPrefix000-MySecondPrefix099, MySecondPrefix300 -"; - + var source = """ + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared dummyLocalizableTitle As LocalizableResourceString = Nothing + Private Shared ReadOnly descriptor As DiagnosticDescriptor = New {|#0:DiagnosticDescriptor|}("Id1", dummyLocalizableTitle, "MyDiagnosticMessage", {|#1:"NotAllowedCategory"|}, DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:="HelpLink") + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = New {|#2:DiagnosticDescriptor|}({|#3:"DifferentPrefixId"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefix", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:="HelpLink") + Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = New {|#4:DiagnosticDescriptor|}({|#5:"Prefix200"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithRange", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:="HelpLink") + Private Shared ReadOnly descriptor4 As DiagnosticDescriptor = New {|#6:DiagnosticDescriptor|}({|#7:"Prefix101"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithId", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:="HelpLink") + Private Shared ReadOnly descriptor5 As DiagnosticDescriptor = New {|#8:DiagnosticDescriptor|}({|#9:"MySecondPrefix400"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefixRangeAndId", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:="HelpLink") + Private Shared ReadOnly descriptor6 As DiagnosticDescriptor = New {|#10:DiagnosticDescriptor|}({|#11:"MyThirdPrefix"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefixRangeAndId", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:="HelpLink") + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor, descriptor2, descriptor3, descriptor4, descriptor5, descriptor6) + End Get + End Property + + Public Overrides Sub Initialize(ByVal context As AnalysisContext) + End Sub + End Class + + """; await new VerifyVB.Test { TestState = { Sources = { source }, - AdditionalFiles = { (AdditionalFileName, additionalText) }, + AdditionalFiles = { (AdditionalFileName, """ + + # FORMAT: + # 'Category': Comma separate list of 'StartId-EndId' or 'Id' or 'Prefix' + + CategoryWithNoIdRangeOrFormat + CategoryWithPrefix: Prefix + CategoryWithRange: Prefix000-Prefix099 + CategoryWithId: Prefix100 + CategoryWithPrefixRangeAndId: MyFirstPrefix, MySecondPrefix000-MySecondPrefix099, MySecondPrefix300 + + """) }, ExpectedDiagnostics = { GetRS1028ResultAt(0), @@ -831,52 +836,53 @@ End Class [Fact] public async Task RS1018_RS1020_VisualBasic_VerifyDiagnostic_CreateHelperAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared dummyLocalizableTitle As LocalizableResourceString = Nothing - Private Shared ReadOnly descriptor As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create(""Id1"", dummyLocalizableTitle, ""MyDiagnosticMessage"", {|#0:""NotAllowedCategory""|}) - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create({|#1:""DifferentPrefixId""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefix"") - Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create({|#2:""Prefix200""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithRange"") - Private Shared ReadOnly descriptor4 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create({|#3:""Prefix101""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithId"") - Private Shared ReadOnly descriptor5 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create({|#4:""MySecondPrefix400""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"") - Private Shared ReadOnly descriptor6 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create({|#5:""MyThirdPrefix""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"") - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor, descriptor2, descriptor3, descriptor4, descriptor5, descriptor6) - End Get - End Property - - Public Overrides Sub Initialize(ByVal context As AnalysisContext) - End Sub -End Class -" + VisualBasicDiagnosticDescriptorCreationHelper; - - string additionalText = @" -# FORMAT: -# 'Category': Comma separate list of 'StartId-EndId' or 'Id' or 'Prefix' - -CategoryWithNoIdRangeOrFormat -CategoryWithPrefix: Prefix -CategoryWithRange: Prefix000-Prefix099 -CategoryWithId: Prefix100 -CategoryWithPrefixRangeAndId: MyFirstPrefix, MySecondPrefix000-MySecondPrefix099, MySecondPrefix300 -"; - + var source = """ + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared dummyLocalizableTitle As LocalizableResourceString = Nothing + Private Shared ReadOnly descriptor As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create("Id1", dummyLocalizableTitle, "MyDiagnosticMessage", {|#0:"NotAllowedCategory"|}) + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create({|#1:"DifferentPrefixId"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefix") + Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create({|#2:"Prefix200"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithRange") + Private Shared ReadOnly descriptor4 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create({|#3:"Prefix101"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithId") + Private Shared ReadOnly descriptor5 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create({|#4:"MySecondPrefix400"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefixRangeAndId") + Private Shared ReadOnly descriptor6 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create({|#5:"MyThirdPrefix"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefixRangeAndId") + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor, descriptor2, descriptor3, descriptor4, descriptor5, descriptor6) + End Get + End Property + + Public Overrides Sub Initialize(ByVal context As AnalysisContext) + End Sub + End Class + + """ + VisualBasicDiagnosticDescriptorCreationHelper; await new VerifyVB.Test { TestState = { Sources = { source }, - AdditionalFiles = { (AdditionalFileName, additionalText) }, + AdditionalFiles = { (AdditionalFileName, """ + + # FORMAT: + # 'Category': Comma separate list of 'StartId-EndId' or 'Id' or 'Prefix' + + CategoryWithNoIdRangeOrFormat + CategoryWithPrefix: Prefix + CategoryWithRange: Prefix000-Prefix099 + CategoryWithId: Prefix100 + CategoryWithPrefixRangeAndId: MyFirstPrefix, MySecondPrefix000-MySecondPrefix099, MySecondPrefix300 + + """) }, ExpectedDiagnostics = { GetRS1020ExpectedDiagnostic(0, "NotAllowedCategory", AdditionalFileName), @@ -894,70 +900,73 @@ End Class [Fact] public async Task RS1018_RS1020_CSharp_NoDiagnosticCasesAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + var source = """ -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static LocalizableResourceString dummyLocalizableTitle = null; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - private static readonly DiagnosticDescriptor descriptor = - {|#0:new DiagnosticDescriptor(""Id1"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithNoIdRangeOrFormat"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static LocalizableResourceString dummyLocalizableTitle = null; - private static readonly DiagnosticDescriptor descriptor2 = - {|#1:new DiagnosticDescriptor(""Prefix"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefix"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; + private static readonly DiagnosticDescriptor descriptor = + {|#0:new DiagnosticDescriptor("Id1", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithNoIdRangeOrFormat", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; - private static readonly DiagnosticDescriptor descriptor2_2 = - {|#2:new DiagnosticDescriptor(""Prefix101"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefix"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; + private static readonly DiagnosticDescriptor descriptor2 = + {|#1:new DiagnosticDescriptor("Prefix", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefix", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; - private static readonly DiagnosticDescriptor descriptor3 = - {|#3:new DiagnosticDescriptor(""Prefix001"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithRange"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; + private static readonly DiagnosticDescriptor descriptor2_2 = + {|#2:new DiagnosticDescriptor("Prefix101", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefix", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; - private static readonly DiagnosticDescriptor descriptor4 = - {|#4:new DiagnosticDescriptor(""Prefix100"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithId"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; + private static readonly DiagnosticDescriptor descriptor3 = + {|#3:new DiagnosticDescriptor("Prefix001", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithRange", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; - private static readonly DiagnosticDescriptor descriptor5 = - {|#5:new DiagnosticDescriptor(""MyFirstPrefix001"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; + private static readonly DiagnosticDescriptor descriptor4 = + {|#4:new DiagnosticDescriptor("Prefix100", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithId", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; - private static readonly DiagnosticDescriptor descriptor6 = - {|#6:new DiagnosticDescriptor(""MySecondPrefix050"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; + private static readonly DiagnosticDescriptor descriptor5 = + {|#5:new DiagnosticDescriptor("MyFirstPrefix001", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefixRangeAndId", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; - private static readonly DiagnosticDescriptor descriptor7 = - {|#7:new DiagnosticDescriptor(""MySecondPrefix300"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; + private static readonly DiagnosticDescriptor descriptor6 = + {|#6:new DiagnosticDescriptor("MySecondPrefix050", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefixRangeAndId", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor, descriptor2, descriptor2_2, descriptor3, descriptor4, descriptor5, descriptor6, descriptor7); - } - } + private static readonly DiagnosticDescriptor descriptor7 = + {|#7:new DiagnosticDescriptor("MySecondPrefix300", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefixRangeAndId", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; - public override void Initialize(AnalysisContext context) - { - } -} -"; - string additionalText = @" -# FORMAT: -# 'Category': Comma separate list of 'StartId-EndId' or 'Id' or 'Prefix' - -CategoryWithNoIdRangeOrFormat -CategoryWithPrefix: Prefix -CategoryWithRange: Prefix000-Prefix099 -CategoryWithId: Prefix100 -CategoryWithPrefixRangeAndId: MyFirstPrefix, MySecondPrefix000-MySecondPrefix099, MySecondPrefix300 -"; + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor, descriptor2, descriptor2_2, descriptor3, descriptor4, descriptor5, descriptor6, descriptor7); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + + """; await new VerifyCS.Test { TestState = { Sources = { source }, - AdditionalFiles = { (AdditionalFileName, additionalText) }, + AdditionalFiles = { (AdditionalFileName, """ + + # FORMAT: + # 'Category': Comma separate list of 'StartId-EndId' or 'Id' or 'Prefix' + + CategoryWithNoIdRangeOrFormat + CategoryWithPrefix: Prefix + CategoryWithRange: Prefix000-Prefix099 + CategoryWithId: Prefix100 + CategoryWithPrefixRangeAndId: MyFirstPrefix, MySecondPrefix000-MySecondPrefix099, MySecondPrefix300 + + """) }, ExpectedDiagnostics = { GetRS1028ResultAt(0), @@ -977,70 +986,72 @@ public override void Initialize(AnalysisContext context) [Fact] public async Task RS1018_RS1020_CSharp_NoDiagnosticCases_CreateHelperAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + var source = """ -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static LocalizableResourceString dummyLocalizableTitle = null; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - private static readonly DiagnosticDescriptor descriptor = - DiagnosticDescriptorHelper.Create(""Id1"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithNoIdRangeOrFormat""); + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static LocalizableResourceString dummyLocalizableTitle = null; - private static readonly DiagnosticDescriptor descriptor2 = - DiagnosticDescriptorHelper.Create(""Prefix"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefix""); + private static readonly DiagnosticDescriptor descriptor = + DiagnosticDescriptorHelper.Create("Id1", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithNoIdRangeOrFormat"); - private static readonly DiagnosticDescriptor descriptor2_2 = - DiagnosticDescriptorHelper.Create(""Prefix101"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefix""); + private static readonly DiagnosticDescriptor descriptor2 = + DiagnosticDescriptorHelper.Create("Prefix", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefix"); - private static readonly DiagnosticDescriptor descriptor3 = - DiagnosticDescriptorHelper.Create(""Prefix001"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithRange""); + private static readonly DiagnosticDescriptor descriptor2_2 = + DiagnosticDescriptorHelper.Create("Prefix101", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefix"); - private static readonly DiagnosticDescriptor descriptor4 = - DiagnosticDescriptorHelper.Create(""Prefix100"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithId""); + private static readonly DiagnosticDescriptor descriptor3 = + DiagnosticDescriptorHelper.Create("Prefix001", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithRange"); - private static readonly DiagnosticDescriptor descriptor5 = - DiagnosticDescriptorHelper.Create(""MyFirstPrefix001"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId""); + private static readonly DiagnosticDescriptor descriptor4 = + DiagnosticDescriptorHelper.Create("Prefix100", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithId"); - private static readonly DiagnosticDescriptor descriptor6 = - DiagnosticDescriptorHelper.Create(""MySecondPrefix050"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId""); + private static readonly DiagnosticDescriptor descriptor5 = + DiagnosticDescriptorHelper.Create("MyFirstPrefix001", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefixRangeAndId"); - private static readonly DiagnosticDescriptor descriptor7 = - DiagnosticDescriptorHelper.Create(""MySecondPrefix300"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId""); + private static readonly DiagnosticDescriptor descriptor6 = + DiagnosticDescriptorHelper.Create("MySecondPrefix050", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefixRangeAndId"); - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor, descriptor2, descriptor2_2, descriptor3, descriptor4, descriptor5, descriptor6, descriptor7); - } - } + private static readonly DiagnosticDescriptor descriptor7 = + DiagnosticDescriptorHelper.Create("MySecondPrefix300", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefixRangeAndId"); - public override void Initialize(AnalysisContext context) - { - } -}" + CSharpDiagnosticDescriptorCreationHelper; - - string additionalText = @" -# FORMAT: -# 'Category': Comma separate list of 'StartId-EndId' or 'Id' or 'Prefix' - -CategoryWithNoIdRangeOrFormat -CategoryWithPrefix: Prefix -CategoryWithRange: Prefix000-Prefix099 -CategoryWithId: Prefix100 -CategoryWithPrefixRangeAndId: MyFirstPrefix, MySecondPrefix000-MySecondPrefix099, MySecondPrefix300 -"; + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor, descriptor2, descriptor2_2, descriptor3, descriptor4, descriptor5, descriptor6, descriptor7); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """ + CSharpDiagnosticDescriptorCreationHelper; await new VerifyCS.Test { TestState = { Sources = { source }, - AdditionalFiles = { (AdditionalFileName, additionalText) } + AdditionalFiles = { (AdditionalFileName, """ + + # FORMAT: + # 'Category': Comma separate list of 'StartId-EndId' or 'Id' or 'Prefix' + + CategoryWithNoIdRangeOrFormat + CategoryWithPrefix: Prefix + CategoryWithRange: Prefix000-Prefix099 + CategoryWithId: Prefix100 + CategoryWithPrefixRangeAndId: MyFirstPrefix, MySecondPrefix000-MySecondPrefix099, MySecondPrefix300 + + """) } }, SolutionTransforms = { WithoutEnableReleaseTrackingWarning } }.RunAsync(); @@ -1049,53 +1060,55 @@ public override void Initialize(AnalysisContext context) [Fact] public async Task RS1018_RS1020_VisualBasic_NoDiagnosticCasesAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared dummyLocalizableTitle As LocalizableResourceString = Nothing - Private Shared ReadOnly descriptor As DiagnosticDescriptor = New {|#0:DiagnosticDescriptor|}(""Id1"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithNoIdRangeOrFormat"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = New {|#1:DiagnosticDescriptor|}(""Prefix"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefix"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") - Private Shared ReadOnly descriptor2_2 As DiagnosticDescriptor = New {|#2:DiagnosticDescriptor|}(""Prefix"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefix"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") - Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = New {|#3:DiagnosticDescriptor|}(""Prefix001"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithRange"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") - Private Shared ReadOnly descriptor4 As DiagnosticDescriptor = New {|#4:DiagnosticDescriptor|}(""Prefix100"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithId"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") - Private Shared ReadOnly descriptor5 As DiagnosticDescriptor = New {|#5:DiagnosticDescriptor|}(""MyFirstPrefix001"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") - Private Shared ReadOnly descriptor6 As DiagnosticDescriptor = New {|#6:DiagnosticDescriptor|}(""MySecondPrefix050"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") - Private Shared ReadOnly descriptor7 As DiagnosticDescriptor = New {|#7:DiagnosticDescriptor|}(""MySecondPrefix300"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor, descriptor2, descriptor2_2, descriptor3, descriptor4, descriptor5, descriptor6, descriptor7) - End Get - End Property - - Public Overrides Sub Initialize(ByVal context As AnalysisContext) - End Sub -End Class -"; - string additionalText = @" -# FORMAT: -# 'Category': Comma separate list of 'StartId-EndId' or 'Id' or 'Prefix' - -CategoryWithNoIdRangeOrFormat -CategoryWithPrefix: Prefix -CategoryWithRange: Prefix000-Prefix099 -CategoryWithId: Prefix100 -CategoryWithPrefixRangeAndId: MyFirstPrefix, MySecondPrefix000-MySecondPrefix099, MySecondPrefix300 -"; - + var source = """ + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared dummyLocalizableTitle As LocalizableResourceString = Nothing + Private Shared ReadOnly descriptor As DiagnosticDescriptor = New {|#0:DiagnosticDescriptor|}("Id1", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithNoIdRangeOrFormat", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:="HelpLink") + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = New {|#1:DiagnosticDescriptor|}("Prefix", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefix", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:="HelpLink") + Private Shared ReadOnly descriptor2_2 As DiagnosticDescriptor = New {|#2:DiagnosticDescriptor|}("Prefix", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefix", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:="HelpLink") + Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = New {|#3:DiagnosticDescriptor|}("Prefix001", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithRange", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:="HelpLink") + Private Shared ReadOnly descriptor4 As DiagnosticDescriptor = New {|#4:DiagnosticDescriptor|}("Prefix100", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithId", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:="HelpLink") + Private Shared ReadOnly descriptor5 As DiagnosticDescriptor = New {|#5:DiagnosticDescriptor|}("MyFirstPrefix001", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefixRangeAndId", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:="HelpLink") + Private Shared ReadOnly descriptor6 As DiagnosticDescriptor = New {|#6:DiagnosticDescriptor|}("MySecondPrefix050", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefixRangeAndId", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:="HelpLink") + Private Shared ReadOnly descriptor7 As DiagnosticDescriptor = New {|#7:DiagnosticDescriptor|}("MySecondPrefix300", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefixRangeAndId", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:="HelpLink") + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor, descriptor2, descriptor2_2, descriptor3, descriptor4, descriptor5, descriptor6, descriptor7) + End Get + End Property + + Public Overrides Sub Initialize(ByVal context As AnalysisContext) + End Sub + End Class + + """; await new VerifyVB.Test { TestState = { Sources = { source }, - AdditionalFiles = { (AdditionalFileName, additionalText) }, + AdditionalFiles = { (AdditionalFileName, """ + + # FORMAT: + # 'Category': Comma separate list of 'StartId-EndId' or 'Id' or 'Prefix' + + CategoryWithNoIdRangeOrFormat + CategoryWithPrefix: Prefix + CategoryWithRange: Prefix000-Prefix099 + CategoryWithId: Prefix100 + CategoryWithPrefixRangeAndId: MyFirstPrefix, MySecondPrefix000-MySecondPrefix099, MySecondPrefix300 + + """) }, ExpectedDiagnostics = { GetRS1028ResultAt(0), @@ -1115,54 +1128,55 @@ End Class [Fact] public async Task RS1018_RS1020_VisualBasic_NoDiagnosticCases_CreateHelperAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared dummyLocalizableTitle As LocalizableResourceString = Nothing - Private Shared ReadOnly descriptor As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create(""Id1"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithNoIdRangeOrFormat"") - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create(""Prefix"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefix"") - Private Shared ReadOnly descriptor2_2 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create(""Prefix"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefix"") - Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create(""Prefix001"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithRange"") - Private Shared ReadOnly descriptor4 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create(""Prefix100"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithId"") - Private Shared ReadOnly descriptor5 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create(""MyFirstPrefix001"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"") - Private Shared ReadOnly descriptor6 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create(""MySecondPrefix050"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"") - Private Shared ReadOnly descriptor7 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create(""MySecondPrefix300"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"") - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor, descriptor2, descriptor2_2, descriptor3, descriptor4, descriptor5, descriptor6, descriptor7) - End Get - End Property - - Public Overrides Sub Initialize(ByVal context As AnalysisContext) - End Sub -End Class -" + VisualBasicDiagnosticDescriptorCreationHelper; - - string additionalText = @" -# FORMAT: -# 'Category': Comma separate list of 'StartId-EndId' or 'Id' or 'Prefix' - -CategoryWithNoIdRangeOrFormat -CategoryWithPrefix: Prefix -CategoryWithRange: Prefix000-Prefix099 -CategoryWithId: Prefix100 -CategoryWithPrefixRangeAndId: MyFirstPrefix, MySecondPrefix000-MySecondPrefix099, MySecondPrefix300 -"; - + var source = """ + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared dummyLocalizableTitle As LocalizableResourceString = Nothing + Private Shared ReadOnly descriptor As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create("Id1", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithNoIdRangeOrFormat") + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create("Prefix", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefix") + Private Shared ReadOnly descriptor2_2 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create("Prefix", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefix") + Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create("Prefix001", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithRange") + Private Shared ReadOnly descriptor4 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create("Prefix100", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithId") + Private Shared ReadOnly descriptor5 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create("MyFirstPrefix001", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefixRangeAndId") + Private Shared ReadOnly descriptor6 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create("MySecondPrefix050", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefixRangeAndId") + Private Shared ReadOnly descriptor7 As DiagnosticDescriptor = DiagnosticDescriptorHelper.Create("MySecondPrefix300", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefixRangeAndId") + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor, descriptor2, descriptor2_2, descriptor3, descriptor4, descriptor5, descriptor6, descriptor7) + End Get + End Property + + Public Overrides Sub Initialize(ByVal context As AnalysisContext) + End Sub + End Class + + """ + VisualBasicDiagnosticDescriptorCreationHelper; await new VerifyVB.Test { TestState = { Sources = { source }, - AdditionalFiles = { (AdditionalFileName, additionalText) } + AdditionalFiles = { (AdditionalFileName, """ + + # FORMAT: + # 'Category': Comma separate list of 'StartId-EndId' or 'Id' or 'Prefix' + + CategoryWithNoIdRangeOrFormat + CategoryWithPrefix: Prefix + CategoryWithRange: Prefix000-Prefix099 + CategoryWithId: Prefix100 + CategoryWithPrefixRangeAndId: MyFirstPrefix, MySecondPrefix000-MySecondPrefix099, MySecondPrefix300 + + """) } }, SolutionTransforms = { WithoutEnableReleaseTrackingWarning } }.RunAsync(); @@ -1175,83 +1189,85 @@ End Class [Fact] public async Task RS1021_VerifyDiagnosticAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static LocalizableResourceString dummyLocalizableTitle = null; + var source = """ - private static readonly DiagnosticDescriptor descriptor = - {|#0:new DiagnosticDescriptor(""Id1"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - private static readonly DiagnosticDescriptor descriptor2 = - {|#1:new DiagnosticDescriptor(""DifferentPrefixId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefix"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; - - private static readonly DiagnosticDescriptor descriptor3 = - {|#2:new DiagnosticDescriptor(""Prefix200"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithRange"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; - - private static readonly DiagnosticDescriptor descriptor4 = - {|#3:new DiagnosticDescriptor(""Prefix101"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithId"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; - - private static readonly DiagnosticDescriptor descriptor5 = - {|#4:new DiagnosticDescriptor(""MySecondPrefix400"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; - - private static readonly DiagnosticDescriptor descriptor6 = - {|#5:new DiagnosticDescriptor(""MyThirdPrefix"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"")|}; + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static LocalizableResourceString dummyLocalizableTitle = null; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor, descriptor2, descriptor3, descriptor4, descriptor5, descriptor6); - } - } + private static readonly DiagnosticDescriptor descriptor = + {|#0:new DiagnosticDescriptor("Id1", dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; - public override void Initialize(AnalysisContext context) - { - } -} -"; - string additionalText = @" -# FORMAT: -# 'Category': Comma separate list of 'StartId-EndId' or 'Id' or 'Prefix' + private static readonly DiagnosticDescriptor descriptor2 = + {|#1:new DiagnosticDescriptor("DifferentPrefixId", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefix", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; -# Illegal: spaces in category name -{|#6:Category with spaces|} -{|#7:Category with spaces and range: Prefix100-Prefix199|} + private static readonly DiagnosticDescriptor descriptor3 = + {|#2:new DiagnosticDescriptor("Prefix200", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithRange", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; -# Illegal: Multiple colons -{|#8:CategoryMultipleColons: IdWithColon:100|} + private static readonly DiagnosticDescriptor descriptor4 = + {|#3:new DiagnosticDescriptor("Prefix101", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithId", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; -# Illegal: Duplicate category -DuplicateCategory1 -{|#9:DuplicateCategory1|} -DuplicateCategory2: Prefix100-Prefix199 -{|#10:DuplicateCategory2: Prefix200-Prefix299|} + private static readonly DiagnosticDescriptor descriptor5 = + {|#4:new DiagnosticDescriptor("MySecondPrefix400", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefixRangeAndId", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; -# Illegal: ID cannot be non-alphanumeric -{|#11:CategoryWithBadId1: Prefix_100|} -{|#12:CategoryWithBadId2: Prefix_100-Prefix_199|} + private static readonly DiagnosticDescriptor descriptor6 = + {|#5:new DiagnosticDescriptor("MyThirdPrefix", dummyLocalizableTitle, "MyDiagnosticMessage", "CategoryWithPrefixRangeAndId", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink")|}; -# Illegal: Id cannot have letters after number -{|#13:CategoryWithBadId3: Prefix000NotAllowed|} -{|#14:CategoryWithBadId4: Prefix000NotAllowed-Prefix099NotAllowed|} + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor, descriptor2, descriptor3, descriptor4, descriptor5, descriptor6); + } + } -# Illegal: Different prefixes in ID range -{|#15:CategoryWithBadId5: Prefix000-DifferentPrefix099|} -"; + public override void Initialize(AnalysisContext context) + { + } + } + """; await new VerifyCS.Test { TestState = { Sources = { source }, - AdditionalFiles = { (AdditionalFileName, additionalText) }, + AdditionalFiles = { (AdditionalFileName, """ + + # FORMAT: + # 'Category': Comma separate list of 'StartId-EndId' or 'Id' or 'Prefix' + + # Illegal: spaces in category name + {|#6:Category with spaces|} + {|#7:Category with spaces and range: Prefix100-Prefix199|} + + # Illegal: Multiple colons + {|#8:CategoryMultipleColons: IdWithColon:100|} + + # Illegal: Duplicate category + DuplicateCategory1 + {|#9:DuplicateCategory1|} + DuplicateCategory2: Prefix100-Prefix199 + {|#10:DuplicateCategory2: Prefix200-Prefix299|} + + # Illegal: ID cannot be non-alphanumeric + {|#11:CategoryWithBadId1: Prefix_100|} + {|#12:CategoryWithBadId2: Prefix_100-Prefix_199|} + + # Illegal: Id cannot have letters after number + {|#13:CategoryWithBadId3: Prefix000NotAllowed|} + {|#14:CategoryWithBadId4: Prefix000NotAllowed-Prefix099NotAllowed|} + + # Illegal: Different prefixes in ID range + {|#15:CategoryWithBadId5: Prefix000-DifferentPrefix099|} + + """) }, ExpectedDiagnostics = { GetRS1021ExpectedDiagnostic(6, "Category with spaces", AdditionalFileName), @@ -1282,33 +1298,37 @@ public override void Initialize(AnalysisContext context) [Fact] public async Task ReportOnMissingCustomTagsAsync() { - await VerifyCSharpAnalyzerAsync(@" -using Microsoft.CodeAnalysis; -public class MyAnalyzer -{ - internal static DiagnosticDescriptor Rule1 = {|#0:new DiagnosticDescriptor("""", """", """", """", DiagnosticSeverity.Warning, false)|}; - internal static DiagnosticDescriptor Rule2 = {|#1:new DiagnosticDescriptor("""", new LocalizableResourceString("""", null, null), - new LocalizableResourceString("""", null, null), """", DiagnosticSeverity.Warning, false)|}; - public void SomeMethod() - { - var diag = new DiagnosticDescriptor("""", """", """", """", DiagnosticSeverity.Warning, false); - } -}", + await VerifyCSharpAnalyzerAsync(""" + + using Microsoft.CodeAnalysis; + public class MyAnalyzer + { + internal static DiagnosticDescriptor Rule1 = {|#0:new DiagnosticDescriptor("", "", "", "", DiagnosticSeverity.Warning, false)|}; + internal static DiagnosticDescriptor Rule2 = {|#1:new DiagnosticDescriptor("", new LocalizableResourceString("", null, null), + new LocalizableResourceString("", null, null), "", DiagnosticSeverity.Warning, false)|}; + public void SomeMethod() + { + var diag = new DiagnosticDescriptor("", "", "", "", DiagnosticSeverity.Warning, false); + } + } + """, GetRS1007ExpectedDiagnostic(0), GetRS1015ExpectedDiagnostic(0), GetRS1028ResultAt(0), GetRS1015ExpectedDiagnostic(1), GetRS1028ResultAt(1)); - await VerifyBasicAnalyzerAsync(@" -Imports Microsoft.CodeAnalysis -Public Class MyAnalyzer - Friend Shared Rule1 As DiagnosticDescriptor = {|#0:New {|#1:DiagnosticDescriptor|}("""", """", """", """", DiagnosticSeverity.Warning, False)|} - Friend Shared Rule2 As DiagnosticDescriptor = New {|#2:DiagnosticDescriptor|}("""", New LocalizableResourceString("""", Nothing, Nothing), New LocalizableResourceString("""", Nothing, Nothing), """", DiagnosticSeverity.Warning, False) - Public Sub SomeMethod() - Dim diag = New DiagnosticDescriptor("""", """", """", """", DiagnosticSeverity.Warning, False) - End Sub -End Class", + await VerifyBasicAnalyzerAsync(""" + + Imports Microsoft.CodeAnalysis + Public Class MyAnalyzer + Friend Shared Rule1 As DiagnosticDescriptor = {|#0:New {|#1:DiagnosticDescriptor|}("", "", "", "", DiagnosticSeverity.Warning, False)|} + Friend Shared Rule2 As DiagnosticDescriptor = New {|#2:DiagnosticDescriptor|}("", New LocalizableResourceString("", Nothing, Nothing), New LocalizableResourceString("", Nothing, Nothing), "", DiagnosticSeverity.Warning, False) + Public Sub SomeMethod() + Dim diag = New DiagnosticDescriptor("", "", "", "", DiagnosticSeverity.Warning, False) + End Sub + End Class + """, GetRS1007ExpectedDiagnostic(0), GetRS1015ExpectedDiagnostic(1), GetRS1028ResultAt(1), @@ -1317,61 +1337,63 @@ End Sub } [Fact] - public async Task DoNotReportOnNamedCustomTagsAsync() - { - await VerifyCSharpAnalyzerAsync(@" -using Microsoft.CodeAnalysis; -public class MyAnalyzer -{ - internal static DiagnosticDescriptor Rule1 = {|#0:new DiagnosticDescriptor("""", """", """", """", DiagnosticSeverity.Warning, false, customTags: """")|}; - internal static DiagnosticDescriptor Rule2 = {|#1:new DiagnosticDescriptor("""", new LocalizableResourceString("""", null, null), - new LocalizableResourceString("""", null, null), """", DiagnosticSeverity.Warning, false, customTags: """")|}; - public void SomeMethod() - { - var diag = new DiagnosticDescriptor("""", """", """", """", DiagnosticSeverity.Warning, false, customTags: """"); - } -}", + public Task DoNotReportOnNamedCustomTagsAsync() + => VerifyCSharpAnalyzerAsync(""" + + using Microsoft.CodeAnalysis; + public class MyAnalyzer + { + internal static DiagnosticDescriptor Rule1 = {|#0:new DiagnosticDescriptor("", "", "", "", DiagnosticSeverity.Warning, false, customTags: "")|}; + internal static DiagnosticDescriptor Rule2 = {|#1:new DiagnosticDescriptor("", new LocalizableResourceString("", null, null), + new LocalizableResourceString("", null, null), "", DiagnosticSeverity.Warning, false, customTags: "")|}; + public void SomeMethod() + { + var diag = new DiagnosticDescriptor("", "", "", "", DiagnosticSeverity.Warning, false, customTags: ""); + } + } + """, GetRS1007ExpectedDiagnostic(0), GetRS1015ExpectedDiagnostic(0), GetRS1015ExpectedDiagnostic(1)); - // Named arguments are incompatible with ParamArray in VB.NET - } - [Fact] public async Task DoNotReportOnCustomTagsAsync() { - await VerifyCSharpAnalyzerAsync(@" -using Microsoft.CodeAnalysis; -public class MyAnalyzer -{ - internal static DiagnosticDescriptor Rule1 = {|#0:new DiagnosticDescriptor("""", """", """", """", DiagnosticSeverity.Warning, false, null, {|#1:null|}, """")|}; - internal static DiagnosticDescriptor Rule2 = new DiagnosticDescriptor("""", new LocalizableResourceString("""", null, null), - new LocalizableResourceString("""", null, null), """", DiagnosticSeverity.Warning, false, new LocalizableResourceString("""", null, null), """", """"); - internal static DiagnosticDescriptor Rule3 = {|#2:new DiagnosticDescriptor("""", """", """", """", DiagnosticSeverity.Warning, false, null, {|#3:null|}, new[] { """", """" })|}; - internal static DiagnosticDescriptor Rule4 = new DiagnosticDescriptor("""", new LocalizableResourceString("""", null, null), - new LocalizableResourceString("""", null, null), """", DiagnosticSeverity.Warning, false, new LocalizableResourceString("""", null, null), """", new[] { """", """" }); - public void SomeMethod() - { - var diag = new DiagnosticDescriptor("""", """", """", """", DiagnosticSeverity.Warning, false, null, null, """"); - } -}", + await VerifyCSharpAnalyzerAsync(""" + + using Microsoft.CodeAnalysis; + public class MyAnalyzer + { + internal static DiagnosticDescriptor Rule1 = {|#0:new DiagnosticDescriptor("", "", "", "", DiagnosticSeverity.Warning, false, null, {|#1:null|}, "")|}; + internal static DiagnosticDescriptor Rule2 = new DiagnosticDescriptor("", new LocalizableResourceString("", null, null), + new LocalizableResourceString("", null, null), "", DiagnosticSeverity.Warning, false, new LocalizableResourceString("", null, null), "", ""); + internal static DiagnosticDescriptor Rule3 = {|#2:new DiagnosticDescriptor("", "", "", "", DiagnosticSeverity.Warning, false, null, {|#3:null|}, new[] { "", "" })|}; + internal static DiagnosticDescriptor Rule4 = new DiagnosticDescriptor("", new LocalizableResourceString("", null, null), + new LocalizableResourceString("", null, null), "", DiagnosticSeverity.Warning, false, new LocalizableResourceString("", null, null), "", new[] { "", "" }); + public void SomeMethod() + { + var diag = new DiagnosticDescriptor("", "", "", "", DiagnosticSeverity.Warning, false, null, null, ""); + } + } + """, GetRS1007ExpectedDiagnostic(0), GetRS1015ExpectedDiagnostic(1), GetRS1007ExpectedDiagnostic(2), GetRS1015ExpectedDiagnostic(3)); - await VerifyBasicAnalyzerAsync(@" -Imports Microsoft.CodeAnalysis -Public Class MyAnalyzer - Friend Shared Rule1 As DiagnosticDescriptor = {|#0:New DiagnosticDescriptor("""", """", """", """", DiagnosticSeverity.Warning, False, Nothing, {|#1:Nothing|}, """")|} - Friend Shared Rule2 As DiagnosticDescriptor = New DiagnosticDescriptor("""", New LocalizableResourceString("""", Nothing, Nothing), New LocalizableResourceString("""", Nothing, Nothing), """", DiagnosticSeverity.Warning, False, New LocalizableResourceString("""", Nothing, Nothing), """", """") - Friend Shared Rule3 As DiagnosticDescriptor = {|#2:New DiagnosticDescriptor("""", """", """", """", DiagnosticSeverity.Warning, False, Nothing, {|#3:Nothing|}, { """", """" })|} - Friend Shared Rule4 As DiagnosticDescriptor = New DiagnosticDescriptor("""", New LocalizableResourceString("""", Nothing, Nothing), New LocalizableResourceString("""", Nothing, Nothing), """", DiagnosticSeverity.Warning, False, New LocalizableResourceString("""", Nothing, Nothing), """", { """", """" }) - Public Sub SomeMethod() - Dim diag = New DiagnosticDescriptor("""", """", """", """", DiagnosticSeverity.Warning, False, Nothing, Nothing, """") - End Sub -End Class", + await VerifyBasicAnalyzerAsync(""" + + Imports Microsoft.CodeAnalysis + Public Class MyAnalyzer + Friend Shared Rule1 As DiagnosticDescriptor = {|#0:New DiagnosticDescriptor("", "", "", "", DiagnosticSeverity.Warning, False, Nothing, {|#1:Nothing|}, "")|} + Friend Shared Rule2 As DiagnosticDescriptor = New DiagnosticDescriptor("", New LocalizableResourceString("", Nothing, Nothing), New LocalizableResourceString("", Nothing, Nothing), "", DiagnosticSeverity.Warning, False, New LocalizableResourceString("", Nothing, Nothing), "", "") + Friend Shared Rule3 As DiagnosticDescriptor = {|#2:New DiagnosticDescriptor("", "", "", "", DiagnosticSeverity.Warning, False, Nothing, {|#3:Nothing|}, { "", "" })|} + Friend Shared Rule4 As DiagnosticDescriptor = New DiagnosticDescriptor("", New LocalizableResourceString("", Nothing, Nothing), New LocalizableResourceString("", Nothing, Nothing), "", DiagnosticSeverity.Warning, False, New LocalizableResourceString("", Nothing, Nothing), "", { "", "" }) + Public Sub SomeMethod() + Dim diag = New DiagnosticDescriptor("", "", "", "", DiagnosticSeverity.Warning, False, Nothing, Nothing, "") + End Sub + End Class + """, GetRS1007ExpectedDiagnostic(0), GetRS1015ExpectedDiagnostic(1), GetRS1007ExpectedDiagnostic(2), @@ -1384,47 +1406,49 @@ End Sub [Fact, WorkItem(1727, "https://github.com/dotnet/roslyn-analyzers/issues/1727")] public async Task RS1029_AlreadyUsedId_DiagnosticAsync() { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpAnalyzerAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static LocalizableResourceString dummyLocalizableTitle = null; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - private static readonly DiagnosticDescriptor descriptor1 = - new DiagnosticDescriptor({|#0:""CA0""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """"); + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static LocalizableResourceString dummyLocalizableTitle = null; - private static readonly DiagnosticDescriptor descriptor2 = - new DiagnosticDescriptor({|#1:""CS0""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """"); + private static readonly DiagnosticDescriptor descriptor1 = + new DiagnosticDescriptor({|#0:"CA0"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: ""); - private static readonly DiagnosticDescriptor descriptor3 = - new DiagnosticDescriptor({|#2:""BC0""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """"); + private static readonly DiagnosticDescriptor descriptor2 = + new DiagnosticDescriptor({|#1:"CS0"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: ""); - private static readonly DiagnosticDescriptor descriptor4 = - new DiagnosticDescriptor({|#3:""CA00000000000000000000""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """"); + private static readonly DiagnosticDescriptor descriptor3 = + new DiagnosticDescriptor({|#2:"BC0"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: ""); - private static readonly DiagnosticDescriptor descriptor5 = - new DiagnosticDescriptor({|#4:""CS00000000000000000000""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """"); + private static readonly DiagnosticDescriptor descriptor4 = + new DiagnosticDescriptor({|#3:"CA00000000000000000000"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: ""); - private static readonly DiagnosticDescriptor descriptor6 = - new DiagnosticDescriptor({|#5:""BC00000000000000000000""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """"); + private static readonly DiagnosticDescriptor descriptor5 = + new DiagnosticDescriptor({|#4:"CS00000000000000000000"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: ""); - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1); - } - } + private static readonly DiagnosticDescriptor descriptor6 = + new DiagnosticDescriptor({|#5:"BC00000000000000000000"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: ""); - public override void Initialize(AnalysisContext context) - { - } -}", + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """, GetRS1029ResultAt(0, "CA0"), GetRS1029ResultAt(1, "CS0"), GetRS1029ResultAt(2, "BC0"), @@ -1432,33 +1456,35 @@ public override void Initialize(AnalysisContext context) GetRS1029ResultAt(4, "CS00000000000000000000"), GetRS1029ResultAt(5, "BC00000000000000000000")); - await VerifyBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared dummyLocalizableTitle As LocalizableResourceString = Nothing - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = New DiagnosticDescriptor({|#0:""CA0""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, True, Nothing, ""HelpLink"", ""customTag"") - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = New DiagnosticDescriptor({|#1:""CS0""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, True, Nothing, ""HelpLink"", ""customTag"") - Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = New DiagnosticDescriptor({|#2:""BC0""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, True, Nothing, ""HelpLink"", ""customTag"") - Private Shared ReadOnly descriptor4 As DiagnosticDescriptor = New DiagnosticDescriptor({|#3:""CA00000000000000000000""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, True, Nothing, ""HelpLink"", ""customTag"") - Private Shared ReadOnly descriptor5 As DiagnosticDescriptor = New DiagnosticDescriptor({|#4:""CS00000000000000000000""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, True, Nothing, ""HelpLink"", ""customTag"") - Private Shared ReadOnly descriptor6 As DiagnosticDescriptor = New DiagnosticDescriptor({|#5:""BC00000000000000000000""|}, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, True, Nothing, ""HelpLink"", ""customTag"") - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1) - End Get - End Property - - Public Overrides Sub Initialize(ByVal context As AnalysisContext) - End Sub -End Class", + await VerifyBasicAnalyzerAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared dummyLocalizableTitle As LocalizableResourceString = Nothing + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = New DiagnosticDescriptor({|#0:"CA0"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, True, Nothing, "HelpLink", "customTag") + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = New DiagnosticDescriptor({|#1:"CS0"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, True, Nothing, "HelpLink", "customTag") + Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = New DiagnosticDescriptor({|#2:"BC0"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, True, Nothing, "HelpLink", "customTag") + Private Shared ReadOnly descriptor4 As DiagnosticDescriptor = New DiagnosticDescriptor({|#3:"CA00000000000000000000"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, True, Nothing, "HelpLink", "customTag") + Private Shared ReadOnly descriptor5 As DiagnosticDescriptor = New DiagnosticDescriptor({|#4:"CS00000000000000000000"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, True, Nothing, "HelpLink", "customTag") + Private Shared ReadOnly descriptor6 As DiagnosticDescriptor = New DiagnosticDescriptor({|#5:"BC00000000000000000000"|}, dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, True, Nothing, "HelpLink", "customTag") + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1) + End Get + End Property + + Public Overrides Sub Initialize(ByVal context As AnalysisContext) + End Sub + End Class + """, GetRS1029ResultAt(0, "CA0"), GetRS1029ResultAt(1, "CS0"), GetRS1029ResultAt(2, "BC0"), @@ -1470,137 +1496,145 @@ End Sub [Fact, WorkItem(1727, "https://github.com/dotnet/roslyn-analyzers/issues/1727")] public async Task RS1029_DiagnosticIdSimilarButNotReserved_NoDiagnosticAsync() { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpAnalyzerAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static LocalizableResourceString dummyLocalizableTitle = null; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - private static readonly DiagnosticDescriptor descriptor1 = - new DiagnosticDescriptor(""CAA0000"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """"); + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static LocalizableResourceString dummyLocalizableTitle = null; - private static readonly DiagnosticDescriptor descriptor2 = - new DiagnosticDescriptor(""CSA0000"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """"); + private static readonly DiagnosticDescriptor descriptor1 = + new DiagnosticDescriptor("CAA0000", dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: ""); - private static readonly DiagnosticDescriptor descriptor3 = - new DiagnosticDescriptor(""BCA0000"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """"); + private static readonly DiagnosticDescriptor descriptor2 = + new DiagnosticDescriptor("CSA0000", dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: ""); - private static readonly DiagnosticDescriptor descriptor4 = - new DiagnosticDescriptor(""CA00A0"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """"); + private static readonly DiagnosticDescriptor descriptor3 = + new DiagnosticDescriptor("BCA0000", dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: ""); - private static readonly DiagnosticDescriptor descriptor5 = - new DiagnosticDescriptor(""CS00A0"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """"); + private static readonly DiagnosticDescriptor descriptor4 = + new DiagnosticDescriptor("CA00A0", dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: ""); - private static readonly DiagnosticDescriptor descriptor6 = - new DiagnosticDescriptor(""BC00A0"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """"); + private static readonly DiagnosticDescriptor descriptor5 = + new DiagnosticDescriptor("CS00A0", dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: ""); - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1); - } - } + private static readonly DiagnosticDescriptor descriptor6 = + new DiagnosticDescriptor("BC00A0", dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: ""); - public override void Initialize(AnalysisContext context) - { - } -}"); - - await VerifyBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared dummyLocalizableTitle As LocalizableResourceString = Nothing - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = New DiagnosticDescriptor(""CAA0000"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, True, Nothing, ""HelpLink"", ""customTag"") - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = New DiagnosticDescriptor(""CSA0000"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, True, Nothing, ""HelpLink"", ""customTag"") - Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = New DiagnosticDescriptor(""BCA0000"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, True, Nothing, ""HelpLink"", ""customTag"") - Private Shared ReadOnly descriptor4 As DiagnosticDescriptor = New DiagnosticDescriptor(""CA00A0"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, True, Nothing, ""HelpLink"", ""customTag"") - Private Shared ReadOnly descriptor5 As DiagnosticDescriptor = New DiagnosticDescriptor(""CS00A0"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, True, Nothing, ""HelpLink"", ""customTag"") - Private Shared ReadOnly descriptor6 As DiagnosticDescriptor = New DiagnosticDescriptor(""BC00A0"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, True, Nothing, ""HelpLink"", ""customTag"") - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1) - End Get - End Property - - Public Overrides Sub Initialize(ByVal context As AnalysisContext) - End Sub -End Class"); + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """); + + await VerifyBasicAnalyzerAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared dummyLocalizableTitle As LocalizableResourceString = Nothing + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = New DiagnosticDescriptor("CAA0000", dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, True, Nothing, "HelpLink", "customTag") + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = New DiagnosticDescriptor("CSA0000", dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, True, Nothing, "HelpLink", "customTag") + Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = New DiagnosticDescriptor("BCA0000", dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, True, Nothing, "HelpLink", "customTag") + Private Shared ReadOnly descriptor4 As DiagnosticDescriptor = New DiagnosticDescriptor("CA00A0", dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, True, Nothing, "HelpLink", "customTag") + Private Shared ReadOnly descriptor5 As DiagnosticDescriptor = New DiagnosticDescriptor("CS00A0", dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, True, Nothing, "HelpLink", "customTag") + Private Shared ReadOnly descriptor6 As DiagnosticDescriptor = New DiagnosticDescriptor("BC00A0", dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, True, Nothing, "HelpLink", "customTag") + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1) + End Get + End Property + + Public Overrides Sub Initialize(ByVal context As AnalysisContext) + End Sub + End Class + """); } [Fact, WorkItem(1727, "https://github.com/dotnet/roslyn-analyzers/issues/1727")] public async Task RS1029_DiagnosticIdSimilarButTooShort_NoDiagnosticAsync() { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpAnalyzerAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static LocalizableResourceString dummyLocalizableTitle = null; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - private static readonly DiagnosticDescriptor descriptor1 = - new DiagnosticDescriptor(""CA"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """"); + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static LocalizableResourceString dummyLocalizableTitle = null; - private static readonly DiagnosticDescriptor descriptor2 = - new DiagnosticDescriptor(""CS"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """"); + private static readonly DiagnosticDescriptor descriptor1 = + new DiagnosticDescriptor("CA", dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: ""); - private static readonly DiagnosticDescriptor descriptor3 = - new DiagnosticDescriptor(""BC"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """"); + private static readonly DiagnosticDescriptor descriptor2 = + new DiagnosticDescriptor("CS", dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: ""); - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1); - } - } + private static readonly DiagnosticDescriptor descriptor3 = + new DiagnosticDescriptor("BC", dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: ""); - public override void Initialize(AnalysisContext context) - { - } -}"); - - await VerifyBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared dummyLocalizableTitle As LocalizableResourceString = Nothing - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = New DiagnosticDescriptor(""CA"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, True, Nothing, ""HelpLink"", ""customTag"") - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = New DiagnosticDescriptor(""CS"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, True, Nothing, ""HelpLink"", ""customTag"") - Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = New DiagnosticDescriptor(""BC"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, True, Nothing, ""HelpLink"", ""customTag"") - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1) - End Get - End Property - - Public Overrides Sub Initialize(ByVal context As AnalysisContext) - End Sub -End Class"); + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """); + + await VerifyBasicAnalyzerAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared dummyLocalizableTitle As LocalizableResourceString = Nothing + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = New DiagnosticDescriptor("CA", dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, True, Nothing, "HelpLink", "customTag") + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = New DiagnosticDescriptor("CS", dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, True, Nothing, "HelpLink", "customTag") + Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = New DiagnosticDescriptor("BC", dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, True, Nothing, "HelpLink", "customTag") + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1) + End Get + End Property + + Public Overrides Sub Initialize(ByVal context As AnalysisContext) + End Sub + End Class + """); } [Theory, WorkItem(1727, "https://github.com/dotnet/roslyn-analyzers/issues/1727")] @@ -1624,32 +1658,34 @@ public async Task RS1029_CADiagnosticIdOnRoslynAnalyzers_NoDiagnosticAsync(strin { await new VerifyCS.Test { - TestCode = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + TestCode = """ -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static LocalizableResourceString dummyLocalizableTitle = null; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - private static readonly DiagnosticDescriptor descriptor1 = - new DiagnosticDescriptor(""CA0000"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """"); + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static LocalizableResourceString dummyLocalizableTitle = null; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1); - } - } + private static readonly DiagnosticDescriptor descriptor1 = + new DiagnosticDescriptor("CA0000", dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: ""); - public override void Initialize(AnalysisContext context) - { - } -}", + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """, SolutionTransforms = { (solution, projectId) => solution.GetProject(projectId)!.WithAssemblyName(assemblyName).Solution, @@ -1659,28 +1695,30 @@ public override void Initialize(AnalysisContext context) await new VerifyVB.Test { - TestCode = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared dummyLocalizableTitle As LocalizableResourceString = Nothing - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = New DiagnosticDescriptor(""CA0000"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, True, Nothing, ""HelpLink"", ""customTag"") - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1) - End Get - End Property - - Public Overrides Sub Initialize(ByVal context As AnalysisContext) - End Sub -End Class", + TestCode = """ + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared dummyLocalizableTitle As LocalizableResourceString = Nothing + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = New DiagnosticDescriptor("CA0000", dummyLocalizableTitle, "MyDiagnosticMessage", "NotAllowedCategory", DiagnosticSeverity.Warning, True, Nothing, "HelpLink", "customTag") + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1) + End Get + End Property + + Public Overrides Sub Initialize(ByVal context As AnalysisContext) + End Sub + End Class + """, SolutionTransforms = { (solution, projectId) => solution.GetProject(projectId)!.WithAssemblyName(assemblyName).Solution, @@ -1696,65 +1734,69 @@ End Sub [WindowsOnlyFact, WorkItem(3575, "https://github.com/dotnet/roslyn-analyzers/issues/3575")] public async Task RS1031_TitleStringEndsWithPeriod_DiagnosticAsync() { - await VerifyCSharpCodeFixAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpCodeFixAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", {|#1:""MyDiagnosticTitle.""|}, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; - private static readonly DiagnosticDescriptor descriptor2 = - {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", {|#3:Title|}, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; - private const string Title = {|#4:""MyDiagnosticTitle.""|}; - private static readonly DiagnosticDescriptor descriptor3 = - {|#5:new DiagnosticDescriptor(""MyDiagnosticId"", {|#6:s_title|}, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; - private static string s_title = {|#7:""MyDiagnosticTitle.""|}; - - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1, descriptor2, descriptor3); - } - } + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override void Initialize(AnalysisContext context) - { - } -}", @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + {|#0:new DiagnosticDescriptor("MyDiagnosticId", {|#1:"MyDiagnosticTitle."|}, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; + private static readonly DiagnosticDescriptor descriptor2 = + {|#2:new DiagnosticDescriptor("MyDiagnosticId", {|#3:Title|}, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; + private const string Title = {|#4:"MyDiagnosticTitle."|}; + private static readonly DiagnosticDescriptor descriptor3 = + {|#5:new DiagnosticDescriptor("MyDiagnosticId", {|#6:s_title|}, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; + private static string s_title = {|#7:"MyDiagnosticTitle."|}; + + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1, descriptor2, descriptor3); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """, """ -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; - private static readonly DiagnosticDescriptor descriptor2 = - {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", Title, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; - private const string Title = ""MyDiagnosticTitle""; - private static readonly DiagnosticDescriptor descriptor3 = - {|#5:new DiagnosticDescriptor(""MyDiagnosticId"", s_title, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; - private static string s_title = ""MyDiagnosticTitle""; - - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1, descriptor2, descriptor3); - } - } + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override void Initialize(AnalysisContext context) - { - } -}", + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; + private static readonly DiagnosticDescriptor descriptor2 = + {|#2:new DiagnosticDescriptor("MyDiagnosticId", Title, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; + private const string Title = "MyDiagnosticTitle"; + private static readonly DiagnosticDescriptor descriptor3 = + {|#5:new DiagnosticDescriptor("MyDiagnosticId", s_title, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; + private static string s_title = "MyDiagnosticTitle"; + + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1, descriptor2, descriptor3); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """, GetRS1007ExpectedDiagnostic(0), VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticTitleCorrectlyRule).WithLocation(1).WithLocation(1), GetRS1007ExpectedDiagnostic(2), @@ -1762,57 +1804,61 @@ public override void Initialize(AnalysisContext context) GetRS1007ExpectedDiagnostic(5), VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticTitleCorrectlyRule).WithLocation(6).WithLocation(7)); - await VerifyBasicCodeFixAsync(@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", {|#1:""MyDiagnosticTitle.""|}, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", {|#3:Title|}, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} - Private Const Title As String = {|#4:""MyDiagnosticTitle.""|} - Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = {|#5:new DiagnosticDescriptor(""MyDiagnosticId"", {|#6:s_title|}, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} - Private Shared ReadOnly s_title As String = {|#7:""MyDiagnosticTitle.""|} - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1, descriptor2, descriptor3) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", Title, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} - Private Const Title As String = ""MyDiagnosticTitle"" - Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = {|#5:new DiagnosticDescriptor(""MyDiagnosticId"", s_title, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} - Private Shared ReadOnly s_title As String = ""MyDiagnosticTitle"" - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1, descriptor2, descriptor3) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", + await VerifyBasicCodeFixAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor("MyDiagnosticId", {|#1:"MyDiagnosticTitle."|}, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor("MyDiagnosticId", {|#3:Title|}, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} + Private Const Title As String = {|#4:"MyDiagnosticTitle."|} + Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = {|#5:new DiagnosticDescriptor("MyDiagnosticId", {|#6:s_title|}, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} + Private Shared ReadOnly s_title As String = {|#7:"MyDiagnosticTitle."|} + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1, descriptor2, descriptor3) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """, """ + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor("MyDiagnosticId", Title, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} + Private Const Title As String = "MyDiagnosticTitle" + Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = {|#5:new DiagnosticDescriptor("MyDiagnosticId", s_title, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} + Private Shared ReadOnly s_title As String = "MyDiagnosticTitle" + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1, descriptor2, descriptor3) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """, GetRS1007ExpectedDiagnostic(0), VerifyVB.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticTitleCorrectlyRule).WithLocation(1).WithLocation(1), GetRS1007ExpectedDiagnostic(2), @@ -1843,192 +1889,206 @@ public async Task RS1031_TitleStringEndsWithPeriod_ResxFile_DiagnosticAsync( string csharpLocalizableFieldDeclaration = "", string basicLocalizableFieldDeclaration = "") { string additionalFileName = "Resources.resx"; - string additionalFileTextFormat = @" - - - {0} - Optional comment. - -"; - - string csharpSourceFormat = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -class Resources -{{ - public static LocalizableResourceString CreateLocalizableResourceString(string resourceName) => default; - public static string AnalyzerTitle => string.Empty; -}} - -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -public sealed class MyAnalyzer : DiagnosticAnalyzer -{{ - private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( - ""RuleId"", {0}, ""Message"", ""Category"", DiagnosticSeverity.Warning, true, ""Description."", ""HelpLinkUri"", ""Tags""); - {1} - public override ImmutableArray SupportedDiagnostics {{ get; }} = ImmutableArray.Create(Rule); - public override void Initialize(AnalysisContext context) {{ }} -}}"; + string additionalFileTextFormat = """ + + + + {0} + Optional comment. + + + """; + + string csharpSourceFormat = """ + + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + class Resources + {{ + public static LocalizableResourceString CreateLocalizableResourceString(string resourceName) => default; + public static string AnalyzerTitle => string.Empty; + }} + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + public sealed class MyAnalyzer : DiagnosticAnalyzer + {{ + private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( + "RuleId", {0}, "Message", "Category", DiagnosticSeverity.Warning, true, "Description.", "HelpLinkUri", "Tags"); + {1} + public override ImmutableArray SupportedDiagnostics {{ get; }} = ImmutableArray.Create(Rule); + public override void Initialize(AnalysisContext context) {{ }} + }} + """; await VerifyCSharpCodeFixAsync( source: string.Format(csharpSourceFormat, $"{{|#0:{csharpLocalizableTitleExpression}|}}", csharpLocalizableFieldDeclaration), fixedSource: string.Format(csharpSourceFormat, csharpLocalizableTitleExpression, csharpLocalizableFieldDeclaration), additionalFileName: additionalFileName, additionalFileText: string.Format(additionalFileTextFormat, "My Analyzer Title."), fixedAdditionalFileText: string.Format(additionalFileTextFormat, "My Analyzer Title"), - expected: new[] - { + expected: + [ VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticTitleCorrectlyRule).WithLocation(0) - }); - - string basicSourceFormat = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - -Class Resources - Public Shared Function CreateLocalizableResourceString(resourceName As String) As LocalizableResourceString - Return Nothing - End Function - Public Shared Readonly Property AnalyzerTitle As String = """" -End Class - - -Public NotInheritable Class MyAnalyzer : Inherits DiagnosticAnalyzer - Private Shared Readonly Rule As DiagnosticDescriptor = New DiagnosticDescriptor( - ""RuleId"", {0}, ""Message"", ""Category"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUri"", ""Custom tags"") - {1} - Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) = ImmutableArray.Create(Rule) - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class"; + ]); + + string basicSourceFormat = """ + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + Class Resources + Public Shared Function CreateLocalizableResourceString(resourceName As String) As LocalizableResourceString + Return Nothing + End Function + Public Shared Readonly Property AnalyzerTitle As String = "" + End Class + + + Public NotInheritable Class MyAnalyzer : Inherits DiagnosticAnalyzer + Private Shared Readonly Rule As DiagnosticDescriptor = New DiagnosticDescriptor( + "RuleId", {0}, "Message", "Category", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUri", "Custom tags") + {1} + Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) = ImmutableArray.Create(Rule) + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + """; await VerifyBasicCodeFixAsync( source: string.Format(basicSourceFormat, $"{{|#0:{basicLocalizableTitleExpression}|}}", basicLocalizableFieldDeclaration), fixedSource: string.Format(basicSourceFormat, basicLocalizableTitleExpression, basicLocalizableFieldDeclaration), additionalFileName: additionalFileName, additionalFileText: string.Format(additionalFileTextFormat, "My Analyzer Title."), fixedAdditionalFileText: string.Format(additionalFileTextFormat, "My Analyzer Title"), - expected: new[] - { + expected: + [ VerifyVB.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticTitleCorrectlyRule).WithLocation(0) - }); + ]); } [WindowsOnlyFact, WorkItem(3575, "https://github.com/dotnet/roslyn-analyzers/issues/3575")] public async Task RS1031_TitleIsMultiSentence_DiagnosticAsync() { - await VerifyCSharpCodeFixAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpCodeFixAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", {|#1:""MyDiagnostic. Title.""|}, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - private static readonly DiagnosticDescriptor descriptor2 = - {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", {|#3:Title|}, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; - private const string Title = {|#4:""MyDiagnostic. Title""|}; + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + {|#0:new DiagnosticDescriptor("MyDiagnosticId", {|#1:"MyDiagnostic. Title."|}, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1, descriptor2); - } - } + private static readonly DiagnosticDescriptor descriptor2 = + {|#2:new DiagnosticDescriptor("MyDiagnosticId", {|#3:Title|}, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; + private const string Title = {|#4:"MyDiagnostic. Title"|}; - public override void Initialize(AnalysisContext context) - { - } -}", @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1, descriptor2); + } + } -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnostic"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + public override void Initialize(AnalysisContext context) + { + } + } + """, """ - private static readonly DiagnosticDescriptor descriptor2 = - {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", Title, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; - private const string Title = ""MyDiagnostic""; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1, descriptor2); - } - } + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnostic", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - public override void Initialize(AnalysisContext context) - { - } -}", + private static readonly DiagnosticDescriptor descriptor2 = + {|#2:new DiagnosticDescriptor("MyDiagnosticId", Title, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; + private const string Title = "MyDiagnostic"; + + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1, descriptor2); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """, GetRS1007ExpectedDiagnostic(0), VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticTitleCorrectlyRule).WithLocation(1).WithLocation(1), GetRS1007ExpectedDiagnostic(2), VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticTitleCorrectlyRule).WithLocation(3).WithLocation(4)); - await VerifyBasicCodeFixAsync(@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", {|#1:""MyDiagnostic. Title.""|}, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} - - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", {|#3:Title|}, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} - Private Const Title As String = {|#4:""MyDiagnostic. Title""|} - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1, descriptor2) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnostic"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} - - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", Title, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} - Private Const Title As String = ""MyDiagnostic"" - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1, descriptor2) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", + await VerifyBasicCodeFixAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor("MyDiagnosticId", {|#1:"MyDiagnostic. Title."|}, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} + + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor("MyDiagnosticId", {|#3:Title|}, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} + Private Const Title As String = {|#4:"MyDiagnostic. Title"|} + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1, descriptor2) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """, """ + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnostic", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} + + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor("MyDiagnosticId", Title, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} + Private Const Title As String = "MyDiagnostic" + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1, descriptor2) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """, GetRS1007ExpectedDiagnostic(0), VerifyVB.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticTitleCorrectlyRule).WithLocation(1).WithLocation(1), GetRS1007ExpectedDiagnostic(2), @@ -2065,190 +2125,204 @@ public async Task RS1031_TitleIsMultiSentence_ResxFile_DiagnosticAsync( async Task VerifyTitleAsync(string title, string fixedTitle) { string additionalFileName = "Resources.resx"; - string additionalFileTextFormat = @" - - - {0} - Optional comment. - -"; - - string csharpSourceFormat = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -class Resources -{{ - public static LocalizableResourceString CreateLocalizableResourceString(string resourceName) => default; - public static string AnalyzerTitle => string.Empty; -}} - -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -public sealed class MyAnalyzer : DiagnosticAnalyzer -{{ - private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( - ""RuleId"", {0}, ""Message"", ""Category"", DiagnosticSeverity.Warning, true, ""Description."", ""HelpLinkUri"", ""Tags""); - {1} - public override ImmutableArray SupportedDiagnostics {{ get; }} = ImmutableArray.Create(Rule); - public override void Initialize(AnalysisContext context) {{ }} -}}"; + string additionalFileTextFormat = """ + + + + {0} + Optional comment. + + + """; + + string csharpSourceFormat = """ + + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + class Resources + {{ + public static LocalizableResourceString CreateLocalizableResourceString(string resourceName) => default; + public static string AnalyzerTitle => string.Empty; + }} + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + public sealed class MyAnalyzer : DiagnosticAnalyzer + {{ + private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( + "RuleId", {0}, "Message", "Category", DiagnosticSeverity.Warning, true, "Description.", "HelpLinkUri", "Tags"); + {1} + public override ImmutableArray SupportedDiagnostics {{ get; }} = ImmutableArray.Create(Rule); + public override void Initialize(AnalysisContext context) {{ }} + }} + """; await VerifyCSharpCodeFixAsync( source: string.Format(csharpSourceFormat, $"{{|#0:{csharpLocalizableTitleExpression}|}}", csharpLocalizableFieldDeclaration), fixedSource: string.Format(csharpSourceFormat, csharpLocalizableTitleExpression, csharpLocalizableFieldDeclaration), additionalFileName: additionalFileName, additionalFileText: string.Format(additionalFileTextFormat, title), fixedAdditionalFileText: string.Format(additionalFileTextFormat, fixedTitle), - expected: new[] - { + expected: + [ VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticTitleCorrectlyRule).WithLocation(0) - }); - - string basicSourceFormat = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - -Class Resources - Public Shared Function CreateLocalizableResourceString(resourceName As String) As LocalizableResourceString - Return Nothing - End Function - Public Shared ReadOnly Property AnalyzerTitle As String = Nothing -End Class - - -Public Class MyAnalyzer : Inherits DiagnosticAnalyzer - Private Shared Rule As DiagnosticDescriptor = New DiagnosticDescriptor( - ""RuleId"", {0}, ""Message"", ""Category"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUri"", ""Tags"") - {1} - Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) = ImmutableArray.Create(Rule) - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class"; + ]); + + string basicSourceFormat = """ + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + Class Resources + Public Shared Function CreateLocalizableResourceString(resourceName As String) As LocalizableResourceString + Return Nothing + End Function + Public Shared ReadOnly Property AnalyzerTitle As String = Nothing + End Class + + + Public Class MyAnalyzer : Inherits DiagnosticAnalyzer + Private Shared Rule As DiagnosticDescriptor = New DiagnosticDescriptor( + "RuleId", {0}, "Message", "Category", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUri", "Tags") + {1} + Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) = ImmutableArray.Create(Rule) + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + """; await VerifyBasicCodeFixAsync( source: string.Format(basicSourceFormat, $"{{|#0:{basicLocalizableTitleExpression}|}}", basicLocalizableFieldDeclaration), fixedSource: string.Format(basicSourceFormat, basicLocalizableTitleExpression, basicLocalizableFieldDeclaration), additionalFileName: additionalFileName, additionalFileText: string.Format(additionalFileTextFormat, title), fixedAdditionalFileText: string.Format(additionalFileTextFormat, fixedTitle), - expected: new[] - { + expected: + [ VerifyVB.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticTitleCorrectlyRule).WithLocation(0) - }); + ]); } } [WindowsOnlyFact, WorkItem(3575, "https://github.com/dotnet/roslyn-analyzers/issues/3575")] public async Task RS1031_TitleIsMultiSentence_MultipleDescriptorsUsingSameTitle_DiagnosticAsync() { - await VerifyCSharpCodeFixAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpCodeFixAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - {|#0:new DiagnosticDescriptor(""MyDiagnosticId1"", {|#1:Title|}, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; - private static readonly DiagnosticDescriptor descriptor2 = - {|#2:new DiagnosticDescriptor(""MyDiagnosticId2"", {|#3:Title|}, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; - private const string Title = {|#4:""MyDiagnosticTitle. AnalyzerTitle.""|}; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1, descriptor2); - } - } + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + {|#0:new DiagnosticDescriptor("MyDiagnosticId1", {|#1:Title|}, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; + private static readonly DiagnosticDescriptor descriptor2 = + {|#2:new DiagnosticDescriptor("MyDiagnosticId2", {|#3:Title|}, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; + private const string Title = {|#4:"MyDiagnosticTitle. AnalyzerTitle."|}; - public override void Initialize(AnalysisContext context) - { - } -}", @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1, descriptor2); + } + } -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - {|#0:new DiagnosticDescriptor(""MyDiagnosticId1"", Title, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; - private static readonly DiagnosticDescriptor descriptor2 = - {|#2:new DiagnosticDescriptor(""MyDiagnosticId2"", Title, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; - private const string Title = ""MyDiagnosticTitle""; + public override void Initialize(AnalysisContext context) + { + } + } + """, """ - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1, descriptor2); - } - } + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override void Initialize(AnalysisContext context) - { - } -}", + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + {|#0:new DiagnosticDescriptor("MyDiagnosticId1", Title, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; + private static readonly DiagnosticDescriptor descriptor2 = + {|#2:new DiagnosticDescriptor("MyDiagnosticId2", Title, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; + private const string Title = "MyDiagnosticTitle"; + + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1, descriptor2); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """, GetRS1007ExpectedDiagnostic(0), VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticTitleCorrectlyRule).WithLocation(1).WithLocation(4), GetRS1007ExpectedDiagnostic(2), VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticTitleCorrectlyRule).WithLocation(3).WithLocation(4) ); - await VerifyBasicCodeFixAsync(@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor(""MyDiagnosticId1"", {|#1:Title|}, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor(""MyDiagnosticId2"", {|#3:Title|}, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} - Private Const Title As String = {|#4:""MyDiagnosticTitle. AnalyzerTitle.""|} - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1, descriptor2) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor(""MyDiagnosticId1"", Title, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor(""MyDiagnosticId2"", Title, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} - Private Const Title As String = ""MyDiagnosticTitle"" - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1, descriptor2) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", + await VerifyBasicCodeFixAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor("MyDiagnosticId1", {|#1:Title|}, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor("MyDiagnosticId2", {|#3:Title|}, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} + Private Const Title As String = {|#4:"MyDiagnosticTitle. AnalyzerTitle."|} + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1, descriptor2) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """, """ + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor("MyDiagnosticId1", Title, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor("MyDiagnosticId2", Title, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} + Private Const Title As String = "MyDiagnosticTitle" + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1, descriptor2) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """, GetRS1007ExpectedDiagnostic(0), VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticTitleCorrectlyRule).WithLocation(1).WithLocation(4), GetRS1007ExpectedDiagnostic(2), @@ -2265,149 +2339,159 @@ End Class public async Task RS1031_TitleIsMultiSentence_MultipleDescriptorsUsingSameTitle_ResxFile_DiagnosticAsync(string csharpTitleExpression, string basicTitleExpression) { string additionalFileName = "Resources.resx"; - string additionalFileTextFormat = @" - - - {0} - -"; - - string csharpSourceFormat = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -class Resources -{{ - public static LocalizableResourceString CreateLocalizableResourceString(string resourceName) => default; - public static string AnalyzerTitle => default; -}} - -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -public sealed class MyAnalyzer : DiagnosticAnalyzer -{{ - private static readonly DiagnosticDescriptor Rule1 = new DiagnosticDescriptor( - ""RuleId"", {0}, ""Message"", ""Category"", DiagnosticSeverity.Warning, true, ""Description."", ""HelpLinkUri"", ""Tags""); - private static readonly DiagnosticDescriptor Rule2 = new DiagnosticDescriptor( - ""RuleId"", {1}, ""Message"", ""Category"", DiagnosticSeverity.Warning, true, ""Description."", ""HelpLinkUri"", ""Tags""); - private static readonly LocalizableString Title = {2}; - - public override ImmutableArray SupportedDiagnostics {{ get; }} = ImmutableArray.Create(Rule1, Rule2); - public override void Initialize(AnalysisContext context) {{ }} -}}"; + string additionalFileTextFormat = """ + + + + {0} + + + """; + + string csharpSourceFormat = """ + + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + class Resources + {{ + public static LocalizableResourceString CreateLocalizableResourceString(string resourceName) => default; + public static string AnalyzerTitle => default; + }} + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + public sealed class MyAnalyzer : DiagnosticAnalyzer + {{ + private static readonly DiagnosticDescriptor Rule1 = new DiagnosticDescriptor( + "RuleId", {0}, "Message", "Category", DiagnosticSeverity.Warning, true, "Description.", "HelpLinkUri", "Tags"); + private static readonly DiagnosticDescriptor Rule2 = new DiagnosticDescriptor( + "RuleId", {1}, "Message", "Category", DiagnosticSeverity.Warning, true, "Description.", "HelpLinkUri", "Tags"); + private static readonly LocalizableString Title = {2}; + + public override ImmutableArray SupportedDiagnostics {{ get; }} = ImmutableArray.Create(Rule1, Rule2); + public override void Initialize(AnalysisContext context) {{ }} + }} + """; await VerifyCSharpCodeFixAsync( source: string.Format(csharpSourceFormat, "{|#0:Title|}", "{|#1:Title|}", csharpTitleExpression), fixedSource: string.Format(csharpSourceFormat, "Title", "Title", csharpTitleExpression), additionalFileName: additionalFileName, additionalFileText: string.Format(additionalFileTextFormat, "MyDiagnostic. Title."), fixedAdditionalFileText: string.Format(additionalFileTextFormat, "MyDiagnostic"), - expected: new[] - { + expected: + [ VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticTitleCorrectlyRule).WithLocation(0), VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticTitleCorrectlyRule).WithLocation(1) - }); - - string basicSourceFormat = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - -Class Resources - Public Shared Function CreateLocalizableResourceString(resourceName As String) As LocalizableResourceString - Return Nothing - End Function - Public Shared ReadOnly Property AnalyzerTitle As String = Nothing -End Class - - -Public Class MyAnalyzer : Inherits DiagnosticAnalyzer - Private Shared ReadOnly Rule1 As DiagnosticDescriptor = New DiagnosticDescriptor( - ""RuleId"", {0}, ""Message"", ""Category"", DiagnosticSeverity.Warning, true, ""Description."", ""HelpLinkUri"", ""Tags"") - Private Shared ReadOnly Rule2 As DiagnosticDescriptor = New DiagnosticDescriptor( - ""RuleId"", {1}, ""Message"", ""Category"", DiagnosticSeverity.Warning, true, ""Description."", ""HelpLinkUri"", ""Tags"") - Private Shared ReadOnly Title As LocalizableString = {2} - - Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) = ImmutableArray.Create(Rule1, Rule2) - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class"; + ]); + + string basicSourceFormat = """ + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + Class Resources + Public Shared Function CreateLocalizableResourceString(resourceName As String) As LocalizableResourceString + Return Nothing + End Function + Public Shared ReadOnly Property AnalyzerTitle As String = Nothing + End Class + + + Public Class MyAnalyzer : Inherits DiagnosticAnalyzer + Private Shared ReadOnly Rule1 As DiagnosticDescriptor = New DiagnosticDescriptor( + "RuleId", {0}, "Message", "Category", DiagnosticSeverity.Warning, true, "Description.", "HelpLinkUri", "Tags") + Private Shared ReadOnly Rule2 As DiagnosticDescriptor = New DiagnosticDescriptor( + "RuleId", {1}, "Message", "Category", DiagnosticSeverity.Warning, true, "Description.", "HelpLinkUri", "Tags") + Private Shared ReadOnly Title As LocalizableString = {2} + + Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) = ImmutableArray.Create(Rule1, Rule2) + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + """; await VerifyBasicCodeFixAsync( source: string.Format(basicSourceFormat, "{|#0:Title|}", "{|#1:Title|}", basicTitleExpression), fixedSource: string.Format(basicSourceFormat, "Title", "Title", basicTitleExpression), additionalFileName: additionalFileName, additionalFileText: string.Format(additionalFileTextFormat, "MyDiagnostic. Title."), fixedAdditionalFileText: string.Format(additionalFileTextFormat, "MyDiagnostic"), - expected: new[] - { + expected: + [ VerifyVB.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticTitleCorrectlyRule).WithLocation(0), VerifyVB.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticTitleCorrectlyRule).WithLocation(1) - }); + ]); } [WindowsOnlyFact, WorkItem(3575, "https://github.com/dotnet/roslyn-analyzers/issues/3575")] public async Task RS1031_TitleStringContainsLineReturn_DiagnosticAsync() { - await VerifyCSharpCodeFixAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpCodeFixAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", {|#1:""MyDiagnostic\rTitle""|}, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - private static readonly DiagnosticDescriptor descriptor2 = - {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", {|#3:""MyDiagnostic\nTitle""|}, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + {|#0:new DiagnosticDescriptor("MyDiagnosticId", {|#1:"MyDiagnostic\rTitle"|}, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - private static readonly DiagnosticDescriptor descriptor3 = - {|#4:new DiagnosticDescriptor(""MyDiagnosticId"", {|#5:""MyDiagnostic\r\nTitle""|}, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + private static readonly DiagnosticDescriptor descriptor2 = + {|#2:new DiagnosticDescriptor("MyDiagnosticId", {|#3:"MyDiagnostic\nTitle"|}, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1, descriptor2, descriptor3); - } - } + private static readonly DiagnosticDescriptor descriptor3 = + {|#4:new DiagnosticDescriptor("MyDiagnosticId", {|#5:"MyDiagnostic\r\nTitle"|}, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - public override void Initialize(AnalysisContext context) - { - } -}", @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1, descriptor2, descriptor3); + } + } -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnostic"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + public override void Initialize(AnalysisContext context) + { + } + } + """, """ - private static readonly DiagnosticDescriptor descriptor2 = - {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnostic"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - private static readonly DiagnosticDescriptor descriptor3 = - {|#4:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnostic"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnostic", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1, descriptor2, descriptor3); - } - } + private static readonly DiagnosticDescriptor descriptor2 = + {|#2:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnostic", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - public override void Initialize(AnalysisContext context) - { - } -}", + private static readonly DiagnosticDescriptor descriptor3 = + {|#4:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnostic", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; + + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1, descriptor2, descriptor3); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """, GetRS1007ExpectedDiagnostic(0), VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticTitleCorrectlyRule).WithLocation(1).WithLocation(1), GetRS1007ExpectedDiagnostic(2), @@ -2416,33 +2500,35 @@ public override void Initialize(AnalysisContext context) VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticTitleCorrectlyRule).WithLocation(5).WithLocation(5)); // NOTE: Code fix does not handle binary operations. - var vbCode = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.VisualBasic + var vbCode = """ - -Class MyAnalyzer - Inherits DiagnosticAnalyzer + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.VisualBasic - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", {|#1:""MyDiagnostic"" & vbCr & ""Title""|}, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} + + Class MyAnalyzer + Inherits DiagnosticAnalyzer - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", {|#3:""MyDiagnostic"" & vbLf & ""Title""|}, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor("MyDiagnosticId", {|#1:"MyDiagnostic" & vbCr & "Title"|}, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} - Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = {|#4:new DiagnosticDescriptor(""MyDiagnosticId"", {|#5:""MyDiagnostic"" & vbCrLf & ""Title""|}, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor("MyDiagnosticId", {|#3:"MyDiagnostic" & vbLf & "Title"|}, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1, descriptor2, descriptor3) - End Get - End Property + Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = {|#4:new DiagnosticDescriptor("MyDiagnosticId", {|#5:"MyDiagnostic" & vbCrLf & "Title"|}, "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -"; + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1, descriptor2, descriptor3) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """; await VerifyBasicCodeFixAsync(vbCode, vbCode, GetRS1007ExpectedDiagnostic(0), VerifyVB.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticTitleCorrectlyRule).WithLocation(1).WithLocation(1), @@ -2474,12 +2560,16 @@ public async Task RS1031_TitleStringContainsLineReturn_ResxFile_DiagnosticAsync( string csharpFieldDeclaration = "", string basicFieldDeclaration = "") { await VerifyTitleAsync( - @"MyDiagnostic -Title.", + """ + MyDiagnostic + Title. + """, @"MyDiagnostic"); await VerifyTitleAsync( - @"MyDiagnostic -Title", + """ + MyDiagnostic + Title + """, @"MyDiagnostic"); return; @@ -2489,144 +2579,154 @@ await VerifyTitleAsync( async Task VerifyTitleAsync(string title, string fixedTitle) { string additionalFileName = "Resources.resx"; - string additionalFileTextFormat = @" - - - {0} - Optional comment. - -"; - - string csharpSourceFormat = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -class Resources -{{ - public static LocalizableResourceString CreateLocalizableResourceString(string resourceName) => default; - public static string AnalyzerTitle => string.Empty; -}} - -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -public sealed class MyAnalyzer : DiagnosticAnalyzer -{{ - private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( - ""RuleId"", {0}, ""Message"", ""Category"", DiagnosticSeverity.Warning, true, ""Description."", ""HelpLinkUri"", ""Tags""); - {1} - public override ImmutableArray SupportedDiagnostics {{ get; }} = ImmutableArray.Create(Rule); - public override void Initialize(AnalysisContext context) {{ }} -}}"; + string additionalFileTextFormat = """ + + + + {0} + Optional comment. + + + """; + + string csharpSourceFormat = """ + + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + class Resources + {{ + public static LocalizableResourceString CreateLocalizableResourceString(string resourceName) => default; + public static string AnalyzerTitle => string.Empty; + }} + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + public sealed class MyAnalyzer : DiagnosticAnalyzer + {{ + private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( + "RuleId", {0}, "Message", "Category", DiagnosticSeverity.Warning, true, "Description.", "HelpLinkUri", "Tags"); + {1} + public override ImmutableArray SupportedDiagnostics {{ get; }} = ImmutableArray.Create(Rule); + public override void Initialize(AnalysisContext context) {{ }} + }} + """; await VerifyCSharpCodeFixAsync( source: string.Format(csharpSourceFormat, $"{{|#0:{csharpTitleExpression}|}}", csharpFieldDeclaration), fixedSource: string.Format(csharpSourceFormat, csharpTitleExpression, csharpFieldDeclaration), additionalFileName: additionalFileName, additionalFileText: string.Format(additionalFileTextFormat, title), fixedAdditionalFileText: string.Format(additionalFileTextFormat, fixedTitle), - expected: new[] - { + expected: + [ VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticTitleCorrectlyRule).WithLocation(0) - }); - - string basicSourceFormat = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - -Class Resources - Public Shared Function CreateLocalizableResourceString(resourceName As String) As LocalizableResourceString - Return Nothing - End Function - Public Shared Readonly Property AnalyzerTitle As String = """" -End Class - - -Public NotInheritable Class MyAnalyzer : Inherits DiagnosticAnalyzer - Private Shared Readonly Rule As DiagnosticDescriptor = New DiagnosticDescriptor( - ""RuleId"", {0}, ""Message"", ""Category"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUri"", ""Custom tags"") - {1} - Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) = ImmutableArray.Create(Rule) - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class"; + ]); + + string basicSourceFormat = """ + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + Class Resources + Public Shared Function CreateLocalizableResourceString(resourceName As String) As LocalizableResourceString + Return Nothing + End Function + Public Shared Readonly Property AnalyzerTitle As String = "" + End Class + + + Public NotInheritable Class MyAnalyzer : Inherits DiagnosticAnalyzer + Private Shared Readonly Rule As DiagnosticDescriptor = New DiagnosticDescriptor( + "RuleId", {0}, "Message", "Category", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUri", "Custom tags") + {1} + Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) = ImmutableArray.Create(Rule) + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + """; await VerifyBasicCodeFixAsync( source: string.Format(basicSourceFormat, $"{{|#0:{basicTitleExpression}|}}", basicFieldDeclaration), fixedSource: string.Format(basicSourceFormat, basicTitleExpression, basicFieldDeclaration), additionalFileName: additionalFileName, additionalFileText: string.Format(additionalFileTextFormat, title), fixedAdditionalFileText: string.Format(additionalFileTextFormat, fixedTitle), - expected: new[] - { + expected: + [ VerifyVB.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticTitleCorrectlyRule).WithLocation(0) - }); + ]); } } [WindowsOnlyFact, WorkItem(3575, "https://github.com/dotnet/roslyn-analyzers/issues/3575")] public async Task RS1031_ValidTitleString_NoDiagnosticAsync() { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpAnalyzerAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - private static readonly DiagnosticDescriptor descriptor2 = - {|#1:new DiagnosticDescriptor(""MyDiagnosticId"", ""Title can contain A.B qualifications"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - private static readonly DiagnosticDescriptor descriptor3 = - {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", ""Title can contain 'A.B' qualifications"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + private static readonly DiagnosticDescriptor descriptor2 = + {|#1:new DiagnosticDescriptor("MyDiagnosticId", "Title can contain A.B qualifications", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1, descriptor2, descriptor3); - } - } + private static readonly DiagnosticDescriptor descriptor3 = + {|#2:new DiagnosticDescriptor("MyDiagnosticId", "Title can contain 'A.B' qualifications", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - public override void Initialize(AnalysisContext context) - { - } -}", + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1, descriptor2, descriptor3); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """, GetRS1007ExpectedDiagnostic(0), GetRS1007ExpectedDiagnostic(1), GetRS1007ExpectedDiagnostic(2)); - await VerifyBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics + await VerifyBasicAnalyzerAsync(""" - -Class MyAnalyzer - Inherits DiagnosticAnalyzer + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} + + Class MyAnalyzer + Inherits DiagnosticAnalyzer - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#1:new DiagnosticDescriptor(""MyDiagnosticId"", ""Title can contain A.B qualifications"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} - Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", ""Title can contain 'A.B' qualifications"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#1:new DiagnosticDescriptor("MyDiagnosticId", "Title can contain A.B qualifications", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1, descriptor2, descriptor3) - End Get - End Property + Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor("MyDiagnosticId", "Title can contain 'A.B' qualifications", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1, descriptor2, descriptor3) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """, GetRS1007ExpectedDiagnostic(0), GetRS1007ExpectedDiagnostic(1), GetRS1007ExpectedDiagnostic(2)); @@ -2652,77 +2752,83 @@ public async Task RS1031_LeadingOrTailingWhitespace_DiagnosticAsync(string cshar async Task VerifyTitleAsync(string title, string fixedTitle) { string additionalFileName = "Resources.resx"; - string additionalFileTextFormat = @" - - - {0} - -"; - - string csharpSourceFormat = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -class Resources -{{ - public static LocalizableResourceString CreateLocalizableResourceString(string resourceName) => default; - public static string AnalyzerTitle => string.Empty; -}} - -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -public sealed class MyAnalyzer : DiagnosticAnalyzer -{{ - private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( - ""RuleId"", {0}, ""Message"", ""Category"", DiagnosticSeverity.Warning, true, ""Description."", ""HelpLinkUri"", ""Tags""); - - public override ImmutableArray SupportedDiagnostics {{ get; }} = ImmutableArray.Create(Rule); - public override void Initialize(AnalysisContext context) {{ }} -}}"; + string additionalFileTextFormat = """ + + + + {0} + + + """; + + string csharpSourceFormat = """ + + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + class Resources + {{ + public static LocalizableResourceString CreateLocalizableResourceString(string resourceName) => default; + public static string AnalyzerTitle => string.Empty; + }} + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + public sealed class MyAnalyzer : DiagnosticAnalyzer + {{ + private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( + "RuleId", {0}, "Message", "Category", DiagnosticSeverity.Warning, true, "Description.", "HelpLinkUri", "Tags"); + + public override ImmutableArray SupportedDiagnostics {{ get; }} = ImmutableArray.Create(Rule); + public override void Initialize(AnalysisContext context) {{ }} + }} + """; await VerifyCSharpCodeFixAsync( source: string.Format(csharpSourceFormat, $"{{|#0:{csharpTitleExpression}|}}"), fixedSource: string.Format(csharpSourceFormat, csharpTitleExpression), additionalFileName: additionalFileName, additionalFileText: string.Format(additionalFileTextFormat, title), fixedAdditionalFileText: string.Format(additionalFileTextFormat, fixedTitle), - expected: new[] - { + expected: + [ VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticTitleCorrectlyRule).WithLocation(0) - }); - - string basicSourceFormat = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - -Class Resources - Public Shared Function CreateLocalizableResourceString(resourceName As String) As LocalizableResourceString - Return Nothing - End Function - Public Shared ReadOnly Property AnalyzerTitle As String = Nothing -End Class - - -Public Class MyAnalyzer : Inherits DiagnosticAnalyzer - Private Shared Rule As DiagnosticDescriptor = New DiagnosticDescriptor( - ""RuleId"", {0}, ""Message"", ""Category"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUri"", ""Tags"") - - Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) = ImmutableArray.Create(Rule) - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class"; + ]); + + string basicSourceFormat = """ + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + Class Resources + Public Shared Function CreateLocalizableResourceString(resourceName As String) As LocalizableResourceString + Return Nothing + End Function + Public Shared ReadOnly Property AnalyzerTitle As String = Nothing + End Class + + + Public Class MyAnalyzer : Inherits DiagnosticAnalyzer + Private Shared Rule As DiagnosticDescriptor = New DiagnosticDescriptor( + "RuleId", {0}, "Message", "Category", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUri", "Tags") + + Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) = ImmutableArray.Create(Rule) + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + """; await VerifyBasicCodeFixAsync( source: string.Format(basicSourceFormat, $"{{|#0:{basicTitleExpression}|}}"), fixedSource: string.Format(basicSourceFormat, basicTitleExpression), additionalFileName: additionalFileName, additionalFileText: string.Format(additionalFileTextFormat, title), fixedAdditionalFileText: string.Format(additionalFileTextFormat, fixedTitle), - expected: new[] - { + expected: + [ VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticTitleCorrectlyRule).WithLocation(0) - }); + ]); } } @@ -2733,115 +2839,123 @@ await VerifyBasicCodeFixAsync( [WindowsOnlyFact, WorkItem(3576, "https://github.com/dotnet/roslyn-analyzers/issues/3576")] public async Task RS1032_MessageStringEndsWithPeriodAndIsNotMultiSentence_DiagnosticAsync() { - await VerifyCSharpCodeFixAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpCodeFixAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", {|#1:""MyDiagnosticMessage.""|}, ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - private static readonly DiagnosticDescriptor descriptor2 = - {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", {|#3:Message|}, ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; - private const string Message = {|#4:""MyDiagnostic.Message.""|}; + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", {|#1:"MyDiagnosticMessage."|}, "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1, descriptor2); - } - } + private static readonly DiagnosticDescriptor descriptor2 = + {|#2:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", {|#3:Message|}, "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; + private const string Message = {|#4:"MyDiagnostic.Message."|}; - public override void Initialize(AnalysisContext context) - { - } -}", @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1, descriptor2); + } + } -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + public override void Initialize(AnalysisContext context) + { + } + } + """, """ - private static readonly DiagnosticDescriptor descriptor2 = - {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", Message, ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; - private const string Message = ""MyDiagnostic.Message""; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1, descriptor2); - } - } + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - public override void Initialize(AnalysisContext context) - { - } -}", + private static readonly DiagnosticDescriptor descriptor2 = + {|#2:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", Message, "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; + private const string Message = "MyDiagnostic.Message"; + + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1, descriptor2); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """, GetRS1007ExpectedDiagnostic(0), VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticMessageCorrectlyRule).WithLocation(1).WithLocation(1), GetRS1007ExpectedDiagnostic(2), VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticMessageCorrectlyRule).WithLocation(3).WithLocation(4)); - await VerifyBasicCodeFixAsync(@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", {|#1:""MyDiagnosticMessage.""|}, ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} - - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", {|#3:Message|}, ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} - Private Const Message As String = {|#4:""MyDiagnostic.Message.""|} - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1, descriptor2) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} - - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", Message, ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} - Private Const Message As String = ""MyDiagnostic.Message"" - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1, descriptor2) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", + await VerifyBasicCodeFixAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", {|#1:"MyDiagnosticMessage."|}, "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} + + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", {|#3:Message|}, "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} + Private Const Message As String = {|#4:"MyDiagnostic.Message."|} + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1, descriptor2) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """, """ + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} + + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", Message, "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} + Private Const Message As String = "MyDiagnostic.Message" + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1, descriptor2) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """, GetRS1007ExpectedDiagnostic(0), VerifyVB.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticMessageCorrectlyRule).WithLocation(1).WithLocation(1), GetRS1007ExpectedDiagnostic(2), @@ -2878,177 +2992,191 @@ public async Task RS1032_MessageStringEndsWithPeriodAndIsNotMultiSentence_ResxFi async Task VerifyMessageAsync(string message, string fixedMessage) { string additionalFileName = "Resources.resx"; - string additionalFileTextFormat = @" - - - {0} - Optional comment. - -"; - - string csharpSourceFormat = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -class Resources -{{ - public static LocalizableResourceString CreateLocalizableResourceString(string resourceName) => default; - public static string AnalyzerMessage => default; -}} - -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -public sealed class MyAnalyzer : DiagnosticAnalyzer -{{ - private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( - ""RuleId"", ""Title"", {0}, ""Category"", DiagnosticSeverity.Warning, true, ""Description."", ""HelpLinkUri"", ""Tags""); - {1} - public override ImmutableArray SupportedDiagnostics {{ get; }} = ImmutableArray.Create(Rule); - public override void Initialize(AnalysisContext context) {{ }} -}}"; + string additionalFileTextFormat = """ + + + + {0} + Optional comment. + + + """; + + string csharpSourceFormat = """ + + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + class Resources + {{ + public static LocalizableResourceString CreateLocalizableResourceString(string resourceName) => default; + public static string AnalyzerMessage => default; + }} + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + public sealed class MyAnalyzer : DiagnosticAnalyzer + {{ + private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( + "RuleId", "Title", {0}, "Category", DiagnosticSeverity.Warning, true, "Description.", "HelpLinkUri", "Tags"); + {1} + public override ImmutableArray SupportedDiagnostics {{ get; }} = ImmutableArray.Create(Rule); + public override void Initialize(AnalysisContext context) {{ }} + }} + """; await VerifyCSharpCodeFixAsync( source: string.Format(csharpSourceFormat, $"{{|#0:{csharpMessageExpression}|}}", csharpFieldDeclaration), fixedSource: string.Format(csharpSourceFormat, csharpMessageExpression, csharpFieldDeclaration), additionalFileName: additionalFileName, additionalFileText: string.Format(additionalFileTextFormat, message), fixedAdditionalFileText: string.Format(additionalFileTextFormat, fixedMessage), - expected: new[] - { + expected: + [ VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticMessageCorrectlyRule).WithLocation(0) - }); - - string basicSourceFormat = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - -Class Resources - Public Shared Function CreateLocalizableResourceString(resourceName As String) As LocalizableResourceString - Return Nothing - End Function - Public Shared ReadOnly Property AnalyzerMessage As String = Nothing -End Class - - -Public NotInheritable Class MyAnalyzer : Inherits DiagnosticAnalyzer - Private Shared Rule As DiagnosticDescriptor = New DiagnosticDescriptor( - ""RuleId"", ""Title"", {0}, ""Category"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUri"", ""Tags"") - {1} - Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) = ImmutableArray.Create(Rule) - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class"; + ]); + + string basicSourceFormat = """ + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + Class Resources + Public Shared Function CreateLocalizableResourceString(resourceName As String) As LocalizableResourceString + Return Nothing + End Function + Public Shared ReadOnly Property AnalyzerMessage As String = Nothing + End Class + + + Public NotInheritable Class MyAnalyzer : Inherits DiagnosticAnalyzer + Private Shared Rule As DiagnosticDescriptor = New DiagnosticDescriptor( + "RuleId", "Title", {0}, "Category", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUri", "Tags") + {1} + Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) = ImmutableArray.Create(Rule) + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + """; await VerifyBasicCodeFixAsync( source: string.Format(basicSourceFormat, $"{{|#0:{basicMessageExpression}|}}", basicFieldDeclaration), fixedSource: string.Format(basicSourceFormat, basicMessageExpression, basicFieldDeclaration), additionalFileName: additionalFileName, additionalFileText: string.Format(additionalFileTextFormat, message), fixedAdditionalFileText: string.Format(additionalFileTextFormat, fixedMessage), - expected: new[] - { + expected: + [ VerifyVB.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticMessageCorrectlyRule).WithLocation(0) - }); + ]); } } [WindowsOnlyFact, WorkItem(3576, "https://github.com/dotnet/roslyn-analyzers/issues/3576")] public async Task RS1032_MessageStringIsMultiSentenceAndDoesNotEndWithPeriod_DiagnosticAsync() { - await VerifyCSharpCodeFixAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpCodeFixAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", {|#1:""Message is. Multi-sentence""|}, ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1); - } - } + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", {|#1:"Message is. Multi-sentence"|}, "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - public override void Initialize(AnalysisContext context) - { - } -}", @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1); + } + } -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""Message is. Multi-sentence."", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + public override void Initialize(AnalysisContext context) + { + } + } + """, """ - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1); - } - } + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override void Initialize(AnalysisContext context) - { - } -}", + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "Message is. Multi-sentence.", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; + + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """, GetRS1007ExpectedDiagnostic(0), VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticMessageCorrectlyRule).WithLocation(1).WithLocation(1)); - await VerifyBasicCodeFixAsync(@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", {|#1:""Message is. Multi-sentence""|}, ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""Message is. Multi-sentence."", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", + await VerifyBasicCodeFixAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", {|#1:"Message is. Multi-sentence"|}, "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """, """ + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "Message is. Multi-sentence.", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """, GetRS1007ExpectedDiagnostic(0), VerifyVB.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticMessageCorrectlyRule).WithLocation(1).WithLocation(1)); } @@ -3056,65 +3184,69 @@ End Class [WindowsOnlyFact, WorkItem(3576, "https://github.com/dotnet/roslyn-analyzers/issues/3576")] public async Task RS1032_MessageStringContainsLineReturn_DiagnosticAsync() { - await VerifyCSharpCodeFixAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpCodeFixAsync(""" + + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", {|#1:""MyDiagnostic\rMessage""|}, ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", {|#1:"MyDiagnostic\rMessage"|}, "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - private static readonly DiagnosticDescriptor descriptor2 = - {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", {|#3:""MyDiagnostic\nMessage""|}, ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + private static readonly DiagnosticDescriptor descriptor2 = + {|#2:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", {|#3:"MyDiagnostic\nMessage"|}, "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - private static readonly DiagnosticDescriptor descriptor3 = - {|#4:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", {|#5:""MyDiagnostic\r\nMessage""|}, ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + private static readonly DiagnosticDescriptor descriptor3 = + {|#4:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", {|#5:"MyDiagnostic\r\nMessage"|}, "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1, descriptor2, descriptor3); - } - } + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1, descriptor2, descriptor3); + } + } - public override void Initialize(AnalysisContext context) - { - } -}", @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + public override void Initialize(AnalysisContext context) + { + } + } + """, """ -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnostic. Message."", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnostic. Message.", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - private static readonly DiagnosticDescriptor descriptor2 = - {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnostic. Message."", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + private static readonly DiagnosticDescriptor descriptor2 = + {|#2:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnostic. Message.", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - private static readonly DiagnosticDescriptor descriptor3 = - {|#4:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnostic. Message."", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + private static readonly DiagnosticDescriptor descriptor3 = + {|#4:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnostic. Message.", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1, descriptor2, descriptor3); - } - } + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1, descriptor2, descriptor3); + } + } - public override void Initialize(AnalysisContext context) - { - } -}", + public override void Initialize(AnalysisContext context) + { + } + } + """, GetRS1007ExpectedDiagnostic(0), VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticMessageCorrectlyRule).WithLocation(1).WithLocation(1), GetRS1007ExpectedDiagnostic(2), @@ -3123,33 +3255,35 @@ public override void Initialize(AnalysisContext context) VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticMessageCorrectlyRule).WithLocation(5).WithLocation(5)); // NOTE: Code fix does not handle binary operations. - var vbCode = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.VisualBasic + var vbCode = """ - -Class MyAnalyzer - Inherits DiagnosticAnalyzer + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.VisualBasic - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", {|#1:""MyDiagnostic"" & vbCr & ""Message""|}, ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} + + Class MyAnalyzer + Inherits DiagnosticAnalyzer - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", {|#3:""MyDiagnostic"" & vbLf & ""Message""|}, ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", {|#1:"MyDiagnostic" & vbCr & "Message"|}, "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} - Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = {|#4:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", {|#5:""MyDiagnostic"" & vbCrLf & ""Message""|}, ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", {|#3:"MyDiagnostic" & vbLf & "Message"|}, "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1, descriptor2, descriptor3) - End Get - End Property + Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = {|#4:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", {|#5:"MyDiagnostic" & vbCrLf & "Message"|}, "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -"; + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1, descriptor2, descriptor3) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """; await VerifyBasicCodeFixAsync(vbCode, vbCode, GetRS1007ExpectedDiagnostic(0), VerifyVB.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticMessageCorrectlyRule).WithLocation(1).WithLocation(1), @@ -3181,11 +3315,15 @@ public async Task RS1032_MessageStringContainsLineReturn_ResxFile_DiagnostiAsync string csharpFieldDeclaration = "", string basicFieldDeclaration = "") { await VerifyMessageAsync( - @"MyDiagnostic -Message1.", "MyDiagnostic. Message1."); + """ + MyDiagnostic + Message1. + """, "MyDiagnostic. Message1."); await VerifyMessageAsync( - @"MyDiagnostic. -Message2", "MyDiagnostic. Message2."); + """ + MyDiagnostic. + Message2 + """, "MyDiagnostic. Message2."); return; // Local functions @@ -3193,150 +3331,160 @@ await VerifyMessageAsync( async Task VerifyMessageAsync(string message, string fixedMessage) { string additionalFileName = "Resources.resx"; - string additionalFileTextFormat = @" - - - {0} - Optional comment. - -"; - - string csharpSourceFormat = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -class Resources -{{ - public static LocalizableResourceString CreateLocalizableResourceString(string resourceName) => default; - public static string AnalyzerMessage => default; -}} - -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -public sealed class MyAnalyzer : DiagnosticAnalyzer -{{ - private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( - ""RuleId"", ""Title"", {0}, ""Category"", DiagnosticSeverity.Warning, true, ""Description."", ""HelpLinkUri"", ""Tags""); - {1} - public override ImmutableArray SupportedDiagnostics {{ get; }} = ImmutableArray.Create(Rule); - public override void Initialize(AnalysisContext context) {{ }} -}}"; + string additionalFileTextFormat = """ + + + + {0} + Optional comment. + + + """; + + string csharpSourceFormat = """ + + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + class Resources + {{ + public static LocalizableResourceString CreateLocalizableResourceString(string resourceName) => default; + public static string AnalyzerMessage => default; + }} + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + public sealed class MyAnalyzer : DiagnosticAnalyzer + {{ + private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( + "RuleId", "Title", {0}, "Category", DiagnosticSeverity.Warning, true, "Description.", "HelpLinkUri", "Tags"); + {1} + public override ImmutableArray SupportedDiagnostics {{ get; }} = ImmutableArray.Create(Rule); + public override void Initialize(AnalysisContext context) {{ }} + }} + """; await VerifyCSharpCodeFixAsync( source: string.Format(csharpSourceFormat, $"{{|#0:{csharpMessageExpression}|}}", csharpFieldDeclaration), fixedSource: string.Format(csharpSourceFormat, csharpMessageExpression, csharpFieldDeclaration), additionalFileName: additionalFileName, additionalFileText: string.Format(additionalFileTextFormat, message), fixedAdditionalFileText: string.Format(additionalFileTextFormat, fixedMessage), - expected: new[] - { + expected: + [ VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticMessageCorrectlyRule).WithLocation(0) - }); - - string basicSourceFormat = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - -Class Resources - Public Shared Function CreateLocalizableResourceString(resourceName As String) As LocalizableResourceString - Return Nothing - End Function - Public Shared ReadOnly Property AnalyzerMessage As String = Nothing -End Class - - -Public NotInheritable Class MyAnalyzer : Inherits DiagnosticAnalyzer - Private Shared Rule As DiagnosticDescriptor = New DiagnosticDescriptor( - ""RuleId"", ""Title"", {0}, ""Category"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUri"", ""Tags"") - {1} - Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) = ImmutableArray.Create(Rule) - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class"; + ]); + + string basicSourceFormat = """ + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + Class Resources + Public Shared Function CreateLocalizableResourceString(resourceName As String) As LocalizableResourceString + Return Nothing + End Function + Public Shared ReadOnly Property AnalyzerMessage As String = Nothing + End Class + + + Public NotInheritable Class MyAnalyzer : Inherits DiagnosticAnalyzer + Private Shared Rule As DiagnosticDescriptor = New DiagnosticDescriptor( + "RuleId", "Title", {0}, "Category", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUri", "Tags") + {1} + Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) = ImmutableArray.Create(Rule) + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + """; await VerifyBasicCodeFixAsync( source: string.Format(basicSourceFormat, $"{{|#0:{basicMessageExpression}|}}", basicFieldDeclaration), fixedSource: string.Format(basicSourceFormat, basicMessageExpression, basicFieldDeclaration), additionalFileName: additionalFileName, additionalFileText: string.Format(additionalFileTextFormat, message), fixedAdditionalFileText: string.Format(additionalFileTextFormat, fixedMessage), - expected: new[] - { + expected: + [ VerifyVB.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticMessageCorrectlyRule).WithLocation(0) - }); + ]); } } [WindowsOnlyFact, WorkItem(3576, "https://github.com/dotnet/roslyn-analyzers/issues/3576")] public async Task RS1032_ValidMessageString_NoDiagnosticAsync() { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpAnalyzerAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - private static readonly DiagnosticDescriptor descriptor2 = - {|#1:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""Message is a. Multi-sentence."", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - private static readonly DiagnosticDescriptor descriptor3 = - {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""Message can contain A.B qualifications"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + private static readonly DiagnosticDescriptor descriptor2 = + {|#1:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "Message is a. Multi-sentence.", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - private static readonly DiagnosticDescriptor descriptor4 = - {|#3:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""Message can contain 'A.B' qualifications"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + private static readonly DiagnosticDescriptor descriptor3 = + {|#2:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "Message can contain A.B qualifications", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1, descriptor2, descriptor3, descriptor4); - } - } + private static readonly DiagnosticDescriptor descriptor4 = + {|#3:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "Message can contain 'A.B' qualifications", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - public override void Initialize(AnalysisContext context) - { - } -}", + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1, descriptor2, descriptor3, descriptor4); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """, GetRS1007ExpectedDiagnostic(0), GetRS1007ExpectedDiagnostic(1), GetRS1007ExpectedDiagnostic(2), GetRS1007ExpectedDiagnostic(3)); - await VerifyBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics + await VerifyBasicAnalyzerAsync(""" - -Class MyAnalyzer - Inherits DiagnosticAnalyzer + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} + + Class MyAnalyzer + Inherits DiagnosticAnalyzer - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#1:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""Message is a. Multi-sentence."", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} - Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""Message can contain A.B qualifications"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#1:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "Message is a. Multi-sentence.", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} - Private Shared ReadOnly descriptor4 As DiagnosticDescriptor = {|#3:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""Message can contain 'A.B' qualifications"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} + Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "Message can contain A.B qualifications", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1, descriptor2, descriptor3, descriptor4) - End Get - End Property + Private Shared ReadOnly descriptor4 As DiagnosticDescriptor = {|#3:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "Message can contain 'A.B' qualifications", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1, descriptor2, descriptor3, descriptor4) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """, GetRS1007ExpectedDiagnostic(0), GetRS1007ExpectedDiagnostic(1), GetRS1007ExpectedDiagnostic(2), @@ -3375,78 +3523,84 @@ public async Task RS1032_LeadingOrTrailingWhitespaces_DiagnosticAsync( async Task VerifyMessageAsync(string message, string fixedMessage) { string additionalFileName = "Resources.resx"; - string additionalFileTextFormat = @" - - - {0} - Optional comment. - -"; - - string csharpSourceFormat = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -class Resources -{{ - public static LocalizableResourceString CreateLocalizableResourceString(string resourceName) => default; - public static string AnalyzerMessage => default; -}} - -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -public sealed class MyAnalyzer : DiagnosticAnalyzer -{{ - private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( - ""RuleId"", ""Title"", {0}, ""Category"", DiagnosticSeverity.Warning, true, ""Description."", ""HelpLinkUri"", ""Tags""); - {1} - public override ImmutableArray SupportedDiagnostics {{ get; }} = ImmutableArray.Create(Rule); - public override void Initialize(AnalysisContext context) {{ }} -}}"; + string additionalFileTextFormat = """ + + + + {0} + Optional comment. + + + """; + + string csharpSourceFormat = """ + + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + class Resources + {{ + public static LocalizableResourceString CreateLocalizableResourceString(string resourceName) => default; + public static string AnalyzerMessage => default; + }} + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + public sealed class MyAnalyzer : DiagnosticAnalyzer + {{ + private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( + "RuleId", "Title", {0}, "Category", DiagnosticSeverity.Warning, true, "Description.", "HelpLinkUri", "Tags"); + {1} + public override ImmutableArray SupportedDiagnostics {{ get; }} = ImmutableArray.Create(Rule); + public override void Initialize(AnalysisContext context) {{ }} + }} + """; await VerifyCSharpCodeFixAsync( source: string.Format(csharpSourceFormat, $"{{|#0:{csharpMessageExpression}|}}", csharpFieldDeclaration), fixedSource: string.Format(csharpSourceFormat, csharpMessageExpression, csharpFieldDeclaration), additionalFileName: additionalFileName, additionalFileText: string.Format(additionalFileTextFormat, message), fixedAdditionalFileText: string.Format(additionalFileTextFormat, fixedMessage), - expected: new[] - { + expected: + [ VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticMessageCorrectlyRule).WithLocation(0) - }); - - string basicSourceFormat = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - -Class Resources - Public Shared Function CreateLocalizableResourceString(resourceName As String) As LocalizableResourceString - Return Nothing - End Function - Public Shared ReadOnly Property AnalyzerMessage As String = Nothing -End Class - - -Public NotInheritable Class MyAnalyzer : Inherits DiagnosticAnalyzer - Private Shared Rule As DiagnosticDescriptor = New DiagnosticDescriptor( - ""RuleId"", ""Title"", {0}, ""Category"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUri"", ""Tags"") - {1} - Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) = ImmutableArray.Create(Rule) - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class"; + ]); + + string basicSourceFormat = """ + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + Class Resources + Public Shared Function CreateLocalizableResourceString(resourceName As String) As LocalizableResourceString + Return Nothing + End Function + Public Shared ReadOnly Property AnalyzerMessage As String = Nothing + End Class + + + Public NotInheritable Class MyAnalyzer : Inherits DiagnosticAnalyzer + Private Shared Rule As DiagnosticDescriptor = New DiagnosticDescriptor( + "RuleId", "Title", {0}, "Category", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUri", "Tags") + {1} + Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) = ImmutableArray.Create(Rule) + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + """; await VerifyBasicCodeFixAsync( source: string.Format(basicSourceFormat, $"{{|#0:{basicMessageExpression}|}}", basicFieldDeclaration), fixedSource: string.Format(basicSourceFormat, basicMessageExpression, basicFieldDeclaration), additionalFileName: additionalFileName, additionalFileText: string.Format(additionalFileTextFormat, message), fixedAdditionalFileText: string.Format(additionalFileTextFormat, fixedMessage), - expected: new[] - { + expected: + [ VerifyVB.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticMessageCorrectlyRule).WithLocation(0) - }); + ]); } } @@ -3457,111 +3611,119 @@ await VerifyBasicCodeFixAsync( [WindowsOnlyFact, WorkItem(3577, "https://github.com/dotnet/roslyn-analyzers/issues/3577")] public async Task RS1033_DescriptionStringDoesNotEndWithPunctuation_DiagnosticAsync() { - await VerifyCSharpCodeFixAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpCodeFixAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, {|#1:description: {|#2:""MyDiagnosticDescription""|}|}, helpLinkUri: ""HelpLink"", customTags: """")|}; - private static readonly DiagnosticDescriptor descriptor2 = - {|#3:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, {|#4:description: Description|}, helpLinkUri: ""HelpLink"", customTags: """")|}; - private const string Description = {|#5:""MyDiagnosticDescription""|}; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1, descriptor2); - } - } + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, {|#1:description: {|#2:"MyDiagnosticDescription"|}|}, helpLinkUri: "HelpLink", customTags: "")|}; + private static readonly DiagnosticDescriptor descriptor2 = + {|#3:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, {|#4:description: Description|}, helpLinkUri: "HelpLink", customTags: "")|}; + private const string Description = {|#5:"MyDiagnosticDescription"|}; - public override void Initialize(AnalysisContext context) - { - } -}", @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1, descriptor2); + } + } -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: ""MyDiagnosticDescription."", helpLinkUri: ""HelpLink"", customTags: """")|}; - private static readonly DiagnosticDescriptor descriptor2 = - {|#3:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description, helpLinkUri: ""HelpLink"", customTags: """")|}; - private const string Description = ""MyDiagnosticDescription.""; + public override void Initialize(AnalysisContext context) + { + } + } + """, """ - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1, descriptor2); - } - } + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override void Initialize(AnalysisContext context) - { - } -}", + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: "MyDiagnosticDescription.", helpLinkUri: "HelpLink", customTags: "")|}; + private static readonly DiagnosticDescriptor descriptor2 = + {|#3:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description, helpLinkUri: "HelpLink", customTags: "")|}; + private const string Description = "MyDiagnosticDescription."; + + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1, descriptor2); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """, GetRS1007ExpectedDiagnostic(0), VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticDescriptionCorrectlyRule).WithLocation(1).WithLocation(2), GetRS1007ExpectedDiagnostic(3), VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticDescriptionCorrectlyRule).WithLocation(4).WithLocation(5)); - await VerifyBasicCodeFixAsync(@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, {|#1:""Description""|}, ""HelpLinkUrl"", ""Tag"")|} - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, {|#3:Description|}, ""HelpLinkUrl"", ""Tag"")|} - Private Const Description As String = {|#4:""Description""|} - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, Description, ""HelpLinkUrl"", ""Tag"")|} - Private Const Description As String = ""Description."" - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", + await VerifyBasicCodeFixAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, {|#1:"Description"|}, "HelpLinkUrl", "Tag")|} + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, {|#3:Description|}, "HelpLinkUrl", "Tag")|} + Private Const Description As String = {|#4:"Description"|} + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """, """ + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, Description, "HelpLinkUrl", "Tag")|} + Private Const Description As String = "Description." + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """, GetRS1007ExpectedDiagnostic(0), VerifyVB.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticDescriptionCorrectlyRule).WithLocation(1).WithLocation(1), GetRS1007ExpectedDiagnostic(2), @@ -3598,151 +3760,161 @@ public async Task RS1033_DescriptionStringDoesNotEndWithPunctuation_ResxFile_Dia async Task VerifyDescriptionAsync(string description, string fixedDescription) { string additionalFileName = "Resources.resx"; - string additionalFileTextFormat = @" - - - {0} - Optional comment. - -"; - - string csharpSourceFormat = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -class Resources -{{ - public static LocalizableResourceString CreateLocalizableResourceString(string resourceName) => default; - public static string AnalyzerDescription => default; -}} - -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -public sealed class MyAnalyzer : DiagnosticAnalyzer -{{ - private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( - ""RuleId"", ""Title"", ""Message"", ""Category"", DiagnosticSeverity.Warning, true, {0}, ""HelpLinkUri"", ""Tags""); - {1} - public override ImmutableArray SupportedDiagnostics {{ get; }} = ImmutableArray.Create(Rule); - public override void Initialize(AnalysisContext context) {{ }} -}}"; + string additionalFileTextFormat = """ + + + + {0} + Optional comment. + + + """; + + string csharpSourceFormat = """ + + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + class Resources + {{ + public static LocalizableResourceString CreateLocalizableResourceString(string resourceName) => default; + public static string AnalyzerDescription => default; + }} + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + public sealed class MyAnalyzer : DiagnosticAnalyzer + {{ + private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( + "RuleId", "Title", "Message", "Category", DiagnosticSeverity.Warning, true, {0}, "HelpLinkUri", "Tags"); + {1} + public override ImmutableArray SupportedDiagnostics {{ get; }} = ImmutableArray.Create(Rule); + public override void Initialize(AnalysisContext context) {{ }} + }} + """; await VerifyCSharpCodeFixAsync( source: string.Format(csharpSourceFormat, $"{{|#0:{csharpDescriptionExpression}|}}", csharpFieldDeclaration), fixedSource: string.Format(csharpSourceFormat, csharpDescriptionExpression, csharpFieldDeclaration), additionalFileName: additionalFileName, additionalFileText: string.Format(additionalFileTextFormat, description), fixedAdditionalFileText: string.Format(additionalFileTextFormat, fixedDescription), - expected: new[] - { + expected: + [ VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticDescriptionCorrectlyRule).WithLocation(0) - }); - - string basicSourceFormat = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - -Class Resources - Public Shared Function CreateLocalizableResourceString(resourceName As String) As LocalizableResourceString - Return Nothing - End Function - Public Shared ReadOnly Property AnalyzerDescription As String = Nothing -End Class - - -Public NotInheritable Class MyAnalyzer : Inherits DiagnosticAnalyzer - Private Shared Rule As DiagnosticDescriptor = New DiagnosticDescriptor( - ""RuleId"", ""Title"", ""Message"", ""Category"", DiagnosticSeverity.Warning, True, {0}, ""HelpLinkUri"", ""Tags"") - {1} - Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) = ImmutableArray.Create(Rule) - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class"; + ]); + + string basicSourceFormat = """ + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + Class Resources + Public Shared Function CreateLocalizableResourceString(resourceName As String) As LocalizableResourceString + Return Nothing + End Function + Public Shared ReadOnly Property AnalyzerDescription As String = Nothing + End Class + + + Public NotInheritable Class MyAnalyzer : Inherits DiagnosticAnalyzer + Private Shared Rule As DiagnosticDescriptor = New DiagnosticDescriptor( + "RuleId", "Title", "Message", "Category", DiagnosticSeverity.Warning, True, {0}, "HelpLinkUri", "Tags") + {1} + Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) = ImmutableArray.Create(Rule) + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + """; await VerifyBasicCodeFixAsync( source: string.Format(basicSourceFormat, $"{{|#0:{basicDescriptionExpression}|}}", basicFieldDeclaration), fixedSource: string.Format(basicSourceFormat, basicDescriptionExpression, basicFieldDeclaration), additionalFileName: additionalFileName, additionalFileText: string.Format(additionalFileTextFormat, description), fixedAdditionalFileText: string.Format(additionalFileTextFormat, fixedDescription), - expected: new[] - { + expected: + [ VerifyVB.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticDescriptionCorrectlyRule).WithLocation(0) - }); + ]); } } [WindowsOnlyFact, WorkItem(3577, "https://github.com/dotnet/roslyn-analyzers/issues/3577")] public async Task RS1033_DescriptionEndsWithPunctuation_NoDiagnosticAsync() { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpAnalyzerAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, - description: ""MyDiagnosticDescription."", helpLinkUri: ""HelpLink"", customTags: """")|}; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - private static readonly DiagnosticDescriptor descriptor2 = - {|#1:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, - description: ""MyDiagnosticDescription!"", helpLinkUri: ""HelpLink"", customTags: """")|}; + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, + description: "MyDiagnosticDescription.", helpLinkUri: "HelpLink", customTags: "")|}; - private static readonly DiagnosticDescriptor descriptor3 = - {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, - description: ""MyDiagnosticDescription?"", helpLinkUri: ""HelpLink"", customTags: """")|}; + private static readonly DiagnosticDescriptor descriptor2 = + {|#1:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, + description: "MyDiagnosticDescription!", helpLinkUri: "HelpLink", customTags: "")|}; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1, descriptor2, descriptor3); - } - } + private static readonly DiagnosticDescriptor descriptor3 = + {|#2:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, + description: "MyDiagnosticDescription?", helpLinkUri: "HelpLink", customTags: "")|}; - public override void Initialize(AnalysisContext context) - { - } -}", + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1, descriptor2, descriptor3); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """, GetRS1007ExpectedDiagnostic(0), GetRS1007ExpectedDiagnostic(1), GetRS1007ExpectedDiagnostic(2)); - await VerifyBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.VisualBasic + await VerifyBasicAnalyzerAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.VisualBasic - -Class MyAnalyzer - Inherits DiagnosticAnalyzer + + Class MyAnalyzer + Inherits DiagnosticAnalyzer - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", - DiagnosticSeverity.Warning, True, ""Description."", ""HelpLinkUrl"", ""Tag"")|} + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", + DiagnosticSeverity.Warning, True, "Description.", "HelpLinkUrl", "Tag")|} - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#1:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", - DiagnosticSeverity.Warning, True, ""Description!"", ""HelpLinkUrl"", ""Tag"")|} + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#1:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", + DiagnosticSeverity.Warning, True, "Description!", "HelpLinkUrl", "Tag")|} - Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", - DiagnosticSeverity.Warning, True, ""Description?"", ""HelpLinkUrl"", ""Tag"")|} + Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", + DiagnosticSeverity.Warning, True, "Description?", "HelpLinkUrl", "Tag")|} - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1, descriptor2, descriptor3) - End Get - End Property + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1, descriptor2, descriptor3) + End Get + End Property - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -", + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """, GetRS1007ExpectedDiagnostic(0), GetRS1007ExpectedDiagnostic(1), GetRS1007ExpectedDiagnostic(2)); @@ -3780,78 +3952,84 @@ public async Task RS1033_LeadingOrTrailingWhitespaces_DiagnosticAsync( async Task VerifyDescriptionAsync(string description, string fixedDescription) { string additionalFileName = "Resources.resx"; - string additionalFileTextFormat = @" - - - {0} - Optional comment. - -"; - - string csharpSourceFormat = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -class Resources -{{ - public static LocalizableResourceString CreateLocalizableResourceString(string resourceName) => default; - public static string AnalyzerDescription => default; -}} - -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -public sealed class MyAnalyzer : DiagnosticAnalyzer -{{ - private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( - ""RuleId"", ""Title"", ""Message"", ""Category"", DiagnosticSeverity.Warning, true, {0}, ""HelpLinkUri"", ""Tags""); - {1} - public override ImmutableArray SupportedDiagnostics {{ get; }} = ImmutableArray.Create(Rule); - public override void Initialize(AnalysisContext context) {{ }} -}}"; + string additionalFileTextFormat = """ + + + + {0} + Optional comment. + + + """; + + string csharpSourceFormat = """ + + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + class Resources + {{ + public static LocalizableResourceString CreateLocalizableResourceString(string resourceName) => default; + public static string AnalyzerDescription => default; + }} + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + public sealed class MyAnalyzer : DiagnosticAnalyzer + {{ + private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( + "RuleId", "Title", "Message", "Category", DiagnosticSeverity.Warning, true, {0}, "HelpLinkUri", "Tags"); + {1} + public override ImmutableArray SupportedDiagnostics {{ get; }} = ImmutableArray.Create(Rule); + public override void Initialize(AnalysisContext context) {{ }} + }} + """; await VerifyCSharpCodeFixAsync( source: string.Format(csharpSourceFormat, $"{{|#0:{csharpDescriptionExpression}|}}", csharpFieldDeclaration), fixedSource: string.Format(csharpSourceFormat, csharpDescriptionExpression, csharpFieldDeclaration), additionalFileName: additionalFileName, additionalFileText: string.Format(additionalFileTextFormat, description), fixedAdditionalFileText: string.Format(additionalFileTextFormat, fixedDescription), - expected: new[] - { + expected: + [ VerifyCS.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticDescriptionCorrectlyRule).WithLocation(0) - }); - - string basicSourceFormat = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - -Class Resources - Public Shared Function CreateLocalizableResourceString(resourceName As String) As LocalizableResourceString - Return Nothing - End Function - Public Shared ReadOnly Property AnalyzerDescription As String = Nothing -End Class - - -Public NotInheritable Class MyAnalyzer : Inherits DiagnosticAnalyzer - Private Shared Rule As DiagnosticDescriptor = New DiagnosticDescriptor( - ""RuleId"", ""Title"", ""Message"", ""Category"", DiagnosticSeverity.Warning, True, {0}, ""HelpLinkUri"", ""Tags"") - {1} - Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) = ImmutableArray.Create(Rule) - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class"; + ]); + + string basicSourceFormat = """ + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + Class Resources + Public Shared Function CreateLocalizableResourceString(resourceName As String) As LocalizableResourceString + Return Nothing + End Function + Public Shared ReadOnly Property AnalyzerDescription As String = Nothing + End Class + + + Public NotInheritable Class MyAnalyzer : Inherits DiagnosticAnalyzer + Private Shared Rule As DiagnosticDescriptor = New DiagnosticDescriptor( + "RuleId", "Title", "Message", "Category", DiagnosticSeverity.Warning, True, {0}, "HelpLinkUri", "Tags") + {1} + Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) = ImmutableArray.Create(Rule) + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + """; await VerifyBasicCodeFixAsync( source: string.Format(basicSourceFormat, $"{{|#0:{basicDescriptionExpression}|}}", basicFieldDeclaration), fixedSource: string.Format(basicSourceFormat, basicDescriptionExpression, basicFieldDeclaration), additionalFileName: additionalFileName, additionalFileText: string.Format(additionalFileTextFormat, description), fixedAdditionalFileText: string.Format(additionalFileTextFormat, fixedDescription), - expected: new[] - { + expected: + [ VerifyVB.Diagnostic(DiagnosticDescriptorCreationAnalyzer.DefineDiagnosticDescriptionCorrectlyRule).WithLocation(0) - }); + ]); } } @@ -3861,209 +4039,221 @@ await VerifyBasicCodeFixAsync( [Fact, WorkItem(6282, "https://github.com/dotnet/roslyn-analyzers/issues/6282")] public async Task RS1037_WithRequiredCustomTag_NoDiagnostic() { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpAnalyzerAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: ""CompilationEnd"")|}; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1); - } - } + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "CompilationEnd")|}; - public override void Initialize(AnalysisContext context) - { - context.RegisterCompilationStartAction(compilationStartAnalysisContext => - { - compilationStartAnalysisContext.RegisterCompilationEndAction(compilationEndAnalysisContext => - { - compilationEndAnalysisContext.ReportDiagnostic(Diagnostic.Create(descriptor1, Location.None)); - }); - }); - } -}", + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1); + } + } + + public override void Initialize(AnalysisContext context) + { + context.RegisterCompilationStartAction(compilationStartAnalysisContext => + { + compilationStartAnalysisContext.RegisterCompilationEndAction(compilationEndAnalysisContext => + { + compilationEndAnalysisContext.ReportDiagnostic(Diagnostic.Create(descriptor1, Location.None)); + }); + }); + } + } + """, GetRS1007ExpectedDiagnostic(0)); - await VerifyBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, description:=Nothing, helpLinkUri:=""HelpLinkUrl"", ""CompilationEnd"")|} - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - context.RegisterCompilationStartAction(Function(compilationStartAnalysisContext) - compilationStartAnalysisContext.RegisterCompilationEndAction(Function(compilationEndAnalysisContext) - compilationEndAnalysisContext.ReportDiagnostic(Diagnostic.Create(descriptor1, Location.None)) - End Function) - End Function) - End Sub -End Class -", + await VerifyBasicAnalyzerAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, description:=Nothing, helpLinkUri:="HelpLinkUrl", "CompilationEnd")|} + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + context.RegisterCompilationStartAction(Function(compilationStartAnalysisContext) + compilationStartAnalysisContext.RegisterCompilationEndAction(Function(compilationEndAnalysisContext) + compilationEndAnalysisContext.ReportDiagnostic(Diagnostic.Create(descriptor1, Location.None)) + End Function) + End Function) + End Sub + End Class + + """, GetRS1007ExpectedDiagnostic(0)); } [Fact, WorkItem(6282, "https://github.com/dotnet/roslyn-analyzers/issues/6282")] public async Task RS1037_NonInlinedCustomTags_NoDiagnostic() { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpAnalyzerAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: tags)|}; - private static readonly string[] tags = new string[] { """" }; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1); - } - } + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: tags)|}; + private static readonly string[] tags = new string[] { "" }; - public override void Initialize(AnalysisContext context) - { - context.RegisterCompilationStartAction(compilationStartAnalysisContext => - { - compilationStartAnalysisContext.RegisterCompilationEndAction(compilationEndAnalysisContext => - { - compilationEndAnalysisContext.ReportDiagnostic(Diagnostic.Create(descriptor1, Location.None)); - }); - }); - } -}", + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1); + } + } + + public override void Initialize(AnalysisContext context) + { + context.RegisterCompilationStartAction(compilationStartAnalysisContext => + { + compilationStartAnalysisContext.RegisterCompilationEndAction(compilationEndAnalysisContext => + { + compilationEndAnalysisContext.ReportDiagnostic(Diagnostic.Create(descriptor1, Location.None)); + }); + }); + } + } + """, GetRS1007ExpectedDiagnostic(0)); - await VerifyBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, description:=Nothing, helpLinkUri:=""HelpLinkUrl"", Tags)|} - Private Shared ReadOnly Tags As String() = { """" } - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - context.RegisterCompilationStartAction(Function(compilationStartAnalysisContext) - compilationStartAnalysisContext.RegisterCompilationEndAction(Function(compilationEndAnalysisContext) - compilationEndAnalysisContext.ReportDiagnostic(Diagnostic.Create(descriptor1, Location.None)) - End Function) - End Function) - End Sub -End Class -", + await VerifyBasicAnalyzerAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = {|#0:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, description:=Nothing, helpLinkUri:="HelpLinkUrl", Tags)|} + Private Shared ReadOnly Tags As String() = { "" } + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + context.RegisterCompilationStartAction(Function(compilationStartAnalysisContext) + compilationStartAnalysisContext.RegisterCompilationEndAction(Function(compilationEndAnalysisContext) + compilationEndAnalysisContext.ReportDiagnostic(Diagnostic.Create(descriptor1, Location.None)) + End Function) + End Function) + End Sub + End Class + + """, GetRS1007ExpectedDiagnostic(0)); } [Fact, WorkItem(6282, "https://github.com/dotnet/roslyn-analyzers/issues/6282")] public async Task RS1037_WithoutRequiredCustomTag_Diagnostic() { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpAnalyzerAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor {|#0:descriptor1|} = - {|#1:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; - private static readonly DiagnosticDescriptor descriptor2 = - {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1, descriptor2); - } - } + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor {|#0:descriptor1|} = + {|#1:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; + private static readonly DiagnosticDescriptor descriptor2 = + {|#2:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - public override void Initialize(AnalysisContext context) - { - context.RegisterCompilationStartAction(compilationStartAnalysisContext => - { - compilationStartAnalysisContext.RegisterCompilationEndAction(compilationEndAnalysisContext => - { - compilationEndAnalysisContext.ReportDiagnostic(Diagnostic.Create(descriptor1, Location.None)); + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1, descriptor2); + } + } - var diag2 = Diagnostic.Create(descriptor2, Location.None); - }); - }); - } -}", + public override void Initialize(AnalysisContext context) + { + context.RegisterCompilationStartAction(compilationStartAnalysisContext => + { + compilationStartAnalysisContext.RegisterCompilationEndAction(compilationEndAnalysisContext => + { + compilationEndAnalysisContext.ReportDiagnostic(Diagnostic.Create(descriptor1, Location.None)); + + var diag2 = Diagnostic.Create(descriptor2, Location.None); + }); + }); + } + } + """, GetRS1037ExpectedDiagnostic(0, "descriptor1"), GetRS1007ExpectedDiagnostic(1), GetRS1007ExpectedDiagnostic(2)); - await VerifyBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly {|#0:descriptor1|} As DiagnosticDescriptor = {|#1:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, description:=Nothing, helpLinkUri:=""HelpLinkUrl"", ""Tag"")|} - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, description:=Nothing, helpLinkUri:=""HelpLinkUrl"", ""Tag"")|} - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1, descriptor2) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - context.RegisterCompilationStartAction(Function(compilationStartAnalysisContext) - compilationStartAnalysisContext.RegisterCompilationEndAction(Function(compilationEndAnalysisContext) - compilationEndAnalysisContext.ReportDiagnostic(Diagnostic.Create(descriptor1, Location.None)) - - Dim diag2 = Diagnostic.Create(descriptor2, Location.None) - End Function) - End Function) - End Sub -End Class -", + await VerifyBasicAnalyzerAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly {|#0:descriptor1|} As DiagnosticDescriptor = {|#1:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, description:=Nothing, helpLinkUri:="HelpLinkUrl", "Tag")|} + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, description:=Nothing, helpLinkUri:="HelpLinkUrl", "Tag")|} + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1, descriptor2) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + context.RegisterCompilationStartAction(Function(compilationStartAnalysisContext) + compilationStartAnalysisContext.RegisterCompilationEndAction(Function(compilationEndAnalysisContext) + compilationEndAnalysisContext.ReportDiagnostic(Diagnostic.Create(descriptor1, Location.None)) + + Dim diag2 = Diagnostic.Create(descriptor2, Location.None) + End Function) + End Function) + End Sub + End Class + + """, GetRS1037ExpectedDiagnostic(0, "descriptor1"), GetRS1007ExpectedDiagnostic(1), GetRS1007ExpectedDiagnostic(2)); @@ -4072,77 +4262,81 @@ End Class [Fact, WorkItem(6282, "https://github.com/dotnet/roslyn-analyzers/issues/6282")] public async Task RS1037_DiagnosticStoredInLocal_WithInitializer_Diagnostic() { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpAnalyzerAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor {|#0:descriptor1|} = - {|#1:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; - private static readonly DiagnosticDescriptor descriptor2 = - {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1, descriptor2); - } - } + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor {|#0:descriptor1|} = + {|#1:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; + private static readonly DiagnosticDescriptor descriptor2 = + {|#2:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - public override void Initialize(AnalysisContext context) - { - context.RegisterCompilationStartAction(compilationStartAnalysisContext => - { - compilationStartAnalysisContext.RegisterCompilationEndAction(compilationEndAnalysisContext => - { - var diag1 = Diagnostic.Create(descriptor1, Location.None); - compilationEndAnalysisContext.ReportDiagnostic(diag1); + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1, descriptor2); + } + } - var diag2 = Diagnostic.Create(descriptor2, Location.None); - }); - }); - } -}", + public override void Initialize(AnalysisContext context) + { + context.RegisterCompilationStartAction(compilationStartAnalysisContext => + { + compilationStartAnalysisContext.RegisterCompilationEndAction(compilationEndAnalysisContext => + { + var diag1 = Diagnostic.Create(descriptor1, Location.None); + compilationEndAnalysisContext.ReportDiagnostic(diag1); + + var diag2 = Diagnostic.Create(descriptor2, Location.None); + }); + }); + } + } + """, GetRS1037ExpectedDiagnostic(0, "descriptor1"), GetRS1007ExpectedDiagnostic(1), GetRS1007ExpectedDiagnostic(2)); - await VerifyBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly {|#0:descriptor1|} As DiagnosticDescriptor = {|#1:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, description:=Nothing, helpLinkUri:=""HelpLinkUrl"", ""Tag"")|} - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, description:=Nothing, helpLinkUri:=""HelpLinkUrl"", ""Tag"")|} - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1, descriptor2) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - context.RegisterCompilationStartAction(Function(compilationStartAnalysisContext) - compilationStartAnalysisContext.RegisterCompilationEndAction(Function(compilationEndAnalysisContext) - Dim diag1 = Diagnostic.Create(descriptor1, Location.None) - compilationEndAnalysisContext.ReportDiagnostic(diag1) - - Dim diag2 = Diagnostic.Create(descriptor2, Location.None) - End Function) - End Function) - End Sub -End Class -", + await VerifyBasicAnalyzerAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly {|#0:descriptor1|} As DiagnosticDescriptor = {|#1:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, description:=Nothing, helpLinkUri:="HelpLinkUrl", "Tag")|} + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = {|#2:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, description:=Nothing, helpLinkUri:="HelpLinkUrl", "Tag")|} + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1, descriptor2) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + context.RegisterCompilationStartAction(Function(compilationStartAnalysisContext) + compilationStartAnalysisContext.RegisterCompilationEndAction(Function(compilationEndAnalysisContext) + Dim diag1 = Diagnostic.Create(descriptor1, Location.None) + compilationEndAnalysisContext.ReportDiagnostic(diag1) + + Dim diag2 = Diagnostic.Create(descriptor2, Location.None) + End Function) + End Function) + End Sub + End Class + + """, GetRS1037ExpectedDiagnostic(0, "descriptor1"), GetRS1007ExpectedDiagnostic(1), GetRS1007ExpectedDiagnostic(2)); @@ -4151,80 +4345,84 @@ End Class [Fact, WorkItem(6282, "https://github.com/dotnet/roslyn-analyzers/issues/6282")] public async Task RS1037_DiagnosticStoredInLocal_WithAssignment_Diagnostic() { - await VerifyCSharpAnalyzerAsync(@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpAnalyzerAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor {|#0:descriptor1|} = - {|#1:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; - private static readonly DiagnosticDescriptor {|#2:descriptor2|} = - {|#3:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1, descriptor2); - } - } + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor {|#0:descriptor1|} = + {|#1:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; + private static readonly DiagnosticDescriptor {|#2:descriptor2|} = + {|#3:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - public override void Initialize(AnalysisContext context) - { - context.RegisterCompilationStartAction(compilationStartAnalysisContext => - { - compilationStartAnalysisContext.RegisterCompilationEndAction(compilationEndAnalysisContext => - { - var diag = Diagnostic.Create(descriptor1, Location.None); - compilationEndAnalysisContext.ReportDiagnostic(diag); + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1, descriptor2); + } + } - diag = Diagnostic.Create(descriptor2, Location.None); - compilationEndAnalysisContext.ReportDiagnostic(diag); - }); - }); - } -}", + public override void Initialize(AnalysisContext context) + { + context.RegisterCompilationStartAction(compilationStartAnalysisContext => + { + compilationStartAnalysisContext.RegisterCompilationEndAction(compilationEndAnalysisContext => + { + var diag = Diagnostic.Create(descriptor1, Location.None); + compilationEndAnalysisContext.ReportDiagnostic(diag); + + diag = Diagnostic.Create(descriptor2, Location.None); + compilationEndAnalysisContext.ReportDiagnostic(diag); + }); + }); + } + } + """, GetRS1037ExpectedDiagnostic(0, "descriptor1"), GetRS1007ExpectedDiagnostic(1), GetRS1037ExpectedDiagnostic(2, "descriptor2"), GetRS1007ExpectedDiagnostic(3)); - await VerifyBasicAnalyzerAsync(@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly {|#0:descriptor1|} As DiagnosticDescriptor = {|#1:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, description:=Nothing, helpLinkUri:=""HelpLinkUrl"", ""Tag"")|} - Private Shared ReadOnly {|#2:descriptor2|} As DiagnosticDescriptor = {|#3:new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, description:=Nothing, helpLinkUri:=""HelpLinkUrl"", ""Tag"")|} - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1, descriptor2) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - context.RegisterCompilationStartAction(Function(compilationStartAnalysisContext) - compilationStartAnalysisContext.RegisterCompilationEndAction(Function(compilationEndAnalysisContext) - Dim diag = Diagnostic.Create(descriptor1, Location.None) - compilationEndAnalysisContext.ReportDiagnostic(diag) - - diag = Diagnostic.Create(descriptor2, Location.None) - compilationEndAnalysisContext.ReportDiagnostic(diag) - End Function) - End Function) - End Sub -End Class -", + await VerifyBasicAnalyzerAsync(""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly {|#0:descriptor1|} As DiagnosticDescriptor = {|#1:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, description:=Nothing, helpLinkUri:="HelpLinkUrl", "Tag")|} + Private Shared ReadOnly {|#2:descriptor2|} As DiagnosticDescriptor = {|#3:new DiagnosticDescriptor("MyDiagnosticId", "MyDiagnosticTitle", "MyDiagnosticMessage", "MyDiagnosticCategory", DiagnosticSeverity.Warning, True, description:=Nothing, helpLinkUri:="HelpLinkUrl", "Tag")|} + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1, descriptor2) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + context.RegisterCompilationStartAction(Function(compilationStartAnalysisContext) + compilationStartAnalysisContext.RegisterCompilationEndAction(Function(compilationEndAnalysisContext) + Dim diag = Diagnostic.Create(descriptor1, Location.None) + compilationEndAnalysisContext.ReportDiagnostic(diag) + + diag = Diagnostic.Create(descriptor2, Location.None) + compilationEndAnalysisContext.ReportDiagnostic(diag) + End Function) + End Function) + End Sub + End Class + + """, GetRS1037ExpectedDiagnostic(0, "descriptor1"), GetRS1007ExpectedDiagnostic(1), GetRS1037ExpectedDiagnostic(2, "descriptor2"), @@ -4236,39 +4434,43 @@ End Class [Fact, WorkItem(6035, "https://github.com/dotnet/roslyn-analyzers/issues/6035")] public async Task VerifyFieldReferenceForFieldDefinedInSeparateFile() { - var file1 = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + var file1 = """ -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor = - {|#0:new DiagnosticDescriptor(HelperType.Id, HelperType.Title, HelperType.Message, HelperType.Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink"", customTags: """")|}; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor); - } - } + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor = + {|#0:new DiagnosticDescriptor(HelperType.Id, HelperType.Title, HelperType.Message, HelperType.Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "HelpLink", customTags: "")|}; - public override void Initialize(AnalysisContext context) - { - } -}"; + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor); + } + } - var file2 = @" -public class HelperType -{ - public const string Id = ""Id""; - public const string Title = ""Title""; - public const string Message = ""Message""; - public const string Category = ""Category""; -}"; + public override void Initialize(AnalysisContext context) + { + } + } + """; + + var file2 = """ + + public class HelperType + { + public const string Id = "Id"; + public const string Title = "Title"; + public const string Message = "Message"; + public const string Category = "Category"; + } + """; var expected = new[] { GetRS1007ExpectedDiagnostic(0) }; var test = new VerifyCS.Test @@ -4477,24 +4679,28 @@ private static Solution WithoutEnableReleaseTrackingWarning(Solution solution, P private const string AdditionalFileName = "DiagnosticCategoryAndIdRanges.txt"; - private const string CSharpDiagnosticDescriptorCreationHelper = @" -internal static class DiagnosticDescriptorHelper -{ - // Dummy DiagnosticDescriptor creation helper. - public static DiagnosticDescriptor Create( - string id, - LocalizableString title, - LocalizableString messageFormat, - string category) - => null; -}"; - private const string VisualBasicDiagnosticDescriptorCreationHelper = @" -Friend Partial Module DiagnosticDescriptorHelper - ' Dummy DiagnosticDescriptor creation helper. - Function Create(id As String, title As LocalizableString, messageFormat As LocalizableString, category As String) As DiagnosticDescriptor - Return Nothing - End Function -End Module"; + private const string CSharpDiagnosticDescriptorCreationHelper = """ + + internal static class DiagnosticDescriptorHelper + { + // Dummy DiagnosticDescriptor creation helper. + public static DiagnosticDescriptor Create( + string id, + LocalizableString title, + LocalizableString messageFormat, + string category) + => null; + } + """; + private const string VisualBasicDiagnosticDescriptorCreationHelper = """ + + Friend Partial Module DiagnosticDescriptorHelper + ' Dummy DiagnosticDescriptor creation helper. + Function Create(id As String, title As LocalizableString, messageFormat As LocalizableString, category As String) As DiagnosticDescriptor + Return Nothing + End Function + End Module + """; #endregion } diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DoNotStorePerCompilationDataOntoFieldsRuleTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DoNotStorePerCompilationDataOntoFieldsRuleTests.cs index 9a31dc99e1926..0bf8b2ab5ccfa 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DoNotStorePerCompilationDataOntoFieldsRuleTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DoNotStorePerCompilationDataOntoFieldsRuleTests.cs @@ -23,46 +23,8 @@ public class DoNotStorePerCompilationDataOntoFieldsRuleTests [Fact, WorkItem(7196, "https://github.com/dotnet/roslyn-analyzers/issues/7196")] public async Task CSharp_VerifyDiagnosticAsync() { - var source = @" -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Operations; -using MyNamedType = Microsoft.CodeAnalysis.INamedTypeSymbol; - -abstract class {|CS1729:MyCompilation|} : Compilation -{ - // Compile error: no public constructor exists on Compilation. -} - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly ITypeSymbol x1; - public static readonly CSharpCompilation x2; - private readonly List x3; - private static Dictionary x4; - private static readonly IBinaryOperation x5; - private static readonly ISymbol x6; - private static readonly IOperation x7; - - public override ImmutableArray SupportedDiagnostics - { - get - { - throw new NotImplementedException(); - } - } - - public override void Initialize(AnalysisContext context) - { - } -}"; - DiagnosticResult[] expected = new[] - { + DiagnosticResult[] expected = + [ GetCSharpExpectedDiagnostic(19, 29, violatingTypeName: typeof(ITypeSymbol).FullName), GetCSharpExpectedDiagnostic(20, 28, violatingTypeName: typeof(CSharpCompilation).FullName), GetCSharpExpectedDiagnostic(21, 27, violatingTypeName: typeof(INamedTypeSymbol).FullName), @@ -70,52 +32,55 @@ public override void Initialize(AnalysisContext context) GetCSharpExpectedDiagnostic(23, 29, violatingTypeName: typeof(IBinaryOperation).FullName), GetCSharpExpectedDiagnostic(24, 29, violatingTypeName: typeof(ISymbol).FullName), GetCSharpExpectedDiagnostic(25, 29, violatingTypeName: typeof(IOperation).FullName) - }; - - await VerifyCS.VerifyAnalyzerAsync(source, expected); + ]; + + await VerifyCS.VerifyAnalyzerAsync(""" + + using System; + using System.Collections.Generic; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + using Microsoft.CodeAnalysis.Operations; + using MyNamedType = Microsoft.CodeAnalysis.INamedTypeSymbol; + + abstract class {|CS1729:MyCompilation|} : Compilation + { + // Compile error: no public constructor exists on Compilation. + } + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly ITypeSymbol x1; + public static readonly CSharpCompilation x2; + private readonly List x3; + private static Dictionary x4; + private static readonly IBinaryOperation x5; + private static readonly ISymbol x6; + private static readonly IOperation x7; + + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """, expected); } [Fact, WorkItem(7196, "https://github.com/dotnet/roslyn-analyzers/issues/7196")] public async Task VisualBasic_VerifyDiagnosticAsync() { - var source = @" -Imports System -Imports System.Collections.Generic -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.Operations -Imports Microsoft.CodeAnalysis.VisualBasic -Imports MyNamedType = Microsoft.CodeAnalysis.INamedTypeSymbol - -MustInherit Class {|BC31399:MyCompilation|} - Inherits Compilation ' Compile error: no public constructor exists on Compilation. -End Class - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly x1 As ITypeSymbol - Public Shared ReadOnly x2 As VisualBasicCompilation - Private ReadOnly x3 As List(Of MyNamedType) - Private Shared x4 As Dictionary(Of MyCompilation, MyNamedType) - Private Shared ReadOnly x5 As IBinaryOperation - Private Shared ReadOnly x6 As ISymbol - Private Shared ReadOnly x7 As IOperation - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub -End Class -"; - DiagnosticResult[] expected = new[] - { + DiagnosticResult[] expected = + [ GetBasicExpectedDiagnostic(19, 35, violatingTypeName: typeof(ITypeSymbol).FullName), GetBasicExpectedDiagnostic(20, 34, violatingTypeName: typeof(VisualBasicCompilation).FullName), GetBasicExpectedDiagnostic(21, 36, violatingTypeName: typeof(INamedTypeSymbol).FullName), @@ -123,225 +88,264 @@ End Class GetBasicExpectedDiagnostic(23, 35, violatingTypeName: typeof(IBinaryOperation).FullName), GetBasicExpectedDiagnostic(24, 35, violatingTypeName: typeof(ISymbol).FullName), GetBasicExpectedDiagnostic(25, 35, violatingTypeName: typeof(IOperation).FullName) - }; - - await VerifyVB.VerifyAnalyzerAsync(source, expected); + ]; + + await VerifyVB.VerifyAnalyzerAsync(""" + + Imports System + Imports System.Collections.Generic + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.Operations + Imports Microsoft.CodeAnalysis.VisualBasic + Imports MyNamedType = Microsoft.CodeAnalysis.INamedTypeSymbol + + MustInherit Class {|BC31399:MyCompilation|} + Inherits Compilation ' Compile error: no public constructor exists on Compilation. + End Class + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly x1 As ITypeSymbol + Public Shared ReadOnly x2 As VisualBasicCompilation + Private ReadOnly x3 As List(Of MyNamedType) + Private Shared x4 As Dictionary(Of MyCompilation, MyNamedType) + Private Shared ReadOnly x5 As IBinaryOperation + Private Shared ReadOnly x6 As ISymbol + Private Shared ReadOnly x7 As IOperation + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + + """, expected); } [Fact] public async Task CSharp_NoDiagnosticCasesAsync() { - var source = @" -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; -using MyNamedType = Microsoft.CodeAnalysis.INamedTypeSymbol; - -abstract class {|CS1729:MyCompilation|} : Compilation -{ - // Compile error: no public constructor exists on Compilation. -} - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor x1; - private readonly List x2; - - public override ImmutableArray SupportedDiagnostics - { - get - { - throw new NotImplementedException(); - } - } - - public override void Initialize(AnalysisContext context) - { - var analyzer = new NestedCompilationAnalyzer(); - context.RegisterCompilationStartAction(analyzer.StartCompilation); - } - - private class NestedCompilationAnalyzer - { - // Ok to store per-compilation data here. - private readonly Dictionary x; - - internal void StartCompilation(CompilationStartAnalysisContext context) - { - } - } - - private struct NestedStructCompilationAnalyzer - { - // Ok to store per-compilation data here. - private readonly Dictionary y; - - internal void StartCompilation(CompilationStartAnalysisContext context) - { - } - } -} - -class MyAnalyzerWithoutAttribute : DiagnosticAnalyzer -{ - // Ok to store per-compilation data here. - private static ITypeSymbol x; - - public override ImmutableArray SupportedDiagnostics - { - get - { - throw new NotImplementedException(); - } - } - - public override void Initialize(AnalysisContext context) - { - throw new NotImplementedException(); - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(source); + await VerifyCS.VerifyAnalyzerAsync(""" + + using System; + using System.Collections.Generic; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + using MyNamedType = Microsoft.CodeAnalysis.INamedTypeSymbol; + + abstract class {|CS1729:MyCompilation|} : Compilation + { + // Compile error: no public constructor exists on Compilation. + } + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor x1; + private readonly List x2; + + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } + + public override void Initialize(AnalysisContext context) + { + var analyzer = new NestedCompilationAnalyzer(); + context.RegisterCompilationStartAction(analyzer.StartCompilation); + } + + private class NestedCompilationAnalyzer + { + // Ok to store per-compilation data here. + private readonly Dictionary x; + + internal void StartCompilation(CompilationStartAnalysisContext context) + { + } + } + + private struct NestedStructCompilationAnalyzer + { + // Ok to store per-compilation data here. + private readonly Dictionary y; + + internal void StartCompilation(CompilationStartAnalysisContext context) + { + } + } + } + + class MyAnalyzerWithoutAttribute : DiagnosticAnalyzer + { + // Ok to store per-compilation data here. + private static ITypeSymbol x; + + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } + + public override void Initialize(AnalysisContext context) + { + throw new NotImplementedException(); + } + } + """); } [Fact] public async Task VisualBasic_NoDiagnosticCasesAsync() { - var source = @" -Imports System -Imports System.Collections.Generic -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic -Imports MyNamedType = Microsoft.CodeAnalysis.INamedTypeSymbol - -MustInherit Class {|BC31399:MyCompilation|} - Inherits Compilation ' Compile error: no public constructor exists on Compilation. -End Class - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly x1 As DiagnosticDescriptor - Private ReadOnly x2 As List(Of LocalizableResourceString) - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - Dim compilationAnalyzer = New NestedCompilationAnalyzer - context.RegisterCompilationStartAction(AddressOf compilationAnalyzer.StartCompilation) - End Sub - - Class NestedCompilationAnalyzer - ' Ok to store per-compilation data here. - Private ReadOnly x As Dictionary(Of MyCompilation, MyNamedType) - - Friend Sub StartCompilation(context As CompilationStartAnalysisContext) - End Sub - End Class - - Structure NestedStructCompilationAnalyzer - ' Ok to store per-compilation data here. - Private ReadOnly y As Dictionary(Of MyCompilation, MyNamedType) - - Friend Sub StartCompilation(context As CompilationStartAnalysisContext) - End Sub - End Structure -End Class - -Class MyAnalyzerWithoutAttribute - Inherits DiagnosticAnalyzer - - ' Ok to store per-compilation data here. - Private Shared x As ITypeSymbol - - Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - Throw New NotImplementedException() - End Sub -End Class -"; - - await VerifyVB.VerifyAnalyzerAsync(source); + await VerifyVB.VerifyAnalyzerAsync(""" + + Imports System + Imports System.Collections.Generic + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.VisualBasic + Imports MyNamedType = Microsoft.CodeAnalysis.INamedTypeSymbol + + MustInherit Class {|BC31399:MyCompilation|} + Inherits Compilation ' Compile error: no public constructor exists on Compilation. + End Class + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly x1 As DiagnosticDescriptor + Private ReadOnly x2 As List(Of LocalizableResourceString) + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + Dim compilationAnalyzer = New NestedCompilationAnalyzer + context.RegisterCompilationStartAction(AddressOf compilationAnalyzer.StartCompilation) + End Sub + + Class NestedCompilationAnalyzer + ' Ok to store per-compilation data here. + Private ReadOnly x As Dictionary(Of MyCompilation, MyNamedType) + + Friend Sub StartCompilation(context As CompilationStartAnalysisContext) + End Sub + End Class + + Structure NestedStructCompilationAnalyzer + ' Ok to store per-compilation data here. + Private ReadOnly y As Dictionary(Of MyCompilation, MyNamedType) + + Friend Sub StartCompilation(context As CompilationStartAnalysisContext) + End Sub + End Structure + End Class + + Class MyAnalyzerWithoutAttribute + Inherits DiagnosticAnalyzer + + ' Ok to store per-compilation data here. + Private Shared x As ITypeSymbol + + Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + Throw New NotImplementedException() + End Sub + End Class + + """); } [Fact, WorkItem(4308, "https://github.com/dotnet/roslyn-analyzers/issues/4308")] public async Task CSharp_NestedStruct_NoDiagnosticAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Operations; - -namespace MyNamespace -{ - [DiagnosticAnalyzer(LanguageNames.CSharp)] - public class AnyInstanceInjectionAnalyzer : DiagnosticAnalyzer - { - public struct DependencyAccess - { - public IMethodSymbol method; - public string expectedName; - } - - public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); - - public override void Initialize(AnalysisContext context) - { - context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); - context.EnableConcurrentExecution(); - context.RegisterCompilationStartAction(OnCompilationStart); - } - - public void OnCompilationStart(CompilationStartAnalysisContext context) - { - var accessors = new ConcurrentBag(); - - context.RegisterSymbolAction( - symbolContext => AnalyzeSymbol(symbolContext, accessors), - SymbolKind.Property, - SymbolKind.Field - ); - - context.RegisterSemanticModelAction( - semanticModelContext => AnalyzeSemanticModel(semanticModelContext, accessors) - ); - } - - public void AnalyzeSymbol(SymbolAnalysisContext context, ConcurrentBag accessors) - { - // collect symbols for analysis - } - - public void AnalyzeSemanticModel(SemanticModelAnalysisContext context, ConcurrentBag accessors) - { - foreach (var access in accessors) - { - // analyze - } - } - } -}"); + await VerifyCS.VerifyAnalyzerAsync(""" + + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + using Microsoft.CodeAnalysis.Operations; + + namespace MyNamespace + { + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public class AnyInstanceInjectionAnalyzer : DiagnosticAnalyzer + { + public struct DependencyAccess + { + public IMethodSymbol method; + public string expectedName; + } + + public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); + + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + context.RegisterCompilationStartAction(OnCompilationStart); + } + + public void OnCompilationStart(CompilationStartAnalysisContext context) + { + var accessors = new ConcurrentBag(); + + context.RegisterSymbolAction( + symbolContext => AnalyzeSymbol(symbolContext, accessors), + SymbolKind.Property, + SymbolKind.Field + ); + + context.RegisterSemanticModelAction( + semanticModelContext => AnalyzeSemanticModel(semanticModelContext, accessors) + ); + } + + public void AnalyzeSymbol(SymbolAnalysisContext context, ConcurrentBag accessors) + { + // collect symbols for analysis + } + + public void AnalyzeSemanticModel(SemanticModelAnalysisContext context, ConcurrentBag accessors) + { + foreach (var access in accessors) + { + // analyze + } + } + } + } + """); } [Theory] @@ -349,31 +353,33 @@ public void AnalyzeSemanticModel(SemanticModelAnalysisContext context, Concurren [InlineData("Action")] public Task CSharp_Func_NoDiagnostic(string delegateType) { - return VerifyCS.VerifyAnalyzerAsync($@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Operations; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -class MyAnalyzer : DiagnosticAnalyzer -{{ - private static readonly {delegateType} x; - - public override ImmutableArray SupportedDiagnostics - {{ - get - {{ - throw new NotImplementedException(); - }} - }} - - public override void Initialize(AnalysisContext context) - {{ - }} -}}"); + return VerifyCS.VerifyAnalyzerAsync($$""" + + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + using Microsoft.CodeAnalysis.Operations; + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly {{delegateType}} x; + + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """); } [Theory] @@ -381,31 +387,33 @@ public override void Initialize(AnalysisContext context) [InlineData("Action")] public Task CSharp_NestedFunc_NoDiagnostic(string delegateType) { - return VerifyCS.VerifyAnalyzerAsync($@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Operations; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -class MyAnalyzer : DiagnosticAnalyzer -{{ - private static readonly ImmutableArray<{delegateType}> x; - - public override ImmutableArray SupportedDiagnostics - {{ - get - {{ - throw new NotImplementedException(); - }} - }} - - public override void Initialize(AnalysisContext context) - {{ - }} -}}"); + return VerifyCS.VerifyAnalyzerAsync($$""" + + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + using Microsoft.CodeAnalysis.Operations; + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly ImmutableArray<{{delegateType}}> x; + + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """); } [Theory] @@ -413,64 +421,68 @@ public override void Initialize(AnalysisContext context) [InlineData("Action")] public Task CSharp_NestedNestedFunc_NoDiagnostic(string delegateType) { - return VerifyCS.VerifyAnalyzerAsync($@" -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Operations; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -class MyAnalyzer : DiagnosticAnalyzer -{{ - private static readonly {delegateType}> x; - - public override ImmutableArray SupportedDiagnostics - {{ - get - {{ - throw new NotImplementedException(); - }} - }} - - public override void Initialize(AnalysisContext context) - {{ - }} -}}"); + return VerifyCS.VerifyAnalyzerAsync($$""" + + using System; + using System.Collections.Generic; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + using Microsoft.CodeAnalysis.Operations; + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly {{delegateType}}> x; + + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """); } [Theory] [CombinatorialData] public Task CSharp_MultiFunc_NoDiagnostic([CombinatorialValues("Func", "Action")] string delegateType, [CombinatorialValues("bool", "int, string")] string types) { - return VerifyCS.VerifyAnalyzerAsync($@" -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Operations; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -class MyAnalyzer : DiagnosticAnalyzer -{{ - private static readonly {delegateType} x; - - public override ImmutableArray SupportedDiagnostics - {{ - get - {{ - throw new NotImplementedException(); - }} - }} - - public override void Initialize(AnalysisContext context) - {{ - }} -}}"); + return VerifyCS.VerifyAnalyzerAsync($$""" + + using System; + using System.Collections.Generic; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + using Microsoft.CodeAnalysis.Operations; + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly {{delegateType}} x; + + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } + + public override void Initialize(AnalysisContext context) + { + } + } + """); } [Theory] @@ -478,30 +490,32 @@ public override void Initialize(AnalysisContext context) [InlineData("Action")] public Task VisualBasic_Func_NoDiagnostic(string delegateType) { - return VerifyVB.VerifyAnalyzerAsync($@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.Operations -Imports Microsoft.CodeAnalysis.VisualBasic - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly x1 As {delegateType}(Of IBinaryOperation) - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - - End Sub -End Class"); + return VerifyVB.VerifyAnalyzerAsync($""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.Operations + Imports Microsoft.CodeAnalysis.VisualBasic + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly x1 As {delegateType}(Of IBinaryOperation) + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + + End Sub + End Class + """); } [Theory] @@ -509,30 +523,32 @@ End Sub [InlineData("Action")] public Task VisualBasic_NestedFunc_NoDiagnostic(string delegateType) { - return VerifyVB.VerifyAnalyzerAsync($@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.Operations -Imports Microsoft.CodeAnalysis.VisualBasic - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly x1 As ImmutableArray(Of {delegateType}(Of IBinaryOperation)) - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - - End Sub -End Class"); + return VerifyVB.VerifyAnalyzerAsync($""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.Operations + Imports Microsoft.CodeAnalysis.VisualBasic + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly x1 As ImmutableArray(Of {delegateType}(Of IBinaryOperation)) + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + + End Sub + End Class + """); } [Theory] @@ -540,61 +556,65 @@ End Sub [InlineData("Action")] public Task VisualBasic_NestedNestedFunc_NoDiagnostic(string delegateType) { - return VerifyVB.VerifyAnalyzerAsync($@" -Imports System -Imports System.Collections.Generic -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.Operations -Imports Microsoft.CodeAnalysis.VisualBasic - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly x1 As {delegateType}(Of List(Of IBinaryOperation)) - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - - End Sub -End Class"); + return VerifyVB.VerifyAnalyzerAsync($""" + + Imports System + Imports System.Collections.Generic + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.Operations + Imports Microsoft.CodeAnalysis.VisualBasic + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly x1 As {delegateType}(Of List(Of IBinaryOperation)) + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + + End Sub + End Class + """); } [Theory] [CombinatorialData] public Task VisualBasic_MultiFunc_NoDiagnostic([CombinatorialValues("Func", "Action")] string delegateType, [CombinatorialValues("Int32", "Int32, String")] string types) { - return VerifyVB.VerifyAnalyzerAsync($@" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.Operations -Imports Microsoft.CodeAnalysis.VisualBasic - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly x1 As {delegateType}(Of IBinaryOperation, {types}) - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - - End Sub -End Class"); + return VerifyVB.VerifyAnalyzerAsync($""" + + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.Operations + Imports Microsoft.CodeAnalysis.VisualBasic + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly x1 As {delegateType}(Of IBinaryOperation, {types}) + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + + End Sub + End Class + """); } private static DiagnosticResult GetCSharpExpectedDiagnostic(int line, int column, string violatingTypeName) => diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DoNotUseCompilationGetSemanticModelTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DoNotUseCompilationGetSemanticModelTests.cs index 3cf7a6a00ae1b..110f9783cce60 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DoNotUseCompilationGetSemanticModelTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DoNotUseCompilationGetSemanticModelTests.cs @@ -19,187 +19,195 @@ public class DoNotUseCompilationGetSemanticModelTests [Fact] public async Task CallInInitializeAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -class Analyzer : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics => throw null; - - public override void Initialize(AnalysisContext context) - { - context.RegisterCompilationStartAction(csac => - { - csac.Compilation.GetSemanticModel(null); - }); - } -}", - GetCSharpExpectedDiagnostic(14, 13)); - - await VerifyVB.VerifyAnalyzerAsync(@" -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - -Class Analyzer - Inherits DiagnosticAnalyzer - - Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New System.Exception - End Get - End Property - - Public Overrides Sub Initialize(ByVal context As AnalysisContext) - context.RegisterCompilationStartAction( - Function(csac) - csac.Compilation.GetSemanticModel(Nothing) - End Function) - End Sub -End Class", - GetBasicExpectedDiagnostic(18, 17)); + await VerifyCS.VerifyAnalyzerAsync(""" + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + class Analyzer : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics => throw null; + + public override void Initialize(AnalysisContext context) + { + context.RegisterCompilationStartAction(csac => + { + csac.Compilation.GetSemanticModel(null); + }); + } + } + """, + GetCSharpExpectedDiagnostic(13, 13)); + + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + Class Analyzer + Inherits DiagnosticAnalyzer + + Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New System.Exception + End Get + End Property + + Public Overrides Sub Initialize(ByVal context As AnalysisContext) + context.RegisterCompilationStartAction( + Function(csac) + csac.Compilation.GetSemanticModel(Nothing) + End Function) + End Sub + End Class + """, + GetBasicExpectedDiagnostic(17, 17)); } [Fact] public async Task CallInSeparateMethodAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -class Analyzer : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics => throw null; - - public override void Initialize(AnalysisContext context) - { - DoSomething(context); - } - - private void DoSomething(AnalysisContext context) - { - context.RegisterOperationAction(oac => - { - var semanticModel = oac.Compilation.GetSemanticModel(null); - }, OperationKind.Invocation); - } -}", - GetCSharpExpectedDiagnostic(19, 33)); - - await VerifyVB.VerifyAnalyzerAsync(@" -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - -Class Analyzer - Inherits DiagnosticAnalyzer - - Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New System.Exception - End Get - End Property - - Public Overrides Sub Initialize(ByVal context As AnalysisContext) - DoSomething(context) - End Sub - - Private Sub DoSomething(ByVal context As AnalysisContext) - context.RegisterOperationAction( - Function(oac) - Dim semanticModel = oac.Compilation.GetSemanticModel(Nothing) - End Function, - OperationKind.Invocation) - End Sub -End Class", - GetBasicExpectedDiagnostic(22, 37)); + await VerifyCS.VerifyAnalyzerAsync(""" + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + class Analyzer : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics => throw null; + + public override void Initialize(AnalysisContext context) + { + DoSomething(context); + } + + private void DoSomething(AnalysisContext context) + { + context.RegisterOperationAction(oac => + { + var semanticModel = oac.Compilation.GetSemanticModel(null); + }, OperationKind.Invocation); + } + } + """, + GetCSharpExpectedDiagnostic(18, 33)); + + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + Class Analyzer + Inherits DiagnosticAnalyzer + + Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New System.Exception + End Get + End Property + + Public Overrides Sub Initialize(ByVal context As AnalysisContext) + DoSomething(context) + End Sub + + Private Sub DoSomething(ByVal context As AnalysisContext) + context.RegisterOperationAction( + Function(oac) + Dim semanticModel = oac.Compilation.GetSemanticModel(Nothing) + End Function, + OperationKind.Invocation) + End Sub + End Class + """, + GetBasicExpectedDiagnostic(21, 37)); } [Fact] public async Task CastedCallAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; - -class Analyzer : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics => throw null; - - public override void Initialize(AnalysisContext context) - { - context.RegisterCompilationStartAction(csac => - { - var csharpCompilation = csac.Compilation as CSharpCompilation; - csharpCompilation.GetSemanticModel(null); - }); - } -}", - GetCSharpExpectedDiagnostic(16, 13)); - - await VerifyVB.VerifyAnalyzerAsync(@" -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic - -Class Analyzer - Inherits DiagnosticAnalyzer - - Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New System.Exception - End Get - End Property - - Public Overrides Sub Initialize(ByVal context As AnalysisContext) - context.RegisterCompilationStartAction( - Function(csac) - Dim basicCompilation = TryCast(csac.Compilation, VisualBasicCompilation) - basicCompilation.GetSemanticModel(Nothing) - End Function) - End Sub -End Class", - GetBasicExpectedDiagnostic(20, 17)); + await VerifyCS.VerifyAnalyzerAsync(""" + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + + class Analyzer : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics => throw null; + + public override void Initialize(AnalysisContext context) + { + context.RegisterCompilationStartAction(csac => + { + var csharpCompilation = csac.Compilation as CSharpCompilation; + csharpCompilation.GetSemanticModel(null); + }); + } + } + """, + GetCSharpExpectedDiagnostic(15, 13)); + + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.VisualBasic + + Class Analyzer + Inherits DiagnosticAnalyzer + + Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New System.Exception + End Get + End Property + + Public Overrides Sub Initialize(ByVal context As AnalysisContext) + context.RegisterCompilationStartAction( + Function(csac) + Dim basicCompilation = TryCast(csac.Compilation, VisualBasicCompilation) + basicCompilation.GetSemanticModel(Nothing) + End Function) + End Sub + End Class + """, + GetBasicExpectedDiagnostic(19, 17)); } [Fact] public async Task CallInNonDiagnosticAnalyzerClassAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -class NotADiagnosticAnalyzer -{ - public void Foo(AnalysisContext context) - { - context.RegisterCompilationStartAction(csac => - { - csac.Compilation.GetSemanticModel(null); - }); - } -}"); - - await VerifyVB.VerifyAnalyzerAsync(@" -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - -Class NotADiagnosticAnalyzer - Public Sub Foo(ByVal context As AnalysisContext) - context.RegisterCompilationStartAction( - Function(csac) - csac.Compilation.GetSemanticModel(Nothing) - End Function) - End Sub -End Class"); + await VerifyCS.VerifyAnalyzerAsync(""" + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + class NotADiagnosticAnalyzer + { + public void Foo(AnalysisContext context) + { + context.RegisterCompilationStartAction(csac => + { + csac.Compilation.GetSemanticModel(null); + }); + } + } + """); + + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + Class NotADiagnosticAnalyzer + Public Sub Foo(ByVal context As AnalysisContext) + context.RegisterCompilationStartAction( + Function(csac) + csac.Compilation.GetSemanticModel(Nothing) + End Function) + End Sub + End Class + """); } private static DiagnosticResult GetCSharpExpectedDiagnostic(int line, int column) => diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DoNotUseFileLocalTypesForAnalyzersOrGeneratorsTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DoNotUseFileLocalTypesForAnalyzersOrGeneratorsTests.cs index 60684ce54e4b4..89987669fab71 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DoNotUseFileLocalTypesForAnalyzersOrGeneratorsTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DoNotUseFileLocalTypesForAnalyzersOrGeneratorsTests.cs @@ -16,9 +16,10 @@ public sealed partial class MetaAnalyzersTests private const string CompilerReferenceVersion = "4.6.0"; [Fact] - public async Task FiresOnFileLocalType_CodeFixProvider() - { - var code = """ + public Task FiresOnFileLocalType_CodeFixProvider() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis; @@ -29,10 +30,7 @@ public async Task FiresOnFileLocalType_CodeFixProvider() public override FixAllProvider GetFixAllProvider() => throw null!; public override Task RegisterCodeFixesAsync(CodeFixContext context) => throw null!; } - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp11, ExpectedDiagnostics = { @@ -40,12 +38,12 @@ public async Task FiresOnFileLocalType_CodeFixProvider() VerifyCS.Diagnostic().WithSpan(5, 12, 5, 16).WithArguments("Type"), } }.RunAsync(); - } [Fact] - public async Task FiresOnFileLocalType_DiagnosticAnalyzer() - { - var code = """ + public Task FiresOnFileLocalType_DiagnosticAnalyzer() + => new VerifyCS.Test + { + TestCode = """ using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; @@ -55,10 +53,7 @@ public async Task FiresOnFileLocalType_DiagnosticAnalyzer() public override void Initialize(AnalysisContext context) => throw null!; } - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp11, ExpectedDiagnostics = { @@ -66,22 +61,19 @@ public async Task FiresOnFileLocalType_DiagnosticAnalyzer() VerifyCS.Diagnostic().WithSpan(4, 12, 4, 16).WithArguments("Type"), } }.RunAsync(); - } [Fact] - public async Task FiresOnFileLocalType_ISourceGenerator() - { - var code = """ + public Task FiresOnFileLocalType_ISourceGenerator() + => new VerifyCS.Test + { + TestCode = """ using Microsoft.CodeAnalysis; file class Type : Microsoft.CodeAnalysis.ISourceGenerator { public void Initialize(GeneratorInitializationContext context) => throw null!; public void Execute(GeneratorExecutionContext context) => throw null!; } - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard20.AddPackages([new PackageIdentity("Microsoft.CodeAnalysis.Common", CompilerReferenceVersion)]), ExpectedDiagnostics = @@ -90,21 +82,18 @@ public async Task FiresOnFileLocalType_ISourceGenerator() VerifyCS.Diagnostic().WithSpan(2, 12, 2, 16).WithArguments("Type"), }, }.RunAsync(); - } [Fact] - public async Task FiresOnFileLocalType_IIncrementalGenerator() - { - var code = """ + public Task FiresOnFileLocalType_IIncrementalGenerator() + => new VerifyCS.Test + { + TestCode = """ using Microsoft.CodeAnalysis; file class Type : Microsoft.CodeAnalysis.IIncrementalGenerator { public void Initialize(IncrementalGeneratorInitializationContext context) => throw null!; } - """; - await new VerifyCS.Test - { - TestCode = code, + """, LanguageVersion = LanguageVersion.CSharp11, ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard20.AddPackages([new PackageIdentity("Microsoft.CodeAnalysis.Common", CompilerReferenceVersion)]), ExpectedDiagnostics = @@ -113,6 +102,5 @@ public async Task FiresOnFileLocalType_IIncrementalGenerator() VerifyCS.Diagnostic().WithSpan(2, 12, 2, 16).WithArguments("Type"), }, }.RunAsync(); - } } } diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/EnableConcurrentExecutionAnalyzerTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/EnableConcurrentExecutionAnalyzerTests.cs index 9338bcb9d1ec0..c3cc4fa6316d2 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/EnableConcurrentExecutionAnalyzerTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/EnableConcurrentExecutionAnalyzerTests.cs @@ -17,164 +17,141 @@ namespace Microsoft.CodeAnalysis.Analyzers.UnitTests.MetaAnalyzers public class EnableConcurrentExecutionAnalyzerTests { [Fact] - public async Task TestSimpleCase_CSharpAsync() - { - var code = @" -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -class Analyzer : DiagnosticAnalyzer { - public override ImmutableArray SupportedDiagnostics => throw null; - public override void Initialize(AnalysisContext [|context|]) - { - } -} -"; - var fixedCode = @" -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -class Analyzer : DiagnosticAnalyzer { - public override ImmutableArray SupportedDiagnostics => throw null; - public override void Initialize(AnalysisContext context) - { - context.EnableConcurrentExecution(); - } -} -"; - - await VerifyCS.VerifyCodeFixAsync(code, fixedCode); - } + public Task TestSimpleCase_CSharpAsync() + => VerifyCS.VerifyCodeFixAsync(""" + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + class Analyzer : DiagnosticAnalyzer { + public override ImmutableArray SupportedDiagnostics => throw null; + public override void Initialize(AnalysisContext [|context|]) + { + } + } + """, """ + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + class Analyzer : DiagnosticAnalyzer { + public override ImmutableArray SupportedDiagnostics => throw null; + public override void Initialize(AnalysisContext context) + { + context.EnableConcurrentExecution(); + } + } + """); [Fact] - public async Task TestSimpleCase_VisualBasicAsync() - { - var code = @" -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - -Class Analyzer - Inherits DiagnosticAnalyzer - - Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New System.Exception - End Get - End Property - - Public Overrides Sub Initialize([|context|] As AnalysisContext) - End Sub -End Class -"; - var fixedCode = @" -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - -Class Analyzer - Inherits DiagnosticAnalyzer - - Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New System.Exception - End Get - End Property - - Public Overrides Sub Initialize([|context|] As AnalysisContext) - context.EnableConcurrentExecution() - End Sub -End Class -"; - - await VerifyVB.VerifyCodeFixAsync(code, fixedCode); - } + public Task TestSimpleCase_VisualBasicAsync() + => VerifyVB.VerifyCodeFixAsync(""" + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + Class Analyzer + Inherits DiagnosticAnalyzer + + Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New System.Exception + End Get + End Property + + Public Overrides Sub Initialize([|context|] As AnalysisContext) + End Sub + End Class + """, """ + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + Class Analyzer + Inherits DiagnosticAnalyzer + + Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New System.Exception + End Get + End Property + + Public Overrides Sub Initialize([|context|] As AnalysisContext) + context.EnableConcurrentExecution() + End Sub + End Class + """); [Fact] - public async Task RenamedMethod_CSharpAsync() - { - var code = @" -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -class Analyzer : DiagnosticAnalyzer { - public override ImmutableArray SupportedDiagnostics => throw null; - public override void Initialize(AnalysisContext context) - { - context.EnableConcurrentExecution(); - } - - public void NotInitialize(AnalysisContext context) - { - } -} -"; - - await VerifyCS.VerifyAnalyzerAsync(code); - } + public Task RenamedMethod_CSharpAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + class Analyzer : DiagnosticAnalyzer { + public override ImmutableArray SupportedDiagnostics => throw null; + public override void Initialize(AnalysisContext context) + { + context.EnableConcurrentExecution(); + } + + public void NotInitialize(AnalysisContext context) + { + } + } + """); [Fact] - public async Task RenamedMethod_VisualBasicAsync() - { - var code = @" -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - -Class Analyzer - Inherits DiagnosticAnalyzer - - Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New System.Exception - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - context.EnableConcurrentExecution() - End Sub - - Public Sub NotInitialize(context As AnalysisContext) - End Sub -End Class -"; - - await VerifyVB.VerifyAnalyzerAsync(code); - } + public Task RenamedMethod_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + Class Analyzer + Inherits DiagnosticAnalyzer + + Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New System.Exception + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + context.EnableConcurrentExecution() + End Sub + + Public Sub NotInitialize(context As AnalysisContext) + End Sub + End Class + """); [Fact, WorkItem(2698, "https://github.com/dotnet/roslyn-analyzers/issues/2698")] - public async Task RS1026_ExpressionBodiedMethodAsync() - { - var code = @" -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -class Analyzer : DiagnosticAnalyzer { - public override ImmutableArray SupportedDiagnostics => throw null; - public override void Initialize(AnalysisContext [|context|]) - => context.RegisterCompilationAction(x => { }); -} -"; - var fixedCode = @" -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -class Analyzer : DiagnosticAnalyzer { - public override ImmutableArray SupportedDiagnostics => throw null; - public override void Initialize(AnalysisContext context) - { - context.EnableConcurrentExecution(); - context.RegisterCompilationAction(x => { }); - } -} -"; - - await VerifyCS.VerifyCodeFixAsync(code, fixedCode); - } + public Task RS1026_ExpressionBodiedMethodAsync() + => VerifyCS.VerifyCodeFixAsync(""" + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + class Analyzer : DiagnosticAnalyzer { + public override ImmutableArray SupportedDiagnostics => throw null; + public override void Initialize(AnalysisContext [|context|]) + => context.RegisterCompilationAction(x => { }); + } + """, """ + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + class Analyzer : DiagnosticAnalyzer { + public override ImmutableArray SupportedDiagnostics => throw null; + public override void Initialize(AnalysisContext context) + { + context.EnableConcurrentExecution(); + context.RegisterCompilationAction(x => { }); + } + } + """); } } diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/InvalidReportDiagnosticRuleTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/InvalidReportDiagnosticRuleTests.cs index 616b437c5278f..2d3a0feda18d8 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/InvalidReportDiagnosticRuleTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/InvalidReportDiagnosticRuleTests.cs @@ -20,250 +20,246 @@ public class InvalidReportDiagnosticRuleTests [Fact] public async Task CSharp_VerifyDiagnosticAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = new DiagnosticDescriptor(""MyDiagnosticId1"", null, null, null, DiagnosticSeverity.Warning, false); - private static readonly DiagnosticDescriptor descriptor2 = new DiagnosticDescriptor(""MyDiagnosticId2"", null, null, null, DiagnosticSeverity.Warning, false); - - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1); - } - } - - public override void Initialize(AnalysisContext context) - { - } - - private static void AnalyzeSymbol(SymbolAnalysisContext context) - { - context.ReportDiagnostic(Diagnostic.Create(descriptor2, Location.None)); - - var diag = Diagnostic.Create(descriptor2, Location.None); - context.ReportDiagnostic(diag); - } - - private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) - { - context.ReportDiagnostic(Diagnostic.Create(descriptor2, Location.None)); - - Diagnostic diag = Diagnostic.Create(descriptor2, Location.None), diag2 = Diagnostic.Create(descriptor2, Location.None); - context.ReportDiagnostic(diag); - } - - private static void AnalyzeOperation(OperationAnalysisContext context) - { - context.ReportDiagnostic(Diagnostic.Create(descriptor2, Location.None)); - - var diag = Diagnostic.Create(descriptor2, Location.None); - context.ReportDiagnostic(diag); - } -}"; - DiagnosticResult[] expected = new[] - { - GetCSharpExpectedDiagnostic(27, 9, unsupportedDescriptorName: "descriptor2"), - GetCSharpExpectedDiagnostic(30, 9, unsupportedDescriptorName: "descriptor2"), - GetCSharpExpectedDiagnostic(35, 9, unsupportedDescriptorName: "descriptor2"), - GetCSharpExpectedDiagnostic(38, 9, unsupportedDescriptorName: "descriptor2"), - GetCSharpExpectedDiagnostic(43, 9, unsupportedDescriptorName: "descriptor2"), - GetCSharpExpectedDiagnostic(46, 9, unsupportedDescriptorName: "descriptor2") - }; - - await VerifyCS.VerifyAnalyzerAsync(source, expected); + DiagnosticResult[] expected = + [ + GetCSharpExpectedDiagnostic(26, 9, unsupportedDescriptorName: "descriptor2"), + GetCSharpExpectedDiagnostic(29, 9, unsupportedDescriptorName: "descriptor2"), + GetCSharpExpectedDiagnostic(34, 9, unsupportedDescriptorName: "descriptor2"), + GetCSharpExpectedDiagnostic(37, 9, unsupportedDescriptorName: "descriptor2"), + GetCSharpExpectedDiagnostic(42, 9, unsupportedDescriptorName: "descriptor2"), + GetCSharpExpectedDiagnostic(45, 9, unsupportedDescriptorName: "descriptor2") + ]; + + await VerifyCS.VerifyAnalyzerAsync(""" + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = new DiagnosticDescriptor("MyDiagnosticId1", null, null, null, DiagnosticSeverity.Warning, false); + private static readonly DiagnosticDescriptor descriptor2 = new DiagnosticDescriptor("MyDiagnosticId2", null, null, null, DiagnosticSeverity.Warning, false); + + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1); + } + } + + public override void Initialize(AnalysisContext context) + { + } + + private static void AnalyzeSymbol(SymbolAnalysisContext context) + { + context.ReportDiagnostic(Diagnostic.Create(descriptor2, Location.None)); + + var diag = Diagnostic.Create(descriptor2, Location.None); + context.ReportDiagnostic(diag); + } + + private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) + { + context.ReportDiagnostic(Diagnostic.Create(descriptor2, Location.None)); + + Diagnostic diag = Diagnostic.Create(descriptor2, Location.None), diag2 = Diagnostic.Create(descriptor2, Location.None); + context.ReportDiagnostic(diag); + } + + private static void AnalyzeOperation(OperationAnalysisContext context) + { + context.ReportDiagnostic(Diagnostic.Create(descriptor2, Location.None)); + + var diag = Diagnostic.Create(descriptor2, Location.None); + context.ReportDiagnostic(diag); + } + } + """, expected); } [Fact, WorkItem(1689, "https://github.com/dotnet/roslyn-analyzers/issues/1689")] public async Task CSharp_VerifyDiagnostic_PropertyInitializerAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = new DiagnosticDescriptor(""MyDiagnosticId1"", null, null, null, DiagnosticSeverity.Warning, false); - private static readonly DiagnosticDescriptor descriptor2 = new DiagnosticDescriptor(""MyDiagnosticId2"", null, null, null, DiagnosticSeverity.Warning, false); - - public override ImmutableArray SupportedDiagnostics { get; } = ImmutableArray.Create(descriptor1); - - public override void Initialize(AnalysisContext context) - { - } - - private static void AnalyzeSymbol(SymbolAnalysisContext context) - { - context.ReportDiagnostic(Diagnostic.Create(descriptor2, Location.None)); - - var diag = Diagnostic.Create(descriptor2, Location.None); - context.ReportDiagnostic(diag); - } -}"; - DiagnosticResult[] expected = new[] - { - GetCSharpExpectedDiagnostic(21, 9, unsupportedDescriptorName: "descriptor2"), - GetCSharpExpectedDiagnostic(24, 9, unsupportedDescriptorName: "descriptor2") - }; - - await VerifyCS.VerifyAnalyzerAsync(source, expected); + DiagnosticResult[] expected = + [ + GetCSharpExpectedDiagnostic(20, 9, unsupportedDescriptorName: "descriptor2"), + GetCSharpExpectedDiagnostic(23, 9, unsupportedDescriptorName: "descriptor2") + ]; + + await VerifyCS.VerifyAnalyzerAsync(""" + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = new DiagnosticDescriptor("MyDiagnosticId1", null, null, null, DiagnosticSeverity.Warning, false); + private static readonly DiagnosticDescriptor descriptor2 = new DiagnosticDescriptor("MyDiagnosticId2", null, null, null, DiagnosticSeverity.Warning, false); + + public override ImmutableArray SupportedDiagnostics { get; } = ImmutableArray.Create(descriptor1); + + public override void Initialize(AnalysisContext context) + { + } + + private static void AnalyzeSymbol(SymbolAnalysisContext context) + { + context.ReportDiagnostic(Diagnostic.Create(descriptor2, Location.None)); + + var diag = Diagnostic.Create(descriptor2, Location.None); + context.ReportDiagnostic(diag); + } + } + """, expected); } [Fact] public async Task VisualBasic_VerifyDiagnosticAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = New DiagnosticDescriptor(""MyDiagnosticId1"", Nothing, Nothing, Nothing, DiagnosticSeverity.Warning, False) - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = New DiagnosticDescriptor(""MyDiagnosticId2"", Nothing, Nothing, Nothing, DiagnosticSeverity.Warning, False) - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub - - Private Shared Sub AnalyzeSymbol(context As SymbolAnalysisContext) - context.ReportDiagnostic(Diagnostic.Create(descriptor2, Location.None)) - - Dim diag = Diagnostic.Create(descriptor2, Location.None) - context.ReportDiagnostic(diag) - End Sub - - Private Shared Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext) - context.ReportDiagnostic(Diagnostic.Create(descriptor2, Location.None)) - - Dim diag = Diagnostic.Create(descriptor2, Location.None), diag2 = Diagnostic.Create(descriptor2, Location.None) - context.ReportDiagnostic(diag) - End Sub - - Private Shared Sub AnalyzeOperation(context As OperationAnalysisContext) - context.ReportDiagnostic(Diagnostic.Create(descriptor2, Location.None)) - - Dim diag = Diagnostic.Create(descriptor2, Location.None) - context.ReportDiagnostic(diag) - End Sub -End Class -"; - DiagnosticResult[] expected = new[] - { - GetBasicExpectedDiagnostic(24, 9, unsupportedDescriptorName: "descriptor2"), - GetBasicExpectedDiagnostic(27, 9, unsupportedDescriptorName: "descriptor2"), - GetBasicExpectedDiagnostic(31, 9, unsupportedDescriptorName: "descriptor2"), - GetBasicExpectedDiagnostic(34, 9, unsupportedDescriptorName: "descriptor2"), - GetBasicExpectedDiagnostic(38, 9, unsupportedDescriptorName: "descriptor2"), - GetBasicExpectedDiagnostic(41, 9, unsupportedDescriptorName: "descriptor2") - }; - - await VerifyVB.VerifyAnalyzerAsync(source, expected); + DiagnosticResult[] expected = + [ + GetBasicExpectedDiagnostic(23, 9, unsupportedDescriptorName: "descriptor2"), + GetBasicExpectedDiagnostic(26, 9, unsupportedDescriptorName: "descriptor2"), + GetBasicExpectedDiagnostic(30, 9, unsupportedDescriptorName: "descriptor2"), + GetBasicExpectedDiagnostic(33, 9, unsupportedDescriptorName: "descriptor2"), + GetBasicExpectedDiagnostic(37, 9, unsupportedDescriptorName: "descriptor2"), + GetBasicExpectedDiagnostic(40, 9, unsupportedDescriptorName: "descriptor2") + ]; + + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = New DiagnosticDescriptor("MyDiagnosticId1", Nothing, Nothing, Nothing, DiagnosticSeverity.Warning, False) + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = New DiagnosticDescriptor("MyDiagnosticId2", Nothing, Nothing, Nothing, DiagnosticSeverity.Warning, False) + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + + Private Shared Sub AnalyzeSymbol(context As SymbolAnalysisContext) + context.ReportDiagnostic(Diagnostic.Create(descriptor2, Location.None)) + + Dim diag = Diagnostic.Create(descriptor2, Location.None) + context.ReportDiagnostic(diag) + End Sub + + Private Shared Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext) + context.ReportDiagnostic(Diagnostic.Create(descriptor2, Location.None)) + + Dim diag = Diagnostic.Create(descriptor2, Location.None), diag2 = Diagnostic.Create(descriptor2, Location.None) + context.ReportDiagnostic(diag) + End Sub + + Private Shared Sub AnalyzeOperation(context As OperationAnalysisContext) + context.ReportDiagnostic(Diagnostic.Create(descriptor2, Location.None)) + + Dim diag = Diagnostic.Create(descriptor2, Location.None) + context.ReportDiagnostic(diag) + End Sub + End Class + """, expected); } [Fact] public async Task CSharp_NoDiagnosticCasesAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = new DiagnosticDescriptor(""MyDiagnosticId1"", null, null, null, DiagnosticSeverity.Warning, false); - private static readonly DiagnosticDescriptor descriptor2 = new DiagnosticDescriptor(""MyDiagnosticId2"", null, null, null, DiagnosticSeverity.Warning, false); - - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(descriptor1); - } - } - - public override void Initialize(AnalysisContext context) - { - } - - private static void AnalyzeSymbol(SymbolAnalysisContext context) - { - // Overload resolution failures - context.{|CS1501:ReportDiagnostic|}(Diagnostic.Create(descriptor2, Location.None), null); - context.ReportDiagnostic(Diagnostic.{|CS0121:Create|}(descriptor2, Location.None, null)); - context.ReportDiagnostic({|CS0841:diag|}); - - // Needs flow analysis - var diag = Diagnostic.Create(descriptor2, Location.None); - var diag2 = diag; - context.ReportDiagnostic(diag2); - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(source); + await VerifyCS.VerifyAnalyzerAsync(""" + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = new DiagnosticDescriptor("MyDiagnosticId1", null, null, null, DiagnosticSeverity.Warning, false); + private static readonly DiagnosticDescriptor descriptor2 = new DiagnosticDescriptor("MyDiagnosticId2", null, null, null, DiagnosticSeverity.Warning, false); + + public override ImmutableArray SupportedDiagnostics + { + get + { + return ImmutableArray.Create(descriptor1); + } + } + + public override void Initialize(AnalysisContext context) + { + } + + private static void AnalyzeSymbol(SymbolAnalysisContext context) + { + // Overload resolution failures + context.{|CS1501:ReportDiagnostic|}(Diagnostic.Create(descriptor2, Location.None), null); + context.ReportDiagnostic(Diagnostic.{|CS0121:Create|}(descriptor2, Location.None, null)); + context.ReportDiagnostic({|CS0841:diag|}); + + // Needs flow analysis + var diag = Diagnostic.Create(descriptor2, Location.None); + var diag2 = diag; + context.ReportDiagnostic(diag2); + } + } + """); } [Fact] public async Task VisualBasic_NoDiagnosticCasesAsync() { - var source = @" -Imports System -Imports System.Collections.Generic -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - - Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = New DiagnosticDescriptor(""MyDiagnosticId1"", Nothing, Nothing, Nothing, DiagnosticSeverity.Warning, False) - Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = New DiagnosticDescriptor(""MyDiagnosticId2"", Nothing, Nothing, Nothing, DiagnosticSeverity.Warning, False) - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Return ImmutableArray.Create(descriptor1) - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - End Sub - - Private Shared Sub AnalyzeSymbol(context As SymbolAnalysisContext) - ' Overload resolution failures - context.ReportDiagnostic(Diagnostic.Create(descriptor2, Location.None), {|BC30057:Nothing|}) - context.ReportDiagnostic(Diagnostic.{|BC30521:Create|}(descriptor2, Location.None, Nothing)) - context.ReportDiagnostic({|BC32000:diag|}) - - ' Needs flow analysis - Dim diag = Diagnostic.Create(descriptor2, Location.None) - Dim diag2 = diag - context.ReportDiagnostic(diag2) - End Sub -End Class -"; - - await VerifyVB.VerifyAnalyzerAsync(source); + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports System.Collections.Generic + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Private Shared ReadOnly descriptor1 As DiagnosticDescriptor = New DiagnosticDescriptor("MyDiagnosticId1", Nothing, Nothing, Nothing, DiagnosticSeverity.Warning, False) + Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = New DiagnosticDescriptor("MyDiagnosticId2", Nothing, Nothing, Nothing, DiagnosticSeverity.Warning, False) + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Return ImmutableArray.Create(descriptor1) + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + + Private Shared Sub AnalyzeSymbol(context As SymbolAnalysisContext) + ' Overload resolution failures + context.ReportDiagnostic(Diagnostic.Create(descriptor2, Location.None), {|BC30057:Nothing|}) + context.ReportDiagnostic(Diagnostic.{|BC30521:Create|}(descriptor2, Location.None, Nothing)) + context.ReportDiagnostic({|BC32000:diag|}) + + ' Needs flow analysis + Dim diag = Diagnostic.Create(descriptor2, Location.None) + Dim diag2 = diag + context.ReportDiagnostic(diag2) + End Sub + End Class + """); } private static DiagnosticResult GetCSharpExpectedDiagnostic(int line, int column, string unsupportedDescriptorName) => diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/InvalidSyntaxKindTypeArgumentRuleTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/InvalidSyntaxKindTypeArgumentRuleTests.cs index 4c37d2f786ad9..3a7153622933c 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/InvalidSyntaxKindTypeArgumentRuleTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/InvalidSyntaxKindTypeArgumentRuleTests.cs @@ -22,173 +22,169 @@ public class InvalidSyntaxKindTypeArgumentRuleTests [Fact] public async Task CSharp_VerifyDiagnosticAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; - -#pragma warning disable RS1012 -#pragma warning disable RS1013 - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -class MyAnalyzer : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics - { - get - { - throw new NotImplementedException(); - } - } - - public override void Initialize(AnalysisContext context) - { - context.RegisterSyntaxNodeAction(AnalyzeSyntax, 0); - context.RegisterCodeBlockStartAction(AnalyzeCodeBlockStart); - } - - private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) - { - } - - private static void AnalyzeCodeBlockStart(CodeBlockStartAnalysisContext context) - { - } -}"; - DiagnosticResult[] expected = new[] - { - GetCSharpExpectedDiagnostic(24, 9, typeArgumentName: "Int32", registerMethodName: DiagnosticWellKnownNames.RegisterSyntaxNodeActionName), - GetCSharpExpectedDiagnostic(25, 9, typeArgumentName: "Int32", registerMethodName: DiagnosticWellKnownNames.RegisterCodeBlockStartActionName) - }; - - await VerifyCS.VerifyAnalyzerAsync(source, expected); + DiagnosticResult[] expected = + [ + GetCSharpExpectedDiagnostic(23, 9, typeArgumentName: "Int32", registerMethodName: DiagnosticWellKnownNames.RegisterSyntaxNodeActionName), + GetCSharpExpectedDiagnostic(24, 9, typeArgumentName: "Int32", registerMethodName: DiagnosticWellKnownNames.RegisterCodeBlockStartActionName) + ]; + + await VerifyCS.VerifyAnalyzerAsync(""" + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + + #pragma warning disable RS1012 + #pragma warning disable RS1013 + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + class MyAnalyzer : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } + + public override void Initialize(AnalysisContext context) + { + context.RegisterSyntaxNodeAction(AnalyzeSyntax, 0); + context.RegisterCodeBlockStartAction(AnalyzeCodeBlockStart); + } + + private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) + { + } + + private static void AnalyzeCodeBlockStart(CodeBlockStartAnalysisContext context) + { + } + } + """, expected); } [Fact] public async Task VisualBasic_VerifyDiagnosticAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - -#Disable Warning RS1012 -#Disable Warning RS1013 - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - context.RegisterSyntaxNodeAction(AddressOf AnalyzeSyntax, 0) - context.RegisterCodeBlockStartAction(Of Int32)(AddressOf AnalyzeCodeBlockStart) - End Sub - - Private Shared Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext) - End Sub - - Private Shared Sub AnalyzeCodeBlockStart(context As CodeBlockStartAnalysisContext(Of Int32)) - End Sub -End Class -"; - DiagnosticResult[] expected = new[] - { - GetBasicExpectedDiagnostic(20, 9, typeArgumentName: "Int32", registerMethodName: DiagnosticWellKnownNames.RegisterSyntaxNodeActionName), - GetBasicExpectedDiagnostic(21, 9, typeArgumentName: "Int32", registerMethodName: DiagnosticWellKnownNames.RegisterCodeBlockStartActionName) - }; - - await VerifyVB.VerifyAnalyzerAsync(source, expected); + DiagnosticResult[] expected = + [ + GetBasicExpectedDiagnostic(19, 9, typeArgumentName: "Int32", registerMethodName: DiagnosticWellKnownNames.RegisterSyntaxNodeActionName), + GetBasicExpectedDiagnostic(20, 9, typeArgumentName: "Int32", registerMethodName: DiagnosticWellKnownNames.RegisterCodeBlockStartActionName) + ]; + + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + #Disable Warning RS1012 + #Disable Warning RS1013 + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + context.RegisterSyntaxNodeAction(AddressOf AnalyzeSyntax, 0) + context.RegisterCodeBlockStartAction(Of Int32)(AddressOf AnalyzeCodeBlockStart) + End Sub + + Private Shared Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext) + End Sub + + Private Shared Sub AnalyzeCodeBlockStart(context As CodeBlockStartAnalysisContext(Of Int32)) + End Sub + End Class + """, expected); } [Fact] public async Task CSharp_NoDiagnosticCasesAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; - -#pragma warning disable RS1012 -#pragma warning disable RS1013 - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -abstract class MyAnalyzer : DiagnosticAnalyzer - where T : struct -{ - public override ImmutableArray SupportedDiagnostics - { - get - { - throw new NotImplementedException(); - } - } - - public override void Initialize(AnalysisContext context) - { - context.{|CS0411:RegisterSyntaxNodeAction|}(AnalyzeSyntax, null); // Overload resolution failure - context.RegisterSyntaxNodeAction<{|CS0246:ErrorType|}>(AnalyzeSyntax, null); // Error type argument - context.RegisterCodeBlockStartAction(AnalyzeCodeBlockStart); // NYI: Type param as a type argument - } - - private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) - { - } - - private static void AnalyzeCodeBlockStart(CodeBlockStartAnalysisContext context) - { - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(source); + await VerifyCS.VerifyAnalyzerAsync(""" + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + + #pragma warning disable RS1012 + #pragma warning disable RS1013 + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + abstract class MyAnalyzer : DiagnosticAnalyzer + where T : struct + { + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } + + public override void Initialize(AnalysisContext context) + { + context.{|CS0411:RegisterSyntaxNodeAction|}(AnalyzeSyntax, null); // Overload resolution failure + context.RegisterSyntaxNodeAction<{|CS0246:ErrorType|}>(AnalyzeSyntax, null); // Error type argument + context.RegisterCodeBlockStartAction(AnalyzeCodeBlockStart); // NYI: Type param as a type argument + } + + private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) + { + } + + private static void AnalyzeCodeBlockStart(CodeBlockStartAnalysisContext context) + { + } + } + """); } [Fact] public async Task VisualBasic_NoDiagnosticCasesAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - -#Disable Warning RS1012 -#Disable Warning RS1013 - - -Class MyAnalyzer(Of T As Structure) - Inherits DiagnosticAnalyzer - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - context.{|BC30518:RegisterSyntaxNodeAction|}(AddressOf AnalyzeSyntax, Nothing) ' Overload resolution failure - context.{|BC30521:RegisterSyntaxNodeAction(Of {|BC30002:ErrorType|})|}(AddressOf AnalyzeSyntax, Nothing) ' Error type argument - context.RegisterCodeBlockStartAction(Of T)(AddressOf AnalyzeCodeBlockStart) ' NYI: Type param as a type argument - End Sub - - Private Shared Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext) - End Sub - - Private Shared Sub AnalyzeCodeBlockStart(context As CodeBlockStartAnalysisContext(Of T)) - End Sub -End Class -"; - - await VerifyVB.VerifyAnalyzerAsync(source); + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + #Disable Warning RS1012 + #Disable Warning RS1013 + + + Class MyAnalyzer(Of T As Structure) + Inherits DiagnosticAnalyzer + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + context.{|BC30518:RegisterSyntaxNodeAction|}(AddressOf AnalyzeSyntax, Nothing) ' Overload resolution failure + context.{|BC30521:RegisterSyntaxNodeAction(Of {|BC30002:ErrorType|})|}(AddressOf AnalyzeSyntax, Nothing) ' Error type argument + context.RegisterCodeBlockStartAction(Of T)(AddressOf AnalyzeCodeBlockStart) ' NYI: Type param as a type argument + End Sub + + Private Shared Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext) + End Sub + + Private Shared Sub AnalyzeCodeBlockStart(context As CodeBlockStartAnalysisContext(Of T)) + End Sub + End Class + """); } private static DiagnosticResult GetCSharpExpectedDiagnostic(int line, int column, string typeArgumentName, string registerMethodName) => diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/MissingDiagnosticAnalyzerAttributeRuleTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/MissingDiagnosticAnalyzerAttributeRuleTests.cs index 1dc7800910b9e..a65efa5b36182 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/MissingDiagnosticAnalyzerAttributeRuleTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/MissingDiagnosticAnalyzerAttributeRuleTests.cs @@ -211,9 +211,8 @@ End Class } [Fact] - public async Task CSharp_NoDiagnosticCasesAsync() - { - var source = """ + public Task CSharp_NoDiagnosticCasesAsync() + => VerifyCS.VerifyAnalyzerAsync(""" using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; @@ -238,14 +237,11 @@ public override void Initialize(AnalysisContext context) public abstract class MyAbstractAnalyzerWithoutAttribute : DiagnosticAnalyzer { } - """; - await VerifyCS.VerifyAnalyzerAsync(source); - } + """); [Fact] - public async Task VisualBasic_NoDiagnosticCasesAsync() - { - var source = """ + public Task VisualBasic_NoDiagnosticCasesAsync() + => VerifyVB.VerifyAnalyzerAsync(""" Imports System Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis @@ -267,7 +263,5 @@ End Class Public MustInherit Class MyAbstractAnalyzerWithoutAttribute Inherits DiagnosticAnalyzer End Class - """; - await VerifyVB.VerifyAnalyzerAsync(source); - } + """); } diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/MissingKindArgumentToRegisterActionRuleTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/MissingKindArgumentToRegisterActionRuleTests.cs index 58355fe23a1b0..dfe39d78f626a 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/MissingKindArgumentToRegisterActionRuleTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/MissingKindArgumentToRegisterActionRuleTests.cs @@ -22,206 +22,203 @@ public class MissingKindArgumentToRegisterActionRuleTests [Fact] public async Task CSharp_VerifyRegisterSymbolActionDiagnosticAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -class MyAnalyzer : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics - { - get - { - throw new NotImplementedException(); - } - } - - public override void Initialize(AnalysisContext context) - { - context.RegisterSymbolAction(AnalyzeSymbol); - } - - private static void AnalyzeSymbol(SymbolAnalysisContext context) - { - } - - private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) - { - } -}"; - DiagnosticResult expected = GetCSharpExpectedDiagnostic(20, 9, MissingKindArgument.SymbolKind); - await VerifyCS.VerifyAnalyzerAsync(source, expected); + DiagnosticResult expected = GetCSharpExpectedDiagnostic(19, 9, MissingKindArgument.SymbolKind); + await VerifyCS.VerifyAnalyzerAsync(""" + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + class MyAnalyzer : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } + + public override void Initialize(AnalysisContext context) + { + context.RegisterSymbolAction(AnalyzeSymbol); + } + + private static void AnalyzeSymbol(SymbolAnalysisContext context) + { + } + + private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) + { + } + } + """, expected); } [Fact] public async Task VisualBasic_VerifyRegisterSymbolActionDiagnosticAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - context.RegisterSymbolAction(AddressOf AnalyzeSymbol) - End Sub - - Private Shared Sub AnalyzeSymbol(context As SymbolAnalysisContext) - End Sub - - Private Shared Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext) - End Sub -End Class -"; - DiagnosticResult expected = GetBasicExpectedDiagnostic(17, 9, MissingKindArgument.SymbolKind); - await VerifyVB.VerifyAnalyzerAsync(source, expected); + DiagnosticResult expected = GetBasicExpectedDiagnostic(16, 9, MissingKindArgument.SymbolKind); + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + context.RegisterSymbolAction(AddressOf AnalyzeSymbol) + End Sub + + Private Shared Sub AnalyzeSymbol(context As SymbolAnalysisContext) + End Sub + + Private Shared Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext) + End Sub + End Class + """, expected); } [Fact] public async Task CSharp_VerifyRegisterSyntaxActionDiagnosticAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -class MyAnalyzer : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics - { - get - { - throw new NotImplementedException(); - } - } - - public override void Initialize(AnalysisContext context) - { - context.RegisterSyntaxNodeAction(AnalyzeSyntax); - } - - private static void AnalyzeSymbol(SymbolAnalysisContext context) - { - } - - private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) - { - } -}"; - DiagnosticResult expected = GetCSharpExpectedDiagnostic(21, 9, MissingKindArgument.SyntaxKind); - await VerifyCS.VerifyAnalyzerAsync(source, expected); + DiagnosticResult expected = GetCSharpExpectedDiagnostic(20, 9, MissingKindArgument.SyntaxKind); + await VerifyCS.VerifyAnalyzerAsync(""" + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + class MyAnalyzer : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } + + public override void Initialize(AnalysisContext context) + { + context.RegisterSyntaxNodeAction(AnalyzeSyntax); + } + + private static void AnalyzeSymbol(SymbolAnalysisContext context) + { + } + + private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) + { + } + } + """, expected); } [Fact] public async Task VisualBasic_VerifyRegisterSyntaxActionDiagnosticAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - context.RegisterSyntaxNodeAction(Of SyntaxKind)(AddressOf AnalyzeSyntax) - End Sub - - Private Shared Sub AnalyzeSymbol(context As SymbolAnalysisContext) - End Sub - - Private Shared Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext) - End Sub -End Class -"; - DiagnosticResult expected = GetBasicExpectedDiagnostic(18, 9, MissingKindArgument.SyntaxKind); - await VerifyVB.VerifyAnalyzerAsync(source, expected); + DiagnosticResult expected = GetBasicExpectedDiagnostic(17, 9, MissingKindArgument.SyntaxKind); + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.VisualBasic + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + context.RegisterSyntaxNodeAction(Of SyntaxKind)(AddressOf AnalyzeSyntax) + End Sub + + Private Shared Sub AnalyzeSymbol(context As SymbolAnalysisContext) + End Sub + + Private Shared Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext) + End Sub + End Class + """, expected); } [Fact] public async Task CSharp_VerifyRegisterOperationActionDiagnosticAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -class MyAnalyzer : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics - { - get - { - throw new NotImplementedException(); - } - } - - public override void Initialize(AnalysisContext context) - { - context.RegisterOperationAction(AnalyzeOperation); - } - - private static void AnalyzeOperation(OperationAnalysisContext context) - { - } -}"; - DiagnosticResult expected = GetCSharpExpectedDiagnostic(20, 9, MissingKindArgument.OperationKind); - await VerifyCS.VerifyAnalyzerAsync(source, expected); + DiagnosticResult expected = GetCSharpExpectedDiagnostic(19, 9, MissingKindArgument.OperationKind); + await VerifyCS.VerifyAnalyzerAsync(""" + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + class MyAnalyzer : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } + + public override void Initialize(AnalysisContext context) + { + context.RegisterOperationAction(AnalyzeOperation); + } + + private static void AnalyzeOperation(OperationAnalysisContext context) + { + } + } + """, expected); } [Fact] public async Task VisualBasic_VerifyRegisterOperationActionDiagnosticAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - context.RegisterOperationAction(AddressOf AnalyzeOperation) - End Sub - - Private Shared Sub AnalyzeOperation(context As OperationAnalysisContext) - End Sub -End Class -"; - DiagnosticResult expected = GetBasicExpectedDiagnostic(17, 9, MissingKindArgument.OperationKind); - await VerifyVB.VerifyAnalyzerAsync(source, expected); + DiagnosticResult expected = GetBasicExpectedDiagnostic(16, 9, MissingKindArgument.OperationKind); + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + context.RegisterOperationAction(AddressOf AnalyzeOperation) + End Sub + + Private Shared Sub AnalyzeOperation(context As OperationAnalysisContext) + End Sub + End Class + """, expected); } private static DiagnosticResult GetCSharpExpectedDiagnostic(int line, int column, MissingKindArgument kind) diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/PreferIsKindAnalyzerTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/PreferIsKindAnalyzerTests.cs index 423b371d9416d..887ed8ab02541 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/PreferIsKindAnalyzerTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/PreferIsKindAnalyzerTests.cs @@ -23,40 +23,35 @@ public class PreferIsKindAnalyzerTests [InlineData("!=")] public async Task TestSimpleReturn_CSAsync(string @operator) { - var source = -$@"using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; - -class C -{{ - bool Method(SyntaxNode node) - {{ - return [|node.Kind()|] {@operator} SyntaxKind.None; - }} -}} -"; - var prefix = @operator switch { "==" => "", "!=" => "!", _ => throw new InvalidOperationException(), }; + await VerifyCS.VerifyCodeFixAsync($$""" + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; - var fixedSource = -$@"using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; - -class C -{{ - bool Method(SyntaxNode node) - {{ - return {prefix}node.IsKind(SyntaxKind.None); - }} -}} -"; - - await VerifyCS.VerifyCodeFixAsync(source, fixedSource); + class C + { + bool Method(SyntaxNode node) + { + return [|node.Kind()|] {{@operator}} SyntaxKind.None; + } + } + """, $$""" + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + + class C + { + bool Method(SyntaxNode node) + { + return {{prefix}}node.IsKind(SyntaxKind.None); + } + } + """); } [Theory] @@ -64,137 +59,117 @@ bool Method(SyntaxNode node) [InlineData("<>")] public async Task TestSimpleReturn_VBAsync(string @operator) { - var source = -$@"Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.VisualBasic - -Class C - Function Method(node As SyntaxNode) As Boolean - Return [|node.Kind()|] {@operator} SyntaxKind.None - End Function -End Class -"; - var prefix = @operator switch { "=" => "", "<>" => "Not ", _ => throw new InvalidOperationException(), }; - - var fixedSource = -$@"Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.VisualBasic - -Class C - Function Method(node As SyntaxNode) As Boolean - Return {prefix}node.IsKind(SyntaxKind.None) - End Function -End Class -"; - - await VerifyVB.VerifyCodeFixAsync(source, fixedSource); + await VerifyVB.VerifyCodeFixAsync($""" + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.VisualBasic + + Class C + Function Method(node As SyntaxNode) As Boolean + Return [|node.Kind()|] {@operator} SyntaxKind.None + End Function + End Class + """, $""" + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.VisualBasic + + Class C + Function Method(node As SyntaxNode) As Boolean + Return {prefix}node.IsKind(SyntaxKind.None) + End Function + End Class + """); } [Fact] - public async Task TestCompoundExpression_CSAsync() - { - var source = -@"using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; - -class C -{ - bool Method(SyntaxNode node) - { - return [|node.Kind()|] != SyntaxKind.None && [|node.Kind()|] != SyntaxKind.TrueKeyword; - } -} -"; - var fixedSource = -@"using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; - -class C -{ - bool Method(SyntaxNode node) - { - return !node.IsKind(SyntaxKind.None) && !node.IsKind(SyntaxKind.TrueKeyword); - } -} -"; + public Task TestCompoundExpression_CSAsync() + => VerifyCS.VerifyCodeFixAsync(""" + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; - await VerifyCS.VerifyCodeFixAsync(source, fixedSource); - } + class C + { + bool Method(SyntaxNode node) + { + return [|node.Kind()|] != SyntaxKind.None && [|node.Kind()|] != SyntaxKind.TrueKeyword; + } + } + """, """ + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + + class C + { + bool Method(SyntaxNode node) + { + return !node.IsKind(SyntaxKind.None) && !node.IsKind(SyntaxKind.TrueKeyword); + } + } + """); [Fact] - public async Task TestCompoundExpression_VBAsync() - { - var source = -@"Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.VisualBasic - -Class C - Function Method(node As SyntaxNode) As Boolean - Return [|node.Kind()|] <> SyntaxKind.None AndAlso [|node.Kind()|] <> SyntaxKind.TrueKeyword - End Function -End Class -"; - var fixedSource = -@"Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.VisualBasic - -Class C - Function Method(node As SyntaxNode) As Boolean - Return Not node.IsKind(SyntaxKind.None) AndAlso Not node.IsKind(SyntaxKind.TrueKeyword) - End Function -End Class -"; - - await VerifyVB.VerifyCodeFixAsync(source, fixedSource); - } + public Task TestCompoundExpression_VBAsync() + => VerifyVB.VerifyCodeFixAsync(""" + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.VisualBasic + + Class C + Function Method(node As SyntaxNode) As Boolean + Return [|node.Kind()|] <> SyntaxKind.None AndAlso [|node.Kind()|] <> SyntaxKind.TrueKeyword + End Function + End Class + """, """ + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.VisualBasic + + Class C + Function Method(node As SyntaxNode) As Boolean + Return Not node.IsKind(SyntaxKind.None) AndAlso Not node.IsKind(SyntaxKind.TrueKeyword) + End Function + End Class + """); [Theory] [InlineData("==")] [InlineData("!=")] public async Task TestCompoundExpression2_CSAsync(string @operator) { - var source = -$@"using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; - -class C -{{ - bool Method(SyntaxNode node) - {{ - return [|node.Kind()|] {@operator} SyntaxKind.None && - [|node.Kind()|] {@operator} SyntaxKind.TrueKeyword; - }} -}} -"; - var prefix = @operator switch { "==" => "", "!=" => "!", _ => throw new InvalidOperationException(), }; + await VerifyCS.VerifyCodeFixAsync($$""" + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; - var fixedSource = -$@"using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; - -class C -{{ - bool Method(SyntaxNode node) - {{ - return {prefix}node.IsKind(SyntaxKind.None) && - {prefix}node.IsKind(SyntaxKind.TrueKeyword); - }} -}} -"; - - await VerifyCS.VerifyCodeFixAsync(source, fixedSource); + class C + { + bool Method(SyntaxNode node) + { + return [|node.Kind()|] {{@operator}} SyntaxKind.None && + [|node.Kind()|] {{@operator}} SyntaxKind.TrueKeyword; + } + } + """, $$""" + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + + class C + { + bool Method(SyntaxNode node) + { + return {{prefix}}node.IsKind(SyntaxKind.None) && + {{prefix}}node.IsKind(SyntaxKind.TrueKeyword); + } + } + """); } [Theory] @@ -202,38 +177,33 @@ bool Method(SyntaxNode node) [InlineData("<>")] public async Task TestCompoundExpression2_VBAsync(string @operator) { - var source = -$@"Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.VisualBasic - -Class C - Function Method(node As SyntaxNode) As Boolean - Return [|node.Kind()|] {@operator} SyntaxKind.None AndAlso - [|node.Kind()|] {@operator} SyntaxKind.TrueKeyword - End Function -End Class -"; - var prefix = @operator switch { "=" => "", "<>" => "Not ", _ => throw new InvalidOperationException(), }; - - var fixedSource = -$@"Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.VisualBasic - -Class C - Function Method(node As SyntaxNode) As Boolean - Return {prefix}node.IsKind(SyntaxKind.None) AndAlso - {prefix}node.IsKind(SyntaxKind.TrueKeyword) - End Function -End Class -"; - - await VerifyVB.VerifyCodeFixAsync(source, fixedSource); + await VerifyVB.VerifyCodeFixAsync($""" + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.VisualBasic + + Class C + Function Method(node As SyntaxNode) As Boolean + Return [|node.Kind()|] {@operator} SyntaxKind.None AndAlso + [|node.Kind()|] {@operator} SyntaxKind.TrueKeyword + End Function + End Class + """, $""" + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.VisualBasic + + Class C + Function Method(node As SyntaxNode) As Boolean + Return {prefix}node.IsKind(SyntaxKind.None) AndAlso + {prefix}node.IsKind(SyntaxKind.TrueKeyword) + End Function + End Class + """); } [Theory] @@ -241,19 +211,6 @@ End Class [InlineData("!=")] public async Task TestCalledAsStaticMethod_CSAsync(string @operator) { - var source = -$@"using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; - -class C -{{ - bool Method(SyntaxNode node) - {{ - return [|Microsoft.CodeAnalysis.CSharp.CSharpExtensions.Kind(node)|] {@operator} SyntaxKind.None; - }} -}} -"; - var prefix = @operator switch { "==" => "", @@ -262,21 +219,33 @@ bool Method(SyntaxNode node) }; var fixedSource = -$@"using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; - -class C -{{ - bool Method(SyntaxNode node) - {{ - return {prefix}Microsoft.CodeAnalysis.CSharp.CSharpExtensions.{{|#0:IsKind|}}(node, SyntaxKind.None); - }} -}} -"; + $$""" + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + + class C + { + bool Method(SyntaxNode node) + { + return {{prefix}}Microsoft.CodeAnalysis.CSharp.CSharpExtensions.{|#0:IsKind|}(node, SyntaxKind.None); + } + } + """; await new VerifyCS.Test { - TestCode = source, + TestCode = $$""" + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + + class C + { + bool Method(SyntaxNode node) + { + return [|Microsoft.CodeAnalysis.CSharp.CSharpExtensions.Kind(node)|] {{@operator}} SyntaxKind.None; + } + } + """, FixedState = { Sources = { fixedSource }, @@ -294,17 +263,6 @@ bool Method(SyntaxNode node) [InlineData("<>")] public async Task TestCalledAsStaticMethod_VBAsync(string @operator) { - var source = -$@"Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.VisualBasic - -Class C - Function Method(node As SyntaxNode) As Boolean - Return [|Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions.Kind(node)|] {@operator} SyntaxKind.None - End Function -End Class -"; - var prefix = @operator switch { "=" => "", @@ -313,19 +271,29 @@ End Class }; var fixedSource = -$@"Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.VisualBasic + $$""" + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.VisualBasic -Class C - Function Method(node As SyntaxNode) As Boolean - Return {prefix}{{|#0:Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions.IsKind|}}(node, SyntaxKind.None) - End Function -End Class -"; + Class C + Function Method(node As SyntaxNode) As Boolean + Return {{prefix}}{|#0:Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions.IsKind|}(node, SyntaxKind.None) + End Function + End Class + """; await new VerifyVB.Test { - TestCode = source, + TestCode = $""" + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.VisualBasic + + Class C + Function Method(node As SyntaxNode) As Boolean + Return [|Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions.Kind(node)|] {@operator} SyntaxKind.None + End Function + End Class + """, FixedState = { Sources = { fixedSource }, @@ -343,60 +311,56 @@ End Class [InlineData("<>")] public async Task TestVBWithoutParensAsync(string @operator) { - var source = -$@"Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.VisualBasic - -Class C - Function Method(node As SyntaxNode) As Boolean - Return [|node.Kind|] {@operator} SyntaxKind.None - End Function -End Class -"; - var prefix = @operator switch { "=" => "", "<>" => "Not ", _ => throw new InvalidOperationException(), }; - - var fixedSource = -$@"Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.VisualBasic - -Class C - Function Method(node As SyntaxNode) As Boolean - Return {prefix}node.IsKind(SyntaxKind.None) - End Function -End Class -"; - - await VerifyVB.VerifyCodeFixAsync(source, fixedSource); + await VerifyVB.VerifyCodeFixAsync($""" + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.VisualBasic + + Class C + Function Method(node As SyntaxNode) As Boolean + Return [|node.Kind|] {@operator} SyntaxKind.None + End Function + End Class + """, $""" + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.VisualBasic + + Class C + Function Method(node As SyntaxNode) As Boolean + Return {prefix}node.IsKind(SyntaxKind.None) + End Function + End Class + """); } [Fact] public async Task TestSwitchStatement_CSAsync() { var source = -@"using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; + """ + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; -class C -{ - void Method(SyntaxNode node) - { - switch (node.Kind()) - { - case SyntaxKind.NewKeyword: - break; - - case SyntaxKind.None: - break; - } - } -} -"; + class C + { + void Method(SyntaxNode node) + { + switch (node.Kind()) + { + case SyntaxKind.NewKeyword: + break; + + case SyntaxKind.None: + break; + } + } + } + """; await VerifyCS.VerifyCodeFixAsync(source, source); } @@ -405,100 +369,92 @@ void Method(SyntaxNode node) public async Task TestSwitchStatement_VBAsync() { var source = -@"Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.VisualBasic - -Class C - Sub Method(node As SyntaxNode) - Select Case node.Kind() - Case SyntaxKind.NewKeyword - Return - Case Else - Return - End Select - End Sub -End Class -"; + """ + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.VisualBasic + + Class C + Sub Method(node As SyntaxNode) + Select Case node.Kind() + Case SyntaxKind.NewKeyword + Return + Case Else + Return + End Select + End Sub + End Class + """; await VerifyVB.VerifyCodeFixAsync(source, source); } [Fact] [WorkItem(4946, "https://github.com/dotnet/roslyn-analyzers/issues/4946")] - public async Task TestSingleNullConditionalAccess_CSAsync() - { - var source = -@"using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; + public Task TestSingleNullConditionalAccess_CSAsync() + => VerifyCS.VerifyCodeFixAsync(""" + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; -class C -{ - bool Method(SyntaxNode node) - { - return [|node?.Kind()|] == SyntaxKind.None; - } -} -"; - - var fixedSource = -@"using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; - -class C -{ - bool Method(SyntaxNode node) - { - return node.IsKind(SyntaxKind.None); - } -} -"; - - await VerifyCS.VerifyCodeFixAsync(source, fixedSource); - } + class C + { + bool Method(SyntaxNode node) + { + return [|node?.Kind()|] == SyntaxKind.None; + } + } + """, """ + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + + class C + { + bool Method(SyntaxNode node) + { + return node.IsKind(SyntaxKind.None); + } + } + """); [Fact] [WorkItem(4946, "https://github.com/dotnet/roslyn-analyzers/issues/4946")] - public async Task TestSingleNullConditionalAccess_VBAsync() - { - var source = -@"Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.VisualBasic - -Class C - Function Method(node As SyntaxNode) As Boolean - Return [|node?.Kind()|] = SyntaxKind.None - End Function -End Class -"; - var fixedSource = -@"Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.VisualBasic - -Class C - Function Method(node As SyntaxNode) As Boolean - Return node.IsKind(SyntaxKind.None) - End Function -End Class -"; - await VerifyVB.VerifyCodeFixAsync(source, fixedSource); - } + public Task TestSingleNullConditionalAccess_VBAsync() + => VerifyVB.VerifyCodeFixAsync(""" + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.VisualBasic + + Class C + Function Method(node As SyntaxNode) As Boolean + Return [|node?.Kind()|] = SyntaxKind.None + End Function + End Class + """, """ + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.VisualBasic + + Class C + Function Method(node As SyntaxNode) As Boolean + Return node.IsKind(SyntaxKind.None) + End Function + End Class + """); [Fact] [WorkItem(4946, "https://github.com/dotnet/roslyn-analyzers/issues/4946")] public async Task TestSingleNullConditionalAccess_SyntaxToken_CSAsync() { var source = -@"using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; + """ + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; -class C -{ - bool Method(SyntaxToken? token) - { - return token?.Kind() == SyntaxKind.None; - } -} -"; + class C + { + bool Method(SyntaxToken? token) + { + return token?.Kind() == SyntaxKind.None; + } + } + """; await VerifyCS.VerifyCodeFixAsync(source, source); } @@ -508,15 +464,16 @@ bool Method(SyntaxToken? token) public async Task TestSingleNullConditionalAccess_SyntaxToken_VBAsync() { var source = -@"Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.VisualBasic - -Class C - Function Method(token As SyntaxToken?) As Boolean - Return token?.Kind() = SyntaxKind.None - End Function -End Class -"; + """ + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.VisualBasic + + Class C + Function Method(token As SyntaxToken?) As Boolean + Return token?.Kind() = SyntaxKind.None + End Function + End Class + """; await VerifyVB.VerifyCodeFixAsync(source, source); } } diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/ReleaseTrackingAnalyzerTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/ReleaseTrackingAnalyzerTests.cs index 9b2a21c6faed0..d2a3c1537532c 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/ReleaseTrackingAnalyzerTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/ReleaseTrackingAnalyzerTests.cs @@ -22,59 +22,60 @@ public class ReleaseTrackingAnalyzerTests [Fact] public async Task TestNoDeclaredAnalyzersAsync() { - var source = @""; - - var shippedText = @""; - var unshippedText = @""; - - await VerifyCSharpAsync(source, shippedText, unshippedText); + await VerifyCSharpAsync(@"", @"", @""); } [InlineData(@"{|RS2008:""Id1""|}", null, null)] - [InlineData(@"""Id1""", "", null)] - [InlineData(@"""Id1""", null, "")] + [InlineData(""" + "Id1" + """, "", null)] + [InlineData(""" + "Id1" + """, null, "")] [InlineData(@"{|RS2000:""Id1""|}", "", "")] [Theory] public async Task TestMissingReleasesFilesAsync(string id, string shippedText, string unshippedText) { - var source = $@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{{ - // Enabled by default descriptor. - private static readonly DiagnosticDescriptor descriptor1 = - new DiagnosticDescriptor({id}, ""Title1"", ""Message1"", ""Category1"", DiagnosticSeverity.Warning, isEnabledByDefault: true); + await VerifyCSharpAsync($$""" - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); - public override void Initialize(AnalysisContext context) {{ }} -}}"; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - await VerifyCSharpAsync(source, shippedText, unshippedText); + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + // Enabled by default descriptor. + private static readonly DiagnosticDescriptor descriptor1 = + new DiagnosticDescriptor({{id}}, "Title1", "Message1", "Category1", DiagnosticSeverity.Warning, isEnabledByDefault: true); + + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); + public override void Initialize(AnalysisContext context) { } + } + """, shippedText, unshippedText); } [Fact] public async Task TestCodeFixToEnableAnalyzerReleaseTrackingAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + var source = """ -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - new DiagnosticDescriptor({|RS2008:""Id1""|}, ""Title1"", ""Message1"", ""Category1"", DiagnosticSeverity.Warning, isEnabledByDefault: true); + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + new DiagnosticDescriptor({|RS2008:"Id1"|}, "Title1", "Message1", "Category1", DiagnosticSeverity.Warning, isEnabledByDefault: true); - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); - public override void Initialize(AnalysisContext context) { } -}"; + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); + public override void Initialize(AnalysisContext context) { } + } + """; var test = new CSharpCodeFixVerifier.Test() { @@ -146,156 +147,152 @@ public override void Initialize(AnalysisContext context) { } [Theory] public async Task TestReleasesFileAlreadyHasEntryAsync(string shippedText, string unshippedText) { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - // Enabled by default descriptor. - private static readonly DiagnosticDescriptor descriptor1 = - new DiagnosticDescriptor(""Id1"", ""Title1"", ""Message1"", ""Category1"", DiagnosticSeverity.Warning, isEnabledByDefault: true); + await VerifyCSharpAsync(""" - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); - public override void Initialize(AnalysisContext context) {{ }} -}"; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - await VerifyCSharpAsync(source, shippedText, unshippedText); + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + // Enabled by default descriptor. + private static readonly DiagnosticDescriptor descriptor1 = + new DiagnosticDescriptor("Id1", "Title1", "Message1", "Category1", DiagnosticSeverity.Warning, isEnabledByDefault: true); + + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); + public override void Initialize(AnalysisContext context) {{ }} + } + """, shippedText, unshippedText); } [Fact] public async Task TestRemoveUnshippedDeletedDiagnosticIdRuleAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Empty; - public override void Initialize(AnalysisContext context) {{ }} -}"; - var shippedText = @""; var unshippedText = DefaultUnshippedHeader + "Id1 | Category1 | Warning |"; - await VerifyCSharpAsync(source, shippedText, unshippedText, + await VerifyCSharpAsync(""" + + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Empty; + public override void Initialize(AnalysisContext context) {{ }} + } + """, @"", unshippedText, new DiagnosticResult(DiagnosticDescriptorCreationAnalyzer.RemoveUnshippedDeletedDiagnosticIdRule).WithArguments("Id1")); } [Fact] public async Task TestRemoveShippedDeletedDiagnosticIdRuleAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Empty; - public override void Initialize(AnalysisContext context) {{ }} -}"; var shippedText = DefaultShippedHeader + "Id1 | Category1 | Warning |"; - var unshippedText = @""; + await VerifyCSharpAsync(""" + + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - await VerifyCSharpAsync(source, shippedText, unshippedText, + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Empty; + public override void Initialize(AnalysisContext context) {{ }} + } + """, shippedText, @"", new DiagnosticResult(DiagnosticDescriptorCreationAnalyzer.RemoveShippedDeletedDiagnosticIdRule).WithArguments("Id1", "1.0")); } [Fact] public async Task TestCodeFixToAddUnshippedEntriesAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpAdditionalFileFixAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - // Enabled by default descriptor. - private static readonly DiagnosticDescriptor descriptor1 = - new DiagnosticDescriptor({|RS2000:""Id1""|}, ""Title1"", ""Message1"", ""Category1"", DiagnosticSeverity.Warning, isEnabledByDefault: true); - - // Duplicate descriptor with different message. - private static readonly DiagnosticDescriptor descriptor1_dupe = - new DiagnosticDescriptor({|RS2000:""Id1""|}, ""Title1"", ""DifferentMessage"", ""Category1"", DiagnosticSeverity.Warning, isEnabledByDefault: true); - - // Disabled by default descriptor. - private static readonly DiagnosticDescriptor descriptor2 = - new DiagnosticDescriptor({|RS2000:""Id2""|}, ""Title2"", ""Message2"", ""Category2"", DiagnosticSeverity.Warning, isEnabledByDefault: false); - - // Descriptor with help link. - private static readonly DiagnosticDescriptor descriptor3 = - new DiagnosticDescriptor({|RS2000:""Id3""|}, ""Title3"", ""Message3"", ""Category3"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""Dummy""); - - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1, descriptor1_dupe, descriptor2, descriptor3); - public override void Initialize(AnalysisContext context) { } -}"; - - var shippedText = @""; - var unshippedText = @""; - var fixedUnshippedText = -$@"{DefaultUnshippedHeader}Id1 | Category1 | Warning | MyAnalyzer -Id2 | Category2 | Disabled | MyAnalyzer -Id3 | Category3 | Warning | MyAnalyzer, [Documentation](Dummy)"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + // Enabled by default descriptor. + private static readonly DiagnosticDescriptor descriptor1 = + new DiagnosticDescriptor({|RS2000:"Id1"|}, "Title1", "Message1", "Category1", DiagnosticSeverity.Warning, isEnabledByDefault: true); + + // Duplicate descriptor with different message. + private static readonly DiagnosticDescriptor descriptor1_dupe = + new DiagnosticDescriptor({|RS2000:"Id1"|}, "Title1", "DifferentMessage", "Category1", DiagnosticSeverity.Warning, isEnabledByDefault: true); + + // Disabled by default descriptor. + private static readonly DiagnosticDescriptor descriptor2 = + new DiagnosticDescriptor({|RS2000:"Id2"|}, "Title2", "Message2", "Category2", DiagnosticSeverity.Warning, isEnabledByDefault: false); + + // Descriptor with help link. + private static readonly DiagnosticDescriptor descriptor3 = + new DiagnosticDescriptor({|RS2000:"Id3"|}, "Title3", "Message3", "Category3", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "Dummy"); + + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1, descriptor1_dupe, descriptor2, descriptor3); + public override void Initialize(AnalysisContext context) { } + } + """, @"", @"", $""" + {DefaultUnshippedHeader}Id1 | Category1 | Warning | MyAnalyzer + Id2 | Category2 | Disabled | MyAnalyzer + Id3 | Category3 | Warning | MyAnalyzer, [Documentation](Dummy) + """); } [Fact] public async Task TestCodeFixToAddUnshippedEntries_DiagnosticDescriptorHelperAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + var source = """ -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - // Enabled by default descriptor. - private static readonly DiagnosticDescriptor descriptor1 = - DiagnosticDescriptorHelper.Create({|RS2000:""Id1""|}, ""Title1"", ""Message1"", ""Category1"", RuleLevel.BuildWarning); - - // Duplicate descriptor with different message. - private static readonly DiagnosticDescriptor descriptor1_dupe = - DiagnosticDescriptorHelper.Create({|RS2000:""Id1""|}, ""Title1"", ""DifferentMessage"", ""Category1"", RuleLevel.BuildWarning); - - // Disabled by default descriptor. - private static readonly DiagnosticDescriptor descriptor2 = - DiagnosticDescriptorHelper.Create({|RS2000:""Id2""|}, ""Title2"", ""Message2"", ""Category2"", RuleLevel.Disabled); - - // Descriptor with help link. - private static readonly DiagnosticDescriptor descriptor3 = - DiagnosticDescriptorHelper.Create({|RS2000:""Id3""|}, ""Title3"", ""Message3"", ""Category3"", RuleLevel.BuildWarning, helpLinkUri: ""Dummy""); - - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1, descriptor1_dupe, descriptor2, descriptor3); - public override void Initialize(AnalysisContext context) { } -}" + CSharpDiagnosticDescriptorCreationHelper; - - var shippedText = @""; - var unshippedText = @""; - var fixedUnshippedText = -$@"{DefaultUnshippedHeader}Id1 | Category1 | Warning | MyAnalyzer -Id2 | Category2 | Disabled | MyAnalyzer -Id3 | Category3 | Warning | MyAnalyzer, [Documentation](Dummy)"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + // Enabled by default descriptor. + private static readonly DiagnosticDescriptor descriptor1 = + DiagnosticDescriptorHelper.Create({|RS2000:"Id1"|}, "Title1", "Message1", "Category1", RuleLevel.BuildWarning); + + // Duplicate descriptor with different message. + private static readonly DiagnosticDescriptor descriptor1_dupe = + DiagnosticDescriptorHelper.Create({|RS2000:"Id1"|}, "Title1", "DifferentMessage", "Category1", RuleLevel.BuildWarning); + + // Disabled by default descriptor. + private static readonly DiagnosticDescriptor descriptor2 = + DiagnosticDescriptorHelper.Create({|RS2000:"Id2"|}, "Title2", "Message2", "Category2", RuleLevel.Disabled); + + // Descriptor with help link. + private static readonly DiagnosticDescriptor descriptor3 = + DiagnosticDescriptorHelper.Create({|RS2000:"Id3"|}, "Title3", "Message3", "Category3", RuleLevel.BuildWarning, helpLinkUri: "Dummy"); + + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1, descriptor1_dupe, descriptor2, descriptor3); + public override void Initialize(AnalysisContext context) { } + } + """ + CSharpDiagnosticDescriptorCreationHelper; + await VerifyCSharpAdditionalFileFixAsync(source, @"", @"", $""" + {DefaultUnshippedHeader}Id1 | Category1 | Warning | MyAnalyzer + Id2 | Category2 | Disabled | MyAnalyzer + Id3 | Category3 | Warning | MyAnalyzer, [Documentation](Dummy) + """); } - private const string BlankLine = @" -"; + private const string BlankLine = """ + + + """; // Comments [InlineData(DefaultUnshippedHeader + @"; Comments are preserved" + BlankLine, @@ -309,24 +306,23 @@ public override void Initialize(AnalysisContext context) { } [Theory] public async Task TestCodeFixToAddUnshippedEntries_TriviaIsPreservedAsync(string unshippedText, string fixedUnshippedText) { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpAdditionalFileFixAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - new DiagnosticDescriptor({|RS2000:""Id1""|}, ""Title1"", ""Message1"", ""Category1"", DiagnosticSeverity.Warning, isEnabledByDefault: true); + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); - public override void Initialize(AnalysisContext context) { } -}"; + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + new DiagnosticDescriptor({|RS2000:"Id1"|}, "Title1", "Message1", "Category1", DiagnosticSeverity.Warning, isEnabledByDefault: true); - var shippedText = @""; - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); + public override void Initialize(AnalysisContext context) { } + } + """, @"", unshippedText, fixedUnshippedText); } // Added after current entry. @@ -346,26 +342,26 @@ public override void Initialize(AnalysisContext context) { } [Theory] public async Task TestCodeFixToAddUnshippedEntries_AlreadyHasDifferentUnshippedEntriesAsync(string differentRuleId, string unshippedText, string fixedUnshippedText, string shippedText = "") { - var source = $@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpAdditionalFileFixAsync($$""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{{ - private static readonly DiagnosticDescriptor descriptor1 = - new DiagnosticDescriptor({{|RS2000:""Id1""|}}, ""Title1"", ""Message1"", ""Category1"", DiagnosticSeverity.Warning, isEnabledByDefault: true); + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - private static readonly DiagnosticDescriptor descriptor2 = - new DiagnosticDescriptor(""{differentRuleId}"", ""DifferentTitle"", ""DifferentMessage"", ""DifferentCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true); + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + new DiagnosticDescriptor({|RS2000:"Id1"|}, "Title1", "Message1", "Category1", DiagnosticSeverity.Warning, isEnabledByDefault: true); - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1, descriptor2); - public override void Initialize(AnalysisContext context) {{ }} -}}"; + private static readonly DiagnosticDescriptor descriptor2 = + new DiagnosticDescriptor("{{differentRuleId}}", "DifferentTitle", "DifferentMessage", "DifferentCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1, descriptor2); + public override void Initialize(AnalysisContext context) { } + } + """, shippedText, unshippedText, fixedUnshippedText); } // Adds to existing new rules table and creates a new changed rules table. @@ -379,29 +375,29 @@ public override void Initialize(AnalysisContext context) {{ }} [Theory] public async Task TestCodeFixToAddUnshippedEntriesToMultipleTablesAsync(string unshippedText, string fixedUnshippedText, string shippedText = "") { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpAdditionalFileFixAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor0 = - new DiagnosticDescriptor(""Id0"", ""Title0"", ""Message0"", ""Category0"", DiagnosticSeverity.Warning, isEnabledByDefault: true); + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - private static readonly DiagnosticDescriptor descriptor1 = - new DiagnosticDescriptor({|RS2000:""Id1""|}, ""Title1"", ""Message1"", ""Category1"", DiagnosticSeverity.Warning, isEnabledByDefault: true); + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor0 = + new DiagnosticDescriptor("Id0", "Title0", "Message0", "Category0", DiagnosticSeverity.Warning, isEnabledByDefault: true); - private static readonly DiagnosticDescriptor descriptor2 = - new DiagnosticDescriptor({|RS2001:""Id2""|}, ""DifferentTitle"", ""DifferentMessage"", ""DifferentCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true); + private static readonly DiagnosticDescriptor descriptor1 = + new DiagnosticDescriptor({|RS2000:"Id1"|}, "Title1", "Message1", "Category1", DiagnosticSeverity.Warning, isEnabledByDefault: true); - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor0, descriptor1, descriptor2); - public override void Initialize(AnalysisContext context) { } -}"; + private static readonly DiagnosticDescriptor descriptor2 = + new DiagnosticDescriptor({|RS2001:"Id2"|}, "DifferentTitle", "DifferentMessage", "DifferentCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor0, descriptor1, descriptor2); + public override void Initialize(AnalysisContext context) { } + } + """, shippedText, unshippedText, fixedUnshippedText); } [InlineData("", @@ -419,104 +415,95 @@ public override void Initialize(AnalysisContext context) { } [Theory] public async Task TestCodeFixToAddUnshippedEntries_AlreadyHasDifferentShippedEntryAsync(string shippedText, string fixedUnshippedText, string expectedDiagnosticId) { - var source = $@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{{ - // Enabled by default descriptor. - private static readonly DiagnosticDescriptor descriptor1 = - new DiagnosticDescriptor({{|{expectedDiagnosticId}:""Id1""|}}, ""Title1"", ""Message1"", ""Category1"", DiagnosticSeverity.Warning, isEnabledByDefault: true); - - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); - public override void Initialize(AnalysisContext context) {{ }} -}}"; - - var unshippedText = @""; - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); + await VerifyCSharpAdditionalFileFixAsync($$""" + + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + // Enabled by default descriptor. + private static readonly DiagnosticDescriptor descriptor1 = + new DiagnosticDescriptor({|{{expectedDiagnosticId}}:"Id1"|}, "Title1", "Message1", "Category1", DiagnosticSeverity.Warning, isEnabledByDefault: true); + + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); + public override void Initialize(AnalysisContext context) { } + } + """, shippedText, @"", fixedUnshippedText); } [Fact] public async Task TestCodeFixToUpdateMultipleUnshippedEntriesAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - // Enabled by default descriptor. - private static readonly DiagnosticDescriptor descriptor1 = - new DiagnosticDescriptor({|RS2001:""Id1""|}, ""Title1"", ""Message1"", ""Category1"", DiagnosticSeverity.Warning, isEnabledByDefault: true); - - // Disable by default descriptor. - private static readonly DiagnosticDescriptor descriptor2 = - new DiagnosticDescriptor({|RS2001:""Id2""|}, ""Title2"", ""Message2"", ""Category2"", DiagnosticSeverity.Warning, isEnabledByDefault: false); - - // Descriptor with help - ensure that just adding a help link does not require a new analyzer release entry. - private static readonly DiagnosticDescriptor descriptor3 = - new DiagnosticDescriptor(""Id3"", ""Title3"", ""Message3"", ""Category3"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""Dummy""); - - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1, descriptor2, descriptor3); - public override void Initialize(AnalysisContext context) { } -}"; - - var shippedText = @""; + await VerifyCSharpAdditionalFileFixAsync(""" - var unshippedText = -$@"{DefaultUnshippedHeader}Id1 | DifferentCategory | Warning | MyAnalyzer -Id2 | Category2 | Warning | MyAnalyzer -Id3 | Category3 | Warning | MyAnalyzer"; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - var fixedUnshippedText = -$@"{DefaultUnshippedHeader}Id1 | Category1 | Warning | MyAnalyzer -Id2 | Category2 | Disabled | MyAnalyzer -Id3 | Category3 | Warning | MyAnalyzer"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + // Enabled by default descriptor. + private static readonly DiagnosticDescriptor descriptor1 = + new DiagnosticDescriptor({|RS2001:"Id1"|}, "Title1", "Message1", "Category1", DiagnosticSeverity.Warning, isEnabledByDefault: true); + + // Disable by default descriptor. + private static readonly DiagnosticDescriptor descriptor2 = + new DiagnosticDescriptor({|RS2001:"Id2"|}, "Title2", "Message2", "Category2", DiagnosticSeverity.Warning, isEnabledByDefault: false); + + // Descriptor with help - ensure that just adding a help link does not require a new analyzer release entry. + private static readonly DiagnosticDescriptor descriptor3 = + new DiagnosticDescriptor("Id3", "Title3", "Message3", "Category3", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "Dummy"); + + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1, descriptor2, descriptor3); + public override void Initialize(AnalysisContext context) { } + } + """, @"", $""" + {DefaultUnshippedHeader}Id1 | DifferentCategory | Warning | MyAnalyzer + Id2 | Category2 | Warning | MyAnalyzer + Id3 | Category3 | Warning | MyAnalyzer + """, $""" + {DefaultUnshippedHeader}Id1 | Category1 | Warning | MyAnalyzer + Id2 | Category2 | Disabled | MyAnalyzer + Id3 | Category3 | Warning | MyAnalyzer + """); } [Fact] public async Task TestCodeFixToAddUnshippedEntries_UndetectedFieldsAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -public static class DiagnosticDescriptorHelper -{ - public static DiagnosticDescriptor Create( - string id, - LocalizableString title, - LocalizableString messageFormat) - => null; -} - -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - DiagnosticDescriptorHelper.Create({|RS2000:""Id1""|}, ""Title1"", ""Message1""); + var entry = $@"Id1 | {ReleaseTrackingHelper.UndetectedText} | {ReleaseTrackingHelper.UndetectedText} | MyAnalyzer"; + await VerifyCSharpAdditionalFileFixAsync(""" - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); - public override void Initialize(AnalysisContext context) { } -}"; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - var shippedText = @""; - var unshippedText = @""; - var entry = $@"Id1 | {ReleaseTrackingHelper.UndetectedText} | {ReleaseTrackingHelper.UndetectedText} | MyAnalyzer"; - var fixedUnshippedText = $@"{DefaultUnshippedHeader}{entry}"; + public static class DiagnosticDescriptorHelper + { + public static DiagnosticDescriptor Create( + string id, + LocalizableString title, + LocalizableString messageFormat) + => null; + } + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + DiagnosticDescriptorHelper.Create({|RS2000:"Id1"|}, "Title1", "Message1"); - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText, additionalExpectedDiagnosticsInInput: ImmutableArray.Empty, + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); + public override void Initialize(AnalysisContext context) { } + } + """, @"", @"", $@"{DefaultUnshippedHeader}{entry}", additionalExpectedDiagnosticsInInput: ImmutableArray.Empty, additionalExpectedDiagnosticsInResult: ImmutableArray.Create( GetAdditionalFileResultAt(5, 1, ReleaseTrackingHelper.UnshippedFileName, @@ -528,35 +515,32 @@ await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fix [Fact] public async Task TestNoCodeFixToAddUnshippedEntries_UndetectedFieldsAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -public static class DiagnosticDescriptorHelper -{ - public static DiagnosticDescriptor Create( - string id, - LocalizableString title, - LocalizableString messageFormat) - => null; -} + await VerifyCSharpAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - DiagnosticDescriptorHelper.Create(""Id1"", ""Title1"", ""Message1""); + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); - public override void Initialize(AnalysisContext context) { } -}"; - - var shippedText = @""; - var unshippedText = $@"{DefaultUnshippedHeader}Id1 | CustomCategory | Warning |"; + public static class DiagnosticDescriptorHelper + { + public static DiagnosticDescriptor Create( + string id, + LocalizableString title, + LocalizableString messageFormat) + => null; + } + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + DiagnosticDescriptorHelper.Create("Id1", "Title1", "Message1"); - await VerifyCSharpAsync(source, shippedText, unshippedText); + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); + public override void Initialize(AnalysisContext context) { } + } + """, @"", $@"{DefaultUnshippedHeader}Id1 | CustomCategory | Warning |"); } // No header in unshipped @@ -598,25 +582,25 @@ public override void Initialize(AnalysisContext context) { } [Theory] public async Task TestInvalidHeaderDiagnosticAsync(string shippedText, string unshippedText, int line = 1) { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + var fileWithDiagnostics = shippedText.Length > 0 ? ReleaseTrackingHelper.ShippedFileName : ReleaseTrackingHelper.UnshippedFileName; + var diagnosticText = (shippedText.Length > 0 ? shippedText : unshippedText).Split([Environment.NewLine], StringSplitOptions.None).ElementAt(line - 1); + await VerifyCSharpAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - new DiagnosticDescriptor(""Id1"", ""Title1"", ""Message1"", ""Category1"", DiagnosticSeverity.Warning, isEnabledByDefault: true); + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); - public override void Initialize(AnalysisContext context) { } -}"; + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + new DiagnosticDescriptor("Id1", "Title1", "Message1", "Category1", DiagnosticSeverity.Warning, isEnabledByDefault: true); - var fileWithDiagnostics = shippedText.Length > 0 ? ReleaseTrackingHelper.ShippedFileName : ReleaseTrackingHelper.UnshippedFileName; - var diagnosticText = (shippedText.Length > 0 ? shippedText : unshippedText).Split(new[] { Environment.NewLine }, StringSplitOptions.None).ElementAt(line - 1); - await VerifyCSharpAsync(source, shippedText, unshippedText, + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); + public override void Initialize(AnalysisContext context) { } + } + """, shippedText, unshippedText, GetAdditionalFileResultAt(line, 1, fileWithDiagnostics, DiagnosticDescriptorCreationAnalyzer.InvalidHeaderInAnalyzerReleasesFileRule, @@ -643,29 +627,28 @@ await VerifyCSharpAsync(source, shippedText, unshippedText, [Theory] public async Task TestInvalidEntryDiagnosticAsync(string entry, bool hasUndetectedField) { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - new DiagnosticDescriptor(""Id1"", ""Title1"", ""Message1"", ""Category1"", DiagnosticSeverity.Warning, isEnabledByDefault: true); - - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); - public override void Initialize(AnalysisContext context) { } -}"; var rule = hasUndetectedField ? DiagnosticDescriptorCreationAnalyzer.InvalidUndetectedEntryInAnalyzerReleasesFileRule : DiagnosticDescriptorCreationAnalyzer.InvalidEntryInAnalyzerReleasesFileRule; - - var shippedText = @""; var unshippedText = DefaultUnshippedHeader + entry; - await VerifyCSharpAsync(source, shippedText, unshippedText, + await VerifyCSharpAsync(""" + + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + new DiagnosticDescriptor("Id1", "Title1", "Message1", "Category1", DiagnosticSeverity.Warning, isEnabledByDefault: true); + + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); + public override void Initialize(AnalysisContext context) { } + } + """, @"", unshippedText, GetAdditionalFileResultAt(5, 1, ReleaseTrackingHelper.UnshippedFileName, rule, @@ -704,29 +687,28 @@ await VerifyCSharpAsync(source, shippedText, unshippedText, [Theory] public async Task TestInvalidEntryDiagnostic_ChangedRulesAsync(string entry, bool hasUndetectedField) { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - new DiagnosticDescriptor(""Id1"", ""Title1"", ""Message1"", ""Category1"", DiagnosticSeverity.Warning, isEnabledByDefault: true); - - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); - public override void Initialize(AnalysisContext context) { } -}"; var rule = hasUndetectedField ? DiagnosticDescriptorCreationAnalyzer.InvalidUndetectedEntryInAnalyzerReleasesFileRule : DiagnosticDescriptorCreationAnalyzer.InvalidEntryInAnalyzerReleasesFileRule; - - var shippedText = @""; var unshippedText = DefaultChangedUnshippedHeader + entry; - await VerifyCSharpAsync(source, shippedText, unshippedText, + await VerifyCSharpAsync(""" + + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + new DiagnosticDescriptor("Id1", "Title1", "Message1", "Category1", DiagnosticSeverity.Warning, isEnabledByDefault: true); + + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); + public override void Initialize(AnalysisContext context) { } + } + """, @"", unshippedText, GetAdditionalFileResultAt(5, 1, ReleaseTrackingHelper.UnshippedFileName, rule, @@ -751,22 +733,23 @@ await VerifyCSharpAsync(source, shippedText, unshippedText, [Theory] public async Task TestDuplicateEntryInReleaseDiagnosticAsync(string shippedText, string unshippedText) { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - new DiagnosticDescriptor(""Id1"", ""Title1"", ""Message1"", ""Category1"", DiagnosticSeverity.Warning, isEnabledByDefault: true); + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); - public override void Initialize(AnalysisContext context) { } -}"; - await VerifyCSharpAsync(source, shippedText, unshippedText); + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + new DiagnosticDescriptor("Id1", "Title1", "Message1", "Category1", DiagnosticSeverity.Warning, isEnabledByDefault: true); + + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); + public override void Initialize(AnalysisContext context) { } + } + """, shippedText, unshippedText); } // Duplicate entries across shipped and unshipped. @@ -786,22 +769,23 @@ public override void Initialize(AnalysisContext context) { } [Theory] public async Task TestDuplicateEntryBetweenReleasesDiagnosticAsync(string shippedText, string unshippedText) { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - new DiagnosticDescriptor(""Id1"", ""Title1"", ""Message1"", ""Category1"", DiagnosticSeverity.Warning, isEnabledByDefault: true); + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); - public override void Initialize(AnalysisContext context) { } -}"; - await VerifyCSharpAsync(source, shippedText, unshippedText); + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + new DiagnosticDescriptor("Id1", "Title1", "Message1", "Category1", DiagnosticSeverity.Warning, isEnabledByDefault: true); + + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); + public override void Initialize(AnalysisContext context) { } + } + """, shippedText, unshippedText); } // Remove entry in unshipped for already shipped release. @@ -813,22 +797,23 @@ public override void Initialize(AnalysisContext context) { } [Theory] public async Task TestRemoveEntryInReleaseFile_DiagnosticCasesAsync(string shippedText, string unshippedText, string expectedDiagnosticId) { - var source = $@" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{{ - private static readonly DiagnosticDescriptor descriptor1 = - new DiagnosticDescriptor({{|{expectedDiagnosticId}:""Id1""|}}, ""Title1"", ""Message1"", ""Category1"", DiagnosticSeverity.Warning, isEnabledByDefault: true); - - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); - public override void Initialize(AnalysisContext context) {{ }} -}}"; - await VerifyCSharpAsync(source, shippedText, unshippedText); + await VerifyCSharpAsync($$""" + + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + new DiagnosticDescriptor({|{{expectedDiagnosticId}}:"Id1"|}, "Title1", "Message1", "Category1", DiagnosticSeverity.Warning, isEnabledByDefault: true); + + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); + public override void Initialize(AnalysisContext context) { } + } + """, shippedText, unshippedText); } // Invalid remove entry without prior shipped entry in shipped. @@ -838,21 +823,22 @@ public override void Initialize(AnalysisContext context) {{ }} [Theory] public async Task TestInvalidRemoveWithoutShippedEntryInReleaseFileAsync(string shippedText, string unshippedText) { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Empty; - public override void Initialize(AnalysisContext context) { } -}"; var fileWithDiagnostics = shippedText.Length > 0 ? ReleaseTrackingHelper.ShippedFileName : ReleaseTrackingHelper.UnshippedFileName; - var lineCount = (shippedText.Length > 0 ? shippedText : unshippedText).Split(new[] { Environment.NewLine }, StringSplitOptions.None).Length; - await VerifyCSharpAsync(source, shippedText, unshippedText, + var lineCount = (shippedText.Length > 0 ? shippedText : unshippedText).Split([Environment.NewLine], StringSplitOptions.None).Length; + await VerifyCSharpAsync(""" + + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Empty; + public override void Initialize(AnalysisContext context) { } + } + """, shippedText, unshippedText, GetAdditionalFileResultAt(lineCount, 1, fileWithDiagnostics, DiagnosticDescriptorCreationAnalyzer.InvalidRemovedOrChangedWithoutPriorNewEntryInAnalyzerReleasesFileRule, @@ -868,24 +854,25 @@ await VerifyCSharpAsync(source, shippedText, unshippedText, [Theory] public async Task TestInvalidChangedWithoutShippedEntryInReleaseFileAsync(string shippedText, string unshippedText) { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + var fileWithDiagnostics = shippedText.Length > 0 ? ReleaseTrackingHelper.ShippedFileName : ReleaseTrackingHelper.UnshippedFileName; + var lineCount = (shippedText.Length > 0 ? shippedText : unshippedText).Split([Environment.NewLine], StringSplitOptions.None).Length; + await VerifyCSharpAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - new DiagnosticDescriptor(""Id1"", ""Title1"", ""Message1"", ""Category1"", DiagnosticSeverity.Hidden, isEnabledByDefault: true); + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); - public override void Initialize(AnalysisContext context) { } -}"; - var fileWithDiagnostics = shippedText.Length > 0 ? ReleaseTrackingHelper.ShippedFileName : ReleaseTrackingHelper.UnshippedFileName; - var lineCount = (shippedText.Length > 0 ? shippedText : unshippedText).Split(new[] { Environment.NewLine }, StringSplitOptions.None).Length; - await VerifyCSharpAsync(source, shippedText, unshippedText, + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + new DiagnosticDescriptor("Id1", "Title1", "Message1", "Category1", DiagnosticSeverity.Hidden, isEnabledByDefault: true); + + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); + public override void Initialize(AnalysisContext context) { } + } + """, shippedText, unshippedText, GetAdditionalFileResultAt(lineCount, 1, fileWithDiagnostics, DiagnosticDescriptorCreationAnalyzer.InvalidRemovedOrChangedWithoutPriorNewEntryInAnalyzerReleasesFileRule, @@ -901,23 +888,24 @@ await VerifyCSharpAsync(source, shippedText, unshippedText, [Theory] public async Task TestInvalidRemoveWithoutShippedEntryInReleaseFile_02Async(string shippedText, string unshippedText) { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + var fileWithDiagnostics = shippedText.Length > 0 ? ReleaseTrackingHelper.ShippedFileName : ReleaseTrackingHelper.UnshippedFileName; + await VerifyCSharpAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - new DiagnosticDescriptor(""Id1"", ""Title1"", ""Message1"", ""Category1"", DiagnosticSeverity.Warning, isEnabledByDefault: true); + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); - public override void Initialize(AnalysisContext context) { } -}"; - var fileWithDiagnostics = shippedText.Length > 0 ? ReleaseTrackingHelper.ShippedFileName : ReleaseTrackingHelper.UnshippedFileName; - await VerifyCSharpAsync(source, shippedText, unshippedText, + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + new DiagnosticDescriptor("Id1", "Title1", "Message1", "Category1", DiagnosticSeverity.Warning, isEnabledByDefault: true); + + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); + public override void Initialize(AnalysisContext context) { } + } + """, shippedText, unshippedText, GetAdditionalFileResultAt(7, 1, fileWithDiagnostics, DiagnosticDescriptorCreationAnalyzer.InvalidRemovedOrChangedWithoutPriorNewEntryInAnalyzerReleasesFileRule, @@ -935,44 +923,42 @@ await VerifyCSharpAsync(source, shippedText, unshippedText, [Theory] public async Task TestRemoveEntryInReleaseFile_NoDiagnosticCasesAsync(string shippedText, string unshippedText) { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCSharpAsync(""" -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Empty; - public override void Initialize(AnalysisContext context) { } -}"; - await VerifyCSharpAsync(source, shippedText, unshippedText); + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Empty; + public override void Initialize(AnalysisContext context) { } + } + """, shippedText, unshippedText); } [Fact, WorkItem(5828, "https://github.com/dotnet/roslyn-analyzers/issues/5828")] public async Task TestTargetTypedNew() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] -class MyAnalyzer : DiagnosticAnalyzer -{ - private static readonly DiagnosticDescriptor descriptor1 = - new(""Id1"", ""Title1"", ""Message1"", ""Category1"", DiagnosticSeverity.Warning, isEnabledByDefault: true); + await VerifyCSharpAsync(""" - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); - public override void Initialize(AnalysisContext context) { } -}"; + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - var shippedText = @""; - var unshippedText = $@"{DefaultUnshippedHeader}Id1 | Category1 | Warning |"; + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + class MyAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor descriptor1 = + new("Id1", "Title1", "Message1", "Category1", DiagnosticSeverity.Warning, isEnabledByDefault: true); - await VerifyCSharpAsync(source, shippedText, unshippedText); + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor1); + public override void Initialize(AnalysisContext context) { } + } + """, @"", $@"{DefaultUnshippedHeader}Id1 | Category1 | Warning |"); } #region Helpers @@ -1102,31 +1088,33 @@ private async Task VerifyAdditionalFileFixAsync(string language, string source, await test.RunAsync(); } - private const string CSharpDiagnosticDescriptorCreationHelper = @" -internal static class DiagnosticDescriptorHelper -{ - // Dummy DiagnosticDescriptor creation helper. - public static DiagnosticDescriptor Create( - string id, - LocalizableString title, - LocalizableString messageFormat, - string category, - RuleLevel ruleLevel, - string helpLinkUri = null) - => null; -} + private const string CSharpDiagnosticDescriptorCreationHelper = """ -namespace Microsoft.CodeAnalysis -{ - internal enum RuleLevel - { - BuildWarning = 1, - IdeSuggestion = 2, - IdeHidden_BulkConfigurable = 3, - Disabled = 4, - CandidateForRemoval = 5, - } -}"; + internal static class DiagnosticDescriptorHelper + { + // Dummy DiagnosticDescriptor creation helper. + public static DiagnosticDescriptor Create( + string id, + LocalizableString title, + LocalizableString messageFormat, + string category, + RuleLevel ruleLevel, + string helpLinkUri = null) + => null; + } + + namespace Microsoft.CodeAnalysis + { + internal enum RuleLevel + { + BuildWarning = 1, + IdeSuggestion = 2, + IdeHidden_BulkConfigurable = 3, + Disabled = 4, + CandidateForRemoval = 5, + } + } + """; #endregion } } diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/SemanticModelGetDeclaredSymbolAlwaysReturnsNullAnalyzerTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/SemanticModelGetDeclaredSymbolAlwaysReturnsNullAnalyzerTests.cs index 7a81cb09a8127..40f6466d31baa 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/SemanticModelGetDeclaredSymbolAlwaysReturnsNullAnalyzerTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/SemanticModelGetDeclaredSymbolAlwaysReturnsNullAnalyzerTests.cs @@ -24,19 +24,18 @@ public sealed class SemanticModelGetDeclaredSymbolAlwaysReturnsNullAnalyzerTests [InlineData("LockStatementSyntax")] public Task Diagnostic(string type) { - var code = $@" -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.Syntax; - -public class Test {{ - public void M(SemanticModel semanticModel, {type} syntax) {{ - var x = {{|#0:semanticModel.GetDeclaredSymbol(syntax)|}}; - }} -}}"; - return new VerifyCS.Test { - TestCode = code, + TestCode = $$""" + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp.Syntax; + + public class Test { + public void M(SemanticModel semanticModel, {{type}} syntax) { + var x = {|#0:semanticModel.GetDeclaredSymbol(syntax)|}; + } + } + """, ExpectedDiagnostics = { new DiagnosticResult(CSharpSemanticModelGetDeclaredSymbolAlwaysReturnsNullAnalyzer.DiagnosticDescriptor).WithLocation(0).WithArguments(type) } }.RunAsync(); } @@ -47,19 +46,18 @@ public void M(SemanticModel semanticModel, {type} syntax) {{ [InlineData("EventFieldDeclarationSyntax")] public Task Field_Diagnostic(string type) { - var code = $@" -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.Syntax; - -public class Test {{ - public void M(SemanticModel semanticModel, {type} syntax) {{ - var x = {{|#0:semanticModel.GetDeclaredSymbol(syntax)|}}; - }} -}}"; - return new VerifyCS.Test { - TestCode = code, + TestCode = $$""" + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp.Syntax; + + public class Test { + public void M(SemanticModel semanticModel, {{type}} syntax) { + var x = {|#0:semanticModel.GetDeclaredSymbol(syntax)|}; + } + } + """, ExpectedDiagnostics = { new DiagnosticResult(CSharpSemanticModelGetDeclaredSymbolAlwaysReturnsNullAnalyzer.FieldDiagnosticDescriptor).WithLocation(0).WithArguments(type) } }.RunAsync(); } @@ -72,31 +70,31 @@ public void M(SemanticModel semanticModel, {type} syntax) {{ [InlineData("NamespaceDeclarationSyntax")] public Task NoDiagnostic(string type) { - var code = $@" -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.Syntax; - -public class Test {{ - public void M(SemanticModel semanticModel, {type} syntax) {{ - var x = semanticModel.GetDeclaredSymbol(syntax); - }} -}}"; - - return VerifyCS.VerifyAnalyzerAsync(code); + return VerifyCS.VerifyAnalyzerAsync($$""" + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp.Syntax; + + public class Test { + public void M(SemanticModel semanticModel, {{type}} syntax) { + var x = semanticModel.GetDeclaredSymbol(syntax); + } + } + """); } [Fact] public Task NoDiagnosticForCompilationError() { - const string code = @" -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.Syntax; - -public class Test { - public void M(SemanticModel semanticModel) { - var x = semanticModel.{|CS7036:GetDeclaredSymbol|}(); - } -}"; + const string code = """ + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp.Syntax; + + public class Test { + public void M(SemanticModel semanticModel) { + var x = semanticModel.{|CS7036:GetDeclaredSymbol|}(); + } + } + """; return VerifyCS.VerifyAnalyzerAsync(code); } diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/StartActionWithNoRegisteredActionsRuleTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/StartActionWithNoRegisteredActionsRuleTests.cs index 8b1ed69a0742c..35c12f6375c18 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/StartActionWithNoRegisteredActionsRuleTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/StartActionWithNoRegisteredActionsRuleTests.cs @@ -22,484 +22,473 @@ public class StartActionWithNoRegisteredActionsRuleTests [Fact] public async Task CSharp_VerifyDiagnosticAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -class MyAnalyzer : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics - { - get - { - throw new NotImplementedException(); - } - } - - public override void Initialize(AnalysisContext context) - { - context.RegisterCompilationStartAction(compilationContext => - { - }); - - context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.InvocationExpression); - context.RegisterCodeBlockStartAction(AnalyzeCodeBlockStart); - context.RegisterOperationBlockStartAction(AnalyzeOperationBlockStart); - } - - private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) - { - } - - private static void AnalyzeCodeBlockStart(CodeBlockStartAnalysisContext codeBlockContext) - { - } - - private static void AnalyzeOperationBlockStart(OperationBlockStartAnalysisContext operationBlockContext) - { - } -}"; - DiagnosticResult[] expected = new[] - { - GetCSharpExpectedDiagnostic(21, 48, parameterName: "compilationContext", kind: StartActionKind.CompilationStartAction), - GetCSharpExpectedDiagnostic(34, 47, parameterName: "codeBlockContext", kind: StartActionKind.CodeBlockStartAction), - GetCSharpExpectedDiagnostic(38, 52, parameterName: "operationBlockContext", kind: StartActionKind.OperationBlockStartAction) - }; - - await VerifyCS.VerifyAnalyzerAsync(source, expected); + DiagnosticResult[] expected = + [ + GetCSharpExpectedDiagnostic(20, 48, parameterName: "compilationContext", kind: StartActionKind.CompilationStartAction), + GetCSharpExpectedDiagnostic(33, 47, parameterName: "codeBlockContext", kind: StartActionKind.CodeBlockStartAction), + GetCSharpExpectedDiagnostic(37, 52, parameterName: "operationBlockContext", kind: StartActionKind.OperationBlockStartAction) + ]; + + await VerifyCS.VerifyAnalyzerAsync(""" + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + class MyAnalyzer : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } + + public override void Initialize(AnalysisContext context) + { + context.RegisterCompilationStartAction(compilationContext => + { + }); + + context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.InvocationExpression); + context.RegisterCodeBlockStartAction(AnalyzeCodeBlockStart); + context.RegisterOperationBlockStartAction(AnalyzeOperationBlockStart); + } + + private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) + { + } + + private static void AnalyzeCodeBlockStart(CodeBlockStartAnalysisContext codeBlockContext) + { + } + + private static void AnalyzeOperationBlockStart(OperationBlockStartAnalysisContext operationBlockContext) + { + } + } + """, expected); } [Fact] public async Task VisualBasic_VerifyDiagnosticAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - context.RegisterCompilationStartAction( - Sub(compilationContext As CompilationStartAnalysisContext) - End Sub - ) - - context.RegisterSyntaxNodeAction(AddressOf AnalyzeSyntax, SyntaxKind.InvocationExpression) - context.RegisterCodeBlockStartAction(Of SyntaxKind)(AddressOf AnalyzeCodeBlockStart) - context.RegisterOperationBlockStartAction(AddressOf AnalyzeOperationBlockStart) - End Sub - - Private Shared Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext) - End Sub - - Private Shared Sub AnalyzeCodeBlockStart(codeBlockContext As CodeBlockStartAnalysisContext(Of SyntaxKind)) - End Sub - - Private Shared Sub AnalyzeOperationBlockStart(operationBlockContext As OperationBlockStartAnalysisContext) - End Sub -End Class -"; - DiagnosticResult[] expected = new[] - { - GetBasicExpectedDiagnostic(19, 17, parameterName: "compilationContext", kind: StartActionKind.CompilationStartAction), - GetBasicExpectedDiagnostic(31, 46, parameterName: "codeBlockContext", kind: StartActionKind.CodeBlockStartAction), - GetBasicExpectedDiagnostic(34, 51, parameterName: "operationBlockContext", kind: StartActionKind.OperationBlockStartAction) - }; + DiagnosticResult[] expected = + [ + GetBasicExpectedDiagnostic(18, 17, parameterName: "compilationContext", kind: StartActionKind.CompilationStartAction), + GetBasicExpectedDiagnostic(30, 46, parameterName: "codeBlockContext", kind: StartActionKind.CodeBlockStartAction), + GetBasicExpectedDiagnostic(33, 51, parameterName: "operationBlockContext", kind: StartActionKind.OperationBlockStartAction) + ]; + + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.VisualBasic + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + context.RegisterCompilationStartAction( + Sub(compilationContext As CompilationStartAnalysisContext) + End Sub + ) + + context.RegisterSyntaxNodeAction(AddressOf AnalyzeSyntax, SyntaxKind.InvocationExpression) + context.RegisterCodeBlockStartAction(Of SyntaxKind)(AddressOf AnalyzeCodeBlockStart) + context.RegisterOperationBlockStartAction(AddressOf AnalyzeOperationBlockStart) + End Sub + + Private Shared Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext) + End Sub + + Private Shared Sub AnalyzeCodeBlockStart(codeBlockContext As CodeBlockStartAnalysisContext(Of SyntaxKind)) + End Sub - await VerifyVB.VerifyAnalyzerAsync(source, expected); + Private Shared Sub AnalyzeOperationBlockStart(operationBlockContext As OperationBlockStartAnalysisContext) + End Sub + End Class + """, expected); } [Fact] public async Task CSharp_NoDiagnosticCasesAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -abstract class MyAnalyzer : DiagnosticAnalyzer - where T : struct -{ - public override ImmutableArray SupportedDiagnostics - { - get - { - throw new NotImplementedException(); - } - } - - public override void Initialize(AnalysisContext context) - { - context.RegisterCompilationStartAction(compilationContext => - { - compilationContext.RegisterCodeBlockStartAction(AnalyzeCodeBlockStart); - }); - } - - private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) - { - } - - private static void AnalyzeCodeBlockStart(CodeBlockStartAnalysisContext context) - { - context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.InvocationExpression); - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(source); + await VerifyCS.VerifyAnalyzerAsync(""" + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + abstract class MyAnalyzer : DiagnosticAnalyzer + where T : struct + { + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } + + public override void Initialize(AnalysisContext context) + { + context.RegisterCompilationStartAction(compilationContext => + { + compilationContext.RegisterCodeBlockStartAction(AnalyzeCodeBlockStart); + }); + } + + private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) + { + } + + private static void AnalyzeCodeBlockStart(CodeBlockStartAnalysisContext context) + { + context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.InvocationExpression); + } + } + """); } [Fact] public async Task CSharp_NoDiagnosticCases_2Async() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -abstract class MyAnalyzer : DiagnosticAnalyzer - where T : struct -{ - public override ImmutableArray SupportedDiagnostics - { - get - { - throw new NotImplementedException(); - } - } - - public override void Initialize(AnalysisContext context) - { - context.RegisterCompilationStartAction(compilationContext => - { - compilationContext.RegisterCodeBlockStartAction(codeBlockContext => - { - AnalyzeCodeBlockStart(codeBlockContext); - }); - }); - } - - private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) - { - } - - private static void AnalyzeCodeBlockStart(CodeBlockStartAnalysisContext context) - { - context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.InvocationExpression); - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(source); + await VerifyCS.VerifyAnalyzerAsync(""" + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + abstract class MyAnalyzer : DiagnosticAnalyzer + where T : struct + { + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } + + public override void Initialize(AnalysisContext context) + { + context.RegisterCompilationStartAction(compilationContext => + { + compilationContext.RegisterCodeBlockStartAction(codeBlockContext => + { + AnalyzeCodeBlockStart(codeBlockContext); + }); + }); + } + + private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) + { + } + + private static void AnalyzeCodeBlockStart(CodeBlockStartAnalysisContext context) + { + context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.InvocationExpression); + } + } + """); } [Fact] public async Task CSharp_NoDiagnosticCases_OperationAnalyzerRegistrationAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -class MyAnalyzer : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics - { - get - { - throw new NotImplementedException(); - } - } - - public override void Initialize(AnalysisContext context) - { - context.RegisterOperationAction(AnalyzeOperation, OperationKind.Invocation); - } - - private static void AnalyzeOperation(OperationAnalysisContext context) - { - } -} - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -class MyAnalyzer2 : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics - { - get - { - throw new NotImplementedException(); - } - } - - public override void Initialize(AnalysisContext context) - { - context.RegisterOperationBlockAction(AnalyzeOperationBlock); - } - - private static void AnalyzeOperationBlock(OperationBlockAnalysisContext context) - { - } -}"; - await VerifyCS.VerifyAnalyzerAsync(source); + await VerifyCS.VerifyAnalyzerAsync(""" + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + class MyAnalyzer : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } + + public override void Initialize(AnalysisContext context) + { + context.RegisterOperationAction(AnalyzeOperation, OperationKind.Invocation); + } + + private static void AnalyzeOperation(OperationAnalysisContext context) + { + } + } + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + class MyAnalyzer2 : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } + + public override void Initialize(AnalysisContext context) + { + context.RegisterOperationBlockAction(AnalyzeOperationBlock); + } + + private static void AnalyzeOperationBlock(OperationBlockAnalysisContext context) + { + } + } + """); } [Fact] public async Task CSharp_NoDiagnosticCases_NestedOperationAnalyzerRegistrationAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -class MyAnalyzer : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics - { - get - { - throw new NotImplementedException(); - } - } - - public override void Initialize(AnalysisContext context) - { - context.RegisterCompilationStartAction(compilationContext => - { - compilationContext.RegisterOperationBlockStartAction(operationBlockContext => - { - AnalyzeOperationBlockStart(operationBlockContext); - }); - }); - - context.RegisterCompilationStartAction(compilationContext => - { - compilationContext.RegisterOperationAction(AnalyzeOperation, OperationKind.Invocation); - }); - - context.RegisterCompilationStartAction(compilationContext => - { - compilationContext.RegisterOperationBlockAction(AnalyzeOperationBlock); - }); - } - - private static void AnalyzeOperation(OperationAnalysisContext context) - { - } - - private static void AnalyzeOperationBlock(OperationBlockAnalysisContext context) - { - } - - private static void AnalyzeOperationBlockStart(OperationBlockStartAnalysisContext context) - { - context.RegisterOperationAction(AnalyzeOperation, OperationKind.Invocation); - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(source); + await VerifyCS.VerifyAnalyzerAsync(""" + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + class MyAnalyzer : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } + + public override void Initialize(AnalysisContext context) + { + context.RegisterCompilationStartAction(compilationContext => + { + compilationContext.RegisterOperationBlockStartAction(operationBlockContext => + { + AnalyzeOperationBlockStart(operationBlockContext); + }); + }); + + context.RegisterCompilationStartAction(compilationContext => + { + compilationContext.RegisterOperationAction(AnalyzeOperation, OperationKind.Invocation); + }); + + context.RegisterCompilationStartAction(compilationContext => + { + compilationContext.RegisterOperationBlockAction(AnalyzeOperationBlock); + }); + } + + private static void AnalyzeOperation(OperationAnalysisContext context) + { + } + + private static void AnalyzeOperationBlock(OperationBlockAnalysisContext context) + { + } + + private static void AnalyzeOperationBlockStart(OperationBlockStartAnalysisContext context) + { + context.RegisterOperationAction(AnalyzeOperation, OperationKind.Invocation); + } + } + """); } [Fact] public async Task VisualBasic_NoDiagnosticCasesAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic - - -Class MyAnalyzer(Of T As Structure) - Inherits DiagnosticAnalyzer - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - context.RegisterCompilationStartAction( - Sub(compilationContext As CompilationStartAnalysisContext) - compilationContext.RegisterCodeBlockStartAction(Of SyntaxKind)(AddressOf AnalyzeCodeBlockStart) - End Sub - ) - End Sub - - Private Shared Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext) - End Sub - - Private Shared Sub AnalyzeCodeBlockStart(context As CodeBlockStartAnalysisContext(Of SyntaxKind)) - context.RegisterSyntaxNodeAction(AddressOf AnalyzeSyntax, SyntaxKind.InvocationExpression) - End Sub -End Class -"; - - await VerifyVB.VerifyAnalyzerAsync(source); + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.VisualBasic + + + Class MyAnalyzer(Of T As Structure) + Inherits DiagnosticAnalyzer + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + context.RegisterCompilationStartAction( + Sub(compilationContext As CompilationStartAnalysisContext) + compilationContext.RegisterCodeBlockStartAction(Of SyntaxKind)(AddressOf AnalyzeCodeBlockStart) + End Sub + ) + End Sub + + Private Shared Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext) + End Sub + + Private Shared Sub AnalyzeCodeBlockStart(context As CodeBlockStartAnalysisContext(Of SyntaxKind)) + context.RegisterSyntaxNodeAction(AddressOf AnalyzeSyntax, SyntaxKind.InvocationExpression) + End Sub + End Class + """); } [Fact] public async Task VisualBasic_NoDiagnosticCases_2Async() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic - - -Class MyAnalyzer(Of T As Structure) - Inherits DiagnosticAnalyzer - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - context.RegisterCompilationStartAction( - Sub(compilationContext As CompilationStartAnalysisContext) - compilationContext.RegisterCodeBlockStartAction(Of SyntaxKind)( - Sub(codeBlockContext As CodeBlockStartAnalysisContext(Of SyntaxKind)) - AnalyzeCodeBlockStart(codeBlockContext) + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.VisualBasic + + + Class MyAnalyzer(Of T As Structure) + Inherits DiagnosticAnalyzer + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + context.RegisterCompilationStartAction( + Sub(compilationContext As CompilationStartAnalysisContext) + compilationContext.RegisterCodeBlockStartAction(Of SyntaxKind)( + Sub(codeBlockContext As CodeBlockStartAnalysisContext(Of SyntaxKind)) + AnalyzeCodeBlockStart(codeBlockContext) + End Sub + ) + End Sub + ) End Sub - ) - End Sub - ) - End Sub - Private Shared Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext) - End Sub - - Private Shared Sub AnalyzeCodeBlockStart(context As CodeBlockStartAnalysisContext(Of SyntaxKind)) - context.RegisterSyntaxNodeAction(AddressOf AnalyzeSyntax, SyntaxKind.InvocationExpression) - End Sub -End Class -"; + Private Shared Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext) + End Sub - await VerifyVB.VerifyAnalyzerAsync(source); + Private Shared Sub AnalyzeCodeBlockStart(context As CodeBlockStartAnalysisContext(Of SyntaxKind)) + context.RegisterSyntaxNodeAction(AddressOf AnalyzeSyntax, SyntaxKind.InvocationExpression) + End Sub + End Class + """); } [Fact] public async Task VisualBasic_NoDiagnosticCases_OperationAnalyzerRegistrationAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - _ -Class MyAnalyzer - Inherits DiagnosticAnalyzer - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - context.RegisterOperationAction(AddressOf AnalyzeOperation, OperationKind.Invocation) - End Sub - - Private Shared Sub AnalyzeOperation(context As OperationAnalysisContext) - End Sub -End Class - - _ -Class MyAnalyzer2 - Inherits DiagnosticAnalyzer - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - context.RegisterOperationBlockAction(AddressOf AnalyzeOperationBlock) - End Sub - - Private Shared Sub AnalyzeOperationBlock(context As OperationBlockAnalysisContext) - End Sub -End Class -"; - await VerifyVB.VerifyAnalyzerAsync(source); + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + _ + Class MyAnalyzer + Inherits DiagnosticAnalyzer + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + context.RegisterOperationAction(AddressOf AnalyzeOperation, OperationKind.Invocation) + End Sub + + Private Shared Sub AnalyzeOperation(context As OperationAnalysisContext) + End Sub + End Class + + _ + Class MyAnalyzer2 + Inherits DiagnosticAnalyzer + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + context.RegisterOperationBlockAction(AddressOf AnalyzeOperationBlock) + End Sub + + Private Shared Sub AnalyzeOperationBlock(context As OperationBlockAnalysisContext) + End Sub + End Class + """); } [Fact] public async Task VisualBasic_NoDiagnosticCases_NestedOperationAnalyzerRegistrationAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics - - _ -MustInherit Class MyAnalyzer - Inherits DiagnosticAnalyzer - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - context.RegisterCompilationStartAction(Function(compilationContext) - compilationContext.RegisterOperationBlockStartAction(Function(operationBlockContext) - AnalyzeOperationBlockStart(operationBlockContext) - End Function) - End Function) - - context.RegisterCompilationStartAction(Function(compilationContext) - compilationContext.RegisterOperationAction(AddressOf AnalyzeOperation, OperationKind.Invocation) - End Function) - - context.RegisterCompilationStartAction(Function(compilationContext) - compilationContext.RegisterOperationBlockAction(AddressOf AnalyzeOperationBlock) - End Function) - End Sub - - Private Shared Sub AnalyzeOperation(context As OperationAnalysisContext) - End Sub - - Private Shared Sub AnalyzeOperationBlock(context As OperationBlockAnalysisContext) - End Sub - - Private Shared Sub AnalyzeOperationBlockStart(context As OperationBlockStartAnalysisContext) - context.RegisterOperationAction(AddressOf AnalyzeOperation, OperationKind.Invocation) - End Sub -End Class -"; - - await VerifyVB.VerifyAnalyzerAsync(source); + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + _ + MustInherit Class MyAnalyzer + Inherits DiagnosticAnalyzer + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + context.RegisterCompilationStartAction(Function(compilationContext) + compilationContext.RegisterOperationBlockStartAction(Function(operationBlockContext) + AnalyzeOperationBlockStart(operationBlockContext) + End Function) + End Function) + + context.RegisterCompilationStartAction(Function(compilationContext) + compilationContext.RegisterOperationAction(AddressOf AnalyzeOperation, OperationKind.Invocation) + End Function) + + context.RegisterCompilationStartAction(Function(compilationContext) + compilationContext.RegisterOperationBlockAction(AddressOf AnalyzeOperationBlock) + End Function) + End Sub + + Private Shared Sub AnalyzeOperation(context As OperationAnalysisContext) + End Sub + + Private Shared Sub AnalyzeOperationBlock(context As OperationBlockAnalysisContext) + End Sub + + Private Shared Sub AnalyzeOperationBlockStart(context As OperationBlockStartAnalysisContext) + context.RegisterOperationAction(AddressOf AnalyzeOperation, OperationKind.Invocation) + End Sub + End Class + """); } private static DiagnosticResult GetCSharpExpectedDiagnostic(int line, int column, string parameterName, StartActionKind kind) => @@ -526,7 +515,7 @@ private static string[] GetExpectedArguments(string parameterName, StartActionKi _ => throw new ArgumentException("Unsupported action kind", nameof(kind)), }; - return new[] { parameterName, arg2 }; + return [parameterName, arg2]; } private enum StartActionKind diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/StartActionWithOnlyEndActionRuleTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/StartActionWithOnlyEndActionRuleTests.cs index 0fa2b7abedcdd..4a1b559f6d2df 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/StartActionWithOnlyEndActionRuleTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/StartActionWithOnlyEndActionRuleTests.cs @@ -22,314 +22,307 @@ public class StartActionWithOnlyEndActionRuleTests [Fact] public async Task CSharp_VerifyDiagnosticAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -class MyAnalyzer : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics - { - get - { - throw new NotImplementedException(); - } - } - - public override void Initialize(AnalysisContext context) - { - context.RegisterCompilationStartAction(compilationContext => - { - compilationContext.RegisterCompilationEndAction(null); - }); - - context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.InvocationExpression); - context.RegisterCodeBlockStartAction(AnalyzeCodeBlockStart); - context.RegisterOperationBlockStartAction(AnalyzeOperationBlockStart); - } - - private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) - { - } - - private static void AnalyzeCodeBlockStart(CodeBlockStartAnalysisContext codeBlockContext) - { - codeBlockContext.RegisterCodeBlockEndAction(null); - } - - private static void AnalyzeOperationBlockStart(OperationBlockStartAnalysisContext operationBlockContext) - { - operationBlockContext.RegisterOperationBlockEndAction(null); - } -}"; - DiagnosticResult[] expected = new[] - { - GetCSharpExpectedDiagnostic(21, 48, parameterName: "compilationContext", kind: StartActionKind.CompilationStartAction), - GetCSharpExpectedDiagnostic(35, 47, parameterName: "codeBlockContext", kind: StartActionKind.CodeBlockStartAction), - GetCSharpExpectedDiagnostic(40, 52, parameterName: "operationBlockContext", kind: StartActionKind.OperationBlockStartAction) - }; - - await VerifyCS.VerifyAnalyzerAsync(source, expected); + DiagnosticResult[] expected = + [ + GetCSharpExpectedDiagnostic(20, 48, parameterName: "compilationContext", kind: StartActionKind.CompilationStartAction), + GetCSharpExpectedDiagnostic(34, 47, parameterName: "codeBlockContext", kind: StartActionKind.CodeBlockStartAction), + GetCSharpExpectedDiagnostic(39, 52, parameterName: "operationBlockContext", kind: StartActionKind.OperationBlockStartAction) + ]; + + await VerifyCS.VerifyAnalyzerAsync(""" + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + class MyAnalyzer : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } + + public override void Initialize(AnalysisContext context) + { + context.RegisterCompilationStartAction(compilationContext => + { + compilationContext.RegisterCompilationEndAction(null); + }); + + context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.InvocationExpression); + context.RegisterCodeBlockStartAction(AnalyzeCodeBlockStart); + context.RegisterOperationBlockStartAction(AnalyzeOperationBlockStart); + } + + private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) + { + } + + private static void AnalyzeCodeBlockStart(CodeBlockStartAnalysisContext codeBlockContext) + { + codeBlockContext.RegisterCodeBlockEndAction(null); + } + + private static void AnalyzeOperationBlockStart(OperationBlockStartAnalysisContext operationBlockContext) + { + operationBlockContext.RegisterOperationBlockEndAction(null); + } + } + """, expected); } [Fact] public async Task VisualBasic_VerifyDiagnosticAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic - - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - context.RegisterCompilationStartAction( - Sub(compilationContext As CompilationStartAnalysisContext) - compilationContext.RegisterCompilationEndAction(Nothing) - End Sub - ) - - context.RegisterSyntaxNodeAction(AddressOf AnalyzeSyntax, SyntaxKind.InvocationExpression) - context.RegisterCodeBlockStartAction(Of SyntaxKind)(AddressOf AnalyzeCodeBlockStart) - context.RegisterOperationBlockStartAction(AddressOf AnalyzeOperationBlockStart) - End Sub - - Private Shared Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext) - End Sub - - Private Shared Sub AnalyzeCodeBlockStart(codeBlockContext As CodeBlockStartAnalysisContext(Of SyntaxKind)) - codeBlockContext.RegisterCodeBlockEndAction(Nothing) - End Sub - - Private Shared Sub AnalyzeOperationBlockStart(operationBlockContext As OperationBlockStartAnalysisContext) - operationBlockContext.RegisterOperationBlockEndAction(Nothing) - End Sub -End Class -"; - DiagnosticResult[] expected = new[] - { - GetBasicExpectedDiagnostic(19, 17, parameterName: "compilationContext", kind: StartActionKind.CompilationStartAction), - GetBasicExpectedDiagnostic(32, 46, parameterName: "codeBlockContext", kind: StartActionKind.CodeBlockStartAction), - GetBasicExpectedDiagnostic(36, 51, parameterName: "operationBlockContext", kind: StartActionKind.OperationBlockStartAction) - }; + DiagnosticResult[] expected = + [ + GetBasicExpectedDiagnostic(18, 17, parameterName: "compilationContext", kind: StartActionKind.CompilationStartAction), + GetBasicExpectedDiagnostic(31, 46, parameterName: "codeBlockContext", kind: StartActionKind.CodeBlockStartAction), + GetBasicExpectedDiagnostic(35, 51, parameterName: "operationBlockContext", kind: StartActionKind.OperationBlockStartAction) + ]; + + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.VisualBasic + + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + context.RegisterCompilationStartAction( + Sub(compilationContext As CompilationStartAnalysisContext) + compilationContext.RegisterCompilationEndAction(Nothing) + End Sub + ) + + context.RegisterSyntaxNodeAction(AddressOf AnalyzeSyntax, SyntaxKind.InvocationExpression) + context.RegisterCodeBlockStartAction(Of SyntaxKind)(AddressOf AnalyzeCodeBlockStart) + context.RegisterOperationBlockStartAction(AddressOf AnalyzeOperationBlockStart) + End Sub + + Private Shared Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext) + End Sub + + Private Shared Sub AnalyzeCodeBlockStart(codeBlockContext As CodeBlockStartAnalysisContext(Of SyntaxKind)) + codeBlockContext.RegisterCodeBlockEndAction(Nothing) + End Sub - await VerifyVB.VerifyAnalyzerAsync(source, expected); + Private Shared Sub AnalyzeOperationBlockStart(operationBlockContext As OperationBlockStartAnalysisContext) + operationBlockContext.RegisterOperationBlockEndAction(Nothing) + End Sub + End Class + """, expected); } [Fact] public async Task CSharp_NoDiagnosticCasesAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -abstract class MyAnalyzer : DiagnosticAnalyzer - where T : struct -{ - public override ImmutableArray SupportedDiagnostics - { - get - { - throw new NotImplementedException(); - } - } - - public override void Initialize(AnalysisContext context) - { - context.RegisterCompilationStartAction(compilationContext => - { - compilationContext.RegisterCodeBlockStartAction(AnalyzeCodeBlockStart); - compilationContext.RegisterOperationBlockStartAction(AnalyzeOperationBlockStart); - compilationContext.RegisterCompilationEndAction(null); - }); - } - - private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) - { - } - - private static void AnalyzeCodeBlockStart(CodeBlockStartAnalysisContext context) - { - context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.InvocationExpression); - context.RegisterCodeBlockEndAction(null); - } - - private static void AnalyzeOperation(OperationAnalysisContext context) - { - } - - private static void AnalyzeOperationBlockStart(OperationBlockStartAnalysisContext context) - { - context.RegisterOperationAction(AnalyzeOperation, OperationKind.Invocation); - context.RegisterOperationBlockEndAction(null); - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(source); + await VerifyCS.VerifyAnalyzerAsync(""" + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + abstract class MyAnalyzer : DiagnosticAnalyzer + where T : struct + { + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } + + public override void Initialize(AnalysisContext context) + { + context.RegisterCompilationStartAction(compilationContext => + { + compilationContext.RegisterCodeBlockStartAction(AnalyzeCodeBlockStart); + compilationContext.RegisterOperationBlockStartAction(AnalyzeOperationBlockStart); + compilationContext.RegisterCompilationEndAction(null); + }); + } + + private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) + { + } + + private static void AnalyzeCodeBlockStart(CodeBlockStartAnalysisContext context) + { + context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.InvocationExpression); + context.RegisterCodeBlockEndAction(null); + } + + private static void AnalyzeOperation(OperationAnalysisContext context) + { + } + + private static void AnalyzeOperationBlockStart(OperationBlockStartAnalysisContext context) + { + context.RegisterOperationAction(AnalyzeOperation, OperationKind.Invocation); + context.RegisterOperationBlockEndAction(null); + } + } + """); } [Fact] public async Task CSharp_NoDiagnosticCases_2Async() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -abstract class MyAnalyzer : DiagnosticAnalyzer - where T : struct -{ - public override ImmutableArray SupportedDiagnostics - { - get - { - throw new NotImplementedException(); + await VerifyCS.VerifyAnalyzerAsync(""" + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + abstract class MyAnalyzer : DiagnosticAnalyzer + where T : struct + { + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } + + public override void Initialize(AnalysisContext context) + { + context.RegisterCompilationStartAction(compilationContext => + { + compilationContext.RegisterCodeBlockStartAction(codeBlockContext => + { + AnalyzeCodeBlockStart(codeBlockContext); + }); + + compilationContext.RegisterCompilationEndAction(null); + }); + } + + private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) + { + } + + private static void AnalyzeCodeBlockStart(CodeBlockStartAnalysisContext context) + { + context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.InvocationExpression); + context.RegisterCodeBlockEndAction(null); + } + } + """); } - } - public override void Initialize(AnalysisContext context) - { - context.RegisterCompilationStartAction(compilationContext => + [Fact] + public async Task VisualBasic_NoDiagnosticCasesAsync() { - compilationContext.RegisterCodeBlockStartAction(codeBlockContext => - { - AnalyzeCodeBlockStart(codeBlockContext); - }); - - compilationContext.RegisterCompilationEndAction(null); - }); - } + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.VisualBasic + + + Class MyAnalyzer(Of T As Structure) + Inherits DiagnosticAnalyzer + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + context.RegisterCompilationStartAction( + Sub(compilationContext As CompilationStartAnalysisContext) + compilationContext.RegisterCodeBlockStartAction(Of SyntaxKind)(AddressOf AnalyzeCodeBlockStart) + compilationContext.RegisterOperationBlockStartAction(AddressOf AnalyzeOperationBlockStart) + compilationContext.RegisterCompilationEndAction(Nothing) + End Sub + ) + End Sub - private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) - { - } + Private Shared Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext) + End Sub - private static void AnalyzeCodeBlockStart(CodeBlockStartAnalysisContext context) - { - context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.InvocationExpression); - context.RegisterCodeBlockEndAction(null); - } -}"; + Private Shared Sub AnalyzeCodeBlockStart(context As CodeBlockStartAnalysisContext(Of SyntaxKind)) + context.RegisterSyntaxNodeAction(AddressOf AnalyzeSyntax, SyntaxKind.InvocationExpression) + context.RegisterCodeBlockEndAction(Nothing) + End Sub - await VerifyCS.VerifyAnalyzerAsync(source); - } + Private Shared Sub AnalyzeOperation(context As OperationAnalysisContext) + End Sub - [Fact] - public async Task VisualBasic_NoDiagnosticCasesAsync() - { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic - - -Class MyAnalyzer(Of T As Structure) - Inherits DiagnosticAnalyzer - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - context.RegisterCompilationStartAction( - Sub(compilationContext As CompilationStartAnalysisContext) - compilationContext.RegisterCodeBlockStartAction(Of SyntaxKind)(AddressOf AnalyzeCodeBlockStart) - compilationContext.RegisterOperationBlockStartAction(AddressOf AnalyzeOperationBlockStart) - compilationContext.RegisterCompilationEndAction(Nothing) - End Sub - ) - End Sub - - Private Shared Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext) - End Sub - - Private Shared Sub AnalyzeCodeBlockStart(context As CodeBlockStartAnalysisContext(Of SyntaxKind)) - context.RegisterSyntaxNodeAction(AddressOf AnalyzeSyntax, SyntaxKind.InvocationExpression) - context.RegisterCodeBlockEndAction(Nothing) - End Sub - - Private Shared Sub AnalyzeOperation(context As OperationAnalysisContext) - End Sub - - Private Shared Sub AnalyzeOperationBlockStart(context As OperationBlockStartAnalysisContext) - context.RegisterOperationAction(AddressOf AnalyzeOperation, OperationKind.Invocation) - context.RegisterOperationBlockEndAction(Nothing) - End Sub -End Class -"; - - await VerifyVB.VerifyAnalyzerAsync(source); + Private Shared Sub AnalyzeOperationBlockStart(context As OperationBlockStartAnalysisContext) + context.RegisterOperationAction(AddressOf AnalyzeOperation, OperationKind.Invocation) + context.RegisterOperationBlockEndAction(Nothing) + End Sub + End Class + """); } [Fact] public async Task VisualBasic_NoDiagnosticCases_2Async() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic - - -Class MyAnalyzer(Of T As Structure) - Inherits DiagnosticAnalyzer - - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Sub Initialize(context As AnalysisContext) - context.RegisterCompilationStartAction( - Sub(compilationContext As CompilationStartAnalysisContext) - compilationContext.RegisterCodeBlockStartAction(Of SyntaxKind)( - Sub(codeBlockContext As CodeBlockStartAnalysisContext(Of SyntaxKind)) - AnalyzeCodeBlockStart(codeBlockContext) + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + Imports Microsoft.CodeAnalysis.VisualBasic + + + Class MyAnalyzer(Of T As Structure) + Inherits DiagnosticAnalyzer + + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException() + End Get + End Property + + Public Overrides Sub Initialize(context As AnalysisContext) + context.RegisterCompilationStartAction( + Sub(compilationContext As CompilationStartAnalysisContext) + compilationContext.RegisterCodeBlockStartAction(Of SyntaxKind)( + Sub(codeBlockContext As CodeBlockStartAnalysisContext(Of SyntaxKind)) + AnalyzeCodeBlockStart(codeBlockContext) + End Sub + ) + + compilationContext.RegisterCompilationEndAction(Nothing) + End Sub + ) End Sub - ) - - compilationContext.RegisterCompilationEndAction(Nothing) - End Sub - ) - End Sub - - Private Shared Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext) - End Sub - Private Shared Sub AnalyzeCodeBlockStart(context As CodeBlockStartAnalysisContext(Of SyntaxKind)) - context.RegisterSyntaxNodeAction(AddressOf AnalyzeSyntax, SyntaxKind.InvocationExpression) - context.RegisterCodeBlockEndAction(Nothing) - End Sub -End Class -"; + Private Shared Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext) + End Sub - await VerifyVB.VerifyAnalyzerAsync(source); + Private Shared Sub AnalyzeCodeBlockStart(context As CodeBlockStartAnalysisContext(Of SyntaxKind)) + context.RegisterSyntaxNodeAction(AddressOf AnalyzeSyntax, SyntaxKind.InvocationExpression) + context.RegisterCodeBlockEndAction(Nothing) + End Sub + End Class + """); } private static DiagnosticResult GetCSharpExpectedDiagnostic(int line, int column, string parameterName, StartActionKind kind) => @@ -375,7 +368,7 @@ private static string[] GetExpectedArguments(string parameterName, StartActionKi throw new ArgumentException("Unsupported argument kind", nameof(kind)); } - return new[] { parameterName, endActionName, statelessActionName, arg4 }; + return [parameterName, endActionName, statelessActionName, arg4]; } private enum StartActionKind diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/SymbolIsBannedInAnalyzersTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/SymbolIsBannedInAnalyzersTests.cs index d3790578a0b54..6af11b3ef9e0c 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/SymbolIsBannedInAnalyzersTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/SymbolIsBannedInAnalyzersTests.cs @@ -21,253 +21,243 @@ namespace Microsoft.CodeAnalysis.Analyzers.UnitTests public class SymbolIsBannedInAnalyzersTests { [Fact] - public async Task UseBannedApi_EnforcementEnabled_CSharp() - { - await new VerifyCS.Test + public Task UseBannedApi_EnforcementEnabled_CSharp() + => new VerifyCS.Test { LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp9, - TestCode = @" -using System.IO; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + TestCode = """ + using System.IO; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; -[DiagnosticAnalyzer(LanguageNames.CSharp)] -class MyAnalyzer -{ -} + [DiagnosticAnalyzer(LanguageNames.CSharp)] + class MyAnalyzer + { + } -class C -{ - void M() - { - _ = File.Exists(""something""); - } -} -", + class C + { + void M() + { + _ = File.Exists("something"); + } + } + """, ExpectedDiagnostics = { // /0/Test0.cs(15,13): error RS1035: The symbol 'File' is banned for use by analyzers: Do not do file IO in analyzers - VerifyCS.Diagnostic("RS1035").WithSpan(15, 13, 15, 37).WithArguments("File", ": Do not do file IO in analyzers"), + VerifyCS.Diagnostic("RS1035").WithSpan(14, 13, 14, 37).WithArguments("File", ": Do not do file IO in analyzers"), }, TestState = { - AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true + AnalyzerConfigFiles = { ("/.editorconfig", $""" + root = true -[*] -build_property.EnforceExtendedAnalyzerRules = true -"), }, + [*] + build_property.EnforceExtendedAnalyzerRules = true + """), }, } }.RunAsync(); - } [Fact] - public async Task UseBannedApi_EnforcementEnabled_Generator_CSharp() - { - await new VerifyCS.Test + public Task UseBannedApi_EnforcementEnabled_Generator_CSharp() + => new VerifyCS.Test { LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp9, - TestCode = @" -using System.IO; -using Microsoft.CodeAnalysis; + TestCode = """ + using System.IO; + using Microsoft.CodeAnalysis; -namespace Microsoft.CodeAnalysis -{ - public class GeneratorAttribute : System.Attribute { } -} + namespace Microsoft.CodeAnalysis + { + public class GeneratorAttribute : System.Attribute { } + } -[Generator] -class MyAnalyzer -{ -} + [Generator] + class MyAnalyzer + { + } -class C -{ - void M() - { - _ = File.Exists(""something""); - } -} -", + class C + { + void M() + { + _ = File.Exists("something"); + } + } + """, ExpectedDiagnostics = { // /0/Test0.cs(19,13): error RS1035: The symbol 'File' is banned for use by analyzers: Do not do file IO in analyzers - VerifyCS.Diagnostic("RS1035").WithSpan(19, 13, 19, 37).WithArguments("File", ": Do not do file IO in analyzers"), + VerifyCS.Diagnostic("RS1035").WithSpan(18, 13, 18, 37).WithArguments("File", ": Do not do file IO in analyzers"), }, TestState = { - AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true + AnalyzerConfigFiles = { ("/.editorconfig", $""" + root = true -[*] -build_property.EnforceExtendedAnalyzerRules = true -"), }, + [*] + build_property.EnforceExtendedAnalyzerRules = true + """), }, } }.RunAsync(); - } [Fact] - public async Task UseBannedApi_EnforcementNotSpecified_CSharp() - { - await new VerifyCS.Test + public Task UseBannedApi_EnforcementNotSpecified_CSharp() + => new VerifyCS.Test { LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp9, - TestCode = @" -using System.IO; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + TestCode = """ + using System.IO; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; -[DiagnosticAnalyzer(LanguageNames.CSharp)] -class MyAnalyzer -{ -} + [DiagnosticAnalyzer(LanguageNames.CSharp)] + class MyAnalyzer + { + } -class C -{ - void M() - { - _ = File.Exists(""something""); - } -} -", + class C + { + void M() + { + _ = File.Exists("something"); + } + } + """, ExpectedDiagnostics = { // /0/Test0.cs(7,7): warning RS1036: 'MyAnalyzer': A project containing analyzers or source generators should specify the property 'true' - VerifyCS.Diagnostic("RS1036").WithSpan(7, 7, 7, 17).WithArguments("MyAnalyzer"), + VerifyCS.Diagnostic("RS1036").WithSpan(6, 7, 6, 17).WithArguments("MyAnalyzer"), } }.RunAsync(); - } [Fact] - public async Task UseBannedApi_EnforcementDisabled_CSharp() - { - await new VerifyCS.Test + public Task UseBannedApi_EnforcementDisabled_CSharp() + => new VerifyCS.Test { LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp9, - TestCode = @" -using System.IO; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + TestCode = """ + using System.IO; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; -[DiagnosticAnalyzer(LanguageNames.CSharp)] -class MyAnalyzer -{ -} + [DiagnosticAnalyzer(LanguageNames.CSharp)] + class MyAnalyzer + { + } -class C -{ - void M() - { - _ = File.Exists(""something""); - } -} -", + class C + { + void M() + { + _ = File.Exists("something"); + } + } + """, TestState = { - AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true + AnalyzerConfigFiles = { ("/.editorconfig", $""" + root = true -[*] -build_property.EnforceExtendedAnalyzerRules = false -"), + [*] + build_property.EnforceExtendedAnalyzerRules = false + """), }, } }.RunAsync(); - } [Fact] - public async Task UseBannedApi_EnforcementEnabled_Basic() - { - await new VerifyVB.Test + public Task UseBannedApi_EnforcementEnabled_Basic() + => new VerifyVB.Test { LanguageVersion = Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.Latest, - TestCode = @" -Imports System.IO -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics + TestCode = """ + Imports System.IO + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics - -Class MyDiagnosticAnalyzer -End Class + + Class MyDiagnosticAnalyzer + End Class -Class C - Function M() - File.Exists(""something"") - End Function -End Class -", + Class C + Function M() + File.Exists("something") + End Function + End Class + """, ExpectedDiagnostics = { // /0/Test0.vb(12,9,12,33): error RS1035: The symbol 'File' is banned for use by analyzers: Do not do file IO in analyzers - VerifyVB.Diagnostic("RS1035").WithSpan(12, 9, 12, 33).WithArguments("File", ": Do not do file IO in analyzers"), + VerifyVB.Diagnostic("RS1035").WithSpan(11, 9, 11, 33).WithArguments("File", ": Do not do file IO in analyzers"), }, TestState = { - AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true + AnalyzerConfigFiles = { ("/.editorconfig", $""" + root = true -[*] -build_property.EnforceExtendedAnalyzerRules = true -"), + [*] + build_property.EnforceExtendedAnalyzerRules = true + """), }, } }.RunAsync(); - } [Fact] - public async Task UseBannedApi_EnforcementNotSpecified_Basic() - { - await new VerifyVB.Test + public Task UseBannedApi_EnforcementNotSpecified_Basic() + => new VerifyVB.Test { LanguageVersion = Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.Latest, - TestCode = @" -Imports System.IO -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics + TestCode = """ + Imports System.IO + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics - -Class MyDiagnosticAnalyzer -End Class + + Class MyDiagnosticAnalyzer + End Class -Class C - Function M() - File.Exists(""something"") - End Function -End Class -", + Class C + Function M() + File.Exists("something") + End Function + End Class + """, ExpectedDiagnostics = { // /0/Test0.vb(7,7): warning RS1036: 'MyDiagnosticAnalyzer': A project containing analyzers or source generators should specify the property 'true' - VerifyVB.Diagnostic("RS1036").WithSpan(7, 7, 7, 27).WithArguments("MyDiagnosticAnalyzer"), + VerifyVB.Diagnostic("RS1036").WithSpan(6, 7, 6, 27).WithArguments("MyDiagnosticAnalyzer"), } }.RunAsync(); - } [Fact] - public async Task UseBannedApi_EnforcementDisabled_Basic() - { - await new VerifyVB.Test + public Task UseBannedApi_EnforcementDisabled_Basic() + => new VerifyVB.Test { LanguageVersion = Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.Latest, - TestCode = @" -Imports System.IO -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics + TestCode = """ + Imports System.IO + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics - -Class MyDiagnosticAnalyzer -End Class + + Class MyDiagnosticAnalyzer + End Class -Class C - Function M() - File.Exists(""something"") - End Function -End Class -", + Class C + Function M() + File.Exists("something") + End Function + End Class + """, TestState = { - AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true + AnalyzerConfigFiles = { ("/.editorconfig", $""" + root = true -[*] -build_property.EnforceExtendedAnalyzerRules = false -"), + [*] + build_property.EnforceExtendedAnalyzerRules = false + """), }, } }.RunAsync(); - } [Fact] - public async Task UseBannedApi_ISourceGenerator() - { - await new VerifyCS.Test + public Task UseBannedApi_ISourceGenerator() + => new VerifyCS.Test { ReferenceAssemblies = AdditionalMetadataReferences.Default.WithPackages(ImmutableArray.Create(new PackageIdentity("Microsoft.CodeAnalysis.Common", "4.5.0"))), TestCode = """ @@ -306,6 +296,5 @@ public void Execute(GeneratorExecutionContext context) VerifyCS.Diagnostic("RS1035").WithLocation(1).WithArguments("GeneratorExecutionContext", ": Non-incremental source generators should not be used, implement IIncrementalGenerator instead"), } }.RunAsync(); - } } } diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/UnsupportedSymbolKindArgumentRuleTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/UnsupportedSymbolKindArgumentRuleTests.cs index dc435024867e7..19c700b374b18 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/UnsupportedSymbolKindArgumentRuleTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/UnsupportedSymbolKindArgumentRuleTests.cs @@ -21,234 +21,230 @@ public class UnsupportedSymbolKindArgumentRuleTests [Fact] public async Task CSharp_VerifyDiagnosticAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + DiagnosticResult[] expected = + [ + GetCSharpExpectedDiagnostic(20, 13, unsupportedSymbolKind: SymbolKind.Alias), + GetCSharpExpectedDiagnostic(21, 13, unsupportedSymbolKind: SymbolKind.ArrayType), + GetCSharpExpectedDiagnostic(22, 13, unsupportedSymbolKind: SymbolKind.Assembly), + GetCSharpExpectedDiagnostic(23, 13, unsupportedSymbolKind: SymbolKind.Discard), + GetCSharpExpectedDiagnostic(24, 13, unsupportedSymbolKind: SymbolKind.DynamicType), + GetCSharpExpectedDiagnostic(25, 13, unsupportedSymbolKind: SymbolKind.ErrorType), + GetCSharpExpectedDiagnostic(28, 13, unsupportedSymbolKind: SymbolKind.Label), + GetCSharpExpectedDiagnostic(29, 13, unsupportedSymbolKind: SymbolKind.Local), + GetCSharpExpectedDiagnostic(31, 13, unsupportedSymbolKind: SymbolKind.NetModule), + GetCSharpExpectedDiagnostic(35, 13, unsupportedSymbolKind: SymbolKind.PointerType), + GetCSharpExpectedDiagnostic(37, 13, unsupportedSymbolKind: SymbolKind.Preprocessing), + GetCSharpExpectedDiagnostic(38, 13, unsupportedSymbolKind: SymbolKind.RangeVariable), + GetCSharpExpectedDiagnostic(39, 13, unsupportedSymbolKind: SymbolKind.TypeParameter), + ]; -[DiagnosticAnalyzer(LanguageNames.CSharp)] -class MyAnalyzer : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics - { - get - { - throw new NotImplementedException(); - } - } + await VerifyCS.VerifyAnalyzerAsync(""" + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; - public override void Initialize(AnalysisContext context) - { - context.RegisterSymbolAction(AnalyzeSymbol, - SymbolKind.Alias, - SymbolKind.ArrayType, - SymbolKind.Assembly, - SymbolKind.Discard, - SymbolKind.DynamicType, - SymbolKind.ErrorType, - SymbolKind.Event, - SymbolKind.Field, - SymbolKind.Label, - SymbolKind.Local, - SymbolKind.Method, - SymbolKind.NetModule, - SymbolKind.NamedType, - SymbolKind.Namespace, - SymbolKind.Parameter, - SymbolKind.PointerType, - SymbolKind.Property, - SymbolKind.Preprocessing, - SymbolKind.RangeVariable, - SymbolKind.TypeParameter); - } + [DiagnosticAnalyzer(LanguageNames.CSharp)] + class MyAnalyzer : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } - private static void AnalyzeSymbol(SymbolAnalysisContext context) - { - } -}"; - DiagnosticResult[] expected = new[] - { - GetCSharpExpectedDiagnostic(21, 13, unsupportedSymbolKind: SymbolKind.Alias), - GetCSharpExpectedDiagnostic(22, 13, unsupportedSymbolKind: SymbolKind.ArrayType), - GetCSharpExpectedDiagnostic(23, 13, unsupportedSymbolKind: SymbolKind.Assembly), - GetCSharpExpectedDiagnostic(24, 13, unsupportedSymbolKind: SymbolKind.Discard), - GetCSharpExpectedDiagnostic(25, 13, unsupportedSymbolKind: SymbolKind.DynamicType), - GetCSharpExpectedDiagnostic(26, 13, unsupportedSymbolKind: SymbolKind.ErrorType), - GetCSharpExpectedDiagnostic(29, 13, unsupportedSymbolKind: SymbolKind.Label), - GetCSharpExpectedDiagnostic(30, 13, unsupportedSymbolKind: SymbolKind.Local), - GetCSharpExpectedDiagnostic(32, 13, unsupportedSymbolKind: SymbolKind.NetModule), - GetCSharpExpectedDiagnostic(36, 13, unsupportedSymbolKind: SymbolKind.PointerType), - GetCSharpExpectedDiagnostic(38, 13, unsupportedSymbolKind: SymbolKind.Preprocessing), - GetCSharpExpectedDiagnostic(39, 13, unsupportedSymbolKind: SymbolKind.RangeVariable), - GetCSharpExpectedDiagnostic(40, 13, unsupportedSymbolKind: SymbolKind.TypeParameter), - }; + public override void Initialize(AnalysisContext context) + { + context.RegisterSymbolAction(AnalyzeSymbol, + SymbolKind.Alias, + SymbolKind.ArrayType, + SymbolKind.Assembly, + SymbolKind.Discard, + SymbolKind.DynamicType, + SymbolKind.ErrorType, + SymbolKind.Event, + SymbolKind.Field, + SymbolKind.Label, + SymbolKind.Local, + SymbolKind.Method, + SymbolKind.NetModule, + SymbolKind.NamedType, + SymbolKind.Namespace, + SymbolKind.Parameter, + SymbolKind.PointerType, + SymbolKind.Property, + SymbolKind.Preprocessing, + SymbolKind.RangeVariable, + SymbolKind.TypeParameter); + } - await VerifyCS.VerifyAnalyzerAsync(source, expected); + private static void AnalyzeSymbol(SymbolAnalysisContext context) + { + } + } + """, expected); } [Fact] public async Task VisualBasic_VerifyRegisterSymbolActionDiagnosticAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics + DiagnosticResult[] expected = + [ + GetBasicExpectedDiagnostic(17, 13, unsupportedSymbolKind: SymbolKind.Alias), + GetBasicExpectedDiagnostic(18, 13, unsupportedSymbolKind: SymbolKind.ArrayType), + GetBasicExpectedDiagnostic(19, 13, unsupportedSymbolKind: SymbolKind.Assembly), + GetBasicExpectedDiagnostic(20, 13, unsupportedSymbolKind: SymbolKind.Discard), + GetBasicExpectedDiagnostic(21, 13, unsupportedSymbolKind: SymbolKind.DynamicType), + GetBasicExpectedDiagnostic(22, 13, unsupportedSymbolKind: SymbolKind.ErrorType), + GetBasicExpectedDiagnostic(25, 13, unsupportedSymbolKind: SymbolKind.Label), + GetBasicExpectedDiagnostic(26, 13, unsupportedSymbolKind: SymbolKind.Local), + GetBasicExpectedDiagnostic(28, 13, unsupportedSymbolKind: SymbolKind.NetModule), + GetBasicExpectedDiagnostic(32, 13, unsupportedSymbolKind: SymbolKind.PointerType), + GetBasicExpectedDiagnostic(34, 13, unsupportedSymbolKind: SymbolKind.Preprocessing), + GetBasicExpectedDiagnostic(35, 13, unsupportedSymbolKind: SymbolKind.RangeVariable), + GetBasicExpectedDiagnostic(36, 13, unsupportedSymbolKind: SymbolKind.TypeParameter), + ]; - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException() - End Get - End Property + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics - Public Overrides Sub Initialize(context As AnalysisContext) - context.RegisterSymbolAction(AddressOf AnalyzeSymbol, - SymbolKind.Alias, - SymbolKind.ArrayType, - SymbolKind.Assembly, - SymbolKind.Discard, - SymbolKind.DynamicType, - SymbolKind.ErrorType, - SymbolKind.Event, - SymbolKind.Field, - SymbolKind.Label, - SymbolKind.Local, - SymbolKind.Method, - SymbolKind.NetModule, - SymbolKind.NamedType, - SymbolKind.Namespace, - SymbolKind.Parameter, - SymbolKind.PointerType, - SymbolKind.Property, - SymbolKind.Preprocessing, - SymbolKind.RangeVariable, - SymbolKind.TypeParameter) - End Sub + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException() + End Get + End Property - Private Shared Sub AnalyzeSymbol(context As SymbolAnalysisContext) - End Sub -End Class -"; - DiagnosticResult[] expected = new[] - { - GetBasicExpectedDiagnostic(18, 13, unsupportedSymbolKind: SymbolKind.Alias), - GetBasicExpectedDiagnostic(19, 13, unsupportedSymbolKind: SymbolKind.ArrayType), - GetBasicExpectedDiagnostic(20, 13, unsupportedSymbolKind: SymbolKind.Assembly), - GetBasicExpectedDiagnostic(21, 13, unsupportedSymbolKind: SymbolKind.Discard), - GetBasicExpectedDiagnostic(22, 13, unsupportedSymbolKind: SymbolKind.DynamicType), - GetBasicExpectedDiagnostic(23, 13, unsupportedSymbolKind: SymbolKind.ErrorType), - GetBasicExpectedDiagnostic(26, 13, unsupportedSymbolKind: SymbolKind.Label), - GetBasicExpectedDiagnostic(27, 13, unsupportedSymbolKind: SymbolKind.Local), - GetBasicExpectedDiagnostic(29, 13, unsupportedSymbolKind: SymbolKind.NetModule), - GetBasicExpectedDiagnostic(33, 13, unsupportedSymbolKind: SymbolKind.PointerType), - GetBasicExpectedDiagnostic(35, 13, unsupportedSymbolKind: SymbolKind.Preprocessing), - GetBasicExpectedDiagnostic(36, 13, unsupportedSymbolKind: SymbolKind.RangeVariable), - GetBasicExpectedDiagnostic(37, 13, unsupportedSymbolKind: SymbolKind.TypeParameter), - }; + Public Overrides Sub Initialize(context As AnalysisContext) + context.RegisterSymbolAction(AddressOf AnalyzeSymbol, + SymbolKind.Alias, + SymbolKind.ArrayType, + SymbolKind.Assembly, + SymbolKind.Discard, + SymbolKind.DynamicType, + SymbolKind.ErrorType, + SymbolKind.Event, + SymbolKind.Field, + SymbolKind.Label, + SymbolKind.Local, + SymbolKind.Method, + SymbolKind.NetModule, + SymbolKind.NamedType, + SymbolKind.Namespace, + SymbolKind.Parameter, + SymbolKind.PointerType, + SymbolKind.Property, + SymbolKind.Preprocessing, + SymbolKind.RangeVariable, + SymbolKind.TypeParameter) + End Sub - await VerifyVB.VerifyAnalyzerAsync(source, expected); + Private Shared Sub AnalyzeSymbol(context As SymbolAnalysisContext) + End Sub + End Class + """, expected); } [Fact] public async Task CSharp_NoDiagnosticCasesAsync() { - var source = @" -using System; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; + await VerifyCS.VerifyAnalyzerAsync(""" + using System; + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; -[DiagnosticAnalyzer(LanguageNames.CSharp)] -class MyAnalyzer : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics - { - get - { - throw new NotImplementedException(); - } - } - - public override void Initialize(AnalysisContext context) - { - // Valid symbol kinds. - context.RegisterSymbolAction(AnalyzeSymbol, - SymbolKind.Event, - SymbolKind.Field, - SymbolKind.Method, - SymbolKind.NamedType, - SymbolKind.Namespace, - SymbolKind.Property); + [DiagnosticAnalyzer(LanguageNames.CSharp)] + class MyAnalyzer : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics + { + get + { + throw new NotImplementedException(); + } + } - // Overload resolution failure - context.RegisterSymbolAction({|CS1503:AnalyzeSyntax|}, - SymbolKind.Event, - SymbolKind.Field, - SymbolKind.Method, - SymbolKind.NamedType, - SymbolKind.Namespace, - SymbolKind.Property); - } + public override void Initialize(AnalysisContext context) + { + // Valid symbol kinds. + context.RegisterSymbolAction(AnalyzeSymbol, + SymbolKind.Event, + SymbolKind.Field, + SymbolKind.Method, + SymbolKind.NamedType, + SymbolKind.Namespace, + SymbolKind.Property); - private static void AnalyzeSymbol(SymbolAnalysisContext context) - { - } + // Overload resolution failure + context.RegisterSymbolAction({|CS1503:AnalyzeSyntax|}, + SymbolKind.Event, + SymbolKind.Field, + SymbolKind.Method, + SymbolKind.NamedType, + SymbolKind.Namespace, + SymbolKind.Property); + } - private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) - { - } -}"; + private static void AnalyzeSymbol(SymbolAnalysisContext context) + { + } - await VerifyCS.VerifyAnalyzerAsync(source); + private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) + { + } + } + """); } [Fact] public async Task VisualBasic_NoDiagnosticCasesAsync() { - var source = @" -Imports System -Imports System.Collections.Immutable -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics - -Class MyAnalyzer - Inherits DiagnosticAnalyzer - Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) - Get - Throw New NotImplementedException() - End Get - End Property + + Class MyAnalyzer + Inherits DiagnosticAnalyzer + Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) + Get + Throw New NotImplementedException() + End Get + End Property - Public Overrides Sub Initialize(context As AnalysisContext) - - ' Valid symbol kinds - context.RegisterSymbolAction(AddressOf AnalyzeSymbol, - SymbolKind.Event, - SymbolKind.Field, - SymbolKind.Method, - SymbolKind.NamedType, - SymbolKind.Namespace, - SymbolKind.Property) + Public Overrides Sub Initialize(context As AnalysisContext) - ' Overload resolution failure - context.{|BC30518:RegisterSymbolAction|}(AddressOf AnalyzeSyntax, - SymbolKind.Alias) - End Sub + ' Valid symbol kinds + context.RegisterSymbolAction(AddressOf AnalyzeSymbol, + SymbolKind.Event, + SymbolKind.Field, + SymbolKind.Method, + SymbolKind.NamedType, + SymbolKind.Namespace, + SymbolKind.Property) - Private Shared Sub AnalyzeSymbol(context As SymbolAnalysisContext) - End Sub + ' Overload resolution failure + context.{|BC30518:RegisterSymbolAction|}(AddressOf AnalyzeSyntax, + SymbolKind.Alias) + End Sub - Private Shared Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext) - End Sub -End Class -"; + Private Shared Sub AnalyzeSymbol(context As SymbolAnalysisContext) + End Sub - await VerifyVB.VerifyAnalyzerAsync(source); + Private Shared Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext) + End Sub + End Class + """); } private static DiagnosticResult GetCSharpExpectedDiagnostic(int line, int column, SymbolKind unsupportedSymbolKind) => diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/Microsoft.CodeAnalysis.Analyzers.UnitTests.csproj b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/Microsoft.CodeAnalysis.Analyzers.UnitTests.csproj index d855603b027b4..ce32ee839c3ac 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/Microsoft.CodeAnalysis.Analyzers.UnitTests.csproj +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/Microsoft.CodeAnalysis.Analyzers.UnitTests.csproj @@ -3,15 +3,15 @@ $(NetRoslyn) true - $(MicrosoftCodeAnalysisVersionForTests) + true - - - - - - + + + + + + diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/UpgradeMSBuildWorkspaceAnalyzerTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/UpgradeMSBuildWorkspaceAnalyzerTests.cs index 7371f32772647..44f111552487a 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/UpgradeMSBuildWorkspaceAnalyzerTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/UpgradeMSBuildWorkspaceAnalyzerTests.cs @@ -24,39 +24,36 @@ public class UpgradeMSBuildWorkspaceAnalyzerTests new PackageIdentity("Microsoft.CodeAnalysis.CSharp.Workspaces", "2.9.0"), new PackageIdentity("Microsoft.Build.Locator", "1.0.18"))); - private static async Task VerifyCSharpAsync(string source, ReferenceAssemblies referenceAssemblies) - { - await new VerifyCS.Test() + private static Task VerifyCSharpAsync(string source, ReferenceAssemblies referenceAssemblies) + => new VerifyCS.Test() { TestCode = source, FixedCode = source, ReferenceAssemblies = referenceAssemblies, }.RunAsync(); - } - private static async Task VerifyVisualBasicAsync(string source, ReferenceAssemblies referenceAssemblies) - { - await new VerifyVB.Test() + private static Task VerifyVisualBasicAsync(string source, ReferenceAssemblies referenceAssemblies) + => new VerifyVB.Test() { TestCode = source, FixedCode = source, ReferenceAssemblies = referenceAssemblies, }.RunAsync(); - } [Fact] public async Task CSharp_VerifyWithMSBuildWorkspaceAsync() { - const string source = @" -using Microsoft.CodeAnalysis.MSBuild; + const string source = """ + using Microsoft.CodeAnalysis.MSBuild; -class Usage -{ - void M() - { - var workspace = MSBuildWorkspace.Create(); - } -}"; + class Usage + { + void M() + { + var workspace = MSBuildWorkspace.Create(); + } + } + """; await VerifyCSharpAsync(source, s_withMSBuildWorkspaces); } @@ -64,44 +61,47 @@ void M() [Fact] public async Task CSharp_VerifyWithoutMSBuildWorkspaceAsync() { - const string source = @" -using Microsoft.CodeAnalysis.{|CS0234:MSBuild|}; + const string source = """ + using Microsoft.CodeAnalysis.{|CS0234:MSBuild|}; -class Usage -{ - void M() - { - var workspace = [|{|CS0103:MSBuildWorkspace|}|].Create(); - } -}"; + class Usage + { + void M() + { + var workspace = [|{|CS0103:MSBuildWorkspace|}|].Create(); + } + } + """; await VerifyCSharpAsync(source, s_withDesktopWorkspaces); } [Fact] public async Task VisualBasic_VerifyWithMSBuildWorkspaceAsync() { - const string source = @" -Imports Microsoft.CodeAnalysis.MSBuild + const string source = """ + Imports Microsoft.CodeAnalysis.MSBuild -Class Usage - Sub M() - Dim workspace = MSBuildWorkspace.Create() - End Sub -End Class"; + Class Usage + Sub M() + Dim workspace = MSBuildWorkspace.Create() + End Sub + End Class + """; await VerifyVisualBasicAsync(source, s_withMSBuildWorkspaces); } [Fact] public async Task VisualBasic_VerifyWithoutMSBuildWorkspaceAsync() { - const string source = @" -Imports Microsoft.CodeAnalysis.MSBuild + const string source = """ + Imports Microsoft.CodeAnalysis.MSBuild -Class Usage - Sub M() - Dim workspace = [|{|BC30451:MSBuildWorkspace|}|].Create() - End Sub -End Class"; + Class Usage + Sub M() + Dim workspace = [|{|BC30451:MSBuildWorkspace|}|].Create() + End Sub + End Class + """; await VerifyVisualBasicAsync(source, s_withDesktopWorkspaces); } } diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/UseReturnValueFromImmutableObjectMethodTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/UseReturnValueFromImmutableObjectMethodTests.cs index b9a1c038d45df..f8e94b247659f 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/UseReturnValueFromImmutableObjectMethodTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/UnitTests/UseReturnValueFromImmutableObjectMethodTests.cs @@ -20,189 +20,185 @@ public class UseReturnValueFromImmutableObjectMethodTests [Fact] public async Task CSharpVerifyDiagnosticsAsync() { - var source = @" -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Text; - -class TestSimple -{ - void M() - { - Document document = default(Document); - {|#0:document.WithText(default(SourceText))|}; - - Project project = default(Project); - {|#1:project.AddDocument(""Sample.cs"", default(SourceText))|}; - - Solution solution = default(Solution); - {|#2:solution.AddProject(""Sample"", ""Sample"", ""CSharp"")|}; - - Compilation compilation = default(Compilation); - {|#3:compilation.RemoveAllSyntaxTrees()|}; - } -} -"; DiagnosticResult documentExpected = GetCSharpExpectedDiagnostic(0, "Document", "WithText"); DiagnosticResult projectExpected = GetCSharpExpectedDiagnostic(1, "Project", "AddDocument"); DiagnosticResult solutionExpected = GetCSharpExpectedDiagnostic(2, "Solution", "AddProject"); DiagnosticResult compilationExpected = GetCSharpExpectedDiagnostic(3, "Compilation", "RemoveAllSyntaxTrees"); - await VerifyCS.VerifyAnalyzerAsync(source, documentExpected, projectExpected, solutionExpected, compilationExpected); + await VerifyCS.VerifyAnalyzerAsync(""" + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Text; + + class TestSimple + { + void M() + { + Document document = default(Document); + {|#0:document.WithText(default(SourceText))|}; + + Project project = default(Project); + {|#1:project.AddDocument("Sample.cs", default(SourceText))|}; + + Solution solution = default(Solution); + {|#2:solution.AddProject("Sample", "Sample", "CSharp")|}; + + Compilation compilation = default(Compilation); + {|#3:compilation.RemoveAllSyntaxTrees()|}; + } + } + """, documentExpected, projectExpected, solutionExpected, compilationExpected); } [Fact] public async Task VisualBasicVerifyDiagnosticsAsync() { - var source = @" -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Text - -Class TestSimple - Sub M() - Dim document As Document = Nothing - {|#0:document.WithText(Nothing)|} - - Dim project As Project = Nothing - {|#1:project.AddDocument(""Sample.cs"", CType(Nothing, SourceText))|} - - Dim solution As Solution = Nothing - {|#2:solution.AddProject(""Sample"", ""Sample"", ""CSharp"")|} - - Dim compilation As Compilation = Nothing - {|#3:compilation.RemoveAllSyntaxTrees()|} - End Sub -End Class -"; DiagnosticResult documentExpected = GetVisualBasicExpectedDiagnostic(0, "Document", "WithText"); DiagnosticResult projectExpected = GetVisualBasicExpectedDiagnostic(1, "Project", "AddDocument"); DiagnosticResult solutionExpected = GetVisualBasicExpectedDiagnostic(2, "Solution", "AddProject"); DiagnosticResult compilationExpected = GetVisualBasicExpectedDiagnostic(3, "Compilation", "RemoveAllSyntaxTrees"); - await VerifyVB.VerifyAnalyzerAsync(source, documentExpected, projectExpected, solutionExpected, compilationExpected); + await VerifyVB.VerifyAnalyzerAsync(""" + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Text + + Class TestSimple + Sub M() + Dim document As Document = Nothing + {|#0:document.WithText(Nothing)|} + + Dim project As Project = Nothing + {|#1:project.AddDocument("Sample.cs", CType(Nothing, SourceText))|} + + Dim solution As Solution = Nothing + {|#2:solution.AddProject("Sample", "Sample", "CSharp")|} + + Dim compilation As Compilation = Nothing + {|#3:compilation.RemoveAllSyntaxTrees()|} + End Sub + End Class + """, documentExpected, projectExpected, solutionExpected, compilationExpected); } [Fact] public async Task CSharp_VerifyDiagnosticOnExtensionMethodAsync() { - var source = @" -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Text; - -class TestExtensionMethodTrivia -{ - void M() - { - SyntaxNode node = default(SyntaxNode); - {|#0:node.WithLeadingTrivia()|}; - } -}"; DiagnosticResult expected = GetCSharpExpectedDiagnostic(0, "SyntaxNode", "WithLeadingTrivia"); - await VerifyCS.VerifyAnalyzerAsync(source, expected); + await VerifyCS.VerifyAnalyzerAsync(""" + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Text; + + class TestExtensionMethodTrivia + { + void M() + { + SyntaxNode node = default(SyntaxNode); + {|#0:node.WithLeadingTrivia()|}; + } + } + """, expected); } [Fact] public async Task VisualBasic_VerifyDiagnosticOnExtensionMethodAsync() { - var source = @" -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Text - -Class TestExtensionMethodTrivia - Sub M() - Dim node As SyntaxNode = Nothing - {|#0:node.WithLeadingTrivia()|} - End Sub -End Class"; DiagnosticResult expected = GetVisualBasicExpectedDiagnostic(0, "SyntaxNode", "WithLeadingTrivia"); - await VerifyVB.VerifyAnalyzerAsync(source, expected); + await VerifyVB.VerifyAnalyzerAsync(""" + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Text + + Class TestExtensionMethodTrivia + Sub M() + Dim node As SyntaxNode = Nothing + {|#0:node.WithLeadingTrivia()|} + End Sub + End Class + """, expected); } [Fact] - public async Task CSharp_VerifyNoDiagnosticAsync() - { - var source = @" -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Text; - -namespace ConsoleApplication1 -{ - class TestNoDiagnostic - { - public Document M() - { - Document document = default(Document); - var newDocument = document.WithText(default(SourceText)); - document = document.WithText(default(SourceText)); - - OtherMethod(document.WithText(default(SourceText))); - return document.WithText(default(SourceText)); - } - - public void OtherMethod(Document document) - { - } - } -}"; - await VerifyCS.VerifyAnalyzerAsync(source); - } + public Task CSharp_VerifyNoDiagnosticAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Text; + + namespace ConsoleApplication1 + { + class TestNoDiagnostic + { + public Document M() + { + Document document = default(Document); + var newDocument = document.WithText(default(SourceText)); + document = document.WithText(default(SourceText)); + + OtherMethod(document.WithText(default(SourceText))); + return document.WithText(default(SourceText)); + } + + public void OtherMethod(Document document) + { + } + } + } + """); [Fact] - public async Task VisualBasic_VerifyNoDiagnosticAsync() - { - var source = @" -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Text - -Namespace ConsoleApplication1 - Class TestNoDiagnostic - Public Function M() As Document - Dim document As Document = Nothing - Dim newDocument = document.WithText(Nothing) - document = document.WithText(Nothing) - - OtherMethod(document.WithText(Nothing)) - Return document.WithText(Nothing) - End Function - - Public Sub OtherMethod(document As Document) - End Sub - End Class -End Namespace"; - await VerifyVB.VerifyAnalyzerAsync(source); - } + public Task VisualBasic_VerifyNoDiagnosticAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Text + + Namespace ConsoleApplication1 + Class TestNoDiagnostic + Public Function M() As Document + Dim document As Document = Nothing + Dim newDocument = document.WithText(Nothing) + document = document.WithText(Nothing) + + OtherMethod(document.WithText(Nothing)) + Return document.WithText(Nothing) + End Function + + Public Sub OtherMethod(document As Document) + End Sub + End Class + End Namespace + """); [Fact] public async Task CSharp_ReturnsVoid() { - var source = @" -namespace Microsoft.CodeAnalysis -{ - public class Compilation - { - internal void AddSomething() - { - } - - internal void M() => AddSomething(); - } -}"; + var source = """ + namespace Microsoft.CodeAnalysis + { + public class Compilation + { + internal void AddSomething() + { + } + + internal void M() => AddSomething(); + } + } + """; await VerifyCS.VerifyCodeFixAsync(source, source); } [Fact] public async Task VisualBasic_ReturnsVoid() { - var source = @" -Namespace Microsoft.CodeAnalysis - Public Class Compilation - Friend Sub AddSomething() - End Sub - - Friend Sub M() - AddSomething() - End Sub - End Class -End Namespace"; + var source = """ + Namespace Microsoft.CodeAnalysis + Public Class Compilation + Friend Sub AddSomething() + End Sub + + Friend Sub M() + AddSomething() + End Sub + End Class + End Namespace + """; await VerifyVB.VerifyCodeFixAsync(source, source); } diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.Analyzers.vbproj b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.Analyzers.vbproj index ecd76b9973106..7268a9278819e 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.Analyzers.vbproj +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.Analyzers.vbproj @@ -3,7 +3,6 @@ netstandard2.0 - $(MicrosoftCodeAnalysisVersionForCodeAnalysisAnalyzers) @@ -11,10 +10,22 @@ - - - - - - + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/VisualBasic/VisualBasicUpgradeMSBuildWorkspaceAnalyzer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/VisualBasic/VisualBasicUpgradeMSBuildWorkspaceAnalyzer.vb index 9ab5739c8aedc..ad30b06a8987c 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/VisualBasic/VisualBasicUpgradeMSBuildWorkspaceAnalyzer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/VisualBasic/VisualBasicUpgradeMSBuildWorkspaceAnalyzer.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Analyzer.Utilities.Extensions -Imports Microsoft.CodeAnalysis.Analyzers Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/CSharp/CSharpSymbolIsBannedAnalyzer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/CSharp/CSharpSymbolIsBannedAnalyzer.cs index dde086c94da26..7a8262626fd09 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/CSharp/CSharpSymbolIsBannedAnalyzer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/CSharp/CSharpSymbolIsBannedAnalyzer.cs @@ -2,12 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.BannedApiAnalyzers; +using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; -using System.Collections.Generic; +using Microsoft.CodeAnalysis.BannedApiAnalyzers; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.BannedApiAnalyzers { diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/CSharp/Microsoft.CodeAnalysis.CSharp.BannedApiAnalyzers.csproj b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/CSharp/Microsoft.CodeAnalysis.CSharp.BannedApiAnalyzers.csproj index f6314d78423ae..5f484c8d5afe4 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/CSharp/Microsoft.CodeAnalysis.CSharp.BannedApiAnalyzers.csproj +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/CSharp/Microsoft.CodeAnalysis.CSharp.BannedApiAnalyzers.csproj @@ -2,11 +2,10 @@ netstandard2.0 - $(MicrosoftCodeAnalysisVersionForBannedApiAnalyzers) - - + + diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/BannedApiAnalyzerResources.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/BannedApiAnalyzerResources.cs index 1287e1c7ec890..77dd93f659c37 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/BannedApiAnalyzerResources.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/BannedApiAnalyzerResources.cs @@ -4,7 +4,7 @@ using System; -namespace Microsoft.CodeAnalysis.BannedApiAnalyzers +namespace Microsoft.CodeAnalysis { internal partial class BannedApiAnalyzerResources { diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/DocumentationCommentIdParser.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/DocumentationCommentIdParser.cs index 9aef41eb17ece..eee87587af75b 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/DocumentationCommentIdParser.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/DocumentationCommentIdParser.cs @@ -10,7 +10,7 @@ namespace Microsoft.CodeAnalysis.BannedApiAnalyzers /// internal static class DocumentationCommentIdParser { - private static readonly char[] s_nameDelimiters = { ':', '.', '(', ')', '{', '}', '[', ']', ',', '\'', '@', '*', '`', '~' }; + private static readonly char[] s_nameDelimiters = [':', '.', '(', ')', '{', '}', '[', ']', ',', '\'', '@', '*', '`', '~']; public static (string ParentName, string SymbolName)? ParseDeclaredSymbolId(string id) { diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/Microsoft.CodeAnalysis.BannedApiAnalyzers.csproj b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/Microsoft.CodeAnalysis.BannedApiAnalyzers.csproj index 50581fa6cc713..1a9dca530bbdf 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/Microsoft.CodeAnalysis.BannedApiAnalyzers.csproj +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/Microsoft.CodeAnalysis.BannedApiAnalyzers.csproj @@ -7,10 +7,11 @@ Restore would conclude that there is a cyclic dependency between us and the Microsoft.CodeAnalysis.BannedApiAnalyzer package. --> *$(MSBuildProjectFile)* - $(MicrosoftCodeAnalysisVersionForBannedApiAnalyzers) + Microsoft.CodeAnalysis - + + @@ -24,4 +25,13 @@ + + + + + + + + + diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/RestrictedInternalsVisibleToAnalyzer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/RestrictedInternalsVisibleToAnalyzer.cs index 259d3e271ab88..b4d55f87ba9cd 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/RestrictedInternalsVisibleToAnalyzer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/RestrictedInternalsVisibleToAnalyzer.cs @@ -11,7 +11,8 @@ using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; - +using Microsoft.CodeAnalysis.Shared.Extensions; +using Microsoft.CodeAnalysis.Shared.Utilities; using DiagnosticIds = Roslyn.Diagnostics.Analyzers.RoslynDiagnosticIds; namespace Microsoft.CodeAnalysis.BannedApiAnalyzers @@ -192,7 +193,7 @@ private static void VerifySymbol( if (symbol != null && IsBannedSymbol(symbol, restrictedInternalsVisibleToMap, namespaceToIsBannedMap)) { - var bannedSymbolDisplayString = symbol.ToDisplayString(SymbolDisplayFormats.QualifiedTypeAndNamespaceSymbolDisplayFormat); + var bannedSymbolDisplayString = symbol.ToDisplayString(Analyzer.Utilities.SymbolDisplayFormats.QualifiedTypeAndNamespaceSymbolDisplayFormat); var assemblyName = symbol.ContainingAssembly.Name; var restrictedNamespaces = string.Join(", ", restrictedInternalsVisibleToMap[symbol.ContainingAssembly]); var diagnostic = node.CreateDiagnostic(Rule, bannedSymbolDisplayString, assemblyName, restrictedNamespaces); diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/SymbolIsBannedAnalyzerBase.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/SymbolIsBannedAnalyzerBase.cs index 844bda1a5c5cc..8d6e96c742b64 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/SymbolIsBannedAnalyzerBase.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/SymbolIsBannedAnalyzerBase.cs @@ -11,6 +11,7 @@ using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; +using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.BannedApiAnalyzers diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/UnitTests/Microsoft.CodeAnalysis.BannedApiAnalyzers.UnitTests.csproj b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/UnitTests/Microsoft.CodeAnalysis.BannedApiAnalyzers.UnitTests.csproj index 682600f323ee1..605faecccd633 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/UnitTests/Microsoft.CodeAnalysis.BannedApiAnalyzers.UnitTests.csproj +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/UnitTests/Microsoft.CodeAnalysis.BannedApiAnalyzers.UnitTests.csproj @@ -4,15 +4,14 @@ $(NetRoslyn) true true - $(MicrosoftCodeAnalysisVersionForTests) - - - - - - + + + + + + diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/UnitTests/RestrictedInternalsVisibleToAnalyzerTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/UnitTests/RestrictedInternalsVisibleToAnalyzerTests.cs index bdf1aa0ee4287..a02c9e4c63f5d 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/UnitTests/RestrictedInternalsVisibleToAnalyzerTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/UnitTests/RestrictedInternalsVisibleToAnalyzerTests.cs @@ -40,27 +40,31 @@ private static DiagnosticResult GetBasicResultAt(int startLine, int startColumn, private const string CSharpApiProviderFileName = "ApiProviderFileName.cs"; private const string VisualBasicApiProviderFileName = "ApiProviderFileName.vb"; - private const string CSharpRestrictedInternalsVisibleToAttribute = @" -namespace System.Runtime.CompilerServices -{ - [System.AttributeUsage(System.AttributeTargets.Assembly, AllowMultiple = true)] - internal class RestrictedInternalsVisibleToAttribute : System.Attribute - { - public RestrictedInternalsVisibleToAttribute(string assemblyName, params string[] restrictedNamespaces) - { - } - } -}"; - private const string VisualBasicRestrictedInternalsVisibleToAttribute = @" -Namespace System.Runtime.CompilerServices - - Friend Class RestrictedInternalsVisibleToAttribute - Inherits System.Attribute - - Public Sub New(ByVal assemblyName As String, ParamArray restrictedNamespaces As String()) - End Sub - End Class -End Namespace"; + private const string CSharpRestrictedInternalsVisibleToAttribute = """ + + namespace System.Runtime.CompilerServices + { + [System.AttributeUsage(System.AttributeTargets.Assembly, AllowMultiple = true)] + internal class RestrictedInternalsVisibleToAttribute : System.Attribute + { + public RestrictedInternalsVisibleToAttribute(string assemblyName, params string[] restrictedNamespaces) + { + } + } + } + """; + private const string VisualBasicRestrictedInternalsVisibleToAttribute = """ + + Namespace System.Runtime.CompilerServices + + Friend Class RestrictedInternalsVisibleToAttribute + Inherits System.Attribute + + Public Sub New(ByVal assemblyName As String, ParamArray restrictedNamespaces As String()) + End Sub + End Class + End Namespace + """; private async Task VerifyCSharpAsync(string apiProviderSource, string apiConsumerSource, params DiagnosticResult[] expected) { @@ -126,942 +130,869 @@ private static Solution ApplySolutionTransforms(Solution solution, ProjectId api } [Fact] - public async Task CSharp_NoIVT_NoRestrictedIVT_NoDiagnosticAsync() - { - var apiProviderSource = @" -namespace N1 -{ - internal class C1 { } -}"; + public Task CSharp_NoIVT_NoRestrictedIVT_NoDiagnosticAsync() + => VerifyCSharpAsync(""" - var apiConsumerSource = @" -class C2 -{ - void M(N1.{|CS0122:C1|} c) - { - } -}"; + namespace N1 + { + internal class C1 { } + } + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource); - } + class C2 + { + void M(N1.{|CS0122:C1|} c) + { + } + } + """); [Fact] - public async Task Basic_NoIVT_NoRestrictedIVT_NoDiagnosticAsync() - { - var apiProviderSource = @" -Namespace N1 - Friend Class C1 - End Class -End Namespace"; - - var apiConsumerSource = @" -Class C2 - Private Sub M(c As {|BC30389:N1.C1|}) - End Sub -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource); - } + public Task Basic_NoIVT_NoRestrictedIVT_NoDiagnosticAsync() + => VerifyBasicAsync(""" + + Namespace N1 + Friend Class C1 + End Class + End Namespace + """, """ + + Class C2 + Private Sub M(c As {|BC30389:N1.C1|}) + End Sub + End Class + """); [Fact] - public async Task CSharp_IVT_NoRestrictedIVT_NoDiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] + public Task CSharp_IVT_NoRestrictedIVT_NoDiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - internal class C1 { } -}"; + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] - var apiConsumerSource = @" -class C2 -{ - void M(N1.C1 c) - { - } -}"; + namespace N1 + { + internal class C1 { } + } + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource); - } + class C2 + { + void M(N1.C1 c) + { + } + } + """); [Fact] - public async Task Basic_IVT_NoRestrictedIVT_NoDiagnosticAsync() - { - var apiProviderSource = @" - + public Task Basic_IVT_NoRestrictedIVT_NoDiagnosticAsync() + => VerifyBasicAsync(""" -Namespace N1 - Friend Class C1 - End Class -End Namespace"; + - var apiConsumerSource = @" -Class C2 - Private Sub M(c As N1.C1) - End Sub -End Class"; + Namespace N1 + Friend Class C1 + End Class + End Namespace + """, """ - await VerifyBasicAsync(apiProviderSource, apiConsumerSource); - } + Class C2 + Private Sub M(c As N1.C1) + End Sub + End Class + """); [Fact] - public async Task CSharp_NoIVT_RestrictedIVT_NoDiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""NonExistentNamespace"")] + public Task CSharp_NoIVT_RestrictedIVT_NoDiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - internal class C1 { } -}"; + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "NonExistentNamespace")] - var apiConsumerSource = @" -class C2 -{ - void M(N1.{|CS0122:C1|} c) - { - } -}"; + namespace N1 + { + internal class C1 { } + } + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource); - } + class C2 + { + void M(N1.{|CS0122:C1|} c) + { + } + } + """); [Fact] - public async Task Basic_NoIVT_RestrictedIVT_NoDiagnosticAsync() - { - var apiProviderSource = @" - + public Task Basic_NoIVT_RestrictedIVT_NoDiagnosticAsync() + => VerifyBasicAsync(""" -Namespace N1 - Friend Class C1 - End Class -End Namespace"; + - var apiConsumerSource = @" -Class C2 - Private Sub M(c As {|BC30389:N1.C1|}) - End Sub -End Class"; + Namespace N1 + Friend Class C1 + End Class + End Namespace + """, """ - await VerifyBasicAsync(apiProviderSource, apiConsumerSource); - } + Class C2 + Private Sub M(c As {|BC30389:N1.C1|}) + End Sub + End Class + """); [Fact] - public async Task CSharp_IVT_RestrictedIVT_BasicScenario_NoDiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N1"")] + public Task CSharp_IVT_RestrictedIVT_BasicScenario_NoDiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - internal class C1 { } -}"; + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N1")] - var apiConsumerSource = @" -class C2 -{ - void M(N1.C1 c) - { - } -}"; + namespace N1 + { + internal class C1 { } + } + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource); - } + class C2 + { + void M(N1.C1 c) + { + } + } + """); [Fact] - public async Task Basic_IVT_RestrictedIVT_BasicScenario_NoDiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Friend Class C1 - End Class -End Namespace"; - - var apiConsumerSource = @" -Class C2 - Private Sub M(c As N1.C1) - End Sub -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource); - } + public Task Basic_IVT_RestrictedIVT_BasicScenario_NoDiagnosticAsync() + => VerifyBasicAsync(""" + + + + + Namespace N1 + Friend Class C1 + End Class + End Namespace + """, """ + + Class C2 + Private Sub M(c As N1.C1) + End Sub + End Class + """); [Fact] - public async Task CSharp_IVT_RestrictedIVT_BasicScenario_DiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N2"")] + public Task CSharp_IVT_RestrictedIVT_BasicScenario_DiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - internal class C1 { } -}"; + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N2")] - var apiConsumerSource = @" -class C2 -{ - void M({|#0:N1.C1|} c) - { - } -}"; + namespace N1 + { + internal class C1 { } + } + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource, + class C2 + { + void M({|#0:N1.C1|} c) + { + } + } + """, GetCSharpResultAt(0, "N1.C1", "N2")); - } [Fact] - public async Task Basic_IVT_RestrictedIVT_BasicScenario_DiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Friend Class C1 - End Class -End Namespace"; - - var apiConsumerSource = @" -Class C2 - Private Sub M(c As {|#0:N1.C1|}) - End Sub -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource, + public Task Basic_IVT_RestrictedIVT_BasicScenario_DiagnosticAsync() + => VerifyBasicAsync(""" + + + + + Namespace N1 + Friend Class C1 + End Class + End Namespace + """, """ + + Class C2 + Private Sub M(c As {|#0:N1.C1|}) + End Sub + End Class + """, GetBasicResultAt(0, "N1.C1", "N2")); - } [Fact] - public async Task CSharp_IVT_RestrictedIVT_MultipleAttributes_NoDiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N1"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N2"")] + public Task CSharp_IVT_RestrictedIVT_MultipleAttributes_NoDiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - internal class C1 { } -} + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N1")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N2")] -namespace N2 -{ - internal class C2 { } -}"; + namespace N1 + { + internal class C1 { } + } - var apiConsumerSource = @" -class C2 -{ - void M(N1.C1 c1, N2.C2 c2) - { - } -}"; + namespace N2 + { + internal class C2 { } + } + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource); - } + class C2 + { + void M(N1.C1 c1, N2.C2 c2) + { + } + } + """); [Fact] - public async Task Basic_IVT_RestrictedIVT_MultipleAttributes_NoDiagnosticAsync() - { - var apiProviderSource = @" - - - - -Namespace N1 - Friend Class C1 - End Class -End Namespace - -Namespace N2 - Friend Class C2 - End Class -End Namespace"; - - var apiConsumerSource = @" -Class C2 - Private Sub M(c1 As N1.C1, c2 As N2.C2) - End Sub -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource); - } + public Task Basic_IVT_RestrictedIVT_MultipleAttributes_NoDiagnosticAsync() + => VerifyBasicAsync(""" + + + + + + Namespace N1 + Friend Class C1 + End Class + End Namespace + + Namespace N2 + Friend Class C2 + End Class + End Namespace + """, """ + + Class C2 + Private Sub M(c1 As N1.C1, c2 As N2.C2) + End Sub + End Class + """); [Fact] - public async Task CSharp_IVT_RestrictedIVT_MultipleAttributes_DiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N1"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N2"")] + public Task CSharp_IVT_RestrictedIVT_MultipleAttributes_DiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - internal class C1 { } -} + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N1")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N2")] -namespace N2 -{ - internal class C2 { } -} + namespace N1 + { + internal class C1 { } + } -namespace N3 -{ - internal class C3 { } -}"; + namespace N2 + { + internal class C2 { } + } - var apiConsumerSource = @" -class C2 -{ - void M(N1.C1 c1, N2.C2 c2, {|#0:N3.C3|} c3) - { - } -}"; + namespace N3 + { + internal class C3 { } + } + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource, + class C2 + { + void M(N1.C1 c1, N2.C2 c2, {|#0:N3.C3|} c3) + { + } + } + """, GetCSharpResultAt(0, "N3.C3", "N1, N2")); - } [Fact] - public async Task Basic_IVT_RestrictedIVT_MultipleAttributes_DiagnosticAsync() - { - var apiProviderSource = @" - - - - -Namespace N1 - Friend Class C1 - End Class -End Namespace - -Namespace N2 - Friend Class C2 - End Class -End Namespace - -Namespace N3 - Friend Class C3 - End Class -End Namespace"; - - var apiConsumerSource = @" -Class C2 - Private Sub M(c1 As N1.C1, c2 As N2.C2, c3 As {|#0:N3.C3|}) - End Sub -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource, + public Task Basic_IVT_RestrictedIVT_MultipleAttributes_DiagnosticAsync() + => VerifyBasicAsync(""" + + + + + + Namespace N1 + Friend Class C1 + End Class + End Namespace + + Namespace N2 + Friend Class C2 + End Class + End Namespace + + Namespace N3 + Friend Class C3 + End Class + End Namespace + """, """ + + Class C2 + Private Sub M(c1 As N1.C1, c2 As N2.C2, c3 As {|#0:N3.C3|}) + End Sub + End Class + """, GetCSharpResultAt(0, "N3.C3", "N1, N2")); - } [Fact] - public async Task CSharp_IVT_RestrictedIVT_ProjectNameMismatch_NoDiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""XYZ"", ""NonExistentNamespace"")] + public Task CSharp_IVT_RestrictedIVT_ProjectNameMismatch_NoDiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - internal class C1 { } -}"; + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("XYZ", "NonExistentNamespace")] - var apiConsumerSource = @" -class C2 -{ - void M(N1.C1 c) - { - } -}"; + namespace N1 + { + internal class C1 { } + } + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource); - } + class C2 + { + void M(N1.C1 c) + { + } + } + """); [Fact] - public async Task Basic_IVT_RestrictedIVT_ProjectNameMismatch_NoDiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Friend Class C1 - End Class -End Namespace"; - - var apiConsumerSource = @" -Class C2 - Private Sub M(c As N1.C1) - End Sub -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource); - } + public Task Basic_IVT_RestrictedIVT_ProjectNameMismatch_NoDiagnosticAsync() + => VerifyBasicAsync(""" + + + + + Namespace N1 + Friend Class C1 + End Class + End Namespace + """, """ + + Class C2 + Private Sub M(c As N1.C1) + End Sub + End Class + """); [Fact] - public async Task CSharp_IVT_RestrictedIVT_ProjectNameMismatch_DiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N2"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""XYZ"", ""N1"")] + public Task CSharp_IVT_RestrictedIVT_ProjectNameMismatch_DiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - internal class C1 { } -}"; + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N2")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("XYZ", "N1")] - var apiConsumerSource = @" -class C2 -{ - void M({|#0:N1.C1|} c) - { - } -}"; + namespace N1 + { + internal class C1 { } + } + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource, + class C2 + { + void M({|#0:N1.C1|} c) + { + } + } + """, GetCSharpResultAt(0, "N1.C1", "N2")); - } [Fact] - public async Task Basic_IVT_RestrictedIVT_ProjectNameMismatch_DiagnosticAsync() - { - var apiProviderSource = @" - - - - -Namespace N1 - Friend Class C1 - End Class -End Namespace"; - - var apiConsumerSource = @" -Class C2 - Private Sub M(c As {|#0:N1.C1|}) - End Sub -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource, + public Task Basic_IVT_RestrictedIVT_ProjectNameMismatch_DiagnosticAsync() + => VerifyBasicAsync(""" + + + + + + Namespace N1 + Friend Class C1 + End Class + End Namespace + """, """ + + Class C2 + Private Sub M(c As {|#0:N1.C1|}) + End Sub + End Class + """, GetBasicResultAt(0, "N1.C1", "N2")); - } [Fact] - public async Task CSharp_IVT_RestrictedIVT_NoRestrictedNamespace_NoDiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"")] + public Task CSharp_IVT_RestrictedIVT_NoRestrictedNamespace_NoDiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - internal class C1 { } -}"; + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName")] - var apiConsumerSource = @" -class C2 -{ - void M(N1.C1 c) - { - } -}"; + namespace N1 + { + internal class C1 { } + } + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource); - } + class C2 + { + void M(N1.C1 c) + { + } + } + """); [Fact] - public async Task Basic_IVT_RestrictedIVT_NoRestrictedNamespace_NoDiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Friend Class C1 - End Class -End Namespace"; - - var apiConsumerSource = @" -Class C2 - Private Sub M(c As N1.C1) - End Sub -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource); - } + public Task Basic_IVT_RestrictedIVT_NoRestrictedNamespace_NoDiagnosticAsync() + => VerifyBasicAsync(""" + + + + + Namespace N1 + Friend Class C1 + End Class + End Namespace + """, """ + + Class C2 + Private Sub M(c As N1.C1) + End Sub + End Class + """); [Fact] - public async Task CSharp_IVT_RestrictedIVT_QualifiedNamespace_NoDiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N1.N2"")] + public Task CSharp_IVT_RestrictedIVT_QualifiedNamespace_NoDiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - namespace N2 - { - internal class C1 { } - } -}"; + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N1.N2")] - var apiConsumerSource = @" -class C2 -{ - void M(N1.N2.C1 c) - { - } -}"; + namespace N1 + { + namespace N2 + { + internal class C1 { } + } + } + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource); - } + class C2 + { + void M(N1.N2.C1 c) + { + } + } + """); [Fact] - public async Task Basic_IVT_RestrictedIVT_QualifiedNamespace_NoDiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Namespace N2 - Friend Class C1 - End Class - End Namespace -End Namespace"; - - var apiConsumerSource = @" -Class C2 - Private Sub M(c As N1.N2.C1) - End Sub -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource); - } + public Task Basic_IVT_RestrictedIVT_QualifiedNamespace_NoDiagnosticAsync() + => VerifyBasicAsync(""" + + + + + Namespace N1 + Namespace N2 + Friend Class C1 + End Class + End Namespace + End Namespace + """, """ + + Class C2 + Private Sub M(c As N1.N2.C1) + End Sub + End Class + """); [Fact] - public async Task CSharp_IVT_RestrictedIVT_QualifiedNamespace_DiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N1.N2"")] + public Task CSharp_IVT_RestrictedIVT_QualifiedNamespace_DiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - namespace N2 - { - internal class C1 { } - } + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N1.N2")] - internal class C3 { } -}"; + namespace N1 + { + namespace N2 + { + internal class C1 { } + } - var apiConsumerSource = @" -class C2 -{ - void M(N1.N2.C1 c1, {|#0:N1.C3|} c3) - { - } -}"; + internal class C3 { } + } + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource, + class C2 + { + void M(N1.N2.C1 c1, {|#0:N1.C3|} c3) + { + } + } + """, GetCSharpResultAt(0, "N1.C3", "N1.N2")); - } [Fact] - public async Task Basic_IVT_RestrictedIVT_QualifiedNamespace_DiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Namespace N2 - Friend Class C1 - End Class - End Namespace - - Friend Class C3 - End Class -End Namespace"; - - var apiConsumerSource = @" -Class C2 - Private Sub M(c1 As N1.N2.C1, c3 As {|#0:N1.C3|}) - End Sub -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource, + public Task Basic_IVT_RestrictedIVT_QualifiedNamespace_DiagnosticAsync() + => VerifyBasicAsync(""" + + + + + Namespace N1 + Namespace N2 + Friend Class C1 + End Class + End Namespace + + Friend Class C3 + End Class + End Namespace + """, """ + + Class C2 + Private Sub M(c1 As N1.N2.C1, c3 As {|#0:N1.C3|}) + End Sub + End Class + """, GetBasicResultAt(0, "N1.C3", "N1.N2")); - } [Fact] - public async Task CSharp_IVT_RestrictedIVT_AncestorNamespace_NoDiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N1"")] + public Task CSharp_IVT_RestrictedIVT_AncestorNamespace_NoDiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - namespace N2 - { - internal class C1 { } - } -}"; + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N1")] - var apiConsumerSource = @" -class C2 -{ - void M(N1.N2.C1 c) - { - } -}"; + namespace N1 + { + namespace N2 + { + internal class C1 { } + } + } + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource); - } + class C2 + { + void M(N1.N2.C1 c) + { + } + } + """); [Fact] - public async Task Basic_IVT_RestrictedIVT_AncestorNamespace_NoDiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Namespace N2 - Friend Class C1 - End Class - End Namespace -End Namespace"; - - var apiConsumerSource = @" -Class C2 - Private Sub M(c As N1.N2.C1) - End Sub -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource); - } + public Task Basic_IVT_RestrictedIVT_AncestorNamespace_NoDiagnosticAsync() + => VerifyBasicAsync(""" + + + + + Namespace N1 + Namespace N2 + Friend Class C1 + End Class + End Namespace + End Namespace + """, """ + + Class C2 + Private Sub M(c As N1.N2.C1) + End Sub + End Class + """); [Fact] - public async Task CSharp_IVT_RestrictedIVT_AncestorNamespace_DiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N1.N2"")] + public Task CSharp_IVT_RestrictedIVT_AncestorNamespace_DiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - namespace N2 - { - internal class C1 { } - } + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N1.N2")] - internal class C2 { } -}"; + namespace N1 + { + namespace N2 + { + internal class C1 { } + } - var apiConsumerSource = @" -class C2 -{ - void M(N1.N2.C1 c1, {|#0:N1.C2|} c2) - { - } -}"; + internal class C2 { } + } + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource, + class C2 + { + void M(N1.N2.C1 c1, {|#0:N1.C2|} c2) + { + } + } + """, GetCSharpResultAt(0, "N1.C2", "N1.N2")); - } [Fact] - public async Task Basic_IVT_RestrictedIVT_AncestorNamespace_DiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Namespace N2 - Friend Class C1 - End Class - End Namespace - - Friend Class C2 - End Class -End Namespace"; - - var apiConsumerSource = @" -Class C2 - Private Sub M(c1 As N1.N2.C1, c2 As {|#0:N1.C2|}) - End Sub -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource, + public Task Basic_IVT_RestrictedIVT_AncestorNamespace_DiagnosticAsync() + => VerifyBasicAsync(""" + + + + + Namespace N1 + Namespace N2 + Friend Class C1 + End Class + End Namespace + + Friend Class C2 + End Class + End Namespace + """, """ + + Class C2 + Private Sub M(c1 As N1.N2.C1, c2 As {|#0:N1.C2|}) + End Sub + End Class + """, GetBasicResultAt(0, "N1.C2", "N1.N2")); - } [Fact] - public async Task CSharp_IVT_RestrictedIVT_QualifiedAndAncestorNamespace_NoDiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N1"", ""N1.N2"")] + public Task CSharp_IVT_RestrictedIVT_QualifiedAndAncestorNamespace_NoDiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - namespace N2 - { - internal class C1 { } - } -}"; + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N1", "N1.N2")] - var apiConsumerSource = @" -class C2 -{ - void M(N1.N2.C1 c) - { - } -}"; + namespace N1 + { + namespace N2 + { + internal class C1 { } + } + } + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource); - } + class C2 + { + void M(N1.N2.C1 c) + { + } + } + """); [Fact] - public async Task Basic_IVT_RestrictedIVT_QualifiedAndAncestorNamespace_NoDiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Namespace N2 - Friend Class C1 - End Class - End Namespace -End Namespace"; - - var apiConsumerSource = @" -Class C2 - Private Sub M(c As N1.N2.C1) - End Sub -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource); - } + public Task Basic_IVT_RestrictedIVT_QualifiedAndAncestorNamespace_NoDiagnosticAsync() + => VerifyBasicAsync(""" + + + + + Namespace N1 + Namespace N2 + Friend Class C1 + End Class + End Namespace + End Namespace + """, """ + + Class C2 + Private Sub M(c As N1.N2.C1) + End Sub + End Class + """); [Fact] - public async Task CSharp_IVT_RestrictedIVT_NestedType_NoDiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N1"")] + public Task CSharp_IVT_RestrictedIVT_NestedType_NoDiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - internal class C1 { internal class Nested { } } -}"; + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N1")] - var apiConsumerSource = @" -class C2 -{ - void M(N1.C1 c, N1.C1.Nested nested) - { - } -}"; + namespace N1 + { + internal class C1 { internal class Nested { } } + } + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource); - } + class C2 + { + void M(N1.C1 c, N1.C1.Nested nested) + { + } + } + """); [Fact] - public async Task Basic_IVT_RestrictedIVT_NestedType_NoDiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Friend Class C1 - Friend Class Nested - End Class - End Class -End Namespace"; - - var apiConsumerSource = @" -Class C2 - Private Sub M(c As N1.C1, nested As N1.C1.Nested) - End Sub -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource); - } + public Task Basic_IVT_RestrictedIVT_NestedType_NoDiagnosticAsync() + => VerifyBasicAsync(""" - [Fact] - public async Task CSharp_IVT_RestrictedIVT_NestedType_DiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N2"")] + + -namespace N1 -{ - public class C1 { internal class Nested { } } -}"; + Namespace N1 + Friend Class C1 + Friend Class Nested + End Class + End Class + End Namespace + """, """ - var apiConsumerSource = @" -class C2 -{ - void M(N1.C1 c, {|#0:N1.C1.Nested|} nested) - { - } -}"; + Class C2 + Private Sub M(c As N1.C1, nested As N1.C1.Nested) + End Sub + End Class + """); + + [Fact] + public Task CSharp_IVT_RestrictedIVT_NestedType_DiagnosticAsync() + => VerifyCSharpAsync(""" + + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N2")] - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource, + namespace N1 + { + public class C1 { internal class Nested { } } + } + """, """ + + class C2 + { + void M(N1.C1 c, {|#0:N1.C1.Nested|} nested) + { + } + } + """, GetCSharpResultAt(0, "N1.C1.Nested", "N2")); - } [Fact] - public async Task Basic_IVT_RestrictedIVT_NestedType_DiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Public Class C1 - Friend Class Nested - End Class - End Class -End Namespace"; - - var apiConsumerSource = @" -Class C2 - Private Sub M(c As N1.C1, nested As {|#0:N1.C1.Nested|}) - End Sub -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource, + public Task Basic_IVT_RestrictedIVT_NestedType_DiagnosticAsync() + => VerifyBasicAsync(""" + + + + + Namespace N1 + Public Class C1 + Friend Class Nested + End Class + End Class + End Namespace + """, """ + + Class C2 + Private Sub M(c As N1.C1, nested As {|#0:N1.C1.Nested|}) + End Sub + End Class + """, GetBasicResultAt(0, "N1.C1.Nested", "N2")); - } [Fact] - public async Task CSharp_IVT_RestrictedIVT_UsageInAttributes_NoDiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N1"")] + public Task CSharp_IVT_RestrictedIVT_UsageInAttributes_NoDiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - internal class C1 : System.Attribute - { - public C1(object o) { } - } -}"; + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N1")] - var apiConsumerSource = @" -[N1.C1(typeof(N1.C1))] -class C2 -{ - [N1.C1(typeof(N1.C1))] - private readonly int field; + namespace N1 + { + internal class C1 : System.Attribute + { + public C1(object o) { } + } + } + """, """ - [N1.C1(typeof(N1.C1))] - private int Property { [N1.C1(typeof(N1.C1))] get; } + [N1.C1(typeof(N1.C1))] + class C2 + { + [N1.C1(typeof(N1.C1))] + private readonly int field; - [N1.C1(typeof(N1.C1))] - private event System.EventHandler X; + [N1.C1(typeof(N1.C1))] + private int Property { [N1.C1(typeof(N1.C1))] get; } - [N1.C1(typeof(N1.C1))] - [return: N1.C1(typeof(N1.C1))] - int M([N1.C1(typeof(N1.C1))]object c) - { - return 0; - } -}"; + [N1.C1(typeof(N1.C1))] + private event System.EventHandler X; - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource); - } + [N1.C1(typeof(N1.C1))] + [return: N1.C1(typeof(N1.C1))] + int M([N1.C1(typeof(N1.C1))]object c) + { + return 0; + } + } + """); [Fact] - public async Task Basic_IVT_RestrictedIVT_UsageInAttributes_NoDiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Friend Class C1 - Inherits System.Attribute - Public Sub New(obj As Object) - End Sub - End Class -End Namespace"; - - var apiConsumerSource = @" - -Class C2 - - Private ReadOnly field As Integer - - - Private ReadOnly Property [Property] As Integer - - - Private Event X As System.EventHandler - - - Private Function M( ByVal c As Object) As Integer - Return 0 - End Function -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource); - } + public Task Basic_IVT_RestrictedIVT_UsageInAttributes_NoDiagnosticAsync() + => VerifyBasicAsync(""" + + + + + Namespace N1 + Friend Class C1 + Inherits System.Attribute + Public Sub New(obj As Object) + End Sub + End Class + End Namespace + """, """ + + + Class C2 + + Private ReadOnly field As Integer + + + Private ReadOnly Property [Property] As Integer + + + Private Event X As System.EventHandler + + + Private Function M( ByVal c As Object) As Integer + Return 0 + End Function + End Class + """); [Fact] - public async Task CSharp_IVT_RestrictedIVT_UsageInAttributes_DiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N2"")] + public Task CSharp_IVT_RestrictedIVT_UsageInAttributes_DiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - internal class C1 : System.Attribute - { - public C1(object o) { } - } -}"; + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N2")] - var apiConsumerSource = @" -[{|#16:{|#0:N1.C1|}(typeof({|#1:N1.C1|}))|}] -class C2 -{ - [{|#17:{|#2:N1.C1|}(typeof({|#3:N1.C1|}))|}] - private readonly int field; + namespace N1 + { + internal class C1 : System.Attribute + { + public C1(object o) { } + } + } + """, """ - [{|#18:{|#4:N1.C1|}(typeof({|#5:N1.C1|}))|}] - private int Property { [{|#19:{|#6:N1.C1|}(typeof({|#7:N1.C1|}))|}] get; } + [{|#16:{|#0:N1.C1|}(typeof({|#1:N1.C1|}))|}] + class C2 + { + [{|#17:{|#2:N1.C1|}(typeof({|#3:N1.C1|}))|}] + private readonly int field; - [{|#20:{|#8:N1.C1|}(typeof({|#9:N1.C1|}))|}] - private event System.EventHandler X; + [{|#18:{|#4:N1.C1|}(typeof({|#5:N1.C1|}))|}] + private int Property { [{|#19:{|#6:N1.C1|}(typeof({|#7:N1.C1|}))|}] get; } - [{|#21:{|#10:N1.C1|}(typeof({|#11:N1.C1|}))|}] - [return: {|#22:{|#12:N1.C1|}(typeof({|#13:N1.C1|}))|}] - int M([{|#23:{|#14:N1.C1|}(typeof({|#15:N1.C1|}))|}]object c) - { - return 0; - } -}"; + [{|#20:{|#8:N1.C1|}(typeof({|#9:N1.C1|}))|}] + private event System.EventHandler X; - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource, + [{|#21:{|#10:N1.C1|}(typeof({|#11:N1.C1|}))|}] + [return: {|#22:{|#12:N1.C1|}(typeof({|#13:N1.C1|}))|}] + int M([{|#23:{|#14:N1.C1|}(typeof({|#15:N1.C1|}))|}]object c) + { + return 0; + } + } + """, GetCSharpResultAt(0, "N1.C1", "N2"), GetCSharpResultAt(1, "N1.C1", "N2"), GetCSharpResultAt(2, "N1.C1", "N2"), @@ -1087,42 +1018,40 @@ await VerifyCSharpAsync(apiProviderSource, apiConsumerSource, GetCSharpResultAt(22, "N1.C1.C1", "N2"), GetCSharpResultAt(23, "N1.C1.C1", "N2") ); - } [Fact] - public async Task Basic_IVT_RestrictedIVT_UsageInAttributes_DiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Friend Class C1 - Inherits System.Attribute - Public Sub New(obj As Object) - End Sub - End Class -End Namespace"; - - var apiConsumerSource = @" -<{|#14:{|#0:N1.C1|}(GetType({|#1:N1.C1|}))|}> -Class C2 - <{|#15:{|#2:N1.C1|}(GetType({|#3:N1.C1|}))|}> - Private ReadOnly field As Integer - - <{|#16:{|#4:N1.C1|}(GetType({|#5:N1.C1|}))|}> - Private ReadOnly Property [Property] As Integer - - <{|#17:{|#6:N1.C1|}(GetType({|#7:N1.C1|}))|}> - Private Event X As System.EventHandler - - <{|#18:{|#8:N1.C1|}(GetType({|#9:N1.C1|}))|}> - Private Function M(<{|#19:{|#10:N1.C1|}(GetType({|#11:N1.C1|}))|}> ByVal c As Object) As <{|#20:{|#12:N1.C1|}(GetType({|#13:N1.C1|}))|}> Integer - Return 0 - End Function -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource, + public Task Basic_IVT_RestrictedIVT_UsageInAttributes_DiagnosticAsync() + => VerifyBasicAsync(""" + + + + + Namespace N1 + Friend Class C1 + Inherits System.Attribute + Public Sub New(obj As Object) + End Sub + End Class + End Namespace + """, """ + + <{|#14:{|#0:N1.C1|}(GetType({|#1:N1.C1|}))|}> + Class C2 + <{|#15:{|#2:N1.C1|}(GetType({|#3:N1.C1|}))|}> + Private ReadOnly field As Integer + + <{|#16:{|#4:N1.C1|}(GetType({|#5:N1.C1|}))|}> + Private ReadOnly Property [Property] As Integer + + <{|#17:{|#6:N1.C1|}(GetType({|#7:N1.C1|}))|}> + Private Event X As System.EventHandler + + <{|#18:{|#8:N1.C1|}(GetType({|#9:N1.C1|}))|}> + Private Function M(<{|#19:{|#10:N1.C1|}(GetType({|#11:N1.C1|}))|}> ByVal c As Object) As <{|#20:{|#12:N1.C1|}(GetType({|#13:N1.C1|}))|}> Integer + Return 0 + End Function + End Class + """, GetBasicResultAt(0, "N1.C1", "N2"), GetBasicResultAt(1, "N1.C1", "N2"), GetBasicResultAt(2, "N1.C1", "N2"), @@ -1145,99 +1074,93 @@ await VerifyBasicAsync(apiProviderSource, apiConsumerSource, GetBasicResultAt(19, "N1.C1.New", "N2"), GetBasicResultAt(20, "N1.C1.New", "N2") ); - } [Fact] - public async Task CSharp_IVT_RestrictedIVT_UsageInDeclaration_NoDiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N1"")] + public Task CSharp_IVT_RestrictedIVT_UsageInDeclaration_NoDiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - internal class C1 { } -}"; + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N1")] - var apiConsumerSource = @" -class C2 : N1.C1 -{ - private readonly N1.C1 field; - private N1.C1 Property { get; } - private N1.C1 this[N1.C1 index] { get => null; } - N1.C1 M(N1.C1 c) - { - return null; - } -}"; + namespace N1 + { + internal class C1 { } + } + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource); - } + class C2 : N1.C1 + { + private readonly N1.C1 field; + private N1.C1 Property { get; } + private N1.C1 this[N1.C1 index] { get => null; } + N1.C1 M(N1.C1 c) + { + return null; + } + } + """); [Fact] - public async Task Basic_IVT_RestrictedIVT_UsageInDeclaration_NoDiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Friend Class C1 - End Class -End Namespace"; - - var apiConsumerSource = @" -Class C2 - Inherits N1.C1 - - Private ReadOnly field As N1.C1 - Private ReadOnly Property [Property] As N1.C1 - - Private ReadOnly Property Item(index As N1.C1) As N1.C1 - Get - Return Nothing - End Get - End Property - - Private Function M(c As N1.C1) As N1.C1 - Return Nothing - End Function -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource); - } + public Task Basic_IVT_RestrictedIVT_UsageInDeclaration_NoDiagnosticAsync() + => VerifyBasicAsync(""" + + + + + Namespace N1 + Friend Class C1 + End Class + End Namespace + """, """ + + Class C2 + Inherits N1.C1 + + Private ReadOnly field As N1.C1 + Private ReadOnly Property [Property] As N1.C1 + + Private ReadOnly Property Item(index As N1.C1) As N1.C1 + Get + Return Nothing + End Get + End Property + + Private Function M(c As N1.C1) As N1.C1 + Return Nothing + End Function + End Class + """); [Fact] - public async Task CSharp_IVT_RestrictedIVT_UsageInDeclaration_DiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N2"")] + public Task CSharp_IVT_RestrictedIVT_UsageInDeclaration_DiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - internal class C1 { } - internal class C2 { } - internal class C3 { } - internal class C4 { } - internal class C5 { } - internal class C6 { } - internal class C7 { } -}"; - - var apiConsumerSource = @" -class B : {|#0:N1.C1|} -{ - private readonly {|#1:N1.C2|} field; - private {|#2:N1.C3|} Property { get; } - private {|#3:N1.C4|} this[{|#4:N1.C5|} index] { get => null; } - {|#5:N1.C6|} M({|#6:N1.C7|} c) - { - return null; - } -}"; + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N2")] - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource, + namespace N1 + { + internal class C1 { } + internal class C2 { } + internal class C3 { } + internal class C4 { } + internal class C5 { } + internal class C6 { } + internal class C7 { } + } + """, """ + + class B : {|#0:N1.C1|} + { + private readonly {|#1:N1.C2|} field; + private {|#2:N1.C3|} Property { get; } + private {|#3:N1.C4|} this[{|#4:N1.C5|} index] { get => null; } + {|#5:N1.C6|} M({|#6:N1.C7|} c) + { + return null; + } + } + """, GetCSharpResultAt(0, "N1.C1", "N2"), GetCSharpResultAt(1, "N1.C2", "N2"), GetCSharpResultAt(2, "N1.C3", "N2"), @@ -1245,51 +1168,49 @@ await VerifyCSharpAsync(apiProviderSource, apiConsumerSource, GetCSharpResultAt(4, "N1.C5", "N2"), GetCSharpResultAt(5, "N1.C6", "N2"), GetCSharpResultAt(6, "N1.C7", "N2")); - } [Fact] - public async Task Basic_IVT_RestrictedIVT_UsageInDeclaration_DiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Friend Class C1 - End Class - Friend Class C2 - End Class - Friend Class C3 - End Class - Friend Class C4 - End Class - Friend Class C5 - End Class - Friend Class C6 - End Class - Friend Class C7 - End Class -End Namespace"; - - var apiConsumerSource = @" -Class B - Inherits {|#0:N1.C1|} - - Private ReadOnly field As {|#1:N1.C2|} - Private ReadOnly Property [Property] As {|#2:N1.C3|} - - Private ReadOnly Property Item(index As {|#3:N1.C4|}) As {|#4:N1.C5|} - Get - Return Nothing - End Get - End Property - - Private Function M(c As {|#5:N1.C6|}) As {|#6:N1.C7|} - Return Nothing - End Function -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource, + public Task Basic_IVT_RestrictedIVT_UsageInDeclaration_DiagnosticAsync() + => VerifyBasicAsync(""" + + + + + Namespace N1 + Friend Class C1 + End Class + Friend Class C2 + End Class + Friend Class C3 + End Class + Friend Class C4 + End Class + Friend Class C5 + End Class + Friend Class C6 + End Class + Friend Class C7 + End Class + End Namespace + """, """ + + Class B + Inherits {|#0:N1.C1|} + + Private ReadOnly field As {|#1:N1.C2|} + Private ReadOnly Property [Property] As {|#2:N1.C3|} + + Private ReadOnly Property Item(index As {|#3:N1.C4|}) As {|#4:N1.C5|} + Get + Return Nothing + End Get + End Property + + Private Function M(c As {|#5:N1.C6|}) As {|#6:N1.C7|} + Return Nothing + End Function + End Class + """, GetBasicResultAt(0, "N1.C1", "N2"), GetBasicResultAt(1, "N1.C2", "N2"), GetBasicResultAt(2, "N1.C3", "N2"), @@ -1297,874 +1218,816 @@ await VerifyBasicAsync(apiProviderSource, apiConsumerSource, GetBasicResultAt(4, "N1.C5", "N2"), GetBasicResultAt(5, "N1.C6", "N2"), GetBasicResultAt(6, "N1.C7", "N2")); - } [Fact] - public async Task CSharp_IVT_RestrictedIVT_UsageInExecutableCode_NoDiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N1"")] - -namespace N1 -{ - internal class C1 : System.Attribute - { - public C1(object o) { } - public C1 GetC() => this; - public C1 GetC(C1 c) => c; - public object GetObject() => this; - public C1 Field; - public C1 Property { get; set; } - } -}"; + public Task CSharp_IVT_RestrictedIVT_UsageInExecutableCode_NoDiagnosticAsync() + => VerifyCSharpAsync(""" - var apiConsumerSource = @" -class C2 -{ - // Field initializer - private readonly N1.C1 field = new N1.C1(null); + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N1")] - // Property initializer - private N1.C1 Property { get; } = new N1.C1(null); + namespace N1 + { + internal class C1 : System.Attribute + { + public C1(object o) { } + public C1 GetC() => this; + public C1 GetC(C1 c) => c; + public object GetObject() => this; + public C1 Field; + public C1 Property { get; set; } + } + } + """, """ + + class C2 + { + // Field initializer + private readonly N1.C1 field = new N1.C1(null); - void M(object c) - { - var x = new N1.C1(null); // Object creation - N1.C1 y = x.GetC(); // Invocation - var z = y.GetC(x); // Parameter type - _ = (N1.C1)z.GetObject(); // Conversion - _ = z.Field; // Field reference - _ = z.Property; // Property reference - } -}"; + // Property initializer + private N1.C1 Property { get; } = new N1.C1(null); - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource); - } + void M(object c) + { + var x = new N1.C1(null); // Object creation + N1.C1 y = x.GetC(); // Invocation + var z = y.GetC(x); // Parameter type + _ = (N1.C1)z.GetObject(); // Conversion + _ = z.Field; // Field reference + _ = z.Property; // Property reference + } + } + """); + + [Fact] + public Task Basic_IVT_RestrictedIVT_UsageInExecutableCode_NoDiagnosticAsync() + => VerifyBasicAsync(""" + + + + + Namespace N1 + Friend Class C1 + Inherits System.Attribute + + Public Sub New(ByVal o As Object) + End Sub + + Public Function GetC() As C1 + Return Me + End Function + + Public Function GetC(ByVal c As C1) As C1 + Return c + End Function + + Public Function GetObject() As Object + Return Me + End Function + + Public Field As C1 + Public Property [Property] As C1 + End Class + End Namespace + """, """ + + Class C2 + Private ReadOnly field As N1.C1 = New N1.C1(Nothing) + Private ReadOnly Property [Property] As N1.C1 = New N1.C1(Nothing) + + Private Sub M(ByVal c As Object) + Dim x = New N1.C1(Nothing) + Dim y As N1.C1 = x.GetC() + Dim z = y.GetC(x) + Dim unused1 = CType(z.GetObject(), N1.C1) + Dim unused2 = z.Field + Dim unused3 = z.[Property] + End Sub + End Class + """); + + [Fact] + public Task CSharp_IVT_RestrictedIVT_PublicTypeInternalMember_NoDiagnosticAsync() + => VerifyCSharpAsync(""" + + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N1")] + + namespace N1 + { + public class C1 + { + internal int Field; + } + } + """, """ - [Fact] - public async Task Basic_IVT_RestrictedIVT_UsageInExecutableCode_NoDiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Friend Class C1 - Inherits System.Attribute - - Public Sub New(ByVal o As Object) - End Sub - - Public Function GetC() As C1 - Return Me - End Function - - Public Function GetC(ByVal c As C1) As C1 - Return c - End Function - - Public Function GetObject() As Object - Return Me - End Function - - Public Field As C1 - Public Property [Property] As C1 - End Class -End Namespace"; - - var apiConsumerSource = @" -Class C2 - Private ReadOnly field As N1.C1 = New N1.C1(Nothing) - Private ReadOnly Property [Property] As N1.C1 = New N1.C1(Nothing) - - Private Sub M(ByVal c As Object) - Dim x = New N1.C1(Nothing) - Dim y As N1.C1 = x.GetC() - Dim z = y.GetC(x) - Dim unused1 = CType(z.GetObject(), N1.C1) - Dim unused2 = z.Field - Dim unused3 = z.[Property] - End Sub -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource); - } + class C2 + { + int M(N1.C1 c) + { + return c.Field; + } + } + """); [Fact] - public async Task CSharp_IVT_RestrictedIVT_PublicTypeInternalMember_NoDiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N1"")] + public Task Basic_IVT_RestrictedIVT_PublicTypeInternalMember_NoDiagnosticAsync() + => VerifyBasicAsync(""" -namespace N1 -{ - public class C1 - { - internal int Field; - } -}"; + + - var apiConsumerSource = @" -class C2 -{ - int M(N1.C1 c) - { - return c.Field; - } -}"; + Namespace N1 + Public Class C1 + Friend Field As Integer + End Class + End Namespace + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource); - } + Class C2 + Private Function M(c As N1.C1) As Integer + Return c.Field + End Function + End Class + """); [Fact] - public async Task Basic_IVT_RestrictedIVT_PublicTypeInternalMember_NoDiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Public Class C1 - Friend Field As Integer - End Class -End Namespace"; - - var apiConsumerSource = @" -Class C2 - Private Function M(c As N1.C1) As Integer - Return c.Field - End Function -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource); - } + public Task CSharp_IVT_RestrictedIVT_PublicTypeInternalField_DiagnosticAsync() + => VerifyCSharpAsync(""" - [Fact] - public async Task CSharp_IVT_RestrictedIVT_PublicTypeInternalField_DiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N2"")] - -namespace N1 -{ - public class C1 - { - internal int Field; - } -}"; + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N2")] - var apiConsumerSource = @" -class C2 -{ - int M(N1.C1 c) - { - return {|#0:c.Field|}; - } -}"; + namespace N1 + { + public class C1 + { + internal int Field; + } + } + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource, + class C2 + { + int M(N1.C1 c) + { + return {|#0:c.Field|}; + } + } + """, GetCSharpResultAt(0, "N1.C1.Field", "N2")); - } [Fact] - public async Task Basic_IVT_RestrictedIVT_PublicTypeInternalField_DiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Public Class C1 - Friend Field As Integer - End Class -End Namespace"; - - var apiConsumerSource = @" -Class C2 - Private Function M(c As N1.C1) As Integer - Return {|#0:c.Field|} - End Function -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource, + public Task Basic_IVT_RestrictedIVT_PublicTypeInternalField_DiagnosticAsync() + => VerifyBasicAsync(""" + + + + + Namespace N1 + Public Class C1 + Friend Field As Integer + End Class + End Namespace + """, """ + + Class C2 + Private Function M(c As N1.C1) As Integer + Return {|#0:c.Field|} + End Function + End Class + """, GetBasicResultAt(0, "N1.C1.Field", "N2")); - } [Fact] - public async Task CSharp_IVT_RestrictedIVT_PublicTypeInternalMethod_DiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N2"")] + public Task CSharp_IVT_RestrictedIVT_PublicTypeInternalMethod_DiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - public class C1 - { - internal int Method() => 0; - } -}"; + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N2")] - var apiConsumerSource = @" -class C2 -{ - int M(N1.C1 c) - { - return {|#0:c.Method()|}; - } -}"; + namespace N1 + { + public class C1 + { + internal int Method() => 0; + } + } + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource, + class C2 + { + int M(N1.C1 c) + { + return {|#0:c.Method()|}; + } + } + """, GetCSharpResultAt(0, "N1.C1.Method", "N2")); - } [Fact] - public async Task Basic_IVT_RestrictedIVT_PublicTypeInternalMethod_DiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Public Class C1 - Friend Function Method() As Integer - Return 0 - End Function - End Class -End Namespace"; - - var apiConsumerSource = @" -Class C2 - Private Function M(c As N1.C1) As Integer - Return {|#0:c.Method()|} - End Function -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource, - GetBasicResultAt(0, "N1.C1.Method", "N2")); - } + public Task Basic_IVT_RestrictedIVT_PublicTypeInternalMethod_DiagnosticAsync() + => VerifyBasicAsync(""" - [Fact] - public async Task CSharp_IVT_RestrictedIVT_PublicTypeInternalExtensionMethod_NoDiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N1"")] + + -namespace N1 -{ - public class C1 - { - } - - public static class C1Extensions - { - internal static int Method(this C1 c1) => 0; - } -}"; + Namespace N1 + Public Class C1 + Friend Function Method() As Integer + Return 0 + End Function + End Class + End Namespace + """, """ - var apiConsumerSource = @"using static N1.C1Extensions; -class C2 -{ - int M(N1.C1 c) - { - return c.Method(); - } -}"; - - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource); - } - - [Fact] - public async Task Basic_IVT_RestrictedIVT_PublicTypeInternalExtensionMethod_NoDiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Public Class C1 - End Class - - Public Module C1Extensions - - Friend Function Method(c As C1) As Integer - Return 0 - End Function - End Module -End Namespace"; - - var apiConsumerSource = @"Imports N1.C1Extensions -Class C2 - Private Function M(c As N1.C1) As Integer - Return c.Method() - End Function -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource); - } + Class C2 + Private Function M(c As N1.C1) As Integer + Return {|#0:c.Method()|} + End Function + End Class + """, + GetBasicResultAt(0, "N1.C1.Method", "N2")); [Fact] - public async Task CSharp_IVT_RestrictedIVT_PublicTypeInternalExtensionMethod_DiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N2"")] + public Task CSharp_IVT_RestrictedIVT_PublicTypeInternalExtensionMethod_NoDiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - public class C1 - { - } + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N1")] - public static class C1Extensions - { - internal static int Method(this C1 c1) => 0; - } -}"; + namespace N1 + { + public class C1 + { + } - var apiConsumerSource = @"using static N1.C1Extensions; -class C2 -{ - int M(N1.C1 c) - { - return {|#0:c.Method()|}; - } -}"; + public static class C1Extensions + { + internal static int Method(this C1 c1) => 0; + } + } + """, """ + using static N1.C1Extensions; + class C2 + { + int M(N1.C1 c) + { + return c.Method(); + } + } + """); + + [Fact] + public Task Basic_IVT_RestrictedIVT_PublicTypeInternalExtensionMethod_NoDiagnosticAsync() + => VerifyBasicAsync(""" + + + + + Namespace N1 + Public Class C1 + End Class + + Public Module C1Extensions + + Friend Function Method(c As C1) As Integer + Return 0 + End Function + End Module + End Namespace + """, """ + Imports N1.C1Extensions + Class C2 + Private Function M(c As N1.C1) As Integer + Return c.Method() + End Function + End Class + """); + + [Fact] + public Task CSharp_IVT_RestrictedIVT_PublicTypeInternalExtensionMethod_DiagnosticAsync() + => VerifyCSharpAsync(""" + + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N2")] + + namespace N1 + { + public class C1 + { + } - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource, + public static class C1Extensions + { + internal static int Method(this C1 c1) => 0; + } + } + """, """ + using static N1.C1Extensions; + class C2 + { + int M(N1.C1 c) + { + return {|#0:c.Method()|}; + } + } + """, GetCSharpResultAt(0, "N1.C1.Method", "N2")); - } [Fact] - public async Task Basic_IVT_RestrictedIVT_PublicTypeInternalExtensionMethod_DiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Public Class C1 - End Class - - Public Module C1Extensions - - Friend Function Method(c As C1) As Integer - Return 0 - End Function - End Module -End Namespace"; - - var apiConsumerSource = @"Imports N1.C1Extensions -Class C2 - Private Function M(c As N1.C1) As Integer - Return {|#0:c.Method()|} - End Function -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource, + public Task Basic_IVT_RestrictedIVT_PublicTypeInternalExtensionMethod_DiagnosticAsync() + => VerifyBasicAsync(""" + + + + + Namespace N1 + Public Class C1 + End Class + + Public Module C1Extensions + + Friend Function Method(c As C1) As Integer + Return 0 + End Function + End Module + End Namespace + """, """ + Imports N1.C1Extensions + Class C2 + Private Function M(c As N1.C1) As Integer + Return {|#0:c.Method()|} + End Function + End Class + """, GetBasicResultAt(0, "N1.C1.Method", "N2")); - } [Fact] - public async Task CSharp_IVT_RestrictedIVT_PublicTypeInternalProperty_DiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N2"")] + public Task CSharp_IVT_RestrictedIVT_PublicTypeInternalProperty_DiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - public class C1 - { - internal int Property { get => 0; } - } -}"; + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N2")] - var apiConsumerSource = @" -class C2 -{ - int M(N1.C1 c) - { - return {|#0:c.Property|}; - } -}"; + namespace N1 + { + public class C1 + { + internal int Property { get => 0; } + } + } + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource, + class C2 + { + int M(N1.C1 c) + { + return {|#0:c.Property|}; + } + } + """, GetCSharpResultAt(0, "N1.C1.Property", "N2")); - } [Fact] - public async Task Basic_IVT_RestrictedIVT_PublicTypeInternalProperty_DiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Public Class C1 - Friend ReadOnly Property [Property] As Integer - End Class -End Namespace"; - - var apiConsumerSource = @" -Class C2 - Private Function M(c As N1.C1) As Integer - Return {|#0:c.[Property]|} - End Function -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource, + public Task Basic_IVT_RestrictedIVT_PublicTypeInternalProperty_DiagnosticAsync() + => VerifyBasicAsync(""" + + + + + Namespace N1 + Public Class C1 + Friend ReadOnly Property [Property] As Integer + End Class + End Namespace + """, """ + + Class C2 + Private Function M(c As N1.C1) As Integer + Return {|#0:c.[Property]|} + End Function + End Class + """, GetBasicResultAt(0, "N1.C1.Property", "N2")); - } [Fact] - public async Task CSharp_IVT_RestrictedIVT_PublicTypeInternalEvent_DiagnosticAsync() - { - var apiProviderSource = @"using System; + public Task CSharp_IVT_RestrictedIVT_PublicTypeInternalEvent_DiagnosticAsync() + => VerifyCSharpAsync(""" + using System; -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N2"")] + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N2")] -namespace N1 -{ - public class C1 - { - internal event EventHandler Event; - } -}"; - - var apiConsumerSource = @" -class C2 -{ - void M(N1.C1 c) - { - _ = {|#0:c.{|CS0070:Event|}|}; - } -}"; + namespace N1 + { + public class C1 + { + internal event EventHandler Event; + } + } + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource, + class C2 + { + void M(N1.C1 c) + { + _ = {|#0:c.{|CS0070:Event|}|}; + } + } + """, GetCSharpResultAt(0, "N1.C1.Event", "N2")); - } [Fact] - public async Task Basic_IVT_RestrictedIVT_PublicTypeInternalEvent_DiagnosticAsync() - { - var apiProviderSource = @"Imports System + public Task Basic_IVT_RestrictedIVT_PublicTypeInternalEvent_DiagnosticAsync() + => VerifyBasicAsync(""" + Imports System - - + + -Namespace N1 - Public Class C1 - Friend Event [Event] As EventHandler - End Class -End Namespace"; + Namespace N1 + Public Class C1 + Friend Event [Event] As EventHandler + End Class + End Namespace + """, """ - var apiConsumerSource = @" -Class C2 - Private Sub M(c As N1.C1) - Dim unused = {|BC32022:c.[Event]|} - End Sub -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource, + Class C2 + Private Sub M(c As N1.C1) + Dim unused = {|BC32022:c.[Event]|} + End Sub + End Class + """, GetBasicResultAt(4, 22, 4, 31, "N1.C1.Event", "N2")); - } [Fact] - public async Task CSharp_IVT_RestrictedIVT_PublicTypeInternalConstructor_DiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N2"")] + public Task CSharp_IVT_RestrictedIVT_PublicTypeInternalConstructor_DiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - public class C1 - { - internal C1() { } - } -}"; + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N2")] - var apiConsumerSource = @" -class C2 -{ - void M() - { - var c = {|#0:new N1.C1()|}; - } -}"; + namespace N1 + { + public class C1 + { + internal C1() { } + } + } + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource, + class C2 + { + void M() + { + var c = {|#0:new N1.C1()|}; + } + } + """, GetCSharpResultAt(0, "N1.C1.C1", "N2")); - } [Fact] - public async Task Basic_IVT_RestrictedIVT_PublicTypeInternalConstructor_DiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Public Class C1 - Friend Sub New() - End Sub - End Class -End Namespace"; - - var apiConsumerSource = @" -Class C2 - Private Sub M() - Dim c = {|#0:New N1.C1()|} - End Sub -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource, + public Task Basic_IVT_RestrictedIVT_PublicTypeInternalConstructor_DiagnosticAsync() + => VerifyBasicAsync(""" + + + + + Namespace N1 + Public Class C1 + Friend Sub New() + End Sub + End Class + End Namespace + """, """ + + Class C2 + Private Sub M() + Dim c = {|#0:New N1.C1()|} + End Sub + End Class + """, GetBasicResultAt(0, "N1.C1.New", "N2")); - } [Fact] - public async Task CSharp_IVT_RestrictedIVT_Conversions_DiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N2"")] + public Task CSharp_IVT_RestrictedIVT_Conversions_DiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - internal interface I1 { } - public class C1 : I1 { } -}"; + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N2")] - var apiConsumerSource = @" -class C2 -{ - void M(N1.C1 c) - { - _ = ({|#0:N1.I1|})c; // Explicit - {|#1:N1.I1|} y = c; // Implicit - } -}"; + namespace N1 + { + internal interface I1 { } + public class C1 : I1 { } + } + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource, + class C2 + { + void M(N1.C1 c) + { + _ = ({|#0:N1.I1|})c; // Explicit + {|#1:N1.I1|} y = c; // Implicit + } + } + """, GetCSharpResultAt(0, "N1.I1", "N2"), GetCSharpResultAt(1, "N1.I1", "N2")); - } [Fact] - public async Task Basic_IVT_RestrictedIVT_Conversions_DiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Friend Interface I1 - End Interface - - Public Class C1 - Implements I1 - End Class -End Namespace"; - - var apiConsumerSource = @" -Class C2 - Private Function M(c As N1.C1) As Integer - Dim x = CType(c, {|#0:N1.I1|}) - Dim y As {|#1:N1.I1|} = c - End Function -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource, + public Task Basic_IVT_RestrictedIVT_Conversions_DiagnosticAsync() + => VerifyBasicAsync(""" + + + + + Namespace N1 + Friend Interface I1 + End Interface + + Public Class C1 + Implements I1 + End Class + End Namespace + """, """ + + Class C2 + Private Function M(c As N1.C1) As Integer + Dim x = CType(c, {|#0:N1.I1|}) + Dim y As {|#1:N1.I1|} = c + End Function + End Class + """, GetCSharpResultAt(0, "N1.I1", "N2"), GetCSharpResultAt(1, "N1.I1", "N2")); - } [Fact] - public async Task CSharp_IVT_RestrictedIVT_UsageInTypeArgument_NoDiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N1"")] + public Task CSharp_IVT_RestrictedIVT_UsageInTypeArgument_NoDiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - internal class C1 - { - public C1 GetC1() => null; - } + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N1")] - internal class C3 { } -}"; + namespace N1 + { + internal class C1 + { + public C1 GetC1() => null; + } - var apiConsumerSource = @" -using N1; -class C2 : C1 -{ - void M(C1 c1, C1 c2) - { - _ = c2.GetC1(); - _ = c2.GetC1>(); - } -}"; + internal class C3 { } + } + """, """ - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource); - } + using N1; + class C2 : C1 + { + void M(C1 c1, C1 c2) + { + _ = c2.GetC1(); + _ = c2.GetC1>(); + } + } + """); [Fact] - public async Task Basic_IVT_RestrictedIVT_UsageInTypeArgument_NoDiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Friend Class C1(Of T) - Public Function GetC1(Of U)() As C1(Of Object) - Return Nothing - End Function - End Class - - Friend Class C3 - End Class -End Namespace"; - - var apiConsumerSource = @" -Imports N1 - -Class C2 - Inherits C1(Of C3) - - Private Sub M(ByVal c1 As C1(Of C3), ByVal c2 As C1(Of Object)) - Dim unused1 = c2.GetC1(Of C3)() - Dim unused2 = c2.GetC1(Of C1(Of C3))() - End Sub -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource); - } + public Task Basic_IVT_RestrictedIVT_UsageInTypeArgument_NoDiagnosticAsync() + => VerifyBasicAsync(""" + + + + + Namespace N1 + Friend Class C1(Of T) + Public Function GetC1(Of U)() As C1(Of Object) + Return Nothing + End Function + End Class + + Friend Class C3 + End Class + End Namespace + """, """ + + Imports N1 + + Class C2 + Inherits C1(Of C3) + + Private Sub M(ByVal c1 As C1(Of C3), ByVal c2 As C1(Of Object)) + Dim unused1 = c2.GetC1(Of C3)() + Dim unused2 = c2.GetC1(Of C1(Of C3))() + End Sub + End Class + """); [Fact] - public async Task CSharp_IVT_RestrictedIVT_UsageInTypeArgument_DiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N2"")] + public Task CSharp_IVT_RestrictedIVT_UsageInTypeArgument_DiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - internal class C3 { } - internal class C4 { } - internal class C5 { } - internal class C6 { } + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N2")] -} + namespace N1 + { + internal class C3 { } + internal class C4 { } + internal class C5 { } + internal class C6 { } -namespace N2 -{ - internal class C1 - { - public C1 GetC1() => null; - } -} -"; + } - var apiConsumerSource = @" -using N1; -using N2; + namespace N2 + { + internal class C1 + { + public C1 GetC1() => null; + } + } -class C2 : C1<{|#0:C3|}> -{ - void M(C1<{|#1:C4|}> c1, C1 c2) - { - _ = c2.GetC1<{|#2:C5|}>(); - _ = c2.GetC1>(); - } -}"; + """, """ + + using N1; + using N2; - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource, + class C2 : C1<{|#0:C3|}> + { + void M(C1<{|#1:C4|}> c1, C1 c2) + { + _ = c2.GetC1<{|#2:C5|}>(); + _ = c2.GetC1>(); + } + } + """, GetCSharpResultAt(0, "N1.C3", "N2"), GetCSharpResultAt(1, "N1.C4", "N2"), GetCSharpResultAt(2, "N1.C5", "N2"), GetCSharpResultAt(3, "N1.C6", "N2")); - } [Fact] - public async Task Basic_IVT_RestrictedIVT_UsageInTypeArgument_DiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Friend Class C3 - End Class - Friend Class C4 - End Class - Friend Class C5 - End Class - Friend Class C6 - End Class -End Namespace - -Namespace N2 - Friend Class C1(Of T) - Public Function GetC1(Of U)() As C1(Of Object) - Return Nothing - End Function - End Class -End Namespace"; - - var apiConsumerSource = @" -Imports N1 -Imports N2 - -Class C2 - Inherits C1(Of {|#0:C3|}) - - Private Sub M(ByVal c1 As C1(Of {|#1:C4|}), ByVal c2 As C1(Of Object)) - Dim unused1 = c2.GetC1(Of {|#2:C5|})() - Dim unused2 = c2.GetC1(Of C1(Of {|#3:C6|}))() - End Sub -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource, + public Task Basic_IVT_RestrictedIVT_UsageInTypeArgument_DiagnosticAsync() + => VerifyBasicAsync(""" + + + + + Namespace N1 + Friend Class C3 + End Class + Friend Class C4 + End Class + Friend Class C5 + End Class + Friend Class C6 + End Class + End Namespace + + Namespace N2 + Friend Class C1(Of T) + Public Function GetC1(Of U)() As C1(Of Object) + Return Nothing + End Function + End Class + End Namespace + """, """ + + Imports N1 + Imports N2 + + Class C2 + Inherits C1(Of {|#0:C3|}) + + Private Sub M(ByVal c1 As C1(Of {|#1:C4|}), ByVal c2 As C1(Of Object)) + Dim unused1 = c2.GetC1(Of {|#2:C5|})() + Dim unused2 = c2.GetC1(Of C1(Of {|#3:C6|}))() + End Sub + End Class + """, GetCSharpResultAt(0, "N1.C3", "N2"), GetCSharpResultAt(1, "N1.C4", "N2"), GetCSharpResultAt(2, "N1.C5", "N2"), GetCSharpResultAt(3, "N1.C6", "N2")); - } [Fact] - public async Task CSharp_IVT_RestrictedIVT_UsingAlias_NoDiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N1"")] - -namespace N1 -{ - internal class C1 { } -}"; + public Task CSharp_IVT_RestrictedIVT_UsingAlias_NoDiagnosticAsync() + => VerifyCSharpAsync(""" - var apiConsumerSource = @"using ImportedC1 = N1.C1; -class C2 -{ - void M(ImportedC1 c) - { - } -}"; + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N1")] - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource); - } + namespace N1 + { + internal class C1 { } + } + """, """ + using ImportedC1 = N1.C1; + class C2 + { + void M(ImportedC1 c) + { + } + } + """); [Fact] - public async Task Basic_IVT_RestrictedIVT_UsingAlias_NoDiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Friend Class C1 - End Class -End Namespace"; - - var apiConsumerSource = @"Imports ImportedC1 = N1.C1 -Class C2 - Private Sub M(c As ImportedC1) - End Sub -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource); - } + public Task Basic_IVT_RestrictedIVT_UsingAlias_NoDiagnosticAsync() + => VerifyBasicAsync(""" - [Fact] - public async Task CSharp_IVT_RestrictedIVT_UsingAlias_DiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N2"")] + + -namespace N1 -{ - internal class C1 { } -}"; + Namespace N1 + Friend Class C1 + End Class + End Namespace + """, """ + Imports ImportedC1 = N1.C1 + Class C2 + Private Sub M(c As ImportedC1) + End Sub + End Class + """); - var apiConsumerSource = @"using ImportedC1 = N1.C1; -class C2 -{ - void M({|#0:ImportedC1|} c) - { - } -}"; + [Fact] + public Task CSharp_IVT_RestrictedIVT_UsingAlias_DiagnosticAsync() + => VerifyCSharpAsync(""" - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource, + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N2")] + + namespace N1 + { + internal class C1 { } + } + """, """ + using ImportedC1 = N1.C1; + class C2 + { + void M({|#0:ImportedC1|} c) + { + } + } + """, GetCSharpResultAt(0, "N1.C1", "N2")); - } [Fact] - public async Task Basic_IVT_RestrictedIVT_UsingAlias_DiagnosticAsync() - { - var apiProviderSource = @" - - - -Namespace N1 - Friend Class C1 - End Class -End Namespace"; - - var apiConsumerSource = @"Imports ImportedC1 = N1.C1 -Class C2 - Private Sub M(c As {|#0:ImportedC1|}) - End Sub -End Class"; - - await VerifyBasicAsync(apiProviderSource, apiConsumerSource, + public Task Basic_IVT_RestrictedIVT_UsingAlias_DiagnosticAsync() + => VerifyBasicAsync(""" + + + + + Namespace N1 + Friend Class C1 + End Class + End Namespace + """, """ + Imports ImportedC1 = N1.C1 + Class C2 + Private Sub M(c As {|#0:ImportedC1|}) + End Sub + End Class + """, GetBasicResultAt(0, "N1.C1", "N2")); - } [Fact] [WorkItem(2655, "https://github.com/dotnet/roslyn-analyzers/issues/2655")] - public async Task CSharp_IVT_RestrictedIVT_InternalOperators_DiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N2"")] + public Task CSharp_IVT_RestrictedIVT_InternalOperators_DiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - internal class C - { - public static implicit operator C(int i) => new C(); - public static explicit operator C(float f) => new C(); - public static C operator +(C c, int i) => c; - public static C operator ++(C c) => c; - public static C operator -(C c) => c; - } -}"; + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N2")] - var apiConsumerSource = @" -using N1; -class C2 -{ - void M() - { - {|#0:C|} c = {|#1:0|}; // implicit conversion. - c = {|#2:({|#3:C|})1.0f|}; // Explicit conversion. - c = {|#4:c + 1|}; // Binary operator. - {|#5:c++|}; // Increment or decrement. - c = {|#6:-c|}; // Unary operator. - } -}"; - - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource, + namespace N1 + { + internal class C + { + public static implicit operator C(int i) => new C(); + public static explicit operator C(float f) => new C(); + public static C operator +(C c, int i) => c; + public static C operator ++(C c) => c; + public static C operator -(C c) => c; + } + } + """, """ + + using N1; + class C2 + { + void M() + { + {|#0:C|} c = {|#1:0|}; // implicit conversion. + c = {|#2:({|#3:C|})1.0f|}; // Explicit conversion. + c = {|#4:c + 1|}; // Binary operator. + {|#5:c++|}; // Increment or decrement. + c = {|#6:-c|}; // Unary operator. + } + } + """, GetCSharpResultAt(0, "N1.C", "N2"), GetCSharpResultAt(1, "N1.C.implicit operator N1.C", "N2"), GetCSharpResultAt(2, "N1.C.explicit operator N1.C", "N2"), @@ -2172,45 +2035,43 @@ await VerifyCSharpAsync(apiProviderSource, apiConsumerSource, GetCSharpResultAt(4, "N1.C.operator +", "N2"), GetCSharpResultAt(5, "N1.C.operator ++", "N2"), GetCSharpResultAt(6, "N1.C.operator -", "N2")); - } [Fact] [WorkItem(2655, "https://github.com/dotnet/roslyn-analyzers/issues/2655")] - public async Task CSharp_IVT_RestrictedIVT_TypeArgumentUsage_DiagnosticAsync() - { - var apiProviderSource = @" -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ApiConsumerProjectName"")] -[assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo(""ApiConsumerProjectName"", ""N2"")] + public Task CSharp_IVT_RestrictedIVT_TypeArgumentUsage_DiagnosticAsync() + => VerifyCSharpAsync(""" -namespace N1 -{ - internal struct C {} -}"; + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ApiConsumerProjectName")] + [assembly: System.Runtime.CompilerServices.RestrictedInternalsVisibleTo("ApiConsumerProjectName", "N2")] - var apiConsumerSource = @" -using N1; -namespace N2 -{ - class G - { - class N - { } + namespace N1 + { + internal struct C {} + } + """, """ - unsafe void M() - { - var b = new G<{|#0:C|}>(); - var c = new G<{|#1:C|}>.N(); - var d = new G.N<{|#2:C|}>(); - var e = new G.N<{|#3:C|}>>.N(); - var f = new G.N>.N(); - var g = new {|#5:C|}[42]; - var h = new G<{|#6:C|}[]>(); - fixed ({|#7:C|}* i = &g[0]) { } - } - } -}"; + using N1; + namespace N2 + { + class G + { + class N + { } - await VerifyCSharpAsync(apiProviderSource, apiConsumerSource, + unsafe void M() + { + var b = new G<{|#0:C|}>(); + var c = new G<{|#1:C|}>.N(); + var d = new G.N<{|#2:C|}>(); + var e = new G.N<{|#3:C|}>>.N(); + var f = new G.N>.N(); + var g = new {|#5:C|}[42]; + var h = new G<{|#6:C|}[]>(); + fixed ({|#7:C|}* i = &g[0]) { } + } + } + } + """, // Test0.cs(12,27): error RS0035: External access to internal symbol 'N1.C' is prohibited. Assembly 'ApiProviderProjectName' only allows access to internal symbols defined in the following namespace(s): 'N2' GetCSharpResultAt(0, "N1.C", "N2"), // Test0.cs(13,27): error RS0035: External access to internal symbol 'N1.C' is prohibited. Assembly 'ApiProviderProjectName' only allows access to internal symbols defined in the following namespace(s): 'N2' @@ -2227,6 +2088,5 @@ await VerifyCSharpAsync(apiProviderSource, apiConsumerSource, GetCSharpResultAt(6, "N1.C", "N2"), // Test0.cs(19,20): error RS0035: External access to internal symbol 'N1.C' is prohibited. Assembly 'ApiProviderProjectName' only allows access to internal symbols defined in the following namespace(s): 'N2' GetCSharpResultAt(7, "N1.C", "N2")); - } } } diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/UnitTests/SymbolIsBannedAnalyzerTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/UnitTests/SymbolIsBannedAnalyzerTests.cs index 7aa267b0d2238..876acc5ed77c9 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/UnitTests/SymbolIsBannedAnalyzerTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/UnitTests/SymbolIsBannedAnalyzerTests.cs @@ -69,76 +69,54 @@ private static async Task VerifyCSharpAnalyzerAsync(string source, string banned public async Task NoDiagnosticForNoBannedTextAsync() { await VerifyCS.VerifyAnalyzerAsync("class C { }"); - await VerifyVB.VerifyAnalyzerAsync(@"Class C -End Class"); + await VerifyVB.VerifyAnalyzerAsync(""" + Class C + End Class + """); } [Fact] - public async Task NoDiagnosticReportedForEmptyBannedTextAsync() - { - var source = @""; - - var bannedText = @""; - - await VerifyCSharpAnalyzerAsync(source, bannedText); - } + public Task NoDiagnosticReportedForEmptyBannedTextAsync() + => VerifyCSharpAnalyzerAsync(@"", @""); [Fact] - public async Task NoDiagnosticReportedForMultilineBlankBannedTextAsync() - { - var source = @" - + public Task NoDiagnosticReportedForMultilineBlankBannedTextAsync() + => VerifyCSharpAnalyzerAsync(""" -"; - - var bannedText = @""; - - await VerifyCSharpAnalyzerAsync(source, bannedText); - } + """, @""); [Fact] - public async Task NoDiagnosticReportedForMultilineMessageOnlyBannedTextAsync() - { - var source = @""; - var bannedText = @" -;first - ;second -;third // comment"; - - await VerifyCSharpAnalyzerAsync(source, bannedText); - } + public Task NoDiagnosticReportedForMultilineMessageOnlyBannedTextAsync() + => VerifyCSharpAnalyzerAsync(@"", """ + ;first + ;second + ;third // comment + """); [Fact] public async Task DiagnosticReportedForDuplicateBannedApiLinesAsync() { - var source = @""; - var bannedText = @" -{|#0:T:System.Console|} -{|#1:T:System.Console|}"; - var expected = new DiagnosticResult(SymbolIsBannedAnalyzer.DuplicateBannedSymbolRule) .WithLocation(1) .WithLocation(0) .WithArguments("System.Console"); - await VerifyCSharpAnalyzerAsync(source, bannedText, expected); + await VerifyCSharpAnalyzerAsync(@"", """ + {|#0:T:System.Console|} + {|#1:T:System.Console|} + """, expected); } [Fact] public async Task DiagnosticReportedForDuplicateBannedApiLinesWithDifferentIdsAsync() { - // The colon in the documentation ID is optional. - // Verify that it doesn't cause exceptions when building look ups. - - var source = @""; - var bannedText = @" -{|#0:T:System.Console;Message 1|} -{|#1:TSystem.Console;Message 2|}"; - var expected = new DiagnosticResult(SymbolIsBannedAnalyzer.DuplicateBannedSymbolRule) .WithLocation(1) .WithLocation(0) .WithArguments("System.Console"); - await VerifyCSharpAnalyzerAsync(source, bannedText, expected); + await VerifyCSharpAnalyzerAsync(@"", """ + {|#0:T:System.Console;Message 1|} + {|#1:TSystem.Console;Message 2|} + """, expected); } [Fact] @@ -172,16 +150,18 @@ public async Task DiagnosticReportedForDuplicateBannedApiLinesInDifferentFiles() [Fact] public async Task DiagnosticReportedForDuplicateBannedApiLinesWithCommentsAsync() { - var source = @""; - var bannedText = @" -{|#0:T:System.Console|} " + '\t' + @" //comment here with whitespace before it -{|#1:T:System.Console|}//should not affect the reported duplicate"; + var bannedText = """ + {|#0:T:System.Console|} + """ + '\t' + """ + //comment here with whitespace before it + {|#1:T:System.Console|}//should not affect the reported duplicate + """; var expected = new DiagnosticResult(SymbolIsBannedAnalyzer.DuplicateBannedSymbolRule) .WithLocation(1) .WithLocation(0) .WithArguments("System.Console"); - await VerifyCSharpAnalyzerAsync(source, bannedText, expected); + await VerifyCSharpAnalyzerAsync(@"", bannedText, expected); } [Fact] @@ -224,75 +204,68 @@ public async Task NoDiagnosticReportedForCommentLine() public async Task NoDiagnosticReportedForCommentedOutBannedApiLineAsync() { var bannedText = @"//T:N.Banned"; - - var csharpSource = @" -namespace N -{ - class Banned { } - class C - { - void M() - { - var c = new Banned(); - } - } -}"; - - await VerifyCSharpAnalyzerAsync(csharpSource, bannedText); - - var visualBasicSource = @" -Namespace N - Class Banned : End Class - Class C - Sub M() - Dim c As New Banned() - End Sub - End Class -End Namespace"; - - await VerifyBasicAnalyzerAsync(visualBasicSource, bannedText); + await VerifyCSharpAnalyzerAsync(""" + namespace N + { + class Banned { } + class C + { + void M() + { + var c = new Banned(); + } + } + } + """, bannedText); + await VerifyBasicAnalyzerAsync(""" + Namespace N + Class Banned : End Class + Class C + Sub M() + Dim c As New Banned() + End Sub + End Class + End Namespace + """, bannedText); } [Fact] public async Task NoDiagnosticReportedForCommentLineThatBeginsWithWhitespaceAsync() { var bannedText = @" // comment here"; - - var csharpSource = @" -namespace N -{ - class Banned { } - class C - { - void M() - { - var c = new Banned(); - } - } -}"; - - await VerifyCSharpAnalyzerAsync(csharpSource, bannedText); - - var visualBasicSource = @" -Namespace N - Class Banned : End Class - Class C - Sub M() - Dim c As New Banned() - End Sub - End Class -End Namespace"; - - await VerifyBasicAnalyzerAsync(visualBasicSource, bannedText); + await VerifyCSharpAnalyzerAsync(""" + namespace N + { + class Banned { } + class C + { + void M() + { + var c = new Banned(); + } + } + } + """, bannedText); + await VerifyBasicAnalyzerAsync(""" + Namespace N + Class Banned : End Class + Class C + Sub M() + Dim c As New Banned() + End Sub + End Class + End Namespace + """, bannedText); } [Fact] public async Task NoDiagnosticReportedForCommentedOutDuplicateBannedApiLinesAsync() { var source = @""; - var bannedText = @" -//T:System.Console -//T:System.Console"; + var bannedText = """ + //T:System.Console + //T:System.Console + """; await VerifyCSharpAnalyzerAsync(source, bannedText); await VerifyBasicAnalyzerAsync(source, bannedText); @@ -302,60 +275,52 @@ public async Task NoDiagnosticReportedForCommentedOutDuplicateBannedApiLinesAsyn public async Task DiagnosticReportedForBannedApiLineWithCommentAtTheEndAsync() { var bannedText = @"T:N.Banned//comment here"; - - var csharpSource = @" -namespace N -{ - class Banned { } - class C - { - void M() - { - var c = {|#0:new Banned()|}; - } - } -}"; - - await VerifyCSharpAnalyzerAsync(csharpSource, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", "")); - - var visualBasicSource = @" -Namespace N - Class Banned : End Class - Class C - Sub M() - Dim c As {|#0:New Banned()|} - End Sub - End Class -End Namespace"; - - await VerifyBasicAnalyzerAsync(visualBasicSource, bannedText, GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", "")); + await VerifyCSharpAnalyzerAsync(""" + namespace N + { + class Banned { } + class C + { + void M() + { + var c = {|#0:new Banned()|}; + } + } + } + """, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", "")); + await VerifyBasicAnalyzerAsync(""" + Namespace N + Class Banned : End Class + Class C + Sub M() + Dim c As {|#0:New Banned()|} + End Sub + End Class + End Namespace + """, bannedText, GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", "")); } [Fact] public async Task DiagnosticReportedForInterfaceImplementationAsync() { var bannedText = "T:N.IBanned//comment here"; - - var csharpSource = @" -namespace N -{ - interface IBanned { } - class C : {|#0:IBanned|} - { - } -}"; - - await VerifyCSharpAnalyzerAsync(csharpSource, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "IBanned", "")); - - var visualBasicSource = @" -Namespace N - Interface IBanned : End Interface - Class C - Implements {|#0:IBanned|} - End Class -End Namespace"; - - await VerifyBasicAnalyzerAsync(visualBasicSource, bannedText, GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "IBanned", "")); + await VerifyCSharpAnalyzerAsync(""" + namespace N + { + interface IBanned { } + class C : {|#0:IBanned|} + { + } + } + """, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "IBanned", "")); + await VerifyBasicAnalyzerAsync(""" + Namespace N + Interface IBanned : End Interface + Class C + Implements {|#0:IBanned|} + End Class + End Namespace + """, bannedText, GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "IBanned", "")); } @@ -363,27 +328,23 @@ End Class public async Task DiagnosticReportedForClassInheritanceAsync() { var bannedText = "T:N.Banned//comment here"; - - var csharpSource = @" -namespace N -{ - class Banned { } - class C : {|#0:Banned|} - { - } -}"; - - await VerifyCSharpAnalyzerAsync(csharpSource, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", "")); - - var visualBasicSource = @" -Namespace N - Class Banned : End Class - Class C - Inherits {|#0:Banned|} - End Class -End Namespace"; - - await VerifyBasicAnalyzerAsync(visualBasicSource, bannedText, GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", "")); + await VerifyCSharpAnalyzerAsync(""" + namespace N + { + class Banned { } + class C : {|#0:Banned|} + { + } + } + """, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", "")); + await VerifyBasicAnalyzerAsync(""" + Namespace N + Class Banned : End Class + Class C + Inherits {|#0:Banned|} + End Class + End Namespace + """, bannedText, GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", "")); } @@ -391,174 +352,148 @@ End Class public async Task DiagnosticReportedForBannedApiLineWithWhitespaceThenCommentAtTheEndAsync() { var bannedText = "T:N.Banned \t //comment here"; - - var csharpSource = @" -namespace N -{ - class Banned { } - class C - { - void M() - { - var c = {|#0:new Banned()|}; - } - } -}"; - - await VerifyCSharpAnalyzerAsync(csharpSource, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", "")); - - var visualBasicSource = @" -Namespace N - Class Banned : End Class - Class C - Sub M() - Dim c As {|#0:New Banned()|} - End Sub - End Class -End Namespace"; - - await VerifyBasicAnalyzerAsync(visualBasicSource, bannedText, GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", "")); + await VerifyCSharpAnalyzerAsync(""" + namespace N + { + class Banned { } + class C + { + void M() + { + var c = {|#0:new Banned()|}; + } + } + } + """, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", "")); + await VerifyBasicAnalyzerAsync(""" + Namespace N + Class Banned : End Class + Class C + Sub M() + Dim c As {|#0:New Banned()|} + End Sub + End Class + End Namespace + """, bannedText, GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", "")); } [Fact] public async Task DiagnosticReportedForBannedApiLineWithMessageThenWhitespaceFollowedByCommentAtTheEndMustNotIncludeWhitespaceInMessageAsync() { var bannedText = "T:N.Banned;message \t //comment here"; - - var csharpSource = @" -namespace N -{ - class Banned { } - class C - { - void M() - { - var c = {|#0:new Banned()|}; - } - } -}"; - - await VerifyCSharpAnalyzerAsync(csharpSource, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", ": message")); - - var visualBasicSource = @" -Namespace N - Class Banned : End Class - Class C - Sub M() - Dim c As {|#0:New Banned()|} - End Sub - End Class -End Namespace"; - - await VerifyBasicAnalyzerAsync(visualBasicSource, bannedText, GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", ": message")); + await VerifyCSharpAnalyzerAsync(""" + namespace N + { + class Banned { } + class C + { + void M() + { + var c = {|#0:new Banned()|}; + } + } + } + """, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", ": message")); + await VerifyBasicAnalyzerAsync(""" + Namespace N + Class Banned : End Class + Class C + Sub M() + Dim c As {|#0:New Banned()|} + End Sub + End Class + End Namespace + """, bannedText, GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", ": message")); } #endregion Comments in BannedSymbols.txt tests [Fact] - public async Task CSharp_BannedApiFile_MessageIncludedInDiagnosticAsync() - { - var source = @" -namespace N -{ - class Banned { } - class C - { - void M() - { - var c = {|#0:new Banned()|}; - } - } -}"; - - var bannedText = @"T:N.Banned;Use NonBanned instead"; - - await VerifyCSharpAnalyzerAsync(source, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", ": Use NonBanned instead")); - } + public Task CSharp_BannedApiFile_MessageIncludedInDiagnosticAsync() + => VerifyCSharpAnalyzerAsync(""" + namespace N + { + class Banned { } + class C + { + void M() + { + var c = {|#0:new Banned()|}; + } + } + } + """, @"T:N.Banned;Use NonBanned instead", GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", ": Use NonBanned instead")); [Fact] - public async Task CSharp_BannedApiFile_WhiteSpaceAsync() - { - var source = @" -namespace N -{ - class Banned { } - class C - { - void M() - { - var c = {|#0:new Banned()|}; - } - } -}"; - - var bannedText = @" - T:N.Banned "; - - await VerifyCSharpAnalyzerAsync(source, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", "")); - } + public Task CSharp_BannedApiFile_WhiteSpaceAsync() + => VerifyCSharpAnalyzerAsync(""" + namespace N + { + class Banned { } + class C + { + void M() + { + var c = {|#0:new Banned()|}; + } + } + } + """, """ + T:N.Banned + """, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", "")); [Fact] - public async Task CSharp_BannedApiFile_WhiteSpaceWithMessageAsync() - { - var source = @" -namespace N -{ - class Banned { } - class C - { - void M() - { - var c = {|#0:new Banned()|}; - } - } -}"; - - var bannedText = @"T:N.Banned ; Use NonBanned instead "; - - await VerifyCSharpAnalyzerAsync(source, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", ": Use NonBanned instead")); - } + public Task CSharp_BannedApiFile_WhiteSpaceWithMessageAsync() + => VerifyCSharpAnalyzerAsync(""" + namespace N + { + class Banned { } + class C + { + void M() + { + var c = {|#0:new Banned()|}; + } + } + } + """, @"T:N.Banned ; Use NonBanned instead ", GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", ": Use NonBanned instead")); [Fact] - public async Task CSharp_BannedApiFile_EmptyMessageAsync() - { - var source = @" -namespace N -{ - class Banned { } - class C - { - void M() - { - var c = {|#0:new Banned()|}; - } - } -}"; - - var bannedText = @"T:N.Banned;"; - - await VerifyCSharpAnalyzerAsync(source, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", "")); - } + public Task CSharp_BannedApiFile_EmptyMessageAsync() + => VerifyCSharpAnalyzerAsync(""" + namespace N + { + class Banned { } + class C + { + void M() + { + var c = {|#0:new Banned()|}; + } + } + } + """, @"T:N.Banned;", GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", "")); [Fact] public async Task CSharp_BannedApi_MultipleFiles() { - var source = @" -namespace N -{ - class BannedA { } - class BannedB { } - class NotBanned { } - class C - { - void M() - { - var a = {|#0:new BannedA()|}; - var b = {|#1:new BannedB()|}; - var c = new NotBanned(); - } - } -}"; + var source = """ + namespace N + { + class BannedA { } + class BannedB { } + class NotBanned { } + class C + { + void M() + { + var a = {|#0:new BannedA()|}; + var b = {|#1:new BannedB()|}; + var c = new NotBanned(); + } + } + } + """; var test = new VerifyCS.Test { @@ -583,226 +518,183 @@ void M() } [Fact] - public async Task CSharp_BannedType_ConstructorAsync() - { - var source = @" -namespace N -{ - class Banned { } - class C - { - void M() - { - var c = {|#0:new Banned()|}; - } - } -}"; - - var bannedText = @" -T:N.Banned"; - - await VerifyCSharpAnalyzerAsync(source, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", "")); - } + public Task CSharp_BannedType_ConstructorAsync() + => VerifyCSharpAnalyzerAsync(""" + namespace N + { + class Banned { } + class C + { + void M() + { + var c = {|#0:new Banned()|}; + } + } + } + """, """ + T:N.Banned + """, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", "")); [Fact] - public async Task CSharp_BannedNamespace_ConstructorAsync() - { - var source = @" -namespace N -{ - class C - { - void M() - { - var c = {|#0:new N.C()|}; - } - } -} -"; - - var bannedText = @" -N:N"; - - await VerifyCSharpAnalyzerAsync(source, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "N", "")); - } + public Task CSharp_BannedNamespace_ConstructorAsync() + => VerifyCSharpAnalyzerAsync(""" + namespace N + { + class C + { + void M() + { + var c = {|#0:new N.C()|}; + } + } + } + """, """ + N:N + """, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "N", "")); [Fact] - public async Task CSharp_BannedNamespace_Parent_ConstructorAsync() - { - var source = @" -namespace N.NN -{ - class C - { - void M() - { - var a = {|#0:new N.NN.C()|}; - } - } -} -"; - - var bannedText = @" -N:N"; - - await VerifyCSharpAnalyzerAsync(source, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "N", "")); - } + public Task CSharp_BannedNamespace_Parent_ConstructorAsync() + => VerifyCSharpAnalyzerAsync(""" + namespace N.NN + { + class C + { + void M() + { + var a = {|#0:new N.NN.C()|}; + } + } + } + """, """ + N:N + """, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "N", "")); [Fact] - public async Task CSharp_BannedNamespace_MethodGroupAsync() - { - var source = @" -namespace N -{ - delegate void D(); - class C - { - void M() - { - D d = {|#0:M|}; - } - } -} -"; - - var bannedText = @" -N:N"; - - await VerifyCSharpAnalyzerAsync(source, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "N", "")); - } + public Task CSharp_BannedNamespace_MethodGroupAsync() + => VerifyCSharpAnalyzerAsync(""" + namespace N + { + delegate void D(); + class C + { + void M() + { + D d = {|#0:M|}; + } + } + } + """, """ + N:N + """, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "N", "")); [Fact] - public async Task CSharp_BannedNamespace_PropertyAsync() - { - var source = @" -namespace N -{ - class C - { - public int P { get; set; } - void M() - { - {|#0:P|} = {|#1:P|}; - } - } -} -"; - - var bannedText = @" -N:N"; - - await VerifyCSharpAnalyzerAsync(source, bannedText, + public Task CSharp_BannedNamespace_PropertyAsync() + => VerifyCSharpAnalyzerAsync(""" + namespace N + { + class C + { + public int P { get; set; } + void M() + { + {|#0:P|} = {|#1:P|}; + } + } + } + """, """ + N:N + """, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "N", ""), GetCSharpResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "N", "")); - } [Fact] - public async Task CSharp_BannedNamespace_MethodAsync() - { - var source = @" -namespace N -{ - interface I - { - void M(); - } -} + public Task CSharp_BannedNamespace_MethodAsync() + => VerifyCSharpAnalyzerAsync(""" + namespace N + { + interface I + { + void M(); + } + } -class C -{ - void M() - { - N.I i = null; - {|#0:i.M()|}; - } -}"; - var bannedText = @"N:N"; + class C + { + void M() + { + N.I i = null; + {|#0:i.M()|}; + } + } + """, @"N:N", GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "N", "")); - await VerifyCSharpAnalyzerAsync(source, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "N", "")); - } + [Fact] + public Task CSharp_BannedNamespace_TypeOfArgument() + => VerifyCSharpAnalyzerAsync(""" + namespace N + { + class Banned { } + } + class C + { + void M() + { + var type = {|#0:typeof(N.Banned)|}; + } + } + """, @"N:N", GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "N", "")); [Fact] - public async Task CSharp_BannedNamespace_TypeOfArgument() - { - var source = @" -namespace N -{ - class Banned { } -} -class C -{ - void M() - { - var type = {|#0:typeof(N.Banned)|}; - } -} -"; - var bannedText = @"N:N"; - await VerifyCSharpAnalyzerAsync(source, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "N", "")); - } + public Task CSharp_BannedNamespace_Constituent() + => VerifyCSharpAnalyzerAsync(""" + class C + { + void M() + { + var thread = {|#0:new System.Threading.Thread((System.Threading.ThreadStart)null)|}; + } + } + """, @"N:System.Threading", GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "System.Threading", "")); [Fact] - public async Task CSharp_BannedNamespace_Constituent() - { - var source = @" -class C -{ - void M() - { - var thread = {|#0:new System.Threading.Thread((System.Threading.ThreadStart)null)|}; - } -} -"; - var bannedText = @"N:System.Threading"; - await VerifyCSharpAnalyzerAsync(source, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "System.Threading", "")); - } - - [Fact] - public async Task CSharp_BannedGenericType_ConstructorAsync() - { - var source = @" -class C -{ - void M() - { - var c = {|#0:new System.Collections.Generic.List()|}; - } -}"; - - var bannedText = @" -T:System.Collections.Generic.List`1"; - - await VerifyCSharpAnalyzerAsync(source, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "List", "")); - } + public Task CSharp_BannedGenericType_ConstructorAsync() + => VerifyCSharpAnalyzerAsync(""" + class C + { + void M() + { + var c = {|#0:new System.Collections.Generic.List()|}; + } + } + """, """ + T:System.Collections.Generic.List`1 + """, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "List", "")); [Fact] - public async Task CSharp_BannedType_AsTypeArgumentAsync() - { - var source = @" -struct C {} + public Task CSharp_BannedType_AsTypeArgumentAsync() + => VerifyCSharpAnalyzerAsync(""" + struct C {} -class G -{ - class N - { } - - unsafe void M() - { - var b = {|#0:new G()|}; - var c = {|#1:new G.N()|}; - var d = {|#2:new G.N()|}; - var e = {|#3:new G.N>.N()|}; - var f = {|#4:new G.N>.N()|}; - var g = {|#5:new C[42]|}; - var h = {|#6:new G()|}; - fixed (C* i = {|#7:&g[0]|}) { } - } -}"; - - var bannedText = @" -T:C"; + class G + { + class N + { } - await VerifyCSharpAnalyzerAsync(source, bannedText, + unsafe void M() + { + var b = {|#0:new G()|}; + var c = {|#1:new G.N()|}; + var d = {|#2:new G.N()|}; + var e = {|#3:new G.N>.N()|}; + var f = {|#4:new G.N>.N()|}; + var g = {|#5:new C[42]|}; + var h = {|#6:new G()|}; + fixed (C* i = {|#7:&g[0]|}) { } + } + } + """, """ + T:C + """, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", ""), GetCSharpResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", ""), GetCSharpResultAt(2, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", ""), @@ -811,98 +703,83 @@ await VerifyCSharpAnalyzerAsync(source, bannedText, GetCSharpResultAt(5, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", ""), GetCSharpResultAt(6, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", ""), GetCSharpResultAt(7, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", "")); - } [Fact] - public async Task CSharp_BannedNestedType_ConstructorAsync() - { - var source = @" -class C -{ - class Nested { } - void M() - { - var n = {|#0:new Nested()|}; - } -}"; - - var bannedText = @" -T:C.Nested"; - - await VerifyCSharpAnalyzerAsync(source, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Nested", "")); - } + public Task CSharp_BannedNestedType_ConstructorAsync() + => VerifyCSharpAnalyzerAsync(""" + class C + { + class Nested { } + void M() + { + var n = {|#0:new Nested()|}; + } + } + """, """ + T:C.Nested + """, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Nested", "")); [Fact] - public async Task CSharp_BannedType_MethodOnNestedTypeAsync() - { - var source = @" -class C -{ - public static class Nested - { - public static void M() { } - } -} - -class D -{ - void M2() - { - {|#0:C.Nested.M()|}; - } -}"; - var bannedText = @" -T:C"; + public Task CSharp_BannedType_MethodOnNestedTypeAsync() + => VerifyCSharpAnalyzerAsync(""" + class C + { + public static class Nested + { + public static void M() { } + } + } - await VerifyCSharpAnalyzerAsync(source, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", "")); - } + class D + { + void M2() + { + {|#0:C.Nested.M()|}; + } + } + """, """ + T:C + """, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", "")); [Fact] - public async Task CSharp_BannedInterface_MethodAsync() - { - var source = @" -interface I -{ - void M(); -} - -class C -{ - void M() - { - I i = null; - {|#0:i.M()|}; - } -}"; - var bannedText = @"T:I"; + public Task CSharp_BannedInterface_MethodAsync() + => VerifyCSharpAnalyzerAsync(""" + interface I + { + void M(); + } - await VerifyCSharpAnalyzerAsync(source, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "I", "")); - } + class C + { + void M() + { + I i = null; + {|#0:i.M()|}; + } + } + """, @"T:I", GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "I", "")); [Fact] - public async Task CSharp_BannedClass_OperatorsAsync() - { - var source = @" -class C -{ - public static implicit operator C(int i) => {|#0:new C()|}; - public static explicit operator C(float f) => {|#1:new C()|}; - public static C operator +(C c, int i) => c; - public static C operator ++(C c) => c; - public static C operator -(C c) => c; - - void M() - { - C c = {|#2:0|}; // implicit conversion. - c = {|#3:(C)1.0f|}; // Explicit conversion. - c = {|#4:c + 1|}; // Binary operator. - {|#5:c++|}; // Increment or decrement. - c = {|#6:-c|}; // Unary operator. - } -}"; - var bannedText = @"T:C"; + public Task CSharp_BannedClass_OperatorsAsync() + => VerifyCSharpAnalyzerAsync(""" + class C + { + public static implicit operator C(int i) => {|#0:new C()|}; + public static explicit operator C(float f) => {|#1:new C()|}; + public static C operator +(C c, int i) => c; + public static C operator ++(C c) => c; + public static C operator -(C c) => c; - await VerifyCSharpAnalyzerAsync(source, bannedText, + void M() + { + C c = {|#2:0|}; // implicit conversion. + c = {|#3:(C)1.0f|}; // Explicit conversion. + c = {|#4:c + 1|}; // Binary operator. + {|#5:c++|}; // Increment or decrement. + c = {|#6:-c|}; // Unary operator. + } + } + """, @"T:C", GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", ""), GetCSharpResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", ""), GetCSharpResultAt(2, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", ""), @@ -910,764 +787,666 @@ await VerifyCSharpAnalyzerAsync(source, bannedText, GetCSharpResultAt(4, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", ""), GetCSharpResultAt(5, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", ""), GetCSharpResultAt(6, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", "")); - } [Fact] - public async Task CSharp_BannedClass_PropertyAsync() - { - var source = @" -class C -{ - public int P { get; set; } - void M() - { - {|#0:P|} = {|#1:P|}; - } -}"; - var bannedText = @"T:C"; - - await VerifyCSharpAnalyzerAsync(source, bannedText, + public Task CSharp_BannedClass_PropertyAsync() + => VerifyCSharpAnalyzerAsync(""" + class C + { + public int P { get; set; } + void M() + { + {|#0:P|} = {|#1:P|}; + } + } + """, @"T:C", GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", ""), GetCSharpResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", "")); - } [Fact] - public async Task CSharp_BannedClass_FieldAsync() - { - var source = @" -class C -{ - public int F; - void M() - { - {|#0:F|} = {|#1:F|}; - } -}"; - var bannedText = @"T:C"; - - await VerifyCSharpAnalyzerAsync(source, bannedText, + public Task CSharp_BannedClass_FieldAsync() + => VerifyCSharpAnalyzerAsync(""" + class C + { + public int F; + void M() + { + {|#0:F|} = {|#1:F|}; + } + } + """, @"T:C", GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", ""), GetCSharpResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", "")); - } [Fact] - public async Task CSharp_BannedClass_EventAsync() - { - var source = @" -using System; - -class C -{ - public event EventHandler E; - void M() - { - {|#0:E|} += null; - {|#1:E|} -= null; - {|#2:E|}(null, EventArgs.Empty); - } -}"; - var bannedText = @"T:C"; + public Task CSharp_BannedClass_EventAsync() + => VerifyCSharpAnalyzerAsync(""" + using System; - await VerifyCSharpAnalyzerAsync(source, bannedText, + class C + { + public event EventHandler E; + void M() + { + {|#0:E|} += null; + {|#1:E|} -= null; + {|#2:E|}(null, EventArgs.Empty); + } + } + """, @"T:C", GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", ""), GetCSharpResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", ""), GetCSharpResultAt(2, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", "")); - } [Fact] - public async Task CSharp_BannedClass_MethodGroupAsync() - { - var source = @" -delegate void D(); -class C -{ - void M() - { - D d = {|#0:M|}; - } -} -"; - var bannedText = @"T:C"; - - await VerifyCSharpAnalyzerAsync(source, bannedText, + public Task CSharp_BannedClass_MethodGroupAsync() + => VerifyCSharpAnalyzerAsync(""" + delegate void D(); + class C + { + void M() + { + D d = {|#0:M|}; + } + } + """, @"T:C", GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", "")); - } [Fact] - public async Task CSharp_BannedClass_DocumentationReferenceAsync() - { - var source = @" -class C { } - -/// -class D { } -"; - var bannedText = @"T:C"; + public Task CSharp_BannedClass_DocumentationReferenceAsync() + => VerifyCSharpAnalyzerAsync(""" + class C { } - await VerifyCSharpAnalyzerAsync(source, bannedText, + /// + class D { } + """, @"T:C", GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", "")); - } [Fact] - public async Task CSharp_BannedAttribute_UsageOnTypeAsync() - { - var source = @" -using System; + public Task CSharp_BannedAttribute_UsageOnTypeAsync() + => VerifyCSharpAnalyzerAsync(""" + using System; -[AttributeUsage(AttributeTargets.All, Inherited = true)] -class BannedAttribute : Attribute { } + [AttributeUsage(AttributeTargets.All, Inherited = true)] + class BannedAttribute : Attribute { } -[{|#0:Banned|}] -class C { } -class D : C { } -"; - var bannedText = @"T:BannedAttribute"; - - await VerifyCSharpAnalyzerAsync(source, bannedText, + [{|#0:Banned|}] + class C { } + class D : C { } + """, @"T:BannedAttribute", GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "BannedAttribute", ""), GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "BannedAttribute", "")); - } [Fact] - public async Task CSharp_BannedAttribute_UsageOnMemberAsync() - { - var source = @" -using System; + public Task CSharp_BannedAttribute_UsageOnMemberAsync() + => VerifyCSharpAnalyzerAsync(""" + using System; -[AttributeUsage(AttributeTargets.All, Inherited = true)] -class BannedAttribute : Attribute { } + [AttributeUsage(AttributeTargets.All, Inherited = true)] + class BannedAttribute : Attribute { } -class C -{ - [{|#0:Banned|}] - public int SomeProperty { get; } -} -"; - var bannedText = @"T:BannedAttribute"; - - await VerifyCSharpAnalyzerAsync(source, bannedText, + class C + { + [{|#0:Banned|}] + public int SomeProperty { get; } + } + """, @"T:BannedAttribute", GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "BannedAttribute", ""), GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "BannedAttribute", "")); - } [Fact] - public async Task CSharp_BannedAttribute_UsageOnAssemblyAsync() - { - var source = @" -using System; + public Task CSharp_BannedAttribute_UsageOnAssemblyAsync() + => VerifyCSharpAnalyzerAsync(""" + using System; -[assembly: {|#0:BannedAttribute|}] + [assembly: {|#0:BannedAttribute|}] -[AttributeUsage(AttributeTargets.All, Inherited = true)] -class BannedAttribute : Attribute { } -"; - - var bannedText = @"T:BannedAttribute"; - - await VerifyCSharpAnalyzerAsync(source, bannedText, + [AttributeUsage(AttributeTargets.All, Inherited = true)] + class BannedAttribute : Attribute { } + """, @"T:BannedAttribute", GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "BannedAttribute", ""), GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "BannedAttribute", "")); - } [Fact] - public async Task CSharp_BannedAttribute_UsageOnModuleAsync() - { - var source = @" -using System; + public Task CSharp_BannedAttribute_UsageOnModuleAsync() + => VerifyCSharpAnalyzerAsync(""" + using System; -[module: {|#0:BannedAttribute|}] + [module: {|#0:BannedAttribute|}] -[AttributeUsage(AttributeTargets.All, Inherited = true)] -class BannedAttribute : Attribute { } -"; - - var bannedText = @"T:BannedAttribute"; - - await VerifyCSharpAnalyzerAsync(source, bannedText, + [AttributeUsage(AttributeTargets.All, Inherited = true)] + class BannedAttribute : Attribute { } + """, @"T:BannedAttribute", GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "BannedAttribute", ""), GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "BannedAttribute", "")); - } [Fact] public async Task CSharp_BannedConstructorAsync() { - var source = @" -namespace N -{ - class Banned - { - public Banned() {} - public Banned(int i) {} - } - class C - { - void M() - { - var c = {|#0:new Banned()|}; - var d = {|#1:new Banned(1)|}; - } - } -}"; - - var bannedText1 = @"M:N.Banned.#ctor"; - var bannedText2 = @"M:N.Banned.#ctor(System.Int32)"; - - await VerifyCSharpAnalyzerAsync( - source, - bannedText1, - GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned.Banned()", "")); - - await VerifyCSharpAnalyzerAsync( - source, - bannedText2, - GetCSharpResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned.Banned(int)", "")); - } - - [Fact] - public async Task Csharp_BannedConstructor_AttributeAsync() - { - var source = @" -using System; - -[AttributeUsage(AttributeTargets.All, Inherited = true)] -class BannedAttribute : Attribute -{ - public BannedAttribute() {} - public BannedAttribute(int banned) {} - public BannedAttribute(string notBanned) {} -} - -class C -{ - [{|#0:Banned|}] - public int SomeProperty { get; } - - [{|#1:Banned(1)|}] - public void SomeMethod() {} - - [Banned("""")] - class D {} -} -"; - var bannedText1 = @"M:BannedAttribute.#ctor"; - var bannedText2 = @"M:BannedAttribute.#ctor(System.Int32)"; - - await VerifyCSharpAnalyzerAsync( - source, - bannedText1, - GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "BannedAttribute.BannedAttribute()", ""), - GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "BannedAttribute.BannedAttribute()", "")); - - await VerifyCSharpAnalyzerAsync( - source, - bannedText2, - GetCSharpResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "BannedAttribute.BannedAttribute(int)", ""), - GetCSharpResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "BannedAttribute.BannedAttribute(int)", "")); - } - - [Fact] - public async Task CSharp_BannedMethodAsync() - { - var source = @" -namespace N -{ - class C - { - public void Banned() {} - public void Banned(int i) {} - public void Banned(T t) {} - - void M() - { - {|#0:Banned()|}; - {|#1:Banned(1)|}; - {|#2:Banned("""")|}; - } - } - - class D - { - public void Banned() {} - public void Banned(int i) {} - public void Banned(U u) {} - - void M() - { - {|#3:Banned()|}; - {|#4:Banned(1)|}; - {|#5:Banned("""")|}; - } - } -}"; - - var bannedText1 = @"M:N.C.Banned"; - var bannedText2 = @"M:N.C.Banned(System.Int32)"; - var bannedText3 = @"M:N.C.Banned``1(``0)"; - var bannedText4 = @"M:N.D`1.Banned()"; - var bannedText5 = @"M:N.D`1.Banned(System.Int32)"; - var bannedText6 = @"M:N.D`1.Banned``1(``0)"; - - await VerifyCSharpAnalyzerAsync( - source, - bannedText1, - GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Banned()", "")); - - await VerifyCSharpAnalyzerAsync( - source, - bannedText2, - GetCSharpResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Banned(int)", "")); - - await VerifyCSharpAnalyzerAsync( - source, - bannedText3, - GetCSharpResultAt(2, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Banned(T)", "")); - - await VerifyCSharpAnalyzerAsync( - source, - bannedText4, - GetCSharpResultAt(3, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "D.Banned()", "")); - - await VerifyCSharpAnalyzerAsync( - source, - bannedText5, - GetCSharpResultAt(4, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "D.Banned(int)", "")); - - await VerifyCSharpAnalyzerAsync( - source, - bannedText6, - GetCSharpResultAt(5, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "D.Banned(U)", "")); - } - - [Fact] - public async Task CSharp_BannedPropertyAsync() - { - var source = @" -namespace N -{ - class C - { - public int Banned { get; set; } - - void M() - { - {|#0:Banned|} = {|#1:Banned|}; - } - } -}"; - - var bannedText = @"P:N.C.Banned"; - - await VerifyCSharpAnalyzerAsync( - source, - bannedText, - GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Banned", ""), - GetCSharpResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Banned", "")); - } - - [Fact] - public async Task CSharp_BannedFieldAsync() - { - var source = @" -namespace N -{ - class C - { - public int Banned; - - void M() - { - {|#0:Banned|} = {|#1:Banned|}; - } - } -}"; - - var bannedText = @"F:N.C.Banned"; - - await VerifyCSharpAnalyzerAsync( - source, - bannedText, - GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Banned", ""), - GetCSharpResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Banned", "")); - } - - [Fact] - public async Task CSharp_BannedEventAsync() - { - var source = @" -namespace N -{ - class C - { - public event System.Action Banned; - - void M() - { - {|#0:Banned|} += null; - {|#1:Banned|} -= null; - {|#2:Banned|}(); - } - } -}"; - - var bannedText = @"E:N.C.Banned"; - - await VerifyCSharpAnalyzerAsync( - source, - bannedText, - GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Banned", ""), - GetCSharpResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Banned", ""), - GetCSharpResultAt(2, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Banned", "")); - } - - [Fact] - public async Task CSharp_BannedMethodGroupAsync() - { - var source = @" -namespace N -{ - class C - { - public void Banned() {} - - void M() - { - System.Action b = {|#0:Banned|}; - } - } -}"; - var bannedText = @"M:N.C.Banned"; - + var source = """ + namespace N + { + class Banned + { + public Banned() {} + public Banned(int i) {} + } + class C + { + void M() + { + var c = {|#0:new Banned()|}; + var d = {|#1:new Banned(1)|}; + } + } + } + """; await VerifyCSharpAnalyzerAsync( source, - bannedText, - GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Banned()", "")); - } - - [Fact] - public async Task CSharp_NoDiagnosticClass_TypeOfArgument() - { - var source = @" -class Banned { } -class C -{ - void M() - { - var type = {|#0:typeof(C)|}; - } -} -"; - var bannedText = @"T:Banned"; - await VerifyCSharpAnalyzerAsync(source, bannedText); - } - - [Fact] - public async Task CSharp_BannedClass_TypeOfArgument() - { - var source = @" -class Banned { } -class C -{ - void M() - { - var type = {|#0:typeof(Banned)|}; - } -} -"; - var bannedText = @"T:Banned"; - await VerifyCSharpAnalyzerAsync(source, bannedText, GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", "")); + @"M:N.Banned.#ctor", + GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned.Banned()", "")); + + await VerifyCSharpAnalyzerAsync( + source, + @"M:N.Banned.#ctor(System.Int32)", + GetCSharpResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned.Banned(int)", "")); } - [Fact, WorkItem(3295, "https://github.com/dotnet/roslyn-analyzers/issues/3295")] - public async Task CSharp_BannedAbstractVirtualMemberAlsoBansOverrides_RootLevelIsBannedAsync() + [Fact] + public async Task Csharp_BannedConstructor_AttributeAsync() { - var source = @" -using System; + var source = """ + using System; -namespace N -{ - public abstract class C1 - { - public abstract void Method1(); - public abstract int Property1 { get; set; } - public abstract event Action Event1; - - public virtual void Method2() {} - public virtual int Property2 { get; set; } - public virtual event Action Event2; - } - - public class C2 : C1 - { - public override void Method1() {} - public override int Property1 { get; set; } - public override event Action Event1; + [AttributeUsage(AttributeTargets.All, Inherited = true)] + class BannedAttribute : Attribute + { + public BannedAttribute() {} + public BannedAttribute(int banned) {} + public BannedAttribute(string notBanned) {} + } - public override void Method2() - { - {|RS0030:base.Method2()|}; - } + class C + { + [{|#0:Banned|}] + public int SomeProperty { get; } - public override int Property2 { get; set; } - public override event Action Event2; + [{|#1:Banned(1)|}] + public void SomeMethod() {} - void M1() - { - {|RS0030:Method1()|}; - if ({|RS0030:Property1|} == 42 && {|RS0030:Event1|} != null) {} + [Banned("")] + class D {} + } + """; + await VerifyCSharpAnalyzerAsync( + source, + @"M:BannedAttribute.#ctor", + GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "BannedAttribute.BannedAttribute()", ""), + GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "BannedAttribute.BannedAttribute()", "")); - {|RS0030:Method2()|}; - if ({|RS0030:Property2|} == 42 && {|RS0030:Event2|} != null) {} + await VerifyCSharpAnalyzerAsync( + source, + @"M:BannedAttribute.#ctor(System.Int32)", + GetCSharpResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "BannedAttribute.BannedAttribute(int)", ""), + GetCSharpResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "BannedAttribute.BannedAttribute(int)", "")); } - } - public class C3 : C2 - { - public override void Method1() + [Fact] + public async Task CSharp_BannedMethodAsync() { - {|RS0030:base.Method1()|}; - } + var source = """ + namespace N + { + class C + { + public void Banned() {} + public void Banned(int i) {} + public void Banned(T t) {} + + void M() + { + {|#0:Banned()|}; + {|#1:Banned(1)|}; + {|#2:Banned("")|}; + } + } + + class D + { + public void Banned() {} + public void Banned(int i) {} + public void Banned(U u) {} + + void M() + { + {|#3:Banned()|}; + {|#4:Banned(1)|}; + {|#5:Banned("")|}; + } + } + } + """; + await VerifyCSharpAnalyzerAsync( + source, + @"M:N.C.Banned", + GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Banned()", "")); - public override int Property1 { get; set; } - public override event Action Event1; + await VerifyCSharpAnalyzerAsync( + source, + @"M:N.C.Banned(System.Int32)", + GetCSharpResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Banned(int)", "")); - public override void Method2() - { - {|RS0030:base.Method2()|}; - } + await VerifyCSharpAnalyzerAsync( + source, + @"M:N.C.Banned``1(``0)", + GetCSharpResultAt(2, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Banned(T)", "")); - public override int Property2 { get; set; } - public override event Action Event2; + await VerifyCSharpAnalyzerAsync( + source, + @"M:N.D`1.Banned()", + GetCSharpResultAt(3, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "D.Banned()", "")); - void M2() - { - {|RS0030:Method1()|}; - if ({|RS0030:Property1|} == 42 && {|RS0030:Event1|} != null) {} + await VerifyCSharpAnalyzerAsync( + source, + @"M:N.D`1.Banned(System.Int32)", + GetCSharpResultAt(4, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "D.Banned(int)", "")); - {|RS0030:Method2()|}; - if ({|RS0030:Property2|} == 42 && {|RS0030:Event2|} != null) {} + await VerifyCSharpAnalyzerAsync( + source, + @"M:N.D`1.Banned``1(``0)", + GetCSharpResultAt(5, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "D.Banned(U)", "")); } - } -}"; - var bannedText = @"M:N.C1.Method1 -P:N.C1.Property1 -E:N.C1.Event1 -M:N.C1.Method2 -P:N.C1.Property2 -E:N.C1.Event2"; + [Fact] + public Task CSharp_BannedPropertyAsync() + => VerifyCSharpAnalyzerAsync( + """ + namespace N + { + class C + { + public int Banned { get; set; } - await VerifyCSharpAnalyzerAsync(source, bannedText); - } + void M() + { + {|#0:Banned|} = {|#1:Banned|}; + } + } + } + """, + @"P:N.C.Banned", + GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Banned", ""), + GetCSharpResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Banned", "")); - [Fact, WorkItem(3295, "https://github.com/dotnet/roslyn-analyzers/issues/3295")] - public async Task CSharp_BannedAbstractVirtualMemberBansCorrectOverrides_MiddleLevelIsBannedAsync() - { - var source = @" -using System; + [Fact] + public Task CSharp_BannedFieldAsync() + => VerifyCSharpAnalyzerAsync( + """ + namespace N + { + class C + { + public int Banned; -namespace N -{ - public abstract class C1 - { - public abstract void Method1(); - public abstract int Property1 { get; set; } - public abstract event Action Event1; + void M() + { + {|#0:Banned|} = {|#1:Banned|}; + } + } + } + """, + @"F:N.C.Banned", + GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Banned", ""), + GetCSharpResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Banned", "")); - public virtual void Method2() {} - public virtual int Property2 { get; set; } - public virtual event Action Event2; - } + [Fact] + public Task CSharp_BannedEventAsync() + => VerifyCSharpAnalyzerAsync( + """ + namespace N + { + class C + { + public event System.Action Banned; + + void M() + { + {|#0:Banned|} += null; + {|#1:Banned|} -= null; + {|#2:Banned|}(); + } + } + } + """, + @"E:N.C.Banned", + GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Banned", ""), + GetCSharpResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Banned", ""), + GetCSharpResultAt(2, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Banned", "")); - public class C2 : C1 - { - public override void Method1() {} - public override int Property1 { get; set; } - public override event Action Event1; + [Fact] + public Task CSharp_BannedMethodGroupAsync() + => VerifyCSharpAnalyzerAsync( + """ + namespace N + { + class C + { + public void Banned() {} - public override void Method2() - { - base.Method2(); - } + void M() + { + System.Action b = {|#0:Banned|}; + } + } + } + """, + @"M:N.C.Banned", + GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Banned()", "")); - public override int Property2 { get; set; } - public override event Action Event2; + [Fact] + public Task CSharp_NoDiagnosticClass_TypeOfArgument() + => VerifyCSharpAnalyzerAsync(""" + class Banned { } + class C + { + void M() + { + var type = {|#0:typeof(C)|}; + } + } + """, @"T:Banned"); - void M1() - { - {|RS0030:Method1()|}; - if ({|RS0030:Property1|} == 42 && {|RS0030:Event1|} != null) {} + [Fact] + public Task CSharp_BannedClass_TypeOfArgument() + => VerifyCSharpAnalyzerAsync(""" + class Banned { } + class C + { + void M() + { + var type = {|#0:typeof(Banned)|}; + } + } + """, @"T:Banned", GetCSharpResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", "")); - {|RS0030:Method2()|}; - if ({|RS0030:Property2|} == 42 && {|RS0030:Event2|} != null) {} - } - } + [Fact, WorkItem(3295, "https://github.com/dotnet/roslyn-analyzers/issues/3295")] + public Task CSharp_BannedAbstractVirtualMemberAlsoBansOverrides_RootLevelIsBannedAsync() + => VerifyCSharpAnalyzerAsync(""" + using System; - public class C3 : C2 - { - public override void Method1() - { - {|RS0030:base.Method1()|}; - } + namespace N + { + public abstract class C1 + { + public abstract void Method1(); + public abstract int Property1 { get; set; } + public abstract event Action Event1; - public override int Property1 { get; set; } - public override event Action Event1; + public virtual void Method2() {} + public virtual int Property2 { get; set; } + public virtual event Action Event2; + } - public override void Method2() - { - {|RS0030:base.Method2()|}; - } + public class C2 : C1 + { + public override void Method1() {} + public override int Property1 { get; set; } + public override event Action Event1; - public override int Property2 { get; set; } - public override event Action Event2; + public override void Method2() + { + {|RS0030:base.Method2()|}; + } - void M2() - { - {|RS0030:Method1()|}; - if ({|RS0030:Property1|} == 42 && {|RS0030:Event1|} != null) {} + public override int Property2 { get; set; } + public override event Action Event2; - {|RS0030:Method2()|}; - if ({|RS0030:Property2|} == 42 && {|RS0030:Event2|} != null) {} - } - } -}"; + void M1() + { + {|RS0030:Method1()|}; + if ({|RS0030:Property1|} == 42 && {|RS0030:Event1|} != null) {} - var bannedText = @"M:N.C2.Method1 -P:N.C2.Property1 -E:N.C2.Event1 -M:N.C2.Method2 -P:N.C2.Property2 -E:N.C2.Event2"; + {|RS0030:Method2()|}; + if ({|RS0030:Property2|} == 42 && {|RS0030:Event2|} != null) {} + } + } - await VerifyCSharpAnalyzerAsync(source, bannedText); - } + public class C3 : C2 + { + public override void Method1() + { + {|RS0030:base.Method1()|}; + } + + public override int Property1 { get; set; } + public override event Action Event1; + + public override void Method2() + { + {|RS0030:base.Method2()|}; + } + + public override int Property2 { get; set; } + public override event Action Event2; + + void M2() + { + {|RS0030:Method1()|}; + if ({|RS0030:Property1|} == 42 && {|RS0030:Event1|} != null) {} + + {|RS0030:Method2()|}; + if ({|RS0030:Property2|} == 42 && {|RS0030:Event2|} != null) {} + } + } + } + """, """ + M:N.C1.Method1 + P:N.C1.Property1 + E:N.C1.Event1 + M:N.C1.Method2 + P:N.C1.Property2 + E:N.C1.Event2 + """); [Fact, WorkItem(3295, "https://github.com/dotnet/roslyn-analyzers/issues/3295")] - public async Task CSharp_BannedAbstractVirtualMemberBansCorrectOverrides_LeafLevelIsBannedAsync() - { - var source = @" -using System; + public Task CSharp_BannedAbstractVirtualMemberBansCorrectOverrides_MiddleLevelIsBannedAsync() + => VerifyCSharpAnalyzerAsync(""" + using System; -namespace N -{ - public abstract class C1 - { - public abstract void Method1(); - public abstract int Property1 { get; set; } - public abstract event Action Event1; + namespace N + { + public abstract class C1 + { + public abstract void Method1(); + public abstract int Property1 { get; set; } + public abstract event Action Event1; - public virtual void Method2() {} - public virtual int Property2 { get; set; } - public virtual event Action Event2; - } + public virtual void Method2() {} + public virtual int Property2 { get; set; } + public virtual event Action Event2; + } - public class C2 : C1 - { - public override void Method1() {} - public override int Property1 { get; set; } - public override event Action Event1; + public class C2 : C1 + { + public override void Method1() {} + public override int Property1 { get; set; } + public override event Action Event1; - public override void Method2() - { - base.Method2(); - } + public override void Method2() + { + base.Method2(); + } - public override int Property2 { get; set; } - public override event Action Event2; + public override int Property2 { get; set; } + public override event Action Event2; - void M1() - { - Method1(); - if (Property1 == 42 && Event1 != null) {} + void M1() + { + {|RS0030:Method1()|}; + if ({|RS0030:Property1|} == 42 && {|RS0030:Event1|} != null) {} - Method2(); - if (Property2 == 42 && Event2 != null) {} - } - } + {|RS0030:Method2()|}; + if ({|RS0030:Property2|} == 42 && {|RS0030:Event2|} != null) {} + } + } - public class C3 : C2 - { - public override void Method1() - { - base.Method1(); - } + public class C3 : C2 + { + public override void Method1() + { + {|RS0030:base.Method1()|}; + } + + public override int Property1 { get; set; } + public override event Action Event1; + + public override void Method2() + { + {|RS0030:base.Method2()|}; + } + + public override int Property2 { get; set; } + public override event Action Event2; + + void M2() + { + {|RS0030:Method1()|}; + if ({|RS0030:Property1|} == 42 && {|RS0030:Event1|} != null) {} + + {|RS0030:Method2()|}; + if ({|RS0030:Property2|} == 42 && {|RS0030:Event2|} != null) {} + } + } + } + """, """ + M:N.C2.Method1 + P:N.C2.Property1 + E:N.C2.Event1 + M:N.C2.Method2 + P:N.C2.Property2 + E:N.C2.Event2 + """); - public override int Property1 { get; set; } - public override event Action Event1; + [Fact, WorkItem(3295, "https://github.com/dotnet/roslyn-analyzers/issues/3295")] + public Task CSharp_BannedAbstractVirtualMemberBansCorrectOverrides_LeafLevelIsBannedAsync() + => VerifyCSharpAnalyzerAsync(""" + using System; - public override void Method2() - { - base.Method2(); - } + namespace N + { + public abstract class C1 + { + public abstract void Method1(); + public abstract int Property1 { get; set; } + public abstract event Action Event1; - public override int Property2 { get; set; } - public override event Action Event2; + public virtual void Method2() {} + public virtual int Property2 { get; set; } + public virtual event Action Event2; + } - void M2() - { - {|RS0030:Method1()|}; - if ({|RS0030:Property1|} == 42 && {|RS0030:Event1|} != null) {} + public class C2 : C1 + { + public override void Method1() {} + public override int Property1 { get; set; } + public override event Action Event1; - {|RS0030:Method2()|}; - if ({|RS0030:Property2|} == 42 && {|RS0030:Event2|} != null) {} - } - } -}"; + public override void Method2() + { + base.Method2(); + } - var bannedText = @"M:N.C3.Method1 -P:N.C3.Property1 -E:N.C3.Event1 -M:N.C3.Method2 -P:N.C3.Property2 -E:N.C3.Event2"; + public override int Property2 { get; set; } + public override event Action Event2; - await VerifyCSharpAnalyzerAsync(source, bannedText); - } + void M1() + { + Method1(); + if (Property1 == 42 && Event1 != null) {} - [Fact] - public async Task CSharp_InvalidOverrideDefinitionAsync() - { - var source = @" -using System; + Method2(); + if (Property2 == 42 && Event2 != null) {} + } + } -namespace N -{ - public class C1 - { - public void Method1() {} - } + public class C3 : C2 + { + public override void Method1() + { + base.Method1(); + } + + public override int Property1 { get; set; } + public override event Action Event1; + + public override void Method2() + { + base.Method2(); + } + + public override int Property2 { get; set; } + public override event Action Event2; + + void M2() + { + {|RS0030:Method1()|}; + if ({|RS0030:Property1|} == 42 && {|RS0030:Event1|} != null) {} + + {|RS0030:Method2()|}; + if ({|RS0030:Property2|} == 42 && {|RS0030:Event2|} != null) {} + } + } + } + """, """ + M:N.C3.Method1 + P:N.C3.Property1 + E:N.C3.Event1 + M:N.C3.Method2 + P:N.C3.Property2 + E:N.C3.Event2 + """); - public class C2 : C1 - { - public override void {|CS0506:Method1|}() {} + [Fact] + public Task CSharp_InvalidOverrideDefinitionAsync() + => VerifyCSharpAnalyzerAsync(""" + using System; - void M1() - { - Method1(); - } - } -}"; + namespace N + { + public class C1 + { + public void Method1() {} + } - var bannedText = @"M:N.C1.Method1"; + public class C2 : C1 + { + public override void {|CS0506:Method1|}() {} - await VerifyCSharpAnalyzerAsync(source, bannedText); - } + void M1() + { + Method1(); + } + } + } + """, @"M:N.C1.Method1"); [Fact] public async Task VisualBasic_BannedApi_MultipleFiles() { - var source = @" -Namespace N - Class BannedA : End Class - Class BannedB : End Class - Class NotBanned : End Class - Class C - Sub M() - Dim a As {|#0:New BannedA()|} - Dim b As {|#1:New BannedB()|} - Dim c As New NotBanned() - End Sub - End Class -End Namespace"; + var source = """ + Namespace N + Class BannedA : End Class + Class BannedB : End Class + Class NotBanned : End Class + Class C + Sub M() + Dim a As {|#0:New BannedA()|} + Dim b As {|#1:New BannedB()|} + Dim c As New NotBanned() + End Sub + End Class + End Namespace + """; var test = new VerifyVB.Test { @@ -1692,328 +1471,263 @@ End Class } [Fact] - public async Task VisualBasic_BannedType_ConstructorAsync() - { - var source = @" -Namespace N - Class Banned : End Class - Class C - Sub M() - Dim c As {|#0:New Banned()|} - End Sub - End Class -End Namespace"; - - var bannedText = @"T:N.Banned"; - - await VerifyBasicAnalyzerAsync(source, bannedText, GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", "")); - } - - [Fact] - public async Task VisualBasic_BannedGenericType_ConstructorAsync() - { - var source = @" -Class C - Sub M() - Dim c = {|#0:New System.Collections.Generic.List(Of String)()|} - End Sub -End Class"; - - var bannedText = @" -T:System.Collections.Generic.List`1"; - - await VerifyBasicAnalyzerAsync(source, bannedText, GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "List(Of T)", "")); - } - - [Fact] - public async Task VisualBasic_BannedNestedType_ConstructorAsync() - { - var source = @" -Class C - Class Nested : End Class - Sub M() - Dim n As {|#0:New Nested()|} - End Sub -End Class"; - - var bannedText = @" -T:C.Nested"; - - await VerifyBasicAnalyzerAsync(source, bannedText, GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Nested", "")); - } - - [Fact] - public async Task VisualBasic_BannedType_MethodOnNestedTypeAsync() - { - var source = @" -Class C - Public Class Nested - Public Shared Sub M() : End Sub - End Class -End Class - -Class D - Sub M2() - {|#0:C.Nested.M()|} - End Sub -End Class -"; - var bannedText = @" -T:C"; - - await VerifyBasicAnalyzerAsync(source, bannedText, GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", "")); - } - - [Fact] - public async Task VisualBasic_BannedInterface_MethodAsync() - { - var source = @" -Interface I - Sub M() -End Interface - -Class C - Sub M() - Dim i As I = Nothing - {|#0:i.M()|} - End Sub -End Class"; - var bannedText = @"T:I"; - - await VerifyBasicAnalyzerAsync(source, bannedText, GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "I", "")); - } - - [Fact] - public async Task VisualBasic_BannedClass_PropertyAsync() - { - var source = @" -Class C - Public Property P As Integer - Sub M() - {|#0:P|} = {|#1:P|} - End Sub -End Class"; - var bannedText = @"T:C"; - - await VerifyBasicAnalyzerAsync(source, bannedText, + public Task VisualBasic_BannedType_ConstructorAsync() + => VerifyBasicAnalyzerAsync(""" + Namespace N + Class Banned : End Class + Class C + Sub M() + Dim c As {|#0:New Banned()|} + End Sub + End Class + End Namespace + """, @"T:N.Banned", GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Banned", "")); + + [Fact] + public Task VisualBasic_BannedGenericType_ConstructorAsync() + => VerifyBasicAnalyzerAsync(""" + Class C + Sub M() + Dim c = {|#0:New System.Collections.Generic.List(Of String)()|} + End Sub + End Class + """, """ + T:System.Collections.Generic.List`1 + """, GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "List(Of T)", "")); + + [Fact] + public Task VisualBasic_BannedNestedType_ConstructorAsync() + => VerifyBasicAnalyzerAsync(""" + Class C + Class Nested : End Class + Sub M() + Dim n As {|#0:New Nested()|} + End Sub + End Class + """, """ + T:C.Nested + """, GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C.Nested", "")); + + [Fact] + public Task VisualBasic_BannedType_MethodOnNestedTypeAsync() + => VerifyBasicAnalyzerAsync(""" + Class C + Public Class Nested + Public Shared Sub M() : End Sub + End Class + End Class + + Class D + Sub M2() + {|#0:C.Nested.M()|} + End Sub + End Class + """, """ + T:C + """, GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", "")); + + [Fact] + public Task VisualBasic_BannedInterface_MethodAsync() + => VerifyBasicAnalyzerAsync(""" + Interface I + Sub M() + End Interface + + Class C + Sub M() + Dim i As I = Nothing + {|#0:i.M()|} + End Sub + End Class + """, @"T:I", GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "I", "")); + + [Fact] + public Task VisualBasic_BannedClass_PropertyAsync() + => VerifyBasicAnalyzerAsync(""" + Class C + Public Property P As Integer + Sub M() + {|#0:P|} = {|#1:P|} + End Sub + End Class + """, @"T:C", GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", ""), GetBasicResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", "")); - } [Fact] - public async Task VisualBasic_BannedClass_FieldAsync() - { - var source = @" -Class C - Public F As Integer - Sub M() - {|#0:F|} = {|#1:F|} - End Sub -End Class"; - var bannedText = @"T:C"; - - await VerifyBasicAnalyzerAsync(source, bannedText, + public Task VisualBasic_BannedClass_FieldAsync() + => VerifyBasicAnalyzerAsync(""" + Class C + Public F As Integer + Sub M() + {|#0:F|} = {|#1:F|} + End Sub + End Class + """, @"T:C", GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", ""), GetBasicResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", "")); - } [Fact] - public async Task VisualBasic_BannedClass_EventAsync() - { - var source = @" -Imports System - -Class C - public Event E As EventHandler - Sub M() - AddHandler {|#0:E|}, Nothing - RemoveHandler {|#1:E|}, Nothing - RaiseEvent {|#2:E|}(Me, EventArgs.Empty) - End Sub -End Class"; - var bannedText = @"T:C"; - - await VerifyBasicAnalyzerAsync(source, bannedText, + public Task VisualBasic_BannedClass_EventAsync() + => VerifyBasicAnalyzerAsync(""" + Imports System + + Class C + public Event E As EventHandler + Sub M() + AddHandler {|#0:E|}, Nothing + RemoveHandler {|#1:E|}, Nothing + RaiseEvent {|#2:E|}(Me, EventArgs.Empty) + End Sub + End Class + """, @"T:C", GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", ""), GetBasicResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", ""), GetBasicResultAt(2, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", "")); - } [Fact] - public async Task VisualBasic_BannedClass_MethodGroupAsync() - { - var source = @" -Delegate Sub D() -Class C - Sub M() - Dim d as D = {|#0:AddressOf M|} - End Sub -End Class"; - var bannedText = @"T:C"; - - await VerifyBasicAnalyzerAsync(source, bannedText, + public Task VisualBasic_BannedClass_MethodGroupAsync() + => VerifyBasicAnalyzerAsync(""" + Delegate Sub D() + Class C + Sub M() + Dim d as D = {|#0:AddressOf M|} + End Sub + End Class + """, @"T:C", GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", "")); - } [Fact] - public async Task VisualBasic_BannedAttribute_UsageOnTypeAsync() - { - var source = @" -Imports System - - -Class BannedAttribute - Inherits Attribute -End Class - -<{|#0:Banned|}> -Class C -End Class -Class D - Inherits C -End Class -"; - var bannedText = @"T:BannedAttribute"; - - await VerifyBasicAnalyzerAsync(source, bannedText, + public Task VisualBasic_BannedAttribute_UsageOnTypeAsync() + => VerifyBasicAnalyzerAsync(""" + Imports System + + + Class BannedAttribute + Inherits Attribute + End Class + + <{|#0:Banned|}> + Class C + End Class + Class D + Inherits C + End Class + """, @"T:BannedAttribute", GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "BannedAttribute", ""), GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "BannedAttribute", "")); - } [Fact] - public async Task VisualBasic_BannedAttribute_UsageOnMemberAsync() - { - var source = @" -Imports System - - -Class BannedAttribute - Inherits System.Attribute -End Class - -Class C - <{|#0:Banned|}> - Public ReadOnly Property SomeProperty As Integer -End Class -"; - var bannedText = @"T:BannedAttribute"; - - await VerifyBasicAnalyzerAsync(source, bannedText, + public Task VisualBasic_BannedAttribute_UsageOnMemberAsync() + => VerifyBasicAnalyzerAsync(""" + Imports System + + + Class BannedAttribute + Inherits System.Attribute + End Class + + Class C + <{|#0:Banned|}> + Public ReadOnly Property SomeProperty As Integer + End Class + """, @"T:BannedAttribute", GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "BannedAttribute", ""), GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "BannedAttribute", "")); - } [Fact] - public async Task VisualBasic_BannedAttribute_UsageOnAssemblyAsync() - { - var source = @" -Imports System + public Task VisualBasic_BannedAttribute_UsageOnAssemblyAsync() + => VerifyBasicAnalyzerAsync(""" + Imports System -<{|#0:Assembly:BannedAttribute|}> + <{|#0:Assembly:BannedAttribute|}> - -Class BannedAttribute - Inherits Attribute -End Class -"; - - var bannedText = @"T:BannedAttribute"; - - await VerifyBasicAnalyzerAsync(source, bannedText, + + Class BannedAttribute + Inherits Attribute + End Class + """, @"T:BannedAttribute", GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "BannedAttribute", ""), GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "BannedAttribute", "")); - } [Fact] - public async Task VisualBasic_BannedAttribute_UsageOnModuleAsync() - { - var source = @" -Imports System + public Task VisualBasic_BannedAttribute_UsageOnModuleAsync() + => VerifyBasicAnalyzerAsync(""" + Imports System -<{|#0:Module:BannedAttribute|}> + <{|#0:Module:BannedAttribute|}> - -Class BannedAttribute - Inherits Attribute -End Class -"; - - var bannedText = @"T:BannedAttribute"; - - await VerifyBasicAnalyzerAsync(source, bannedText, + + Class BannedAttribute + Inherits Attribute + End Class + """, @"T:BannedAttribute", GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "BannedAttribute", ""), GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "BannedAttribute", "")); - } [Fact] public async Task VisualBasic_BannedConstructorAsync() { - var source = @" -Namespace N - Class Banned - Sub New : End Sub - Sub New(ByVal I As Integer) : End Sub - End Class - Class C - Sub M() - Dim c As {|#0:New Banned()|} - Dim d As {|#1:New Banned(1)|} - End Sub - End Class -End Namespace"; - - var bannedText1 = @"M:N.Banned.#ctor"; - var bannedText2 = @"M:N.Banned.#ctor(System.Int32)"; - + var source = """ + Namespace N + Class Banned + Sub New : End Sub + Sub New(ByVal I As Integer) : End Sub + End Class + Class C + Sub M() + Dim c As {|#0:New Banned()|} + Dim d As {|#1:New Banned(1)|} + End Sub + End Class + End Namespace + """; await VerifyBasicAnalyzerAsync( source, - bannedText1, + @"M:N.Banned.#ctor", GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Public Sub New()", "")); await VerifyBasicAnalyzerAsync( source, - bannedText2, + @"M:N.Banned.#ctor(System.Int32)", GetBasicResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Public Sub New(I As Integer)", "")); } [Fact] public async Task VisualBasic_BannedConstructor_AttributeAsync() { - var source = @" -Imports System + var source = """ + Imports System - -Class BannedAttribute - Inherits System.Attribute + + Class BannedAttribute + Inherits System.Attribute - Sub New : End Sub - Sub New(ByVal Banned As Integer) : End Sub - Sub New(ByVal NotBanned As String) : End Sub -End Class + Sub New : End Sub + Sub New(ByVal Banned As Integer) : End Sub + Sub New(ByVal NotBanned As String) : End Sub + End Class -Class C - <{|#0:Banned|}> - Public ReadOnly Property SomeProperty As Integer + Class C + <{|#0:Banned|}> + Public ReadOnly Property SomeProperty As Integer - <{|#1:Banned(1)|}> - Public Sub SomeMethod : End Sub - - - Class D : End Class -End Class -"; - var bannedText1 = @"M:BannedAttribute.#ctor"; - var bannedText2 = @"M:BannedAttribute.#ctor(System.Int32)"; + <{|#1:Banned(1)|}> + Public Sub SomeMethod : End Sub + + Class D : End Class + End Class + """; await VerifyBasicAnalyzerAsync( source, - bannedText1, + @"M:BannedAttribute.#ctor", GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Public Sub New()", ""), GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Public Sub New()", "")); await VerifyBasicAnalyzerAsync( source, - bannedText2, + @"M:BannedAttribute.#ctor(System.Int32)", GetBasicResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Public Sub New(Banned As Integer)", ""), GetBasicResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Public Sub New(Banned As Integer)", "")); } @@ -2021,388 +1735,348 @@ await VerifyBasicAnalyzerAsync( [Fact] public async Task VisualBasic_BannedMethodAsync() { - var source = @" -Namespace N - Class C - Sub Banned : End Sub - Sub Banned(ByVal I As Integer) : End Sub - Sub M() - {|#0:Me.Banned()|} - {|#1:Me.Banned(1)|} - End Sub - End Class -End Namespace"; - - var bannedText1 = @"M:N.C.Banned"; - var bannedText2 = @"M:N.C.Banned(System.Int32)"; - + var source = """ + Namespace N + Class C + Sub Banned : End Sub + Sub Banned(ByVal I As Integer) : End Sub + Sub M() + {|#0:Me.Banned()|} + {|#1:Me.Banned(1)|} + End Sub + End Class + End Namespace + """; await VerifyBasicAnalyzerAsync( source, - bannedText1, + @"M:N.C.Banned", GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Public Sub Banned()", "")); await VerifyBasicAnalyzerAsync( source, - bannedText2, + @"M:N.C.Banned(System.Int32)", GetBasicResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Public Sub Banned(I As Integer)", "")); } [Fact] - public async Task VisualBasic_BannedPropertyAsync() - { - var source = @" -Namespace N - Class C - Public Property Banned As Integer - Sub M() - {|#0:Banned|} = {|#1:Banned|} - End Sub - End Class -End Namespace"; - - var bannedText = @"P:N.C.Banned"; - - await VerifyBasicAnalyzerAsync( - source, - bannedText, + public Task VisualBasic_BannedPropertyAsync() + => VerifyBasicAnalyzerAsync( + """ + Namespace N + Class C + Public Property Banned As Integer + Sub M() + {|#0:Banned|} = {|#1:Banned|} + End Sub + End Class + End Namespace + """, + @"P:N.C.Banned", GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Public Property Banned As Integer", ""), GetBasicResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Public Property Banned As Integer", "")); - } [Fact] - public async Task VisualBasic_BannedFieldAsync() - { - var source = @" -Namespace N - Class C - Public Banned As Integer - Sub M() - {|#0:Banned|} = {|#1:Banned|} - End Sub - End Class -End Namespace"; - - var bannedText = @"F:N.C.Banned"; - - await VerifyBasicAnalyzerAsync( - source, - bannedText, + public Task VisualBasic_BannedFieldAsync() + => VerifyBasicAnalyzerAsync( + """ + Namespace N + Class C + Public Banned As Integer + Sub M() + {|#0:Banned|} = {|#1:Banned|} + End Sub + End Class + End Namespace + """, + @"F:N.C.Banned", GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Public Banned As Integer", ""), GetBasicResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Public Banned As Integer", "")); - } [Fact] - public async Task VisualBasic_BannedEventAsync() - { - var source = @" -Namespace N - Class C - Public Event Banned As System.Action - Sub M() - AddHandler {|#0:Banned|}, Nothing - RemoveHandler {|#1:Banned|}, Nothing - RaiseEvent {|#2:Banned|}() - End Sub - End Class -End Namespace"; - - var bannedText = @"E:N.C.Banned"; - - await VerifyBasicAnalyzerAsync( - source, - bannedText, + public Task VisualBasic_BannedEventAsync() + => VerifyBasicAnalyzerAsync( + """ + Namespace N + Class C + Public Event Banned As System.Action + Sub M() + AddHandler {|#0:Banned|}, Nothing + RemoveHandler {|#1:Banned|}, Nothing + RaiseEvent {|#2:Banned|}() + End Sub + End Class + End Namespace + """, + @"E:N.C.Banned", GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Public Event Banned As Action", ""), GetBasicResultAt(1, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Public Event Banned As Action", ""), GetBasicResultAt(2, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Public Event Banned As Action", "")); - } [Fact] - public async Task VisualBasic_BannedMethodGroupAsync() - { - var source = @" -Namespace N - Class C - Public Sub Banned() : End Sub - Sub M() - Dim b As System.Action = {|#0:AddressOf Banned|} - End Sub - End Class -End Namespace"; - - var bannedText = @"M:N.C.Banned"; - - await VerifyBasicAnalyzerAsync( - source, - bannedText, + public Task VisualBasic_BannedMethodGroupAsync() + => VerifyBasicAnalyzerAsync( + """ + Namespace N + Class C + Public Sub Banned() : End Sub + Sub M() + Dim b As System.Action = {|#0:AddressOf Banned|} + End Sub + End Class + End Namespace + """, + @"M:N.C.Banned", GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "Public Sub Banned()", "")); - } [Fact] - public async Task VisualBasic_BannedClass_DocumentationReferenceAsync() - { - var source = @" -Class C : End Class - -''' -Class D : End Class -"; - var bannedText = @"T:C"; + public Task VisualBasic_BannedClass_DocumentationReferenceAsync() + => VerifyBasicAnalyzerAsync(""" + Class C : End Class - await VerifyBasicAnalyzerAsync(source, bannedText, + ''' + Class D : End Class + """, @"T:C", GetBasicResultAt(0, SymbolIsBannedAnalyzer.SymbolIsBannedRule, "C", "")); - } [Fact, WorkItem(3295, "https://github.com/dotnet/roslyn-analyzers/issues/3295")] - public async Task VisualBasic_BannedAbstractVirtualMemberAlsoBansOverrides_RootLevelIsBannedAsync() - { - var source = @" -Imports System - -Namespace N - Public MustInherit Class C1 - Public MustOverride Sub Method1() - Public MustOverride Property Property1 As Integer - - Public Overridable Sub Method2() - End Sub + public Task VisualBasic_BannedAbstractVirtualMemberAlsoBansOverrides_RootLevelIsBannedAsync() + => VerifyBasicAnalyzerAsync(""" + Imports System - Public Overridable Property Property2 As Integer - End Class + Namespace N + Public MustInherit Class C1 + Public MustOverride Sub Method1() + Public MustOverride Property Property1 As Integer - Public Class C2 - Inherits C1 + Public Overridable Sub Method2() + End Sub - Public Overrides Sub Method1() - End Sub + Public Overridable Property Property2 As Integer + End Class - Public Overrides Property Property1 As Integer + Public Class C2 + Inherits C1 - Public Overrides Sub Method2() - {|RS0030:MyBase.Method2()|} - End Sub + Public Overrides Sub Method1() + End Sub - Public Overrides Property Property2 As Integer + Public Overrides Property Property1 As Integer - Private Sub M1() - {|RS0030:Method1()|} + Public Overrides Sub Method2() + {|RS0030:MyBase.Method2()|} + End Sub - If {|RS0030:Property1|} = 42 Then - End If + Public Overrides Property Property2 As Integer - {|RS0030:Method2()|} + Private Sub M1() + {|RS0030:Method1()|} - If {|RS0030:Property2|} = 42 Then - End If - End Sub - End Class + If {|RS0030:Property1|} = 42 Then + End If - Public Class C3 - Inherits C2 + {|RS0030:Method2()|} - Public Overrides Sub Method1() - {|RS0030:MyBase.Method1()|} - End Sub + If {|RS0030:Property2|} = 42 Then + End If + End Sub + End Class - Public Overrides Property Property1 As Integer + Public Class C3 + Inherits C2 - Public Overrides Sub Method2() - {|RS0030:MyBase.Method2()|} - End Sub + Public Overrides Sub Method1() + {|RS0030:MyBase.Method1()|} + End Sub - Public Overrides Property Property2 As Integer + Public Overrides Property Property1 As Integer - Private Sub M2() - {|RS0030:Method1()|} + Public Overrides Sub Method2() + {|RS0030:MyBase.Method2()|} + End Sub - If {|RS0030:Property1|} = 42 Then - End If + Public Overrides Property Property2 As Integer - {|RS0030:Method2()|} + Private Sub M2() + {|RS0030:Method1()|} - If {|RS0030:Property2|} = 42 Then - End If - End Sub - End Class -End Namespace -"; + If {|RS0030:Property1|} = 42 Then + End If - var bannedText = @"M:N.C1.Method1 -P:N.C1.Property1 -E:N.C1.Event1 -M:N.C1.Method2 -P:N.C1.Property2 -E:N.C1.Event2"; + {|RS0030:Method2()|} - await VerifyBasicAnalyzerAsync(source, bannedText); - } + If {|RS0030:Property2|} = 42 Then + End If + End Sub + End Class + End Namespace + """, """ + M:N.C1.Method1 + P:N.C1.Property1 + E:N.C1.Event1 + M:N.C1.Method2 + P:N.C1.Property2 + E:N.C1.Event2 + """); [Fact, WorkItem(3295, "https://github.com/dotnet/roslyn-analyzers/issues/3295")] - public async Task VisualBasic_BannedAbstractVirtualMemberAlsoBansOverrides_MiddleLevelIsBannedAsync() - { - var source = @" -Imports System - -Namespace N - Public MustInherit Class C1 - Public MustOverride Sub Method1() - Public MustOverride Property Property1 As Integer + public Task VisualBasic_BannedAbstractVirtualMemberAlsoBansOverrides_MiddleLevelIsBannedAsync() + => VerifyBasicAnalyzerAsync(""" + Imports System - Public Overridable Sub Method2() - End Sub + Namespace N + Public MustInherit Class C1 + Public MustOverride Sub Method1() + Public MustOverride Property Property1 As Integer - Public Overridable Property Property2 As Integer - End Class + Public Overridable Sub Method2() + End Sub - Public Class C2 - Inherits C1 + Public Overridable Property Property2 As Integer + End Class - Public Overrides Sub Method1() - End Sub + Public Class C2 + Inherits C1 - Public Overrides Property Property1 As Integer + Public Overrides Sub Method1() + End Sub - Public Overrides Sub Method2() - MyBase.Method2() - End Sub + Public Overrides Property Property1 As Integer - Public Overrides Property Property2 As Integer + Public Overrides Sub Method2() + MyBase.Method2() + End Sub - Private Sub M1() - {|RS0030:Method1()|} + Public Overrides Property Property2 As Integer - If {|RS0030:Property1|} = 42 Then - End If + Private Sub M1() + {|RS0030:Method1()|} - {|RS0030:Method2()|} + If {|RS0030:Property1|} = 42 Then + End If - If {|RS0030:Property2|} = 42 Then - End If - End Sub - End Class + {|RS0030:Method2()|} - Public Class C3 - Inherits C2 + If {|RS0030:Property2|} = 42 Then + End If + End Sub + End Class - Public Overrides Sub Method1() - {|RS0030:MyBase.Method1()|} - End Sub + Public Class C3 + Inherits C2 - Public Overrides Property Property1 As Integer + Public Overrides Sub Method1() + {|RS0030:MyBase.Method1()|} + End Sub - Public Overrides Sub Method2() - {|RS0030:MyBase.Method2()|} - End Sub + Public Overrides Property Property1 As Integer - Public Overrides Property Property2 As Integer + Public Overrides Sub Method2() + {|RS0030:MyBase.Method2()|} + End Sub - Private Sub M2() - {|RS0030:Method1()|} + Public Overrides Property Property2 As Integer - If {|RS0030:Property1|} = 42 Then - End If + Private Sub M2() + {|RS0030:Method1()|} - {|RS0030:Method2()|} + If {|RS0030:Property1|} = 42 Then + End If - If {|RS0030:Property2|} = 42 Then - End If - End Sub - End Class -End Namespace -"; + {|RS0030:Method2()|} - var bannedText = @"M:N.C2.Method1 -P:N.C2.Property1 -E:N.C2.Event1 -M:N.C2.Method2 -P:N.C2.Property2 -E:N.C2.Event2"; - - await VerifyBasicAnalyzerAsync(source, bannedText); - } + If {|RS0030:Property2|} = 42 Then + End If + End Sub + End Class + End Namespace + """, """ + M:N.C2.Method1 + P:N.C2.Property1 + E:N.C2.Event1 + M:N.C2.Method2 + P:N.C2.Property2 + E:N.C2.Event2 + """); [Fact, WorkItem(3295, "https://github.com/dotnet/roslyn-analyzers/issues/3295")] - public async Task VisualBasic_BannedAbstractVirtualMemberAlsoBansOverrides_LeafLevelIsBannedAsync() - { - var source = @" -Imports System + public Task VisualBasic_BannedAbstractVirtualMemberAlsoBansOverrides_LeafLevelIsBannedAsync() + => VerifyBasicAnalyzerAsync(""" + Imports System -Namespace N - Public MustInherit Class C1 - Public MustOverride Sub Method1() - Public MustOverride Property Property1 As Integer + Namespace N + Public MustInherit Class C1 + Public MustOverride Sub Method1() + Public MustOverride Property Property1 As Integer - Public Overridable Sub Method2() - End Sub + Public Overridable Sub Method2() + End Sub - Public Overridable Property Property2 As Integer - End Class + Public Overridable Property Property2 As Integer + End Class - Public Class C2 - Inherits C1 + Public Class C2 + Inherits C1 - Public Overrides Sub Method1() - End Sub + Public Overrides Sub Method1() + End Sub - Public Overrides Property Property1 As Integer + Public Overrides Property Property1 As Integer - Public Overrides Sub Method2() - MyBase.Method2() - End Sub + Public Overrides Sub Method2() + MyBase.Method2() + End Sub - Public Overrides Property Property2 As Integer + Public Overrides Property Property2 As Integer - Private Sub M1() - Method1() + Private Sub M1() + Method1() - If Property1 = 42 Then - End If + If Property1 = 42 Then + End If - Method2() + Method2() - If Property2 = 42 Then - End If - End Sub - End Class + If Property2 = 42 Then + End If + End Sub + End Class - Public Class C3 - Inherits C2 + Public Class C3 + Inherits C2 - Public Overrides Sub Method1() - MyBase.Method1() - End Sub + Public Overrides Sub Method1() + MyBase.Method1() + End Sub - Public Overrides Property Property1 As Integer + Public Overrides Property Property1 As Integer - Public Overrides Sub Method2() - MyBase.Method2() - End Sub + Public Overrides Sub Method2() + MyBase.Method2() + End Sub - Public Overrides Property Property2 As Integer + Public Overrides Property Property2 As Integer - Private Sub M2() - {|RS0030:Method1()|} + Private Sub M2() + {|RS0030:Method1()|} - If {|RS0030:Property1|} = 42 Then - End If + If {|RS0030:Property1|} = 42 Then + End If - {|RS0030:Method2()|} + {|RS0030:Method2()|} - If {|RS0030:Property2|} = 42 Then - End If - End Sub - End Class -End Namespace -"; - - var bannedText = @"M:N.C3.Method1 -P:N.C3.Property1 -E:N.C3.Event1 -M:N.C3.Method2 -P:N.C3.Property2 -E:N.C3.Event2"; - - await VerifyBasicAnalyzerAsync(source, bannedText); - } + If {|RS0030:Property2|} = 42 Then + End If + End Sub + End Class + End Namespace + """, """ + M:N.C3.Method1 + P:N.C3.Property1 + E:N.C3.Event1 + M:N.C3.Method2 + P:N.C3.Property2 + E:N.C3.Event2 + """); #endregion } diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.BannedApiAnalyzers.vbproj b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.BannedApiAnalyzers.vbproj index cbc1784d1a0f2..8b8821b877f67 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.BannedApiAnalyzers.vbproj +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.BannedApiAnalyzers.vbproj @@ -2,12 +2,11 @@ netstandard2.0 - $(MicrosoftCodeAnalysisVersionForBannedApiAnalyzers) - - + + diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.CSharp/Microsoft.CodeAnalysis.ResxSourceGenerator.CSharp.csproj b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.CSharp/Microsoft.CodeAnalysis.ResxSourceGenerator.CSharp.csproj index 078117badf8b2..93aef8f260982 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.CSharp/Microsoft.CodeAnalysis.ResxSourceGenerator.CSharp.csproj +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.CSharp/Microsoft.CodeAnalysis.ResxSourceGenerator.CSharp.csproj @@ -7,13 +7,22 @@ *$(MSBuildProjectFile)* - $(MicrosoftCodeAnalysisVersionForResxSourceGenerators) - - - - + + + + + + + + + + + + + + diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests.csproj b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests.csproj index d8a57efd760f2..1a1d829966613 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests.csproj +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests.csproj @@ -5,17 +5,19 @@ true true - $(MicrosoftCodeAnalysisVersionForResxSourceGenerators) + true - - - - - - + + + + + + + + diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_AsConstantsCSharpAsync_False/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_AsConstantsCSharpAsync_False/Resources.Designer.cs index c1c925afa5ad4..2fac9e79a9114 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_AsConstantsCSharpAsync_False/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_AsConstantsCSharpAsync_False/Resources.Designer.cs @@ -18,4 +18,4 @@ internal static partial class Resources public static string @Name => GetResourceString("Name")!; } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_AsConstantsCSharpAsync_True/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_AsConstantsCSharpAsync_True/Resources.Designer.cs index c7688ac134b46..f73138317b94e 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_AsConstantsCSharpAsync_True/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_AsConstantsCSharpAsync_True/Resources.Designer.cs @@ -18,4 +18,4 @@ internal static partial class Resources public const string @Name = "Name"; } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_AsConstantsVisualBasicAsync_False/Resources.Designer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_AsConstantsVisualBasicAsync_False/Resources.Designer.vb index 7e5e0abe937db..1881b74aa2fe0 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_AsConstantsVisualBasicAsync_False/Resources.Designer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_AsConstantsVisualBasicAsync_False/Resources.Designer.vb @@ -30,4 +30,4 @@ Namespace Global.TestProject End Property End Class -End Namespace +End Namespace \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_AsConstantsVisualBasicAsync_True/Resources.Designer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_AsConstantsVisualBasicAsync_True/Resources.Designer.vb index 3a7ff2a36a27a..51007fe274133 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_AsConstantsVisualBasicAsync_True/Resources.Designer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_AsConstantsVisualBasicAsync_True/Resources.Designer.vb @@ -26,4 +26,4 @@ Namespace Global.TestProject Public Const [Name] As String = "Name" End Class -End Namespace +End Namespace \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_ClassNameCSharpAsync/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_ClassNameCSharpAsync/Resources.Designer.cs index c1c925afa5ad4..2fac9e79a9114 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_ClassNameCSharpAsync/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_ClassNameCSharpAsync/Resources.Designer.cs @@ -18,4 +18,4 @@ internal static partial class Resources public static string @Name => GetResourceString("Name")!; } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_ClassNameCSharpAsync_NS/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_ClassNameCSharpAsync_NS/Resources.Designer.cs index 88c522856854a..7e9c3d3186964 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_ClassNameCSharpAsync_NS/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_ClassNameCSharpAsync_NS/Resources.Designer.cs @@ -20,4 +20,3 @@ internal static partial class NS public static string @Name => GetResourceString("Name")!; } - diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_ClassNameCSharpAsync_NS1.NS2/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_ClassNameCSharpAsync_NS1.NS2/Resources.Designer.cs index 4ded4b004c555..0b14582ae4dab 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_ClassNameCSharpAsync_NS1.NS2/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_ClassNameCSharpAsync_NS1.NS2/Resources.Designer.cs @@ -21,4 +21,4 @@ internal static partial class NS2 public static string @Name => GetResourceString("Name")!; } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_ClassNameVisualBasicAsync/Resources.Designer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_ClassNameVisualBasicAsync/Resources.Designer.vb index 7e5e0abe937db..1881b74aa2fe0 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_ClassNameVisualBasicAsync/Resources.Designer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_ClassNameVisualBasicAsync/Resources.Designer.vb @@ -30,4 +30,4 @@ Namespace Global.TestProject End Property End Class -End Namespace +End Namespace \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_ClassNameVisualBasicAsync_NS/Resources.Designer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_ClassNameVisualBasicAsync_NS/Resources.Designer.vb index 84a8ca15a650d..99fb93d506625 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_ClassNameVisualBasicAsync_NS/Resources.Designer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_ClassNameVisualBasicAsync_NS/Resources.Designer.vb @@ -33,4 +33,3 @@ Friend Partial Class NS End Property End Class - diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_ClassNameVisualBasicAsync_NS1.NS2/Resources.Designer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_ClassNameVisualBasicAsync_NS1.NS2/Resources.Designer.vb index 866c481c2e8f9..aec967ea7e6c7 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_ClassNameVisualBasicAsync_NS1.NS2/Resources.Designer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_ClassNameVisualBasicAsync_NS1.NS2/Resources.Designer.vb @@ -33,4 +33,4 @@ Namespace Global.NS1 End Property End Class -End Namespace +End Namespace \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_DefaultCSharpAsync_CSharp5/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_DefaultCSharpAsync_CSharp5/Resources.Designer.cs index ff7d2796857ea..1add95c012006 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_DefaultCSharpAsync_CSharp5/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_DefaultCSharpAsync_CSharp5/Resources.Designer.cs @@ -18,4 +18,4 @@ internal static partial class Resources public static string @Name => GetResourceString("Name"); } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_DefaultCSharpAsync_CSharp6/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_DefaultCSharpAsync_CSharp6/Resources.Designer.cs index ff7d2796857ea..1add95c012006 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_DefaultCSharpAsync_CSharp6/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_DefaultCSharpAsync_CSharp6/Resources.Designer.cs @@ -18,4 +18,4 @@ internal static partial class Resources public static string @Name => GetResourceString("Name"); } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_DefaultCSharpAsync_CSharp7/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_DefaultCSharpAsync_CSharp7/Resources.Designer.cs index ff7d2796857ea..1add95c012006 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_DefaultCSharpAsync_CSharp7/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_DefaultCSharpAsync_CSharp7/Resources.Designer.cs @@ -18,4 +18,4 @@ internal static partial class Resources public static string @Name => GetResourceString("Name"); } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_DefaultCSharpAsync_CSharp8/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_DefaultCSharpAsync_CSharp8/Resources.Designer.cs index c1c925afa5ad4..2fac9e79a9114 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_DefaultCSharpAsync_CSharp8/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_DefaultCSharpAsync_CSharp8/Resources.Designer.cs @@ -18,4 +18,4 @@ internal static partial class Resources public static string @Name => GetResourceString("Name")!; } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_DefaultCSharpAsync_CSharp9/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_DefaultCSharpAsync_CSharp9/Resources.Designer.cs index c1c925afa5ad4..2fac9e79a9114 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_DefaultCSharpAsync_CSharp9/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_DefaultCSharpAsync_CSharp9/Resources.Designer.cs @@ -18,4 +18,4 @@ internal static partial class Resources public static string @Name => GetResourceString("Name")!; } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_DefaultVisualBasicAsync/Resources.Designer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_DefaultVisualBasicAsync/Resources.Designer.vb index 7e5e0abe937db..1881b74aa2fe0 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_DefaultVisualBasicAsync/Resources.Designer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_DefaultVisualBasicAsync/Resources.Designer.vb @@ -30,4 +30,4 @@ Namespace Global.TestProject End Property End Class -End Namespace +End Namespace \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsCSharpAsync_0_False/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsCSharpAsync_0_False/Resources.Designer.cs index 5d380b3db1666..a3bf560ad794e 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsCSharpAsync_0_False/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsCSharpAsync_0_False/Resources.Designer.cs @@ -18,4 +18,4 @@ internal static partial class Resources public static string @Name => GetResourceString("Name")!; } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsCSharpAsync_0_True/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsCSharpAsync_0_True/Resources.Designer.cs index b3919a15c4f5b..12087eef572f4 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsCSharpAsync_0_True/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsCSharpAsync_0_True/Resources.Designer.cs @@ -14,7 +14,6 @@ internal static partial class Resources [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] [return: global::System.Diagnostics.CodeAnalysis.NotNullIfNotNull("defaultValue")] internal static string? GetResourceString(string resourceKey, string? defaultValue = null) => ResourceManager.GetString(resourceKey, Culture) ?? defaultValue; - private static string GetResourceString(string resourceKey, string[]? formatterNames) { var value = GetResourceString(resourceKey) ?? ""; @@ -27,7 +26,6 @@ private static string GetResourceString(string resourceKey, string[]? formatterN } return value; } - /// value {0} public static string @Name => GetResourceString("Name")!; /// value {0} @@ -36,4 +34,4 @@ internal static string FormatName(object? p0) } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsCSharpAsync_replacement_False/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsCSharpAsync_replacement_False/Resources.Designer.cs index 4feef75d44d61..590417cc80362 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsCSharpAsync_replacement_False/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsCSharpAsync_replacement_False/Resources.Designer.cs @@ -18,4 +18,4 @@ internal static partial class Resources public static string @Name => GetResourceString("Name")!; } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsCSharpAsync_replacement_True/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsCSharpAsync_replacement_True/Resources.Designer.cs index fa77240ec63c1..06520b226cda0 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsCSharpAsync_replacement_True/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsCSharpAsync_replacement_True/Resources.Designer.cs @@ -14,7 +14,6 @@ internal static partial class Resources [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] [return: global::System.Diagnostics.CodeAnalysis.NotNullIfNotNull("defaultValue")] internal static string? GetResourceString(string resourceKey, string? defaultValue = null) => ResourceManager.GetString(resourceKey, Culture) ?? defaultValue; - private static string GetResourceString(string resourceKey, string[]? formatterNames) { var value = GetResourceString(resourceKey) ?? ""; @@ -27,7 +26,6 @@ private static string GetResourceString(string resourceKey, string[]? formatterN } return value; } - /// value {replacement} public static string @Name => GetResourceString("Name")!; /// value {replacement} @@ -36,4 +34,4 @@ internal static string FormatName(object? replacement) } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsCSharpAsync_x_False/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsCSharpAsync_x_False/Resources.Designer.cs index 19b20ba8116e2..2587512dce418 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsCSharpAsync_x_False/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsCSharpAsync_x_False/Resources.Designer.cs @@ -18,4 +18,4 @@ internal static partial class Resources public static string @Name => GetResourceString("Name")!; } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsCSharpAsync_x_True/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsCSharpAsync_x_True/Resources.Designer.cs index fe057e9cbfcb4..a7f8f5585ef49 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsCSharpAsync_x_True/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsCSharpAsync_x_True/Resources.Designer.cs @@ -14,7 +14,6 @@ internal static partial class Resources [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] [return: global::System.Diagnostics.CodeAnalysis.NotNullIfNotNull("defaultValue")] internal static string? GetResourceString(string resourceKey, string? defaultValue = null) => ResourceManager.GetString(resourceKey, Culture) ?? defaultValue; - private static string GetResourceString(string resourceKey, string[]? formatterNames) { var value = GetResourceString(resourceKey) ?? ""; @@ -27,7 +26,6 @@ private static string GetResourceString(string resourceKey, string[]? formatterN } return value; } - /// value {x} public static string @Name => GetResourceString("Name")!; /// value {x} @@ -36,4 +34,4 @@ internal static string FormatName(object? x) } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsVisualBasicAsync_False/Resources.Designer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsVisualBasicAsync_False/Resources.Designer.vb index 7e5e0abe937db..1881b74aa2fe0 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsVisualBasicAsync_False/Resources.Designer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_EmitFormatMethodsVisualBasicAsync_False/Resources.Designer.vb @@ -30,4 +30,4 @@ Namespace Global.TestProject End Property End Class -End Namespace +End Namespace \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_IncludeDefaultValuesCSharpAsync_False/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_IncludeDefaultValuesCSharpAsync_False/Resources.Designer.cs index c1c925afa5ad4..2fac9e79a9114 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_IncludeDefaultValuesCSharpAsync_False/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_IncludeDefaultValuesCSharpAsync_False/Resources.Designer.cs @@ -18,4 +18,4 @@ internal static partial class Resources public static string @Name => GetResourceString("Name")!; } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_IncludeDefaultValuesCSharpAsync_True/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_IncludeDefaultValuesCSharpAsync_True/Resources.Designer.cs index 1473a8f809be9..63a7569d3f4fe 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_IncludeDefaultValuesCSharpAsync_True/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_IncludeDefaultValuesCSharpAsync_True/Resources.Designer.cs @@ -18,4 +18,4 @@ internal static partial class Resources public static string @Name => GetResourceString("Name", @"value"); } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_IncludeDefaultValuesVisualBasicAsync_False/Resources.Designer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_IncludeDefaultValuesVisualBasicAsync_False/Resources.Designer.vb index 7e5e0abe937db..1881b74aa2fe0 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_IncludeDefaultValuesVisualBasicAsync_False/Resources.Designer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_IncludeDefaultValuesVisualBasicAsync_False/Resources.Designer.vb @@ -30,4 +30,4 @@ Namespace Global.TestProject End Property End Class -End Namespace +End Namespace \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_IncludeDefaultValuesVisualBasicAsync_True/Resources.Designer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_IncludeDefaultValuesVisualBasicAsync_True/Resources.Designer.vb index a7d121e8de99e..efd9799c93bd5 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_IncludeDefaultValuesVisualBasicAsync_True/Resources.Designer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_IncludeDefaultValuesVisualBasicAsync_True/Resources.Designer.vb @@ -30,4 +30,4 @@ Namespace Global.TestProject End Property End Class -End Namespace +End Namespace \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_NoWarnsCSharpAsync/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_NoWarnsCSharpAsync/Resources.Designer.cs index c1c925afa5ad4..2fac9e79a9114 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_NoWarnsCSharpAsync/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_NoWarnsCSharpAsync/Resources.Designer.cs @@ -18,4 +18,4 @@ internal static partial class Resources public static string @Name => GetResourceString("Name")!; } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_NoWarnsCSharpAsync_CS1591/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_NoWarnsCSharpAsync_CS1591/Resources.Designer.cs index 2de335ef9122b..18d0d80d62846 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_NoWarnsCSharpAsync_CS1591/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_NoWarnsCSharpAsync_CS1591/Resources.Designer.cs @@ -22,4 +22,4 @@ internal static partial class Resources } } -#pragma warning restore CS1591 +#pragma warning restore CS1591 \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_NoWarnsCSharpAsync_CS1591_IDE0010/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_NoWarnsCSharpAsync_CS1591_IDE0010/Resources.Designer.cs index 62cee7c3c5d04..0d2a9ee2c9c9b 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_NoWarnsCSharpAsync_CS1591_IDE0010/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_NoWarnsCSharpAsync_CS1591_IDE0010/Resources.Designer.cs @@ -22,4 +22,4 @@ internal static partial class Resources } } -#pragma warning restore CS1591, IDE0010 +#pragma warning restore CS1591, IDE0010 \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_NoWarnsVisualBasicAsync/Resources.Designer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_NoWarnsVisualBasicAsync/Resources.Designer.vb index 7e5e0abe937db..1881b74aa2fe0 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_NoWarnsVisualBasicAsync/Resources.Designer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_NoWarnsVisualBasicAsync/Resources.Designer.vb @@ -30,4 +30,4 @@ Namespace Global.TestProject End Property End Class -End Namespace +End Namespace \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_NoWarnsVisualBasicAsync_CS1591/Resources.Designer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_NoWarnsVisualBasicAsync_CS1591/Resources.Designer.vb index 17132d5e6825b..d6bc23deb51b4 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_NoWarnsVisualBasicAsync_CS1591/Resources.Designer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_NoWarnsVisualBasicAsync_CS1591/Resources.Designer.vb @@ -34,4 +34,4 @@ Namespace Global.TestProject End Class End Namespace -#Enable Warning CS1591 +#Enable Warning CS1591 \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_NoWarnsVisualBasicAsync_CS1591_IDE0010/Resources.Designer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_NoWarnsVisualBasicAsync_CS1591_IDE0010/Resources.Designer.vb index 72d82353a1840..13a1478426604 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_NoWarnsVisualBasicAsync_CS1591_IDE0010/Resources.Designer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_NoWarnsVisualBasicAsync_CS1591_IDE0010/Resources.Designer.vb @@ -34,4 +34,4 @@ Namespace Global.TestProject End Class End Namespace -#Enable Warning CS1591, IDE0010 +#Enable Warning CS1591, IDE0010 \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_OmitGetResourceStringCSharpAsync_False/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_OmitGetResourceStringCSharpAsync_False/Resources.Designer.cs index c1c925afa5ad4..2fac9e79a9114 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_OmitGetResourceStringCSharpAsync_False/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_OmitGetResourceStringCSharpAsync_False/Resources.Designer.cs @@ -18,4 +18,4 @@ internal static partial class Resources public static string @Name => GetResourceString("Name")!; } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_OmitGetResourceStringCSharpAsync_True/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_OmitGetResourceStringCSharpAsync_True/Resources.Designer.cs index 82e188c979458..4dcdb8ee2d734 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_OmitGetResourceStringCSharpAsync_True/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_OmitGetResourceStringCSharpAsync_True/Resources.Designer.cs @@ -15,4 +15,4 @@ internal static partial class Resources public static string @Name => GetResourceString("Name")!; } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_OmitGetResourceStringVisualBasicAsync_False/Resources.Designer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_OmitGetResourceStringVisualBasicAsync_False/Resources.Designer.vb index 7e5e0abe937db..1881b74aa2fe0 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_OmitGetResourceStringVisualBasicAsync_False/Resources.Designer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_OmitGetResourceStringVisualBasicAsync_False/Resources.Designer.vb @@ -30,4 +30,4 @@ Namespace Global.TestProject End Property End Class -End Namespace +End Namespace \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_OmitGetResourceStringVisualBasicAsync_True/Resources.Designer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_OmitGetResourceStringVisualBasicAsync_True/Resources.Designer.vb index 2a310c4b2fc5f..e09b6fa5270ca 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_OmitGetResourceStringVisualBasicAsync_True/Resources.Designer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_OmitGetResourceStringVisualBasicAsync_True/Resources.Designer.vb @@ -26,4 +26,4 @@ Namespace Global.TestProject End Property End Class -End Namespace +End Namespace \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_PublicCSharpAsync_False/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_PublicCSharpAsync_False/Resources.Designer.cs index c1c925afa5ad4..2fac9e79a9114 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_PublicCSharpAsync_False/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_PublicCSharpAsync_False/Resources.Designer.cs @@ -18,4 +18,4 @@ internal static partial class Resources public static string @Name => GetResourceString("Name")!; } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_PublicCSharpAsync_True/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_PublicCSharpAsync_True/Resources.Designer.cs index 5aec8c10768e0..fa8c5ef10b58a 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_PublicCSharpAsync_True/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_PublicCSharpAsync_True/Resources.Designer.cs @@ -18,4 +18,4 @@ public static partial class Resources public static string @Name => GetResourceString("Name")!; } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_PublicVisualBasicAsync_False/Resources.Designer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_PublicVisualBasicAsync_False/Resources.Designer.vb index 7e5e0abe937db..1881b74aa2fe0 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_PublicVisualBasicAsync_False/Resources.Designer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_PublicVisualBasicAsync_False/Resources.Designer.vb @@ -30,4 +30,4 @@ Namespace Global.TestProject End Property End Class -End Namespace +End Namespace \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_PublicVisualBasicAsync_True/Resources.Designer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_PublicVisualBasicAsync_True/Resources.Designer.vb index 64be47f98a099..93940b29acdd9 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_PublicVisualBasicAsync_True/Resources.Designer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_PublicVisualBasicAsync_True/Resources.Designer.vb @@ -30,4 +30,4 @@ Namespace Global.TestProject End Property End Class -End Namespace +End Namespace \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RelativeDirCSharpAsync/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RelativeDirCSharpAsync/Resources.Designer.cs index c1c925afa5ad4..2fac9e79a9114 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RelativeDirCSharpAsync/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RelativeDirCSharpAsync/Resources.Designer.cs @@ -18,4 +18,4 @@ internal static partial class Resources public static string @Name => GetResourceString("Name")!; } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RelativeDirCSharpAsync_NS/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RelativeDirCSharpAsync_NS/Resources.Designer.cs index 1f3c879f30782..a6af5bd3745d3 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RelativeDirCSharpAsync_NS/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RelativeDirCSharpAsync_NS/Resources.Designer.cs @@ -18,4 +18,4 @@ internal static partial class NSResources public static string @Name => GetResourceString("Name")!; } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RelativeDirCSharpAsync_NS1.NS2/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RelativeDirCSharpAsync_NS1.NS2/Resources.Designer.cs index f32431e787727..c1d9e6b13138b 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RelativeDirCSharpAsync_NS1.NS2/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RelativeDirCSharpAsync_NS1.NS2/Resources.Designer.cs @@ -18,4 +18,4 @@ internal static partial class NS2Resources public static string @Name => GetResourceString("Name")!; } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RelativeDirVisualBasicAsync/Resources.Designer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RelativeDirVisualBasicAsync/Resources.Designer.vb index 7e5e0abe937db..1881b74aa2fe0 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RelativeDirVisualBasicAsync/Resources.Designer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RelativeDirVisualBasicAsync/Resources.Designer.vb @@ -30,4 +30,4 @@ Namespace Global.TestProject End Property End Class -End Namespace +End Namespace \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RelativeDirVisualBasicAsync_NS/Resources.Designer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RelativeDirVisualBasicAsync_NS/Resources.Designer.vb index 8bd90c0fae28f..847700ea28f25 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RelativeDirVisualBasicAsync_NS/Resources.Designer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RelativeDirVisualBasicAsync_NS/Resources.Designer.vb @@ -30,4 +30,4 @@ Namespace Global.TestProject End Property End Class -End Namespace +End Namespace \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RelativeDirVisualBasicAsync_NS1.NS2/Resources.Designer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RelativeDirVisualBasicAsync_NS1.NS2/Resources.Designer.vb index c0a22ef9916df..af17bb8acc0c7 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RelativeDirVisualBasicAsync_NS1.NS2/Resources.Designer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RelativeDirVisualBasicAsync_NS1.NS2/Resources.Designer.vb @@ -30,4 +30,4 @@ Namespace Global.TestProject.NS1 End Property End Class -End Namespace +End Namespace \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RootNamespaceCSharpAsync/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RootNamespaceCSharpAsync/Resources.Designer.cs index f82cd00193064..030e93a384552 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RootNamespaceCSharpAsync/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RootNamespaceCSharpAsync/Resources.Designer.cs @@ -17,4 +17,3 @@ internal static partial class Resources public static string @Name => GetResourceString("Name")!; } - diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RootNamespaceCSharpAsync_NS/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RootNamespaceCSharpAsync_NS/Resources.Designer.cs index e92f3ef2aded2..a843b814f1f48 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RootNamespaceCSharpAsync_NS/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RootNamespaceCSharpAsync_NS/Resources.Designer.cs @@ -18,4 +18,4 @@ internal static partial class Resources public static string @Name => GetResourceString("Name")!; } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RootNamespaceCSharpAsync_NS1.NS2/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RootNamespaceCSharpAsync_NS1.NS2/Resources.Designer.cs index 9bdce5dfefde8..523f57c6448d3 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RootNamespaceCSharpAsync_NS1.NS2/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RootNamespaceCSharpAsync_NS1.NS2/Resources.Designer.cs @@ -18,4 +18,4 @@ internal static partial class Resources public static string @Name => GetResourceString("Name")!; } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RootNamespaceVisualBasicAsync/Resources.Designer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RootNamespaceVisualBasicAsync/Resources.Designer.vb index 0b157c5101818..9359a0d0fa1d1 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RootNamespaceVisualBasicAsync/Resources.Designer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RootNamespaceVisualBasicAsync/Resources.Designer.vb @@ -30,4 +30,3 @@ Friend Partial Class Resources End Property End Class - diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RootNamespaceVisualBasicAsync_NS/Resources.Designer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RootNamespaceVisualBasicAsync_NS/Resources.Designer.vb index 1d7d203bc1fb3..ca6eedd3ab0b7 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RootNamespaceVisualBasicAsync_NS/Resources.Designer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RootNamespaceVisualBasicAsync_NS/Resources.Designer.vb @@ -30,4 +30,4 @@ Namespace Global.NS End Property End Class -End Namespace +End Namespace \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RootNamespaceVisualBasicAsync_NS1.NS2/Resources.Designer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RootNamespaceVisualBasicAsync_NS1.NS2/Resources.Designer.vb index 25ea9cf6a93f6..8e004bd0a8169 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RootNamespaceVisualBasicAsync_NS1.NS2/Resources.Designer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/SingleString_RootNamespaceVisualBasicAsync_NS1.NS2/Resources.Designer.vb @@ -30,4 +30,4 @@ Namespace Global.NS1.NS2 End Property End Class -End Namespace +End Namespace \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/TwoResourcesSameName_DefaultCSharpAsync/Resources.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/TwoResourcesSameName_DefaultCSharpAsync/Resources.Designer.cs index ec47ea64240a4..6074150a4e43a 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/TwoResourcesSameName_DefaultCSharpAsync/Resources.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/TwoResourcesSameName_DefaultCSharpAsync/Resources.Designer.cs @@ -18,4 +18,4 @@ internal static partial class Resources public static string @Name => GetResourceString("Name")!; } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/TwoResourcesSameName_DefaultCSharpAsync/Resources0.Designer.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/TwoResourcesSameName_DefaultCSharpAsync/Resources0.Designer.cs index 26e3d38af1550..35ec698372f03 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/TwoResourcesSameName_DefaultCSharpAsync/Resources0.Designer.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/TwoResourcesSameName_DefaultCSharpAsync/Resources0.Designer.cs @@ -18,4 +18,4 @@ internal static partial class Resources public static string @Name => GetResourceString("Name")!; } -} +} \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/TwoResourcesSameName_DefaultVisualBasicAsync/Resources.Designer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/TwoResourcesSameName_DefaultVisualBasicAsync/Resources.Designer.vb index dd7fa8fdeb5ee..24298d6b5a7c9 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/TwoResourcesSameName_DefaultVisualBasicAsync/Resources.Designer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/TwoResourcesSameName_DefaultVisualBasicAsync/Resources.Designer.vb @@ -30,4 +30,4 @@ Namespace Global.TestProject.First End Property End Class -End Namespace +End Namespace \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/TwoResourcesSameName_DefaultVisualBasicAsync/Resources0.Designer.vb b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/TwoResourcesSameName_DefaultVisualBasicAsync/Resources0.Designer.vb index b4a921a70e1f1..2bc55392ba0ca 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/TwoResourcesSameName_DefaultVisualBasicAsync/Resources0.Designer.vb +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Resources/TwoResourcesSameName_DefaultVisualBasicAsync/Resources0.Designer.vb @@ -30,4 +30,4 @@ Namespace Global.TestProject.Second End Property End Class -End Namespace +End Namespace \ No newline at end of file diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/ResxGeneratorTests.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/ResxGeneratorTests.cs index ff378459bdf80..55bea2fa656a9 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/ResxGeneratorTests.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/ResxGeneratorTests.cs @@ -5,811 +5,860 @@ using System.Threading.Tasks; using Xunit; using CSharpLanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion; -using VerifyCS = Microsoft.CodeAnalysis.ResxSourceGenerator.Test.CSharpSourceGeneratorVerifier; -using VerifyVB = Microsoft.CodeAnalysis.ResxSourceGenerator.Test.VisualBasicSourceGeneratorVerifier; -namespace Microsoft.CodeAnalysis.ResxSourceGenerator.Test +namespace Microsoft.CodeAnalysis.ResxSourceGenerator.Test; + +using VerifyCS = CSharpSourceGeneratorVerifier; +using VerifyVB = VisualBasicSourceGeneratorVerifier; + +public sealed class ResxGeneratorTests { - public class ResxGeneratorTests + private const string ResxHeader = """ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + """; + private const string ResxFooter = """ + + """; + + [Theory] + [InlineData(CSharpLanguageVersion.CSharp5, Skip = "Expression-bodied members are not supported in C# 5")] + [InlineData(CSharpLanguageVersion.CSharp6)] + [InlineData(CSharpLanguageVersion.CSharp7)] + [InlineData(CSharpLanguageVersion.CSharp8)] + [InlineData(CSharpLanguageVersion.CSharp9)] + public async Task SingleString_DefaultCSharpAsync(CSharpLanguageVersion languageVersion) { - private const string ResxHeader = @" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 - -"; - private const string ResxFooter = @" -"; - - [Theory] - [InlineData(CSharpLanguageVersion.CSharp5, Skip = "Expression-bodied members are not supported in C# 5")] - [InlineData(CSharpLanguageVersion.CSharp6)] - [InlineData(CSharpLanguageVersion.CSharp7)] - [InlineData(CSharpLanguageVersion.CSharp8)] - [InlineData(CSharpLanguageVersion.CSharp9)] - public async Task SingleString_DefaultCSharpAsync(CSharpLanguageVersion languageVersion) + var code = ResxHeader + + """ + + value + comment + + """ + + ResxFooter; + + await new VerifyCS.Test(identifier: languageVersion.ToString()) { - var code = ResxHeader - + @" - value - comment - " - + ResxFooter; - - await new VerifyCS.Test(identifier: languageVersion.ToString()) + LanguageVersion = languageVersion, + TestState = { - LanguageVersion = languageVersion, - TestState = - { - Sources = { "" }, - AdditionalFiles = { ("/0/Resources.resx", code) }, - }, - }.AddGeneratedSources().RunAsync(); - } + Sources = { "" }, + AdditionalFiles = { ("/0/Resources.resx", code) }, + }, + }.AddGeneratedSources().RunAsync(); + } - [Fact] - public async Task TwoResourcesSameName_DefaultCSharpAsync() + [Fact] + public async Task TwoResourcesSameName_DefaultCSharpAsync() + { + var code = ResxHeader + + """ + + value + comment + + """ + + ResxFooter; + + await new VerifyCS.Test() { - var code = ResxHeader - + @" - value - comment - " - + ResxFooter; - - await new VerifyCS.Test() + TestState = { - TestState = + Sources = { "" }, + AdditionalFiles = { - Sources = { "" }, - AdditionalFiles = - { - ("/0/First/Resources.resx", code), - ("/0/Second/Resources.resx", code), - }, - AnalyzerConfigFiles = - { - ("/.globalconfig", $@" -is_global = true - -build_property.RootNamespace = TestProject - -[/0/First/Resources.resx] -build_metadata.AdditionalFiles.RelativeDir = First/ - -[/0/Second/Resources.resx] -build_metadata.AdditionalFiles.RelativeDir = Second/ -"), - }, + ("/0/First/Resources.resx", code), + ("/0/Second/Resources.resx", code), }, - }.AddGeneratedSources().RunAsync(); - } - - [Fact] - public async Task TwoResourcesSameName_DefaultVisualBasicAsync() - { - var code = ResxHeader - + @" - value - comment - " - + ResxFooter; - - await new VerifyVB.Test() - { - TestState = + AnalyzerConfigFiles = { - Sources = { "" }, - AdditionalFiles = - { - ("/0/First/Resources.resx", code), - ("/0/Second/Resources.resx", code), - }, - AnalyzerConfigFiles = - { - ("/.globalconfig", $@" -is_global = true - -build_property.RootNamespace = TestProject - -[/0/First/Resources.resx] -build_metadata.AdditionalFiles.RelativeDir = First/ - -[/0/Second/Resources.resx] -build_metadata.AdditionalFiles.RelativeDir = Second/ -"), - }, + ("/.globalconfig", $""" + is_global = true + + build_property.RootNamespace = TestProject + + [/0/First/Resources.resx] + build_metadata.AdditionalFiles.RelativeDir = First/ + + [/0/Second/Resources.resx] + build_metadata.AdditionalFiles.RelativeDir = Second/ + """), }, - }.AddGeneratedSources().RunAsync(); - } + }, + }.AddGeneratedSources().RunAsync(); + } - [Fact] - public async Task SingleString_DefaultVisualBasicAsync() + [Fact] + public async Task TwoResourcesSameName_DefaultVisualBasicAsync() + { + var code = ResxHeader + + """ + + value + comment + + """ + + ResxFooter; + + await new VerifyVB.Test() { - var code = ResxHeader - + @" - value - comment - " - + ResxFooter; - - await new VerifyVB.Test + TestState = { - TestState = + Sources = { "" }, + AdditionalFiles = { - AdditionalFiles = { ("/0/Resources.resx", code) }, + ("/0/First/Resources.resx", code), + ("/0/Second/Resources.resx", code), }, - }.AddGeneratedSources().RunAsync(); - } + AnalyzerConfigFiles = + { + ("/.globalconfig", $""" + is_global = true + + build_property.RootNamespace = TestProject + + [/0/First/Resources.resx] + build_metadata.AdditionalFiles.RelativeDir = First/ + + [/0/Second/Resources.resx] + build_metadata.AdditionalFiles.RelativeDir = Second/ + """), + }, + }, + }.AddGeneratedSources().RunAsync(); + } - [Fact] - public async Task SingleString_DisableCodeGenAsync() + [Fact] + public async Task SingleString_DefaultVisualBasicAsync() + { + var code = ResxHeader + + """ + + value + comment + + """ + + ResxFooter; + + await new VerifyVB.Test { - var code = ResxHeader - + @" - value - comment - " - + ResxFooter; - - await new VerifyCS.Test + TestState = { - TestState = - { - Sources = { "" }, - AdditionalFiles = { ("/0/Resources.resx", code) }, - AnalyzerConfigFiles = - { - ("/.globalconfig", @" -is_global = true - -[/0/Resources.resx] -build_metadata.AdditionalFiles.GenerateSource = false -"), - }, - }, - }.RunAsync(); + AdditionalFiles = { ("/0/Resources.resx", code) }, + }, + }.AddGeneratedSources().RunAsync(); + } - await new VerifyVB.Test + [Fact] + public async Task SingleString_DisableCodeGenAsync() + { + var code = ResxHeader + + """ + + value + comment + + """ + + ResxFooter; + + await new VerifyCS.Test + { + TestState = { - TestState = + Sources = { "" }, + AdditionalFiles = { ("/0/Resources.resx", code) }, + AnalyzerConfigFiles = { - Sources = { "" }, - AdditionalFiles = { ("/0/Resources.resx", code) }, - AnalyzerConfigFiles = - { - ("/.globalconfig", @" -is_global = true - -[/0/Resources.resx] -build_metadata.AdditionalFiles.GenerateSource = false -"), - }, + ("/.globalconfig", """ + is_global = true + + [/0/Resources.resx] + build_metadata.AdditionalFiles.GenerateSource = false + """), }, - }.RunAsync(); - } - - [Theory] - [InlineData("")] - [InlineData("NS")] - [InlineData("NS1.NS2")] - public async Task SingleString_RootNamespaceCSharpAsync(string rootNamespace) + }, + }.RunAsync(); + + await new VerifyVB.Test { - var code = ResxHeader - + @" - value - comment - " - + ResxFooter; - - await new VerifyCS.Test(identifier: rootNamespace) + TestState = { - TestState = + Sources = { "" }, + AdditionalFiles = { ("/0/Resources.resx", code) }, + AnalyzerConfigFiles = { - AdditionalFiles = { ("/0/Resources.resx", code) }, - AnalyzerConfigFiles = - { - ("/.globalconfig", $@" -is_global = true - -build_property.RootNamespace = {rootNamespace} -"), - }, + ("/.globalconfig", """ + is_global = true + + [/0/Resources.resx] + build_metadata.AdditionalFiles.GenerateSource = false + """), }, - }.AddGeneratedSources().RunAsync(); - } - - [Theory] - [InlineData("")] - [InlineData("NS")] - [InlineData("NS1.NS2")] - public async Task SingleString_RootNamespaceVisualBasicAsync(string rootNamespace) + }, + }.RunAsync(); + } + + [Theory] + [InlineData("")] + [InlineData("NS")] + [InlineData("NS1.NS2")] + public async Task SingleString_RootNamespaceCSharpAsync(string rootNamespace) + { + var code = ResxHeader + + """ + + value + comment + + """ + + ResxFooter; + + await new VerifyCS.Test(identifier: rootNamespace) { - var code = ResxHeader - + @" - value - comment - " - + ResxFooter; - - await new VerifyVB.Test(identifier: rootNamespace) + TestState = { - TestState = + AdditionalFiles = { ("/0/Resources.resx", code) }, + AnalyzerConfigFiles = { - AdditionalFiles = { ("/0/Resources.resx", code) }, - AnalyzerConfigFiles = - { - ("/.globalconfig", $@" -is_global = true - -build_property.RootNamespace = {rootNamespace} -"), - }, + ("/.globalconfig", $""" + is_global = true + + build_property.RootNamespace = {rootNamespace} + """), }, - }.AddGeneratedSources().RunAsync(); - } - - [Theory] - [InlineData("")] - [InlineData("NS")] - [InlineData("NS1.NS2")] - public async Task SingleString_RelativeDirCSharpAsync(string relativeDir) + }, + }.AddGeneratedSources().RunAsync(); + } + + [Theory] + [InlineData("")] + [InlineData("NS")] + [InlineData("NS1.NS2")] + public async Task SingleString_RootNamespaceVisualBasicAsync(string rootNamespace) + { + var code = ResxHeader + + """ + + value + comment + + """ + + ResxFooter; + + await new VerifyVB.Test(identifier: rootNamespace) { - var code = ResxHeader - + @" - value - comment - " - + ResxFooter; - - await new VerifyCS.Test(identifier: relativeDir) + TestState = { - TestState = + AdditionalFiles = { ("/0/Resources.resx", code) }, + AnalyzerConfigFiles = { - AdditionalFiles = { ("/0/Resources.resx", code) }, - AnalyzerConfigFiles = - { - ("/.globalconfig", $@" -is_global = true - -[/0/Resources.resx] -build_metadata.AdditionalFiles.RelativeDir = {relativeDir} -"), - }, + ("/.globalconfig", $""" + is_global = true + + build_property.RootNamespace = {rootNamespace} + """), }, - }.AddGeneratedSources().RunAsync(); - } - - [Theory] - [InlineData("")] - [InlineData("NS")] - [InlineData("NS1.NS2")] - public async Task SingleString_RelativeDirVisualBasicAsync(string relativeDir) + }, + }.AddGeneratedSources().RunAsync(); + } + + [Theory] + [InlineData("")] + [InlineData("NS")] + [InlineData("NS1.NS2")] + public async Task SingleString_RelativeDirCSharpAsync(string relativeDir) + { + var code = ResxHeader + + """ + + value + comment + + """ + + ResxFooter; + + await new VerifyCS.Test(identifier: relativeDir) { - var code = ResxHeader - + @" - value - comment - " - + ResxFooter; - - await new VerifyVB.Test(identifier: relativeDir) + TestState = { - TestState = + AdditionalFiles = { ("/0/Resources.resx", code) }, + AnalyzerConfigFiles = { - AdditionalFiles = { ("/0/Resources.resx", code) }, - AnalyzerConfigFiles = - { - ("/.globalconfig", $@" -is_global = true - -[/0/Resources.resx] -build_metadata.AdditionalFiles.RelativeDir = {relativeDir} -"), - }, + ("/.globalconfig", $""" + is_global = true + + [/0/Resources.resx] + build_metadata.AdditionalFiles.RelativeDir = {relativeDir} + """), }, - }.AddGeneratedSources().RunAsync(); - } - - [Theory] - [InlineData("")] - [InlineData("NS")] - [InlineData("NS1.NS2")] - public async Task SingleString_ClassNameCSharpAsync(string className) + }, + }.AddGeneratedSources().RunAsync(); + } + + [Theory] + [InlineData("")] + [InlineData("NS")] + [InlineData("NS1.NS2")] + public async Task SingleString_RelativeDirVisualBasicAsync(string relativeDir) + { + var code = ResxHeader + + """ + + value + comment + + """ + + ResxFooter; + + await new VerifyVB.Test(identifier: relativeDir) { - var code = ResxHeader - + @" - value - comment - " - + ResxFooter; - - await new VerifyCS.Test(identifier: className) + TestState = { - TestState = + AdditionalFiles = { ("/0/Resources.resx", code) }, + AnalyzerConfigFiles = { - AdditionalFiles = { ("/0/Resources.resx", code) }, - AnalyzerConfigFiles = - { - ("/.globalconfig", $@" -is_global = true - -[/0/Resources.resx] -build_metadata.AdditionalFiles.ClassName = {className} -"), - }, + ("/.globalconfig", $""" + is_global = true + + [/0/Resources.resx] + build_metadata.AdditionalFiles.RelativeDir = {relativeDir} + """), }, - }.AddGeneratedSources().RunAsync(); - } - - [Theory] - [InlineData("")] - [InlineData("NS")] - [InlineData("NS1.NS2")] - public async Task SingleString_ClassNameVisualBasicAsync(string className) + }, + }.AddGeneratedSources().RunAsync(); + } + + [Theory] + [InlineData("")] + [InlineData("NS")] + [InlineData("NS1.NS2")] + public async Task SingleString_ClassNameCSharpAsync(string className) + { + var code = ResxHeader + + """ + + value + comment + + """ + + ResxFooter; + + await new VerifyCS.Test(identifier: className) { - var code = ResxHeader - + @" - value - comment - " - + ResxFooter; - - await new VerifyVB.Test(identifier: className) + TestState = { - TestState = + AdditionalFiles = { ("/0/Resources.resx", code) }, + AnalyzerConfigFiles = { - AdditionalFiles = { ("/0/Resources.resx", code) }, - AnalyzerConfigFiles = - { - ("/.globalconfig", $@" -is_global = true - -[/0/Resources.resx] -build_metadata.AdditionalFiles.ClassName = {className} -"), - }, + ("/.globalconfig", $""" + is_global = true + + [/0/Resources.resx] + build_metadata.AdditionalFiles.ClassName = {className} + """), }, - }.AddGeneratedSources().RunAsync(); - } + }, + }.AddGeneratedSources().RunAsync(); + } - [Theory] - [CombinatorialData] - public async Task SingleString_OmitGetResourceStringCSharpAsync(bool omitGetResourceString) + [Theory] + [InlineData("")] + [InlineData("NS")] + [InlineData("NS1.NS2")] + public async Task SingleString_ClassNameVisualBasicAsync(string className) + { + var code = ResxHeader + + """ + + value + comment + + """ + + ResxFooter; + + await new VerifyVB.Test(identifier: className) { - var code = ResxHeader - + @" - value - comment - " - + ResxFooter; - - var customGetResourceString = @"#nullable enable + TestState = + { + AdditionalFiles = { ("/0/Resources.resx", code) }, + AnalyzerConfigFiles = + { + ("/.globalconfig", $""" + is_global = true -namespace TestProject -{ - internal static partial class Resources - { - internal static string? GetResourceString(string resourceKey, string? defaultValue = null) => throw null!; + [/0/Resources.resx] + build_metadata.AdditionalFiles.ClassName = {className} + """), + }, + }, + }.AddGeneratedSources().RunAsync(); } -} -"; - await new VerifyCS.Test(identifier: omitGetResourceString.ToString()) + [Theory] + [CombinatorialData] + public async Task SingleString_OmitGetResourceStringCSharpAsync(bool omitGetResourceString) + { + var code = ResxHeader + + """ + + value + comment + + """ + + ResxFooter; + + var customGetResourceString = """ + #nullable enable + + namespace TestProject { - TestState = + internal static partial class Resources { - Sources = { omitGetResourceString ? customGetResourceString : "" }, - AdditionalFiles = { ("/0/Resources.resx", code) }, - AnalyzerConfigFiles = - { - ("/.globalconfig", $@" -is_global = true - -[/0/Resources.resx] -build_metadata.AdditionalFiles.OmitGetResourceString = {(omitGetResourceString ? "true" : "false")} -"), - }, - }, - }.AddGeneratedSources().RunAsync(); - } + internal static string? GetResourceString(string resourceKey, string? defaultValue = null) => throw null!; + } + } + """; - [Theory] - [CombinatorialData] - public async Task SingleString_OmitGetResourceStringVisualBasicAsync(bool omitGetResourceString) + await new VerifyCS.Test(identifier: omitGetResourceString.ToString()) { - var code = ResxHeader - + @" - value - comment - " - + ResxFooter; - - var customGetResourceString = @" -Namespace Global.TestProject - Friend Partial Class Resources - Friend Shared Function GetResourceString(resourceKey As String, Optional defaultValue As String = Nothing) - Return """" - End Function - End Class -End Namespace -"; - - await new VerifyVB.Test(identifier: omitGetResourceString.ToString()) + TestState = { - TestState = + Sources = { omitGetResourceString ? customGetResourceString : "" }, + AdditionalFiles = { ("/0/Resources.resx", code) }, + AnalyzerConfigFiles = { - Sources = { omitGetResourceString ? customGetResourceString : "" }, - AdditionalFiles = { ("/0/Resources.resx", code) }, - AnalyzerConfigFiles = - { - ("/.globalconfig", $@" -is_global = true - -[/0/Resources.resx] -build_metadata.AdditionalFiles.OmitGetResourceString = {(omitGetResourceString ? "true" : "false")} -"), - }, + ("/.globalconfig", $""" + is_global = true + + [/0/Resources.resx] + build_metadata.AdditionalFiles.OmitGetResourceString = {(omitGetResourceString ? "true" : "false")} + """), }, - }.AddGeneratedSources().RunAsync(); - } + }, + }.AddGeneratedSources().RunAsync(); + } - [Theory] - [CombinatorialData] - public async Task SingleString_AsConstantsCSharpAsync(bool asConstants) + [Theory] + [CombinatorialData] + public async Task SingleString_OmitGetResourceStringVisualBasicAsync(bool omitGetResourceString) + { + var code = ResxHeader + + """ + + value + comment + + """ + + ResxFooter; + + var customGetResourceString = """ + Namespace Global.TestProject + Friend Partial Class Resources + Friend Shared Function GetResourceString(resourceKey As String, Optional defaultValue As String = Nothing) + Return "" + End Function + End Class + End Namespace + """; + + await new VerifyVB.Test(identifier: omitGetResourceString.ToString()) { - var code = ResxHeader - + @" - value - comment - " - + ResxFooter; - - await new VerifyCS.Test(identifier: asConstants.ToString()) + TestState = { - TestState = + Sources = { omitGetResourceString ? customGetResourceString : "" }, + AdditionalFiles = { ("/0/Resources.resx", code) }, + AnalyzerConfigFiles = { - AdditionalFiles = { ("/0/Resources.resx", code) }, - AnalyzerConfigFiles = - { - ("/.globalconfig", $@" -is_global = true - -[/0/Resources.resx] -build_metadata.AdditionalFiles.AsConstants = {(asConstants ? "true" : "false")} -"), - }, + ("/.globalconfig", $""" + is_global = true + + [/0/Resources.resx] + build_metadata.AdditionalFiles.OmitGetResourceString = {(omitGetResourceString ? "true" : "false")} + """), }, - }.AddGeneratedSources().RunAsync(); - } + }, + }.AddGeneratedSources().RunAsync(); + } - [Theory] - [CombinatorialData] - public async Task SingleString_AsConstantsVisualBasicAsync(bool asConstants) + [Theory] + [CombinatorialData] + public async Task SingleString_AsConstantsCSharpAsync(bool asConstants) + { + var code = ResxHeader + + """ + + value + comment + + """ + + ResxFooter; + + await new VerifyCS.Test(identifier: asConstants.ToString()) { - var code = ResxHeader - + @" - value - comment - " - + ResxFooter; - - await new VerifyVB.Test(identifier: asConstants.ToString()) + TestState = { - TestState = + AdditionalFiles = { ("/0/Resources.resx", code) }, + AnalyzerConfigFiles = { - AdditionalFiles = { ("/0/Resources.resx", code) }, - AnalyzerConfigFiles = - { - ("/.globalconfig", $@" -is_global = true - -[/0/Resources.resx] -build_metadata.AdditionalFiles.AsConstants = {(asConstants ? "true" : "false")} -"), - }, + ("/.globalconfig", $""" + is_global = true + + [/0/Resources.resx] + build_metadata.AdditionalFiles.AsConstants = {(asConstants ? "true" : "false")} + """), }, - }.AddGeneratedSources().RunAsync(); - } + }, + }.AddGeneratedSources().RunAsync(); + } - [Theory] - [CombinatorialData] - public async Task SingleString_IncludeDefaultValuesCSharpAsync(bool includeDefaultValues) + [Theory] + [CombinatorialData] + public async Task SingleString_AsConstantsVisualBasicAsync(bool asConstants) + { + var code = ResxHeader + + """ + + value + comment + + """ + + ResxFooter; + + await new VerifyVB.Test(identifier: asConstants.ToString()) { - var code = ResxHeader - + @" - value - comment - " - + ResxFooter; - - await new VerifyCS.Test(identifier: includeDefaultValues.ToString()) + TestState = { - TestState = + AdditionalFiles = { ("/0/Resources.resx", code) }, + AnalyzerConfigFiles = { - AdditionalFiles = { ("/0/Resources.resx", code) }, - AnalyzerConfigFiles = - { - ("/.globalconfig", $@" -is_global = true - -[/0/Resources.resx] -build_metadata.AdditionalFiles.IncludeDefaultValues = {(includeDefaultValues ? "true" : "false")} -"), - }, + ("/.globalconfig", $""" + is_global = true + + [/0/Resources.resx] + build_metadata.AdditionalFiles.AsConstants = {(asConstants ? "true" : "false")} + """), }, - }.AddGeneratedSources().RunAsync(); - } + }, + }.AddGeneratedSources().RunAsync(); + } - [Theory] - [CombinatorialData] - public async Task SingleString_IncludeDefaultValuesVisualBasicAsync(bool includeDefaultValues) + [Theory] + [CombinatorialData] + public async Task SingleString_IncludeDefaultValuesCSharpAsync(bool includeDefaultValues) + { + var code = ResxHeader + + """ + + value + comment + + """ + + ResxFooter; + + await new VerifyCS.Test(identifier: includeDefaultValues.ToString()) { - var code = ResxHeader - + @" - value - comment - " - + ResxFooter; - - await new VerifyVB.Test(identifier: includeDefaultValues.ToString()) + TestState = { - TestState = + AdditionalFiles = { ("/0/Resources.resx", code) }, + AnalyzerConfigFiles = { - AdditionalFiles = { ("/0/Resources.resx", code) }, - AnalyzerConfigFiles = - { - ("/.globalconfig", $@" -is_global = true - -[/0/Resources.resx] -build_metadata.AdditionalFiles.IncludeDefaultValues = {(includeDefaultValues ? "true" : "false")} -"), - }, + ("/.globalconfig", $""" + is_global = true + + [/0/Resources.resx] + build_metadata.AdditionalFiles.IncludeDefaultValues = {(includeDefaultValues ? "true" : "false")} + """), }, - }.AddGeneratedSources().RunAsync(); - } - - [Theory] - [CombinatorialData] - public async Task SingleString_EmitFormatMethodsCSharpAsync( - [CombinatorialValues("0", "x", "replacement")] string placeholder, - bool emitFormatMethods) + }, + }.AddGeneratedSources().RunAsync(); + } + + [Theory] + [CombinatorialData] + public async Task SingleString_IncludeDefaultValuesVisualBasicAsync(bool includeDefaultValues) + { + var code = ResxHeader + + """ + + value + comment + + """ + + ResxFooter; + + await new VerifyVB.Test(identifier: includeDefaultValues.ToString()) { - var code = ResxHeader - + $@" - value {{{placeholder}}} - comment - " - + ResxFooter; - - await new VerifyCS.Test(identifier: $"{placeholder}_{emitFormatMethods}") + TestState = { - TestState = + AdditionalFiles = { ("/0/Resources.resx", code) }, + AnalyzerConfigFiles = { - AdditionalFiles = { ("/0/Resources.resx", code) }, - AnalyzerConfigFiles = - { - ("/.globalconfig", $@" -is_global = true - -[/0/Resources.resx] -build_metadata.AdditionalFiles.EmitFormatMethods = {(emitFormatMethods ? "true" : "false")} -"), - }, + ("/.globalconfig", $""" + is_global = true + + [/0/Resources.resx] + build_metadata.AdditionalFiles.IncludeDefaultValues = {(includeDefaultValues ? "true" : "false")} + """), }, - }.AddGeneratedSources().RunAsync(); - } + }, + }.AddGeneratedSources().RunAsync(); + } - [Theory] - [InlineData(true, Skip = "Not yet supported")] - [InlineData(false)] - public async Task SingleString_EmitFormatMethodsVisualBasicAsync(bool emitFormatMethods) + [Theory] + [CombinatorialData] + public async Task SingleString_EmitFormatMethodsCSharpAsync( + [CombinatorialValues("0", "x", "replacement")] string placeholder, + bool emitFormatMethods) + { + var code = ResxHeader + + $$""" + + value {{{placeholder}}} + comment + + """ + + ResxFooter; + + await new VerifyCS.Test(identifier: $"{placeholder}_{emitFormatMethods}") { - var code = ResxHeader - + @" - value - comment - " - + ResxFooter; - - await new VerifyVB.Test(identifier: emitFormatMethods.ToString()) + TestState = { - TestState = + AdditionalFiles = { ("/0/Resources.resx", code) }, + AnalyzerConfigFiles = { - AdditionalFiles = { ("/0/Resources.resx", code) }, - AnalyzerConfigFiles = - { - ("/.globalconfig", $@" -is_global = true - -[/0/Resources.resx] -build_metadata.AdditionalFiles.EmitFormatMethods = {(emitFormatMethods ? "true" : "false")} -"), - }, + ("/.globalconfig", $""" + is_global = true + + [/0/Resources.resx] + build_metadata.AdditionalFiles.EmitFormatMethods = {(emitFormatMethods ? "true" : "false")} + """), }, - }.AddGeneratedSources().RunAsync(); - } + }, + }.AddGeneratedSources().RunAsync(); + } - [Theory] - [CombinatorialData] - public async Task SingleString_PublicCSharpAsync(bool publicResource) + [Theory] + [InlineData(true, Skip = "Not yet supported")] + [InlineData(false)] + public async Task SingleString_EmitFormatMethodsVisualBasicAsync(bool emitFormatMethods) + { + var code = ResxHeader + + """ + + value + comment + + """ + + ResxFooter; + + await new VerifyVB.Test(identifier: emitFormatMethods.ToString()) { - var code = ResxHeader - + @" - value - comment - " - + ResxFooter; - - await new VerifyCS.Test(identifier: publicResource.ToString()) + TestState = { - TestState = + AdditionalFiles = { ("/0/Resources.resx", code) }, + AnalyzerConfigFiles = { - AdditionalFiles = { ("/0/Resources.resx", code) }, - AnalyzerConfigFiles = - { - ("/.globalconfig", $@" -is_global = true - -[/0/Resources.resx] -build_metadata.AdditionalFiles.Public = {(publicResource ? "true" : "false")} -"), - }, + ("/.globalconfig", $""" + is_global = true + + [/0/Resources.resx] + build_metadata.AdditionalFiles.EmitFormatMethods = {(emitFormatMethods ? "true" : "false")} + """), }, - }.AddGeneratedSources().RunAsync(); - } + }, + }.AddGeneratedSources().RunAsync(); + } - [Theory] - [CombinatorialData] - public async Task SingleString_PublicVisualBasicAsync(bool publicResource) + [Theory] + [CombinatorialData] + public async Task SingleString_PublicCSharpAsync(bool publicResource) + { + var code = ResxHeader + + """ + + value + comment + + """ + + ResxFooter; + + await new VerifyCS.Test(identifier: publicResource.ToString()) { - var code = ResxHeader - + @" - value - comment - " - + ResxFooter; - - await new VerifyVB.Test(identifier: publicResource.ToString()) + TestState = { - TestState = + AdditionalFiles = { ("/0/Resources.resx", code) }, + AnalyzerConfigFiles = { - AdditionalFiles = { ("/0/Resources.resx", code) }, - AnalyzerConfigFiles = - { - ("/.globalconfig", $@" -is_global = true - -[/0/Resources.resx] -build_metadata.AdditionalFiles.Public = {(publicResource ? "true" : "false")} -"), - }, - }, - }.AddGeneratedSources().RunAsync(); - } - - [Theory] - [InlineData("")] - [InlineData("CS1591")] - [InlineData("CS1591, IDE0010")] - [InlineData(" , CS1591, IDE0010 ")] - public async Task SingleString_NoWarnsCSharpAsync(string noWarn) - { - var code = ResxHeader - + @" - value - comment - " - + ResxFooter; + ("/.globalconfig", $""" + is_global = true - var id = string.Join("_", noWarn.Replace(" ", "").Split(",", System.StringSplitOptions.TrimEntries | System.StringSplitOptions.RemoveEmptyEntries)); + [/0/Resources.resx] + build_metadata.AdditionalFiles.Public = {(publicResource ? "true" : "false")} + """), + }, + }, + }.AddGeneratedSources().RunAsync(); + } - await new VerifyCS.Test(identifier: id) + [Theory] + [CombinatorialData] + public async Task SingleString_PublicVisualBasicAsync(bool publicResource) + { + var code = ResxHeader + + """ + + value + comment + + """ + + ResxFooter; + + await new VerifyVB.Test(identifier: publicResource.ToString()) + { + TestState = { - TestState = + AdditionalFiles = { ("/0/Resources.resx", code) }, + AnalyzerConfigFiles = { - AdditionalFiles = { ("/0/Resources.resx", code) }, - AnalyzerConfigFiles = - { - ("/.globalconfig", $@" -is_global = true - -[/0/Resources.resx] -build_metadata.AdditionalFiles.NoWarn = {noWarn} -"), - }, + ("/.globalconfig", $""" + is_global = true + + [/0/Resources.resx] + build_metadata.AdditionalFiles.Public = {(publicResource ? "true" : "false")} + """), }, - }.AddGeneratedSources().RunAsync(); - } - - [Theory] - [InlineData("")] - [InlineData("CS1591")] - [InlineData("CS1591, IDE0010")] - [InlineData(" , CS1591, IDE0010 ")] - public async Task SingleString_NoWarnsVisualBasicAsync(string noWarn) + }, + }.AddGeneratedSources().RunAsync(); + } + + [Theory] + [InlineData("")] + [InlineData("CS1591")] + [InlineData("CS1591, IDE0010")] + [InlineData(" , CS1591, IDE0010 ")] + public async Task SingleString_NoWarnsCSharpAsync(string noWarn) + { + var code = ResxHeader + + """ + + value + comment + + """ + + ResxFooter; + + var id = string.Join("_", noWarn.Replace(" ", "").Split(",", System.StringSplitOptions.TrimEntries | System.StringSplitOptions.RemoveEmptyEntries)); + + await new VerifyCS.Test(identifier: id) { - var code = ResxHeader - + @" - value - comment - " - + ResxFooter; + TestState = + { + AdditionalFiles = { ("/0/Resources.resx", code) }, + AnalyzerConfigFiles = + { + ("/.globalconfig", $""" + is_global = true - var id = string.Join("_", noWarn.Replace(" ", "").Split(",", System.StringSplitOptions.TrimEntries | System.StringSplitOptions.RemoveEmptyEntries)); + [/0/Resources.resx] + build_metadata.AdditionalFiles.NoWarn = {noWarn} + """), + }, + }, + }.AddGeneratedSources().RunAsync(); + } - await new VerifyVB.Test(identifier: id) + [Theory] + [InlineData("")] + [InlineData("CS1591")] + [InlineData("CS1591, IDE0010")] + [InlineData(" , CS1591, IDE0010 ")] + public async Task SingleString_NoWarnsVisualBasicAsync(string noWarn) + { + var code = ResxHeader + + """ + + value + comment + + """ + + ResxFooter; + + var id = string.Join("_", noWarn.Replace(" ", "").Split(",", System.StringSplitOptions.TrimEntries | System.StringSplitOptions.RemoveEmptyEntries)); + + await new VerifyVB.Test(identifier: id) + { + TestState = { - TestState = + AdditionalFiles = { ("/0/Resources.resx", code) }, + AnalyzerConfigFiles = { - AdditionalFiles = { ("/0/Resources.resx", code) }, - AnalyzerConfigFiles = - { - ("/.globalconfig", $@" -is_global = true - -[/0/Resources.resx] -build_metadata.AdditionalFiles.NoWarn = {noWarn} -"), - }, + ("/.globalconfig", $""" + is_global = true + + [/0/Resources.resx] + build_metadata.AdditionalFiles.NoWarn = {noWarn} + """), }, - }.AddGeneratedSources().RunAsync(); - } + }, + }.AddGeneratedSources().RunAsync(); } } diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Verifiers/CSharpVerifierHelper.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Verifiers/CSharpVerifierHelper.cs index 69ff503c1aa74..ca5557a9ee2c1 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Verifiers/CSharpVerifierHelper.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests/Verifiers/CSharpVerifierHelper.cs @@ -23,7 +23,7 @@ internal static class CSharpVerifierHelper private static ImmutableDictionary GetNullableWarningsFromCompiler() { - string[] args = { "/warnaserror:nullable" }; + string[] args = ["/warnaserror:nullable"]; var commandLineArguments = CSharpCommandLineParser.Default.Parse(args, baseDirectory: Environment.CurrentDirectory, sdkDirectory: Environment.CurrentDirectory); return commandLineArguments.CompilationOptions.SpecificDiagnosticOptions; } diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.VisualBasic/Microsoft.CodeAnalysis.ResxSourceGenerator.VisualBasic.csproj b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.VisualBasic/Microsoft.CodeAnalysis.ResxSourceGenerator.VisualBasic.csproj index 7f190491047d1..49c651fc18aa9 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.VisualBasic/Microsoft.CodeAnalysis.ResxSourceGenerator.VisualBasic.csproj +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.VisualBasic/Microsoft.CodeAnalysis.ResxSourceGenerator.VisualBasic.csproj @@ -7,13 +7,22 @@ *$(MSBuildProjectFile)* - $(MicrosoftCodeAnalysisVersionForResxSourceGenerators) - - - - + + + + + + + + + + + + + + diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator/AbstractResxGenerator.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator/AbstractResxGenerator.cs index 5314b0b8d0a05..1d9bb6027c938 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator/AbstractResxGenerator.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator/AbstractResxGenerator.cs @@ -19,6 +19,7 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; #pragma warning disable IDE0010 // Add missing cases (noise) #pragma warning disable IDE0057 // Use range operator (incorrectly reported when Range is not defined) @@ -203,7 +204,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context) } catch (Exception ex) { - var exceptionLines = ex.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None); + var exceptionLines = ex.ToString().Split([Environment.NewLine], StringSplitOptions.None); var text = string.Join("", exceptionLines.Select(line => "#error " + line + Environment.NewLine)); var errorText = SourceText.From(text, Encoding.UTF8, SourceHashAlgorithm.Sha256); context.AddSource($"{resourceInformation.ResourceHintName}.Error", errorText); @@ -339,7 +340,9 @@ private void LogError(Lang language, string message) var result = language switch { Lang.CSharp => $"#error {message}", - Lang.VisualBasic => $"#Error \"{message}\"", + Lang.VisualBasic => $""" + #Error "{message}" + """, _ => message, }; @@ -380,7 +383,8 @@ public bool Execute(CancellationToken cancellationToken) return false; } - var resourceAccessName = RoslynString.IsNullOrEmpty(ResourceInformation.ResourceClassName) ? ResourceInformation.ResourceName : ResourceInformation.ResourceClassName; + var resourceAccessName = string.IsNullOrEmpty(ResourceInformation.ResourceClassName) ? ResourceInformation.ResourceName : ResourceInformation.ResourceClassName; + Contract.ThrowIfNull(resourceAccessName); SplitName(resourceAccessName, out var namespaceName, out var className); var classIndent = namespaceName == null ? "" : " "; @@ -461,7 +465,9 @@ public bool Execute(CancellationToken cancellationToken) case Lang.VisualBasic: if (ResourceInformation.AsConstants) { - strings.AppendLine($"{memberIndent}Public Const [{identifier}] As String = \"{name}\""); + strings.AppendLine($""" + {memberIndent}Public Const [{identifier}] As String = "{name}" + """); } else { @@ -505,36 +511,40 @@ public bool Execute(CancellationToken cancellationToken) getResourceStringAttributes.Add("[return: global::System.Diagnostics.CodeAnalysis.NotNullIfNotNull(\"defaultValue\")]"); } - getStringMethod = $@"{memberIndent}public static global::System.Globalization.CultureInfo{(CompilationInformation.SupportsNullable ? "?" : "")} Culture {{ get; set; }} -{string.Join(Environment.NewLine, getResourceStringAttributes.Select(attr => memberIndent + attr))} -{memberIndent}internal static {(CompilationInformation.SupportsNullable ? "string?" : "string")} GetResourceString(string resourceKey, {(CompilationInformation.SupportsNullable ? "string?" : "string")} defaultValue = null) => ResourceManager.GetString(resourceKey, Culture) ?? defaultValue;"; + getStringMethod = $$""" + {{memberIndent}}public static global::System.Globalization.CultureInfo{{(CompilationInformation.SupportsNullable ? "?" : "")}} Culture { get; set; } + {{string.Join(Environment.NewLine, getResourceStringAttributes.Select(attr => memberIndent + attr))}} + {{memberIndent}}internal static {{(CompilationInformation.SupportsNullable ? "string?" : "string")}} GetResourceString(string resourceKey, {{(CompilationInformation.SupportsNullable ? "string?" : "string")}} defaultValue = null) => ResourceManager.GetString(resourceKey, Culture) ?? defaultValue; + """; if (ResourceInformation.EmitFormatMethods) { - getStringMethod += $@" - -{memberIndent}private static string GetResourceString(string resourceKey, string[]? formatterNames) -{memberIndent}{{ -{memberIndent} var value = GetResourceString(resourceKey) ?? """"; -{memberIndent} if (formatterNames != null) -{memberIndent} {{ -{memberIndent} for (var i = 0; i < formatterNames.Length; i++) -{memberIndent} {{ -{memberIndent} value = value.Replace(""{{"" + formatterNames[i] + ""}}"", ""{{"" + i + ""}}""); -{memberIndent} }} -{memberIndent} }} -{memberIndent} return value; -{memberIndent}}} -"; + getStringMethod += $$""" + + {{memberIndent}}private static string GetResourceString(string resourceKey, string[]? formatterNames) + {{memberIndent}}{ + {{memberIndent}} var value = GetResourceString(resourceKey) ?? ""; + {{memberIndent}} if (formatterNames != null) + {{memberIndent}} { + {{memberIndent}} for (var i = 0; i < formatterNames.Length; i++) + {{memberIndent}} { + {{memberIndent}} value = value.Replace("{" + formatterNames[i] + "}", "{" + i + "}"); + {{memberIndent}} } + {{memberIndent}} } + {{memberIndent}} return value; + {{memberIndent}}} + """; } break; case Lang.VisualBasic: - getStringMethod = $@"{memberIndent}Public Shared Property Culture As Global.System.Globalization.CultureInfo -{memberIndent} -{memberIndent}Friend Shared Function GetResourceString(ByVal resourceKey As String, Optional ByVal defaultValue As String = Nothing) As String -{memberIndent} Return ResourceManager.GetString(resourceKey, Culture) -{memberIndent}End Function"; + getStringMethod = $""" + {memberIndent}Public Shared Property Culture As Global.System.Globalization.CultureInfo + {memberIndent} + {memberIndent}Friend Shared Function GetResourceString(ByVal resourceKey As String, Optional ByVal defaultValue As String = Nothing) As String + {memberIndent} Return ResourceManager.GetString(resourceKey, Culture) + {memberIndent}End Function + """; if (ResourceInformation.EmitFormatMethods) { throw new NotImplementedException(); @@ -595,22 +605,28 @@ public bool Execute(CancellationToken cancellationToken) resourceTypeDefinition = $"{resourceClassIndent}internal static class {resourceClassName} {{ }}"; if (resourceNamespaceName != null) { - resourceTypeDefinition = $@"namespace {resourceNamespaceName} -{{ -{resourceTypeDefinition} -}}"; + resourceTypeDefinition = $$""" + namespace {{resourceNamespaceName}} + { + {{resourceTypeDefinition}} + } + """; } break; case Lang.VisualBasic: - resourceTypeDefinition = $@"{resourceClassIndent}Friend Class {resourceClassName} -{resourceClassIndent}End Class"; + resourceTypeDefinition = $""" + {resourceClassIndent}Friend Class {resourceClassName} + {resourceClassIndent}End Class + """; if (resourceNamespaceName != null) { - resourceTypeDefinition = $@"Namespace {resourceNamespaceName} -{resourceTypeDefinition} -End Namespace"; + resourceTypeDefinition = $""" + Namespace {resourceNamespaceName} + {resourceTypeDefinition} + End Namespace + """; } break; @@ -652,49 +668,51 @@ public bool Execute(CancellationToken cancellationToken) switch (language) { case Lang.CSharp: - result = $@"// {noWarnDisabled} - -{(CompilationInformation.SupportsNullable ? "#nullable enable" : "")} -using System.Reflection; - -{resourceTypeDefinition} -{namespaceStart} -{classIndent}{(ResourceInformation.Public ? "public" : "internal")} static partial class {className} -{classIndent}{{ -{memberIndent}private static global::System.Resources.ResourceManager{(CompilationInformation.SupportsNullable ? "?" : "")} s_resourceManager; -{memberIndent}public static global::System.Resources.ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new global::System.Resources.ResourceManager(typeof({resourceTypeName}))); -{getStringMethod} -{strings} -{classIndent}}} -{namespaceEnd}{noWarnRestored} -"; + result = $$""" + // {{noWarnDisabled}} + + {{(CompilationInformation.SupportsNullable ? "#nullable enable" : "")}} + using System.Reflection; + + {{resourceTypeDefinition}} + {{namespaceStart}} + {{classIndent}}{{(ResourceInformation.Public ? "public" : "internal")}} static partial class {{className}} + {{classIndent}}{ + {{memberIndent}}private static global::System.Resources.ResourceManager{{(CompilationInformation.SupportsNullable ? "?" : "")}} s_resourceManager; + {{memberIndent}}public static global::System.Resources.ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new global::System.Resources.ResourceManager(typeof({{resourceTypeName}}))); + {{getStringMethod}} + {{strings}} + {{classIndent}}} + {{namespaceEnd}}{{noWarnRestored}} + """; break; case Lang.VisualBasic: - result = $@"' {noWarnDisabled} - -Imports System.Reflection - -{resourceTypeDefinition} -{namespaceStart} -{classIndent}{(ResourceInformation.Public ? "Public" : "Friend")} Partial Class {className} -{memberIndent}Private Sub New -{memberIndent}End Sub -{memberIndent} -{memberIndent}Private Shared s_resourceManager As Global.System.Resources.ResourceManager -{memberIndent}Public Shared ReadOnly Property ResourceManager As Global.System.Resources.ResourceManager -{memberIndent} Get -{memberIndent} If s_resourceManager Is Nothing Then -{memberIndent} s_resourceManager = New Global.System.Resources.ResourceManager(GetType({resourceTypeName})) -{memberIndent} End If -{memberIndent} Return s_resourceManager -{memberIndent} End Get -{memberIndent}End Property -{getStringMethod} -{strings} -{classIndent}End Class -{namespaceEnd}{noWarnRestored} -"; + result = $""" + ' {noWarnDisabled} + + Imports System.Reflection + + {resourceTypeDefinition} + {namespaceStart} + {classIndent}{(ResourceInformation.Public ? "Public" : "Friend")} Partial Class {className} + {memberIndent}Private Sub New + {memberIndent}End Sub + {memberIndent} + {memberIndent}Private Shared s_resourceManager As Global.System.Resources.ResourceManager + {memberIndent}Public Shared ReadOnly Property ResourceManager As Global.System.Resources.ResourceManager + {memberIndent} Get + {memberIndent} If s_resourceManager Is Nothing Then + {memberIndent} s_resourceManager = New Global.System.Resources.ResourceManager(GetType({resourceTypeName})) + {memberIndent} End If + {memberIndent} Return s_resourceManager + {memberIndent} End Get + {memberIndent}End Property + {getStringMethod} + {strings} + {classIndent}End Class + {namespaceEnd}{noWarnRestored} + """; break; default: @@ -766,7 +784,7 @@ private static void RenderDocComment(Lang language, string memberIndent, StringB var escapedTrimmedValue = new XElement("summary", value).ToString(); - foreach (var line in escapedTrimmedValue.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None)) + foreach (var line in escapedTrimmedValue.Split(["\r\n", "\r", "\n"], StringSplitOptions.None)) { strings.Append(memberIndent).Append(docCommentStart).Append(' '); strings.AppendLine(line); @@ -866,7 +884,11 @@ public ResourceString(string name, string value) public bool HasArguments => _arguments.Count > 0; - public string GetArgumentNames() => string.Join(", ", _arguments.Select(a => "\"" + a + "\"")); + public string GetArgumentNames() => string.Join(", ", _arguments.Select(a => """ + " + """ + a + """ + " + """)); public string GetArguments() => string.Join(", ", _arguments.Select(GetArgName)); diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.csproj b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.csproj index 3c35be7569a5c..d9374df726fae 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.csproj +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator.csproj @@ -7,7 +7,7 @@ *$(MSBuildProjectFile)* - $(MicrosoftCodeAnalysisVersionForResxSourceGenerators) + Microsoft.CodeAnalysis @@ -17,9 +17,29 @@ - + + + + + + + + + + + + + + + + + + + + + diff --git a/src/RoslynAnalyzers/NuGet/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.Package.csproj b/src/RoslynAnalyzers/NuGet/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.Package.csproj index bffd6ae6a5b94..0d608b0c581b5 100644 --- a/src/RoslynAnalyzers/NuGet/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.Package.csproj +++ b/src/RoslynAnalyzers/NuGet/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.Package.csproj @@ -17,17 +17,30 @@ Restore would conclude that there is a cyclic dependency between Microsoft.CodeAnalysis and Microsoft.CodeAnalysis.Analyzers. --> *$(MSBuildProjectFile)* - $(MicrosoftCodeAnalysisVersionForCodeAnalysisAnalyzers) - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/RoslynAnalyzers/NuGet/Microsoft.CodeAnalysis.Metrics/Microsoft.CodeAnalysis.Metrics.Package.csproj b/src/RoslynAnalyzers/NuGet/Microsoft.CodeAnalysis.Metrics/Microsoft.CodeAnalysis.Metrics.Package.csproj index d47d5f2419162..842a3f09379fe 100644 --- a/src/RoslynAnalyzers/NuGet/Microsoft.CodeAnalysis.Metrics/Microsoft.CodeAnalysis.Metrics.Package.csproj +++ b/src/RoslynAnalyzers/NuGet/Microsoft.CodeAnalysis.Metrics/Microsoft.CodeAnalysis.Metrics.Package.csproj @@ -17,7 +17,6 @@ $(NoWarn);NU5100 $(MetricsVersionPrefix) - $(MicrosoftCodeAnalysisVersionForMetrics) 1.1.2 @@ -33,15 +32,15 @@ - - - - - - - - - + + + + + + + + + diff --git a/src/RoslynAnalyzers/NuGet/Microsoft.CodeAnalysis.RulesetToEditorconfigConverter/Microsoft.CodeAnalysis.RulesetToEditorconfigConverter.Package.csproj b/src/RoslynAnalyzers/NuGet/Microsoft.CodeAnalysis.RulesetToEditorconfigConverter/Microsoft.CodeAnalysis.RulesetToEditorconfigConverter.Package.csproj index 28a1367d9a73a..828220cfc9757 100644 --- a/src/RoslynAnalyzers/NuGet/Microsoft.CodeAnalysis.RulesetToEditorconfigConverter/Microsoft.CodeAnalysis.RulesetToEditorconfigConverter.Package.csproj +++ b/src/RoslynAnalyzers/NuGet/Microsoft.CodeAnalysis.RulesetToEditorconfigConverter/Microsoft.CodeAnalysis.RulesetToEditorconfigConverter.Package.csproj @@ -16,7 +16,6 @@ $(NoWarn);NU5100 - $(MicrosoftCodeAnalysisVersionForExecution) @@ -28,11 +27,11 @@ - - - - - - + + + + + + \ No newline at end of file diff --git a/src/RoslynAnalyzers/NuGet/PerformanceSensitiveAnalyzers/PerformanceSensitiveAttribute.cs b/src/RoslynAnalyzers/NuGet/PerformanceSensitiveAnalyzers/PerformanceSensitiveAttribute.cs index 47f2139618b2b..2f753bdefb408 100644 --- a/src/RoslynAnalyzers/NuGet/PerformanceSensitiveAnalyzers/PerformanceSensitiveAttribute.cs +++ b/src/RoslynAnalyzers/NuGet/PerformanceSensitiveAnalyzers/PerformanceSensitiveAttribute.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. #pragma warning disable CS1574 // XML comment has cref attribute that could not be resolved (not all builds have all types) diff --git a/src/RoslynAnalyzers/NuGet/Roslyn.Diagnostics.Analyzers/Roslyn.Diagnostics.Analyzers.Package.csproj b/src/RoslynAnalyzers/NuGet/Roslyn.Diagnostics.Analyzers/Roslyn.Diagnostics.Analyzers.Package.csproj index 9a006b994d27f..2914a966f09dd 100644 --- a/src/RoslynAnalyzers/NuGet/Roslyn.Diagnostics.Analyzers/Roslyn.Diagnostics.Analyzers.Package.csproj +++ b/src/RoslynAnalyzers/NuGet/Roslyn.Diagnostics.Analyzers/Roslyn.Diagnostics.Analyzers.Package.csproj @@ -11,17 +11,30 @@ Roslyn.Diagnostics Analyzers Roslyn CodeAnalysis Compiler CSharp VB VisualBasic Diagnostic Analyzers Syntax Semantics true - $(MicrosoftCodeAnalysisForRoslynDiagnosticsAnalyzersVersion) - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/CSharp/Analyzers/Microsoft.CodeAnalysis.CSharp.PerformanceSensitiveAnalyzers.csproj b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/CSharp/Analyzers/Microsoft.CodeAnalysis.CSharp.PerformanceSensitiveAnalyzers.csproj index 48e6187175354..ab192628effd6 100644 --- a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/CSharp/Analyzers/Microsoft.CodeAnalysis.CSharp.PerformanceSensitiveAnalyzers.csproj +++ b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/CSharp/Analyzers/Microsoft.CodeAnalysis.CSharp.PerformanceSensitiveAnalyzers.csproj @@ -2,15 +2,14 @@ netstandard2.0 - $(MicrosoftCodeAnalysisVersionForPerfSensitiveAnalyzers) - - + + diff --git a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/CSharp/CodeFixes/AvoidAllocationWithArrayEmptyCodeFix.cs b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/CSharp/CodeFixes/AvoidAllocationWithArrayEmptyCodeFix.cs index 229feeb5492fd..40f1a3fc49e26 100644 --- a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/CSharp/CodeFixes/AvoidAllocationWithArrayEmptyCodeFix.cs +++ b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/CSharp/CodeFixes/AvoidAllocationWithArrayEmptyCodeFix.cs @@ -8,12 +8,12 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using Analyzer.Utilities; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers; +using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.PerformanceSensitiveAnalyzers.CodeFixes { diff --git a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/CSharp/CodeFixes/Microsoft.CodeAnalysis.CSharp.PerformanceSensitiveAnalyzers.CodeFixes.csproj b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/CSharp/CodeFixes/Microsoft.CodeAnalysis.CSharp.PerformanceSensitiveAnalyzers.CodeFixes.csproj index b880cec7da169..a238bdbf5c7c9 100644 --- a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/CSharp/CodeFixes/Microsoft.CodeAnalysis.CSharp.PerformanceSensitiveAnalyzers.CodeFixes.csproj +++ b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/CSharp/CodeFixes/Microsoft.CodeAnalysis.CSharp.PerformanceSensitiveAnalyzers.CodeFixes.csproj @@ -3,7 +3,6 @@ netstandard2.0 true - $(MicrosoftCodeAnalysisVersionForPerfSensitiveAnalyzers) @@ -12,9 +11,9 @@ - - - + + + diff --git a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/Core/ExplicitAllocationAnalyzer.cs b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/Core/ExplicitAllocationAnalyzer.cs index 9cf63be92a69f..2b2bc0b83769d 100644 --- a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/Core/ExplicitAllocationAnalyzer.cs +++ b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/Core/ExplicitAllocationAnalyzer.cs @@ -92,7 +92,7 @@ protected override void AnalyzeNode(OperationAnalysisContext context, in Perform if (context.Operation is IObjectCreationOperation or ITypeParameterObjectCreationOperation) { - if (context.Operation.Parent?.Kind == OperationKindEx.Attribute) + if (context.Operation.Parent?.Kind == OperationKind.Attribute) { // Don't report attribute usage as creating a new instance return; diff --git a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/Core/Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.csproj b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/Core/Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.csproj index 1fcfbcb1300ff..30340cb676d48 100644 --- a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/Core/Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.csproj +++ b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/Core/Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.csproj @@ -7,10 +7,11 @@ Restore would conclude that there is a cyclic dependency between us and the Microsoft.CodeAnalysis.PerformanceSensitive.Analyzers nuget package. --> *$(MSBuildProjectFile)* - $(MicrosoftCodeAnalysisVersionForPerfSensitiveAnalyzers) + Microsoft.CodeAnalysis - + + @@ -21,4 +22,13 @@ + + + + + + + + + diff --git a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/Core/PerformanceSensitiveAnalyzersResources.cs b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/Core/PerformanceSensitiveAnalyzersResources.cs index c08f6e061cb38..0bfcb38c4004d 100644 --- a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/Core/PerformanceSensitiveAnalyzersResources.cs +++ b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/Core/PerformanceSensitiveAnalyzersResources.cs @@ -4,7 +4,7 @@ using System; -namespace Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers +namespace Microsoft.CodeAnalysis { internal partial class PerformanceSensitiveAnalyzersResources { diff --git a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/AvoidAllocationWithArrayEmptyCodeFixTests.cs b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/AvoidAllocationWithArrayEmptyCodeFixTests.cs index fc9e515a2d0d6..8554fb4694795 100644 --- a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/AvoidAllocationWithArrayEmptyCodeFixTests.cs +++ b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/AvoidAllocationWithArrayEmptyCodeFixTests.cs @@ -3,543 +3,515 @@ // See the LICENSE file in the project root for more information. using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CSharp.PerformanceSensitiveAnalyzers.CodeFixes; using Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers; +using Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.UnitTests; using Xunit; -using VerifyCS = Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.UnitTests.CSharpPerformanceCodeFixVerifier< - Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.ExplicitAllocationAnalyzer, - Microsoft.CodeAnalysis.CSharp.PerformanceSensitiveAnalyzers.CodeFixes.AvoidAllocationWithArrayEmptyCodeFix>; -namespace Microsoft.CodeAnalysis.PerformanceSensitive.Analyzers.UnitTests -{ - public class AvoidAllocationWithArrayEmptyCodeFixTests - { - [Theory] - [InlineData("IEnumerable")] - [InlineData("IReadOnlyList")] - [InlineData("IReadOnlyCollection")] - public async Task ShouldReplaceEmptyListCreationWithArrayEmptyWithReturnTypeAsync(string type) - { - var initial = $@" -using System; -using System.Collections.Generic; -using Roslyn.Utilities; - -namespace SampleNamespace -{{ - class SampleClass - {{ - [PerformanceSensitive(""uri"")] - public {type} DoSomething() - {{ - return new List(); - }} - }} -}}"; - - var expected = $@" -using System; -using System.Collections.Generic; -using Roslyn.Utilities; - -namespace SampleNamespace -{{ - class SampleClass - {{ - [PerformanceSensitive(""uri"")] - public {type} DoSomething() - {{ - return Array.Empty(); - }} - }} -}}"; - await VerifyCS.VerifyCodeFixAsync(initial, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithSpan(13, 20, 13, 35), expected); - } - - [Fact] - public async Task ShouldReplaceEmptyListCreationWithArrayEmptyWhenReturnFromMethodArrayAsync() - { - var before = @" -using System; -using System.Collections.Generic; -using Roslyn.Utilities; - -namespace SampleNamespace -{ - class SampleClass - { - [PerformanceSensitive(""uri"")] - public int[] DoSomething() - { - return new int[0]; - } - } -}"; - var after = @" -using System; -using System.Collections.Generic; -using Roslyn.Utilities; - -namespace SampleNamespace -{ - class SampleClass - { - [PerformanceSensitive(""uri"")] - public int[] DoSomething() - { - return Array.Empty(); - } - } -}"; - - await VerifyCS.VerifyCodeFixAsync(before, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ArrayCreationRule).WithSpan(13, 20, 13, 30), after); - } - - [Fact] - public async Task ShouldReplaceEmptyLisCreationWithArrayEmptyForArrowExpressionAsync() - { - var before = @" -using System; -using System.Collections.Generic; -using Roslyn.Utilities; - -namespace SampleNamespace -{ - class SampleClass - { - [PerformanceSensitive(""uri"")] - public IEnumerable DoSomething => new List(); - } -}"; - var after = @" -using System; -using System.Collections.Generic; -using Roslyn.Utilities; +namespace Microsoft.CodeAnalysis.PerformanceSensitive.Analyzers.UnitTests; -namespace SampleNamespace -{ - class SampleClass - { - [PerformanceSensitive(""uri"")] - public IEnumerable DoSomething => Array.Empty(); - } -}"; - - await VerifyCS.VerifyCodeFixAsync(before, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithSpan(11, 48, 11, 63), after); - } - [Fact] - public async Task ShouldReplaceEmptyListCreationWithArrayEmptyForReadonlyPropertyAsync() - { - var before = @" -using System; -using System.Collections.Generic; -using Roslyn.Utilities; - -namespace SampleNamespace -{ - class SampleClass - { - [PerformanceSensitive(""uri"")] - public IEnumerable DoSomething { get {return new List();}} - } -}"; - var after = @" -using System; -using System.Collections.Generic; -using Roslyn.Utilities; - -namespace SampleNamespace -{ - class SampleClass - { - [PerformanceSensitive(""uri"")] - public IEnumerable DoSomething { get {return Array.Empty();}} - } -}"; - - await VerifyCS.VerifyCodeFixAsync(before, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithSpan(11, 59, 11, 74), after); - } - [Fact] - public async Task ShouldReplaceEmptyListWithCreationWithPredefinedSizeWithArrayEmptyAsync() - { - var before = @" -using System; -using System.Collections.Generic; -using Roslyn.Utilities; - -namespace SampleNamespace -{ - class SampleClass - { - [PerformanceSensitive(""uri"")] - public IEnumerable DoSomething() - { - return new List(10); - } - } -}"; - var after = @" -using System; -using System.Collections.Generic; -using Roslyn.Utilities; +using VerifyCS = CSharpPerformanceCodeFixVerifier< + ExplicitAllocationAnalyzer, + AvoidAllocationWithArrayEmptyCodeFix>; -namespace SampleNamespace +public class AvoidAllocationWithArrayEmptyCodeFixTests { - class SampleClass - { - [PerformanceSensitive(""uri"")] - public IEnumerable DoSomething() - { - return Array.Empty(); - } - } -}"; - - await VerifyCS.VerifyCodeFixAsync(before, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithSpan(13, 20, 13, 37), after); - } - [Fact] - public async Task ShouldNotProposeCodeFixWhenNonEmptyListCreatedAsync() - { - var code = @" -using System; -using System.Collections.Generic; -using Roslyn.Utilities; - -namespace SampleNamespace -{ - class SampleClass - { - [PerformanceSensitive(""uri"")] - public IEnumerable DoSomething() - { - return new List(){1, 2}; - } - } -}"; - - await VerifyCS.VerifyCodeFixAsync(code, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithSpan(13, 20, 13, 41), code); - } - [Fact] - public async Task ShouldNotProposeCodeFixWhenReturnTypeInheritFormEnumerableAsync() - { - var code = @" -using System; -using System.Collections.Generic; -using Roslyn.Utilities; - -namespace SampleNamespace -{ - class SampleClass - { - [PerformanceSensitive(""uri"")] - public List DoSomething() - { - return new List(); - } - } -}"; - - await VerifyCS.VerifyCodeFixAsync(code, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithSpan(13, 20, 13, 35), code); - } - [Fact] - public async Task ShouldNotProposeCodeFixWhenForCollectionCreationUsingCopyConstructorAsync() - { - var code = @" -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using Roslyn.Utilities; - -namespace SampleNamespace -{ - class SampleClass - { - [PerformanceSensitive(""uri"")] - public IEnumerable DoSomething() - { - var innerList = new List(){1, 2}; - return new ReadOnlyCollection(innerList); - } - } -}"; - - await VerifyCS.VerifyCodeFixAsync(code, - new[] + [Theory] + [InlineData("IEnumerable")] + [InlineData("IReadOnlyList")] + [InlineData("IReadOnlyCollection")] + public Task ShouldReplaceEmptyListCreationWithArrayEmptyWithReturnTypeAsync(string type) + => VerifyCS.VerifyCodeFixAsync($$""" + using System; + using System.Collections.Generic; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass { - VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithSpan(14, 29, 14, 50), - VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithSpan(15, 20, 15, 58), - }, code); - } - [Fact] - public async Task ShouldReplacEmptyCollectionCreationWithArrayEmptyAsync() - { - var before = @" -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using Roslyn.Utilities; - -namespace SampleNamespace -{ - class SampleClass - { - [PerformanceSensitive(""uri"")] - public IEnumerable DoSomething() - { - return new Collection(); - } - } -}"; - var after = @" -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using Roslyn.Utilities; - -namespace SampleNamespace -{ - class SampleClass - { - [PerformanceSensitive(""uri"")] - public IEnumerable DoSomething() - { - return Array.Empty(); - } - } -}"; - - await VerifyCS.VerifyCodeFixAsync(before, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithSpan(14, 20, 14, 41), after); - } - [Fact] - public async Task ShouldReplaceEmptyArrayCreationWithArrayEmptyAsync() - { - var before = @" -using System; -using System.Collections.Generic; -using Roslyn.Utilities; - -namespace SampleNamespace -{ - class SampleClass - { - [PerformanceSensitive(""uri"")] - public IEnumerable DoSomething() - { - return new int[0]; - } - } -}"; - var after = @" -using System; -using System.Collections.Generic; -using Roslyn.Utilities; - -namespace SampleNamespace -{ - class SampleClass - { - [PerformanceSensitive(""uri"")] - public IEnumerable DoSomething() - { - return Array.Empty(); - } - } -}"; - - await VerifyCS.VerifyCodeFixAsync(before, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ArrayCreationRule).WithSpan(13, 20, 13, 30), after); - } - [Fact] - public async Task ShouldNotProposeCodeFixWhenNonEmptyArrayCreationAsync() - { - var code = @" -using System; -using System.Collections.Generic; -using Roslyn.Utilities; - -namespace SampleNamespace -{ - class SampleClass - { - [PerformanceSensitive(""uri"")] - public IEnumerable DoSomething() - { - return new int[]{1, 2}; - } - } -}"; - - await VerifyCS.VerifyCodeFixAsync(code, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ArrayCreationRule).WithSpan(13, 20, 13, 35), code); - } - [Fact] - public async Task ShouldReplaceEmptyArrayCreationWithInitBlockWithArrayEmptyAsync() - { - var before = @" -using System; -using System.Collections.Generic; -using Roslyn.Utilities; - -namespace SampleNamespace -{ - class SampleClass - { - [PerformanceSensitive(""uri"")] - public IEnumerable DoSomething() - { - return new int[] { }; - } - } -}"; - var after = @" -using System; -using System.Collections.Generic; -using Roslyn.Utilities; - -namespace SampleNamespace -{ - class SampleClass - { - [PerformanceSensitive(""uri"")] - public IEnumerable DoSomething() - { - return Array.Empty(); - } - } -}"; - - await VerifyCS.VerifyCodeFixAsync(before, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ArrayCreationRule).WithSpan(13, 20, 13, 33), after); - } - [Fact] - public async Task ShouldReplaceListCreationAsMethodInvocationParameterWithArrayEmptyAsync() - { - var before = @" -using System; -using System.Collections.Generic; -using Roslyn.Utilities; - -namespace SampleNamespace -{ - class SampleClass - { - [PerformanceSensitive(""uri"")] - public void DoSomething() - { - Do(new List()); - } - - private void Do(IEnumerable a) - { - - } - } -}"; - var after = @" -using System; -using System.Collections.Generic; -using Roslyn.Utilities; - -namespace SampleNamespace -{ - class SampleClass - { - [PerformanceSensitive(""uri"")] - public void DoSomething() - { - Do(Array.Empty()); - } - - private void Do(IEnumerable a) - { - - } - } -}"; - - await VerifyCS.VerifyCodeFixAsync(before, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithSpan(13, 16, 13, 31), after); - } - [Fact] - public async Task ShouldReplaceArrayCreationAsMethodInvocationParameterWithArrayEmptyAsync() - { - var before = @" -using System; -using System.Collections.Generic; -using Roslyn.Utilities; - -namespace SampleNamespace -{ - class SampleClass + [PerformanceSensitive("uri")] + public {{type}} DoSomething() + { + return new List(); + } + } + } + """, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithSpan(12, 20, 12, 35), $$""" + using System; + using System.Collections.Generic; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public {{type}} DoSomething() + { + return Array.Empty(); + } + } + } + """); + + [Fact] + public Task ShouldReplaceEmptyListCreationWithArrayEmptyWhenReturnFromMethodArrayAsync() + => VerifyCS.VerifyCodeFixAsync(""" + using System; + using System.Collections.Generic; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public int[] DoSomething() + { + return new int[0]; + } + } + } + """, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ArrayCreationRule).WithSpan(12, 20, 12, 30), """ + using System; + using System.Collections.Generic; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public int[] DoSomething() + { + return Array.Empty(); + } + } + } + """); + + [Fact] + public Task ShouldReplaceEmptyLisCreationWithArrayEmptyForArrowExpressionAsync() + => VerifyCS.VerifyCodeFixAsync(""" + using System; + using System.Collections.Generic; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public IEnumerable DoSomething => new List(); + } + } + """, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithSpan(10, 48, 10, 63), """ + using System; + using System.Collections.Generic; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public IEnumerable DoSomething => Array.Empty(); + } + } + """); + [Fact] + public Task ShouldReplaceEmptyListCreationWithArrayEmptyForReadonlyPropertyAsync() + => VerifyCS.VerifyCodeFixAsync(""" + using System; + using System.Collections.Generic; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public IEnumerable DoSomething { get {return new List();}} + } + } + """, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithSpan(10, 59, 10, 74), """ + using System; + using System.Collections.Generic; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public IEnumerable DoSomething { get {return Array.Empty();}} + } + } + """); + [Fact] + public Task ShouldReplaceEmptyListWithCreationWithPredefinedSizeWithArrayEmptyAsync() + => VerifyCS.VerifyCodeFixAsync(""" + using System; + using System.Collections.Generic; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public IEnumerable DoSomething() + { + return new List(10); + } + } + } + """, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithSpan(12, 20, 12, 37), """ + using System; + using System.Collections.Generic; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public IEnumerable DoSomething() + { + return Array.Empty(); + } + } + } + """); + [Fact] + public async Task ShouldNotProposeCodeFixWhenNonEmptyListCreatedAsync() { - [PerformanceSensitive(""uri"")] - public void DoSomething() - { - Do(new int[0]); - } - - private void Do(IEnumerable a) - { - - } + var code = """ + using System; + using System.Collections.Generic; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public IEnumerable DoSomething() + { + return new List(){1, 2}; + } + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithSpan(12, 20, 12, 41), code); } -}"; - var after = @" -using System; -using System.Collections.Generic; -using Roslyn.Utilities; - -namespace SampleNamespace -{ - class SampleClass + [Fact] + public async Task ShouldNotProposeCodeFixWhenReturnTypeInheritFormEnumerableAsync() { - [PerformanceSensitive(""uri"")] - public void DoSomething() - { - Do(Array.Empty()); - } - - private void Do(IEnumerable a) - { - - } + var code = """ + using System; + using System.Collections.Generic; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public List DoSomething() + { + return new List(); + } + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithSpan(12, 20, 12, 35), code); } -}"; - - await VerifyCS.VerifyCodeFixAsync(before, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ArrayCreationRule).WithSpan(13, 16, 13, 26), after); - } - [Fact] - public async Task ShouldReplaceArrayCreationAsDelegateInvocationParameterWithArrayEmptyAsync() - { - var before = @" -using System; -using System.Collections.Generic; -using Roslyn.Utilities; - -namespace SampleNamespace -{ - class SampleClass + [Fact] + public async Task ShouldNotProposeCodeFixWhenForCollectionCreationUsingCopyConstructorAsync() { - [PerformanceSensitive(""uri"")] - public void DoSomething(Action> doSth) - { - doSth(new int[0]); - } + var code = """ + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public IEnumerable DoSomething() + { + var innerList = new List(){1, 2}; + return new ReadOnlyCollection(innerList); + } + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, + [ + VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithSpan(13, 29, 13, 50), + VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithSpan(14, 20, 14, 58), + ], code); } -}"; - var after = @" -using System; -using System.Collections.Generic; -using Roslyn.Utilities; - -namespace SampleNamespace -{ - class SampleClass + [Fact] + public Task ShouldReplacEmptyCollectionCreationWithArrayEmptyAsync() + => VerifyCS.VerifyCodeFixAsync(""" + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public IEnumerable DoSomething() + { + return new Collection(); + } + } + } + """, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithSpan(13, 20, 13, 41), """ + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public IEnumerable DoSomething() + { + return Array.Empty(); + } + } + } + """); + [Fact] + public Task ShouldReplaceEmptyArrayCreationWithArrayEmptyAsync() + => VerifyCS.VerifyCodeFixAsync(""" + using System; + using System.Collections.Generic; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public IEnumerable DoSomething() + { + return new int[0]; + } + } + } + """, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ArrayCreationRule).WithSpan(12, 20, 12, 30), """ + using System; + using System.Collections.Generic; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public IEnumerable DoSomething() + { + return Array.Empty(); + } + } + } + """); + [Fact] + public async Task ShouldNotProposeCodeFixWhenNonEmptyArrayCreationAsync() { - [PerformanceSensitive(""uri"")] - public void DoSomething(Action> doSth) - { - doSth(Array.Empty()); - } - } -}"; - - await VerifyCS.VerifyCodeFixAsync(before, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ArrayCreationRule).WithSpan(13, 19, 13, 29), after); - } + var code = """ + using System; + using System.Collections.Generic; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public IEnumerable DoSomething() + { + return new int[]{1, 2}; + } + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ArrayCreationRule).WithSpan(12, 20, 12, 35), code); } + [Fact] + public Task ShouldReplaceEmptyArrayCreationWithInitBlockWithArrayEmptyAsync() + => VerifyCS.VerifyCodeFixAsync(""" + using System; + using System.Collections.Generic; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public IEnumerable DoSomething() + { + return new int[] { }; + } + } + } + """, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ArrayCreationRule).WithSpan(12, 20, 12, 33), """ + using System; + using System.Collections.Generic; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public IEnumerable DoSomething() + { + return Array.Empty(); + } + } + } + """); + [Fact] + public Task ShouldReplaceListCreationAsMethodInvocationParameterWithArrayEmptyAsync() + => VerifyCS.VerifyCodeFixAsync(""" + using System; + using System.Collections.Generic; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public void DoSomething() + { + Do(new List()); + } + + private void Do(IEnumerable a) + { + + } + } + } + """, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithSpan(12, 16, 12, 31), """ + using System; + using System.Collections.Generic; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public void DoSomething() + { + Do(Array.Empty()); + } + + private void Do(IEnumerable a) + { + + } + } + } + """); + [Fact] + public Task ShouldReplaceArrayCreationAsMethodInvocationParameterWithArrayEmptyAsync() + => VerifyCS.VerifyCodeFixAsync(""" + using System; + using System.Collections.Generic; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public void DoSomething() + { + Do(new int[0]); + } + + private void Do(IEnumerable a) + { + + } + } + } + """, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ArrayCreationRule).WithSpan(12, 16, 12, 26), """ + using System; + using System.Collections.Generic; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public void DoSomething() + { + Do(Array.Empty()); + } + + private void Do(IEnumerable a) + { + + } + } + } + """); + [Fact] + public Task ShouldReplaceArrayCreationAsDelegateInvocationParameterWithArrayEmptyAsync() + => VerifyCS.VerifyCodeFixAsync(""" + using System; + using System.Collections.Generic; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public void DoSomething(Action> doSth) + { + doSth(new int[0]); + } + } + } + """, VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ArrayCreationRule).WithSpan(12, 19, 12, 29), """ + using System; + using System.Collections.Generic; + using Roslyn.Utilities; + + namespace SampleNamespace + { + class SampleClass + { + [PerformanceSensitive("uri")] + public void DoSomething(Action> doSth) + { + doSth(Array.Empty()); + } + } + } + """); } diff --git a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/CSharpPerformanceCodeFixVerifier`2.cs b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/CSharpPerformanceCodeFixVerifier`2.cs index df37773c89e70..b408fbb8f9d37 100644 --- a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/CSharpPerformanceCodeFixVerifier`2.cs +++ b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/CSharpPerformanceCodeFixVerifier`2.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Testing; @@ -16,31 +17,32 @@ public static partial class CSharpPerformanceCodeFixVerifier CSharpCodeFixVerifier.Diagnostic(); @@ -51,7 +53,8 @@ public static DiagnosticResult Diagnostic(string diagnosticId) public static DiagnosticResult Diagnostic(DiagnosticDescriptor descriptor) => CSharpCodeFixVerifier.Diagnostic(descriptor); - public static async Task VerifyAnalyzerAsync(string source, params DiagnosticResult[] expected) + public static async Task VerifyAnalyzerAsync( + [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string source, params DiagnosticResult[] expected) { var test = new Test { @@ -69,13 +72,21 @@ public static async Task VerifyAnalyzerAsync(string source, params DiagnosticRes await test.RunAsync(); } - public static Task VerifyCodeFixAsync(string source, string fixedSource) + public static Task VerifyCodeFixAsync( + [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string source, + [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string fixedSource) => VerifyCodeFixAsync(source, DiagnosticResult.EmptyDiagnosticResults, fixedSource); - public static Task VerifyCodeFixAsync(string source, DiagnosticResult expected, string fixedSource) - => VerifyCodeFixAsync(source, new[] { expected }, fixedSource); + public static Task VerifyCodeFixAsync( + [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string source, + DiagnosticResult expected, + [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string fixedSource) + => VerifyCodeFixAsync(source, [expected], fixedSource); - public static async Task VerifyCodeFixAsync(string source, DiagnosticResult[] expected, string fixedSource) + public static async Task VerifyCodeFixAsync( + [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string source, + DiagnosticResult[] expected, + [StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string fixedSource) { var test = new Test { diff --git a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/CallSiteImplicitAllocationAnalyzerTests.cs b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/CallSiteImplicitAllocationAnalyzerTests.cs index e55f42813baee..5ed9549069443 100644 --- a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/CallSiteImplicitAllocationAnalyzerTests.cs +++ b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/CallSiteImplicitAllocationAnalyzerTests.cs @@ -4,223 +4,204 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.PerformanceSensitiveAnalyzers; +using Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.UnitTests; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; -using VerifyCS = Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.UnitTests.CSharpPerformanceCodeFixVerifier< - Microsoft.CodeAnalysis.CSharp.PerformanceSensitiveAnalyzers.CallSiteImplicitAllocationAnalyzer, - Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; -namespace Microsoft.CodeAnalysisPerformanceSensitiveAnalyzers.UnitTests -{ - public class CallSiteImplicitAllocationAnalyzerTests - { - [Fact] - public async Task CallSiteImplicitAllocation_ParamAsync() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; +namespace Microsoft.CodeAnalysisPerformanceSensitiveAnalyzers.UnitTests; + +using VerifyCS = CSharpPerformanceCodeFixVerifier< + CallSiteImplicitAllocationAnalyzer, + EmptyCodeFixProvider>; -public class MyClass +public sealed class CallSiteImplicitAllocationAnalyzerTests { - [PerformanceSensitive(""uri"")] - public void Testing() - { - - Params(); //no allocation, because compiler will implicitly substitute Array.Empty() - Params(1, 2); - Params(new [] { 1, 2}); // explicit, so no warning - ParamsWithObjects(new [] { 1, 2}); // explicit, but converted to objects, so stil la warning?! - - // Only 4 args and above use the params overload of String.Format - var test = String.Format(""Testing {0}, {1}, {2}, {3}"", 1, ""blah"", 2.0m, 'c'); - } - - public void Params(params int[] args) - { - } - - public void ParamsWithObjects(params object[] args) - { - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, - // Test0.cs(11,9): warning HAA0101: This call site is calling into a function with a 'params' parameter. This results in an array allocation + [Fact] + public Task CallSiteImplicitAllocation_ParamAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + { + + Params(); //no allocation, because compiler will implicitly substitute Array.Empty() + Params(1, 2); + Params(new [] { 1, 2}); // explicit, so no warning + ParamsWithObjects(new [] { 1, 2}); // explicit, but converted to objects, so stil la warning?! + + // Only 4 args and above use the params overload of String.Format + var test = String.Format("Testing {0}, {1}, {2}, {3}", 1, "blah", 2.0m, 'c'); + } + + public void Params(params int[] args) + { + } + + public void ParamsWithObjects(params object[] args) + { + } + } + """, + // Test0.cs(11,9): warning HAA0101: This call site is calling into a function with a 'params' parameter. This results in an array allocation #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(CallSiteImplicitAllocationAnalyzer.ParamsParameterRule).WithLocation(11, 9), + VerifyCS.Diagnostic(CallSiteImplicitAllocationAnalyzer.ParamsParameterRule).WithLocation(11, 9), #pragma warning restore RS0030 // Do not use banned APIs - // Test0.cs(13,9): warning HAA0101: This call site is calling into a function with a 'params' parameter. This results in an array allocation + // Test0.cs(13,9): warning HAA0101: This call site is calling into a function with a 'params' parameter. This results in an array allocation #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(CallSiteImplicitAllocationAnalyzer.ParamsParameterRule).WithLocation(13, 9), + VerifyCS.Diagnostic(CallSiteImplicitAllocationAnalyzer.ParamsParameterRule).WithLocation(13, 9), #pragma warning restore RS0030 // Do not use banned APIs - // Test0.cs(16,20): warning HAA0101: This call site is calling into a function with a 'params' parameter. This results in an array allocation + // Test0.cs(16,20): warning HAA0101: This call site is calling into a function with a 'params' parameter. This results in an array allocation #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(CallSiteImplicitAllocationAnalyzer.ParamsParameterRule).WithLocation(16, 20)); -#pragma warning restore RS0030 // Do not use banned APIs - } + VerifyCS.Diagnostic(CallSiteImplicitAllocationAnalyzer.ParamsParameterRule).WithLocation(16, 20)); - [Fact, WorkItem(3272, "https://github.com/dotnet/roslyn-analyzers/issues/3272")] - public async Task EmptyParamsWithNetFramework45Async() + [Fact, WorkItem(3272, "https://github.com/dotnet/roslyn-analyzers/issues/3272")] + public Task EmptyParamsWithNetFramework45Async() + => new VerifyCS.Test { - await new VerifyCS.Test + ReferenceAssemblies = ReferenceAssemblies.NetFramework.Net45.Default, + TestState = { - ReferenceAssemblies = ReferenceAssemblies.NetFramework.Net45.Default, - TestState = + Sources = { - Sources = - { - @" -using System; -using Roslyn.Utilities; + """ + using System; + using Roslyn.Utilities; -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - Params(); // allocation - } - - public void Params(params int[] args) - { - } -}", - ("PerformanceSensitiveAttribute.cs", VerifyCS.PerformanceSensitiveAttributeSource) - }, - ExpectedDiagnostics = + public class MyClass { + [PerformanceSensitive("uri")] + public void Testing() + { + Params(); // allocation + } + + public void Params(params int[] args) + { + } + } + """, + ("PerformanceSensitiveAttribute.cs", VerifyCS.PerformanceSensitiveAttributeSource) + }, + ExpectedDiagnostics = + { #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(CallSiteImplicitAllocationAnalyzer.ParamsParameterRule).WithLocation(10, 9), + VerifyCS.Diagnostic(CallSiteImplicitAllocationAnalyzer.ParamsParameterRule).WithLocation(9, 9), #pragma warning restore RS0030 // Do not use banned APIs - }, }, - }.RunAsync(); - } + }, + }.RunAsync(); - [Fact] - public async Task CallSiteImplicitAllocation_NonOverridenMethodOnStructAsync() - { - var sampleProgram = @" -using System; -using Roslyn.Utilities; + [Fact] + public Task CallSiteImplicitAllocation_NonOverridenMethodOnStructAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - var normal = new Normal().GetHashCode(); - var overridden = new OverrideToHashCode().GetHashCode(); - } -} + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + { + var normal = new Normal().GetHashCode(); + var overridden = new OverrideToHashCode().GetHashCode(); + } + } -public struct Normal -{ -} + public struct Normal + { + } -public struct OverrideToHashCode -{ - public override int GetHashCode() - { - return -1; - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, - // Test0.cs(10,22): warning HAA0102: Non-overridden virtual method call on a value type adds a boxing or constrained instruction + public struct OverrideToHashCode + { + public override int GetHashCode() + { + return -1; + } + } + """, + // Test0.cs(10,22): warning HAA0102: Non-overridden virtual method call on a value type adds a boxing or constrained instruction #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(CallSiteImplicitAllocationAnalyzer.ValueTypeNonOverridenCallRule).WithLocation(10, 22)); -#pragma warning restore RS0030 // Do not use banned APIs - } + VerifyCS.Diagnostic(CallSiteImplicitAllocationAnalyzer.ValueTypeNonOverridenCallRule).WithLocation(9, 22)); - [Fact] - public async Task CallSiteImplicitAllocation_DoNotReportNonOverriddenMethodCallForStaticCallsAsync() - { - var sampleProgram = @" -using System; -using Roslyn.Utilities; + [Fact] + public Task CallSiteImplicitAllocation_DoNotReportNonOverriddenMethodCallForStaticCallsAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - var t = System.Enum.GetUnderlyingType(typeof(System.StringComparison)); - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram); - } - - [Fact] - public async Task CallSiteImplicitAllocation_DoNotReportNonOverriddenMethodCallForNonVirtualCallsAsync() - { - var sampleProgram = @" -using System.IO; -using Roslyn.Utilities; + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + { + var t = System.Enum.GetUnderlyingType(typeof(System.StringComparison)); + } + } + """); + + [Fact] + public Task CallSiteImplicitAllocation_DoNotReportNonOverriddenMethodCallForNonVirtualCallsAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System.IO; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + { + FileAttributes attr = FileAttributes.System; + attr.HasFlag (FileAttributes.Directory); + } + } + """); + + [Fact] + public Task ParamsIsPrecededByOptionalParametersAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System.IO; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + void Fun1() + { + Fun2(); + {|#0:Fun2(args: "", i: 5)|}; + } -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - FileAttributes attr = FileAttributes.System; - attr.HasFlag (FileAttributes.Directory); - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(sampleProgram); - } - - [Fact] - public async Task ParamsIsPrecededByOptionalParametersAsync() - { - var sampleProgram = @" -using System.IO; -using Roslyn.Utilities; + void Fun2(int i = 0, params object[] args) + { + } + } + """, + VerifyCS.Diagnostic(CallSiteImplicitAllocationAnalyzer.ParamsParameterRule).WithLocation(0)); -public class MyClass -{ - [PerformanceSensitive(""uri"")] - void Fun1() - { - Fun2(); - {|#0:Fun2(args: """", i: 5)|}; - } - - void Fun2(int i = 0, params object[] args) - { - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, - VerifyCS.Diagnostic(CallSiteImplicitAllocationAnalyzer.ParamsParameterRule).WithLocation(0)); - } - - [Fact] - [WorkItem(7995606, "http://stackoverflow.com/questions/7995606/boxing-occurrence-in-c-sharp")] - public async Task Calling_non_overridden_virtual_methods_on_value_typesAsync() - { - var source = @" -using System; -using Roslyn.Utilities; + [Fact] + [WorkItem(7995606, "http://stackoverflow.com/questions/7995606/boxing-occurrence-in-c-sharp")] + public Task Calling_non_overridden_virtual_methods_on_value_typesAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; -enum E { A } + enum E { A } -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void SomeMethod() - { - E.A.GetHashCode(); - } -}"; - await VerifyCS.VerifyAnalyzerAsync(source, - // Test0.cs(12,9): warning HAA0102: Non-overridden virtual method call on a value type adds a boxing or constrained instruction + public class MyClass + { + [PerformanceSensitive("uri")] + public void SomeMethod() + { + E.A.GetHashCode(); + } + } + """, + // Test0.cs(12,9): warning HAA0102: Non-overridden virtual method call on a value type adds a boxing or constrained instruction #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(CallSiteImplicitAllocationAnalyzer.ValueTypeNonOverridenCallRule).WithLocation(12, 9)); -#pragma warning restore RS0030 // Do not use banned APIs - } - } + VerifyCS.Diagnostic(CallSiteImplicitAllocationAnalyzer.ValueTypeNonOverridenCallRule).WithLocation(11, 9)); } diff --git a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/ConcatenationAllocationAnalyzerTests.cs b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/ConcatenationAllocationAnalyzerTests.cs index 9553de2ab5d4b..680e1420ebbcb 100644 --- a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/ConcatenationAllocationAnalyzerTests.cs +++ b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/ConcatenationAllocationAnalyzerTests.cs @@ -4,120 +4,111 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.PerformanceSensitiveAnalyzers; +using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; -using VerifyCS = Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.UnitTests.CSharpPerformanceCodeFixVerifier< - Microsoft.CodeAnalysis.CSharp.PerformanceSensitiveAnalyzers.ConcatenationAllocationAnalyzer, - Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; -namespace Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.UnitTests -{ - public class ConcatenationAllocationAnalyzerTests - { - [Fact] - public async Task ConcatenationAllocation_Basic1Async() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; +namespace Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.UnitTests; + +using VerifyCS = CSharpPerformanceCodeFixVerifier< + ConcatenationAllocationAnalyzer, + EmptyCodeFixProvider>; -public class MyClass +public sealed class ConcatenationAllocationAnalyzerTests { - [PerformanceSensitive(""uri"")] - public void Testing() - { - string s0 = ""hello"" + 0.ToString() + ""world"" + 1.ToString(); - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram); - } + [Fact] + public Task ConcatenationAllocation_Basic1Async() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; - [Fact] - public async Task ConcatenationAllocation_Basic2Async() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + { + string s0 = "hello" + 0.ToString() + "world" + 1.ToString(); + } + } + """); -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - string s2 = ""ohell"" + 2.ToString() + ""world"" + 3.ToString() + 4.ToString(); - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, - // Test0.cs(9,21): warning HAA0201: Considering using StringBuilder + [Fact] + public Task ConcatenationAllocation_Basic2Async() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + { + string s2 = "ohell" + 2.ToString() + "world" + 3.ToString() + 4.ToString(); + } + } + """, + // Test0.cs(9,21): warning HAA0201: Considering using StringBuilder #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(ConcatenationAllocationAnalyzer.StringConcatenationAllocationRule).WithLocation(9, 21)); -#pragma warning restore RS0030 // Do not use banned APIs - } + VerifyCS.Diagnostic(ConcatenationAllocationAnalyzer.StringConcatenationAllocationRule).WithLocation(9, 21)); - [Theory] - [InlineData("string s0 = nameof(System.String) + '-';")] - [InlineData("string s0 = nameof(System.String) + true;")] - [InlineData("string s0 = nameof(System.String) + new System.IntPtr();")] - [InlineData("string s0 = nameof(System.String) + new System.UIntPtr();")] - public async Task ConcatenationAllocation_DoNotWarnForOptimizedValueTypesAsync(string statement) - { - var source = $@"using System; -using Roslyn.Utilities; + [Theory] + [InlineData("string s0 = nameof(System.String) + '-';")] + [InlineData("string s0 = nameof(System.String) + true;")] + [InlineData("string s0 = nameof(System.String) + new System.IntPtr();")] + [InlineData("string s0 = nameof(System.String) + new System.UIntPtr();")] + public Task ConcatenationAllocation_DoNotWarnForOptimizedValueTypesAsync(string statement) + => VerifyCS.VerifyAnalyzerAsync($$""" + using System; + using Roslyn.Utilities; -public class MyClass -{{ - [PerformanceSensitive(""uri"")] - public void Testing() - {{ - {statement} - }} -}}"; - await VerifyCS.VerifyAnalyzerAsync(source); - } + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + { + {{statement}} + } + } + """); - [Theory] - [InlineData(@"const string s0 = nameof(System.String) + ""."" + nameof(System.String);")] - [InlineData(@"const string s0 = nameof(System.String) + ""."";")] - [InlineData(@"string s0 = nameof(System.String) + ""."" + nameof(System.String);")] - [InlineData(@"string s0 = nameof(System.String) + ""."";")] - public async Task ConcatenationAllocation_DoNotWarnForConstAsync(string statement) - { - var source = $@"using System; -using Roslyn.Utilities; + [Theory] + [InlineData(@"const string s0 = nameof(System.String) + ""."" + nameof(System.String);")] + [InlineData(@"const string s0 = nameof(System.String) + ""."";")] + [InlineData(@"string s0 = nameof(System.String) + ""."" + nameof(System.String);")] + [InlineData(@"string s0 = nameof(System.String) + ""."";")] + public Task ConcatenationAllocation_DoNotWarnForConstAsync(string statement) + => VerifyCS.VerifyAnalyzerAsync($$""" + using System; + using Roslyn.Utilities; -public class MyClass -{{ - [PerformanceSensitive(""uri"")] - public void Testing() - {{ - {statement} - }} -}}"; - await VerifyCS.VerifyAnalyzerAsync(source); - } + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + { + {{statement}} + } + } + """); - [Fact] - [WorkItem(7995606, "http://stackoverflow.com/questions/7995606/boxing-occurrence-in-c-sharp")] - public async Task Non_constant_value_types_in_CSharp_string_concatenationAsync() - { - var source = @" -using System; -using Roslyn.Utilities; + [Fact] + [WorkItem(7995606, "http://stackoverflow.com/questions/7995606/boxing-occurrence-in-c-sharp")] + public Task Non_constant_value_types_in_CSharp_string_concatenationAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void SomeMethod() - { - System.DateTime c = System.DateTime.Now; - string s1 = ""char value will box"" + c; - } -}"; - await VerifyCS.VerifyAnalyzerAsync(source, - // Test0.cs(11,45): warning HAA0202: Value type (System.DateTime) is being boxed to a reference type for a string concatenation. + public class MyClass + { + [PerformanceSensitive("uri")] + public void SomeMethod() + { + System.DateTime c = System.DateTime.Now; + string s1 = "char value will box" + c; + } + } + """, + // Test0.cs(11,45): warning HAA0202: Value type (System.DateTime) is being boxed to a reference type for a string concatenation. #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(ConcatenationAllocationAnalyzer.ValueTypeToReferenceTypeInAStringConcatenationRule).WithLocation(11, 45).WithArguments("System.DateTime")); -#pragma warning restore RS0030 // Do not use banned APIs - } - } + VerifyCS.Diagnostic(ConcatenationAllocationAnalyzer.ValueTypeToReferenceTypeInAStringConcatenationRule).WithLocation(10, 45).WithArguments("System.DateTime")); } diff --git a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/DisplayClassAllocationAnalyzerTests.cs b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/DisplayClassAllocationAnalyzerTests.cs index 6e43176009d5f..8c0f431e85aa6 100644 --- a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/DisplayClassAllocationAnalyzerTests.cs +++ b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/DisplayClassAllocationAnalyzerTests.cs @@ -4,181 +4,166 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.PerformanceSensitiveAnalyzers; +using Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.UnitTests; +using Microsoft.CodeAnalysis.Testing; using Xunit; -using VerifyCS = Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.UnitTests.CSharpPerformanceCodeFixVerifier< - Microsoft.CodeAnalysis.CSharp.PerformanceSensitiveAnalyzers.DisplayClassAllocationAnalyzer, - Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; -namespace Microsoft.CodeAnalysis.PerformanceSensitive.Analyzers.UnitTests -{ - public class DisplayClassAllocationAnalyzerTests - { - [Fact] - public async Task DisplayClassAllocation_AnonymousMethodExpressionSyntaxAsync() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; - -class Test +namespace Microsoft.CodeAnalysis.PerformanceSensitive.Analyzers.UnitTests; + +using VerifyCS = CSharpPerformanceCodeFixVerifier< + DisplayClassAllocationAnalyzer, + EmptyCodeFixProvider>; + +public sealed class DisplayClassAllocationAnalyzerTests { - static void Main() - { - Action action = CreateAction(5); - } - - [PerformanceSensitive(""uri"")] - static Action CreateAction(T item) - { - T test = default(T); - int counter = 0; - return delegate - { - counter++; - Console.WriteLine(""counter={0}"", counter); - }; - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, - // Test0.cs(15,13): warning HAA0302: The compiler will emit a class that will hold this as a field to allow capturing of this closure + [Fact] + public Task DisplayClassAllocation_AnonymousMethodExpressionSyntaxAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + class Test + { + static void Main() + { + Action action = CreateAction(5); + } + + [PerformanceSensitive("uri")] + static Action CreateAction(T item) + { + T test = default(T); + int counter = 0; + return delegate + { + counter++; + Console.WriteLine("counter={0}", counter); + }; + } + } + """, + // Test0.cs(15,13): warning HAA0302: The compiler will emit a class that will hold this as a field to allow capturing of this closure #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(DisplayClassAllocationAnalyzer.ClosureCaptureRule).WithLocation(15, 13), + VerifyCS.Diagnostic(DisplayClassAllocationAnalyzer.ClosureCaptureRule).WithLocation(15, 13), #pragma warning restore RS0030 // Do not use banned APIs - // Test0.cs(16,16): warning HAA0303: Considering moving this out of the generic method + // Test0.cs(16,16): warning HAA0303: Considering moving this out of the generic method #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(DisplayClassAllocationAnalyzer.LambaOrAnonymousMethodInGenericMethodRule).WithLocation(16, 16), + VerifyCS.Diagnostic(DisplayClassAllocationAnalyzer.LambaOrAnonymousMethodInGenericMethodRule).WithLocation(16, 16), #pragma warning restore RS0030 // Do not use banned APIs - // Test0.cs(16,16): warning HAA0301: Heap allocation of closure Captures: counter + // Test0.cs(16,16): warning HAA0301: Heap allocation of closure Captures: counter #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(DisplayClassAllocationAnalyzer.ClosureDriverRule).WithLocation(16, 16).WithArguments("counter")); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task DisplayClassAllocation_SimpleLambdaExpressionSyntaxAsync() - { - var sampleProgram = -@"using System.Collections.Generic; -using System; -using System.Linq; -using Roslyn.Utilities; - -public class Testing -{ - [PerformanceSensitive(""uri"")] - public Testing() - { - int[] intData = new[] { 123, 32, 4 }; - int min = 31; - var results = intData.Where(i => i > min).ToList(); - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, - // Test0.cs(12,13): warning HAA0302: The compiler will emit a class that will hold this as a field to allow capturing of this closure + VerifyCS.Diagnostic(DisplayClassAllocationAnalyzer.ClosureDriverRule).WithLocation(16, 16).WithArguments("counter")); + + [Fact] + public Task DisplayClassAllocation_SimpleLambdaExpressionSyntaxAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System.Collections.Generic; + using System; + using System.Linq; + using Roslyn.Utilities; + + public class Testing + { + [PerformanceSensitive("uri")] + public Testing() + { + int[] intData = new[] { 123, 32, 4 }; + int min = 31; + var results = intData.Where(i => i > min).ToList(); + } + } + """, + // Test0.cs(12,13): warning HAA0302: The compiler will emit a class that will hold this as a field to allow capturing of this closure #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(DisplayClassAllocationAnalyzer.ClosureCaptureRule).WithLocation(12, 13), + VerifyCS.Diagnostic(DisplayClassAllocationAnalyzer.ClosureCaptureRule).WithLocation(12, 13), #pragma warning restore RS0030 // Do not use banned APIs - // Test0.cs(13,39): warning HAA0301: Heap allocation of closure Captures: min + // Test0.cs(13,39): warning HAA0301: Heap allocation of closure Captures: min #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(DisplayClassAllocationAnalyzer.ClosureDriverRule).WithLocation(13, 39).WithArguments("min")); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task DisplayClassAllocation_ParenthesizedLambdaExpressionSyntaxAsync() - { - var sampleProgram = -@"using System.Collections.Generic; -using System; -using System.Linq; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void SomeMethod() - { - var words = new[] { ""aaaa"", ""bbbb"", ""cccc"", ""ddd"" }; - var actions = new List(); - foreach (string word in words) // <-- captured closure - { - actions.Add(() => Console.WriteLine(word)); // <-- reason for closure capture - } - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, - // Test0.cs(13,25): warning HAA0302: The compiler will emit a class that will hold this as a field to allow capturing of this closure + VerifyCS.Diagnostic(DisplayClassAllocationAnalyzer.ClosureDriverRule).WithLocation(13, 39).WithArguments("min")); + + [Fact] + public Task DisplayClassAllocation_ParenthesizedLambdaExpressionSyntaxAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System.Collections.Generic; + using System; + using System.Linq; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void SomeMethod() + { + var words = new[] { "aaaa", "bbbb", "cccc", "ddd" }; + var actions = new List(); + foreach (string word in words) // <-- captured closure + { + actions.Add(() => Console.WriteLine(word)); // <-- reason for closure capture + } + } + } + """, + // Test0.cs(13,25): warning HAA0302: The compiler will emit a class that will hold this as a field to allow capturing of this closure #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(DisplayClassAllocationAnalyzer.ClosureCaptureRule).WithLocation(13, 25), + VerifyCS.Diagnostic(DisplayClassAllocationAnalyzer.ClosureCaptureRule).WithLocation(13, 25), #pragma warning restore RS0030 // Do not use banned APIs - // Test0.cs(15,28): warning HAA0301: Heap allocation of closure Captures: word + // Test0.cs(15,28): warning HAA0301: Heap allocation of closure Captures: word #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(DisplayClassAllocationAnalyzer.ClosureDriverRule).WithLocation(15, 28).WithArguments("word")); -#pragma warning restore RS0030 // Do not use banned APIs - } + VerifyCS.Diagnostic(DisplayClassAllocationAnalyzer.ClosureDriverRule).WithLocation(15, 28).WithArguments("word")); - [Fact] - public async Task DisplayClassAllocation_DoNotReportForNonCapturingAnonymousMethodAsync() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; + [Fact] + public Task DisplayClassAllocation_DoNotReportForNonCapturingAnonymousMethodAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Sorter(int[] arr) - { - System.Array.Sort(arr, delegate(int x, int y) { return x - y; }); - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram); - } - - [Fact] - public async Task DisplayClassAllocation_DoNotReportForNonCapturingLambdaAsync() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Sorter(int[] arr) - { - System.Array.Sort(arr, (x, y) => x - y); - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram); - } - - [Fact] - public async Task DisplayClassAllocation_ReportForCapturingAnonymousMethodAsync() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Sorter(int[] arr) - { - int z = 2; - System.Array.Sort(arr, delegate(int x, int y) { return x - z; }); - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, - // Test0.cs(9,13): warning HAA0302: The compiler will emit a class that will hold this as a field to allow capturing of this closure + public class MyClass + { + [PerformanceSensitive("uri")] + public void Sorter(int[] arr) + { + System.Array.Sort(arr, delegate(int x, int y) { return x - y; }); + } + } + """); + + [Fact] + public Task DisplayClassAllocation_DoNotReportForNonCapturingLambdaAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Sorter(int[] arr) + { + System.Array.Sort(arr, (x, y) => x - y); + } + } + """); + + [Fact] + public Task DisplayClassAllocation_ReportForCapturingAnonymousMethodAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Sorter(int[] arr) + { + int z = 2; + System.Array.Sort(arr, delegate(int x, int y) { return x - z; }); + } + } + """, + // Test0.cs(9,13): warning HAA0302: The compiler will emit a class that will hold this as a field to allow capturing of this closure #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(DisplayClassAllocationAnalyzer.ClosureCaptureRule).WithLocation(9, 13), + VerifyCS.Diagnostic(DisplayClassAllocationAnalyzer.ClosureCaptureRule).WithLocation(9, 13), #pragma warning restore RS0030 // Do not use banned APIs - // Test0.cs(10,32): warning HAA0301: Heap allocation of closure Captures: z + // Test0.cs(10,32): warning HAA0301: Heap allocation of closure Captures: z #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(DisplayClassAllocationAnalyzer.ClosureDriverRule).WithLocation(10, 32).WithArguments("z")); -#pragma warning restore RS0030 // Do not use banned APIs - } - } + VerifyCS.Diagnostic(DisplayClassAllocationAnalyzer.ClosureDriverRule).WithLocation(10, 32).WithArguments("z")); } diff --git a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/EnumeratorAllocationAnalyzerTests.cs b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/EnumeratorAllocationAnalyzerTests.cs index d248a59333474..eb8a5092ffa0c 100644 --- a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/EnumeratorAllocationAnalyzerTests.cs +++ b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/EnumeratorAllocationAnalyzerTests.cs @@ -3,163 +3,155 @@ // See the LICENSE file in the project root for more information. using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CSharp.PerformanceSensitiveAnalyzers; +using Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.UnitTests; +using Microsoft.CodeAnalysis.Testing; using Xunit; -using VerifyCS = Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.UnitTests.CSharpPerformanceCodeFixVerifier< - Microsoft.CodeAnalysis.CSharp.PerformanceSensitiveAnalyzers.EnumeratorAllocationAnalyzer, - Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; -namespace Microsoft.CodeAnalysis.PerformanceSensitive.Analyzers.UnitTests -{ - public class EnumeratorAllocationAnalyzerTests - { - [Fact] - public async Task EnumeratorAllocation_BasicAsync() - { - var sampleProgram = -@"using System.Collections.Generic; -using System; -using System.Linq; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void SomeMethod() - { - int[] intData = new[] { 123, 32, 4 }; - IList iListData = new[] { 123, 32, 4 }; - List listData = new[] { 123, 32, 4 }.ToList(); - - foreach (var i in intData) - { - Console.WriteLine(i); - } - - foreach (var i in listData) - { - Console.WriteLine(i); - } - - foreach (var i in iListData) // Allocations (line 19) - { - Console.WriteLine(i); - } - - foreach (var i in (IEnumerable)intData) // Allocations (line 24) - { - Console.WriteLine(i); - } - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, - // Test0.cs(25,24): warning HAA0401: Non-ValueType enumerator may result in a heap allocation -#pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic().WithLocation(25, 24), -#pragma warning restore RS0030 // Do not use banned APIs - // Test0.cs(30,24): warning HAA0401: Non-ValueType enumerator may result in a heap allocation -#pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic().WithLocation(30, 24)); -#pragma warning restore RS0030 // Do not use banned APIs - } +namespace Microsoft.CodeAnalysis.PerformanceSensitive.Analyzers.UnitTests; - [Fact] - public async Task EnumeratorAllocation_AdvancedAsync() - { - var sampleProgram = -@"using System.Collections.Generic; -using System; -using Roslyn.Utilities; +using VerifyCS = CSharpPerformanceCodeFixVerifier< + EnumeratorAllocationAnalyzer, + EmptyCodeFixProvider>; -public class MyClass +public sealed class EnumeratorAllocationAnalyzerTests { - [PerformanceSensitive(""uri"")] - public void SomeMethod() - { - // These next 3 are from the YouTube video - foreach (object a in new[] { 1, 2, 3}) // Allocations 'new [] { 1. 2, 3}' - { - Console.WriteLine(a.ToString()); - } - - IEnumerable fx1 = default(IEnumerable); - foreach (var f in fx1) // Allocations 'in' - { - } - - List fx2 = default(List); - foreach (var f in fx2) // NO Allocations - { - } - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, - // Test0.cs(17,24): warning HAA0401: Non-ValueType enumerator may result in a heap allocation + [Fact] + public Task EnumeratorAllocation_BasicAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System.Collections.Generic; + using System; + using System.Linq; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void SomeMethod() + { + int[] intData = new[] { 123, 32, 4 }; + IList iListData = new[] { 123, 32, 4 }; + List listData = new[] { 123, 32, 4 }.ToList(); + + foreach (var i in intData) + { + Console.WriteLine(i); + } + + foreach (var i in listData) + { + Console.WriteLine(i); + } + + foreach (var i in iListData) // Allocations (line 19) + { + Console.WriteLine(i); + } + + foreach (var i in (IEnumerable)intData) // Allocations (line 24) + { + Console.WriteLine(i); + } + } + } + """, + // Test0.cs(25,24): warning HAA0401: Non-ValueType enumerator may result in a heap allocation #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic().WithLocation(17, 24)); + VerifyCS.Diagnostic().WithLocation(25, 24), #pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task EnumeratorAllocation_Via_InvocationExpressionSyntaxAsync() - { - var sampleProgram = -@"using System.Collections.Generic; -using System.Collections; -using System; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void SomeMethod() - { - var enumeratorRaw = GetIEnumerableRaw(); - while (enumeratorRaw.MoveNext()) - { - Console.WriteLine(enumeratorRaw.Current.ToString()); - } - - var enumeratorRawViaIEnumerable = GetIEnumeratorViaIEnumerable(); - while (enumeratorRawViaIEnumerable.MoveNext()) - { - Console.WriteLine(enumeratorRawViaIEnumerable.Current.ToString()); - } - } - - private IEnumerator GetIEnumerableRaw() - { - return new[] { 123, 32, 4 }.GetEnumerator(); - } - - private IEnumerator GetIEnumeratorViaIEnumerable() - { - int[] intData = new[] { 123, 32, 4 }; - return (IEnumerator)intData.GetEnumerator(); - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, - // Test0.cs(17,43): warning HAA0401: Non-ValueType enumerator may result in a heap allocation + // Test0.cs(30,24): warning HAA0401: Non-ValueType enumerator may result in a heap allocation #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic().WithLocation(17, 43)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task EnumeratorAllocation_IterateOverString_NoWarningAsync() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void SomeMethod() - { - foreach (char c in ""aaa"") { }; - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram); - } - } + VerifyCS.Diagnostic().WithLocation(30, 24)); + + [Fact] + public Task EnumeratorAllocation_AdvancedAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System.Collections.Generic; + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void SomeMethod() + { + // These next 3 are from the YouTube video + foreach (object a in new[] { 1, 2, 3}) // Allocations 'new [] { 1. 2, 3}' + { + Console.WriteLine(a.ToString()); + } + + IEnumerable fx1 = default(IEnumerable); + foreach (var f in fx1) // Allocations 'in' + { + } + + List fx2 = default(List); + foreach (var f in fx2) // NO Allocations + { + } + } + } + """, + // Test0.cs(17,24): warning HAA0401: Non-ValueType enumerator may result in a heap allocation +#pragma warning disable RS0030 // Do not use banned APIs + VerifyCS.Diagnostic().WithLocation(17, 24)); + + [Fact] + public Task EnumeratorAllocation_Via_InvocationExpressionSyntaxAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System.Collections.Generic; + using System.Collections; + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void SomeMethod() + { + var enumeratorRaw = GetIEnumerableRaw(); + while (enumeratorRaw.MoveNext()) + { + Console.WriteLine(enumeratorRaw.Current.ToString()); + } + + var enumeratorRawViaIEnumerable = GetIEnumeratorViaIEnumerable(); + while (enumeratorRawViaIEnumerable.MoveNext()) + { + Console.WriteLine(enumeratorRawViaIEnumerable.Current.ToString()); + } + } + + private IEnumerator GetIEnumerableRaw() + { + return new[] { 123, 32, 4 }.GetEnumerator(); + } + + private IEnumerator GetIEnumeratorViaIEnumerable() + { + int[] intData = new[] { 123, 32, 4 }; + return (IEnumerator)intData.GetEnumerator(); + } + } + """, + // Test0.cs(17,43): warning HAA0401: Non-ValueType enumerator may result in a heap allocation +#pragma warning disable RS0030 // Do not use banned APIs + VerifyCS.Diagnostic().WithLocation(17, 43)); + + [Fact] + public Task EnumeratorAllocation_IterateOverString_NoWarningAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void SomeMethod() + { + foreach (char c in "aaa") { }; + } + } + """); } diff --git a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/ExplicitAllocationAnalyzerTests.cs b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/ExplicitAllocationAnalyzerTests.cs index 840d31534ffd5..208e5874c6fa7 100644 --- a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/ExplicitAllocationAnalyzerTests.cs +++ b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/ExplicitAllocationAnalyzerTests.cs @@ -4,863 +4,757 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers; +using Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.UnitTests; +using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; -using VerifyCS = Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.UnitTests.CSharpPerformanceCodeFixVerifier< - Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.ExplicitAllocationAnalyzer, - Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; -using VerifyVB = Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.UnitTests.VisualBasicPerformanceCodeFixVerifier< - Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.ExplicitAllocationAnalyzer, - Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; - -namespace Microsoft.CodeAnalysis.PerformanceSensitive.Analyzers.UnitTests -{ - public class ExplicitAllocationAnalyzerTests - { - [Fact] - public async Task ExplicitAllocation_ObjectInitializerAsync() - { - var sampleProgram = - @"using System; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - var @class = new TestClass { Name = ""Bob"" }; - } -} - -public class TestClass -{ - public string Name { get; set; } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, -#pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(9, 22)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task ExplicitAllocation_ObjectInitializer_VisualBasicAsync() - { - var code = - @"Imports System -Imports Roslyn.Utilities - -Public Class A - - Public Sub Testing() - Dim instance = New TestClass With {.Name = ""Bob""} - End Sub -End Class - -Public Class TestClass - Public Property Name As String -End Class"; - - await VerifyVB.VerifyAnalyzerAsync( - code, -#pragma warning disable RS0030 // Do not use banned APIs - VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(7, 24)); -#pragma warning restore RS0030 // Do not use banned APIs - } - [Fact] - public async Task ExplicitAllocation_ObjectInitializerStruct_NoWarningAsync() - { - var sampleProgram = - @"using System; -using Roslyn.Utilities; +namespace Microsoft.CodeAnalysis.PerformanceSensitive.Analyzers.UnitTests; -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - var @struct = new TestStruct { Name = ""Bob"" }; - } -} +using VerifyCS = CSharpPerformanceCodeFixVerifier< + ExplicitAllocationAnalyzer, + EmptyCodeFixProvider>; +using VerifyVB = VisualBasicPerformanceCodeFixVerifier< + ExplicitAllocationAnalyzer, + EmptyCodeFixProvider>; -public struct TestStruct -{ - public string Name { get; set; } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram); - } - - [Fact] - public async Task ExplicitAllocation_ObjectInitializerStruct_NoWarning_VisualBasicAsync() - { - var code = - @"Imports System -Imports Roslyn.Utilities - -Public Class A - - Public Sub Testing() - Dim instance = New TestClass With {.Name = ""Bob""} - End Sub -End Class - -Public Structure TestClass - Public Property Name As String -End Structure"; - - await VerifyVB.VerifyAnalyzerAsync(code); - } - - [Fact] - public async Task ExplicitAllocation_ImplicitArrayCreationAsync() - { - var sampleProgram = - @"using System.Collections.Generic; -using Roslyn.Utilities; - -public class MyClass +public sealed class ExplicitAllocationAnalyzerTests { - [PerformanceSensitive(""uri"")] - public void Testing() - { - int[] intData = new[] { 123, 32, 4 }; - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, + [Fact] + public Task ExplicitAllocation_ObjectInitializerAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + { + var @class = new TestClass { Name = "Bob" }; + } + } + + public class TestClass + { + public string Name { get; set; } + } + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ArrayCreationRule).WithLocation(9, 25)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task ExplicitAllocation_ImplicitArrayCreation_VisualBasicAsync() - { - var sampleProgram = - @"Imports System.Collections.Generic -Imports Roslyn.Utilities - -Public Class A - - Public Sub Testing() - Dim intData() As Integer = {123, 32, 4} - End Sub -End Class"; - await VerifyVB.VerifyAnalyzerAsync(sampleProgram, + VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(9, 22)); + + [Fact] + public Task ExplicitAllocation_ObjectInitializer_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync( + """ + Imports System + Imports Roslyn.Utilities + + Public Class A + + Public Sub Testing() + Dim instance = New TestClass With {.Name = "Bob"} + End Sub + End Class + + Public Class TestClass + Public Property Name As String + End Class + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.ArrayCreationRule).WithLocation(7, 36)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task ExplicitAllocation_AnonymousObjectCreationAsync() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - var temp = new { A = 123, Name = ""Test"", }; - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, + VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(7, 24)); + + [Fact] + public Task ExplicitAllocation_ObjectInitializerStruct_NoWarningAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + { + var @struct = new TestStruct { Name = "Bob" }; + } + } + + public struct TestStruct + { + public string Name { get; set; } + } + """); + + [Fact] + public Task ExplicitAllocation_ObjectInitializerStruct_NoWarning_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports Roslyn.Utilities + + Public Class A + + Public Sub Testing() + Dim instance = New TestClass With {.Name = "Bob"} + End Sub + End Class + + Public Structure TestClass + Public Property Name As String + End Structure + """); + + [Fact] + public Task ExplicitAllocation_ImplicitArrayCreationAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System.Collections.Generic; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + { + int[] intData = new[] { 123, 32, 4 }; + } + } + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.AnonymousObjectCreationRule).WithLocation(9, 20)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task ExplicitAllocation_AnonymousObjectCreation_VisualBasicAsync() - { - var sampleProgram = -@"Imports System -Imports Roslyn.Utilities - -Public Class A - - Public Sub Testing() - Dim temp = New With {Key .B = 123, .Name = ""Test""} - End Sub -End Class"; - await VerifyVB.VerifyAnalyzerAsync(sampleProgram, + VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ArrayCreationRule).WithLocation(9, 25)); + + [Fact] + public Task ExplicitAllocation_ImplicitArrayCreation_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Imports System.Collections.Generic + Imports Roslyn.Utilities + + Public Class A + + Public Sub Testing() + Dim intData() As Integer = {123, 32, 4} + End Sub + End Class + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.AnonymousObjectCreationRule).WithLocation(7, 20)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task ExplicitAllocation_ArrayCreationAsync() - { - var sampleProgram = -@"using System.Collections.Generic; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - int[] intData = new int[] { 123, 32, 4 }; - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, + VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.ArrayCreationRule).WithLocation(7, 36)); + + [Fact] + public Task ExplicitAllocation_AnonymousObjectCreationAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + { + var temp = new { A = 123, Name = "Test", }; + } + } + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ArrayCreationRule).WithLocation(9, 25)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task ExplicitAllocation_ArrayCreation_VisualBasicAsync() - { - var sampleProgram = -@"Imports System.Collections.Generic -Imports Roslyn.Utilities - -Public Class A - - Public Sub Testing() - Dim intData = New Integer() {123, 32, 4} - End Sub -End Class"; - await VerifyVB.VerifyAnalyzerAsync(sampleProgram, + VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.AnonymousObjectCreationRule).WithLocation(9, 20)); + + [Fact] + public Task ExplicitAllocation_AnonymousObjectCreation_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports Roslyn.Utilities + + Public Class A + + Public Sub Testing() + Dim temp = New With {Key .B = 123, .Name = "Test"} + End Sub + End Class + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.ArrayCreationRule).WithLocation(7, 23)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task ExplicitAllocation_ObjectCreationAsync() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - var allocation = new String('a', 10); - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, + VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.AnonymousObjectCreationRule).WithLocation(7, 20)); + + [Fact] + public Task ExplicitAllocation_ArrayCreationAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System.Collections.Generic; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + { + int[] intData = new int[] { 123, 32, 4 }; + } + } + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(9, 26)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task ExplicitAllocation_ObjectCreation_VisualBasicAsync() - { - var sampleProgram = -@"Imports System -Imports Roslyn.Utilities - -Public Class A - - Public Sub Testing() - Dim allocation = New String(""a""c, 10) - End Sub -End Class"; - await VerifyVB.VerifyAnalyzerAsync(sampleProgram, + VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ArrayCreationRule).WithLocation(9, 25)); + + [Fact] + public Task ExplicitAllocation_ArrayCreation_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Imports System.Collections.Generic + Imports Roslyn.Utilities + + Public Class A + + Public Sub Testing() + Dim intData = New Integer() {123, 32, 4} + End Sub + End Class + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(7, 26)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task ExplicitAllocation_LetClauseAsync() - { - var sampleProgram = -@"using System.Collections.Generic; -using System.Linq; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - int[] intData = new[] { 123, 32, 4 }; - var result = (from a in intData - let b = a * 3 - select b).ToList(); - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, + VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.ArrayCreationRule).WithLocation(7, 23)); + + [Fact] + public Task ExplicitAllocation_ObjectCreationAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + { + var allocation = new String('a', 10); + } + } + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ArrayCreationRule).WithLocation(10, 25), -#pragma warning restore RS0030 // Do not use banned APIs + VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(9, 26)); + + [Fact] + public Task ExplicitAllocation_ObjectCreation_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports Roslyn.Utilities + + Public Class A + + Public Sub Testing() + Dim allocation = New String("a"c, 10) + End Sub + End Class + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.LetCauseRule).WithLocation(12, 23)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task ExplicitAllocation_LetClause_VisualBasicAsync() - { - var sampleProgram = -@"Imports System.Collections.Generic -Imports System.Linq -Imports Roslyn.Utilities - -Public Class A - - Public Sub Testing() - Dim intData() As Integer = {123, 32, 4} - Dim result = (From x In intData - Let b = x * 3 - Select b).ToList() - End Sub -End Class"; - await VerifyVB.VerifyAnalyzerAsync(sampleProgram, + VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(7, 26)); + + [Fact] + public Task ExplicitAllocation_LetClauseAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System.Collections.Generic; + using System.Linq; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + { + int[] intData = new[] { 123, 32, 4 }; + var result = (from a in intData + let b = a * 3 + select b).ToList(); + } + } + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.ArrayCreationRule).WithLocation(8, 36), + VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ArrayCreationRule).WithLocation(10, 25), #pragma warning restore RS0030 // Do not use banned APIs #pragma warning disable RS0030 // Do not use banned APIs - VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.LetCauseRule).WithLocation(10, 27)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - [WorkItem(7995606, "http://stackoverflow.com/questions/7995606/boxing-occurrence-in-c-sharp")] - public async Task Converting_any_value_type_to_System_Object_typeAsync() - { - var source = @" -using Roslyn.Utilities; - -public struct S { } - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void SomeMethod() - { - object box = new S(); - } -}"; - await VerifyCS.VerifyAnalyzerAsync(source, + VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.LetCauseRule).WithLocation(12, 23)); + + [Fact] + public Task ExplicitAllocation_LetClause_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Imports System.Collections.Generic + Imports System.Linq + Imports Roslyn.Utilities + + Public Class A + + Public Sub Testing() + Dim intData() As Integer = {123, 32, 4} + Dim result = (From x In intData + Let b = x * 3 + Select b).ToList() + End Sub + End Class + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(11, 22)); + VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.ArrayCreationRule).WithLocation(8, 36), #pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - [WorkItem(7995606, "http://stackoverflow.com/questions/7995606/boxing-occurrence-in-c-sharp")] - public async Task Converting_any_value_type_to_System_Object_type_VisualBasicAsync() - { - var source = @" -Imports Roslyn.Utilities - -Public Structure S -End Structure - -Public Class A - - Public Sub SomeMethod() - Dim box As Object = new S() - End Sub -End Class"; - await VerifyVB.VerifyAnalyzerAsync(source, #pragma warning disable RS0030 // Do not use banned APIs - VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(10, 29)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - [WorkItem(7995606, "http://stackoverflow.com/questions/7995606/boxing-occurrence-in-c-sharp")] - public async Task Converting_any_value_type_to_System_ValueType_typeAsync() - { - var source = @" -using Roslyn.Utilities; - -public struct S { } - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void SomeMethod() - { - System.ValueType box = new S(); - } -}"; - await VerifyCS.VerifyAnalyzerAsync(source, + VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.LetCauseRule).WithLocation(10, 27)); + + [Fact] + [WorkItem(7995606, "http://stackoverflow.com/questions/7995606/boxing-occurrence-in-c-sharp")] + public Task Converting_any_value_type_to_System_Object_typeAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using Roslyn.Utilities; + + public struct S { } + + public class MyClass + { + [PerformanceSensitive("uri")] + public void SomeMethod() + { + object box = new S(); + } + } + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(11, 32)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - [WorkItem(7995606, "http://stackoverflow.com/questions/7995606/boxing-occurrence-in-c-sharp")] - public async Task Converting_any_value_type_to_System_ValueType_type_VisualBasicAsync() - { - var source = @" -Imports Roslyn.Utilities - -Public Structure S -End Structure - -Public Class A - - Public Sub SomeMethod() - Dim box As System.ValueType = new S() - End Sub -End Class"; - await VerifyVB.VerifyAnalyzerAsync(source, + VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(10, 22)); + + [Fact] + [WorkItem(7995606, "http://stackoverflow.com/questions/7995606/boxing-occurrence-in-c-sharp")] + public Task Converting_any_value_type_to_System_Object_type_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Imports Roslyn.Utilities + + Public Structure S + End Structure + + Public Class A + + Public Sub SomeMethod() + Dim box As Object = new S() + End Sub + End Class + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(10, 39)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - [WorkItem(7995606, "http://stackoverflow.com/questions/7995606/boxing-occurrence-in-c-sharp")] - public async Task Converting_any_value_type_into_interface_referenceAsync() - { - var source = @" -using Roslyn.Utilities; - -interface I { } - -public struct S : I { } - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void SomeMethod() - { - I box = new S(); - } -}"; - await VerifyCS.VerifyAnalyzerAsync(source, + VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(9, 29)); + + [Fact] + [WorkItem(7995606, "http://stackoverflow.com/questions/7995606/boxing-occurrence-in-c-sharp")] + public Task Converting_any_value_type_to_System_ValueType_typeAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using Roslyn.Utilities; + + public struct S { } + + public class MyClass + { + [PerformanceSensitive("uri")] + public void SomeMethod() + { + System.ValueType box = new S(); + } + } + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(13, 17)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - [WorkItem(7995606, "http://stackoverflow.com/questions/7995606/boxing-occurrence-in-c-sharp")] - public async Task Converting_any_value_type_into_interface_reference_VisualBasicAsync() - { - var source = @" -Imports Roslyn.Utilities - -Interface I -End Interface - -Public Structure S - Implements I -End Structure - -Public Class A - - Public Sub SomeMethod() - Dim box As I = new S() - End Sub -End Class"; - await VerifyVB.VerifyAnalyzerAsync(source, + VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(10, 32)); + + [Fact] + [WorkItem(7995606, "http://stackoverflow.com/questions/7995606/boxing-occurrence-in-c-sharp")] + public Task Converting_any_value_type_to_System_ValueType_type_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Imports Roslyn.Utilities + + Public Structure S + End Structure + + Public Class A + + Public Sub SomeMethod() + Dim box As System.ValueType = new S() + End Sub + End Class + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(14, 24)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task ExplicitAllocation_StructCreation_NoWarningAsync() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; - -public struct S { } - -public class MyClass -{ - - [PerformanceSensitive(""uri"")] - public void Testing() - { - var noBox1 = new DateTime(); - S noBox2 = new S(); - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram); - } - - [Fact] - public async Task ExplicitAllocation_StructCreation_NoWarning_VisualBasicAsync() - { - var sampleProgram = -@"Imports System -Imports Roslyn.Utilities - -Public Structure S -End Structure - -Public Class A - - Public Sub Testing() - Dim noBox1 = new DateTime() - Dim noBox2 As S = new S() - End Sub -End Class"; - await VerifyVB.VerifyAnalyzerAsync(sampleProgram); - } - - [Fact] - public async Task ExplicitAllocation_PrimitiveTypeConversion_NoWarningAsync() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - double x = new int(); - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram); - } - - [Fact] - public async Task ExplicitAllocation_PrimitiveTypeConversion_NoWarning_VisualBasicAsync() - { - var sampleProgram = -@"Imports System -Imports Roslyn.Utilities - -Public Class A - - Public Sub Testing() - Dim x As Double = New Integer() - End Sub -End Class"; - await VerifyVB.VerifyAnalyzerAsync(sampleProgram); - } - - [Fact] - public async Task ExplicitAllocation_ImplicitValueTypeConversion_NoWarningAsync() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; - -struct A -{ - public static implicit operator A(B other) - { - return new A(); - } -} - -struct B -{ -} - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - A a = new B(); - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram); - } - - [Fact] - public async Task ExplicitAllocation_ImplicitValueTypeConversion_NoWarning_VisualBasicAsync() - { - var sampleProgram = -@"Imports System -Imports Roslyn.Utilities - -Structure A - Public Shared Widening Operator CType(other As B) As A - Return New A() - End Operator -End Structure - -Structure B -End Structure - -Public Class C - - Public Sub Testing() - Dim a As A = New B() - End Sub -End Class"; - await VerifyVB.VerifyAnalyzerAsync(sampleProgram); - } - - [Fact] - public async Task ExplicitAllocation_NoParamsArrayCreationAsync() - { - var sampleProgram = -@"using System.Collections.Generic; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing(params int[] values) - { - Testing(); - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram); - } - - [Fact] - public async Task ExplicitAllocation_NoParamsArrayCreation_VisualBasicAsync() - { - var sampleProgram = -@"Imports System.Collections.Generic -Imports Roslyn.Utilities - -Public Class A - - Public Sub Testing(ParamArray values() As Integer) - Testing() - End Sub -End Class"; - await VerifyVB.VerifyAnalyzerAsync(sampleProgram); - } - - [Fact] - public async Task ExplicitAllocation_ExplicitDelegateCreationAsync() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing(object sender, EventArgs e) - { - var handler = new EventHandler(Testing); - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, + VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(9, 39)); + + [Fact] + [WorkItem(7995606, "http://stackoverflow.com/questions/7995606/boxing-occurrence-in-c-sharp")] + public Task Converting_any_value_type_into_interface_referenceAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using Roslyn.Utilities; + + interface I { } + + public struct S : I { } + + public class MyClass + { + [PerformanceSensitive("uri")] + public void SomeMethod() + { + I box = new S(); + } + } + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(9, 23)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task ExplicitAllocation_ExplicitDelegateCreation_VisualBasicAsync() - { - var sampleProgram = -@"Imports System -Imports Roslyn.Utilities - -Public Class A - - Public Sub Testing(sender As Object, e As EventArgs) - Dim handler = new EventHandler(AddressOf Testing) - End Sub -End Class"; - await VerifyVB.VerifyAnalyzerAsync(sampleProgram, + VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(12, 17)); + + [Fact] + [WorkItem(7995606, "http://stackoverflow.com/questions/7995606/boxing-occurrence-in-c-sharp")] + public Task Converting_any_value_type_into_interface_reference_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Imports Roslyn.Utilities + + Interface I + End Interface + + Public Structure S + Implements I + End Structure + + Public Class A + + Public Sub SomeMethod() + Dim box As I = new S() + End Sub + End Class + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(7, 23)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task ExplicitAllocation_ImplicitDelegateCreationAsync() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing(object sender, EventArgs e) - { - EventHandler handler = Testing; - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram); - } - - [Fact] - public async Task ExplicitAllocation_ImplicitDelegateCreation_VisualBasicAsync() - { - var sampleProgram = -@"Imports System -Imports Roslyn.Utilities - -Public Class A - - Public Sub Testing(sender As Object, e As EventArgs) - Dim handler As EventHandler = AddressOf Testing - End Sub -End Class"; - await VerifyVB.VerifyAnalyzerAsync(sampleProgram); - } - - [Fact] - public async Task ExplicitAllocation_ListInitializerCreationAsync() - { - var sampleProgram = -@"using System.Collections.Generic; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - var intData = new List { 3, 4 }; - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, + VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(13, 24)); + + [Fact] + public Task ExplicitAllocation_StructCreation_NoWarningAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public struct S { } + + public class MyClass + { + + [PerformanceSensitive("uri")] + public void Testing() + { + var noBox1 = new DateTime(); + S noBox2 = new S(); + } + } + """); + + [Fact] + public Task ExplicitAllocation_StructCreation_NoWarning_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports Roslyn.Utilities + + Public Structure S + End Structure + + Public Class A + + Public Sub Testing() + Dim noBox1 = new DateTime() + Dim noBox2 As S = new S() + End Sub + End Class + """); + + [Fact] + public Task ExplicitAllocation_PrimitiveTypeConversion_NoWarningAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + { + double x = new int(); + } + } + """); + + [Fact] + public Task ExplicitAllocation_PrimitiveTypeConversion_NoWarning_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports Roslyn.Utilities + + Public Class A + + Public Sub Testing() + Dim x As Double = New Integer() + End Sub + End Class + """); + + [Fact] + public Task ExplicitAllocation_ImplicitValueTypeConversion_NoWarningAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + struct A + { + public static implicit operator A(B other) + { + return new A(); + } + } + + struct B + { + } + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + { + A a = new B(); + } + } + """); + + [Fact] + public Task ExplicitAllocation_ImplicitValueTypeConversion_NoWarning_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports Roslyn.Utilities + + Structure A + Public Shared Widening Operator CType(other As B) As A + Return New A() + End Operator + End Structure + + Structure B + End Structure + + Public Class C + + Public Sub Testing() + Dim a As A = New B() + End Sub + End Class + """); + + [Fact] + public Task ExplicitAllocation_NoParamsArrayCreationAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System.Collections.Generic; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing(params int[] values) + { + Testing(); + } + } + """); + + [Fact] + public Task ExplicitAllocation_NoParamsArrayCreation_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Imports System.Collections.Generic + Imports Roslyn.Utilities + + Public Class A + + Public Sub Testing(ParamArray values() As Integer) + Testing() + End Sub + End Class + """); + + [Fact] + public Task ExplicitAllocation_ExplicitDelegateCreationAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing(object sender, EventArgs e) + { + var handler = new EventHandler(Testing); + } + } + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(9, 23)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task ExplicitAllocation_ListInitializerCreation_VisualBasicAsync() - { - var sampleProgram = -@"Imports System.Collections.Generic -Imports Roslyn.Utilities - -Public Class A - - Public Sub Testing() - Dim intData = New List(Of Integer) From {3, 4} - End Sub -End Class"; - await VerifyVB.VerifyAnalyzerAsync(sampleProgram, + VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(9, 23)); + + [Fact] + public Task ExplicitAllocation_ExplicitDelegateCreation_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports Roslyn.Utilities + + Public Class A + + Public Sub Testing(sender As Object, e As EventArgs) + Dim handler = new EventHandler(AddressOf Testing) + End Sub + End Class + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(7, 23)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task ExplicitAllocation_GenericObjectCreationAsync() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing() - where T : class, new() - { - var allocation = new T(); - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, + VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(7, 23)); + + [Fact] + public Task ExplicitAllocation_ImplicitDelegateCreationAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing(object sender, EventArgs e) + { + EventHandler handler = Testing; + } + } + """); + + [Fact] + public Task ExplicitAllocation_ImplicitDelegateCreation_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports Roslyn.Utilities + + Public Class A + + Public Sub Testing(sender As Object, e As EventArgs) + Dim handler As EventHandler = AddressOf Testing + End Sub + End Class + """); + + [Fact] + public Task ExplicitAllocation_ListInitializerCreationAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System.Collections.Generic; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + { + var intData = new List { 3, 4 }; + } + } + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(10, 26)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task ExplicitAllocation_GenericObjectCreation_VisualBasicAsync() - { - var sampleProgram = -@"Imports System -Imports Roslyn.Utilities - -Public Class A - - Public Sub Testing(Of T As {Class, New})() - Dim allocation = New T() - End Sub -End Class"; - await VerifyVB.VerifyAnalyzerAsync(sampleProgram, + VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(9, 23)); + + [Fact] + public Task ExplicitAllocation_ListInitializerCreation_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Imports System.Collections.Generic + Imports Roslyn.Utilities + + Public Class A + + Public Sub Testing() + Dim intData = New List(Of Integer) From {3, 4} + End Sub + End Class + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(7, 26)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task ExplicitAllocation_GenericObjectCreation2Async() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing() - where T : struct - { - object allocation = new T(); - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, + VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(7, 23)); + + [Fact] + public Task ExplicitAllocation_GenericObjectCreationAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + where T : class, new() + { + var allocation = new T(); + } + } + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(10, 29)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task ExplicitAllocation_GenericObjectCreation2_VisualBasicAsync() - { - var sampleProgram = -@"Imports System -Imports Roslyn.Utilities - -Public Class A - - Public Sub Testing(Of T As Structure)() - Dim allocation As Object = New T() - End Sub -End Class"; - await VerifyVB.VerifyAnalyzerAsync(sampleProgram, + VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(10, 26)); + + [Fact] + public Task ExplicitAllocation_GenericObjectCreation_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports Roslyn.Utilities + + Public Class A + + Public Sub Testing(Of T As {Class, New})() + Dim allocation = New T() + End Sub + End Class + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(7, 36)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task ExplicitAllocation_GenericObjectCreation3Async() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing() - where T : struct - { - T value = new T(); - } -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram); - } - - [Fact] - public async Task ExplicitAllocation_GenericObjectCreation3_VisualBasicAsync() - { - var sampleProgram = -@"Imports System -Imports Roslyn.Utilities - -Public Class A - - Public Sub Testing(Of T As Structure)() - Dim value As T = new T() - End Sub -End Class"; - await VerifyVB.VerifyAnalyzerAsync(sampleProgram); - } - } + VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(7, 26)); + + [Fact] + public Task ExplicitAllocation_GenericObjectCreation2Async() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + where T : struct + { + object allocation = new T(); + } + } + """, +#pragma warning disable RS0030 // Do not use banned APIs + VerifyCS.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(10, 29)); + + [Fact] + public Task ExplicitAllocation_GenericObjectCreation2_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports Roslyn.Utilities + + Public Class A + + Public Sub Testing(Of T As Structure)() + Dim allocation As Object = New T() + End Sub + End Class + """, +#pragma warning disable RS0030 // Do not use banned APIs + VerifyVB.Diagnostic(ExplicitAllocationAnalyzer.ObjectCreationRule).WithLocation(7, 36)); + + [Fact] + public Task ExplicitAllocation_GenericObjectCreation3Async() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + where T : struct + { + T value = new T(); + } + } + """); + + [Fact] + public Task ExplicitAllocation_GenericObjectCreation3_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Imports System + Imports Roslyn.Utilities + + Public Class A + + Public Sub Testing(Of T As Structure)() + Dim value As T = new T() + End Sub + End Class + """); } diff --git a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.UnitTests.csproj b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.UnitTests.csproj index c730446de83be..87f74bb548653 100644 --- a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.UnitTests.csproj +++ b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.UnitTests.csproj @@ -9,15 +9,14 @@ $(NoWarn);CA2007 true - $(MicrosoftCodeAnalysisVersionForTests) - - - - - - + + + + + + diff --git a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/TypeConversionAllocationAnalyzerTests.cs b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/TypeConversionAllocationAnalyzerTests.cs index b4a9794971548..39c7bd518870d 100644 --- a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/TypeConversionAllocationAnalyzerTests.cs +++ b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/TypeConversionAllocationAnalyzerTests.cs @@ -4,857 +4,812 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.PerformanceSensitiveAnalyzers; +using Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.UnitTests; +using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; -using VerifyCS = Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.UnitTests.CSharpPerformanceCodeFixVerifier< - Microsoft.CodeAnalysis.CSharp.PerformanceSensitiveAnalyzers.TypeConversionAllocationAnalyzer, - Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; -namespace Microsoft.CodeAnalysis.PerformanceSensitive.Analyzers.UnitTests -{ - public class TypeConversionAllocationAnalyzerTests - { - [Fact] - public async Task TypeConversionAllocation_ArgumentSyntaxAsync() - { - await VerifyCS.VerifyAnalyzerAsync(@" -using System; -using Roslyn.Utilities; - -public class MyObject -{ - public MyObject(object obj) - { - } - - private void ObjCall(object obj) - { - } - - [PerformanceSensitive(""uri"")] - public void SomeMethod() - { - ObjCall(10); // Allocation - _ = new MyObject(10); // Allocation - } -}", +namespace Microsoft.CodeAnalysis.PerformanceSensitive.Analyzers.UnitTests; + +using VerifyCS = CSharpPerformanceCodeFixVerifier< + TypeConversionAllocationAnalyzer, + EmptyCodeFixProvider>; + +public sealed class TypeConversionAllocationAnalyzerTests +{ + [Fact] + public Task TypeConversionAllocation_ArgumentSyntaxAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyObject + { + public MyObject(object obj) + { + } + + private void ObjCall(object obj) + { + } + + [PerformanceSensitive("uri")] + public void SomeMethod() + { + ObjCall(10); // Allocation + _ = new MyObject(10); // Allocation + } + } + """, #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(18, 17), + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(17, 17), #pragma warning restore RS0030 // Do not use banned APIs #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(19, 26) + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(18, 26) #pragma warning restore RS0030 // Do not use banned APIs - ); - } - - [Fact] - public async Task TypeConversionAllocation_ArgumentSyntax_WithDelegatesAsync() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - var @class = new MyClass(); - @class.ProcessFunc(someObjCall); // implicit, so Allocation - @class.ProcessFunc(new Func(someObjCall)); // Explicit, so NO Allocation - } - - public void ProcessFunc(Func func) - { - } - - private string someObjCall(object obj) => null; -} - -public struct MyStruct -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - var @struct = new MyStruct(); - @struct.ProcessFunc(someObjCall); // implicit allocation + boxing - @struct.ProcessFunc(new Func(someObjCall)); // Explicit allocation + boxing - } - - public void ProcessFunc(Func func) - { - } - - private string someObjCall(object obj) => null; -}"; - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, - // Test0.cs(10,28): warning HAA0603: This will allocate a delegate instance - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.MethodGroupAllocationRule).WithSpan(10, 28, 10, 39), - // Test0.cs(27,29): warning HAA0602: Struct instance method being used for delegate creation, this will result in a boxing instruction - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.MethodGroupAllocationRule).WithSpan(27, 29, 27, 40), - // Test0.cs(27,29): warning HAA0603: This will allocate a delegate instance - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.DelegateOnStructInstanceRule).WithSpan(27, 29, 27, 40), - // Test0.cs(28,54): warning HAA0602: Struct instance method being used for delegate creation, this will result in a boxing instruction - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.DelegateOnStructInstanceRule).WithSpan(28, 54, 28, 65)); - } - - [Fact] - public async Task TypeConversionAllocation_ReturnStatementSyntaxAsync() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; - -public class MyObject -{ - public Object Obj1 - { - [PerformanceSensitive(""uri"")] - get { return 0; } - } - - [PerformanceSensitive(""uri"")] - public Object Obj2 - { - get { return 0; } - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, - // Test0.cs(9,22): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable + ); + + [Fact] + public Task TypeConversionAllocation_ArgumentSyntax_WithDelegatesAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + { + var @class = new MyClass(); + @class.ProcessFunc(someObjCall); // implicit, so Allocation + @class.ProcessFunc(new Func(someObjCall)); // Explicit, so NO Allocation + } + + public void ProcessFunc(Func func) + { + } + + private string someObjCall(object obj) => null; + } + + public struct MyStruct + { + [PerformanceSensitive("uri")] + public void Testing() + { + var @struct = new MyStruct(); + @struct.ProcessFunc(someObjCall); // implicit allocation + boxing + @struct.ProcessFunc(new Func(someObjCall)); // Explicit allocation + boxing + } + + public void ProcessFunc(Func func) + { + } + + private string someObjCall(object obj) => null; + } + """, + // Test0.cs(10,28): warning HAA0603: This will allocate a delegate instance + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.MethodGroupAllocationRule).WithSpan(10, 28, 10, 39), + // Test0.cs(27,29): warning HAA0602: Struct instance method being used for delegate creation, this will result in a boxing instruction + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.MethodGroupAllocationRule).WithSpan(27, 29, 27, 40), + // Test0.cs(27,29): warning HAA0603: This will allocate a delegate instance + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.DelegateOnStructInstanceRule).WithSpan(27, 29, 27, 40), + // Test0.cs(28,54): warning HAA0602: Struct instance method being used for delegate creation, this will result in a boxing instruction + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.DelegateOnStructInstanceRule).WithSpan(28, 54, 28, 65)); + + [Fact] + public Task TypeConversionAllocation_ReturnStatementSyntaxAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyObject + { + public Object Obj1 + { + [PerformanceSensitive("uri")] + get { return 0; } + } + + [PerformanceSensitive("uri")] + public Object Obj2 + { + get { return 0; } + } + } + """, + // Test0.cs(9,22): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(9, 22), + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(9, 22), #pragma warning restore RS0030 // Do not use banned APIs - // Test0.cs(15,22): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable + // Test0.cs(15,22): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(15, 22)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task TypeConversionAllocation_ReturnStatementSyntax_NoAllocAsync() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; - -public class MyObject -{ - [PerformanceSensitive(""uri"")] - public Object ObjNoAllocation1 { get { return 0.ToString(); } } - - public Object ObjNoAllocation2 - { - [PerformanceSensitive(""uri"")] - get { return 0.ToString(); } - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(sampleProgram); - } - - [Fact] - public async Task TypeConversionAllocation_YieldStatementSyntaxAsync() - { - var sampleProgram = -@"using System; -using System.Collections.Generic; -using Roslyn.Utilities; - -public class MyClass -{ - public void SomeMethod() - { - foreach (var item in GetItems()) - { - } - - foreach (var item in GetItemsNoAllocation()) - { - } - } - - [PerformanceSensitive(""uri"")] - public IEnumerable GetItems() - { - yield return 0; // Allocation - yield break; - } - - [PerformanceSensitive(""uri"")] - public IEnumerable GetItemsNoAllocation() - { - yield return 0; // NO Allocation (IEnumerable) - yield break; - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, - // Test0.cs(21,22): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(15, 22)); + + [Fact] + public Task TypeConversionAllocation_ReturnStatementSyntax_NoAllocAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyObject + { + [PerformanceSensitive("uri")] + public Object ObjNoAllocation1 { get { return 0.ToString(); } } + + public Object ObjNoAllocation2 + { + [PerformanceSensitive("uri")] + get { return 0.ToString(); } + } + } + """); + + [Fact] + public Task TypeConversionAllocation_YieldStatementSyntaxAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using System.Collections.Generic; + using Roslyn.Utilities; + + public class MyClass + { + public void SomeMethod() + { + foreach (var item in GetItems()) + { + } + + foreach (var item in GetItemsNoAllocation()) + { + } + } + + [PerformanceSensitive("uri")] + public IEnumerable GetItems() + { + yield return 0; // Allocation + yield break; + } + + [PerformanceSensitive("uri")] + public IEnumerable GetItemsNoAllocation() + { + yield return 0; // NO Allocation (IEnumerable) + yield break; + } + } + """, + // Test0.cs(21,22): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(21, 22)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task TypeConversionAllocation_BinaryExpressionSyntaxAsync() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void SomeMethod() - { - object x = ""blah""; - object a1 = x ?? 0; // Allocation - object a2 = x ?? 0.ToString(); // No Allocation - - var b1 = 10 as object; // Allocation - var b2 = 10.ToString() as object; // No Allocation - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, - // Test0.cs(10,26): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(21, 22)); + + [Fact] + public Task TypeConversionAllocation_BinaryExpressionSyntaxAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void SomeMethod() + { + object x = "blah"; + object a1 = x ?? 0; // Allocation + object a2 = x ?? 0.ToString(); // No Allocation + + var b1 = 10 as object; // Allocation + var b2 = 10.ToString() as object; // No Allocation + } + } + """, + // Test0.cs(10,26): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(10, 26), + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(10, 26), #pragma warning restore RS0030 // Do not use banned APIs - // Test0.cs(13,18): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable + // Test0.cs(13,18): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(13, 18)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task TypeConversionAllocation_BinaryExpressionSyntax_WithDelegatesAsync() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - Func temp = null; - var result1 = temp ?? someObjCall; // implicit, so Allocation - var result2 = temp ?? new Func(someObjCall); // Explicit, so NO Allocation - } - - private string someObjCall(object obj) - { - return obj.ToString(); - } -} - -public struct MyStruct -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - Func temp = null; - var result1 = temp ?? someObjCall; // implicit allocation + boxing - var result2 = temp ?? new Func(someObjCall); // Explicit allocation + boxing - } - - private string someObjCall(object obj) - { - return obj.ToString(); - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, - // Test0.cs(10,31): warning HAA0603: This will allocate a delegate instance - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.MethodGroupAllocationRule).WithSpan(10, 31, 10, 42), - // Test0.cs(26,31): warning HAA0602: Struct instance method being used for delegate creation, this will result in a boxing instruction - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.DelegateOnStructInstanceRule).WithSpan(26, 31, 26, 42), - // Test0.cs(26,31): warning HAA0603: This will allocate a delegate instance - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.MethodGroupAllocationRule).WithSpan(26, 31, 26, 42), - // Test0.cs(27,56): warning HAA0602: Struct instance method being used for delegate creation, this will result in a boxing instruction - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.DelegateOnStructInstanceRule).WithSpan(27, 56, 27, 67)); - } - - [Fact] - public async Task TypeConversionAllocation_EqualsValueClauseSyntaxAsync() - { - // for (object i = 0;;) - var sampleProgram = -@"using System; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void SomeMethod() - { - for (object i = 0;;) // Allocation - { - } - - for (int i = 0;;) // NO Allocation - { - } - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, - // Test0.cs(9,25): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(13, 18)); + + [Fact] + public Task TypeConversionAllocation_BinaryExpressionSyntax_WithDelegatesAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + { + Func temp = null; + var result1 = temp ?? someObjCall; // implicit, so Allocation + var result2 = temp ?? new Func(someObjCall); // Explicit, so NO Allocation + } + + private string someObjCall(object obj) + { + return obj.ToString(); + } + } + + public struct MyStruct + { + [PerformanceSensitive("uri")] + public void Testing() + { + Func temp = null; + var result1 = temp ?? someObjCall; // implicit allocation + boxing + var result2 = temp ?? new Func(someObjCall); // Explicit allocation + boxing + } + + private string someObjCall(object obj) + { + return obj.ToString(); + } + } + """, + // Test0.cs(10,31): warning HAA0603: This will allocate a delegate instance + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.MethodGroupAllocationRule).WithSpan(10, 31, 10, 42), + // Test0.cs(26,31): warning HAA0602: Struct instance method being used for delegate creation, this will result in a boxing instruction + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.DelegateOnStructInstanceRule).WithSpan(26, 31, 26, 42), + // Test0.cs(26,31): warning HAA0603: This will allocate a delegate instance + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.MethodGroupAllocationRule).WithSpan(26, 31, 26, 42), + // Test0.cs(27,56): warning HAA0602: Struct instance method being used for delegate creation, this will result in a boxing instruction + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.DelegateOnStructInstanceRule).WithSpan(27, 56, 27, 67)); + + [Fact] + public Task TypeConversionAllocation_EqualsValueClauseSyntaxAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void SomeMethod() + { + for (object i = 0;;) // Allocation + { + } + + for (int i = 0;;) // NO Allocation + { + } + } + } + """, + // Test0.cs(9,25): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(9, 25)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task TypeConversionAllocation_EqualsValueClauseSyntax_WithDelegatesAsync() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - Func func2 = someObjCall; // implicit, so Allocation - Func func1 = new Func(someObjCall); // Explicit, so NO Allocation - } - - private string someObjCall(object obj) - { - return obj.ToString(); - } -} - -public struct MyStruct -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - Func func2 = someObjCall; // implicit allocation + boxing - Func func1 = new Func(someObjCall); // Explicit allocation + boxing - } - - private string someObjCall(object obj) - { - return obj.ToString(); - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, - // Test0.cs(9,38): warning HAA0603: This will allocate a delegate instance - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.MethodGroupAllocationRule).WithSpan(9, 38, 9, 49), - // Test0.cs(24,38): warning HAA0602: Struct instance method being used for delegate creation, this will result in a boxing instruction - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.DelegateOnStructInstanceRule).WithSpan(24, 38, 24, 49), - // Test0.cs(24,38): warning HAA0603: This will allocate a delegate instance - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.MethodGroupAllocationRule).WithSpan(24, 38, 24, 49), - // Test0.cs(25,63): warning HAA0602: Struct instance method being used for delegate creation, this will result in a boxing instruction - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.DelegateOnStructInstanceRule).WithSpan(25, 63, 25, 74)); - } - - [Fact] - [WorkItem(2, "https://github.com/mjsabby/RoslynClrHeapAllocationAnalyzer/issues/2")] - public async Task TypeConversionAllocation_EqualsValueClause_ExplicitMethodGroupAllocation_BugAsync() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - Action methodGroup = this.Method; - } - - private void Method() - { - } -} - -public struct MyStruct -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - Action methodGroup = this.Method; - } - - private void Method() - { - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, - // Test0.cs(9,30): warning HAA0603: This will allocate a delegate instance + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(9, 25)); + + [Fact] + public Task TypeConversionAllocation_EqualsValueClauseSyntax_WithDelegatesAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + { + Func func2 = someObjCall; // implicit, so Allocation + Func func1 = new Func(someObjCall); // Explicit, so NO Allocation + } + + private string someObjCall(object obj) + { + return obj.ToString(); + } + } + + public struct MyStruct + { + [PerformanceSensitive("uri")] + public void Testing() + { + Func func2 = someObjCall; // implicit allocation + boxing + Func func1 = new Func(someObjCall); // Explicit allocation + boxing + } + + private string someObjCall(object obj) + { + return obj.ToString(); + } + } + """, + // Test0.cs(9,38): warning HAA0603: This will allocate a delegate instance + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.MethodGroupAllocationRule).WithSpan(9, 38, 9, 49), + // Test0.cs(24,38): warning HAA0602: Struct instance method being used for delegate creation, this will result in a boxing instruction + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.DelegateOnStructInstanceRule).WithSpan(24, 38, 24, 49), + // Test0.cs(24,38): warning HAA0603: This will allocate a delegate instance + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.MethodGroupAllocationRule).WithSpan(24, 38, 24, 49), + // Test0.cs(25,63): warning HAA0602: Struct instance method being used for delegate creation, this will result in a boxing instruction + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.DelegateOnStructInstanceRule).WithSpan(25, 63, 25, 74)); + + [Fact] + [WorkItem(2, "https://github.com/mjsabby/RoslynClrHeapAllocationAnalyzer/issues/2")] + public Task TypeConversionAllocation_EqualsValueClause_ExplicitMethodGroupAllocation_BugAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + { + Action methodGroup = this.Method; + } + + private void Method() + { + } + } + + public struct MyStruct + { + [PerformanceSensitive("uri")] + public void Testing() + { + Action methodGroup = this.Method; + } + + private void Method() + { + } + } + """, + // Test0.cs(9,30): warning HAA0603: This will allocate a delegate instance #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.MethodGroupAllocationRule).WithLocation(9, 30), + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.MethodGroupAllocationRule).WithLocation(9, 30), #pragma warning restore RS0030 // Do not use banned APIs - // Test0.cs(22,30): warning HAA0603: This will allocate a delegate instance + // Test0.cs(22,30): warning HAA0603: This will allocate a delegate instance #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.MethodGroupAllocationRule).WithLocation(22, 30), + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.MethodGroupAllocationRule).WithLocation(22, 30), #pragma warning restore RS0030 // Do not use banned APIs - // Test0.cs(22,30): warning HAA0602: Struct instance method being used for delegate creation, this will result in a boxing instruction + // Test0.cs(22,30): warning HAA0602: Struct instance method being used for delegate creation, this will result in a boxing instruction #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.DelegateOnStructInstanceRule).WithLocation(22, 30)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task TypeConversionAllocation_ConditionalExpressionSyntaxAsync() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - object obj = ""test""; - object test1 = true ? 0 : obj; // Allocation - object test2 = true ? 0.ToString() : obj; // NO Allocation - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, - // Test0.cs(10,31): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.DelegateOnStructInstanceRule).WithLocation(22, 30)); + + [Fact] + public Task TypeConversionAllocation_ConditionalExpressionSyntaxAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + { + object obj = "test"; + object test1 = true ? 0 : obj; // Allocation + object test2 = true ? 0.ToString() : obj; // NO Allocation + } + } + """, + // Test0.cs(10,31): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(10, 31)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task TypeConversionAllocation_CastExpressionSyntaxAsync() - { - var sampleProgram = -@"using System; -using Roslyn.Utilities; - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - var f1 = (object)5; // Allocation - var f2 = (object)""5""; // NO Allocation - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(sampleProgram, - // Test0.cs(9,26): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(10, 31)); + + [Fact] + public Task TypeConversionAllocation_CastExpressionSyntaxAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + public class MyClass + { + [PerformanceSensitive("uri")] + public void Testing() + { + var f1 = (object)5; // Allocation + var f2 = (object)"5"; // NO Allocation + } + } + """, + // Test0.cs(9,26): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(9, 26)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task TypeConversionAllocation_ArgumentWithImplicitStringCastOperatorAsync() - { - const string programWithoutImplicitCastOperator = @" -using System; -using Roslyn.Utilities; - -public struct AStruct -{ - [PerformanceSensitive(""uri"")] - public static void Dump(AStruct astruct) - { - System.Console.WriteLine(astruct); - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(programWithoutImplicitCastOperator, - // Test0.cs(10,34): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(9, 26)); + + [Fact] + public async Task TypeConversionAllocation_ArgumentWithImplicitStringCastOperatorAsync() + { + const string programWithoutImplicitCastOperator = """ + using System; + using Roslyn.Utilities; + + public struct AStruct + { + [PerformanceSensitive("uri")] + public static void Dump(AStruct astruct) + { + System.Console.WriteLine(astruct); + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(programWithoutImplicitCastOperator, + // Test0.cs(10,34): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(10, 34)); + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(9, 34)); #pragma warning restore RS0030 // Do not use banned APIs - const string programWithImplicitCastOperator = @" -using System; -using Roslyn.Utilities; - -public struct AStruct -{ - public readonly string WrappedString; - - public AStruct(string s) - { - WrappedString = s ?? """"; - } - - [PerformanceSensitive(""uri"")] - public static void Dump(AStruct astruct) - { - System.Console.WriteLine(astruct); - } - - [PerformanceSensitive(""uri"")] - public static implicit operator string(AStruct astruct) - { - return astruct.WrappedString; - } -}"; - await VerifyCS.VerifyAnalyzerAsync(programWithImplicitCastOperator); - } - - [Fact] - public async Task TypeConversionAllocation_YieldReturnImplicitStringCastOperatorAsync() - { - const string programWithoutImplicitCastOperator = @" -using System; -using Roslyn.Utilities; - -public struct AStruct -{ - [PerformanceSensitive(""uri"")] - public System.Collections.Generic.IEnumerator GetEnumerator() - { - yield return this; - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(programWithoutImplicitCastOperator, - // Test0.cs(10,22): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable + const string programWithImplicitCastOperator = """ + using System; + using Roslyn.Utilities; + + public struct AStruct + { + public readonly string WrappedString; + + public AStruct(string s) + { + WrappedString = s ?? ""; + } + + [PerformanceSensitive("uri")] + public static void Dump(AStruct astruct) + { + System.Console.WriteLine(astruct); + } + + [PerformanceSensitive("uri")] + public static implicit operator string(AStruct astruct) + { + return astruct.WrappedString; + } + } + """; + await VerifyCS.VerifyAnalyzerAsync(programWithImplicitCastOperator); + } + + [Fact] + public async Task TypeConversionAllocation_YieldReturnImplicitStringCastOperatorAsync() + { + const string programWithoutImplicitCastOperator = """ + using System; + using Roslyn.Utilities; + + public struct AStruct + { + [PerformanceSensitive("uri")] + public System.Collections.Generic.IEnumerator GetEnumerator() + { + yield return this; + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(programWithoutImplicitCastOperator, + // Test0.cs(10,22): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(10, 22)); + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(9, 22)); #pragma warning restore RS0030 // Do not use banned APIs - const string programWithImplicitCastOperator = @" -using System; -using Roslyn.Utilities; - -public struct AStruct -{ - [PerformanceSensitive(""uri"")] - public System.Collections.Generic.IEnumerator GetEnumerator() - { - yield return this; - } - - public static implicit operator string(AStruct astruct) - { - return """"; - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(programWithImplicitCastOperator); - } - - [Fact] - public async Task TypeConversionAllocation_InterpolatedStringWithInt_BoxingWarningAsync() - { - var source = @" -using System; -using Roslyn.Utilities; - -class Program -{ - [PerformanceSensitive(""uri"")] - void SomeMethod() - { - string s = $""{1}""; - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(source, - // Test0.cs(10,23): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable + const string programWithImplicitCastOperator = """ + using System; + using Roslyn.Utilities; + + public struct AStruct + { + [PerformanceSensitive("uri")] + public System.Collections.Generic.IEnumerator GetEnumerator() + { + yield return this; + } + + public static implicit operator string(AStruct astruct) + { + return ""; + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(programWithImplicitCastOperator); + } + + [Fact] + public Task TypeConversionAllocation_InterpolatedStringWithInt_BoxingWarningAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + class Program + { + [PerformanceSensitive("uri")] + void SomeMethod() + { + string s = $"{1}"; + } + } + """, + // Test0.cs(10,23): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(10, 23)); -#pragma warning restore RS0030 // Do not use banned APIs - } + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(9, 23)); #if false - [Fact] - public void TypeConversionAllocation_InterpolatedStringWithString_NoWarning() - { - var sampleProgram = @"string s = $""{1.ToString()}"";"; + [Fact] + public void TypeConversionAllocation_InterpolatedStringWithString_NoWarning() + { + var sampleProgram = @"string s = $""{1.ToString()}"";"; - var analyser = new TypeConversionAllocationAnalyzer(); - var info = ProcessCode(analyser, sampleProgram, ImmutableArray.Create(SyntaxKind.Interpolation)); + var analyser = new TypeConversionAllocationAnalyzer(); + var info = ProcessCode(analyser, sampleProgram, ImmutableArray.Create(SyntaxKind.Interpolation)); - Assert.Empty(info.Allocations); - } + Assert.Empty(info.Allocations); + } #endif - [Theory] - [InlineData(@"private readonly System.Func fileExists = System.IO.File.Exists;")] - [InlineData(@"private System.Func fileExists { get; } = System.IO.File.Exists;")] - [InlineData(@"private static System.Func fileExists { get; } = System.IO.File.Exists;")] - [InlineData(@"private static readonly System.Func fileExists = System.IO.File.Exists;")] - public async Task TypeConversionAllocation_DelegateAssignmentToReadonly_DoNotWarnAsync(string snippet) - { - var source = $@" -using System; -using Roslyn.Utilities; - -class Program -{{ - [PerformanceSensitive(""uri"")] - {snippet} -}}"; - - await VerifyCS.VerifyAnalyzerAsync(source, - // Test0.cs(8,68): info HeapAnalyzerReadonlyMethodGroupAllocationRule: This will allocate a delegate instance -#pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ReadonlyMethodGroupAllocationRule).WithLocation(8, 68)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task TypeConversionAllocation_ExpressionBodiedPropertyBoxing_WithBoxingAsync() - { - const string snippet = @" -using System; -using Roslyn.Utilities; - -class Program -{ - [PerformanceSensitive(""uri"")] - object Obj => 1; -}"; - - await VerifyCS.VerifyAnalyzerAsync(snippet, - // Test0.cs(8,19): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable -#pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(8, 19)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task TypeConversionAllocation_ExpressionBodiedPropertyBoxing_WithoutBoxingAsync() - { - const string snippet = @" -using System; -using Roslyn.Utilities; - -class Program -{ - [PerformanceSensitive(""uri"")] - object Obj => 1.ToString(); -}"; - - await VerifyCS.VerifyAnalyzerAsync(snippet); - } - - [Fact] - public async Task TypeConversionAllocation_ExpressionBodiedPropertyDelegateAsync() - { - const string snippet = @" -using System; -using Roslyn.Utilities; - -class Program -{ - void Function(int i) { } - - [PerformanceSensitive(""uri"")] - Action Obj => Function; -}"; - - await VerifyCS.VerifyAnalyzerAsync(snippet, - // Test0.cs(10,24): warning HAA0603: This will allocate a delegate instance + [Theory] + [InlineData(@"private readonly System.Func fileExists = System.IO.File.Exists;")] + [InlineData(@"private System.Func fileExists { get; } = System.IO.File.Exists;")] + [InlineData(@"private static System.Func fileExists { get; } = System.IO.File.Exists;")] + [InlineData(@"private static readonly System.Func fileExists = System.IO.File.Exists;")] + public Task TypeConversionAllocation_DelegateAssignmentToReadonly_DoNotWarnAsync(string snippet) + => VerifyCS.VerifyAnalyzerAsync($$""" + using System; + using Roslyn.Utilities; + + class Program + { + [PerformanceSensitive("uri")] + {{snippet}} + } + """, + // Test0.cs(8,68): info HeapAnalyzerReadonlyMethodGroupAllocationRule: This will allocate a delegate instance #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.MethodGroupAllocationRule).WithLocation(10, 24)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task TypeConversionAllocation_ExpressionBodiedPropertyExplicitDelegate_NoWarningAsync() - { - // Tests that an explicit delegate creation does not trigger HAA0603. It should be handled by HAA0502. - const string snippet = @" -using System; -using Roslyn.Utilities; - -class Program -{ - void Function(int i) { } - - [PerformanceSensitive(""uri"")] - Action Obj => new Action(Function); -}"; - - await VerifyCS.VerifyAnalyzerAsync(snippet); - } - - [Fact] - [WorkItem(7995606, "http://stackoverflow.com/questions/7995606/boxing-occurrence-in-c-sharp")] - public async Task Converting_any_enumeration_type_to_System_Enum_typeAsync() - { - var source = @" -using Roslyn.Utilities; + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ReadonlyMethodGroupAllocationRule).WithLocation(7, 68)); -enum E { A } - -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void SomeMethod() + [Fact] + public async Task TypeConversionAllocation_ExpressionBodiedPropertyBoxing_WithBoxingAsync() { - System.Enum box = E.A; - } -}"; - await VerifyCS.VerifyAnalyzerAsync(source, - // Test0.cs(11,27): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable -#pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(11, 27)); -#pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - [WorkItem(7995606, "http://stackoverflow.com/questions/7995606/boxing-occurrence-in-c-sharp")] - public async Task Creating_delegate_from_value_type_instance_methodAsync() - { - var source = @" -using System; -using Roslyn.Utilities; + const string snippet = """ + using System; + using Roslyn.Utilities; -struct S { public void M() {} } + class Program + { + [PerformanceSensitive("uri")] + object Obj => 1; + } + """; -public class MyClass -{ - [PerformanceSensitive(""uri"")] - public void SomeMethod() - { - Action box = new S().M; - } -}"; - await VerifyCS.VerifyAnalyzerAsync(source, - // Test0.cs(12,22): warning HAA0603: This will allocate a delegate instance -#pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.MethodGroupAllocationRule).WithLocation(12, 22), -#pragma warning restore RS0030 // Do not use banned APIs - // Test0.cs(12,22): warning HAA0602: Struct instance method being used for delegate creation, this will result in a boxing instruction + await VerifyCS.VerifyAnalyzerAsync(snippet, + // Test0.cs(8,19): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable #pragma warning disable RS0030 // Do not use banned APIs - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.DelegateOnStructInstanceRule).WithLocation(12, 22)); + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(7, 19)); #pragma warning restore RS0030 // Do not use banned APIs - } - - [Fact] - public async Task TypeConversionAllocation_NoDiagnosticWhenPassingDelegateAsArgumentAsync() - { - const string snippet = @" -using System; -using Roslyn.Utilities; - -struct Foo -{ - [PerformanceSensitive(""uri"")] - void Do(Action process) - { - DoMore(process); } - void DoMore(Action process) + [Fact] + public async Task TypeConversionAllocation_ExpressionBodiedPropertyBoxing_WithoutBoxingAsync() { - process(); - } -} - "; - await VerifyCS.VerifyAnalyzerAsync(snippet); - } - - [Fact] - public async Task TypeConversionAllocation_ReportBoxingAllocationForPassingStructInstanceMethodForDelegateConstructorAsync() - { - const string snippet = @" -using System; -using Roslyn.Utilities; - -public struct MyStruct -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - var @struct = new MyStruct(); - @struct.ProcessFunc(new Func(FooObjCall)); - } + const string snippet = """ + using System; + using Roslyn.Utilities; - public void ProcessFunc(Func func) - { - } + class Program + { + [PerformanceSensitive("uri")] + object Obj => 1.ToString(); + } + """; - private string FooObjCall(object obj) - { - return obj.ToString(); + await VerifyCS.VerifyAnalyzerAsync(snippet); } -} - "; - await VerifyCS.VerifyAnalyzerAsync(snippet, - // Test0.cs(11,54): warning HAA0602: Struct instance method being used for delegate creation, this will result in a boxing instruction - VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.DelegateOnStructInstanceRule).WithSpan(11, 54, 11, 64)); - } + [Fact] + public async Task TypeConversionAllocation_ExpressionBodiedPropertyDelegateAsync() + { + const string snippet = """ + using System; + using Roslyn.Utilities; - [Fact] - public async Task TypeConversionAllocation_DoNotReportBoxingAllocationForPassingStructStaticMethodForDelegateConstructorAsync() - { - const string snippet = @" -using System; -using Roslyn.Utilities; + class Program + { + void Function(int i) { } -public struct MyStruct -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - var @struct = new MyStruct(); - @struct.ProcessFunc(new Func(FooObjCall)); - } + [PerformanceSensitive("uri")] + Action Obj => Function; + } + """; - public void ProcessFunc(Func func) - { + await VerifyCS.VerifyAnalyzerAsync(snippet, + // Test0.cs(10,24): warning HAA0603: This will allocate a delegate instance +#pragma warning disable RS0030 // Do not use banned APIs + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.MethodGroupAllocationRule).WithLocation(9, 24)); +#pragma warning restore RS0030 // Do not use banned APIs } - private static string FooObjCall(object obj) + [Fact] + public async Task TypeConversionAllocation_ExpressionBodiedPropertyExplicitDelegate_NoWarningAsync() { - return obj.ToString(); - } -} - "; - - await VerifyCS.VerifyAnalyzerAsync(snippet); - } + // Tests that an explicit delegate creation does not trigger HAA0603. It should be handled by HAA0502. + const string snippet = """ + using System; + using Roslyn.Utilities; - [Fact] - public async Task TypeConversionAllocation_DoNotReportInlineDelegateAsStructInstanceMethodsAsync() - { - const string snippet = @" -using System; -using Roslyn.Utilities; + class Program + { + void Function(int i) { } -public struct MyStruct -{ - [PerformanceSensitive(""uri"")] - public void Testing() - { - var ints = new[] { 5, 4, 3, 2, 1 }; - Array.Sort(ints, delegate(int x, int y) { return x - y; }); - Array.Sort(ints, (x, y) => x - y); - DoSomething(() => throw new Exception()); - DoSomething(delegate() { throw new Exception(); }); + [PerformanceSensitive("uri")] + Action Obj => new Action(Function); + } + """; - DoSomething2(x => throw new Exception()); + await VerifyCS.VerifyAnalyzerAsync(snippet); } - private static void DoSomething(Action action) - { - } + [Fact] + [WorkItem(7995606, "http://stackoverflow.com/questions/7995606/boxing-occurrence-in-c-sharp")] + public Task Converting_any_enumeration_type_to_System_Enum_typeAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using Roslyn.Utilities; - private static void DoSomething2(Action action) - { - } -} - "; + enum E { A } - await VerifyCS.VerifyAnalyzerAsync(snippet); - } + public class MyClass + { + [PerformanceSensitive("uri")] + public void SomeMethod() + { + System.Enum box = E.A; + } + } + """, + // Test0.cs(11,27): warning HAA0601: Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable +#pragma warning disable RS0030 // Do not use banned APIs + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.ValueTypeToReferenceTypeConversionRule).WithLocation(10, 27)); + + [Fact] + [WorkItem(7995606, "http://stackoverflow.com/questions/7995606/boxing-occurrence-in-c-sharp")] + public Task Creating_delegate_from_value_type_instance_methodAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + using Roslyn.Utilities; + + struct S { public void M() {} } + + public class MyClass + { + [PerformanceSensitive("uri")] + public void SomeMethod() + { + Action box = new S().M; + } + } + """, + // Test0.cs(12,22): warning HAA0603: This will allocate a delegate instance +#pragma warning disable RS0030 // Do not use banned APIs + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.MethodGroupAllocationRule).WithLocation(11, 22), +#pragma warning restore RS0030 // Do not use banned APIs + // Test0.cs(12,22): warning HAA0602: Struct instance method being used for delegate creation, this will result in a boxing instruction +#pragma warning disable RS0030 // Do not use banned APIs + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.DelegateOnStructInstanceRule).WithLocation(11, 22)); + + [Fact] + public async Task TypeConversionAllocation_NoDiagnosticWhenPassingDelegateAsArgumentAsync() + { + const string snippet = """ + using System; + using Roslyn.Utilities; + + struct Foo + { + [PerformanceSensitive("uri")] + void Do(Action process) + { + DoMore(process); + } + + void DoMore(Action process) + { + process(); + } + } + """; + await VerifyCS.VerifyAnalyzerAsync(snippet); + } + + [Fact] + public async Task TypeConversionAllocation_ReportBoxingAllocationForPassingStructInstanceMethodForDelegateConstructorAsync() + { + const string snippet = """ + using System; + using Roslyn.Utilities; + + public struct MyStruct + { + [PerformanceSensitive("uri")] + public void Testing() + { + var @struct = new MyStruct(); + @struct.ProcessFunc(new Func(FooObjCall)); + } + + public void ProcessFunc(Func func) + { + } + + private string FooObjCall(object obj) + { + return obj.ToString(); + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(snippet, + // Test0.cs(11,54): warning HAA0602: Struct instance method being used for delegate creation, this will result in a boxing instruction + VerifyCS.Diagnostic(TypeConversionAllocationAnalyzer.DelegateOnStructInstanceRule).WithSpan(10, 54, 10, 64)); + } + + [Fact] + public async Task TypeConversionAllocation_DoNotReportBoxingAllocationForPassingStructStaticMethodForDelegateConstructorAsync() + { + const string snippet = """ + using System; + using Roslyn.Utilities; + + public struct MyStruct + { + [PerformanceSensitive("uri")] + public void Testing() + { + var @struct = new MyStruct(); + @struct.ProcessFunc(new Func(FooObjCall)); + } + + public void ProcessFunc(Func func) + { + } + + private static string FooObjCall(object obj) + { + return obj.ToString(); + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(snippet); + } + + [Fact] + public async Task TypeConversionAllocation_DoNotReportInlineDelegateAsStructInstanceMethodsAsync() + { + const string snippet = """ + using System; + using Roslyn.Utilities; + + public struct MyStruct + { + [PerformanceSensitive("uri")] + public void Testing() + { + var ints = new[] { 5, 4, 3, 2, 1 }; + Array.Sort(ints, delegate(int x, int y) { return x - y; }); + Array.Sort(ints, (x, y) => x - y); + DoSomething(() => throw new Exception()); + DoSomething(delegate() { throw new Exception(); }); + + DoSomething2(x => throw new Exception()); + } + + private static void DoSomething(Action action) + { + } + + private static void DoSomething2(Action action) + { + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(snippet); } } diff --git a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/VisualBasicPerformanceCodeFixVerifier`2.cs b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/VisualBasicPerformanceCodeFixVerifier`2.cs index e13b2a47d0c1e..ca24d689c87f9 100644 --- a/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/VisualBasicPerformanceCodeFixVerifier`2.cs +++ b/src/RoslynAnalyzers/PerformanceSensitiveAnalyzers/UnitTests/VisualBasicPerformanceCodeFixVerifier`2.cs @@ -14,31 +14,31 @@ public static partial class VisualBasicPerformanceCodeFixVerifier - Friend NotInheritable Class PerformanceSensitiveAttribute - Inherits Attribute + Namespace Global.Roslyn.Utilities + + Friend NotInheritable Class PerformanceSensitiveAttribute + Inherits Attribute - Public Sub New(uri As String) - Me.Uri = uri - End Sub + Public Sub New(uri As String) + Me.Uri = uri + End Sub - Public ReadOnly Property Uri As String - Public Property Constraint As String - Public Property AllowCaptures As Boolean - Public Property AllowGenericEnumeration As Boolean - Public Property AllowLocks As Boolean - Public Property OftenCompletesSynchronously As Boolean - Public Property IsParallelEntry As Boolean - End Class -End Namespace -"; + Public ReadOnly Property Uri As String + Public Property Constraint As String + Public Property AllowCaptures As Boolean + Public Property AllowGenericEnumeration As Boolean + Public Property AllowLocks As Boolean + Public Property OftenCompletesSynchronously As Boolean + Public Property IsParallelEntry As Boolean + End Class + End Namespace + """; public static DiagnosticResult Diagnostic() => VisualBasicCodeFixVerifier.Diagnostic(); @@ -71,7 +71,7 @@ public static Task VerifyCodeFixAsync(string source, string fixedSource) => VerifyCodeFixAsync(source, DiagnosticResult.EmptyDiagnosticResults, fixedSource); public static Task VerifyCodeFixAsync(string source, DiagnosticResult expected, string fixedSource) - => VerifyCodeFixAsync(source, new[] { expected }, fixedSource); + => VerifyCodeFixAsync(source, [expected], fixedSource); public static async Task VerifyCodeFixAsync(string source, DiagnosticResult[] expected, string fixedSource) { diff --git a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/DeclarePublicApiAnalyzer.Impl.cs b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/DeclarePublicApiAnalyzer.Impl.cs index 543198664b6c4..7324bc17a418c 100644 --- a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/DeclarePublicApiAnalyzer.Impl.cs +++ b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/DeclarePublicApiAnalyzer.Impl.cs @@ -13,10 +13,13 @@ using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Analyzer.Utilities.Lightup; -using Analyzer.Utilities.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Shared.Extensions; +using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.PublicApiAnalyzers { @@ -138,7 +141,7 @@ internal void OnPropertyAction(SymbolAnalysisContext symbolContext) } } - private void CheckPropertyAccessor(SymbolAnalysisContext symbolContext, IMethodSymbol accessor) + private void CheckPropertyAccessor(SymbolAnalysisContext symbolContext, IMethodSymbol? accessor) { if (accessor == null) { @@ -294,7 +297,7 @@ private void OnSymbolActionCore(ISymbol symbol, Action reportDiagnos if (publicApiName.Name != publicApiName.NameWithNullability) { // '#nullable enable' would be useful and should be set - reportDiagnosticAtLocations(GetDiagnostic(ShouldAnnotatePublicApiFilesRule, ShouldAnnotateInternalApiFilesRule), ImmutableDictionary.Empty); + reportDiagnosticAtLocations(GetDiagnostic(ShouldAnnotatePublicApiFilesRule, ShouldAnnotateInternalApiFilesRule), ImmutableDictionary.Empty); } } @@ -315,7 +318,7 @@ private void OnSymbolActionCore(ISymbol symbol, Action reportDiagnos !CanTypeBeExtended(method.ContainingType.BaseType)) { string errorMessageName = GetErrorMessageName(method, isImplicitlyDeclaredConstructor); - ImmutableDictionary propertyBag = ImmutableDictionary.Empty; + ImmutableDictionary propertyBag = ImmutableDictionary.Empty; var locations = isImplicitlyDeclaredConstructor ? method.ContainingType.Locations : method.Locations; reportDiagnostic(Diagnostic.Create(GetDiagnostic(ExposedNoninstantiableTypePublic, ExposedNoninstantiableTypeInternal), locations[0], propertyBag, errorMessageName)); } @@ -352,7 +355,7 @@ private void OnSymbolActionCore(ISymbol symbol, Action reportDiagnos { string errorMessageName = GetErrorMessageName(method, isImplicitlyDeclaredConstructor); var diagnostic = GetDiagnostic(AvoidMultipleOverloadsWithOptionalParametersPublic, AvoidMultipleOverloadsWithOptionalParametersInternal); - reportDiagnosticAtLocations(diagnostic, ImmutableDictionary.Empty, errorMessageName, diagnostic.HelpLinkUri); + reportDiagnosticAtLocations(diagnostic, ImmutableDictionary.Empty, errorMessageName, diagnostic.HelpLinkUri); break; } @@ -365,7 +368,7 @@ private void OnSymbolActionCore(ISymbol symbol, Action reportDiagnos { string errorMessageName = GetErrorMessageName(method, isImplicitlyDeclaredConstructor); var diagnostic = GetDiagnostic(OverloadWithOptionalParametersShouldHaveMostParametersPublic, OverloadWithOptionalParametersShouldHaveMostParametersInternal); - reportDiagnosticAtLocations(diagnostic, ImmutableDictionary.Empty, errorMessageName, diagnostic.HelpLinkUri); + reportDiagnosticAtLocations(diagnostic, ImmutableDictionary.Empty, errorMessageName, diagnostic.HelpLinkUri); break; } else if (!overloadHasOptionalParams) @@ -377,7 +380,7 @@ private void OnSymbolActionCore(ISymbol symbol, Action reportDiagnos { string errorMessageName = GetErrorMessageName(method, isImplicitlyDeclaredConstructor); var diagnostic = GetDiagnostic(OverloadWithOptionalParametersShouldHaveMostParametersPublic, OverloadWithOptionalParametersShouldHaveMostParametersInternal); - reportDiagnosticAtLocations(diagnostic, ImmutableDictionary.Empty, errorMessageName, diagnostic.HelpLinkUri); + reportDiagnosticAtLocations(diagnostic, ImmutableDictionary.Empty, errorMessageName, diagnostic.HelpLinkUri); break; } } @@ -389,7 +392,7 @@ private void OnSymbolActionCore(ISymbol symbol, Action reportDiagnos return; // local functions - void reportDiagnosticAtLocations(DiagnosticDescriptor descriptor, ImmutableDictionary propertyBag, params object[] args) + void reportDiagnosticAtLocations(DiagnosticDescriptor descriptor, ImmutableDictionary propertyBag, params object[] args) { foreach (var location in locationsToReport) { @@ -410,7 +413,7 @@ void reportDeclareNewApi(ISymbol symbol, bool isImplicitlyDeclaredConstructor, s string errorMessageName = GetErrorMessageName(symbol, isImplicitlyDeclaredConstructor); // Compute public API names for any stale siblings to remove from unshipped text (e.g. during signature change of unshipped public API). var siblingPublicApiNamesToRemove = GetSiblingNamesToRemoveFromUnshippedText(symbol, cancellationToken); - ImmutableDictionary propertyBag = ImmutableDictionary.Empty + ImmutableDictionary propertyBag = ImmutableDictionary.Empty .Add(ApiNamePropertyBagKey, publicApiName) .Add(MinimalNamePropertyBagKey, errorMessageName) .Add(ApiNamesOfSiblingsToRemovePropertyBagKey, siblingPublicApiNamesToRemove); @@ -422,7 +425,7 @@ void reportAnnotateApi(ISymbol symbol, bool isImplicitlyDeclaredConstructor, Api { // Public API missing annotations in public API file - report diagnostic. string errorMessageName = GetErrorMessageName(symbol, isImplicitlyDeclaredConstructor); - ImmutableDictionary propertyBag = ImmutableDictionary.Empty + ImmutableDictionary propertyBag = ImmutableDictionary.Empty .Add(ApiNamePropertyBagKey, publicApiName.Name) .Add(ApiNameWithNullabilityPropertyBagKey, withObliviousIfNeeded(publicApiName.NameWithNullability)) .Add(MinimalNamePropertyBagKey, errorMessageName) @@ -442,7 +445,7 @@ void reportObliviousApi(ISymbol symbol) // Public API using oblivious types in public API file - report diagnostic. string errorMessageName = GetErrorMessageName(symbol, isImplicitlyDeclaredConstructor); - reportDiagnosticAtLocations(GetDiagnostic(ObliviousPublicApiRule, ObliviousInternalApiRule), ImmutableDictionary.Empty, errorMessageName); + reportDiagnosticAtLocations(GetDiagnostic(ObliviousPublicApiRule, ObliviousInternalApiRule), ImmutableDictionary.Empty, errorMessageName); } bool lookupPublicApi(ApiName overloadPublicApiName, out ApiLine overloadPublicApiLine) @@ -702,7 +705,8 @@ private void ProcessTypeForwardedAttributes(Compilation compilation, Action reportDiagnostic) } Location location = pair.Value.GetLocation(_additionalFiles); - ImmutableDictionary propertyBag = ImmutableDictionary.Empty.Add(ApiNamePropertyBagKey, pair.Value.Text); + ImmutableDictionary propertyBag = ImmutableDictionary.Empty.Add(ApiNamePropertyBagKey, pair.Value.Text); reportDiagnostic(Diagnostic.Create(GetDiagnostic(RemoveDeletedPublicApiRule, RemoveDeletedInternalApiRule), location, propertyBag, pair.Value.Text)); } } @@ -802,7 +806,7 @@ private bool IsTrackedAPI(ISymbol symbol, CancellationToken cancellationToken) return false; } - if (IsNamespaceSkipped(symbol, cancellationToken)) + if (IsNamespaceSkipped(symbol)) { return false; } @@ -810,7 +814,7 @@ private bool IsTrackedAPI(ISymbol symbol, CancellationToken cancellationToken) return IsTrackedApiCore(symbol, cancellationToken); } - private bool IsNamespaceSkipped(ISymbol symbol, CancellationToken cancellationToken) + private bool IsNamespaceSkipped(ISymbol symbol) { var @namespace = symbol as INamespaceSymbol ?? symbol.ContainingNamespace; @@ -845,7 +849,7 @@ private bool IsNamespaceSkipped(ISymbol symbol, CancellationToken cancellationTo } finally { - skippedNamespaces?.Free(cancellationToken); + skippedNamespaces?.Free(); } } @@ -968,7 +972,7 @@ public override bool VisitNamedType(INamedTypeSymbol symbol) { if (!_ignoreTopLevelNullability && symbol.IsReferenceType && - symbol.NullableAnnotation() == NullableAnnotation.None) + symbol.NullableAnnotation == NullableAnnotation.None) { return true; } @@ -992,7 +996,7 @@ public override bool VisitNamedType(INamedTypeSymbol symbol) public override bool VisitArrayType(IArrayTypeSymbol symbol) { - if (symbol.NullableAnnotation() == NullableAnnotation.None) + if (symbol.NullableAnnotation == NullableAnnotation.None) { return true; } @@ -1009,7 +1013,7 @@ public override bool VisitPointerType(IPointerTypeSymbol symbol) public override bool VisitTypeParameter(ITypeParameterSymbol symbol) { if (symbol.IsReferenceType && - symbol.NullableAnnotation() == NullableAnnotation.None) + symbol.NullableAnnotation == NullableAnnotation.None) { // Example: // I @@ -1036,7 +1040,7 @@ public static bool VisitNamedTypeDeclaration(INamedTypeSymbol symbol) private static bool CheckTypeParameterConstraints(ITypeParameterSymbol symbol) { if (symbol.HasReferenceTypeConstraint() && - symbol.ReferenceTypeConstraintNullableAnnotation() == NullableAnnotation.None) + symbol.ReferenceTypeConstraintNullableAnnotation == NullableAnnotation.None) { // where T : class~ return true; diff --git a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/DeclarePublicApiAnalyzer.cs b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/DeclarePublicApiAnalyzer.cs index 79ecd049f7116..7890ac01ec697 100644 --- a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/DeclarePublicApiAnalyzer.cs +++ b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/DeclarePublicApiAnalyzer.cs @@ -9,8 +9,8 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; -using Analyzer.Utilities.PooledObjects; using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.PublicApiAnalyzers @@ -43,7 +43,7 @@ public sealed partial class DeclarePublicApiAnalyzer : DiagnosticAnalyzer internal const string FileName = "FileName"; private const char ObliviousMarker = '~'; - private static readonly char[] ObliviousMarkerArray = { ObliviousMarker }; + private static readonly char[] ObliviousMarkerArray = [ObliviousMarker]; /// /// Boolean option to configure if public API analyzer should bail out silently if public API files are missing. @@ -197,8 +197,8 @@ private static ApiData ReadApiData(SourceText sourceText, bool isShippedApi) private static bool TryGetApiData(CompilationStartAnalysisContext context, bool isPublic, List errors, [NotNullWhen(true)] out ImmutableDictionary? additionalFiles, [NotNullWhen(true)] out ApiData? shippedData, [NotNullWhen(true)] out ApiData? unshippedData) { - using var allShippedData = ArrayBuilder.GetInstance(); - using var allUnshippedData = ArrayBuilder.GetInstance(); + using var _1 = ArrayBuilder.GetInstance(out var allShippedData); + using var _2 = ArrayBuilder.GetInstance(out var allUnshippedData); AddApiTexts(context, isPublic, out additionalFiles, allShippedData, allUnshippedData); @@ -285,7 +285,7 @@ private static bool TryGetEditorConfigOption(AnalyzerOptions analyzerOptions, Sy return false; } - var options = getOptionsMethod.Invoke(provider, new object[] { tree }); + var options = getOptionsMethod.Invoke(provider, [tree]); var tryGetValueMethod = options.GetType().GetRuntimeMethods().FirstOrDefault(m => m.Name == "TryGetValue"); if (tryGetValueMethod == null) { @@ -334,7 +334,7 @@ private static bool TryGetEditorConfigOptionForSkippedNamespaces(AnalyzerOptions return false; } - var namespaceStrings = namespacesString.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + var namespaceStrings = namespacesString.Split([','], StringSplitOptions.RemoveEmptyEntries); if (namespaceStrings.Length == 0) { return false; @@ -366,6 +366,9 @@ private static void AddApiTexts( var apiDataProvider = file.IsShipping ? s_shippingApiDataProvider : s_nonShippingApiDataProvider; var text = additionalText.GetText(context.CancellationToken); + if (text is null) + continue; + additionalFiles = additionalFiles.Add(additionalText, text); if (!context.TryGetValue(text, apiDataProvider, out var apiData)) continue; @@ -395,9 +398,10 @@ private static bool ValidateApiFiles(ImmutableDictionary.GetInstance(StringComparer.Ordinal); + var publicApiMap = PooledDictionary.GetInstance(StringComparer.Ordinal); ValidateApiList(additionalFiles, publicApiMap, shippedData.ApiList, isPublic, errors); ValidateApiList(additionalFiles, publicApiMap, unshippedData.ApiList, isPublic, errors); + publicApiMap.Free(); return errors.Count == 0; } diff --git a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/ITypeParameterSymbolExtensions.cs b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/ITypeParameterSymbolExtensions.cs index dfc2573b8e92d..1027223a1475d 100644 --- a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/ITypeParameterSymbolExtensions.cs +++ b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/ITypeParameterSymbolExtensions.cs @@ -2,23 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using Microsoft.CodeAnalysis; namespace Analyzer.Utilities.Lightup { internal static class ITypeParameterSymbolExtensions { - private static readonly Func s_hasReferenceTypeConstraint - = LightupHelpers.CreateSymbolPropertyAccessor(typeof(ITypeParameterSymbol), nameof(HasReferenceTypeConstraint), fallbackResult: false); - - private static readonly Func s_referenceTypeConstraintNullableAnnotation - = LightupHelpers.CreateSymbolPropertyAccessor(typeof(ITypeParameterSymbol), nameof(ReferenceTypeConstraintNullableAnnotation), fallbackResult: Lightup.NullableAnnotation.None); - public static bool HasReferenceTypeConstraint(this ITypeParameterSymbol typeParameterSymbol) - => s_hasReferenceTypeConstraint(typeParameterSymbol); - - public static NullableAnnotation ReferenceTypeConstraintNullableAnnotation(this ITypeParameterSymbol typeParameterSymbol) - => s_referenceTypeConstraintNullableAnnotation(typeParameterSymbol); + => typeParameterSymbol.HasReferenceTypeConstraint; } } diff --git a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/ITypeSymbolExtensions.cs b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/ITypeSymbolExtensions.cs index 5a55a4c0c6769..7b0a93978b441 100644 --- a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/ITypeSymbolExtensions.cs +++ b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/ITypeSymbolExtensions.cs @@ -2,17 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using Microsoft.CodeAnalysis; namespace Analyzer.Utilities.Lightup { internal static class ITypeSymbolExtensions { - private static readonly Func s_nullableAnnotation - = LightupHelpers.CreateSymbolPropertyAccessor(typeof(ITypeSymbol), nameof(NullableAnnotation), fallbackResult: Lightup.NullableAnnotation.None); - public static NullableAnnotation NullableAnnotation(this ITypeSymbol typeSymbol) - => s_nullableAnnotation(typeSymbol); + => typeSymbol.NullableAnnotation; } } diff --git a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/Microsoft.CodeAnalysis.PublicApiAnalyzers.csproj b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/Microsoft.CodeAnalysis.PublicApiAnalyzers.csproj index 565b77f8080e6..a96fa2b8c2c90 100644 --- a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/Microsoft.CodeAnalysis.PublicApiAnalyzers.csproj +++ b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/Microsoft.CodeAnalysis.PublicApiAnalyzers.csproj @@ -7,11 +7,14 @@ Restore would conclude that there is a cyclic dependency between us and the Microsoft.CodeAnalysis.PublicApiAnalyzer package. --> *$(MSBuildProjectFile)* - $(MicrosoftCodeAnalysisVersionForPublicApiAnalyzers) + Microsoft.CodeAnalysis - + + + + @@ -24,4 +27,12 @@ + + + + + + + + diff --git a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/NullableAnnotation.cs b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/NullableAnnotation.cs deleted file mode 100644 index ce8d83bc6402d..0000000000000 --- a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/NullableAnnotation.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Diagnostics.CodeAnalysis; - -namespace Analyzer.Utilities.Lightup -{ - /// - /// Represents the nullability of values that can be assigned - /// to an expression used as an lvalue. - /// - [SuppressMessage("Design", "CA1028:Enum Storage should be Int32", Justification = "Underlying type must match the original underlying type.")] - internal enum NullableAnnotation : byte - { - /// - /// The expression has not been analyzed, or the syntax is - /// not an expression (such as a statement). - /// - /// - /// There are a few different reasons the expression could - /// have not been analyzed: - /// 1) The symbol producing the expression comes from - /// a method that has not been annotated, such as - /// invoking a C# 7.3 or earlier method, or a - /// method in this compilation that is in a disabled - /// context. - /// 2) Nullable is completely disabled in this - /// compilation. - /// - None = 0, - - /// - /// The expression is not annotated (does not have a ?). - /// - NotAnnotated, - - /// - /// The expression is annotated (does have a ?). - /// - Annotated, - } -} diff --git a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/PublicApiAnalyzerResources.cs b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/PublicApiAnalyzerResources.cs index bf96660a9afae..cf3b6dbc94a87 100644 --- a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/PublicApiAnalyzerResources.cs +++ b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/Analyzers/PublicApiAnalyzerResources.cs @@ -4,7 +4,7 @@ using System; -namespace Microsoft.CodeAnalysis.PublicApiAnalyzers +namespace Microsoft.CodeAnalysis { internal partial class PublicApiAnalyzerResources { diff --git a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/AnnotatePublicApiFix.cs b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/AnnotatePublicApiFix.cs index 5a81e7ffb01d1..66b30fdd3cdf6 100644 --- a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/AnnotatePublicApiFix.cs +++ b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/AnnotatePublicApiFix.cs @@ -38,10 +38,19 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) foreach (Diagnostic diagnostic in context.Diagnostics) { - string minimalSymbolName = diagnostic.Properties[DeclarePublicApiAnalyzer.MinimalNamePropertyBagKey]; - string publicSymbolName = diagnostic.Properties[DeclarePublicApiAnalyzer.ApiNamePropertyBagKey]; - string publicSymbolNameWithNullability = diagnostic.Properties[DeclarePublicApiAnalyzer.ApiNameWithNullabilityPropertyBagKey]; - string fileName = diagnostic.Properties[DeclarePublicApiAnalyzer.FileName]; + string? minimalSymbolName = diagnostic.Properties[DeclarePublicApiAnalyzer.MinimalNamePropertyBagKey]; + string? publicSymbolName = diagnostic.Properties[DeclarePublicApiAnalyzer.ApiNamePropertyBagKey]; + string? publicSymbolNameWithNullability = diagnostic.Properties[DeclarePublicApiAnalyzer.ApiNameWithNullabilityPropertyBagKey]; + string? fileName = diagnostic.Properties[DeclarePublicApiAnalyzer.FileName]; + + if (minimalSymbolName is null || + publicSymbolName is null || + publicSymbolNameWithNullability is null || + fileName is null) + { + // If any of the required properties are missing, we cannot register a fix. + continue; + } TextDocument? document = project.GetPublicApiDocument(fileName); @@ -59,7 +68,7 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) return Task.CompletedTask; - static async Task GetFixAsync(TextDocument publicSurfaceAreaDocument, string oldSymbolName, string newSymbolName, CancellationToken cancellationToken) + static async Task GetFixAsync(TextDocument publicSurfaceAreaDocument, string oldSymbolName, string newSymbolName, CancellationToken cancellationToken) { SourceText sourceText = await publicSurfaceAreaDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); SourceText newSourceText = AnnotateSymbolNamesInSourceText(sourceText, new Dictionary { [oldSymbolName] = newSymbolName }); @@ -111,24 +120,24 @@ public FixAllAdditionalDocumentChangeAction(string title, Solution solution, Lis foreach (var (project, diagnostics) in _diagnosticsToFix) { - IEnumerable> groupedDiagnostics = + IEnumerable> groupedDiagnostics = diagnostics .Where(d => d.Location.IsInSource) .GroupBy(d => d.Location.SourceTree); var allChanges = new Dictionary>(); - foreach (IGrouping grouping in groupedDiagnostics) + foreach (IGrouping grouping in groupedDiagnostics) { - Document document = project.GetDocument(grouping.Key); + Document? document = project.GetDocument(grouping.Key); if (document is null) { continue; } - SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); + SyntaxNode? root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + SemanticModel? semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (Diagnostic diagnostic in grouping) { @@ -141,10 +150,17 @@ public FixAllAdditionalDocumentChangeAction(string title, Solution solution, Lis continue; } - string oldName = diagnostic.Properties[DeclarePublicApiAnalyzer.ApiNamePropertyBagKey]; - string newName = diagnostic.Properties[DeclarePublicApiAnalyzer.ApiNameWithNullabilityPropertyBagKey]; + string? oldName = diagnostic.Properties[DeclarePublicApiAnalyzer.ApiNamePropertyBagKey]; + string? newName = diagnostic.Properties[DeclarePublicApiAnalyzer.ApiNameWithNullabilityPropertyBagKey]; bool isShipped = diagnostic.Properties[DeclarePublicApiAnalyzer.ApiIsShippedPropertyBagKey] == "true"; - string fileName = diagnostic.Properties[DeclarePublicApiAnalyzer.FileName]; + string? fileName = diagnostic.Properties[DeclarePublicApiAnalyzer.FileName]; + + if (oldName is null || + newName is null || + fileName is null) + { + continue; + } if (!allChanges.TryGetValue(fileName, out var mapToUpdate)) { @@ -190,9 +206,10 @@ private class PublicSurfaceAreaFixAllProvider : FixAllProvider { case FixAllScope.Document: { - ImmutableArray diagnostics = await fixAllContext.GetDocumentDiagnosticsAsync(fixAllContext.Document).ConfigureAwait(false); + Document document = fixAllContext.Document!; + ImmutableArray diagnostics = await fixAllContext.GetDocumentDiagnosticsAsync(document).ConfigureAwait(false); diagnosticsToFix.Add(new KeyValuePair>(fixAllContext.Project, diagnostics)); - title = string.Format(CultureInfo.InvariantCulture, PublicApiAnalyzerResources.AddAllItemsInDocumentToTheApiTitle, fixAllContext.Document.Name); + title = string.Format(CultureInfo.InvariantCulture, PublicApiAnalyzerResources.AddAllItemsInDocumentToTheApiTitle, document.Name); break; } diff --git a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/DeclarePublicApiFix.cs b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/DeclarePublicApiFix.cs index fc3c8cf1f154b..2a9a44ebefc03 100644 --- a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/DeclarePublicApiFix.cs +++ b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/DeclarePublicApiFix.cs @@ -11,10 +11,10 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using Analyzer.Utilities.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Diagnostics.Analyzers; using DiagnosticIds = Roslyn.Diagnostics.Analyzers.RoslynDiagnosticIds; @@ -40,9 +40,15 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) foreach (Diagnostic diagnostic in context.Diagnostics) { bool isPublic = diagnostic.Id == DiagnosticIds.DeclarePublicApiRuleId; - string minimalSymbolName = diagnostic.Properties[DeclarePublicApiAnalyzer.MinimalNamePropertyBagKey]; - string publicSurfaceAreaSymbolName = diagnostic.Properties[DeclarePublicApiAnalyzer.ApiNamePropertyBagKey]; - ImmutableHashSet siblingSymbolNamesToRemove = diagnostic.Properties[DeclarePublicApiAnalyzer.ApiNamesOfSiblingsToRemovePropertyBagKey] + string? minimalSymbolName = diagnostic.Properties[DeclarePublicApiAnalyzer.MinimalNamePropertyBagKey]; + string? publicSurfaceAreaSymbolName = diagnostic.Properties[DeclarePublicApiAnalyzer.ApiNamePropertyBagKey]; + string? siblingsToRemoveSymbolNames = diagnostic.Properties[DeclarePublicApiAnalyzer.ApiNamesOfSiblingsToRemovePropertyBagKey]; + if (minimalSymbolName == null || publicSurfaceAreaSymbolName == null || siblingsToRemoveSymbolNames == null) + { + continue; + } + + ImmutableHashSet siblingSymbolNamesToRemove = siblingsToRemoveSymbolNames .Split(DeclarePublicApiAnalyzer.ApiNamesOfSiblingsToRemovePropertyBagValueSeparator.ToCharArray()) .ToImmutableHashSet(); @@ -67,6 +73,12 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) foreach (var additional in project.AdditionalDocuments) { + if (additional.FilePath == null) + { + // Skip documents without a file path, as they cannot be public API files. + continue; + } + var file = new PublicApiFile(additional.FilePath, isPublic); if (file.IsApiFile && !file.IsShipping) @@ -82,7 +94,7 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) } } - private static async Task GetFixAsync(TextDocument? surfaceAreaDocument, bool isPublic, Project project, string newSymbolName, ImmutableHashSet siblingSymbolNamesToRemove, CancellationToken cancellationToken) + private static async Task GetFixAsync(TextDocument? surfaceAreaDocument, bool isPublic, Project project, string newSymbolName, ImmutableHashSet siblingSymbolNamesToRemove, CancellationToken cancellationToken) { if (surfaceAreaDocument == null) { @@ -187,9 +199,9 @@ internal static List GetLinesFromSourceText(SourceText? sourceText) internal class AdditionalDocumentChangeAction : CodeAction { - private readonly Func> _createChangedAdditionalDocument; + private readonly Func> _createChangedAdditionalDocument; - public AdditionalDocumentChangeAction(string title, DocumentId? apiDocId, bool isPublic, Func> createChangedAdditionalDocument) + public AdditionalDocumentChangeAction(string title, DocumentId? apiDocId, bool isPublic, Func> createChangedAdditionalDocument) { this.Title = title; EquivalenceKey = apiDocId.CreateEquivalenceKey(isPublic); @@ -200,7 +212,7 @@ public AdditionalDocumentChangeAction(string title, DocumentId? apiDocId, bool i public override string EquivalenceKey { get; } - protected override Task GetChangedSolutionAsync(CancellationToken cancellationToken) + protected override Task GetChangedSolutionAsync(CancellationToken cancellationToken) { return _createChangedAdditionalDocument(cancellationToken); } @@ -239,7 +251,7 @@ public FixAllAdditionalDocumentChangeAction(string title, DocumentId? apiDocId, await publicSurfaceAreaAdditionalDocument.GetTextAsync(cancellationToken).ConfigureAwait(false) : null; - IEnumerable> groupedDiagnostics = + IEnumerable> groupedDiagnostics = diagnostics .Where(d => d.Location.IsInSource) .GroupBy(d => d.Location.SourceTree); @@ -247,17 +259,17 @@ await publicSurfaceAreaAdditionalDocument.GetTextAsync(cancellationToken).Config var newSymbolNames = new SortedSet(IgnoreCaseWhenPossibleComparer.Instance); var symbolNamesToRemoveBuilder = PooledHashSet.GetInstance(); - foreach (IGrouping grouping in groupedDiagnostics) + foreach (IGrouping grouping in groupedDiagnostics) { - Document document = project.GetDocument(grouping.Key); + Document? document = project.GetDocument(grouping.Key); if (document == null) { continue; } - SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); + SyntaxNode? root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + SemanticModel? semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (Diagnostic diagnostic in grouping) { @@ -269,12 +281,16 @@ or RoslynDiagnosticIds.ObliviousPublicApiRuleId continue; } - string publicSurfaceAreaSymbolName = diagnostic.Properties[DeclarePublicApiAnalyzer.ApiNamePropertyBagKey]; + string? publicSurfaceAreaSymbolName = diagnostic.Properties[DeclarePublicApiAnalyzer.ApiNamePropertyBagKey]; + if (publicSurfaceAreaSymbolName == null) + { + continue; + } newSymbolNames.Add(publicSurfaceAreaSymbolName); - string siblingNamesToRemove = diagnostic.Properties[DeclarePublicApiAnalyzer.ApiNamesOfSiblingsToRemovePropertyBagKey]; - if (siblingNamesToRemove.Length > 0) + string? siblingNamesToRemove = diagnostic.Properties[DeclarePublicApiAnalyzer.ApiNamesOfSiblingsToRemovePropertyBagKey]; + if (siblingNamesToRemove is { Length: > 0 }) { var namesToRemove = siblingNamesToRemove.Split(DeclarePublicApiAnalyzer.ApiNamesOfSiblingsToRemovePropertyBagValueSeparator.ToCharArray()); foreach (var nameToRemove in namesToRemove) @@ -285,7 +301,8 @@ or RoslynDiagnosticIds.ObliviousPublicApiRuleId } } - var symbolNamesToRemove = symbolNamesToRemoveBuilder.ToImmutableAndFree(); + var symbolNamesToRemove = symbolNamesToRemoveBuilder.ToImmutableHashSet(); + symbolNamesToRemoveBuilder.Free(); // We shouldn't be attempting to remove any symbol name, while also adding it. Debug.Assert(newSymbolNames.All(newSymbolName => !symbolNamesToRemove.Contains(newSymbolName))); @@ -311,10 +328,15 @@ or RoslynDiagnosticIds.ObliviousPublicApiRuleId } // NOTE: We need to avoid creating duplicate files for multi-tfm projects. See https://github.com/dotnet/roslyn-analyzers/issues/3952. - using var uniqueProjectPaths = PooledHashSet.GetInstance(); + using var _ = PooledHashSet.GetInstance(out var uniqueProjectPaths); foreach (KeyValuePair pair in addedPublicSurfaceAreaText) { var project = newSolution.GetProject(pair.Key); + if (project == null) + { + continue; + } + if (uniqueProjectPaths.Add(project.FilePath ?? project.Name)) { newSolution = AddPublicApiFiles(project, pair.Value, _isPublic); @@ -335,9 +357,10 @@ private class PublicSurfaceAreaFixAllProvider : FixAllProvider { case FixAllScope.Document: { - ImmutableArray diagnostics = await fixAllContext.GetDocumentDiagnosticsAsync(fixAllContext.Document).ConfigureAwait(false); + Document document = fixAllContext.Document!; + ImmutableArray diagnostics = await fixAllContext.GetDocumentDiagnosticsAsync(document).ConfigureAwait(false); diagnosticsToFix.Add(new KeyValuePair>(fixAllContext.Project, diagnostics)); - title = string.Format(CultureInfo.InvariantCulture, PublicApiAnalyzerResources.AddAllItemsInDocumentToTheApiTitle, fixAllContext.Document.Name); + title = string.Format(CultureInfo.InvariantCulture, PublicApiAnalyzerResources.AddAllItemsInDocumentToTheApiTitle, document.Name); break; } diff --git a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/Microsoft.CodeAnalysis.PublicApiAnalyzers.CodeFixes.csproj b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/Microsoft.CodeAnalysis.PublicApiAnalyzers.CodeFixes.csproj index ae78c84642fb0..d2185aab06d81 100644 --- a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/Microsoft.CodeAnalysis.PublicApiAnalyzers.CodeFixes.csproj +++ b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/Microsoft.CodeAnalysis.PublicApiAnalyzers.CodeFixes.csproj @@ -7,7 +7,6 @@ Restore would conclude that there is a cyclic dependency between us and the DotNetAnalyzers.PublicApiAnalyzer.CodeFixes package. --> *$(MSBuildProjectFile)* - $(MicrosoftCodeAnalysisVersionForPublicApiAnalyzers) true @@ -16,8 +15,8 @@ - - + + diff --git a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/NullableEnablePublicApiFix.cs b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/NullableEnablePublicApiFix.cs index 16cb4f0293ffc..c3e5978aa1342 100644 --- a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/NullableEnablePublicApiFix.cs +++ b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/NullableEnablePublicApiFix.cs @@ -10,9 +10,9 @@ using System.Globalization; using System.Threading; using System.Threading.Tasks; -using Analyzer.Utilities.PooledObjects; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using DiagnosticIds = Roslyn.Diagnostics.Analyzers.RoslynDiagnosticIds; @@ -53,7 +53,7 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) return Task.CompletedTask; } - private static async Task GetFixAsync(TextDocument surfaceAreaDocument, CancellationToken cancellationToken) + private static async Task GetFixAsync(TextDocument surfaceAreaDocument, CancellationToken cancellationToken) { SourceText sourceText = await surfaceAreaDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); SourceText newSourceText = AddNullableEnable(sourceText); @@ -86,7 +86,7 @@ public FixAllAdditionalDocumentChangeAction(string title, Solution solution, Lis { var updatedSurfaceAreaText = new List<(DocumentId, SourceText)>(); - using var uniqueShippedDocuments = PooledHashSet.GetInstance(); + using var _ = PooledHashSet.GetInstance(out var uniqueShippedDocuments); foreach (var project in _projectsToFix) { foreach (var isPublic in new[] { true, false }) diff --git a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/PublicApiFixHelpers.cs b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/PublicApiFixHelpers.cs index 542bae97e2562..3441beb243a8a 100644 --- a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/PublicApiFixHelpers.cs +++ b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/PublicApiFixHelpers.cs @@ -12,7 +12,7 @@ namespace Microsoft.CodeAnalysis.PublicApiAnalyzers { internal static class PublicApiFixHelpers { - private static readonly char[] SemicolonSplit = new[] { ';' }; + private static readonly char[] SemicolonSplit = [';']; internal static void Deconstruct(this KeyValuePair kv, out TKey key, out TValue value) { @@ -37,7 +37,14 @@ internal static string CreateEquivalenceKey(this DocumentId? doc, bool isPublic) internal static DocumentId? CreateDocIdFromEquivalenceKey(this FixAllContext fixAllContext, out bool isPublic) { - var split = fixAllContext.CodeActionEquivalenceKey.Split(SemicolonSplit, StringSplitOptions.RemoveEmptyEntries); + var equivalenceKey = fixAllContext.CodeActionEquivalenceKey; + if (equivalenceKey is null) + { + isPublic = false; + return null; + } + + var split = equivalenceKey.Split(SemicolonSplit, StringSplitOptions.RemoveEmptyEntries); isPublic = bool.Parse(split[^1]); diff --git a/src/RoslynAnalyzers/PublicApiAnalyzers/UnitTests/AnnotatePublicApiAnalyzerTestsBase.cs b/src/RoslynAnalyzers/PublicApiAnalyzers/UnitTests/AnnotatePublicApiAnalyzerTestsBase.cs index fc3a32d6dc09f..dda55cb9cc8b1 100644 --- a/src/RoslynAnalyzers/PublicApiAnalyzers/UnitTests/AnnotatePublicApiAnalyzerTestsBase.cs +++ b/src/RoslynAnalyzers/PublicApiAnalyzers/UnitTests/AnnotatePublicApiAnalyzerTestsBase.cs @@ -53,10 +53,8 @@ private async Task VerifyCSharpAsync(string source, string shippedApiText, strin await test.RunAsync(); } - private async Task VerifyCSharpAdditionalFileFixAsync(string source, string oldShippedApiText, string oldUnshippedApiText, string newShippedApiText, string newUnshippedApiText) - { - await VerifyAdditionalFileFixAsync(source, oldShippedApiText, oldUnshippedApiText, newShippedApiText, newUnshippedApiText); - } + private Task VerifyCSharpAdditionalFileFixAsync(string source, string oldShippedApiText, string oldUnshippedApiText, string newShippedApiText, string newUnshippedApiText) + => VerifyAdditionalFileFixAsync(source, oldShippedApiText, oldUnshippedApiText, newShippedApiText, newUnshippedApiText); private async Task VerifyAdditionalFileFixAsync(string source, string oldShippedApiText, string oldUnshippedApiText, string newShippedApiText, string newUnshippedApiText) { @@ -76,42 +74,30 @@ private async Task VerifyAdditionalFileFixAsync(string source, string oldShipped #region Fix tests [Fact, WorkItem(4040, "https://github.com/dotnet/roslyn-analyzers/issues/4040")] - public async Task NoObliviousWhenUnannotatedClassConstraintAsync() - { - var source = $$""" + public Task NoObliviousWhenUnannotatedClassConstraintAsync() + => VerifyCSharpAsync($$""" #nullable enable {{EnabledModifier}} class C where T : class { } - """; - - var shippedText = @""; - var unshippedText = @"#nullable enable -C.C() -> void -C -"; - - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + """, @"", """ + #nullable enable + C.C() -> void + C + """); [Fact, WorkItem(4040, "https://github.com/dotnet/roslyn-analyzers/issues/4040")] - public async Task NoObliviousWhenAnnotatedClassConstraintAsync() - { - var source = $$""" + public Task NoObliviousWhenAnnotatedClassConstraintAsync() + => VerifyCSharpAsync($$""" #nullable enable {{EnabledModifier}} class C where T : class? { } - """; - - var shippedText = @""; - var unshippedText = @"#nullable enable -C.C() -> void -C -"; - - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + """, @"", """ + #nullable enable + C.C() -> void + C + """); [Fact] public async Task NoObliviousWhenAnnotatedClassConstraintMultipleFiles() @@ -124,12 +110,14 @@ public async Task NoObliviousWhenAnnotatedClassConstraintMultipleFiles() """; var shippedText = @"#nullable enable"; - var unshippedText1 = @"#nullable enable -C.C() -> void -"; - var unshippedText2 = @"#nullable enable -C -"; + var unshippedText1 = """ + #nullable enable + C.C() -> void + """; + var unshippedText2 = """ + #nullable enable + C + """; var test = new CSharpCodeFixTest { @@ -149,74 +137,55 @@ public async Task NoObliviousWhenAnnotatedClassConstraintMultipleFiles() } [Fact, WorkItem(4040, "https://github.com/dotnet/roslyn-analyzers/issues/4040")] - public async Task ObliviousWhenObliviousClassConstraintAsync() - { - var source = $$""" + public Task ObliviousWhenObliviousClassConstraintAsync() + => VerifyCSharpAsync($$""" #nullable enable {{EnabledModifier}} class {|{{ObliviousApiId}}:C|} // oblivious #nullable disable where T : class { } - """; - - var shippedText = @""; - var unshippedText = @"#nullable enable -C.C() -> void -~C -"; - - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + """, @"", """ + #nullable enable + C.C() -> void + ~C + """); [Fact, WorkItem(4040, "https://github.com/dotnet/roslyn-analyzers/issues/4040")] - public async Task NoObliviousWhenUnannotatedReferenceTypeConstraintAsync() - { - var source = $$""" + public Task NoObliviousWhenUnannotatedReferenceTypeConstraintAsync() + => VerifyCSharpAsync($$""" #nullable enable {{EnabledModifier}} class D { } {{EnabledModifier}} class C where T : D { } - """; - - var shippedText = @""; - var unshippedText = @"#nullable enable -C.C() -> void -C -D -D.D() -> void -"; - - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + """, @"", """ + #nullable enable + C.C() -> void + C + D + D.D() -> void + """); [Fact, WorkItem(4040, "https://github.com/dotnet/roslyn-analyzers/issues/4040")] - public async Task NoObliviousWhenAnnotatedReferenceTypeConstraintAsync() - { - var source = $$""" + public Task NoObliviousWhenAnnotatedReferenceTypeConstraintAsync() + => VerifyCSharpAsync($$""" #nullable enable {{EnabledModifier}} class D { } {{EnabledModifier}} class C where T : D? { } - """; - - var shippedText = @""; - var unshippedText = @"#nullable enable -C.C() -> void -C -D -D.D() -> void -"; - - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + """, @"", """ + #nullable enable + C.C() -> void + C + D + D.D() -> void + """); [Fact, WorkItem(4040, "https://github.com/dotnet/roslyn-analyzers/issues/4040")] - public async Task ObliviousWhenObliviousReferenceTypeConstraintAsync() - { - var source = $$""" + public Task ObliviousWhenObliviousReferenceTypeConstraintAsync() + => VerifyCSharpAsync($$""" #nullable enable {{EnabledModifier}} class D { } @@ -225,82 +194,63 @@ public async Task ObliviousWhenObliviousReferenceTypeConstraintAsync() where T : D { } - """; - - var shippedText = @""; - var unshippedText = @"#nullable enable -C.C() -> void -~C -D -D.D() -> void -"; - - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + """, @"", """ + #nullable enable + C.C() -> void + ~C + D + D.D() -> void + """); [Fact] - public async Task DoNotAnnotateMemberInUnannotatedUnshippedAPI_NullableAsync() - { - var source = $$""" + public Task DoNotAnnotateMemberInUnannotatedUnshippedAPI_NullableAsync() + => VerifyCSharpAsync($$""" #nullable enable {{EnabledModifier}} class C { {{EnabledModifier}} string? {|{{ShouldAnnotateApiFilesId}}:Field|}; } - """; - - var shippedText = @""; - var unshippedText = @"C -C.C() -> void -C.Field -> string"; - - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + """, @"", """ + C + C.C() -> void + C.Field -> string + """); [Fact] - public async Task DoNotAnnotateMemberInUnannotatedUnshippedAPI_NonNullableAsync() - { - var source = $$""" + public Task DoNotAnnotateMemberInUnannotatedUnshippedAPI_NonNullableAsync() + => VerifyCSharpAsync($$""" #nullable enable {{EnabledModifier}} class C { {{EnabledModifier}} string {|{{ShouldAnnotateApiFilesId}}:Field2|}; } - """; - - var shippedText = @""; - var unshippedText = @"C -C.C() -> void -C.Field2 -> string"; - - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + """, @"", """ + C + C.C() -> void + C.Field2 -> string + """); [Fact] - public async Task DoNotAnnotateMemberInUnannotatedShippedAPIAsync() - { - var source = $$""" + public Task DoNotAnnotateMemberInUnannotatedShippedAPIAsync() + => VerifyCSharpAsync($$""" #nullable enable {{EnabledModifier}} class C { {{EnabledModifier}} string? {|{{ShouldAnnotateApiFilesId}}:Field|}; {{EnabledModifier}} string {|{{ShouldAnnotateApiFilesId}}:Field2|}; } - """; - - var shippedText = @"C -C.C() -> void -C.Field -> string -C.Field2 -> string"; - var unshippedText = @""; - - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + """, """ + C + C.C() -> void + C.Field -> string + C.Field2 -> string + """, @""); [Fact] public async Task AnnotatedMemberInAnnotatedShippedAPIAsync() { - var source = $$""" + var unshippedText = @""; + await VerifyCSharpAdditionalFileFixAsync($$""" #nullable enable {{EnabledModifier}} class C { @@ -308,31 +258,28 @@ public async Task AnnotatedMemberInAnnotatedShippedAPIAsync() {{EnabledModifier}} string? {|{{AnnotateApiId}}:Field|}; {{EnabledModifier}} string {|{{AnnotateApiId}}:Field2|}; } - """; - - var shippedText = @"#nullable enable -C -C.C() -> void -C.OldField -> string? -C.Field -> string -C.Field2 -> string"; - - var unshippedText = @""; - - var fixedShippedText = @"#nullable enable -C -C.C() -> void -C.OldField -> string? -C.Field -> string? -C.Field2 -> string!"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedShippedText, newUnshippedApiText: unshippedText); + """, """ + #nullable enable + C + C.C() -> void + C.OldField -> string? + C.Field -> string + C.Field2 -> string + """, unshippedText, """ + #nullable enable + C + C.C() -> void + C.OldField -> string? + C.Field -> string? + C.Field2 -> string! + """, newUnshippedApiText: unshippedText); } [Fact] public async Task AnnotatedMemberInAnnotatedUnshippedAPI_EnabledViaUnshippedAsync() { - var source = $$""" + var shippedText = @""; + await VerifyCSharpAdditionalFileFixAsync($$""" #nullable enable {{EnabledModifier}} class C { @@ -340,31 +287,30 @@ public async Task AnnotatedMemberInAnnotatedUnshippedAPI_EnabledViaUnshippedAsyn {{EnabledModifier}} string? {|{{AnnotateApiId}}:Field|}; {{EnabledModifier}} string {|{{AnnotateApiId}}:Field2|}; } - """; - - var unshippedText = @"#nullable enable -C -C.C() -> void -C.OldField -> string? -C.Field -> string -C.Field2 -> string"; - - var shippedText = @""; - - var fixedUnshippedText = @"#nullable enable -C -C.C() -> void -C.OldField -> string? -C.Field -> string? -C.Field2 -> string!"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, shippedText, fixedUnshippedText); + """, shippedText, """ + #nullable enable + C + C.C() -> void + C.OldField -> string? + C.Field -> string + C.Field2 -> string + """, shippedText, """ + #nullable enable + C + C.C() -> void + C.OldField -> string? + C.Field -> string? + C.Field2 -> string! + """); } [Fact] public async Task AnnotatedMemberInAnnotatedUnshippedAPI_EnabledViaMultipleUnshippedAsync() { - var source = $$""" + var shippedText = @""; + var test = new CSharpCodeFixTest(); + + test.TestState.Sources.Add($$""" #nullable enable {{EnabledModifier}} class C { @@ -372,35 +318,29 @@ public async Task AnnotatedMemberInAnnotatedUnshippedAPI_EnabledViaMultipleUnshi {{EnabledModifier}} string? {|{{AnnotateApiId}}:Field|}; {{EnabledModifier}} string {|{{AnnotateApiId}}:Field2|}; } - """; - - var unshippedText = @"#nullable enable -C -C.C() -> void -C.OldField -> string? -C.Field -> string -C.Field2 -> string"; - - var shippedText = @""; - - var fixedUnshippedText = @"#nullable enable -C -C.C() -> void -C.OldField -> string? -C.Field -> string? -C.Field2 -> string!"; - - var test = new CSharpCodeFixTest(); - - test.TestState.Sources.Add(source); + """); test.TestState.AdditionalFiles.Add((ShippedFileName, shippedText)); test.TestState.AdditionalFiles.Add((UnshippedFileName, string.Empty)); - test.TestState.AdditionalFiles.Add((UnshippedFileNamePrefix + "test" + DeclarePublicApiAnalyzer.Extension, unshippedText)); + test.TestState.AdditionalFiles.Add((UnshippedFileNamePrefix + "test" + DeclarePublicApiAnalyzer.Extension, """ + #nullable enable + C + C.C() -> void + C.OldField -> string? + C.Field -> string + C.Field2 -> string + """)); test.FixedState.AdditionalFiles.Add((ShippedFileName, shippedText)); test.FixedState.AdditionalFiles.Add((UnshippedFileName, string.Empty)); - test.FixedState.AdditionalFiles.Add((UnshippedFileNamePrefix + "test" + DeclarePublicApiAnalyzer.Extension, fixedUnshippedText)); + test.FixedState.AdditionalFiles.Add((UnshippedFileNamePrefix + "test" + DeclarePublicApiAnalyzer.Extension, """ + #nullable enable + C + C.C() -> void + C.OldField -> string? + C.Field -> string? + C.Field2 -> string! + """)); await test.RunAsync(); } @@ -408,7 +348,8 @@ public async Task AnnotatedMemberInAnnotatedUnshippedAPI_EnabledViaMultipleUnshi [Fact] public async Task AnnotatedMemberInAnnotatedUnshippedAPI_EnabledViaShippedAsync() { - var source = $$""" + var shippedText = @"#nullable enable"; + await VerifyCSharpAdditionalFileFixAsync($$""" #nullable enable {{EnabledModifier}} class C { @@ -416,28 +357,26 @@ public async Task AnnotatedMemberInAnnotatedUnshippedAPI_EnabledViaShippedAsync( {{EnabledModifier}} string? {|{{AnnotateApiId}}:Field|}; {{EnabledModifier}} string {|{{AnnotateApiId}}:Field2|}; } - """; - - var shippedText = @"#nullable enable"; - var unshippedText = @"C -C.C() -> void -C.OldField -> string? -C.Field -> string -C.Field2 -> string"; - - var fixedUnshippedText = @"C -C.C() -> void -C.OldField -> string? -C.Field -> string? -C.Field2 -> string!"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, newShippedApiText: shippedText, fixedUnshippedText); + """, shippedText, """ + C + C.C() -> void + C.OldField -> string? + C.Field -> string + C.Field2 -> string + """, newShippedApiText: shippedText, """ + C + C.C() -> void + C.OldField -> string? + C.Field -> string? + C.Field2 -> string! + """); } [Fact] public async Task AnnotatedMemberInAnnotatedUnshippedAPI_EnabledViaBothAsync() { - var source = $$""" + var shippedText = @"#nullable enable"; + await VerifyCSharpAdditionalFileFixAsync($$""" #nullable enable {{EnabledModifier}} class C { @@ -445,128 +384,130 @@ public async Task AnnotatedMemberInAnnotatedUnshippedAPI_EnabledViaBothAsync() {{EnabledModifier}} string? {|{{AnnotateApiId}}:Field|}; {{EnabledModifier}} string {|{{AnnotateApiId}}:Field2|}; } - """; - - var shippedText = @"#nullable enable"; - var unshippedText = @"#nullable enable -C -C.C() -> void -C.OldField -> string? -C.Field -> string -C.Field2 -> string"; - - var fixedUnshippedText = @"#nullable enable -C -C.C() -> void -C.OldField -> string? -C.Field -> string? -C.Field2 -> string!"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, newShippedApiText: shippedText, fixedUnshippedText); + """, shippedText, """ + #nullable enable + C + C.C() -> void + C.OldField -> string? + C.Field -> string + C.Field2 -> string + """, newShippedApiText: shippedText, """ + #nullable enable + C + C.C() -> void + C.OldField -> string? + C.Field -> string? + C.Field2 -> string! + """); } [Fact] public async Task TestAddAndRemoveMembers_CSharp_Fix_WithAddedNullability_WithoutObliviousAsync() { - var source = $$""" + var shippedText = $@"#nullable enable"; + await VerifyCSharpAdditionalFileFixAsync($$""" #nullable enable {{EnabledModifier}} class C { {{EnabledModifier}} string? {|{{AnnotateApiId}}:ChangedField|}; } - """; - var shippedText = $@"#nullable enable"; - var unshippedText = @"C -C.C() -> void -C.ChangedField -> string"; - var fixedUnshippedText = @"C -C.C() -> void -C.ChangedField -> string?"; - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, newShippedApiText: shippedText, fixedUnshippedText); + """, shippedText, """ + C + C.C() -> void + C.ChangedField -> string + """, newShippedApiText: shippedText, """ + C + C.C() -> void + C.ChangedField -> string? + """); } [Fact] public async Task LegacyAPIShouldBeAnnotatedWithObliviousMarkerAsync() { - var source = $$""" + var shippedText = $@"#nullable enable"; + await VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifier}} class C { {{EnabledModifier}} string {|{{AnnotateApiId}}:{|{{ObliviousApiId}}:Field|}|}; // oblivious } - """; - var shippedText = $@"#nullable enable"; - var unshippedText = @"C -C.C() -> void -C.Field -> string"; - var fixedUnshippedText = @"C -C.C() -> void -~C.Field -> string"; - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, newShippedApiText: shippedText, fixedUnshippedText); + """, shippedText, """ + C + C.C() -> void + C.Field -> string + """, newShippedApiText: shippedText, """ + C + C.C() -> void + ~C.Field -> string + """); } [Fact] public async Task LegacyAPIShouldBeAnnotatedWithObliviousMarker_ShippedFileAsync() { - var source = $$""" + var unshippedText = @""; + await VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifier}} class C { {{EnabledModifier}} string {|{{AnnotateApiId}}:{|{{ObliviousApiId}}:Field|}|}; // oblivious } - """; - var shippedText = $@"#nullable enable -C -C.C() -> void -C.Field -> string"; - var unshippedText = @""; - var fixedShippedText = $@"#nullable enable -C -C.C() -> void -~C.Field -> string"; - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedShippedText, newUnshippedApiText: unshippedText); + """, $""" + #nullable enable + C + C.C() -> void + C.Field -> string + """, unshippedText, $""" + #nullable enable + C + C.C() -> void + ~C.Field -> string + """, newUnshippedApiText: unshippedText); } [Fact] public async Task LegacyAPIWithObliviousMarkerGetsAnnotatedAsNullableAsync() { - var source = $$""" + var unshippedText = @""; + await VerifyCSharpAdditionalFileFixAsync($$""" #nullable enable {{EnabledModifier}} class C { {{EnabledModifier}} string? {|{{AnnotateApiId}}:Field|}; } - """; - var shippedText = $@"#nullable enable -C -C.C() -> void -~C.Field -> string"; - var unshippedText = @""; - var fixedShippedText = $@"#nullable enable -C -C.C() -> void -C.Field -> string?"; - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedShippedText, newUnshippedApiText: unshippedText); + """, $""" + #nullable enable + C + C.C() -> void + ~C.Field -> string + """, unshippedText, $""" + #nullable enable + C + C.C() -> void + C.Field -> string? + """, newUnshippedApiText: unshippedText); } [Fact] public async Task LegacyAPIWithObliviousMarkerGetsAnnotatedAsNotNullableAsync() { - var source = $$""" + var unshippedText = @""; + await VerifyCSharpAdditionalFileFixAsync($$""" #nullable enable {{EnabledModifier}} class C { {{EnabledModifier}} string {|{{AnnotateApiId}}:Field|}; } - """; - var shippedText = $@"#nullable enable -C -C.C() -> void -~C.Field -> string"; - var unshippedText = @""; - var fixedShippedText = $@"#nullable enable -C -C.C() -> void -C.Field -> string!"; - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedShippedText, newUnshippedApiText: unshippedText); + """, $""" + #nullable enable + C + C.C() -> void + ~C.Field -> string + """, unshippedText, $""" + #nullable enable + C + C.C() -> void + C.Field -> string! + """, newUnshippedApiText: unshippedText); } #endregion diff --git a/src/RoslynAnalyzers/PublicApiAnalyzers/UnitTests/DeclarePublicAPIAnalyzerTestsBase.cs b/src/RoslynAnalyzers/PublicApiAnalyzers/UnitTests/DeclarePublicAPIAnalyzerTestsBase.cs index d90694b131f11..3e1174ef8e70c 100644 --- a/src/RoslynAnalyzers/PublicApiAnalyzers/UnitTests/DeclarePublicAPIAnalyzerTestsBase.cs +++ b/src/RoslynAnalyzers/PublicApiAnalyzers/UnitTests/DeclarePublicAPIAnalyzerTestsBase.cs @@ -205,20 +205,14 @@ private async Task VerifyCSharpAsync(string source, string shippedApiText, strin await test.RunAsync(); } - private async Task VerifyCSharpAdditionalFileFixAsync(string source, string? shippedApiText, string? oldUnshippedApiText, string newUnshippedApiText) - { - await VerifyAdditionalFileFixAsync(LanguageNames.CSharp, source, shippedApiText, oldUnshippedApiText, newUnshippedApiText); - } + private Task VerifyCSharpAdditionalFileFixAsync(string source, string? shippedApiText, string? oldUnshippedApiText, string newUnshippedApiText) + => VerifyAdditionalFileFixAsync(LanguageNames.CSharp, source, shippedApiText, oldUnshippedApiText, newUnshippedApiText); - private async Task VerifyNet50CSharpAdditionalFileFixAsync(string source, string? shippedApiText, string? oldUnshippedApiText, string newUnshippedApiText) - { - await VerifyAdditionalFileFixAsync(LanguageNames.CSharp, source, shippedApiText, oldUnshippedApiText, newUnshippedApiText, ReferenceAssemblies.Net.Net50); - } + private Task VerifyNet50CSharpAdditionalFileFixAsync(string source, string? shippedApiText, string? oldUnshippedApiText, string newUnshippedApiText) + => VerifyAdditionalFileFixAsync(LanguageNames.CSharp, source, shippedApiText, oldUnshippedApiText, newUnshippedApiText, ReferenceAssemblies.Net.Net50); - private async Task VerifyNet80CSharpAdditionalFileFixAsync(string source, string? shippedApiText, string? oldUnshippedApiText, string newUnshippedApiText) - { - await VerifyAdditionalFileFixAsync(LanguageNames.CSharp, source, shippedApiText, oldUnshippedApiText, newUnshippedApiText, ReferenceAssemblies.Net.Net80); - } + private Task VerifyNet80CSharpAdditionalFileFixAsync(string source, string? shippedApiText, string? oldUnshippedApiText, string newUnshippedApiText) + => VerifyAdditionalFileFixAsync(LanguageNames.CSharp, source, shippedApiText, oldUnshippedApiText, newUnshippedApiText, ReferenceAssemblies.Net.Net80); private async Task VerifyAdditionalFileFixAsync(string language, string source, string? shippedApiText, string? oldUnshippedApiText, string newUnshippedApiText, ReferenceAssemblies? referenceAssemblies = null) @@ -252,39 +246,32 @@ private async Task VerifyAdditionalFileFixAsync(string language, string source, [WorkItem(2622, "https://github.com/dotnet/roslyn-analyzers/issues/2622")] public async Task AnalyzerFileMissing_ShippedAsync() { - var source = $$""" + string? shippedText = null; + var expected = new DiagnosticResult(ApiFileMissing) + .WithArguments(ShippedFileName); + await VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { private C() { } } - """; - - string? shippedText = null; - string? unshippedText = @""; - - var expected = new DiagnosticResult(ApiFileMissing) - .WithArguments(ShippedFileName); - await VerifyCSharpAsync(source, shippedText, unshippedText, expected); + """, shippedText, @"", expected); } [Fact] [WorkItem(2622, "https://github.com/dotnet/roslyn-analyzers/issues/2622")] public async Task AnalyzerFileMissing_UnshippedAsync() { - var source = $$""" - {{EnabledModifierCSharp}} class C - { - private C() { } - } - """; - - string? shippedText = @""; string? unshippedText = null; var expected = new DiagnosticResult(ApiFileMissing) .WithArguments(UnshippedFileName); - await VerifyCSharpAsync(source, shippedText, unshippedText, expected); + await VerifyCSharpAsync($$""" + {{EnabledModifierCSharp}} class C + { + private C() { } + } + """, @"", unshippedText, expected); } [Theory] @@ -294,95 +281,66 @@ private C() { } [WorkItem(2622, "https://github.com/dotnet/roslyn-analyzers/issues/2622")] public async Task AnalyzerFileMissing_BothAsync(string editorconfigText) { - var source = $$""" - - {{EnabledModifierCSharp}} class C - { - private C() { } - } - """; - string? shippedText = null; string? unshippedText = null; var expectedDiagnostics = Array.Empty(); if (!editorconfigText.EndsWith("true", StringComparison.OrdinalIgnoreCase)) { - expectedDiagnostics = new[] { GetCSharpResultAt(2, 8 + EnabledModifierCSharp.Length, DeclareNewApiRule, "C") }; + expectedDiagnostics = [GetCSharpResultAt(2, 8 + EnabledModifierCSharp.Length, DeclareNewApiRule, "C")]; } - await VerifyCSharpAsync(source, shippedText, unshippedText, $"[*]\r\n{editorconfigText}", expectedDiagnostics); + await VerifyCSharpAsync($$""" + + {{EnabledModifierCSharp}} class C + { + private C() { } + } + """, shippedText, unshippedText, $"[*]\r\n{editorconfigText}", expectedDiagnostics); } [Fact] public async Task AnalyzerFilePresent_MissingNonEnabledText() { - var source = $$""" + var expectedDiagnostics = new[] { GetCSharpResultAt(2, 8 + EnabledModifierCSharp.Length, DeclareNewApiRule, "C") }; + + await VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { private C() { } } - """; - - string? shippedText = ""; - string? unshippedText = ""; - - var expectedDiagnostics = new[] { GetCSharpResultAt(2, 8 + EnabledModifierCSharp.Length, DeclareNewApiRule, "C") }; - - await VerifyCSharpAsync(source, shippedText, unshippedText, $"[*]\r\ndotnet_public_api_analyzer.require_api_files = true", expectedDiagnostics); + """, "", "", $"[*]\r\ndotnet_public_api_analyzer.require_api_files = true", expectedDiagnostics); } [Fact] - public async Task EmptyPublicAPIFilesAsync() - { - var source = @""; - - var shippedText = @""; - var unshippedText = @""; - - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + public Task EmptyPublicAPIFilesAsync() + => VerifyCSharpAsync(@"", @"", @""); [Fact] - public async Task SimpleMissingTypeAsync() - { - var source = $$""" + public Task SimpleMissingTypeAsync() + => VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { private C() { } } - """; - - var shippedText = @""; - var unshippedText = @""; - - await VerifyCSharpAsync(source, shippedText, unshippedText, GetCSharpResultAt(2, 8 + EnabledModifierCSharp.Length, DeclareNewApiRule, "C")); - } + """, @"", @"", GetCSharpResultAt(2, 8 + EnabledModifierCSharp.Length, DeclareNewApiRule, "C")); [Fact, WorkItem(2690, "https://github.com/dotnet/wpf/issues/2690")] - public async Task XamlGeneratedNamespaceWorkaroundAsync() - { - var source = $$""" + public Task XamlGeneratedNamespaceWorkaroundAsync() + => VerifyCSharpAsync($$""" namespace XamlGeneratedNamespace { {{EnabledModifierCSharp}} sealed class GeneratedInternalTypeHelper { } } - """; - - var shippedText = @""; - var unshippedText = @""; - - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + """, @"", @""); [Fact] - public async Task SimpleMissingMember_CSharpAsync() - { - var source = $$""" + public Task SimpleMissingMember_CSharpAsync() + => VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { @@ -391,12 +349,7 @@ public async Task SimpleMissingMember_CSharpAsync() {{EnabledModifierCSharp}} void Method() { } {{EnabledModifierCSharp}} int ArrowExpressionProperty => 0; } - """; - - var shippedText = @""; - var unshippedText = @""; - - await VerifyCSharpAsync(source, shippedText, unshippedText, + """, @"", @"", // Test0.cs(2,14): error RS0016: Symbol 'C' is not part of the declared API. GetCSharpResultAt(2, 8 + EnabledModifierCSharp.Length, DeclareNewApiRule, "C"), // Test0.cs(2,14): warning RS0016: Symbol 'C.C() -> void' is not part of the declared API. @@ -411,16 +364,14 @@ await VerifyCSharpAsync(source, shippedText, unshippedText, GetCSharpResultAt(6, 11 + EnabledModifierCSharp.Length, DeclareNewApiRule, "C.Method() -> void"), // Test0.cs(7,43): error RS0016: Symbol 'C.ArrowExpressionProperty.get -> int' is not part of the declared API. GetCSharpResultAt(7, 37 + EnabledModifierCSharp.Length, DeclareNewApiRule, "C.ArrowExpressionProperty.get -> int")); - } [Theory] [InlineData("string ", "string!")] [InlineData("string?", "string?")] [InlineData("int ", "int")] [InlineData("int? ", "int?")] - public async Task SimpleMissingMember_CSharp_NullableTypes(string csharp, string message) - { - var source = $$""" + public Task SimpleMissingMember_CSharp_NullableTypes(string csharp, string message) + => VerifyCSharpAsync($$""" #nullable enable {{EnabledModifierCSharp}} class C { @@ -429,12 +380,7 @@ public async Task SimpleMissingMember_CSharp_NullableTypes(string csharp, string {{EnabledModifierCSharp}} void Method({{csharp}} p) { } {{EnabledModifierCSharp}} {{csharp}} ArrowExpressionProperty => default; } - """; - - var shippedText = "#nullable enable"; - var unshippedText = "#nullable enable"; - - await VerifyCSharpAsync(source, shippedText, unshippedText, + """, "#nullable enable", "#nullable enable", // Test0.cs(2,14): error RS0016: Symbol 'C' is not part of the declared API. GetCSharpResultAt(2, 8 + EnabledModifierCSharp.Length, DeclareNewApiRule, "C"), // Test0.cs(2,14): warning RS0016: Symbol 'C.C() -> void' is not part of the declared API. @@ -449,12 +395,10 @@ await VerifyCSharpAsync(source, shippedText, unshippedText, GetCSharpResultAt(6, 11 + EnabledModifierCSharp.Length, DeclareNewApiRule, $"C.Method({message} p) -> void"), // Test0.cs(7,43): error RS0016: Symbol 'C.ArrowExpressionProperty.get -> int' is not part of the declared API. GetCSharpResultAt(7, 41 + EnabledModifierCSharp.Length, DeclareNewApiRule, $"C.ArrowExpressionProperty.get -> {message}")); - } [Fact, WorkItem(821, "https://github.com/dotnet/roslyn-analyzers/issues/821")] - public async Task SimpleMissingMember_BasicAsync() - { - var source = $""" + public Task SimpleMissingMember_BasicAsync() + => VerifyBasicAsync($""" Imports System @@ -477,12 +421,7 @@ End Sub {EnabledModifierVB} ReadOnly Property ReadOnlyAutoProperty As Integer = 0 {EnabledModifierVB} Property NormalAutoProperty As Integer = 0 End Class - """; - - var shippedText = @""; - var unshippedText = @""; - - await VerifyBasicAsync(source, shippedText, unshippedText, + """, @"", @"", // Test0.vb(4,14): warning RS0016: Symbol 'C' is not part of the declared API. GetBasicResultAt(4, 14, DeclareNewApiRule, "C"), // Test0.cs(2,14): warning RS0016: Symbol 'C.New() -> Void' is not part of the declared API. @@ -501,12 +440,10 @@ await VerifyBasicAsync(source, shippedText, unshippedText, GetBasicResultAt(21, 21, DeclareNewApiRule, "C.NormalAutoProperty() -> Integer"), // Test0.vb(21,21): warning RS0016: Symbol 'C.NormalAutoProperty(AutoPropertyValue As Integer) -> Void' is not part of the declared API. GetBasicResultAt(21, 21, DeclareNewApiRule, "C.NormalAutoProperty(AutoPropertyValue As Integer) -> Void")); - } [Fact(), WorkItem(821, "https://github.com/dotnet/roslyn-analyzers/issues/821")] - public async Task SimpleMissingMember_Basic1Async() - { - var source = $""" + public Task SimpleMissingMember_Basic1Async() + => VerifyBasicAsync($""" Imports System {EnabledModifierVB} Class C @@ -534,125 +471,98 @@ End Property {EnabledModifierVB} Property Property1 As Integer End Class - """; + """, """ - var shippedText = @" -C -C.New() -> Void -C.Property() -> Integer -C.Property(AutoPropertyValue As Integer) -> Void -C.Property1() -> Integer -C.Property1(AutoPropertyValue As Integer) -> Void -C.ReadOnlyProperty0() -> Integer -C.ReadOnlyProperty1() -> Integer -C.ReadOnlyProperty2() -> Integer -C.WriteOnlyProperty0(Value As Integer) -> Void -"; - var unshippedText = @""; - await VerifyBasicAsync(source, shippedText, unshippedText); - } + C + C.New() -> Void + C.Property() -> Integer + C.Property(AutoPropertyValue As Integer) -> Void + C.Property1() -> Integer + C.Property1(AutoPropertyValue As Integer) -> Void + C.ReadOnlyProperty0() -> Integer + C.ReadOnlyProperty1() -> Integer + C.ReadOnlyProperty2() -> Integer + C.WriteOnlyProperty0(Value As Integer) -> Void + + """, @""); [Fact, WorkItem(806, "https://github.com/dotnet/roslyn-analyzers/issues/806")] - public async Task ShippedTextWithImplicitConstructorAsync() - { - var source = $$""" + public Task ShippedTextWithImplicitConstructorAsync() + => VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { private C() { } } - """; - - var shippedText = @" -C -C -> void()"; - var unshippedText = @""; + """, """ - await VerifyCSharpAsync(source, shippedText, unshippedText, + C + C -> void() + """, @"", // PublicAPI.Shipped.txt(3,1): warning RS0017: Symbol 'C -> void()' is part of the declared API, but is either not public or could not be found GetAdditionalFileResultAt(3, 1, ShippedFileName, RemoveDeletedApiRule, "C -> void()")); - } [Fact, WorkItem(806, "https://github.com/dotnet/roslyn-analyzers/issues/806")] - public async Task ShippedTextForImplicitConstructorAsync() - { - var source = $$""" + public Task ShippedTextForImplicitConstructorAsync() + => VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { } - """; - - var shippedText = @" -C -C.C() -> void"; - var unshippedText = @""; + """, """ - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + C + C.C() -> void + """, @""); [Fact, WorkItem(806, "https://github.com/dotnet/roslyn-analyzers/issues/806")] - public async Task UnshippedTextForImplicitConstructorAsync() - { - var source = $$""" + public Task UnshippedTextForImplicitConstructorAsync() + => VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { } - """; + """, """ - var shippedText = @" -C"; - var unshippedText = @" -C.C() -> void"; + C + """, """ - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + C.C() -> void + """); [Fact, WorkItem(806, "https://github.com/dotnet/roslyn-analyzers/issues/806")] - public async Task ShippedTextWithMissingImplicitConstructorAsync() - { - var source = $$""" + public Task ShippedTextWithMissingImplicitConstructorAsync() + => VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { } - """; + """, """ - var shippedText = @" -C"; - var unshippedText = @""; - - await VerifyCSharpAsync(source, shippedText, unshippedText, + C + """, @"", // Test0.cs(2,14): warning RS0016: Symbol 'C.C() -> void' is not part of the declared API. GetCSharpResultAt(2, 8 + EnabledModifierCSharp.Length, DeclareNewApiRule, "C.C() -> void")); - } [Fact, WorkItem(806, "https://github.com/dotnet/roslyn-analyzers/issues/806")] - public async Task ShippedTextWithImplicitConstructorAndBreakingCodeChangeAsync() - { - var source = $$""" + public Task ShippedTextWithImplicitConstructorAndBreakingCodeChangeAsync() + => VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { private C() { } } - """; - - var shippedText = @" -C -C.C() -> void"; - var unshippedText = @""; + """, """ - await VerifyCSharpAsync(source, shippedText, unshippedText, + C + C.C() -> void + """, @"", // PublicAPI.Shipped.txt(3,1): warning RS0017: Symbol 'C.C() -> void' is part of the declared API, but is either not public or could not be found GetAdditionalFileResultAt(3, 1, ShippedFileName, RemoveDeletedApiRule, "C.C() -> void")); - } [Fact] - public async Task SimpleMemberAsync() - { - var source = $$""" + public Task SimpleMemberAsync() + => VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { @@ -661,25 +571,20 @@ public async Task SimpleMemberAsync() {{EnabledModifierCSharp}} void Method() { } } - """; + """, """ - var shippedText = @" -C -C.C() -> void -C.Field -> int -C.Property.get -> int -C.Property.set -> void -C.Method() -> void -"; - var unshippedText = @""; + C + C.C() -> void + C.Field -> int + C.Property.get -> int + C.Property.set -> void + C.Method() -> void - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + """, @""); [Fact] - public async Task SplitBetweenShippedUnshippedAsync() - { - var source = $$""" + public Task SplitBetweenShippedUnshippedAsync() + => VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { @@ -687,26 +592,23 @@ public async Task SplitBetweenShippedUnshippedAsync() {{EnabledModifierCSharp}} int Property { get; set; } {{EnabledModifierCSharp}} void Method() { } } - """; + """, """ - var shippedText = @" -C -C.C() -> void -C.Field -> int -C.Property.get -> int -C.Property.set -> void -"; - var unshippedText = @" -C.Method() -> void -"; - - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + C + C.C() -> void + C.Field -> int + C.Property.get -> int + C.Property.set -> void + + """, """ + + C.Method() -> void + + """); [Fact] - public async Task EnumSplitBetweenFilesAsync() - { - var source = $$""" + public Task EnumSplitBetweenFilesAsync() + => VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} enum E { @@ -715,48 +617,41 @@ public async Task EnumSplitBetweenFilesAsync() V3 = 3, } - """; + """, """ - var shippedText = @" -E -E.V1 = 1 -> E -E.V2 = 2 -> E -"; + E + E.V1 = 1 -> E + E.V2 = 2 -> E - var unshippedText = @" -E.V3 = 3 -> E -"; + """, """ - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + E.V3 = 3 -> E + + """); [Fact] - public async Task SimpleRemovedMemberAsync() - { - var source = $$""" + public Task SimpleRemovedMemberAsync() + => VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { public int Field; public int Property { get; set; } } - """; + """, """ + + C + C.C() -> void + C.Field -> int + C.Property.get -> int + C.Property.set -> void + C.Method() -> void - var shippedText = @" -C -C.C() -> void -C.Field -> int -C.Property.get -> int -C.Property.set -> void -C.Method() -> void -"; + """, $""" - string unshippedText = $@" -{DeclarePublicApiAnalyzer.RemovedApiPrefix}C.Method() -> void -"; + {DeclarePublicApiAnalyzer.RemovedApiPrefix}C.Method() -> void - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + """); [Theory] [CombinatorialData] @@ -773,23 +668,29 @@ public async Task RemovedPrefixForNonRemovedApiAsync(bool includeInShipped) } """; - var shippedText = @" -C -C.C() -> void -C.Field -> int -C.Property.get -> int -C.Property.set -> void -"; + var shippedText = """ + + C + C.C() -> void + C.Field -> int + C.Property.get -> int + C.Property.set -> void + + """; if (includeInShipped) { - shippedText += @"C.Method() -> void -"; + shippedText += """ + C.Method() -> void + + """; } - string unshippedText = $@" -{DeclarePublicApiAnalyzer.RemovedApiPrefix}C.Method() -> void -"; + string unshippedText = $""" + + {DeclarePublicApiAnalyzer.RemovedApiPrefix}C.Method() -> void + + """; var diagnostics = new[] { // PublicAPI.Unshipped.txt(2,1): warning RS0050: Symbol 'C.Method() -> void' is marked as removed but it isn't deleted in source code @@ -811,52 +712,30 @@ public async Task RemovedPrefixForNonRemovedApiAsync(bool includeInShipped) [Fact] public async Task ApiFileShippedWithRemovedAsync() { - var source = $$""" + var expected = new DiagnosticResult(ApiFilesInvalid) + .WithArguments(DeclarePublicApiAnalyzer.InvalidReasonShippedCantHaveRemoved); + await VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { {{EnabledModifierCSharp}} int Field; {{EnabledModifierCSharp}} int Property { get; set; } } - """; - - string shippedText = $@" -C -C.Field -> int -C.Property.get -> int -C.Property.set -> void -{DeclarePublicApiAnalyzer.RemovedApiPrefix}C.Method() -> void -"; + """, $""" - string unshippedText = $@""; + C + C.Field -> int + C.Property.get -> int + C.Property.set -> void + {DeclarePublicApiAnalyzer.RemovedApiPrefix}C.Method() -> void - var expected = new DiagnosticResult(ApiFilesInvalid) - .WithArguments(DeclarePublicApiAnalyzer.InvalidReasonShippedCantHaveRemoved); - await VerifyCSharpAsync(source, shippedText, unshippedText, expected); + """, $@"", expected); } [Fact] [WorkItem(312, "https://github.com/dotnet/roslyn-analyzers/issues/312")] public async Task DuplicateSymbolInSameAPIFileAsync() { - var source = $$""" - - {{EnabledModifierCSharp}} class C - { - {{EnabledModifierCSharp}} int Field; - {{EnabledModifierCSharp}} int Property { get; set; } - } - """; - - var shippedText = @" -C -C.Field -> int -C.Property.get -> int -C.Property.set -> void -C.Property.get -> int -"; - - var unshippedText = @""; #pragma warning disable RS0030 // Do not use banned APIs #pragma warning disable RS0030 // Do not use banned APIs @@ -866,33 +745,28 @@ public async Task DuplicateSymbolInSameAPIFileAsync() .WithLocation(ShippedFileName, 4, 1) #pragma warning restore RS0030 // Do not use banned APIs .WithArguments("C.Property.get -> int"); - await VerifyCSharpAsync(source, shippedText, unshippedText, expected); - } - - [Fact] - [WorkItem(312, "https://github.com/dotnet/roslyn-analyzers/issues/312")] - public async Task DuplicateSymbolInDifferentAPIFilesAsync() - { - var source = $$""" + await VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { {{EnabledModifierCSharp}} int Field; {{EnabledModifierCSharp}} int Property { get; set; } } + """, """ - """; + C + C.Field -> int + C.Property.get -> int + C.Property.set -> void + C.Property.get -> int - var shippedText = @" -C -C.C() -> void -C.Field -> int -C.Property.get -> int -C.Property.set -> void -"; + """, @"", expected); + } - var unshippedText = @" -C.Property.get -> int"; + [Fact] + [WorkItem(312, "https://github.com/dotnet/roslyn-analyzers/issues/312")] + public async Task DuplicateSymbolInDifferentAPIFilesAsync() + { #pragma warning disable RS0030 // Do not use banned APIs #pragma warning disable RS0030 // Do not use banned APIs @@ -902,132 +776,121 @@ public async Task DuplicateSymbolInDifferentAPIFilesAsync() .WithLocation(ShippedFileName, 5, 1) #pragma warning restore RS0030 // Do not use banned APIs .WithArguments("C.Property.get -> int"); - await VerifyCSharpAsync(source, shippedText, unshippedText, expected); - } - - [Fact] - [WorkItem(4584, "https://github.com/dotnet/roslyn-analyzers/issues/4584")] - public async Task DuplicateObliviousSymbolsInSameApiFileAsync() - { - var source = $$""" + await VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { {{EnabledModifierCSharp}} int Field; {{EnabledModifierCSharp}} int Property { get; set; } } - """; - var shippedText = $$""" - #nullable enable + """, """ + C C.C() -> void C.Field -> int + C.Property.get -> int C.Property.set -> void - ~C.Property.get -> int - {|{{DuplicatedSymbolInApiFileId}}:~C.Property.get -> int|} - """; - var unshippedText = @""; + """, """ - await VerifyCSharpAsync(source, shippedText, unshippedText); + C.Property.get -> int + """, expected); } [Fact] [WorkItem(4584, "https://github.com/dotnet/roslyn-analyzers/issues/4584")] - public async Task DuplicateSymbolUsingObliviousInSameApiFilesAsync() - { - var source = $$""" + public Task DuplicateObliviousSymbolsInSameApiFileAsync() + => VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { {{EnabledModifierCSharp}} int Field; {{EnabledModifierCSharp}} int Property { get; set; } } - """; - - var shippedText = $$""" + """, $$""" #nullable enable C C.C() -> void C.Field -> int - C.Property.get -> int C.Property.set -> void + ~C.Property.get -> int {|{{DuplicatedSymbolInApiFileId}}:~C.Property.get -> int|} - - """; - - var unshippedText = @""; - - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + """, @""); [Fact] [WorkItem(4584, "https://github.com/dotnet/roslyn-analyzers/issues/4584")] - public async Task DuplicateSymbolUsingObliviousInDifferentApiFilesAsync() - { - var source = $$""" + public Task DuplicateSymbolUsingObliviousInSameApiFilesAsync() + => VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { {{EnabledModifierCSharp}} int Field; {{EnabledModifierCSharp}} int Property { get; set; } } - """; - - var shippedText = @"#nullable enable -C -C.C() -> void -C.Field -> int -~C.Property.get -> int -C.Property.set -> void -"; - - var unshippedText = $$""" + """, $$""" #nullable enable - {|{{DuplicatedSymbolInApiFileId}}:C.Property.get -> int|} - """; + C + C.C() -> void + C.Field -> int + C.Property.get -> int + C.Property.set -> void + {|{{DuplicatedSymbolInApiFileId}}:~C.Property.get -> int|} - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + """, @""); [Fact] [WorkItem(4584, "https://github.com/dotnet/roslyn-analyzers/issues/4584")] - public async Task MultipleDuplicateSymbolsUsingObliviousInDifferentApiFilesAsync() - { - var source = $$""" + public Task DuplicateSymbolUsingObliviousInDifferentApiFilesAsync() + => VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { {{EnabledModifierCSharp}} int Field; {{EnabledModifierCSharp}} int Property { get; set; } } + """, """ + #nullable enable + C + C.C() -> void + C.Field -> int + ~C.Property.get -> int + C.Property.set -> void - """; + """, $$""" + #nullable enable + {|{{DuplicatedSymbolInApiFileId}}:C.Property.get -> int|} + """); - var shippedText = @"#nullable enable -C -C.C() -> void -C.Field -> int -C.Property.get -> int -C.Property.set -> void -"; + [Fact] + [WorkItem(4584, "https://github.com/dotnet/roslyn-analyzers/issues/4584")] + public Task MultipleDuplicateSymbolsUsingObliviousInDifferentApiFilesAsync() + => VerifyCSharpAsync($$""" - var unshippedText = $$""" + {{EnabledModifierCSharp}} class C + { + {{EnabledModifierCSharp}} int Field; + {{EnabledModifierCSharp}} int Property { get; set; } + } + + """, """ + #nullable enable + C + C.C() -> void + C.Field -> int + C.Property.get -> int + C.Property.set -> void + + """, $$""" #nullable enable {|{{DuplicatedSymbolInApiFileId}}:~C.Property.get -> int|} {|{{DuplicatedSymbolInApiFileId}}:C.Property.get -> int|} {|{{DuplicatedSymbolInApiFileId}}:~C.Property.set -> void|} - """; - - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + """); [Fact, WorkItem(773, "https://github.com/dotnet/roslyn-analyzers/issues/773")] - public async Task ApiFileShippedWithNonExistentMembersAsync() - { - // Type C has no public member "Method", but the shipped API has an entry for it. - var source = $$""" + public Task ApiFileShippedWithNonExistentMembersAsync() + => VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { @@ -1036,28 +899,29 @@ public async Task ApiFileShippedWithNonExistentMembersAsync() private void Method() { } } - """; + """, $""" - string shippedText = $@" -C -C.C() -> void -C.Field -> int -C.Property.get -> int -C.Property.set -> void -C.Method() -> void -"; - string unshippedText = $@""; - - await VerifyCSharpAsync(source, shippedText, unshippedText, + C + C.C() -> void + C.Field -> int + C.Property.get -> int + C.Property.set -> void + C.Method() -> void + + """, $@"", // PublicAPI.Shipped.txt(7,1): warning RS0017: Symbol 'C.Method() -> void' is part of the declared API, but is either not public or could not be found GetAdditionalFileResultAt(7, 1, ShippedFileName, RemoveDeletedApiRule, "C.Method() -> void")); - } [Fact, WorkItem(773, "https://github.com/dotnet/roslyn-analyzers/issues/773")] public async Task ApiFileShippedWithNonExistentMembers_TestFullPathAsync() { // Type C has no public member "Method", but the shipped API has an entry for it. - var source = $$""" + + var tempPath = Path.GetTempPath(); + var shippedFilePath = Path.Combine(tempPath, ShippedFileName); + var unshippedFilePath = Path.Combine(tempPath, UnshippedFileName); + + await VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { @@ -1065,23 +929,16 @@ public async Task ApiFileShippedWithNonExistentMembers_TestFullPathAsync() {{EnabledModifierCSharp}} int Property { get; set; } private void Method() { } } - """; + """, $""" - var tempPath = Path.GetTempPath(); - string shippedText = $@" -C -C.C() -> void -C.Field -> int -C.Property.get -> int -C.Property.set -> void -C.Method() -> void -"; - var shippedFilePath = Path.Combine(tempPath, ShippedFileName); - - string unshippedText = $@""; - var unshippedFilePath = Path.Combine(tempPath, UnshippedFileName); + C + C.C() -> void + C.Field -> int + C.Property.get -> int + C.Property.set -> void + C.Method() -> void - await VerifyCSharpAsync(source, shippedText, unshippedText, shippedFilePath, unshippedFilePath, + """, $@"", shippedFilePath, unshippedFilePath, // <%TEMP_PATH%>\PublicAPI.Shipped.txt(7,1): warning RS0017: Symbol 'C.Method() -> void' is part of the declared API, but is either not public or could not be found GetAdditionalFileResultAt(7, 1, shippedFilePath, RemoveDeletedApiRule, "C.Method() -> void")); } @@ -1094,27 +951,27 @@ public async Task TypeForwardsAreProcessed1Async() return; } - var source = @" -[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.StringComparison))] -"; - #if NETCOREAPP var containingAssembly = "System.Runtime"; + #else - var containingAssembly = "mscorlib"; #endif - string shippedText = $@" -System.StringComparison (forwarded, contained in {containingAssembly}) -System.StringComparison.CurrentCulture = 0 -> System.StringComparison (forwarded, contained in {containingAssembly}) -System.StringComparison.CurrentCultureIgnoreCase = 1 -> System.StringComparison (forwarded, contained in {containingAssembly}) -System.StringComparison.InvariantCulture = 2 -> System.StringComparison (forwarded, contained in {containingAssembly}) -System.StringComparison.InvariantCultureIgnoreCase = 3 -> System.StringComparison (forwarded, contained in {containingAssembly}) -System.StringComparison.Ordinal = 4 -> System.StringComparison (forwarded, contained in {containingAssembly}) -System.StringComparison.OrdinalIgnoreCase = 5 -> System.StringComparison (forwarded, contained in {containingAssembly}) -"; - string unshippedText = $@""; - - await VerifyCSharpAsync(source, shippedText, unshippedText); + + await VerifyCSharpAsync(""" + + [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.StringComparison))] + + """, $""" + + System.StringComparison (forwarded, contained in {containingAssembly}) + System.StringComparison.CurrentCulture = 0 -> System.StringComparison (forwarded, contained in {containingAssembly}) + System.StringComparison.CurrentCultureIgnoreCase = 1 -> System.StringComparison (forwarded, contained in {containingAssembly}) + System.StringComparison.InvariantCulture = 2 -> System.StringComparison (forwarded, contained in {containingAssembly}) + System.StringComparison.InvariantCultureIgnoreCase = 3 -> System.StringComparison (forwarded, contained in {containingAssembly}) + System.StringComparison.Ordinal = 4 -> System.StringComparison (forwarded, contained in {containingAssembly}) + System.StringComparison.OrdinalIgnoreCase = 5 -> System.StringComparison (forwarded, contained in {containingAssembly}) + + """, $@""); } [Fact] @@ -1125,10 +982,6 @@ public async Task TypeForwardsAreProcessed2Async() return; } - var source = @" -[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.StringComparer))] -"; - #if NETCOREAPP var containingAssembly = "System.Runtime.Extensions"; const string NonNullSuffix = "!"; @@ -1138,36 +991,43 @@ public async Task TypeForwardsAreProcessed2Async() const string NonNullSuffix = ""; const string NullableSuffix = ""; #endif - string shippedText = $@" -System.StringComparer (forwarded, contained in {containingAssembly}) -static System.StringComparer.InvariantCulture.get -> System.StringComparer{NonNullSuffix} (forwarded, contained in {containingAssembly}) -static System.StringComparer.InvariantCultureIgnoreCase.get -> System.StringComparer{NonNullSuffix} (forwarded, contained in {containingAssembly}) -static System.StringComparer.CurrentCulture.get -> System.StringComparer{NonNullSuffix} (forwarded, contained in {containingAssembly}) -static System.StringComparer.CurrentCultureIgnoreCase.get -> System.StringComparer{NonNullSuffix} (forwarded, contained in {containingAssembly}) -static System.StringComparer.Ordinal.get -> System.StringComparer{NonNullSuffix} (forwarded, contained in {containingAssembly}) -static System.StringComparer.OrdinalIgnoreCase.get -> System.StringComparer{NonNullSuffix} (forwarded, contained in {containingAssembly}) -static System.StringComparer.Create(System.Globalization.CultureInfo{NonNullSuffix} culture, bool ignoreCase) -> System.StringComparer{NonNullSuffix} (forwarded, contained in {containingAssembly}) -System.StringComparer.Compare(object{NullableSuffix} x, object{NullableSuffix} y) -> int (forwarded, contained in {containingAssembly}) -System.StringComparer.Equals(object{NullableSuffix} x, object{NullableSuffix} y) -> bool (forwarded, contained in {containingAssembly}) -System.StringComparer.GetHashCode(object{NonNullSuffix} obj) -> int (forwarded, contained in {containingAssembly}) -abstract System.StringComparer.Compare(string{NullableSuffix} x, string{NullableSuffix} y) -> int (forwarded, contained in {containingAssembly}) -abstract System.StringComparer.Equals(string{NullableSuffix} x, string{NullableSuffix} y) -> bool (forwarded, contained in {containingAssembly}) -abstract System.StringComparer.GetHashCode(string{NonNullSuffix} obj) -> int (forwarded, contained in {containingAssembly}) -System.StringComparer.StringComparer() -> void (forwarded, contained in {containingAssembly}) -"; + string shippedText = $""" + + System.StringComparer (forwarded, contained in {containingAssembly}) + static System.StringComparer.InvariantCulture.get -> System.StringComparer{NonNullSuffix} (forwarded, contained in {containingAssembly}) + static System.StringComparer.InvariantCultureIgnoreCase.get -> System.StringComparer{NonNullSuffix} (forwarded, contained in {containingAssembly}) + static System.StringComparer.CurrentCulture.get -> System.StringComparer{NonNullSuffix} (forwarded, contained in {containingAssembly}) + static System.StringComparer.CurrentCultureIgnoreCase.get -> System.StringComparer{NonNullSuffix} (forwarded, contained in {containingAssembly}) + static System.StringComparer.Ordinal.get -> System.StringComparer{NonNullSuffix} (forwarded, contained in {containingAssembly}) + static System.StringComparer.OrdinalIgnoreCase.get -> System.StringComparer{NonNullSuffix} (forwarded, contained in {containingAssembly}) + static System.StringComparer.Create(System.Globalization.CultureInfo{NonNullSuffix} culture, bool ignoreCase) -> System.StringComparer{NonNullSuffix} (forwarded, contained in {containingAssembly}) + System.StringComparer.Compare(object{NullableSuffix} x, object{NullableSuffix} y) -> int (forwarded, contained in {containingAssembly}) + System.StringComparer.Equals(object{NullableSuffix} x, object{NullableSuffix} y) -> bool (forwarded, contained in {containingAssembly}) + System.StringComparer.GetHashCode(object{NonNullSuffix} obj) -> int (forwarded, contained in {containingAssembly}) + abstract System.StringComparer.Compare(string{NullableSuffix} x, string{NullableSuffix} y) -> int (forwarded, contained in {containingAssembly}) + abstract System.StringComparer.Equals(string{NullableSuffix} x, string{NullableSuffix} y) -> bool (forwarded, contained in {containingAssembly}) + abstract System.StringComparer.GetHashCode(string{NonNullSuffix} obj) -> int (forwarded, contained in {containingAssembly}) + System.StringComparer.StringComparer() -> void (forwarded, contained in {containingAssembly}) + + """; #if NETCOREAPP - shippedText = $@" -#nullable enable -{shippedText} -static System.StringComparer.Create(System.Globalization.CultureInfo{NonNullSuffix} culture, System.Globalization.CompareOptions options) -> System.StringComparer{NonNullSuffix} (forwarded, contained in {containingAssembly}) -static System.StringComparer.FromComparison(System.StringComparison comparisonType) -> System.StringComparer{NonNullSuffix} (forwarded, contained in {containingAssembly}) -"; + shippedText = $""" + + #nullable enable + {shippedText} + static System.StringComparer.Create(System.Globalization.CultureInfo{NonNullSuffix} culture, System.Globalization.CompareOptions options) -> System.StringComparer{NonNullSuffix} (forwarded, contained in {containingAssembly}) + static System.StringComparer.FromComparison(System.StringComparison comparisonType) -> System.StringComparer{NonNullSuffix} (forwarded, contained in {containingAssembly}) + + """; + #endif - string unshippedText = $@""; + await VerifyCSharpAsync(""" + + [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.StringComparer))] - await VerifyCSharpAsync(source, shippedText, unshippedText); + """, shippedText, $@""); } [Fact, WorkItem(1192, "https://github.com/dotnet/roslyn-analyzers/issues/1192")] @@ -1178,20 +1038,17 @@ public async Task OpenGenericTypeForwardsAreProcessedAsync() return; } - var source = @" -[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.IEnumerable<>))] -"; - - string shippedText = ""; - string unshippedText = ""; - #if NETCOREAPP var containingAssembly = "System.Runtime"; #else var containingAssembly = "mscorlib"; #endif - await VerifyCSharpAsync(source, shippedText, unshippedText, + await VerifyCSharpAsync(""" + + [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.IEnumerable<>))] + + """, "", "", // /0/Test0.cs(2,12): warning RS0016: Symbol 'System.Collections.Generic.IEnumerable (forwarded, contained in System.Runtime)' is not part of the declared API GetCSharpResultAt(2, 12, DeclareNewApiRule, $"System.Collections.Generic.IEnumerable (forwarded, contained in {containingAssembly})"), // /0/Test0.cs(2,12): warning RS0016: Symbol 'System.Collections.Generic.IEnumerable.GetEnumerator() -> System.Collections.Generic.IEnumerator (forwarded, contained in System.Runtime)' is not part of the declared API @@ -1211,20 +1068,17 @@ public async Task GenericTypeForwardsAreProcessedAsync() return; } - var source = @" -[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.IEnumerable))] -"; - - string shippedText = ""; - string unshippedText = ""; - #if NETCOREAPP var containingAssembly = "System.Runtime"; #else var containingAssembly = "mscorlib"; #endif - await VerifyCSharpAsync(source, shippedText, unshippedText, + await VerifyCSharpAsync(""" + + [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.IEnumerable))] + + """, "", "", // /0/Test0.cs(2,12): warning RS0016: Symbol 'System.Collections.Generic.IEnumerable (forwarded, contained in System.Runtime)' is not part of the declared API GetCSharpResultAt(2, 12, DeclareNewApiRule, $"System.Collections.Generic.IEnumerable (forwarded, contained in {containingAssembly})"), // /0/Test0.cs(2,12): warning RS0016: Symbol 'System.Collections.Generic.IEnumerable.GetEnumerator() -> System.Collections.Generic.IEnumerator (forwarded, contained in System.Runtime)' is not part of the declared API @@ -1239,47 +1093,6 @@ await VerifyCSharpAsync(source, shippedText, unshippedText, [Fact, WorkItem(851, "https://github.com/dotnet/roslyn-analyzers/issues/851")] public async Task TestAvoidMultipleOverloadsWithOptionalParametersAsync() { - var source = $$""" - - public class C - { - // ok - single overload with optional params, 2 overloads have no public API entries. - {{EnabledModifierCSharp}} void Method1(int p1, int p2, int p3 = 0) { } - {{EnabledModifierCSharp}} void Method1() { } - {{EnabledModifierCSharp}} void Method1(int p1, int p2) { } - {{EnabledModifierCSharp}} void Method1(char p1, params int[] p2) { } - - // ok - multiple overloads with optional params, but only one is public. - {{EnabledModifierCSharp}} void Method2(int p1 = 0) { } - {{DisabledModifierCSharp}} void Method2(char p1 = '0') { } - private void Method2(string p1 = null) { } - - // ok - multiple overloads with optional params, but all are shipped. - {{EnabledModifierCSharp}} void Method3(int p1 = 0) { } - {{EnabledModifierCSharp}} void Method3(string p1 = null) { } - - // fire on unshipped (1) - multiple overloads with optional params, all but first are shipped. - {{EnabledModifierCSharp}} void Method4(int p1 = 0) { } - {{EnabledModifierCSharp}} void Method4(char p1 = 'a') { } - {{EnabledModifierCSharp}} void Method4(string p1 = null) { } - - // fire on all unshipped (3) - multiple overloads with optional params, all are unshipped, 2 have unshipped entries. - {{EnabledModifierCSharp}} void Method5(int p1 = 0) { } - {{EnabledModifierCSharp}} void Method5(char p1 = 'a') { } - {{EnabledModifierCSharp}} void Method5(string p1 = null) { } - - // ok - multiple overloads with optional params, but all have same params (differ only by generic vs non-generic). - {{EnabledModifierCSharp}} object Method6(int p1 = 0) { return Method6(p1); } - {{EnabledModifierCSharp}} T Method6(int p1 = 0) { return default(T); } - } - """; - - string shippedText = """ - C.Method3(int p1 = 0) -> void - C.Method3(string p1 = null) -> void - C.Method4(char p1 = 'a') -> void - C.Method4(string p1 = null) -> void - """; string unshippedText = (IsInternalTest ? "" : """ @@ -1319,7 +1132,7 @@ private void Method2(string p1 = null) { } // Test0.cs(27,17): warning RS0026: Symbol 'Method5' violates the backcompat requirement: 'Do not add multiple overloads with optional parameters'. See 'https://github.com/dotnet/roslyn/blob/main/docs/Adding%20Optional%20Parameters%20in%20Public%20API.md' for details. GetCSharpResultAt(27, 19, AvoidMultipleOverloadsWithOptionalParameters, "Method5", AvoidMultipleOverloadsWithOptionalParameters.HelpLinkUri) } - : new[] { + : [ // Test0.cs(5,17): warning RS0016: Symbol 'C.Method1(int p1, int p2, int p3 = 0) -> void' is not part of the declared API. GetCSharpResultAt(5, 17, DeclareNewApiRule, "C.Method1(int p1, int p2, int p3 = 0) -> void"), // Test0.cs(8,17): warning RS0016: Symbol 'C.Method1(char p1, params int[] p2) -> void' is not part of the declared API. @@ -1334,60 +1147,52 @@ private void Method2(string p1 = null) { } GetCSharpResultAt(26, 17, AvoidMultipleOverloadsWithOptionalParameters, "Method5", AvoidMultipleOverloadsWithOptionalParameters.HelpLinkUri), // Test0.cs(27,17): warning RS0026: Symbol 'Method5' violates the backcompat requirement: 'Do not add multiple overloads with optional parameters'. See 'https://github.com/dotnet/roslyn/blob/main/docs/Adding%20Optional%20Parameters%20in%20Public%20API.md' for details. GetCSharpResultAt(27, 17, AvoidMultipleOverloadsWithOptionalParameters, "Method5", AvoidMultipleOverloadsWithOptionalParameters.HelpLinkUri) - }; + ]; - await VerifyCSharpAsync(source, shippedText, unshippedText, result); - } - - [Fact, WorkItem(851, "https://github.com/dotnet/roslyn-analyzers/issues/851")] - public async Task TestOverloadWithOptionalParametersShouldHaveMostParametersAsync() - { - var source = $$""" + await VerifyCSharpAsync($$""" public class C { - // ok - single overload with optional params has most parameters. + // ok - single overload with optional params, 2 overloads have no public API entries. {{EnabledModifierCSharp}} void Method1(int p1, int p2, int p3 = 0) { } {{EnabledModifierCSharp}} void Method1() { } {{EnabledModifierCSharp}} void Method1(int p1, int p2) { } {{EnabledModifierCSharp}} void Method1(char p1, params int[] p2) { } - // ok - multiple overloads with optional params violating most params requirement, but only one is public. + // ok - multiple overloads with optional params, but only one is public. {{EnabledModifierCSharp}} void Method2(int p1 = 0) { } - {{DisabledModifierCSharp}} void Method2(int p1, char p2 = '0') { } + {{DisabledModifierCSharp}} void Method2(char p1 = '0') { } private void Method2(string p1 = null) { } - // ok - multiple overloads with optional params violating most params requirement, but all are shipped. + // ok - multiple overloads with optional params, but all are shipped. {{EnabledModifierCSharp}} void Method3(int p1 = 0) { } {{EnabledModifierCSharp}} void Method3(string p1 = null) { } - {{EnabledModifierCSharp}} void Method3(int p1, int p2) { } - // fire on unshipped (1) - single overload with optional params and violating most params requirement. - {{EnabledModifierCSharp}} void Method4(int p1 = 0) { } // unshipped - {{EnabledModifierCSharp}} void Method4(char p1, int p2) { } // unshipped - {{EnabledModifierCSharp}} void Method4(string p1, int p2) { } // unshipped + // fire on unshipped (1) - multiple overloads with optional params, all but first are shipped. + {{EnabledModifierCSharp}} void Method4(int p1 = 0) { } + {{EnabledModifierCSharp}} void Method4(char p1 = 'a') { } + {{EnabledModifierCSharp}} void Method4(string p1 = null) { } - // fire on shipped (1) - single shipped overload with optional params and violating most params requirement due to a new unshipped API. - {{EnabledModifierCSharp}} void Method5(int p1 = 0) { } // shipped - {{EnabledModifierCSharp}} void Method5(char p1) { } // shipped - {{EnabledModifierCSharp}} void Method5(string p1) { } // unshipped + // fire on all unshipped (3) - multiple overloads with optional params, all are unshipped, 2 have unshipped entries. + {{EnabledModifierCSharp}} void Method5(int p1 = 0) { } + {{EnabledModifierCSharp}} void Method5(char p1 = 'a') { } + {{EnabledModifierCSharp}} void Method5(string p1 = null) { } - // fire on multiple shipped (2) - multiple shipped overloads with optional params and violating most params requirement due to a new unshipped API - {{EnabledModifierCSharp}} void Method6(int p1 = 0) { } // shipped - {{EnabledModifierCSharp}} void Method6(char p1 = 'a') { } // shipped - {{EnabledModifierCSharp}} void Method6(string p1) { } // unshipped + // ok - multiple overloads with optional params, but all have same params (differ only by generic vs non-generic). + {{EnabledModifierCSharp}} object Method6(int p1 = 0) { return Method6(p1); } + {{EnabledModifierCSharp}} T Method6(int p1 = 0) { return default(T); } } - """; - - string shippedText = """ + """, """ C.Method3(int p1 = 0) -> void - C.Method3(int p1, int p2) -> void C.Method3(string p1 = null) -> void - C.Method5(char p1) -> void - C.Method5(int p1 = 0) -> void - C.Method6(char p1 = 'a') -> void - C.Method6(int p1 = 0) -> void - """; + C.Method4(char p1 = 'a') -> void + C.Method4(string p1 = null) -> void + """, unshippedText, result); + } + + [Fact, WorkItem(851, "https://github.com/dotnet/roslyn-analyzers/issues/851")] + public async Task TestOverloadWithOptionalParametersShouldHaveMostParametersAsync() + { string unshippedText = (IsInternalTest ? "" : """ C @@ -1406,10 +1211,10 @@ private void Method2(string p1 = null) { } C.Method6(string p1) -> void """; - var diagnostics = IsInternalTest ? new DiagnosticResult[] { + var diagnostics = IsInternalTest ? [ // /0/Test0.cs(11,19): warning RS0059: Symbol 'Method2' violates the backcompat requirement: 'Do not add multiple overloads with optional parameters'. See 'https://github.com/dotnet/roslyn/blob/main/docs/Adding%20Optional%20Parameters%20in%20Public%20API.md' for details. GetCSharpResultAt(11, 19, AvoidMultipleOverloadsWithOptionalParameters, "Method2", AvoidMultipleOverloadsWithOptionalParameters.HelpLinkUri), - } : Array.Empty(); + ] : Array.Empty(); diagnostics = diagnostics.Concat(new[] { // Test0.cs(21,17): warning RS0027: Symbol 'Method4' violates the backcompat requirement: 'Public API with optional parameter(s) should have the most parameters amongst its public overloads'. See 'https://github.com/dotnet/roslyn/blob/main/docs/Adding%20Optional%20Parameters%20in%20Public%20API.md' for details. @@ -1422,13 +1227,57 @@ private void Method2(string p1 = null) { } GetCSharpResultAt(32, 11 + EnabledModifierCSharp.Length, OverloadWithOptionalParametersShouldHaveMostParameters, "Method6", OverloadWithOptionalParametersShouldHaveMostParameters.HelpLinkUri) }).ToArray(); - await VerifyCSharpAsync(source, shippedText, unshippedText, diagnostics); + await VerifyCSharpAsync($$""" + + public class C + { + // ok - single overload with optional params has most parameters. + {{EnabledModifierCSharp}} void Method1(int p1, int p2, int p3 = 0) { } + {{EnabledModifierCSharp}} void Method1() { } + {{EnabledModifierCSharp}} void Method1(int p1, int p2) { } + {{EnabledModifierCSharp}} void Method1(char p1, params int[] p2) { } + + // ok - multiple overloads with optional params violating most params requirement, but only one is public. + {{EnabledModifierCSharp}} void Method2(int p1 = 0) { } + {{DisabledModifierCSharp}} void Method2(int p1, char p2 = '0') { } + private void Method2(string p1 = null) { } + + // ok - multiple overloads with optional params violating most params requirement, but all are shipped. + {{EnabledModifierCSharp}} void Method3(int p1 = 0) { } + {{EnabledModifierCSharp}} void Method3(string p1 = null) { } + {{EnabledModifierCSharp}} void Method3(int p1, int p2) { } + + // fire on unshipped (1) - single overload with optional params and violating most params requirement. + {{EnabledModifierCSharp}} void Method4(int p1 = 0) { } // unshipped + {{EnabledModifierCSharp}} void Method4(char p1, int p2) { } // unshipped + {{EnabledModifierCSharp}} void Method4(string p1, int p2) { } // unshipped + + // fire on shipped (1) - single shipped overload with optional params and violating most params requirement due to a new unshipped API. + {{EnabledModifierCSharp}} void Method5(int p1 = 0) { } // shipped + {{EnabledModifierCSharp}} void Method5(char p1) { } // shipped + {{EnabledModifierCSharp}} void Method5(string p1) { } // unshipped + + // fire on multiple shipped (2) - multiple shipped overloads with optional params and violating most params requirement due to a new unshipped API + {{EnabledModifierCSharp}} void Method6(int p1 = 0) { } // shipped + {{EnabledModifierCSharp}} void Method6(char p1 = 'a') { } // shipped + {{EnabledModifierCSharp}} void Method6(string p1) { } // unshipped + } + """, """ + C.Method3(int p1 = 0) -> void + C.Method3(int p1, int p2) -> void + C.Method3(string p1 = null) -> void + C.Method5(char p1) -> void + C.Method5(int p1 = 0) -> void + C.Method6(char p1 = 'a') -> void + C.Method6(int p1 = 0) -> void + """, unshippedText, diagnostics); } [Fact, WorkItem(4766, "https://github.com/dotnet/roslyn-analyzers/issues/4766")] public async Task TestObsoleteOverloadWithOptionalParameters_NoDiagnosticAsync() { - var source = $$""" + string shippedText = string.Empty; + await VerifyCSharpAsync($$""" using System; @@ -1439,24 +1288,20 @@ public async Task TestObsoleteOverloadWithOptionalParameters_NoDiagnosticAsync() [Obsolete] {{EnabledModifierCSharp}} void M(char p1, int p2) { } } - """; + """, shippedText, """ - string shippedText = string.Empty; - string unshippedText = @" -C -C.C() -> void + C + C.C() -> void -C.M(char p1, int p2) -> void -C.M(int p1 = 0) -> void -"; + C.M(char p1, int p2) -> void + C.M(int p1 = 0) -> void - await VerifyCSharpAsync(source, shippedText, unshippedText); + """); } [Fact, WorkItem(4766, "https://github.com/dotnet/roslyn-analyzers/issues/4766")] - public async Task TestMultipleOverloadsWithOptionalParameter_OneIsObsoleteAsync() - { - var source = $$""" + public Task TestMultipleOverloadsWithOptionalParameter_OneIsObsoleteAsync() + => VerifyCSharpAsync($$""" using System; @@ -1467,20 +1312,15 @@ public async Task TestMultipleOverloadsWithOptionalParameter_OneIsObsoleteAsync( [Obsolete] {{EnabledModifierCSharp}} void M(char p1 = '0') { } } - """; - - string shippedText = @"C -C.C() -> void -C.M(char p1 = '0') -> void"; - string unshippedText = "C.M(int p1 = 0) -> void"; - - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + """, """ + C + C.C() -> void + C.M(char p1 = '0') -> void + """, "C.M(int p1 = 0) -> void"); [Fact] - public async Task ObliviousMember_SimpleAsync() - { - var source = $$""" + public Task ObliviousMember_SimpleAsync() + => VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { @@ -1489,20 +1329,16 @@ public async Task ObliviousMember_SimpleAsync() {{EnabledModifierCSharp}} string Method(string x) => throw null!; {{EnabledModifierCSharp}} string ArrowExpressionProperty => throw null!; } - """; - - var shippedText = @"#nullable enable -C -C.ArrowExpressionProperty.get -> string -C.C() -> void -C.Field -> string -C.Method(string x) -> string -C.Property.get -> string -C.Property.set -> void"; - - var unshippedText = @""; - - await VerifyCSharpAsync(source, shippedText, unshippedText, + """, """ + #nullable enable + C + C.ArrowExpressionProperty.get -> string + C.C() -> void + C.Field -> string + C.Method(string x) -> string + C.Property.get -> string + C.Property.set -> void + """, @"", GetCSharpResultAt(4, 13 + EnabledModifierCSharp.Length, AnnotateApiRule, "C.Field -> string"), GetCSharpResultAt(4, 13 + EnabledModifierCSharp.Length, ObliviousApiRule, "Field"), GetCSharpResultAt(5, 24 + EnabledModifierCSharp.Length, AnnotateApiRule, "C.Property.get -> string"), @@ -1514,14 +1350,12 @@ await VerifyCSharpAsync(source, shippedText, unshippedText, GetCSharpResultAt(7, 40 + EnabledModifierCSharp.Length, AnnotateApiRule, "C.ArrowExpressionProperty.get -> string"), GetCSharpResultAt(7, 40 + EnabledModifierCSharp.Length, ObliviousApiRule, "ArrowExpressionProperty.get") ); - } [Theory] [InlineData("string ", "string", "string!")] [InlineData("string?", "string", "string?")] - public async Task ObliviousMember_Simple_NullableTypes(string csharp, string unannotated, string annotated) - { - var source = $$""" + public Task ObliviousMember_Simple_NullableTypes(string csharp, string unannotated, string annotated) + => VerifyCSharpAsync($$""" #nullable enable {{EnabledModifierCSharp}} class C { @@ -1530,9 +1364,7 @@ public async Task ObliviousMember_Simple_NullableTypes(string csharp, string una {{EnabledModifierCSharp}} {{csharp}} Method({{csharp}} x) => throw null!; {{EnabledModifierCSharp}} {{csharp}} ArrowExpressionProperty => throw null!; } - """; - - var shippedText = $""" + """, $""" #nullable enable C C.ArrowExpressionProperty.get -> {unannotated} @@ -1541,21 +1373,15 @@ public async Task ObliviousMember_Simple_NullableTypes(string csharp, string una C.Method({unannotated} x) -> {unannotated} C.Property.get -> {unannotated} C.Property.set -> void - """; - - var unshippedText = ""; - - await VerifyCSharpAsync(source, shippedText, unshippedText, + """, "", GetCSharpResultAt(4, 14 + EnabledModifierCSharp.Length, AnnotateApiRule, $"C.Field -> {annotated}"), GetCSharpResultAt(5, 25 + EnabledModifierCSharp.Length, AnnotateApiRule, $"C.Property.get -> {annotated}"), GetCSharpResultAt(6, 14 + EnabledModifierCSharp.Length, AnnotateApiRule, $"C.Method({annotated} x) -> {annotated}"), GetCSharpResultAt(7, 41 + EnabledModifierCSharp.Length, AnnotateApiRule, $"C.ArrowExpressionProperty.get -> {annotated}")); - } [Fact] - public async Task ObliviousMember_AlreadyMarkedAsObliviousAsync() - { - var source = $$""" + public Task ObliviousMember_AlreadyMarkedAsObliviousAsync() + => VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { @@ -1579,29 +1405,25 @@ public async Task ObliviousMember_AlreadyMarkedAsObliviousAsync() } {{EnabledModifierCSharp}} class D { public class E { } } - """; - - var shippedText = @"#nullable enable -C -~C.ArrowExpressionProperty.get -> string -C.C() -> void -~C.Field -> string -~C.Field2 -> D! -~C.Method(string x) -> void -~C.Method2() -> string -~C.Property.get -> string -~C.Property.set -> void -~C.Method3() -> D.E! -~C.this[string x].set -> void -~C.this[string x].get -> string -D -D.D() -> void -D.E -D.E.E() -> void"; - - var unshippedText = @""; - - await VerifyCSharpAsync(source, shippedText, unshippedText, + """, """ + #nullable enable + C + ~C.ArrowExpressionProperty.get -> string + C.C() -> void + ~C.Field -> string + ~C.Field2 -> D! + ~C.Method(string x) -> void + ~C.Method2() -> string + ~C.Property.get -> string + ~C.Property.set -> void + ~C.Method3() -> D.E! + ~C.this[string x].set -> void + ~C.this[string x].get -> string + D + D.D() -> void + D.E + D.E.E() -> void + """, @"", GetCSharpResultAt(4, 13 + EnabledModifierCSharp.Length, ObliviousApiRule, "Field"), GetCSharpResultAt(7, 11, ObliviousApiRule, "Field2"), GetCSharpResultAt(9, 24 + EnabledModifierCSharp.Length, ObliviousApiRule, "Property.get"), @@ -1613,12 +1435,10 @@ await VerifyCSharpAsync(source, shippedText, unshippedText, GetCSharpResultAt(20, 30 + EnabledModifierCSharp.Length, ObliviousApiRule, "this.get"), GetCSharpResultAt(20, 50 + EnabledModifierCSharp.Length, ObliviousApiRule, "this.set") ); - } [Fact] - public async Task ObliviousMember_AlreadyMarkedAsOblivious_TypeParametersWithClassConstraintAsync() - { - var source = $$""" + public Task ObliviousMember_AlreadyMarkedAsOblivious_TypeParametersWithClassConstraintAsync() + => VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { @@ -1631,35 +1451,29 @@ public async Task ObliviousMember_AlreadyMarkedAsOblivious_TypeParametersWithCla } {{EnabledModifierCSharp}} class D where T : class { } {{EnabledModifierCSharp}} class E { public class F where T : class { } } - """; - - var shippedText = @"#nullable enable -C -C.C() -> void -~C.M(T t) -> void -C.M2(T! t) -> void -C.M3(T t) -> void -~D -D.D() -> void -E -E.E() -> void -~E.F -E.F.F() -> void -"; - - var unshippedText = @""; - - await VerifyCSharpAsync(source, shippedText, unshippedText, + """, """ + #nullable enable + C + C.C() -> void + ~C.M(T t) -> void + C.M2(T! t) -> void + C.M3(T t) -> void + ~D + D.D() -> void + E + E.E() -> void + ~E.F + E.F.F() -> void + + """, @"", GetCSharpResultAt(4, 11 + EnabledModifierCSharp.Length, ObliviousApiRule, "M"), GetCSharpResultAt(11, 8 + EnabledModifierCSharp.Length, ObliviousApiRule, "D"), GetCSharpResultAt(12, 25 + EnabledModifierCSharp.Length, ObliviousApiRule, "F") ); - } [Fact] - public async Task ObliviousMember_AlreadyMarkedAsOblivious_TypeParametersWithNotNullConstraintAsync() - { - var source = $$""" + public Task ObliviousMember_AlreadyMarkedAsOblivious_TypeParametersWithNotNullConstraintAsync() + => VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { @@ -1669,24 +1483,18 @@ public async Task ObliviousMember_AlreadyMarkedAsOblivious_TypeParametersWithNot {{EnabledModifierCSharp}} void M2(T t) where T : notnull { } #nullable disable } - """; - - var shippedText = @"#nullable enable -C -C.C() -> void -C.M(T t) -> void -C.M2(T t) -> void -"; + """, """ + #nullable enable + C + C.C() -> void + C.M(T t) -> void + C.M2(T t) -> void - var unshippedText = @""; - - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + """, @""); [Fact] - public async Task ObliviousMember_AlreadyMarkedAsOblivious_TypeParametersWithMiscConstraintsAsync() - { - var source = $$""" + public Task ObliviousMember_AlreadyMarkedAsOblivious_TypeParametersWithMiscConstraintsAsync() + => VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} interface I { } {{EnabledModifierCSharp}} class C @@ -1701,33 +1509,27 @@ public async Task ObliviousMember_AlreadyMarkedAsOblivious_TypeParametersWithMis {{EnabledModifierCSharp}} void M3b() where T : U where U : class { } #nullable disable } - """; - - var shippedText = @"#nullable enable -I -C -C.C() -> void -~C.M1() -> void -~C.M2() -> void -~C.M3() -> void -C.M1b() -> void -C.M2b() -> void -C.M3b() -> void -"; - - var unshippedText = @""; - - await VerifyCSharpAsync(source, shippedText, unshippedText, + """, """ + #nullable enable + I + C + C.C() -> void + ~C.M1() -> void + ~C.M2() -> void + ~C.M3() -> void + C.M1b() -> void + C.M2b() -> void + C.M3b() -> void + + """, @"", GetCSharpResultAt(5, 11 + EnabledModifierCSharp.Length, ObliviousApiRule, "M1"), GetCSharpResultAt(6, 11 + EnabledModifierCSharp.Length, ObliviousApiRule, "M2"), GetCSharpResultAt(7, 11 + EnabledModifierCSharp.Length, ObliviousApiRule, "M3") ); - } [Fact] - public async Task ObliviousMember_AlreadyMarkedAsOblivious_TypeParametersWithMiscConstraints2Async() - { - var source = $$""" + public Task ObliviousMember_AlreadyMarkedAsOblivious_TypeParametersWithMiscConstraints2Async() + => VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} interface I { } {{EnabledModifierCSharp}} class C @@ -1741,26 +1543,20 @@ public async Task ObliviousMember_AlreadyMarkedAsOblivious_TypeParametersWithMis #nullable disable } - """; - - var shippedText = @"#nullable enable -I -C -C.C() -> void -~C.M1() -> void -"; - - var unshippedText = @""; + """, """ + #nullable enable + I + C + C.C() -> void + ~C.M1() -> void - await VerifyCSharpAsync(source, shippedText, unshippedText, + """, @"", GetCSharpResultAt(6, 11 + EnabledModifierCSharp.Length, ObliviousApiRule, "M1") ); - } [Fact] - public async Task ObliviousMember_NestedEnumIsNotObliviousAsync() - { - var source = $$""" + public Task ObliviousMember_NestedEnumIsNotObliviousAsync() + => VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { @@ -1770,24 +1566,18 @@ public async Task ObliviousMember_NestedEnumIsNotObliviousAsync() Some } } - """; - - var shippedText = @"#nullable enable -C -C.C() -> void -C.E -C.E.None = 0 -> C.E -C.E.Some = 1 -> C.E"; - - var unshippedText = @""; - - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + """, """ + #nullable enable + C + C.C() -> void + C.E + C.E.None = 0 -> C.E + C.E.Some = 1 -> C.E + """, @""); [Fact] - public async Task NestedEnumIsNotObliviousAsync() - { - var source = $$""" + public Task NestedEnumIsNotObliviousAsync() + => VerifyCSharpAsync($$""" #nullable enable {{EnabledModifierCSharp}} class C @@ -1798,24 +1588,18 @@ public async Task NestedEnumIsNotObliviousAsync() Some } } - """; - - var shippedText = @"#nullable enable -C -C.C() -> void -C.E -C.E.None = 0 -> C.E -C.E.Some = 1 -> C.E"; - - var unshippedText = @""; - - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + """, """ + #nullable enable + C + C.C() -> void + C.E + C.E.None = 0 -> C.E + C.E.Some = 1 -> C.E + """, @""); [Fact] - public async Task ObliviousTypeArgumentInContainingTypeAsync() - { - var source = $$""" + public Task ObliviousTypeArgumentInContainingTypeAsync() + => VerifyCSharpAsync($$""" #nullable enable {{EnabledModifierCSharp}} class C @@ -1828,26 +1612,20 @@ public async Task ObliviousTypeArgumentInContainingTypeAsync() #nullable enable >.Nested field; } - """; - - var shippedText = @"#nullable enable -C -C.C() -> void -C.Nested -C.Nested.Nested() -> void -~C.field -> C.Nested"; - - var unshippedText = @""; - - await VerifyCSharpAsync(source, shippedText, unshippedText, + """, """ + #nullable enable + C + C.C() -> void + C.Nested + C.Nested.Nested() -> void + ~C.field -> C.Nested + """, @"", GetCSharpResultAt(11, 22, ObliviousApiRule, "field") ); - } [Fact] - public async Task ImplicitContainingType_TClassAsync() - { - var source = $$""" + public Task ImplicitContainingType_TClassAsync() + => VerifyCSharpAsync($$""" #nullable enable {{EnabledModifierCSharp}} class C where T : class @@ -1858,36 +1636,22 @@ public async Task ImplicitContainingType_TClassAsync() {{EnabledModifierCSharp}} C.Nested field2; } - """; - - var shippedText = @"#nullable enable -C -C.C() -> void -C.Nested -C.Nested.Nested() -> void -~C.field -> C.Nested -C.field2 -> C.Nested"; - - var unshippedText = @""; - - // Note: although the code is entirely nullable-enabled, the compiler uses a containing type that is - // `C` so there is an oblivious symbol. This only happens when the type parameter is constrained - // such that it could be annotated in C# 8 (`T?` would have been allowed). - // - // One recourse is to use a suppression around such APIs: - // #pragma warning disable RS0041 // uses oblivious reference types - // - // Another recourse is to make the containing type explicit: `C.Nested` - await VerifyCSharpAsync(source, shippedText, unshippedText, + """, """ + #nullable enable + C + C.C() -> void + C.Nested + C.Nested.Nested() -> void + ~C.field -> C.Nested + C.field2 -> C.Nested + """, @"", // /0/Test0.cs(7,19): warning RS0041: Symbol 'field' uses some oblivious reference types. GetCSharpResultAt(7, 13 + EnabledModifierCSharp.Length, ObliviousApiRule, "field") ); - } [Fact] - public async Task ImplicitContainingType_TOpenAsync() - { - var source = $$""" + public Task ImplicitContainingType_TOpenAsync() + => VerifyCSharpAsync($$""" #nullable enable {{EnabledModifierCSharp}} class C @@ -1897,25 +1661,23 @@ public async Task ImplicitContainingType_TOpenAsync() {{EnabledModifierCSharp}} Nested field; {{EnabledModifierCSharp}} Nested field2; } - """; - - var shippedText = @"#nullable enable -C -C.C() -> void -C.Nested -C.Nested.Nested() -> void -C.field -> C.Nested -C.field2 -> C.Nested"; - - var unshippedText = @""; - - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + """, """ + #nullable enable + C + C.C() -> void + C.Nested + C.Nested.Nested() -> void + C.field -> C.Nested + C.field2 -> C.Nested + """, @""); [Fact] public async Task SkippedNamespace_ExactMatches() { - var source = $$""" + string? shippedText = null; + string? unshippedText = null; + + await VerifyCSharpAsync($$""" namespace My.Namespace { {{EnabledModifierCSharp}} class C @@ -1930,12 +1692,7 @@ namespace Other.Namespace {{EnabledModifierCSharp}} D() { } } } - """; - - string? shippedText = null; - string? unshippedText = null; - - await VerifyCSharpAsync(source, shippedText, unshippedText, $"[*]\r\ndotnet_public_api_analyzer.skip_namespaces = My.Namespace", + """, shippedText, unshippedText, $"[*]\r\ndotnet_public_api_analyzer.skip_namespaces = My.Namespace", // /0/Test0.cs(10,18): warning RS0016: Symbol 'Other.Namespace.D' is not part of the declared public API GetCSharpResultAt(10, 12 + EnabledModifierCSharp.Length, DeclareNewApiRule, "Other.Namespace.D"), // /0/Test0.cs(12,16): warning RS0016: Symbol 'Other.Namespace.D.D() -> void' is not part of the declared public API @@ -1945,7 +1702,10 @@ await VerifyCSharpAsync(source, shippedText, unshippedText, $"[*]\r\ndotnet_publ [Fact] public async Task SkippedNamespace_ShorterSpecifiedNamespace() { - var source = $$""" + string? shippedText = null; + string? unshippedText = null; + + await VerifyCSharpAsync($$""" namespace My.Namespace { {{EnabledModifierCSharp}} class C @@ -1953,18 +1713,16 @@ namespace My.Namespace {{EnabledModifierCSharp}} C() { } } } - """; - - string? shippedText = null; - string? unshippedText = null; - - await VerifyCSharpAsync(source, shippedText, unshippedText, $"[*]\r\ndotnet_public_api_analyzer.skip_namespaces = My"); + """, shippedText, unshippedText, $"[*]\r\ndotnet_public_api_analyzer.skip_namespaces = My"); } [Fact] public async Task SkippedNamespace_MoreDerivedNamespace() { - var source = $$""" + string? shippedText = null; + string? unshippedText = null; + + await VerifyCSharpAsync($$""" namespace My.Namespace { {{EnabledModifierCSharp}} class C @@ -1972,12 +1730,7 @@ namespace My.Namespace {{EnabledModifierCSharp}} C() { } } } - """; - - string? shippedText = null; - string? unshippedText = null; - - await VerifyCSharpAsync(source, shippedText, unshippedText, $"[*]\r\ndotnet_public_api_analyzer.skip_namespaces = My.Namespace.Longer", + """, shippedText, unshippedText, $"[*]\r\ndotnet_public_api_analyzer.skip_namespaces = My.Namespace.Longer", // /0/Test0.cs(3,18): warning RS0016: Symbol 'My.Namespace.C' is not part of the declared public API GetCSharpResultAt(line: 3, 12 + EnabledModifierCSharp.Length, DeclareNewApiRule, "My.Namespace.C"), // /0/Test0.cs(5,16): warning RS0016: Symbol 'My.Namespace.C.C() -> void' is not part of the declared public API @@ -2011,20 +1764,6 @@ namespace My.Namespace [Fact] public async Task ShippedTextWithMissingImplicitRecordMembers() { - var source = $$""" - #nullable enable - {{EnabledModifierCSharp}} record C(int X, string Y) - { - } - - namespace System.Runtime.CompilerServices - { - internal static class IsExternalInit - { - } - } - """; - var shippedText = """ #nullable enable C @@ -2053,26 +1792,34 @@ virtual C.PrintMembers(System.Text.StringBuilder! builder) -> bool var unshippedText = string.Empty; - await VerifyCSharpAsync(source, shippedText, unshippedText); + await VerifyCSharpAsync($$""" + #nullable enable + {{EnabledModifierCSharp}} record C(int X, string Y) + { + } + + namespace System.Runtime.CompilerServices + { + internal static class IsExternalInit + { + } + } + """, shippedText, unshippedText); } [Fact] public async Task ShippedTextWithMissingDelegate() { - var source = $$""" + var unshippedText = string.Empty; + + await VerifyCSharpAsync($$""" #nullable enable {{EnabledModifierCSharp}} delegate void D(int X, string Y); - """; - - var shippedText = """ + """, """ #nullable enable D virtual D.Invoke(int X, string! Y) -> void - """; - - var unshippedText = string.Empty; - - await VerifyCSharpAsync(source, shippedText, unshippedText); + """, unshippedText); } #endregion @@ -2082,81 +1829,67 @@ virtual D.Invoke(int X, string! Y) -> void [Fact] public async Task ShippedTextWithMissingImplicitStructConstructorAsync() { - var source = $$""" + var unshippedText = string.Empty; + await VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} struct {|{{AddNewApiId}}:C|} { } - """; - - var shippedText = @" -C"; - var unshippedText = string.Empty; - var fixedUnshippedText = "C.C() -> void"; + """, """ - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); + C + """, unshippedText, "C.C() -> void"); } [Fact] public async Task ShippedTextWithMissingImplicitStructConstructorWithExplicitPrivateCtorWithParametersAsync() { - var source = $$""" + var unshippedText = string.Empty; + await VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} struct {|{{AddNewApiId}}:C|} { private C(string x) {} } - """; - - var shippedText = @" -C"; - var unshippedText = string.Empty; - var fixedUnshippedText = "C.C() -> void"; + """, """ - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); + C + """, unshippedText, "C.C() -> void"); } [Fact] public async Task ShippedTextWithMissingImplicitStructConstructorWithOtherOverloadsAsync() { - var source = $$""" + var unshippedText = string.Empty; + await VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} struct {|{{AddNewApiId}}:C|} { {{EnabledModifierCSharp}} C(int value) { } } - """; - - var shippedText = @" -C -C.C(int value) -> void"; - var unshippedText = string.Empty; - var fixedUnshippedText = "C.C() -> void"; + """, """ - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); + C + C.C(int value) -> void + """, unshippedText, "C.C() -> void"); } [Fact] [WorkItem(2622, "https://github.com/dotnet/roslyn-analyzers/issues/2622")] public async Task AnalyzerFileMissing_Both_FixAsync() { - var source = $$""" + string? shippedText = null; + string? unshippedText = null; + await VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} class {|{{AddNewApiId}}:C|} { private C() { } } - """; - - string? shippedText = null; - string? unshippedText = null; - var fixedUnshippedText = @"C"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); + """, shippedText, unshippedText, @"C"); } [Fact] - public async Task TestSimpleMissingMember_FixAsync() - { - var source = $$""" + public Task TestSimpleMissingMember_FixAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} class C { {{EnabledModifierCSharp}} int Field; @@ -2166,35 +1899,31 @@ public async Task TestSimpleMissingMember_FixAsync() {{EnabledModifierCSharp}} int {|{{AddNewApiId}}:NewField|}; // Newly added field, not in current public API. } - """; - - var shippedText = @""; - var unshippedText = @"C -C.ArrowExpressionProperty.get -> int -C.C() -> void -C.Field -> int -C.Method() -> void -C.Property.get -> int -C.Property.set -> void"; - var fixedUnshippedText = @"C -C.ArrowExpressionProperty.get -> int -C.C() -> void -C.Field -> int -C.Method() -> void -C.NewField -> int -C.Property.get -> int -C.Property.set -> void"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); - } + """, @"", """ + C + C.ArrowExpressionProperty.get -> int + C.C() -> void + C.Field -> int + C.Method() -> void + C.Property.get -> int + C.Property.set -> void + """, """ + C + C.ArrowExpressionProperty.get -> int + C.C() -> void + C.Field -> int + C.Method() -> void + C.NewField -> int + C.Property.get -> int + C.Property.set -> void + """); [Theory] [WorkItem(4749, "https://github.com/dotnet/roslyn-analyzers/issues/4749")] [InlineData("\r\n")] // Windows line ending. [InlineData("\n")] // Linux line ending. - public async Task TestUseExistingLineEndingsAsync(string lineEnding) - { - var source = $$""" + public Task TestUseExistingLineEndingsAsync(string lineEnding) + => VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} class C { private C() { } @@ -2202,79 +1931,58 @@ private C() { } {{EnabledModifierCSharp}} int Field2; {{EnabledModifierCSharp}} int {|{{AddNewApiId}}:Field3|}; // Newly added field, not in current public API. } - """; - - var shippedText = @""; - var unshippedText = $"C{lineEnding}C.Field1 -> int{lineEnding}C.Field2 -> int"; - var fixedUnshippedText = $"C{lineEnding}C.Field1 -> int{lineEnding}C.Field2 -> int{lineEnding}C.Field3 -> int"; - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); - } + """, @"", $"C{lineEnding}C.Field1 -> int{lineEnding}C.Field2 -> int", $"C{lineEnding}C.Field1 -> int{lineEnding}C.Field2 -> int{lineEnding}C.Field3 -> int"); [Fact] [WorkItem(4749, "https://github.com/dotnet/roslyn-analyzers/issues/4749")] - public async Task TestUseOSLineEndingAsync() - { - var source = $$""" + public Task TestUseOSLineEndingAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} class C { private C() { } {{EnabledModifierCSharp}} int {|{{AddNewApiId}}:Field1|}; // Newly added field, not in current public API. } - """; - var shippedText = @""; - var unshippedText = $"C"; - var fixedUnshippedText = $"C{Environment.NewLine}C.Field1 -> int"; - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); - } + """, @"", $"C", $"C{Environment.NewLine}C.Field1 -> int"); [Fact] - public async Task TestSimpleMissingMember_Fix_WithoutNullabilityAsync() - { - var source = $$""" + public Task TestSimpleMissingMember_Fix_WithoutNullabilityAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" #nullable enable {{EnabledModifierCSharp}} class C { {{EnabledModifierCSharp}} string? {|{{ShouldAnnotateApiFilesId}}:{|{{AddNewApiId}}:NewField|}|}; // Newly added field, not in current public API. } - """; - - var shippedText = @""; - var unshippedText = @"C -C.C() -> void"; - var fixedUnshippedText = @"C -C.C() -> void -C.NewField -> string"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); - } + """, @"", """ + C + C.C() -> void + """, """ + C + C.C() -> void + C.NewField -> string + """); [InlineData(0)] [InlineData(1)] [Theory] public async Task TestSimpleMissingMember_Fix_WithoutNullability_MultipleFilesAsync(int index) { - var source = $$""" - #nullable enable - {{EnabledModifierCSharp}} class C - { - {{EnabledModifierCSharp}} string? {|{{ShouldAnnotateApiFilesId}}:{|{{AddNewApiId}}:NewField|}|}; // Newly added field, not in current public API. - } - """; - var shippedText = @""; - var unshippedText1 = @"C -C.C() -> void"; + var unshippedText1 = """ + C + C.C() -> void + """; var unshippedText2 = @""; - var fixedUnshippedText1_index0 = @"C -C.C() -> void -C.NewField -> string"; - var fixedUnshippedText1_index1 = "C.NewField -> string"; - var unshippedTextName2 = UnshippedFileNamePrefix + "test" + DeclarePublicApiAnalyzer.Extension; var test = new CSharpCodeFixTest(); - test.TestState.Sources.Add(source); + test.TestState.Sources.Add($$""" + #nullable enable + {{EnabledModifierCSharp}} class C + { + {{EnabledModifierCSharp}} string? {|{{ShouldAnnotateApiFilesId}}:{|{{AddNewApiId}}:NewField|}|}; // Newly added field, not in current public API. + } + """); test.TestState.AdditionalFiles.Add((ShippedFileName, shippedText)); test.TestState.AdditionalFiles.Add((UnshippedFileName, unshippedText1)); test.TestState.AdditionalFiles.Add((unshippedTextName2, unshippedText2)); @@ -2284,13 +1992,17 @@ public async Task TestSimpleMissingMember_Fix_WithoutNullability_MultipleFilesAs if (index == 0) { - test.FixedState.AdditionalFiles.Add((UnshippedFileName, fixedUnshippedText1_index0)); + test.FixedState.AdditionalFiles.Add((UnshippedFileName, """ + C + C.C() -> void + C.NewField -> string + """)); test.FixedState.AdditionalFiles.Add((unshippedTextName2, unshippedText2)); } else if (index == 1) { test.FixedState.AdditionalFiles.Add((UnshippedFileName, unshippedText1)); - test.FixedState.AdditionalFiles.Add((unshippedTextName2, fixedUnshippedText1_index1)); + test.FixedState.AdditionalFiles.Add((unshippedTextName2, "C.NewField -> string")); } else { @@ -2301,120 +2013,99 @@ public async Task TestSimpleMissingMember_Fix_WithoutNullability_MultipleFilesAs } [Fact] - public async Task TestSimpleMissingMember_Fix_WithNullabilityAsync() - { - var source = $$""" + public Task TestSimpleMissingMember_Fix_WithNullabilityAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" #nullable enable {{EnabledModifierCSharp}} class C { {{EnabledModifierCSharp}} string? {|{{AddNewApiId}}:NewField|}; // Newly added field, not in current public API. } - """; - - var shippedText = $@"#nullable enable"; - var unshippedText = @"C -C.C() -> void"; - var fixedUnshippedText = @"C -C.C() -> void -C.NewField -> string?"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); - } + """, $@"#nullable enable", """ + C + C.C() -> void + """, """ + C + C.C() -> void + C.NewField -> string? + """); [Fact] - public async Task TestSimpleMissingMember_Fix_WithNullability2Async() - { - var source = $$""" + public Task TestSimpleMissingMember_Fix_WithNullability2Async() + => VerifyCSharpAdditionalFileFixAsync($$""" #nullable enable {{EnabledModifierCSharp}} class C { {{EnabledModifierCSharp}} string? OldField; {{EnabledModifierCSharp}} string? {|{{AddNewApiId}}:NewField|}; // Newly added field, not in current public API. } - """; - var shippedText = $@"#nullable enable"; - var unshippedText = @"C -C.C() -> void -C.OldField -> string?"; - var fixedUnshippedText = @"C -C.C() -> void -C.NewField -> string? -C.OldField -> string?"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); - } + """, $@"#nullable enable", """ + C + C.C() -> void + C.OldField -> string? + """, """ + C + C.C() -> void + C.NewField -> string? + C.OldField -> string? + """); [Fact] - public async Task TestSimpleMissingMember_Fix_WithNullability3Async() - { - var source = $$""" + public Task TestSimpleMissingMember_Fix_WithNullability3Async() + => VerifyCSharpAsync($$""" #nullable enable {{EnabledModifierCSharp}} class C { {{EnabledModifierCSharp}} string? OldField; {{EnabledModifierCSharp}} string? NewField; } - """; - var shippedText = $@"#nullable enable -C -C.C() -> void -C.NewField -> string? -C.OldField -> string?"; - - var unshippedText = ""; - - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + """, $""" + #nullable enable + C + C.C() -> void + C.NewField -> string? + C.OldField -> string? + """, ""); [Fact] - public async Task TestAddAndRemoveMembers_CSharp_Fix_WithRemovedNullabilityAsync() - { - var source = $$""" + public Task TestAddAndRemoveMembers_CSharp_Fix_WithRemovedNullabilityAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} class C { {{EnabledModifierCSharp}} string {|{{ObliviousApiId}}:{|{{AddNewApiId}}:ChangedField|}|}; // oblivious } - """; - var shippedText = $@"#nullable enable"; - var unshippedText = $$""" + """, $@"#nullable enable", $$""" C C.C() -> void {|{{RemoveApiId}}:C.ChangedField -> string?|} - """; - var fixedUnshippedText = @"C -C.C() -> void -~C.ChangedField -> string"; - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); - } + """, """ + C + C.C() -> void + ~C.ChangedField -> string + """); [Fact, WorkItem(3793, "https://github.com/dotnet/roslyn-analyzers/issues/3793")] - public async Task ObliviousApiDiagnosticInGeneratedFileStillWarnAsync() - { - // We complain about oblivious APIs in generated files too (no special treatment) - var source = $$""" + public Task ObliviousApiDiagnosticInGeneratedFileStillWarnAsync() + => VerifyCSharpAsync($$""" // {{EnabledModifierCSharp}} class C { {{EnabledModifierCSharp}} string ObliviousField; } - """; - var shippedText = "#nullable enable"; - var unshippedText = @"C -C.C() -> void -C.ObliviousField -> string"; - await VerifyCSharpAsync(source, shippedText, unshippedText, + """, "#nullable enable", """ + C + C.C() -> void + C.ObliviousField -> string + """, // /0/Test0.cs(5,19): warning RS0036: Symbol 'C.ObliviousField -> string' is missing nullability annotations in the declared API. GetCSharpResultAt(5, 13 + EnabledModifierCSharp.Length, AnnotateApiRule, "C.ObliviousField -> string"), // /0/Test0.cs(5,19): warning RS0041: Symbol 'ObliviousField' uses some oblivious reference types. GetCSharpResultAt(5, 13 + EnabledModifierCSharp.Length, ObliviousApiRule, "ObliviousField") ); - } [Fact, WorkItem(3672, "https://github.com/dotnet/roslyn-analyzers/issues/3672")] - public async Task TypeArgumentRefersToTypeParameter_OnMethodAsync() - { - var source = $$""" + public Task TypeArgumentRefersToTypeParameter_OnMethodAsync() + => VerifyCSharpAsync($$""" #nullable enable {{EnabledModifierCSharp}} static class C @@ -2424,40 +2115,30 @@ public async Task TypeArgumentRefersToTypeParameter_OnMethodAsync() { } } - """; - var shippedText = "#nullable enable"; - var unshippedText = @""; - await VerifyCSharpAsync(source, shippedText, unshippedText, + """, "#nullable enable", @"", // /0/Test0.cs(3,21): warning RS0016: Symbol 'C' is not part of the declared API. GetCSharpResultAt(3, 15 + EnabledModifierCSharp.Length, DeclareNewApiRule, "C"), // /0/Test0.cs(5,24): warning RS0016: Symbol 'static C.M() -> void' is not part of the declared API. GetCSharpResultAt(5, 18 + EnabledModifierCSharp.Length, DeclareNewApiRule, "static C.M() -> void") ); - } [Fact, WorkItem(3672, "https://github.com/dotnet/roslyn-analyzers/issues/3672")] - public async Task TypeArgumentRefersToTypeParameter_OnTypeAsync() - { - var source = $$""" + public Task TypeArgumentRefersToTypeParameter_OnTypeAsync() + => VerifyCSharpAsync($$""" #nullable enable {{EnabledModifierCSharp}} static class C where T : System.IComparable { } - """; - var shippedText = "#nullable enable"; - var unshippedText = @""; - await VerifyCSharpAsync(source, shippedText, unshippedText, + """, "#nullable enable", @"", // /0/Test0.cs(3,21): warning RS0016: Symbol 'C' is not part of the declared API. GetCSharpResultAt(3, 15 + EnabledModifierCSharp.Length, DeclareNewApiRule, "C") ); - } [Fact, WorkItem(3672, "https://github.com/dotnet/roslyn-analyzers/issues/3672")] - public async Task TypeArgumentRefersToTypeParameter_OnType_SecondTypeArgumentAsync() - { - var source = $$""" + public Task TypeArgumentRefersToTypeParameter_OnType_SecondTypeArgumentAsync() + => VerifyCSharpAsync($$""" #nullable enable {{EnabledModifierCSharp}} static class C @@ -2469,21 +2150,16 @@ public async Task TypeArgumentRefersToTypeParameter_OnType_SecondTypeArgumentAsy > { } - """; - var shippedText = "#nullable enable"; - var unshippedText = @""; - await VerifyCSharpAsync(source, shippedText, unshippedText, + """, "#nullable enable", @"", // /0/Test0.cs(3,21): warning RS0016: Symbol '~C' is not part of the declared API. GetCSharpResultAt(3, 15 + EnabledModifierCSharp.Length, DeclareNewApiRule, "~C"), // /0/Test0.cs(3,21): warning RS0041: Symbol 'C' uses some oblivious reference types. GetCSharpResultAt(3, 15 + EnabledModifierCSharp.Length, ObliviousApiRule, "C") ); - } [Fact, WorkItem(3672, "https://github.com/dotnet/roslyn-analyzers/issues/3672")] - public async Task TypeArgumentRefersToTypeParameter_OnType_ObliviousReferenceAsync() - { - var source = $$""" + public Task TypeArgumentRefersToTypeParameter_OnType_ObliviousReferenceAsync() + => VerifyCSharpAsync($$""" #nullable enable {{EnabledModifierCSharp}} static class C @@ -2495,85 +2171,64 @@ public async Task TypeArgumentRefersToTypeParameter_OnType_ObliviousReferenceAsy { } - """; - var shippedText = "#nullable enable"; - var unshippedText = @""; - await VerifyCSharpAsync(source, shippedText, unshippedText, + """, "#nullable enable", @"", // /0/Test0.cs(3,21): warning RS0016: Symbol '~C' is not part of the declared API. GetCSharpResultAt(3, 15 + EnabledModifierCSharp.Length, DeclareNewApiRule, "~C"), // /0/Test0.cs(3,21): warning RS0041: Symbol 'C' uses some oblivious reference types. GetCSharpResultAt(3, 15 + EnabledModifierCSharp.Length, ObliviousApiRule, "C") ); - } [Fact] public async Task ApiFileShippedWithDuplicateNullableEnableAsync() { - var source = $$""" + var expected = new DiagnosticResult(ApiFilesInvalid) + .WithArguments(DeclarePublicApiAnalyzer.InvalidReasonMisplacedNullableEnable); + await VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { } - """; - - string shippedText = $@" -#nullable enable -#nullable enable -"; + """, $""" - string unshippedText = $@""; + #nullable enable + #nullable enable - var expected = new DiagnosticResult(ApiFilesInvalid) - .WithArguments(DeclarePublicApiAnalyzer.InvalidReasonMisplacedNullableEnable); - await VerifyCSharpAsync(source, shippedText, unshippedText, expected); + """, $@"", expected); } [Fact] public async Task ApiFileUnshippedWithDuplicateNullableEnableAsync() { - var source = $$""" + var expected = new DiagnosticResult(ApiFilesInvalid) + .WithArguments(DeclarePublicApiAnalyzer.InvalidReasonMisplacedNullableEnable); + await VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { } - """; - - string shippedText = $@""; + """, $@"", $""" - string unshippedText = $@" -#nullable enable -#nullable enable -"; + #nullable enable + #nullable enable - var expected = new DiagnosticResult(ApiFilesInvalid) - .WithArguments(DeclarePublicApiAnalyzer.InvalidReasonMisplacedNullableEnable); - await VerifyCSharpAsync(source, shippedText, unshippedText, expected); + """, expected); } [Fact] - public async Task ApiFileShippedWithoutNullableEnable_AvoidUnnecessaryDiagnosticAsync() - { - var source = $$""" + public Task ApiFileShippedWithoutNullableEnable_AvoidUnnecessaryDiagnosticAsync() + => VerifyCSharpAsync($$""" {{EnabledModifierCSharp}} class C { } - """; - - string shippedText = $@"C -C.C() -> void"; - - string unshippedText = $@""; - - // Only oblivious APIs, so no need to warn about lack of '#nullable enable' - await VerifyCSharpAsync(source, shippedText, unshippedText, System.Array.Empty()); - } + """, $""" + C + C.C() -> void + """, $@"", System.Array.Empty()); [Fact] - public async Task TestAddAndRemoveMembers_CSharp_FixAsync() - { - // Unshipped file has a state 'ObsoleteField' entry and a missing 'NewField' entry. - var source = $$""" + public Task TestAddAndRemoveMembers_CSharp_FixAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} class C { {{EnabledModifierCSharp}} int Field; @@ -2583,9 +2238,7 @@ public async Task TestAddAndRemoveMembers_CSharp_FixAsync() {{EnabledModifierCSharp}} int {|{{AddNewApiId}}:NewField|}; } - """; - var shippedText = @""; - var unshippedText = $$""" + """, @"", $$""" C C.ArrowExpressionProperty.get -> int C.C() -> void @@ -2594,40 +2247,29 @@ public async Task TestAddAndRemoveMembers_CSharp_FixAsync() {|{{RemoveApiId}}:C.ObsoleteField -> int|} C.Property.get -> int C.Property.set -> void - """; - var fixedUnshippedText = @"C -C.ArrowExpressionProperty.get -> int -C.C() -> void -C.Field -> int -C.Method() -> void -C.NewField -> int -C.Property.get -> int -C.Property.set -> void"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); - } + """, """ + C + C.ArrowExpressionProperty.get -> int + C.C() -> void + C.Field -> int + C.Method() -> void + C.NewField -> int + C.Property.get -> int + C.Property.set -> void + """); [Fact] - public async Task TestSimpleMissingType_FixAsync() - { - var source = $$""" + public Task TestSimpleMissingType_FixAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} class {|{{AddNewApiId}}:C|} { private C() { } } - """; - - var shippedText = @""; - var unshippedText = @""; - var fixedUnshippedText = @"C"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); - } + """, @"", @"", @"C"); [Fact] - public async Task TestMultipleMissingTypeAndMember_FixAsync() - { - var source = $$""" + public Task TestMultipleMissingTypeAndMember_FixAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} class {|{{AddNewApiId}}:C|} { private C() { } @@ -2635,22 +2277,16 @@ private C() { } } {{EnabledModifierCSharp}} class {|{{AddNewApiId}}:{|{{AddNewApiId}}:C2|}|} { } - """; - - var shippedText = @""; - var unshippedText = @""; - var fixedUnshippedText = @"C -C.Field -> int -C2 -C2.C2() -> void"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); - } + """, @"", @"", """ + C + C.Field -> int + C2 + C2.C2() -> void + """); [Fact] - public async Task TestMultipleMissingTypeAndMember_CaseSensitiveFixAsync() - { - var source = $$""" + public Task TestMultipleMissingTypeAndMember_CaseSensitiveFixAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} class {|{{AddNewApiId}}:C|} { private C() { } @@ -2661,64 +2297,42 @@ private C() { } } {{EnabledModifierCSharp}} class {|{{AddNewApiId}}:{|{{AddNewApiId}}:C2|}|} { } - """; - - var shippedText = @""; - var unshippedText = @""; - var fixedUnshippedText = @"C -C.Field_A -> int -C.Field_b -> int -C.Field_C -> int -C.Field_d -> int -C2 -C2.C2() -> void"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); - } + """, @"", @"", """ + C + C.Field_A -> int + C.Field_b -> int + C.Field_C -> int + C.Field_d -> int + C2 + C2.C2() -> void + """); [Fact] - public async Task TestChangingMethodSignatureForAnUnshippedMethod_FixAsync() - { - var source = $$""" + public Task TestChangingMethodSignatureForAnUnshippedMethod_FixAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} class C { private C() { } {{EnabledModifierCSharp}} void {|{{AddNewApiId}}:Method|}(int p1){ } } - """; - - var shippedText = @"C"; - // previously method had no params, so the fix should remove the previous overload. - var unshippedText = $$"""{|{{RemoveApiId}}:C.Method() -> void|}"""; - var fixedUnshippedText = @"C.Method(int p1) -> void"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); - } + """, @"C", $$"""{|{{RemoveApiId}}:C.Method() -> void|}""", @"C.Method(int p1) -> void"); [Fact] - public async Task TestChangingMethodSignatureForAnUnshippedMethod_Fix_WithNullabilityAsync() - { - var source = $$""" + public Task TestChangingMethodSignatureForAnUnshippedMethod_Fix_WithNullabilityAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} class C { private C() { } {{EnabledModifierCSharp}} void {|{{AddNewApiId}}:Method|}(object? p1){ } } - """; - - var shippedText = $@"#nullable enable -C"; - // previously method had no params, so the fix should remove the previous overload. - var unshippedText = $$"""{|{{RemoveApiId}}:C.Method(string p1) -> void|}"""; - var fixedUnshippedText = @"C.Method(object? p1) -> void"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); - } + """, $""" + #nullable enable + C + """, $$"""{|{{RemoveApiId}}:C.Method(string p1) -> void|}""", @"C.Method(object? p1) -> void"); [Fact] - public async Task TestChangingMethodSignatureForAnUnshippedMethodWithShippedOverloads_FixAsync() - { - var source = $$""" + public Task TestChangingMethodSignatureForAnUnshippedMethodWithShippedOverloads_FixAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} class C { private C() { } @@ -2726,33 +2340,15 @@ private C() { } {{EnabledModifierCSharp}} void Method(int p1, int p2){ } {{EnabledModifierCSharp}} void {|{{AddNewApiId}}:Method|}(char p1){ } } - """; - - var shippedText = @"C -C.Method(int p1) -> void -C.Method(int p1, int p2) -> void"; - // previously method had no params, so the fix should remove the previous overload. - var unshippedText = $$"""{|{{RemoveApiId}}:C.Method() -> void|}"""; - var fixedUnshippedText = @"C.Method(char p1) -> void"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); - } + """, """ + C + C.Method(int p1) -> void + C.Method(int p1, int p2) -> void + """, $$"""{|{{RemoveApiId}}:C.Method() -> void|}""", @"C.Method(char p1) -> void"); [Fact] public async Task TestAddingNewPublicOverload_FixAsync() { - var source = $$""" - public class C - { - private C() { } - {{EnabledModifierCSharp}} void {|{{AddNewApiId}}:Method|}(){ } - {{DisabledModifierCSharp}} void Method(int p1){ } - {{DisabledModifierCSharp}} void Method(int p1, int p2){ } - {{EnabledModifierCSharp}} void Method(char p1){ } - } - """; - - var shippedText = @""; var unshippedText = IsInternalTest ? """ C.Method(char p1) -> void @@ -2772,13 +2368,21 @@ private C() { } C.Method(char p1) -> void """; - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); + await VerifyCSharpAdditionalFileFixAsync($$""" + public class C + { + private C() { } + {{EnabledModifierCSharp}} void {|{{AddNewApiId}}:Method|}(){ } + {{DisabledModifierCSharp}} void Method(int p1){ } + {{DisabledModifierCSharp}} void Method(int p1, int p2){ } + {{EnabledModifierCSharp}} void Method(char p1){ } + } + """, @"", unshippedText, fixedUnshippedText); } [Fact] - public async Task TestMissingTypeAndMemberAndNestedMembers_FixAsync() - { - var source = $$""" + public Task TestMissingTypeAndMemberAndNestedMembers_FixAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} class {|{{AddNewApiId}}:C|} { private C() { } @@ -2791,24 +2395,20 @@ private C() { } } {{EnabledModifierCSharp}} class {|{{AddNewApiId}}:{|{{AddNewApiId}}:C2|}|} { } - """; - - var shippedText = @"C.CC -C.CC.CC() -> void"; - var unshippedText = @""; - var fixedUnshippedText = @"C -C.CC.Field -> int -C.Field -> int -C2 -C2.C2() -> void"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); - } + """, """ + C.CC + C.CC.CC() -> void + """, @"", """ + C + C.CC.Field -> int + C.Field -> int + C2 + C2.C2() -> void + """); [Fact] - public async Task TestMissingNestedGenericMembersAndStaleMembers_FixAsync() - { - var source = $$""" + public Task TestMissingNestedGenericMembersAndStaleMembers_FixAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} class {|{{AddNewApiId}}:C|} { private C() { } @@ -2829,10 +2429,7 @@ private C() { } } {{EnabledModifierCSharp}} class {|{{AddNewApiId}}:{|{{AddNewApiId}}:C2|}|} { } - """; - - var shippedText = @""; - var unshippedText = $$""" + """, @"", $$""" C.C3 C.C3.C3() -> void C.C3.C4 @@ -2841,8 +2438,7 @@ private C() { } C.CC.CC() -> void {|{{RemoveApiId}}:C.Field2 -> C.C3.C4|} {|{{RemoveApiId}}:C.Method(C.C3.C4 p1) -> C.C3.C4|} - """; - var fixedUnshippedText = """ + """, """ C C.C3 C.C3.C3() -> void @@ -2855,15 +2451,11 @@ private C() { } C.Field -> C.CC C2 C2.C2() -> void - """; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); - } + """); [Fact] - public async Task TestWithExistingUnshippedNestedMembers_FixAsync() - { - var source = $$""" + public Task TestWithExistingUnshippedNestedMembers_FixAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} class {|{{AddNewApiId}}:C|} { private C() { } @@ -2876,27 +2468,23 @@ private C() { } } {{EnabledModifierCSharp}} class {|{{AddNewApiId}}:{|{{AddNewApiId}}:C2|}|} { } - """; - - var shippedText = @""; - var unshippedText = @"C.CC -C.CC.CC() -> void -C.CC.Field -> int"; - var fixedUnshippedText = @"C -C.CC -C.CC.CC() -> void -C.CC.Field -> int -C.Field -> int -C2 -C2.C2() -> void"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); - } + """, @"", """ + C.CC + C.CC.CC() -> void + C.CC.Field -> int + """, """ + C + C.CC + C.CC.CC() -> void + C.CC.Field -> int + C.Field -> int + C2 + C2.C2() -> void + """); [Fact] - public async Task TestWithExistingUnshippedNestedGenericMembers_FixAsync() - { - var source = $$""" + public Task TestWithExistingUnshippedNestedGenericMembers_FixAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} class C { private C() { } @@ -2911,28 +2499,24 @@ private CC() { } {{EnabledModifierCSharp}} int Field; } } - """; - - var shippedText = @""; - var unshippedText = @"C -C.CC -C.CC.Field -> int -C.CC -C.CC.Field -> int"; - var fixedUnshippedText = @"C -C.CC -C.CC.CC() -> void -C.CC.Field -> int -C.CC -C.CC.Field -> int"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); - } + """, @"", """ + C + C.CC + C.CC.Field -> int + C.CC + C.CC.Field -> int + """, """ + C + C.CC + C.CC.CC() -> void + C.CC.Field -> int + C.CC + C.CC.Field -> int + """); [Fact] - public async Task TestWithExistingShippedNestedMembers_FixAsync() - { - var source = $$""" + public Task TestWithExistingShippedNestedMembers_FixAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} class {|{{AddNewApiId}}:C|} { private C() { } @@ -2945,24 +2529,20 @@ private C() { } } {{EnabledModifierCSharp}} class {|{{AddNewApiId}}:{|{{AddNewApiId}}:C2|}|} { } - """; - - var shippedText = @"C.CC -C.CC.CC() -> void -C.CC.Field -> int"; - var unshippedText = @""; - var fixedUnshippedText = @"C -C.Field -> int -C2 -C2.C2() -> void"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); - } + """, """ + C.CC + C.CC.CC() -> void + C.CC.Field -> int + """, @"", """ + C + C.Field -> int + C2 + C2.C2() -> void + """); [Fact] - public async Task TestOnlyRemoveStaleSiblingEntries_FixAsync() - { - var source = $$""" + public Task TestOnlyRemoveStaleSiblingEntries_FixAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} class {|{{AddNewApiId}}:C|} { private C() { } @@ -2975,16 +2555,12 @@ private C() { } } {{EnabledModifierCSharp}} class {|{{AddNewApiId}}:{|{{AddNewApiId}}:C2|}|} { } - """; - - var shippedText = @""; - var unshippedText = $$""" + """, @"", $$""" C.CC C.CC.CC() -> void {|{{RemoveApiId}}:C.CC.Field -> int|} - """; - var fixedUnshippedText = $$""" + """, $$""" C C.CC C.CC.CC() -> void @@ -2992,10 +2568,7 @@ private C() { } C.Field -> int C2 C2.C2() -> void - """; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); - } + """); [Theory] [InlineData("", "")] @@ -3011,165 +2584,148 @@ public async Task TestPreserveTrailingNewlineAsync(string originalEndOfFile, str {{EnabledModifierCSharp}} int {|{{AddNewApiId}}:NewField|}; // Newly added field, not in current public API. } """; - - var shippedText = @""; - var unshippedText = $@"C -C.C() -> void -C.Property.get -> int{originalEndOfFile}"; - var fixedUnshippedText = $@"C -C.C() -> void -C.NewField -> int -C.Property.get -> int{expectedEndOfFile}"; + var unshippedText = $""" + C + C.C() -> void + C.Property.get -> int{originalEndOfFile} + """; + var fixedUnshippedText = $""" + C + C.C() -> void + C.NewField -> int + C.Property.get -> int{expectedEndOfFile} + """; await VerifyCSharpAdditionalFileFixAsync( source.ReplaceLineEndings("\r\n"), - shippedText, + @"", unshippedText.ReplaceLineEndings("\r\n"), fixedUnshippedText.ReplaceLineEndings("\r\n")); } [Fact] - public async Task MissingType_AAsync() - { - var source = $$""" + public Task MissingType_AAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} class {|{{AddNewApiId}}:{|{{AddNewApiId}}:A|}|} { } {{EnabledModifierCSharp}} class B { } {{EnabledModifierCSharp}} class D { } - """; - - var unshippedText = @"B -B.B() -> void -D -D.D() -> void"; - - var expectedUnshippedText = @"A -A.A() -> void -B -B.B() -> void -D -D.D() -> void"; - await VerifyCSharpAdditionalFileFixAsync(source, shippedApiText: "", oldUnshippedApiText: unshippedText, newUnshippedApiText: expectedUnshippedText); - } + """, shippedApiText: "", oldUnshippedApiText: """ + B + B.B() -> void + D + D.D() -> void + """, newUnshippedApiText: """ + A + A.A() -> void + B + B.B() -> void + D + D.D() -> void + """); [Fact] - public async Task MissingType_CAsync() - { - var source = $$""" + public Task MissingType_CAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} class B { } {{EnabledModifierCSharp}} class {|{{AddNewApiId}}:{|{{AddNewApiId}}:C|}|} { } {{EnabledModifierCSharp}} class D { } - """; - - var unshippedText = @"B -B.B() -> void -D -D.D() -> void"; - - var expectedUnshippedText = @"B -B.B() -> void -C -C.C() -> void -D -D.D() -> void"; - await VerifyCSharpAdditionalFileFixAsync(source, shippedApiText: "", oldUnshippedApiText: unshippedText, newUnshippedApiText: expectedUnshippedText); - } + """, shippedApiText: "", oldUnshippedApiText: """ + B + B.B() -> void + D + D.D() -> void + """, newUnshippedApiText: """ + B + B.B() -> void + C + C.C() -> void + D + D.D() -> void + """); [Fact] - public async Task MissingType_EAsync() - { - var source = $$""" + public Task MissingType_EAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} class B { } {{EnabledModifierCSharp}} class D { } {{EnabledModifierCSharp}} class {|{{AddNewApiId}}:{|{{AddNewApiId}}:E|}|} { } - """; - - var unshippedText = @"B -B.B() -> void -D -D.D() -> void"; - - var expectedUnshippedText = @"B -B.B() -> void -D -D.D() -> void -E -E.E() -> void"; - await VerifyCSharpAdditionalFileFixAsync(source, shippedApiText: "", oldUnshippedApiText: unshippedText, newUnshippedApiText: expectedUnshippedText); - } + """, shippedApiText: "", oldUnshippedApiText: """ + B + B.B() -> void + D + D.D() -> void + """, newUnshippedApiText: """ + B + B.B() -> void + D + D.D() -> void + E + E.E() -> void + """); [Fact] - public async Task MissingType_Unordered_AAsync() - { - var source = $$""" + public Task MissingType_Unordered_AAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} class {|{{AddNewApiId}}:{|{{AddNewApiId}}:A|}|} { } {{EnabledModifierCSharp}} class B { } {{EnabledModifierCSharp}} class D { } - """; - - var unshippedText = @"D -D.D() -> void -B -B.B() -> void"; - - var expectedUnshippedText = @"A -A.A() -> void -D -D.D() -> void -B -B.B() -> void"; - await VerifyCSharpAdditionalFileFixAsync(source, shippedApiText: "", oldUnshippedApiText: unshippedText, newUnshippedApiText: expectedUnshippedText); - } + """, shippedApiText: "", oldUnshippedApiText: """ + D + D.D() -> void + B + B.B() -> void + """, newUnshippedApiText: """ + A + A.A() -> void + D + D.D() -> void + B + B.B() -> void + """); [Fact] - public async Task MissingType_Unordered_CAsync() - { - var source = $$""" + public Task MissingType_Unordered_CAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} class B { } {{EnabledModifierCSharp}} class {|{{AddNewApiId}}:{|{{AddNewApiId}}:C|}|} { } {{EnabledModifierCSharp}} class D { } - """; - - var unshippedText = @"D -D.D() -> void -B -B.B() -> void"; - - var expectedUnshippedText = @"C -C.C() -> void -D -D.D() -> void -B -B.B() -> void"; - await VerifyCSharpAdditionalFileFixAsync(source, shippedApiText: "", oldUnshippedApiText: unshippedText, newUnshippedApiText: expectedUnshippedText); - } + """, shippedApiText: "", oldUnshippedApiText: """ + D + D.D() -> void + B + B.B() -> void + """, newUnshippedApiText: """ + C + C.C() -> void + D + D.D() -> void + B + B.B() -> void + """); [Fact] - public async Task MissingType_Unordered_EAsync() - { - var source = $$""" + public Task MissingType_Unordered_EAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} class B { } {{EnabledModifierCSharp}} class D { } {{EnabledModifierCSharp}} class {|{{AddNewApiId}}:{|{{AddNewApiId}}:E|}|} { } - """; - - var unshippedText = @"D -D.D() -> void -B -B.B() -> void"; - - var expectedUnshippedText = @"D -D.D() -> void -B -B.B() -> void -E -E.E() -> void"; - await VerifyCSharpAdditionalFileFixAsync(source, shippedApiText: "", oldUnshippedApiText: unshippedText, newUnshippedApiText: expectedUnshippedText); - } + """, shippedApiText: "", oldUnshippedApiText: """ + D + D.D() -> void + B + B.B() -> void + """, newUnshippedApiText: """ + D + D.D() -> void + B + B.B() -> void + E + E.E() -> void + """); [Fact, WorkItem(2195, "https://github.com/dotnet/roslyn-analyzers/issues/2195")] - public async Task TestPartialTypeAsync() - { - var source = $$""" + public Task TestPartialTypeAsync() + => VerifyCSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} partial class {|{{AddNewApiId}}:{|{{AddNewApiId}}:C|}|} { } @@ -3177,24 +2733,16 @@ public async Task TestPartialTypeAsync() {{EnabledModifierCSharp}} partial class {|{{AddNewApiId}}:{|{{AddNewApiId}}:C|}|} { } - """; - - var shippedText = @""; - var unshippedText = @""; - var fixedUnshippedText = @"C -C.C() -> void"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); - } + """, @"", @"", """ + C + C.C() -> void + """); [Fact, WorkItem(4133, "https://github.com/dotnet/roslyn-analyzers/issues/4133")] - public async Task Record_ImplicitProperty_FixAsync() - { - var source = $$""" + public Task Record_ImplicitProperty_FixAsync() + => VerifyNet50CSharpAdditionalFileFixAsync($$""" {{EnabledModifierCSharp}} record R(int {|{{AddNewApiId}}:P|}); - """; - - var shippedText = """ + """, """ #nullable enable R.R(R! original) -> void virtual R.$() -> R! @@ -3207,44 +2755,33 @@ override R.ToString() -> string! virtual R.EqualityContract.get -> System.Type! virtual R.Equals(R? other) -> bool virtual R.PrintMembers(System.Text.StringBuilder! builder) -> bool - """; - var unshippedText = """ + """, """ #nullable enable R R.R(int P) -> void R.P.get -> int - """; - var fixedUnshippedText = """ + """, """ #nullable enable R R.P.init -> void R.R(int P) -> void R.P.get -> int - """; - - await VerifyNet50CSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); - } + """); [Fact] [WorkItem(6759, "https://github.com/dotnet/roslyn-analyzers/issues/6759")] - public async Task TestExperimentalApiAsync() - { - var source = $$""" + public Task TestExperimentalApiAsync() + => VerifyNet80CSharpAdditionalFileFixAsync($$""" using System.Diagnostics.CodeAnalysis; [Experimental("ID1")] {{EnabledModifierCSharp}} class {|{{AddNewApiId}}:{|{{AddNewApiId}}:C|}|} { } - """; - - var shippedText = @""; - var unshippedText = @""; - var fixedUnshippedText = @"[ID1]C -[ID1]C.C() -> void"; - - await VerifyNet80CSharpAdditionalFileFixAsync(source, shippedText, unshippedText, fixedUnshippedText); - } + """, @"", @"", """ + [ID1]C + [ID1]C.C() -> void + """); [Theory] [InlineData("")] @@ -3265,8 +2802,10 @@ public async Task TestExperimentalApiWithInvalidArgumentAsync(string invalidArgu var shippedText = @""; var unshippedText = @""; - var fixedUnshippedText = @"[???]C -[???]C.C() -> void"; + var fixedUnshippedText = """ + [???]C + [???]C.C() -> void + """; var test = new CSharpCodeFixTest() { diff --git a/src/RoslynAnalyzers/PublicApiAnalyzers/UnitTests/Microsoft.CodeAnalysis.PublicApiAnalyzers.UnitTests.csproj b/src/RoslynAnalyzers/PublicApiAnalyzers/UnitTests/Microsoft.CodeAnalysis.PublicApiAnalyzers.UnitTests.csproj index 168869c1289fb..f657d8baa5c95 100644 --- a/src/RoslynAnalyzers/PublicApiAnalyzers/UnitTests/Microsoft.CodeAnalysis.PublicApiAnalyzers.UnitTests.csproj +++ b/src/RoslynAnalyzers/PublicApiAnalyzers/UnitTests/Microsoft.CodeAnalysis.PublicApiAnalyzers.UnitTests.csproj @@ -3,15 +3,14 @@ $(NetRoslyn) true - $(MicrosoftCodeAnalysisVersionForTests) - - - - - - + + + + + + diff --git a/src/RoslynAnalyzers/PublicApiAnalyzers/UnitTests/NullableEnablePublicApiAnalyzerTests.cs b/src/RoslynAnalyzers/PublicApiAnalyzers/UnitTests/NullableEnablePublicApiAnalyzerTests.cs index d8b805e7af438..a4eb1c8ab3b59 100644 --- a/src/RoslynAnalyzers/PublicApiAnalyzers/UnitTests/NullableEnablePublicApiAnalyzerTests.cs +++ b/src/RoslynAnalyzers/PublicApiAnalyzers/UnitTests/NullableEnablePublicApiAnalyzerTests.cs @@ -39,10 +39,8 @@ private async Task VerifyCSharpAsync(string source, string shippedApiText, strin await test.RunAsync(); } - private async Task VerifyCSharpAdditionalFileFixAsync(string source, string oldShippedApiText, string oldUnshippedApiText, string newSource, string newShippedApiText, string newUnshippedApiText) - { - await VerifyAdditionalFileFixAsync(source, oldShippedApiText, oldUnshippedApiText, newSource, newShippedApiText, newUnshippedApiText); - } + private Task VerifyCSharpAdditionalFileFixAsync(string source, string oldShippedApiText, string oldUnshippedApiText, string newSource, string newShippedApiText, string newUnshippedApiText) + => VerifyAdditionalFileFixAsync(source, oldShippedApiText, oldUnshippedApiText, newSource, newShippedApiText, newUnshippedApiText); private async Task VerifyAdditionalFileFixAsync(string source, string oldShippedApiText, string oldUnshippedApiText, string newSource, string newShippedApiText, string newUnshippedApiText) { @@ -65,140 +63,115 @@ private async Task VerifyAdditionalFileFixAsync(string source, string oldShipped [Fact] public async Task NullableEnableShippedAPI_NullableMemberAsync() { - var source = @" -#nullable enable -public class C -{ - public string? {|RS0037:Field|}; -} -"; - - var shippedText = @""; - var unshippedText = @"C -C.C() -> void -C.Field -> string"; - - // The source is unchanged, but a new diagnostic appears - var newSource = @" -#nullable enable -public class C -{ - public string? {|RS0036:Field|}; -} -"; - var fixedShippedText = @"#nullable enable -"; + var unshippedText = """ + C + C.C() -> void + C.Field -> string + """; + await VerifyCSharpAdditionalFileFixAsync(""" + #nullable enable + public class C + { + public string? {|RS0037:Field|}; + } + """, @"", unshippedText, """ + #nullable enable + public class C + { + public string? {|RS0036:Field|}; + } + """, """ + #nullable enable - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, newSource, fixedShippedText, newUnshippedApiText: unshippedText); + """, newUnshippedApiText: unshippedText); } [Fact] public async Task NullableEnableShippedAPI_NonNullableMemberAsync() { - var source = @" -#nullable enable -public class C -{ - public string {|RS0037:Field2|}; -} -"; - - var shippedText = @""; - var unshippedText = @"C -C.C() -> void -C.Field2 -> string"; - - // The source is unchanged, but a new diagnostic appears - var newSource = @" -#nullable enable -public class C -{ - public string {|RS0036:Field2|}; -} -"; - - var fixedShippedText = @"#nullable enable -"; + var unshippedText = """ + C + C.C() -> void + C.Field2 -> string + """; + await VerifyCSharpAdditionalFileFixAsync(""" + #nullable enable + public class C + { + public string {|RS0037:Field2|}; + } + """, @"", unshippedText, """ + #nullable enable + public class C + { + public string {|RS0036:Field2|}; + } + """, """ + #nullable enable - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, newSource, fixedShippedText, newUnshippedApiText: unshippedText); + """, newUnshippedApiText: unshippedText); } [Fact] public async Task NullableEnableShippedAPI_NonEmptyFileAsync() { - var source = @" -#nullable enable -public class C -{ - public string? {|RS0037:Field|}; -} -"; - - var shippedText = @"C -C.C() -> void -C.Field -> string"; var unshippedText = @""; - - var newSource = @" -#nullable enable -public class C -{ - public string? {|RS0036:Field|}; -} -"; - - var fixedShippedText = @"#nullable enable -C -C.C() -> void -C.Field -> string"; - - await VerifyCSharpAdditionalFileFixAsync(source, shippedText, unshippedText, newSource, fixedShippedText, newUnshippedApiText: unshippedText); + await VerifyCSharpAdditionalFileFixAsync(""" + #nullable enable + public class C + { + public string? {|RS0037:Field|}; + } + """, """ + C + C.C() -> void + C.Field -> string + """, unshippedText, """ + #nullable enable + public class C + { + public string? {|RS0036:Field|}; + } + """, """ + #nullable enable + C + C.C() -> void + C.Field -> string + """, newUnshippedApiText: unshippedText); } [Fact] - public async Task DoNotWarnIfAlreadyEnabled_ViaUnshippedFileAsync() - { - var source = @" -#nullable enable -public class C -{ - public string? {|RS0036:Field|}; - public string {|RS0036:Field2|}; -} -"; - - var shippedText = @"C -C.C() -> void -C.Field -> string -C.Field2 -> string"; - - var unshippedText = @"#nullable enable"; - - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + public Task DoNotWarnIfAlreadyEnabled_ViaUnshippedFileAsync() + => VerifyCSharpAsync(""" + #nullable enable + public class C + { + public string? {|RS0036:Field|}; + public string {|RS0036:Field2|}; + } + """, """ + C + C.C() -> void + C.Field -> string + C.Field2 -> string + """, @"#nullable enable"); [Fact] - public async Task DoNotWarnIfAlreadyEnabled_ViaShippedFileAsync() - { - var source = @" -#nullable enable -public class C -{ - public string? {|RS0036:Field|}; - public string {|RS0036:Field2|}; -} -"; - - var shippedText = @"#nullable enable -C -C.C() -> void -C.Field -> string -C.Field2 -> string"; - - var unshippedText = @""; - - await VerifyCSharpAsync(source, shippedText, unshippedText); - } + public Task DoNotWarnIfAlreadyEnabled_ViaShippedFileAsync() + => VerifyCSharpAsync(""" + #nullable enable + public class C + { + public string? {|RS0036:Field|}; + public string {|RS0036:Field2|}; + } + """, """ + #nullable enable + C + C.C() -> void + C.Field -> string + C.Field2 -> string + """, @""); #endregion } diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpApplyTraitToClass.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpApplyTraitToClass.cs index a59fdb2194c32..804c39de4dc33 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpApplyTraitToClass.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpApplyTraitToClass.cs @@ -7,6 +7,7 @@ using Analyzer.Utilities; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; +using Microsoft.CodeAnalysis.CSharp.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Diagnostics.Analyzers; diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpAvoidOptSuffixForNullableEnableCodeCodeFixProvider.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpAvoidOptSuffixForNullableEnableCodeCodeFixProvider.cs index 28de224bf2595..2a9a5cc8b8c5e 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpAvoidOptSuffixForNullableEnableCodeCodeFixProvider.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpAvoidOptSuffixForNullableEnableCodeCodeFixProvider.cs @@ -63,8 +63,10 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) } } +#pragma warning disable CS0618 // Type or member is obsolete private static async Task RemoveOptSuffixOnVariableAsync(Document document, ISymbol variableSymbol, string newName, CancellationToken cancellationToken) - => await Renamer.RenameSymbolAsync(document.Project.Solution, variableSymbol, newName, document.Project.Solution.Options, cancellationToken) - .ConfigureAwait(false); + => await Renamer.RenameSymbolAsync( + document.Project.Solution, variableSymbol, newName, document.Project.Solution.Options, cancellationToken).ConfigureAwait(false); +#pragma warning restore CS0618 // Type or member is obsolete } } diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpCreateTestAccessor.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpCreateTestAccessor.cs index 623bd9673dbc6..d680674c23657 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpCreateTestAccessor.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpCreateTestAccessor.cs @@ -6,9 +6,9 @@ using System; using System.Composition; -using Analyzer.Utilities; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; +using Microsoft.CodeAnalysis.CSharp.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Diagnostics.Analyzers; diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpDoNotCapturePrimaryContructorParameters.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpDoNotCapturePrimaryContructorParameters.cs index 090e3667290ed..1a9ced0b54cb5 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpDoNotCapturePrimaryContructorParameters.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpDoNotCapturePrimaryContructorParameters.cs @@ -2,12 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Immutable; using Analyzer.Utilities; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Roslyn.Diagnostics.Analyzers; -using System.Collections.Immutable; namespace Roslyn.Diagnostics.CSharp.Analyzers { diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpDoNotUseDebugAssertForInterpolatedStringsFixer.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpDoNotUseDebugAssertForInterpolatedStringsFixer.cs index 705d65842f9ac..11ac090ca6509 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpDoNotUseDebugAssertForInterpolatedStringsFixer.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpDoNotUseDebugAssertForInterpolatedStringsFixer.cs @@ -14,12 +14,12 @@ using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; +using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Diagnostics.Analyzers; namespace Roslyn.Diagnostics.CSharp.Analyzers { - [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(CSharpDoNotUseDebugAssertForInterpolatedStringsFixer))] - [Shared] + [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(CSharpDoNotUseDebugAssertForInterpolatedStringsFixer)), Shared] [method: ImportingConstructor] [method: Obsolete("This exported object must be obtained through the MEF export provider.", error: true)] public sealed class CSharpDoNotUseDebugAssertForInterpolatedStringsFixer() : CodeFixProvider diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpExposeMemberForTesting.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpExposeMemberForTesting.cs index 82ff4db303fd3..3ad1dc8c1ea77 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpExposeMemberForTesting.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpExposeMemberForTesting.cs @@ -10,6 +10,7 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Diagnostics.Analyzers; diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpImportingConstructorShouldBeObsoleteCodeFixProvider.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpImportingConstructorShouldBeObsoleteCodeFixProvider.cs new file mode 100644 index 0000000000000..2fd8126376480 --- /dev/null +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpImportingConstructorShouldBeObsoleteCodeFixProvider.cs @@ -0,0 +1,33 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Composition; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Shared.Extensions; + +namespace Roslyn.Diagnostics.Analyzers; + +using static CSharpSyntaxTokens; +using static SyntaxFactory; + +[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(CSharpImportingConstructorShouldBeObsoleteCodeFixProvider)), Shared] +[method: ImportingConstructor] +[method: Obsolete("This exported object must be obtained through the MEF export provider.", error: true)] +internal sealed class CSharpImportingConstructorShouldBeObsoleteCodeFixProvider() : + AbstractImportingConstructorShouldBeObsoleteCodeFixProvider +{ + protected override bool IsOnPrimaryConstructorTypeDeclaration(SyntaxNode attributeName, [NotNullWhen(true)] out SyntaxNode? typeDeclaration) + { + typeDeclaration = attributeName.GetAncestor()?.Parent; + return typeDeclaration is TypeDeclarationSyntax { ParameterList: not null }; + } + + protected override SyntaxNode AddMethodTarget(SyntaxNode attributeList) + => ((AttributeListSyntax)attributeList).WithTarget(AttributeTargetSpecifier(MethodKeyword)); +} diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpRunIterations.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpRunIterations.cs index f242b5129ab93..9231e16355540 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpRunIterations.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/CSharpRunIterations.cs @@ -7,6 +7,7 @@ using Analyzer.Utilities; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; +using Microsoft.CodeAnalysis.CSharp.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Diagnostics.Analyzers; diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/NumberCommentsRefactoring.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/NumberCommentsRefactoring.cs index 0d37add0a4aca..169118f39c4c5 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/NumberCommentsRefactoring.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/NumberCommentsRefactoring.cs @@ -14,6 +14,7 @@ using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; @@ -63,14 +64,22 @@ private static async Task FixCommentsAsync(Document document, LiteralE static string? getPrefix(string text) { - if (text.StartsWith("@\"", StringComparison.OrdinalIgnoreCase)) + if (text.StartsWith(""" + @" + """, StringComparison.OrdinalIgnoreCase)) { - return "@\""; + return """ + @" + """; } - if (text.StartsWith("\"", StringComparison.OrdinalIgnoreCase)) + if (text.StartsWith(""" + " + """, StringComparison.OrdinalIgnoreCase)) { - return "\""; + return """ + " + """; } return null; diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/Roslyn.Diagnostics.CSharp.Analyzers.csproj b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/Roslyn.Diagnostics.CSharp.Analyzers.csproj index aa3e2777ba3dd..061ad2a47ac2a 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/Roslyn.Diagnostics.CSharp.Analyzers.csproj +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/Roslyn.Diagnostics.CSharp.Analyzers.csproj @@ -2,7 +2,7 @@ netstandard2.0 - $(MicrosoftCodeAnalysisForRoslynDiagnosticsAnalyzersVersion) + Microsoft.CodeAnalysis.CSharp @@ -10,11 +10,25 @@ - - - - - - - + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/AbstractApplyTraitToClass`1.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/AbstractApplyTraitToClass`1.cs index 7504d7d45c2ee..43e41122137b8 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/AbstractApplyTraitToClass`1.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/AbstractApplyTraitToClass`1.cs @@ -61,7 +61,7 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte CodeAction.Create( RoslynDiagnosticsAnalyzersResources.ApplyTraitToContainingType, cancellationToken => ApplyTraitToClassAsync(state, cancellationToken), - nameof(AbstractApplyTraitToClass))); + nameof(AbstractApplyTraitToClass<>))); } private async Task ApplyTraitToClassAsync(State state, CancellationToken cancellationToken) diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/AbstractCreateTestAccessor`1.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/AbstractCreateTestAccessor`1.cs index 54dcd6456817b..4ac28004fcd50 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/AbstractCreateTestAccessor`1.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/AbstractCreateTestAccessor`1.cs @@ -49,7 +49,7 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte CodeAction.Create( RoslynDiagnosticsAnalyzersResources.CreateTestAccessorMessage, cancellationToken => CreateTestAccessorAsync(context.Document, location.SourceSpan, cancellationToken), - nameof(AbstractCreateTestAccessor))); + nameof(AbstractCreateTestAccessor<>))); } private static bool IsClassOrStruct(ITypeSymbol typeSymbol) diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/AbstractDoNotCopyValue.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/AbstractDoNotCopyValue.cs index 9d23563a735b8..61cff0c849701 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/AbstractDoNotCopyValue.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/AbstractDoNotCopyValue.cs @@ -1439,7 +1439,7 @@ when SymbolEqualityComparer.Default.Equals(taskType, Cache.ValueTaskT) || Symbol case OperationKind.Throw: return RefKind.None; - case OperationKindEx.CollectionExpression: + case OperationKind.CollectionExpression: return RefKind.None; default: diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/AbstractRunIterations`1.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/AbstractRunIterations`1.cs index 6f8e7deb2177c..74c81a2f36669 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/AbstractRunIterations`1.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/AbstractRunIterations`1.cs @@ -13,6 +13,7 @@ using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; +using Roslyn.Utilities; namespace Roslyn.Diagnostics.Analyzers { diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/DoNotMixAttributesFromDifferentVersionsOfMEF.Fixer.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/DoNotMixAttributesFromDifferentVersionsOfMEF.Fixer.cs index 86f697fd00ec9..3cb4590ffc788 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/DoNotMixAttributesFromDifferentVersionsOfMEF.Fixer.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/DoNotMixAttributesFromDifferentVersionsOfMEF.Fixer.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Microsoft.CodeAnalysis.CodeFixes; using System.Collections.Immutable; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CodeFixes; namespace Roslyn.Diagnostics.Analyzers { diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/ExportedPartsShouldHaveImportingConstructorCodeFixProvider.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/ExportedPartsShouldHaveImportingConstructorCodeFixProvider.cs index 294c725da11c4..b642602f35feb 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/ExportedPartsShouldHaveImportingConstructorCodeFixProvider.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/ExportedPartsShouldHaveImportingConstructorCodeFixProvider.cs @@ -16,6 +16,7 @@ using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editing; +using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Roslyn.Diagnostics.Analyzers @@ -183,7 +184,7 @@ private static async Task AddImportingConstructorAttributeAsync(Docume { if (attributeClass.Name == nameof(ExportAttribute)) { - exportAttributeSymbol = attributeClass; + exportAttributeSymbol = (INamedTypeSymbol)attributeClass; break; } } diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/ImportingConstructorShouldBeObsoleteCodeFixProvider.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/ImportingConstructorShouldBeObsoleteCodeFixProvider.cs index dcd7231a565b5..d4a449d92b89d 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/ImportingConstructorShouldBeObsoleteCodeFixProvider.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/ImportingConstructorShouldBeObsoleteCodeFixProvider.cs @@ -2,11 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable warnings - using System; using System.Collections.Immutable; -using System.Composition; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -16,225 +14,224 @@ using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editing; +using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; -namespace Roslyn.Diagnostics.Analyzers -{ - [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = nameof(ImportingConstructorShouldBeObsoleteCodeFixProvider))] - [Shared] - [method: ImportingConstructor] - [method: Obsolete("This exported object must be obtained through the MEF export provider.", error: true)] - public class ImportingConstructorShouldBeObsoleteCodeFixProvider() : CodeFixProvider - { - public override ImmutableArray FixableDiagnosticIds { get; } = ImmutableArray.Create(ImportingConstructorShouldBeObsolete.Rule.Id); +namespace Roslyn.Diagnostics.Analyzers; - public override FixAllProvider GetFixAllProvider() - => WellKnownFixAllProviders.BatchFixer; +public abstract class AbstractImportingConstructorShouldBeObsoleteCodeFixProvider() : CodeFixProvider +{ + public override ImmutableArray FixableDiagnosticIds { get; } = [ImportingConstructorShouldBeObsolete.Rule.Id]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) - { - foreach (var diagnostic in context.Diagnostics) - { - if (!diagnostic.Properties.TryGetValue(nameof(ImportingConstructorShouldBeObsolete.Scenario), out var scenario)) - { - continue; - } - - string title; - Func> createChangedDocument; - switch (scenario) - { - case ImportingConstructorShouldBeObsolete.Scenario.MissingAttribute: - title = RoslynDiagnosticsAnalyzersResources.ImportingConstructorShouldBeObsoleteCodeFix_MissingAttribute; - createChangedDocument = cancellationToken => AddObsoleteAttributeAsync(context.Document, diagnostic.Location.SourceSpan, cancellationToken); - break; - - case ImportingConstructorShouldBeObsolete.Scenario.MissingDescription: - title = RoslynDiagnosticsAnalyzersResources.ImportingConstructorShouldBeObsoleteCodeFix_MissingDescription; - createChangedDocument = cancellationToken => AddDescriptionAndErrorAsync(context.Document, diagnostic.Location.SourceSpan, cancellationToken); - break; - - case ImportingConstructorShouldBeObsolete.Scenario.IncorrectDescription: - title = RoslynDiagnosticsAnalyzersResources.ImportingConstructorShouldBeObsoleteCodeFix_IncorrectDescription; - createChangedDocument = cancellationToken => UpdateDescriptionAsync(context.Document, diagnostic.Location.SourceSpan, cancellationToken); - break; - - case ImportingConstructorShouldBeObsolete.Scenario.MissingError: - title = RoslynDiagnosticsAnalyzersResources.ImportingConstructorShouldBeObsoleteCodeFix_MissingError; - createChangedDocument = cancellationToken => AddErrorAsync(context.Document, diagnostic.Location.SourceSpan, cancellationToken); - break; - - case ImportingConstructorShouldBeObsolete.Scenario.ErrorSetToFalse: - title = RoslynDiagnosticsAnalyzersResources.ImportingConstructorShouldBeObsoleteCodeFix_ErrorSetToFalse; - createChangedDocument = cancellationToken => SetErrorToTrueAsync(context.Document, diagnostic.Location.SourceSpan, cancellationToken); - break; - - default: - continue; - } - - context.RegisterCodeFix( - CodeAction.Create( - title, - createChangedDocument, - equivalenceKey: scenario), - diagnostic); - } + protected abstract bool IsOnPrimaryConstructorTypeDeclaration(SyntaxNode attributeName, [NotNullWhen(true)] out SyntaxNode? typeDeclaration); + protected abstract SyntaxNode AddMethodTarget(SyntaxNode attributeList); - return Task.CompletedTask; - } + public override FixAllProvider GetFixAllProvider() + => WellKnownFixAllProviders.BatchFixer; - private static async Task AddObsoleteAttributeAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) + public override Task RegisterCodeFixesAsync(CodeFixContext context) + { + foreach (var diagnostic in context.Diagnostics) { - var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); - var obsoleteAttributeSymbol = semanticModel.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemObsoleteAttribute); - if (obsoleteAttributeSymbol is null) + if (!diagnostic.Properties.TryGetValue(nameof(ImportingConstructorShouldBeObsolete.Scenario), out var scenario)) { - return document; + continue; } - var constructor = root.FindNode(sourceSpan, getInnermostNodeForTie: true); - - var generator = SyntaxGenerator.GetGenerator(document); - - var declaration = generator.TryGetContainingDeclaration(constructor, DeclarationKind.Constructor); - if (declaration is null) + string title; + Func> createChangedDocument; + switch (scenario) { - return document; + case ImportingConstructorShouldBeObsolete.Scenario.MissingAttribute: + title = RoslynDiagnosticsAnalyzersResources.ImportingConstructorShouldBeObsoleteCodeFix_MissingAttribute; + createChangedDocument = cancellationToken => AddObsoleteAttributeAsync(context.Document, diagnostic.Location.SourceSpan, cancellationToken); + break; + + case ImportingConstructorShouldBeObsolete.Scenario.MissingDescription: + title = RoslynDiagnosticsAnalyzersResources.ImportingConstructorShouldBeObsoleteCodeFix_MissingDescription; + createChangedDocument = cancellationToken => AddDescriptionAndErrorAsync(context.Document, diagnostic.Location.SourceSpan, cancellationToken); + break; + + case ImportingConstructorShouldBeObsolete.Scenario.IncorrectDescription: + title = RoslynDiagnosticsAnalyzersResources.ImportingConstructorShouldBeObsoleteCodeFix_IncorrectDescription; + createChangedDocument = cancellationToken => UpdateDescriptionAsync(context.Document, diagnostic.Location.SourceSpan, cancellationToken); + break; + + case ImportingConstructorShouldBeObsolete.Scenario.MissingError: + title = RoslynDiagnosticsAnalyzersResources.ImportingConstructorShouldBeObsoleteCodeFix_MissingError; + createChangedDocument = cancellationToken => AddErrorAsync(context.Document, diagnostic.Location.SourceSpan, cancellationToken); + break; + + case ImportingConstructorShouldBeObsolete.Scenario.ErrorSetToFalse: + title = RoslynDiagnosticsAnalyzersResources.ImportingConstructorShouldBeObsoleteCodeFix_ErrorSetToFalse; + createChangedDocument = cancellationToken => SetErrorToTrueAsync(context.Document, diagnostic.Location.SourceSpan, cancellationToken); + break; + + default: + continue; } - var obsoleteAttribute = generator.Attribute( - generator.TypeExpression(obsoleteAttributeSymbol).WithAddImportsAnnotation(), - new[] - { - GenerateDescriptionArgument(generator, semanticModel), - GenerateErrorArgument(generator, allowNamedArgument: document.Project.Language == LanguageNames.CSharp), - }); - - var newDeclaration = generator.AddAttributes(declaration, obsoleteAttribute); - return document.WithSyntaxRoot(root.ReplaceNode(declaration, newDeclaration)); + context.RegisterCodeFix( + CodeAction.Create( + title, + createChangedDocument, + equivalenceKey: scenario), + diagnostic); } - private static async Task AddDescriptionAndErrorAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) - { - var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); + return Task.CompletedTask; + } - var obsoleteAttributeApplication = root.FindNode(sourceSpan, getInnermostNodeForTie: true); + private async Task AddObsoleteAttributeAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) + { + var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); + var obsoleteAttributeSymbol = semanticModel.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemObsoleteAttribute); + if (obsoleteAttributeSymbol is null) + return document; + + var attributeName = root.FindNode(sourceSpan, getInnermostNodeForTie: true); + + var generator = SyntaxGenerator.GetGenerator(document); + + var isPrimaryConstructorTypeDeclaration = this.IsOnPrimaryConstructorTypeDeclaration(attributeName, out var typeDeclaration); + var declaration = isPrimaryConstructorTypeDeclaration + ? typeDeclaration + : generator.TryGetContainingDeclaration(attributeName, DeclarationKind.Constructor); + if (declaration is null) + return document; + + var obsoleteAttributeList = generator.Attribute( + generator.TypeExpression(obsoleteAttributeSymbol).WithAddImportsAnnotation(), + [ + GenerateDescriptionArgument(generator, semanticModel), + GenerateErrorArgument(generator, allowNamedArgument: document.Project.Language == LanguageNames.CSharp), + ]); + + obsoleteAttributeList = isPrimaryConstructorTypeDeclaration ? this.AddMethodTarget(obsoleteAttributeList) : obsoleteAttributeList; + + var newDeclaration = generator.AddAttributes(declaration, obsoleteAttributeList); + return document.WithSyntaxRoot(root.ReplaceNode(declaration, newDeclaration)); + } - var generator = SyntaxGenerator.GetGenerator(document); + private static async Task AddDescriptionAndErrorAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) + { + var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); - var declaration = generator.TryGetContainingDeclaration(obsoleteAttributeApplication, DeclarationKind.Attribute); - if (declaration is null) - { - return document; - } + var obsoleteAttributeApplication = root.FindNode(sourceSpan, getInnermostNodeForTie: true); - var descriptionArgument = GenerateDescriptionArgument(generator, semanticModel); - var errorArgument = GenerateErrorArgument(generator, allowNamedArgument: document.Project.Language == LanguageNames.CSharp); - var newDeclaration = generator.AddAttributeArguments(declaration, new[] { descriptionArgument, errorArgument }); - return document.WithSyntaxRoot(root.ReplaceNode(declaration, newDeclaration)); - } + var generator = SyntaxGenerator.GetGenerator(document); - private static async Task UpdateDescriptionAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) + var declaration = generator.TryGetContainingDeclaration(obsoleteAttributeApplication, DeclarationKind.Attribute); + if (declaration is null) { - var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); + return document; + } - var obsoleteAttributeApplication = root.FindNode(sourceSpan, getInnermostNodeForTie: true); + var descriptionArgument = GenerateDescriptionArgument(generator, semanticModel); + var errorArgument = GenerateErrorArgument(generator, allowNamedArgument: document.Project.Language == LanguageNames.CSharp); + var newDeclaration = generator.AddAttributeArguments(declaration, [descriptionArgument, errorArgument]); + return document.WithSyntaxRoot(root.ReplaceNode(declaration, newDeclaration)); + } - var generator = SyntaxGenerator.GetGenerator(document); + private static async Task UpdateDescriptionAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) + { + var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); - var declaration = generator.TryGetContainingDeclaration(obsoleteAttributeApplication, DeclarationKind.Attribute); - if (declaration is null) - { - return document; - } + var obsoleteAttributeApplication = root.FindNode(sourceSpan, getInnermostNodeForTie: true); - var argumentToReplace = generator.GetAttributeArguments(declaration).ElementAtOrDefault(0); - if (argumentToReplace is null) - { - return document; - } + var generator = SyntaxGenerator.GetGenerator(document); - var descriptionArgument = GenerateDescriptionArgument(generator, semanticModel); - return document.WithSyntaxRoot(root.ReplaceNode(argumentToReplace, descriptionArgument)); + var declaration = generator.TryGetContainingDeclaration(obsoleteAttributeApplication, DeclarationKind.Attribute); + if (declaration is null) + { + return document; } - private static async Task AddErrorAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) + var argumentToReplace = generator.GetAttributeArguments(declaration).ElementAtOrDefault(0); + if (argumentToReplace is null) { - var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + return document; + } - var obsoleteAttributeApplication = root.FindNode(sourceSpan, getInnermostNodeForTie: true); + var descriptionArgument = GenerateDescriptionArgument(generator, semanticModel); + return document.WithSyntaxRoot(root.ReplaceNode(argumentToReplace, descriptionArgument)); + } - var generator = SyntaxGenerator.GetGenerator(document); + private static async Task AddErrorAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) + { + var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - var declaration = generator.TryGetContainingDeclaration(obsoleteAttributeApplication, DeclarationKind.Attribute); - if (declaration is null) - { - return document; - } + var obsoleteAttributeApplication = root.FindNode(sourceSpan, getInnermostNodeForTie: true); - var errorArgument = GenerateErrorArgument(generator, allowNamedArgument: document.Project.Language == LanguageNames.CSharp); - var newDeclaration = generator.AddAttributeArguments(declaration, new[] { errorArgument }); - return document.WithSyntaxRoot(root.ReplaceNode(declaration, newDeclaration)); - } + var generator = SyntaxGenerator.GetGenerator(document); - private static async Task SetErrorToTrueAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) + var declaration = generator.TryGetContainingDeclaration(obsoleteAttributeApplication, DeclarationKind.Attribute); + if (declaration is null) { - var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + return document; + } - var obsoleteAttributeApplication = root.FindNode(sourceSpan, getInnermostNodeForTie: true); + var errorArgument = GenerateErrorArgument(generator, allowNamedArgument: document.Project.Language == LanguageNames.CSharp); + var newDeclaration = generator.AddAttributeArguments(declaration, [errorArgument]); + return document.WithSyntaxRoot(root.ReplaceNode(declaration, newDeclaration)); + } - var generator = SyntaxGenerator.GetGenerator(document); + private static async Task SetErrorToTrueAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) + { + var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - var declaration = generator.TryGetContainingDeclaration(obsoleteAttributeApplication, DeclarationKind.Attribute); - if (declaration is null) - { - return document; - } + var obsoleteAttributeApplication = root.FindNode(sourceSpan, getInnermostNodeForTie: true); - var argumentToReplace = generator.GetAttributeArguments(declaration).ElementAtOrDefault(1); - if (argumentToReplace is null) - { - return document; - } + var generator = SyntaxGenerator.GetGenerator(document); - var errorArgument = GenerateErrorArgument(generator, allowNamedArgument: document.Project.Language == LanguageNames.CSharp); - return document.WithSyntaxRoot(root.ReplaceNode(argumentToReplace, errorArgument)); + var declaration = generator.TryGetContainingDeclaration(obsoleteAttributeApplication, DeclarationKind.Attribute); + if (declaration is null) + { + return document; } - private static SyntaxNode GenerateDescriptionArgument(SyntaxGenerator generator, SemanticModel semanticModel) + var argumentToReplace = generator.GetAttributeArguments(declaration).ElementAtOrDefault(1); + if (argumentToReplace is null) { - SyntaxNode attributeArgument; - if (semanticModel.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftCodeAnalysisHostMefMefConstruction, out var mefConstructionType) && - mefConstructionType.GetMembers("ImportingConstructorMessage").OfType().Any()) - { - attributeArgument = generator.MemberAccessExpression( - generator.TypeExpression(mefConstructionType).WithAddImportsAnnotation(), - generator.IdentifierName("ImportingConstructorMessage")); - } - else - { - attributeArgument = generator.LiteralExpression("This exported object must be obtained through the MEF export provider."); - } + return document; + } + + var errorArgument = GenerateErrorArgument(generator, allowNamedArgument: document.Project.Language == LanguageNames.CSharp); + return document.WithSyntaxRoot(root.ReplaceNode(argumentToReplace, errorArgument)); + } - return generator.AttributeArgument(attributeArgument); + private static SyntaxNode GenerateDescriptionArgument(SyntaxGenerator generator, SemanticModel semanticModel) + { + SyntaxNode attributeArgument; + if (semanticModel.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftCodeAnalysisHostMefMefConstruction, out var mefConstructionType) && + mefConstructionType.GetMembers("ImportingConstructorMessage").OfType().Any()) + { + attributeArgument = generator.MemberAccessExpression( + generator.TypeExpression(mefConstructionType).WithAddImportsAnnotation(), + generator.IdentifierName("ImportingConstructorMessage")); + } + else + { + attributeArgument = generator.LiteralExpression("This exported object must be obtained through the MEF export provider."); } - private static SyntaxNode GenerateErrorArgument(SyntaxGenerator generator, bool allowNamedArgument) + return generator.AttributeArgument(attributeArgument); + } + + private static SyntaxNode GenerateErrorArgument(SyntaxGenerator generator, bool allowNamedArgument) + { + if (allowNamedArgument) { - if (allowNamedArgument) - { - var argument = generator.Argument("error", RefKind.None, generator.TrueLiteralExpression()); - var attribute = generator.Attribute("ignored", argument); - return generator.GetAttributeArguments(attribute)[0]; - } - else - { - return generator.AttributeArgument(generator.TrueLiteralExpression()); - } + var argument = generator.Argument("error", RefKind.None, generator.TrueLiteralExpression()); + var attribute = generator.Attribute("ignored", argument); + return generator.GetAttributeArguments(attribute)[0]; + } + else + { + return generator.AttributeArgument(generator.TrueLiteralExpression()); } } } diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/Roslyn.Diagnostics.Analyzers.csproj b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/Roslyn.Diagnostics.Analyzers.csproj index 5fc6f22708f51..cb964a356fe0b 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/Roslyn.Diagnostics.Analyzers.csproj +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/Roslyn.Diagnostics.Analyzers.csproj @@ -7,7 +7,7 @@ Restore would conclude that there is a cyclic dependency between us and the Roslyn.Diagnostics.Analyzers package. --> *$(MSBuildProjectFile)* - $(MicrosoftCodeAnalysisForRoslynDiagnosticsAnalyzersVersion) + Microsoft.CodeAnalysis @@ -15,13 +15,36 @@ - - + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/RoslynDiagnosticsAnalyzersResources.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/RoslynDiagnosticsAnalyzersResources.cs index f768dbdb0baa3..e3ad123b643b8 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/RoslynDiagnosticsAnalyzersResources.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/RoslynDiagnosticsAnalyzersResources.cs @@ -5,7 +5,7 @@ using System; using Microsoft.CodeAnalysis; -namespace Roslyn.Diagnostics.Analyzers +namespace Microsoft.CodeAnalysis { internal partial class RoslynDiagnosticsAnalyzersResources { diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/SymbolDeclaredEventMustBeGeneratedForSourceSymbols.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/SymbolDeclaredEventMustBeGeneratedForSourceSymbols.cs index 26c3e663e7b7d..49fa6ccd7ab16 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/SymbolDeclaredEventMustBeGeneratedForSourceSymbols.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/SymbolDeclaredEventMustBeGeneratedForSourceSymbols.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Concurrent; +using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; @@ -13,6 +14,8 @@ using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Shared.Extensions; +using Roslyn.Utilities; namespace Roslyn.Diagnostics.Analyzers { diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/TestExportsShouldNotBeDiscoverableCodeFixProvider.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/TestExportsShouldNotBeDiscoverableCodeFixProvider.cs index 805af31ccc30e..f596347c9cee0 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/TestExportsShouldNotBeDiscoverableCodeFixProvider.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/TestExportsShouldNotBeDiscoverableCodeFixProvider.cs @@ -16,6 +16,7 @@ using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editing; +using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Roslyn.Diagnostics.Analyzers @@ -75,7 +76,7 @@ private static async Task AddPartNotDiscoverableAttributeAsync(Documen { if (attributeClass.Name == nameof(ExportAttribute)) { - exportAttributeSymbol = attributeClass; + exportAttributeSymbol = (INamedTypeSymbol)attributeClass; break; } } diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/ApplyTraitToClassTests.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/ApplyTraitToClassTests.cs index 65cefa6849b2a..ee0010aea08c9 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/ApplyTraitToClassTests.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/ApplyTraitToClassTests.cs @@ -18,160 +18,140 @@ public class ApplyTraitToClassTests [InlineData("A", "")] [InlineData("", "A")] [InlineData("A", "A")] - public async Task MoveTraitToType_MovesSecond_CSharpAsync(string name, string value) - { - var source = $@" -using Xunit; - -class C -{{ - [$$Trait(""{name}"", ""{value}"")] - public void Method() {{ }} - - [Fact, Trait(""{name}"", ""{value}"")] - public void Method2() {{ }} -}} -"; - var fixedSource = $@" -using Xunit; - -[Trait(""{name}"", ""{value}"")] -class C -{{ - public void Method() {{ }} - - [Fact] - public void Method2() {{ }} -}} -"; - - await new VerifyCS.Test + public Task MoveTraitToType_MovesSecond_CSharpAsync(string name, string value) + => new VerifyCS.Test { ReferenceAssemblies = AdditionalMetadataReferences.DefaultWithXUnit, - TestCode = source, - FixedCode = fixedSource, + TestCode = $$""" + using Xunit; + + class C + { + [$$Trait("{{name}}", "{{value}}")] + public void Method() { } + + [Fact, Trait("{{name}}", "{{value}}")] + public void Method2() { } + } + """, + FixedCode = $$""" + using Xunit; + + [Trait("{{name}}", "{{value}}")] + class C + { + public void Method() { } + + [Fact] + public void Method2() { } + } + """, }.RunAsync(); - } [Theory] [InlineData("A", "")] [InlineData("", "A")] [InlineData("A", "A")] - public async Task MoveTraitToType_MovesSecond_VisualBasicAsync(string name, string value) - { - var source = $@" -Imports Xunit - -Class C - <$$Trait(""{name}"", ""{value}"")> - Public Sub Method() - End Sub - - - Public Sub Method2() - End Sub -End Class -"; - var fixedSource = $@" -Imports Xunit - - -Class C - Public Sub Method() - End Sub - - - Public Sub Method2() - End Sub -End Class -"; - - await new VerifyVB.Test + public Task MoveTraitToType_MovesSecond_VisualBasicAsync(string name, string value) + => new VerifyVB.Test { ReferenceAssemblies = AdditionalMetadataReferences.DefaultWithXUnit, - TestCode = source, - FixedCode = fixedSource, + TestCode = $""" + Imports Xunit + + Class C + <$$Trait("{name}", "{value}")> + Public Sub Method() + End Sub + + + Public Sub Method2() + End Sub + End Class + """, + FixedCode = $""" + Imports Xunit + + + Class C + Public Sub Method() + End Sub + + + Public Sub Method2() + End Sub + End Class + """, }.RunAsync(); - } [Theory] [InlineData("A", "")] [InlineData("", "A")] [InlineData("A", "A")] - public async Task MoveTraitToType_MovesOnlyFirst_CSharpAsync(string name, string value) - { - var source = $@" -using Xunit; - -class C -{{ - [$$Trait("""", """")] - public void Method() {{ }} - - [Fact, Trait(""{name}"", ""{value}"")] - public void Method2() {{ }} -}} -"; - var fixedSource = $@" -using Xunit; - -[Trait("""", """")] -class C -{{ - public void Method() {{ }} - - [Fact, Trait(""{name}"", ""{value}"")] - public void Method2() {{ }} -}} -"; - - await new VerifyCS.Test + public Task MoveTraitToType_MovesOnlyFirst_CSharpAsync(string name, string value) + => new VerifyCS.Test { ReferenceAssemblies = AdditionalMetadataReferences.DefaultWithXUnit, - TestCode = source, - FixedCode = fixedSource, + TestCode = $$""" + using Xunit; + + class C + { + [$$Trait("", "")] + public void Method() { } + + [Fact, Trait("{{name}}", "{{value}}")] + public void Method2() { } + } + """, + FixedCode = $$""" + using Xunit; + + [Trait("", "")] + class C + { + public void Method() { } + + [Fact, Trait("{{name}}", "{{value}}")] + public void Method2() { } + } + """, }.RunAsync(); - } [Theory] [InlineData("A", "")] [InlineData("", "A")] [InlineData("A", "A")] - public async Task MoveTraitToType_MovesOnlyFirst_VisualBasicAsync(string name, string value) - { - var source = $@" -Imports Xunit - -Class C - <$$Trait("""", """")> - Public Sub Method() - End Sub - - - Public Sub Method2() - End Sub -End Class -"; - var fixedSource = $@" -Imports Xunit - - -Class C - Public Sub Method() - End Sub - - - Public Sub Method2() - End Sub -End Class -"; - - await new VerifyVB.Test + public Task MoveTraitToType_MovesOnlyFirst_VisualBasicAsync(string name, string value) + => new VerifyVB.Test { ReferenceAssemblies = AdditionalMetadataReferences.DefaultWithXUnit, - TestCode = source, - FixedCode = fixedSource, + TestCode = $""" + Imports Xunit + + Class C + <$$Trait("", "")> + Public Sub Method() + End Sub + + + Public Sub Method2() + End Sub + End Class + """, + FixedCode = $""" + Imports Xunit + + + Class C + Public Sub Method() + End Sub + + + Public Sub Method2() + End Sub + End Class + """, }.RunAsync(); - } } } diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/CSharpAvoidOptSuffixForNullableEnableCodeTests.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/CSharpAvoidOptSuffixForNullableEnableCodeTests.cs index 03ad33e84a8fa..699b8f22490c8 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/CSharpAvoidOptSuffixForNullableEnableCodeTests.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/CSharpAvoidOptSuffixForNullableEnableCodeTests.cs @@ -15,393 +15,388 @@ namespace Roslyn.Diagnostics.Analyzers.UnitTests public class CSharpAvoidOptSuffixForNullableEnableCodeTests { [Fact] - public async Task RS0046_CSharp8_NullableEnabledCode_DiagnosticAsync() - { - await new VerifyCS.Test + public Task RS0046_CSharp8_NullableEnabledCode_DiagnosticAsync() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp8, - TestCode = @" -#nullable enable + TestCode = """ + #nullable enable -public class Class1 -{ - private Class1? [|_instanceOpt|], [|otherInstanceOpt|]; + public class Class1 + { + private Class1? [|_instanceOpt|], [|otherInstanceOpt|]; - public Class1? [|PropertyOpt|] { get; set; } + public Class1? [|PropertyOpt|] { get; set; } - public void Method1(string? [|sOpt|]) - { - string? [|localOpt|] = null, [|otherLocalOpt|] = null; + public void Method1(string? [|sOpt|]) + { + string? [|localOpt|] = null, [|otherLocalOpt|] = null; - System.Console.WriteLine(""{0}, {1}, {2}, {3}, {4}, {5}"", _instanceOpt, otherInstanceOpt, PropertyOpt, sOpt, localOpt, otherLocalOpt); - } -}", - FixedCode = @" -#nullable enable + System.Console.WriteLine("{0}, {1}, {2}, {3}, {4}, {5}", _instanceOpt, otherInstanceOpt, PropertyOpt, sOpt, localOpt, otherLocalOpt); + } + } + """, + FixedCode = """ + #nullable enable -public class Class1 -{ - private Class1? _instance, otherInstance; + public class Class1 + { + private Class1? _instance, otherInstance; - public Class1? Property { get; set; } + public Class1? Property { get; set; } - public void Method1(string? s) - { - string? local = null, otherLocal = null; + public void Method1(string? s) + { + string? local = null, otherLocal = null; - System.Console.WriteLine(""{0}, {1}, {2}, {3}, {4}, {5}"", _instance, otherInstance, Property, s, local, otherLocal); - } -}", + System.Console.WriteLine("{0}, {1}, {2}, {3}, {4}, {5}", _instance, otherInstance, Property, s, local, otherLocal); + } + } + """, }.RunAsync(); - } [Fact] - public async Task RS0046_CSharp8_NullableEnabledCodeNonNullableType_NoDiagnosticAsync() - { - await new VerifyCS.Test + public Task RS0046_CSharp8_NullableEnabledCodeNonNullableType_NoDiagnosticAsync() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp8, - TestCode = @" -#nullable enable + TestCode = """ + #nullable enable -public class Class1 -{ - private Class1 _instanceOpt = new Class1(), otherInstanceOpt = new Class1(); + public class Class1 + { + private Class1 _instanceOpt = new Class1(), otherInstanceOpt = new Class1(); - public Class1 PropertyOpt { get; set; } = new Class1(); + public Class1 PropertyOpt { get; set; } = new Class1(); - public void Method1(string sOpt) - { - string localOpt, otherLocalOpt; - } -}", + public void Method1(string sOpt) + { + string localOpt, otherLocalOpt; + } + } + """, }.RunAsync(); - } [Fact] - public async Task RS0046_CSharp8_NullableEnabledCodeValueType_DiagnosticAsync() - { - await new VerifyCS.Test + public Task RS0046_CSharp8_NullableEnabledCodeValueType_DiagnosticAsync() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp8, - TestCode = @" -#nullable enable + TestCode = """ + #nullable enable -public enum MyEnum { A, } + public enum MyEnum { A, } -public class Class1 -{ - private MyEnum? [|_instanceOpt|], [|otherInstanceOpt|]; + public class Class1 + { + private MyEnum? [|_instanceOpt|], [|otherInstanceOpt|]; - public MyEnum? [|PropertyOpt|] { get; set; } + public MyEnum? [|PropertyOpt|] { get; set; } - public void Method1(MyEnum? [|eOpt|]) - { - MyEnum? [|localOpt|] = null, [|otherLocalOpt|] = null; + public void Method1(MyEnum? [|eOpt|]) + { + MyEnum? [|localOpt|] = null, [|otherLocalOpt|] = null; - System.Console.WriteLine(""{0}, {1}, {2}, {3}, {4}, {5}"", _instanceOpt, otherInstanceOpt, PropertyOpt, eOpt, localOpt, otherLocalOpt); - } -}", - FixedCode = @" -#nullable enable + System.Console.WriteLine("{0}, {1}, {2}, {3}, {4}, {5}", _instanceOpt, otherInstanceOpt, PropertyOpt, eOpt, localOpt, otherLocalOpt); + } + } + """, + FixedCode = """ + #nullable enable -public enum MyEnum { A, } + public enum MyEnum { A, } -public class Class1 -{ - private MyEnum? _instance, otherInstance; + public class Class1 + { + private MyEnum? _instance, otherInstance; - public MyEnum? Property { get; set; } + public MyEnum? Property { get; set; } - public void Method1(MyEnum? e) - { - MyEnum? local = null, otherLocal = null; + public void Method1(MyEnum? e) + { + MyEnum? local = null, otherLocal = null; - System.Console.WriteLine(""{0}, {1}, {2}, {3}, {4}, {5}"", _instance, otherInstance, Property, e, local, otherLocal); - } -}", + System.Console.WriteLine("{0}, {1}, {2}, {3}, {4}, {5}", _instance, otherInstance, Property, e, local, otherLocal); + } + } + """, }.RunAsync(); - } [Fact] - public async Task RS0046_CSharp8_NullableEnabledCodeNonNullableValueType_NoDiagnosticAsync() - { - await new VerifyCS.Test + public Task RS0046_CSharp8_NullableEnabledCodeNonNullableValueType_NoDiagnosticAsync() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp8, - TestCode = @" -#nullable enable + TestCode = """ + #nullable enable -public enum MyEnum { A, } + public enum MyEnum { A, } -public class Class1 -{ - private MyEnum _instanceOpt = MyEnum.A, otherInstanceOpt = MyEnum.A; + public class Class1 + { + private MyEnum _instanceOpt = MyEnum.A, otherInstanceOpt = MyEnum.A; - public MyEnum PropertyOpt { get; set; } + public MyEnum PropertyOpt { get; set; } - public void Method1(MyEnum eOpt) - { - MyEnum localOpt, otherLocalOpt; - } -}", + public void Method1(MyEnum eOpt) + { + MyEnum localOpt, otherLocalOpt; + } + } + """, }.RunAsync(); - } [Fact] - public async Task RS0046_CSharp8_NonNullableEnabledCode_NoDiagnosticAsync() - { - await new VerifyCS.Test + public Task RS0046_CSharp8_NonNullableEnabledCode_NoDiagnosticAsync() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp8, TestCode = - @" -public class Class1 -{ - private Class1 _instanceOpt, otherInstanceOpt; - - public Class1 PropertyOpt { get; set; } - - public void Method1(string sOpt) - { - string localOpt, otherLocalOpt; - } -}", + """ + public class Class1 + { + private Class1 _instanceOpt, otherInstanceOpt; + + public Class1 PropertyOpt { get; set; } + + public void Method1(string sOpt) + { + string localOpt, otherLocalOpt; + } + } + """, }.RunAsync(); - } [Fact] - public async Task RS0046_CSharp8_NullableDisabledCode_NoDiagnosticAsync() - { - await new VerifyCS.Test + public Task RS0046_CSharp8_NullableDisabledCode_NoDiagnosticAsync() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp8, TestCode = -@" -#nullable disable + """ + #nullable disable -public class Class1 -{ - private Class1 _instanceOpt, otherInstanceOpt; + public class Class1 + { + private Class1 _instanceOpt, otherInstanceOpt; - public Class1 PropertyOpt { get; set; } + public Class1 PropertyOpt { get; set; } - public void Method1(string sOpt) - { - string localOpt, otherLocalOpt; - } -}", + public void Method1(string sOpt) + { + string localOpt, otherLocalOpt; + } + } + """, }.RunAsync(); - } [Fact] - public async Task RS0046_PriorToCSharp8_NoDiagnosticAsync() - { - await new VerifyCS.Test + public Task RS0046_PriorToCSharp8_NoDiagnosticAsync() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp7_3, TestCode = - @" -public class Class1 -{ - private Class1 _instanceOpt, otherInstanceOpt; - - public Class1 PropertyOpt { get; set; } - - public void Method1(string sOpt) - { - string localOpt, otherLocalOpt; - } -}", + """ + public class Class1 + { + private Class1 _instanceOpt, otherInstanceOpt; + + public Class1 PropertyOpt { get; set; } + + public void Method1(string sOpt) + { + string localOpt, otherLocalOpt; + } + } + """, }.RunAsync(); - } [Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/3707")] - public async Task RS0046_CSharp8_VariableWithoutOptAlreadyExists_DiagnosticButNoCodeFixAsync() - { - await new VerifyCS.Test + public Task RS0046_CSharp8_VariableWithoutOptAlreadyExists_DiagnosticButNoCodeFixAsync() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp8, - TestCode = @" -#nullable enable - -public class Class1 -{ - private Class1? [|_instanceOpt|], _instance; - - public Class1? [|PropertyOpt|] { get; set; } - public Class1? Property { get; set; } - - public void Method1(string? [|sOpt|], string? s) - { - string? [|localOpt|], local; - } -}", - FixedCode = @" -#nullable enable - -public class Class1 -{ - private Class1? [|_instanceOpt|], _instance; - - public Class1? [|PropertyOpt|] { get; set; } - public Class1? Property { get; set; } - - public void Method1(string? [|sOpt|], string? s) - { - string? [|localOpt|], local; - } -}", + TestCode = """ + #nullable enable + + public class Class1 + { + private Class1? [|_instanceOpt|], _instance; + + public Class1? [|PropertyOpt|] { get; set; } + public Class1? Property { get; set; } + + public void Method1(string? [|sOpt|], string? s) + { + string? [|localOpt|], local; + } + } + """, + FixedCode = """ + #nullable enable + + public class Class1 + { + private Class1? [|_instanceOpt|], _instance; + + public Class1? [|PropertyOpt|] { get; set; } + public Class1? Property { get; set; } + + public void Method1(string? [|sOpt|], string? s) + { + string? [|localOpt|], local; + } + } + """, }.RunAsync(); - } [Fact] - public async Task RS0046_CSharp8_UnknownType_DiagnosticAndCodeFixAsync() - { - await new VerifyCS.Test + public Task RS0046_CSharp8_UnknownType_DiagnosticAndCodeFixAsync() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp8, - TestCode = @" -#nullable enable - -public class Class1 -{ - private {|CS0246:Class2|}? [|_instanceOpt|]; - - public {|CS0246:Class2|}? [|PropertyOpt|] { get; set; } - - public void Method1({|CS0246:Class2|}? [|sOpt|]) - { - {|CS0246:Class2|}? [|localOpt|]; - } -}", - FixedCode = @" -#nullable enable - -public class Class1 -{ - private {|CS0246:Class2|}? _instance; - - public {|CS0246:Class2|}? Property { get; set; } - - public void Method1({|CS0246:Class2|}? s) - { - {|CS0246:Class2|}? local; - } -}", + TestCode = """ + #nullable enable + + public class Class1 + { + private {|CS0246:Class2|}? [|_instanceOpt|]; + + public {|CS0246:Class2|}? [|PropertyOpt|] { get; set; } + + public void Method1({|CS0246:Class2|}? [|sOpt|]) + { + {|CS0246:Class2|}? [|localOpt|]; + } + } + """, + FixedCode = """ + #nullable enable + + public class Class1 + { + private {|CS0246:Class2|}? _instance; + + public {|CS0246:Class2|}? Property { get; set; } + + public void Method1({|CS0246:Class2|}? s) + { + {|CS0246:Class2|}? local; + } + } + """, }.RunAsync(); - } [Fact, WorkItem(3813, "https://github.com/dotnet/roslyn-analyzers/issues/3813")] - public async Task RS0046_CSharp8_NullableEnabledCode_InterfaceImplementation_NoDiagnosticAsync() - { - await new VerifyCS.Test + public Task RS0046_CSharp8_NullableEnabledCode_InterfaceImplementation_NoDiagnosticAsync() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp8, - TestCode = @" -#nullable enable - -public interface ISomething -{ - ISomething? [|PropertyOpt|] { get; set; } - void Method1(string? [|sOpt|]); -} - -public class Class1 : ISomething -{ - public ISomething? PropertyOpt { get; set; } - - public void Method1(string? sOpt) - { - string? [|localOpt|] = null, [|otherLocalOpt|] = null; - - System.Console.WriteLine(""{0}, {1}, {2}, {3}"", PropertyOpt, sOpt, localOpt, otherLocalOpt); - } -}", - FixedCode = @" -#nullable enable - -public interface ISomething -{ - ISomething? Property { get; set; } - void Method1(string? s); -} - -public class Class1 : ISomething -{ - public ISomething? Property { get; set; } - - public void Method1(string? sOpt) - { - string? local = null, otherLocal = null; - - System.Console.WriteLine(""{0}, {1}, {2}, {3}"", Property, sOpt, local, otherLocal); - } -}", + TestCode = """ + #nullable enable + + public interface ISomething + { + ISomething? [|PropertyOpt|] { get; set; } + void Method1(string? [|sOpt|]); + } + + public class Class1 : ISomething + { + public ISomething? PropertyOpt { get; set; } + + public void Method1(string? sOpt) + { + string? [|localOpt|] = null, [|otherLocalOpt|] = null; + + System.Console.WriteLine("{0}, {1}, {2}, {3}", PropertyOpt, sOpt, localOpt, otherLocalOpt); + } + } + """, + FixedCode = """ + #nullable enable + + public interface ISomething + { + ISomething? Property { get; set; } + void Method1(string? s); + } + + public class Class1 : ISomething + { + public ISomething? Property { get; set; } + + public void Method1(string? sOpt) + { + string? local = null, otherLocal = null; + + System.Console.WriteLine("{0}, {1}, {2}, {3}", Property, sOpt, local, otherLocal); + } + } + """, }.RunAsync(); - } [Fact, WorkItem(3813, "https://github.com/dotnet/roslyn-analyzers/issues/3813")] - public async Task RS0046_CSharp8_NullableEnabledCode_Override_NoDiagnosticAsync() - { - await new VerifyCS.Test + public Task RS0046_CSharp8_NullableEnabledCode_Override_NoDiagnosticAsync() + => new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp8, - TestCode = @" -#nullable enable - -public class Base -{ - public virtual Base? [|PropertyOpt|] { get; set; } - - public virtual void Method1(string? [|sOpt|]) - { - System.Console.WriteLine(""{0}"", sOpt); - } -} - -public class Derived : Base -{ - public override Base? PropertyOpt { get; set; } - - public override void Method1(string? sOpt) - { - string? [|localOpt|] = null, [|otherLocalOpt|] = null; - - System.Console.WriteLine(""{0}, {1}, {2}, {3}"", PropertyOpt, sOpt, localOpt, otherLocalOpt); - } -}", - FixedCode = @" -#nullable enable - -public class Base -{ - public virtual Base? Property { get; set; } - - public virtual void Method1(string? s) - { - System.Console.WriteLine(""{0}"", s); - } -} - -public class Derived : Base -{ - public override Base? Property { get; set; } - - public override void Method1(string? sOpt) - { - string? local = null, otherLocal = null; - - System.Console.WriteLine(""{0}, {1}, {2}, {3}"", Property, sOpt, local, otherLocal); - } -}", + TestCode = """ + #nullable enable + + public class Base + { + public virtual Base? [|PropertyOpt|] { get; set; } + + public virtual void Method1(string? [|sOpt|]) + { + System.Console.WriteLine("{0}", sOpt); + } + } + + public class Derived : Base + { + public override Base? PropertyOpt { get; set; } + + public override void Method1(string? sOpt) + { + string? [|localOpt|] = null, [|otherLocalOpt|] = null; + + System.Console.WriteLine("{0}, {1}, {2}, {3}", PropertyOpt, sOpt, localOpt, otherLocalOpt); + } + } + """, + FixedCode = """ + #nullable enable + + public class Base + { + public virtual Base? Property { get; set; } + + public virtual void Method1(string? s) + { + System.Console.WriteLine("{0}", s); + } + } + + public class Derived : Base + { + public override Base? Property { get; set; } + + public override void Method1(string? sOpt) + { + string? local = null, otherLocal = null; + + System.Console.WriteLine("{0}, {1}, {2}, {3}", Property, sOpt, local, otherLocal); + } + } + """, }.RunAsync(); - } } } diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/CSharpDoNotCapturePrimaryConstructorParametersTests.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/CSharpDoNotCapturePrimaryConstructorParametersTests.cs index c93b01c550b98..2001757e2118b 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/CSharpDoNotCapturePrimaryConstructorParametersTests.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/CSharpDoNotCapturePrimaryConstructorParametersTests.cs @@ -14,26 +14,23 @@ namespace Roslyn.Diagnostics.Analyzers.UnitTests public class CSharpDoNotCapturePrimaryConstructorParametersTests { [Fact] - public async Task ErrorOnCapture_InMethod() - { - var source = """ + public Task ErrorOnCapture_InMethod() + => new VerifyCS.Test + { + TestCode = """ class C(int i) { private int M() => [|i|]; } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task ErrorOnCapture_InProperty() - { - var source = """ + public Task ErrorOnCapture_InProperty() + => new VerifyCS.Test + { + TestCode = """ class C(int i) { private int P @@ -42,19 +39,15 @@ private int P set => [|i|] = value; } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task ErrorOnCapture_InIndexer() - { - var source = """ + public Task ErrorOnCapture_InIndexer() + => new VerifyCS.Test + { + TestCode = """ class C(int i) { private int this[int param] @@ -63,19 +56,15 @@ private int this[int param] set => [|i|] = value; } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task ErrorOnCapture_InEvent() - { - var source = """ + public Task ErrorOnCapture_InEvent() + => new VerifyCS.Test + { + TestCode = """ class C(int i) { public event System.Action E @@ -84,19 +73,15 @@ public event System.Action E remove => _ = [|i|]; } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task ErrorOnCapture_UseInSubsequentConstructor() - { - var source = """ + public Task ErrorOnCapture_UseInSubsequentConstructor() + => new VerifyCS.Test + { + TestCode = """ class C(int i) { C(bool b) : this(1) @@ -104,11 +89,7 @@ class C(int i) _ = i; } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp12, ExpectedDiagnostics = { // /0/Test0.cs(5,13): error RS0103: Primary constructor parameter 'i' should not be implicitly captured @@ -117,77 +98,61 @@ class C(int i) DiagnosticResult.CompilerError("CS9105").WithSpan(5, 13, 5, 14).WithArguments("int i"), } }.RunAsync(); - } [Fact] - public async Task NoError_PassToBase() - { - var source = """ + public Task NoError_PassToBase() + => new VerifyCS.Test + { + TestCode = """ class Base(int i); class Derived(int i) : Base(i); - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task NoError_FieldInitializer() - { - var source = """ + public Task NoError_FieldInitializer() + => new VerifyCS.Test + { + TestCode = """ class C(int i) { public int I = i; } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task NoError_PropertyInitializer() - { - var source = """ + public Task NoError_PropertyInitializer() + => new VerifyCS.Test + { + TestCode = """ class C(int i) { public int I { get; set; } = i; } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task NoError_CapturedInLambda() - { - var source = """ + public Task NoError_CapturedInLambda() + => new VerifyCS.Test + { + TestCode = """ using System; public class Base(Action action); public class Derived(int i) : Base(() => Console.WriteLine(i)); - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task NoError_LocalFunctionParameterReference() - { - var source = """ + public Task NoError_LocalFunctionParameterReference() + => new VerifyCS.Test + { + TestCode = """ using System; class C { @@ -203,13 +168,8 @@ void Nested1(int i) } } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp12, }.RunAsync(); - } } } diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/CSharpDoNotUseDebugAssertForInterpolatedStringsTests.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/CSharpDoNotUseDebugAssertForInterpolatedStringsTests.cs index aa4056f0d4975..cfb246b02b28b 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/CSharpDoNotUseDebugAssertForInterpolatedStringsTests.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/CSharpDoNotUseDebugAssertForInterpolatedStringsTests.cs @@ -37,9 +37,11 @@ public static void Assert(bool condition, string message) { } [InlineData("""" $"""{0}""" """")] - public async Task InterpolatedString(string @string) - { - var source = $$""" + public Task InterpolatedString(string @string) + => new VerifyCS.Test + { + ReferenceAssemblies = AdditionalMetadataReferences.DefaultNetFramework, + TestCode = $$""" using System.Diagnostics; class C @@ -51,9 +53,8 @@ void M() } {{RoslynDebug}} - """; - - var @fixed = $$""" + """, + FixedCode = $$""" using System.Diagnostics; using Roslyn.Utilities; @@ -66,21 +67,16 @@ void M() } {{RoslynDebug}} - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = AdditionalMetadataReferences.DefaultNetFramework, - TestCode = source, - FixedCode = @fixed, + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task NoCrashOnUsingStaticedAssert() - { - var source = $$""" + public Task NoCrashOnUsingStaticedAssert() + => new VerifyCS.Test + { + ReferenceAssemblies = AdditionalMetadataReferences.DefaultNetFramework, + TestCode = $$""" using static System.Diagnostics.Debug; class C @@ -92,15 +88,9 @@ void M() } {{RoslynDebug}} - """; - - await new VerifyCS.Test - { - ReferenceAssemblies = AdditionalMetadataReferences.DefaultNetFramework, - TestCode = source, + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp12, }.RunAsync(); - } [Theory] [InlineData(""" @@ -115,9 +105,10 @@ void M() [InlineData("""" $"""{"0"}""" """")] - public async Task NoAssertForConstantString(string @string) - { - var source = $$""" + public Task NoAssertForConstantString(string @string) + => new VerifyCS.Test + { + TestCode = $$""" using System.Diagnostics; class C @@ -129,13 +120,8 @@ void M() } {{RoslynDebug}} - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp12, }.RunAsync(); - } } } diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/CreateTestAccessorTests.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/CreateTestAccessorTests.cs index edc930222e24b..0846bd31dce4b 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/CreateTestAccessorTests.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/CreateTestAccessorTests.cs @@ -24,24 +24,28 @@ public class CreateTestAccessorTests [InlineData("[|class TestClass|] ")] public async Task CreateTestAccessorCSharpAsync(string typeHeader) { - var source = typeHeader + @"{ -}"; - var fixedSourceBody = @"{ - internal TestAccessor GetTestAccessor() - { - return new TestAccessor(this); - } - - internal readonly struct TestAccessor - { - private readonly TestClass _instance; - - internal TestAccessor(TestClass instance) - { - _instance = instance; - } - } -}"; + var source = typeHeader + """ + { + } + """; + var fixedSourceBody = """ + { + internal TestAccessor GetTestAccessor() + { + return new TestAccessor(this); + } + + internal readonly struct TestAccessor + { + private readonly TestClass _instance; + + internal TestAccessor(TestClass instance) + { + _instance = instance; + } + } + } + """; var fixedSource = "class TestClass " + fixedSourceBody; await VerifyCS.VerifyRefactoringAsync(source, fixedSource); @@ -59,24 +63,28 @@ internal TestAccessor(TestClass instance) [InlineData("[|struct TestStruct|] ")] public async Task CreateTestAccessorStructCSharpAsync(string typeHeader) { - var source = typeHeader + @"{ -}"; - var fixedSourceBody = @"{ - internal TestAccessor GetTestAccessor() - { - return new TestAccessor(this); - } - - internal readonly struct TestAccessor - { - private readonly TestStruct _instance; - - internal TestAccessor(TestStruct instance) - { - _instance = instance; - } - } -}"; + var source = typeHeader + """ + { + } + """; + var fixedSourceBody = """ + { + internal TestAccessor GetTestAccessor() + { + return new TestAccessor(this); + } + + internal readonly struct TestAccessor + { + private readonly TestStruct _instance; + + internal TestAccessor(TestStruct instance) + { + _instance = instance; + } + } + } + """; var fixedSource = "struct TestStruct " + fixedSourceBody; await VerifyCS.VerifyRefactoringAsync(source, fixedSource); @@ -94,24 +102,28 @@ internal TestAccessor(TestStruct instance) [InlineData("[|record TestRecord|] ")] public async Task CreateTestAccessorRecordCSharpAsync(string typeHeader) { - var source = typeHeader + @"{ -}"; - var fixedSourceBody = @"{ - internal TestAccessor GetTestAccessor() - { - return new TestAccessor(this); - } - - internal readonly struct TestAccessor - { - private readonly TestRecord _instance; - - internal TestAccessor(TestRecord instance) - { - _instance = instance; - } - } -}"; + var source = typeHeader + """ + { + } + """; + var fixedSourceBody = """ + { + internal TestAccessor GetTestAccessor() + { + return new TestAccessor(this); + } + + internal readonly struct TestAccessor + { + private readonly TestRecord _instance; + + internal TestAccessor(TestRecord instance) + { + _instance = instance; + } + } + } + """; var fixedSource = "record TestRecord " + fixedSourceBody; await new VerifyCS.Test @@ -156,24 +168,27 @@ public async Task UnsupportedTypeCSharpAsync(TypeKind typeKind) [InlineData("[|Class TestClass|]")] public async Task CreateTestAccessorVisualBasicAsync(string typeHeader) { - var source = $@"{typeHeader} -End Class"; - var fixedSourceBody = @" - Friend Function GetTestAccessor() As TestAccessor - Return New TestAccessor(Me) - End Function - - Friend Structure TestAccessor - Private ReadOnly _instance As TestClass - - Friend Sub New(instance As TestClass) - _instance = instance - End Sub - End Structure -End Class"; + var fixedSourceBody = """ + + Friend Function GetTestAccessor() As TestAccessor + Return New TestAccessor(Me) + End Function + + Friend Structure TestAccessor + Private ReadOnly _instance As TestClass + + Friend Sub New(instance As TestClass) + _instance = instance + End Sub + End Structure + End Class + """; var fixedSource = "Class TestClass" + fixedSourceBody; - await VerifyVB.VerifyRefactoringAsync(source, fixedSource); + await VerifyVB.VerifyRefactoringAsync($""" + {typeHeader} + End Class + """, fixedSource); // Applying the refactoring a second time does not produce any changes fixedSource = typeHeader + fixedSourceBody; @@ -188,24 +203,27 @@ End Structure [InlineData("[|Structure TestStructure|]")] public async Task CreateTestAccessorStructureVisualBasicAsync(string typeHeader) { - var source = $@"{typeHeader} -End Structure"; - var fixedSourceBody = @" - Friend Function GetTestAccessor() As TestAccessor - Return New TestAccessor(Me) - End Function - - Friend Structure TestAccessor - Private ReadOnly _instance As TestStructure - - Friend Sub New(instance As TestStructure) - _instance = instance - End Sub - End Structure -End Structure"; + var fixedSourceBody = """ + + Friend Function GetTestAccessor() As TestAccessor + Return New TestAccessor(Me) + End Function + + Friend Structure TestAccessor + Private ReadOnly _instance As TestStructure + + Friend Sub New(instance As TestStructure) + _instance = instance + End Sub + End Structure + End Structure + """; var fixedSource = "Structure TestStructure" + fixedSourceBody; - await VerifyVB.VerifyRefactoringAsync(source, fixedSource); + await VerifyVB.VerifyRefactoringAsync($""" + {typeHeader} + End Structure + """, fixedSource); // Applying the refactoring a second time does not produce any changes fixedSource = typeHeader + fixedSourceBody; diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/DefaultableTypeShouldHaveDefaultableFieldsTests.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/DefaultableTypeShouldHaveDefaultableFieldsTests.cs index 275a79db9201b..1b1fb3b7eca44 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/DefaultableTypeShouldHaveDefaultableFieldsTests.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/DefaultableTypeShouldHaveDefaultableFieldsTests.cs @@ -14,14 +14,15 @@ namespace Roslyn.Diagnostics.Analyzers.UnitTests { public class DefaultableTypeShouldHaveDefaultableFieldsTests { - private const string NonDefaultableAttribute = @"// -using System; + private const string NonDefaultableAttribute = """ + // + using System; -namespace Roslyn.Utilities { - [AttributeUsage(AttributeTargets.Struct | AttributeTargets.GenericParameter)] - sealed class NonDefaultableAttribute : Attribute { } -} -"; + namespace Roslyn.Utilities { + [AttributeUsage(AttributeTargets.Struct | AttributeTargets.GenericParameter)] + sealed class NonDefaultableAttribute : Attribute { } + } + """; public static IEnumerable DefaultableTypes { @@ -66,24 +67,24 @@ public static IEnumerable NonDefaultableTypes [MemberData(nameof(NonDefaultableTypes))] public async Task TestNonDefaultableStructWithNonDefaultableTypeFieldAsync(string nonDefaultableType) { - var code = $@" -#nullable enable + var code = $$""" + #nullable enable -using System; -using Roslyn.Utilities; + using System; + using Roslyn.Utilities; -[NonDefaultable] -struct NonDefaultableStruct {{ }} + [NonDefaultable] + struct NonDefaultableStruct { } -[NonDefaultable] -struct NonDefaultableTestStruct {{ - {nonDefaultableType} field; - {nonDefaultableType} Property {{ get; }} + [NonDefaultable] + struct NonDefaultableTestStruct { + {{nonDefaultableType}} field; + {{nonDefaultableType}} Property { get; } - static {nonDefaultableType} staticField = default!; - static {nonDefaultableType} StaticProperty {{ get; }} = default!; -}} -"; + static {{nonDefaultableType}} staticField = default!; + static {{nonDefaultableType}} StaticProperty { get; } = default!; + } + """; await new VerifyCS.Test { @@ -96,24 +97,24 @@ struct NonDefaultableTestStruct {{ [MemberData(nameof(NonDefaultableTypes))] public async Task TestNonDefaultableStructWithNonDefaultableTypeNullableDisableFieldAsync(string nonDefaultableType) { - var code = $@" -#nullable disable + var code = $$""" + #nullable disable -using System; -using Roslyn.Utilities; + using System; + using Roslyn.Utilities; -[NonDefaultable] -struct NonDefaultableStruct {{ }} + [NonDefaultable] + struct NonDefaultableStruct { } -[NonDefaultable] -struct NonDefaultableTestStruct {{ - {nonDefaultableType} field; - {nonDefaultableType} Property {{ get; }} + [NonDefaultable] + struct NonDefaultableTestStruct { + {{nonDefaultableType}} field; + {{nonDefaultableType}} Property { get; } - static {nonDefaultableType} staticField; - static {nonDefaultableType} StaticProperty {{ get; }} -}} -"; + static {{nonDefaultableType}} staticField; + static {{nonDefaultableType}} StaticProperty { get; } + } + """; await new VerifyCS.Test { @@ -126,21 +127,21 @@ struct NonDefaultableTestStruct {{ [MemberData(nameof(DefaultableTypes))] public async Task TestNonDefaultableStructWithDefaultableTypeFieldAsync(string defaultableType) { - var code = $@" -#nullable enable + var code = $$""" + #nullable enable -using System; -using Roslyn.Utilities; + using System; + using Roslyn.Utilities; -[NonDefaultable] -struct NonDefaultableTestStruct {{ - {defaultableType} field; - {defaultableType} Property {{ get; }} + [NonDefaultable] + struct NonDefaultableTestStruct { + {{defaultableType}} field; + {{defaultableType}} Property { get; } - static {defaultableType} staticField; - static {defaultableType} StaticProperty {{ get; }} -}} -"; + static {{defaultableType}} staticField; + static {{defaultableType}} StaticProperty { get; } + } + """; await new VerifyCS.Test { @@ -153,21 +154,21 @@ struct NonDefaultableTestStruct {{ [MemberData(nameof(DefaultableTypesNullableDisableContext))] public async Task TestNonDefaultableStructWithDefaultableTypeNullableDisableFieldAsync(string defaultableType) { - var code = $@" -#nullable disable + var code = $$""" + #nullable disable -using System; -using Roslyn.Utilities; + using System; + using Roslyn.Utilities; -[NonDefaultable] -struct NonDefaultableTestStruct {{ - {defaultableType} field; - {defaultableType} Property {{ get; }} + [NonDefaultable] + struct NonDefaultableTestStruct { + {{defaultableType}} field; + {{defaultableType}} Property { get; } - static {defaultableType} staticField; - static {defaultableType} StaticProperty {{ get; }} -}} -"; + static {{defaultableType}} staticField; + static {{defaultableType}} StaticProperty { get; } + } + """; await new VerifyCS.Test { @@ -180,19 +181,19 @@ struct NonDefaultableTestStruct {{ [MemberData(nameof(DefaultableTypes))] public async Task TestDefaultableStructWithDefaultableTypeFieldAsync(string defaultableType) { - var code = $@" -#nullable enable + var code = $$""" + #nullable enable -using System; + using System; -struct DefaultableStruct {{ - {defaultableType} field; - {defaultableType} Property {{ get; }} + struct DefaultableStruct { + {{defaultableType}} field; + {{defaultableType}} Property { get; } - static {defaultableType} staticField; - static {defaultableType} StaticProperty {{ get; }} -}} -"; + static {{defaultableType}} staticField; + static {{defaultableType}} StaticProperty { get; } + } + """; await new VerifyCS.Test { @@ -205,19 +206,19 @@ struct DefaultableStruct {{ [MemberData(nameof(DefaultableTypes))] public async Task TestClassWithDefaultableTypeFieldAsync(string defaultableType) { - var code = $@" -#nullable enable + var code = $$""" + #nullable enable -using System; + using System; -class TestClass {{ - {defaultableType} field; - {defaultableType} Property {{ get; }} + class TestClass { + {{defaultableType}} field; + {{defaultableType}} Property { get; } - static {defaultableType} staticField; - static {defaultableType} StaticProperty {{ get; }} -}} -"; + static {{defaultableType}} staticField; + static {{defaultableType}} StaticProperty { get; } + } + """; await new VerifyCS.Test { @@ -230,19 +231,19 @@ class TestClass {{ [MemberData(nameof(DefaultableTypesNullableDisableContext))] public async Task TestClassWithDefaultableTypeNullableDisableFieldAsync(string defaultableType) { - var code = $@" -#nullable disable + var code = $$""" + #nullable disable -using System; + using System; -class TestClass {{ - {defaultableType} field; - {defaultableType} Property {{ get; }} + class TestClass { + {{defaultableType}} field; + {{defaultableType}} Property { get; } - static {defaultableType} staticField; - static {defaultableType} StaticProperty {{ get; }} -}} -"; + static {{defaultableType}} staticField; + static {{defaultableType}} StaticProperty { get; } + } + """; await new VerifyCS.Test { @@ -255,23 +256,23 @@ class TestClass {{ [MemberData(nameof(NonDefaultableTypes))] public async Task TestDefaultableStructWithNonDefaultableTypeFieldAsync(string nonDefaultableType) { - var code = $@" -#nullable enable + var code = $$""" + #nullable enable -using System; -using Roslyn.Utilities; + using System; + using Roslyn.Utilities; -[NonDefaultable] -struct NonDefaultableStruct {{ }} + [NonDefaultable] + struct NonDefaultableStruct { } -struct DefaultableStruct {{ - {nonDefaultableType} [|field|]; - {nonDefaultableType} [|Property|] {{ get; }} + struct DefaultableStruct { + {{nonDefaultableType}} [|field|]; + {{nonDefaultableType}} [|Property|] { get; } - static {nonDefaultableType} StaticField = default!; - static {nonDefaultableType} StaticProperty {{ get; }} = default!; -}} -"; + static {{nonDefaultableType}} StaticField = default!; + static {{nonDefaultableType}} StaticProperty { get; } = default!; + } + """; await new VerifyCS.Test { @@ -284,23 +285,23 @@ struct DefaultableStruct {{ [MemberData(nameof(NonDefaultableTypes))] public async Task TestDefaultableStructWithNonDefaultableTypeNullableDisableFieldAsync(string nonDefaultableType) { - var code = $@" -#nullable disable + var code = $$""" + #nullable disable -using System; -using Roslyn.Utilities; + using System; + using Roslyn.Utilities; -[NonDefaultable] -struct NonDefaultableStruct {{ }} + [NonDefaultable] + struct NonDefaultableStruct { } -struct DefaultableStruct {{ - {nonDefaultableType} field; - {nonDefaultableType} Property {{ get; }} + struct DefaultableStruct { + {{nonDefaultableType}} field; + {{nonDefaultableType}} Property { get; } - static {nonDefaultableType} StaticField; - static {nonDefaultableType} StaticProperty {{ get; }} -}} -"; + static {{nonDefaultableType}} StaticField; + static {{nonDefaultableType}} StaticProperty { get; } + } + """; await new VerifyCS.Test { diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/DoNotCallGetTestAccessorTests.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/DoNotCallGetTestAccessorTests.cs index 8c0a1e6bd7385..820d3cef57600 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/DoNotCallGetTestAccessorTests.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/DoNotCallGetTestAccessorTests.cs @@ -16,208 +16,194 @@ namespace Roslyn.Diagnostics.Analyzers.UnitTests public class DoNotCallGetTestAccessorTests { [Fact] - public async Task DoNotCallGetTestAccessor_CSharpAsync() - { - var source = @"class TestClass { - internal void Method() - { - _ = [|GetTestAccessor()|]; - _ = [|this.GetTestAccessor()|]; - _ = [|new TestClass().GetTestAccessor()|]; - } - - internal TestAccessor GetTestAccessor() - { - return new TestAccessor(this); - } - - internal readonly struct TestAccessor - { - private readonly TestClass _testClass; - - internal TestAccessor(TestClass testClass) - { - _testClass = testClass; - } - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(source); - } + public Task DoNotCallGetTestAccessor_CSharpAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + class TestClass { + internal void Method() + { + _ = [|GetTestAccessor()|]; + _ = [|this.GetTestAccessor()|]; + _ = [|new TestClass().GetTestAccessor()|]; + } + + internal TestAccessor GetTestAccessor() + { + return new TestAccessor(this); + } + + internal readonly struct TestAccessor + { + private readonly TestClass _testClass; + + internal TestAccessor(TestClass testClass) + { + _testClass = testClass; + } + } + } + """); [Fact] - public async Task DoNotCallGetTestAccessor_VisualBasicAsync() - { - var source = @"Class TestClass - Friend Sub Method() - Dim a = [|GetTestAccessor()|] - Dim b = [|Me.GetTestAccessor()|] - Dim c = [|New TestClass().GetTestAccessor()|] - End Sub - - Friend Function GetTestAccessor() As TestAccessor - Return New TestAccessor(Me) - End Function - - Friend Structure TestAccessor - Private ReadOnly _testClass As TestClass - - Friend Sub New(testClass As TestClass) - _testClass = testClass - End Sub - End Structure -End Class"; - - await VerifyVB.VerifyAnalyzerAsync(source); - } + public Task DoNotCallGetTestAccessor_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Class TestClass + Friend Sub Method() + Dim a = [|GetTestAccessor()|] + Dim b = [|Me.GetTestAccessor()|] + Dim c = [|New TestClass().GetTestAccessor()|] + End Sub + + Friend Function GetTestAccessor() As TestAccessor + Return New TestAccessor(Me) + End Function + + Friend Structure TestAccessor + Private ReadOnly _testClass As TestClass + + Friend Sub New(testClass As TestClass) + _testClass = testClass + End Sub + End Structure + End Class + """); [Fact] - public async Task DoNotConstructTestAccessor_CSharpAsync() - { - var source = @"class TestClass { - internal void Method() - { - _ = [|new TestAccessor(this)|]; - _ = [|new TestAccessor(new TestClass())|]; - } - - internal TestAccessor GetTestAccessor() - { - return new TestAccessor(this); - } - - internal readonly struct TestAccessor - { - private readonly TestClass _testClass; - - internal TestAccessor(TestClass testClass) - { - _testClass = testClass; - } - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(source); - } + public Task DoNotConstructTestAccessor_CSharpAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + class TestClass { + internal void Method() + { + _ = [|new TestAccessor(this)|]; + _ = [|new TestAccessor(new TestClass())|]; + } + + internal TestAccessor GetTestAccessor() + { + return new TestAccessor(this); + } + + internal readonly struct TestAccessor + { + private readonly TestClass _testClass; + + internal TestAccessor(TestClass testClass) + { + _testClass = testClass; + } + } + } + """); [Fact] - public async Task DoNotConstructTestAccessor_VisualBasicAsync() - { - var source = @"Class TestClass - Friend Sub Method() - Dim a = [|New TestAccessor(Me)|] - Dim b = [|New TestAccessor(New TestClass())|] - End Sub - - Friend Function GetTestAccessor() As TestAccessor - Return New TestAccessor(Me) - End Function - - Friend Structure TestAccessor - Private ReadOnly _testClass As TestClass - - Friend Sub New(testClass As TestClass) - _testClass = testClass - End Sub - End Structure -End Class"; - - await VerifyVB.VerifyAnalyzerAsync(source); - } + public Task DoNotConstructTestAccessor_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Class TestClass + Friend Sub Method() + Dim a = [|New TestAccessor(Me)|] + Dim b = [|New TestAccessor(New TestClass())|] + End Sub + + Friend Function GetTestAccessor() As TestAccessor + Return New TestAccessor(Me) + End Function + + Friend Structure TestAccessor + Private ReadOnly _testClass As TestClass + + Friend Sub New(testClass As TestClass) + _testClass = testClass + End Sub + End Structure + End Class + """); [Fact] - public async Task DoNotAccessTestAccessorStaticMember_CSharpAsync() - { - var source = @" -using System; - -class TestClass { - internal void Method() - { - _ = [|TestAccessor.ExposedField|]; - _ = [|TestAccessor.ExposedProperty|]; - [|TestAccessor.ExposedEvent|] += delegate { }; - [|TestAccessor.ExposedMethod()|]; - } - - internal TestAccessor GetTestAccessor() - { - return new TestAccessor(this); - } - - internal readonly struct TestAccessor - { - private readonly TestClass _testClass; - - internal TestAccessor(TestClass testClass) - { - _testClass = testClass; - } - - public static int ExposedField; - public static int ExposedProperty => 0; - public static event EventHandler ExposedEvent { add { } remove { } } - public static void ExposedMethod() { } - } -} - -class OtherClass { - internal void Method() - { - _ = [|TestClass.TestAccessor.ExposedField|]; - _ = [|TestClass.TestAccessor.ExposedProperty|]; - [|TestClass.TestAccessor.ExposedEvent|] += delegate { }; - [|TestClass.TestAccessor.ExposedMethod()|]; - } -}"; - - await VerifyCS.VerifyAnalyzerAsync(source); - } + public Task DoNotAccessTestAccessorStaticMember_CSharpAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System; + + class TestClass { + internal void Method() + { + _ = [|TestAccessor.ExposedField|]; + _ = [|TestAccessor.ExposedProperty|]; + [|TestAccessor.ExposedEvent|] += delegate { }; + [|TestAccessor.ExposedMethod()|]; + } + + internal TestAccessor GetTestAccessor() + { + return new TestAccessor(this); + } + + internal readonly struct TestAccessor + { + private readonly TestClass _testClass; + + internal TestAccessor(TestClass testClass) + { + _testClass = testClass; + } + + public static int ExposedField; + public static int ExposedProperty => 0; + public static event EventHandler ExposedEvent { add { } remove { } } + public static void ExposedMethod() { } + } + } + + class OtherClass { + internal void Method() + { + _ = [|TestClass.TestAccessor.ExposedField|]; + _ = [|TestClass.TestAccessor.ExposedProperty|]; + [|TestClass.TestAccessor.ExposedEvent|] += delegate { }; + [|TestClass.TestAccessor.ExposedMethod()|]; + } + } + """); [Fact] - public async Task DoNotAccessTestAccessorStaticMember_VisualBasicAsync() - { - var source = @" -Imports System - -Class TestClass - Friend Sub Method() - Dim a = [|TestAccessor.ExposedField|] - Dim b = [|TestAccessor.ExposedProperty|] - AddHandler [|TestAccessor.ExposedEvent|], Sub(_1, _2) Return - [|TestAccessor.ExposedMethod()|] - End Sub - - Friend Function GetTestAccessor() As TestAccessor - Return New TestAccessor(Me) - End Function - - Friend Structure TestAccessor - Private ReadOnly _testClass As TestClass - - Friend Sub New(testClass As TestClass) - _testClass = testClass - End Sub - - Public Shared ExposedField As Integer - Public Shared ReadOnly Property ExposedProperty As Integer = 0 - Public Shared Event ExposedEvent As EventHandler - - Public Shared Sub ExposedMethod() - End Sub - End Structure -End Class - -Class OtherClass - Friend Sub Method() - Dim a = [|TestClass.TestAccessor.ExposedField|] - Dim b = [|TestClass.TestAccessor.ExposedProperty|] - AddHandler [|TestClass.TestAccessor.ExposedEvent|], Sub(_1, _2) Return - [|TestClass.TestAccessor.ExposedMethod()|] - End Sub -End Class"; - - await VerifyVB.VerifyAnalyzerAsync(source); - } + public Task DoNotAccessTestAccessorStaticMember_VisualBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + Imports System + + Class TestClass + Friend Sub Method() + Dim a = [|TestAccessor.ExposedField|] + Dim b = [|TestAccessor.ExposedProperty|] + AddHandler [|TestAccessor.ExposedEvent|], Sub(_1, _2) Return + [|TestAccessor.ExposedMethod()|] + End Sub + + Friend Function GetTestAccessor() As TestAccessor + Return New TestAccessor(Me) + End Function + + Friend Structure TestAccessor + Private ReadOnly _testClass As TestClass + + Friend Sub New(testClass As TestClass) + _testClass = testClass + End Sub + + Public Shared ExposedField As Integer + Public Shared ReadOnly Property ExposedProperty As Integer = 0 + Public Shared Event ExposedEvent As EventHandler + + Public Shared Sub ExposedMethod() + End Sub + End Structure + End Class + + Class OtherClass + Friend Sub Method() + Dim a = [|TestClass.TestAccessor.ExposedField|] + Dim b = [|TestClass.TestAccessor.ExposedProperty|] + AddHandler [|TestClass.TestAccessor.ExposedEvent|], Sub(_1, _2) Return + [|TestClass.TestAccessor.ExposedMethod()|] + End Sub + End Class + """); } } diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/DoNotCopyValueTests.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/DoNotCopyValueTests.cs index 7dfef6e3e9188..ab563ff48b18b 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/DoNotCopyValueTests.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/DoNotCopyValueTests.cs @@ -19,50 +19,49 @@ namespace Roslyn.Diagnostics.Analyzers.UnitTests public class DoNotCopyValueTests { [Fact] - public async Task TestSliceOfStringAsync() - { - await new VerifyCS.Test + public Task TestSliceOfStringAsync() + => new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp9, - TestCode = @" -using System.Runtime.InteropServices; + TestCode = """ + using System.Runtime.InteropServices; -class C -{ - void M() - { - var local = """"[..]; - local = """"[..]; - } -} -", + class C + { + void M() + { + var local = ""[..]; + local = ""[..]; + } + } + """, }.RunAsync(); - } [Fact] public async Task TestAcquireFromReturnByValueAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -using System.Runtime.InteropServices; + await VerifyCS.VerifyAnalyzerAsync(""" + using System.Runtime.InteropServices; -class C -{ - void M() - { - var local = GCHandle.Alloc(new object()); - } -} -"); + class C + { + void M() + { + var local = GCHandle.Alloc(new object()); + } + } + """); - await VerifyVB.VerifyAnalyzerAsync(@" -Imports System.Runtime.InteropServices + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System.Runtime.InteropServices -Class C - Sub M() - Dim local = GCHandle.Alloc(New Object()) - End Sub -End Class"); + Class C + Sub M() + Dim local = GCHandle.Alloc(New Object()) + End Sub + End Class + """); } [Theory] @@ -72,34 +71,35 @@ End Sub [InlineData("Func>", "Func(Of ConfiguredTaskAwaitable(Of GCHandle))")] public async Task TestAcquireFromAwaitInvocationAsync(string csharpInvokeType, string visualBasicInvokeType) { - await VerifyCS.VerifyAnalyzerAsync($@" -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Threading.Tasks; + await VerifyCS.VerifyAnalyzerAsync($$""" + using System; + using System.Runtime.CompilerServices; + using System.Runtime.InteropServices; + using System.Threading.Tasks; -class C -{{ - async Task M({csharpInvokeType} d) - {{ - var local = await d(); - local = await d(); - }} -}} -"); - - await VerifyVB.VerifyAnalyzerAsync($@" -Imports System -Imports System.Runtime.CompilerServices -Imports System.Runtime.InteropServices -Imports System.Threading.Tasks - -Class C - Async Function M(d as {visualBasicInvokeType}) As Task - Dim local = Await d() - local = Await d() - End Function -End Class"); + class C + { + async Task M({{csharpInvokeType}} d) + { + var local = await d(); + local = await d(); + } + } + """); + + await VerifyVB.VerifyAnalyzerAsync($""" + Imports System + Imports System.Runtime.CompilerServices + Imports System.Runtime.InteropServices + Imports System.Threading.Tasks + + Class C + Async Function M(d as {visualBasicInvokeType}) As Task + Dim local = Await d() + local = Await d() + End Function + End Class + """); } [Theory] @@ -107,30 +107,31 @@ End Function [InlineData("ConfiguredValueTaskAwaitable", "ConfiguredValueTaskAwaitable(Of GCHandle)")] public async Task TestAcquireFromAwaitAsync(string csharpAwaitableType, string visualBasicAwaitableType) { - await VerifyCS.VerifyAnalyzerAsync($@" -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Threading.Tasks; + await VerifyCS.VerifyAnalyzerAsync($$""" + using System.Runtime.CompilerServices; + using System.Runtime.InteropServices; + using System.Threading.Tasks; -class C -{{ - async Task M({csharpAwaitableType} task) - {{ - var local = await task; - }} -}} -"); - - await VerifyVB.VerifyAnalyzerAsync($@" -Imports System.Runtime.CompilerServices -Imports System.Runtime.InteropServices -Imports System.Threading.Tasks - -Class C - Async Function M(task as {visualBasicAwaitableType}) As Task - Dim local = Await task - End Function -End Class"); + class C + { + async Task M({{csharpAwaitableType}} task) + { + var local = await task; + } + } + """); + + await VerifyVB.VerifyAnalyzerAsync($""" + Imports System.Runtime.CompilerServices + Imports System.Runtime.InteropServices + Imports System.Threading.Tasks + + Class C + Async Function M(task as {visualBasicAwaitableType}) As Task + Dim local = Await task + End Function + End Class + """); } [Theory] @@ -138,32 +139,33 @@ End Function [InlineData("ConfiguredTaskAwaitable", "ConfiguredTaskAwaitable(Of GCHandle)")] public async Task TestFailedAcquireFromUnsupportedAwaitAsync(string csharpAwaitableType, string visualBasicAwaitableType) { - await VerifyCS.VerifyAnalyzerAsync($@" -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Threading.Tasks; + await VerifyCS.VerifyAnalyzerAsync($$""" + using System.Runtime.CompilerServices; + using System.Runtime.InteropServices; + using System.Threading.Tasks; -class C -{{ - async Task M({csharpAwaitableType} task) - {{ - var local {{|#0:= await task|}}; - }} -}} -", + class C + { + async Task M({{csharpAwaitableType}} task) + { + var local {|#0:= await task|}; + } + } + """, // /0/Test0.cs(10,19): warning RS0042: Cannot assign a value from a reference to non-copyable type 'System.Runtime.InteropServices.GCHandle' VerifyCS.Diagnostic(AbstractDoNotCopyValue.NoAssignValueFromReferenceRule).WithLocation(0).WithArguments("System.Runtime.InteropServices.GCHandle")); - await VerifyVB.VerifyAnalyzerAsync($@" -Imports System.Runtime.CompilerServices -Imports System.Runtime.InteropServices -Imports System.Threading.Tasks - -Class C - Async Function M(task as {visualBasicAwaitableType}) As Task - Dim local {{|#0:= Await task|}} - End Function -End Class", + await VerifyVB.VerifyAnalyzerAsync($$""" + Imports System.Runtime.CompilerServices + Imports System.Runtime.InteropServices + Imports System.Threading.Tasks + + Class C + Async Function M(task as {{visualBasicAwaitableType}}) As Task + Dim local {|#0:= Await task|} + End Function + End Class + """, // /0/Test0.vb(8,19): warning RS0042: Cannot assign a value from a reference to non-copyable type 'System.Runtime.InteropServices.GCHandle' VerifyVB.Diagnostic(AbstractDoNotCopyValue.NoAssignValueFromReferenceRule).WithLocation(0).WithArguments("System.Runtime.InteropServices.GCHandle")); } @@ -176,34 +178,35 @@ End Function [InlineData("((C)this).field", "DirectCast(Me, C).field")] public async Task TestAcquireIntoFieldFromReturnByValueAsync(string csharpFieldReference, string? visualBasicFieldReference) { - await VerifyCS.VerifyAnalyzerAsync($@" -using System.Runtime.InteropServices; + await VerifyCS.VerifyAnalyzerAsync($$""" + using System.Runtime.InteropServices; -class C -{{ - GCHandle field; + class C + { + GCHandle field; - void M(bool condition) - {{ - {csharpFieldReference} = GCHandle.Alloc(new object()); - {csharpFieldReference} = condition ? GCHandle.Alloc(new object()) : GCHandle.Alloc(new object()); - }} -}} -"); + void M(bool condition) + { + {{csharpFieldReference}} = GCHandle.Alloc(new object()); + {{csharpFieldReference}} = condition ? GCHandle.Alloc(new object()) : GCHandle.Alloc(new object()); + } + } + """); if (visualBasicFieldReference is object) { - await VerifyVB.VerifyAnalyzerAsync($@" -Imports System.Runtime.InteropServices - -Class C - Dim field As GCHandle - - Sub M(condition As Boolean) - {visualBasicFieldReference} = GCHandle.Alloc(New Object()) - {visualBasicFieldReference} = If(condition, GCHandle.Alloc(New Object()), GCHandle.Alloc(New Object())) - End Sub -End Class"); + await VerifyVB.VerifyAnalyzerAsync($""" + Imports System.Runtime.InteropServices + + Class C + Dim field As GCHandle + + Sub M(condition As Boolean) + {visualBasicFieldReference} = GCHandle.Alloc(New Object()) + {visualBasicFieldReference} = If(condition, GCHandle.Alloc(New Object()), GCHandle.Alloc(New Object())) + End Sub + End Class + """); } } @@ -215,177 +218,171 @@ End Sub [InlineData("((C)this).field", "DirectCast(Me, C).field")] public async Task TestAcquireIntoArrayFieldFromReturnByValueAsync(string csharpFieldReference, string? visualBasicFieldReference) { - await VerifyCS.VerifyAnalyzerAsync($@" -using System.Runtime.InteropServices; + await VerifyCS.VerifyAnalyzerAsync($$""" + using System.Runtime.InteropServices; -class C -{{ - GCHandle[] field; + class C + { + GCHandle[] field; - void M() - {{ - {csharpFieldReference}[0] = GCHandle.Alloc(new object()); - }} -}} -"); + void M() + { + {{csharpFieldReference}}[0] = GCHandle.Alloc(new object()); + } + } + """); if (visualBasicFieldReference is object) { - await VerifyVB.VerifyAnalyzerAsync($@" -Imports System.Runtime.InteropServices + await VerifyVB.VerifyAnalyzerAsync($""" + Imports System.Runtime.InteropServices -Class C - Dim field As GCHandle() + Class C + Dim field As GCHandle() - Sub M() - {visualBasicFieldReference}(0) = GCHandle.Alloc(New Object()) - End Sub -End Class"); + Sub M() + {visualBasicFieldReference}(0) = GCHandle.Alloc(New Object()) + End Sub + End Class + """); } } [Fact] - public async Task TestDoNotAcquireFromReturnByReferenceAsync() - { - await VerifyCS.VerifyAnalyzerAsync(@" -using System.Runtime.InteropServices; + public Task TestDoNotAcquireFromReturnByReferenceAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System.Runtime.InteropServices; -class C -{ - void M() - { - var local {|#0:= GetRef()|}; - } + class C + { + void M() + { + var local {|#0:= GetRef()|}; + } - ref GCHandle GetRef() => throw null; -} -", + ref GCHandle GetRef() => throw null; + } + """, // /0/Test0.cs(8,19): warning RS0042: Cannot assign a value from a reference to non-copyable type 'System.Runtime.InteropServices.GCHandle' VerifyCS.Diagnostic(AbstractDoNotCopyValue.NoAssignValueFromReferenceRule).WithLocation(0).WithArguments("System.Runtime.InteropServices.GCHandle")); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/77925")] - public async Task TestPassToInstancePropertyGetterAsync() - { - await VerifyCS.VerifyAnalyzerAsync(@" -using System.Runtime.InteropServices; + public Task TestPassToInstancePropertyGetterAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System.Runtime.InteropServices; -class C -{ - GCHandle field; - readonly GCHandle readonlyfield; + class C + { + GCHandle field; + readonly GCHandle readonlyfield; - void M() - { - var local = new GCHandle(); - ref var reflocal = ref local; - ref readonly var refreadonlylocal = ref local; - - // Call each proprety twice to ensure the analyzer didn't silently treat one like a move - _ = field.Target; - _ = field.Target; - _ = local.Target; - _ = local.Target; - _ = reflocal.Target; - _ = reflocal.Target; - - _ = {|#0:readonlyfield|}.Target; - _ = {|#1:refreadonlylocal|}.Target; - } -} -", + void M() + { + var local = new GCHandle(); + ref var reflocal = ref local; + ref readonly var refreadonlylocal = ref local; + + // Call each proprety twice to ensure the analyzer didn't silently treat one like a move + _ = field.Target; + _ = field.Target; + _ = local.Target; + _ = local.Target; + _ = reflocal.Target; + _ = reflocal.Target; + + _ = {|#0:readonlyfield|}.Target; + _ = {|#1:refreadonlylocal|}.Target; + } + } + """, // /0/Test0.cs(23,13): warning RS0042: Unsupported use of non-copyable type 'System.Runtime.InteropServices.GCHandle' in 'FieldReference' operation VerifyCS.Diagnostic(AbstractDoNotCopyValue.UnsupportedUseRule).WithLocation(0).WithArguments("System.Runtime.InteropServices.GCHandle", "FieldReference"), // /0/Test0.cs(17,13): warning RS0042: Unsupported use of non-copyable type 'System.Runtime.InteropServices.GCHandle' in 'LocalReference' operation VerifyCS.Diagnostic(AbstractDoNotCopyValue.UnsupportedUseRule).WithLocation(1).WithArguments("System.Runtime.InteropServices.GCHandle", "LocalReference")); - } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/77925")] - public async Task TestPassToInstanceMethodAsync() - { - await VerifyCS.VerifyAnalyzerAsync(@" -using System.Runtime.InteropServices; + public Task TestPassToInstanceMethodAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System.Runtime.InteropServices; -class C -{ - GCHandle field; - readonly GCHandle readonlyfield; + class C + { + GCHandle field; + readonly GCHandle readonlyfield; - void M() - { - var local = new GCHandle(); - ref var reflocal = ref local; - ref readonly var refreadonlylocal = ref local; - - // Call each method twice to ensure the analyzer didn't silently treat one like a move - _ = field.AddrOfPinnedObject(); - _ = field.AddrOfPinnedObject(); - _ = local.AddrOfPinnedObject(); - _ = local.AddrOfPinnedObject(); - _ = reflocal.AddrOfPinnedObject(); - _ = reflocal.AddrOfPinnedObject(); - - _ = {|#0:readonlyfield|}.AddrOfPinnedObject(); - _ = {|#1:refreadonlylocal|}.AddrOfPinnedObject(); - } -} -", + void M() + { + var local = new GCHandle(); + ref var reflocal = ref local; + ref readonly var refreadonlylocal = ref local; + + // Call each method twice to ensure the analyzer didn't silently treat one like a move + _ = field.AddrOfPinnedObject(); + _ = field.AddrOfPinnedObject(); + _ = local.AddrOfPinnedObject(); + _ = local.AddrOfPinnedObject(); + _ = reflocal.AddrOfPinnedObject(); + _ = reflocal.AddrOfPinnedObject(); + + _ = {|#0:readonlyfield|}.AddrOfPinnedObject(); + _ = {|#1:refreadonlylocal|}.AddrOfPinnedObject(); + } + } + """, // /0/Test0.cs(23,13): warning RS0042: Unsupported use of non-copyable type 'System.Runtime.InteropServices.GCHandle' in 'FieldReference' operation VerifyCS.Diagnostic(AbstractDoNotCopyValue.UnsupportedUseRule).WithLocation(0).WithArguments("System.Runtime.InteropServices.GCHandle", "FieldReference"), // /0/Test0.cs(17,13): warning RS0042: Unsupported use of non-copyable type 'System.Runtime.InteropServices.GCHandle' in 'LocalReference' operation VerifyCS.Diagnostic(AbstractDoNotCopyValue.UnsupportedUseRule).WithLocation(1).WithArguments("System.Runtime.InteropServices.GCHandle", "LocalReference")); - } [Fact] - public async Task TestPassToExtensionMethodAsync() - { - await VerifyCS.VerifyAnalyzerAsync(@" -using System.Runtime.InteropServices; + public Task TestPassToExtensionMethodAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System.Runtime.InteropServices; -class C -{ - GCHandle field; - readonly GCHandle readonlyfield; + class C + { + GCHandle field; + readonly GCHandle readonlyfield; - void M() - { - var local = new GCHandle(); - ref var reflocal = ref local; - ref readonly var refreadonlylocal = ref local; - - // Success cases. Call each method twice to ensure the analyzer didn't silently treat one like a move. - field.XRef(); - field.XRef(); - local.XRef(); - local.XRef(); - reflocal.XRef(); - reflocal.XRef(); - - readonlyfield.XIn(); - readonlyfield.XIn(); - reflocal.XIn(); - reflocal.XIn(); - local.XIn(); - local.XIn(); - - // Failure cases. - {|#0:{|CS0192:readonlyfield|}|}.XRef(); - {|#1:{|CS1510:refreadonlylocal|}|}.XRef(); - {|#2:field|}.X(); - {|#3:readonlyfield|}.X(); - {|#4:local|}.X(); - {|#5:reflocal|}.X(); - {|#6:refreadonlylocal|}.X(); - } -} + void M() + { + var local = new GCHandle(); + ref var reflocal = ref local; + ref readonly var refreadonlylocal = ref local; + + // Success cases. Call each method twice to ensure the analyzer didn't silently treat one like a move. + field.XRef(); + field.XRef(); + local.XRef(); + local.XRef(); + reflocal.XRef(); + reflocal.XRef(); + + readonlyfield.XIn(); + readonlyfield.XIn(); + reflocal.XIn(); + reflocal.XIn(); + local.XIn(); + local.XIn(); + + // Failure cases. + {|#0:{|CS0192:readonlyfield|}|}.XRef(); + {|#1:{|CS1510:refreadonlylocal|}|}.XRef(); + {|#2:field|}.X(); + {|#3:readonlyfield|}.X(); + {|#4:local|}.X(); + {|#5:reflocal|}.X(); + {|#6:refreadonlylocal|}.X(); + } + } -static class E -{ - public static void X(this GCHandle handle) { } - public static void XRef(this ref GCHandle handle) { } - public static void XIn(this in GCHandle handle) { } -} -", + static class E + { + public static void X(this GCHandle handle) { } + public static void XRef(this ref GCHandle handle) { } + public static void XIn(this in GCHandle handle) { } + } + """, // /0/Test0.cs(31,9): warning RS0042: Unsupported use of non-copyable type 'System.Runtime.InteropServices.GCHandle' in 'FieldReference' operation VerifyCS.Diagnostic(AbstractDoNotCopyValue.UnsupportedUseRule).WithLocation(0).WithArguments("System.Runtime.InteropServices.GCHandle", "FieldReference"), // /0/Test0.cs(32,9): warning RS0042: Unsupported use of non-copyable type 'System.Runtime.InteropServices.GCHandle' in 'LocalReference' operation @@ -400,221 +397,208 @@ public static void XIn(this in GCHandle handle) { } VerifyCS.Diagnostic(AbstractDoNotCopyValue.UnsupportedUseRule).WithLocation(5).WithArguments("System.Runtime.InteropServices.GCHandle", "LocalReference"), // /0/Test0.cs(37,9): warning RS0042: Unsupported use of non-copyable type 'System.Runtime.InteropServices.GCHandle' in 'LocalReference' operation VerifyCS.Diagnostic(AbstractDoNotCopyValue.UnsupportedUseRule).WithLocation(6).WithArguments("System.Runtime.InteropServices.GCHandle", "LocalReference")); - } [Theory] [InlineData("throw null")] [InlineData("(true ? throw null : default(GCHandle))")] [InlineData("(false ? new GCHandle() : throw null)")] - public async Task TestConversionFromThrowNullAsync(string throwExpression) - { - await VerifyCS.VerifyAnalyzerAsync($@" -using System.Runtime.InteropServices; - -class C -{{ - GCHandle Get() => {throwExpression}; -}} -"); - } + public Task TestConversionFromThrowNullAsync(string throwExpression) + => VerifyCS.VerifyAnalyzerAsync($$""" + using System.Runtime.InteropServices; + + class C + { + GCHandle Get() => {{throwExpression}}; + } + """); [Fact] public async Task TestPassByReferenceAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -using System.Runtime.InteropServices; + await VerifyCS.VerifyAnalyzerAsync(""" + using System.Runtime.InteropServices; -class C -{ - void Get(ref GCHandle handle) => Get(ref handle); -} -"); + class C + { + void Get(ref GCHandle handle) => Get(ref handle); + } + """); - await VerifyVB.VerifyAnalyzerAsync(@" -Imports System.Runtime.InteropServices + await VerifyVB.VerifyAnalyzerAsync(""" + Imports System.Runtime.InteropServices -Class C - Sub Method(ByRef handle As GCHandle) - Method(handle) - End Sub -End Class"); + Class C + Sub Method(ByRef handle As GCHandle) + Method(handle) + End Sub + End Class + """); } [Fact] - public async Task TestPassByReadOnlyReferenceAsync() - { - await VerifyCS.VerifyAnalyzerAsync(@" -using System.Runtime.InteropServices; + public Task TestPassByReadOnlyReferenceAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System.Runtime.InteropServices; -class C -{ - void Get(in GCHandle handle) => Get(in handle); -} -"); - } + class C + { + void Get(in GCHandle handle) => Get(in handle); + } + """); [Fact] - public async Task TestAssignToMemberAsync() - { - await VerifyCS.VerifyAnalyzerAsync(@" -using System.Runtime.InteropServices; + public Task TestAssignToMemberAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System.Runtime.InteropServices; -class C -{ - CannotCopy _field; + class C + { + CannotCopy _field; - void Method(CannotCopy parameter) - { - CannotCopy local = new CannotCopy(); + void Method(CannotCopy parameter) + { + CannotCopy local = new CannotCopy(); - _field.Field = 0; - parameter.Field = 0; - local.Field = 0; + _field.Field = 0; + parameter.Field = 0; + local.Field = 0; - _field.Property = 0; - parameter.Property = 0; - local.Property = 0; - } -} + _field.Property = 0; + parameter.Property = 0; + local.Property = 0; + } + } -[NonCopyable] -struct CannotCopy -{ - public int Field; - public int Property { get; set; } -} + [NonCopyable] + struct CannotCopy + { + public int Field; + public int Property { get; set; } + } -internal sealed class NonCopyableAttribute : System.Attribute { } -"); - } + internal sealed class NonCopyableAttribute : System.Attribute { } + """); [Fact] - public async Task ReturnLocalByValueAsync() - { - var source = @" -using System.Runtime.InteropServices; - -class C -{ - GCHandle Method() - { - GCHandle handle = default; - return handle; - } -} -"; - - await new VerifyCS.Test + public Task ReturnLocalByValueAsync() + => new VerifyCS.Test { - TestCode = source, + TestCode = """ + using System.Runtime.InteropServices; + + class C + { + GCHandle Method() + { + GCHandle handle = default; + return handle; + } + } + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] - public async Task TestReturnMemberAsync() - { - var source = @" -using System.Runtime.InteropServices; - -class C -{ - CannotCopy _field; - readonly CannotCopy _readonlyField; + public Task TestReturnMemberAsync() + => new VerifyCS.Test + { + TestCode = """ + using System.Runtime.InteropServices; - int ReturnFieldMemberField() - { - return _field.Field; - } + class C + { + CannotCopy _field; + readonly CannotCopy _readonlyField; - int ReturnReadonlyFieldMemberField() - { - return _readonlyField.Field; - } + int ReturnFieldMemberField() + { + return _field.Field; + } - int ReturnParameterMemberField(CannotCopy parameter) - { - return parameter.Field; - } + int ReturnReadonlyFieldMemberField() + { + return _readonlyField.Field; + } - int ReturnArrayParameterMemberField(CannotCopy[] parameter) - { - return parameter[0].Field; - } + int ReturnParameterMemberField(CannotCopy parameter) + { + return parameter.Field; + } - int ReturnLocalMemberField() - { - CannotCopy local = new CannotCopy(); - return local.Field; - } + int ReturnArrayParameterMemberField(CannotCopy[] parameter) + { + return parameter[0].Field; + } - int ReturnFieldMemberProperty() - { - return _field.Property; - } + int ReturnLocalMemberField() + { + CannotCopy local = new CannotCopy(); + return local.Field; + } - int ReturnReadonlyFieldMemberProperty() - { - return {|#0:_readonlyField|}.Property; - } + int ReturnFieldMemberProperty() + { + return _field.Property; + } - int ReturnParameterMemberProperty(CannotCopy parameter) - { - return parameter.Property; - } + int ReturnReadonlyFieldMemberProperty() + { + return {|#0:_readonlyField|}.Property; + } - int ReturnArrayParameterMemberProperty(CannotCopy[] parameter) - { - return parameter[0].Property; - } + int ReturnParameterMemberProperty(CannotCopy parameter) + { + return parameter.Property; + } - int ReturnLocalMemberProperty() - { - CannotCopy local = new CannotCopy(); - return local.Property; - } + int ReturnArrayParameterMemberProperty(CannotCopy[] parameter) + { + return parameter[0].Property; + } - int ReturnFieldMemberReadonlyProperty() - { - return _field.ReadonlyProperty; - } + int ReturnLocalMemberProperty() + { + CannotCopy local = new CannotCopy(); + return local.Property; + } - int ReturnReadonlyFieldMemberReadonlyProperty() - { - return _readonlyField.ReadonlyProperty; - } + int ReturnFieldMemberReadonlyProperty() + { + return _field.ReadonlyProperty; + } - int ReturnParameterMemberReadonlyProperty(CannotCopy parameter) - { - return parameter.ReadonlyProperty; - } + int ReturnReadonlyFieldMemberReadonlyProperty() + { + return _readonlyField.ReadonlyProperty; + } - int ReturnArrayParameterMemberReadonlyProperty(CannotCopy[] parameter) - { - return parameter[0].ReadonlyProperty; - } + int ReturnParameterMemberReadonlyProperty(CannotCopy parameter) + { + return parameter.ReadonlyProperty; + } - int ReturnLocalMemberReadonlyProperty() - { - CannotCopy local = new CannotCopy(); - return local.ReadonlyProperty; - } -} + int ReturnArrayParameterMemberReadonlyProperty(CannotCopy[] parameter) + { + return parameter[0].ReadonlyProperty; + } -[NonCopyable] -struct CannotCopy -{ - public int Field; - public int Property { get { return 0; } } - public int ReadonlyProperty { readonly get { return 0; } set { } } -} + int ReturnLocalMemberReadonlyProperty() + { + CannotCopy local = new CannotCopy(); + return local.ReadonlyProperty; + } + } -internal sealed class NonCopyableAttribute : System.Attribute { } -"; + [NonCopyable] + struct CannotCopy + { + public int Field; + public int Property { get { return 0; } } + public int ReadonlyProperty { readonly get { return 0; } set { } } + } - await new VerifyCS.Test - { - TestCode = source, + internal sealed class NonCopyableAttribute : System.Attribute { } + """, ExpectedDiagnostics = { // The only reported diagnostic occurs for the invocation of a non-readonly getter of a readonly @@ -625,129 +609,108 @@ internal sealed class NonCopyableAttribute : System.Attribute { } }, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] - public async Task NonReadonlyMemberPropertiesAsync() - { - // Verify that a non-readonly member of a non-copyable type can reference another non-readonly member of the - // same type. - var source = @" -using System.Runtime.InteropServices; - -[NonCopyable] -struct CannotCopy -{ - public int First { get { return 0; } } - public int Second { get { return First; } } - public int Third => First; -} + public Task NonReadonlyMemberPropertiesAsync() + => new VerifyCS.Test + { + TestCode = """ + using System.Runtime.InteropServices; -internal sealed class NonCopyableAttribute : System.Attribute { } -"; + [NonCopyable] + struct CannotCopy + { + public int First { get { return 0; } } + public int Second { get { return First; } } + public int Third => First; + } - await new VerifyCS.Test - { - TestCode = source, + internal sealed class NonCopyableAttribute : System.Attribute { } + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] - public async Task NonReadonlyMemberMethodsAsync() - { - // Verify that a non-readonly member of a non-copyable type can reference another non-readonly member of the - // same type. - var source = @" -using System.Runtime.InteropServices; - -[NonCopyable] -struct CannotCopy -{ - public int First() { return 0; } - public int Second() { return First(); } - public int Third() => First(); -} + public Task NonReadonlyMemberMethodsAsync() + => new VerifyCS.Test + { + TestCode = """ + using System.Runtime.InteropServices; -internal sealed class NonCopyableAttribute : System.Attribute { } -"; + [NonCopyable] + struct CannotCopy + { + public int First() { return 0; } + public int Second() { return First(); } + public int Third() => First(); + } - await new VerifyCS.Test - { - TestCode = source, + internal sealed class NonCopyableAttribute : System.Attribute { } + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] - public async Task AllowObjectInitializerAsync() - { - var source = @" -using System.Runtime.InteropServices; - -class C -{ - CannotCopy Method() - { - return new CannotCopy() { First = 0, Second = 1 }; - } -} + public Task AllowObjectInitializerAsync() + => new VerifyCS.Test + { + TestCode = """ + using System.Runtime.InteropServices; -[NonCopyable] -struct CannotCopy -{ - public int First { get; set; } - public int Second { get; set; } -} + class C + { + CannotCopy Method() + { + return new CannotCopy() { First = 0, Second = 1 }; + } + } -internal sealed class NonCopyableAttribute : System.Attribute { } -"; + [NonCopyable] + struct CannotCopy + { + public int First { get; set; } + public int Second { get; set; } + } - await new VerifyCS.Test - { - TestCode = source, + internal sealed class NonCopyableAttribute : System.Attribute { } + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] - public async Task AllowCustomForeachEnumeratorAsync() - { - var source = @" -using System.Runtime.InteropServices; - -class C -{ - void Method() - { - var cannotCopy = new CannotCopy(); - foreach (var obj in cannotCopy) - { - } - } -} + public Task AllowCustomForeachEnumeratorAsync() + => new VerifyCS.Test + { + TestCode = """ + using System.Runtime.InteropServices; -[NonCopyable] -struct CannotCopy -{ - public Enumerator GetEnumerator() => throw null; + class C + { + void Method() + { + var cannotCopy = new CannotCopy(); + foreach (var obj in cannotCopy) + { + } + } + } - public struct Enumerator - { - public object Current => throw null; - public bool MoveNext() => throw null; - } -} + [NonCopyable] + struct CannotCopy + { + public Enumerator GetEnumerator() => throw null; -internal sealed class NonCopyableAttribute : System.Attribute { } -"; + public struct Enumerator + { + public object Current => throw null; + public bool MoveNext() => throw null; + } + } - await new VerifyCS.Test - { - TestCode = source, + internal sealed class NonCopyableAttribute : System.Attribute { } + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, }.RunAsync(); - } [Theory] [CombinatorialData] @@ -755,45 +718,43 @@ public async Task AllowCustomForeachEnumeratorParameterReferenceAsync( [CombinatorialValues("", "ref", "in")] string parameterModifiers, [CombinatorialValues("", "readonly")] string getEnumeratorModifiers) { - var source = $@" -using System.Runtime.InteropServices; - -class C -{{ - void Method({parameterModifiers} CannotCopy cannotCopy) - {{ - foreach (var obj in {{|#0:cannotCopy|}}) - {{ - }} - }} -}} - -[NonCopyable] -struct CannotCopy -{{ - public {getEnumeratorModifiers} Enumerator GetEnumerator() => throw null; - - public struct Enumerator - {{ - public object Current => throw null; - public bool MoveNext() => throw null; - }} -}} - -internal sealed class NonCopyableAttribute : System.Attribute {{ }} -"; - var expected = (parameterModifiers, getEnumeratorModifiers) switch { // /0/Test0.cs(8,29): warning RS0042: Unsupported use of non-copyable type 'CannotCopy' in 'ParameterReference' operation - ("in", "") => new[] { VerifyCS.Diagnostic(AbstractDoNotCopyValue.UnsupportedUseRule).WithLocation(0).WithArguments("CannotCopy", "ParameterReference") }, + ("in", "") => [VerifyCS.Diagnostic(AbstractDoNotCopyValue.UnsupportedUseRule).WithLocation(0).WithArguments("CannotCopy", "ParameterReference")], _ => DiagnosticResult.EmptyDiagnosticResults, }; var test = new VerifyCS.Test { - TestCode = source, + TestCode = $$""" + using System.Runtime.InteropServices; + + class C + { + void Method({{parameterModifiers}} CannotCopy cannotCopy) + { + foreach (var obj in {|#0:cannotCopy|}) + { + } + } + } + + [NonCopyable] + struct CannotCopy + { + public {{getEnumeratorModifiers}} Enumerator GetEnumerator() => throw null; + + public struct Enumerator + { + public object Current => throw null; + public bool MoveNext() => throw null; + } + } + + internal sealed class NonCopyableAttribute : System.Attribute { } + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, }; @@ -802,289 +763,261 @@ internal sealed class NonCopyableAttribute : System.Attribute {{ }} } [Fact] - public async Task AllowCustomForeachEnumeratorDisposableObject1Async() - { - var source = @" -using System; -using System.Runtime.InteropServices; - -class C -{ - void Method() - { - using var cannotCopy = new CannotCopy(); - foreach (var obj in cannotCopy) - { - } - } -} - -[NonCopyable] -struct CannotCopy : IDisposable -{ - public void Dispose() => throw null; - public Enumerator GetEnumerator() => throw null; + public Task AllowCustomForeachEnumeratorDisposableObject1Async() + => new VerifyCS.Test + { + TestCode = """ + using System; + using System.Runtime.InteropServices; - public struct Enumerator - { - public object Current => throw null; - public bool MoveNext() => throw null; - } -} + class C + { + void Method() + { + using var cannotCopy = new CannotCopy(); + foreach (var obj in cannotCopy) + { + } + } + } -internal sealed class NonCopyableAttribute : System.Attribute { } -"; + [NonCopyable] + struct CannotCopy : IDisposable + { + public void Dispose() => throw null; + public Enumerator GetEnumerator() => throw null; - await new VerifyCS.Test - { - TestCode = source, + public struct Enumerator + { + public object Current => throw null; + public bool MoveNext() => throw null; + } + } + + internal sealed class NonCopyableAttribute : System.Attribute { } + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] - public async Task AllowCustomForeachEnumeratorDisposableObject2Async() - { - var source = @" -using System; -using System.Runtime.InteropServices; - -class C -{ - void Method() - { - using (var cannotCopy = new CannotCopy()) - { - foreach (var obj in cannotCopy) + public Task AllowCustomForeachEnumeratorDisposableObject2Async() + => new VerifyCS.Test { - } - } - } -} + TestCode = """ + using System; + using System.Runtime.InteropServices; -[NonCopyable] -struct CannotCopy : IDisposable -{ - public void Dispose() => throw null; - public Enumerator GetEnumerator() => throw null; + class C + { + void Method() + { + using (var cannotCopy = new CannotCopy()) + { + foreach (var obj in cannotCopy) + { + } + } + } + } - public struct Enumerator - { - public object Current => throw null; - public bool MoveNext() => throw null; - } -} + [NonCopyable] + struct CannotCopy : IDisposable + { + public void Dispose() => throw null; + public Enumerator GetEnumerator() => throw null; -internal sealed class NonCopyableAttribute : System.Attribute { } -"; + public struct Enumerator + { + public object Current => throw null; + public bool MoveNext() => throw null; + } + } - await new VerifyCS.Test - { - TestCode = source, + internal sealed class NonCopyableAttribute : System.Attribute { } + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, }.RunAsync(); - } [Theory] [InlineData("new CannotCopy()")] [InlineData("default(CannotCopy)")] [InlineData("CannotCopy.Create()")] [InlineData("CannotCopy.Empty")] - public async Task AllowDisposableObjectAsync(string creation) - { - var source = $@" -using System; -using System.Runtime.InteropServices; - -class C -{{ - void UsingStatement() - {{ - using ({creation}) - {{ - }} - }} - - void UsingStatementWithVariable() - {{ - using (var cannotCopy = {creation}) - {{ - }} - }} - - void UsingStatementWithDiscard() - {{ - using (_ = {creation}) - {{ - }} - }} - - void UsingDeclarationStatement() - {{ - using var cannotCopy = {creation}; - }} -}} - -[NonCopyable] -struct CannotCopy : IDisposable -{{ - public static CannotCopy Empty => throw null; - public static CannotCopy Create() => throw null; - - public void Dispose() => throw null; -}} - -internal sealed class NonCopyableAttribute : System.Attribute {{ }} -"; - - await new VerifyCS.Test + public Task AllowDisposableObjectAsync(string creation) + => new VerifyCS.Test { - TestCode = source, + TestCode = $$""" + using System; + using System.Runtime.InteropServices; + + class C + { + void UsingStatement() + { + using ({{creation}}) + { + } + } + + void UsingStatementWithVariable() + { + using (var cannotCopy = {{creation}}) + { + } + } + + void UsingStatementWithDiscard() + { + using (_ = {{creation}}) + { + } + } + + void UsingDeclarationStatement() + { + using var cannotCopy = {{creation}}; + } + } + + [NonCopyable] + struct CannotCopy : IDisposable + { + public static CannotCopy Empty => throw null; + public static CannotCopy Create() => throw null; + + public void Dispose() => throw null; + } + + internal sealed class NonCopyableAttribute : System.Attribute { } + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] - public async Task AllowCustomForeachReadonlyEnumeratorAsync() - { - var source = @" -using System.Runtime.InteropServices; - -class C -{ - void Method() - { - var cannotCopy = new CannotCopy(); - foreach (var obj in cannotCopy) - { - } - } -} + public Task AllowCustomForeachReadonlyEnumeratorAsync() + => new VerifyCS.Test + { + TestCode = """ + using System.Runtime.InteropServices; -[NonCopyable] -struct CannotCopy -{ - public readonly Enumerator GetEnumerator() => throw null; + class C + { + void Method() + { + var cannotCopy = new CannotCopy(); + foreach (var obj in cannotCopy) + { + } + } + } - public struct Enumerator - { - public object Current => throw null; - public bool MoveNext() => throw null; - } -} + [NonCopyable] + struct CannotCopy + { + public readonly Enumerator GetEnumerator() => throw null; -internal sealed class NonCopyableAttribute : System.Attribute { } -"; + public struct Enumerator + { + public object Current => throw null; + public bool MoveNext() => throw null; + } + } - await new VerifyCS.Test - { - TestCode = source, + internal sealed class NonCopyableAttribute : System.Attribute { } + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, }.RunAsync(); - } [Theory] [InlineData("")] [InlineData("ref")] [InlineData("in")] - public async Task AllowNameOfParameterReferenceAsync(string parameterModifiers) - { - var source = $@" -using System.Runtime.InteropServices; - -class C -{{ - void Method({parameterModifiers} CannotCopy value) - {{ - _ = nameof(CannotCopy); - _ = nameof(value); - _ = nameof(value.ToString); - }} -}} - -[NonCopyable] -struct CannotCopy -{{ -}} - -internal sealed class NonCopyableAttribute : System.Attribute {{ }} -"; - - await new VerifyCS.Test + public Task AllowNameOfParameterReferenceAsync(string parameterModifiers) + => new VerifyCS.Test { - TestCode = source, + TestCode = $$""" + using System.Runtime.InteropServices; + + class C + { + void Method({{parameterModifiers}} CannotCopy value) + { + _ = nameof(CannotCopy); + _ = nameof(value); + _ = nameof(value.ToString); + } + } + + [NonCopyable] + struct CannotCopy + { + } + + internal sealed class NonCopyableAttribute : System.Attribute { } + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, }.RunAsync(); - } [Theory] [InlineData("ref")] [InlineData("in")] - public async Task AllowUnsafeAsRefParameterReferenceAsync(string parameterModifiers) - { - var source = $@" -using System.Runtime.InteropServices; - -class C -{{ - ref CannotCopy Method({parameterModifiers} CannotCopy cannotCopy) - {{ - return ref AsRef(in cannotCopy); - }} + public Task AllowUnsafeAsRefParameterReferenceAsync(string parameterModifiers) + => new VerifyCS.Test + { + TestCode = $$""" + using System.Runtime.InteropServices; - ref T AsRef(in T value) - => throw null; -}} + class C + { + ref CannotCopy Method({{parameterModifiers}} CannotCopy cannotCopy) + { + return ref AsRef(in cannotCopy); + } -[NonCopyable] -struct CannotCopy -{{ -}} + ref T AsRef(in T value) + => throw null; + } -internal sealed class NonCopyableAttribute : System.Attribute {{ }} -"; + [NonCopyable] + struct CannotCopy + { + } - await new VerifyCS.Test - { - TestCode = source, + internal sealed class NonCopyableAttribute : System.Attribute { } + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, }.RunAsync(); - } [Theory] [CombinatorialData] - public async Task AllowUnsafeAsRefParameterReference2Async( + public Task AllowUnsafeAsRefParameterReference2Async( [CombinatorialValues("ref", "in", "ref readonly")] string parameterModifiers, [CombinatorialValues("in", "scoped in", "ref readonly", "scoped ref readonly")] string asRefParameterModifiers) - { - var source = $@" -using System.Runtime.InteropServices; - -class C -{{ - ref CannotCopy Method({parameterModifiers} CannotCopy cannotCopy) - {{ - return ref AsRef(in cannotCopy); - }} + => new VerifyCS.Test + { + TestCode = $$""" + using System.Runtime.InteropServices; - ref T AsRef({asRefParameterModifiers} T value) - => throw null; -}} + class C + { + ref CannotCopy Method({{parameterModifiers}} CannotCopy cannotCopy) + { + return ref AsRef(in cannotCopy); + } -[NonCopyable] -struct CannotCopy -{{ -}} + ref T AsRef({{asRefParameterModifiers}} T value) + => throw null; + } -internal sealed class NonCopyableAttribute : System.Attribute {{ }} -"; + [NonCopyable] + struct CannotCopy + { + } - await new VerifyCS.Test - { - TestCode = source, + internal sealed class NonCopyableAttribute : System.Attribute { } + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp12, }.RunAsync(); - } [Theory] [InlineData("ref")] @@ -1096,74 +1029,68 @@ public async Task StoreUnsafeAsRefParameterReferenceToLocalAsync(string paramete "in" => "ref readonly", _ => parameterModifiers, }; + await new VerifyCS.Test + { + TestCode = $$""" + using System.Runtime.InteropServices; - var source = $@" -using System.Runtime.InteropServices; - -class C -{{ - void Method({parameterModifiers} CannotCopy cannotCopy) - {{ - {localModifiers} var local = ref AsRef(in cannotCopy); - - local = ref AsRef(in cannotCopy); - }} + class C + { + void Method({{parameterModifiers}} CannotCopy cannotCopy) + { + {{localModifiers}} var local = ref AsRef(in cannotCopy); - ref T AsRef(in T value) - => throw null; -}} + local = ref AsRef(in cannotCopy); + } -[NonCopyable] -struct CannotCopy -{{ -}} + ref T AsRef(in T value) + => throw null; + } -internal sealed class NonCopyableAttribute : System.Attribute {{ }} -"; + [NonCopyable] + struct CannotCopy + { + } - await new VerifyCS.Test - { - TestCode = source, + internal sealed class NonCopyableAttribute : System.Attribute { } + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, }.RunAsync(); } [Fact] - public async Task CannotStoreRefReturnByValueAsync() - { - var source = $@" -using System.Runtime.InteropServices; - -class C -{{ - void Method(in CannotCopy cannotCopy) - {{ - // Test with initializer - var local {{|#0:= AsRef(in cannotCopy)|}}; + public Task CannotStoreRefReturnByValueAsync() + => new VerifyCS.Test + { + TestCode = $$""" + using System.Runtime.InteropServices; - // Test with assignment to local - local = {{|#1:AsRef(in cannotCopy)|}}; + class C + { + void Method(in CannotCopy cannotCopy) + { + // Test with initializer + var local {|#0:= AsRef(in cannotCopy)|}; - // Implicit and explicit discard is acceptable - AsRef(in cannotCopy); - _ = AsRef(in cannotCopy); - }} + // Test with assignment to local + local = {|#1:AsRef(in cannotCopy)|}; - ref T AsRef(in T value) - => throw null; -}} + // Implicit and explicit discard is acceptable + AsRef(in cannotCopy); + _ = AsRef(in cannotCopy); + } -[NonCopyable] -struct CannotCopy -{{ -}} + ref T AsRef(in T value) + => throw null; + } -internal sealed class NonCopyableAttribute : System.Attribute {{ }} -"; + [NonCopyable] + struct CannotCopy + { + } - await new VerifyCS.Test - { - TestCode = source, + internal sealed class NonCopyableAttribute : System.Attribute { } + """, ExpectedDiagnostics = { // /0/Test0.cs(8,19): warning RS0042: Cannot assign a value from a reference to non-copyable type 'CannotCopy' @@ -1173,36 +1100,32 @@ internal sealed class NonCopyableAttribute : System.Attribute {{ }} }, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] - public async Task CannotReturnRefReturnByValueAsync() - { - var source = $@" -using System.Runtime.InteropServices; - -class C -{{ - CannotCopy Method(in CannotCopy cannotCopy) - {{ - return {{|#0:AsRef(in cannotCopy)|}}; - }} + public Task CannotReturnRefReturnByValueAsync() + => new VerifyCS.Test + { + TestCode = $$""" + using System.Runtime.InteropServices; - ref T AsRef(in T value) - => throw null; -}} + class C + { + CannotCopy Method(in CannotCopy cannotCopy) + { + return {|#0:AsRef(in cannotCopy)|}; + } -[NonCopyable] -struct CannotCopy -{{ -}} + ref T AsRef(in T value) + => throw null; + } -internal sealed class NonCopyableAttribute : System.Attribute {{ }} -"; + [NonCopyable] + struct CannotCopy + { + } - await new VerifyCS.Test - { - TestCode = source, + internal sealed class NonCopyableAttribute : System.Attribute { } + """, ExpectedDiagnostics = { // /0/Test0.cs(8,16): warning RS0042: Cannot return a value from a reference to non-copyable type 'CannotCopy' @@ -1210,107 +1133,102 @@ internal sealed class NonCopyableAttribute : System.Attribute {{ }} }, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] - public async Task TestNonCopyableAttributeAsync() - { - await VerifyCS.VerifyAnalyzerAsync(@" -using System.Runtime.InteropServices; + public Task TestNonCopyableAttributeAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System.Runtime.InteropServices; -class C -{ - CanCopy _canCopy; - CannotCopy _cannotCopy; + class C + { + CanCopy _canCopy; + CannotCopy _cannotCopy; - void Method(object value) - { - Method(_canCopy); - Method({|#0:_cannotCopy|}); - } -} + void Method(object value) + { + Method(_canCopy); + Method({|#0:_cannotCopy|}); + } + } -struct CanCopy -{ -} + struct CanCopy + { + } -[NonCopyable] -struct CannotCopy -{ -} + [NonCopyable] + struct CannotCopy + { + } -internal sealed class NonCopyableAttribute : System.Attribute { } -", + internal sealed class NonCopyableAttribute : System.Attribute { } + """, // /0/Test0.cs(12,16): warning RS0042: Unsupported use of non-copyable type 'CannotCopy' in 'FieldReference' operation VerifyCS.Diagnostic(AbstractDoNotCopyValue.UnsupportedUseRule).WithLocation(0).WithArguments("CannotCopy", "FieldReference")); - } [Fact] - public async Task DoNotWrapNonCopyableTypeInNullableTAsync() - { - await VerifyCS.VerifyAnalyzerAsync(@" -using System.Runtime.InteropServices; + public Task DoNotWrapNonCopyableTypeInNullableTAsync() + => VerifyCS.VerifyAnalyzerAsync(""" + using System.Runtime.InteropServices; -class C -{ - GCHandle? field {|#0:= null|}; -} -", + class C + { + GCHandle? field {|#0:= null|}; + } + """, // /0/Test0.cs(6,21): warning RS0042: Do not wrap non-copyable type 'System.Runtime.InteropServices.GCHandle?' in 'FieldInitializer' operation VerifyCS.Diagnostic(AbstractDoNotCopyValue.AvoidNullableWrapperRule).WithLocation(0).WithArguments("System.Runtime.InteropServices.GCHandle?", "FieldInitializer")); - } [Fact] public async Task DoNotDefineNonCopyableFieldInCopyableTypeAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -class C1 -{ - CanCopy field1; - CannotCopy field2; -} + await VerifyCS.VerifyAnalyzerAsync(""" + class C1 + { + CanCopy field1; + CannotCopy field2; + } -struct C2 -{ - CanCopy field1; - CannotCopy {|#0:field2|}; -} + struct C2 + { + CanCopy field1; + CannotCopy {|#0:field2|}; + } -[NonCopyable] -struct C3 -{ - CanCopy field1; - CannotCopy field2; -} + [NonCopyable] + struct C3 + { + CanCopy field1; + CannotCopy field2; + } -struct CanCopy { } -[NonCopyable] struct CannotCopy { } -internal sealed class NonCopyableAttribute : System.Attribute { } -", + struct CanCopy { } + [NonCopyable] struct CannotCopy { } + internal sealed class NonCopyableAttribute : System.Attribute { } + """, // /0/Test0.cs(11,16): warning RS0042: Copyable field 'C2.field2' cannot have non-copyable type 'CannotCopy' VerifyCS.Diagnostic(AbstractDoNotCopyValue.NoFieldOfCopyableTypeRule).WithLocation(0).WithArguments("CannotCopy", "C2.field2")); - await VerifyVB.VerifyAnalyzerAsync(@" -Class C1 - Private field1 As CanCopy - Private field2 As CannotCopy -End Class - -Structure C2 - Private field1 As CanCopy - Private {|#0:field2|} As CannotCopy -End Structure - - -Structure C3 - Private field1 As CanCopy - Private field2 As CannotCopy -End Structure - -Structure CanCopy : End Structure - Structure CannotCopy : End Structure -Public NotInheritable Class NonCopyableAttribute : Inherits System.Attribute : End Class -", + await VerifyVB.VerifyAnalyzerAsync(""" + Class C1 + Private field1 As CanCopy + Private field2 As CannotCopy + End Class + + Structure C2 + Private field1 As CanCopy + Private {|#0:field2|} As CannotCopy + End Structure + + + Structure C3 + Private field1 As CanCopy + Private field2 As CannotCopy + End Structure + + Structure CanCopy : End Structure + Structure CannotCopy : End Structure + Public NotInheritable Class NonCopyableAttribute : Inherits System.Attribute : End Class + """, // /0/Test0.vb(9,13): warning RS0042: Copyable field 'Private field2 As CannotCopy' cannot have non-copyable type 'CannotCopy' VerifyVB.Diagnostic(AbstractDoNotCopyValue.NoFieldOfCopyableTypeRule).WithLocation(0).WithArguments("CannotCopy", "Private field2 As CannotCopy")); } @@ -1318,85 +1236,85 @@ End Structure [Fact] public async Task DoNotDefineNonCopyableAutoPropertyAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -class C1 -{ - CanCopy Property1 { get; set; } - CanCopy Property2 { get => throw null; set => throw null; } - CannotCopy {|#0:Property3|} { get; set; } - CannotCopy Property4 { get => throw null; set => throw null; } -} + await VerifyCS.VerifyAnalyzerAsync(""" + class C1 + { + CanCopy Property1 { get; set; } + CanCopy Property2 { get => throw null; set => throw null; } + CannotCopy {|#0:Property3|} { get; set; } + CannotCopy Property4 { get => throw null; set => throw null; } + } -struct C2 -{ - CanCopy Property1 { get; set; } - CanCopy Property2 { get => throw null; set => throw null; } - CannotCopy {|#1:Property3|} { get; set; } - CannotCopy Property4 { get => throw null; set => throw null; } -} + struct C2 + { + CanCopy Property1 { get; set; } + CanCopy Property2 { get => throw null; set => throw null; } + CannotCopy {|#1:Property3|} { get; set; } + CannotCopy Property4 { get => throw null; set => throw null; } + } -struct CanCopy { } -[NonCopyable] struct CannotCopy { } -internal sealed class NonCopyableAttribute : System.Attribute { } -", + struct CanCopy { } + [NonCopyable] struct CannotCopy { } + internal sealed class NonCopyableAttribute : System.Attribute { } + """, // /0/Test0.cs(6,16): warning RS0042: Auto-property 'C1.Property3' cannot have non-copyable type 'CannotCopy' VerifyCS.Diagnostic(AbstractDoNotCopyValue.NoAutoPropertyRule).WithLocation(0).WithArguments("CannotCopy", "C1.Property3"), // /0/Test0.cs(14,16): warning RS0042: Auto-property 'C2.Property3' cannot have non-copyable type 'CannotCopy' VerifyCS.Diagnostic(AbstractDoNotCopyValue.NoAutoPropertyRule).WithLocation(1).WithArguments("CannotCopy", "C2.Property3")); - await VerifyVB.VerifyAnalyzerAsync(@" -Class C1 - Private Property Property1 As CanCopy - - Private Property Property2 As CanCopy - Get - Throw DirectCast(Nothing, System.Exception) - End Get - Set - Throw DirectCast(Nothing, System.Exception) - End Set - End Property - - Private Property {|#0:Property3|} As CannotCopy - - Private Property Property4 As CannotCopy - Get - Throw DirectCast(Nothing, System.Exception) - End Get - Set - Throw DirectCast(Nothing, System.Exception) - End Set - End Property -End Class - -Structure C2 - Private Property Property1 As CanCopy - - Private Property Property2 As CanCopy - Get - Throw DirectCast(Nothing, System.Exception) - End Get - Set - Throw DirectCast(Nothing, System.Exception) - End Set - End Property - - Private Property {|#1:Property3|} As CannotCopy - - Private Property Property4 As CannotCopy - Get - Throw DirectCast(Nothing, System.Exception) - End Get - Set - Throw DirectCast(Nothing, System.Exception) - End Set - End Property -End Structure - -Structure CanCopy : End Structure - Structure CannotCopy : End Structure -Public NotInheritable Class NonCopyableAttribute : Inherits System.Attribute : End Class -", + await VerifyVB.VerifyAnalyzerAsync(""" + Class C1 + Private Property Property1 As CanCopy + + Private Property Property2 As CanCopy + Get + Throw DirectCast(Nothing, System.Exception) + End Get + Set + Throw DirectCast(Nothing, System.Exception) + End Set + End Property + + Private Property {|#0:Property3|} As CannotCopy + + Private Property Property4 As CannotCopy + Get + Throw DirectCast(Nothing, System.Exception) + End Get + Set + Throw DirectCast(Nothing, System.Exception) + End Set + End Property + End Class + + Structure C2 + Private Property Property1 As CanCopy + + Private Property Property2 As CanCopy + Get + Throw DirectCast(Nothing, System.Exception) + End Get + Set + Throw DirectCast(Nothing, System.Exception) + End Set + End Property + + Private Property {|#1:Property3|} As CannotCopy + + Private Property Property4 As CannotCopy + Get + Throw DirectCast(Nothing, System.Exception) + End Get + Set + Throw DirectCast(Nothing, System.Exception) + End Set + End Property + End Structure + + Structure CanCopy : End Structure + Structure CannotCopy : End Structure + Public NotInheritable Class NonCopyableAttribute : Inherits System.Attribute : End Class + """, // /0/Test0.vb(14,22): warning RS0042: Auto-property 'Private Property Property3 As CannotCopy' cannot have non-copyable type 'CannotCopy' VerifyVB.Diagnostic(AbstractDoNotCopyValue.NoAutoPropertyRule).WithLocation(0).WithArguments("CannotCopy", "Private Property Property3 As CannotCopy"), // /0/Test0.vb(38,22): warning RS0042: Auto-property 'Private Property Property3 As CannotCopy' cannot have non-copyable type 'CannotCopy' @@ -1404,9 +1322,10 @@ End Structure } [Fact] - public async Task AllowCopyFromCollectionExpression() - { - var source = """ + public Task AllowCopyFromCollectionExpression() + => new VerifyCS.Test + { + TestCode = """ using System; using System.Collections; using System.Collections.Generic; @@ -1449,19 +1368,15 @@ public CollectionBuilderAttribute(Type builderType, string methodName) public string MethodName { get; } } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp12, }.RunAsync(); - } [Fact] - public async Task DoNotAllowCopyInCollectionExpressionElement() - { - var source = """ + public Task DoNotAllowCopyInCollectionExpressionElement() + => new VerifyCS.Test + { + TestCode = """ using System; using System.Collections; using System.Collections.Generic; @@ -1508,17 +1423,12 @@ public CollectionBuilderAttribute(Type builderType, string methodName) public string MethodName { get; } } } - """; - - await new VerifyCS.Test - { - TestCode = source, + """, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp12, ExpectedDiagnostics = { // /0/Test0.cs(25,27): warning RS0042: Unsupported use of non-copyable type 'S' in 'LocalReference' operation VerifyCS.Diagnostic(AbstractDoNotCopyValue.UnsupportedUseRule).WithLocation(0).WithArguments("S", "LocalReference") } }.RunAsync(); - } } } diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/DoNotMixAttributesFromDifferentVersionsOfMEFTests.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/DoNotMixAttributesFromDifferentVersionsOfMEFTests.cs index 0c72b7819fe5d..07ede0af7aa67 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/DoNotMixAttributesFromDifferentVersionsOfMEFTests.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/DoNotMixAttributesFromDifferentVersionsOfMEFTests.cs @@ -16,311 +16,331 @@ namespace Roslyn.Diagnostics.Analyzers.UnitTests { public class DoNotMixAttributesFromDifferentVersionsOfMEFTests { - private const string CSharpWellKnownAttributesDefinition = @" -namespace System.Composition -{ - public class ExportAttribute : System.Attribute - { - public ExportAttribute(System.Type contractType){ } - } + private const string CSharpWellKnownAttributesDefinition = """ - public class MetadataAttributeAttribute : System.Attribute - { - public MetadataAttributeAttribute() { } - } + namespace System.Composition + { + public class ExportAttribute : System.Attribute + { + public ExportAttribute(System.Type contractType){ } + } - public class ImportAttribute : System.Attribute - { - public ImportAttribute() { } - } + public class MetadataAttributeAttribute : System.Attribute + { + public MetadataAttributeAttribute() { } + } - public class ImportingConstructorAttribute : System.Attribute - { - public ImportingConstructorAttribute() { } - } -} + public class ImportAttribute : System.Attribute + { + public ImportAttribute() { } + } -[System.Composition.MetadataAttribute] -public class SystemCompositionMetadataAttribute : System.Attribute -{ - public class ExportAttribute : System.Attribute - { - public ExportAttribute(System.Type contractType){ } - } + public class ImportingConstructorAttribute : System.Attribute + { + public ImportingConstructorAttribute() { } + } + } - public class MetadataAttributeAttribute : System.Attribute - { - public MetadataAttributeAttribute() { } - } + [System.Composition.MetadataAttribute] + public class SystemCompositionMetadataAttribute : System.Attribute + { + public class ExportAttribute : System.Attribute + { + public ExportAttribute(System.Type contractType){ } + } - public class ImportAttribute : System.Attribute - { - public ImportAttribute() { } - } + public class MetadataAttributeAttribute : System.Attribute + { + public MetadataAttributeAttribute() { } + } - public class ImportingConstructorAttribute : System.Attribute - { - public ImportingConstructorAttribute() { } - } -} + public class ImportAttribute : System.Attribute + { + public ImportAttribute() { } + } -namespace System.ComponentModel.Composition -{ - public class ExportAttribute : System.Attribute - { - public ExportAttribute(System.Type contractType){ } - } + public class ImportingConstructorAttribute : System.Attribute + { + public ImportingConstructorAttribute() { } + } + } - public class MetadataAttributeAttribute : System.Attribute - { - public MetadataAttributeAttribute() { } - } + namespace System.ComponentModel.Composition + { + public class ExportAttribute : System.Attribute + { + public ExportAttribute(System.Type contractType){ } + } - public class ImportAttribute : System.Attribute - { - public ImportAttribute() { } - } + public class MetadataAttributeAttribute : System.Attribute + { + public MetadataAttributeAttribute() { } + } - public class ImportingConstructorAttribute : System.Attribute - { - public ImportingConstructorAttribute() { } - } -} + public class ImportAttribute : System.Attribute + { + public ImportAttribute() { } + } -[System.ComponentModel.Composition.MetadataAttribute] -public class SystemComponentModelCompositionMetadataAttribute : System.Attribute -{ -} -"; - private const string BasicWellKnownAttributesDefinition = @" -Namespace System.Composition - Public Class ExportAttribute - Inherits System.Attribute - Public Sub New(contractType As System.Type) - End Sub - End Class - - Public Class MetadataAttributeAttribute - Inherits System.Attribute - Public Sub New() - End Sub - End Class - - Public Class ImportAttribute - Inherits System.Attribute - Public Sub New() - End Sub - End Class - - Public Class ImportingConstructorAttribute - Inherits System.Attribute - Public Sub New() - End Sub - End Class -End Namespace - - _ -Public Class SystemCompositionMetadataAttribute - Inherits System.Attribute -End Class - -Namespace System.ComponentModel.Composition - Public Class ExportAttribute - Inherits System.Attribute - Public Sub New(contractType As System.Type) - End Sub - End Class - - Public Class MetadataAttributeAttribute - Inherits System.Attribute - Public Sub New() - End Sub - End Class - - Public Class ImportAttribute - Inherits System.Attribute - Public Sub New() - End Sub - End Class - - Public Class ImportingConstructorAttribute - Inherits System.Attribute - Public Sub New() - End Sub - End Class -End Namespace - - _ -Public Class SystemComponentModelCompositionMetadataAttribute - Inherits System.Attribute -End Class -"; + public class ImportingConstructorAttribute : System.Attribute + { + public ImportingConstructorAttribute() { } + } + } + + [System.ComponentModel.Composition.MetadataAttribute] + public class SystemComponentModelCompositionMetadataAttribute : System.Attribute + { + } + + """; + private const string BasicWellKnownAttributesDefinition = """ + + Namespace System.Composition + Public Class ExportAttribute + Inherits System.Attribute + Public Sub New(contractType As System.Type) + End Sub + End Class + + Public Class MetadataAttributeAttribute + Inherits System.Attribute + Public Sub New() + End Sub + End Class + + Public Class ImportAttribute + Inherits System.Attribute + Public Sub New() + End Sub + End Class + + Public Class ImportingConstructorAttribute + Inherits System.Attribute + Public Sub New() + End Sub + End Class + End Namespace + + _ + Public Class SystemCompositionMetadataAttribute + Inherits System.Attribute + End Class + + Namespace System.ComponentModel.Composition + Public Class ExportAttribute + Inherits System.Attribute + Public Sub New(contractType As System.Type) + End Sub + End Class + + Public Class MetadataAttributeAttribute + Inherits System.Attribute + Public Sub New() + End Sub + End Class + + Public Class ImportAttribute + Inherits System.Attribute + Public Sub New() + End Sub + End Class + + Public Class ImportingConstructorAttribute + Inherits System.Attribute + Public Sub New() + End Sub + End Class + End Namespace + + _ + Public Class SystemComponentModelCompositionMetadataAttribute + Inherits System.Attribute + End Class + + """; #region No Diagnostic Tests [Fact] public async Task NoDiagnosticCases_SingleMefAttributeAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -using System; + await VerifyCS.VerifyAnalyzerAsync(""" -[System.Composition.Export(typeof(C))] -public class C -{ -} + using System; -[System.ComponentModel.Composition.Export(typeof(C2))] -public class C2 -{ -} -" + CSharpWellKnownAttributesDefinition); + [System.Composition.Export(typeof(C))] + public class C + { + } + + [System.ComponentModel.Composition.Export(typeof(C2))] + public class C2 + { + } + + """ + CSharpWellKnownAttributesDefinition); + + await VerifyVB.VerifyAnalyzerAsync(""" - await VerifyVB.VerifyAnalyzerAsync(@" -Imports System + Imports System - _ -Public Class C -End Class + _ + Public Class C + End Class - _ -Public Class C2 -End Class -" + BasicWellKnownAttributesDefinition); + _ + Public Class C2 + End Class + + """ + BasicWellKnownAttributesDefinition); } [Fact] public async Task NoDiagnosticCases_SingleMefAttributeAndValidMetadataAttributeAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -using System; + await VerifyCS.VerifyAnalyzerAsync(""" -[System.Composition.Export(typeof(C))] -[SystemCompositionMetadataAttribute] -public class C -{ -} + using System; -[System.ComponentModel.Composition.Export(typeof(C2))] -[SystemComponentModelCompositionMetadataAttribute] -public class C2 -{ -} -" + CSharpWellKnownAttributesDefinition); + [System.Composition.Export(typeof(C))] + [SystemCompositionMetadataAttribute] + public class C + { + } + + [System.ComponentModel.Composition.Export(typeof(C2))] + [SystemComponentModelCompositionMetadataAttribute] + public class C2 + { + } + + """ + CSharpWellKnownAttributesDefinition); + + await VerifyVB.VerifyAnalyzerAsync(""" - await VerifyVB.VerifyAnalyzerAsync(@" -Imports System + Imports System - _ - _ -Public Class C -End Class + _ + _ + Public Class C + End Class - _ - _ -Public Class C2 -End Class -" + BasicWellKnownAttributesDefinition); + _ + _ + Public Class C2 + End Class + + """ + BasicWellKnownAttributesDefinition); } [Fact] public async Task NoDiagnosticCases_SingleMefAttributeAndAnotherExportAttributeAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -using System; + await VerifyCS.VerifyAnalyzerAsync(""" -[System.Composition.Export(typeof(C)), MyNamespace.Export(typeof(C))] -public class C -{ -} + using System; -[System.ComponentModel.Composition.Export(typeof(C2)), MyNamespace.Export(typeof(C2))] -public class C2 -{ -} + [System.Composition.Export(typeof(C)), MyNamespace.Export(typeof(C))] + public class C + { + } -namespace MyNamespace -{ - public class ExportAttribute : System.Attribute - { - public ExportAttribute(System.Type contractType){ } - } -} -" + CSharpWellKnownAttributesDefinition); - - await VerifyVB.VerifyAnalyzerAsync(@" -Imports System - - _ -Public Class C -End Class - - _ -Public Class C2 -End Class - -Namespace MyNamespace - Public Class ExportAttribute - Inherits System.Attribute - Public Sub New(contractType As System.Type) - End Sub - End Class -End Namespace -" + BasicWellKnownAttributesDefinition); + [System.ComponentModel.Composition.Export(typeof(C2)), MyNamespace.Export(typeof(C2))] + public class C2 + { + } + + namespace MyNamespace + { + public class ExportAttribute : System.Attribute + { + public ExportAttribute(System.Type contractType){ } + } + } + + """ + CSharpWellKnownAttributesDefinition); + + await VerifyVB.VerifyAnalyzerAsync(""" + + Imports System + + _ + Public Class C + End Class + + _ + Public Class C2 + End Class + + Namespace MyNamespace + Public Class ExportAttribute + Inherits System.Attribute + Public Sub New(contractType As System.Type) + End Sub + End Class + End Namespace + + """ + BasicWellKnownAttributesDefinition); } [Fact] public async Task NoDiagnosticCases_SingleMefAttributeOnTypeAndValidMefAttributeOnMemberAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -using System; + await VerifyCS.VerifyAnalyzerAsync(""" -public class B { } + using System; -[System.Composition.Export(typeof(C))] -public class C -{ - [System.Composition.ImportingConstructor] - public C([System.Composition.Import]B b) { } + public class B { } - [System.Composition.Import] - public B PropertyB { get; } -} + [System.Composition.Export(typeof(C))] + public class C + { + [System.Composition.ImportingConstructor] + public C([System.Composition.Import]B b) { } -[System.ComponentModel.Composition.Export(typeof(C2))] -public class C2 -{ - [System.ComponentModel.Composition.ImportingConstructor] - public C2([System.ComponentModel.Composition.Import]B b) { } + [System.Composition.Import] + public B PropertyB { get; } + } - [System.ComponentModel.Composition.Import] - public B PropertyB { get; } -} -" + CSharpWellKnownAttributesDefinition); - - await VerifyVB.VerifyAnalyzerAsync(@" -Public Class B -End Class - - _ -Public Class C - _ - Public Sub New( b As B) - End Sub - - _ - Public ReadOnly Property PropertyB() As B -End Class - - _ -Public Class C2 - _ - Public Sub New( b As B) - End Sub - - _ - Public ReadOnly Property PropertyB() As B -End Class -" + BasicWellKnownAttributesDefinition); + [System.ComponentModel.Composition.Export(typeof(C2))] + public class C2 + { + [System.ComponentModel.Composition.ImportingConstructor] + public C2([System.ComponentModel.Composition.Import]B b) { } + + [System.ComponentModel.Composition.Import] + public B PropertyB { get; } + } + + """ + CSharpWellKnownAttributesDefinition); + + await VerifyVB.VerifyAnalyzerAsync(""" + + Public Class B + End Class + + _ + Public Class C + _ + Public Sub New( b As B) + End Sub + + _ + Public ReadOnly Property PropertyB() As B + End Class + + _ + Public Class C2 + _ + Public Sub New( b As B) + End Sub + + _ + Public ReadOnly Property PropertyB() As B + End Class + + """ + BasicWellKnownAttributesDefinition); } [Fact] @@ -332,18 +352,20 @@ public async Task NoDiagnosticCases_UnresolvedTypesAsync() { Sources = { - @" -using System; + """ -public class B { } + using System; -[System.{|CS0234:Composition|}.Export(typeof(C))] -public class C -{ - [System.ComponentModel.{|CS0234:Composition|}.Import] - public B PropertyB { get; } -} -" + public class B { } + + [System.{|CS0234:Composition|}.Export(typeof(C))] + public class C + { + [System.ComponentModel.{|CS0234:Composition|}.Import] + public B PropertyB { get; } + } + + """ }, }, ReferenceAssemblies = ReferenceAssemblies.Default, @@ -355,16 +377,18 @@ public class C { Sources = { - @" -Public Class B -End Class - -<{|BC30002:System.Composition.Export|}(GetType(C))> _ -Public Class C - <{|BC30002:System.ComponentModel.Composition.Import|}> _ - Public ReadOnly Property PropertyB() As B -End Class -" + """ + + Public Class B + End Class + + <{|BC30002:System.Composition.Export|}(GetType(C))> _ + Public Class C + <{|BC30002:System.ComponentModel.Composition.Import|}> _ + Public ReadOnly Property PropertyB() As B + End Class + + """ }, }, ReferenceAssemblies = ReferenceAssemblies.Default, @@ -374,37 +398,41 @@ End Class [Fact] public async Task NoDiagnosticCases_MultiMefMetadataAttributeAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -using System; + await VerifyCS.VerifyAnalyzerAsync(""" -[System.ComponentModel.Composition.Export(typeof(C)), MyNamespace.MultiMefMetadataAttribute] -public class C -{ -} + using System; -namespace MyNamespace -{ - [System.ComponentModel.Composition.MetadataAttribute, System.Composition.MetadataAttribute] - public class MultiMefMetadataAttribute : System.Attribute - { - } -} -" + CSharpWellKnownAttributesDefinition); - - await VerifyVB.VerifyAnalyzerAsync(@" -Imports System - - _ -Public Class C -End Class - -Namespace MyNamespace - _ - Public Class MultiMefMetadataAttribute - Inherits System.Attribute - End Class -End Namespace -" + BasicWellKnownAttributesDefinition); + [System.ComponentModel.Composition.Export(typeof(C)), MyNamespace.MultiMefMetadataAttribute] + public class C + { + } + + namespace MyNamespace + { + [System.ComponentModel.Composition.MetadataAttribute, System.Composition.MetadataAttribute] + public class MultiMefMetadataAttribute : System.Attribute + { + } + } + + """ + CSharpWellKnownAttributesDefinition); + + await VerifyVB.VerifyAnalyzerAsync(""" + + Imports System + + _ + Public Class C + End Class + + Namespace MyNamespace + _ + Public Class MultiMefMetadataAttribute + Inherits System.Attribute + End Class + End Namespace + + """ + BasicWellKnownAttributesDefinition); } #endregion @@ -414,39 +442,43 @@ End Namespace [Fact] public async Task DiagnosticCases_BadMetadataAttributeAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -using System; + await VerifyCS.VerifyAnalyzerAsync(""" -[System.Composition.Export(typeof(C))] -[SystemComponentModelCompositionMetadataAttribute] -public class C -{ -} + using System; -[System.ComponentModel.Composition.Export(typeof(C2))] -[SystemCompositionMetadataAttribute] -public class C2 -{ -} -" + CSharpWellKnownAttributesDefinition, + [System.Composition.Export(typeof(C))] + [SystemComponentModelCompositionMetadataAttribute] + public class C + { + } + + [System.ComponentModel.Composition.Export(typeof(C2))] + [SystemCompositionMetadataAttribute] + public class C2 + { + } + + """ + CSharpWellKnownAttributesDefinition, // Test0.cs(5,2): warning RS0006: Attribute 'SystemComponentModelCompositionMetadataAttribute' comes from a different version of MEF than the export attribute on 'C' GetCSharpResultAt(5, 2, "SystemComponentModelCompositionMetadataAttribute", "C"), // Test0.cs(11,2): warning RS0006: Attribute 'SystemCompositionMetadataAttribute' comes from a different version of MEF than the export attribute on 'C2' GetCSharpResultAt(11, 2, "SystemCompositionMetadataAttribute", "C2")); - await VerifyVB.VerifyAnalyzerAsync(@" -Imports System + await VerifyVB.VerifyAnalyzerAsync(""" - _ - _ -Public Class C -End Class + Imports System - _ - _ -Public Class C2 -End Class -" + BasicWellKnownAttributesDefinition, + _ + _ + Public Class C + End Class + + _ + _ + Public Class C2 + End Class + + """ + BasicWellKnownAttributesDefinition, // Test0.vb(5,2): warning RS0006: Attribute 'SystemComponentModelCompositionMetadataAttribute' comes from a different version of MEF than the export attribute on 'C' GetBasicResultAt(5, 2, "SystemComponentModelCompositionMetadataAttribute", "C"), // Test0.vb(10,2): warning RS0006: Attribute 'SystemCompositionMetadataAttribute' comes from a different version of MEF than the export attribute on 'C2' @@ -456,31 +488,33 @@ End Class [Fact] public async Task DiagnosticCases_BadMefAttributeOnMemberAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -using System; + await VerifyCS.VerifyAnalyzerAsync(""" -public class B { } + using System; -[System.Composition.Export(typeof(C))] -public class C -{ - [System.ComponentModel.Composition.ImportingConstructor] - public C([System.Composition.Import]B b) { } + public class B { } - [System.ComponentModel.Composition.Import] - public B PropertyB { get; } -} + [System.Composition.Export(typeof(C))] + public class C + { + [System.ComponentModel.Composition.ImportingConstructor] + public C([System.Composition.Import]B b) { } -[System.ComponentModel.Composition.Export(typeof(C2))] -public class C2 -{ - [System.Composition.ImportingConstructor] - public C2([System.ComponentModel.Composition.Import]B b) { } + [System.ComponentModel.Composition.Import] + public B PropertyB { get; } + } - [System.Composition.Import] - public B PropertyB { get; } -} -" + CSharpWellKnownAttributesDefinition, + [System.ComponentModel.Composition.Export(typeof(C2))] + public class C2 + { + [System.Composition.ImportingConstructor] + public C2([System.ComponentModel.Composition.Import]B b) { } + + [System.Composition.Import] + public B PropertyB { get; } + } + + """ + CSharpWellKnownAttributesDefinition, // Test0.cs(9,6): warning RS0006: Attribute 'ImportingConstructorAttribute' comes from a different version of MEF than the export attribute on 'C' GetCSharpResultAt(9, 6, "ImportingConstructorAttribute", "C"), // Test0.cs(12,6): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C' @@ -491,30 +525,32 @@ public C2([System.ComponentModel.Composition.Import]B b) { } GetCSharpResultAt(22, 6, "ImportAttribute", "C2") ); - await VerifyVB.VerifyAnalyzerAsync(@" -Public Class B -End Class - - _ -Public Class C - _ - Public Sub New( b As B) - End Sub - - _ - Public ReadOnly Property PropertyB() As B -End Class - - _ -Public Class C2 - _ - Public Sub New( b As B) - End Sub - - _ - Public ReadOnly Property PropertyB() As B -End Class -" + BasicWellKnownAttributesDefinition, + await VerifyVB.VerifyAnalyzerAsync(""" + + Public Class B + End Class + + _ + Public Class C + _ + Public Sub New( b As B) + End Sub + + _ + Public ReadOnly Property PropertyB() As B + End Class + + _ + Public Class C2 + _ + Public Sub New( b As B) + End Sub + + _ + Public ReadOnly Property PropertyB() As B + End Class + + """ + BasicWellKnownAttributesDefinition, // Test0.vb(7,3): warning RS0006: Attribute 'ImportingConstructorAttribute' comes from a different version of MEF than the export attribute on 'C' GetBasicResultAt(7, 3, "ImportingConstructorAttribute", "C"), // Test0.vb(11,3): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C' @@ -529,60 +565,64 @@ End Class [Fact] public async Task DiagnosticCases_BadMefAttributeOnParameterAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -using System; + await VerifyCS.VerifyAnalyzerAsync(""" -public class B { } + using System; -[System.Composition.Export(typeof(C))] -public class C -{ - [System.Composition.ImportingConstructor] - public C([System.ComponentModel.Composition.Import]B b) { } + public class B { } - [System.Composition.Import] - public B PropertyB { get; } -} + [System.Composition.Export(typeof(C))] + public class C + { + [System.Composition.ImportingConstructor] + public C([System.ComponentModel.Composition.Import]B b) { } -[System.ComponentModel.Composition.Export(typeof(C2))] -public class C2 -{ - [System.ComponentModel.Composition.ImportingConstructor] - public C2([System.Composition.Import]B b) { } + [System.Composition.Import] + public B PropertyB { get; } + } - [System.ComponentModel.Composition.Import] - public B PropertyB { get; } -} -" + CSharpWellKnownAttributesDefinition, + [System.ComponentModel.Composition.Export(typeof(C2))] + public class C2 + { + [System.ComponentModel.Composition.ImportingConstructor] + public C2([System.Composition.Import]B b) { } + + [System.ComponentModel.Composition.Import] + public B PropertyB { get; } + } + + """ + CSharpWellKnownAttributesDefinition, // Test0.cs(10,15): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C' GetCSharpResultAt(10, 15, "ImportAttribute", "C"), // Test0.cs(20,16): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C2' GetCSharpResultAt(20, 16, "ImportAttribute", "C2")); - await VerifyVB.VerifyAnalyzerAsync(@" -Public Class B -End Class - - _ -Public Class C - _ - Public Sub New( b As B) - End Sub - - _ - Public ReadOnly Property PropertyB() As B -End Class - - _ -Public Class C2 - _ - Public Sub New( b As B) - End Sub - - _ - Public ReadOnly Property PropertyB() As B -End Class -" + BasicWellKnownAttributesDefinition, + await VerifyVB.VerifyAnalyzerAsync(""" + + Public Class B + End Class + + _ + Public Class C + _ + Public Sub New( b As B) + End Sub + + _ + Public ReadOnly Property PropertyB() As B + End Class + + _ + Public Class C2 + _ + Public Sub New( b As B) + End Sub + + _ + Public ReadOnly Property PropertyB() As B + End Class + + """ + BasicWellKnownAttributesDefinition, // Test0.vb(8,18): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C' GetBasicResultAt(8, 18, "ImportAttribute", "C"), // Test0.vb(18,18): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C2' diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/ExportedPartsShouldHaveImportingConstructorTests.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/ExportedPartsShouldHaveImportingConstructorTests.cs index 036df74a9b1c4..3e012f731cba0 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/ExportedPartsShouldHaveImportingConstructorTests.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/ExportedPartsShouldHaveImportingConstructorTests.cs @@ -21,15 +21,15 @@ public class ExportedPartsShouldHaveImportingConstructorTests [InlineData("System.ComponentModel.Composition")] public async Task SingleExpectedConstructor_CSharpAsync(string mefNamespace) { - var source = $@" -using {mefNamespace}; + var source = $$""" + using {{mefNamespace}}; -[Export] -class C {{ - [ImportingConstructor] - public C() {{ }} -}} -"; + [Export] + class C { + [ImportingConstructor] + public C() { } + } + """; await new VerifyCS.Test { @@ -46,16 +46,16 @@ public C() {{ }} [InlineData("System.ComponentModel.Composition")] public async Task SingleExpectedConstructor_VisualBasicAsync(string mefNamespace) { - var source = $@" -Imports {mefNamespace} + var source = $""" + Imports {mefNamespace} - -Class C - - Public Sub New() - End Sub -End Class -"; + + Class C + + Public Sub New() + End Sub + End Class + """; await new VerifyVB.Test { @@ -74,21 +74,21 @@ End Class [InlineData("System.ComponentModel.Composition", false)] public async Task NotInheritedAttribute_CSharpAsync(string mefNamespace, bool reflectionInherited) { - var source = $@" -using {mefNamespace}; + var source = $$""" + using {{mefNamespace}}; -[System.AttributeUsage(System.AttributeTargets.All, Inherited = {(reflectionInherited ? "true" : "false")})] -class NotInheritedExportAttribute : System.Attribute {{ }} + [System.AttributeUsage(System.AttributeTargets.All, Inherited = {{(reflectionInherited ? "true" : "false")}})] + class NotInheritedExportAttribute : System.Attribute { } -[NotInheritedExport] -class C {{ - [ImportingConstructor] - public C() {{ }} -}} + [NotInheritedExport] + class C { + [ImportingConstructor] + public C() { } + } -class D : C {{ -}} -"; + class D : C { + } + """; await new VerifyCS.Test { @@ -107,25 +107,25 @@ class D : C {{ [InlineData("System.ComponentModel.Composition", false)] public async Task NotInheritedAttribute_VisualBasicAsync(string mefNamespace, bool reflectionInherited) { - var source = $@" -Imports {mefNamespace} - - -Class NotInheritedExportAttribute - Inherits System.Attribute -End Class - - -Class C - - Public Sub New() - End Sub -End Class - -Class D - Inherits C -End Class -"; + var source = $""" + Imports {mefNamespace} + + + Class NotInheritedExportAttribute + Inherits System.Attribute + End Class + + + Class C + + Public Sub New() + End Sub + End Class + + Class D + Inherits C + End Class + """; await new VerifyVB.Test { @@ -141,34 +141,34 @@ End Class [InlineData("System.ComponentModel.Composition")] public async Task InheritedExportAttribute_CSharpAsync(string mefNamespace) { - var source = $@" -using {mefNamespace}; - -[InheritedExport] -class C {{ - [ImportingConstructor] - public C() {{ }} -}} - -class D : C {{ -}} -"; - var fixedSource = $@" -using {mefNamespace}; - -[InheritedExport] -class C {{ - [ImportingConstructor] - public C() {{ }} -}} - -class D : C {{ - [ImportingConstructor] - public D() - {{ - }} -}} -"; + var source = $$""" + using {{mefNamespace}}; + + [InheritedExport] + class C { + [ImportingConstructor] + public C() { } + } + + class D : C { + } + """; + var fixedSource = $$""" + using {{mefNamespace}}; + + [InheritedExport] + class C { + [ImportingConstructor] + public C() { } + } + + class D : C { + [ImportingConstructor] + public D() + { + } + } + """; await new VerifyCS.Test { @@ -189,37 +189,37 @@ public D() [InlineData("System.ComponentModel.Composition")] public async Task InheritedExportAttribute_VisualBasicAsync(string mefNamespace) { - var source = $@" -Imports {mefNamespace} - - -Class C - - Public Sub New() - End Sub -End Class - -Class D - Inherits C -End Class -"; - var fixedSource = $@" -Imports {mefNamespace} - - -Class C - - Public Sub New() - End Sub -End Class - -Class D - Inherits C - - Public Sub New() - End Sub -End Class -"; + var source = $""" + Imports {mefNamespace} + + + Class C + + Public Sub New() + End Sub + End Class + + Class D + Inherits C + End Class + """; + var fixedSource = $""" + Imports {mefNamespace} + + + Class C + + Public Sub New() + End Sub + End Class + + Class D + Inherits C + + Public Sub New() + End Sub + End Class + """; await new VerifyVB.Test { @@ -241,17 +241,17 @@ End Class [InlineData("System.ComponentModel.Composition")] public async Task ExportAttributeNotInherited_CSharpAsync(string mefNamespace) { - var source = $@" -using {mefNamespace}; + var source = $$""" + using {{mefNamespace}}; -[Export] -class C {{ - [ImportingConstructor] - public C() {{ }} -}} + [Export] + class C { + [ImportingConstructor] + public C() { } + } -class D : C {{ }} -"; + class D : C { } + """; await new VerifyCS.Test { @@ -268,20 +268,20 @@ class D : C {{ }} [InlineData("System.ComponentModel.Composition")] public async Task ExportAttributeNotInherited_VisualBasicAsync(string mefNamespace) { - var source = $@" -Imports {mefNamespace} + var source = $""" + Imports {mefNamespace} - -Class C - - Public Sub New() - End Sub -End Class + + Class C + + Public Sub New() + End Sub + End Class -Class D - Inherits C -End Class -"; + Class D + Inherits C + End Class + """; await new VerifyVB.Test { @@ -298,17 +298,17 @@ End Class [InlineData("System.ComponentModel.Composition")] public async Task InstanceAndImplicitStaticConstructor_CSharpAsync(string mefNamespace) { - var source = $@" -using {mefNamespace}; + var source = $$""" + using {{mefNamespace}}; -[Export] -class C {{ - private static readonly object _gate = new object(); + [Export] + class C { + private static readonly object _gate = new object(); - [ImportingConstructor] - public C() {{ }} -}} -"; + [ImportingConstructor] + public C() { } + } + """; await new VerifyCS.Test { @@ -325,18 +325,18 @@ public C() {{ }} [InlineData("System.ComponentModel.Composition")] public async Task InstanceAndImplicitStaticConstructor_VisualBasicAsync(string mefNamespace) { - var source = $@" -Imports {mefNamespace} + var source = $""" + Imports {mefNamespace} - -Class C - Private Shared ReadOnly _gate As Object = New Object() + + Class C + Private Shared ReadOnly _gate As Object = New Object() - - Public Sub New() - End Sub -End Class -"; + + Public Sub New() + End Sub + End Class + """; await new VerifyVB.Test { @@ -353,19 +353,19 @@ End Class [InlineData("System.ComponentModel.Composition")] public async Task InstanceAndExplicitStaticConstructor_CSharpAsync(string mefNamespace) { - var source = $@" -using {mefNamespace}; + var source = $$""" + using {{mefNamespace}}; -[Export] -class C {{ - private static readonly object _gate; + [Export] + class C { + private static readonly object _gate; - static C() {{ _gate = new object(); }} + static C() { _gate = new object(); } - [ImportingConstructor] - public C() {{ }} -}} -"; + [ImportingConstructor] + public C() { } + } + """; await new VerifyCS.Test { @@ -382,22 +382,22 @@ public C() {{ }} [InlineData("System.ComponentModel.Composition")] public async Task InstanceAndExplicitStaticConstructor_VisualBasicAsync(string mefNamespace) { - var source = $@" -Imports {mefNamespace} + var source = $""" + Imports {mefNamespace} - -Class C - Private Shared ReadOnly _gate As Object + + Class C + Private Shared ReadOnly _gate As Object - Shared Sub New() - _gate = New Object() - End Sub + Shared Sub New() + _gate = New Object() + End Sub - - Public Sub New() - End Sub -End Class -"; + + Public Sub New() + End Sub + End Class + """; await new VerifyVB.Test { @@ -414,23 +414,23 @@ End Class [InlineData("System.ComponentModel.Composition")] public async Task ImplicitConstructor_CSharpAsync(string mefNamespace) { - var source = $@" -using {mefNamespace}; - -[Export] -class C {{ }} -"; - var fixedSource = $@" -using {mefNamespace}; - -[Export] -class C {{ - [ImportingConstructor] - public C() - {{ - }} -}} -"; + var source = $$""" + using {{mefNamespace}}; + + [Export] + class C { } + """; + var fixedSource = $$""" + using {{mefNamespace}}; + + [Export] + class C { + [ImportingConstructor] + public C() + { + } + } + """; await new VerifyCS.Test { @@ -438,7 +438,7 @@ public C() { Sources = { source }, AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyCS.Diagnostic().WithSpan(4, 2, 4, 8).WithArguments("C") }, + ExpectedDiagnostics = { VerifyCS.Diagnostic().WithSpan(3, 2, 3, 8).WithArguments("C") }, }, FixedState = { @@ -452,23 +452,23 @@ public C() [InlineData("System.ComponentModel.Composition")] public async Task ImplicitConstructor_VisualBasicAsync(string mefNamespace) { - var source = $@" -Imports {mefNamespace} - - -Class C -End Class -"; - var fixedSource = $@" -Imports {mefNamespace} - - -Class C - - Public Sub New() - End Sub -End Class -"; + var source = $""" + Imports {mefNamespace} + + + Class C + End Class + """; + var fixedSource = $""" + Imports {mefNamespace} + + + Class C + + Public Sub New() + End Sub + End Class + """; await new VerifyVB.Test { @@ -476,7 +476,7 @@ End Class { Sources = { source }, AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyVB.Diagnostic().WithSpan(4, 2, 4, 8).WithArguments("C") }, + ExpectedDiagnostics = { VerifyVB.Diagnostic().WithSpan(3, 2, 3, 8).WithArguments("C") }, }, FixedState = { @@ -490,21 +490,21 @@ End Class [InlineData("System.ComponentModel.Composition")] public async Task ImplicitConstructorAddImport_CSharpAsync(string mefNamespace) { - var source = $@" -[{mefNamespace}.Export] -class C {{ }} -"; - var fixedSource = $@" -using {mefNamespace}; - -[{mefNamespace}.Export] -class C {{ - [ImportingConstructor] - public C() - {{ - }} -}} -"; + var source = $$""" + [{{mefNamespace}}.Export] + class C { } + """; + var fixedSource = $$""" + using {{mefNamespace}}; + + [{{mefNamespace}}.Export] + class C { + [ImportingConstructor] + public C() + { + } + } + """; await new VerifyCS.Test { @@ -512,7 +512,7 @@ public C() { Sources = { source }, AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyCS.Diagnostic().WithSpan(2, 2, 2, mefNamespace.Length + 9).WithArguments("C") }, + ExpectedDiagnostics = { VerifyCS.Diagnostic().WithSpan(1, 2, 1, mefNamespace.Length + 9).WithArguments("C") }, }, FixedState = { @@ -526,21 +526,21 @@ public C() [InlineData("System.ComponentModel.Composition")] public async Task ImplicitConstructorAddImport_VisualBasicAsync(string mefNamespace) { - var source = $@" -<{mefNamespace}.Export> -Class C -End Class -"; - var fixedSource = $@" -Imports {mefNamespace} - -<{mefNamespace}.Export> -Class C - - Public Sub New() - End Sub -End Class -"; + var source = $""" + <{mefNamespace}.Export> + Class C + End Class + """; + var fixedSource = $""" + Imports {mefNamespace} + + <{mefNamespace}.Export> + Class C + + Public Sub New() + End Sub + End Class + """; await new VerifyVB.Test { @@ -548,7 +548,7 @@ End Class { Sources = { source }, AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyVB.Diagnostic().WithSpan(2, 2, 2, mefNamespace.Length + 9).WithArguments("C") }, + ExpectedDiagnostics = { VerifyVB.Diagnostic().WithSpan(1, 2, 1, mefNamespace.Length + 9).WithArguments("C") }, }, FixedState = { @@ -562,31 +562,31 @@ End Class [InlineData("System.ComponentModel.Composition")] public async Task ImplicitConstructorPlacement_CSharpAsync(string mefNamespace) { - var source = $@" -using {mefNamespace}; + var source = $$""" + using {{mefNamespace}}; -[Export] -class C {{ - private readonly int _value = 0; + [Export] + class C { + private readonly int _value = 0; - private int Value => _value; -}} -"; - var fixedSource = $@" -using {mefNamespace}; + private int Value => _value; + } + """; + var fixedSource = $$""" + using {{mefNamespace}}; -[Export] -class C {{ - private readonly int _value = 0; + [Export] + class C { + private readonly int _value = 0; - [ImportingConstructor] - public C() - {{ - }} + [ImportingConstructor] + public C() + { + } - private int Value => _value; -}} -"; + private int Value => _value; + } + """; await new VerifyCS.Test { @@ -594,7 +594,7 @@ public C() { Sources = { source }, AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyCS.Diagnostic().WithSpan(4, 2, 4, 8).WithArguments("C") }, + ExpectedDiagnostics = { VerifyCS.Diagnostic().WithSpan(3, 2, 3, 8).WithArguments("C") }, }, FixedState = { @@ -608,38 +608,38 @@ public C() [InlineData("System.ComponentModel.Composition")] public async Task ImplicitConstructorPlacement_VisualBasicAsync(string mefNamespace) { - var source = $@" -Imports {mefNamespace} - - -Class C - Private ReadOnly _value1 As Integer = 0 - - Private ReadOnly Property Value - Get - return _value1 - End Get - End Property -End Class -"; - var fixedSource = $@" -Imports {mefNamespace} - - -Class C - Private ReadOnly _value1 As Integer = 0 - - - Public Sub New() - End Sub - - Private ReadOnly Property Value - Get - return _value1 - End Get - End Property -End Class -"; + var source = $""" + Imports {mefNamespace} + + + Class C + Private ReadOnly _value1 As Integer = 0 + + Private ReadOnly Property Value + Get + return _value1 + End Get + End Property + End Class + """; + var fixedSource = $""" + Imports {mefNamespace} + + + Class C + Private ReadOnly _value1 As Integer = 0 + + + Public Sub New() + End Sub + + Private ReadOnly Property Value + Get + return _value1 + End Get + End Property + End Class + """; await new VerifyVB.Test { @@ -647,7 +647,7 @@ End Class { Sources = { source }, AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyVB.Diagnostic().WithSpan(4, 2, 4, 8).WithArguments("C") }, + ExpectedDiagnostics = { VerifyVB.Diagnostic().WithSpan(3, 2, 3, 8).WithArguments("C") }, }, FixedState = { @@ -661,23 +661,23 @@ End Class [InlineData("System.ComponentModel.Composition")] public async Task MissingAttributeConstructor_CSharpAsync(string mefNamespace) { - var source = $@" -using {mefNamespace}; - -[Export] -class C {{ - public C() {{ }} -}} -"; - var fixedSource = $@" -using {mefNamespace}; - -[Export] -class C {{ - [ImportingConstructor] - public C() {{ }} -}} -"; + var source = $$""" + using {{mefNamespace}}; + + [Export] + class C { + public C() { } + } + """; + var fixedSource = $$""" + using {{mefNamespace}}; + + [Export] + class C { + [ImportingConstructor] + public C() { } + } + """; await new VerifyCS.Test { @@ -685,7 +685,7 @@ public C() {{ }} { Sources = { source }, AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyCS.Diagnostic().WithSpan(6, 5, 6, 19).WithArguments("C") }, + ExpectedDiagnostics = { VerifyCS.Diagnostic().WithSpan(5, 5, 5, 19).WithArguments("C") }, }, FixedState = { @@ -699,25 +699,25 @@ public C() {{ }} [InlineData("System.ComponentModel.Composition")] public async Task MissingAttributeConstructor_VisualBasicAsync(string mefNamespace) { - var source = $@" -Imports {mefNamespace} - - -Class C - Public Sub New() - End Sub -End Class -"; - var fixedSource = $@" -Imports {mefNamespace} - - -Class C - - Public Sub New() - End Sub -End Class -"; + var source = $""" + Imports {mefNamespace} + + + Class C + Public Sub New() + End Sub + End Class + """; + var fixedSource = $""" + Imports {mefNamespace} + + + Class C + + Public Sub New() + End Sub + End Class + """; await new VerifyVB.Test { @@ -725,7 +725,7 @@ End Class { Sources = { source }, AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyVB.Diagnostic().WithSpan(6, 5, 6, 21).WithArguments("C") }, + ExpectedDiagnostics = { VerifyVB.Diagnostic().WithSpan(5, 5, 5, 21).WithArguments("C") }, }, FixedState = { @@ -739,21 +739,21 @@ End Class [InlineData("System.ComponentModel.Composition")] public async Task MissingAttributeConstructorAddImport_CSharpAsync(string mefNamespace) { - var source = $@" -[{mefNamespace}.Export] -class C {{ - public C() {{ }} -}} -"; - var fixedSource = $@" -using {mefNamespace}; - -[{mefNamespace}.Export] -class C {{ - [ImportingConstructor] - public C() {{ }} -}} -"; + var source = $$""" + [{{mefNamespace}}.Export] + class C { + public C() { } + } + """; + var fixedSource = $$""" + using {{mefNamespace}}; + + [{{mefNamespace}}.Export] + class C { + [ImportingConstructor] + public C() { } + } + """; await new VerifyCS.Test { @@ -761,7 +761,7 @@ public C() {{ }} { Sources = { source }, AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyCS.Diagnostic().WithSpan(4, 5, 4, 19).WithArguments("C") }, + ExpectedDiagnostics = { VerifyCS.Diagnostic().WithSpan(3, 5, 3, 19).WithArguments("C") }, }, FixedState = { @@ -775,23 +775,23 @@ public C() {{ }} [InlineData("System.ComponentModel.Composition")] public async Task MissingAttributeConstructorAddImport_VisualBasicAsync(string mefNamespace) { - var source = $@" -<{mefNamespace}.Export> -Class C - Public Sub New() - End Sub -End Class -"; - var fixedSource = $@" -Imports {mefNamespace} - -<{mefNamespace}.Export> -Class C - - Public Sub New() - End Sub -End Class -"; + var source = $""" + <{mefNamespace}.Export> + Class C + Public Sub New() + End Sub + End Class + """; + var fixedSource = $""" + Imports {mefNamespace} + + <{mefNamespace}.Export> + Class C + + Public Sub New() + End Sub + End Class + """; await new VerifyVB.Test { @@ -799,7 +799,7 @@ End Class { Sources = { source }, AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyVB.Diagnostic().WithSpan(4, 5, 4, 21).WithArguments("C") }, + ExpectedDiagnostics = { VerifyVB.Diagnostic().WithSpan(3, 5, 3, 21).WithArguments("C") }, }, FixedState = { @@ -813,24 +813,24 @@ End Class [InlineData("System.ComponentModel.Composition")] public async Task NonPublicConstructor_CSharpAsync(string mefNamespace) { - var source = $@" -using {mefNamespace}; - -[Export] -class C {{ - [ImportingConstructor] - internal C() {{ }} -}} -"; - var fixedSource = $@" -using {mefNamespace}; - -[Export] -class C {{ - [ImportingConstructor] - public C() {{ }} -}} -"; + var source = $$""" + using {{mefNamespace}}; + + [Export] + class C { + [ImportingConstructor] + internal C() { } + } + """; + var fixedSource = $$""" + using {{mefNamespace}}; + + [Export] + class C { + [ImportingConstructor] + public C() { } + } + """; await new VerifyCS.Test { @@ -838,7 +838,7 @@ public C() {{ }} { Sources = { source }, AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyCS.Diagnostic().WithSpan(6, 6, 6, 26).WithArguments("C") }, + ExpectedDiagnostics = { VerifyCS.Diagnostic().WithSpan(5, 6, 5, 26).WithArguments("C") }, }, FixedState = { @@ -852,26 +852,26 @@ public C() {{ }} [InlineData("System.ComponentModel.Composition")] public async Task NonPublicConstructor_VisualBasicAsync(string mefNamespace) { - var source = $@" -Imports {mefNamespace} - - -Class C - - Friend Sub New() - End Sub -End Class -"; - var fixedSource = $@" -Imports {mefNamespace} - - -Class C - - Public Sub New() - End Sub -End Class -"; + var source = $""" + Imports {mefNamespace} + + + Class C + + Friend Sub New() + End Sub + End Class + """; + var fixedSource = $""" + Imports {mefNamespace} + + + Class C + + Public Sub New() + End Sub + End Class + """; await new VerifyVB.Test { @@ -879,7 +879,7 @@ End Class { Sources = { source }, AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyVB.Diagnostic().WithSpan(6, 6, 6, 26).WithArguments("C") }, + ExpectedDiagnostics = { VerifyVB.Diagnostic().WithSpan(5, 6, 5, 26).WithArguments("C") }, }, FixedState = { @@ -893,19 +893,19 @@ End Class [InlineData("System.ComponentModel.Composition")] public async Task MultipleConstructors_CSharpAsync(string mefNamespace) { - var source = $@" -using {mefNamespace}; + var source = $$""" + using {{mefNamespace}}; -[Export] -class C {{ - [ImportingConstructor] - public C() {{ }} + [Export] + class C { + [ImportingConstructor] + public C() { } - internal C(string x) {{ }} + internal C(string x) { } - private C(int x) {{ }} -}} -"; + private C(int x) { } + } + """; await new VerifyCS.Test { @@ -915,8 +915,8 @@ private C(int x) {{ }} AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, ExpectedDiagnostics = { - VerifyCS.Diagnostic().WithSpan(9, 5, 9, 29).WithArguments("C"), - VerifyCS.Diagnostic().WithSpan(11, 5, 11, 25).WithArguments("C"), + VerifyCS.Diagnostic().WithSpan(8, 5, 8, 29).WithArguments("C"), + VerifyCS.Diagnostic().WithSpan(10, 5, 10, 25).WithArguments("C"), }, }, FixedState = @@ -932,22 +932,22 @@ private C(int x) {{ }} [InlineData("System.ComponentModel.Composition")] public async Task MultipleConstructors_VisualBasicAsync(string mefNamespace) { - var source = $@" -Imports {mefNamespace} + var source = $""" + Imports {mefNamespace} - -Class C - - Public Sub New() - End Sub + + Class C + + Public Sub New() + End Sub - Friend Sub New(x as String) - End Sub + Friend Sub New(x as String) + End Sub - Private Sub New(x as Integer) - End Sub -End Class -"; + Private Sub New(x as Integer) + End Sub + End Class + """; await new VerifyVB.Test { @@ -957,8 +957,8 @@ End Class AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, ExpectedDiagnostics = { - VerifyVB.Diagnostic().WithSpan(10, 5, 10, 32).WithArguments("C"), - VerifyVB.Diagnostic().WithSpan(13, 5, 13, 34).WithArguments("C"), + VerifyVB.Diagnostic().WithSpan(9, 5, 9, 32).WithArguments("C"), + VerifyVB.Diagnostic().WithSpan(12, 5, 12, 34).WithArguments("C"), }, }, FixedState = diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/ExposeMemberForTestingTests.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/ExposeMemberForTestingTests.cs index adf2fa9bde2d2..960367f50db21 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/ExposeMemberForTestingTests.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/ExposeMemberForTestingTests.cs @@ -16,28 +16,32 @@ public class ExposeMemberForTestingTests [Fact] public async Task ExposeFieldCSharpAsync() { - var source = @"class TestClass { - private int _field; - internal readonly struct [|TestAccessor|] { - private readonly TestClass _testClass; - internal TestAccessor(TestClass testClass) => _testClass = testClass; - } -}"; - var fixedSource = @"class TestClass { - private int _field; - internal readonly struct [|TestAccessor|] { - private readonly TestClass _testClass; - internal TestAccessor(TestClass testClass) => _testClass = testClass; - - internal ref int Field - { - get - { - return ref _testClass._field; - } - } - } -}"; + var source = """ + class TestClass { + private int _field; + internal readonly struct [|TestAccessor|] { + private readonly TestClass _testClass; + internal TestAccessor(TestClass testClass) => _testClass = testClass; + } + } + """; + var fixedSource = """ + class TestClass { + private int _field; + internal readonly struct [|TestAccessor|] { + private readonly TestClass _testClass; + internal TestAccessor(TestClass testClass) => _testClass = testClass; + + internal ref int Field + { + get + { + return ref _testClass._field; + } + } + } + } + """; await new VerifyCS.Test { @@ -56,33 +60,37 @@ internal ref int Field [Fact] public async Task ExposeFieldVisualBasicAsync() { - var source = @"Class TestClass - Private Dim _field As Integer - Friend Structure [|TestAccessor|] - Private Dim ReadOnly _testClass As TestClass - Friend Sub New(testClass As TestClass) - _testClass = testClass - End Sub - End Structure -End Class"; - var fixedSource = @"Class TestClass - Private Dim _field As Integer - Friend Structure [|TestAccessor|] - Private Dim ReadOnly _testClass As TestClass - Friend Sub New(testClass As TestClass) - _testClass = testClass - End Sub - - Friend Property Field As Integer - Get - Return _testClass._field - End Get - Set(value As Integer) - _testClass._field = value - End Set - End Property - End Structure -End Class"; + var source = """ + Class TestClass + Private Dim _field As Integer + Friend Structure [|TestAccessor|] + Private Dim ReadOnly _testClass As TestClass + Friend Sub New(testClass As TestClass) + _testClass = testClass + End Sub + End Structure + End Class + """; + var fixedSource = """ + Class TestClass + Private Dim _field As Integer + Friend Structure [|TestAccessor|] + Private Dim ReadOnly _testClass As TestClass + Friend Sub New(testClass As TestClass) + _testClass = testClass + End Sub + + Friend Property Field As Integer + Get + Return _testClass._field + End Get + Set(value As Integer) + _testClass._field = value + End Set + End Property + End Structure + End Class + """; await new VerifyVB.Test { @@ -101,28 +109,32 @@ End Structure [Fact] public async Task ExposeReadOnlyFieldCSharpAsync() { - var source = @"class TestClass { - private readonly int _field; - internal readonly struct [|TestAccessor|] { - private readonly TestClass _testClass; - internal TestAccessor(TestClass testClass) => _testClass = testClass; - } -}"; - var fixedSource = @"class TestClass { - private readonly int _field; - internal readonly struct [|TestAccessor|] { - private readonly TestClass _testClass; - internal TestAccessor(TestClass testClass) => _testClass = testClass; - - internal ref readonly int Field - { - get - { - return ref _testClass._field; - } - } - } -}"; + var source = """ + class TestClass { + private readonly int _field; + internal readonly struct [|TestAccessor|] { + private readonly TestClass _testClass; + internal TestAccessor(TestClass testClass) => _testClass = testClass; + } + } + """; + var fixedSource = """ + class TestClass { + private readonly int _field; + internal readonly struct [|TestAccessor|] { + private readonly TestClass _testClass; + internal TestAccessor(TestClass testClass) => _testClass = testClass; + + internal ref readonly int Field + { + get + { + return ref _testClass._field; + } + } + } + } + """; await new VerifyCS.Test { @@ -141,30 +153,34 @@ internal ref readonly int Field [Fact] public async Task ExposeReadOnlyFieldVisualBasicAsync() { - var source = @"Class TestClass - Private ReadOnly _field As Integer - Friend Structure [|TestAccessor|] - Private Dim ReadOnly _testClass As TestClass - Friend Sub New(testClass As TestClass) - _testClass = testClass - End Sub - End Structure -End Class"; - var fixedSource = @"Class TestClass - Private ReadOnly _field As Integer - Friend Structure [|TestAccessor|] - Private Dim ReadOnly _testClass As TestClass - Friend Sub New(testClass As TestClass) - _testClass = testClass - End Sub - - Friend ReadOnly Property Field As Integer - Get - Return _testClass._field - End Get - End Property - End Structure -End Class"; + var source = """ + Class TestClass + Private ReadOnly _field As Integer + Friend Structure [|TestAccessor|] + Private Dim ReadOnly _testClass As TestClass + Friend Sub New(testClass As TestClass) + _testClass = testClass + End Sub + End Structure + End Class + """; + var fixedSource = """ + Class TestClass + Private ReadOnly _field As Integer + Friend Structure [|TestAccessor|] + Private Dim ReadOnly _testClass As TestClass + Friend Sub New(testClass As TestClass) + _testClass = testClass + End Sub + + Friend ReadOnly Property Field As Integer + Get + Return _testClass._field + End Get + End Property + End Structure + End Class + """; await new VerifyVB.Test { @@ -183,33 +199,37 @@ End Structure [Fact] public async Task ExposePropertyCSharpAsync() { - var source = @"class TestClass { - private int Property { get; set; } - internal readonly struct [|TestAccessor|] { - private readonly TestClass _testClass; - internal TestAccessor(TestClass testClass) => _testClass = testClass; - } -}"; - var fixedSource = @"class TestClass { - private int Property { get; set; } - internal readonly struct [|TestAccessor|] { - private readonly TestClass _testClass; - internal TestAccessor(TestClass testClass) => _testClass = testClass; - - internal int Property - { - get - { - return _testClass.Property; - } - - set - { - _testClass.Property = value; - } - } - } -}"; + var source = """ + class TestClass { + private int Property { get; set; } + internal readonly struct [|TestAccessor|] { + private readonly TestClass _testClass; + internal TestAccessor(TestClass testClass) => _testClass = testClass; + } + } + """; + var fixedSource = """ + class TestClass { + private int Property { get; set; } + internal readonly struct [|TestAccessor|] { + private readonly TestClass _testClass; + internal TestAccessor(TestClass testClass) => _testClass = testClass; + + internal int Property + { + get + { + return _testClass.Property; + } + + set + { + _testClass.Property = value; + } + } + } + } + """; await new VerifyCS.Test { @@ -228,33 +248,37 @@ internal int Property [Fact] public async Task ExposePropertyVisualBasicAsync() { - var source = @"Class TestClass - Private Property TestProperty As Integer - Friend Structure [|TestAccessor|] - Private Dim ReadOnly _testClass As TestClass - Friend Sub New(testClass As TestClass) - _testClass = testClass - End Sub - End Structure -End Class"; - var fixedSource = @"Class TestClass - Private Property TestProperty As Integer - Friend Structure [|TestAccessor|] - Private Dim ReadOnly _testClass As TestClass - Friend Sub New(testClass As TestClass) - _testClass = testClass - End Sub - - Friend Property TestProperty As Integer - Get - Return _testClass.TestProperty - End Get - Set(value As Integer) - _testClass.TestProperty = value - End Set - End Property - End Structure -End Class"; + var source = """ + Class TestClass + Private Property TestProperty As Integer + Friend Structure [|TestAccessor|] + Private Dim ReadOnly _testClass As TestClass + Friend Sub New(testClass As TestClass) + _testClass = testClass + End Sub + End Structure + End Class + """; + var fixedSource = """ + Class TestClass + Private Property TestProperty As Integer + Friend Structure [|TestAccessor|] + Private Dim ReadOnly _testClass As TestClass + Friend Sub New(testClass As TestClass) + _testClass = testClass + End Sub + + Friend Property TestProperty As Integer + Get + Return _testClass.TestProperty + End Get + Set(value As Integer) + _testClass.TestProperty = value + End Set + End Property + End Structure + End Class + """; await new VerifyVB.Test { @@ -273,28 +297,32 @@ End Structure [Fact] public async Task ExposeReadOnlyPropertyCSharpAsync() { - var source = @"class TestClass { - private int Property { get; } - internal readonly struct [|TestAccessor|] { - private readonly TestClass _testClass; - internal TestAccessor(TestClass testClass) => _testClass = testClass; - } -}"; - var fixedSource = @"class TestClass { - private int Property { get; } - internal readonly struct [|TestAccessor|] { - private readonly TestClass _testClass; - internal TestAccessor(TestClass testClass) => _testClass = testClass; - - internal int Property - { - get - { - return _testClass.Property; - } - } - } -}"; + var source = """ + class TestClass { + private int Property { get; } + internal readonly struct [|TestAccessor|] { + private readonly TestClass _testClass; + internal TestAccessor(TestClass testClass) => _testClass = testClass; + } + } + """; + var fixedSource = """ + class TestClass { + private int Property { get; } + internal readonly struct [|TestAccessor|] { + private readonly TestClass _testClass; + internal TestAccessor(TestClass testClass) => _testClass = testClass; + + internal int Property + { + get + { + return _testClass.Property; + } + } + } + } + """; await new VerifyCS.Test { @@ -313,30 +341,34 @@ internal int Property [Fact] public async Task ExposeReadOnlyPropertyVisualBasicAsync() { - var source = @"Class TestClass - Private ReadOnly Property TestProperty As Integer - Friend Structure [|TestAccessor|] - Private Dim ReadOnly _testClass As TestClass - Friend Sub New(testClass As TestClass) - _testClass = testClass - End Sub - End Structure -End Class"; - var fixedSource = @"Class TestClass - Private ReadOnly Property TestProperty As Integer - Friend Structure [|TestAccessor|] - Private Dim ReadOnly _testClass As TestClass - Friend Sub New(testClass As TestClass) - _testClass = testClass - End Sub - - Friend ReadOnly Property TestProperty As Integer - Get - Return _testClass.TestProperty - End Get - End Property - End Structure -End Class"; + var source = """ + Class TestClass + Private ReadOnly Property TestProperty As Integer + Friend Structure [|TestAccessor|] + Private Dim ReadOnly _testClass As TestClass + Friend Sub New(testClass As TestClass) + _testClass = testClass + End Sub + End Structure + End Class + """; + var fixedSource = """ + Class TestClass + Private ReadOnly Property TestProperty As Integer + Friend Structure [|TestAccessor|] + Private Dim ReadOnly _testClass As TestClass + Friend Sub New(testClass As TestClass) + _testClass = testClass + End Sub + + Friend ReadOnly Property TestProperty As Integer + Get + Return _testClass.TestProperty + End Get + End Property + End Structure + End Class + """; await new VerifyVB.Test { @@ -355,28 +387,32 @@ End Structure [Fact] public async Task ExposeWriteOnlyPropertyCSharpAsync() { - var source = @"class TestClass { - private int Property { set { } } - internal readonly struct [|TestAccessor|] { - private readonly TestClass _testClass; - internal TestAccessor(TestClass testClass) => _testClass = testClass; - } -}"; - var fixedSource = @"class TestClass { - private int Property { set { } } - internal readonly struct [|TestAccessor|] { - private readonly TestClass _testClass; - internal TestAccessor(TestClass testClass) => _testClass = testClass; - - internal int Property - { - set - { - _testClass.Property = value; - } - } - } -}"; + var source = """ + class TestClass { + private int Property { set { } } + internal readonly struct [|TestAccessor|] { + private readonly TestClass _testClass; + internal TestAccessor(TestClass testClass) => _testClass = testClass; + } + } + """; + var fixedSource = """ + class TestClass { + private int Property { set { } } + internal readonly struct [|TestAccessor|] { + private readonly TestClass _testClass; + internal TestAccessor(TestClass testClass) => _testClass = testClass; + + internal int Property + { + set + { + _testClass.Property = value; + } + } + } + } + """; await new VerifyCS.Test { @@ -395,36 +431,40 @@ internal int Property [Fact] public async Task ExposeWriteOnlyPropertyVisualBasicAsync() { - var source = @"Class TestClass - Private WriteOnly Property TestProperty As Integer - Set(value As Integer) - End Set - End Property - Friend Structure [|TestAccessor|] - Private Dim ReadOnly _testClass As TestClass - Friend Sub New(testClass As TestClass) - _testClass = testClass - End Sub - End Structure -End Class"; - var fixedSource = @"Class TestClass - Private WriteOnly Property TestProperty As Integer - Set(value As Integer) - End Set - End Property - Friend Structure [|TestAccessor|] - Private Dim ReadOnly _testClass As TestClass - Friend Sub New(testClass As TestClass) - _testClass = testClass - End Sub - - Friend WriteOnly Property TestProperty As Integer - Set(value As Integer) - _testClass.TestProperty = value - End Set - End Property - End Structure -End Class"; + var source = """ + Class TestClass + Private WriteOnly Property TestProperty As Integer + Set(value As Integer) + End Set + End Property + Friend Structure [|TestAccessor|] + Private Dim ReadOnly _testClass As TestClass + Friend Sub New(testClass As TestClass) + _testClass = testClass + End Sub + End Structure + End Class + """; + var fixedSource = """ + Class TestClass + Private WriteOnly Property TestProperty As Integer + Set(value As Integer) + End Set + End Property + Friend Structure [|TestAccessor|] + Private Dim ReadOnly _testClass As TestClass + Friend Sub New(testClass As TestClass) + _testClass = testClass + End Sub + + Friend WriteOnly Property TestProperty As Integer + Set(value As Integer) + _testClass.TestProperty = value + End Set + End Property + End Structure + End Class + """; await new VerifyVB.Test { diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/ImportingConstructorShouldBeObsoleteTests.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/ImportingConstructorShouldBeObsoleteTests.cs index 90917dc75d345..4f01537fea49a 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/ImportingConstructorShouldBeObsoleteTests.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/ImportingConstructorShouldBeObsoleteTests.cs @@ -5,766 +5,746 @@ using System.Threading.Tasks; using Test.Utilities; using Xunit; -using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< - Roslyn.Diagnostics.Analyzers.ImportingConstructorShouldBeObsolete, - Roslyn.Diagnostics.Analyzers.ImportingConstructorShouldBeObsoleteCodeFixProvider>; -using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< - Roslyn.Diagnostics.Analyzers.ImportingConstructorShouldBeObsolete, - Roslyn.Diagnostics.Analyzers.ImportingConstructorShouldBeObsoleteCodeFixProvider>; - -namespace Roslyn.Diagnostics.Analyzers.UnitTests + +namespace Roslyn.Diagnostics.Analyzers.UnitTests; + +using VerifyCS = CSharpCodeFixVerifier< + ImportingConstructorShouldBeObsolete, + CSharpImportingConstructorShouldBeObsoleteCodeFixProvider>; +using VerifyVB = VisualBasicCodeFixVerifier< + ImportingConstructorShouldBeObsolete, + BasicImportingConstructorShouldBeObsoleteCodeFixProvider>; + +public sealed class ImportingConstructorShouldBeObsoleteTests { - public class ImportingConstructorShouldBeObsoleteTests + [Theory] + [InlineData("System.Composition")] + [InlineData("System.ComponentModel.Composition")] + public async Task SingleExpectedConstructor_CSharpAsync(string mefNamespace) + { + var source = $$""" + using System; + using {{mefNamespace}}; + using Microsoft.CodeAnalysis.Host.Mef; + + [Export] + class C { + [ImportingConstructor] + [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + public C() { } + } + + namespace Microsoft.CodeAnalysis.Host.Mef { + static class MefConstruction { + internal const string ImportingConstructorMessage = "This exported object must be obtained through the MEF export provider."; + } + } + """; + + await new VerifyCS.Test + { + TestState = + { + Sources = { source }, + AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, + }, + }.RunAsync(); + } + + [Theory] + [InlineData("System.Composition")] + [InlineData("System.ComponentModel.Composition")] + public async Task SingleExpectedConstructor_VisualBasicAsync(string mefNamespace) { - [Theory] - [InlineData("System.Composition")] - [InlineData("System.ComponentModel.Composition")] - public async Task SingleExpectedConstructor_CSharpAsync(string mefNamespace) + var source = $""" + Imports System + Imports {mefNamespace} + Imports Microsoft.CodeAnalysis.Host.Mef + + + Class C + + + Public Sub New() + End Sub + End Class + + Namespace Global.Microsoft.CodeAnalysis.Host.Mef.MefConstruction + Module MefConstruction + Friend Const ImportingConstructorMessage As String = "This exported object must be obtained through the MEF export provider." + End Module + End Namespace + """; + + await new VerifyVB.Test { - var source = $@" -using System; -using {mefNamespace}; -using Microsoft.CodeAnalysis.Host.Mef; - -[Export] -class C {{ - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public C() {{ }} -}} - -namespace Microsoft.CodeAnalysis.Host.Mef {{ - static class MefConstruction {{ - internal const string ImportingConstructorMessage = ""This exported object must be obtained through the MEF export provider.""; - }} -}} -"; - - await new VerifyCS.Test + TestState = { - TestState = - { - Sources = { source }, - AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - }, - }.RunAsync(); - } - - [Theory] - [InlineData("System.Composition")] - [InlineData("System.ComponentModel.Composition")] - public async Task SingleExpectedConstructor_VisualBasicAsync(string mefNamespace) + Sources = { source }, + AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, + }, + }.RunAsync(); + } + + [Theory] + [InlineData("System.Composition")] + [InlineData("System.ComponentModel.Composition")] + public async Task ObsoleteButNotError_CSharpAsync(string mefNamespace) + { + var source = $$""" + using System; + using {{mefNamespace}}; + using Microsoft.CodeAnalysis.Host.Mef; + + [Export] + class C { + [ImportingConstructor] + [[|Obsolete(MefConstruction.ImportingConstructorMessage, error: false)|]] + public C() { } + } + + namespace Microsoft.CodeAnalysis.Host.Mef { + static class MefConstruction { + internal const string ImportingConstructorMessage = "This exported object must be obtained through the MEF export provider."; + } + } + """; + await new VerifyCS.Test { - var source = $@" -Imports System -Imports {mefNamespace} -Imports Microsoft.CodeAnalysis.Host.Mef - - -Class C - - - Public Sub New() - End Sub -End Class - -Namespace Global.Microsoft.CodeAnalysis.Host.Mef.MefConstruction - Module MefConstruction - Friend Const ImportingConstructorMessage As String = ""This exported object must be obtained through the MEF export provider."" - End Module -End Namespace -"; - - await new VerifyVB.Test + TestState = { - TestState = - { - Sources = { source }, - AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - }, - }.RunAsync(); - } - - [Theory] - [InlineData("System.Composition")] - [InlineData("System.ComponentModel.Composition")] - public async Task ObsoleteButNotError_CSharpAsync(string mefNamespace) + Sources = { source }, + AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, + }, + FixedCode = $$""" + using System; + using {{mefNamespace}}; + using Microsoft.CodeAnalysis.Host.Mef; + + [Export] + class C { + [ImportingConstructor] + [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + public C() { } + } + + namespace Microsoft.CodeAnalysis.Host.Mef { + static class MefConstruction { + internal const string ImportingConstructorMessage = "This exported object must be obtained through the MEF export provider."; + } + } + """, + }.RunAsync(); + } + + [Theory] + [InlineData("System.Composition")] + [InlineData("System.ComponentModel.Composition")] + public async Task ObsoleteButNotError_VisualBasicAsync(string mefNamespace) + { + var source = $""" + Imports System + Imports {mefNamespace} + Imports Microsoft.CodeAnalysis.Host.Mef + + + Class C + + <[|Obsolete(MefConstruction.ImportingConstructorMessage, False)|]> + Public Sub New() + End Sub + End Class + + Namespace Global.Microsoft.CodeAnalysis.Host.Mef.MefConstruction + Module MefConstruction + Friend Const ImportingConstructorMessage As String = "This exported object must be obtained through the MEF export provider." + End Module + End Namespace + """; + await new VerifyVB.Test { - var source = $@" -using System; -using {mefNamespace}; -using Microsoft.CodeAnalysis.Host.Mef; - -[Export] -class C {{ - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: false)] - public C() {{ }} -}} - -namespace Microsoft.CodeAnalysis.Host.Mef {{ - static class MefConstruction {{ - internal const string ImportingConstructorMessage = ""This exported object must be obtained through the MEF export provider.""; - }} -}} -"; - var fixedSource = $@" -using System; -using {mefNamespace}; -using Microsoft.CodeAnalysis.Host.Mef; - -[Export] -class C {{ - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public C() {{ }} -}} - -namespace Microsoft.CodeAnalysis.Host.Mef {{ - static class MefConstruction {{ - internal const string ImportingConstructorMessage = ""This exported object must be obtained through the MEF export provider.""; - }} -}} -"; - - await new VerifyCS.Test + TestState = { - TestState = - { - Sources = { source }, - AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyCS.Diagnostic().WithSpan(9, 6, 9, 73).WithArguments("C") }, - }, - FixedState = - { - Sources = { fixedSource }, - }, - }.RunAsync(); - } - - [Theory] - [InlineData("System.Composition")] - [InlineData("System.ComponentModel.Composition")] - public async Task ObsoleteButNotError_VisualBasicAsync(string mefNamespace) + Sources = { source }, + AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, + }, + FixedCode = $""" + Imports System + Imports {mefNamespace} + Imports Microsoft.CodeAnalysis.Host.Mef + + + Class C + + + Public Sub New() + End Sub + End Class + + Namespace Global.Microsoft.CodeAnalysis.Host.Mef.MefConstruction + Module MefConstruction + Friend Const ImportingConstructorMessage As String = "This exported object must be obtained through the MEF export provider." + End Module + End Namespace + """, + }.RunAsync(); + } + + [WindowsOnlyTheory] + [InlineData("System.Composition")] + [InlineData("System.ComponentModel.Composition")] + public async Task NotMarkedObsolete_CSharpAsync(string mefNamespace) + { + var source = $$""" + using System; + using {{mefNamespace}}; + + [Export] + class C { + [[|ImportingConstructor|]] + public C() { } + } + + namespace Microsoft.CodeAnalysis.Host.Mef { + static class MefConstruction { + internal const string ImportingConstructorMessage = "This exported object must be obtained through the MEF export provider."; + } + } + """; + await new VerifyCS.Test { - var source = $@" -Imports System -Imports {mefNamespace} -Imports Microsoft.CodeAnalysis.Host.Mef - - -Class C - - - Public Sub New() - End Sub -End Class - -Namespace Global.Microsoft.CodeAnalysis.Host.Mef.MefConstruction - Module MefConstruction - Friend Const ImportingConstructorMessage As String = ""This exported object must be obtained through the MEF export provider."" - End Module -End Namespace -"; - var fixedSource = $@" -Imports System -Imports {mefNamespace} -Imports Microsoft.CodeAnalysis.Host.Mef - - -Class C - - - Public Sub New() - End Sub -End Class - -Namespace Global.Microsoft.CodeAnalysis.Host.Mef.MefConstruction - Module MefConstruction - Friend Const ImportingConstructorMessage As String = ""This exported object must be obtained through the MEF export provider."" - End Module -End Namespace -"; - - await new VerifyVB.Test + TestState = { - TestState = - { - Sources = { source }, - AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyVB.Diagnostic().WithSpan(9, 6, 9, 66).WithArguments("C") }, - }, - FixedState = - { - Sources = { fixedSource }, - }, - }.RunAsync(); - } - - [WindowsOnlyTheory] - [InlineData("System.Composition")] - [InlineData("System.ComponentModel.Composition")] - public async Task NotMarkedObsolete_CSharpAsync(string mefNamespace) + Sources = { source }, + AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, + }, + FixedCode = $$""" + using System; + using {{mefNamespace}}; + using Microsoft.CodeAnalysis.Host.Mef; + + [Export] + class C { + [ImportingConstructor] + [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + public C() { } + } + + namespace Microsoft.CodeAnalysis.Host.Mef { + static class MefConstruction { + internal const string ImportingConstructorMessage = "This exported object must be obtained through the MEF export provider."; + } + } + """, + }.RunAsync(); + } + + [WindowsOnlyTheory] + [InlineData("System.Composition")] + [InlineData("System.ComponentModel.Composition")] + public async Task NotMarkedObsolete_PrimaryConstructor_CSharpAsync(string mefNamespace) + { + var source = $$""" + using System; + using {{mefNamespace}}; + + [Export] + [method: [|ImportingConstructor|]] + class C() { + } + + namespace Microsoft.CodeAnalysis.Host.Mef { + static class MefConstruction { + internal const string ImportingConstructorMessage = "This exported object must be obtained through the MEF export provider."; + } + } + """; + await new VerifyCS.Test { - var source = $@" -using System; -using {mefNamespace}; - -[Export] -class C {{ - [ImportingConstructor] - public C() {{ }} -}} - -namespace Microsoft.CodeAnalysis.Host.Mef {{ - static class MefConstruction {{ - internal const string ImportingConstructorMessage = ""This exported object must be obtained through the MEF export provider.""; - }} -}} -"; - var fixedSource = $@" -using System; -using {mefNamespace}; -using Microsoft.CodeAnalysis.Host.Mef; - -[Export] -class C {{ - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public C() {{ }} -}} - -namespace Microsoft.CodeAnalysis.Host.Mef {{ - static class MefConstruction {{ - internal const string ImportingConstructorMessage = ""This exported object must be obtained through the MEF export provider.""; - }} -}} -"; - - await new VerifyCS.Test + TestState = { - TestState = - { - Sources = { source }, - AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyCS.Diagnostic().WithSpan(7, 6, 7, 26).WithArguments("C") }, - }, - FixedState = - { - Sources = { fixedSource }, - }, - }.RunAsync(); - } - - [WindowsOnlyTheory] - [InlineData("System.Composition")] - [InlineData("System.ComponentModel.Composition")] - public async Task NotMarkedObsolete_VisualBasicAsync(string mefNamespace) + Sources = { source }, + AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, + }, + FixedCode = $$""" + using System; + using {{mefNamespace}}; + using Microsoft.CodeAnalysis.Host.Mef; + + [Export] + [method: ImportingConstructor] + [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + class C() { + } + + namespace Microsoft.CodeAnalysis.Host.Mef { + static class MefConstruction { + internal const string ImportingConstructorMessage = "This exported object must be obtained through the MEF export provider."; + } + } + """, + LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp12, + }.RunAsync(); + } + + [WindowsOnlyTheory] + [InlineData("System.Composition")] + [InlineData("System.ComponentModel.Composition")] + public async Task NotMarkedObsolete_VisualBasicAsync(string mefNamespace) + { + var source = $""" + Imports System + Imports {mefNamespace} + + + Class C + <[|ImportingConstructor|]> + Public Sub New() + End Sub + End Class + + Namespace Global.Microsoft.CodeAnalysis.Host.Mef + Module MefConstruction + Friend Const ImportingConstructorMessage As String = "This exported object must be obtained through the MEF export provider." + End Module + End Namespace + """; + await new VerifyVB.Test { - var source = $@" -Imports System -Imports {mefNamespace} - - -Class C - - Public Sub New() - End Sub -End Class - -Namespace Global.Microsoft.CodeAnalysis.Host.Mef - Module MefConstruction - Friend Const ImportingConstructorMessage As String = ""This exported object must be obtained through the MEF export provider."" - End Module -End Namespace -"; - var fixedSource = $@" -Imports System -Imports {mefNamespace} -Imports Microsoft.CodeAnalysis.Host.Mef - - -Class C - - - Public Sub New() - End Sub -End Class - -Namespace Global.Microsoft.CodeAnalysis.Host.Mef - Module MefConstruction - Friend Const ImportingConstructorMessage As String = ""This exported object must be obtained through the MEF export provider."" - End Module -End Namespace -"; - - await new VerifyVB.Test + TestState = { - TestState = - { - Sources = { source }, - AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyVB.Diagnostic().WithSpan(7, 6, 7, 26).WithArguments("C") }, - }, - FixedState = - { - Sources = { fixedSource }, - }, - }.RunAsync(); - } - - [WindowsOnlyTheory] - [InlineData("System.Composition")] - [InlineData("System.ComponentModel.Composition")] - public async Task NotMarkedObsoleteAddImports_CSharpAsync(string mefNamespace) + Sources = { source }, + AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, + }, + FixedCode = $""" + Imports System + Imports {mefNamespace} + Imports Microsoft.CodeAnalysis.Host.Mef + + + Class C + + + Public Sub New() + End Sub + End Class + + Namespace Global.Microsoft.CodeAnalysis.Host.Mef + Module MefConstruction + Friend Const ImportingConstructorMessage As String = "This exported object must be obtained through the MEF export provider." + End Module + End Namespace + """, + }.RunAsync(); + } + + [WindowsOnlyTheory] + [InlineData("System.Composition")] + [InlineData("System.ComponentModel.Composition")] + public async Task NotMarkedObsoleteAddImports_CSharpAsync(string mefNamespace) + { + var source = $$""" + using {{mefNamespace}}; + + [Export] + class C { + [[|ImportingConstructor|]] + public C() { } + } + """; + var helperSource = $$""" + namespace Microsoft.CodeAnalysis.Host.Mef { + static class MefConstruction { + internal const string ImportingConstructorMessage = "This exported object must be obtained through the MEF export provider."; + } + } + """; + var fixedSource = $$""" + using System; + using {{mefNamespace}}; + using Microsoft.CodeAnalysis.Host.Mef; + + [Export] + class C { + [ImportingConstructor] + [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + public C() { } + } + """; + + await new VerifyCS.Test { - var source = $@" -using {mefNamespace}; - -[Export] -class C {{ - [ImportingConstructor] - public C() {{ }} -}} -"; - var helperSource = $@" -namespace Microsoft.CodeAnalysis.Host.Mef {{ - static class MefConstruction {{ - internal const string ImportingConstructorMessage = ""This exported object must be obtained through the MEF export provider.""; - }} -}} -"; - var fixedSource = $@" -using System; -using {mefNamespace}; -using Microsoft.CodeAnalysis.Host.Mef; - -[Export] -class C {{ - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public C() {{ }} -}} -"; - - await new VerifyCS.Test + TestState = + { + Sources = { source, helperSource }, + AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, + }, + FixedState = { - TestState = - { - Sources = { source, helperSource }, - AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyCS.Diagnostic().WithSpan(6, 6, 6, 26).WithArguments("C") }, - }, - FixedState = - { - Sources = { fixedSource, helperSource }, - }, - }.RunAsync(); - } - - [WindowsOnlyTheory] - [InlineData("System.Composition")] - [InlineData("System.ComponentModel.Composition")] - public async Task NotMarkedObsoleteAddImports_VisualBasicAsync(string mefNamespace) + Sources = { fixedSource, helperSource }, + }, + }.RunAsync(); + } + + [WindowsOnlyTheory] + [InlineData("System.Composition")] + [InlineData("System.ComponentModel.Composition")] + public async Task NotMarkedObsoleteAddImports_VisualBasicAsync(string mefNamespace) + { + var source = $""" + Imports {mefNamespace} + + + Class C + <[|ImportingConstructor|]> + Public Sub New() + End Sub + End Class + + Namespace Global.Microsoft.CodeAnalysis.Host.Mef + Module MefConstruction + Friend Const ImportingConstructorMessage As String = "This exported object must be obtained through the MEF export provider." + End Module + End Namespace + """; + await new VerifyVB.Test { - var source = $@" -Imports {mefNamespace} - - -Class C - - Public Sub New() - End Sub -End Class - -Namespace Global.Microsoft.CodeAnalysis.Host.Mef - Module MefConstruction - Friend Const ImportingConstructorMessage As String = ""This exported object must be obtained through the MEF export provider."" - End Module -End Namespace -"; - var fixedSource = $@" -Imports System - -Imports {mefNamespace} -Imports Microsoft.CodeAnalysis.Host.Mef - - -Class C - - - Public Sub New() - End Sub -End Class - -Namespace Global.Microsoft.CodeAnalysis.Host.Mef - Module MefConstruction - Friend Const ImportingConstructorMessage As String = ""This exported object must be obtained through the MEF export provider."" - End Module -End Namespace -"; - - await new VerifyVB.Test + TestState = { - TestState = - { - Sources = { source }, - AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyVB.Diagnostic().WithSpan(6, 6, 6, 26).WithArguments("C") }, - }, - FixedState = - { - Sources = { fixedSource }, - }, - }.RunAsync(); - } - - [WindowsOnlyTheory] - [InlineData("System.Composition")] - [InlineData("System.ComponentModel.Composition")] - public async Task MessageArgumentOmitted_CSharpAsync(string mefNamespace) + Sources = { source }, + AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, + }, + FixedCode = $""" + Imports System + Imports {mefNamespace} + Imports Microsoft.CodeAnalysis.Host.Mef + + + Class C + + + Public Sub New() + End Sub + End Class + + Namespace Global.Microsoft.CodeAnalysis.Host.Mef + Module MefConstruction + Friend Const ImportingConstructorMessage As String = "This exported object must be obtained through the MEF export provider." + End Module + End Namespace + """, + }.RunAsync(); + } + + [WindowsOnlyTheory] + [InlineData("System.Composition")] + [InlineData("System.ComponentModel.Composition")] + public async Task MessageArgumentOmitted_CSharpAsync(string mefNamespace) + { + var source = $$""" + using System; + using {{mefNamespace}}; + + [Export] + class C { + [ImportingConstructor] + [[|Obsolete|]] + public C() { } + } + + namespace Microsoft.CodeAnalysis.Host.Mef { + static class MefConstruction { + internal const string ImportingConstructorMessage = "This exported object must be obtained through the MEF export provider."; + } + } + """; + await new VerifyCS.Test { - var source = $@" -using System; -using {mefNamespace}; - -[Export] -class C {{ - [ImportingConstructor] - [Obsolete] - public C() {{ }} -}} - -namespace Microsoft.CodeAnalysis.Host.Mef {{ - static class MefConstruction {{ - internal const string ImportingConstructorMessage = ""This exported object must be obtained through the MEF export provider.""; - }} -}} -"; - var fixedSource = $@" -using System; -using {mefNamespace}; -using Microsoft.CodeAnalysis.Host.Mef; - -[Export] -class C {{ - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public C() {{ }} -}} - -namespace Microsoft.CodeAnalysis.Host.Mef {{ - static class MefConstruction {{ - internal const string ImportingConstructorMessage = ""This exported object must be obtained through the MEF export provider.""; - }} -}} -"; - - await new VerifyCS.Test + TestState = { - TestState = - { - Sources = { source }, - AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyCS.Diagnostic().WithSpan(8, 6, 8, 14).WithArguments("C") }, - }, - FixedState = - { - Sources = { fixedSource }, - }, - }.RunAsync(); - } - - [WindowsOnlyTheory] - [InlineData("System.Composition")] - [InlineData("System.ComponentModel.Composition")] - public async Task MessageArgumentOmitted_VisualBasicAsync(string mefNamespace) + Sources = { source }, + AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, + }, + FixedCode = $$""" + using System; + using {{mefNamespace}}; + using Microsoft.CodeAnalysis.Host.Mef; + + [Export] + class C { + [ImportingConstructor] + [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + public C() { } + } + + namespace Microsoft.CodeAnalysis.Host.Mef { + static class MefConstruction { + internal const string ImportingConstructorMessage = "This exported object must be obtained through the MEF export provider."; + } + } + """, + }.RunAsync(); + } + + [WindowsOnlyTheory] + [InlineData("System.Composition")] + [InlineData("System.ComponentModel.Composition")] + public async Task MessageArgumentOmitted_VisualBasicAsync(string mefNamespace) + { + var source = $""" + Imports System + Imports {mefNamespace} + + + Class C + + <[|Obsolete|]> + Public Sub New() + End Sub + End Class + + Namespace Global.Microsoft.CodeAnalysis.Host.Mef + Module MefConstruction + Friend Const ImportingConstructorMessage As String = "This exported object must be obtained through the MEF export provider." + End Module + End Namespace + """; + await new VerifyVB.Test { - var source = $@" -Imports System -Imports {mefNamespace} - - -Class C - - - Public Sub New() - End Sub -End Class - -Namespace Global.Microsoft.CodeAnalysis.Host.Mef - Module MefConstruction - Friend Const ImportingConstructorMessage As String = ""This exported object must be obtained through the MEF export provider."" - End Module -End Namespace -"; - var fixedSource = $@" -Imports System -Imports {mefNamespace} -Imports Microsoft.CodeAnalysis.Host.Mef - - -Class C - - - Public Sub New() - End Sub -End Class - -Namespace Global.Microsoft.CodeAnalysis.Host.Mef - Module MefConstruction - Friend Const ImportingConstructorMessage As String = ""This exported object must be obtained through the MEF export provider."" - End Module -End Namespace -"; - - await new VerifyVB.Test + TestState = { - TestState = - { - Sources = { source }, - AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyVB.Diagnostic().WithSpan(8, 6, 8, 14).WithArguments("C") }, - }, - FixedState = - { - Sources = { fixedSource }, - }, - }.RunAsync(); - } - - [Theory] - [InlineData("System.Composition")] - [InlineData("System.ComponentModel.Composition")] - public async Task ErrorArgumentOmitted_CSharpAsync(string mefNamespace) + Sources = { source }, + AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, + }, + FixedCode = $""" + Imports System + Imports {mefNamespace} + Imports Microsoft.CodeAnalysis.Host.Mef + + + Class C + + + Public Sub New() + End Sub + End Class + + Namespace Global.Microsoft.CodeAnalysis.Host.Mef + Module MefConstruction + Friend Const ImportingConstructorMessage As String = "This exported object must be obtained through the MEF export provider." + End Module + End Namespace + """, + }.RunAsync(); + } + + [Theory] + [InlineData("System.Composition")] + [InlineData("System.ComponentModel.Composition")] + public async Task ErrorArgumentOmitted_CSharpAsync(string mefNamespace) + { + var source = $$""" + using System; + using {{mefNamespace}}; + using Microsoft.CodeAnalysis.Host.Mef; + + [Export] + class C { + [ImportingConstructor] + [[|Obsolete(MefConstruction.ImportingConstructorMessage)|]] + public C() { } + } + + namespace Microsoft.CodeAnalysis.Host.Mef { + static class MefConstruction { + internal const string ImportingConstructorMessage = "This exported object must be obtained through the MEF export provider."; + } + } + """; + await new VerifyCS.Test { - var source = $@" -using System; -using {mefNamespace}; -using Microsoft.CodeAnalysis.Host.Mef; - -[Export] -class C {{ - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage)] - public C() {{ }} -}} - -namespace Microsoft.CodeAnalysis.Host.Mef {{ - static class MefConstruction {{ - internal const string ImportingConstructorMessage = ""This exported object must be obtained through the MEF export provider.""; - }} -}} -"; - var fixedSource = $@" -using System; -using {mefNamespace}; -using Microsoft.CodeAnalysis.Host.Mef; - -[Export] -class C {{ - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public C() {{ }} -}} - -namespace Microsoft.CodeAnalysis.Host.Mef {{ - static class MefConstruction {{ - internal const string ImportingConstructorMessage = ""This exported object must be obtained through the MEF export provider.""; - }} -}} -"; - - await new VerifyCS.Test + TestState = { - TestState = - { - Sources = { source }, - AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyCS.Diagnostic().WithSpan(9, 6, 9, 59).WithArguments("C") }, - }, - FixedState = - { - Sources = { fixedSource }, - }, - }.RunAsync(); - } - - [Theory] - [InlineData("System.Composition")] - [InlineData("System.ComponentModel.Composition")] - public async Task ErrorArgumentOmitted_VisualBasicAsync(string mefNamespace) + Sources = { source }, + AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, + }, + FixedCode = $$""" + using System; + using {{mefNamespace}}; + using Microsoft.CodeAnalysis.Host.Mef; + + [Export] + class C { + [ImportingConstructor] + [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + public C() { } + } + + namespace Microsoft.CodeAnalysis.Host.Mef { + static class MefConstruction { + internal const string ImportingConstructorMessage = "This exported object must be obtained through the MEF export provider."; + } + } + """, + }.RunAsync(); + } + + [Theory] + [InlineData("System.Composition")] + [InlineData("System.ComponentModel.Composition")] + public async Task ErrorArgumentOmitted_VisualBasicAsync(string mefNamespace) + { + var source = $""" + Imports System + Imports {mefNamespace} + Imports Microsoft.CodeAnalysis.Host.Mef + + + Class C + + <[|Obsolete(MefConstruction.ImportingConstructorMessage)|]> + Public Sub New() + End Sub + End Class + + Namespace Global.Microsoft.CodeAnalysis.Host.Mef.MefConstruction + Module MefConstruction + Friend Const ImportingConstructorMessage As String = "This exported object must be obtained through the MEF export provider." + End Module + End Namespace + """; + await new VerifyVB.Test { - var source = $@" -Imports System -Imports {mefNamespace} -Imports Microsoft.CodeAnalysis.Host.Mef - - -Class C - - - Public Sub New() - End Sub -End Class - -Namespace Global.Microsoft.CodeAnalysis.Host.Mef.MefConstruction - Module MefConstruction - Friend Const ImportingConstructorMessage As String = ""This exported object must be obtained through the MEF export provider."" - End Module -End Namespace -"; - var fixedSource = $@" -Imports System -Imports {mefNamespace} -Imports Microsoft.CodeAnalysis.Host.Mef - - -Class C - - - Public Sub New() - End Sub -End Class - -Namespace Global.Microsoft.CodeAnalysis.Host.Mef.MefConstruction - Module MefConstruction - Friend Const ImportingConstructorMessage As String = ""This exported object must be obtained through the MEF export provider."" - End Module -End Namespace -"; - - await new VerifyVB.Test + TestState = { - TestState = - { - Sources = { source }, - AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyVB.Diagnostic().WithSpan(9, 6, 9, 59).WithArguments("C") }, - }, - FixedState = - { - Sources = { fixedSource }, - }, - }.RunAsync(); - } - - [WindowsOnlyTheory] - [InlineData("System.Composition")] - [InlineData("System.ComponentModel.Composition")] - public async Task IncorrectMessage_CSharpAsync(string mefNamespace) + Sources = { source }, + AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, + }, + FixedCode = $""" + Imports System + Imports {mefNamespace} + Imports Microsoft.CodeAnalysis.Host.Mef + + + Class C + + + Public Sub New() + End Sub + End Class + + Namespace Global.Microsoft.CodeAnalysis.Host.Mef.MefConstruction + Module MefConstruction + Friend Const ImportingConstructorMessage As String = "This exported object must be obtained through the MEF export provider." + End Module + End Namespace + """, + }.RunAsync(); + } + + [WindowsOnlyTheory] + [InlineData("System.Composition")] + [InlineData("System.ComponentModel.Composition")] + public async Task IncorrectMessage_CSharpAsync(string mefNamespace) + { + var source = $$""" + using System; + using {{mefNamespace}}; + + [Export] + class C { + [ImportingConstructor] + [[|Obsolete("INCORRECT MESSAGE")|]] + public C() { } + } + + namespace Microsoft.CodeAnalysis.Host.Mef { + static class MefConstruction { + internal const string ImportingConstructorMessage = "This exported object must be obtained through the MEF export provider."; + } + } + """; + await new VerifyCS.Test { - var source = $@" -using System; -using {mefNamespace}; - -[Export] -class C {{ - [ImportingConstructor] - [Obsolete(""INCORRECT MESSAGE"")] - public C() {{ }} -}} - -namespace Microsoft.CodeAnalysis.Host.Mef {{ - static class MefConstruction {{ - internal const string ImportingConstructorMessage = ""This exported object must be obtained through the MEF export provider.""; - }} -}} -"; - var fixedSource = $@" -using System; -using {mefNamespace}; -using Microsoft.CodeAnalysis.Host.Mef; - -[Export] -class C {{ - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public C() {{ }} -}} - -namespace Microsoft.CodeAnalysis.Host.Mef {{ - static class MefConstruction {{ - internal const string ImportingConstructorMessage = ""This exported object must be obtained through the MEF export provider.""; - }} -}} -"; - - await new VerifyCS.Test + TestState = { - TestState = - { - Sources = { source }, - AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyCS.Diagnostic().WithSpan(8, 6, 8, 35).WithArguments("C") }, - }, - FixedState = - { - Sources = { fixedSource }, - }, - NumberOfIncrementalIterations = 2, - NumberOfFixAllIterations = 2, - }.RunAsync(); - } - - [WindowsOnlyTheory] - [InlineData("System.Composition")] - [InlineData("System.ComponentModel.Composition")] - public async Task IncorrectMessage_VisualBasicAsync(string mefNamespace) + Sources = { source }, + AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, + }, + FixedCode = $$""" + using System; + using {{mefNamespace}}; + using Microsoft.CodeAnalysis.Host.Mef; + + [Export] + class C { + [ImportingConstructor] + [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + public C() { } + } + + namespace Microsoft.CodeAnalysis.Host.Mef { + static class MefConstruction { + internal const string ImportingConstructorMessage = "This exported object must be obtained through the MEF export provider."; + } + } + """, + NumberOfIncrementalIterations = 2, + NumberOfFixAllIterations = 2, + }.RunAsync(); + } + + [WindowsOnlyTheory] + [InlineData("System.Composition")] + [InlineData("System.ComponentModel.Composition")] + public async Task IncorrectMessage_VisualBasicAsync(string mefNamespace) + { + var source = $""" + Imports System + Imports {mefNamespace} + + + Class C + + <[|Obsolete("INCORRECT MESSAGE")|]> + Public Sub New() + End Sub + End Class + + Namespace Global.Microsoft.CodeAnalysis.Host.Mef + Module MefConstruction + Friend Const ImportingConstructorMessage As String = "This exported object must be obtained through the MEF export provider." + End Module + End Namespace + """; + await new VerifyVB.Test { - var source = $@" -Imports System -Imports {mefNamespace} - - -Class C - - - Public Sub New() - End Sub -End Class - -Namespace Global.Microsoft.CodeAnalysis.Host.Mef - Module MefConstruction - Friend Const ImportingConstructorMessage As String = ""This exported object must be obtained through the MEF export provider."" - End Module -End Namespace -"; - var fixedSource = $@" -Imports System -Imports {mefNamespace} -Imports Microsoft.CodeAnalysis.Host.Mef - - -Class C - - - Public Sub New() - End Sub -End Class - -Namespace Global.Microsoft.CodeAnalysis.Host.Mef - Module MefConstruction - Friend Const ImportingConstructorMessage As String = ""This exported object must be obtained through the MEF export provider."" - End Module -End Namespace -"; - - await new VerifyVB.Test + TestState = { - TestState = - { - Sources = { source }, - AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyVB.Diagnostic().WithSpan(8, 6, 8, 35).WithArguments("C") }, - }, - FixedState = - { - Sources = { fixedSource }, - }, - NumberOfIncrementalIterations = 2, - NumberOfFixAllIterations = 2, - }.RunAsync(); - } + Sources = { source }, + AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, + }, + FixedCode = $""" + Imports System + Imports {mefNamespace} + Imports Microsoft.CodeAnalysis.Host.Mef + + + Class C + + + Public Sub New() + End Sub + End Class + + Namespace Global.Microsoft.CodeAnalysis.Host.Mef + Module MefConstruction + Friend Const ImportingConstructorMessage As String = "This exported object must be obtained through the MEF export provider." + End Module + End Namespace + """, + NumberOfIncrementalIterations = 2, + NumberOfFixAllIterations = 2, + }.RunAsync(); } } diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/NumberCommentsRefactoringTests.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/NumberCommentsRefactoringTests.cs index 95b6e0663789a..a4205d3a6389e 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/NumberCommentsRefactoringTests.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/NumberCommentsRefactoringTests.cs @@ -14,20 +14,22 @@ public class NumberCommentsRefactoringTests [Fact] public async Task TestAsync() { - const string source = @" -public class C -{ - string s = @"" -[||]class D { } // -""; -}"; - const string fixedSource = @" -public class C -{ - string s = @"" -class D { } // 1 -""; -}"; + const string source = """ + public class C + { + string s = @" + [||]class D { } // + "; + } + """; + const string fixedSource = """ + public class C + { + string s = @" + class D { } // 1 + "; + } + """; await VerifyCS.VerifyRefactoringAsync(source, fixedSource); } @@ -102,133 +104,145 @@ class E { } // 2, 3 [Fact] public async Task CSharp_VerifyFix_WithTriviaAsync() { - const string source = @" -public class C -{ - string s = -[||]/*before*/ @"" -class D { } // -"" /*after*/ ; -}"; - const string fixedSource = @" -public class C -{ - string s = -/*before*/ @"" -class D { } // 1 -"" /*after*/ ; -}"; + const string source = """ + public class C + { + string s = + [||]/*before*/ @" + class D { } // + " /*after*/ ; + } + """; + const string fixedSource = """ + public class C + { + string s = + /*before*/ @" + class D { } // 1 + " /*after*/ ; + } + """; await VerifyCS.VerifyRefactoringAsync(source, fixedSource); } [Fact] public async Task CSharp_VerifyFix_NonNumberCommentsLeftAloneAsync() { - const string source = @" -public class C -{ - string s = @"" -[||]// -class D // -{// -} // test -""; -}"; - const string fixedSource = @" -public class C -{ - string s = @"" -// -class D // 1 -{// -} // test -""; -}"; + const string source = """ + public class C + { + string s = @" + [||]// + class D // + {// + } // test + "; + } + """; + const string fixedSource = """ + public class C + { + string s = @" + // + class D // 1 + {// + } // test + "; + } + """; await VerifyCS.VerifyRefactoringAsync(source, fixedSource); } [Fact] public async Task CSharp_VerifyFix_MultipleCommasAsync() { - const string source = @" -public class C -{ - string s = @"" -[||]class D //1 -{ //, -} // -""; -}"; - const string fixedSource = @" -public class C -{ - string s = @"" -class D // 1 -{ // 2, 3 -} // 4 -""; -}"; + const string source = """ + public class C + { + string s = @" + [||]class D //1 + { //, + } // + "; + } + """; + const string fixedSource = """ + public class C + { + string s = @" + class D // 1 + { // 2, 3 + } // 4 + "; + } + """; await VerifyCS.VerifyRefactoringAsync(source, fixedSource); } [Fact] public async Task CSharp_VerifyFix_LastLineAsync() { - const string source = @" -public class C -{ - string s = @""[||]class D { } //""; -}"; - const string fixedSource = @" -public class C -{ - string s = @""class D { } // 1""; -}"; + const string source = """ + public class C + { + string s = @"[||]class D { } //"; + } + """; + const string fixedSource = """ + public class C + { + string s = @"class D { } // 1"; + } + """; await VerifyCS.VerifyRefactoringAsync(source, fixedSource); } [Fact] public async Task CountOverTenAsync() { - const string source = @" -public class C -{ - string s = @"" -[||]class D { } // ,,,,,,,,,,,, -""; -}"; - const string fixedSource = @" -public class C -{ - string s = @"" -class D { } // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 -""; -}"; + const string source = """ + public class C + { + string s = @" + [||]class D { } // ,,,,,,,,,,,, + "; + } + """; + const string fixedSource = """ + public class C + { + string s = @" + class D { } // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 + "; + } + """; await VerifyCS.VerifyRefactoringAsync(source, fixedSource); } [Fact] public async Task EmptyNumberIsImproperAsync() { - const string source = @" -public class C -{ - string s = @"" -[||]class D // 1 -{ // 2, 3 -} // -""; -}"; + const string source = """ + public class C + { + string s = @" + [||]class D // 1 + { // 2, 3 + } // + "; + } + """; - const string fixedSource = @" -public class C -{ - string s = @"" -class D // 1 -{ // 2, 3 -} // 4 -""; -}"; + const string fixedSource = """ + public class C + { + string s = @" + class D // 1 + { // 2, 3 + } // 4 + "; + } + """; await VerifyCS.VerifyRefactoringAsync(source, fixedSource); } @@ -236,25 +250,27 @@ class D // 1 [Fact] public async Task EmptyNumberBeforeCommaIsImproperAsync() { - const string source = @" -public class C -{ - string s = @"" -[||]class C // 1 -{ // , 3 -} -""; -}"; + const string source = """ + public class C + { + string s = @" + [||]class C // 1 + { // , 3 + } + "; + } + """; - const string fixedSource = @" -public class C -{ - string s = @"" -class C // 1 -{ // 2, 3 -} -""; -}"; + const string fixedSource = """ + public class C + { + string s = @" + class C // 1 + { // 2, 3 + } + "; + } + """; await VerifyCS.VerifyRefactoringAsync(source, fixedSource); } @@ -262,31 +278,33 @@ class C // 1 [Fact] public async Task EmptyCommentOnEmptyLineIsProperAsync() { - const string source = @" -public class C -{ - string s = @"" -// much stuff -// -// more stuff -[||]class C // 1 -{ // 2, 3 -} // -""; -}"; + const string source = """ + public class C + { + string s = @" + // much stuff + // + // more stuff + [||]class C // 1 + { // 2, 3 + } // + "; + } + """; - const string fixedSource = @" -public class C -{ - string s = @"" -// much stuff -// -// more stuff -class C // 1 -{ // 2, 3 -} // 4 -""; -}"; + const string fixedSource = """ + public class C + { + string s = @" + // much stuff + // + // more stuff + class C // 1 + { // 2, 3 + } // 4 + "; + } + """; await VerifyCS.VerifyRefactoringAsync(source, fixedSource); } diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/PartsExportedWithMEFv2MustBeMarkedAsSharedTests.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/PartsExportedWithMEFv2MustBeMarkedAsSharedTests.cs index fcc7154869167..b69ea3ac9a08a 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/PartsExportedWithMEFv2MustBeMarkedAsSharedTests.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/PartsExportedWithMEFv2MustBeMarkedAsSharedTests.cs @@ -16,57 +16,65 @@ namespace Roslyn.Diagnostics.Analyzers.UnitTests { public class PartsExportedWithMEFv2MustBeMarkedAsSharedTests { - private const string CSharpWellKnownAttributesDefinition = @" -namespace System.Composition -{ - public class ExportAttribute : System.Attribute - { - public ExportAttribute(System.Type contractType){ } - } + private const string CSharpWellKnownAttributesDefinition = """ + + namespace System.Composition + { + public class ExportAttribute : System.Attribute + { + public ExportAttribute(System.Type contractType){ } + } + + public class SharedAttribute : System.Attribute + { + } + } + + """; + private const string BasicWellKnownAttributesDefinition = """ + + Namespace System.Composition + Public Class ExportAttribute + Inherits System.Attribute + Public Sub New(contractType As System.Type) + End Sub + End Class + + Public Class SharedAttribute + Inherits System.Attribute + End Class + End Namespace - public class SharedAttribute : System.Attribute - { - } -} -"; - private const string BasicWellKnownAttributesDefinition = @" -Namespace System.Composition - Public Class ExportAttribute - Inherits System.Attribute - Public Sub New(contractType As System.Type) - End Sub - End Class - - Public Class SharedAttribute - Inherits System.Attribute - End Class -End Namespace - -"; + + """; #region No Diagnostic Tests [Fact] public async Task NoDiagnosticCases_ResolvedTypesAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -using System; -using System.Composition; + await VerifyCS.VerifyAnalyzerAsync(""" -[Export(typeof(C)), Shared] -public class C -{ -} -" + CSharpWellKnownAttributesDefinition); + using System; + using System.Composition; + + [Export(typeof(C)), Shared] + public class C + { + } + + """ + CSharpWellKnownAttributesDefinition); + + await VerifyVB.VerifyAnalyzerAsync(""" - await VerifyVB.VerifyAnalyzerAsync(@" -Imports System -Imports System.Composition + Imports System + Imports System.Composition - _ -Public Class C -End Class -" + BasicWellKnownAttributesDefinition); + _ + Public Class C + End Class + + """ + BasicWellKnownAttributesDefinition); } [Fact] @@ -78,15 +86,17 @@ public async Task NoDiagnosticCases_UnresolvedTypesAsync() { Sources = { - @" -using System; -using System.{|CS0234:Composition|}; + """ -[{|CS0246:{|CS0246:Export|}|}(typeof(C)), {|CS0246:{|CS0246:Shared|}|}] -public class C -{ -} -", + using System; + using System.{|CS0234:Composition|}; + + [{|CS0246:{|CS0246:Export|}|}(typeof(C)), {|CS0246:{|CS0246:Shared|}|}] + public class C + { + } + + """, }, }, ReferenceAssemblies = ReferenceAssemblies.Default, @@ -98,14 +108,16 @@ public class C { Sources = { - @" -Imports System -Imports System.Composition - -<{|BC30002:Export|}(GetType(C)), {|BC30002:[Shared]|}> _ -Public Class C -End Class -" + """ + + Imports System + Imports System.Composition + + <{|BC30002:Export|}(GetType(C)), {|BC30002:[Shared]|}> _ + Public Class C + End Class + + """ }, }, ReferenceAssemblies = ReferenceAssemblies.Default, @@ -119,93 +131,109 @@ End Class [Fact] public async Task DiagnosticCases_NoSharedAttributeAsync() { - await VerifyCS.VerifyCodeFixAsync(@" -using System; -using System.Composition; + await VerifyCS.VerifyCodeFixAsync(""" -[[|Export(typeof(C))|]] -public class C -{ -} -" + CSharpWellKnownAttributesDefinition, @" -using System; -using System.Composition; + using System; + using System.Composition; -[Export(typeof(C))] -[Shared] -public class C -{ -} -" + CSharpWellKnownAttributesDefinition); - - await VerifyVB.VerifyCodeFixAsync(@" -Imports System -Imports System.Composition - -<[|Export(GetType(C))|]> _ -Public Class C -End Class -" + BasicWellKnownAttributesDefinition, @" -Imports System -Imports System.Composition - - _ -<[Shared]> -Public Class C -End Class -" + BasicWellKnownAttributesDefinition); + [[|Export(typeof(C))|]] + public class C + { + } + + """ + CSharpWellKnownAttributesDefinition, """ + + using System; + using System.Composition; + + [Export(typeof(C))] + [Shared] + public class C + { + } + + """ + CSharpWellKnownAttributesDefinition); + + await VerifyVB.VerifyCodeFixAsync(""" + + Imports System + Imports System.Composition + + <[|Export(GetType(C))|]> _ + Public Class C + End Class + + """ + BasicWellKnownAttributesDefinition, """ + + Imports System + Imports System.Composition + + _ + <[Shared]> + Public Class C + End Class + + """ + BasicWellKnownAttributesDefinition); } [Fact] public async Task DiagnosticCases_DifferentSharedAttributeAsync() { - await VerifyCS.VerifyCodeFixAsync(@" -using System; + await VerifyCS.VerifyCodeFixAsync(""" -[[|System.Composition.Export(typeof(C))|], Shared] -public class C -{ -} + using System; -public class SharedAttribute: Attribute -{ -} -" + CSharpWellKnownAttributesDefinition, @" -using System; + [[|System.Composition.Export(typeof(C))|], Shared] + public class C + { + } -[System.Composition.Export(typeof(C)), Shared] -[System.Composition.Shared] -public class C -{ -} + public class SharedAttribute: Attribute + { + } -public class SharedAttribute: Attribute -{ -} -" + CSharpWellKnownAttributesDefinition); - - await VerifyVB.VerifyCodeFixAsync(@" -Imports System - -<[|System.Composition.Export(GetType(C))|], [Shared]> _ -Public Class C -End Class - -Public Class SharedAttribute - Inherits Attribute -End Class -" + BasicWellKnownAttributesDefinition, @" -Imports System - - _ - -Public Class C -End Class - -Public Class SharedAttribute - Inherits Attribute -End Class -" + BasicWellKnownAttributesDefinition); + """ + CSharpWellKnownAttributesDefinition, """ + + using System; + + [System.Composition.Export(typeof(C)), Shared] + [System.Composition.Shared] + public class C + { + } + + public class SharedAttribute: Attribute + { + } + + """ + CSharpWellKnownAttributesDefinition); + + await VerifyVB.VerifyCodeFixAsync(""" + + Imports System + + <[|System.Composition.Export(GetType(C))|], [Shared]> _ + Public Class C + End Class + + Public Class SharedAttribute + Inherits Attribute + End Class + + """ + BasicWellKnownAttributesDefinition, """ + + Imports System + + _ + + Public Class C + End Class + + Public Class SharedAttribute + Inherits Attribute + End Class + + """ + BasicWellKnownAttributesDefinition); } #endregion diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/PreferNullLiteralTests.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/PreferNullLiteralTests.cs index 030091c2792dc..5abafc0ce6da0 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/PreferNullLiteralTests.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/PreferNullLiteralTests.cs @@ -16,46 +16,41 @@ public class PreferNullLiteralTests [Theory] [InlineData("default")] [InlineData("default(object)")] - public async Task PreferNullLiteral_ClassAsync(string defaultValueExpression) - { - var source = $@" -class Type -{{ - object Method() - {{ - return [|{defaultValueExpression}|]; - }} -}} -"; - var fixedSource = @" -class Type -{ - object Method() - { - return null; - } -} -"; - - await VerifyCS.VerifyCodeFixAsync(source, fixedSource); - } + public Task PreferNullLiteral_ClassAsync(string defaultValueExpression) + => VerifyCS.VerifyCodeFixAsync($$""" + class Type + { + object Method() + { + return [|{{defaultValueExpression}}|]; + } + } + """, """ + class Type + { + object Method() + { + return null; + } + } + """); [Fact] public async Task UnresolvedTypeAsync() { - var source = @" -class Type -{ - void Method() - { - {|CS0411:Method2|}(default); - } - - void Method2(T value) - { - } -} -"; + var source = """ + class Type + { + void Method() + { + {|CS0411:Method2|}(default); + } + + void Method2(T value) + { + } + } + """; await VerifyCS.VerifyCodeFixAsync(source, source); } @@ -64,177 +59,162 @@ void Method2(T value) [InlineData("default", "null")] [InlineData("default(object)", "null")] [InlineData("default(object?)", "null")] - public async Task ReturnFromNullableContextAsync(string defaultValueExpression, string fixedExpression) - { - var source = $@" -#nullable enable - -class Type -{{ - object Method() - {{ - return [|{defaultValueExpression}|]!; - }} -}} -"; - var fixedSource = $@" -#nullable enable - -class Type -{{ - object Method() - {{ - return {fixedExpression}!; - }} -}} -"; - - await new VerifyCS.Test + public Task ReturnFromNullableContextAsync(string defaultValueExpression, string fixedExpression) + => new VerifyCS.Test { - TestCode = source, - FixedCode = fixedSource, + TestCode = $$""" + #nullable enable + + class Type + { + object Method() + { + return [|{{defaultValueExpression}}|]!; + } + } + """, + FixedCode = $$""" + #nullable enable + + class Type + { + object Method() + { + return {{fixedExpression}}!; + } + } + """, LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); - } [Theory] [InlineData("[|default(object)|]!", "((object?)null)!")] [InlineData("[|default(object?)|]!", "((object?)null)!")] [InlineData("[|default(object)|]", "(object?)null")] [InlineData("[|default(object?)|]", "(object?)null")] - public async Task InvocationInNullableContextAsync(string defaultValueExpression, string fixedExpression) - { - var source = $@" -#nullable enable - -class Type -{{ - void Method() - {{ - Method2({defaultValueExpression}); - }} - - void Method2(T value) - {{ - }} -}} -"; - var fixedSource = $@" -#nullable enable - -class Type -{{ - void Method() - {{ - Method2({fixedExpression}); - }} - - void Method2(T value) - {{ - }} -}} -"; - - await new VerifyCS.Test + public Task InvocationInNullableContextAsync(string defaultValueExpression, string fixedExpression) + => new VerifyCS.Test { - TestCode = source, - FixedCode = fixedSource, + TestCode = $$""" + #nullable enable + + class Type + { + void Method() + { + Method2({{defaultValueExpression}}); + } + + void Method2(T value) + { + } + } + """, + FixedCode = $$""" + #nullable enable + + class Type + { + void Method() + { + Method2({{fixedExpression}}); + } + + void Method2(T value) + { + } + } + """, LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); - } [Fact] public async Task NullPointerAsync() { - var source = @" -unsafe class Type -{ - void Method() - { - Method2([|default(int*)|]); - } - - void Method2(int* value) { } - void Method2(byte* value) { } -} -"; - var fixedSource = @" -unsafe class Type -{ - void Method() - { - Method2((int*)null); - } - - void Method2(int* value) { } - void Method2(byte* value) { } -} -"; + var source = """ + unsafe class Type + { + void Method() + { + Method2([|default(int*)|]); + } + + void Method2(int* value) { } + void Method2(byte* value) { } + } + """; + var fixedSource = """ + unsafe class Type + { + void Method() + { + Method2((int*)null); + } + + void Method2(int* value) { } + void Method2(byte* value) { } + } + """; await VerifyCS.VerifyCodeFixAsync(source, fixedSource); } [Fact] - public async Task PointerInNullableContextAsync() - { - var source = @" -#nullable enable - -unsafe class Type -{ - void Method() - { - Method2([|default(int*)|]); - } - - void Method2(int* value) { } - void Method2(byte* value) { } -} -"; - var fixedSource = @" -#nullable enable - -unsafe class Type -{ - void Method() - { - Method2((int*)null); - } - - void Method2(int* value) { } - void Method2(byte* value) { } -} -"; - - await new VerifyCS.Test + public Task PointerInNullableContextAsync() + => new VerifyCS.Test { - TestCode = source, - FixedCode = fixedSource, + TestCode = """ + #nullable enable + + unsafe class Type + { + void Method() + { + Method2([|default(int*)|]); + } + + void Method2(int* value) { } + void Method2(byte* value) { } + } + """, + FixedCode = """ + #nullable enable + + unsafe class Type + { + void Method() + { + Method2((int*)null); + } + + void Method2(int* value) { } + void Method2(byte* value) { } + } + """, LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); - } [Theory] [InlineData("default")] [InlineData("default(object)")] public async Task PreferNullLiteral_DefaultParameterValueAsync(string defaultValueExpression) { - var source = $@" -class Type -{{ - void Method(object value = [|{defaultValueExpression}|]) - {{ - }} -}} -"; - var fixedSource = @" -class Type -{ - void Method(object value = null) - { - } -} -"; + var source = $$""" + class Type + { + void Method(object value = [|{{defaultValueExpression}}|]) + { + } + } + """; + var fixedSource = """ + class Type + { + void Method(object value = null) + { + } + } + """; await VerifyCS.VerifyCodeFixAsync(source, fixedSource); } @@ -242,44 +222,44 @@ void Method(object value = null) [Fact] public async Task PreferNullLiteral_ArgumentFormattingAsync() { - var source = $@" -class Type -{{ - void Method() - {{ - Method2( - 0, - [|default|], - /*1*/ [|default|] /*2*/, - [|default(object)|], - /*1*/ [|default /*2*/ ( /*3*/ object /*4*/ )|] /*5*/, - """"); - }} - - void Method2(params object[] values) - {{ - }} -}} -"; - var fixedSource = @" -class Type -{ - void Method() - { - Method2( - 0, - null, - /*1*/ null /*2*/, - null, - /*1*/ /*3*/ /*4*/ null /*2*/ /*5*/, - """"); - } - - void Method2(params object[] values) - { - } -} -"; + var source = $$""" + class Type + { + void Method() + { + Method2( + 0, + [|default|], + /*1*/ [|default|] /*2*/, + [|default(object)|], + /*1*/ [|default /*2*/ ( /*3*/ object /*4*/ )|] /*5*/, + ""); + } + + void Method2(params object[] values) + { + } + } + """; + var fixedSource = """ + class Type + { + void Method() + { + Method2( + 0, + null, + /*1*/ null /*2*/, + null, + /*1*/ /*3*/ /*4*/ null /*2*/ /*5*/, + ""); + } + + void Method2(params object[] values) + { + } + } + """; await VerifyCS.VerifyCodeFixAsync(source, fixedSource); } @@ -287,44 +267,44 @@ void Method2(params object[] values) [Fact] public async Task PreferNullLiteral_OverloadResolutionAsync() { - var source = @" -using System; - -class Type -{ - void Method() - { - Method2([|default(object)|]); - Method2([|default(string)|]); - Method2([|default(IComparable)|]); - Method2([|default(int?)|]); - Method2(default(int)); - } - - void Method2(T value) - { - } -} -"; - var fixedSource = @" -using System; - -class Type -{ - void Method() - { - Method2((object)null); - Method2((string)null); - Method2((IComparable)null); - Method2((int?)null); - Method2(default(int)); - } - - void Method2(T value) - { - } -} -"; + var source = """ + using System; + + class Type + { + void Method() + { + Method2([|default(object)|]); + Method2([|default(string)|]); + Method2([|default(IComparable)|]); + Method2([|default(int?)|]); + Method2(default(int)); + } + + void Method2(T value) + { + } + } + """; + var fixedSource = """ + using System; + + class Type + { + void Method() + { + Method2((object)null); + Method2((string)null); + Method2((IComparable)null); + Method2((int?)null); + Method2(default(int)); + } + + void Method2(T value) + { + } + } + """; await VerifyCS.VerifyCodeFixAsync(source, fixedSource); } @@ -332,44 +312,44 @@ void Method2(T value) [Fact] public async Task PreferNullLiteral_ParenthesizeWhereNecessaryAsync() { - var source = @" -using System; - -class Type -{ - void Method() - { - Method2([|default(object)|]?.ToString()); - Method2([|default(string)|]?.ToString()); - Method2([|default(IComparable)|]?.ToString()); - Method2([|default(int?)|]?.ToString()); - Method2(default(int).ToString()); - } - - void Method2(string value) - { - } -} -"; - var fixedSource = @" -using System; - -class Type -{ - void Method() - { - Method2(((object)null)?.ToString()); - Method2(((string)null)?.ToString()); - Method2(((IComparable)null)?.ToString()); - Method2(((int?)null)?.ToString()); - Method2(default(int).ToString()); - } - - void Method2(string value) - { - } -} -"; + var source = """ + using System; + + class Type + { + void Method() + { + Method2([|default(object)|]?.ToString()); + Method2([|default(string)|]?.ToString()); + Method2([|default(IComparable)|]?.ToString()); + Method2([|default(int?)|]?.ToString()); + Method2(default(int).ToString()); + } + + void Method2(string value) + { + } + } + """; + var fixedSource = """ + using System; + + class Type + { + void Method() + { + Method2(((object)null)?.ToString()); + Method2(((string)null)?.ToString()); + Method2(((IComparable)null)?.ToString()); + Method2(((int?)null)?.ToString()); + Method2(default(int).ToString()); + } + + void Method2(string value) + { + } + } + """; await VerifyCS.VerifyCodeFixAsync(source, fixedSource); } @@ -377,15 +357,15 @@ void Method2(string value) [Fact] public async Task PreferNullLiteral_StructAsync() { - var source = @" -class Type -{ - int Method() - { - return default; - } -} -"; + var source = """ + class Type + { + int Method() + { + return default; + } + } + """; await VerifyCS.VerifyCodeFixAsync(source, source); } @@ -393,15 +373,15 @@ int Method() [Fact] public async Task PreferNullLiteral_StructConvertedToReferenceTypeAsync() { - var source = @" -class Type -{ - object Method() - { - return default(int); - } -} -"; + var source = """ + class Type + { + object Method() + { + return default(int); + } + } + """; await VerifyCS.VerifyCodeFixAsync(source, source); } @@ -409,15 +389,15 @@ object Method() [Fact] public async Task PreferNullLiteral_UnconstrainedGenericAsync() { - var source = @" -class Type -{ - T Method() - { - return default; - } -} -"; + var source = """ + class Type + { + T Method() + { + return default; + } + } + """; await VerifyCS.VerifyCodeFixAsync(source, source); } @@ -425,26 +405,26 @@ T Method() [Fact] public async Task PreferNullLiteral_GenericConstrainedToReferenceTypeAsync() { - var source = @" -class Type -{ - T Method() - where T : class - { - return [|default|]; - } -} -"; - var fixedSource = @" -class Type -{ - T Method() - where T : class - { - return null; - } -} -"; + var source = """ + class Type + { + T Method() + where T : class + { + return [|default|]; + } + } + """; + var fixedSource = """ + class Type + { + T Method() + where T : class + { + return null; + } + } + """; await VerifyCS.VerifyCodeFixAsync(source, fixedSource); } @@ -452,16 +432,16 @@ T Method() [Fact] public async Task PreferNullLiteral_GenericConstrainedToInterfaceAsync() { - var source = @" -class Type -{ - T Method() - where T : System.IComparable - { - return default; - } -} -"; + var source = """ + class Type + { + T Method() + where T : System.IComparable + { + return default; + } + } + """; await VerifyCS.VerifyCodeFixAsync(source, source); } @@ -469,16 +449,16 @@ T Method() [Fact] public async Task PreferNullLiteral_GenericConstrainedToValueTypeAsync() { - var source = @" -class Type -{ - T Method() - where T : struct - { - return default; - } -} -"; + var source = """ + class Type + { + T Method() + where T : struct + { + return default; + } + } + """; await VerifyCS.VerifyCodeFixAsync(source, source); } @@ -488,19 +468,19 @@ T Method() [InlineData("int?")] public async Task IgnoreDefaultParametersAsync(string defaultParameterType) { - var source = $@" -class Type -{{ - void Method1() - {{ - Method2(0); - }} - - void Method2(int first, {defaultParameterType} value = null) - {{ - }} -}} -"; + var source = $$""" + class Type + { + void Method1() + { + Method2(0); + } + + void Method2(int first, {{defaultParameterType}} value = null) + { + } + } + """; await VerifyCS.VerifyCodeFixAsync(source, source); } diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/RelaxTestNamingSuppressorTests.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/RelaxTestNamingSuppressorTests.cs index 569484312a8fa..b89f5f7650e62 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/RelaxTestNamingSuppressorTests.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/RelaxTestNamingSuppressorTests.cs @@ -29,15 +29,15 @@ private static Solution WithoutSuppressedDiagnosticsTransform(Solution solution, [Fact(Skip = "https://github.com/dotnet/roslyn/issues/41584")] public async Task TestClassWithFactAsync() { - var code = @" -using System.Threading.Tasks; -using Xunit; + var code = """ + using System.Threading.Tasks; + using Xunit; -public class SomeClass { -[Fact] -public async Task [|TestMethod|]() { } -} -"; + public class SomeClass { + [Fact] + public async Task [|TestMethod|]() { } + } + """; await new VerifyCS.Test { @@ -57,14 +57,14 @@ public class SomeClass { [Fact(Skip = "https://github.com/dotnet/roslyn/issues/41584")] public async Task TestClassWithTheoryAsync() { - var code = @" -using Xunit; + var code = """ + using Xunit; -public class [|SomeClass|] { -[Theory, InlineData(0)] -public void TestMethod(int arg) { } -} -"; + public class [|SomeClass|] { + [Theory, InlineData(0)] + public void TestMethod(int arg) { } + } + """; await new VerifyCS.Test { @@ -84,15 +84,15 @@ public void TestMethod(int arg) { } [Fact] public async Task TestAlreadyHasAsyncSuffixAsync() { - var code = @" -using System.Threading.Tasks; -using Xunit; + var code = """ + using System.Threading.Tasks; + using Xunit; -public class SomeClass { -[Fact] -public async Task TestMethodAsync() { } -} -"; + public class SomeClass { + [Fact] + public async Task TestMethodAsync() { } + } + """; await new VerifyCS.Test { diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/Roslyn.Diagnostics.Analyzers.UnitTests.csproj b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/Roslyn.Diagnostics.Analyzers.UnitTests.csproj index 0155cfdec23c9..c56f55e4c333c 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/Roslyn.Diagnostics.Analyzers.UnitTests.csproj +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/Roslyn.Diagnostics.Analyzers.UnitTests.csproj @@ -3,15 +3,15 @@ $(NetRoslyn) true - $(MicrosoftCodeAnalysisVersionForTests) + true - - - - - - + + + + + + diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/RunIterationsTests.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/RunIterationsTests.cs index 01f12682fb471..35a4faccdaac1 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/RunIterationsTests.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/RunIterationsTests.cs @@ -40,34 +40,36 @@ public async Task RunIterationsOfFact_CSharp(string attributeName) await new VerifyCS.Test { ReferenceAssemblies = xunitWithCombinatorial, - TestCode = $@"using Xunit; - -class TestClass -{{ - [{attributeName}] - public void $$Method() - {{ - }} -}} - -class CustomFactAttribute : FactAttribute {{ }} -class CustomTheoryAttribute : TheoryAttribute {{ }} -", - FixedCode = $@"using Xunit; - -class TestClass -{{ - [{updatedName}] - [CombinatorialData] - public void $$Method([CombinatorialRange(0, 10)] int iteration) - {{ - _ = iteration; - }} -}} - -class CustomFactAttribute : FactAttribute {{ }} -class CustomTheoryAttribute : TheoryAttribute {{ }} -", + TestCode = $$""" + using Xunit; + + class TestClass + { + [{{attributeName}}] + public void $$Method() + { + } + } + + class CustomFactAttribute : FactAttribute { } + class CustomTheoryAttribute : TheoryAttribute { } + """, + FixedCode = $$""" + using Xunit; + + class TestClass + { + [{{updatedName}}] + [CombinatorialData] + public void $$Method([CombinatorialRange(0, 10)] int iteration) + { + _ = iteration; + } + } + + class CustomFactAttribute : FactAttribute { } + class CustomTheoryAttribute : TheoryAttribute { } + """, }.RunAsync(); } @@ -91,29 +93,31 @@ public async Task RunIterationsOfFact_VisualBasic(string attributeName) await new VerifyVB.Test { ReferenceAssemblies = xunitWithCombinatorial, - TestCode = $@"Imports Xunit - -Class TestClass - <{attributeName}> - Public Sub $$Method() - End Sub -End Class - -Class CustomFactAttribute : Inherits FactAttribute : End Class -Class CustomTheoryAttribute : Inherits TheoryAttribute : End Class -", - FixedCode = $@"Imports Xunit - -Class TestClass - <{updatedName}> - - Public Sub $$Method( iteration As Integer) - End Sub -End Class - -Class CustomFactAttribute : Inherits FactAttribute : End Class -Class CustomTheoryAttribute : Inherits TheoryAttribute : End Class -", + TestCode = $""" + Imports Xunit + + Class TestClass + <{attributeName}> + Public Sub $$Method() + End Sub + End Class + + Class CustomFactAttribute : Inherits FactAttribute : End Class + Class CustomTheoryAttribute : Inherits TheoryAttribute : End Class + """, + FixedCode = $""" + Imports Xunit + + Class TestClass + <{updatedName}> + + Public Sub $$Method( iteration As Integer) + End Sub + End Class + + Class CustomFactAttribute : Inherits FactAttribute : End Class + Class CustomTheoryAttribute : Inherits TheoryAttribute : End Class + """, }.RunAsync(); } @@ -136,34 +140,36 @@ public async Task RunIterationsOfFactWithTrait_CSharp(string attributeName) await new VerifyCS.Test { ReferenceAssemblies = xunitWithCombinatorial, - TestCode = $@"using Xunit; - -class TestClass -{{ - [{attributeName}, Trait(""Key"", ""Value"")] - public void $$Method() - {{ - }} -}} - -class CustomFactAttribute : FactAttribute {{ }} -class CustomTheoryAttribute : TheoryAttribute {{ }} -", - FixedCode = $@"using Xunit; - -class TestClass -{{ - [{updatedName}, Trait(""Key"", ""Value"")] - [CombinatorialData] - public void $$Method([CombinatorialRange(0, 10)] int iteration) - {{ - _ = iteration; - }} -}} - -class CustomFactAttribute : FactAttribute {{ }} -class CustomTheoryAttribute : TheoryAttribute {{ }} -", + TestCode = $$""" + using Xunit; + + class TestClass + { + [{{attributeName}}, Trait("Key", "Value")] + public void $$Method() + { + } + } + + class CustomFactAttribute : FactAttribute { } + class CustomTheoryAttribute : TheoryAttribute { } + """, + FixedCode = $$""" + using Xunit; + + class TestClass + { + [{{updatedName}}, Trait("Key", "Value")] + [CombinatorialData] + public void $$Method([CombinatorialRange(0, 10)] int iteration) + { + _ = iteration; + } + } + + class CustomFactAttribute : FactAttribute { } + class CustomTheoryAttribute : TheoryAttribute { } + """, }.RunAsync(); } @@ -187,29 +193,31 @@ public async Task RunIterationsOfFactWithTrait_VisualBasic(string attributeName) await new VerifyVB.Test { ReferenceAssemblies = xunitWithCombinatorial, - TestCode = $@"Imports Xunit - -Class TestClass - <{attributeName}, Trait(""Key"", ""Value"")> - Public Sub $$Method() - End Sub -End Class - -Class CustomFactAttribute : Inherits FactAttribute : End Class -Class CustomTheoryAttribute : Inherits TheoryAttribute : End Class -", - FixedCode = $@"Imports Xunit - -Class TestClass - <{updatedName}, Trait(""Key"", ""Value"")> - - Public Sub $$Method( iteration As Integer) - End Sub -End Class - -Class CustomFactAttribute : Inherits FactAttribute : End Class -Class CustomTheoryAttribute : Inherits TheoryAttribute : End Class -", + TestCode = $""" + Imports Xunit + + Class TestClass + <{attributeName}, Trait("Key", "Value")> + Public Sub $$Method() + End Sub + End Class + + Class CustomFactAttribute : Inherits FactAttribute : End Class + Class CustomTheoryAttribute : Inherits TheoryAttribute : End Class + """, + FixedCode = $""" + Imports Xunit + + Class TestClass + <{updatedName}, Trait("Key", "Value")> + + Public Sub $$Method( iteration As Integer) + End Sub + End Class + + Class CustomFactAttribute : Inherits FactAttribute : End Class + Class CustomTheoryAttribute : Inherits TheoryAttribute : End Class + """, }.RunAsync(); } @@ -220,21 +228,22 @@ End Class [InlineData("CustomTheoryAttribute")] public async Task NoIterationsForTheoryWithInlineData_CSharp(string attributeName) { - var testCode = $@"using Xunit; - -class TestClass -{{ - [{attributeName}] - [InlineData(true)] - public void $$Method(bool arg) - {{ - _ = arg; - }} -}} - -class CustomFactAttribute : FactAttribute {{ }} -class CustomTheoryAttribute : TheoryAttribute {{ }} -"; + var testCode = $$""" + using Xunit; + + class TestClass + { + [{{attributeName}}] + [InlineData(true)] + public void $$Method(bool arg) + { + _ = arg; + } + } + + class CustomFactAttribute : FactAttribute { } + class CustomTheoryAttribute : TheoryAttribute { } + """; await new VerifyCS.Test { @@ -251,18 +260,19 @@ class CustomTheoryAttribute : TheoryAttribute {{ }} [InlineData("CustomTheoryAttribute")] public async Task NoIterationsForTheoryWithInlineData_VisualBasic(string attributeName) { - var testCode = $@"Imports Xunit + var testCode = $""" + Imports Xunit -Class TestClass - <{attributeName}> - - Public Sub $$Method(arg As Boolean) - End Sub -End Class + Class TestClass + <{attributeName}> + + Public Sub $$Method(arg As Boolean) + End Sub + End Class -Class CustomFactAttribute : Inherits FactAttribute : End Class -Class CustomTheoryAttribute : Inherits TheoryAttribute : End Class -"; + Class CustomFactAttribute : Inherits FactAttribute : End Class + Class CustomTheoryAttribute : Inherits TheoryAttribute : End Class + """; await new VerifyVB.Test { @@ -279,21 +289,22 @@ End Class [InlineData("CustomTheoryAttribute")] public async Task NoIterationsForTheoryWithIterations_CSharp(string attributeName) { - var testCode = $@"using Xunit; - -class TestClass -{{ - [{attributeName}] - [CombinatorialData] - public void $$Method([CombinatorialRange(0, 10)] int iteration) - {{ - _ = iteration; - }} -}} - -class CustomFactAttribute : FactAttribute {{ }} -class CustomTheoryAttribute : TheoryAttribute {{ }} -"; + var testCode = $$""" + using Xunit; + + class TestClass + { + [{{attributeName}}] + [CombinatorialData] + public void $$Method([CombinatorialRange(0, 10)] int iteration) + { + _ = iteration; + } + } + + class CustomFactAttribute : FactAttribute { } + class CustomTheoryAttribute : TheoryAttribute { } + """; await new VerifyCS.Test { @@ -310,18 +321,19 @@ class CustomTheoryAttribute : TheoryAttribute {{ }} [InlineData("CustomTheoryAttribute")] public async Task NoIterationsForTheoryWithIterations_VisualBasic(string attributeName) { - var testCode = $@"Imports Xunit + var testCode = $""" + Imports Xunit -Class TestClass - <{attributeName}> - - Public Sub $$Method( iteration As Integer) - End Sub -End Class + Class TestClass + <{attributeName}> + + Public Sub $$Method( iteration As Integer) + End Sub + End Class -Class CustomFactAttribute : Inherits FactAttribute : End Class -Class CustomTheoryAttribute : Inherits TheoryAttribute : End Class -"; + Class CustomFactAttribute : Inherits FactAttribute : End Class + Class CustomTheoryAttribute : Inherits TheoryAttribute : End Class + """; await new VerifyVB.Test { @@ -336,80 +348,80 @@ End Class [InlineData("TheoryAttribute")] [InlineData("CustomTheory")] [InlineData("CustomTheoryAttribute")] - public async Task RunIterationsOfTheory_CSharp(string attributeName) - { - await new VerifyCS.Test + public Task RunIterationsOfTheory_CSharp(string attributeName) + => new VerifyCS.Test { ReferenceAssemblies = xunitWithCombinatorial, - TestCode = $@"using Xunit; - -class TestClass -{{ - [{attributeName}] - [CombinatorialData] - public void $$Method(bool arg) - {{ - _ = arg; - }} -}} - -class CustomFactAttribute : FactAttribute {{ }} -class CustomTheoryAttribute : TheoryAttribute {{ }} -", - FixedCode = $@"using Xunit; - -class TestClass -{{ - [{attributeName}] - [CombinatorialData] - public void $$Method(bool arg, [CombinatorialRange(0, 10)] int iteration) - {{ - _ = iteration; - _ = arg; - }} -}} - -class CustomFactAttribute : FactAttribute {{ }} -class CustomTheoryAttribute : TheoryAttribute {{ }} -", + TestCode = $$""" + using Xunit; + + class TestClass + { + [{{attributeName}}] + [CombinatorialData] + public void $$Method(bool arg) + { + _ = arg; + } + } + + class CustomFactAttribute : FactAttribute { } + class CustomTheoryAttribute : TheoryAttribute { } + """, + FixedCode = $$""" + using Xunit; + + class TestClass + { + [{{attributeName}}] + [CombinatorialData] + public void $$Method(bool arg, [CombinatorialRange(0, 10)] int iteration) + { + _ = iteration; + _ = arg; + } + } + + class CustomFactAttribute : FactAttribute { } + class CustomTheoryAttribute : TheoryAttribute { } + """, }.RunAsync(); - } [Theory] [InlineData("Theory")] [InlineData("TheoryAttribute")] [InlineData("CustomTheory")] [InlineData("CustomTheoryAttribute")] - public async Task RunIterationsOfTheory_VisualBasic(string attributeName) - { - await new VerifyVB.Test + public Task RunIterationsOfTheory_VisualBasic(string attributeName) + => new VerifyVB.Test { ReferenceAssemblies = xunitWithCombinatorial, - TestCode = $@"Imports Xunit - -Class TestClass - <{attributeName}> - - Public Sub $$Method(arg As Boolean) - End Sub -End Class - -Class CustomFactAttribute : Inherits FactAttribute : End Class -Class CustomTheoryAttribute : Inherits TheoryAttribute : End Class -", - FixedCode = $@"Imports Xunit - -Class TestClass - <{attributeName}> - - Public Sub $$Method(arg As Boolean, iteration As Integer) - End Sub -End Class - -Class CustomFactAttribute : Inherits FactAttribute : End Class -Class CustomTheoryAttribute : Inherits TheoryAttribute : End Class -", + TestCode = $""" + Imports Xunit + + Class TestClass + <{attributeName}> + + Public Sub $$Method(arg As Boolean) + End Sub + End Class + + Class CustomFactAttribute : Inherits FactAttribute : End Class + Class CustomTheoryAttribute : Inherits TheoryAttribute : End Class + """, + FixedCode = $""" + Imports Xunit + + Class TestClass + <{attributeName}> + + Public Sub $$Method(arg As Boolean, iteration As Integer) + End Sub + End Class + + Class CustomFactAttribute : Inherits FactAttribute : End Class + Class CustomTheoryAttribute : Inherits TheoryAttribute : End Class + """, }.RunAsync(); - } } } diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/SpecializedEnumerableCreationAnalyzerTests.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/SpecializedEnumerableCreationAnalyzerTests.cs index 8b6d222fc06ab..09a876c8eb641 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/SpecializedEnumerableCreationAnalyzerTests.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/SpecializedEnumerableCreationAnalyzerTests.cs @@ -16,18 +16,22 @@ namespace Roslyn.Diagnostics.Analyzers.UnitTests { public class SpecializedEnumerableCreationAnalyzerTests { - private readonly string _csharpSpecializedCollectionsDefinition = @" -namespace Roslyn.Utilities -{ - public class SpecializedCollections { } -} -"; - private readonly string _basicSpecializedCollectionsDefinition = @" -Namespace Roslyn.Utilities - Public Class SpecializedCollections - End Class -End Namespace -"; + private readonly string _csharpSpecializedCollectionsDefinition = """ + + namespace Roslyn.Utilities + { + public class SpecializedCollections { } + } + + """; + private readonly string _basicSpecializedCollectionsDefinition = """ + + Namespace Roslyn.Utilities + Public Class SpecializedCollections + End Class + End Namespace + + """; private static DiagnosticResult GetCSharpEmptyEnumerableResultAt(int line, int column) => #pragma warning disable RS0030 // Do not use banned APIs @@ -50,283 +54,283 @@ private static DiagnosticResult GetBasicSingletonEnumerableResultAt(int line, in #pragma warning restore RS0030 // Do not use banned APIs [Fact] - public async Task ReturnEmptyArrayCSharpAsync() - { - await VerifyCS.VerifyAnalyzerAsync(@" -using System.Collections.Generic; + public Task ReturnEmptyArrayCSharpAsync() + => VerifyCS.VerifyAnalyzerAsync(""" -class C -{ - IEnumerable M1() { return new int[0]; } - IEnumerable M2() { return new int[0] { }; } - int[] M3() { return new int[0]; } -} -" + _csharpSpecializedCollectionsDefinition, + using System.Collections.Generic; + + class C + { + IEnumerable M1() { return new int[0]; } + IEnumerable M2() { return new int[0] { }; } + int[] M3() { return new int[0]; } + } + + """ + _csharpSpecializedCollectionsDefinition, GetCSharpEmptyEnumerableResultAt(6, 36), GetCSharpEmptyEnumerableResultAt(7, 36)); - } [Fact] - public async Task ReturnSingletonArrayCSharpAsync() - { - await VerifyCS.VerifyAnalyzerAsync(@" -using System.Collections.Generic; + public Task ReturnSingletonArrayCSharpAsync() + => VerifyCS.VerifyAnalyzerAsync(""" -class C -{ - IEnumerable M1() { return new int[1]; } - IEnumerable M2() { return new int[1] { 1 }; } - IEnumerable M3() { return new[] { 1 }; } - int[] M4() { return new[] { 1 }; } -} -" + _csharpSpecializedCollectionsDefinition, + using System.Collections.Generic; + + class C + { + IEnumerable M1() { return new int[1]; } + IEnumerable M2() { return new int[1] { 1 }; } + IEnumerable M3() { return new[] { 1 }; } + int[] M4() { return new[] { 1 }; } + } + + """ + _csharpSpecializedCollectionsDefinition, GetCSharpSingletonEnumerableResultAt(6, 36), GetCSharpSingletonEnumerableResultAt(7, 36), GetCSharpSingletonEnumerableResultAt(8, 36)); - } [Fact] - public async Task ReturnLinqEmptyEnumerableCSharpAsync() - { - await VerifyCS.VerifyAnalyzerAsync(@" -using System.Collections.Generic; -using System.Linq; + public Task ReturnLinqEmptyEnumerableCSharpAsync() + => VerifyCS.VerifyAnalyzerAsync(""" -class C -{ - IEnumerable M1() { return Enumerable.Empty(); } -} -" + _csharpSpecializedCollectionsDefinition, + using System.Collections.Generic; + using System.Linq; + + class C + { + IEnumerable M1() { return Enumerable.Empty(); } + } + + """ + _csharpSpecializedCollectionsDefinition, GetCSharpEmptyEnumerableResultAt(7, 36)); - } [Fact(Skip = "855425")] - public async Task ReturnArrayWithinExpressionCSharpAsync() - { - await VerifyCS.VerifyAnalyzerAsync(@" -using System.Collections.Generic; + public Task ReturnArrayWithinExpressionCSharpAsync() + => VerifyCS.VerifyAnalyzerAsync(""" -class C -{ - IEnumerable M1() { return 0 == 1 ? new[] { 1 } : new[] { 2 }; } - IEnumerable M2() { return null ?? new int[0]; } -} -" + _csharpSpecializedCollectionsDefinition, + using System.Collections.Generic; + + class C + { + IEnumerable M1() { return 0 == 1 ? new[] { 1 } : new[] { 2 }; } + IEnumerable M2() { return null ?? new int[0]; } + } + + """ + _csharpSpecializedCollectionsDefinition, GetCSharpSingletonEnumerableResultAt(6, 45), GetCSharpSingletonEnumerableResultAt(6, 59), GetCSharpEmptyEnumerableResultAt(7, 44)); - } [Fact] - public async Task ReturnLinqEmptyEnumerableWithinExpressionCSharpAsync() - { - await VerifyCS.VerifyAnalyzerAsync(@" -using System.Collections.Generic; -using System.Linq; + public Task ReturnLinqEmptyEnumerableWithinExpressionCSharpAsync() + => VerifyCS.VerifyAnalyzerAsync(""" -class C -{ - IEnumerable M1() { return 0 == 1 ? Enumerable.Empty() : null; } - IEnumerable M2() { return null ?? Enumerable.Empty(); } -} -" + _csharpSpecializedCollectionsDefinition, + using System.Collections.Generic; + using System.Linq; + + class C + { + IEnumerable M1() { return 0 == 1 ? Enumerable.Empty() : null; } + IEnumerable M2() { return null ?? Enumerable.Empty(); } + } + + """ + _csharpSpecializedCollectionsDefinition, GetCSharpEmptyEnumerableResultAt(7, 45), GetCSharpEmptyEnumerableResultAt(8, 44)); - } [Fact] - public async Task ReturnMultiElementArrayCSharpAsync() - { - await VerifyCS.VerifyAnalyzerAsync(@" -using System.Collections.Generic; + public Task ReturnMultiElementArrayCSharpAsync() + => VerifyCS.VerifyAnalyzerAsync(""" -class C -{ - IEnumerable M1() { return new int[2]; } - IEnumerable M2() { return new int[2] { 1, 2 }; } - IEnumerable M3() { return new[] { 1, 2 }; } - int[] M4() { return new[] { 1, 2 }; } -} -" + _csharpSpecializedCollectionsDefinition); - } + using System.Collections.Generic; + + class C + { + IEnumerable M1() { return new int[2]; } + IEnumerable M2() { return new int[2] { 1, 2 }; } + IEnumerable M3() { return new[] { 1, 2 }; } + int[] M4() { return new[] { 1, 2 }; } + } + + """ + _csharpSpecializedCollectionsDefinition); [Fact] - public async Task ReturnJaggedArrayCSharpAsync() - { - await VerifyCS.VerifyAnalyzerAsync(@" -using System.Collections.Generic; + public Task ReturnJaggedArrayCSharpAsync() + => VerifyCS.VerifyAnalyzerAsync(""" -class C -{ - IEnumerable M1() { return new int[2][] { new int[0], new int[0] }; } - IEnumerable M2() { return new[] { new[] { 1 } }; } - IEnumerable M3() { return new[] { new[] { 1, 2, 3 }, new[] { 1 } }; } -} -" + _csharpSpecializedCollectionsDefinition, + using System.Collections.Generic; + + class C + { + IEnumerable M1() { return new int[2][] { new int[0], new int[0] }; } + IEnumerable M2() { return new[] { new[] { 1 } }; } + IEnumerable M3() { return new[] { new[] { 1, 2, 3 }, new[] { 1 } }; } + } + + """ + _csharpSpecializedCollectionsDefinition, GetCSharpSingletonEnumerableResultAt(7, 38)); - } [Fact(Skip = "855425")] - public async Task ImplicitConversionToNestedEnumerableCSharpAsync() - { - await VerifyCS.VerifyAnalyzerAsync(@" -using System.Collections.Generic; + public Task ImplicitConversionToNestedEnumerableCSharpAsync() + => VerifyCS.VerifyAnalyzerAsync(""" -class C -{ - IEnumerable> M1() { return new[] { new[] { 1 } }; } -} -" + _csharpSpecializedCollectionsDefinition, + using System.Collections.Generic; + + class C + { + IEnumerable> M1() { return new[] { new[] { 1 } }; } + } + + """ + _csharpSpecializedCollectionsDefinition, GetCSharpSingletonEnumerableResultAt(5, 49), GetCSharpSingletonEnumerableResultAt(5, 57)); - } [Fact] - public async Task ReturnEmptyArrayBasicAsync() - { - await VerifyVB.VerifyAnalyzerAsync(@" -Imports System.Collections.Generic - -Class C - Function M1() As IEnumerable(Of Integer) - Return New Integer(0) {} - End Function - Function M2() As IEnumerable(Of Integer) - Return {} - End Function -End Class -" + _basicSpecializedCollectionsDefinition, + public Task ReturnEmptyArrayBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + + Imports System.Collections.Generic + + Class C + Function M1() As IEnumerable(Of Integer) + Return New Integer(0) {} + End Function + Function M2() As IEnumerable(Of Integer) + Return {} + End Function + End Class + + """ + _basicSpecializedCollectionsDefinition, GetBasicEmptyEnumerableResultAt(6, 16), GetBasicEmptyEnumerableResultAt(9, 16)); - } [Fact] - public async Task ReturnLinqEmptyEnumerableBasicAsync() - { - await VerifyVB.VerifyAnalyzerAsync(@" -Imports System.Collections.Generic -Imports System.Linq - -Class C - Function M1() As IEnumerable(Of Integer) - Return Enumerable.Empty(Of Integer)() - End Function -End Class -" + _basicSpecializedCollectionsDefinition, + public Task ReturnLinqEmptyEnumerableBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + + Imports System.Collections.Generic + Imports System.Linq + + Class C + Function M1() As IEnumerable(Of Integer) + Return Enumerable.Empty(Of Integer)() + End Function + End Class + + """ + _basicSpecializedCollectionsDefinition, GetBasicEmptyEnumerableResultAt(7, 16)); - } [Fact] - public async Task ReturnSingletonArrayBasicAsync() - { - await VerifyVB.VerifyAnalyzerAsync(@" -Imports System.Collections.Generic - -Class C - Function M1() As IEnumerable(Of Integer) - Return New Integer(0) {1} - End Function - Function M2() As IEnumerable(Of Integer) - Return {1} - End Function -End Class -" + _basicSpecializedCollectionsDefinition, + public Task ReturnSingletonArrayBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + + Imports System.Collections.Generic + + Class C + Function M1() As IEnumerable(Of Integer) + Return New Integer(0) {1} + End Function + Function M2() As IEnumerable(Of Integer) + Return {1} + End Function + End Class + + """ + _basicSpecializedCollectionsDefinition, GetBasicSingletonEnumerableResultAt(6, 16), GetBasicSingletonEnumerableResultAt(9, 16)); - } [Fact(Skip = "855425")] - public async Task ReturnArrayWithinExpressionBasicAsync() - { - await VerifyVB.VerifyAnalyzerAsync(@" -Imports System.Collections.Generic - -Class C - Function M1() As IEnumerable(Of Integer) - Return If(True, {1}, {2}) - End Function - Function M2() As IEnumerable(Of Integer) - Return If(True, {1}) - End Function -End Class -" + _basicSpecializedCollectionsDefinition, + public Task ReturnArrayWithinExpressionBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + + Imports System.Collections.Generic + + Class C + Function M1() As IEnumerable(Of Integer) + Return If(True, {1}, {2}) + End Function + Function M2() As IEnumerable(Of Integer) + Return If(True, {1}) + End Function + End Class + + """ + _basicSpecializedCollectionsDefinition, GetBasicSingletonEnumerableResultAt(6, 25), GetBasicSingletonEnumerableResultAt(6, 30), GetBasicSingletonEnumerableResultAt(9, 25)); - } [Fact] - public async Task ReturnLinqEmptyEnumerableWithinExpressionBasicAsync() - { - await VerifyVB.VerifyAnalyzerAsync(@" -Imports System.Collections.Generic -Imports System.Linq - -Class C - Function M1() As IEnumerable(Of Integer) - Return If(True, Enumerable.Empty(Of Integer)(), Nothing) - End Function - Function M2() As IEnumerable(Of Integer) - Return If({|BC33107:True|}, Enumerable.Empty(Of Integer)()) - End Function -End Class -" + _basicSpecializedCollectionsDefinition, + public Task ReturnLinqEmptyEnumerableWithinExpressionBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + + Imports System.Collections.Generic + Imports System.Linq + + Class C + Function M1() As IEnumerable(Of Integer) + Return If(True, Enumerable.Empty(Of Integer)(), Nothing) + End Function + Function M2() As IEnumerable(Of Integer) + Return If({|BC33107:True|}, Enumerable.Empty(Of Integer)()) + End Function + End Class + + """ + _basicSpecializedCollectionsDefinition, GetBasicEmptyEnumerableResultAt(7, 25), GetBasicEmptyEnumerableResultAt(10, 25)); - } [Fact] - public async Task ReturnMultiElementArrayBasicAsync() - { - await VerifyVB.VerifyAnalyzerAsync(@" -Imports System.Collections.Generic - -Class C - Function M1() As IEnumerable(Of Integer) - Return New Integer(1) {1, 2} - End Function - Function M2() As IEnumerable(Of Integer) - Return {1, 2} - End Function -End Class -" + _basicSpecializedCollectionsDefinition); - } + public Task ReturnMultiElementArrayBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + + Imports System.Collections.Generic + + Class C + Function M1() As IEnumerable(Of Integer) + Return New Integer(1) {1, 2} + End Function + Function M2() As IEnumerable(Of Integer) + Return {1, 2} + End Function + End Class + + """ + _basicSpecializedCollectionsDefinition); [Fact] - public async Task ReturnJaggedArrayBasicAsync() - { - await VerifyVB.VerifyAnalyzerAsync(@" -Imports System.Collections.Generic - -Class C - Function M1() As IEnumerable(Of Integer()) - Return New Integer(1)() {New Integer() {}, New Integer() {}} - End Function - Function M2() As IEnumerable(Of Integer()) - Return {({1})} - End Function - Function M3() As IEnumerable(Of Integer()) - Return {({1, 2, 3}), ({1})} - End Function -End Class -" + _basicSpecializedCollectionsDefinition, + public Task ReturnJaggedArrayBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + + Imports System.Collections.Generic + + Class C + Function M1() As IEnumerable(Of Integer()) + Return New Integer(1)() {New Integer() {}, New Integer() {}} + End Function + Function M2() As IEnumerable(Of Integer()) + Return {({1})} + End Function + Function M3() As IEnumerable(Of Integer()) + Return {({1, 2, 3}), ({1})} + End Function + End Class + + """ + _basicSpecializedCollectionsDefinition, GetBasicSingletonEnumerableResultAt(9, 16)); - } [Fact(Skip = "855425")] - public async Task ImplicitConversionToNestedEnumerableBasicAsync() - { - await VerifyVB.VerifyAnalyzerAsync(@" -Imports System.Collections.Generic - -Class C - Function M1() As IEnumerable(Of IEnumerable(Of Integer)) - Return {({1})} - End Function -End Class -" + _basicSpecializedCollectionsDefinition, + public Task ImplicitConversionToNestedEnumerableBasicAsync() + => VerifyVB.VerifyAnalyzerAsync(""" + + Imports System.Collections.Generic + + Class C + Function M1() As IEnumerable(Of IEnumerable(Of Integer)) + Return {({1})} + End Function + End Class + + """ + _basicSpecializedCollectionsDefinition, GetBasicSingletonEnumerableResultAt(6, 16), GetBasicSingletonEnumerableResultAt(6, 17)); - } } } diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/TemporaryArrayAsRefTests.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/TemporaryArrayAsRefTests.cs index 78df26ae8a452..572888d7a88f1 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/TemporaryArrayAsRefTests.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/TemporaryArrayAsRefTests.cs @@ -17,57 +17,63 @@ namespace Roslyn.Diagnostics.Analyzers.UnitTests { public class TemporaryArrayAsRefTests { - public const string TemporaryArraySource_CSharp = @" -namespace Microsoft.CodeAnalysis.Shared.Collections -{ - internal struct TemporaryArray : System.IDisposable - { - public void Dispose() { } - } + public const string TemporaryArraySource_CSharp = """ - internal static class TemporaryArrayExtensions - { - public static ref TemporaryArray AsRef(this in TemporaryArray array) => throw null; - } -} -"; - public const string TemporaryArraySource_VisualBasic = @" -Namespace Microsoft.CodeAnalysis.Shared.Collections - Friend Structure TemporaryArray(Of T) - Implements System.IDisposable - - Public Sub Dispose() Implements System.IDisposable.Dispose - End Sub - End Structure - - Friend Module TemporaryArrayExtensions - - Public Function AsRef(Of T)(array As TemporaryArray(Of T)) As TemporaryArray(Of T) - Return Nothing - End Function - End Module -End Namespace -"; + namespace Microsoft.CodeAnalysis.Shared.Collections + { + internal struct TemporaryArray : System.IDisposable + { + public void Dispose() { } + } + + internal static class TemporaryArrayExtensions + { + public static ref TemporaryArray AsRef(this in TemporaryArray array) => throw null; + } + } + + """; + public const string TemporaryArraySource_VisualBasic = """ + + Namespace Microsoft.CodeAnalysis.Shared.Collections + Friend Structure TemporaryArray(Of T) + Implements System.IDisposable + + Public Sub Dispose() Implements System.IDisposable.Dispose + End Sub + End Structure + + Friend Module TemporaryArrayExtensions + + Public Function AsRef(Of T)(array As TemporaryArray(Of T)) As TemporaryArray(Of T) + Return Nothing + End Function + End Module + End Namespace + + """; [Fact] public async Task TestUsingVariable_CSharpAsync() { - var code = @" -using Microsoft.CodeAnalysis.Shared.Collections; + var code = """ -class C -{ - void Method() - { - using (var array = new TemporaryArray()) - { - ref var arrayRef1 = ref array.AsRef(); - ref var arrayRef2 = ref TemporaryArrayExtensions.AsRef(in array); - } - } -} + using Microsoft.CodeAnalysis.Shared.Collections; -" + TemporaryArraySource_CSharp; + class C + { + void Method() + { + using (var array = new TemporaryArray()) + { + ref var arrayRef1 = ref array.AsRef(); + ref var arrayRef2 = ref TemporaryArrayExtensions.AsRef(in array); + } + } + } + + + """ + TemporaryArraySource_CSharp; await new VerifyCS.Test { @@ -79,19 +85,21 @@ void Method() [Fact] public async Task TestUsingVariable_VisualBasicAsync() { - var code = @" -Imports Microsoft.CodeAnalysis.Shared.Collections + var code = """ + + Imports Microsoft.CodeAnalysis.Shared.Collections + + Class C + Sub Method() + Using array = New TemporaryArray(Of Integer)() + Dim arrayRef1 = array.AsRef() + Dim arrayRef2 = TemporaryArrayExtensions.AsRef(array) + End Using + End Sub + End Class -Class C - Sub Method() - Using array = New TemporaryArray(Of Integer)() - Dim arrayRef1 = array.AsRef() - Dim arrayRef2 = TemporaryArrayExtensions.AsRef(array) - End Using - End Sub -End Class -" + TemporaryArraySource_VisualBasic; + """ + TemporaryArraySource_VisualBasic; await new VerifyVB.Test { @@ -103,20 +111,22 @@ End Class [Fact] public async Task TestUsingDeclarationVariable_CSharpAsync() { - var code = @" -using Microsoft.CodeAnalysis.Shared.Collections; + var code = """ -class C -{ - void Method() - { - using var array = new TemporaryArray(); - ref var arrayRef1 = ref array.AsRef(); - ref var arrayRef2 = ref TemporaryArrayExtensions.AsRef(in array); - } -} + using Microsoft.CodeAnalysis.Shared.Collections; -" + TemporaryArraySource_CSharp; + class C + { + void Method() + { + using var array = new TemporaryArray(); + ref var arrayRef1 = ref array.AsRef(); + ref var arrayRef2 = ref TemporaryArrayExtensions.AsRef(in array); + } + } + + + """ + TemporaryArraySource_CSharp; await new VerifyCS.Test { @@ -128,20 +138,22 @@ void Method() [Fact] public async Task TestNonUsingVariable_CSharpAsync() { - var code = @" -using Microsoft.CodeAnalysis.Shared.Collections; + var code = """ + + using Microsoft.CodeAnalysis.Shared.Collections; + + class C + { + void Method() + { + var array = new TemporaryArray(); + ref var arrayRef1 = ref [|array.AsRef()|]; + ref var arrayRef2 = ref [|TemporaryArrayExtensions.AsRef(in array)|]; + } + } -class C -{ - void Method() - { - var array = new TemporaryArray(); - ref var arrayRef1 = ref [|array.AsRef()|]; - ref var arrayRef2 = ref [|TemporaryArrayExtensions.AsRef(in array)|]; - } -} -" + TemporaryArraySource_CSharp; + """ + TemporaryArraySource_CSharp; await new VerifyCS.Test { @@ -153,18 +165,20 @@ void Method() [Fact] public async Task TestNonUsingVariable_VisualBasicAsync() { - var code = @" -Imports Microsoft.CodeAnalysis.Shared.Collections - -Class C - Sub Method() - Dim array = New TemporaryArray(Of Integer)() - Dim arrayRef1 = [|array.AsRef()|] - Dim arrayRef2 = [|TemporaryArrayExtensions.AsRef(array)|] - End Sub -End Class - -" + TemporaryArraySource_VisualBasic; + var code = """ + + Imports Microsoft.CodeAnalysis.Shared.Collections + + Class C + Sub Method() + Dim array = New TemporaryArray(Of Integer)() + Dim arrayRef1 = [|array.AsRef()|] + Dim arrayRef2 = [|TemporaryArrayExtensions.AsRef(array)|] + End Sub + End Class + + + """ + TemporaryArraySource_VisualBasic; await new VerifyVB.Test { diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/TestExportsShouldNotBeDiscoverableTests.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/TestExportsShouldNotBeDiscoverableTests.cs index 3574e2895dc9c..39a0ef3e97dc9 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/TestExportsShouldNotBeDiscoverableTests.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/UnitTests/TestExportsShouldNotBeDiscoverableTests.cs @@ -21,19 +21,19 @@ public class TestExportsShouldNotBeDiscoverableTests [InlineData("System.ComponentModel.Composition")] public async Task Discoverable_CSharpAsync(string mefNamespace) { - var source = $@" -using {mefNamespace}; + var source = $$""" + using {{mefNamespace}}; -[Export] -class C {{ }} -"; - var fixedSource = $@" -using {mefNamespace}; + [Export] + class C { } + """; + var fixedSource = $$""" + using {{mefNamespace}}; -[Export] -[PartNotDiscoverable] -class C {{ }} -"; + [Export] + [PartNotDiscoverable] + class C { } + """; await new VerifyCS.Test { @@ -41,7 +41,7 @@ class C {{ }} { Sources = { source }, AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyCS.Diagnostic().WithSpan(4, 2, 4, 8).WithArguments("C") }, + ExpectedDiagnostics = { VerifyCS.Diagnostic().WithSpan(3, 2, 3, 8).WithArguments("C") }, }, FixedState = { @@ -55,17 +55,17 @@ class C {{ }} [InlineData("System.ComponentModel.Composition")] public async Task DiscoverableAddImport_CSharpAsync(string mefNamespace) { - var source = $@" -[{mefNamespace}.Export] -class C {{ }} -"; - var fixedSource = $@" -using {mefNamespace}; - -[{mefNamespace}.Export] -[PartNotDiscoverable] -class C {{ }} -"; + var source = $$""" + [{{mefNamespace}}.Export] + class C { } + """; + var fixedSource = $$""" + using {{mefNamespace}}; + + [{{mefNamespace}}.Export] + [PartNotDiscoverable] + class C { } + """; await new VerifyCS.Test { @@ -73,7 +73,7 @@ class C {{ }} { Sources = { source }, AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyCS.Diagnostic().WithSpan(2, 2, 2, mefNamespace.Length + 9).WithArguments("C") }, + ExpectedDiagnostics = { VerifyCS.Diagnostic().WithSpan(1, 2, 1, mefNamespace.Length + 9).WithArguments("C") }, }, FixedState = { @@ -87,13 +87,13 @@ class C {{ }} [InlineData("System.ComponentModel.Composition")] public async Task NotDiscoverable_CSharpAsync(string mefNamespace) { - var source = $@" -using {mefNamespace}; + var source = $$""" + using {{mefNamespace}}; -[Export] -[PartNotDiscoverable] -class C {{ }} -"; + [Export] + [PartNotDiscoverable] + class C { } + """; await new VerifyCS.Test { @@ -110,21 +110,21 @@ class C {{ }} [InlineData("System.ComponentModel.Composition")] public async Task Discoverable_VisualBasicAsync(string mefNamespace) { - var source = $@" -Imports {mefNamespace} - - -Class C -End Class -"; - var fixedSource = $@" -Imports {mefNamespace} - - - -Class C -End Class -"; + var source = $""" + Imports {mefNamespace} + + + Class C + End Class + """; + var fixedSource = $""" + Imports {mefNamespace} + + + + Class C + End Class + """; await new VerifyVB.Test { @@ -132,7 +132,7 @@ End Class { Sources = { source }, AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyVB.Diagnostic().WithSpan(4, 2, 4, 8).WithArguments("C") }, + ExpectedDiagnostics = { VerifyVB.Diagnostic().WithSpan(3, 2, 3, 8).WithArguments("C") }, }, FixedState = { @@ -146,19 +146,19 @@ End Class [InlineData("System.ComponentModel.Composition")] public async Task DiscoverableAddImport_VisualBasicAsync(string mefNamespace) { - var source = $@" -<{mefNamespace}.Export> -Class C -End Class -"; - var fixedSource = $@" -Imports {mefNamespace} - -<{mefNamespace}.Export> - -Class C -End Class -"; + var source = $""" + <{mefNamespace}.Export> + Class C + End Class + """; + var fixedSource = $""" + Imports {mefNamespace} + + <{mefNamespace}.Export> + + Class C + End Class + """; await new VerifyVB.Test { @@ -166,7 +166,7 @@ End Class { Sources = { source }, AdditionalReferences = { AdditionalMetadataReferences.SystemComponentModelCompositionReference }, - ExpectedDiagnostics = { VerifyVB.Diagnostic().WithSpan(2, 2, 2, mefNamespace.Length + 9).WithArguments("C") }, + ExpectedDiagnostics = { VerifyVB.Diagnostic().WithSpan(1, 2, 1, mefNamespace.Length + 9).WithArguments("C") }, }, FixedState = { @@ -180,14 +180,14 @@ End Class [InlineData("System.ComponentModel.Composition")] public async Task NotDiscoverable_VisualBasicAsync(string mefNamespace) { - var source = $@" -Imports {mefNamespace} - - - -Class C -End Class -"; + var source = $""" + Imports {mefNamespace} + + + + Class C + End Class + """; await new VerifyVB.Test { diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/BasicImportingConstructorShouldBeObsoleteCodeFixProvider.vb b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/BasicImportingConstructorShouldBeObsoleteCodeFixProvider.vb new file mode 100644 index 0000000000000..c4e969ab1de03 --- /dev/null +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/BasicImportingConstructorShouldBeObsoleteCodeFixProvider.vb @@ -0,0 +1,27 @@ +' Licensed to the .NET Foundation under one or more agreements. +' The .NET Foundation licenses this file to you under the MIT license. +' See the LICENSE file in the project root for more information. + +Imports System.Composition +Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.CodeFixes + +Namespace Roslyn.Diagnostics.Analyzers + + Public NotInheritable Class BasicImportingConstructorShouldBeObsoleteCodeFixProvider + Inherits AbstractImportingConstructorShouldBeObsoleteCodeFixProvider + + + + Public Sub New() + End Sub + + Protected Overrides Function IsOnPrimaryConstructorTypeDeclaration(attributeName As SyntaxNode, ByRef typeDeclaration As SyntaxNode) As Boolean + Return False + End Function + + Protected Overrides Function AddMethodTarget(attributeList As SyntaxNode) As SyntaxNode + Return attributeList + End Function + End Class +End Namespace diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/BasicInvokeTheCorrectPropertyToEnsureCorrectUseSiteDiagnostics.vb b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/BasicInvokeTheCorrectPropertyToEnsureCorrectUseSiteDiagnostics.vb index 7233ce2b509dd..efcc1e995adce 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/BasicInvokeTheCorrectPropertyToEnsureCorrectUseSiteDiagnostics.vb +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/BasicInvokeTheCorrectPropertyToEnsureCorrectUseSiteDiagnostics.vb @@ -6,10 +6,9 @@ Imports System.Collections.Immutable Imports Analyzer.Utilities.Extensions Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Diagnostics.Analyzers -Imports Roslyn.Diagnostics.Analyzers.RoslynDiagnosticsAnalyzersResources +Imports Microsoft.CodeAnalysis.RoslynDiagnosticsAnalyzersResources Namespace Roslyn.Diagnostics.VisualBasic.Analyzers diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/BasicSpecializedEnumerableCreationAnalyzer.vb b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/BasicSpecializedEnumerableCreationAnalyzer.vb index 60ba5053e07b6..af6766a348a14 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/BasicSpecializedEnumerableCreationAnalyzer.vb +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/BasicSpecializedEnumerableCreationAnalyzer.vb @@ -5,7 +5,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Diagnostics.Analyzers diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/BasicSymbolDeclaredEventMustBeGeneratedForSourceSymbols.vb b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/BasicSymbolDeclaredEventMustBeGeneratedForSourceSymbols.vb index c8cff17347991..832c89fffb61d 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/BasicSymbolDeclaredEventMustBeGeneratedForSourceSymbols.vb +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/BasicSymbolDeclaredEventMustBeGeneratedForSourceSymbols.vb @@ -6,7 +6,6 @@ Imports System.Collections.Immutable Imports Analyzer.Utilities.Extensions Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Diagnostics.Analyzers diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/Roslyn.Diagnostics.VisualBasic.Analyzers.vbproj b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/Roslyn.Diagnostics.VisualBasic.Analyzers.vbproj index d985054a90641..4f24de5dec847 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/Roslyn.Diagnostics.VisualBasic.Analyzers.vbproj +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/Roslyn.Diagnostics.VisualBasic.Analyzers.vbproj @@ -2,17 +2,29 @@ netstandard2.0 - $(MicrosoftCodeAnalysisForRoslynDiagnosticsAnalyzersVersion) - - - - - - - + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/VisualBasicApplyTraitToClass.vb b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/VisualBasicApplyTraitToClass.vb index ee4b9f24b2c66..8f99501152a5c 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/VisualBasicApplyTraitToClass.vb +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/VisualBasicApplyTraitToClass.vb @@ -3,9 +3,9 @@ ' See the LICENSE file in the project root for more information. Imports System.Composition -Imports Analyzer.Utilities Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeRefactorings +Imports Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Diagnostics.Analyzers diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/VisualBasicCreateTestAccessor.vb b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/VisualBasicCreateTestAccessor.vb index cc819a041726c..20d4336e59362 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/VisualBasicCreateTestAccessor.vb +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/VisualBasicCreateTestAccessor.vb @@ -3,9 +3,9 @@ ' See the LICENSE file in the project root for more information. Imports System.Composition -Imports Analyzer.Utilities Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeRefactorings +Imports Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Diagnostics.Analyzers diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/VisualBasicExposeMemberForTesting.vb b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/VisualBasicExposeMemberForTesting.vb index 92d50e090abc3..b02868c11a8ab 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/VisualBasicExposeMemberForTesting.vb +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/VisualBasicExposeMemberForTesting.vb @@ -3,9 +3,9 @@ ' See the LICENSE file in the project root for more information. Imports System.Composition -Imports Analyzer.Utilities Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeRefactorings +Imports Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Diagnostics.Analyzers diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/VisualBasicRunIterations.vb b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/VisualBasicRunIterations.vb index 691b46f3204dc..19139fd38e049 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/VisualBasicRunIterations.vb +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/VisualBasic/VisualBasicRunIterations.vb @@ -3,11 +3,11 @@ ' See the LICENSE file in the project root for more information. Imports System.Composition -Imports Analyzer.Utilities Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Diagnostics.Analyzers +Imports Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings Namespace Roslyn.Diagnostics.VisualBasic.Analyzers diff --git a/src/RoslynAnalyzers/Test.Utilities/CSharpCodeFixVerifier`2+Test.cs b/src/RoslynAnalyzers/Test.Utilities/CSharpCodeFixVerifier`2+Test.cs index 0870989b0635a..64ad6e29213ad 100644 --- a/src/RoslynAnalyzers/Test.Utilities/CSharpCodeFixVerifier`2+Test.cs +++ b/src/RoslynAnalyzers/Test.Utilities/CSharpCodeFixVerifier`2+Test.cs @@ -49,7 +49,7 @@ public Test() private static ImmutableDictionary GetNullableWarningsFromCompiler() { - string[] args = { "/warnaserror:nullable" }; + string[] args = ["/warnaserror:nullable"]; var commandLineArguments = CSharpCommandLineParser.Default.Parse(args, baseDirectory: Environment.CurrentDirectory, sdkDirectory: Environment.CurrentDirectory); var nullableWarnings = commandLineArguments.CompilationOptions.SpecificDiagnosticOptions; diff --git a/src/RoslynAnalyzers/Test.Utilities/CSharpCodeFixVerifier`2.cs b/src/RoslynAnalyzers/Test.Utilities/CSharpCodeFixVerifier`2.cs index cba1fa656ec54..f435a3d86dd03 100644 --- a/src/RoslynAnalyzers/Test.Utilities/CSharpCodeFixVerifier`2.cs +++ b/src/RoslynAnalyzers/Test.Utilities/CSharpCodeFixVerifier`2.cs @@ -40,7 +40,7 @@ public static async Task VerifyCodeFixAsync([StringSyntax("C#-test")] string sou => await VerifyCodeFixAsync(source, DiagnosticResult.EmptyDiagnosticResults, fixedSource); public static async Task VerifyCodeFixAsync([StringSyntax("C#-test")] string source, DiagnosticResult expected, [StringSyntax("C#-test")] string fixedSource) - => await VerifyCodeFixAsync(source, new[] { expected }, fixedSource); + => await VerifyCodeFixAsync(source, [expected], fixedSource); public static async Task VerifyCodeFixAsync([StringSyntax("C#-test")] string source, DiagnosticResult[] expected, [StringSyntax("C#-test")] string fixedSource) { diff --git a/src/RoslynAnalyzers/Test.Utilities/CSharpCodeRefactoringVerifier`1.cs b/src/RoslynAnalyzers/Test.Utilities/CSharpCodeRefactoringVerifier`1.cs index 31eb5573ddd57..951a50b7974d0 100644 --- a/src/RoslynAnalyzers/Test.Utilities/CSharpCodeRefactoringVerifier`1.cs +++ b/src/RoslynAnalyzers/Test.Utilities/CSharpCodeRefactoringVerifier`1.cs @@ -18,7 +18,7 @@ public static async Task VerifyRefactoringAsync([StringSyntax("C#-test")] string /// public static async Task VerifyRefactoringAsync([StringSyntax("C#-test")] string source, DiagnosticResult expected, [StringSyntax("C#-test")] string fixedSource) - => await VerifyRefactoringAsync(source, new[] { expected }, fixedSource); + => await VerifyRefactoringAsync(source, [expected], fixedSource); /// public static async Task VerifyRefactoringAsync([StringSyntax("C#-test")] string source, DiagnosticResult[] expected, [StringSyntax("C#-test")] string fixedSource) diff --git a/src/RoslynAnalyzers/Test.Utilities/CSharpSecurityCodeFixVerifier`2.cs b/src/RoslynAnalyzers/Test.Utilities/CSharpSecurityCodeFixVerifier`2.cs index ef44324b83d9d..6590a1197d986 100644 --- a/src/RoslynAnalyzers/Test.Utilities/CSharpSecurityCodeFixVerifier`2.cs +++ b/src/RoslynAnalyzers/Test.Utilities/CSharpSecurityCodeFixVerifier`2.cs @@ -39,7 +39,7 @@ public static Task VerifyCodeFixAsync([StringSyntax("C#-test")] string source, [ => VerifyCodeFixAsync(source, DiagnosticResult.EmptyDiagnosticResults, fixedSource); public static Task VerifyCodeFixAsync([StringSyntax("C#-test")] string source, DiagnosticResult expected, [StringSyntax("C#-test")] string fixedSource) - => VerifyCodeFixAsync(source, new[] { expected }, fixedSource); + => VerifyCodeFixAsync(source, [expected], fixedSource); public static async Task VerifyCodeFixAsync([StringSyntax("C#-test")] string source, DiagnosticResult[] expected, [StringSyntax("C#-test")] string fixedSource) { diff --git a/src/RoslynAnalyzers/Test.Utilities/CodeMetricsTestsBase.cs b/src/RoslynAnalyzers/Test.Utilities/CodeMetricsTestsBase.cs index 897879960e628..0289cefc7c742 100644 --- a/src/RoslynAnalyzers/Test.Utilities/CodeMetricsTestsBase.cs +++ b/src/RoslynAnalyzers/Test.Utilities/CodeMetricsTestsBase.cs @@ -61,13 +61,13 @@ protected Project CreateProject(string[] sources, string language = LanguageName } protected void VerifyCSharp(string source, string expectedMetricsText, bool expectDiagnostics = false) - => Verify(new[] { source }, expectedMetricsText, expectDiagnostics, LanguageNames.CSharp); + => Verify([source], expectedMetricsText, expectDiagnostics, LanguageNames.CSharp); protected void VerifyCSharp(string[] sources, string expectedMetricsText, bool expectDiagnostics = false) => Verify(sources, expectedMetricsText, expectDiagnostics, LanguageNames.CSharp); protected void VerifyBasic(string source, string expectedMetricsText, bool expectDiagnostics = false) - => Verify(new[] { source }, expectedMetricsText, expectDiagnostics, LanguageNames.VisualBasic); + => Verify([source], expectedMetricsText, expectDiagnostics, LanguageNames.VisualBasic); private void Verify(string[] sources, string expectedMetricsText, bool expectDiagnostics, string language) { @@ -85,8 +85,8 @@ private void Verify(string[] sources, string expectedMetricsText, bool expectDia var actualMetricsText = GetMetricsDataString(compilation).Trim(); expectedMetricsText = expectedMetricsText.Trim(); - var actualMetricsTextLines = actualMetricsText.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); - var expectedMetricsTextLines = expectedMetricsText.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); + var actualMetricsTextLines = actualMetricsText.Split([Environment.NewLine], StringSplitOptions.RemoveEmptyEntries); + var expectedMetricsTextLines = expectedMetricsText.Split([Environment.NewLine], StringSplitOptions.RemoveEmptyEntries); var success = true; if (actualMetricsTextLines.Length != expectedMetricsTextLines.Length) diff --git a/src/RoslynAnalyzers/Test.Utilities/SharedTestCode.cs b/src/RoslynAnalyzers/Test.Utilities/SharedTestCode.cs index 297807039fe07..22c4a41cf437e 100644 --- a/src/RoslynAnalyzers/Test.Utilities/SharedTestCode.cs +++ b/src/RoslynAnalyzers/Test.Utilities/SharedTestCode.cs @@ -6,24 +6,24 @@ namespace Test.Utilities { public static class SharedCode { - public const string WrongSanitizer = @" -using System; -using System.Data.SqlClient; -using System.IO; -using System.Web; + public const string WrongSanitizer = """ + using System; + using System.Data.SqlClient; + using System.IO; + using System.Web; -public partial class WebForm : System.Web.UI.Page -{ - protected void Page_Load(object sender, EventArgs e) - { - string input = Request.Form[""in""]; - StringWriter w = new StringWriter(); - Server.HtmlEncode(input, w); - Response.Write("""" + w.ToString() + """"); - // make sure it is not like any unknown method breaks the taint path, it should warn about sql injection - SqlCommand sqlCommand = new SqlCommand(w.ToString()); - } -} -"; + public partial class WebForm : System.Web.UI.Page + { + protected void Page_Load(object sender, EventArgs e) + { + string input = Request.Form["in"]; + StringWriter w = new StringWriter(); + Server.HtmlEncode(input, w); + Response.Write("" + w.ToString() + ""); + // make sure it is not like any unknown method breaks the taint path, it should warn about sql injection + SqlCommand sqlCommand = new SqlCommand(w.ToString()); + } + } + """; } } diff --git a/src/RoslynAnalyzers/Test.Utilities/Test.Utilities.csproj b/src/RoslynAnalyzers/Test.Utilities/Test.Utilities.csproj index 1c92274532f79..93c0156842dda 100644 --- a/src/RoslynAnalyzers/Test.Utilities/Test.Utilities.csproj +++ b/src/RoslynAnalyzers/Test.Utilities/Test.Utilities.csproj @@ -5,20 +5,18 @@ true false true - $(MicrosoftCodeAnalysisVersionForToolsAndUtilities) - - - TEST_UTILITIES + Microsoft.CodeAnalysis + $(DefineConstants),TEST_UTILITIES - - - - - - + + + + + + @@ -45,4 +43,12 @@ + + + + + + + + diff --git a/src/RoslynAnalyzers/Test.Utilities/VisualBasicCodeFixVerifier`2.cs b/src/RoslynAnalyzers/Test.Utilities/VisualBasicCodeFixVerifier`2.cs index 48e2ee4e47028..212a3ac20c5ec 100644 --- a/src/RoslynAnalyzers/Test.Utilities/VisualBasicCodeFixVerifier`2.cs +++ b/src/RoslynAnalyzers/Test.Utilities/VisualBasicCodeFixVerifier`2.cs @@ -39,7 +39,7 @@ public static async Task VerifyCodeFixAsync(string source, string fixedSource) => await VerifyCodeFixAsync(source, DiagnosticResult.EmptyDiagnosticResults, fixedSource); public static async Task VerifyCodeFixAsync(string source, DiagnosticResult expected, string fixedSource) - => await VerifyCodeFixAsync(source, new[] { expected }, fixedSource); + => await VerifyCodeFixAsync(source, [expected], fixedSource); public static async Task VerifyCodeFixAsync(string source, DiagnosticResult[] expected, string fixedSource) { diff --git a/src/RoslynAnalyzers/Test.Utilities/VisualBasicCodeRefactoringVerifier`1.cs b/src/RoslynAnalyzers/Test.Utilities/VisualBasicCodeRefactoringVerifier`1.cs index 684a1b532a5b7..9ba7523c68d23 100644 --- a/src/RoslynAnalyzers/Test.Utilities/VisualBasicCodeRefactoringVerifier`1.cs +++ b/src/RoslynAnalyzers/Test.Utilities/VisualBasicCodeRefactoringVerifier`1.cs @@ -17,7 +17,7 @@ public static async Task VerifyRefactoringAsync(string source, string fixedSourc /// public static async Task VerifyRefactoringAsync(string source, DiagnosticResult expected, string fixedSource) - => await VerifyRefactoringAsync(source, new[] { expected }, fixedSource); + => await VerifyRefactoringAsync(source, [expected], fixedSource); /// public static async Task VerifyRefactoringAsync(string source, DiagnosticResult[] expected, string fixedSource) diff --git a/src/RoslynAnalyzers/Test.Utilities/VisualBasicSecurityCodeFixVerifier`2.cs b/src/RoslynAnalyzers/Test.Utilities/VisualBasicSecurityCodeFixVerifier`2.cs index 82491d0e23857..11afbb1304b8c 100644 --- a/src/RoslynAnalyzers/Test.Utilities/VisualBasicSecurityCodeFixVerifier`2.cs +++ b/src/RoslynAnalyzers/Test.Utilities/VisualBasicSecurityCodeFixVerifier`2.cs @@ -39,7 +39,7 @@ public static Task VerifyCodeFixAsync(string source, string fixedSource) => VerifyCodeFixAsync(source, DiagnosticResult.EmptyDiagnosticResults, fixedSource); public static Task VerifyCodeFixAsync(string source, DiagnosticResult expected, string fixedSource) - => VerifyCodeFixAsync(source, new[] { expected }, fixedSource); + => VerifyCodeFixAsync(source, [expected], fixedSource); public static async Task VerifyCodeFixAsync(string source, DiagnosticResult[] expected, string fixedSource) { diff --git a/src/RoslynAnalyzers/Text.Analyzers/CSharp/Text.CSharp.Analyzers.csproj b/src/RoslynAnalyzers/Text.Analyzers/CSharp/Text.CSharp.Analyzers.csproj index 6ffc9d72af198..0d829ac1874da 100644 --- a/src/RoslynAnalyzers/Text.Analyzers/CSharp/Text.CSharp.Analyzers.csproj +++ b/src/RoslynAnalyzers/Text.Analyzers/CSharp/Text.CSharp.Analyzers.csproj @@ -2,15 +2,14 @@ netstandard2.0 - $(MicrosoftCodeAnalysisVersionForTextAnalyzers) - - - - + + + + \ No newline at end of file diff --git a/src/RoslynAnalyzers/Text.Analyzers/Core/Text.Analyzers.csproj b/src/RoslynAnalyzers/Text.Analyzers/Core/Text.Analyzers.csproj index 3780a727920b0..3e6c88a1a3cee 100644 --- a/src/RoslynAnalyzers/Text.Analyzers/Core/Text.Analyzers.csproj +++ b/src/RoslynAnalyzers/Text.Analyzers/Core/Text.Analyzers.csproj @@ -7,7 +7,7 @@ Restore would conclude that there is a cyclic dependency between us and the Text.Analyzers nuget package. --> *$(MSBuildProjectFile)* - $(MicrosoftCodeAnalysisVersionForTextAnalyzers) + Microsoft.CodeAnalysis @@ -24,9 +24,18 @@ - - + + + + + + + + + + + diff --git a/src/RoslynAnalyzers/Text.Analyzers/Core/TextAnalyzersResources.cs b/src/RoslynAnalyzers/Text.Analyzers/Core/TextAnalyzersResources.cs index 5e99665fdc31f..037709a855523 100644 --- a/src/RoslynAnalyzers/Text.Analyzers/Core/TextAnalyzersResources.cs +++ b/src/RoslynAnalyzers/Text.Analyzers/Core/TextAnalyzersResources.cs @@ -5,7 +5,7 @@ using System; using Microsoft.CodeAnalysis; -namespace Text.Analyzers +namespace Microsoft.CodeAnalysis { internal partial class TextAnalyzersResources { diff --git a/src/RoslynAnalyzers/Text.Analyzers/UnitTests/EnumsShouldHavePluralNamesTests.cs b/src/RoslynAnalyzers/Text.Analyzers/UnitTests/EnumsShouldHavePluralNamesTests.cs index 61a3f5b1ff9f5..1697a780fa5d9 100644 --- a/src/RoslynAnalyzers/Text.Analyzers/UnitTests/EnumsShouldHavePluralNamesTests.cs +++ b/src/RoslynAnalyzers/Text.Analyzers/UnitTests/EnumsShouldHavePluralNamesTests.cs @@ -21,415 +21,463 @@ public class EnumsShouldHavePluralNamesTests [Fact] public async Task CA1714_CA1717_Test_EnumWithNoFlags_SingularNameAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" - public class A - { - public enum Day - { - Sunday = 0, - Monday = 1, - Tuesday = 2 - - }; - }" + await VerifyCS.VerifyAnalyzerAsync(""" + + public class A + { + public enum Day + { + Sunday = 0, + Monday = 1, + Tuesday = 2 + + }; + } + """ ); - await VerifyVB.VerifyAnalyzerAsync(@" - Public Class A - Public Enum Day - Sunday = 0 - Monday = 1 - Tuesday = 2 + await VerifyVB.VerifyAnalyzerAsync(""" - End Enum - End Class - "); + Public Class A + Public Enum Day + Sunday = 0 + Monday = 1 + Tuesday = 2 + + End Enum + End Class + + """); } [Fact] public async Task CA1714_CA1717__Test_EnumWithNoFlags_PluralNameAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" - public class A - { - public enum Days - { - sunday = 0, - Monday = 1, - Tuesday = 2 - - }; - }", + await VerifyCS.VerifyAnalyzerAsync(""" + + public class A + { + public enum Days + { + sunday = 0, + Monday = 1, + Tuesday = 2 + + }; + } + """, GetCSharpNoPluralResultAt(4, 44)); - await VerifyVB.VerifyAnalyzerAsync(@" - Public Class A - Public Enum Days - Sunday = 0 - Monday = 1 - Tuesday = 2 + await VerifyVB.VerifyAnalyzerAsync(""" + + Public Class A + Public Enum Days + Sunday = 0 + Monday = 1 + Tuesday = 2 - End Enum - End Class - ", + End Enum + End Class + + """, GetBasicNoPluralResultAt(3, 38)); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task CA1714_CA1717__Test_EnumWithNoFlags_PluralName_InternalAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -class A -{ - enum Days - { - sunday = 0, - Monday = 1, - Tuesday = 2 - - }; -} - -public class A2 -{ - private enum Days - { - sunday = 0, - Monday = 1, - Tuesday = 2 - - }; -} - -internal class A3 -{ - public enum Days - { - sunday = 0, - Monday = 1, - Tuesday = 2 - - }; -} -"); - - await VerifyVB.VerifyAnalyzerAsync(@" -Class A - Private Enum Days - Sunday = 0 - Monday = 1 - Tuesday = 2 - End Enum -End Class - -Public Class A2 - Private Enum Days - Sunday = 0 - Monday = 1 - Tuesday = 2 - End Enum -End Class - -Friend Class A3 - Public Enum Days - Sunday = 0 - Monday = 1 - Tuesday = 2 - End Enum -End Class -"); + await VerifyCS.VerifyAnalyzerAsync(""" + + class A + { + enum Days + { + sunday = 0, + Monday = 1, + Tuesday = 2 + + }; + } + + public class A2 + { + private enum Days + { + sunday = 0, + Monday = 1, + Tuesday = 2 + + }; + } + + internal class A3 + { + public enum Days + { + sunday = 0, + Monday = 1, + Tuesday = 2 + + }; + } + + """); + + await VerifyVB.VerifyAnalyzerAsync(""" + + Class A + Private Enum Days + Sunday = 0 + Monday = 1 + Tuesday = 2 + End Enum + End Class + + Public Class A2 + Private Enum Days + Sunday = 0 + Monday = 1 + Tuesday = 2 + End Enum + End Class + + Friend Class A3 + Public Enum Days + Sunday = 0 + Monday = 1 + Tuesday = 2 + End Enum + End Class + + """); } [Fact] public async Task CA1714_CA1717__Test_EnumWithNoFlags_PluralName_UpperCaseAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" - public class A - { - public enum DAYS - { - sunday = 0, - Monday = 1, - Tuesday = 2 - - }; - }", + await VerifyCS.VerifyAnalyzerAsync(""" + + public class A + { + public enum DAYS + { + sunday = 0, + Monday = 1, + Tuesday = 2 + + }; + } + """, GetCSharpNoPluralResultAt(4, 44)); - await VerifyVB.VerifyAnalyzerAsync(@" - Public Class A - Public Enum DAYS - Sunday = 0 - Monday = 1 - Tuesday = 2 + await VerifyVB.VerifyAnalyzerAsync(""" + + Public Class A + Public Enum DAYS + Sunday = 0 + Monday = 1 + Tuesday = 2 - End Enum - End Class - ", + End Enum + End Class + + """, GetBasicNoPluralResultAt(3, 38)); } [Fact] public async Task CA1714_CA1717_Test_EnumWithFlags_SingularNameAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" - public class A - { - [System.Flags] - public enum Day - { - sunday = 0, - Monday = 1, - Tuesday = 2 - - }; - }", + await VerifyCS.VerifyAnalyzerAsync(""" + + public class A + { + [System.Flags] + public enum Day + { + sunday = 0, + Monday = 1, + Tuesday = 2 + + }; + } + """, GetCSharpPluralResultAt(5, 44)); - await VerifyVB.VerifyAnalyzerAsync(@" - Public Class A - _ - Public Enum Day - Sunday = 0 - Monday = 1 - Tuesday = 2 - End Enum - End Class", + await VerifyVB.VerifyAnalyzerAsync(""" + + Public Class A + _ + Public Enum Day + Sunday = 0 + Monday = 1 + Tuesday = 2 + End Enum + End Class + """, GetBasicPluralResultAt(4, 34)); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task CA1714_CA1717_Test_EnumWithFlags_SingularName_InternalAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" -class A -{ - [System.Flags] - enum Day - { - sunday = 0, - Monday = 1, - Tuesday = 2 - - } -} - -public class A2 -{ - [System.Flags] - private enum Day - { - sunday = 0, - Monday = 1, - Tuesday = 2 - - } -} - -internal class A3 -{ - [System.Flags] - public enum Day - { - sunday = 0, - Monday = 1, - Tuesday = 2 - - } -} -"); - - await VerifyVB.VerifyAnalyzerAsync(@" -Class A - _ - Enum Day - Sunday = 0 - Monday = 1 - Tuesday = 2 - End Enum -End Class - -Public Class A2 - _ - Private Enum Day - Sunday = 0 - Monday = 1 - Tuesday = 2 - End Enum -End Class - -Friend Class A3 - _ - Public Enum Day - Sunday = 0 - Monday = 1 - Tuesday = 2 - End Enum -End Class -"); + await VerifyCS.VerifyAnalyzerAsync(""" + + class A + { + [System.Flags] + enum Day + { + sunday = 0, + Monday = 1, + Tuesday = 2 + + } + } + + public class A2 + { + [System.Flags] + private enum Day + { + sunday = 0, + Monday = 1, + Tuesday = 2 + + } + } + + internal class A3 + { + [System.Flags] + public enum Day + { + sunday = 0, + Monday = 1, + Tuesday = 2 + + } + } + + """); + + await VerifyVB.VerifyAnalyzerAsync(""" + + Class A + _ + Enum Day + Sunday = 0 + Monday = 1 + Tuesday = 2 + End Enum + End Class + + Public Class A2 + _ + Private Enum Day + Sunday = 0 + Monday = 1 + Tuesday = 2 + End Enum + End Class + + Friend Class A3 + _ + Public Enum Day + Sunday = 0 + Monday = 1 + Tuesday = 2 + End Enum + End Class + + """); } [Fact] public async Task CA1714_CA1717_Test_EnumWithFlags_PluralNameAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" - public class A - { - [System.Flags] - public enum Days - { - sunday = 0, - Monday = 1, - Tuesday = 2 - - }; - }"); - - await VerifyVB.VerifyAnalyzerAsync(@" - Public Class A - _ - Public Enum Days - Sunday = 0 - Monday = 1 - Tuesday = 2 - End Enum - End Class"); + await VerifyCS.VerifyAnalyzerAsync(""" + + public class A + { + [System.Flags] + public enum Days + { + sunday = 0, + Monday = 1, + Tuesday = 2 + + }; + } + """); + + await VerifyVB.VerifyAnalyzerAsync(""" + + Public Class A + _ + Public Enum Days + Sunday = 0 + Monday = 1 + Tuesday = 2 + End Enum + End Class + """); } [Fact] public async Task CA1714_CA1717_Test_EnumWithFlags_PluralName_UpperCaseAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" - public class A - { - [System.Flags] - public enum DAYS - { - sunday = 0, - Monday = 1, - Tuesday = 2 - - }; - }"); - - await VerifyVB.VerifyAnalyzerAsync(@" - Public Class A - _ - Public Enum DAYS - Sunday = 0 - Monday = 1 - Tuesday = 2 - End Enum - End Class"); + await VerifyCS.VerifyAnalyzerAsync(""" + + public class A + { + [System.Flags] + public enum DAYS + { + sunday = 0, + Monday = 1, + Tuesday = 2 + + }; + } + """); + + await VerifyVB.VerifyAnalyzerAsync(""" + + Public Class A + _ + Public Enum DAYS + Sunday = 0 + Monday = 1 + Tuesday = 2 + End Enum + End Class + """); } [Fact, WorkItem(1323, "https://github.com/dotnet/roslyn-analyzers/issues/1323")] public async Task CA1714_CA1717_Test_EnumWithFlags_NonPluralNameEndsWithSAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" - public class A - { - [System.Flags] - public enum Axis - { - x = 0, - y = 1, - z = 2 - - }; - }", + await VerifyCS.VerifyAnalyzerAsync(""" + + public class A + { + [System.Flags] + public enum Axis + { + x = 0, + y = 1, + z = 2 + + }; + } + """, GetCSharpPluralResultAt(5, 44)); - await VerifyVB.VerifyAnalyzerAsync(@" - Public Class A - _ - Public Enum Axis - x = 0 - y = 1 - z = 2 - End Enum - End Class", + await VerifyVB.VerifyAnalyzerAsync(""" + + Public Class A + _ + Public Enum Axis + x = 0 + y = 1 + z = 2 + End Enum + End Class + """, GetBasicPluralResultAt(4, 34)); } [Fact, WorkItem(1323, "https://github.com/dotnet/roslyn-analyzers/issues/1323")] public async Task CA1714_CA1717_Test_EnumWithFlags_PluralNameEndsWithSAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" - public class A - { - [System.Flags] - public enum Axes - { - x = 0, - y = 1, - z = 2 - - }; - }"); - - await VerifyVB.VerifyAnalyzerAsync(@" - Public Class A - _ - Public Enum Axes - x = 0 - y = 1 - z = 2 - End Enum - End Class"); + await VerifyCS.VerifyAnalyzerAsync(""" + + public class A + { + [System.Flags] + public enum Axes + { + x = 0, + y = 1, + z = 2 + + }; + } + """); + + await VerifyVB.VerifyAnalyzerAsync(""" + + Public Class A + _ + Public Enum Axes + x = 0 + y = 1 + z = 2 + End Enum + End Class + """); } [Fact, WorkItem(1323, "https://github.com/dotnet/roslyn-analyzers/issues/1323")] public async Task CA1714_CA1717_Test_EnumWithFlags_PluralName_NotEndingWithSAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" - public class A - { - [System.Flags] - public enum Men - { - M1 = 0, - M2 = 1, - M3 = 2 - - }; - }"); - - await VerifyVB.VerifyAnalyzerAsync(@" - Public Class A - < System.Flags > _ - Public Enum Men - M1 = 0 - M2 = 1 - M3 = 2 - End Enum - End Class"); + await VerifyCS.VerifyAnalyzerAsync(""" + + public class A + { + [System.Flags] + public enum Men + { + M1 = 0, + M2 = 1, + M3 = 2 + + }; + } + """); + + await VerifyVB.VerifyAnalyzerAsync(""" + + Public Class A + < System.Flags > _ + Public Enum Men + M1 = 0 + M2 = 1 + M3 = 2 + End Enum + End Class + """); } [Fact, WorkItem(1323, "https://github.com/dotnet/roslyn-analyzers/issues/1323")] public async Task CA1714_CA1717_Test_EnumWithNoFlags_PluralWord_NotEndingWithSAsync() { - await VerifyCS.VerifyAnalyzerAsync(@" - public class A - { - public enum Men - { - M1 = 0, - M2 = 1, - M3 = 2 - - }; - }", + await VerifyCS.VerifyAnalyzerAsync(""" + + public class A + { + public enum Men + { + M1 = 0, + M2 = 1, + M3 = 2 + + }; + } + """, GetCSharpNoPluralResultAt(4, 44)); - await VerifyVB.VerifyAnalyzerAsync(@" - Public Class A - Public Enum Men - M1 = 0 - M2 = 1 - M3 = 2 - End Enum - End Class", + await VerifyVB.VerifyAnalyzerAsync(""" + + Public Class A + Public Enum Men + M1 = 0 + M2 = 1 + M3 = 2 + End Enum + End Class + """, GetBasicNoPluralResultAt(3, 37)); } @@ -437,84 +485,96 @@ End Enum public async Task CA1714_CA1717_Test_EnumWithNoFlags_irregularPluralWord_EndingWith_aeAsync() { // Humanizer does not recognize 'formulae' as plural, but we skip words ending with 'ae' - await VerifyCS.VerifyAnalyzerAsync(@" - public class A - { - [System.Flags] - public enum formulae - { - M1 = 0, - M2 = 1, - M3 = 2 - - }; - }"); - - await VerifyVB.VerifyAnalyzerAsync(@" - Public Class A - < System.Flags > _ - Public Enum formulae - M1 = 0 - M2 = 1 - M3 = 2 - End Enum - End Class"); + await VerifyCS.VerifyAnalyzerAsync(""" + + public class A + { + [System.Flags] + public enum formulae + { + M1 = 0, + M2 = 1, + M3 = 2 + + }; + } + """); + + await VerifyVB.VerifyAnalyzerAsync(""" + + Public Class A + < System.Flags > _ + Public Enum formulae + M1 = 0 + M2 = 1 + M3 = 2 + End Enum + End Class + """); } [Fact, WorkItem(1323, "https://github.com/dotnet/roslyn-analyzers/issues/1323")] public async Task CA1714_CA1717_Test_EnumWithNoFlags_irregularPluralWord_EndingWith_iAsync() { // Humanizer does not recognize 'trophi' as plural, but we skip words ending with 'i' - await VerifyCS.VerifyAnalyzerAsync(@" - public class A - { - [System.Flags] - public enum trophi - { - M1 = 0, - M2 = 1, - M3 = 2 - - }; - }"); - - await VerifyVB.VerifyAnalyzerAsync(@" - Public Class A - < System.Flags > _ - Public Enum trophi - M1 = 0 - M2 = 1 - M3 = 2 - End Enum - End Class"); + await VerifyCS.VerifyAnalyzerAsync(""" + + public class A + { + [System.Flags] + public enum trophi + { + M1 = 0, + M2 = 1, + M3 = 2 + + }; + } + """); + + await VerifyVB.VerifyAnalyzerAsync(""" + + Public Class A + < System.Flags > _ + Public Enum trophi + M1 = 0 + M2 = 1 + M3 = 2 + End Enum + End Class + """); } [Fact, WorkItem(1323, "https://github.com/dotnet/roslyn-analyzers/issues/1323")] public async Task CA1714_CA1717_Test_EnumWithNoFlags_NonAsciiAsync() { // We skip non-ASCII names. - await VerifyCS.VerifyAnalyzerAsync(@" - public class A - { - [System.Flags] - public enum UnicodeNameΔ - { - M1 = 0, - M2 = 1, - M3 = 2 - - }; - }"); - - await VerifyVB.VerifyAnalyzerAsync(@" - Public Class A - < System.Flags > _ - Public Enum UnicodeNameΔ - M1 = 0 - M2 = 1 - M3 = 2 - End Enum - End Class"); + await VerifyCS.VerifyAnalyzerAsync(""" + + public class A + { + [System.Flags] + public enum UnicodeNameΔ + { + M1 = 0, + M2 = 1, + M3 = 2 + + }; + } + """); + + await VerifyVB.VerifyAnalyzerAsync(""" + + Public Class A + < System.Flags > _ + Public Enum UnicodeNameΔ + M1 = 0 + M2 = 1 + M3 = 2 + End Enum + End Class + """); } [Theory, WorkItem(2229, "https://github.com/dotnet/roslyn-analyzers/issues/2229")] @@ -528,29 +588,33 @@ public async Task CA1714_CA1717__Test_EnumWithNoFlags_PluralName_MultipleCulture var currentCulture = CultureInfo.DefaultThreadCurrentCulture; CultureInfo.DefaultThreadCurrentCulture = CultureInfo.GetCultureInfo(culture); - await VerifyCS.VerifyAnalyzerAsync(@" - public class A - { - public enum Days - { - sunday = 0, - Monday = 1, - Tuesday = 2 - - }; - }", + await VerifyCS.VerifyAnalyzerAsync(""" + + public class A + { + public enum Days + { + sunday = 0, + Monday = 1, + Tuesday = 2 + + }; + } + """, GetCSharpNoPluralResultAt(4, 44)); - await VerifyVB.VerifyAnalyzerAsync(@" - Public Class A - Public Enum Days - Sunday = 0 - Monday = 1 - Tuesday = 2 + await VerifyVB.VerifyAnalyzerAsync(""" + + Public Class A + Public Enum Days + Sunday = 0 + Monday = 1 + Tuesday = 2 - End Enum - End Class - ", + End Enum + End Class + + """, GetBasicNoPluralResultAt(3, 38)); CultureInfo.DefaultThreadCurrentCulture = currentCulture; diff --git a/src/RoslynAnalyzers/Text.Analyzers/UnitTests/IdentifiersShouldBeSpelledCorrectlyTests.cs b/src/RoslynAnalyzers/Text.Analyzers/UnitTests/IdentifiersShouldBeSpelledCorrectlyTests.cs index 0160dfd7b191d..73f10827faa0a 100644 --- a/src/RoslynAnalyzers/Text.Analyzers/UnitTests/IdentifiersShouldBeSpelledCorrectlyTests.cs +++ b/src/RoslynAnalyzers/Text.Analyzers/UnitTests/IdentifiersShouldBeSpelledCorrectlyTests.cs @@ -25,34 +25,34 @@ public enum DictionaryType } public static IEnumerable MisspelledMembers - => new[] - { + => + [ new object[] { CreateTypeWithConstructor("Clazz", constructorName: "{|#0:Clazz|}", isStatic: false), "Clazz", "Clazz.Clazz()" }, - new object[] { CreateTypeWithConstructor("Clazz", constructorName: "{|#0:Clazz|}", isStatic: true), "Clazz", "Clazz.Clazz()" }, - new object[] { CreateTypeWithField("Program", "{|#0:_fild|}"), "fild", "Program._fild" }, - new object[] { CreateTypeWithEvent("Program", "{|#0:Evt|}"), "Evt", "Program.Evt" }, - new object[] { CreateTypeWithProperty("Program", "{|#0:Naem|}"), "Naem", "Program.Naem" }, - new object[] { CreateTypeWithMethod("Program", "{|#0:SomeMathod|}"), "Mathod", "Program.SomeMathod()" }, - }; + [CreateTypeWithConstructor("Clazz", constructorName: "{|#0:Clazz|}", isStatic: true), "Clazz", "Clazz.Clazz()"], + [CreateTypeWithField("Program", "{|#0:_fild|}"), "fild", "Program._fild"], + [CreateTypeWithEvent("Program", "{|#0:Evt|}"), "Evt", "Program.Evt"], + [CreateTypeWithProperty("Program", "{|#0:Naem|}"), "Naem", "Program.Naem"], + [CreateTypeWithMethod("Program", "{|#0:SomeMathod|}"), "Mathod", "Program.SomeMathod()"], + ]; public static IEnumerable UnmeaningfulMembers - => new[] - { + => + [ new object[] { CreateTypeWithConstructor("A", constructorName: "{|#0:A|}", isStatic: false), "A" }, - new object[] { CreateTypeWithConstructor("B", constructorName: "{|#0:B|}", isStatic: false), "B" }, - new object[] { CreateTypeWithField("Program", "{|#0:_c|}"), "c" }, - new object[] { CreateTypeWithEvent("Program", "{|#0:D|}"), "D" }, - new object[] { CreateTypeWithProperty("Program", "{|#0:E|}"), "E" }, - new object[] { CreateTypeWithMethod("Program", "{|#0:F|}"), "F" }, - }; + [CreateTypeWithConstructor("B", constructorName: "{|#0:B|}", isStatic: false), "B"], + [CreateTypeWithField("Program", "{|#0:_c|}"), "c"], + [CreateTypeWithEvent("Program", "{|#0:D|}"), "D"], + [CreateTypeWithProperty("Program", "{|#0:E|}"), "E"], + [CreateTypeWithMethod("Program", "{|#0:F|}"), "F"], + ]; public static IEnumerable MisspelledMemberParameters - => new[] - { + => + [ new object[] { CreateTypeWithConstructor("Program", parameter: "int {|#0:yourNaem|}", isStatic: false), "Naem", "yourNaem", "Program.Program(int)" }, - new object[] { CreateTypeWithMethod("Program", "Method", "int {|#0:yourNaem|}"), "Naem", "yourNaem", "Program.Method(int)" }, - new object[] { CreateTypeWithIndexer("Program", "int {|#0:yourNaem|}"), "Naem", "yourNaem", "Program.this[int]" }, - }; + [CreateTypeWithMethod("Program", "Method", "int {|#0:yourNaem|}"), "Naem", "yourNaem", "Program.Method(int)"], + [CreateTypeWithIndexer("Program", "int {|#0:yourNaem|}"), "Naem", "yourNaem", "Program.this[int]"], + ]; [Theory] [InlineData("namespace Bar { }")] @@ -70,39 +70,35 @@ public async Task NoMisspellings_Verify_NoDiagnosticsAsync(string source) [Fact] public async Task MisspellingAllowedByGlobalXmlDictionary_Verify_NoDiagnosticsAsync() { - var source = "class Clazz { }"; - var dictionary = CreateXmlDictionary(new[] { "clazz" }); + var dictionary = CreateXmlDictionary(["clazz"]); - await VerifyCSharpAsync(source, dictionary); + await VerifyCSharpAsync("class Clazz { }", dictionary); } [Fact] public async Task MisspellingAllowedByGlobalDicDictionary_Verify_NoDiagnosticsAsync() { - var source = "class Clazz { }"; - var dictionary = CreateDicDictionary(new[] { "clazz" }); + var dictionary = CreateDicDictionary(["clazz"]); - await VerifyCSharpAsync(source, dictionary); + await VerifyCSharpAsync("class Clazz { }", dictionary); } [Fact] public async Task MisspellingsAllowedByMultipleGlobalDictionaries_Verify_NoDiagnosticsAsync() { - var source = @"class Clazz { const string Naem = ""foo""; }"; - var xmlDictionary = CreateXmlDictionary(new[] { "clazz" }); - var dicDictionary = CreateDicDictionary(new[] { "naem" }); + var xmlDictionary = CreateXmlDictionary(["clazz"]); + var dicDictionary = CreateDicDictionary(["naem"]); - await VerifyCSharpAsync(source, new[] { xmlDictionary, dicDictionary }); + await VerifyCSharpAsync(@"class Clazz { const string Naem = ""foo""; }", [xmlDictionary, dicDictionary]); } [Fact] public async Task CorrectWordDisallowedByGlobalXmlDictionary_Verify_EmitsDiagnosticAsync() { - var source = "class {|#0:Program|} { }"; - var dictionary = CreateXmlDictionary(null, new[] { "program" }); + var dictionary = CreateXmlDictionary(null, ["program"]); await VerifyCSharpAsync( - source, + "class {|#0:Program|} { }", dictionary, VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.TypeRule) .WithLocation(0) @@ -112,17 +108,16 @@ await VerifyCSharpAsync( [Fact] public async Task MisspellingAllowedByProjectDictionary_Verify_NoDiagnosticsAsync() { - var source = "class Clazz {}"; - var dictionary = CreateDicDictionary(new[] { "clazz" }); + var dictionary = CreateDicDictionary(["clazz"]); - await VerifyCSharpAsync(source, dictionary); + await VerifyCSharpAsync("class Clazz {}", dictionary); } [Fact] public async Task MisspellingAllowedByDifferentProjectDictionary_Verify_EmitsDiagnosticAsync() { var source = "class {|#0:Clazz|} {}"; - var dictionary = CreateDicDictionary(new[] { "clazz" }); + var dictionary = CreateDicDictionary(["clazz"]); var test = new VerifyCS.Test { TestState = @@ -211,10 +206,8 @@ static Solution RenameProjectAssembly(Solution solution, ProjectId projectId) [Fact] public async Task NamespaceMisspelled_Verify_EmitsDiagnosticAsync() { - var source = "namespace Tests.{|#0:MyNarmspace|} {}"; - await VerifyCSharpAsync( - source, + "namespace Tests.{|#0:MyNarmspace|} {}", VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.NamespaceRule) .WithLocation(0) .WithArguments("Narmspace", "Tests.MyNarmspace")); @@ -223,10 +216,8 @@ await VerifyCSharpAsync( [Fact] public async Task NamespaceUnmeaningful_Verify_EmitsDiagnosticAsync() { - var source = "namespace Tests.{|#0:A|} {}"; - await VerifyCSharpAsync( - source, + "namespace Tests.{|#0:A|} {}", VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.NamespaceMoreMeaningfulNameRule) .WithLocation(0) .WithArguments("A")); @@ -276,30 +267,29 @@ await VerifyCSharpAsync( [Fact] public async Task MemberOverrideMisspelled_Verify_EmitsDiagnosticOnlyAtDefinitionAsync() { - var source = @" - abstract class Parent - { - protected abstract string {|#0:Naem|} { get; } - - public abstract int {|#1:Mathod|}(); - } + await VerifyCSharpAsync( + """ + abstract class Parent + { + protected abstract string {|#0:Naem|} { get; } - class Child : Parent - { - protected override string Naem => ""child""; + public abstract int {|#1:Mathod|}(); + } - public override int Mathod() => 0; - } + class Child : Parent + { + protected override string Naem => "child"; - class Grandchild : Child - { - protected override string Naem => ""grandchild""; + public override int Mathod() => 0; + } - public override int Mathod() => 1; - }"; + class Grandchild : Child + { + protected override string Naem => "grandchild"; - await VerifyCSharpAsync( - source, + public override int Mathod() => 1; + } + """, VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MemberRule) .WithLocation(0) .WithArguments("Naem", "Parent.Naem"), @@ -322,17 +312,16 @@ await VerifyCSharpAsync( [Fact] public async Task VariableMisspelled_Verify_EmitsDiagnosticAsync() { - var source = @" - class Program - { - public Program() - { - var {|#0:myVoriable|} = 5; - } - }"; - await VerifyCSharpAsync( - source, + """ + class Program + { + public Program() + { + var {|#0:myVoriable|} = 5; + } + } + """, VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.VariableRule) .WithLocation(0) .WithArguments("Voriable", "myVoriable")); @@ -352,18 +341,17 @@ await VerifyCSharpAsync( [Fact] public async Task MemberParameterUnmeaningful_Verify_EmitsDiagnosticAsync() { - var source = @" - class Program - { - public void Method(string {|#0:a|}) - { - } - - public string this[int {|#1:i|}] => null; - }"; - await VerifyCSharpAsync( - source, + """ + class Program + { + public void Method(string {|#0:a|}) + { + } + + public string this[int {|#1:i|}] => null; + } + """, VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MemberParameterMoreMeaningfulNameRule) .WithLocation(0) .WithArguments("Program.Method(string)", "a"), @@ -375,30 +363,29 @@ await VerifyCSharpAsync( [Fact] public async Task MemberParameterMisspelledInterfaceImplementation_Verify_EmitsDiagnosticOnlyAtDefinitionAsync() { - var source = @" - interface IProgram - { - void Method(string {|#0:explaintain|}); - - string this[int {|#1:indxe|}] { get; } - } + await VerifyCSharpAsync( + """ + interface IProgram + { + void Method(string {|#0:explaintain|}); - class Program : IProgram - { - public void Method(string explaintain) - { - } + string this[int {|#1:indxe|}] { get; } + } - public string this[int indxe] => null; + class Program : IProgram + { + public void Method(string explaintain) + { + } - public void Method2(long {|#2:enviromentId|}) - { - } + public string this[int indxe] => null; - }"; + public void Method2(long {|#2:enviromentId|}) + { + } - await VerifyCSharpAsync( - source, + } + """, VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MemberParameterRule) .WithLocation(0) .WithArguments("IProgram.Method(string)", "explaintain", "explaintain"), @@ -413,30 +400,29 @@ await VerifyCSharpAsync( [Fact] public async Task MemberParameterUnmeaningfulInterfaceImplementation_Verify_EmitsDiagnosticOnlyAtDefinitionAsync() { - var source = @" - interface IProgram - { - void Method(string {|#0:a|}); - - string this[int {|#1:i|}] { get; } - } + await VerifyCSharpAsync( + """ + interface IProgram + { + void Method(string {|#0:a|}); - class Program : IProgram - { - public void Method(string a) - { - } + string this[int {|#1:i|}] { get; } + } - public string this[int i] => null; + class Program : IProgram + { + public void Method(string a) + { + } - public void Method2(long {|#2:x|}) - { - } + public string this[int i] => null; - }"; + public void Method2(long {|#2:x|}) + { + } - await VerifyCSharpAsync( - source, + } + """, VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MemberParameterMoreMeaningfulNameRule) .WithLocation(0) .WithArguments("IProgram.Method(string)", "a"), @@ -451,30 +437,29 @@ await VerifyCSharpAsync( [Fact] public async Task MemberParameterUnmeaningfulExplicitInterfaceImplementation_Verify_EmitsDiagnosticOnlyAtDefinitionAsync() { - var source = @" - interface IProgram - { - void Method(string {|#0:a|}); - - string this[int {|#1:i|}] { get; } - } + await VerifyCSharpAsync( + """ + interface IProgram + { + void Method(string {|#0:a|}); - class Program : IProgram - { - void IProgram.Method(string a) - { - } + string this[int {|#1:i|}] { get; } + } - string IProgram.this[int i] => null; + class Program : IProgram + { + void IProgram.Method(string a) + { + } - public void Method2(long {|#2:x|}) - { - } + string IProgram.this[int i] => null; - }"; + public void Method2(long {|#2:x|}) + { + } - await VerifyCSharpAsync( - source, + } + """, VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MemberParameterMoreMeaningfulNameRule) .WithLocation(0) .WithArguments("IProgram.Method(string)", "a"), @@ -489,30 +474,29 @@ await VerifyCSharpAsync( [Fact] public async Task MemberParameterMisspelledExplicitInterfaceImplementation_Verify_EmitsDiagnosticOnlyAtDefinitionAsync() { - var source = @" - interface IProgram - { - void Method(string {|#0:explaintain|}); - - string this[int {|#1:indxe|}] { get; } - } + await VerifyCSharpAsync( + """ + interface IProgram + { + void Method(string {|#0:explaintain|}); - class Program : IProgram - { - void IProgram.Method(string explaintain) - { - } + string this[int {|#1:indxe|}] { get; } + } - string IProgram.this[int indxe] => null; + class Program : IProgram + { + void IProgram.Method(string explaintain) + { + } - public void Method2(long {|#2:enviromentId|}) - { - } + string IProgram.this[int indxe] => null; - }"; + public void Method2(long {|#2:enviromentId|}) + { + } - await VerifyCSharpAsync( - source, + } + """, VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MemberParameterRule) .WithLocation(0) .WithArguments("IProgram.Method(string)", "explaintain", "explaintain"), @@ -527,26 +511,25 @@ await VerifyCSharpAsync( [Fact] public async Task MemberParameterMisspelledOverrideImplementation_Verify_EmitsDiagnosticOnlyAtDefinitionAsync() { - var source = @" - public abstract class Base - { - public abstract void Method(string {|#0:explaintain|}); - } - - public class Derived : Base - { - public override void Method(string explaintain) - { - } + await VerifyCSharpAsync( + """ + public abstract class Base + { + public abstract void Method(string {|#0:explaintain|}); + } - public void Method2(long {|#1:enviromentId|}) - { - } + public class Derived : Base + { + public override void Method(string explaintain) + { + } - }"; + public void Method2(long {|#1:enviromentId|}) + { + } - await VerifyCSharpAsync( - source, + } + """, VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MemberParameterRule) .WithLocation(0) .WithArguments("Base.Method(string)", "explaintain", "explaintain"), @@ -558,52 +541,49 @@ await VerifyCSharpAsync( [Fact] public async Task MemberParameterMisspelledOverrideImplementationWithNameMismatch_Verify_EmitsDiagnosticOnlyAtDefinitionAsync() { - var source = @" - public abstract class Base - { - public abstract void Method(string {|#0:explaintain|}); - public abstract void Method2(string {|#1:inupts|}); - } - - public class Mid : Base - { - public override void Method(string explaintain) - { - } - - public override void Method2(string {|#2:paarmeter|}) - { - } - } + await VerifyCSharpAsync( + """ + public abstract class Base + { + public abstract void Method(string {|#0:explaintain|}); + public abstract void Method2(string {|#1:inupts|}); + } - public class Derived : Mid - { - public override void Method(string explanation) - { - } + public class Mid : Base + { + public override void Method(string explaintain) + { + } - public override void Method2(string {|#3:paarmeterId|}) - { - } + public override void Method2(string {|#2:paarmeter|}) + { + } + } - } + public class Derived : Mid + { + public override void Method(string explanation) + { + } - public class Derived2 : Mid - { - public override void Method(string {|#4:explaintaing|}) - { - } + public override void Method2(string {|#3:paarmeterId|}) + { + } - public override void Method2(string {|#5:strValue|}) - { - } + } - } + public class Derived2 : Mid + { + public override void Method(string {|#4:explaintaing|}) + { + } -"; + public override void Method2(string {|#5:strValue|}) + { + } - await VerifyCSharpAsync( - source, + } + """, VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MemberParameterRule) .WithLocation(0) .WithArguments("Base.Method(string)", "explaintain", "explaintain"), @@ -627,31 +607,28 @@ await VerifyCSharpAsync( [Fact] public async Task MemberParameterMisspelledIndexerOVerrideWithNameMismatch_Verify_EmitsDiagnosticOnlyAtDefinitionAsync() { - var source = @" - public interface IProgram - { - string this[int {|#0:indxe|}] { get; } - } - - public class Program : IProgram - { - public virtual string this[int indxe] => null; - } - - public class DerivedProgram : Program - { - public override string this[int indxe] => null; - } + await VerifyCSharpAsync( + """ + public interface IProgram + { + string this[int {|#0:indxe|}] { get; } + } - public class DerivedProgram2 : Program - { - public override string this[int {|#1:indexe|}] => null; - } + public class Program : IProgram + { + public virtual string this[int indxe] => null; + } -"; + public class DerivedProgram : Program + { + public override string this[int indxe] => null; + } - await VerifyCSharpAsync( - source, + public class DerivedProgram2 : Program + { + public override string this[int {|#1:indexe|}] => null; + } + """, VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MemberParameterRule) .WithLocation(0) .WithArguments("IProgram.this[int]", "indxe", "indxe"), @@ -663,10 +640,8 @@ await VerifyCSharpAsync( [Fact] public async Task DelegateParameterMisspelled_Verify_EmitsDiagnosticAsync() { - var source = "delegate void MyDelegate(string {|#0:firstNaem|});"; - await VerifyCSharpAsync( - source, + "delegate void MyDelegate(string {|#0:firstNaem|});", VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.DelegateParameterRule) .WithLocation(0) .WithArguments("MyDelegate", "Naem", "firstNaem")); @@ -675,10 +650,8 @@ await VerifyCSharpAsync( [Fact] public async Task DelegateParameterUnmeaningful_Verify_EmitsDiagnosticAsync() { - var source = "delegate void MyDelegate(string {|#0:a|});"; - await VerifyCSharpAsync( - source, + "delegate void MyDelegate(string {|#0:a|});", VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.DelegateParameterMoreMeaningfulNameRule) .WithLocation(0) .WithArguments("MyDelegate", "a")); @@ -716,16 +689,15 @@ await VerifyCSharpAsync( [Fact] public async Task MethodTypeParameterMisspelled_Verify_EmitsDiagnosticAsync() { - var source = @" - class Program - { - void Method<{|#0:TTipe|}>(TTipe item) - { - } - }"; - await VerifyCSharpAsync( - source, + """ + class Program + { + void Method<{|#0:TTipe|}>(TTipe item) + { + } + } + """, VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MethodTypeParameterRule) .WithLocation(0) .WithArguments("Program.Method(TTipe)", "Tipe", "TTipe")); @@ -734,16 +706,15 @@ await VerifyCSharpAsync( [Fact] public async Task MethodTypeParameterUnmeaningful_Verify_EmitsDiagnosticAsync() { - var source = @" - class Program - { - void Method<{|#0:TA|}>(TA parameter) - { - } - }"; - await VerifyCSharpAsync( - source, + """ + class Program + { + void Method<{|#0:TA|}>(TA parameter) + { + } + } + """, VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MethodTypeParameterMoreMeaningfulNameRule) .WithLocation(0) .WithArguments("Program.Method(TA)", "TA")); @@ -752,9 +723,7 @@ await VerifyCSharpAsync( [Fact] public async Task MisspellingContainsOnlyCapitalizedLetters_Verify_NoDiagnosticsAsync() { - var source = "class FCCA { }"; - - await VerifyCSharpAsync(source); + await VerifyCSharpAsync("class FCCA { }"); } [Theory] @@ -762,23 +731,23 @@ public async Task MisspellingContainsOnlyCapitalizedLetters_Verify_NoDiagnostics [InlineData("0xDEADBEEF")] public async Task MisspellingStartsWithADigit_Verify_NoDiagnosticsAsync(string misspelling) { - var source = $"enum Name {{ My{misspelling} }}"; - - await VerifyCSharpAsync(source); + await VerifyCSharpAsync($"enum Name {{ My{misspelling} }}"); } [Fact] public async Task MalformedXmlDictionary_Verify_EmitsDiagnosticAsync() { - var contents = @" - - - - okay - bad - - - "; + var contents = """ + + + + + okay + bad + + + + """; var dictionary = ("CodeAnalysisDictionary.xml", contents); await VerifyCSharpAsync( @@ -794,7 +763,7 @@ private Task VerifyCSharpAsync(string source, params DiagnosticResult[] expected => VerifyCSharpAsync(source, Array.Empty<(string Path, string Text)>(), expected); private Task VerifyCSharpAsync(string source, (string Path, string Text) additionalText, params DiagnosticResult[] expected) - => VerifyCSharpAsync(source, new[] { additionalText }, expected); + => VerifyCSharpAsync(source, [additionalText], expected); private async Task VerifyCSharpAsync(string source, (string Path, string Text)[] additionalTexts, params DiagnosticResult[] expected) { @@ -819,15 +788,15 @@ private static (string Path, string Text) CreateXmlDictionary(IEnumerable? recognizedWords, IEnumerable? unrecognizedWords = null) { - var contents = $@" - - - {CreateXml(recognizedWords)} - {CreateXml(unrecognizedWords)} - -"; - - return (filename, contents); + return (filename, $""" + + + + {CreateXml(recognizedWords)} + {CreateXml(unrecognizedWords)} + + + """); static string CreateXml(IEnumerable? words) => string.Join(Environment.NewLine, words?.Select(x => $"{x}") ?? Enumerable.Empty()); @@ -846,13 +815,14 @@ private static string CreateTypeWithConstructor(string typeName, string construc constructorName = typeName; } - return $@" -#pragma warning disable {IdentifiersShouldBeSpelledCorrectlyAnalyzer.RuleId} -class {typeName} -#pragma warning restore {IdentifiersShouldBeSpelledCorrectlyAnalyzer.RuleId} -{{ - {(isStatic ? "static " : string.Empty)}{constructorName}({parameter}) {{ }} -}}"; + return $$""" + #pragma warning disable {{IdentifiersShouldBeSpelledCorrectlyAnalyzer.RuleId}} + class {{typeName}} + #pragma warning restore {{IdentifiersShouldBeSpelledCorrectlyAnalyzer.RuleId}} + { + {{(isStatic ? "static " : string.Empty)}}{{constructorName}}({{parameter}}) { } + } + """; } private static string CreateTypeWithMethod(string typeName, string methodName, string parameter = "") @@ -868,8 +838,10 @@ private static string CreateTypeWithField(string typeName, string fieldName) => $"class {typeName} {{ private string {fieldName}; }}"; private static string CreateTypeWithEvent(string typeName, string eventName) - => $@"using System; + => $$""" + using System; -class {typeName} {{ event EventHandler {eventName}; }}"; + class {{typeName}} { event EventHandler {{eventName}}; } + """; } } diff --git a/src/RoslynAnalyzers/Text.Analyzers/UnitTests/Text.Analyzers.UnitTests.csproj b/src/RoslynAnalyzers/Text.Analyzers/UnitTests/Text.Analyzers.UnitTests.csproj index 11178d278ffce..daf991d74669e 100644 --- a/src/RoslynAnalyzers/Text.Analyzers/UnitTests/Text.Analyzers.UnitTests.csproj +++ b/src/RoslynAnalyzers/Text.Analyzers/UnitTests/Text.Analyzers.UnitTests.csproj @@ -3,15 +3,14 @@ $(NetRoslyn) true - $(MicrosoftCodeAnalysisVersionForTests) - - - - - - + + + + + + diff --git a/src/RoslynAnalyzers/Text.Analyzers/VisualBasic/Text.VisualBasic.Analyzers.vbproj b/src/RoslynAnalyzers/Text.Analyzers/VisualBasic/Text.VisualBasic.Analyzers.vbproj index 564c3fae66b9f..c5a711c22e6a8 100644 --- a/src/RoslynAnalyzers/Text.Analyzers/VisualBasic/Text.VisualBasic.Analyzers.vbproj +++ b/src/RoslynAnalyzers/Text.Analyzers/VisualBasic/Text.VisualBasic.Analyzers.vbproj @@ -2,15 +2,14 @@ netstandard2.0 - $(MicrosoftCodeAnalysisVersionForTextAnalyzers) - - - - + + + + \ No newline at end of file diff --git a/src/RoslynAnalyzers/Tools/GenerateAnalyzerNuspec/Program.cs b/src/RoslynAnalyzers/Tools/GenerateAnalyzerNuspec/Program.cs index 84bf9192516ae..b3b19ee6ba76b 100644 --- a/src/RoslynAnalyzers/Tools/GenerateAnalyzerNuspec/Program.cs +++ b/src/RoslynAnalyzers/Tools/GenerateAnalyzerNuspec/Program.cs @@ -21,13 +21,13 @@ string projectDir = args[2]; string configuration = args[3]; string[] tfms = args[4].Split(';'); -var metadataList = args[5].Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); -var fileList = args[6].Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); +var metadataList = args[5].Split([';'], StringSplitOptions.RemoveEmptyEntries); +var fileList = args[6].Split([';'], StringSplitOptions.RemoveEmptyEntries); var readmeFile = args[7]; -var folderList = args[8].Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); -var assemblyList = args[9].Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); -var dependencyList = args[10].Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); -var libraryList = args[11].Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); +var folderList = args[8].Split([';'], StringSplitOptions.RemoveEmptyEntries); +var assemblyList = args[9].Split([';'], StringSplitOptions.RemoveEmptyEntries); +var dependencyList = args[10].Split([';'], StringSplitOptions.RemoveEmptyEntries); +var libraryList = args[11].Split([';'], StringSplitOptions.RemoveEmptyEntries); var rulesetsDir = args[12]; var editorconfigsDir = args[13]; var artifactsBinDir = args[14]; diff --git a/src/RoslynAnalyzers/Tools/GenerateDocumentationAndConfigFiles/CodeFixerExtensions.cs b/src/RoslynAnalyzers/Tools/GenerateDocumentationAndConfigFiles/CodeFixerExtensions.cs index 1a009aefa24f8..ee0afe0ad0c45 100644 --- a/src/RoslynAnalyzers/Tools/GenerateDocumentationAndConfigFiles/CodeFixerExtensions.cs +++ b/src/RoslynAnalyzers/Tools/GenerateDocumentationAndConfigFiles/CodeFixerExtensions.cs @@ -52,14 +52,16 @@ public static ImmutableArray GetFixers(this AnalyzerFileReferen } } } - catch + catch (Exception ex) { + Console.WriteLine($"Error creating instance of {typeInfo.FullName} in {analyzerFileReference.FullPath}\r\n{ex.Message}\r\n{ex}"); } } } } - catch + catch (Exception ex) { + Console.WriteLine($"Error processing analyzer file reference: {analyzerFileReference.FullPath}\r\n{ex.Message}\r\n{ex}"); } return builder != null ? builder.ToImmutable() : ImmutableArray.Empty; diff --git a/src/RoslynAnalyzers/Tools/GenerateDocumentationAndConfigFiles/GenerateDocumentationAndConfigFiles.csproj b/src/RoslynAnalyzers/Tools/GenerateDocumentationAndConfigFiles/GenerateDocumentationAndConfigFiles.csproj index a5fe77b7c35de..b8953b75143c0 100644 --- a/src/RoslynAnalyzers/Tools/GenerateDocumentationAndConfigFiles/GenerateDocumentationAndConfigFiles.csproj +++ b/src/RoslynAnalyzers/Tools/GenerateDocumentationAndConfigFiles/GenerateDocumentationAndConfigFiles.csproj @@ -5,30 +5,42 @@ true false true - $(MicrosoftCodeAnalysisVersionForExecution) + Microsoft.CodeAnalysis - - - - - - - - - - + + - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + - $(MicrosoftCodeAnalysisVersionForMetrics) 1.1.2 $(MetricsVersionPrefix) + Microsoft.CodeAnalysis - - - - - - - - - + + + + + + + + + @@ -41,4 +41,12 @@ + + + + + + + + diff --git a/src/RoslynAnalyzers/Tools/Metrics/Metrics.csproj b/src/RoslynAnalyzers/Tools/Metrics/Metrics.csproj index 76dd20c75e36a..ff7a519a245ea 100644 --- a/src/RoslynAnalyzers/Tools/Metrics/Metrics.csproj +++ b/src/RoslynAnalyzers/Tools/Metrics/Metrics.csproj @@ -7,24 +7,24 @@ true $(NoWarn);CS0436 - $(MicrosoftCodeAnalysisVersionForMetrics) 1.1.2 $(MetricsVersionPrefix) + Microsoft.CodeAnalysis - - - - - - - - - + + + + + + + + + @@ -35,4 +35,12 @@ + + + + + + + + diff --git a/src/RoslynAnalyzers/Tools/Metrics/Program.cs b/src/RoslynAnalyzers/Tools/Metrics/Program.cs index 2c098b802aaa7..4056dd2379104 100644 --- a/src/RoslynAnalyzers/Tools/Metrics/Program.cs +++ b/src/RoslynAnalyzers/Tools/Metrics/Program.cs @@ -167,25 +167,26 @@ ErrorCode parseArguments() static ErrorCode usage() { - Console.WriteLine(@" -Usage: Metrics.exe + Console.WriteLine(""" + Usage: Metrics.exe -Help for command-line arguments: + Help for command-line arguments: -/project: [Short form: /p:] -Project(s) to analyze. + /project: [Short form: /p:] + Project(s) to analyze. -/solution: [Short form: /s:] -Solution(s) to analyze. + /solution: [Short form: /s:] + Solution(s) to analyze. -/out: [Short form: /o:] -Metrics results XML output file. + /out: [Short form: /o:] + Metrics results XML output file. -/quiet [Short form: /q] -Silence all console output other than error reporting. + /quiet [Short form: /q] + Silence all console output other than error reporting. -/help [Short form: /?] -Display this help message."); + /help [Short form: /?] + Display this help message. + """); return ErrorCode.Usage; } diff --git a/src/RoslynAnalyzers/Tools/RulesetToEditorconfigConverter/Source/RulesetToEditorconfigConverter.csproj b/src/RoslynAnalyzers/Tools/RulesetToEditorconfigConverter/Source/RulesetToEditorconfigConverter.csproj index dfd0bb223b6cf..067aea706a357 100644 --- a/src/RoslynAnalyzers/Tools/RulesetToEditorconfigConverter/Source/RulesetToEditorconfigConverter.csproj +++ b/src/RoslynAnalyzers/Tools/RulesetToEditorconfigConverter/Source/RulesetToEditorconfigConverter.csproj @@ -5,19 +5,32 @@ false true true - $(MicrosoftCodeAnalysisVersionForExecution) - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/RoslynAnalyzers/Tools/RulesetToEditorconfigConverter/Tests/RulesetToEditorconfigConverter.UnitTests.csproj b/src/RoslynAnalyzers/Tools/RulesetToEditorconfigConverter/Tests/RulesetToEditorconfigConverter.UnitTests.csproj index 7c23401c3f2d9..82f9564a7b055 100644 --- a/src/RoslynAnalyzers/Tools/RulesetToEditorconfigConverter/Tests/RulesetToEditorconfigConverter.UnitTests.csproj +++ b/src/RoslynAnalyzers/Tools/RulesetToEditorconfigConverter/Tests/RulesetToEditorconfigConverter.UnitTests.csproj @@ -9,4 +9,12 @@ + + + + + + + + diff --git a/src/RoslynAnalyzers/Tools/RulesetToEditorconfigConverter/Tests/RulesetToEditorconfigConverterTests.cs b/src/RoslynAnalyzers/Tools/RulesetToEditorconfigConverter/Tests/RulesetToEditorconfigConverterTests.cs index 591963e143b59..0a3d7293443b0 100644 --- a/src/RoslynAnalyzers/Tools/RulesetToEditorconfigConverter/Tests/RulesetToEditorconfigConverterTests.cs +++ b/src/RoslynAnalyzers/Tools/RulesetToEditorconfigConverter/Tests/RulesetToEditorconfigConverterTests.cs @@ -49,401 +49,376 @@ private static void Verify(string rulesetText, string expectedEditorconfigText, [Fact] public void RuleSeveritiesPreserved() { - var rulesetText = @" - - - - - - - - - -"; - var editorconfigText = @" -# NOTE: Requires **VS2019 16.3** or later + Verify(""" + + + + + + + + + + + """, """ + # NOTE: Requires **VS2019 16.3** or later -# ConfigurationFileName -# Description: Configuration file description + # ConfigurationFileName + # Description: Configuration file description -# Code files -[*.{cs,vb}] + # Code files + [*.{cs,vb}] -dotnet_diagnostic.CA1000.severity = error + dotnet_diagnostic.CA1000.severity = error -dotnet_diagnostic.CA1001.severity = warning + dotnet_diagnostic.CA1001.severity = warning -dotnet_diagnostic.CA1002.severity = suggestion + dotnet_diagnostic.CA1002.severity = suggestion -dotnet_diagnostic.CA1003.severity = silent + dotnet_diagnostic.CA1003.severity = silent -dotnet_diagnostic.CA1004.severity = none -"; - - Verify(rulesetText, editorconfigText); + dotnet_diagnostic.CA1004.severity = none + """); } [Fact] public void RuleSeveritiesAcrossRulesGroupsPreserved() { - var rulesetText = @" - - - - - - - - -"; - var editorconfigText = @" -# NOTE: Requires **VS2019 16.3** or later - -# ConfigurationFileName -# Description: Configuration file description - -# Code files -[*.{cs,vb}] - - -dotnet_diagnostic.CA1000.severity = error - -dotnet_diagnostic.CA1001.severity = warning -"; - - Verify(rulesetText, editorconfigText); + Verify(""" + + + + + + + + + + """, """ + # NOTE: Requires **VS2019 16.3** or later + + # ConfigurationFileName + # Description: Configuration file description + + # Code files + [*.{cs,vb}] + + + dotnet_diagnostic.CA1000.severity = error + + dotnet_diagnostic.CA1001.severity = warning + """); } [Fact] public void RuleSeverityOverrideAfterIncludePreserved() { - var rulesetText = $@" - - - - - - - -"; - - var includedRulesetText = @" - - - - - -"; - var editorconfigText = @" -# NOTE: Requires **VS2019 16.3** or later - -# ConfigurationFileName -# Description: Configuration file description - -# Code files -[*.{cs,vb}] - - -dotnet_diagnostic.CA1000.severity = warning -"; - - Verify(rulesetText, editorconfigText, includedRulesetText); + Verify($""" + + + + + + + + + """, """ + # NOTE: Requires **VS2019 16.3** or later + + # ConfigurationFileName + # Description: Configuration file description + + # Code files + [*.{cs,vb}] + + + dotnet_diagnostic.CA1000.severity = warning + """, """ + + + + + + + """); } [Fact] public void IncludeAllPreserved() { - var rulesetText = @" - - - - - - - -"; - var editorconfigText = @" -# NOTE: Requires **VS2019 16.3** or later + Verify(""" + + + -# ConfigurationFileName -# Description: Configuration file description + + + + + """, """ + # NOTE: Requires **VS2019 16.3** or later -# Code files -[*.{cs,vb}] + # ConfigurationFileName + # Description: Configuration file description + # Code files + [*.{cs,vb}] -# Default severity for analyzer diagnostics - Requires **VS2019 16.5** or later -dotnet_analyzer_diagnostic.severity = warning -dotnet_diagnostic.CA1000.severity = error -"; + # Default severity for analyzer diagnostics - Requires **VS2019 16.5** or later + dotnet_analyzer_diagnostic.severity = warning - Verify(rulesetText, editorconfigText); + dotnet_diagnostic.CA1000.severity = error + """); } [Fact] public void CommentBeforeRulePreserved() { - var rulesetText = @" - - - - - - -"; - var editorconfigText = @" -# NOTE: Requires **VS2019 16.3** or later - -# ConfigurationFileName -# Description: Configuration file description - -# Code files -[*.{cs,vb}] - - -# Comment before rule -dotnet_diagnostic.CA1000.severity = none -"; - - Verify(rulesetText, editorconfigText); + Verify(""" + + + + + + + + """, """ + # NOTE: Requires **VS2019 16.3** or later + + # ConfigurationFileName + # Description: Configuration file description + + # Code files + [*.{cs,vb}] + + + # Comment before rule + dotnet_diagnostic.CA1000.severity = none + """); } [Fact] public void MultilineCommentBeforeRulePreserved() { - var rulesetText = @" - - - - - - -"; - var editorconfigText = @" -# NOTE: Requires **VS2019 16.3** or later - -# ConfigurationFileName -# Description: Configuration file description - -# Code files -[*.{cs,vb}] - - -# Multiline -# comment -# before -# rule -dotnet_diagnostic.CA1000.severity = none -"; - - Verify(rulesetText, editorconfigText); + Verify(""" + + + + + + + + """, """ + # NOTE: Requires **VS2019 16.3** or later + + # ConfigurationFileName + # Description: Configuration file description + + # Code files + [*.{cs,vb}] + + + # Multiline + # comment + # before + # rule + dotnet_diagnostic.CA1000.severity = none + """); } [Fact] public void MultipleCommentsBeforeRulePreserved() { - var rulesetText = @" - - - - - - - -"; - var editorconfigText = @" -# NOTE: Requires **VS2019 16.3** or later - -# ConfigurationFileName -# Description: Configuration file description - -# Code files -[*.{cs,vb}] - - -# Comment1 before rule -# Comment2 before rule -dotnet_diagnostic.CA1000.severity = none -"; - - Verify(rulesetText, editorconfigText); + Verify(""" + + + + + + + + + """, """ + # NOTE: Requires **VS2019 16.3** or later + + # ConfigurationFileName + # Description: Configuration file description + + # Code files + [*.{cs,vb}] + + + # Comment1 before rule + # Comment2 before rule + dotnet_diagnostic.CA1000.severity = none + """); } [Fact] public void CommentAfterRulePreserved() { - var rulesetText = @" - - - - - -"; - var editorconfigText = @" -# NOTE: Requires **VS2019 16.3** or later - -# ConfigurationFileName -# Description: Configuration file description - -# Code files -[*.{cs,vb}] - - -# Comment after rule -dotnet_diagnostic.CA1000.severity = none -"; - - Verify(rulesetText, editorconfigText); + Verify(""" + + + + + + + """, """ + # NOTE: Requires **VS2019 16.3** or later + + # ConfigurationFileName + # Description: Configuration file description + + # Code files + [*.{cs,vb}] + + + # Comment after rule + dotnet_diagnostic.CA1000.severity = none + """); } [Fact] public void CommentsBeforeAndAfterRulePreserved() { - var rulesetText = @" - - - - - - -"; - var editorconfigText = @" -# NOTE: Requires **VS2019 16.3** or later - -# ConfigurationFileName -# Description: Configuration file description - -# Code files -[*.{cs,vb}] - - -# Comment before rule -# Comment after rule -dotnet_diagnostic.CA1000.severity = none -"; - - Verify(rulesetText, editorconfigText); + Verify(""" + + + + + + + + """, """ + # NOTE: Requires **VS2019 16.3** or later + + # ConfigurationFileName + # Description: Configuration file description + + # Code files + [*.{cs,vb}] + + + # Comment before rule + # Comment after rule + dotnet_diagnostic.CA1000.severity = none + """); } [Fact] public void CommentsFromIncludedRulesetPreserved() { - var rulesetText = $@" - - - -"; - var includedRulesetText = @" - - - - - - -"; - var editorconfigText = @" -# NOTE: Requires **VS2019 16.3** or later - -# ConfigurationFileName -# Description: Configuration file description - -# Code files -[*.{cs,vb}] - - -# Comment before rule -# Comment after rule -dotnet_diagnostic.CA1000.severity = none -"; - - Verify(rulesetText, editorconfigText, includedRulesetText); + Verify($""" + + + + + """, """ + # NOTE: Requires **VS2019 16.3** or later + + # ConfigurationFileName + # Description: Configuration file description + + # Code files + [*.{cs,vb}] + + + # Comment before rule + # Comment after rule + dotnet_diagnostic.CA1000.severity = none + """, """ + + + + + + + + """); } [Fact] public void CommentsFromPrimaryAndIncludedRulesetPreserved() { - var rulesetText = $@" - - - - - - - - -"; - var includedRulesetText = @" - - - - - - -"; - var editorconfigText = @" -# NOTE: Requires **VS2019 16.3** or later - -# ConfigurationFileName -# Description: Configuration file description - -# Code files -[*.{cs,vb}] - - -# Before comment from primary ruleset -# After comment from primary ruleset -dotnet_diagnostic.CA1000.severity = warning - -# Before comment from included ruleset -# After comment from included ruleset -dotnet_diagnostic.CA10001.severity = error -"; - - Verify(rulesetText, editorconfigText, includedRulesetText); + Verify($""" + + + + + + + + + + """, """ + # NOTE: Requires **VS2019 16.3** or later + + # ConfigurationFileName + # Description: Configuration file description + + # Code files + [*.{cs,vb}] + + + # Before comment from primary ruleset + # After comment from primary ruleset + dotnet_diagnostic.CA1000.severity = warning + + # Before comment from included ruleset + # After comment from included ruleset + dotnet_diagnostic.CA10001.severity = error + """, """ + + + + + + + + """); } [Fact] public void CommentsFromOverrideAfterIncludedRulesetPreserved() { - var rulesetText = $@" - - - - - - - - -"; - var includedRulesetText = @" - - - - - - -"; - var editorconfigText = @" -# NOTE: Requires **VS2019 16.3** or later - -# ConfigurationFileName -# Description: Configuration file description - -# Code files -[*.{cs,vb}] - - -# Before comment from primary ruleset -# After comment from primary ruleset -dotnet_diagnostic.CA1000.severity = warning -"; - - Verify(rulesetText, editorconfigText, includedRulesetText); + Verify($""" + + + + + + + + + + """, """ + # NOTE: Requires **VS2019 16.3** or later + + # ConfigurationFileName + # Description: Configuration file description + + # Code files + [*.{cs,vb}] + + + # Before comment from primary ruleset + # After comment from primary ruleset + dotnet_diagnostic.CA1000.severity = warning + """, """ + + + + + + + + """); } } } diff --git a/src/RoslynAnalyzers/Utilities.UnitTests/AdditionalFileProviderTests.cs b/src/RoslynAnalyzers/Utilities.UnitTests/AdditionalFileProviderTests.cs index 8589aeaf4dda4..ac92027fd4955 100644 --- a/src/RoslynAnalyzers/Utilities.UnitTests/AdditionalFileProviderTests.cs +++ b/src/RoslynAnalyzers/Utilities.UnitTests/AdditionalFileProviderTests.cs @@ -21,9 +21,9 @@ namespace Analyzers.Utilities.UnitTests public sealed class AdditionalFileProviderTests { [Theory] - [InlineData(new object[] { new string[] { } })] - [InlineData(new object[] { new string[] { "b.txt" } })] - [InlineData(new object[] { new string[] { "a.bat" } })] + [InlineData([new string[] { }])] + [InlineData([new string[] { "b.txt" }])] + [InlineData([new string[] { "a.bat" }])] public void DesiredFileMissing_GetFile_ReturnsNull(string[] fileNames) { var fileProvider = new AdditionalFileProvider(CreateAdditionalFiles(fileNames)); diff --git a/src/RoslynAnalyzers/Utilities.UnitTests/Analyzer.Utilities.UnitTests.csproj b/src/RoslynAnalyzers/Utilities.UnitTests/Analyzer.Utilities.UnitTests.csproj index 5fe9fadef427e..e59ba7dcea2b9 100644 --- a/src/RoslynAnalyzers/Utilities.UnitTests/Analyzer.Utilities.UnitTests.csproj +++ b/src/RoslynAnalyzers/Utilities.UnitTests/Analyzer.Utilities.UnitTests.csproj @@ -5,15 +5,14 @@ true true true - $(MicrosoftCodeAnalysisVersionForToolsAndUtilities) - - - - - - + + + + + + diff --git a/src/RoslynAnalyzers/Utilities.UnitTests/Extensions/IEnumerableExensionsTests.cs b/src/RoslynAnalyzers/Utilities.UnitTests/Extensions/IEnumerableExensionsTests.cs index 4ad6a5bb0ecba..ca4350321d2a8 100644 --- a/src/RoslynAnalyzers/Utilities.UnitTests/Extensions/IEnumerableExensionsTests.cs +++ b/src/RoslynAnalyzers/Utilities.UnitTests/Extensions/IEnumerableExensionsTests.cs @@ -5,6 +5,8 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Linq; +using Roslyn.Utilities; using Xunit; namespace Analyzer.Utilities.Extensions @@ -140,15 +142,5 @@ private sealed class IntCollection : ICollection public bool Remove(int item) => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); } - - [Fact] - public void Concat_WhenCollectionIsNull_ThrowsDirectly() - { - Assert.Throws(() => - { - IEnumerable collection = null!; - collection.Concat(1); - }); - } } } diff --git a/src/RoslynAnalyzers/Utilities.UnitTests/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisTests.cs b/src/RoslynAnalyzers/Utilities.UnitTests/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisTests.cs index 62a481955ac45..434026e4ce085 100644 --- a/src/RoslynAnalyzers/Utilities.UnitTests/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisTests.cs +++ b/src/RoslynAnalyzers/Utilities.UnitTests/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisTests.cs @@ -61,7 +61,7 @@ private void VerifyCSharp( { expectedResults ??= Array.Empty<(int Line, int Column, string? MethodName, HazardousUsageEvaluationResult Result)>(); - Project project = CreateProject(new string[] { source, TestTypeToTrackSource }); + Project project = CreateProject([source, TestTypeToTrackSource]); Compilation? compilation = project.GetCompilationAsync().Result; Assert.NotNull(compilation); CompilationUtils.ValidateNoCompileErrors(compilation.GetDiagnostics()); @@ -224,7 +224,7 @@ public static void StaticMethod(TestTypeToTrack staticMethodParameter) new PropertyMapperCollection( new PropertyMapper( // Definitely null => unflagged, definitely non-null => flagged, otherwise => maybe. "AString", - (PointsToAbstractValue pointsToAbstractValue) => + pointsToAbstractValue => { return pointsToAbstractValue.NullState switch { @@ -237,7 +237,7 @@ public static void StaticMethod(TestTypeToTrack staticMethodParameter) new HazardousUsageEvaluatorCollection( new HazardousUsageEvaluator( // When TypeToTrack.Method() is invoked, need to evaluate its state. "Method", - (IMethodSymbol methodSymbol, PropertySetAbstractValue abstractValue) => + (methodSymbol, abstractValue) => { // When doing this for reals, need to examine the method to make sure we're looking at the right method and arguments. @@ -253,7 +253,7 @@ public static void StaticMethod(TestTypeToTrack staticMethodParameter) "OtherClass", "OtherMethod", "t", - (IMethodSymbol methodSymbol, PropertySetAbstractValue abstractValue) => + (methodSymbol, abstractValue) => { // When doing this for reals, need to examine the method to make sure we're looking at the right method and arguments. @@ -270,7 +270,7 @@ public static void StaticMethod(TestTypeToTrack staticMethodParameter) "OtherClass", "StaticMethod", "staticMethodParameter", - (IMethodSymbol methodSymbol, PropertySetAbstractValue abstractValue) => + (methodSymbol, abstractValue) => { // When doing this for reals, need to examine the method to make sure we're looking at the right method and arguments. @@ -399,7 +399,7 @@ void TestMethod() new( "TestTypeToTrackWithConstructor", new ConstructorMapper( - (IMethodSymbol method, IReadOnlyList argumentPointsToAbstractValues) => + (method, argumentPointsToAbstractValues) => { // When doing this for reals, need to examine the method to make sure we're looking at the right method and arguments. PropertySetAbstractValueKind kind = PropertySetAbstractValueKind.Unknown; @@ -420,7 +420,7 @@ void TestMethod() new PropertyMapperCollection( new PropertyMapper( // Definitely null => unflagged, definitely non-null => flagged, otherwise => maybe. "AString", - (PointsToAbstractValue pointsToAbstractValue) => + pointsToAbstractValue => { return pointsToAbstractValue.NullState switch { @@ -433,7 +433,7 @@ void TestMethod() new HazardousUsageEvaluatorCollection( new HazardousUsageEvaluator( "Method", - (IMethodSymbol methodSymbol, PropertySetAbstractValue abstractValue) => + (methodSymbol, abstractValue) => { // When doing this for reals, need to examine the method to make sure we're looking at the right method and arguments. @@ -525,14 +525,14 @@ void TestMethod() new PropertyMapperCollection( new PropertyMapper( "AnEnum", - (ValueContentAbstractValue valueContentAbstractValue) => + valueContentAbstractValue => { return PropertySetCallbacks.EvaluateLiteralValues(valueContentAbstractValue, v => v is not null && v.Equals(0)); })), new HazardousUsageEvaluatorCollection( new HazardousUsageEvaluator( // When TypeToTrack.Method() is invoked, need to evaluate its state. "Method", - (IMethodSymbol methodSymbol, PropertySetAbstractValue abstractValue) => + (methodSymbol, abstractValue) => { // When doing this for reals, need to examine the method to make sure we're looking at the right method and arguments. @@ -586,7 +586,7 @@ void TestMethod() new( "TestTypeToTrackWithConstructor", new ConstructorMapper( - (IMethodSymbol method, IReadOnlyList argumentValueContentAbstractValues, IReadOnlyList argumentPointsToAbstractValues) => + (method, argumentValueContentAbstractValues, argumentPointsToAbstractValues) => { // When doing this for reals, need to examine the method to make sure we're looking at the right method and arguments. @@ -598,14 +598,14 @@ void TestMethod() new PropertyMapperCollection( new PropertyMapper( "AnEnum", - (ValueContentAbstractValue valueContentAbstractValue) => + valueContentAbstractValue => { return PropertySetCallbacks.EvaluateLiteralValues(valueContentAbstractValue, v => v is not null && v.Equals(0)); })), new HazardousUsageEvaluatorCollection( new HazardousUsageEvaluator( // When TypeToTrack.Method() is invoked, need to evaluate its state. "Method", - (IMethodSymbol methodSymbol, PropertySetAbstractValue abstractValue) => + (methodSymbol, abstractValue) => { // When doing this for reals, need to examine the method to make sure we're looking at the right method and arguments. @@ -663,7 +663,7 @@ void TestMethod() new PropertyMapperCollection( new PropertyMapper( "AString", - (ValueContentAbstractValue valueContentAbstractValue) => + valueContentAbstractValue => { return PropertySetCallbacks.EvaluateLiteralValues( valueContentAbstractValue, @@ -671,14 +671,14 @@ void TestMethod() }), new PropertyMapper( "AnEnum", - (ValueContentAbstractValue valueContentAbstractValue) => + valueContentAbstractValue => { return PropertySetCallbacks.EvaluateLiteralValues(valueContentAbstractValue, v => v is not null && v.Equals(2)); })), new HazardousUsageEvaluatorCollection( new HazardousUsageEvaluator( "Method", - (IMethodSymbol methodSymbol, PropertySetAbstractValue abstractValue) => + (methodSymbol, abstractValue) => { // When doing this for reals, need to examine the method to make sure we're looking at the right method and arguments. @@ -823,7 +823,7 @@ void TestMethod() new( "TestTypeToTrackWithConstructor", new ConstructorMapper( - (IMethodSymbol constructorMethodSymbol, IReadOnlyList argumentPointsToAbstractValues) => + (constructorMethodSymbol, argumentPointsToAbstractValues) => { // When doing this for reals, need to examine the method to make sure we're looking at the right method and arguments. @@ -845,7 +845,7 @@ void TestMethod() new PropertyMapperCollection( new PropertyMapper( "AnObject", - (PointsToAbstractValue pointsToAbstractValue) => + pointsToAbstractValue => { // Better to compare LocationTypeOpt to INamedTypeSymbol, but for this demonstration, just using MetadataName. PropertySetAbstractValueKind kind; @@ -865,7 +865,7 @@ void TestMethod() new HazardousUsageEvaluatorCollection( new HazardousUsageEvaluator( // When TypeToTrack.Method() is invoked, need to evaluate its state. "Method", - (IMethodSymbol methodSymbol, PropertySetAbstractValue abstractValue) => + (methodSymbol, abstractValue) => { // When doing this for reals, need to examine the method to make sure we're looking at the right method and arguments. @@ -946,9 +946,9 @@ void TestMethod() new( "TestTypeToTrackWithConstructor", new ConstructorMapper( - (IMethodSymbol constructorMethodSymbol, - IReadOnlyList argumentValueContentAbstractValues, - IReadOnlyList argumentPointsToAbstractValues) => + (constructorMethodSymbol, + argumentValueContentAbstractValues, + argumentPointsToAbstractValues) => { // When doing this for reals, need to examine the method to make sure we're looking at the right method and arguments. @@ -960,7 +960,7 @@ void TestMethod() new PropertyMapperCollection( new PropertyMapper( "AString", - (ValueContentAbstractValue valueContentAbstractValue) => + valueContentAbstractValue => { return PropertySetCallbacks.EvaluateLiteralValues( valueContentAbstractValue, @@ -969,7 +969,7 @@ void TestMethod() new HazardousUsageEvaluatorCollection( new HazardousUsageEvaluator( // When TypeToTrackWithConstructor.Method() is invoked, need to evaluate its state. "Method", - (IMethodSymbol methodSymbol, PropertySetAbstractValue abstractValue) => + (methodSymbol, abstractValue) => { // When doing this for reals, need to examine the method to make sure we're looking at the right method and arguments. @@ -1038,7 +1038,7 @@ TestTypeToTrackWithConstructor GetTestType() new PropertyMapperCollection( new PropertyMapper( // Definitely null => unflagged, definitely non-null => flagged, otherwise => maybe. "AString", - (PointsToAbstractValue pointsToAbstractValue) => + pointsToAbstractValue => { return pointsToAbstractValue.NullState switch { @@ -1051,7 +1051,7 @@ TestTypeToTrackWithConstructor GetTestType() new HazardousUsageEvaluatorCollection( new HazardousUsageEvaluator( HazardousUsageEvaluatorKind.Return, - (PropertySetAbstractValue abstractValue) => + abstractValue => { // With only one property being tracked, this is straightforward. return abstractValue[0] switch @@ -1142,7 +1142,7 @@ object TestMethod() new PropertyMapperCollection( new PropertyMapper( // Definitely null => unflagged, definitely non-null => flagged, otherwise => maybe. "AString", - (PointsToAbstractValue pointsToAbstractValue) => + pointsToAbstractValue => { return pointsToAbstractValue.NullState switch { @@ -1155,7 +1155,7 @@ object TestMethod() propertyIndex: 0), // Both AString and AnObject point to index 0. new PropertyMapper( // Definitely null => unflagged, definitely non-null => flagged, otherwise => maybe. "AnObject", - (PointsToAbstractValue pointsToAbstractValue) => + pointsToAbstractValue => { return pointsToAbstractValue.NullState switch { @@ -1169,7 +1169,7 @@ object TestMethod() new HazardousUsageEvaluatorCollection( new HazardousUsageEvaluator( // When TypeToTrack.Method() is invoked, need to evaluate its state. "Method", - (IMethodSymbol methodSymbol, PropertySetAbstractValue abstractValue) => + (methodSymbol, abstractValue) => { // When doing this for reals, need to examine the method to make sure we're looking at the right method and arguments. diff --git a/src/RoslynAnalyzers/Utilities.UnitTests/Lightup/LightupHelpersTests.cs b/src/RoslynAnalyzers/Utilities.UnitTests/Lightup/LightupHelpersTests.cs index a8869bb4a1a50..b3ccb2276251f 100644 --- a/src/RoslynAnalyzers/Utilities.UnitTests/Lightup/LightupHelpersTests.cs +++ b/src/RoslynAnalyzers/Utilities.UnitTests/Lightup/LightupHelpersTests.cs @@ -121,12 +121,17 @@ private sealed class EmptySymbol : ISymbol ISymbol ISymbol.OriginalDefinition => throw new NotImplementedException(); bool ISymbol.HasUnsupportedMetadata => throw new NotImplementedException(); + int ISymbol.MetadataToken => throw new NotImplementedException(); + void ISymbol.Accept(SymbolVisitor visitor) => throw new NotImplementedException(); TResult ISymbol.Accept(SymbolVisitor visitor) => throw new NotImplementedException(); + TResult ISymbol.Accept(SymbolVisitor visitor, TArgument argument) + => throw new NotImplementedException(); + public bool Equals(ISymbol? other) => throw new NotImplementedException(); diff --git a/src/RoslynAnalyzers/Utilities.UnitTests/Options/SymbolNamesWithValueOptionTests.cs b/src/RoslynAnalyzers/Utilities.UnitTests/Options/SymbolNamesWithValueOptionTests.cs index c47da354f3319..ec88314b01076 100644 --- a/src/RoslynAnalyzers/Utilities.UnitTests/Options/SymbolNamesWithValueOptionTests.cs +++ b/src/RoslynAnalyzers/Utilities.UnitTests/Options/SymbolNamesWithValueOptionTests.cs @@ -71,19 +71,20 @@ public void UnqualifiedSymbolNamesAreProcessedAsNames() public void QualifiedSymbolNamesWithoutPrefixAreIgnored() { // Arrange - var compilation = GetCompilation(@" -using System; + var compilation = GetCompilation(""" + using System; -public namespace MyNamespace -{ - public class MyClass - { - public int MyField; - public int MyProperty { get; set; } - public event EventHandler MyEvent; - public void MyMethod() {} - } -}"); + public namespace MyNamespace + { + public class MyClass + { + public int MyField; + public int MyProperty { get; set; } + public event EventHandler MyEvent; + public void MyMethod() {} + } + } + """); var symbolNames = ImmutableArray.Create( "MyNamespace.MySubNamespace", "MyNamespace.MyClass", @@ -105,19 +106,20 @@ public void MyMethod() {} public void QualifiedSymbolNamesWithPrefixAreProcessedAsSymbols() { // Arrange - var compilation = GetCompilation(@" -using System; + var compilation = GetCompilation(""" + using System; -public namespace MyNamespace -{ - public class MyClass - { - public int MyField; - public int MyProperty { get; set; } - public event EventHandler MyEvent; - public void MyMethod() {} - } -}"); + public namespace MyNamespace + { + public class MyClass + { + public int MyField; + public int MyProperty { get; set; } + public event EventHandler MyEvent; + public void MyMethod() {} + } + } + """); var symbolNames = ImmutableArray.Create( "N:MyNamespace", "T:MyNamespace.MyClass", @@ -238,13 +240,14 @@ public void WildcardConstructionsWithPrefixAreCorrectlyClassified() public void ValueCanBeAssociatedWithAllSymbolNames() { // Arrange - var compilation = GetCompilation(@" -using System; + var compilation = GetCompilation(""" + using System; -public namespace MyNamespace -{ - public class MyClass {} -}"); + public namespace MyNamespace + { + public class MyClass {} + } + """); var symbolNames = ImmutableArray.Create( "MyClass->SomeValue1", "T:MyNamespace.MyClass->SomeValue2", @@ -257,7 +260,7 @@ public class MyClass {} var options = SymbolNamesWithValueOption.Create(symbolNames, compilation, null, getSymbolNamePartsFunc: symbolName => { - var split = symbolName.Split(new[] { "->" }, StringSplitOptions.RemoveEmptyEntries); + var split = symbolName.Split(["->"], StringSplitOptions.RemoveEmptyEntries); return new SymbolNamesWithValueOption.NameParts(split[0], split[1]); }); @@ -277,13 +280,14 @@ public class MyClass {} [WorkItem(1242125, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1242125")] public void FastPathDoesNotCache() { - var compilation = GetCompilation(@" -using System; + var compilation = GetCompilation(""" + using System; -public namespace MyNamespace -{ - public class MyClass {} -}"); + public namespace MyNamespace + { + public class MyClass {} + } + """); var namedTypeSymbol = (INamedTypeSymbol)compilation.GetSymbolsWithName("MyClass").Single(); @@ -335,33 +339,34 @@ public class MyClass {} public void WildcardMatch(string patternName, string symbolName) { // Arrange - var compilation = GetCompilation(@" -public namespace MyCompany.MyProduct.MyFeature -{ - public class MyOuterClass - { - public class MyInnerClass - { - public int MyField; - public MyInnerClass() {} - public MyInnerClass(int i) {} - public int MyProperty { get; set; } - public int this[] - { - get { return 42; } - set {} - } - public int this[string s] - { - get { return 42; } - set {} - } - public event EventHandler MyEvent; - public void MyMethod() {} - public void MyMethod2(string s) {} - } - } -}"); + var compilation = GetCompilation(""" + public namespace MyCompany.MyProduct.MyFeature + { + public class MyOuterClass + { + public class MyInnerClass + { + public int MyField; + public MyInnerClass() {} + public MyInnerClass(int i) {} + public int MyProperty { get; set; } + public int this[] + { + get { return 42; } + set {} + } + public int this[string s] + { + get { return 42; } + set {} + } + public event EventHandler MyEvent; + public void MyMethod() {} + public void MyMethod2(string s) {} + } + } + } + """); var symbolNames = ImmutableArray.Create(patternName); var symbol = FindSymbol(compilation, symbolName); var options = SymbolNamesWithValueOption.Create(symbolNames, compilation, null, static name => new SymbolNamesWithValueOption.NameParts(name, Unit.Default)); diff --git a/src/RoslynAnalyzers/Utilities/Compiler/Analyzer.Utilities.projitems b/src/RoslynAnalyzers/Utilities/Compiler/Analyzer.Utilities.projitems index fe0da97cb9fcb..99a63cd21578e 100644 --- a/src/RoslynAnalyzers/Utilities/Compiler/Analyzer.Utilities.projitems +++ b/src/RoslynAnalyzers/Utilities/Compiler/Analyzer.Utilities.projitems @@ -8,13 +8,13 @@ Analyzer.Utilities - + $(DefineConstants),CODEANALYSIS_V3_OR_BETTER - + $(DefineConstants),CODEANALYSIS_V3_7_OR_BETTER - + $(DefineConstants);HAS_IOPERATION true - /// - /// - public class Program - { - public static void Main(string[] args) + await TestServices.Editor.SetTextAsync(""" + using System; + using System.Collections.Generic; + using System.Text; + namespace ConsoleApplication1 { - Console.WriteLine(""Hello World""); - } - } - }", HangMitigatingCancellationToken); + /// innertext + /// + /// + /// + /// + public class Program + { + public static void Main(string[] args) + { + Console.WriteLine("Hello World"); + } + } + } + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("class", charsOffset: 0, HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentTokenTypeAsync(tokenType: "keyword", HangMitigatingCancellationToken); @@ -73,17 +75,19 @@ public static void Main(string[] args) [IdeFact, Trait(Traits.Editor, Traits.Editors.LanguageServerProtocol)] public async Task SemanticClassification() { - await TestServices.Editor.SetTextAsync(@" -using System; -using System.Collections.Generic; -class Program : Attribute -{ - static void Main(string[] args) - { - List list = new List(); - Program.Main(null); - } -}", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + + using System; + using System.Collections.Generic; + class Program : Attribute + { + static void Main(string[] args) + { + List list = new List(); + Program.Main(null); + } + } + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("Attribute", charsOffset: 0, HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentTokenTypeAsync(tokenType: "class name", HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("list", charsOffset: 8, HangMitigatingCancellationToken); @@ -108,23 +112,25 @@ static void Main(string[] args) [IdeFact] public async Task VerifyProjectConfigChange() { - await TestServices.Editor.SetTextAsync(@" -namespace ClassLibrary1 -{ - public class Class1 - { -#if DEBUG - void Goo() - { - } -#else - void Bar() - { - } -#endif - } -} -", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + + namespace ClassLibrary1 + { + public class Class1 + { + #if DEBUG + void Goo() + { + } + #else + void Bar() + { + } + #endif + } + } + + """, HangMitigatingCancellationToken); await TestServices.Shell.ExecuteCommandAsync(VSConstants.VSStd97CmdID.SolutionCfg, argument: "Debug", HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("Goo", charsOffset: 0, HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpCodeActions.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpCodeActions.cs index e7ea9428208d1..85c6f6f591d45 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpCodeActions.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpCodeActions.cs @@ -331,24 +331,7 @@ public int Y2 [WorkItem("https://github.com/dotnet/roslyn/issues/74761")] public async Task FixAllOccurrencesIgnoresGeneratedCode(FixAllScope scope) { - var markup = """ - using System; - using $$System.Threading; - - class C - { - public IntPtr X1 { get; set; } - } - """; - var expectedText = """ - using System; - - class C - { - public IntPtr X1 { get; set; } - } - """; - var generatedSourceMarkup = """ + MarkupTestFile.GetPosition(""" // using System; using $$System.Threading; @@ -357,9 +340,7 @@ class D { public IntPtr X1 { get; set; } } - """; - - MarkupTestFile.GetPosition(generatedSourceMarkup, out var generatedSource, out int generatedSourcePosition); + """, out var generatedSource, out int generatedSourcePosition); await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "D.cs", generatedSource, open: false, HangMitigatingCancellationToken); @@ -368,7 +349,15 @@ class D // Verify that applying a Fix All operation does not change generated files. // This is a regression test for correctness with respect to the design. - await SetUpEditorAsync(markup, HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + using System; + using $$System.Threading; + + class C + { + public IntPtr X1 { get; set; } + } + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync( "Remove unnecessary usings", @@ -376,7 +365,14 @@ await TestServices.EditorVerifier.CodeActionAsync( fixAllScope: scope, cancellationToken: HangMitigatingCancellationToken); - AssertEx.EqualOrDiff(expectedText, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); + AssertEx.EqualOrDiff(""" + using System; + + class C + { + public IntPtr X1 { get; set; } + } + """, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, "D.cs", HangMitigatingCancellationToken); AssertEx.EqualOrDiff(generatedSource, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); @@ -780,7 +776,7 @@ static async Task VerifyDiagnosticInErrorListAsync(string expectedSeverity, Test [WorkItem("https://github.com/dotnet/roslyn/issues/46784")] public async Task ConfigureSeverityWithManualEditsToEditorconfig() { - var markup = """ + await SetUpEditorAsync(""" class C { public static void Main() @@ -789,8 +785,7 @@ public static void Main() int $$x; } } - """; - await SetUpEditorAsync(markup, HangMitigatingCancellationToken); + """, HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAllAsyncOperationsAsync( [ @@ -864,19 +859,9 @@ static async Task VerifyDiagnosticInErrorListAsync(string expectedSeverity, Test [InlineData(BackgroundAnalysisScope.FullSolution, CompilerDiagnosticsScope.FullSolution)] internal async Task ConfigureSeverityWithManualEditsToEditorconfig_CurrentDocumentScope(BackgroundAnalysisScope analyzerScope, CompilerDiagnosticsScope compilerScope) { - var markup1 = """ - class C - { - public static void Main() - { - // CS0219: The variable 'x' is assigned but its value is never used - // IDE0059: Unnecessary assignment of a value to 'x' - int x = 0; - } - } - """; + await TestServices.Workspace.SetBackgroundAnalysisOptionsAsync(analyzerScope, compilerScope, HangMitigatingCancellationToken); - var markup2 = """ + await SetUpEditorAsync(""" class C2 { public static void M() @@ -886,10 +871,7 @@ public static void M() int $$y = 0; } } - """; - await TestServices.Workspace.SetBackgroundAnalysisOptionsAsync(analyzerScope, compilerScope, HangMitigatingCancellationToken); - - await SetUpEditorAsync(markup2, HangMitigatingCancellationToken); + """, HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAllAsyncOperationsAsync( [ @@ -900,7 +882,17 @@ await TestServices.Workspace.WaitForAllAsyncOperationsAsync( ], HangMitigatingCancellationToken); - await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "Class2.cs", markup1, open: true, cancellationToken: HangMitigatingCancellationToken); + await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "Class2.cs", """ + class C + { + public static void Main() + { + // CS0219: The variable 'x' is assigned but its value is never used + // IDE0059: Unnecessary assignment of a value to 'x' + int x = 0; + } + } + """, open: true, cancellationToken: HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAllAsyncOperationsAsync( [ @@ -1018,7 +1010,28 @@ void OtherMethod() } } """; - var expectedText = """ + await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, "Class1.cs", HangMitigatingCancellationToken); + + MarkupTestFile.GetSpans(markup, out _, out var _); + await SetUpEditorAsync(markup, HangMitigatingCancellationToken); + await TestServices.Workspace.WaitForAllAsyncOperationsAsync( + [ + FeatureAttribute.Workspace, + FeatureAttribute.SolutionCrawlerLegacy, + FeatureAttribute.DiagnosticService, + FeatureAttribute.ErrorSquiggles + ], + HangMitigatingCancellationToken); + + await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); + + await TestServices.EditorVerifier.CodeActionAsync( + "Add braces", + applyFix: true, + fixAllScope: FixAllScope.ContainingMember, + cancellationToken: HangMitigatingCancellationToken); + + AssertEx.EqualOrDiff(""" class Program1 { static void Main() @@ -1053,30 +1066,7 @@ void OtherMethod() if (true) if (true) return; } } - """; - - await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, "Class1.cs", HangMitigatingCancellationToken); - - MarkupTestFile.GetSpans(markup, out _, out var _); - await SetUpEditorAsync(markup, HangMitigatingCancellationToken); - await TestServices.Workspace.WaitForAllAsyncOperationsAsync( - [ - FeatureAttribute.Workspace, - FeatureAttribute.SolutionCrawlerLegacy, - FeatureAttribute.DiagnosticService, - FeatureAttribute.ErrorSquiggles - ], - HangMitigatingCancellationToken); - - await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); - - await TestServices.EditorVerifier.CodeActionAsync( - "Add braces", - applyFix: true, - fixAllScope: FixAllScope.ContainingMember, - cancellationToken: HangMitigatingCancellationToken); - - AssertEx.EqualOrDiff(expectedText, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); + """, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); } [IdeFact] @@ -1115,7 +1105,47 @@ void M2() } } """; - var expectedText1 = """ + await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "Class2.cs", """ + partial class Program1 + { + void OtherFileMethod() + { + if (true) if (true) return; + + if (false) if (false) return; + } + } + + class OtherType2 + { + void OtherMethod() + { + if (true) if (true) return; + } + } + """, cancellationToken: HangMitigatingCancellationToken); + await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, "Class1.cs", HangMitigatingCancellationToken); + + MarkupTestFile.GetSpans(markup1, out _, out var _); + await SetUpEditorAsync(markup1, HangMitigatingCancellationToken); + await TestServices.Workspace.WaitForAllAsyncOperationsAsync( + [ + FeatureAttribute.Workspace, + FeatureAttribute.SolutionCrawlerLegacy, + FeatureAttribute.DiagnosticService, + FeatureAttribute.ErrorSquiggles + ], + HangMitigatingCancellationToken); + + await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); + + await TestServices.EditorVerifier.CodeActionAsync( + "Add braces", + applyFix: true, + fixAllScope: FixAllScope.ContainingType, + cancellationToken: HangMitigatingCancellationToken); + + AssertEx.EqualOrDiff(""" partial class Program1 { static void Main() @@ -1170,28 +1200,9 @@ void M2() } } } - """; + """, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); - var markup2 = """ - partial class Program1 - { - void OtherFileMethod() - { - if (true) if (true) return; - - if (false) if (false) return; - } - } - - class OtherType2 - { - void OtherMethod() - { - if (true) if (true) return; - } - } - """; - var expectedText2 = """ + AssertEx.EqualOrDiff(""" partial class Program1 { void OtherFileMethod() @@ -1221,33 +1232,7 @@ void OtherMethod() if (true) if (true) return; } } - """; - - await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "Class2.cs", markup2, cancellationToken: HangMitigatingCancellationToken); - await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, "Class1.cs", HangMitigatingCancellationToken); - - MarkupTestFile.GetSpans(markup1, out _, out var _); - await SetUpEditorAsync(markup1, HangMitigatingCancellationToken); - await TestServices.Workspace.WaitForAllAsyncOperationsAsync( - [ - FeatureAttribute.Workspace, - FeatureAttribute.SolutionCrawlerLegacy, - FeatureAttribute.DiagnosticService, - FeatureAttribute.ErrorSquiggles - ], - HangMitigatingCancellationToken); - - await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); - - await TestServices.EditorVerifier.CodeActionAsync( - "Add braces", - applyFix: true, - fixAllScope: FixAllScope.ContainingType, - cancellationToken: HangMitigatingCancellationToken); - - AssertEx.EqualOrDiff(expectedText1, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); - - AssertEx.EqualOrDiff(expectedText2, await TestServices.SolutionExplorer.GetFileContentsAsync(ProjectName, "Class2.cs", HangMitigatingCancellationToken)); + """, await TestServices.SolutionExplorer.GetFileContentsAsync(ProjectName, "Class2.cs", HangMitigatingCancellationToken)); } [IdeFact] @@ -1279,7 +1264,28 @@ void M3() } } """; - var expectedText = """" + await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, "Class1.cs", HangMitigatingCancellationToken); + + MarkupTestFile.GetSpans(markup, out _, out var _); + await SetUpEditorAsync(markup, HangMitigatingCancellationToken); + await TestServices.Workspace.WaitForAllAsyncOperationsAsync( + [ + FeatureAttribute.Workspace, + FeatureAttribute.SolutionCrawlerLegacy, + FeatureAttribute.DiagnosticService, + FeatureAttribute.ErrorSquiggles + ], + HangMitigatingCancellationToken); + + await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); + + await TestServices.EditorVerifier.CodeActionAsync( + "Convert to raw string", + applyFix: true, + fixAllScope: FixAllScope.ContainingMember, + cancellationToken: HangMitigatingCancellationToken); + + AssertEx.EqualOrDiff("""" class C1 { void M() @@ -1303,30 +1309,7 @@ void M3() var singleLine2 = @"goo""bar"; } } - """"; - - await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, "Class1.cs", HangMitigatingCancellationToken); - - MarkupTestFile.GetSpans(markup, out _, out var _); - await SetUpEditorAsync(markup, HangMitigatingCancellationToken); - await TestServices.Workspace.WaitForAllAsyncOperationsAsync( - [ - FeatureAttribute.Workspace, - FeatureAttribute.SolutionCrawlerLegacy, - FeatureAttribute.DiagnosticService, - FeatureAttribute.ErrorSquiggles - ], - HangMitigatingCancellationToken); - - await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); - - await TestServices.EditorVerifier.CodeActionAsync( - "Convert to raw string", - applyFix: true, - fixAllScope: FixAllScope.ContainingMember, - cancellationToken: HangMitigatingCancellationToken); - - AssertEx.EqualOrDiff(expectedText, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); + """", await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); } [IdeFact] @@ -1367,61 +1350,82 @@ void M4() } } """; - var expectedText1 = """" + await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "Class2.cs", """ partial class C1 { - void M() - { - var singleLine1 = """a"""; - var singleLine2 = """goo"bar"""; - } - - void M2() + void M5() { - var singleLine1 = """a"""; - var singleLine2 = """goo"bar"""; + var singleLine1 = "a"; + var singleLine2 = @"goo""bar"; } } class C2 { - void M3() + void M6() { var singleLine1 = "a"; var singleLine2 = @"goo""bar"; } } + """, cancellationToken: HangMitigatingCancellationToken); + await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, "Class1.cs", HangMitigatingCancellationToken); + MarkupTestFile.GetSpans(markup1, out _, out var _); + await SetUpEditorAsync(markup1, HangMitigatingCancellationToken); + await TestServices.Workspace.WaitForAllAsyncOperationsAsync( + [ + FeatureAttribute.Workspace, + FeatureAttribute.SolutionCrawlerLegacy, + FeatureAttribute.DiagnosticService, + FeatureAttribute.ErrorSquiggles + ], + HangMitigatingCancellationToken); + + await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); + + await TestServices.EditorVerifier.CodeActionAsync( + "Convert to raw string", + applyFix: true, + fixAllScope: FixAllScope.ContainingType, + cancellationToken: HangMitigatingCancellationToken); + + AssertEx.EqualOrDiff("""" partial class C1 { - void M4() + void M() + { + var singleLine1 = """a"""; + var singleLine2 = """goo"bar"""; + } + + void M2() { var singleLine1 = """a"""; var singleLine2 = """goo"bar"""; } } - """"; - var markup2 = """ - partial class C1 + class C2 { - void M5() + void M3() { var singleLine1 = "a"; var singleLine2 = @"goo""bar"; } } - class C2 + partial class C1 { - void M6() + void M4() { - var singleLine1 = "a"; - var singleLine2 = @"goo""bar"; + var singleLine1 = """a"""; + var singleLine2 = """goo"bar"""; } } - """; - var expectedText2 = """" + """", await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); + + AssertEx.EqualOrDiff("""" partial class C1 { void M5() @@ -1439,33 +1443,7 @@ void M6() var singleLine2 = @"goo""bar"; } } - """"; - - await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "Class2.cs", markup2, cancellationToken: HangMitigatingCancellationToken); - await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, "Class1.cs", HangMitigatingCancellationToken); - - MarkupTestFile.GetSpans(markup1, out _, out var _); - await SetUpEditorAsync(markup1, HangMitigatingCancellationToken); - await TestServices.Workspace.WaitForAllAsyncOperationsAsync( - [ - FeatureAttribute.Workspace, - FeatureAttribute.SolutionCrawlerLegacy, - FeatureAttribute.DiagnosticService, - FeatureAttribute.ErrorSquiggles - ], - HangMitigatingCancellationToken); - - await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); - - await TestServices.EditorVerifier.CodeActionAsync( - "Convert to raw string", - applyFix: true, - fixAllScope: FixAllScope.ContainingType, - cancellationToken: HangMitigatingCancellationToken); - - AssertEx.EqualOrDiff(expectedText1, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); - - AssertEx.EqualOrDiff(expectedText2, await TestServices.SolutionExplorer.GetFileContentsAsync(ProjectName, "Class2.cs", HangMitigatingCancellationToken)); + """", await TestServices.SolutionExplorer.GetFileContentsAsync(ProjectName, "Class2.cs", HangMitigatingCancellationToken)); } [IdeFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)] @@ -1513,11 +1491,6 @@ await TestServices.Workspace.WaitForAllAsyncOperationsAsync( public async Task TestNonSourceDocumentRefactoring() { var markup = @"$$# Editorconfig File"; - var expectedText = """ - # Editorconfig File - # Refactored - """; - await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, "Class1.cs", HangMitigatingCancellationToken); await TestServices.SolutionExplorer.AddAnalyzerReferenceAsync(ProjectName, typeof(NonSourceFileRefactoring).Assembly.Location, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.AddFileAsync(ProjectName, ".editorconfig", contents: "", open: true, HangMitigatingCancellationToken); @@ -1540,7 +1513,10 @@ await TestServices.EditorVerifier.CodeActionAsync( applyFix: true, cancellationToken: HangMitigatingCancellationToken); - AssertEx.EqualOrDiff(expectedText, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); + AssertEx.EqualOrDiff(""" + # Editorconfig File + # Refactored + """, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); } [IdeFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpCodeDefinitionWindow.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpCodeDefinitionWindow.cs index be1b20f907437..623a50db6fac3 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpCodeDefinitionWindow.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpCodeDefinitionWindow.cs @@ -33,12 +33,14 @@ public async Task CodeDefinitionWindowOpensMetadataAsSource(bool enableDecompila // our regular file. await TestServices.Editor.ActivateAsync(HangMitigatingCancellationToken); - await SetUpEditorAsync(@" -public class Test -{ - $$int field; -} -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + public class Test + { + $$int field; + } + + """, HangMitigatingCancellationToken); // The structure line should be the same, and we'll check for the presence/absence of the decompilation marker Assert.Contains("public struct Int32", await TestServices.CodeDefinitionWindow.GetCurrentLineTextAsync(HangMitigatingCancellationToken)); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpCompleteStatement.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpCompleteStatement.cs index cf79ca809e25e..c39df34d88ae9 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpCompleteStatement.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpCompleteStatement.cs @@ -22,17 +22,19 @@ public CSharpCompleteStatement() [IdeFact] public async Task UndoRestoresCaretPosition1() { - await SetUpEditorAsync(@" -public class Test -{ - private object f; + await SetUpEditorAsync(""" - public void Method() - { - f.ToString($$) - } -} -", HangMitigatingCancellationToken); + public class Test + { + private object f; + + public void Method() + { + f.ToString($$) + } + } + + """, HangMitigatingCancellationToken); await TestServices.Input.SendAsync(';', HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentLineTextAsync(" f.ToString();$$", assertCaretPosition: true); @@ -44,17 +46,19 @@ public void Method() [IdeFact, WorkItem("https://github.com/dotnet/roslyn/issues/43400")] public async Task UndoRestoresCaretPosition2() { - await SetUpEditorAsync(@" -public class Test -{ - private object f; + await SetUpEditorAsync(""" - public void Method() - { - Method(condition ? whenTrue $$) - } -} -", HangMitigatingCancellationToken); + public class Test + { + private object f; + + public void Method() + { + Method(condition ? whenTrue $$) + } + } + + """, HangMitigatingCancellationToken); await TestServices.Input.SendAsync(';', HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentLineTextAsync(" Method(condition ? whenTrue );$$", assertCaretPosition: true); @@ -66,17 +70,19 @@ public void Method() [IdeFact] public async Task UndoRestoresFormatBeforeRestoringCaretPosition() { - await SetUpEditorAsync(@" -public class Test -{ - private object f; + await SetUpEditorAsync(""" - public void Method() - { - f.ToString($$ ) - } -} -", HangMitigatingCancellationToken); + public class Test + { + private object f; + + public void Method() + { + f.ToString($$ ) + } + } + + """, HangMitigatingCancellationToken); await TestServices.Input.SendAsync(';', HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentLineTextAsync(" f.ToString();$$", assertCaretPosition: true); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpEncapsulateField.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpEncapsulateField.cs index 65f1d0fe598d2..d20c9a4218f48 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpEncapsulateField.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpEncapsulateField.cs @@ -22,18 +22,20 @@ public CSharpEncapsulateField() protected override string LanguageName => LanguageNames.CSharp; - private const string TestSource = @" -namespace myNamespace -{ - class Program - { - private static int? $$param = 0; - static void Main(string[] args) + private const string TestSource = """ + + namespace myNamespace { - param = 80; + class Program + { + private static int? $$param = 0; + static void Main(string[] args) + { + param = 80; + } + } } - } -}"; + """; [IdeFact] public async Task EncapsulateThroughCommand() @@ -64,21 +66,23 @@ public async Task EncapsulateThroughLightbulbIncludingReferences() await TestServices.EditorVerifier.CodeActionAsync("Encapsulate field: 'param' (and use property)", applyFix: true, blockUntilComplete: true, cancellationToken: HangMitigatingCancellationToken); } - await TestServices.EditorVerifier.TextContainsAsync(@" -namespace myNamespace -{ - class Program - { - private static int? param = 0; + await TestServices.EditorVerifier.TextContainsAsync(""" - public static int? Param { get => param; set => param = value; } + namespace myNamespace + { + class Program + { + private static int? param = 0; - static void Main(string[] args) - { - Param = 80; - } - } -}", cancellationToken: HangMitigatingCancellationToken); + public static int? Param { get => param; set => param = value; } + + static void Main(string[] args) + { + Param = 80; + } + } + } + """, cancellationToken: HangMitigatingCancellationToken); } [IdeFact] @@ -94,20 +98,22 @@ public async Task EncapsulateThroughLightbulbDefinitionsOnly() await TestServices.EditorVerifier.CodeActionAsync("Encapsulate field: 'param' (but still use field)", applyFix: true, blockUntilComplete: true, cancellationToken: HangMitigatingCancellationToken); } - await TestServices.EditorVerifier.TextContainsAsync(@" -namespace myNamespace -{ - class Program - { - private static int? param = 0; + await TestServices.EditorVerifier.TextContainsAsync(""" - public static int? Param { get => param; set => param = value; } + namespace myNamespace + { + class Program + { + private static int? param = 0; - static void Main(string[] args) - { - param = 80; - } - } -}", cancellationToken: HangMitigatingCancellationToken); + public static int? Param { get => param; set => param = value; } + + static void Main(string[] args) + { + param = 80; + } + } + } + """, cancellationToken: HangMitigatingCancellationToken); } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpErrorListCommon.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpErrorListCommon.cs index 1fff96533d0fe..07a12c116c5d2 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpErrorListCommon.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpErrorListCommon.cs @@ -26,19 +26,21 @@ protected CSharpErrorListCommon(string templateName) [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/61367")] public virtual async Task ErrorList() { - await TestServices.Editor.SetTextAsync(@" -class C -{ - void M(P p) - { - System.Console.WriteLin(); - } + await TestServices.Editor.SetTextAsync(""" - static void Main(string[] args) - { - } -} -", HangMitigatingCancellationToken); + class C + { + void M(P p) + { + System.Console.WriteLin(); + } + + static void Main(string[] args) + { + } + } + + """, HangMitigatingCancellationToken); await TestServices.ErrorList.ShowErrorListAsync(HangMitigatingCancellationToken); var expectedContents = new[] { "Class1.cs(4, 12): error CS0246: The type or namespace name 'P' could not be found (are you missing a using directive or an assembly reference?)", @@ -65,15 +67,17 @@ static void Main(string[] args) [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/61367")] public virtual async Task ErrorLevelWarning() { - await TestServices.Editor.SetTextAsync(@" -class C -{ - static void Main(string[] args) - { - int unused = 0; - } -} -", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + + class C + { + static void Main(string[] args) + { + int unused = 0; + } + } + + """, HangMitigatingCancellationToken); await TestServices.ErrorList.ShowErrorListAsync(HangMitigatingCancellationToken); var expectedContents = new[] { "Class1.cs(6, 13): warning CS0219: The variable 'unused' is assigned but its value is never used", @@ -88,16 +92,18 @@ static void Main(string[] args) [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/61367")] public virtual async Task ErrorsDuringMethodBodyEditing() { - await TestServices.Editor.SetTextAsync(@" -class Program2 -{ - static void Main(string[] args) - { - int aa = 7; - int a = aa; - } -} -", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + + class Program2 + { + static void Main(string[] args) + { + int aa = 7; + int a = aa; + } + } + + """, HangMitigatingCancellationToken); await TestServices.ErrorList.ShowErrorListAsync(HangMitigatingCancellationToken); var expectedContents = new string[] { }; await TestServices.Workspace.WaitForAllAsyncOperationsAsync([FeatureAttribute.Workspace, FeatureAttribute.SolutionCrawlerLegacy, FeatureAttribute.DiagnosticService, FeatureAttribute.ErrorSquiggles, FeatureAttribute.ErrorList], HangMitigatingCancellationToken); @@ -136,16 +142,18 @@ static void Main(string[] args) [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/63026")] public virtual async Task ErrorsAfterClosingFile() { - await TestServices.Editor.SetTextAsync(@" -class Program2 -{ - static void Main(string[] args) - { - int aa = 7; - int a = aa; - } -} -", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + + class Program2 + { + static void Main(string[] args) + { + int aa = 7; + int a = aa; + } + } + + """, HangMitigatingCancellationToken); await TestServices.ErrorList.ShowErrorListAsync(HangMitigatingCancellationToken); var expectedContents = new string[] { }; await TestServices.Workspace.WaitForAllAsyncOperationsAsync([FeatureAttribute.Workspace, FeatureAttribute.SolutionCrawlerLegacy, FeatureAttribute.DiagnosticService, FeatureAttribute.ErrorSquiggles, FeatureAttribute.ErrorList], HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpErrorListWeb.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpErrorListWeb.cs index c798552b18994..ff02b8f286ad2 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpErrorListWeb.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpErrorListWeb.cs @@ -25,14 +25,13 @@ public CSharpErrorListWeb() [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/70627")] public async Task ClosedRazorFile() { - var source = """ + await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, @"Pages\\Index.razor", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" @page @{ var x = "Hello" } -"""; - await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, @"Pages\\Index.razor", HangMitigatingCancellationToken); - await TestServices.Editor.SetTextAsync(source, HangMitigatingCancellationToken); +""", HangMitigatingCancellationToken); await TestServices.SolutionExplorer.SaveAllAsync(HangMitigatingCancellationToken); await TestServices.SolutionExplorer.CloseActiveWindow(HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpExtractInterfaceDialog.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpExtractInterfaceDialog.cs index 730ddf4261a7e..41a739c78c443 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpExtractInterfaceDialog.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpExtractInterfaceDialog.cs @@ -25,11 +25,13 @@ public CSharpExtractInterfaceDialog() [IdeFact] public async Task VerifyCancellation() { - await SetUpEditorAsync(@"class C$$ -{ - public void M() { } -} -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + class C$$ + { + public void M() { } + } + + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", applyFix: true, @@ -40,21 +42,25 @@ await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", await TestServices.ExtractInterfaceDialog.ClickCancelAsync(HangMitigatingCancellationToken); await TestServices.ExtractInterfaceDialog.VerifyClosedAsync(HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@"class C -{ - public void M() { } -} -", cancellationToken: HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextContainsAsync(""" + class C + { + public void M() { } + } + + """, cancellationToken: HangMitigatingCancellationToken); } [IdeFact] public async Task CheckFileName() { - await SetUpEditorAsync(@"class C$$ -{ - public void M() { } -} -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + class C$$ + { + public void M() { } + } + + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", applyFix: true, @@ -73,12 +79,14 @@ await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", [IdeFact] public async Task VerifySelectAndDeselectAllButtons() { - await SetUpEditorAsync(@"class C$$ -{ - public void M1() { } - public void M2() { } -} -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + class C$$ + { + public void M1() { } + public void M2() { } + } + + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", @@ -112,12 +120,14 @@ await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", [IdeFact] public async Task OnlySelectedItemsAreGenerated() { - await SetUpEditorAsync(@"class C$$ -{ - public void M1() { } - public void M2() { } -} -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + class C$$ + { + public void M1() { } + public void M2() { } + } + + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", @@ -132,28 +142,34 @@ await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", await TestServices.ExtractInterfaceDialog.VerifyClosedAsync(HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, "Class1.cs", HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@"class C : IC -{ - public void M1() { } - public void M2() { } -} -", cancellationToken: HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextContainsAsync(""" + class C : IC + { + public void M1() { } + public void M2() { } + } + + """, cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, "IC.cs", HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@"interface IC -{ - void M2(); -}", cancellationToken: HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextContainsAsync(""" + interface IC + { + void M2(); + } + """, cancellationToken: HangMitigatingCancellationToken); } [IdeFact] public async Task CheckSameFile() { - await SetUpEditorAsync(@"class C$$ -{ - public void M() { } -} -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + class C$$ + { + public void M() { } + } + + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", applyFix: true, @@ -167,28 +183,32 @@ await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", await TestServices.ExtractInterfaceDialog.ClickOKAsync(HangMitigatingCancellationToken); await TestServices.ExtractInterfaceDialog.VerifyClosedAsync(HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@"interface IC -{ - void M(); -} + await TestServices.EditorVerifier.TextContainsAsync(""" + interface IC + { + void M(); + } -class C : IC -{ - public void M() { } -} -", cancellationToken: HangMitigatingCancellationToken); + class C : IC + { + public void M() { } + } + + """, cancellationToken: HangMitigatingCancellationToken); } [IdeFact] public async Task CheckSameFileOnlySelectedItems() { - await SetUpEditorAsync(@"class C$$ -{ - public void M1() { } - public void M2() { } -} -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + class C$$ + { + public void M1() { } + public void M2() { } + } + + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", @@ -203,30 +223,34 @@ await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", await TestServices.ExtractInterfaceDialog.ClickOKAsync(HangMitigatingCancellationToken); await TestServices.ExtractInterfaceDialog.VerifyClosedAsync(HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@"interface IC -{ - void M2(); -} + await TestServices.EditorVerifier.TextContainsAsync(""" + interface IC + { + void M2(); + } -class C : IC -{ - public void M1() { } - public void M2() { } -} -", cancellationToken: HangMitigatingCancellationToken); + class C : IC + { + public void M1() { } + public void M2() { } + } + + """, cancellationToken: HangMitigatingCancellationToken); } [IdeFact] public async Task CheckSameFileNamespace() { - await SetUpEditorAsync(@"namespace A -{ - class C$$ - { - public void M() { } - } -} -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + namespace A + { + class C$$ + { + public void M() { } + } + } + + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", applyFix: true, @@ -240,29 +264,33 @@ await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", await TestServices.ExtractInterfaceDialog.ClickOKAsync(HangMitigatingCancellationToken); await TestServices.ExtractInterfaceDialog.VerifyClosedAsync(HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@"namespace A -{ - interface IC - { - void M(); - } - - class C : IC - { - public void M() { } - } -} -", cancellationToken: HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextContainsAsync(""" + namespace A + { + interface IC + { + void M(); + } + + class C : IC + { + public void M() { } + } + } + + """, cancellationToken: HangMitigatingCancellationToken); } [IdeFact] public async Task CheckSameWithTypes() { - await SetUpEditorAsync(@"class C$$ -{ - public bool M() => false; -} -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + class C$$ + { + public bool M() => false; + } + + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", applyFix: true, @@ -276,15 +304,17 @@ await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", await TestServices.ExtractInterfaceDialog.ClickOKAsync(HangMitigatingCancellationToken); await TestServices.ExtractInterfaceDialog.VerifyClosedAsync(HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@"interface IC -{ - bool M(); -} + await TestServices.EditorVerifier.TextContainsAsync(""" + interface IC + { + bool M(); + } -class C : IC -{ - public bool M() => false; -} -", cancellationToken: HangMitigatingCancellationToken); + class C : IC + { + public bool M() => false; + } + + """, cancellationToken: HangMitigatingCancellationToken); } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpExtractMethod.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpExtractMethod.cs index 34fd5b841d7fb..2369035ab263a 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpExtractMethod.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpExtractMethod.cs @@ -18,21 +18,23 @@ namespace Roslyn.VisualStudio.NewIntegrationTests.CSharp; [Trait(Traits.Feature, Traits.Features.ExtractMethod)] public class CSharpExtractMethod : AbstractEditorTest { - private const string TestSource = @" -using System; -public class Program -{ - public int Method() - { - Console.WriteLine(""Hello World""); - int a; - int b; - a = 5; - b = 10; - int result = a * b; - return result; - } -}"; + private const string TestSource = """ + + using System; + public class Program + { + public int Method() + { + Console.WriteLine("Hello World"); + int a; + int b; + a = 5; + b = 10; + int result = a * b; + return result; + } + } + """; protected override string LanguageName => LanguageNames.CSharp; @@ -49,38 +51,39 @@ public async Task SimpleExtractMethod() await TestServices.Editor.PlaceCaretAsync("World", charsOffset: 4, occurrence: 0, extendSelection: true, selectBlock: false, HangMitigatingCancellationToken); await TestServices.Shell.ExecuteCommandAsync(WellKnownCommands.Refactor.ExtractMethod, HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.ExtractMethod, HangMitigatingCancellationToken); - - var expectedMarkup = @" -using System; -public class Program -{ - public int Method() - { - [|NewMethod|](); - int a; - int b; - a = 5; - b = 10; - int result = a * b; - return result; - } - - private static void [|NewMethod|]() - { - Console.WriteLine(""Hello World""); - } -}"; - - MarkupTestFile.GetSpans(expectedMarkup, out var expectedText, out var spans); + MarkupTestFile.GetSpans(""" + + using System; + public class Program + { + public int Method() + { + [|NewMethod|](); + int a; + int b; + a = 5; + b = 10; + int result = a * b; + return result; + } + + private static void [|NewMethod|]() + { + Console.WriteLine("Hello World"); + } + } + """, out var expectedText, out var spans); await TestServices.EditorVerifier.TextContainsAsync(expectedText, cancellationToken: HangMitigatingCancellationToken); var tags = (await TestServices.Editor.GetRenameTagsAsync(HangMitigatingCancellationToken)).SelectAsArray(tag => tag.Span.Span.ToTextSpan()); AssertEx.SetEqual(spans, tags); await TestServices.Input.SendAsync(["SayHello", VirtualKeyCode.RETURN], HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@"private static void SayHello() - { - Console.WriteLine(""Hello World""); - }", cancellationToken: HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextContainsAsync(""" + private static void SayHello() + { + Console.WriteLine("Hello World"); + } + """, cancellationToken: HangMitigatingCancellationToken); } [IdeFact, WorkItem("https://github.com/dotnet/roslyn/pull/61369")] @@ -91,37 +94,38 @@ public async Task ExtractMethodWithTriviaSelected() await TestServices.Editor.PlaceCaretAsync("result;", charsOffset: 4, occurrence: 0, extendSelection: true, selectBlock: false, HangMitigatingCancellationToken); await TestServices.Shell.ExecuteCommandAsync(WellKnownCommands.Refactor.ExtractMethod, HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.ExtractMethod, HangMitigatingCancellationToken); - - var expectedMarkup = @" -using System; -public class Program -{ - public int Method() - { - Console.WriteLine(""Hello World""); - int a; - int b; - a = 5; - b = 10; - return [|NewMethod|](a, b); - } - - private static int [|NewMethod|](int a, int b) - { - return a * b; - } -}"; - - MarkupTestFile.GetSpans(expectedMarkup, out var expectedText, out var spans); + MarkupTestFile.GetSpans(""" + + using System; + public class Program + { + public int Method() + { + Console.WriteLine("Hello World"); + int a; + int b; + a = 5; + b = 10; + return [|NewMethod|](a, b); + } + + private static int [|NewMethod|](int a, int b) + { + return a * b; + } + } + """, out var expectedText, out var spans); Assert.Equal(expectedText, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); var tags = (await TestServices.Editor.GetRenameTagsAsync(HangMitigatingCancellationToken)).SelectAsArray(tag => tag.Span.Span.ToTextSpan()); AssertEx.SetEqual(spans, tags); await TestServices.Input.SendAsync(["SayHello", VirtualKeyCode.RETURN], HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@"private static int SayHello(int a, int b) - { - return a * b; - }", cancellationToken: HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextContainsAsync(""" + private static int SayHello(int a, int b) + { + return a * b; + } + """, cancellationToken: HangMitigatingCancellationToken); } [IdeFact] @@ -131,30 +135,29 @@ public async Task ExtractViaCodeAction() await TestServices.Editor.PlaceCaretAsync("a = 5", charsOffset: -1, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("a * b", charsOffset: 1, occurrence: 0, extendSelection: true, selectBlock: false, HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Extract method", applyFix: true, blockUntilComplete: true, cancellationToken: HangMitigatingCancellationToken); - - var expectedMarkup = @" -using System; -public class Program -{ - public int Method() - { - Console.WriteLine(""Hello World""); - int a; - int b; - int result; - [|NewMethod|](out a, out b, out result); - return result; - } - - private static void [|NewMethod|](out int a, out int b, out int result) - { - a = 5; - b = 10; - result = a * b; - } -}"; - - MarkupTestFile.GetSpans(expectedMarkup, out var expectedText, out var spans); + MarkupTestFile.GetSpans(""" + + using System; + public class Program + { + public int Method() + { + Console.WriteLine("Hello World"); + int a; + int b; + int result; + [|NewMethod|](out a, out b, out result); + return result; + } + + private static void [|NewMethod|](out int a, out int b, out int result) + { + a = 5; + b = 10; + result = a * b; + } + } + """, out var expectedText, out var spans); Assert.Equal(expectedText, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); var tags = (await TestServices.Editor.GetRenameTagsAsync(HangMitigatingCancellationToken)).SelectAsArray(tag => tag.Span.Span.ToTextSpan()); AssertEx.SetEqual(spans, tags); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpF1Help.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpF1Help.cs index fcea866909ec4..8c58a8308d1e4 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpF1Help.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpF1Help.cs @@ -23,52 +23,52 @@ public CSharpF1Help() } [IdeFact] - private async Task F1Help() + public async Task F1Help() { - var text = @" -using System; -using System.IO; -using System.Linq; -using System.Collections.Generic; + await SetUpEditorAsync(""" -namespace F1TestNamespace -{ - #region TaoRegion - abstract class ShapesClass { } + using System; + using System.IO; + using System.Linq; + using System.Collections.Generic; - class Program$$ - { - public static void Main() - { - } + namespace F1TestNamespace + { + #region TaoRegion + abstract class ShapesClass { } - public IEnumerable Linq1() - { - int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; - int i = numbers.First(); - int j = Array.IndexOf(numbers, 1); + class Program$$ + { + public static void Main() + { + } - var lowNums1 = - from n in numbers - orderby n ascending - where n < 5 - select n; + public IEnumerable Linq1() + { + int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; + int i = numbers.First(); + int j = Array.IndexOf(numbers, 1); - var numberGroups = - from n in numbers - let m = 1 - join p in numbers on i equals p - group n by n % 5 into g - select new { Remainder = g.Key, Numbers = g }; + var lowNums1 = + from n in numbers + orderby n ascending + where n < 5 + select n; - foreach (int element in numbers) yield return i; - } + var numberGroups = + from n in numbers + let m = 1 + join p in numbers on i equals p + group n by n % 5 into g + select new { Remainder = g.Key, Numbers = g }; - } - #endregion TaoRegion -}"; + foreach (int element in numbers) yield return i; + } - await SetUpEditorAsync(text, HangMitigatingCancellationToken); + } + #endregion TaoRegion + } + """, HangMitigatingCancellationToken); await VerifyAsync("abstract", "abstract_CSharpKeyword", HangMitigatingCancellationToken); await VerifyAsync("ascending", "ascending_CSharpKeyword", HangMitigatingCancellationToken); await VerifyAsync("from", "from_CSharpKeyword", HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpFindReferences.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpFindReferences.cs index caa3edce69170..1b9f73e458793 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpFindReferences.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpFindReferences.cs @@ -30,23 +30,27 @@ public CSharpFindReferences() [IdeFact] public async Task FindReferencesToCtor() { - await SetUpEditorAsync(@" -class Program -{ -}$$ -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + class Program + { + }$$ + + """, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "File2.cs", cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, "File2.cs", HangMitigatingCancellationToken); - await SetUpEditorAsync(@" -class SomeOtherClass -{ - void M() - { - Program p = new Progr$$am(); - } -} -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + class SomeOtherClass + { + void M() + { + Program p = new Progr$$am(); + } + } + + """, HangMitigatingCancellationToken); await TestServices.Input.SendAsync((VirtualKeyCode.F12, VirtualKeyCode.SHIFT), HangMitigatingCancellationToken); @@ -81,16 +85,18 @@ void M() public async Task FindReferencesToLocals() { await using var telemetry = await TestServices.Telemetry.EnableTestTelemetryChannelAsync(HangMitigatingCancellationToken); - await SetUpEditorAsync(@" -class Program -{ - static void Main() - { - int local = 1; - Console.WriteLine(local$$); - } -} -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + class Program + { + static void Main() + { + int local = 1; + Console.WriteLine(local$$); + } + } + + """, HangMitigatingCancellationToken); await TestServices.Input.SendAsync((VirtualKeyCode.F12, VirtualKeyCode.SHIFT), HangMitigatingCancellationToken); @@ -119,15 +125,17 @@ static void Main() [IdeFact] public async Task FindReferencesToString() { - await SetUpEditorAsync(@" -class Program -{ - static void Main() - { - string local = ""1""$$; - } -} -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + class Program + { + static void Main() + { + string local = "1"$$; + } + } + + """, HangMitigatingCancellationToken); await TestServices.Input.SendAsync((VirtualKeyCode.F12, VirtualKeyCode.SHIFT), HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpFormatting.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpFormatting.cs index 8d71e94b4aef8..53259a2ba1810 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpFormatting.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpFormatting.cs @@ -27,242 +27,278 @@ public CSharpFormatting() public async Task AlignOpenBraceWithMethodDeclaration() { await using var telemetry = await TestServices.Telemetry.EnableTestTelemetryChannelAsync(HangMitigatingCancellationToken); - await SetUpEditorAsync(@" -$$class C -{ - void Main() - { - } -}", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + $$class C + { + void Main() + { + } + } + """, HangMitigatingCancellationToken); await TestServices.Editor.FormatDocumentAsync(HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -class C -{ - void Main() - { - } -}", cancellationToken: HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextContainsAsync(""" + + class C + { + void Main() + { + } + } + """, cancellationToken: HangMitigatingCancellationToken); await telemetry.VerifyFiredAsync(["vs/ide/vbcs/commandhandler/formatcommand"], HangMitigatingCancellationToken); } [IdeFact] public async Task FormatOnSemicolon() { - await SetUpEditorAsync(@" -public class C -{ - void Goo() - { - var x = from a in new List() - where x % 2 = 0 - select x ;$$ - } -}", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" - await TestServices.Input.SendAsync([VirtualKeyCode.BACK, ';'], HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -public class C -{ - void Goo() - { - var x = from a in new List() + public class C + { + void Goo() + { + var x = from a in new List() where x % 2 = 0 - select x; - } -}", cancellationToken: HangMitigatingCancellationToken); + select x ;$$ + } + } + """, HangMitigatingCancellationToken); + + await TestServices.Input.SendAsync([VirtualKeyCode.BACK, ';'], HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextContainsAsync(""" + + public class C + { + void Goo() + { + var x = from a in new List() + where x % 2 = 0 + select x; + } + } + """, cancellationToken: HangMitigatingCancellationToken); } [IdeFact] public async Task FormatSelection() { - await SetUpEditorAsync(@" -public class C { - public void M( ) {$$ - } -}", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + public class C { + public void M( ) {$$ + } + } + """, HangMitigatingCancellationToken); await TestServices.Editor.SelectTextInCurrentDocumentAsync("public void M( ) {", HangMitigatingCancellationToken); await TestServices.Editor.FormatSelectionAsync(HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -public class C { - public void M() - { - } -}", cancellationToken: HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextContainsAsync(""" + + public class C { + public void M() + { + } + } + """, cancellationToken: HangMitigatingCancellationToken); } [IdeFact] public async Task PasteCodeWithLambdaBody() { - await SetUpEditorAsync(@" -using System; -class Program -{ - static void Main() - { - Action a = () => - { - using (null) + await SetUpEditorAsync(""" + + using System; + class Program { - $$ + static void Main() + { + Action a = () => + { + using (null) + { + $$ + } + }; + } } - }; - } -}", HangMitigatingCancellationToken); - await TestServices.Editor.PasteAsync(@" Action b = () => - { + """, HangMitigatingCancellationToken); + await TestServices.Editor.PasteAsync(""" + Action b = () => + { - };", HangMitigatingCancellationToken); + }; + """, HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -using System; -class Program -{ - static void Main() - { - Action a = () => - { - using (null) + await TestServices.EditorVerifier.TextContainsAsync(""" + + using System; + class Program { - Action b = () => + static void Main() { - - }; + Action a = () => + { + using (null) + { + Action b = () => + { + + }; + } + }; + } } - }; - } -}", cancellationToken: HangMitigatingCancellationToken); + """, cancellationToken: HangMitigatingCancellationToken); // Undo should only undo the formatting await TestServices.Shell.ExecuteCommandAsync(WellKnownCommands.Edit.Undo, HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -using System; -class Program -{ - static void Main() - { - Action a = () => - { - using (null) - { - Action b = () => - { + await TestServices.EditorVerifier.TextContainsAsync(""" - }; + using System; + class Program + { + static void Main() + { + Action a = () => + { + using (null) + { + Action b = () => + { + + }; + } + }; + } } - }; - } -}", cancellationToken: HangMitigatingCancellationToken); + """, cancellationToken: HangMitigatingCancellationToken); } [IdeFact] public async Task PasteCodeWithLambdaBody2() { - await SetUpEditorAsync(@" -using System; -class Program -{ - static void Main() - { - Action a = () => - { - using (null) + await SetUpEditorAsync(""" + + using System; + class Program { - $$ + static void Main() + { + Action a = () => + { + using (null) + { + $$ + } + }; + } } - }; - } -}", HangMitigatingCancellationToken); - await TestServices.Editor.PasteAsync(@" Action b = n => - { - Console.Writeline(n); - };", HangMitigatingCancellationToken); - - await TestServices.EditorVerifier.TextContainsAsync(@" -using System; -class Program -{ - static void Main() - { - Action a = () => - { - using (null) + """, HangMitigatingCancellationToken); + await TestServices.Editor.PasteAsync(""" + Action b = n => + { + Console.Writeline(n); + }; + """, HangMitigatingCancellationToken); + + await TestServices.EditorVerifier.TextContainsAsync(""" + + using System; + class Program { - Action b = n => + static void Main() { - Console.Writeline(n); - }; + Action a = () => + { + using (null) + { + Action b = n => + { + Console.Writeline(n); + }; + } + }; + } } - }; - } -}", cancellationToken: HangMitigatingCancellationToken); + """, cancellationToken: HangMitigatingCancellationToken); } [IdeFact] public async Task PasteCodeWithLambdaBody3() { - await SetUpEditorAsync(@" -using System; -class Program -{ - static void Main() - { - Action a = () => - { - using (null) + await SetUpEditorAsync(""" + + using System; + class Program { - $$ + static void Main() + { + Action a = () => + { + using (null) + { + $$ + } + }; + } } - }; - } -}", HangMitigatingCancellationToken); - await TestServices.Editor.PasteAsync(@" D d = delegate(int x) -{ - return 2 * x; -};", HangMitigatingCancellationToken); + """, HangMitigatingCancellationToken); + await TestServices.Editor.PasteAsync(""" + D d = delegate(int x) + { + return 2 * x; + }; + """, HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -using System; -class Program -{ - static void Main() - { - Action a = () => - { - using (null) + await TestServices.EditorVerifier.TextContainsAsync(""" + + using System; + class Program { - D d = delegate (int x) + static void Main() { - return 2 * x; - }; + Action a = () => + { + using (null) + { + D d = delegate (int x) + { + return 2 * x; + }; + } + }; + } } - }; - } -}", cancellationToken: HangMitigatingCancellationToken); + """, cancellationToken: HangMitigatingCancellationToken); } [IdeFact] public async Task ShiftEnterWithIntelliSenseAndBraceMatching() { - await SetUpEditorAsync(@" -class Program -{ - object M(object bar) - { - return M$$ - } -}", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + class Program + { + object M(object bar) + { + return M$$ + } + } + """, HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.Workspace, HangMitigatingCancellationToken); await TestServices.Input.SendAsync(["(ba", (VirtualKeyCode.RETURN, VirtualKeyCode.SHIFT), "// comment"], HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -class Program -{ - object M(object bar) - { - return M(bar); - // comment - } -}", cancellationToken: HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextContainsAsync(""" + + class Program + { + object M(object bar) + { + return M(bar); + // comment + } + } + """, cancellationToken: HangMitigatingCancellationToken); } [IdeFact] @@ -270,29 +306,19 @@ object M(object bar) [WorkItem("https://github.com/dotnet/roslyn/issues/15003")] public async Task ApplyEditorConfigAndFormatDocument() { - var markup = @" -class C -{ - public int X1 - { - get - { - $$return 3; - } - } -}"; - var expectedTextTwoSpaceIndent = @" -class C -{ - public int X1 - { - get - { - return 3; - } - } -}"; + var markup = """ + class C + { + public int X1 + { + get + { + $$return 3; + } + } + } + """; await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, "Class1.cs", HangMitigatingCancellationToken); MarkupTestFile.GetSpans(markup, out var expectedTextFourSpaceIndent, out _); @@ -320,11 +346,13 @@ await TestServices.Workspace.WaitForAllAsyncOperationsAsync( * verifies that the next Format Document operation adheres to the formatting. */ - var editorConfig = @"root = true + var editorConfig = """ + root = true + + [*.cs] + indent_size = 2 -[*.cs] -indent_size = 2 -"; + """; await TestServices.SolutionExplorer.AddFileAsync(ProjectName, ".editorconfig", editorConfig, open: false, HangMitigatingCancellationToken); @@ -338,7 +366,19 @@ await TestServices.Workspace.WaitForAllAsyncOperationsAsync( HangMitigatingCancellationToken); await TestServices.Editor.FormatDocumentAsync(HangMitigatingCancellationToken); - Assert.Equal(expectedTextTwoSpaceIndent, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); + Assert.Equal(""" + + class C + { + public int X1 + { + get + { + return 3; + } + } + } + """, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); /* * The third portion of this test modifies the existing .editorconfig file with a new indentation behavior, diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpGenerateFromUsage.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpGenerateFromUsage.cs index 908dffff63b34..eac26ea2340cb 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpGenerateFromUsage.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpGenerateFromUsage.cs @@ -25,22 +25,26 @@ public CSharpGenerateFromUsage() public async Task GenerateLocal() { await SetUpEditorAsync( -@"class Program -{ - static void Main(string[] args) - { - string s = $$xyz; - } -}", HangMitigatingCancellationToken); + """ + class Program + { + static void Main(string[] args) + { + string s = $$xyz; + } + } + """, HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Generate local 'xyz'", applyFix: true, cancellationToken: HangMitigatingCancellationToken); await TestServices.EditorVerifier.TextContainsAsync( -@"class Program -{ - static void Main(string[] args) - { - string xyz = null; - string s = xyz; - } -}", cancellationToken: HangMitigatingCancellationToken); + """ + class Program + { + static void Main(string[] args) + { + string xyz = null; + string s = xyz; + } + } + """, cancellationToken: HangMitigatingCancellationToken); } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpGenerateTypeDialog.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpGenerateTypeDialog.cs index b2873b63c43f1..9295c040b7b28 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpGenerateTypeDialog.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpGenerateTypeDialog.cs @@ -25,14 +25,16 @@ public CSharpGenerateTypeDialog() [IdeFact] public async Task OpenAndCloseDialog() { - await SetUpEditorAsync(@"class C -{ - void Method() - { - $$A a; - } -} -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + class C + { + void Method() + { + $$A a; + } + } + + """, HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Generate new type...", applyFix: true, @@ -53,14 +55,16 @@ public async Task CSharpToBasic() var project = ProjectName; await TestServices.SolutionExplorer.OpenFileAsync(project, "Class1.cs", HangMitigatingCancellationToken); - await SetUpEditorAsync(@"class C -{ - void Method() - { - $$A a; - } -} -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + class C + { + void Method() + { + $$A a; + } + } + + """, HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Generate new type...", applyFix: true, @@ -77,22 +81,26 @@ void Method() await TestServices.SolutionExplorer.OpenFileAsync(vbProj, "GenerateTypeTest.vb", HangMitigatingCancellationToken); var actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); - Assert.Contains(@"Public Interface A -End Interface -", actualText); + Assert.Contains(""" + Public Interface A + End Interface + + """, actualText); await TestServices.SolutionExplorer.OpenFileAsync(project, "Class1.cs", HangMitigatingCancellationToken); actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); - Assert.Contains(@"using VBProj; - -class C -{ - void Method() - { - A a; - } -} -", actualText); + Assert.Contains(""" + using VBProj; + + class C + { + void Method() + { + A a; + } + } + + """, actualText); } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpGoToBase.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpGoToBase.cs index 1fb1a350db622..b8fa9f22de01f 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpGoToBase.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpGoToBase.cs @@ -27,15 +27,17 @@ public async Task GoToBaseFromMetadataAsSource() await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "C.cs", cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, "C.cs", HangMitigatingCancellationToken); await TestServices.Editor.SetTextAsync( -@"using System; + """ + using System; -class C -{ - public override string ToString() - { - return ""C""; - } -}", HangMitigatingCancellationToken); + class C + { + public override string ToString() + { + return "C"; + } + } + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("ToString", charsOffset: -1, HangMitigatingCancellationToken); await TestServices.Editor.GoToBaseAsync(HangMitigatingCancellationToken); Assert.Equal("Object [decompiled] [Read Only]", await TestServices.Shell.GetActiveWindowCaptionAsync(HangMitigatingCancellationToken)); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpGoToDefinition.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpGoToDefinition.cs index 7dc154a768b0b..24a5ea9a3d0a2 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpGoToDefinition.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpGoToDefinition.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Options; @@ -32,16 +33,20 @@ public async Task GoToClassDeclaration() await TestServices.SolutionExplorer.AddFileAsync(project, "FileDef.cs", cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(project, "FileDef.cs", HangMitigatingCancellationToken); await TestServices.Editor.SetTextAsync( -@"class SomeClass -{ -}", HangMitigatingCancellationToken); + """ + class SomeClass + { + } + """, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.AddFileAsync(project, "FileConsumer.cs", cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(project, "FileConsumer.cs", HangMitigatingCancellationToken); await TestServices.Editor.SetTextAsync( -@"class SomeOtherClass -{ - SomeClass sc; -}", HangMitigatingCancellationToken); + """ + class SomeOtherClass + { + SomeClass sc; + } + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("SomeClass", charsOffset: 0, HangMitigatingCancellationToken); await TestServices.Editor.GoToDefinitionAsync(HangMitigatingCancellationToken); Assert.Equal($"FileDef.cs", await TestServices.Shell.GetActiveDocumentFileNameAsync(HangMitigatingCancellationToken)); @@ -56,18 +61,22 @@ public async Task GoToDefinitionOpensProvisionalTabIfDocumentNotAlreadyOpen() await TestServices.SolutionExplorer.AddFileAsync(project, "FileDef.cs", cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(project, "FileDef.cs", HangMitigatingCancellationToken); await TestServices.Editor.SetTextAsync( -@"class SomeClass -{ -} -", HangMitigatingCancellationToken); + """ + class SomeClass + { + } + + """, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.CloseCodeFileAsync(project, "FileDef.cs", saveFile: true, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.AddFileAsync(project, "FileConsumer.cs", cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(project, "FileConsumer.cs", HangMitigatingCancellationToken); await TestServices.Editor.SetTextAsync( -@"class SomeOtherClass -{ - SomeClass sc; -}", HangMitigatingCancellationToken); + """ + class SomeOtherClass + { + SomeClass sc; + } + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("SomeClass", charsOffset: 0, HangMitigatingCancellationToken); await TestServices.Editor.GoToDefinitionAsync(HangMitigatingCancellationToken); Assert.Equal("FileDef.cs", await TestServices.Shell.GetActiveWindowCaptionAsync(HangMitigatingCancellationToken)); @@ -79,9 +88,11 @@ await TestServices.Editor.SetTextAsync( public async Task GoToDefinitionWithMultipleResults() { await SetUpEditorAsync( -@"partial class /*Marker*/ $$PartialClass { } + """ + partial class /*Marker*/ $$PartialClass { } -partial class PartialClass { int i = 0; }", HangMitigatingCancellationToken); + partial class PartialClass { int i = 0; } + """, HangMitigatingCancellationToken); await TestServices.Editor.GoToDefinitionAsync(HangMitigatingCancellationToken); Assert.Equal("'PartialClass' declarations - Entire solution", await TestServices.Shell.GetActiveWindowCaptionAsync(HangMitigatingCancellationToken)); @@ -115,15 +126,17 @@ public async Task GoToDefinitionFromMetadataCollapsed() await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "C.cs", cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, "C.cs", HangMitigatingCancellationToken); await TestServices.Editor.SetTextAsync( -@"using System; + """ + using System; -class C -{ - public override string ToString() - { - return ""C""; - } -}", HangMitigatingCancellationToken); + class C + { + public override string ToString() + { + return "C"; + } + } + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("override", charsOffset: -1, HangMitigatingCancellationToken); await TestServices.Editor.GoToDefinitionAsync(HangMitigatingCancellationToken); @@ -146,15 +159,17 @@ public async Task GoToDefinitionFromMetadataNotCollapsed() await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "C.cs", cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, "C.cs", HangMitigatingCancellationToken); await TestServices.Editor.SetTextAsync( -@"using System; + """ + using System; -class C -{ - public override string ToString() - { - return ""C""; - } -}", HangMitigatingCancellationToken); + class C + { + public override string ToString() + { + return "C"; + } + } + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("override", charsOffset: -1, HangMitigatingCancellationToken); await TestServices.Editor.GoToDefinitionAsync(HangMitigatingCancellationToken); @@ -173,15 +188,17 @@ public async Task GoToDefinitionFromMetadataSecondHop() await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "C.cs", cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, "C.cs", HangMitigatingCancellationToken); await TestServices.Editor.SetTextAsync( -@"using System; + """ + using System; -class C -{ - public void Test() - { - var helper = new Roslyn.VisualStudio.NewIntegrationTests.CSharp.CSharpGoToBase(); - } -}", HangMitigatingCancellationToken); + class C + { + public void Test() + { + var helper = new Roslyn.VisualStudio.NewIntegrationTests.CSharp.CSharpGoToBase(); + } + } + """, HangMitigatingCancellationToken); // Purposefully not using this test class as test data, or the strings in this test could be found await TestServices.Editor.PlaceCaretAsync("CSharpGoToBase", charsOffset: -1, HangMitigatingCancellationToken); @@ -222,15 +239,17 @@ public async Task TestGotoDefinitionWithValueTuple(string expression) await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "C.cs", cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, "C.cs", HangMitigatingCancellationToken); await TestServices.Editor.SetTextAsync( -@$"using System; - -class C -{{ - void M() - {{ - {expression} - }} -}}", HangMitigatingCancellationToken); + $$""" + using System; + + class C + { + void M() + { + {{expression}} + } + } + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("ValueTuple", charsOffset: -1, HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpGoToImplementation.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpGoToImplementation.cs index ec9bc8da159ac..18f0a4e1455c1 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpGoToImplementation.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpGoToImplementation.cs @@ -38,15 +38,19 @@ public async Task SimpleGoToImplementation(bool asyncNavigation) await TestServices.SolutionExplorer.AddFileAsync(project, "FileImplementation.cs", cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(project, "FileImplementation.cs", HangMitigatingCancellationToken); await TestServices.Editor.SetTextAsync( -@"class Implementation : IGoo -{ -}", HangMitigatingCancellationToken); + """ + class Implementation : IGoo + { + } + """, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.AddFileAsync(project, "FileInterface.cs", cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(project, "FileInterface.cs", HangMitigatingCancellationToken); await TestServices.Editor.SetTextAsync( -@"interface IGoo -{ -}", HangMitigatingCancellationToken); + """ + interface IGoo + { + } + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("interface IGoo", charsOffset: 0, HangMitigatingCancellationToken); await TestServices.Editor.GoToImplementationAsync(HangMitigatingCancellationToken); @@ -78,17 +82,21 @@ public async Task GoToImplementationOpensProvisionalTabIfDocumentNotOpen(bool as await TestServices.SolutionExplorer.AddFileAsync(project, "FileImplementation.cs", cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(project, "FileImplementation.cs", HangMitigatingCancellationToken); await TestServices.Editor.SetTextAsync( -@"class Implementation : IBar -{ -} -", HangMitigatingCancellationToken); + """ + class Implementation : IBar + { + } + + """, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.CloseCodeFileAsync(project, "FileImplementation.cs", saveFile: true, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.AddFileAsync(project, "FileInterface.cs", cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(project, "FileInterface.cs", HangMitigatingCancellationToken); await TestServices.Editor.SetTextAsync( -@"interface IBar -{ -}", HangMitigatingCancellationToken); + """ + interface IBar + { + } + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("interface IBar", charsOffset: 0, HangMitigatingCancellationToken); await TestServices.Editor.GoToImplementationAsync(HangMitigatingCancellationToken); @@ -122,15 +130,17 @@ public async Task GoToImplementationFromMetadataAsSource(bool asyncNavigation) await TestServices.SolutionExplorer.AddFileAsync(project, "FileImplementation.cs", cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(project, "FileImplementation.cs", HangMitigatingCancellationToken); await TestServices.Editor.SetTextAsync( -@"using System; - -class Implementation : IDisposable -{ - public void SomeMethod() - { - IDisposable d; - } -}", HangMitigatingCancellationToken); + """ + using System; + + class Implementation : IDisposable + { + public void SomeMethod() + { + IDisposable d; + } + } + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("IDisposable d", charsOffset: -1, HangMitigatingCancellationToken); await TestServices.Editor.GoToDefinitionAsync(HangMitigatingCancellationToken); Assert.Equal("IDisposable [decompiled] [Read Only]", await TestServices.Shell.GetActiveWindowCaptionAsync(HangMitigatingCancellationToken)); @@ -167,36 +177,40 @@ public async Task GoToImplementationFromSourceAndMetadata(bool asyncNavigation) await TestServices.SolutionExplorer.AddFileAsync(project, "FileImplementation.cs", cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(project, "FileImplementation.cs", HangMitigatingCancellationToken); await TestServices.Editor.SetTextAsync( -@"using System; - -class Implementation : IDisposable -{ - public void Dispose() - { - } -}", HangMitigatingCancellationToken); + """ + using System; + + class Implementation : IDisposable + { + public void Dispose() + { + } + } + """, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.CloseCodeFileAsync(project, "FileImplementation.cs", saveFile: true, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.AddFileAsync(project, "FileUsage.cs", cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(project, "FileUsage.cs", HangMitigatingCancellationToken); await TestServices.Editor.SetTextAsync( -@"using System; - -class C -{ - void M() - { - IDisposable c; - try - { - c = new Implementation(); - } - finally - { - c.Dispose(); - } - } -}", HangMitigatingCancellationToken); + """ + using System; + + class C + { + void M() + { + IDisposable c; + try + { + c = new Implementation(); + } + finally + { + c.Dispose(); + } + } + } + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("Dispose", charsOffset: -1, HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpImmediate.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpImmediate.cs index 04001f04d0cc7..d551d5c55f4d3 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpImmediate.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpImmediate.cs @@ -32,16 +32,18 @@ public override async Task InitializeAsync() [IdeFact] public async Task DumpLocalVariableValue() { - await TestServices.Editor.SetTextAsync(@" -class Program -{ - static void Main(string[] args) - { - int n1Var = 42; - int n2Var = 43; - } -} -", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + + class Program + { + static void Main(string[] args) + { + int n1Var = 42; + int n2Var = 43; + } + } + + """, HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.Workspace, HangMitigatingCancellationToken); await TestServices.Debugger.SetBreakpointAsync(ProjectName, "Program.cs", "}", HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpInheritanceMarginTests.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpInheritanceMarginTests.cs index 59d2c974d6708..519ab60e49d84 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpInheritanceMarginTests.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpInheritanceMarginTests.cs @@ -32,14 +32,16 @@ public async Task TestNavigateInSource() await TestServices.SolutionExplorer.OpenFileAsync(project, "Test.cs", HangMitigatingCancellationToken); await TestServices.InheritanceMargin.SetTextAndEnsureGlyphsAppearAsync( -@" -interface IBar -{ -} + """ -class Implementation : IBar -{ -}", expectedGlyphsNumberInMargin: 2, HangMitigatingCancellationToken); + interface IBar + { + } + + class Implementation : IBar + { + } + """, expectedGlyphsNumberInMargin: 2, HangMitigatingCancellationToken); await TestServices.InheritanceMargin.ClickTheGlyphOnLine(2, HangMitigatingCancellationToken); @@ -60,17 +62,19 @@ public async Task TestMultipleItemsOnSameLine() await TestServices.SolutionExplorer.OpenFileAsync(project, "Test.cs", HangMitigatingCancellationToken); await TestServices.InheritanceMargin.SetTextAndEnsureGlyphsAppearAsync( -@" -using System; -interface IBar -{ - event EventHandler e1, e2; -} + """ -class Implementation : IBar -{ - public event EventHandler e1, e2; -}", expectedGlyphsNumberInMargin: 4, HangMitigatingCancellationToken); + using System; + interface IBar + { + event EventHandler e1, e2; + } + + class Implementation : IBar + { + public event EventHandler e1, e2; + } + """, expectedGlyphsNumberInMargin: 4, HangMitigatingCancellationToken); await TestServices.InheritanceMargin.ClickTheGlyphOnLine(5, HangMitigatingCancellationToken); @@ -94,16 +98,18 @@ public async Task TestNavigateToMetadata() await TestServices.SolutionExplorer.OpenFileAsync(project, "Test.cs", HangMitigatingCancellationToken); await TestServices.InheritanceMargin.SetTextAndEnsureGlyphsAppearAsync( -@" -using System.Collections; + """ -class Implementation : IEnumerable -{ - public IEnumerator GetEnumerator() - { - throw new NotImplementedException(); - } -}", expectedGlyphsNumberInMargin: 2, HangMitigatingCancellationToken); + using System.Collections; + + class Implementation : IEnumerable + { + public IEnumerator GetEnumerator() + { + throw new NotImplementedException(); + } + } + """, expectedGlyphsNumberInMargin: 2, HangMitigatingCancellationToken); await TestServices.InheritanceMargin.ClickTheGlyphOnLine(4, HangMitigatingCancellationToken); @@ -129,23 +135,27 @@ public async Task TestNavigateToDifferentProjects() var vbProjectName = "TestVBProject"; await TestServices.SolutionExplorer.AddProjectAsync( vbProjectName, WellKnownProjectTemplates.VisualBasicNetStandardClassLibrary, LanguageNames.VisualBasic, cancellationToken: HangMitigatingCancellationToken); - await TestServices.SolutionExplorer.AddFileAsync(vbProjectName, "Test.vb", @" -Namespace MyNs - Public Interface IBar - End Interface -End Namespace"); + await TestServices.SolutionExplorer.AddFileAsync(vbProjectName, "Test.vb", """ + + Namespace MyNs + Public Interface IBar + End Interface + End Namespace + """); await TestServices.SolutionExplorer.AddFileAsync(csharpProjectName, "Test.cs", cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.AddProjectReferenceAsync(csharpProjectName, vbProjectName, cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(csharpProjectName, "Test.cs", HangMitigatingCancellationToken); await TestServices.InheritanceMargin.SetTextAndEnsureGlyphsAppearAsync( -@" -using TestVBProject.MyNs; + """ -class Implementation : IBar -{ -}", expectedGlyphsNumberInMargin: 1, HangMitigatingCancellationToken); + using TestVBProject.MyNs; + + class Implementation : IBar + { + } + """, expectedGlyphsNumberInMargin: 1, HangMitigatingCancellationToken); await TestServices.InheritanceMargin.ClickTheGlyphOnLine(4, HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpIntelliSense.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpIntelliSense.cs index dca2852b8ab66..9ce1a553604fc 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpIntelliSense.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpIntelliSense.cs @@ -61,11 +61,13 @@ public async Task AtNamespaceLevel(bool showCompletionInArgumentLists) [IdeTheory, CombinatorialData] public async Task SpeculativeTInList(bool showCompletionInArgumentLists) { - await SetUpEditorAsync(@" -class C -{ - $$ -}", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + class C + { + $$ + } + """, HangMitigatingCancellationToken); var globalOptions = await TestServices.Shell.GetComponentModelServiceAsync(HangMitigatingCancellationToken); globalOptions.SetGlobalOption(CompletionOptionsStorage.TriggerInArgumentLists, LanguageNames.CSharp, showCompletionInArgumentLists); @@ -82,11 +84,13 @@ class C await TestServices.Input.SendAsync(' ', HangMitigatingCancellationToken); await TestServices.Input.SendAsync("Goo() { }", HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -class C -{ - public T Goo() { }$$ -}", + await TestServices.EditorVerifier.TextContainsAsync(""" + + class C + { + public T Goo() { }$$ + } + """, assertCaretPosition: true, HangMitigatingCancellationToken); } @@ -94,20 +98,22 @@ public T Goo() { }$$ [IdeTheory, CombinatorialData] public async Task VerifyCompletionListMembersOnStaticTypesAndCompleteThem(bool showCompletionInArgumentLists) { - await SetUpEditorAsync(@" -public class Program -{ - static void Main(string[] args) - { - NavigateTo$$ - } -} - -public static class NavigateTo -{ - public static void Search(string s){ } - public static void Navigate(int i){ } -}", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + public class Program + { + static void Main(string[] args) + { + NavigateTo$$ + } + } + + public static class NavigateTo + { + public static void Search(string s){ } + public static void Navigate(int i){ } + } + """, HangMitigatingCancellationToken); var globalOptions = await TestServices.Shell.GetComponentModelServiceAsync(HangMitigatingCancellationToken); globalOptions.SetGlobalOption(CompletionOptionsStorage.TriggerInArgumentLists, LanguageNames.CSharp, showCompletionInArgumentLists); @@ -235,15 +241,17 @@ public async Task NavigatingWithDownKey(bool showCompletionInArgumentLists) [IdeTheory, CombinatorialData] public async Task XmlDocCommentIntelliSense(bool showCompletionInArgumentLists) { - await SetUpEditorAsync(@" -class Class1 -{ - ///$$ - void Main(string[] args) - { - - } -}", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + class Class1 + { + ///$$ + void Main(string[] args) + { + + } + } + """, HangMitigatingCancellationToken); var globalOptions = await TestServices.Shell.GetComponentModelServiceAsync(HangMitigatingCancellationToken); globalOptions.SetGlobalOption(CompletionOptionsStorage.TriggerInArgumentLists, LanguageNames.CSharp, showCompletionInArgumentLists); @@ -272,10 +280,12 @@ void Main(string[] args) [IdeTheory, CombinatorialData] public async Task XmlTagCompletion(bool showCompletionInArgumentLists) { - await SetUpEditorAsync(@" -/// $$ -class C { } -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + /// $$ + class C { } + + """, HangMitigatingCancellationToken); var globalOptions = await TestServices.Shell.GetComponentModelServiceAsync(HangMitigatingCancellationToken); globalOptions.SetGlobalOption(CompletionOptionsStorage.TriggerInArgumentLists, LanguageNames.CSharp, showCompletionInArgumentLists); @@ -284,10 +294,12 @@ class C { } await TestServices.Input.SendAsync("", HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentLineTextAsync("/// $$", assertCaretPosition: true, HangMitigatingCancellationToken); - await SetUpEditorAsync(@" -/// $$ -class C { } -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + /// $$ + class C { } + + """, HangMitigatingCancellationToken); await TestServices.Input.SendAsync("$$", assertCaretPosition: true, HangMitigatingCancellationToken); @@ -296,14 +308,16 @@ class C { } [IdeTheory, CombinatorialData] public async Task SignatureHelpShowsUp(bool showCompletionInArgumentLists) { - await SetUpEditorAsync(@" -class Class1 -{ - void Main(string[] args) - { - $$ - } -}", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + class Class1 + { + void Main(string[] args) + { + $$ + } + } + """, HangMitigatingCancellationToken); var globalOptions = await TestServices.Shell.GetComponentModelServiceAsync(HangMitigatingCancellationToken); globalOptions.SetGlobalOption(CompletionOptionsStorage.TriggerInArgumentLists, LanguageNames.CSharp, showCompletionInArgumentLists); @@ -327,12 +341,14 @@ void Main(string[] args) [WorkItem("https://github.com/dotnet/roslyn/issues/33825")] public async Task CompletionUsesTrackingPointsInTheFaceOfAutomaticBraceCompletion(bool showCompletionInArgumentLists) { - await SetUpEditorAsync(@" -class Class1 -{ - void Main(string[] args) - $$ -}", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + class Class1 + { + void Main(string[] args) + $$ + } + """, HangMitigatingCancellationToken); var globalOptions = await TestServices.Shell.GetComponentModelServiceAsync(HangMitigatingCancellationToken); globalOptions.SetGlobalOption(CompletionOptionsStorage.TriggerInArgumentLists, LanguageNames.CSharp, showCompletionInArgumentLists); @@ -353,13 +369,15 @@ await TestServices.Input.SendAsync( await TestServices.Input.SendAsync('}', HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -class Class1 -{ - void Main(string[] args) - { - }$$ -}", + await TestServices.EditorVerifier.TextContainsAsync(""" + + class Class1 + { + void Main(string[] args) + { + }$$ + } + """, assertCaretPosition: true, HangMitigatingCancellationToken); } @@ -368,14 +386,16 @@ void Main(string[] args) [WorkItem("https://github.com/dotnet/roslyn/issues/33823")] public async Task CommitOnShiftEnter(bool showCompletionInArgumentLists) { - await SetUpEditorAsync(@" -class Class1 -{ - void Main(string[] args) - { - $$ - } -}", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + class Class1 + { + void Main(string[] args) + { + $$ + } + } + """, HangMitigatingCancellationToken); var globalOptions = await TestServices.Shell.GetComponentModelServiceAsync(HangMitigatingCancellationToken); globalOptions.SetGlobalOption(CompletionOptionsStorage.TriggerInArgumentLists, LanguageNames.CSharp, showCompletionInArgumentLists); @@ -390,15 +410,17 @@ await TestServices.Input.SendAsync( ], HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -class Class1 -{ - void Main(string[] args) - { - Main -$$ - } -}", + await TestServices.EditorVerifier.TextContainsAsync(""" + + class Class1 + { + void Main(string[] args) + { + Main + $$ + } + } + """, assertCaretPosition: true, HangMitigatingCancellationToken); } @@ -406,14 +428,16 @@ void Main(string[] args) [IdeTheory, CombinatorialData] public async Task LineBreakOnShiftEnter(bool showCompletionInArgumentLists) { - await SetUpEditorAsync(@" -class Class1 -{ - void Main(string[] args) - { - $$ - } -}", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + class Class1 + { + void Main(string[] args) + { + $$ + } + } + """, HangMitigatingCancellationToken); var globalOptions = await TestServices.Shell.GetComponentModelServiceAsync(HangMitigatingCancellationToken); globalOptions.SetGlobalOption(CompletionOptionsStorage.TriggerInArgumentLists, LanguageNames.CSharp, showCompletionInArgumentLists); @@ -428,15 +452,17 @@ await TestServices.Input.SendAsync( ], HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -class Class1 -{ - void Main(string[] args) - { - Main -$$ - } -}", + await TestServices.EditorVerifier.TextContainsAsync(""" + + class Class1 + { + void Main(string[] args) + { + Main + $$ + } + } + """, assertCaretPosition: true, HangMitigatingCancellationToken); @@ -445,11 +471,13 @@ void Main(string[] args) [IdeTheory, CombinatorialData] public async Task CommitOnLeftCurly(bool showCompletionInArgumentLists) { - await SetUpEditorAsync(@" -class Class1 -{ - $$ -}", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + class Class1 + { + $$ + } + """, HangMitigatingCancellationToken); var globalOptions = await TestServices.Shell.GetComponentModelServiceAsync(HangMitigatingCancellationToken); globalOptions.SetGlobalOption(CompletionOptionsStorage.TriggerInArgumentLists, LanguageNames.CSharp, showCompletionInArgumentLists); @@ -462,11 +490,13 @@ class Class1 await TestServices.Input.SendAsync("{", HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -class Class1 -{ - int P { get { $$} } -}", + await TestServices.EditorVerifier.TextContainsAsync(""" + + class Class1 + { + int P { get { $$} } + } + """, assertCaretPosition: true, HangMitigatingCancellationToken); } @@ -477,15 +507,17 @@ public async Task EnsureTheCaretIsVisibleAfterALongEdit(bool showCompletionInArg { var visibleColumns = await TestServices.Editor.GetVisibleColumnCountAsync(HangMitigatingCancellationToken); var variableName = new string('a', (int)(0.75 * visibleColumns)); - await SetUpEditorAsync($@" -public class Program -{{ - static void Main(string[] args) - {{ - var {variableName} = 0; - {variableName} = $$ - }} -}}", HangMitigatingCancellationToken); + await SetUpEditorAsync($$""" + + public class Program + { + static void Main(string[] args) + { + var {{variableName}} = 0; + {{variableName}} = $$ + } + } + """, HangMitigatingCancellationToken); var globalOptions = await TestServices.Shell.GetComponentModelServiceAsync(HangMitigatingCancellationToken); globalOptions.SetGlobalOption(CompletionOptionsStorage.TriggerInArgumentLists, LanguageNames.CSharp, showCompletionInArgumentLists); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpInteractive.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpInteractive.cs index a0edc3ee1ecb5..2cb5102f79b6f 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpInteractive.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpInteractive.cs @@ -42,46 +42,56 @@ public async Task ForEachStatement() [IdeFact] public async Task TopLevelMethod() { - await TestServices.InteractiveWindow.SubmitTextAsync(@"int Fac(int x) -{ - return x < 1 ? 1 : x * Fac(x - 1); -} -Fac(4)", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.SubmitTextAsync(""" + int Fac(int x) + { + return x < 1 ? 1 : x * Fac(x - 1); + } + Fac(4) + """, HangMitigatingCancellationToken); await TestServices.InteractiveWindow.WaitForLastReplOutputAsync($"{24}", HangMitigatingCancellationToken); } [IdeFact] public async Task WpfInteractionAsync() { - await TestServices.InteractiveWindow.SubmitTextAsync(@"#r ""WindowsBase"" -#r ""PresentationCore"" -#r ""PresentationFramework"" -#r ""System.Xaml""", HangMitigatingCancellationToken); - - await TestServices.InteractiveWindow.SubmitTextAsync(@"using System.Windows; -using System.Windows.Controls; -using System.Windows.Media; -using System.Windows.Media.Imaging;", HangMitigatingCancellationToken); - - await TestServices.InteractiveWindow.SubmitTextAsync(@"var w = new Window(); -w.Title = ""Hello World""; -w.FontFamily = new FontFamily(""Calibri""); -w.FontSize = 24; -w.Height = 300; -w.Width = 300; -w.Topmost = true; -w.Visibility = Visibility.Visible;", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.SubmitTextAsync(""" + #r "WindowsBase" + #r "PresentationCore" + #r "PresentationFramework" + #r "System.Xaml" + """, HangMitigatingCancellationToken); + + await TestServices.InteractiveWindow.SubmitTextAsync(""" + using System.Windows; + using System.Windows.Controls; + using System.Windows.Media; + using System.Windows.Media.Imaging; + """, HangMitigatingCancellationToken); + + await TestServices.InteractiveWindow.SubmitTextAsync(""" + var w = new Window(); + w.Title = "Hello World"; + w.FontFamily = new FontFamily("Calibri"); + w.FontSize = 24; + w.Height = 300; + w.Width = 300; + w.Topmost = true; + w.Visibility = Visibility.Visible; + """, HangMitigatingCancellationToken); var testValue = Guid.NewGuid(); - await TestServices.InteractiveWindow.SubmitTextAsync($@"var b = new Button(); -b.Content = ""{testValue}""; -b.Margin = new Thickness(40); -b.Click += (sender, e) => Console.WriteLine(""Hello, World!""); + await TestServices.InteractiveWindow.SubmitTextAsync($""" + var b = new Button(); + b.Content = "{testValue}"; + b.Margin = new Thickness(40); + b.Click += (sender, e) => Console.WriteLine("Hello, World!"); -var g = new Grid(); -g.Children.Add(b); -w.Content = g;", HangMitigatingCancellationToken); + var g = new Grid(); + g.Children.Add(b); + w.Content = g; + """, HangMitigatingCancellationToken); await AutomationElementHelper.ClickAutomationElementAsync(testValue.ToString(), recursive: true); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpInteractiveAsyncOutput.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpInteractiveAsyncOutput.cs index 8b8f971a2b334..884b0d709cc86 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpInteractiveAsyncOutput.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpInteractiveAsyncOutput.cs @@ -15,13 +15,15 @@ public async Task VerifyPreviousAndNextHistory() { await TestServices.InteractiveWindow.SubmitTextAsync(@"#cls", HangMitigatingCancellationToken); - await TestServices.InteractiveWindow.SubmitTextAsync(@"using System.Threading; -var t1 = new Thread(() => { for (int i = 0; ; i++) { Console.WriteLine('$'); Thread.Sleep(500); } }); -var t2 = new Thread(() => { for (int i = 0; ; i++) { Console.Write('$'); Thread.Sleep(101); } }); -var t3 = new Thread(() => { while (true) { Console.Write('\r'); Thread.Sleep(1200); } }); -t1.Start(); -t2.Start(); -t3.Start();", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.SubmitTextAsync(""" + using System.Threading; + var t1 = new Thread(() => { for (int i = 0; ; i++) { Console.WriteLine('$'); Thread.Sleep(500); } }); + var t2 = new Thread(() => { for (int i = 0; ; i++) { Console.Write('$'); Thread.Sleep(101); } }); + var t3 = new Thread(() => { while (true) { Console.Write('\r'); Thread.Sleep(1200); } }); + t1.Start(); + t2.Start(); + t3.Start(); + """, HangMitigatingCancellationToken); await TestServices.InteractiveWindow.SubmitTextAsync(@"#help", HangMitigatingCancellationToken); await Task.Delay(TimeSpan.FromSeconds(1)); @@ -50,12 +52,14 @@ public async Task VerifyPreviousAndNextHistory() await TestServices.InteractiveWindowVerifier.ReplPromptConsistencyAsync(prompt: "....", output: "$", HangMitigatingCancellationToken); - await TestServices.InteractiveWindow.SubmitTextAsync(@"t1.Abort(); -t1.Join(); -t2.Abort(); -t2.Join(); -t3.Abort(); -t3.Join();", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.SubmitTextAsync(""" + t1.Abort(); + t1.Join(); + t2.Abort(); + t2.Join(); + t3.Abort(); + t3.Join(); + """, HangMitigatingCancellationToken); await TestServices.InteractiveWindow.ClearReplTextAsync(HangMitigatingCancellationToken); await TestServices.InteractiveWindow.ResetAsync(HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpInteractiveBoxSelection.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpInteractiveBoxSelection.cs index 857ff0576c36b..a1180c3235866 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpInteractiveBoxSelection.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpInteractiveBoxSelection.cs @@ -34,14 +34,16 @@ public async Task TopLeftBottomRightPromptToSymbol() await TestServices.InteractiveWindow.PlaceCaretAsync("x", 0, occurrence: 0, extendSelection: true, selectBlock: true, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync(["__", VirtualKeyCode.ESCAPE, "|"], HangMitigatingCancellationToken); - Assert.Equal(@"__234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__|234567890ABCDEF -1234567890ABCDEF", await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); + Assert.Equal(""" + __234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __|234567890ABCDEF + 1234567890ABCDEF + """, await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); } [IdeFact] @@ -52,14 +54,16 @@ public async Task BottomRightTopLeftPromptToSymbol() await TestServices.InteractiveWindow.PlaceCaretAsync(">", 1, occurrence: 0, extendSelection: true, selectBlock: true, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync(["__", VirtualKeyCode.ESCAPE, "|"], HangMitigatingCancellationToken); - Assert.Equal(@"__|234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -1234567890ABCDEF", await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); + Assert.Equal(""" + __|234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + 1234567890ABCDEF + """, await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); } [IdeFact] @@ -70,14 +74,16 @@ public async Task TopRightBottomLeftPromptToSymbol() await TestServices.InteractiveWindow.PlaceCaretAsync("x", -2, occurrence: 0, extendSelection: true, selectBlock: true, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync(["__", VirtualKeyCode.ESCAPE, "|"], HangMitigatingCancellationToken); - Assert.Equal(@"__234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__|234567890ABCDEF -1234567890ABCDEF", await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); + Assert.Equal(""" + __234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __|234567890ABCDEF + 1234567890ABCDEF + """, await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); } [IdeFact] @@ -88,14 +94,16 @@ public async Task BottomLeftTopRightPromptToSymbol() await TestServices.InteractiveWindow.PlaceCaretAsync(">", 3, occurrence: 0, extendSelection: true, selectBlock: true, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync(["__", VirtualKeyCode.ESCAPE, "|"], HangMitigatingCancellationToken); - Assert.Equal(@"__|234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -1234567890ABCDEF", await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); + Assert.Equal(""" + __|234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + 1234567890ABCDEF + """, await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); } [IdeFact] @@ -106,14 +114,16 @@ public async Task TopLeftBottomRightSymbolToSymbol() await TestServices.InteractiveWindow.PlaceCaretAsync("e", 1, occurrence: 0, extendSelection: true, selectBlock: true, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync(["__", VirtualKeyCode.ESCAPE, "|"], HangMitigatingCancellationToken); - Assert.Equal(@"1234567890ABCDEF -1234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__|234567890ABCDEF -1234567890ABCDEF", await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); + Assert.Equal(""" + 1234567890ABCDEF + 1234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __|234567890ABCDEF + 1234567890ABCDEF + """, await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); } [IdeFact] @@ -124,14 +134,16 @@ public async Task BottomRightTopLeftSymbolToSymbol() await TestServices.InteractiveWindow.PlaceCaretAsync("s", -1, occurrence: 0, extendSelection: true, selectBlock: true, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync(["__", VirtualKeyCode.ESCAPE, "|"], HangMitigatingCancellationToken); - Assert.Equal(@"1234567890ABCDEF -1234567890ABCDEF -__|234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -1234567890ABCDEF", await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); + Assert.Equal(""" + 1234567890ABCDEF + 1234567890ABCDEF + __|234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + 1234567890ABCDEF + """, await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); } [IdeFact] @@ -142,14 +154,16 @@ public async Task TopRightBottomLeftSymbolToSymbol() await TestServices.InteractiveWindow.PlaceCaretAsync("e", -1, occurrence: 0, extendSelection: true, selectBlock: true, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync(["__", VirtualKeyCode.ESCAPE, "|"], HangMitigatingCancellationToken); - Assert.Equal(@"1234567890ABCDEF -1234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__|234567890ABCDEF -1234567890ABCDEF", await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); + Assert.Equal(""" + 1234567890ABCDEF + 1234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __|234567890ABCDEF + 1234567890ABCDEF + """, await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); } [IdeFact] @@ -160,14 +174,16 @@ public async Task BottomLeftTopRightSymbolToSymbol() await TestServices.InteractiveWindow.PlaceCaretAsync("s", 1, occurrence: 0, extendSelection: true, selectBlock: true, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync(["__", VirtualKeyCode.ESCAPE, "|"], HangMitigatingCancellationToken); - Assert.Equal(@"1234567890ABCDEF -1234567890ABCDEF -__|234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -__234567890ABCDEF -1234567890ABCDEF", await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); + Assert.Equal(""" + 1234567890ABCDEF + 1234567890ABCDEF + __|234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + __234567890ABCDEF + 1234567890ABCDEF + """, await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); } [IdeFact] @@ -178,14 +194,16 @@ public async Task TopLeftBottomRightSelection1() await TestServices.InteractiveWindow.PlaceCaretAsync("e", 2, occurrence: 0, extendSelection: true, selectBlock: true, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync("_", HangMitigatingCancellationToken); - Assert.Equal(@"1234567890ABCDEF -1234567890ABCDEF -_34567890ABCDEF -_34567890ABCDEF -_34567890ABCDEF -_34567890ABCDEF -_34567890ABCDEF -1234567890ABCDEF", await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); + Assert.Equal(""" + 1234567890ABCDEF + 1234567890ABCDEF + _34567890ABCDEF + _34567890ABCDEF + _34567890ABCDEF + _34567890ABCDEF + _34567890ABCDEF + 1234567890ABCDEF + """, await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); } [IdeFact] @@ -229,14 +247,16 @@ public async Task SelectionTouchingSubmissionBuffer() await TestServices.InteractiveWindow.PlaceCaretAsync("e", -1, occurrence: 0, extendSelection: true, selectBlock: true, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync("__", HangMitigatingCancellationToken); - Assert.Equal(@"1234567890ABCDEF -1234567890ABCDEF -__s234567890ABCDEF -__1234567890ABCDEF -__1234567890ABCDEF -__1234567890ABCDEF -__e234567890ABCDEF -1234567890ABCDEF", await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); + Assert.Equal(""" + 1234567890ABCDEF + 1234567890ABCDEF + __s234567890ABCDEF + __1234567890ABCDEF + __1234567890ABCDEF + __1234567890ABCDEF + __e234567890ABCDEF + 1234567890ABCDEF + """, await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); } [IdeFact] @@ -247,14 +267,16 @@ public async Task PrimaryPromptLongerThanSecondaryZeroWidthNextToPromptSelection await TestServices.InteractiveWindow.PlaceCaretAsync("e", -1, occurrence: 0, extendSelection: true, selectBlock: true, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync("__", HangMitigatingCancellationToken); - Assert.Equal(@"1234567890ABCDEF -1234567890ABCDEF -__s234567890ABCDEF -__1234567890ABCDEF -__1234567890ABCDEF -__1234567890ABCDEF -__e234567890ABCDEF -1234567890ABCDEF", await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); + Assert.Equal(""" + 1234567890ABCDEF + 1234567890ABCDEF + __s234567890ABCDEF + __1234567890ABCDEF + __1234567890ABCDEF + __1234567890ABCDEF + __e234567890ABCDEF + 1234567890ABCDEF + """, await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); } [IdeFact] @@ -265,14 +287,16 @@ public async Task Backspace() await TestServices.InteractiveWindow.PlaceCaretAsync("e", 0, occurrence: 0, extendSelection: true, selectBlock: true, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync([VirtualKeyCode.BACK, VirtualKeyCode.BACK], HangMitigatingCancellationToken); - Assert.Equal(@"1CDEF -1CDEF -1CDEF -1CDEF -1CDEF -1CDEF -1CDEF -1234567890ABCDEF", await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); + Assert.Equal(""" + 1CDEF + 1CDEF + 1CDEF + 1CDEF + 1CDEF + 1CDEF + 1CDEF + 1234567890ABCDEF + """, await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); } [IdeFact] @@ -283,14 +307,16 @@ public async Task BackspaceBehavesLikeDelete() await TestServices.InteractiveWindow.PlaceCaretAsync("e", 0, occurrence: 0, extendSelection: true, selectBlock: true, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync([VirtualKeyCode.BACK, VirtualKeyCode.BACK], HangMitigatingCancellationToken); - Assert.Equal(@"CDEF -CDEF -CDEF -CDEF -CDEF -CDEF -CDEF -1234567890ABCDEF", await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); + Assert.Equal(""" + CDEF + CDEF + CDEF + CDEF + CDEF + CDEF + CDEF + 1234567890ABCDEF + """, await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); } [IdeFact] @@ -326,63 +352,65 @@ public async Task LeftToRightReversedTypeCharacter() Assert.Equal(@"__4567890ABCDEF", await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); } - private async Task InsertInputWithXAtLeftAsync(CancellationToken cancellationToken) - { - await TestServices.InteractiveWindow.InsertCodeAsync(@"1234567890ABCDEF -1234567890ABCDEF -1234567890ABCDEF -1234567890ABCDEF -1234567890ABCDEF -1234567890ABCDEF -x234567890ABCDEF -1234567890ABCDEF", cancellationToken); - } - - private async Task InsertInputWithSAndEAtLeftAsync(CancellationToken cancellationToken) - { - await TestServices.InteractiveWindow.InsertCodeAsync(@"1234567890ABCDEF -1234567890ABCDEF -s234567890ABCDEF -1234567890ABCDEF -1234567890ABCDEF -1234567890ABCDEF -e234567890ABCDEF -1234567890ABCDEF", cancellationToken); - } - - private async Task InsertInputWithSAndEInTheMiddleAsync(CancellationToken cancellationToken) - { - await TestServices.InteractiveWindow.InsertCodeAsync(@"12s4567890ABCDEF -1234567890ABCDEF -1234567890ABCDEF -1234567890ABCDEF -1234567890ABCDEF -1234567890ABCDEF -1234567890AeCDEF -1234567890ABCDEF", cancellationToken); - } - - private async Task InsertInputWithEInTheMiddleAsync(CancellationToken cancellationToken) - { - await TestServices.InteractiveWindow.InsertCodeAsync(@"1234567890ABCDEF -1234567890ABCDEF -1234567890ABCDEF -1234567890ABCDEF -1234567890ABCDEF -1234567890ABCDEF -1234567890AeCDEF -1234567890ABCDEF", cancellationToken); - } + private Task InsertInputWithXAtLeftAsync(CancellationToken cancellationToken) + => TestServices.InteractiveWindow.InsertCodeAsync(""" + 1234567890ABCDEF + 1234567890ABCDEF + 1234567890ABCDEF + 1234567890ABCDEF + 1234567890ABCDEF + 1234567890ABCDEF + x234567890ABCDEF + 1234567890ABCDEF + """, cancellationToken); + + private Task InsertInputWithSAndEAtLeftAsync(CancellationToken cancellationToken) + => TestServices.InteractiveWindow.InsertCodeAsync(""" + 1234567890ABCDEF + 1234567890ABCDEF + s234567890ABCDEF + 1234567890ABCDEF + 1234567890ABCDEF + 1234567890ABCDEF + e234567890ABCDEF + 1234567890ABCDEF + """, cancellationToken); + + private Task InsertInputWithSAndEInTheMiddleAsync(CancellationToken cancellationToken) + => TestServices.InteractiveWindow.InsertCodeAsync(""" + 12s4567890ABCDEF + 1234567890ABCDEF + 1234567890ABCDEF + 1234567890ABCDEF + 1234567890ABCDEF + 1234567890ABCDEF + 1234567890AeCDEF + 1234567890ABCDEF + """, cancellationToken); + + private Task InsertInputWithEInTheMiddleAsync(CancellationToken cancellationToken) + => TestServices.InteractiveWindow.InsertCodeAsync(""" + 1234567890ABCDEF + 1234567890ABCDEF + 1234567890ABCDEF + 1234567890ABCDEF + 1234567890ABCDEF + 1234567890ABCDEF + 1234567890AeCDEF + 1234567890ABCDEF + """, cancellationToken); private async Task VerifyOriginalCodeWithSAndEAtLeftAsync(CancellationToken cancellationToken) { - Assert.Equal(@"1234567890ABCDEF -1234567890ABCDEF -s234567890ABCDEF -1234567890ABCDEF -1234567890ABCDEF -1234567890ABCDEF -e234567890ABCDEF -1234567890ABCDEF", await TestServices.InteractiveWindow.GetLastReplInputAsync(cancellationToken)); + Assert.Equal(""" + 1234567890ABCDEF + 1234567890ABCDEF + s234567890ABCDEF + 1234567890ABCDEF + 1234567890ABCDEF + 1234567890ABCDEF + e234567890ABCDEF + 1234567890ABCDEF + """, await TestServices.InteractiveWindow.GetLastReplInputAsync(cancellationToken)); } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpInteractiveCommands.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpInteractiveCommands.cs index e113da6fd7af5..10ebe502f30d5 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpInteractiveCommands.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpInteractiveCommands.cs @@ -17,7 +17,9 @@ public async Task VerifyPreviousAndNextHistory() { await TestServices.InteractiveWindow.SubmitTextAsync("1 + 2", HangMitigatingCancellationToken); await TestServices.InteractiveWindow.SubmitTextAsync("1.ToString()", HangMitigatingCancellationToken); - await TestServices.InteractiveWindow.WaitForLastReplOutputAsync("\"1\"", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.WaitForLastReplOutputAsync(""" + "1" + """, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync((VirtualKeyCode.UP, VirtualKeyCode.MENU), HangMitigatingCancellationToken); Assert.Equal("1.ToString()", await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); await TestServices.Input.SendWithoutActivateAsync(VirtualKeyCode.RETURN, HangMitigatingCancellationToken); @@ -26,7 +28,9 @@ public async Task VerifyPreviousAndNextHistory() // check the previous result await TestServices.InteractiveWindow.WaitForLastReplInputAsync("", HangMitigatingCancellationToken); - await TestServices.InteractiveWindow.WaitForLastReplOutputAsync("\"1\"", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.WaitForLastReplOutputAsync(""" + "1" + """, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync((VirtualKeyCode.UP, VirtualKeyCode.MENU), HangMitigatingCancellationToken); Assert.Equal("1.ToString()", await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); await TestServices.Input.SendWithoutActivateAsync((VirtualKeyCode.UP, VirtualKeyCode.MENU), HangMitigatingCancellationToken); @@ -36,7 +40,9 @@ public async Task VerifyPreviousAndNextHistory() await TestServices.Input.SendWithoutActivateAsync((VirtualKeyCode.DOWN, VirtualKeyCode.MENU), HangMitigatingCancellationToken); Assert.Equal("1.ToString()", await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); await TestServices.Input.SendWithoutActivateAsync(VirtualKeyCode.RETURN, HangMitigatingCancellationToken); - await TestServices.InteractiveWindow.WaitForLastReplOutputAsync("\"1\"", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.WaitForLastReplOutputAsync(""" + "1" + """, HangMitigatingCancellationToken); } [IdeFact] diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpInteractiveDirectives.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpInteractiveDirectives.cs index 0ae62f0ab2aa8..90b0843b601f1 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpInteractiveDirectives.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpInteractiveDirectives.cs @@ -4,6 +4,7 @@ using System.Threading.Tasks; using Microsoft.VisualStudio.IntegrationTest.Utilities; +using Roslyn.Test.Utilities; using Roslyn.Utilities; using Roslyn.VisualStudio.NewIntegrationTests.InProcess; using WindowsInput.Native; @@ -46,8 +47,10 @@ public async Task VerifyHostCommandsCompletionList() item => Assert.DoesNotContain(item, completionItems)); await TestServices.InteractiveWindow.ClearReplTextAsync(HangMitigatingCancellationToken); - await TestServices.InteractiveWindow.InsertCodeAsync(@"int x = 1; // -#", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.InsertCodeAsync(""" + int x = 1; // + # + """, HangMitigatingCancellationToken); await TestServices.InteractiveWindow.InvokeCompletionListAsync(HangMitigatingCancellationToken); completionItems = (await TestServices.InteractiveWindow.GetCompletionItemsAsync(HangMitigatingCancellationToken)).SelectAsArray(item => item.DisplayText); @@ -81,10 +84,14 @@ public async Task VerifyHostCommandsCompletionList() [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/71641")] public async Task VerifyHashRDirective() { - await TestServices.InteractiveWindow.SubmitTextAsync("#r \"System.Numerics\"", HangMitigatingCancellationToken); - await TestServices.InteractiveWindow.SubmitTextAsync(@"using System.Numerics; -var bigInt = new BigInteger(); -bigInt", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.SubmitTextAsync(""" + #r "System.Numerics" + """, HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.SubmitTextAsync(""" + using System.Numerics; + var bigInt = new BigInteger(); + bigInt + """, HangMitigatingCancellationToken); await TestServices.InteractiveWindow.WaitForLastReplOutputAsync("[0]", HangMitigatingCancellationToken); } @@ -92,11 +99,15 @@ public async Task VerifyHashRDirective() [IdeFact] public async Task VerifyLocalDeclarationWithTheSameNameHidesImportedMembersFromHashR() { - await TestServices.InteractiveWindow.SubmitTextAsync("#r \"System.Numerics\"", HangMitigatingCancellationToken); - await TestServices.InteractiveWindow.SubmitTextAsync(@"using System.Numerics; -class Complex { public int goo() { return 4; } } -var comp = new Complex(); -comp.goo()", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.SubmitTextAsync(""" + #r "System.Numerics" + """, HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.SubmitTextAsync(""" + using System.Numerics; + class Complex { public int goo() { return 4; } } + var comp = new Complex(); + comp.goo() + """, HangMitigatingCancellationToken); await TestServices.InteractiveWindow.WaitForLastReplOutputAsync("4", HangMitigatingCancellationToken); } @@ -104,24 +115,34 @@ public async Task VerifyLocalDeclarationWithTheSameNameHidesImportedMembersFromH [IdeFact] public async Task VerifyLocalDeclarationInCsxFileWithTheSameNameHidesImportedMembersFromHashR() { - await TestServices.InteractiveWindow.SubmitTextAsync("#r \"System.Numerics\"", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.SubmitTextAsync(""" + #r "System.Numerics" + """, HangMitigatingCancellationToken); await TestServices.InteractiveWindow.SubmitTextAsync("using System.Numerics;", HangMitigatingCancellationToken); using var temporaryTextFile = new TemporaryTextFile( "directivesScenario4.csx", "class Complex { public int goo() { return 4; } }"); temporaryTextFile.Create(); - await TestServices.InteractiveWindow.SubmitTextAsync(string.Format("#load \"{0}\"", temporaryTextFile.FullName), HangMitigatingCancellationToken); - await TestServices.InteractiveWindow.SubmitTextAsync(@"var comp = new Complex(); -comp.goo()", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.SubmitTextAsync(string.Format(""" + #load "{0}" + """, temporaryTextFile.FullName), HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.SubmitTextAsync(""" + var comp = new Complex(); + comp.goo() + """, HangMitigatingCancellationToken); await TestServices.InteractiveWindow.WaitForLastReplOutputAsync("4", HangMitigatingCancellationToken); } [IdeFact] public async Task VerifyAssembliesReferencedByDefault() { - await TestServices.InteractiveWindow.SubmitTextAsync(@"using System.Diagnostics; -Process.GetCurrentProcess().ProcessName", HangMitigatingCancellationToken); - await TestServices.InteractiveWindow.WaitForLastReplOutputAsync("\"InteractiveHost64\"", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.SubmitTextAsync(""" + using System.Diagnostics; + Process.GetCurrentProcess().ProcessName + """, HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.WaitForLastReplOutputAsync(""" + "InteractiveHost64" + """, HangMitigatingCancellationToken); } [IdeFact] @@ -131,7 +152,9 @@ public async Task VerifyHashLoadDirective() "directivesScenario6.csx", "System.Console.WriteLine(2);"); temporaryTextFile.Create(); - await TestServices.InteractiveWindow.SubmitTextAsync(string.Format("#load \"{0}\"", temporaryTextFile.FullName), HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.SubmitTextAsync(string.Format(""" + #load "{0}" + """, temporaryTextFile.FullName), HangMitigatingCancellationToken); await TestServices.InteractiveWindow.WaitForLastReplOutputAsync("2", HangMitigatingCancellationToken); await TestServices.InteractiveWindow.SubmitTextAsync("#load text", HangMitigatingCancellationToken); await TestServices.InteractiveWindow.WaitForLastReplOutputAsync("(1,7): error CS7010: Quoted file name expected", HangMitigatingCancellationToken); @@ -156,38 +179,36 @@ public async Task VerifySquiggleAndErrorMessageUnderIncorrectDirective() public async Task VerifyHashHelpDirectiveOutputNoSquigglesUnderHashHelp() { await TestServices.InteractiveWindow.SubmitTextAsync("#help", HangMitigatingCancellationToken); - await TestServices.InteractiveWindow.WaitForLastReplOutputAsync(@"Keyboard shortcuts: - Enter If the current submission appears to be complete, evaluate it. Otherwise, insert a new line. - Ctrl-Enter Within the current submission, evaluate the current submission. - Within a previous submission, append the previous submission to the current submission. - Shift-Enter Insert a new line. - Escape Clear the current submission. - Alt-UpArrow Replace the current submission with a previous submission. - Alt-DownArrow Replace the current submission with a subsequent submission (after having previously navigated backwards). - Ctrl-Alt-UpArrow Replace the current submission with a previous submission beginning with the same text. - Ctrl-Alt-DownArrow Replace the current submission with a subsequent submission beginning with the same text (after having previously navigated backwards). - Ctrl-K, Ctrl-Enter Paste the selection at the end of interactive buffer, leave caret at the end of input. - Ctrl-E, Ctrl-Enter Paste and execute the selection before any pending input in the interactive buffer. - Ctrl-A First press, select the submission containing the cursor. Second press, select all text in the window. -REPL commands: - #cls, #clear Clears the contents of the editor window, leaving history and execution context intact. - #help Display help on specified command, or all available commands and key bindings if none specified. - #reset Reset the execution environment to the initial state and keep history, with the option to switch the runtime of the host process. -Script directives: - #r Add a metadata reference to specified assembly and all its dependencies, e.g. #r ""myLib.dll"". - #load Load specified script file and execute it, e.g. #load ""myScript.csx"".", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.WaitForLastReplOutputAsync(""" + Keyboard shortcuts: + Enter If the current submission appears to be complete, evaluate it. Otherwise, insert a new line. + Ctrl-Enter Within the current submission, evaluate the current submission. + Within a previous submission, append the previous submission to the current submission. + Shift-Enter Insert a new line. + Escape Clear the current submission. + Alt-UpArrow Replace the current submission with a previous submission. + Alt-DownArrow Replace the current submission with a subsequent submission (after having previously navigated backwards). + Ctrl-Alt-UpArrow Replace the current submission with a previous submission beginning with the same text. + Ctrl-Alt-DownArrow Replace the current submission with a subsequent submission beginning with the same text (after having previously navigated backwards). + Ctrl-K, Ctrl-Enter Paste the selection at the end of interactive buffer, leave caret at the end of input. + Ctrl-E, Ctrl-Enter Paste and execute the selection before any pending input in the interactive buffer. + Ctrl-A First press, select the submission containing the cursor. Second press, select all text in the window. + REPL commands: + #cls, #clear Clears the contents of the editor window, leaving history and execution context intact. + #help Display help on specified command, or all available commands and key bindings if none specified. + #reset Reset the execution environment to the initial state and keep history, with the option to switch the runtime of the host process. + Script directives: + #r Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll". + #load Load specified script file and execute it, e.g. #load "myScript.csx". + """, HangMitigatingCancellationToken); // TODO implement GetErrorListErrorCount: https://github.com/dotnet/roslyn/issues/18035 // VerifyErrorCount(0); } [IdeFact] - public async Task VerifyHashCls() - { - await TestServices.InteractiveWindow.SubmitTextAsync("#cls", HangMitigatingCancellationToken); - // TODO implement GetErrorListErrorCount: https://github.com/dotnet/roslyn/issues/18035 - // VerifyErrorCount(0); - } + public Task VerifyHashCls() + => TestServices.InteractiveWindow.SubmitTextAsync("#cls", HangMitigatingCancellationToken); [IdeFact] public async Task VerifyHashReset() @@ -195,8 +216,10 @@ public async Task VerifyHashReset() await TestServices.InteractiveWindow.SubmitTextAsync("1+1", HangMitigatingCancellationToken); await TestServices.InteractiveWindow.WaitForLastReplOutputAsync("2", HangMitigatingCancellationToken); await TestServices.InteractiveWindow.SubmitTextAsync("#reset", HangMitigatingCancellationToken); - await TestServices.InteractiveWindow.WaitForLastReplOutputAsync(@"Resetting execution engine. -Loading context from 'CSharpInteractive.rsp'.", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.WaitForLastReplOutputAsync(""" + Resetting execution engine. + Loading context from 'CSharpInteractive.rsp'. + """, HangMitigatingCancellationToken); // TODO implement GetErrorListErrorCount: https://github.com/dotnet/roslyn/issues/18035 // VerifyErrorCount(0); } @@ -205,8 +228,10 @@ await TestServices.InteractiveWindow.WaitForLastReplOutputAsync(@"Resetting exec public async Task VerifyDisplayCommandUsageOutputNoSquigglesUnderSlashHelp() { await TestServices.InteractiveWindow.SubmitTextAsync("#reset /help", HangMitigatingCancellationToken); - await TestServices.InteractiveWindow.WaitForLastReplOutputContainsAsync(@"Usage: - #reset [noconfig]", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.WaitForLastReplOutputContainsAsync(""" + Usage: + #reset [noconfig] + """, HangMitigatingCancellationToken); // TODO implement GetErrorListErrorCount: https://github.com/dotnet/roslyn/issues/18035 // VerifyErrorCount(0); await TestServices.InteractiveWindow.SubmitTextAsync("#load /help", HangMitigatingCancellationToken); @@ -216,16 +241,18 @@ await TestServices.InteractiveWindow.WaitForLastReplOutputContainsAsync(@"Usage: [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/8281")] public async Task VerifyNoSquigglesErrorMessagesAndIntellisenseFeaturesContinueWorkingAfterReset() { - await TestServices.InteractiveWindow.SubmitTextAsync(@"using static System.Console; -/// innertext -/// -/// --> -/// > -/// -public static void Main(string[] args) - { - WriteLine(""Hello World""); - }", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.InsertCodeAsync(""" + using System.Console; + /// innertext + /// + /// + /// + /// > + /// + public static void Main(string[] args) + { + WriteLine("Hello World"); + } + """, HangMitigatingCancellationToken); await TestServices.InteractiveWindow.PlaceCaretAsync("using", HangMitigatingCancellationToken); await TestServices.InteractiveWindowVerifier.CurrentTokenTypeAsync(tokenType: "keyword", HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpReplIdeFeatures.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpReplIdeFeatures.cs index 4a3321c30c06e..ac5036da0f0ee 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpReplIdeFeatures.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpReplIdeFeatures.cs @@ -48,8 +48,10 @@ public async Task VerifyQuickInfoOnStringDocCommentsFromMetadata() [IdeFact] public async Task International() { - await TestServices.InteractiveWindow.InsertCodeAsync(@"delegate void العربية(); -العربية func = () => System.Console.WriteLine(2);", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.InsertCodeAsync(""" + delegate void العربية(); + العربية func = () => System.Console.WriteLine(2); + """, HangMitigatingCancellationToken); await TestServices.InteractiveWindow.PlaceCaretAsync("func", charsOffset: -1, HangMitigatingCancellationToken); await TestServices.InteractiveWindow.InvokeQuickInfoAsync(HangMitigatingCancellationToken); var s = await TestServices.InteractiveWindow.GetQuickInfoAsync(HangMitigatingCancellationToken); @@ -158,15 +160,17 @@ public async Task HighlightRefsMultipleSubmisionsVerifyRenameTagsOnRedefinedVari [IdeFact] public async Task DisabledCommandsPart1() { - await TestServices.InteractiveWindow.InsertCodeAsync(@"public class Class -{ - int field; + await TestServices.InteractiveWindow.InsertCodeAsync(""" + public class Class + { + int field; - public void Method(int x) - { - int abc = 1 + 1; - } -}", HangMitigatingCancellationToken); + public void Method(int x) + { + int abc = 1 + 1; + } + } + """, HangMitigatingCancellationToken); await TestServices.InteractiveWindow.PlaceCaretAsync("abc", charsOffset: 0, HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.Workspace, HangMitigatingCancellationToken); @@ -201,9 +205,11 @@ await TestServices.InteractiveWindowVerifier.CodeActionsAsync( new string[] { "using System.Collections;", "System.Collections.ArrayList" }, "using System.Collections;", cancellationToken: HangMitigatingCancellationToken); - Assert.Equal(@"using System.Collections; + Assert.Equal(""" + using System.Collections; -typeof(ArrayList)", await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); + typeof(ArrayList) + """, await TestServices.InteractiveWindow.GetLastReplInputAsync(HangMitigatingCancellationToken)); } [IdeFact] diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpReplIntellisense.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpReplIntellisense.cs index e1f382362804c..700d7097b9e4e 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpReplIntellisense.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpReplIntellisense.cs @@ -32,7 +32,9 @@ public async Task VerifyCompletionListOnEmptyTextAtTopLevel() [IdeFact] public async Task VerifySharpRCompletionList() { - await TestServices.InteractiveWindow.InsertCodeAsync("#r \"", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.InsertCodeAsync(""" + #r " + """, HangMitigatingCancellationToken); await TestServices.InteractiveWindow.InvokeCompletionListAsync(HangMitigatingCancellationToken); Assert.Contains("System", (await TestServices.InteractiveWindow.GetCompletionItemsAsync(HangMitigatingCancellationToken)).Select(item => item.DisplayText)); } @@ -51,9 +53,11 @@ public async Task VerifyCommitCompletionOnTopLevel() [IdeFact] public async Task VerifyCompletionListForAmbiguousParsingCases() { - await TestServices.InteractiveWindow.InsertCodeAsync(@"class C { } -public delegate R Del(T arg); -Del(T arg); + Del item.DisplayText)); } @@ -61,7 +65,9 @@ await TestServices.InteractiveWindow.InsertCodeAsync(@"class C { } [IdeFact] public async Task VerifySharpLoadCompletionList() { - await TestServices.InteractiveWindow.InsertCodeAsync("#load \"", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.InsertCodeAsync(""" + #load " + """, HangMitigatingCancellationToken); await TestServices.InteractiveWindow.InvokeCompletionListAsync(HangMitigatingCancellationToken); Assert.Contains("C:", (await TestServices.InteractiveWindow.GetCompletionItemsAsync(HangMitigatingCancellationToken)).Select(item => item.DisplayText)); } @@ -90,7 +96,9 @@ public async Task VerifyCompletionListForLoadMembers() "c.csx", "int x = 2; class Complex { public int goo() { return 4; } }"); temporaryTextFile.Create(); - await TestServices.InteractiveWindow.SubmitTextAsync(string.Format("#load \"{0}\"", temporaryTextFile.FullName), HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.SubmitTextAsync(string.Format(""" + #load "{0}" + """, temporaryTextFile.FullName), HangMitigatingCancellationToken); await TestServices.InteractiveWindow.InvokeCompletionListAsync(HangMitigatingCancellationToken); var completionItems = (await TestServices.InteractiveWindow.GetCompletionItemsAsync(HangMitigatingCancellationToken)).SelectAsArray(item => item.DisplayText); Assert.All( diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpSendToInteractive.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpSendToInteractive.cs index d6f54115c87d9..fde1ad8477d70 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpSendToInteractive.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpSendToInteractive.cs @@ -26,35 +26,37 @@ public override async Task InitializeAsync() var project = ProjectName; await TestServices.SolutionExplorer.AddProjectAsync(project, WellKnownProjectTemplates.ConsoleApplication, LanguageNames.CSharp, HangMitigatingCancellationToken); - await TestServices.Editor.SetTextAsync(@"using System; - - namespace TestProj - { - public class Program - { - public static void Main(string[] args) - { - /* 1 */int x = 1;/* 2 */ - - /* 3 */int y = 2; - int z = 3;/* 4 */ - - /* 5 */ string a = ""alpha""; - string b = ""x *= 4; "";/* 6 */ - - /* 7 */int j = 7;/* 8 */ - } - } - - public class C - { - public string M() - { - return ""C.M()""; - } - } - } -", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + using System; + + namespace TestProj + { + public class Program + { + public static void Main(string[] args) + { + /* 1 */int x = 1;/* 2 */ + + /* 3 */int y = 2; + int z = 3;/* 4 */ + + /* 5 */ string a = "alpha"; + string b = "x *= 4; ";/* 6 */ + + /* 7 */int j = 7;/* 8 */ + } + } + + public class C + { + public string M() + { + return "C.M()"; + } + } + } + + """, HangMitigatingCancellationToken); await TestServices.Editor.ActivateAsync(HangMitigatingCancellationToken); await TestServices.InteractiveWindow.SubmitTextAsync("using System;", HangMitigatingCancellationToken); @@ -73,7 +75,9 @@ public async Task SendSingleLineSubmissionToInteractive() await TestServices.InteractiveWindow.ClearReplTextAsync(HangMitigatingCancellationToken); await TestServices.InteractiveWindow.SubmitTextAsync("x.ToString()", HangMitigatingCancellationToken); - await TestServices.InteractiveWindow.WaitForLastReplOutputContainsAsync("\"1\"", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.WaitForLastReplOutputContainsAsync(""" + "1" + """, HangMitigatingCancellationToken); } [IdeFact] @@ -89,9 +93,13 @@ public async Task SendMultipleLineSubmissionToInteractive() await TestServices.InteractiveWindow.ClearReplTextAsync(HangMitigatingCancellationToken); await TestServices.InteractiveWindow.SubmitTextAsync("y.ToString()", HangMitigatingCancellationToken); - await TestServices.InteractiveWindow.WaitForLastReplOutputContainsAsync("\"2\"", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.WaitForLastReplOutputContainsAsync(""" + "2" + """, HangMitigatingCancellationToken); await TestServices.InteractiveWindow.SubmitTextAsync("z.ToString()", HangMitigatingCancellationToken); - await TestServices.InteractiveWindow.WaitForLastReplOutputContainsAsync("\"3\"", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.WaitForLastReplOutputContainsAsync(""" + "3" + """, HangMitigatingCancellationToken); } [IdeFact] @@ -107,8 +115,12 @@ public async Task SendMultipleLineBlockSelectedSubmissionToInteractive() await TestServices.InteractiveWindow.WaitForLastReplOutputAsync("\n. x *= 4; ", HangMitigatingCancellationToken); await TestServices.InteractiveWindow.ClearReplTextAsync(HangMitigatingCancellationToken); - await TestServices.InteractiveWindow.SubmitTextAsync("a + \"s\"", HangMitigatingCancellationToken); - await TestServices.InteractiveWindow.WaitForLastReplOutputContainsAsync("\"alphas\"", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.SubmitTextAsync(""" + a + "s" + """, HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.WaitForLastReplOutputContainsAsync(""" + "alphas" + """, HangMitigatingCancellationToken); await TestServices.InteractiveWindow.SubmitTextAsync("b", HangMitigatingCancellationToken); await TestServices.InteractiveWindow.WaitForLastReplOutputContainsAsync("CS0103", HangMitigatingCancellationToken); await TestServices.InteractiveWindow.SubmitTextAsync("x", HangMitigatingCancellationToken); @@ -128,7 +140,9 @@ public async Task SendToInteractiveWithKeyboardShortcut() await TestServices.InteractiveWindow.ClearReplTextAsync(HangMitigatingCancellationToken); await TestServices.InteractiveWindow.SubmitTextAsync("j.ToString()", HangMitigatingCancellationToken); - await TestServices.InteractiveWindow.WaitForLastReplOutputContainsAsync("\"7\"", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.WaitForLastReplOutputContainsAsync(""" + "7" + """, HangMitigatingCancellationToken); } [IdeFact] @@ -180,7 +194,9 @@ public async Task ExecuteMultipleLineBlockSelectedSubmissionInInteractiveWhilePr await TestServices.InteractiveWindow.ClearReplTextAsync(HangMitigatingCancellationToken); await TestServices.InteractiveWindow.SubmitTextAsync("a", HangMitigatingCancellationToken); - await TestServices.InteractiveWindow.WaitForLastReplOutputAsync("\"alpha\"", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.WaitForLastReplOutputAsync(""" + "alpha" + """, HangMitigatingCancellationToken); await TestServices.InteractiveWindow.SubmitTextAsync("b", HangMitigatingCancellationToken); await TestServices.InteractiveWindow.WaitForLastReplOutputContainsAsync("CS0103", HangMitigatingCancellationToken); @@ -208,22 +224,25 @@ public async Task ExecuteInInteractiveWithKeyboardShortcut() public async Task AddAssemblyReferenceAndTypesToInteractive() { await TestServices.InteractiveWindow.ClearReplTextAsync(HangMitigatingCancellationToken); - await TestServices.InteractiveWindow.SubmitTextAsync("#r \"System.Numerics\"", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.SubmitTextAsync(""" + #r "System.Numerics" + """, HangMitigatingCancellationToken); await TestServices.InteractiveWindow.SubmitTextAsync("Console.WriteLine(new System.Numerics.BigInteger(42));", HangMitigatingCancellationToken); await TestServices.InteractiveWindow.WaitForLastReplOutputAsync("42", HangMitigatingCancellationToken); await TestServices.InteractiveWindow.SubmitTextAsync("public class MyClass { public string MyFunc() { return \"MyClass.MyFunc()\"; } }", HangMitigatingCancellationToken); await TestServices.InteractiveWindow.SubmitTextAsync("(new MyClass()).MyFunc()", HangMitigatingCancellationToken); - await TestServices.InteractiveWindow.WaitForLastReplOutputAsync("\"MyClass.MyFunc()\"", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.WaitForLastReplOutputAsync(""" + "MyClass.MyFunc()" + """, HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.SolutionCrawlerLegacy, HangMitigatingCancellationToken); } [IdeFact] public async Task ResetInteractiveFromProjectAndVerify() { - var assembly = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; var project = ProjectName; - await TestServices.SolutionExplorer.AddMetadataReferenceAsync(assembly, project, HangMitigatingCancellationToken); + await TestServices.SolutionExplorer.AddMetadataReferenceAsync("System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", project, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.SelectItemAsync(ProjectName, HangMitigatingCancellationToken); await TestServices.Shell.ExecuteCommandAsync(HangMitigatingCancellationToken); @@ -235,11 +254,15 @@ public async Task ResetInteractiveFromProjectAndVerify() await TestServices.InteractiveWindow.WaitForLastReplOutputContainsAsync("CS0103", HangMitigatingCancellationToken); await TestServices.InteractiveWindow.SubmitTextAsync("(new TestProj.C()).M()", HangMitigatingCancellationToken); - await TestServices.InteractiveWindow.WaitForLastReplOutputAsync("\"C.M()\"", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.WaitForLastReplOutputAsync(""" + "C.M()" + """, HangMitigatingCancellationToken); await TestServices.InteractiveWindow.SubmitTextAsync("System.Windows.Forms.Form f = new System.Windows.Forms.Form(); f.Text = \"goo\";", HangMitigatingCancellationToken); await TestServices.InteractiveWindow.SubmitTextAsync("f.Text", HangMitigatingCancellationToken); - await TestServices.InteractiveWindow.WaitForLastReplOutputAsync("\"goo\"", HangMitigatingCancellationToken); + await TestServices.InteractiveWindow.WaitForLastReplOutputAsync(""" + "goo" + """, HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.SolutionCrawlerLegacy, HangMitigatingCancellationToken); } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpSignatureHelp.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpSignatureHelp.cs index aa14e1b820e43..29ee385311efc 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpSignatureHelp.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpSignatureHelp.cs @@ -26,43 +26,45 @@ public CSharpSignatureHelp() [IdeFact] public async Task MethodSignatureHelp() { - await SetUpEditorAsync(@" -using System; -class C -{ - void M() - { - GenericMethod(null, 1); - $$ - } - C Method(int i) { return null; } - - /// - /// Hello World 2.0! - /// - /// an integer, preferably 42. - /// an integer, anything you like. - /// returns an object of type C - C Method(int i, int i2) { return null; } - - /// - /// Hello Generic World! - /// - /// Type Param 1 - /// Param 1 of type T1 - /// Null - C GenericMethod(T1 i) { return null; } - C GenericMethod(T1 i, T2 i2) { return null; } - - /// - /// Complex Method Params - /// - /// Jagged MultiDimensional Array - /// Out Array - /// Dynamic and Params param - /// Null - void OutAndParam(ref string[][,] strings, out string[] outArr, params dynamic d) {outArr = null;} -}", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + using System; + class C + { + void M() + { + GenericMethod(null, 1); + $$ + } + C Method(int i) { return null; } + + /// + /// Hello World 2.0! + /// + /// an integer, preferably 42. + /// an integer, anything you like. + /// returns an object of type C + C Method(int i, int i2) { return null; } + + /// + /// Hello Generic World! + /// + /// Type Param 1 + /// Param 1 of type T1 + /// Null + C GenericMethod(T1 i) { return null; } + C GenericMethod(T1 i, T2 i2) { return null; } + + /// + /// Complex Method Params + /// + /// Jagged MultiDimensional Array + /// Out Array + /// Dynamic and Params param + /// Null + void OutAndParam(ref string[][,] strings, out string[] outArr, params dynamic d) {outArr = null;} + } + """, HangMitigatingCancellationToken); await TestServices.Input.SendAsync("var m = Method(1,", HangMitigatingCancellationToken); await TestServices.Editor.InvokeSignatureHelpAsync(HangMitigatingCancellationToken); @@ -121,42 +123,44 @@ void M() [IdeFact] public async Task GenericMethodSignatureHelp1() { - await SetUpEditorAsync(@" -using System; -class C -{ - void M() - { - GenericMethod<$$string, int>(null, 1); - } - C Method(int i) { return null; } - - /// - /// Hello World 2.0! - /// - /// an integer, preferably 42. - /// an integer, anything you like. - /// returns an object of type C - C Method(int i, int i2) { return null; } - - /// - /// Hello Generic World! - /// - /// Type Param 1 - /// Param 1 of type T1 - /// Null - C GenericMethod(T1 i) { return null; } - C GenericMethod(T1 i, T2 i2) { return null; } - - /// - /// Complex Method Params - /// - /// Jagged MultiDimensional Array - /// Out Array - /// Dynamic and Params param - /// Null - void OutAndParam(ref string[][,] strings, out string[] outArr, params dynamic d) {outArr = null;} -}", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + using System; + class C + { + void M() + { + GenericMethod<$$string, int>(null, 1); + } + C Method(int i) { return null; } + + /// + /// Hello World 2.0! + /// + /// an integer, preferably 42. + /// an integer, anything you like. + /// returns an object of type C + C Method(int i, int i2) { return null; } + + /// + /// Hello Generic World! + /// + /// Type Param 1 + /// Param 1 of type T1 + /// Null + C GenericMethod(T1 i) { return null; } + C GenericMethod(T1 i, T2 i2) { return null; } + + /// + /// Complex Method Params + /// + /// Jagged MultiDimensional Array + /// Out Array + /// Dynamic and Params param + /// Null + void OutAndParam(ref string[][,] strings, out string[] outArr, params dynamic d) {outArr = null;} + } + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeSignatureHelpAsync(HangMitigatingCancellationToken); var signature = await TestServices.Editor.GetCurrentSignatureAsync(HangMitigatingCancellationToken); @@ -184,42 +188,44 @@ void M() [IdeFact] public async Task GenericMethodSignatureHelp2() { - await SetUpEditorAsync(@" -using System; -class C -{ - void M() - { - GenericMethod($$null, 1); - } - C Method(int i) { return null; } - - /// - /// Hello World 2.0! - /// - /// an integer, preferably 42. - /// an integer, anything you like. - /// returns an object of type C - C Method(int i, int i2) { return null; } - - /// - /// Hello Generic World! - /// - /// Type Param 1 - /// Param 1 of type T1 - /// Null - C GenericMethod(T1 i) { return null; } - C GenericMethod(T1 i, T2 i2) { return null; } - - /// - /// Complex Method Params - /// - /// Jagged MultiDimensional Array - /// Out Array - /// Dynamic and Params param - /// Null - void OutAndParam(ref string[][,] strings, out string[] outArr, params dynamic d) {outArr = null;} -}", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + using System; + class C + { + void M() + { + GenericMethod($$null, 1); + } + C Method(int i) { return null; } + + /// + /// Hello World 2.0! + /// + /// an integer, preferably 42. + /// an integer, anything you like. + /// returns an object of type C + C Method(int i, int i2) { return null; } + + /// + /// Hello Generic World! + /// + /// Type Param 1 + /// Param 1 of type T1 + /// Null + C GenericMethod(T1 i) { return null; } + C GenericMethod(T1 i, T2 i2) { return null; } + + /// + /// Complex Method Params + /// + /// Jagged MultiDimensional Array + /// Out Array + /// Dynamic and Params param + /// Null + void OutAndParam(ref string[][,] strings, out string[] outArr, params dynamic d) {outArr = null;} + } + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeSignatureHelpAsync(HangMitigatingCancellationToken); var signature = await TestServices.Editor.GetCurrentSignatureAsync(HangMitigatingCancellationToken); @@ -247,19 +253,21 @@ void M() [IdeFact, WorkItem("https://github.com/dotnet/roslyn/issues/42484")] public async Task ExplicitSignatureHelpDismissesCompletion() { - await SetUpEditorAsync(@" -class C -{ - void M() - { - Test$$ - } + await SetUpEditorAsync(""" + + class C + { + void M() + { + Test$$ + } - void Test() { } - void Test(int x) { } - void Test(int x, int y) { } - void Test(int x, int y, int z) { } -}", HangMitigatingCancellationToken); + void Test() { } + void Test(int x) { } + void Test(int x, int y) { } + void Test(int x, int y, int z) { } + } + """, HangMitigatingCancellationToken); await TestServices.Workspace.SetTriggerCompletionInArgumentListsAsync(LanguageNames.CSharp, true, HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpSourceGenerators.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpSourceGenerators.cs index f37d5a8f0ec34..a556af30ee9af 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpSourceGenerators.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpSourceGenerators.cs @@ -16,16 +16,13 @@ using Roslyn.VisualStudio.NewIntegrationTests.InProcess; using WindowsInput.Native; using Xunit; -using Xunit.Abstractions; namespace Roslyn.VisualStudio.NewIntegrationTests.CSharp; [Trait(Traits.Feature, Traits.Features.SourceGenerators)] -public sealed class CSharpSourceGenerators(ITestOutputHelper testOutputHelper) +public sealed class CSharpSourceGenerators() : AbstractEditorTest(nameof(CSharpSourceGenerators), WellKnownProjectTemplates.ConsoleApplication) { - private readonly ITestOutputHelper _testOutputHelper = testOutputHelper; - protected override string LanguageName => LanguageNames.CSharp; public override async Task InitializeAsync() diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpSquigglesCommon.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpSquigglesCommon.cs index 27ca7969b911d..d8362cf254f79 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpSquigglesCommon.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpSquigglesCommon.cs @@ -46,11 +46,15 @@ private static void Sub() } """, HangMitigatingCancellationToken); - var usingsErrorTags = SupportsGlobalUsings ? ("suggestion", TextSpan.FromBounds(0, 68), @"using System; -using System.Collections.Generic; -using System.Text;", "IDE0005: Using directive is unnecessary.") - : ("suggestion", TextSpan.FromBounds(15, 68), @"using System.Collections.Generic; -using System.Text;", "IDE0005: Using directive is unnecessary."); + var usingsErrorTags = SupportsGlobalUsings ? ("suggestion", TextSpan.FromBounds(0, 68), """ + using System; + using System.Collections.Generic; + using System.Text; + """, "IDE0005: Using directive is unnecessary.") + : ("suggestion", TextSpan.FromBounds(15, 68), """ + using System.Collections.Generic; + using System.Text; + """, "IDE0005: Using directive is unnecessary."); await TestServices.EditorVerifier.ErrorTagsAsync( [ diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpTyping.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpTyping.cs index f74d2e50bdaa9..b5aaccae1501a 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpTyping.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpTyping.cs @@ -25,39 +25,42 @@ public CSharpTyping() [IdeFact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/957250")] public async Task TypingInPartialType() { - await SetUpEditorAsync(@" -public partial class Test -{ - private int f; + await SetUpEditorAsync(""" - static void Main(string[] args) { } - public void Noop() - { - f = 1;$$ - } -} -", HangMitigatingCancellationToken); - var secondPartialDecl = @" -public partial class Test -{ - int val1 = 1, val2 = 2; - public void TestA() - { - TestB(); - } -} -"; - var thirdPartialDecl = @" -public partial class Test -{ - public void TestB() - { - int val1x = this.val1, val2x = this.val2; - } -}"; + public partial class Test + { + private int f; + + static void Main(string[] args) { } + public void Noop() + { + f = 1;$$ + } + } + + """, HangMitigatingCancellationToken); + await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "PartialType2.cs", """ + + public partial class Test + { + int val1 = 1, val2 = 2; + public void TestA() + { + TestB(); + } + } + + """, open: false, HangMitigatingCancellationToken); + await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "PartialType3.cs", """ - await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "PartialType2.cs", secondPartialDecl, open: false, HangMitigatingCancellationToken); - await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "PartialType3.cs", thirdPartialDecl, open: false, HangMitigatingCancellationToken); + public partial class Test + { + public void TestB() + { + int val1x = this.val1, val2x = this.val2; + } + } + """, open: false, HangMitigatingCancellationToken); // Typing intermixed with explicit Wait operations to ensure that // we trigger multiple open file analyses along with cancellations. @@ -71,17 +74,19 @@ public void TestB() await TestServices.Input.SendAsync("2;", HangMitigatingCancellationToken); await TestServices.EditorVerifier.TextContainsAsync( - @" -public partial class Test -{ - private int f; + """ - static void Main(string[] args) { } - public void Noop() - { - f = 1; - f = 2; - } -}"); + public partial class Test + { + private int f; + + static void Main(string[] args) { } + public void Noop() + { + f = 1; + f = 2; + } + } + """); } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpUpdateProjectToAllowUnsafe.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpUpdateProjectToAllowUnsafe.cs index 69db571be4c4f..8d34f6523423a 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpUpdateProjectToAllowUnsafe.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpUpdateProjectToAllowUnsafe.cs @@ -19,10 +19,12 @@ public class CSharpUpdateProjectToAllowUnsafe : AbstractUpgradeProjectTest { private async Task InvokeFixAsync(CancellationToken cancellationToken) { - await TestServices.Editor.SetTextAsync(@" -unsafe class C -{ -}", cancellationToken); + await TestServices.Editor.SetTextAsync(""" + + unsafe class C + { + } + """, cancellationToken); await TestServices.Editor.ActivateAsync(cancellationToken); await TestServices.Editor.PlaceCaretAsync("C", charsOffset: 0, cancellationToken); @@ -69,40 +71,42 @@ public async Task LegacyProject_MultiplePlatforms_AllConfigurationsUpdated() await TestServices.SolutionExplorer.AddCustomProjectAsync( project, ".csproj", - $@" - - - - Debug - x64 - {{F4233BA4-A4CB-498B-BBC1-65A42206B1BA}} - Library - {ProjectName} - {ProjectName} - v4.6 - - - bin\x86\Debug\ - x86 - - - bin\x86\Release\ - x86 - true - - - bin\x64\Debug\ - x64 - false - - - bin\x64\Release\ - x64 - - - - -", + $$""" + + + + + Debug + x64 + {F4233BA4-A4CB-498B-BBC1-65A42206B1BA} + Library + {{ProjectName}} + {{ProjectName}} + v4.6 + + + bin\x86\Debug\ + x86 + + + bin\x86\Release\ + x86 + true + + + bin\x64\Debug\ + x64 + false + + + bin\x64\Release\ + x64 + + + + + + """, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.AddFileAsync(project, "C.cs", open: true, cancellationToken: HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpUpgradeProject.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpUpgradeProject.cs index fdd977fcc444b..18aad21bf8ecc 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpUpgradeProject.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpUpgradeProject.cs @@ -19,9 +19,11 @@ public class CSharpUpgradeProject : AbstractUpgradeProjectTest { private async Task InvokeFixAsync(string version, CancellationToken cancellationToken) { - await TestServices.Editor.SetTextAsync(@$" -#error version:{version} -", cancellationToken); + await TestServices.Editor.SetTextAsync($""" + + #error version:{version} + + """, cancellationToken); await TestServices.Editor.ActivateAsync(cancellationToken); await TestServices.Editor.PlaceCaretAsync($"version:{version}", charsOffset: 0, cancellationToken); @@ -55,39 +57,41 @@ public async Task LegacyProject_AllConfigurationsUpdated() await TestServices.SolutionExplorer.AddCustomProjectAsync( project, ".csproj", - $@" - - - - Debug - x64 - {{F4233BA4-A4CB-498B-BBC1-65A42206B1BA}} - Library - {ProjectName} - {ProjectName} - v4.6 - 7.0 - - - bin\x86\Debug\ - x86 - - - bin\x86\Release\ - x86 - - - bin\x64\Debug\ - x64 - - - bin\x64\Release\ - x64 - - - - -", + $$""" + + + + + Debug + x64 + {F4233BA4-A4CB-498B-BBC1-65A42206B1BA} + Library + {{ProjectName}} + {{ProjectName}} + v4.6 + 7.0 + + + bin\x86\Debug\ + x86 + + + bin\x86\Release\ + x86 + + + bin\x64\Debug\ + x64 + + + bin\x64\Release\ + x64 + + + + + + """, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.AddFileAsync(project, "C.cs", open: true, cancellationToken: HangMitigatingCancellationToken); @@ -105,42 +109,44 @@ public async Task LegacyProject_MultiplePlatforms_AllConfigurationsUpdated() await TestServices.SolutionExplorer.AddCustomProjectAsync( project, ".csproj", - $@" - - - - Debug - x64 - {{F4233BA4-A4CB-498B-BBC1-65A42206B1BA}} - Library - {ProjectName} - {ProjectName} - v4.6 - - - bin\x86\Debug\ - x86 - 7.2 - - - bin\x86\Release\ - x86 - 7.1 - - - bin\x64\Debug\ - x64 - 7.0 - - - bin\x64\Release\ - x64 - 7.1 - - - - -", + $$""" + + + + + Debug + x64 + {F4233BA4-A4CB-498B-BBC1-65A42206B1BA} + Library + {{ProjectName}} + {{ProjectName}} + v4.6 + + + bin\x86\Debug\ + x86 + 7.2 + + + bin\x86\Release\ + x86 + 7.1 + + + bin\x64\Debug\ + x64 + 7.0 + + + bin\x64\Release\ + x64 + 7.1 + + + + + + """, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.AddFileAsync(project, "C.cs", open: true, cancellationToken: HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpWinForms.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpWinForms.cs index f4aa270674050..07ddd881d08db 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpWinForms.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/CSharpWinForms.cs @@ -7,8 +7,8 @@ using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; -using Roslyn.VisualStudio.IntegrationTests; using Roslyn.Test.Utilities; +using Roslyn.VisualStudio.IntegrationTests; using Xunit; namespace Roslyn.VisualStudio.NewIntegrationTests.CSharp; @@ -33,7 +33,9 @@ public async Task AddControl() await TestServices.SolutionExplorer.SaveFileAsync(project, "Form1.resx", HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(project, "Form1.Designer.cs", HangMitigatingCancellationToken); var actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); - Assert.Contains(@"this.SomeButton.Name = ""SomeButton""", actualText); + Assert.Contains(""" + this.SomeButton.Name = "SomeButton" + """, actualText); Assert.Contains(@"private System.Windows.Forms.Button SomeButton;", actualText); } @@ -49,7 +51,9 @@ public async Task ChangeControlProperty() await TestServices.SolutionExplorer.CloseDesignerFileAsync(project, "Form1.cs", saveFile: true, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(project, "Form1.Designer.cs", HangMitigatingCancellationToken); var actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); - Assert.Contains(@"this.SomeButton.Text = ""NewButtonText""", actualText); + Assert.Contains(""" + this.SomeButton.Text = "NewButtonText" + """, actualText); } [IdeFact] @@ -95,18 +99,20 @@ public async Task AddClickHandler() Assert.Contains(@"this.SomeButton.Click += new System.EventHandler(this.ExecuteWhenButtonClicked);", designerActualText); await TestServices.SolutionExplorer.OpenFileAsync(project, "Form1.cs", HangMitigatingCancellationToken); var codeFileActualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); - Assert.Contains(@" public partial class Form1 : Form - { - public Form1() - { - InitializeComponent(); - } - - private void ExecuteWhenButtonClicked(object sender, EventArgs e) - { - - } - }", codeFileActualText); + Assert.Contains(""" + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + + private void ExecuteWhenButtonClicked(object sender, EventArgs e) + { + + } + } + """, codeFileActualText); } [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/77293")] diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/DocumentationCommentTests.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/DocumentationCommentTests.cs index 1f17fbef0026e..2110537dd9fd5 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/DocumentationCommentTests.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/CSharp/DocumentationCommentTests.cs @@ -25,37 +25,36 @@ public DocumentationCommentTests() [IdeFact, WorkItem("https://github.com/dotnet/roslyn/issues/54391")] public async Task TypingCharacter_MultiCaret() { - var code = -@" -//{|selection:|} -class C1 { } - -//{|selection:|} -class C2 { } - -//{|selection:|} -class C3 { } -"; - await SetUpEditorAsync(code, HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + //{|selection:|} + class C1 { } + + //{|selection:|} + class C2 { } + + //{|selection:|} + class C3 { } + + """, HangMitigatingCancellationToken); await TestServices.Input.SendAsync('/', HangMitigatingCancellationToken); - var expected = -@" -/// -/// $$ -/// -class C1 { } - -/// -/// -/// -class C2 { } - -/// -/// -/// -class C3 { } -"; - - await TestServices.EditorVerifier.TextContainsAsync(expected, assertCaretPosition: true, cancellationToken: HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextContainsAsync(""" + + /// + /// $$ + /// + class C1 { } + + /// + /// + /// + class C2 { } + + /// + /// + /// + class C3 { } + + """, assertCaretPosition: true, cancellationToken: HangMitigatingCancellationToken); } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/AddParameterDialogInProcess.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/AddParameterDialogInProcess.cs index e97323c77fba6..ce0b4d26b67cd 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/AddParameterDialogInProcess.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/AddParameterDialogInProcess.cs @@ -74,15 +74,11 @@ public async Task CloseWindowAsync(CancellationToken cancellationToken) return true; } - public async Task ClickOKAsync(CancellationToken cancellationToken) - { - await ClickAsync(dialog => dialog.GetTestAccessor().OKButton, cancellationToken); - } + public Task ClickOKAsync(CancellationToken cancellationToken) + => ClickAsync(dialog => dialog.GetTestAccessor().OKButton, cancellationToken); - public async Task ClickCancelAsync(CancellationToken cancellationToken) - { - await ClickAsync(dialog => dialog.GetTestAccessor().CancelButton, cancellationToken); - } + public Task ClickCancelAsync(CancellationToken cancellationToken) + => ClickAsync(dialog => dialog.GetTestAccessor().CancelButton, cancellationToken); public async Task FillCallSiteFieldAsync(string callsiteValue, CancellationToken cancellationToken) { @@ -117,8 +113,6 @@ public async Task FillTypeFieldAsync(string typeName, CancellationToken cancella dialog.TypeContentControl.Text = typeName; } - public async Task SetCallSiteTodoAsync(CancellationToken cancellationToken) - { - await ClickAsync(dialog => dialog.IntroduceErrorRadioButton, cancellationToken); - } + public Task SetCallSiteTodoAsync(CancellationToken cancellationToken) + => ClickAsync(dialog => dialog.IntroduceErrorRadioButton, cancellationToken); } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/ChangeSignatureDialogInProcess.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/ChangeSignatureDialogInProcess.cs index 6cc00a581a2ed..8d5ac3f89e214 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/ChangeSignatureDialogInProcess.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/ChangeSignatureDialogInProcess.cs @@ -91,30 +91,20 @@ public async Task ClickCancelAsync(CancellationToken cancellationToken) await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.LightBulb, cancellationToken); } - public async Task ClickDownButtonAsync(CancellationToken cancellationToken) - { - await ClickAsync(dialog => dialog.GetTestAccessor().DownButton, cancellationToken); - } + public Task ClickDownButtonAsync(CancellationToken cancellationToken) + => ClickAsync(dialog => dialog.GetTestAccessor().DownButton, cancellationToken); - public async Task ClickUpButtonAsync(CancellationToken cancellationToken) - { - await ClickAsync(dialog => dialog.GetTestAccessor().UpButton, cancellationToken); - } + public Task ClickUpButtonAsync(CancellationToken cancellationToken) + => ClickAsync(dialog => dialog.GetTestAccessor().UpButton, cancellationToken); - public async Task ClickAddButtonAsync(CancellationToken cancellationToken) - { - await ClickAsync(dialog => dialog.GetTestAccessor().AddButton, cancellationToken); - } + public Task ClickAddButtonAsync(CancellationToken cancellationToken) + => ClickAsync(dialog => dialog.GetTestAccessor().AddButton, cancellationToken); - public async Task ClickRemoveButtonAsync(CancellationToken cancellationToken) - { - await ClickAsync(dialog => dialog.GetTestAccessor().RemoveButton, cancellationToken); - } + public Task ClickRemoveButtonAsync(CancellationToken cancellationToken) + => ClickAsync(dialog => dialog.GetTestAccessor().RemoveButton, cancellationToken); - public async Task ClickRestoreButtonAsync(CancellationToken cancellationToken) - { - await ClickAsync(dialog => dialog.GetTestAccessor().RestoreButton, cancellationToken); - } + public Task ClickRestoreButtonAsync(CancellationToken cancellationToken) + => ClickAsync(dialog => dialog.GetTestAccessor().RestoreButton, cancellationToken); public async Task SelectParameterAsync(string parameterName, CancellationToken cancellationToken) { diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/DebuggerInProcess.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/DebuggerInProcess.cs index 1afd2f44e3e5e..abb0cd1fa39b6 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/DebuggerInProcess.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/DebuggerInProcess.cs @@ -83,16 +83,14 @@ public async Task GoAsync(bool waitForBreakMode, CancellationToken cancellationT debugger.Go(waitForBreakMode); } - public async Task StepOverAsync(bool waitForBreakOrEnd, CancellationToken cancellationToken) - { - await WaitForRaiseDebuggerDteCommandAsync( + public Task StepOverAsync(bool waitForBreakOrEnd, CancellationToken cancellationToken) + => WaitForRaiseDebuggerDteCommandAsync( async cancellationToken => { var debugger = await GetDebuggerAsync(cancellationToken); debugger.StepOver(waitForBreakOrEnd); }, cancellationToken); - } public async Task StopAsync(bool waitForDesignMode, CancellationToken cancellationToken) { @@ -151,10 +149,8 @@ private static async Task WaitForRaiseDebuggerDteCommandAsync(Func /// Delegate to invoke. - public static async Task TryWaitForAsync(Func> predicate, CancellationToken cancellationToken) - { - await TryWaitForAsync(DefaultPollingInterCallSleep, predicate, cancellationToken); - } + public static Task TryWaitForAsync(Func> predicate, CancellationToken cancellationToken) + => TryWaitForAsync(DefaultPollingInterCallSleep, predicate, cancellationToken); /// /// Polls for the specified delegate to return true for the given timeout. diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/EditorInProcess.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/EditorInProcess.cs index aa1e6c3957241..2f5672bad7864 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/EditorInProcess.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/EditorInProcess.cs @@ -27,11 +27,9 @@ using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; -using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; -using Microsoft.VisualStudio.LanguageServices.FindUsages; using Microsoft.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; @@ -1065,15 +1063,11 @@ public Task FormatSelectionAsync(CancellationToken cancellationToken) return TestServices.Shell.ExecuteCommandAsync(VSConstants.VSStd2KCmdID.FORMATSELECTION, cancellationToken); } - private async Task WaitForSignatureHelpAsync(CancellationToken cancellationToken) - { - await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.SignatureHelp, cancellationToken); - } + private Task WaitForSignatureHelpAsync(CancellationToken cancellationToken) + => TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.SignatureHelp, cancellationToken); - private async Task WaitForCompletionSetAsync(CancellationToken cancellationToken) - { - await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.CompletionSet, cancellationToken); - } + private Task WaitForCompletionSetAsync(CancellationToken cancellationToken) + => TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.CompletionSet, cancellationToken); public async Task AddWinFormButtonAsync(string buttonName, CancellationToken cancellationToken) { diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/ExtractInterfaceDialogInProcess.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/ExtractInterfaceDialogInProcess.cs index ef6bdfe6219b3..c3e3292a609e8 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/ExtractInterfaceDialogInProcess.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/ExtractInterfaceDialogInProcess.cs @@ -117,20 +117,14 @@ public async Task>> GetSelectedItemsAsyn .ToImmutableArray(); } - public async Task ClickDeselectAllAsync(CancellationToken cancellationToken) - { - await ClickAsync(dialog => dialog.GetTestAccessor().DeselectAllButton, cancellationToken); - } + public Task ClickDeselectAllAsync(CancellationToken cancellationToken) + => ClickAsync(dialog => dialog.GetTestAccessor().DeselectAllButton, cancellationToken); - public async Task ClickSelectAllAsync(CancellationToken cancellationToken) - { - await ClickAsync(dialog => dialog.GetTestAccessor().SelectAllButton, cancellationToken); - } + public Task ClickSelectAllAsync(CancellationToken cancellationToken) + => ClickAsync(dialog => dialog.GetTestAccessor().SelectAllButton, cancellationToken); - public async Task SelectSameFileAsync(CancellationToken cancellationToken) - { - await ClickAsync(dialog => dialog.GetTestAccessor().DestinationCurrentFileSelectionRadioButton, cancellationToken); - } + public Task SelectSameFileAsync(CancellationToken cancellationToken) + => ClickAsync(dialog => dialog.GetTestAccessor().DestinationCurrentFileSelectionRadioButton, cancellationToken); public async Task ToggleItemAsync(string item, CancellationToken cancellationToken) { diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/Helper.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/Helper.cs index 5e1ae57e938aa..accb5e7bedaf2 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/Helper.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/Helper.cs @@ -12,18 +12,16 @@ namespace Roslyn.VisualStudio.IntegrationTests.InProcess; internal static class Helper { - private static IUIAutomation2? _automation; - public static IUIAutomation2 Automation { get { - if (_automation == null) + if (field == null) { - Interlocked.CompareExchange(ref _automation, new CUIAutomation8(), null); + Interlocked.CompareExchange(ref field, new CUIAutomation8(), null); } - return _automation; + return field; } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/ITextViewWindowInProcessExtensions.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/ITextViewWindowInProcessExtensions.cs index 9ca7b549ca516..c0759eca82f23 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/ITextViewWindowInProcessExtensions.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/ITextViewWindowInProcessExtensions.cs @@ -244,8 +244,6 @@ public static async Task GetCaretPositionAsync(this ITextViewWind return view.Caret.Position; } - private static async Task WaitForCompletionSetAsync(ITextViewWindowInProcess textViewWindow, CancellationToken cancellationToken) - { - await textViewWindow.TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.CompletionSet, cancellationToken); - } + private static Task WaitForCompletionSetAsync(ITextViewWindowInProcess textViewWindow, CancellationToken cancellationToken) + => textViewWindow.TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.CompletionSet, cancellationToken); } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/ImmediateWindowInProcess.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/ImmediateWindowInProcess.cs index 7d4704db802e6..f7ca1b8c4c3df 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/ImmediateWindowInProcess.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/ImmediateWindowInProcess.cs @@ -15,10 +15,8 @@ namespace Roslyn.VisualStudio.NewIntegrationTests.InProcess; [TestService] internal sealed partial class ImmediateWindowInProcess { - public async Task ShowAsync(CancellationToken cancellationToken) - { - await TestServices.Shell.ExecuteCommandAsync(WellKnownCommands.Debug.Immediate, cancellationToken); - } + public Task ShowAsync(CancellationToken cancellationToken) + => TestServices.Shell.ExecuteCommandAsync(WellKnownCommands.Debug.Immediate, cancellationToken); public async Task ClearAllAsync(CancellationToken cancellationToken) { diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/InlineRenameInProcess.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/InlineRenameInProcess.cs index b676c74a13f13..cfbe45a073def 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/InlineRenameInProcess.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/InlineRenameInProcess.cs @@ -7,8 +7,6 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Implementation.InlineRename; -using Microsoft.CodeAnalysis.Editor.InlineRename; -using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Extensibility.Testing; using Microsoft.VisualStudio.TextManager.Interop; diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/PickMembersDialogInProcess.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/PickMembersDialogInProcess.cs index d6a661ad276d3..e224451f7b396 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/PickMembersDialogInProcess.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/PickMembersDialogInProcess.cs @@ -88,8 +88,6 @@ public async Task ClickCancelAsync(CancellationToken cancellationToken) await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.LightBulb, cancellationToken); } - public async Task ClickDownAsync(CancellationToken cancellationToken) - { - await ClickAsync(dialog => dialog.GetTestAccessor().DownButton, cancellationToken); - } + public Task ClickDownAsync(CancellationToken cancellationToken) + => ClickAsync(dialog => dialog.GetTestAccessor().DownButton, cancellationToken); } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/ShellInProcess.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/ShellInProcess.cs index 51ba613459504..91d7d95dd1358 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/ShellInProcess.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/ShellInProcess.cs @@ -203,8 +203,6 @@ public PauseFileChangesRestorer(IVsFileChangeEx3 fileChangeService) } public async ValueTask DisposeAsync() - { - await _fileChangeService.Resume(); - } + => await _fileChangeService.Resume(); } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/SolutionExplorerInProcess.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/SolutionExplorerInProcess.cs index 5b4046b4bc69a..3378688392117 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/SolutionExplorerInProcess.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/SolutionExplorerInProcess.cs @@ -406,15 +406,11 @@ public async Task CloseActiveWindow(CancellationToken cancellationToken) ErrorHandler.ThrowOnFailure(windowFrame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave)); } - public async Task CloseDesignerFileAsync(string projectName, string relativeFilePath, bool saveFile, CancellationToken cancellationToken) - { - await CloseFileAsync(projectName, relativeFilePath, VSConstants.LOGVIEWID.Designer_guid, saveFile, cancellationToken); - } + public Task CloseDesignerFileAsync(string projectName, string relativeFilePath, bool saveFile, CancellationToken cancellationToken) + => CloseFileAsync(projectName, relativeFilePath, VSConstants.LOGVIEWID.Designer_guid, saveFile, cancellationToken); - public async Task CloseCodeFileAsync(string projectName, string relativeFilePath, bool saveFile, CancellationToken cancellationToken) - { - await CloseFileAsync(projectName, relativeFilePath, VSConstants.LOGVIEWID.Code_guid, saveFile, cancellationToken); - } + public Task CloseCodeFileAsync(string projectName, string relativeFilePath, bool saveFile, CancellationToken cancellationToken) + => CloseFileAsync(projectName, relativeFilePath, VSConstants.LOGVIEWID.Code_guid, saveFile, cancellationToken); private async Task CloseFileAsync(string projectName, string relativeFilePath, Guid logicalView, bool saveFile, CancellationToken cancellationToken) { diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/StateResetInProcess.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/StateResetInProcess.cs index 1073ccf478474..f0729ac896255 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/StateResetInProcess.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/StateResetInProcess.cs @@ -8,9 +8,9 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.AddImportOnPaste; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.CodeStyle; -using Microsoft.CodeAnalysis.Editor.InlineRename; using Microsoft.CodeAnalysis.Editor.Options; using Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit; using Microsoft.CodeAnalysis.Formatting; diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/WorkaroundsInProcess.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/WorkaroundsInProcess.cs index 7dcb16d81f1ca..0e2ec56fa7bec 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/WorkaroundsInProcess.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/WorkaroundsInProcess.cs @@ -3,12 +3,10 @@ // See the LICENSE file in the project root for more information. using System; -using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.Internal.VisualStudio.Shell.Interop; -using Microsoft.VisualStudio; using Microsoft.VisualStudio.Extensibility.Testing; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/WorkspaceInProcess.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/WorkspaceInProcess.cs index 3859d74ce7ad1..fa25161fb5aa7 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/WorkspaceInProcess.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/WorkspaceInProcess.cs @@ -7,6 +7,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeStyle; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit; @@ -160,16 +161,14 @@ public async Task WaitForAllAsyncOperationsAsync(string[] featureNames, Cancella await listenerProvider.WaitAllAsync(workspace, featureNames).WithCancellation(cancellationToken); } - public async Task WaitForRenameAsync(CancellationToken cancellationToken) - { - await WaitForAllAsyncOperationsAsync( + public Task WaitForRenameAsync(CancellationToken cancellationToken) + => WaitForAllAsyncOperationsAsync( [ FeatureAttribute.Rename, FeatureAttribute.RenameTracking, FeatureAttribute.InlineRenameFlyout, ], cancellationToken); - } /// /// This event listener is an adapter to expose asynchronous file save operations to Roslyn via its standard diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InfrastructureTests.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InfrastructureTests.cs index f5df77d39f53d..ee87ada0aa40e 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/InfrastructureTests.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/InfrastructureTests.cs @@ -25,11 +25,13 @@ public InfrastructureTests() public async Task CanCloseSaveDialog() { await SetUpEditorAsync( - @" -namespace MyNamespace -{ -$$ -}", + """ + + namespace MyNamespace + { + $$ + } + """, HangMitigatingCancellationToken); // Trigger a call to File.Close to ensure we can recover from it diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicAddMissingReference.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicAddMissingReference.cs index 1306fc788c00a..d504847b81598 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicAddMissingReference.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicAddMissingReference.cs @@ -16,94 +16,102 @@ namespace Roslyn.VisualStudio.NewIntegrationTests.VisualBasic; [Trait(Traits.Feature, Traits.Features.AddMissingReference)] public class BasicAddMissingReference : AbstractEditorTest { - private const string FileInLibraryProject1 = @"Public Class Class1 - Inherits System.Windows.Forms.Form - Public Sub goo() + private const string FileInLibraryProject1 = """ + Public Class Class1 + Inherits System.Windows.Forms.Form + Public Sub goo() - End Sub -End Class + End Sub + End Class -Public Class class2 - Public Sub goo(ByVal x As System.Windows.Forms.Form) + Public Class class2 + Public Sub goo(ByVal x As System.Windows.Forms.Form) - End Sub + End Sub - Public Event ee As System.Windows.Forms.ColumnClickEventHandler -End Class + Public Event ee As System.Windows.Forms.ColumnClickEventHandler + End Class -Public Class class3 - Implements System.Windows.Forms.IButtonControl + Public Class class3 + Implements System.Windows.Forms.IButtonControl - Public Property DialogResult() As System.Windows.Forms.DialogResult Implements System.Windows.Forms.IButtonControl.DialogResult - Get + Public Property DialogResult() As System.Windows.Forms.DialogResult Implements System.Windows.Forms.IButtonControl.DialogResult + Get - End Get - Set(ByVal Value As System.Windows.Forms.DialogResult) + End Get + Set(ByVal Value As System.Windows.Forms.DialogResult) - End Set - End Property + End Set + End Property - Public Sub NotifyDefault(ByVal value As Boolean) Implements System.Windows.Forms.IButtonControl.NotifyDefault + Public Sub NotifyDefault(ByVal value As Boolean) Implements System.Windows.Forms.IButtonControl.NotifyDefault - End Sub + End Sub - Public Sub PerformClick() Implements System.Windows.Forms.IButtonControl.PerformClick + Public Sub PerformClick() Implements System.Windows.Forms.IButtonControl.PerformClick - End Sub -End Class -"; - private const string FileInLibraryProject2 = @"Public Class Class1 - Inherits System.Xml.XmlAttribute - Sub New() - MyBase.New(Nothing, Nothing, Nothing, Nothing) - End Sub - Sub goo() + End Sub + End Class - End Sub - Public bar As ClassLibrary3.Class1 -End Class -"; - private const string FileInLibraryProject3 = @"Public Class Class1 - Public Enum E - E1 - E2 - End Enum + """; + private const string FileInLibraryProject2 = """ + Public Class Class1 + Inherits System.Xml.XmlAttribute + Sub New() + MyBase.New(Nothing, Nothing, Nothing, Nothing) + End Sub + Sub goo() - Public Function Goo() As ADODB.Recordset - Dim x As ADODB.Recordset = Nothing - Return x - End Function + End Sub + Public bar As ClassLibrary3.Class1 + End Class + """; + private const string FileInLibraryProject3 = """ + Public Class Class1 + Public Enum E + E1 + E2 + End Enum -End Class -"; - private const string FileInConsoleProject1 = @"Imports System.Data.XLinq + Public Function Goo() As ADODB.Recordset + Dim x As ADODB.Recordset = Nothing + Return x + End Function -Module Module1 - Sub Main() - 'ERRID_UnreferencedAssembly3 - Dim y As New ClassLibrary1.class2 - y.goo(Nothing) + End Class - 'ERRID_UnreferencedAssemblyEvent3 - AddHandler y.ee, Nothing + """; + private const string FileInConsoleProject1 = """ + Imports System.Data.XLinq - 'ERRID_UnreferencedAssemblyBase3 - Dim x As New ClassLibrary1.Class1 - x.goo() - 'ERRID_UnreferencedAssemblyImplements3 - Dim z As New ClassLibrary1.class3 - Dim xxx = z.DialogResult - 'ERRID_SymbolFromUnreferencedProject3 - Dim a As New ClassLibrary2.Class1 - Dim c As Boolean = a.HasChildNodes() + Module Module1 - Dim d = a.bar - End Sub + Sub Main() + 'ERRID_UnreferencedAssembly3 + Dim y As New ClassLibrary1.class2 + y.goo(Nothing) -End Module -"; + 'ERRID_UnreferencedAssemblyEvent3 + AddHandler y.ee, Nothing + + 'ERRID_UnreferencedAssemblyBase3 + Dim x As New ClassLibrary1.Class1 + x.goo() + 'ERRID_UnreferencedAssemblyImplements3 + Dim z As New ClassLibrary1.class3 + Dim xxx = z.DialogResult + 'ERRID_SymbolFromUnreferencedProject3 + Dim a As New ClassLibrary2.Class1 + Dim c As Boolean = a.HasChildNodes() + + Dim d = a.bar + End Sub + + End Module + + """; private const string ClassLibrary1Name = "ClassLibrary1"; private const string ClassLibrary2Name = "ClassLibrary2"; diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicArgumentProvider.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicArgumentProvider.cs index 3c4f9a6d077bd..36e16663ff428 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicArgumentProvider.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicArgumentProvider.cs @@ -34,14 +34,16 @@ public override async Task InitializeAsync() [IdeFact] public async Task SimpleTabTabCompletion() { - await SetUpEditorAsync(@" -Public Class Test - Private f As Object + await SetUpEditorAsync(""" - Public Sub Method()$$ - End Sub -End Class -", HangMitigatingCancellationToken); + Public Class Test + Private f As Object + + Public Sub Method()$$ + End Sub + End Class + + """, HangMitigatingCancellationToken); await TestServices.Input.SendAsync(VirtualKeyCode.RETURN, HangMitigatingCancellationToken); await TestServices.Input.SendAsync("f.ToSt", HangMitigatingCancellationToken); @@ -60,13 +62,15 @@ End Class [IdeFact] public async Task TabTabCompleteObjectEquals() { - await SetUpEditorAsync(@" -Public Class Test - Public Sub Method() - $$ - End Sub -End Class -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Public Class Test + Public Sub Method() + $$ + End Sub + End Class + + """, HangMitigatingCancellationToken); await TestServices.Input.SendAsync("Object.Equ", HangMitigatingCancellationToken); @@ -81,13 +85,15 @@ End Class [IdeFact] public async Task TabTabCompleteNewObject() { - await SetUpEditorAsync(@" -Public Class Test - Public Sub Method() - Dim value = $$ - End Sub -End Class -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Public Class Test + Public Sub Method() + Dim value = $$ + End Sub + End Class + + """, HangMitigatingCancellationToken); await TestServices.Input.SendAsync("New Obje", HangMitigatingCancellationToken); @@ -105,15 +111,17 @@ End Class [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/63043")] public async Task TabTabCompletionWithArguments() { - await SetUpEditorAsync(@" -Imports System -Public Class Test - Private f As Integer + await SetUpEditorAsync(""" + + Imports System + Public Class Test + Private f As Integer - Public Sub Method(provider As IFormatProvider)$$ - End Sub -End Class -", HangMitigatingCancellationToken); + Public Sub Method(provider As IFormatProvider)$$ + End Sub + End Class + + """, HangMitigatingCancellationToken); await TestServices.Input.SendAsync(VirtualKeyCode.RETURN, HangMitigatingCancellationToken); await TestServices.Input.SendAsync("f.ToSt", HangMitigatingCancellationToken); @@ -134,7 +142,9 @@ End Class await TestServices.Input.SendAsync(VirtualKeyCode.DOWN, HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentLineTextAsync(" f.ToString(Nothing$$, provider)", assertCaretPosition: true, HangMitigatingCancellationToken); - await TestServices.Input.SendAsync("\"format\"", HangMitigatingCancellationToken); + await TestServices.Input.SendAsync(""" + "format" + """, HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentLineTextAsync(" f.ToString(\"format\"$$, provider)", assertCaretPosition: true, HangMitigatingCancellationToken); await TestServices.Input.SendAsync(VirtualKeyCode.TAB, HangMitigatingCancellationToken); @@ -153,22 +163,24 @@ End Class [IdeFact] public async Task FullCycle() { - await SetUpEditorAsync(@" -Imports System -Public Class TestClass - Public Sub Method()$$ - End Sub + await SetUpEditorAsync(""" + + Imports System + Public Class TestClass + Public Sub Method()$$ + End Sub - Sub Test() - End Sub + Sub Test() + End Sub - Sub Test(x As Integer) - End Sub + Sub Test(x As Integer) + End Sub - Sub Test(x As Integer, y As Integer) - End Sub -End Class -", HangMitigatingCancellationToken); + Sub Test(x As Integer, y As Integer) + End Sub + End Class + + """, HangMitigatingCancellationToken); await TestServices.Input.SendAsync(VirtualKeyCode.RETURN, HangMitigatingCancellationToken); await TestServices.Input.SendAsync("Tes", HangMitigatingCancellationToken); @@ -199,22 +211,24 @@ End Class [IdeFact] public async Task ImplicitArgumentSwitching() { - await SetUpEditorAsync(@" -Imports System -Public Class TestClass - Public Sub Method()$$ - End Sub + await SetUpEditorAsync(""" + + Imports System + Public Class TestClass + Public Sub Method()$$ + End Sub - Sub Test() - End Sub + Sub Test() + End Sub - Sub Test(x As Integer) - End Sub + Sub Test(x As Integer) + End Sub - Sub Test(x As Integer, y As Integer) - End Sub -End Class -", HangMitigatingCancellationToken); + Sub Test(x As Integer, y As Integer) + End Sub + End Class + + """, HangMitigatingCancellationToken); await TestServices.Input.SendAsync(VirtualKeyCode.RETURN, HangMitigatingCancellationToken); await TestServices.Input.SendAsync("Tes", HangMitigatingCancellationToken); @@ -236,14 +250,16 @@ End Class [IdeFact] public async Task SmartBreakLineWithTabTabCompletion() { - await SetUpEditorAsync(@" -Public Class Test - Private f As Object + await SetUpEditorAsync(""" + + Public Class Test + Private f As Object - Public Sub Method()$$ - End Sub -End Class -", HangMitigatingCancellationToken); + Public Sub Method()$$ + End Sub + End Class + + """, HangMitigatingCancellationToken); await TestServices.Input.SendAsync(VirtualKeyCode.RETURN, HangMitigatingCancellationToken); await TestServices.Input.SendAsync("f.ToSt", HangMitigatingCancellationToken); @@ -256,15 +272,17 @@ End Class await TestServices.EditorVerifier.CurrentLineTextAsync(" f.ToString($$)", assertCaretPosition: true, HangMitigatingCancellationToken); await TestServices.Input.SendAsync((VirtualKeyCode.RETURN, VirtualKeyCode.SHIFT), HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -Public Class Test - Private f As Object - - Public Sub Method() - f.ToString() -$$ - End Sub -End Class -", assertCaretPosition: true, HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextContainsAsync(""" + + Public Class Test + Private f As Object + + Public Sub Method() + f.ToString() + $$ + End Sub + End Class + + """, assertCaretPosition: true, HangMitigatingCancellationToken); } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicAutomaticBraceCompletion.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicAutomaticBraceCompletion.cs index 294aba768cb0d..fc92e757988a5 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicAutomaticBraceCompletion.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicAutomaticBraceCompletion.cs @@ -1,11 +1,10 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; -using Microsoft.CodeAnalysis.Editor.InlineRename; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; @@ -33,12 +32,14 @@ public async Task Braces_InsertionAndTabCompleting(bool argumentCompletion) var globalOptions = await TestServices.Shell.GetComponentModelServiceAsync(HangMitigatingCancellationToken); globalOptions.SetGlobalOption(CompletionViewOptionsStorage.EnableArgumentCompletionSnippets, LanguageNames.VisualBasic, argumentCompletion); - await SetUpEditorAsync(@" -Class C - Sub Goo() - $$ - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + Sub Goo() + $$ + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync("Dim x = {", HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentLineTextAsync(" Dim x = {$$}", assertCaretPosition: true, HangMitigatingCancellationToken); @@ -71,12 +72,14 @@ await TestServices.Input.SendWithoutActivateAsync( [IdeFact] public async Task Braces_Overtyping() { - await SetUpEditorAsync(@" -Class C - Sub Goo() - $$ - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + Sub Goo() + $$ + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync("Dim x = {", HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync('}', HangMitigatingCancellationToken); @@ -86,12 +89,14 @@ End Sub [IdeFact] public async Task ParenthesesTypeoverAfterStringLiterals() { - await SetUpEditorAsync(@" -Class C - Sub Goo() - $$ - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + Sub Goo() + $$ + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync("Console.Write(", HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentLineTextAsync(" Console.Write($$)", assertCaretPosition: true, HangMitigatingCancellationToken); @@ -109,23 +114,27 @@ End Sub [IdeFact] public async Task Braces_OnReturnNoFormattingOnlyIndentationBeforeCloseBrace() { - await SetUpEditorAsync(@" -Class C - Sub Goo() - $$ - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + Sub Goo() + $$ + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync("Dim x = {", HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync(VirtualKeyCode.RETURN, HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentLineTextAsync(" $$}", assertCaretPosition: true, HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -Class C - Sub Goo() - Dim x = { - $$} - End Sub -End Class", + await TestServices.EditorVerifier.TextContainsAsync(""" + + Class C + Sub Goo() + Dim x = { + $$} + End Sub + End Class + """, assertCaretPosition: true, HangMitigatingCancellationToken); } @@ -133,10 +142,12 @@ End Sub [IdeFact] public async Task Paren_InsertionAndTabCompleting() { - await SetUpEditorAsync(@" -Class C - $$ -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + $$ + End Class + """, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync("Sub Goo(", HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentLineTextAsync(" Sub Goo($$)", assertCaretPosition: true, HangMitigatingCancellationToken); @@ -150,10 +161,12 @@ Class C [IdeFact] public async Task Paren_Overtyping() { - await SetUpEditorAsync(@" -Class C - $$ -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + $$ + End Class + """, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync("Sub Goo(", HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentLineTextAsync(" Sub Goo($$)", assertCaretPosition: true, HangMitigatingCancellationToken); @@ -166,12 +179,14 @@ Class C [IdeFact] public async Task Bracket_Insertion() { - await SetUpEditorAsync(@" -Class C - Sub Goo() - $$ - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + Sub Goo() + $$ + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync("Dim [Dim", HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentLineTextAsync(" Dim [Dim$$]", assertCaretPosition: true, HangMitigatingCancellationToken); @@ -180,12 +195,14 @@ End Sub [IdeFact] public async Task Bracket_Overtyping() { - await SetUpEditorAsync(@" -Class C - Sub Goo() - $$ - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + Sub Goo() + $$ + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync("Dim [Dim", HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentLineTextAsync(" Dim [Dim$$]", assertCaretPosition: true, HangMitigatingCancellationToken); @@ -197,15 +214,21 @@ End Sub [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/63576")] public async Task DoubleQuote_InsertionAndTabCompletion() { - await SetUpEditorAsync(@" -Class C - Sub Goo() - $$ - End Sub -End Class", HangMitigatingCancellationToken); - - await TestServices.Input.SendWithoutActivateAsync("Dim str = \"", HangMitigatingCancellationToken); - await TestServices.EditorVerifier.CurrentLineTextAsync(" Dim str = \"$$\"", assertCaretPosition: true, HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + Sub Goo() + $$ + End Sub + End Class + """, HangMitigatingCancellationToken); + + await TestServices.Input.SendWithoutActivateAsync(""" + Dim str = " + """, HangMitigatingCancellationToken); + await TestServices.EditorVerifier.CurrentLineTextAsync(""" + Dim str = "$$" + """, assertCaretPosition: true, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync(VirtualKeyCode.TAB, HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentLineTextAsync(" Dim str = \"\"$$", assertCaretPosition: true, HangMitigatingCancellationToken); @@ -214,15 +237,17 @@ End Sub [IdeFact] public async Task Nested_AllKinds_1() { - await SetUpEditorAsync(@" -Class C - Sub New([dim] As String) - End Sub + await SetUpEditorAsync(""" - Sub Goo() - $$ - End Sub -End Class", HangMitigatingCancellationToken); + Class C + Sub New([dim] As String) + End Sub + + Sub Goo() + $$ + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync( [ @@ -239,15 +264,17 @@ await TestServices.Input.SendWithoutActivateAsync( [IdeFact] public async Task Nested_AllKinds_2() { - await SetUpEditorAsync(@" -Class C - Sub New([dim] As String) - End Sub + await SetUpEditorAsync(""" + + Class C + Sub New([dim] As String) + End Sub - Sub Goo() - $$ - End Sub -End Class", HangMitigatingCancellationToken); + Sub Goo() + $$ + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync( [ @@ -268,38 +295,48 @@ await TestServices.Input.SendWithoutActivateAsync( [IdeFact] public async Task Negative_NoCompletionInComments() { - await SetUpEditorAsync(@" -Class C - Sub Goo() - ' $$ - End Sub -End Class", HangMitigatingCancellationToken); - - await TestServices.Input.SendWithoutActivateAsync("{([\"", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + Sub Goo() + ' $$ + End Sub + End Class + """, HangMitigatingCancellationToken); + + await TestServices.Input.SendWithoutActivateAsync(""" + {([" + """, HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentLineTextAsync(" ' {([\"$$", assertCaretPosition: true, HangMitigatingCancellationToken); } [IdeFact] public async Task Negative_NoCompletionInStringLiterals() { - await SetUpEditorAsync(@" -Class C - Sub Goo() - $$ - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + Sub Goo() + $$ + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync("Dim s = \"{([", HangMitigatingCancellationToken); - await TestServices.EditorVerifier.CurrentLineTextAsync(" Dim s = \"{([$$\"", assertCaretPosition: true, HangMitigatingCancellationToken); + await TestServices.EditorVerifier.CurrentLineTextAsync(""" + Dim s = "{([$$" + """, assertCaretPosition: true, HangMitigatingCancellationToken); } [IdeFact] public async Task Negative_NoCompletionInXmlDocComment() { - await SetUpEditorAsync(@" -$$ -Class C -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + $$ + Class C + End Class + """, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync("'''", HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync('{', HangMitigatingCancellationToken); @@ -312,14 +349,16 @@ Class C [IdeFact] public async Task Negative_NoCompletionInXmlDocCommentAtEndOfTag() { - await SetUpEditorAsync(@" -Class C - ''' - ''' $$ - ''' - Sub Goo() - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + ''' + ''' $$ + ''' + Sub Goo() + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync("(", HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentLineTextAsync(" ''' ($$", assertCaretPosition: true, HangMitigatingCancellationToken); @@ -329,12 +368,14 @@ End Sub [IdeFact] public async Task LineCommittingIssue() { - await SetUpEditorAsync(@" -Class C - Sub Goo() - $$ - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + Sub Goo() + $$ + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync("Dim x=\"\" '", HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentLineTextAsync(" Dim x=\"\" '$$", assertCaretPosition: true, HangMitigatingCancellationToken); @@ -344,11 +385,13 @@ End Sub [IdeFact] public async Task VirtualWhitespaceIssue() { - await SetUpEditorAsync(@" -Class C - Sub Goo()$$ - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + Sub Goo()$$ + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync(VirtualKeyCode.RETURN, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync('(', HangMitigatingCancellationToken); @@ -361,14 +404,16 @@ End Sub [IdeFact] public async Task CompletionWithIntelliSenseWindowUp() { - await SetUpEditorAsync(@" -Class C - Sub Goo() - End Sub - Sub Test() - $$ - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + Sub Goo() + End Sub + Sub Test() + $$ + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync("Goo(", HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentLineTextAsync(" Goo($$)", assertCaretPosition: true, HangMitigatingCancellationToken); @@ -378,9 +423,11 @@ End Sub [IdeFact] public async Task CompletionAtTheEndOfFile() { - await SetUpEditorAsync(@" -Class C - $$", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + $$ + """, HangMitigatingCancellationToken); await TestServices.Input.SendWithoutActivateAsync("Sub Goo(", HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentLineTextAsync(" Sub Goo($$)", assertCaretPosition: true, HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicBuild.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicBuild.cs index 2ed076ae4d016..8dc01653c1f09 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicBuild.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicBuild.cs @@ -30,15 +30,15 @@ public override async Task InitializeAsync() [IdeFact, Trait(Traits.Feature, Traits.Features.Build)] public async Task BuildProject() { - var editorText = @"Module Module1 + await TestServices.Editor.SetTextAsync(""" + Module Module1 - Sub Main() - Console.WriteLine(""Hello, World!"") - End Sub + Sub Main() + Console.WriteLine("Hello, World!") + End Sub -End Module"; - - await TestServices.Editor.SetTextAsync(editorText, HangMitigatingCancellationToken); + End Module + """, HangMitigatingCancellationToken); var succeed = await TestServices.SolutionExplorer.BuildSolutionAndWaitAsync(HangMitigatingCancellationToken); Assert.True(succeed); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicChangeSignatureDialog.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicChangeSignatureDialog.cs index 0606a816b23e0..c85fda5c6e3d1 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicChangeSignatureDialog.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicChangeSignatureDialog.cs @@ -26,11 +26,13 @@ public BasicChangeSignatureDialog() [IdeFact] public async Task VerifyCodeRefactoringOffered() { - await SetUpEditorAsync(@" -Class C - Sub Method$$(a As Integer, b As Integer) - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + Sub Method$$(a As Integer, b As Integer) + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Change signature...", applyFix: false, cancellationToken: HangMitigatingCancellationToken); @@ -39,32 +41,38 @@ End Sub [IdeFact] public async Task VerifyRefactoringCancelled() { - await SetUpEditorAsync(@" -Class C - Sub Method$$(a As Integer, b As String) - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + Sub Method$$(a As Integer, b As String) + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.ChangeSignatureDialog.InvokeAsync(HangMitigatingCancellationToken); await TestServices.ChangeSignatureDialog.VerifyOpenAsync(HangMitigatingCancellationToken); await TestServices.ChangeSignatureDialog.ClickCancelAsync(HangMitigatingCancellationToken); await TestServices.ChangeSignatureDialog.VerifyClosedAsync(HangMitigatingCancellationToken); var actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); - Assert.Contains(@" -Class C - Sub Method(a As Integer, b As String) - End Sub -End Class", actualText); + Assert.Contains(""" + + Class C + Sub Method(a As Integer, b As String) + End Sub + End Class + """, actualText); } [IdeFact] public async Task VerifyReorderParameters() { - await SetUpEditorAsync(@" -Class C - Sub Method$$(a As Integer, b As String) - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + Sub Method$$(a As Integer, b As String) + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.ChangeSignatureDialog.InvokeAsync(HangMitigatingCancellationToken); await TestServices.ChangeSignatureDialog.VerifyOpenAsync(HangMitigatingCancellationToken); @@ -73,44 +81,49 @@ End Sub await TestServices.ChangeSignatureDialog.ClickOKAsync(HangMitigatingCancellationToken); await TestServices.ChangeSignatureDialog.VerifyClosedAsync(HangMitigatingCancellationToken); var actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); - Assert.Contains(@" -Class C - Sub Method(b As String, a As Integer) - End Sub -End Class", actualText); + Assert.Contains(""" + + Class C + Sub Method(b As String, a As Integer) + End Sub + End Class + """, actualText); } [IdeFact] public async Task VerifyReorderAndRemoveParametersAcrossLanguages() { - await SetUpEditorAsync(@" -Class VBTest - Sub TestMethod() - Dim x As New CSharpClass - x.Method$$(0, ""str"", 3.0) - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class VBTest + Sub TestMethod() + Dim x As New CSharpClass + x.Method$$(0, "str", 3.0) + End Sub + End Class + """, HangMitigatingCancellationToken); var csharpProject = "CSharpProject"; await TestServices.SolutionExplorer.AddProjectAsync(csharpProject, WellKnownProjectTemplates.ClassLibrary, LanguageNames.CSharp, HangMitigatingCancellationToken); - await TestServices.Editor.SetTextAsync(@" -public class CSharpClass -{ - /// - /// A method in CSharp. - /// - /// parameter a - /// parameter b - /// parameter c - /// One - public int Method(int a, string b, double c) - { - return 1; - } -}", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + + public class CSharpClass + { + /// + /// A method in CSharp. + /// + /// parameter a + /// parameter b + /// parameter c + /// One + public int Method(int a, string b, double c) + { + return 1; + } + } + """, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.SaveAllAsync(HangMitigatingCancellationToken); var project = ProjectName; - var csharpProjectReference = "CSharpProject"; - await TestServices.SolutionExplorer.AddProjectReferenceAsync(project, csharpProjectReference, HangMitigatingCancellationToken); + await TestServices.SolutionExplorer.AddProjectReferenceAsync(project, "CSharpProject", HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(project, "Class1.vb", HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.Workspace, HangMitigatingCancellationToken); @@ -132,35 +145,38 @@ public int Method(int a, string b, double c) Assert.Contains(@"x.Method(""str"")", actualText); await TestServices.SolutionExplorer.OpenFileAsync(csharpProject, "Class1.cs", HangMitigatingCancellationToken); actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); - var expectedText = @" -public class CSharpClass -{ - /// - /// A method in CSharp. - /// - /// parameter b - /// - /// - /// One - public int Method(string b) - { - return 1; - } -}"; - Assert.Contains(expectedText, actualText); + Assert.Contains(""" + + public class CSharpClass + { + /// + /// A method in CSharp. + /// + /// parameter b + /// + /// + /// One + public int Method(string b) + { + return 1; + } + } + """, actualText); } [IdeFact] public async Task VerifyAddParameter() { - await SetUpEditorAsync(@" -Class C - Sub Method$$(a As Integer, b As String) - End Sub - Sub NewMethod() - Method(1, ""stringB"") - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + Sub Method$$(a As Integer, b As String) + End Sub + Sub NewMethod() + Method(1, "stringB") + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.ChangeSignatureDialog.InvokeAsync(HangMitigatingCancellationToken); await TestServices.ChangeSignatureDialog.VerifyOpenAsync(HangMitigatingCancellationToken); @@ -210,24 +226,28 @@ End Sub await TestServices.ChangeSignatureDialog.ClickOKAsync(HangMitigatingCancellationToken); await TestServices.ChangeSignatureDialog.VerifyClosedAsync(HangMitigatingCancellationToken); var actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); - Assert.Contains(@" -Class C - Sub Method(a As Integer, d As Integer, b As String, c As String) - End Sub - Sub NewMethod() - Method(1, 3, ""stringB"", TODO) - End Sub -End Class", actualText); + Assert.Contains(""" + + Class C + Sub Method(a As Integer, d As Integer, b As String, c As String) + End Sub + Sub NewMethod() + Method(1, 3, "stringB", TODO) + End Sub + End Class + """, actualText); } [IdeFact] public async Task VerifyAddParameterRefactoringCancelled() { - await SetUpEditorAsync(@" -Class C - Sub Method$$(a As Integer, b As String) - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + Sub Method$$(a As Integer, b As String) + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.ChangeSignatureDialog.InvokeAsync(HangMitigatingCancellationToken); await TestServices.ChangeSignatureDialog.VerifyOpenAsync(HangMitigatingCancellationToken); @@ -241,37 +261,42 @@ End Sub await TestServices.ChangeSignatureDialog.ClickCancelAsync(HangMitigatingCancellationToken); await TestServices.ChangeSignatureDialog.VerifyClosedAsync(HangMitigatingCancellationToken); var actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); - Assert.Contains(@" -Class C - Sub Method(a As Integer, b As String) - End Sub -End Class", actualText); + Assert.Contains(""" + + Class C + Sub Method(a As Integer, b As String) + End Sub + End Class + """, actualText); } [IdeFact] public async Task VerifyAddParametersAcrossLanguages() { - await SetUpEditorAsync(@" -Class VBTest - Sub TestMethod() - Dim x As New CSharpClass - x.Method$$(0, ""str"", 3.0) - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class VBTest + Sub TestMethod() + Dim x As New CSharpClass + x.Method$$(0, "str", 3.0) + End Sub + End Class + """, HangMitigatingCancellationToken); var csharpProject = "CSharpProject"; await TestServices.SolutionExplorer.AddProjectAsync(csharpProject, WellKnownProjectTemplates.ClassLibrary, LanguageNames.CSharp, HangMitigatingCancellationToken); - await TestServices.Editor.SetTextAsync(@" -public class CSharpClass -{ - public int Method(int a, string b, double c) - { - return 1; - } -}", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + + public class CSharpClass + { + public int Method(int a, string b, double c) + { + return 1; + } + } + """, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.SaveAllAsync(HangMitigatingCancellationToken); var project = ProjectName; - var csharpProjectReference = "CSharpProject"; - await TestServices.SolutionExplorer.AddProjectReferenceAsync(project, csharpProjectReference, HangMitigatingCancellationToken); + await TestServices.SolutionExplorer.AddProjectReferenceAsync(project, "CSharpProject", HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(project, "Class1.vb", HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.Workspace, HangMitigatingCancellationToken); @@ -283,7 +308,9 @@ public int Method(int a, string b, double c) await TestServices.AddParameterDialog.VerifyOpenAsync(HangMitigatingCancellationToken); await TestServices.AddParameterDialog.FillTypeFieldAsync("string", HangMitigatingCancellationToken); await TestServices.AddParameterDialog.FillNameFieldAsync("d", HangMitigatingCancellationToken); - await TestServices.AddParameterDialog.FillCallSiteFieldAsync(@"""str2""", HangMitigatingCancellationToken); + await TestServices.AddParameterDialog.FillCallSiteFieldAsync(""" + "str2" + """, HangMitigatingCancellationToken); await TestServices.AddParameterDialog.ClickOKAsync(HangMitigatingCancellationToken); await TestServices.AddParameterDialog.VerifyClosedAsync(HangMitigatingCancellationToken); @@ -293,14 +320,15 @@ public int Method(int a, string b, double c) Assert.Contains(@"x.Method(0, ""str"", 3.0, ""str2"")", actualText); await TestServices.SolutionExplorer.OpenFileAsync(csharpProject, "Class1.cs", HangMitigatingCancellationToken); actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); - var expectedText = @" -public class CSharpClass -{ - public int Method(int a, string b, double c, string d) - { - return 1; - } -}"; - Assert.Contains(expectedText, actualText); + Assert.Contains(""" + + public class CSharpClass + { + public int Method(int a, string b, double c, string d) + { + return 1; + } + } + """, actualText); } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicClassification.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicClassification.cs index 3b394b7728a5c..37f414381aae3 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicClassification.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicClassification.cs @@ -24,20 +24,22 @@ public BasicClassification() : base(nameof(BasicClassification)) [IdeFact] public async Task Verify_Color_Of_Some_Tokens() { - await TestServices.Editor.SetTextAsync(@"Imports System -Imports MathAlias = System.Math -Namespace Acme - ''' innertext - ''' - ''' - ''' - ''' - Public Class Program - Public Shared Sub Main(args As String()) - Console.WriteLine(""Hello World"") 'comment - End Sub - End Class -End Namespace", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + Imports System + Imports MathAlias = System.Math + Namespace Acme + ''' innertext + ''' + ''' + ''' + ''' + Public Class Program + Public Shared Sub Main(args As String()) + Console.WriteLine("Hello World") 'comment + End Sub + End Class + End Namespace + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("MathAlias", charsOffset: 0, HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentTokenTypeAsync(tokenType: "class name", HangMitigatingCancellationToken); @@ -70,11 +72,13 @@ End Class [IdeFact] public async Task Semantic_Classification() { - await TestServices.Editor.SetTextAsync(@" -Imports System -Class Goo - Inherits Attribute -End Class", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + + Imports System + Class Goo + Inherits Attribute + End Class + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("Goo", charsOffset: 0, HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentTokenTypeAsync(tokenType: "class name", HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("Attribute", charsOffset: 0, HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicCodeActions.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicCodeActions.cs index b95c58d734a7a..3c5ad2bedca54 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicCodeActions.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicCodeActions.cs @@ -24,32 +24,38 @@ public BasicCodeActions() [IdeFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)] public async Task GenerateMethodInClosedFile() { - await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "Goo.vb", @" -Class Goo -End Class -", cancellationToken: HangMitigatingCancellationToken); - - await SetUpEditorAsync(@" -Imports System; - -Class Program - Sub Main(args As String()) - Dim f as Goo = new Goo() - f.Bar()$$ - End Sub -End Class -", HangMitigatingCancellationToken); + await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "Goo.vb", """ + + Class Goo + End Class + + """, cancellationToken: HangMitigatingCancellationToken); + + await SetUpEditorAsync(""" + + Imports System; + + Class Program + Sub Main(args As String()) + Dim f as Goo = new Goo() + f.Bar()$$ + End Sub + End Class + + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Generate method 'Bar'", applyFix: true, cancellationToken: HangMitigatingCancellationToken); AssertEx.EqualOrDiff( - @" -Class Goo - Friend Sub Bar() - Throw New NotImplementedException() - End Sub -End Class -", + """ + + Class Goo + Friend Sub Bar() + Throw New NotImplementedException() + End Sub + End Class + + """, await TestServices.SolutionExplorer.GetFileContentsAsync(ProjectName, "Goo.vb", HangMitigatingCancellationToken)); } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicCodeDefinitionWindow.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicCodeDefinitionWindow.cs index 7d80d3dcd9686..10a266104778c 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicCodeDefinitionWindow.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicCodeDefinitionWindow.cs @@ -33,11 +33,13 @@ public async Task CodeDefinitionWindowOpensMetadataAsSource(bool enableDecompila // our regular file. await TestServices.Editor.ActivateAsync(HangMitigatingCancellationToken); - await SetUpEditorAsync(@" -Public Class Test - Dim field As $$Integer -End Class -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Public Class Test + Dim field As $$Integer + End Class + + """, HangMitigatingCancellationToken); // If we are enabling decompilation, we'll get C# code since we don't support decompiling into VB if (enableDecompilation) diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicEditAndContinue.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicEditAndContinue.cs index fa77fcf752dde..e538196f53718 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicEditAndContinue.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicEditAndContinue.cs @@ -8,8 +8,8 @@ using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; -using Roslyn.VisualStudio.IntegrationTests; using Roslyn.Test.Utilities; +using Roslyn.VisualStudio.IntegrationTests; using Xunit; namespace Roslyn.VisualStudio.NewIntegrationTests.VisualBasic; @@ -49,23 +49,25 @@ public override async Task InitializeAsync() [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/75456")] public async Task UpdateActiveStatementLeafNode() { - await TestServices.Editor.SetTextAsync(@" -Imports System -Imports System.Collections.Generic -Imports System.Linq - -Module Module1 - Sub Main() - Dim names(2) As String - names(0) = ""goo"" - names(1) = ""bar"" - - For index = 0 To names.GetUpperBound(0) - Console.WriteLine(names(index)) - Next - End Sub -End Module -", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + + Imports System + Imports System.Collections.Generic + Imports System.Linq + + Module Module1 + Sub Main() + Dim names(2) As String + names(0) = "goo" + names(1) = "bar" + + For index = 0 To names.GetUpperBound(0) + Console.WriteLine(names(index)) + Next + End Sub + End Module + + """, HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.Workspace, HangMitigatingCancellationToken); await TestServices.Debugger.SetBreakpointAsync(ProjectName, FileName, "names(0)", HangMitigatingCancellationToken); @@ -73,35 +75,43 @@ End Module await TestServices.Editor.ActivateAsync(HangMitigatingCancellationToken); await TestServices.Editor.ReplaceTextAsync("names(0)", "names(1)", HangMitigatingCancellationToken); await TestServices.Debugger.StepOverAsync(waitForBreakOrEnd: true, HangMitigatingCancellationToken); - await TestServices.Debugger.CheckExpressionAsync("names(1)", "String", "\"goo\"", HangMitigatingCancellationToken); + await TestServices.Debugger.CheckExpressionAsync("names(1)", "String", """ + "goo" + """, HangMitigatingCancellationToken); await TestServices.Debugger.StepOverAsync(waitForBreakOrEnd: true, HangMitigatingCancellationToken); - await TestServices.Debugger.CheckExpressionAsync("names(1)", "String", "\"bar\"", HangMitigatingCancellationToken); + await TestServices.Debugger.CheckExpressionAsync("names(1)", "String", """ + "bar" + """, HangMitigatingCancellationToken); } [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/75456")] public async Task AddTryCatchAroundActiveStatement() { - await TestServices.Editor.SetTextAsync(@" -Imports System -Module Module1 - Sub Main() - Goo() - End Sub - - Private Sub Goo() - Console.WriteLine(1) - End Sub -End Module", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + + Imports System + Module Module1 + Sub Main() + Goo() + End Sub + + Private Sub Goo() + Console.WriteLine(1) + End Sub + End Module + """, HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.Workspace, HangMitigatingCancellationToken); await TestServices.Debugger.SetBreakpointAsync(ProjectName, FileName, "Console.WriteLine(1)", HangMitigatingCancellationToken); await TestServices.Debugger.GoAsync(waitForBreakMode: true, HangMitigatingCancellationToken); await TestServices.Editor.ActivateAsync(HangMitigatingCancellationToken); await TestServices.Editor.ReplaceTextAsync("Console.WriteLine(1)", - @"Try -Console.WriteLine(1) -Catch ex As Exception -End Try", HangMitigatingCancellationToken); + """ + Try + Console.WriteLine(1) + Catch ex As Exception + End Try + """, HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.Workspace, HangMitigatingCancellationToken); await TestServices.Debugger.StepOverAsync(waitForBreakOrEnd: true, HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentLineTextAsync(" End Try", cancellationToken: HangMitigatingCancellationToken); @@ -110,16 +120,18 @@ Catch ex As Exception [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/75456")] public async Task EditLambdaExpression() { - await TestServices.Editor.SetTextAsync(@" -Imports System -Module Module1 - Private Delegate Function del(i As Integer) As Integer + await TestServices.Editor.SetTextAsync(""" + + Imports System + Module Module1 + Private Delegate Function del(i As Integer) As Integer - Sub Main() - Dim myDel As del = Function(x) x * x - Dim j As Integer = myDel(5) - End Sub -End Module", HangMitigatingCancellationToken); + Sub Main() + Dim myDel As del = Function(x) x * x + Dim j As Integer = myDel(5) + End Sub + End Module + """, HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.Workspace, HangMitigatingCancellationToken); await TestServices.Debugger.SetBreakpointAsync(ProjectName, FileName, "x * x", charsOffset: -1, HangMitigatingCancellationToken); @@ -167,15 +179,17 @@ await TestServices.Workspace.WaitForAllAsyncOperationsAsync( [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/75456")] public async Task EnCWhileDebuggingFromImmediateWindow() { - await TestServices.Editor.SetTextAsync(@" -Imports System + await TestServices.Editor.SetTextAsync(""" -Module Module1 - Sub Main() - Dim x = 4 - Console.WriteLine(x) - End Sub -End Module", HangMitigatingCancellationToken); + Imports System + + Module Module1 + Sub Main() + Dim x = 4 + Console.WriteLine(x) + End Sub + End Module + """, HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.Workspace, HangMitigatingCancellationToken); await TestServices.Debugger.GoAsync(waitForBreakMode: true, HangMitigatingCancellationToken); @@ -197,32 +211,36 @@ private async Task SetupMultiProjectSolutionAsync(CancellationToken cancellation await TestServices.SolutionExplorer.AddFileAsync(cSharpLibrary, "File1.cs", cancellationToken: cancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(basicLibrary, "Class1.vb", cancellationToken); - await TestServices.Editor.SetTextAsync(@" -Imports System -Public Class Class1 - Public Sub New() - End Sub - - Public Sub PrintX(x As Integer) - Console.WriteLine(x) - End Sub -End Class -", cancellationToken); + await TestServices.Editor.SetTextAsync(""" + + Imports System + Public Class Class1 + Public Sub New() + End Sub + + Public Sub PrintX(x As Integer) + Console.WriteLine(x) + End Sub + End Class + + """, cancellationToken); await TestServices.SolutionExplorer.AddProjectReferenceAsync(ProjectName, basicLibrary, cancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, FileName, cancellationToken); - await TestServices.Editor.SetTextAsync(@" -Imports System -Imports BasicLibrary1 + await TestServices.Editor.SetTextAsync(""" + + Imports System + Imports BasicLibrary1 + + Module Module1 + Sub Main() + Dim c As New Class1() + c.PrintX(5) + End Sub + End Module -Module Module1 - Sub Main() - Dim c As New Class1() - c.PrintX(5) - End Sub -End Module -", cancellationToken); + """, cancellationToken); await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.Workspace, cancellationToken); } @@ -254,20 +272,24 @@ await TestServices.Workspace.WaitForAllAsyncOperationsAsync( [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/75456")] public async Task LocalsWindowUpdatesAfterLocalGetsItsTypeUpdatedDuringEnC() { - await TestServices.Editor.SetTextAsync(@" -Imports System -Module Module1 - Sub Main() - Dim goo As String = ""abc"" - Console.WriteLine(goo) - End Sub -End Module -", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + + Imports System + Module Module1 + Sub Main() + Dim goo As String = "abc" + Console.WriteLine(goo) + End Sub + End Module + + """, HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.Workspace, HangMitigatingCancellationToken); await TestServices.Debugger.SetBreakpointAsync(ProjectName, FileName, "End Sub", HangMitigatingCancellationToken); await TestServices.Debugger.GoAsync(waitForBreakMode: true, HangMitigatingCancellationToken); await TestServices.Editor.ActivateAsync(HangMitigatingCancellationToken); - await TestServices.Editor.ReplaceTextAsync("Dim goo As String = \"abc\"", "Dim goo As Single = 10", HangMitigatingCancellationToken); + await TestServices.Editor.ReplaceTextAsync(""" + Dim goo As String = "abc" + """, "Dim goo As Single = 10", HangMitigatingCancellationToken); await TestServices.Editor.SelectTextInCurrentDocumentAsync("Sub Main()", HangMitigatingCancellationToken); await TestServices.Debugger.SetNextStatementAsync(HangMitigatingCancellationToken); await TestServices.Debugger.GoAsync(waitForBreakMode: true, HangMitigatingCancellationToken); @@ -278,23 +300,25 @@ End Module [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/75456")] public async Task LocalsWindowUpdatesCorrectlyDuringEnC() { - await TestServices.Editor.SetTextAsync(@" -Imports System - -Module Module1 - Sub Main() - bar(5) - End Sub - - Function bar(ByVal moo As Long) As Decimal - Dim iInt As Integer = 0 - Dim lLng As Long = 5 - - iInt += 30 - Return 4 - End Function -End Module -", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + + Imports System + + Module Module1 + Sub Main() + bar(5) + End Sub + + Function bar(ByVal moo As Long) As Decimal + Dim iInt As Integer = 0 + Dim lLng As Long = 5 + + iInt += 30 + Return 4 + End Function + End Module + + """, HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.Workspace, HangMitigatingCancellationToken); await TestServices.Debugger.SetBreakpointAsync(ProjectName, FileName, "Function bar(ByVal moo As Long) As Decimal", HangMitigatingCancellationToken); await TestServices.Debugger.GoAsync(waitForBreakMode: true, HangMitigatingCancellationToken); @@ -312,16 +336,18 @@ End Module [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/75456")] public async Task WatchWindowUpdatesCorrectlyDuringEnC() { - await TestServices.Editor.SetTextAsync(@" -Imports System + await TestServices.Editor.SetTextAsync(""" + + Imports System + + Module Module1 + Sub Main() + Dim iInt As Integer = 0 + System.Diagnostics.Debugger.Break() + End Sub + End Module -Module Module1 - Sub Main() - Dim iInt As Integer = 0 - System.Diagnostics.Debugger.Break() - End Sub -End Module -", HangMitigatingCancellationToken); + """, HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.Workspace, HangMitigatingCancellationToken); await TestServices.Debugger.GoAsync(waitForBreakMode: true, HangMitigatingCancellationToken); @@ -329,8 +355,10 @@ End Module await TestServices.Debugger.CheckExpressionAsync("iInt", "Integer", "0", HangMitigatingCancellationToken); - await TestServices.Editor.ReplaceTextAsync("System.Diagnostics.Debugger.Break()", @"iInt = 5 -System.Diagnostics.Debugger.Break()", HangMitigatingCancellationToken); + await TestServices.Editor.ReplaceTextAsync("System.Diagnostics.Debugger.Break()", """ + iInt = 5 + System.Diagnostics.Debugger.Break() + """, HangMitigatingCancellationToken); await TestServices.Editor.SelectTextInCurrentDocumentAsync("iInt = 5", HangMitigatingCancellationToken); await TestServices.Debugger.SetNextStatementAsync(HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicEncapsulateField.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicEncapsulateField.cs index 197214b9e86e8..d55512104b8d8 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicEncapsulateField.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicEncapsulateField.cs @@ -22,13 +22,15 @@ public BasicEncapsulateField() protected override string LanguageName => LanguageNames.VisualBasic; - private const string TestSource = @" -Module Module1 - Public $$name As Integer? = 0 - Sub Main() - name = 90 - End Sub -End Module"; + private const string TestSource = """ + + Module Module1 + Public $$name As Integer? = 0 + Sub Main() + name = 90 + End Sub + End Module + """; [IdeFact] public async Task EncapsulateThroughCommand() @@ -44,16 +46,18 @@ public async Task EncapsulateThroughCommand() await encapsulateField.InvokeAsync(HangMitigatingCancellationToken); await dialog.VerifyOpenAsync(encapsulateField.DialogName, HangMitigatingCancellationToken); await dialog.ClickApplyAndWaitForFeatureAsync(encapsulateField.DialogName, FeatureAttribute.EncapsulateField, HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" Private _name As Integer? = 0 - - Public Property Name As Integer? - Get - Return _name - End Get - Set(value As Integer?) - _name = value - End Set - End Property", cancellationToken: HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextContainsAsync(""" + Private _name As Integer? = 0 + + Public Property Name As Integer? + Get + Return _name + End Get + Set(value As Integer?) + _name = value + End Set + End Property + """, cancellationToken: HangMitigatingCancellationToken); } [IdeFact] @@ -69,23 +73,25 @@ public async Task EncapsulateThroughLightbulbIncludingReferences() await TestServices.EditorVerifier.CodeActionAsync("Encapsulate field: 'name' (and use property)", applyFix: true, blockUntilComplete: true, cancellationToken: HangMitigatingCancellationToken); } - await TestServices.EditorVerifier.TextContainsAsync(@" -Module Module1 - Private _name As Integer? = 0 - - Public Property Name As Integer? - Get - Return _name - End Get - Set(value As Integer?) - _name = value - End Set - End Property - - Sub Main() - Name = 90 - End Sub -End Module", cancellationToken: HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextContainsAsync(""" + + Module Module1 + Private _name As Integer? = 0 + + Public Property Name As Integer? + Get + Return _name + End Get + Set(value As Integer?) + _name = value + End Set + End Property + + Sub Main() + Name = 90 + End Sub + End Module + """, cancellationToken: HangMitigatingCancellationToken); } [IdeFact] @@ -101,22 +107,24 @@ public async Task EncapsulateThroughLightbulbDefinitionsOnly() await TestServices.EditorVerifier.CodeActionAsync("Encapsulate field: 'name' (but still use field)", applyFix: true, blockUntilComplete: true, cancellationToken: HangMitigatingCancellationToken); } - await TestServices.EditorVerifier.TextContainsAsync(@" -Module Module1 - Private _name As Integer? = 0 - - Public Property Name As Integer? - Get - Return _name - End Get - Set(value As Integer?) - _name = value - End Set - End Property - - Sub Main() - name = 90 - End Sub -End Module", cancellationToken: HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextContainsAsync(""" + + Module Module1 + Private _name As Integer? = 0 + + Public Property Name As Integer? + Get + Return _name + End Get + Set(value As Integer?) + _name = value + End Set + End Property + + Sub Main() + name = 90 + End Sub + End Module + """, cancellationToken: HangMitigatingCancellationToken); } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicEndConstruct.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicEndConstruct.cs index d68b2dfc8b8f3..4d8064925bba2 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicEndConstruct.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicEndConstruct.cs @@ -24,74 +24,90 @@ public BasicEndConstruct() [IdeFact] public async Task EndConstruct() { - await SetUpEditorAsync(@" -Class Program - Sub Main() - If True Then $$ - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class Program + Sub Main() + If True Then $$ + End Sub + End Class + """, HangMitigatingCancellationToken); // Send a space to convert virtual whitespace into real whitespace await TestServices.Input.SendAsync([VirtualKeyCode.RETURN, " "], HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -Class Program - Sub Main() - If True Then - $$ - End If - End Sub -End Class", assertCaretPosition: true, HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextContainsAsync(""" + + Class Program + Sub Main() + If True Then + $$ + End If + End Sub + End Class + """, assertCaretPosition: true, HangMitigatingCancellationToken); } [IdeFact] public async Task IntelliSenseCompletedWhile() { - await SetUpEditorAsync(@" -Class Program - Sub Main() - $$ - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class Program + Sub Main() + $$ + End Sub + End Class + """, HangMitigatingCancellationToken); // Send a space to convert virtual whitespace into real whitespace await TestServices.Input.SendAsync(["While True", VirtualKeyCode.RETURN, " "], HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -Class Program - Sub Main() - While True - $$ - End While - End Sub -End Class", assertCaretPosition: true, HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextContainsAsync(""" + + Class Program + Sub Main() + While True + $$ + End While + End Sub + End Class + """, assertCaretPosition: true, HangMitigatingCancellationToken); } [IdeFact] public async Task InterfaceToClassFixup() { - await SetUpEditorAsync(@" -Interface$$ C -End Interface", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Interface$$ C + End Interface + """, HangMitigatingCancellationToken); await TestServices.Input.SendAsync((VirtualKeyCode.BACK, VirtualKeyCode.CONTROL), HangMitigatingCancellationToken); await TestServices.Input.SendAsync(["Class", VirtualKeyCode.TAB], HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -Class C -End Class", cancellationToken: HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextContainsAsync(""" + + Class C + End Class + """, cancellationToken: HangMitigatingCancellationToken); } [IdeFact] public async Task CaseInsensitiveSubToFunction() { - await SetUpEditorAsync(@" -Class C - Public Sub$$ Goo() - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + Public Sub$$ Goo() + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Input.SendAsync((VirtualKeyCode.BACK, VirtualKeyCode.CONTROL), HangMitigatingCancellationToken); await TestServices.Input.SendAsync(["fu", VirtualKeyCode.TAB], HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -Class C - Public Function Goo() - End Function -End Class", cancellationToken: HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextContainsAsync(""" + + Class C + Public Function Goo() + End Function + End Class + """, cancellationToken: HangMitigatingCancellationToken); } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicErrorListCommon.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicErrorListCommon.cs index 248b65f874c89..e5d5f508ed17b 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicErrorListCommon.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicErrorListCommon.cs @@ -26,19 +26,21 @@ protected BasicErrorListCommon(string templateName) [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/63041")] public virtual async Task ErrorList() { - await TestServices.Editor.SetTextAsync(@" -Module Module1 + await TestServices.Editor.SetTextAsync(""" - Function Good() As P - Return Nothing - End Function + Module Module1 - Sub Main() - Goo() - End Sub + Function Good() As P + Return Nothing + End Function -End Module -", HangMitigatingCancellationToken); + Sub Main() + Goo() + End Sub + + End Module + + """, HangMitigatingCancellationToken); await TestServices.ErrorList.ShowErrorListAsync(HangMitigatingCancellationToken); var expectedContents = new[] { "Class1.vb(4, 24): error BC30002: Type 'P' is not defined.", @@ -64,16 +66,18 @@ End Module [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/63981 and https://github.com/dotnet/roslyn/issues/63982")] public virtual async Task ErrorsDuringMethodBodyEditing() { - await TestServices.Editor.SetTextAsync(@" -Namespace N - Class C - Private F As Integer - Sub S() - ' Comment - End Sub - End Class -End Namespace -", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + + Namespace N + Class C + Private F As Integer + Sub S() + ' Comment + End Sub + End Class + End Namespace + + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync(" Comment", charsOffset: -2, HangMitigatingCancellationToken); await TestServices.Input.SendAsync("F = 0", HangMitigatingCancellationToken); await TestServices.ErrorList.ShowErrorListAsync(HangMitigatingCancellationToken); @@ -113,8 +117,10 @@ End Namespace public virtual async Task BuildErrorsInClosedFiles() { // Enter code with compiler error. - await TestServices.Editor.SetTextAsync(@"Class Class1 -", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + Class Class1 + + """, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.SaveAllAsync(HangMitigatingCancellationToken); // Close active tab before build. diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicExpressionEvaluator.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicExpressionEvaluator.cs index 470f91da44d51..2f77558f37f46 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicExpressionEvaluator.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicExpressionEvaluator.cs @@ -26,41 +26,43 @@ public override async Task InitializeAsync() await TestServices.SolutionExplorer.CreateSolutionAsync(nameof(BasicExpressionEvaluator), HangMitigatingCancellationToken); await TestServices.SolutionExplorer.AddProjectAsync("TestProj", WellKnownProjectTemplates.ConsoleApplication, LanguageNames.VisualBasic, HangMitigatingCancellationToken); - await TestServices.Editor.SetTextAsync(@"Imports System + await TestServices.Editor.SetTextAsync(""" + Imports System -Module Module1 + Module Module1 - Sub Main() - Dim mySByte As SByte = SByte.MaxValue / 2 - Dim myShort As Short = Short.MaxValue / 2 - Dim myInt As Integer = Integer.MaxValue / 2 - Dim myLong As Long = Long.MaxValue / 2 + Sub Main() + Dim mySByte As SByte = SByte.MaxValue / 2 + Dim myShort As Short = Short.MaxValue / 2 + Dim myInt As Integer = Integer.MaxValue / 2 + Dim myLong As Long = Long.MaxValue / 2 - Dim myByte As Byte = Byte.MaxValue / 2 - Dim myUShort As UShort = UShort.MaxValue / 2 - Dim myUInt As UInteger = UInteger.MaxValue / 2 - Dim myULong As ULong = ULong.MaxValue / 2 + Dim myByte As Byte = Byte.MaxValue / 2 + Dim myUShort As UShort = UShort.MaxValue / 2 + Dim myUInt As UInteger = UInteger.MaxValue / 2 + Dim myULong As ULong = ULong.MaxValue / 2 - Dim myFloat As Single = Single.MaxValue / 2 - Dim myDouble As Double = Double.MaxValue / 2 - Dim myDecimal As Decimal = Decimal.MaxValue / 2 + Dim myFloat As Single = Single.MaxValue / 2 + Dim myDouble As Double = Double.MaxValue / 2 + Dim myDecimal As Decimal = Decimal.MaxValue / 2 - Dim myChar As Char = ""A""c - Dim myBool As Boolean = True + Dim myChar As Char = "A"c + Dim myBool As Boolean = True - Dim myObject As Object = Nothing - Dim myString As String = String.Empty + Dim myObject As Object = Nothing + Dim myString As String = String.Empty - Dim myValueType As System.ValueType = myShort - Dim myEnum As System.Enum = Nothing - Dim myArray As System.Array = Nothing - Dim myDelegate As System.Delegate = Nothing - Dim myMulticastDelegate As System.MulticastDelegate = Nothing + Dim myValueType As System.ValueType = myShort + Dim myEnum As System.Enum = Nothing + Dim myArray As System.Array = Nothing + Dim myDelegate As System.Delegate = Nothing + Dim myMulticastDelegate As System.MulticastDelegate = Nothing - System.Diagnostics.Debugger.Break() - End Sub + System.Diagnostics.Debugger.Break() + End Sub -End Module", HangMitigatingCancellationToken); + End Module + """, HangMitigatingCancellationToken); } [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/75456")] @@ -80,10 +82,14 @@ public async Task ValidateLocalsWindow() Assert.Equal(("Single", "1.70141173E+38"), await TestServices.LocalsWindow.GetEntryAsync(["myFloat"], HangMitigatingCancellationToken)); Assert.Equal(("Double", "8.9884656743115785E+307"), await TestServices.LocalsWindow.GetEntryAsync(["myDouble"], HangMitigatingCancellationToken)); Assert.Equal(("Decimal", "39614081257132168796771975168"), await TestServices.LocalsWindow.GetEntryAsync(["myDecimal"], HangMitigatingCancellationToken)); - Assert.Equal(("Char", "\"A\"c"), await TestServices.LocalsWindow.GetEntryAsync(["myChar"], HangMitigatingCancellationToken)); + Assert.Equal(("Char", """ + "A"c + """), await TestServices.LocalsWindow.GetEntryAsync(["myChar"], HangMitigatingCancellationToken)); Assert.Equal(("Boolean", "True"), await TestServices.LocalsWindow.GetEntryAsync(["myBool"], HangMitigatingCancellationToken)); Assert.Equal(("Object", "Nothing"), await TestServices.LocalsWindow.GetEntryAsync(["myObject"], HangMitigatingCancellationToken)); - Assert.Equal(("String", "\"\""), await TestServices.LocalsWindow.GetEntryAsync(["myString"], HangMitigatingCancellationToken)); + Assert.Equal(("String", """ + "" + """), await TestServices.LocalsWindow.GetEntryAsync(["myString"], HangMitigatingCancellationToken)); Assert.Equal(("System.ValueType {Short}", "16384"), await TestServices.LocalsWindow.GetEntryAsync(["myValueType"], HangMitigatingCancellationToken)); Assert.Equal(("System.Enum", "Nothing"), await TestServices.LocalsWindow.GetEntryAsync(["myEnum"], HangMitigatingCancellationToken)); Assert.Equal(("System.Array", "Nothing"), await TestServices.LocalsWindow.GetEntryAsync(["myArray"], HangMitigatingCancellationToken)); @@ -99,9 +105,13 @@ public async Task EvaluatePrimitiveValues() // It is better to use the Immediate Window but DTE does not provide an access to it. await TestServices.Debugger.CheckExpressionAsync("myByte", "Byte", "128", HangMitigatingCancellationToken); await TestServices.Debugger.CheckExpressionAsync("myFloat", "Single", "1.70141173E+38", HangMitigatingCancellationToken); - await TestServices.Debugger.CheckExpressionAsync("myChar", "Char", "\"A\"c", HangMitigatingCancellationToken); + await TestServices.Debugger.CheckExpressionAsync("myChar", "Char", """ + "A"c + """, HangMitigatingCancellationToken); await TestServices.Debugger.CheckExpressionAsync("myObject", "Object", "Nothing", HangMitigatingCancellationToken); - await TestServices.Debugger.CheckExpressionAsync("myString", "String", "\"\"", HangMitigatingCancellationToken); + await TestServices.Debugger.CheckExpressionAsync("myString", "String", """ + "" + """, HangMitigatingCancellationToken); } [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/75456")] @@ -122,26 +132,28 @@ public async Task EvaluateInvalidExpressions() [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/75456")] public async Task StateMachineTypeParameters() { - await TestServices.Editor.SetTextAsync(@" -Imports System -Imports System.Collections.Generic - -Module Module1 - Sub Main() - For Each arg In I({ ""a"", ""b""}) - Console.WriteLine(arg) - Next - End Sub - - Iterator Function I(Of T)(tt As T()) As IEnumerable(Of T) - For Each item In tt - Stop - Yield item - Next - End Function - -End Module -", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + + Imports System + Imports System.Collections.Generic + + Module Module1 + Sub Main() + For Each arg In I({ "a", "b"}) + Console.WriteLine(arg) + Next + End Sub + + Iterator Function I(Of T)(tt As T()) As IEnumerable(Of T) + For Each item In tt + Stop + Yield item + Next + End Function + + End Module + + """, HangMitigatingCancellationToken); await TestServices.Debugger.GoAsync(waitForBreakMode: true, HangMitigatingCancellationToken); Assert.Equal(("", ""), await TestServices.LocalsWindow.GetEntryAsync(["Type variables"], HangMitigatingCancellationToken)); Assert.Equal(("String", "String"), await TestServices.LocalsWindow.GetEntryAsync(["Type variables", "T"], HangMitigatingCancellationToken)); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicExtractInterfaceDialog.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicExtractInterfaceDialog.cs index 41161a96a59a3..c9393720216f9 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicExtractInterfaceDialog.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicExtractInterfaceDialog.cs @@ -24,10 +24,12 @@ public BasicExtractInterfaceDialog() [IdeFact] public async Task CoreScenario() { - await SetUpEditorAsync(@"Class C$$ - Public Sub M() - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + Class C$$ + Public Sub M() + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", @@ -41,27 +43,33 @@ await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, "Class1.vb", HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@"Class C - Implements IC + await TestServices.EditorVerifier.TextContainsAsync(""" + Class C + Implements IC - Public Sub M() Implements IC.M - End Sub -End Class", cancellationToken: HangMitigatingCancellationToken); + Public Sub M() Implements IC.M + End Sub + End Class + """, cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, "IC.vb", HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@"Interface IC - Sub M() -End Interface", cancellationToken: HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextContainsAsync(""" + Interface IC + Sub M() + End Interface + """, cancellationToken: HangMitigatingCancellationToken); } [IdeFact] public async Task CheckFileName() { - await SetUpEditorAsync(@"Class C2$$ - Public Sub M() - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + Class C2$$ + Public Sub M() + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", @@ -81,10 +89,12 @@ await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", [IdeFact] public async Task CheckSameFile() { - await SetUpEditorAsync(@"Class C$$ - Public Sub M() - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + Class C$$ + Public Sub M() + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", applyFix: true, @@ -98,27 +108,31 @@ await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", await TestServices.ExtractInterfaceDialog.ClickOKAsync(HangMitigatingCancellationToken); await TestServices.ExtractInterfaceDialog.VerifyClosedAsync(HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@"Interface IC - Sub M() -End Interface + await TestServices.EditorVerifier.TextContainsAsync(""" + Interface IC + Sub M() + End Interface -Class C - Implements IC + Class C + Implements IC - Public Sub M() Implements IC.M - End Sub -End Class", cancellationToken: HangMitigatingCancellationToken); + Public Sub M() Implements IC.M + End Sub + End Class + """, cancellationToken: HangMitigatingCancellationToken); } [IdeFact] public async Task CheckSameFileOnlySelectedItems() { - await SetUpEditorAsync(@"Class C$$ - Public Sub M1() - Public Sub M2() - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + Class C$$ + Public Sub M1() + Public Sub M2() + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", @@ -133,28 +147,32 @@ await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", await TestServices.ExtractInterfaceDialog.ClickOKAsync(HangMitigatingCancellationToken); await TestServices.ExtractInterfaceDialog.VerifyClosedAsync(HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@"Interface IC - Sub M2() -End Interface + await TestServices.EditorVerifier.TextContainsAsync(""" + Interface IC + Sub M2() + End Interface -Class C - Implements IC + Class C + Implements IC - Public Sub M1() - Public Sub M2() Implements IC.M2 - End Sub -End Class"); + Public Sub M1() + Public Sub M2() Implements IC.M2 + End Sub + End Class + """); } [IdeFact] public async Task CheckSameFileNamespace() { - await SetUpEditorAsync(@"Namespace A - Class C$$ - Public Sub M() - End Sub - End Class -End Namespace", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + Namespace A + Class C$$ + Public Sub M() + End Sub + End Class + End Namespace + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", @@ -169,17 +187,19 @@ await TestServices.EditorVerifier.CodeActionAsync("Extract interface...", await TestServices.ExtractInterfaceDialog.ClickOKAsync(HangMitigatingCancellationToken); await TestServices.ExtractInterfaceDialog.VerifyClosedAsync(HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@"Namespace A - Interface IC - Sub M() - End Interface + await TestServices.EditorVerifier.TextContainsAsync(""" + Namespace A + Interface IC + Sub M() + End Interface - Class C - Implements IC + Class C + Implements IC - Public Sub M() Implements IC.M - End Sub - End Class -End Namespace", cancellationToken: HangMitigatingCancellationToken); + Public Sub M() Implements IC.M + End Sub + End Class + End Namespace + """, cancellationToken: HangMitigatingCancellationToken); } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicExtractMethod.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicExtractMethod.cs index bb28d06a8d51b..6b8ad0e4ee628 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicExtractMethod.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicExtractMethod.cs @@ -18,25 +18,27 @@ namespace Roslyn.VisualStudio.NewIntegrationTests.VisualBasic; [Trait(Traits.Feature, Traits.Features.ExtractMethod)] public class BasicExtractMethod : AbstractEditorTest { - private const string TestSource = @" -Imports System -Imports System.Collections.Generic -Imports System.Linq - -Module Program - Sub Main(args As String()) - Console.WriteLine(""Hello VB!"") - End Sub - - Function F() As Integer - Dim a As Integer - Dim b As Integer - a = 5 - b = 5 - Dim result = a * b - Return result - End Function -End Module"; + private const string TestSource = """ + + Imports System + Imports System.Collections.Generic + Imports System.Linq + + Module Program + Sub Main(args As String()) + Console.WriteLine("Hello VB!") + End Sub + + Function F() As Integer + Dim a As Integer + Dim b As Integer + a = 5 + b = 5 + Dim result = a * b + Return result + End Function + End Module + """; protected override string LanguageName => LanguageNames.VisualBasic; @@ -53,40 +55,41 @@ public async Task SimpleExtractMethod() await TestServices.Editor.PlaceCaretAsync("Hello VB!", charsOffset: 3, occurrence: 0, extendSelection: true, selectBlock: false, HangMitigatingCancellationToken); await TestServices.Shell.ExecuteCommandAsync(WellKnownCommands.Refactor.ExtractMethod, HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.ExtractMethod, HangMitigatingCancellationToken); - - var expectedMarkup = @" -Imports System -Imports System.Collections.Generic -Imports System.Linq - -Module Program - Sub Main(args As String()) - [|NewMethod|]() - End Sub - - Private Sub [|NewMethod|]() - Console.WriteLine(""Hello VB!"") - End Sub - - Function F() As Integer - Dim a As Integer - Dim b As Integer - a = 5 - b = 5 - Dim result = a * b - Return result - End Function -End Module"; - - MarkupTestFile.GetSpans(expectedMarkup, out var expectedText, out var spans); + MarkupTestFile.GetSpans(""" + + Imports System + Imports System.Collections.Generic + Imports System.Linq + + Module Program + Sub Main(args As String()) + [|NewMethod|]() + End Sub + + Private Sub [|NewMethod|]() + Console.WriteLine("Hello VB!") + End Sub + + Function F() As Integer + Dim a As Integer + Dim b As Integer + a = 5 + b = 5 + Dim result = a * b + Return result + End Function + End Module + """, out var expectedText, out var spans); await TestServices.EditorVerifier.TextContainsAsync(expectedText, cancellationToken: HangMitigatingCancellationToken); var tags = (await TestServices.Editor.GetRenameTagsAsync(HangMitigatingCancellationToken)).SelectAsArray(tag => tag.Span.Span.ToTextSpan()); AssertEx.SetEqual(spans, tags); await TestServices.Input.SendAsync(["SayHello", VirtualKeyCode.RETURN], HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" Private Sub SayHello() - Console.WriteLine(""Hello VB!"") - End Sub", cancellationToken: HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextContainsAsync(""" + Private Sub SayHello() + Console.WriteLine("Hello VB!") + End Sub + """, cancellationToken: HangMitigatingCancellationToken); } [IdeFact] @@ -96,33 +99,32 @@ public async Task ExtractViaCodeAction() await TestServices.Editor.PlaceCaretAsync("a = 5", charsOffset: -1, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("a * b", charsOffset: 1, occurrence: 0, extendSelection: true, selectBlock: false, HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Extract method", applyFix: true, blockUntilComplete: true, cancellationToken: HangMitigatingCancellationToken); - - var expectedMarkup = @" -Imports System -Imports System.Collections.Generic -Imports System.Linq - -Module Program - Sub Main(args As String()) - Console.WriteLine(""Hello VB!"") - End Sub - - Function F() As Integer - Dim a As Integer - Dim b As Integer - Dim result As Integer = Nothing - [|NewMethod|](a, b, result) - Return result - End Function - - Private Sub [|NewMethod|](ByRef a As Integer, ByRef b As Integer, ByRef result As Integer) - a = 5 - b = 5 - result = a * b - End Sub -End Module"; - - MarkupTestFile.GetSpans(expectedMarkup, out var expectedText, out var spans); + MarkupTestFile.GetSpans(""" + + Imports System + Imports System.Collections.Generic + Imports System.Linq + + Module Program + Sub Main(args As String()) + Console.WriteLine("Hello VB!") + End Sub + + Function F() As Integer + Dim a As Integer + Dim b As Integer + Dim result As Integer = Nothing + [|NewMethod|](a, b, result) + Return result + End Function + + Private Sub [|NewMethod|](ByRef a As Integer, ByRef b As Integer, ByRef result As Integer) + a = 5 + b = 5 + result = a * b + End Sub + End Module + """, out var expectedText, out var spans); Assert.Equal(expectedText, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); var tags = (await TestServices.Editor.GetRenameTagsAsync(HangMitigatingCancellationToken)).SelectAsArray(tag => tag.Span.Span.ToTextSpan()); AssertEx.SetEqual(spans, tags); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicF1Help.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicF1Help.cs index af4b961eae419..a3ff6661e68a9 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicF1Help.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicF1Help.cs @@ -23,26 +23,26 @@ public BasicF1Help() } [IdeFact] - private async Task F1Help() + public async Task F1Help() { - var text = @" -Imports System -Imports System.Collections.Generic -Imports System.Linq - -Module Program$$ - Sub Main(args As String()) - Dim query = From arg In args - Select args.Any(Function(a) a.Length > 5) - Dim x = 0 - x += 1 - End Sub - Public Function F() As Object - Return Nothing - End Function -End Module"; - - await SetUpEditorAsync(text, HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Imports System + Imports System.Collections.Generic + Imports System.Linq + + Module Program$$ + Sub Main(args As String()) + Dim query = From arg In args + Select args.Any(Function(a) a.Length > 5) + Dim x = 0 + x += 1 + End Sub + Public Function F() As Object + Return Nothing + End Function + End Module + """, HangMitigatingCancellationToken); await VerifyAsync("Linq", "System.Linq", HangMitigatingCancellationToken); await VerifyAsync("String", "vb.String", HangMitigatingCancellationToken); await VerifyAsync("Any", "System.Linq.Enumerable.Any", HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicFindReferences.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicFindReferences.cs index d2bb4e39d757e..2487d5c74ff12 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicFindReferences.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicFindReferences.cs @@ -25,14 +25,16 @@ public BasicFindReferences() [IdeFact] public async Task FindReferencesToLocals() { - await SetUpEditorAsync(@" -Class Program - Sub Main() - Dim local = 1 - Console.WriteLine(loca$$l) - End Sub -End Class -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class Program + Sub Main() + Dim local = 1 + Console.WriteLine(loca$$l) + End Sub + End Class + + """, HangMitigatingCancellationToken); await TestServices.Input.SendAsync((VirtualKeyCode.F12, VirtualKeyCode.SHIFT), HangMitigatingCancellationToken); @@ -59,22 +61,26 @@ End Class [IdeFact] public async Task FindReferencesToSharedField() { - await SetUpEditorAsync(@" -Class Program - Public Shared Alpha As Int32 -End Class$$ -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class Program + Public Shared Alpha As Int32 + End Class$$ + + """, HangMitigatingCancellationToken); var project = ProjectName; await TestServices.SolutionExplorer.AddFileAsync(project, "File2.vb", cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(project, "File2.vb", HangMitigatingCancellationToken); - await SetUpEditorAsync(@" -Class SomeOtherClass - Sub M() - Console.WriteLine(Program.$$Alpha) - End Sub -End Class -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class SomeOtherClass + Sub M() + Console.WriteLine(Program.$$Alpha) + End Sub + End Class + + """, HangMitigatingCancellationToken); await TestServices.Input.SendAsync((VirtualKeyCode.F12, VirtualKeyCode.SHIFT), HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicFormatting.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicFormatting.cs index 5d7c98910f776..a1d905752470a 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicFormatting.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicFormatting.cs @@ -38,42 +38,52 @@ public async Task VerifyFormattingIndent() await TestServices.Editor.FormatDocumentAsync(HangMitigatingCancellationToken); await TestServices.EditorVerifier.TextContainsAsync( -@"Module A - Sub Main(args As String()) + """ + Module A + Sub Main(args As String()) - End Sub -End Module", cancellationToken: HangMitigatingCancellationToken); + End Sub + End Module + """, cancellationToken: HangMitigatingCancellationToken); } [IdeFact] public async Task VerifyCaseCorrection() { - await SetUpEditorAsync(@" -$$module A -end module", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + $$module A + end module + """, HangMitigatingCancellationToken); await TestServices.Editor.FormatDocumentAsync(HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -Module A -End Module", cancellationToken: HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextContainsAsync(""" + + Module A + End Module + """, cancellationToken: HangMitigatingCancellationToken); } [IdeFact] public async Task ShiftEnterWithIntelliSenseAndBraceMatching() { - await SetUpEditorAsync(@" -Module Program - Function Main(ooo As Object) As Object - Return Main$$ - End Function -End Module", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Module Program + Function Main(ooo As Object) As Object + Return Main$$ + End Function + End Module + """, HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.Workspace, HangMitigatingCancellationToken); await TestServices.Input.SendAsync(["(o", (VirtualKeyCode.RETURN, VirtualKeyCode.SHIFT), "'comment"], HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -Module Program - Function Main(ooo As Object) As Object - Return Main(ooo) - 'comment - End Function -End Module", cancellationToken: HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextContainsAsync(""" + + Module Program + Function Main(ooo As Object) As Object + Return Main(ooo) + 'comment + End Function + End Module + """, cancellationToken: HangMitigatingCancellationToken); } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicGenerateConstructorDialog.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicGenerateConstructorDialog.cs index 08ccf502eb8e5..5ffc6ee7507d5 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicGenerateConstructorDialog.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicGenerateConstructorDialog.cs @@ -27,14 +27,16 @@ public BasicGenerateConstructorDialog() [IdeFact] public async Task VerifyCodeRefactoringOfferedAndCanceled() { - await SetUpEditorAsync(@" -Class C - Dim i as Integer - Dim j as String - Dim k as Boolean + await SetUpEditorAsync(""" -$$ -End Class", HangMitigatingCancellationToken); + Class C + Dim i as Integer + Dim j as String + Dim k as Boolean + + $$ + End Class + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Generate constructor from members...", applyFix: true, blockUntilComplete: false, cancellationToken: HangMitigatingCancellationToken); @@ -42,28 +44,32 @@ Dim k as Boolean await TestServices.PickMembersDialog.ClickCancelAsync(HangMitigatingCancellationToken); var actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); Assert.Contains( -@" -Class C - Dim i as Integer - Dim j as String - Dim k as Boolean + """ + + Class C + Dim i as Integer + Dim j as String + Dim k as Boolean -End Class", actualText); + End Class + """, actualText); } [IdeFact] public async Task VerifyCodeRefactoringOfferedAndAccepted() { await SetUpEditorAsync( -@" -Class C - Dim i as Integer - Dim j as String - Dim k as Boolean + """ + + Class C + Dim i as Integer + Dim j as String + Dim k as Boolean -$$ -End Class", HangMitigatingCancellationToken); + $$ + End Class + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Generate constructor from members...", applyFix: true, blockUntilComplete: false, cancellationToken: HangMitigatingCancellationToken); @@ -72,32 +78,36 @@ Dim k as Boolean await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.LightBulb, HangMitigatingCancellationToken); var actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); Assert.Contains( -@" -Class C - Dim i as Integer - Dim j as String - Dim k as Boolean - - Public Sub New(i As Integer, j As String, k As Boolean) - Me.i = i - Me.j = j - Me.k = k - End Sub -End Class", actualText); + """ + + Class C + Dim i as Integer + Dim j as String + Dim k as Boolean + + Public Sub New(i As Integer, j As String, k As Boolean) + Me.i = i + Me.j = j + Me.k = k + End Sub + End Class + """, actualText); } [IdeFact] public async Task VerifyReordering() { await SetUpEditorAsync( -@" -Class C - Dim i as Integer - Dim j as String - Dim k as Boolean + """ -$$ -End Class", HangMitigatingCancellationToken); + Class C + Dim i as Integer + Dim j as String + Dim k as Boolean + + $$ + End Class + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Generate constructor from members...", applyFix: true, blockUntilComplete: false, cancellationToken: HangMitigatingCancellationToken); @@ -109,32 +119,36 @@ Dim k as Boolean await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.LightBulb, HangMitigatingCancellationToken); var actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); Assert.Contains( -@" -Class C - Dim i as Integer - Dim j as String - Dim k as Boolean - - Public Sub New(j As String, i As Integer, k As Boolean) - Me.j = j - Me.i = i - Me.k = k - End Sub -End Class", actualText); + """ + + Class C + Dim i as Integer + Dim j as String + Dim k as Boolean + + Public Sub New(j As String, i As Integer, k As Boolean) + Me.j = j + Me.i = i + Me.k = k + End Sub + End Class + """, actualText); } [IdeFact] public async Task VerifyDeselect() { await SetUpEditorAsync( -@" -Class C - Dim i as Integer - Dim j as String - Dim k as Boolean + """ + + Class C + Dim i as Integer + Dim j as String + Dim k as Boolean -$$ -End Class", HangMitigatingCancellationToken); + $$ + End Class + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Generate constructor from members...", applyFix: true, blockUntilComplete: false, cancellationToken: HangMitigatingCancellationToken); @@ -146,16 +160,18 @@ Dim k as Boolean await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.LightBulb, HangMitigatingCancellationToken); var actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); Assert.Contains( -@" -Class C - Dim i as Integer - Dim j as String - Dim k as Boolean - - Public Sub New(j As String, k As Boolean) - Me.j = j - Me.k = k - End Sub -End Class", actualText); + """ + + Class C + Dim i as Integer + Dim j as String + Dim k as Boolean + + Public Sub New(j As String, k As Boolean) + Me.j = j + Me.k = k + End Sub + End Class + """, actualText); } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicGenerateEqualsAndGetHashCodeDialog.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicGenerateEqualsAndGetHashCodeDialog.cs index 8327da5c56f73..daaf8b3ca5e37 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicGenerateEqualsAndGetHashCodeDialog.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicGenerateEqualsAndGetHashCodeDialog.cs @@ -24,66 +24,72 @@ public BasicGenerateEqualsAndGetHashCodeDialog() [IdeFact] public async Task VerifyCodeRefactoringOfferedAndCanceled() { - await SetUpEditorAsync(@" -Class C - Dim i as Integer - Dim j as String - Dim k as Boolean + await SetUpEditorAsync(""" -$$ -End Class", HangMitigatingCancellationToken); + Class C + Dim i as Integer + Dim j as String + Dim k as Boolean + + $$ + End Class + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Generate Equals(object)...", applyFix: true, blockUntilComplete: false, cancellationToken: HangMitigatingCancellationToken); await TestServices.PickMembersDialog.VerifyOpenAsync(HangMitigatingCancellationToken); await TestServices.PickMembersDialog.ClickCancelAsync(HangMitigatingCancellationToken); var actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); - var expectedText = @" -Class C - Dim i as Integer - Dim j as String - Dim k as Boolean + Assert.Contains(""" + + Class C + Dim i as Integer + Dim j as String + Dim k as Boolean -End Class"; - Assert.Contains(expectedText, actualText); + End Class + """, actualText); } [IdeFact] public async Task VerifyCodeRefactoringOfferedAndAccepted() { - await SetUpEditorAsync(@" -Imports TestProj + await SetUpEditorAsync(""" + + Imports TestProj -Class C - Dim i as Integer - Dim j as String - Dim k as Boolean + Class C + Dim i as Integer + Dim j as String + Dim k as Boolean -$$ -End Class", HangMitigatingCancellationToken); + $$ + End Class + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeCodeActionListAsync(HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Generate Equals(object)...", applyFix: true, blockUntilComplete: false, cancellationToken: HangMitigatingCancellationToken); await TestServices.PickMembersDialog.VerifyOpenAsync(HangMitigatingCancellationToken); await TestServices.PickMembersDialog.ClickOKAsync(HangMitigatingCancellationToken); var actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); - var expectedText = @" -Imports TestProj - -Class C - Dim i as Integer - Dim j as String - Dim k as Boolean - - Public Overrides Function Equals(obj As Object) As Boolean - Dim c = TryCast(obj, C) - Return c IsNot Nothing AndAlso - i = c.i AndAlso - j = c.j AndAlso - k = c.k - End Function -End Class"; - Assert.Contains(expectedText, actualText); + Assert.Contains(""" + + Imports TestProj + + Class C + Dim i as Integer + Dim j as String + Dim k as Boolean + + Public Overrides Function Equals(obj As Object) As Boolean + Dim c = TryCast(obj, C) + Return c IsNot Nothing AndAlso + i = c.i AndAlso + j = c.j AndAlso + k = c.k + End Function + End Class + """, actualText); } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicGenerateFromUsage.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicGenerateFromUsage.cs index 10d8c0f9baa11..790052481ab17 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicGenerateFromUsage.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicGenerateFromUsage.cs @@ -23,36 +23,44 @@ public BasicGenerateFromUsage() public async Task GenerateLocal() { await SetUpEditorAsync( -@"Module Program - Sub Main(args As String()) - Dim x As String = $$xyz - End Sub -End Module", HangMitigatingCancellationToken); + """ + Module Program + Sub Main(args As String()) + Dim x As String = $$xyz + End Sub + End Module + """, HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Generate local 'xyz'", applyFix: true, cancellationToken: HangMitigatingCancellationToken); await TestServices.EditorVerifier.TextContainsAsync( -@"Module Program - Sub Main(args As String()) - Dim xyz As String = Nothing - Dim x As String = xyz - End Sub -End Module", cancellationToken: HangMitigatingCancellationToken); + """ + Module Program + Sub Main(args As String()) + Dim xyz As String = Nothing + Dim x As String = xyz + End Sub + End Module + """, cancellationToken: HangMitigatingCancellationToken); } [IdeFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInNewFile() { await SetUpEditorAsync( -@"Module Program - Sub Main(args As String()) - Dim x As New $$ClassInNewFile() - End Sub -End Module", HangMitigatingCancellationToken); + """ + Module Program + Sub Main(args As String()) + Dim x As New $$ClassInNewFile() + End Sub + End Module + """, HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Generate class 'ClassInNewFile' in new file", applyFix: true, cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(ProjectName, "ClassInNewFile.vb", HangMitigatingCancellationToken); await TestServices.EditorVerifier.TextContainsAsync( -@"Friend Class ClassInNewFile - Public Sub New() - End Sub -End Class", cancellationToken: HangMitigatingCancellationToken); + """ + Friend Class ClassInNewFile + Public Sub New() + End Sub + End Class + """, cancellationToken: HangMitigatingCancellationToken); } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicGenerateTypeDialog.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicGenerateTypeDialog.cs index 88630a329c0d0..32f541479ed04 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicGenerateTypeDialog.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicGenerateTypeDialog.cs @@ -31,13 +31,15 @@ public async Task BasicToCSharp() var project = ProjectName; await TestServices.SolutionExplorer.OpenFileAsync(project, "Class1.vb", HangMitigatingCancellationToken); - await SetUpEditorAsync(@" -Class C - Sub Method() - $$Dim _A As A - End Sub -End Class -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + Sub Method() + $$Dim _A As A + End Sub + End Class + + """, HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Generate new type...", applyFix: true, blockUntilComplete: false, @@ -51,35 +53,41 @@ End Class await TestServices.GenerateTypeDialog.ClickOKAsync(HangMitigatingCancellationToken); await TestServices.GenerateTypeDialog.VerifyClosedAsync(HangMitigatingCancellationToken); var actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); - Assert.Contains(@"Imports CSProj + Assert.Contains(""" + Imports CSProj + + Class C + Sub Method() + Dim _A As A + End Sub + End Class -Class C - Sub Method() - Dim _A As A - End Sub -End Class -", actualText); + """, actualText); await TestServices.SolutionExplorer.OpenFileAsync(csProj, "GenerateTypeTest.cs", HangMitigatingCancellationToken); actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); - Assert.Contains(@"namespace CSProj -{ - public struct A - { - } -}", actualText); + Assert.Contains(""" + namespace CSProj + { + public struct A + { + } + } + """, actualText); } [IdeFact] public async Task SameProject() { - await SetUpEditorAsync(@" -Class C - Sub Method() - $$Dim _A As A - End Sub -End Class -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + Sub Method() + $$Dim _A As A + End Sub + End Class + + """, HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Generate new type...", applyFix: true, @@ -96,18 +104,22 @@ End Class await TestServices.SolutionExplorer.OpenFileAsync(project, "GenerateTypeTest.vb", HangMitigatingCancellationToken); var actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); - Assert.Contains(@"Public Structure A -End Structure -", actualText); + Assert.Contains(""" + Public Structure A + End Structure + + """, actualText); await TestServices.SolutionExplorer.OpenFileAsync(project, "Class1.vb", HangMitigatingCancellationToken); actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); - Assert.Contains(@"Class C - Sub Method() - Dim _A As A - End Sub -End Class -", actualText); + Assert.Contains(""" + Class C + Sub Method() + Dim _A As A + End Sub + End Class + + """, actualText); } [IdeFact] @@ -116,12 +128,14 @@ public async Task CheckFoldersPopulateComboBox() var project = ProjectName; await TestServices.SolutionExplorer.AddFileAsync(project, @"folder1\folder2\GenerateTypeTests.vb", open: true, cancellationToken: HangMitigatingCancellationToken); - await SetUpEditorAsync(@"Class C - Sub Method() - $$Dim _A As A - End Sub -End Class -", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + Class C + Sub Method() + $$Dim _A As A + End Sub + End Class + + """, HangMitigatingCancellationToken); await TestServices.EditorVerifier.CodeActionAsync("Generate new type...", applyFix: true, blockUntilComplete: false, diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicGoToDefinition.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicGoToDefinition.cs index b6adfd645e916..afe2ba347331d 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicGoToDefinition.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicGoToDefinition.cs @@ -32,14 +32,18 @@ public async Task GoToClassDeclaration() await TestServices.SolutionExplorer.AddFileAsync(project, "FileDef.vb", cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(project, "FileDef.vb", HangMitigatingCancellationToken); await TestServices.Editor.SetTextAsync( -@"Class SomeClass -End Class", HangMitigatingCancellationToken); + """ + Class SomeClass + End Class + """, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.AddFileAsync(project, "FileConsumer.vb", cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(project, "FileConsumer.vb", HangMitigatingCancellationToken); await TestServices.Editor.SetTextAsync( -@"Class SomeOtherClass - Dim gibberish As SomeClass -End Class", HangMitigatingCancellationToken); + """ + Class SomeOtherClass + Dim gibberish As SomeClass + End Class + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("SomeClass", charsOffset: 0, HangMitigatingCancellationToken); await TestServices.Editor.GoToDefinitionAsync(HangMitigatingCancellationToken); Assert.Equal($"FileDef.vb", await TestServices.Shell.GetActiveDocumentFileNameAsync(HangMitigatingCancellationToken)); @@ -92,11 +96,13 @@ public async Task GoToBaseFromMetadataAsSource() await TestServices.SolutionExplorer.AddFileAsync(project, "SomeClass.vb", cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(project, "SomeClass.vb", HangMitigatingCancellationToken); await TestServices.Editor.SetTextAsync( -@"Class SomeClass - Public Overrides Function ToString() As String - Return MyBase.ToString() - End Function -End Class", HangMitigatingCancellationToken); + """ + Class SomeClass + Public Overrides Function ToString() As String + Return MyBase.ToString() + End Function + End Class + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("Overrides", charsOffset: -1, HangMitigatingCancellationToken); await TestServices.Editor.GoToDefinitionAsync(HangMitigatingCancellationToken); Assert.Equal("Object [from metadata] [Read Only]", await TestServices.Shell.GetActiveWindowCaptionAsync(HangMitigatingCancellationToken)); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicGoToImplementation.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicGoToImplementation.cs index 02dcfce275963..e3929e617b2d1 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicGoToImplementation.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicGoToImplementation.cs @@ -35,14 +35,18 @@ public async Task SimpleGoToImplementation(bool asyncNavigation) await TestServices.SolutionExplorer.AddFileAsync(project, "FileImplementation.vb", cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(project, "FileImplementation.vb", HangMitigatingCancellationToken); await TestServices.Editor.SetTextAsync( -@"Class Implementation - Implements IGoo -End Class", HangMitigatingCancellationToken); + """ + Class Implementation + Implements IGoo + End Class + """, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.AddFileAsync(project, "FileInterface.vb", cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(project, "FileInterface.vb", HangMitigatingCancellationToken); await TestServices.Editor.SetTextAsync( -@"Interface IGoo -End Interface", HangMitigatingCancellationToken); + """ + Interface IGoo + End Interface + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("Interface IGoo", charsOffset: 0, HangMitigatingCancellationToken); await TestServices.Editor.GoToImplementationAsync(HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicImmediate.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicImmediate.cs index 3081cfb95799e..fcc715bf816af 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicImmediate.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicImmediate.cs @@ -32,14 +32,16 @@ public override async Task InitializeAsync() [IdeFact] public async Task DumpLocalVariableValue() { - await TestServices.Editor.SetTextAsync(@" -Module Module1 - Sub Main() - Dim n1Var As Integer = 42 - Dim n2Var As Integer = 43 - End Sub -End Module -", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + + Module Module1 + Sub Main() + Dim n1Var As Integer = 42 + Dim n2Var As Integer = 43 + End Sub + End Module + + """, HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.Workspace, HangMitigatingCancellationToken); await TestServices.Debugger.SetBreakpointAsync(ProjectName, "Module1.vb", "End Sub", HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicIntelliSense.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicIntelliSense.cs index fc96edbb79803..9f730b18d2d8f 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicIntelliSense.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicIntelliSense.cs @@ -42,24 +42,28 @@ public override async Task InitializeAsync() [IdeFact] public async Task IntelliSenseTriggersOnParenWithBraceCompletionAndCorrectUndoMerging() { - await SetUpEditorAsync(@" -Module Module1 - Sub Main() - $$ - End Sub -End Module", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Module Module1 + Sub Main() + $$ + End Sub + End Module + """, HangMitigatingCancellationToken); await TestServices.Editor.SetUseSuggestionModeAsync(false, HangMitigatingCancellationToken); await TestServices.Input.SendAsync("dim q as lis(", HangMitigatingCancellationToken); Assert.Contains("Of", (await TestServices.Editor.GetCompletionItemsAsync(HangMitigatingCancellationToken)).Select(completion => completion.DisplayText)); - await TestServices.EditorVerifier.TextContainsAsync(@" -Module Module1 - Sub Main() - Dim q As List($$) - End Sub -End Module", + await TestServices.EditorVerifier.TextContainsAsync(""" + + Module Module1 + Sub Main() + Dim q As List($$) + End Sub + End Module + """, assertCaretPosition: true, HangMitigatingCancellationToken); @@ -70,12 +74,14 @@ await TestServices.Input.SendAsync( ], HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -Module Module1 - Sub Main() - Dim q As List(Of$$) - End Sub -End Module", + await TestServices.EditorVerifier.TextContainsAsync(""" + + Module Module1 + Sub Main() + Dim q As List(Of$$) + End Sub + End Module + """, assertCaretPosition: true, HangMitigatingCancellationToken); @@ -84,78 +90,92 @@ End Sub await TestServices.Input.SendAsync(')', HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -Module Module1 - Sub Main() - Dim q As List(Of Integer)$$ - End Sub -End Module", + await TestServices.EditorVerifier.TextContainsAsync(""" + + Module Module1 + Sub Main() + Dim q As List(Of Integer)$$ + End Sub + End Module + """, assertCaretPosition: true, HangMitigatingCancellationToken); await TestServices.Input.SendAsync((VirtualKeyCode.VK_Z, VirtualKeyCode.CONTROL), HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -Module Module1 - Sub Main() - Dim q As List(Of inte)$$ - End Sub -End Module", + await TestServices.EditorVerifier.TextContainsAsync(""" + + Module Module1 + Sub Main() + Dim q As List(Of inte)$$ + End Sub + End Module + """, assertCaretPosition: true, HangMitigatingCancellationToken); await TestServices.Input.SendAsync((VirtualKeyCode.VK_Z, VirtualKeyCode.CONTROL), HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -Module Module1 - Sub Main() - Dim q As List(Of inte$$) - End Sub -End Module", + await TestServices.EditorVerifier.TextContainsAsync(""" + + Module Module1 + Sub Main() + Dim q As List(Of inte$$) + End Sub + End Module + """, assertCaretPosition: true, HangMitigatingCancellationToken); await TestServices.Input.SendAsync((VirtualKeyCode.VK_Z, VirtualKeyCode.CONTROL), HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -Module Module1 - Sub Main() - Dim q As List(Of$$) - End Sub -End Module", + await TestServices.EditorVerifier.TextContainsAsync(""" + + Module Module1 + Sub Main() + Dim q As List(Of$$) + End Sub + End Module + """, assertCaretPosition: true, HangMitigatingCancellationToken); await TestServices.Input.SendAsync((VirtualKeyCode.VK_Z, VirtualKeyCode.CONTROL), HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -Module Module1 - Sub Main() - Dim q As List($$) - End Sub -End Module", + await TestServices.EditorVerifier.TextContainsAsync(""" + + Module Module1 + Sub Main() + Dim q As List($$) + End Sub + End Module + """, assertCaretPosition: true, HangMitigatingCancellationToken); await TestServices.Input.SendAsync((VirtualKeyCode.VK_Z, VirtualKeyCode.CONTROL), HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -Module Module1 - Sub Main() - Dim q As lis($$) - End Sub -End Module", + await TestServices.EditorVerifier.TextContainsAsync(""" + + Module Module1 + Sub Main() + Dim q As lis($$) + End Sub + End Module + """, assertCaretPosition: true, HangMitigatingCancellationToken); await TestServices.Input.SendAsync((VirtualKeyCode.VK_Z, VirtualKeyCode.CONTROL), HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -Module Module1 - Sub Main() - Dim q As lis($$ - End Sub -End Module", + await TestServices.EditorVerifier.TextContainsAsync(""" + + Module Module1 + Sub Main() + Dim q As lis($$ + End Sub + End Module + """, assertCaretPosition: true, HangMitigatingCancellationToken); } @@ -163,12 +183,14 @@ End Sub [IdeFact] public async Task TypeAVariableDeclaration() { - await SetUpEditorAsync(@" -Module Module1 - Sub Main() - $$ - End Sub -End Module", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Module Module1 + Sub Main() + $$ + End Sub + End Module + """, HangMitigatingCancellationToken); await TestServices.Editor.SetUseSuggestionModeAsync(false, HangMitigatingCancellationToken); @@ -223,12 +245,14 @@ await TestServices.Input.SendAsync( [IdeFact] public async Task DismissIntelliSenseOnApostrophe() { - await SetUpEditorAsync(@" -Module Module1 - Sub Main() - $$ - End Sub -End Module", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Module Module1 + Sub Main() + $$ + End Sub + End Module + """, HangMitigatingCancellationToken); await TestServices.Editor.SetUseSuggestionModeAsync(false, HangMitigatingCancellationToken); @@ -238,18 +262,22 @@ End Sub await TestServices.Input.SendAsync("'", HangMitigatingCancellationToken); Assert.False(await TestServices.Editor.IsCompletionActiveAsync(HangMitigatingCancellationToken)); var actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); - Assert.Contains(@"Module Module1 - Sub Main() - Dim q As ' - End Sub -End Module", actualText); + Assert.Contains(""" + Module Module1 + Sub Main() + Dim q As ' + End Sub + End Module + """, actualText); } [IdeFact] public async Task TypeLeftAngleAfterImports() { - await SetUpEditorAsync(@" -Imports$$", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Imports$$ + """, HangMitigatingCancellationToken); await TestServices.Editor.SetUseSuggestionModeAsync(false, HangMitigatingCancellationToken); @@ -264,12 +292,14 @@ await SetUpEditorAsync(@" [IdeFact] public async Task DismissAndRetriggerIntelliSenseOnEquals() { - await SetUpEditorAsync(@" -Module Module1 - Function M(val As Integer) As Integer - $$ - End Function -End Module", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Module Module1 + Function M(val As Integer) As Integer + $$ + End Function + End Module + """, HangMitigatingCancellationToken); await TestServices.Editor.SetUseSuggestionModeAsync(false, HangMitigatingCancellationToken); @@ -280,12 +310,14 @@ End Function Assert.Contains("val", (await TestServices.Editor.GetCompletionItemsAsync(HangMitigatingCancellationToken)).Select(completion => completion.DisplayText)); await TestServices.Input.SendAsync(' ', HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" -Module Module1 - Function M(val As Integer) As Integer - M=val $$ - End Function -End Module", + await TestServices.EditorVerifier.TextContainsAsync(""" + + Module Module1 + Function M(val As Integer) As Integer + M=val $$ + End Function + End Module + """, assertCaretPosition: true, HangMitigatingCancellationToken); } @@ -325,15 +357,17 @@ public async Task CtrlAltSpaceOption() [IdeFact] public async Task EnterTriggerCompletionListAndImplementInterface() { - await SetUpEditorAsync(@" -Interface UFoo - Sub FooBar() -End Interface + await SetUpEditorAsync(""" -Public Class Bar - Implements$$ + Interface UFoo + Sub FooBar() + End Interface -End Class", HangMitigatingCancellationToken); + Public Class Bar + Implements$$ + + End Class + """, HangMitigatingCancellationToken); await TestServices.Editor.SetUseSuggestionModeAsync(false, HangMitigatingCancellationToken); @@ -343,17 +377,19 @@ Public Class Bar await TestServices.Input.SendAsync(VirtualKeyCode.RETURN, HangMitigatingCancellationToken); Assert.False(await TestServices.Editor.IsCompletionActiveAsync(HangMitigatingCancellationToken)); var actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); - Assert.Contains(@" -Interface UFoo - Sub FooBar() -End Interface - -Public Class Bar - Implements UFoo - - Public Sub FooBar() Implements UFoo.FooBar - Throw New NotImplementedException() - End Sub -End Class", actualText); + Assert.Contains(""" + + Interface UFoo + Sub FooBar() + End Interface + + Public Class Bar + Implements UFoo + + Public Sub FooBar() Implements UFoo.FooBar + Throw New NotImplementedException() + End Sub + End Class + """, actualText); } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicKeywordHighlighting.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicKeywordHighlighting.cs index be462d51416be..7e867fe36250d 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicKeywordHighlighting.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicKeywordHighlighting.cs @@ -28,14 +28,16 @@ public BasicKeywordHighlighting() [IdeFact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task NavigationBetweenKeywords() { - await TestServices.Editor.SetTextAsync(@" -Class C - Sub Main() - For a = 0 To 1 Step 1 - For b = 0 To 2 - Next b, a - End Sub -End Class", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + + Class C + Sub Main() + For a = 0 To 1 Step 1 + For b = 0 To 2 + Next b, a + End Sub + End Class + """, HangMitigatingCancellationToken); await VerifyAsync("To", 4, HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAsyncOperationsAsync(FeatureAttribute.ReferenceHighlighting, HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicLineCommit.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicLineCommit.cs index 7fafef8b13234..7c8889bbe3014 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicLineCommit.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicLineCommit.cs @@ -4,6 +4,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; @@ -29,11 +30,13 @@ public BasicLineCommit() [IdeFact] public async Task CaseCorrection() { - await TestServices.Editor.SetTextAsync(@"Module Goo - Sub M() -Dim x = Sub() - End Sub -End Module", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + Module Goo + Sub M() + Dim x = Sub() + End Sub + End Module + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("Sub()", charsOffset: 1, HangMitigatingCancellationToken); await TestServices.Input.SendAsync(VirtualKeyCode.RETURN, HangMitigatingCancellationToken); @@ -43,21 +46,25 @@ End Sub [IdeFact] public async Task UndoWithEndConstruct() { - await TestServices.Editor.SetTextAsync(@"Module Module1 - Sub Main() - End Sub - REM -End Module", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + Module Module1 + Sub Main() + End Sub + REM + End Module + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync(" REM", charsOffset: 0, HangMitigatingCancellationToken); await TestServices.Input.SendAsync(["sub", VirtualKeyCode.ESCAPE, " goo()", VirtualKeyCode.RETURN], HangMitigatingCancellationToken); - AssertEx.EqualOrDiff(@"Module Module1 - Sub Main() - End Sub - Sub goo() - - End Sub -End Module", await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); + AssertEx.EqualOrDiff(""" + Module Module1 + Sub Main() + End Sub + Sub goo() + + End Sub + End Module + """, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); await TestServices.Shell.ExecuteCommandAsync(WellKnownCommands.Edit.Undo, HangMitigatingCancellationToken); Assert.Equal(54, (await TestServices.Editor.GetCaretPositionAsync(HangMitigatingCancellationToken)).BufferPosition.Position); } @@ -65,22 +72,26 @@ End Sub [IdeFact] public async Task UndoWithoutEndConstruct() { - await TestServices.Editor.SetTextAsync(@"Module Module1 + await TestServices.Editor.SetTextAsync(""" + Module Module1 - ''' - Sub Main() - End Sub -End Module", HangMitigatingCancellationToken); + ''' + Sub Main() + End Sub + End Module + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("Module1", charsOffset: 0, HangMitigatingCancellationToken); await TestServices.Input.SendAsync([VirtualKeyCode.DOWN, VirtualKeyCode.RETURN], HangMitigatingCancellationToken); - AssertEx.EqualOrDiff(@"Module Module1 + AssertEx.EqualOrDiff(""" + Module Module1 - ''' - Sub Main() - End Sub -End Module", await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); + ''' + Sub Main() + End Sub + End Module + """, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); Assert.Equal(18, (await TestServices.Editor.GetCaretPositionAsync(HangMitigatingCancellationToken)).BufferPosition.Position); await TestServices.Shell.ExecuteCommandAsync(WellKnownCommands.Edit.Undo, HangMitigatingCancellationToken); Assert.Equal(16, (await TestServices.Editor.GetCaretPositionAsync(HangMitigatingCancellationToken)).BufferPosition.Position); @@ -89,11 +100,13 @@ End Sub [IdeFact] public async Task CommitOnSave() { - await TestServices.Editor.SetTextAsync(@"Module Module1 - Sub Main() - End Sub -End Module -", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + Module Module1 + Sub Main() + End Sub + End Module + + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("(", charsOffset: 1, HangMitigatingCancellationToken); await TestServices.Input.SendAsync(["x As integer", VirtualKeyCode.TAB], HangMitigatingCancellationToken); @@ -106,38 +119,46 @@ End Module await TestServices.SolutionExplorerVerifier.ActiveDocumentIsSavedAsync(HangMitigatingCancellationToken); Assert.True(await TestServices.Editor.IsSavedAsync(HangMitigatingCancellationToken)); - AssertEx.EqualOrDiff(@"Module Module1 - Sub Main(x As Integer) - End Sub -End Module -", await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); + AssertEx.EqualOrDiff(""" + Module Module1 + Sub Main(x As Integer) + End Sub + End Module + + """, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); await TestServices.Shell.ExecuteCommandAsync(WellKnownCommands.Edit.Undo, HangMitigatingCancellationToken); - AssertEx.EqualOrDiff(@"Module Module1 - Sub Main(x As Integer) - End Sub -End Module -", await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); + AssertEx.EqualOrDiff(""" + Module Module1 + Sub Main(x As Integer) + End Sub + End Module + + """, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); Assert.Equal(45, (await TestServices.Editor.GetCaretPositionAsync(HangMitigatingCancellationToken)).BufferPosition.Position); } [IdeFact] public async Task CommitOnFocusLost() { - await TestServices.Editor.SetTextAsync(@"Module M - Sub M() - End Sub -End Module", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + Module M + Sub M() + End Sub + End Module + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("End Sub", charsOffset: -1, HangMitigatingCancellationToken); await TestServices.Input.SendAsync(" ", HangMitigatingCancellationToken); await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "TestZ.vb", open: true, cancellationToken: HangMitigatingCancellationToken); // Cause focus lost await TestServices.Input.SendAsync(" ", HangMitigatingCancellationToken); await TestServices.SolutionExplorer.CloseCodeFileAsync(ProjectName, "TestZ.vb", saveFile: false, cancellationToken: HangMitigatingCancellationToken); - AssertEx.EqualOrDiff(@"Module M - Sub M() - End Sub -End Module", await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); + AssertEx.EqualOrDiff(""" + Module M + Sub M() + End Sub + End Module + """, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); } [IdeFact] @@ -146,19 +167,23 @@ public async Task CommitOnFocusLostDoesNotFormatWithPrettyListingOff() var globalOptions = await TestServices.Shell.GetComponentModelServiceAsync(HangMitigatingCancellationToken); globalOptions.SetGlobalOption(LineCommitOptionsStorage.PrettyListing, LanguageNames.VisualBasic, false); - await TestServices.Editor.SetTextAsync(@"Module M - Sub M() - End Sub -End Module", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + Module M + Sub M() + End Sub + End Module + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("End Sub", charsOffset: -1, HangMitigatingCancellationToken); await TestServices.Input.SendAsync(" ", HangMitigatingCancellationToken); await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "TestZ.vb", open: true, cancellationToken: HangMitigatingCancellationToken); // Cause focus lost await TestServices.Input.SendAsync(" ", HangMitigatingCancellationToken); await TestServices.SolutionExplorer.CloseCodeFileAsync(ProjectName, "TestZ.vb", saveFile: false, HangMitigatingCancellationToken); - AssertEx.EqualOrDiff(@"Module M - Sub M() - End Sub -End Module", await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); + AssertEx.EqualOrDiff(""" + Module M + Sub M() + End Sub + End Module + """, await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken)); } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicNavigateTo.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicNavigateTo.cs index e1db3de60d547..2b43b08e9fd95 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicNavigateTo.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicNavigateTo.cs @@ -27,14 +27,18 @@ public async Task NavigateTo() { var project = ProjectName; var csProject = "CSProject"; - await TestServices.SolutionExplorer.AddFileAsync(project, "test1.vb", open: false, contents: @" -Class FirstClass - Sub FirstMethod() - End Sub -End Class", cancellationToken: HangMitigatingCancellationToken); - - await TestServices.SolutionExplorer.AddFileAsync(project, "test2.vb", open: true, contents: @" -", cancellationToken: HangMitigatingCancellationToken); + await TestServices.SolutionExplorer.AddFileAsync(project, "test1.vb", open: false, contents: """ + + Class FirstClass + Sub FirstMethod() + End Sub + End Class + """, cancellationToken: HangMitigatingCancellationToken); + + await TestServices.SolutionExplorer.AddFileAsync(project, "test2.vb", open: true, contents: """ + + + """, cancellationToken: HangMitigatingCancellationToken); await TestServices.Shell.ShowNavigateToDialogAsync(HangMitigatingCancellationToken); await TestServices.Input.SendToNavigateToAsync(["FirstMethod", VirtualKeyCode.RETURN], HangMitigatingCancellationToken); await TestServices.Workarounds.WaitForNavigationAsync(HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicNavigationBar.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicNavigationBar.cs index 8a1547bdf6b23..be1159ae32124 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicNavigationBar.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicNavigationBar.cs @@ -18,17 +18,19 @@ namespace Roslyn.VisualStudio.NewIntegrationTests.VisualBasic; [Trait(Traits.Feature, Traits.Features.NavigationBar)] public class BasicNavigationBar : AbstractEditorTest { - private const string TestSource = @" -Class C - Public WithEvents Domain As AppDomain - Public Sub $$Goo() - End Sub -End Class - -Structure S - Public Property A As Integer - Public Property B As Integer -End Structure"; + private const string TestSource = """ + + Class C + Public WithEvents Domain As AppDomain + Public Sub $$Goo() + End Sub + End Class + + Structure S + Public Property A As Integer + Public Property B As Integer + End Structure + """; public BasicNavigationBar() : base(nameof(BasicNavigationBar)) @@ -92,10 +94,12 @@ public async Task CodeSpit() await TestServices.Editor.ExpandNavigationBarAsync(NavigationBarDropdownKind.Member, HangMitigatingCancellationToken); Assert.Equal(new[] { "New", "Finalize", "Goo" }, await TestServices.Editor.GetNavigationBarItemsAsync(NavigationBarDropdownKind.Member, HangMitigatingCancellationToken)); await TestServices.Editor.SelectNavigationBarItemAsync(NavigationBarDropdownKind.Member, "New", HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@" - Public Sub New() + await TestServices.EditorVerifier.TextContainsAsync(""" + + Public Sub New() - End Sub", cancellationToken: HangMitigatingCancellationToken); + End Sub + """, cancellationToken: HangMitigatingCancellationToken); await TestServices.EditorVerifier.CaretPositionAsync(78, HangMitigatingCancellationToken); // Caret is between New() and End Sub() in virtual whitespace await TestServices.EditorVerifier.CurrentLineTextAsync("$$", assertCaretPosition: true, HangMitigatingCancellationToken); } @@ -115,39 +119,41 @@ public async Task VerifyOption() [IdeFact] public async Task VerifyEvents() { - await SetUpEditorAsync(@" -$$Class Item1 - Public Event EvA As Action - Public Event EvB As Action -End Class - -Class Item2 - Public Event EvX As Action - Public Event EvY As Action -End Class - -Partial Class C - WithEvents item1 As Item1 - WithEvents item2 As Item2 -End Class - -Partial Class C - Private Sub item1_EvA() Handles item1.EvA - ' 1 - End Sub - - Private Sub item1_EvB() Handles item1.EvB - ' 2 - End Sub - - Private Sub item2_EvX() Handles item2.EvX - ' 3 - End Sub - - Private Sub item2_EvY() Handles item2.EvY - ' 4 - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + $$Class Item1 + Public Event EvA As Action + Public Event EvB As Action + End Class + + Class Item2 + Public Event EvX As Action + Public Event EvY As Action + End Class + + Partial Class C + WithEvents item1 As Item1 + WithEvents item2 As Item2 + End Class + + Partial Class C + Private Sub item1_EvA() Handles item1.EvA + ' 1 + End Sub + + Private Sub item1_EvB() Handles item1.EvB + ' 2 + End Sub + + Private Sub item2_EvX() Handles item2.EvX + ' 3 + End Sub + + Private Sub item2_EvY() Handles item2.EvY + ' 4 + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("' 1", charsOffset: 0, HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicOrganizing.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicOrganizing.cs index 017edf3ada4d8..426e0dd090d22 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicOrganizing.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicOrganizing.cs @@ -23,26 +23,30 @@ public BasicOrganizing() [IdeFact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task RemoveAndSort() { - await SetUpEditorAsync(@"Imports System.Linq$$ -Imports System -Imports System.Runtime.InteropServices -Imports System.Runtime.CompilerServices -Class Test - Sub Method( Optional str As String = Nothing) - Dim data As COMException - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + Imports System.Linq$$ + Imports System + Imports System.Runtime.InteropServices + Imports System.Runtime.CompilerServices + Class Test + Sub Method( Optional str As String = Nothing) + Dim data As COMException + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Shell.ExecuteCommandAsync(WellKnownCommands.Edit.RemoveAndSort, HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAsyncOperationsAsync( FeatureAttribute.OrganizeDocument, HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextContainsAsync(@"Imports System.Runtime.CompilerServices -Imports System.Runtime.InteropServices -Class Test - Sub Method( Optional str As String = Nothing) - Dim data As COMException - End Sub -End Class", cancellationToken: HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextContainsAsync(""" + Imports System.Runtime.CompilerServices + Imports System.Runtime.InteropServices + Class Test + Sub Method( Optional str As String = Nothing) + Dim data As COMException + End Sub + End Class + """, cancellationToken: HangMitigatingCancellationToken); } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicOutlining.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicOutlining.cs index 3cb18781fc3b9..35dfc8f8c432f 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicOutlining.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicOutlining.cs @@ -24,18 +24,19 @@ public BasicOutlining() [IdeFact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task Outlining() { - var input = @" -[|Imports System -Imports System.Text|] + MarkupTestFile.GetSpans(""" -[|Namespace Acme - [|Module Module1 - [|Sub Main() - - End Sub|] - End Module|] -End Namespace|]"; - MarkupTestFile.GetSpans(input, out var text, out var spans); + [|Imports System + Imports System.Text|] + + [|Namespace Acme + [|Module Module1 + [|Sub Main() + + End Sub|] + End Module|] + End Namespace|] + """, out var text, out var spans); await TestServices.Editor.SetTextAsync(text, HangMitigatingCancellationToken); var actualSpansWithState = await TestServices.Editor.GetOutliningSpansAsync(HangMitigatingCancellationToken); var actualSpans = actualSpansWithState.Select(span => span.Span); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicQuickInfo.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicQuickInfo.cs index c1e92615c48c6..b743c9e7a5c01 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicQuickInfo.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicQuickInfo.cs @@ -23,12 +23,14 @@ public BasicQuickInfo() [IdeFact] public async Task QuickInfo1() { - await SetUpEditorAsync(@" -''' Hello! -Class Program - Sub Main(ByVal args As String$$()) - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + ''' Hello! + Class Program + Sub Main(ByVal args As String$$()) + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeQuickInfoAsync(HangMitigatingCancellationToken); var quickInfo = await TestServices.Editor.GetQuickInfoAsync(HangMitigatingCancellationToken); Assert.Equal("Class System.String\r\nRepresents text as a sequence of UTF-16 code units.To browse the .NET Framework source code for this type, see the Reference Source.", quickInfo); @@ -37,18 +39,22 @@ End Sub [IdeFact] public async Task International() { - await SetUpEditorAsync(@" -''' -''' This is an XML doc comment defined in code. -''' -Class العربية123 - Shared Sub Goo() - Dim goo as العربية123$$ - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + ''' + ''' This is an XML doc comment defined in code. + ''' + Class العربية123 + Shared Sub Goo() + Dim goo as العربية123$$ + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeQuickInfoAsync(HangMitigatingCancellationToken); var quickInfo = await TestServices.Editor.GetQuickInfoAsync(HangMitigatingCancellationToken); - Assert.Equal(@"Class TestProj.العربية123 -This is an XML doc comment defined in code.", quickInfo); + Assert.Equal(""" + Class TestProj.العربية123 + This is an XML doc comment defined in code. + """, quickInfo); } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicReferenceHighlighting.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicReferenceHighlighting.cs index 6eb2fed555abd..3943a4071d6e1 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicReferenceHighlighting.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicReferenceHighlighting.cs @@ -33,15 +33,16 @@ public BasicReferenceHighlighting() [IdeFact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task Highlighting() { - var markup = @" -Class C - Dim {|definition:Goo|} as Int32 - Function M() - Console.WriteLine({|reference:Goo|}) - {|writtenReference:Goo|} = 4 - End Function -End Class"; - MarkupTestFile.GetSpans(markup, out var text, out IDictionary> spans); + MarkupTestFile.GetSpans(""" + + Class C + Dim {|definition:Goo|} as Int32 + Function M() + Console.WriteLine({|reference:Goo|}) + {|writtenReference:Goo|} = 4 + End Function + End Class + """, out var text, out IDictionary> spans); await TestServices.Editor.SetTextAsync(text, HangMitigatingCancellationToken); await VerifyAsync("Goo", spans, HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicRename.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicRename.cs index e4d81c41c40a4..e91d9c9f5ef34 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicRename.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicRename.cs @@ -37,21 +37,23 @@ public override async Task InitializeAsync() [IdeFact] public async Task VerifyLocalVariableRename() { - var markup = @" -Imports System -Imports System.Collections.Generic -Imports System.Linq - -Module Program - Sub Main(args As String()) - Dim [|x|]$$ As Integer = 0 - [|x|] = 5 - TestMethod([|x|]) - End Sub - Sub TestMethod(y As Integer) - - End Sub -End Module"; + var markup = """ + + Imports System + Imports System.Collections.Generic + Imports System.Linq + + Module Program + Sub Main(args As String()) + Dim [|x|]$$ As Integer = 0 + [|x|] = 5 + TestMethod([|x|]) + End Sub + Sub TestMethod(y As Integer) + + End Sub + End Module + """; await SetUpEditorAsync(markup, HangMitigatingCancellationToken); await TestServices.InlineRename.InvokeAsync(HangMitigatingCancellationToken); @@ -62,21 +64,23 @@ End Sub await TestServices.Input.SendWithoutActivateAsync([VirtualKeyCode.VK_Y, VirtualKeyCode.RETURN], HangMitigatingCancellationToken); await TestServices.Workspace.WaitForRenameAsync(HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextEqualsAsync(@" -Imports System -Imports System.Collections.Generic -Imports System.Linq - -Module Program - Sub Main(args As String()) - Dim y$$ As Integer = 0 - y = 5 - TestMethod(y) - End Sub - Sub TestMethod(y As Integer) - - End Sub -End Module", HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextEqualsAsync(""" + + Imports System + Imports System.Collections.Generic + Imports System.Linq + + Module Program + Sub Main(args As String()) + Dim y$$ As Integer = 0 + y = 5 + TestMethod(y) + End Sub + Sub TestMethod(y As Integer) + + End Sub + End Module + """, HangMitigatingCancellationToken); } [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/63576")] @@ -85,22 +89,24 @@ public async Task VerifyLocalVariableRenameWithCommentsUpdated() // "variable" is intentionally misspelled as "varixable" and "this" is misspelled as // "thix" below to ensure we don't change instances of "x" in comments that are part of // larger words - var markup = @" -Imports System -Imports System.Collections.Generic -Imports System.Linq - -Module Program - ''' - ''' creates a varixable named [|x|] xx - ''' - ''' - Sub Main(args As String()) - ' thix varixable is named [|x|] xx - Dim [|x|]$$ As Integer = 0 - [|x|] = 5 - TestMethod([|x|]) -End Module"; + var markup = """ + + Imports System + Imports System.Collections.Generic + Imports System.Linq + + Module Program + ''' + ''' creates a varixable named [|x|] xx + ''' + ''' + Sub Main(args As String()) + ' thix varixable is named [|x|] xx + Dim [|x|]$$ As Integer = 0 + [|x|] = 5 + TestMethod([|x|]) + End Module + """; await SetUpEditorAsync(markup, HangMitigatingCancellationToken); await TestServices.InlineRename.InvokeAsync(HangMitigatingCancellationToken); await TestServices.InlineRename.ToggleIncludeCommentsAsync(HangMitigatingCancellationToken); @@ -112,39 +118,43 @@ Sub Main(args As String()) await TestServices.Input.SendWithoutActivateAsync([VirtualKeyCode.VK_Y, VirtualKeyCode.RETURN], HangMitigatingCancellationToken); await TestServices.Workspace.WaitForRenameAsync(HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextEqualsAsync(@" -Imports System -Imports System.Collections.Generic -Imports System.Linq - -Module Program - ''' - ''' creates a varixable named y xx - ''' - ''' - Sub Main(args As String()) - ' thix varixable is named y xx - Dim y$$ As Integer = 0 - y = 5 - TestMethod(y) -End Module", HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextEqualsAsync(""" + + Imports System + Imports System.Collections.Generic + Imports System.Linq + + Module Program + ''' + ''' creates a varixable named y xx + ''' + ''' + Sub Main(args As String()) + ' thix varixable is named y xx + Dim y$$ As Integer = 0 + y = 5 + TestMethod(y) + End Module + """, HangMitigatingCancellationToken); } [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/63576")] public async Task VerifyLocalVariableRenameWithStringsUpdated() { - var markup = @" -Imports System -Imports System.Collections.Generic -Imports System.Linq - -Module Program - Sub Main(args As String()) - Dim [|x|]$$ As Integer = 0 - [|x|] = 5 - Dim s = ""[|x|] xx [|x|]"" - End Sub -End Module"; + var markup = """ + + Imports System + Imports System.Collections.Generic + Imports System.Linq + + Module Program + Sub Main(args As String()) + Dim [|x|]$$ As Integer = 0 + [|x|] = 5 + Dim s = "[|x|] xx [|x|]" + End Sub + End Module + """; await SetUpEditorAsync(markup, HangMitigatingCancellationToken); await TestServices.InlineRename.InvokeAsync(HangMitigatingCancellationToken); @@ -157,34 +167,38 @@ End Sub await TestServices.Input.SendWithoutActivateAsync([VirtualKeyCode.VK_Y, VirtualKeyCode.RETURN], HangMitigatingCancellationToken); await TestServices.Workspace.WaitForRenameAsync(HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextEqualsAsync(@" -Imports System -Imports System.Collections.Generic -Imports System.Linq - -Module Program - Sub Main(args As String()) - Dim y$$ As Integer = 0 - y = 5 - Dim s = ""y xx y"" - End Sub -End Module", HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextEqualsAsync(""" + + Imports System + Imports System.Collections.Generic + Imports System.Linq + + Module Program + Sub Main(args As String()) + Dim y$$ As Integer = 0 + y = 5 + Dim s = "y xx y" + End Sub + End Module + """, HangMitigatingCancellationToken); } [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/63576")] public async Task VerifyOverloadsUpdated() { - var markup = @" -Interface I - Sub [|TestMethod|]$$(y As Integer) - Sub [|TestMethod|](y As String) -End Interface - -Public MustInherit Class A - Implements I - Public MustOverride Sub [|TestMethod|](y As Integer) Implements I.[|TestMethod|] - Public MustOverride Sub [|TestMethod|](y As String) Implements I.[|TestMethod|] -End Class"; + var markup = """ + + Interface I + Sub [|TestMethod|]$$(y As Integer) + Sub [|TestMethod|](y As String) + End Interface + + Public MustInherit Class A + Implements I + Public MustOverride Sub [|TestMethod|](y As Integer) Implements I.[|TestMethod|] + Public MustOverride Sub [|TestMethod|](y As String) Implements I.[|TestMethod|] + End Class + """; await SetUpEditorAsync(markup, HangMitigatingCancellationToken); await TestServices.InlineRename.InvokeAsync(HangMitigatingCancellationToken); @@ -197,28 +211,32 @@ Implements I await TestServices.Input.SendWithoutActivateAsync([VirtualKeyCode.VK_Y, VirtualKeyCode.RETURN], HangMitigatingCancellationToken); await TestServices.Workspace.WaitForRenameAsync(HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextEqualsAsync(@" -Interface I - Sub y$$(y As Integer) - Sub y(y As String) -End Interface - -Public MustInherit Class A - Implements I - Public MustOverride Sub y(y As Integer) Implements I.y - Public MustOverride Sub y(y As String) Implements I.y -End Class", HangMitigatingCancellationToken); + await TestServices.EditorVerifier.TextEqualsAsync(""" + + Interface I + Sub y$$(y As Integer) + Sub y(y As String) + End Interface + + Public MustInherit Class A + Implements I + Public MustOverride Sub y(y As Integer) Implements I.y + Public MustOverride Sub y(y As String) Implements I.y + End Class + """, HangMitigatingCancellationToken); } [IdeFact, WorkItem("https://github.com/dotnet/roslyn/issues/21657")] public async Task VerifyAttributeRename() { - var markup = @" -Imports System + var markup = """ -Public Class [|$$ustom|]Attribute - Inherits Attribute -End Class"; + Imports System + + Public Class [|$$ustom|]Attribute + Inherits Attribute + End Class + """; await SetUpEditorAsync(markup, HangMitigatingCancellationToken); await TestServices.InlineRename.InvokeAsync(HangMitigatingCancellationToken); @@ -229,23 +247,27 @@ Inherits Attribute await TestServices.Input.SendWithoutActivateAsync(["Custom", VirtualKeyCode.RETURN], HangMitigatingCancellationToken); await TestServices.Workspace.WaitForRenameAsync(HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextEqualsAsync(@" -Imports System + await TestServices.EditorVerifier.TextEqualsAsync(""" + + Imports System -Public Class Custom$$Attribute - Inherits Attribute -End Class", HangMitigatingCancellationToken); + Public Class Custom$$Attribute + Inherits Attribute + End Class + """, HangMitigatingCancellationToken); } [IdeFact, WorkItem("https://github.com/dotnet/roslyn/issues/21657")] public async Task VerifyAttributeRenameWhileRenameClasss() { - var markup = @" -Imports System + var markup = """ -Public Class [|$$ustom|]Attribute - Inherits Attribute -End Class"; + Imports System + + Public Class [|$$ustom|]Attribute + Inherits Attribute + End Class + """; await SetUpEditorAsync(markup, HangMitigatingCancellationToken); await TestServices.InlineRename.InvokeAsync(HangMitigatingCancellationToken); @@ -257,27 +279,31 @@ Inherits Attribute await TestServices.Input.SendWithoutActivateAsync(["Custom", VirtualKeyCode.RETURN], HangMitigatingCancellationToken); await TestServices.Workspace.WaitForRenameAsync(HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextEqualsAsync(@" -Imports System + await TestServices.EditorVerifier.TextEqualsAsync(""" + + Imports System -Public Class Custom$$Attribute - Inherits Attribute -End Class", HangMitigatingCancellationToken); + Public Class Custom$$Attribute + Inherits Attribute + End Class + """, HangMitigatingCancellationToken); } [IdeFact, WorkItem("https://github.com/dotnet/roslyn/issues/21657")] public async Task VerifyAttributeRenameWhileRenameAttribute() { - var markup = @" -Imports System + var markup = """ -<[|$$ustom|]> -Class Bar -End Class + Imports System -Public Class [|ustom|]Attribute - Inherits Attribute -End Class"; + <[|$$ustom|]> + Class Bar + End Class + + Public Class [|ustom|]Attribute + Inherits Attribute + End Class + """; await SetUpEditorAsync(markup, HangMitigatingCancellationToken); await TestServices.InlineRename.InvokeAsync(HangMitigatingCancellationToken); @@ -288,31 +314,35 @@ Inherits Attribute await TestServices.Input.SendWithoutActivateAsync(["Custom", VirtualKeyCode.RETURN], HangMitigatingCancellationToken); await TestServices.Workspace.WaitForRenameAsync(HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextEqualsAsync(@" -Imports System + await TestServices.EditorVerifier.TextEqualsAsync(""" + + Imports System - -Class Bar -End Class + + Class Bar + End Class -Public Class CustomAttribute - Inherits Attribute -End Class", HangMitigatingCancellationToken); + Public Class CustomAttribute + Inherits Attribute + End Class + """, HangMitigatingCancellationToken); } [IdeFact, WorkItem("https://github.com/dotnet/roslyn/issues/21657")] public async Task VerifyAttributeRenameWhileRenameAttributeClass() { - var markup = @" -Imports System + var markup = """ + + Imports System -<[|ustom|]> -Class Bar -End Class + <[|ustom|]> + Class Bar + End Class -Public Class [|$$ustom|]Attribute - Inherits Attribute -End Class"; + Public Class [|$$ustom|]Attribute + Inherits Attribute + End Class + """; await SetUpEditorAsync(markup, HangMitigatingCancellationToken); await TestServices.InlineRename.InvokeAsync(HangMitigatingCancellationToken); @@ -323,27 +353,31 @@ Inherits Attribute await TestServices.Input.SendWithoutActivateAsync(["Custom", VirtualKeyCode.RETURN], HangMitigatingCancellationToken); await TestServices.Workspace.WaitForRenameAsync(HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextEqualsAsync(@" -Imports System + await TestServices.EditorVerifier.TextEqualsAsync(""" - -Class Bar -End Class + Imports System -Public Class Custom$$Attribute - Inherits Attribute -End Class", HangMitigatingCancellationToken); + + Class Bar + End Class + + Public Class Custom$$Attribute + Inherits Attribute + End Class + """, HangMitigatingCancellationToken); } [IdeFact, WorkItem("https://github.com/dotnet/roslyn/issues/21657")] public async Task VerifyAttributeCapitalizedRename() { - var markup = @" -Imports System + var markup = """ + + Imports System -Public Class [|$$ustom|]ATTRIBUTE - Inherits Attribute -End Class"; + Public Class [|$$ustom|]ATTRIBUTE + Inherits Attribute + End Class + """; await SetUpEditorAsync(markup, HangMitigatingCancellationToken); await TestServices.InlineRename.InvokeAsync(HangMitigatingCancellationToken); @@ -354,23 +388,27 @@ Inherits Attribute await TestServices.Input.SendWithoutActivateAsync(["Custom", VirtualKeyCode.RETURN], HangMitigatingCancellationToken); await TestServices.Workspace.WaitForRenameAsync(HangMitigatingCancellationToken); - await TestServices.EditorVerifier.TextEqualsAsync(@" -Imports System + await TestServices.EditorVerifier.TextEqualsAsync(""" -Public Class CustomAttribute$$ - Inherits Attribute -End Class", HangMitigatingCancellationToken); + Imports System + + Public Class CustomAttribute$$ + Inherits Attribute + End Class + """, HangMitigatingCancellationToken); } - [IdeFact, WorkItem("https://github.com/dotnet/roslyn/issues/21657")] + [IdeFact(Skip = "https://github.com/dotnet/roslyn/issues/79300"), WorkItem("https://github.com/dotnet/roslyn/issues/21657")] public async Task VerifyAttributeNotCapitalizedRename() { - var markup = @" -Imports System + var markup = """ -Public Class [|$$ustom|]attribute - Inherits Attribute -End Class"; + Imports System + + Public Class [|$$ustom|]attribute + Inherits Attribute + End Class + """; await SetUpEditorAsync(markup, HangMitigatingCancellationToken); await TestServices.InlineRename.InvokeAsync(HangMitigatingCancellationToken); @@ -384,22 +422,26 @@ Inherits Attribute try { // This is the expected behavior - await TestServices.EditorVerifier.TextEqualsAsync(@" -Imports System + await TestServices.EditorVerifier.TextEqualsAsync(""" + + Imports System -Public Class CustomAttribute$$ - Inherits Attribute -End Class", HangMitigatingCancellationToken); + Public Class CustomAttribute$$ + Inherits Attribute + End Class + """, HangMitigatingCancellationToken); } catch (XunitException) { // But sometimes we get this instead - await TestServices.EditorVerifier.TextEqualsAsync(@" -Imports System + await TestServices.EditorVerifier.TextEqualsAsync(""" + + Imports System -Public Class CustomA$$ttribute - Inherits Attribute -End Class", HangMitigatingCancellationToken); + Public Class CustomA$$ttribute + Inherits Attribute + End Class + """, HangMitigatingCancellationToken); } } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicSignatureHelp.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicSignatureHelp.cs index ca3653a4bfad5..eb96f39ef554e 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicSignatureHelp.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicSignatureHelp.cs @@ -17,54 +17,56 @@ public class BasicSignatureHelp : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; - private const string Baseline = @" -Class C - Sub M() - $$ - End Sub - - Function Method(i As Integer) As C - Return Nothing - End Function - - ''' - ''' Hello World 2.0! - ''' - ''' an integer, preferably 42. - ''' an integer, anything you like. - ''' returns an object of type C - Function Method(i As Integer, i2 As Integer) As C - Return Nothing - End Function - - - ''' - ''' Hello Generic World! - ''' - ''' Type Param 1 - ''' Param 1 of type T1 - ''' Null - Function GenericMethod(Of T1)(i As T1) As C - Return Nothing - End Function - - - Function GenericMethod(Of T1, T2)(i As T1, i2 As T2) As C - Return Nothing - End Function - - - ''' - ''' Complex Method Params - ''' - ''' Jagged MultiDimensional Array - ''' Out Array - ''' Dynamic and Params param - ''' Null - Sub OutAndParam(ByRef strings As String()(,), ByRef outArr As String(), ParamArray d As Object) - End Sub -End Class -"; + private const string Baseline = """ + + Class C + Sub M() + $$ + End Sub + + Function Method(i As Integer) As C + Return Nothing + End Function + + ''' + ''' Hello World 2.0! + ''' + ''' an integer, preferably 42. + ''' an integer, anything you like. + ''' returns an object of type C + Function Method(i As Integer, i2 As Integer) As C + Return Nothing + End Function + + + ''' + ''' Hello Generic World! + ''' + ''' Type Param 1 + ''' Param 1 of type T1 + ''' Null + Function GenericMethod(Of T1)(i As T1) As C + Return Nothing + End Function + + + Function GenericMethod(Of T1, T2)(i As T1, i2 As T2) As C + Return Nothing + End Function + + + ''' + ''' Complex Method Params + ''' + ''' Jagged MultiDimensional Array + ''' Out Array + ''' Dynamic and Params param + ''' Null + Sub OutAndParam(ByRef strings As String()(,), ByRef outArr As String(), ParamArray d As Object) + End Sub + End Class + + """; public BasicSignatureHelp() : base(nameof(BasicSignatureHelp)) @@ -127,34 +129,36 @@ public async Task GenericMethodSignatureHelp1() [IdeFact] public async Task GenericMethodSignatureHelp2() { - await SetUpEditorAsync(@" -Imports System -Class C(Of T, R) - Sub M() - $$ - End Sub - - ''' - ''' Generic Method with 1 Type Param - ''' - ''' Type Parameter - ''' param i of type T1 - Sub GenericMethod(Of T1)(i As T1) - End Sub - - - ''' - ''' Generic Method with 2 Type Params - ''' - ''' Type Parameter 1 - ''' Type Parameter 2 - ''' param i of type T1 - ''' param i2 of type T2 - ''' Null - Function GenericMethod(Of T1, T2)(i As T1, i2 As T2) As C(Of T, R) - Return Nothing - End Function -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Imports System + Class C(Of T, R) + Sub M() + $$ + End Sub + + ''' + ''' Generic Method with 1 Type Param + ''' + ''' Type Parameter + ''' param i of type T1 + Sub GenericMethod(Of T1)(i As T1) + End Sub + + + ''' + ''' Generic Method with 2 Type Params + ''' + ''' Type Parameter 1 + ''' Type Parameter 2 + ''' param i of type T1 + ''' param i2 of type T2 + ''' Null + Function GenericMethod(Of T1, T2)(i As T1, i2 As T2) As C(Of T, R) + Return Nothing + End Function + End Class + """, HangMitigatingCancellationToken); await TestServices.Input.SendAsync("GenericMethod", HangMitigatingCancellationToken); await TestServices.Input.SendAsync(VirtualKeyCode.ESCAPE, HangMitigatingCancellationToken); @@ -178,21 +182,23 @@ End Function [IdeFact] public async Task GenericMethodSignatureHelp_InvokeSighelp() { - await SetUpEditorAsync(@" -Imports System -Class C - Sub M() - GenericMethod(Of String, $$Integer)(Nothing, 1) - End Sub - - Function GenericMethod(Of T1)(i As T1) As C - Return Nothing - End Function - - Function GenericMethod(Of T1, T2)(i As T1, i2 As T2) As C - Return Nothing - End Function -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Imports System + Class C + Sub M() + GenericMethod(Of String, $$Integer)(Nothing, 1) + End Sub + + Function GenericMethod(Of T1)(i As T1) As C + Return Nothing + End Function + + Function GenericMethod(Of T1, T2)(i As T1, i2 As T2) As C + Return Nothing + End Function + End Class + """, HangMitigatingCancellationToken); await TestServices.Editor.InvokeSignatureHelpAsync(HangMitigatingCancellationToken); var signature = await TestServices.Editor.GetCurrentSignatureAsync(HangMitigatingCancellationToken); @@ -220,12 +226,14 @@ End Function [IdeFact] public async Task VerifyActiveParameterChanges() { - await SetUpEditorAsync(@" -Module M - Sub Method(a As Integer, b As Integer) - $$ - End Sub -End Module", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Module M + Sub Method(a As Integer, b As Integer) + $$ + End Sub + End Module + """, HangMitigatingCancellationToken); await TestServices.Input.SendAsync("Method(", HangMitigatingCancellationToken); var signature = await TestServices.Editor.GetCurrentSignatureAsync(HangMitigatingCancellationToken); @@ -242,22 +250,26 @@ End Sub [IdeFact] public async Task HandleBufferTextChangesDuringComputation() { - await SetUpEditorAsync(@" -Class C - Sub Goo() - End Sub - Sub Test() - $$ - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + + Class C + Sub Goo() + End Sub + Sub Test() + $$ + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Input.SendAsync("Goo(", HangMitigatingCancellationToken); var signature = await TestServices.Editor.GetCurrentSignatureAsync(HangMitigatingCancellationToken); Assert.Equal("C.Goo()", signature.Content); - await TestServices.Editor.SetTextAsync(@" -Class C - 'Marker", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + + Class C + 'Marker + """, HangMitigatingCancellationToken); Assert.False(await TestServices.Editor.IsSignatureHelpActiveAsync(HangMitigatingCancellationToken)); } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicWinForms.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicWinForms.cs index 665b166ab1896..e3c890f4f3b7b 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicWinForms.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/VisualBasic/BasicWinForms.cs @@ -29,11 +29,13 @@ public async Task TestMyIntelliSense() { var project = ProjectName; await TestServices.SolutionExplorer.OpenFileAsync(project, "Form1.vb", HangMitigatingCancellationToken); - await SetUpEditorAsync(@"Public Class Form1 - Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load - $$ - End Sub -End Class", HangMitigatingCancellationToken); + await SetUpEditorAsync(""" + Public Class Form1 + Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load + $$ + End Sub + End Class + """, HangMitigatingCancellationToken); await TestServices.Input.SendAsync("My.", HangMitigatingCancellationToken); var completionItems = (await TestServices.Editor.GetCompletionItemsAsync(HangMitigatingCancellationToken)).SelectAsArray(item => item.DisplayText); @@ -67,7 +69,9 @@ public async Task AddControl() await TestServices.SolutionExplorer.CloseDesignerFileAsync(project, "Form1.vb", saveFile: true, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(project, "Form1.Designer.vb", HangMitigatingCancellationToken); var actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); - Assert.Contains(@"Me.SomeButton.Name = ""SomeButton""", actualText); + Assert.Contains(""" + Me.SomeButton.Name = "SomeButton" + """, actualText); Assert.Contains(@"Friend WithEvents SomeButton As Button", actualText); } @@ -83,7 +87,9 @@ public async Task ChangeControlProperty() await TestServices.SolutionExplorer.CloseDesignerFileAsync(project, "Form1.vb", saveFile: true, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.OpenFileAsync(project, "Form1.Designer.vb", HangMitigatingCancellationToken); var actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); - Assert.Contains(@"Me.SomeButton.Text = ""NewButtonText""", actualText); + Assert.Contains(""" + Me.SomeButton.Text = "NewButtonText" + """, actualText); } [IdeFact] @@ -103,10 +109,16 @@ public async Task ChangeControlPropertyInCode() await TestServices.SolutionExplorer.OpenFileAsync(project, "Form1.Designer.vb", HangMitigatingCancellationToken); // Verify that the control's property was set correctly. The following text should appear in InitializeComponent(). var actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); - Assert.Contains(@"Me.SomeButton.Text = ""ButtonTextGoesHere""", actualText); + Assert.Contains(""" + Me.SomeButton.Text = "ButtonTextGoesHere" + """, actualText); // Replace text property with something else - await TestServices.Editor.SelectTextInCurrentDocumentAsync(@"Me.SomeButton.Text = ""ButtonTextGoesHere""", HangMitigatingCancellationToken); - await TestServices.Input.SendAsync(@"Me.SomeButton.Text = ""GibberishText""", HangMitigatingCancellationToken); + await TestServices.Editor.SelectTextInCurrentDocumentAsync(""" + Me.SomeButton.Text = "ButtonTextGoesHere" + """, HangMitigatingCancellationToken); + await TestServices.Input.SendAsync(""" + Me.SomeButton.Text = "GibberishText" + """, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.CloseCodeFileAsync(project, "Form1.Designer.vb", saveFile: true, HangMitigatingCancellationToken); // Verify that the control text has changed in the designer await TestServices.SolutionExplorer.OpenFileWithDesignerAsync(project, "Form1.vb", HangMitigatingCancellationToken); @@ -159,8 +171,12 @@ await TestServices.Workspace.WaitForAllAsyncOperationsAsync( // Verify that the rename propagated in designer code await TestServices.SolutionExplorer.OpenFileAsync(project, "Form1.Designer.vb", HangMitigatingCancellationToken); var formDesignerActualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); - Assert.Contains(@"Me.SomeNewButton.Name = ""SomeNewButton""", formDesignerActualText); - Assert.Contains(@"Me.SomeNewButton.Text = ""ButtonTextValue""", formDesignerActualText); + Assert.Contains(""" + Me.SomeNewButton.Name = "SomeNewButton" + """, formDesignerActualText); + Assert.Contains(""" + Me.SomeNewButton.Text = "ButtonTextValue" + """, formDesignerActualText); Assert.Contains(@"Friend WithEvents SomeNewButton As Button", formDesignerActualText); // Verify that the old button name goes away var actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); @@ -262,7 +278,9 @@ await TestServices.Workspace.WaitForAllAsyncOperationsAsync( Assert.Empty(await TestServices.ErrorList.GetBuildErrorsAsync(HangMitigatingCancellationToken)); await TestServices.SolutionExplorer.OpenFileAsync(project, "Form1.Designer.vb", HangMitigatingCancellationToken); var actualText = await TestServices.Editor.GetTextAsync(HangMitigatingCancellationToken); - Assert.DoesNotContain(@"Me.SomeButton.Name = ""SomeButton""", actualText); + Assert.DoesNotContain(""" + Me.SomeButton.Name = "SomeButton" + """, actualText); Assert.DoesNotContain(@"Friend WithEvents SomeButton As Button", actualText); } } diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/Workspace/WorkspaceBase.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/Workspace/WorkspaceBase.cs index a58a5bf222fcf..aa4151c901905 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/Workspace/WorkspaceBase.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/Workspace/WorkspaceBase.cs @@ -49,18 +49,19 @@ public async Task OpenCSharpThenVBSolution() await TestServices.SolutionExplorer.CreateSolutionAsync(nameof(WorkspaceBase), HangMitigatingCancellationToken); await TestServices.SolutionExplorer.AddProjectAsync("TestProj", WellKnownProjectTemplates.ClassLibrary, languageName: LanguageNames.VisualBasic, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.RestoreNuGetPackagesAsync(HangMitigatingCancellationToken); - await TestServices.Editor.SetTextAsync(@"Imports System -Class Program - Private e As Exception -End Class", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + Imports System + Class Program + Private e As Exception + End Class + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("Exception", charsOffset: 0, HangMitigatingCancellationToken); await TestServices.EditorVerifier.CurrentTokenTypeAsync(tokenType: "class name", HangMitigatingCancellationToken); } public virtual async Task MetadataReference() { - var reference = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; - await TestServices.SolutionExplorer.AddMetadataReferenceAsync(reference, "TestProj", HangMitigatingCancellationToken); + await TestServices.SolutionExplorer.AddMetadataReferenceAsync("WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", "TestProj", HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAllAsyncOperationsAsync([FeatureAttribute.Workspace], HangMitigatingCancellationToken); await TestServices.Editor.SetTextAsync("class C { System.Windows.Point p; }", HangMitigatingCancellationToken); @@ -106,16 +107,18 @@ public async Task ProjectProperties() await TestServices.Workspace.SetFullSolutionAnalysisAsync(true, HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAllAsyncOperationsAsync([FeatureAttribute.Workspace], HangMitigatingCancellationToken); - await TestServices.Editor.SetTextAsync(@"Module Program - Sub Main() - Dim x = 42 - M(x) - End Sub - Sub M(p As Integer) - End Sub - Sub M(p As Object) - End Sub -End Module", HangMitigatingCancellationToken); + await TestServices.Editor.SetTextAsync(""" + Module Program + Sub Main() + Dim x = 42 + M(x) + End Sub + Sub M(p As Integer) + End Sub + Sub M(p As Object) + End Sub + End Module + """, HangMitigatingCancellationToken); await TestServices.Editor.PlaceCaretAsync("(x)", charsOffset: -1, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.SetProjectInferAsync(ProjectName, true, HangMitigatingCancellationToken); await TestServices.Editor.InvokeQuickInfoAsync(HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/New.IntegrationTests/Workspace/WorkspacesNetCore.cs b/src/VisualStudio/IntegrationTest/New.IntegrationTests/Workspace/WorkspacesNetCore.cs index a5ed33d83d2e0..ae3fe7a997172 100644 --- a/src/VisualStudio/IntegrationTest/New.IntegrationTests/Workspace/WorkspacesNetCore.cs +++ b/src/VisualStudio/IntegrationTest/New.IntegrationTests/Workspace/WorkspacesNetCore.cs @@ -27,11 +27,13 @@ public WorkspacesNetCore() public override async Task MetadataReference() { await TestServices.SolutionExplorer.CreateSolutionAsync(nameof(WorkspacesNetCore), HangMitigatingCancellationToken); - await TestServices.SolutionExplorer.AddCustomProjectAsync(ProjectName, ".csproj", @" - - net472 - -", HangMitigatingCancellationToken); + await TestServices.SolutionExplorer.AddCustomProjectAsync(ProjectName, ".csproj", """ + + + net472 + + + """, HangMitigatingCancellationToken); await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "Class1.cs", contents: string.Empty, open: true, cancellationToken: HangMitigatingCancellationToken); await TestServices.SolutionExplorer.RestoreNuGetPackagesAsync(HangMitigatingCancellationToken); await TestServices.Workspace.WaitForAllAsyncOperationsAsync([FeatureAttribute.Workspace], HangMitigatingCancellationToken); diff --git a/src/VisualStudio/IntegrationTest/TestSetup/Microsoft.VisualStudio.IntegrationTest.Setup.csproj b/src/VisualStudio/IntegrationTest/TestSetup/Microsoft.VisualStudio.IntegrationTest.Setup.csproj index 76dc705fa5b96..1b8bf8a3a0b39 100644 --- a/src/VisualStudio/IntegrationTest/TestSetup/Microsoft.VisualStudio.IntegrationTest.Setup.csproj +++ b/src/VisualStudio/IntegrationTest/TestSetup/Microsoft.VisualStudio.IntegrationTest.Setup.csproj @@ -13,6 +13,8 @@ true false true + true + diff --git a/src/VisualStudio/Setup.Dependencies/Roslyn.VisualStudio.Setup.Dependencies.csproj b/src/VisualStudio/Setup.Dependencies/Roslyn.VisualStudio.Setup.Dependencies.csproj index c6a5af7de2024..c01ae1ae71a30 100644 --- a/src/VisualStudio/Setup.Dependencies/Roslyn.VisualStudio.Setup.Dependencies.csproj +++ b/src/VisualStudio/Setup.Dependencies/Roslyn.VisualStudio.Setup.Dependencies.csproj @@ -15,6 +15,7 @@ false $(CommonExtensionInstallationRoot) Microsoft\VBCSharp\Dependencies + true false - - false diff --git a/src/VisualStudio/Setup/Roslyn.VisualStudio.Setup.csproj b/src/VisualStudio/Setup/Roslyn.VisualStudio.Setup.csproj index 756037d4dd28c..64c2f77a97596 100644 --- a/src/VisualStudio/Setup/Roslyn.VisualStudio.Setup.csproj +++ b/src/VisualStudio/Setup/Roslyn.VisualStudio.Setup.csproj @@ -15,6 +15,7 @@ $(CommonExtensionInstallationRoot) $(LanguageServicesExtensionInstallationFolder) true + true Microsoft.CodeAnalysis.LanguageServices diff --git a/src/VisualStudio/TestUtilities2/CallHierarchy/CallHierarchyTestState.vb b/src/VisualStudio/TestUtilities2/CallHierarchy/CallHierarchyTestState.vb index 9cef445672f68..d2cb3ee7d1e4d 100644 --- a/src/VisualStudio/TestUtilities2/CallHierarchy/CallHierarchyTestState.vb +++ b/src/VisualStudio/TestUtilities2/CallHierarchy/CallHierarchyTestState.vb @@ -3,6 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities diff --git a/src/VisualStudio/TestUtilities2/CodeModel/CodeModelTestHelpers.vb b/src/VisualStudio/TestUtilities2/CodeModel/CodeModelTestHelpers.vb index d386e87a059fb..626916dfee1c3 100644 --- a/src/VisualStudio/TestUtilities2/CodeModel/CodeModelTestHelpers.vb +++ b/src/VisualStudio/TestUtilities2/CodeModel/CodeModelTestHelpers.vb @@ -9,7 +9,6 @@ Imports EnvDTE Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel diff --git a/src/VisualStudio/TestUtilities2/CodeModel/CodeModelTestState.vb b/src/VisualStudio/TestUtilities2/CodeModel/CodeModelTestState.vb index 639e5cec355fd..3fdeefd6f7bbe 100644 --- a/src/VisualStudio/TestUtilities2/CodeModel/CodeModelTestState.vb +++ b/src/VisualStudio/TestUtilities2/CodeModel/CodeModelTestState.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.ErrorReporting Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel diff --git a/src/VisualStudio/TestUtilities2/CodeModel/Mocks/MockTextManagerAdapter.vb b/src/VisualStudio/TestUtilities2/CodeModel/Mocks/MockTextManagerAdapter.vb index 755071fbf0dc4..9a64255b96d5d 100644 --- a/src/VisualStudio/TestUtilities2/CodeModel/Mocks/MockTextManagerAdapter.vb +++ b/src/VisualStudio/TestUtilities2/CodeModel/Mocks/MockTextManagerAdapter.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel diff --git a/src/VisualStudio/TestUtilities2/CodeModel/Mocks/MockVisualStudioWorkspace.vb b/src/VisualStudio/TestUtilities2/CodeModel/Mocks/MockVisualStudioWorkspace.vb index f535cc16a6710..b5b5db66e8ee7 100644 --- a/src/VisualStudio/TestUtilities2/CodeModel/Mocks/MockVisualStudioWorkspace.vb +++ b/src/VisualStudio/TestUtilities2/CodeModel/Mocks/MockVisualStudioWorkspace.vb @@ -5,15 +5,11 @@ Imports System.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.FindSymbols Imports Microsoft.CodeAnalysis.Host -Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Composition -Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel -Imports Microsoft.VisualStudio.LanguageServices.Implementation.Interop Imports Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem diff --git a/src/VisualStudio/TestUtilities2/Microsoft.VisualStudio.LanguageServices.Test.Utilities2.vbproj b/src/VisualStudio/TestUtilities2/Microsoft.VisualStudio.LanguageServices.Test.Utilities2.vbproj index 10368afb757b8..80c7298015159 100644 --- a/src/VisualStudio/TestUtilities2/Microsoft.VisualStudio.LanguageServices.Test.Utilities2.vbproj +++ b/src/VisualStudio/TestUtilities2/Microsoft.VisualStudio.LanguageServices.Test.Utilities2.vbproj @@ -55,9 +55,6 @@ - - - diff --git a/src/VisualStudio/TestUtilities2/MockExtensionManager.vb b/src/VisualStudio/TestUtilities2/MockExtensionManager.vb index debf644c7f18b..ac3cf99968b2c 100644 --- a/src/VisualStudio/TestUtilities2/MockExtensionManager.vb +++ b/src/VisualStudio/TestUtilities2/MockExtensionManager.vb @@ -2,13 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Globalization Imports System.IO -Imports System.Xml -Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Moq -Imports Roslyn.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Diagnostics Public Class MockExtensionManager diff --git a/src/VisualStudio/TestUtilities2/MockServiceProvider.vb b/src/VisualStudio/TestUtilities2/MockServiceProvider.vb index a9db0ba131a4e..9584002c56ba2 100644 --- a/src/VisualStudio/TestUtilities2/MockServiceProvider.vb +++ b/src/VisualStudio/TestUtilities2/MockServiceProvider.vb @@ -55,6 +55,13 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests Case GetType(SVsFileChangeEx) Return _fileChangeEx + Case GetType(SVsRunningDocumentTable) + Dim mock = New Mock(Of IVsRunningDocumentTable) + mock.As(Of IVsRunningDocumentTable4)() + + mock.Setup(Function(m) m.AdviseRunningDocTableEvents(It.IsAny(Of IVsRunningDocTableEvents), It.IsAny(Of UInteger))).Returns(VSConstants.S_OK) + Return mock.Object + Case Else Throw New Exception($"{NameOf(MockServiceProvider)} does not implement {serviceType.FullName}.") End Select diff --git a/src/VisualStudio/TestUtilities2/ProjectSystemShim/Framework/MockHierarchy.vb b/src/VisualStudio/TestUtilities2/ProjectSystemShim/Framework/MockHierarchy.vb index d2d15aa98eec9..c0cee0006cba4 100644 --- a/src/VisualStudio/TestUtilities2/ProjectSystemShim/Framework/MockHierarchy.vb +++ b/src/VisualStudio/TestUtilities2/ProjectSystemShim/Framework/MockHierarchy.vb @@ -5,9 +5,7 @@ Imports Microsoft.VisualStudio.Shell.Interop Imports Microsoft.VisualStudio.OLE.Interop Imports System.Runtime.InteropServices -Imports Microsoft.VisualStudio.Shell Imports Roslyn.Utilities -Imports System.IO Imports Moq Imports Microsoft.VisualStudio.LanguageServices.ProjectSystem diff --git a/src/VisualStudio/TestUtilities2/ProjectSystemShim/Framework/TestEnvironment.vb b/src/VisualStudio/TestUtilities2/ProjectSystemShim/Framework/TestEnvironment.vb index af2c680a287ca..4b1bbf1f9a740 100644 --- a/src/VisualStudio/TestUtilities2/ProjectSystemShim/Framework/TestEnvironment.vb +++ b/src/VisualStudio/TestUtilities2/ProjectSystemShim/Framework/TestEnvironment.vb @@ -22,7 +22,7 @@ Imports Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBro Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.CPS Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy -Imports Microsoft.VisualStudio.LanguageServices.Implementation.TaskList +Imports Microsoft.VisualStudio.LanguageServices.Telemetry Imports Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Imports Microsoft.VisualStudio.LanguageServices.UnitTests.Diagnostics Imports Microsoft.VisualStudio.Shell.Interop @@ -66,7 +66,10 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Fr GetType(VisualStudioMetadataReferenceManager), GetType(MockWorkspaceEventListenerProvider), GetType(HierarchyItemToProjectIdMap), - GetType(DiagnosticAnalyzerService)) + GetType(DiagnosticAnalyzerService), + GetType(VisualStudioWorkspaceTelemetryService), + GetType(OpenTextBufferProvider), + GetType(StubVsEditorAdaptersFactoryService)) Private ReadOnly _workspace As VisualStudioWorkspaceImpl Private ReadOnly _projectFilePaths As New List(Of String) diff --git a/src/VisualStudio/TestUtilities2/StubVsServiceExporter`1.vb b/src/VisualStudio/TestUtilities2/StubVsServiceExporter`1.vb index f452db68ba4bf..71411a6d3b915 100644 --- a/src/VisualStudio/TestUtilities2/StubVsServiceExporter`1.vb +++ b/src/VisualStudio/TestUtilities2/StubVsServiceExporter`1.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System Imports System.ComponentModel.Composition Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.VisualStudio diff --git a/src/VisualStudio/TestUtilities2/VisualStudioTestCompositions.vb b/src/VisualStudio/TestUtilities2/VisualStudioTestCompositions.vb index 02f0ba17845c9..373374a5d3ba1 100644 --- a/src/VisualStudio/TestUtilities2/VisualStudioTestCompositions.vb +++ b/src/VisualStudio/TestUtilities2/VisualStudioTestCompositions.vb @@ -4,7 +4,6 @@ Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Editor.UnitTests -Imports Microsoft.CodeAnalysis.Notification Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.CSharp Imports Microsoft.VisualStudio.LanguageServices.Remote diff --git a/src/VisualStudio/VisualBasic/Impl/CodeModel/ModifierFlagsExtensions.vb b/src/VisualStudio/VisualBasic/Impl/CodeModel/ModifierFlagsExtensions.vb index a28eb4909d9f3..52255e5d172fe 100644 --- a/src/VisualStudio/VisualBasic/Impl/CodeModel/ModifierFlagsExtensions.vb +++ b/src/VisualStudio/VisualBasic/Impl/CodeModel/ModifierFlagsExtensions.vb @@ -6,7 +6,6 @@ Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Extensions -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel diff --git a/src/VisualStudio/VisualBasic/Impl/CodeModel/SyntaxExtensions.vb b/src/VisualStudio/VisualBasic/Impl/CodeModel/SyntaxExtensions.vb index 2f6a49592ccae..ccee02f4aa088 100644 --- a/src/VisualStudio/VisualBasic/Impl/CodeModel/SyntaxExtensions.vb +++ b/src/VisualStudio/VisualBasic/Impl/CodeModel/SyntaxExtensions.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices -Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/VisualStudio/VisualBasic/Impl/CodeModel/SyntaxListExtensions.vb b/src/VisualStudio/VisualBasic/Impl/CodeModel/SyntaxListExtensions.vb index 539322cd83fe0..5405abca4ff45 100644 --- a/src/VisualStudio/VisualBasic/Impl/CodeModel/SyntaxListExtensions.vb +++ b/src/VisualStudio/VisualBasic/Impl/CodeModel/SyntaxListExtensions.vb @@ -4,9 +4,6 @@ Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel Friend Module SyntaxListExtensions diff --git a/src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelService.NodeLocator.vb b/src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelService.NodeLocator.vb index 4e255ca47373b..28a9c7d1185d6 100644 --- a/src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelService.NodeLocator.vb +++ b/src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelService.NodeLocator.vb @@ -6,7 +6,6 @@ Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities Imports Microsoft.CodeAnalysis.Formatting -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Extensions diff --git a/src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelService.vb b/src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelService.vb index 4647c60471c8e..9a23ab0c79319 100644 --- a/src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelService.vb +++ b/src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelService.vb @@ -28,7 +28,6 @@ Imports Microsoft.VisualStudio.LanguageServices.Implementation.Utilities Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Extenders Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.MethodXml Imports Microsoft.VisualStudio.Text -Imports Microsoft.VisualStudio.Text.Editor Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel Partial Friend Class VisualBasicCodeModelService diff --git a/src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelServiceFactory.vb b/src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelServiceFactory.vb index 0976dc0c150a8..0cd6cbe18dba0 100644 --- a/src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelServiceFactory.vb +++ b/src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelServiceFactory.vb @@ -11,7 +11,6 @@ Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Options Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel -Imports Microsoft.VisualStudio.Text.Editor Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel diff --git a/src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelService_Prototype.vb b/src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelService_Prototype.vb index e9b8b50b9114e..0a00c00b18862 100644 --- a/src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelService_Prototype.vb +++ b/src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelService_Prototype.vb @@ -5,8 +5,6 @@ Imports System.Collections.Immutable Imports System.Text Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.Utilities diff --git a/src/VisualStudio/VisualBasic/Impl/LanguageService/VisualBasicCodeCleanupFixer.vb b/src/VisualStudio/VisualBasic/Impl/LanguageService/VisualBasicCodeCleanupFixer.vb index 68349b1b937ba..cb78083bdbe3c 100644 --- a/src/VisualStudio/VisualBasic/Impl/LanguageService/VisualBasicCodeCleanupFixer.vb +++ b/src/VisualStudio/VisualBasic/Impl/LanguageService/VisualBasicCodeCleanupFixer.vb @@ -7,7 +7,6 @@ Imports System.ComponentModel.Composition Imports Microsoft.CodeAnalysis.Editor Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Host.Mef -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeCleanup Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Imports Microsoft.VisualStudio.Shell diff --git a/src/VisualStudio/VisualBasic/Impl/LanguageService/VisualBasicLanguageService.vb b/src/VisualStudio/VisualBasic/Impl/LanguageService/VisualBasicLanguageService.vb index 84cc9edacb87b..2745f652bdfab 100644 --- a/src/VisualStudio/VisualBasic/Impl/LanguageService/VisualBasicLanguageService.vb +++ b/src/VisualStudio/VisualBasic/Impl/LanguageService/VisualBasicLanguageService.vb @@ -8,7 +8,6 @@ Imports Microsoft.CodeAnalysis.Editor Imports Microsoft.CodeAnalysis.Workspaces.ProjectSystem Imports Microsoft.VisualStudio.LanguageServices.Implementation.DebuggerIntelliSense Imports Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService -Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.Venus Imports Microsoft.VisualStudio.Shell.Interop Imports Microsoft.VisualStudio.Text diff --git a/src/VisualStudio/VisualBasic/Impl/LanguageService/VisualBasicPackage.IVbCompiler.vb b/src/VisualStudio/VisualBasic/Impl/LanguageService/VisualBasicPackage.IVbCompiler.vb index 951e9f3d5c927..effe9b67cd5cf 100644 --- a/src/VisualStudio/VisualBasic/Impl/LanguageService/VisualBasicPackage.IVbCompiler.vb +++ b/src/VisualStudio/VisualBasic/Impl/LanguageService/VisualBasicPackage.IVbCompiler.vb @@ -4,7 +4,6 @@ Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.VisualStudio.LanguageServices.Implementation.TaskList Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop Imports Microsoft.VisualStudio.Shell.Interop diff --git a/src/VisualStudio/VisualBasic/Impl/Options/AdvancedOptionPageControl.xaml.vb b/src/VisualStudio/VisualBasic/Impl/Options/AdvancedOptionPageControl.xaml.vb index 17d9b7b929749..fa7331bfb7cff 100644 --- a/src/VisualStudio/VisualBasic/Impl/Options/AdvancedOptionPageControl.xaml.vb +++ b/src/VisualStudio/VisualBasic/Impl/Options/AdvancedOptionPageControl.xaml.vb @@ -15,33 +15,26 @@ Imports Microsoft.CodeAnalysis.DocumentHighlighting Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking Imports Microsoft.CodeAnalysis.Editor.Implementation.SplitComment -Imports Microsoft.CodeAnalysis.Editor.Implementation.Suggestions Imports Microsoft.CodeAnalysis.Editor.InlineDiagnostics Imports Microsoft.CodeAnalysis.Editor.InlineHints -Imports Microsoft.CodeAnalysis.Editor.InlineRename Imports Microsoft.CodeAnalysis.Editor.Shared.Options -Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration Imports Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit -Imports Microsoft.CodeAnalysis.ExtractMethod Imports Microsoft.CodeAnalysis.Features.EmbeddedLanguages.RegularExpressions.LanguageServices Imports Microsoft.CodeAnalysis.Features.EmbeddedLanguages.Json.LanguageServices Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.ImplementType Imports Microsoft.CodeAnalysis.InheritanceMargin Imports Microsoft.CodeAnalysis.InlineHints -Imports Microsoft.CodeAnalysis.InlineRename Imports Microsoft.CodeAnalysis.KeywordHighlighting Imports Microsoft.CodeAnalysis.LineSeparators Imports Microsoft.CodeAnalysis.QuickInfo Imports Microsoft.CodeAnalysis.ReferenceHighlighting -Imports Microsoft.CodeAnalysis.Remote Imports Microsoft.CodeAnalysis.SolutionCrawler Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.SymbolSearch Imports Microsoft.CodeAnalysis.ValidateFormatString Imports Microsoft.CodeAnalysis.VisualBasic.AutomaticInsertionOfAbstractOrInterfaceMembers -Imports Microsoft.VisualStudio.LanguageServices.DocumentOutline Imports Microsoft.VisualStudio.LanguageServices.Implementation Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options diff --git a/src/VisualStudio/VisualBasic/Impl/Options/IntelliSenseOptionPage.vb b/src/VisualStudio/VisualBasic/Impl/Options/IntelliSenseOptionPage.vb index 8a8983780d8e4..0a760a499e8d6 100644 --- a/src/VisualStudio/VisualBasic/Impl/Options/IntelliSenseOptionPage.vb +++ b/src/VisualStudio/VisualBasic/Impl/Options/IntelliSenseOptionPage.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System Imports System.Runtime.InteropServices Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options diff --git a/src/VisualStudio/VisualBasic/Impl/Options/NamingStylesOptionPage.vb b/src/VisualStudio/VisualBasic/Impl/Options/NamingStylesOptionPage.vb index 67abb4df5daac..387c61bb93bad 100644 --- a/src/VisualStudio/VisualBasic/Impl/Options/NamingStylesOptionPage.vb +++ b/src/VisualStudio/VisualBasic/Impl/Options/NamingStylesOptionPage.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Runtime.InteropServices -Imports System.Windows Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Notification Imports Microsoft.VisualStudio.ComponentModelHost diff --git a/src/VisualStudio/VisualBasic/Impl/Options/StyleViewModel.vb b/src/VisualStudio/VisualBasic/Impl/Options/StyleViewModel.vb index 97aee74630bba..37fd7565f15b4 100644 --- a/src/VisualStudio/VisualBasic/Impl/Options/StyleViewModel.vb +++ b/src/VisualStudio/VisualBasic/Impl/Options/StyleViewModel.vb @@ -5,7 +5,6 @@ Imports System.Windows.Data Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeStyle -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.CodeStyle Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options diff --git a/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/Interop/IVbBuildStatusCallback.vb b/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/Interop/IVbBuildStatusCallback.vb index 618fcfb7ae65a..55f67449a8643 100644 --- a/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/Interop/IVbBuildStatusCallback.vb +++ b/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/Interop/IVbBuildStatusCallback.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Runtime.InteropServices -Imports Microsoft.VisualStudio.Shell.Interop Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop diff --git a/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/Interop/IVbCompilerHost.vb b/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/Interop/IVbCompilerHost.vb index 95cf4c3494629..08fc781947b64 100644 --- a/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/Interop/IVbCompilerHost.vb +++ b/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/Interop/IVbCompilerHost.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Runtime.InteropServices -Imports Microsoft.VisualStudio.Shell.Interop Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop diff --git a/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/Interop/IVbTempPECompilerFactory.vb b/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/Interop/IVbTempPECompilerFactory.vb index 826509549524f..aa571d1a00895 100644 --- a/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/Interop/IVbTempPECompilerFactory.vb +++ b/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/Interop/IVbTempPECompilerFactory.vb @@ -3,8 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Runtime.InteropServices -Imports System.Runtime.InteropServices.ComTypes -Imports Microsoft.VisualStudio.Shell.Interop Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop diff --git a/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/Interop/OutputLevel.vb b/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/Interop/OutputLevel.vb index 579e94cc0eef1..7dc8d3cf3a30e 100644 --- a/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/Interop/OutputLevel.vb +++ b/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/Interop/OutputLevel.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Runtime.InteropServices - Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop Friend Enum OutputLevel OUTPUT_Quiet diff --git a/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/TempPECompiler.vb b/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/TempPECompiler.vb index d3dba3a9f5d13..b0d92b1ba43fd 100644 --- a/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/TempPECompiler.vb +++ b/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/TempPECompiler.vb @@ -5,8 +5,6 @@ Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Host -Imports Microsoft.VisualStudio -Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop Imports Microsoft.VisualStudio.Shell.Interop diff --git a/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/VisualBasicEntryPointFinder.vb b/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/VisualBasicEntryPointFinder.vb index 902e3feaa8b19..4b570761d863c 100644 --- a/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/VisualBasicEntryPointFinder.vb +++ b/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/VisualBasicEntryPointFinder.vb @@ -28,12 +28,6 @@ Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim Dim visitor = New VisualBasicEntryPointFinder(compilation, findFormsOnly) Dim symbol = compilation.SourceModule.GlobalNamespace - ' Attempt to only search source symbols - ' Some callers will give a symbol that is not part of a compilation - If symbol.ContainingCompilation IsNot Nothing Then - symbol = symbol.ContainingCompilation.SourceModule.GlobalNamespace - End If - visitor.Visit(symbol) Return visitor.EntryPoints End Function diff --git a/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/VisualBasicEntryPointFinderService.vb b/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/VisualBasicEntryPointFinderService.vb index b2ddf22cc26a3..b21f14eb109fb 100644 --- a/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/VisualBasicEntryPointFinderService.vb +++ b/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/VisualBasicEntryPointFinderService.vb @@ -17,7 +17,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim Public Sub New() End Sub - Protected Overrides Function FindEntryPoints(compilation As Compilation, findFormsOnly As Boolean) As IEnumerable(Of INamedTypeSymbol) + Public Overrides Function FindEntryPoints(compilation As Compilation, findFormsOnly As Boolean) As IEnumerable(Of INamedTypeSymbol) Return VisualBasicEntryPointFinder.FindEntryPoints(compilation, findFormsOnly) End Function End Class diff --git a/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/VisualBasicProject.OptionsProcessor.vb b/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/VisualBasicProject.OptionsProcessor.vb index d2351a187f297..a01bfb356f3fe 100644 --- a/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/VisualBasicProject.OptionsProcessor.vb +++ b/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/VisualBasicProject.OptionsProcessor.vb @@ -221,7 +221,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim Private Shared Function GetConditionalCompilationSymbols(kind As OutputKind, str As String) As ImmutableArray(Of KeyValuePair(Of String, Object)) Debug.Assert(str IsNot Nothing) - Dim key = KeyValuePairUtil.Create(str, kind) + Dim key = KeyValuePair.Create(str, kind) Dim result As ImmutableArray(Of KeyValuePair(Of String, Object)) = Nothing If s_conditionalCompilationSymbolsCache.TryGetValue(key, result) Then diff --git a/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/VisualBasicProject.vb b/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/VisualBasicProject.vb index 0b6512d5a454f..91e6db9953c3e 100644 --- a/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/VisualBasicProject.vb +++ b/src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/VisualBasicProject.vb @@ -8,15 +8,12 @@ Imports System.Runtime.InteropServices Imports System.Runtime.InteropServices.ComTypes Imports System.Threading Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.ErrorReporting -Imports Microsoft.CodeAnalysis.Host -Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.VisualStudio.ComponentModelHost Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel -Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy -Imports Microsoft.VisualStudio.LanguageServices.Implementation.TaskList Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop Imports Microsoft.VisualStudio.Shell.Interop diff --git a/src/VisualStudio/VisualBasic/Impl/Snippets/VisualBasicSnippetExpansionLanguageHelper.vb b/src/VisualStudio/VisualBasic/Impl/Snippets/VisualBasicSnippetExpansionLanguageHelper.vb index 7e18a757f01d2..23fb0d49f2e83 100644 --- a/src/VisualStudio/VisualBasic/Impl/Snippets/VisualBasicSnippetExpansionLanguageHelper.vb +++ b/src/VisualStudio/VisualBasic/Impl/Snippets/VisualBasicSnippetExpansionLanguageHelper.vb @@ -6,6 +6,7 @@ Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.AddImport +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Editor.Shared.Extensions Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Formatting diff --git a/src/VisualStudio/VisualBasic/Impl/Venus/ContainedLanguageStaticEventBinding.vb b/src/VisualStudio/VisualBasic/Impl/Venus/ContainedLanguageStaticEventBinding.vb index bbfaca0e3ffe3..53f7f5ae866a5 100644 --- a/src/VisualStudio/VisualBasic/Impl/Venus/ContainedLanguageStaticEventBinding.vb +++ b/src/VisualStudio/VisualBasic/Impl/Venus/ContainedLanguageStaticEventBinding.vb @@ -5,7 +5,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Collections -Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic diff --git a/src/VisualStudio/VisualBasic/Impl/Venus/VisualBasicAdditionalFormattingRuleLanguageService.vb b/src/VisualStudio/VisualBasic/Impl/Venus/VisualBasicAdditionalFormattingRuleLanguageService.vb index df8db2345dc32..1edcdbeddb3b7 100644 --- a/src/VisualStudio/VisualBasic/Impl/Venus/VisualBasicAdditionalFormattingRuleLanguageService.vb +++ b/src/VisualStudio/VisualBasic/Impl/Venus/VisualBasicAdditionalFormattingRuleLanguageService.vb @@ -6,7 +6,6 @@ Imports System.Composition Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities Imports Microsoft.CodeAnalysis.Formatting.Rules -Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus diff --git a/src/VisualStudio/VisualBasic/Impl/Venus/VisualBasicContainedLanguage.vb b/src/VisualStudio/VisualBasic/Impl/Venus/VisualBasicContainedLanguage.vb index 6a03ab41c021e..91265d677ae02 100644 --- a/src/VisualStudio/VisualBasic/Impl/Venus/VisualBasicContainedLanguage.vb +++ b/src/VisualStudio/VisualBasic/Impl/Venus/VisualBasicContainedLanguage.vb @@ -3,16 +3,12 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics -Imports Microsoft.CodeAnalysis.Editor.Host -Imports Microsoft.CodeAnalysis.Editor.Shared.Extensions Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Workspaces.ProjectSystem Imports Microsoft.VisualStudio.ComponentModelHost -Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus Imports Microsoft.VisualStudio.Shell.Interop Imports Microsoft.VisualStudio.Utilities diff --git a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/Roslyn.VisualStudio.DiagnosticsWindow.csproj b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/Roslyn.VisualStudio.DiagnosticsWindow.csproj index 0b326d99a0166..cffd7bb9e6037 100644 --- a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/Roslyn.VisualStudio.DiagnosticsWindow.csproj +++ b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/Roslyn.VisualStudio.DiagnosticsWindow.csproj @@ -15,6 +15,7 @@ false false true + true GetAutoInsertAsync(TextDocument document, char typedChar, int position, CancellationToken cancellationToken); + Task GetAutoInsertAsync(TextDocument document, char typedChar, int position, CancellationToken cancellationToken); } diff --git a/src/VisualStudio/Xaml/Impl/Features/OrganizeImports/XamlOrganizeImportsService.cs b/src/VisualStudio/Xaml/Impl/Features/OrganizeImports/XamlOrganizeImportsService.cs index 0f2f2b19e3d43..ae19d479f9086 100644 --- a/src/VisualStudio/Xaml/Impl/Features/OrganizeImports/XamlOrganizeImportsService.cs +++ b/src/VisualStudio/Xaml/Impl/Features/OrganizeImports/XamlOrganizeImportsService.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable - using System; using System.Composition; using System.Threading; @@ -16,35 +14,19 @@ namespace Microsoft.CodeAnalysis.Editor.Xaml.OrganizeImports; [ExportLanguageService(typeof(IOrganizeImportsService), StringConstants.XamlLanguageName), Shared] -internal sealed partial class XamlOrganizeImportsService : IOrganizeImportsService +[method: ImportingConstructor] +[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] +internal sealed partial class XamlOrganizeImportsService(IXamlOrganizeNamespacesService organizeService) : IOrganizeImportsService { - private readonly IXamlOrganizeNamespacesService _organizeService; - - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public XamlOrganizeImportsService(IXamlOrganizeNamespacesService organizeService) - { - _organizeService = organizeService; - } + private readonly IXamlOrganizeNamespacesService _organizeService = organizeService; public async Task OrganizeImportsAsync(Document document, OrganizeImportsOptions options, CancellationToken cancellationToken) { return await _organizeService.OrganizeNamespacesAsync(document, options.PlaceSystemNamespaceFirst, cancellationToken).ConfigureAwait(false) ?? document; } - public string SortImportsDisplayStringWithAccelerator - { - get - { - return Resources.Sort_Namespaces; - } - } + public string SortImportsDisplayStringWithAccelerator => Resources.Sort_Namespaces_with_accelerator; + public string SortImportsDisplayStringWithoutAccelerator => Resources.Sort_Namespaces; - public string SortAndRemoveUnusedImportsDisplayStringWithAccelerator - { - get - { - return Resources.RemoveAndSortNamespacesWithAccelerator; - } - } + public string SortAndRemoveUnusedImportsDisplayStringWithAccelerator => Resources.RemoveAndSortNamespacesWithAccelerator; } diff --git a/src/VisualStudio/Xaml/Impl/Features/TypeRename/IXamlTypeRenameService.cs b/src/VisualStudio/Xaml/Impl/Features/TypeRename/IXamlTypeRenameService.cs index 05ecb26beb825..372fa2cdc8450 100644 --- a/src/VisualStudio/Xaml/Impl/Features/TypeRename/IXamlTypeRenameService.cs +++ b/src/VisualStudio/Xaml/Impl/Features/TypeRename/IXamlTypeRenameService.cs @@ -11,5 +11,5 @@ namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.TypeRename; internal interface IXamlTypeRenameService : ILanguageService { - public Task GetTypeRenameAsync(TextDocument document, int position, CancellationToken cancellationToken); + Task GetTypeRenameAsync(TextDocument document, int position, CancellationToken cancellationToken); } diff --git a/src/VisualStudio/Xaml/Impl/Implementation/LanguageClient/XamlInProcLanguageClient.cs b/src/VisualStudio/Xaml/Impl/Implementation/LanguageClient/XamlInProcLanguageClient.cs index ce86544584499..3127b454c06d4 100644 --- a/src/VisualStudio/Xaml/Impl/Implementation/LanguageClient/XamlInProcLanguageClient.cs +++ b/src/VisualStudio/Xaml/Impl/Implementation/LanguageClient/XamlInProcLanguageClient.cs @@ -14,9 +14,9 @@ using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.LanguageServer.Client; -using Roslyn.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer; using Microsoft.VisualStudio.Utilities; +using Roslyn.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Xaml; diff --git a/src/VisualStudio/Xaml/Impl/Implementation/LanguageClient/XamlInProcLanguageClientDisableUX.cs b/src/VisualStudio/Xaml/Impl/Implementation/LanguageClient/XamlInProcLanguageClientDisableUX.cs index 07314195d06c3..413caa32d8646 100644 --- a/src/VisualStudio/Xaml/Impl/Implementation/LanguageClient/XamlInProcLanguageClientDisableUX.cs +++ b/src/VisualStudio/Xaml/Impl/Implementation/LanguageClient/XamlInProcLanguageClientDisableUX.cs @@ -14,9 +14,9 @@ using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.LanguageServer.Client; -using Roslyn.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer; using Microsoft.VisualStudio.Utilities; +using Roslyn.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Xaml; diff --git a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Commands/CreateEventCommandHandler.cs b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Commands/CreateEventCommandHandler.cs index d3a4d26bacaaf..9791d01ac0fca 100644 --- a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Commands/CreateEventCommandHandler.cs +++ b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Commands/CreateEventCommandHandler.cs @@ -16,7 +16,6 @@ using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Completion; using Newtonsoft.Json.Linq; using Roslyn.LanguageServer.Protocol; -using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler; diff --git a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Completion/CompletionHandler.cs b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Completion/CompletionHandler.cs index 780f365f9a271..58aba76096271 100644 --- a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Completion/CompletionHandler.cs +++ b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Completion/CompletionHandler.cs @@ -12,13 +12,13 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Xaml; +using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.Text; -using Roslyn.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Completion; -using Microsoft.CodeAnalysis.Extensions; +using Roslyn.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler; diff --git a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Definitions/GoToDefinitionHandler.cs b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Definitions/GoToDefinitionHandler.cs index 2b2b38d725e74..a384aec71eaa9 100644 --- a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Definitions/GoToDefinitionHandler.cs +++ b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Definitions/GoToDefinitionHandler.cs @@ -19,9 +19,9 @@ using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; -using Roslyn.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Definitions; using Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer; +using Roslyn.LanguageServer.Protocol; using Roslyn.Utilities; using LSP = Roslyn.LanguageServer.Protocol; diff --git a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Diagnostics/AbstractPullDiagnosticHandler.cs b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Diagnostics/AbstractPullDiagnosticHandler.cs index e775f1ae02091..43dc24de3c07e 100644 --- a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Diagnostics/AbstractPullDiagnosticHandler.cs +++ b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Diagnostics/AbstractPullDiagnosticHandler.cs @@ -15,8 +15,8 @@ using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; -using Roslyn.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Diagnostics; +using Roslyn.LanguageServer.Protocol; using Roslyn.Utilities; using LSP = Roslyn.LanguageServer.Protocol; diff --git a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Diagnostics/DocumentPullDiagnosticHandler.cs b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Diagnostics/DocumentPullDiagnosticHandler.cs index 1e6687b9bba3b..61b727edd8121 100644 --- a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Diagnostics/DocumentPullDiagnosticHandler.cs +++ b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Diagnostics/DocumentPullDiagnosticHandler.cs @@ -9,9 +9,9 @@ using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CommonLanguageServerProtocol.Framework; -using Roslyn.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Diagnostics; using Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer; +using Roslyn.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Implementation.LanguageServer.Handler.Diagnostics; diff --git a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Diagnostics/WorkspacePullDiagnosticHandler.cs b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Diagnostics/WorkspacePullDiagnosticHandler.cs index c907f002b2370..f96133e81b63c 100644 --- a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Diagnostics/WorkspacePullDiagnosticHandler.cs +++ b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Diagnostics/WorkspacePullDiagnosticHandler.cs @@ -10,10 +10,10 @@ using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.PooledObjects; -using Roslyn.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Diagnostics; using Microsoft.VisualStudio.LanguageServices.Xaml.Implementation.LanguageServer.Extensions; using Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer; +using Roslyn.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Implementation.LanguageServer.Handler.Diagnostics; diff --git a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/FoldingRanges/FoldingRangesHandler.cs b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/FoldingRanges/FoldingRangesHandler.cs index 62e154dd99b00..01cf24ccc6cc0 100644 --- a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/FoldingRanges/FoldingRangesHandler.cs +++ b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/FoldingRanges/FoldingRangesHandler.cs @@ -9,8 +9,8 @@ using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.PooledObjects; -using Roslyn.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Structure; +using Roslyn.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler; diff --git a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Formatting/AbstractFormatDocumentHandlerBase.cs b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Formatting/AbstractFormatDocumentHandlerBase.cs index e10b0f779f498..ef76ebcf64a34 100644 --- a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Formatting/AbstractFormatDocumentHandlerBase.cs +++ b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Formatting/AbstractFormatDocumentHandlerBase.cs @@ -9,8 +9,8 @@ using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; -using Roslyn.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Formatting; +using Roslyn.LanguageServer.Protocol; using LSP = Roslyn.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler; diff --git a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Formatting/FormatDocumentOnTypeHandler.cs b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Formatting/FormatDocumentOnTypeHandler.cs index 7bbc15d0a92ed..0b7344efad5b4 100644 --- a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Formatting/FormatDocumentOnTypeHandler.cs +++ b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Formatting/FormatDocumentOnTypeHandler.cs @@ -11,8 +11,8 @@ using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.PooledObjects; -using Roslyn.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Formatting; +using Roslyn.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler; diff --git a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Hover/HoverHandler.cs b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Hover/HoverHandler.cs index 220927c3be735..9c79c15af9af6 100644 --- a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Hover/HoverHandler.cs +++ b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Hover/HoverHandler.cs @@ -10,15 +10,15 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; -using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.LanguageServer.Handler; +using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; -using Roslyn.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Features.QuickInfo; using Microsoft.VisualStudio.LanguageServices.Xaml.Implementation.LanguageServer.Extensions; using Microsoft.VisualStudio.Text.Adornments; +using Roslyn.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler; diff --git a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/OnAutoInsert/OnAutoInsertHandler.cs b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/OnAutoInsert/OnAutoInsertHandler.cs index d977c09b1ab80..57a5e251e6f49 100644 --- a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/OnAutoInsert/OnAutoInsertHandler.cs +++ b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/OnAutoInsert/OnAutoInsertHandler.cs @@ -6,12 +6,12 @@ using System.Composition; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.LanguageServer.Handler; -using Roslyn.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Features.AutoInsert; -using Microsoft.CodeAnalysis; +using Roslyn.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler; diff --git a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/OnTypeRename/OnTypeRenameHandler.cs b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/OnTypeRename/OnTypeRenameHandler.cs index f728077523acb..cc1f6a76acc1d 100644 --- a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/OnTypeRename/OnTypeRenameHandler.cs +++ b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/OnTypeRename/OnTypeRenameHandler.cs @@ -7,12 +7,12 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.LanguageServer.Handler; -using Roslyn.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Features.TypeRename; -using Microsoft.CodeAnalysis; +using Roslyn.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler; diff --git a/src/VisualStudio/Xaml/Impl/Resources.resx b/src/VisualStudio/Xaml/Impl/Resources.resx index 0d254409cfb00..73970a205bd7b 100644 --- a/src/VisualStudio/Xaml/Impl/Resources.resx +++ b/src/VisualStudio/Xaml/Impl/Resources.resx @@ -123,7 +123,10 @@ Remove Unnecessary Namespaces - + &Sort Namespaces + + Sort Namespaces + \ No newline at end of file diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.cs.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.cs.xlf index 81f5e90eec306..08d84aadd88bb 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.cs.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.cs.xlf @@ -13,8 +13,13 @@ + Sort Namespaces + Sort Namespaces + + + &Sort Namespaces - &Seřadit obory názvů + &Sort Namespaces diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.de.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.de.xlf index 8fdf44577a8e6..8a8f7db9c876f 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.de.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.de.xlf @@ -13,8 +13,13 @@ + Sort Namespaces + Sort Namespaces + + + &Sort Namespaces - Namespaces &sortieren + &Sort Namespaces diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.es.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.es.xlf index 9e5436e1847c4..ea19bf04d32e9 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.es.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.es.xlf @@ -13,8 +13,13 @@ + Sort Namespaces + Sort Namespaces + + + &Sort Namespaces - Orde&nar espacios de nombres + &Sort Namespaces diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.fr.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.fr.xlf index 5bca29bf02dbf..aad6b3900c37a 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.fr.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.fr.xlf @@ -13,8 +13,13 @@ + Sort Namespaces + Sort Namespaces + + + &Sort Namespaces - &Trier les espaces de noms + &Sort Namespaces diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.it.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.it.xlf index ad38bcea623fd..136035825e821 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.it.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.it.xlf @@ -13,8 +13,13 @@ + Sort Namespaces + Sort Namespaces + + + &Sort Namespaces - Or&dina spazi dei nomi + &Sort Namespaces diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.ja.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.ja.xlf index 819d150ca12e3..3fe750d02406c 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.ja.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.ja.xlf @@ -13,8 +13,13 @@ + Sort Namespaces + Sort Namespaces + + + &Sort Namespaces - 名前空間の並べ替え(&S) + &Sort Namespaces diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.ko.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.ko.xlf index fd25824b1cf8d..1c83511142a42 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.ko.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.ko.xlf @@ -13,8 +13,13 @@ + Sort Namespaces + Sort Namespaces + + + &Sort Namespaces - 네임 스페이스 정렬(&S) + &Sort Namespaces diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.pl.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.pl.xlf index 447ddeb132399..314ec49319497 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.pl.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.pl.xlf @@ -13,8 +13,13 @@ + Sort Namespaces + Sort Namespaces + + + &Sort Namespaces - &Sortuj przestrzenie nazw + &Sort Namespaces diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.pt-BR.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.pt-BR.xlf index 12b198750208c..520ab2048daf9 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.pt-BR.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.pt-BR.xlf @@ -13,8 +13,13 @@ + Sort Namespaces + Sort Namespaces + + + &Sort Namespaces - Cla&ssificar Namespaces + &Sort Namespaces diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.ru.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.ru.xlf index 2e88234ff0bed..1cc110524f1d2 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.ru.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.ru.xlf @@ -13,8 +13,13 @@ + Sort Namespaces + Sort Namespaces + + + &Sort Namespaces - &Сортировать пространства имен + &Sort Namespaces diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.tr.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.tr.xlf index 8c28cdf33e838..a51d5580f3c28 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.tr.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.tr.xlf @@ -13,8 +13,13 @@ + Sort Namespaces + Sort Namespaces + + + &Sort Namespaces - &Ad Alanlarını Sırala + &Sort Namespaces diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.zh-Hans.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.zh-Hans.xlf index ddcb444de9c81..97494d1b9351e 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.zh-Hans.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.zh-Hans.xlf @@ -13,8 +13,13 @@ + Sort Namespaces + Sort Namespaces + + + &Sort Namespaces - 对命名空间排序(&S) + &Sort Namespaces diff --git a/src/VisualStudio/Xaml/Impl/xlf/Resources.zh-Hant.xlf b/src/VisualStudio/Xaml/Impl/xlf/Resources.zh-Hant.xlf index dde036c6c76e8..ca0c0db70a5f9 100644 --- a/src/VisualStudio/Xaml/Impl/xlf/Resources.zh-Hant.xlf +++ b/src/VisualStudio/Xaml/Impl/xlf/Resources.zh-Hant.xlf @@ -13,8 +13,13 @@ + Sort Namespaces + Sort Namespaces + + + &Sort Namespaces - 排序 Namespace(&S) + &Sort Namespaces diff --git a/src/Workspaces/CSharp/Portable/CSharpWorkspaceResources.resx b/src/Workspaces/CSharp/Portable/CSharpWorkspaceResources.resx index 96627de595696..da8e10efa6221 100644 --- a/src/Workspaces/CSharp/Portable/CSharpWorkspaceResources.resx +++ b/src/Workspaces/CSharp/Portable/CSharpWorkspaceResources.resx @@ -126,9 +126,12 @@ R&emove and Sort Usings - + &Sort Usings + + Sort Usings + C# Formatting Rules diff --git a/src/Workspaces/CSharp/Portable/Classification/SyntaxClassification/FunctionPointerUnmanagedCallingConventionClassifier.cs b/src/Workspaces/CSharp/Portable/Classification/SyntaxClassification/FunctionPointerUnmanagedCallingConventionClassifier.cs index 0f0f2628153f6..e7e565b5cd85b 100644 --- a/src/Workspaces/CSharp/Portable/Classification/SyntaxClassification/FunctionPointerUnmanagedCallingConventionClassifier.cs +++ b/src/Workspaces/CSharp/Portable/Classification/SyntaxClassification/FunctionPointerUnmanagedCallingConventionClassifier.cs @@ -9,7 +9,6 @@ using Microsoft.CodeAnalysis.Classification.Classifiers; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Classification; diff --git a/src/Workspaces/CSharp/Portable/Classification/SyntaxClassification/NameSyntaxClassifier.cs b/src/Workspaces/CSharp/Portable/Classification/SyntaxClassification/NameSyntaxClassifier.cs index cb55f3a0f4c11..1b083846d6899 100644 --- a/src/Workspaces/CSharp/Portable/Classification/SyntaxClassification/NameSyntaxClassifier.cs +++ b/src/Workspaces/CSharp/Portable/Classification/SyntaxClassification/NameSyntaxClassifier.cs @@ -15,7 +15,6 @@ using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Classification.Classifiers; diff --git a/src/Workspaces/CSharp/Portable/Classification/Worker.cs b/src/Workspaces/CSharp/Portable/Classification/Worker.cs index 283c9431f1a19..187d858170464 100644 --- a/src/Workspaces/CSharp/Portable/Classification/Worker.cs +++ b/src/Workspaces/CSharp/Portable/Classification/Worker.cs @@ -10,8 +10,8 @@ using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Shared.Extensions; +using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Classification; diff --git a/src/Workspaces/CSharp/Portable/CodeGeneration/CSharpSyntaxGenerator.cs b/src/Workspaces/CSharp/Portable/CodeGeneration/CSharpSyntaxGenerator.cs index 89c78923cc538..cf03d43c8ed4e 100644 --- a/src/Workspaces/CSharp/Portable/CodeGeneration/CSharpSyntaxGenerator.cs +++ b/src/Workspaces/CSharp/Portable/CodeGeneration/CSharpSyntaxGenerator.cs @@ -26,7 +26,9 @@ namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration; using static CSharpSyntaxTokens; [ExportLanguageService(typeof(SyntaxGenerator), LanguageNames.CSharp), Shared] -internal sealed class CSharpSyntaxGenerator : SyntaxGenerator +[method: ImportingConstructor] +[method: SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Incorrectly used in production code: https://github.com/dotnet/roslyn/issues/42839")] +internal sealed class CSharpSyntaxGenerator() : SyntaxGenerator { // A bit hacky, but we need to actually run ParseToken on the "nameof" text as there's no // other way to get a token back that has the appropriate internal bit set that indicates @@ -34,12 +36,6 @@ internal sealed class CSharpSyntaxGenerator : SyntaxGenerator private static readonly IdentifierNameSyntax s_nameOfIdentifier = SyntaxFactory.IdentifierName(SyntaxFactory.ParseToken("nameof")); - [ImportingConstructor] - [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Incorrectly used in production code: https://github.com/dotnet/roslyn/issues/42839")] - public CSharpSyntaxGenerator() - { - } - internal override SyntaxTrivia ElasticMarker => SyntaxFactory.ElasticMarker; internal override SyntaxGeneratorInternal SyntaxGeneratorInternal @@ -1409,8 +1405,11 @@ private static bool CanHaveAccessibility(SyntaxNode declaration) public override Accessibility GetAccessibility(SyntaxNode declaration) => CSharpAccessibilityFacts.Instance.GetAccessibility(declaration); - private static void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out DeclarationModifiers modifiers, out bool isDefault) - => CSharpAccessibilityFacts.GetAccessibilityAndModifiers(modifierList, out accessibility, out modifiers, out isDefault); + private static void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out DeclarationModifiers declarationModifiers, out bool isDefault) + { + CSharpAccessibilityFacts.GetAccessibilityAndModifiers(modifierList, out accessibility, out var modifiers, out isDefault); + declarationModifiers = modifiers.ToDeclarationModifiers(); + } public override SyntaxNode WithAccessibility(SyntaxNode declaration, Accessibility accessibility) { @@ -1886,7 +1885,168 @@ private static SyntaxList WithTypeConstrain } public override DeclarationKind GetDeclarationKind(SyntaxNode declaration) - => CSharpAccessibilityFacts.GetDeclarationKind(declaration); + { + switch (declaration.Kind()) + { + case SyntaxKind.ClassDeclaration: + case SyntaxKind.RecordDeclaration: + return DeclarationKind.Class; + case SyntaxKind.StructDeclaration: + case SyntaxKind.RecordStructDeclaration: + return DeclarationKind.Struct; + case SyntaxKind.InterfaceDeclaration: + return DeclarationKind.Interface; + case SyntaxKind.EnumDeclaration: + return DeclarationKind.Enum; + case SyntaxKind.DelegateDeclaration: + return DeclarationKind.Delegate; + + case SyntaxKind.MethodDeclaration: + return DeclarationKind.Method; + case SyntaxKind.OperatorDeclaration: + return DeclarationKind.Operator; + case SyntaxKind.ConversionOperatorDeclaration: + return DeclarationKind.ConversionOperator; + case SyntaxKind.ConstructorDeclaration: + return DeclarationKind.Constructor; + case SyntaxKind.DestructorDeclaration: + return DeclarationKind.Destructor; + + case SyntaxKind.PropertyDeclaration: + return DeclarationKind.Property; + case SyntaxKind.IndexerDeclaration: + return DeclarationKind.Indexer; + case SyntaxKind.EventDeclaration: + return DeclarationKind.CustomEvent; + case SyntaxKind.EnumMemberDeclaration: + return DeclarationKind.EnumMember; + case SyntaxKind.CompilationUnit: + return DeclarationKind.CompilationUnit; + case SyntaxKind.NamespaceDeclaration: + case SyntaxKind.FileScopedNamespaceDeclaration: + return DeclarationKind.Namespace; + case SyntaxKind.UsingDirective: + return DeclarationKind.NamespaceImport; + case SyntaxKind.Parameter: + return DeclarationKind.Parameter; + + case SyntaxKind.ParenthesizedLambdaExpression: + case SyntaxKind.SimpleLambdaExpression: + return DeclarationKind.LambdaExpression; + + case SyntaxKind.FieldDeclaration: + var fd = (FieldDeclarationSyntax)declaration; + if (fd.Declaration != null && fd.Declaration.Variables.Count == 1) + { + // this node is considered the declaration if it contains only one variable. + return DeclarationKind.Field; + } + else + { + return DeclarationKind.None; + } + + case SyntaxKind.EventFieldDeclaration: + var ef = (EventFieldDeclarationSyntax)declaration; + if (ef.Declaration != null && ef.Declaration.Variables.Count == 1) + { + // this node is considered the declaration if it contains only one variable. + return DeclarationKind.Event; + } + else + { + return DeclarationKind.None; + } + + case SyntaxKind.LocalDeclarationStatement: + var ld = (LocalDeclarationStatementSyntax)declaration; + if (ld.Declaration != null && ld.Declaration.Variables.Count == 1) + { + // this node is considered the declaration if it contains only one variable. + return DeclarationKind.Variable; + } + else + { + return DeclarationKind.None; + } + + case SyntaxKind.VariableDeclaration: + { + var vd = (VariableDeclarationSyntax)declaration; + if (vd.Variables.Count == 1 && vd.Parent == null) + { + // this node is the declaration if it contains only one variable and has no parent. + return DeclarationKind.Variable; + } + else + { + return DeclarationKind.None; + } + } + + case SyntaxKind.VariableDeclarator: + { + var vd = declaration.Parent as VariableDeclarationSyntax; + + // this node is considered the declaration if it is one among many, or it has no parent + if (vd == null || vd.Variables.Count > 1) + { + if (ParentIsFieldDeclaration(vd)) + { + return DeclarationKind.Field; + } + else if (ParentIsEventFieldDeclaration(vd)) + { + return DeclarationKind.Event; + } + else + { + return DeclarationKind.Variable; + } + } + + break; + } + + case SyntaxKind.AttributeList: + var list = (AttributeListSyntax)declaration; + if (list.Attributes.Count == 1) + { + return DeclarationKind.Attribute; + } + + break; + + case SyntaxKind.Attribute: + if (declaration.Parent is not AttributeListSyntax parentList || parentList.Attributes.Count > 1) + { + return DeclarationKind.Attribute; + } + + break; + + case SyntaxKind.GetAccessorDeclaration: + return DeclarationKind.GetAccessor; + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.InitAccessorDeclaration: + return DeclarationKind.SetAccessor; + case SyntaxKind.AddAccessorDeclaration: + return DeclarationKind.AddAccessor; + case SyntaxKind.RemoveAccessorDeclaration: + return DeclarationKind.RemoveAccessor; + } + + return DeclarationKind.None; + } + + private static bool ParentIsFieldDeclaration([NotNullWhen(true)] SyntaxNode? node) + => node?.Parent.IsKind(SyntaxKind.FieldDeclaration) ?? false; + + private static bool ParentIsEventFieldDeclaration([NotNullWhen(true)] SyntaxNode? node) + => node?.Parent.IsKind(SyntaxKind.EventFieldDeclaration) ?? false; + + private static bool ParentIsLocalDeclarationStatement([NotNullWhen(true)] SyntaxNode? node) + => node?.Parent.IsKind(SyntaxKind.LocalDeclarationStatement) ?? false; public override string GetName(SyntaxNode declaration) => declaration switch @@ -2082,9 +2242,9 @@ private static SyntaxNode GetFullDeclaration(SyntaxNode declaration) { case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; - if (CSharpAccessibilityFacts.ParentIsFieldDeclaration(vd) - || CSharpAccessibilityFacts.ParentIsEventFieldDeclaration(vd) - || CSharpAccessibilityFacts.ParentIsLocalDeclarationStatement(vd)) + if (ParentIsFieldDeclaration(vd) + || ParentIsEventFieldDeclaration(vd) + || ParentIsLocalDeclarationStatement(vd)) { Contract.ThrowIfNull(vd.Parent); return vd.Parent; @@ -2179,14 +2339,11 @@ private static TNode AddMissingTokens(TNode node, bool recurse) return (TNode)rewriter.Visit(node); } - private sealed class AddMissingTokensRewriter : CSharpSyntaxRewriter + private sealed class AddMissingTokensRewriter(bool recurse) : CSharpSyntaxRewriter { - private readonly bool _recurse; + private readonly bool _recurse = recurse; private bool _firstVisit = true; - public AddMissingTokensRewriter(bool recurse) - => _recurse = recurse; - [return: NotNullIfNotNull(nameof(node))] public override SyntaxNode? Visit(SyntaxNode? node) { diff --git a/src/Workspaces/CSharp/Portable/FindSymbols/FindSymbolsUtilities.cs b/src/Workspaces/CSharp/Portable/FindSymbols/FindSymbolsUtilities.cs index 5d4db96c73a7b..35306414207af 100644 --- a/src/Workspaces/CSharp/Portable/FindSymbols/FindSymbolsUtilities.cs +++ b/src/Workspaces/CSharp/Portable/FindSymbols/FindSymbolsUtilities.cs @@ -2,11 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FindSymbols; diff --git a/src/Workspaces/CSharp/Portable/Formatting/CSharpFormattingOptions.cs b/src/Workspaces/CSharp/Portable/Formatting/CSharpFormattingOptions.cs index 9158f08247247..23d9e5f83dc16 100644 --- a/src/Workspaces/CSharp/Portable/Formatting/CSharpFormattingOptions.cs +++ b/src/Workspaces/CSharp/Portable/Formatting/CSharpFormattingOptions.cs @@ -133,7 +133,8 @@ public SpacePlacementInternalStorageMapping(IOption2 internalOption, SpacePlacem public static Option SpaceBeforeSemicolonsInForStatement { get; } = CSharpFormattingOptions2.SpaceBeforeSemicolonsInForStatement.ToPublicOption(); /// - public static Option SpacingAroundBinaryOperator { get; } = CSharpFormattingOptions2.SpacingAroundBinaryOperator.ToPublicOption(); + public static Option SpacingAroundBinaryOperator { get; } = + CSharpFormattingOptions2.SpacingAroundBinaryOperator.ToPublicOption().ConvertEnumOption(); /// public static Option IndentBraces { get; } = CSharpFormattingOptions2.IndentBraces.ToPublicOption(); @@ -151,7 +152,8 @@ public SpacePlacementInternalStorageMapping(IOption2 internalOption, SpacePlacem public static Option IndentSwitchCaseSectionWhenBlock { get; } = CSharpFormattingOptions2.IndentSwitchCaseSectionWhenBlock.ToPublicOption(); /// - public static Option LabelPositioning { get; } = CSharpFormattingOptions2.LabelPositioning.ToPublicOption(); + public static Option LabelPositioning { get; } = + CSharpFormattingOptions2.LabelPositioning.ToPublicOption().ConvertEnumOption(); /// public static Option WrappingPreserveSingleLine { get; } = CSharpFormattingOptions2.WrappingPreserveSingleLine.ToPublicOption(); @@ -187,3 +189,27 @@ public SpacePlacementInternalStorageMapping(IOption2 internalOption, SpacePlacem /// public static Option NewLineForClausesInQuery { get; } = CSharpFormattingOptions2.NewLineForClausesInQuery.ToPublicOption(); } + +public enum LabelPositionOptions +{ + /// Placed in the Zeroth column of the text editor + LeftMost = LabelPositionOptionsInternal.LeftMost, + + /// Placed at one less indent to the current context + OneLess = LabelPositionOptionsInternal.OneLess, + + /// Placed at the same indent as the current context + NoIndent = LabelPositionOptionsInternal.NoIndent, +} + +public enum BinaryOperatorSpacingOptions +{ + /// Single Spacing + Single = BinaryOperatorSpacingOptionsInternal.Single, + + /// Ignore Formatting + Ignore = BinaryOperatorSpacingOptionsInternal.Ignore, + + /// Remove Spacing + Remove = BinaryOperatorSpacingOptionsInternal.Remove, +} diff --git a/src/Workspaces/CSharp/Portable/LanguageServices/FixAllSpanMappingService/CSharpFixAllSpanMappingService.cs b/src/Workspaces/CSharp/Portable/LanguageServices/FixAllSpanMappingService/CSharpFixAllSpanMappingService.cs index f99a109911933..33ecdd714ce22 100644 --- a/src/Workspaces/CSharp/Portable/LanguageServices/FixAllSpanMappingService/CSharpFixAllSpanMappingService.cs +++ b/src/Workspaces/CSharp/Portable/LanguageServices/FixAllSpanMappingService/CSharpFixAllSpanMappingService.cs @@ -8,11 +8,11 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CodeFixesAndRefactorings; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; -using Microsoft.CodeAnalysis.CodeFixesAndRefactorings; namespace Microsoft.CodeAnalysis.CSharp.CodeFixesAndRefactorings; diff --git a/src/Workspaces/CSharp/Portable/Microsoft.CodeAnalysis.CSharp.Workspaces.csproj b/src/Workspaces/CSharp/Portable/Microsoft.CodeAnalysis.CSharp.Workspaces.csproj index 150d011eb0286..c77015a1b03d7 100644 --- a/src/Workspaces/CSharp/Portable/Microsoft.CodeAnalysis.CSharp.Workspaces.csproj +++ b/src/Workspaces/CSharp/Portable/Microsoft.CodeAnalysis.CSharp.Workspaces.csproj @@ -6,6 +6,7 @@ Microsoft.CodeAnalysis.CSharp true $(NetRoslynSourceBuild);netstandard2.0 + $(DefineConstants);CSHARP_WORKSPACE full @@ -47,6 +48,7 @@ + diff --git a/src/Workspaces/CSharp/Portable/OrganizeImports/CSharpOrganizeImportsService.Rewriter.cs b/src/Workspaces/CSharp/Portable/OrganizeImports/CSharpOrganizeImportsService.Rewriter.cs index a901004ab6d2c..ebf0c90a92998 100644 --- a/src/Workspaces/CSharp/Portable/OrganizeImports/CSharpOrganizeImportsService.Rewriter.cs +++ b/src/Workspaces/CSharp/Portable/OrganizeImports/CSharpOrganizeImportsService.Rewriter.cs @@ -2,13 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Collections.Generic; -using System.Linq; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.OrganizeImports; -using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.OrganizeImports; @@ -20,8 +17,6 @@ private sealed class Rewriter(OrganizeImportsOptions options) : CSharpSyntaxRewr private readonly bool _separateGroups = options.SeparateImportDirectiveGroups; private readonly SyntaxTrivia _fallbackTrivia = CSharpSyntaxGeneratorInternal.Instance.EndOfLine(options.NewLine); - public readonly IList TextChanges = []; - public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node) { node = (CompilationUnitSyntax)base.VisitCompilationUnit(node)!; @@ -31,14 +26,7 @@ public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node) _fallbackTrivia, out var organizedExternAliasList, out var organizedUsingList); - var result = node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList); - if (node != result) - { - AddTextChange(node.Externs, organizedExternAliasList); - AddTextChange(node.Usings, organizedUsingList); - } - - return result; + return node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList); } public override SyntaxNode VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node) @@ -56,27 +44,7 @@ private BaseNamespaceDeclarationSyntax VisitBaseNamespaceDeclaration(BaseNamespa _fallbackTrivia, out var organizedExternAliasList, out var organizedUsingList); - var result = node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList); - if (node != result) - { - AddTextChange(node.Externs, organizedExternAliasList); - AddTextChange(node.Usings, organizedUsingList); - } - - return result; - } - - private void AddTextChange(SyntaxList list, SyntaxList organizedList) - where TSyntax : SyntaxNode - { - if (list.Count > 0) - this.TextChanges.Add(new TextChange(GetTextSpan(list), GetNewText(organizedList))); + return node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList); } - - private static string GetNewText(SyntaxList organizedList) where TSyntax : SyntaxNode - => string.Join(string.Empty, organizedList.Select(t => t.ToFullString())); - - private static TextSpan GetTextSpan(SyntaxList list) where TSyntax : SyntaxNode - => TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.End); } } diff --git a/src/Workspaces/CSharp/Portable/OrganizeImports/CSharpOrganizeImportsService.cs b/src/Workspaces/CSharp/Portable/OrganizeImports/CSharpOrganizeImportsService.cs index 8a67c11256287..c18f361b1ada0 100644 --- a/src/Workspaces/CSharp/Portable/OrganizeImports/CSharpOrganizeImportsService.cs +++ b/src/Workspaces/CSharp/Portable/OrganizeImports/CSharpOrganizeImportsService.cs @@ -29,6 +29,9 @@ public async Task OrganizeImportsAsync(Document document, OrganizeImpo } public string SortImportsDisplayStringWithAccelerator + => CSharpWorkspaceResources.Sort_Usings_with_accelerator; + + public string SortImportsDisplayStringWithoutAccelerator => CSharpWorkspaceResources.Sort_Usings; public string SortAndRemoveUnusedImportsDisplayStringWithAccelerator diff --git a/src/Workspaces/CSharp/Portable/Recommendations/CSharpRecommendationServiceRunner.cs b/src/Workspaces/CSharp/Portable/Recommendations/CSharpRecommendationServiceRunner.cs index 1a4276e13ddfd..58bccf1e2827e 100644 --- a/src/Workspaces/CSharp/Portable/Recommendations/CSharpRecommendationServiceRunner.cs +++ b/src/Workspaces/CSharp/Portable/Recommendations/CSharpRecommendationServiceRunner.cs @@ -700,7 +700,7 @@ private RecommendedSymbols GetSymbolsOffOfBoundExpression( var typeMembers = GetSymbolsOffOfBoundExpressionWorker(reinterpretedBinding, originalExpression, expression, containerType, unwrapNullable, isForDereference); return new RecommendedSymbols( - result.NamedSymbols.Concat(typeMembers.NamedSymbols), + [.. result.NamedSymbols, .. typeMembers.NamedSymbols], result.UnnamedSymbols); bool CanAccessInstanceAndStaticMembersOffOf(out SymbolInfo reinterpretedBinding) diff --git a/src/Workspaces/CSharp/Portable/Rename/CSharpRenameRewriterLanguageService.cs b/src/Workspaces/CSharp/Portable/Rename/CSharpRenameRewriterLanguageService.cs index 043057b57b8a5..ddd9ed99601c8 100644 --- a/src/Workspaces/CSharp/Portable/Rename/CSharpRenameRewriterLanguageService.cs +++ b/src/Workspaces/CSharp/Portable/Rename/CSharpRenameRewriterLanguageService.cs @@ -10,6 +10,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Simplification; using Microsoft.CodeAnalysis.CSharp.Symbols; diff --git a/src/Workspaces/CSharp/Portable/Simplification/Reducers/AbstractCSharpReducer.AbstractReductionRewriter.cs b/src/Workspaces/CSharp/Portable/Simplification/Reducers/AbstractCSharpReducer.AbstractReductionRewriter.cs index a6fd31373ac62..424806ebf81a2 100644 --- a/src/Workspaces/CSharp/Portable/Simplification/Reducers/AbstractCSharpReducer.AbstractReductionRewriter.cs +++ b/src/Workspaces/CSharp/Portable/Simplification/Reducers/AbstractCSharpReducer.AbstractReductionRewriter.cs @@ -11,7 +11,6 @@ using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Simplification; diff --git a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.cs.xlf b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.cs.xlf index c57c7d358205a..33545db947b0e 100644 --- a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.cs.xlf +++ b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.cs.xlf @@ -17,11 +17,6 @@ Od&ebrat a seřadit direktivy Using - - &Sort Usings - &Seřadit direktivy using - - Only attributes, constructor initializers, expressions or statements can be made explicit Jako explicitní jde nastavit jenom atributy, inicializátory konstruktorů, výrazy nebo příkazy. @@ -32,6 +27,16 @@ Implementujte rozhraní. + + Sort Usings + Sort Usings + + + + &Sort Usings + &Sort Usings + + \ No newline at end of file diff --git a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.de.xlf b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.de.xlf index bf506d9defc67..9ee5bae6a406c 100644 --- a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.de.xlf +++ b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.de.xlf @@ -17,11 +17,6 @@ &Unnötige Using-Direktiven entfernen und sortieren - - &Sort Usings - Using-Anweisungen &sortieren - - Only attributes, constructor initializers, expressions or statements can be made explicit Nur Attribute, Konstruktor-Initialisierungen, Ausdrücke oder Anweisungen können den Status ausdrücklich erhalten @@ -32,6 +27,16 @@ Schnittstelle implementieren + + Sort Usings + Sort Usings + + + + &Sort Usings + &Sort Usings + + \ No newline at end of file diff --git a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.es.xlf b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.es.xlf index e62149f0ac2a9..7e3143f7c2de4 100644 --- a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.es.xlf +++ b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.es.xlf @@ -17,11 +17,6 @@ Q&uitar y ordenar usos - - &Sort Usings - &Ordenar instrucciones Using - - Only attributes, constructor initializers, expressions or statements can be made explicit Solo los atributos, los inicializadores de constructor, las expresiones o las declaraciones se pueden hacer explícitos @@ -32,6 +27,16 @@ Implementar interfaz + + Sort Usings + Sort Usings + + + + &Sort Usings + &Sort Usings + + \ No newline at end of file diff --git a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.fr.xlf b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.fr.xlf index c7aefe011ed76..e82232c064c63 100644 --- a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.fr.xlf +++ b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.fr.xlf @@ -17,11 +17,6 @@ Supprim&er et trier les instructions using - - &Sort Usings - &Trier les using - - Only attributes, constructor initializers, expressions or statements can be made explicit Seuls des attributs, des initialiseurs de constructeur, des expressions ou des instructions peuvent être explicites @@ -32,6 +27,16 @@ Implémenter l'interface + + Sort Usings + Sort Usings + + + + &Sort Usings + &Sort Usings + + \ No newline at end of file diff --git a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.it.xlf b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.it.xlf index 00a8f47b2c708..c7ec6ca314db7 100644 --- a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.it.xlf +++ b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.it.xlf @@ -17,11 +17,6 @@ Ri&muovi e ordina using - - &Sort Usings - Or&dina using - - Only attributes, constructor initializers, expressions or statements can be made explicit È possibile rendere espliciti solo attributi, inizializzatori di costruttore, espressioni o istruzioni @@ -32,6 +27,16 @@ Implementa l'interfaccia + + Sort Usings + Sort Usings + + + + &Sort Usings + &Sort Usings + + \ No newline at end of file diff --git a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.ja.xlf b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.ja.xlf index 16105f18ed1a8..db574a94a4074 100644 --- a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.ja.xlf +++ b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.ja.xlf @@ -17,11 +17,6 @@ Using の削除と並び替え(&E) - - &Sort Usings - using の並べ替え(&S) - - Only attributes, constructor initializers, expressions or statements can be made explicit 明示できるのは、属性、コンストラクターの初期化子、式、ステートメントだけです @@ -32,6 +27,16 @@ インターフェイスを実装します + + Sort Usings + Sort Usings + + + + &Sort Usings + &Sort Usings + + \ No newline at end of file diff --git a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.ko.xlf b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.ko.xlf index 1af27670a5ef4..855470f1a71a9 100644 --- a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.ko.xlf +++ b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.ko.xlf @@ -17,11 +17,6 @@ Using 제거 및 정렬(&E) - - &Sort Usings - Using 정렬(&S) - - Only attributes, constructor initializers, expressions or statements can be made explicit 특성, 생성자 이니셜라이저, 식 또는 문만 명시적일 수 있습니다. @@ -32,6 +27,16 @@ 인터페이스 구현 + + Sort Usings + Sort Usings + + + + &Sort Usings + &Sort Usings + + \ No newline at end of file diff --git a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.pl.xlf b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.pl.xlf index dffddae7341e9..80043d65c21a0 100644 --- a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.pl.xlf +++ b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.pl.xlf @@ -17,11 +17,6 @@ &Usuń i sortuj instrukcje Usings - - &Sort Usings - &Sortuj użycia - - Only attributes, constructor initializers, expressions or statements can be made explicit Jako jawne można ustawić tylko atrybuty, inicjatory konstruktorów, wyrażenia lub instrukcje @@ -32,6 +27,16 @@ Zaimplementuj interfejs + + Sort Usings + Sort Usings + + + + &Sort Usings + &Sort Usings + + \ No newline at end of file diff --git a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.pt-BR.xlf b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.pt-BR.xlf index 985ccfe7e1802..627547cbca0c6 100644 --- a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.pt-BR.xlf +++ b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.pt-BR.xlf @@ -17,11 +17,6 @@ R&emover e Classificar Usos - - &Sort Usings - Cla&ssificar Usos - - Only attributes, constructor initializers, expressions or statements can be made explicit Somente atributos, inicializadores de construtor, expressões ou instruções podem ser tornados explícitos @@ -32,6 +27,16 @@ Implementar a interface + + Sort Usings + Sort Usings + + + + &Sort Usings + &Sort Usings + + \ No newline at end of file diff --git a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.ru.xlf b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.ru.xlf index 4e2577909af26..26b8702978d76 100644 --- a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.ru.xlf +++ b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.ru.xlf @@ -17,11 +17,6 @@ У&далить и отсортировать директивы using - - &Sort Usings - &Сортировать директивы using - - Only attributes, constructor initializers, expressions or statements can be made explicit Явными могут быть сделаны только атрибуты, инициализаторы конструктора, выражения или операторы @@ -32,6 +27,16 @@ Реализовать интерфейс + + Sort Usings + Sort Usings + + + + &Sort Usings + &Sort Usings + + \ No newline at end of file diff --git a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.tr.xlf b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.tr.xlf index c4a7ce714dd3c..8adb55b87028a 100644 --- a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.tr.xlf +++ b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.tr.xlf @@ -17,11 +17,6 @@ &Kaldır ve Sıralama Usings - - &Sort Usings - &Using’leri Sırala - - Only attributes, constructor initializers, expressions or statements can be made explicit Yalnızca öznitelikler, oluşturucu başlatıcıları, ifadeler veya deyimler açık hale getirilebilir @@ -32,6 +27,16 @@ Arabirimi uygula + + Sort Usings + Sort Usings + + + + &Sort Usings + &Sort Usings + + \ No newline at end of file diff --git a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.zh-Hans.xlf b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.zh-Hans.xlf index a36cc4ba030f2..b4daf1db7e64e 100644 --- a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.zh-Hans.xlf +++ b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.zh-Hans.xlf @@ -17,11 +17,6 @@ 删除 Using 和对其排序(&E) - - &Sort Usings - 对 using 排序(&S) - - Only attributes, constructor initializers, expressions or statements can be made explicit 仅属性、构造函数初始值设定项、表达式或语句可为显式 @@ -32,6 +27,16 @@ 实现接口 + + Sort Usings + Sort Usings + + + + &Sort Usings + &Sort Usings + + \ No newline at end of file diff --git a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.zh-Hant.xlf b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.zh-Hant.xlf index e29c508f42ffd..21e3b6798742d 100644 --- a/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.zh-Hant.xlf +++ b/src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.zh-Hant.xlf @@ -17,11 +17,6 @@ 移除和排序 Using(&E) - - &Sort Usings - 排序 Using(&S) - - Only attributes, constructor initializers, expressions or statements can be made explicit 只有屬性、建構函式初始設定式、運算式或陳述式才可明確設定 @@ -32,6 +27,16 @@ 實作介面 + + Sort Usings + Sort Usings + + + + &Sort Usings + &Sort Usings + + \ No newline at end of file diff --git a/src/Workspaces/CSharpTest/CSharpSyntaxFactsServiceTests.cs b/src/Workspaces/CSharpTest/CSharpSyntaxFactsServiceTests.cs index dbc47f6058221..3dbcebf86a26c 100644 --- a/src/Workspaces/CSharpTest/CSharpSyntaxFactsServiceTests.cs +++ b/src/Workspaces/CSharpTest/CSharpSyntaxFactsServiceTests.cs @@ -24,199 +24,221 @@ private static bool IsQueryKeyword(string markup) private static string WrapInMethod(string methodBody) { - return $@" -class C -{{ - void M() - {{ - {methodBody} - }} -}}"; + return $$""" + class C + { + void M() + { + {{methodBody}} + } + } + """; } [Fact] public void IsQueryKeyword_From() { - Assert.True(IsQueryKeyword(WrapInMethod(@" -var result = $$from var1 in collection1"))); + Assert.True(IsQueryKeyword(WrapInMethod(""" + var result = $$from var1 in collection1 + """))); } [Fact] public void IsQueryKeyword_In() { - Assert.True(IsQueryKeyword(WrapInMethod(@" -var result = from var1 $$in collection1"))); + Assert.True(IsQueryKeyword(WrapInMethod(""" + var result = from var1 $$in collection1 + """))); } [Fact] public void IsQueryKeyword_Where() { - Assert.True(IsQueryKeyword(WrapInMethod(@" -var customerOrders = from cust in customers - $$where cust.CustomerID = 1"))); + Assert.True(IsQueryKeyword(WrapInMethod(""" + var customerOrders = from cust in customers + $$where cust.CustomerID = 1 + """))); } [Fact] public void IsQueryKeyword_Select() { - Assert.True(IsQueryKeyword(WrapInMethod(@" -var customerOrders = from cust in customers - from ord in orders - where cust.CustomerID == ord.CustomerID - $$select cust.CompanyName, ord.OrderDate"))); + Assert.True(IsQueryKeyword(WrapInMethod(""" + var customerOrders = from cust in customers + from ord in orders + where cust.CustomerID == ord.CustomerID + $$select cust.CompanyName, ord.OrderDate + """))); } [Fact] public void IsQueryKeyword_GroupBy_Group() { - Assert.True(IsQueryKeyword(WrapInMethod(@" -var customersByCountry = from cust in customers - $$group cust by cust.Country - into g"))); + Assert.True(IsQueryKeyword(WrapInMethod(""" + var customersByCountry = from cust in customers + $$group cust by cust.Country + into g + """))); } [Fact] public void IsQueryKeyword_GroupBy_By() { - Assert.True(IsQueryKeyword(WrapInMethod(@" -var customersByCountry = from cust in customers - group cust $$by cust.Country - into g"))); + Assert.True(IsQueryKeyword(WrapInMethod(""" + var customersByCountry = from cust in customers + group cust $$by cust.Country + into g + """))); } [Fact] public void IsQueryKeyword_Into() { - Assert.True(IsQueryKeyword(WrapInMethod(@" -var customersByCountry = from cust in customers - group cust by cust.Country - $$into g"))); + Assert.True(IsQueryKeyword(WrapInMethod(""" + var customersByCountry = from cust in customers + group cust by cust.Country + $$into g + """))); } [Fact] public void IsQueryKeyword_GroupJoin_Join() { - Assert.True(IsQueryKeyword(WrapInMethod(@" -var query = from person in people - $$join pet in pets on person equals pet.Owner into gj - select new { OwnerName = person.FirstName, Pets = gj };"))); + Assert.True(IsQueryKeyword(WrapInMethod(""" + var query = from person in people + $$join pet in pets on person equals pet.Owner into gj + select new { OwnerName = person.FirstName, Pets = gj }; + """))); } [Fact] public void IsQueryKeyword_GroupJoin_In() { - Assert.True(IsQueryKeyword(WrapInMethod(@" -var query = from person in people - join pet $$in pets on person equals pet.Owner into gj - select new { OwnerName = person.FirstName, Pets = gj };"))); + Assert.True(IsQueryKeyword(WrapInMethod(""" + var query = from person in people + join pet $$in pets on person equals pet.Owner into gj + select new { OwnerName = person.FirstName, Pets = gj }; + """))); } [Fact] public void IsQueryKeyword_GroupJoin_On() { - Assert.True(IsQueryKeyword(WrapInMethod(@" -var query = from person in people - join pet in pets $$on person equals pet.Owner into gj - select new { OwnerName = person.FirstName, Pets = gj };"))); + Assert.True(IsQueryKeyword(WrapInMethod(""" + var query = from person in people + join pet in pets $$on person equals pet.Owner into gj + select new { OwnerName = person.FirstName, Pets = gj }; + """))); } [Fact] public void IsQueryKeyword_GroupJoin_Equals() { - Assert.True(IsQueryKeyword(WrapInMethod(@" -var query = from person in people - join pet in pets on person $$equals pet.Owner into gj - select new { OwnerName = person.FirstName, Pets = gj };"))); + Assert.True(IsQueryKeyword(WrapInMethod(""" + var query = from person in people + join pet in pets on person $$equals pet.Owner into gj + select new { OwnerName = person.FirstName, Pets = gj }; + """))); } [Fact] public void IsQueryKeyword_GroupJoin_Into() { - Assert.True(IsQueryKeyword(WrapInMethod(@" -var query = from person in people - join pet in pets on person equals pet.Owner $$into gj - select new { OwnerName = person.FirstName, Pets = gj };"))); + Assert.True(IsQueryKeyword(WrapInMethod(""" + var query = from person in people + join pet in pets on person equals pet.Owner $$into gj + select new { OwnerName = person.FirstName, Pets = gj }; + """))); } [Fact] public void IsQueryKeyword_Join_Join() { - Assert.True(IsQueryKeyword(WrapInMethod(@" -var query = from person in people - $$join pet in pets on person equals pet.Owner - select new { OwnerName = person.FirstName, PetName = pet.Name };"))); + Assert.True(IsQueryKeyword(WrapInMethod(""" + var query = from person in people + $$join pet in pets on person equals pet.Owner + select new { OwnerName = person.FirstName, PetName = pet.Name }; + """))); } [Fact] public void IsQueryKeyword_Join_In() { - Assert.True(IsQueryKeyword(WrapInMethod(@" -var query = from person in people - join pet $$in pets on person equals pet.Owner - select new { OwnerName = person.FirstName, PetName = pet.Name };"))); + Assert.True(IsQueryKeyword(WrapInMethod(""" + var query = from person in people + join pet $$in pets on person equals pet.Owner + select new { OwnerName = person.FirstName, PetName = pet.Name }; + """))); } [Fact] public void IsQueryKeyword_Join_On() { - Assert.True(IsQueryKeyword(WrapInMethod(@" -var query = from person in people - join pet in pets $$on person equals pet.Owner - select new { OwnerName = person.FirstName, PetName = pet.Name };"))); + Assert.True(IsQueryKeyword(WrapInMethod(""" + var query = from person in people + join pet in pets $$on person equals pet.Owner + select new { OwnerName = person.FirstName, PetName = pet.Name }; + """))); } [Fact] public void IsQueryKeyword_Join_Equals() { - Assert.True(IsQueryKeyword(WrapInMethod(@" -var query = from person in people - join pet in pets on person $$equals pet.Owner - select new { OwnerName = person.FirstName, PetName = pet.Name };"))); + Assert.True(IsQueryKeyword(WrapInMethod(""" + var query = from person in people + join pet in pets on person $$equals pet.Owner + select new { OwnerName = person.FirstName, PetName = pet.Name }; + """))); } [Fact] public void IsQueryKeyword_Let() { - Assert.True(IsQueryKeyword(WrapInMethod(@" -var discountedProducts = from prod in products - $$let discount = prod.UnitPrice * 0.1 - where discount >= 50 - select new { prod.ProductName, prod.UnitPrice, Discount }"))); + Assert.True(IsQueryKeyword(WrapInMethod(""" + var discountedProducts = from prod in products + $$let discount = prod.UnitPrice * 0.1 + where discount >= 50 + select new { prod.ProductName, prod.UnitPrice, Discount } + """))); } [Fact] public void IsQueryKeyword_OrderBy_OrderBy() { - Assert.True(IsQueryKeyword(WrapInMethod(@" -var titlesDescendingPrice = from book in books - $$orderby book.Price descending, book.Title ascending, book.Author - select new { book.Title, book.Price }"))); + Assert.True(IsQueryKeyword(WrapInMethod(""" + var titlesDescendingPrice = from book in books + $$orderby book.Price descending, book.Title ascending, book.Author + select new { book.Title, book.Price } + """))); } [Fact] public void IsQueryKeyword_OrderBy_Descending() { - Assert.True(IsQueryKeyword(WrapInMethod(@" -var titlesDescendingPrice = from book in books - orderby book.Price $$descending, book.Title ascending, book.Author - select new { book.Title, book.Price }"))); + Assert.True(IsQueryKeyword(WrapInMethod(""" + var titlesDescendingPrice = from book in books + orderby book.Price $$descending, book.Title ascending, book.Author + select new { book.Title, book.Price } + """))); } [Fact] public void IsQueryKeyword_OrderBy_Ascending() { - Assert.True(IsQueryKeyword(WrapInMethod(@" -var titlesDescendingPrice = from book in books - orderby book.Price descending, book.Title $$ascending, book.Author - select new { book.Title, book.Price }"))); + Assert.True(IsQueryKeyword(WrapInMethod(""" + var titlesDescendingPrice = from book in books + orderby book.Price descending, book.Title $$ascending, book.Author + select new { book.Title, book.Price } + """))); } [Fact] public void IsQueryKeyword_Not_ForEach_In() { - Assert.False(IsQueryKeyword(WrapInMethod(@" -foreach (var i $$in new int[0]) -{ -}"))); + Assert.False(IsQueryKeyword(WrapInMethod(""" + foreach (var i $$in new int[0]) + { + } + """))); } } diff --git a/src/Workspaces/CSharpTest/CodeGeneration/AddAttributesTests.cs b/src/Workspaces/CSharpTest/CodeGeneration/AddAttributesTests.cs index 8b253fadd6bf0..651c68f701fb7 100644 --- a/src/Workspaces/CSharpTest/CodeGeneration/AddAttributesTests.cs +++ b/src/Workspaces/CSharpTest/CodeGeneration/AddAttributesTests.cs @@ -65,21 +65,21 @@ private static async Task TestAsync(string initialText, string attributeAddedTex } [Fact] - public async Task TestAddAssemblyAttributeListToEmptyDocument() - { - await TestAsync( -string.Empty, -@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] -"); - } + public Task TestAddAssemblyAttributeListToEmptyDocument() + => TestAsync( + string.Empty, + """ + [assembly: System.Reflection.AssemblyVersion("1.0.0.0")] + + """); [Fact] - public async Task TestAddAssemblyAttributeListToDocumentWithOtherAssemblyAttribute() - { - await TestAsync( -@"[assembly: System.Reflection.AssemblyName(""Test"")]", -@"[assembly: System.Reflection.AssemblyName(""Test"")] -[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] -"); - } + public Task TestAddAssemblyAttributeListToDocumentWithOtherAssemblyAttribute() + => TestAsync( + """[assembly: System.Reflection.AssemblyName("Test")]""", + """ + [assembly: System.Reflection.AssemblyName("Test")] + [assembly: System.Reflection.AssemblyVersion("1.0.0.0")] + + """); } diff --git a/src/Workspaces/CSharpTest/CodeGeneration/AddImportsTests.cs b/src/Workspaces/CSharpTest/CodeGeneration/AddImportsTests.cs index 1f3ad883f6b7a..d952d3cc2776e 100644 --- a/src/Workspaces/CSharpTest/CodeGeneration/AddImportsTests.cs +++ b/src/Workspaces/CSharpTest/CodeGeneration/AddImportsTests.cs @@ -120,638 +120,711 @@ private static async Task TestAsync( ]; [Theory, MemberData(nameof(TestAllData))] - public async Task TestAddImport(bool useSymbolAnnotations) - { - await TestAsync( -@"class C -{ - public System.Collections.Generic.List F; -}", - -@"using System.Collections.Generic; - -class C -{ - public System.Collections.Generic.List F; -}", - -@"using System.Collections.Generic; - -class C -{ - public List F; -}", useSymbolAnnotations); - } + public Task TestAddImport(bool useSymbolAnnotations) + => TestAsync( + """ + class C + { + public System.Collections.Generic.List F; + } + """, + + """ + using System.Collections.Generic; + + class C + { + public System.Collections.Generic.List F; + } + """, + + """ + using System.Collections.Generic; + + class C + { + public List F; + } + """, useSymbolAnnotations); [Theory, MemberData(nameof(TestAllData))] - public async Task TestAddSystemImportFirst(bool useSymbolAnnotations) - { - await TestAsync( -@"using N; - -class C -{ - public System.Collections.Generic.List F; -}", - -@"using System.Collections.Generic; -using N; - -class C -{ - public System.Collections.Generic.List F; -}", - -@"using System.Collections.Generic; -using N; - -class C -{ - public List F; -}", useSymbolAnnotations); - } + public Task TestAddSystemImportFirst(bool useSymbolAnnotations) + => TestAsync( + """ + using N; + + class C + { + public System.Collections.Generic.List F; + } + """, + + """ + using System.Collections.Generic; + using N; + + class C + { + public System.Collections.Generic.List F; + } + """, + + """ + using System.Collections.Generic; + using N; + + class C + { + public List F; + } + """, useSymbolAnnotations); [Theory, MemberData(nameof(TestAllData))] - public async Task TestDoNotAddSystemImportFirst(bool useSymbolAnnotations) - { - await TestAsync( -@"using N; - -class C -{ - public System.Collections.Generic.List F; -}", - -@"using N; -using System.Collections.Generic; - -class C -{ - public System.Collections.Generic.List F; -}", - -@"using N; -using System.Collections.Generic; - -class C -{ - public List F; -}", + public Task TestDoNotAddSystemImportFirst(bool useSymbolAnnotations) + => TestAsync( + """ + using N; + + class C + { + public System.Collections.Generic.List F; + } + """, + + """ + using N; + using System.Collections.Generic; + + class C + { + public System.Collections.Generic.List F; + } + """, + + """ + using N; + using System.Collections.Generic; + + class C + { + public List F; + } + """, useSymbolAnnotations, placeSystemNamespaceFirst: false ); - } [Theory, MemberData(nameof(TestAllData))] - public async Task TestAddImportsInOrder(bool useSymbolAnnotations) - { - await TestAsync( -@"using System.Collections; -using System.Diagnostics; - -class C -{ - public System.Collections.Generic.List F; -}", - -@"using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; - -class C -{ - public System.Collections.Generic.List F; -}", - -@"using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; - -class C -{ - public List F; -}", useSymbolAnnotations); - } + public Task TestAddImportsInOrder(bool useSymbolAnnotations) + => TestAsync( + """ + using System.Collections; + using System.Diagnostics; + + class C + { + public System.Collections.Generic.List F; + } + """, + + """ + using System.Collections; + using System.Collections.Generic; + using System.Diagnostics; + + class C + { + public System.Collections.Generic.List F; + } + """, + + """ + using System.Collections; + using System.Collections.Generic; + using System.Diagnostics; + + class C + { + public List F; + } + """, useSymbolAnnotations); [Theory, MemberData(nameof(TestAllData))] - public async Task TestAddMultipleImportsInOrder(bool useSymbolAnnotations) - { - await TestAsync( -@"class C -{ - public System.Collections.Generic.List F; - public System.EventHandler Handler; -}", - -@"using System; -using System.Collections.Generic; - -class C -{ - public System.Collections.Generic.List F; - public System.EventHandler Handler; -}", - -@"using System; -using System.Collections.Generic; - -class C -{ - public List F; - public EventHandler Handler; -}", useSymbolAnnotations); - } + public Task TestAddMultipleImportsInOrder(bool useSymbolAnnotations) + => TestAsync( + """ + class C + { + public System.Collections.Generic.List F; + public System.EventHandler Handler; + } + """, + + """ + using System; + using System.Collections.Generic; + + class C + { + public System.Collections.Generic.List F; + public System.EventHandler Handler; + } + """, + + """ + using System; + using System.Collections.Generic; + + class C + { + public List F; + public EventHandler Handler; + } + """, useSymbolAnnotations); [Theory, MemberData(nameof(TestAllData))] - public async Task TestImportNotRedundantlyAdded(bool useSymbolAnnotations) - { - await TestAsync( -@"using System.Collections.Generic; - -class C -{ - public System.Collections.Generic.List F; -}", - -@"using System.Collections.Generic; - -class C -{ - public System.Collections.Generic.List F; -}", - -@"using System.Collections.Generic; - -class C -{ - public List F; -}", useSymbolAnnotations); - } + public Task TestImportNotRedundantlyAdded(bool useSymbolAnnotations) + => TestAsync( + """ + using System.Collections.Generic; + + class C + { + public System.Collections.Generic.List F; + } + """, + + """ + using System.Collections.Generic; + + class C + { + public System.Collections.Generic.List F; + } + """, + + """ + using System.Collections.Generic; + + class C + { + public List F; + } + """, useSymbolAnnotations); [Fact] - public async Task TestBuiltInTypeFromSyntaxes() - { - await TestAsync( -@"class C -{ - public System.Int32 F; -}", - -@"using System; - -class C -{ - public System.Int32 F; -}", - -@" -class C -{ - public int F; -}", useSymbolAnnotations: false); - } + public Task TestBuiltInTypeFromSyntaxes() + => TestAsync( + """ + class C + { + public System.Int32 F; + } + """, + + """ + using System; + + class C + { + public System.Int32 F; + } + """, + + """ + + class C + { + public int F; + } + """, useSymbolAnnotations: false); [Fact] - public async Task TestBuiltInTypeFromSymbols() - { - await TestAsync( -@"class C -{ - public System.Int32 F; -}", - -@"class C -{ - public System.Int32 F; -}", - -@"class C -{ - public int F; -}", useSymbolAnnotations: true); - } + public Task TestBuiltInTypeFromSymbols() + => TestAsync( + """ + class C + { + public System.Int32 F; + } + """, + + """ + class C + { + public System.Int32 F; + } + """, + + """ + class C + { + public int F; + } + """, useSymbolAnnotations: true); [Theory, MemberData(nameof(TestAllData))] - public async Task TestImportNotAddedForNamespaceDeclarations(bool useSymbolAnnotations) - { - await TestNoImportsAddedAsync( -@"namespace N -{ -}", useSymbolAnnotations); - } + public Task TestImportNotAddedForNamespaceDeclarations(bool useSymbolAnnotations) + => TestNoImportsAddedAsync( + """ + namespace N + { + } + """, useSymbolAnnotations); [Theory, MemberData(nameof(TestAllData))] - public async Task TestImportNotAddedForReferencesInsideNamespaceDeclarations(bool useSymbolAnnotations) - { - await TestAsync( -@"namespace N -{ - class C - { - private N.C c; - } -}", - -@"namespace N -{ - class C - { - private N.C c; - } -}", - -@"namespace N -{ - class C - { - private C c; - } -}", useSymbolAnnotations); - } + public Task TestImportNotAddedForReferencesInsideNamespaceDeclarations(bool useSymbolAnnotations) + => TestAsync( + """ + namespace N + { + class C + { + private N.C c; + } + } + """, + + """ + namespace N + { + class C + { + private N.C c; + } + } + """, + + """ + namespace N + { + class C + { + private C c; + } + } + """, useSymbolAnnotations); [Theory, MemberData(nameof(TestAllData))] - public async Task TestImportNotAddedForReferencesInsideParentOfNamespaceDeclarations(bool useSymbolAnnotations) - { - await TestAsync( -@"namespace N -{ - class C - { - } -} - -namespace N.N1 -{ - class C1 - { - private N.C c; - } -}", - -@"namespace N -{ - class C - { - } -} + public Task TestImportNotAddedForReferencesInsideParentOfNamespaceDeclarations(bool useSymbolAnnotations) + => TestAsync( + """ + namespace N + { + class C + { + } + } -namespace N.N1 -{ - class C1 - { - private N.C c; - } -}", + namespace N.N1 + { + class C1 + { + private N.C c; + } + } + """, + + """ + namespace N + { + class C + { + } + } -@"namespace N -{ - class C - { - } -} + namespace N.N1 + { + class C1 + { + private N.C c; + } + } + """, + + """ + namespace N + { + class C + { + } + } -namespace N.N1 -{ - class C1 - { - private C c; - } -}", useSymbolAnnotations); - } + namespace N.N1 + { + class C1 + { + private C c; + } + } + """, useSymbolAnnotations); [Theory, MemberData(nameof(TestAllData))] - public async Task TestImportNotAddedForReferencesMatchingNestedImports(bool useSymbolAnnotations) - { - await TestAsync( -@"namespace N -{ - using System.Collections.Generic; - - class C - { - private System.Collections.Generic.List F; - } -}", + public Task TestImportNotAddedForReferencesMatchingNestedImports(bool useSymbolAnnotations) + => TestAsync( + """ + namespace N + { + using System.Collections.Generic; + + class C + { + private System.Collections.Generic.List F; + } + } + """, -@"namespace N -{ - using System.Collections.Generic; + """ + namespace N + { + using System.Collections.Generic; - class C - { - private System.Collections.Generic.List F; - } -}", + class C + { + private System.Collections.Generic.List F; + } + } + """, -@"namespace N -{ - using System.Collections.Generic; + """ + namespace N + { + using System.Collections.Generic; - class C - { - private List F; - } -}", useSymbolAnnotations); - } + class C + { + private List F; + } + } + """, useSymbolAnnotations); [Theory, MemberData(nameof(TestAllData))] - public async Task TestImportRemovedIfItMakesReferenceAmbiguous(bool useSymbolAnnotations) - { - // this is not really an artifact of the AddImports feature, it is due - // to Simplifier not reducing the namespace reference because it would - // become ambiguous, thus leaving an unused using directive - await TestAsync( -@"namespace N -{ - class C - { - } -} + public Task TestImportRemovedIfItMakesReferenceAmbiguous(bool useSymbolAnnotations) + => TestAsync( + """ + namespace N + { + class C + { + } + } -class C -{ - public N.C F; -}", + class C + { + public N.C F; + } + """, -@"using N; + """ + using N; -namespace N -{ - class C - { - } -} + namespace N + { + class C + { + } + } -class C -{ - public N.C F; -}", + class C + { + public N.C F; + } + """, -@" -namespace N -{ - class C - { - } -} + """ -class C -{ - public N.C F; -}", useSymbolAnnotations); - } + namespace N + { + class C + { + } + } + + class C + { + public N.C F; + } + """, useSymbolAnnotations); [Theory, MemberData(nameof(TestAllData))] [WorkItem("https://github.com/dotnet/roslyn/issues/8797")] - public async Task TestBannerTextRemainsAtTopOfDocumentWithoutExistingImports(bool useSymbolAnnotations) - { - await TestAsync( -@"// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (C) MyOrgnaization 2016 -// -// -------------------------------------------------------------------------------------------------------------------- -class C -{ - public System.Collections.Generic.List F; -}", - -@"// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (C) MyOrgnaization 2016 -// -// -------------------------------------------------------------------------------------------------------------------- -using System.Collections.Generic; - -class C -{ - public System.Collections.Generic.List F; -}", - -@"// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (C) MyOrgnaization 2016 -// -// -------------------------------------------------------------------------------------------------------------------- -using System.Collections.Generic; - -class C -{ - public List F; -}", useSymbolAnnotations); - } + public Task TestBannerTextRemainsAtTopOfDocumentWithoutExistingImports(bool useSymbolAnnotations) + => TestAsync( + """ + // -------------------------------------------------------------------------------------------------------------------- + // + // Copyright (C) MyOrgnaization 2016 + // + // -------------------------------------------------------------------------------------------------------------------- + class C + { + public System.Collections.Generic.List F; + } + """, + + """ + // -------------------------------------------------------------------------------------------------------------------- + // + // Copyright (C) MyOrgnaization 2016 + // + // -------------------------------------------------------------------------------------------------------------------- + using System.Collections.Generic; + + class C + { + public System.Collections.Generic.List F; + } + """, + + """ + // -------------------------------------------------------------------------------------------------------------------- + // + // Copyright (C) MyOrgnaization 2016 + // + // -------------------------------------------------------------------------------------------------------------------- + using System.Collections.Generic; + + class C + { + public List F; + } + """, useSymbolAnnotations); [Theory, MemberData(nameof(TestAllData))] [WorkItem("https://github.com/dotnet/roslyn/issues/8797")] - public async Task TestBannerTextRemainsAtTopOfDocumentWithExistingImports(bool useSymbolAnnotations) - { - await TestAsync( -@"// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (C) MyOrgnaization 2016 -// -// -------------------------------------------------------------------------------------------------------------------- -using ZZZ; - -class C -{ - public System.Collections.Generic.List F; -}", - -@"// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (C) MyOrgnaization 2016 -// -// -------------------------------------------------------------------------------------------------------------------- -using System.Collections.Generic; -using ZZZ; - -class C -{ - public System.Collections.Generic.List F; -}", - -@"// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (C) MyOrgnaization 2016 -// -// -------------------------------------------------------------------------------------------------------------------- -using System.Collections.Generic; -using ZZZ; - -class C -{ - public List F; -}", useSymbolAnnotations); - } + public Task TestBannerTextRemainsAtTopOfDocumentWithExistingImports(bool useSymbolAnnotations) + => TestAsync( + """ + // -------------------------------------------------------------------------------------------------------------------- + // + // Copyright (C) MyOrgnaization 2016 + // + // -------------------------------------------------------------------------------------------------------------------- + using ZZZ; + + class C + { + public System.Collections.Generic.List F; + } + """, + + """ + // -------------------------------------------------------------------------------------------------------------------- + // + // Copyright (C) MyOrgnaization 2016 + // + // -------------------------------------------------------------------------------------------------------------------- + using System.Collections.Generic; + using ZZZ; + + class C + { + public System.Collections.Generic.List F; + } + """, + + """ + // -------------------------------------------------------------------------------------------------------------------- + // + // Copyright (C) MyOrgnaization 2016 + // + // -------------------------------------------------------------------------------------------------------------------- + using System.Collections.Generic; + using ZZZ; + + class C + { + public List F; + } + """, useSymbolAnnotations); [Theory, MemberData(nameof(TestAllData))] [WorkItem("https://github.com/dotnet/roslyn/issues/8797")] - public async Task TestLeadingWhitespaceLinesArePreserved(bool useSymbolAnnotations) - { - await TestAsync( -@"class C -{ - public System.Collections.Generic.List F; -}", - -@"using System.Collections.Generic; - -class C -{ - public System.Collections.Generic.List F; -}", - -@"using System.Collections.Generic; - -class C -{ - public List F; -}", useSymbolAnnotations); - } + public Task TestLeadingWhitespaceLinesArePreserved(bool useSymbolAnnotations) + => TestAsync( + """ + class C + { + public System.Collections.Generic.List F; + } + """, + + """ + using System.Collections.Generic; + + class C + { + public System.Collections.Generic.List F; + } + """, + + """ + using System.Collections.Generic; + + class C + { + public List F; + } + """, useSymbolAnnotations); [Theory, MemberData(nameof(TestAllData))] - public async Task TestImportAddedToNestedImports(bool useSymbolAnnotations) - { - await TestAsync( -@"namespace N -{ - using System; - - class C - { - private System.Collections.Generic.List F; - } -}", - -@"namespace N -{ - using System; - using System.Collections.Generic; - - class C - { - private System.Collections.Generic.List F; - } -}", - -@"namespace N -{ - using System; - using System.Collections.Generic; - - class C - { - private List F; - } -}", useSymbolAnnotations); - } + public Task TestImportAddedToNestedImports(bool useSymbolAnnotations) + => TestAsync( + """ + namespace N + { + using System; + + class C + { + private System.Collections.Generic.List F; + } + } + """, + + """ + namespace N + { + using System; + using System.Collections.Generic; + + class C + { + private System.Collections.Generic.List F; + } + } + """, + + """ + namespace N + { + using System; + using System.Collections.Generic; + + class C + { + private List F; + } + } + """, useSymbolAnnotations); [Theory, MemberData(nameof(TestAllData))] - public async Task TestImportNameNotSimplfied(bool useSymbolAnnotations) - { - await TestAsync( -@"namespace System -{ - using System.Threading; - - class C - { - private System.Collections.Generic.List F; - } -}", - -@"namespace System -{ - using System.Collections.Generic; - using System.Threading; - - class C - { - private System.Collections.Generic.List F; - } -}", - -@"namespace System -{ - using System.Collections.Generic; - using System.Threading; - - class C - { - private List F; - } -}", useSymbolAnnotations); - } + public Task TestImportNameNotSimplfied(bool useSymbolAnnotations) + => TestAsync( + """ + namespace System + { + using System.Threading; + + class C + { + private System.Collections.Generic.List F; + } + } + """, + + """ + namespace System + { + using System.Collections.Generic; + using System.Threading; + + class C + { + private System.Collections.Generic.List F; + } + } + """, + + """ + namespace System + { + using System.Collections.Generic; + using System.Threading; + + class C + { + private List F; + } + } + """, useSymbolAnnotations); [Theory, MemberData(nameof(TestAllData))] - public async Task TestUnnecessaryImportAddedAndRemoved(bool useSymbolAnnotations) - { - await TestAsync( -@"using List = System.Collections.Generic.List; - -namespace System -{ - class C - { - private List F; - } -}", - -@"using System.Collections.Generic; -using List = System.Collections.Generic.List; - -namespace System -{ - class C - { - private List F; - } -}", + public Task TestUnnecessaryImportAddedAndRemoved(bool useSymbolAnnotations) + => TestAsync( + """ + using List = System.Collections.Generic.List; + + namespace System + { + class C + { + private List F; + } + } + """, + + """ + using System.Collections.Generic; + using List = System.Collections.Generic.List; + + namespace System + { + class C + { + private List F; + } + } + """, -@"using List = System.Collections.Generic.List; + """ + using List = System.Collections.Generic.List; -namespace System -{ - class C - { - private List F; - } -}", useSymbolAnnotations); - } + namespace System + { + class C + { + private List F; + } + } + """, useSymbolAnnotations); [Theory, MemberData(nameof(TestAllData))] - public async Task TestImportAddedToStartOfDocumentIfNoNestedImports(bool useSymbolAnnotations) - { - await TestAsync( -@"namespace N -{ - class C - { - private System.Collections.Generic.List F; - } -}", + public Task TestImportAddedToStartOfDocumentIfNoNestedImports(bool useSymbolAnnotations) + => TestAsync( + """ + namespace N + { + class C + { + private System.Collections.Generic.List F; + } + } + """, -@"using System.Collections.Generic; + """ + using System.Collections.Generic; -namespace N -{ - class C - { - private System.Collections.Generic.List F; - } -}", + namespace N + { + class C + { + private System.Collections.Generic.List F; + } + } + """, -@"using System.Collections.Generic; + """ + using System.Collections.Generic; -namespace N -{ - class C - { - private List F; - } -}", useSymbolAnnotations); - } + namespace N + { + class C + { + private List F; + } + } + """, useSymbolAnnotations); [Theory, MemberData(nameof(TestAllData))] [WorkItem("https://github.com/dotnet/roslyn/issues/9228")] @@ -761,15 +834,17 @@ public async Task TestDoNotAddDuplicateImportIfNamespaceIsDefinedInSourceAndExte @"namespace N.M { public class A : System.Attribute { } }"; var code = -@"using System; -using N.M; + """ + using System; + using N.M; -class C -{ - public void M1(String p1) { } + class C + { + public void M1(String p1) { } - public void M2([A] String p2) { } -}"; + public void M2([A] String p2) { } + } + """; var otherAssemblyReference = GetInMemoryAssemblyReferenceForCode(externalCode); @@ -817,15 +892,17 @@ public void M2([A] String p2) { } var formatted = await Formatter.FormatAsync(imported, formattingOptions, CancellationToken.None); var actualText = (await formatted.GetTextAsync()).ToString(); - Assert.Equal(@"using System; -using N.M; + Assert.Equal(""" + using System; + using N.M; -class C -{ - public void M1([global::N.M.A] String p1) { } + class C + { + public void M1([global::N.M.A] String p1) { } - public void M2([A] String p2) { } -}", actualText); + public void M2([A] String p2) { } + } + """, actualText); } private static MetadataReference GetInMemoryAssemblyReferenceForCode(string code) @@ -843,482 +920,498 @@ private static MetadataReference GetInMemoryAssemblyReferenceForCode(string code #region AddImports Safe Tests [Fact] - public async Task TestSafeWithMatchingSimpleName() - { - await TestNoImportsAddedAsync( -@"using B; - -namespace A -{ - class C1 {} - class C2 {} -} - -namespace B -{ - class C1 {} -} - -class C -{ - C1 M(A.C2 c2) => default; -}", useSymbolAnnotations: true); - } + public Task TestSafeWithMatchingSimpleName() + => TestNoImportsAddedAsync( + """ + using B; + + namespace A + { + class C1 {} + class C2 {} + } + + namespace B + { + class C1 {} + } + + class C + { + C1 M(A.C2 c2) => default; + } + """, useSymbolAnnotations: true); [Fact] - public async Task TestSafeWithMatchingGenericName() - { - await TestNoImportsAddedAsync( -@"using B; - -namespace A -{ - class C1 {} - class C2 {} -} - -namespace B -{ - class C1 {} -} - -class C -{ - C1 M(A.C2 c2) => default; -}", useSymbolAnnotations: true); - } + public Task TestSafeWithMatchingGenericName() + => TestNoImportsAddedAsync( + """ + using B; + + namespace A + { + class C1 {} + class C2 {} + } + + namespace B + { + class C1 {} + } + + class C + { + C1 M(A.C2 c2) => default; + } + """, useSymbolAnnotations: true); [Fact] - public async Task TestSafeWithMatchingQualifiedName() - { - await TestNoImportsAddedAsync( -@"using B; - -namespace A -{ - class O {} - class C2 {} -} - -namespace B -{ - class O - { - public class C1 {} - } -} - -class C -{ - O.C1 M(A.C2 c2) => default; -}", useSymbolAnnotations: true); - } + public Task TestSafeWithMatchingQualifiedName() + => TestNoImportsAddedAsync( + """ + using B; + + namespace A + { + class O {} + class C2 {} + } + + namespace B + { + class O + { + public class C1 {} + } + } + + class C + { + O.C1 M(A.C2 c2) => default; + } + """, useSymbolAnnotations: true); [Fact] - public async Task TestSafeWithMatchingAliasedIdentifierName() - { - await TestNoImportsAddedAsync( -@"using C1 = B.C1; - -namespace A -{ - class C1 {} - class C2 {} -} - -namespace B -{ - class C1 {} -} - -namespace Inner -{ - class C - { - C1 M(A.C2 c2) => default; - } -}", useSymbolAnnotations: true); - } + public Task TestSafeWithMatchingAliasedIdentifierName() + => TestNoImportsAddedAsync( + """ + using C1 = B.C1; + + namespace A + { + class C1 {} + class C2 {} + } + + namespace B + { + class C1 {} + } + + namespace Inner + { + class C + { + C1 M(A.C2 c2) => default; + } + } + """, useSymbolAnnotations: true); [Fact] - public async Task TestSafeWithMatchingGenericNameAndTypeArguments() - { - await TestNoImportsAddedAsync( -@"using B; - -namespace A -{ - class C1 {} - class C2 {} - class C3 {} -} - -namespace B -{ - class C1 {} - class C3 {} -} - -class C -{ - C1 M(A.C2 c2) => default; -}", useSymbolAnnotations: true); - } + public Task TestSafeWithMatchingGenericNameAndTypeArguments() + => TestNoImportsAddedAsync( + """ + using B; + + namespace A + { + class C1 {} + class C2 {} + class C3 {} + } + + namespace B + { + class C1 {} + class C3 {} + } + + class C + { + C1 M(A.C2 c2) => default; + } + """, useSymbolAnnotations: true); [Fact] - public async Task TestSafeWithMatchingGenericNameAndTypeArguments_DifferentArity() - { - await TestAsync( -@"using B; - -namespace A -{ - class C1 {} - class C2 {} -} - -namespace B -{ - class C1 {} - class C3 {} -} - -class C -{ - C1 M(A.C2 c2) => default; -}", -@"using A; -using B; - -namespace A -{ - class C1 {} - class C2 {} -} - -namespace B -{ - class C1 {} - class C3 {} -} - -class C -{ - C1 M(A.C2 c2) => default; -}", -@"using A; -using B; - -namespace A -{ - class C1 {} - class C2 {} -} - -namespace B -{ - class C1 {} - class C3 {} -} - -class C -{ - C1 M(C2 c2) => default; -}", useSymbolAnnotations: true); - } + public Task TestSafeWithMatchingGenericNameAndTypeArguments_DifferentArity() + => TestAsync( + """ + using B; + + namespace A + { + class C1 {} + class C2 {} + } + + namespace B + { + class C1 {} + class C3 {} + } + + class C + { + C1 M(A.C2 c2) => default; + } + """, + """ + using A; + using B; + + namespace A + { + class C1 {} + class C2 {} + } + + namespace B + { + class C1 {} + class C3 {} + } + + class C + { + C1 M(A.C2 c2) => default; + } + """, + """ + using A; + using B; + + namespace A + { + class C1 {} + class C2 {} + } + + namespace B + { + class C1 {} + class C3 {} + } + + class C + { + C1 M(C2 c2) => default; + } + """, useSymbolAnnotations: true); [Fact] - public async Task TestSafeWithMatchingQualifiedNameAndTypeArguments() - { - await TestNoImportsAddedAsync( -@"using B; - -namespace A -{ - class O {} - class C2 {} - class C3 {} -} - -namespace B -{ - class C3 {} - class O - { - public class C1 {} - } -} - -class C -{ - O.C1 M(A.C2 c2) => default; -}", useSymbolAnnotations: true); - } + public Task TestSafeWithMatchingQualifiedNameAndTypeArguments() + => TestNoImportsAddedAsync( + """ + using B; + + namespace A + { + class O {} + class C2 {} + class C3 {} + } + + namespace B + { + class C3 {} + class O + { + public class C1 {} + } + } + + class C + { + O.C1 M(A.C2 c2) => default; + } + """, useSymbolAnnotations: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39641")] - public async Task TestSafeWithMatchingSimpleNameInAllLocations() - { - await TestNoImportsAddedAsync( -@"using B; -using System.Collections.Generic; + public Task TestSafeWithMatchingSimpleNameInAllLocations() + => TestNoImportsAddedAsync( + """ + using B; + using System.Collections.Generic; + + namespace A + { + class C1 { } + class C2 { } + } + + namespace B + { + class C1 + { + public static C1 P { get; } + } + } + + #nullable enable + #pragma warning disable + + class C + { + /// + /// + /// + C1 M(C1 c1, A.C2 c2) -namespace A -{ - class C1 { } - class C2 { } -} - -namespace B -{ - class C1 - { - public static C1 P { get; } - } -} - -#nullable enable -#pragma warning disable - -class C -{ - /// - /// - /// - C1 M(C1 c1, A.C2 c2) - - { - C1 result = (C1)c1 ?? new C1() ?? C1.P ?? new C1[0] { }[0] ?? new List()[0] ?? (C1?)null; - (C1 a, int b) = (default, default); - return result; - } -}", useSymbolAnnotations: true); - } + { + C1 result = (C1)c1 ?? new C1() ?? C1.P ?? new C1[0] { }[0] ?? new List()[0] ?? (C1?)null; + (C1 a, int b) = (default, default); + return result; + } + } + """, useSymbolAnnotations: true); [Fact] - public async Task TestSafeWithMatchingExtensionMethod() - { - await TestNoImportsAddedAsync( -@"using B; - -namespace A -{ - static class AExtensions - { - public static void M(this int a){} - } - public class C1 {} -} - -namespace B -{ - static class BExtensions - { - public static void M(this int a){} - } -} + public Task TestSafeWithMatchingExtensionMethod() + => TestNoImportsAddedAsync( + """ + using B; + + namespace A + { + static class AExtensions + { + public static void M(this int a){} + } + public class C1 {} + } + + namespace B + { + static class BExtensions + { + public static void M(this int a){} + } + } -class C -{ - void M(A.C1 c1) => 42.M(); -}", useSymbolAnnotations: true); - } + class C + { + void M(A.C1 c1) => 42.M(); + } + """, useSymbolAnnotations: true); [Fact] - public async Task TestSafeWithMatchingExtensionMethodAndArguments() - { - await TestNoImportsAddedAsync( -@"using B; - -namespace A -{ - static class AExtensions - { - public static void M(this int a, C2 c2){} - } - public class C1 {} - public class C2 {} -} - -namespace B -{ - static class BExtensions - { - public static void M(this int a, C2 c2){} - } - public class C2 {} -} + public Task TestSafeWithMatchingExtensionMethodAndArguments() + => TestNoImportsAddedAsync( + """ + using B; + + namespace A + { + static class AExtensions + { + public static void M(this int a, C2 c2){} + } + public class C1 {} + public class C2 {} + } + + namespace B + { + static class BExtensions + { + public static void M(this int a, C2 c2){} + } + public class C2 {} + } -class C -{ - void M(A.C1 c1) => 42.M(default(C2)); -}", useSymbolAnnotations: true); - } + class C + { + void M(A.C1 c1) => 42.M(default(C2)); + } + """, useSymbolAnnotations: true); [Fact] - public async Task TestSafeWithMatchingExtensionMethodAndTypeArguments() - { - await TestNoImportsAddedAsync( -@"using B; - -namespace A -{ - static class AExtensions - { - public static void M(this int a){} - } - public class C1 {} - public class C2 {} -} - -namespace B -{ - static class BExtensions - { - public static void M(this int a){} - } - public class C2 {} -} + public Task TestSafeWithMatchingExtensionMethodAndTypeArguments() + => TestNoImportsAddedAsync( + """ + using B; + + namespace A + { + static class AExtensions + { + public static void M(this int a){} + } + public class C1 {} + public class C2 {} + } + + namespace B + { + static class BExtensions + { + public static void M(this int a){} + } + public class C2 {} + } -class C -{ - void M(A.C1 c1) => 42.M(); -}", useSymbolAnnotations: true); - } + class C + { + void M(A.C1 c1) => 42.M(); + } + """, useSymbolAnnotations: true); [Fact] - public async Task TestSafeWithLambdaExtensionMethodAmbiguity() - { - await TestNoImportsAddedAsync( -@"using System; + public Task TestSafeWithLambdaExtensionMethodAmbiguity() + => TestNoImportsAddedAsync( + """ + using System; -class C -{ - // Don't add a using for N even though it is used here. - public N.Other x; + class C + { + // Don't add a using for N even though it is used here. + public N.Other x; - public static void Main() - { - M(x => x.M1()); - } + public static void Main() + { + M(x => x.M1()); + } - public static void M(Action a){} - public static void M(Action a){} + public static void M(Action a){} + public static void M(Action a){} - public void M1(){} -} + public void M1(){} + } -namespace N -{ - public class Other { } + namespace N + { + public class Other { } - public static class Extensions - { - public static void M1(this int a){} - } -}", useSymbolAnnotations: true); - } + public static class Extensions + { + public static void M1(this int a){} + } + } + """, useSymbolAnnotations: true); [Theory, MemberData(nameof(TestAllData))] [WorkItem("https://github.com/dotnet/roslyn/issues/55746")] - public async Task TestAddImport_InsideNamespace(bool useSymbolAnnotations) - { - await TestAsync( -@"namespace N -{ - class C - { - public System.Collections.Generic.List F; - } -}", + public Task TestAddImport_InsideNamespace(bool useSymbolAnnotations) + => TestAsync( + """ + namespace N + { + class C + { + public System.Collections.Generic.List F; + } + } + """, -@"namespace N -{ - using System.Collections.Generic; + """ + namespace N + { + using System.Collections.Generic; - class C - { - public System.Collections.Generic.List F; - } -}", + class C + { + public System.Collections.Generic.List F; + } + } + """, -@"namespace N -{ - using System.Collections.Generic; + """ + namespace N + { + using System.Collections.Generic; - class C - { - public List F; - } -}", useSymbolAnnotations, placeImportsInsideNamespaces: true); - } + class C + { + public List F; + } + } + """, useSymbolAnnotations, placeImportsInsideNamespaces: true); [Theory, MemberData(nameof(TestAllData))] [WorkItem("https://github.com/dotnet/roslyn/issues/55746")] - public async Task TestAddImport_InsideNamespace_NoNamespace(bool useSymbolAnnotations) - { - await TestAsync( -@"class C -{ - public System.Collections.Generic.List F; -}", - -@"using System.Collections.Generic; - -class C -{ - public System.Collections.Generic.List F; -}", - -@"using System.Collections.Generic; - -class C -{ - public List F; -}", useSymbolAnnotations, placeImportsInsideNamespaces: true); - } + public Task TestAddImport_InsideNamespace_NoNamespace(bool useSymbolAnnotations) + => TestAsync( + """ + class C + { + public System.Collections.Generic.List F; + } + """, + + """ + using System.Collections.Generic; + + class C + { + public System.Collections.Generic.List F; + } + """, + + """ + using System.Collections.Generic; + + class C + { + public List F; + } + """, useSymbolAnnotations, placeImportsInsideNamespaces: true); [Theory, MemberData(nameof(TestAllData))] [WorkItem("https://github.com/dotnet/roslyn/issues/55746")] - public async Task TestAddImport_InsideNamespace_MultipleNamespaces(bool useSymbolAnnotations) - { - await TestAsync( -@"namespace N1 -{ - namespace N2 - { - class C - { - public System.Collections.Generic.List F; - } - } -}", - -@"namespace N1 -{ - namespace N2 - { - using System.Collections.Generic; - - class C - { - public System.Collections.Generic.List F; - } - } -}", - -@"namespace N1 -{ - namespace N2 - { - using System.Collections.Generic; - - class C - { - public List F; - } - } -}", useSymbolAnnotations, placeImportsInsideNamespaces: true); - } + public Task TestAddImport_InsideNamespace_MultipleNamespaces(bool useSymbolAnnotations) + => TestAsync( + """ + namespace N1 + { + namespace N2 + { + class C + { + public System.Collections.Generic.List F; + } + } + } + """, + + """ + namespace N1 + { + namespace N2 + { + using System.Collections.Generic; + + class C + { + public System.Collections.Generic.List F; + } + } + } + """, + + """ + namespace N1 + { + namespace N2 + { + using System.Collections.Generic; + + class C + { + public List F; + } + } + } + """, useSymbolAnnotations, placeImportsInsideNamespaces: true); #endregion } diff --git a/src/Workspaces/CSharpTest/CodeGeneration/SymbolEditorTests.cs b/src/Workspaces/CSharpTest/CodeGeneration/SymbolEditorTests.cs index f6c7df4c1d3d7..5807144a09957 100644 --- a/src/Workspaces/CSharpTest/CodeGeneration/SymbolEditorTests.cs +++ b/src/Workspaces/CSharpTest/CodeGeneration/SymbolEditorTests.cs @@ -63,18 +63,11 @@ private static async Task GetActualAsync(Document document) public async Task TestEditOneDeclaration() { var code = -@"class C -{ -}"; - - var expected = -@"class C -{ - void m() - { - } -}"; - + """ + class C + { + } + """; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); @@ -84,29 +77,25 @@ void m() var actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected, actual); + Assert.Equal(""" + class C + { + void m() + { + } + } + """, actual); } [Fact] public async Task TestSequentialEdits() { var code = -@"class C -{ -}"; - - var expected = -@"class C -{ - void m() - { - } - - void m2() - { - } -}"; - + """ + class C + { + } + """; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); @@ -121,29 +110,29 @@ void m2() var actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected, actual); + Assert.Equal(""" + class C + { + void m() + { + } + + void m2() + { + } + } + """, actual); } [Fact] public async Task TestSequentialEdit_NewSymbols() { var code = -@"class C -{ -}"; - - var expected = -@"class C -{ - void m() - { - } - - void m2() - { - } -}"; - + """ + class C + { + } + """; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); @@ -158,36 +147,33 @@ void m2() var actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected, actual); + Assert.Equal(""" + class C + { + void m() + { + } + + void m2() + { + } + } + """, actual); } [Fact] public async Task TestSequentialEdits_SeparateSymbols() { var code = -@"class A -{ -} - -class B -{ -}"; - - var expected = -@"class A -{ - void ma() - { - } -} - -class B -{ - void mb() - { - } -}"; - + """ + class A + { + } + + class B + { + } + """; var solution = GetSolution(code); var comp = await solution.Projects.First().GetCompilationAsync(); var symbolA = comp.GlobalNamespace.GetMembers("A").First(); @@ -202,38 +188,39 @@ void mb() Assert.Equal(1, newSymbolB.GetMembers("mb").Length); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected, actual); + Assert.Equal(""" + class A + { + void ma() + { + } + } + + class B + { + void mb() + { + } + } + """, actual); } [Fact] public async Task TestSequentialEdits_SeparateSymbolsAndFiles() { var code1 = -@"class A -{ -}"; + """ + class A + { + } + """; var code2 = -@"class B -{ -}"; - - var expected1 = -@"class A -{ - void ma() - { - } -}"; - - var expected2 = -@"class B -{ - void mb() - { - } -}"; - + """ + class B + { + } + """; var solution = GetSolution(code1, code2); var comp = await solution.Projects.First().GetCompilationAsync(); var symbolA = comp.GlobalNamespace.GetMembers("A").First(); @@ -251,31 +238,37 @@ void mb() var actual1 = await GetActualAsync(docs[0]); var actual2 = await GetActualAsync(docs[1]); - Assert.Equal(expected1, actual1); - Assert.Equal(expected2, actual2); + Assert.Equal(""" + class A + { + void ma() + { + } + } + """, actual1); + Assert.Equal(""" + class B + { + void mb() + { + } + } + """, actual2); } [Fact] public async Task TestEditAllDeclarations_SameFile() { var code = -@"public partial class C -{ -} - -public partial class C -{ -}"; - - var expected = -@"internal partial class C -{ -} - -internal partial class C -{ -}"; - + """ + public partial class C + { + } + + public partial class C + { + } + """; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); @@ -284,34 +277,34 @@ internal partial class C var actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected, actual); + Assert.Equal(""" + internal partial class C + { + } + + internal partial class C + { + } + """, actual); } [Fact] public async Task TestEditAllDeclarations_MultipleFiles() { var code1 = -@"class C -{ -}"; + """ + class C + { + } + """; var code2 = -@"class C -{ - void M() {} -}"; - - var expected1 = -@"public class C -{ -}"; - - var expected2 = -@"public class C -{ - void M() {} -}"; - + """ + class C + { + void M() {} + } + """; var solution = GetSolution(code1, code2); var comp = await solution.Projects.First().GetCompilationAsync(); var symbol = comp.GlobalNamespace.GetMembers("C").First(); @@ -323,34 +316,32 @@ void M() {} var actual1 = await GetActualAsync(docs[0]); var actual2 = await GetActualAsync(docs[1]); - Assert.Equal(expected1, actual1); - Assert.Equal(expected2, actual2); + Assert.Equal(""" + public class C + { + } + """, actual1); + Assert.Equal(""" + public class C + { + void M() {} + } + """, actual2); } [Fact] public async Task TestEditDeclarationWithLocation_Last() { var code = -@"partial class C -{ -} - -partial class C -{ -}"; - - var expected = -@"partial class C -{ -} - -partial class C -{ - void m() - { - } -}"; - + """ + partial class C + { + } + + partial class C + { + } + """; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var location = symbol.Locations.Last(); @@ -361,33 +352,33 @@ void m() var actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected, actual); + Assert.Equal(""" + partial class C + { + } + + partial class C + { + void m() + { + } + } + """, actual); } [Fact] public async Task TestEditDeclarationWithLocation_First() { var code = -@"partial class C -{ -} - -partial class C -{ -}"; - - var expected = -@"partial class C -{ - void m() - { - } -} - -partial class C -{ -}"; - + """ + partial class C + { + } + + partial class C + { + } + """; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var location = symbol.Locations.First(); @@ -398,37 +389,33 @@ partial class C var actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected, actual); + Assert.Equal(""" + partial class C + { + void m() + { + } + } + + partial class C + { + } + """, actual); } [Fact] public async Task TestEditDeclarationWithLocation_SequentialEdits_SameLocation() { var code = -@"partial class C -{ -} - -partial class C -{ -}"; - - var expected = -@"partial class C -{ -} - -partial class C -{ - void m() - { - } - - void m2() - { - } -}"; - + """ + partial class C + { + } + + partial class C + { + } + """; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var location = symbol.Locations.Last(); @@ -444,37 +431,37 @@ void m2() var actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected, actual); + Assert.Equal(""" + partial class C + { + } + + partial class C + { + void m() + { + } + + void m2() + { + } + } + """, actual); } [Fact] public async Task TestEditDeclarationWithLocation_SequentialEdits_NewLocation() { var code = -@"partial class C -{ -} - -partial class C -{ -}"; - - var expected = -@"partial class C -{ -} - -partial class C -{ - void m() - { - } - - void m2() - { - } -}"; - + """ + partial class C + { + } + + partial class C + { + } + """; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var location = symbol.Locations.Last(); @@ -491,40 +478,40 @@ void m2() var actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected, actual); + Assert.Equal(""" + partial class C + { + } + + partial class C + { + void m() + { + } + + void m2() + { + } + } + """, actual); } [Fact] public async Task TestEditDeclarationWithMember() { var code = -@"partial class C -{ -} - -partial class C -{ - void m() - { - } -}"; - - var expected = -@"partial class C -{ -} - -partial class C -{ - void m() - { - } - - void m2() - { - } -}"; - + """ + partial class C + { + } + + partial class C + { + void m() + { + } + } + """; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); var member = symbol.GetMembers("m").First(); @@ -535,7 +522,22 @@ void m2() var actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected, actual); + Assert.Equal(""" + partial class C + { + } + + partial class C + { + void m() + { + } + + void m2() + { + } + } + """, actual); } [Fact] @@ -543,15 +545,11 @@ public async Task TestChangeLogicalIdentityReturnsCorrectSymbol_OneDeclaration() { // proves that APIs return the correct new symbol even after a change that changes the symbol's logical identity. var code = -@"class C -{ -}"; - - var expected = -@"class X -{ -}"; - + """ + class C + { + } + """; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); @@ -565,7 +563,11 @@ public async Task TestChangeLogicalIdentityReturnsCorrectSymbol_OneDeclaration() var actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected, actual); + Assert.Equal(""" + class X + { + } + """, actual); } [Fact] @@ -573,22 +575,15 @@ public async Task TestChangeLogicalIdentityReturnsCorrectSymbol_AllDeclarations( { // proves that APIs return the correct new symbol even after a change that changes the symbol's logical identity. var code = -@"partial class C -{ -} - -partial class C -{ -}"; - - var expected = -@"partial class X -{ -} - -partial class X -{ -}"; + """ + partial class C + { + } + + partial class C + { + } + """; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); @@ -602,20 +597,26 @@ partial class X var actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected, actual); + Assert.Equal(""" + partial class X + { + } + + partial class X + { + } + """, actual); } [Fact] public async Task TestRemovedDeclarationReturnsNull() { var code = -@"class C -{ -}"; - - var expected = -@""; - + """ + class C + { + } + """; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); @@ -625,27 +626,22 @@ public async Task TestRemovedDeclarationReturnsNull() var actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected, actual); + Assert.Equal(@"", actual); } [Fact] public async Task TestRemovedOneOfManyDeclarationsReturnsChangedSymbol() { var code = -@"partial class C -{ -} - -partial class C -{ -}"; - - var expected = -@" -partial class C -{ -}"; - + """ + partial class C + { + } + + partial class C + { + } + """; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); @@ -656,25 +652,27 @@ partial class C var actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected, actual); + Assert.Equal(""" + + partial class C + { + } + """, actual); } [Fact] public async Task TestRemoveAllOfManyDeclarationsReturnsNull() { var code = -@"partial class C -{ -} - -partial class C -{ -}"; - - var expected = -@" -"; - + """ + partial class C + { + } + + partial class C + { + } + """; var solution = GetSolution(code); var symbol = (await GetSymbolsAsync(solution, "C")).First(); var editor = SymbolEditor.Create(solution); @@ -684,29 +682,22 @@ partial class C var actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected, actual); + Assert.Equal(""" + + + """, actual); } [Fact] public async Task TestRemoveFieldFromMultiFieldDeclaration() { var code = -@"class C -{ - public int X, Y; -}"; - - var expected = -@"class C -{ - public int Y; -}"; - - var expected2 = -@"class C -{ -}"; - + """ + class C + { + public int X, Y; + } + """; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); var symbolX = symbol.GetMembers("X").First(); @@ -719,45 +710,42 @@ public async Task TestRemoveFieldFromMultiFieldDeclaration() Assert.Null(newSymbolX); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected, actual); + Assert.Equal(""" + class C + { + public int Y; + } + """, actual); // now remove Y -- should remove entire remaining field declaration var newSymbolY = (INamedTypeSymbol)await editor.EditOneDeclarationAsync(symbolY, (e, d) => e.RemoveNode(d)); Assert.Null(newSymbolY); actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected2, actual); + Assert.Equal(""" + class C + { + } + """, actual); } [Fact] public async Task TestSetBaseType_ExistingBase() { var code = -@"class C : B -{ -} - -class A -{ -} - -class B -{ -}"; - - var expected = -@"class C : A -{ -} - -class A -{ -} - -class B -{ -}"; - + """ + class C : B + { + } + + class A + { + } + + class B + { + } + """; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); @@ -767,38 +755,38 @@ class B var newSymbolC = await editor.SetBaseTypeAsync(symbol, g => g.IdentifierName("A")); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected, actual); + Assert.Equal(""" + class C : A + { + } + + class A + { + } + + class B + { + } + """, actual); } [Fact] public async Task TestSetBaseType_ExistingInterface() { var code = -@"class C : I -{ -} - -class A -{ -} - -interface I -{ -}"; - - var expected = -@"class C : A, I -{ -} - -class A -{ -} - -interface I -{ -}"; - + """ + class C : I + { + } + + class A + { + } + + interface I + { + } + """; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); @@ -808,30 +796,34 @@ interface I var newSymbolC = await editor.SetBaseTypeAsync(symbol, g => g.IdentifierName("A")); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected, actual); + Assert.Equal(""" + class C : A, I + { + } + + class A + { + } + + interface I + { + } + """, actual); } [Fact] public async Task TestSetBaseType_NoBaseOrInterface() { var code = -@"class C -{ -} - -class A -{ -}"; - - var expected = -@"class C : A -{ -} - -class A -{ -}"; - + """ + class C + { + } + + class A + { + } + """; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); @@ -841,30 +833,30 @@ class A var newSymbolC = await editor.SetBaseTypeAsync(symbol, g => g.IdentifierName("A")); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected, actual); + Assert.Equal(""" + class C : A + { + } + + class A + { + } + """, actual); } [Fact] public async Task TestSetBaseType_UnknownBase() { var code = -@"class C : X -{ -} - -class A -{ -}"; - - var expected = -@"class C : A -{ -} - -class A -{ -}"; - + """ + class C : X + { + } + + class A + { + } + """; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); @@ -874,30 +866,30 @@ class A var newSymbolC = editor.SetBaseTypeAsync(symbol, g => g.IdentifierName("A")); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected, actual); + Assert.Equal(""" + class C : A + { + } + + class A + { + } + """, actual); } [Fact] public async Task TestSetBaseType_Null_ExistingBase() { var code = -@"class C : A -{ -} - -class A -{ -}"; - - var expected = -@"class C -{ -} - -class A -{ -}"; - + """ + class C : A + { + } + + class A + { + } + """; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); @@ -907,38 +899,34 @@ class A var newSymbolC = await editor.SetBaseTypeAsync(symbol, g => null); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected, actual); + Assert.Equal(""" + class C + { + } + + class A + { + } + """, actual); } [Fact] public async Task TestSetBaseType_Null_ExistingBaseAndInterface() { var code = -@"class C : A, I -{ -} - -class A -{ -} - -interface I -{ -}"; - - var expected = -@"class C : I -{ -} - -class A -{ -} - -interface I -{ -}"; - + """ + class C : A, I + { + } + + class A + { + } + + interface I + { + } + """; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); @@ -948,30 +936,34 @@ interface I var newSymbolC = await editor.SetBaseTypeAsync(symbol, g => null); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected, actual); + Assert.Equal(""" + class C : I + { + } + + class A + { + } + + interface I + { + } + """, actual); } [Fact] public async Task TestSetBaseType_Null_ExistingInterface() { var code = -@"class C : I -{ -} - -interface I -{ -}"; - - var expected = -@"class C : I -{ -} - -interface I -{ -}"; - + """ + class C : I + { + } + + interface I + { + } + """; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); @@ -981,22 +973,26 @@ interface I var newSymbolC = await editor.SetBaseTypeAsync(symbol, g => null); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected, actual); + Assert.Equal(""" + class C : I + { + } + + interface I + { + } + """, actual); } [Fact] public async Task TestSetBaseType_Null_UnknownBase() { var code = -@"class C : X -{ -}"; - - var expected = -@"class C -{ -}"; - + """ + class C : X + { + } + """; var solution = GetSolution(code); var symbol = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); @@ -1006,28 +1002,34 @@ public async Task TestSetBaseType_Null_UnknownBase() var newSymbolC = await editor.SetBaseTypeAsync(symbol, g => null); var actual = await GetActualAsync(editor.GetChangedDocuments().First()); - Assert.Equal(expected, actual); + Assert.Equal(""" + class C + { + } + """, actual); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2650")] public async Task TestEditExplicitInterfaceIndexer() { var code = -@"public interface I -{ - int this[int item] { get; } -} - -public class C : I -{ - int I.this[int item] - { - get - { - return item; - } - } -}"; + """ + public interface I + { + int this[int item] { get; } + } + + public class C : I + { + int I.this[int item] + { + get + { + return item; + } + } + } + """; var solution = GetSolution(code); var typeC = (INamedTypeSymbol)(await GetSymbolsAsync(solution, "C")).First(); diff --git a/src/Workspaces/CSharpTest/CodeGeneration/SyntaxGeneratorTests.cs b/src/Workspaces/CSharpTest/CodeGeneration/SyntaxGeneratorTests.cs index b07288e1ec865..00f9b96b90efe 100644 --- a/src/Workspaces/CSharpTest/CodeGeneration/SyntaxGeneratorTests.cs +++ b/src/Workspaces/CSharpTest/CodeGeneration/SyntaxGeneratorTests.cs @@ -118,8 +118,12 @@ public void TestLiteralExpressions() VerifySyntax(Generator.LiteralExpression('c'), "'c'"); - VerifySyntax(Generator.LiteralExpression("str"), "\"str\""); - VerifySyntax(Generator.LiteralExpression("s\"t\"r"), "\"s\\\"t\\\"r\""); + VerifySyntax(Generator.LiteralExpression("str"), """ + "str" + """); + VerifySyntax(Generator.LiteralExpression("s\"t\"r"), """ + "s\"t\"r" + """); VerifySyntax(Generator.LiteralExpression(true), "true"); VerifySyntax(Generator.LiteralExpression(false), "false"); @@ -167,57 +171,75 @@ public void TestByteLiteralExpressions() public void TestAttributeData() { VerifySyntax(Generator.Attribute(GetAttributeData( -@"using System; -public class MyAttribute : Attribute { }", + """ + using System; + public class MyAttribute : Attribute { } + """, @"[MyAttribute]")), @"[global::MyAttribute]"); VerifySyntax(Generator.Attribute(GetAttributeData( -@"using System; -public class MyAttribute : Attribute { public MyAttribute(object value) { } }", + """ + using System; + public class MyAttribute : Attribute { public MyAttribute(object value) { } } + """, @"[MyAttribute(null)]")), @"[global::MyAttribute(null)]"); VerifySyntax(Generator.Attribute(GetAttributeData( -@"using System; -public class MyAttribute : Attribute { public MyAttribute(int value) { } }", + """ + using System; + public class MyAttribute : Attribute { public MyAttribute(int value) { } } + """, @"[MyAttribute(123)]")), @"[global::MyAttribute(123)]"); VerifySyntax(Generator.Attribute(GetAttributeData( -@"using System; -public class MyAttribute : Attribute { public MyAttribute(double value) { } }", + """ + using System; + public class MyAttribute : Attribute { public MyAttribute(double value) { } } + """, @"[MyAttribute(12.3)]")), @"[global::MyAttribute(12.3)]"); VerifySyntax(Generator.Attribute(GetAttributeData( -@"using System; -public class MyAttribute : Attribute { public MyAttribute(string value) { } }", + """ + using System; + public class MyAttribute : Attribute { public MyAttribute(string value) { } } + """, @"[MyAttribute(""value"")]")), @"[global::MyAttribute(""value"")]"); VerifySyntax(Generator.Attribute(GetAttributeData( -@"using System; -public enum E { A, B, C } -public class MyAttribute : Attribute { public MyAttribute(E value) { } }", + """ + using System; + public enum E { A, B, C } + public class MyAttribute : Attribute { public MyAttribute(E value) { } } + """, @"[MyAttribute(E.A)]")), @"[global::MyAttribute(global::E.A)]"); VerifySyntax(Generator.Attribute(GetAttributeData( -@"using System; -public class MyAttribute : Attribute { public MyAttribute(Type value) { } }", + """ + using System; + public class MyAttribute : Attribute { public MyAttribute(Type value) { } } + """, @"[MyAttribute(typeof (MyAttribute))]")), @"[global::MyAttribute(typeof(global::MyAttribute))]"); VerifySyntax(Generator.Attribute(GetAttributeData( -@"using System; -public class MyAttribute : Attribute { public MyAttribute(int[] values) { } }", + """ + using System; + public class MyAttribute : Attribute { public MyAttribute(int[] values) { } } + """, @"[MyAttribute(new [] {1, 2, 3})]")), @"[global::MyAttribute(new[] { 1, 2, 3 })]"); VerifySyntax(Generator.Attribute(GetAttributeData( -@"using System; -public class MyAttribute : Attribute { public int Value {get; set;} }", + """ + using System; + public class MyAttribute : Attribute { public int Value {get; set;} } + """, @"[MyAttribute(Value = 123)]")), @"[global::MyAttribute(Value = 123)]"); @@ -842,7 +864,7 @@ public void TestMethodDeclarations() "partial void m()\r\n{\r\n y;\r\n}"); VerifySyntax( - Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Partial | DeclarationModifiers.Async, statements: null), + Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Partial | DeclarationModifiers.Async, statements: null), "partial void m();"); } @@ -1592,11 +1614,12 @@ public void TestAsPrivateInterfaceImplementation() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/3928")] public void TestAsPrivateInterfaceImplementationRemovesConstraints() { - var code = @" -public interface IFace -{ - void Method() where T : class; -}"; + var code = """ + public interface IFace + { + void Method() where T : class; + } + """; var cu = ParseCompilationUnit(code); var iface = cu.Members[0]; @@ -2062,8 +2085,10 @@ private void CheckAddRemoveAttribute(SyntaxNode declaration) [Fact] public void TestAddRemoveAttributesPerservesTrivia() { - var cls = ParseCompilationUnit(@"// comment -public class C { } // end").Members[0]; + var cls = ParseCompilationUnit(""" + // comment + public class C { } // end + """).Members[0]; var added = Generator.AddAttributes(cls, Generator.Attribute("a")); VerifySyntax(added, "// comment\r\n[a]\r\npublic class C\r\n{\r\n} // end\r\n"); @@ -2236,10 +2261,12 @@ public void TestInterfaceDeclarationWithEventFromSymbol() { VerifySyntax( Generator.Declaration(_emptyCompilation.GetTypeByMetadataName("System.ComponentModel.INotifyPropertyChanged")), -@"public interface INotifyPropertyChanged -{ - event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged; -}"); + """ + public interface INotifyPropertyChanged + { + event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged; + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38379")] @@ -2248,9 +2275,11 @@ public void TestUnsafeFieldDeclarationFromSymbol() VerifySyntax( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.IntPtr").GetMembers("ToPointer").Single()), -@"public unsafe void* ToPointer() -{ -}"); + """ + public unsafe void* ToPointer() + { + } + """); } [Fact] @@ -2259,12 +2288,14 @@ public void TestEnumDeclarationFromSymbol() VerifySyntax( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.DateTimeKind")), -@"public enum DateTimeKind -{ - Unspecified = 0, - Utc = 1, - Local = 2 -}"); + """ + public enum DateTimeKind + { + Unspecified = 0, + Utc = 1, + Local = 2 + } + """); } [Fact] @@ -2273,12 +2304,14 @@ public void TestEnumWithUnderlyingTypeFromSymbol() VerifySyntax( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.Security.SecurityRuleSet")), -@"public enum SecurityRuleSet : byte -{ - None = 0, - Level1 = 1, - Level2 = 2 -}"); + """ + public enum SecurityRuleSet : byte + { + None = 0, + Level1 = 1, + Level2 = 2 + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66381")] @@ -2733,11 +2766,12 @@ private void TestRemoveNamespaceImport(SyntaxNode declaration, string name, stri [Fact] public void TestRemoveNodeInTrivia() { - var code = @" -/// ... -public class C -{ -}"; + var code = """ + /// ... + public class C + { + } + """; var cu = ParseCompilationUnit(code); var cls = cu.Members[0]; @@ -2747,21 +2781,23 @@ public class C VerifySyntaxRaw( newCu, - @" + """ -public class C -{ -}"); + public class C + { + } + """); } [Fact] public void TestReplaceNodeInTrivia() { - var code = @" -/// ... -public class C -{ -}"; + var code = """ + /// ... + public class C + { + } + """; var cu = ParseCompilationUnit(code); var cls = cu.Members[0]; @@ -2772,21 +2808,23 @@ public class C var newCu = Generator.ReplaceNode(cu, summary, summary2); VerifySyntaxRaw( - newCu, @" -/// -public class C -{ -}"); + newCu, """ + /// + public class C + { + } + """); } [Fact] public void TestInsertAfterNodeInTrivia() { - var code = @" -/// ... -public class C -{ -}"; + var code = """ + /// ... + public class C + { + } + """; var cu = ParseCompilationUnit(code); var cls = cu.Members[0]; @@ -2795,21 +2833,23 @@ public class C var newCu = Generator.InsertNodesAfter(cu, text, [text]); VerifySyntaxRaw( - newCu, @" -/// ... ... -public class C -{ -}"); + newCu, """ + /// ... ... + public class C + { + } + """); } [Fact] public void TestInsertBeforeNodeInTrivia() { - var code = @" -/// ... -public class C -{ -}"; + var code = """ + /// ... + public class C + { + } + """; var cu = ParseCompilationUnit(code); var cls = cu.Members[0]; @@ -2818,11 +2858,12 @@ public class C var newCu = Generator.InsertNodesBefore(cu, text, [text]); VerifySyntaxRaw( - newCu, @" -/// ... ... -public class C -{ -}"); + newCu, """ + /// ... ... + public class C + { + } + """); } [Fact] @@ -3180,28 +3221,36 @@ public void TestWithModifiers_AllowedModifiers() public void TestAddPublicToStaticConstructor() { var ctor = Generator.ConstructorDeclaration("C", modifiers: DeclarationModifiers.Static); - VerifySyntax(ctor, @"static C() -{ -}"); + VerifySyntax(ctor, """ + static C() + { + } + """); var publicCtor = Generator.WithAccessibility(ctor, Accessibility.Public); - VerifySyntax(publicCtor, @"public C() -{ -}"); + VerifySyntax(publicCtor, """ + public C() + { + } + """); } [Fact] public void TestAddStaticToPublicConstructor() { var ctor = Generator.ConstructorDeclaration("C", accessibility: Accessibility.Public); - VerifySyntax(ctor, @"public C() -{ -}"); + VerifySyntax(ctor, """ + public C() + { + } + """); var staticCtor = Generator.WithModifiers(ctor, DeclarationModifiers.Static); - VerifySyntax(staticCtor, @"static C() -{ -}"); + VerifySyntax(staticCtor, """ + static C() + { + } + """); } [Fact] @@ -3209,9 +3258,11 @@ public void TestAddAbstractToFileClass() { var fileClass = (ClassDeclarationSyntax)ParseMemberDeclaration("file class C { }"); var fileAbstractClass = Generator.WithModifiers(fileClass, Generator.GetModifiers(fileClass).WithIsAbstract(true)); - VerifySyntax(fileAbstractClass, @"file abstract class C -{ -}"); + VerifySyntax(fileAbstractClass, """ + file abstract class C + { + } + """); } [Fact] @@ -3219,9 +3270,11 @@ public void TestAddPublicToFileClass() { var fileClass = (ClassDeclarationSyntax)ParseMemberDeclaration("file class C { }"); var filePublicClass = Generator.WithAccessibility(fileClass, Accessibility.Public); - VerifySyntax(filePublicClass, @"public class C -{ -}"); + VerifySyntax(filePublicClass, """ + public class C + { + } + """); } [Fact] @@ -3229,9 +3282,11 @@ public void TestAddFileModifierToAbstractClass() { var abstractClass = (ClassDeclarationSyntax)ParseMemberDeclaration("abstract class C { }"); var fileAbstractClass = Generator.WithModifiers(abstractClass, Generator.GetModifiers(abstractClass).WithIsFile(true)); - VerifySyntax(fileAbstractClass, @"file abstract class C -{ -}"); + VerifySyntax(fileAbstractClass, """ + file abstract class C + { + } + """); } [Fact] @@ -3239,9 +3294,11 @@ public void TestAddFileModifierToPublicClass() { var publicClass = (ClassDeclarationSyntax)ParseMemberDeclaration("public class C { }"); var filePublicClass = Generator.WithModifiers(publicClass, Generator.GetModifiers(publicClass).WithIsFile(true)); - VerifySyntax(filePublicClass, @"file class C -{ -}"); + VerifySyntax(filePublicClass, """ + file class C + { + } + """); } [Fact] @@ -3466,9 +3523,11 @@ public void TestAccessorDeclarations() var newNewGetAccessor = Generator.WithStatements(newGetAccessor, []); VerifySyntax(newNewGetAccessor, -@"get -{ -}"); + """ + get + { + } + """); // change accessors var newProp = Generator.ReplaceNode(prop, getAccessor, Generator.WithAccessibility(getAccessor, Accessibility.Public)); @@ -3523,11 +3582,13 @@ public void TestAccessorDeclarations2() public void TestAccessorsOnSpecialProperties() { var root = ParseCompilationUnit( -@"class C -{ - public int X { get; set; } = 100; - public int Y => 300; -}"); + """ + class C + { + public int X { get; set; } = 100; + public int Y => 300; + } + """); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; @@ -3544,11 +3605,13 @@ public void TestAccessorsOnSpecialProperties() public void TestAccessorsOnSpecialIndexers() { var root = ParseCompilationUnit( -@"class C -{ - public int this[int p] { get { return p * 10; } set { } }; - public int this[int p] => p * 10; -}"); + """ + class C + { + public int this[int p] { get { return p * 10; } set { } }; + public int this[int p] => p * 10; + } + """); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; @@ -3566,12 +3629,14 @@ public void TestExpressionsOnSpecialProperties() { // you can get/set expression from both expression value property and initialized properties var root = ParseCompilationUnit( -@"class C -{ - public int X { get; set; } = 100; - public int Y => 300; - public int Z { get; set; } -}"); + """ + class C + { + public int X { get; set; } = 100; + public int Y => 300; + public int Z { get; set; } + } + """); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; var z = Generator.GetMembers(root.Members[0])[2]; @@ -3592,11 +3657,13 @@ public void TestExpressionsOnSpecialIndexers() { // you can get/set expression from both expression value property and initialized properties var root = ParseCompilationUnit( -@"class C -{ - public int this[int p] { get { return p * 10; } set { } }; - public int this[int p] => p * 10; -}"); + """ + class C + { + public int this[int p] { get { return p * 10; } set { } }; + public int this[int p] => p * 10; + } + """); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; @@ -3717,9 +3784,11 @@ public void TestWithAccessorStatements() public void TestGetBaseAndInterfaceTypes() { var classBI = ParseCompilationUnit( -@"class C : B, I -{ -}").Members[0]; + """ + class C : B, I + { + } + """).Members[0]; var baseListBI = Generator.GetBaseAndInterfaceTypes(classBI); Assert.NotNull(baseListBI); @@ -3728,9 +3797,11 @@ public void TestGetBaseAndInterfaceTypes() Assert.Equal("I", baseListBI[1].ToString()); var classB = ParseCompilationUnit( -@"class C : B -{ -}").Members[0]; + """ + class C : B + { + } + """).Members[0]; var baseListB = Generator.GetBaseAndInterfaceTypes(classB); Assert.NotNull(baseListB); @@ -3738,9 +3809,11 @@ public void TestGetBaseAndInterfaceTypes() Assert.Equal("B", baseListB[0].ToString()); var classN = ParseCompilationUnit( -@"class C -{ -}").Members[0]; + """ + class C + { + } + """).Members[0]; var baseListN = Generator.GetBaseAndInterfaceTypes(classN); Assert.NotNull(baseListN); @@ -3751,115 +3824,149 @@ public void TestGetBaseAndInterfaceTypes() public void TestRemoveBaseAndInterfaceTypes() { var classBI = ParseCompilationUnit( -@"class C : B, I -{ -}").Members[0]; + """ + class C : B, I + { + } + """).Members[0]; var baseListBI = Generator.GetBaseAndInterfaceTypes(classBI); Assert.NotNull(baseListBI); VerifySyntax( Generator.RemoveNode(classBI, baseListBI[0]), -@"class C : I -{ -}"); + """ + class C : I + { + } + """); VerifySyntax( Generator.RemoveNode(classBI, baseListBI[1]), -@"class C : B -{ -}"); + """ + class C : B + { + } + """); VerifySyntax( Generator.RemoveNodes(classBI, baseListBI), -@"class C -{ -}"); + """ + class C + { + } + """); } [Fact] public void TestAddBaseType() { var classC = ParseCompilationUnit( -@"class C -{ -}").Members[0]; + """ + class C + { + } + """).Members[0]; var classCI = ParseCompilationUnit( -@"class C : I -{ -}").Members[0]; + """ + class C : I + { + } + """).Members[0]; var classCB = ParseCompilationUnit( -@"class C : B -{ -}").Members[0]; + """ + class C : B + { + } + """).Members[0]; VerifySyntax( Generator.AddBaseType(classC, Generator.IdentifierName("T")), -@"class C : T -{ -}"); + """ + class C : T + { + } + """); VerifySyntax( Generator.AddBaseType(classCI, Generator.IdentifierName("T")), -@"class C : T, I -{ -}"); + """ + class C : T, I + { + } + """); // TODO: find way to avoid this VerifySyntax( Generator.AddBaseType(classCB, Generator.IdentifierName("T")), -@"class C : T, B -{ -}"); + """ + class C : T, B + { + } + """); } [Fact] public void TestAddInterfaceTypes() { var classC = ParseCompilationUnit( -@"class C -{ -}").Members[0]; + """ + class C + { + } + """).Members[0]; var classCI = ParseCompilationUnit( -@"class C : I -{ -}").Members[0]; + """ + class C : I + { + } + """).Members[0]; var classCB = ParseCompilationUnit( -@"class C : B -{ -}").Members[0]; + """ + class C : B + { + } + """).Members[0]; VerifySyntax( Generator.AddInterfaceType(classC, Generator.IdentifierName("T")), -@"class C : T -{ -}"); + """ + class C : T + { + } + """); VerifySyntax( Generator.AddInterfaceType(classCI, Generator.IdentifierName("T")), -@"class C : I, T -{ -}"); + """ + class C : I, T + { + } + """); VerifySyntax( Generator.AddInterfaceType(classCB, Generator.IdentifierName("T")), -@"class C : B, T -{ -}"); + """ + class C : B, T + { + } + """); } [Fact] public void TestMultiFieldDeclarations() { var comp = Compile( -@"public class C -{ - public static int X, Y, Z; -}"); + """ + public class C + { + public static int X, Y, Z; + } + """); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var symbolX = (IFieldSymbol)symbolC.GetMembers("X").First(); @@ -3932,105 +4039,131 @@ public void TestMultiFieldDeclarations() VerifySyntax( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), -@"public class C -{ - T A; - public static int X, Y, Z; -}"); + """ + public class C + { + T A; + public static int X, Y, Z; + } + """); VerifySyntax( Generator.InsertMembers(declC, 1, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), -@"public class C -{ - public static int X; - T A; - public static int Y, Z; -}"); + """ + public class C + { + public static int X; + T A; + public static int Y, Z; + } + """); VerifySyntax( Generator.InsertMembers(declC, 2, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), -@"public class C -{ - public static int X, Y; - T A; - public static int Z; -}"); + """ + public class C + { + public static int X, Y; + T A; + public static int Z; + } + """); VerifySyntax( Generator.InsertMembers(declC, 3, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), -@"public class C -{ - public static int X, Y, Z; - T A; -}"); + """ + public class C + { + public static int X, Y, Z; + T A; + } + """); VerifySyntax( Generator.ClassDeclaration("C", members: [declX, declY]), -@"class C -{ - public static int X; - public static int Y; -}"); + """ + class C + { + public static int X; + public static int Y; + } + """); VerifySyntax( Generator.ReplaceNode(declC, declX, xTypedT), -@"public class C -{ - public static T X; - public static int Y, Z; -}"); - + """ + public class C + { + public static T X; + public static int Y, Z; + } + """); + VerifySyntax( Generator.ReplaceNode(declC, declY, Generator.WithType(declY, Generator.IdentifierName("T"))), -@"public class C -{ - public static int X; - public static T Y; - public static int Z; -}"); + """ + public class C + { + public static int X; + public static T Y; + public static int Z; + } + """); VerifySyntax( Generator.ReplaceNode(declC, declZ, Generator.WithType(declZ, Generator.IdentifierName("T"))), -@"public class C -{ - public static int X, Y; - public static T Z; -}"); + """ + public class C + { + public static int X, Y; + public static T Z; + } + """); VerifySyntax( Generator.ReplaceNode(declC, declX, Generator.WithAccessibility(declX, Accessibility.Private)), -@"public class C -{ - private static int X; - public static int Y, Z; -}"); + """ + public class C + { + private static int X; + public static int Y, Z; + } + """); VerifySyntax( Generator.ReplaceNode(declC, declX, Generator.WithModifiers(declX, DeclarationModifiers.None)), -@"public class C -{ - public int X; - public static int Y, Z; -}"); + """ + public class C + { + public int X; + public static int Y, Z; + } + """); VerifySyntax( Generator.ReplaceNode(declC, declX, Generator.WithName(declX, "Q")), -@"public class C -{ - public static int Q, Y, Z; -}"); + """ + public class C + { + public static int Q, Y, Z; + } + """); VerifySyntax( Generator.ReplaceNode(declC, declX.GetAncestorOrThis(), VariableDeclarator("Q")), -@"public class C -{ - public static int Q, Y, Z; -}"); + """ + public class C + { + public static int Q, Y, Z; + } + """); VerifySyntax( Generator.ReplaceNode(declC, declX, Generator.WithExpression(declX, Generator.IdentifierName("e"))), -@"public class C -{ - public static int X = e, Y, Z; -}"); + """ + public class C + { + public static int X = e, Y, Z; + } + """); } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/48789")] @@ -4039,44 +4172,51 @@ public void TestMultiFieldDeclarations() public void TestInsertMembersOnRecord_SemiColon(string typeKind) { var comp = Compile( -$@"public {typeKind} C; -"); + $""" + public {typeKind} C; + """); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), -$@"public {typeKind} C -{{ - T A; -}}"); + $$""" + public {{typeKind}} C + { + T A; + } + """); } [Fact] public void TestInsertMembersOnClass_SemiColon() { var comp = Compile( -$@"public class C; -"); + $""" + public class C; + """); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), -$@"public class C -{{ - T A; -}}"); + $$""" + public class C + { + T A; + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecordStruct_SemiColon() { var src = -@"public record struct C; -"; + """ + public record struct C; + """; var comp = CSharpCompilation.Create("test") .AddReferences(NetFramework.mscorlib) .AddSyntaxTrees(ParseSyntaxTree(src, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview))); @@ -4086,128 +4226,150 @@ public void TestInsertMembersOnRecordStruct_SemiColon() VerifySyntax( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), -@"public record struct C -{ - T A; -}"); + """ + public record struct C + { + T A; + } + """); } [Fact] public void TestInsertMembersOnStruct_SemiColon() { var comp = Compile( -$@"public struct C; -"); + $""" + public struct C; + """); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), -$@"public struct C -{{ - T A; -}}"); + $$""" + public struct C + { + T A; + } + """); } [Fact] public void TestInsertMembersOnInterface_SemiColon_01() { var comp = Compile( -$@"public interface C; -"); + $""" + public interface C; + """); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax( Generator.InsertMembers(declC, 0, Generator.PropertyDeclaration("A", Generator.IdentifierName("T"))), -$@"public interface C -{{ - T A {{ get; set; }} -}}"); + $$""" + public interface C + { + T A { get; set; } + } + """); } [Fact] public void TestInsertMembersOnInterface_SemiColon_02() { var comp = Compile( -$@"public interface C(); -"); + $""" + public interface C(); + """); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax( Generator.InsertMembers(declC, 0, Generator.PropertyDeclaration("A", Generator.IdentifierName("T"))), -$@"public interface C() -{{ - T A {{ get; set; }} -}}"); + $$""" + public interface C() + { + T A { get; set; } + } + """); } [Fact] public void TestInsertMembersOnEnum_SemiColon() { var comp = Compile( -$@"public enum C; -"); + $""" + public enum C; + """); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax( Generator.InsertMembers(declC, 0, Generator.EnumMember("A")), -$@"public enum C -{{ - A -}}"); + $$""" + public enum C + { + A + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecord_Braces() { var comp = Compile( -@"public record C { } -"); + """ + public record C { } + """); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), -@"public record C -{ - T A; -}"); + """ + public record C + { + T A; + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecord_BracesAndSemiColon() { var comp = Compile( -@"public record C { }; -"); + """ + public record C { }; + """); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), -@"public record C -{ - T A; -}"); + """ + public record C + { + T A; + } + """); } [Fact] public void TestMultiAttributeDeclarations() { var comp = Compile( -@"[X, Y, Z] -public class C -{ -}"); + """ + [X, Y, Z] + public class C + { + } + """); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var attrs = Generator.GetAttributes(declC); @@ -4234,127 +4396,159 @@ public class C // Inserting new attributes VerifySyntax( Generator.InsertAttributes(declC, 0, Generator.Attribute("A")), -@"[A] -[X, Y, Z] -public class C -{ -}"); + """ + [A] + [X, Y, Z] + public class C + { + } + """); VerifySyntax( Generator.InsertAttributes(declC, 1, Generator.Attribute("A")), -@"[X] -[A] -[Y, Z] -public class C -{ -}"); + """ + [X] + [A] + [Y, Z] + public class C + { + } + """); VerifySyntax( Generator.InsertAttributes(declC, 2, Generator.Attribute("A")), -@"[X, Y] -[A] -[Z] -public class C -{ -}"); + """ + [X, Y] + [A] + [Z] + public class C + { + } + """); VerifySyntax( Generator.InsertAttributes(declC, 3, Generator.Attribute("A")), -@"[X, Y, Z] -[A] -public class C -{ -}"); + """ + [X, Y, Z] + [A] + public class C + { + } + """); // Removing attributes VerifySyntax( Generator.RemoveNodes(declC, [attrX]), -@"[Y, Z] -public class C -{ -}"); + """ + [Y, Z] + public class C + { + } + """); VerifySyntax( Generator.RemoveNodes(declC, [attrY]), -@"[X, Z] -public class C -{ -}"); + """ + [X, Z] + public class C + { + } + """); VerifySyntax( Generator.RemoveNodes(declC, [attrZ]), -@"[X, Y] -public class C -{ -}"); + """ + [X, Y] + public class C + { + } + """); VerifySyntax( Generator.RemoveNodes(declC, [attrX, attrY]), -@"[Z] -public class C -{ -}"); + """ + [Z] + public class C + { + } + """); VerifySyntax( Generator.RemoveNodes(declC, [attrX, attrZ]), -@"[Y] -public class C -{ -}"); + """ + [Y] + public class C + { + } + """); VerifySyntax( Generator.RemoveNodes(declC, [attrY, attrZ]), -@"[X] -public class C -{ -}"); + """ + [X] + public class C + { + } + """); VerifySyntax( Generator.RemoveNodes(declC, [attrX, attrY, attrZ]), -@"public class C -{ -}"); + """ + public class C + { + } + """); // Replacing attributes VerifySyntax( Generator.ReplaceNode(declC, attrX, Generator.Attribute("A")), -@"[A, Y, Z] -public class C -{ -}"); + """ + [A, Y, Z] + public class C + { + } + """); VerifySyntax( Generator.ReplaceNode(declC, attrY, Generator.Attribute("A")), -@"[X, A, Z] -public class C -{ -}"); + """ + [X, A, Z] + public class C + { + } + """); VerifySyntax( Generator.ReplaceNode(declC, attrZ, Generator.Attribute("A")), -@"[X, Y, A] -public class C -{ -}"); + """ + [X, Y, A] + public class C + { + } + """); VerifySyntax( Generator.ReplaceNode(declC, attrX, Generator.AddAttributeArguments(attrX, [Generator.AttributeArgument(Generator.IdentifierName("e"))])), -@"[X(e), Y, Z] -public class C -{ -}"); + """ + [X(e), Y, Z] + public class C + { + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66376")] public void TestRefReturnType() { var comp = Compile( -@"public class C -{ - public ref T GetPinnableReference() { throw null; } - public ref readonly T this[int index] { get { throw null; } } - public ref int P => throw null; -}"); + """ + public class C + { + public ref T GetPinnableReference() { throw null; } + public ref readonly T this[int index] { get { throw null; } } + public ref int P => throw null; + } + """); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var method = symbolC.GetMembers().OfType().Single(m => m.MethodKind == MethodKind.Ordinary); @@ -4378,13 +4572,15 @@ public void TestRefReturnType() public void TestMultiReturnAttributeDeclarations() { var comp = Compile( -@"public class C -{ - [return: X, Y, Z] - public void M() - { - } -}"); + """ + public class C + { + [return: X, Y, Z] + public void M() + { + } + } + """); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var declM = Generator.GetMembers(declC).First(); @@ -4414,69 +4610,83 @@ public void M() // Inserting new attributes VerifySyntax( Generator.InsertReturnAttributes(declM, 0, Generator.Attribute("A")), -@"[return: A] -[return: X, Y, Z] -public void M() -{ -}"); + """ + [return: A] + [return: X, Y, Z] + public void M() + { + } + """); VerifySyntax( Generator.InsertReturnAttributes(declM, 1, Generator.Attribute("A")), -@"[return: X] -[return: A] -[return: Y, Z] -public void M() -{ -}"); + """ + [return: X] + [return: A] + [return: Y, Z] + public void M() + { + } + """); VerifySyntax( Generator.InsertReturnAttributes(declM, 2, Generator.Attribute("A")), -@"[return: X, Y] -[return: A] -[return: Z] -public void M() -{ -}"); + """ + [return: X, Y] + [return: A] + [return: Z] + public void M() + { + } + """); VerifySyntax( Generator.InsertReturnAttributes(declM, 3, Generator.Attribute("A")), -@"[return: X, Y, Z] -[return: A] -public void M() -{ -}"); + """ + [return: X, Y, Z] + [return: A] + public void M() + { + } + """); // replacing VerifySyntax( Generator.ReplaceNode(declM, attrX, Generator.Attribute("Q")), -@"[return: Q, Y, Z] -public void M() -{ -}"); + """ + [return: Q, Y, Z] + public void M() + { + } + """); VerifySyntax( Generator.ReplaceNode(declM, attrX, Generator.AddAttributeArguments(attrX, [Generator.AttributeArgument(Generator.IdentifierName("e"))])), -@"[return: X(e), Y, Z] -public void M() -{ -}"); + """ + [return: X(e), Y, Z] + public void M() + { + } + """); } [Fact] public void TestMixedAttributeDeclarations() { var comp = Compile( -@"public class C -{ - [X] - [return: A] - [Y, Z] - [return: B, C, D] - [P] - public void M() - { - } -}"); + """ + public class C + { + [X] + [return: A] + [Y, Z] + [return: B, C, D] + [P] + public void M() + { + } + } + """); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var declM = Generator.GetMembers(declC).First(); @@ -4522,150 +4732,168 @@ public void M() // inserting VerifySyntax( Generator.InsertAttributes(declM, 0, Generator.Attribute("Q")), -@"[Q] -[X] -[return: A] -[Y, Z] -[return: B, C, D] -[P] -public void M() -{ -}"); + """ + [Q] + [X] + [return: A] + [Y, Z] + [return: B, C, D] + [P] + public void M() + { + } + """); VerifySyntax( Generator.InsertAttributes(declM, 1, Generator.Attribute("Q")), -@"[X] -[return: A] -[Q] -[Y, Z] -[return: B, C, D] -[P] -public void M() -{ -}"); + """ + [X] + [return: A] + [Q] + [Y, Z] + [return: B, C, D] + [P] + public void M() + { + } + """); VerifySyntax( Generator.InsertAttributes(declM, 2, Generator.Attribute("Q")), -@"[X] -[return: A] -[Y] -[Q] -[Z] -[return: B, C, D] -[P] -public void M() -{ -}"); + """ + [X] + [return: A] + [Y] + [Q] + [Z] + [return: B, C, D] + [P] + public void M() + { + } + """); VerifySyntax( Generator.InsertAttributes(declM, 3, Generator.Attribute("Q")), -@"[X] -[return: A] -[Y, Z] -[return: B, C, D] -[Q] -[P] -public void M() -{ -}"); + """ + [X] + [return: A] + [Y, Z] + [return: B, C, D] + [Q] + [P] + public void M() + { + } + """); VerifySyntax( Generator.InsertAttributes(declM, 4, Generator.Attribute("Q")), -@"[X] -[return: A] -[Y, Z] -[return: B, C, D] -[P] -[Q] -public void M() -{ -}"); + """ + [X] + [return: A] + [Y, Z] + [return: B, C, D] + [P] + [Q] + public void M() + { + } + """); VerifySyntax( Generator.InsertReturnAttributes(declM, 0, Generator.Attribute("Q")), -@"[X] -[return: Q] -[return: A] -[Y, Z] -[return: B, C, D] -[P] -public void M() -{ -}"); + """ + [X] + [return: Q] + [return: A] + [Y, Z] + [return: B, C, D] + [P] + public void M() + { + } + """); VerifySyntax( Generator.InsertReturnAttributes(declM, 1, Generator.Attribute("Q")), -@"[X] -[return: A] -[Y, Z] -[return: Q] -[return: B, C, D] -[P] -public void M() -{ -}"); + """ + [X] + [return: A] + [Y, Z] + [return: Q] + [return: B, C, D] + [P] + public void M() + { + } + """); VerifySyntax( Generator.InsertReturnAttributes(declM, 2, Generator.Attribute("Q")), -@"[X] -[return: A] -[Y, Z] -[return: B] -[return: Q] -[return: C, D] -[P] -public void M() -{ -}"); + """ + [X] + [return: A] + [Y, Z] + [return: B] + [return: Q] + [return: C, D] + [P] + public void M() + { + } + """); VerifySyntax( Generator.InsertReturnAttributes(declM, 3, Generator.Attribute("Q")), -@"[X] -[return: A] -[Y, Z] -[return: B, C] -[return: Q] -[return: D] -[P] -public void M() -{ -}"); + """ + [X] + [return: A] + [Y, Z] + [return: B, C] + [return: Q] + [return: D] + [P] + public void M() + { + } + """); VerifySyntax( Generator.InsertReturnAttributes(declM, 4, Generator.Attribute("Q")), -@"[X] -[return: A] -[Y, Z] -[return: B, C, D] -[return: Q] -[P] -public void M() -{ -}"); + """ + [X] + [return: A] + [Y, Z] + [return: B, C, D] + [return: Q] + [P] + public void M() + { + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/293")] [Trait(Traits.Feature, Traits.Features.Formatting)] public void IntroduceBaseList() { - var text = @" -public class C -{ -} -"; - var expected = @" -public class C : IDisposable -{ -} -"; - + var text = """ + public class C + { + } + """; var root = ParseCompilationUnit(text); var decl = root.DescendantNodes().OfType().First(); var newDecl = Generator.AddInterfaceType(decl, Generator.IdentifierName("IDisposable")); var newRoot = root.ReplaceNode(decl, newDecl); var elasticOnlyFormatted = Formatter.Format(newRoot, SyntaxAnnotation.ElasticAnnotation, _workspace.Services.SolutionServices, CSharpSyntaxFormattingOptions.Default, CancellationToken.None).ToFullString(); - Assert.Equal(expected, elasticOnlyFormatted); + Assert.Equal(""" + public class C : IDisposable + { + } + """, elasticOnlyFormatted); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67335")] @@ -4847,128 +5075,139 @@ public class C2 : C public void TestNamespaceModifiers() { TestModifiersAsync(DeclarationModifiers.None, - @" -[|namespace N1 -{ -}|]"); + """ + [|namespace N1 + { + }|] + """); } [Fact, WorkItem(" https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestFileScopedNamespaceModifiers() { TestModifiersAsync(DeclarationModifiers.None, - @" -[|namespace N1;|]"); + """ + [|namespace N1;|] + """); } [Fact, WorkItem(" https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestClassModifiers1() { TestModifiersAsync(DeclarationModifiers.Static, - @" -[|static class C -{ -}|]"); + """ + [|static class C + { + }|] + """); } [Fact, WorkItem(" https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestMethodModifiers() { TestModifiersAsync(DeclarationModifiers.Sealed | DeclarationModifiers.Override, - @" -class C -{ - [|public sealed override void M() { }|] -}"); + """ + class C + { + [|public sealed override void M() { }|] + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66170")] public void TestMethodModifiers2() { TestModifiersAsync(DeclarationModifiers.ReadOnly, - @" -struct S -{ - [|public readonly void M() { }|] -}"); + """ + struct S + { + [|public readonly void M() { }|] + } + """); } [Fact] public void TestAsyncMethodModifier() { TestModifiersAsync(DeclarationModifiers.Async, - @" -using System.Threading.Tasks; -class C -{ - [|public async Task DoAsync() { await Task.CompletedTask; }|] -} -"); + """ + using System.Threading.Tasks; + class C + { + [|public async Task DoAsync() { await Task.CompletedTask; }|] + } + """); } [Fact, WorkItem(" https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestPropertyModifiers1() { TestModifiersAsync(DeclarationModifiers.Virtual | DeclarationModifiers.ReadOnly, - @" -class C -{ - [|public virtual int X => 0;|] -}"); + """ + class C + { + [|public virtual int X => 0;|] + } + """); } [Fact] public void TestPropertyModifiers2() { TestModifiersAsync(DeclarationModifiers.ReadOnly | DeclarationModifiers.Required, - @" -class C -{ - [|public required int X => 0;|] -}"); + """ + class C + { + [|public required int X => 0;|] + } + """); } [Fact, WorkItem(" https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestFieldModifiers1() { TestModifiersAsync(DeclarationModifiers.Static, - @" -class C -{ - public static int [|X|]; -}"); + """ + class C + { + public static int [|X|]; + } + """); } [Fact] public void TestFieldModifiers2() { TestModifiersAsync(DeclarationModifiers.Required, - @" -class C -{ - public required int [|X|]; -}"); + """ + class C + { + public required int [|X|]; + } + """); } [Fact, WorkItem(" https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestEvent1() { TestModifiersAsync(DeclarationModifiers.Virtual, - @" -class C -{ - public virtual event System.Action [|X|]; -}"); + """ + class C + { + public virtual event System.Action [|X|]; + } + """); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65834")] public void TestStructModifiers1() { TestModifiersAsync(DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed, - @" -public readonly struct [|S|] -{ -}"); + """ + public readonly struct [|S|] + { + } + """); } [Fact] diff --git a/src/Workspaces/CSharpTest/CodeStyle/CSharpEditorConfigCodeStyleParserTests.cs b/src/Workspaces/CSharpTest/CodeStyle/CSharpEditorConfigCodeStyleParserTests.cs index 84c010a55efd5..adaad2e49a16b 100644 --- a/src/Workspaces/CSharpTest/CodeStyle/CSharpEditorConfigCodeStyleParserTests.cs +++ b/src/Workspaces/CSharpTest/CodeStyle/CSharpEditorConfigCodeStyleParserTests.cs @@ -25,7 +25,7 @@ public sealed class CSharpEditorConfigCodeStyleParserTests [InlineData(" none ", BinaryOperatorSpacingOptions.Remove)] [InlineData(" before_and_after ", BinaryOperatorSpacingOptions.Single)] public void TestParseSpacingAroundBinaryOperator(string rawValue, BinaryOperatorSpacingOptions parsedValue) - => Assert.Equal(parsedValue, CSharpFormattingOptions2.ParseEditorConfigSpacingAroundBinaryOperator(rawValue)); + => Assert.Equal(parsedValue, (BinaryOperatorSpacingOptions)CSharpFormattingOptions2.ParseEditorConfigSpacingAroundBinaryOperator(rawValue)); [Theory] [InlineData("flush_left", LabelPositionOptions.LeftMost)] @@ -37,7 +37,7 @@ public void TestParseSpacingAroundBinaryOperator(string rawValue, BinaryOperator [InlineData(" no_change ", LabelPositionOptions.NoIndent)] [InlineData(" one_less_than_current ", LabelPositionOptions.OneLess)] public void TestParseLabelPositioning(string rawValue, LabelPositionOptions parsedValue) - => Assert.Equal(parsedValue, CSharpFormattingOptions2.ParseEditorConfigLabelPositioning(rawValue)); + => Assert.Equal(parsedValue, (LabelPositionOptions)CSharpFormattingOptions2.ParseEditorConfigLabelPositioning(rawValue)); [Theory] [InlineData("false:none", (int)ExpressionBodyPreference.Never, ReportDiagnostic.Suppress)] diff --git a/src/Workspaces/CSharpTest/EmbeddedLanguages/VirtualChars/CSharpVirtualCharServiceTests.cs b/src/Workspaces/CSharpTest/EmbeddedLanguages/VirtualChars/CSharpVirtualCharServiceTests.cs index 4db8d22b4d159..99ce6a4d44e70 100644 --- a/src/Workspaces/CSharpTest/EmbeddedLanguages/VirtualChars/CSharpVirtualCharServiceTests.cs +++ b/src/Workspaces/CSharpTest/EmbeddedLanguages/VirtualChars/CSharpVirtualCharServiceTests.cs @@ -127,163 +127,243 @@ namespace N [Fact] public void TestEmptyString() - => Test("\"\"", ""); + => Test(""" + "" + """, ""); [Fact] public void TestEmptyVerbatimString() - => Test("@\"\"", ""); + => Test(""" + @"" + """, ""); [Fact] public void TestSimpleString() - => Test("\"a\"", "['a',[1,2]]"); + => Test(""" + "a" + """, "['a',[1,2]]"); [Fact] public void TestSimpleMultiCharString() - => Test("\"abc\"", "['a',[1,2]]['b',[2,3]]['c',[3,4]]"); + => Test(""" + "abc" + """, "['a',[1,2]]['b',[2,3]]['c',[3,4]]"); [Fact] public void TestBracesInSimpleString() - => Test("\"{{\"", "['{',[1,2]]['{',[2,3]]"); + => Test(""" + "{{" + """, "['{',[1,2]]['{',[2,3]]"); [Fact] public void TestBracesInInterpolatedSimpleString() - => Test("$\"{{\"", "['{',[2,4]]"); + => Test(""" + $"{{" + """, "['{',[2,4]]"); [Fact] public void TestBracesInInterpolatedVerbatimSimpleString() - => Test("$@\"{{\"", "['{',[3,5]]"); + => Test(""" + $@"{{" + """, "['{',[3,5]]"); [Fact] public void TestBracesInReverseInterpolatedVerbatimSimpleString() - => Test("@$\"{{\"", "['{',[3,5]]"); + => Test(""" + @$"{{" + """, "['{',[3,5]]"); [Fact] public void TestEscapeInInterpolatedSimpleString() - => Test("$\"\\n\"", @"['\u000A',[2,4]]"); + => Test(""" + $"\n" + """, @"['\u000A',[2,4]]"); [Fact] public void TestEscapeInInterpolatedSimpleString_E() - => Test("$\"\\e\"", @"['\u001B',[2,4]]"); + => Test(""" + $"\e" + """, @"['\u001B',[2,4]]"); [Fact] public void TestEscapeInInterpolatedVerbatimSimpleString() - => Test("$@\"\\n\"", @"['\u005C',[3,4]]['n',[4,5]]"); + => Test(""" + $@"\n" + """, @"['\u005C',[3,4]]['n',[4,5]]"); [Fact] public void TestSimpleVerbatimString() - => Test("@\"a\"", "['a',[2,3]]"); + => Test(""" + @"a" + """, "['a',[2,3]]"); [Fact] public void TestUnterminatedString() - => TestFailure("\""); + => TestFailure(""" + " + """); [Fact] public void TestUnterminatedVerbatimString() - => TestFailure("@\""); + => TestFailure(""" + @" + """); [Fact] public void TestSimpleEscape() - => Test(@"""a\ta""", "['a',[1,2]]['\\u0009',[2,4]]['a',[4,5]]"); + => Test(""" + "a\ta" + """, "['a',[1,2]]['\\u0009',[2,4]]['a',[4,5]]"); [Fact] public void TestMultipleSimpleEscape() - => Test(@"""a\t\ta""", "['a',[1,2]]['\\u0009',[2,4]]['\\u0009',[4,6]]['a',[6,7]]"); + => Test(""" + "a\t\ta" + """, "['a',[1,2]]['\\u0009',[2,4]]['\\u0009',[4,6]]['a',[6,7]]"); [Fact] public void TestNonEscapeInVerbatim() - => Test(@"@""a\ta""", "['a',[2,3]]['\\u005C',[3,4]]['t',[4,5]]['a',[5,6]]"); + => Test(""" + @"a\ta" + """, "['a',[2,3]]['\\u005C',[3,4]]['t',[4,5]]['a',[5,6]]"); [Fact] public void TestInvalidHexEscape() - => TestFailure(@"""\xZ"""); + => TestFailure(""" + "\xZ" + """); [Fact] public void TestValidHex1Escape() - => Test(@"""\xa""", @"['\u000A',[1,4]]"); + => Test(""" + "\xa" + """, @"['\u000A',[1,4]]"); [Fact] public void TestValidHex1EscapeInInterpolatedString() - => Test(@"$""\xa""", @"['\u000A',[2,5]]"); + => Test(""" + $"\xa" + """, @"['\u000A',[2,5]]"); [Fact] public void TestValidHex2Escape() - => Test(@"""\xaa""", @"['\u00AA',[1,5]]"); + => Test(""" + "\xaa" + """, @"['\u00AA',[1,5]]"); [Fact] public void TestValidHex3Escape() - => Test(@"""\xaaa""", @"['\u0AAA',[1,6]]"); + => Test(""" + "\xaaa" + """, @"['\u0AAA',[1,6]]"); [Fact] public void TestValidHex4Escape() - => Test(@"""\xaaaa""", @"['\uAAAA',[1,7]]"); + => Test(""" + "\xaaaa" + """, @"['\uAAAA',[1,7]]"); [Fact] public void TestValidHex5Escape() - => Test(@"""\xaaaaa""", @"['\uAAAA',[1,7]]['a',[7,8]]"); + => Test(""" + "\xaaaaa" + """, @"['\uAAAA',[1,7]]['a',[7,8]]"); [Fact] public void TestValidHex6Escape() - => Test(@"""a\xaaaaa""", @"['a',[1,2]]['\uAAAA',[2,8]]['a',[8,9]]"); + => Test(""" + "a\xaaaaa" + """, @"['a',[1,2]]['\uAAAA',[2,8]]['a',[8,9]]"); [Fact] public void TestInvalidUnicodeEscape() - => TestFailure(@"""\u000"""); + => TestFailure(""" + "\u000" + """); [Fact] public void TestValidUnicodeEscape1() - => Test(@"""\u0000""", @"['\u0000',[1,7]]"); + => Test(""" + "\u0000" + """, @"['\u0000',[1,7]]"); [Fact] public void TestValidUnicodeEscape2() - => Test(@"""a\u0000a""", @"['a',[1,2]]['\u0000',[2,8]]['a',[8,9]]"); + => Test(""" + "a\u0000a" + """, @"['a',[1,2]]['\u0000',[2,8]]['a',[8,9]]"); [Fact] public void TestInvalidLongUnicodeEscape1() - => TestFailure(@"""\U0000"""); + => TestFailure(""" + "\U0000" + """); [Fact] public void TestInvalidLongUnicodeEscape2() - => TestFailure(@"""\U10000000"""); + => TestFailure(""" + "\U10000000" + """); [Fact] public void TestValidLongEscape1_InCharRange() - => Test(@"""\U00000000""", @"['\u0000',[1,11]]"); + => Test(""" + "\U00000000" + """, @"['\u0000',[1,11]]"); [Fact] public void TestValidLongEscape2_InCharRange() - => Test(@"""\U0000ffff""", @"['\uFFFF',[1,11]]"); + => Test(""" + "\U0000ffff" + """, @"['\uFFFF',[1,11]]"); [Fact] public void TestValidLongEscape3_InCharRange() - => Test(@"""a\U00000000a""", @"['a',[1,2]]['\u0000',[2,12]]['a',[12,13]]"); + => Test(""" + "a\U00000000a" + """, @"['a',[1,2]]['\u0000',[2,12]]['a',[12,13]]"); [Fact] public void TestValidLongEscape1_NotInCharRange() - => Test(@"""\U00010000""", @"['\U00010000',[1,11]]"); + => Test(""" + "\U00010000" + """, @"['\U00010000',[1,11]]"); [Fact] public void TestValidLongEscape2_NotInCharRange() - => Test(@"""\U0002A6A5𪚥""", @"['\U0002A6A5',[1,11]]['\U0002A6A5',[11,13]]"); + => Test(""" + "\U0002A6A5𪚥" + """, @"['\U0002A6A5',[1,11]]['\U0002A6A5',[11,13]]"); [Fact] public void TestSurrogate1() - => Test(@"""😊""", @"['\U0001F60A',[1,3]]"); + => Test(""" + "😊" + """, @"['\U0001F60A',[1,3]]"); [Fact] public void TestSurrogate2() - => Test(@"""\U0001F60A""", @"['\U0001F60A',[1,11]]"); + => Test(""" + "\U0001F60A" + """, @"['\U0001F60A',[1,11]]"); [Fact] public void TestSurrogate3() - => Test(@"""\ud83d\ude0a""", @"['\U0001F60A',[1,13]]"); + => Test(""" + "\ud83d\ude0a" + """, @"['\U0001F60A',[1,13]]"); [Fact] public void TestHighSurrogate() - => Test(@"""\ud83d""", @"['\uD83D',[1,7]]"); + => Test(""" + "\ud83d" + """, @"['\uD83D',[1,7]]"); [Fact] public void TestLowSurrogate() - => Test(@"""\ude0a""", @"['\uDE0A',[1,7]]"); + => Test(""" + "\ude0a" + """, @"['\uDE0A',[1,7]]"); [Fact] public void TestMixedSurrogate1() @@ -295,665 +375,845 @@ public void TestMixedSurrogate2() [Fact] public void TestEscapedQuoteInVerbatimString() - => Test("@\"a\"\"a\"", @"['a',[2,3]]['\u0022',[3,5]]['a',[5,6]]"); + => Test(""" + @"a""a" + """, @"['a',[2,3]]['\u0022',[3,5]]['a',[5,6]]"); [Fact] public void TestSingleLineRawString() - => Test(@"""""""goo""""""", @"['g',[3,4]]['o',[4,5]]['o',[5,6]]"); + => Test("""" + """goo""" + """", @"['g',[3,4]]['o',[4,5]]['o',[5,6]]"); [Fact] public void TestMultiLineRawString1() - => Test(@""""""" - goo - """"""", @"['g',[9,10]]['o',[10,11]]['o',[11,12]]"); + => Test("""" + """ + goo + """ + """", @"['g',[9,10]]['o',[10,11]]['o',[11,12]]"); [Fact] public void TestMultiLineRawString2() - => Test(@""""""" - goo - bar - """"""", @"['g',[9,10]]['o',[10,11]]['o',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]]['b',[18,19]]['a',[19,20]]['r',[20,21]]"); + => Test("""" + """ + goo + bar + """ + """", @"['g',[9,10]]['o',[10,11]]['o',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]]['b',[18,19]]['a',[19,20]]['r',[20,21]]"); [Fact] public void TestMultiLineRawString3() - => Test(@""""""" - goo - bar - """"""", @"['g',[9,10]]['o',[10,11]]['o',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]][' ',[18,19]][' ',[19,20]][' ',[20,21]][' ',[21,22]]['b',[22,23]]['a',[23,24]]['r',[24,25]]"); + => Test("""" + """ + goo + bar + """ + """", @"['g',[9,10]]['o',[10,11]]['o',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]][' ',[18,19]][' ',[19,20]][' ',[20,21]][' ',[21,22]]['b',[22,23]]['a',[23,24]]['r',[24,25]]"); [Fact] public void TestMultiLineRawString4() - => Test(@""""""" - goo - bar - """"""", @"[' ',[9,10]][' ',[10,11]][' ',[11,12]][' ',[12,13]]['g',[13,14]]['o',[14,15]]['o',[15,16]]['\u000D',[16,17]]['\u000A',[17,18]]['b',[22,23]]['a',[23,24]]['r',[24,25]]"); + => Test("""" + """ + goo + bar + """ + """", @"[' ',[9,10]][' ',[10,11]][' ',[11,12]][' ',[12,13]]['g',[13,14]]['o',[14,15]]['o',[15,16]]['\u000D',[16,17]]['\u000A',[17,18]]['b',[22,23]]['a',[23,24]]['r',[24,25]]"); [Fact] public void TestMultiLineRawString5() - => Test(@""""""" - goo + => Test("""" + """ + goo - bar - """"""", @"['g',[9,10]]['o',[10,11]]['o',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]]['\u000D',[14,15]]['\u000A',[15,16]]['b',[20,21]]['a',[21,22]]['r',[22,23]]"); + bar + """ + """", @"['g',[9,10]]['o',[10,11]]['o',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]]['\u000D',[14,15]]['\u000A',[15,16]]['b',[20,21]]['a',[21,22]]['r',[22,23]]"); [Fact] public void TestMultiLineRawString6() - => Test(@""""""" - goo - - bar - """"""", @"['g',[9,10]]['o',[10,11]]['o',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]]['\u000D',[18,19]]['\u000A',[19,20]]['b',[24,25]]['a',[25,26]]['r',[26,27]]"); + => Test("""" + """ + goo + + bar + """ + """", @"['g',[9,10]]['o',[10,11]]['o',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]]['\u000D',[18,19]]['\u000A',[19,20]]['b',[24,25]]['a',[25,26]]['r',[26,27]]"); [Fact] public void TestMultiLineRawString7() - => Test(@""""""" - goo - - bar - """"""", @"['g',[9,10]]['o',[10,11]]['o',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]][' ',[18,19]][' ',[19,20]]['\u000D',[20,21]]['\u000A',[21,22]]['b',[26,27]]['a',[27,28]]['r',[28,29]]"); + => Test("""" + """ + goo + + bar + """ + """", @"['g',[9,10]]['o',[10,11]]['o',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]][' ',[18,19]][' ',[19,20]]['\u000D',[20,21]]['\u000A',[21,22]]['b',[26,27]]['a',[27,28]]['r',[28,29]]"); [Fact] public void TestMultiLineRawString8() - => Test(@""""""" - goo + => Test("""" + """ + goo - bar + bar - """"""", @"['g',[9,10]]['o',[10,11]]['o',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]]['\u000D',[14,15]]['\u000A',[15,16]]['b',[20,21]]['a',[21,22]]['r',[22,23]]['\u000D',[23,24]]['\u000A',[24,25]]"); + """ + """", @"['g',[9,10]]['o',[10,11]]['o',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]]['\u000D',[14,15]]['\u000A',[15,16]]['b',[20,21]]['a',[21,22]]['r',[22,23]]['\u000D',[23,24]]['\u000A',[24,25]]"); [Fact] public void TestMultiLineRawString9() - => Test(@""""""" - goo + => Test("""" + """ + goo - bar - - """"""", @"['g',[9,10]]['o',[10,11]]['o',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]]['\u000D',[14,15]]['\u000A',[15,16]]['b',[20,21]]['a',[21,22]]['r',[22,23]]['\u000D',[23,24]]['\u000A',[24,25]]"); + bar + + """ + """", @"['g',[9,10]]['o',[10,11]]['o',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]]['\u000D',[14,15]]['\u000A',[15,16]]['b',[20,21]]['a',[21,22]]['r',[22,23]]['\u000D',[23,24]]['\u000A',[24,25]]"); [Fact] public void TestMultiLineRawString10() - => Test(@""""""" - goo + => Test("""" + """ + goo - bar - - """"""", @"['g',[9,10]]['o',[10,11]]['o',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]]['\u000D',[14,15]]['\u000A',[15,16]]['b',[20,21]]['a',[21,22]]['r',[22,23]]['\u000D',[23,24]]['\u000A',[24,25]][' ',[29,30]][' ',[30,31]]"); + bar + + """ + """", @"['g',[9,10]]['o',[10,11]]['o',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]]['\u000D',[14,15]]['\u000A',[15,16]]['b',[20,21]]['a',[21,22]]['r',[22,23]]['\u000D',[23,24]]['\u000A',[24,25]][' ',[29,30]][' ',[30,31]]"); [Fact] public void TestMultiLineRawString11() - => Test(@""""""" -goo + => Test("""" + """ + goo -bar -""""""", @"['g',[5,6]]['o',[6,7]]['o',[7,8]]['\u000D',[8,9]]['\u000A',[9,10]]['\u000D',[10,11]]['\u000A',[11,12]]['b',[12,13]]['a',[13,14]]['r',[14,15]]"); + bar + """ + """", @"['g',[5,6]]['o',[6,7]]['o',[7,8]]['\u000D',[8,9]]['\u000A',[9,10]]['\u000D',[10,11]]['\u000A',[11,12]]['b',[12,13]]['a',[13,14]]['r',[14,15]]"); [Fact] public void TestMultiLineRawString12() - => Test(@""""""" - goo + => Test("""" + """ + goo - bar -""""""", @"[' ',[5,6]][' ',[6,7]]['g',[7,8]]['o',[8,9]]['o',[9,10]]['\u000D',[10,11]]['\u000A',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]][' ',[14,15]][' ',[15,16]]['b',[16,17]]['a',[17,18]]['r',[18,19]]"); + bar + """ + """", @"[' ',[5,6]][' ',[6,7]]['g',[7,8]]['o',[8,9]]['o',[9,10]]['\u000D',[10,11]]['\u000A',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]][' ',[14,15]][' ',[15,16]]['b',[16,17]]['a',[17,18]]['r',[18,19]]"); [Fact] public void TestMultiLineRawString13() - => Test(@""""""" + => Test("""" + """ - goo + goo - bar - """"""", @"['\u000D',[5,6]]['\u000A',[6,7]]['g',[11,12]]['o',[12,13]]['o',[13,14]]['\u000D',[14,15]]['\u000A',[15,16]]['\u000D',[16,17]]['\u000A',[17,18]]['b',[22,23]]['a',[23,24]]['r',[24,25]]"); + bar + """ + """", @"['\u000D',[5,6]]['\u000A',[6,7]]['g',[11,12]]['o',[12,13]]['o',[13,14]]['\u000D',[14,15]]['\u000A',[15,16]]['\u000D',[16,17]]['\u000A',[17,18]]['b',[22,23]]['a',[23,24]]['r',[24,25]]"); [Fact] public void TestMultiLineRawString14() - => Test(@""""""" - - goo + => Test("""" + """ + + goo - bar - """"""", @"['\u000D',[9,10]]['\u000A',[10,11]]['g',[15,16]]['o',[16,17]]['o',[17,18]]['\u000D',[18,19]]['\u000A',[19,20]]['\u000D',[20,21]]['\u000A',[21,22]]['b',[26,27]]['a',[27,28]]['r',[28,29]]"); + bar + """ + """", @"['\u000D',[9,10]]['\u000A',[10,11]]['g',[15,16]]['o',[16,17]]['o',[17,18]]['\u000D',[18,19]]['\u000A',[19,20]]['\u000D',[20,21]]['\u000A',[21,22]]['b',[26,27]]['a',[27,28]]['r',[28,29]]"); [Fact] public void TestMultiLineRawString15() - => Test(@""""""" - - goo + => Test("""" + """ + + goo - bar - """"""", @"[' ',[9,10]][' ',[10,11]]['\u000D',[11,12]]['\u000A',[12,13]]['g',[17,18]]['o',[18,19]]['o',[19,20]]['\u000D',[20,21]]['\u000A',[21,22]]['\u000D',[22,23]]['\u000A',[23,24]]['b',[28,29]]['a',[29,30]]['r',[30,31]]"); + bar + """ + """", @"[' ',[9,10]][' ',[10,11]]['\u000D',[11,12]]['\u000A',[12,13]]['g',[17,18]]['o',[18,19]]['o',[19,20]]['\u000D',[20,21]]['\u000A',[21,22]]['\u000D',[22,23]]['\u000A',[23,24]]['b',[28,29]]['a',[29,30]]['r',[30,31]]"); [Fact] public void TestMultiLineRawString16() - => Test(@""""""" + => Test("""" + """ - """"""", @""); + """ + """", @""); [Fact] public void TestMultiLineRawString17() - => Test(@""""""" - - """"""", @""); + => Test("""" + """ + + """ + """", @""); [Fact] public void TestMultiLineRawString18() - => Test(@""""""" - - """"""", @"[' ',[9,10]][' ',[10,11]]"); + => Test("""" + """ + + """ + """", @"[' ',[9,10]][' ',[10,11]]"); [Fact] public void TestMultiLineRawString19() - => Test(@""""""" - goo - """"""", @"['g',[11,12]]['o',[12,13]]['o',[13,14]]"); + => Test("""" + """ + goo + """ + """", @"['g',[11,12]]['o',[12,13]]['o',[13,14]]"); [Fact] public void TestSingleLineInterpolatedRawString1() - => Test(@"$""""""goo""""""", @"['g',[4,5]]['o',[5,6]]['o',[6,7]]"); + => Test("""" + $"""goo""" + """", @"['g',[4,5]]['o',[5,6]]['o',[6,7]]"); [Fact] public void TestSingleLineInterpolatedRawString2() - => Test(@"$""""""goo{0}""""""", @"['g',[4,5]]['o',[5,6]]['o',[6,7]]"); + => Test("""" + $"""goo{0}""" + """", @"['g',[4,5]]['o',[5,6]]['o',[6,7]]"); [Fact] public void TestSingleLineInterpolatedRawString3() - => Test(@"$""""""{0}goo""""""", @"['g',[7,8]]['o',[8,9]]['o',[9,10]]"); + => Test("""" + $"""{0}goo""" + """", @"['g',[7,8]]['o',[8,9]]['o',[9,10]]"); [Fact] public void TestSingleLineInterpolatedRawString4() - => Test(@"$""""""{0}goo{1}""""""", @"['g',[7,8]]['o',[8,9]]['o',[9,10]]"); + => Test("""" + $"""{0}goo{1}""" + """", @"['g',[7,8]]['o',[8,9]]['o',[9,10]]"); [Fact] public void TestSingleLineInterpolatedRawString5() - => Test(@"$""""""goo{0}{1}""""""", @"['g',[4,5]]['o',[5,6]]['o',[6,7]]"); + => Test("""" + $"""goo{0}{1}""" + """", @"['g',[4,5]]['o',[5,6]]['o',[6,7]]"); [Fact] public void TestSingleLineInterpolatedRawString6() - => Test(@"$""""""{0}{1}goo""""""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]"); + => Test("""" + $"""{0}{1}goo""" + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]"); [Fact] public void TestSingleLineInterpolatedRawString7() - => Test(@"$""""""goo{0}bar{1}""""""", @"['g',[4,5]]['o',[5,6]]['o',[6,7]]['b',[10,11]]['a',[11,12]]['r',[12,13]]"); + => Test("""" + $"""goo{0}bar{1}""" + """", @"['g',[4,5]]['o',[5,6]]['o',[6,7]]['b',[10,11]]['a',[11,12]]['r',[12,13]]"); [Fact] public void TestSingleLineInterpolatedRawString8() - => Test(@"$""""""{0}goo{1}bar""""""", @"['g',[7,8]]['o',[8,9]]['o',[9,10]]['b',[13,14]]['a',[14,15]]['r',[15,16]]"); + => Test("""" + $"""{0}goo{1}bar""" + """", @"['g',[7,8]]['o',[8,9]]['o',[9,10]]['b',[13,14]]['a',[14,15]]['r',[15,16]]"); [Fact] public void TestSingleLineInterpolatedRawString9() - => Test(@"$""""""goo{0}{1}bar""""""", @"['g',[4,5]]['o',[5,6]]['o',[6,7]]['b',[13,14]]['a',[14,15]]['r',[15,16]]"); + => Test("""" + $"""goo{0}{1}bar""" + """", @"['g',[4,5]]['o',[5,6]]['o',[6,7]]['b',[13,14]]['a',[14,15]]['r',[15,16]]"); [Fact] public void TestSingleLineInterpolatedRawString10() - => Test(@"$""""""goo{0}bar{1}baz""""""", @"['g',[4,5]]['o',[5,6]]['o',[6,7]]['b',[10,11]]['a',[11,12]]['r',[12,13]]['b',[16,17]]['a',[17,18]]['z',[18,19]]"); + => Test("""" + $"""goo{0}bar{1}baz""" + """", @"['g',[4,5]]['o',[5,6]]['o',[6,7]]['b',[10,11]]['a',[11,12]]['r',[12,13]]['b',[16,17]]['a',[17,18]]['z',[18,19]]"); [Fact] public void TestMultiLineInterpolatedRawString1() - => Test(@"$"""""" - goo - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]"); + => Test("""" + $""" + goo + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]"); [Fact] public void TestMultiLineInterpolatedRawString2() - => Test(@"$"""""" - goo - bar - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['b',[19,20]]['a',[20,21]]['r',[21,22]]"); + => Test("""" + $""" + goo + bar + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['b',[19,20]]['a',[20,21]]['r',[21,22]]"); [Fact] public void TestMultiLineInterpolatedRawString3() - => Test(@"$"""""" - goo - bar - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[19,20]][' ',[20,21]][' ',[21,22]][' ',[22,23]]['b',[23,24]]['a',[24,25]]['r',[25,26]]"); + => Test("""" + $""" + goo + bar + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[19,20]][' ',[20,21]][' ',[21,22]][' ',[22,23]]['b',[23,24]]['a',[24,25]]['r',[25,26]]"); [Fact] public void TestMultiLineInterpolatedRawString4() - => Test(@"$"""""" - goo - bar - """"""", @"[' ',[10,11]][' ',[11,12]][' ',[12,13]][' ',[13,14]]['g',[14,15]]['o',[15,16]]['o',[16,17]]['\u000D',[17,18]]['\u000A',[18,19]]['b',[23,24]]['a',[24,25]]['r',[25,26]]"); + => Test("""" + $""" + goo + bar + """ + """", @"[' ',[10,11]][' ',[11,12]][' ',[12,13]][' ',[13,14]]['g',[14,15]]['o',[15,16]]['o',[16,17]]['\u000D',[17,18]]['\u000A',[18,19]]['b',[23,24]]['a',[24,25]]['r',[25,26]]"); [Fact] public void TestMultiLineInterpolatedRawString5() - => Test(@"$"""""" - goo + => Test("""" + $""" + goo - bar - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[15,16]]['\u000A',[16,17]]['b',[21,22]]['a',[22,23]]['r',[23,24]]"); + bar + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[15,16]]['\u000A',[16,17]]['b',[21,22]]['a',[22,23]]['r',[23,24]]"); [Fact] public void TestMultiLineInterpolatedRawString6() - => Test(@"$"""""" - goo - - bar - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[19,20]]['\u000A',[20,21]]['b',[25,26]]['a',[26,27]]['r',[27,28]]"); + => Test("""" + $""" + goo + + bar + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[19,20]]['\u000A',[20,21]]['b',[25,26]]['a',[26,27]]['r',[27,28]]"); [Fact] public void TestMultiLineInterpolatedRawString7() - => Test(@"$"""""" - goo - - bar - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[19,20]][' ',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]['b',[27,28]]['a',[28,29]]['r',[29,30]]"); + => Test("""" + $""" + goo + + bar + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[19,20]][' ',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]['b',[27,28]]['a',[28,29]]['r',[29,30]]"); [Fact] public void TestMultiLineInterpolatedRawString8() - => Test(@"$"""""" - goo + => Test("""" + $""" + goo - bar + bar - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[15,16]]['\u000A',[16,17]]['b',[21,22]]['a',[22,23]]['r',[23,24]]['\u000D',[24,25]]['\u000A',[25,26]]"); + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[15,16]]['\u000A',[16,17]]['b',[21,22]]['a',[22,23]]['r',[23,24]]['\u000D',[24,25]]['\u000A',[25,26]]"); [Fact] public void TestMultiLineInterpolatedRawString9() - => Test(@"$"""""" - goo + => Test("""" + $""" + goo - bar - - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[15,16]]['\u000A',[16,17]]['b',[21,22]]['a',[22,23]]['r',[23,24]]['\u000D',[24,25]]['\u000A',[25,26]]"); + bar + + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[15,16]]['\u000A',[16,17]]['b',[21,22]]['a',[22,23]]['r',[23,24]]['\u000D',[24,25]]['\u000A',[25,26]]"); [Fact] public void TestMultiLineInterpolatedRawString10() - => Test(@"$"""""" - goo + => Test("""" + $""" + goo - bar - - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[15,16]]['\u000A',[16,17]]['b',[21,22]]['a',[22,23]]['r',[23,24]]['\u000D',[24,25]]['\u000A',[25,26]][' ',[30,31]][' ',[31,32]]"); + bar + + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[15,16]]['\u000A',[16,17]]['b',[21,22]]['a',[22,23]]['r',[23,24]]['\u000D',[24,25]]['\u000A',[25,26]][' ',[30,31]][' ',[31,32]]"); [Fact] public void TestMultiLineInterpolatedRawString11() - => Test(@"$"""""" -goo + => Test("""" + $""" + goo -bar -""""""", @"['g',[6,7]]['o',[7,8]]['o',[8,9]]['\u000D',[9,10]]['\u000A',[10,11]]['\u000D',[11,12]]['\u000A',[12,13]]['b',[13,14]]['a',[14,15]]['r',[15,16]]"); + bar + """ + """", @"['g',[6,7]]['o',[7,8]]['o',[8,9]]['\u000D',[9,10]]['\u000A',[10,11]]['\u000D',[11,12]]['\u000A',[12,13]]['b',[13,14]]['a',[14,15]]['r',[15,16]]"); [Fact] public void TestMultiLineInterpolatedRawString12() - => Test(@"$"""""" - goo + => Test("""" + $""" + goo - bar -""""""", @"[' ',[6,7]][' ',[7,8]]['g',[8,9]]['o',[9,10]]['o',[10,11]]['\u000D',[11,12]]['\u000A',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[15,16]][' ',[16,17]]['b',[17,18]]['a',[18,19]]['r',[19,20]]"); + bar + """ + """", @"[' ',[6,7]][' ',[7,8]]['g',[8,9]]['o',[9,10]]['o',[10,11]]['\u000D',[11,12]]['\u000A',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[15,16]][' ',[16,17]]['b',[17,18]]['a',[18,19]]['r',[19,20]]"); [Fact] public void TestMultiLineInterpolatedRawString13() - => Test(@"$"""""" + => Test("""" + $""" - goo + goo - bar - """"""", @"['\u000D',[6,7]]['\u000A',[7,8]]['g',[12,13]]['o',[13,14]]['o',[14,15]]['\u000D',[15,16]]['\u000A',[16,17]]['\u000D',[17,18]]['\u000A',[18,19]]['b',[23,24]]['a',[24,25]]['r',[25,26]]"); + bar + """ + """", @"['\u000D',[6,7]]['\u000A',[7,8]]['g',[12,13]]['o',[13,14]]['o',[14,15]]['\u000D',[15,16]]['\u000A',[16,17]]['\u000D',[17,18]]['\u000A',[18,19]]['b',[23,24]]['a',[24,25]]['r',[25,26]]"); [Fact] public void TestMultiLineInterpolatedRawString14() - => Test(@"$"""""" - - goo + => Test("""" + $""" + + goo - bar - """"""", @"['\u000D',[10,11]]['\u000A',[11,12]]['g',[16,17]]['o',[17,18]]['o',[18,19]]['\u000D',[19,20]]['\u000A',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]['b',[27,28]]['a',[28,29]]['r',[29,30]]"); + bar + """ + """", @"['\u000D',[10,11]]['\u000A',[11,12]]['g',[16,17]]['o',[17,18]]['o',[18,19]]['\u000D',[19,20]]['\u000A',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]['b',[27,28]]['a',[28,29]]['r',[29,30]]"); [Fact] public void TestMultiLineInterpolatedRawString15() - => Test(@"$"""""" - - goo + => Test("""" + $""" + + goo - bar - """"""", @"[' ',[10,11]][' ',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]]['g',[18,19]]['o',[19,20]]['o',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]['\u000D',[23,24]]['\u000A',[24,25]]['b',[29,30]]['a',[30,31]]['r',[31,32]]"); + bar + """ + """", @"[' ',[10,11]][' ',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]]['g',[18,19]]['o',[19,20]]['o',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]['\u000D',[23,24]]['\u000A',[24,25]]['b',[29,30]]['a',[30,31]]['r',[31,32]]"); [Fact] public void TestMultiLineInterpolatedRawString16() - => Test(@"$"""""" + => Test("""" + $""" - """"""", @""); + """ + """", @""); [Fact] public void TestMultiLineInterpolatedRawString17() - => Test(@"$"""""" - - """"""", @""); + => Test("""" + $""" + + """ + """", @""); [Fact] public void TestMultiLineInterpolatedRawString18() - => Test(@"$"""""" - - """"""", @"[' ',[10,11]][' ',[11,12]]"); + => Test("""" + $""" + + """ + """", @"[' ',[10,11]][' ',[11,12]]"); [Fact] public void TestMultiLineInterpolatedRawString19() - => Test(@"$"""""" - goo - """"""", @"['g',[12,13]]['o',[13,14]]['o',[14,15]]"); + => Test("""" + $""" + goo + """ + """", @"['g',[12,13]]['o',[13,14]]['o',[14,15]]"); [Fact] public void TestMultiLineInterpolatedRawString20() - => Test(@"$"""""" - goo - {1} - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]"); + => Test("""" + $""" + goo + {1} + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]"); [Fact] public void TestMultiLineInterpolatedRawString21() - => Test(@"$"""""" - goo{1} - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]"); + => Test("""" + $""" + goo{1} + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]"); [Fact] public void TestMultiLineInterpolatedRawString22() - => Test(@"$"""""" - {1}goo - """"""", @"['g',[13,14]]['o',[14,15]]['o',[15,16]]"); + => Test("""" + $""" + {1}goo + """ + """", @"['g',[13,14]]['o',[14,15]]['o',[15,16]]"); [Fact] public void TestMultiLineInterpolatedRawString23() - => Test(@"$"""""" - {1} - goo - """"""", @"['\u000D',[13,14]]['\u000A',[14,15]]['g',[19,20]]['o',[20,21]]['o',[21,22]]"); + => Test("""" + $""" + {1} + goo + """ + """", @"['\u000D',[13,14]]['\u000A',[14,15]]['g',[19,20]]['o',[20,21]]['o',[21,22]]"); [Fact] public void TestMultiLineInterpolatedRawString24() - => Test(@"$"""""" - goo - {1} - """"""", @"[' ',[10,11]][' ',[11,12]]['g',[12,13]]['o',[13,14]]['o',[14,15]]['\u000D',[15,16]]['\u000A',[16,17]]"); + => Test("""" + $""" + goo + {1} + """ + """", @"[' ',[10,11]][' ',[11,12]]['g',[12,13]]['o',[13,14]]['o',[14,15]]['\u000D',[15,16]]['\u000A',[16,17]]"); [Fact] public void TestMultiLineInterpolatedRawString25() - => Test(@"$"""""" - goo - {1} - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[19,20]][' ',[20,21]]"); + => Test("""" + $""" + goo + {1} + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[19,20]][' ',[20,21]]"); [Fact] public void TestMultiLineInterpolatedRawString26() - => Test(@"$"""""" - goo - {1} - """"""", @"[' ',[10,11]][' ',[11,12]]['g',[12,13]]['o',[13,14]]['o',[14,15]]['\u000D',[15,16]]['\u000A',[16,17]][' ',[21,22]][' ',[22,23]]"); + => Test("""" + $""" + goo + {1} + """ + """", @"[' ',[10,11]][' ',[11,12]]['g',[12,13]]['o',[13,14]]['o',[14,15]]['\u000D',[15,16]]['\u000A',[16,17]][' ',[21,22]][' ',[22,23]]"); [Fact] public void TestMultiLineInterpolatedRawString27() - => Test(@"$"""""" + => Test("""" + $""" - goo - {1} - """"""", @"['\u000D',[6,7]]['\u000A',[7,8]]['g',[12,13]]['o',[13,14]]['o',[14,15]]['\u000D',[15,16]]['\u000A',[16,17]]"); + goo + {1} + """ + """", @"['\u000D',[6,7]]['\u000A',[7,8]]['g',[12,13]]['o',[13,14]]['o',[14,15]]['\u000D',[15,16]]['\u000A',[16,17]]"); [Fact] public void TestMultiLineInterpolatedRawString28() - => Test(@"$"""""" - - goo - {1} - """"""", @"['\u000D',[10,11]]['\u000A',[11,12]]['g',[16,17]]['o',[17,18]]['o',[18,19]]['\u000D',[19,20]]['\u000A',[20,21]]"); + => Test("""" + $""" + + goo + {1} + """ + """", @"['\u000D',[10,11]]['\u000A',[11,12]]['g',[16,17]]['o',[17,18]]['o',[18,19]]['\u000D',[19,20]]['\u000A',[20,21]]"); [Fact] public void TestMultiLineInterpolatedRawString29() - => Test(@"$"""""" - - goo - {1} - """"""", @"[' ',[10,11]][' ',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]]['g',[18,19]]['o',[19,20]]['o',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]"); + => Test("""" + $""" + + goo + {1} + """ + """", @"[' ',[10,11]][' ',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]]['g',[18,19]]['o',[19,20]]['o',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]"); [Fact] public void TestMultiLineInterpolatedRawString30() - => Test(@"$"""""" - goo + => Test("""" + $""" + goo - {1} - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[15,16]]['\u000A',[16,17]]"); + {1} + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[15,16]]['\u000A',[16,17]]"); [Fact] public void TestMultiLineInterpolatedRawString31() - => Test(@"$"""""" - goo - - {1} - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[19,20]]['\u000A',[20,21]]"); + => Test("""" + $""" + goo + + {1} + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[19,20]]['\u000A',[20,21]]"); [Fact] public void TestMultiLineInterpolatedRawString32() - => Test(@"$"""""" - goo - - {1} - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[19,20]][' ',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]"); + => Test("""" + $""" + goo + + {1} + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[19,20]][' ',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]"); [Fact] public void TestMultiLineInterpolatedRawString33() - => Test(@"$"""""" - goo - {1} + => Test("""" + $""" + goo + {1} - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[22,23]]['\u000A',[23,24]]"); + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[22,23]]['\u000A',[23,24]]"); [Fact] public void TestMultiLineInterpolatedRawString34() - => Test(@"$"""""" - goo - {1} - - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[22,23]]['\u000A',[23,24]]"); + => Test("""" + $""" + goo + {1} + + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[22,23]]['\u000A',[23,24]]"); [Fact] public void TestMultiLineInterpolatedRawString35() - => Test(@"$"""""" - goo - {1} - - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[22,23]]['\u000A',[23,24]][' ',[28,29]][' ',[29,30]]"); + => Test("""" + $""" + goo + {1} + + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[22,23]]['\u000A',[23,24]][' ',[28,29]][' ',[29,30]]"); [Fact] public void TestMultiLineInterpolatedRawString36() - => Test(@"$"""""" - - goo - {1} - - """"""", @"[' ',[10,11]][' ',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]]['g',[18,19]]['o',[19,20]]['o',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]['\u000D',[30,31]]['\u000A',[31,32]][' ',[36,37]][' ',[37,38]]"); + => Test("""" + $""" + + goo + {1} + + """ + """", @"[' ',[10,11]][' ',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]]['g',[18,19]]['o',[19,20]]['o',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]['\u000D',[30,31]]['\u000A',[31,32]][' ',[36,37]][' ',[37,38]]"); [Fact] public void TestMultiLineInterpolatedRawString37() - => Test(@"$"""""" - - goo - - {1} - - """"""", @"[' ',[10,11]][' ',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]]['g',[18,19]]['o',[19,20]]['o',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]][' ',[27,28]][' ',[28,29]]['\u000D',[29,30]]['\u000A',[30,31]]['\u000D',[38,39]]['\u000A',[39,40]][' ',[44,45]][' ',[45,46]]"); + => Test("""" + $""" + + goo + + {1} + + """ + """", @"[' ',[10,11]][' ',[11,12]]['\u000D',[12,13]]['\u000A',[13,14]]['g',[18,19]]['o',[19,20]]['o',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]][' ',[27,28]][' ',[28,29]]['\u000D',[29,30]]['\u000A',[30,31]]['\u000D',[38,39]]['\u000A',[39,40]][' ',[44,45]][' ',[45,46]]"); [Fact] public void TestMultiLineInterpolatedRawString38() - => Test(@"$"""""" - - goo - - {1} - - """"""", @"[' ',[12,13]][' ',[13,14]]['\u000D',[14,15]]['\u000A',[15,16]]['g',[20,21]]['o',[21,22]]['o',[22,23]]['\u000D',[23,24]]['\u000A',[24,25]][' ',[29,30]][' ',[30,31]]['\u000D',[31,32]]['\u000A',[32,33]]['\u000D',[40,41]]['\u000A',[41,42]][' ',[46,47]][' ',[47,48]]"); + => Test("""" + $""" + + goo + + {1} + + """ + """", @"[' ',[12,13]][' ',[13,14]]['\u000D',[14,15]]['\u000A',[15,16]]['g',[20,21]]['o',[21,22]]['o',[22,23]]['\u000D',[23,24]]['\u000A',[24,25]][' ',[29,30]][' ',[30,31]]['\u000D',[31,32]]['\u000A',[32,33]]['\u000D',[40,41]]['\u000A',[41,42]][' ',[46,47]][' ',[47,48]]"); [Fact] public void TestMultiLineInterpolatedRawString39() - => Test(@"$"""""" - goo{1}bar - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['b',[16,17]]['a',[17,18]]['r',[18,19]]"); + => Test("""" + $""" + goo{1}bar + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['b',[16,17]]['a',[17,18]]['r',[18,19]]"); [Fact] public void TestMultiLineInterpolatedRawString39_b() - => Test(@"$$"""""" - goo{{1}}bar - """"""", @"['g',[11,12]]['o',[12,13]]['o',[13,14]]['b',[19,20]]['a',[20,21]]['r',[21,22]]"); + => Test("""" + $$""" + goo{{1}}bar + """ + """", @"['g',[11,12]]['o',[12,13]]['o',[13,14]]['b',[19,20]]['a',[20,21]]['r',[21,22]]"); [Fact] public void TestMultiLineInterpolatedRawString40() - => Test(@"$"""""" - goo - {1}bar - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['b',[22,23]]['a',[23,24]]['r',[24,25]]"); + => Test("""" + $""" + goo + {1}bar + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['b',[22,23]]['a',[23,24]]['r',[24,25]]"); [Fact] public void TestMultiLineInterpolatedRawString41() - => Test(@"$"""""" - goo{1} - bar - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[16,17]]['\u000A',[17,18]]['b',[22,23]]['a',[23,24]]['r',[24,25]]"); + => Test("""" + $""" + goo{1} + bar + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[16,17]]['\u000A',[17,18]]['b',[22,23]]['a',[23,24]]['r',[24,25]]"); [Fact] public void TestMultiLineInterpolatedRawString42() - => Test(@"$"""""" - goo - {1} - bar - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[22,23]]['\u000A',[23,24]]['b',[28,29]]['a',[29,30]]['r',[30,31]]"); + => Test("""" + $""" + goo + {1} + bar + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[22,23]]['\u000A',[23,24]]['b',[28,29]]['a',[29,30]]['r',[30,31]]"); [Fact] public void TestMultiLineInterpolatedRawString43() - => Test(@"$"""""" - goo - {1} - bar - """"""", @"[' ',[10,11]][' ',[11,12]]['g',[12,13]]['o',[13,14]]['o',[14,15]]['\u000D',[15,16]]['\u000A',[16,17]]['\u000D',[24,25]]['\u000A',[25,26]]['b',[30,31]]['a',[31,32]]['r',[32,33]]"); + => Test("""" + $""" + goo + {1} + bar + """ + """", @"[' ',[10,11]][' ',[11,12]]['g',[12,13]]['o',[13,14]]['o',[14,15]]['\u000D',[15,16]]['\u000A',[16,17]]['\u000D',[24,25]]['\u000A',[25,26]]['b',[30,31]]['a',[31,32]]['r',[32,33]]"); [Fact] public void TestMultiLineInterpolatedRawString44() - => Test(@"$"""""" - goo - {1} - bar - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[19,20]][' ',[20,21]]['\u000D',[24,25]]['\u000A',[25,26]]['b',[30,31]]['a',[31,32]]['r',[32,33]]"); + => Test("""" + $""" + goo + {1} + bar + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[19,20]][' ',[20,21]]['\u000D',[24,25]]['\u000A',[25,26]]['b',[30,31]]['a',[31,32]]['r',[32,33]]"); [Fact] public void TestMultiLineInterpolatedRawString45() - => Test(@"$"""""" - goo - {1} - bar - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[22,23]]['\u000A',[23,24]][' ',[28,29]][' ',[29,30]]['b',[30,31]]['a',[31,32]]['r',[32,33]]"); + => Test("""" + $""" + goo + {1} + bar + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[22,23]]['\u000A',[23,24]][' ',[28,29]][' ',[29,30]]['b',[30,31]]['a',[31,32]]['r',[32,33]]"); [Fact] public void TestMultiLineInterpolatedRawString46() - => Test(@"$"""""" - goo + => Test("""" + $""" + goo - {1} - bar - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[15,16]]['\u000A',[16,17]]['\u000D',[24,25]]['\u000A',[25,26]]['b',[30,31]]['a',[31,32]]['r',[32,33]]"); + {1} + bar + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[15,16]]['\u000A',[16,17]]['\u000D',[24,25]]['\u000A',[25,26]]['b',[30,31]]['a',[31,32]]['r',[32,33]]"); [Fact] public void TestMultiLineInterpolatedRawString47() - => Test(@"$"""""" - goo - - {1} - bar - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[19,20]]['\u000A',[20,21]]['\u000D',[28,29]]['\u000A',[29,30]]['b',[34,35]]['a',[35,36]]['r',[36,37]]"); + => Test("""" + $""" + goo + + {1} + bar + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]]['\u000D',[19,20]]['\u000A',[20,21]]['\u000D',[28,29]]['\u000A',[29,30]]['b',[34,35]]['a',[35,36]]['r',[36,37]]"); [Fact] public void TestMultiLineInterpolatedRawString48() - => Test(@"$"""""" - goo - - {1} - bar - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[19,20]][' ',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]['\u000D',[30,31]]['\u000A',[31,32]]['b',[36,37]]['a',[37,38]]['r',[38,39]]"); + => Test("""" + $""" + goo + + {1} + bar + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[19,20]][' ',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]['\u000D',[30,31]]['\u000A',[31,32]]['b',[36,37]]['a',[37,38]]['r',[38,39]]"); [Fact] public void TestMultiLineInterpolatedRawString49() - => Test(@"$"""""" - goo - - {1} + => Test("""" + $""" + goo + + {1} - bar - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[19,20]][' ',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]['\u000D',[30,31]]['\u000A',[31,32]]['\u000D',[32,33]]['\u000A',[33,34]]['b',[38,39]]['a',[39,40]]['r',[40,41]]"); + bar + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[19,20]][' ',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]['\u000D',[30,31]]['\u000A',[31,32]]['\u000D',[32,33]]['\u000A',[33,34]]['b',[38,39]]['a',[39,40]]['r',[40,41]]"); [Fact] public void TestMultiLineInterpolatedRawString50() - => Test(@"$"""""" - goo - - {1} - - bar - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[19,20]][' ',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]['\u000D',[30,31]]['\u000A',[31,32]]['\u000D',[36,37]]['\u000A',[37,38]]['b',[42,43]]['a',[43,44]]['r',[44,45]]"); + => Test("""" + $""" + goo + + {1} + + bar + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[19,20]][' ',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]['\u000D',[30,31]]['\u000A',[31,32]]['\u000D',[36,37]]['\u000A',[37,38]]['b',[42,43]]['a',[43,44]]['r',[44,45]]"); [Fact] public void TestMultiLineInterpolatedRawString51() - => Test(@"$"""""" - goo - - {1} - - bar - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[19,20]][' ',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]['\u000D',[30,31]]['\u000A',[31,32]][' ',[36,37]][' ',[37,38]]['\u000D',[38,39]]['\u000A',[39,40]]['b',[44,45]]['a',[45,46]]['r',[46,47]]"); + => Test("""" + $""" + goo + + {1} + + bar + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[19,20]][' ',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]['\u000D',[30,31]]['\u000A',[31,32]][' ',[36,37]][' ',[37,38]]['\u000D',[38,39]]['\u000A',[39,40]]['b',[44,45]]['a',[45,46]]['r',[46,47]]"); [Fact] public void TestMultiLineInterpolatedRawString52() - => Test(@"$"""""" - goo - - {1} - - bar + => Test("""" + $""" + goo + + {1} + + bar - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[19,20]][' ',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]['\u000D',[30,31]]['\u000A',[31,32]][' ',[36,37]][' ',[37,38]]['\u000D',[38,39]]['\u000A',[39,40]]['b',[44,45]]['a',[45,46]]['r',[46,47]]['\u000D',[47,48]]['\u000A',[48,49]]"); + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[19,20]][' ',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]['\u000D',[30,31]]['\u000A',[31,32]][' ',[36,37]][' ',[37,38]]['\u000D',[38,39]]['\u000A',[39,40]]['b',[44,45]]['a',[45,46]]['r',[46,47]]['\u000D',[47,48]]['\u000A',[48,49]]"); [Fact] public void TestMultiLineInterpolatedRawString53() - => Test(@"$"""""" - goo - - {1} - - bar - - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[19,20]][' ',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]['\u000D',[30,31]]['\u000A',[31,32]][' ',[36,37]][' ',[37,38]]['\u000D',[38,39]]['\u000A',[39,40]]['b',[44,45]]['a',[45,46]]['r',[46,47]]['\u000D',[47,48]]['\u000A',[48,49]]"); + => Test("""" + $""" + goo + + {1} + + bar + + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[19,20]][' ',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]['\u000D',[30,31]]['\u000A',[31,32]][' ',[36,37]][' ',[37,38]]['\u000D',[38,39]]['\u000A',[39,40]]['b',[44,45]]['a',[45,46]]['r',[46,47]]['\u000D',[47,48]]['\u000A',[48,49]]"); [Fact] public void TestMultiLineInterpolatedRawString54() - => Test(@"$"""""" - goo - - {1} - - bar - - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[19,20]][' ',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]['\u000D',[30,31]]['\u000A',[31,32]][' ',[36,37]][' ',[37,38]]['\u000D',[38,39]]['\u000A',[39,40]]['b',[44,45]]['a',[45,46]]['r',[46,47]]['\u000D',[47,48]]['\u000A',[48,49]][' ',[53,54]][' ',[54,55]]"); + => Test("""" + $""" + goo + + {1} + + bar + + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['\u000D',[13,14]]['\u000A',[14,15]][' ',[19,20]][' ',[20,21]]['\u000D',[21,22]]['\u000A',[22,23]]['\u000D',[30,31]]['\u000A',[31,32]][' ',[36,37]][' ',[37,38]]['\u000D',[38,39]]['\u000A',[39,40]]['b',[44,45]]['a',[45,46]]['r',[46,47]]['\u000D',[47,48]]['\u000A',[48,49]][' ',[53,54]][' ',[54,55]]"); [Fact] public void TestMultiLineInterpolatedRawString55() - => Test(@"$"""""" - goo{1}bar{2}baz - """"""", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['b',[16,17]]['a',[17,18]]['r',[18,19]]['b',[22,23]]['a',[23,24]]['z',[24,25]]"); + => Test("""" + $""" + goo{1}bar{2}baz + """ + """", @"['g',[10,11]]['o',[11,12]]['o',[12,13]]['b',[16,17]]['a',[17,18]]['r',[18,19]]['b',[22,23]]['a',[23,24]]['z',[24,25]]"); [Fact] public void TestMultiLineInterpolatedRawString55_b() - => Test(@"$$$"""""" - goo{{{1}}}bar{{{2}}}baz - """"""", @"['g',[12,13]]['o',[13,14]]['o',[14,15]]['b',[22,23]]['a',[23,24]]['r',[24,25]]['b',[32,33]]['a',[33,34]]['z',[34,35]]"); + => Test("""" + $$$""" + goo{{{1}}}bar{{{2}}}baz + """ + """", @"['g',[12,13]]['o',[13,14]]['o',[14,15]]['b',[22,23]]['a',[23,24]]['r',[24,25]]['b',[32,33]]['a',[33,34]]['z',[34,35]]"); [Fact] public void TestMultiLineInterpolatedRawString56() - => Test(@"$"""""" - goo{1}bar{2}baz - """"""", @"['g',[12,13]]['o',[13,14]]['o',[14,15]]['b',[18,19]]['a',[19,20]]['r',[20,21]]['b',[24,25]]['a',[25,26]]['z',[26,27]]"); + => Test("""" + $""" + goo{1}bar{2}baz + """ + """", @"['g',[12,13]]['o',[13,14]]['o',[14,15]]['b',[18,19]]['a',[19,20]]['r',[20,21]]['b',[24,25]]['a',[25,26]]['z',[26,27]]"); [Fact] public void TestMultiLineInterpolatedRawString57() - => Test(@"$"""""" - goo - - {1} - - bar{2} - - baz - """"""", @"['g',[12,13]]['o',[13,14]]['o',[14,15]]['\u000D',[15,16]]['\u000A',[16,17]]['\u000D',[17,18]]['\u000A',[18,19]]['\u000D',[26,27]]['\u000A',[27,28]]['\u000D',[32,33]]['\u000A',[33,34]][' ',[38,39]][' ',[39,40]]['b',[40,41]]['a',[41,42]]['r',[42,43]]['\u000D',[46,47]]['\u000A',[47,48]][' ',[52,53]][' ',[53,54]][' ',[54,55]][' ',[55,56]]['\u000D',[56,57]]['\u000A',[57,58]][' ',[62,63]][' ',[63,64]][' ',[64,65]][' ',[65,66]][' ',[66,67]][' ',[67,68]][' ',[68,69]][' ',[69,70]]['b',[70,71]]['a',[71,72]]['z',[72,73]]"); + => Test("""" + $""" + goo + + {1} + + bar{2} + + baz + """ + """", @"['g',[12,13]]['o',[13,14]]['o',[14,15]]['\u000D',[15,16]]['\u000A',[16,17]]['\u000D',[17,18]]['\u000A',[18,19]]['\u000D',[26,27]]['\u000A',[27,28]]['\u000D',[32,33]]['\u000A',[33,34]][' ',[38,39]][' ',[39,40]]['b',[40,41]]['a',[41,42]]['r',[42,43]]['\u000D',[46,47]]['\u000A',[47,48]][' ',[52,53]][' ',[53,54]][' ',[54,55]][' ',[55,56]]['\u000D',[56,57]]['\u000A',[57,58]][' ',[62,63]][' ',[63,64]][' ',[64,65]][' ',[65,66]][' ',[66,67]][' ',[67,68]][' ',[68,69]][' ',[69,70]]['b',[70,71]]['a',[71,72]]['z',[72,73]]"); } diff --git a/src/Workspaces/CSharpTest/Formatting/CSharpFormattingTestBase.cs b/src/Workspaces/CSharpTest/Formatting/CSharpFormattingTestBase.cs index 481000073bcce..dd9c5eced1189 100644 --- a/src/Workspaces/CSharpTest/Formatting/CSharpFormattingTestBase.cs +++ b/src/Workspaces/CSharpTest/Formatting/CSharpFormattingTestBase.cs @@ -3,8 +3,8 @@ // See the LICENSE file in the project root for more information. using System.Collections.Generic; -using System.Threading.Tasks; using System.Diagnostics.CodeAnalysis; +using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests.Formatting; @@ -13,10 +13,7 @@ namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Formatting; public class CSharpFormattingTestBase : FormattingTestBase { - private Workspace? _ws; - - protected Workspace DefaultWorkspace - => _ws ??= new AdhocWorkspace(); + protected Workspace DefaultWorkspace { get => field ??= new AdhocWorkspace(); private set; } protected override SyntaxNode ParseCompilation(string text, ParseOptions? parseOptions) => SyntaxFactory.ParseCompilationUnit(text, options: (CSharpParseOptions?)parseOptions); diff --git a/src/Workspaces/CSharpTest/Formatting/EditorConfigOptionParserTests.cs b/src/Workspaces/CSharpTest/Formatting/EditorConfigOptionParserTests.cs index 1f9e2d0a1eccc..ee5e6e089173b 100644 --- a/src/Workspaces/CSharpTest/Formatting/EditorConfigOptionParserTests.cs +++ b/src/Workspaces/CSharpTest/Formatting/EditorConfigOptionParserTests.cs @@ -37,7 +37,7 @@ internal void TestParseSpacingWithinParenthesesList(string list, SpacePlacementW InlineData("before_and_after", BinaryOperatorSpacingOptions.Single)] public void TestParseEditorConfigSpacingAroundBinaryOperatorTrue(string value, BinaryOperatorSpacingOptions expectedResult) { - Assert.True(CSharpFormattingOptions2.ParseEditorConfigSpacingAroundBinaryOperator(value) == expectedResult, + Assert.True(CSharpFormattingOptions2.ParseEditorConfigSpacingAroundBinaryOperator(value) == (BinaryOperatorSpacingOptionsInternal)expectedResult, $"Expected option {value} to be parsed as set."); } @@ -47,7 +47,7 @@ public void TestParseEditorConfigSpacingAroundBinaryOperatorTrue(string value, B InlineData("before_and_after,ignore")] public void TestParseEditorConfigSpacingAroundBinaryOperatorFalse(string value) { - Assert.True(CSharpFormattingOptions2.ParseEditorConfigSpacingAroundBinaryOperator(value) == BinaryOperatorSpacingOptions.Single, + Assert.True(CSharpFormattingOptions2.ParseEditorConfigSpacingAroundBinaryOperator(value) == BinaryOperatorSpacingOptionsInternal.Single, $"Expected option {value} to be parsed as default option."); } @@ -57,7 +57,7 @@ public void TestParseEditorConfigSpacingAroundBinaryOperatorFalse(string value) InlineData("one_less_than_current", LabelPositionOptions.OneLess)] public void TestParseEditorConfigLabelPositioningTrue(string value, LabelPositionOptions expectedValue) { - Assert.True(CSharpFormattingOptions2.ParseEditorConfigLabelPositioning(value) == expectedValue, + Assert.True(CSharpFormattingOptions2.ParseEditorConfigLabelPositioning(value) == (LabelPositionOptionsInternal)expectedValue, $"Expected option {value} to be parsed as set."); } @@ -67,7 +67,7 @@ public void TestParseEditorConfigLabelPositioningTrue(string value, LabelPositio InlineData("one_less_thancurrent")] public void TestParseEditorConfigLabelPositioningFalse(string value) { - Assert.True(CSharpFormattingOptions2.ParseEditorConfigLabelPositioning(value) == LabelPositionOptions.NoIndent, + Assert.True(CSharpFormattingOptions2.ParseEditorConfigLabelPositioning(value) == LabelPositionOptionsInternal.NoIndent, $"Expected option {value} to be parsed default"); } diff --git a/src/Workspaces/CSharpTest/Formatting/FormattingElasticTriviaTests.cs b/src/Workspaces/CSharpTest/Formatting/FormattingElasticTriviaTests.cs index fbe7799616997..92d02e6e0f510 100644 --- a/src/Workspaces/CSharpTest/Formatting/FormattingElasticTriviaTests.cs +++ b/src/Workspaces/CSharpTest/Formatting/FormattingElasticTriviaTests.cs @@ -25,24 +25,6 @@ public sealed class FormattingEngineElasticTriviaTests : CSharpFormattingTestBas [Fact(Skip = "530167")] public void FormatElasticTrivia() { - var expected = @"extern alias A1; - -#line 99 - -[assembly: My] - -class My : System.Attribute -{ -} - -class A -{ -} - -[My] -class B -{ -}"; var compilation = CompilationUnit( externs: [ExternAliasDirective("A1")], usings: default, @@ -87,23 +69,42 @@ class B using var workspace = new AdhocWorkspace(); var newCompilation = Formatter.Format(compilation, workspace.Services.SolutionServices, CSharpSyntaxFormattingOptions.Default, CancellationToken.None); - Assert.Equal(expected, newCompilation.ToFullString()); + Assert.Equal(""" + extern alias A1; + + #line 99 + + [assembly: My] + + class My : System.Attribute + { + } + + class A + { + } + + [My] + class B + { + } + """, newCompilation.ToFullString()); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1947")] public void ElasticLineBreaksBetweenMembers() { - var text = @" -public class C -{ - public string f1; + var text = """ + public class C + { + public string f1; - // example comment - public string f2; -} + // example comment + public string f2; + } -public class SomeAttribute : System.Attribute { } -"; + public class SomeAttribute : System.Attribute { } + """; var workspace = new AdhocWorkspace(); var generator = SyntaxGenerator.GetGenerator(workspace, LanguageNames.CSharp); @@ -113,18 +114,18 @@ public class SomeAttribute : System.Attribute { } var newRoot = root.ReplaceNode(decl, newDecl); var options = CSharpSyntaxFormattingOptions.Default; - var expected = @" -public class C -{ - public string f1; + var expected = """ + public class C + { + public string f1; - // example comment - [Some] - public string f2; -} + // example comment + [Some] + public string f2; + } -public class SomeAttribute : System.Attribute { } -"; + public class SomeAttribute : System.Attribute { } + """; var formatted = Formatter.Format(newRoot, workspace.Services.SolutionServices, options, CancellationToken.None).ToFullString(); Assert.Equal(expected, formatted); @@ -139,12 +140,6 @@ public class SomeAttribute : System.Attribute { } [Fact, WorkItem("https://roslyn.codeplex.com/workitem/408")] public void FormatElasticTriviaBetweenPropertiesWithoutAccessors() { - var expected = @"class PropertyTest -{ - string MyProperty => ""42""; - - string MyProperty => ""42""; -}"; var property = PropertyDeclaration( attributeLists: default, modifiers: [], @@ -183,6 +178,13 @@ public void FormatElasticTriviaBetweenPropertiesWithoutAccessors() using var workspace = new AdhocWorkspace(); var newCompilation = Formatter.Format(compilation, workspace.Services.SolutionServices, CSharpSyntaxFormattingOptions.Default, CancellationToken.None); - Assert.Equal(expected, newCompilation.ToFullString()); + Assert.Equal(""" + class PropertyTest + { + string MyProperty => "42"; + + string MyProperty => "42"; + } + """, newCompilation.ToFullString()); } } diff --git a/src/Workspaces/CSharpTest/Formatting/FormattingMultipleSpanTests.cs b/src/Workspaces/CSharpTest/Formatting/FormattingMultipleSpanTests.cs index 9c89bfda443f3..6f9ead626e3b3 100644 --- a/src/Workspaces/CSharpTest/Formatting/FormattingMultipleSpanTests.cs +++ b/src/Workspaces/CSharpTest/Formatting/FormattingMultipleSpanTests.cs @@ -22,138 +22,127 @@ namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Formatting; public sealed class FormattingEngineMultiSpanTests : CSharpFormattingTestBase { [Fact] - public async Task EndOfLine() - { - var content = @"namespace A{/*1*/}/*2*/"; - var expected = @"namespace A{}"; - - await AssertFormatAsync(content, expected); - } + public Task EndOfLine() + => AssertFormatAsync(@"namespace A{/*1*/}/*2*/", @"namespace A{}"); [Fact] public async Task Simple1() => await AssertFormatAsync("namespace A/*1*/{}/*2*/ class A {}", "namespace A{ } class A {}"); [Fact] - public async Task DoNotFormatTriviaOutsideOfSpan_IncludingTrailingTriviaOnNewLine() - { - var content = @"namespace A -/*1*/{ - }/*2*/ - -class A /*1*/{}/*2*/"; - - var expected = @"namespace A -{ -} - -class A { }"; + public Task DoNotFormatTriviaOutsideOfSpan_IncludingTrailingTriviaOnNewLine() + => AssertFormatAsync(""" + namespace A + /*1*/{ + }/*2*/ + + class A /*1*/{}/*2*/ + """, """ + namespace A + { + } - await AssertFormatAsync(content, expected); - } + class A { } + """); [Fact] - public async Task FormatIncludingTrivia() - { - var content = @"namespace A -/*1*/{ - } /*2*/ - -class A /*1*/{}/*2*/"; - - var expected = @"namespace A -{ -} - -class A { }"; + public Task FormatIncludingTrivia() + => AssertFormatAsync(""" + namespace A + /*1*/{ + } /*2*/ + + class A /*1*/{}/*2*/ + """, """ + namespace A + { + } - await AssertFormatAsync(content, expected); - } + class A { } + """); [Fact] - public async Task MergeSpanAndFormat() - { - var content = @"namespace A -/*1*/{ - } /*2*/ /*1*/ - -class A{}/*2*/"; - - var expected = @"namespace A -{ -} - -class A { }"; + public Task MergeSpanAndFormat() + => AssertFormatAsync(""" + namespace A + /*1*/{ + } /*2*/ /*1*/ + + class A{}/*2*/ + """, """ + namespace A + { + } - await AssertFormatAsync(content, expected); - } + class A { } + """); [Fact] - public async Task OverlappedSpan() - { - var content = @"namespace A -/*1*/{ - /*1*/ } /*2*/ - -class A{}/*2*/"; - - var expected = @"namespace A -{ -} - -class A { }"; + public Task OverlappedSpan() + => AssertFormatAsync(""" + namespace A + /*1*/{ + /*1*/ } /*2*/ + + class A{}/*2*/ + """, """ + namespace A + { + } - await AssertFormatAsync(content, expected); - } + class A { } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554160")] public async Task FormatSpanNullReference01() { - var code = @"/*1*/class C -{ - void F() - { - System.Console.WriteLine(); - } -}/*2*/"; - - var expected = @"class C -{ - void F() - { - System.Console.WriteLine(); - } -}"; var changingOptions = new OptionsCollection(LanguageNames.CSharp) { { CSharpFormattingOptions2.IndentBlock, false } }; - await AssertFormatAsync(code, expected, changedOptionSet: changingOptions); + await AssertFormatAsync(""" + /*1*/class C + { + void F() + { + System.Console.WriteLine(); + } + }/*2*/ + """, """ + class C + { + void F() + { + System.Console.WriteLine(); + } + } + """, changedOptionSet: changingOptions); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554160")] public async Task FormatSpanNullReference02() { - var code = @"class C/*1*/ -{ - void F() - { - System.Console.WriteLine(); - } -}/*2*/"; - - var expected = @"class C -{ - void F() - { - System.Console.WriteLine(); - } -}"; var changingOptions = new OptionsCollection(LanguageNames.CSharp) { { CSharpFormattingOptions2.WrappingPreserveSingleLine, false } }; - await AssertFormatAsync(code, expected, changedOptionSet: changingOptions); + await AssertFormatAsync(""" + class C/*1*/ + { + void F() + { + System.Console.WriteLine(); + } + }/*2*/ + """, """ + class C + { + void F() + { + System.Console.WriteLine(); + } + } + """, changedOptionSet: changingOptions); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539231")] diff --git a/src/Workspaces/CSharpTest/Formatting/FormattingTests.cs b/src/Workspaces/CSharpTest/Formatting/FormattingTests.cs index bf3025d67ebad..017e939694037 100644 --- a/src/Workspaces/CSharpTest/Formatting/FormattingTests.cs +++ b/src/Workspaces/CSharpTest/Formatting/FormattingTests.cs @@ -26,76 +26,48 @@ public async Task Format1() => await AssertFormatAsync("namespace A { }", "namespace A{}"); [Fact] - public async Task Format2() - { - var content = """ - class A { - } - """; - - var expected = """ + public Task Format2() + => AssertFormatAsync(""" class A { } - """; - await AssertFormatAsync(expected, content); - } + """, """ + class A { + } + """); [Fact] - public async Task Format3() - { - var content = """ - class A - { - int i = 20 ; } - """; - - var expected = """ + public Task Format3() + => AssertFormatAsync(""" class A { int i = 20; } - """; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task Format4() - { - var content = """ + """, """ class A { - int i = 20 ; int j = 1 + 2 ; - T . S = Test ( 10 ) ; - } - """; + int i = 20 ; } + """); - var expected = """ + [Fact] + public Task Format4() + => AssertFormatAsync(""" class A { int i = 20; int j = 1 + 2; T.S = Test( 10 ); } - """; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task Format5() - { - var content = """ + """, """ class A { - List < int > Method < TArg , TArg2 > ( TArg a, TArg2 b ) - { int i = 20 ; int j = 1 + 2 ; T . S = Test ( 10 ) ; - } } - """; + } + """); - var expected = """ + [Fact] + public Task Format5() + => AssertFormatAsync(""" class A { List Method(TArg a, TArg2 b) @@ -104,24 +76,19 @@ List Method(TArg a, TArg2 b) T.S = Test(10); } } - """; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task Format6() - { - var content = """ + """, """ class A { - A a = new A { - Property1 = 1, Property2 = 3, - Property3 = { 1 , 2 , 3 } }; - } - """; + List < int > Method < TArg , TArg2 > ( TArg a, TArg2 b ) + { + int i = 20 ; int j = 1 + 2 ; + T . S = Test ( 10 ) ; + } } + """); - var expected = """ + [Fact] + public Task Format6() + => AssertFormatAsync(""" class A { A a = new A @@ -131,50 +98,32 @@ class A Property3 = { 1, 2, 3 } }; } - """; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task Format7() - { - var content = """ + """, """ class A { - var a = from i in new [ ] { 1 , 2 , 3 } where i > 10 select i ; - } - """; + A a = new A { + Property1 = 1, Property2 = 3, + Property3 = { 1 , 2 , 3 } }; + } + """); - var expected = """ + [Fact] + public Task Format7() + => AssertFormatAsync(""" class A { var a = from i in new[] { 1, 2, 3 } where i > 10 select i; } - """; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task Format8() - { - var content = """ + """, """ class A { - void Method() - { - if (true) - { - } - else if (false) - { - } - } + var a = from i in new [ ] { 1 , 2 , 3 } where i > 10 select i ; } - """; + """); - var expected = """ + [Fact] + public Task Format8() + => AssertFormatAsync(""" class A { void Method() @@ -187,25 +136,24 @@ void Method() } } } - """; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task Format9() - { - var content = """ + """, """ class A { void Method() { - if (true) { } else if (false) { } + if (true) + { + } + else if (false) + { + } } } - """; + """); - var expected = """ + [Fact] + public Task Format9() + => AssertFormatAsync(""" class A { void Method() @@ -213,38 +161,36 @@ void Method() if (true) { } else if (false) { } } } - """; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task Format10() - { - var content = """ + """, """ class A { - var a = from i in new [ ] { 1 , 2 , 3 } - where i > 10 select i ; + void Method() + { + if (true) { } else if (false) { } } - """; + } + """); - var expected = """ + [Fact] + public Task Format10() + => AssertFormatAsync(""" class A { var a = from i in new[] { 1, 2, 3 } where i > 10 select i; } - """; - - await AssertFormatAsync(expected, content); - } + """, """ + class A + { + var a = from i in new [ ] { 1 , 2 , 3 } + where i > 10 select i ; + } + """); [Fact] - public async Task ObjectInitializer() - { - await AssertFormatAsync(""" + public Task ObjectInitializer() + => AssertFormatAsync(""" public class C { public C() @@ -275,12 +221,10 @@ public C() } } """); - } [Fact] - public async Task AnonymousType() - { - await AssertFormatAsync(""" + public Task AnonymousType() + => AssertFormatAsync(""" class C { C() @@ -313,12 +257,10 @@ class C } } """); - } [Fact] - public async Task MultilineLambda() - { - await AssertFormatAsync(""" + public Task MultilineLambda() + => AssertFormatAsync(""" class C { C() @@ -351,12 +293,10 @@ class C } } """); - } [Fact] - public async Task AnonymousMethod() - { - await AssertFormatAsync(""" + public Task AnonymousMethod() + => AssertFormatAsync(""" class C { C() @@ -379,12 +319,10 @@ class C } } """); - } [Fact] - public async Task Scen1() - { - await AssertFormatAsync(""" + public Task Scen1() + => AssertFormatAsync(""" namespace Namespace1 { class Program @@ -450,12 +388,10 @@ static void Method(int i, string s, bool b) } } """); - } [Fact] - public async Task Scen2() - { - await AssertFormatAsync(""" + public Task Scen2() + => AssertFormatAsync(""" namespace MyNamespace { class Class1 @@ -750,12 +686,10 @@ public void Method(T t) } } """); - } [Fact] - public async Task Scen3() - { - await AssertFormatAsync(""" + public Task Scen3() + => AssertFormatAsync(""" namespace Namespace1 { class Program @@ -778,12 +712,10 @@ static void Main() } } """); - } [Fact] - public async Task Scen4() - { - await AssertFormatAsync(""" + public Task Scen4() + => AssertFormatAsync(""" class Class1 { // public void goo() @@ -802,12 +734,10 @@ class Class1 // } } """); - } [Fact] - public async Task Scen5() - { - await AssertFormatAsync(""" + public Task Scen5() + => AssertFormatAsync(""" class Class1 { public void Method() @@ -830,12 +760,10 @@ public void Method() } } """); - } [Fact] - public async Task Scen6() - { - await AssertFormatAsync(""" + public Task Scen6() + => AssertFormatAsync(""" namespace Namespace1 { class OuterClass @@ -856,12 +784,10 @@ class InnerClass } } """); - } [Fact] - public async Task Scen7() - { - await AssertFormatAsync(""" + public Task Scen7() + => AssertFormatAsync(""" class Class1 { public void Method() @@ -896,12 +822,10 @@ public void Method() } } """); - } [Fact] - public async Task Scen8() - { - await AssertFormatAsync(""" + public Task Scen8() + => AssertFormatAsync(""" class Class1 { public void Method() @@ -918,12 +842,10 @@ public void Method() } } """); - } [Fact] - public async Task IndentStatementsInMethod() - { - await AssertFormatAsync(""" + public Task IndentStatementsInMethod() + => AssertFormatAsync(""" class C { void Goo() @@ -944,12 +866,10 @@ void Goo() } } """); - } [Fact] - public async Task IndentFieldsInClass() - { - await AssertFormatAsync(""" + public Task IndentFieldsInClass() + => AssertFormatAsync(""" class C { int a = 10; @@ -964,12 +884,10 @@ class C int c; } """); - } [Fact] - public async Task IndentUserDefaultSettingTest() - { - await AssertFormatAsync(""" + public Task IndentUserDefaultSettingTest() + => AssertFormatAsync(""" class Class2 { public void nothing() @@ -1048,7 +966,6 @@ public void nothing_again(Action a) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766133")] public async Task RelativeIndentationToFirstTokenInBaseTokenWithObjectInitializers() @@ -1605,9 +1522,8 @@ void M() } [Fact] - public async Task TestWrappingDefault() - { - await AssertFormatAsync(""" + public Task TestWrappingDefault() + => AssertFormatAsync(""" class Class5 { delegate void Del(int x); @@ -1646,7 +1562,6 @@ void bar() } } """); - } [Fact] public async Task TestWrappingNonDefault_FormatBlock() @@ -1908,9 +1823,8 @@ static void Main(string[] args) } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/751789")] - public async Task NewLineForOpenBracesDefault() - { - await AssertFormatAsync(""" + public Task NewLineForOpenBracesDefault() + => AssertFormatAsync(""" class f00 { void br() @@ -2040,7 +1954,6 @@ public class goo : System.Object } } """); - } [Fact, WorkItem("https://developercommunity.visualstudio.com/content/problem/8808/c-structure-guide-lines-for-unsafe-fixed.html")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/751789")] @@ -2175,9 +2088,8 @@ public class goo : System.Object } [Fact] - public async Task NewLineForKeywordDefault() - { - await AssertFormatAsync(""" + public Task NewLineForKeywordDefault() + => AssertFormatAsync(""" class c { void f00() @@ -2233,7 +2145,6 @@ void f00(){ } } """); - } [Fact] public async Task NewLineForKeywordNonDefault() @@ -2342,9 +2253,8 @@ void Method() } [Fact] - public async Task NewLineForExpressionDefault() - { - await AssertFormatAsync(""" + public Task NewLineForExpressionDefault() + => AssertFormatAsync(""" class f00 { void br() @@ -2410,7 +2320,6 @@ from o in c.Orders orderby o.Total descending } } """); - } [Fact] public async Task NewLineForExpressionNonDefault() @@ -2483,9 +2392,8 @@ from o in c.Orders orderby o.Total descending } [Fact] - public async Task Enums_Bug2586() - { - await AssertFormatAsync(""" + public Task Enums_Bug2586() + => AssertFormatAsync(""" enum E { a = 10, @@ -2500,16 +2408,14 @@ enum E c } """); - } [Fact] public async Task DoNotInsertLineBreaksInSingleLineEnum() => await AssertFormatAsync(@"enum E { a = 10, b, c }", @"enum E { a = 10, b, c }"); [Fact] - public async Task AlreadyFormattedSwitchIsNotFormatted_Bug2588() - { - await AssertFormatAsync(""" + public Task AlreadyFormattedSwitchIsNotFormatted_Bug2588() + => AssertFormatAsync(""" class C { void M() @@ -2534,12 +2440,10 @@ void M() } } """); - } [Fact] - public async Task BreaksAreAlignedInSwitchCasesFormatted_Bug2587() - { - await AssertFormatAsync(""" + public Task BreaksAreAlignedInSwitchCasesFormatted_Bug2587() + => AssertFormatAsync(""" class C { void M() @@ -2564,12 +2468,10 @@ void M() } } """); - } [Fact] - public async Task BreaksAndBracesAreAlignedInSwitchCasesWithBracesFormatted_Bug2587() - { - await AssertFormatAsync(""" + public Task BreaksAndBracesAreAlignedInSwitchCasesWithBracesFormatted_Bug2587() + => AssertFormatAsync(""" class C { void M() @@ -2598,12 +2500,10 @@ void M() } } """); - } [Fact] - public async Task LineBreaksAreNotInsertedForSwitchCasesOnASingleLine1() - { - await AssertFormatAsync(""" + public Task LineBreaksAreNotInsertedForSwitchCasesOnASingleLine1() + => AssertFormatAsync(""" class C { void M() @@ -2628,12 +2528,10 @@ void M() } } """); - } [Fact] - public async Task LineBreaksAreNotInsertedForSwitchCasesOnASingleLine2() - { - await AssertFormatAsync(""" + public Task LineBreaksAreNotInsertedForSwitchCasesOnASingleLine2() + => AssertFormatAsync(""" class C { void M() @@ -2658,12 +2556,10 @@ void M() } } """); - } [Fact] - public async Task FormatLabelAndGoto1_Bug2588() - { - await AssertFormatAsync(""" + public Task FormatLabelAndGoto1_Bug2588() + => AssertFormatAsync(""" class C { void M() @@ -2682,12 +2578,10 @@ void M() } } """); - } [Fact] - public async Task FormatLabelAndGoto2_Bug2588() - { - await AssertFormatAsync(""" + public Task FormatLabelAndGoto2_Bug2588() + => AssertFormatAsync(""" class C { void M() @@ -2708,12 +2602,10 @@ void M() } } """); - } [Fact] - public async Task FormatNestedLabelAndGoto1_Bug2588() - { - await AssertFormatAsync(""" + public Task FormatNestedLabelAndGoto1_Bug2588() + => AssertFormatAsync(""" class C { void M() @@ -2738,12 +2630,10 @@ void M() } } """); - } [Fact] - public async Task FormatNestedLabelAndGoto2_Bug2588() - { - await AssertFormatAsync(""" + public Task FormatNestedLabelAndGoto2_Bug2588() + => AssertFormatAsync(""" class C { void M() @@ -2770,12 +2660,10 @@ void M() } } """); - } [Fact] - public async Task AlreadyFormattedGotoLabelIsNotFormatted1_Bug2588() - { - await AssertFormatAsync(""" + public Task AlreadyFormattedGotoLabelIsNotFormatted1_Bug2588() + => AssertFormatAsync(""" class C { void M() @@ -2794,12 +2682,10 @@ void M() } } """); - } [Fact] - public async Task AlreadyFormattedGotoLabelIsNotFormatted2_Bug2588() - { - await AssertFormatAsync(""" + public Task AlreadyFormattedGotoLabelIsNotFormatted2_Bug2588() + => AssertFormatAsync(""" class C { void M() @@ -2816,12 +2702,10 @@ void M() } } """); - } [Fact] - public async Task AlreadyFormattedGotoLabelIsNotFormatted3_Bug2588() - { - await AssertFormatAsync(""" + public Task AlreadyFormattedGotoLabelIsNotFormatted3_Bug2588() + => AssertFormatAsync(""" class C { void M() @@ -2842,12 +2726,10 @@ void M() } } """); - } [Fact] - public async Task DoNotAddLineBreakBeforeWhere1_Bug2582() - { - await AssertFormatAsync(""" + public Task DoNotAddLineBreakBeforeWhere1_Bug2582() + => AssertFormatAsync(""" class C { void M() where T : I @@ -2862,12 +2744,10 @@ void M() where T : I } } """); - } [Fact] - public async Task DoNotAddLineBreakBeforeWhere2_Bug2582() - { - await AssertFormatAsync(""" + public Task DoNotAddLineBreakBeforeWhere2_Bug2582() + => AssertFormatAsync(""" class C where T : I { } @@ -2876,12 +2756,10 @@ class C where T : I { } """); - } [Fact] - public async Task DoNotAddSpaceAfterUnaryMinus() - { - await AssertFormatAsync(""" + public Task DoNotAddSpaceAfterUnaryMinus() + => AssertFormatAsync(""" class C { void M() @@ -2898,12 +2776,10 @@ void M() } } """); - } [Fact] - public async Task DoNotAddSpaceAfterUnaryPlus() - { - await AssertFormatAsync(""" + public Task DoNotAddSpaceAfterUnaryPlus() + => AssertFormatAsync(""" class C { void M() @@ -2920,7 +2796,6 @@ void M() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545909")] public async Task DoNotAddSpaceAfterIncrement() @@ -2983,9 +2858,8 @@ void M(int[] i) } [Fact] - public async Task Anchoring() - { - await AssertFormatAsync(""" + public Task Anchoring() + => AssertFormatAsync(""" class C { void M() @@ -3006,12 +2880,10 @@ void M() } } """); - } [Fact] - public async Task Exclamation() - { - await AssertFormatAsync(""" + public Task Exclamation() + => AssertFormatAsync(""" class C { void M() @@ -3028,12 +2900,10 @@ void M() } } """); - } [Fact] - public async Task StartAndEndTrivia() - { - await AssertFormatAsync(""" + public Task StartAndEndTrivia() + => AssertFormatAsync(""" @@ -3054,12 +2924,10 @@ class C { } """); - } [Fact] - public async Task FirstTriviaAndAnchoring1() - { - await AssertFormatAsync(""" + public Task FirstTriviaAndAnchoring1() + => AssertFormatAsync(""" namespace N { @@ -3095,12 +2963,10 @@ void Method() { """); - } [Fact] - public async Task FirstTriviaAndAnchoring2() - { - await AssertFormatAsync(""" + public Task FirstTriviaAndAnchoring2() + => AssertFormatAsync(""" namespace N { @@ -3131,12 +2997,10 @@ class C { """); - } [Fact] - public async Task FirstTriviaAndAnchoring3() - { - await AssertFormatAsync(""" + public Task FirstTriviaAndAnchoring3() + => AssertFormatAsync(""" class C @@ -3164,12 +3028,10 @@ class C { """); - } [Fact] - public async Task Base1() - { - await AssertFormatAsync(""" + public Task Base1() + => AssertFormatAsync(""" class C { C() : base() @@ -3184,12 +3046,10 @@ class C } } """); - } [Fact] - public async Task This1() - { - await AssertFormatAsync(""" + public Task This1() + => AssertFormatAsync(""" class C { C(int i) : this() @@ -3208,12 +3068,10 @@ class C C ( ) { } } """); - } [Fact] - public async Task QueryExpression1() - { - await AssertFormatAsync(""" + public Task QueryExpression1() + => AssertFormatAsync(""" class C { int Method() @@ -3232,12 +3090,10 @@ int Method() } } """); - } [Fact] - public async Task QueryExpression2() - { - await AssertFormatAsync(""" + public Task QueryExpression2() + => AssertFormatAsync(""" class C { int Method() @@ -3260,12 +3116,10 @@ select b } } """); - } [Fact] - public async Task QueryExpression3() - { - await AssertFormatAsync(""" + public Task QueryExpression3() + => AssertFormatAsync(""" class C { int Method() @@ -3294,12 +3148,10 @@ from b in Get(1 + } } """); - } [Fact] - public async Task QueryExpression4() - { - await AssertFormatAsync(""" + public Task QueryExpression4() + => AssertFormatAsync(""" class C { int Method() @@ -3324,12 +3176,10 @@ select b } } """); - } [Fact] - public async Task Label1() - { - await AssertFormatAsync(""" + public Task Label1() + => AssertFormatAsync(""" class C { int Method() @@ -3346,12 +3196,10 @@ int Method() } } """); - } [Fact] - public async Task Label2() - { - await AssertFormatAsync(""" + public Task Label2() + => AssertFormatAsync(""" class C { int Method() @@ -3370,12 +3218,10 @@ int Method() } } """); - } [Fact] - public async Task Label3() - { - await AssertFormatAsync(""" + public Task Label3() + => AssertFormatAsync(""" class C { int Method() @@ -3396,12 +3242,10 @@ int Method() } } """); - } [Fact] - public async Task Label4() - { - await AssertFormatAsync(""" + public Task Label4() + => AssertFormatAsync(""" class C { int Method() @@ -3422,12 +3266,10 @@ int Method() } } """); - } [Fact] - public async Task Label5() - { - await AssertFormatAsync(""" + public Task Label5() + => AssertFormatAsync(""" class C { int Method() @@ -3446,12 +3288,10 @@ int Method() } } """); - } [Fact] - public async Task Label6() - { - await AssertFormatAsync(""" + public Task Label6() + => AssertFormatAsync(""" class C { int Method() @@ -3472,12 +3312,10 @@ int Method() } } """); - } [Fact] - public async Task Label7() - { - await AssertFormatAsync(""" + public Task Label7() + => AssertFormatAsync(""" class C { int Method() @@ -3500,12 +3338,10 @@ int Method() } } """); - } [Fact] - public async Task Label8() - { - await AssertFormatAsync(""" + public Task Label8() + => AssertFormatAsync(""" class C { int Method() @@ -3526,12 +3362,10 @@ int Method() } } """); - } [Fact] - public async Task AutoProperty() - { - await AssertFormatAsync(""" + public Task AutoProperty() + => AssertFormatAsync(""" class Class { private int Age { get; set; } @@ -3544,12 +3378,10 @@ class Class public string Names { get; set;} } """); - } [Fact] - public async Task NormalPropertyGet() - { - await AssertFormatAsync(""" + public Task NormalPropertyGet() + => AssertFormatAsync(""" class Class { private string name; @@ -3574,12 +3406,10 @@ public string Names } } """); - } [Fact] - public async Task NormalPropertyBoth() - { - await AssertFormatAsync(""" + public Task NormalPropertyBoth() + => AssertFormatAsync(""" class Class { private string name; @@ -3612,12 +3442,10 @@ public string Names } } """); - } [Fact] - public async Task ErrorHandling1() - { - await AssertFormatAsync(""" + public Task ErrorHandling1() + => AssertFormatAsync(""" class C { int Method() @@ -3634,12 +3462,10 @@ int Method() } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537763")] - public async Task NullableType() - { - await AssertFormatAsync(""" + public Task NullableType() + => AssertFormatAsync(""" class Program { static void Main(string[] args) @@ -3656,12 +3482,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537766")] - public async Task SuppressWrappingOnBraces() - { - await AssertFormatAsync(""" + public Task SuppressWrappingOnBraces() + => AssertFormatAsync(""" class Class1 { } @@ -3670,12 +3494,10 @@ class Class1 {} """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537824")] - public async Task DoWhile() - { - await AssertFormatAsync(""" + public Task DoWhile() + => AssertFormatAsync(""" public class Class1 { void Goo() @@ -3698,12 +3520,10 @@ void Goo() } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537774")] - public async Task SuppressWrappingBug() - { - await AssertFormatAsync(""" + public Task SuppressWrappingBug() + => AssertFormatAsync(""" class Class1 { int Goo() @@ -3721,12 +3541,10 @@ int Goo() } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537768")] - public async Task PreserveLineForAttribute() - { - await AssertFormatAsync(""" + public Task PreserveLineForAttribute() + => AssertFormatAsync(""" class Class1 { [STAThread] @@ -3745,12 +3563,10 @@ static void Main(string[] args) } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537878")] - public async Task NoFormattingOnMissingTokens() - { - await AssertFormatAsync(""" + public Task NoFormattingOnMissingTokens() + => AssertFormatAsync(""" namespace ClassLibrary1 { class Class1 @@ -3775,12 +3591,10 @@ void Goo() } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537783")] - public async Task UnaryExpression() - { - await AssertFormatAsync(""" + public Task UnaryExpression() + => AssertFormatAsync(""" class Program { static void Main(string[] args) @@ -3801,12 +3615,10 @@ static void Main(string[] args) } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537885")] - public async Task Pointer() - { - await AssertFormatAsync(""" + public Task Pointer() + => AssertFormatAsync(""" class Program { static void Main(string[] args) @@ -3825,7 +3637,6 @@ static void Main(string[] args) } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50723")] public async Task TuplePointer() @@ -3845,9 +3656,8 @@ public static void Main(string[] args) } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537886")] - public async Task Tild() - { - await AssertFormatAsync(""" + public Task Tild() + => AssertFormatAsync(""" class Program { static void Main(string[] args) @@ -3868,12 +3678,10 @@ static void Main(string[] args) } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537884")] - public async Task ArrayInitializer1() - { - await AssertFormatAsync(""" + public Task ArrayInitializer1() + => AssertFormatAsync(""" class Program { static void Main(string[] args) @@ -3896,12 +3704,10 @@ static void Main(string[] args) } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537884")] - public async Task ArrayInitializer2() - { - await AssertFormatAsync(""" + public Task ArrayInitializer2() + => AssertFormatAsync(""" class Program { static void Main(string[] args) @@ -3924,12 +3730,10 @@ static void Main(string[] args) } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537884")] - public async Task ImplicitArrayInitializer() - { - await AssertFormatAsync(""" + public Task ImplicitArrayInitializer() + => AssertFormatAsync(""" class Program { static void Main(string[] args) @@ -3952,12 +3756,10 @@ static void Main(string[] args) } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65498")] - public async Task StackAllocArrayInitializer0() - { - await AssertFormatAsync(""" + public Task StackAllocArrayInitializer0() + => AssertFormatAsync(""" F(stackalloc int[] { 1, @@ -3970,12 +3772,10 @@ await AssertFormatAsync(""" 2, } ); """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65498")] - public async Task StackAllocArrayInitializer0_Implicit() - { - await AssertFormatAsync(""" + public Task StackAllocArrayInitializer0_Implicit() + => AssertFormatAsync(""" F(stackalloc[] { 1, @@ -3990,12 +3790,10 @@ await AssertFormatAsync(""" } ); """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65498")] - public async Task StackAllocArrayInitializer1() - { - await AssertFormatAsync(""" + public Task StackAllocArrayInitializer1() + => AssertFormatAsync(""" F( stackalloc int[] { @@ -4012,12 +3810,10 @@ stackalloc int[] } ); """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65498")] - public async Task StackAllocArrayInitializer1_Implicit() - { - await AssertFormatAsync(""" + public Task StackAllocArrayInitializer1_Implicit() + => AssertFormatAsync(""" F( stackalloc[] { @@ -4034,12 +3830,10 @@ stackalloc [] } ); """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65498")] - public async Task StackAllocArrayInitializer2() - { - await AssertFormatAsync(""" + public Task StackAllocArrayInitializer2() + => AssertFormatAsync(""" var x = (stackalloc int[] {1,2, 3 }); @@ -4048,12 +3842,10 @@ await AssertFormatAsync(""" 3 }); """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65498")] - public async Task StackAllocArrayInitializer2_Implicit() - { - await AssertFormatAsync(""" + public Task StackAllocArrayInitializer2_Implicit() + => AssertFormatAsync(""" var x = (stackalloc[] {1, 2, 3 @@ -4064,12 +3856,10 @@ await AssertFormatAsync(""" 2, 3 }); """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537884")] - public async Task CollectionInitializer() - { - await AssertFormatAsync(""" + public Task CollectionInitializer() + => AssertFormatAsync(""" class Program { static void Main(string[] args) @@ -4092,12 +3882,10 @@ static void Main(string[] args) } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537916")] - public async Task AddressOfOperator() - { - await AssertFormatAsync(""" + public Task AddressOfOperator() + => AssertFormatAsync(""" unsafe class Class1 { void Method() @@ -4118,12 +3906,10 @@ void Method() } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537885")] - public async Task DereferenceOperator() - { - await AssertFormatAsync(""" + public Task DereferenceOperator() + => AssertFormatAsync(""" unsafe class Class1 { void Method() @@ -4146,21 +3932,17 @@ void Method() } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537905")] - public async Task Namespaces() - { - await AssertFormatAsync(""" + public Task Namespaces() + => AssertFormatAsync(""" using System; using System.Data; """, @"using System; using System.Data;"); - } [Fact] - public async Task NamespaceDeclaration() - { - await AssertFormatAsync(""" + public Task NamespaceDeclaration() + => AssertFormatAsync(""" namespace N { } @@ -4169,12 +3951,10 @@ namespace N { } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537902")] - public async Task DoWhile1() - { - await AssertFormatAsync(""" + public Task DoWhile1() + => AssertFormatAsync(""" class Program { static void Main(string[] args) @@ -4193,12 +3973,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task NewConstraint() - { - await AssertFormatAsync(""" + public Task NewConstraint() + => AssertFormatAsync(""" class Program { void Test(T t) where T : new() @@ -4213,12 +3991,10 @@ class Program } } """); - } [Fact] - public async Task UnaryExpressionWithInitializer() - { - await AssertFormatAsync(""" + public Task UnaryExpressionWithInitializer() + => AssertFormatAsync(""" using System; using System.Collections.Generic; using System.Linq; @@ -4249,12 +4025,10 @@ static void Main(string[] args) } } """); - } [Fact] - public async Task Attributes1() - { - await AssertFormatAsync(""" + public Task Attributes1() + => AssertFormatAsync(""" class Program { [Flags] public void Method() { } @@ -4265,12 +4039,10 @@ class Program [ Flags ] public void Method ( ) { } } """); - } [Fact] - public async Task Attributes2() - { - await AssertFormatAsync(""" + public Task Attributes2() + => AssertFormatAsync(""" class Program { [Flags] @@ -4283,12 +4055,10 @@ [ Flags ] public void Method ( ) { } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538288")] - public async Task ColonColon1() - { - await AssertFormatAsync(""" + public Task ColonColon1() + => AssertFormatAsync(""" class Program { public void Method() @@ -4304,12 +4074,10 @@ public void Method ( ) { } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538354")] - public async Task BugFix3939() - { - await AssertFormatAsync(""" + public Task BugFix3939() + => AssertFormatAsync(""" using System. Collections. @@ -4320,16 +4088,14 @@ await AssertFormatAsync(""" Collections. Generic; """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538354")] public async Task Tab1() => await AssertFormatAsync(@"using System;", @" using System;"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538329")] - public async Task SuppressLinkBreakInIfElseStatement() - { - await AssertFormatAsync(""" + public Task SuppressLinkBreakInIfElseStatement() + => AssertFormatAsync(""" class Program { static void Main(string[] args) @@ -4350,12 +4116,10 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538464")] - public async Task BugFix4087() - { - await AssertFormatAsync(""" + public Task BugFix4087() + => AssertFormatAsync(""" class Program { static void Main(string[] args) @@ -4372,53 +4136,40 @@ static void Main(string[] args) } } """); - } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538511")] - public async Task AttributeTargetSpecifier() - { - var code = """ + public Task AttributeTargetSpecifier() + => AssertFormatAsync(""" public class Class1 { - [method : + [method: void Test() { } } - """; - - var expected = """ + """, """ public class Class1 { - [method: + [method : void Test() { } } - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538635")] - public async Task Finalizer() - { - var code = """ + public Task Finalizer() + => AssertFormatAsync(""" public class Class1 { - ~ Class1() { } + ~Class1() { } } - """; - - var expected = """ + """, """ public class Class1 { - ~Class1() { } + ~ Class1() { } } - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538743")] public async Task BugFix4442() @@ -4439,230 +4190,184 @@ static void Main(string[] args) } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538658")] - public async Task BugFix4328() - { - var code = """ + public Task BugFix4328() + => AssertFormatAsync(""" class Program { static void Main(string[] args) { - double d = new double (); + double d = new double(); } } - """; - var expected = """ + """, """ class Program { static void Main(string[] args) { - double d = new double(); + double d = new double (); } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538658")] - public async Task BugFix4515() - { - var code = """ + public Task BugFix4515() + => AssertFormatAsync(""" class Program { static void Main(string[] args) { - var t = typeof ( System.Object ) ; - var t1 = default ( System.Object ) ; - var t2 = sizeof ( System.Object ) ; + var t = typeof(System.Object); + var t1 = default(System.Object); + var t2 = sizeof(System.Object); } } - """; - var expected = """ + """, """ class Program { static void Main(string[] args) { - var t = typeof(System.Object); - var t1 = default(System.Object); - var t2 = sizeof(System.Object); + var t = typeof ( System.Object ) ; + var t1 = default ( System.Object ) ; + var t2 = sizeof ( System.Object ) ; } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact] - public async Task CastExpressionTest() - { - var code = """ + public Task CastExpressionTest() + => AssertFormatAsync(""" class Program { static void Main(string[] args) { - var a = (int) 1; + var a = (int)1; } } - """; - var expected = """ + """, """ class Program { static void Main(string[] args) { - var a = (int)1; + var a = (int) 1; } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact] - public async Task NamedParameter() - { - var code = """ + public Task NamedParameter() + => AssertFormatAsync(""" class Program { static void Main(string[] args) { - Main ( args : null ) ; + Main(args: null); } } - """; - var expected = """ + """, """ class Program { static void Main(string[] args) { - Main(args: null); + Main ( args : null ) ; } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact] - public async Task RefReadonlyParameters() - { - var code = """ + public Task RefReadonlyParameters() + => AssertFormatAsync(""" class C { - int this [ ref readonly int x , ref readonly int y ] { get ; set ; } - void M ( ref readonly int x , ref readonly int y ) { } + int this[ref readonly int x, ref readonly int y] { get; set; } + void M(ref readonly int x, ref readonly int y) { } } - """; - var expected = """ + """, """ class C { - int this[ref readonly int x, ref readonly int y] { get; set; } - void M(ref readonly int x, ref readonly int y) { } + int this [ ref readonly int x , ref readonly int y ] { get ; set ; } + void M ( ref readonly int x , ref readonly int y ) { } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539259")] - public async Task BugFix5143() - { - var code = """ + public Task BugFix5143() + => AssertFormatAsync(""" class Program { static void Main(string[] args) { - int x = Goo ( - delegate ( int x ) { return x ; } ) ; + int x = Goo( + delegate (int x) { return x; }); } } - """; - var expected = """ + """, """ class Program { static void Main(string[] args) { - int x = Goo( - delegate (int x) { return x; }); + int x = Goo ( + delegate ( int x ) { return x ; } ) ; } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539338")] - public async Task BugFix5251() - { - var code = """ + public Task BugFix5251() + => AssertFormatAsync(""" class Program { - public static string Goo { get; private set; } + public static string Goo { get; private set; } } - """; - var expected = """ + """, """ class Program { - public static string Goo { get; private set; } + public static string Goo { get; private set; } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539358")] - public async Task BugFix5277() - { - var code = """ + public Task BugFix5277() + => AssertFormatAsync(""" #if true - #endif + #endif - """; - var expected = """ + """, """ #if true - #endif + #endif - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539542")] - public async Task BugFix5544() - { - var code = """ + public Task BugFix5544() + => AssertFormatAsync(""" class Program { unsafe static void Main(string[] args) { Program* p; - p -> Goo = 5; + p->Goo = 5; } } - """; - var expected = """ + """, """ class Program { unsafe static void Main(string[] args) { Program* p; - p->Goo = 5; + p -> Goo = 5; } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539587")] - public async Task BugFix5602() - { - var code = """ - class Bug - { - public static void func() - { - long b = // - } - } - """; - var expected = """ + public Task BugFix5602() + => AssertFormatAsync(""" class Bug { public static void func() @@ -4670,60 +4375,57 @@ public static void func() long b = // } } - """; - await AssertFormatAsync(expected, code); - } + """, """ + class Bug + { + public static void func() + { + long b = // + } + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539616")] - public async Task BugFix5637() - { - var code = """ + public Task BugFix5637() + => AssertFormatAsync(""" class Bug { // test - public static void func() + public static void func() { } } - """; - var expected = """ + """, """ class Bug { // test - public static void func() + public static void func() { } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact] - public async Task GenericType() - { - var code = """ + public Task GenericType() + => AssertFormatAsync(""" class Bug { - class N : Bug< T [ ] > + class N : Bug { } } - """; - var expected = """ + """, """ class Bug { - class N : Bug + class N : Bug< T [ ] > { } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539878")] - public async Task BugFix5978() - { - var code = """ + public Task BugFix5978() + => AssertFormatAsync(""" class Program { static void Main(string[] args) @@ -4733,18 +4435,17 @@ static void Main(string[] args) if (i < 5) { label5: - if (i == 4) - { - } - else - { - System.Console.WriteLine("a"); - } + if (i == 4) + { + } + else + { + System.Console.WriteLine("a"); + } } } } - """; - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -4754,24 +4455,21 @@ static void Main(string[] args) if (i < 5) { label5: - if (i == 4) - { - } - else - { - System.Console.WriteLine("a"); - } + if (i == 4) + { + } + else + { + System.Console.WriteLine("a"); + } } } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539878")] - public async Task BugFix5979() - { - var code = """ + public Task BugFix5979() + => AssertFormatAsync(""" delegate int del(int i); class Program { @@ -4779,13 +4477,12 @@ static void Main(string[] args) { del q = x => { - label2: goto label1; - label1: return x; + label2: goto label1; + label1: return x; }; } } - """; - var expected = """ + """, """ delegate int del(int i); class Program { @@ -4793,75 +4490,64 @@ static void Main(string[] args) { del q = x => { - label2: goto label1; - label1: return x; + label2: goto label1; + label1: return x; }; } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539891")] - public async Task BugFix5993() - { - var code = """ + public Task BugFix5993() + => AssertFormatAsync(""" public class MyClass { public static void Main() { lab1: { - lab1:// CS0158 - goto lab1; + lab1:// CS0158 + goto lab1; } } } - """; - var expected = """ + """, """ public class MyClass { public static void Main() { lab1: { - lab1:// CS0158 - goto lab1; + lab1:// CS0158 + goto lab1; } } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540315")] - public async Task BugFix6536() - { - var code = """ + public Task BugFix6536() + => AssertFormatAsync(""" public class MyClass { public static void Main() { - int i = - - 1 + + + 1 + - + 1 + - + 1 ; + int i = - -1 + + +1 + -+1 + -+1; } } - """; - var expected = """ + """, """ public class MyClass { public static void Main() { - int i = - -1 + + +1 + -+1 + -+1; + int i = - - 1 + + + 1 + - + 1 + - + 1 ; } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540801")] - public async Task BugFix7211() - { - var code = """ + public Task BugFix7211() + => AssertFormatAsync(""" class Program { static void Main(string[] args) @@ -4872,9 +4558,7 @@ static void Main(string[] args) } } } - """; - - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -4885,14 +4569,11 @@ static void Main(string[] args) } } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541035")] - public async Task BugFix7564_1() - { - var code = """ + public Task BugFix7564_1() + => AssertFormatAsync(""" class Program { static void Main(string[] args) @@ -4903,9 +4584,7 @@ static void Main(string[] args) } } } - """; - - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -4916,14 +4595,11 @@ static void Main(string[] args) } } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541035")] - public async Task BugFix7564_2() - { - var code = """ + public Task BugFix7564_2() + => AssertFormatAsync(""" class Program { static void Main(string[] args) @@ -4934,9 +4610,7 @@ static void Main(string[] args) } } } - """; - - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -4947,39 +4621,31 @@ static void Main(string[] args) } } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem(8385, "DevDiv_Projects/Roslyn")] - public async Task NullCoalescingOperator() - { - var code = """ + public Task NullCoalescingOperator() + => AssertFormatAsync(""" class C { void M() { - object o2 = null??null; + object o2 = null ?? null; } } - """; - - var expected = """ + """, """ class C { void M() { - object o2 = null ?? null; + object o2 = null??null; } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541925")] - public async Task QueryContinuation() - { - var code = """ + public Task QueryContinuation() + => AssertFormatAsync(""" using System.Linq; class C { @@ -4988,12 +4654,10 @@ static void Main(string[] args) var temp = from x in "abc" let z = x.ToString() select z into w - select w; + select w; } } - """; - - var expected = """ + """, """ using System.Linq; class C { @@ -5002,68 +4666,55 @@ static void Main(string[] args) var temp = from x in "abc" let z = x.ToString() select z into w - select w; + select w; } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact] - public async Task QueryContinuation2() - { - var code = """ + public Task QueryContinuation2() + => AssertFormatAsync(""" using System.Linq; class C { static void Main(string[] args) { - var temp = from x in "abc" select x into + var temp = from x in "abc" + select x into } } - """; - - var expected = """ + """, """ using System.Linq; class C { static void Main(string[] args) { - var temp = from x in "abc" - select x into + var temp = from x in "abc" select x into } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542305")] - public async Task AttributeFormatting1() - { - var code = """ + public Task AttributeFormatting1() + => AssertFormatAsync(""" class Program { - void AddClass(string name,[OptionalAttribute] object position,[OptionalAttribute] object bases) + void AddClass(string name, [OptionalAttribute] object position, [OptionalAttribute] object bases) { } } - """; - - var expected = """ + """, """ class Program { - void AddClass(string name, [OptionalAttribute] object position, [OptionalAttribute] object bases) + void AddClass(string name,[OptionalAttribute] object position,[OptionalAttribute] object bases) { } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542304")] - public async Task CloseBracesInArgumentList() - { - var code = """ + public Task CloseBracesInArgumentList() + => AssertFormatAsync(""" class Program { static void Main(string[] args) @@ -5074,12 +4725,10 @@ static void Main(string[] args) var baseIndentation = this.tokenStream.GetCurrentColumn(operation.BaseToken); return baseIndentation + indentationDelta; - } , isThreadSafe: true); + }, isThreadSafe: true); } } - """; - - var expected = """ + """, """ class Program { static void Main(string[] args) @@ -5090,77 +4739,56 @@ static void Main(string[] args) var baseIndentation = this.tokenStream.GetCurrentColumn(operation.BaseToken); return baseIndentation + indentationDelta; - }, isThreadSafe: true); + } , isThreadSafe: true); } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542538")] - public async Task MissingTokens() - { - var code = """ + public Task MissingTokens() + => AssertFormatAsync(""" using System; delegate void myDelegate(int name = 1); class innerClass { public innerClass() { - myDelegate x = (int y=1) => { return; }; + myDelegate x = (int y = 1) => { return; }; } } - """; - - var expected = """ + """, """ using System; delegate void myDelegate(int name = 1); class innerClass { public innerClass() { - myDelegate x = (int y = 1) => { return; }; + myDelegate x = (int y=1) => { return; }; } } - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542199")] - public async Task ColumnOfVeryFirstToken() - { - var code = @" W )b"; - - var expected = @"W )b"; - - await AssertFormatAsync(expected, code); - } + public Task ColumnOfVeryFirstToken() + => AssertFormatAsync(@"W )b", @" W )b"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542718")] - public async Task EmptySuppressionSpan() - { - var code = """ - enum E - { - a,, - } - """; - - var expected = """ + public Task EmptySuppressionSpan() + => AssertFormatAsync(""" enum E { a,, } - """; - - await AssertFormatAsync(expected, code); - } + """, """ + enum E + { + a,, + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542790")] - public async Task LabelInSwitch() - { - var code = """ + public Task LabelInSwitch() + => AssertFormatAsync(""" class test { public static void Main() @@ -5169,17 +4797,15 @@ public static void Main() switch (target) { case "t1": - label1: - goto label1; + label1: + goto label1; case "t2": - label2: - goto label2; + label2: + goto label2; } } } - """; - - var expected = """ + """, """ class test { public static void Main() @@ -5188,37 +4814,19 @@ public static void Main() switch (target) { case "t1": - label1: - goto label1; + label1: + goto label1; case "t2": - label2: - goto label2; + label2: + goto label2; } } } - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543112")] public void FormatArbitaryNode() { - var expected = """ - public int Prop - { - get - { - return c; - } - - set - { - c = value; - } - } - """; - var property = SyntaxFactory.PropertyDeclaration( attributeLists: [], [PublicKeyword], @@ -5237,47 +4845,53 @@ public int Prop using var workspace = new AdhocWorkspace(); var newProperty = Formatter.Format(property, workspace.Services.SolutionServices, CSharpSyntaxFormattingOptions.Default, CancellationToken.None); - Assert.Equal(expected, newProperty.ToFullString()); + Assert.Equal(""" + public int Prop + { + get + { + return c; + } + + set + { + c = value; + } + } + """, newProperty.ToFullString()); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543140")] - public async Task OmittedTypeArgument() - { - var code = """ + public Task OmittedTypeArgument() + => AssertFormatAsync(""" using System; using System.Collections.Generic; using System.Linq; - + class Program { static void Main(string[] args) { - Console.WriteLine(typeof(Dictionary<, >).IsGenericTypeDefinition); + Console.WriteLine(typeof(Dictionary<,>).IsGenericTypeDefinition); } } - """; - - var expected = """ + """, """ using System; using System.Collections.Generic; using System.Linq; - + class Program { static void Main(string[] args) { - Console.WriteLine(typeof(Dictionary<,>).IsGenericTypeDefinition); + Console.WriteLine(typeof(Dictionary<, >).IsGenericTypeDefinition); } } - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543131")] - public async Task TryAfterLabel() - { - var code = """ + public Task TryAfterLabel() + => AssertFormatAsync(""" using System; class Program { @@ -5287,15 +4901,13 @@ static int Main() int sum = 0; lock (lockObj) try - { sum = 0; } - catch (Exception ex) - { Console.WriteLine(ex); } + { sum = 0; } + catch (Exception ex) + { Console.WriteLine(ex); } return sum; } } - """; - - var expected = """ + """, """ using System; class Program { @@ -5305,39 +4917,17 @@ static int Main() int sum = 0; lock (lockObj) try - { sum = 0; } - catch (Exception ex) - { Console.WriteLine(ex); } + { sum = 0; } + catch (Exception ex) + { Console.WriteLine(ex); } return sum; } } - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact] - public async Task QueryContinuation1() - { - var code = """ - using System.Linq; - - class Program - { - static void Main(string[] args) - { - var q = from arg in args - group arg by arg.Length into final - where final - .Select(c => c) - .Distinct() - .Count() > 0 - select final; - } - } - """; - - var expected = """ + public Task QueryContinuation1() + => AssertFormatAsync(""" using System.Linq; class Program @@ -5353,97 +4943,91 @@ where final select final; } } - """; + """, """ + using System.Linq; - await AssertFormatAsync(expected, code); - } + class Program + { + static void Main(string[] args) + { + var q = from arg in args + group arg by arg.Length into final + where final + .Select(c => c) + .Distinct() + .Count() > 0 + select final; + } + } + """); [Fact] - public async Task TestCSharpFormattingSpacingOptions() - { - var text = - """ + public Task TestCSharpFormattingSpacingOptions() + => AssertFormatAsync(""" interface f1 { } - interface f2 : f1 { } + interface f2 : f1 { } - struct d2 : f1 { } + struct d2 : f1 { } - class goo : System . Object + class goo : System.Object { - public int bar = 1* 2; - public void goobar ( ) + public int bar = 1 * 2; + public void goobar() { - goobar ( ); + goobar(); } - public int toofoobar( int i , int j ) + public int toofoobar(int i, int j) { - int s = ( int ) ( 34 ); - if ( i < 0 ) + int s = (int)(34); + if (i < 0) { } - return toofoobar( i,j ); + return toofoobar(i, j); } - public string parfoobar(string [ ] str) + public string parfoobar(string[] str) { - for(int i = 0 ; i < 28 ; i++) { } - return str[ 5 ]; + for (int i = 0; i < 28; i++) { } + return str[5]; } } - """; - var expectedFormattedText = - """ + """, """ interface f1 { } - interface f2 : f1 { } + interface f2 : f1 { } - struct d2 : f1 { } + struct d2 : f1 { } - class goo : System.Object + class goo : System . Object { - public int bar = 1 * 2; - public void goobar() + public int bar = 1* 2; + public void goobar ( ) { - goobar(); + goobar ( ); } - public int toofoobar(int i, int j) + public int toofoobar( int i , int j ) { - int s = (int)(34); - if (i < 0) + int s = ( int ) ( 34 ); + if ( i < 0 ) { } - return toofoobar(i, j); + return toofoobar( i,j ); } - public string parfoobar(string[] str) + public string parfoobar(string [ ] str) { - for (int i = 0; i < 28; i++) { } - return str[5]; + for(int i = 0 ; i < 28 ; i++) { } + return str[ 5 ]; } } - """; - - await AssertFormatAsync(expectedFormattedText, text); - } + """); [Fact] - public async Task SpacingFixInTokenBasedForIfAndSwitchCase() - { - var code = """ - class Class5{ - void bar() - { - if(x == 1) - x = 2; else x = 3; - switch (x) { - case 1: break; case 2: break; default: break;} - } - } - """; - var expectedCode = """ + public Task SpacingFixInTokenBasedForIfAndSwitchCase() + => AssertFormatAsync(""" class Class5 { void bar() @@ -5459,22 +5043,21 @@ void bar() } } } - """; - await AssertFormatAsync(expectedCode, code); - } - - [Fact] - public async Task SpacingInDeconstruction() - { - var code = """ + """, """ class Class5{ void bar() { - var(x,y)=(1,2); + if(x == 1) + x = 2; else x = 3; + switch (x) { + case 1: break; case 2: break; default: break;} } } - """; - var expectedCode = """ + """); + + [Fact] + public Task SpacingInDeconstruction() + => AssertFormatAsync(""" class Class5 { void bar() @@ -5482,65 +5065,58 @@ void bar() var (x, y) = (1, 2); } } - """; - - await AssertFormatAsync(expectedCode, code); - } + """, """ + class Class5{ + void bar() + { + var(x,y)=(1,2); + } + } + """); [Fact] - public async Task SpacingInNullableTuple() - { - var code = """ + public Task SpacingInNullableTuple() + => AssertFormatAsync(""" class Class5 { void bar() { - (int, string) ? x = (1, "hello"); + (int, string)? x = (1, "hello"); } } - """; - var expectedCode = """ + """, """ class Class5 { void bar() { - (int, string)? x = (1, "hello"); + (int, string) ? x = (1, "hello"); } } - """; - - await AssertFormatAsync(expectedCode, code); - } + """); [Fact] - public async Task SpacingInTupleArrayCreation() - { - var code = """ + public Task SpacingInTupleArrayCreation() + => AssertFormatAsync(""" class C { void bar() { - (string a, string b)[] ab = new(string a, string b) [1]; + (string a, string b)[] ab = new (string a, string b)[1]; } } - """; - var expectedCode = """ + """, """ class C { void bar() { - (string a, string b)[] ab = new (string a, string b)[1]; + (string a, string b)[] ab = new(string a, string b) [1]; } } - """; - - await AssertFormatAsync(expectedCode, code); - } + """); [Fact] - public async Task SpacingInTupleArrayCreation2() - { - var code = """ + public Task SpacingInTupleArrayCreation2() + => AssertFormatAsync(""" class C { void bar() @@ -5548,8 +5124,7 @@ void bar() (string a, string b)[] ab = new( } } - """; - var expectedCode = """ + """, """ class C { void bar() @@ -5557,66 +5132,45 @@ void bar() (string a, string b)[] ab = new( } } - """; - - await AssertFormatAsync(expectedCode, code); - } + """); [Fact] - public async Task SpacingInImplicitObjectCreation() - { - var code = """ + public Task SpacingInImplicitObjectCreation() + => AssertFormatAsync(""" class C { void bar() { - C a = new (); + C a = new(); } } - """; - var expectedCode = """ + """, """ class C { void bar() { - C a = new(); + C a = new (); } } - """; - - await AssertFormatAsync(expectedCode, code); - } + """); [Fact] - public async Task FormatRecursivePattern_Positional() - { - var code = """ + public Task FormatRecursivePattern_Positional() + => AssertFormatAsync(""" class C { - void M() { _ = this is ( 1 , 2 ) ; } + void M() { _ = this is (1, 2); } } - """; - var expectedCode = """ + """, """ class C { - void M() { _ = this is (1, 2); } + void M() { _ = this is ( 1 , 2 ) ; } } - """; - - await AssertFormatAsync(expectedCode, code); - } + """); [Fact] - public async Task FormatRecursivePattern_Positional_Singleline() - { - var code = """ - class C - { - void M() { - _ = this is ( 1 , 2 ) ; } - } - """; - var expectedCode = """ + public Task FormatRecursivePattern_Positional_Singleline() + => AssertFormatAsync(""" class C { void M() @@ -5624,24 +5178,17 @@ void M() _ = this is (1, 2); } } - """; - - await AssertFormatAsync(expectedCode, code); - } - - [Fact] - public async Task FormatRecursivePattern_Positional_Multiline() - { - var code = """ + """, """ class C { void M() { - _ = this is ( 1 , - 2 , - 3 ) ; } + _ = this is ( 1 , 2 ) ; } } - """; - var expectedCode = """ + """); + + [Fact] + public Task FormatRecursivePattern_Positional_Multiline() + => AssertFormatAsync(""" class C { void M() @@ -5651,14 +5198,7 @@ void M() 3); } } - """; - await AssertFormatAsync(expectedCode, code); - } - - [Fact] - public async Task FormatRecursivePattern_Positional_Multiline2() - { - var code = """ + """, """ class C { void M() { @@ -5666,8 +5206,11 @@ void M() { 2 , 3 ) ; } } - """; - var expectedCode = """ + """); + + [Fact] + public Task FormatRecursivePattern_Positional_Multiline2() + => AssertFormatAsync(""" class C { void M() @@ -5677,24 +5220,19 @@ void M() 3); } } - """; - await AssertFormatAsync(expectedCode, code); - } - - [Fact] - public async Task FormatRecursivePattern_Positional_Multiline3() - { - var code = """ + """, """ class C { void M() { - _ = this is - ( 1 , + _ = this is ( 1 , 2 , 3 ) ; } } - """; - var expectedCode = """ + """); + + [Fact] + public Task FormatRecursivePattern_Positional_Multiline3() + => AssertFormatAsync(""" class C { void M() @@ -5705,23 +5243,20 @@ void M() 3); } } - """; - await AssertFormatAsync(expectedCode, code); - } - - [Fact] - public async Task FormatRecursivePattern_Positional_Multiline4() - { - var code = """ + """, """ class C { void M() { _ = this is ( 1 , - 2 , 3 ) ; } + 2 , + 3 ) ; } } - """; - var expectedCode = """ + """); + + [Fact] + public Task FormatRecursivePattern_Positional_Multiline4() + => AssertFormatAsync(""" class C { void M() @@ -5731,33 +5266,45 @@ void M() 2, 3); } } - """; - await AssertFormatAsync(expectedCode, code); - } + """, """ + class C + { + void M() { + _ = this is + ( 1 , + 2 , 3 ) ; } + } + """); [Fact] - public async Task FormatRecursivePattern_Properties_Singleline() - { - var code = """ + public Task FormatRecursivePattern_Properties_Singleline() + => AssertFormatAsync(""" class C { - void M() { _ = this is C{ P1 : 1 } ; } + void M() { _ = this is C { P1: 1 }; } } - """; - var expectedCode = """ + """, """ class C { - void M() { _ = this is C { P1: 1 }; } + void M() { _ = this is C{ P1 : 1 } ; } } - """; - - await AssertFormatAsync(expectedCode, code); - } + """); [Fact] - public async Task FormatRecursivePattern_Properties_Multiline() - { - var code = """ + public Task FormatRecursivePattern_Properties_Multiline() + => AssertFormatAsync(""" + class C + { + void M() + { + _ = this is + { + P1: 1, + P2: 2 + }; + } + } + """, """ class C { void M() { @@ -5768,8 +5315,11 @@ void M() { } ; } } - """; - var expectedCode = """ + """); + + [Fact] + public Task FormatRecursivePattern_Properties_Multiline2() + => AssertFormatAsync(""" class C { void M() @@ -5781,15 +5331,7 @@ void M() }; } } - """; - - await AssertFormatAsync(expectedCode, code); - } - - [Fact] - public async Task FormatRecursivePattern_Properties_Multiline2() - { - var code = """ + """, """ class C { void M() { @@ -5799,8 +5341,11 @@ void M() { } ; } } - """; - var expectedCode = """ + """); + + [Fact] + public Task FormatRecursivePattern_Properties_Multiline3() + => AssertFormatAsync(""" class C { void M() @@ -5808,19 +5353,11 @@ void M() _ = this is { P1: 1, - P2: 2 + P2: 2, P3: 3 }; } } - """; - - await AssertFormatAsync(expectedCode, code); - } - - [Fact] - public async Task FormatRecursivePattern_Properties_Multiline3() - { - var code = """ + """, """ class C { void M() { @@ -5830,46 +5367,25 @@ void M() { } ; } } - """; - var expectedCode = """ + """); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27268")] + public Task FormatRecursivePattern_NoSpaceBetweenTypeAndPositionalSubpattern() + => AssertFormatAsync(""" class C { void M() { - _ = this is - { - P1: 1, - P2: 2, P3: 3 - }; + _ = this is C(1, 2) { }; } } - """; - - await AssertFormatAsync(expectedCode, code); - } - - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27268")] - public async Task FormatRecursivePattern_NoSpaceBetweenTypeAndPositionalSubpattern() - { - var code = """ + """, """ class C { void M() { _ = this is C( 1 , 2 ){} ; } } - """; - var expectedCode = """ - class C - { - void M() - { - _ = this is C(1, 2) { }; - } - } - """; - // no space separates the type and the positional pattern - await AssertFormatAsync(expectedCode, code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27268")] public async Task FormatRecursivePattern_PreferSpaceBetweenTypeAndPositionalSubpattern() @@ -5878,14 +5394,7 @@ public async Task FormatRecursivePattern_PreferSpaceBetweenTypeAndPositionalSubp { { CSharpFormattingOptions2.SpaceAfterMethodCallName, true } }; - var code = """ - class C - { - void M() { - _ = this is C( 1 , 2 ){} ; } - } - """; - var expectedCode = """ + await AssertFormatAsync(""" class C { void M() @@ -5893,8 +5402,13 @@ void M() _ = this is C (1, 2) { }; } } - """; - await AssertFormatAsync(expectedCode, code, changedOptionSet: changingOptions); + """, """ + class C + { + void M() { + _ = this is C( 1 , 2 ){} ; } + } + """, changedOptionSet: changingOptions); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27268")] @@ -5904,15 +5418,7 @@ public async Task FormatRecursivePattern_PreferSpaceInsidePositionalSubpatternPa { { CSharpFormattingOptions2.SpaceWithinMethodCallParentheses, true } }; - var code = """ - class C - { - void M() { - _ = this is C( 1 , 2 ){} ; - _ = this is C( ){} ; } - } - """; - var expectedCode = """ + await AssertFormatAsync(""" class C { void M() @@ -5921,8 +5427,14 @@ void M() _ = this is C() { }; } } - """; - await AssertFormatAsync(expectedCode, code, changedOptionSet: changingOptions); + """, """ + class C + { + void M() { + _ = this is C( 1 , 2 ){} ; + _ = this is C( ){} ; } + } + """, changedOptionSet: changingOptions); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/27268")] @@ -5932,15 +5444,7 @@ public async Task FormatRecursivePattern_PreferSpaceInsideEmptyPositionalSubpatt { { CSharpFormattingOptions2.SpaceBetweenEmptyMethodCallParentheses, true } }; - var code = """ - class C - { - void M() { - _ = this is C( 1 , 2 ){} ; - _ = this is C( ){} ; } - } - """; - var expectedCode = """ + await AssertFormatAsync(""" class C { void M() @@ -5949,8 +5453,14 @@ void M() _ = this is C( ) { }; } } - """; - await AssertFormatAsync(expectedCode, code, changedOptionSet: changingOptions); + """, """ + class C + { + void M() { + _ = this is C( 1 , 2 ){} ; + _ = this is C( ){} ; } + } + """, changedOptionSet: changingOptions); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/34683")] @@ -5975,9 +5485,18 @@ void M() } [Fact] - public async Task FormatPropertyPattern_MultilineAndEmpty() - { - var code = """ + public Task FormatPropertyPattern_MultilineAndEmpty() + => AssertFormatAsync(""" + class C + { + void M() + { + _ = this is + { + }; + } + } + """, """ class C { void M() { @@ -5986,25 +5505,25 @@ void M() { }; } } - """; - var expectedCode = """ + """); + + [Fact] + public Task FormatSwitchExpression_IndentArms() + => AssertFormatAsync(""" class C { void M() { - _ = this is + _ = this switch { + { P1: 1 } => true, + (0, 1) => true, + _ => false }; + } } - """; - await AssertFormatAsync(expectedCode, code); - } - - [Fact] - public async Task FormatSwitchExpression_IndentArms() - { - var code = """ + """, """ class C { void M() { @@ -6017,29 +5536,20 @@ void M() { } } - """; - var expectedCode = """ + """); + + [Fact] + public Task FormatPropertyPattern_FollowedByInvocation() + => AssertFormatAsync(""" class C { void M() { - _ = this switch - { - { P1: 1 } => true, - (0, 1) => true, - _ => false - }; - + _ = this is { } + M(); } } - """; - await AssertFormatAsync(expectedCode, code); - } - - [Fact] - public async Task FormatPropertyPattern_FollowedByInvocation() - { - var code = """ + """, """ class C { void M() { @@ -6047,25 +5557,20 @@ void M() { M(); } } - """; - var expectedCode = """ + """); + + [Fact] + public Task FormatPositionalPattern_FollowedByInvocation() + => AssertFormatAsync(""" class C { void M() { - _ = this is { } + _ = this is (1, 2) { } M(); } } - """; - // although 'M' will be parsed into the pattern on line above, we should not wrap the pattern - await AssertFormatAsync(expectedCode, code); - } - - [Fact] - public async Task FormatPositionalPattern_FollowedByInvocation() - { - var code = """ + """, """ class C { void M() { @@ -6073,25 +5578,22 @@ void M() { M(); } } - """; - var expectedCode = """ + """); + + [Fact] + public Task FormatPositionalPattern_FollowedByScope() + => AssertFormatAsync(""" class C { void M() { - _ = this is (1, 2) { } + _ = this is (1, 2) + { M(); } } - """; - // although 'M' will be parsed into the pattern on line above, we should not wrap the pattern - await AssertFormatAsync(expectedCode, code); - } - - [Fact] - public async Task FormatPositionalPattern_FollowedByScope() - { - var code = """ + } + """, """ class C { void M() { @@ -6101,27 +5603,21 @@ void M() { } } } - """; - var expectedCode = """ + """); + + [Fact] + public Task FormatSwitchExpression_MultilineAndNoArms() + => AssertFormatAsync(""" class C { void M() { - _ = this is (1, 2) + _ = this switch { - M(); + }; } } - } - """; - // You should not invoke Format on incomplete code and expect nice results - await AssertFormatAsync(expectedCode, code); - } - - [Fact] - public async Task FormatSwitchExpression_MultilineAndNoArms() - { - var code = """ + """, """ class C { void M() { @@ -6130,25 +5626,28 @@ void M() { }; } } - """; - var expectedCode = """ + """); + + [Fact] + public Task FormatSwitchExpression_ExpressionAnchoredToArm() + => AssertFormatAsync(""" class C { void M() { _ = this switch { + { P1: 1 } + => true, + (0, 1) + => true, + _ + => false }; + } } - """; - await AssertFormatAsync(expectedCode, code); - } - - [Fact] - public async Task FormatSwitchExpression_ExpressionAnchoredToArm() - { - var code = """ + """, """ class C { void M() { @@ -6164,8 +5663,11 @@ void M() { } } - """; - var expectedCode = """ + """); + + [Fact] + public Task FormatSwitchExpression_NoSpaceBeforeColonInArm() + => AssertFormatAsync(""" class C { void M() @@ -6182,14 +5684,7 @@ void M() } } - """; - await AssertFormatAsync(expectedCode, code); - } - - [Fact] - public async Task FormatSwitchExpression_NoSpaceBeforeColonInArm() - { - var code = """ + """, """ class C { void M() { @@ -6205,32 +5700,25 @@ void M() { } } - """; - var expectedCode = """ + """); + + [Fact] + public Task FormatSwitchExpression_ArmCommaWantsNewline() + => AssertFormatAsync(""" class C { void M() { _ = this switch { - { P1: 1 } - => true, - (0, 1) - => true, - _ - => false + { P1: 1 } => true, + (0, 1) => true, + _ => false }; } } - """; - await AssertFormatAsync(expectedCode, code); - } - - [Fact] - public async Task FormatSwitchExpression_ArmCommaWantsNewline() - { - var code = """ + """, """ class C { void M() { @@ -6242,8 +5730,11 @@ void M() { } } - """; - var expectedCode = """ + """); + + [Fact] + public Task FormatSwitchExpression_ArmCommaPreservesLines() + => AssertFormatAsync(""" class C { void M() @@ -6251,20 +5742,14 @@ void M() _ = this switch { { P1: 1 } => true, + (0, 1) => true, _ => false }; } } - """; - await AssertFormatAsync(expectedCode, code); - } - - [Fact] - public async Task FormatSwitchExpression_ArmCommaPreservesLines() - { - var code = """ + """, """ class C { void M() { @@ -6277,43 +5762,11 @@ void M() { } } - """; - var expectedCode = """ - class C - { - void M() - { - _ = this switch - { - { P1: 1 } => true, + """); - (0, 1) => true, - _ => false - }; - - } - } - """; - await AssertFormatAsync(expectedCode, code); - } - - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33839")] - public async Task FormatSwitchExpression_ExpressionBody() - { - var code = """ - - public class Test - { - public object Method(int i) - => i switch - { - 1 => 'a', - 2 => 'b', - _ => null, - }; - } - """; - var expectedCode = """ + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33839")] + public Task FormatSwitchExpression_ExpressionBody() + => AssertFormatAsync(""" public class Test { @@ -6325,10 +5778,19 @@ public object Method(int i) _ => null, }; } - """; + """, """ - await AssertFormatAsync(expectedCode, code); - } + public class Test + { + public object Method(int i) + => i switch + { + 1 => 'a', + 2 => 'b', + _ => null, + }; + } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/72196")] [InlineData("[]")] @@ -6338,41 +5800,36 @@ public object Method(int i) [InlineData("[var a, .., var b]")] [InlineData("[{ } a, null]")] [InlineData("[a, []]")] - public async Task FormatSwitchExpression_ListPatternAligned(string listPattern) - { - var code = $$""" + public Task FormatSwitchExpression_ListPatternAligned(string listPattern) + => AssertFormatAsync($$""" class C { void M() { _ = Array.Empty() switch { - {{listPattern}} => 0, + {{listPattern}} => 0, _ => 1, }; } } - """; - var expectedCode = $$""" + """, $$""" class C { void M() { _ = Array.Empty() switch { - {{listPattern}} => 0, + {{listPattern}} => 0, _ => 1, }; } } - """; - await AssertFormatAsync(expectedCode, code); - } + """); [Fact] - public async Task FormatSwitchWithPropertyPattern() - { - var code = """ + public Task FormatSwitchWithPropertyPattern() + => AssertFormatAsync(""" class C { void M() @@ -6384,8 +5841,7 @@ void M() } } } - """; - var expectedCode = """ + """, """ class C { void M() @@ -6397,14 +5853,11 @@ void M() } } } - """; - await AssertFormatAsync(expectedCode, code); - } + """); [Fact] - public async Task FormatSwitchWithPropertyPattern_Singleline() - { - var code = """ + public Task FormatSwitchWithPropertyPattern_Singleline() + => AssertFormatAsync(""" class C { void M() @@ -6415,8 +5868,7 @@ void M() } } } - """; - var expectedCode = """ + """, """ class C { void M() @@ -6427,75 +5879,54 @@ void M() } } } - """; - - await AssertFormatAsync(expectedCode, code); - } + """); [Fact] - public async Task FormatSwitchWithPropertyPattern_Singleline2() - { - var code = """ + public Task FormatSwitchWithPropertyPattern_Singleline2() + => AssertFormatAsync(""" class C { void M() { switch (this) { - case { P1: 1, P2: { P3: 3, P4: 4 } }: System.Console.Write(1); - break; + case { P1: 1, P2: { P3: 3, P4: 4 } }: + System.Console.Write(1); + break; } } } - """; - var expectedCode = """ + """, """ class C { void M() { switch (this) { - case { P1: 1, P2: { P3: 3, P4: 4 } }: - System.Console.Write(1); - break; + case { P1: 1, P2: { P3: 3, P4: 4 } }: System.Console.Write(1); + break; } } } - """; - await AssertFormatAsync(expectedCode, code); - } + """); [Fact] - public async Task SpacingInTupleExtension() - { - var code = """ + public Task SpacingInTupleExtension() + => AssertFormatAsync(""" static class Class5 { - static void Extension(this(int, string) self) { } + static void Extension(this (int, string) self) { } } - """; - var expectedCode = """ + """, """ static class Class5 { - static void Extension(this (int, string) self) { } + static void Extension(this(int, string) self) { } } - """; - - await AssertFormatAsync(expectedCode, code); - } + """); [Fact] - public async Task SpacingInNestedDeconstruction() - { - var code = """ - class Class5{ - void bar() - { - ( int x1 , var( x2,x3 ) )=(1,(2,3)); - } - } - """; - var expectedCode = """ + public Task SpacingInNestedDeconstruction() + => AssertFormatAsync(""" class Class5 { void bar() @@ -6503,16 +5934,18 @@ void bar() (int x1, var (x2, x3)) = (1, (2, 3)); } } - """; - - await AssertFormatAsync(expectedCode, code); - } + """, """ + class Class5{ + void bar() + { + ( int x1 , var( x2,x3 ) )=(1,(2,3)); + } + } + """); [Fact] - public async Task SpacingInSuppressNullableWarningExpression() - { - var code = - """ + public Task SpacingInSuppressNullableWarningExpression() + => AssertFormatAsync(""" class C { static object F() @@ -6520,12 +5953,10 @@ static object F() object? o[] = null; object? x = null; object? y = null; - return x ! ?? (y) ! ?? o[0] !; + return x! ?? (y)! ?? o[0]!; } } - """; - var expectedCode = - """ + """, """ class C { static object F() @@ -6533,62 +5964,56 @@ static object F() object? o[] = null; object? x = null; object? y = null; - return x! ?? (y)! ?? o[0]!; + return x ! ?? (y) ! ?? o[0] !; } } - """; - - await AssertFormatAsync(expectedCode, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545335")] - public async Task PreprocessorOnSameLine() - { - var code = """ + public Task PreprocessorOnSameLine() + => AssertFormatAsync(""" class C { }#line default #line hidden - """; - - var expected = """ + """, """ class C { }#line default #line hidden - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545626")] - public async Task ArraysInAttributes() - { - var code = """ + public Task ArraysInAttributes() + => AssertFormatAsync(""" [A(X = new int[] { 1 })] public class A : Attribute { public int[] X; } - """; - - var expected = """ + """, """ [A(X = new int[] { 1 })] public class A : Attribute { public int[] X; } - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530580")] - public async Task NoNewLineAfterBraceInExpression() - { - var code = """ + public Task NoNewLineAfterBraceInExpression() + => AssertFormatAsync(""" + public class A + { + void Method() + { + var po = cancellationToken.CanBeCanceled ? + new ParallelOptions() { CancellationToken = cancellationToken } : + defaultParallelOptions; + } + } + """, """ public class A { void Method() @@ -6598,27 +6023,23 @@ void Method() defaultParallelOptions; } } - """; + """); - var expected = """ - public class A + [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530580")] + public Task NoIndentForNestedUsingWithoutBraces() + => AssertFormatAsync(""" + class C { - void Method() + void M() { - var po = cancellationToken.CanBeCanceled ? - new ParallelOptions() { CancellationToken = cancellationToken } : - defaultParallelOptions; + using (null) + using (null) + { + } } } - """; - await AssertFormatAsync(expected, code); - } - - [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530580")] - public async Task NoIndentForNestedUsingWithoutBraces() - { - var code = """ + """, """ class C { void M() @@ -6630,13 +6051,16 @@ void M() } } - """; + """); - var expected = """ + [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530580")] + public Task NoIndentForNestedUsingWithoutBraces2() + => AssertFormatAsync(""" class C { void M() { + using (null) using (null) using (null) { @@ -6644,15 +6068,7 @@ void M() } } - """; - - await AssertFormatAsync(expected, code); - } - - [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530580")] - public async Task NoIndentForNestedUsingWithoutBraces2() - { - var code = """ + """, """ class C { void M() @@ -6665,9 +6081,11 @@ void M() } } - """; + """); - var expected = """ + [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530580")] + public Task NoIndentForNestedUsingWithoutBraces3() + => AssertFormatAsync(""" class C { void M() @@ -6680,15 +6098,7 @@ void M() } } - """; - - await AssertFormatAsync(expected, code); - } - - [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530580")] - public async Task NoIndentForNestedUsingWithoutBraces3() - { - var code = """ + """, """ class C { void M() @@ -6701,105 +6111,71 @@ void M() } } - """; - - var expected = """ - class C - { - void M() - { - using (null) - using (null) - using (null) - { - } - } - } - - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546678")] - public async Task UnicodeWhitespace() - { - var code = "\u001A"; - - await AssertFormatAsync("", code); - } + public Task UnicodeWhitespace() + => AssertFormatAsync("", "\u001A"); [Fact, WorkItem(17431, "DevDiv_Projects/Roslyn")] - public async Task NoElasticRuleOnRegularFile() - { - var code = """ + public Task NoElasticRuleOnRegularFile() + => AssertFormatAsync(""" class Consumer { public int P { - } + } } - """; - - var expected = """ + """, """ class Consumer { public int P { - } + } } - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem(584599, "DevDiv_Projects/Roslyn")] - public async Task CaseSection() - { - var code = """ + public Task CaseSection() + => AssertFormatAsync(""" class C { void Method() { - switch(i) + switch (i) { - // test1 + // test1 case 1: - // test2 + // test2 case 2: - // test3 + // test3 int i2 = 10; - // test 4 + // test 4 case 4: - // test 5 + // test 5 } } } - """; - - var expected = """ + """, """ class C { void Method() { - switch (i) + switch(i) { - // test1 + // test1 case 1: - // test2 + // test2 case 2: - // test3 + // test3 int i2 = 10; - // test 4 + // test 4 case 4: - // test 5 + // test 5 } } } - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem(553654, "DevDiv_Projects/Roslyn")] public async Task Bugfix_553654_LabelStatementIndenting() @@ -6808,41 +6184,36 @@ public async Task Bugfix_553654_LabelStatementIndenting() { { CSharpFormattingOptions2.LabelPositioning, LabelPositionOptions.LeftMost } }; - - var code = """ + await AssertFormatAsync(""" class Program { void F() { foreach (var x in new int[] { }) { - goo: + goo: int a = 1; } } } - """; - - var expected = """ + """, """ class Program { void F() { foreach (var x in new int[] { }) { - goo: + goo: int a = 1; } } } - """; - await AssertFormatAsync(expected, code, changingOptions); + """, changingOptions); } [Fact, WorkItem(707064, "DevDiv_Projects/Roslyn")] - public async Task Bugfix_707064_SpaceAfterSecondSemiColonInFor() - { - var code = """ + public Task Bugfix_707064_SpaceAfterSecondSemiColonInFor() + => AssertFormatAsync(""" class Program { void F() @@ -6852,9 +6223,7 @@ void F() } } } - """; - - var expected = """ + """, """ class Program { void F() @@ -6864,41 +6233,33 @@ void F() } } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/772313")] - public async Task Bugfix_772313_ReturnKeywordBeforeQueryClauseDoesNotTriggerNewLineOnFormat() - { - var code = """ + public Task Bugfix_772313_ReturnKeywordBeforeQueryClauseDoesNotTriggerNewLineOnFormat() + => AssertFormatAsync(""" class C { int M() { - return from c in " + return from c in " select c; } } - """; - - var expected = """ + """, """ class C { int M() { - return from c in " + return from c in " select c; } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/772304")] - public async Task Bugfix_772313_PreserveMethodParameterIndentWhenAttributePresent() - { - var code = """ + public Task Bugfix_772313_PreserveMethodParameterIndentWhenAttributePresent() + => AssertFormatAsync(""" class C { void M @@ -6926,9 +6287,7 @@ void M List b ); } - """; - - var expected = """ + """, """ class C { void M @@ -6956,24 +6315,17 @@ void M List b ); } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/776513")] - public async Task Bugfix_776513_CheckBraceIfNotMissingBeforeApplyingOperationForBracedBlocks() - { - var code = """ + public Task Bugfix_776513_CheckBraceIfNotMissingBeforeApplyingOperationForBracedBlocks() + => AssertFormatAsync(""" var alwaysTriggerList = new[] Dim triggerOnlyWithLettersList = - """; - - var expected = """ + """, """ var alwaysTriggerList = new[] Dim triggerOnlyWithLettersList = - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/769342")] public async Task ShouldFormatDocCommentWithIndentSameAsTabSizeWithUseTabTrue() @@ -7106,92 +6458,90 @@ public void goo() [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/176345")] public async Task TestSpacingOptionAfterControlFlowKeyword() { - var code = """ + var optionSet = new OptionsCollection(LanguageNames.CSharp) { { CSharpFormattingOptions2.SpaceAfterControlFlowStatementKeyword, false } }; + await AssertFormatAsync(""" class Program { public void goo() { int i; - for (i=0; i<10; i++) - {} + for(i = 0; i < 10; i++) + { } - foreach (i in new[] {1,2,3}) - {} + foreach(i in new[] { 1, 2, 3 }) + { } - if (i==10) - {} + if(i == 10) + { } - while (i==10) - {} + while(i == 10) + { } - switch (i) + switch(i) { default: break; } - do {} while (true); + do { } while(true); try { } - catch (System.Exception e) when (true) + catch(System.Exception e) when(true) { } - using (somevar) + using(somevar) { } - lock (somevar) + lock(somevar) { } - fixed (somevar) + fixed(somevar) { } } } - """; - var expected = """ + """, """ class Program { public void goo() { int i; - for(i = 0; i < 10; i++) - { } + for (i=0; i<10; i++) + {} - foreach(i in new[] { 1, 2, 3 }) - { } + foreach (i in new[] {1,2,3}) + {} - if(i == 10) - { } + if (i==10) + {} - while(i == 10) - { } + while (i==10) + {} - switch(i) + switch (i) { default: break; } - do { } while(true); + do {} while (true); try { } - catch(System.Exception e) when(true) + catch (System.Exception e) when (true) { } - using(somevar) + using (somevar) { } - lock(somevar) + lock (somevar) { } - fixed(somevar) + fixed (somevar) { } } } - """; - var optionSet = new OptionsCollection(LanguageNames.CSharp) { { CSharpFormattingOptions2.SpaceAfterControlFlowStatementKeyword, false } }; - await AssertFormatAsync(expected, code, changedOptionSet: optionSet); + """, changedOptionSet: optionSet); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766212")] @@ -7208,7 +6558,7 @@ public void Main() } } """; - var expectedDefault = """ + await AssertFormatAsync(""" class Program { @@ -7218,10 +6568,9 @@ public void Main() var digits = new List { 1, 2, 3, 4 }; } } - """; - await AssertFormatAsync(expectedDefault, code); - - var expectedAfterCommaDisabled = """ + """, code); + var optionSet = new OptionsCollection(LanguageNames.CSharp) { { CSharpFormattingOptions2.SpaceAfterComma, false } }; + await AssertFormatAsync(""" class Program { @@ -7231,11 +6580,9 @@ public void Main() var digits = new List { 1,2,3,4 }; } } - """; - var optionSet = new OptionsCollection(LanguageNames.CSharp) { { CSharpFormattingOptions2.SpaceAfterComma, false } }; - await AssertFormatAsync(expectedAfterCommaDisabled, code, changedOptionSet: optionSet); - - var expectedBeforeCommaEnabled = """ + """, code, changedOptionSet: optionSet); + optionSet.Add(CSharpFormattingOptions2.SpaceBeforeComma, true); + await AssertFormatAsync(""" class Program { @@ -7245,15 +6592,12 @@ public void Main() var digits = new List { 1 ,2 ,3 ,4 }; } } - """; - optionSet.Add(CSharpFormattingOptions2.SpaceBeforeComma, true); - await AssertFormatAsync(expectedBeforeCommaEnabled, code, changedOptionSet: optionSet); + """, code, changedOptionSet: optionSet); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/772308")] - public async Task Bugfix_772308_SeparateSuppressionForEachCaseLabelEvenIfEmpty() - { - var code = """ + public Task Bugfix_772308_SeparateSuppressionForEachCaseLabelEvenIfEmpty() + => AssertFormatAsync(""" class C { @@ -7264,15 +6608,13 @@ int M() case 1: return 1; case 2: return 2; case 3: - case 4: return 4; + case 4: return 4; default: } } } - """; - - var expected = """ + """, """ class C { @@ -7283,47 +6625,17 @@ int M() case 1: return 1; case 2: return 2; case 3: - case 4: return 4; + case 4: return 4; default: } } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844913")] - public async Task QueryExpressionInExpression() - { - var code = """ - - class C - { - public void CreateSettingsFile(string path, string comment) { - var xml = new XDocument( - new XDeclaration(1.0, utf8, yes), - new XComment(comment), - new XElement(UserSettings, - new XElement(ToolsOptions, - from t in KnownSettings.DefaultCategories - group t by t.Item1 into cat - select new XElement(ToolsOptionsCategory, - new XAttribute(name, cat.Key), - cat.Select(sc => new XElement(ToolsOptionsSubCategory, new XAttribute(name, sc.Item2))) - ) - ) - ) - ); - UpdateSettingsXml(xml); - xml.Save(path); - SettingsPath = path; - } - } - - """; - - var expected = """ + public Task QueryExpressionInExpression() + => AssertFormatAsync(""" class C { @@ -7349,9 +6661,32 @@ group t by t.Item1 into cat } } - """; - await AssertFormatAsync(expected, code); - } + """, """ + + class C + { + public void CreateSettingsFile(string path, string comment) { + var xml = new XDocument( + new XDeclaration(1.0, utf8, yes), + new XComment(comment), + new XElement(UserSettings, + new XElement(ToolsOptions, + from t in KnownSettings.DefaultCategories + group t by t.Item1 into cat + select new XElement(ToolsOptionsCategory, + new XAttribute(name, cat.Key), + cat.Select(sc => new XElement(ToolsOptionsSubCategory, new XAttribute(name, sc.Item2))) + ) + ) + ) + ); + UpdateSettingsXml(xml); + xml.Save(path); + SettingsPath = path; + } + } + + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843479")] public async Task EmbeddedStatementElse() @@ -7360,42 +6695,37 @@ public async Task EmbeddedStatementElse() { { CSharpFormattingOptions2.NewLineForElse, false } }; - - var code = """ + await AssertFormatAsync(""" class C { void Method() { if (true) - Console.WriteLine(); else - Console.WriteLine(); + Console.WriteLine(); + else + Console.WriteLine(); } } - """; - - var expected = """ + """, """ class C { void Method() { if (true) - Console.WriteLine(); - else - Console.WriteLine(); + Console.WriteLine(); else + Console.WriteLine(); } } - """; - await AssertFormatAsync(expected, code, changingOptions); + """, changingOptions); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/772311")] - public async Task LineCommentAtTheEndOfLine() - { - var code = """ + public Task LineCommentAtTheEndOfLine() + => AssertFormatAsync(""" using System; @@ -7404,15 +6734,13 @@ class Program static void Main(string[] args) { Console.WriteLine(); // this is a comment - // that I would like to keep + // that I would like to keep - // properly indented + // properly indented } } - """; - - var expected = """ + """, """ using System; @@ -7421,20 +6749,17 @@ class Program static void Main(string[] args) { Console.WriteLine(); // this is a comment - // that I would like to keep + // that I would like to keep - // properly indented + // properly indented } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38224")] - public async Task BlockCommentAtTheEndOfLine1() - { - var code = """ + public Task BlockCommentAtTheEndOfLine1() + => AssertFormatAsync(""" using System; @@ -7443,15 +6768,13 @@ class Program static void Main(string[] args) { Console.WriteLine(); /* this is a comment */ - // that I would like to keep + // that I would like to keep - // properly indented + // properly indented } } - """; - - var expected = """ + """, """ using System; @@ -7460,20 +6783,17 @@ class Program static void Main(string[] args) { Console.WriteLine(); /* this is a comment */ - // that I would like to keep + // that I would like to keep - // properly indented + // properly indented } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38224")] - public async Task BlockCommentAtTheEndOfLine2() - { - var code = """ + public Task BlockCommentAtTheEndOfLine2() + => AssertFormatAsync(""" using System; @@ -7482,15 +6802,13 @@ class Program static void Main(string[] args) { Console.WriteLine(); // this is a comment - /* that I would like to keep */ + /* that I would like to keep */ - // properly indented + // properly indented } } - """; - - var expected = """ + """, """ using System; @@ -7499,15 +6817,13 @@ class Program static void Main(string[] args) { Console.WriteLine(); // this is a comment - /* that I would like to keep */ + /* that I would like to keep */ - // properly indented + // properly indented } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38224")] public async Task BlockCommentAtBeginningOfLine() @@ -7532,39 +6848,6 @@ static void Main( [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/772311")] public async Task TestTab() { - var code = """ - - using System; - - class Program - { - /// - /// This function is the callback used to execute a command when a menu item is clicked. - /// See the Initialize method to see how the menu item is associated to this function using - /// the OleMenuCommandService service and the MenuCommand class. - /// - private void MenuItemCallback(object sender, EventArgs e) { - // Show a Message Box to prove we were here - IVsUIShell uiShell = (IVsUIShell)GetService(typeof(SVsUIShell)); - Guid clsid = Guid.Empty; - int result; - Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(uiShell.ShowMessageBox( - 0, - ref clsid, - Rebracer, - string.Format(CultureInfo.CurrentCulture, Inside {0}.MenuItemCallback(), this.ToString()), - string.Empty, - 0, - OLEMSGBUTTON.OLEMSGBUTTON_OK, - OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST, - OLEMSGICON.OLEMSGICON_INFO, - 0, // false - out result)); - } - } - - """; - var expected = """ using System; @@ -7600,19 +6883,46 @@ private void MenuItemCallback(object sender, EventArgs e) """; var optionSet = new OptionsCollection(LanguageNames.CSharp) { { FormattingOptions2.UseTabs, true } }; - await AssertFormatAsync(expected, code, changedOptionSet: optionSet); + await AssertFormatAsync(expected, """ + + using System; + + class Program + { + /// + /// This function is the callback used to execute a command when a menu item is clicked. + /// See the Initialize method to see how the menu item is associated to this function using + /// the OleMenuCommandService service and the MenuCommand class. + /// + private void MenuItemCallback(object sender, EventArgs e) { + // Show a Message Box to prove we were here + IVsUIShell uiShell = (IVsUIShell)GetService(typeof(SVsUIShell)); + Guid clsid = Guid.Empty; + int result; + Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(uiShell.ShowMessageBox( + 0, + ref clsid, + Rebracer, + string.Format(CultureInfo.CurrentCulture, Inside {0}.MenuItemCallback(), this.ToString()), + string.Empty, + 0, + OLEMSGBUTTON.OLEMSGBUTTON_OK, + OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST, + OLEMSGICON.OLEMSGICON_INFO, + 0, // false + out result)); + } + } + + """, changedOptionSet: optionSet); await AssertFormatAsync(expected, expected, changedOptionSet: optionSet); } [Fact] public async Task LeaveBlockSingleLine_False() { - var code = """ - - namespace N { class C { int x; } } - """; - - var expected = """ + var options = new OptionsCollection(LanguageNames.CSharp) { { CSharpFormattingOptions2.WrappingPreserveSingleLine, false } }; + await AssertFormatAsync(""" namespace N { @@ -7621,21 +6931,17 @@ class C int x; } } - """; + """, """ - var options = new OptionsCollection(LanguageNames.CSharp) { { CSharpFormattingOptions2.WrappingPreserveSingleLine, false } }; - await AssertFormatAsync(expected, code, changedOptionSet: options); + namespace N { class C { int x; } } + """, changedOptionSet: options); } [Fact] public async Task LeaveBlockSingleLine_False2() { - var code = """ - - class C { void goo() { } } - """; - - var expected = """ + var options = new OptionsCollection(LanguageNames.CSharp) { { CSharpFormattingOptions2.WrappingPreserveSingleLine, false } }; + await AssertFormatAsync(""" class C { @@ -7643,67 +6949,41 @@ void goo() { } } - """; + """, """ - var options = new OptionsCollection(LanguageNames.CSharp) { { CSharpFormattingOptions2.WrappingPreserveSingleLine, false } }; - await AssertFormatAsync(expected, code, changedOptionSet: options); + class C { void goo() { } } + """, changedOptionSet: options); } [Fact] public async Task LeaveStatementMethodDeclarationSameLine_False() { - var code = """ + var options = new OptionsCollection(LanguageNames.CSharp) { { CSharpFormattingOptions2.WrappingKeepStatementsOnSingleLine, false } }; + await AssertFormatAsync(""" class Program { void goo() { - int x = 0; int y = 0; + int x = 0; + int y = 0; } } - """; - - var expected = """ + """, """ class Program { void goo() { - int x = 0; - int y = 0; + int x = 0; int y = 0; } } - """; - - var options = new OptionsCollection(LanguageNames.CSharp) { { CSharpFormattingOptions2.WrappingKeepStatementsOnSingleLine, false } }; - await AssertFormatAsync(expected, code, changedOptionSet: options); + """, changedOptionSet: options); } [Fact] public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_0000() { - var code = """ - - class Program - { - int[ ] x; - int[ , ] y; - int[ , , ] z = new int[1,2,3]; - var a = new[ ] { 0 }; - } - """; - - var expected = """ - - class Program - { - int[] x; - int[,] y; - int[,,] z = new int[1,2,3]; - var a = new[] { 0 }; - } - """; - var options = new OptionsCollection(LanguageNames.CSharp) { { SpaceBetweenEmptySquareBrackets, false }, @@ -7711,13 +6991,16 @@ class Program { SpaceBeforeComma, false }, { SpaceAfterComma, false }, }; - await AssertFormatAsync(expected, code, changedOptionSet: options); - } + await AssertFormatAsync(""" - [Fact] - public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_0001() - { - var code = """ + class Program + { + int[] x; + int[,] y; + int[,,] z = new int[1,2,3]; + var a = new[] { 0 }; + } + """, """ class Program { @@ -7726,19 +7009,12 @@ class Program int[ , , ] z = new int[1,2,3]; var a = new[ ] { 0 }; } - """; - - var expected = """ - - class Program - { - int[] x; - int[,] y; - int[,,] z = new int[1, 2, 3]; - var a = new[] { 0 }; - } - """; + """, changedOptionSet: options); + } + [Fact] + public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_0001() + { var options = new OptionsCollection(LanguageNames.CSharp) { { SpaceBetweenEmptySquareBrackets, false }, @@ -7746,13 +7022,16 @@ class Program { SpaceBeforeComma, false }, { SpaceAfterComma, true }, }; - await AssertFormatAsync(expected, code, changedOptionSet: options); - } + await AssertFormatAsync(""" - [Fact] - public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_0010() - { - var code = """ + class Program + { + int[] x; + int[,] y; + int[,,] z = new int[1, 2, 3]; + var a = new[] { 0 }; + } + """, """ class Program { @@ -7761,19 +7040,12 @@ class Program int[ , , ] z = new int[1,2,3]; var a = new[ ] { 0 }; } - """; - - var expected = """ - - class Program - { - int[] x; - int[,] y; - int[,,] z = new int[1 ,2 ,3]; - var a = new[] { 0 }; - } - """; + """, changedOptionSet: options); + } + [Fact] + public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_0010() + { var options = new OptionsCollection(LanguageNames.CSharp) { { SpaceBetweenEmptySquareBrackets, false }, @@ -7781,13 +7053,16 @@ class Program { SpaceBeforeComma, true }, { SpaceAfterComma, false }, }; - await AssertFormatAsync(expected, code, changedOptionSet: options); - } + await AssertFormatAsync(""" - [Fact] - public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_0011() - { - var code = """ + class Program + { + int[] x; + int[,] y; + int[,,] z = new int[1 ,2 ,3]; + var a = new[] { 0 }; + } + """, """ class Program { @@ -7796,19 +7071,12 @@ class Program int[ , , ] z = new int[1,2,3]; var a = new[ ] { 0 }; } - """; - - var expected = """ - - class Program - { - int[] x; - int[,] y; - int[,,] z = new int[1 , 2 , 3]; - var a = new[] { 0 }; - } - """; + """, changedOptionSet: options); + } + [Fact] + public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_0011() + { var options = new OptionsCollection(LanguageNames.CSharp) { { SpaceBetweenEmptySquareBrackets, false }, @@ -7816,34 +7084,30 @@ class Program { SpaceBeforeComma, true }, { SpaceAfterComma, true }, }; - await AssertFormatAsync(expected, code, changedOptionSet: options); - } - - [Fact] - public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_0100() - { - var code = """ + await AssertFormatAsync(""" class Program { - int[ ] x; - int[, ] y; - int[, , ] z = new int[1,2,3]; - var a = new[ ] { 0 }; + int[] x; + int[,] y; + int[,,] z = new int[1 , 2 , 3]; + var a = new[] { 0 }; } - """; - - var expected = """ + """, """ class Program { - int[] x; - int[,] y; - int[,,] z = new int[ 1,2,3 ]; - var a = new[] { 0 }; + int[ ] x; + int[ , ] y; + int[ , , ] z = new int[1,2,3]; + var a = new[ ] { 0 }; } - """; + """, changedOptionSet: options); + } + [Fact] + public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_0100() + { var options = new OptionsCollection(LanguageNames.CSharp) { { SpaceBetweenEmptySquareBrackets, false }, @@ -7851,13 +7115,16 @@ class Program { SpaceBeforeComma, false }, { SpaceAfterComma, false }, }; - await AssertFormatAsync(expected, code, changedOptionSet: options); - } + await AssertFormatAsync(""" - [Fact] - public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_0101() - { - var code = """ + class Program + { + int[] x; + int[,] y; + int[,,] z = new int[ 1,2,3 ]; + var a = new[] { 0 }; + } + """, """ class Program { @@ -7866,19 +7133,12 @@ class Program int[, , ] z = new int[1,2,3]; var a = new[ ] { 0 }; } - """; - - var expected = """ - - class Program - { - int[] x; - int[,] y; - int[,,] z = new int[ 1, 2, 3 ]; - var a = new[] { 0 }; - } - """; + """, changedOptionSet: options); + } + [Fact] + public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_0101() + { var options = new OptionsCollection(LanguageNames.CSharp) { { SpaceBetweenEmptySquareBrackets, false }, @@ -7886,13 +7146,16 @@ class Program { SpaceBeforeComma, false }, { SpaceAfterComma, true }, }; - await AssertFormatAsync(expected, code, changedOptionSet: options); - } + await AssertFormatAsync(""" - [Fact] - public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_0110() - { - var code = """ + class Program + { + int[] x; + int[,] y; + int[,,] z = new int[ 1, 2, 3 ]; + var a = new[] { 0 }; + } + """, """ class Program { @@ -7901,19 +7164,12 @@ class Program int[, , ] z = new int[1,2,3]; var a = new[ ] { 0 }; } - """; - - var expected = """ - - class Program - { - int[] x; - int[,] y; - int[,,] z = new int[ 1 ,2 ,3 ]; - var a = new[] { 0 }; - } - """; + """, changedOptionSet: options); + } + [Fact] + public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_0110() + { var options = new OptionsCollection(LanguageNames.CSharp) { { SpaceBetweenEmptySquareBrackets, false }, @@ -7921,13 +7177,16 @@ class Program { SpaceBeforeComma, true }, { SpaceAfterComma, false }, }; - await AssertFormatAsync(expected, code, changedOptionSet: options); - } + await AssertFormatAsync(""" - [Fact] - public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_0111() - { - var code = """ + class Program + { + int[] x; + int[,] y; + int[,,] z = new int[ 1 ,2 ,3 ]; + var a = new[] { 0 }; + } + """, """ class Program { @@ -7936,19 +7195,12 @@ class Program int[, , ] z = new int[1,2,3]; var a = new[ ] { 0 }; } - """; - - var expected = """ - - class Program - { - int[] x; - int[,] y; - int[,,] z = new int[ 1 , 2 , 3 ]; - var a = new[] { 0 }; - } - """; + """, changedOptionSet: options); + } + [Fact] + public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_0111() + { var options = new OptionsCollection(LanguageNames.CSharp) { { SpaceBetweenEmptySquareBrackets, false }, @@ -7956,34 +7208,30 @@ class Program { SpaceBeforeComma, true }, { SpaceAfterComma, true }, }; - await AssertFormatAsync(expected, code, changedOptionSet: options); - } - - [Fact] - public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_1000() - { - var code = """ + await AssertFormatAsync(""" class Program { int[] x; - int[ ,] y; - int[ , ,] z = new int[1,2,3]; + int[,] y; + int[,,] z = new int[ 1 , 2 , 3 ]; var a = new[] { 0 }; } - """; - - var expected = """ + """, """ class Program { int[ ] x; - int[ , ] y; - int[ , , ] z = new int[1,2,3]; + int[, ] y; + int[, , ] z = new int[1,2,3]; var a = new[ ] { 0 }; } - """; + """, changedOptionSet: options); + } + [Fact] + public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_1000() + { var options = new OptionsCollection(LanguageNames.CSharp) { { SpaceBetweenEmptySquareBrackets, true }, @@ -7991,13 +7239,16 @@ class Program { SpaceBeforeComma, false }, { SpaceAfterComma, false }, }; - await AssertFormatAsync(expected, code, changedOptionSet: options); - } + await AssertFormatAsync(""" - [Fact] - public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_1001() - { - var code = """ + class Program + { + int[ ] x; + int[ , ] y; + int[ , , ] z = new int[1,2,3]; + var a = new[ ] { 0 }; + } + """, """ class Program { @@ -8006,19 +7257,12 @@ class Program int[ , ,] z = new int[1,2,3]; var a = new[] { 0 }; } - """; - - var expected = """ - - class Program - { - int[ ] x; - int[ , ] y; - int[ , , ] z = new int[1, 2, 3]; - var a = new[ ] { 0 }; - } - """; + """, changedOptionSet: options); + } + [Fact] + public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_1001() + { var options = new OptionsCollection(LanguageNames.CSharp) { { SpaceBetweenEmptySquareBrackets, true }, @@ -8026,13 +7270,16 @@ class Program { SpaceBeforeComma, false }, { SpaceAfterComma, true }, }; - await AssertFormatAsync(expected, code, changedOptionSet: options); - } + await AssertFormatAsync(""" - [Fact] - public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_1010() - { - var code = """ + class Program + { + int[ ] x; + int[ , ] y; + int[ , , ] z = new int[1, 2, 3]; + var a = new[ ] { 0 }; + } + """, """ class Program { @@ -8041,19 +7288,12 @@ class Program int[ , ,] z = new int[1,2,3]; var a = new[] { 0 }; } - """; - - var expected = """ - - class Program - { - int[ ] x; - int[ , ] y; - int[ , , ] z = new int[1 ,2 ,3]; - var a = new[ ] { 0 }; - } - """; + """, changedOptionSet: options); + } + [Fact] + public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_1010() + { var options = new OptionsCollection(LanguageNames.CSharp) { { SpaceBetweenEmptySquareBrackets, true }, @@ -8061,13 +7301,16 @@ class Program { SpaceBeforeComma, true }, { SpaceAfterComma, false }, }; - await AssertFormatAsync(expected, code, changedOptionSet: options); - } + await AssertFormatAsync(""" - [Fact] - public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_1011() - { - var code = """ + class Program + { + int[ ] x; + int[ , ] y; + int[ , , ] z = new int[1 ,2 ,3]; + var a = new[ ] { 0 }; + } + """, """ class Program { @@ -8076,19 +7319,12 @@ class Program int[ , ,] z = new int[1,2,3]; var a = new[] { 0 }; } - """; - - var expected = """ - - class Program - { - int[ ] x; - int[ , ] y; - int[ , , ] z = new int[1 , 2 , 3]; - var a = new[ ] { 0 }; - } - """; + """, changedOptionSet: options); + } + [Fact] + public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_1011() + { var options = new OptionsCollection(LanguageNames.CSharp) { { SpaceBetweenEmptySquareBrackets, true }, @@ -8096,34 +7332,30 @@ class Program { SpaceBeforeComma, true }, { SpaceAfterComma, true }, }; - await AssertFormatAsync(expected, code, changedOptionSet: options); - } - - [Fact] - public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_1100() - { - var code = """ + await AssertFormatAsync(""" class Program { int[ ] x; int[ , ] y; - int[ , , ] z = new int[1,2,3]; + int[ , , ] z = new int[1 , 2 , 3]; var a = new[ ] { 0 }; } - """; - - var expected = """ + """, """ class Program { - int[ ] x; - int[ , ] y; - int[ , , ] z = new int[ 1,2,3 ]; - var a = new[ ] { 0 }; + int[] x; + int[ ,] y; + int[ , ,] z = new int[1,2,3]; + var a = new[] { 0 }; } - """; + """, changedOptionSet: options); + } + [Fact] + public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_1100() + { var options = new OptionsCollection(LanguageNames.CSharp) { { SpaceBetweenEmptySquareBrackets, true }, @@ -8131,34 +7363,30 @@ class Program { SpaceBeforeComma, false }, { SpaceAfterComma, false }, }; - await AssertFormatAsync(expected, code, changedOptionSet: options); - } - - [Fact] - public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_1101() - { - var code = """ + await AssertFormatAsync(""" class Program { int[ ] x; int[ , ] y; - int[ , , ] z = new int[1,2,3]; + int[ , , ] z = new int[ 1,2,3 ]; var a = new[ ] { 0 }; } - """; - - var expected = """ + """, """ class Program { int[ ] x; int[ , ] y; - int[ , , ] z = new int[ 1, 2, 3 ]; + int[ , , ] z = new int[1,2,3]; var a = new[ ] { 0 }; } - """; + """, changedOptionSet: options); + } + [Fact] + public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_1101() + { var options = new OptionsCollection(LanguageNames.CSharp) { { SpaceBetweenEmptySquareBrackets, true }, @@ -8166,34 +7394,30 @@ class Program { SpaceBeforeComma, false }, { SpaceAfterComma, true }, }; - await AssertFormatAsync(expected, code, changedOptionSet: options); - } - - [Fact] - public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_1110() - { - var code = """ + await AssertFormatAsync(""" class Program { int[ ] x; int[ , ] y; - int[ , , ] z = new int[1,2,3]; + int[ , , ] z = new int[ 1, 2, 3 ]; var a = new[ ] { 0 }; } - """; - - var expected = """ + """, """ class Program { int[ ] x; int[ , ] y; - int[ , , ] z = new int[ 1 ,2 ,3 ]; + int[ , , ] z = new int[1,2,3]; var a = new[ ] { 0 }; } - """; + """, changedOptionSet: options); + } + [Fact] + public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_1110() + { var options = new OptionsCollection(LanguageNames.CSharp) { { SpaceBetweenEmptySquareBrackets, true }, @@ -8201,78 +7425,88 @@ class Program { SpaceBeforeComma, true }, { SpaceAfterComma, false }, }; - await AssertFormatAsync(expected, code, changedOptionSet: options); + await AssertFormatAsync(""" + + class Program + { + int[ ] x; + int[ , ] y; + int[ , , ] z = new int[ 1 ,2 ,3 ]; + var a = new[ ] { 0 }; + } + """, """ + + class Program + { + int[ ] x; + int[ , ] y; + int[ , , ] z = new int[1,2,3]; + var a = new[ ] { 0 }; + } + """, changedOptionSet: options); } [Fact] public async Task SpaceWithinEmptyBracketPrecedencesSpaceBeforeOrAfterComma_1111() { - var code = """ + var options = new OptionsCollection(LanguageNames.CSharp) + { + { SpaceBetweenEmptySquareBrackets, true }, + { SpaceWithinSquareBrackets, true }, + { SpaceBeforeComma, true }, + { SpaceAfterComma, true }, + }; + await AssertFormatAsync(""" class Program { int[ ] x; int[ , ] y; - int[ , , ] z = new int[1,2,3]; + int[ , , ] z = new int[ 1 , 2 , 3 ]; var a = new[ ] { 0 }; } - """; - - var expected = """ + """, """ class Program { int[ ] x; int[ , ] y; - int[ , , ] z = new int[ 1 , 2 , 3 ]; + int[ , , ] z = new int[1,2,3]; var a = new[ ] { 0 }; } - """; - - var options = new OptionsCollection(LanguageNames.CSharp) - { - { SpaceBetweenEmptySquareBrackets, true }, - { SpaceWithinSquareBrackets, true }, - { SpaceBeforeComma, true }, - { SpaceAfterComma, true }, - }; - await AssertFormatAsync(expected, code, changedOptionSet: options); + """, changedOptionSet: options); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14128")] public async Task SpaceBeforeCommasInLocalFunctionParameters() { - var code = """ + var options = new OptionsCollection(LanguageNames.CSharp) + { + { SpaceBeforeComma, true }, + }; + await AssertFormatAsync(""" class Program { void Goo() { - void LocalFunction(int i, string s) + void LocalFunction(int i , string s) { } } } - """; - - var expected = """ + """, """ class Program { void Goo() { - void LocalFunction(int i , string s) + void LocalFunction(int i, string s) { } } } - """; - - var options = new OptionsCollection(LanguageNames.CSharp) - { - { SpaceBeforeComma, true }, - }; - await AssertFormatAsync(expected, code, changedOptionSet: options); + """, changedOptionSet: options); } [Fact] @@ -8305,67 +7539,50 @@ class Program [Fact] public async Task SquareBracesBefore_True() { - var code = """ + var options = new OptionsCollection(LanguageNames.CSharp) { { CSharpFormattingOptions2.SpaceBeforeOpenSquareBracket, true } }; + await AssertFormatAsync(""" class Program { - int[] x; + int [] x; } - """; - - var expected = """ + """, """ class Program { - int [] x; + int[] x; } - """; - - var options = new OptionsCollection(LanguageNames.CSharp) { { CSharpFormattingOptions2.SpaceBeforeOpenSquareBracket, true } }; - await AssertFormatAsync(expected, code, changedOptionSet: options); + """, changedOptionSet: options); } [Fact] public async Task SquareBracesAndValue_True() { - var code = """ + var options = new OptionsCollection(LanguageNames.CSharp) { { CSharpFormattingOptions2.SpaceWithinSquareBrackets, true } }; + await AssertFormatAsync(""" class Program { - int[3] x; + int[ 3 ] x; } - """; - - var expected = """ + """, """ class Program { - int[ 3 ] x; + int[3] x; } - """; - - var options = new OptionsCollection(LanguageNames.CSharp) { { CSharpFormattingOptions2.SpaceWithinSquareBrackets, true } }; - await AssertFormatAsync(expected, code, changedOptionSet: options); + """, changedOptionSet: options); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/917351")] public async Task TestLockStatement() { - var code = """ - - class Program - { - public void Method() - { - lock (expression) - { - // goo - } - } - } - """; + var options = new OptionsCollection(LanguageNames.CSharp) + { + { NewLineBeforeOpenBrace, NewLineBeforeOpenBrace.DefaultValue.WithFlagValue(NewLineBeforeOpenBracePlacement.ControlBlocks, false) } + }; - var expected = """ + await AssertFormatAsync(""" class Program { @@ -8376,37 +7593,30 @@ public void Method() } } } - """; - - var options = new OptionsCollection(LanguageNames.CSharp) - { - { NewLineBeforeOpenBrace, NewLineBeforeOpenBrace.DefaultValue.WithFlagValue(NewLineBeforeOpenBracePlacement.ControlBlocks, false) } - }; - - await AssertFormatAsync(expected, code, changedOptionSet: options); - } - - [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962416")] - public async Task TestCheckedAndUncheckedStatement() - { - var code = """ + """, """ class Program { public void Method() { - checked + lock (expression) { // goo } - unchecked - { - } } } - """; + """, changedOptionSet: options); + } - var expected = """ + [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962416")] + public async Task TestCheckedAndUncheckedStatement() + { + var options = new OptionsCollection(LanguageNames.CSharp) + { + { NewLineBeforeOpenBrace , NewLineBeforeOpenBrace.DefaultValue.WithFlagValue(NewLineBeforeOpenBracePlacement.ControlBlocks, false) } + }; + + await AssertFormatAsync(""" class Program { @@ -8419,20 +7629,29 @@ public void Method() } } } - """; - - var options = new OptionsCollection(LanguageNames.CSharp) - { - { NewLineBeforeOpenBrace , NewLineBeforeOpenBrace.DefaultValue.WithFlagValue(NewLineBeforeOpenBracePlacement.ControlBlocks, false) } - }; + """, """ - await AssertFormatAsync(expected, code, changedOptionSet: options); + class Program + { + public void Method() + { + checked + { + // goo + } + unchecked + { + } + } + } + """, changedOptionSet: options); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/953535")] public async Task ConditionalMemberAccess() { - var code = """ + var parseOptions = new CSharpParseOptions(); + await AssertFormatAsync(""" using System; class A @@ -8445,14 +7664,12 @@ class Program static void Main(string[] args) { A a = null; - A ?.a = null; - System.Console.WriteLine(args ?[0]); - System.Console.WriteLine(args ?.Length); + A?.a = null; + System.Console.WriteLine(args?[0]); + System.Console.WriteLine(args?.Length); } } - """; - - var expected = """ + """, """ using System; class A @@ -8465,14 +7682,12 @@ class Program static void Main(string[] args) { A a = null; - A?.a = null; - System.Console.WriteLine(args?[0]); - System.Console.WriteLine(args?.Length); + A ?.a = null; + System.Console.WriteLine(args ?[0]); + System.Console.WriteLine(args ?.Length); } } - """; - var parseOptions = new CSharpParseOptions(); - await AssertFormatAsync(expected, code, parseOptions: parseOptions); + """, parseOptions: parseOptions); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924172")] @@ -8482,7 +7697,7 @@ public async Task IgnoreSpacesInDeclarationStatementEnabled() { { CSharpFormattingOptions2.SpacesIgnoreAroundVariableDeclaration, true } }; - var code = """ + await AssertFormatAsync(""" class Program { @@ -8491,9 +7706,7 @@ static void Main(string[] args) int s; } } - """; - - var expected = """ + """, """ class Program { @@ -8502,14 +7715,12 @@ static void Main(string[] args) int s; } } - """; - await AssertFormatAsync(expected, code, changedOptionSet: changingOptions); + """, changedOptionSet: changingOptions); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899492")] - public async Task CommentIsLeadingTriviaOfStatementNotLabel() - { - var code = """ + public Task CommentIsLeadingTriviaOfStatementNotLabel() + => AssertFormatAsync(""" class C { @@ -8521,9 +7732,7 @@ void M() M(); } } - """; - - var expected = """ + """, """ class C { @@ -8535,14 +7744,11 @@ void M() M(); } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991547")] - public async Task DoNotWrappingTryCatchFinallyIfOnSingleLine() - { - var code = """ + public Task DoNotWrappingTryCatchFinallyIfOnSingleLine() + => AssertFormatAsync(""" class C { @@ -8553,9 +7759,7 @@ void M() finally { } } } - """; - - var expected = """ + """, """ class C { @@ -8566,14 +7770,11 @@ void M() finally { } } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact] - public async Task InterpolatedStrings1() - { - var code = """ + public Task InterpolatedStrings1() + => AssertFormatAsync(""" class C { @@ -8583,9 +7784,7 @@ void M() var b = $"Hello, {a}"; } } - """; - - var expected = """ + """, """ class C { @@ -8595,15 +7794,11 @@ void M() var b = $"Hello, {a}"; } } - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact] - public async Task InterpolatedStrings2() - { - var code = """ + public Task InterpolatedStrings2() + => AssertFormatAsync(""" class C { @@ -8614,9 +7809,7 @@ void M() var c = $"{a}, {b}"; } } - """; - - var expected = """ + """, """ class C { @@ -8627,75 +7820,59 @@ void M() var c = $"{a}, {b}"; } } - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact] - public async Task InterpolatedStrings3() - { - var code = """ + public Task InterpolatedStrings3() + => AssertFormatAsync(""" class C { void M() { var a = "World"; - var b = $"Hello, { a }"; + var b = $"Hello, {a}"; } } - """; - - var expected = """ + """, """ class C { void M() { var a = "World"; - var b = $"Hello, {a}"; + var b = $"Hello, { a }"; } } - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact] - public async Task InterpolatedRawStrings3() - { - var code = """" + public Task InterpolatedRawStrings3() + => AssertFormatAsync("""" class C { void M() { var a = "World"; - var b = $"""Hello, { a }"""; + var b = $"""Hello, {a}"""; } } - """"; - - var expected = """" + """", """" class C { void M() { var a = "World"; - var b = $"""Hello, {a}"""; + var b = $"""Hello, { a }"""; } } - """"; - - await AssertFormatAsync(expected, code); - } + """"); [Fact] - public async Task InterpolatedStrings4() - { - var code = """ + public Task InterpolatedStrings4() + => AssertFormatAsync(""" class C { @@ -8703,12 +7880,10 @@ void M() { var a = "Hello"; var b = "World"; - var c = $"{ a }, { b }"; + var c = $"{a}, {b}"; } } - """; - - var expected = """ + """, """ class C { @@ -8716,18 +7891,14 @@ void M() { var a = "Hello"; var b = "World"; - var c = $"{a}, {b}"; + var c = $"{ a }, { b }"; } - } - """; - - await AssertFormatAsync(expected, code); - } + } + """); [Fact] - public async Task InterpolatedStrings5() - { - var code = """ + public Task InterpolatedStrings5() + => AssertFormatAsync(""" class C { @@ -8737,9 +7908,7 @@ void M() var b = $@"Hello, {a}"; } } - """; - - var expected = """ + """, """ class C { @@ -8749,15 +7918,11 @@ void M() var b = $@"Hello, {a}"; } } - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact] - public async Task InterpolatedStrings6() - { - var code = """ + public Task InterpolatedStrings6() + => AssertFormatAsync(""" class C { @@ -8768,9 +7933,7 @@ void M() var c = $@"{a}, {b}"; } } - """; - - var expected = """ + """, """ class C { @@ -8781,45 +7944,35 @@ void M() var c = $@"{a}, {b}"; } } - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact] - public async Task InterpolatedStrings7() - { - var code = """ + public Task InterpolatedStrings7() + => AssertFormatAsync(""" class C { void M() { var a = "World"; - var b = $@"Hello, { a }"; + var b = $@"Hello, {a}"; } } - """; - - var expected = """ + """, """ class C { void M() { var a = "World"; - var b = $@"Hello, {a}"; + var b = $@"Hello, { a }"; } } - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact] - public async Task InterpolatedStrings8() - { - var code = """ + public Task InterpolatedStrings8() + => AssertFormatAsync(""" class C { @@ -8827,12 +7980,10 @@ void M() { var a = "Hello"; var b = "World"; - var c = $@"{ a }, { b }"; + var c = $@"{a}, {b}"; } } - """; - - var expected = """ + """, """ class C { @@ -8840,104 +7991,82 @@ void M() { var a = "Hello"; var b = "World"; - var c = $@"{a}, {b}"; + var c = $@"{ a }, { b }"; } } - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact] - public async Task InterpolatedStrings9() - { - var code = """ + public Task InterpolatedStrings9() + => AssertFormatAsync(""" class C { void M() { var a = "Hello"; - var c = $"{ a }, World"; + var c = $"{a}, World"; } } - """; - - var expected = """ + """, """ class C { void M() { var a = "Hello"; - var c = $"{a}, World"; + var c = $"{ a }, World"; } } - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact] - public async Task InterpolatedStrings10() - { - var code = """ + public Task InterpolatedStrings10() + => AssertFormatAsync(""" class C { void M() { - var s = $"{42 , -4 :x}"; + var s = $"{42,-4:x}"; } } - """; - - var expected = """ + """, """ class C { void M() { - var s = $"{42,-4:x}"; + var s = $"{42 , -4 :x}"; } } - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact] - public async Task InterpolatedRawStrings10() - { - var code = """" + public Task InterpolatedRawStrings10() + => AssertFormatAsync("""" class C { void M() { - var s = $"""{42 , -4 :x}"""; + var s = $"""{42,-4:x}"""; } } - """"; - - var expected = """" + """", """" class C { void M() { - var s = $"""{42,-4:x}"""; + var s = $"""{42 , -4 :x}"""; } } - """"; - - await AssertFormatAsync(expected, code); - } + """"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/59811")] - public async Task InterpolatedStrings11() - { - var code = """ + public Task InterpolatedStrings11() + => AssertFormatAsync(""" class C { @@ -8946,12 +8075,10 @@ void M() var hostAddress = "host"; var nasTypeId = "nas"; var version = "1.2"; - var c = $"{ hostAddress?? ""}/{nasTypeId }/{version??""}"; + var c = $"{hostAddress ?? ""}/{nasTypeId}/{version ?? ""}"; } } - """; - - var expected = """ + """, """ class C { @@ -8960,157 +8087,124 @@ void M() var hostAddress = "host"; var nasTypeId = "nas"; var version = "1.2"; - var c = $"{hostAddress ?? ""}/{nasTypeId}/{version ?? ""}"; + var c = $"{ hostAddress?? ""}/{nasTypeId }/{version??""}"; } } - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/59811")] - public async Task InterpolatedStrings12() - { - var code = """ + public Task InterpolatedStrings12() + => AssertFormatAsync(""" class C { void M() { var a = 1.2M; - var c = $"{ a : 000.00 }"; + var c = $"{a: 000.00 }"; } } - """; - - var expected = """ + """, """ class C { void M() { var a = 1.2M; - var c = $"{a: 000.00 }"; + var c = $"{ a : 000.00 }"; } } - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/59811")] - public async Task InterpolatedStrings13() - { - var code = """ + public Task InterpolatedStrings13() + => AssertFormatAsync(""" class C { void M() { var a = 1.2M; - var c = $"{ (a > 2?"a":"b"}"; + var c = $"{(a > 2 ? "a" : "b"}"; } } - """; - - var expected = """ + """, """ class C { void M() { var a = 1.2M; - var c = $"{(a > 2 ? "a" : "b"}"; + var c = $"{ (a > 2?"a":"b"}"; } } - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact] - public async Task InterpolatedStrings14() - { - var code = """ + public Task InterpolatedStrings14() + => AssertFormatAsync(""" class C { void M() { - var s = $"{ 42 , -4 :x}"; + var s = $"{42,-4:x}"; } } - """; - - var expected = """ + """, """ class C { void M() { - var s = $"{42,-4:x}"; + var s = $"{ 42 , -4 :x}"; } } - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact] - public async Task InterpolatedStrings15() - { - var code = """ + public Task InterpolatedStrings15() + => AssertFormatAsync(""" class C { void M() { - var s = $"{ 42 , -4 }"; + var s = $"{42,-4}"; } } - """; - - var expected = """ + """, """ class C { void M() { - var s = $"{42,-4}"; + var s = $"{ 42 , -4 }"; } } - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact] - public async Task InterpolatedStrings16() - { - var code = """ + public Task InterpolatedStrings16() + => AssertFormatAsync(""" class C { void M() { - var s = $"{ 42 , -4 : x }"; + var s = $"{42,-4: x }"; } } - """; - - var expected = """ + """, """ class C { void M() { - var s = $"{42,-4: x }"; + var s = $"{ 42 , -4 : x }"; } } - """; - - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1151")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1041787")] @@ -9170,9 +8264,8 @@ static void Main(string[] args) } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1100920")] - public async Task NoLineOperationAroundInterpolationSyntax() - { - await AssertFormatAsync(""" + public Task NoLineOperationAroundInterpolationSyntax() + => AssertFormatAsync(""" class Program { static string F(int a, int b, int c) @@ -9189,7 +8282,6 @@ static string F(int a, int b, int c) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/62")] public async Task SpaceAfterWhenInExceptionFilter() @@ -9432,9 +8524,8 @@ public void goo() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1298")] - public async Task DoNotforceAccessorsToNewLineWithPropertyInitializers() - { - var code = """ + public Task DoNotforceAccessorsToNewLineWithPropertyInitializers() + => AssertFormatAsync(""" using System.Collections.Generic; class Program @@ -9446,9 +8537,7 @@ class Program public class ExcludeValidation { } - """; - - var expected = """ + """, """ using System.Collections.Generic; class Program @@ -9460,9 +8549,7 @@ class Program public class ExcludeValidation { } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1339")] public async Task DoNotFormatAutoPropertyInitializerIfNotDifferentLine() @@ -9481,155 +8568,135 @@ static void Main(string[] args) } [Fact] - public async Task SpacingForForStatementInfiniteLoop() - { - var code = """ + public Task SpacingForForStatementInfiniteLoop() + => AssertFormatAsync(""" class Program { void Main() { - for ( ;;) + for (; ; ) { } } } - """; - var expected = """ + """, """ class Program { void Main() { - for (; ; ) + for ( ;;) { } } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact] public async Task SpacingForForStatementInfiniteLoopWithNoSpaces() { - var code = """ + var optionSet = new OptionsCollection(LanguageNames.CSharp) + { + { CSharpFormattingOptions2.SpaceAfterSemicolonsInForStatement, false }, + }; + + await AssertFormatAsync(""" class Program { void Main() { - for ( ; ; ) + for (;;) { } } } - """; - var expected = """ + """, """ class Program { void Main() { - for (;;) + for ( ; ; ) { } } } - """; - var optionSet = new OptionsCollection(LanguageNames.CSharp) - { - { CSharpFormattingOptions2.SpaceAfterSemicolonsInForStatement, false }, - }; - - await AssertFormatAsync(expected, code, changedOptionSet: optionSet); + """, changedOptionSet: optionSet); } [Fact] public async Task SpacingForForStatementInfiniteLoopWithSpacesBefore() { - var code = """ + var optionSet = new OptionsCollection(LanguageNames.CSharp) + { + { CSharpFormattingOptions2.SpaceBeforeSemicolonsInForStatement, true }, + { CSharpFormattingOptions2.SpaceAfterSemicolonsInForStatement, false }, + }; + + await AssertFormatAsync(""" class Program { void Main() { - for (;; ) + for ( ; ;) { } } } - """; - var expected = """ + """, """ class Program { void Main() { - for ( ; ;) + for (;; ) { } } } - """; - var optionSet = new OptionsCollection(LanguageNames.CSharp) - { - { CSharpFormattingOptions2.SpaceBeforeSemicolonsInForStatement, true }, - { CSharpFormattingOptions2.SpaceAfterSemicolonsInForStatement, false }, - }; - - await AssertFormatAsync(expected, code, changedOptionSet: optionSet); + """, changedOptionSet: optionSet); } [Fact] public async Task SpacingForForStatementInfiniteLoopWithSpacesBeforeAndAfter() { - var code = """ + var optionSet = new OptionsCollection(LanguageNames.CSharp) + { + { CSharpFormattingOptions2.SpaceBeforeSemicolonsInForStatement, true }, + }; + + await AssertFormatAsync(""" class Program { void Main() { - for (;;) + for ( ; ; ) { } } } - """; - var expected = """ + """, """ class Program { void Main() { - for ( ; ; ) + for (;;) { } } } - """; - var optionSet = new OptionsCollection(LanguageNames.CSharp) - { - { CSharpFormattingOptions2.SpaceBeforeSemicolonsInForStatement, true }, - }; - - await AssertFormatAsync(expected, code, changedOptionSet: optionSet); + """, changedOptionSet: optionSet); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4240")] [WorkItem("https://github.com/dotnet/roslyn/issues/4421")] - public async Task VerifySpacingAfterMethodDeclarationName_Default() - { - var code = """ - class Program - { - public static Program operator + (Program p1, Program p2) { return null; } - public static implicit operator string (Program p) { return null; } - public static void M () { } - public void F () { } - } - """; - var expected = """ + public Task VerifySpacingAfterMethodDeclarationName_Default() + => AssertFormatAsync(""" class Program { public static Program operator +(Program p1, Program p2) { return null; } @@ -9637,9 +8704,15 @@ class Program public static void M() { } public void F() { } } - """; - await AssertFormatAsync(expected, code); - } + """, """ + class Program + { + public static Program operator + (Program p1, Program p2) { return null; } + public static implicit operator string (Program p) { return null; } + public static void M () { } + public void F () { } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4421")] [WorkItem("https://github.com/dotnet/roslyn/issues/4240")] @@ -9649,16 +8722,7 @@ public async Task VerifySpacingAfterMethodDeclarationName_NonDefault() { { CSharpFormattingOptions2.SpacingAfterMethodDeclarationName, true } }; - var code = """ - class Program - { - public static Program operator + (Program p1, Program p2) { return null; } - public static implicit operator string (Program p) { return null; } - public static void M () { } - public void F () { } - } - """; - var expected = """ + await AssertFormatAsync(""" class Program { public static Program operator + (Program p1, Program p2) { return null; } @@ -9666,8 +8730,15 @@ class Program public static void M () { } public void F () { } } - """; - await AssertFormatAsync(expected, code, changedOptionSet: changingOptions); + """, """ + class Program + { + public static Program operator + (Program p1, Program p2) { return null; } + public static implicit operator string (Program p) { return null; } + public static void M () { } + public void F () { } + } + """, changedOptionSet: changingOptions); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/939")] @@ -9701,66 +8772,58 @@ This is a multiline comment [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4280")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1184285")] - public async Task FormatDictionaryInitializers() - { - var code = """ + public Task FormatDictionaryInitializers() + => AssertFormatAsync(""" class Program { void Main() { - var sample = new Dictionary {["x"] = "d" ,["z"] = "XX" }; + var sample = new Dictionary { ["x"] = "d", ["z"] = "XX" }; } } - """; - var expected = """ + """, """ class Program { void Main() { - var sample = new Dictionary { ["x"] = "d", ["z"] = "XX" }; + var sample = new Dictionary {["x"] = "d" ,["z"] = "XX" }; } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/3256")] - public async Task SwitchSectionHonorsNewLineForBracesinControlBlockOption_Default() - { - var code = """ + public Task SwitchSectionHonorsNewLineForBracesinControlBlockOption_Default() + => AssertFormatAsync(""" class Program { public void goo() { int f = 1; - switch (f) { - case 1: { + switch (f) + { + case 1: + { // DO nothing break; } } } } - """; - var expected = """ + """, """ class Program { public void goo() { int f = 1; - switch (f) - { - case 1: - { + switch (f) { + case 1: { // DO nothing break; } } } } - """; - await AssertFormatAsync(expected, code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/3256")] public async Task SwitchSectionHonorsNewLineForBracesinControlBlockOption_NonDefault() @@ -9769,40 +8832,37 @@ public async Task SwitchSectionHonorsNewLineForBracesinControlBlockOption_NonDef { { NewLineBeforeOpenBrace, NewLineBeforeOpenBrace.DefaultValue.WithFlagValue(NewLineBeforeOpenBracePlacement.ControlBlocks, false) } }; - var code = """ + await AssertFormatAsync(""" class Program { public void goo() { int f = 1; - switch (f) - { - case 1: - { + switch (f) { + case 1: { // DO nothing break; } } } } - """; - - var expected = """ + """, """ class Program { public void goo() { int f = 1; - switch (f) { - case 1: { + switch (f) + { + case 1: + { // DO nothing break; } } } } - """; - await AssertFormatAsync(expected, code, changedOptionSet: changingOptions); + """, changedOptionSet: changingOptions); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4014")] @@ -10095,9 +9155,8 @@ class C } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4720")] - public async Task KeepAccessorWithAttributeOnSingleLine() - { - await AssertFormatAsync(""" + public Task KeepAccessorWithAttributeOnSingleLine() + => AssertFormatAsync(""" class Program { @@ -10118,7 +9177,6 @@ public Int32 PaymentMethodID } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/6905")] public async Task KeepConstructorBodyInSameLineAsBaseConstructorInitializer() @@ -10155,9 +9213,8 @@ public C() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/6905")] - public async Task KeepConstructorBodyInSameLineAsThisConstructorInitializerAdjustSpace() - { - await AssertFormatAsync(""" + public Task KeepConstructorBodyInSameLineAsThisConstructorInitializerAdjustSpace() + => AssertFormatAsync(""" class C { @@ -10178,12 +9235,10 @@ public C() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4720")] - public async Task OneSpaceBetweenAccessorsAndAttributes() - { - await AssertFormatAsync(""" + public Task OneSpaceBetweenAccessorsAndAttributes() + => AssertFormatAsync(""" class Program { @@ -10196,12 +9251,10 @@ class Program public int SomeProperty { [SomeAttribute] get; [SomeAttribute] private set; } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7900")] - public async Task FormatEmbeddedStatementInsideLockStatement() - { - await AssertFormatAsync(""" + public Task FormatEmbeddedStatementInsideLockStatement() + => AssertFormatAsync(""" class C { @@ -10222,12 +9275,10 @@ public void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/7900")] - public async Task FormatEmbeddedStatementInsideLockStatementDifferentLine() - { - await AssertFormatAsync(""" + public Task FormatEmbeddedStatementInsideLockStatementDifferentLine() + => AssertFormatAsync(""" class C { @@ -10250,7 +9301,6 @@ public void M() } } """); - } [Fact] public async Task PropertyDeclarationSimple() @@ -10380,9 +9430,8 @@ void M() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/6628")] - public async Task FormatElseBlockBracesOnDifferentLineToNewLines() - { - await AssertFormatAsync(""" + public Task FormatElseBlockBracesOnDifferentLineToNewLines() + => AssertFormatAsync(""" class C { @@ -10410,7 +9459,6 @@ public void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/6628")] public async Task FormatOnElseBlockBracesOnSameLineRemainsInSameLine_1() @@ -10432,9 +9480,8 @@ public void M() } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11572")] - public async Task FormatAttributeOnSameLineAsField() - { - await AssertFormatAsync( + public Task FormatAttributeOnSameLineAsField() + => AssertFormatAsync( """ class C @@ -10448,12 +9495,10 @@ class C { [Attr] int i; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21789")] - public async Task FormatMultipleAttributeOnSameLineAsField1() - { - await AssertFormatAsync( + public Task FormatMultipleAttributeOnSameLineAsField1() + => AssertFormatAsync( """ class C @@ -10471,12 +9516,10 @@ class C { [Attr3][Attr4] int i; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21789")] - public async Task FormatMultipleAttributesOnSameLineAsField2() - { - await AssertFormatAsync( + public Task FormatMultipleAttributesOnSameLineAsField2() + => AssertFormatAsync( """ class C @@ -10493,12 +9536,10 @@ class C { [Attr3][Attr4] int i; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/21789")] - public async Task FormatMultipleAttributeOnSameLineAndFieldOnNewLine() - { - await AssertFormatAsync( + public Task FormatMultipleAttributeOnSameLineAndFieldOnNewLine() + => AssertFormatAsync( """ class C @@ -10515,7 +9556,6 @@ class C { int i; } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/6628")] public async Task FormatOnElseBlockBracesOnSameLineRemainsInSameLine_2() @@ -10542,9 +9582,8 @@ public void FormatSingleStructDeclaration() => Formatter.Format(SyntaxFactory.StructDeclaration("S"), DefaultWorkspace.Services.SolutionServices, CSharpSyntaxFormattingOptions.Default, CancellationToken.None); [Fact] - public async Task FormatIndexExpression() - { - await AssertFormatAsync(""" + public Task FormatIndexExpression() + => AssertFormatAsync(""" class C { @@ -10565,12 +9604,10 @@ void M() } } """); - } [Fact] - public async Task FormatRangeExpression_NoOperands() - { - await AssertFormatAsync(""" + public Task FormatRangeExpression_NoOperands() + => AssertFormatAsync(""" class C { @@ -10591,12 +9628,10 @@ void M() } } """); - } [Fact] - public async Task FormatRangeExpression_RightOperand() - { - await AssertFormatAsync(""" + public Task FormatRangeExpression_RightOperand() + => AssertFormatAsync(""" class C { @@ -10617,12 +9652,10 @@ void M() } } """); - } [Fact] - public async Task FormatRangeExpression_LeftOperand() - { - await AssertFormatAsync(""" + public Task FormatRangeExpression_LeftOperand() + => AssertFormatAsync(""" class C { @@ -10643,12 +9676,10 @@ void M() } } """); - } [Fact] - public async Task FormatRangeExpression_BothOperands() - { - await AssertFormatAsync(""" + public Task FormatRangeExpression_BothOperands() + => AssertFormatAsync(""" class C { @@ -10669,12 +9700,10 @@ void M() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32113")] - public async Task FormatCommaAfterCloseBrace_CommaRemainIntheSameLine() - { - await AssertFormatAsync( + public Task FormatCommaAfterCloseBrace_CommaRemainIntheSameLine() + => AssertFormatAsync( """ public class Test @@ -10703,12 +9732,10 @@ public void Foo() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32113")] - public async Task FormatCommaAfterCloseBrace_SpaceSurroundWillBeRemoved() - { - await AssertFormatAsync( + public Task FormatCommaAfterCloseBrace_SpaceSurroundWillBeRemoved() + => AssertFormatAsync( """ public class Test @@ -10737,7 +9764,6 @@ public void Foo() } } """); - } [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/31571")] [WorkItem("https://github.com/dotnet/roslyn/issues/33910")] @@ -10830,9 +9856,8 @@ public void FixMyType() } [Fact] - public async Task ClassConstraint() - { - await AssertFormatAsync( + public Task ClassConstraint() + => AssertFormatAsync( """ class Program @@ -10847,12 +9872,10 @@ class Program { } """); - } [Fact] - public async Task SingleLinePropertyPattern1() - { - await AssertFormatAsync( + public Task SingleLinePropertyPattern1() + => AssertFormatAsync( """ using System.Collections.Generic; @@ -10881,12 +9904,10 @@ public void FixMyType() } } """); - } [Fact] - public async Task SingleLinePropertyPattern2() - { - await AssertFormatAsync( + public Task SingleLinePropertyPattern2() + => AssertFormatAsync( """ using System.Collections.Generic; @@ -10909,7 +9930,6 @@ public void FixMyType(object o) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37030")] public async Task SpaceAroundEnumMemberDeclarationIgnored() @@ -10964,9 +9984,8 @@ enum TestEnum } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38895")] - public async Task FormattingNbsp() - { - await AssertFormatAsync( + public Task FormattingNbsp() + => AssertFormatAsync( """ class C @@ -10987,24 +10006,10 @@ class C }; } """.Replace(" ", "\u00A0")); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47438")] - public async Task IndentationForMultilineWith() - { - var code = """ - record C(int X) - { - C M() - { - return this with - { - X = 1 - }; - } - } - """; - var expectedCode = """ + public Task IndentationForMultilineWith() + => AssertFormatAsync(""" record C(int X) { C M() @@ -11015,25 +10020,22 @@ C M() }; } } - """; - - await AssertFormatAsync(expectedCode, code); - } - - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47438")] - public async Task IndentationForMultilineWith_ArrowBody() - { - var code = """ + """, """ record C(int X) { C M() - => this with + { + return this with { X = 1 }; + } } - """; - var expectedCode = """ + """); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47438")] + public Task IndentationForMultilineWith_ArrowBody() + => AssertFormatAsync(""" record C(int X) { C M() @@ -11042,25 +10044,20 @@ C M() X = 1 }; } - """; - - await AssertFormatAsync(expectedCode, code); - } - - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47438")] - public async Task IndentationForMultilineWith_ArrowBody_WithTrailingComma() - { - var code = """ + """, """ record C(int X) { C M() => this with { - X = 1, + X = 1 }; } - """; - var expectedCode = """ + """); + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47438")] + public Task IndentationForMultilineWith_ArrowBody_WithTrailingComma() + => AssertFormatAsync(""" record C(int X) { C M() @@ -11069,150 +10066,130 @@ C M() X = 1, }; } - """; - - await AssertFormatAsync(expectedCode, code); - } + """, """ + record C(int X) + { + C M() + => this with + { + X = 1, + }; + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41022")] - public async Task SpacingAfterAttribute() - { - var code = """ + public Task SpacingAfterAttribute() + => AssertFormatAsync(""" class C { - void M([My]string?[]?[] x) + void M([My] string?[]?[] x) { } } - """; - var expectedCode = """ + """, """ class C { - void M([My] string?[]?[] x) + void M([My]string?[]?[] x) { } } - """; - - await AssertFormatAsync(expectedCode, code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41022")] - public async Task SpacingAfterAttribute_Multiple() - { - var code = """ + public Task SpacingAfterAttribute_Multiple() + => AssertFormatAsync(""" class C { - void M([My][My] int x) + void M([My][My] int x) { } } - """; - var expectedCode = """ + """, """ class C { - void M([My][My] int x) + void M([My][My] int x) { } } - """; - - await AssertFormatAsync(expectedCode, code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41022")] - public async Task SpacingAfterAttribute_Multiple2() - { - var code = """ + public Task SpacingAfterAttribute_Multiple2() + => AssertFormatAsync(""" class C { - void M([My] [My] int x) + void M([My][My] int x) { } } - """; - var expectedCode = """ + """, """ class C { - void M([My][My] int x) + void M([My] [My] int x) { } } - """; - - await AssertFormatAsync(expectedCode, code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/41022")] - public async Task SpacingAfterAttribute_MultipleOnDeclaration() - { - var code = """ + public Task SpacingAfterAttribute_MultipleOnDeclaration() + => AssertFormatAsync(""" class C { - [My] [My] void M() + [My] + [My] + void M() { } } - """; - var expectedCode = """ + """, """ class C { - [My] - [My] - void M() + [My] [My] void M() { } } - """; - - await AssertFormatAsync(expectedCode, code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/47442")] - public async Task IndentImplicitObjectCreationInitializer() - { - var code = """ + public Task IndentImplicitObjectCreationInitializer() + => AssertFormatAsync(""" class C { public string Name { get; set; } public static C Create1(string name) => new C() - { - Name = name - }; + { + Name = name + }; public static C Create2(string name) => new() - { - Name = name - }; + { + Name = name + }; } - """; - var expectedCode = """ + """, """ class C { public string Name { get; set; } public static C Create1(string name) => new C() - { - Name = name - }; + { + Name = name + }; public static C Create2(string name) => new() - { - Name = name - }; + { + Name = name + }; } - """; - - await AssertFormatAsync(expectedCode, code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36913")] - public async Task NewLinesForBraces_SwitchExpression_Default() - { - await AssertFormatAsync( + public Task NewLinesForBraces_SwitchExpression_Default() + => AssertFormatAsync( """ class A @@ -11238,7 +10215,6 @@ void br() } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/36913")] public async Task NewLinesForBraces_SwitchExpression_NonDefault() @@ -11276,9 +10252,8 @@ void br() } [Fact, WorkItem("https://github.com/dotnet/roslyn/discussions/49725")] - public async Task NewLinesForBraces_RecordWithInitializer_Default() - { - await AssertFormatAsync( + public Task NewLinesForBraces_RecordWithInitializer_Default() + => AssertFormatAsync( """ record R(int X); @@ -11306,7 +10281,6 @@ void Goo(R r) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/discussions/49725")] public async Task NewLinesForBraces_RecordWithInitializer_NonDefault() @@ -11346,63 +10320,54 @@ void Goo(R r) } [Fact] - public async Task NoSpacesInPropertyPatterns() - { - var code = """ + public Task NoSpacesInPropertyPatterns() + => AssertFormatAsync(""" class C { int IntProperty { get; set; } void M() { - _ = this is { IntProperty : 2 }; + _ = this is { IntProperty: 2 }; } } - """; - var expectedCode = """ + """, """ class C { int IntProperty { get; set; } void M() { - _ = this is { IntProperty: 2 }; + _ = this is { IntProperty : 2 }; } } - """; - await AssertFormatAsync(expectedCode, code); - } + """); [Fact] - public async Task NoSpacesInExtendedPropertyPatterns() - { - var code = """ + public Task NoSpacesInExtendedPropertyPatterns() + => AssertFormatAsync(""" class C { C CProperty { get; set; } int IntProperty { get; set; } void M() { - _ = this is { CProperty . IntProperty : 2 }; + _ = this is { CProperty.IntProperty: 2 }; } } - """; - var expectedCode = """ + """, """ class C { C CProperty { get; set; } int IntProperty { get; set; } void M() { - _ = this is { CProperty.IntProperty: 2 }; + _ = this is { CProperty . IntProperty : 2 }; } } - """; - await AssertFormatAsync(expectedCode, code); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52413")] - public async Task NewLinesForBraces_PropertyPatternClauses_Default() - { - await AssertFormatAsync( + public Task NewLinesForBraces_PropertyPatternClauses_Default() + => AssertFormatAsync( """ class A @@ -11432,7 +10397,6 @@ public bool IsFoo(A a) } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52413")] public async Task NewLinesForBraces_PropertyPatternClauses_NonDefault() @@ -11539,9 +10503,8 @@ public bool IsFoo(A a) } [Fact] - public async Task RecordClass() - { - await AssertFormatAsync( + public Task RecordClass() + => AssertFormatAsync( """ record class R(int X); @@ -11552,12 +10515,10 @@ record class R(int X); record class R(int X); """); - } [Fact] - public async Task Class() - { - await AssertFormatAsync( + public Task Class() + => AssertFormatAsync( """ class R(int X); @@ -11568,12 +10529,10 @@ class R(int X); class R(int X) ; """); - } [Fact] - public async Task Interface() - { - await AssertFormatAsync( + public Task Interface() + => AssertFormatAsync( """ interface R(int X); @@ -11584,12 +10543,10 @@ interface R(int X); interface R(int X) ; """); - } [Fact] - public async Task RecordStruct() - { - await AssertFormatAsync( + public Task RecordStruct() + => AssertFormatAsync( """ record struct R(int X); @@ -11600,12 +10557,10 @@ record struct R(int X); record struct R(int X); """); - } [Fact] - public async Task Struct() - { - await AssertFormatAsync( + public Task Struct() + => AssertFormatAsync( """ struct R(int X); @@ -11616,7 +10571,6 @@ struct R(int X); struct R(int X) ; """); - } [Fact] public async Task FormatListPattern() @@ -11879,17 +10833,8 @@ void M() } [Fact] - public async Task FormatSlicePattern() - { - var code = """ - class C - { - void M() { - _ = this is[ 0,.. var rest ]; - } - } - """; - var expectedCode = """ + public Task FormatSlicePattern() + => AssertFormatAsync(""" class C { void M() @@ -11897,22 +10842,18 @@ void M() _ = this is [0, .. var rest]; } } - """; - await AssertFormatAsync(expectedCode, code); - } - - [Fact] - public async Task FormatSlicePattern_NoSpace() - { - var code = """ + """, """ class C { void M() { - _ = this is[ 0,..var rest ]; + _ = this is[ 0,.. var rest ]; } } - """; - var expectedCode = """ + """); + + [Fact] + public Task FormatSlicePattern_NoSpace() + => AssertFormatAsync(""" class C { void M() @@ -11920,22 +10861,18 @@ void M() _ = this is [0, .. var rest]; } } - """; - await AssertFormatAsync(expectedCode, code); - } - - [Fact] - public async Task FormatSlicePatternWithAnd() - { - var code = """ + """, """ class C { void M() { - _ = this is[ 0,.. {Count: >0} and var rest ]; + _ = this is[ 0,..var rest ]; } } - """; - var expectedCode = """ + """); + + [Fact] + public Task FormatSlicePatternWithAnd() + => AssertFormatAsync(""" class C { void M() @@ -11943,22 +10880,18 @@ void M() _ = this is [0, .. { Count: > 0 } and var rest]; } } - """; - await AssertFormatAsync(expectedCode, code); - } - - [Fact] - public async Task FormatLengthAndListPattern() - { - var code = """ + """, """ class C { void M() { - _ = this is{Count:>0 and var x}and[ 1,2,3 ]; + _ = this is[ 0,.. {Count: >0} and var rest ]; } } - """; - var expectedCode = """ + """); + + [Fact] + public Task FormatLengthAndListPattern() + => AssertFormatAsync(""" class C { void M() @@ -11966,14 +10899,18 @@ void M() _ = this is { Count: > 0 and var x } and [1, 2, 3]; } } - """; - await AssertFormatAsync(expectedCode, code); - } + """, """ + class C + { + void M() { + _ = this is{Count:>0 and var x}and[ 1,2,3 ]; + } + } + """); [Fact] - public async Task LambdaReturnType_01() - { - await AssertFormatAsync( + public Task LambdaReturnType_01() + => AssertFormatAsync( """ class Program { @@ -11986,12 +10923,10 @@ class Program Delegate D = void () => { }; } """); - } [Fact] - public async Task LambdaReturnType_02() - { - await AssertFormatAsync( + public Task LambdaReturnType_02() + => AssertFormatAsync( """ class Program { @@ -12004,12 +10939,10 @@ class Program Delegate D = A.B()=>{ }; } """); - } [Fact] - public async Task LambdaReturnType_03() - { - await AssertFormatAsync( + public Task LambdaReturnType_03() + => AssertFormatAsync( """ class Program { @@ -12022,12 +10955,10 @@ class Program Delegate D = A < B > ( x ) => x; } """); - } [Fact] - public async Task LambdaReturnType_04() - { - await AssertFormatAsync( + public Task LambdaReturnType_04() + => AssertFormatAsync( """ class Program { @@ -12040,7 +10971,6 @@ class Program object F = Func((A,B)((A,B)t)=>t); } """); - } [Fact] public async Task LineSpanDirective() @@ -12068,9 +10998,8 @@ static void Main() } [Fact] - public async Task FileScopedNamespace() - { - await AssertFormatAsync( + public Task FileScopedNamespace() + => AssertFormatAsync( expected: """ namespace NS; @@ -12085,12 +11014,10 @@ namespace NS; class C { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/67400")] - public async Task FileScopedNamespaceNewline() - { - await AssertFormatAsync( + public Task FileScopedNamespaceNewline() + => AssertFormatAsync( expected: """ namespace Some.Namespace; @@ -12104,12 +11031,10 @@ public class MyClass { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56498")] - public async Task NewInImplicitObjectCreation() - { - await AssertFormatAsync( + public Task NewInImplicitObjectCreation() + => AssertFormatAsync( expected: """ class C @@ -12131,12 +11056,10 @@ void M() { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56498")] - public async Task NewInTupleArrayCreation() - { - await AssertFormatAsync( + public Task NewInTupleArrayCreation() + => AssertFormatAsync( expected: """ class C @@ -12158,12 +11081,10 @@ void M() { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56498")] - public async Task NewInArrayCreation() - { - await AssertFormatAsync( + public Task NewInArrayCreation() + => AssertFormatAsync( expected: """ class C @@ -12185,12 +11106,10 @@ void M() { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56498")] - public async Task NewInImplicitArrayCreation() - { - await AssertFormatAsync( + public Task NewInImplicitArrayCreation() + => AssertFormatAsync( expected: """ class C @@ -12212,12 +11131,10 @@ void M() { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56498")] - public async Task NewInConstructorConstraint() - { - await AssertFormatAsync( + public Task NewInConstructorConstraint() + => AssertFormatAsync( expected: """ class C @@ -12237,12 +11154,10 @@ class C } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56498")] - public async Task NewMethodOverloadWithTupleReturnType() - { - await AssertFormatAsync( + public Task NewMethodOverloadWithTupleReturnType() + => AssertFormatAsync( expected: """ class C @@ -12259,12 +11174,10 @@ class C } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56498")] - public async Task NewPropertyWithTupleReturnType() - { - await AssertFormatAsync( + public Task NewPropertyWithTupleReturnType() + => AssertFormatAsync( expected: """ class C @@ -12281,12 +11194,10 @@ class C } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56498")] - public async Task NewIndexerWithTupleReturnType() - { - await AssertFormatAsync( + public Task NewIndexerWithTupleReturnType() + => AssertFormatAsync( expected: """ class C @@ -12303,12 +11214,10 @@ class C } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56543")] - public async Task FormatAttributeOnLambda() - { - await AssertFormatAsync( + public Task FormatAttributeOnLambda() + => AssertFormatAsync( expected: """ var f = [Attribute] () => { }; @@ -12319,12 +11228,10 @@ await AssertFormatAsync( var f = [Attribute] () => { }; """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56543")] - public async Task FormatAttributeOnLambda_TwoAttributes() - { - await AssertFormatAsync( + public Task FormatAttributeOnLambda_TwoAttributes() + => AssertFormatAsync( expected: """ var f = [Attribute][Attribute2] () => { }; @@ -12335,12 +11242,10 @@ await AssertFormatAsync( var f = [Attribute] [Attribute2] () => { }; """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56543")] - public async Task FormatAttributeOnMethod_TwoAttributes() - { - await AssertFormatAsync( + public Task FormatAttributeOnMethod_TwoAttributes() + => AssertFormatAsync( expected: """ [Attribute][Attribute2] @@ -12355,12 +11260,10 @@ void M() { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56543")] - public async Task FormatAttributeOnTypeParameter_TwoAttributes() - { - await AssertFormatAsync( + public Task FormatAttributeOnTypeParameter_TwoAttributes() + => AssertFormatAsync( expected: """ class C<[Attribute][Attribute2] T> { } @@ -12371,12 +11274,10 @@ class C<[Attribute][Attribute2] T> { } class C< [Attribute] [Attribute2] T > { } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56543")] - public async Task FormatAttributeOnTypeParameter_TwoAttributes_Method() - { - await AssertFormatAsync( + public Task FormatAttributeOnTypeParameter_TwoAttributes_Method() + => AssertFormatAsync( expected: """ class C @@ -12393,12 +11294,10 @@ void M< [Attribute] [Attribute2] T > ( ) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56543")] - public async Task FormatAttributeOnParameter_TwoAttributes() - { - await AssertFormatAsync( + public Task FormatAttributeOnParameter_TwoAttributes() + => AssertFormatAsync( expected: """ class C @@ -12415,12 +11314,10 @@ void M( [Attribute] [Attribute2] T t ) { } } """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56543")] - public async Task FormatAttributeOnLambdaWithExplicitType() - { - await AssertFormatAsync( + public Task FormatAttributeOnLambdaWithExplicitType() + => AssertFormatAsync( expected: """ var f = [Attribute] int () => 1; @@ -12431,12 +11328,10 @@ await AssertFormatAsync( var f = [Attribute] int () => 1; """); - } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56543")] - public async Task FormatAttributeOnLambdaInInvocation() - { - await AssertFormatAsync( + public Task FormatAttributeOnLambdaInInvocation() + => AssertFormatAsync( expected: """ f([Attribute] () => { }); @@ -12447,22 +11342,18 @@ await AssertFormatAsync( f( [Attribute] () => { }); """); - } [Fact] - public async Task FormatAttributeOnLambdaParameter() - { - await AssertFormatAsync(expected: """ + public Task FormatAttributeOnLambdaParameter() + => AssertFormatAsync(expected: """ var f = ([Attribute] int x = 1) => x; """, code: """ var f = ( [ Attribute ]int x=1)=>x; """); - } [Fact] - public async Task FormatRawStringInterpolation() - { - await AssertFormatAsync( + public Task FormatRawStringInterpolation() + => AssertFormatAsync( expected: """" var s = $"""{s}""" @@ -12473,12 +11364,10 @@ await AssertFormatAsync( var s = $"""{s}""" """"); - } [Fact] - public async Task FormatRawStringInterpolation2() - { - await AssertFormatAsync( + public Task FormatRawStringInterpolation2() + => AssertFormatAsync( expected: """" var s = $"""{s,0: x }""" @@ -12489,12 +11378,10 @@ await AssertFormatAsync( var s = $"""{s, 0 : x }""" """"); - } [Fact] - public async Task FormatUsingAliasToType1() - { - await AssertFormatAsync( + public Task FormatUsingAliasToType1() + => AssertFormatAsync( expected: """ f([Attribute] () => { }); @@ -12505,7 +11392,6 @@ await AssertFormatAsync( f( [Attribute] () => { }); """); - } [Theory] [InlineData("using X=int ;", "using X = int;")] @@ -12518,27 +11404,22 @@ await AssertFormatAsync( [InlineData("global using unsafe X=int * ;", "global using unsafe X = int*;")] [InlineData("using X=int ?;", "using X = int?;")] [InlineData("using X=delegate * ;", "using X = delegate*;")] - public async Task TestNormalizeUsingAlias(string text, string expected) - { - await AssertFormatAsync(expected, text); - } + public Task TestNormalizeUsingAlias(string text, string expected) + => AssertFormatAsync(expected, text); [Fact] - public async Task FormatNullConditionalAssignment() - { - await AssertFormatAsync( + public Task FormatNullConditionalAssignment() + => AssertFormatAsync( expected: """ x?.y = z; """, code: """ x ? . y = z ; """); - } [Fact] - public async Task TestExtension1() - { - await AssertFormatAsync( + public Task TestExtension1() + => AssertFormatAsync( """ static class C { @@ -12562,5 +11443,4 @@ public void M ( ) } """, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersionExtensions.CSharpNext)); - } } diff --git a/src/Workspaces/CSharpTest/Formatting/FormattingTests_FunctionPointers.cs b/src/Workspaces/CSharpTest/Formatting/FormattingTests_FunctionPointers.cs index ddc32fe3aabe9..208bbe44f13b9 100644 --- a/src/Workspaces/CSharpTest/Formatting/FormattingTests_FunctionPointers.cs +++ b/src/Workspaces/CSharpTest/Formatting/FormattingTests_FunctionPointers.cs @@ -14,110 +14,86 @@ namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Formatting; public sealed class FormattingTests_FunctionPointers : CSharpFormattingTestBase { [Fact] - public async Task FormatFunctionPointer() - { - var content = @" -unsafe class C -{ - delegate * < int , int > functionPointer; -}"; - - var expected = @" -unsafe class C -{ - delegate* functionPointer; -}"; - - await AssertFormatAsync(expected, content); - } + public Task FormatFunctionPointer() + => AssertFormatAsync(""" + unsafe class C + { + delegate* functionPointer; + } + """, """ + unsafe class C + { + delegate * < int , int > functionPointer; + } + """); [Fact] - public async Task FormatFunctionPointerWithManagedCallingConvention() - { - var content = @" -unsafe class C -{ - delegate *managed < int , int > functionPointer; -}"; - - var expected = @" -unsafe class C -{ - delegate* managed functionPointer; -}"; - - await AssertFormatAsync(expected, content); - } + public Task FormatFunctionPointerWithManagedCallingConvention() + => AssertFormatAsync(""" + unsafe class C + { + delegate* managed functionPointer; + } + """, """ + unsafe class C + { + delegate *managed < int , int > functionPointer; + } + """); [Fact] - public async Task FormatFunctionPointerWithUnmanagedCallingConvention() - { - var content = @" -unsafe class C -{ - delegate *unmanaged < int , int > functionPointer; -}"; - - var expected = @" -unsafe class C -{ - delegate* unmanaged functionPointer; -}"; - - await AssertFormatAsync(expected, content); - } + public Task FormatFunctionPointerWithUnmanagedCallingConvention() + => AssertFormatAsync(""" + unsafe class C + { + delegate* unmanaged functionPointer; + } + """, """ + unsafe class C + { + delegate *unmanaged < int , int > functionPointer; + } + """); [Fact] - public async Task FormatFunctionPointerWithUnmanagedCallingConventionAndSpecifiers() - { - var content = @" -unsafe class C -{ - delegate *unmanaged [ Cdecl , Thiscall ] < int , int > functionPointer; -}"; - - var expected = @" -unsafe class C -{ - delegate* unmanaged[Cdecl, Thiscall] functionPointer; -}"; - - await AssertFormatAsync(expected, content); - } + public Task FormatFunctionPointerWithUnmanagedCallingConventionAndSpecifiers() + => AssertFormatAsync(""" + unsafe class C + { + delegate* unmanaged[Cdecl, Thiscall] functionPointer; + } + """, """ + unsafe class C + { + delegate *unmanaged [ Cdecl , Thiscall ] < int , int > functionPointer; + } + """); [Fact] - public async Task FormatFunctionPointerWithUnrecognizedCallingConvention() - { - var content = @" -unsafe class C -{ - delegate *invalid < int , int > functionPointer; -}"; - - var expected = @" -unsafe class C -{ - delegate*invalid functionPointer; -}"; - - await AssertFormatAsync(expected, content); - } + public Task FormatFunctionPointerWithUnrecognizedCallingConvention() + => AssertFormatAsync(""" + unsafe class C + { + delegate*invalid functionPointer; + } + """, """ + unsafe class C + { + delegate *invalid < int , int > functionPointer; + } + """); [Fact] - public async Task FormatFunctionPointerWithInvalidCallingConventionAndSpecifiers() - { - var content = @" -unsafe class C -{ - delegate *invalid [ Cdecl , Thiscall ] < int , int > functionPointer; -}"; - - var expected = @" -unsafe class C -{ - delegate*invalid [Cdecl, Thiscall] functionPointer; -}"; - - await AssertFormatAsync(expected, content); - } + public Task FormatFunctionPointerWithInvalidCallingConventionAndSpecifiers() + => AssertFormatAsync(""" + unsafe class C + { + delegate*invalid [Cdecl, Thiscall] functionPointer; + } + """, """ + unsafe class C + { + delegate *invalid [ Cdecl , Thiscall ] < int , int > functionPointer; + } + """); } diff --git a/src/Workspaces/CSharpTest/Formatting/FormattingTests_Patterns.cs b/src/Workspaces/CSharpTest/Formatting/FormattingTests_Patterns.cs index 0db9772924b86..f7907ffe98bc2 100644 --- a/src/Workspaces/CSharpTest/Formatting/FormattingTests_Patterns.cs +++ b/src/Workspaces/CSharpTest/Formatting/FormattingTests_Patterns.cs @@ -21,43 +21,33 @@ public async Task FormatRelationalPatterns1( [CombinatorialValues("<", "<=", ">", ">=")] string operatorText, BinaryOperatorSpacingOptions spacing) { - var content = $@" -class A -{{ - bool Method(int value) - {{ - return value is {operatorText} 3 or {operatorText} 5; - }} -}} -"; - - var expectedSingle = $@" -class A -{{ - bool Method(int value) - {{ - return value is {operatorText} 3 or {operatorText} 5; - }} -}} -"; - var expectedIgnore = $@" -class A -{{ - bool Method(int value) - {{ - return value is {operatorText} 3 or {operatorText} 5; - }} -}} -"; - var expectedRemove = $@" -class A -{{ - bool Method(int value) - {{ - return value is {operatorText}3 or {operatorText}5; - }} -}} -"; + var expectedSingle = $$""" + class A + { + bool Method(int value) + { + return value is {{operatorText}} 3 or {{operatorText}} 5; + } + } + """; + var expectedIgnore = $$""" + class A + { + bool Method(int value) + { + return value is {{operatorText}} 3 or {{operatorText}} 5; + } + } + """; + var expectedRemove = $$""" + class A + { + bool Method(int value) + { + return value is {{operatorText}}3 or {{operatorText}}5; + } + } + """; var expected = spacing switch { @@ -71,7 +61,15 @@ bool Method(int value) { { CSharpFormattingOptions2.SpacingAroundBinaryOperator, spacing }, }; - await AssertFormatAsync(expected, content, changedOptionSet: changingOptions); + await AssertFormatAsync(expected, $$""" + class A + { + bool Method(int value) + { + return value is {{operatorText}} 3 or {{operatorText}} 5; + } + } + """, changedOptionSet: changingOptions); } [Theory, CombinatorialData] @@ -80,70 +78,60 @@ public async Task FormatRelationalPatterns2( BinaryOperatorSpacingOptions spacing, bool spaceWithinExpressionParentheses) { - var content = $@" -class A -{{ - bool Method(int value) - {{ - return value is ( {operatorText} 3 ) or ( {operatorText} 5 ) ; - }} -}} -"; - - var expectedSingleFalse = $@" -class A -{{ - bool Method(int value) - {{ - return value is ({operatorText} 3) or ({operatorText} 5); - }} -}} -"; - var expectedIgnoreFalse = $@" -class A -{{ - bool Method(int value) - {{ - return value is ({operatorText} 3) or ({operatorText} 5); - }} -}} -"; - var expectedRemoveFalse = $@" -class A -{{ - bool Method(int value) - {{ - return value is ({operatorText}3) or ({operatorText}5); - }} -}} -"; - var expectedSingleTrue = $@" -class A -{{ - bool Method(int value) - {{ - return value is ( {operatorText} 3 ) or ( {operatorText} 5 ); - }} -}} -"; - var expectedIgnoreTrue = $@" -class A -{{ - bool Method(int value) - {{ - return value is ( {operatorText} 3 ) or ( {operatorText} 5 ); - }} -}} -"; - var expectedRemoveTrue = $@" -class A -{{ - bool Method(int value) - {{ - return value is ( {operatorText}3 ) or ( {operatorText}5 ); - }} -}} -"; + var expectedSingleFalse = $$""" + class A + { + bool Method(int value) + { + return value is ({{operatorText}} 3) or ({{operatorText}} 5); + } + } + """; + var expectedIgnoreFalse = $$""" + class A + { + bool Method(int value) + { + return value is ({{operatorText}} 3) or ({{operatorText}} 5); + } + } + """; + var expectedRemoveFalse = $$""" + class A + { + bool Method(int value) + { + return value is ({{operatorText}}3) or ({{operatorText}}5); + } + } + """; + var expectedSingleTrue = $$""" + class A + { + bool Method(int value) + { + return value is ( {{operatorText}} 3 ) or ( {{operatorText}} 5 ); + } + } + """; + var expectedIgnoreTrue = $$""" + class A + { + bool Method(int value) + { + return value is ( {{operatorText}} 3 ) or ( {{operatorText}} 5 ); + } + } + """; + var expectedRemoveTrue = $$""" + class A + { + bool Method(int value) + { + return value is ( {{operatorText}}3 ) or ( {{operatorText}}5 ); + } + } + """; var expected = (spacing, spaceWithinExpressionParentheses) switch { @@ -161,49 +149,47 @@ bool Method(int value) { CSharpFormattingOptions2.SpacingAroundBinaryOperator, spacing }, { CSharpFormattingOptions2.SpaceBetweenParentheses, CSharpFormattingOptions2.SpaceBetweenParentheses.DefaultValue.WithFlagValue(SpacePlacementWithinParentheses.Expressions, spaceWithinExpressionParentheses) }, }; - await AssertFormatAsync(expected, content, changedOptionSet: changingOptions); + await AssertFormatAsync(expected, $$""" + class A + { + bool Method(int value) + { + return value is ( {{operatorText}} 3 ) or ( {{operatorText}} 5 ) ; + } + } + """, changedOptionSet: changingOptions); } [Theory, CombinatorialData] public async Task FormatNotPatterns1(BinaryOperatorSpacingOptions spacing) { - var content = $@" -class A -{{ - bool Method(int value) - {{ - return value is not 3 or not 5; - }} -}} -"; - - var expectedSingle = $@" -class A -{{ - bool Method(int value) - {{ - return value is not 3 or not 5; - }} -}} -"; - var expectedIgnore = $@" -class A -{{ - bool Method(int value) - {{ - return value is not 3 or not 5; - }} -}} -"; - var expectedRemove = $@" -class A -{{ - bool Method(int value) - {{ - return value is not 3 or not 5; - }} -}} -"; + var expectedSingle = $$""" + class A + { + bool Method(int value) + { + return value is not 3 or not 5; + } + } + """; + var expectedIgnore = $$""" + class A + { + bool Method(int value) + { + return value is not 3 or not 5; + } + } + """; + var expectedRemove = $$""" + class A + { + bool Method(int value) + { + return value is not 3 or not 5; + } + } + """; var expected = spacing switch { @@ -217,7 +203,15 @@ bool Method(int value) { { CSharpFormattingOptions2.SpacingAroundBinaryOperator, spacing }, }; - await AssertFormatAsync(expected, content, changedOptionSet: changingOptions); + await AssertFormatAsync(expected, $$""" + class A + { + bool Method(int value) + { + return value is not 3 or not 5; + } + } + """, changedOptionSet: changingOptions); } [Theory, CombinatorialData] @@ -225,70 +219,60 @@ public async Task FormatNotPatterns2( BinaryOperatorSpacingOptions spacing, bool spaceWithinExpressionParentheses) { - var content = $@" -class A -{{ - bool Method(int value) - {{ - return value is ( not 3 ) or ( not 5 ); - }} -}} -"; - - var expectedSingleFalse = $@" -class A -{{ - bool Method(int value) - {{ - return value is (not 3) or (not 5); - }} -}} -"; - var expectedIgnoreFalse = $@" -class A -{{ - bool Method(int value) - {{ - return value is (not 3) or (not 5); - }} -}} -"; - var expectedRemoveFalse = $@" -class A -{{ - bool Method(int value) - {{ - return value is (not 3) or (not 5); - }} -}} -"; - var expectedSingleTrue = $@" -class A -{{ - bool Method(int value) - {{ - return value is ( not 3 ) or ( not 5 ); - }} -}} -"; - var expectedIgnoreTrue = $@" -class A -{{ - bool Method(int value) - {{ - return value is ( not 3 ) or ( not 5 ); - }} -}} -"; - var expectedRemoveTrue = $@" -class A -{{ - bool Method(int value) - {{ - return value is ( not 3 ) or ( not 5 ); - }} -}} -"; + var expectedSingleFalse = $$""" + class A + { + bool Method(int value) + { + return value is (not 3) or (not 5); + } + } + """; + var expectedIgnoreFalse = $$""" + class A + { + bool Method(int value) + { + return value is (not 3) or (not 5); + } + } + """; + var expectedRemoveFalse = $$""" + class A + { + bool Method(int value) + { + return value is (not 3) or (not 5); + } + } + """; + var expectedSingleTrue = $$""" + class A + { + bool Method(int value) + { + return value is ( not 3 ) or ( not 5 ); + } + } + """; + var expectedIgnoreTrue = $$""" + class A + { + bool Method(int value) + { + return value is ( not 3 ) or ( not 5 ); + } + } + """; + var expectedRemoveTrue = $$""" + class A + { + bool Method(int value) + { + return value is ( not 3 ) or ( not 5 ); + } + } + """; var expected = (spacing, spaceWithinExpressionParentheses) switch { @@ -306,247 +290,216 @@ bool Method(int value) { CSharpFormattingOptions2.SpacingAroundBinaryOperator, spacing }, { CSharpFormattingOptions2.SpaceBetweenParentheses, CSharpFormattingOptions2.SpaceBetweenParentheses.DefaultValue.WithFlagValue(SpacePlacementWithinParentheses.Expressions, spaceWithinExpressionParentheses) }, }; - await AssertFormatAsync(expected, content, changedOptionSet: changingOptions); + await AssertFormatAsync(expected, $$""" + class A + { + bool Method(int value) + { + return value is ( not 3 ) or ( not 5 ); + } + } + """, changedOptionSet: changingOptions); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46284")] - public async Task FormatMultiLinePattern1() - { - var content = @" -class TypeName -{ - bool MethodName(string value) - { - return value is object - && value is - { - Length: 2, - }; - } -} -"; - var expected = @" -class TypeName -{ - bool MethodName(string value) - { - return value is object - && value is - { - Length: 2, - }; - } -} -"; - - await AssertFormatAsync(expected, content); - } + public Task FormatMultiLinePattern1() + => AssertFormatAsync(""" + class TypeName + { + bool MethodName(string value) + { + return value is object + && value is + { + Length: 2, + }; + } + } + """, """ + class TypeName + { + bool MethodName(string value) + { + return value is object + && value is + { + Length: 2, + }; + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46284")] - public async Task FormatMultiLinePattern2() - { - var content = @" -class TypeName -{ - private static bool IsCallingConventionModifier(CustomModifier modifier) - { - var modifierType = ((CSharpCustomModifier)modifier).ModifierSymbol; - return (object)modifierType.ContainingAssembly == modifierType.ContainingAssembly.CorLibrary - && modifierType.Name != ""CallConv"" - && modifierType.Arity == 0 - && modifierType.Name.StartsWith(""CallConv"", StringComparison.Ordinal) - && modifierType.ContainingNamespace is - { - Name: ""CompilerServices"", - ContainingNamespace: - { - Name: ""Runtime"", - ContainingNamespace: - { - Name: ""System"", - ContainingNamespace: { IsGlobalNamespace: true } - } - } - }; - } -} -"; - var expected = @" -class TypeName -{ - private static bool IsCallingConventionModifier(CustomModifier modifier) - { - var modifierType = ((CSharpCustomModifier)modifier).ModifierSymbol; - return (object)modifierType.ContainingAssembly == modifierType.ContainingAssembly.CorLibrary - && modifierType.Name != ""CallConv"" - && modifierType.Arity == 0 - && modifierType.Name.StartsWith(""CallConv"", StringComparison.Ordinal) - && modifierType.ContainingNamespace is - { - Name: ""CompilerServices"", - ContainingNamespace: - { - Name: ""Runtime"", - ContainingNamespace: - { - Name: ""System"", - ContainingNamespace: { IsGlobalNamespace: true } - } - } - }; - } -} -"; - - await AssertFormatAsync(expected, content); - } + public Task FormatMultiLinePattern2() + => AssertFormatAsync(""" + class TypeName + { + private static bool IsCallingConventionModifier(CustomModifier modifier) + { + var modifierType = ((CSharpCustomModifier)modifier).ModifierSymbol; + return (object)modifierType.ContainingAssembly == modifierType.ContainingAssembly.CorLibrary + && modifierType.Name != "CallConv" + && modifierType.Arity == 0 + && modifierType.Name.StartsWith("CallConv", StringComparison.Ordinal) + && modifierType.ContainingNamespace is + { + Name: "CompilerServices", + ContainingNamespace: + { + Name: "Runtime", + ContainingNamespace: + { + Name: "System", + ContainingNamespace: { IsGlobalNamespace: true } + } + } + }; + } + } + """, """ + class TypeName + { + private static bool IsCallingConventionModifier(CustomModifier modifier) + { + var modifierType = ((CSharpCustomModifier)modifier).ModifierSymbol; + return (object)modifierType.ContainingAssembly == modifierType.ContainingAssembly.CorLibrary + && modifierType.Name != "CallConv" + && modifierType.Arity == 0 + && modifierType.Name.StartsWith("CallConv", StringComparison.Ordinal) + && modifierType.ContainingNamespace is + { + Name: "CompilerServices", + ContainingNamespace: + { + Name: "Runtime", + ContainingNamespace: + { + Name: "System", + ContainingNamespace: { IsGlobalNamespace: true } + } + } + }; + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/46284")] - public async Task FormatMultiLinePattern3() - { - var content = @" -class TypeName -{ - private static bool IsCallingConventionModifier(CustomModifier modifier) - { - var modifierType = ((CSharpCustomModifier)modifier).ModifierSymbol; - return (object)modifierType.ContainingAssembly == modifierType.ContainingAssembly.CorLibrary - && modifierType.Name != ""CallConv"" - && modifierType.Arity == 0 - && modifierType.Name.StartsWith(""CallConv"", StringComparison.Ordinal) - && modifierType.ContainingNamespace is -{ -Name: ""CompilerServices"", -ContainingNamespace: -{ -Name: ""Runtime"", -ContainingNamespace: -{ -Name: ""System"", -ContainingNamespace: { IsGlobalNamespace: true } -} -} -}; - } -} -"; - var expected = @" -class TypeName -{ - private static bool IsCallingConventionModifier(CustomModifier modifier) - { - var modifierType = ((CSharpCustomModifier)modifier).ModifierSymbol; - return (object)modifierType.ContainingAssembly == modifierType.ContainingAssembly.CorLibrary - && modifierType.Name != ""CallConv"" - && modifierType.Arity == 0 - && modifierType.Name.StartsWith(""CallConv"", StringComparison.Ordinal) - && modifierType.ContainingNamespace is - { - Name: ""CompilerServices"", - ContainingNamespace: - { - Name: ""Runtime"", - ContainingNamespace: - { - Name: ""System"", - ContainingNamespace: { IsGlobalNamespace: true } - } - } - }; - } -} -"; - - await AssertFormatAsync(expected, content); - } - - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42861")] - public async Task FormatMultiLinePattern4() - { - var content = @" -class TypeName -{ - void MethodName(string value) - { - if (value is - { - Length: 2, - }) -{ -} - } -} -"; - var expected = @" -class TypeName -{ - void MethodName(string value) - { - if (value is + public Task FormatMultiLinePattern3() + => AssertFormatAsync(""" + class TypeName { - Length: 2, - }) - { - } - } -} -"; - - await AssertFormatAsync(expected, content); - } + private static bool IsCallingConventionModifier(CustomModifier modifier) + { + var modifierType = ((CSharpCustomModifier)modifier).ModifierSymbol; + return (object)modifierType.ContainingAssembly == modifierType.ContainingAssembly.CorLibrary + && modifierType.Name != "CallConv" + && modifierType.Arity == 0 + && modifierType.Name.StartsWith("CallConv", StringComparison.Ordinal) + && modifierType.ContainingNamespace is + { + Name: "CompilerServices", + ContainingNamespace: + { + Name: "Runtime", + ContainingNamespace: + { + Name: "System", + ContainingNamespace: { IsGlobalNamespace: true } + } + } + }; + } + } + """, """ + class TypeName + { + private static bool IsCallingConventionModifier(CustomModifier modifier) + { + var modifierType = ((CSharpCustomModifier)modifier).ModifierSymbol; + return (object)modifierType.ContainingAssembly == modifierType.ContainingAssembly.CorLibrary + && modifierType.Name != "CallConv" + && modifierType.Arity == 0 + && modifierType.Name.StartsWith("CallConv", StringComparison.Ordinal) + && modifierType.ContainingNamespace is + { + Name: "CompilerServices", + ContainingNamespace: + { + Name: "Runtime", + ContainingNamespace: + { + Name: "System", + ContainingNamespace: { IsGlobalNamespace: true } + } + } + }; + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42861")] - public async Task FormatMultiLinePattern5() - { - var content = @" -class TypeName -{ - void MethodName(string value) - { - while (value is - { - Length: 2, - }) -{ -} - } -} -"; - var expected = @" -class TypeName -{ - void MethodName(string value) - { - while (value is + public Task FormatMultiLinePattern4() + => AssertFormatAsync(""" + class TypeName { - Length: 2, - }) - { - } - } -} -"; - - await AssertFormatAsync(expected, content); - } + void MethodName(string value) + { + if (value is + { + Length: 2, + }) + { + } + } + } + """, """ + class TypeName + { + void MethodName(string value) + { + if (value is + { + Length: 2, + }) + { + } + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42861")] - public async Task FormatNestedListPattern1() - { - var content = """ - class C + public Task FormatMultiLinePattern5() + => AssertFormatAsync(""" + class TypeName { - void M(string[] ss) + void MethodName(string value) { - if (ss is [ [ ] ]) + while (value is + { + Length: 2, + }) { - } } } - """; + """, """ + class TypeName + { + void MethodName(string value) + { + while (value is + { + Length: 2, + }) + { + } + } + } + """); - var expected = """ + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42861")] + public Task FormatNestedListPattern1() + => AssertFormatAsync(""" class C { void M(string[] ss) @@ -557,28 +510,22 @@ void M(string[] ss) } } } - """; - - await AssertFormatAsync(expected, content); - } - - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42861")] - public async Task FormatNestedListPattern2() - { - var content = """ + """, """ class C { void M(string[] ss) { - if (ss is [ [ ],[ ] ]) + if (ss is [ [ ] ]) { } } } - """; + """); - var expected = """ + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42861")] + public Task FormatNestedListPattern2() + => AssertFormatAsync(""" class C { void M(string[] ss) @@ -589,28 +536,22 @@ void M(string[] ss) } } } - """; - - await AssertFormatAsync(expected, content); - } - - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42861")] - public async Task FormatNestedListPattern3() - { - var content = """ + """, """ class C { void M(string[] ss) { - if (ss is [ [ ],[ ] , [ ] ] ) + if (ss is [ [ ],[ ] ]) { } } } - """; + """); - var expected = """ + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42861")] + public Task FormatNestedListPattern3() + => AssertFormatAsync(""" class C { void M(string[] ss) @@ -621,28 +562,22 @@ void M(string[] ss) } } } - """; - - await AssertFormatAsync(expected, content); - } - - [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42861")] - public async Task FormatNestedListPattern4() - { - var content = """ + """, """ class C { - void M(string[][] ss) + void M(string[] ss) { - if (ss is [ [ [ ] ] ] ) + if (ss is [ [ ],[ ] , [ ] ] ) { } } } - """; + """); - var expected = """ + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/42861")] + public Task FormatNestedListPattern4() + => AssertFormatAsync(""" class C { void M(string[][] ss) @@ -653,8 +588,16 @@ void M(string[][] ss) } } } - """; + """, """ + class C + { + void M(string[][] ss) + { + if (ss is [ [ [ ] ] ] ) + { - await AssertFormatAsync(expected, content); - } + } + } + } + """); } diff --git a/src/Workspaces/CSharpTest/Formatting/FormattingTreeEditTests.cs b/src/Workspaces/CSharpTest/Formatting/FormattingTreeEditTests.cs index 8aa6f61d7e806..b1391b2d62172 100644 --- a/src/Workspaces/CSharpTest/Formatting/FormattingTreeEditTests.cs +++ b/src/Workspaces/CSharpTest/Formatting/FormattingTreeEditTests.cs @@ -28,12 +28,12 @@ private static Document GetDocument(string code) [Fact] public async Task SpaceAfterAttribute() { - var code = @" -public class C -{ - void M(int? p) { } -} -"; + var code = """ + public class C + { + void M(int? p) { } + } + """; var document = GetDocument(code); var g = SyntaxGenerator.GetGenerator(document); var root = await document.GetSyntaxRootAsync(); @@ -45,12 +45,12 @@ void M(int? p) { } var result1 = Formatter.Format(root1, document.Project.Solution.Services, options, CancellationToken.None); - Assert.Equal(@" -public class C -{ - void M([MyAttr] int? p) { } -} -", result1.ToFullString()); + Assert.Equal(""" + public class C + { + void M([MyAttr] int? p) { } + } + """, result1.ToFullString()); // verify change doesn't affect how attributes appear before other kinds of declarations var method = root.DescendantNodes().OfType().First(); @@ -58,12 +58,12 @@ void M([MyAttr] int? p) { } var root2 = root.ReplaceNode(method, g.AddAttributes(method, g.Attribute("MyAttr"))); var result2 = Formatter.Format(root2, document.Project.Solution.Services, options, CancellationToken.None); - Assert.Equal(@" -public class C -{ - [MyAttr] - void M(int? p) { } -} -", result2.ToFullString()); + Assert.Equal(""" + public class C + { + [MyAttr] + void M(int? p) { } + } + """, result2.ToFullString()); } } diff --git a/src/Workspaces/CSharpTest/Formatting/FormattingTriviaTests.cs b/src/Workspaces/CSharpTest/Formatting/FormattingTriviaTests.cs index 6fd504c052723..1d6acc43d167b 100644 --- a/src/Workspaces/CSharpTest/Formatting/FormattingTriviaTests.cs +++ b/src/Workspaces/CSharpTest/Formatting/FormattingTriviaTests.cs @@ -4,15 +4,15 @@ #nullable disable +using System; using System.Linq; -using Microsoft.CodeAnalysis.Test.Utilities; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Formatting; +using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; -using System.Threading.Tasks; -using System.Threading; -using Microsoft.CodeAnalysis.CSharp.Formatting; -using System; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Formatting; @@ -20,1720 +20,1554 @@ namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Formatting; public sealed class FormattingEngineTriviaTests : CSharpFormattingTestBase { [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/31130")] - public async Task PreprocessorNullable() - { - var content = @" - #nullable -class C -{ - #nullable enable - void Method() - { - #nullable disable - } -}"; - - var expected = @" -#nullable -class C -{ -#nullable enable - void Method() - { -#nullable disable - } -}"; - await AssertFormatAsync(expected, content); - } + public Task PreprocessorNullable() + => AssertFormatAsync(""" + #nullable + class C + { + #nullable enable + void Method() + { + #nullable disable + } + } + """, """ + #nullable + class C + { + #nullable enable + void Method() + { + #nullable disable + } + } + """); [Fact] - public async Task PreprocessorInEmptyFile() - { - var content = @" - + public Task PreprocessorInEmptyFile() + => AssertFormatAsync(""" #line 1000 - #error - "; - - var expected = @" - -#line 1000 -#error -"; - - await AssertFormatAsync(expected, content); - } + #error + """, """ + #line 1000 + #error + """); [Fact] - public async Task Comment1() - { - var content = @" // single line comment - class C { }"; - - var expected = @"// single line comment -class C { }"; - - await AssertFormatAsync(expected, content); - } + public Task Comment1() + => AssertFormatAsync(""" + // single line comment + class C { } + """, """ + // single line comment + class C { } + """); [Fact] - public async Task Comment2() - { - var content = @"class C -{ + public Task Comment2() + => AssertFormatAsync(""" + class C + { // single line comment - int i; -}"; - - var expected = @"class C -{ - // single line comment - int i; -}"; - - await AssertFormatAsync(expected, content); - } + int i; + } + """, """ + class C + { + // single line comment + int i; + } + """); [Fact] - public async Task Comment3() - { - var content = @"class C -{ + public Task Comment3() + => AssertFormatAsync(""" + class C + { // single line comment -}"; - - var expected = @"class C -{ - // single line comment -}"; - - await AssertFormatAsync(expected, content); - } + } + """, """ + class C + { + // single line comment + } + """); [Fact] - public async Task Comment4() - { - var content = @"class C -{ + public Task Comment4() + => AssertFormatAsync(""" + class C + { // single line comment -// single line comment 2 - void Method() { } -}"; - - var expected = @"class C -{ - // single line comment - // single line comment 2 - void Method() { } -}"; - - await AssertFormatAsync(expected, content); - } + // single line comment 2 + void Method() { } + } + """, """ + class C + { + // single line comment + // single line comment 2 + void Method() { } + } + """); [Fact] - public async Task Comment5() - { - var content = @"class C -{ - void Method() { - // single line comment - // single line comment 2 -} -}"; - - var expected = @"class C -{ - void Method() - { - // single line comment - // single line comment 2 - } -}"; - - await AssertFormatAsync(expected, content); - } + public Task Comment5() + => AssertFormatAsync(""" + class C + { + void Method() + { + // single line comment + // single line comment 2 + } + } + """, """ + class C + { + void Method() { + // single line comment + // single line comment 2 + } + } + """); [Fact] - public async Task Comment6() - { - var content = @"class C -{ - void Method() { - // single line comment - // single line comment 2 - int i = 10; -} -}"; - - var expected = @"class C -{ - void Method() - { - // single line comment - // single line comment 2 - int i = 10; - } -}"; - - await AssertFormatAsync(expected, content); - } + public Task Comment6() + => AssertFormatAsync(""" + class C + { + void Method() + { + // single line comment + // single line comment 2 + int i = 10; + } + } + """, """ + class C + { + void Method() { + // single line comment + // single line comment 2 + int i = 10; + } + } + """); [Fact] - public async Task Comment7() - { - var content = @"class C -{ - void Method() { - // single line comment - - int i = 10; - - // single line comment 2 -} -}"; - - var expected = @"class C -{ - void Method() - { - // single line comment - - int i = 10; + public Task Comment7() + => AssertFormatAsync(""" + class C + { + void Method() + { + // single line comment + + int i = 10; + + // single line comment 2 + } + } + """, """ + class C + { + void Method() { + // single line comment - // single line comment 2 - } -}"; + int i = 10; - await AssertFormatAsync(expected, content); - } + // single line comment 2 + } + } + """); [Fact] - public async Task Comment8() - { - var content = @"class C -{ - void Method() { - /* multiline comment */ - - int i = 10; -} -}"; - - var expected = @"class C -{ - void Method() - { - /* multiline comment */ - - int i = 10; - } -}"; - - await AssertFormatAsync(expected, content); - } + public Task Comment8() + => AssertFormatAsync(""" + class C + { + void Method() + { + /* multiline comment */ + + int i = 10; + } + } + """, """ + class C + { + void Method() { + /* multiline comment */ + + int i = 10; + } + } + """); [Fact] - public async Task Comment9() - { - var content = @"class C -{ - void Method() { - /* multiline comment */ - - int i = 10; -} -}"; - - var expected = @"class C -{ - void Method() - { - /* multiline comment */ - - int i = 10; - } -}"; - - await AssertFormatAsync(expected, content); - } + public Task Comment9() + => AssertFormatAsync(""" + class C + { + void Method() + { + /* multiline comment */ + + int i = 10; + } + } + """, """ + class C + { + void Method() { + /* multiline comment */ + + int i = 10; + } + } + """); [Fact] - public async Task Comment10() - { - var content = @"class C -{ - void Method() { - /* multiline comment */ - - int i = 10; -/* multiline comment */ -} -}"; - - var expected = @"class C -{ - void Method() - { - /* multiline comment */ - - int i = 10; - /* multiline comment */ - } -}"; - - await AssertFormatAsync(expected, content); - } + public Task Comment10() + => AssertFormatAsync(""" + class C + { + void Method() + { + /* multiline comment */ + + int i = 10; + /* multiline comment */ + } + } + """, """ + class C + { + void Method() { + /* multiline comment */ + + int i = 10; + /* multiline comment */ + } + } + """); [Fact] - public async Task Comment11() - { - var content = @"class C -{ - void Method() { + public Task Comment11() + => AssertFormatAsync(""" + class C + { + void Method() + { /* * multiline comment */ - int i = 10; - -/* - * multiline comment - */ -} -}"; - - var expected = @"class C -{ - void Method() - { - /* - * multiline comment - */ - - int i = 10; + int i = 10; - /* - * multiline comment - */ - } -}"; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task Comment12() - { - var content = @"class C -{ - void Method() { - /* + /* * multiline comment */ + } + } + """, """ + class C + { + void Method() { + /* + * multiline comment + */ - int i = 10; + int i = 10; - /* + /* * multiline comment */ -} -}"; - - var expected = @"class C -{ - void Method() - { - /* -* multiline comment -*/ - - int i = 10; - - /* -* multiline comment -*/ - } -}"; - - await AssertFormatAsync(expected, content); - } + } + } + """); [Fact] - public async Task Comment13() - { - var content = @"class C -{ - void Method() { // test - int i = 10; -} -}"; - - var expected = @"class C -{ - void Method() - { // test - int i = 10; - } -}"; + public Task Comment12() + => AssertFormatAsync(""" + class C + { + void Method() + { + /* + * multiline comment + */ - await AssertFormatAsync(expected, content); - } + int i = 10; - [Fact] - public async Task Comment14() - { - var content = @"class C -{ - void Method() { // test - // test 2 - // test 3 - int i = 10; -} -}"; + /* + * multiline comment + */ + } + } + """, """ + class C + { + void Method() { + /* + * multiline comment + */ - var expected = @"class C -{ - void Method() - { // test - // test 2 - // test 3 - int i = 10; - } -}"; + int i = 10; - await AssertFormatAsync(expected, content); - } + /* + * multiline comment + */ + } + } + """); [Fact] - public async Task Comment15() - { - var content = @"class C -{ - void Method() { /* test */ - int i = 10; -} -}"; - - var expected = @"class C -{ - void Method() - { /* test */ - int i = 10; - } -}"; - - await AssertFormatAsync(expected, content); - } + public Task Comment13() + => AssertFormatAsync(""" + class C + { + void Method() + { // test + int i = 10; + } + } + """, """ + class C + { + void Method() { // test + int i = 10; + } + } + """); [Fact] - public async Task Comment16() - { - var content = @"class C -{ - void Method() { /* test - * - */ - int i = 10; -} -}"; + public Task Comment14() + => AssertFormatAsync(""" + class C + { + void Method() + { // test + // test 2 + // test 3 + int i = 10; + } + } + """, """ + class C + { + void Method() { // test + // test 2 + // test 3 + int i = 10; + } + } + """); - var expected = @"class C -{ - void Method() - { /* test - * - */ - int i = 10; - } -}"; + [Fact] + public Task Comment15() + => AssertFormatAsync(""" + class C + { + void Method() + { /* test */ + int i = 10; + } + } + """, """ + class C + { + void Method() { /* test */ + int i = 10; + } + } + """); - await AssertFormatAsync(expected, content); - } + [Fact] + public Task Comment16() + => AssertFormatAsync(""" + class C + { + void Method() + { /* test + * + */ + int i = 10; + } + } + """, """ + class C + { + void Method() { /* test + * + */ + int i = 10; + } + } + """); [Fact] - public async Task Comment17() - { - var content = @"class C -{ - void Method() { + public Task Comment17() + => AssertFormatAsync(""" + class C + { + void Method() + { /* test * */ // test - int i = 10; -} -}"; - - var expected = @"class C -{ - void Method() - { - /* test - * - */ // test - int i = 10; - } -}"; - - await AssertFormatAsync(expected, content); - } + int i = 10; + } + } + """, """ + class C + { + void Method() { + /* test + * + */ // test + int i = 10; + } + } + """); [Fact] - public async Task Comment18() - { - var content = @"class C -{ - void Method() { + public Task Comment18() + => AssertFormatAsync(""" + class C + { + void Method() + { /* test * */ // test // test 2 - int i = 10; -} -}"; - - var expected = @"class C -{ - void Method() - { - /* test - * - */ // test - // test 2 - int i = 10; - } -}"; - - await AssertFormatAsync(expected, content); - } + int i = 10; + } + } + """, """ + class C + { + void Method() { + /* test + * + */ // test + // test 2 + int i = 10; + } + } + """); [Fact] - public async Task Comment19() - { - var content = @"class C -{ - void Method() { + public Task Comment19() + => AssertFormatAsync(""" + class C + { + void Method() + { /* test * */ /* test 2 * */ - int i = 10; -} -}"; - - var expected = @"class C -{ - void Method() - { - /* test - * - */ /* test 2 - * - */ - int i = 10; - } -}"; - - await AssertFormatAsync(expected, content); - } + int i = 10; + } + } + """, """ + class C + { + void Method() { + /* test + * + */ /* test 2 + * + */ + int i = 10; + } + } + """); [Fact] - public async Task Comment20() - { - var content = @"class C -{ - void Method() { - int i = 10; + public Task Comment20() + => AssertFormatAsync(""" + class C + { + void Method() + { + int i = 10; /* test * */ /* test 2 * */ -} -}"; - - var expected = @"class C -{ - void Method() - { - int i = 10; - /* test - * - */ /* test 2 - * - */ - } -}"; - - await AssertFormatAsync(expected, content); - } - - // for now, formatting engine doesn't re-indent token if the indentation line contains noisy - // chars - [Fact] - public async Task Comment21() - { - var content = @"class C -{ - void Method() { - /* */ int i = 10; -} -}"; - - var expected = @"class C -{ - void Method() - { - /* */ - int i = 10; - } -}"; - - await AssertFormatAsync(expected, content); - } + } + } + """, """ + class C + { + void Method() { + int i = 10; + /* test + * + */ /* test 2 + * + */ + } + } + """); // for now, formatting engine doesn't re-indent token if the indentation line contains noisy // chars - [Fact] - public async Task Comment22() - { - var content = @"class C -{ - void Method() { - int i = - /* */ 10; -} -}"; - - var expected = @"class C -{ - void Method() - { - int i = - /* */ 10; - } -}"; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task Comment23() - { - var content = @"class C -{ - void Method() { - int /* */ i = /* */ 10; -} -}"; - - var expected = @"class C -{ - void Method() - { - int /* */ i = /* */ 10; - } -}"; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task Comment24() - { - var content = @"class C -{ - void Method() { - /* - */ int i = 10; -} -}"; - - var expected = @"class C -{ - void Method() - { - /* - */ - int i = 10; - } -}"; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task DocComment1() - { - var content = @"class C -{ - void Method() { - /** - */ - int i = 10; -} -}"; - - var expected = @"class C -{ - void Method() - { - /** - */ - int i = 10; - } -}"; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task DocComment2() - { - var content = @"class C -{ - void Method() { /** - */ - int i = 10; -} -}"; - - var expected = @"class C -{ - void Method() - { /** - */ - int i = 10; - } -}"; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task DocComment3() - { - var content = @"class C -{ - void Method() { - int i = 10; - /** - */ -} -}"; - - var expected = @"class C -{ - void Method() - { - int i = 10; - /** - */ - } -}"; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task DocComment4() - { - var content = @"class C -{ - void Method() { - int i = 10; /** - */ -} -}"; - - var expected = @"class C -{ - void Method() - { - int i = 10; /** - */ - } -}"; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task DocComment5() - { - var content = @"class C -{ - void Method() { - int i = 10; /** */ -} -}"; - - var expected = @"class C -{ - void Method() - { - int i = 10; /** */ - } -}"; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task DocComment6() - { - var content = @"class C -{ - void Method() { - int i /** */ = - /** */ 10; -} -}"; - - var expected = @"class C -{ - void Method() - { - int i /** */ = - /** */ 10; - } -}"; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task DocComment7() - { - var content = @"class C -{ - void Method() { /// - /// - int i = 10; -} -}"; - - var expected = @"class C -{ - void Method() - { /// - /// - int i = 10; - } -}"; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task DocComment8() - { - var content = @"class C -{ - void Method() { - /// - /// - int i = 10; -} -}"; - - var expected = @"class C -{ - void Method() - { - /// - /// - int i = 10; - } -}"; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task DocComment9() - { - var content = @"class C -{ - void Method() { - int i = 10; -/// - /// -} -}"; - - var expected = @"class C -{ - void Method() - { - int i = 10; - /// - /// - } -}"; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task DocComment10() - { - var content = @"class C -{ - void Method() { -/// -/** - */ /// - /// - int i = 10; -} -}"; - - var expected = @"class C -{ - void Method() - { - /// - /** - */ /// - /// - int i = 10; - } -}"; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task DocComment11() - { - var content = @"class C -{ - void Method() { -/// -/** - */ /** - * - */ - int i = 10; -} -}"; - - var expected = @"class C -{ - void Method() - { - /// - /** - */ /** - * - */ - int i = 10; - } -}"; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task DocComment12() - { - var content = @"class C -{ - void Method() { -/// -/** - */ /** */ - int i = 10; -} -}"; - - var expected = @"class C -{ - void Method() - { - /// - /** - */ /** */ - int i = 10; - } -}"; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task MixCommentAndDocComment1() - { - var content = @"class C -{ - void Method() { -// -/** - */ /* - */ // - int i = 10; -} -}"; - - var expected = @"class C -{ - void Method() - { - // - /** - */ /* - */ // - int i = 10; - } -}"; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task MixCommentAndDocComment2() - { - var content = @"class C -{ - void Method() { -/* - * - */ /** - * - */ /* - * - */ /// - /// - int i = 10; -} -}"; - - var expected = @"class C -{ - void Method() - { - /* - * - */ /** - * - */ /* - * - */ /// - /// - int i = 10; - } -}"; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task MixCommentAndDocComment3() - { - var content = @"class C -{ - void Method() { - // test - // test 2 - - /// - /// test 3 - /// - -int i = 10; -} -}"; - - var expected = @"class C -{ - void Method() - { - // test - // test 2 - - /// - /// test 3 - /// - - int i = 10; - } -}"; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task MixCommentAndDocComment4() - { - var content = @"class C -{ - /// - /// test 3 - /// -void Method() { - // test - // test 2 - -int i = 10; -} -}"; - - var expected = @"class C -{ - /// - /// test 3 - /// - void Method() - { - // test - // test 2 - - int i = 10; - } -}"; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task Preprocessor1() - { - var content = @"class C -{ - #if true - #endif -void Method() { -int i = 10; -} -}"; - - var expected = @"class C -{ -#if true -#endif - void Method() - { - int i = 10; - } -}"; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task Preprocessor2() - { - var content = @"class C -{ - #if true -void Method() { -int i = 10; -} -} - #endif -"; - - var expected = @"class C -{ -#if true - void Method() - { - int i = 10; - } -} -#endif -"; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task Preprocessor3() - { - var content = @"class C -{ - #if true -void Method() { - #elif false -int i = 10; -} -} - #endif -} -}"; - - var expected = @"class C -{ -#if true - void Method() - { -#elif false -int i = 10; -} -} -#endif - } -}"; - - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task Preprocessor4() - { - var content = @"class C -{ - #if true -void Method() { -} - #elif false -int i = 10; -} - #endif -} -"; - - var expected = @"class C -{ -#if true - void Method() - { - } -#elif false -int i = 10; -} -#endif -} -"; - - // turn off transformation check - conditional directive preprocessor - await AssertFormatAsync(expected, content); - } - - [Fact] - public async Task Preprocessor5() - { - var content = @"class C -{ - #region Test - int i = 10; - #endregion - -void Method() { -} -} -"; + [Fact] + public Task Comment21() + => AssertFormatAsync(""" + class C + { + void Method() + { + /* */ + int i = 10; + } + } + """, """ + class C + { + void Method() { + /* */ int i = 10; + } + } + """); - var expected = @"class C -{ - #region Test - int i = 10; - #endregion + // for now, formatting engine doesn't re-indent token if the indentation line contains noisy + // chars + [Fact] + public Task Comment22() + => AssertFormatAsync(""" + class C + { + void Method() + { + int i = + /* */ 10; + } + } + """, """ + class C + { + void Method() { + int i = + /* */ 10; + } + } + """); - void Method() - { - } -} -"; + [Fact] + public Task Comment23() + => AssertFormatAsync(""" + class C + { + void Method() + { + int /* */ i = /* */ 10; + } + } + """, """ + class C + { + void Method() { + int /* */ i = /* */ 10; + } + } + """); - await AssertFormatAsync(expected, content); - } + [Fact] + public Task Comment24() + => AssertFormatAsync(""" + class C + { + void Method() + { + /* + */ + int i = 10; + } + } + """, """ + class C + { + void Method() { + /* + */ int i = 10; + } + } + """); [Fact] - public async Task Preprocessor6() - { - var content = @"class C -{ - #region Test - int i = 10; - #endregion + public Task DocComment1() + => AssertFormatAsync(""" + class C + { + void Method() + { + /** + */ + int i = 10; + } + } + """, """ + class C + { + void Method() { + /** + */ + int i = 10; + } + } + """); -void Method() { -} -} -"; + [Fact] + public Task DocComment2() + => AssertFormatAsync(""" + class C + { + void Method() + { /** + */ + int i = 10; + } + } + """, """ + class C + { + void Method() { /** + */ + int i = 10; + } + } + """); - var expected = @"class C -{ - #region Test - int i = 10; - #endregion + [Fact] + public Task DocComment3() + => AssertFormatAsync(""" + class C + { + void Method() + { + int i = 10; + /** + */ + } + } + """, """ + class C + { + void Method() { + int i = 10; + /** + */ + } + } + """); - void Method() - { - } -} -"; + [Fact] + public Task DocComment4() + => AssertFormatAsync(""" + class C + { + void Method() + { + int i = 10; /** + */ + } + } + """, """ + class C + { + void Method() { + int i = 10; /** + */ + } + } + """); - await AssertFormatAsync(expected, content); - } + [Fact] + public Task DocComment5() + => AssertFormatAsync(""" + class C + { + void Method() + { + int i = 10; /** */ + } + } + """, """ + class C + { + void Method() { + int i = 10; /** */ + } + } + """); [Fact] - public async Task Preprocessor7() - { - var content = @"class C -{ - #region Test - int i = 10; - -void Method() { -} -#endregion -} -"; + public Task DocComment6() + => AssertFormatAsync(""" + class C + { + void Method() + { + int i /** */ = + /** */ 10; + } + } + """, """ + class C + { + void Method() { + int i /** */ = + /** */ 10; + } + } + """); - var expected = @"class C -{ - #region Test - int i = 10; + [Fact] + public Task DocComment7() + => AssertFormatAsync(""" + class C + { + void Method() + { /// + /// + int i = 10; + } + } + """, """ + class C + { + void Method() { /// + /// + int i = 10; + } + } + """); - void Method() - { - } - #endregion -} -"; + [Fact] + public Task DocComment8() + => AssertFormatAsync(""" + class C + { + void Method() + { + /// + /// + int i = 10; + } + } + """, """ + class C + { + void Method() { + /// + /// + int i = 10; + } + } + """); - await AssertFormatAsync(expected, content); - } + [Fact] + public Task DocComment9() + => AssertFormatAsync(""" + class C + { + void Method() + { + int i = 10; + /// + /// + } + } + """, """ + class C + { + void Method() { + int i = 10; + /// + /// + } + } + """); [Fact] - public async Task Preprocessor8() - { - var content = @"class C -{ - #region Test - int i = 10; - -void Method() { -#endregion -int i = 10; -} -} -"; + public Task DocComment10() + => AssertFormatAsync(""" + class C + { + void Method() + { + /// + /** + */ /// + /// + int i = 10; + } + } + """, """ + class C + { + void Method() { + /// + /** + */ /// + /// + int i = 10; + } + } + """); - var expected = @"class C -{ - #region Test - int i = 10; + [Fact] + public Task DocComment11() + => AssertFormatAsync(""" + class C + { + void Method() + { + /// + /** + */ /** + * + */ + int i = 10; + } + } + """, """ + class C + { + void Method() { + /// + /** + */ /** + * + */ + int i = 10; + } + } + """); - void Method() - { - #endregion - int i = 10; - } -} -"; + [Fact] + public Task DocComment12() + => AssertFormatAsync(""" + class C + { + void Method() + { + /// + /** + */ /** */ + int i = 10; + } + } + """, """ + class C + { + void Method() { + /// + /** + */ /** */ + int i = 10; + } + } + """); - await AssertFormatAsync(expected, content); - } + [Fact] + public Task MixCommentAndDocComment1() + => AssertFormatAsync(""" + class C + { + void Method() + { + // + /** + */ /* + */ // + int i = 10; + } + } + """, """ + class C + { + void Method() { + // + /** + */ /* + */ // + int i = 10; + } + } + """); [Fact] - public async Task MixAll() - { - var content = @"class C -{ - #region Test + public Task MixCommentAndDocComment2() + => AssertFormatAsync(""" + class C + { + void Method() + { + /* + * + */ /** + * + */ /* + * + */ /// + /// + int i = 10; + } + } + """, """ + class C + { + void Method() { + /* + * + */ /** + * + */ /* + * + */ /// + /// + int i = 10; + } + } + """); - #if true + [Fact] + public Task MixCommentAndDocComment3() + => AssertFormatAsync(""" + class C + { + void Method() + { + // test + // test 2 + /// + /// test 3 + /// + + int i = 10; + } + } + """, """ + class C + { + void Method() { // test + // test 2 + + /// + /// test 3 + /// + + int i = 10; + } + } + """); + + [Fact] + public Task MixCommentAndDocComment4() + => AssertFormatAsync(""" + class C + { + /// + /// test 3 /// - /// - int i = 10; + void Method() + { + // test + // test 2 - #else -void Method() { -} - #endif -#endregion -} -"; + int i = 10; + } + } + """, """ + class C + { + /// + /// test 3 + /// + void Method() { + // test + // test 2 - var expected = @"class C -{ - #region Test + int i = 10; + } + } + """); -#if true + [Fact] + public Task Preprocessor1() + => AssertFormatAsync(""" + class C + { + #if true + #endif + void Method() + { + int i = 10; + } + } + """, """ + class C + { + #if true + #endif + void Method() { + int i = 10; + } + } + """); - // test - /// - /// - int i = 10; + [Fact] + public Task Preprocessor2() + => AssertFormatAsync(""" + class C + { + #if true + void Method() + { + int i = 10; + } + } + #endif + """, """ + class C + { + #if true + void Method() { + int i = 10; + } + } + #endif + """); -#else -void Method() { -} -#endif - #endregion -} -"; + [Fact] + public Task Preprocessor3() + => AssertFormatAsync(""" + class C + { + #if true + void Method() + { + #elif false + int i = 10; + } + } + #endif + } + } + """, """ + class C + { + #if true + void Method() { + #elif false + int i = 10; + } + } + #endif + } + } + """); - // turn off transformation check since it doesn't work for conditional directive yet. - await AssertFormatAsync(expected, content); - } + [Fact] + public Task Preprocessor4() + => AssertFormatAsync(""" + class C + { + #if true + void Method() + { + } + #elif false + int i = 10; + } + #endif + } + """, """ + class C + { + #if true + void Method() { + } + #elif false + int i = 10; + } + #endif + } + """); - [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537895")] - public async Task Preprocessor9() - { - var content = @"class C -{ -void Method() { -#region Myregion - int a; - if (true) - a++; - #endregion -} -} -"; + [Fact] + public Task Preprocessor5() + => AssertFormatAsync(""" + class C + { + #region Test + int i = 10; + #endregion + + void Method() + { + } + } + """, """ + class C + { + #region Test + int i = 10; + #endregion + + void Method() { + } + } + """); - var expected = @"class C -{ - void Method() - { - #region Myregion - int a; - if (true) - a++; - #endregion - } -} -"; + [Fact] + public Task Preprocessor6() + => AssertFormatAsync(""" + class C + { + #region Test + int i = 10; + #endregion + + void Method() + { + } + } + """, """ + class C + { + #region Test + int i = 10; + #endregion + + void Method() { + } + } + """); - await AssertFormatAsync(expected, content); - } + [Fact] + public Task Preprocessor7() + => AssertFormatAsync(""" + class C + { + #region Test + int i = 10; + + void Method() + { + } + #endregion + } + """, """ + class C + { + #region Test + int i = 10; + + void Method() { + } + #endregion + } + """); - [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537895")] - public async Task Preprocessor10() - { - var content = @"class C -{ -void Method() { - int a; - if (true) - a++; -#region Myregion -} -} -"; + [Fact] + public Task Preprocessor8() + => AssertFormatAsync(""" + class C + { + #region Test + int i = 10; + + void Method() + { + #endregion + int i = 10; + } + } + """, """ + class C + { + #region Test + int i = 10; + + void Method() { + #endregion + int i = 10; + } + } + """); - var expected = @"class C -{ - void Method() - { - int a; - if (true) - a++; - #region Myregion - } -} -"; + [Fact] + public Task MixAll() + => AssertFormatAsync(""" + class C + { + #region Test - await AssertFormatAsync(expected, content); - } + #if true - [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537765")] - public async Task Comment25() - { - var content = @"class C -{ - void Goo()//method -{ - int x;//variable -double y; - } -} -"; + // test + /// + /// + int i = 10; + + #else + void Method() { + } + #endif + #endregion + } + """, """ + class C + { + #region Test + + #if true + + // test + /// + /// + int i = 10; + + #else + void Method() { + } + #endif + #endregion + } + """); - var expected = @"class C -{ - void Goo()//method - { - int x;//variable - double y; - } -} -"; + [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537895")] + public Task Preprocessor9() + => AssertFormatAsync(""" + class C + { + void Method() + { + #region Myregion + int a; + if (true) + a++; + #endregion + } + } + """, """ + class C + { + void Method() { + #region Myregion + int a; + if (true) + a++; + #endregion + } + } + """); - await AssertFormatAsync(expected, content); - } + [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537895")] + public Task Preprocessor10() + => AssertFormatAsync(""" + class C + { + void Method() + { + int a; + if (true) + a++; + #region Myregion + } + } + """, """ + class C + { + void Method() { + int a; + if (true) + a++; + #region Myregion + } + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537765")] - public async Task Comment26() - { - var content = @"public class Class1 -{ - void Goo() - { -/**/int x; - } -}"; - - var expected = @"public class Class1 -{ - void Goo() - { - /**/ - int x; - } -}"; + public Task Comment25() + => AssertFormatAsync(""" + class C + { + void Goo()//method + { + int x;//variable + double y; + } + } + """, """ + class C + { + void Goo()//method + { + int x;//variable + double y; + } + } + """); - await AssertFormatAsync(expected, content); - } + [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537765")] + public Task Comment26() + => AssertFormatAsync(""" + public class Class1 + { + void Goo() + { + /**/ + int x; + } + } + """, """ + public class Class1 + { + void Goo() + { + /**/int x; + } + } + """); [Fact] public async Task Comment27() { - var content = @"public class Class1 -{ - void Goo() - { - // - // - } -}"; + var content = """ + public class Class1 + { + void Goo() + { + // + // + } + } + """; await AssertFormatAsync(content, content); } [Fact] - public async Task Comment28() - { - var content = @"public class Class1 -{ - void Goo() - { - // - - // - - } -}"; - - var expected = @"public class Class1 -{ - void Goo() - { - // - - // - - } -}"; - await AssertFormatAsync(expected, content); - } + public Task Comment28() + => AssertFormatAsync(""" + public class Class1 + { + void Goo() + { + // + + // + + } + } + """, """ + public class Class1 + { + void Goo() + { + // + + // + + } + } + """); [Fact] - public async Task Comment29() - { - var content = @"public class Class1 -{ - void Goo() - { - int /**/ i = 10; - } -}"; - - var code = @"public class Class1 -{ - void Goo() - { - int /**/ i = 10; - } -}"; - - await AssertFormatAsync(code, content); - } + public Task Comment29() + => AssertFormatAsync(""" + public class Class1 + { + void Goo() + { + int /**/ i = 10; + } + } + """, """ + public class Class1 + { + void Goo() + { + int /**/ i = 10; + } + } + """); [Fact] - public async Task Comment30() - { - var content = @" -// Test"; - - var code = @" -// Test"; - - await AssertFormatAsync(code, content); - } + public Task Comment30() + => AssertFormatAsync(""" + // Test + """, """ + // Test + """); [Fact] - public async Task Comment31() - { - var content = @"/// -/// - /// -class Program -{ - static void Main(string[] args) - { - } -} -"; - - var code = @"/// -/// -/// -class Program -{ - static void Main(string[] args) - { - } -} -"; - - await AssertFormatAsync(code, content); - } + public Task Comment31() + => AssertFormatAsync(""" + /// + /// + /// + class Program + { + static void Main(string[] args) + { + } + } + """, """ + /// + /// + /// + class Program + { + static void Main(string[] args) + { + } + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538703")] - public async Task Comment32() - { - var content = @"class Program -{ - /// - /// TestMethod -/// - void Method() { } -} -"; - - var code = @"class Program -{ - /// - /// TestMethod - /// - void Method() { } -} -"; - - await AssertFormatAsync(code, content); - } + public Task Comment32() + => AssertFormatAsync(""" + class Program + { + /// + /// TestMethod + /// + void Method() { } + } + """, """ + class Program + { + /// + /// TestMethod + /// + void Method() { } + } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542316")] - public async Task CommentInExpression() - { - var content = @"using System; -using System.Collections.Generic; -using System.Linq; - -class Program -{ - static void Main(string[] args) - { - CreateCompilationWithMscorlib(source).VerifyDiagnostics( - // (10,30): error CS0455: Type parameter 'X' inherits conflicting constraints 'B' and 'A' - Diagnostic(ErrorCode.ERR_BaseConstraintConflict, ""X"").WithArguments(""X"", ""B"", ""A"").WithLocation(10, 30)); - } -} -"; - - var code = @"using System; -using System.Collections.Generic; -using System.Linq; - -class Program -{ - static void Main(string[] args) - { - CreateCompilationWithMscorlib(source).VerifyDiagnostics( - // (10,30): error CS0455: Type parameter 'X' inherits conflicting constraints 'B' and 'A' - Diagnostic(ErrorCode.ERR_BaseConstraintConflict, ""X"").WithArguments(""X"", ""B"", ""A"").WithLocation(10, 30)); - } -} -"; - - await AssertFormatAsync(code, content); - } + public Task CommentInExpression() + => AssertFormatAsync(""" + using System; + using System.Collections.Generic; + using System.Linq; + + class Program + { + static void Main(string[] args) + { + CreateCompilationWithMscorlib(source).VerifyDiagnostics( + // (10,30): error CS0455: Type parameter 'X' inherits conflicting constraints 'B' and 'A' + Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "X").WithArguments("X", "B", "A").WithLocation(10, 30)); + } + } + """, """ + using System; + using System.Collections.Generic; + using System.Linq; + + class Program + { + static void Main(string[] args) + { + CreateCompilationWithMscorlib(source).VerifyDiagnostics( + // (10,30): error CS0455: Type parameter 'X' inherits conflicting constraints 'B' and 'A' + Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "X").WithArguments("X", "B", "A").WithLocation(10, 30)); + } + } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44423")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542546")] - public async Task FormatInvalidCode_1() - { - var expected = @"> Roslyn.Utilities.dll! Basic"; - var content = @"> Roslyn.Utilities.dll! Basic"; - await AssertFormatAsync(expected, content); - } + public Task FormatInvalidCode_1() + => AssertFormatAsync(@"> Roslyn.Utilities.dll! Basic", @"> Roslyn.Utilities.dll! Basic"); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/44423")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542546")] - public async Task FormatInvalidCode_2() - { - var content = @"> Roslyn.Utilities.dll! Line 43 + 0x5 bytes Basic"; - var expectedContent = @"> Roslyn.Utilities.dll! Line 43 + 0x5 bytes Basic"; - await AssertFormatAsync(expectedContent, content); - } + public Task FormatInvalidCode_2() + => AssertFormatAsync(@"> Roslyn.Utilities.dll! Line 43 + 0x5 bytes Basic", @"> Roslyn.Utilities.dll! Line 43 + 0x5 bytes Basic"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537895")] - public async Task EmbededStatement1() - { - var content = @"using System; -using System.Collections.Generic; -using System.Linq; - -class Program -{ - static void Main(string[] args) - { - #region Myregion - int a; - if (true) - a++; - #endregion - } -}"; - var expectedContent = @"using System; -using System.Collections.Generic; -using System.Linq; - -class Program -{ - static void Main(string[] args) - { - #region Myregion - int a; - if (true) - a++; - #endregion - } -}"; - await AssertFormatAsync(expectedContent, content); - } + public Task EmbededStatement1() + => AssertFormatAsync(""" + using System; + using System.Collections.Generic; + using System.Linq; + + class Program + { + static void Main(string[] args) + { + #region Myregion + int a; + if (true) + a++; + #endregion + } + } + """, """ + using System; + using System.Collections.Generic; + using System.Linq; + + class Program + { + static void Main(string[] args) + { + #region Myregion + int a; + if (true) + a++; + #endregion + } + } + """); [Fact] - public async Task RefKeywords() - { - var content = @"class C -{ - static void Main(string[] args) - { - int i = 1; - TypedReference tr = __makeref( i ); - Type t = __reftype( tr - ); - int j = __refvalue( tr , - int - ); - } -}"; - - var expected = @"class C -{ - static void Main(string[] args) - { - int i = 1; - TypedReference tr = __makeref(i); - Type t = __reftype(tr - ); - int j = __refvalue(tr, - int - ); - } -}"; - - await AssertFormatAsync(expected, content); - } + public Task RefKeywords() + => AssertFormatAsync(""" + class C + { + static void Main(string[] args) + { + int i = 1; + TypedReference tr = __makeref(i); + Type t = __reftype(tr + ); + int j = __refvalue(tr, + int + ); + } + } + """, """ + class C + { + static void Main(string[] args) + { + int i = 1; + TypedReference tr = __makeref( i ); + Type t = __reftype( tr + ); + int j = __refvalue( tr , + int + ); + } + } + """); [Fact] public void NewLineOptions_LineFeedOnly() @@ -1752,34 +1586,24 @@ public void NewLineOptions_LineFeedOnly() var formatted = Formatter.Format(tree, workspace.Services.SolutionServices, options, CancellationToken.None); var actual = formatted.ToFullString(); - var expected = "class C\n{\n}"; - - Assert.Equal(expected, actual); + Assert.Equal("class C\n{\n}", actual); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/4019")] public void FormatWithTabs() { - var code = @"#region Assembly mscorlib -// C:\ -#endregion - -using System.Collections; - -class F -{ - string s; -}"; - var expected = @"#region Assembly mscorlib -// C:\ -#endregion + var code = """ + #region Assembly mscorlib + // C:\ + #endregion -using System.Collections; + using System.Collections; -class F -{ - string s; -}"; + class F + { + string s; + } + """; var tree = SyntaxFactory.ParseCompilationUnit(code); var newLine = Environment.NewLine; @@ -1798,30 +1622,41 @@ class F var formatted = Formatter.Format(tree, workspace.Services.SolutionServices, options, CancellationToken.None); var actual = formatted.ToFullString(); - Assert.Equal(expected, actual); + Assert.Equal(""" + #region Assembly mscorlib + // C:\ + #endregion + + using System.Collections; + + class F + { + string s; + } + """, actual); } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39351")] - public async Task SingleLineComment_AtEndOfFile_DoesNotAddNewLine() - { - await AssertNoFormattingChangesAsync(@"class Program { } + public Task SingleLineComment_AtEndOfFile_DoesNotAddNewLine() + => AssertNoFormattingChangesAsync(""" + class Program { } -// Test"); - } + // Test + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39351")] - public async Task MultiLineComment_AtEndOfFile_DoesNotAddNewLine() - { - await AssertNoFormattingChangesAsync(@"class Program { } + public Task MultiLineComment_AtEndOfFile_DoesNotAddNewLine() + => AssertNoFormattingChangesAsync(""" + class Program { } -/* Test */"); - } + /* Test */ + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39351")] - public async Task DocComment_AtEndOfFile_DoesNotAddNewLine() - { - await AssertNoFormattingChangesAsync(@"class Program { } + public Task DocComment_AtEndOfFile_DoesNotAddNewLine() + => AssertNoFormattingChangesAsync(""" + class Program { } -/// Test"); - } + /// Test + """); } diff --git a/src/Workspaces/CSharpTest/OrganizeImports/OrganizeUsingsTests.cs b/src/Workspaces/CSharpTest/OrganizeImports/OrganizeUsingsTests.cs index 77bbcba1784b8..81b2d98388acb 100644 --- a/src/Workspaces/CSharpTest/OrganizeImports/OrganizeUsingsTests.cs +++ b/src/Workspaces/CSharpTest/OrganizeImports/OrganizeUsingsTests.cs @@ -55,27 +55,19 @@ public async Task SingleUsingStatement() } [Fact] - public async Task AliasesAtBottom() - { - var initial = - """ + public Task AliasesAtBottom() + => CheckAsync(""" using A = B; using C; using D = E; using F; - """; - - var final = - """ + """, """ using C; using F; using A = B; using D = E; - """; - - await CheckAsync(initial, final); - } + """); [Theory, WorkItem("https://github.com/dotnet/roslyn/issues/44136")] [InlineData("\n")] @@ -83,9 +75,6 @@ public async Task AliasesAtBottom() public async Task PreserveExistingEndOfLine(string fallbackEndOfLine) { var initial = "using A = B;\nusing C;\nusing D = E;\nusing F;\n"; - - var final = "using C;\nusing F;\nusing A = B;\nusing D = E;\n"; - using var workspace = new AdhocWorkspace(); var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp); var document = project.AddDocument("Document", initial); @@ -100,14 +89,12 @@ public async Task PreserveExistingEndOfLine(string fallbackEndOfLine) var organizeImportsService = document.GetRequiredLanguageService(); var newDocument = await organizeImportsService.OrganizeImportsAsync(document, options, CancellationToken.None); var newRoot = await newDocument.GetRequiredSyntaxRootAsync(default); - Assert.Equal(final, newRoot.ToFullString()); + Assert.Equal("using C;\nusing F;\nusing A = B;\nusing D = E;\n", newRoot.ToFullString()); } [Fact] - public async Task UsingStaticsBetweenUsingsAndAliases() - { - var initial = - """ + public Task UsingStaticsBetweenUsingsAndAliases() + => CheckAsync(""" using static System.Convert; using A = B; using C; @@ -115,10 +102,7 @@ public async Task UsingStaticsBetweenUsingsAndAliases() using D = E; using static System.Console; using F; - """; - - var final = - """ + """, """ using C; using F; using Z; @@ -127,16 +111,11 @@ public async Task UsingStaticsBetweenUsingsAndAliases() using A = B; using D = E; - """; - - await CheckAsync(initial, final); - } + """); [Fact] - public async Task NestedStatements() - { - var initial = - """ + public Task NestedStatements() + => CheckAsync(""" using B; using A; @@ -175,10 +154,7 @@ namespace N5 using M; } } - """; - - var final = - """ + """, """ using A; using B; @@ -217,15 +193,11 @@ namespace N5 using N; } } - """; - await CheckAsync(initial, final); - } + """); [Fact] - public async Task FileScopedNamespace() - { - var initial = - """ + public Task FileScopedNamespace() + => CheckAsync(""" using B; using A; @@ -234,10 +206,7 @@ namespace N; using D; using C; - """; - - var final = - """ + """, """ using A; using B; @@ -246,47 +215,33 @@ namespace N; using C; using D; - """; - await CheckAsync(initial, final); - } + """); [Fact] - public async Task SpecialCaseSystem() - { - var initial = - """ + public Task SpecialCaseSystem() + => CheckAsync(""" using M2; using M1; using System.Linq; using System; - """; - - var final = - """ + """, """ using System; using System.Linq; using M1; using M2; - """; - await CheckAsync(initial, final, placeSystemNamespaceFirst: true); - } + """, placeSystemNamespaceFirst: true); [Fact] - public async Task SpecialCaseSystemWithUsingStatic() - { - var initial = - """ + public Task SpecialCaseSystemWithUsingStatic() + => CheckAsync(""" using M2; using M1; using System.Linq; using System; using static Microsoft.Win32.Registry; using static System.BitConverter; - """; - - var final = - """ + """, """ using System; using System.Linq; using M1; @@ -294,63 +249,44 @@ public async Task SpecialCaseSystemWithUsingStatic() using static System.BitConverter; using static Microsoft.Win32.Registry; - """; - await CheckAsync(initial, final, placeSystemNamespaceFirst: true); - } + """, placeSystemNamespaceFirst: true); [Fact] - public async Task DoNotSpecialCaseSystem() - { - var initial = - """ + public Task DoNotSpecialCaseSystem() + => CheckAsync(""" using M2; using M1; using System.Linq; using System; - """; - - var final = - """ + """, """ using M1; using M2; using System; using System.Linq; - """; - - await CheckAsync(initial, final); - } + """); [Fact] - public async Task DoNotSpecialCaseSystemWithUsingStatics() - { - var initial = - """ + public Task DoNotSpecialCaseSystemWithUsingStatics() + => CheckAsync(""" using M2; using M1; using System.Linq; using System; using static Microsoft.Win32.Registry; using static System.BitConverter; - """; - - var final = - """ + """, """ using M1; using M2; using System; using System.Linq; using static Microsoft.Win32.Registry; using static System.BitConverter; - """; - await CheckAsync(initial, final); - } + """); [Fact] - public async Task IndentationAfterSorting() - { - var initial = - """ + public Task IndentationAfterSorting() + => CheckAsync(""" namespace A { using V.W; @@ -363,10 +299,7 @@ class B { } namespace U { } namespace V.W { } namespace X.Y.Z { } - """; - - var final = - """ + """, """ namespace A { using U; @@ -379,16 +312,11 @@ class B { } namespace U { } namespace V.W { } namespace X.Y.Z { } - """; - - await CheckAsync(initial, final); - } + """); [Fact] - public async Task DoNotTouchCommentsAtBeginningOfFile1() - { - var initial = - """ + public Task DoNotTouchCommentsAtBeginningOfFile1() + => CheckAsync(""" // Copyright (c) Microsoft Corporation. All rights reserved. using B; @@ -397,10 +325,7 @@ public async Task DoNotTouchCommentsAtBeginningOfFile1() namespace A { } namespace B { } - """; - - var final = - """ + """, """ // Copyright (c) Microsoft Corporation. All rights reserved. // I like namespace A @@ -409,16 +334,11 @@ namespace B { } namespace A { } namespace B { } - """; - - await CheckAsync(initial, final); - } + """); [Fact] - public async Task DoNotTouchCommentsAtBeginningOfFile2() - { - var initial = - """ + public Task DoNotTouchCommentsAtBeginningOfFile2() + => CheckAsync(""" /* Copyright (c) Microsoft Corporation. All rights reserved. */ using B; @@ -427,10 +347,7 @@ public async Task DoNotTouchCommentsAtBeginningOfFile2() namespace A { } namespace B { } - """; - - var final = - """ + """, """ /* Copyright (c) Microsoft Corporation. All rights reserved. */ /* I like namespace A */ @@ -439,16 +356,11 @@ namespace B { } namespace A { } namespace B { } - """; - - await CheckAsync(initial, final); - } + """); [Fact] - public async Task DoNotTouchCommentsAtBeginningOfFile3() - { - var initial = - """ + public Task DoNotTouchCommentsAtBeginningOfFile3() + => CheckAsync(""" // Copyright (c) Microsoft Corporation. All rights reserved. using B; @@ -457,10 +369,7 @@ public async Task DoNotTouchCommentsAtBeginningOfFile3() namespace A { } namespace B { } - """; - - var final = - """ + """, """ // Copyright (c) Microsoft Corporation. All rights reserved. /// I like namespace A @@ -469,16 +378,11 @@ namespace B { } namespace A { } namespace B { } - """; - - await CheckAsync(initial, final); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33251")] - public async Task DoNotTouchCommentsAtBeginningOfFile4() - { - var initial = - """ + public Task DoNotTouchCommentsAtBeginningOfFile4() + => CheckAsync(""" /// Copyright (c) Microsoft Corporation. All rights reserved. using B; @@ -487,10 +391,7 @@ public async Task DoNotTouchCommentsAtBeginningOfFile4() namespace A { } namespace B { } - """; - - var final = - """ + """, """ /// Copyright (c) Microsoft Corporation. All rights reserved. /// I like namespace A @@ -499,16 +400,11 @@ namespace B { } namespace A { } namespace B { } - """; - - await CheckAsync(initial, final); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33251")] - public async Task DoNotTouchCommentsAtBeginningOfFile5() - { - var initial = - """ + public Task DoNotTouchCommentsAtBeginningOfFile5() + => CheckAsync(""" /** Copyright (c) Microsoft Corporation. All rights reserved. */ @@ -518,10 +414,7 @@ public async Task DoNotTouchCommentsAtBeginningOfFile5() namespace A { } namespace B { } - """; - - var final = - """ + """, """ /** Copyright (c) Microsoft Corporation. All rights reserved. */ @@ -531,16 +424,11 @@ namespace B { } namespace A { } namespace B { } - """; - - await CheckAsync(initial, final); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2480")] - public async Task DoTouchCommentsAtBeginningOfFile1() - { - var initial = - """ + public Task DoTouchCommentsAtBeginningOfFile1() + => CheckAsync(""" // Copyright (c) Microsoft Corporation. All rights reserved. using B; // I like namespace A @@ -548,10 +436,7 @@ public async Task DoTouchCommentsAtBeginningOfFile1() namespace A { } namespace B { } - """; - - var final = - """ + """, """ // Copyright (c) Microsoft Corporation. All rights reserved. // I like namespace A using A; @@ -559,16 +444,11 @@ namespace B { } namespace A { } namespace B { } - """; - - await CheckAsync(initial, final); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2480")] - public async Task DoTouchCommentsAtBeginningOfFile2() - { - var initial = - """ + public Task DoTouchCommentsAtBeginningOfFile2() + => CheckAsync(""" /* Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /* I like namespace A */ @@ -576,10 +456,7 @@ public async Task DoTouchCommentsAtBeginningOfFile2() namespace A { } namespace B { } - """; - - var final = - """ + """, """ /* Copyright (c) Microsoft Corporation. All rights reserved. */ /* I like namespace A */ using A; @@ -587,16 +464,11 @@ namespace B { } namespace A { } namespace B { } - """; - - await CheckAsync(initial, final); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2480")] - public async Task DoTouchCommentsAtBeginningOfFile3() - { - var initial = - """ + public Task DoTouchCommentsAtBeginningOfFile3() + => CheckAsync(""" /// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A @@ -604,10 +476,7 @@ public async Task DoTouchCommentsAtBeginningOfFile3() namespace A { } namespace B { } - """; - - var final = - """ + """, """ /// I like namespace A using A; /// Copyright (c) Microsoft Corporation. All rights reserved. @@ -615,16 +484,11 @@ namespace B { } namespace A { } namespace B { } - """; - - await CheckAsync(initial, final); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2480")] - public async Task CommentsNotAtTheStartOfTheFile1() - { - var initial = - """ + public Task CommentsNotAtTheStartOfTheFile1() + => CheckAsync(""" namespace N { // attached to System.Text @@ -632,10 +496,7 @@ namespace N // attached to System using System; } - """; - - var final = - """ + """, """ namespace N { // attached to System @@ -643,16 +504,11 @@ namespace N // attached to System.Text using System.Text; } - """; - - await CheckAsync(initial, final); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/2480")] - public async Task CommentsNotAtTheStartOfTheFile2() - { - var initial = - """ + public Task CommentsNotAtTheStartOfTheFile2() + => CheckAsync(""" namespace N { // not attached to System.Text @@ -661,10 +517,7 @@ namespace N // attached to System using System; } - """; - - var final = - """ + """, """ namespace N { // not attached to System.Text @@ -673,10 +526,7 @@ namespace N using System; using System.Text; } - """; - - await CheckAsync(initial, final); - } + """); [Fact] public async Task DoNotSortIfEndIfBlocks() @@ -702,10 +552,8 @@ namespace D { } } [Fact] - public async Task ExternAliases() - { - var initial = - """ + public Task ExternAliases() + => CheckAsync(""" extern alias Z; extern alias Y; extern alias X; @@ -741,10 +589,7 @@ namespace L struct T { } } } - """; - - var final = - """ + """, """ extern alias X; extern alias Y; extern alias Z; @@ -780,10 +625,7 @@ namespace L struct T { } } } - """; - - await CheckAsync(initial, final); - } + """); [Fact] public async Task DuplicateUsings() @@ -800,50 +642,32 @@ public async Task DuplicateUsings() } [Fact] - public async Task InlineComments() - { - var initial = - """ + public Task InlineComments() + => CheckAsync(""" /*00*/using/*01*/D/*02*/;/*03*/ /*04*/using/*05*/C/*06*/;/*07*/ /*08*/using/*09*/A/*10*/;/*11*/ /*12*/using/*13*/B/*14*/;/*15*/ /*16*/ - """; - - var final = - """ + """, """ /*08*/using/*09*/A/*10*/;/*11*/ /*12*/using/*13*/B/*14*/;/*15*/ /*04*/using/*05*/C/*06*/;/*07*/ /*00*/using/*01*/D/*02*/;/*03*/ /*16*/ - """; - - await CheckAsync(initial, final); - } + """); [Fact] - public async Task AllOnOneLine() - { - var initial = -@"using C; using B; using A;"; - - var final = - """ + public Task AllOnOneLine() + => CheckAsync(@"using C; using B; using A;", """ using A; using B; using C; - """; - - await CheckAsync(initial, final); - } + """); [Fact] - public async Task InsideRegionBlock() - { - var initial = - """ + public Task InsideRegionBlock() + => CheckAsync(""" #region Using directives using C; using A; @@ -853,9 +677,7 @@ public async Task InsideRegionBlock() class Class1 { } - """; - var final = - """ + """, """ #region Using directives using A; using B; @@ -865,10 +687,7 @@ class Class1 class Class1 { } - """; - - await CheckAsync(initial, final); - } + """); [Fact] public async Task NestedRegionBlock() @@ -907,10 +726,8 @@ public async Task MultipleRegionBlocks() } [Fact] - public async Task InterleavedNewlines() - { - var initial = - """ + public Task InterleavedNewlines() + => CheckAsync(""" using B; using A; @@ -918,43 +735,29 @@ public async Task InterleavedNewlines() using C; class D { } - """; - - var final = - """ + """, """ using A; using B; using C; class D { } - """; - - await CheckAsync(initial, final); - } + """); [Fact] - public async Task InsideIfEndIfBlock() - { - var initial = - """ + public Task InsideIfEndIfBlock() + => CheckAsync(""" #if !X using B; using A; using C; #endif - """; - - var final = - """ + """, """ #if !X using A; using B; using C; #endif - """; - - await CheckAsync(initial, final); - } + """); [Fact] public async Task IfEndIfBlockAbove() @@ -1017,10 +820,8 @@ public async Task IfEndIfBlockBelow() } [Fact] - public async Task Korean() - { - var initial = - """ + public Task Korean() + => CheckAsync(""" using 하; using 파; using 타; @@ -1035,10 +836,7 @@ public async Task Korean() using 다; using 나; using 가; - """; - - var final = - """ + """, """ using 가; using 나; using 다; @@ -1054,16 +852,11 @@ public async Task Korean() using 파; using 하; - """; - - await CheckAsync(initial, final); - } + """); [Fact] - public async Task DoNotSpecialCaseSystem1() - { - var initial = - """ + public Task DoNotSpecialCaseSystem1() + => CheckAsync(""" using B; using System.Collections.Generic; using C; @@ -1073,10 +866,7 @@ public async Task DoNotSpecialCaseSystem1() using System; using System.Collections; using A; - """; - - var final = - """ + """, """ using _System; using A; using B; @@ -1087,16 +877,11 @@ public async Task DoNotSpecialCaseSystem1() using System.Collections.Generic; using SystemZ; - """; - - await CheckAsync(initial, final, placeSystemNamespaceFirst: false); - } + """, placeSystemNamespaceFirst: false); [Fact] - public async Task DoNotSpecialCaseSystem2() - { - var initial = - """ + public Task DoNotSpecialCaseSystem2() + => CheckAsync(""" extern alias S; extern alias R; extern alias T; @@ -1113,10 +898,7 @@ public async Task DoNotSpecialCaseSystem2() using M = System.Collections; using System.Collections; using A; - """; - - var final = - """ + """, """ extern alias R; extern alias S; extern alias T; @@ -1134,16 +916,50 @@ public async Task DoNotSpecialCaseSystem2() using Y = System.UInt32; using Z = System.Int32; - """; - - await CheckAsync(initial, final, placeSystemNamespaceFirst: false); - } + """, placeSystemNamespaceFirst: false); [Fact] public async Task CaseSensitivity1() { - var initial = - """ + string sortedKana; + if (GlobalizationUtilities.ICUMode()) + { + sortedKana = + """ + using あ; + using ア; + using ああ; + using あア; + using アあ; + using アア; + using あア; + using アア; + using ア; + using アあ; + using アア; + using アア; + """; + } + else + { + sortedKana = + """ + using ア; + using ア; + using あ; + using アア; + using アア; + using アア; + using アア; + using アあ; + using アあ; + using あア; + using あア; + using ああ; + """; + } + + await CheckAsync(""" using Bb; using B; using bB; @@ -1183,48 +999,7 @@ public async Task CaseSensitivity1() using cc; using cC; using CC; - """; - - string sortedKana; - if (GlobalizationUtilities.ICUMode()) - { - sortedKana = - """ - using あ; - using ア; - using ああ; - using あア; - using アあ; - using アア; - using あア; - using アア; - using ア; - using アあ; - using アア; - using アア; - """; - } - else - { - sortedKana = - """ - using ア; - using ア; - using あ; - using アア; - using アア; - using アア; - using アア; - using アあ; - using アあ; - using あア; - using あア; - using ああ; - """; - } - - var final = - $""" + """, $""" using a; using A; using aa; @@ -1254,8 +1029,7 @@ public async Task CaseSensitivity1() using CC; {sortedKana} - """; - await CheckAsync(initial, final); + """); } [Fact] @@ -1318,10 +1092,8 @@ await CheckAsync(initial, } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20988")] - public async Task TestGrouping() - { - var initial = - """ + public Task TestGrouping() + => CheckAsync(""" // Banner using Microsoft.CodeAnalysis.CSharp.Extensions; @@ -1333,10 +1105,7 @@ public async Task TestGrouping() using Roslyn.Utilities; using IntList = System.Collections.Generic.List; using static System.Console; - """; - - var final = - """ + """, """ // Banner using System.Collections.Generic; @@ -1352,17 +1121,11 @@ public async Task TestGrouping() using IntList = System.Collections.Generic.List; - """; - - await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: true); - } + """, placeSystemNamespaceFirst: true, separateImportGroups: true); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/20988")] - public async Task TestGrouping2() - { - // Make sure we don't insert extra newlines if they're already there. - var initial = - """ + public Task TestGrouping2() + => CheckAsync(""" // Banner using System.Collections.Generic; @@ -1378,10 +1141,7 @@ public async Task TestGrouping2() using IntList = System.Collections.Generic.List; - """; - - var final = - """ + """, """ // Banner using System.Collections.Generic; @@ -1397,18 +1157,13 @@ public async Task TestGrouping2() using IntList = System.Collections.Generic.List; - """; - - await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: true); - } + """, placeSystemNamespaceFirst: true, separateImportGroups: true); [Theory, WorkItem(20988, "https://github.com/dotnet/roslyn/issues/19306")] [InlineData("\n")] [InlineData("\r\n")] - public async Task TestGrouping3(string endOfLine) - { - var initial = - """ + public Task TestGrouping3(string endOfLine) + => CheckAsync(""" // Banner using Microsoft.CodeAnalysis.CSharp.Extensions; @@ -1420,10 +1175,7 @@ public async Task TestGrouping3(string endOfLine) using Roslyn.Utilities; using IntList = System.Collections.Generic.List; using static System.Console; - """; - - var final = - """ + """, """ // Banner using System.Collections.Generic; @@ -1439,24 +1191,18 @@ public async Task TestGrouping3(string endOfLine) using IntList = System.Collections.Generic.List; - """; - - await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: true, endOfLine: endOfLine); - } + """, placeSystemNamespaceFirst: true, separateImportGroups: true, endOfLine: endOfLine); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71502")] - public async Task GlobalsBeforeNonGlobals() - { - var initial = """ + public Task GlobalsBeforeNonGlobals() + => CheckAsync(""" using A = B; using static C; using X; global using A = B; global using static C; global using X; - """; - - var final = """ + """, """ global using X; global using static C; global using A = B; @@ -1464,42 +1210,27 @@ public async Task GlobalsBeforeNonGlobals() using static C; using A = B; - """; - - await CheckAsync(initial, final); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71502")] - public async Task GlobalNonNamedAliases1() - { - var initial = """ + public Task GlobalNonNamedAliases1() + => CheckAsync(""" global using B = (int, string); global using A = int; - """; - - var final = """ + """, """ global using A = int; global using B = (int, string); - """; - - await CheckAsync(initial, final); - } + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71502")] - public async Task GlobalNonNamedAliases2() - { - var initial = """ + public Task GlobalNonNamedAliases2() + => CheckAsync(""" global using unsafe DataLogWriteFunc = delegate* unmanaged[Cdecl]; global using unsafe DataLogHandle = void*; - """; - - var final = """ + """, """ global using unsafe DataLogHandle = void*; global using unsafe DataLogWriteFunc = delegate* unmanaged[Cdecl]; - """; - - await CheckAsync(initial, final); - } + """); } diff --git a/src/Workspaces/Core/Portable/CodeActions/CodeAction.cs b/src/Workspaces/Core/Portable/CodeActions/CodeAction.cs index dbd9f775ca9d0..d0bed3f4f5309 100644 --- a/src/Workspaces/Core/Portable/CodeActions/CodeAction.cs +++ b/src/Workspaces/Core/Portable/CodeActions/CodeAction.cs @@ -8,11 +8,13 @@ using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeCleanup; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeRefactorings; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; @@ -79,6 +81,8 @@ public abstract partial class CodeAction /// public virtual string? EquivalenceKey => null; + internal virtual CodeActionCleanup Cleanup => CodeActionCleanup.Default; + /// /// Priority of this particular action within a group of other actions. Less relevant actions should override /// this and specify a lower priority so that more important actions are easily accessible to the user. Returns @@ -396,15 +400,13 @@ protected virtual Task GetChangedDocumentAsync(IProgress internal async Task GetChangedSolutionInternalAsync( - Solution originalSolution, IProgress progress, bool postProcessChanges = true, CancellationToken cancellationToken = default) + Solution originalSolution, IProgress progress, CancellationToken cancellationToken) { var solution = await GetChangedSolutionAsync(progress, cancellationToken).ConfigureAwait(false); - if (solution == null || !postProcessChanges) - { + if (solution == null) return solution; - } - return await PostProcessChangesAsync(originalSolution, solution, cancellationToken).ConfigureAwait(false); + return await PostProcessChangesAsync(originalSolution, solution, progress, this.Cleanup, cancellationToken).ConfigureAwait(false); } internal Task GetChangedDocumentInternalAsync(CancellationToken cancellation) @@ -421,7 +423,7 @@ protected Task> PostProcessAsync(IEnumerable #pragma warning restore CA1822 // Mark members as static => PostProcessAsync(originalSolution: null, operations, cancellationToken); - internal static async Task> PostProcessAsync( + internal async Task> PostProcessAsync( Solution? originalSolution, IEnumerable operations, CancellationToken cancellationToken) { using var result = TemporaryArray.Empty; @@ -430,7 +432,8 @@ internal static async Task> PostProcessAsync { if (op is ApplyChangesOperation ac) { - result.Add(new ApplyChangesOperation(await PostProcessChangesAsync(originalSolution, ac.ChangedSolution, cancellationToken).ConfigureAwait(false))); + result.Add(new ApplyChangesOperation(await PostProcessChangesAsync( + originalSolution, ac.ChangedSolution, CodeAnalysisProgress.None, this.Cleanup, cancellationToken).ConfigureAwait(false))); } else { @@ -449,21 +452,7 @@ internal static async Task> PostProcessAsync #pragma warning disable CA1822 // Mark members as static. This is a public API. protected Task PostProcessChangesAsync(Solution changedSolution, CancellationToken cancellationToken) #pragma warning restore CA1822 // Mark members as static - => PostProcessChangesAsync(originalSolution: null, changedSolution, cancellationToken); - - private static async Task PostProcessChangesAsync( - Solution? originalSolution, - Solution changedSolution, - CancellationToken cancellationToken) - { - // originalSolution is only null on backward compatible codepaths. In that case, we get the workspace's - // current solution. This is not ideal (as that is a mutable field that could be changing out from - // underneath us). But it's the only option we have for the compat case with existing public extension - // points. - originalSolution ??= changedSolution.Workspace.CurrentSolution; - - return await CleanSyntaxAndSemanticsAsync(originalSolution, changedSolution, CodeAnalysisProgress.None, cancellationToken).ConfigureAwait(false); - } + => PostProcessChangesAsync(originalSolution: null, changedSolution, progress: CodeAnalysisProgress.None, this.Cleanup, cancellationToken); /// /// Apply post processing steps to a single document: @@ -545,6 +534,10 @@ public static CodeAction Create(string title, Func [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "This is source compatible")] public static CodeAction Create(string title, Func, CancellationToken, Task> createChangedSolution, string? equivalenceKey = null, CodeActionPriority priority = CodeActionPriority.Default) + => Create(title, createChangedSolution, equivalenceKey, priority, CodeActionCleanup.Default); + + internal static CodeAction Create( + string title, Func, CancellationToken, Task> createChangedSolution, string? equivalenceKey, CodeActionPriority priority, CodeActionCleanup cleanup) { if (title == null) throw new ArgumentNullException(nameof(title)); @@ -552,7 +545,7 @@ public static CodeAction Create(string title, Func @@ -705,23 +698,28 @@ internal class SolutionChangeAction : SimpleCodeAction { private readonly Func, CancellationToken, Task> _createChangedSolution; + internal override CodeActionCleanup Cleanup { get; } + protected SolutionChangeAction( string title, Func, CancellationToken, Task> createChangedSolution, string? equivalenceKey, CodeActionPriority priority, + CodeActionCleanup cleanup, bool createdFromFactoryMethod) : base(title, equivalenceKey, priority, createdFromFactoryMethod) { _createChangedSolution = createChangedSolution; + this.Cleanup = cleanup; } protected SolutionChangeAction( string title, Func, CancellationToken, Task> createChangedSolution, string? equivalenceKey, - CodeActionPriority priority = CodeActionPriority.Default) - : this(title, createChangedSolution, equivalenceKey, priority, createdFromFactoryMethod: false) + CodeActionPriority priority, + CodeActionCleanup cleanup) + : this(title, createChangedSolution, equivalenceKey, priority, cleanup, createdFromFactoryMethod: false) { } @@ -729,8 +727,9 @@ public static SolutionChangeAction New( string title, Func, CancellationToken, Task> createChangedSolution, string? equivalenceKey, - CodeActionPriority priority = CodeActionPriority.Default) - => new(title, createChangedSolution, equivalenceKey, priority, createdFromFactoryMethod: true); + CodeActionPriority priority, + CodeActionCleanup cleanup) + => new(title, createChangedSolution, equivalenceKey, priority, cleanup, createdFromFactoryMethod: true); protected sealed override Task GetChangedSolutionAsync(IProgress progress, CancellationToken cancellationToken) => _createChangedSolution(progress, cancellationToken).AsNullable(); diff --git a/src/Workspaces/Core/Portable/CodeActions/CodeAction_Cleanup.cs b/src/Workspaces/Core/Portable/CodeActions/CodeAction_Cleanup.cs index 8eff1e04efb3b..b43a77428d3ad 100644 --- a/src/Workspaces/Core/Portable/CodeActions/CodeAction_Cleanup.cs +++ b/src/Workspaces/Core/Portable/CodeActions/CodeAction_Cleanup.cs @@ -20,18 +20,43 @@ namespace Microsoft.CodeAnalysis.CodeActions; +internal enum CodeActionCleanup +{ + /// + /// No automatic cleanup will be performed on the solution after the code action is applied. + /// + None, + + /// + /// Automatic syntax cleanup will be performed on the solution after the code action is applied. + /// + SyntaxOnly, + + /// + /// Automatic syntax and semantics cleanup will be performed on the solution after the code action is applied. + /// + SyntaxAndSemantics, + + Default = SyntaxAndSemantics, +} + public abstract partial class CodeAction { + private static readonly Func> s_cleanupSyntaxPass = + static (document, options, cancellationToken) => CleanupSyntaxAsync(document, options, cancellationToken); + + private static readonly ImmutableArray>> s_cleanupSyntaxPasses = [s_cleanupSyntaxPass]; + /// /// We do cleanup in N serialized passes. This allows us to process all documents in parallel, while only forking /// the solution N times *total* (instead of N times *per* document). /// - private static readonly ImmutableArray>> s_cleanupPasses = + private static readonly ImmutableArray>> s_allCleanupPasses = [ // First, ensure that everything is formatted as the feature asked for. We want to do this prior to doing // semantic cleanup as the semantic cleanup passes may end up making changes that end up dropping some of // the formatting/elastic annotations that the feature wanted respected. - static (document, options, cancellationToken) => CleanupSyntaxAsync(document, options, cancellationToken), + s_cleanupSyntaxPass, // Then add all missing imports to all changed documents. static (document, options, cancellationToken) => ImportAdder.AddImportsFromSymbolAnnotationAsync(document, Simplifier.AddImportsAnnotation, options.AddImportOptions, cancellationToken), // Then simplify any expanded constructs. @@ -41,7 +66,7 @@ public abstract partial class CodeAction // Finally, after doing the semantic cleanup, do another syntax cleanup pass to ensure that the tree is in a // good state. The semantic cleanup passes may have introduced new nodes with elastic trivia that have to be // cleaned. - static (document, options, cancellationToken) => CleanupSyntaxAsync(document, options, cancellationToken), + s_cleanupSyntaxPass, ]; internal static async Task CleanupSyntaxAsync(Document document, CodeCleanupOptions options, CancellationToken cancellationToken) @@ -67,21 +92,44 @@ internal static ImmutableArray GetAllChangedOrAddedDocumentIds( .Concat(solutionChanges.GetAddedProjects().SelectMany(p => p.DocumentIds)) .Concat(solutionChanges.GetExplicitlyChangedSourceGeneratedDocuments()); - return documentIds.ToImmutableArray(); + return [.. documentIds]; + } + + internal static async Task PostProcessChangesAsync( + Solution? originalSolution, + Solution changedSolution, + IProgress progress, + CodeActionCleanup cleanup, + CancellationToken cancellationToken) + { + if (cleanup is CodeActionCleanup.None) + return changedSolution; + + // originalSolution is only null on backward compatible codepaths. In that case, we get the workspace's + // current solution. This is not ideal (as that is a mutable field that could be changing out from + // underneath us). But it's the only option we have for the compat case with existing public extension + // points. + originalSolution ??= changedSolution.Workspace.CurrentSolution; + + return await CleanSyntaxAndSemanticsAsync( + originalSolution, changedSolution, progress, + cleanup is CodeActionCleanup.SyntaxOnly ? s_cleanupSyntaxPasses : s_allCleanupPasses, + cancellationToken).ConfigureAwait(false); } - internal static async Task CleanSyntaxAndSemanticsAsync( + private static async Task CleanSyntaxAndSemanticsAsync( Solution originalSolution, Solution changedSolution, IProgress progress, + ImmutableArray>> passes, CancellationToken cancellationToken) { var documentIds = GetAllChangedOrAddedDocumentIds(originalSolution, changedSolution); var documentIdsAndOptionsToClean = await GetDocumentIdsAndOptionsToCleanAsync().ConfigureAwait(false); // Then do a pass where we cleanup semantics. - var cleanedSolution = await RunAllCleanupPassesInOrderAsync( - changedSolution, documentIdsAndOptionsToClean, progress, cancellationToken).ConfigureAwait(false); + var cleanedSolution = await RunCleanupPassesInOrderAsync( + changedSolution, documentIdsAndOptionsToClean, progress, passes, cancellationToken).ConfigureAwait(false); return cleanedSolution; @@ -112,26 +160,28 @@ internal static async ValueTask CleanupDocumentAsync(Document document if (!document.SupportsSyntaxTree) return document; - var cleanedSolution = await RunAllCleanupPassesInOrderAsync( + var cleanedSolution = await RunCleanupPassesInOrderAsync( document.Project.Solution, [(document.Id, options)], CodeAnalysisProgress.None, + s_allCleanupPasses, cancellationToken).ConfigureAwait(false); return await cleanedSolution.GetRequiredDocumentAsync(document.Id, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); } - private static async Task RunAllCleanupPassesInOrderAsync( + private static async Task RunCleanupPassesInOrderAsync( Solution solution, ImmutableArray<(DocumentId documentId, CodeCleanupOptions options)> documentIdsAndOptions, IProgress progress, + ImmutableArray>> passes, CancellationToken cancellationToken) { // One item per document per cleanup pass. - progress.AddItems(documentIdsAndOptions.Length * s_cleanupPasses.Length); + progress.AddItems(documentIdsAndOptions.Length * passes.Length); var currentSolution = solution; - foreach (var cleanupPass in s_cleanupPasses) + foreach (var cleanupPass in passes) currentSolution = await RunParallelCleanupPassAsync(currentSolution, cleanupPass).ConfigureAwait(false); return currentSolution; diff --git a/src/Workspaces/Core/Portable/CodeCleanup/AbstractCodeCleanerService.cs b/src/Workspaces/Core/Portable/CodeCleanup/AbstractCodeCleanerService.cs index 0282c380e2a79..c80f6de284e67 100644 --- a/src/Workspaces/Core/Portable/CodeCleanup/AbstractCodeCleanerService.cs +++ b/src/Workspaces/Core/Portable/CodeCleanup/AbstractCodeCleanerService.cs @@ -9,15 +9,15 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeCleanup.Providers; -using Microsoft.CodeAnalysis.Internal.Log; +using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; +using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; -using Microsoft.CodeAnalysis.Formatting; namespace Microsoft.CodeAnalysis.CodeCleanup; diff --git a/src/Workspaces/Core/Portable/CodeCleanup/CodeCleaner.cs b/src/Workspaces/Core/Portable/CodeCleanup/CodeCleaner.cs index e1bb98484c3b0..df6dd11541222 100644 --- a/src/Workspaces/Core/Portable/CodeCleanup/CodeCleaner.cs +++ b/src/Workspaces/Core/Portable/CodeCleanup/CodeCleaner.cs @@ -8,10 +8,10 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeCleanup.Providers; -using Microsoft.CodeAnalysis.Shared.Extensions; +using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; +using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; -using Microsoft.CodeAnalysis.Formatting; namespace Microsoft.CodeAnalysis.CodeCleanup; diff --git a/src/Workspaces/Core/Portable/CodeCleanup/Providers/SimplificationCodeCleanupProvider.cs b/src/Workspaces/Core/Portable/CodeCleanup/Providers/SimplificationCodeCleanupProvider.cs index fc30204eb8faf..ea4943c2ef085 100644 --- a/src/Workspaces/Core/Portable/CodeCleanup/Providers/SimplificationCodeCleanupProvider.cs +++ b/src/Workspaces/Core/Portable/CodeCleanup/Providers/SimplificationCodeCleanupProvider.cs @@ -5,8 +5,8 @@ using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Formatting; +using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; diff --git a/src/Workspaces/Core/Portable/CodeFixes/ExportCodeFixProviderAttribute.cs b/src/Workspaces/Core/Portable/CodeFixes/ExportCodeFixProviderAttribute.cs index 4e39cb7f72ae8..378387d50c716 100644 --- a/src/Workspaces/Core/Portable/CodeFixes/ExportCodeFixProviderAttribute.cs +++ b/src/Workspaces/Core/Portable/CodeFixes/ExportCodeFixProviderAttribute.cs @@ -6,6 +6,7 @@ using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; +using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes; diff --git a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/BatchFixAllProvider.cs b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/BatchFixAllProvider.cs index 8cfc1d14069cc..b1ea8e1d60665 100644 --- a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/BatchFixAllProvider.cs +++ b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/BatchFixAllProvider.cs @@ -164,7 +164,7 @@ private static async Task> GetAllChangedDocumentsInDiag foreach (var codeAction in codeActions) { var changedSolution = await codeAction.GetChangedSolutionInternalAsync( - solution, fixAllContext.Progress, cancellationToken: cancellationToken).ConfigureAwait(false); + solution, fixAllContext.Progress, cancellationToken).ConfigureAwait(false); if (changedSolution != null) { var changedDocumentIds = new SolutionChanges(changedSolution, solution).GetProjectChanges().SelectMany(p => p.GetChangedDocuments()); diff --git a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllContext.DiagnosticProvider.cs b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllContext.DiagnosticProvider.cs index 391678a382115..ce49576aa2cb8 100644 --- a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllContext.DiagnosticProvider.cs +++ b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllContext.DiagnosticProvider.cs @@ -79,7 +79,7 @@ internal static async Task diagnostics)>.RunParallelAsync( diff --git a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllContext.cs b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllContext.cs index 56de731c8bfb4..a450cde44c701 100644 --- a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllContext.cs +++ b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllContext.cs @@ -73,8 +73,6 @@ public partial class FixAllContext : IFixAllContext #region IFixAllContext implementation IFixAllState IFixAllContext.State => this.State; - IFixAllProvider IFixAllContext.FixAllProvider => this.FixAllProvider; - object IFixAllContext.Provider => this.CodeFixProvider; string IFixAllContext.GetDefaultFixAllTitle() diff --git a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllProvider.cs b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllProvider.cs index 113fffc4fe716..b5aac3e0083bf 100644 --- a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllProvider.cs +++ b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllProvider.cs @@ -21,16 +21,13 @@ public abstract class FixAllProvider : IFixAllProvider private protected static ImmutableArray DefaultSupportedFixAllScopes = [FixAllScope.Document, FixAllScope.Project, FixAllScope.Solution]; - /// - /// Gets the supported scopes for fixing all occurrences of a diagnostic. - /// By default, it returns the following scopes: - /// (a) - /// (b) and - /// (c) - /// public virtual IEnumerable GetSupportedFixAllScopes() => DefaultSupportedFixAllScopes; + CodeActionCleanup IFixAllProvider.Cleanup => this.Cleanup; + + internal virtual CodeActionCleanup Cleanup => CodeActionCleanup.Default; + /// /// Gets the diagnostic IDs for which fix all occurrences is supported. /// By default, it returns for the given . @@ -77,6 +74,14 @@ public static FixAllProvider Create(Func, Task> fixAllAsync, ImmutableArray supportedFixAllScopes) + { + return Create(fixAllAsync, supportedFixAllScopes, CodeActionCleanup.Default); + } + + internal static FixAllProvider Create( + Func, Task> fixAllAsync, + ImmutableArray supportedFixAllScopes, + CodeActionCleanup cleanup) { if (fixAllAsync is null) throw new ArgumentNullException(nameof(fixAllAsync)); @@ -87,7 +92,7 @@ public static FixAllProvider Create( if (supportedFixAllScopes.Contains(FixAllScope.Custom)) throw new ArgumentException(WorkspacesResources.FixAllScope_Custom_is_not_supported_with_this_API, nameof(supportedFixAllScopes)); - return new CallbackDocumentBasedFixAllProvider(fixAllAsync, supportedFixAllScopes); + return new CallbackDocumentBasedFixAllProvider(fixAllAsync, supportedFixAllScopes, cleanup); } #region IFixAllProvider implementation @@ -97,8 +102,11 @@ public static FixAllProvider Create( private sealed class CallbackDocumentBasedFixAllProvider( Func, Task> fixAllAsync, - ImmutableArray supportedFixAllScopes) : DocumentBasedFixAllProvider(supportedFixAllScopes) + ImmutableArray supportedFixAllScopes, + CodeActionCleanup cleanup) : DocumentBasedFixAllProvider(supportedFixAllScopes) { + internal override CodeActionCleanup Cleanup { get; } = cleanup; + protected override Task FixAllAsync(FixAllContext context, Document document, ImmutableArray diagnostics) => fixAllAsync(context, document, diagnostics); } diff --git a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/TextChangeMerger.cs b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/TextChangeMerger.cs index 54f3121429c3b..ecb3fe1a00e09 100644 --- a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/TextChangeMerger.cs +++ b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/TextChangeMerger.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; diff --git a/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/DefaultFixAllProviderHelpers.cs b/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/DefaultFixAllProviderHelpers.cs index 158596febdcc8..9e2cd45ee9c9b 100644 --- a/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/DefaultFixAllProviderHelpers.cs +++ b/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/DefaultFixAllProviderHelpers.cs @@ -26,26 +26,25 @@ internal static class DefaultFixAllProviderHelpers Func, Task> fixAllContextsAsync) where TFixAllContext : IFixAllContext { - // We're about to do a lot of computation to compute all the diagnostics needed and to perform the // changes. Keep this solution alive on the OOP side so that we never drop it and then resync it // (which would cause us to drop/recreate compilations, skeletons and sg docs. - using var _ = await RemoteKeepAliveSession.CreateAsync(fixAllContext.Solution, fixAllContext.CancellationToken).ConfigureAwait(false); + using var _ = await RemoteKeepAliveSession.CreateAsync(fixAllContext.State.Solution, fixAllContext.CancellationToken).ConfigureAwait(false); - var solution = fixAllContext.Scope switch + var solution = fixAllContext.State.Scope switch { FixAllScope.Document or FixAllScope.ContainingMember or FixAllScope.ContainingType => await GetDocumentFixesAsync(fixAllContext, fixAllContextsAsync).ConfigureAwait(false), FixAllScope.Project => await GetProjectFixesAsync(fixAllContext, fixAllContextsAsync).ConfigureAwait(false), FixAllScope.Solution => await GetSolutionFixesAsync(fixAllContext, fixAllContextsAsync).ConfigureAwait(false), - _ => throw ExceptionUtilities.UnexpectedValue(fixAllContext.Scope), + _ => throw ExceptionUtilities.UnexpectedValue(fixAllContext.State.Scope), }; if (solution == null) return null; return CodeAction.Create( - title, _ => Task.FromResult(solution)); + title, (_, _) => Task.FromResult(solution), equivalenceKey: null, CodeActionPriority.Default, fixAllContext.State.FixAllProvider.Cleanup); } private static Task GetDocumentFixesAsync( @@ -58,14 +57,14 @@ FixAllScope.Document or FixAllScope.ContainingMember or FixAllScope.ContainingTy TFixAllContext fixAllContext, Func, Task> fixAllContextsAsync) where TFixAllContext : IFixAllContext - => fixAllContextsAsync(fixAllContext, [(TFixAllContext)fixAllContext.With((document: null, fixAllContext.Project))]); + => fixAllContextsAsync(fixAllContext, [(TFixAllContext)fixAllContext.With((document: null, fixAllContext.State.Project))]); private static Task GetSolutionFixesAsync( TFixAllContext fixAllContext, Func, Task> fixAllContextsAsync) where TFixAllContext : IFixAllContext { - var solution = fixAllContext.Solution; + var solution = fixAllContext.State.Solution; var dependencyGraph = solution.GetProjectDependencyGraph(); // Walk through each project in topological order, determining and applying the diagnostics for each @@ -82,7 +81,7 @@ FixAllScope.Document or FixAllScope.ContainingMember or FixAllScope.ContainingTy // different language. var sortedProjects = dependencyGraph.GetTopologicallySortedProjects() .Select(solution.GetRequiredProject) - .Where(p => p.Language == fixAllContext.Project.Language); + .Where(p => p.Language == fixAllContext.State.Project.Language); return fixAllContextsAsync( fixAllContext, sortedProjects.SelectAsArray(p => (TFixAllContext)fixAllContext.With((document: null, project: p), scope: FixAllScope.Project))); diff --git a/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/DocumentBasedFixAllProviderHelpers.cs b/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/DocumentBasedFixAllProviderHelpers.cs index bf8e25f0f5484..bd02c225db200 100644 --- a/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/DocumentBasedFixAllProviderHelpers.cs +++ b/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/DocumentBasedFixAllProviderHelpers.cs @@ -32,7 +32,7 @@ internal static class DocumentBasedFixAllProviderHelpers progressTracker.Report(CodeAnalysisProgress.Description(progressTrackerDescription)); - var originalSolution = originalFixAllContext.Solution; + var originalSolution = originalFixAllContext.State.Solution; // One work item for each context. progressTracker.AddItems(fixAllContexts.Length); @@ -44,11 +44,8 @@ internal static class DocumentBasedFixAllProviderHelpers progressTracker.Report(CodeAnalysisProgress.Clear()); progressTracker.Report(CodeAnalysisProgress.Description(WorkspacesResources.Running_code_cleanup_on_fixed_documents)); - var cleanedSolution = await CodeAction.CleanSyntaxAndSemanticsAsync( - originalSolution, - dirtySolution, - progressTracker, - cancellationToken).ConfigureAwait(false); + var cleanedSolution = await CodeAction.PostProcessChangesAsync( + originalSolution, dirtySolution, progressTracker, originalFixAllContext.State.FixAllProvider.Cleanup, cancellationToken).ConfigureAwait(false); // Once we clean the document, we get the text of it and insert that back into the final solution. This way we // can release both the original fixed tree, and the cleaned tree (both of which can be much more expensive than @@ -77,7 +74,7 @@ async Task GetInitialUncleanedSolutionAsync(Solution originalSolution) using var _ = progressTracker.ItemCompletedScope(); Contract.ThrowIfFalse( - fixAllContext.Scope is FixAllScope.Document or FixAllScope.Project or FixAllScope.ContainingMember or FixAllScope.ContainingType); + fixAllContext.State.Scope is FixAllScope.Document or FixAllScope.Project or FixAllScope.ContainingMember or FixAllScope.ContainingType); // Defer to the FixAllProvider to actually compute each fixed document. await getFixedDocumentsAsync( diff --git a/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/FixAllProviderInfo.cs b/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/FixAllProviderInfo.cs index 138d93cf713a4..c14ea9c150d24 100644 --- a/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/FixAllProviderInfo.cs +++ b/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/FixAllProviderInfo.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.Linq; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeRefactorings; using Roslyn.Utilities; diff --git a/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/IFixAllContext.cs b/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/IFixAllContext.cs index 13c705805da00..e4a930af4031e 100644 --- a/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/IFixAllContext.cs +++ b/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/IFixAllContext.cs @@ -14,13 +14,7 @@ namespace Microsoft.CodeAnalysis.CodeFixesAndRefactorings; internal interface IFixAllContext { IFixAllState State { get; } - IFixAllProvider FixAllProvider { get; } - Solution Solution { get; } - Project Project { get; } - Document? Document { get; } object Provider { get; } - FixAllScope Scope { get; } - string? CodeActionEquivalenceKey { get; } CancellationToken CancellationToken { get; } IProgress Progress { get; } diff --git a/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/IFixAllProvider.cs b/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/IFixAllProvider.cs index 668dc36aacc0a..50db400fe367f 100644 --- a/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/IFixAllProvider.cs +++ b/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/IFixAllProvider.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; -using FixAllScope = Microsoft.CodeAnalysis.CodeFixes.FixAllScope; +using Microsoft.CodeAnalysis.CodeFixes; namespace Microsoft.CodeAnalysis.CodeFixesAndRefactorings; @@ -14,6 +14,20 @@ namespace Microsoft.CodeAnalysis.CodeFixesAndRefactorings; /// internal interface IFixAllProvider { + /// + /// Gets the supported scopes for applying multiple occurrences of a code refactoring. + /// By default, it returns the following scopes: + /// (a) + /// (b) and + /// (c) + /// IEnumerable GetSupportedFixAllScopes(); + Task GetFixAsync(IFixAllContext fixAllContext); + + /// + /// The sort of cleanup that should automatically be poerformed for this fix all provider. By default this is + /// . + /// + CodeActionCleanup Cleanup { get; } } diff --git a/src/Workspaces/Core/Portable/CodeRefactorings/FixAllOccurences/FixAllContext.cs b/src/Workspaces/Core/Portable/CodeRefactorings/FixAllOccurences/FixAllContext.cs index 2433faae81c2a..7dec1f30e253f 100644 --- a/src/Workspaces/Core/Portable/CodeRefactorings/FixAllOccurences/FixAllContext.cs +++ b/src/Workspaces/Core/Portable/CodeRefactorings/FixAllOccurences/FixAllContext.cs @@ -65,8 +65,6 @@ internal sealed class FixAllContext : IFixAllContext #region IFixAllContext implementation IFixAllState IFixAllContext.State => this.State; - IFixAllProvider IFixAllContext.FixAllProvider => this.FixAllProvider; - object IFixAllContext.Provider => this.CodeRefactoringProvider; string IFixAllContext.GetDefaultFixAllTitle() => this.GetDefaultFixAllTitle(); diff --git a/src/Workspaces/Core/Portable/CodeRefactorings/FixAllOccurences/FixAllProvider.cs b/src/Workspaces/Core/Portable/CodeRefactorings/FixAllOccurences/FixAllProvider.cs index 15b064bed2aa3..4bb45d22e184b 100644 --- a/src/Workspaces/Core/Portable/CodeRefactorings/FixAllOccurences/FixAllProvider.cs +++ b/src/Workspaces/Core/Portable/CodeRefactorings/FixAllOccurences/FixAllProvider.cs @@ -24,16 +24,11 @@ internal abstract class FixAllProvider : IFixAllProvider private protected static ImmutableArray DefaultSupportedFixAllScopes = [FixAllScope.Document, FixAllScope.Project, FixAllScope.Solution]; - /// - /// Gets the supported scopes for applying multiple occurrences of a code refactoring. - /// By default, it returns the following scopes: - /// (a) - /// (b) and - /// (c) - /// public virtual IEnumerable GetSupportedFixAllScopes() => DefaultSupportedFixAllScopes; + public virtual CodeActionCleanup Cleanup => CodeActionCleanup.Default; + /// /// Gets fix all occurrences fix for the given fixAllContext. /// @@ -77,6 +72,14 @@ public static FixAllProvider Create(Func>, Task> fixAllAsync, ImmutableArray supportedFixAllScopes) + { + return Create(fixAllAsync, supportedFixAllScopes, CodeActionCleanup.Default); + } + + internal static FixAllProvider Create( + Func>, Task> fixAllAsync, + ImmutableArray supportedFixAllScopes, + CodeActionCleanup cleanup) { if (fixAllAsync is null) throw new ArgumentNullException(nameof(fixAllAsync)); @@ -87,13 +90,16 @@ public static FixAllProvider Create( if (supportedFixAllScopes.Contains(FixAllScope.Custom)) throw new ArgumentException(WorkspacesResources.FixAllScope_Custom_is_not_supported_with_this_API, nameof(supportedFixAllScopes)); - return new CallbackDocumentBasedFixAllProvider(fixAllAsync, supportedFixAllScopes); + return new CallbackDocumentBasedFixAllProvider(fixAllAsync, supportedFixAllScopes, cleanup); } private sealed class CallbackDocumentBasedFixAllProvider( Func>, Task> fixAllAsync, - ImmutableArray supportedFixAllScopes) : DocumentBasedFixAllProvider(supportedFixAllScopes) + ImmutableArray supportedFixAllScopes, + CodeActionCleanup cleanup) : DocumentBasedFixAllProvider(supportedFixAllScopes) { + public override CodeActionCleanup Cleanup { get; } = cleanup; + protected override Task FixAllAsync(FixAllContext context, Document document, Optional> fixAllSpans) => fixAllAsync(context, document, fixAllSpans); } diff --git a/src/Workspaces/Core/Portable/CodeRefactorings/FixAllOccurences/FixAllState.cs b/src/Workspaces/Core/Portable/CodeRefactorings/FixAllOccurences/FixAllState.cs index c100f75be9641..d0e11df8f598f 100644 --- a/src/Workspaces/Core/Portable/CodeRefactorings/FixAllOccurences/FixAllState.cs +++ b/src/Workspaces/Core/Portable/CodeRefactorings/FixAllOccurences/FixAllState.cs @@ -100,7 +100,7 @@ internal async Task KeyValuePairUtil.Create(kvp.Key, new Optional>(kvp.Value))) + return spansByDocument.Select(kvp => KeyValuePair.Create(kvp.Key, new Optional>(kvp.Value))) .ToImmutableDictionaryOrEmpty(); case FixAllScope.Document: diff --git a/src/Workspaces/Core/Portable/CodeRefactorings/SyntaxEditorBasedCodeRefactoringProvider.cs b/src/Workspaces/Core/Portable/CodeRefactorings/SyntaxEditorBasedCodeRefactoringProvider.cs index 6c97f2080b6e3..0ef5c4888c6cd 100644 --- a/src/Workspaces/Core/Portable/CodeRefactorings/SyntaxEditorBasedCodeRefactoringProvider.cs +++ b/src/Workspaces/Core/Portable/CodeRefactorings/SyntaxEditorBasedCodeRefactoringProvider.cs @@ -6,6 +6,7 @@ using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; @@ -19,6 +20,7 @@ internal abstract partial class SyntaxEditorBasedCodeRefactoringProvider : CodeR protected static readonly ImmutableArray AllFixAllScopes = [FixAllScope.Document, FixAllScope.Project, FixAllScope.Solution, FixAllScope.ContainingType, FixAllScope.ContainingMember]; protected abstract ImmutableArray SupportedFixAllScopes { get; } + protected virtual CodeActionCleanup Cleanup => CodeActionCleanup.Default; internal sealed override FixAllProvider? GetFixAllProvider() { @@ -28,7 +30,8 @@ internal abstract partial class SyntaxEditorBasedCodeRefactoringProvider : CodeR return FixAllProvider.Create( async (fixAllContext, document, fixAllSpans) => await this.FixAllAsync(document, fixAllSpans, fixAllContext.CodeActionEquivalenceKey, fixAllContext.CancellationToken).ConfigureAwait(false), - SupportedFixAllScopes); + SupportedFixAllScopes, + this.Cleanup); } protected Task FixAsync( diff --git a/src/Workspaces/Core/Portable/Diagnostics/AnalysisResultPair.cs b/src/Workspaces/Core/Portable/Diagnostics/AnalysisResultPair.cs index 6a3b25d488546..c7635ccb52155 100644 --- a/src/Workspaces/Core/Portable/Diagnostics/AnalysisResultPair.cs +++ b/src/Workspaces/Core/Portable/Diagnostics/AnalysisResultPair.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using System.Collections.Generic; using Microsoft.CodeAnalysis.Diagnostics.Telemetry; using Roslyn.Utilities; @@ -10,15 +11,6 @@ namespace Microsoft.CodeAnalysis.Diagnostics; internal sealed class AnalysisResultPair { - private readonly AnalysisResult? _projectAnalysisResult; - private readonly AnalysisResult? _hostAnalysisResult; - - private ImmutableDictionary>>? _lazyMergedSyntaxDiagnostics; - private ImmutableDictionary>>? _lazyMergedSemanticDiagnostics; - private ImmutableDictionary>>? _lazyMergedAdditionalFileDiagnostics; - private ImmutableDictionary>? _lazyMergedCompilationDiagnostics; - private ImmutableDictionary? _lazyMergedAnalyzerTelemetryInfo; - public AnalysisResultPair(AnalysisResult? projectAnalysisResult, AnalysisResult? hostAnalysisResult) { if (projectAnalysisResult is not null && hostAnalysisResult is not null) @@ -29,20 +21,20 @@ public AnalysisResultPair(AnalysisResult? projectAnalysisResult, AnalysisResult? Contract.ThrowIfTrue(projectAnalysisResult is null && hostAnalysisResult is null); } - _projectAnalysisResult = projectAnalysisResult; - _hostAnalysisResult = hostAnalysisResult; + ProjectAnalysisResult = projectAnalysisResult; + HostAnalysisResult = hostAnalysisResult; } - public AnalysisResult? ProjectAnalysisResult => _projectAnalysisResult; + public AnalysisResult? ProjectAnalysisResult { get; } - public AnalysisResult? HostAnalysisResult => _hostAnalysisResult; + public AnalysisResult? HostAnalysisResult { get; } public ImmutableDictionary>> MergedSyntaxDiagnostics { get { return InterlockedOperations.Initialize( - ref _lazyMergedSyntaxDiagnostics, + ref field, static arg => { if (arg.projectDiagnostics is null) @@ -67,7 +59,7 @@ public ImmutableDictionary { if (arg.projectDiagnostics is null) @@ -92,7 +84,7 @@ public ImmutableDictionary { if (arg.projectDiagnostics is null) @@ -117,7 +109,7 @@ public ImmutableDictionary> Merge get { return InterlockedOperations.Initialize( - ref _lazyMergedCompilationDiagnostics, + ref field, static arg => { if (arg.projectDiagnostics is null) @@ -142,7 +134,7 @@ public ImmutableDictionary MergedAnal get { return InterlockedOperations.Initialize( - ref _lazyMergedAnalyzerTelemetryInfo, + ref field, static arg => { if (arg.projectTelemetryInfo is null) @@ -160,6 +152,8 @@ public ImmutableDictionary MergedAnal }, (projectTelemetryInfo: ProjectAnalysisResult?.AnalyzerTelemetryInfo, hostTelemetryInfo: HostAnalysisResult?.AnalyzerTelemetryInfo)); } + + private set; } public static AnalysisResultPair? FromResult(AnalysisResult? projectAnalysisResult, AnalysisResult? hostAnalysisResult) diff --git a/src/Workspaces/Core/Portable/Diagnostics/CompilationWithAnalyzersPair.cs b/src/Workspaces/Core/Portable/Diagnostics/CompilationWithAnalyzersPair.cs index 5e308ed7521be..a532074b3fa8e 100644 --- a/src/Workspaces/Core/Portable/Diagnostics/CompilationWithAnalyzersPair.cs +++ b/src/Workspaces/Core/Portable/Diagnostics/CompilationWithAnalyzersPair.cs @@ -15,9 +15,6 @@ namespace Microsoft.CodeAnalysis.Diagnostics; internal sealed class CompilationWithAnalyzersPair { - private readonly CompilationWithAnalyzers? _projectCompilationWithAnalyzers; - private readonly CompilationWithAnalyzers? _hostCompilationWithAnalyzers; - public CompilationWithAnalyzersPair(CompilationWithAnalyzers? projectCompilationWithAnalyzers, CompilationWithAnalyzers? hostCompilationWithAnalyzers) { if (projectCompilationWithAnalyzers is not null && hostCompilationWithAnalyzers is not null) @@ -30,25 +27,25 @@ public CompilationWithAnalyzersPair(CompilationWithAnalyzers? projectCompilation Contract.ThrowIfTrue(projectCompilationWithAnalyzers is null && hostCompilationWithAnalyzers is null); } - _projectCompilationWithAnalyzers = projectCompilationWithAnalyzers; - _hostCompilationWithAnalyzers = hostCompilationWithAnalyzers; + ProjectCompilationWithAnalyzers = projectCompilationWithAnalyzers; + HostCompilationWithAnalyzers = hostCompilationWithAnalyzers; } - public Compilation? ProjectCompilation => _projectCompilationWithAnalyzers?.Compilation; + public Compilation? ProjectCompilation => ProjectCompilationWithAnalyzers?.Compilation; - public Compilation? HostCompilation => _hostCompilationWithAnalyzers?.Compilation; + public Compilation? HostCompilation => HostCompilationWithAnalyzers?.Compilation; - public CompilationWithAnalyzers? ProjectCompilationWithAnalyzers => _projectCompilationWithAnalyzers; + public CompilationWithAnalyzers? ProjectCompilationWithAnalyzers { get; } - public CompilationWithAnalyzers? HostCompilationWithAnalyzers => _hostCompilationWithAnalyzers; + public CompilationWithAnalyzers? HostCompilationWithAnalyzers { get; } - public bool ConcurrentAnalysis => _projectCompilationWithAnalyzers?.AnalysisOptions.ConcurrentAnalysis ?? _hostCompilationWithAnalyzers!.AnalysisOptions.ConcurrentAnalysis; + public bool ConcurrentAnalysis => ProjectCompilationWithAnalyzers?.AnalysisOptions.ConcurrentAnalysis ?? HostCompilationWithAnalyzers!.AnalysisOptions.ConcurrentAnalysis; public bool HasAnalyzers => ProjectAnalyzers.Any() || HostAnalyzers.Any(); - public ImmutableArray ProjectAnalyzers => _projectCompilationWithAnalyzers?.Analyzers ?? []; + public ImmutableArray ProjectAnalyzers => ProjectCompilationWithAnalyzers?.Analyzers ?? []; - public ImmutableArray HostAnalyzers => _hostCompilationWithAnalyzers?.Analyzers ?? []; + public ImmutableArray HostAnalyzers => HostCompilationWithAnalyzers?.Analyzers ?? []; public Task GetAnalyzerTelemetryInfoAsync(DiagnosticAnalyzer analyzer, CancellationToken cancellationToken) { diff --git a/src/Workspaces/Core/Portable/Diagnostics/DiagnosticAnalysisResult.cs b/src/Workspaces/Core/Portable/Diagnostics/DiagnosticAnalysisResult.cs index d4f626bbac9f1..7c383e08af162 100644 --- a/src/Workspaces/Core/Portable/Diagnostics/DiagnosticAnalysisResult.cs +++ b/src/Workspaces/Core/Portable/Diagnostics/DiagnosticAnalysisResult.cs @@ -6,6 +6,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Collections; diff --git a/src/Workspaces/Core/Portable/Differencing/LongestCommonSubsequence.cs b/src/Workspaces/Core/Portable/Differencing/LongestCommonSubsequence.cs index be69c9dd8d29b..940ae13015146 100644 --- a/src/Workspaces/Core/Portable/Differencing/LongestCommonSubsequence.cs +++ b/src/Workspaces/Core/Portable/Differencing/LongestCommonSubsequence.cs @@ -285,7 +285,7 @@ protected IEnumerable> GetMatchingPairs(TSequence oldSequ Debug.Assert(yEnd > yMid); xEnd--; yEnd--; - yield return KeyValuePairUtil.Create(xEnd, yEnd); + yield return KeyValuePair.Create(xEnd, yEnd); } x = xStart; diff --git a/src/Workspaces/Core/Portable/Editing/DeclarationKind.cs b/src/Workspaces/Core/Portable/Editing/DeclarationKind.cs index 8793dfd2a364f..ad49d9a8915c7 100644 --- a/src/Workspaces/Core/Portable/Editing/DeclarationKind.cs +++ b/src/Workspaces/Core/Portable/Editing/DeclarationKind.cs @@ -5,11 +5,7 @@ using System; using System.ComponentModel; -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Editing; -#else namespace Microsoft.CodeAnalysis.Editing; -#endif /// /// This should contain only language-agnostic declarations. Things like record struct should fall under struct, etc. diff --git a/src/Workspaces/Core/Portable/Editing/DeclarationModifiers.cs b/src/Workspaces/Core/Portable/Editing/DeclarationModifiers.cs index 5e7e0cc1de489..15214850ffb3b 100644 --- a/src/Workspaces/Core/Portable/Editing/DeclarationModifiers.cs +++ b/src/Workspaces/Core/Portable/Editing/DeclarationModifiers.cs @@ -6,18 +6,14 @@ using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Editing; -#else namespace Microsoft.CodeAnalysis.Editing; -#endif public readonly record struct DeclarationModifiers { - private readonly Modifiers _modifiers; + internal readonly Modifiers Modifiers; - private DeclarationModifiers(Modifiers modifiers) - => _modifiers = modifiers; + internal DeclarationModifiers(Modifiers modifiers) + => Modifiers = modifiers; internal DeclarationModifiers( bool isStatic = false, @@ -100,129 +96,102 @@ or IMethodSymbol return DeclarationModifiers.None; } - public bool IsStatic => (_modifiers & Modifiers.Static) != 0; + public bool IsStatic => (Modifiers & Modifiers.Static) != 0; - public bool IsAbstract => (_modifiers & Modifiers.Abstract) != 0; + public bool IsAbstract => (Modifiers & Modifiers.Abstract) != 0; - public bool IsNew => (_modifiers & Modifiers.New) != 0; + public bool IsNew => (Modifiers & Modifiers.New) != 0; - public bool IsUnsafe => (_modifiers & Modifiers.Unsafe) != 0; + public bool IsUnsafe => (Modifiers & Modifiers.Unsafe) != 0; - public bool IsReadOnly => (_modifiers & Modifiers.ReadOnly) != 0; + public bool IsReadOnly => (Modifiers & Modifiers.ReadOnly) != 0; - public bool IsVirtual => (_modifiers & Modifiers.Virtual) != 0; + public bool IsVirtual => (Modifiers & Modifiers.Virtual) != 0; - public bool IsOverride => (_modifiers & Modifiers.Override) != 0; + public bool IsOverride => (Modifiers & Modifiers.Override) != 0; - public bool IsSealed => (_modifiers & Modifiers.Sealed) != 0; + public bool IsSealed => (Modifiers & Modifiers.Sealed) != 0; - public bool IsConst => (_modifiers & Modifiers.Const) != 0; + public bool IsConst => (Modifiers & Modifiers.Const) != 0; - public bool IsWithEvents => (_modifiers & Modifiers.WithEvents) != 0; + public bool IsWithEvents => (Modifiers & Modifiers.WithEvents) != 0; - public bool IsPartial => (_modifiers & Modifiers.Partial) != 0; + public bool IsPartial => (Modifiers & Modifiers.Partial) != 0; - public bool IsAsync => (_modifiers & Modifiers.Async) != 0; + public bool IsAsync => (Modifiers & Modifiers.Async) != 0; - public bool IsWriteOnly => (_modifiers & Modifiers.WriteOnly) != 0; + public bool IsWriteOnly => (Modifiers & Modifiers.WriteOnly) != 0; - public bool IsRef => (_modifiers & Modifiers.Ref) != 0; + public bool IsRef => (Modifiers & Modifiers.Ref) != 0; - public bool IsVolatile => (_modifiers & Modifiers.Volatile) != 0; + public bool IsVolatile => (Modifiers & Modifiers.Volatile) != 0; - public bool IsExtern => (_modifiers & Modifiers.Extern) != 0; + public bool IsExtern => (Modifiers & Modifiers.Extern) != 0; - public bool IsRequired => (_modifiers & Modifiers.Required) != 0; + public bool IsRequired => (Modifiers & Modifiers.Required) != 0; - public bool IsFile => (_modifiers & Modifiers.File) != 0; + public bool IsFile => (Modifiers & Modifiers.File) != 0; - internal bool IsFixed => (_modifiers & Modifiers.Fixed) != 0; + internal bool IsFixed => (Modifiers & Modifiers.Fixed) != 0; public DeclarationModifiers WithIsStatic(bool isStatic) - => new(SetFlag(_modifiers, Modifiers.Static, isStatic)); + => new(SetFlag(Modifiers, Modifiers.Static, isStatic)); public DeclarationModifiers WithIsAbstract(bool isAbstract) - => new(SetFlag(_modifiers, Modifiers.Abstract, isAbstract)); + => new(SetFlag(Modifiers, Modifiers.Abstract, isAbstract)); public DeclarationModifiers WithIsNew(bool isNew) - => new(SetFlag(_modifiers, Modifiers.New, isNew)); + => new(SetFlag(Modifiers, Modifiers.New, isNew)); public DeclarationModifiers WithIsUnsafe(bool isUnsafe) - => new(SetFlag(_modifiers, Modifiers.Unsafe, isUnsafe)); + => new(SetFlag(Modifiers, Modifiers.Unsafe, isUnsafe)); public DeclarationModifiers WithIsReadOnly(bool isReadOnly) - => new(SetFlag(_modifiers, Modifiers.ReadOnly, isReadOnly)); + => new(SetFlag(Modifiers, Modifiers.ReadOnly, isReadOnly)); public DeclarationModifiers WithIsVirtual(bool isVirtual) - => new(SetFlag(_modifiers, Modifiers.Virtual, isVirtual)); + => new(SetFlag(Modifiers, Modifiers.Virtual, isVirtual)); public DeclarationModifiers WithIsOverride(bool isOverride) - => new(SetFlag(_modifiers, Modifiers.Override, isOverride)); + => new(SetFlag(Modifiers, Modifiers.Override, isOverride)); public DeclarationModifiers WithIsSealed(bool isSealed) - => new(SetFlag(_modifiers, Modifiers.Sealed, isSealed)); + => new(SetFlag(Modifiers, Modifiers.Sealed, isSealed)); public DeclarationModifiers WithIsConst(bool isConst) - => new(SetFlag(_modifiers, Modifiers.Const, isConst)); + => new(SetFlag(Modifiers, Modifiers.Const, isConst)); public DeclarationModifiers WithWithEvents(bool withEvents) - => new(SetFlag(_modifiers, Modifiers.WithEvents, withEvents)); + => new(SetFlag(Modifiers, Modifiers.WithEvents, withEvents)); public DeclarationModifiers WithPartial(bool isPartial) - => new(SetFlag(_modifiers, Modifiers.Partial, isPartial)); + => new(SetFlag(Modifiers, Modifiers.Partial, isPartial)); [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "Public API.")] public DeclarationModifiers WithAsync(bool isAsync) - => new(SetFlag(_modifiers, Modifiers.Async, isAsync)); + => new(SetFlag(Modifiers, Modifiers.Async, isAsync)); public DeclarationModifiers WithIsWriteOnly(bool isWriteOnly) - => new(SetFlag(_modifiers, Modifiers.WriteOnly, isWriteOnly)); + => new(SetFlag(Modifiers, Modifiers.WriteOnly, isWriteOnly)); public DeclarationModifiers WithIsRef(bool isRef) - => new(SetFlag(_modifiers, Modifiers.Ref, isRef)); + => new(SetFlag(Modifiers, Modifiers.Ref, isRef)); public DeclarationModifiers WithIsVolatile(bool isVolatile) - => new(SetFlag(_modifiers, Modifiers.Volatile, isVolatile)); + => new(SetFlag(Modifiers, Modifiers.Volatile, isVolatile)); public DeclarationModifiers WithIsExtern(bool isExtern) - => new(SetFlag(_modifiers, Modifiers.Extern, isExtern)); + => new(SetFlag(Modifiers, Modifiers.Extern, isExtern)); public DeclarationModifiers WithIsRequired(bool isRequired) - => new(SetFlag(_modifiers, Modifiers.Required, isRequired)); + => new(SetFlag(Modifiers, Modifiers.Required, isRequired)); public DeclarationModifiers WithIsFile(bool isFile) - => new(SetFlag(_modifiers, Modifiers.File, isFile)); + => new(SetFlag(Modifiers, Modifiers.File, isFile)); private static Modifiers SetFlag(Modifiers existing, Modifiers modifier, bool isSet) => isSet ? (existing | modifier) : (existing & ~modifier); - [Flags] - private enum Modifiers - { -#pragma warning disable format - None = 0, - Static = 1 << 0, - Abstract = 1 << 1, - New = 1 << 2, - Unsafe = 1 << 3, - ReadOnly = 1 << 4, - Virtual = 1 << 5, - Override = 1 << 6, - Sealed = 1 << 7, - Const = 1 << 8, - WithEvents = 1 << 9, - Partial = 1 << 10, - Async = 1 << 11, - WriteOnly = 1 << 12, - Ref = 1 << 13, - Volatile = 1 << 14, - Extern = 1 << 15, - Required = 1 << 16, - File = 1 << 17, - Fixed = 1 << 18, -#pragma warning restore format - } - public static DeclarationModifiers None => default; public static DeclarationModifiers Static => new(Modifiers.Static); @@ -246,19 +215,19 @@ private enum Modifiers internal static DeclarationModifiers Fixed => new(Modifiers.Fixed); public static DeclarationModifiers operator |(DeclarationModifiers left, DeclarationModifiers right) - => new(left._modifiers | right._modifiers); + => new(left.Modifiers | right.Modifiers); public static DeclarationModifiers operator &(DeclarationModifiers left, DeclarationModifiers right) - => new(left._modifiers & right._modifiers); + => new(left.Modifiers & right.Modifiers); public static DeclarationModifiers operator +(DeclarationModifiers left, DeclarationModifiers right) - => new(left._modifiers | right._modifiers); + => new(left.Modifiers | right.Modifiers); public static DeclarationModifiers operator -(DeclarationModifiers left, DeclarationModifiers right) - => new(left._modifiers & ~right._modifiers); + => new(left.Modifiers & ~right.Modifiers); public override string ToString() - => _modifiers.ToString(); + => Modifiers.ToString(); public static bool TryParse(string value, out DeclarationModifiers modifiers) { diff --git a/src/Workspaces/Core/Portable/Editing/SyntaxGenerator.cs b/src/Workspaces/Core/Portable/Editing/SyntaxGenerator.cs index ea037cbd0e758..6ed520b901114 100644 --- a/src/Workspaces/Core/Portable/Editing/SyntaxGenerator.cs +++ b/src/Workspaces/Core/Portable/Editing/SyntaxGenerator.cs @@ -2333,25 +2333,25 @@ public SyntaxNode ConvertExpression(ITypeSymbol type, SyntaxNode expression) /// Creates an expression that declares a single parameter value returning lambda expression. /// public SyntaxNode ValueReturningLambdaExpression(string parameterName, SyntaxNode expression) - => ValueReturningLambdaExpression(new[] { LambdaParameter(parameterName) }, expression); + => ValueReturningLambdaExpression([LambdaParameter(parameterName)], expression); /// /// Creates an expression that declares a single parameter void returning lambda expression. /// public SyntaxNode VoidReturningLambdaExpression(string parameterName, SyntaxNode expression) - => VoidReturningLambdaExpression(new[] { LambdaParameter(parameterName) }, expression); + => VoidReturningLambdaExpression([LambdaParameter(parameterName)], expression); /// /// Creates an expression that declares a single parameter value returning lambda expression. /// public SyntaxNode ValueReturningLambdaExpression(string parameterName, IEnumerable statements) - => ValueReturningLambdaExpression(new[] { LambdaParameter(parameterName) }, statements); + => ValueReturningLambdaExpression([LambdaParameter(parameterName)], statements); /// /// Creates an expression that declares a single parameter void returning lambda expression. /// public SyntaxNode VoidReturningLambdaExpression(string parameterName, IEnumerable statements) - => VoidReturningLambdaExpression(new[] { LambdaParameter(parameterName) }, statements); + => VoidReturningLambdaExpression([LambdaParameter(parameterName)], statements); /// /// Creates an expression that declares a zero parameter value returning lambda expression. diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.BidirectionalSymbolSet.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.BidirectionalSymbolSet.cs index 84d1eb09e6a8d..725ef992e8cbd 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.BidirectionalSymbolSet.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.BidirectionalSymbolSet.cs @@ -2,12 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols; diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.UnidirectionalSymbolSet.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.UnidirectionalSymbolSet.cs index 9cbb5846a849e..624a9edaf9764 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.UnidirectionalSymbolSet.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.UnidirectionalSymbolSet.cs @@ -2,12 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols; diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AbstractReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AbstractReferenceFinder.cs index c06cd44d208d0..cfb3f83439906 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AbstractReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AbstractReferenceFinder.cs @@ -9,6 +9,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; @@ -607,7 +608,17 @@ protected static SymbolUsageInfo GetSymbolUsageInfo( while (syntaxFacts.IsQualifiedName(topNameNode.Parent)) topNameNode = topNameNode.Parent; - var isInNamespaceNameContext = syntaxFacts.IsBaseNamespaceDeclaration(topNameNode.Parent); + var parent = topNameNode?.Parent; + + // typeof/sizeof are a special case where we don't want to return a TypeOrNamespaceUsageInfo, but rather a ValueUsageInfo.Name. + // This brings it in line with nameof(...), making all those operators appear in a similar fashion. + if (parent?.RawKind == syntaxFacts.SyntaxKinds.TypeOfExpression || + parent?.RawKind == syntaxFacts.SyntaxKinds.SizeOfExpression) + { + return new(ValueUsageInfo.Name, typeOrNamespaceUsageInfoOpt: null); + } + + var isInNamespaceNameContext = syntaxFacts.IsBaseNamespaceDeclaration(parent); return syntaxFacts.IsInNamespaceOrTypeContext(topNameNode) ? SymbolUsageInfo.Create(GetTypeOrNamespaceUsageInfo()) : GetSymbolUsageInfoCommon(); @@ -676,18 +687,12 @@ SymbolUsageInfo GetSymbolUsageInfoCommon() if (operation is IObjectCreationOperation) return SymbolUsageInfo.Create(TypeOrNamespaceUsageInfo.ObjectCreation); - switch (operation?.Parent) - { - case INameOfOperation: - case ITypeOfOperation: - case ISizeOfOperation: - return SymbolUsageInfo.Create(ValueUsageInfo.Name); - } + // Note: sizeof/typeof also return 'name', but are handled above in GetSymbolUsageInfo. + if (operation?.Parent is INameOfOperation) + return SymbolUsageInfo.Create(ValueUsageInfo.Name); if (node.IsPartOfStructuredTrivia()) - { return SymbolUsageInfo.Create(ValueUsageInfo.Name); - } var symbolInfo = semanticModel.GetSymbolInfo(node, cancellationToken); if (symbolInfo.Symbol != null) diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ConstructorInitializerSymbolReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ConstructorInitializerSymbolReferenceFinder.cs index 85aef6b00770c..817f2e3157159 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ConstructorInitializerSymbolReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ConstructorInitializerSymbolReferenceFinder.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Extensions; diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/EventSymbolReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/EventSymbolReferenceFinder.cs index e961f81af4f5c..611c8a6476e0b 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/EventSymbolReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/EventSymbolReferenceFinder.cs @@ -32,7 +32,7 @@ protected sealed override ValueTask> DetermineCascadedSy .WhereAsArray(n => symbol.Equals(n.AssociatedSymbol)) .CastArray(); - return new(GetOtherPartsOfPartial(symbol).Concat(backingFields).Concat(associatedNamedTypes)); + return new([.. GetOtherPartsOfPartial(symbol), .. backingFields, .. associatedNamedTypes]); } private static ImmutableArray GetOtherPartsOfPartial(IEventSymbol symbol) diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/MethodTypeParameterSymbolReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/MethodTypeParameterSymbolReferenceFinder.cs index f0150097e7a10..2df106afae26a 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/MethodTypeParameterSymbolReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/MethodTypeParameterSymbolReferenceFinder.cs @@ -7,6 +7,7 @@ using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Collections; namespace Microsoft.CodeAnalysis.FindSymbols.Finders; diff --git a/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo.cs b/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo.cs index e0b2b86906e9a..74cc81d0414e2 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Immutable; +using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; diff --git a/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo_Source.cs b/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo_Source.cs index 13904c4d55950..9365aaa490484 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo_Source.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo_Source.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; diff --git a/src/Workspaces/Core/Portable/FindSymbols/SyntaxTree/SyntaxTreeIndex_Forwarders.cs b/src/Workspaces/Core/Portable/FindSymbols/SyntaxTree/SyntaxTreeIndex_Forwarders.cs index 7d4ff66ba23c7..7ff47aee566a3 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/SyntaxTree/SyntaxTreeIndex_Forwarders.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/SyntaxTree/SyntaxTreeIndex_Forwarders.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Utilities; diff --git a/src/Workspaces/Core/Portable/FindSymbols/TopLevelSyntaxTree/DeclaredSymbolInfo.cs b/src/Workspaces/Core/Portable/FindSymbols/TopLevelSyntaxTree/DeclaredSymbolInfo.cs index bb6492341618b..a35454805107f 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/TopLevelSyntaxTree/DeclaredSymbolInfo.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/TopLevelSyntaxTree/DeclaredSymbolInfo.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Runtime.Serialization; using System.Threading; using Microsoft.CodeAnalysis.ErrorReporting; diff --git a/src/Workspaces/Core/Portable/FindSymbols/TopLevelSyntaxTree/TopLevelSyntaxTreeIndex.ExtensionMethodInfo.cs b/src/Workspaces/Core/Portable/FindSymbols/TopLevelSyntaxTree/TopLevelSyntaxTreeIndex.ExtensionMethodInfo.cs index a8b3dc5868605..63325aa9bc5f3 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/TopLevelSyntaxTree/TopLevelSyntaxTreeIndex.ExtensionMethodInfo.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/TopLevelSyntaxTree/TopLevelSyntaxTreeIndex.ExtensionMethodInfo.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Immutable; +using System.Collections.Generic; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; diff --git a/src/Workspaces/Core/Portable/FindSymbols/TopLevelSyntaxTree/TopLevelSyntaxTreeIndex_Create.cs b/src/Workspaces/Core/Portable/FindSymbols/TopLevelSyntaxTree/TopLevelSyntaxTreeIndex_Create.cs index b2d4ab62247df..68d69caa90d46 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/TopLevelSyntaxTree/TopLevelSyntaxTreeIndex_Create.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/TopLevelSyntaxTree/TopLevelSyntaxTreeIndex_Create.cs @@ -2,11 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols; diff --git a/src/Workspaces/Core/Portable/Formatting/Formatter.cs b/src/Workspaces/Core/Portable/Formatting/Formatter.cs index f793f2098f88e..a53c694513162 100644 --- a/src/Workspaces/Core/Portable/Formatting/Formatter.cs +++ b/src/Workspaces/Core/Portable/Formatting/Formatter.cs @@ -14,7 +14,6 @@ using Microsoft.CodeAnalysis.OrganizeImports; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; -using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Formatting.FormattingExtensions; namespace Microsoft.CodeAnalysis.Formatting; diff --git a/src/Workspaces/Core/Portable/LanguageServices/FixAllSpanMappingService/AbstractFixAllSpanMappingService.cs b/src/Workspaces/Core/Portable/LanguageServices/FixAllSpanMappingService/AbstractFixAllSpanMappingService.cs index 570016ae58692..b4dcb079f2807 100644 --- a/src/Workspaces/Core/Portable/LanguageServices/FixAllSpanMappingService/AbstractFixAllSpanMappingService.cs +++ b/src/Workspaces/Core/Portable/LanguageServices/FixAllSpanMappingService/AbstractFixAllSpanMappingService.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; @@ -37,7 +38,7 @@ private async Task>> GetF if (fixAllInContainingMember) { - return ImmutableDictionary.CreateRange([KeyValuePairUtil.Create(document, ImmutableArray.Create(decl.FullSpan))]); + return ImmutableDictionary.CreateRange([KeyValuePair.Create(document, ImmutableArray.Create(decl.FullSpan))]); } else { @@ -63,7 +64,7 @@ private async Task>> GetF } else { - return ImmutableDictionary.CreateRange([KeyValuePairUtil.Create(document, ImmutableArray.Create(decl.FullSpan))]); + return ImmutableDictionary.CreateRange([KeyValuePair.Create(document, ImmutableArray.Create(decl.FullSpan))]); } } } diff --git a/src/Workspaces/Core/Portable/LinkedFileDiffMerging/LinkedFileDiffMergingSession.cs b/src/Workspaces/Core/Portable/LinkedFileDiffMerging/LinkedFileDiffMergingSession.cs index be368ac9acf9a..240487ee59cc7 100644 --- a/src/Workspaces/Core/Portable/LinkedFileDiffMerging/LinkedFileDiffMergingSession.cs +++ b/src/Workspaces/Core/Portable/LinkedFileDiffMerging/LinkedFileDiffMergingSession.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Immutable; +using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; diff --git a/src/Workspaces/Core/Portable/Log/AbstractLogAggregator.cs b/src/Workspaces/Core/Portable/Log/AbstractLogAggregator.cs index c729fe335320a..0eeed5676ac85 100644 --- a/src/Workspaces/Core/Portable/Log/AbstractLogAggregator.cs +++ b/src/Workspaces/Core/Portable/Log/AbstractLogAggregator.cs @@ -39,7 +39,7 @@ protected AbstractLogAggregator() public void Clear() => _map.Clear(); public IEnumerator> GetEnumerator() - => _map.Select(static kvp => KeyValuePairUtil.Create((TKey)kvp.Key, kvp.Value)).GetEnumerator(); + => _map.Select(static kvp => KeyValuePair.Create((TKey)kvp.Key, kvp.Value)).GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); diff --git a/src/Workspaces/Core/Portable/Log/KeyValueLogMessage.cs b/src/Workspaces/Core/Portable/Log/KeyValueLogMessage.cs index 7f042cfff0808..f4426df0e3721 100644 --- a/src/Workspaces/Core/Portable/Log/KeyValueLogMessage.cs +++ b/src/Workspaces/Core/Portable/Log/KeyValueLogMessage.cs @@ -3,12 +3,12 @@ // See the LICENSE file in the project root for more information. using System; -using System.Diagnostics; using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.PooledObjects; -using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.Internal.Log; diff --git a/src/Workspaces/Core/Portable/Options/GlobalOptionService.cs b/src/Workspaces/Core/Portable/Options/GlobalOptionService.cs index 9bd8329165872..3a95e81589cc9 100644 --- a/src/Workspaces/Core/Portable/Options/GlobalOptionService.cs +++ b/src/Workspaces/Core/Portable/Options/GlobalOptionService.cs @@ -7,6 +7,7 @@ using System.Collections.Immutable; using System.Composition; using System.Diagnostics; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; @@ -139,7 +140,7 @@ public void SetGlobalOption(PerLanguageOption2 option, string language, T => SetGlobalOption(new OptionKey2(option, language), value); public void SetGlobalOption(OptionKey2 optionKey, object? value) - => SetGlobalOptions(OneOrMany.Create(KeyValuePairUtil.Create(optionKey, value))); + => SetGlobalOptions(OneOrMany.Create(KeyValuePair.Create(optionKey, value))); public bool SetGlobalOptions(ImmutableArray> options) => SetGlobalOptions(OneOrMany.Create(options)); diff --git a/src/Workspaces/Core/Portable/Options/ILegacyGlobalOptionsWorkspaceService.cs b/src/Workspaces/Core/Portable/Options/ILegacyGlobalOptionsWorkspaceService.cs index c5161226ff7af..5887c97a8f07d 100644 --- a/src/Workspaces/Core/Portable/Options/ILegacyGlobalOptionsWorkspaceService.cs +++ b/src/Workspaces/Core/Portable/Options/ILegacyGlobalOptionsWorkspaceService.cs @@ -13,19 +13,19 @@ namespace Microsoft.CodeAnalysis.Options; /// internal interface ILegacyGlobalOptionsWorkspaceService : IWorkspaceService { - public bool RazorUseTabs { get; } - public int RazorTabSize { get; } + bool RazorUseTabs { get; } + int RazorTabSize { get; } - public bool GenerateOverrides { get; set; } + bool GenerateOverrides { get; set; } - public bool GetGenerateEqualsAndGetHashCodeFromMembersGenerateOperators(string language); - public void SetGenerateEqualsAndGetHashCodeFromMembersGenerateOperators(string language, bool value); + bool GetGenerateEqualsAndGetHashCodeFromMembersGenerateOperators(string language); + void SetGenerateEqualsAndGetHashCodeFromMembersGenerateOperators(string language, bool value); - public bool GetGenerateEqualsAndGetHashCodeFromMembersImplementIEquatable(string language); - public void SetGenerateEqualsAndGetHashCodeFromMembersImplementIEquatable(string language, bool value); + bool GetGenerateEqualsAndGetHashCodeFromMembersImplementIEquatable(string language); + void SetGenerateEqualsAndGetHashCodeFromMembersImplementIEquatable(string language, bool value); - public bool GetGenerateConstructorFromMembersOptionsAddNullChecks(string language); - public void SetGenerateConstructorFromMembersOptionsAddNullChecks(string language, bool value); + bool GetGenerateConstructorFromMembersOptionsAddNullChecks(string language); + void SetGenerateConstructorFromMembersOptionsAddNullChecks(string language, bool value); SyntaxFormattingOptions GetSyntaxFormattingOptions(LanguageServices languageServices); } diff --git a/src/Workspaces/Core/Portable/Options/Option.cs b/src/Workspaces/Core/Portable/Options/Option.cs index e6a7bab492d7b..d92b9e31b6f4d 100644 --- a/src/Workspaces/Core/Portable/Options/Option.cs +++ b/src/Workspaces/Core/Portable/Options/Option.cs @@ -14,17 +14,17 @@ namespace Microsoft.CodeAnalysis.Options; /// public class Option : IPublicOption { - private readonly OptionDefinition _optionDefinition; + internal readonly OptionDefinition OptionDefinition; public string Feature { get; } - internal OptionGroup Group => _optionDefinition.Group; + internal OptionGroup Group => OptionDefinition.Group; public string Name { get; } - public T DefaultValue => (T)_optionDefinition.DefaultValue!; + public T DefaultValue => (T)OptionDefinition.DefaultValue!; - public Type Type => _optionDefinition.Type; + public Type Type => OptionDefinition.Type; public ImmutableArray StorageLocations { get; } @@ -71,11 +71,11 @@ internal Option( { } - internal Option(OptionDefinition optionDefinition, string feature, string name, ImmutableArray storageLocations) + internal Option(OptionDefinition optionDefinition, string feature, string name, ImmutableArray storageLocations) { Feature = feature; Name = name; - _optionDefinition = optionDefinition; + OptionDefinition = optionDefinition; StorageLocations = storageLocations; } @@ -85,13 +85,13 @@ internal Option(OptionDefinition optionDefinition, string feature, string name, IPublicOption? IOption2.PublicOption => null; - OptionDefinition IOption2.Definition => _optionDefinition; + OptionDefinition IOption2.Definition => OptionDefinition; bool IEquatable.Equals(IOption2? other) => Equals(other); public override string ToString() => this.PublicOptionDefinitionToString(); - public override int GetHashCode() => _optionDefinition.GetHashCode(); + public override int GetHashCode() => OptionDefinition.GetHashCode(); public override bool Equals(object? obj) => Equals(obj as IOption2); diff --git a/src/Workspaces/Core/Portable/Options/OptionChangedEventArgs.cs b/src/Workspaces/Core/Portable/Options/OptionChangedEventArgs.cs index 3d2381312b72a..40cd17756831f 100644 --- a/src/Workspaces/Core/Portable/Options/OptionChangedEventArgs.cs +++ b/src/Workspaces/Core/Portable/Options/OptionChangedEventArgs.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Immutable; +using System.Linq; namespace Microsoft.CodeAnalysis.Options; diff --git a/src/Workspaces/Core/Portable/Options/OptionExtensions.cs b/src/Workspaces/Core/Portable/Options/OptionExtensions.cs new file mode 100644 index 0000000000000..0f0d651f35a17 --- /dev/null +++ b/src/Workspaces/Core/Portable/Options/OptionExtensions.cs @@ -0,0 +1,32 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +#pragma warning disable RS0030 // Do not used banned APIs: Option + +using System; +using Microsoft.CodeAnalysis.Shared.Utilities; + +namespace Microsoft.CodeAnalysis.Options; + +internal static class OptionExtensions +{ + /// + /// Allows an option of one enum type to be converted to another enum type, provided that both enums share the same underlying type. + /// Useful for some cases in Roslyn where we have an existing shipped public option in the Workspace layer, and an internal option + /// in the CodeStyle layer, and we want to map between them. + /// + public static Option ConvertEnumOption(this Option option) + where TFromEnum : struct, Enum + where TToEnum : struct, Enum + { + var definition = option.OptionDefinition; + var newDefaultValue = EnumValueUtilities.ConvertEnum(definition.DefaultValue); + var newSerializer = EditorConfigValueSerializer.ConvertEnumSerializer(definition.Serializer); + + var newDefinition = new OptionDefinition( + defaultValue: newDefaultValue, newSerializer, definition.Group, definition.ConfigName, definition.StorageMapping, definition.IsEditorConfigOption); + + return new(newDefinition, option.Feature, option.Name, option.StorageLocations); + } +} diff --git a/src/Workspaces/Core/Portable/Options/SolutionOptionSet.cs b/src/Workspaces/Core/Portable/Options/SolutionOptionSet.cs index 68659ab3f5627..4401c0f3efdb9 100644 --- a/src/Workspaces/Core/Portable/Options/SolutionOptionSet.cs +++ b/src/Workspaces/Core/Portable/Options/SolutionOptionSet.cs @@ -78,8 +78,8 @@ internal override OptionSet WithChangedOptionInternal(OptionKey optionKey, objec internal (ImmutableArray> internallyDefined, ImmutableArray> externallyDefined) GetChangedOptions() { - var internallyDefined = _changedOptionKeys.Where(key => key.Option is IOption2).SelectAsArray(key => KeyValuePairUtil.Create(new OptionKey2((IOption2)key.Option, key.Language), _values[key])); - var externallyDefined = _changedOptionKeys.Where(key => key.Option is not IOption2).SelectAsArray(key => KeyValuePairUtil.Create(key, _values[key])); + var internallyDefined = _changedOptionKeys.Where(key => key.Option is IOption2).SelectAsArray(key => KeyValuePair.Create(new OptionKey2((IOption2)key.Option, key.Language), _values[key])); + var externallyDefined = _changedOptionKeys.Where(key => key.Option is not IOption2).SelectAsArray(key => KeyValuePair.Create(key, _values[key])); return (internallyDefined, externallyDefined); } } diff --git a/src/Workspaces/Core/Portable/OrganizeImports/IOrganizeImportsService.cs b/src/Workspaces/Core/Portable/OrganizeImports/IOrganizeImportsService.cs index 29add83cefc62..6d15287b6ea60 100644 --- a/src/Workspaces/Core/Portable/OrganizeImports/IOrganizeImportsService.cs +++ b/src/Workspaces/Core/Portable/OrganizeImports/IOrganizeImportsService.cs @@ -13,6 +13,7 @@ internal interface IOrganizeImportsService : ILanguageService Task OrganizeImportsAsync(Document document, OrganizeImportsOptions options, CancellationToken cancellationToken); string SortImportsDisplayStringWithAccelerator { get; } + string SortImportsDisplayStringWithoutAccelerator { get; } string SortAndRemoveUnusedImportsDisplayStringWithAccelerator { get; } } diff --git a/src/Workspaces/Core/Portable/PatternMatching/AllLowerCamelCaseMatcher.cs b/src/Workspaces/Core/Portable/PatternMatching/AllLowerCamelCaseMatcher.cs index 7924b7ef0adcc..9e631c1f83995 100644 --- a/src/Workspaces/Core/Portable/PatternMatching/AllLowerCamelCaseMatcher.cs +++ b/src/Workspaces/Core/Portable/PatternMatching/AllLowerCamelCaseMatcher.cs @@ -7,6 +7,7 @@ using System; using System.Collections.Immutable; using System.Globalization; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared; using Microsoft.CodeAnalysis.Shared.Collections; diff --git a/src/Workspaces/Core/Portable/PatternMatching/CamelCaseResult.cs b/src/Workspaces/Core/Portable/PatternMatching/CamelCaseResult.cs index 4763682e687cd..53bca79b17448 100644 --- a/src/Workspaces/Core/Portable/PatternMatching/CamelCaseResult.cs +++ b/src/Workspaces/Core/Portable/PatternMatching/CamelCaseResult.cs @@ -5,6 +5,7 @@ #nullable disable using System.Diagnostics; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; diff --git a/src/Workspaces/Core/Portable/PatternMatching/ContainerPatternMatcher.cs b/src/Workspaces/Core/Portable/PatternMatching/ContainerPatternMatcher.cs index 3e3100f55177b..45ed5e4737539 100644 --- a/src/Workspaces/Core/Portable/PatternMatching/ContainerPatternMatcher.cs +++ b/src/Workspaces/Core/Portable/PatternMatching/ContainerPatternMatcher.cs @@ -5,6 +5,7 @@ using System; using System.Globalization; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Collections; namespace Microsoft.CodeAnalysis.PatternMatching; diff --git a/src/Workspaces/Core/Portable/PatternMatching/PatternMatcher.TextChunk.cs b/src/Workspaces/Core/Portable/PatternMatching/PatternMatcher.TextChunk.cs index d00c5e73b1ee2..8d51d52bee1da 100644 --- a/src/Workspaces/Core/Portable/PatternMatching/PatternMatcher.TextChunk.cs +++ b/src/Workspaces/Core/Portable/PatternMatching/PatternMatcher.TextChunk.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; diff --git a/src/Workspaces/Core/Portable/PatternMatching/PatternMatcher.cs b/src/Workspaces/Core/Portable/PatternMatching/PatternMatcher.cs index 96c74e0f71db9..f2d2537328621 100644 --- a/src/Workspaces/Core/Portable/PatternMatching/PatternMatcher.cs +++ b/src/Workspaces/Core/Portable/PatternMatching/PatternMatcher.cs @@ -7,6 +7,7 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Utilities; diff --git a/src/Workspaces/Core/Portable/PatternMatching/PatternMatcherExtensions.cs b/src/Workspaces/Core/Portable/PatternMatching/PatternMatcherExtensions.cs index 4a84ecfd62499..cb4d669c21cf1 100644 --- a/src/Workspaces/Core/Portable/PatternMatching/PatternMatcherExtensions.cs +++ b/src/Workspaces/Core/Portable/PatternMatching/PatternMatcherExtensions.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Collections; namespace Microsoft.CodeAnalysis.PatternMatching; diff --git a/src/Workspaces/Core/Portable/PatternMatching/SimplePatternMatcher.cs b/src/Workspaces/Core/Portable/PatternMatching/SimplePatternMatcher.cs index 32e0b1c2d0c39..df6028079c652 100644 --- a/src/Workspaces/Core/Portable/PatternMatching/SimplePatternMatcher.cs +++ b/src/Workspaces/Core/Portable/PatternMatching/SimplePatternMatcher.cs @@ -5,6 +5,7 @@ #nullable disable using System.Globalization; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Collections; namespace Microsoft.CodeAnalysis.PatternMatching; diff --git a/src/Workspaces/Core/Portable/PublicAPI.Unshipped.txt b/src/Workspaces/Core/Portable/PublicAPI.Unshipped.txt index 1b7b7865e52fd..a0961d4c58c45 100644 --- a/src/Workspaces/Core/Portable/PublicAPI.Unshipped.txt +++ b/src/Workspaces/Core/Portable/PublicAPI.Unshipped.txt @@ -1,6 +1,5 @@ *REMOVED*abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithModifiers(Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers) -> Microsoft.CodeAnalysis.SyntaxNode Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithModifiers(Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers) -> Microsoft.CodeAnalysis.SyntaxNode - Microsoft.CodeAnalysis.Editing.OperatorKind.AdditionAssignment = 27 -> Microsoft.CodeAnalysis.Editing.OperatorKind Microsoft.CodeAnalysis.Editing.OperatorKind.BitwiseAndAssignment = 33 -> Microsoft.CodeAnalysis.Editing.OperatorKind Microsoft.CodeAnalysis.Editing.OperatorKind.BitwiseOrAssignment = 34 -> Microsoft.CodeAnalysis.Editing.OperatorKind @@ -11,4 +10,28 @@ Microsoft.CodeAnalysis.Editing.OperatorKind.ModulusAssignment = 31 -> Microsoft. Microsoft.CodeAnalysis.Editing.OperatorKind.MultiplicationAssignment = 29 -> Microsoft.CodeAnalysis.Editing.OperatorKind Microsoft.CodeAnalysis.Editing.OperatorKind.RightShiftAssignment = 36 -> Microsoft.CodeAnalysis.Editing.OperatorKind Microsoft.CodeAnalysis.Editing.OperatorKind.SubtractionAssignment = 28 -> Microsoft.CodeAnalysis.Editing.OperatorKind -Microsoft.CodeAnalysis.Editing.OperatorKind.UnsignedRightShiftAssignment = 37 -> Microsoft.CodeAnalysis.Editing.OperatorKind \ No newline at end of file +Microsoft.CodeAnalysis.Editing.OperatorKind.UnsignedRightShiftAssignment = 37 -> Microsoft.CodeAnalysis.Editing.OperatorKind +Microsoft.CodeAnalysis.Workspace.RegisterDocumentActiveContextChangedHandler(System.Action handler, Microsoft.CodeAnalysis.WorkspaceEventOptions? options = null) -> Microsoft.CodeAnalysis.WorkspaceEventRegistration +Microsoft.CodeAnalysis.Workspace.RegisterDocumentClosedHandler(System.Action handler, Microsoft.CodeAnalysis.WorkspaceEventOptions? options = null) -> Microsoft.CodeAnalysis.WorkspaceEventRegistration +Microsoft.CodeAnalysis.Workspace.RegisterDocumentOpenedHandler(System.Action handler, Microsoft.CodeAnalysis.WorkspaceEventOptions? options = null) -> Microsoft.CodeAnalysis.WorkspaceEventRegistration +Microsoft.CodeAnalysis.Workspace.RegisterTextDocumentClosedHandler(System.Action handler, Microsoft.CodeAnalysis.WorkspaceEventOptions? options = null) -> Microsoft.CodeAnalysis.WorkspaceEventRegistration +Microsoft.CodeAnalysis.Workspace.RegisterTextDocumentOpenedHandler(System.Action handler, Microsoft.CodeAnalysis.WorkspaceEventOptions? options = null) -> Microsoft.CodeAnalysis.WorkspaceEventRegistration +Microsoft.CodeAnalysis.Workspace.RegisterWorkspaceChangedHandler(System.Action handler, Microsoft.CodeAnalysis.WorkspaceEventOptions? options = null) -> Microsoft.CodeAnalysis.WorkspaceEventRegistration +Microsoft.CodeAnalysis.Workspace.RegisterWorkspaceChangedImmediateHandler(System.Action handler, Microsoft.CodeAnalysis.WorkspaceEventOptions? options = null) -> Microsoft.CodeAnalysis.WorkspaceEventRegistration +Microsoft.CodeAnalysis.Workspace.RegisterWorkspaceFailedHandler(System.Action handler, Microsoft.CodeAnalysis.WorkspaceEventOptions? options = null) -> Microsoft.CodeAnalysis.WorkspaceEventRegistration +Microsoft.CodeAnalysis.WorkspaceEventOptions +Microsoft.CodeAnalysis.WorkspaceEventOptions.Deconstruct(out bool RequiresMainThread) -> void +Microsoft.CodeAnalysis.WorkspaceEventOptions.Equals(Microsoft.CodeAnalysis.WorkspaceEventOptions other) -> bool +Microsoft.CodeAnalysis.WorkspaceEventOptions.RequiresMainThread.get -> bool +Microsoft.CodeAnalysis.WorkspaceEventOptions.RequiresMainThread.set -> void +Microsoft.CodeAnalysis.WorkspaceEventOptions.WorkspaceEventOptions() -> void +Microsoft.CodeAnalysis.WorkspaceEventOptions.WorkspaceEventOptions(bool RequiresMainThread) -> void +Microsoft.CodeAnalysis.WorkspaceEventRegistration +Microsoft.CodeAnalysis.WorkspaceEventRegistration.Dispose() -> void +override Microsoft.CodeAnalysis.WorkspaceEventOptions.Equals(object obj) -> bool +override Microsoft.CodeAnalysis.WorkspaceEventOptions.GetHashCode() -> int +override Microsoft.CodeAnalysis.WorkspaceEventOptions.ToString() -> string +static Microsoft.CodeAnalysis.WorkspaceEventOptions.operator !=(Microsoft.CodeAnalysis.WorkspaceEventOptions left, Microsoft.CodeAnalysis.WorkspaceEventOptions right) -> bool +static Microsoft.CodeAnalysis.WorkspaceEventOptions.operator ==(Microsoft.CodeAnalysis.WorkspaceEventOptions left, Microsoft.CodeAnalysis.WorkspaceEventOptions right) -> bool +static readonly Microsoft.CodeAnalysis.WorkspaceEventOptions.DefaultOptions -> Microsoft.CodeAnalysis.WorkspaceEventOptions +static readonly Microsoft.CodeAnalysis.WorkspaceEventOptions.RequiresMainThreadOptions -> Microsoft.CodeAnalysis.WorkspaceEventOptions \ No newline at end of file diff --git a/src/Workspaces/Core/Portable/Remote/RemoteHostClient.cs b/src/Workspaces/Core/Portable/Remote/RemoteHostClient.cs index 0c51bf0d12c80..54846ba331e66 100644 --- a/src/Workspaces/Core/Portable/Remote/RemoteHostClient.cs +++ b/src/Workspaces/Core/Portable/Remote/RemoteHostClient.cs @@ -5,8 +5,8 @@ using System; using System.Threading; using System.Threading.Tasks; -using Roslyn.Utilities; using Microsoft.CodeAnalysis.Host; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote; diff --git a/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.Session.cs b/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.Session.cs index bd3a117b5cc92..abd64f62bbcc3 100644 --- a/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.Session.cs +++ b/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.Session.cs @@ -106,7 +106,8 @@ public async Task ResolveConflictsAsync() _replacementTextValid = IsIdentifierValid_Worker(baseSolution, _replacementText, documentsGroupedByTopologicallySortedProjectId.Select(g => g.Key)); var renamedSpansTracker = new RenamedSpansTracker(); - var conflictResolution = new MutableConflictResolution(baseSolution, renamedSpansTracker, _replacementText, _replacementTextValid); + var conflictResolution = new MutableConflictResolution( + baseSolution, renamedSpansTracker, _replacementText, _replacementTextValid, this.RenameOptions); var intermediateSolution = conflictResolution.OldSolution; foreach (var documentsByProject in documentsGroupedByTopologicallySortedProjectId) @@ -133,7 +134,7 @@ public async Task ResolveConflictsAsync() // 3. Through the whole process we maintain a map of the oldspan to newspan. In case of expansion & rename, we map the expanded node and the renamed token conflictResolution.UpdateCurrentSolution(await AnnotateAndRename_WorkerAsync( baseSolution, - conflictResolution.CurrentSolution, + conflictResolution, documentIdsThatGetsAnnotatedAndRenamed, _renameLocationSet.Locations, renamedSpansTracker, @@ -199,7 +200,8 @@ .. conflictResolution.RelatedLocations } // Step 3: Simplify the project - conflictResolution.UpdateCurrentSolution(await renamedSpansTracker.SimplifyAsync(conflictResolution.CurrentSolution, documentsByProject, _replacementTextValid, _renameAnnotations, _cancellationToken).ConfigureAwait(false)); + conflictResolution.UpdateCurrentSolution(await renamedSpansTracker.SimplifyAsync( + conflictResolution.CurrentSolution, documentsByProject, _replacementTextValid, _renameAnnotations, this.RenameOptions, _cancellationToken).ConfigureAwait(false)); intermediateSolution = await conflictResolution.RemoveAllRenameAnnotationsAsync( intermediateSolution, documentsByProject, _renameAnnotations, _cancellationToken).ConfigureAwait(false); conflictResolution.UpdateCurrentSolution(intermediateSolution); @@ -211,11 +213,14 @@ .. conflictResolution.RelatedLocations if (IsRenameValid(conflictResolution, renamedSymbolInNewSolution)) { + var declarationDocument = await conflictResolution.CurrentSolution.GetRequiredDocumentAsync( + _documentIdOfRenameSymbolDeclaration, RenameOptions.RenameInSourceGeneratedDocuments, _cancellationToken).ConfigureAwait(false); + var semanticModel = await declarationDocument.GetRequiredSemanticModelAsync(_cancellationToken).ConfigureAwait(false); await AddImplicitConflictsAsync( renamedSymbolInNewSolution, _renameLocationSet.Symbol, _renameLocationSet.ImplicitLocations, - await conflictResolution.CurrentSolution.GetRequiredDocument(_documentIdOfRenameSymbolDeclaration).GetRequiredSemanticModelAsync(_cancellationToken).ConfigureAwait(false), + semanticModel, _renameSymbolDeclarationLocation, renamedSpansTracker.GetAdjustedPosition(_renameSymbolDeclarationLocation.SourceSpan.Start, _documentIdOfRenameSymbolDeclaration), conflictResolution, @@ -266,7 +271,8 @@ private async Task DebugVerifyNoErrorsAsync(MutableConflictResolution conflictRe foreach (var documentId in documents) { // remember if there were issues in the document prior to renaming it. - var originalDoc = conflictResolution.OldSolution.GetRequiredDocument(documentId); + var originalDoc = await conflictResolution.OldSolution.GetRequiredDocumentAsync( + documentId, RenameOptions.RenameInSourceGeneratedDocuments, _cancellationToken).ConfigureAwait(false); documentIdErrorStateLookup.Add(documentId, await originalDoc.HasAnyErrorsAsync(_cancellationToken).ConfigureAwait(false)); } @@ -288,7 +294,9 @@ private async Task DebugVerifyNoErrorsAsync(MutableConflictResolution conflictRe // errors. if (!documentIdErrorStateLookup[documentId] && _nonConflictSymbolKeys.IsDefault) { - await conflictResolution.CurrentSolution.GetRequiredDocument(documentId).VerifyNoErrorsAsync("Rename introduced errors in error-free code", _cancellationToken, ignoreErrorCodes).ConfigureAwait(false); + var changeDoc = await conflictResolution.CurrentSolution.GetRequiredDocumentAsync( + documentId, RenameOptions.RenameInSourceGeneratedDocuments, _cancellationToken).ConfigureAwait(false); + await changeDoc.VerifyNoErrorsAsync("Rename introduced errors in error-free code", _cancellationToken, ignoreErrorCodes).ConfigureAwait(false); } } } @@ -345,9 +353,11 @@ private async Task IdentifyConflictsAsync( foreach (var documentId in documentIdsForConflictResolution) { - var newDocument = conflictResolution.CurrentSolution.GetRequiredDocument(documentId); + var newDocument = await conflictResolution.CurrentSolution.GetRequiredDocumentAsync( + documentId, RenameOptions.RenameInSourceGeneratedDocuments, _cancellationToken).ConfigureAwait(false); var syntaxRoot = await newDocument.GetRequiredSyntaxRootAsync(_cancellationToken).ConfigureAwait(false); - var baseDocument = conflictResolution.OldSolution.GetRequiredDocument(documentId); + var baseDocument = await conflictResolution.OldSolution.GetRequiredDocumentAsync( + documentId, RenameOptions.RenameInSourceGeneratedDocuments, _cancellationToken).ConfigureAwait(false); var baseSyntaxTree = await baseDocument.GetRequiredSyntaxTreeAsync(_cancellationToken).ConfigureAwait(false); var baseRoot = await baseDocument.GetRequiredSyntaxRootAsync(_cancellationToken).ConfigureAwait(false); SemanticModel? newDocumentSemanticModel = null; @@ -454,7 +464,7 @@ private async Task IdentifyConflictsAsync( var referencedSymbols = _renameLocationSet.ReferencedSymbols; var renameSymbol = _renameLocationSet.Symbol; await AddDeclarationConflictsAsync( - renamedSymbolInNewSolution, renameSymbol, referencedSymbols, conflictResolution, reverseMappedLocations, _cancellationToken).ConfigureAwait(false); + projectId, renamedSymbolInNewSolution, renameSymbol, referencedSymbols, conflictResolution, reverseMappedLocations, _cancellationToken).ConfigureAwait(false); } return conflictResolution.RelatedLocations.Any(r => r.Type == RelatedLocationType.PossiblyResolvableConflict); @@ -681,7 +691,8 @@ private async Task GetRenamedSymbolInCurrentSolutionAsync(MutableConfli ? conflictResolution.GetAdjustedTokenStartingPosition(_renameSymbolDeclarationLocation.SourceSpan.Start, _documentIdOfRenameSymbolDeclaration) : _renameSymbolDeclarationLocation.SourceSpan.Start; - var document = conflictResolution.CurrentSolution.GetRequiredDocument(_documentIdOfRenameSymbolDeclaration); + var document = await conflictResolution.CurrentSolution.GetRequiredDocumentAsync( + _documentIdOfRenameSymbolDeclaration, RenameOptions.RenameInSourceGeneratedDocuments, _cancellationToken).ConfigureAwait(false); var newSymbol = await SymbolFinder.FindSymbolAtPositionAsync(document, start, cancellationToken: _cancellationToken).ConfigureAwait(false); return newSymbol; } @@ -773,7 +784,7 @@ private async Task AddDocumentsWithPotentialConflictsAsync( // The rename process and annotation for the bookkeeping is performed in one-step private async Task AnnotateAndRename_WorkerAsync( Solution originalSolution, - Solution partiallyRenamedSolution, + MutableConflictResolution conflictResolution, HashSet documentIdsToRename, ImmutableArray renameLocations, RenamedSpansTracker renameSpansTracker, @@ -783,11 +794,14 @@ private async Task AnnotateAndRename_WorkerAsync( { try { + var partiallyRenamedSolution = conflictResolution.CurrentSolution; + foreach (var documentId in documentIdsToRename.ToList()) { _cancellationToken.ThrowIfCancellationRequested(); - var document = originalSolution.GetRequiredDocument(documentId); + var document = await originalSolution.GetRequiredDocumentAsync( + documentId, RenameOptions.RenameInSourceGeneratedDocuments, _cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetRequiredSemanticModelAsync(_cancellationToken).ConfigureAwait(false); var originalSyntaxRoot = await semanticModel.SyntaxTree.GetRootAsync(_cancellationToken).ConfigureAwait(false); @@ -842,7 +856,7 @@ private async Task AnnotateAndRename_WorkerAsync( } else { - partiallyRenamedSolution = partiallyRenamedSolution.WithDocumentSyntaxRoot(documentId, newRoot, PreservationMode.PreserveIdentity); + partiallyRenamedSolution = await conflictResolution.WithDocumentSyntaxRootAsync(partiallyRenamedSolution, documentId, newRoot, _cancellationToken).ConfigureAwait(false); } } diff --git a/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.cs b/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.cs index 7d4ab01b204a6..d4a2a4a81d33c 100644 --- a/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.cs +++ b/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.cs @@ -225,6 +225,7 @@ private static async Task AddImplicitConflictsAsync( /// perspective of find all references), but we still need to track it. /// private static async Task AddDeclarationConflictsAsync( + ProjectId projectId, ISymbol renamedSymbol, ISymbol renameSymbol, IEnumerable referencedSymbols, @@ -234,7 +235,7 @@ private static async Task AddDeclarationConflictsAsync( { try { - var projectOpt = conflictResolution.CurrentSolution.GetProject(renamedSymbol.ContainingAssembly, cancellationToken); + var projectOpt = conflictResolution.CurrentSolution.GetProject(projectId); if (renamedSymbol.ContainingSymbol.IsKind(SymbolKind.NamedType)) { Contract.ThrowIfNull(projectOpt); diff --git a/src/Workspaces/Core/Portable/Rename/ConflictEngine/MutableConflictResolution.cs b/src/Workspaces/Core/Portable/Rename/ConflictEngine/MutableConflictResolution.cs index 640060742c13f..f2abbbc1e9613 100644 --- a/src/Workspaces/Core/Portable/Rename/ConflictEngine/MutableConflictResolution.cs +++ b/src/Workspaces/Core/Portable/Rename/ConflictEngine/MutableConflictResolution.cs @@ -22,9 +22,9 @@ internal sealed class MutableConflictResolution( Solution oldSolution, RenamedSpansTracker renamedSpansTracker, string replacementText, - bool replacementTextValid) + bool replacementTextValid, + SymbolRenameOptions options) { - // List of All the Locations that were renamed and conflict-complexified public readonly List RelatedLocations = []; @@ -49,6 +49,8 @@ internal sealed class MutableConflictResolution( /// public Solution CurrentSolution { get; private set; } = oldSolution; + private readonly SymbolRenameOptions _options = options; + private (DocumentId documentId, string newName) _renamedDocument; internal void ClearDocuments(IEnumerable conflictLocationDocumentIds) @@ -70,7 +72,8 @@ internal async Task RemoveAllRenameAnnotationsAsync( { if (renamedSpansTracker.IsDocumentChanged(documentId)) { - var document = CurrentSolution.GetRequiredDocument(documentId); + var document = await CurrentSolution.GetRequiredDocumentAsync( + documentId, _options.RenameInSourceGeneratedDocuments, cancellationToken).ConfigureAwait(false); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // For the computeReplacementToken and computeReplacementNode functions, use @@ -83,7 +86,7 @@ internal async Task RemoveAllRenameAnnotationsAsync( trivia: [], computeReplacementTrivia: null); - intermediateSolution = intermediateSolution.WithDocumentSyntaxRoot(documentId, newRoot, PreservationMode.PreserveIdentity); + intermediateSolution = await WithDocumentSyntaxRootAsync(intermediateSolution, documentId, newRoot, cancellationToken).ConfigureAwait(false); } } @@ -164,4 +167,27 @@ public ConflictResolution ToConflictResolution() documentToComplexifiedSpansMap, documentToRelatedLocationsMap); } + + /// + /// Updates the syntax root of a document in the solution with a new syntax root. + /// + /// + /// This method specifically is used to handle source generated documents, when that option is on, which need some extra + /// work before calling the normal WithDocumentSyntaxRoot method. If the option is not set, there should be no source generated + /// documents, and the method will complete synchronously. + /// + internal async ValueTask WithDocumentSyntaxRootAsync(Solution solution, DocumentId documentId, SyntaxNode newRoot, CancellationToken cancellationToken) + { + // In a source generated document, we have to ensure we've realized the "old" tree in the modified solution or WithDocumentSyntaxRoot + // won't work. Performing a rename in a source generated document is opt-in, so we can assume that we only hit this condition in + // scenarios that wanted it. + if (documentId.IsSourceGenerated) + { + Contract.ThrowIfFalse(_options.RenameInSourceGeneratedDocuments); + + _ = await solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: _options.RenameInSourceGeneratedDocuments, cancellationToken).ConfigureAwait(false); + } + + return solution.WithDocumentSyntaxRoot(documentId, newRoot, PreservationMode.PreserveIdentity); + } } diff --git a/src/Workspaces/Core/Portable/Rename/ConflictEngine/RenamedSpansTracker.cs b/src/Workspaces/Core/Portable/Rename/ConflictEngine/RenamedSpansTracker.cs index bd829afbeb303..93df9e4b58822 100644 --- a/src/Workspaces/Core/Portable/Rename/ConflictEngine/RenamedSpansTracker.cs +++ b/src/Workspaces/Core/Portable/Rename/ConflictEngine/RenamedSpansTracker.cs @@ -143,13 +143,22 @@ public IEnumerable DocumentIds } } - internal async Task SimplifyAsync(Solution solution, IEnumerable documentIds, bool replacementTextValid, AnnotationTable renameAnnotations, CancellationToken cancellationToken) + internal async Task SimplifyAsync( + Solution solution, + IEnumerable documentIds, + bool replacementTextValid, + AnnotationTable renameAnnotations, + SymbolRenameOptions options, + CancellationToken cancellationToken) { foreach (var documentId in documentIds) { if (this.IsDocumentChanged(documentId)) { - var document = solution.GetRequiredDocument(documentId); + // It's possible that rename will have found locations in generated documents, so we have to make sure to allow that. We assume that the + // entry point to rename will only process source generated documents if it needed to. + var document = await solution.GetRequiredDocumentAsync( + documentId, options.RenameInSourceGeneratedDocuments, cancellationToken).ConfigureAwait(false); if (replacementTextValid) { diff --git a/src/Workspaces/Core/Portable/Rename/RenameOptions.cs b/src/Workspaces/Core/Portable/Rename/RenameOptions.cs index 8ed3222cdbfa2..5e4c859135b23 100644 --- a/src/Workspaces/Core/Portable/Rename/RenameOptions.cs +++ b/src/Workspaces/Core/Portable/Rename/RenameOptions.cs @@ -34,7 +34,22 @@ public readonly record struct SymbolRenameOptions( [property: DataMember(Order = 0)] bool RenameOverloads = false, [property: DataMember(Order = 1)] bool RenameInStrings = false, [property: DataMember(Order = 2)] bool RenameInComments = false, - [property: DataMember(Order = 3)] bool RenameFile = false); + [property: DataMember(Order = 3)] bool RenameFile = false) +{ + internal SymbolRenameOptions( + bool renameOverloads, + bool renameInStrings, + bool renameInComments, + bool renameFile, + bool renameInSourceGeneratedDocuments) + : this(renameOverloads, renameInStrings, renameInComments, renameFile) + { + RenameInSourceGeneratedDocuments = renameInSourceGeneratedDocuments; + } + + [DataMember(Order = 4)] + internal bool RenameInSourceGeneratedDocuments { get; init; } = false; +} /// /// Options for renaming a document. diff --git a/src/Workspaces/Core/Portable/Rename/Renamer.RenameSymbolDocumentAction.cs b/src/Workspaces/Core/Portable/Rename/Renamer.RenameSymbolDocumentAction.cs index 2001a1f5b6ce8..196d3c6210efc 100644 --- a/src/Workspaces/Core/Portable/Rename/Renamer.RenameSymbolDocumentAction.cs +++ b/src/Workspaces/Core/Portable/Rename/Renamer.RenameSymbolDocumentAction.cs @@ -3,11 +3,11 @@ // See the LICENSE file in the project root for more information. using System.Globalization; +using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Shared.Extensions; -using System.Linq; using Microsoft.CodeAnalysis.Utilities; namespace Microsoft.CodeAnalysis.Rename; diff --git a/src/Workspaces/Core/Portable/Rename/SymbolicRenameLocations.ReferenceProcessing.cs b/src/Workspaces/Core/Portable/Rename/SymbolicRenameLocations.ReferenceProcessing.cs index 38cc6276c93c3..e7a6295685706 100644 --- a/src/Workspaces/Core/Portable/Rename/SymbolicRenameLocations.ReferenceProcessing.cs +++ b/src/Workspaces/Core/Portable/Rename/SymbolicRenameLocations.ReferenceProcessing.cs @@ -158,7 +158,7 @@ private static string TrimNameToAfterLastDot(string name) /// Given a ISymbol, returns the renameable locations for a given symbol. /// public static async Task> GetRenamableDefinitionLocationsAsync( - ISymbol referencedSymbol, ISymbol originalSymbol, Solution solution, CancellationToken cancellationToken) + ISymbol referencedSymbol, ISymbol originalSymbol, Solution solution, SymbolRenameOptions options, CancellationToken cancellationToken) { var shouldIncludeSymbol = await ShouldIncludeSymbolAsync(referencedSymbol, originalSymbol, solution, false, cancellationToken).ConfigureAwait(false); if (!shouldIncludeSymbol) @@ -173,7 +173,7 @@ public static async Task> GetRenamableDefinitionL return []; } - var results = ArrayBuilder.GetInstance(); + using var _ = ArrayBuilder.GetInstance(out var results); // If the original symbol was an alias, then the definitions will just be the // location of the alias, always @@ -181,7 +181,7 @@ public static async Task> GetRenamableDefinitionL { var location = originalSymbol.Locations.Single(); AddRenameLocationIfNotGenerated(location); - return results.ToImmutableAndFree(); + return results.ToImmutableAndClear(); } var isRenamableAccessor = await IsPropertyAccessorOrAnOverrideAsync(referencedSymbol, solution, cancellationToken).ConfigureAwait(false); @@ -226,7 +226,7 @@ public static async Task> GetRenamableDefinitionL } } - return results.ToImmutableAndFree(); + return results.ToImmutableAndClear(); void AddRenameLocationIfNotGenerated(Location location, bool isRenamableAccessor = false) { @@ -236,16 +236,17 @@ void AddRenameLocationIfNotGenerated(Location location, bool isRenamableAccessor // If the location is in a source generated file, we won't rename it. Our assumption in this case is we // have cascaded to this symbol from our original source symbol, and the generator will update this file // based on the renamed symbol. - if (document is not SourceGeneratedDocument) + if (options.RenameInSourceGeneratedDocuments || document is not SourceGeneratedDocument) results.Add(new RenameLocation(location, document.Id, isRenamableAccessor: isRenamableAccessor)); } } - internal static async Task> GetRenamableReferenceLocationsAsync(ISymbol referencedSymbol, ISymbol originalSymbol, ReferenceLocation location, Solution solution, CancellationToken cancellationToken) + internal static async Task> GetRenamableReferenceLocationsAsync( + ISymbol referencedSymbol, ISymbol originalSymbol, ReferenceLocation location, Solution solution, SymbolRenameOptions options, CancellationToken cancellationToken) { // We won't try to update references in source generated files; we'll assume the generator will rerun // and produce an updated document with the new name. - if (location.Document is SourceGeneratedDocument) + if (!options.RenameInSourceGeneratedDocuments && location.Document is SourceGeneratedDocument) return []; var shouldIncludeSymbol = await ShouldIncludeSymbolAsync(referencedSymbol, originalSymbol, solution, true, cancellationToken).ConfigureAwait(false); @@ -282,7 +283,11 @@ internal static async Task> GetRenamableReferenceLoc // rather than a whole namespace of stuff. if (location.Alias != null) { - if (location.Alias.Name == referencedSymbol.Name) + var referencedSymbolName = referencedSymbol is IMethodSymbol { MethodKind: MethodKind.Constructor } constructorSymbol + ? constructorSymbol.ContainingType.Name + : referencedSymbol.Name; + + if (location.Alias.Name == referencedSymbolName) { results.Add(new RenameLocation(location.Location, location.Document.Id, candidateReason: location.CandidateReason, isRenamableAliasUsage: true, isWrittenTo: location.IsWrittenTo)); diff --git a/src/Workspaces/Core/Portable/Rename/SymbolicRenameLocations.cs b/src/Workspaces/Core/Portable/Rename/SymbolicRenameLocations.cs index 6c3440d1a04d1..44feed9b4d376 100644 --- a/src/Workspaces/Core/Portable/Rename/SymbolicRenameLocations.cs +++ b/src/Workspaces/Core/Portable/Rename/SymbolicRenameLocations.cs @@ -63,10 +63,10 @@ public static async Task FindLocationsInCurrentProcessA symbol = await RenameUtilities.FindDefinitionSymbolAsync(symbol, solution, cancellationToken).ConfigureAwait(false); // First, find the direct references just to the symbol being renamed. - var originalSymbolResult = await AddLocationsReferenceSymbolsAsync(symbol, solution, cancellationToken).ConfigureAwait(false); + var originalSymbolResult = await AddLocationsReferenceSymbolsAsync(symbol, solution, options, cancellationToken).ConfigureAwait(false); // Next, find references to overloads, if the user has asked to rename those as well. - var overloadsResult = options.RenameOverloads ? await GetOverloadsAsync(symbol, solution, cancellationToken).ConfigureAwait(false) : + var overloadsResult = options.RenameOverloads ? await GetOverloadsAsync(symbol, solution, options, cancellationToken).ConfigureAwait(false) : []; // Finally, include strings/comments if that's what the user wants. @@ -111,12 +111,12 @@ public static async Task FindLocationsInCurrentProcessA } private static async Task> GetOverloadsAsync( - ISymbol symbol, Solution solution, CancellationToken cancellationToken) + ISymbol symbol, Solution solution, SymbolRenameOptions options, CancellationToken cancellationToken) { using var _ = ArrayBuilder.GetInstance(out var overloadsResult); foreach (var overloadedSymbol in RenameUtilities.GetOverloadedSymbols(symbol)) - overloadsResult.Add(await AddLocationsReferenceSymbolsAsync(overloadedSymbol, solution, cancellationToken).ConfigureAwait(false)); + overloadsResult.Add(await AddLocationsReferenceSymbolsAsync(overloadedSymbol, solution, options, cancellationToken).ConfigureAwait(false)); return overloadsResult.ToImmutableAndClear(); } @@ -124,6 +124,7 @@ private static async Task> GetOverloadsAsync( private static async Task AddLocationsReferenceSymbolsAsync( ISymbol symbol, Solution solution, + SymbolRenameOptions options, CancellationToken cancellationToken) { var locations = ImmutableHashSet.CreateBuilder(); @@ -133,11 +134,12 @@ private static async Task AddLocationsReferenceSymbolsAsync( foreach (var referencedSymbol in referenceSymbols) { locations.AddAll( - await ReferenceProcessing.GetRenamableDefinitionLocationsAsync(referencedSymbol.Definition, symbol, solution, cancellationToken).ConfigureAwait(false)); + await ReferenceProcessing.GetRenamableDefinitionLocationsAsync(referencedSymbol.Definition, symbol, solution, options, cancellationToken).ConfigureAwait(false)); locations.AddAll( await referencedSymbol.Locations.SelectManyInParallelAsync( - (l, c) => ReferenceProcessing.GetRenamableReferenceLocationsAsync(referencedSymbol.Definition, symbol, l, solution, c), + (l, c) => ReferenceProcessing.GetRenamableReferenceLocationsAsync( + referencedSymbol.Definition, symbol, l, solution, options, c), cancellationToken).ConfigureAwait(false)); } diff --git a/src/Workspaces/Core/Portable/Serialization/AbstractOptionsSerializationService.cs b/src/Workspaces/Core/Portable/Serialization/AbstractOptionsSerializationService.cs index 3bc9a229e7357..302a645646c24 100644 --- a/src/Workspaces/Core/Portable/Serialization/AbstractOptionsSerializationService.cs +++ b/src/Workspaces/Core/Portable/Serialization/AbstractOptionsSerializationService.cs @@ -142,7 +142,7 @@ protected static ( var key = reader.ReadString(); var value = (ReportDiagnostic)reader.ReadInt32(); - specificDiagnosticOptionsList.Add(KeyValuePairUtil.Create(key, value)); + specificDiagnosticOptionsList.Add(KeyValuePair.Create(key, value)); } } @@ -228,7 +228,7 @@ protected static (SourceCodeKind kind, DocumentationMode documentationMode, IEnu var key = reader.ReadString(); var value = reader.ReadString(); - featuresList.Add(KeyValuePairUtil.Create(key, value)); + featuresList.Add(KeyValuePair.Create(key, value)); } } diff --git a/src/Workspaces/Core/Portable/Shared/Extensions/ILanguageMetadataExtensions.cs b/src/Workspaces/Core/Portable/Shared/Extensions/ILanguageMetadataExtensions.cs index fbc0e1b339f68..e4376a18de6b0 100644 --- a/src/Workspaces/Core/Portable/Shared/Extensions/ILanguageMetadataExtensions.cs +++ b/src/Workspaces/Core/Portable/Shared/Extensions/ILanguageMetadataExtensions.cs @@ -38,7 +38,7 @@ public static ImmutableDictionary KeyValuePairUtil.Create(kvp.Key, kvp.Value.ToImmutableAndFree())).ToImmutableDictionary(); + return builder.Select(kvp => KeyValuePair.Create(kvp.Key, kvp.Value.ToImmutableAndFree())).ToImmutableDictionary(); } public static ImmutableDictionary>> ToPerLanguageMapWithMultipleLanguages(this IEnumerable> services) diff --git a/src/Workspaces/Core/Portable/Shared/Extensions/SourceTextExtensions.cs b/src/Workspaces/Core/Portable/Shared/Extensions/SourceTextExtensions.cs index 5ba3bca4346bd..2ea96a1626d14 100644 --- a/src/Workspaces/Core/Portable/Shared/Extensions/SourceTextExtensions.cs +++ b/src/Workspaces/Core/Portable/Shared/Extensions/SourceTextExtensions.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Immutable; using System.IO; +using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Host; diff --git a/src/Workspaces/Core/Portable/Shared/Extensions/SyntaxGeneratorExtensions.cs b/src/Workspaces/Core/Portable/Shared/Extensions/SyntaxGeneratorExtensions.cs index 643ba4c58dfc5..1e479fb429b48 100644 --- a/src/Workspaces/Core/Portable/Shared/Extensions/SyntaxGeneratorExtensions.cs +++ b/src/Workspaces/Core/Portable/Shared/Extensions/SyntaxGeneratorExtensions.cs @@ -25,7 +25,7 @@ public static IMethodSymbol CreateBaseDelegatingConstructor( return CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default, accessibility: Accessibility.Public, - modifiers: new DeclarationModifiers(), + modifiers: DeclarationModifiers.None, typeName: typeName, parameters: constructor.Parameters, statements: default, diff --git a/src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListener.cs b/src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListener.cs index 174d252614bbc..ed0dfbf53b914 100644 --- a/src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListener.cs +++ b/src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListener.cs @@ -22,7 +22,6 @@ internal sealed partial class AsynchronousOperationListener : IAsynchronousOpera private List _diagnosticTokenList = []; private int _counter; - private bool _trackActiveTokens; public AsynchronousOperationListener() : this(featureName: "noname", enableDiagnosticTokens: false) @@ -94,7 +93,7 @@ public IAsyncToken BeginAsyncOperation(string name, object? tag = null, [CallerF using (_gate.DisposableWait(CancellationToken.None)) { IAsyncToken asyncToken; - if (_trackActiveTokens) + if (TrackActiveTokens) { var token = new DiagnosticAsyncToken(this, name, tag, filePath, lineNumber); _diagnosticTokenList.Add(token); @@ -134,7 +133,7 @@ private void Decrement_NoLock(AsyncToken token) oldSource.Dispose(); } - if (_trackActiveTokens) + if (TrackActiveTokens) { var i = 0; var removed = false; @@ -197,17 +196,17 @@ public async Task WaitUntilConditionIsMetAsync(Func /// Event data to be sent /// Optional parameter used to determine whether to send the telemetry event (in milliseconds) - public IDisposable? LogBlockTime(KeyValueLogMessage logMessage, int minThresholdMs = -1); + IDisposable? LogBlockTime(KeyValueLogMessage logMessage, int minThresholdMs = -1); } diff --git a/src/Workspaces/Core/Portable/Telemetry/ITelemetryLog.cs b/src/Workspaces/Core/Portable/Telemetry/ITelemetryLog.cs index c96bba2b4bb39..147c2c916a0ef 100644 --- a/src/Workspaces/Core/Portable/Telemetry/ITelemetryLog.cs +++ b/src/Workspaces/Core/Portable/Telemetry/ITelemetryLog.cs @@ -11,5 +11,5 @@ internal interface ITelemetryLog /// /// Adds a telemetry event with values obtained from context message /// - public void Log(KeyValueLogMessage logMessage); + void Log(KeyValueLogMessage logMessage); } diff --git a/src/Workspaces/Core/Portable/Telemetry/ITelemetryLogProvider.cs b/src/Workspaces/Core/Portable/Telemetry/ITelemetryLogProvider.cs index 8ef0da7052293..c670bdb1ebfd8 100644 --- a/src/Workspaces/Core/Portable/Telemetry/ITelemetryLogProvider.cs +++ b/src/Workspaces/Core/Portable/Telemetry/ITelemetryLogProvider.cs @@ -12,7 +12,7 @@ internal interface ITelemetryLogProvider /// Returns an for logging telemetry. /// /// FunctionId representing the telemetry operation - public ITelemetryBlockLog? GetLog(FunctionId functionId); + ITelemetryBlockLog? GetLog(FunctionId functionId); /// /// Returns an aggregating for logging histogram based telemetry. @@ -20,16 +20,16 @@ internal interface ITelemetryLogProvider /// FunctionId representing the telemetry operation /// Optional values indicating bucket boundaries in milliseconds. If not specified, /// all aggregating events created will use a default configuration - public ITelemetryBlockLog? GetHistogramLog(FunctionId functionId, double[]? bucketBoundaries = null); + ITelemetryBlockLog? GetHistogramLog(FunctionId functionId, double[]? bucketBoundaries = null); /// /// Returns an aggregating for logging counter telemetry. /// /// FunctionId representing the telemetry operation - public ITelemetryLog? GetCounterLog(FunctionId functionId); + ITelemetryLog? GetCounterLog(FunctionId functionId); /// /// Flushes all telemetry logs /// - public void Flush(); + void Flush(); } diff --git a/src/Workspaces/Core/Portable/Utilities/SpellChecker.cs b/src/Workspaces/Core/Portable/Utilities/SpellChecker.cs index 76e93c5d10ded..a4c4d299f462e 100644 --- a/src/Workspaces/Core/Portable/Utilities/SpellChecker.cs +++ b/src/Workspaces/Core/Portable/Utilities/SpellChecker.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Collections; diff --git a/src/Workspaces/Core/Portable/Workspace/Host/IWorkspaceTestLogger.cs b/src/Workspaces/Core/Portable/Workspace/Host/IWorkspaceTestLogger.cs index 9aa5621db72b3..a13a1b666bf03 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/IWorkspaceTestLogger.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/IWorkspaceTestLogger.cs @@ -6,5 +6,5 @@ namespace Microsoft.CodeAnalysis.Host; internal interface IWorkspaceTestLogger : IWorkspaceService { - public void Log(string message); + void Log(string message); } diff --git a/src/Workspaces/Core/Portable/Workspace/Host/Mef/MefHostServices.cs b/src/Workspaces/Core/Portable/Workspace/Host/Mef/MefHostServices.cs index f5283e66ea43a..472370e224f48 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/Mef/MefHostServices.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/Mef/MefHostServices.cs @@ -73,33 +73,35 @@ private sealed class WithMetadataImporter #region Defaults - private static MefHostServices s_defaultHost; public static MefHostServices DefaultHost { get { - if (s_defaultHost == null) + if (field == null) { var host = Create(DefaultAssemblies); - Interlocked.CompareExchange(ref s_defaultHost, host, null); + Interlocked.CompareExchange(ref field, host, null); } - return s_defaultHost; + return field; } + + private set; } - private static ImmutableArray s_defaultAssemblies; public static ImmutableArray DefaultAssemblies { get { - if (s_defaultAssemblies.IsDefault) + if (field.IsDefault) { - ImmutableInterlocked.InterlockedInitialize(ref s_defaultAssemblies, LoadDefaultAssemblies()); + ImmutableInterlocked.InterlockedInitialize(ref field, LoadDefaultAssemblies()); } - return s_defaultAssemblies; + return field; } + + private set; } // Used to build a MEF composition using the main workspaces assemblies and the known VisualBasic/CSharp workspace assemblies. @@ -135,7 +137,7 @@ internal static void HookServiceCreation(CreationHook hook) s_creationHook = hook; // The existing host, if any, is not retained past this call. - s_defaultHost = null; + DefaultHost = null; } } } diff --git a/src/Workspaces/Core/Portable/Workspace/Host/TaskScheduler/TaskSchedulerProvider.cs b/src/Workspaces/Core/Portable/Workspace/Host/TaskScheduler/TaskSchedulerProvider.cs index afee922e20d64..0c2dbae286c02 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/TaskScheduler/TaskSchedulerProvider.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/TaskScheduler/TaskSchedulerProvider.cs @@ -2,11 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Microsoft.CodeAnalysis.Host.Mef; using System; using System.Composition; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Host; diff --git a/src/Workspaces/Core/Portable/Workspace/Host/TaskScheduler/WorkspaceAsynchronousOperationListenerProvider.cs b/src/Workspaces/Core/Portable/Workspace/Host/TaskScheduler/WorkspaceAsynchronousOperationListenerProvider.cs index 886d4bf7acb45..1a0422b9cdc76 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/TaskScheduler/WorkspaceAsynchronousOperationListenerProvider.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/TaskScheduler/WorkspaceAsynchronousOperationListenerProvider.cs @@ -2,10 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Microsoft.CodeAnalysis.Host.Mef; -using Microsoft.CodeAnalysis.Shared.TestHooks; using System; using System.Composition; +using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.Shared.TestHooks; namespace Microsoft.CodeAnalysis.Host; diff --git a/src/Workspaces/Core/Portable/Workspace/Host/TemporaryStorage/ITemporaryStorageStreamHandle.cs b/src/Workspaces/Core/Portable/Workspace/Host/TemporaryStorage/ITemporaryStorageStreamHandle.cs index 2a237a6fd1a47..808d8df094a50 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/TemporaryStorage/ITemporaryStorageStreamHandle.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/TemporaryStorage/ITemporaryStorageStreamHandle.cs @@ -16,7 +16,7 @@ namespace Microsoft.CodeAnalysis.Host; /// internal interface ITemporaryStorageStreamHandle { - public TemporaryStorageIdentifier Identifier { get; } + TemporaryStorageIdentifier Identifier { get; } /// /// Reads the data indicated to by this handle into a stream. This stream can be created in a different process diff --git a/src/Workspaces/Core/Portable/Workspace/Host/TemporaryStorage/ITemporaryStorageTextHandle.cs b/src/Workspaces/Core/Portable/Workspace/Host/TemporaryStorage/ITemporaryStorageTextHandle.cs index d2c1dcccc88b1..2fa55ef5ba798 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/TemporaryStorage/ITemporaryStorageTextHandle.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/TemporaryStorage/ITemporaryStorageTextHandle.cs @@ -10,7 +10,7 @@ namespace Microsoft.CodeAnalysis.Host; internal interface ITemporaryStorageTextHandle { - public TemporaryStorageIdentifier Identifier { get; } + TemporaryStorageIdentifier Identifier { get; } SourceText ReadFromTemporaryStorage(CancellationToken cancellationToken); Task ReadFromTemporaryStorageAsync(CancellationToken cancellationToken); diff --git a/src/Workspaces/Core/Portable/Workspace/Host/TemporaryStorage/LegacyTemporaryStorageService.cs b/src/Workspaces/Core/Portable/Workspace/Host/TemporaryStorage/LegacyTemporaryStorageService.cs index be4762ca42833..a4e011da48238 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/TemporaryStorage/LegacyTemporaryStorageService.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/TemporaryStorage/LegacyTemporaryStorageService.cs @@ -7,8 +7,8 @@ using System.IO; using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Host; diff --git a/src/Workspaces/Core/Portable/Workspace/ProjectSystem/FileWatchedPortableExecutableReferenceFactory.cs b/src/Workspaces/Core/Portable/Workspace/ProjectSystem/FileWatchedPortableExecutableReferenceFactory.cs index f68e3fa6861e7..afe95e4b871bb 100644 --- a/src/Workspaces/Core/Portable/Workspace/ProjectSystem/FileWatchedPortableExecutableReferenceFactory.cs +++ b/src/Workspaces/Core/Portable/Workspace/ProjectSystem/FileWatchedPortableExecutableReferenceFactory.cs @@ -142,7 +142,6 @@ public void StopWatchingReference(string fullFilePath, TReference? referenceToTr { lock (_gate) { - var disposalLocation = callerFilePath + ", line " + callerLineNumber; if (!_referenceFileWatchingTokens.TryGetValue(fullFilePath, out var watchedFileReference)) { if (referenceToTrack != null) @@ -167,6 +166,8 @@ public void StopWatchingReference(string fullFilePath, TReference? referenceToTr if (referenceToTrack != null) { + var disposalLocation = callerFilePath + ", line " + callerLineNumber; + _previousDisposalLocations.Remove(referenceToTrack); _previousDisposalLocations.Add(referenceToTrack, disposalLocation); } diff --git a/src/Workspaces/Core/Portable/Workspace/ProjectSystem/IHostDiagnosticAnalyzerProvider.cs b/src/Workspaces/Core/Portable/Workspace/ProjectSystem/IHostDiagnosticAnalyzerProvider.cs deleted file mode 100644 index 709388e199aed..0000000000000 --- a/src/Workspaces/Core/Portable/Workspace/ProjectSystem/IHostDiagnosticAnalyzerProvider.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Immutable; -using Microsoft.CodeAnalysis.Diagnostics; - -namespace Microsoft.CodeAnalysis.Workspaces.ProjectSystem; - -/// -/// An interface implemented by hosts to provide the host-level analyzers; for example in Visual Studio for Windows this -/// is where we'll fetch VSIX-defined analyzers. -/// -internal interface IHostDiagnosticAnalyzerProvider -{ - ImmutableArray<(AnalyzerFileReference reference, string extensionId)> GetAnalyzerReferencesInExtensions(); - - /// - /// Gets the path to any assemblies that represent the closure of razor compiler. - /// - ImmutableArray<(string path, string extensionId)> GetRazorAssembliesInExtensions(); -} diff --git a/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProject.BatchingDocumentCollection.cs b/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProject.BatchingDocumentCollection.cs index b13a1ae6cecf8..ab75dacee1552 100644 --- a/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProject.BatchingDocumentCollection.cs +++ b/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProject.BatchingDocumentCollection.cs @@ -13,7 +13,6 @@ using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Threading; using Roslyn.Utilities; diff --git a/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProject.cs b/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProject.cs index 4f6e9559d07bf..14578055e8ff2 100644 --- a/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProject.cs +++ b/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProject.cs @@ -81,14 +81,6 @@ internal sealed partial class ProjectSystemProject private string? _filePath; private CompilationOptions? _compilationOptions; private ParseOptions? _parseOptions; - private SourceHashAlgorithm _checksumAlgorithm = SourceHashAlgorithms.Default; - private bool _hasAllInformation = true; - private string? _compilationOutputAssemblyFilePath; - private string? _outputFilePath; - private string? _outputRefFilePath; - private string? _generatedFilesOutputDirectory; - private string? _defaultNamespace; - private bool _hasSdkCodeStyleAnalyzers; /// /// If this project is the 'primary' project the project system cares about for a group of Roslyn projects that @@ -97,11 +89,6 @@ internal sealed partial class ProjectSystemProject /// internal bool IsPrimary { get; set; } = true; - // Actual property values for 'RunAnalyzers' and 'RunAnalyzersDuringLiveAnalysis' properties from the project file. - // Both these properties can be used to configure running analyzers, with RunAnalyzers overriding RunAnalyzersDuringLiveAnalysis. - private bool? _runAnalyzersPropertyValue; - private bool? _runAnalyzersDuringLiveAnalysisPropertyValue; - // Effective boolean value to determine if analyzers should be executed based on _runAnalyzersPropertyValue and _runAnalyzersDuringLiveAnalysisPropertyValue. private bool _runAnalyzers = true; @@ -396,9 +383,9 @@ public ParseOptions? ParseOptions /// internal string? CompilationOutputAssemblyFilePath { - get => _compilationOutputAssemblyFilePath; + get; set => ChangeProjectOutputPath( - ref _compilationOutputAssemblyFilePath, + ref field, value, s => s.WithProjectCompilationOutputInfo(Id, s.GetRequiredProject(Id).CompilationOutputInfo.WithAssemblyPath(value))); } @@ -408,23 +395,23 @@ internal string? CompilationOutputAssemblyFilePath /// internal string? GeneratedFilesOutputDirectory { - get => _generatedFilesOutputDirectory; + get; set => ChangeProjectOutputPath( - ref _generatedFilesOutputDirectory, + ref field, value, s => s.WithProjectCompilationOutputInfo(Id, s.GetRequiredProject(Id).CompilationOutputInfo.WithGeneratedFilesOutputDirectory(value))); } public string? OutputFilePath { - get => _outputFilePath; - set => ChangeProjectOutputPath(ref _outputFilePath, value, s => s.WithProjectOutputFilePath(Id, value)); + get; + set => ChangeProjectOutputPath(ref field, value, s => s.WithProjectOutputFilePath(Id, value)); } public string? OutputRefFilePath { - get => _outputRefFilePath; - set => ChangeProjectOutputPath(ref _outputRefFilePath, value, s => s.WithProjectOutputRefFilePath(Id, value)); + get; + set => ChangeProjectOutputPath(ref field, value, s => s.WithProjectOutputRefFilePath(Id, value)); } public string? FilePath @@ -441,34 +428,37 @@ public string DisplayName public SourceHashAlgorithm ChecksumAlgorithm { - get => _checksumAlgorithm; - set => ChangeProjectProperty(ref _checksumAlgorithm, value, s => s.WithProjectChecksumAlgorithm(Id, value)); - } + get; + set => ChangeProjectProperty(ref field, value, s => s.WithProjectChecksumAlgorithm(Id, value)); + } = SourceHashAlgorithms.Default; // internal to match the visibility of the Workspace-level API -- this is something // we use but we haven't made officially public yet. internal bool HasAllInformation { - get => _hasAllInformation; - set => ChangeProjectProperty(ref _hasAllInformation, value, s => s.WithHasAllInformation(Id, value)); - } + get; + set => ChangeProjectProperty(ref field, value, s => s.WithHasAllInformation(Id, value)); + } = true; + + // Actual property values for 'RunAnalyzers' and 'RunAnalyzersDuringLiveAnalysis' properties from the project file. + // Both these properties can be used to configure running analyzers, with RunAnalyzers overriding RunAnalyzersDuringLiveAnalysis. internal bool? RunAnalyzers { - get => _runAnalyzersPropertyValue; + get; set { - _runAnalyzersPropertyValue = value; + field = value; UpdateRunAnalyzers(); } } internal bool? RunAnalyzersDuringLiveAnalysis { - get => _runAnalyzersDuringLiveAnalysisPropertyValue; + get; set { - _runAnalyzersDuringLiveAnalysisPropertyValue = value; + field = value; UpdateRunAnalyzers(); } } @@ -476,14 +466,14 @@ internal bool? RunAnalyzersDuringLiveAnalysis private void UpdateRunAnalyzers() { // Property RunAnalyzers overrides RunAnalyzersDuringLiveAnalysis, and default when both properties are not set is 'true'. - var runAnalyzers = _runAnalyzersPropertyValue ?? _runAnalyzersDuringLiveAnalysisPropertyValue ?? true; + var runAnalyzers = RunAnalyzers ?? RunAnalyzersDuringLiveAnalysis ?? true; ChangeProjectProperty(ref _runAnalyzers, runAnalyzers, s => s.WithRunAnalyzers(Id, runAnalyzers)); } internal bool HasSdkCodeStyleAnalyzers { - get => _hasSdkCodeStyleAnalyzers; - set => ChangeProjectProperty(ref _hasSdkCodeStyleAnalyzers, value, s => s.WithHasSdkCodeStyleAnalyzers(Id, value)); + get; + set => ChangeProjectProperty(ref field, value, s => s.WithHasSdkCodeStyleAnalyzers(Id, value)); } /// @@ -499,8 +489,8 @@ internal bool HasSdkCodeStyleAnalyzers /// internal string? DefaultNamespace { - get => _defaultNamespace; - set => ChangeProjectProperty(ref _defaultNamespace, value, s => s.WithProjectDefaultNamespace(Id, value)); + get; + set => ChangeProjectProperty(ref field, value, s => s.WithProjectDefaultNamespace(Id, value)); } /// @@ -726,7 +716,7 @@ static ProjectUpdateState UpdateMetadataReferences( foreach (var (path, properties) in metadataReferencesAddedInBatch) { projectUpdateState = TryCreateConvertedProjectReference_NoLock( - projectId, path, properties, projectUpdateState, solutionChanges.Solution, out var projectReference); + projectBeforeMutation.State, path, properties, projectUpdateState, solutionChanges.Solution, out var projectReference); if (projectReference != null) { @@ -1152,13 +1142,6 @@ private OneOrMany GetMappedAnalyzerPaths(string fullPath) return OneOrMany.Empty; } - if (IsSdkRazorSourceGenerator(fullPath)) - { - // Map all files in the SDK directory that contains the Razor source generator to source generator files loaded from VSIX. - // Include the generator and all its dependencies shipped in VSIX, discard the generator and all dependencies in the SDK - return GetMappedRazorSourceGenerator(fullPath); - } - if (TryRedirectAnalyzerAssembly(fullPath) is { } redirectedPath) { return OneOrMany.Create(redirectedPath); @@ -1207,39 +1190,6 @@ private OneOrMany GetMappedAnalyzerPaths(string fullPath) _ => false, }; - internal const string RazorVsixExtensionId = "Microsoft.VisualStudio.RazorExtension"; - private static readonly string s_razorSourceGeneratorSdkDirectory = CreateDirectoryPathFragment("Sdks", "Microsoft.NET.Sdk.Razor", "source-generators"); - private static readonly ImmutableArray s_razorSourceGeneratorAssemblyNames = - [ - "Microsoft.NET.Sdk.Razor.SourceGenerators", - "Microsoft.CodeAnalysis.Razor.Compiler.SourceGenerators", - "Microsoft.CodeAnalysis.Razor.Compiler", - ]; - private static readonly ImmutableArray s_razorSourceGeneratorAssemblyRootedFileNames = s_razorSourceGeneratorAssemblyNames.SelectAsArray( - assemblyName => PathUtilities.DirectorySeparatorStr + assemblyName + ".dll"); - - private static bool IsSdkRazorSourceGenerator(string fullPath) => DirectoryNameEndsWith(fullPath, s_razorSourceGeneratorSdkDirectory); - - private OneOrMany GetMappedRazorSourceGenerator(string fullPath) - { - var vsixRazorAnalyzers = _hostInfo.HostDiagnosticAnalyzerProvider.GetRazorAssembliesInExtensions().SelectAsArray( - predicate: item => item.extensionId == RazorVsixExtensionId, - selector: item => item.path); - - if (!vsixRazorAnalyzers.IsEmpty) - { - if (s_razorSourceGeneratorAssemblyRootedFileNames.Any( - static (fileName, fullPath) => fullPath.EndsWith(fileName, StringComparison.OrdinalIgnoreCase), fullPath)) - { - return OneOrMany.Create(vsixRazorAnalyzers); - } - - return OneOrMany.Empty; - } - - return OneOrMany.Create(fullPath); - } - private static string CreateDirectoryPathFragment(params string[] paths) => Path.Combine([" ", .. paths, " "]).Trim(); private static bool DirectoryNameEndsWith(string fullPath, string ending) => fullPath.LastIndexOf(ending, StringComparison.OrdinalIgnoreCase) + ending.Length - 1 == diff --git a/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProjectFactory.cs b/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProjectFactory.cs index a08cafbe655a5..12c3ab9fa3039 100644 --- a/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProjectFactory.cs +++ b/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProjectFactory.cs @@ -7,6 +7,7 @@ using System.Collections.Immutable; using System.IO; using System.Linq; +using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; @@ -548,14 +549,20 @@ private static ProjectUpdateState ConvertMetadataReferencesToProjectReferences_N string outputPath, ProjectUpdateState projectUpdateState) { - foreach (var projectIdToRetarget in solutionChanges.Solution.ProjectIds) + // PERF: call GetRequiredProjectState instead of GetRequiredProject, otherwise creating a new project + // might force all Project instances to get created. + var candidateProjectState = solutionChanges.Solution.GetRequiredProjectState(projectIdToReference); + + foreach (var projectToRetarget in solutionChanges.Solution.SortedProjectStates) { - if (CanConvertMetadataReferenceToProjectReference(solutionChanges.Solution, projectIdToRetarget, referencedProjectId: projectIdToReference)) + // PERF: If we don't even have any metadata references yet, then don't even call CanConvertMetadataReferenceToProjectReference. + // This optimizes the early parts of solution load, where projects may be created with their output paths right away, + // but metadata references come in later. CanConvertMetadataReferenceToProjectReference isn't terribly expensive + // but when called enough times things can start to add up. + if (projectToRetarget.MetadataReferences.Count > 0 && + CanConvertMetadataReferenceToProjectReference(solutionChanges.Solution, projectToRetarget, candidateProjectState)) { - // PERF: call GetRequiredProjectState instead of GetRequiredProject, otherwise creating a new project - // might force all Project instances to get created. - var projectState = solutionChanges.Solution.GetRequiredProjectState(projectIdToRetarget); - foreach (var reference in projectState.MetadataReferences) + foreach (var reference in projectToRetarget.MetadataReferences) { if (reference is PortableExecutableReference peReference && string.Equals(peReference.FilePath, outputPath, StringComparison.OrdinalIgnoreCase)) @@ -564,13 +571,13 @@ private static ProjectUpdateState ConvertMetadataReferencesToProjectReferences_N var projectReference = new ProjectReference(projectIdToReference, peReference.Properties.Aliases, peReference.Properties.EmbedInteropTypes); var newSolution = solutionChanges.Solution - .RemoveMetadataReference(projectIdToRetarget, peReference) - .AddProjectReference(projectIdToRetarget, projectReference); + .RemoveMetadataReference(projectToRetarget.Id, peReference) + .AddProjectReference(projectToRetarget.Id, projectReference); - solutionChanges.UpdateSolutionForProjectAction(projectIdToRetarget, newSolution); + solutionChanges.UpdateSolutionForProjectAction(projectToRetarget.Id, newSolution); - projectUpdateState = GetReferenceInformation(projectIdToRetarget, projectUpdateState, out var projectInfo); - projectUpdateState = projectUpdateState.WithProjectReferenceInfo(projectIdToRetarget, + projectUpdateState = GetReferenceInformation(projectToRetarget.Id, projectUpdateState, out var projectInfo); + projectUpdateState = projectUpdateState.WithProjectReferenceInfo(projectToRetarget.Id, projectInfo.WithConvertedProjectReference(peReference.FilePath!, projectReference)); // We have converted one, but you could have more than one reference with different aliases that @@ -585,33 +592,25 @@ private static ProjectUpdateState ConvertMetadataReferencesToProjectReferences_N [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/31306", Constraint = "Avoid calling " + nameof(CodeAnalysis.Solution.GetProject) + " to avoid realizing all projects.")] - private static bool CanConvertMetadataReferenceToProjectReference(Solution solution, ProjectId projectIdWithMetadataReference, ProjectId referencedProjectId) + private static bool CanConvertMetadataReferenceToProjectReference(Solution solution, ProjectState projectWithMetadataReference, ProjectState candidateProjectToReference) { // We can never make a project reference ourselves. This isn't a meaningful scenario, but if somebody does this by accident // we do want to throw exceptions. - if (projectIdWithMetadataReference == referencedProjectId) + if (projectWithMetadataReference.Id == candidateProjectToReference.Id) { return false; } - // PERF: call GetProjectState instead of GetProject, otherwise creating a new project might force all - // Project instances to get created. - var projectWithMetadataReference = solution.GetProjectState(projectIdWithMetadataReference); - var referencedProject = solution.GetProjectState(referencedProjectId); - - Contract.ThrowIfNull(projectWithMetadataReference); - Contract.ThrowIfNull(referencedProject); - // We don't want to convert a metadata reference to a project reference if the project being referenced isn't // something we can create a Compilation for. For example, if we have a C# project, and it's referencing a F# // project via a metadata reference everything would be fine if we left it a metadata reference. Converting it // to a project reference means we couldn't create a Compilation anymore in the IDE, since the C# compilation // would need to reference an F# compilation. F# projects referencing other F# projects though do expect this to // work, and so we'll always allow references through of the same language. - if (projectWithMetadataReference.Language != referencedProject.Language) + if (projectWithMetadataReference.Language != candidateProjectToReference.Language) { if (projectWithMetadataReference.LanguageServices.GetService() != null && - referencedProject.LanguageServices.GetService() == null) + candidateProjectToReference.LanguageServices.GetService() == null) { // We're referencing something that we can't create a compilation from something that can, so keep the metadata reference return false; @@ -621,11 +620,11 @@ private static bool CanConvertMetadataReferenceToProjectReference(Solution solut // Getting a metadata reference from a 'module' is not supported from the compilation layer. Nor is emitting a // 'metadata-only' stream for it (a 'skeleton' reference). So converting a NetModule reference to a project // reference won't actually help us out. Best to keep this as a plain metadata reference. - if (referencedProject.CompilationOptions?.OutputKind == OutputKind.NetModule) + if (candidateProjectToReference.CompilationOptions?.OutputKind == OutputKind.NetModule) return false; // If this is going to cause a circular reference, also disallow it - if (solution.GetProjectDependencyGraph().GetProjectsThatThisProjectTransitivelyDependsOn(referencedProjectId).Contains(projectIdWithMetadataReference)) + if (solution.GetProjectDependencyGraph().DoesProjectTransitivelyDependOnProject(candidateProjectToReference.Id, projectWithMetadataReference.Id)) { return false; } @@ -696,7 +695,7 @@ private static ProjectUpdateState ConvertProjectReferencesToMetadataReferences_N /// during a workspace update (which will attempt to apply the update multiple times). /// public static ProjectUpdateState TryCreateConvertedProjectReference_NoLock( - ProjectId referencingProject, + ProjectState referencingProjectState, string path, MetadataReferenceProperties properties, ProjectUpdateState projectUpdateState, @@ -707,15 +706,15 @@ public static ProjectUpdateState TryCreateConvertedProjectReference_NoLock( { var projectIdToReference = ids.First(); - if (CanConvertMetadataReferenceToProjectReference(currentSolution, referencingProject, projectIdToReference)) + if (CanConvertMetadataReferenceToProjectReference(currentSolution, referencingProjectState, currentSolution.GetRequiredProjectState(projectIdToReference))) { projectReference = new ProjectReference( projectIdToReference, aliases: properties.Aliases, embedInteropTypes: properties.EmbedInteropTypes); - projectUpdateState = GetReferenceInformation(referencingProject, projectUpdateState, out var projectReferenceInfo); - projectUpdateState = projectUpdateState.WithProjectReferenceInfo(referencingProject, projectReferenceInfo.WithConvertedProjectReference(path, projectReference)); + projectUpdateState = GetReferenceInformation(referencingProjectState.Id, projectUpdateState, out var projectReferenceInfo); + projectUpdateState = projectUpdateState.WithProjectReferenceInfo(referencingProjectState.Id, projectReferenceInfo.WithConvertedProjectReference(path, projectReference)); return projectUpdateState; } else diff --git a/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProjectHostInfo.cs b/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProjectHostInfo.cs index 60a6142c0b39e..3d216250947a4 100644 --- a/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProjectHostInfo.cs +++ b/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProjectHostInfo.cs @@ -12,5 +12,4 @@ namespace Microsoft.CodeAnalysis.Workspaces.ProjectSystem; internal sealed record ProjectSystemHostInfo( ImmutableArray> DynamicFileInfoProviders, - IHostDiagnosticAnalyzerProvider HostDiagnosticAnalyzerProvider, ImmutableArray AnalyzerAssemblyRedirectors); diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/DocumentId.cs b/src/Workspaces/Core/Portable/Workspace/Solution/DocumentId.cs index 126ee2af8858a..0209282e6e4d3 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/DocumentId.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/DocumentId.cs @@ -25,14 +25,14 @@ public sealed class DocumentId : IEquatable [DataMember(Order = 2)] internal bool IsSourceGenerated { get; } [DataMember(Order = 3)] - private readonly string? _debugName; + internal string? DebugName { get; } private DocumentId(ProjectId projectId, Guid guid, bool isSourceGenerated, string? debugName) { this.ProjectId = projectId; this.Id = guid; this.IsSourceGenerated = isSourceGenerated; - _debugName = debugName; + DebugName = debugName; } /// @@ -57,10 +57,8 @@ internal static DocumentId CreateFromSerialized(ProjectId projectId, Guid id, bo return new DocumentId(projectId, id, isSourceGenerated, debugName); } - internal string? DebugName => _debugName; - internal string GetDebuggerDisplay() - => string.Format("({0}, #{1} - {2})", this.GetType().Name, this.Id, _debugName); + => string.Format("({0}, #{1} - {2})", this.GetType().Name, this.Id, DebugName); public override string ToString() => GetDebuggerDisplay(); diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/ProjectDependencyGraph_RemoveAllProjectReferences.cs b/src/Workspaces/Core/Portable/Workspace/Solution/ProjectDependencyGraph_RemoveAllProjectReferences.cs index 671f47c514c23..808af9f6c9f37 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/ProjectDependencyGraph_RemoveAllProjectReferences.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/ProjectDependencyGraph_RemoveAllProjectReferences.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using System.Collections.Generic; using System.Diagnostics; using Roslyn.Utilities; diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/ProjectDependencyGraph_RemoveProject.cs b/src/Workspaces/Core/Portable/Workspace/Solution/ProjectDependencyGraph_RemoveProject.cs index 55a18783bd6b2..e174d115beb0c 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/ProjectDependencyGraph_RemoveProject.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/ProjectDependencyGraph_RemoveProject.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using System.Collections.Generic; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/ProjectDependencyGraph_RemoveProjectReference.cs b/src/Workspaces/Core/Portable/Workspace/Solution/ProjectDependencyGraph_RemoveProjectReference.cs index d0c569c34c9fa..a68ed998b9a15 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/ProjectDependencyGraph_RemoveProjectReference.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/ProjectDependencyGraph_RemoveProjectReference.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using System.Collections.Generic; using System.Diagnostics; using Roslyn.Utilities; diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/ProjectId.cs b/src/Workspaces/Core/Portable/Workspace/Solution/ProjectId.cs index 78dd75ceb9525..f7f3818683cc4 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/ProjectId.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/ProjectId.cs @@ -41,12 +41,12 @@ public sealed class ProjectId : IEquatable, IComparable /// ). /// [DataMember(Order = 1)] - private readonly string? _debugName; + internal string? DebugName { get; } private ProjectId(Guid guid, string? debugName) { this.Id = guid; - _debugName = debugName; + DebugName = debugName; } /// @@ -66,10 +66,8 @@ public static ProjectId CreateFromSerialized(Guid id, string? debugName = null) return new ProjectId(id, debugName); } - internal string? DebugName => _debugName; - private string GetDebuggerDisplay() - => string.Format("({0}, #{1} - {2})", this.GetType().Name, this.Id, _debugName); + => string.Format("({0}, #{1} - {2})", this.GetType().Name, this.Id, DebugName); public override string ToString() => GetDebuggerDisplay(); diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/ProjectState.cs b/src/Workspaces/Core/Portable/Workspace/Solution/ProjectState.cs index 10b22797c0fed..50c5adf2f2523 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/ProjectState.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/ProjectState.cs @@ -11,6 +11,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Host; @@ -47,23 +48,11 @@ internal sealed partial class ProjectState : IComparable private readonly AsyncLazy _lazyLatestDocumentVersion; private readonly AsyncLazy _lazyLatestDocumentTopLevelChangeVersion; - // Checksums for this solution state (access via LazyChecksums) - private AsyncLazy? _lazyChecksums; - - // Mapping from content has to document id (access via LazyContentHashToDocumentId) - private AsyncLazy, DocumentId>>? _lazyContentHashToDocumentId; - /// /// Analyzer config options to be used for specific trees. /// private readonly AnalyzerConfigOptionsCache _analyzerConfigOptionsCache; - private ImmutableArray _lazyAdditionalFiles; - - private AnalyzerOptions? _lazyProjectAnalyzerOptions; - - private AnalyzerOptions? _lazyHostAnalyzerOptions; - private ProjectState( ProjectInfo projectInfo, LanguageServices languageServices, @@ -155,31 +144,32 @@ private AsyncLazy LazyChecksums { get { - if (_lazyChecksums is null) + if (field is null) { Interlocked.CompareExchange( - ref _lazyChecksums, + ref field, AsyncLazy.Create(static (self, cancellationToken) => self.ComputeChecksumsAsync(cancellationToken), arg: this), null); } - return _lazyChecksums; + return field; } } + // Mapping from content has to document id (access via LazyContentHashToDocumentId) private AsyncLazy, DocumentId>> LazyContentHashToDocumentId { get { - if (_lazyContentHashToDocumentId is null) + if (field is null) { Interlocked.CompareExchange( - ref _lazyContentHashToDocumentId, + ref field, AsyncLazy.Create(static (self, cancellationToken) => self.ComputeContentHashToDocumentIdAsync(cancellationToken), arg: this), null); } - return _lazyContentHashToDocumentId; + return field; } } @@ -326,7 +316,7 @@ private ImmutableArray AdditionalFiles get { return InterlockedOperations.Initialize( - ref _lazyAdditionalFiles, + ref field, static self => self.AdditionalDocumentStates.SelectAsArray(static documentState => documentState.AdditionalText), this); } @@ -334,19 +324,21 @@ private ImmutableArray AdditionalFiles public AnalyzerOptions ProjectAnalyzerOptions => InterlockedOperations.Initialize( - ref _lazyProjectAnalyzerOptions, + ref field, static self => new AnalyzerOptions( additionalFiles: self.AdditionalFiles, optionsProvider: new ProjectAnalyzerConfigOptionsProvider(self)), this); public AnalyzerOptions HostAnalyzerOptions - => InterlockedOperations.Initialize( - ref _lazyHostAnalyzerOptions, + { + get => InterlockedOperations.Initialize( + ref field, static self => new AnalyzerOptions( additionalFiles: self.AdditionalFiles, optionsProvider: new ProjectHostAnalyzerConfigOptionsProvider(self)), - this); + this); private set; + } public AnalyzerConfigData GetAnalyzerOptionsForPath(string path, CancellationToken cancellationToken) => _analyzerConfigOptionsCache.Lazy.GetValue(cancellationToken).GetOptionsForSourcePath(path); diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.RegularCompilationTracker_Generators.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.RegularCompilationTracker_Generators.cs index decb2264fa93d..45549fde47210 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.RegularCompilationTracker_Generators.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.RegularCompilationTracker_Generators.cs @@ -4,12 +4,14 @@ using System; using System.Collections.Immutable; +using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.PooledObjects; diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.SymbolToProjectId.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.SymbolToProjectId.cs index b4d3e1fd6b24b..2e08d2deb7f03 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.SymbolToProjectId.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.SymbolToProjectId.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Shared.Extensions; diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.WithFrozenSourceGeneratedDocumentsCompilationTracker.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.WithFrozenSourceGeneratedDocumentsCompilationTracker.cs index 8d877f12d1cf8..c541999178796 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.WithFrozenSourceGeneratedDocumentsCompilationTracker.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.WithFrozenSourceGeneratedDocumentsCompilationTracker.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Immutable; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState_Checksum.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState_Checksum.cs index 2f17660b6a891..9caa92ca310a6 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState_Checksum.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState_Checksum.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; -using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState_SourceGenerators.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState_SourceGenerators.cs index 51bfb2bb07687..38a2ce133ec5e 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState_SourceGenerators.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState_SourceGenerators.cs @@ -9,6 +9,7 @@ using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionId.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionId.cs index 7d1896a8935f2..b2ea85e38bd59 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionId.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionId.cs @@ -24,14 +24,13 @@ public sealed class SolutionId : IEquatable /// [DataMember(Order = 0)] public Guid Id { get; } - [DataMember(Order = 1)] - private readonly string _debugName; + internal string DebugName { get; } private SolutionId(Guid id, string debugName) { this.Id = id; - _debugName = debugName; + DebugName = debugName; } /// @@ -53,10 +52,8 @@ public static SolutionId CreateFromSerialized(Guid id, string debugName = null) return new SolutionId(id, debugName); } - internal string DebugName => _debugName; - private string GetDebuggerDisplay() - => string.Format("({0}, #{1} - {2})", GetType().Name, this.Id, _debugName); + => string.Format("({0}, #{1} - {2})", GetType().Name, this.Id, DebugName); public override bool Equals(object obj) => this.Equals(obj as SolutionId); diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.cs index 307f2a3cf64ab..60ad44dd0eb0d 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.cs @@ -1214,7 +1214,7 @@ public static ProjectDependencyGraph CreateDependencyGraph( IReadOnlyList projectIds, ImmutableArray sortedNewProjectStates) { - var map = sortedNewProjectStates.Select(state => KeyValuePairUtil.Create( + var map = sortedNewProjectStates.Select(state => KeyValuePair.Create( state.Id, state.ProjectReferences.Where(pr => GetProjectState(sortedNewProjectStates, pr.ProjectId) != null).Select(pr => pr.ProjectId).ToImmutableHashSet())) .ToImmutableDictionary(); diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/StateChecksums.cs b/src/Workspaces/Core/Portable/Workspace/Solution/StateChecksums.cs index 63caf30a1f4d6..d328bcda6883f 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/StateChecksums.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/StateChecksums.cs @@ -192,8 +192,6 @@ internal sealed class SolutionStateChecksums( ChecksumCollection analyzerReferences, Checksum fallbackAnalyzerOptionsChecksum) { - private ProjectCone? _projectCone; - public Checksum Checksum { get; } = Checksum.Create(stackalloc[] { projectConeId == null ? Checksum.Null : projectConeId.Checksum, @@ -212,7 +210,7 @@ internal sealed class SolutionStateChecksums( // Acceptably not threadsafe. ProjectCone is a class, and the runtime guarantees anyone will see this field fully // initialized. It's acceptable to have multiple instances of this in a race condition as the data will be same // (and our asserts don't check for reference equality, only value equality). - public ProjectCone? ProjectCone => _projectCone ??= ComputeProjectCone(); + public ProjectCone? ProjectCone { get => field ??= ComputeProjectCone(); private set; } private ProjectCone? ComputeProjectCone() => ProjectConeId == null ? null : new ProjectCone(ProjectConeId, Projects.Ids.ToFrozenSet()); diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/TextDocumentStates.cs b/src/Workspaces/Core/Portable/Workspace/Solution/TextDocumentStates.cs index 7d3a3c7c6f9b4..06a46edd4effd 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/TextDocumentStates.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/TextDocumentStates.cs @@ -13,6 +13,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Shared.Collections; @@ -149,7 +150,7 @@ public TextDocumentStates AddRange(ImmutableArray states) return new( _ids.AddRange(ids), - States.AddRange(states.Select(state => KeyValuePairUtil.Create(state.Id, state))), + States.AddRange(states.Select(state => KeyValuePair.Create(state.Id, state))), filePathToDocumentIds: null); } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/VersionSource/RecoverableTextAndVersion.RecoverableText.cs b/src/Workspaces/Core/Portable/Workspace/Solution/VersionSource/RecoverableTextAndVersion.RecoverableText.cs index 6997357e85bf7..54d0a321aa8a5 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/VersionSource/RecoverableTextAndVersion.RecoverableText.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/VersionSource/RecoverableTextAndVersion.RecoverableText.cs @@ -31,11 +31,6 @@ private sealed partial class RecoverableText AsynchronousOperationListenerProvider.NullListener, CancellationToken.None); - /// - /// Lazily created. Access via the property. - /// - private SemaphoreSlim? _lazyGate; - /// /// Whether or not we've saved our value to secondary storage. Used so we only do that once. /// @@ -53,7 +48,7 @@ private sealed partial class RecoverableText /// private WeakReference? _weakReference; - private SemaphoreSlim Gate => InterlockedOperations.Initialize(ref _lazyGate, SemaphoreSlimFactory.Instance); + private SemaphoreSlim Gate { get => InterlockedOperations.Initialize(ref field, SemaphoreSlimFactory.Instance); set; } /// /// Attempts to get the value, but only through the weak reference. This will only succeed *after* the value diff --git a/src/Workspaces/Core/Portable/Workspace/WorkspaceEventMap.cs b/src/Workspaces/Core/Portable/Workspace/WorkspaceEventMap.cs index 25c312703ccbc..28ebd8688b86e 100644 --- a/src/Workspaces/Core/Portable/Workspace/WorkspaceEventMap.cs +++ b/src/Workspaces/Core/Portable/Workspace/WorkspaceEventMap.cs @@ -7,9 +7,8 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Linq; -using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.ErrorReporting; -using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Workspace; namespace Microsoft.CodeAnalysis; diff --git a/src/Workspaces/Core/Portable/Workspace/WorkspaceEventOptions.cs b/src/Workspaces/Core/Portable/Workspace/WorkspaceEventOptions.cs index 522e52fc13a47..0de1e31575221 100644 --- a/src/Workspaces/Core/Portable/Workspace/WorkspaceEventOptions.cs +++ b/src/Workspaces/Core/Portable/Workspace/WorkspaceEventOptions.cs @@ -4,7 +4,7 @@ namespace Microsoft.CodeAnalysis; -internal record struct WorkspaceEventOptions(bool RequiresMainThread) +public record struct WorkspaceEventOptions(bool RequiresMainThread) { public static readonly WorkspaceEventOptions DefaultOptions = new(RequiresMainThread: false); public static readonly WorkspaceEventOptions RequiresMainThreadOptions = new(RequiresMainThread: true); diff --git a/src/Workspaces/Core/Portable/Workspace/WorkspaceEventRegistration.cs b/src/Workspaces/Core/Portable/Workspace/WorkspaceEventRegistration.cs index e54261036c404..4c001f68ceadf 100644 --- a/src/Workspaces/Core/Portable/Workspace/WorkspaceEventRegistration.cs +++ b/src/Workspaces/Core/Portable/Workspace/WorkspaceEventRegistration.cs @@ -14,11 +14,18 @@ namespace Microsoft.CodeAnalysis; /// /// This class is used to manage the lifecycle of an event handler associated with a workspace event. /// When the instance is disposed, the event handler is automatically unregistered from the event map. -internal sealed class WorkspaceEventRegistration(WorkspaceEventMap eventMap, WorkspaceEventType eventType, WorkspaceEventHandlerAndOptions handlerAndOptions) : IDisposable +public sealed class WorkspaceEventRegistration : IDisposable { - private readonly WorkspaceEventType _eventType = eventType; - private readonly WorkspaceEventHandlerAndOptions _handlerAndOptions = handlerAndOptions; - private WorkspaceEventMap? _eventMap = eventMap; + private readonly WorkspaceEventType _eventType; + private readonly WorkspaceEventHandlerAndOptions _handlerAndOptions; + private WorkspaceEventMap? _eventMap; + + internal WorkspaceEventRegistration(WorkspaceEventMap eventMap, WorkspaceEventType eventType, WorkspaceEventHandlerAndOptions handlerAndOptions) + { + _eventType = eventType; + _handlerAndOptions = handlerAndOptions; + _eventMap = eventMap; + } public void Dispose() { diff --git a/src/Workspaces/Core/Portable/Workspace/Workspace_Editor.cs b/src/Workspaces/Core/Portable/Workspace/Workspace_Editor.cs index 471b32c7bbfa9..5aee5921f967c 100644 --- a/src/Workspaces/Core/Portable/Workspace/Workspace_Editor.cs +++ b/src/Workspaces/Core/Portable/Workspace/Workspace_Editor.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; diff --git a/src/Workspaces/Core/Portable/Workspace/Workspace_Events.cs b/src/Workspaces/Core/Portable/Workspace/Workspace_Events.cs index 9ac3bd1527c1c..732c7325ae0d6 100644 --- a/src/Workspaces/Core/Portable/Workspace/Workspace_Events.cs +++ b/src/Workspaces/Core/Portable/Workspace/Workspace_Events.cs @@ -33,7 +33,7 @@ internal enum WorkspaceEventType /// /// Registers a handler that is fired whenever the current solution is changed. /// - internal WorkspaceEventRegistration RegisterWorkspaceChangedHandler(Action handler, WorkspaceEventOptions? options = null) + public WorkspaceEventRegistration RegisterWorkspaceChangedHandler(Action handler, WorkspaceEventOptions? options = null) => RegisterHandler(WorkspaceEventType.WorkspaceChange, handler, options); /// @@ -42,45 +42,45 @@ internal WorkspaceEventRegistration RegisterWorkspaceChangedHandler(Action - internal WorkspaceEventRegistration RegisterWorkspaceChangedImmediateHandler(Action handler, WorkspaceEventOptions? options = null) + public WorkspaceEventRegistration RegisterWorkspaceChangedImmediateHandler(Action handler, WorkspaceEventOptions? options = null) => RegisterHandler(WorkspaceEventType.WorkspaceChangedImmediate, handler, options); /// /// Registers a handler that is fired whenever the workspace or part of its solution model /// fails to access a file or other external resource. /// - internal WorkspaceEventRegistration RegisterWorkspaceFailedHandler(Action handler, WorkspaceEventOptions? options = null) + public WorkspaceEventRegistration RegisterWorkspaceFailedHandler(Action handler, WorkspaceEventOptions? options = null) => RegisterHandler(WorkspaceEventType.WorkspaceFailed, handler, options); /// /// Registers a handler that is fired when a is opened in the editor. /// - internal WorkspaceEventRegistration RegisterDocumentOpenedHandler(Action handler, WorkspaceEventOptions? options = null) + public WorkspaceEventRegistration RegisterDocumentOpenedHandler(Action handler, WorkspaceEventOptions? options = null) => RegisterHandler(WorkspaceEventType.DocumentOpened, handler, options); /// /// Registers a handler that is fired when a is closed in the editor. /// - internal WorkspaceEventRegistration RegisterDocumentClosedHandler(Action handler, WorkspaceEventOptions? options = null) + public WorkspaceEventRegistration RegisterDocumentClosedHandler(Action handler, WorkspaceEventOptions? options = null) => RegisterHandler(WorkspaceEventType.DocumentClosed, handler, options); /// /// Registers a handler that is fired when any is opened in the editor. /// - internal WorkspaceEventRegistration RegisterTextDocumentOpenedHandler(Action handler, WorkspaceEventOptions? options = null) + public WorkspaceEventRegistration RegisterTextDocumentOpenedHandler(Action handler, WorkspaceEventOptions? options = null) => RegisterHandler(WorkspaceEventType.TextDocumentOpened, handler, options); /// /// Registers a handler that is fired when any is closed in the editor. /// - internal WorkspaceEventRegistration RegisterTextDocumentClosedHandler(Action handler, WorkspaceEventOptions? options = null) + public WorkspaceEventRegistration RegisterTextDocumentClosedHandler(Action handler, WorkspaceEventOptions? options = null) => RegisterHandler(WorkspaceEventType.TextDocumentClosed, handler, options); /// /// Registers a handler that is fired when the active context document associated with a buffer /// changes. /// - internal WorkspaceEventRegistration RegisterDocumentActiveContextChangedHandler(Action handler, WorkspaceEventOptions? options = null) + public WorkspaceEventRegistration RegisterDocumentActiveContextChangedHandler(Action handler, WorkspaceEventOptions? options = null) => RegisterHandler(WorkspaceEventType.DocumentActiveContextChanged, handler, options); private WorkspaceEventRegistration RegisterHandler(WorkspaceEventType eventType, Action handler, WorkspaceEventOptions? options = null) diff --git a/src/Workspaces/Core/Portable/Workspace/Workspace_EventsLegacy.cs b/src/Workspaces/Core/Portable/Workspace/Workspace_EventsLegacy.cs index 58028bd0d7c9a..18c16019e6ef9 100644 --- a/src/Workspaces/Core/Portable/Workspace/Workspace_EventsLegacy.cs +++ b/src/Workspaces/Core/Portable/Workspace/Workspace_EventsLegacy.cs @@ -4,7 +4,7 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.ComponentModel; namespace Microsoft.CodeAnalysis; @@ -20,6 +20,8 @@ public abstract partial class Workspace /// /// An event raised whenever the current solution is changed. /// + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete($"Use {nameof(RegisterWorkspaceChangedHandler)} instead, which by default will no longer run on the UI thread.", error: false)] public event EventHandler WorkspaceChanged { add => AddLegacyEventHandler(value, WorkspaceEventType.WorkspaceChange); @@ -30,6 +32,8 @@ public event EventHandler WorkspaceChanged /// An event raised whenever the workspace or part of its solution model /// fails to access a file or other external resource. /// + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete($"Use {nameof(RegisterWorkspaceFailedHandler)} instead, which by default will no longer run on the UI thread.", error: false)] public event EventHandler WorkspaceFailed { add => AddLegacyEventHandler(value, WorkspaceEventType.WorkspaceFailed); @@ -39,6 +43,8 @@ public event EventHandler WorkspaceFailed /// /// An event that is fired when a is opened in the editor. /// + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete($"Use {nameof(RegisterDocumentOpenedHandler)} instead, which by default will no longer run on the UI thread.", error: false)] public event EventHandler DocumentOpened { add => AddLegacyEventHandler(value, WorkspaceEventType.DocumentOpened); @@ -48,6 +54,8 @@ public event EventHandler DocumentOpened /// /// An event that is fired when any is opened in the editor. /// + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete($"Use {nameof(RegisterTextDocumentOpenedHandler)} instead, which by default will no longer run on the UI thread.", error: false)] public event EventHandler TextDocumentOpened { add => AddLegacyEventHandler(value, WorkspaceEventType.TextDocumentOpened); @@ -57,6 +65,8 @@ public event EventHandler TextDocumentOpened /// /// An event that is fired when a is closed in the editor. /// + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete($"Use {nameof(RegisterDocumentClosedHandler)} instead, which by default will no longer run on the UI thread.", error: false)] public event EventHandler DocumentClosed { add => AddLegacyEventHandler(value, WorkspaceEventType.DocumentClosed); @@ -66,6 +76,8 @@ public event EventHandler DocumentClosed /// /// An event that is fired when any is closed in the editor. /// + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete($"Use {nameof(RegisterTextDocumentClosedHandler)} instead, which by default will no longer run on the UI thread.", error: false)] public event EventHandler TextDocumentClosed { add => AddLegacyEventHandler(value, WorkspaceEventType.TextDocumentClosed); @@ -76,6 +88,8 @@ public event EventHandler TextDocumentClosed /// An event that is fired when the active context document associated with a buffer /// changes. /// + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete($"Use {nameof(RegisterDocumentActiveContextChangedHandler)} instead, which by default will no longer run on the UI thread.", error: false)] public event EventHandler DocumentActiveContextChanged { add => AddLegacyEventHandler(value, WorkspaceEventType.DocumentActiveContextChanged); diff --git a/src/Workspaces/CoreTest/BatchFixAllProviderTests.cs b/src/Workspaces/CoreTest/BatchFixAllProviderTests.cs index 114544a2bfe27..1252e90ead361 100644 --- a/src/Workspaces/CoreTest/BatchFixAllProviderTests.cs +++ b/src/Workspaces/CoreTest/BatchFixAllProviderTests.cs @@ -25,26 +25,20 @@ namespace Microsoft.CodeAnalysis.UnitTests; public sealed class BatchFixAllProviderTests { [Fact] - public async Task TestDefaultSelectionNestedFixers() - { - var testCode = @" -class TestClass { - int field = [|0|]; -} -"; - var fixedCode = $@" -class TestClass {{ - int field = 1; -}} -"; - - // Three CodeFixProviders provide three actions - await new CSharpTest([[1], [2], [3]], nested: true) + public Task TestDefaultSelectionNestedFixers() + => new CSharpTest([[1], [2], [3]], nested: true) { - TestCode = testCode, - FixedCode = fixedCode, + TestCode = """ + class TestClass { + int field = [|0|]; + } + """, + FixedCode = $$""" + class TestClass { + int field = 1; + } + """, }.RunAsync(); - } [DiagnosticAnalyzer(LanguageNames.CSharp)] private sealed class LiteralZeroAnalyzer : DiagnosticAnalyzer diff --git a/src/Workspaces/CoreTest/CodeCleanup/AddMissingTokensTests.cs b/src/Workspaces/CoreTest/CodeCleanup/AddMissingTokensTests.cs index 2649e00938715..e9bc09675095c 100644 --- a/src/Workspaces/CoreTest/CodeCleanup/AddMissingTokensTests.cs +++ b/src/Workspaces/CoreTest/CodeCleanup/AddMissingTokensTests.cs @@ -20,2695 +20,2554 @@ namespace Microsoft.CodeAnalysis.UnitTests.CodeCleanup; public sealed class AddMissingTokensTests { [Fact] - public async Task MultipleLineIfStatementThen() - { - var code = @"[| - If True - Dim a = 1 - End If|]"; - - var expected = @" - If True Then - Dim a = 1 - End If"; - - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + public Task MultipleLineIfStatementThen() + => VerifyAsync(CreateMethod(""" + [| + If True + Dim a = 1 + End If|] + """), CreateMethod(""" + + If True Then + Dim a = 1 + End If + """)); [Fact] - public async Task TypeArgumentOf() - { - var code = @"[| - Dim a As List(Integer)|]"; - - var expected = @" - Dim a As List(Of Integer)"; + public Task TypeArgumentOf() + => VerifyAsync(CreateMethod(""" + [| + Dim a As List(Integer)|] + """), CreateMethod(""" - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + Dim a As List(Of Integer) + """)); [Fact] - public async Task TypeParameterOf() - { - var code = @"[|Class A(T) -End Class|]"; - - var expected = @"Class A(Of T) -End Class"; - - await VerifyAsync(code, expected); - } + public Task TypeParameterOf() + => VerifyAsync(""" + [|Class A(T) + End Class|] + """, """ + Class A(Of T) + End Class + """); [Fact] - public async Task MethodDeclaration() - { - var code = @"Class A - [|Sub Test - End Sub|] -End Class"; - - var expected = @"Class A - Sub Test() - End Sub -End Class"; - - await VerifyAsync(code, expected); - } + public Task MethodDeclaration() + => VerifyAsync(""" + Class A + [|Sub Test + End Sub|] + End Class + """, """ + Class A + Sub Test() + End Sub + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544318")] - public async Task MethodInvocation_TypeArgParens() - { - var code = @"[|Imports System -Imports System.Collections.Generic -Imports System.Linq -Imports System.Threading - -Module Program - Sub Main(args As String()) - [|Dim q = New List(Of Thread - - |]End Sub|]"; - - var expected = @"Imports System -Imports System.Collections.Generic -Imports System.Linq -Imports System.Threading - -Module Program - Sub Main(args As String()) - Dim q = New List(Of Thread - - End Sub"; - - await VerifyAsync(code, expected); - } + public Task MethodInvocation_TypeArgParens() + => VerifyAsync(""" + [|Imports System + Imports System.Collections.Generic + Imports System.Linq + Imports System.Threading + + Module Program + Sub Main(args As String()) + [|Dim q = New List(Of Thread + + |]End Sub|] + """, """ + Imports System + Imports System.Collections.Generic + Imports System.Linq + Imports System.Threading + + Module Program + Sub Main(args As String()) + Dim q = New List(Of Thread + + End Sub + """); [Fact] - public async Task MethodInvocation_Sub() - { - var code = @"Class A - Sub Test - [|Test|] - End Sub -End Class"; - - var expected = @"Class A - Sub Test - Test() - End Sub -End Class"; - - await VerifyAsync(code, expected); - } + public Task MethodInvocation_Sub() + => VerifyAsync(""" + Class A + Sub Test + [|Test|] + End Sub + End Class + """, """ + Class A + Sub Test + Test() + End Sub + End Class + """); [Fact] - public async Task MethodInvocation_Function() - { - var code = @"Class A - Function Test() As Integer - [|Test|] - Return 1 - End Function -End Class"; - - var expected = @"Class A - Function Test() As Integer - Test() - Return 1 - End Function -End Class"; - - await VerifyAsync(code, expected); - } + public Task MethodInvocation_Function() + => VerifyAsync(""" + Class A + Function Test() As Integer + [|Test|] + Return 1 + End Function + End Class + """, """ + Class A + Function Test() As Integer + Test() + Return 1 + End Function + End Class + """); [Fact] - public async Task IdentifierMethod_Return() - { - var code = @"Class A - Function Test() As Integer - Return [|Test2|] - End Function - - Function Test2() As Integer - Return 1 - End Function -End Class"; - - var expected = @"Class A - Function Test() As Integer - Return Test2() - End Function - - Function Test2() As Integer - Return 1 - End Function -End Class"; - - await VerifyAsync(code, expected); - } + public Task IdentifierMethod_Return() + => VerifyAsync(""" + Class A + Function Test() As Integer + Return [|Test2|] + End Function - [Fact] - public async Task IdentifierMethod_Assign() - { - var code = @"Class A - Function Test() As Integer - Dim a = [|Test2|] - Return 1 - End Function - - Function Test2() As Integer - Return 1 - End Function -End Class"; - - var expected = @"Class A - Function Test() As Integer - Dim a = Test2() - Return 1 - End Function - - Function Test2() As Integer - Return 1 - End Function -End Class"; - - await VerifyAsync(code, expected); - } + Function Test2() As Integer + Return 1 + End Function + End Class + """, """ + Class A + Function Test() As Integer + Return Test2() + End Function - [Fact] - public async Task IdentifierMethod_DotName_DoNotAdd() - { - var code = @"Class A - Function Test() As Integer - Dim a = [|Me.Test2|] - Return 1 - End Function - - Function Test2() As Integer - Return 1 - End Function -End Class"; - - var expected = @"Class A - Function Test() As Integer - Dim a = Me.Test2 - Return 1 - End Function - - Function Test2() As Integer - Return 1 - End Function -End Class"; - - await VerifyAsync(code, expected); - } + Function Test2() As Integer + Return 1 + End Function + End Class + """); [Fact] - public async Task MethodInvocation_DotName() - { - var code = @"Class A - Function Test() As Integer - [|Me.Test2|] - Return 1 - End Function - - Function Test2() As Integer - Return 1 - End Function -End Class"; - - var expected = @"Class A - Function Test() As Integer - Me.Test2() - Return 1 - End Function - - Function Test2() As Integer - Return 1 - End Function -End Class"; - - await VerifyAsync(code, expected); - } + public Task IdentifierMethod_Assign() + => VerifyAsync(""" + Class A + Function Test() As Integer + Dim a = [|Test2|] + Return 1 + End Function - [Fact] - public async Task MethodInvocation_Generic() - { - var code = @"Class A - Function Test() As Integer - [|Me.Test2(Of Integer)|] - Return 1 - End Function - - Function Test2(Of T) As Integer - Return 1 - End Function -End Class"; - - var expected = @"Class A - Function Test() As Integer - Me.Test2(Of Integer)() - Return 1 - End Function - - Function Test2(Of T) As Integer - Return 1 - End Function -End Class"; - - await VerifyAsync(code, expected); - } + Function Test2() As Integer + Return 1 + End Function + End Class + """, """ + Class A + Function Test() As Integer + Dim a = Test2() + Return 1 + End Function - [Fact] - public async Task MethodInvocation_Call() - { - var code = @"Class A - Function Test() As Integer - Call [|Me.Test2|] - Return 1 - End Function - - Function Test2() As Integer - Return 1 - End Function -End Class"; - - var expected = @"Class A - Function Test() As Integer - Call Me.Test2() - Return 1 - End Function - - Function Test2() As Integer - Return 1 - End Function -End Class"; - - await VerifyAsync(code, expected); - } + Function Test2() As Integer + Return 1 + End Function + End Class + """); [Fact] - public async Task EventHandler_AddressOf1() - { - var code = @"Class A - Sub EventMethod() - [|AddHandler TestEvent, AddressOf EventMethod|] - End Sub - - Public Event TestEvent() -End Class"; - - var expected = @"Class A - Sub EventMethod() - AddHandler TestEvent, AddressOf EventMethod - End Sub + public Task IdentifierMethod_DotName_DoNotAdd() + => VerifyAsync(""" + Class A + Function Test() As Integer + Dim a = [|Me.Test2|] + Return 1 + End Function - Public Event TestEvent() -End Class"; + Function Test2() As Integer + Return 1 + End Function + End Class + """, """ + Class A + Function Test() As Integer + Dim a = Me.Test2 + Return 1 + End Function - await VerifyAsync(code, expected); - } + Function Test2() As Integer + Return 1 + End Function + End Class + """); [Fact] - public async Task EventHandler_AddressOf2() - { - var code = @"Class A - Sub EventMethod() - [|RemoveHandler TestEvent, AddressOf EventMethod|] - End Sub - - Public Event TestEvent() -End Class"; - - var expected = @"Class A - Sub EventMethod() - RemoveHandler TestEvent, AddressOf EventMethod - End Sub - - Public Event TestEvent() -End Class"; + public Task MethodInvocation_DotName() + => VerifyAsync(""" + Class A + Function Test() As Integer + [|Me.Test2|] + Return 1 + End Function - await VerifyAsync(code, expected); - } + Function Test2() As Integer + Return 1 + End Function + End Class + """, """ + Class A + Function Test() As Integer + Me.Test2() + Return 1 + End Function - [Fact] - public async Task Delegate_AddressOf() - { - var code = @"Class A - Sub Method() - [|Dim a As Action = New Action(AddressOf Method)|] - End Sub -End Class"; - - var expected = @"Class A - Sub Method() - Dim a As Action = New Action(AddressOf Method) - End Sub -End Class"; - - await VerifyAsync(code, expected); - } + Function Test2() As Integer + Return 1 + End Function + End Class + """); [Fact] - public async Task EventDeclaration() - { - var code = @"Class A - Sub EventMethod() - [|RaiseEvent TestEvent|] - End Sub - - Public Event TestEvent() -End Class"; - - var expected = @"Class A - Sub EventMethod() - RaiseEvent TestEvent() - End Sub + public Task MethodInvocation_Generic() + => VerifyAsync(""" + Class A + Function Test() As Integer + [|Me.Test2(Of Integer)|] + Return 1 + End Function - Public Event TestEvent() -End Class"; + Function Test2(Of T) As Integer + Return 1 + End Function + End Class + """, """ + Class A + Function Test() As Integer + Me.Test2(Of Integer)() + Return 1 + End Function - await VerifyAsync(code, expected); - } + Function Test2(Of T) As Integer + Return 1 + End Function + End Class + """); [Fact] - public async Task RaiseEvent() - { - var code = @"Class A - Sub EventMethod() - RaiseEvent TestEvent - End Sub - - [|Public Event TestEvent|] -End Class"; - - var expected = @"Class A - Sub EventMethod() - RaiseEvent TestEvent - End Sub + public Task MethodInvocation_Call() + => VerifyAsync(""" + Class A + Function Test() As Integer + Call [|Me.Test2|] + Return 1 + End Function - Public Event TestEvent() -End Class"; + Function Test2() As Integer + Return 1 + End Function + End Class + """, """ + Class A + Function Test() As Integer + Call Me.Test2() + Return 1 + End Function - await VerifyAsync(code, expected); - } + Function Test2() As Integer + Return 1 + End Function + End Class + """); [Fact] - public async Task DelegateInvocation() - { - var code = @" - Dim a As Action - [|a|]"; - - var expected = @" - Dim a As Action - a()"; - - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + public Task EventHandler_AddressOf1() + => VerifyAsync(""" + Class A + Sub EventMethod() + [|AddHandler TestEvent, AddressOf EventMethod|] + End Sub + + Public Event TestEvent() + End Class + """, """ + Class A + Sub EventMethod() + AddHandler TestEvent, AddressOf EventMethod + End Sub + + Public Event TestEvent() + End Class + """); [Fact] - public async Task Attribute() - { - var code = @"[| -Class C(Of T) - Sub Main - Dim a = {1, 2, 3} - End Sub -End Class|]"; - - var expected = @" -Class C(Of T) - Sub Main() - Dim a = {1, 2, 3} - End Sub -End Class"; - - await VerifyAsync(code, expected); - } + public Task EventHandler_AddressOf2() + => VerifyAsync(""" + Class A + Sub EventMethod() + [|RemoveHandler TestEvent, AddressOf EventMethod|] + End Sub + + Public Event TestEvent() + End Class + """, """ + Class A + Sub EventMethod() + RemoveHandler TestEvent, AddressOf EventMethod + End Sub + + Public Event TestEvent() + End Class + """); [Fact] - public async Task ObjectCreation() - { - var code = @"[|Module Program - Sub Main(args As String()) - Dim x As New ClassInNewFile - Dim c As CustomClass = New CustomClass(""constructor"") - End Sub -End Module - -Friend Class CustomClass - Sub New(p1 As String) - End Sub -End Class - -Class ClassInNewFile -End Class|]"; - - var expected = @"Module Program - Sub Main(args As String()) - Dim x As New ClassInNewFile - Dim c As CustomClass = New CustomClass(""constructor"") - End Sub -End Module - -Friend Class CustomClass - Sub New(p1 As String) - End Sub -End Class - -Class ClassInNewFile -End Class"; - - await VerifyAsync(code, expected); - } + public Task Delegate_AddressOf() + => VerifyAsync(""" + Class A + Sub Method() + [|Dim a As Action = New Action(AddressOf Method)|] + End Sub + End Class + """, """ + Class A + Sub Method() + Dim a As Action = New Action(AddressOf Method) + End Sub + End Class + """); [Fact] - public async Task Constructor() - { - var code = @"[|Class C - Sub New - End Sub -End Class|]"; - - var expected = @"Class C - Sub New() - End Sub -End Class"; - - await VerifyAsync(code, expected); - } + public Task EventDeclaration() + => VerifyAsync(""" + Class A + Sub EventMethod() + [|RaiseEvent TestEvent|] + End Sub + + Public Event TestEvent() + End Class + """, """ + Class A + Sub EventMethod() + RaiseEvent TestEvent() + End Sub + + Public Event TestEvent() + End Class + """); [Fact] - public async Task DeclareStatement() - { - var code = @"[|Class C - Declare Function getUserName Lib ""advapi32.dll"" Alias ""GetUserNameA"" -End Class|]"; - - var expected = @"Class C - Declare Function getUserName Lib ""advapi32.dll"" Alias ""GetUserNameA"" () -End Class"; - - await VerifyAsync(code, expected); - } + public Task RaiseEvent() + => VerifyAsync(""" + Class A + Sub EventMethod() + RaiseEvent TestEvent + End Sub + + [|Public Event TestEvent|] + End Class + """, """ + Class A + Sub EventMethod() + RaiseEvent TestEvent + End Sub + + Public Event TestEvent() + End Class + """); [Fact] - public async Task DelegateStatement() - { - var code = @"[|Class C - Delegate Sub Test -End Class|]"; + public Task DelegateInvocation() + => VerifyAsync(CreateMethod(""" - var expected = @"Class C - Delegate Sub Test() -End Class"; + Dim a As Action + [|a|] + """), CreateMethod(""" - await VerifyAsync(code, expected); - } + Dim a As Action + a() + """)); [Fact] - public async Task MethodStatementWithComment() - { - var code = @"[|Class C - [|Sub Test ' test - End Sub|] -End Class|]"; - - var expected = @"Class C - Sub Test() ' test - End Sub -End Class"; - - await VerifyAsync(code, expected); - } + public Task Attribute() + => VerifyAsync(""" + [| + Class C(Of T) + Sub Main + Dim a = {1, 2, 3} + End Sub + End Class|] + """, """ + + Class C(Of T) + Sub Main() + Dim a = {1, 2, 3} + End Sub + End Class + """); [Fact] - public async Task MultipleLineIfStatementThenWithComment() - { - var code = @"[| - If True ' test - Dim a = 1 - End If|]"; + public Task ObjectCreation() + => VerifyAsync(""" + [|Module Program + Sub Main(args As String()) + Dim x As New ClassInNewFile + Dim c As CustomClass = New CustomClass("constructor") + End Sub + End Module + + Friend Class CustomClass + Sub New(p1 As String) + End Sub + End Class + + Class ClassInNewFile + End Class|] + """, """ + Module Program + Sub Main(args As String()) + Dim x As New ClassInNewFile + Dim c As CustomClass = New CustomClass("constructor") + End Sub + End Module + + Friend Class CustomClass + Sub New(p1 As String) + End Sub + End Class + + Class ClassInNewFile + End Class + """); - var expected = @" - If True Then ' test - Dim a = 1 - End If"; - - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + [Fact] + public Task Constructor() + => VerifyAsync(""" + [|Class C + Sub New + End Sub + End Class|] + """, """ + Class C + Sub New() + End Sub + End Class + """); [Fact] - public async Task TypeArgumentOf_Comment_DoNotAdd() - { - var code = @"[| - Dim a As List( ' test - Integer)|]"; + public Task DeclareStatement() + => VerifyAsync(""" + [|Class C + Declare Function getUserName Lib "advapi32.dll" Alias "GetUserNameA" + End Class|] + """, """ + Class C + Declare Function getUserName Lib "advapi32.dll" Alias "GetUserNameA" () + End Class + """); - var expected = @" - Dim a As List( ' test - Integer)"; + [Fact] + public Task DelegateStatement() + => VerifyAsync(""" + [|Class C + Delegate Sub Test + End Class|] + """, """ + Class C + Delegate Sub Test() + End Class + """); - // parser doesn't recognize the broken list as Type Argument List - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + [Fact] + public Task MethodStatementWithComment() + => VerifyAsync(""" + [|Class C + [|Sub Test ' test + End Sub|] + End Class|] + """, """ + Class C + Sub Test() ' test + End Sub + End Class + """); [Fact] - public async Task TypeParameterOf_Comment() - { - var code = @"[|Class A( ' test - T) -End Class|]"; + public Task MultipleLineIfStatementThenWithComment() + => VerifyAsync(CreateMethod(""" + [| + If True ' test + Dim a = 1 + End If|] + """), CreateMethod(""" + + If True Then ' test + Dim a = 1 + End If + """)); - var expected = @"Class A(Of ' test - T) -End Class"; + [Fact] + public Task TypeArgumentOf_Comment_DoNotAdd() + => VerifyAsync(CreateMethod(""" + [| + Dim a As List( ' test + Integer)|] + """), CreateMethod(""" - await VerifyAsync(code, expected); - } + Dim a As List( ' test + Integer) + """)); [Fact] - public async Task MethodInvocation_Function_Comment() - { - var code = @"Class A - Function Test() As Integer - [|Test ' test|] - Return 1 - End Function -End Class"; - - var expected = @"Class A - Function Test() As Integer - Test() ' test - Return 1 - End Function -End Class"; - - await VerifyAsync(code, expected); - } + public Task TypeParameterOf_Comment() + => VerifyAsync(""" + [|Class A( ' test + T) + End Class|] + """, """ + Class A(Of ' test + T) + End Class + """); [Fact] - public async Task IdentifierMethod_Return_Comment() - { - var code = @"Class A - Function Test() As Integer - Return [|Test2 ' test|] - End Function - - Function Test2() As Integer - Return 1 - End Function -End Class"; - - var expected = @"Class A - Function Test() As Integer - Return Test2() ' test - End Function - - Function Test2() As Integer - Return 1 - End Function -End Class"; - - await VerifyAsync(code, expected); - } + public Task MethodInvocation_Function_Comment() + => VerifyAsync(""" + Class A + Function Test() As Integer + [|Test ' test|] + Return 1 + End Function + End Class + """, """ + Class A + Function Test() As Integer + Test() ' test + Return 1 + End Function + End Class + """); [Fact] - public async Task ImplementsClause() - { - var code = @"Class Program - Implements I - [|Public Sub Method() Implements I.Method - End Sub|] -End Class - -Interface I - Sub Method() -End Interface"; - - var expected = @"Class Program - Implements I - Public Sub Method() Implements I.Method - End Sub -End Class - -Interface I - Sub Method() -End Interface"; - - await VerifyAsync(code, expected); - } + public Task IdentifierMethod_Return_Comment() + => VerifyAsync(""" + Class A + Function Test() As Integer + Return [|Test2 ' test|] + End Function - [Fact] - public async Task OperatorStatement() - { - var code = @"[|Public Structure abc - Public Shared Operator And(ByVal x As abc, ByVal y As abc) As abc - Dim r As New abc - ' Insert code to calculate And of x and y. - Return r - End Operator -End Structure|]"; - - var expected = @"Public Structure abc - Public Shared Operator And(ByVal x As abc, ByVal y As abc) As abc - Dim r As New abc - ' Insert code to calculate And of x and y. - Return r - End Operator -End Structure"; - - await VerifyAsync(code, expected); - } + Function Test2() As Integer + Return 1 + End Function + End Class + """, """ + Class A + Function Test() As Integer + Return Test2() ' test + End Function + + Function Test2() As Integer + Return 1 + End Function + End Class + """); [Fact] - public async Task PropertyAndAccessorStatement() - { - var code = @"[|Class Class1 - Private propertyValue As String - Public Property prop1() As String - Get - Return propertyValue - End Get - Set(ByVal value As String) - propertyValue = value - End Set - End Property -End Class|]"; - - var expected = @"Class Class1 - Private propertyValue As String - Public Property prop1() As String - Get - Return propertyValue - End Get - Set(ByVal value As String) - propertyValue = value - End Set - End Property -End Class"; - - await VerifyAsync(code, expected); - } + public Task ImplementsClause() + => VerifyAsync(""" + Class Program + Implements I + [|Public Sub Method() Implements I.Method + End Sub|] + End Class + + Interface I + Sub Method() + End Interface + """, """ + Class Program + Implements I + Public Sub Method() Implements I.Method + End Sub + End Class + + Interface I + Sub Method() + End Interface + """); [Fact] - public async Task LambdaExpression() - { - var code = @"[|Class Class1 - Dim f as Action = Sub() - End Sub -End Class|]"; + public Task OperatorStatement() + => VerifyAsync(""" + [|Public Structure abc + Public Shared Operator And(ByVal x As abc, ByVal y As abc) As abc + Dim r As New abc + ' Insert code to calculate And of x and y. + Return r + End Operator + End Structure|] + """, """ + Public Structure abc + Public Shared Operator And(ByVal x As abc, ByVal y As abc) As abc + Dim r As New abc + ' Insert code to calculate And of x and y. + Return r + End Operator + End Structure + """); - var expected = @"Class Class1 - Dim f as Action = Sub() - End Sub -End Class"; + [Fact] + public Task PropertyAndAccessorStatement() + => VerifyAsync(""" + [|Class Class1 + Private propertyValue As String + Public Property prop1() As String + Get + Return propertyValue + End Get + Set(ByVal value As String) + propertyValue = value + End Set + End Property + End Class|] + """, """ + Class Class1 + Private propertyValue As String + Public Property prop1() As String + Get + Return propertyValue + End Get + Set(ByVal value As String) + propertyValue = value + End Set + End Property + End Class + """); - await VerifyAsync(code, expected); - } + [Fact] + public Task LambdaExpression() + => VerifyAsync(""" + [|Class Class1 + Dim f as Action = Sub() + End Sub + End Class|] + """, """ + Class Class1 + Dim f as Action = Sub() + End Sub + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544225")] - public async Task StructuredTrivia_Expression_DoNotCrash() - { - var code = @"[|#Const Goo1 = 1 -#Const Goo2 = 2 -#If Goo1 Then -#ElseIf Goo2 Then -#Else -#End If|]"; - var expected = @"#Const Goo1 = 1 -#Const Goo2 = 2 -#If Goo1 Then -#ElseIf Goo2 Then -#Else -#End If"; - await VerifyAsync(code, expected); - } + public Task StructuredTrivia_Expression_DoNotCrash() + => VerifyAsync(""" + [|#Const Goo1 = 1 + #Const Goo2 = 2 + #If Goo1 Then + #ElseIf Goo2 Then + #Else + #End If|] + """, """ + #Const Goo1 = 1 + #Const Goo2 = 2 + #If Goo1 Then + #ElseIf Goo2 Then + #Else + #End If + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544169")] - public async Task EventStatement_AsClause() - { - var code = @"[|Imports System.ComponentModel -Class Goo - Public Event PropertyChanged As PropertyChangedEventHandler -End Class|]"; - var expected = @"Imports System.ComponentModel -Class Goo - Public Event PropertyChanged As PropertyChangedEventHandler -End Class"; - - await VerifyAsync(code, expected); - } + public Task EventStatement_AsClause() + => VerifyAsync(""" + [|Imports System.ComponentModel + Class Goo + Public Event PropertyChanged As PropertyChangedEventHandler + End Class|] + """, """ + Imports System.ComponentModel + Class Goo + Public Event PropertyChanged As PropertyChangedEventHandler + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544167")] - public async Task InvocationExpression_NoParenthesesForPredefinedCastExpression() - { - var code = @"[|Class Program - Sub Main(args As String()) - CInt(5) - End Sub -End Class|]"; - var expected = @"Class Program - Sub Main(args As String()) - CInt(5) - End Sub -End Class"; - - await VerifyAsync(code, expected); - } + public Task InvocationExpression_NoParenthesesForPredefinedCastExpression() + => VerifyAsync(""" + [|Class Program + Sub Main(args As String()) + CInt(5) + End Sub + End Class|] + """, """ + Class Program + Sub Main(args As String()) + CInt(5) + End Sub + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544178")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544317")] - public async Task ObjectCreationExpression() - { - var code = @"[|Class C - Function F() As C - Return New C - End Function -End Class|]"; - var expected = @"Class C - Function F() As C - Return New C - End Function -End Class"; - - await VerifyAsync(code, expected); - } + public Task ObjectCreationExpression() + => VerifyAsync(""" + [|Class C + Function F() As C + Return New C + End Function + End Class|] + """, """ + Class C + Function F() As C + Return New C + End Function + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544317")] - public async Task ObjectCreationExpression_Initializer() - { - var code = @"[|Public Class SomeClass - Public goo As Integer - - Sub SomeSub() - [|Dim c = New SomeClass With {.goo = 23}|] - End Sub -End Class|]"; - var expected = @"Public Class SomeClass - Public goo As Integer - - Sub SomeSub() - Dim c = New SomeClass With {.goo = 23} - End Sub -End Class"; - - await VerifyAsync(code, expected); - } + public Task ObjectCreationExpression_Initializer() + => VerifyAsync(""" + [|Public Class SomeClass + Public goo As Integer + + Sub SomeSub() + [|Dim c = New SomeClass With {.goo = 23}|] + End Sub + End Class|] + """, """ + Public Class SomeClass + Public goo As Integer + + Sub SomeSub() + Dim c = New SomeClass With {.goo = 23} + End Sub + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544178")] - public async Task ObjectCreationExpression_GenericName() - { - var code = @"[|Imports System - -Module Program - Sub Main(args As String()) - Dim q = New List(Of Integer - End Sub -End Module|]"; - - var expected = @"Imports System - -Module Program - Sub Main(args As String()) - Dim q = New List(Of Integer - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task ObjectCreationExpression_GenericName() + => VerifyAsync(""" + [|Imports System + + Module Program + Sub Main(args As String()) + Dim q = New List(Of Integer + End Sub + End Module|] + """, """ + Imports System + + Module Program + Sub Main(args As String()) + Dim q = New List(Of Integer + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544178")] - public async Task ObjectCreationExpression_AsNewClause() - { - var code = @"[|Class C - Dim a As New C -End Class|]"; - var expected = @"Class C - Dim a As New C -End Class"; - - await VerifyAsync(code, expected); - } + public Task ObjectCreationExpression_AsNewClause() + => VerifyAsync(""" + [|Class C + Dim a As New C + End Class|] + """, """ + Class C + Dim a As New C + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544301")] - public async Task ContinueStatement_While() - { - var code = @"Module M - Sub S() - [|While True - Continue - End While|] - End Sub -End Module"; - var expected = @"Module M - Sub S() - While True - Continue While - End While - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task ContinueStatement_While() + => VerifyAsync(""" + Module M + Sub S() + [|While True + Continue + End While|] + End Sub + End Module + """, """ + Module M + Sub S() + While True + Continue While + End While + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544301")] - public async Task ContinueStatement_For() - { - var code = @"Module M - Sub S() - [|For i = 1 to 10 - Continue - Next|] - End Sub -End Module"; - var expected = @"Module M - Sub S() - For i = 1 to 10 - Continue For - Next - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task ContinueStatement_For() + => VerifyAsync(""" + Module M + Sub S() + [|For i = 1 to 10 + Continue + Next|] + End Sub + End Module + """, """ + Module M + Sub S() + For i = 1 to 10 + Continue For + Next + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544380")] - public async Task IfDirective() - { - var code = @"[|#If VBC_VER >= 9.0 - -Class C -End Class|]"; - var expected = @"#If VBC_VER >= 9.0 Then + public Task IfDirective() + => VerifyAsync(""" + [|#If VBC_VER >= 9.0 -Class C -End Class"; + Class C + End Class|] + """, """ + #If VBC_VER >= 9.0 Then - await VerifyAsync(code, expected); - } + Class C + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544386")] - public async Task NamedFieldInitializer() - { - var code = @"[|Class S - Public Sub Goo() - End Sub - Property X - Sub test() - Dim x = New S With {.X = 0,.Goo} - End Sub -End Class|]"; - var expected = @"Class S - Public Sub Goo() - End Sub - Property X - Sub test() - Dim x = New S With {.X = 0, .Goo} - End Sub -End Class"; - - await VerifyAsync(code, expected); - } + public Task NamedFieldInitializer() + => VerifyAsync(""" + [|Class S + Public Sub Goo() + End Sub + Property X + Sub test() + Dim x = New S With {.X = 0,.Goo} + End Sub + End Class|] + """, """ + Class S + Public Sub Goo() + End Sub + Property X + Sub test() + Dim x = New S With {.X = 0, .Goo} + End Sub + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544526")] - public async Task DoNotCrash_ImplementsStatement() - { - var code = @"[|Class C - Sub Main() - Implements IDisposable.Dispose - End Sub -End Class|]"; - var expected = @"Class C - Sub Main() - Implements IDisposable.Dispose - End Sub -End Class"; - - await VerifyAsync(code, expected); - } + public Task DoNotCrash_ImplementsStatement() + => VerifyAsync(""" + [|Class C + Sub Main() + Implements IDisposable.Dispose + End Sub + End Class|] + """, """ + Class C + Sub Main() + Implements IDisposable.Dispose + End Sub + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544525")] - public async Task AccessorStatement_AddRemoveHandler_RaiseEvent() - { - var code = @"[|Class C - Public Custom Event E1 As Action - AddHandler - End AddHandler - RemoveHandler - End RemoveHandler - RaiseEvent - End RaiseEvent - End Event -End Class|]"; - var expected = @"Class C - Public Custom Event E1 As Action - AddHandler() - End AddHandler - RemoveHandler() - End RemoveHandler - RaiseEvent() - End RaiseEvent - End Event -End Class"; - - await VerifyAsync(code, expected); - } + public Task AccessorStatement_AddRemoveHandler_RaiseEvent() + => VerifyAsync(""" + [|Class C + Public Custom Event E1 As Action + AddHandler + End AddHandler + RemoveHandler + End RemoveHandler + RaiseEvent + End RaiseEvent + End Event + End Class|] + """, """ + Class C + Public Custom Event E1 As Action + AddHandler() + End AddHandler + RemoveHandler() + End RemoveHandler + RaiseEvent() + End RaiseEvent + End Event + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545176")] - public async Task CallStatement_Lambda() - { - var code = @"[|Module Program - Sub Main() - Call Sub() Console.WriteLine(1) - End Sub -End Module|]"; - var expected = @"Module Program - Sub Main() - Call Sub() Console.WriteLine(1) - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task CallStatement_Lambda() + => VerifyAsync(""" + [|Module Program + Sub Main() + Call Sub() Console.WriteLine(1) + End Sub + End Module|] + """, """ + Module Program + Sub Main() + Call Sub() Console.WriteLine(1) + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545256")] - public async Task HandlesClauseItem_DoNotAddParentheses() - { - var code = @"[|Structure s1 - Sub Goo() Handles Me.Goo - - End Sub -End Structure|]"; - var expected = @"Structure s1 - Sub Goo() Handles Me.Goo - - End Sub -End Structure"; - - await VerifyAsync(code, expected); - } + public Task HandlesClauseItem_DoNotAddParentheses() + => VerifyAsync(""" + [|Structure s1 + Sub Goo() Handles Me.Goo + + End Sub + End Structure|] + """, """ + Structure s1 + Sub Goo() Handles Me.Goo + + End Sub + End Structure + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545380")] - public async Task DoNotAddParenthesesInForEachControlVariable() - { - var code = @"[|Module Module1 - Sub Main() - For Each goo in {} - End Sub - - Sub Goo() - End Sub -End Module|]"; - var expected = @"Module Module1 - Sub Main() - For Each goo in {} - End Sub - - Sub Goo() - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task DoNotAddParenthesesInForEachControlVariable() + => VerifyAsync(""" + [|Module Module1 + Sub Main() + For Each goo in {} + End Sub + + Sub Goo() + End Sub + End Module|] + """, """ + Module Module1 + Sub Main() + For Each goo in {} + End Sub + + Sub Goo() + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545380")] - public async Task DoNotAddParenthesesInForControlVariable() - { - var code = @"[|Module Module1 - Sub Main() - For goo to - End Sub - - Sub Goo() - End Sub -End Module|]"; - var expected = @"Module Module1 - Sub Main() - For goo to - End Sub - - Sub Goo() - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task DoNotAddParenthesesInForControlVariable() + => VerifyAsync(""" + [|Module Module1 + Sub Main() + For goo to + End Sub + + Sub Goo() + End Sub + End Module|] + """, """ + Module Module1 + Sub Main() + For goo to + End Sub + + Sub Goo() + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545483")] - public async Task DoNotAddParenthesesForMissingName() - { - var code = @"[|Class C - Public Overrides Function|]"; - var expected = @"Class C - Public Overrides Function"; - - await VerifyAsync(code, expected); - } + public Task DoNotAddParenthesesForMissingName() + => VerifyAsync(""" + [|Class C + Public Overrides Function|] + """, """ + Class C + Public Overrides Function + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545483")] - public async Task CombinedDelegates() - { - var code = @"[|Imports System -Class A - Public Shared Operator +(x As A, y As A) As Action - End Operator - Shared Sub Main() - Dim x As New A - Call x + x - End Sub -End Class|]"; - var expected = @"Imports System -Class A - Public Shared Operator +(x As A, y As A) As Action - End Operator - Shared Sub Main() - Dim x As New A - Call x + x - End Sub -End Class"; - - await VerifyAsync(code, expected); - } + public Task CombinedDelegates() + => VerifyAsync(""" + [|Imports System + Class A + Public Shared Operator +(x As A, y As A) As Action + End Operator + Shared Sub Main() + Dim x As New A + Call x + x + End Sub + End Class|] + """, """ + Imports System + Class A + Public Shared Operator +(x As A, y As A) As Action + End Operator + Shared Sub Main() + Dim x As New A + Call x + x + End Sub + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546581")] - public async Task ThenOmittedWithSurroundingErrors() - { - var code = @"[| - If True OrElse|]"; - var expected = @" - If True OrElse"; + public Task ThenOmittedWithSurroundingErrors() + => VerifyAsync(CreateMethod(""" + [| + If True OrElse|] + """), CreateMethod(""" - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + If True OrElse + """)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546581")] - public async Task ThenOmittedWithSurroundingErrors1() - { - var code = @"[| - If True|]"; - var expected = @" - If True Then"; + public Task ThenOmittedWithSurroundingErrors1() + => VerifyAsync(CreateMethod(""" + [| + If True|] + """), CreateMethod(""" - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + If True Then + """)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546797")] - public async Task ParenthesisWithLineContinuation() - { - var code = @"[| - System.Diagnostics.Debug.Assert _ (True)|]"; - var expected = @" - System.Diagnostics.Debug.Assert _ (True)"; - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + public Task ParenthesisWithLineContinuation() + => VerifyAsync(CreateMethod(""" + [| + System.Diagnostics.Debug.Assert _ (True)|] + """), CreateMethod(""" + + System.Diagnostics.Debug.Assert _ (True) + """)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546806")] - public async Task ThenWithLineContinuation() - { - var code = @"[| -#If Condition _ Then - ' blah -#End If|]"; - var expected = @" -#If Condition _ Then - ' blah -#End If"; - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + public Task ThenWithLineContinuation() + => VerifyAsync(CreateMethod(""" + [| + #If Condition _ Then + ' blah + #End If|] + """), CreateMethod(""" + + #If Condition _ Then + ' blah + #End If + """)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531278")] - public async Task ThenInIfDirective() - { - var code = @"#Const ccConst = 0 -[|#If ccConst -#End If|] -Imports System -Imports System.Collections.Generic -Imports System.Linq -Module Program - Sub Main(args As String()) - End Sub -End Module"; - var expected = @"#Const ccConst = 0 -#If ccConst Then -#End If -Imports System -Imports System.Collections.Generic -Imports System.Linq -Module Program - Sub Main(args As String()) - End Sub -End Module"; - await VerifyAsync(code, expected); - } + public Task ThenInIfDirective() + => VerifyAsync(""" + #Const ccConst = 0 + [|#If ccConst + #End If|] + Imports System + Imports System.Collections.Generic + Imports System.Linq + Module Program + Sub Main(args As String()) + End Sub + End Module + """, """ + #Const ccConst = 0 + #If ccConst Then + #End If + Imports System + Imports System.Collections.Generic + Imports System.Linq + Module Program + Sub Main(args As String()) + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/607792")] - public async Task CaseKeywordInSelectStatement() - { - var code = @" -Module Program - Sub Main() -[| - Select 1 - End Select + public Task CaseKeywordInSelectStatement() + => VerifyAsync(""" - Dim z = Function() From x In """" - :Select 1 - End Select + Module Program + Sub Main() + [| + Select 1 + End Select - Dim z2 = Function() From x In """" : Select 1 - End Select -|] - End Sub -End Module"; + Dim z = Function() From x In "" + :Select 1 + End Select - var expected = @" -Module Program - Sub Main() + Dim z2 = Function() From x In "" : Select 1 + End Select + |] + End Sub + End Module + """, """ - Select Case 1 - End Select + Module Program + Sub Main() - Dim z = Function() From x In """" - : Select Case 1 - End Select + Select Case 1 + End Select - Dim z2 = Function() From x In """" : Select Case 1 - End Select + Dim z = Function() From x In "" + : Select Case 1 + End Select - End Sub -End Module"; + Dim z2 = Function() From x In "" : Select Case 1 + End Select - await VerifyAsync(code, expected); - } + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530789")] - public async Task Bug530789() - { - var code = @"Imports System -Module Program - Sub Main() - [|If True Then Console.WriteLine else If False Then Console.WriteLine else Console.writeline|] - End Sub -End Module"; - - var expected = @"Imports System -Module Program - Sub Main() - If True Then Console.WriteLine() else If False Then Console.WriteLine() else Console.writeline() - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task Bug530789() + => VerifyAsync(""" + Imports System + Module Program + Sub Main() + [|If True Then Console.WriteLine else If False Then Console.WriteLine else Console.writeline|] + End Sub + End Module + """, """ + Imports System + Module Program + Sub Main() + If True Then Console.WriteLine() else If False Then Console.WriteLine() else Console.writeline() + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530039")] - public async Task TestArraySyntax() - { - var code = @"[|Module TestMod -Sub Main() -Dim y As Object -Dim x As cls2(Of y.gettype()) -End Sub -End Module|]"; - - var expected = @"Module TestMod - Sub Main() - Dim y As Object - Dim x As cls2(Of y.gettype()) - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task TestArraySyntax() + => VerifyAsync(""" + [|Module TestMod + Sub Main() + Dim y As Object + Dim x As cls2(Of y.gettype()) + End Sub + End Module|] + """, """ + Module TestMod + Sub Main() + Dim y As Object + Dim x As cls2(Of y.gettype()) + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602932")] - public async Task TestAsyncFunctionWithoutAsClause() - { - var code = @"[| -Interface I - Function Goo() As System.Threading.Tasks.Task -End Interface - -Class Test - Implements I - - ' a. Basic - Async Function Goo1() - End Function - - ' b. With Trailing trivia - Async Function Goo2() ' Trailing - End Function + public Task TestAsyncFunctionWithoutAsClause() + => VerifyAsync(""" + [| + Interface I + Function Goo() As System.Threading.Tasks.Task + End Interface + + Class Test + Implements I + + ' a. Basic + Async Function Goo1() + End Function - ' c. Without Parenthesis - Async Function Goo4 - End Function + ' b. With Trailing trivia + Async Function Goo2() ' Trailing + End Function - ' d. With Implements/Handles clause - Async Function Goo5() Implements I.Goo - End Function + ' c. Without Parenthesis + Async Function Goo4 + End Function - ' e. With Implements/Handles clause with trivia - Async Function Goo6() Implements I.Goo ' Trailing - End Function + ' d. With Implements/Handles clause + Async Function Goo5() Implements I.Goo + End Function - ' f. Invalid Async Sub - Async Sub Goo7() - End Sub + ' e. With Implements/Handles clause with trivia + Async Function Goo6() Implements I.Goo ' Trailing + End Function - ' g. Without End Function - Async Function Goo3() + ' f. Invalid Async Sub + Async Sub Goo7() + End Sub - ' h. With End Function On SameLine - Async Function Goo4(ByVal x As Integer) End Function + ' g. Without End Function + Async Function Goo3() -End Class|]"; + ' h. With End Function On SameLine + Async Function Goo4(ByVal x As Integer) End Function - var expected = @" -Interface I - Function Goo() As System.Threading.Tasks.Task -End Interface + End Class|] + """, """ -Class Test - Implements I + Interface I + Function Goo() As System.Threading.Tasks.Task + End Interface - ' a. Basic - Async Function Goo1() As System.Threading.Tasks.Task - End Function + Class Test + Implements I - ' b. With Trailing trivia - Async Function Goo2() As System.Threading.Tasks.Task ' Trailing - End Function + ' a. Basic + Async Function Goo1() As System.Threading.Tasks.Task + End Function - ' c. Without Parenthesis - Async Function Goo4() As System.Threading.Tasks.Task - End Function + ' b. With Trailing trivia + Async Function Goo2() As System.Threading.Tasks.Task ' Trailing + End Function - ' d. With Implements/Handles clause - Async Function Goo5() As System.Threading.Tasks.Task Implements I.Goo - End Function + ' c. Without Parenthesis + Async Function Goo4() As System.Threading.Tasks.Task + End Function - ' e. With Implements/Handles clause with trivia - Async Function Goo6() As System.Threading.Tasks.Task Implements I.Goo ' Trailing - End Function + ' d. With Implements/Handles clause + Async Function Goo5() As System.Threading.Tasks.Task Implements I.Goo + End Function - ' f. Invalid Async Sub - Async Sub Goo7() - End Sub + ' e. With Implements/Handles clause with trivia + Async Function Goo6() As System.Threading.Tasks.Task Implements I.Goo ' Trailing + End Function - ' g. Without End Function - Async Function Goo3() As System.Threading.Tasks.Task + ' f. Invalid Async Sub + Async Sub Goo7() + End Sub - ' h. With End Function On SameLine - Async Function Goo4(ByVal x As Integer) As System.Threading.Tasks.Task End Function + ' g. Without End Function + Async Function Goo3() As System.Threading.Tasks.Task -End Class"; + ' h. With End Function On SameLine + Async Function Goo4(ByVal x As Integer) As System.Threading.Tasks.Task End Function - await VerifyAsync(code, expected); - } + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602932")] - public async Task TestAsyncFunctionWithoutAsClause_WithAddedImports() - { - var code = @"[| -Imports System -Imports System.Threading.Tasks + public Task TestAsyncFunctionWithoutAsClause_WithAddedImports() + => VerifyAsync(""" + [| + Imports System + Imports System.Threading.Tasks -Interface I - Function Goo() As Task -End Interface + Interface I + Function Goo() As Task + End Interface -Class Test - Implements I + Class Test + Implements I - ' a. Basic - Async Function Goo1() - End Function - - ' b. With Trailing trivia - Async Function Goo2() ' Trailing - End Function + ' a. Basic + Async Function Goo1() + End Function - ' c. Without Parenthesis - Async Function Goo4 - End Function + ' b. With Trailing trivia + Async Function Goo2() ' Trailing + End Function - ' d. With Implements/Handles clause - Async Function Goo5() Implements I.Goo - End Function + ' c. Without Parenthesis + Async Function Goo4 + End Function - ' e. With Implements/Handles clause with trivia - Async Function Goo6() Implements I.Goo ' Trailing - End Function + ' d. With Implements/Handles clause + Async Function Goo5() Implements I.Goo + End Function - ' f. Invalid Async Sub - Async Sub Goo7() - End Sub + ' e. With Implements/Handles clause with trivia + Async Function Goo6() Implements I.Goo ' Trailing + End Function - ' g. Without End Function - Async Function Goo3() + ' f. Invalid Async Sub + Async Sub Goo7() + End Sub - ' h. With End Function On SameLine - Async Function Goo4(ByVal x As Integer) End Function + ' g. Without End Function + Async Function Goo3() -End Class|]"; + ' h. With End Function On SameLine + Async Function Goo4(ByVal x As Integer) End Function - var expected = @" -Imports System -Imports System.Threading.Tasks + End Class|] + """, """ -Interface I - Function Goo() As Task -End Interface + Imports System + Imports System.Threading.Tasks -Class Test - Implements I + Interface I + Function Goo() As Task + End Interface - ' a. Basic - Async Function Goo1() As Task - End Function + Class Test + Implements I - ' b. With Trailing trivia - Async Function Goo2() As Task ' Trailing - End Function + ' a. Basic + Async Function Goo1() As Task + End Function - ' c. Without Parenthesis - Async Function Goo4() As Task - End Function + ' b. With Trailing trivia + Async Function Goo2() As Task ' Trailing + End Function - ' d. With Implements/Handles clause - Async Function Goo5() As Task Implements I.Goo - End Function + ' c. Without Parenthesis + Async Function Goo4() As Task + End Function - ' e. With Implements/Handles clause with trivia - Async Function Goo6() As Task Implements I.Goo ' Trailing - End Function + ' d. With Implements/Handles clause + Async Function Goo5() As Task Implements I.Goo + End Function - ' f. Invalid Async Sub - Async Sub Goo7() - End Sub + ' e. With Implements/Handles clause with trivia + Async Function Goo6() As Task Implements I.Goo ' Trailing + End Function - ' g. Without End Function - Async Function Goo3() As Task + ' f. Invalid Async Sub + Async Sub Goo7() + End Sub - ' h. With End Function On SameLine - Async Function Goo4(ByVal x As Integer) As Task End Function + ' g. Without End Function + Async Function Goo3() As Task -End Class"; + ' h. With End Function On SameLine + Async Function Goo4(ByVal x As Integer) As Task End Function - await VerifyAsync(code, expected); - } + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602932")] - public async Task TestIteratorFunctionWithoutAsClause() - { - var code = @"[| -Interface I - Function Goo() As System.Collections.IEnumerable -End Interface - -Class Test - Implements I - - ' a. Basic - Iterator Function Goo1() - End Function - - ' b. With Trailing trivia - Iterator Function Goo2() ' Trailing - End Function + public Task TestIteratorFunctionWithoutAsClause() + => VerifyAsync(""" + [| + Interface I + Function Goo() As System.Collections.IEnumerable + End Interface + + Class Test + Implements I + + ' a. Basic + Iterator Function Goo1() + End Function - ' c. Without Parenthesis - Iterator Function Goo4 - End Function + ' b. With Trailing trivia + Iterator Function Goo2() ' Trailing + End Function - ' d. With Implements/Handles clause - Iterator Function Goo5() Implements I.Goo - End Function + ' c. Without Parenthesis + Iterator Function Goo4 + End Function - ' e. With Implements/Handles clause with trivia - Iterator Function Goo6() Implements I.Goo ' Trailing - End Function + ' d. With Implements/Handles clause + Iterator Function Goo5() Implements I.Goo + End Function - ' f. Invalid Iterator Sub - Iterator Sub Goo7() - End Sub + ' e. With Implements/Handles clause with trivia + Iterator Function Goo6() Implements I.Goo ' Trailing + End Function - ' g. Without End Function - Iterator Function Goo3() + ' f. Invalid Iterator Sub + Iterator Sub Goo7() + End Sub -End Class|]"; + ' g. Without End Function + Iterator Function Goo3() - var expected = @" -Interface I - Function Goo() As System.Collections.IEnumerable -End Interface + End Class|] + """, """ -Class Test - Implements I + Interface I + Function Goo() As System.Collections.IEnumerable + End Interface - ' a. Basic - Iterator Function Goo1() As System.Collections.IEnumerable - End Function + Class Test + Implements I - ' b. With Trailing trivia - Iterator Function Goo2() As System.Collections.IEnumerable ' Trailing - End Function + ' a. Basic + Iterator Function Goo1() As System.Collections.IEnumerable + End Function - ' c. Without Parenthesis - Iterator Function Goo4() As System.Collections.IEnumerable - End Function + ' b. With Trailing trivia + Iterator Function Goo2() As System.Collections.IEnumerable ' Trailing + End Function - ' d. With Implements/Handles clause - Iterator Function Goo5() As System.Collections.IEnumerable Implements I.Goo - End Function + ' c. Without Parenthesis + Iterator Function Goo4() As System.Collections.IEnumerable + End Function - ' e. With Implements/Handles clause with trivia - Iterator Function Goo6() As System.Collections.IEnumerable Implements I.Goo ' Trailing - End Function + ' d. With Implements/Handles clause + Iterator Function Goo5() As System.Collections.IEnumerable Implements I.Goo + End Function - ' f. Invalid Iterator Sub - Iterator Sub Goo7() - End Sub + ' e. With Implements/Handles clause with trivia + Iterator Function Goo6() As System.Collections.IEnumerable Implements I.Goo ' Trailing + End Function - ' g. Without End Function - Iterator Function Goo3() As System.Collections.IEnumerable + ' f. Invalid Iterator Sub + Iterator Sub Goo7() + End Sub -End Class"; + ' g. Without End Function + Iterator Function Goo3() As System.Collections.IEnumerable - await VerifyAsync(code, expected); - } + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602932")] - public async Task TestIteratorFunctionWithoutAsClause_WithAddedImports() - { - var code = @"[| -Imports System -Imports System.Collections -Imports System.Collections.Generic - -Interface I - Function Goo() As System.Collections.IEnumerable -End Interface - -Class Test - Implements I - - ' a. Basic - Iterator Function Goo1() - End Function - - ' b. With Trailing trivia - Iterator Function Goo2() ' Trailing - End Function + public Task TestIteratorFunctionWithoutAsClause_WithAddedImports() + => VerifyAsync(""" + [| + Imports System + Imports System.Collections + Imports System.Collections.Generic + + Interface I + Function Goo() As System.Collections.IEnumerable + End Interface + + Class Test + Implements I + + ' a. Basic + Iterator Function Goo1() + End Function - ' c. Without Parenthesis - Iterator Function Goo4 - End Function + ' b. With Trailing trivia + Iterator Function Goo2() ' Trailing + End Function - ' d. With Implements/Handles clause - Iterator Function Goo5() Implements I.Goo - End Function + ' c. Without Parenthesis + Iterator Function Goo4 + End Function - ' e. With Implements/Handles clause with trivia - Iterator Function Goo6() Implements I.Goo ' Trailing - End Function + ' d. With Implements/Handles clause + Iterator Function Goo5() Implements I.Goo + End Function - ' f. Invalid Iterator Sub - Iterator Sub Goo7() - End Sub + ' e. With Implements/Handles clause with trivia + Iterator Function Goo6() Implements I.Goo ' Trailing + End Function - ' g. Without End Function - Iterator Function Goo3() + ' f. Invalid Iterator Sub + Iterator Sub Goo7() + End Sub -End Class|]"; + ' g. Without End Function + Iterator Function Goo3() - var expected = @" -Imports System -Imports System.Collections -Imports System.Collections.Generic + End Class|] + """, """ -Interface I - Function Goo() As System.Collections.IEnumerable -End Interface + Imports System + Imports System.Collections + Imports System.Collections.Generic -Class Test - Implements I + Interface I + Function Goo() As System.Collections.IEnumerable + End Interface - ' a. Basic - Iterator Function Goo1() As IEnumerable - End Function + Class Test + Implements I - ' b. With Trailing trivia - Iterator Function Goo2() As IEnumerable ' Trailing - End Function + ' a. Basic + Iterator Function Goo1() As IEnumerable + End Function - ' c. Without Parenthesis - Iterator Function Goo4() As IEnumerable - End Function + ' b. With Trailing trivia + Iterator Function Goo2() As IEnumerable ' Trailing + End Function - ' d. With Implements/Handles clause - Iterator Function Goo5() As IEnumerable Implements I.Goo - End Function + ' c. Without Parenthesis + Iterator Function Goo4() As IEnumerable + End Function - ' e. With Implements/Handles clause with trivia - Iterator Function Goo6() As IEnumerable Implements I.Goo ' Trailing - End Function + ' d. With Implements/Handles clause + Iterator Function Goo5() As IEnumerable Implements I.Goo + End Function - ' f. Invalid Iterator Sub - Iterator Sub Goo7() - End Sub + ' e. With Implements/Handles clause with trivia + Iterator Function Goo6() As IEnumerable Implements I.Goo ' Trailing + End Function - ' g. Without End Function - Iterator Function Goo3() As IEnumerable + ' f. Invalid Iterator Sub + Iterator Sub Goo7() + End Sub -End Class"; + ' g. Without End Function + Iterator Function Goo3() As IEnumerable - await VerifyAsync(code, expected); - } + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602932")] - public async Task TestAsyncFunctionWithAsClause() - { - var code = @"[| -Interface I - Function Goo() As System.Threading.Tasks.Task -End Interface - -Class MyType - Public Class Task - End Class -End Class - -Class MyTask - Inherits Task - Sub New() - MyBase.New(Nothing) - End Sub -End Class - -Class Test(Of T) - Implements I - - ' a. Basic - Async Function Goo1() As Integer - End Function - - ' b. With Trailing trivia - Async Function Goo2() As Integer ' Trailing - End Function - - ' c. Without Parenthesis - Async Function Goo3 As Integer ' Trailing - End Function - - ' d. With Implements/Handles clause - Async Function Goo4() As Integer Implements I.Goo - End Function - - ' e. With Implements/Handles clause with trivia - Async Function Goo5() As Integer Implements I.Goo ' Trailing - End Function - - ' f. Invalid Async Sub - Async Sub Goo6() As Integer - End Sub - - ' g. With valid Task return type - Async Function Goo7() As Task - End Function - - ' h. With valid Task(Of T) return type - Async Function Goo8() As Task(Of T) - End Function - - ' i. With valid Task(Of Integer) return type - Async Function Goo9() As Task(Of Integer) - End Function - - ' j. With invalid user defined Task return type - Async Function Goo10() As MyType.Task - End Function - - ' k. With error return type - Async Function Goo11() As ErrorType - End Function - - ' l. Without a return type - Async Function Goo12() As ' Trailing - End Function - - ' m. With trivia within AsClause - Async Function Goo13() As Integer ' Trailing - End Function - - ' n. With return type that inherits from Task - Async Function Goo14() As MyTask - End Function - - ' o. Without End Function - Async Function GooLast() As Integer + public Task TestAsyncFunctionWithAsClause() + => VerifyAsync(""" + [| + Interface I + Function Goo() As System.Threading.Tasks.Task + End Interface + + Class MyType + Public Class Task + End Class + End Class + + Class MyTask + Inherits Task + Sub New() + MyBase.New(Nothing) + End Sub + End Class + + Class Test(Of T) + Implements I + + ' a. Basic + Async Function Goo1() As Integer + End Function -End Class|]"; + ' b. With Trailing trivia + Async Function Goo2() As Integer ' Trailing + End Function - var expected = @" -Interface I - Function Goo() As System.Threading.Tasks.Task -End Interface + ' c. Without Parenthesis + Async Function Goo3 As Integer ' Trailing + End Function -Class MyType - Public Class Task - End Class -End Class + ' d. With Implements/Handles clause + Async Function Goo4() As Integer Implements I.Goo + End Function -Class MyTask - Inherits Task - Sub New() - MyBase.New(Nothing) - End Sub -End Class + ' e. With Implements/Handles clause with trivia + Async Function Goo5() As Integer Implements I.Goo ' Trailing + End Function -Class Test(Of T) - Implements I + ' f. Invalid Async Sub + Async Sub Goo6() As Integer + End Sub - ' a. Basic - Async Function Goo1() As System.Threading.Tasks.Task(Of Integer) - End Function + ' g. With valid Task return type + Async Function Goo7() As Task + End Function - ' b. With Trailing trivia - Async Function Goo2() As System.Threading.Tasks.Task(Of Integer) ' Trailing - End Function + ' h. With valid Task(Of T) return type + Async Function Goo8() As Task(Of T) + End Function - ' c. Without Parenthesis - Async Function Goo3() As System.Threading.Tasks.Task(Of Integer) ' Trailing - End Function + ' i. With valid Task(Of Integer) return type + Async Function Goo9() As Task(Of Integer) + End Function - ' d. With Implements/Handles clause - Async Function Goo4() As System.Threading.Tasks.Task(Of Integer) Implements I.Goo - End Function + ' j. With invalid user defined Task return type + Async Function Goo10() As MyType.Task + End Function - ' e. With Implements/Handles clause with trivia - Async Function Goo5() As System.Threading.Tasks.Task(Of Integer) Implements I.Goo ' Trailing - End Function + ' k. With error return type + Async Function Goo11() As ErrorType + End Function - ' f. Invalid Async Sub - Async Sub Goo6() As Integer - End Sub + ' l. Without a return type + Async Function Goo12() As ' Trailing + End Function - ' g. With valid Task return type - Async Function Goo7() As Task - End Function + ' m. With trivia within AsClause + Async Function Goo13() As Integer ' Trailing + End Function - ' h. With valid Task(Of T) return type - Async Function Goo8() As Task(Of T) - End Function + ' n. With return type that inherits from Task + Async Function Goo14() As MyTask + End Function - ' i. With valid Task(Of Integer) return type - Async Function Goo9() As Task(Of Integer) - End Function + ' o. Without End Function + Async Function GooLast() As Integer - ' j. With invalid user defined Task return type - Async Function Goo10() As System.Threading.Tasks.Task(Of MyType.Task) - End Function + End Class|] + """, """ - ' k. With error return type - Async Function Goo11() As ErrorType - End Function + Interface I + Function Goo() As System.Threading.Tasks.Task + End Interface - ' l. Without a return type - Async Function Goo12() As ' Trailing - End Function + Class MyType + Public Class Task + End Class + End Class - ' m. With trivia within AsClause - Async Function Goo13() As System.Threading.Tasks.Task(Of Integer) ' Trailing - End Function + Class MyTask + Inherits Task + Sub New() + MyBase.New(Nothing) + End Sub + End Class - ' n. With return type that inherits from Task - Async Function Goo14() As System.Threading.Tasks.Task(Of MyTask) - End Function + Class Test(Of T) + Implements I - ' o. Without End Function - Async Function GooLast() As System.Threading.Tasks.Task(Of Integer) + ' a. Basic + Async Function Goo1() As System.Threading.Tasks.Task(Of Integer) + End Function -End Class"; + ' b. With Trailing trivia + Async Function Goo2() As System.Threading.Tasks.Task(Of Integer) ' Trailing + End Function - await VerifyAsync(code, expected); - } + ' c. Without Parenthesis + Async Function Goo3() As System.Threading.Tasks.Task(Of Integer) ' Trailing + End Function - [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602932")] - public async Task TestAsyncFunctionWithAsClause_WithAddedImports() - { - var code = @"[| -Imports System -Imports System.Threading.Tasks - -Interface I - Function Goo() As System.Threading.Tasks.Task -End Interface - -Class MyType - Public Class Task - End Class -End Class - -Class MyTask - Inherits Task - Sub New() - MyBase.New(Nothing) - End Sub -End Class - -Class Test(Of T) - Implements I + ' d. With Implements/Handles clause + Async Function Goo4() As System.Threading.Tasks.Task(Of Integer) Implements I.Goo + End Function - ' a. Basic - Async Function Goo1() As Integer - End Function + ' e. With Implements/Handles clause with trivia + Async Function Goo5() As System.Threading.Tasks.Task(Of Integer) Implements I.Goo ' Trailing + End Function - ' b. With Trailing trivia - Async Function Goo2() As Integer ' Trailing - End Function + ' f. Invalid Async Sub + Async Sub Goo6() As Integer + End Sub - ' c. Without Parenthesis - Async Function Goo3 As Integer ' Trailing - End Function + ' g. With valid Task return type + Async Function Goo7() As Task + End Function - ' d. With Implements/Handles clause - Async Function Goo4() As Integer Implements I.Goo - End Function + ' h. With valid Task(Of T) return type + Async Function Goo8() As Task(Of T) + End Function - ' e. With Implements/Handles clause with trivia - Async Function Goo5() As Integer Implements I.Goo ' Trailing - End Function + ' i. With valid Task(Of Integer) return type + Async Function Goo9() As Task(Of Integer) + End Function - ' f. Invalid Async Sub - Async Sub Goo6() As Integer - End Sub + ' j. With invalid user defined Task return type + Async Function Goo10() As System.Threading.Tasks.Task(Of MyType.Task) + End Function - ' g. With valid Task return type - Async Function Goo7() As Task - End Function + ' k. With error return type + Async Function Goo11() As ErrorType + End Function - ' h. With valid Task(Of T) return type - Async Function Goo8() As Task(Of T) - End Function + ' l. Without a return type + Async Function Goo12() As ' Trailing + End Function - ' i. With valid Task(Of Integer) return type - Async Function Goo9() As Task(Of Integer) - End Function + ' m. With trivia within AsClause + Async Function Goo13() As System.Threading.Tasks.Task(Of Integer) ' Trailing + End Function - ' j. With invalid user defined Task return type - Async Function Goo10() As MyType.Task - End Function + ' n. With return type that inherits from Task + Async Function Goo14() As System.Threading.Tasks.Task(Of MyTask) + End Function - ' k. With error return type - Async Function Goo11() As ErrorType - End Function + ' o. Without End Function + Async Function GooLast() As System.Threading.Tasks.Task(Of Integer) - ' l. Without a return type - Async Function Goo12() As ' Trailing - End Function + End Class + """); - ' m. With trivia within AsClause - Async Function Goo13() As Integer ' Trailing - End Function + [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602932")] + public Task TestAsyncFunctionWithAsClause_WithAddedImports() + => VerifyAsync(""" + [| + Imports System + Imports System.Threading.Tasks + + Interface I + Function Goo() As System.Threading.Tasks.Task + End Interface + + Class MyType + Public Class Task + End Class + End Class + + Class MyTask + Inherits Task + Sub New() + MyBase.New(Nothing) + End Sub + End Class + + Class Test(Of T) + Implements I + + ' a. Basic + Async Function Goo1() As Integer + End Function - ' n. With return type that inherits from Task - Async Function Goo14() As MyTask - End Function + ' b. With Trailing trivia + Async Function Goo2() As Integer ' Trailing + End Function - ' o. Without End Function - Async Function GooLast() As Integer + ' c. Without Parenthesis + Async Function Goo3 As Integer ' Trailing + End Function -End Class|]"; + ' d. With Implements/Handles clause + Async Function Goo4() As Integer Implements I.Goo + End Function - var expected = @" -Imports System -Imports System.Threading.Tasks + ' e. With Implements/Handles clause with trivia + Async Function Goo5() As Integer Implements I.Goo ' Trailing + End Function -Interface I - Function Goo() As System.Threading.Tasks.Task -End Interface + ' f. Invalid Async Sub + Async Sub Goo6() As Integer + End Sub -Class MyType - Public Class Task - End Class -End Class + ' g. With valid Task return type + Async Function Goo7() As Task + End Function -Class MyTask - Inherits Task - Sub New() - MyBase.New(Nothing) - End Sub -End Class + ' h. With valid Task(Of T) return type + Async Function Goo8() As Task(Of T) + End Function -Class Test(Of T) - Implements I + ' i. With valid Task(Of Integer) return type + Async Function Goo9() As Task(Of Integer) + End Function - ' a. Basic - Async Function Goo1() As Task(Of Integer) - End Function + ' j. With invalid user defined Task return type + Async Function Goo10() As MyType.Task + End Function - ' b. With Trailing trivia - Async Function Goo2() As Task(Of Integer) ' Trailing - End Function + ' k. With error return type + Async Function Goo11() As ErrorType + End Function - ' c. Without Parenthesis - Async Function Goo3() As Task(Of Integer) ' Trailing - End Function + ' l. Without a return type + Async Function Goo12() As ' Trailing + End Function - ' d. With Implements/Handles clause - Async Function Goo4() As Task(Of Integer) Implements I.Goo - End Function + ' m. With trivia within AsClause + Async Function Goo13() As Integer ' Trailing + End Function - ' e. With Implements/Handles clause with trivia - Async Function Goo5() As Task(Of Integer) Implements I.Goo ' Trailing - End Function + ' n. With return type that inherits from Task + Async Function Goo14() As MyTask + End Function - ' f. Invalid Async Sub - Async Sub Goo6() As Integer - End Sub + ' o. Without End Function + Async Function GooLast() As Integer - ' g. With valid Task return type - Async Function Goo7() As Task - End Function + End Class|] + """, """ - ' h. With valid Task(Of T) return type - Async Function Goo8() As Task(Of T) - End Function + Imports System + Imports System.Threading.Tasks - ' i. With valid Task(Of Integer) return type - Async Function Goo9() As Task(Of Integer) - End Function + Interface I + Function Goo() As System.Threading.Tasks.Task + End Interface - ' j. With invalid user defined Task return type - Async Function Goo10() As Task(Of MyType.Task) - End Function + Class MyType + Public Class Task + End Class + End Class - ' k. With error return type - Async Function Goo11() As ErrorType - End Function + Class MyTask + Inherits Task + Sub New() + MyBase.New(Nothing) + End Sub + End Class - ' l. Without a return type - Async Function Goo12() As ' Trailing - End Function + Class Test(Of T) + Implements I - ' m. With trivia within AsClause - Async Function Goo13() As Task(Of Integer) ' Trailing - End Function + ' a. Basic + Async Function Goo1() As Task(Of Integer) + End Function - ' n. With return type that inherits from Task - Async Function Goo14() As Task(Of MyTask) - End Function + ' b. With Trailing trivia + Async Function Goo2() As Task(Of Integer) ' Trailing + End Function - ' o. Without End Function - Async Function GooLast() As Task(Of Integer) + ' c. Without Parenthesis + Async Function Goo3() As Task(Of Integer) ' Trailing + End Function -End Class"; + ' d. With Implements/Handles clause + Async Function Goo4() As Task(Of Integer) Implements I.Goo + End Function - await VerifyAsync(code, expected); - } + ' e. With Implements/Handles clause with trivia + Async Function Goo5() As Task(Of Integer) Implements I.Goo ' Trailing + End Function - [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602932")] - public async Task TestIteratorFunctionWithAsClause() - { - var code = @"[| -Interface I - Function Goo() As System.Collections.IEnumerable -End Interface + ' f. Invalid Async Sub + Async Sub Goo6() As Integer + End Sub -Class MyType - Public Class IEnumerable - End Class -End Class + ' g. With valid Task return type + Async Function Goo7() As Task + End Function -Class MyIEnumerable - Implements System.Collections.IEnumerable + ' h. With valid Task(Of T) return type + Async Function Goo8() As Task(Of T) + End Function - Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator - Throw New NotImplementedException() - End Function -End Class + ' i. With valid Task(Of Integer) return type + Async Function Goo9() As Task(Of Integer) + End Function -Class Test(Of T) - Implements I + ' j. With invalid user defined Task return type + Async Function Goo10() As Task(Of MyType.Task) + End Function - ' a. Basic - Iterator Function Goo1() As Integer - End Function + ' k. With error return type + Async Function Goo11() As ErrorType + End Function - ' b. With Trailing trivia - Iterator Function Goo2() As Integer ' Trailing - End Function + ' l. Without a return type + Async Function Goo12() As ' Trailing + End Function - ' c. Without Parenthesis - Iterator Function Goo3 As Integer ' Trailing - End Function + ' m. With trivia within AsClause + Async Function Goo13() As Task(Of Integer) ' Trailing + End Function - ' d. With Implements/Handles clause - Iterator Function Goo4() As Integer Implements I.Goo - End Function + ' n. With return type that inherits from Task + Async Function Goo14() As Task(Of MyTask) + End Function - ' e. With Implements/Handles clause with trivia - Iterator Function Goo5() As Integer Implements I.Goo ' Trailing - End Function + ' o. Without End Function + Async Function GooLast() As Task(Of Integer) - ' f. Invalid Iterator Sub - Iterator Sub Goo6() As Integer - End Sub + End Class + """); - ' g1. With valid IEnumerable return type - Iterator Function Goo7_1() As System.Collections.IEnumerable - End Function + [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602932")] + public Task TestIteratorFunctionWithAsClause() + => VerifyAsync(""" + [| + Interface I + Function Goo() As System.Collections.IEnumerable + End Interface + + Class MyType + Public Class IEnumerable + End Class + End Class + + Class MyIEnumerable + Implements System.Collections.IEnumerable + + Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator + Throw New NotImplementedException() + End Function + End Class - ' g2. With valid IEnumerator return type - Iterator Function Goo7_2() As System.Collections.IEnumerator - End Function + Class Test(Of T) + Implements I - ' h1. With valid IEnumerable(Of T) return type - Iterator Function Goo8_1() As System.Collections.Generic.IEnumerable(Of T) - End Function + ' a. Basic + Iterator Function Goo1() As Integer + End Function - ' h2. With valid IEnumerator(Of T) return type - Iterator Function Goo8_2() As System.Collections.Generic.IEnumerator(Of T) - End Function + ' b. With Trailing trivia + Iterator Function Goo2() As Integer ' Trailing + End Function - ' i1. With valid IEnumerable(Of Integer) return type - Iterator Function Goo9_1() As System.Collections.Generic.IEnumerable(Of Integer) - End Function + ' c. Without Parenthesis + Iterator Function Goo3 As Integer ' Trailing + End Function - ' i2. With valid IEnumerator(Of Integer) return type - Iterator Function Goo9_2() As System.Collections.Generic.IEnumerator(Of Integer) - End Function + ' d. With Implements/Handles clause + Iterator Function Goo4() As Integer Implements I.Goo + End Function - ' j. With invalid user defined IEnumerable return type - Iterator Function Goo10() As MyType.IEnumerable - End Function + ' e. With Implements/Handles clause with trivia + Iterator Function Goo5() As Integer Implements I.Goo ' Trailing + End Function - ' k. With error return type - Iterator Function Goo11() As ErrorType - End Function + ' f. Invalid Iterator Sub + Iterator Sub Goo6() As Integer + End Sub - ' l. Without a return type - Iterator Function Goo12() As ' Trailing - End Function + ' g1. With valid IEnumerable return type + Iterator Function Goo7_1() As System.Collections.IEnumerable + End Function - ' m. With trivia within AsClause - Iterator Function Goo13() As Integer ' Trailing - End Function + ' g2. With valid IEnumerator return type + Iterator Function Goo7_2() As System.Collections.IEnumerator + End Function - ' n. With return type that implements IEnumerable - Iterator Function Goo14() As MyIEnumerable - End Function + ' h1. With valid IEnumerable(Of T) return type + Iterator Function Goo8_1() As System.Collections.Generic.IEnumerable(Of T) + End Function - ' o. Without End Function - Iterator Function GooLast() As Integer + ' h2. With valid IEnumerator(Of T) return type + Iterator Function Goo8_2() As System.Collections.Generic.IEnumerator(Of T) + End Function -End Class|]"; + ' i1. With valid IEnumerable(Of Integer) return type + Iterator Function Goo9_1() As System.Collections.Generic.IEnumerable(Of Integer) + End Function - var expected = @" -Interface I - Function Goo() As System.Collections.IEnumerable -End Interface + ' i2. With valid IEnumerator(Of Integer) return type + Iterator Function Goo9_2() As System.Collections.Generic.IEnumerator(Of Integer) + End Function -Class MyType - Public Class IEnumerable - End Class -End Class + ' j. With invalid user defined IEnumerable return type + Iterator Function Goo10() As MyType.IEnumerable + End Function -Class MyIEnumerable - Implements System.Collections.IEnumerable + ' k. With error return type + Iterator Function Goo11() As ErrorType + End Function - Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator - Throw New NotImplementedException() - End Function -End Class + ' l. Without a return type + Iterator Function Goo12() As ' Trailing + End Function -Class Test(Of T) - Implements I + ' m. With trivia within AsClause + Iterator Function Goo13() As Integer ' Trailing + End Function - ' a. Basic - Iterator Function Goo1() As System.Collections.Generic.IEnumerable(Of Integer) - End Function + ' n. With return type that implements IEnumerable + Iterator Function Goo14() As MyIEnumerable + End Function - ' b. With Trailing trivia - Iterator Function Goo2() As System.Collections.Generic.IEnumerable(Of Integer) ' Trailing - End Function + ' o. Without End Function + Iterator Function GooLast() As Integer - ' c. Without Parenthesis - Iterator Function Goo3() As System.Collections.Generic.IEnumerable(Of Integer) ' Trailing - End Function + End Class|] + """, """ - ' d. With Implements/Handles clause - Iterator Function Goo4() As System.Collections.Generic.IEnumerable(Of Integer) Implements I.Goo - End Function + Interface I + Function Goo() As System.Collections.IEnumerable + End Interface - ' e. With Implements/Handles clause with trivia - Iterator Function Goo5() As System.Collections.Generic.IEnumerable(Of Integer) Implements I.Goo ' Trailing - End Function + Class MyType + Public Class IEnumerable + End Class + End Class - ' f. Invalid Iterator Sub - Iterator Sub Goo6() As Integer - End Sub + Class MyIEnumerable + Implements System.Collections.IEnumerable - ' g1. With valid IEnumerable return type - Iterator Function Goo7_1() As System.Collections.IEnumerable - End Function + Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator + Throw New NotImplementedException() + End Function + End Class - ' g2. With valid IEnumerator return type - Iterator Function Goo7_2() As System.Collections.IEnumerator - End Function + Class Test(Of T) + Implements I - ' h1. With valid IEnumerable(Of T) return type - Iterator Function Goo8_1() As System.Collections.Generic.IEnumerable(Of T) - End Function + ' a. Basic + Iterator Function Goo1() As System.Collections.Generic.IEnumerable(Of Integer) + End Function - ' h2. With valid IEnumerator(Of T) return type - Iterator Function Goo8_2() As System.Collections.Generic.IEnumerator(Of T) - End Function + ' b. With Trailing trivia + Iterator Function Goo2() As System.Collections.Generic.IEnumerable(Of Integer) ' Trailing + End Function - ' i1. With valid IEnumerable(Of Integer) return type - Iterator Function Goo9_1() As System.Collections.Generic.IEnumerable(Of Integer) - End Function + ' c. Without Parenthesis + Iterator Function Goo3() As System.Collections.Generic.IEnumerable(Of Integer) ' Trailing + End Function - ' i2. With valid IEnumerator(Of Integer) return type - Iterator Function Goo9_2() As System.Collections.Generic.IEnumerator(Of Integer) - End Function + ' d. With Implements/Handles clause + Iterator Function Goo4() As System.Collections.Generic.IEnumerable(Of Integer) Implements I.Goo + End Function - ' j. With invalid user defined IEnumerable return type - Iterator Function Goo10() As System.Collections.Generic.IEnumerable(Of MyType.IEnumerable) - End Function + ' e. With Implements/Handles clause with trivia + Iterator Function Goo5() As System.Collections.Generic.IEnumerable(Of Integer) Implements I.Goo ' Trailing + End Function - ' k. With error return type - Iterator Function Goo11() As ErrorType - End Function + ' f. Invalid Iterator Sub + Iterator Sub Goo6() As Integer + End Sub - ' l. Without a return type - Iterator Function Goo12() As ' Trailing - End Function + ' g1. With valid IEnumerable return type + Iterator Function Goo7_1() As System.Collections.IEnumerable + End Function - ' m. With trivia within AsClause - Iterator Function Goo13() As System.Collections.Generic.IEnumerable(Of Integer) ' Trailing - End Function + ' g2. With valid IEnumerator return type + Iterator Function Goo7_2() As System.Collections.IEnumerator + End Function - ' n. With return type that implements IEnumerable - Iterator Function Goo14() As System.Collections.Generic.IEnumerable(Of MyIEnumerable) - End Function + ' h1. With valid IEnumerable(Of T) return type + Iterator Function Goo8_1() As System.Collections.Generic.IEnumerable(Of T) + End Function - ' o. Without End Function - Iterator Function GooLast() As System.Collections.Generic.IEnumerable(Of Integer) + ' h2. With valid IEnumerator(Of T) return type + Iterator Function Goo8_2() As System.Collections.Generic.IEnumerator(Of T) + End Function -End Class"; + ' i1. With valid IEnumerable(Of Integer) return type + Iterator Function Goo9_1() As System.Collections.Generic.IEnumerable(Of Integer) + End Function - await VerifyAsync(code, expected); - } + ' i2. With valid IEnumerator(Of Integer) return type + Iterator Function Goo9_2() As System.Collections.Generic.IEnumerator(Of Integer) + End Function - [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602932")] - public async Task TestIteratorFunctionWithAsClause_WithAddedImports() - { - var code = @"[| -Imports System -Imports System.Collections.Generic + ' j. With invalid user defined IEnumerable return type + Iterator Function Goo10() As System.Collections.Generic.IEnumerable(Of MyType.IEnumerable) + End Function -Interface I - Function Goo() As System.Collections.IEnumerable -End Interface + ' k. With error return type + Iterator Function Goo11() As ErrorType + End Function -Class MyType - Public Class IEnumerable - End Class -End Class + ' l. Without a return type + Iterator Function Goo12() As ' Trailing + End Function -Class MyIEnumerable - Implements System.Collections.IEnumerable + ' m. With trivia within AsClause + Iterator Function Goo13() As System.Collections.Generic.IEnumerable(Of Integer) ' Trailing + End Function - Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator - Throw New NotImplementedException() - End Function -End Class + ' n. With return type that implements IEnumerable + Iterator Function Goo14() As System.Collections.Generic.IEnumerable(Of MyIEnumerable) + End Function -Class Test(Of T) - Implements I + ' o. Without End Function + Iterator Function GooLast() As System.Collections.Generic.IEnumerable(Of Integer) - ' a. Basic - Iterator Function Goo1() As Integer - End Function + End Class + """); - ' b. With Trailing trivia - Iterator Function Goo2() As Integer ' Trailing - End Function + [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602932")] + public Task TestIteratorFunctionWithAsClause_WithAddedImports() + => VerifyAsync(""" + [| + Imports System + Imports System.Collections.Generic + + Interface I + Function Goo() As System.Collections.IEnumerable + End Interface + + Class MyType + Public Class IEnumerable + End Class + End Class + + Class MyIEnumerable + Implements System.Collections.IEnumerable + + Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator + Throw New NotImplementedException() + End Function + End Class - ' c. Without Parenthesis - Iterator Function Goo3 As Integer ' Trailing - End Function + Class Test(Of T) + Implements I - ' d. With Implements/Handles clause - Iterator Function Goo4() As Integer Implements I.Goo - End Function + ' a. Basic + Iterator Function Goo1() As Integer + End Function - ' e. With Implements/Handles clause with trivia - Iterator Function Goo5() As Integer Implements I.Goo ' Trailing - End Function + ' b. With Trailing trivia + Iterator Function Goo2() As Integer ' Trailing + End Function - ' f. Invalid Iterator Sub - Iterator Sub Goo6() As Integer - End Sub + ' c. Without Parenthesis + Iterator Function Goo3 As Integer ' Trailing + End Function - ' g1. With valid IEnumerable return type - Iterator Function Goo7_1() As System.Collections.IEnumerable - End Function + ' d. With Implements/Handles clause + Iterator Function Goo4() As Integer Implements I.Goo + End Function - ' g2. With valid IEnumerator return type - Iterator Function Goo7_2() As System.Collections.IEnumerator - End Function + ' e. With Implements/Handles clause with trivia + Iterator Function Goo5() As Integer Implements I.Goo ' Trailing + End Function - ' h1. With valid IEnumerable(Of T) return type - Iterator Function Goo8_1() As IEnumerable(Of T) - End Function + ' f. Invalid Iterator Sub + Iterator Sub Goo6() As Integer + End Sub - ' h2. With valid IEnumerator(Of T) return type - Iterator Function Goo8_2() As System.Collections.Generic.IEnumerator(Of T) - End Function + ' g1. With valid IEnumerable return type + Iterator Function Goo7_1() As System.Collections.IEnumerable + End Function - ' i1. With valid IEnumerable(Of Integer) return type - Iterator Function Goo9_1() As IEnumerable(Of Integer) - End Function + ' g2. With valid IEnumerator return type + Iterator Function Goo7_2() As System.Collections.IEnumerator + End Function - ' i2. With valid IEnumerator(Of Integer) return type - Iterator Function Goo9_2() As System.Collections.Generic.IEnumerator(Of Integer) - End Function + ' h1. With valid IEnumerable(Of T) return type + Iterator Function Goo8_1() As IEnumerable(Of T) + End Function - ' j. With invalid user defined IEnumerable return type - Iterator Function Goo10() As MyType.IEnumerable - End Function + ' h2. With valid IEnumerator(Of T) return type + Iterator Function Goo8_2() As System.Collections.Generic.IEnumerator(Of T) + End Function - ' k. With error return type - Iterator Function Goo11() As ErrorType - End Function + ' i1. With valid IEnumerable(Of Integer) return type + Iterator Function Goo9_1() As IEnumerable(Of Integer) + End Function - ' l. Without a return type - Iterator Function Goo12() As ' Trailing - End Function + ' i2. With valid IEnumerator(Of Integer) return type + Iterator Function Goo9_2() As System.Collections.Generic.IEnumerator(Of Integer) + End Function - ' m. With trivia within AsClause - Iterator Function Goo13() As Integer ' Trailing - End Function + ' j. With invalid user defined IEnumerable return type + Iterator Function Goo10() As MyType.IEnumerable + End Function - ' n. With return type that implements IEnumerable - Iterator Function Goo14() As MyIEnumerable - End Function + ' k. With error return type + Iterator Function Goo11() As ErrorType + End Function - ' o. Without End Function - Iterator Function GooLast() As Integer + ' l. Without a return type + Iterator Function Goo12() As ' Trailing + End Function -End Class|]"; + ' m. With trivia within AsClause + Iterator Function Goo13() As Integer ' Trailing + End Function - var expected = @" -Imports System -Imports System.Collections.Generic + ' n. With return type that implements IEnumerable + Iterator Function Goo14() As MyIEnumerable + End Function -Interface I - Function Goo() As System.Collections.IEnumerable -End Interface + ' o. Without End Function + Iterator Function GooLast() As Integer -Class MyType - Public Class IEnumerable - End Class -End Class + End Class|] + """, """ -Class MyIEnumerable - Implements System.Collections.IEnumerable + Imports System + Imports System.Collections.Generic - Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator - Throw New NotImplementedException() - End Function -End Class + Interface I + Function Goo() As System.Collections.IEnumerable + End Interface -Class Test(Of T) - Implements I + Class MyType + Public Class IEnumerable + End Class + End Class - ' a. Basic - Iterator Function Goo1() As IEnumerable(Of Integer) - End Function + Class MyIEnumerable + Implements System.Collections.IEnumerable - ' b. With Trailing trivia - Iterator Function Goo2() As IEnumerable(Of Integer) ' Trailing - End Function + Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator + Throw New NotImplementedException() + End Function + End Class - ' c. Without Parenthesis - Iterator Function Goo3() As IEnumerable(Of Integer) ' Trailing - End Function + Class Test(Of T) + Implements I - ' d. With Implements/Handles clause - Iterator Function Goo4() As IEnumerable(Of Integer) Implements I.Goo - End Function + ' a. Basic + Iterator Function Goo1() As IEnumerable(Of Integer) + End Function - ' e. With Implements/Handles clause with trivia - Iterator Function Goo5() As IEnumerable(Of Integer) Implements I.Goo ' Trailing - End Function + ' b. With Trailing trivia + Iterator Function Goo2() As IEnumerable(Of Integer) ' Trailing + End Function - ' f. Invalid Iterator Sub - Iterator Sub Goo6() As Integer - End Sub + ' c. Without Parenthesis + Iterator Function Goo3() As IEnumerable(Of Integer) ' Trailing + End Function - ' g1. With valid IEnumerable return type - Iterator Function Goo7_1() As System.Collections.IEnumerable - End Function + ' d. With Implements/Handles clause + Iterator Function Goo4() As IEnumerable(Of Integer) Implements I.Goo + End Function - ' g2. With valid IEnumerator return type - Iterator Function Goo7_2() As System.Collections.IEnumerator - End Function + ' e. With Implements/Handles clause with trivia + Iterator Function Goo5() As IEnumerable(Of Integer) Implements I.Goo ' Trailing + End Function - ' h1. With valid IEnumerable(Of T) return type - Iterator Function Goo8_1() As IEnumerable(Of T) - End Function + ' f. Invalid Iterator Sub + Iterator Sub Goo6() As Integer + End Sub - ' h2. With valid IEnumerator(Of T) return type - Iterator Function Goo8_2() As System.Collections.Generic.IEnumerator(Of T) - End Function + ' g1. With valid IEnumerable return type + Iterator Function Goo7_1() As System.Collections.IEnumerable + End Function - ' i1. With valid IEnumerable(Of Integer) return type - Iterator Function Goo9_1() As IEnumerable(Of Integer) - End Function + ' g2. With valid IEnumerator return type + Iterator Function Goo7_2() As System.Collections.IEnumerator + End Function - ' i2. With valid IEnumerator(Of Integer) return type - Iterator Function Goo9_2() As System.Collections.Generic.IEnumerator(Of Integer) - End Function + ' h1. With valid IEnumerable(Of T) return type + Iterator Function Goo8_1() As IEnumerable(Of T) + End Function - ' j. With invalid user defined IEnumerable return type - Iterator Function Goo10() As IEnumerable(Of MyType.IEnumerable) - End Function + ' h2. With valid IEnumerator(Of T) return type + Iterator Function Goo8_2() As System.Collections.Generic.IEnumerator(Of T) + End Function - ' k. With error return type - Iterator Function Goo11() As ErrorType - End Function + ' i1. With valid IEnumerable(Of Integer) return type + Iterator Function Goo9_1() As IEnumerable(Of Integer) + End Function - ' l. Without a return type - Iterator Function Goo12() As ' Trailing - End Function + ' i2. With valid IEnumerator(Of Integer) return type + Iterator Function Goo9_2() As System.Collections.Generic.IEnumerator(Of Integer) + End Function - ' m. With trivia within AsClause - Iterator Function Goo13() As IEnumerable(Of Integer) ' Trailing - End Function + ' j. With invalid user defined IEnumerable return type + Iterator Function Goo10() As IEnumerable(Of MyType.IEnumerable) + End Function - ' n. With return type that implements IEnumerable - Iterator Function Goo14() As IEnumerable(Of MyIEnumerable) - End Function + ' k. With error return type + Iterator Function Goo11() As ErrorType + End Function - ' o. Without End Function - Iterator Function GooLast() As IEnumerable(Of Integer) + ' l. Without a return type + Iterator Function Goo12() As ' Trailing + End Function -End Class"; + ' m. With trivia within AsClause + Iterator Function Goo13() As IEnumerable(Of Integer) ' Trailing + End Function - await VerifyAsync(code, expected); - } + ' n. With return type that implements IEnumerable + Iterator Function Goo14() As IEnumerable(Of MyIEnumerable) + End Function - [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602932")] - public async Task TestAsyncFunctionWithAliasedReturnType() - { - var code = @"[| -Imports System -Imports System.Threading.Tasks -Imports X = System.Threading.Tasks.Task -Imports Y = System.Threading -Class Test - Async Function Goo() As X - End Function - Async Function Bar() As Y.Tasks.Task -End Class|]"; - - var expected = @" -Imports System -Imports System.Threading.Tasks -Imports X = System.Threading.Tasks.Task -Imports Y = System.Threading -Class Test - Async Function Goo() As X - End Function - Async Function Bar() As Y.Tasks.Task -End Class"; - - await VerifyAsync(code, expected); - } + ' o. Without End Function + Iterator Function GooLast() As IEnumerable(Of Integer) - [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602932")] - public async Task TestIteratorFunctionWithAliasedReturnType() - { - var code = @"[| -Imports System -Imports System.Collections -Imports X = System.Collections.IEnumerable -Imports Y = System.Collections -Class Test - Iterator Function Goo() As X - End Function - Iterator Function Bar() As Y.IEnumerable -End Class|]"; - - var expected = @" -Imports System -Imports System.Collections -Imports X = System.Collections.IEnumerable -Imports Y = System.Collections -Class Test - Iterator Function Goo() As X - End Function - Iterator Function Bar() As Y.IEnumerable -End Class"; - - await VerifyAsync(code, expected); - } + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602932")] - public async Task TestAsyncFunctionWithAliasedReturnType_2() - { - var code = @"[| -Imports System -Imports System.Threading.Tasks -Imports Y = System.Int32 - -Class Test - Async Function Goo() As Y ' Trailing - End Function -End Class|]"; - - var expected = @" -Imports System -Imports System.Threading.Tasks -Imports Y = System.Int32 - -Class Test - Async Function Goo() As Task(Of Y) ' Trailing - End Function -End Class"; - - await VerifyAsync(code, expected); - } + public Task TestAsyncFunctionWithAliasedReturnType() + => VerifyAsync(""" + [| + Imports System + Imports System.Threading.Tasks + Imports X = System.Threading.Tasks.Task + Imports Y = System.Threading + Class Test + Async Function Goo() As X + End Function + Async Function Bar() As Y.Tasks.Task + End Class|] + """, """ + + Imports System + Imports System.Threading.Tasks + Imports X = System.Threading.Tasks.Task + Imports Y = System.Threading + Class Test + Async Function Goo() As X + End Function + Async Function Bar() As Y.Tasks.Task + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602932")] - public async Task TestIteratorFunctionWithAliasedReturnType_2() - { - var code = @"[| -Imports System -Imports System.Threading.Tasks -Imports Y = System.Int32 - -Class Test - Iterator Function Goo() As Y ' Trailing - End Function -End Class|]"; - - var expected = @" -Imports System -Imports System.Threading.Tasks -Imports Y = System.Int32 - -Class Test - Iterator Function Goo() As Collections.Generic.IEnumerable(Of Y) ' Trailing - End Function -End Class"; - - await VerifyAsync(code, expected); - } + public Task TestIteratorFunctionWithAliasedReturnType() + => VerifyAsync(""" + [| + Imports System + Imports System.Collections + Imports X = System.Collections.IEnumerable + Imports Y = System.Collections + Class Test + Iterator Function Goo() As X + End Function + Iterator Function Bar() As Y.IEnumerable + End Class|] + """, """ + + Imports System + Imports System.Collections + Imports X = System.Collections.IEnumerable + Imports Y = System.Collections + Class Test + Iterator Function Goo() As X + End Function + Iterator Function Bar() As Y.IEnumerable + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602932")] - public async Task TestAsyncFunctionWithQualifiedNameReturnType() - { - var code = @"[| -Imports System -Imports System.Threading.Tasks - -Class Test - Async Function Goo() As System.Int32 ' Trailing - End Function -End Class|]"; - - var expected = @" -Imports System -Imports System.Threading.Tasks + public Task TestAsyncFunctionWithAliasedReturnType_2() + => VerifyAsync(""" + [| + Imports System + Imports System.Threading.Tasks + Imports Y = System.Int32 + + Class Test + Async Function Goo() As Y ' Trailing + End Function + End Class|] + """, """ -Class Test - Async Function Goo() As Task(Of System.Int32) ' Trailing - End Function -End Class"; + Imports System + Imports System.Threading.Tasks + Imports Y = System.Int32 - await VerifyAsync(code, expected); - } + Class Test + Async Function Goo() As Task(Of Y) ' Trailing + End Function + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602932")] - public async Task TestIteratorFunctionWithQualifiedNameReturnType() - { - var code = @"[| -Imports System -Imports System.Collections - -Class Test - Iterator Function Goo() As System.Int32 ' Trailing - End Function -End Class|]"; - - var expected = @" -Imports System -Imports System.Collections - -Class Test - Iterator Function Goo() As Generic.IEnumerable(Of System.Int32) ' Trailing - End Function -End Class"; - - await VerifyAsync(code, expected); - } + public Task TestIteratorFunctionWithAliasedReturnType_2() + => VerifyAsync(""" + [| + Imports System + Imports System.Threading.Tasks + Imports Y = System.Int32 + + Class Test + Iterator Function Goo() As Y ' Trailing + End Function + End Class|] + """, """ - [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602932")] - public async Task TestAsyncLambdaFunction() - { - var code = @"[| -Imports System -Imports System.Threading.Tasks + Imports System + Imports System.Threading.Tasks + Imports Y = System.Int32 -Class Test - Async Function Goo() As Integer - ' Basic - Dim a = Async Function() As Integer + Class Test + Iterator Function Goo() As Collections.Generic.IEnumerable(Of Y) ' Trailing End Function + End Class + """); - ' With trailing trivia - Dim b = Async Function() As Integer ' Trailing + [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602932")] + public Task TestAsyncFunctionWithQualifiedNameReturnType() + => VerifyAsync(""" + [| + Imports System + Imports System.Threading.Tasks + + Class Test + Async Function Goo() As System.Int32 ' Trailing End Function + End Class|] + """, """ - ' Single Line lambda - Dim c = Async Function() 0 + Imports System + Imports System.Threading.Tasks - ' Without AsClause - Dim d = Async Function() + Class Test + Async Function Goo() As Task(Of System.Int32) ' Trailing End Function + End Class + """); - ' With valid Task return type - Dim e = Async Function() as Task + [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602932")] + public Task TestIteratorFunctionWithQualifiedNameReturnType() + => VerifyAsync(""" + [| + Imports System + Imports System.Collections + + Class Test + Iterator Function Goo() As System.Int32 ' Trailing End Function + End Class|] + """, """ - ' Without End Function - Dim last = Async Function() As Integer ' Trailing - End Function -End Class|]"; - - var expected = @" -Imports System -Imports System.Threading.Tasks + Imports System + Imports System.Collections -Class Test - Async Function Goo() As Task(Of Integer) - ' Basic - Dim a = Async Function() As Task(Of Integer) + Class Test + Iterator Function Goo() As Generic.IEnumerable(Of System.Int32) ' Trailing End Function + End Class + """); - ' With trailing trivia - Dim b = Async Function() As Task(Of Integer) ' Trailing + [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602932")] + public Task TestAsyncLambdaFunction() + => VerifyAsync(""" + [| + Imports System + Imports System.Threading.Tasks + + Class Test + Async Function Goo() As Integer + ' Basic + Dim a = Async Function() As Integer + End Function + + ' With trailing trivia + Dim b = Async Function() As Integer ' Trailing + End Function + + ' Single Line lambda + Dim c = Async Function() 0 + + ' Without AsClause + Dim d = Async Function() + End Function + + ' With valid Task return type + Dim e = Async Function() as Task + End Function + + ' Without End Function + Dim last = Async Function() As Integer ' Trailing End Function + End Class|] + """, """ - ' Single Line lambda - Dim c = Async Function() 0 + Imports System + Imports System.Threading.Tasks - ' Without AsClause - Dim d = Async Function() - End Function + Class Test + Async Function Goo() As Task(Of Integer) + ' Basic + Dim a = Async Function() As Task(Of Integer) + End Function - ' With valid Task return type - Dim e = Async Function() as Task - End Function + ' With trailing trivia + Dim b = Async Function() As Task(Of Integer) ' Trailing + End Function - ' Without End Function - Dim last = Async Function() As Task(Of Integer) ' Trailing - End Function -End Class"; + ' Single Line lambda + Dim c = Async Function() 0 - await VerifyAsync(code, expected); - } + ' Without AsClause + Dim d = Async Function() + End Function - [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602932")] - public async Task TestIteratorLambdaFunction() - { - var code = @"[| -Imports System -Imports System.Collections.Generic + ' With valid Task return type + Dim e = Async Function() as Task + End Function -Class Test - Iterator Function Goo() As Integer - ' Basic - Dim a = Iterator Function() As Integer - End Function + ' Without End Function + Dim last = Async Function() As Task(Of Integer) ' Trailing + End Function + End Class + """); - ' With trailing trivia - Dim b = Iterator Function() As Integer ' Trailing + [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602932")] + public Task TestIteratorLambdaFunction() + => VerifyAsync(""" + [| + Imports System + Imports System.Collections.Generic + + Class Test + Iterator Function Goo() As Integer + ' Basic + Dim a = Iterator Function() As Integer + End Function + + ' With trailing trivia + Dim b = Iterator Function() As Integer ' Trailing + End Function + + ' Single Line lambda + Dim c = Iterator Function() 0 + + ' Without AsClause + Dim d = Iterator Function() + End Function + + ' With valid IEnumerable return type + Dim e = Iterator Function() as System.Collections.IEnumerable + End Function + + ' Without End Function + Dim last = Iterator Function() As Integer ' Trailing End Function + End Class|] + """, """ - ' Single Line lambda - Dim c = Iterator Function() 0 + Imports System + Imports System.Collections.Generic - ' Without AsClause - Dim d = Iterator Function() - End Function + Class Test + Iterator Function Goo() As IEnumerable(Of Integer) + ' Basic + Dim a = Iterator Function() As IEnumerable(Of Integer) + End Function - ' With valid IEnumerable return type - Dim e = Iterator Function() as System.Collections.IEnumerable - End Function + ' With trailing trivia + Dim b = Iterator Function() As IEnumerable(Of Integer) ' Trailing + End Function - ' Without End Function - Dim last = Iterator Function() As Integer ' Trailing - End Function -End Class|]"; + ' Single Line lambda + Dim c = Iterator Function() 0 - var expected = @" -Imports System -Imports System.Collections.Generic + ' Without AsClause + Dim d = Iterator Function() + End Function -Class Test - Iterator Function Goo() As IEnumerable(Of Integer) - ' Basic - Dim a = Iterator Function() As IEnumerable(Of Integer) - End Function + ' With valid IEnumerable return type + Dim e = Iterator Function() as System.Collections.IEnumerable + End Function - ' With trailing trivia - Dim b = Iterator Function() As IEnumerable(Of Integer) ' Trailing - End Function + ' Without End Function + Dim last = Iterator Function() As IEnumerable(Of Integer) ' Trailing + End Function + End Class + """); - ' Single Line lambda - Dim c = Iterator Function() 0 - - ' Without AsClause - Dim d = Iterator Function() + [Fact] + public Task TestNoParenthesesForArgument() + => VerifyAsync(""" + [| + Imports System + Imports System.Collections.Generic + + Class Test + Private Function Goo() As Integer + Return 1 End Function - ' With valid IEnumerable return type - Dim e = Iterator Function() as System.Collections.IEnumerable - End Function + Private Sub Caller(i As Integer) + Caller(Goo) + End Sub + End Class|] + """, """ - ' Without End Function - Dim last = Iterator Function() As IEnumerable(Of Integer) ' Trailing - End Function -End Class"; + Imports System + Imports System.Collections.Generic - await VerifyAsync(code, expected); - } + Class Test + Private Function Goo() As Integer + Return 1 + End Function - [Fact] - public async Task TestNoParenthesesForArgument() - { - // making roslyn behavior same as dev12 - // also, this is one of most expensive one to check whether - // parentheses needs to be inserted or not. - - var code = @"[| -Imports System -Imports System.Collections.Generic - -Class Test - Private Function Goo() As Integer - Return 1 - End Function - - Private Sub Caller(i As Integer) - Caller(Goo) - End Sub -End Class|]"; - - var expected = @" -Imports System -Imports System.Collections.Generic - -Class Test - Private Function Goo() As Integer - Return 1 - End Function - - Private Sub Caller(i As Integer) - Caller(Goo) - End Sub -End Class"; - - await VerifyAsync(code, expected); - } + Private Sub Caller(i As Integer) + Caller(Goo) + End Sub + End Class + """); [Fact] - public async Task TestNoParenthesesForNameOf() - { - var code = @"[| -Module M - Sub Main() - Dim s = NameOf(Main) - End Sub -End Module|]"; - - var expected = @" -Module M - Sub Main() - Dim s = NameOf(Main) - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task TestNoParenthesesForNameOf() + => VerifyAsync(""" + [| + Module M + Sub Main() + Dim s = NameOf(Main) + End Sub + End Module|] + """, """ + + Module M + Sub Main() + Dim s = NameOf(Main) + End Sub + End Module + """); [Fact] - public async Task OptionExplicitOn() - { - var code = @"[|Option Explicit|]"; - var expected = @"Option Explicit On -"; + public Task OptionExplicitOn() + => VerifyAsync(@"[|Option Explicit|]", """ + Option Explicit On - await VerifyAsync(code, expected); - } + """); [Fact] - public async Task OptionInferOn() - { - var code = @"[|Option Infer|]"; - var expected = @"Option Infer On -"; + public Task OptionInferOn() + => VerifyAsync(@"[|Option Infer|]", """ + Option Infer On - await VerifyAsync(code, expected); - } + """); [Fact] - public async Task OptionStrictOn() - { - var code = @"[|Option Strict|]"; - var expected = @"Option Strict On -"; + public Task OptionStrictOn() + => VerifyAsync(@"[|Option Strict|]", """ + Option Strict On - await VerifyAsync(code, expected); - } + """); private static string CreateMethod(string body) { - return @"Imports System -Class C - Public Sub Method()" + body + @" - End Sub -End Class"; + return """ + Imports System + Class C + Public Sub Method() + """ + body + """ + + End Sub + End Class + """; } private static async Task VerifyAsync(string codeWithMarker, string expectedResult) diff --git a/src/Workspaces/CoreTest/CodeCleanup/CodeCleanupTests.cs b/src/Workspaces/CoreTest/CodeCleanup/CodeCleanupTests.cs index 892d6804e0172..0e562bd597b7d 100644 --- a/src/Workspaces/CoreTest/CodeCleanup/CodeCleanupTests.cs +++ b/src/Workspaces/CoreTest/CodeCleanup/CodeCleanupTests.cs @@ -16,7 +16,6 @@ using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; -using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.CodeCleanup; @@ -80,8 +79,10 @@ public async Task CodeCleanersCSharp_Spans() [Fact] public void DefaultVisualBasicCodeCleanups() { - var document = CreateDocument(@"Class C -End Class", LanguageNames.VisualBasic); + var document = CreateDocument(""" + Class C + End Class + """, LanguageNames.VisualBasic); var codeCleanups = CodeCleaner.GetDefaultProviders(document); Assert.NotEmpty(codeCleanups); } @@ -89,8 +90,10 @@ public void DefaultVisualBasicCodeCleanups() [Fact] public async Task CodeCleanersVisualBasic_NoSpans() { - var document = CreateDocument(@"Class C -End Class", LanguageNames.VisualBasic); + var document = CreateDocument(""" + Class C + End Class + """, LanguageNames.VisualBasic); var cleanDocument = await CodeCleaner.CleanupAsync(document, [], await document.GetCodeCleanupOptionsAsync(CancellationToken.None)); Assert.Equal(document, cleanDocument); @@ -99,8 +102,10 @@ public async Task CodeCleanersVisualBasic_NoSpans() [Fact] public async Task CodeCleanersVisualBasic_Document() { - var document = CreateDocument(@"Class C -End Class", LanguageNames.VisualBasic); + var document = CreateDocument(""" + Class C + End Class + """, LanguageNames.VisualBasic); var cleanDocument = await CodeCleaner.CleanupAsync(document, await document.GetCodeCleanupOptionsAsync(CancellationToken.None)); Assert.Equal(document, cleanDocument); @@ -109,8 +114,10 @@ public async Task CodeCleanersVisualBasic_Document() [Fact] public async Task CodeCleanersVisualBasic_Span() { - var document = CreateDocument(@"Class C -End Class", LanguageNames.VisualBasic); + var document = CreateDocument(""" + Class C + End Class + """, LanguageNames.VisualBasic); var root = await document.GetSyntaxRootAsync(); var cleanDocument = await CodeCleaner.CleanupAsync(document, root.FullSpan, await document.GetCodeCleanupOptionsAsync(CancellationToken.None)); @@ -120,8 +127,10 @@ public async Task CodeCleanersVisualBasic_Span() [Fact] public async Task CodeCleanersVisualBasic_Spans() { - var document = CreateDocument(@"Class C -End Class", LanguageNames.VisualBasic); + var document = CreateDocument(""" + Class C + End Class + """, LanguageNames.VisualBasic); var root = await document.GetSyntaxRootAsync(); var cleanDocument = await CodeCleaner.CleanupAsync(document, [root.FullSpan], await document.GetCodeCleanupOptionsAsync(CancellationToken.None)); @@ -143,8 +152,10 @@ public async Task CodeCleanersCSharp_Annotation() [Fact] public async Task CodeCleanersVisualBasic_Annotation() { - var document = CreateDocument(@"Class C -End Class", LanguageNames.VisualBasic); + var document = CreateDocument(""" + Class C + End Class + """, LanguageNames.VisualBasic); var annotation = new SyntaxAnnotation(); document = document.WithSyntaxRoot((await document.GetSyntaxRootAsync()).WithAdditionalAnnotations(annotation)); @@ -262,41 +273,39 @@ public Task MultipleRanges() => VerifyRange("namespace N { class C {|r:{ {|b:void Method() { }|} }|} class C2 {|r:{ {|b:void Method() { }|} }|} }"); [Fact, WorkItem(12848, "DevDiv_Projects/Roslyn")] - public async Task DoNotCrash_VB() - { - var code = @"#If DEBUG OrElse TRACE Then -Imports System.Diagnostics -#ElseIf SILVERLIGHT Then -Imports System.Diagnostics -#Else -Imports System.Diagnostics -#End If - -{|r:# {|b: |} - Region|} ""Region"" -#Region ""more"" -#End Region -#End Region"; - - await VerifyRange(code, LanguageNames.VisualBasic); - } + public Task DoNotCrash_VB() + => VerifyRange(""" + #If DEBUG OrElse TRACE Then + Imports System.Diagnostics + #ElseIf SILVERLIGHT Then + Imports System.Diagnostics + #Else + Imports System.Diagnostics + #End If + + {|r:# {|b: |} + Region|} "Region" + #Region "more" + #End Region + #End Region + """, LanguageNames.VisualBasic); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774295")] public async Task DoNotCrash_VB_2() { - var code = @" -Public Class Class1 - Public Custom Event Event2 As EventHandler - AddHandler(ByVal value As EventHandler) - End AddHandler - RemoveHandler(ByVal value As EventHandler) - End RemoveHandler - RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) - e - End Event - -End Class -"; + var code = """ + Public Class Class1 + Public Custom Event Event2 As EventHandler + AddHandler(ByVal value As EventHandler) + End AddHandler + RemoveHandler(ByVal value As EventHandler) + End RemoveHandler + RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) + e + End Event + + End Class + """; var document = CreateDocument(code, LanguageNames.VisualBasic); var semanticModel = await document.GetSemanticModelAsync(); var root = await document.GetSyntaxRootAsync(); @@ -320,24 +329,21 @@ End Class } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547075")] - public async Task TestCodeCleanupWithinNonStructuredTrivia() - { - var code = @" -#Const ccConst = 0 -#If {|b: -|}Then -Imports System -Imports System.Collections.Generic -Imports System.Linq - -Module Program - Sub Main(args As String()) - - End Sub -End Module"; - - await VerifyRange(code, LanguageNames.VisualBasic); - } + public Task TestCodeCleanupWithinNonStructuredTrivia() + => VerifyRange(""" + #Const ccConst = 0 + #If {|b: + |}Then + Imports System + Imports System.Collections.Generic + Imports System.Linq + + Module Program + Sub Main(args As String()) + + End Sub + End Module + """, LanguageNames.VisualBasic); [Fact] public async Task RangeWithTransformation_OutsideOfRange() diff --git a/src/Workspaces/CoreTest/CodeCleanup/FixIncorrectTokenTests.cs b/src/Workspaces/CoreTest/CodeCleanup/FixIncorrectTokenTests.cs index d8f972d735942..726d9c8e597e9 100644 --- a/src/Workspaces/CoreTest/CodeCleanup/FixIncorrectTokenTests.cs +++ b/src/Workspaces/CoreTest/CodeCleanup/FixIncorrectTokenTests.cs @@ -20,694 +20,677 @@ namespace Microsoft.CodeAnalysis.UnitTests.CodeCleanup; public sealed class FixIncorrectTokensTests { [Fact, WorkItem(17313, "DevDiv_Projects/Roslyn")] - public async Task FixEndIfKeyword_WithMatchingIf() - { - var code = @" -Module Program - Sub Main(args As String()) - [|If args IsNot Nothing Then - System.Console.WriteLine(args) - endif|] - End Sub -End Module"; - - var expected = @" -Module Program - Sub Main(args As String()) - If args IsNot Nothing Then - System.Console.WriteLine(args) - End If - End Sub -End Module"; - await VerifyAsync(code, expected); - } + public Task FixEndIfKeyword_WithMatchingIf() + => VerifyAsync(""" + + Module Program + Sub Main(args As String()) + [|If args IsNot Nothing Then + System.Console.WriteLine(args) + endif|] + End Sub + End Module + """, """ + + Module Program + Sub Main(args As String()) + If args IsNot Nothing Then + System.Console.WriteLine(args) + End If + End Sub + End Module + """); [Fact, WorkItem(17313, "DevDiv_Projects/Roslyn")] - public async Task FixEndIfKeyword_WithMatchingIf_Directive() - { - var code = @"[| -#If c = 0 Then -#Endif|]"; - - var expected = @" -#If c = 0 Then -#End If"; - await VerifyAsync(code, expected); - } + public Task FixEndIfKeyword_WithMatchingIf_Directive() + => VerifyAsync(""" + [| + #If c = 0 Then + #Endif|] + """, """ + + #If c = 0 Then + #End If + """); [Fact, WorkItem(17313, "DevDiv_Projects/Roslyn")] - public async Task FixEndIfKeyword_WithoutMatchingIf() - { - var code = @" -Module Program - Sub Main(args As String()) - [|EndIf|] - End Sub -End Module"; - - var expected = @" -Module Program - Sub Main(args As String()) - End If - End Sub -End Module"; - await VerifyAsync(code, expected); - } + public Task FixEndIfKeyword_WithoutMatchingIf() + => VerifyAsync(""" + + Module Program + Sub Main(args As String()) + [|EndIf|] + End Sub + End Module + """, """ + + Module Program + Sub Main(args As String()) + End If + End Sub + End Module + """); [Fact, WorkItem(17313, "DevDiv_Projects/Roslyn")] - public async Task FixEndIfKeyword_WithoutMatchingIf_Directive() - { - var code = @"[| -Class X -End Class + public Task FixEndIfKeyword_WithoutMatchingIf_Directive() + => VerifyAsync(""" + [| + Class X + End Class -#Endif|]"; + #Endif|] + """, """ - var expected = @" -Class X -End Class + Class X + End Class -#End If"; - await VerifyAsync(code, expected); - } + #End If + """); [Fact(Skip = "889521")] [WorkItem(17313, "DevDiv_Projects/Roslyn")] - public async Task FixEndIfKeyword_SameLineAsIf() - { - var code = @" -Module Program - Sub Main(args As String()) - If args IsNot Nothing Then [|EndIf|] - End Sub -End Module"; - - var expected = @" -Module Program - Sub Main(args As String()) - If args IsNot Nothing Then - End If - End Sub -End Module"; - await VerifyAsync(code, expected); - } + public Task FixEndIfKeyword_SameLineAsIf() + => VerifyAsync(""" + + Module Program + Sub Main(args As String()) + If args IsNot Nothing Then [|EndIf|] + End Sub + End Module + """, """ + + Module Program + Sub Main(args As String()) + If args IsNot Nothing Then + End If + End Sub + End Module + """); [Fact, WorkItem(17313, "DevDiv_Projects/Roslyn")] - public async Task FixEndIfKeyword_SameLineAsIf_Invalid() - { - var code = @" -Module Program - Sub Main(args As String()) - If args IsNot Nothing [|EndIf|] - End Sub -End Module"; - - var expected = @" -Module Program - Sub Main(args As String()) - If args IsNot Nothing EndIf - End Sub -End Module"; - await VerifyAsync(code, expected); - } + public Task FixEndIfKeyword_SameLineAsIf_Invalid() + => VerifyAsync(""" + + Module Program + Sub Main(args As String()) + If args IsNot Nothing [|EndIf|] + End Sub + End Module + """, """ + + Module Program + Sub Main(args As String()) + If args IsNot Nothing EndIf + End Sub + End Module + """); [Fact, WorkItem(17313, "DevDiv_Projects/Roslyn")] - public async Task FixEndIfKeyword_SameLineAsIf_Directive() - { - var code = @"[| -#If c = 0 Then #Endif|]"; + public Task FixEndIfKeyword_SameLineAsIf_Directive() + => VerifyAsync(""" + [| + #If c = 0 Then #Endif|] + """, """ - var expected = @" -#If c = 0 Then #Endif"; - await VerifyAsync(code, expected); - } + #If c = 0 Then #Endif + """); [Fact, WorkItem(17313, "DevDiv_Projects/Roslyn")] - public async Task FixEndIfKeyword_WithLeadingTrivia() - { - var code = @" -Module Program - Sub Main(args As String()) - [|If args IsNot Nothing Then - System.Console.WriteLine(args) -' Dummy Endif - EndIf|] - End Sub -End Module"; - - var expected = @" -Module Program - Sub Main(args As String()) - If args IsNot Nothing Then - System.Console.WriteLine(args) + public Task FixEndIfKeyword_WithLeadingTrivia() + => VerifyAsync(""" + + Module Program + Sub Main(args As String()) + [|If args IsNot Nothing Then + System.Console.WriteLine(args) ' Dummy Endif - End If - End Sub -End Module"; - await VerifyAsync(code, expected); - } + EndIf|] + End Sub + End Module + """, """ + + Module Program + Sub Main(args As String()) + If args IsNot Nothing Then + System.Console.WriteLine(args) + ' Dummy Endif + End If + End Sub + End Module + """); [Fact, WorkItem(17313, "DevDiv_Projects/Roslyn")] - public async Task FixEndIfKeyword_WithLeadingTrivia_Directive() - { - var code = @"[| -#If c = 0 Then -'#Endif -#Endif -|]"; - - var expected = @" -#If c = 0 Then -'#Endif -#End If -"; - await VerifyAsync(code, expected); - } + public Task FixEndIfKeyword_WithLeadingTrivia_Directive() + => VerifyAsync(""" + [| + #If c = 0 Then + '#Endif + #Endif + |] + """, """ + + #If c = 0 Then + '#Endif + #End If + + """); [Fact, WorkItem(17313, "DevDiv_Projects/Roslyn")] - public async Task FixEndIfKeyword_InvocationExpressionArgument() - { - var code = @" -Module Program - Sub Main(args As String()) - [|If args IsNot Nothing Then - System.Console.WriteLine(args) - InvocationExpression EndIf|] - End Sub -End Module"; - - var expected = @" -Module Program - Sub Main(args As String()) - If args IsNot Nothing Then - System.Console.WriteLine(args) - InvocationExpression EndIf - End Sub -End Module"; - await VerifyAsync(code, expected); - } + public Task FixEndIfKeyword_InvocationExpressionArgument() + => VerifyAsync(""" + + Module Program + Sub Main(args As String()) + [|If args IsNot Nothing Then + System.Console.WriteLine(args) + InvocationExpression EndIf|] + End Sub + End Module + """, """ + + Module Program + Sub Main(args As String()) + If args IsNot Nothing Then + System.Console.WriteLine(args) + InvocationExpression EndIf + End Sub + End Module + """); [Fact, WorkItem(17313, "DevDiv_Projects/Roslyn")] - public async Task FixEndIfKeyword_InvalidDirectiveCases() - { - var code = @"[| -' BadDirective cases -#If c = 0 Then -#InvocationExpression #Endif + public Task FixEndIfKeyword_InvalidDirectiveCases() + => VerifyAsync(""" + [| + ' BadDirective cases + #If c = 0 Then + #InvocationExpression #Endif -#If c = 0 Then -InvocationExpression# #Endif + #If c = 0 Then + InvocationExpression# #Endif -#If c = 0 Then -InvocationExpression #Endif + #If c = 0 Then + InvocationExpression #Endif -' Missing EndIfDirective cases -#If c = 0 Then -#InvocationExpression -#Endif + ' Missing EndIfDirective cases + #If c = 0 Then + #InvocationExpression + #Endif -#If c = 0 Then -InvocationExpression# -#Endif + #If c = 0 Then + InvocationExpression# + #Endif -#If c = 0 Then -InvocationExpression -#Endif -|]"; + #If c = 0 Then + InvocationExpression + #Endif + |] + """, """ - var expected = @" -' BadDirective cases -#If c = 0 Then -#InvocationExpression #Endif + ' BadDirective cases + #If c = 0 Then + #InvocationExpression #Endif -#If c = 0 Then -InvocationExpression# #Endif + #If c = 0 Then + InvocationExpression# #Endif -#If c = 0 Then -InvocationExpression #Endif + #If c = 0 Then + InvocationExpression #Endif -' Missing EndIfDirective cases -#If c = 0 Then -#InvocationExpression -#End If + ' Missing EndIfDirective cases + #If c = 0 Then + #InvocationExpression + #End If -#If c = 0 Then -InvocationExpression# -#End If + #If c = 0 Then + InvocationExpression# + #End If -#If c = 0 Then -InvocationExpression -#End If -"; - await VerifyAsync(code, expected); - } + #If c = 0 Then + InvocationExpression + #End If + + """); [Fact, WorkItem(17313, "DevDiv_Projects/Roslyn")] - public async Task FixEndIfKeyword_WithTrailingTrivia() - { - var code = @" -Module Program - Sub Main(args As String()) - [|If args IsNot Nothing Then - System.Console.WriteLine(args) - EndIf ' Dummy EndIf|] - End Sub -End Module"; - - var expected = @" -Module Program - Sub Main(args As String()) - If args IsNot Nothing Then - System.Console.WriteLine(args) - End If ' Dummy EndIf - End Sub -End Module"; - await VerifyAsync(code, expected); - } + public Task FixEndIfKeyword_WithTrailingTrivia() + => VerifyAsync(""" + + Module Program + Sub Main(args As String()) + [|If args IsNot Nothing Then + System.Console.WriteLine(args) + EndIf ' Dummy EndIf|] + End Sub + End Module + """, """ + + Module Program + Sub Main(args As String()) + If args IsNot Nothing Then + System.Console.WriteLine(args) + End If ' Dummy EndIf + End Sub + End Module + """); [Fact, WorkItem(17313, "DevDiv_Projects/Roslyn")] - public async Task FixEndIfKeyword_WithTrailingTrivia_Directive() - { - var code = @"[| -#If c = 0 Then -#Endif '#Endif -|]"; - - var expected = @" -#If c = 0 Then -#End If '#Endif -"; - await VerifyAsync(code, expected); - } + public Task FixEndIfKeyword_WithTrailingTrivia_Directive() + => VerifyAsync(""" + [| + #If c = 0 Then + #Endif '#Endif + |] + """, """ + + #If c = 0 Then + #End If '#Endif + + """); [Fact, WorkItem(17313, "DevDiv_Projects/Roslyn")] - public async Task FixEndIfKeyword_WithIdentifierTokenTrailingTrivia() - { - var code = @" -Module Program - Sub Main(args As String()) - [|If args IsNot Nothing Then - System.Console.WriteLine(args) - EndIf IdentifierToken|] - End Sub -End Module"; - - var expected = @" -Module Program - Sub Main(args As String()) - If args IsNot Nothing Then - System.Console.WriteLine(args) - End If IdentifierToken - End Sub -End Module"; - await VerifyAsync(code, expected); - } + public Task FixEndIfKeyword_WithIdentifierTokenTrailingTrivia() + => VerifyAsync(""" + + Module Program + Sub Main(args As String()) + [|If args IsNot Nothing Then + System.Console.WriteLine(args) + EndIf IdentifierToken|] + End Sub + End Module + """, """ + + Module Program + Sub Main(args As String()) + If args IsNot Nothing Then + System.Console.WriteLine(args) + End If IdentifierToken + End Sub + End Module + """); [Fact, WorkItem(17313, "DevDiv_Projects/Roslyn")] - public async Task FixEndIfKeyword_InvalidDirectiveCases_02() - { - var code = @"[| -' BadDirective cases -#If c = 0 Then -#Endif #IdentifierToken + public Task FixEndIfKeyword_InvalidDirectiveCases_02() + => VerifyAsync(""" + [| + ' BadDirective cases + #If c = 0 Then + #Endif #IdentifierToken -#If c = 0 Then -#Endif IdentifierToken# + #If c = 0 Then + #Endif IdentifierToken# -#If c = 0 Then -#Endif IdentifierToken + #If c = 0 Then + #Endif IdentifierToken -' Missing EndIfDirective cases -#If c = 0 Then -#Endif -#IdentifierToken + ' Missing EndIfDirective cases + #If c = 0 Then + #Endif + #IdentifierToken -#If c = 0 Then -#Endif -IdentifierToken# + #If c = 0 Then + #Endif + IdentifierToken# -#If c = 0 Then -#Endif -IdentifierToken -|]"; + #If c = 0 Then + #Endif + IdentifierToken + |] + """, """ - var expected = @" -' BadDirective cases -#If c = 0 Then -#End If #IdentifierToken + ' BadDirective cases + #If c = 0 Then + #End If #IdentifierToken -#If c = 0 Then -#End If IdentifierToken# + #If c = 0 Then + #End If IdentifierToken# -#If c = 0 Then -#End If IdentifierToken + #If c = 0 Then + #End If IdentifierToken -' Missing EndIfDirective cases -#If c = 0 Then -#End If -#IdentifierToken + ' Missing EndIfDirective cases + #If c = 0 Then + #End If + #IdentifierToken -#If c = 0 Then -#End If -IdentifierToken# + #If c = 0 Then + #End If + IdentifierToken# -#If c = 0 Then -#End If -IdentifierToken -"; - await VerifyAsync(code, expected); - } + #If c = 0 Then + #End If + IdentifierToken + + """); [Fact, WorkItem(17313, "DevDiv_Projects/Roslyn")] - public async Task FixEndIfKeyword_WithLeadingAndTrailingTrivia() - { - var code = @" -Module Program - Sub Main(args As String()) - [|If args IsNot Nothing Then - System.Console.WriteLine(args) -' Dummy EndIf -EndIf -' Dummy EndIf|] - End Sub -End Module"; - - var expected = @" -Module Program - Sub Main(args As String()) - If args IsNot Nothing Then - System.Console.WriteLine(args) + public Task FixEndIfKeyword_WithLeadingAndTrailingTrivia() + => VerifyAsync(""" + + Module Program + Sub Main(args As String()) + [|If args IsNot Nothing Then + System.Console.WriteLine(args) ' Dummy EndIf - End If - ' Dummy EndIf - End Sub -End Module"; - await VerifyAsync(code, expected); - } + EndIf + ' Dummy EndIf|] + End Sub + End Module + """, """ + + Module Program + Sub Main(args As String()) + If args IsNot Nothing Then + System.Console.WriteLine(args) + ' Dummy EndIf + End If + ' Dummy EndIf + End Sub + End Module + """); [Fact, WorkItem(17313, "DevDiv_Projects/Roslyn")] - public async Task FixEndIfKeyword_WithLeadingAndTrailingTrivia_Directive() - { - var code = @"[| -#If c = 0 Then -'#Endif -#Endif '#Endif -|]"; - - var expected = @" -#If c = 0 Then -'#Endif -#End If '#Endif -"; - await VerifyAsync(code, expected); - } + public Task FixEndIfKeyword_WithLeadingAndTrailingTrivia_Directive() + => VerifyAsync(""" + [| + #If c = 0 Then + '#Endif + #Endif '#Endif + |] + """, """ + + #If c = 0 Then + '#Endif + #End If '#Endif + + """); [Fact, WorkItem(17313, "DevDiv_Projects/Roslyn")] - public async Task FixEndIfKeyword_WithLeadingAndTrailingInvocationExpressions() - { - var code = @" -Module Program - Sub Main(args As String()) - [|If args IsNot Nothing Then - System.Console.WriteLine(args) -IdentifierToken -EndIf -IdentifierToken|] - End Sub -End Module"; - - var expected = @" -Module Program - Sub Main(args As String()) - If args IsNot Nothing Then - System.Console.WriteLine(args) + public Task FixEndIfKeyword_WithLeadingAndTrailingInvocationExpressions() + => VerifyAsync(""" + + Module Program + Sub Main(args As String()) + [|If args IsNot Nothing Then + System.Console.WriteLine(args) IdentifierToken - End If - IdentifierToken - End Sub -End Module"; - await VerifyAsync(code, expected); - } + EndIf + IdentifierToken|] + End Sub + End Module + """, """ + + Module Program + Sub Main(args As String()) + If args IsNot Nothing Then + System.Console.WriteLine(args) + IdentifierToken + End If + IdentifierToken + End Sub + End Module + """); [Fact, WorkItem(17313, "DevDiv_Projects/Roslyn")] - public async Task FixEndIfKeyword_WithLeadingAndTrailingInvocationExpressions_Directive() - { - var code = @"[| -' BadDirective cases -#If c = 0 Then -#InvalidTrivia #Endif #InvalidTrivia + public Task FixEndIfKeyword_WithLeadingAndTrailingInvocationExpressions_Directive() + => VerifyAsync(""" + [| + ' BadDirective cases + #If c = 0 Then + #InvalidTrivia #Endif #InvalidTrivia -#If c = 0 Then -InvalidTrivia #Endif InvalidTrivia + #If c = 0 Then + InvalidTrivia #Endif InvalidTrivia -#If c = 0 Then -InvalidTrivia# #Endif InvalidTrivia# + #If c = 0 Then + InvalidTrivia# #Endif InvalidTrivia# -' Missing EndIfDirective cases -#If c = 0 Then -#InvalidTrivia -#Endif #InvalidTrivia + ' Missing EndIfDirective cases + #If c = 0 Then + #InvalidTrivia + #Endif #InvalidTrivia -#If c = 0 Then -InvalidTrivia -#Endif InvalidTrivia + #If c = 0 Then + InvalidTrivia + #Endif InvalidTrivia -#If c = 0 Then -InvalidTrivia# -#Endif InvalidTrivia# -|]"; + #If c = 0 Then + InvalidTrivia# + #Endif InvalidTrivia# + |] + """, """ - var expected = @" -' BadDirective cases -#If c = 0 Then -#InvalidTrivia #Endif #InvalidTrivia + ' BadDirective cases + #If c = 0 Then + #InvalidTrivia #Endif #InvalidTrivia -#If c = 0 Then -InvalidTrivia #Endif InvalidTrivia + #If c = 0 Then + InvalidTrivia #Endif InvalidTrivia -#If c = 0 Then -InvalidTrivia# #Endif InvalidTrivia# + #If c = 0 Then + InvalidTrivia# #Endif InvalidTrivia# -' Missing EndIfDirective cases -#If c = 0 Then -#InvalidTrivia -#End If #InvalidTrivia + ' Missing EndIfDirective cases + #If c = 0 Then + #InvalidTrivia + #End If #InvalidTrivia -#If c = 0 Then -InvalidTrivia -#End If InvalidTrivia + #If c = 0 Then + InvalidTrivia + #End If InvalidTrivia -#If c = 0 Then -InvalidTrivia# -#End If InvalidTrivia# -"; - await VerifyAsync(code, expected); - } + #If c = 0 Then + InvalidTrivia# + #End If InvalidTrivia# + + """); [Fact, WorkItem(5722, "DevDiv_Projects/Roslyn")] - public async Task FixPrimitiveTypeKeywords_ValidCases() - { - var code = @"[| -Imports SystemAlias = System -Imports SystemInt16Alias = System.Short -Imports SystemUInt16Alias = System.ushort -Imports SystemInt32Alias = System.INTEGER -Imports SystemUInt32Alias = System.UInteger -Imports SystemInt64Alias = System.Long -Imports SystemUInt64Alias = System.uLong -Imports SystemDateTimeAlias = System.Date - -Module Program - Sub Main(args As String()) - Dim a1 As System.Short = 0 - Dim b1 As SystemAlias.SHORT = a1 - Dim c1 As SystemInt16Alias = b1 - - Dim a2 As System.UShort = 0 - Dim b2 As SystemAlias.USHORT = a2 - Dim c2 As SystemUInt16Alias = b2 - - Dim a3 As System.Integer = 0 - Dim b3 As SystemAlias.INTEGER = a3 - Dim c3 As SystemInt32Alias = b3 - - Dim a4 As System.UInteger = 0 - Dim b4 As SystemAlias.UINTEGER = a4 - Dim c4 As SystemUInt32Alias = b4 - - Dim a5 As System.Long = 0 - Dim b5 As SystemAlias.LONG = a5 - Dim c5 As SystemInt64Alias = b5 - - Dim a6 As System.ULong = 0 - Dim b6 As SystemAlias.ULONG = 0 - Dim c6 As SystemUInt64Alias = 0 - - Dim a7 As System.Date = Nothing - Dim b7 As SystemAlias.DATE = Nothing - Dim c7 As SystemDateTimeAlias = Nothing - End Sub -End Module -|]"; - - var expected = @" -Imports SystemAlias = System -Imports SystemInt16Alias = System.Int16 -Imports SystemUInt16Alias = System.UInt16 -Imports SystemInt32Alias = System.Int32 -Imports SystemUInt32Alias = System.UInt32 -Imports SystemInt64Alias = System.Int64 -Imports SystemUInt64Alias = System.UInt64 -Imports SystemDateTimeAlias = System.DateTime - -Module Program - Sub Main(args As String()) - Dim a1 As System.Int16 = 0 - Dim b1 As SystemAlias.Int16 = a1 - Dim c1 As SystemInt16Alias = b1 - - Dim a2 As System.UInt16 = 0 - Dim b2 As SystemAlias.UInt16 = a2 - Dim c2 As SystemUInt16Alias = b2 - - Dim a3 As System.Int32 = 0 - Dim b3 As SystemAlias.Int32 = a3 - Dim c3 As SystemInt32Alias = b3 - - Dim a4 As System.UInt32 = 0 - Dim b4 As SystemAlias.UInt32 = a4 - Dim c4 As SystemUInt32Alias = b4 - - Dim a5 As System.Int64 = 0 - Dim b5 As SystemAlias.Int64 = a5 - Dim c5 As SystemInt64Alias = b5 - - Dim a6 As System.UInt64 = 0 - Dim b6 As SystemAlias.UInt64 = 0 - Dim c6 As SystemUInt64Alias = 0 - - Dim a7 As System.DateTime = Nothing - Dim b7 As SystemAlias.DateTime = Nothing - Dim c7 As SystemDateTimeAlias = Nothing - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task FixPrimitiveTypeKeywords_ValidCases() + => VerifyAsync(""" + [| + Imports SystemAlias = System + Imports SystemInt16Alias = System.Short + Imports SystemUInt16Alias = System.ushort + Imports SystemInt32Alias = System.INTEGER + Imports SystemUInt32Alias = System.UInteger + Imports SystemInt64Alias = System.Long + Imports SystemUInt64Alias = System.uLong + Imports SystemDateTimeAlias = System.Date + + Module Program + Sub Main(args As String()) + Dim a1 As System.Short = 0 + Dim b1 As SystemAlias.SHORT = a1 + Dim c1 As SystemInt16Alias = b1 + + Dim a2 As System.UShort = 0 + Dim b2 As SystemAlias.USHORT = a2 + Dim c2 As SystemUInt16Alias = b2 + + Dim a3 As System.Integer = 0 + Dim b3 As SystemAlias.INTEGER = a3 + Dim c3 As SystemInt32Alias = b3 + + Dim a4 As System.UInteger = 0 + Dim b4 As SystemAlias.UINTEGER = a4 + Dim c4 As SystemUInt32Alias = b4 + + Dim a5 As System.Long = 0 + Dim b5 As SystemAlias.LONG = a5 + Dim c5 As SystemInt64Alias = b5 + + Dim a6 As System.ULong = 0 + Dim b6 As SystemAlias.ULONG = 0 + Dim c6 As SystemUInt64Alias = 0 + + Dim a7 As System.Date = Nothing + Dim b7 As SystemAlias.DATE = Nothing + Dim c7 As SystemDateTimeAlias = Nothing + End Sub + End Module + |] + """, """ + + Imports SystemAlias = System + Imports SystemInt16Alias = System.Int16 + Imports SystemUInt16Alias = System.UInt16 + Imports SystemInt32Alias = System.Int32 + Imports SystemUInt32Alias = System.UInt32 + Imports SystemInt64Alias = System.Int64 + Imports SystemUInt64Alias = System.UInt64 + Imports SystemDateTimeAlias = System.DateTime + + Module Program + Sub Main(args As String()) + Dim a1 As System.Int16 = 0 + Dim b1 As SystemAlias.Int16 = a1 + Dim c1 As SystemInt16Alias = b1 + + Dim a2 As System.UInt16 = 0 + Dim b2 As SystemAlias.UInt16 = a2 + Dim c2 As SystemUInt16Alias = b2 + + Dim a3 As System.Int32 = 0 + Dim b3 As SystemAlias.Int32 = a3 + Dim c3 As SystemInt32Alias = b3 + + Dim a4 As System.UInt32 = 0 + Dim b4 As SystemAlias.UInt32 = a4 + Dim c4 As SystemUInt32Alias = b4 + + Dim a5 As System.Int64 = 0 + Dim b5 As SystemAlias.Int64 = a5 + Dim c5 As SystemInt64Alias = b5 + + Dim a6 As System.UInt64 = 0 + Dim b6 As SystemAlias.UInt64 = 0 + Dim c6 As SystemUInt64Alias = 0 + + Dim a7 As System.DateTime = Nothing + Dim b7 As SystemAlias.DateTime = Nothing + Dim c7 As SystemDateTimeAlias = Nothing + End Sub + End Module + + """); [Fact, WorkItem(5722, "DevDiv_Projects/Roslyn")] public async Task FixPrimitiveTypeKeywords_InvalidCases() { // With a user defined type named System // No fixups as System binds to type not a namespace. - var code = @" -Imports SystemAlias = System -Imports SystemInt16Alias = System.Short -Imports SystemUInt16Alias = System.ushort -Imports SystemInt32Alias = System.INTEGER -Imports SystemUInt32Alias = System.UInteger -Imports SystemInt64Alias = System.Long -Imports SystemUInt64Alias = System.uLong -Imports SystemDateTimeAlias = System.Date - -Class System -End Class - -Module Program - Sub Main(args As String()) - Dim a1 As System.Short = 0 - Dim b1 As SystemAlias.SHORT = a1 - Dim c1 As SystemInt16Alias = b1 - Dim d1 As System.System.Short = 0 - Dim e1 As Short = 0 - - Dim a2 As System.UShort = 0 - Dim b2 As SystemAlias.USHORT = a2 - Dim c2 As SystemUInt16Alias = b2 - Dim d2 As System.System.UShort = 0 - Dim e2 As UShort = 0 - - Dim a3 As System.Integer = 0 - Dim b3 As SystemAlias.INTEGER = a3 - Dim c3 As SystemInt32Alias = b3 - Dim d3 As System.System.Integer = 0 - Dim e3 As Integer = 0 - - Dim a4 As System.UInteger = 0 - Dim b4 As SystemAlias.UINTEGER = a4 - Dim c4 As SystemUInt32Alias = b4 - Dim d4 As System.System.UInteger = 0 - Dim e4 As UInteger = 0 - - Dim a5 As System.Long = 0 - Dim b5 As SystemAlias.LONG = a5 - Dim c5 As SystemInt64Alias = b5 - Dim d5 As System.System.Long = 0 - Dim e5 As Long = 0 - - Dim a6 As System.ULong = 0 - Dim b6 As SystemAlias.ULONG = 0 - Dim c6 As SystemUInt64Alias = 0 - Dim d6 As System.System.ULong = 0 - Dim e6 As ULong = 0 - - Dim a7 As System.Date = Nothing - Dim b7 As SystemAlias.DATE = Nothing - Dim c7 As SystemDateTimeAlias = Nothing - Dim d7 As System.System.Date = 0 - Dim e7 As Date = 0 - End Sub -End Module -"; + var code = """ + + Imports SystemAlias = System + Imports SystemInt16Alias = System.Short + Imports SystemUInt16Alias = System.ushort + Imports SystemInt32Alias = System.INTEGER + Imports SystemUInt32Alias = System.UInteger + Imports SystemInt64Alias = System.Long + Imports SystemUInt64Alias = System.uLong + Imports SystemDateTimeAlias = System.Date + + Class System + End Class + + Module Program + Sub Main(args As String()) + Dim a1 As System.Short = 0 + Dim b1 As SystemAlias.SHORT = a1 + Dim c1 As SystemInt16Alias = b1 + Dim d1 As System.System.Short = 0 + Dim e1 As Short = 0 + + Dim a2 As System.UShort = 0 + Dim b2 As SystemAlias.USHORT = a2 + Dim c2 As SystemUInt16Alias = b2 + Dim d2 As System.System.UShort = 0 + Dim e2 As UShort = 0 + + Dim a3 As System.Integer = 0 + Dim b3 As SystemAlias.INTEGER = a3 + Dim c3 As SystemInt32Alias = b3 + Dim d3 As System.System.Integer = 0 + Dim e3 As Integer = 0 + + Dim a4 As System.UInteger = 0 + Dim b4 As SystemAlias.UINTEGER = a4 + Dim c4 As SystemUInt32Alias = b4 + Dim d4 As System.System.UInteger = 0 + Dim e4 As UInteger = 0 + + Dim a5 As System.Long = 0 + Dim b5 As SystemAlias.LONG = a5 + Dim c5 As SystemInt64Alias = b5 + Dim d5 As System.System.Long = 0 + Dim e5 As Long = 0 + + Dim a6 As System.ULong = 0 + Dim b6 As SystemAlias.ULONG = 0 + Dim c6 As SystemUInt64Alias = 0 + Dim d6 As System.System.ULong = 0 + Dim e6 As ULong = 0 + + Dim a7 As System.Date = Nothing + Dim b7 As SystemAlias.DATE = Nothing + Dim c7 As SystemDateTimeAlias = Nothing + Dim d7 As System.System.Date = 0 + Dim e7 As Date = 0 + End Sub + End Module + + """; await VerifyAsync(@"[|" + code + @"|]", expectedResult: code); // No Fixes in trivia - code = @" -Imports SystemAlias = System -'Imports SystemInt16Alias = System.Short - -Module Program - Sub Main(args As String()) - ' Dim a1 As System.Short = 0 - ' Dim b1 As SystemAlias.SHORT = a1 - End Sub -End Module -"; + code = """ + + Imports SystemAlias = System + 'Imports SystemInt16Alias = System.Short + + Module Program + Sub Main(args As String()) + ' Dim a1 As System.Short = 0 + ' Dim b1 As SystemAlias.SHORT = a1 + End Sub + End Module + + """; await VerifyAsync(@"[|" + code + @"|]", expectedResult: code); } [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/606015")] - public async Task FixFullWidthSingleQuotes() - { - var code = @"[| -‘fullwidth 1  -’fullwidth 2 -‘‘fullwidth 3 -’'fullwidth 4 -'‘fullwidth 5 -‘’fullwidth 6 -‘’‘’fullwidth 7 -'‘’‘’fullwidth 8|]"; - - var expected = @" -'fullwidth 1  -'fullwidth 2 -'‘fullwidth 3 -''fullwidth 4 -'‘fullwidth 5 -'’fullwidth 6 -'’‘’fullwidth 7 -'‘’‘’fullwidth 8"; - await VerifyAsync(code, expected); - } + public Task FixFullWidthSingleQuotes() + => VerifyAsync(""" + [| + ‘fullwidth 1  + ’fullwidth 2 + ‘‘fullwidth 3 + ’'fullwidth 4 + '‘fullwidth 5 + ‘’fullwidth 6 + ‘’‘’fullwidth 7 + '‘’‘’fullwidth 8|] + """, """ + + 'fullwidth 1  + 'fullwidth 2 + '‘fullwidth 3 + ''fullwidth 4 + '‘fullwidth 5 + '’fullwidth 6 + '’‘’fullwidth 7 + '‘’‘’fullwidth 8 + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/707135")] public async Task FixFullWidthSingleQuotes2() @@ -718,11 +701,7 @@ public async Task FixFullWidthSingleQuotes2() { System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("zh-CN"); - - var code = @"[|‘’fullwidth 1|]"; - - var expected = @"'’fullwidth 1"; - await VerifyAsync(code, expected); + await VerifyAsync(@"[|‘’fullwidth 1|]", @"'’fullwidth 1"); } finally { diff --git a/src/Workspaces/CoreTest/CodeCleanup/NormalizeModifiersOrOperatorsTests.cs b/src/Workspaces/CoreTest/CodeCleanup/NormalizeModifiersOrOperatorsTests.cs index eda535a3d5115..e2fd93500319b 100644 --- a/src/Workspaces/CoreTest/CodeCleanup/NormalizeModifiersOrOperatorsTests.cs +++ b/src/Workspaces/CoreTest/CodeCleanup/NormalizeModifiersOrOperatorsTests.cs @@ -20,997 +20,901 @@ namespace Microsoft.CodeAnalysis.UnitTests.CodeCleanup; public sealed class NormalizeModifiersOrOperatorsTests { [Fact] - public async Task PartialMethod() - { - var code = @"[|Class A - Private Partial Sub() - End Sub -End Class|]"; - - var expected = @"Class A - Partial Private Sub() - End Sub -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task PartialClass() - { - var code = @"[|Public Partial Class A -End Class|]"; - - var expected = @"Partial Public Class A -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task DefaultProperty() - { - var code = @"[|Class Class1 - Public Default Property prop1(i As Integer) As Integer - Get - Return i - End Get - Set(ByVal value As Integer) - End Set - End Property -End Class|]"; - - var expected = @"Class Class1 - Default Public Property prop1(i As Integer) As Integer - Get - Return i - End Get - Set(ByVal value As Integer) - End Set - End Property -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task Accessors() - { - var code = @"[|Public Module M -End Module - -NotInheritable Friend Class C - MustInherit Protected Friend Class N - Overridable Public Sub Test() - End Sub - - MustOverride Protected Sub Test2() - - Shared Private Sub Test3() - End Sub - End Class - - Public Class O - Inherits N - - Shadows Public Sub Test() - End Sub - - Overrides Protected Sub Test2() - End Sub - End Class -End Class|]"; - - var expected = @"Public Module M -End Module - -Friend NotInheritable Class C - Protected Friend MustInherit Class N - Public Overridable Sub Test() - End Sub - - Protected MustOverride Sub Test2() - - Private Shared Sub Test3() - End Sub - End Class - - Public Class O - Inherits N - - Public Shadows Sub Test() - End Sub - - Protected Overrides Sub Test2() - End Sub - End Class -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task Structure() - { - var code = @"[|Public Partial Structure S -End Structure|]"; - - var expected = @"Partial Public Structure S -End Structure"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task Interface() - { - var code = @"[|Public Interface O - Public Interface S - End Interface -End Interface - -Public Interface O2 - Inherits O - - Shadows Public Interface S - End Interface -End Interface|]"; - - var expected = @"Public Interface O - Public Interface S - End Interface -End Interface - -Public Interface O2 - Inherits O - - Public Shadows Interface S - End Interface -End Interface"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task Class() - { - var code = @"[|MustInherit Public Class C -End Class|]"; - - var expected = @"Public MustInherit Class C -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task Enum() - { - var code = @"[|Public Class O - Public Enum S - None - End Enum -End Class - -Public Class O2 - Inherits O - - Shadows Public Enum S - None - End Enum -End Class|]"; - - var expected = @"Public Class O - Public Enum S - None - End Enum -End Class - -Public Class O2 - Inherits O - - Public Shadows Enum S - None - End Enum -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task Method() - { - var code = @"[|Public Class O - Overridable Protected Function Test() As Integer - Return 0 - End Function -End Class|]"; - - var expected = @"Public Class O - Protected Overridable Function Test() As Integer - Return 0 - End Function -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task Declare() - { - var code = @"[|Class C - Overloads Public Declare Function getUserName Lib ""advapi32.dll"" Alias ""GetUserNameA"" (ByVal lpBuffer As String, ByRef nSize As Integer) As Integer -End Class|]"; - - var expected = @"Class C - Public Overloads Declare Function getUserName Lib ""advapi32.dll"" Alias ""GetUserNameA"" (ByVal lpBuffer As String, ByRef nSize As Integer) As Integer -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task Delegate() - { - var code = @"[|Public Class O - Public Delegate Function S() As Integer -End Class - -Public Class O2 - Inherits O - - Shadows Public Delegate Function S() As Integer -End Class|]"; - - var expected = @"Public Class O - Public Delegate Function S() As Integer -End Class - -Public Class O2 - Inherits O - - Public Shadows Delegate Function S() As Integer -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task Event() - { - var code = @"[|Public Class O - Shared Public Event Test As System.EventHandler -End Class|]"; - - var expected = @"Public Class O - Public Shared Event Test As System.EventHandler -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task Operator() - { - var code = @"[|Public Structure abc - Shared Overloads Public Operator And(ByVal x As abc, ByVal y As abc) As abc - End Operator -End Structure|]"; - - var expected = @"Public Structure abc - Public Overloads Shared Operator And(ByVal x As abc, ByVal y As abc) As abc - End Operator -End Structure"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task Property() - { - var code = @"[|Class Class1 - Overridable Public Property prop1 As Integer -End Class|]"; - - var expected = @"Class Class1 - Public Overridable Property prop1 As Integer -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task Accessor() - { - var code = @"[|Class Class1 - Public Property prop1 As Integer - Private Get - Return 0 - End Get - Set(value As Integer) - - End Set - End Property -End Class|]"; - - var expected = @"Class Class1 - Public Property prop1 As Integer - Private Get - Return 0 - End Get - Set(value As Integer) - - End Set - End Property -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task IncompleteMember() - { - var code = @"[|Class Program - Shared Private Dim -End Class|]"; - - var expected = @"Class Program - Shared Private Dim -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task Field() - { - var code = @"[|Class Program - Shared ReadOnly Private Dim f = 1 -End Class|]"; - - var expected = @"Class Program - Private Shared ReadOnly f = 1 -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task NotOverridable_Overridable_Overrides() - { - var code = @"[|Public Class Program - Class N - Inherits Program - - Overrides Public NotOverridable Sub test() - MyBase.test() - End Sub - End Class - - Overridable Public Sub test() - End Sub -End Class|]"; - - var expected = @"Public Class Program - Class N - Inherits Program - - Public NotOverridable Overrides Sub test() - MyBase.test() - End Sub - End Class - - Public Overridable Sub test() - End Sub -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task MustOverride_MustInherit() - { - var code = @"[|MustInherit Public Class Program - MustOverride Public Sub test() -End Class|]"; - - var expected = @"Public MustInherit Class Program - Public MustOverride Sub test() -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task Overloads() - { - var code = @"[|Public MustInherit Class Program - Overloads Public Sub test() - End Sub - - Overloads Public Sub test(i As Integer) - End Sub -End Class|]"; - - var expected = @"Public MustInherit Class Program - Public Overloads Sub test() - End Sub - - Public Overloads Sub test(i As Integer) - End Sub -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task NotInheritable() - { - var code = @"[|NotInheritable Public Class Program -End Class|]"; - - var expected = @"Public NotInheritable Class Program -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task Shared_Shadow_ReadOnly_Const() - { - var code = @"[|Class C - Class N - Public Sub Test() - End Sub - - Const Private Dim c As Integer = 2 - Shared ReadOnly Private Dim f = 1 - End Class - - Public Class O - Inherits N - - Shadows Public Sub Test() - End Sub - End Class -End Class|]"; - - var expected = @"Class C - Class N - Public Sub Test() - End Sub - - Private Const c As Integer = 2 - Private Shared ReadOnly f = 1 - End Class - - Public Class O - Inherits N - - Public Shadows Sub Test() - End Sub - End Class -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task WriteOnly() - { - var code = @"[|Class C - WriteOnly Public Property Test - Set(value) - End Set - End Property -End Class|]"; - - var expected = @"Class C - Public WriteOnly Property Test - Set(value) - End Set - End Property -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task WithEvent_Custom_Dim() - { - var code = @"[|Imports System - -Public Class A - Public Custom Event MyEvent As EventHandler - AddHandler(value As EventHandler) - End AddHandler - - RemoveHandler(value As EventHandler) - End RemoveHandler - - RaiseEvent(sender As Object, e As EventArgs) - End RaiseEvent - End Event -End Class - -Class B - WithEvents Dim EventSource As A - Public Sub EventHandler(s As Object, a As EventArgs) Handles EventSource.MyEvent - End Sub -End Class|]"; - - var expected = @"Imports System - -Public Class A - Public Custom Event MyEvent As EventHandler - AddHandler(value As EventHandler) - End AddHandler - - RemoveHandler(value As EventHandler) - End RemoveHandler - - RaiseEvent(sender As Object, e As EventArgs) - End RaiseEvent - End Event -End Class - -Class B - Dim WithEvents EventSource As A - Public Sub EventHandler(s As Object, a As EventArgs) Handles EventSource.MyEvent - End Sub -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task Widening_Narrowing() - { - var code = @"[|Public Structure digit -Widening Shared Public Operator CType(ByVal d As digit) As Byte - Return 0 - End Operator - Narrowing Public Shared Operator CType(ByVal b As Byte) As digit - Return Nothing - End Operator -End Structure|]"; - - var expected = @"Public Structure digit - Public Shared Widening Operator CType(ByVal d As digit) As Byte - Return 0 - End Operator - Public Shared Narrowing Operator CType(ByVal b As Byte) As digit - Return Nothing - End Operator -End Structure"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task Static_Const_Dim() - { - var code = @"[|Class A - Sub Method() - Dim Static a As Integer = 1 - Const a2 As Integer = 2 - End Sub -End Class|]"; - - var expected = @"Class A - Sub Method() - Static Dim a As Integer = 1 - Const a2 As Integer = 2 - End Sub -End Class"; - - await VerifyAsync(code, expected); - } + public Task PartialMethod() + => VerifyAsync(""" + [|Class A + Private Partial Sub() + End Sub + End Class|] + """, """ + Class A + Partial Private Sub() + End Sub + End Class + """); + + [Fact] + public Task PartialClass() + => VerifyAsync(""" + [|Public Partial Class A + End Class|] + """, """ + Partial Public Class A + End Class + """); + + [Fact] + public Task DefaultProperty() + => VerifyAsync(""" + [|Class Class1 + Public Default Property prop1(i As Integer) As Integer + Get + Return i + End Get + Set(ByVal value As Integer) + End Set + End Property + End Class|] + """, """ + Class Class1 + Default Public Property prop1(i As Integer) As Integer + Get + Return i + End Get + Set(ByVal value As Integer) + End Set + End Property + End Class + """); + + [Fact] + public Task Accessors() + => VerifyAsync(""" + [|Public Module M + End Module + + NotInheritable Friend Class C + MustInherit Protected Friend Class N + Overridable Public Sub Test() + End Sub + + MustOverride Protected Sub Test2() + + Shared Private Sub Test3() + End Sub + End Class + + Public Class O + Inherits N + + Shadows Public Sub Test() + End Sub + + Overrides Protected Sub Test2() + End Sub + End Class + End Class|] + """, """ + Public Module M + End Module + + Friend NotInheritable Class C + Protected Friend MustInherit Class N + Public Overridable Sub Test() + End Sub + + Protected MustOverride Sub Test2() + + Private Shared Sub Test3() + End Sub + End Class + + Public Class O + Inherits N + + Public Shadows Sub Test() + End Sub + + Protected Overrides Sub Test2() + End Sub + End Class + End Class + """); + + [Fact] + public Task Structure() + => VerifyAsync(""" + [|Public Partial Structure S + End Structure|] + """, """ + Partial Public Structure S + End Structure + """); + + [Fact] + public Task Interface() + => VerifyAsync(""" + [|Public Interface O + Public Interface S + End Interface + End Interface + + Public Interface O2 + Inherits O + + Shadows Public Interface S + End Interface + End Interface|] + """, """ + Public Interface O + Public Interface S + End Interface + End Interface + + Public Interface O2 + Inherits O + + Public Shadows Interface S + End Interface + End Interface + """); + + [Fact] + public Task Class() + => VerifyAsync(""" + [|MustInherit Public Class C + End Class|] + """, """ + Public MustInherit Class C + End Class + """); + + [Fact] + public Task Enum() + => VerifyAsync(""" + [|Public Class O + Public Enum S + None + End Enum + End Class + + Public Class O2 + Inherits O + + Shadows Public Enum S + None + End Enum + End Class|] + """, """ + Public Class O + Public Enum S + None + End Enum + End Class + + Public Class O2 + Inherits O + + Public Shadows Enum S + None + End Enum + End Class + """); + + [Fact] + public Task Method() + => VerifyAsync(""" + [|Public Class O + Overridable Protected Function Test() As Integer + Return 0 + End Function + End Class|] + """, """ + Public Class O + Protected Overridable Function Test() As Integer + Return 0 + End Function + End Class + """); + + [Fact] + public Task Declare() + => VerifyAsync(""" + [|Class C + Overloads Public Declare Function getUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, ByRef nSize As Integer) As Integer + End Class|] + """, """ + Class C + Public Overloads Declare Function getUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, ByRef nSize As Integer) As Integer + End Class + """); + + [Fact] + public Task Delegate() + => VerifyAsync(""" + [|Public Class O + Public Delegate Function S() As Integer + End Class + + Public Class O2 + Inherits O + + Shadows Public Delegate Function S() As Integer + End Class|] + """, """ + Public Class O + Public Delegate Function S() As Integer + End Class + + Public Class O2 + Inherits O + + Public Shadows Delegate Function S() As Integer + End Class + """); + + [Fact] + public Task Event() + => VerifyAsync(""" + [|Public Class O + Shared Public Event Test As System.EventHandler + End Class|] + """, """ + Public Class O + Public Shared Event Test As System.EventHandler + End Class + """); + + [Fact] + public Task Operator() + => VerifyAsync(""" + [|Public Structure abc + Shared Overloads Public Operator And(ByVal x As abc, ByVal y As abc) As abc + End Operator + End Structure|] + """, """ + Public Structure abc + Public Overloads Shared Operator And(ByVal x As abc, ByVal y As abc) As abc + End Operator + End Structure + """); + + [Fact] + public Task Property() + => VerifyAsync(""" + [|Class Class1 + Overridable Public Property prop1 As Integer + End Class|] + """, """ + Class Class1 + Public Overridable Property prop1 As Integer + End Class + """); + + [Fact] + public Task Accessor() + => VerifyAsync(""" + [|Class Class1 + Public Property prop1 As Integer + Private Get + Return 0 + End Get + Set(value As Integer) + + End Set + End Property + End Class|] + """, """ + Class Class1 + Public Property prop1 As Integer + Private Get + Return 0 + End Get + Set(value As Integer) + + End Set + End Property + End Class + """); + + [Fact] + public Task IncompleteMember() + => VerifyAsync(""" + [|Class Program + Shared Private Dim + End Class|] + """, """ + Class Program + Shared Private Dim + End Class + """); + + [Fact] + public Task Field() + => VerifyAsync(""" + [|Class Program + Shared ReadOnly Private Dim f = 1 + End Class|] + """, """ + Class Program + Private Shared ReadOnly f = 1 + End Class + """); + + [Fact] + public Task NotOverridable_Overridable_Overrides() + => VerifyAsync(""" + [|Public Class Program + Class N + Inherits Program + + Overrides Public NotOverridable Sub test() + MyBase.test() + End Sub + End Class + + Overridable Public Sub test() + End Sub + End Class|] + """, """ + Public Class Program + Class N + Inherits Program + + Public NotOverridable Overrides Sub test() + MyBase.test() + End Sub + End Class + + Public Overridable Sub test() + End Sub + End Class + """); + + [Fact] + public Task MustOverride_MustInherit() + => VerifyAsync(""" + [|MustInherit Public Class Program + MustOverride Public Sub test() + End Class|] + """, """ + Public MustInherit Class Program + Public MustOverride Sub test() + End Class + """); + + [Fact] + public Task Overloads() + => VerifyAsync(""" + [|Public MustInherit Class Program + Overloads Public Sub test() + End Sub + + Overloads Public Sub test(i As Integer) + End Sub + End Class|] + """, """ + Public MustInherit Class Program + Public Overloads Sub test() + End Sub + + Public Overloads Sub test(i As Integer) + End Sub + End Class + """); + + [Fact] + public Task NotInheritable() + => VerifyAsync(""" + [|NotInheritable Public Class Program + End Class|] + """, """ + Public NotInheritable Class Program + End Class + """); + + [Fact] + public Task Shared_Shadow_ReadOnly_Const() + => VerifyAsync(""" + [|Class C + Class N + Public Sub Test() + End Sub + + Const Private Dim c As Integer = 2 + Shared ReadOnly Private Dim f = 1 + End Class + + Public Class O + Inherits N + + Shadows Public Sub Test() + End Sub + End Class + End Class|] + """, """ + Class C + Class N + Public Sub Test() + End Sub + + Private Const c As Integer = 2 + Private Shared ReadOnly f = 1 + End Class + + Public Class O + Inherits N + + Public Shadows Sub Test() + End Sub + End Class + End Class + """); + + [Fact] + public Task WriteOnly() + => VerifyAsync(""" + [|Class C + WriteOnly Public Property Test + Set(value) + End Set + End Property + End Class|] + """, """ + Class C + Public WriteOnly Property Test + Set(value) + End Set + End Property + End Class + """); + + [Fact] + public Task WithEvent_Custom_Dim() + => VerifyAsync(""" + [|Imports System + + Public Class A + Public Custom Event MyEvent As EventHandler + AddHandler(value As EventHandler) + End AddHandler + + RemoveHandler(value As EventHandler) + End RemoveHandler + + RaiseEvent(sender As Object, e As EventArgs) + End RaiseEvent + End Event + End Class + + Class B + WithEvents Dim EventSource As A + Public Sub EventHandler(s As Object, a As EventArgs) Handles EventSource.MyEvent + End Sub + End Class|] + """, """ + Imports System + + Public Class A + Public Custom Event MyEvent As EventHandler + AddHandler(value As EventHandler) + End AddHandler + + RemoveHandler(value As EventHandler) + End RemoveHandler + + RaiseEvent(sender As Object, e As EventArgs) + End RaiseEvent + End Event + End Class + + Class B + Dim WithEvents EventSource As A + Public Sub EventHandler(s As Object, a As EventArgs) Handles EventSource.MyEvent + End Sub + End Class + """); + + [Fact] + public Task Widening_Narrowing() + => VerifyAsync(""" + [|Public Structure digit + Widening Shared Public Operator CType(ByVal d As digit) As Byte + Return 0 + End Operator + Narrowing Public Shared Operator CType(ByVal b As Byte) As digit + Return Nothing + End Operator + End Structure|] + """, """ + Public Structure digit + Public Shared Widening Operator CType(ByVal d As digit) As Byte + Return 0 + End Operator + Public Shared Narrowing Operator CType(ByVal b As Byte) As digit + Return Nothing + End Operator + End Structure + """); + + [Fact] + public Task Static_Const_Dim() + => VerifyAsync(""" + [|Class A + Sub Method() + Dim Static a As Integer = 1 + Const a2 As Integer = 2 + End Sub + End Class|] + """, """ + Class A + Sub Method() + Static Dim a As Integer = 1 + Const a2 As Integer = 2 + End Sub + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544520")] - public async Task RemoveByVal1() - { - var code = @"[|Class A - Sub Method(ByVal t As String) - End Sub -End Class|]"; - - var expected = @"Class A - Sub Method(ByVal t As String) - End Sub -End Class"; - - await VerifyAsync(code, expected); - } + public Task RemoveByVal1() + => VerifyAsync(""" + [|Class A + Sub Method(ByVal t As String) + End Sub + End Class|] + """, """ + Class A + Sub Method(ByVal t As String) + End Sub + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544520")] - public async Task RemoveByVal2() - { - var code = @"[|Class A - Sub Method(ByVal t As String, ByRef t1 As String) - End Sub -End Class|]"; - - var expected = @"Class A - Sub Method(ByVal t As String, ByRef t1 As String) - End Sub -End Class"; - - await VerifyAsync(code, expected); - } + public Task RemoveByVal2() + => VerifyAsync(""" + [|Class A + Sub Method(ByVal t As String, ByRef t1 As String) + End Sub + End Class|] + """, """ + Class A + Sub Method(ByVal t As String, ByRef t1 As String) + End Sub + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544520")] - public async Task RemoveByVal_LineContinuation() - { - var code = @"[|Class A - Sub Method( _ - ByVal _ - _ - t As String, ByRef t1 As String) - End Sub -End Class|]"; - - var expected = @"Class A - Sub Method( _ - ByVal _ - _ - t As String, ByRef t1 As String) - End Sub -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task RemoveDim() - { - var code = @"[|Class A - Dim Shared Private a As Integer = 1 -End Class|]"; - - var expected = @"Class A - Private Shared a As Integer = 1 -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task RemoveDim_LineContinuation() - { - var code = @"[|Class A - Dim _ - Shared _ - Private _ - a As Integer = 1 -End Class|]"; - - var expected = @"Class A - Private _ - Shared _ - _ - a As Integer = 1 -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task LessThanGreaterThan() - { - var code = @"[|Class A - Sub Test() - If 1 >< 2 Then - End If - End Sub -End Class|]"; - - var expected = @"Class A - Sub Test() - If 1 <> 2 Then - End If - End Sub -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task GreaterThanEquals() - { - var code = @"[|Class A - Sub Test() - If 1 => 2 Then - End If - End Sub -End Class|]"; - - var expected = @"Class A - Sub Test() - If 1 >= 2 Then - End If - End Sub -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task LessThanEquals() - { - var code = @"[|Class A - Sub Test() - If 1 =< 2 Then - End If - End Sub -End Class|]"; - - var expected = @"Class A - Sub Test() - If 1 <= 2 Then - End If - End Sub -End Class"; - - await VerifyAsync(code, expected); - } - - [Fact] - public async Task LessThanEquals_LineContinuation() - { - var code = @"[|Class A - Sub Test() - If 1 _ - = _ - < _ - 2 Then - End If - End Sub -End Class|]"; - - var expected = @"Class A - Sub Test() - If 1 _ - <= _ - 2 Then - End If - End Sub -End Class"; - - await VerifyAsync(code, expected); - } + public Task RemoveByVal_LineContinuation() + => VerifyAsync(""" + [|Class A + Sub Method( _ + ByVal _ + _ + t As String, ByRef t1 As String) + End Sub + End Class|] + """, """ + Class A + Sub Method( _ + ByVal _ + _ + t As String, ByRef t1 As String) + End Sub + End Class + """); + + [Fact] + public Task RemoveDim() + => VerifyAsync(""" + [|Class A + Dim Shared Private a As Integer = 1 + End Class|] + """, """ + Class A + Private Shared a As Integer = 1 + End Class + """); + + [Fact] + public Task RemoveDim_LineContinuation() + => VerifyAsync(""" + [|Class A + Dim _ + Shared _ + Private _ + a As Integer = 1 + End Class|] + """, """ + Class A + Private _ + Shared _ + _ + a As Integer = 1 + End Class + """); + + [Fact] + public Task LessThanGreaterThan() + => VerifyAsync(""" + [|Class A + Sub Test() + If 1 >< 2 Then + End If + End Sub + End Class|] + """, """ + Class A + Sub Test() + If 1 <> 2 Then + End If + End Sub + End Class + """); + + [Fact] + public Task GreaterThanEquals() + => VerifyAsync(""" + [|Class A + Sub Test() + If 1 => 2 Then + End If + End Sub + End Class|] + """, """ + Class A + Sub Test() + If 1 >= 2 Then + End If + End Sub + End Class + """); + + [Fact] + public Task LessThanEquals() + => VerifyAsync(""" + [|Class A + Sub Test() + If 1 =< 2 Then + End If + End Sub + End Class|] + """, """ + Class A + Sub Test() + If 1 <= 2 Then + End If + End Sub + End Class + """); + + [Fact] + public Task LessThanEquals_LineContinuation() + => VerifyAsync(""" + [|Class A + Sub Test() + If 1 _ + = _ + < _ + 2 Then + End If + End Sub + End Class|] + """, """ + Class A + Sub Test() + If 1 _ + <= _ + 2 Then + End If + End Sub + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544300")] - public async Task NormalizedOperator_StructuredTrivia() - { - var code = @"[|#If VBC_VER => 9.0|]"; - - var expected = @"#If VBC_VER >= 9.0"; - - await VerifyAsync(code, expected); - } + public Task NormalizedOperator_StructuredTrivia() + => VerifyAsync(@"[|#If VBC_VER => 9.0|]", @"#If VBC_VER >= 9.0"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544520")] - public async Task DoNotRemoveByVal() - { - var code = @"[|Module Program - Sub Main( - ByVal _ - args _ - As String) - End Sub -End Module|]"; - - var expected = @"Module Program - Sub Main( - ByVal _ - args _ - As String) - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task DoNotRemoveByVal() + => VerifyAsync(""" + [|Module Program + Sub Main( + ByVal _ + args _ + As String) + End Sub + End Module|] + """, """ + Module Program + Sub Main( + ByVal _ + args _ + As String) + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544561")] - public async Task NormalizeOperator_Text() - { - var code = @"[|Module Program - Sub Main() - Dim z = 1 - Dim y = 2 - Dim x = z < > y - End Sub -End Module|]"; - - var expected = @"Module Program - Sub Main() - Dim z = 1 - Dim y = 2 - Dim x = z <> y - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task NormalizeOperator_Text() + => VerifyAsync(""" + [|Module Program + Sub Main() + Dim z = 1 + Dim y = 2 + Dim x = z < > y + End Sub + End Module|] + """, """ + Module Program + Sub Main() + Dim z = 1 + Dim y = 2 + Dim x = z <> y + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544557")] - public async Task NormalizeOperator_OperatorStatement() - { - var code = @"[|Class S - Shared Operator >< (s1 As S, s2 As S) As S -End Class|]"; - - var expected = @"Class S - Shared Operator <>(s1 As S, s2 As S) As S -End Class"; - - await VerifyAsync(code, expected); - } + public Task NormalizeOperator_OperatorStatement() + => VerifyAsync(""" + [|Class S + Shared Operator >< (s1 As S, s2 As S) As S + End Class|] + """, """ + Class S + Shared Operator <>(s1 As S, s2 As S) As S + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544574")] - public async Task Reorder_OperatorTokenAndModifiers() - { - var code = @"[|Class S - Shared Operator Widening CType(aa As S) As Byte -End Class|]"; - - var expected = @"Class S - Shared Widening Operator CType(aa As S) As Byte -End Class"; - - await VerifyAsync(code, expected); - } + public Task Reorder_OperatorTokenAndModifiers() + => VerifyAsync(""" + [|Class S + Shared Operator Widening CType(aa As S) As Byte + End Class|] + """, """ + Class S + Shared Widening Operator CType(aa As S) As Byte + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546521")] - public async Task SkippedTokenOperator() - { - var code = @"[|Module M - Public Shared Narrowing Operator CTypeByVal s As Integer) As Test2 - Return New Test2() - End Operator -End Module|]"; - - var expected = @"Module M - Public Shared Narrowing Operator CTypeByVal s As Integer) As Test2 - Return New Test2() - End Operator -End Module"; - - await VerifyAsync(code, expected); - } + public Task SkippedTokenOperator() + => VerifyAsync(""" + [|Module M + Public Shared Narrowing Operator CTypeByVal s As Integer) As Test2 + Return New Test2() + End Operator + End Module|] + """, """ + Module M + Public Shared Narrowing Operator CTypeByVal s As Integer) As Test2 + Return New Test2() + End Operator + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547255")] - public async Task ReorderAsyncModifier() - { - var code = @"[|Module M - Public Async Function Goo() As Task(Of Integer) - Return 0 - End Function - - Async Public Function Goo2() As Task(Of Integer) - Return 0 - End Function - - Async Overridable Public Function Goo3() As Task(Of Integer) - Return 0 - End Function -End Module|]"; - - var expected = @"Module M - Public Async Function Goo() As Task(Of Integer) - Return 0 - End Function - - Public Async Function Goo2() As Task(Of Integer) - Return 0 - End Function - - Public Overridable Async Function Goo3() As Task(Of Integer) - Return 0 - End Function -End Module"; - - await VerifyAsync(code, expected); - } + public Task ReorderAsyncModifier() + => VerifyAsync(""" + [|Module M + Public Async Function Goo() As Task(Of Integer) + Return 0 + End Function + + Async Public Function Goo2() As Task(Of Integer) + Return 0 + End Function + + Async Overridable Public Function Goo3() As Task(Of Integer) + Return 0 + End Function + End Module|] + """, """ + Module M + Public Async Function Goo() As Task(Of Integer) + Return 0 + End Function + + Public Async Function Goo2() As Task(Of Integer) + Return 0 + End Function + + Public Overridable Async Function Goo3() As Task(Of Integer) + Return 0 + End Function + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547255")] - public async Task ReorderIteratorModifier() - { - var code = @"[|Module M - Public Iterator Function Goo() As IEnumerable(Of Integer) - Yield Return 0 - End Function - - Iterator Public Function Goo2() As IEnumerable(Of Integer) - Yield Return 0 - End Function - - Iterator Overridable Public Function Goo3() As IEnumerable(Of Integer) - Yield Return 0 - End Function -End Module|]"; - - var expected = @"Module M - Public Iterator Function Goo() As IEnumerable(Of Integer) - Yield Return 0 - End Function - - Public Iterator Function Goo2() As IEnumerable(Of Integer) - Yield Return 0 - End Function - - Public Overridable Iterator Function Goo3() As IEnumerable(Of Integer) - Yield Return 0 - End Function -End Module"; - - await VerifyAsync(code, expected); - } + public Task ReorderIteratorModifier() + => VerifyAsync(""" + [|Module M + Public Iterator Function Goo() As IEnumerable(Of Integer) + Yield Return 0 + End Function + + Iterator Public Function Goo2() As IEnumerable(Of Integer) + Yield Return 0 + End Function + + Iterator Overridable Public Function Goo3() As IEnumerable(Of Integer) + Yield Return 0 + End Function + End Module|] + """, """ + Module M + Public Iterator Function Goo() As IEnumerable(Of Integer) + Yield Return 0 + End Function + + Public Iterator Function Goo2() As IEnumerable(Of Integer) + Yield Return 0 + End Function + + Public Overridable Iterator Function Goo3() As IEnumerable(Of Integer) + Yield Return 0 + End Function + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611766")] - public async Task ReorderDuplicateModifiers() - { - var code = @"[|Module M - Public Public Function Goo() As Integer - Return 0 - End Function - - Iterator Public Public Iterator Public Function Goo2() As IEnumerable(Of Integer) - Yield Return 0 - End Function -End Module|]"; - - var expected = @"Module M - Public Function Goo() As Integer - Return 0 - End Function - - Public Iterator Function Goo2() As IEnumerable(Of Integer) - Yield Return 0 - End Function -End Module"; - - await VerifyAsync(code, expected); - } + public Task ReorderDuplicateModifiers() + => VerifyAsync(""" + [|Module M + Public Public Function Goo() As Integer + Return 0 + End Function + + Iterator Public Public Iterator Public Function Goo2() As IEnumerable(Of Integer) + Yield Return 0 + End Function + End Module|] + """, """ + Module M + Public Function Goo() As Integer + Return 0 + End Function + + Public Iterator Function Goo2() As IEnumerable(Of Integer) + Yield Return 0 + End Function + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530058")] - public async Task TestBadOperatorToken() - { - var code = @"[|Module Test -Class c1 -Shared Operator ||(ByVal x As c1, ByVal y As c1) As Integer -End Operator -End Class -End Module|]"; - - var expected = @"Module Test - Class c1 - Shared Operator ||(ByVal x As c1, ByVal y As c1) As Integer - End Operator - End Class -End Module"; - - await VerifyAsync(code, expected); - } + public Task TestBadOperatorToken() + => VerifyAsync(""" + [|Module Test + Class c1 + Shared Operator ||(ByVal x As c1, ByVal y As c1) As Integer + End Operator + End Class + End Module|] + """, """ + Module Test + Class c1 + Shared Operator ||(ByVal x As c1, ByVal y As c1) As Integer + End Operator + End Class + End Module + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/1534")] - public async Task TestColonEqualsToken() - { - var code = @"[|Module Program - Sub Main(args As String()) - Main(args : = args) - End Sub -End Module|]"; - - var expected = @"Module Program - Sub Main(args As String()) - Main(args:=args) - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task TestColonEqualsToken() + => VerifyAsync(""" + [|Module Program + Sub Main(args As String()) + Main(args : = args) + End Sub + End Module|] + """, """ + Module Program + Sub Main(args As String()) + Main(args:=args) + End Sub + End Module + """); private static async Task VerifyAsync(string codeWithMarker, string expectedResult) { diff --git a/src/Workspaces/CoreTest/CodeCleanup/ReduceTokenTests.cs b/src/Workspaces/CoreTest/CodeCleanup/ReduceTokenTests.cs index c72e5f9336e8e..2c54566c94134 100644 --- a/src/Workspaces/CoreTest/CodeCleanup/ReduceTokenTests.cs +++ b/src/Workspaces/CoreTest/CodeCleanup/ReduceTokenTests.cs @@ -27,1695 +27,1674 @@ public sealed class ReduceTokenTests #endif [Fact, WorkItem(5529, "DevDiv_Projects/Roslyn")] - public async Task ReduceSingleLiterals_LessThan8Digits() - { - var code = @"[| -Module Program - Sub Main(args As String()) - ' CATEGORY 1: Less than 8 significant digits - ' Dev11 and Roslyn behavior are identical: UNCHANGED - - ' 5 significant digits - Const f_5_1 As Single = .14995F ' Dev11 & Roslyn: Pretty listed to 0.14995F - Const f_5_2 As Single = 0.14995f ' Dev11 & Roslyn: Unchanged - Const f_5_3 As Single = 1.4995F ' Dev11 & Roslyn: Unchanged - Const f_5_4 As Single = 149.95f ' Dev11 & Roslyn: Unchanged - Const f_5_5 As Single = 1499.5F ' Dev11 & Roslyn: Unchanged - Const f_5_6 As Single = 14995.0f ' Dev11 & Roslyn: Unchanged - - ' 7 significant digits - Const f_7_1 As Single = .1499995F ' Dev11 & Roslyn: Pretty listed to 0.1499995F - Const f_7_2 As Single = 0.1499995f ' Dev11 & Roslyn: Unchanged - Const f_7_3 As Single = 1.499995F ' Dev11 & Roslyn: Unchanged - Const f_7_4 As Single = 1499.995f ' Dev11 & Roslyn: Unchanged - Const f_7_5 As Single = 149999.5F ' Dev11 & Roslyn: Unchanged - Const f_7_6 As Single = 1499995.0f ' Dev11 & Roslyn: Unchanged - - Console.WriteLine(f_5_1) - Console.WriteLine(f_5_2) - Console.WriteLine(f_5_3) - Console.WriteLine(f_5_4) - Console.WriteLine(f_5_5) - Console.WriteLine(f_5_6) - - Console.WriteLine(f_7_1) - Console.WriteLine(f_7_2) - Console.WriteLine(f_7_3) - Console.WriteLine(f_7_4) - Console.WriteLine(f_7_5) - Console.WriteLine(f_7_6) - End Sub -End Module -|]"; - - var expected = @" -Module Program - Sub Main(args As String()) - ' CATEGORY 1: Less than 8 significant digits - ' Dev11 and Roslyn behavior are identical: UNCHANGED - - ' 5 significant digits - Const f_5_1 As Single = 0.14995F ' Dev11 & Roslyn: Pretty listed to 0.14995F - Const f_5_2 As Single = 0.14995F ' Dev11 & Roslyn: Unchanged - Const f_5_3 As Single = 1.4995F ' Dev11 & Roslyn: Unchanged - Const f_5_4 As Single = 149.95F ' Dev11 & Roslyn: Unchanged - Const f_5_5 As Single = 1499.5F ' Dev11 & Roslyn: Unchanged - Const f_5_6 As Single = 14995.0F ' Dev11 & Roslyn: Unchanged - - ' 7 significant digits - Const f_7_1 As Single = 0.1499995F ' Dev11 & Roslyn: Pretty listed to 0.1499995F - Const f_7_2 As Single = 0.1499995F ' Dev11 & Roslyn: Unchanged - Const f_7_3 As Single = 1.499995F ' Dev11 & Roslyn: Unchanged - Const f_7_4 As Single = 1499.995F ' Dev11 & Roslyn: Unchanged - Const f_7_5 As Single = 149999.5F ' Dev11 & Roslyn: Unchanged - Const f_7_6 As Single = 1499995.0F ' Dev11 & Roslyn: Unchanged - - Console.WriteLine(f_5_1) - Console.WriteLine(f_5_2) - Console.WriteLine(f_5_3) - Console.WriteLine(f_5_4) - Console.WriteLine(f_5_5) - Console.WriteLine(f_5_6) - - Console.WriteLine(f_7_1) - Console.WriteLine(f_7_2) - Console.WriteLine(f_7_3) - Console.WriteLine(f_7_4) - Console.WriteLine(f_7_5) - Console.WriteLine(f_7_6) - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceSingleLiterals_LessThan8Digits() + => VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + ' CATEGORY 1: Less than 8 significant digits + ' Dev11 and Roslyn behavior are identical: UNCHANGED + + ' 5 significant digits + Const f_5_1 As Single = .14995F ' Dev11 & Roslyn: Pretty listed to 0.14995F + Const f_5_2 As Single = 0.14995f ' Dev11 & Roslyn: Unchanged + Const f_5_3 As Single = 1.4995F ' Dev11 & Roslyn: Unchanged + Const f_5_4 As Single = 149.95f ' Dev11 & Roslyn: Unchanged + Const f_5_5 As Single = 1499.5F ' Dev11 & Roslyn: Unchanged + Const f_5_6 As Single = 14995.0f ' Dev11 & Roslyn: Unchanged + + ' 7 significant digits + Const f_7_1 As Single = .1499995F ' Dev11 & Roslyn: Pretty listed to 0.1499995F + Const f_7_2 As Single = 0.1499995f ' Dev11 & Roslyn: Unchanged + Const f_7_3 As Single = 1.499995F ' Dev11 & Roslyn: Unchanged + Const f_7_4 As Single = 1499.995f ' Dev11 & Roslyn: Unchanged + Const f_7_5 As Single = 149999.5F ' Dev11 & Roslyn: Unchanged + Const f_7_6 As Single = 1499995.0f ' Dev11 & Roslyn: Unchanged + + Console.WriteLine(f_5_1) + Console.WriteLine(f_5_2) + Console.WriteLine(f_5_3) + Console.WriteLine(f_5_4) + Console.WriteLine(f_5_5) + Console.WriteLine(f_5_6) + + Console.WriteLine(f_7_1) + Console.WriteLine(f_7_2) + Console.WriteLine(f_7_3) + Console.WriteLine(f_7_4) + Console.WriteLine(f_7_5) + Console.WriteLine(f_7_6) + End Sub + End Module + |] + """, """ + + Module Program + Sub Main(args As String()) + ' CATEGORY 1: Less than 8 significant digits + ' Dev11 and Roslyn behavior are identical: UNCHANGED + + ' 5 significant digits + Const f_5_1 As Single = 0.14995F ' Dev11 & Roslyn: Pretty listed to 0.14995F + Const f_5_2 As Single = 0.14995F ' Dev11 & Roslyn: Unchanged + Const f_5_3 As Single = 1.4995F ' Dev11 & Roslyn: Unchanged + Const f_5_4 As Single = 149.95F ' Dev11 & Roslyn: Unchanged + Const f_5_5 As Single = 1499.5F ' Dev11 & Roslyn: Unchanged + Const f_5_6 As Single = 14995.0F ' Dev11 & Roslyn: Unchanged + + ' 7 significant digits + Const f_7_1 As Single = 0.1499995F ' Dev11 & Roslyn: Pretty listed to 0.1499995F + Const f_7_2 As Single = 0.1499995F ' Dev11 & Roslyn: Unchanged + Const f_7_3 As Single = 1.499995F ' Dev11 & Roslyn: Unchanged + Const f_7_4 As Single = 1499.995F ' Dev11 & Roslyn: Unchanged + Const f_7_5 As Single = 149999.5F ' Dev11 & Roslyn: Unchanged + Const f_7_6 As Single = 1499995.0F ' Dev11 & Roslyn: Unchanged + + Console.WriteLine(f_5_1) + Console.WriteLine(f_5_2) + Console.WriteLine(f_5_3) + Console.WriteLine(f_5_4) + Console.WriteLine(f_5_5) + Console.WriteLine(f_5_6) + + Console.WriteLine(f_7_1) + Console.WriteLine(f_7_2) + Console.WriteLine(f_7_3) + Console.WriteLine(f_7_4) + Console.WriteLine(f_7_5) + Console.WriteLine(f_7_6) + End Sub + End Module + + """); [Fact, WorkItem(5529, "DevDiv_Projects/Roslyn")] - public async Task ReduceSingleLiterals_LessThan8Digits_WithTypeCharacterSingle() - { - var code = @"[| -Module Program - Sub Main(args As String()) - ' CATEGORY 1: Less than 8 significant digits - ' Dev11 and Roslyn behavior are identical: UNCHANGED - - ' 5 significant digits - Const f_5_1 As Single = .14995! ' Dev11 & Roslyn: Pretty listed to 0.14995! - Const f_5_2 As Single = 0.14995! ' Dev11 & Roslyn: Unchanged - Const f_5_3 As Single = 1.4995! ' Dev11 & Roslyn: Unchanged - Const f_5_4 As Single = 149.95! ' Dev11 & Roslyn: Unchanged - Const f_5_5 As Single = 1499.5! ' Dev11 & Roslyn: Unchanged - Const f_5_6 As Single = 14995.0! ' Dev11 & Roslyn: Unchanged - - ' 7 significant digits - Const f_7_1 As Single = .1499995! ' Dev11 & Roslyn: Pretty listed to 0.1499995! - Const f_7_2 As Single = 0.1499995! ' Dev11 & Roslyn: Unchanged - Const f_7_3 As Single = 1.499995! ' Dev11 & Roslyn: Unchanged - Const f_7_4 As Single = 1499.995! ' Dev11 & Roslyn: Unchanged - Const f_7_5 As Single = 149999.5! ' Dev11 & Roslyn: Unchanged - Const f_7_6 As Single = 1499995.0! ' Dev11 & Roslyn: Unchanged - - Console.WriteLine(f_5_1) - Console.WriteLine(f_5_2) - Console.WriteLine(f_5_3) - Console.WriteLine(f_5_4) - Console.WriteLine(f_5_5) - Console.WriteLine(f_5_6) - - Console.WriteLine(f_7_1) - Console.WriteLine(f_7_2) - Console.WriteLine(f_7_3) - Console.WriteLine(f_7_4) - Console.WriteLine(f_7_5) - Console.WriteLine(f_7_6) - End Sub -End Module -|]"; - - var expected = @" -Module Program - Sub Main(args As String()) - ' CATEGORY 1: Less than 8 significant digits - ' Dev11 and Roslyn behavior are identical: UNCHANGED - - ' 5 significant digits - Const f_5_1 As Single = 0.14995! ' Dev11 & Roslyn: Pretty listed to 0.14995! - Const f_5_2 As Single = 0.14995! ' Dev11 & Roslyn: Unchanged - Const f_5_3 As Single = 1.4995! ' Dev11 & Roslyn: Unchanged - Const f_5_4 As Single = 149.95! ' Dev11 & Roslyn: Unchanged - Const f_5_5 As Single = 1499.5! ' Dev11 & Roslyn: Unchanged - Const f_5_6 As Single = 14995.0! ' Dev11 & Roslyn: Unchanged - - ' 7 significant digits - Const f_7_1 As Single = 0.1499995! ' Dev11 & Roslyn: Pretty listed to 0.1499995! - Const f_7_2 As Single = 0.1499995! ' Dev11 & Roslyn: Unchanged - Const f_7_3 As Single = 1.499995! ' Dev11 & Roslyn: Unchanged - Const f_7_4 As Single = 1499.995! ' Dev11 & Roslyn: Unchanged - Const f_7_5 As Single = 149999.5! ' Dev11 & Roslyn: Unchanged - Const f_7_6 As Single = 1499995.0! ' Dev11 & Roslyn: Unchanged - - Console.WriteLine(f_5_1) - Console.WriteLine(f_5_2) - Console.WriteLine(f_5_3) - Console.WriteLine(f_5_4) - Console.WriteLine(f_5_5) - Console.WriteLine(f_5_6) - - Console.WriteLine(f_7_1) - Console.WriteLine(f_7_2) - Console.WriteLine(f_7_3) - Console.WriteLine(f_7_4) - Console.WriteLine(f_7_5) - Console.WriteLine(f_7_6) - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceSingleLiterals_LessThan8Digits_WithTypeCharacterSingle() + => VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + ' CATEGORY 1: Less than 8 significant digits + ' Dev11 and Roslyn behavior are identical: UNCHANGED + + ' 5 significant digits + Const f_5_1 As Single = .14995! ' Dev11 & Roslyn: Pretty listed to 0.14995! + Const f_5_2 As Single = 0.14995! ' Dev11 & Roslyn: Unchanged + Const f_5_3 As Single = 1.4995! ' Dev11 & Roslyn: Unchanged + Const f_5_4 As Single = 149.95! ' Dev11 & Roslyn: Unchanged + Const f_5_5 As Single = 1499.5! ' Dev11 & Roslyn: Unchanged + Const f_5_6 As Single = 14995.0! ' Dev11 & Roslyn: Unchanged + + ' 7 significant digits + Const f_7_1 As Single = .1499995! ' Dev11 & Roslyn: Pretty listed to 0.1499995! + Const f_7_2 As Single = 0.1499995! ' Dev11 & Roslyn: Unchanged + Const f_7_3 As Single = 1.499995! ' Dev11 & Roslyn: Unchanged + Const f_7_4 As Single = 1499.995! ' Dev11 & Roslyn: Unchanged + Const f_7_5 As Single = 149999.5! ' Dev11 & Roslyn: Unchanged + Const f_7_6 As Single = 1499995.0! ' Dev11 & Roslyn: Unchanged + + Console.WriteLine(f_5_1) + Console.WriteLine(f_5_2) + Console.WriteLine(f_5_3) + Console.WriteLine(f_5_4) + Console.WriteLine(f_5_5) + Console.WriteLine(f_5_6) + + Console.WriteLine(f_7_1) + Console.WriteLine(f_7_2) + Console.WriteLine(f_7_3) + Console.WriteLine(f_7_4) + Console.WriteLine(f_7_5) + Console.WriteLine(f_7_6) + End Sub + End Module + |] + """, """ + + Module Program + Sub Main(args As String()) + ' CATEGORY 1: Less than 8 significant digits + ' Dev11 and Roslyn behavior are identical: UNCHANGED + + ' 5 significant digits + Const f_5_1 As Single = 0.14995! ' Dev11 & Roslyn: Pretty listed to 0.14995! + Const f_5_2 As Single = 0.14995! ' Dev11 & Roslyn: Unchanged + Const f_5_3 As Single = 1.4995! ' Dev11 & Roslyn: Unchanged + Const f_5_4 As Single = 149.95! ' Dev11 & Roslyn: Unchanged + Const f_5_5 As Single = 1499.5! ' Dev11 & Roslyn: Unchanged + Const f_5_6 As Single = 14995.0! ' Dev11 & Roslyn: Unchanged + + ' 7 significant digits + Const f_7_1 As Single = 0.1499995! ' Dev11 & Roslyn: Pretty listed to 0.1499995! + Const f_7_2 As Single = 0.1499995! ' Dev11 & Roslyn: Unchanged + Const f_7_3 As Single = 1.499995! ' Dev11 & Roslyn: Unchanged + Const f_7_4 As Single = 1499.995! ' Dev11 & Roslyn: Unchanged + Const f_7_5 As Single = 149999.5! ' Dev11 & Roslyn: Unchanged + Const f_7_6 As Single = 1499995.0! ' Dev11 & Roslyn: Unchanged + + Console.WriteLine(f_5_1) + Console.WriteLine(f_5_2) + Console.WriteLine(f_5_3) + Console.WriteLine(f_5_4) + Console.WriteLine(f_5_5) + Console.WriteLine(f_5_6) + + Console.WriteLine(f_7_1) + Console.WriteLine(f_7_2) + Console.WriteLine(f_7_3) + Console.WriteLine(f_7_4) + Console.WriteLine(f_7_5) + Console.WriteLine(f_7_6) + End Sub + End Module + + """); [Fact, WorkItem(5529, "DevDiv_Projects/Roslyn")] - public async Task ReduceSingleLiterals_8Digits() - { - var code = @"[| -Module Program - Sub Main(args As String()) - ' CATEGORY 2: 8 significant digits - ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits - - Const f_8_1 As Single = .14999795F ' Dev11 & Roslyn: 0.14999795F - Const f_8_2 As Single = .14999797f ' Dev11 & Roslyn: 0.149997965F - - Const f_8_3 As Single = 0.1499797F ' Dev11 & Roslyn: Unchanged - - Const f_8_4 As Single = 1.4999794f ' Dev11 & Roslyn: 1.49997938F - Const f_8_5 As Single = 1.4999797F ' Dev11 & Roslyn: 1.49997973F - - Const f_8_6 As Single = 1499.9794f ' Dev11 & Roslyn: 1499.97937F - - Const f_8_7 As Single = 1499979.7F ' Dev11 & Roslyn: 1499979.75F - - Const f_8_8 As Single = 14999797.0F ' Dev11 & Roslyn: unchanged - - Console.WriteLine(f_8_1) - Console.WriteLine(f_8_2) - Console.WriteLine(f_8_3) - Console.WriteLine(f_8_4) - Console.WriteLine(f_8_5) - Console.WriteLine(f_8_6) - Console.WriteLine(f_8_7) - Console.WriteLine(f_8_8) - End Sub -End Module -|]"; - - var expected = $@" -Module Program - Sub Main(args As String()) - ' CATEGORY 2: 8 significant digits - ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits - - Const f_8_1 As Single = 0.14999795F ' Dev11 & Roslyn: 0.14999795F - Const f_8_2 As Single = {(IsNetCoreApp ? "0.14999796F" : "0.149997965F")} ' Dev11 & Roslyn: 0.149997965F - - Const f_8_3 As Single = 0.1499797F ' Dev11 & Roslyn: Unchanged - - Const f_8_4 As Single = {(IsNetCoreApp ? "1.4999794F" : "1.49997938F")} ' Dev11 & Roslyn: 1.49997938F - Const f_8_5 As Single = {(IsNetCoreApp ? "1.4999797F" : "1.49997973F")} ' Dev11 & Roslyn: 1.49997973F - - Const f_8_6 As Single = {(IsNetCoreApp ? "1499.9794F" : "1499.97937F")} ' Dev11 & Roslyn: 1499.97937F - - Const f_8_7 As Single = {(IsNetCoreApp ? "1499979.8F" : "1499979.75F")} ' Dev11 & Roslyn: 1499979.75F - - Const f_8_8 As Single = 14999797.0F ' Dev11 & Roslyn: unchanged - - Console.WriteLine(f_8_1) - Console.WriteLine(f_8_2) - Console.WriteLine(f_8_3) - Console.WriteLine(f_8_4) - Console.WriteLine(f_8_5) - Console.WriteLine(f_8_6) - Console.WriteLine(f_8_7) - Console.WriteLine(f_8_8) - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceSingleLiterals_8Digits() + => VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + ' CATEGORY 2: 8 significant digits + ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits + + Const f_8_1 As Single = .14999795F ' Dev11 & Roslyn: 0.14999795F + Const f_8_2 As Single = .14999797f ' Dev11 & Roslyn: 0.149997965F + + Const f_8_3 As Single = 0.1499797F ' Dev11 & Roslyn: Unchanged + + Const f_8_4 As Single = 1.4999794f ' Dev11 & Roslyn: 1.49997938F + Const f_8_5 As Single = 1.4999797F ' Dev11 & Roslyn: 1.49997973F + + Const f_8_6 As Single = 1499.9794f ' Dev11 & Roslyn: 1499.97937F + + Const f_8_7 As Single = 1499979.7F ' Dev11 & Roslyn: 1499979.75F + + Const f_8_8 As Single = 14999797.0F ' Dev11 & Roslyn: unchanged + + Console.WriteLine(f_8_1) + Console.WriteLine(f_8_2) + Console.WriteLine(f_8_3) + Console.WriteLine(f_8_4) + Console.WriteLine(f_8_5) + Console.WriteLine(f_8_6) + Console.WriteLine(f_8_7) + Console.WriteLine(f_8_8) + End Sub + End Module + |] + """, $""" + + Module Program + Sub Main(args As String()) + ' CATEGORY 2: 8 significant digits + ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits + + Const f_8_1 As Single = 0.14999795F ' Dev11 & Roslyn: 0.14999795F + Const f_8_2 As Single = {(IsNetCoreApp ? "0.14999796F" : "0.149997965F")} ' Dev11 & Roslyn: 0.149997965F + + Const f_8_3 As Single = 0.1499797F ' Dev11 & Roslyn: Unchanged + + Const f_8_4 As Single = {(IsNetCoreApp ? "1.4999794F" : "1.49997938F")} ' Dev11 & Roslyn: 1.49997938F + Const f_8_5 As Single = {(IsNetCoreApp ? "1.4999797F" : "1.49997973F")} ' Dev11 & Roslyn: 1.49997973F + + Const f_8_6 As Single = {(IsNetCoreApp ? "1499.9794F" : "1499.97937F")} ' Dev11 & Roslyn: 1499.97937F + + Const f_8_7 As Single = {(IsNetCoreApp ? "1499979.8F" : "1499979.75F")} ' Dev11 & Roslyn: 1499979.75F + + Const f_8_8 As Single = 14999797.0F ' Dev11 & Roslyn: unchanged + + Console.WriteLine(f_8_1) + Console.WriteLine(f_8_2) + Console.WriteLine(f_8_3) + Console.WriteLine(f_8_4) + Console.WriteLine(f_8_5) + Console.WriteLine(f_8_6) + Console.WriteLine(f_8_7) + Console.WriteLine(f_8_8) + End Sub + End Module + + """); [Fact, WorkItem(5529, "DevDiv_Projects/Roslyn")] - public async Task ReduceSingleLiterals_8Digits_WithTypeCharacterSingle() - { - var code = @"[| -Module Program - Sub Main(args As String()) - ' CATEGORY 2: 8 significant digits - ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits - - Const f_8_1 As Single = .14999795! ' Dev11 & Roslyn: 0.14999795F - Const f_8_2 As Single = .14999797! ' Dev11 & Roslyn: 0.149997965F - - Const f_8_3 As Single = 0.1499797! ' Dev11 & Roslyn: Unchanged - - Const f_8_4 As Single = 1.4999794! ' Dev11 & Roslyn: 1.49997938F - Const f_8_5 As Single = 1.4999797! ' Dev11 & Roslyn: 1.49997973F - - Const f_8_6 As Single = 1499.9794! ' Dev11 & Roslyn: 1499.97937F - - Const f_8_7 As Single = 1499979.7! ' Dev11 & Roslyn: 1499979.75F - - Const f_8_8 As Single = 14999797.0! ' Dev11 & Roslyn: unchanged - - Console.WriteLine(f_8_1) - Console.WriteLine(f_8_2) - Console.WriteLine(f_8_3) - Console.WriteLine(f_8_4) - Console.WriteLine(f_8_5) - Console.WriteLine(f_8_6) - Console.WriteLine(f_8_7) - Console.WriteLine(f_8_8) - End Sub -End Module -|]"; - - var expected = $@" -Module Program - Sub Main(args As String()) - ' CATEGORY 2: 8 significant digits - ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits - - Const f_8_1 As Single = 0.14999795! ' Dev11 & Roslyn: 0.14999795F - Const f_8_2 As Single = {(IsNetCoreApp ? "0.14999796!" : "0.149997965!")} ' Dev11 & Roslyn: 0.149997965F - - Const f_8_3 As Single = 0.1499797! ' Dev11 & Roslyn: Unchanged - - Const f_8_4 As Single = {(IsNetCoreApp ? "1.4999794!" : "1.49997938!")} ' Dev11 & Roslyn: 1.49997938F - Const f_8_5 As Single = {(IsNetCoreApp ? "1.4999797!" : "1.49997973!")} ' Dev11 & Roslyn: 1.49997973F - - Const f_8_6 As Single = {(IsNetCoreApp ? "1499.9794!" : "1499.97937!")} ' Dev11 & Roslyn: 1499.97937F - - Const f_8_7 As Single = {(IsNetCoreApp ? "1499979.8!" : "1499979.75!")} ' Dev11 & Roslyn: 1499979.75F - - Const f_8_8 As Single = 14999797.0! ' Dev11 & Roslyn: unchanged - - Console.WriteLine(f_8_1) - Console.WriteLine(f_8_2) - Console.WriteLine(f_8_3) - Console.WriteLine(f_8_4) - Console.WriteLine(f_8_5) - Console.WriteLine(f_8_6) - Console.WriteLine(f_8_7) - Console.WriteLine(f_8_8) - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceSingleLiterals_8Digits_WithTypeCharacterSingle() + => VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + ' CATEGORY 2: 8 significant digits + ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits + + Const f_8_1 As Single = .14999795! ' Dev11 & Roslyn: 0.14999795F + Const f_8_2 As Single = .14999797! ' Dev11 & Roslyn: 0.149997965F + + Const f_8_3 As Single = 0.1499797! ' Dev11 & Roslyn: Unchanged + + Const f_8_4 As Single = 1.4999794! ' Dev11 & Roslyn: 1.49997938F + Const f_8_5 As Single = 1.4999797! ' Dev11 & Roslyn: 1.49997973F + + Const f_8_6 As Single = 1499.9794! ' Dev11 & Roslyn: 1499.97937F + + Const f_8_7 As Single = 1499979.7! ' Dev11 & Roslyn: 1499979.75F + + Const f_8_8 As Single = 14999797.0! ' Dev11 & Roslyn: unchanged + + Console.WriteLine(f_8_1) + Console.WriteLine(f_8_2) + Console.WriteLine(f_8_3) + Console.WriteLine(f_8_4) + Console.WriteLine(f_8_5) + Console.WriteLine(f_8_6) + Console.WriteLine(f_8_7) + Console.WriteLine(f_8_8) + End Sub + End Module + |] + """, $""" + + Module Program + Sub Main(args As String()) + ' CATEGORY 2: 8 significant digits + ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits + + Const f_8_1 As Single = 0.14999795! ' Dev11 & Roslyn: 0.14999795F + Const f_8_2 As Single = {(IsNetCoreApp ? "0.14999796!" : "0.149997965!")} ' Dev11 & Roslyn: 0.149997965F + + Const f_8_3 As Single = 0.1499797! ' Dev11 & Roslyn: Unchanged + + Const f_8_4 As Single = {(IsNetCoreApp ? "1.4999794!" : "1.49997938!")} ' Dev11 & Roslyn: 1.49997938F + Const f_8_5 As Single = {(IsNetCoreApp ? "1.4999797!" : "1.49997973!")} ' Dev11 & Roslyn: 1.49997973F + + Const f_8_6 As Single = {(IsNetCoreApp ? "1499.9794!" : "1499.97937!")} ' Dev11 & Roslyn: 1499.97937F + + Const f_8_7 As Single = {(IsNetCoreApp ? "1499979.8!" : "1499979.75!")} ' Dev11 & Roslyn: 1499979.75F + + Const f_8_8 As Single = 14999797.0! ' Dev11 & Roslyn: unchanged + + Console.WriteLine(f_8_1) + Console.WriteLine(f_8_2) + Console.WriteLine(f_8_3) + Console.WriteLine(f_8_4) + Console.WriteLine(f_8_5) + Console.WriteLine(f_8_6) + Console.WriteLine(f_8_7) + Console.WriteLine(f_8_8) + End Sub + End Module + + """); [Fact, WorkItem(5529, "DevDiv_Projects/Roslyn")] - public async Task ReduceSingleLiterals_GreaterThan8Digits() - { - var code = @"[| -Module Program - Sub Main(args As String()) - ' CATEGORY 3: > 8 significant digits - ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits - - ' (a) > 8 significant digits overall, but < 8 digits before decimal point. - Const f_9_1 As Single = .149997938F ' Dev11 & Roslyn: 0.149997935F - Const f_9_2 As Single = 0.149997931f ' Dev11 & Roslyn: 0.149997935F - Const f_9_3 As Single = 1.49997965F ' Dev11 & Roslyn: 1.49997962F - - Const f_10_1 As Single = 14999.79652f ' Dev11 & Roslyn: 14999.7969F - - ' (b) > 8 significant digits before decimal point. - Const f_10_2 As Single = 149997965.2F ' Dev11 & Roslyn: 149997968.0F - Const f_10_3 As Single = 1499979652.0f ' Dev11 & Roslyn: 1.49997965E+9F - - Const f_24_1 As Single = 111111149999124689999.499F ' Dev11 & Roslyn: 1.11111148E+20F - - ' (c) Overflow/Underflow cases for Single: Ensure no pretty listing/round off - ' Holds signed IEEE 32-bit (4-byte) single-precision floating-point numbers ranging in value from -3.4028235E+38 through -1.401298E-45 for negative values and - ' from 1.401298E-45 through 3.4028235E+38 for positive values. - - Const f_overflow_1 As Single = -3.4028235E+39F ' Dev11 & Roslyn: Unchanged - Const f_overflow_2 As Single = 3.4028235E+39F ' Dev11 & Roslyn: Unchanged - Const f_underflow_1 As Single = -1.401298E-47F ' Dev11: -0.0F, Roslyn: Unchanged - Const f_underflow_2 As Single = 1.401298E-47F ' Dev11: 0.0F, Roslyn: Unchanged - - Console.WriteLine(f_9_1) - Console.WriteLine(f_9_2) - Console.WriteLine(f_9_3) - Console.WriteLine(f_10_1) - Console.WriteLine(f_10_2) - Console.WriteLine(f_10_3) - Console.WriteLine(f_24_1) - - Console.WriteLine(f_overflow_1) - Console.WriteLine(f_overflow_2) - Console.WriteLine(f_underflow_1) - Console.WriteLine(f_underflow_2) - End Sub -End Module -|]"; - - var expected = $@" -Module Program - Sub Main(args As String()) - ' CATEGORY 3: > 8 significant digits - ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits - - ' (a) > 8 significant digits overall, but < 8 digits before decimal point. - Const f_9_1 As Single = {(IsNetCoreApp ? "0.14999793F" : "0.149997935F")} ' Dev11 & Roslyn: 0.149997935F - Const f_9_2 As Single = {(IsNetCoreApp ? "0.14999793F" : "0.149997935F")} ' Dev11 & Roslyn: 0.149997935F - Const f_9_3 As Single = {(IsNetCoreApp ? "1.4999796F" : "1.49997962F")} ' Dev11 & Roslyn: 1.49997962F - - Const f_10_1 As Single = {(IsNetCoreApp ? "14999.797F" : "14999.7969F")} ' Dev11 & Roslyn: 14999.7969F - - ' (b) > 8 significant digits before decimal point. - Const f_10_2 As Single = {(IsNetCoreApp ? "149997970.0F" : "149997968.0F")} ' Dev11 & Roslyn: 149997968.0F - Const f_10_3 As Single = {(IsNetCoreApp ? "1.4999796E+9F" : "1.49997965E+9F")} ' Dev11 & Roslyn: 1.49997965E+9F - - Const f_24_1 As Single = {(IsNetCoreApp ? "1.1111115E+20F" : "1.11111148E+20F")} ' Dev11 & Roslyn: 1.11111148E+20F - - ' (c) Overflow/Underflow cases for Single: Ensure no pretty listing/round off - ' Holds signed IEEE 32-bit (4-byte) single-precision floating-point numbers ranging in value from -3.4028235E+38 through -1.401298E-45 for negative values and - ' from 1.401298E-45 through 3.4028235E+38 for positive values. - - Const f_overflow_1 As Single = -3.4028235E+39F ' Dev11 & Roslyn: Unchanged - Const f_overflow_2 As Single = 3.4028235E+39F ' Dev11 & Roslyn: Unchanged - Const f_underflow_1 As Single = -1.401298E-47F ' Dev11: -0.0F, Roslyn: Unchanged - Const f_underflow_2 As Single = 1.401298E-47F ' Dev11: 0.0F, Roslyn: Unchanged - - Console.WriteLine(f_9_1) - Console.WriteLine(f_9_2) - Console.WriteLine(f_9_3) - Console.WriteLine(f_10_1) - Console.WriteLine(f_10_2) - Console.WriteLine(f_10_3) - Console.WriteLine(f_24_1) - - Console.WriteLine(f_overflow_1) - Console.WriteLine(f_overflow_2) - Console.WriteLine(f_underflow_1) - Console.WriteLine(f_underflow_2) - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceSingleLiterals_GreaterThan8Digits() + => VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + ' CATEGORY 3: > 8 significant digits + ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits + + ' (a) > 8 significant digits overall, but < 8 digits before decimal point. + Const f_9_1 As Single = .149997938F ' Dev11 & Roslyn: 0.149997935F + Const f_9_2 As Single = 0.149997931f ' Dev11 & Roslyn: 0.149997935F + Const f_9_3 As Single = 1.49997965F ' Dev11 & Roslyn: 1.49997962F + + Const f_10_1 As Single = 14999.79652f ' Dev11 & Roslyn: 14999.7969F + + ' (b) > 8 significant digits before decimal point. + Const f_10_2 As Single = 149997965.2F ' Dev11 & Roslyn: 149997968.0F + Const f_10_3 As Single = 1499979652.0f ' Dev11 & Roslyn: 1.49997965E+9F + + Const f_24_1 As Single = 111111149999124689999.499F ' Dev11 & Roslyn: 1.11111148E+20F + + ' (c) Overflow/Underflow cases for Single: Ensure no pretty listing/round off + ' Holds signed IEEE 32-bit (4-byte) single-precision floating-point numbers ranging in value from -3.4028235E+38 through -1.401298E-45 for negative values and + ' from 1.401298E-45 through 3.4028235E+38 for positive values. + + Const f_overflow_1 As Single = -3.4028235E+39F ' Dev11 & Roslyn: Unchanged + Const f_overflow_2 As Single = 3.4028235E+39F ' Dev11 & Roslyn: Unchanged + Const f_underflow_1 As Single = -1.401298E-47F ' Dev11: -0.0F, Roslyn: Unchanged + Const f_underflow_2 As Single = 1.401298E-47F ' Dev11: 0.0F, Roslyn: Unchanged + + Console.WriteLine(f_9_1) + Console.WriteLine(f_9_2) + Console.WriteLine(f_9_3) + Console.WriteLine(f_10_1) + Console.WriteLine(f_10_2) + Console.WriteLine(f_10_3) + Console.WriteLine(f_24_1) + + Console.WriteLine(f_overflow_1) + Console.WriteLine(f_overflow_2) + Console.WriteLine(f_underflow_1) + Console.WriteLine(f_underflow_2) + End Sub + End Module + |] + """, $""" + + Module Program + Sub Main(args As String()) + ' CATEGORY 3: > 8 significant digits + ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits + + ' (a) > 8 significant digits overall, but < 8 digits before decimal point. + Const f_9_1 As Single = {(IsNetCoreApp ? "0.14999793F" : "0.149997935F")} ' Dev11 & Roslyn: 0.149997935F + Const f_9_2 As Single = {(IsNetCoreApp ? "0.14999793F" : "0.149997935F")} ' Dev11 & Roslyn: 0.149997935F + Const f_9_3 As Single = {(IsNetCoreApp ? "1.4999796F" : "1.49997962F")} ' Dev11 & Roslyn: 1.49997962F + + Const f_10_1 As Single = {(IsNetCoreApp ? "14999.797F" : "14999.7969F")} ' Dev11 & Roslyn: 14999.7969F + + ' (b) > 8 significant digits before decimal point. + Const f_10_2 As Single = {(IsNetCoreApp ? "149997970.0F" : "149997968.0F")} ' Dev11 & Roslyn: 149997968.0F + Const f_10_3 As Single = {(IsNetCoreApp ? "1.4999796E+9F" : "1.49997965E+9F")} ' Dev11 & Roslyn: 1.49997965E+9F + + Const f_24_1 As Single = {(IsNetCoreApp ? "1.1111115E+20F" : "1.11111148E+20F")} ' Dev11 & Roslyn: 1.11111148E+20F + + ' (c) Overflow/Underflow cases for Single: Ensure no pretty listing/round off + ' Holds signed IEEE 32-bit (4-byte) single-precision floating-point numbers ranging in value from -3.4028235E+38 through -1.401298E-45 for negative values and + ' from 1.401298E-45 through 3.4028235E+38 for positive values. + + Const f_overflow_1 As Single = -3.4028235E+39F ' Dev11 & Roslyn: Unchanged + Const f_overflow_2 As Single = 3.4028235E+39F ' Dev11 & Roslyn: Unchanged + Const f_underflow_1 As Single = -1.401298E-47F ' Dev11: -0.0F, Roslyn: Unchanged + Const f_underflow_2 As Single = 1.401298E-47F ' Dev11: 0.0F, Roslyn: Unchanged + + Console.WriteLine(f_9_1) + Console.WriteLine(f_9_2) + Console.WriteLine(f_9_3) + Console.WriteLine(f_10_1) + Console.WriteLine(f_10_2) + Console.WriteLine(f_10_3) + Console.WriteLine(f_24_1) + + Console.WriteLine(f_overflow_1) + Console.WriteLine(f_overflow_2) + Console.WriteLine(f_underflow_1) + Console.WriteLine(f_underflow_2) + End Sub + End Module + + """); [Fact, WorkItem(5529, "DevDiv_Projects/Roslyn")] - public async Task ReduceSingleLiterals_GreaterThan8Digits_WithTypeCharacterSingle() - { - var code = @"[| -Module Program - Sub Main(args As String()) - ' CATEGORY 3: > 8 significant digits - ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits - - ' (a) > 8 significant digits overall, but < 8 digits before decimal point. - Const f_9_1 As Single = .149997938! ' Dev11 & Roslyn: 0.149997935F - Const f_9_2 As Single = 0.149997931! ' Dev11 & Roslyn: 0.149997935F - Const f_9_3 As Single = 1.49997965! ' Dev11 & Roslyn: 1.49997962F - - Const f_10_1 As Single = 14999.79652! ' Dev11 & Roslyn: 14999.7969F - - ' (b) > 8 significant digits before decimal point. - Const f_10_2 As Single = 149997965.2! ' Dev11 & Roslyn: 149997968.0F - Const f_10_3 As Single = 1499979652.0! ' Dev11 & Roslyn: 1.49997965E+9F - - Const f_24_1 As Single = 111111149999124689999.499! ' Dev11 & Roslyn: 1.11111148E+20F - - ' (c) Overflow/Underflow cases for Single: Ensure no pretty listing/round off - ' Holds signed IEEE 32-bit (4-byte) single-precision floating-point numbers ranging in value from -3.4028235E+38 through -1.401298E-45 for negative values and - ' from 1.401298E-45 through 3.4028235E+38 for positive values. - - Const f_overflow_1 As Single = -3.4028235E+39! ' Dev11 & Roslyn: Unchanged - Const f_overflow_2 As Single = 3.4028235E+39! ' Dev11 & Roslyn: Unchanged - Const f_underflow_1 As Single = -1.401298E-47! ' Dev11: -0.0F, Roslyn: Unchanged - Const f_underflow_2 As Single = 1.401298E-47! ' Dev11: 0.0F, Roslyn: Unchanged - - Console.WriteLine(f_9_1) - Console.WriteLine(f_9_2) - Console.WriteLine(f_9_3) - Console.WriteLine(f_10_1) - Console.WriteLine(f_10_2) - Console.WriteLine(f_10_3) - Console.WriteLine(f_24_1) - - Console.WriteLine(f_overflow_1) - Console.WriteLine(f_overflow_2) - Console.WriteLine(f_underflow_1) - Console.WriteLine(f_underflow_2) - End Sub -End Module -|]"; - - var expected = $@" -Module Program - Sub Main(args As String()) - ' CATEGORY 3: > 8 significant digits - ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits - - ' (a) > 8 significant digits overall, but < 8 digits before decimal point. - Const f_9_1 As Single = {(IsNetCoreApp ? "0.14999793!" : "0.149997935!")} ' Dev11 & Roslyn: 0.149997935F - Const f_9_2 As Single = {(IsNetCoreApp ? "0.14999793!" : "0.149997935!")} ' Dev11 & Roslyn: 0.149997935F - Const f_9_3 As Single = {(IsNetCoreApp ? "1.4999796!" : "1.49997962!")} ' Dev11 & Roslyn: 1.49997962F - - Const f_10_1 As Single = {(IsNetCoreApp ? "14999.797!" : "14999.7969!")} ' Dev11 & Roslyn: 14999.7969F - - ' (b) > 8 significant digits before decimal point. - Const f_10_2 As Single = {(IsNetCoreApp ? "149997970.0!" : "149997968.0!")} ' Dev11 & Roslyn: 149997968.0F - Const f_10_3 As Single = {(IsNetCoreApp ? "1.4999796E+9!" : "1.49997965E+9!")} ' Dev11 & Roslyn: 1.49997965E+9F - - Const f_24_1 As Single = {(IsNetCoreApp ? "1.1111115E+20!" : "1.11111148E+20!")} ' Dev11 & Roslyn: 1.11111148E+20F - - ' (c) Overflow/Underflow cases for Single: Ensure no pretty listing/round off - ' Holds signed IEEE 32-bit (4-byte) single-precision floating-point numbers ranging in value from -3.4028235E+38 through -1.401298E-45 for negative values and - ' from 1.401298E-45 through 3.4028235E+38 for positive values. - - Const f_overflow_1 As Single = -3.4028235E+39! ' Dev11 & Roslyn: Unchanged - Const f_overflow_2 As Single = 3.4028235E+39! ' Dev11 & Roslyn: Unchanged - Const f_underflow_1 As Single = -1.401298E-47! ' Dev11: -0.0F, Roslyn: Unchanged - Const f_underflow_2 As Single = 1.401298E-47! ' Dev11: 0.0F, Roslyn: Unchanged - - Console.WriteLine(f_9_1) - Console.WriteLine(f_9_2) - Console.WriteLine(f_9_3) - Console.WriteLine(f_10_1) - Console.WriteLine(f_10_2) - Console.WriteLine(f_10_3) - Console.WriteLine(f_24_1) - - Console.WriteLine(f_overflow_1) - Console.WriteLine(f_overflow_2) - Console.WriteLine(f_underflow_1) - Console.WriteLine(f_underflow_2) - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceSingleLiterals_GreaterThan8Digits_WithTypeCharacterSingle() + => VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + ' CATEGORY 3: > 8 significant digits + ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits + + ' (a) > 8 significant digits overall, but < 8 digits before decimal point. + Const f_9_1 As Single = .149997938! ' Dev11 & Roslyn: 0.149997935F + Const f_9_2 As Single = 0.149997931! ' Dev11 & Roslyn: 0.149997935F + Const f_9_3 As Single = 1.49997965! ' Dev11 & Roslyn: 1.49997962F + + Const f_10_1 As Single = 14999.79652! ' Dev11 & Roslyn: 14999.7969F + + ' (b) > 8 significant digits before decimal point. + Const f_10_2 As Single = 149997965.2! ' Dev11 & Roslyn: 149997968.0F + Const f_10_3 As Single = 1499979652.0! ' Dev11 & Roslyn: 1.49997965E+9F + + Const f_24_1 As Single = 111111149999124689999.499! ' Dev11 & Roslyn: 1.11111148E+20F + + ' (c) Overflow/Underflow cases for Single: Ensure no pretty listing/round off + ' Holds signed IEEE 32-bit (4-byte) single-precision floating-point numbers ranging in value from -3.4028235E+38 through -1.401298E-45 for negative values and + ' from 1.401298E-45 through 3.4028235E+38 for positive values. + + Const f_overflow_1 As Single = -3.4028235E+39! ' Dev11 & Roslyn: Unchanged + Const f_overflow_2 As Single = 3.4028235E+39! ' Dev11 & Roslyn: Unchanged + Const f_underflow_1 As Single = -1.401298E-47! ' Dev11: -0.0F, Roslyn: Unchanged + Const f_underflow_2 As Single = 1.401298E-47! ' Dev11: 0.0F, Roslyn: Unchanged + + Console.WriteLine(f_9_1) + Console.WriteLine(f_9_2) + Console.WriteLine(f_9_3) + Console.WriteLine(f_10_1) + Console.WriteLine(f_10_2) + Console.WriteLine(f_10_3) + Console.WriteLine(f_24_1) + + Console.WriteLine(f_overflow_1) + Console.WriteLine(f_overflow_2) + Console.WriteLine(f_underflow_1) + Console.WriteLine(f_underflow_2) + End Sub + End Module + |] + """, $""" + + Module Program + Sub Main(args As String()) + ' CATEGORY 3: > 8 significant digits + ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits + + ' (a) > 8 significant digits overall, but < 8 digits before decimal point. + Const f_9_1 As Single = {(IsNetCoreApp ? "0.14999793!" : "0.149997935!")} ' Dev11 & Roslyn: 0.149997935F + Const f_9_2 As Single = {(IsNetCoreApp ? "0.14999793!" : "0.149997935!")} ' Dev11 & Roslyn: 0.149997935F + Const f_9_3 As Single = {(IsNetCoreApp ? "1.4999796!" : "1.49997962!")} ' Dev11 & Roslyn: 1.49997962F + + Const f_10_1 As Single = {(IsNetCoreApp ? "14999.797!" : "14999.7969!")} ' Dev11 & Roslyn: 14999.7969F + + ' (b) > 8 significant digits before decimal point. + Const f_10_2 As Single = {(IsNetCoreApp ? "149997970.0!" : "149997968.0!")} ' Dev11 & Roslyn: 149997968.0F + Const f_10_3 As Single = {(IsNetCoreApp ? "1.4999796E+9!" : "1.49997965E+9!")} ' Dev11 & Roslyn: 1.49997965E+9F + + Const f_24_1 As Single = {(IsNetCoreApp ? "1.1111115E+20!" : "1.11111148E+20!")} ' Dev11 & Roslyn: 1.11111148E+20F + + ' (c) Overflow/Underflow cases for Single: Ensure no pretty listing/round off + ' Holds signed IEEE 32-bit (4-byte) single-precision floating-point numbers ranging in value from -3.4028235E+38 through -1.401298E-45 for negative values and + ' from 1.401298E-45 through 3.4028235E+38 for positive values. + + Const f_overflow_1 As Single = -3.4028235E+39! ' Dev11 & Roslyn: Unchanged + Const f_overflow_2 As Single = 3.4028235E+39! ' Dev11 & Roslyn: Unchanged + Const f_underflow_1 As Single = -1.401298E-47! ' Dev11: -0.0F, Roslyn: Unchanged + Const f_underflow_2 As Single = 1.401298E-47! ' Dev11: 0.0F, Roslyn: Unchanged + + Console.WriteLine(f_9_1) + Console.WriteLine(f_9_2) + Console.WriteLine(f_9_3) + Console.WriteLine(f_10_1) + Console.WriteLine(f_10_2) + Console.WriteLine(f_10_3) + Console.WriteLine(f_24_1) + + Console.WriteLine(f_overflow_1) + Console.WriteLine(f_overflow_2) + Console.WriteLine(f_underflow_1) + Console.WriteLine(f_underflow_2) + End Sub + End Module + + """); [Fact, WorkItem(5529, "DevDiv_Projects/Roslyn")] - public async Task ReduceDoubleLiterals_LessThan16Digits() - { - var code = @"[| -Module Program - Sub Main(args As String()) - ' CATEGORY 1: Less than 16 significant digits precision, - ' Dev11 and Roslyn behavior are identical: UNCHANGED - - ' 13 significant digits - Const f_13_1 As Double = .1499599999999 ' Dev11 & Roslyn: Pretty listed to 0.1499599999999 - Const f_13_2 As Double = 0.149959999999 ' Dev11 & Roslyn: Unchanged - Const f_13_3 As Double = 1.499599999999 ' Dev11 & Roslyn: Unchanged - Const f_13_4 As Double = 1499599.999999 ' Dev11 & Roslyn: Unchanged - Const f_13_5 As Double = 149959999999.9 ' Dev11 & Roslyn: Unchanged - Const f_13_6 As Double = 1499599999999.0 ' Dev11 & Roslyn: Unchanged - - ' 15 significant digits - Const f_15_1 As Double = .149999999999995 ' Dev11 & Roslyn: Pretty listed to 0.149999999999995 - Const f_15_2 As Double = 0.14999999999995 ' Dev11 & Roslyn: Unchanged - Const f_15_3 As Double = 1.49999999999995 ' Dev11 & Roslyn: Unchanged - Const f_15_4 As Double = 14999999.9999995 ' Dev11 & Roslyn: Unchanged - Const f_15_5 As Double = 14999999999999.5 ' Dev11 & Roslyn: Unchanged - Const f_15_6 As Double = 149999999999995.0 ' Dev11 & Roslyn: Unchanged - - Console.WriteLine(f_13_1) - Console.WriteLine(f_13_2) - Console.WriteLine(f_13_3) - Console.WriteLine(f_13_4) - Console.WriteLine(f_13_5) - Console.WriteLine(f_13_6) - - Console.WriteLine(f_15_1) - Console.WriteLine(f_15_2) - Console.WriteLine(f_15_3) - Console.WriteLine(f_15_4) - Console.WriteLine(f_15_5) - Console.WriteLine(f_15_6) - End Sub -End Module -|]"; - - var expected = @" -Module Program - Sub Main(args As String()) - ' CATEGORY 1: Less than 16 significant digits precision, - ' Dev11 and Roslyn behavior are identical: UNCHANGED - - ' 13 significant digits - Const f_13_1 As Double = 0.1499599999999 ' Dev11 & Roslyn: Pretty listed to 0.1499599999999 - Const f_13_2 As Double = 0.149959999999 ' Dev11 & Roslyn: Unchanged - Const f_13_3 As Double = 1.499599999999 ' Dev11 & Roslyn: Unchanged - Const f_13_4 As Double = 1499599.999999 ' Dev11 & Roslyn: Unchanged - Const f_13_5 As Double = 149959999999.9 ' Dev11 & Roslyn: Unchanged - Const f_13_6 As Double = 1499599999999.0 ' Dev11 & Roslyn: Unchanged - - ' 15 significant digits - Const f_15_1 As Double = 0.149999999999995 ' Dev11 & Roslyn: Pretty listed to 0.149999999999995 - Const f_15_2 As Double = 0.14999999999995 ' Dev11 & Roslyn: Unchanged - Const f_15_3 As Double = 1.49999999999995 ' Dev11 & Roslyn: Unchanged - Const f_15_4 As Double = 14999999.9999995 ' Dev11 & Roslyn: Unchanged - Const f_15_5 As Double = 14999999999999.5 ' Dev11 & Roslyn: Unchanged - Const f_15_6 As Double = 149999999999995.0 ' Dev11 & Roslyn: Unchanged - - Console.WriteLine(f_13_1) - Console.WriteLine(f_13_2) - Console.WriteLine(f_13_3) - Console.WriteLine(f_13_4) - Console.WriteLine(f_13_5) - Console.WriteLine(f_13_6) - - Console.WriteLine(f_15_1) - Console.WriteLine(f_15_2) - Console.WriteLine(f_15_3) - Console.WriteLine(f_15_4) - Console.WriteLine(f_15_5) - Console.WriteLine(f_15_6) - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceDoubleLiterals_LessThan16Digits() + => VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + ' CATEGORY 1: Less than 16 significant digits precision, + ' Dev11 and Roslyn behavior are identical: UNCHANGED + + ' 13 significant digits + Const f_13_1 As Double = .1499599999999 ' Dev11 & Roslyn: Pretty listed to 0.1499599999999 + Const f_13_2 As Double = 0.149959999999 ' Dev11 & Roslyn: Unchanged + Const f_13_3 As Double = 1.499599999999 ' Dev11 & Roslyn: Unchanged + Const f_13_4 As Double = 1499599.999999 ' Dev11 & Roslyn: Unchanged + Const f_13_5 As Double = 149959999999.9 ' Dev11 & Roslyn: Unchanged + Const f_13_6 As Double = 1499599999999.0 ' Dev11 & Roslyn: Unchanged + + ' 15 significant digits + Const f_15_1 As Double = .149999999999995 ' Dev11 & Roslyn: Pretty listed to 0.149999999999995 + Const f_15_2 As Double = 0.14999999999995 ' Dev11 & Roslyn: Unchanged + Const f_15_3 As Double = 1.49999999999995 ' Dev11 & Roslyn: Unchanged + Const f_15_4 As Double = 14999999.9999995 ' Dev11 & Roslyn: Unchanged + Const f_15_5 As Double = 14999999999999.5 ' Dev11 & Roslyn: Unchanged + Const f_15_6 As Double = 149999999999995.0 ' Dev11 & Roslyn: Unchanged + + Console.WriteLine(f_13_1) + Console.WriteLine(f_13_2) + Console.WriteLine(f_13_3) + Console.WriteLine(f_13_4) + Console.WriteLine(f_13_5) + Console.WriteLine(f_13_6) + + Console.WriteLine(f_15_1) + Console.WriteLine(f_15_2) + Console.WriteLine(f_15_3) + Console.WriteLine(f_15_4) + Console.WriteLine(f_15_5) + Console.WriteLine(f_15_6) + End Sub + End Module + |] + """, """ + + Module Program + Sub Main(args As String()) + ' CATEGORY 1: Less than 16 significant digits precision, + ' Dev11 and Roslyn behavior are identical: UNCHANGED + + ' 13 significant digits + Const f_13_1 As Double = 0.1499599999999 ' Dev11 & Roslyn: Pretty listed to 0.1499599999999 + Const f_13_2 As Double = 0.149959999999 ' Dev11 & Roslyn: Unchanged + Const f_13_3 As Double = 1.499599999999 ' Dev11 & Roslyn: Unchanged + Const f_13_4 As Double = 1499599.999999 ' Dev11 & Roslyn: Unchanged + Const f_13_5 As Double = 149959999999.9 ' Dev11 & Roslyn: Unchanged + Const f_13_6 As Double = 1499599999999.0 ' Dev11 & Roslyn: Unchanged + + ' 15 significant digits + Const f_15_1 As Double = 0.149999999999995 ' Dev11 & Roslyn: Pretty listed to 0.149999999999995 + Const f_15_2 As Double = 0.14999999999995 ' Dev11 & Roslyn: Unchanged + Const f_15_3 As Double = 1.49999999999995 ' Dev11 & Roslyn: Unchanged + Const f_15_4 As Double = 14999999.9999995 ' Dev11 & Roslyn: Unchanged + Const f_15_5 As Double = 14999999999999.5 ' Dev11 & Roslyn: Unchanged + Const f_15_6 As Double = 149999999999995.0 ' Dev11 & Roslyn: Unchanged + + Console.WriteLine(f_13_1) + Console.WriteLine(f_13_2) + Console.WriteLine(f_13_3) + Console.WriteLine(f_13_4) + Console.WriteLine(f_13_5) + Console.WriteLine(f_13_6) + + Console.WriteLine(f_15_1) + Console.WriteLine(f_15_2) + Console.WriteLine(f_15_3) + Console.WriteLine(f_15_4) + Console.WriteLine(f_15_5) + Console.WriteLine(f_15_6) + End Sub + End Module + + """); [Fact, WorkItem(5529, "DevDiv_Projects/Roslyn")] - public async Task ReduceDoubleLiterals_LessThan16Digits_WithTypeCharacter() - { - var code = @"[| -Module Program - Sub Main(args As String()) - ' CATEGORY 1: Less than 16 significant digits precision, - ' Dev11 and Roslyn behavior are identical: UNCHANGED - - ' 13 significant digits - Const f_13_1 As Double = .1499599999999R ' Dev11 & Roslyn: Pretty listed to 0.1499599999999 - Const f_13_2 As Double = 0.149959999999r ' Dev11 & Roslyn: Unchanged - Const f_13_3 As Double = 1.499599999999# ' Dev11 & Roslyn: Unchanged - Const f_13_4 As Double = 1499599.999999# ' Dev11 & Roslyn: Unchanged - Const f_13_5 As Double = 149959999999.9r ' Dev11 & Roslyn: Unchanged - Const f_13_6 As Double = 1499599999999.0R ' Dev11 & Roslyn: Unchanged - - ' 15 significant digits - Const f_15_1 As Double = .149999999999995R ' Dev11 & Roslyn: Pretty listed to 0.149999999999995 - Const f_15_2 As Double = 0.14999999999995r ' Dev11 & Roslyn: Unchanged - Const f_15_3 As Double = 1.49999999999995# ' Dev11 & Roslyn: Unchanged - Const f_15_4 As Double = 14999999.9999995# ' Dev11 & Roslyn: Unchanged - Const f_15_5 As Double = 14999999999999.5r ' Dev11 & Roslyn: Unchanged - Const f_15_6 As Double = 149999999999995.0R ' Dev11 & Roslyn: Unchanged - - Console.WriteLine(f_13_1) - Console.WriteLine(f_13_2) - Console.WriteLine(f_13_3) - Console.WriteLine(f_13_4) - Console.WriteLine(f_13_5) - Console.WriteLine(f_13_6) - - Console.WriteLine(f_15_1) - Console.WriteLine(f_15_2) - Console.WriteLine(f_15_3) - Console.WriteLine(f_15_4) - Console.WriteLine(f_15_5) - Console.WriteLine(f_15_6) - End Sub -End Module -|]"; - - var expected = @" -Module Program - Sub Main(args As String()) - ' CATEGORY 1: Less than 16 significant digits precision, - ' Dev11 and Roslyn behavior are identical: UNCHANGED - - ' 13 significant digits - Const f_13_1 As Double = 0.1499599999999R ' Dev11 & Roslyn: Pretty listed to 0.1499599999999 - Const f_13_2 As Double = 0.149959999999R ' Dev11 & Roslyn: Unchanged - Const f_13_3 As Double = 1.499599999999# ' Dev11 & Roslyn: Unchanged - Const f_13_4 As Double = 1499599.999999# ' Dev11 & Roslyn: Unchanged - Const f_13_5 As Double = 149959999999.9R ' Dev11 & Roslyn: Unchanged - Const f_13_6 As Double = 1499599999999.0R ' Dev11 & Roslyn: Unchanged - - ' 15 significant digits - Const f_15_1 As Double = 0.149999999999995R ' Dev11 & Roslyn: Pretty listed to 0.149999999999995 - Const f_15_2 As Double = 0.14999999999995R ' Dev11 & Roslyn: Unchanged - Const f_15_3 As Double = 1.49999999999995# ' Dev11 & Roslyn: Unchanged - Const f_15_4 As Double = 14999999.9999995# ' Dev11 & Roslyn: Unchanged - Const f_15_5 As Double = 14999999999999.5R ' Dev11 & Roslyn: Unchanged - Const f_15_6 As Double = 149999999999995.0R ' Dev11 & Roslyn: Unchanged - - Console.WriteLine(f_13_1) - Console.WriteLine(f_13_2) - Console.WriteLine(f_13_3) - Console.WriteLine(f_13_4) - Console.WriteLine(f_13_5) - Console.WriteLine(f_13_6) - - Console.WriteLine(f_15_1) - Console.WriteLine(f_15_2) - Console.WriteLine(f_15_3) - Console.WriteLine(f_15_4) - Console.WriteLine(f_15_5) - Console.WriteLine(f_15_6) - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceDoubleLiterals_LessThan16Digits_WithTypeCharacter() + => VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + ' CATEGORY 1: Less than 16 significant digits precision, + ' Dev11 and Roslyn behavior are identical: UNCHANGED + + ' 13 significant digits + Const f_13_1 As Double = .1499599999999R ' Dev11 & Roslyn: Pretty listed to 0.1499599999999 + Const f_13_2 As Double = 0.149959999999r ' Dev11 & Roslyn: Unchanged + Const f_13_3 As Double = 1.499599999999# ' Dev11 & Roslyn: Unchanged + Const f_13_4 As Double = 1499599.999999# ' Dev11 & Roslyn: Unchanged + Const f_13_5 As Double = 149959999999.9r ' Dev11 & Roslyn: Unchanged + Const f_13_6 As Double = 1499599999999.0R ' Dev11 & Roslyn: Unchanged + + ' 15 significant digits + Const f_15_1 As Double = .149999999999995R ' Dev11 & Roslyn: Pretty listed to 0.149999999999995 + Const f_15_2 As Double = 0.14999999999995r ' Dev11 & Roslyn: Unchanged + Const f_15_3 As Double = 1.49999999999995# ' Dev11 & Roslyn: Unchanged + Const f_15_4 As Double = 14999999.9999995# ' Dev11 & Roslyn: Unchanged + Const f_15_5 As Double = 14999999999999.5r ' Dev11 & Roslyn: Unchanged + Const f_15_6 As Double = 149999999999995.0R ' Dev11 & Roslyn: Unchanged + + Console.WriteLine(f_13_1) + Console.WriteLine(f_13_2) + Console.WriteLine(f_13_3) + Console.WriteLine(f_13_4) + Console.WriteLine(f_13_5) + Console.WriteLine(f_13_6) + + Console.WriteLine(f_15_1) + Console.WriteLine(f_15_2) + Console.WriteLine(f_15_3) + Console.WriteLine(f_15_4) + Console.WriteLine(f_15_5) + Console.WriteLine(f_15_6) + End Sub + End Module + |] + """, """ + + Module Program + Sub Main(args As String()) + ' CATEGORY 1: Less than 16 significant digits precision, + ' Dev11 and Roslyn behavior are identical: UNCHANGED + + ' 13 significant digits + Const f_13_1 As Double = 0.1499599999999R ' Dev11 & Roslyn: Pretty listed to 0.1499599999999 + Const f_13_2 As Double = 0.149959999999R ' Dev11 & Roslyn: Unchanged + Const f_13_3 As Double = 1.499599999999# ' Dev11 & Roslyn: Unchanged + Const f_13_4 As Double = 1499599.999999# ' Dev11 & Roslyn: Unchanged + Const f_13_5 As Double = 149959999999.9R ' Dev11 & Roslyn: Unchanged + Const f_13_6 As Double = 1499599999999.0R ' Dev11 & Roslyn: Unchanged + + ' 15 significant digits + Const f_15_1 As Double = 0.149999999999995R ' Dev11 & Roslyn: Pretty listed to 0.149999999999995 + Const f_15_2 As Double = 0.14999999999995R ' Dev11 & Roslyn: Unchanged + Const f_15_3 As Double = 1.49999999999995# ' Dev11 & Roslyn: Unchanged + Const f_15_4 As Double = 14999999.9999995# ' Dev11 & Roslyn: Unchanged + Const f_15_5 As Double = 14999999999999.5R ' Dev11 & Roslyn: Unchanged + Const f_15_6 As Double = 149999999999995.0R ' Dev11 & Roslyn: Unchanged + + Console.WriteLine(f_13_1) + Console.WriteLine(f_13_2) + Console.WriteLine(f_13_3) + Console.WriteLine(f_13_4) + Console.WriteLine(f_13_5) + Console.WriteLine(f_13_6) + + Console.WriteLine(f_15_1) + Console.WriteLine(f_15_2) + Console.WriteLine(f_15_3) + Console.WriteLine(f_15_4) + Console.WriteLine(f_15_5) + Console.WriteLine(f_15_6) + End Sub + End Module + + """); [Fact, WorkItem(5529, "DevDiv_Projects/Roslyn")] - public async Task ReduceDoubleLiterals_16Digits() - { - var code = @"[| -Module Program - Sub Main(args As String()) - ' CATEGORY 2: 16 significant digits - ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits - - Const f_16_1 As Double = .1499999999799993 ' Dev11 & Roslyn: 0.1499999999799993 - Const f_16_2 As Double = .1499999999799997 ' Dev11 & Roslyn: 0.14999999997999969 - - Const f_16_3 As Double = 0.149999999799995 ' Dev11 & Roslyn: Unchanged - - Const f_16_4 As Double = 1.499999999799994 ' Dev11 & Roslyn: Unchanged - Const f_16_5 As Double = 1.499999999799995 ' Dev11 & Roslyn: 1.4999999997999951 - - Const f_16_6 As Double = 14999999.99799994 ' Dev11 & Roslyn: Unchanged - Const f_16_7 As Double = 14999999.99799995 ' Dev11 & Roslyn: 14999999.997999949 - - Const f_16_8 As Double = 149999999997999.2 ' Dev11 & Roslyn: 149999999997999.19 - Const f_16_9 As Double = 149999999997999.8 ' Dev11 & Roslyn: 149999999997999.81 - - Const f_16_10 As Double = 1499999999979995.0 ' Dev11 & Roslyn: Unchanged - - Console.WriteLine(f_16_1) - Console.WriteLine(f_16_2) - Console.WriteLine(f_16_3) - Console.WriteLine(f_16_4) - Console.WriteLine(f_16_5) - Console.WriteLine(f_16_6) - Console.WriteLine(f_16_7) - Console.WriteLine(f_16_8) - Console.WriteLine(f_16_9) - Console.WriteLine(f_16_10) - End Sub -End Module -|]"; - - var expected = $@" -Module Program - Sub Main(args As String()) - ' CATEGORY 2: 16 significant digits - ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits - - Const f_16_1 As Double = 0.1499999999799993 ' Dev11 & Roslyn: 0.1499999999799993 - Const f_16_2 As Double = {(IsNetCoreApp ? "0.1499999999799997" : "0.14999999997999969")} ' Dev11 & Roslyn: 0.14999999997999969 - - Const f_16_3 As Double = 0.149999999799995 ' Dev11 & Roslyn: Unchanged - - Const f_16_4 As Double = 1.499999999799994 ' Dev11 & Roslyn: Unchanged - Const f_16_5 As Double = {(IsNetCoreApp ? "1.499999999799995" : "1.4999999997999951")} ' Dev11 & Roslyn: 1.4999999997999951 - - Const f_16_6 As Double = 14999999.99799994 ' Dev11 & Roslyn: Unchanged - Const f_16_7 As Double = {(IsNetCoreApp ? "14999999.99799995" : "14999999.997999949")} ' Dev11 & Roslyn: 14999999.997999949 - - Const f_16_8 As Double = {(IsNetCoreApp ? "149999999997999.2" : "149999999997999.19")} ' Dev11 & Roslyn: 149999999997999.19 - Const f_16_9 As Double = {(IsNetCoreApp ? "149999999997999.8" : "149999999997999.81")} ' Dev11 & Roslyn: 149999999997999.81 - - Const f_16_10 As Double = 1499999999979995.0 ' Dev11 & Roslyn: Unchanged - - Console.WriteLine(f_16_1) - Console.WriteLine(f_16_2) - Console.WriteLine(f_16_3) - Console.WriteLine(f_16_4) - Console.WriteLine(f_16_5) - Console.WriteLine(f_16_6) - Console.WriteLine(f_16_7) - Console.WriteLine(f_16_8) - Console.WriteLine(f_16_9) - Console.WriteLine(f_16_10) - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceDoubleLiterals_16Digits() + => VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + ' CATEGORY 2: 16 significant digits + ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits + + Const f_16_1 As Double = .1499999999799993 ' Dev11 & Roslyn: 0.1499999999799993 + Const f_16_2 As Double = .1499999999799997 ' Dev11 & Roslyn: 0.14999999997999969 + + Const f_16_3 As Double = 0.149999999799995 ' Dev11 & Roslyn: Unchanged + + Const f_16_4 As Double = 1.499999999799994 ' Dev11 & Roslyn: Unchanged + Const f_16_5 As Double = 1.499999999799995 ' Dev11 & Roslyn: 1.4999999997999951 + + Const f_16_6 As Double = 14999999.99799994 ' Dev11 & Roslyn: Unchanged + Const f_16_7 As Double = 14999999.99799995 ' Dev11 & Roslyn: 14999999.997999949 + + Const f_16_8 As Double = 149999999997999.2 ' Dev11 & Roslyn: 149999999997999.19 + Const f_16_9 As Double = 149999999997999.8 ' Dev11 & Roslyn: 149999999997999.81 + + Const f_16_10 As Double = 1499999999979995.0 ' Dev11 & Roslyn: Unchanged + + Console.WriteLine(f_16_1) + Console.WriteLine(f_16_2) + Console.WriteLine(f_16_3) + Console.WriteLine(f_16_4) + Console.WriteLine(f_16_5) + Console.WriteLine(f_16_6) + Console.WriteLine(f_16_7) + Console.WriteLine(f_16_8) + Console.WriteLine(f_16_9) + Console.WriteLine(f_16_10) + End Sub + End Module + |] + """, $""" + + Module Program + Sub Main(args As String()) + ' CATEGORY 2: 16 significant digits + ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits + + Const f_16_1 As Double = 0.1499999999799993 ' Dev11 & Roslyn: 0.1499999999799993 + Const f_16_2 As Double = {(IsNetCoreApp ? "0.1499999999799997" : "0.14999999997999969")} ' Dev11 & Roslyn: 0.14999999997999969 + + Const f_16_3 As Double = 0.149999999799995 ' Dev11 & Roslyn: Unchanged + + Const f_16_4 As Double = 1.499999999799994 ' Dev11 & Roslyn: Unchanged + Const f_16_5 As Double = {(IsNetCoreApp ? "1.499999999799995" : "1.4999999997999951")} ' Dev11 & Roslyn: 1.4999999997999951 + + Const f_16_6 As Double = 14999999.99799994 ' Dev11 & Roslyn: Unchanged + Const f_16_7 As Double = {(IsNetCoreApp ? "14999999.99799995" : "14999999.997999949")} ' Dev11 & Roslyn: 14999999.997999949 + + Const f_16_8 As Double = {(IsNetCoreApp ? "149999999997999.2" : "149999999997999.19")} ' Dev11 & Roslyn: 149999999997999.19 + Const f_16_9 As Double = {(IsNetCoreApp ? "149999999997999.8" : "149999999997999.81")} ' Dev11 & Roslyn: 149999999997999.81 + + Const f_16_10 As Double = 1499999999979995.0 ' Dev11 & Roslyn: Unchanged + + Console.WriteLine(f_16_1) + Console.WriteLine(f_16_2) + Console.WriteLine(f_16_3) + Console.WriteLine(f_16_4) + Console.WriteLine(f_16_5) + Console.WriteLine(f_16_6) + Console.WriteLine(f_16_7) + Console.WriteLine(f_16_8) + Console.WriteLine(f_16_9) + Console.WriteLine(f_16_10) + End Sub + End Module + + """); [Fact, WorkItem(5529, "DevDiv_Projects/Roslyn")] - public async Task ReduceDoubleLiterals_16Digits_WithTypeCharacter() - { - var code = @"[| -Module Program - Sub Main(args As String()) - ' CATEGORY 2: 16 significant digits - ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits - - Const f_16_1 As Double = .1499999999799993R ' Dev11 & Roslyn: 0.1499999999799993 - Const f_16_2 As Double = .1499999999799997r ' Dev11 & Roslyn: 0.14999999997999969 - - Const f_16_3 As Double = 0.149999999799995# ' Dev11 & Roslyn: Unchanged - - Const f_16_4 As Double = 1.499999999799994R ' Dev11 & Roslyn: Unchanged - Const f_16_5 As Double = 1.499999999799995r ' Dev11 & Roslyn: 1.4999999997999951 - - Const f_16_6 As Double = 14999999.99799994# ' Dev11 & Roslyn: Unchanged - Const f_16_7 As Double = 14999999.99799995R ' Dev11 & Roslyn: 14999999.997999949 - - Const f_16_8 As Double = 149999999997999.2r ' Dev11 & Roslyn: 149999999997999.19 - Const f_16_9 As Double = 149999999997999.8# ' Dev11 & Roslyn: 149999999997999.81 - - Const f_16_10 As Double = 1499999999979995.0R ' Dev11 & Roslyn: Unchanged - - Console.WriteLine(f_16_1) - Console.WriteLine(f_16_2) - Console.WriteLine(f_16_3) - Console.WriteLine(f_16_4) - Console.WriteLine(f_16_5) - Console.WriteLine(f_16_6) - Console.WriteLine(f_16_7) - Console.WriteLine(f_16_8) - Console.WriteLine(f_16_9) - Console.WriteLine(f_16_10) - End Sub -End Module -|]"; - - var expected = $@" -Module Program - Sub Main(args As String()) - ' CATEGORY 2: 16 significant digits - ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits - - Const f_16_1 As Double = 0.1499999999799993R ' Dev11 & Roslyn: 0.1499999999799993 - Const f_16_2 As Double = {(IsNetCoreApp ? "0.1499999999799997R" : "0.14999999997999969R")} ' Dev11 & Roslyn: 0.14999999997999969 - - Const f_16_3 As Double = 0.149999999799995# ' Dev11 & Roslyn: Unchanged - - Const f_16_4 As Double = 1.499999999799994R ' Dev11 & Roslyn: Unchanged - Const f_16_5 As Double = {(IsNetCoreApp ? "1.499999999799995R" : "1.4999999997999951R")} ' Dev11 & Roslyn: 1.4999999997999951 - - Const f_16_6 As Double = 14999999.99799994# ' Dev11 & Roslyn: Unchanged - Const f_16_7 As Double = {(IsNetCoreApp ? "14999999.99799995R" : "14999999.997999949R")} ' Dev11 & Roslyn: 14999999.997999949 - - Const f_16_8 As Double = {(IsNetCoreApp ? "149999999997999.2R" : "149999999997999.19R")} ' Dev11 & Roslyn: 149999999997999.19 - Const f_16_9 As Double = {(IsNetCoreApp ? "149999999997999.8#" : "149999999997999.81#")} ' Dev11 & Roslyn: 149999999997999.81 - - Const f_16_10 As Double = 1499999999979995.0R ' Dev11 & Roslyn: Unchanged - - Console.WriteLine(f_16_1) - Console.WriteLine(f_16_2) - Console.WriteLine(f_16_3) - Console.WriteLine(f_16_4) - Console.WriteLine(f_16_5) - Console.WriteLine(f_16_6) - Console.WriteLine(f_16_7) - Console.WriteLine(f_16_8) - Console.WriteLine(f_16_9) - Console.WriteLine(f_16_10) - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceDoubleLiterals_16Digits_WithTypeCharacter() + => VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + ' CATEGORY 2: 16 significant digits + ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits + + Const f_16_1 As Double = .1499999999799993R ' Dev11 & Roslyn: 0.1499999999799993 + Const f_16_2 As Double = .1499999999799997r ' Dev11 & Roslyn: 0.14999999997999969 + + Const f_16_3 As Double = 0.149999999799995# ' Dev11 & Roslyn: Unchanged + + Const f_16_4 As Double = 1.499999999799994R ' Dev11 & Roslyn: Unchanged + Const f_16_5 As Double = 1.499999999799995r ' Dev11 & Roslyn: 1.4999999997999951 + + Const f_16_6 As Double = 14999999.99799994# ' Dev11 & Roslyn: Unchanged + Const f_16_7 As Double = 14999999.99799995R ' Dev11 & Roslyn: 14999999.997999949 + + Const f_16_8 As Double = 149999999997999.2r ' Dev11 & Roslyn: 149999999997999.19 + Const f_16_9 As Double = 149999999997999.8# ' Dev11 & Roslyn: 149999999997999.81 + + Const f_16_10 As Double = 1499999999979995.0R ' Dev11 & Roslyn: Unchanged + + Console.WriteLine(f_16_1) + Console.WriteLine(f_16_2) + Console.WriteLine(f_16_3) + Console.WriteLine(f_16_4) + Console.WriteLine(f_16_5) + Console.WriteLine(f_16_6) + Console.WriteLine(f_16_7) + Console.WriteLine(f_16_8) + Console.WriteLine(f_16_9) + Console.WriteLine(f_16_10) + End Sub + End Module + |] + """, $""" + + Module Program + Sub Main(args As String()) + ' CATEGORY 2: 16 significant digits + ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits + + Const f_16_1 As Double = 0.1499999999799993R ' Dev11 & Roslyn: 0.1499999999799993 + Const f_16_2 As Double = {(IsNetCoreApp ? "0.1499999999799997R" : "0.14999999997999969R")} ' Dev11 & Roslyn: 0.14999999997999969 + + Const f_16_3 As Double = 0.149999999799995# ' Dev11 & Roslyn: Unchanged + + Const f_16_4 As Double = 1.499999999799994R ' Dev11 & Roslyn: Unchanged + Const f_16_5 As Double = {(IsNetCoreApp ? "1.499999999799995R" : "1.4999999997999951R")} ' Dev11 & Roslyn: 1.4999999997999951 + + Const f_16_6 As Double = 14999999.99799994# ' Dev11 & Roslyn: Unchanged + Const f_16_7 As Double = {(IsNetCoreApp ? "14999999.99799995R" : "14999999.997999949R")} ' Dev11 & Roslyn: 14999999.997999949 + + Const f_16_8 As Double = {(IsNetCoreApp ? "149999999997999.2R" : "149999999997999.19R")} ' Dev11 & Roslyn: 149999999997999.19 + Const f_16_9 As Double = {(IsNetCoreApp ? "149999999997999.8#" : "149999999997999.81#")} ' Dev11 & Roslyn: 149999999997999.81 + + Const f_16_10 As Double = 1499999999979995.0R ' Dev11 & Roslyn: Unchanged + + Console.WriteLine(f_16_1) + Console.WriteLine(f_16_2) + Console.WriteLine(f_16_3) + Console.WriteLine(f_16_4) + Console.WriteLine(f_16_5) + Console.WriteLine(f_16_6) + Console.WriteLine(f_16_7) + Console.WriteLine(f_16_8) + Console.WriteLine(f_16_9) + Console.WriteLine(f_16_10) + End Sub + End Module + + """); [Fact, WorkItem(5529, "DevDiv_Projects/Roslyn")] - public async Task ReduceDoubleLiterals_GreaterThan16Digits() - { - var code = @"[| -Module Program - Sub Main(args As String()) - ' CATEGORY 3: > 16 significant digits - ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits - - ' (a) > 16 significant digits overall, but < 16 digits before decimal point. - Const f_17_1 As Double = .14999999997999938 ' Dev11 & Roslyn: 0.14999999997999938 - Const f_17_2 As Double = .14999999997999939 ' Dev11 & Roslyn: 0.14999999997999938 - Const f_17_3 As Double = .14999999997999937 ' Dev11 & Roslyn: 0.14999999997999938 - - Const f_17_4 As Double = 0.1499999997999957 ' Dev11 & Roslyn: Unchanged - Const f_17_5 As Double = 0.1499999997999958 ' Dev11 & Roslyn: 0.14999999979999579 - - Const f_17_6 As Double = 1.4999999997999947 ' Dev11 & Roslyn: Unchanged - Const f_17_7 As Double = 1.4999999997999945 ' Dev11 & Roslyn: 1.4999999997999944 - Const f_17_8 As Double = 1.4999999997999946 ' Dev11 & Roslyn: 1.4999999997999947 - - Const f_18_1 As Double = 14999999.9979999459 ' Dev11 & Roslyn: 14999999.997999946 - Const f_18_2 As Double = 14999999.9979999451 ' Dev11 & Roslyn: 14999999.997999946 - Const f_18_3 As Double = 14999999.9979999454 ' Dev11 & Roslyn: 14999999.997999946 - - ' (b) > 16 significant digits before decimal point. - Const f_18_4 As Double = 14999999999733999.2 ' Dev11 & Roslyn: 1.4999999999734E+16 - Const f_18_5 As Double = 14999999999379995.0 ' Dev11 & Roslyn: 14999999999379996.0 - - Const f_24_1 As Double = 111111149999124689999.499 ' Dev11 & Roslyn: 1.1111114999912469E+20 - - ' (c) Overflow/Underflow cases for Double: Ensure no pretty listing/round off - ' Holds signed IEEE 64-bit (8-byte) double-precision floating-point numbers ranging in value from -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values and - ' from 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values. - - Const f_overflow_1 As Double = -1.79769313486231570E+309 ' Dev11 & Roslyn: Unchanged - Const f_overflow_2 As Double = 1.79769313486231570E+309 ' Dev11 & Roslyn: Unchanged - Const f_underflow_1 As Double = -4.94065645841246544E-326 ' Dev11: -0.0F, Roslyn: unchanged - Const f_underflow_2 As Double = 4.94065645841246544E-326 ' Dev11: 0.0F, Roslyn: unchanged - - Console.WriteLine(f_17_1) - Console.WriteLine(f_17_2) - Console.WriteLine(f_17_3) - Console.WriteLine(f_17_4) - Console.WriteLine(f_17_5) - Console.WriteLine(f_17_6) - Console.WriteLine(f_17_7) - Console.WriteLine(f_17_8) - - Console.WriteLine(f_18_1) - Console.WriteLine(f_18_2) - Console.WriteLine(f_18_3) - Console.WriteLine(f_18_4) - Console.WriteLine(f_18_5) - - Console.WriteLine(f_24_1) - - Console.WriteLine(f_overflow_1) - Console.WriteLine(f_overflow_2) - Console.WriteLine(f_underflow_1) - Console.WriteLine(f_underflow_2) - End Sub -End Module -|]"; - - var expected = $@" -Module Program - Sub Main(args As String()) - ' CATEGORY 3: > 16 significant digits - ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits - - ' (a) > 16 significant digits overall, but < 16 digits before decimal point. - Const f_17_1 As Double = 0.14999999997999938 ' Dev11 & Roslyn: 0.14999999997999938 - Const f_17_2 As Double = 0.14999999997999938 ' Dev11 & Roslyn: 0.14999999997999938 - Const f_17_3 As Double = 0.14999999997999938 ' Dev11 & Roslyn: 0.14999999997999938 - - Const f_17_4 As Double = 0.1499999997999957 ' Dev11 & Roslyn: Unchanged - Const f_17_5 As Double = {(IsNetCoreApp ? "0.1499999997999958" : "0.14999999979999579")} ' Dev11 & Roslyn: 0.14999999979999579 - - Const f_17_6 As Double = 1.4999999997999947 ' Dev11 & Roslyn: Unchanged - Const f_17_7 As Double = 1.4999999997999944 ' Dev11 & Roslyn: 1.4999999997999944 - Const f_17_8 As Double = 1.4999999997999947 ' Dev11 & Roslyn: 1.4999999997999947 - - Const f_18_1 As Double = 14999999.997999946 ' Dev11 & Roslyn: 14999999.997999946 - Const f_18_2 As Double = 14999999.997999946 ' Dev11 & Roslyn: 14999999.997999946 - Const f_18_3 As Double = 14999999.997999946 ' Dev11 & Roslyn: 14999999.997999946 - - ' (b) > 16 significant digits before decimal point. - Const f_18_4 As Double = {(IsNetCoreApp ? "14999999999734000.0" : "1.4999999999734E+16")} ' Dev11 & Roslyn: 1.4999999999734E+16 - Const f_18_5 As Double = 14999999999379996.0 ' Dev11 & Roslyn: 14999999999379996.0 - - Const f_24_1 As Double = {(IsNetCoreApp ? "1.111111499991247E+20" : "1.1111114999912469E+20")} ' Dev11 & Roslyn: 1.1111114999912469E+20 - - ' (c) Overflow/Underflow cases for Double: Ensure no pretty listing/round off - ' Holds signed IEEE 64-bit (8-byte) double-precision floating-point numbers ranging in value from -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values and - ' from 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values. - - Const f_overflow_1 As Double = -1.79769313486231570E+309 ' Dev11 & Roslyn: Unchanged - Const f_overflow_2 As Double = 1.79769313486231570E+309 ' Dev11 & Roslyn: Unchanged - Const f_underflow_1 As Double = -4.94065645841246544E-326 ' Dev11: -0.0F, Roslyn: unchanged - Const f_underflow_2 As Double = 4.94065645841246544E-326 ' Dev11: 0.0F, Roslyn: unchanged - - Console.WriteLine(f_17_1) - Console.WriteLine(f_17_2) - Console.WriteLine(f_17_3) - Console.WriteLine(f_17_4) - Console.WriteLine(f_17_5) - Console.WriteLine(f_17_6) - Console.WriteLine(f_17_7) - Console.WriteLine(f_17_8) - - Console.WriteLine(f_18_1) - Console.WriteLine(f_18_2) - Console.WriteLine(f_18_3) - Console.WriteLine(f_18_4) - Console.WriteLine(f_18_5) - - Console.WriteLine(f_24_1) - - Console.WriteLine(f_overflow_1) - Console.WriteLine(f_overflow_2) - Console.WriteLine(f_underflow_1) - Console.WriteLine(f_underflow_2) - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceDoubleLiterals_GreaterThan16Digits() + => VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + ' CATEGORY 3: > 16 significant digits + ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits + + ' (a) > 16 significant digits overall, but < 16 digits before decimal point. + Const f_17_1 As Double = .14999999997999938 ' Dev11 & Roslyn: 0.14999999997999938 + Const f_17_2 As Double = .14999999997999939 ' Dev11 & Roslyn: 0.14999999997999938 + Const f_17_3 As Double = .14999999997999937 ' Dev11 & Roslyn: 0.14999999997999938 + + Const f_17_4 As Double = 0.1499999997999957 ' Dev11 & Roslyn: Unchanged + Const f_17_5 As Double = 0.1499999997999958 ' Dev11 & Roslyn: 0.14999999979999579 + + Const f_17_6 As Double = 1.4999999997999947 ' Dev11 & Roslyn: Unchanged + Const f_17_7 As Double = 1.4999999997999945 ' Dev11 & Roslyn: 1.4999999997999944 + Const f_17_8 As Double = 1.4999999997999946 ' Dev11 & Roslyn: 1.4999999997999947 + + Const f_18_1 As Double = 14999999.9979999459 ' Dev11 & Roslyn: 14999999.997999946 + Const f_18_2 As Double = 14999999.9979999451 ' Dev11 & Roslyn: 14999999.997999946 + Const f_18_3 As Double = 14999999.9979999454 ' Dev11 & Roslyn: 14999999.997999946 + + ' (b) > 16 significant digits before decimal point. + Const f_18_4 As Double = 14999999999733999.2 ' Dev11 & Roslyn: 1.4999999999734E+16 + Const f_18_5 As Double = 14999999999379995.0 ' Dev11 & Roslyn: 14999999999379996.0 + + Const f_24_1 As Double = 111111149999124689999.499 ' Dev11 & Roslyn: 1.1111114999912469E+20 + + ' (c) Overflow/Underflow cases for Double: Ensure no pretty listing/round off + ' Holds signed IEEE 64-bit (8-byte) double-precision floating-point numbers ranging in value from -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values and + ' from 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values. + + Const f_overflow_1 As Double = -1.79769313486231570E+309 ' Dev11 & Roslyn: Unchanged + Const f_overflow_2 As Double = 1.79769313486231570E+309 ' Dev11 & Roslyn: Unchanged + Const f_underflow_1 As Double = -4.94065645841246544E-326 ' Dev11: -0.0F, Roslyn: unchanged + Const f_underflow_2 As Double = 4.94065645841246544E-326 ' Dev11: 0.0F, Roslyn: unchanged + + Console.WriteLine(f_17_1) + Console.WriteLine(f_17_2) + Console.WriteLine(f_17_3) + Console.WriteLine(f_17_4) + Console.WriteLine(f_17_5) + Console.WriteLine(f_17_6) + Console.WriteLine(f_17_7) + Console.WriteLine(f_17_8) + + Console.WriteLine(f_18_1) + Console.WriteLine(f_18_2) + Console.WriteLine(f_18_3) + Console.WriteLine(f_18_4) + Console.WriteLine(f_18_5) + + Console.WriteLine(f_24_1) + + Console.WriteLine(f_overflow_1) + Console.WriteLine(f_overflow_2) + Console.WriteLine(f_underflow_1) + Console.WriteLine(f_underflow_2) + End Sub + End Module + |] + """, $""" + + Module Program + Sub Main(args As String()) + ' CATEGORY 3: > 16 significant digits + ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits + + ' (a) > 16 significant digits overall, but < 16 digits before decimal point. + Const f_17_1 As Double = 0.14999999997999938 ' Dev11 & Roslyn: 0.14999999997999938 + Const f_17_2 As Double = 0.14999999997999938 ' Dev11 & Roslyn: 0.14999999997999938 + Const f_17_3 As Double = 0.14999999997999938 ' Dev11 & Roslyn: 0.14999999997999938 + + Const f_17_4 As Double = 0.1499999997999957 ' Dev11 & Roslyn: Unchanged + Const f_17_5 As Double = {(IsNetCoreApp ? "0.1499999997999958" : "0.14999999979999579")} ' Dev11 & Roslyn: 0.14999999979999579 + + Const f_17_6 As Double = 1.4999999997999947 ' Dev11 & Roslyn: Unchanged + Const f_17_7 As Double = 1.4999999997999944 ' Dev11 & Roslyn: 1.4999999997999944 + Const f_17_8 As Double = 1.4999999997999947 ' Dev11 & Roslyn: 1.4999999997999947 + + Const f_18_1 As Double = 14999999.997999946 ' Dev11 & Roslyn: 14999999.997999946 + Const f_18_2 As Double = 14999999.997999946 ' Dev11 & Roslyn: 14999999.997999946 + Const f_18_3 As Double = 14999999.997999946 ' Dev11 & Roslyn: 14999999.997999946 + + ' (b) > 16 significant digits before decimal point. + Const f_18_4 As Double = {(IsNetCoreApp ? "14999999999734000.0" : "1.4999999999734E+16")} ' Dev11 & Roslyn: 1.4999999999734E+16 + Const f_18_5 As Double = 14999999999379996.0 ' Dev11 & Roslyn: 14999999999379996.0 + + Const f_24_1 As Double = {(IsNetCoreApp ? "1.111111499991247E+20" : "1.1111114999912469E+20")} ' Dev11 & Roslyn: 1.1111114999912469E+20 + + ' (c) Overflow/Underflow cases for Double: Ensure no pretty listing/round off + ' Holds signed IEEE 64-bit (8-byte) double-precision floating-point numbers ranging in value from -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values and + ' from 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values. + + Const f_overflow_1 As Double = -1.79769313486231570E+309 ' Dev11 & Roslyn: Unchanged + Const f_overflow_2 As Double = 1.79769313486231570E+309 ' Dev11 & Roslyn: Unchanged + Const f_underflow_1 As Double = -4.94065645841246544E-326 ' Dev11: -0.0F, Roslyn: unchanged + Const f_underflow_2 As Double = 4.94065645841246544E-326 ' Dev11: 0.0F, Roslyn: unchanged + + Console.WriteLine(f_17_1) + Console.WriteLine(f_17_2) + Console.WriteLine(f_17_3) + Console.WriteLine(f_17_4) + Console.WriteLine(f_17_5) + Console.WriteLine(f_17_6) + Console.WriteLine(f_17_7) + Console.WriteLine(f_17_8) + + Console.WriteLine(f_18_1) + Console.WriteLine(f_18_2) + Console.WriteLine(f_18_3) + Console.WriteLine(f_18_4) + Console.WriteLine(f_18_5) + + Console.WriteLine(f_24_1) + + Console.WriteLine(f_overflow_1) + Console.WriteLine(f_overflow_2) + Console.WriteLine(f_underflow_1) + Console.WriteLine(f_underflow_2) + End Sub + End Module + + """); [Fact, WorkItem(5529, "DevDiv_Projects/Roslyn")] - public async Task ReduceDoubleLiterals_GreaterThan16Digits_WithTypeCharacter() - { - var code = @"[| -Module Program - Sub Main(args As String()) - ' CATEGORY 3: > 16 significant digits - ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits - - ' (a) > 16 significant digits overall, but < 16 digits before decimal point. - Const f_17_1 As Double = .14999999997999938R ' Dev11 & Roslyn: 0.14999999997999938 - Const f_17_2 As Double = .14999999997999939r ' Dev11 & Roslyn: 0.14999999997999938 - Const f_17_3 As Double = .14999999997999937# ' Dev11 & Roslyn: 0.14999999997999938 - - Const f_17_4 As Double = 0.1499999997999957R ' Dev11 & Roslyn: Unchanged - Const f_17_5 As Double = 0.1499999997999958r ' Dev11 & Roslyn: 0.14999999979999579 - - Const f_17_6 As Double = 1.4999999997999947# ' Dev11 & Roslyn: Unchanged - Const f_17_7 As Double = 1.4999999997999945R ' Dev11 & Roslyn: 1.4999999997999944 - Const f_17_8 As Double = 1.4999999997999946r ' Dev11 & Roslyn: 1.4999999997999947 - - Const f_18_1 As Double = 14999999.9979999459# ' Dev11 & Roslyn: 14999999.997999946 - Const f_18_2 As Double = 14999999.9979999451R ' Dev11 & Roslyn: 14999999.997999946 - Const f_18_3 As Double = 14999999.9979999454r ' Dev11 & Roslyn: 14999999.997999946 - - ' (b) > 16 significant digits before decimal point. - Const f_18_4 As Double = 14999999999733999.2# ' Dev11 & Roslyn: 1.4999999999734E+16 - Const f_18_5 As Double = 14999999999379995.0R ' Dev11 & Roslyn: 14999999999379996.0 - - Const f_24_1 As Double = 111111149999124689999.499r ' Dev11 & Roslyn: 1.1111114999912469E+20 - - ' (c) Overflow/Underflow cases for Double: Ensure no pretty listing/round off - ' Holds signed IEEE 64-bit (8-byte) double-precision floating-point numbers ranging in value from -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values and - ' from 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values. - - Const f_overflow_1 As Double = -1.79769313486231570E+309# ' Dev11 & Roslyn: Unchanged - Const f_overflow_2 As Double = 1.79769313486231570E+309R ' Dev11 & Roslyn: Unchanged - Const f_underflow_1 As Double = -4.94065645841246544E-326r ' Dev11: -0.0F, Roslyn: unchanged - Const f_underflow_2 As Double = 4.94065645841246544E-326# ' Dev11: 0.0F, Roslyn: unchanged - - Console.WriteLine(f_17_1) - Console.WriteLine(f_17_2) - Console.WriteLine(f_17_3) - Console.WriteLine(f_17_4) - Console.WriteLine(f_17_5) - Console.WriteLine(f_17_6) - Console.WriteLine(f_17_7) - Console.WriteLine(f_17_8) - - Console.WriteLine(f_18_1) - Console.WriteLine(f_18_2) - Console.WriteLine(f_18_3) - Console.WriteLine(f_18_4) - Console.WriteLine(f_18_5) - - Console.WriteLine(f_24_1) - - Console.WriteLine(f_overflow_1) - Console.WriteLine(f_overflow_2) - Console.WriteLine(f_underflow_1) - Console.WriteLine(f_underflow_2) - End Sub -End Module -|]"; - - var expected = $@" -Module Program - Sub Main(args As String()) - ' CATEGORY 3: > 16 significant digits - ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits - - ' (a) > 16 significant digits overall, but < 16 digits before decimal point. - Const f_17_1 As Double = 0.14999999997999938R ' Dev11 & Roslyn: 0.14999999997999938 - Const f_17_2 As Double = 0.14999999997999938R ' Dev11 & Roslyn: 0.14999999997999938 - Const f_17_3 As Double = 0.14999999997999938# ' Dev11 & Roslyn: 0.14999999997999938 - - Const f_17_4 As Double = 0.1499999997999957R ' Dev11 & Roslyn: Unchanged - Const f_17_5 As Double = {(IsNetCoreApp ? "0.1499999997999958R" : "0.14999999979999579R")} ' Dev11 & Roslyn: 0.14999999979999579 - - Const f_17_6 As Double = 1.4999999997999947# ' Dev11 & Roslyn: Unchanged - Const f_17_7 As Double = 1.4999999997999944R ' Dev11 & Roslyn: 1.4999999997999944 - Const f_17_8 As Double = 1.4999999997999947R ' Dev11 & Roslyn: 1.4999999997999947 - - Const f_18_1 As Double = 14999999.997999946# ' Dev11 & Roslyn: 14999999.997999946 - Const f_18_2 As Double = 14999999.997999946R ' Dev11 & Roslyn: 14999999.997999946 - Const f_18_3 As Double = 14999999.997999946R ' Dev11 & Roslyn: 14999999.997999946 - - ' (b) > 16 significant digits before decimal point. - Const f_18_4 As Double = {(IsNetCoreApp ? "14999999999734000.0#" : "1.4999999999734E+16#")} ' Dev11 & Roslyn: 1.4999999999734E+16 - Const f_18_5 As Double = 14999999999379996.0R ' Dev11 & Roslyn: 14999999999379996.0 - - Const f_24_1 As Double = {(IsNetCoreApp ? "1.111111499991247E+20R" : "1.1111114999912469E+20R")} ' Dev11 & Roslyn: 1.1111114999912469E+20 - - ' (c) Overflow/Underflow cases for Double: Ensure no pretty listing/round off - ' Holds signed IEEE 64-bit (8-byte) double-precision floating-point numbers ranging in value from -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values and - ' from 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values. - - Const f_overflow_1 As Double = -1.79769313486231570E+309# ' Dev11 & Roslyn: Unchanged - Const f_overflow_2 As Double = 1.79769313486231570E+309R ' Dev11 & Roslyn: Unchanged - Const f_underflow_1 As Double = -4.94065645841246544E-326R ' Dev11: -0.0F, Roslyn: unchanged - Const f_underflow_2 As Double = 4.94065645841246544E-326# ' Dev11: 0.0F, Roslyn: unchanged - - Console.WriteLine(f_17_1) - Console.WriteLine(f_17_2) - Console.WriteLine(f_17_3) - Console.WriteLine(f_17_4) - Console.WriteLine(f_17_5) - Console.WriteLine(f_17_6) - Console.WriteLine(f_17_7) - Console.WriteLine(f_17_8) - - Console.WriteLine(f_18_1) - Console.WriteLine(f_18_2) - Console.WriteLine(f_18_3) - Console.WriteLine(f_18_4) - Console.WriteLine(f_18_5) - - Console.WriteLine(f_24_1) - - Console.WriteLine(f_overflow_1) - Console.WriteLine(f_overflow_2) - Console.WriteLine(f_underflow_1) - Console.WriteLine(f_underflow_2) - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceDoubleLiterals_GreaterThan16Digits_WithTypeCharacter() + => VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + ' CATEGORY 3: > 16 significant digits + ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits + + ' (a) > 16 significant digits overall, but < 16 digits before decimal point. + Const f_17_1 As Double = .14999999997999938R ' Dev11 & Roslyn: 0.14999999997999938 + Const f_17_2 As Double = .14999999997999939r ' Dev11 & Roslyn: 0.14999999997999938 + Const f_17_3 As Double = .14999999997999937# ' Dev11 & Roslyn: 0.14999999997999938 + + Const f_17_4 As Double = 0.1499999997999957R ' Dev11 & Roslyn: Unchanged + Const f_17_5 As Double = 0.1499999997999958r ' Dev11 & Roslyn: 0.14999999979999579 + + Const f_17_6 As Double = 1.4999999997999947# ' Dev11 & Roslyn: Unchanged + Const f_17_7 As Double = 1.4999999997999945R ' Dev11 & Roslyn: 1.4999999997999944 + Const f_17_8 As Double = 1.4999999997999946r ' Dev11 & Roslyn: 1.4999999997999947 + + Const f_18_1 As Double = 14999999.9979999459# ' Dev11 & Roslyn: 14999999.997999946 + Const f_18_2 As Double = 14999999.9979999451R ' Dev11 & Roslyn: 14999999.997999946 + Const f_18_3 As Double = 14999999.9979999454r ' Dev11 & Roslyn: 14999999.997999946 + + ' (b) > 16 significant digits before decimal point. + Const f_18_4 As Double = 14999999999733999.2# ' Dev11 & Roslyn: 1.4999999999734E+16 + Const f_18_5 As Double = 14999999999379995.0R ' Dev11 & Roslyn: 14999999999379996.0 + + Const f_24_1 As Double = 111111149999124689999.499r ' Dev11 & Roslyn: 1.1111114999912469E+20 + + ' (c) Overflow/Underflow cases for Double: Ensure no pretty listing/round off + ' Holds signed IEEE 64-bit (8-byte) double-precision floating-point numbers ranging in value from -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values and + ' from 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values. + + Const f_overflow_1 As Double = -1.79769313486231570E+309# ' Dev11 & Roslyn: Unchanged + Const f_overflow_2 As Double = 1.79769313486231570E+309R ' Dev11 & Roslyn: Unchanged + Const f_underflow_1 As Double = -4.94065645841246544E-326r ' Dev11: -0.0F, Roslyn: unchanged + Const f_underflow_2 As Double = 4.94065645841246544E-326# ' Dev11: 0.0F, Roslyn: unchanged + + Console.WriteLine(f_17_1) + Console.WriteLine(f_17_2) + Console.WriteLine(f_17_3) + Console.WriteLine(f_17_4) + Console.WriteLine(f_17_5) + Console.WriteLine(f_17_6) + Console.WriteLine(f_17_7) + Console.WriteLine(f_17_8) + + Console.WriteLine(f_18_1) + Console.WriteLine(f_18_2) + Console.WriteLine(f_18_3) + Console.WriteLine(f_18_4) + Console.WriteLine(f_18_5) + + Console.WriteLine(f_24_1) + + Console.WriteLine(f_overflow_1) + Console.WriteLine(f_overflow_2) + Console.WriteLine(f_underflow_1) + Console.WriteLine(f_underflow_2) + End Sub + End Module + |] + """, $""" + + Module Program + Sub Main(args As String()) + ' CATEGORY 3: > 16 significant digits + ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits + + ' (a) > 16 significant digits overall, but < 16 digits before decimal point. + Const f_17_1 As Double = 0.14999999997999938R ' Dev11 & Roslyn: 0.14999999997999938 + Const f_17_2 As Double = 0.14999999997999938R ' Dev11 & Roslyn: 0.14999999997999938 + Const f_17_3 As Double = 0.14999999997999938# ' Dev11 & Roslyn: 0.14999999997999938 + + Const f_17_4 As Double = 0.1499999997999957R ' Dev11 & Roslyn: Unchanged + Const f_17_5 As Double = {(IsNetCoreApp ? "0.1499999997999958R" : "0.14999999979999579R")} ' Dev11 & Roslyn: 0.14999999979999579 + + Const f_17_6 As Double = 1.4999999997999947# ' Dev11 & Roslyn: Unchanged + Const f_17_7 As Double = 1.4999999997999944R ' Dev11 & Roslyn: 1.4999999997999944 + Const f_17_8 As Double = 1.4999999997999947R ' Dev11 & Roslyn: 1.4999999997999947 + + Const f_18_1 As Double = 14999999.997999946# ' Dev11 & Roslyn: 14999999.997999946 + Const f_18_2 As Double = 14999999.997999946R ' Dev11 & Roslyn: 14999999.997999946 + Const f_18_3 As Double = 14999999.997999946R ' Dev11 & Roslyn: 14999999.997999946 + + ' (b) > 16 significant digits before decimal point. + Const f_18_4 As Double = {(IsNetCoreApp ? "14999999999734000.0#" : "1.4999999999734E+16#")} ' Dev11 & Roslyn: 1.4999999999734E+16 + Const f_18_5 As Double = 14999999999379996.0R ' Dev11 & Roslyn: 14999999999379996.0 + + Const f_24_1 As Double = {(IsNetCoreApp ? "1.111111499991247E+20R" : "1.1111114999912469E+20R")} ' Dev11 & Roslyn: 1.1111114999912469E+20 + + ' (c) Overflow/Underflow cases for Double: Ensure no pretty listing/round off + ' Holds signed IEEE 64-bit (8-byte) double-precision floating-point numbers ranging in value from -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values and + ' from 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values. + + Const f_overflow_1 As Double = -1.79769313486231570E+309# ' Dev11 & Roslyn: Unchanged + Const f_overflow_2 As Double = 1.79769313486231570E+309R ' Dev11 & Roslyn: Unchanged + Const f_underflow_1 As Double = -4.94065645841246544E-326R ' Dev11: -0.0F, Roslyn: unchanged + Const f_underflow_2 As Double = 4.94065645841246544E-326# ' Dev11: 0.0F, Roslyn: unchanged + + Console.WriteLine(f_17_1) + Console.WriteLine(f_17_2) + Console.WriteLine(f_17_3) + Console.WriteLine(f_17_4) + Console.WriteLine(f_17_5) + Console.WriteLine(f_17_6) + Console.WriteLine(f_17_7) + Console.WriteLine(f_17_8) + + Console.WriteLine(f_18_1) + Console.WriteLine(f_18_2) + Console.WriteLine(f_18_3) + Console.WriteLine(f_18_4) + Console.WriteLine(f_18_5) + + Console.WriteLine(f_24_1) + + Console.WriteLine(f_overflow_1) + Console.WriteLine(f_overflow_2) + Console.WriteLine(f_underflow_1) + Console.WriteLine(f_underflow_2) + End Sub + End Module + + """); [Fact, WorkItem(5529, "DevDiv_Projects/Roslyn")] - public async Task ReduceDecimalLiterals_LessThan30Digits() - { - var code = @"[| -Module Program - Sub Main(args As String()) - ' CATEGORY 1: Less than 30 significant digits - ' Dev11 and Roslyn behavior are identical: UNCHANGED - - ' 27 significant digits - Const d_27_1 As Decimal = .123456789012345678901234567D ' Dev11 & Roslyn: Pretty listed to 0.123456789012345678901234567D - Const d_27_2 As Decimal = 0.123456789012345678901234567d ' Dev11 & Roslyn: Unchanged - Const d_27_3 As Decimal = 1.23456789012345678901234567D ' Dev11 & Roslyn: Unchanged - Const d_27_4 As Decimal = 123456789012.345678901234567d ' Dev11 & Roslyn: Unchanged - Const d_27_5 As Decimal = 12345678901234567890123456.7D ' Dev11 & Roslyn: Unchanged - Const d_27_6 As Decimal = 123456789012345678901234567.0d ' Dev11 & Roslyn: Pretty listed to 123456789012345678901234567D - - ' 29 significant digits - Const d_29_1 As Decimal = .12345678901234567890123456789D ' Dev11 & Roslyn: 0.1234567890123456789012345679D - Const d_29_2 As Decimal = 0.12345678901234567890123456789d ' Dev11 & Roslyn: 0.1234567890123456789012345679D - Const d_29_3 As Decimal = 1.2345678901234567890123456789D ' Dev11 & Roslyn: Unchanged - Const d_29_4 As Decimal = 123456789012.34567890123456789d ' Dev11 & Roslyn: Unchanged - Const d_29_5 As Decimal = 1234567890123456789012345678.9D ' Dev11 & Roslyn: Unchanged - Const d_29_6 As Decimal = 12345678901234567890123456789.0d ' Dev11 & Roslyn: Pretty listed to 12345678901234567890123456789D - - Console.WriteLine(d_27_1) - Console.WriteLine(d_27_2) - Console.WriteLine(d_27_3) - Console.WriteLine(d_27_4) - Console.WriteLine(d_27_5) - Console.WriteLine(d_27_6) - - Console.WriteLine(d_29_1) - Console.WriteLine(d_29_2) - Console.WriteLine(d_29_3) - Console.WriteLine(d_29_4) - Console.WriteLine(d_29_5) - Console.WriteLine(d_29_6) - End Sub -End Module -|]"; - - var expected = @" -Module Program - Sub Main(args As String()) - ' CATEGORY 1: Less than 30 significant digits - ' Dev11 and Roslyn behavior are identical: UNCHANGED - - ' 27 significant digits - Const d_27_1 As Decimal = 0.123456789012345678901234567D ' Dev11 & Roslyn: Pretty listed to 0.123456789012345678901234567D - Const d_27_2 As Decimal = 0.123456789012345678901234567D ' Dev11 & Roslyn: Unchanged - Const d_27_3 As Decimal = 1.23456789012345678901234567D ' Dev11 & Roslyn: Unchanged - Const d_27_4 As Decimal = 123456789012.345678901234567D ' Dev11 & Roslyn: Unchanged - Const d_27_5 As Decimal = 12345678901234567890123456.7D ' Dev11 & Roslyn: Unchanged - Const d_27_6 As Decimal = 123456789012345678901234567D ' Dev11 & Roslyn: Pretty listed to 123456789012345678901234567D - - ' 29 significant digits - Const d_29_1 As Decimal = 0.1234567890123456789012345679D ' Dev11 & Roslyn: 0.1234567890123456789012345679D - Const d_29_2 As Decimal = 0.1234567890123456789012345679D ' Dev11 & Roslyn: 0.1234567890123456789012345679D - Const d_29_3 As Decimal = 1.2345678901234567890123456789D ' Dev11 & Roslyn: Unchanged - Const d_29_4 As Decimal = 123456789012.34567890123456789D ' Dev11 & Roslyn: Unchanged - Const d_29_5 As Decimal = 1234567890123456789012345678.9D ' Dev11 & Roslyn: Unchanged - Const d_29_6 As Decimal = 12345678901234567890123456789D ' Dev11 & Roslyn: Pretty listed to 12345678901234567890123456789D - - Console.WriteLine(d_27_1) - Console.WriteLine(d_27_2) - Console.WriteLine(d_27_3) - Console.WriteLine(d_27_4) - Console.WriteLine(d_27_5) - Console.WriteLine(d_27_6) - - Console.WriteLine(d_29_1) - Console.WriteLine(d_29_2) - Console.WriteLine(d_29_3) - Console.WriteLine(d_29_4) - Console.WriteLine(d_29_5) - Console.WriteLine(d_29_6) - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceDecimalLiterals_LessThan30Digits() + => VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + ' CATEGORY 1: Less than 30 significant digits + ' Dev11 and Roslyn behavior are identical: UNCHANGED + + ' 27 significant digits + Const d_27_1 As Decimal = .123456789012345678901234567D ' Dev11 & Roslyn: Pretty listed to 0.123456789012345678901234567D + Const d_27_2 As Decimal = 0.123456789012345678901234567d ' Dev11 & Roslyn: Unchanged + Const d_27_3 As Decimal = 1.23456789012345678901234567D ' Dev11 & Roslyn: Unchanged + Const d_27_4 As Decimal = 123456789012.345678901234567d ' Dev11 & Roslyn: Unchanged + Const d_27_5 As Decimal = 12345678901234567890123456.7D ' Dev11 & Roslyn: Unchanged + Const d_27_6 As Decimal = 123456789012345678901234567.0d ' Dev11 & Roslyn: Pretty listed to 123456789012345678901234567D + + ' 29 significant digits + Const d_29_1 As Decimal = .12345678901234567890123456789D ' Dev11 & Roslyn: 0.1234567890123456789012345679D + Const d_29_2 As Decimal = 0.12345678901234567890123456789d ' Dev11 & Roslyn: 0.1234567890123456789012345679D + Const d_29_3 As Decimal = 1.2345678901234567890123456789D ' Dev11 & Roslyn: Unchanged + Const d_29_4 As Decimal = 123456789012.34567890123456789d ' Dev11 & Roslyn: Unchanged + Const d_29_5 As Decimal = 1234567890123456789012345678.9D ' Dev11 & Roslyn: Unchanged + Const d_29_6 As Decimal = 12345678901234567890123456789.0d ' Dev11 & Roslyn: Pretty listed to 12345678901234567890123456789D + + Console.WriteLine(d_27_1) + Console.WriteLine(d_27_2) + Console.WriteLine(d_27_3) + Console.WriteLine(d_27_4) + Console.WriteLine(d_27_5) + Console.WriteLine(d_27_6) + + Console.WriteLine(d_29_1) + Console.WriteLine(d_29_2) + Console.WriteLine(d_29_3) + Console.WriteLine(d_29_4) + Console.WriteLine(d_29_5) + Console.WriteLine(d_29_6) + End Sub + End Module + |] + """, """ + + Module Program + Sub Main(args As String()) + ' CATEGORY 1: Less than 30 significant digits + ' Dev11 and Roslyn behavior are identical: UNCHANGED + + ' 27 significant digits + Const d_27_1 As Decimal = 0.123456789012345678901234567D ' Dev11 & Roslyn: Pretty listed to 0.123456789012345678901234567D + Const d_27_2 As Decimal = 0.123456789012345678901234567D ' Dev11 & Roslyn: Unchanged + Const d_27_3 As Decimal = 1.23456789012345678901234567D ' Dev11 & Roslyn: Unchanged + Const d_27_4 As Decimal = 123456789012.345678901234567D ' Dev11 & Roslyn: Unchanged + Const d_27_5 As Decimal = 12345678901234567890123456.7D ' Dev11 & Roslyn: Unchanged + Const d_27_6 As Decimal = 123456789012345678901234567D ' Dev11 & Roslyn: Pretty listed to 123456789012345678901234567D + + ' 29 significant digits + Const d_29_1 As Decimal = 0.1234567890123456789012345679D ' Dev11 & Roslyn: 0.1234567890123456789012345679D + Const d_29_2 As Decimal = 0.1234567890123456789012345679D ' Dev11 & Roslyn: 0.1234567890123456789012345679D + Const d_29_3 As Decimal = 1.2345678901234567890123456789D ' Dev11 & Roslyn: Unchanged + Const d_29_4 As Decimal = 123456789012.34567890123456789D ' Dev11 & Roslyn: Unchanged + Const d_29_5 As Decimal = 1234567890123456789012345678.9D ' Dev11 & Roslyn: Unchanged + Const d_29_6 As Decimal = 12345678901234567890123456789D ' Dev11 & Roslyn: Pretty listed to 12345678901234567890123456789D + + Console.WriteLine(d_27_1) + Console.WriteLine(d_27_2) + Console.WriteLine(d_27_3) + Console.WriteLine(d_27_4) + Console.WriteLine(d_27_5) + Console.WriteLine(d_27_6) + + Console.WriteLine(d_29_1) + Console.WriteLine(d_29_2) + Console.WriteLine(d_29_3) + Console.WriteLine(d_29_4) + Console.WriteLine(d_29_5) + Console.WriteLine(d_29_6) + End Sub + End Module + + """); [Fact, WorkItem(5529, "DevDiv_Projects/Roslyn")] - public async Task ReduceDecimalLiterals_LessThan30Digits_WithTypeCharacterDecimal() - { - var code = @"[| -Module Program - Sub Main(args As String()) - ' CATEGORY 1: Less than 30 significant digits - ' Dev11 and Roslyn behavior are identical: UNCHANGED - - ' 27 significant digits - Const d_27_1 As Decimal = .123456789012345678901234567@ ' Dev11 & Roslyn: Pretty listed to 0.123456789012345678901234567D - Const d_27_2 As Decimal = 0.123456789012345678901234567@ ' Dev11 & Roslyn: Unchanged - Const d_27_3 As Decimal = 1.23456789012345678901234567@ ' Dev11 & Roslyn: Unchanged - Const d_27_4 As Decimal = 123456789012.345678901234567@ ' Dev11 & Roslyn: Unchanged - Const d_27_5 As Decimal = 12345678901234567890123456.7@ ' Dev11 & Roslyn: Unchanged - Const d_27_6 As Decimal = 123456789012345678901234567.0@ ' Dev11 & Roslyn: Pretty listed to 123456789012345678901234567D - - ' 29 significant digits - Const d_29_1 As Decimal = .12345678901234567890123456789@ ' Dev11 & Roslyn: 0.1234567890123456789012345679@ - Const d_29_2 As Decimal = 0.12345678901234567890123456789@ ' Dev11 & Roslyn: 0.1234567890123456789012345679@ - Const d_29_3 As Decimal = 1.2345678901234567890123456789@ ' Dev11 & Roslyn: Unchanged - Const d_29_4 As Decimal = 123456789012.34567890123456789@ ' Dev11 & Roslyn: Unchanged - Const d_29_5 As Decimal = 1234567890123456789012345678.9@ ' Dev11 & Roslyn: Unchanged - Const d_29_6 As Decimal = 12345678901234567890123456789.0@ ' Dev11 & Roslyn: Pretty listed to 12345678901234567890123456789D - - Console.WriteLine(d_27_1) - Console.WriteLine(d_27_2) - Console.WriteLine(d_27_3) - Console.WriteLine(d_27_4) - Console.WriteLine(d_27_5) - Console.WriteLine(d_27_6) - - Console.WriteLine(d_29_1) - Console.WriteLine(d_29_2) - Console.WriteLine(d_29_3) - Console.WriteLine(d_29_4) - Console.WriteLine(d_29_5) - Console.WriteLine(d_29_6) - End Sub -End Module -|]"; - - var expected = @" -Module Program - Sub Main(args As String()) - ' CATEGORY 1: Less than 30 significant digits - ' Dev11 and Roslyn behavior are identical: UNCHANGED - - ' 27 significant digits - Const d_27_1 As Decimal = 0.123456789012345678901234567@ ' Dev11 & Roslyn: Pretty listed to 0.123456789012345678901234567D - Const d_27_2 As Decimal = 0.123456789012345678901234567@ ' Dev11 & Roslyn: Unchanged - Const d_27_3 As Decimal = 1.23456789012345678901234567@ ' Dev11 & Roslyn: Unchanged - Const d_27_4 As Decimal = 123456789012.345678901234567@ ' Dev11 & Roslyn: Unchanged - Const d_27_5 As Decimal = 12345678901234567890123456.7@ ' Dev11 & Roslyn: Unchanged - Const d_27_6 As Decimal = 123456789012345678901234567@ ' Dev11 & Roslyn: Pretty listed to 123456789012345678901234567D - - ' 29 significant digits - Const d_29_1 As Decimal = 0.1234567890123456789012345679@ ' Dev11 & Roslyn: 0.1234567890123456789012345679@ - Const d_29_2 As Decimal = 0.1234567890123456789012345679@ ' Dev11 & Roslyn: 0.1234567890123456789012345679@ - Const d_29_3 As Decimal = 1.2345678901234567890123456789@ ' Dev11 & Roslyn: Unchanged - Const d_29_4 As Decimal = 123456789012.34567890123456789@ ' Dev11 & Roslyn: Unchanged - Const d_29_5 As Decimal = 1234567890123456789012345678.9@ ' Dev11 & Roslyn: Unchanged - Const d_29_6 As Decimal = 12345678901234567890123456789@ ' Dev11 & Roslyn: Pretty listed to 12345678901234567890123456789D - - Console.WriteLine(d_27_1) - Console.WriteLine(d_27_2) - Console.WriteLine(d_27_3) - Console.WriteLine(d_27_4) - Console.WriteLine(d_27_5) - Console.WriteLine(d_27_6) - - Console.WriteLine(d_29_1) - Console.WriteLine(d_29_2) - Console.WriteLine(d_29_3) - Console.WriteLine(d_29_4) - Console.WriteLine(d_29_5) - Console.WriteLine(d_29_6) - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceDecimalLiterals_LessThan30Digits_WithTypeCharacterDecimal() + => VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + ' CATEGORY 1: Less than 30 significant digits + ' Dev11 and Roslyn behavior are identical: UNCHANGED + + ' 27 significant digits + Const d_27_1 As Decimal = .123456789012345678901234567@ ' Dev11 & Roslyn: Pretty listed to 0.123456789012345678901234567D + Const d_27_2 As Decimal = 0.123456789012345678901234567@ ' Dev11 & Roslyn: Unchanged + Const d_27_3 As Decimal = 1.23456789012345678901234567@ ' Dev11 & Roslyn: Unchanged + Const d_27_4 As Decimal = 123456789012.345678901234567@ ' Dev11 & Roslyn: Unchanged + Const d_27_5 As Decimal = 12345678901234567890123456.7@ ' Dev11 & Roslyn: Unchanged + Const d_27_6 As Decimal = 123456789012345678901234567.0@ ' Dev11 & Roslyn: Pretty listed to 123456789012345678901234567D + + ' 29 significant digits + Const d_29_1 As Decimal = .12345678901234567890123456789@ ' Dev11 & Roslyn: 0.1234567890123456789012345679@ + Const d_29_2 As Decimal = 0.12345678901234567890123456789@ ' Dev11 & Roslyn: 0.1234567890123456789012345679@ + Const d_29_3 As Decimal = 1.2345678901234567890123456789@ ' Dev11 & Roslyn: Unchanged + Const d_29_4 As Decimal = 123456789012.34567890123456789@ ' Dev11 & Roslyn: Unchanged + Const d_29_5 As Decimal = 1234567890123456789012345678.9@ ' Dev11 & Roslyn: Unchanged + Const d_29_6 As Decimal = 12345678901234567890123456789.0@ ' Dev11 & Roslyn: Pretty listed to 12345678901234567890123456789D + + Console.WriteLine(d_27_1) + Console.WriteLine(d_27_2) + Console.WriteLine(d_27_3) + Console.WriteLine(d_27_4) + Console.WriteLine(d_27_5) + Console.WriteLine(d_27_6) + + Console.WriteLine(d_29_1) + Console.WriteLine(d_29_2) + Console.WriteLine(d_29_3) + Console.WriteLine(d_29_4) + Console.WriteLine(d_29_5) + Console.WriteLine(d_29_6) + End Sub + End Module + |] + """, """ + + Module Program + Sub Main(args As String()) + ' CATEGORY 1: Less than 30 significant digits + ' Dev11 and Roslyn behavior are identical: UNCHANGED + + ' 27 significant digits + Const d_27_1 As Decimal = 0.123456789012345678901234567@ ' Dev11 & Roslyn: Pretty listed to 0.123456789012345678901234567D + Const d_27_2 As Decimal = 0.123456789012345678901234567@ ' Dev11 & Roslyn: Unchanged + Const d_27_3 As Decimal = 1.23456789012345678901234567@ ' Dev11 & Roslyn: Unchanged + Const d_27_4 As Decimal = 123456789012.345678901234567@ ' Dev11 & Roslyn: Unchanged + Const d_27_5 As Decimal = 12345678901234567890123456.7@ ' Dev11 & Roslyn: Unchanged + Const d_27_6 As Decimal = 123456789012345678901234567@ ' Dev11 & Roslyn: Pretty listed to 123456789012345678901234567D + + ' 29 significant digits + Const d_29_1 As Decimal = 0.1234567890123456789012345679@ ' Dev11 & Roslyn: 0.1234567890123456789012345679@ + Const d_29_2 As Decimal = 0.1234567890123456789012345679@ ' Dev11 & Roslyn: 0.1234567890123456789012345679@ + Const d_29_3 As Decimal = 1.2345678901234567890123456789@ ' Dev11 & Roslyn: Unchanged + Const d_29_4 As Decimal = 123456789012.34567890123456789@ ' Dev11 & Roslyn: Unchanged + Const d_29_5 As Decimal = 1234567890123456789012345678.9@ ' Dev11 & Roslyn: Unchanged + Const d_29_6 As Decimal = 12345678901234567890123456789@ ' Dev11 & Roslyn: Pretty listed to 12345678901234567890123456789D + + Console.WriteLine(d_27_1) + Console.WriteLine(d_27_2) + Console.WriteLine(d_27_3) + Console.WriteLine(d_27_4) + Console.WriteLine(d_27_5) + Console.WriteLine(d_27_6) + + Console.WriteLine(d_29_1) + Console.WriteLine(d_29_2) + Console.WriteLine(d_29_3) + Console.WriteLine(d_29_4) + Console.WriteLine(d_29_5) + Console.WriteLine(d_29_6) + End Sub + End Module + + """); [Fact, WorkItem(5529, "DevDiv_Projects/Roslyn")] - public async Task ReduceDecimalLiterals_30Digits() - { - var code = @"[| -Module Program - Sub Main(args As String()) - ' CATEGORY 2: 30 significant digits - ' Dev11 & Roslyn have identical behavior: pretty listed and round off to <= 29 significant digits - - Const d_30_1 As Decimal = .123456789012345678901234567891D ' Dev11 & Roslyn: 0.1234567890123456789012345679D - Const d_30_2 As Decimal = 0.1234567890123456789012345687891D ' Dev11 & Roslyn: 0.1234567890123456789012345688D - Const d_30_3 As Decimal = 1.23456789012345678901234567891D ' Dev11 & Roslyn: 1.2345678901234567890123456789D - Const d_30_4 As Decimal = 123456789012345.678901234567891D ' Dev11 & Roslyn: 123456789012345.67890123456789D - Const d_30_5 As Decimal = 12345678901234567890123456789.1D ' Dev11 & Roslyn: 12345678901234567890123456789D - - ' Overflow case 30 significant digits before decimal place: Ensure no pretty listing. - Const d_30_6 As Decimal = 123456789012345678901234567891.0D ' Dev11 & Roslyn: 123456789012345678901234567891.0D - - Console.WriteLine(d_30_1) - Console.WriteLine(d_30_2) - Console.WriteLine(d_30_3) - Console.WriteLine(d_30_4) - Console.WriteLine(d_30_5) - Console.WriteLine(d_30_6) - End Sub -End Module -|]"; - - var expected = @" -Module Program - Sub Main(args As String()) - ' CATEGORY 2: 30 significant digits - ' Dev11 & Roslyn have identical behavior: pretty listed and round off to <= 29 significant digits - - Const d_30_1 As Decimal = 0.1234567890123456789012345679D ' Dev11 & Roslyn: 0.1234567890123456789012345679D - Const d_30_2 As Decimal = 0.1234567890123456789012345688D ' Dev11 & Roslyn: 0.1234567890123456789012345688D - Const d_30_3 As Decimal = 1.2345678901234567890123456789D ' Dev11 & Roslyn: 1.2345678901234567890123456789D - Const d_30_4 As Decimal = 123456789012345.67890123456789D ' Dev11 & Roslyn: 123456789012345.67890123456789D - Const d_30_5 As Decimal = 12345678901234567890123456789D ' Dev11 & Roslyn: 12345678901234567890123456789D - - ' Overflow case 30 significant digits before decimal place: Ensure no pretty listing. - Const d_30_6 As Decimal = 123456789012345678901234567891.0D ' Dev11 & Roslyn: 123456789012345678901234567891.0D - - Console.WriteLine(d_30_1) - Console.WriteLine(d_30_2) - Console.WriteLine(d_30_3) - Console.WriteLine(d_30_4) - Console.WriteLine(d_30_5) - Console.WriteLine(d_30_6) - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceDecimalLiterals_30Digits() + => VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + ' CATEGORY 2: 30 significant digits + ' Dev11 & Roslyn have identical behavior: pretty listed and round off to <= 29 significant digits + + Const d_30_1 As Decimal = .123456789012345678901234567891D ' Dev11 & Roslyn: 0.1234567890123456789012345679D + Const d_30_2 As Decimal = 0.1234567890123456789012345687891D ' Dev11 & Roslyn: 0.1234567890123456789012345688D + Const d_30_3 As Decimal = 1.23456789012345678901234567891D ' Dev11 & Roslyn: 1.2345678901234567890123456789D + Const d_30_4 As Decimal = 123456789012345.678901234567891D ' Dev11 & Roslyn: 123456789012345.67890123456789D + Const d_30_5 As Decimal = 12345678901234567890123456789.1D ' Dev11 & Roslyn: 12345678901234567890123456789D + + ' Overflow case 30 significant digits before decimal place: Ensure no pretty listing. + Const d_30_6 As Decimal = 123456789012345678901234567891.0D ' Dev11 & Roslyn: 123456789012345678901234567891.0D + + Console.WriteLine(d_30_1) + Console.WriteLine(d_30_2) + Console.WriteLine(d_30_3) + Console.WriteLine(d_30_4) + Console.WriteLine(d_30_5) + Console.WriteLine(d_30_6) + End Sub + End Module + |] + """, """ + + Module Program + Sub Main(args As String()) + ' CATEGORY 2: 30 significant digits + ' Dev11 & Roslyn have identical behavior: pretty listed and round off to <= 29 significant digits + + Const d_30_1 As Decimal = 0.1234567890123456789012345679D ' Dev11 & Roslyn: 0.1234567890123456789012345679D + Const d_30_2 As Decimal = 0.1234567890123456789012345688D ' Dev11 & Roslyn: 0.1234567890123456789012345688D + Const d_30_3 As Decimal = 1.2345678901234567890123456789D ' Dev11 & Roslyn: 1.2345678901234567890123456789D + Const d_30_4 As Decimal = 123456789012345.67890123456789D ' Dev11 & Roslyn: 123456789012345.67890123456789D + Const d_30_5 As Decimal = 12345678901234567890123456789D ' Dev11 & Roslyn: 12345678901234567890123456789D + + ' Overflow case 30 significant digits before decimal place: Ensure no pretty listing. + Const d_30_6 As Decimal = 123456789012345678901234567891.0D ' Dev11 & Roslyn: 123456789012345678901234567891.0D + + Console.WriteLine(d_30_1) + Console.WriteLine(d_30_2) + Console.WriteLine(d_30_3) + Console.WriteLine(d_30_4) + Console.WriteLine(d_30_5) + Console.WriteLine(d_30_6) + End Sub + End Module + + """); [Fact, WorkItem(5529, "DevDiv_Projects/Roslyn")] - public async Task ReduceDecimalLiterals_30Digits_WithTypeCharacterDecimal() - { - var code = @"[| -Module Program - Sub Main(args As String()) - ' CATEGORY 2: 30 significant digits - ' Dev11 & Roslyn have identical behavior: pretty listed and round off to <= 29 significant digits - - Const d_30_1 As Decimal = .123456789012345678901234567891@ ' Dev11 & Roslyn: 0.1234567890123456789012345679D - Const d_30_2 As Decimal = 0.1234567890123456789012345687891@ ' Dev11 & Roslyn: 0.1234567890123456789012345688D - Const d_30_3 As Decimal = 1.23456789012345678901234567891@ ' Dev11 & Roslyn: 1.2345678901234567890123456789D - Const d_30_4 As Decimal = 123456789012345.678901234567891@ ' Dev11 & Roslyn: 123456789012345.67890123456789D - Const d_30_5 As Decimal = 12345678901234567890123456789.1@ ' Dev11 & Roslyn: 12345678901234567890123456789D - - ' Overflow case 30 significant digits before decimal place: Ensure no pretty listing. - Const d_30_6 As Decimal = 123456789012345678901234567891.0@ ' Dev11 & Roslyn: 123456789012345678901234567891.0D - - Console.WriteLine(d_30_1) - Console.WriteLine(d_30_2) - Console.WriteLine(d_30_3) - Console.WriteLine(d_30_4) - Console.WriteLine(d_30_5) - Console.WriteLine(d_30_6) - End Sub -End Module -|]"; - - var expected = @" -Module Program - Sub Main(args As String()) - ' CATEGORY 2: 30 significant digits - ' Dev11 & Roslyn have identical behavior: pretty listed and round off to <= 29 significant digits - - Const d_30_1 As Decimal = 0.1234567890123456789012345679@ ' Dev11 & Roslyn: 0.1234567890123456789012345679D - Const d_30_2 As Decimal = 0.1234567890123456789012345688@ ' Dev11 & Roslyn: 0.1234567890123456789012345688D - Const d_30_3 As Decimal = 1.2345678901234567890123456789@ ' Dev11 & Roslyn: 1.2345678901234567890123456789D - Const d_30_4 As Decimal = 123456789012345.67890123456789@ ' Dev11 & Roslyn: 123456789012345.67890123456789D - Const d_30_5 As Decimal = 12345678901234567890123456789@ ' Dev11 & Roslyn: 12345678901234567890123456789D - - ' Overflow case 30 significant digits before decimal place: Ensure no pretty listing. - Const d_30_6 As Decimal = 123456789012345678901234567891.0@ ' Dev11 & Roslyn: 123456789012345678901234567891.0D - - Console.WriteLine(d_30_1) - Console.WriteLine(d_30_2) - Console.WriteLine(d_30_3) - Console.WriteLine(d_30_4) - Console.WriteLine(d_30_5) - Console.WriteLine(d_30_6) - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceDecimalLiterals_30Digits_WithTypeCharacterDecimal() + => VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + ' CATEGORY 2: 30 significant digits + ' Dev11 & Roslyn have identical behavior: pretty listed and round off to <= 29 significant digits + + Const d_30_1 As Decimal = .123456789012345678901234567891@ ' Dev11 & Roslyn: 0.1234567890123456789012345679D + Const d_30_2 As Decimal = 0.1234567890123456789012345687891@ ' Dev11 & Roslyn: 0.1234567890123456789012345688D + Const d_30_3 As Decimal = 1.23456789012345678901234567891@ ' Dev11 & Roslyn: 1.2345678901234567890123456789D + Const d_30_4 As Decimal = 123456789012345.678901234567891@ ' Dev11 & Roslyn: 123456789012345.67890123456789D + Const d_30_5 As Decimal = 12345678901234567890123456789.1@ ' Dev11 & Roslyn: 12345678901234567890123456789D + + ' Overflow case 30 significant digits before decimal place: Ensure no pretty listing. + Const d_30_6 As Decimal = 123456789012345678901234567891.0@ ' Dev11 & Roslyn: 123456789012345678901234567891.0D + + Console.WriteLine(d_30_1) + Console.WriteLine(d_30_2) + Console.WriteLine(d_30_3) + Console.WriteLine(d_30_4) + Console.WriteLine(d_30_5) + Console.WriteLine(d_30_6) + End Sub + End Module + |] + """, """ + + Module Program + Sub Main(args As String()) + ' CATEGORY 2: 30 significant digits + ' Dev11 & Roslyn have identical behavior: pretty listed and round off to <= 29 significant digits + + Const d_30_1 As Decimal = 0.1234567890123456789012345679@ ' Dev11 & Roslyn: 0.1234567890123456789012345679D + Const d_30_2 As Decimal = 0.1234567890123456789012345688@ ' Dev11 & Roslyn: 0.1234567890123456789012345688D + Const d_30_3 As Decimal = 1.2345678901234567890123456789@ ' Dev11 & Roslyn: 1.2345678901234567890123456789D + Const d_30_4 As Decimal = 123456789012345.67890123456789@ ' Dev11 & Roslyn: 123456789012345.67890123456789D + Const d_30_5 As Decimal = 12345678901234567890123456789@ ' Dev11 & Roslyn: 12345678901234567890123456789D + + ' Overflow case 30 significant digits before decimal place: Ensure no pretty listing. + Const d_30_6 As Decimal = 123456789012345678901234567891.0@ ' Dev11 & Roslyn: 123456789012345678901234567891.0D + + Console.WriteLine(d_30_1) + Console.WriteLine(d_30_2) + Console.WriteLine(d_30_3) + Console.WriteLine(d_30_4) + Console.WriteLine(d_30_5) + Console.WriteLine(d_30_6) + End Sub + End Module + + """); [Fact, WorkItem(5529, "DevDiv_Projects/Roslyn")] - public async Task ReduceDecimalLiterals_GreaterThan30Digits() - { - var code = @"[| -Module Program - Sub Main(args As String()) - ' CATEGORY 3: > 30 significant digits - ' Dev11 has unpredictable behavior: pretty listed/round off to wrong values in certain cases - ' Roslyn behavior: Always rounded off + pretty listed to <= 29 significant digits - - ' (a) > 30 significant digits overall, but < 30 digits before decimal point. - Const d_32_1 As Decimal = .12345678901234567890123456789012D ' Dev11 & Roslyn: 0.1234567890123456789012345679D - Const d_32_2 As Decimal = 0.123456789012345678901234568789012@ ' Dev11 & Roslyn: 0.1234567890123456789012345688@ - Const d_32_3 As Decimal = 1.2345678901234567890123456789012d ' Dev11 & Roslyn: 1.2345678901234567890123456789D - Const d_32_4 As Decimal = 123456789012345.67890123456789012@ ' Dev11 & Roslyn: 123456789012345.67890123456789@ - - ' (b) > 30 significant digits before decimal point (Overflow case): Ensure no pretty listing. - Const d_35_1 As Decimal = 123456789012345678901234567890123.45D ' Dev11 & Roslyn: 123456789012345678901234567890123.45D - - Console.WriteLine(d_32_1) - Console.WriteLine(d_32_2) - Console.WriteLine(d_32_3) - Console.WriteLine(d_32_4) - Console.WriteLine(d_35_1) - End Sub -End Module -|]"; - - var expected = @" -Module Program - Sub Main(args As String()) - ' CATEGORY 3: > 30 significant digits - ' Dev11 has unpredictable behavior: pretty listed/round off to wrong values in certain cases - ' Roslyn behavior: Always rounded off + pretty listed to <= 29 significant digits - - ' (a) > 30 significant digits overall, but < 30 digits before decimal point. - Const d_32_1 As Decimal = 0.1234567890123456789012345679D ' Dev11 & Roslyn: 0.1234567890123456789012345679D - Const d_32_2 As Decimal = 0.1234567890123456789012345688@ ' Dev11 & Roslyn: 0.1234567890123456789012345688@ - Const d_32_3 As Decimal = 1.2345678901234567890123456789D ' Dev11 & Roslyn: 1.2345678901234567890123456789D - Const d_32_4 As Decimal = 123456789012345.67890123456789@ ' Dev11 & Roslyn: 123456789012345.67890123456789@ - - ' (b) > 30 significant digits before decimal point (Overflow case): Ensure no pretty listing. - Const d_35_1 As Decimal = 123456789012345678901234567890123.45D ' Dev11 & Roslyn: 123456789012345678901234567890123.45D - - Console.WriteLine(d_32_1) - Console.WriteLine(d_32_2) - Console.WriteLine(d_32_3) - Console.WriteLine(d_32_4) - Console.WriteLine(d_35_1) - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceDecimalLiterals_GreaterThan30Digits() + => VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + ' CATEGORY 3: > 30 significant digits + ' Dev11 has unpredictable behavior: pretty listed/round off to wrong values in certain cases + ' Roslyn behavior: Always rounded off + pretty listed to <= 29 significant digits + + ' (a) > 30 significant digits overall, but < 30 digits before decimal point. + Const d_32_1 As Decimal = .12345678901234567890123456789012D ' Dev11 & Roslyn: 0.1234567890123456789012345679D + Const d_32_2 As Decimal = 0.123456789012345678901234568789012@ ' Dev11 & Roslyn: 0.1234567890123456789012345688@ + Const d_32_3 As Decimal = 1.2345678901234567890123456789012d ' Dev11 & Roslyn: 1.2345678901234567890123456789D + Const d_32_4 As Decimal = 123456789012345.67890123456789012@ ' Dev11 & Roslyn: 123456789012345.67890123456789@ + + ' (b) > 30 significant digits before decimal point (Overflow case): Ensure no pretty listing. + Const d_35_1 As Decimal = 123456789012345678901234567890123.45D ' Dev11 & Roslyn: 123456789012345678901234567890123.45D + + Console.WriteLine(d_32_1) + Console.WriteLine(d_32_2) + Console.WriteLine(d_32_3) + Console.WriteLine(d_32_4) + Console.WriteLine(d_35_1) + End Sub + End Module + |] + """, """ + + Module Program + Sub Main(args As String()) + ' CATEGORY 3: > 30 significant digits + ' Dev11 has unpredictable behavior: pretty listed/round off to wrong values in certain cases + ' Roslyn behavior: Always rounded off + pretty listed to <= 29 significant digits + + ' (a) > 30 significant digits overall, but < 30 digits before decimal point. + Const d_32_1 As Decimal = 0.1234567890123456789012345679D ' Dev11 & Roslyn: 0.1234567890123456789012345679D + Const d_32_2 As Decimal = 0.1234567890123456789012345688@ ' Dev11 & Roslyn: 0.1234567890123456789012345688@ + Const d_32_3 As Decimal = 1.2345678901234567890123456789D ' Dev11 & Roslyn: 1.2345678901234567890123456789D + Const d_32_4 As Decimal = 123456789012345.67890123456789@ ' Dev11 & Roslyn: 123456789012345.67890123456789@ + + ' (b) > 30 significant digits before decimal point (Overflow case): Ensure no pretty listing. + Const d_35_1 As Decimal = 123456789012345678901234567890123.45D ' Dev11 & Roslyn: 123456789012345678901234567890123.45D + + Console.WriteLine(d_32_1) + Console.WriteLine(d_32_2) + Console.WriteLine(d_32_3) + Console.WriteLine(d_32_4) + Console.WriteLine(d_35_1) + End Sub + End Module + + """); [Fact, WorkItem(5529, "DevDiv_Projects/Roslyn")] - public async Task ReduceFloatLiteralsWithNegativeExponents() - { - var code = @"[| -Module Program - Sub Main(args As String()) - - ' Floating point values might be represented either in fixed point notation or scientific/exponent notation. - ' MSDN comment for Standard Numeric Format Strings used in Single.ToString(String) API (or Double.ToString(String)): - ' Fixed-point notation is used if the exponent that would result from expressing the number in scientific notation is greater than -5 and - ' less than the precision specifier; otherwise, scientific notation is used. - ' - ' However, Dev11 pretty lister differs from this for floating point values < 0. It uses fixed point notation as long as exponent is greater than '-(actualPrecision + 1)'. - ' For example, consider Single Floating literals: - ' (i) Precision = 7 - ' 0.0000001234567F => 0.0000001234567F (exponent = -7: fixed point notation) - ' 0.00000001234567F => 0.00000001234567F (exponent = -8: fixed point notation) - ' 0.000000001234567F => 1.234567E-9F (exponent = -9: exponent notation) - ' 0.0000000001234567F => 1.234567E-10F (exponent = -10: exponent notation) - ' (ii) Precision = 9 - ' 0.0000000012345678F => 0.00000000123456778F (exponent = -9: fixed point notation) - ' 0.00000000012345678F => 0.000000000123456786F (exponent = -10: fixed point notation) - ' 0.000000000012345678F => 1.23456783E-11F (exponent = -11: exponent notation) - ' 0.0000000000012345678F => 1.23456779E-12F (exponent = -12: exponent notation) - - Const f_1 As Single = 0.000001234567F - Const f_2 As Single = 0.0000001234567F - Const f_3 As Single = 0.00000001234567F - Const f_4 As Single = 0.000000001234567F ' Change at -9 - Const f_5 As Single = 0.0000000001234567F - - Const f_6 As Single = 0.00000000123456778F - Const f_7 As Single = 0.000000000123456786F - Const f_8 As Single = 0.000000000012345678F ' Change at -11 - Const f_9 As Single = 0.0000000000012345678F - - Const d_1 As Single = 0.00000000000000123456789012345 - Const d_2 As Single = 0.000000000000000123456789012345 - Const d_3 As Single = 0.0000000000000000123456789012345 ' Change at -17 - Const d_4 As Single = 0.00000000000000000123456789012345 - - Const d_5 As Double = 0.00000000000000001234567890123456 - Const d_6 As Double = 0.000000000000000001234567890123456 - Const d_7 As Double = 0.0000000000000000001234567890123456 ' Change at -19 - Const d_8 As Double = 0.00000000000000000001234567890123456 - End Sub -End Module -|]"; - - var expected = $@" -Module Program - Sub Main(args As String()) - - ' Floating point values might be represented either in fixed point notation or scientific/exponent notation. - ' MSDN comment for Standard Numeric Format Strings used in Single.ToString(String) API (or Double.ToString(String)): - ' Fixed-point notation is used if the exponent that would result from expressing the number in scientific notation is greater than -5 and - ' less than the precision specifier; otherwise, scientific notation is used. - ' - ' However, Dev11 pretty lister differs from this for floating point values < 0. It uses fixed point notation as long as exponent is greater than '-(actualPrecision + 1)'. - ' For example, consider Single Floating literals: - ' (i) Precision = 7 - ' 0.0000001234567F => 0.0000001234567F (exponent = -7: fixed point notation) - ' 0.00000001234567F => 0.00000001234567F (exponent = -8: fixed point notation) - ' 0.000000001234567F => 1.234567E-9F (exponent = -9: exponent notation) - ' 0.0000000001234567F => 1.234567E-10F (exponent = -10: exponent notation) - ' (ii) Precision = 9 - ' 0.0000000012345678F => 0.00000000123456778F (exponent = -9: fixed point notation) - ' 0.00000000012345678F => 0.000000000123456786F (exponent = -10: fixed point notation) - ' 0.000000000012345678F => 1.23456783E-11F (exponent = -11: exponent notation) - ' 0.0000000000012345678F => 1.23456779E-12F (exponent = -12: exponent notation) - - Const f_1 As Single = 0.000001234567F - Const f_2 As Single = 0.0000001234567F - Const f_3 As Single = 0.00000001234567F - Const f_4 As Single = 1.234567E-9F ' Change at -9 - Const f_5 As Single = 1.234567E-10F - - Const f_6 As Single = {(IsNetCoreApp ? "0.0000000012345678F" : "0.00000000123456778F")} - Const f_7 As Single = {(IsNetCoreApp ? "0.00000000012345679F" : "0.000000000123456786F")} - Const f_8 As Single = {(IsNetCoreApp ? "1.2345678E-11F" : "1.23456783E-11F")} ' Change at -11 - Const f_9 As Single = {(IsNetCoreApp ? "1.2345678E-12F" : "1.23456779E-12F")} - - Const d_1 As Single = 0.00000000000000123456789012345 - Const d_2 As Single = 0.000000000000000123456789012345 - Const d_3 As Single = 1.23456789012345E-17 ' Change at -17 - Const d_4 As Single = 1.23456789012345E-18 - - Const d_5 As Double = {(IsNetCoreApp ? "0.00000000000000001234567890123456" : "0.000000000000000012345678901234561")} - Const d_6 As Double = 0.000000000000000001234567890123456 - Const d_7 As Double = {(IsNetCoreApp ? "1.234567890123456E-19" : "1.2345678901234561E-19")} ' Change at -19 - Const d_8 As Double = 1.234567890123456E-20 - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceFloatLiteralsWithNegativeExponents() + => VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + + ' Floating point values might be represented either in fixed point notation or scientific/exponent notation. + ' MSDN comment for Standard Numeric Format Strings used in Single.ToString(String) API (or Double.ToString(String)): + ' Fixed-point notation is used if the exponent that would result from expressing the number in scientific notation is greater than -5 and + ' less than the precision specifier; otherwise, scientific notation is used. + ' + ' However, Dev11 pretty lister differs from this for floating point values < 0. It uses fixed point notation as long as exponent is greater than '-(actualPrecision + 1)'. + ' For example, consider Single Floating literals: + ' (i) Precision = 7 + ' 0.0000001234567F => 0.0000001234567F (exponent = -7: fixed point notation) + ' 0.00000001234567F => 0.00000001234567F (exponent = -8: fixed point notation) + ' 0.000000001234567F => 1.234567E-9F (exponent = -9: exponent notation) + ' 0.0000000001234567F => 1.234567E-10F (exponent = -10: exponent notation) + ' (ii) Precision = 9 + ' 0.0000000012345678F => 0.00000000123456778F (exponent = -9: fixed point notation) + ' 0.00000000012345678F => 0.000000000123456786F (exponent = -10: fixed point notation) + ' 0.000000000012345678F => 1.23456783E-11F (exponent = -11: exponent notation) + ' 0.0000000000012345678F => 1.23456779E-12F (exponent = -12: exponent notation) + + Const f_1 As Single = 0.000001234567F + Const f_2 As Single = 0.0000001234567F + Const f_3 As Single = 0.00000001234567F + Const f_4 As Single = 0.000000001234567F ' Change at -9 + Const f_5 As Single = 0.0000000001234567F + + Const f_6 As Single = 0.00000000123456778F + Const f_7 As Single = 0.000000000123456786F + Const f_8 As Single = 0.000000000012345678F ' Change at -11 + Const f_9 As Single = 0.0000000000012345678F + + Const d_1 As Single = 0.00000000000000123456789012345 + Const d_2 As Single = 0.000000000000000123456789012345 + Const d_3 As Single = 0.0000000000000000123456789012345 ' Change at -17 + Const d_4 As Single = 0.00000000000000000123456789012345 + + Const d_5 As Double = 0.00000000000000001234567890123456 + Const d_6 As Double = 0.000000000000000001234567890123456 + Const d_7 As Double = 0.0000000000000000001234567890123456 ' Change at -19 + Const d_8 As Double = 0.00000000000000000001234567890123456 + End Sub + End Module + |] + """, $""" + + Module Program + Sub Main(args As String()) + + ' Floating point values might be represented either in fixed point notation or scientific/exponent notation. + ' MSDN comment for Standard Numeric Format Strings used in Single.ToString(String) API (or Double.ToString(String)): + ' Fixed-point notation is used if the exponent that would result from expressing the number in scientific notation is greater than -5 and + ' less than the precision specifier; otherwise, scientific notation is used. + ' + ' However, Dev11 pretty lister differs from this for floating point values < 0. It uses fixed point notation as long as exponent is greater than '-(actualPrecision + 1)'. + ' For example, consider Single Floating literals: + ' (i) Precision = 7 + ' 0.0000001234567F => 0.0000001234567F (exponent = -7: fixed point notation) + ' 0.00000001234567F => 0.00000001234567F (exponent = -8: fixed point notation) + ' 0.000000001234567F => 1.234567E-9F (exponent = -9: exponent notation) + ' 0.0000000001234567F => 1.234567E-10F (exponent = -10: exponent notation) + ' (ii) Precision = 9 + ' 0.0000000012345678F => 0.00000000123456778F (exponent = -9: fixed point notation) + ' 0.00000000012345678F => 0.000000000123456786F (exponent = -10: fixed point notation) + ' 0.000000000012345678F => 1.23456783E-11F (exponent = -11: exponent notation) + ' 0.0000000000012345678F => 1.23456779E-12F (exponent = -12: exponent notation) + + Const f_1 As Single = 0.000001234567F + Const f_2 As Single = 0.0000001234567F + Const f_3 As Single = 0.00000001234567F + Const f_4 As Single = 1.234567E-9F ' Change at -9 + Const f_5 As Single = 1.234567E-10F + + Const f_6 As Single = {(IsNetCoreApp ? "0.0000000012345678F" : "0.00000000123456778F")} + Const f_7 As Single = {(IsNetCoreApp ? "0.00000000012345679F" : "0.000000000123456786F")} + Const f_8 As Single = {(IsNetCoreApp ? "1.2345678E-11F" : "1.23456783E-11F")} ' Change at -11 + Const f_9 As Single = {(IsNetCoreApp ? "1.2345678E-12F" : "1.23456779E-12F")} + + Const d_1 As Single = 0.00000000000000123456789012345 + Const d_2 As Single = 0.000000000000000123456789012345 + Const d_3 As Single = 1.23456789012345E-17 ' Change at -17 + Const d_4 As Single = 1.23456789012345E-18 + + Const d_5 As Double = {(IsNetCoreApp ? "0.00000000000000001234567890123456" : "0.000000000000000012345678901234561")} + Const d_6 As Double = 0.000000000000000001234567890123456 + Const d_7 As Double = {(IsNetCoreApp ? "1.234567890123456E-19" : "1.2345678901234561E-19")} ' Change at -19 + Const d_8 As Double = 1.234567890123456E-20 + End Sub + End Module + + """); [Fact, WorkItem(5529, "DevDiv_Projects/Roslyn")] - public async Task ReduceSingleLiteralsWithTrailingZeros() - { - var code = @"[| -Module Program - Sub Main(args As String()) - Const f1 As Single = 3.011000F ' Dev11 & Roslyn: 3.011F - Const f2 As Single = 3.000000! ' Dev11 & Roslyn: 3.0! - Const f3 As Single = 3.0F ' Dev11 & Roslyn: Unchanged - Const f4 As Single = 3000f ' Dev11 & Roslyn: 3000.0F - Const f5 As Single = 3000E+10! ' Dev11 & Roslyn: 3.0E+13! - Const f6 As Single = 3000.0E+10F ' Dev11 & Roslyn: 3.0E+13F - Const f7 As Single = 3000.010E+1F ' Dev11 & Roslyn: 30000.1F - Const f8 As Single = 3000.123456789010E+10! ' Dev11 & Roslyn: 3.00012337E+13! - Const f9 As Single = 3000.123456789000E+10F ' Dev11 & Roslyn: 3.00012337E+13F - Const f10 As Single = 30001234567890.10E-10f ' Dev11 & Roslyn: 3000.12354F - Const f11 As Single = 3000E-10! ' Dev11 & Roslyn: 0.0000003! - - Console.WriteLine(f1) - Console.WriteLine(f2) - Console.WriteLine(f3) - Console.WriteLine(f4) - Console.WriteLine(f5) - Console.WriteLine(f6) - Console.WriteLine(f7) - Console.WriteLine(f8) - Console.WriteLine(f9) - Console.WriteLine(f10) - Console.WriteLine(f11) - End Sub -End Module -|]"; - - var expected = $@" -Module Program - Sub Main(args As String()) - Const f1 As Single = 3.011F ' Dev11 & Roslyn: 3.011F - Const f2 As Single = 3.0! ' Dev11 & Roslyn: 3.0! - Const f3 As Single = 3.0F ' Dev11 & Roslyn: Unchanged - Const f4 As Single = 3000.0F ' Dev11 & Roslyn: 3000.0F - Const f5 As Single = 3.0E+13! ' Dev11 & Roslyn: 3.0E+13! - Const f6 As Single = 3.0E+13F ' Dev11 & Roslyn: 3.0E+13F - Const f7 As Single = 30000.1F ' Dev11 & Roslyn: 30000.1F - Const f8 As Single = {(IsNetCoreApp ? "3.0001234E+13!" : "3.00012337E+13!")} ' Dev11 & Roslyn: 3.00012337E+13! - Const f9 As Single = {(IsNetCoreApp ? "3.0001234E+13F" : "3.00012337E+13F")} ' Dev11 & Roslyn: 3.00012337E+13F - Const f10 As Single = {(IsNetCoreApp ? "3000.1235F" : "3000.12354F")} ' Dev11 & Roslyn: 3000.12354F - Const f11 As Single = 0.0000003! ' Dev11 & Roslyn: 0.0000003! - - Console.WriteLine(f1) - Console.WriteLine(f2) - Console.WriteLine(f3) - Console.WriteLine(f4) - Console.WriteLine(f5) - Console.WriteLine(f6) - Console.WriteLine(f7) - Console.WriteLine(f8) - Console.WriteLine(f9) - Console.WriteLine(f10) - Console.WriteLine(f11) - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceSingleLiteralsWithTrailingZeros() + => VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + Const f1 As Single = 3.011000F ' Dev11 & Roslyn: 3.011F + Const f2 As Single = 3.000000! ' Dev11 & Roslyn: 3.0! + Const f3 As Single = 3.0F ' Dev11 & Roslyn: Unchanged + Const f4 As Single = 3000f ' Dev11 & Roslyn: 3000.0F + Const f5 As Single = 3000E+10! ' Dev11 & Roslyn: 3.0E+13! + Const f6 As Single = 3000.0E+10F ' Dev11 & Roslyn: 3.0E+13F + Const f7 As Single = 3000.010E+1F ' Dev11 & Roslyn: 30000.1F + Const f8 As Single = 3000.123456789010E+10! ' Dev11 & Roslyn: 3.00012337E+13! + Const f9 As Single = 3000.123456789000E+10F ' Dev11 & Roslyn: 3.00012337E+13F + Const f10 As Single = 30001234567890.10E-10f ' Dev11 & Roslyn: 3000.12354F + Const f11 As Single = 3000E-10! ' Dev11 & Roslyn: 0.0000003! + + Console.WriteLine(f1) + Console.WriteLine(f2) + Console.WriteLine(f3) + Console.WriteLine(f4) + Console.WriteLine(f5) + Console.WriteLine(f6) + Console.WriteLine(f7) + Console.WriteLine(f8) + Console.WriteLine(f9) + Console.WriteLine(f10) + Console.WriteLine(f11) + End Sub + End Module + |] + """, $""" + + Module Program + Sub Main(args As String()) + Const f1 As Single = 3.011F ' Dev11 & Roslyn: 3.011F + Const f2 As Single = 3.0! ' Dev11 & Roslyn: 3.0! + Const f3 As Single = 3.0F ' Dev11 & Roslyn: Unchanged + Const f4 As Single = 3000.0F ' Dev11 & Roslyn: 3000.0F + Const f5 As Single = 3.0E+13! ' Dev11 & Roslyn: 3.0E+13! + Const f6 As Single = 3.0E+13F ' Dev11 & Roslyn: 3.0E+13F + Const f7 As Single = 30000.1F ' Dev11 & Roslyn: 30000.1F + Const f8 As Single = {(IsNetCoreApp ? "3.0001234E+13!" : "3.00012337E+13!")} ' Dev11 & Roslyn: 3.00012337E+13! + Const f9 As Single = {(IsNetCoreApp ? "3.0001234E+13F" : "3.00012337E+13F")} ' Dev11 & Roslyn: 3.00012337E+13F + Const f10 As Single = {(IsNetCoreApp ? "3000.1235F" : "3000.12354F")} ' Dev11 & Roslyn: 3000.12354F + Const f11 As Single = 0.0000003! ' Dev11 & Roslyn: 0.0000003! + + Console.WriteLine(f1) + Console.WriteLine(f2) + Console.WriteLine(f3) + Console.WriteLine(f4) + Console.WriteLine(f5) + Console.WriteLine(f6) + Console.WriteLine(f7) + Console.WriteLine(f8) + Console.WriteLine(f9) + Console.WriteLine(f10) + Console.WriteLine(f11) + End Sub + End Module + + """); [Fact, WorkItem(5529, "DevDiv_Projects/Roslyn")] - public async Task ReduceDoubleLiteralsWithTrailingZeros() - { - var code = @"[| -Module Program - Sub Main(args As String()) - Const d1 As Double = 3.011000 ' Dev11 & Roslyn: 3.011 - Const d2 As Double = 3.000000 ' Dev11 & Roslyn: 3.0 - Const d3 As Double = 3.0 ' Dev11 & Roslyn: Unchanged - Const d4 As Double = 3000R ' Dev11 & Roslyn: 3000.0R - Const d5 As Double = 3000E+10# ' Dev11 & Roslyn: 30000000000000.0# - Const d6 As Double = 3000.0E+10 ' Dev11 & Roslyn: 30000000000000.0 - Const d7 As Double = 3000.010E+1 ' Dev11 & Roslyn: 30000.1 - Const d8 As Double = 3000.123456789010E+10# ' Dev11 & Roslyn: 30001234567890.1# - Const d9 As Double = 3000.123456789000E+10 ' Dev11 & Roslyn: 30001234567890.0 - Const d10 As Double = 30001234567890.10E-10d ' Dev11 & Roslyn: 3000.12345678901D - Const d11 As Double = 3000E-10 ' Dev11 & Roslyn: 0.0000003 - - Console.WriteLine(d1) - Console.WriteLine(d2) - Console.WriteLine(d3) - Console.WriteLine(d4) - Console.WriteLine(d5) - Console.WriteLine(d6) - Console.WriteLine(d7) - Console.WriteLine(d8) - Console.WriteLine(d9) - Console.WriteLine(d10) - Console.WriteLine(d11) - End Sub -End Module -|]"; - - var expected = @" -Module Program - Sub Main(args As String()) - Const d1 As Double = 3.011 ' Dev11 & Roslyn: 3.011 - Const d2 As Double = 3.0 ' Dev11 & Roslyn: 3.0 - Const d3 As Double = 3.0 ' Dev11 & Roslyn: Unchanged - Const d4 As Double = 3000.0R ' Dev11 & Roslyn: 3000.0R - Const d5 As Double = 30000000000000.0# ' Dev11 & Roslyn: 30000000000000.0# - Const d6 As Double = 30000000000000.0 ' Dev11 & Roslyn: 30000000000000.0 - Const d7 As Double = 30000.1 ' Dev11 & Roslyn: 30000.1 - Const d8 As Double = 30001234567890.1# ' Dev11 & Roslyn: 30001234567890.1# - Const d9 As Double = 30001234567890.0 ' Dev11 & Roslyn: 30001234567890.0 - Const d10 As Double = 3000.12345678901D ' Dev11 & Roslyn: 3000.12345678901D - Const d11 As Double = 0.0000003 ' Dev11 & Roslyn: 0.0000003 - - Console.WriteLine(d1) - Console.WriteLine(d2) - Console.WriteLine(d3) - Console.WriteLine(d4) - Console.WriteLine(d5) - Console.WriteLine(d6) - Console.WriteLine(d7) - Console.WriteLine(d8) - Console.WriteLine(d9) - Console.WriteLine(d10) - Console.WriteLine(d11) - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceDoubleLiteralsWithTrailingZeros() + => VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + Const d1 As Double = 3.011000 ' Dev11 & Roslyn: 3.011 + Const d2 As Double = 3.000000 ' Dev11 & Roslyn: 3.0 + Const d3 As Double = 3.0 ' Dev11 & Roslyn: Unchanged + Const d4 As Double = 3000R ' Dev11 & Roslyn: 3000.0R + Const d5 As Double = 3000E+10# ' Dev11 & Roslyn: 30000000000000.0# + Const d6 As Double = 3000.0E+10 ' Dev11 & Roslyn: 30000000000000.0 + Const d7 As Double = 3000.010E+1 ' Dev11 & Roslyn: 30000.1 + Const d8 As Double = 3000.123456789010E+10# ' Dev11 & Roslyn: 30001234567890.1# + Const d9 As Double = 3000.123456789000E+10 ' Dev11 & Roslyn: 30001234567890.0 + Const d10 As Double = 30001234567890.10E-10d ' Dev11 & Roslyn: 3000.12345678901D + Const d11 As Double = 3000E-10 ' Dev11 & Roslyn: 0.0000003 + + Console.WriteLine(d1) + Console.WriteLine(d2) + Console.WriteLine(d3) + Console.WriteLine(d4) + Console.WriteLine(d5) + Console.WriteLine(d6) + Console.WriteLine(d7) + Console.WriteLine(d8) + Console.WriteLine(d9) + Console.WriteLine(d10) + Console.WriteLine(d11) + End Sub + End Module + |] + """, """ + + Module Program + Sub Main(args As String()) + Const d1 As Double = 3.011 ' Dev11 & Roslyn: 3.011 + Const d2 As Double = 3.0 ' Dev11 & Roslyn: 3.0 + Const d3 As Double = 3.0 ' Dev11 & Roslyn: Unchanged + Const d4 As Double = 3000.0R ' Dev11 & Roslyn: 3000.0R + Const d5 As Double = 30000000000000.0# ' Dev11 & Roslyn: 30000000000000.0# + Const d6 As Double = 30000000000000.0 ' Dev11 & Roslyn: 30000000000000.0 + Const d7 As Double = 30000.1 ' Dev11 & Roslyn: 30000.1 + Const d8 As Double = 30001234567890.1# ' Dev11 & Roslyn: 30001234567890.1# + Const d9 As Double = 30001234567890.0 ' Dev11 & Roslyn: 30001234567890.0 + Const d10 As Double = 3000.12345678901D ' Dev11 & Roslyn: 3000.12345678901D + Const d11 As Double = 0.0000003 ' Dev11 & Roslyn: 0.0000003 + + Console.WriteLine(d1) + Console.WriteLine(d2) + Console.WriteLine(d3) + Console.WriteLine(d4) + Console.WriteLine(d5) + Console.WriteLine(d6) + Console.WriteLine(d7) + Console.WriteLine(d8) + Console.WriteLine(d9) + Console.WriteLine(d10) + Console.WriteLine(d11) + End Sub + End Module + + """); [Fact, WorkItem(5529, "DevDiv_Projects/Roslyn")] - public async Task ReduceDecimalLiteralsWithTrailingZeros() - { - var code = @"[| -Module Program - Sub Main(args As String()) - Const d1 As Decimal = 3.011000D ' Dev11 & Roslyn: 3.011D - Const d2 As Decimal = 3.000000D ' Dev11 & Roslyn: 3D - Const d3 As Decimal = 3.0D ' Dev11 & Roslyn: 3D - Const d4 As Decimal = 3000D ' Dev11 & Roslyn: 3000D - Const d5 As Decimal = 3000E+10D ' Dev11 & Roslyn: 30000000000000D - Const d6 As Decimal = 3000.0E+10D ' Dev11 & Roslyn: 30000000000000D - Const d7 As Decimal = 3000.010E+1D ' Dev11 & Roslyn: 30000.1D - Const d8 As Decimal = 3000.123456789010E+10D ' Dev11 & Roslyn: 30001234567890.1D - Const d9 As Decimal = 3000.123456789000E+10D ' Dev11 & Roslyn: 30001234567890D - Const d10 As Decimal = 30001234567890.10E-10D ' Dev11 & Roslyn: 3000.12345678901D - Const d11 As Decimal = 3000E-10D ' Dev11 & Roslyn: 0.0000003D - - Console.WriteLine(d1) - Console.WriteLine(d2) - Console.WriteLine(d3) - Console.WriteLine(d4) - Console.WriteLine(d5) - Console.WriteLine(d6) - Console.WriteLine(d7) - Console.WriteLine(d8) - Console.WriteLine(d9) - Console.WriteLine(d10) - Console.WriteLine(d11) - End Sub -End Module -|]"; - - var expected = @" -Module Program - Sub Main(args As String()) - Const d1 As Decimal = 3.011D ' Dev11 & Roslyn: 3.011D - Const d2 As Decimal = 3D ' Dev11 & Roslyn: 3D - Const d3 As Decimal = 3D ' Dev11 & Roslyn: 3D - Const d4 As Decimal = 3000D ' Dev11 & Roslyn: 3000D - Const d5 As Decimal = 30000000000000D ' Dev11 & Roslyn: 30000000000000D - Const d6 As Decimal = 30000000000000D ' Dev11 & Roslyn: 30000000000000D - Const d7 As Decimal = 30000.1D ' Dev11 & Roslyn: 30000.1D - Const d8 As Decimal = 30001234567890.1D ' Dev11 & Roslyn: 30001234567890.1D - Const d9 As Decimal = 30001234567890D ' Dev11 & Roslyn: 30001234567890D - Const d10 As Decimal = 3000.12345678901D ' Dev11 & Roslyn: 3000.12345678901D - Const d11 As Decimal = 0.0000003D ' Dev11 & Roslyn: 0.0000003D - - Console.WriteLine(d1) - Console.WriteLine(d2) - Console.WriteLine(d3) - Console.WriteLine(d4) - Console.WriteLine(d5) - Console.WriteLine(d6) - Console.WriteLine(d7) - Console.WriteLine(d8) - Console.WriteLine(d9) - Console.WriteLine(d10) - Console.WriteLine(d11) - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceDecimalLiteralsWithTrailingZeros() + => VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + Const d1 As Decimal = 3.011000D ' Dev11 & Roslyn: 3.011D + Const d2 As Decimal = 3.000000D ' Dev11 & Roslyn: 3D + Const d3 As Decimal = 3.0D ' Dev11 & Roslyn: 3D + Const d4 As Decimal = 3000D ' Dev11 & Roslyn: 3000D + Const d5 As Decimal = 3000E+10D ' Dev11 & Roslyn: 30000000000000D + Const d6 As Decimal = 3000.0E+10D ' Dev11 & Roslyn: 30000000000000D + Const d7 As Decimal = 3000.010E+1D ' Dev11 & Roslyn: 30000.1D + Const d8 As Decimal = 3000.123456789010E+10D ' Dev11 & Roslyn: 30001234567890.1D + Const d9 As Decimal = 3000.123456789000E+10D ' Dev11 & Roslyn: 30001234567890D + Const d10 As Decimal = 30001234567890.10E-10D ' Dev11 & Roslyn: 3000.12345678901D + Const d11 As Decimal = 3000E-10D ' Dev11 & Roslyn: 0.0000003D + + Console.WriteLine(d1) + Console.WriteLine(d2) + Console.WriteLine(d3) + Console.WriteLine(d4) + Console.WriteLine(d5) + Console.WriteLine(d6) + Console.WriteLine(d7) + Console.WriteLine(d8) + Console.WriteLine(d9) + Console.WriteLine(d10) + Console.WriteLine(d11) + End Sub + End Module + |] + """, """ + + Module Program + Sub Main(args As String()) + Const d1 As Decimal = 3.011D ' Dev11 & Roslyn: 3.011D + Const d2 As Decimal = 3D ' Dev11 & Roslyn: 3D + Const d3 As Decimal = 3D ' Dev11 & Roslyn: 3D + Const d4 As Decimal = 3000D ' Dev11 & Roslyn: 3000D + Const d5 As Decimal = 30000000000000D ' Dev11 & Roslyn: 30000000000000D + Const d6 As Decimal = 30000000000000D ' Dev11 & Roslyn: 30000000000000D + Const d7 As Decimal = 30000.1D ' Dev11 & Roslyn: 30000.1D + Const d8 As Decimal = 30001234567890.1D ' Dev11 & Roslyn: 30001234567890.1D + Const d9 As Decimal = 30001234567890D ' Dev11 & Roslyn: 30001234567890D + Const d10 As Decimal = 3000.12345678901D ' Dev11 & Roslyn: 3000.12345678901D + Const d11 As Decimal = 0.0000003D ' Dev11 & Roslyn: 0.0000003D + + Console.WriteLine(d1) + Console.WriteLine(d2) + Console.WriteLine(d3) + Console.WriteLine(d4) + Console.WriteLine(d5) + Console.WriteLine(d6) + Console.WriteLine(d7) + Console.WriteLine(d8) + Console.WriteLine(d9) + Console.WriteLine(d10) + Console.WriteLine(d11) + End Sub + End Module + + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/623319")] public async Task ReduceFloatingAndDecimalLiteralsWithDifferentCulture() @@ -1726,25 +1705,25 @@ public async Task ReduceFloatingAndDecimalLiteralsWithDifferentCulture() { System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("de-DE"); - - var code = @"[| -Module Program - Sub Main(args As String()) - Dim d = 1.0D - Dim f = 1.0F - Dim x = 1.0 - End Sub -End Module|]"; - - var expected = @" -Module Program - Sub Main(args As String()) - Dim d = 1D - Dim f = 1.0F - Dim x = 1.0 - End Sub -End Module"; - await VerifyAsync(code, expected); + await VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + Dim d = 1.0D + Dim f = 1.0F + Dim x = 1.0 + End Sub + End Module|] + """, """ + + Module Program + Sub Main(args As String()) + Dim d = 1D + Dim f = 1.0F + Dim x = 1.0 + End Sub + End Module + """); } finally { @@ -1760,25 +1739,25 @@ public async Task ReduceFloatingAndDecimalLiteralsWithInvariantCultureNegatives( { Thread.CurrentThread.CurrentCulture = (CultureInfo)oldCulture.Clone(); Thread.CurrentThread.CurrentCulture.NumberFormat.NegativeSign = "~"; - - var code = @"[| -Module Program - Sub Main(args As String()) - Dim d = -1.0E-11D - Dim f = -1.0E-11F - Dim x = -1.0E-11 - End Sub -End Module|]"; - - var expected = @" -Module Program - Sub Main(args As String()) - Dim d = -0.00000000001D - Dim f = -1.0E-11F - Dim x = -0.00000000001 - End Sub -End Module"; - await VerifyAsync(code, expected); + await VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + Dim d = -1.0E-11D + Dim f = -1.0E-11F + Dim x = -1.0E-11 + End Sub + End Module|] + """, """ + + Module Program + Sub Main(args As String()) + Dim d = -0.00000000001D + Dim f = -1.0E-11F + Dim x = -0.00000000001 + End Sub + End Module + """); } finally { @@ -1787,214 +1766,212 @@ End Sub } [Fact] - public async Task ReduceIntegerLiteralWithLeadingZeros() - { - var code = @"[| -Module Program - Sub Main(args As String()) - Const i0 As Integer = 0060 - Const i1 As Integer = 0060% - Const i2 As Integer = &H006F - Const i3 As Integer = &O0060 - Const i4 As Integer = 0060I - Const i5 As Integer = -0060 - Const i6 As Integer = 000 - Const i7 As UInteger = 0060UI - Const i8 As Integer = &H0000FFFFI - Const i9 As Integer = &O000 - Const i10 As Integer = &H000 - Const l0 As Long = 0060L - Const l1 As Long = 0060& - Const l2 As ULong = 0060UL - Const s0 As Short = 0060S - Const s1 As UShort = 0060US - Const s2 As Short = &H0000FFFFS - End Sub -End Module -|]"; - - var expected = @" -Module Program - Sub Main(args As String()) - Const i0 As Integer = 60 - Const i1 As Integer = 60% - Const i2 As Integer = &H6F - Const i3 As Integer = &O60 - Const i4 As Integer = 60I - Const i5 As Integer = -60 - Const i6 As Integer = 0 - Const i7 As UInteger = 60UI - Const i8 As Integer = &HFFFFI - Const i9 As Integer = &O0 - Const i10 As Integer = &H0 - Const l0 As Long = 60L - Const l1 As Long = 60& - Const l2 As ULong = 60UL - Const s0 As Short = 60S - Const s1 As UShort = 60US - Const s2 As Short = &HFFFFS - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceIntegerLiteralWithLeadingZeros() + => VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + Const i0 As Integer = 0060 + Const i1 As Integer = 0060% + Const i2 As Integer = &H006F + Const i3 As Integer = &O0060 + Const i4 As Integer = 0060I + Const i5 As Integer = -0060 + Const i6 As Integer = 000 + Const i7 As UInteger = 0060UI + Const i8 As Integer = &H0000FFFFI + Const i9 As Integer = &O000 + Const i10 As Integer = &H000 + Const l0 As Long = 0060L + Const l1 As Long = 0060& + Const l2 As ULong = 0060UL + Const s0 As Short = 0060S + Const s1 As UShort = 0060US + Const s2 As Short = &H0000FFFFS + End Sub + End Module + |] + """, """ + + Module Program + Sub Main(args As String()) + Const i0 As Integer = 60 + Const i1 As Integer = 60% + Const i2 As Integer = &H6F + Const i3 As Integer = &O60 + Const i4 As Integer = 60I + Const i5 As Integer = -60 + Const i6 As Integer = 0 + Const i7 As UInteger = 60UI + Const i8 As Integer = &HFFFFI + Const i9 As Integer = &O0 + Const i10 As Integer = &H0 + Const l0 As Long = 60L + Const l1 As Long = 60& + Const l2 As ULong = 60UL + Const s0 As Short = 60S + Const s1 As UShort = 60US + Const s2 As Short = &HFFFFS + End Sub + End Module + + """); [Fact] - public async Task ReduceIntegerLiteralWithNegativeHexOrOctalValue() - { - var code = @"[| -Module Program - Sub Main(args As String()) - Const s0 As Short = &HFFFFS - Const s1 As Short = &O177777S - Const s2 As Short = &H8000S - Const s3 As Short = &O100000S - Const i0 As Integer = &O37777777777I - Const i1 As Integer = &HFFFFFFFFI - Const i2 As Integer = &H80000000I - Const i3 As Integer = &O20000000000I - Const l0 As Long = &HFFFFFFFFFFFFFFFFL - Const l1 As Long = &O1777777777777777777777L - Const l2 As Long = &H8000000000000000L - Const l2 As Long = &O1000000000000000000000L - End Sub -End Module -|]"; - - var expected = @" -Module Program - Sub Main(args As String()) - Const s0 As Short = &HFFFFS - Const s1 As Short = &O177777S - Const s2 As Short = &H8000S - Const s3 As Short = &O100000S - Const i0 As Integer = &O37777777777I - Const i1 As Integer = &HFFFFFFFFI - Const i2 As Integer = &H80000000I - Const i3 As Integer = &O20000000000I - Const l0 As Long = &HFFFFFFFFFFFFFFFFL - Const l1 As Long = &O1777777777777777777777L - Const l2 As Long = &H8000000000000000L - Const l2 As Long = &O1000000000000000000000L - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceIntegerLiteralWithNegativeHexOrOctalValue() + => VerifyAsync(""" + [| + Module Program + Sub Main(args As String()) + Const s0 As Short = &HFFFFS + Const s1 As Short = &O177777S + Const s2 As Short = &H8000S + Const s3 As Short = &O100000S + Const i0 As Integer = &O37777777777I + Const i1 As Integer = &HFFFFFFFFI + Const i2 As Integer = &H80000000I + Const i3 As Integer = &O20000000000I + Const l0 As Long = &HFFFFFFFFFFFFFFFFL + Const l1 As Long = &O1777777777777777777777L + Const l2 As Long = &H8000000000000000L + Const l2 As Long = &O1000000000000000000000L + End Sub + End Module + |] + """, """ + + Module Program + Sub Main(args As String()) + Const s0 As Short = &HFFFFS + Const s1 As Short = &O177777S + Const s2 As Short = &H8000S + Const s3 As Short = &O100000S + Const i0 As Integer = &O37777777777I + Const i1 As Integer = &HFFFFFFFFI + Const i2 As Integer = &H80000000I + Const i3 As Integer = &O20000000000I + Const l0 As Long = &HFFFFFFFFFFFFFFFFL + Const l1 As Long = &O1777777777777777777777L + Const l2 As Long = &H8000000000000000L + Const l2 As Long = &O1000000000000000000000L + End Sub + End Module + + """); [Fact] - public async Task ReduceIntegerLiteralWithOverflow() - { - var code = @"[| -Module Module1 - Sub Main() - Dim sMax As Short = 0032768S - Dim usMax As UShort = 00655536US - Dim iMax As Integer = 002147483648I - Dim uiMax As UInteger = 004294967296UI - Dim lMax As Long = 009223372036854775808L - Dim ulMax As ULong = 0018446744073709551616UL - Dim z As Long = &O37777777777777777777777 - Dim x As Long = &HFFFFFFFFFFFFFFFFF - End Sub -End Module -|]"; - - var expected = @" -Module Module1 - Sub Main() - Dim sMax As Short = 0032768S - Dim usMax As UShort = 00655536US - Dim iMax As Integer = 002147483648I - Dim uiMax As UInteger = 004294967296UI - Dim lMax As Long = 009223372036854775808L - Dim ulMax As ULong = 0018446744073709551616UL - Dim z As Long = &O37777777777777777777777 - Dim x As Long = &HFFFFFFFFFFFFFFFFF - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceIntegerLiteralWithOverflow() + => VerifyAsync(""" + [| + Module Module1 + Sub Main() + Dim sMax As Short = 0032768S + Dim usMax As UShort = 00655536US + Dim iMax As Integer = 002147483648I + Dim uiMax As UInteger = 004294967296UI + Dim lMax As Long = 009223372036854775808L + Dim ulMax As ULong = 0018446744073709551616UL + Dim z As Long = &O37777777777777777777777 + Dim x As Long = &HFFFFFFFFFFFFFFFFF + End Sub + End Module + |] + """, """ + + Module Module1 + Sub Main() + Dim sMax As Short = 0032768S + Dim usMax As UShort = 00655536US + Dim iMax As Integer = 002147483648I + Dim uiMax As UInteger = 004294967296UI + Dim lMax As Long = 009223372036854775808L + Dim ulMax As ULong = 0018446744073709551616UL + Dim z As Long = &O37777777777777777777777 + Dim x As Long = &HFFFFFFFFFFFFFFFFF + End Sub + End Module + + """); [Fact] - public async Task ReduceBinaryIntegerLiteral() - { - var code = @"[| -Module Module1 - Sub Main() - ' signed - Dim a As SByte = &B0111 - Dim b As Short = &B0101 - Dim c As Integer = &B00100100 - Dim d As Long = &B001001100110 - - ' unsigned - Dim e As Byte = &B01011 - Dim f As UShort = &B00100 - Dim g As UInteger = &B001001100110 - Dim h As ULong = &B001001100110 - - ' negative - Dim i As SByte = -&B0111 - Dim j As Short = -&B00101 - Dim k As Integer = -&B00100100 - Dim l As Long = -&B001001100110 - - ' negative literal - Dim m As SByte = &B10000001 - Dim n As Short = &B1000000000000001 - Dim o As Integer = &B10000000000000000000000000000001 - Dim p As Long = &B1000000000000000000000000000000000000000000000000000000000000001 - End Sub -End Module -|]"; - - var expected = @" -Module Module1 - Sub Main() - ' signed - Dim a As SByte = &B111 - Dim b As Short = &B101 - Dim c As Integer = &B100100 - Dim d As Long = &B1001100110 - - ' unsigned - Dim e As Byte = &B1011 - Dim f As UShort = &B100 - Dim g As UInteger = &B1001100110 - Dim h As ULong = &B1001100110 - - ' negative - Dim i As SByte = -&B111 - Dim j As Short = -&B101 - Dim k As Integer = -&B100100 - Dim l As Long = -&B1001100110 - - ' negative literal - Dim m As SByte = &B10000001 - Dim n As Short = &B1000000000000001 - Dim o As Integer = &B10000000000000000000000000000001 - Dim p As Long = &B1000000000000000000000000000000000000000000000000000000000000001 - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task ReduceBinaryIntegerLiteral() + => VerifyAsync(""" + [| + Module Module1 + Sub Main() + ' signed + Dim a As SByte = &B0111 + Dim b As Short = &B0101 + Dim c As Integer = &B00100100 + Dim d As Long = &B001001100110 + + ' unsigned + Dim e As Byte = &B01011 + Dim f As UShort = &B00100 + Dim g As UInteger = &B001001100110 + Dim h As ULong = &B001001100110 + + ' negative + Dim i As SByte = -&B0111 + Dim j As Short = -&B00101 + Dim k As Integer = -&B00100100 + Dim l As Long = -&B001001100110 + + ' negative literal + Dim m As SByte = &B10000001 + Dim n As Short = &B1000000000000001 + Dim o As Integer = &B10000000000000000000000000000001 + Dim p As Long = &B1000000000000000000000000000000000000000000000000000000000000001 + End Sub + End Module + |] + """, """ + + Module Module1 + Sub Main() + ' signed + Dim a As SByte = &B111 + Dim b As Short = &B101 + Dim c As Integer = &B100100 + Dim d As Long = &B1001100110 + + ' unsigned + Dim e As Byte = &B1011 + Dim f As UShort = &B100 + Dim g As UInteger = &B1001100110 + Dim h As ULong = &B1001100110 + + ' negative + Dim i As SByte = -&B111 + Dim j As Short = -&B101 + Dim k As Integer = -&B100100 + Dim l As Long = -&B1001100110 + + ' negative literal + Dim m As SByte = &B10000001 + Dim n As Short = &B1000000000000001 + Dim o As Integer = &B10000000000000000000000000000001 + Dim p As Long = &B1000000000000000000000000000000000000000000000000000000000000001 + End Sub + End Module + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14034")] [WorkItem("https://github.com/dotnet/roslyn/issues/48492")] public async Task DoNotReduceDigitSeparators() { - var source = @" -Module Module1 - Sub Main() - Dim x = 100_000 - Dim y = 100_000.0F - Dim z = 100_000.0D - End Sub -End Module -"; + var source = """ + + Module Module1 + Sub Main() + Dim x = 100_000 + Dim y = 100_000.0F + Dim z = 100_000.0D + End Sub + End Module + + """; var expected = source; await VerifyAsync($"[|{source}|]", expected); } diff --git a/src/Workspaces/CoreTest/CodeCleanup/RemoveUnnecessaryLineContinuationTests.cs b/src/Workspaces/CoreTest/CodeCleanup/RemoveUnnecessaryLineContinuationTests.cs index fe6d0ae8c71c9..15e4fddb5ba21 100644 --- a/src/Workspaces/CoreTest/CodeCleanup/RemoveUnnecessaryLineContinuationTests.cs +++ b/src/Workspaces/CoreTest/CodeCleanup/RemoveUnnecessaryLineContinuationTests.cs @@ -20,1404 +20,1283 @@ namespace Microsoft.CodeAnalysis.UnitTests.CodeCleanup; public sealed class RemoveUnnecessaryLineContinuationTests { [Fact] - public async Task ColonTrivia() - { - var code = @"[| - ::: Console.WriteLine("")|]"; - - var expected = @" - Console.WriteLine("")"; + public Task ColonTrivia() + => VerifyAsync(CreateMethod(""" + [| + ::: Console.WriteLine(")|] + """), CreateMethod(""" - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + Console.WriteLine(") + """)); [Fact] - public async Task ColonTrivia_EndOfLine() - { - var code = @"[| - ::: + public Task ColonTrivia_EndOfLine() + => VerifyAsync(CreateMethod(""" + [| + ::: - Console.WriteLine("")|]"; + Console.WriteLine(")|] + """), CreateMethod(""" - var expected = @" - Console.WriteLine("")"; - - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + Console.WriteLine(") + """)); [Fact] - public async Task ColonTrivia_LineContinuation() - { - var code = @"[| - ::: _ - _ - _ - Console.WriteLine("")|]"; + public Task ColonTrivia_LineContinuation() + => VerifyAsync(CreateMethod(""" + [| + ::: _ + _ + _ + Console.WriteLine(")|] + """), CreateMethod(""" - var expected = @" - Console.WriteLine("")"; - - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + Console.WriteLine(") + """)); [Fact] - public async Task ColonTrivia_LineContinuation2() - { - var code = @"[| - ::: - _ - _ - Console.WriteLine("")|]"; + public Task ColonTrivia_LineContinuation2() + => VerifyAsync(CreateMethod(""" + [| + ::: + _ + _ + Console.WriteLine(")|] + """), CreateMethod(""" - var expected = @" - Console.WriteLine("")"; - - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + Console.WriteLine(") + """)); [Fact] - public async Task ColonTrivia_LineContinuation3() - { - var code = @"[| - ::: - _ - - Console.WriteLine("")|]"; - - var expected = @" + public Task ColonTrivia_LineContinuation3() + => VerifyAsync(CreateMethod(""" + [| + ::: + _ + + Console.WriteLine(")|] + """), CreateMethod(""" - Console.WriteLine("")"; - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + Console.WriteLine(") + """)); [Fact] - public async Task ColonTrivia_LineContinuation_Comment() - { - var code = @"[| - ::: - _ - ' test - Console.WriteLine("")|]"; - - var expected = @" + public Task ColonTrivia_LineContinuation_Comment() + => VerifyAsync(CreateMethod(""" + [| + ::: + _ + ' test + Console.WriteLine(")|] + """), CreateMethod(""" - _ - ' test - Console.WriteLine("")"; - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + _ + ' test + Console.WriteLine(") + """)); [Fact] - public async Task LineContinuation() - { - var code = @"[| - Console.WriteLine("""") _ + public Task LineContinuation() + => VerifyAsync(CreateMethod(""" + [| + Console.WriteLine("") _ - Console.WriteLine("""")|]"; + Console.WriteLine("")|] + """), CreateMethod(""" - var expected = @" - Console.WriteLine("""") + Console.WriteLine("") - Console.WriteLine("""")"; - - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + Console.WriteLine("") + """)); [Fact] - public async Task LineContinuation_MultipleLines() - { - var code = @"[| - Console.WriteLine("""") _ - _ - _ - Console.WriteLine("""")|]"; - - var expected = @" - Console.WriteLine("""") _ - _ - _ - Console.WriteLine("""")"; - - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + public Task LineContinuation_MultipleLines() + => VerifyAsync(CreateMethod(""" + [| + Console.WriteLine("") _ + _ + _ + Console.WriteLine("")|] + """), CreateMethod(""" + + Console.WriteLine("") _ + _ + _ + Console.WriteLine("") + """)); [Fact] - public async Task LineContinuation_MultipleLines2() - { - var code = @"[| - Console.WriteLine("""") _ - _ - _ + public Task LineContinuation_MultipleLines2() + => VerifyAsync(CreateMethod(""" + [| + Console.WriteLine("") _ + _ + _ - Console.WriteLine("""")|]"; + Console.WriteLine("")|] + """), CreateMethod(""" - var expected = @" - Console.WriteLine("""") + Console.WriteLine("") - Console.WriteLine("""")"; - - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + Console.WriteLine("") + """)); [Fact] - public async Task LineContinuation_Invalid() - { - var code = @"[| - Console.WriteLine() _ _ - ' test - : ' test - _ - Console.WriteLine()|]"; - - var expected = @" - Console.WriteLine() _ _ - ' test - ' test - _ - Console.WriteLine()"; - - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + public Task LineContinuation_Invalid() + => VerifyAsync(CreateMethod(""" + [| + Console.WriteLine() _ _ + ' test + : ' test + _ + Console.WriteLine()|] + """), CreateMethod(""" + + Console.WriteLine() _ _ + ' test + ' test + _ + Console.WriteLine() + """)); [Fact] - public async Task ColonToken_SingleLine() - { - var code = @"[| - Console.WriteLine() : Console.WriteLine()|]"; + public Task ColonToken_SingleLine() + => VerifyAsync(CreateMethod(""" + [| + Console.WriteLine() : Console.WriteLine()|] + """), CreateMethod(""" - var expected = @" - Console.WriteLine() : Console.WriteLine()"; - - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + Console.WriteLine() : Console.WriteLine() + """)); [Fact] - public async Task ColonToken_SingleLine_MultipleColon() - { - var code = @"[| - Console.WriteLine() :::: Console.WriteLine()|]"; - - var expected = @" - Console.WriteLine() : Console.WriteLine()"; + public Task ColonToken_SingleLine_MultipleColon() + => VerifyAsync(CreateMethod(""" + [| + Console.WriteLine() :::: Console.WriteLine()|] + """), CreateMethod(""" - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + Console.WriteLine() : Console.WriteLine() + """)); [Fact] - public async Task ColonToken_SingleLine_SkippedTokens() - { - var code = @"[| - Console.WriteLine() _ : Console.WriteLine()|]"; + public Task ColonToken_SingleLine_SkippedTokens() + => VerifyAsync(CreateMethod(""" + [| + Console.WriteLine() _ : Console.WriteLine()|] + """), CreateMethod(""" - var expected = @" - Console.WriteLine() _ : Console.WriteLine()"; - - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + Console.WriteLine() _ : Console.WriteLine() + """)); [Fact] - public async Task ColonToken_LineContinuation_BeforeColonToken() - { - var code = @"[| - Console.WriteLine() _ - : Console.WriteLine()|]"; - - var expected = @" - Console.WriteLine() - Console.WriteLine()"; + public Task ColonToken_LineContinuation_BeforeColonToken() + => VerifyAsync(CreateMethod(""" + [| + Console.WriteLine() _ + : Console.WriteLine()|] + """), CreateMethod(""" - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + Console.WriteLine() + Console.WriteLine() + """)); [Fact] - public async Task ColonToken_LineContinuation_BeforeColonToken2() - { - var code = @"[| - Console.WriteLine() _ _ - : Console.WriteLine()|]"; + public Task ColonToken_LineContinuation_BeforeColonToken2() + => VerifyAsync(CreateMethod(""" + [| + Console.WriteLine() _ _ + : Console.WriteLine()|] + """), CreateMethod(""" - var expected = @" - Console.WriteLine() _ _ - Console.WriteLine()"; - - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + Console.WriteLine() _ _ + Console.WriteLine() + """)); [Fact] - public async Task ColonToken_LineContinuation_Comment_BeforeColonToken() - { - var code = @"[| - Console.WriteLine() _ ' test - : Console.WriteLine()|]"; - - var expected = @" - Console.WriteLine() _ ' test - Console.WriteLine()"; - await VerifyAsync(CreateMethod(code), CreateMethod(expected), LanguageVersion.VisualBasic15); - } + public Task ColonToken_LineContinuation_Comment_BeforeColonToken() + => VerifyAsync(CreateMethod(""" + [| + Console.WriteLine() _ ' test + : Console.WriteLine()|] + """), CreateMethod(""" - [Fact] - public async Task ColonToken_LineContinuation_Comment_BeforeColonTokenV16() - { - var code = @"[| - Console.WriteLine() _ ' test - : Console.WriteLine()|]"; - - var expected = @" - Console.WriteLine() _ ' test - Console.WriteLine()"; - await VerifyAsync(CreateMethod(code), CreateMethod(expected), LanguageVersion.VisualBasic16); - } + Console.WriteLine() _ ' test + Console.WriteLine() + """), LanguageVersion.VisualBasic15); [Fact] - public async Task ColonToken_MultipleLine() - { - var code = @"[| - Console.WriteLine() : - Console.WriteLine()|]"; - - var expected = @" - Console.WriteLine() - Console.WriteLine()"; + public Task ColonToken_LineContinuation_Comment_BeforeColonTokenV16() + => VerifyAsync(CreateMethod(""" + [| + Console.WriteLine() _ ' test + : Console.WriteLine()|] + """), CreateMethod(""" - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + Console.WriteLine() _ ' test + Console.WriteLine() + """), LanguageVersion.VisualBasic16); [Fact] - public async Task ColonToken_LineContinuation_AfterColonToken() - { - var code = @"[| - Console.WriteLine() : _ - Console.WriteLine()|]"; - - var expected = @" - Console.WriteLine() - Console.WriteLine()"; + public Task ColonToken_MultipleLine() + => VerifyAsync(CreateMethod(""" + [| + Console.WriteLine() : + Console.WriteLine()|] + """), CreateMethod(""" - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + Console.WriteLine() + Console.WriteLine() + """)); [Fact] - public async Task ColonToken_LineContinuation_AfterColonToken2() - { - var code = @"[| - Console.WriteLine() : _ - _ - Console.WriteLine()|]"; + public Task ColonToken_LineContinuation_AfterColonToken() + => VerifyAsync(CreateMethod(""" + [| + Console.WriteLine() : _ + Console.WriteLine()|] + """), CreateMethod(""" - var expected = @" - Console.WriteLine() + Console.WriteLine() + Console.WriteLine() + """)); - Console.WriteLine()"; + [Fact] + public Task ColonToken_LineContinuation_AfterColonToken2() + => VerifyAsync(CreateMethod(""" + [| + Console.WriteLine() : _ + _ + Console.WriteLine()|] + """), CreateMethod(""" - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + Console.WriteLine() + + Console.WriteLine() + """)); [Fact] - public async Task ColonToken_LineContinuation_AfterColonToken_MultipleLine() - { - var code = @"[| - Console.WriteLine() : _ - _ - _|]"; + public Task ColonToken_LineContinuation_AfterColonToken_MultipleLine() + => VerifyAsync(CreateMethod(""" + [| + Console.WriteLine() : _ + _ + _|] + """), CreateMethod(""" - var expected = @" - Console.WriteLine() + Console.WriteLine() -"; - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + """)); [Fact] - public async Task ColonToken_LineContinuation_AfterColonToken_Mixed() - { - var code = @"[| - Console.WriteLine() : _ - _ - : - _ - Console.WriteLine()|]"; - - var expected = @" - Console.WriteLine() + public Task ColonToken_LineContinuation_AfterColonToken_Mixed() + => VerifyAsync(CreateMethod(""" + [| + Console.WriteLine() : _ + _ + : + _ + Console.WriteLine()|] + """), CreateMethod(""" + Console.WriteLine() - Console.WriteLine()"; - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + Console.WriteLine() + """)); [Fact] - public async Task ColonToken_LineContinuation_AfterColonToken_Colon_Comment() - { - var code = @"[| - Console.WriteLine() : _ - _ - : ' test - _ - Console.WriteLine()|]"; - - var expected = @" - Console.WriteLine() _ - _ - ' test - _ - Console.WriteLine()"; - - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + public Task ColonToken_LineContinuation_AfterColonToken_Colon_Comment() + => VerifyAsync(CreateMethod(""" + [| + Console.WriteLine() : _ + _ + : ' test + _ + Console.WriteLine()|] + """), CreateMethod(""" + + Console.WriteLine() _ + _ + ' test + _ + Console.WriteLine() + """)); [Fact] - public async Task ColonToken_LineContinuation_Mix() - { - var code = @"[| - Console.WriteLine() _ : _ - _ - : ' test - _ - Console.WriteLine()|]"; - - var expected = @" - Console.WriteLine() _ _ - _ - ' test - _ - Console.WriteLine()"; - - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + public Task ColonToken_LineContinuation_Mix() + => VerifyAsync(CreateMethod(""" + [| + Console.WriteLine() _ : _ + _ + : ' test + _ + Console.WriteLine()|] + """), CreateMethod(""" + + Console.WriteLine() _ _ + _ + ' test + _ + Console.WriteLine() + """)); [Fact] - public async Task ColonToken_If() - { - var code = @"[| - If True Then : - End If|]"; + public Task ColonToken_If() + => VerifyAsync(CreateMethod(""" + [| + If True Then : + End If|] + """), CreateMethod(""" - var expected = @" - If True Then - End If"; - - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + If True Then + End If + """)); [Fact] - public async Task ImplicitLineContinuation() - { - var code = @"[| - Dim i = _ - 1 + _ - 2|]"; - - var expected = @" - Dim i = - 1 + - 2"; - - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + public Task ImplicitLineContinuation() + => VerifyAsync(CreateMethod(""" + [| + Dim i = _ + 1 + _ + 2|] + """), CreateMethod(""" + + Dim i = + 1 + + 2 + """)); [Fact] - public async Task ImplicitLineContinuation_Multiple() - { - var code = @"[| - Dim i = _ - _ - 1 + _ - 2|]"; - - var expected = @" - Dim i = _ - _ - 1 + - 2"; - - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + public Task ImplicitLineContinuation_Multiple() + => VerifyAsync(CreateMethod(""" + [| + Dim i = _ + _ + 1 + _ + 2|] + """), CreateMethod(""" + + Dim i = _ + _ + 1 + + 2 + """)); [Fact] - public async Task LineContinuation_Mix() - { - var code = @"[|Class _ - A - Inherits _ - System _ - . _ - Object - - Public _ - Function _ - Method _ - ( _ - i _ - As _ - Integer _ - , _ - i2 _ - As _ - String _ - ) _ - As _ - Integer - - If _ - i _ - + _ - i2 _ + public Task LineContinuation_Mix() + => VerifyAsync(""" + [|Class _ + A + Inherits _ + System _ . _ - Length _ - = _ - 1 _ - Then - Console _ - . _ - WriteLine _ - ( _ - vbCrLf _ - ) - End _ - If - - Return _ - 1 - End _ - Function -End _ - Class|]"; - - var expected = @"Class _ - A - Inherits _ - System _ - . - Object - - Public _ - Function _ - Method _ - ( - i _ - As _ - Integer _ - , - i2 _ - As _ - String - ) _ - As _ - Integer - - If _ - i _ - + - i2 _ + Object + + Public _ + Function _ + Method _ + ( _ + i _ + As _ + Integer _ + , _ + i2 _ + As _ + String _ + ) _ + As _ + Integer + + If _ + i _ + + _ + i2 _ + . _ + Length _ + = _ + 1 _ + Then + Console _ + . _ + WriteLine _ + ( _ + vbCrLf _ + ) + End _ + If + + Return _ + 1 + End _ + Function + End _ + Class|] + """, """ + Class _ + A + Inherits _ + System _ . - Length _ - = - 1 _ - Then - Console _ - . - WriteLine _ - ( - vbCrLf - ) - End _ - If - - Return _ - 1 - End _ - Function -End _ - Class"; - - await VerifyAsync(code, expected); - } + Object + + Public _ + Function _ + Method _ + ( + i _ + As _ + Integer _ + , + i2 _ + As _ + String + ) _ + As _ + Integer + + If _ + i _ + + + i2 _ + . + Length _ + = + 1 _ + Then + Console _ + . + WriteLine _ + ( + vbCrLf + ) + End _ + If + + Return _ + 1 + End _ + Function + End _ + Class + """); [Fact] - public async Task ImplicitLineContinuation_Invalid() - { - var code = @"[| - Dim i = _ _ - _ _ - 1 + _ _ - 2|]"; - - var expected = @" - Dim i = _ _ - _ _ - 1 + _ _ - 2"; - - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + public Task ImplicitLineContinuation_Invalid() + => VerifyAsync(CreateMethod(""" + [| + Dim i = _ _ + _ _ + 1 + _ _ + 2|] + """), CreateMethod(""" + + Dim i = _ _ + _ _ + 1 + _ _ + 2 + """)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544470")] - public async Task AttributeTargetColon() - { - var code = @"[||]"; - - var expected = @""; - - await VerifyAsync(code, expected); - } + public Task AttributeTargetColon() + => VerifyAsync(""" + [||] + """, """ + + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529428")] - public async Task LineContinuationInImport() - { - var code = @"[|Imports System _ - -|]"; + public Task LineContinuationInImport() + => VerifyAsync(""" + [|Imports System _ - var expected = @"Imports System + |] + """, """ + Imports System -"; - await VerifyAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529425")] - public async Task ColonInOption() - { - var code = @"[|Option Infer On :: Option Explicit Off|]"; - - var expected = @"Option Infer On : Option Explicit Off"; - - await VerifyAsync(code, expected); - } + public Task ColonInOption() + => VerifyAsync(@"[|Option Infer On :: Option Explicit Off|]", @"Option Infer On : Option Explicit Off"); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544524")] - public async Task LineContinuationInNamedFieldInitializer() - { - var code = @"[|Class C - Sub S() - Dim o = New With - { - . _ - a = 2 - } - End Sub -End Class|]"; - - var expected = @"Class C - Sub S() - Dim o = New With - { - . _ - a = 2 - } - End Sub -End Class"; - - await VerifyAsync(code, expected); - } + public Task LineContinuationInNamedFieldInitializer() + => VerifyAsync(""" + [|Class C + Sub S() + Dim o = New With + { + . _ + a = 2 + } + End Sub + End Class|] + """, """ + Class C + Sub S() + Dim o = New With + { + . _ + a = 2 + } + End Sub + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544523")] - public async Task IfPart_Colon1() - { - var code = @"[|Module M - Sub S() - If True Then - : Return : End If - End Sub -End Module|]"; - - var expected = @"Module M - Sub S() - If True Then - Return : End If - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task IfPart_Colon1() + => VerifyAsync(""" + [|Module M + Sub S() + If True Then + : Return : End If + End Sub + End Module|] + """, """ + Module M + Sub S() + If True Then + Return : End If + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544523")] - public async Task IfPart_Colon2() - { - var code = @"[|Module M - Sub S() - If True Then : - Return : End If - End Sub -End Module|]"; - - var expected = @"Module M - Sub S() - If True Then - Return : End If - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task IfPart_Colon2() + => VerifyAsync(""" + [|Module M + Sub S() + If True Then : + Return : End If + End Sub + End Module|] + """, """ + Module M + Sub S() + If True Then + Return : End If + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544523")] - public async Task IfPart_Colon3() - { - var code = @"[|Module M - Sub S() - If True Then : Return - : End If - End Sub -End Module|]"; - - var expected = @"Module M - Sub S() - If True Then : Return - End If - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task IfPart_Colon3() + => VerifyAsync(""" + [|Module M + Sub S() + If True Then : Return + : End If + End Sub + End Module|] + """, """ + Module M + Sub S() + If True Then : Return + End If + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544523")] - public async Task IfPart_Colon4() - { - var code = @"[|Module M - Sub S() - If True Then : Return : - End If - End Sub -End Module|]"; - - var expected = @"Module M - Sub S() - If True Then : Return - End If - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task IfPart_Colon4() + => VerifyAsync(""" + [|Module M + Sub S() + If True Then : Return : + End If + End Sub + End Module|] + """, """ + Module M + Sub S() + If True Then : Return + End If + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544521")] - public async Task LabelColon() - { - var code = @"[|Module Program - Sub S() - L: - End Sub -End Module|]"; - - var expected = @"Module Program - Sub S() -L: - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task LabelColon() + => VerifyAsync(""" + [|Module Program + Sub S() + L: + End Sub + End Module|] + """, """ + Module Program + Sub S() + L: + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544521")] - public async Task LabelColon_ColonTrivia() - { - var code = @"[|Module Program - Sub S() - L::::::::: - End Sub -End Module|]"; - - var expected = @"Module Program - Sub S() -L: - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task LabelColon_ColonTrivia() + => VerifyAsync(""" + [|Module Program + Sub S() + L::::::::: + End Sub + End Module|] + """, """ + Module Program + Sub S() + L: + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544520")] - public async Task LineContinuation_MixedWithImplicitLineContinuation() - { - var code = @"[|Module Program - Sub Main( - _ - args _ - As String) - End Sub -End Module|]"; - - var expected = @"Module Program - Sub Main( + public Task LineContinuation_MixedWithImplicitLineContinuation() + => VerifyAsync(""" + [|Module Program + Sub Main( _ - args _ - As String) - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + args _ + As String) + End Sub + End Module|] + """, """ + Module Program + Sub Main( + _ + args _ + As String) + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544549")] - public async Task ColonTrivia_EndOfFile() - { - var code = @"[|::::::: -|]"; + public Task ColonTrivia_EndOfFile() + => VerifyAsync(""" + [|::::::: + |] + """, """ - var expected = @" -"; - await VerifyAsync(code, expected); - } + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545538")] - public async Task ColonTriviaBeforeCommentTrivia() - { - var code = @"[|Module M - Sub Main() - Dim b = .@x : ' - End Sub -End Module|]"; - - var expected = @"Module M - Sub Main() - Dim b = .@x ' - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task ColonTriviaBeforeCommentTrivia() + => VerifyAsync(""" + [|Module M + Sub Main() + Dim b = .@x : ' + End Sub + End Module|] + """, """ + Module M + Sub Main() + Dim b = .@x ' + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545540")] - public async Task InsideWithStatementWithMemberCall() - { - var code = @"[|Module Program - Sub Main() - With "" - Dim y = From x In "" Distinct - : .ToLower() - End With - End Sub -End Module|]"; - - var expected = @"Module Program - Sub Main() - With "" - Dim y = From x In "" Distinct - : .ToLower() - End With - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task InsideWithStatementWithMemberCall() + => VerifyAsync(""" + [|Module Program + Sub Main() + With " + Dim y = From x In " Distinct + : .ToLower() + End With + End Sub + End Module|] + """, """ + Module Program + Sub Main() + With " + Dim y = From x In " Distinct + : .ToLower() + End With + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545540")] - public async Task InsideWithStatementWithMemberCall2() - { - var code = @"[|Module Program - Sub Main() - With "" - Dim y = From x In """" Distinct : - .ToLower() - End With - End Sub -End Module|]"; - - var expected = @"Module Program - Sub Main() - With "" - Dim y = From x In """" Distinct : - .ToLower() - End With - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task InsideWithStatementWithMemberCall2() + => VerifyAsync(""" + [|Module Program + Sub Main() + With " + Dim y = From x In "" Distinct : + .ToLower() + End With + End Sub + End Module|] + """, """ + Module Program + Sub Main() + With " + Dim y = From x In "" Distinct : + .ToLower() + End With + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545540")] - public async Task InsideWithStatementWithMemberCall3() - { - var code = @"[|Module Program - Sub Main() - With "" - .ToLower() - : .ToLower() - End With - End Sub -End Module|]"; - - var expected = @"Module Program - Sub Main() - With "" - .ToLower() - : .ToLower() - End With - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task InsideWithStatementWithMemberCall3() + => VerifyAsync(""" + [|Module Program + Sub Main() + With " + .ToLower() + : .ToLower() + End With + End Sub + End Module|] + """, """ + Module Program + Sub Main() + With " + .ToLower() + : .ToLower() + End With + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545540")] - public async Task InsideWithStatementWithMemberCall4() - { - var code = @"[|Module Program - Sub Main() - With """" - .ToLower() : - .ToLower() - End With - End Sub -End Module|]"; - - var expected = @"Module Program - Sub Main() - With """" - .ToLower() - .ToLower() - End With - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task InsideWithStatementWithMemberCall4() + => VerifyAsync(""" + [|Module Program + Sub Main() + With "" + .ToLower() : + .ToLower() + End With + End Sub + End Module|] + """, """ + Module Program + Sub Main() + With "" + .ToLower() + .ToLower() + End With + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/607791")] - public async Task InsideWithStatementWithDictionaryAccess() - { - var code = @"[|Imports System.Collections -Module Program - Sub Main() - With New Hashtable - Dim x = From c In """" Distinct - :!A = !B - End With - End Sub -End Module -|]"; - - var expected = @"Imports System.Collections -Module Program - Sub Main() - With New Hashtable - Dim x = From c In """" Distinct - : !A = !B - End With - End Sub -End Module -"; - - await VerifyAsync(code, expected); - } + public Task InsideWithStatementWithDictionaryAccess() + => VerifyAsync(""" + [|Imports System.Collections + Module Program + Sub Main() + With New Hashtable + Dim x = From c In "" Distinct + :!A = !B + End With + End Sub + End Module + |] + """, """ + Imports System.Collections + Module Program + Sub Main() + With New Hashtable + Dim x = From c In "" Distinct + : !A = !B + End With + End Sub + End Module + + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/607791")] - public async Task InsideWithStatementWithDictionaryAccess2() - { - var code = @"[|Imports System.Collections -Module Program - Sub Main() - With New Hashtable - Dim x = From c In """" Distinct : - !A = !B - End With - End Sub -End Module|]"; - - var expected = @"Imports System.Collections -Module Program - Sub Main() - With New Hashtable - Dim x = From c In """" Distinct : - !A = !B - End With - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task InsideWithStatementWithDictionaryAccess2() + => VerifyAsync(""" + [|Imports System.Collections + Module Program + Sub Main() + With New Hashtable + Dim x = From c In "" Distinct : + !A = !B + End With + End Sub + End Module|] + """, """ + Imports System.Collections + Module Program + Sub Main() + With New Hashtable + Dim x = From c In "" Distinct : + !A = !B + End With + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529821")] - public async Task InsideObjectInitializer() - { - var code = @"[|Imports System.Runtime.CompilerServices - -Module Program - Sub Main() - Dim s = New StrongBox(Of Object) With { - .Value = Sub() - Dim y = From x In "" Distinct - : .Value.ToString() - End Sub} - End Sub -End Module|]"; - - var expected = @"Imports System.Runtime.CompilerServices - -Module Program - Sub Main() - Dim s = New StrongBox(Of Object) With { - .Value = Sub() - Dim y = From x In "" Distinct - : .Value.ToString() - End Sub} - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task InsideObjectInitializer() + => VerifyAsync(""" + [|Imports System.Runtime.CompilerServices + + Module Program + Sub Main() + Dim s = New StrongBox(Of Object) With { + .Value = Sub() + Dim y = From x In " Distinct + : .Value.ToString() + End Sub} + End Sub + End Module|] + """, """ + Imports System.Runtime.CompilerServices + + Module Program + Sub Main() + Dim s = New StrongBox(Of Object) With { + .Value = Sub() + Dim y = From x In " Distinct + : .Value.ToString() + End Sub} + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545545")] - public async Task LineContinuationBetweenXmlAndDot() - { - var code = @"[|Module Program - Sub Main() - Dim y = _ - .ToString() - End Sub -End Module|]"; - - var expected = @"Module Program - Sub Main() - Dim y = _ - .ToString() - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task LineContinuationBetweenXmlAndDot() + => VerifyAsync(""" + [|Module Program + Sub Main() + Dim y = _ + .ToString() + End Sub + End Module|] + """, """ + Module Program + Sub Main() + Dim y = _ + .ToString() + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545545")] - public async Task LineContinuationBetweenXmlAndDot1() - { - var code = @"[|Module Program - Sub Main() - Dim x = .. _ - . - End Sub -End Module|]"; - - var expected = @"Module Program - Sub Main() - Dim x = .. _ - . - End Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task LineContinuationBetweenXmlAndDot1() + => VerifyAsync(""" + [|Module Program + Sub Main() + Dim x = .. _ + . + End Sub + End Module|] + """, """ + Module Program + Sub Main() + Dim x = .. _ + . + End Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545565")] - public async Task LineContinuationBeforeFromQueryExpression() - { - var code = @"[|Class C - Sub Main() - Call _ - From x In """" Distinct.ToString() - End Sub -End Class|]"; - - var expected = @"Class C - Sub Main() - Call _ - From x In """" Distinct.ToString() - End Sub -End Class"; - - await VerifyAsync(code, expected); - } + public Task LineContinuationBeforeFromQueryExpression() + => VerifyAsync(""" + [|Class C + Sub Main() + Call _ + From x In "" Distinct.ToString() + End Sub + End Class|] + """, """ + Class C + Sub Main() + Call _ + From x In "" Distinct.ToString() + End Sub + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545565")] - public async Task LineContinuationBeforeFromAggregateExpression() - { - var code = @"[|Class C - Sub Main() - Call _ - Aggregate x In {1} Into Count().ToString() - End Sub -End Class|]"; - - var expected = @"Class C - Sub Main() - Call _ - Aggregate x In {1} Into Count().ToString() - End Sub -End Class"; - - await VerifyAsync(code, expected); - } + public Task LineContinuationBeforeFromAggregateExpression() + => VerifyAsync(""" + [|Class C + Sub Main() + Call _ + Aggregate x In {1} Into Count().ToString() + End Sub + End Class|] + """, """ + Class C + Sub Main() + Call _ + Aggregate x In {1} Into Count().ToString() + End Sub + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530635")] - public async Task LineContinuationAtEndOfLambdaExpression1() - { - var code = @"[|Interface I - Property A As Action -End Interface - -Class C - Implements I - Property A As Action = Sub() Return _ - Implements I.A -End Class|]"; - - var expected = @"Interface I - Property A As Action -End Interface - -Class C - Implements I - Property A As Action = Sub() Return _ - Implements I.A -End Class"; - - await VerifyAsync(code, expected); - } + public Task LineContinuationAtEndOfLambdaExpression1() + => VerifyAsync(""" + [|Interface I + Property A As Action + End Interface + + Class C + Implements I + Property A As Action = Sub() Return _ + Implements I.A + End Class|] + """, """ + Interface I + Property A As Action + End Interface + + Class C + Implements I + Property A As Action = Sub() Return _ + Implements I.A + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530635")] - public async Task LineContinuationAtEndOfLambdaExpression2() - { - var code = @"[|Interface I - Property A As Action -End Interface - -Class C - Implements I - Property A As Action = Sub() - Return - End Sub _ - Implements I.A -End Class|]"; - - var expected = @"Interface I - Property A As Action -End Interface - -Class C - Implements I - Property A As Action = Sub() - Return - End Sub _ - Implements I.A -End Class"; - - await VerifyAsync(code, expected); - } + public Task LineContinuationAtEndOfLambdaExpression2() + => VerifyAsync(""" + [|Interface I + Property A As Action + End Interface + + Class C + Implements I + Property A As Action = Sub() + Return + End Sub _ + Implements I.A + End Class|] + """, """ + Interface I + Property A As Action + End Interface + + Class C + Implements I + Property A As Action = Sub() + Return + End Sub _ + Implements I.A + End Class + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546798")] - public async Task LineContinuationAfterDot() - { - var code = @"[| - System.Diagnostics. _ - Debug.Assert(True)|]"; + public Task LineContinuationAfterDot() + => VerifyAsync(CreateMethod(""" + [| + System.Diagnostics. _ + Debug.Assert(True)|] + """), CreateMethod(""" - var expected = @" - System.Diagnostics. - Debug.Assert(True)"; - - await VerifyAsync(CreateMethod(code), CreateMethod(expected)); - } + System.Diagnostics. + Debug.Assert(True) + """)); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530621")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/631933")] - public async Task DoNotRemoveLineContinuationAfterColonInSingleLineIfStatement() - { - var code = @"[|Module Program - Dim x = Sub() If True Then Dim y : _ - Exit Sub -End Module|]"; - - var expected = @"Module Program - Dim x = Sub() If True Then Dim y : _ - Exit Sub -End Module"; - - await VerifyAsync(code, expected); - } + public Task DoNotRemoveLineContinuationAfterColonInSingleLineIfStatement() + => VerifyAsync(""" + [|Module Program + Dim x = Sub() If True Then Dim y : _ + Exit Sub + End Module|] + """, """ + Module Program + Dim x = Sub() If True Then Dim y : _ + Exit Sub + End Module + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609481")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/631933")] - public async Task DoNotRemoveLineContinuationInSingleLineIfStatement() - { - var code = @"[| -Module Program - Sub Main() - ' Single Line If with explicit line continuations - If True Then _ - Return _ - Else _ - Return - End Sub -End Module -|]"; - - var expected = @" -Module Program - Sub Main() - ' Single Line If with explicit line continuations - If True Then _ - Return _ - Else _ - Return - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task DoNotRemoveLineContinuationInSingleLineIfStatement() + => VerifyAsync(""" + [| + Module Program + Sub Main() + ' Single Line If with explicit line continuations + If True Then _ + Return _ + Else _ + Return + End Sub + End Module + |] + """, """ + + Module Program + Sub Main() + ' Single Line If with explicit line continuations + If True Then _ + Return _ + Else _ + Return + End Sub + End Module + + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609481")] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/631933")] - public async Task DoNotRemoveLineContinuationInNestedSingleLineIfStatement() - { - var code = @"[| -Module Program - Sub Main() - ' Nested Single Line If with explicit line continuations - If True Then _ - If True Then _ - Return _ - Else _ - Return _ - Else _ - Return - - If True Then _ - If True Then _ - Return _ - Else _ - Return _ - Else _ - If True Then _ - Return _ - Else Return - - End Sub -End Module -|]"; - - var expected = @" -Module Program - Sub Main() - ' Nested Single Line If with explicit line continuations - If True Then _ - If True Then _ - Return _ - Else _ - Return _ - Else _ - Return - - If True Then _ - If True Then _ - Return _ - Else _ - Return _ - Else _ - If True Then _ - Return _ - Else Return - - End Sub -End Module -"; - await VerifyAsync(code, expected); - } + public Task DoNotRemoveLineContinuationInNestedSingleLineIfStatement() + => VerifyAsync(""" + [| + Module Program + Sub Main() + ' Nested Single Line If with explicit line continuations + If True Then _ + If True Then _ + Return _ + Else _ + Return _ + Else _ + Return + + If True Then _ + If True Then _ + Return _ + Else _ + Return _ + Else _ + If True Then _ + Return _ + Else Return + + End Sub + End Module + |] + """, """ + + Module Program + Sub Main() + ' Nested Single Line If with explicit line continuations + If True Then _ + If True Then _ + Return _ + Else _ + Return _ + Else _ + Return + + If True Then _ + If True Then _ + Return _ + Else _ + Return _ + Else _ + If True Then _ + Return _ + Else Return + + End Sub + End Module + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/710")] - public async Task DoNotRemoveLineContinuationInStringInterpolation1() - { - var code = @"[| -Module Program - Dim x = $""{ _ - 1}"" -End Module -|]"; - - var expected = @" -Module Program - Dim x = $""{ _ - 1}"" -End Module -"; - await VerifyAsync(code, expected); - } + public Task DoNotRemoveLineContinuationInStringInterpolation1() + => VerifyAsync(""" + [| + Module Program + Dim x = $"{ _ + 1}" + End Module + |] + """, """ + + Module Program + Dim x = $"{ _ + 1}" + End Module + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/710")] - public async Task DoNotRemoveLineContinuationInStringInterpolation2() - { - var code = @"[| -Module Program - Dim x = $""{1 _ - }"" -End Module -|]"; - - var expected = @" -Module Program - Dim x = $""{1 _ - }"" -End Module -"; - await VerifyAsync(code, expected); - } + public Task DoNotRemoveLineContinuationInStringInterpolation2() + => VerifyAsync(""" + [| + Module Program + Dim x = $"{1 _ + }" + End Module + |] + """, """ + + Module Program + Dim x = $"{1 _ + }" + End Module + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/710")] - public async Task DoNotRemoveLineContinuationInStringInterpolation3() - { - var code = @"[| -Module Program - Dim x = $""{ _ + public Task DoNotRemoveLineContinuationInStringInterpolation3() + => VerifyAsync(""" + [| + Module Program + Dim x = $"{ _ -1 _ + 1 _ -}"" -End Module -|]"; + }" + End Module + |] + """, """ - var expected = @" -Module Program - Dim x = $""{ _ + Module Program + Dim x = $"{ _ -1 _ + 1 _ -}"" -End Module -"; - await VerifyAsync(code, expected); - } + }" + End Module + + """); [Theory] [InlineData("_")] [InlineData("_ ' Comment")] [WorkItem("https://github.com/dotnet/roslyn/issues/69696")] - public async Task LineContinuationInString1(string continuation) - { - var code = $@"[| -Module Program - Dim x = ""1"" {continuation} - & ""2"" {continuation} - & ""3"" -End Module -|]"; - - var expected = $@" -Module Program - Dim x = ""1"" {continuation} - & ""2"" {continuation} - & ""3"" -End Module -"; - await VerifyAsync(code, expected); - } + public Task LineContinuationInString1(string continuation) + => VerifyAsync($""" + [| + Module Program + Dim x = "1" {continuation} + & "2" {continuation} + & "3" + End Module + |] + """, $""" + + Module Program + Dim x = "1" {continuation} + & "2" {continuation} + & "3" + End Module + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69696")] - public async Task LineContinuationInString2() - { - var code = $@"[| -Module Program - Dim x = ""1"" & _ - ""2"" & _ - ""3"" -End Module -|]"; - - var expected = $@" -Module Program - Dim x = ""1"" & - ""2"" & - ""3"" -End Module -"; - await VerifyAsync(code, expected); - } + public Task LineContinuationInString2() + => VerifyAsync($""" + [| + Module Program + Dim x = "1" & _ + "2" & _ + "3" + End Module + |] + """, $""" + + Module Program + Dim x = "1" & + "2" & + "3" + End Module + + """); [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69696")] - public async Task LineContinuationInString3() - { - var code = $@"[| -Module Program - Dim x = ""1"" & ' Comment - ""2"" & ' Comment - ""3"" -End Module -|]"; - - var expected = $@" -Module Program - Dim x = ""1"" & ' Comment - ""2"" & ' Comment - ""3"" -End Module -"; - await VerifyAsync(code, expected); - } + public Task LineContinuationInString3() + => VerifyAsync($""" + [| + Module Program + Dim x = "1" & ' Comment + "2" & ' Comment + "3" + End Module + |] + """, $""" + + Module Program + Dim x = "1" & ' Comment + "2" & ' Comment + "3" + End Module + + """); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1085887")] - public async Task DoNotRemoveLineContinuationInVisualBasic9() - { - var code = @"[| -Module Program - Function Add( _ - i As Integer, _ - j As Integer, _ - ) As Integer - - Return i + j - End Function -End Module -|]"; - - var expected = @" -Module Program - Function Add( _ - i As Integer, _ - j As Integer, _ - ) As Integer - - Return i + j - End Function -End Module -"; - await VerifyAsync(code, expected, langVersion: LanguageVersion.VisualBasic9); - } + public Task DoNotRemoveLineContinuationInVisualBasic9() + => VerifyAsync(""" + [| + Module Program + Function Add( _ + i As Integer, _ + j As Integer, _ + ) As Integer + + Return i + j + End Function + End Module + |] + """, """ + + Module Program + Function Add( _ + i As Integer, _ + j As Integer, _ + ) As Integer + + Return i + j + End Function + End Module + + """, langVersion: LanguageVersion.VisualBasic9); [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1085887")] public async Task RemoveLineContinuationInVisualBasic10_11_12_And_14() { - var code = @"[| -Module Program - Function Add( _ - i As Integer, _ - j As Integer, _ - ) As Integer - - Return i + j - End Function -End Module -|]"; - - var expected = @" -Module Program - Function Add( - i As Integer, - j As Integer, - ) As Integer - - Return i + j - End Function -End Module -"; + var code = """ + [| + Module Program + Function Add( _ + i As Integer, _ + j As Integer, _ + ) As Integer + + Return i + j + End Function + End Module + |] + """; + + var expected = """ + + Module Program + Function Add( + i As Integer, + j As Integer, + ) As Integer + + Return i + j + End Function + End Module + + """; await VerifyAsync(code, expected, langVersion: LanguageVersion.VisualBasic10); await VerifyAsync(code, expected, langVersion: LanguageVersion.VisualBasic11); @@ -1427,11 +1306,15 @@ End Module private static string CreateMethod(string body) { - return @"Imports System -Class C - Public Sub Method()" + body + @" - End Sub -End Class"; + return """ + Imports System + Class C + Public Sub Method() + """ + body + """ + + End Sub + End Class + """; } private static async Task VerifyAsync(string codeWithMarker, string expectedResult, LanguageVersion langVersion = LanguageVersion.VisualBasic14) diff --git a/src/Workspaces/CoreTest/CommandLineProject/CommandLineProjectTests.cs b/src/Workspaces/CoreTest/CommandLineProject/CommandLineProjectTests.cs index 328f526bdc9d8..b688c683439ef 100644 --- a/src/Workspaces/CoreTest/CommandLineProject/CommandLineProjectTests.cs +++ b/src/Workspaces/CoreTest/CommandLineProject/CommandLineProjectTests.cs @@ -44,9 +44,8 @@ public void TestCreateWithoutRequiredServices() [Fact] public void TestCreateWithRequiredServices() { - var commandLine = @"goo.cs"; var ws = new AdhocWorkspace(); - _ = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory", ws); + _ = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, @"goo.cs", @"C:\ProjectDirectory", ws); } [Fact] diff --git a/src/Workspaces/CoreTest/Differencing/LongestCommonSubsequenceTests.cs b/src/Workspaces/CoreTest/Differencing/LongestCommonSubsequenceTests.cs index ca5190a3f1e4b..b299d7dbdea86 100644 --- a/src/Workspaces/CoreTest/Differencing/LongestCommonSubsequenceTests.cs +++ b/src/Workspaces/CoreTest/Differencing/LongestCommonSubsequenceTests.cs @@ -3,9 +3,9 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections.Generic; using System.Text; using Xunit; -using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Differencing.UnitTests; diff --git a/src/Workspaces/CoreTest/Differencing/MatchTests.cs b/src/Workspaces/CoreTest/Differencing/MatchTests.cs index 6d5c97c6086a5..f90c0aa8926d1 100644 --- a/src/Workspaces/CoreTest/Differencing/MatchTests.cs +++ b/src/Workspaces/CoreTest/Differencing/MatchTests.cs @@ -3,7 +3,7 @@ // See the LICENSE file in the project root for more information. using System; -using Roslyn.Utilities; +using System.Collections.Generic; using Xunit; namespace Microsoft.CodeAnalysis.Differencing.UnitTests; @@ -22,13 +22,13 @@ public void KnownMatches() x2 = new TestNode(1, 2)); var m = TestTreeComparer.Instance.ComputeMatch(oldRoot, newRoot, - [KeyValuePairUtil.Create(x1, x2), KeyValuePairUtil.Create(x1, x2)]); + [KeyValuePair.Create(x1, x2), KeyValuePair.Create(x1, x2)]); Assert.True(m.TryGetNewNode(x1, out var n)); Assert.Equal(n, x2); - Assert.Throws(() => TestTreeComparer.Instance.ComputeMatch(oldRoot, newRoot, [KeyValuePairUtil.Create(x1, x1)])); + Assert.Throws(() => TestTreeComparer.Instance.ComputeMatch(oldRoot, newRoot, [KeyValuePair.Create(x1, x1)])); - Assert.Throws(() => TestTreeComparer.Instance.ComputeMatch(oldRoot, newRoot, [KeyValuePairUtil.Create(x1, x2), KeyValuePairUtil.Create(x1, new TestNode(0, 0))])); + Assert.Throws(() => TestTreeComparer.Instance.ComputeMatch(oldRoot, newRoot, [KeyValuePair.Create(x1, x2), KeyValuePair.Create(x1, new TestNode(0, 0))])); } [Fact] @@ -46,8 +46,8 @@ public void KnownMatchesDups() var m = TestTreeComparer.Instance.ComputeMatch(oldRoot, newRoot, [ - KeyValuePairUtil.Create(x1, x2), - KeyValuePairUtil.Create(y1, x2), + KeyValuePair.Create(x1, x2), + KeyValuePair.Create(y1, x2), ]); // the first one wins: @@ -72,7 +72,7 @@ public void KnownMatchesRootMatch() var m = TestTreeComparer.Instance.ComputeMatch(oldRoot, newRoot, [ - KeyValuePairUtil.Create(x1, newRoot), + KeyValuePair.Create(x1, newRoot), ]); // the root wins: diff --git a/src/Workspaces/CoreTest/Editing/SyntaxEditorTests.cs b/src/Workspaces/CoreTest/Editing/SyntaxEditorTests.cs index 18294ea5020ff..0acfee417306b 100644 --- a/src/Workspaces/CoreTest/Editing/SyntaxEditorTests.cs +++ b/src/Workspaces/CoreTest/Editing/SyntaxEditorTests.cs @@ -38,11 +38,12 @@ private SyntaxEditor GetEditor(SyntaxNode root) [Fact] public void TestReplaceNode() { - var code = @" -public class C -{ - public int X; -}"; + var code = """ + public class C + { + public int X; + } + """; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; @@ -54,21 +55,23 @@ public class C VerifySyntax( newRoot, - @" -public class C -{ - public string Y; -}"); + """ + public class C + { + public string Y; + } + """); } [Fact] public void TestRemoveNode() { - var code = @" -public class C -{ - public int X; -}"; + var code = """ + public class C + { + public int X; + } + """; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; @@ -80,20 +83,22 @@ public class C VerifySyntax( newRoot, - @" -public class C -{ -}"); + """ + public class C + { + } + """); } [Fact] public void TestInsertAfter() { - var code = @" -public class C -{ - public int X; -}"; + var code = """ + public class C + { + public int X; + } + """; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; @@ -105,22 +110,24 @@ public class C VerifySyntax( newRoot, - @" -public class C -{ - public int X; - public string Y; -}"); + """ + public class C + { + public int X; + public string Y; + } + """); } [Fact] public void TestInsertBefore() { - var code = @" -public class C -{ - public int X; -}"; + var code = """ + public class C + { + public int X; + } + """; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; @@ -132,22 +139,24 @@ public class C VerifySyntax( newRoot, - @" -public class C -{ - public string Y; - public int X; -}"); + """ + public class C + { + public string Y; + public int X; + } + """); } [Fact] public void TestTrackNode() { - var code = @" -public class C -{ - public int X; -}"; + var code = """ + public class C + { + public int X; + } + """; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; @@ -164,11 +173,12 @@ public class C [Fact] public void TestMultipleEdits() { - var code = @" -public class C -{ - public int X; -}"; + var code = """ + public class C + { + public int X; + } + """; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; @@ -182,12 +192,13 @@ public class C VerifySyntax( newRoot, - @" -public class C -{ - public object Z; - public string Y; -}"); + """ + public class C + { + public object Z; + public string Y; + } + """); } [Fact] @@ -204,18 +215,6 @@ Type Main(Type t) } } """; - var fixedCode = """ -using System; -using System.CodeAnalysis; - -public class C -{ - Type Main([Example(Sample.Attribute)] Type t) - { - } -} -"""; - var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; @@ -231,35 +230,33 @@ Type Main([Example(Sample.Attribute)] Type t) var newRoot = editor.GetChangedRoot(); VerifySyntax( - newRoot, fixedCode); - } - - [Fact] - public void TestAddGenericAttribute() - { - var code = """ + newRoot, """ using System; using System.CodeAnalysis; public class C { - Type Main() + Type Main([Example(Sample.Attribute)] Type t) { } } -"""; - var fixedCode = """ +"""); + } + + [Fact] + public void TestAddGenericAttribute() + { + var code = """ using System; using System.CodeAnalysis; public class C { - Type Main<[Example(Sample.Attribute)] T>() + Type Main() { } } """; - var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; @@ -275,36 +272,33 @@ public class C var newRoot = editor.GetChangedRoot(); VerifySyntax( - newRoot, fixedCode); - } - - [Fact] - public void TestAddReturnAttribute() - { - var code = """ + newRoot, """ using System; using System.CodeAnalysis; public class C { - Type Main(Type t) + Type Main<[Example(Sample.Attribute)] T>() { } } -"""; - var fixedCode = """ +"""); + } + + [Fact] + public void TestAddReturnAttribute() + { + var code = """ using System; using System.CodeAnalysis; public class C { - [return: Example(Sample.Attribute)] Type Main(Type t) { } } """; - var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; @@ -318,6 +312,17 @@ Type Main(Type t) var newRoot = editor.GetChangedRoot(); VerifySyntax( - newRoot, fixedCode); + newRoot, """ +using System; +using System.CodeAnalysis; + +public class C +{ + [return: Example(Sample.Attribute)] + Type Main(Type t) + { + } +} +"""); } } diff --git a/src/Workspaces/CoreTest/EditorConfigParsing/NamingStyleParserTests.cs b/src/Workspaces/CoreTest/EditorConfigParsing/NamingStyleParserTests.cs index 8cd862b4b6d7c..0f71a03ec11f2 100644 --- a/src/Workspaces/CoreTest/EditorConfigParsing/NamingStyleParserTests.cs +++ b/src/Workspaces/CoreTest/EditorConfigParsing/NamingStyleParserTests.cs @@ -76,7 +76,7 @@ public void TestParseRoslynEditorConfig() accessibility => Assert.Equal(Accessibility.ProtectedAndFriend, accessibility)); Assert.Equal(TextSpan.FromBounds(2338, 2481), rule0.ApplicableSymbolInfo.Accessibilities.Span); Assert.Collection(rule0.ApplicableSymbolInfo.Modifiers.Value, - modifier => Assert.Equal(new ModifierKind(DeclarationModifiers.Static), modifier)); + modifier => Assert.Equal(new ModifierKind(Modifiers.Static), modifier)); Assert.Equal(TextSpan.FromBounds(2483, 2558), rule0.ApplicableSymbolInfo.Modifiers.Span); Assert.Collection(rule0.ApplicableSymbolInfo.SymbolKinds.Value, symbolKind => Assert.Equal(new SymbolKindOrTypeKind(SymbolKind.Field), symbolKind)); @@ -198,7 +198,7 @@ public void TestParseRoslynEditorConfig() accessibility => Assert.Equal(Accessibility.ProtectedAndFriend, accessibility)); Assert.Equal(TextSpan.FromBounds(3080, 3225), rule3.ApplicableSymbolInfo.Accessibilities.Span); Assert.Collection(rule3.ApplicableSymbolInfo.Modifiers.Value, - modifier => Assert.Equal(new ModifierKind(DeclarationModifiers.ReadOnly), modifier)); + modifier => Assert.Equal(new ModifierKind(Modifiers.ReadOnly), modifier)); Assert.Equal(TextSpan.FromBounds(3227, 3306), rule3.ApplicableSymbolInfo.Modifiers.Span); Assert.Collection(rule3.ApplicableSymbolInfo.SymbolKinds.Value, symbolKind => Assert.Equal(new SymbolKindOrTypeKind(SymbolKind.Field), symbolKind)); @@ -271,7 +271,7 @@ public void TestParseRoslynEditorConfig() accessibility => Assert.Equal(Accessibility.ProtectedOrFriend, accessibility)); Assert.Null(rule5.ApplicableSymbolInfo.Accessibilities.Span); Assert.Collection(rule5.ApplicableSymbolInfo.Modifiers.Value, - modifier => Assert.Equal(new ModifierKind(DeclarationModifiers.Const), modifier)); + modifier => Assert.Equal(new ModifierKind(Modifiers.Const), modifier)); Assert.Equal(TextSpan.FromBounds(3711, 3769), rule5.ApplicableSymbolInfo.Modifiers.Span); Assert.Collection(rule5.ApplicableSymbolInfo.SymbolKinds.Value, symbolKind => Assert.Equal(new SymbolKindOrTypeKind(SymbolKind.Field), symbolKind), @@ -345,7 +345,7 @@ public void TestParseRoslynEditorConfig() accessibility => Assert.Equal(Accessibility.ProtectedOrFriend, accessibility)); Assert.Null(rule7.ApplicableSymbolInfo.Accessibilities.Span); Assert.Collection(rule7.ApplicableSymbolInfo.Modifiers.Value, - modifier => Assert.Equal(new ModifierKind(DeclarationModifiers.Static), modifier)); + modifier => Assert.Equal(new ModifierKind(Modifiers.Static), modifier)); Assert.Equal(TextSpan.FromBounds(4191, 4254), rule7.ApplicableSymbolInfo.Modifiers.Span); Assert.Collection(rule7.ApplicableSymbolInfo.SymbolKinds.Value, symbolKind => Assert.Equal(new SymbolKindOrTypeKind(SymbolKind.Field), symbolKind)); @@ -357,679 +357,680 @@ public void TestParseRoslynEditorConfig() } private const string DefaultDotNet6EditorConfigText = -@" -root = true - -# All files -[*] -indent_style = space - -# Xml files -[*.xml] -indent_size = 2 - -# C# files -[*.cs] - -#### Core EditorConfig Options #### - -# Indentation and spacing -indent_size = 4 -tab_width = 4 - -# New line preferences -end_of_line = crlf -insert_final_newline = false - -#### .NET Coding Conventions #### -[*.{cs,vb}] - -# Organize usings -dotnet_separate_import_directive_groups = true -dotnet_sort_system_directives_first = true -file_header_template = unset - -# this. and Me. preferences -dotnet_style_qualification_for_event = false:silent -dotnet_style_qualification_for_field = false:silent -dotnet_style_qualification_for_method = false:silent -dotnet_style_qualification_for_property = false:silent - -# Language keywords vs BCL types preferences -dotnet_style_predefined_type_for_locals_parameters_members = true:silent -dotnet_style_predefined_type_for_member_access = true:silent - -# Parentheses preferences -dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent -dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent -dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent -dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent - -# Modifier preferences -dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent - -# Expression-level preferences -dotnet_style_coalesce_expression = true:suggestion -dotnet_style_collection_initializer = true:suggestion -dotnet_style_explicit_tuple_names = true:suggestion -dotnet_style_null_propagation = true:suggestion -dotnet_style_object_initializer = true:suggestion -dotnet_style_operator_placement_when_wrapping = beginning_of_line -dotnet_style_prefer_auto_properties = true:suggestion -dotnet_style_prefer_compound_assignment = true:suggestion -dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion -dotnet_style_prefer_conditional_expression_over_return = true:suggestion -dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion -dotnet_style_prefer_inferred_tuple_names = true:suggestion -dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion -dotnet_style_prefer_simplified_boolean_expressions = true:suggestion -dotnet_style_prefer_simplified_interpolation = true:suggestion - -# Field preferences -dotnet_style_readonly_field = true:warning - -# Parameter preferences -dotnet_code_quality_unused_parameters = all:suggestion - -# Suppression preferences -dotnet_remove_unnecessary_suppression_exclusions = none - -#### C# Coding Conventions #### -[*.cs] - -# var preferences -csharp_style_var_elsewhere = false:silent -csharp_style_var_for_built_in_types = false:silent -csharp_style_var_when_type_is_apparent = false:silent - -# Expression-bodied members -csharp_style_expression_bodied_accessors = true:silent -csharp_style_expression_bodied_constructors = false:silent -csharp_style_expression_bodied_indexers = true:silent -csharp_style_expression_bodied_lambdas = true:suggestion -csharp_style_expression_bodied_local_functions = false:silent -csharp_style_expression_bodied_methods = false:silent -csharp_style_expression_bodied_operators = false:silent -csharp_style_expression_bodied_properties = true:silent - -# Pattern matching preferences -csharp_style_pattern_matching_over_as_with_null_check = true:suggestion -csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion -csharp_style_prefer_not_pattern = true:suggestion -csharp_style_prefer_pattern_matching = true:silent -csharp_style_prefer_switch_expression = true:suggestion - -# Null-checking preferences -csharp_style_conditional_delegate_call = true:suggestion - -# Modifier preferences -csharp_prefer_static_local_function = true:warning -csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:silent - -# Code-block preferences -csharp_prefer_braces = true:silent -csharp_prefer_simple_using_statement = true:suggestion - -# Expression-level preferences -csharp_prefer_simple_default_expression = true:suggestion -csharp_style_deconstructed_variable_declaration = true:suggestion -csharp_style_inlined_variable_declaration = true:suggestion -csharp_style_pattern_local_over_anonymous_function = true:suggestion -csharp_style_prefer_index_operator = true:suggestion -csharp_style_prefer_range_operator = true:suggestion -csharp_style_throw_expression = true:suggestion -csharp_style_unused_value_assignment_preference = discard_variable:suggestion -csharp_style_unused_value_expression_statement_preference = discard_variable:silent - -# 'using' directive preferences -csharp_using_directive_placement = outside_namespace:silent - -#### C# Formatting Rules #### - -# New line preferences -csharp_new_line_before_catch = true -csharp_new_line_before_else = true -csharp_new_line_before_finally = true -csharp_new_line_before_members_in_anonymous_types = true -csharp_new_line_before_members_in_object_initializers = true -csharp_new_line_before_open_brace = all -csharp_new_line_between_query_expression_clauses = true - -# Indentation preferences -csharp_indent_block_contents = true -csharp_indent_braces = false -csharp_indent_case_contents = true -csharp_indent_case_contents_when_block = true -csharp_indent_labels = one_less_than_current -csharp_indent_switch_labels = true - -# Space preferences -csharp_space_after_cast = false -csharp_space_after_colon_in_inheritance_clause = true -csharp_space_after_comma = true -csharp_space_after_dot = false -csharp_space_after_keywords_in_control_flow_statements = true -csharp_space_after_semicolon_in_for_statement = true -csharp_space_around_binary_operators = before_and_after -csharp_space_around_declaration_statements = false -csharp_space_before_colon_in_inheritance_clause = true -csharp_space_before_comma = false -csharp_space_before_dot = false -csharp_space_before_open_square_brackets = false -csharp_space_before_semicolon_in_for_statement = false -csharp_space_between_empty_square_brackets = false -csharp_space_between_method_call_empty_parameter_list_parentheses = false -csharp_space_between_method_call_name_and_opening_parenthesis = false -csharp_space_between_method_call_parameter_list_parentheses = false -csharp_space_between_method_declaration_empty_parameter_list_parentheses = false -csharp_space_between_method_declaration_name_and_open_parenthesis = false -csharp_space_between_method_declaration_parameter_list_parentheses = false -csharp_space_between_parentheses = false -csharp_space_between_square_brackets = false - -# Wrapping preferences -csharp_preserve_single_line_blocks = true -csharp_preserve_single_line_statements = true - -#### Naming styles #### -[*.{cs,vb}] - -# Naming rules - -dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.severity = suggestion -dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.symbols = types_and_namespaces -dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.style = pascalcase - -dotnet_naming_rule.interfaces_should_be_ipascalcase.severity = suggestion -dotnet_naming_rule.interfaces_should_be_ipascalcase.symbols = interfaces -dotnet_naming_rule.interfaces_should_be_ipascalcase.style = ipascalcase - -dotnet_naming_rule.type_parameters_should_be_tpascalcase.severity = suggestion -dotnet_naming_rule.type_parameters_should_be_tpascalcase.symbols = type_parameters -dotnet_naming_rule.type_parameters_should_be_tpascalcase.style = tpascalcase - -dotnet_naming_rule.methods_should_be_pascalcase.severity = suggestion -dotnet_naming_rule.methods_should_be_pascalcase.symbols = methods -dotnet_naming_rule.methods_should_be_pascalcase.style = pascalcase - -dotnet_naming_rule.properties_should_be_pascalcase.severity = suggestion -dotnet_naming_rule.properties_should_be_pascalcase.symbols = properties -dotnet_naming_rule.properties_should_be_pascalcase.style = pascalcase - -dotnet_naming_rule.events_should_be_pascalcase.severity = suggestion -dotnet_naming_rule.events_should_be_pascalcase.symbols = events -dotnet_naming_rule.events_should_be_pascalcase.style = pascalcase - -dotnet_naming_rule.local_variables_should_be_camelcase.severity = suggestion -dotnet_naming_rule.local_variables_should_be_camelcase.symbols = local_variables -dotnet_naming_rule.local_variables_should_be_camelcase.style = camelcase - -dotnet_naming_rule.local_constants_should_be_camelcase.severity = suggestion -dotnet_naming_rule.local_constants_should_be_camelcase.symbols = local_constants -dotnet_naming_rule.local_constants_should_be_camelcase.style = camelcase - -dotnet_naming_rule.parameters_should_be_camelcase.severity = suggestion -dotnet_naming_rule.parameters_should_be_camelcase.symbols = parameters -dotnet_naming_rule.parameters_should_be_camelcase.style = camelcase - -dotnet_naming_rule.public_fields_should_be_pascalcase.severity = suggestion -dotnet_naming_rule.public_fields_should_be_pascalcase.symbols = public_fields -dotnet_naming_rule.public_fields_should_be_pascalcase.style = pascalcase - -dotnet_naming_rule.private_fields_should_be__camelcase.severity = suggestion -dotnet_naming_rule.private_fields_should_be__camelcase.symbols = private_fields -dotnet_naming_rule.private_fields_should_be__camelcase.style = _camelcase - -dotnet_naming_rule.private_static_fields_should_be_s_camelcase.severity = suggestion -dotnet_naming_rule.private_static_fields_should_be_s_camelcase.symbols = private_static_fields -dotnet_naming_rule.private_static_fields_should_be_s_camelcase.style = s_camelcase - -dotnet_naming_rule.public_constant_fields_should_be_pascalcase.severity = suggestion -dotnet_naming_rule.public_constant_fields_should_be_pascalcase.symbols = public_constant_fields -dotnet_naming_rule.public_constant_fields_should_be_pascalcase.style = pascalcase - -dotnet_naming_rule.private_constant_fields_should_be_pascalcase.severity = suggestion -dotnet_naming_rule.private_constant_fields_should_be_pascalcase.symbols = private_constant_fields -dotnet_naming_rule.private_constant_fields_should_be_pascalcase.style = pascalcase - -dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.severity = suggestion -dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.symbols = public_static_readonly_fields -dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.style = pascalcase - -dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.severity = suggestion -dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.symbols = private_static_readonly_fields -dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.style = pascalcase - -dotnet_naming_rule.enums_should_be_pascalcase.severity = suggestion -dotnet_naming_rule.enums_should_be_pascalcase.symbols = enums -dotnet_naming_rule.enums_should_be_pascalcase.style = pascalcase - -dotnet_naming_rule.local_functions_should_be_pascalcase.severity = suggestion -dotnet_naming_rule.local_functions_should_be_pascalcase.symbols = local_functions -dotnet_naming_rule.local_functions_should_be_pascalcase.style = pascalcase - -dotnet_naming_rule.non_field_members_should_be_pascalcase.severity = suggestion -dotnet_naming_rule.non_field_members_should_be_pascalcase.symbols = non_field_members -dotnet_naming_rule.non_field_members_should_be_pascalcase.style = pascalcase - -# Symbol specifications - -dotnet_naming_symbols.interfaces.applicable_kinds = interface -dotnet_naming_symbols.interfaces.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.interfaces.required_modifiers = - -dotnet_naming_symbols.enums.applicable_kinds = enum -dotnet_naming_symbols.enums.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.enums.required_modifiers = - -dotnet_naming_symbols.events.applicable_kinds = event -dotnet_naming_symbols.events.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.events.required_modifiers = + """ + root = true + + # All files + [*] + indent_style = space + + # Xml files + [*.xml] + indent_size = 2 + + # C# files + [*.cs] + + #### Core EditorConfig Options #### + + # Indentation and spacing + indent_size = 4 + tab_width = 4 + + # New line preferences + end_of_line = crlf + insert_final_newline = false + + #### .NET Coding Conventions #### + [*.{cs,vb}] + + # Organize usings + dotnet_separate_import_directive_groups = true + dotnet_sort_system_directives_first = true + file_header_template = unset + + # this. and Me. preferences + dotnet_style_qualification_for_event = false:silent + dotnet_style_qualification_for_field = false:silent + dotnet_style_qualification_for_method = false:silent + dotnet_style_qualification_for_property = false:silent + + # Language keywords vs BCL types preferences + dotnet_style_predefined_type_for_locals_parameters_members = true:silent + dotnet_style_predefined_type_for_member_access = true:silent + + # Parentheses preferences + dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent + dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent + dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent + dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent + + # Modifier preferences + dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent + + # Expression-level preferences + dotnet_style_coalesce_expression = true:suggestion + dotnet_style_collection_initializer = true:suggestion + dotnet_style_explicit_tuple_names = true:suggestion + dotnet_style_null_propagation = true:suggestion + dotnet_style_object_initializer = true:suggestion + dotnet_style_operator_placement_when_wrapping = beginning_of_line + dotnet_style_prefer_auto_properties = true:suggestion + dotnet_style_prefer_compound_assignment = true:suggestion + dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion + dotnet_style_prefer_conditional_expression_over_return = true:suggestion + dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion + dotnet_style_prefer_inferred_tuple_names = true:suggestion + dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion + dotnet_style_prefer_simplified_boolean_expressions = true:suggestion + dotnet_style_prefer_simplified_interpolation = true:suggestion + + # Field preferences + dotnet_style_readonly_field = true:warning + + # Parameter preferences + dotnet_code_quality_unused_parameters = all:suggestion + + # Suppression preferences + dotnet_remove_unnecessary_suppression_exclusions = none + + #### C# Coding Conventions #### + [*.cs] + + # var preferences + csharp_style_var_elsewhere = false:silent + csharp_style_var_for_built_in_types = false:silent + csharp_style_var_when_type_is_apparent = false:silent + + # Expression-bodied members + csharp_style_expression_bodied_accessors = true:silent + csharp_style_expression_bodied_constructors = false:silent + csharp_style_expression_bodied_indexers = true:silent + csharp_style_expression_bodied_lambdas = true:suggestion + csharp_style_expression_bodied_local_functions = false:silent + csharp_style_expression_bodied_methods = false:silent + csharp_style_expression_bodied_operators = false:silent + csharp_style_expression_bodied_properties = true:silent + + # Pattern matching preferences + csharp_style_pattern_matching_over_as_with_null_check = true:suggestion + csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion + csharp_style_prefer_not_pattern = true:suggestion + csharp_style_prefer_pattern_matching = true:silent + csharp_style_prefer_switch_expression = true:suggestion + + # Null-checking preferences + csharp_style_conditional_delegate_call = true:suggestion + + # Modifier preferences + csharp_prefer_static_local_function = true:warning + csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:silent + + # Code-block preferences + csharp_prefer_braces = true:silent + csharp_prefer_simple_using_statement = true:suggestion + + # Expression-level preferences + csharp_prefer_simple_default_expression = true:suggestion + csharp_style_deconstructed_variable_declaration = true:suggestion + csharp_style_inlined_variable_declaration = true:suggestion + csharp_style_pattern_local_over_anonymous_function = true:suggestion + csharp_style_prefer_index_operator = true:suggestion + csharp_style_prefer_range_operator = true:suggestion + csharp_style_throw_expression = true:suggestion + csharp_style_unused_value_assignment_preference = discard_variable:suggestion + csharp_style_unused_value_expression_statement_preference = discard_variable:silent + + # 'using' directive preferences + csharp_using_directive_placement = outside_namespace:silent + + #### C# Formatting Rules #### + + # New line preferences + csharp_new_line_before_catch = true + csharp_new_line_before_else = true + csharp_new_line_before_finally = true + csharp_new_line_before_members_in_anonymous_types = true + csharp_new_line_before_members_in_object_initializers = true + csharp_new_line_before_open_brace = all + csharp_new_line_between_query_expression_clauses = true + + # Indentation preferences + csharp_indent_block_contents = true + csharp_indent_braces = false + csharp_indent_case_contents = true + csharp_indent_case_contents_when_block = true + csharp_indent_labels = one_less_than_current + csharp_indent_switch_labels = true + + # Space preferences + csharp_space_after_cast = false + csharp_space_after_colon_in_inheritance_clause = true + csharp_space_after_comma = true + csharp_space_after_dot = false + csharp_space_after_keywords_in_control_flow_statements = true + csharp_space_after_semicolon_in_for_statement = true + csharp_space_around_binary_operators = before_and_after + csharp_space_around_declaration_statements = false + csharp_space_before_colon_in_inheritance_clause = true + csharp_space_before_comma = false + csharp_space_before_dot = false + csharp_space_before_open_square_brackets = false + csharp_space_before_semicolon_in_for_statement = false + csharp_space_between_empty_square_brackets = false + csharp_space_between_method_call_empty_parameter_list_parentheses = false + csharp_space_between_method_call_name_and_opening_parenthesis = false + csharp_space_between_method_call_parameter_list_parentheses = false + csharp_space_between_method_declaration_empty_parameter_list_parentheses = false + csharp_space_between_method_declaration_name_and_open_parenthesis = false + csharp_space_between_method_declaration_parameter_list_parentheses = false + csharp_space_between_parentheses = false + csharp_space_between_square_brackets = false + + # Wrapping preferences + csharp_preserve_single_line_blocks = true + csharp_preserve_single_line_statements = true + + #### Naming styles #### + [*.{cs,vb}] + + # Naming rules + + dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.severity = suggestion + dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.symbols = types_and_namespaces + dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.style = pascalcase + + dotnet_naming_rule.interfaces_should_be_ipascalcase.severity = suggestion + dotnet_naming_rule.interfaces_should_be_ipascalcase.symbols = interfaces + dotnet_naming_rule.interfaces_should_be_ipascalcase.style = ipascalcase + + dotnet_naming_rule.type_parameters_should_be_tpascalcase.severity = suggestion + dotnet_naming_rule.type_parameters_should_be_tpascalcase.symbols = type_parameters + dotnet_naming_rule.type_parameters_should_be_tpascalcase.style = tpascalcase + + dotnet_naming_rule.methods_should_be_pascalcase.severity = suggestion + dotnet_naming_rule.methods_should_be_pascalcase.symbols = methods + dotnet_naming_rule.methods_should_be_pascalcase.style = pascalcase + + dotnet_naming_rule.properties_should_be_pascalcase.severity = suggestion + dotnet_naming_rule.properties_should_be_pascalcase.symbols = properties + dotnet_naming_rule.properties_should_be_pascalcase.style = pascalcase + + dotnet_naming_rule.events_should_be_pascalcase.severity = suggestion + dotnet_naming_rule.events_should_be_pascalcase.symbols = events + dotnet_naming_rule.events_should_be_pascalcase.style = pascalcase + + dotnet_naming_rule.local_variables_should_be_camelcase.severity = suggestion + dotnet_naming_rule.local_variables_should_be_camelcase.symbols = local_variables + dotnet_naming_rule.local_variables_should_be_camelcase.style = camelcase + + dotnet_naming_rule.local_constants_should_be_camelcase.severity = suggestion + dotnet_naming_rule.local_constants_should_be_camelcase.symbols = local_constants + dotnet_naming_rule.local_constants_should_be_camelcase.style = camelcase + + dotnet_naming_rule.parameters_should_be_camelcase.severity = suggestion + dotnet_naming_rule.parameters_should_be_camelcase.symbols = parameters + dotnet_naming_rule.parameters_should_be_camelcase.style = camelcase + + dotnet_naming_rule.public_fields_should_be_pascalcase.severity = suggestion + dotnet_naming_rule.public_fields_should_be_pascalcase.symbols = public_fields + dotnet_naming_rule.public_fields_should_be_pascalcase.style = pascalcase + + dotnet_naming_rule.private_fields_should_be__camelcase.severity = suggestion + dotnet_naming_rule.private_fields_should_be__camelcase.symbols = private_fields + dotnet_naming_rule.private_fields_should_be__camelcase.style = _camelcase + + dotnet_naming_rule.private_static_fields_should_be_s_camelcase.severity = suggestion + dotnet_naming_rule.private_static_fields_should_be_s_camelcase.symbols = private_static_fields + dotnet_naming_rule.private_static_fields_should_be_s_camelcase.style = s_camelcase + + dotnet_naming_rule.public_constant_fields_should_be_pascalcase.severity = suggestion + dotnet_naming_rule.public_constant_fields_should_be_pascalcase.symbols = public_constant_fields + dotnet_naming_rule.public_constant_fields_should_be_pascalcase.style = pascalcase + + dotnet_naming_rule.private_constant_fields_should_be_pascalcase.severity = suggestion + dotnet_naming_rule.private_constant_fields_should_be_pascalcase.symbols = private_constant_fields + dotnet_naming_rule.private_constant_fields_should_be_pascalcase.style = pascalcase + + dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.severity = suggestion + dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.symbols = public_static_readonly_fields + dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.style = pascalcase + + dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.severity = suggestion + dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.symbols = private_static_readonly_fields + dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.style = pascalcase + + dotnet_naming_rule.enums_should_be_pascalcase.severity = suggestion + dotnet_naming_rule.enums_should_be_pascalcase.symbols = enums + dotnet_naming_rule.enums_should_be_pascalcase.style = pascalcase + + dotnet_naming_rule.local_functions_should_be_pascalcase.severity = suggestion + dotnet_naming_rule.local_functions_should_be_pascalcase.symbols = local_functions + dotnet_naming_rule.local_functions_should_be_pascalcase.style = pascalcase + + dotnet_naming_rule.non_field_members_should_be_pascalcase.severity = suggestion + dotnet_naming_rule.non_field_members_should_be_pascalcase.symbols = non_field_members + dotnet_naming_rule.non_field_members_should_be_pascalcase.style = pascalcase + + # Symbol specifications + + dotnet_naming_symbols.interfaces.applicable_kinds = interface + dotnet_naming_symbols.interfaces.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected + dotnet_naming_symbols.interfaces.required_modifiers = + + dotnet_naming_symbols.enums.applicable_kinds = enum + dotnet_naming_symbols.enums.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected + dotnet_naming_symbols.enums.required_modifiers = + + dotnet_naming_symbols.events.applicable_kinds = event + dotnet_naming_symbols.events.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected + dotnet_naming_symbols.events.required_modifiers = -dotnet_naming_symbols.methods.applicable_kinds = method -dotnet_naming_symbols.methods.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.methods.required_modifiers = + dotnet_naming_symbols.methods.applicable_kinds = method + dotnet_naming_symbols.methods.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected + dotnet_naming_symbols.methods.required_modifiers = -dotnet_naming_symbols.properties.applicable_kinds = property -dotnet_naming_symbols.properties.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.properties.required_modifiers = + dotnet_naming_symbols.properties.applicable_kinds = property + dotnet_naming_symbols.properties.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected + dotnet_naming_symbols.properties.required_modifiers = -dotnet_naming_symbols.public_fields.applicable_kinds = field -dotnet_naming_symbols.public_fields.applicable_accessibilities = public, internal -dotnet_naming_symbols.public_fields.required_modifiers = + dotnet_naming_symbols.public_fields.applicable_kinds = field + dotnet_naming_symbols.public_fields.applicable_accessibilities = public, internal + dotnet_naming_symbols.public_fields.required_modifiers = -dotnet_naming_symbols.private_fields.applicable_kinds = field -dotnet_naming_symbols.private_fields.applicable_accessibilities = private, protected, protected_internal, private_protected -dotnet_naming_symbols.private_fields.required_modifiers = + dotnet_naming_symbols.private_fields.applicable_kinds = field + dotnet_naming_symbols.private_fields.applicable_accessibilities = private, protected, protected_internal, private_protected + dotnet_naming_symbols.private_fields.required_modifiers = -dotnet_naming_symbols.private_static_fields.applicable_kinds = field -dotnet_naming_symbols.private_static_fields.applicable_accessibilities = private, protected, protected_internal, private_protected -dotnet_naming_symbols.private_static_fields.required_modifiers = static + dotnet_naming_symbols.private_static_fields.applicable_kinds = field + dotnet_naming_symbols.private_static_fields.applicable_accessibilities = private, protected, protected_internal, private_protected + dotnet_naming_symbols.private_static_fields.required_modifiers = static -dotnet_naming_symbols.types_and_namespaces.applicable_kinds = namespace, class, struct, interface, enum -dotnet_naming_symbols.types_and_namespaces.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.types_and_namespaces.required_modifiers = + dotnet_naming_symbols.types_and_namespaces.applicable_kinds = namespace, class, struct, interface, enum + dotnet_naming_symbols.types_and_namespaces.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected + dotnet_naming_symbols.types_and_namespaces.required_modifiers = -dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method -dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.non_field_members.required_modifiers = + dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method + dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected + dotnet_naming_symbols.non_field_members.required_modifiers = -dotnet_naming_symbols.type_parameters.applicable_kinds = namespace -dotnet_naming_symbols.type_parameters.applicable_accessibilities = * -dotnet_naming_symbols.type_parameters.required_modifiers = + dotnet_naming_symbols.type_parameters.applicable_kinds = namespace + dotnet_naming_symbols.type_parameters.applicable_accessibilities = * + dotnet_naming_symbols.type_parameters.required_modifiers = -dotnet_naming_symbols.private_constant_fields.applicable_kinds = field -dotnet_naming_symbols.private_constant_fields.applicable_accessibilities = private, protected, protected_internal, private_protected -dotnet_naming_symbols.private_constant_fields.required_modifiers = const + dotnet_naming_symbols.private_constant_fields.applicable_kinds = field + dotnet_naming_symbols.private_constant_fields.applicable_accessibilities = private, protected, protected_internal, private_protected + dotnet_naming_symbols.private_constant_fields.required_modifiers = const -dotnet_naming_symbols.local_variables.applicable_kinds = local -dotnet_naming_symbols.local_variables.applicable_accessibilities = local -dotnet_naming_symbols.local_variables.required_modifiers = + dotnet_naming_symbols.local_variables.applicable_kinds = local + dotnet_naming_symbols.local_variables.applicable_accessibilities = local + dotnet_naming_symbols.local_variables.required_modifiers = -dotnet_naming_symbols.local_constants.applicable_kinds = local -dotnet_naming_symbols.local_constants.applicable_accessibilities = local -dotnet_naming_symbols.local_constants.required_modifiers = const + dotnet_naming_symbols.local_constants.applicable_kinds = local + dotnet_naming_symbols.local_constants.applicable_accessibilities = local + dotnet_naming_symbols.local_constants.required_modifiers = const -dotnet_naming_symbols.parameters.applicable_kinds = parameter -dotnet_naming_symbols.parameters.applicable_accessibilities = * -dotnet_naming_symbols.parameters.required_modifiers = + dotnet_naming_symbols.parameters.applicable_kinds = parameter + dotnet_naming_symbols.parameters.applicable_accessibilities = * + dotnet_naming_symbols.parameters.required_modifiers = -dotnet_naming_symbols.public_constant_fields.applicable_kinds = field -dotnet_naming_symbols.public_constant_fields.applicable_accessibilities = public, internal -dotnet_naming_symbols.public_constant_fields.required_modifiers = const + dotnet_naming_symbols.public_constant_fields.applicable_kinds = field + dotnet_naming_symbols.public_constant_fields.applicable_accessibilities = public, internal + dotnet_naming_symbols.public_constant_fields.required_modifiers = const -dotnet_naming_symbols.public_static_readonly_fields.applicable_kinds = field -dotnet_naming_symbols.public_static_readonly_fields.applicable_accessibilities = public, internal -dotnet_naming_symbols.public_static_readonly_fields.required_modifiers = readonly, static + dotnet_naming_symbols.public_static_readonly_fields.applicable_kinds = field + dotnet_naming_symbols.public_static_readonly_fields.applicable_accessibilities = public, internal + dotnet_naming_symbols.public_static_readonly_fields.required_modifiers = readonly, static -dotnet_naming_symbols.private_static_readonly_fields.applicable_kinds = field -dotnet_naming_symbols.private_static_readonly_fields.applicable_accessibilities = private, protected, protected_internal, private_protected -dotnet_naming_symbols.private_static_readonly_fields.required_modifiers = readonly, static + dotnet_naming_symbols.private_static_readonly_fields.applicable_kinds = field + dotnet_naming_symbols.private_static_readonly_fields.applicable_accessibilities = private, protected, protected_internal, private_protected + dotnet_naming_symbols.private_static_readonly_fields.required_modifiers = readonly, static -dotnet_naming_symbols.local_functions.applicable_kinds = local_function -dotnet_naming_symbols.local_functions.applicable_accessibilities = * -dotnet_naming_symbols.local_functions.required_modifiers = + dotnet_naming_symbols.local_functions.applicable_kinds = local_function + dotnet_naming_symbols.local_functions.applicable_accessibilities = * + dotnet_naming_symbols.local_functions.required_modifiers = -# Naming styles + # Naming styles -dotnet_naming_style.pascalcase.required_prefix = -dotnet_naming_style.pascalcase.required_suffix = -dotnet_naming_style.pascalcase.word_separator = -dotnet_naming_style.pascalcase.capitalization = pascal_case + dotnet_naming_style.pascalcase.required_prefix = + dotnet_naming_style.pascalcase.required_suffix = + dotnet_naming_style.pascalcase.word_separator = + dotnet_naming_style.pascalcase.capitalization = pascal_case -dotnet_naming_style.ipascalcase.required_prefix = I -dotnet_naming_style.ipascalcase.required_suffix = -dotnet_naming_style.ipascalcase.word_separator = -dotnet_naming_style.ipascalcase.capitalization = pascal_case + dotnet_naming_style.ipascalcase.required_prefix = I + dotnet_naming_style.ipascalcase.required_suffix = + dotnet_naming_style.ipascalcase.word_separator = + dotnet_naming_style.ipascalcase.capitalization = pascal_case -dotnet_naming_style.tpascalcase.required_prefix = T -dotnet_naming_style.tpascalcase.required_suffix = -dotnet_naming_style.tpascalcase.word_separator = -dotnet_naming_style.tpascalcase.capitalization = pascal_case + dotnet_naming_style.tpascalcase.required_prefix = T + dotnet_naming_style.tpascalcase.required_suffix = + dotnet_naming_style.tpascalcase.word_separator = + dotnet_naming_style.tpascalcase.capitalization = pascal_case -dotnet_naming_style._camelcase.required_prefix = _ -dotnet_naming_style._camelcase.required_suffix = -dotnet_naming_style._camelcase.word_separator = -dotnet_naming_style._camelcase.capitalization = camel_case + dotnet_naming_style._camelcase.required_prefix = _ + dotnet_naming_style._camelcase.required_suffix = + dotnet_naming_style._camelcase.word_separator = + dotnet_naming_style._camelcase.capitalization = camel_case -dotnet_naming_style.camelcase.required_prefix = -dotnet_naming_style.camelcase.required_suffix = -dotnet_naming_style.camelcase.word_separator = -dotnet_naming_style.camelcase.capitalization = camel_case + dotnet_naming_style.camelcase.required_prefix = + dotnet_naming_style.camelcase.required_suffix = + dotnet_naming_style.camelcase.word_separator = + dotnet_naming_style.camelcase.capitalization = camel_case -dotnet_naming_style.s_camelcase.required_prefix = s_ -dotnet_naming_style.s_camelcase.required_suffix = -dotnet_naming_style.s_camelcase.word_separator = -dotnet_naming_style.s_camelcase.capitalization = camel_case -"; + dotnet_naming_style.s_camelcase.required_prefix = s_ + dotnet_naming_style.s_camelcase.required_suffix = + dotnet_naming_style.s_camelcase.word_separator = + dotnet_naming_style.s_camelcase.capitalization = camel_case + """; private const string RoslynEditorConfigText = -@"# EditorConfig is awesome: https://EditorConfig.org - -# top-most EditorConfig file -root = true - -# Don't use tabs for indentation. -[*] -indent_style = space -# (Please don't specify an indent_size here; that has too many unintended consequences.) + """ + # EditorConfig is awesome: https://EditorConfig.org + + # top-most EditorConfig file + root = true + + # Don't use tabs for indentation. + [*] + indent_style = space + # (Please don't specify an indent_size here; that has too many unintended consequences.) -# Code files -[*.{cs,csx,vb,vbx}] -indent_size = 4 -insert_final_newline = true -charset = utf-8-bom + # Code files + [*.{cs,csx,vb,vbx}] + indent_size = 4 + insert_final_newline = true + charset = utf-8-bom -# XML project files -[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}] -indent_size = 2 + # XML project files + [*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}] + indent_size = 2 -# XML config files -[*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}] -indent_size = 2 + # XML config files + [*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}] + indent_size = 2 -# JSON files -[*.json] -indent_size = 2 + # JSON files + [*.json] + indent_size = 2 -# Powershell files -[*.ps1] -indent_size = 2 + # Powershell files + [*.ps1] + indent_size = 2 -# Shell script files -[*.sh] -end_of_line = lf -indent_size = 2 + # Shell script files + [*.sh] + end_of_line = lf + indent_size = 2 -# Dotnet code style settings: -[*.{cs,vb}] + # Dotnet code style settings: + [*.{cs,vb}] -# IDE0055: Fix formatting -dotnet_diagnostic.IDE0055.severity = warning + # IDE0055: Fix formatting + dotnet_diagnostic.IDE0055.severity = warning -# Sort using and Import directives with System.* appearing first -dotnet_sort_system_directives_first = true -dotnet_separate_import_directive_groups = false -# Avoid ""this."" and ""Me."" if not necessary -dotnet_style_qualification_for_field = false:refactoring -dotnet_style_qualification_for_property = false:refactoring -dotnet_style_qualification_for_method = false:refactoring -dotnet_style_qualification_for_event = false:refactoring + # Sort using and Import directives with System.* appearing first + dotnet_sort_system_directives_first = true + dotnet_separate_import_directive_groups = false + # Avoid "this." and "Me." if not necessary + dotnet_style_qualification_for_field = false:refactoring + dotnet_style_qualification_for_property = false:refactoring + dotnet_style_qualification_for_method = false:refactoring + dotnet_style_qualification_for_event = false:refactoring -# Use language keywords instead of framework type names for type references -dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion -dotnet_style_predefined_type_for_member_access = true:suggestion + # Use language keywords instead of framework type names for type references + dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion + dotnet_style_predefined_type_for_member_access = true:suggestion -# Suggest more modern language features when available -dotnet_style_object_initializer = true:suggestion -dotnet_style_collection_initializer = true:suggestion -dotnet_style_coalesce_expression = true:suggestion -dotnet_style_null_propagation = true:suggestion -dotnet_style_explicit_tuple_names = true:suggestion + # Suggest more modern language features when available + dotnet_style_object_initializer = true:suggestion + dotnet_style_collection_initializer = true:suggestion + dotnet_style_coalesce_expression = true:suggestion + dotnet_style_null_propagation = true:suggestion + dotnet_style_explicit_tuple_names = true:suggestion -# Whitespace options -dotnet_style_allow_multiple_blank_lines_experimental = false + # Whitespace options + dotnet_style_allow_multiple_blank_lines_experimental = false -# Non-private static fields are PascalCase -dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.severity = suggestion -dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.symbols = non_private_static_fields -dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.style = non_private_static_field_style + # Non-private static fields are PascalCase + dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.severity = suggestion + dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.symbols = non_private_static_fields + dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.style = non_private_static_field_style -dotnet_naming_symbols.non_private_static_fields.applicable_kinds = field -dotnet_naming_symbols.non_private_static_fields.applicable_accessibilities = public, protected, internal, protected_internal, private_protected -dotnet_naming_symbols.non_private_static_fields.required_modifiers = static + dotnet_naming_symbols.non_private_static_fields.applicable_kinds = field + dotnet_naming_symbols.non_private_static_fields.applicable_accessibilities = public, protected, internal, protected_internal, private_protected + dotnet_naming_symbols.non_private_static_fields.required_modifiers = static -dotnet_naming_style.non_private_static_field_style.capitalization = pascal_case + dotnet_naming_style.non_private_static_field_style.capitalization = pascal_case -# Non-private readonly fields are PascalCase -dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.severity = suggestion -dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.symbols = non_private_readonly_fields -dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.style = non_private_readonly_field_style + # Non-private readonly fields are PascalCase + dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.severity = suggestion + dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.symbols = non_private_readonly_fields + dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.style = non_private_readonly_field_style -dotnet_naming_symbols.non_private_readonly_fields.applicable_kinds = field -dotnet_naming_symbols.non_private_readonly_fields.applicable_accessibilities = public, protected, internal, protected_internal, private_protected -dotnet_naming_symbols.non_private_readonly_fields.required_modifiers = readonly + dotnet_naming_symbols.non_private_readonly_fields.applicable_kinds = field + dotnet_naming_symbols.non_private_readonly_fields.applicable_accessibilities = public, protected, internal, protected_internal, private_protected + dotnet_naming_symbols.non_private_readonly_fields.required_modifiers = readonly -dotnet_naming_style.non_private_readonly_field_style.capitalization = pascal_case + dotnet_naming_style.non_private_readonly_field_style.capitalization = pascal_case -# Constants are PascalCase -dotnet_naming_rule.constants_should_be_pascal_case.severity = suggestion -dotnet_naming_rule.constants_should_be_pascal_case.symbols = constants -dotnet_naming_rule.constants_should_be_pascal_case.style = constant_style + # Constants are PascalCase + dotnet_naming_rule.constants_should_be_pascal_case.severity = suggestion + dotnet_naming_rule.constants_should_be_pascal_case.symbols = constants + dotnet_naming_rule.constants_should_be_pascal_case.style = constant_style -dotnet_naming_symbols.constants.applicable_kinds = field, local -dotnet_naming_symbols.constants.required_modifiers = const + dotnet_naming_symbols.constants.applicable_kinds = field, local + dotnet_naming_symbols.constants.required_modifiers = const -dotnet_naming_style.constant_style.capitalization = pascal_case + dotnet_naming_style.constant_style.capitalization = pascal_case -# Static fields are camelCase and start with s_ -dotnet_naming_rule.static_fields_should_be_camel_case.severity = suggestion -dotnet_naming_rule.static_fields_should_be_camel_case.symbols = static_fields -dotnet_naming_rule.static_fields_should_be_camel_case.style = static_field_style + # Static fields are camelCase and start with s_ + dotnet_naming_rule.static_fields_should_be_camel_case.severity = suggestion + dotnet_naming_rule.static_fields_should_be_camel_case.symbols = static_fields + dotnet_naming_rule.static_fields_should_be_camel_case.style = static_field_style -dotnet_naming_symbols.static_fields.applicable_kinds = field -dotnet_naming_symbols.static_fields.required_modifiers = static - -dotnet_naming_style.static_field_style.capitalization = camel_case -dotnet_naming_style.static_field_style.required_prefix = s_ + dotnet_naming_symbols.static_fields.applicable_kinds = field + dotnet_naming_symbols.static_fields.required_modifiers = static + + dotnet_naming_style.static_field_style.capitalization = camel_case + dotnet_naming_style.static_field_style.required_prefix = s_ -# Instance fields are camelCase and start with _ -dotnet_naming_rule.instance_fields_should_be_camel_case.severity = suggestion -dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields -dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style + # Instance fields are camelCase and start with _ + dotnet_naming_rule.instance_fields_should_be_camel_case.severity = suggestion + dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields + dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style -dotnet_naming_symbols.instance_fields.applicable_kinds = field + dotnet_naming_symbols.instance_fields.applicable_kinds = field -dotnet_naming_style.instance_field_style.capitalization = camel_case -dotnet_naming_style.instance_field_style.required_prefix = _ - -# Locals and parameters are camelCase -dotnet_naming_rule.locals_should_be_camel_case.severity = suggestion -dotnet_naming_rule.locals_should_be_camel_case.symbols = locals_and_parameters -dotnet_naming_rule.locals_should_be_camel_case.style = camel_case_style - -dotnet_naming_symbols.locals_and_parameters.applicable_kinds = parameter, local - -dotnet_naming_style.camel_case_style.capitalization = camel_case - -# Local functions are PascalCase -dotnet_naming_rule.local_functions_should_be_pascal_case.severity = suggestion -dotnet_naming_rule.local_functions_should_be_pascal_case.symbols = local_functions -dotnet_naming_rule.local_functions_should_be_pascal_case.style = local_function_style - -dotnet_naming_symbols.local_functions.applicable_kinds = local_function - -dotnet_naming_style.local_function_style.capitalization = pascal_case - -# By default, name items with PascalCase -dotnet_naming_rule.members_should_be_pascal_case.severity = suggestion -dotnet_naming_rule.members_should_be_pascal_case.symbols = all_members -dotnet_naming_rule.members_should_be_pascal_case.style = pascal_case_style - -dotnet_naming_symbols.all_members.applicable_kinds = * - -dotnet_naming_style.pascal_case_style.capitalization = pascal_case - -# error RS2008: Enable analyzer release tracking for the analyzer project containing rule '{0}' -dotnet_diagnostic.RS2008.severity = none - -# IDE0073: File header -dotnet_diagnostic.IDE0073.severity = warning -file_header_template = Licensed to the .NET Foundation under one or more agreements.\nThe.NET Foundation licenses this file to you under the MIT license.\nSee the LICENSE file in the project root for more information. - -# IDE0035: Remove unreachable code -dotnet_diagnostic.IDE0035.severity = warning - -# IDE0036: Order modifiers -dotnet_diagnostic.IDE0036.severity = warning - -# IDE0043: Format string contains invalid placeholder -dotnet_diagnostic.IDE0043.severity = warning - -# IDE0044: Make field readonly -dotnet_diagnostic.IDE0044.severity = warning - -# RS0016: Only enable if API files are present -dotnet_public_api_analyzer.require_api_files = true - -# CSharp code style settings: -[*.cs] -# Newline settings -csharp_new_line_before_open_brace = all -csharp_new_line_before_else = true -csharp_new_line_before_catch = true -csharp_new_line_before_finally = true -csharp_new_line_before_members_in_object_initializers = true -csharp_new_line_before_members_in_anonymous_types = true -csharp_new_line_between_query_expression_clauses = true - -# Indentation preferences -csharp_indent_block_contents = true -csharp_indent_braces = false -csharp_indent_case_contents = true -csharp_indent_case_contents_when_block = true -csharp_indent_switch_labels = true -csharp_indent_labels = flush_left - -# Whitespace options -csharp_style_allow_embedded_statements_on_same_line_experimental = false -csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false -csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = false - -# Prefer ""var"" everywhere -csharp_style_var_for_built_in_types = true:suggestion -csharp_style_var_when_type_is_apparent = true:suggestion -csharp_style_var_elsewhere = true:suggestion - -# Prefer method-like constructs to have a block body -csharp_style_expression_bodied_methods = false:none -csharp_style_expression_bodied_constructors = false:none -csharp_style_expression_bodied_operators = false:none - -# Prefer property-like constructs to have an expression-body -csharp_style_expression_bodied_properties = true:none -csharp_style_expression_bodied_indexers = true:none -csharp_style_expression_bodied_accessors = true:none - -# Suggest more modern language features when available -csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion -csharp_style_pattern_matching_over_as_with_null_check = true:suggestion -csharp_style_inlined_variable_declaration = true:suggestion -csharp_style_throw_expression = true:suggestion -csharp_style_conditional_delegate_call = true:suggestion - -# Space preferences -csharp_space_after_cast = false -csharp_space_after_colon_in_inheritance_clause = true -csharp_space_after_comma = true -csharp_space_after_dot = false -csharp_space_after_keywords_in_control_flow_statements = true -csharp_space_after_semicolon_in_for_statement = true -csharp_space_around_binary_operators = before_and_after -csharp_space_around_declaration_statements = do_not_ignore -csharp_space_before_colon_in_inheritance_clause = true -csharp_space_before_comma = false -csharp_space_before_dot = false -csharp_space_before_open_square_brackets = false -csharp_space_before_semicolon_in_for_statement = false -csharp_space_between_empty_square_brackets = false -csharp_space_between_method_call_empty_parameter_list_parentheses = false -csharp_space_between_method_call_name_and_opening_parenthesis = false -csharp_space_between_method_call_parameter_list_parentheses = false -csharp_space_between_method_declaration_empty_parameter_list_parentheses = false -csharp_space_between_method_declaration_name_and_open_parenthesis = false -csharp_space_between_method_declaration_parameter_list_parentheses = false -csharp_space_between_parentheses = false -csharp_space_between_square_brackets = false - -# Blocks are allowed -csharp_prefer_braces = true:silent -csharp_preserve_single_line_blocks = true -csharp_preserve_single_line_statements = true - -# Currently only enabled for C# due to crash in VB analyzer. VB can be enabled once -# https://github.com/dotnet/roslyn/pull/54259 has been published. -dotnet_style_allow_statement_immediately_after_block_experimental = false - -[src / CodeStyle/**.{cs,vb}] -# warning RS0005: Do not use generic CodeAction.Create to create CodeAction -dotnet_diagnostic.RS0005.severity = none - -[src/{Analyzers,CodeStyle,Features,Workspaces,EditorFeatures,VisualStudio}/**/*.{ cs,vb}] - -# IDE0011: Add braces -csharp_prefer_braces = when_multiline:warning -# NOTE: We need the below severity entry for Add Braces due to https://github.com/dotnet/roslyn/issues/44201 -dotnet_diagnostic.IDE0011.severity = warning - -# IDE0040: Add accessibility modifiers -dotnet_diagnostic.IDE0040.severity = warning - -# CONSIDER: Are IDE0051 and IDE0052 too noisy to be warnings for IDE editing scenarios? Should they be made build-only warnings? -# IDE0051: Remove unused private member -dotnet_diagnostic.IDE0051.severity = warning - -# IDE0052: Remove unread private member -dotnet_diagnostic.IDE0052.severity = warning - -# IDE0059: Unnecessary assignment to a value -dotnet_diagnostic.IDE0059.severity = warning - -# IDE0060: Remove unused parameter -dotnet_diagnostic.IDE0060.severity = warning - -# CA1012: Abstract types should not have public constructors -dotnet_diagnostic.CA1012.severity = warning - -# CA1822: Make member static -dotnet_diagnostic.CA1822.severity = warning - -# Prefer ""var"" everywhere -dotnet_diagnostic.IDE0007.severity = warning -csharp_style_var_for_built_in_types = true:warning -csharp_style_var_when_type_is_apparent = true:warning -csharp_style_var_elsewhere = true:warning - -# dotnet_style_allow_multiple_blank_lines_experimental -dotnet_diagnostic.IDE2000.severity = warning - -# csharp_style_allow_embedded_statements_on_same_line_experimental -dotnet_diagnostic.IDE2001.severity = warning - -# csharp_style_allow_blank_lines_between_consecutive_braces_experimental -dotnet_diagnostic.IDE2002.severity = warning - -# dotnet_style_allow_statement_immediately_after_block_experimental -dotnet_diagnostic.IDE2003.severity = warning - -# csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental -dotnet_diagnostic.IDE2004.severity = warning - -[src /{ VisualStudio}/**/*.{cs,vb -}] -# CA1822: Make member static -# Not enforced as a build 'warning' for 'VisualStudio' layer due to large number of false positives from https://github.com/dotnet/roslyn-analyzers/issues/3857 and https://github.com/dotnet/roslyn-analyzers/issues/3858 -# Additionally, there is a risk of accidentally breaking an internal API that partners rely on though IVT. -dotnet_diagnostic.CA1822.severity = suggestion -"; + dotnet_naming_style.instance_field_style.capitalization = camel_case + dotnet_naming_style.instance_field_style.required_prefix = _ + + # Locals and parameters are camelCase + dotnet_naming_rule.locals_should_be_camel_case.severity = suggestion + dotnet_naming_rule.locals_should_be_camel_case.symbols = locals_and_parameters + dotnet_naming_rule.locals_should_be_camel_case.style = camel_case_style + + dotnet_naming_symbols.locals_and_parameters.applicable_kinds = parameter, local + + dotnet_naming_style.camel_case_style.capitalization = camel_case + + # Local functions are PascalCase + dotnet_naming_rule.local_functions_should_be_pascal_case.severity = suggestion + dotnet_naming_rule.local_functions_should_be_pascal_case.symbols = local_functions + dotnet_naming_rule.local_functions_should_be_pascal_case.style = local_function_style + + dotnet_naming_symbols.local_functions.applicable_kinds = local_function + + dotnet_naming_style.local_function_style.capitalization = pascal_case + + # By default, name items with PascalCase + dotnet_naming_rule.members_should_be_pascal_case.severity = suggestion + dotnet_naming_rule.members_should_be_pascal_case.symbols = all_members + dotnet_naming_rule.members_should_be_pascal_case.style = pascal_case_style + + dotnet_naming_symbols.all_members.applicable_kinds = * + + dotnet_naming_style.pascal_case_style.capitalization = pascal_case + + # error RS2008: Enable analyzer release tracking for the analyzer project containing rule '{0}' + dotnet_diagnostic.RS2008.severity = none + + # IDE0073: File header + dotnet_diagnostic.IDE0073.severity = warning + file_header_template = Licensed to the .NET Foundation under one or more agreements.\nThe.NET Foundation licenses this file to you under the MIT license.\nSee the LICENSE file in the project root for more information. + + # IDE0035: Remove unreachable code + dotnet_diagnostic.IDE0035.severity = warning + + # IDE0036: Order modifiers + dotnet_diagnostic.IDE0036.severity = warning + + # IDE0043: Format string contains invalid placeholder + dotnet_diagnostic.IDE0043.severity = warning + + # IDE0044: Make field readonly + dotnet_diagnostic.IDE0044.severity = warning + + # RS0016: Only enable if API files are present + dotnet_public_api_analyzer.require_api_files = true + + # CSharp code style settings: + [*.cs] + # Newline settings + csharp_new_line_before_open_brace = all + csharp_new_line_before_else = true + csharp_new_line_before_catch = true + csharp_new_line_before_finally = true + csharp_new_line_before_members_in_object_initializers = true + csharp_new_line_before_members_in_anonymous_types = true + csharp_new_line_between_query_expression_clauses = true + + # Indentation preferences + csharp_indent_block_contents = true + csharp_indent_braces = false + csharp_indent_case_contents = true + csharp_indent_case_contents_when_block = true + csharp_indent_switch_labels = true + csharp_indent_labels = flush_left + + # Whitespace options + csharp_style_allow_embedded_statements_on_same_line_experimental = false + csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false + csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = false + + # Prefer "var" everywhere + csharp_style_var_for_built_in_types = true:suggestion + csharp_style_var_when_type_is_apparent = true:suggestion + csharp_style_var_elsewhere = true:suggestion + + # Prefer method-like constructs to have a block body + csharp_style_expression_bodied_methods = false:none + csharp_style_expression_bodied_constructors = false:none + csharp_style_expression_bodied_operators = false:none + + # Prefer property-like constructs to have an expression-body + csharp_style_expression_bodied_properties = true:none + csharp_style_expression_bodied_indexers = true:none + csharp_style_expression_bodied_accessors = true:none + + # Suggest more modern language features when available + csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion + csharp_style_pattern_matching_over_as_with_null_check = true:suggestion + csharp_style_inlined_variable_declaration = true:suggestion + csharp_style_throw_expression = true:suggestion + csharp_style_conditional_delegate_call = true:suggestion + + # Space preferences + csharp_space_after_cast = false + csharp_space_after_colon_in_inheritance_clause = true + csharp_space_after_comma = true + csharp_space_after_dot = false + csharp_space_after_keywords_in_control_flow_statements = true + csharp_space_after_semicolon_in_for_statement = true + csharp_space_around_binary_operators = before_and_after + csharp_space_around_declaration_statements = do_not_ignore + csharp_space_before_colon_in_inheritance_clause = true + csharp_space_before_comma = false + csharp_space_before_dot = false + csharp_space_before_open_square_brackets = false + csharp_space_before_semicolon_in_for_statement = false + csharp_space_between_empty_square_brackets = false + csharp_space_between_method_call_empty_parameter_list_parentheses = false + csharp_space_between_method_call_name_and_opening_parenthesis = false + csharp_space_between_method_call_parameter_list_parentheses = false + csharp_space_between_method_declaration_empty_parameter_list_parentheses = false + csharp_space_between_method_declaration_name_and_open_parenthesis = false + csharp_space_between_method_declaration_parameter_list_parentheses = false + csharp_space_between_parentheses = false + csharp_space_between_square_brackets = false + + # Blocks are allowed + csharp_prefer_braces = true:silent + csharp_preserve_single_line_blocks = true + csharp_preserve_single_line_statements = true + + # Currently only enabled for C# due to crash in VB analyzer. VB can be enabled once + # https://github.com/dotnet/roslyn/pull/54259 has been published. + dotnet_style_allow_statement_immediately_after_block_experimental = false + + [src / CodeStyle/**.{cs,vb}] + # warning RS0005: Do not use generic CodeAction.Create to create CodeAction + dotnet_diagnostic.RS0005.severity = none + + [src/{Analyzers,CodeStyle,Features,Workspaces,EditorFeatures,VisualStudio}/**/*.{ cs,vb}] + + # IDE0011: Add braces + csharp_prefer_braces = when_multiline:warning + # NOTE: We need the below severity entry for Add Braces due to https://github.com/dotnet/roslyn/issues/44201 + dotnet_diagnostic.IDE0011.severity = warning + + # IDE0040: Add accessibility modifiers + dotnet_diagnostic.IDE0040.severity = warning + + # CONSIDER: Are IDE0051 and IDE0052 too noisy to be warnings for IDE editing scenarios? Should they be made build-only warnings? + # IDE0051: Remove unused private member + dotnet_diagnostic.IDE0051.severity = warning + + # IDE0052: Remove unread private member + dotnet_diagnostic.IDE0052.severity = warning + + # IDE0059: Unnecessary assignment to a value + dotnet_diagnostic.IDE0059.severity = warning + + # IDE0060: Remove unused parameter + dotnet_diagnostic.IDE0060.severity = warning + + # CA1012: Abstract types should not have public constructors + dotnet_diagnostic.CA1012.severity = warning + + # CA1822: Make member static + dotnet_diagnostic.CA1822.severity = warning + + # Prefer "var" everywhere + dotnet_diagnostic.IDE0007.severity = warning + csharp_style_var_for_built_in_types = true:warning + csharp_style_var_when_type_is_apparent = true:warning + csharp_style_var_elsewhere = true:warning + + # dotnet_style_allow_multiple_blank_lines_experimental + dotnet_diagnostic.IDE2000.severity = warning + + # csharp_style_allow_embedded_statements_on_same_line_experimental + dotnet_diagnostic.IDE2001.severity = warning + + # csharp_style_allow_blank_lines_between_consecutive_braces_experimental + dotnet_diagnostic.IDE2002.severity = warning + + # dotnet_style_allow_statement_immediately_after_block_experimental + dotnet_diagnostic.IDE2003.severity = warning + + # csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental + dotnet_diagnostic.IDE2004.severity = warning + + [src /{ VisualStudio}/**/*.{cs,vb + }] + # CA1822: Make member static + # Not enforced as a build 'warning' for 'VisualStudio' layer due to large number of false positives from https://github.com/dotnet/roslyn-analyzers/issues/3857 and https://github.com/dotnet/roslyn-analyzers/issues/3858 + # Additionally, there is a risk of accidentally breaking an internal API that partners rely on though IVT. + dotnet_diagnostic.CA1822.severity = suggestion + """; } diff --git a/src/Workspaces/CoreTest/FindAllDeclarationsTests.TestSolutionsAndProject.cs b/src/Workspaces/CoreTest/FindAllDeclarationsTests.TestSolutionsAndProject.cs index 29a6328e0f9db..6b48840853505 100644 --- a/src/Workspaces/CoreTest/FindAllDeclarationsTests.TestSolutionsAndProject.cs +++ b/src/Workspaces/CoreTest/FindAllDeclarationsTests.TestSolutionsAndProject.cs @@ -156,121 +156,121 @@ public enum SolutionKind } private const string SingleClass = -@" -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TestCases -{ - class TestCase - { + """ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + + namespace TestCases + { + class TestCase + { - } -} - "; + } + } + """; private const string SingleClassWithSingleMethod = -@" -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TestCases -{ - class TestCase - { - static void Test(string[] args) + """ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + + namespace TestCases { + class TestCase + { + static void Test(string[] args) + { + } + } } - } -} - "; + """; private const string SingleClassWithSingleProperty = -@" -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TestCases -{ - class TestCase - { - public int TestProperty{ get; set; } - } -} - "; + """ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + + namespace TestCases + { + class TestCase + { + public int TestProperty{ get; set; } + } + } + """; private const string SingleClassWithSingleField = -@" -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TestCases -{ - class TestCase - { - private int TestField = 0; - } -} - "; + """ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + + namespace TestCases + { + class TestCase + { + private int TestField = 0; + } + } + """; private const string NestedClass = -@" -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TestCases -{ - class TestCase - { - class InnerTestCase + """ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + + namespace TestCases { + class TestCase + { + class InnerTestCase + { + } + } } - } -} - "; + """; private const string Namespace1 = -@" -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TestCase1 -{ - class TestCase - { - } -} - "; + """ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + + namespace TestCase1 + { + class TestCase + { + } + } + """; private const string Namespace2 = -@" -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TestCase2 -{ - class TestCase - { - } -} - "; + """ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + + namespace TestCase2 + { + class TestCase + { + } + } + """; } diff --git a/src/Workspaces/CoreTest/FindAllDeclarationsTests.cs b/src/Workspaces/CoreTest/FindAllDeclarationsTests.cs index 8a4717cfd555b..fabf5e00df08b 100644 --- a/src/Workspaces/CoreTest/FindAllDeclarationsTests.cs +++ b/src/Workspaces/CoreTest/FindAllDeclarationsTests.cs @@ -97,33 +97,27 @@ public async Task FindDeclarationsAsync_Test(string searchTerm, bool ignoreCase, } [Fact] - public async Task FindDeclarationsAsync_Test_NullProject() - { - await Assert.ThrowsAnyAsync(async () => + public Task FindDeclarationsAsync_Test_NullProject() + => Assert.ThrowsAnyAsync(async () => { var declarations = await SymbolFinder.FindDeclarationsAsync(null, "Test", true); }); - } [Fact] - public async Task FindDeclarationsAsync_Test_NullString() - { - await Assert.ThrowsAnyAsync(async () => + public Task FindDeclarationsAsync_Test_NullString() + => Assert.ThrowsAnyAsync(async () => { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindDeclarationsAsync(project, null, true); }); - } [Theory, CombinatorialData] - public async Task FindDeclarationsAsync_Test_Cancellation(TestHost testHost) - { - await Assert.ThrowsAnyAsync(async () => + public Task FindDeclarationsAsync_Test_Cancellation(TestHost testHost) + => Assert.ThrowsAnyAsync(async () => { var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project, testHost); var declarations = await SymbolFinder.FindDeclarationsAsync(project, "Test", true, SymbolFilter.All, new CancellationToken(true)); }); - } [Theory, CombinatorialData] [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1094411")] @@ -161,14 +155,14 @@ public async Task FindDeclarationsAsync_PreviousSubmission(TestHost testHost) solution = solution .AddProject(submission0Id, submission0Name, submission0Name, LanguageNames.CSharp) .AddMetadataReference(submission0Id, MscorlibRef) - .AddDocument(submission0DocId, submission0Name, @" -public class Outer -{ - public class Inner - { - } -} -"); + .AddDocument(submission0DocId, submission0Name, """ + public class Outer + { + public class Inner + { + } + } + """); var submission1Id = ProjectId.CreateNewId(); var submission1DocId = DocumentId.CreateNewId(submission1Id); @@ -177,9 +171,9 @@ public class Inner .AddProject(submission1Id, submission1Name, submission1Name, LanguageNames.CSharp) .AddMetadataReference(submission1Id, MscorlibRef) .AddProjectReference(submission1Id, new ProjectReference(submission0Id)) - .AddDocument(submission1DocId, submission1Name, @" -Inner i; -"); + .AddDocument(submission1DocId, submission1Name, """ + Inner i; + """); var actualSymbol = (await SymbolFinder.FindDeclarationsAsync(solution.GetProject(submission1Id), "Inner", ignoreCase: false)).SingleOrDefault(); var expectedSymbol = (await solution.GetProject(submission0Id).GetCompilationAsync()).GlobalNamespace.GetMembers("Outer").SingleOrDefault().GetMembers("Inner").SingleOrDefault(); @@ -263,33 +257,27 @@ public async Task FindSourceDeclarationsAsync_Project_Test(string searchTerm, bo } [Fact] - public async Task FindSourceDeclarationsAsync_Project_Test_NullProject() - { - await Assert.ThrowsAnyAsync(async () => + public Task FindSourceDeclarationsAsync_Project_Test_NullProject() + => Assert.ThrowsAnyAsync(async () => { var declarations = await SymbolFinder.FindSourceDeclarationsAsync((Project)null, "Test", true); }); - } [Fact] - public async Task FindSourceDeclarationsAsync_Project_Test_NullString() - { - await Assert.ThrowsAnyAsync(async () => + public Task FindSourceDeclarationsAsync_Project_Test_NullString() + => Assert.ThrowsAnyAsync(async () => { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(project, null, true); }); - } [Fact] - public async Task FindSourceDeclarationsAsync_Project_Test_Cancellation() - { - await Assert.ThrowsAnyAsync(async () => + public Task FindSourceDeclarationsAsync_Project_Test_Cancellation() + => Assert.ThrowsAnyAsync(async () => { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(project, "Test", true, SymbolFilter.All, new CancellationToken(true)); }); - } #endregion @@ -368,33 +356,27 @@ public async Task FindSourceDeclarationsAsync_Solution_Test(string searchTerm, b } [Fact] - public async Task FindSourceDeclarationsAsync_Solution_Test_NullProject() - { - await Assert.ThrowsAnyAsync(async () => + public Task FindSourceDeclarationsAsync_Solution_Test_NullProject() + => Assert.ThrowsAnyAsync(async () => { var declarations = await SymbolFinder.FindSourceDeclarationsAsync((Solution)null, "Test", true); }); - } [Fact] - public async Task FindSourceDeclarationsAsync_Solution_Test_NullString() - { - await Assert.ThrowsAnyAsync(async () => + public Task FindSourceDeclarationsAsync_Solution_Test_NullString() + => Assert.ThrowsAnyAsync(async () => { using var workspace = CreateWorkspaceWithSolution(SolutionKind.SingleClass, out var solution); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(solution, null, true); }); - } [Fact] - public async Task FindSourceDeclarationsAsync_Solution_Test_Cancellation() - { - await Assert.ThrowsAnyAsync(async () => + public Task FindSourceDeclarationsAsync_Solution_Test_Cancellation() + => Assert.ThrowsAnyAsync(async () => { using var workspace = CreateWorkspaceWithSolution(SolutionKind.SingleClass, out var solution); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(solution, "Test", true, SymbolFilter.All, new CancellationToken(true)); }); - } #endregion @@ -435,33 +417,27 @@ public async Task FindSourceDeclarationsAsync_Project_Func_Test_AlwaysFalsePredi } [Fact] - public async Task FindSourceDeclarationsAsync_Project_Func_Test_NullProject() - { - await Assert.ThrowsAnyAsync(async () => + public Task FindSourceDeclarationsAsync_Project_Func_Test_NullProject() + => Assert.ThrowsAnyAsync(async () => { var declarations = await SymbolFinder.FindSourceDeclarationsAsync((Project)null, str => str.Contains("Test")); }); - } [Fact] - public async Task FindSourceDeclarationsAsync_Project_Func_Test_NullPredicate() - { - await Assert.ThrowsAnyAsync(async () => + public Task FindSourceDeclarationsAsync_Project_Func_Test_NullPredicate() + => Assert.ThrowsAnyAsync(async () => { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(project, null); }); - } [Fact] - public async Task FindSourceDeclarationsAsync_Project_Func_Test_Cancellation() - { - await Assert.ThrowsAnyAsync(async () => + public Task FindSourceDeclarationsAsync_Project_Func_Test_Cancellation() + => Assert.ThrowsAnyAsync(async () => { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(project, str => str.Contains("Test"), SymbolFilter.All, new CancellationToken(true)); }); - } #endregion @@ -502,33 +478,27 @@ public async Task FindSourceDeclarationsAsync_Solution_Func_Test_AlwaysFalsePred } [Fact] - public async Task FindSourceDeclarationsAsync_Solution_Func_Test_NullSolution() - { - await Assert.ThrowsAnyAsync(async () => + public Task FindSourceDeclarationsAsync_Solution_Func_Test_NullSolution() + => Assert.ThrowsAnyAsync(async () => { await SymbolFinder.FindSourceDeclarationsAsync((Solution)null, str => str.Contains("Test")); }); - } [Fact] - public async Task FindSourceDeclarationsAsync_Solution_Func_Test_NullPredicate() - { - await Assert.ThrowsAnyAsync(async () => + public Task FindSourceDeclarationsAsync_Solution_Func_Test_NullPredicate() + => Assert.ThrowsAnyAsync(async () => { using var workspace = CreateWorkspaceWithSolution(SolutionKind.SingleClass, out var solution); await SymbolFinder.FindSourceDeclarationsAsync(solution, null); }); - } [Fact] - public async Task FindSourceDeclarationsAsync_Solution_Func_Test_Cancellation() - { - await Assert.ThrowsAnyAsync(async () => + public Task FindSourceDeclarationsAsync_Solution_Func_Test_Cancellation() + => Assert.ThrowsAnyAsync(async () => { using var workspace = CreateWorkspaceWithSolution(SolutionKind.SingleClass, out var solution); await SymbolFinder.FindSourceDeclarationsAsync(solution, str => str.Contains("Test"), SymbolFilter.All, new CancellationToken(true)); }); - } #endregion @@ -566,33 +536,27 @@ public async Task FindSourceDeclarationsWithPatternAsync_CamelCase_Project_Test( } [Fact] - public async Task FindSourceDeclarationsWithPatternAsync_Project_Test_NullProject() - { - await Assert.ThrowsAnyAsync(async () => + public Task FindSourceDeclarationsWithPatternAsync_Project_Test_NullProject() + => Assert.ThrowsAnyAsync(async () => { var declarations = await SymbolFinder.FindSourceDeclarationsWithPatternAsync((Project)null, "test"); }); - } [Fact] - public async Task FindSourceDeclarationsWithPatternAsync_Project_Test_NullPattern() - { - await Assert.ThrowsAnyAsync(async () => + public Task FindSourceDeclarationsWithPatternAsync_Project_Test_NullPattern() + => Assert.ThrowsAnyAsync(async () => { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsWithPatternAsync(project, null); }); - } [Fact] - public async Task FindSourceDeclarationsWithPatternAsync_Project_Test_Cancellation() - { - await Assert.ThrowsAnyAsync(async () => + public Task FindSourceDeclarationsWithPatternAsync_Project_Test_Cancellation() + => Assert.ThrowsAnyAsync(async () => { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsWithPatternAsync(project, "test", SymbolFilter.All, new CancellationToken(true)); }); - } #endregion @@ -630,33 +594,27 @@ public async Task FindSourceDeclarationsWithPatternAsync_CamelCase_Solution_Test } [Fact] - public async Task FindSourceDeclarationsWithPatternAsync_Solution_Test_NullSolution() - { - await Assert.ThrowsAnyAsync(async () => + public Task FindSourceDeclarationsWithPatternAsync_Solution_Test_NullSolution() + => Assert.ThrowsAnyAsync(async () => { await SymbolFinder.FindSourceDeclarationsWithPatternAsync((Solution)null, "test"); }); - } [Fact] - public async Task FindSourceDeclarationsWithPatternAsync_Solution_Test_NullPattern() - { - await Assert.ThrowsAnyAsync(async () => + public Task FindSourceDeclarationsWithPatternAsync_Solution_Test_NullPattern() + => Assert.ThrowsAnyAsync(async () => { using var workspace = CreateWorkspaceWithSolution(SolutionKind.SingleClass, out var solution); await SymbolFinder.FindSourceDeclarationsWithPatternAsync(solution, null); }); - } [Fact] - public async Task FindSourceDeclarationsWithPatternAsync_Solution_Test_Cancellation() - { - await Assert.ThrowsAnyAsync(async () => + public Task FindSourceDeclarationsWithPatternAsync_Solution_Test_Cancellation() + => Assert.ThrowsAnyAsync(async () => { using var workspace = CreateWorkspaceWithSolution(SolutionKind.SingleClass, out var solution); await SymbolFinder.FindSourceDeclarationsWithPatternAsync(solution, "test", SymbolFilter.All, new CancellationToken(true)); }); - } #endregion @@ -686,12 +644,6 @@ public async Task TestSymbolTreeInfoSerialization() [Fact, WorkItem("https://github.com/dotnet/roslyn/pull/7941")] public async Task FindDeclarationsInErrorSymbolsDoesntCrash() { - var source = @" -' missing `Class` keyword -Public Class1 - Public Event MyEvent(ByVal a As String) -End Class -"; // create solution var pid = ProjectId.CreateNewId(); @@ -700,7 +652,12 @@ End Class .AddProject(pid, "VBProject", "VBProject", LanguageNames.VisualBasic) .AddMetadataReference(pid, MscorlibRef); var did = DocumentId.CreateNewId(pid); - solution = solution.AddDocument(did, "VBDocument.vb", SourceText.From(source)); + solution = solution.AddDocument(did, "VBDocument.vb", SourceText.From(""" + ' missing `Class` keyword + Public Class1 + Public Event MyEvent(ByVal a As String) + End Class + """)); var project = solution.Projects.Single(); // perform the search diff --git a/src/Workspaces/CoreTest/FindReferencesTests.cs b/src/Workspaces/CoreTest/FindReferencesTests.cs index e39b2a5b956dd..7bb445de7d5df 100644 --- a/src/Workspaces/CoreTest/FindReferencesTests.cs +++ b/src/Workspaces/CoreTest/FindReferencesTests.cs @@ -88,16 +88,18 @@ private static Solution GetMultipleDocumentSolution(Workspace workspace, string[ [Fact] public async Task FindFieldReferencesInSingleDocumentProject() { - var text = @" -public class C { - public int X; - public int Y = X * X; - public void M() { - int x = 10; - int y = x + X; - } -} -"; + var text = """ + + public class C { + public int X; + public int Y = X * X; + public void M() { + int x = 10; + int y = x + X; + } + } + + """; using var workspace = CreateWorkspace(); var solution = GetSingleDocumentSolution(workspace, text); var project = solution.Projects.First(); @@ -111,11 +113,13 @@ public void M() { [Fact] public async Task FindTypeReference_DuplicateMetadataReferences() { - var text = @" -public class C { - public string X; -} -"; + var text = """ + + public class C { + public string X; + } + + """; using var workspace = CreateWorkspace(); var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); @@ -139,32 +143,34 @@ public class C { public async Task PinvokeMethodReferences_VB() { var tree = Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText( - @" -Module Module1 - Declare Function CreateDirectory Lib ""kernel32"" Alias ""CreateDirectoryA"" (ByVal lpPathName As String) As Integer - - Private prop As Integer - Property Prop1 As Integer - Get - Return prop - End Get - Set(value As Integer) - CreateDirectory(""T"") ' Method Call 1 - prop = value - prop = Nothing - End Set - End Property - - Sub Main() - CreateDirectory(""T"") 'Method Call 2 - NormalMethod() ' Method Call 1 - NormalMethod() ' Method Call 2 - End Sub - - Sub NormalMethod() - End Sub - End Module - "); + """ + + Module Module1 + Declare Function CreateDirectory Lib "kernel32" Alias "CreateDirectoryA" (ByVal lpPathName As String) As Integer + + Private prop As Integer + Property Prop1 As Integer + Get + Return prop + End Get + Set(value As Integer) + CreateDirectory("T") ' Method Call 1 + prop = value + prop = Nothing + End Set + End Property + + Sub Main() + CreateDirectory("T") 'Method Call 2 + NormalMethod() ' Method Call 1 + NormalMethod() ' Method Call 2 + End Sub + + Sub NormalMethod() + End Sub + End Module + + """); var prj1Id = ProjectId.CreateNewId(); var docId = DocumentId.CreateNewId(prj1Id); @@ -198,12 +204,14 @@ End Module public async Task TestSymbolWithEmptyIdentifier() { var tree = Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText( - @" -Imports System -Public Class C - private readonly property -End Class - "); + """ + + Imports System + Public Class C + private readonly property + End Class + + """); var prj1Id = ProjectId.CreateNewId(); var docId = DocumentId.CreateNewId(prj1Id); @@ -230,44 +238,46 @@ End Class public async Task PinvokeMethodReferences_CS() { var tree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText( - @" + """ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.Diagnostics; -using System.Runtime.InteropServices; -static class Module1 -{ - [DllImport(""kernel32"", EntryPoint = ""CreateDirectoryA"", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] - public static extern int CreateDirectory(string lpPathName); - private static int prop; - public static int Prop1 - { - get { return prop; } - set + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data; + using System.Diagnostics; + using System.Runtime.InteropServices; + static class Module1 { - CreateDirectory(""T""); - // Method Call 1 - prop = value; - prop = null; - } - } - - public static void Main() - { - CreateDirectory(""T""); // Method Call 2 - NormalMethod(); // Method Call 1 - NormalMethod(); // Method Call 2 - } - - public static void NormalMethod() - { - } - } - "); + [DllImport("kernel32", EntryPoint = "CreateDirectoryA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] + public static extern int CreateDirectory(string lpPathName); + + private static int prop; + public static int Prop1 + { + get { return prop; } + set + { + CreateDirectory("T"); + // Method Call 1 + prop = value; + prop = null; + } + } + + public static void Main() + { + CreateDirectory("T"); // Method Call 2 + NormalMethod(); // Method Call 1 + NormalMethod(); // Method Call 2 + } + + public static void NormalMethod() + { + } + } + + """); var prj1Id = ProjectId.CreateNewId(); var docId = DocumentId.CreateNewId(prj1Id); @@ -301,23 +311,25 @@ public static void NormalMethod() [Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537936")] public async Task FindReferences_InterfaceMapping() { - var text = @" -abstract class C -{ - public abstract void Boo(); // Line 3 -} -interface A -{ - void Boo(); // Line 7 -} - -class B : C, A -{ - void A.Boo() { } // Line 12 - public override void Boo() { } // Line 13 - public void Bar() { Boo(); } // Line 14 -} -"; + var text = """ + + abstract class C + { + public abstract void Boo(); // Line 3 + } + interface A + { + void Boo(); // Line 7 + } + + class B : C, A + { + void A.Boo() { } // Line 12 + public override void Boo() { } // Line 13 + public void Bar() { Boo(); } // Line 14 + } + + """; using var workspace = CreateWorkspace(); var solution = GetSingleDocumentSolution(workspace, text); var project = solution.Projects.First(); @@ -362,28 +374,32 @@ public async Task FindReferences_DifferingAssemblies() { var solution = CreateWorkspace().CurrentSolution; - solution = AddProjectWithMetadataReferences(solution, "NetStandardProject", LanguageNames.CSharp, @" -namespace N -{ - public interface I - { - System.Uri Get(); - } -}", NetStandard20.References.All); + solution = AddProjectWithMetadataReferences(solution, "NetStandardProject", LanguageNames.CSharp, """ - solution = AddProjectWithMetadataReferences(solution, "NetCoreProject", LanguageNames.CSharp, @" -using N; + namespace N + { + public interface I + { + System.Uri Get(); + } + } + """, NetStandard20.References.All); -namespace N2 -{ - public class Impl : I - { - public System.Uri Get() - { - return null; - } - } -}", NetCoreApp.References, solution.Projects.Single(pid => pid.Name == "NetStandardProject").Id); + solution = AddProjectWithMetadataReferences(solution, "NetCoreProject", LanguageNames.CSharp, """ + + using N; + + namespace N2 + { + public class Impl : I + { + public System.Uri Get() + { + return null; + } + } + } + """, NetCoreApp.References, solution.Projects.Single(pid => pid.Name == "NetStandardProject").Id); var netCoreProject = solution.Projects.First(p => p.Name == "NetCoreProject"); var netStandardProject = solution.Projects.First(p => p.Name == "NetStandardProject"); @@ -403,30 +419,36 @@ public System.Uri Get() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/35786")] public async Task FindReferences_MultipleInterfaceInheritence() { - var implText = @"namespace A -{ - class C : ITest - { - public string Name { get; } - public System.Uri Uri { get; } - } -}"; + var implText = """ + namespace A + { + class C : ITest + { + public string Name { get; } + public System.Uri Uri { get; } + } + } + """; - var interface1Text = @"namespace A -{ - interface ITest : ITestBase - { - string Name { get; } - } -}"; + var interface1Text = """ + namespace A + { + interface ITest : ITestBase + { + string Name { get; } + } + } + """; - var interface2Text = @"namespace A -{ - interface ITestBase - { - System.Uri Uri { get; } - } -}"; + var interface2Text = """ + namespace A + { + interface ITestBase + { + System.Uri Uri { get; } + } + } + """; using var workspace = CreateWorkspace(); var solution = GetMultipleDocumentSolution(workspace, [implText, interface1Text, interface2Text]); @@ -453,27 +475,31 @@ public async Task OverriddenMethodsFromPortableToDesktop() var solution = CreateWorkspace().CurrentSolution; // create portable assembly with a virtual method - solution = AddProjectWithMetadataReferences(solution, "PortableProject", LanguageNames.CSharp, @" -namespace N -{ - public class BaseClass - { - public virtual void SomeMethod() { } - } -} -", MscorlibPP7Ref); + solution = AddProjectWithMetadataReferences(solution, "PortableProject", LanguageNames.CSharp, """ + + namespace N + { + public class BaseClass + { + public virtual void SomeMethod() { } + } + } + + """, MscorlibPP7Ref); // create a normal assembly with a type derived from the portable base and overriding the method - solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.CSharp, @" -using N; -namespace M -{ - public class DerivedClass : BaseClass - { - public override void SomeMethod() { } - } -} -", Net40.References.mscorlib, solution.Projects.Single(pid => pid.Name == "PortableProject").Id); + solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.CSharp, """ + + using N; + namespace M + { + public class DerivedClass : BaseClass + { + public override void SomeMethod() { } + } + } + + """, Net40.References.mscorlib, solution.Projects.Single(pid => pid.Name == "PortableProject").Id); // get symbols for methods var portableCompilation = await solution.Projects.Single(p => p.Name == "PortableProject").GetCompilationAsync(); @@ -501,13 +527,15 @@ public override void SomeMethod() { } [Fact] public async Task FindRefereceToUnmanagedConstraint_Type() { - var text = @" -interface unmanaged // Line 1 -{ -} -abstract class C where T : unmanaged // Line 4 -{ -}"; + var text = """ + + interface unmanaged // Line 1 + { + } + abstract class C where T : unmanaged // Line 4 + { + } + """; using var workspace = CreateWorkspace(); var solution = GetSingleDocumentSolution(workspace, text); var project = solution.Projects.First(); @@ -522,19 +550,21 @@ abstract class C where T : unmanaged // Line 4 [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1177764")] public async Task DoNotIncludeConstructorReferenceInTypeList_CSharp() { - var text = @" -class C -{ -} + var text = """ -class Test -{ - void M() - { - C c = new C(); - } -} -"; + class C + { + } + + class Test + { + void M() + { + C c = new C(); + } + } + + """; using var workspace = CreateWorkspace(); var solution = GetSingleDocumentSolution(workspace, text); var project = solution.Projects.First(); @@ -558,16 +588,18 @@ void M() [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1177764")] public async Task DoNotIncludeConstructorReferenceInTypeList_VisualBasic() { - var text = @" -class C -end class - -class Test - sub M() - dim c as C = new C() - end sub -end class -"; + var text = """ + + class C + end class + + class Test + sub M() + dim c as C = new C() + end sub + end class + + """; using var workspace = CreateWorkspace(); var solution = GetSingleDocumentSolution(workspace, text, LanguageNames.VisualBasic); var project = solution.Projects.First(); @@ -591,25 +623,27 @@ end class [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49624")] public async Task DoNotIncludeSameNamedAlias() { - var text = @" -using NestedDummy = Test.Dummy.NestedDummy; + var text = """ -namespace Test -{ - public class DummyFactory - { - public NestedDummy Create() => new NestedDummy(); - } -} + using NestedDummy = Test.Dummy.NestedDummy; -namespace Test -{ - public class Dummy - { - public class NestedDummy { } - } -} -"; + namespace Test + { + public class DummyFactory + { + public NestedDummy Create() => new NestedDummy(); + } + } + + namespace Test + { + public class Dummy + { + public class NestedDummy { } + } + } + + """; using var workspace = CreateWorkspace(); var solution = GetSingleDocumentSolution(workspace, text, LanguageNames.CSharp); var project = solution.Projects.First(); diff --git a/src/Workspaces/CoreTest/Formatter/FormatterTests.cs b/src/Workspaces/CoreTest/Formatter/FormatterTests.cs index 1a89ecd5cc291..040105af59734 100644 --- a/src/Workspaces/CoreTest/Formatter/FormatterTests.cs +++ b/src/Workspaces/CoreTest/Formatter/FormatterTests.cs @@ -169,7 +169,7 @@ static void ValidateCSharpOptions(CSharpSyntaxFormattingOptions formattingOption Assert.True(formattingOptions.Spacing.HasFlag(SpacePlacement.AfterDot)); Assert.True(formattingOptions.Spacing.HasFlag(SpacePlacement.BeforeDot)); - Assert.Equal(BinaryOperatorSpacingOptions.Remove, formattingOptions.SpacingAroundBinaryOperator); + Assert.Equal(BinaryOperatorSpacingOptionsInternal.Remove, formattingOptions.SpacingAroundBinaryOperator); Assert.False(formattingOptions.NewLines.HasFlag(NewLinePlacement.BeforeMembersInObjectInitializers)); Assert.False(formattingOptions.NewLines.HasFlag(NewLinePlacement.BeforeMembersInAnonymousTypes)); @@ -187,7 +187,7 @@ static void ValidateCSharpOptions(CSharpSyntaxFormattingOptions formattingOption Assert.False(formattingOptions.NewLines.HasFlag(NewLinePlacement.BeforeOpenBraceInControlBlocks)); Assert.False(formattingOptions.NewLines.HasFlag(NewLinePlacement.BetweenQueryExpressionClauses)); - Assert.Equal(LabelPositionOptions.LeftMost, formattingOptions.LabelPositioning); + Assert.Equal(LabelPositionOptionsInternal.LeftMost, formattingOptions.LabelPositioning); Assert.True(formattingOptions.Indentation.HasFlag(IndentationPlacement.Braces)); Assert.False(formattingOptions.Indentation.HasFlag(IndentationPlacement.BlockContents)); diff --git a/src/Workspaces/CoreTest/FormattingTests.cs b/src/Workspaces/CoreTest/FormattingTests.cs index 2f01c742a47d5..a369ae8f60fe8 100644 --- a/src/Workspaces/CoreTest/FormattingTests.cs +++ b/src/Workspaces/CoreTest/FormattingTests.cs @@ -23,10 +23,7 @@ public sealed partial class FormattingTests : TestBase [Fact] public void TestCSharpFormatting() { - var text = @"public class C{public int X;}"; - var expectedFormattedText = @"public class C { public int X; }"; - - AssertFormatCSharp(expectedFormattedText, text); + AssertFormatCSharp(@"public class C { public int X; }", @"public class C{public int X;}"); } [Fact] @@ -43,18 +40,15 @@ public void TestCSharpDefaultRules() [Fact] public void TestVisualBasicFormatting() { - var text = @" -Public Class C -Public X As Integer -End Class -"; - var expectedFormattedText = @" -Public Class C - Public X As Integer -End Class -"; - - AssertFormatVB(expectedFormattedText, text); + AssertFormatVB(""" + Public Class C + Public X As Integer + End Class + """, """ + Public Class C + Public X As Integer + End Class + """); } [Fact] diff --git a/src/Workspaces/CoreTest/GeneratedCodeRecognitionTests.cs b/src/Workspaces/CoreTest/GeneratedCodeRecognitionTests.cs index 1a3d4542f905d..17cfb30270d7f 100644 --- a/src/Workspaces/CoreTest/GeneratedCodeRecognitionTests.cs +++ b/src/Workspaces/CoreTest/GeneratedCodeRecognitionTests.cs @@ -57,16 +57,16 @@ private static void TestFileNames(bool assertGenerated, params string[] fileName var project = CreateProject(); var projectWithUserConfiguredGeneratedCodeTrue = project.AddAnalyzerConfigDocument(".editorconfig", - SourceText.From(@" -[*.{cs,vb}] -generated_code = true -"), filePath: @"z:\.editorconfig").Project; + SourceText.From(""" + [*.{cs,vb}] + generated_code = true + """), filePath: @"z:\.editorconfig").Project; var projectWithUserConfiguredGeneratedCodeFalse = project.AddAnalyzerConfigDocument(".editorconfig", - SourceText.From(@" -[*.{cs,vb}] -generated_code = false -"), filePath: @"z:\.editorconfig").Project; + SourceText.From(""" + [*.{cs,vb}] + generated_code = false + """), filePath: @"z:\.editorconfig").Project; foreach (var fileName in fileNames) { diff --git a/src/Workspaces/CoreTest/Host/LanguageServices/TestCSharpCompilationFactoryServiceWithIncrementalGeneratorTracking.cs b/src/Workspaces/CoreTest/Host/LanguageServices/TestCSharpCompilationFactoryServiceWithIncrementalGeneratorTracking.cs index 28b9c036e229f..e03b4bd18810c 100644 --- a/src/Workspaces/CoreTest/Host/LanguageServices/TestCSharpCompilationFactoryServiceWithIncrementalGeneratorTracking.cs +++ b/src/Workspaces/CoreTest/Host/LanguageServices/TestCSharpCompilationFactoryServiceWithIncrementalGeneratorTracking.cs @@ -3,9 +3,9 @@ // See the LICENSE file in the project root for more information. using System; -using System.Composition; using System.Collections.Generic; using System.Collections.Immutable; +using System.Composition; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; diff --git a/src/Workspaces/CoreTest/ObjectSerializationTests.cs b/src/Workspaces/CoreTest/ObjectSerializationTests.cs index 55b64e963c76b..a27a1371f5b85 100644 --- a/src/Workspaces/CoreTest/ObjectSerializationTests.cs +++ b/src/Workspaces/CoreTest/ObjectSerializationTests.cs @@ -495,6 +495,7 @@ private static void TestWritingPrimitiveValues(ObjectWriter writer) writer.WriteInt64((long)ELong.Value); writer.WriteInt64((long)EULong.Value); } + writer.WriteScalarValue(_testNow); } @@ -640,11 +641,6 @@ private static void TestRoundTripStringCharacter(ushort code) TestRoundTripString(new String((char)code, 1)); } - private static void TestRoundTripArray(T[] values) - { - TestRoundTripValue(values); - } - public static IEnumerable GetEncodingTestCases() => EncodingTestHelpers.GetEncodingTestCases(); diff --git a/src/Workspaces/CoreTest/Options/EditorConfigNamingStyleParserTests.cs b/src/Workspaces/CoreTest/Options/EditorConfigNamingStyleParserTests.cs index 279f3ce0cdee4..015ddc14432be 100644 --- a/src/Workspaces/CoreTest/Options/EditorConfigNamingStyleParserTests.cs +++ b/src/Workspaces/CoreTest/Options/EditorConfigNamingStyleParserTests.cs @@ -414,8 +414,8 @@ public void TestRequiredModifiersParse() var csharpResult = OptionsTestHelpers.ParseNamingStylePreferences(charpRule); var vbResult = OptionsTestHelpers.ParseNamingStylePreferences(vbRule); - Assert.Equal(csharpResult.SymbolSpecifications.SelectMany(x => x.RequiredModifierList.Select(y => y.Modifier)), - vbResult.SymbolSpecifications.SelectMany(x => x.RequiredModifierList.Select(y => y.Modifier))); + Assert.Equal(csharpResult.SymbolSpecifications.SelectMany(x => x.RequiredModifierList.Select(y => y.Modifiers)), + vbResult.SymbolSpecifications.SelectMany(x => x.RequiredModifierList.Select(y => y.Modifiers))); Assert.Equal(csharpResult.SymbolSpecifications.SelectMany(x => x.RequiredModifierList.Select(y => y.ModifierKindWrapper)), vbResult.SymbolSpecifications.SelectMany(x => x.RequiredModifierList.Select(y => y.ModifierKindWrapper))); } diff --git a/src/Workspaces/CoreTest/Options/NamingStylePreferencesTests.cs b/src/Workspaces/CoreTest/Options/NamingStylePreferencesTests.cs index 14a01ea4a971a..14ab48ea44189 100644 --- a/src/Workspaces/CoreTest/Options/NamingStylePreferencesTests.cs +++ b/src/Workspaces/CoreTest/Options/NamingStylePreferencesTests.cs @@ -42,73 +42,77 @@ public void TestPreserveDefaultPreferences() [Fact] public void TestCannotUpgrade3To5() { - var serializedPreferences = @" - - - - - Method - - - - - - - Property - Method - - - - - - - - - - - - -"; - AssertTrimmedEqual( NamingStylePreferences.DefaultNamingPreferencesString, - ReserializePreferences(serializedPreferences)); + ReserializePreferences(""" + + + + + Method + + + + + + + Property + Method + + + + + + + + + + + + + + """)); } [Fact] public void TestUpgrade4To5() { - var serializedPreferences = @" - - - - - Method - - - - - - - Property - Method - - - - - - - - - - - - -"; + var serializedPreferences = """ + + + + + Method + + + + + + + Property + Method + + + + + + + + + + + + + + """; AssertTrimmedEqual( serializedPreferences - .Replace("SerializationVersion=\"4\"", "SerializationVersion=\"5\"") + .Replace(""" + SerializationVersion="4" + """, """ + SerializationVersion="5" + """) .Replace("Method", "Ordinary"), ReserializePreferences(serializedPreferences)); } @@ -116,33 +120,34 @@ public void TestUpgrade4To5() [Fact] public void TestPreserveLatestVersion5() { - var serializedPreferences = @" - - - - - Ordinary - - - - - - - Property - Ordinary - - - - - - - - - - - - -"; + var serializedPreferences = """ + + + + + Ordinary + + + + + + + Property + Ordinary + + + + + + + + + + + + + + """; AssertTrimmedEqual( serializedPreferences, @@ -152,37 +157,36 @@ public void TestPreserveLatestVersion5() [Fact] public void TestCannotDowngradeHigherThanLatestVersion5() { - var serializedPreferences = @" - - - - - Ordinary - - - - - - - Property - Ordinary - - - - - - - - - - - - -"; - AssertTrimmedEqual( NamingStylePreferences.DefaultNamingPreferencesString, - ReserializePreferences(serializedPreferences)); + ReserializePreferences(""" + + + + + Ordinary + + + + + + + Property + Ordinary + + + + + + + + + + + + + + """)); } /// diff --git a/src/Workspaces/CoreTest/SemanticModelReuse/SemanticModelReuseTests.cs b/src/Workspaces/CoreTest/SemanticModelReuse/SemanticModelReuseTests.cs index b6bbd1c28a718..c07740e7f4478 100644 --- a/src/Workspaces/CoreTest/SemanticModelReuse/SemanticModelReuseTests.cs +++ b/src/Workspaces/CoreTest/SemanticModelReuse/SemanticModelReuseTests.cs @@ -6,6 +6,8 @@ using System.Threading; using System.Threading.Tasks; +using Basic.Reference.Assemblies; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; @@ -13,7 +15,6 @@ using Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery; using Roslyn.Test.Utilities; using Xunit; -using Basic.Reference.Assemblies; namespace Microsoft.CodeAnalysis.UnitTests.SemanticModelReuse; @@ -274,12 +275,13 @@ public async Task NullBodyReturnsNormalSemanticModel1_VisualBasic() [Fact] public async Task NullBodyReturnsNormalSemanticModel2_VisualBasic() { - var source = @" -class C - sub M() - return - end sub -end class"; + var source = """ + class C + sub M() + return + end sub + end class + """; var document = CreateDocument(source, LanguageNames.VisualBasic); // Even if we've primed things with a real location, getting a semantic model for null should return a @@ -293,12 +295,13 @@ end sub [Fact] public async Task SameSyntaxTreeReturnsNonSpeculativeModel_VisualBasic() { - var source = @" -class C - sub M() - return - end sub -end class"; + var source = """ + class C + sub M() + return + end sub + end class + """; var document = CreateDocument(source, LanguageNames.VisualBasic); // First call will prime the cache to point at the real semantic model. The next call will also use the @@ -319,24 +322,26 @@ end sub [Fact] public async Task InBodyEditShouldProduceCachedModel_VisualBasic() { - var source = @" -class C - sub M() - return - end sub -end class"; + var source = """ + class C + sub M() + return + end sub + end class + """; var document1 = CreateDocument(source, LanguageNames.VisualBasic); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); - var document2 = document1.WithText(SourceText.From(@" -class C - sub M() - return nothing - end sub -end class")); + var document2 = document1.WithText(SourceText.From(""" + class C + sub M() + return nothing + end sub + end class + """)); // This should be able to get a speculative model using the original model we primed the cache with. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); @@ -346,36 +351,39 @@ end sub [Fact] public async Task OutOfBodyEditShouldProduceFreshModel_VisualBasic() { - var source1 = @" -class C - sub M() - return - end sub -end class"; + var source1 = """ + class C + sub M() + return + end sub + end class + """; var document1 = CreateDocument(source1, LanguageNames.VisualBasic); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source1.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); - var source2 = @" -class C - function M() as long - return - end function -end class"; + var source2 = """ + class C + function M() as long + return + end function + end class + """; var document2 = document1.WithText(SourceText.From(source2)); // We changed the return type, so we can't reuse the previous model. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source2.IndexOf("return"), CancellationToken.None); Assert.False(model2.IsSpeculativeSemanticModel); - var document3 = document2.WithText(SourceText.From(@" -class C - function M() as long - return 0 - end function -end class")); + var document3 = document2.WithText(SourceText.From(""" + class C + function M() as long + return 0 + end function + end class + """)); // We are now again only editing a method body so we should be able to get a speculative model. var model3 = await document3.ReuseExistingSpeculativeModelAsync(source2.IndexOf("return"), CancellationToken.None); @@ -385,35 +393,38 @@ end function [Fact] public async Task MultipleBodyEditsShouldProduceFreshModel_VisualBasic() { - var source = @" -class C - sub M() - return - end sub -end class"; + var source = """ + class C + sub M() + return + end sub + end class + """; var document1 = CreateDocument(source, LanguageNames.VisualBasic); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); - var document2 = document1.WithText(SourceText.From(@" -class C - sub M() - return 0 - end sub -end class")); + var document2 = document1.WithText(SourceText.From(""" + class C + sub M() + return 0 + end sub + end class + """)); // This should be able to get a speculative model using the original model we primed the cache with. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model2.IsSpeculativeSemanticModel); - var document3 = document1.WithText(SourceText.From(@" -class C - sub M() - return 1 - end sub -end class")); + var document3 = document1.WithText(SourceText.From(""" + class C + sub M() + return 1 + end sub + end class + """)); // This should be able to get a speculative model using the original model we primed the cache with. var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); @@ -423,41 +434,44 @@ end sub [Fact] public async Task MultipleBodyEditsShouldProduceFreshModel_Accessor_Property_VisualBasic() { - var source = @" -class C - readonly property M as integer - get - return 0 - end get - end property -end class"; + var source = """ + class C + readonly property M as integer + get + return 0 + end get + end property + end class + """; var document1 = CreateDocument(source, LanguageNames.VisualBasic); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); - var document2 = document1.WithText(SourceText.From(@" -class C - readonly property M as integer - get - return 1 - end get - end property -end class")); + var document2 = document1.WithText(SourceText.From(""" + class C + readonly property M as integer + get + return 1 + end get + end property + end class + """)); // This should be able to get a speculative model using the original model we primed the cache with. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model2.IsSpeculativeSemanticModel); - var document3 = document1.WithText(SourceText.From(@" -class C - readonly property M as integer - get - return 2 - end get - end property -end class")); + var document3 = document1.WithText(SourceText.From(""" + class C + readonly property M as integer + get + return 2 + end get + end property + end class + """)); // This should be able to get a speculative model using the original model we primed the cache with. var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); @@ -467,41 +481,44 @@ end property [Fact] public async Task MultipleBodyEditsShouldProduceFreshModel_Accessor_Event_VisualBasic() { - var source = @" -class C - public custom event E as System.Action - addhandler(value as System.Action) - return 0 - end addhandler - end event -end class"; + var source = """ + class C + public custom event E as System.Action + addhandler(value as System.Action) + return 0 + end addhandler + end event + end class + """; var document1 = CreateDocument(source, LanguageNames.VisualBasic); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); - var document2 = document1.WithText(SourceText.From(@" -class C - public custom event E as System.Action - addhandler(value as System.Action) - return 1 - end addhandler - end event -end class")); + var document2 = document1.WithText(SourceText.From(""" + class C + public custom event E as System.Action + addhandler(value as System.Action) + return 1 + end addhandler + end event + end class + """)); // This should be able to get a speculative model using the original model we primed the cache with. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model2.IsSpeculativeSemanticModel); - var document3 = document1.WithText(SourceText.From(@" -class C - public custom event E as System.Action - addhandler(value as System.Action) - return 2 - end addhandler - end event -end class")); + var document3 = document1.WithText(SourceText.From(""" + class C + public custom event E as System.Action + addhandler(value as System.Action) + return 2 + end addhandler + end event + end class + """)); // This should be able to get a speculative model using the original model we primed the cache with. var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); @@ -512,24 +529,26 @@ end event [WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1587699")] public async Task TestOutOfBoundsInSyntaxContext1_VisualBasic() { - var source = @" -class C - sub M() - return - end sub -end class"; + var source = """ + class C + sub M() + return + end sub + end class + """; var document1 = CreateDocument(source, LanguageNames.VisualBasic); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); - var document2 = document1.WithText(SourceText.From(@" -class C - sub M() - return nothing - end sub -end class")); + var document2 = document1.WithText(SourceText.From(""" + class C + sub M() + return nothing + end sub + end class + """)); // This should be able to get a speculative model using the original model we primed the cache with. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); @@ -543,25 +562,27 @@ end sub [WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1587699")] public async Task TestOutOfBoundsInSyntaxContext2_VisualBasic() { - var source = @" -class C - sub M() - return - end sub -end class"; + var source = """ + class C + sub M() + return + end sub + end class + """; var document1 = CreateDocument(source, LanguageNames.VisualBasic); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); - var document2 = document1.WithText(SourceText.From(@" -class C -class C - sub M() - return nothing - end sub -end class")); + var document2 = document1.WithText(SourceText.From(""" + class C + class C + sub M() + return nothing + end sub + end class + """)); // Because the change in trivia shifted the method definition, we are not able to get a speculative model based on previous model var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); diff --git a/src/Workspaces/CoreTest/SolutionTests/DocumentInfoTests.cs b/src/Workspaces/CoreTest/SolutionTests/DocumentInfoTests.cs index e7d4492533846..ccb4c154f1ca7 100644 --- a/src/Workspaces/CoreTest/SolutionTests/DocumentInfoTests.cs +++ b/src/Workspaces/CoreTest/SolutionTests/DocumentInfoTests.cs @@ -7,9 +7,9 @@ using System; using System.Collections.Immutable; using System.Linq; -using Roslyn.Test.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Test.Utilities; +using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests; diff --git a/src/Workspaces/CoreTest/SolutionTests/SolutionTests.cs b/src/Workspaces/CoreTest/SolutionTests/SolutionTests.cs index 2b040629dcc4d..b0661812dcd03 100644 --- a/src/Workspaces/CoreTest/SolutionTests/SolutionTests.cs +++ b/src/Workspaces/CoreTest/SolutionTests/SolutionTests.cs @@ -1674,13 +1674,12 @@ public void WithProjectName() .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed - var projectName = "\0<>a/b/*"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectName(projectId, value), s => s.GetRequiredProject(projectId).Name, - projectName, + "\0<>a/b/*", defaultThrows: true); Assert.Throws("projectId", () => solution.WithProjectName(null!, "x")); @@ -1802,12 +1801,16 @@ public async Task ChangingLanguageVersionReparses() [Theory] [InlineData("#if DEBUG", false, LanguageNames.CSharp)] - [InlineData(@"#region ""goo""", true, LanguageNames.CSharp)] + [InlineData(""" + #region "goo" + """, true, LanguageNames.CSharp)] [InlineData(@"#nullable enable", true, LanguageNames.CSharp)] [InlineData(@"#elif DEBUG", true, LanguageNames.CSharp)] [InlineData("// File", true, LanguageNames.CSharp)] [InlineData("#if DEBUG", false, LanguageNames.VisualBasic)] - [InlineData(@"#region ""goo""", true, LanguageNames.VisualBasic)] + [InlineData(""" + #region "goo" + """, true, LanguageNames.VisualBasic)] [InlineData(@"#ElseIf DEBUG", true, LanguageNames.VisualBasic)] [InlineData("' File", true, LanguageNames.VisualBasic)] public async Task ChangingPreprocessorDirectivesMayReparse(string source, bool expectReuse, string languageName) @@ -3651,14 +3654,16 @@ public void TestRecoverableSyntaxTreeCSharp() var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); - var text = @"public class C { - public void Method1() {} - public void Method2() {} - public void Method3() {} - public void Method4() {} - public void Method5() {} - public void Method6() {} -}"; + var text = """ + public class C { + public void Method1() {} + public void Method2() {} + public void Method3() {} + public void Method4() {} + public void Method5() {} + public void Method6() {} + } + """; using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution @@ -3675,20 +3680,22 @@ public void TestRecoverableSyntaxTreeVisualBasic() var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); - var text = @"Public Class C - Sub Method1() - End Sub - Sub Method2() - End Sub - Sub Method3() - End Sub - Sub Method4() - End Sub - Sub Method5() - End Sub - Sub Method6() - End Sub -End Class"; + var text = """ + Public Class C + Sub Method1() + End Sub + Sub Method2() + End Sub + Sub Method3() + End Sub + Sub Method4() + End Sub + Sub Method5() + End Sub + Sub Method6() + End Sub + End Class + """; using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution @@ -3962,24 +3969,25 @@ public void TestGetProjectForAssemblySymbol() var did2 = DocumentId.CreateNewId(pid2); var did3 = DocumentId.CreateNewId(pid3); - var text1 = @" -Public Class A -End Class"; + var text1 = """ + Public Class A + End Class + """; - var text2 = @" -Public Class B -End Class -"; + var text2 = """ + Public Class B + End Class + """; - var text3 = @" -public class C : B { -} -"; + var text3 = """ + public class C : B { + } + """; - var text4 = @" -public class C : A { -} -"; + var text4 = """ + public class C : A { + } + """; var solution = new AdhocWorkspace().CurrentSolution .AddProject(pid1, "GooA", "Goo.dll", LanguageNames.VisualBasic) @@ -4612,26 +4620,16 @@ ImmutableArray GetSyntaxTrees() } solution = solution.AddProject(pid, "test", "test.dll", LanguageNames.CSharp); - - var text1 = "public class Test1 {}"; var did1 = DocumentId.CreateNewId(pid); - solution = solution.AddDocument(did1, "test1.cs", text1); - - var text2 = "public class Test2 {}"; + solution = solution.AddDocument(did1, "test1.cs", "public class Test1 {}"); var did2 = DocumentId.CreateNewId(pid); - solution = solution.AddDocument(did2, "test2.cs", text2); - - var text3 = "public class Test3 {}"; + solution = solution.AddDocument(did2, "test2.cs", "public class Test2 {}"); var did3 = DocumentId.CreateNewId(pid); - solution = solution.AddDocument(did3, "test3.cs", text3); - - var text4 = "public class Test4 {}"; + solution = solution.AddDocument(did3, "test3.cs", "public class Test3 {}"); var did4 = DocumentId.CreateNewId(pid); - solution = solution.AddDocument(did4, "test4.cs", text4); - - var text5 = "public class Test5 {}"; + solution = solution.AddDocument(did4, "test4.cs", "public class Test4 {}"); var did5 = DocumentId.CreateNewId(pid); - solution = solution.AddDocument(did5, "test5.cs", text5); + solution = solution.AddDocument(did5, "test5.cs", "public class Test5 {}"); var oldVersion = GetVersion(); @@ -4676,26 +4674,16 @@ public void TestUpdateDocumentsOrderExceptions() var pid = ProjectId.CreateNewId(); solution = solution.AddProject(pid, "test", "test.dll", LanguageNames.CSharp); - - var text1 = "public class Test1 {}"; var did1 = DocumentId.CreateNewId(pid); - solution = solution.AddDocument(did1, "test1.cs", text1); - - var text2 = "public class Test2 {}"; + solution = solution.AddDocument(did1, "test1.cs", "public class Test1 {}"); var did2 = DocumentId.CreateNewId(pid); - solution = solution.AddDocument(did2, "test2.cs", text2); - - var text3 = "public class Test3 {}"; + solution = solution.AddDocument(did2, "test2.cs", "public class Test2 {}"); var did3 = DocumentId.CreateNewId(pid); - solution = solution.AddDocument(did3, "test3.cs", text3); - - var text4 = "public class Test4 {}"; + solution = solution.AddDocument(did3, "test3.cs", "public class Test3 {}"); var did4 = DocumentId.CreateNewId(pid); - solution = solution.AddDocument(did4, "test4.cs", text4); - - var text5 = "public class Test5 {}"; + solution = solution.AddDocument(did4, "test4.cs", "public class Test4 {}"); var did5 = DocumentId.CreateNewId(pid); - solution = solution.AddDocument(did5, "test5.cs", text5); + solution = solution.AddDocument(did5, "test5.cs", "public class Test5 {}"); solution = solution.RemoveDocument(did5); @@ -4870,15 +4858,15 @@ public async Task TestAddingEditorConfigFileWithIsGeneratedCodeOption() solution = solution.AddProject(projectId, "Test", "Test.dll", LanguageNames.CSharp) .WithProjectMetadataReferences(projectId, [NetFramework.mscorlib]) .WithProjectCompilationOptions(projectId, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithNullableContextOptions(NullableContextOptions.Enable)); - var src = @" -class C -{ - void M(C? c) - { - _ = c.ToString(); // warning CS8602: Dereference of a possibly null reference. - } -}"; - solution = solution.AddDocument(sourceDocumentId, "Test.cs", src, filePath: @"Z:\Test.cs"); + solution = solution.AddDocument(sourceDocumentId, "Test.cs", """ + class C + { + void M(C? c) + { + _ = c.ToString(); // warning CS8602: Dereference of a possibly null reference. + } + } + """, filePath: @"Z:\Test.cs"); var originalSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var originalCompilation = await solution.GetProject(projectId).GetCompilationAsync(); diff --git a/src/Workspaces/CoreTest/SolutionTests/TryApplyChangesTests.cs b/src/Workspaces/CoreTest/SolutionTests/TryApplyChangesTests.cs index aaeab33774956..6ad47ca0ddb1f 100644 --- a/src/Workspaces/CoreTest/SolutionTests/TryApplyChangesTests.cs +++ b/src/Workspaces/CoreTest/SolutionTests/TryApplyChangesTests.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Test.Utilities; @@ -121,7 +122,7 @@ public void TryApplyWorksIfAllowingAnyParseOption() Assert.True(workspace.TryApplyChanges( project.WithParseOptions( - project.ParseOptions!.WithFeatures([KeyValuePairUtil.Create("Feature", "")])).Solution)); + project.ParseOptions!.WithFeatures([KeyValuePair.Create("Feature", "")])).Solution)); } [Fact] @@ -136,7 +137,7 @@ public void TryApplyWorksSpecificChangeIsAllowedForParseOption() Assert.True( workspace.TryApplyChanges( - project.WithParseOptions(project.ParseOptions!.WithFeatures([KeyValuePairUtil.Create("Feature", "ExpectedValue")])).Solution)); + project.WithParseOptions(project.ParseOptions!.WithFeatures([KeyValuePair.Create("Feature", "ExpectedValue")])).Solution)); } [Fact] @@ -151,7 +152,7 @@ public void TryApplyWorksThrowsIfChangeIsDisallowedForParseOption() var exception = Assert.Throws( () => workspace.TryApplyChanges( - project.WithParseOptions(project.ParseOptions!.WithFeatures([KeyValuePairUtil.Create("Feature", "WrongThing")])).Solution)); + project.WithParseOptions(project.ParseOptions!.WithFeatures([KeyValuePair.Create("Feature", "WrongThing")])).Solution)); Assert.Equal(WorkspacesResources.Changing_parse_options_is_not_supported, exception.Message); } diff --git a/src/Workspaces/CoreTest/SymbolKeyTests.cs b/src/Workspaces/CoreTest/SymbolKeyTests.cs index 62777fd3d8c80..137f5e5600f8f 100644 --- a/src/Workspaces/CoreTest/SymbolKeyTests.cs +++ b/src/Workspaces/CoreTest/SymbolKeyTests.cs @@ -26,35 +26,34 @@ public sealed class SymbolKeyTests : TestBase [Fact] public void TestVersionMismatch() { - var source = @" - -public class C -{ - public class B { }; - public delegate int D(int v); - - public int F; - public B F2; - public int P { get; set;} - public B P2 { get; set; } - public void M() { }; - public void M(int a) { }; - public void M(int a, string b) { }; - public void M(string a, int b) { }; - public void M(B b) { }; - public int M2() { return 0; } - public int M2(int a) { return 0; } - public int M2(int a, string b) { return 0; } - public int M2(string a, int b) { return 0; } - public B M3() { return default(B); } - public int this[int index] { get { return 0; } } - public int this[int a, int b] { get { return 0; } } - public B this[B b] { get { return b; } } - public event D E; - public event D E2 { add; remove; } - public delegate* Ptr; -} -"; + var source = """ + public class C + { + public class B { }; + public delegate int D(int v); + + public int F; + public B F2; + public int P { get; set;} + public B P2 { get; set; } + public void M() { }; + public void M(int a) { }; + public void M(int a, string b) { }; + public void M(string a, int b) { }; + public void M(B b) { }; + public int M2() { return 0; } + public int M2(int a) { return 0; } + public int M2(int a, string b) { return 0; } + public int M2(string a, int b) { return 0; } + public B M3() { return default(B); } + public int this[int index] { get { return 0; } } + public int this[int a, int b] { get { return 0; } } + public B this[B b] { get { return b; } } + public event D E; + public event D E2 { add; remove; } + public delegate* Ptr; + } + """; var compilation = GetCompilation(source, LanguageNames.CSharp); foreach (var symbol in GetDeclaredSymbols(compilation)) { @@ -82,34 +81,33 @@ static void TestVersion(ISymbol symbol, Compilation compilation, int version) [Fact] public void TestMemberDeclarations() { - var source = @" - -public class C -{ - public class B { }; - public delegate int D(int v); - - public int F; - public B F2; - public int P { get; set;} - public B P2 { get; set; } - public void M() { }; - public void M(int a) { }; - public void M(int a, string b) { }; - public void M(string a, int b) { }; - public void M(B b) { }; - public int M2() { return 0; } - public int M2(int a) { return 0; } - public int M2(int a, string b) { return 0; } - public int M2(string a, int b) { return 0; } - public B M3() { return default(B); } - public int this[int index] { get { return 0; } } - public int this[int a, int b] { get { return 0; } } - public B this[B b] { get { return b; } } - public event D E; - public event D E2 { add; remove; } -} -"; + var source = """ + public class C + { + public class B { }; + public delegate int D(int v); + + public int F; + public B F2; + public int P { get; set;} + public B P2 { get; set; } + public void M() { }; + public void M(int a) { }; + public void M(int a, string b) { }; + public void M(string a, int b) { }; + public void M(B b) { }; + public int M2() { return 0; } + public int M2(int a) { return 0; } + public int M2(int a, string b) { return 0; } + public int M2(string a, int b) { return 0; } + public B M3() { return default(B); } + public int this[int index] { get { return 0; } } + public int this[int a, int b] { get { return 0; } } + public B this[B b] { get { return b; } } + public event D E; + public event D E2 { add; remove; } + } + """; var compilation = GetCompilation(source, LanguageNames.CSharp); TestRoundTrip(GetDeclaredSymbols(compilation), compilation); } @@ -117,14 +115,13 @@ public class B { }; [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70782")] public async Task TestNintNuint() { - var source = @" - -public class C -{ - void M(nint x); - void N(nuint x); -} -"; + var source = """ + public class C + { + void M(nint x); + void N(nuint x); + } + """; var netstandardReferences = await ReferenceAssemblies.NetStandard.NetStandard20.ResolveAsync(LanguageNames.CSharp, cancellationToken: default); var netcoreReferences = await ReferenceAssemblies.Net.Net70.ResolveAsync(LanguageNames.CSharp, cancellationToken: default); @@ -139,13 +136,12 @@ public class C [Fact] public void TestMissingField1_CSharp() { - var source = @" - -public class C -{ - const int; -} -"; + var source = """ + public class C + { + const int; + } + """; var compilation = GetCompilation(source, LanguageNames.CSharp); var symbols = GetDeclaredSymbols(compilation); Assert.True(symbols.Any(s => s is IFieldSymbol { MetadataName: "" })); @@ -155,13 +151,12 @@ public class C [Fact] public void TestMissingField2_CSharp() { - var source = @" - -public class C -{ - int a,; -} -"; + var source = """ + public class C + { + int a,; + } + """; var compilation = GetCompilation(source, LanguageNames.CSharp); var symbols = GetDeclaredSymbols(compilation); Assert.True(symbols.Any(s => s is IFieldSymbol { MetadataName: "" })); @@ -171,13 +166,12 @@ public class C [Fact] public void TestMissingField3_CSharp() { - var source = @" - -public class C -{ - const; -} -"; + var source = """ + public class C + { + const; + } + """; var compilation = GetCompilation(source, LanguageNames.CSharp); var symbols = GetDeclaredSymbols(compilation); Assert.True(symbols.Any(s => s is IFieldSymbol { MetadataName: "" })); @@ -187,12 +181,11 @@ public class C [Fact] public void TestMissingField1_VisualBasic() { - var source = @" - -public class C - constant as integer -end class -"; + var source = """ + public class C + constant as integer + end class + """; var compilation = GetCompilation(source, LanguageNames.VisualBasic); var symbols = GetDeclaredSymbols(compilation); Assert.False(symbols.Any(s => s is IFieldSymbol { MetadataName: "" })); @@ -202,12 +195,11 @@ end class [Fact] public void TestMissingField2_VisualBasic() { - var source = @" - -public class C - dim a, -end class -"; + var source = """ + public class C + dim a, + end class + """; var compilation = GetCompilation(source, LanguageNames.VisualBasic); var symbols = GetDeclaredSymbols(compilation); Assert.True(symbols.Any(s => s is IFieldSymbol { MetadataName: "" })); @@ -217,12 +209,11 @@ end class [Fact] public void TestMissingField3_VisualBasic() { - var source = @" - -public class C - dim a, as integer -end class -"; + var source = """ + public class C + dim a, as integer + end class + """; var compilation = GetCompilation(source, LanguageNames.VisualBasic); var symbols = GetDeclaredSymbols(compilation); Assert.False(symbols.Any(s => s is IFieldSymbol { MetadataName: "" })); @@ -232,12 +223,11 @@ end class [Fact] public void TestMissingField4_VisualBasic() { - var source = @" - -public class C - dim a as integer, -end class -"; + var source = """ + public class C + dim a as integer, + end class + """; var compilation = GetCompilation(source, LanguageNames.VisualBasic); var symbols = GetDeclaredSymbols(compilation); Assert.True(symbols.Any(s => s is IFieldSymbol { MetadataName: "" })); @@ -247,12 +237,11 @@ end class [Fact] public void TestMissingField5_VisualBasic() { - var source = @" - -public class C - constant -end class -"; + var source = """ + public class C + constant + end class + """; var compilation = GetCompilation(source, LanguageNames.VisualBasic); var symbols = GetDeclaredSymbols(compilation); Assert.False(symbols.Any(s => s is IFieldSymbol { MetadataName: "" })); @@ -262,12 +251,11 @@ end class [Fact] public void TestMissingField6_VisualBasic() { - var source = @" - -public class C - constant a, -end class -"; + var source = """ + public class C + constant a, + end class + """; var compilation = GetCompilation(source, LanguageNames.VisualBasic); var symbols = GetDeclaredSymbols(compilation); Assert.True(symbols.Any(s => s is IFieldSymbol { MetadataName: "" })); @@ -277,13 +265,12 @@ end class [Fact] public void TestMissingEvent1_CSharp() { - var source = @" - -public class C -{ - event System.Action; -} -"; + var source = """ + public class C + { + event System.Action; + } + """; var compilation = GetCompilation(source, LanguageNames.CSharp); var symbols = GetDeclaredSymbols(compilation); Assert.True(symbols.Any(s => s is IEventSymbol { MetadataName: "" })); @@ -293,13 +280,12 @@ public class C [Fact] public void TestMissingEvent2_CSharp() { - var source = @" - -public class C -{ - event System.Action a,; -} -"; + var source = """ + public class C + { + event System.Action a,; + } + """; var compilation = GetCompilation(source, LanguageNames.CSharp); var symbols = GetDeclaredSymbols(compilation); Assert.True(symbols.Any(s => s is IEventSymbol { MetadataName: "" })); @@ -309,11 +295,11 @@ public class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14364")] public void TestVBParameterizedEvent() { - var source = @" -Module M - Event E(x As Object) -End Module -"; + var source = """ + Module M + Event E(x As Object) + End Module + """; var compilation = GetCompilation(source, LanguageNames.VisualBasic); TestRoundTrip(GetAllSymbols(compilation.GetSemanticModel(compilation.SyntaxTrees.Single())), compilation); } @@ -321,13 +307,13 @@ End Module [Fact] public void TestNamespaceDeclarations() { - var source = @" -namespace N { } -namespace A.B { } -namespace A { namespace B.C { } } -namespace A { namespace B { namespace C { } } } -namespace A { namespace N { } } -"; + var source = """ + namespace N { } + namespace A.B { } + namespace A { namespace B.C { } } + namespace A { namespace B { namespace C { } } } + namespace A { namespace N { } } + """; var compilation = GetCompilation(source, LanguageNames.CSharp); var symbols = GetDeclaredSymbols(compilation); Assert.Equal(5, symbols.Count); @@ -339,22 +325,22 @@ namespace A { namespace N { } } [Fact] public void TestConstructedTypeReferences() { - var source = @" -using System.Collections.Generic; + var source = """ + using System.Collections.Generic; -public class C -{ - public List G1; - public List> G2; - public Dictionary G3; - public int[] A1; - public int[,] A2; - public int[,,] A3; - public List[] A4; - public int* P1; - public int** p2; -} -"; + public class C + { + public List G1; + public List> G2; + public Dictionary G3; + public int[] A1; + public int[,] A2; + public int[,,] A3; + public List[] A4; + public int* P1; + public int** p2; + } + """; var compilation = GetCompilation(source, LanguageNames.CSharp); TestRoundTrip(GetDeclaredSymbols(compilation).OfType().Select(fs => fs.Type), compilation); } @@ -362,17 +348,17 @@ public class C [Fact] public void TestErrorTypeReferences() { - var source = @" -using System.Collections.Generic; + var source = """ + using System.Collections.Generic; -public class C -{ - public T E1; - public List E2; - public T E3; - public T E4; -} -"; + public class C + { + public T E1; + public List E2; + public T E3; + public T E4; + } + """; var compilation = GetCompilation(source, LanguageNames.CSharp); TestRoundTrip(GetDeclaredSymbols(compilation).OfType().Select(fs => fs.Type), compilation, s => s.ToDisplayString()); } @@ -380,20 +366,20 @@ public class C [Fact] public void TestParameterDeclarations() { - var source = @" -using System.Collections.Generic; + var source = """ + using System.Collections.Generic; -public class C -{ - public void M(int p) { } - public void M(int p1, int p2) { } - public void M(T p) { } - public void M(T[] p) { } - public void M(List p) { } - public void M(T* p) { } - public void M(ref int p) { } -} -"; + public class C + { + public void M(int p) { } + public void M(int p1, int p2) { } + public void M(T p) { } + public void M(T[] p) { } + public void M(List p) { } + public void M(T* p) { } + public void M(ref int p) { } + } + """; var compilation = GetCompilation(source, LanguageNames.CSharp); TestRoundTrip(GetDeclaredSymbols(compilation).OfType().SelectMany(ms => ms.Parameters), compilation); } @@ -401,18 +387,18 @@ public void M(ref int p) { } [Fact] public void TestParameterRename() { - var source1 = @" -public class C -{ - public void M(int a, int b, int c) { } -} -"; - var source2 = @" -public class C -{ - public void M(int a, int x, int c) { } -} -"; + var source1 = """ + public class C + { + public void M(int a, int b, int c) { } + } + """; + var source2 = """ + public class C + { + public void M(int a, int x, int c) { } + } + """; var compilation1 = GetCompilation(source1, LanguageNames.CSharp); var compilation2 = GetCompilation(source2, LanguageNames.CSharp); @@ -425,18 +411,18 @@ public void M(int a, int x, int c) { } [Fact] public void TestParameterReorder() { - var source1 = @" -public class C -{ - public void M(int a, int b, int c) { } -} -"; - var source2 = @" -public class C -{ - public void M(int b, int a, int c) { } -} -"; + var source1 = """ + public class C + { + public void M(int a, int b, int c) { } + } + """; + var source2 = """ + public class C + { + public void M(int b, int a, int c) { } + } + """; var compilation1 = GetCompilation(source1, LanguageNames.CSharp); var compilation2 = GetCompilation(source2, LanguageNames.CSharp); @@ -449,60 +435,60 @@ public void M(int b, int a, int c) { } [Fact] public void TestTypeParameters() { - var source = @" -public class C -{ - public void M() { } - public void M(A a) { } - public void M(int i) { } - public void M(A a, B b) { } - public void M(A a, int i) { } - public void M(int i, B b) { } - public void M(B b, A a) { } - public void M(B b, int i) { } - public void M(int i, A a) { } - public void M(int i, int j) { } - public void M(C c) { } - public int GetInt() { return 0 ; } - public A GetA(A a) { return a; } - public A GetA(A a, B b) { return a; } - public B GetB(A a, B b) { return b; } - public C GetC() { return default(C); } -} + var source = """ + public class C + { + public void M() { } + public void M(A a) { } + public void M(int i) { } + public void M(A a, B b) { } + public void M(A a, int i) { } + public void M(int i, B b) { } + public void M(B b, A a) { } + public void M(B b, int i) { } + public void M(int i, A a) { } + public void M(int i, int j) { } + public void M(C c) { } + public int GetInt() { return 0 ; } + public A GetA(A a) { return a; } + public A GetA(A a, B b) { return a; } + public B GetB(A a, B b) { return b; } + public C GetC() { return default(C); } + } -public class C -{ - public void M() { } - public void M(T t) { } - public void M(A a) { } - public void M(T t, A a) { } - public void M(A a, B b) { } - public void M(B b, A a) { } - public void M(C c) { } - public void M(C c) { } - public T GetT() { return default(T); } - public C GetCT() { return default(C); } - public C GetCInt() { return default(C); } - public C GetCA() { return default(C); } -} + public class C + { + public void M() { } + public void M(T t) { } + public void M(A a) { } + public void M(T t, A a) { } + public void M(A a, B b) { } + public void M(B b, A a) { } + public void M(C c) { } + public void M(C c) { } + public T GetT() { return default(T); } + public C GetCT() { return default(C); } + public C GetCInt() { return default(C); } + public C GetCA() { return default(C); } + } -public class C -{ - public void M() { } - public void M(T t, S s) { } - public void M(A a) { } - public void M(T t, S s, A a) { } - public void M(A a, T t, S s) { } - public void M(A a, B b) { } - public void M(T t, S s, A a, B b) { } - public void M(A a, B b, T t, S s) { } - public T GetT() { return default(T); } - public S GetS() { return default(S); } - public C GetCST() { return default(C); } - public C GetCTS() { return default(C); } - public C GetCTA() { return default(C); } -} -"; + public class C + { + public void M() { } + public void M(T t, S s) { } + public void M(A a) { } + public void M(T t, S s, A a) { } + public void M(A a, T t, S s) { } + public void M(A a, B b) { } + public void M(T t, S s, A a, B b) { } + public void M(A a, B b, T t, S s) { } + public T GetT() { return default(T); } + public S GetS() { return default(S); } + public C GetCST() { return default(C); } + public C GetCTS() { return default(C); } + public C GetCTA() { return default(C); } + } + """; var compilation = GetCompilation(source, LanguageNames.CSharp); TestRoundTrip(GetDeclaredSymbols(compilation), compilation); @@ -511,33 +497,33 @@ public void M(A a, B b, T t, S s) { } [Fact] public void TestLocals() { - var source = @" -using System.Collections.Generic; + var source = """ + using System.Collections.Generic; -public class C -{ - public void M() { - int a, b; - if (a > b) { - int c = a + b; - } + public class C + { + public void M() { + int a, b; + if (a > b) { + int c = a + b; + } - { - string d = ""; - } + { + string d = "; + } - { - double d = 0.0; - } + { + double d = 0.0; + } - { - bool d = false; - } + { + bool d = false; + } - var q = new { }; - } -} -"; + var q = new { }; + } + } + """; var compilation = GetCompilation(source, LanguageNames.CSharp); var symbols = GetDeclaredSymbols(compilation).OfType().SelectMany(ms => GetInteriorSymbols(ms, compilation).OfType()).ToList(); Assert.Equal(7, symbols.Count); @@ -547,19 +533,19 @@ public void M() { [Fact] public void TestLabels() { - var source = @" -using System.Collections.Generic; + var source = """ + using System.Collections.Generic; -public class C -{ - public void M() { - start: goto end; - end: goto start; - end: ; // duplicate label - } - } -} -"; + public class C + { + public void M() { + start: goto end; + end: goto start; + end: ; // duplicate label + } + } + } + """; var compilation = GetCompilation(source, LanguageNames.CSharp); var symbols = GetDeclaredSymbols(compilation).OfType().SelectMany(ms => GetInteriorSymbols(ms, compilation).OfType()).ToList(); Assert.Equal(3, symbols.Count); @@ -569,24 +555,24 @@ public void M() { [Fact] public void TestRangeVariables() { - var source = @" -using System.Collections.Generic; + var source = """ + using System.Collections.Generic; -public class C -{ - public void M() { - int[] xs = new int[] { 1, 2, 3, 4 }; - - { - var q = from x in xs where x > 2 select x; - } + public class C + { + public void M() { + int[] xs = new int[] { 1, 2, 3, 4 }; - { - var q2 = from x in xs where x < 4 select x; - } - } -} -"; + { + var q = from x in xs where x > 2 select x; + } + + { + var q2 = from x in xs where x < 4 select x; + } + } + } + """; var compilation = GetCompilation(source, LanguageNames.CSharp); var symbols = GetDeclaredSymbols(compilation).OfType().SelectMany(ms => GetInteriorSymbols(ms, compilation).OfType()).ToList(); Assert.Equal(2, symbols.Count); @@ -596,24 +582,24 @@ public void M() { [Fact] public void TestMethodReferences() { - var source = @" -public class C -{ - public void M() { } - public void M(int x) { } - public void M2() { } - public void M2(T t) { } - public T M3(T t) { return default(T); } - - public void Test() { - M(): - M(0); - M2(); - M2(0); - var tmp = M3(0); - } -} -"; + var source = """ + public class C + { + public void M() { } + public void M(int x) { } + public void M2() { } + public void M2(T t) { } + public T M3(T t) { return default(T); } + + public void Test() { + M(): + M(0); + M2(); + M2(0); + var tmp = M3(0); + } + } + """; var compilation = GetCompilation(source, LanguageNames.CSharp); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); @@ -624,32 +610,32 @@ public void Test() { [Fact] public void TestExtensionMethodReferences() { - var source = @" -using System; -using System.Collections.Generic; + var source = """ + using System; + using System.Collections.Generic; -public static class E -{ - public static void Z(this C c) { } - public static void Z(this C c, int x) { } - public static void Z(this T t, string y) { } - public static void Z(this T t, T t2) { } - public static void Y(this T t, S other) { } - public static TResult Select(this IEnumerable collection, Func selector) { return null;} -} + public static class E + { + public static void Z(this C c) { } + public static void Z(this C c, int x) { } + public static void Z(this T t, string y) { } + public static void Z(this T t, T t2) { } + public static void Y(this T t, S other) { } + public static TResult Select(this IEnumerable collection, Func selector) { return null;} + } -public class C -{ - public void M() { - this.Z(); - this.Z(1); - this.Z(""test""); - this.Z(this); - this.Y(1.0); - new[] { 1, 2, 3 }.Select( - } -} -"; + public class C + { + public void M() { + this.Z(); + this.Z(1); + this.Z("test"); + this.Z(this); + this.Y(1.0); + new[] { 1, 2, 3 }.Select( + } + } + """; var compilation = GetCompilation(source, LanguageNames.CSharp); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); @@ -662,16 +648,16 @@ public void M() { [Fact] public void TestAliasSymbols() { - var source = @" -using G=System.Collections.Generic; -using GL=System.Collections.Generic.List; + var source = """ + using G=System.Collections.Generic; + using GL=System.Collections.Generic.List; -public class C -{ - public G.List F; - public GL F2; -} -"; + public class C + { + public G.List F; + public GL F2; + } + """; var compilation = GetCompilation(source, LanguageNames.CSharp); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); @@ -690,13 +676,13 @@ public class C [Fact] public void TestDynamicSymbols() { - var source = @" -public class C -{ - public dynamic F; - public dynamic[] F2; -} -"; + var source = """ + public class C + { + public dynamic F; + public dynamic[] F2; + } + """; var compilation = GetCompilation(source, LanguageNames.CSharp); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); @@ -709,12 +695,12 @@ public class C [Fact] public void TestSelfReferentialGenericMethod() { - var source = @" -public class C -{ - public void M() { } -} -"; + var source = """ + public class C + { + public void M() { } + } + """; var compilation = GetCompilation(source, LanguageNames.CSharp); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); @@ -728,11 +714,11 @@ public void M() { } [Fact] public void TestSelfReferentialGenericType() { - var source = @" -public class C -{ -} -"; + var source = """ + public class C + { + } + """; var compilation = GetCompilation(source, LanguageNames.CSharp); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); @@ -746,13 +732,14 @@ public class C [Fact, WorkItem("https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=235912&_a=edit")] public void TestNestedGenericType() { - var source = @" -public class A -{ - public class B - { - } -}"; + var source = """ + public class A + { + public class B + { + } + } + """; var compilation = GetCompilation(source, LanguageNames.CSharp); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); @@ -766,16 +753,17 @@ public class B [Fact, WorkItem("https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=235912&_a=edit")] public void TestNestedGenericType1() { - var source = @" -using System.Collections.Generic; + var source = """ + using System.Collections.Generic; -public class A -{ - public class B - { - void M(T1 t1, T2, T3 t3, List l1, List l2) { } - } -}"; + public class A + { + public class B + { + void M(T1 t1, T2, T3 t3, List l1, List l2) { } + } + } + """; var compilation = GetCompilation(source, LanguageNames.CSharp); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); @@ -845,19 +833,19 @@ public void TestGenericMethodTypeParameter() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11193")] public async Task TestGetInteriorSymbolsDoesNotCrashOnSpeculativeSemanticModel() { - var markup = @" -class C -{ - void goo() - { - System.Func lambda = () => - { - int x; - $$ - } - } -}"; - MarkupTestFile.GetPosition(markup, out var text, out int position); + MarkupTestFile.GetPosition(""" + class C + { + void goo() + { + System.Func lambda = () => + { + int x; + $$ + } + } + } + """, out var text, out int position); var sourceText = SourceText.From(text); var workspace = new AdhocWorkspace(); @@ -889,22 +877,22 @@ void goo() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/11193")] public async Task TestGetInteriorSymbolsDoesNotCrashOnSpeculativeSemanticModel_InProperty() { - var markup = @" -class C -{ - int Prop - { - get - { - System.Func lambda = () => + MarkupTestFile.GetPosition(""" + class C { - int x; - $$ + int Prop + { + get + { + System.Func lambda = () => + { + int x; + $$ + } + } + } } - } - } -}"; - MarkupTestFile.GetPosition(markup, out var text, out int position); + """, out var text, out int position); var sourceText = SourceText.From(text); var workspace = new AdhocWorkspace(); @@ -936,18 +924,18 @@ int Prop [Fact] public void TestGenericMethodTypeParameterMissing1() { - var source1 = @" -public class C -{ - void M(T t) { } -} -"; + var source1 = """ + public class C + { + void M(T t) { } + } + """; - var source2 = @" -public class C -{ -} -"; + var source2 = """ + public class C + { + } + """; var compilation1 = GetCompilation(source1, LanguageNames.CSharp); var compilation2 = GetCompilation(source2, LanguageNames.CSharp); @@ -963,19 +951,20 @@ public class C [Fact, WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems?id=377839")] public void TestConstructedMethodInsideLocalFunctionWithTypeParameters() { - var source = @" -using System.Linq; + var source = """ + using System.Linq; -class C -{ - void Method() - { - object LocalFunction() - { - return Enumerable.Empty(); - } - } -}"; + class C + { + void Method() + { + object LocalFunction() + { + return Enumerable.Empty(); + } + } + } + """; var compilation = GetCompilation(source, LanguageNames.CSharp); var symbols = GetAllSymbols( compilation.GetSemanticModel(compilation.SyntaxTrees.Single()), @@ -1004,15 +993,16 @@ object LocalFunction() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17702")] public void TestTupleWithLocalTypeReferences1() { - var source = @" -using System.Linq; + var source = """ + using System.Linq; -class C -{ - void Method((C, int) t) - { - } -}"; + class C + { + void Method((C, int) t) + { + } + } + """; // Tuples store locations along with them. But we can only recover those locations // if we're re-resolving into a compilation with the same files. var compilation1 = GetCompilation(source, LanguageNames.CSharp, "File1.cs"); @@ -1041,15 +1031,16 @@ void Method((C, int) t) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/17702")] public void TestTupleWithLocalTypeReferences2() { - var source = @" -using System.Linq; + var source = """ + using System.Linq; -class C -{ - void Method((C a, int b) t) - { - } -}"; + class C + { + void Method((C a, int b) t) + { + } + } + """; // Tuples store locations along with them. But we can only recover those locations // if we're re-resolving into a compilation with the same files. var compilation1 = GetCompilation(source, LanguageNames.CSharp, "File1.cs"); @@ -1078,11 +1069,12 @@ void Method((C a, int b) t) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14365")] public void TestErrorType_CSharp() { - var source = @" -class C -{ - int i { get; } -}"; + var source = """ + class C + { + int i { get; } + } + """; // We don't add metadata references, so even `int` will be an error type. var compilation1 = GetCompilation(source, LanguageNames.CSharp, "File1.cs", []); @@ -1114,10 +1106,11 @@ class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14365")] public void TestErrorType_VB() { - var source = @" -class C - public readonly property i as integer -end class"; + var source = """ + class C + public readonly property i as integer + end class + """; // We don't add metadata references, so even `int` will be an error type. var compilation1 = GetCompilation(source, LanguageNames.VisualBasic, "File1.vb", []); @@ -1149,20 +1142,22 @@ public readonly property i as integer [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14365")] public void TestErrorTypeInNestedNamespace() { - var source1 = @" -public class C -{ - public System.Collections.IEnumerable I { get; } -}"; + var source1 = """ + public class C + { + public System.Collections.IEnumerable I { get; } + } + """; - var source2 = @" -class X -{ - void M() - { - new C().I; - } -}"; + var source2 = """ + class X + { + void M() + { + new C().I; + } + } + """; // We don't add metadata to the second compilation, so even `System.Collections.IEnumerable` will be an // error type. @@ -1199,17 +1194,19 @@ void M() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/14365")] public void TestErrorTypeInNestedNamespace_VB() { - var source1 = @" -public class C - public readonly property I as System.Collections.IEnumerable -end class"; - - var source2 = @" -class X - sub M() - dim y = new C().I; - end sub -end class"; + var source1 = """ + public class C + public readonly property I as System.Collections.IEnumerable + end class + """; + + var source2 = """ + class X + sub M() + dim y = new C().I; + end sub + end class + """; // We don't add metadata to the second compilation, so even `System.Collections.IEnumerable` will be an // error type. @@ -1246,12 +1243,13 @@ end sub [Fact] public void TestFunctionPointerTypeSymbols() { - var source = @" -class C -{ - public delegate* ptr1; - public delegate* ptr1; -}"; + var source = """ + class C + { + public delegate* ptr1; + public delegate* ptr1; + } + """; var comp = GetCompilation(source, LanguageNames.CSharp); var fields = GetDeclaredSymbols(comp).OfType().Select(f => f.Type); @@ -1261,11 +1259,12 @@ class C [Fact] public void TestGenericErrorType() { - var source1 = @" -public class C -{ - public Goo G() { } -}"; + var source1 = """ + public class C + { + public Goo G() { } + } + """; // We don't add metadata to the second compilation, so even `System.Collections.IEnumerable` will be an // error type. @@ -1324,81 +1323,81 @@ public void TestCrossLanguageEquality1() [Fact] public void TestBodySymbolsWithEdits() { - var source = @" -using System.Collections.Generic; -using System.Linq; - -public class C -{ - public void M() - { - void InteriorMethod() - { - int a, b; - if (a > b) { - int c = a + b; - } + var source = """ + using System.Collections.Generic; + using System.Linq; + public class C { - string d = ""; - } + public void M() + { + void InteriorMethod() + { + int a, b; + if (a > b) { + int c = a + b; + } - { - double d = 0.0; - } + { + string d = "; + } - { - bool d = false; - } + { + double d = 0.0; + } - var q = new { }; + { + bool d = false; + } - int[] xs = new int[] { 1, 2, 3, 4 }; + var q = new { }; - { - var q = from x in xs where x > 2 select x; - } + int[] xs = new int[] { 1, 2, 3, 4 }; - { - var q2 = from x in xs where x < 4 select x; - } + { + var q = from x in xs where x > 2 select x; + } - start: goto end; - end: goto start; - end: ; // duplicate label + { + var q2 = from x in xs where x < 4 select x; + } - DeepLocalFunction(); + start: goto end; + end: goto start; + end: ; // duplicate label - void DeepLocalFunction() - { - int[] xs = new int[] { 1, 2, 3, 4 }; + DeepLocalFunction(); - { - string d = ""; - } + void DeepLocalFunction() + { + int[] xs = new int[] { 1, 2, 3, 4 }; - { - double d = 0.0; - } + { + string d = "; + } - { - bool d = false; - } + { + double d = 0.0; + } - { - var q = from x in xs where x > 2 select x; - } + { + bool d = false; + } - { - var q2 = from x in xs where x < 4 select x; - } + { + var q = from x in xs where x > 2 select x; + } + + { + var q2 = from x in xs where x < 4 select x; + } - InteriorMethod(); + InteriorMethod(); + } + } + } } - } - } -} -"; + """; var compilation = GetCompilation(source, LanguageNames.CSharp); var methods = GetDeclaredSymbols(compilation).OfType(); var symbols = methods.SelectMany(ms => GetInteriorSymbols(ms, compilation)).Where(s => SymbolKey.IsBodyLevelSymbol(s)).ToList(); diff --git a/src/Workspaces/CoreTest/SyntaxNodeTests.cs b/src/Workspaces/CoreTest/SyntaxNodeTests.cs index a4bb7035948b6..81a812676dd41 100644 --- a/src/Workspaces/CoreTest/SyntaxNodeTests.cs +++ b/src/Workspaces/CoreTest/SyntaxNodeTests.cs @@ -24,8 +24,6 @@ public sealed partial class SyntaxNodeTests : TestBase public async Task TestReplaceOneNodeAsync() { var text = @"public class C { public int X; }"; - var expected = @"public class C { public int Y; }"; - var tree = SyntaxFactory.ParseSyntaxTree(text); var root = tree.GetRoot(); @@ -38,15 +36,13 @@ public async Task TestReplaceOneNodeAsync() var actual = newRoot.ToString(); - Assert.Equal(expected, actual); + Assert.Equal(@"public class C { public int Y; }", actual); } [Fact] public async Task TestReplaceNestedNodesAsync() { var text = @"public class C { public int X; }"; - var expected = @"public class C1 { public int X1; }"; - var tree = SyntaxFactory.ParseSyntaxTree(text); var root = tree.GetRoot(); @@ -72,7 +68,7 @@ public async Task TestReplaceNestedNodesAsync() var actual = newRoot.ToString(); - Assert.Equal(expected, actual); + Assert.Equal(@"public class C1 { public int X1; }", actual); Assert.Equal(computations, nodes.Count); } diff --git a/src/Workspaces/CoreTest/SyntaxPathTests.cs b/src/Workspaces/CoreTest/SyntaxPathTests.cs index 56293bd3a7191..6c431c5e7777c 100644 --- a/src/Workspaces/CoreTest/SyntaxPathTests.cs +++ b/src/Workspaces/CoreTest/SyntaxPathTests.cs @@ -129,19 +129,21 @@ public void TestRoot4() public void TestMethodBodyChange() { var text = -@"namespace N { - class C { - void M1() { - int i1; - } - void M2() { - int i2; - } - void M3() { - int i3; - } - } - }"; + """ + namespace N { + class C { + void M1() { + int i1; + } + void M2() { + int i2; + } + void M3() { + int i3; + } + } + } + """; var tree = SyntaxFactory.ParseSyntaxTree(text); var namespaceDecl = (NamespaceDeclarationSyntax)(tree.GetRoot() as CompilationUnitSyntax).Members[0]; @@ -174,12 +176,14 @@ void M3() { public void TestAddBase() { var text = -@"namespace N { - class C { - } - class D { - } - }"; + """ + namespace N { + class C { + } + class D { + } + } + """; var tree = SyntaxFactory.ParseSyntaxTree(text); var namespaceDecl = (NamespaceDeclarationSyntax)(tree.GetRoot() as CompilationUnitSyntax).Members[0]; @@ -203,16 +207,18 @@ class D { public void TestAddFieldBefore() { var text = -@"namespace N { - class C { - void M1() { - int i1; - } - bool M2() { - int i2; - } - } - }"; + """ + namespace N { + class C { + void M1() { + int i1; + } + bool M2() { + int i2; + } + } + } + """; var tree = SyntaxFactory.ParseSyntaxTree(text); var namespaceDecl = (NamespaceDeclarationSyntax)((CompilationUnitSyntax)tree.GetRoot()).Members[0]; @@ -239,12 +245,14 @@ bool M2() { public void TestChangeType() { var text = -@"namespace N { - class C { - } - class D { - } - }"; + """ + namespace N { + class C { + } + class D { + } + } + """; var tree = SyntaxFactory.ParseSyntaxTree(text); var namespaceDecl = (NamespaceDeclarationSyntax)((CompilationUnitSyntax)tree.GetRoot()).Members[0]; @@ -266,13 +274,15 @@ class D { public void TestChangeType1() { var text = -@"namespace N { - class C { - void Goo(); - } - class D { - } - }"; + """ + namespace N { + class C { + void Goo(); + } + class D { + } + } + """; var tree = SyntaxFactory.ParseSyntaxTree(text); var namespaceDecl = (NamespaceDeclarationSyntax)((CompilationUnitSyntax)tree.GetRoot()).Members[0]; @@ -297,12 +307,14 @@ class D { public void TestWhitespace1() { var text = -@"namespace N { - class C { - } - class D { - } - }"; + """ + namespace N { + class C { + } + class D { + } + } + """; var text2 = text.Replace(" ", " "); var tree = SyntaxFactory.ParseSyntaxTree(text); @@ -327,12 +339,14 @@ class D { public void TestComment() { var text = -@"namespace N { - class C { - } - struct D { - } - }"; + """ + namespace N { + class C { + } + struct D { + } + } + """; var tree = SyntaxFactory.ParseSyntaxTree(text); var namespaceDecl = (NamespaceDeclarationSyntax)((CompilationUnitSyntax)tree.GetRoot()).Members[0]; @@ -356,23 +370,14 @@ struct D { public void TestPP1() { var text = -@"namespace N { - class C { - } - struct D { - } - }"; - - var text2 = -@"namespace N { -#if true - class C { - } - struct D { - } -#endif - }"; - + """ + namespace N { + class C { + } + struct D { + } + } + """; var tree = SyntaxFactory.ParseSyntaxTree(text); var namespaceDecl = (NamespaceDeclarationSyntax)((CompilationUnitSyntax)tree.GetRoot()).Members[0]; var class1 = (TypeDeclarationSyntax)namespaceDecl.Members[0]; @@ -381,7 +386,16 @@ struct D { var path1 = new SyntaxPath(class1); var path2 = new SyntaxPath(class2); - tree = WithReplace(tree, 0, text.Length, text2); + tree = WithReplace(tree, 0, text.Length, """ + namespace N { + #if true + class C { + } + struct D { + } + #endif + } + """); Assert.True(path1.TryResolve(tree, CancellationToken.None, out SyntaxNode n1)); Assert.True(path2.TryResolve(tree, CancellationToken.None, out SyntaxNode n2)); diff --git a/src/Workspaces/CoreTest/SyntaxReferenceTests.cs b/src/Workspaces/CoreTest/SyntaxReferenceTests.cs index 149f40c6c9b2b..95012e75d01bd 100644 --- a/src/Workspaces/CoreTest/SyntaxReferenceTests.cs +++ b/src/Workspaces/CoreTest/SyntaxReferenceTests.cs @@ -3,15 +3,15 @@ // See the LICENSE file in the project root for more information. using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; -using Microsoft.CodeAnalysis.Shared.Extensions; using CS = Microsoft.CodeAnalysis.CSharp; using VB = Microsoft.CodeAnalysis.VisualBasic; -using System.Threading.Tasks; -using System.Threading; namespace Microsoft.CodeAnalysis.UnitTests; @@ -46,11 +46,11 @@ private static Solution AddSingleFileVisualBasicProject(Solution solution, strin public async Task TestCSharpReferenceToZeroWidthNode() { using var workspace = CreateWorkspace(); - var solution = AddSingleFileCSharpProject(workspace.CurrentSolution, @" -public class C<> -{ -} -"); + var solution = AddSingleFileCSharpProject(workspace.CurrentSolution, """ + public class C<> + { + } + """); var tree = await solution.Projects.First().Documents.First().GetRequiredSyntaxTreeAsync(CancellationToken.None); @@ -69,10 +69,10 @@ public class C<> public async Task TestVisualBasicReferenceToZeroWidthNode() { using var workspace = CreateWorkspace(); - var solution = AddSingleFileVisualBasicProject(workspace.CurrentSolution, @" -Public Class C(Of ) -End Class -"); + var solution = AddSingleFileVisualBasicProject(workspace.CurrentSolution, """ + Public Class C(Of ) + End Class + """); var tree = await solution.Projects.First().Documents.First().GetRequiredSyntaxTreeAsync(CancellationToken.None); @@ -91,13 +91,13 @@ End Class public async Task TestCSharpReferenceToNodeInStructuredTrivia() { using var workspace = CreateWorkspace(); - var solution = AddSingleFileCSharpProject(workspace.CurrentSolution, @" -#if true || true -public class C -{ -} -#endif -"); + var solution = AddSingleFileCSharpProject(workspace.CurrentSolution, """ + #if true || true + public class C + { + } + #endif + """); var tree = await solution.Projects.First().Documents.First().GetRequiredSyntaxTreeAsync(CancellationToken.None); // find binary node that is part of #if directive @@ -114,12 +114,12 @@ public class C public async Task TestVisualBasicReferenceToNodeInStructuredTrivia() { using var workspace = CreateWorkspace(); - var solution = AddSingleFileVisualBasicProject(workspace.CurrentSolution, @" -#If True Or True Then -Public Class C -End Class -#End If -"); + var solution = AddSingleFileVisualBasicProject(workspace.CurrentSolution, """ + #If True Or True Then + Public Class C + End Class + #End If + """); var tree = await solution.Projects.First().Documents.First().GetRequiredSyntaxTreeAsync(CancellationToken.None); @@ -137,13 +137,13 @@ End Class public async Task TestCSharpReferenceToZeroWidthNodeInStructuredTrivia() { using var workspace = CreateWorkspace(); - var solution = AddSingleFileCSharpProject(workspace.CurrentSolution, @" -#if true || -public class C -{ -} -#endif -"); + var solution = AddSingleFileCSharpProject(workspace.CurrentSolution, """ + #if true || + public class C + { + } + #endif + """); var tree = await solution.Projects.First().Documents.First().GetRequiredSyntaxTreeAsync(CancellationToken.None); @@ -165,12 +165,12 @@ public class C public async System.Threading.Tasks.Task TestVisualBasicReferenceToZeroWidthNodeInStructuredTriviaAsync() { using var workspace = CreateWorkspace(); - var solution = AddSingleFileVisualBasicProject(workspace.CurrentSolution, @" -#If (True Or ) Then -Public Class C -End Class -#End If -"); + var solution = AddSingleFileVisualBasicProject(workspace.CurrentSolution, """ + #If (True Or ) Then + Public Class C + End Class + #End If + """); var tree = await solution.Projects.First().Documents.First().GetRequiredSyntaxTreeAsync(CancellationToken.None); diff --git a/src/Workspaces/CoreTest/UtilityTest/AsyncLazyTests.cs b/src/Workspaces/CoreTest/UtilityTest/AsyncLazyTests.cs index c9424a771e567..e0ee92943f719 100644 --- a/src/Workspaces/CoreTest/UtilityTest/AsyncLazyTests.cs +++ b/src/Workspaces/CoreTest/UtilityTest/AsyncLazyTests.cs @@ -183,7 +183,7 @@ private static void GetValueOrGetValueAsyncThrowsCorrectExceptionDuringCancellat try { doGetValue(lazy, cancellationTokenSource.Token); - AssertEx.Fail(nameof(AsyncLazy.GetValue) + " did not throw an exception."); + AssertEx.Fail(nameof(AsyncLazy<>.GetValue) + " did not throw an exception."); } catch (OperationCanceledException oce) { @@ -211,7 +211,7 @@ public void GetValueAsyncThatIsCancelledReturnsTaskCancelledWithCorrectToken() try { task.Wait(); - AssertEx.Fail(nameof(AsyncLazy.GetValueAsync) + " did not throw an exception."); + AssertEx.Fail(nameof(AsyncLazy<>.GetValueAsync) + " did not throw an exception."); } catch (AggregateException ex) { diff --git a/src/Workspaces/CoreTest/UtilityTest/BKTreeTests.cs b/src/Workspaces/CoreTest/UtilityTest/BKTreeTests.cs index 83ccf241c462b..ae7506121e820 100644 --- a/src/Workspaces/CoreTest/UtilityTest/BKTreeTests.cs +++ b/src/Workspaces/CoreTest/UtilityTest/BKTreeTests.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Collections; using Roslyn.Utilities; using Xunit; diff --git a/src/Workspaces/CoreTest/UtilityTest/DocumentationCommentIdTests.cs b/src/Workspaces/CoreTest/UtilityTest/DocumentationCommentIdTests.cs index 766f5027b446b..3b4a6af829766 100644 --- a/src/Workspaces/CoreTest/UtilityTest/DocumentationCommentIdTests.cs +++ b/src/Workspaces/CoreTest/UtilityTest/DocumentationCommentIdTests.cs @@ -60,28 +60,28 @@ private static void CheckReferenceId(string expectedId, INamespaceOrTypeSymbol s [Fact] public void TestCSharpTypeIds() { - var compilation = CreateCSharpCompilation(@" -enum Color { Red, Blue, Green } -namespace Acme -{ - interface IProcess { } - struct ValueType - { - private int total; - } - class Widget : IProcess - { - public class NestedClass { } - public interface IMenuItem { } - public delegate void Del(int i); - public enum Direction { North, South, East, West } - } - class MyList - { - class Helper { } - } -} -"); + var compilation = CreateCSharpCompilation(""" + enum Color { Red, Blue, Green } + namespace Acme + { + interface IProcess { } + struct ValueType + { + private int total; + } + class Widget : IProcess + { + public class NestedClass { } + public interface IMenuItem { } + public delegate void Del(int i); + public enum Direction { North, South, East, West } + } + class MyList + { + class Helper { } + } + } + """); CheckDeclarationId("T:Color", compilation.GetTypeByMetadataName("Color"), compilation); CheckDeclarationId("T:Acme.IProcess", compilation.GetTypeByMetadataName("Acme.IProcess"), compilation); CheckDeclarationId("T:Acme.ValueType", compilation.GetTypeByMetadataName("Acme.ValueType"), compilation); @@ -97,32 +97,32 @@ class Helper { } [Fact] public void TestCSharpFields() { - var compilation = CreateCSharpCompilation(@" -enum Color { Red, Blue, Green } -namespace Acme -{ - interface IProcess { } - struct ValueType - { - private int total; - } - class Widget : IProcess - { - public class NestedClass - { - private int value; - } - private string message; - private static Color defaultColor; - private const double PI = 3.14159; - protected readonly double monthlyAverage; - private long[] array1; - private widget[,] array2; - private unsafe int *pCount; - private unsafe float **ppValues; - } -} -"); + var compilation = CreateCSharpCompilation(""" + enum Color { Red, Blue, Green } + namespace Acme + { + interface IProcess { } + struct ValueType + { + private int total; + } + class Widget : IProcess + { + public class NestedClass + { + private int value; + } + private string message; + private static Color defaultColor; + private const double PI = 3.14159; + protected readonly double monthlyAverage; + private long[] array1; + private widget[,] array2; + private unsafe int *pCount; + private unsafe float **ppValues; + } + } + """); CheckDeclarationId("F:Acme.ValueType.total", compilation, s => s.Name == "total"); CheckDeclarationId("F:Acme.Widget.NestedClass.value", compilation, s => s.Name == "value"); @@ -139,18 +139,18 @@ public class NestedClass [Fact] public void TestCSharpConstructors() { - var compilation = CreateCSharpCompilation(@" -namespace Acme -{ - interface IProcess { } - class Widget : IProcess - { - static Widget() { } - public Widget() { } - public Widget(string s) { } - } -} -"); + var compilation = CreateCSharpCompilation(""" + namespace Acme + { + interface IProcess { } + class Widget : IProcess + { + static Widget() { } + public Widget() { } + public Widget(string s) { } + } + } + """); CheckDeclarationId("M:Acme.Widget.#cctor", compilation, s => s.MethodKind == MethodKind.StaticConstructor); CheckDeclarationId("M:Acme.Widget.#ctor", compilation, s => s.MethodKind == MethodKind.Constructor && s.Parameters.Length == 0); @@ -160,16 +160,16 @@ public Widget(string s) { } [Fact] public void TestCSharpDestructors() { - var compilation = CreateCSharpCompilation(@" -namespace Acme -{ - interface IProcess { } - class Widget : IProcess - { - ~Widget() { } - } -} -"); + var compilation = CreateCSharpCompilation(""" + namespace Acme + { + interface IProcess { } + class Widget : IProcess + { + ~Widget() { } + } + } + """); CheckDeclarationId("M:Acme.Widget.Finalize", compilation, s => s.MethodKind == MethodKind.Destructor); } @@ -177,41 +177,41 @@ class Widget : IProcess [Fact] public void TestCSharpMethods() { - var compilation = CreateCSharpCompilation(@" -enum Color { Red, Blue, Green } -namespace Acme -{ - struct ValueType - { - public void M(int i) { } - } - interface IProcess { } - class Widget : IProcess - { - public class NestedClass - { - public void M(int i) { } - } - public static void M0() { } - public void M1(char c, out float f, ref ValueType v) { } - public void M2(short[] x1, int[,] x2, long[][] x3) { } - public void M3(long[][] x3, Widget[][,,] x4) { } - public void M4(char *pc, Color **pf) { } - public void M5(void *pv, double *[][,] pd) { } - public void M6(int i, params object[] args) { } - } - class MyList - { - public void Test(T t) { } - } - class UseList - { - public void Process(MyList list) { } - public MyList GetValues(T inputValue) { return null; } - public void Process2(MyList list) { } - } -} -"); + var compilation = CreateCSharpCompilation(""" + enum Color { Red, Blue, Green } + namespace Acme + { + struct ValueType + { + public void M(int i) { } + } + interface IProcess { } + class Widget : IProcess + { + public class NestedClass + { + public void M(int i) { } + } + public static void M0() { } + public void M1(char c, out float f, ref ValueType v) { } + public void M2(short[] x1, int[,] x2, long[][] x3) { } + public void M3(long[][] x3, Widget[][,,] x4) { } + public void M4(char *pc, Color **pf) { } + public void M5(void *pv, double *[][,] pd) { } + public void M6(int i, params object[] args) { } + } + class MyList + { + public void Test(T t) { } + } + class UseList + { + public void Process(MyList list) { } + public MyList GetValues(T inputValue) { return null; } + public void Process2(MyList list) { } + } + } + """); CheckDeclarationId("M:Acme.ValueType.M(System.Int32)", compilation, s => s.Name == "M" && s.Parameters is [{ Type.Name: "Int32" }]); CheckDeclarationId("M:Acme.Widget.NestedClass.M(System.Int32)", compilation, s => s.Name == "M" && s.Parameters is [{ Type.Name: "Int32" }]); @@ -231,18 +231,18 @@ public void Process2(MyList list) { } [Fact] public void TestCSharpPropertiesAndIndexers() { - var compilation = CreateCSharpCompilation(@" -namespace Acme -{ - interface IProcess { } - class Widget : IProcess - { - public int Width { get { return 0; } set { } } - public int this[int i] { get { return 0; } set { } } - public int this[string s, int i] { get { return 0; } set { } } - } -} -"); + var compilation = CreateCSharpCompilation(""" + namespace Acme + { + interface IProcess { } + class Widget : IProcess + { + public int Width { get { return 0; } set { } } + public int this[int i] { get { return 0; } set { } } + public int this[string s, int i] { get { return 0; } set { } } + } + } + """); CheckDeclarationIdExact("P:Acme.Widget.Width", compilation, p => p.Name == "Width"); CheckDeclarationIdExact("P:Acme.Widget.Item(System.Int32)", compilation, p => p.Parameters.Length == 1); @@ -252,31 +252,31 @@ class Widget : IProcess [Fact] public void TestCSharpEvents() { - var compilation = CreateCSharpCompilation(@" -namespace Acme -{ - class Widget : IProcess - { - public delegate void Del(int i); - public event Del AnEvent; - } -} -"); + var compilation = CreateCSharpCompilation(""" + namespace Acme + { + class Widget : IProcess + { + public delegate void Del(int i); + public event Del AnEvent; + } + } + """); CheckDeclarationId("E:Acme.Widget.AnEvent", compilation, e => e.Name == "AnEvent"); } [Fact] public void TestCSharpUnaryOperators() { - var compilation = CreateCSharpCompilation(@" -namespace Acme -{ - class Widget : IProcess - { - public static Widget operator+(Widget x) { return x; } - } -} -"); + var compilation = CreateCSharpCompilation(""" + namespace Acme + { + class Widget : IProcess + { + public static Widget operator+(Widget x) { return x; } + } + } + """); CheckDeclarationId("M:Acme.Widget.op_UnaryPlus(Acme.Widget)", compilation, m => m.MethodKind == MethodKind.UserDefinedOperator && m.Parameters.Length == 1); } @@ -284,15 +284,15 @@ class Widget : IProcess [Fact] public void TestCSharpBinaryOperators() { - var compilation = CreateCSharpCompilation(@" -namespace Acme -{ - class Widget : IProcess - { - public static Widget operator+(Widget x1, Widget x2) { return x1; } - } -} -"); + var compilation = CreateCSharpCompilation(""" + namespace Acme + { + class Widget : IProcess + { + public static Widget operator+(Widget x1, Widget x2) { return x1; } + } + } + """); CheckDeclarationId("M:Acme.Widget.op_Addition(Acme.Widget,Acme.Widget)", compilation, m => m.MethodKind == MethodKind.UserDefinedOperator && m.Parameters.Length == 2); } @@ -300,16 +300,16 @@ class Widget : IProcess [Fact] public void TestCSharpConversionOperators() { - var compilation = CreateCSharpCompilation(@" -namespace Acme -{ - class Widget : IProcess - { - public static explicit operator int(Widget x) { return 0; } - public static implicit operator long(Widget x) { return 0; } - } -} -"); + var compilation = CreateCSharpCompilation(""" + namespace Acme + { + class Widget : IProcess + { + public static explicit operator int(Widget x) { return 0; } + public static implicit operator long(Widget x) { return 0; } + } + } + """); CheckDeclarationId("M:Acme.Widget.op_Explicit(Acme.Widget)~System.Int32", compilation, m => m.MethodKind == MethodKind.Conversion && m.Parameters.Length == 1 && m.ReturnType.Name == "Int32"); CheckDeclarationId("M:Acme.Widget.op_Implicit(Acme.Widget)~System.Int64", compilation, m => m.MethodKind == MethodKind.Conversion && m.Parameters.Length == 1 && m.ReturnType.Name == "Int64"); @@ -318,19 +318,19 @@ class Widget : IProcess [Fact] public void TestTypeReferences() { - var compilation = CreateCSharpCompilation(@" -namespace Acme -{ - class OuterType - { - class InnerType - { - } - - public void M(D d) { } - } -} -"); + var compilation = CreateCSharpCompilation(""" + namespace Acme + { + class OuterType + { + class InnerType + { + } + + public void M(D d) { } + } + } + """); var outerType = compilation.GetTypeByMetadataName("Acme.OuterType`1"); var innerType = compilation.GetTypeByMetadataName("Acme.OuterType`1+InnerType`2"); diff --git a/src/Workspaces/CoreTest/UtilityTest/DocumentationCommentTests.cs b/src/Workspaces/CoreTest/UtilityTest/DocumentationCommentTests.cs index 41d92db58e7aa..2482e7591e5fd 100644 --- a/src/Workspaces/CoreTest/UtilityTest/DocumentationCommentTests.cs +++ b/src/Workspaces/CoreTest/UtilityTest/DocumentationCommentTests.cs @@ -25,14 +25,16 @@ public void ParseEmptyXmlFragment() public void ParseFullTag() { var comment = DocumentationComment.FromXmlFragment( - @"Hello, world! - 42. - 43. - goo.Bar(); - A goo. - A type. - An exception - A remark"); + """ + Hello, world! + 42. + 43. + goo.Bar(); + A goo. + A type. + An exception + A remark + """); Assert.Equal("Hello, world!", comment.SummaryText); Assert.Equal("42.", comment.ReturnsText); @@ -51,14 +53,16 @@ public void ParseFullTag() public void ParseFullTagEmptyValues() { var comment = DocumentationComment.FromXmlFragment( - @" - - - - - - - "); + """ + + + + + + + + + """); Assert.Equal(string.Empty, comment.SummaryText); Assert.Equal(string.Empty, comment.ReturnsText); @@ -85,10 +89,12 @@ public void ParseTagWithMultipleSummaries() [WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522741")] public void ParseTagWithMultiLineComments() { - var comment = DocumentationComment.FromXmlFragment(@" -Summary 1 -Summary 2 -"); + var comment = DocumentationComment.FromXmlFragment(""" + + Summary 1 + Summary 2 + + """); Assert.Equal("Summary 1 Summary 2", comment.SummaryText); } @@ -106,9 +112,11 @@ public void ParseInvalidXML() public void PreserveParameterNameOrdering() { var comment = DocumentationComment.FromXmlFragment( -@"Z -A -B"); + """ + Z + A + B + """); Assert.Equal("z", comment.ParameterNames[0]); Assert.Equal("a", comment.ParameterNames[1]); @@ -119,9 +127,11 @@ public void PreserveParameterNameOrdering() public void PreserveTypeParameterNameOrdering() { var comment = DocumentationComment.FromXmlFragment( -@"Z -A -B"); + """ + Z + A + B + """); Assert.Equal("z", comment.TypeParameterNames[0]); Assert.Equal("a", comment.TypeParameterNames[1]); @@ -132,9 +142,11 @@ public void PreserveTypeParameterNameOrdering() public void PreserveExceptionTypeOrdering() { var comment = DocumentationComment.FromXmlFragment( -@"Z -A -B"); + """ + Z + A + B + """); Assert.Equal("z", comment.ExceptionTypes[0]); Assert.Equal("a", comment.ExceptionTypes[1]); @@ -145,9 +157,11 @@ public void PreserveExceptionTypeOrdering() public void UnknownTag() { var comment = DocumentationComment.FromXmlFragment( -@"This is a summary. -This is another summary. -The param named 'a'"); + """ + This is a summary. + This is another summary. + The param named 'a' + """); Assert.Equal("This is a summary.", comment.SummaryText); Assert.Equal("a", comment.ParameterNames[0]); @@ -158,9 +172,11 @@ public void UnknownTag() public void TextOutsideTag() { var comment = DocumentationComment.FromXmlFragment( -@"This is a summary. -This is random top-level text. -The param named 'a'"); + """ + This is a summary. + This is random top-level text. + The param named 'a' + """); Assert.Equal("This is a summary.", comment.SummaryText); Assert.Equal("a", comment.ParameterNames[0]); @@ -171,11 +187,13 @@ This is random top-level text. public void SingleTopLevelTag() { var comment = DocumentationComment.FromXmlFragment( -@" -This is a summary. -This is random top-level text. -The param named 'a' -"); + """ + + This is a summary. + This is random top-level text. + The param named 'a' + + """); Assert.Equal("This is a summary.", comment.SummaryText); Assert.Equal("a", comment.ParameterNames[0]); @@ -186,8 +204,10 @@ This is random top-level text. public void MultipleParamsWithSameName() { var comment = DocumentationComment.FromXmlFragment( -@"This comment should be retained. -This comment should not be retained."); + """ + This comment should be retained. + This comment should not be retained. + """); Assert.Equal(1, comment.ParameterNames.Length); Assert.Equal("a", comment.ParameterNames[0]); @@ -198,8 +218,10 @@ public void MultipleParamsWithSameName() public void MultipleTypeParamsWithSameName() { var comment = DocumentationComment.FromXmlFragment( -@"This comment should be retained. -This comment should not be retained."); + """ + This comment should be retained. + This comment should not be retained. + """); Assert.Equal(1, comment.TypeParameterNames.Length); Assert.Equal("a", comment.TypeParameterNames[0]); @@ -210,10 +232,12 @@ public void MultipleTypeParamsWithSameName() public void MultipleExceptionsWithSameName() { var comment = DocumentationComment.FromXmlFragment( -@"First A description -First B description -Second A description -Second B description"); + """ + First A description + First B description + Second A description + Second B description + """); Assert.Equal(2, comment.ExceptionTypes.Length); Assert.Equal("A", comment.ExceptionTypes[0]); @@ -258,36 +282,42 @@ public void ReservedXmlNamespaceInName() [Fact, WorkItem("https://github.com/dotnet/roslyn/pull/18901")] public void TrimEachLine() { - var multiLineText = @" + var multiLineText = """ -Hello - World . -+ -....... + Hello + World . + + + ....... -123 - 1"; + 123 - var fullXml = $@"{multiLineText} - {multiLineText} - {multiLineText} - {multiLineText} - {multiLineText} - {multiLineText} - {multiLineText}"; + 1 + """; - var expected = @"Hello - World . -+ -....... -123 - 1"; + var fullXml = $""" + {multiLineText} + {multiLineText} + {multiLineText} + {multiLineText} + {multiLineText} + {multiLineText} + {multiLineText} + """; + + var expected = """ + Hello + World . + + + ....... + 123 + 1 + """; var comment = DocumentationComment.FromXmlFragment(fullXml); @@ -303,38 +333,44 @@ World . [Fact, WorkItem("https://github.com/dotnet/roslyn/pull/18901")] public void TrimEachLineCommonOffset() { - var multiLineText = @" + var multiLineText = """ + - Hello - World . - + - ....... - + Hello + World . + + + ....... + - 123 + 123 - 1"; + 1 + """; - var fullXml = $@"{multiLineText} - {multiLineText} - {multiLineText} - {multiLineText} - {multiLineText} - {multiLineText} - {multiLineText}"; + var fullXml = $""" + {multiLineText} + {multiLineText} + {multiLineText} + {multiLineText} + {multiLineText} + {multiLineText} + {multiLineText} + """; - var expected = @"Hello - World . -+ -....... + var expected = """ + Hello + World . + + + ....... - 123 - 1"; + 123 + 1 + """; var comment = DocumentationComment.FromXmlFragment(fullXml); diff --git a/src/Workspaces/CoreTest/WorkspaceServiceTests/GlobalOptionServiceTests.cs b/src/Workspaces/CoreTest/WorkspaceServiceTests/GlobalOptionServiceTests.cs index f21ae85b54be9..e2682d72a3ddf 100644 --- a/src/Workspaces/CoreTest/WorkspaceServiceTests/GlobalOptionServiceTests.cs +++ b/src/Workspaces/CoreTest/WorkspaceServiceTests/GlobalOptionServiceTests.cs @@ -37,13 +37,13 @@ public void LegacyGlobalOptions_SetGet() optionService.SetOptions( [], - [KeyValuePairUtil.Create(optionKey, (object?)2)]); + [KeyValuePair.Create(optionKey, (object?)2)]); Assert.Equal(2, optionService.GetExternallyDefinedOption(optionKey)); optionService.SetOptions( [], - [KeyValuePairUtil.Create(optionKey, (object?)3)]); + [KeyValuePair.Create(optionKey, (object?)3)]); Assert.Equal(3, optionService.GetExternallyDefinedOption(optionKey)); } @@ -121,7 +121,7 @@ public void InternallyDefinedOption() // Update global option indirectly via legacy service updates current solutions. optionService.SetOptions( - [KeyValuePairUtil.Create(new OptionKey2(FormattingOptions2.NewLine, "lang"), (object?)"NEW_LINE")], + [KeyValuePair.Create(new OptionKey2(FormattingOptions2.NewLine, "lang"), (object?)"NEW_LINE")], []); Assert.Equal("NEW_LINE", workspace1.CurrentSolution.Options.GetOption(perLanguageOptionKey)); @@ -180,9 +180,9 @@ public void GlobalOptions() globalOptions.SetGlobalOptions( [ - KeyValuePairUtil.Create(new OptionKey2(option1), (object?)5), - KeyValuePairUtil.Create(new OptionKey2(option2), (object?)6), - KeyValuePairUtil.Create(new OptionKey2(option3), (object?)3), + KeyValuePair.Create(new OptionKey2(option1), (object?)5), + KeyValuePair.Create(new OptionKey2(option2), (object?)6), + KeyValuePair.Create(new OptionKey2(option3), (object?)3), ]); AssertEx.Equal( diff --git a/src/Workspaces/CoreTest/WorkspaceTests/WorkspaceTests.cs b/src/Workspaces/CoreTest/WorkspaceTests/WorkspaceTests.cs index f196d2294437f..be4982b6c49ae 100644 --- a/src/Workspaces/CoreTest/WorkspaceTests/WorkspaceTests.cs +++ b/src/Workspaces/CoreTest/WorkspaceTests/WorkspaceTests.cs @@ -4,13 +4,13 @@ #nullable disable +using System; using Microsoft.CodeAnalysis.Host; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; -using Xunit; -using System; -using Microsoft.CodeAnalysis.Options; using Roslyn.Test.Utilities; +using Xunit; namespace Microsoft.CodeAnalysis.UnitTests; @@ -199,7 +199,19 @@ public void SetOptions_PublicGlobalOptions() { foreach (var language in OptionsTestHelpers.GetApplicableLanguages(option)) { - Assert.Equal(value, workspace2.Options.GetOption(new OptionKey(option, language))); + var currentValue = workspace2.Options.GetOption(new OptionKey(option, language)); + if (!Equals(currentValue, value)) + { + if (currentValue.GetType().IsEnum && value.GetType().IsEnum) + { + // Enum values are not equal if they are different instances, even if they have the same value. + Assert.Equal(Convert.ToInt32(currentValue), Convert.ToInt32(value)); + } + else + { + Assert.Equal(value, currentValue); + } + } } } } diff --git a/src/Workspaces/CoreTestUtilities/GlobalizationUtilities.cs b/src/Workspaces/CoreTestUtilities/GlobalizationUtilities.cs index 70799b4ef2fd2..be399bcdf62cc 100644 --- a/src/Workspaces/CoreTestUtilities/GlobalizationUtilities.cs +++ b/src/Workspaces/CoreTestUtilities/GlobalizationUtilities.cs @@ -5,6 +5,7 @@ using System.Globalization; namespace Microsoft.CodeAnalysis.UnitTests; + internal sealed class GlobalizationUtilities { /// diff --git a/src/Workspaces/CoreTestUtilities/Options/OptionsTestHelpers.cs b/src/Workspaces/CoreTestUtilities/Options/OptionsTestHelpers.cs index 8249bd2870215..028b36ae741b7 100644 --- a/src/Workspaces/CoreTestUtilities/Options/OptionsTestHelpers.cs +++ b/src/Workspaces/CoreTestUtilities/Options/OptionsTestHelpers.cs @@ -7,6 +7,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Diagnostics; diff --git a/src/Workspaces/CoreTestUtilities/Remote/TestSerializerService.cs b/src/Workspaces/CoreTestUtilities/Remote/TestSerializerService.cs index 89309f9a843c1..e924f85e54e59 100644 --- a/src/Workspaces/CoreTestUtilities/Remote/TestSerializerService.cs +++ b/src/Workspaces/CoreTestUtilities/Remote/TestSerializerService.cs @@ -37,7 +37,7 @@ internal sealed class TestSerializerService( .Add(TestBase.ValueTupleRef, nameof(TestBase.ValueTupleRef)) .Add(TestBase.SystemRuntimeFacadeRef, nameof(TestBase.SystemRuntimeFacadeRef)); private static readonly ImmutableDictionary s_wellKnownReferences = ImmutableDictionary.Create() - .AddRange(s_wellKnownReferenceNames.Select(pair => KeyValuePairUtil.Create(pair.Value!, pair.Key))); + .AddRange(s_wellKnownReferenceNames.Select(pair => KeyValuePair.Create(pair.Value!, pair.Key))); private readonly ConcurrentDictionary _sharedTestGeneratorReferences = sharedTestGeneratorReferences; diff --git a/src/Workspaces/CoreTestUtilities/TestAnalyzerReferenceByLanguage.cs b/src/Workspaces/CoreTestUtilities/TestAnalyzerReferenceByLanguage.cs index 97d967d22f136..b9b6f8de25e68 100644 --- a/src/Workspaces/CoreTestUtilities/TestAnalyzerReferenceByLanguage.cs +++ b/src/Workspaces/CoreTestUtilities/TestAnalyzerReferenceByLanguage.cs @@ -51,7 +51,7 @@ public override ImmutableArray GetAnalyzers(string language) public TestAnalyzerReferenceByLanguage WithAdditionalAnalyzers(string language, IEnumerable analyzers) { var newAnalyzersMap = ImmutableDictionary.CreateRange( - _analyzersMap.Select(kvp => KeyValuePairUtil.Create( + _analyzersMap.Select(kvp => KeyValuePair.Create( kvp.Key, kvp.Key == language ? kvp.Value.AddRange(analyzers) : kvp.Value))); return new(newAnalyzersMap); } diff --git a/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace_XmlConsumption.cs b/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace_XmlConsumption.cs index 383d24c93fa07..12fcab3bafc6c 100644 --- a/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace_XmlConsumption.cs +++ b/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace_XmlConsumption.cs @@ -284,7 +284,7 @@ private static ParseOptions GetPreProcessorParseOptions(string language, XAttrib else if (language == LanguageNames.VisualBasic) { return new VisualBasicParseOptions(preprocessorSymbols: preprocessorSymbolsAttribute.Value - .Split(',').Select(v => KeyValuePairUtil.Create(v.Split('=').ElementAt(0), (object)v.Split('=').ElementAt(1))).ToImmutableArray()); + .Split(',').Select(v => KeyValuePair.Create(v.Split('=').ElementAt(0), (object)v.Split('=').ElementAt(1))).ToImmutableArray()); } else { @@ -302,7 +302,7 @@ private static ParseOptions GetParseOptionsWithFeatures(ParseOptions parseOption var key = split[0]; var value = split.Length == 2 ? split[1] : "true"; - return KeyValuePairUtil.Create(key, value); + return KeyValuePair.Create(key, value); }); return parseOptions.WithFeatures(features); diff --git a/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace`1.cs b/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace`1.cs index 67e34ce4b0c87..b3090fef39cfd 100644 --- a/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace`1.cs +++ b/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace`1.cs @@ -118,7 +118,7 @@ public void SetAnalyzerFallbackOptions(string language, params (string name, str s => s.WithFallbackAnalyzerOptions(s.FallbackAnalyzerOptions.SetItem(language, StructuredAnalyzerConfigOptions.Create( new DictionaryAnalyzerConfigOptions( - options.Select(static o => KeyValuePairUtil.Create(o.name, o.value)).ToImmutableDictionary())))), + options.Select(static o => KeyValuePair.Create(o.name, o.value)).ToImmutableDictionary())))), changeKind: WorkspaceChangeKind.SolutionChanged); } diff --git a/src/Workspaces/MSBuild/BuildHost/BuildHost.cs b/src/Workspaces/MSBuild/BuildHost/BuildHost.cs index 92abd8997af61..c121ef1bb646f 100644 --- a/src/Workspaces/MSBuild/BuildHost/BuildHost.cs +++ b/src/Workspaces/MSBuild/BuildHost/BuildHost.cs @@ -4,8 +4,8 @@ using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.IO; +using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; diff --git a/src/Workspaces/MSBuild/BuildHost/Microsoft.CodeAnalysis.Workspaces.MSBuild.BuildHost.csproj b/src/Workspaces/MSBuild/BuildHost/Microsoft.CodeAnalysis.Workspaces.MSBuild.BuildHost.csproj index b5114733f03aa..e7679eeaee2bb 100644 --- a/src/Workspaces/MSBuild/BuildHost/Microsoft.CodeAnalysis.Workspaces.MSBuild.BuildHost.csproj +++ b/src/Workspaces/MSBuild/BuildHost/Microsoft.CodeAnalysis.Workspaces.MSBuild.BuildHost.csproj @@ -68,7 +68,6 @@ - diff --git a/src/Workspaces/MSBuild/Core/MSBuild/MSBuildProjectLoader.Worker.cs b/src/Workspaces/MSBuild/Core/MSBuild/MSBuildProjectLoader.Worker.cs index 83177f2becfc0..4f92c9fea189b 100644 --- a/src/Workspaces/MSBuild/Core/MSBuild/MSBuildProjectLoader.Worker.cs +++ b/src/Workspaces/MSBuild/Core/MSBuild/MSBuildProjectLoader.Worker.cs @@ -36,11 +36,6 @@ private sealed partial class Worker /// private readonly ImmutableArray _requestedProjectPaths; - /// - /// Global MSBuild properties to set when loading projects. - /// - private readonly ImmutableDictionary _globalProperties; - /// /// Map of s, project paths, and output file paths. /// @@ -78,7 +73,6 @@ public Worker( BuildHostProcessManager buildHostProcessManager, ImmutableArray requestedProjectPaths, string baseDirectory, - ImmutableDictionary globalProperties, ProjectMap? projectMap, IProgress? progress, DiagnosticReportingOptions requestedProjectOptions, @@ -92,7 +86,6 @@ public Worker( _buildHostProcessManager = buildHostProcessManager; _baseDirectory = baseDirectory; _requestedProjectPaths = requestedProjectPaths; - _globalProperties = globalProperties; _projectMap = projectMap ?? ProjectMap.Create(); _progress = progress; _requestedProjectOptions = requestedProjectOptions; diff --git a/src/Workspaces/MSBuild/Core/MSBuild/MSBuildProjectLoader.Worker_ResolveReferences.cs b/src/Workspaces/MSBuild/Core/MSBuild/MSBuildProjectLoader.Worker_ResolveReferences.cs index d97c1c7cdb846..ca00abece4f0e 100644 --- a/src/Workspaces/MSBuild/Core/MSBuild/MSBuildProjectLoader.Worker_ResolveReferences.cs +++ b/src/Workspaces/MSBuild/Core/MSBuild/MSBuildProjectLoader.Worker_ResolveReferences.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; diff --git a/src/Workspaces/MSBuild/Core/MSBuild/MSBuildProjectLoader.cs b/src/Workspaces/MSBuild/Core/MSBuild/MSBuildProjectLoader.cs index 97cebc35edcb0..042bf7b41b698 100644 --- a/src/Workspaces/MSBuild/Core/MSBuild/MSBuildProjectLoader.cs +++ b/src/Workspaces/MSBuild/Core/MSBuild/MSBuildProjectLoader.cs @@ -10,7 +10,6 @@ using Microsoft.Build.Framework; using Microsoft.CodeAnalysis.Host; using Roslyn.Utilities; -using MSB = Microsoft.Build; namespace Microsoft.CodeAnalysis.MSBuild; @@ -193,7 +192,6 @@ public async Task LoadSolutionInfoAsync( projectPaths, // TryGetAbsoluteSolutionPath should not return an invalid path baseDirectory: Path.GetDirectoryName(absoluteSolutionPath)!, - Properties, projectMap: null, progress, requestedProjectOptions: reportingOptions, @@ -254,7 +252,6 @@ public async Task> LoadProjectInfoAsync( buildHostProcessManager, requestedProjectPaths: [projectFilePath], baseDirectory: Directory.GetCurrentDirectory(), - globalProperties: Properties, projectMap, progress, requestedProjectOptions, diff --git a/src/Workspaces/MSBuild/Core/MSBuild/MSBuildWorkspace.cs b/src/Workspaces/MSBuild/Core/MSBuild/MSBuildWorkspace.cs index 18ce7a0dd306f..2422b71abd8e5 100644 --- a/src/Workspaces/MSBuild/Core/MSBuild/MSBuildWorkspace.cs +++ b/src/Workspaces/MSBuild/Core/MSBuild/MSBuildWorkspace.cs @@ -698,6 +698,38 @@ protected override void ApplyAnalyzerReferenceRemoved(ProjectId projectId, Analy this.OnAnalyzerReferenceRemoved(projectId, analyzerReference); } + #endregion + + #region temporarily exposed internal methods for prototyping purpose only + internal void OnDocumentRemovedInternal(DocumentId documentId) + { + this.OnDocumentRemoved(documentId); + } + + internal void OnAdditionalDocumentRemovedInternal(DocumentId documentId) + { + this.OnAdditionalDocumentRemoved(documentId); + } + + internal void OnAnalyzerConfigDocumentRemovedInternal(DocumentId documentId) + { + this.OnAnalyzerConfigDocumentRemoved(documentId); + } + + internal void OnDocumentTextChangedInternal(DocumentId documentId, SourceText newText) + { + this.OnDocumentTextChanged(documentId, newText, PreservationMode.PreserveValue); + } + + internal void OnAdditionalDocumentTextChangedInternal(DocumentId documentId, SourceText newText) + { + this.OnAdditionalDocumentTextChanged(documentId, newText, PreservationMode.PreserveValue); + } + + internal void OnAnalyzerConfigDocumentTextChangedInternal(DocumentId documentId, SourceText newText) + { + this.OnAnalyzerConfigDocumentTextChanged(documentId, newText, PreservationMode.PreserveValue); + } + #endregion } -#endregion diff --git a/src/Workspaces/MSBuild/Core/MSBuild/ProjectFileExtensionRegistry.cs b/src/Workspaces/MSBuild/Core/MSBuild/ProjectFileExtensionRegistry.cs index 331656d56dc5e..ebe1ad1ca1f04 100644 --- a/src/Workspaces/MSBuild/Core/MSBuild/ProjectFileExtensionRegistry.cs +++ b/src/Workspaces/MSBuild/Core/MSBuild/ProjectFileExtensionRegistry.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; +using System.Linq; using Microsoft.CodeAnalysis.Host; using Roslyn.Utilities; diff --git a/src/Workspaces/MSBuild/Core/Microsoft.CodeAnalysis.Workspaces.MSBuild.csproj b/src/Workspaces/MSBuild/Core/Microsoft.CodeAnalysis.Workspaces.MSBuild.csproj index fb6da908cb6bc..7cca46fc60ebd 100644 --- a/src/Workspaces/MSBuild/Core/Microsoft.CodeAnalysis.Workspaces.MSBuild.csproj +++ b/src/Workspaces/MSBuild/Core/Microsoft.CodeAnalysis.Workspaces.MSBuild.csproj @@ -70,6 +70,7 @@ + - - - diff --git a/src/Workspaces/Remote/ServiceHub/Services/DiagnosticAnalyzer/DiagnosticComputer.cs b/src/Workspaces/Remote/ServiceHub/Services/DiagnosticAnalyzer/DiagnosticComputer.cs index 9f3b0470ee343..1002f75adb039 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/DiagnosticAnalyzer/DiagnosticComputer.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/DiagnosticAnalyzer/DiagnosticComputer.cs @@ -5,10 +5,10 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; -using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics.Telemetry; using Microsoft.CodeAnalysis.Host; @@ -17,9 +17,7 @@ using Microsoft.CodeAnalysis.Telemetry; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Workspaces.Diagnostics; -using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; -using static Microsoft.VisualStudio.Threading.ThreadingTools; namespace Microsoft.CodeAnalysis.Remote.Diagnostics; diff --git a/src/Workspaces/Remote/ServiceHub/Services/DiagnosticAnalyzer/RemoteDiagnosticAnalyzerService.cs b/src/Workspaces/Remote/ServiceHub/Services/DiagnosticAnalyzer/RemoteDiagnosticAnalyzerService.cs index 14d7aeb454b01..37861b2ddac56 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/DiagnosticAnalyzer/RemoteDiagnosticAnalyzerService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/DiagnosticAnalyzer/RemoteDiagnosticAnalyzerService.cs @@ -4,12 +4,13 @@ using System.Collections.Immutable; using System.Diagnostics; +using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Remote.Diagnostics; -using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Telemetry; using RoslynLogger = Microsoft.CodeAnalysis.Internal.Log.Logger; diff --git a/src/Workspaces/Remote/ServiceHub/Services/EditAndContinue/RemoteEditAndContinueService.cs b/src/Workspaces/Remote/ServiceHub/Services/EditAndContinue/RemoteEditAndContinueService.cs index 4d3382c362072..06ad70bc0c782 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/EditAndContinue/RemoteEditAndContinueService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/EditAndContinue/RemoteEditAndContinueService.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Immutable; -using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Contracts.EditAndContinue; diff --git a/src/Workspaces/Remote/ServiceHub/Services/SemanticSearch/RemoteSemanticSearchService.cs b/src/Workspaces/Remote/ServiceHub/Services/SemanticSearch/RemoteSemanticSearchService.cs index 465b6965a227f..4ad6ce988f5a9 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/SemanticSearch/RemoteSemanticSearchService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/SemanticSearch/RemoteSemanticSearchService.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; diff --git a/src/Workspaces/Remote/ServiceHubTest/TelemetryLoggerTests.cs b/src/Workspaces/Remote/ServiceHubTest/TelemetryLoggerTests.cs index 3e06fc0844d1f..dd92413a633b2 100644 --- a/src/Workspaces/Remote/ServiceHubTest/TelemetryLoggerTests.cs +++ b/src/Workspaces/Remote/ServiceHubTest/TelemetryLoggerTests.cs @@ -6,9 +6,8 @@ using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Internal.Log; -using Microsoft.CodeAnalysis.Telemetry; -using Microsoft.VisualStudio.Telemetry; using Microsoft.CodeAnalysis.UnitTests.Logging; +using Microsoft.VisualStudio.Telemetry; using Roslyn.Test.Utilities; using Xunit; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CSharpCompilerExtensions.projitems b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CSharpCompilerExtensions.projitems index a567cd03b6aca..fd9f9aba7d1f9 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CSharpCompilerExtensions.projitems +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CSharpCompilerExtensions.projitems @@ -97,6 +97,7 @@ + diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeGeneration/CSharpSyntaxTokens.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeGeneration/CSharpSyntaxTokens.cs index a19a899cef01d..34bdac702acb6 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeGeneration/CSharpSyntaxTokens.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeGeneration/CSharpSyntaxTokens.cs @@ -32,7 +32,9 @@ internal static class CSharpSyntaxTokens public static readonly SyntaxToken EndOfDocumentationCommentToken = Token(SyntaxKind.EndOfDocumentationCommentToken); public static readonly SyntaxToken EqualsToken = Token(SyntaxKind.EqualsToken); public static readonly SyntaxToken ExplicitKeyword = Token(SyntaxKind.ExplicitKeyword); +#if !ROSLYN_4_12_OR_LOWER public static readonly SyntaxToken ExtensionKeyword = Token(SyntaxKind.ExtensionKeyword); +#endif public static readonly SyntaxToken ExternKeyword = Token(SyntaxKind.ExternKeyword); public static readonly SyntaxToken FileKeyword = Token(SyntaxKind.FileKeyword); public static readonly SyntaxToken FixedKeyword = Token(SyntaxKind.FixedKeyword); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/CSharpCodeStyleOptions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/CSharpCodeStyleOptions.cs index c484d9584c3a2..1c633ea244817 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/CSharpCodeStyleOptions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/CSharpCodeStyleOptions.cs @@ -252,7 +252,7 @@ private static Option2> CreatePreferE public static Option2> AllowEmbeddedStatementsOnSameLine { get; } = CreateOption( CodeStyleOptionGroups.NewLinePreferences, "csharp_style_allow_embedded_statements_on_same_line_experimental", - CSharpSimplifierOptions.Default.AllowEmbeddedStatementsOnSameLine); + CSharpSimplifierOptions.Default.AllowEmbeddedStatementsOnSameLine); public static Option2> AllowBlankLinesBetweenConsecutiveBraces { get; } = CreateOption( CodeStyleOptionGroups.NewLinePreferences, diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/PreferBracesPreference.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/PreferBracesPreference.cs index c7ad48c4a15b7..fbafb7fe53e91 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/PreferBracesPreference.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/PreferBracesPreference.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#pragma warning disable CS1574 // XML comment has cref attribute that could not be resolved + using System.Xml.Linq; using Microsoft.CodeAnalysis.CSharp.CodeStyle; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/TypeStyle/TypeStyleHelper.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/TypeStyle/TypeStyleHelper.cs index 3e8d199278fcd..9a0982f7ab78b 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/TypeStyle/TypeStyleHelper.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/TypeStyle/TypeStyleHelper.cs @@ -10,7 +10,6 @@ using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeStyle.TypeStyle; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/EmbeddedLanguages/VirtualChars/CSharpVirtualCharService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/EmbeddedLanguages/VirtualChars/CSharpVirtualCharService.cs index 3b5dfe1af5ffd..ef1afc430db50 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/EmbeddedLanguages/VirtualChars/CSharpVirtualCharService.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/EmbeddedLanguages/VirtualChars/CSharpVirtualCharService.cs @@ -178,7 +178,7 @@ private static VirtualCharSequence TryConvertMultiLineRawStringToVirtualChars( // they start right after some `{...}` interpolation var isFirstChunk = parentExpression is LiteralExpressionSyntax || - (parentExpression is InterpolatedStringExpressionSyntax { Contents: var contents } && contents.First() == token.GetRequiredParent()); + (parentExpression is InterpolatedStringExpressionSyntax { Contents: [var firstContent, ..] } && firstContent == token.GetRequiredParent()); if (parentExpression.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)) return default; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/MemberDeclarationSyntaxExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/MemberDeclarationSyntaxExtensions.cs index 65d821e8e421b..66e1943fd0716 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/MemberDeclarationSyntaxExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/MemberDeclarationSyntaxExtensions.cs @@ -32,7 +32,9 @@ public static SyntaxToken GetNameToken(this MemberDeclarationSyntax member) case SyntaxKind.EnumDeclaration: return ((EnumDeclarationSyntax)member).Identifier; case SyntaxKind.ClassDeclaration: +#if !ROSLYN_4_12_OR_LOWER case SyntaxKind.ExtensionBlockDeclaration: +#endif case SyntaxKind.InterfaceDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: @@ -72,7 +74,9 @@ public static int GetArity(this MemberDeclarationSyntax member) switch (member.Kind()) { case SyntaxKind.ClassDeclaration: +#if !ROSLYN_4_12_OR_LOWER case SyntaxKind.ExtensionBlockDeclaration: +#endif case SyntaxKind.InterfaceDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: @@ -97,7 +101,9 @@ public static int GetArity(this MemberDeclarationSyntax member) switch (member.Kind()) { case SyntaxKind.ClassDeclaration: +#if !ROSLYN_4_12_OR_LOWER case SyntaxKind.ExtensionBlockDeclaration: +#endif case SyntaxKind.InterfaceDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SyntaxNodeExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SyntaxNodeExtensions.cs index 4ef6792ee67c5..cb6f346f48e6b 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SyntaxNodeExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SyntaxNodeExtensions.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#pragma warning disable CS1574 // XML comment has cref attribute that could not be resolved + using System; using System.Collections.Generic; using System.Collections.Immutable; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SyntaxTriviaListExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SyntaxTriviaListExtensions.cs index 3bd36245042af..7e25ed75db023 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SyntaxTriviaListExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SyntaxTriviaListExtensions.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Collections; using Roslyn.Utilities; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpFormattingOptions2.Parsers.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpFormattingOptions2.Parsers.cs index aefefa5b1a696..f357a04a31304 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpFormattingOptions2.Parsers.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpFormattingOptions2.Parsers.cs @@ -89,16 +89,16 @@ internal static string ToEditorConfigValue(NewLineBeforeOpenBracePlacement value _ => ToEditorConfigFlagList((int)value, static v => s_newLineOptionsEditorConfigMap[(NewLineBeforeOpenBracePlacement)v]) }; - internal static BinaryOperatorSpacingOptions ParseEditorConfigSpacingAroundBinaryOperator(string binaryOperatorSpacingValue) - => s_binaryOperatorSpacingOptionsEditorConfigMap.TryGetValue(binaryOperatorSpacingValue.Trim(), out var value) ? value : BinaryOperatorSpacingOptions.Single; + internal static BinaryOperatorSpacingOptionsInternal ParseEditorConfigSpacingAroundBinaryOperator(string binaryOperatorSpacingValue) + => s_binaryOperatorSpacingOptionsEditorConfigMap.TryGetValue(binaryOperatorSpacingValue.Trim(), out var value) ? value : BinaryOperatorSpacingOptionsInternal.Single; - private static string GetSpacingAroundBinaryOperatorEditorConfigString(BinaryOperatorSpacingOptions value) + private static string GetSpacingAroundBinaryOperatorEditorConfigString(BinaryOperatorSpacingOptionsInternal value) => s_binaryOperatorSpacingOptionsEditorConfigMap.TryGetKey(value, out var key) ? key : ""; - internal static LabelPositionOptions ParseEditorConfigLabelPositioning(string labelIndentationValue) - => s_labelPositionOptionsEditorConfigMap.TryGetValue(labelIndentationValue.Trim(), out var value) ? value : LabelPositionOptions.NoIndent; + internal static LabelPositionOptionsInternal ParseEditorConfigLabelPositioning(string labelIndentationValue) + => s_labelPositionOptionsEditorConfigMap.TryGetValue(labelIndentationValue.Trim(), out var value) ? value : LabelPositionOptionsInternal.NoIndent; - private static string GetLabelPositionOptionEditorConfigString(LabelPositionOptions value) + private static string GetLabelPositionOptionEditorConfigString(LabelPositionOptionsInternal value) => s_labelPositionOptionsEditorConfigMap.TryGetKey(value, out var key) ? key : ""; internal static bool DetermineIfIgnoreSpacesAroundVariableDeclarationIsSet(string value) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpFormattingOptions2.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpFormattingOptions2.cs index 6f77426cb7fb1..812aeb23db8ca 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpFormattingOptions2.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpFormattingOptions2.cs @@ -3,13 +3,10 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; -using Roslyn.Utilities; +using System.Collections.Generic; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Formatting; - -#if CODE_STYLE -using CSharpWorkspaceResources = Microsoft.CodeAnalysis.CSharp.CSharpCodeStyleResources; -#endif +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Formatting; @@ -24,42 +21,42 @@ internal static partial class CSharpFormattingOptions2 private static readonly BidirectionalMap s_spacingWithinParenthesisOptionsEditorConfigMap = new( [ - KeyValuePairUtil.Create("expressions", SpacePlacementWithinParentheses.Expressions), - KeyValuePairUtil.Create("type_casts", SpacePlacementWithinParentheses.TypeCasts), - KeyValuePairUtil.Create("control_flow_statements", SpacePlacementWithinParentheses.ControlFlowStatements), + KeyValuePair.Create("expressions", SpacePlacementWithinParentheses.Expressions), + KeyValuePair.Create("type_casts", SpacePlacementWithinParentheses.TypeCasts), + KeyValuePair.Create("control_flow_statements", SpacePlacementWithinParentheses.ControlFlowStatements), ]); - private static readonly BidirectionalMap s_binaryOperatorSpacingOptionsEditorConfigMap = + private static readonly BidirectionalMap s_binaryOperatorSpacingOptionsEditorConfigMap = new( [ - KeyValuePairUtil.Create("ignore", BinaryOperatorSpacingOptions.Ignore), - KeyValuePairUtil.Create("none", BinaryOperatorSpacingOptions.Remove), - KeyValuePairUtil.Create("before_and_after", BinaryOperatorSpacingOptions.Single), + KeyValuePair.Create("ignore", BinaryOperatorSpacingOptionsInternal.Ignore), + KeyValuePair.Create("none", BinaryOperatorSpacingOptionsInternal.Remove), + KeyValuePair.Create("before_and_after", BinaryOperatorSpacingOptionsInternal.Single), ]); - private static readonly BidirectionalMap s_labelPositionOptionsEditorConfigMap = + private static readonly BidirectionalMap s_labelPositionOptionsEditorConfigMap = new( [ - KeyValuePairUtil.Create("flush_left", LabelPositionOptions.LeftMost), - KeyValuePairUtil.Create("no_change", LabelPositionOptions.NoIndent), - KeyValuePairUtil.Create("one_less_than_current", LabelPositionOptions.OneLess), + KeyValuePair.Create("flush_left", LabelPositionOptionsInternal.LeftMost), + KeyValuePair.Create("no_change", LabelPositionOptionsInternal.NoIndent), + KeyValuePair.Create("one_less_than_current", LabelPositionOptionsInternal.OneLess), ]); private static readonly BidirectionalMap s_legacyNewLineOptionsEditorConfigMap = new( [ - KeyValuePairUtil.Create("object_collection_array_initalizers", NewLineBeforeOpenBracePlacement.ObjectCollectionArrayInitializers), + KeyValuePair.Create("object_collection_array_initalizers", NewLineBeforeOpenBracePlacement.ObjectCollectionArrayInitializers), ]); private static readonly BidirectionalMap s_newLineOptionsEditorConfigMap = new( [ - KeyValuePairUtil.Create("all", NewLineBeforeOpenBracePlacement.All), - KeyValuePairUtil.Create("accessors", NewLineBeforeOpenBracePlacement.Accessors), - KeyValuePairUtil.Create("types", NewLineBeforeOpenBracePlacement.Types), - KeyValuePairUtil.Create("methods", NewLineBeforeOpenBracePlacement.Methods), - KeyValuePairUtil.Create("properties", NewLineBeforeOpenBracePlacement.Properties), - KeyValuePairUtil.Create("anonymous_methods", NewLineBeforeOpenBracePlacement.AnonymousMethods), - KeyValuePairUtil.Create("control_blocks", NewLineBeforeOpenBracePlacement.ControlBlocks), - KeyValuePairUtil.Create("anonymous_types", NewLineBeforeOpenBracePlacement.AnonymousTypes), - KeyValuePairUtil.Create("object_collection_array_initializers", NewLineBeforeOpenBracePlacement.ObjectCollectionArrayInitializers), - KeyValuePairUtil.Create("lambdas", NewLineBeforeOpenBracePlacement.LambdaExpressionBody), + KeyValuePair.Create("all", NewLineBeforeOpenBracePlacement.All), + KeyValuePair.Create("accessors", NewLineBeforeOpenBracePlacement.Accessors), + KeyValuePair.Create("types", NewLineBeforeOpenBracePlacement.Types), + KeyValuePair.Create("methods", NewLineBeforeOpenBracePlacement.Methods), + KeyValuePair.Create("properties", NewLineBeforeOpenBracePlacement.Properties), + KeyValuePair.Create("anonymous_methods", NewLineBeforeOpenBracePlacement.AnonymousMethods), + KeyValuePair.Create("control_blocks", NewLineBeforeOpenBracePlacement.ControlBlocks), + KeyValuePair.Create("anonymous_types", NewLineBeforeOpenBracePlacement.AnonymousTypes), + KeyValuePair.Create("object_collection_array_initializers", NewLineBeforeOpenBracePlacement.ObjectCollectionArrayInitializers), + KeyValuePair.Create("lambdas", NewLineBeforeOpenBracePlacement.LambdaExpressionBody), ]); #endregion @@ -181,10 +178,10 @@ private static Option2 CreateOption(OptionGroup group, string name, T defa CSharpSyntaxFormattingOptions.SpacingDefault.HasFlag(SpacePlacement.BeforeSemicolonsInForStatement)) .WithPublicOption(PublicFeatureName, "SpaceBeforeSemicolonsInForStatement"); - public static Option2 SpacingAroundBinaryOperator { get; } = CreateOption( + public static Option2 SpacingAroundBinaryOperator { get; } = CreateOption( CSharpFormattingOptionGroups.Spacing, "csharp_space_around_binary_operators", CSharpSyntaxFormattingOptions.Default.SpacingAroundBinaryOperator, - new EditorConfigValueSerializer( + new EditorConfigValueSerializer( s => ParseEditorConfigSpacingAroundBinaryOperator(s), GetSpacingAroundBinaryOperatorEditorConfigString)) .WithPublicOption(PublicFeatureName, "SpacingAroundBinaryOperator"); @@ -214,10 +211,10 @@ private static Option2 CreateOption(OptionGroup group, string name, T defa CSharpSyntaxFormattingOptions.IndentationDefault.HasFlag(IndentationPlacement.SwitchCaseContentsWhenBlock)) .WithPublicOption(PublicFeatureName, "IndentSwitchCaseSectionWhenBlock"); - public static Option2 LabelPositioning { get; } = CreateOption( + public static Option2 LabelPositioning { get; } = CreateOption( CSharpFormattingOptionGroups.Indentation, "csharp_indent_labels", CSharpSyntaxFormattingOptions.Default.LabelPositioning, - new EditorConfigValueSerializer( + new EditorConfigValueSerializer( s => ParseEditorConfigLabelPositioning(s), GetLabelPositionOptionEditorConfigString)) .WithPublicOption(PublicFeatureName, "LabelPositioning"); @@ -290,11 +287,7 @@ private static Option2 CreateOption(OptionGroup group, string name, T defa internal static readonly ImmutableArray UndocumentedOptions = [CollectionExpressionWrappingLength]; } -#if CODE_STYLE -internal enum LabelPositionOptions -#else -public enum LabelPositionOptions -#endif +internal enum LabelPositionOptionsInternal { /// Placed in the Zeroth column of the text editor LeftMost = 0, @@ -306,11 +299,7 @@ public enum LabelPositionOptions NoIndent = 2 } -#if CODE_STYLE -internal enum BinaryOperatorSpacingOptions -#else -public enum BinaryOperatorSpacingOptions -#endif +internal enum BinaryOperatorSpacingOptionsInternal { /// Single Spacing Single = 0, diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpSyntaxFormattingOptions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpSyntaxFormattingOptions.cs index fdedddbada910..9a15d6f96a3e6 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpSyntaxFormattingOptions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpSyntaxFormattingOptions.cs @@ -53,9 +53,9 @@ internal sealed record class CSharpSyntaxFormattingOptions : SyntaxFormattingOpt public static readonly CSharpSyntaxFormattingOptions Default = new(); [DataMember] public SpacePlacement Spacing { get; init; } = SpacingDefault; - [DataMember] public BinaryOperatorSpacingOptions SpacingAroundBinaryOperator { get; init; } = BinaryOperatorSpacingOptions.Single; + [DataMember] public BinaryOperatorSpacingOptionsInternal SpacingAroundBinaryOperator { get; init; } = BinaryOperatorSpacingOptionsInternal.Single; [DataMember] public NewLinePlacement NewLines { get; init; } = NewLinesDefault; - [DataMember] public LabelPositionOptions LabelPositioning { get; init; } = LabelPositionOptions.OneLess; + [DataMember] public LabelPositionOptionsInternal LabelPositioning { get; init; } = LabelPositionOptionsInternal.OneLess; [DataMember] public IndentationPlacement Indentation { get; init; } = IndentationDefault; [DataMember] public bool WrappingKeepStatementsOnSingleLine { get; init; } = true; [DataMember] public bool WrappingPreserveSingleLine { get; init; } = true; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/TriviaDataFactory.CodeShapeAnalyzer.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/TriviaDataFactory.CodeShapeAnalyzer.cs index 714be8d8f31b1..a76712cb714ec 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/TriviaDataFactory.CodeShapeAnalyzer.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/TriviaDataFactory.CodeShapeAnalyzer.cs @@ -7,7 +7,6 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Formatting; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/IndentBlockFormattingRule.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/IndentBlockFormattingRule.cs index d136d9b319edd..81012f4414972 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/IndentBlockFormattingRule.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/IndentBlockFormattingRule.cs @@ -109,7 +109,7 @@ private void AddSwitchIndentationOperation(List list, Synt var switchStatement = (SwitchStatementSyntax)node.Parent; var lastSection = switchStatement.Sections.Last() == node; - if (section.Statements.Count == 0) + if (section.Statements is not ([var firstStatement, ..] and [.., var lastStatement])) { // even if there is no statement under section, we still want indent operation var lastTokenOfLabel = section.Labels.Last().GetLastToken(includeZeroWidth: true); @@ -121,8 +121,8 @@ private void AddSwitchIndentationOperation(List list, Synt return; } - var startToken = section.Statements.First().GetFirstToken(includeZeroWidth: true); - var endToken = section.Statements.Last().GetLastToken(includeZeroWidth: true); + var startToken = firstStatement.GetFirstToken(includeZeroWidth: true); + var endToken = lastStatement.GetLastToken(includeZeroWidth: true); // see whether we are the last statement var span = CommonFormattingHelpers.GetSpanIncludingTrailingAndLeadingTriviaOfAdjacentTokens(startToken, endToken); @@ -136,11 +136,11 @@ private void AddLabelIndentationOperation(List list, Synta // label statement if (node is LabeledStatementSyntax labeledStatement) { - if (_options.LabelPositioning == LabelPositionOptions.OneLess) + if (_options.LabelPositioning == LabelPositionOptionsInternal.OneLess) { AddUnindentBlockOperation(list, labeledStatement.Identifier, labeledStatement.ColonToken); } - else if (_options.LabelPositioning == LabelPositionOptions.LeftMost) + else if (_options.LabelPositioning == LabelPositionOptionsInternal.LeftMost) { AddAbsoluteZeroIndentBlockOperation(list, labeledStatement.Identifier, labeledStatement.ColonToken); } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/SpacingFormattingRule.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/SpacingFormattingRule.cs index ccf10986adf30..1588776f29edb 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/SpacingFormattingRule.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/SpacingFormattingRule.cs @@ -333,9 +333,9 @@ previousToken.Parent is AssignmentExpressionSyntax || { switch (_options.SpacingAroundBinaryOperator) { - case BinaryOperatorSpacingOptions.Single: + case BinaryOperatorSpacingOptionsInternal.Single: return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine); - case BinaryOperatorSpacingOptions.Remove: + case BinaryOperatorSpacingOptionsInternal.Remove: if (currentKind == SyntaxKind.IsKeyword || currentKind == SyntaxKind.AsKeyword || currentKind == SyntaxKind.AndKeyword || @@ -352,7 +352,7 @@ previousToken.Parent is AssignmentExpressionSyntax || { return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine); } - case BinaryOperatorSpacingOptions.Ignore: + case BinaryOperatorSpacingOptionsInternal.Ignore: return CreateAdjustSpacesOperation(0, AdjustSpacesOption.PreserveSpaces); default: System.Diagnostics.Debug.Assert(false, "Invalid BinaryOperatorSpacingOptions"); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/SuppressFormattingRule.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/SuppressFormattingRule.cs index 153e48b8a9c08..a4e91ffcd8e60 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/SuppressFormattingRule.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/SuppressFormattingRule.cs @@ -220,9 +220,9 @@ private static void AddSpecificNodesSuppressOperations(ArrayBuilder : AbstractPrecedenceService where TSyntax : SyntaxNode { - protected AbstractCSharpPrecedenceService() - { - } - public sealed override PrecedenceKind GetPrecedenceKind(OperatorPrecedence precedence) - { - switch (precedence) + => precedence switch { - case OperatorPrecedence.NullCoalescing: return PrecedenceKind.Coalesce; - case OperatorPrecedence.ConditionalOr: - case OperatorPrecedence.ConditionalAnd: return PrecedenceKind.Logical; - case OperatorPrecedence.LogicalOr: - case OperatorPrecedence.LogicalXor: - case OperatorPrecedence.LogicalAnd: return PrecedenceKind.Bitwise; - case OperatorPrecedence.Equality: return PrecedenceKind.Equality; - case OperatorPrecedence.RelationalAndTypeTesting: return PrecedenceKind.Relational; - case OperatorPrecedence.Shift: return PrecedenceKind.Shift; - case OperatorPrecedence.Additive: - case OperatorPrecedence.Multiplicative: return PrecedenceKind.Arithmetic; - default: return PrecedenceKind.Other; - } - } + OperatorPrecedence.NullCoalescing => PrecedenceKind.Coalesce, + OperatorPrecedence.ConditionalOr or OperatorPrecedence.ConditionalAnd => PrecedenceKind.Logical, + OperatorPrecedence.LogicalOr or OperatorPrecedence.LogicalXor or OperatorPrecedence.LogicalAnd => PrecedenceKind.Bitwise, + OperatorPrecedence.Equality => PrecedenceKind.Equality, + OperatorPrecedence.RelationalAndTypeTesting => PrecedenceKind.Relational, + OperatorPrecedence.Shift => PrecedenceKind.Shift, + OperatorPrecedence.Additive or OperatorPrecedence.Multiplicative => PrecedenceKind.Arithmetic, + _ => PrecedenceKind.Other, + }; } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/RefactoringHelpers/CSharpRefactoringHelpers.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/RefactoringHelpers/CSharpRefactoringHelpers.cs new file mode 100644 index 0000000000000..9170d1ee2fa9c --- /dev/null +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/RefactoringHelpers/CSharpRefactoringHelpers.cs @@ -0,0 +1,113 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Microsoft.CodeAnalysis.CodeRefactorings; +using Microsoft.CodeAnalysis.CSharp.Extensions; +using Microsoft.CodeAnalysis.CSharp.LanguageService; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.LanguageService; +using Microsoft.CodeAnalysis.Shared.Extensions; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings; + +internal sealed class CSharpRefactoringHelpers : AbstractRefactoringHelpers +{ + public static readonly CSharpRefactoringHelpers Instance = new(); + + private CSharpRefactoringHelpers() + { + } + + protected override IHeaderFacts HeaderFacts => CSharpHeaderFacts.Instance; + protected override ISyntaxFacts SyntaxFacts => CSharpSyntaxFacts.Instance; + + public override bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration) + { + var token = root.FindToken(position); + var typeDecl = token.GetAncestor(); + typeDeclaration = typeDecl; + + if (typeDecl == null) + return false; + + RoslynDebug.AssertNotNull(typeDeclaration); + if (position < typeDecl.OpenBraceToken.Span.End || + position > typeDecl.CloseBraceToken.Span.Start) + { + return false; + } + + var line = sourceText.Lines.GetLineFromPosition(position); + if (!line.IsEmptyOrWhitespace()) + return false; + + var member = typeDecl.Members.FirstOrDefault(d => d.FullSpan.Contains(position)); + if (member == null) + { + // There are no members, or we're after the last member. + return true; + } + else + { + // We're within a member. Make sure we're in the leading whitespace of + // the member. + if (position < member.SpanStart) + { + foreach (var trivia in member.GetLeadingTrivia()) + { + if (!trivia.IsWhitespaceOrEndOfLine()) + return false; + + if (trivia.FullSpan.Contains(position)) + return true; + } + } + } + + return false; + } + + protected override IEnumerable ExtractNodesSimple(SyntaxNode? node, ISyntaxFacts syntaxFacts) + { + if (node == null) + { + yield break; + } + + foreach (var extractedNode in base.ExtractNodesSimple(node, syntaxFacts)) + { + yield return extractedNode; + } + + // `var a = b;` + // -> `var a = b`; + if (node is LocalDeclarationStatementSyntax localDeclaration) + { + yield return localDeclaration.Declaration; + } + + // var `a = b`; + if (node is VariableDeclaratorSyntax declarator) + { + var declaration = declarator.Parent; + if (declaration?.Parent is LocalDeclarationStatementSyntax localDeclarationStatement) + { + var variables = syntaxFacts.GetVariablesOfLocalDeclarationStatement(localDeclarationStatement); + if (variables.Count == 1) + { + // -> `var a = b`; + yield return declaration; + + // -> `var a = b;` + yield return localDeclarationStatement; + } + } + } + } +} diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SemanticFacts/CSharpSemanticFacts.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SemanticFacts/CSharpSemanticFacts.cs index 40ba28461581a..6c974e58626df 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SemanticFacts/CSharpSemanticFacts.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SemanticFacts/CSharpSemanticFacts.cs @@ -11,6 +11,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageService; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -405,7 +406,11 @@ IdentifierNameSyntax nameSyntax when IsInPreprocessingSymbolContext(nameSyntax) }; private static IPreprocessingSymbol? CreatePreprocessingSymbol(SemanticModel model, SyntaxToken identifier) +#if !ROSLYN_4_12_OR_LOWER => model.Compilation.CreatePreprocessingSymbol(identifier.ValueText); +#else + => null; +#endif private static bool IsInPreprocessingSymbolContext(SyntaxNode node) => node.Ancestors().Any(n => n.Kind() is @@ -417,7 +422,7 @@ SyntaxKind.DefineDirectiveTrivia or public bool TryGetPrimaryConstructor(INamedTypeSymbol typeSymbol, [NotNullWhen(true)] out IMethodSymbol? primaryConstructor) => typeSymbol.TryGetPrimaryConstructor(out primaryConstructor); -#if !CODE_STYLE +#if CSHARP_WORKSPACE public async Task GetInterceptorSymbolAsync(Document document, int position, CancellationToken cancellationToken) { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpAccessibilityFacts.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpAccessibilityFacts.cs index ddda6b850c315..7fcca759d7a48 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpAccessibilityFacts.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpAccessibilityFacts.cs @@ -3,15 +3,9 @@ // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Shared.Extensions; -using System.Diagnostics.CodeAnalysis; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Editing; -#else -using Microsoft.CodeAnalysis.Editing; -#endif namespace Microsoft.CodeAnalysis.CSharp.LanguageService; @@ -46,9 +40,10 @@ public bool CanHaveAccessibility(SyntaxNode declaration, bool ignoreDeclarationM return true; case SyntaxKind.VariableDeclaration: + return declaration.Parent is BaseFieldDeclarationSyntax; + case SyntaxKind.VariableDeclarator: - var declarationKind = GetDeclarationKind(declaration); - return declarationKind is DeclarationKind.Field or DeclarationKind.Event; + return declaration.Parent is VariableDeclarationSyntax { Parent: BaseFieldDeclarationSyntax }; case SyntaxKind.ConstructorDeclaration: // Static constructor can't have accessibility @@ -100,10 +95,10 @@ public Accessibility GetAccessibility(SyntaxNode declaration) return accessibility; } - public static void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out DeclarationModifiers modifiers, out bool isDefault) + public static void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out Modifiers modifiers, out bool isDefault) { accessibility = Accessibility.NotApplicable; - modifiers = DeclarationModifiers.None; + modifiers = Modifiers.None; isDefault = false; foreach (var token in modifierList) @@ -127,185 +122,30 @@ public static void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, ou modifiers |= token.Kind() switch { - SyntaxKind.AbstractKeyword => DeclarationModifiers.Abstract, - SyntaxKind.NewKeyword => DeclarationModifiers.New, - SyntaxKind.OverrideKeyword => DeclarationModifiers.Override, - SyntaxKind.VirtualKeyword => DeclarationModifiers.Virtual, - SyntaxKind.StaticKeyword => DeclarationModifiers.Static, - SyntaxKind.AsyncKeyword => DeclarationModifiers.Async, - SyntaxKind.ConstKeyword => DeclarationModifiers.Const, - SyntaxKind.ReadOnlyKeyword => DeclarationModifiers.ReadOnly, - SyntaxKind.SealedKeyword => DeclarationModifiers.Sealed, - SyntaxKind.UnsafeKeyword => DeclarationModifiers.Unsafe, - SyntaxKind.PartialKeyword => DeclarationModifiers.Partial, - SyntaxKind.RefKeyword => DeclarationModifiers.Ref, - SyntaxKind.VolatileKeyword => DeclarationModifiers.Volatile, - SyntaxKind.ExternKeyword => DeclarationModifiers.Extern, - SyntaxKind.FileKeyword => DeclarationModifiers.File, - SyntaxKind.RequiredKeyword => DeclarationModifiers.Required, - SyntaxKind.FixedKeyword => DeclarationModifiers.Fixed, - _ => DeclarationModifiers.None, + SyntaxKind.AbstractKeyword => Modifiers.Abstract, + SyntaxKind.NewKeyword => Modifiers.New, + SyntaxKind.OverrideKeyword => Modifiers.Override, + SyntaxKind.VirtualKeyword => Modifiers.Virtual, + SyntaxKind.StaticKeyword => Modifiers.Static, + SyntaxKind.AsyncKeyword => Modifiers.Async, + SyntaxKind.ConstKeyword => Modifiers.Const, + SyntaxKind.ReadOnlyKeyword => Modifiers.ReadOnly, + SyntaxKind.SealedKeyword => Modifiers.Sealed, + SyntaxKind.UnsafeKeyword => Modifiers.Unsafe, + SyntaxKind.PartialKeyword => Modifiers.Partial, + SyntaxKind.RefKeyword => Modifiers.Ref, + SyntaxKind.VolatileKeyword => Modifiers.Volatile, + SyntaxKind.ExternKeyword => Modifiers.Extern, + SyntaxKind.FileKeyword => Modifiers.File, + SyntaxKind.RequiredKeyword => Modifiers.Required, + SyntaxKind.FixedKeyword => Modifiers.Fixed, + _ => Modifiers.None, }; isDefault |= token.Kind() == SyntaxKind.DefaultKeyword; } } - public static DeclarationKind GetDeclarationKind(SyntaxNode declaration) - { - switch (declaration.Kind()) - { - case SyntaxKind.ClassDeclaration: - case SyntaxKind.RecordDeclaration: - return DeclarationKind.Class; - case SyntaxKind.StructDeclaration: - case SyntaxKind.RecordStructDeclaration: - return DeclarationKind.Struct; - case SyntaxKind.InterfaceDeclaration: - return DeclarationKind.Interface; - case SyntaxKind.EnumDeclaration: - return DeclarationKind.Enum; - case SyntaxKind.DelegateDeclaration: - return DeclarationKind.Delegate; - - case SyntaxKind.MethodDeclaration: - return DeclarationKind.Method; - case SyntaxKind.OperatorDeclaration: - return DeclarationKind.Operator; - case SyntaxKind.ConversionOperatorDeclaration: - return DeclarationKind.ConversionOperator; - case SyntaxKind.ConstructorDeclaration: - return DeclarationKind.Constructor; - case SyntaxKind.DestructorDeclaration: - return DeclarationKind.Destructor; - - case SyntaxKind.PropertyDeclaration: - return DeclarationKind.Property; - case SyntaxKind.IndexerDeclaration: - return DeclarationKind.Indexer; - case SyntaxKind.EventDeclaration: - return DeclarationKind.CustomEvent; - case SyntaxKind.EnumMemberDeclaration: - return DeclarationKind.EnumMember; - case SyntaxKind.CompilationUnit: - return DeclarationKind.CompilationUnit; - case SyntaxKind.NamespaceDeclaration: - case SyntaxKind.FileScopedNamespaceDeclaration: - return DeclarationKind.Namespace; - case SyntaxKind.UsingDirective: - return DeclarationKind.NamespaceImport; - case SyntaxKind.Parameter: - return DeclarationKind.Parameter; - - case SyntaxKind.ParenthesizedLambdaExpression: - case SyntaxKind.SimpleLambdaExpression: - return DeclarationKind.LambdaExpression; - - case SyntaxKind.FieldDeclaration: - var fd = (FieldDeclarationSyntax)declaration; - if (fd.Declaration != null && fd.Declaration.Variables.Count == 1) - { - // this node is considered the declaration if it contains only one variable. - return DeclarationKind.Field; - } - else - { - return DeclarationKind.None; - } - - case SyntaxKind.EventFieldDeclaration: - var ef = (EventFieldDeclarationSyntax)declaration; - if (ef.Declaration != null && ef.Declaration.Variables.Count == 1) - { - // this node is considered the declaration if it contains only one variable. - return DeclarationKind.Event; - } - else - { - return DeclarationKind.None; - } - - case SyntaxKind.LocalDeclarationStatement: - var ld = (LocalDeclarationStatementSyntax)declaration; - if (ld.Declaration != null && ld.Declaration.Variables.Count == 1) - { - // this node is considered the declaration if it contains only one variable. - return DeclarationKind.Variable; - } - else - { - return DeclarationKind.None; - } - - case SyntaxKind.VariableDeclaration: - { - var vd = (VariableDeclarationSyntax)declaration; - if (vd.Variables.Count == 1 && vd.Parent == null) - { - // this node is the declaration if it contains only one variable and has no parent. - return DeclarationKind.Variable; - } - else - { - return DeclarationKind.None; - } - } - - case SyntaxKind.VariableDeclarator: - { - var vd = declaration.Parent as VariableDeclarationSyntax; - - // this node is considered the declaration if it is one among many, or it has no parent - if (vd == null || vd.Variables.Count > 1) - { - if (ParentIsFieldDeclaration(vd)) - { - return DeclarationKind.Field; - } - else if (ParentIsEventFieldDeclaration(vd)) - { - return DeclarationKind.Event; - } - else - { - return DeclarationKind.Variable; - } - } - - break; - } - - case SyntaxKind.AttributeList: - var list = (AttributeListSyntax)declaration; - if (list.Attributes.Count == 1) - { - return DeclarationKind.Attribute; - } - - break; - - case SyntaxKind.Attribute: - if (declaration.Parent is not AttributeListSyntax parentList || parentList.Attributes.Count > 1) - { - return DeclarationKind.Attribute; - } - - break; - - case SyntaxKind.GetAccessorDeclaration: - return DeclarationKind.GetAccessor; - case SyntaxKind.SetAccessorDeclaration: - case SyntaxKind.InitAccessorDeclaration: - return DeclarationKind.SetAccessor; - case SyntaxKind.AddAccessorDeclaration: - return DeclarationKind.AddAccessor; - case SyntaxKind.RemoveAccessorDeclaration: - return DeclarationKind.RemoveAccessor; - } - - return DeclarationKind.None; - } - public static SyntaxTokenList GetModifierTokens(SyntaxNode declaration) => declaration switch { @@ -319,13 +159,4 @@ public static SyntaxTokenList GetModifierTokens(SyntaxNode declaration) AnonymousFunctionExpressionSyntax anonymous => anonymous.Modifiers, _ => default, }; - - public static bool ParentIsFieldDeclaration([NotNullWhen(true)] SyntaxNode? node) - => node?.Parent.IsKind(SyntaxKind.FieldDeclaration) ?? false; - - public static bool ParentIsEventFieldDeclaration([NotNullWhen(true)] SyntaxNode? node) - => node?.Parent.IsKind(SyntaxKind.EventFieldDeclaration) ?? false; - - public static bool ParentIsLocalDeclarationStatement([NotNullWhen(true)] SyntaxNode? node) - => node?.Parent.IsKind(SyntaxKind.LocalDeclarationStatement) ?? false; } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpSyntaxFacts.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpSyntaxFacts.cs index 43b54f2dae630..9a163c7477c77 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpSyntaxFacts.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpSyntaxFacts.cs @@ -836,6 +836,7 @@ public string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, strin return builder.ToString(); } +#if !ROSLYN_4_12_OR_LOWER else if (memberDeclaration is ExtensionBlockDeclarationSyntax extensionDeclaration) { using var _ = PooledStringBuilder.GetInstance(out var builder); @@ -847,6 +848,7 @@ public string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, strin AppendParameterList(builder, extensionDeclaration.ParameterList); return builder.ToString(); } +#endif else { Debug.Assert(memberDeclaration.Kind() == SyntaxKind.IncompleteMember); @@ -872,6 +874,7 @@ static void AppendTypeParameterList(StringBuilder builder, TypeParameterListSynt } } +#if !ROSLYN_4_12_OR_LOWER void AppendParameterList(StringBuilder builder, ParameterListSyntax? parameterList) { if (parameterList != null) @@ -881,6 +884,7 @@ void AppendParameterList(StringBuilder builder, ParameterListSyntax? parameterLi builder.Append(')'); } } +#endif } public SyntaxList GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpSyntaxKinds.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpSyntaxKinds.cs index 5afb9f1eadcfb..e74bd19a93133 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpSyntaxKinds.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpSyntaxKinds.cs @@ -118,11 +118,13 @@ public int Convert(TSyntaxKind kind) where TSyntaxKind : struct public int ReferenceNotEqualsExpression => (int)SyntaxKind.NotEqualsExpression; public int SimpleAssignmentExpression => (int)SyntaxKind.SimpleAssignmentExpression; public int SimpleMemberAccessExpression => (int)SyntaxKind.SimpleMemberAccessExpression; + public int? SizeOfExpression => (int)SyntaxKind.SizeOfExpression; public int? SuppressNullableWarningExpression => (int)SyntaxKind.SuppressNullableWarningExpression; public int TernaryConditionalExpression => (int)SyntaxKind.ConditionalExpression; public int ThisExpression => (int)SyntaxKind.ThisExpression; public int? ThrowExpression => (int)SyntaxKind.ThrowExpression; public int TupleExpression => (int)SyntaxKind.TupleExpression; + public int TypeOfExpression => (int)SyntaxKind.TypeOfExpression; public int? AndPattern => (int)SyntaxKind.AndPattern; public int? ConstantPattern => (int)SyntaxKind.ConstantPattern; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Simplification/Simplifiers/CastSimplifier.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Simplification/Simplifiers/CastSimplifier.cs index 19f48c1475d69..4e99b8b60e9ab 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Simplification/Simplifiers/CastSimplifier.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Simplification/Simplifiers/CastSimplifier.cs @@ -548,7 +548,7 @@ private static bool IsConversionCastSafeToRemove( } } - // We can safely remove convertion to object in interpolated strings regardless of nullability + // We can safely remove conversion to object in interpolated strings regardless of nullability if (castNode.IsParentKind(SyntaxKind.Interpolation) && originalConversionOperation.Type?.SpecialType is SpecialType.System_Object) return true; @@ -919,16 +919,20 @@ bool IsConditionalCastSafeToRemoveDueToConversionToOtherBranch() return false; // Check if 'y' has the same type as 'z'. - if (!otherSideType.Equals(thisSideRewrittenType)) + if (!otherSideType.Equals(thisSideRewrittenType, SymbolEqualityComparer.IncludeNullability)) return false; - // Now check that with the (T) cast removed, that the outer `x ? y : z` is still immediately converted to a - // 'T'. If so, we can remove this inner (T) cast. + // Now check that with the (T) cast removed, that the outer `x ? y : z` is still + // immediately implicitly converted to a 'T'. If so, we can remove this inner (T) cast. var rewrittenConditionalConvertedType = rewrittenSemanticModel.GetTypeInfo(rewrittenConditionalExpression, cancellationToken).ConvertedType; if (rewrittenConditionalConvertedType is null) return false; + var outerConversion = rewrittenSemanticModel.GetConversion(rewrittenConditionalExpression, cancellationToken); + if (!outerConversion.IsImplicit) + return false; + return rewrittenConditionalConvertedType.Equals(conversionOperation.Type); } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/SpeculationAnalyzer.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/SpeculationAnalyzer.cs index 4cb6588957b74..6f5bee5068d76 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/SpeculationAnalyzer.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/SpeculationAnalyzer.cs @@ -9,6 +9,7 @@ using System.Diagnostics; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageService; using Microsoft.CodeAnalysis.CSharp.Syntax; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/TypeStyle/CSharpUseImplicitTypeHelper.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/TypeStyle/CSharpUseImplicitTypeHelper.cs index 0ad0363d96bfd..e37d16980e7f1 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/TypeStyle/CSharpUseImplicitTypeHelper.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/TypeStyle/CSharpUseImplicitTypeHelper.cs @@ -122,18 +122,14 @@ SyntaxKind.ForStatement or if (variableDeclaration.Variables is not [{ Initializer.Value: var initializer } variable]) return false; - // Do not suggest var replacement for stackalloc span expressions. - // This will change the bound type from a span to a pointer. - if (!variableDeclaration.Type.IsKind(SyntaxKind.PointerType)) + // Do not suggest var replacement for stackalloc span expressions. This will change the bound type from a + // span to a pointer. Note: this only applies to `var v = stackalloc ...;` If `stackalloc` is anywhere + // lower (including `var v = (stackalloc ...);`), then this is will be a span, and it will be ok to change + // to use 'var'. + if (!variableDeclaration.Type.IsKind(SyntaxKind.PointerType) && + initializer is StackAllocArrayCreationExpressionSyntax) { - var containsStackAlloc = initializer - .DescendantNodesAndSelf(descendIntoChildren: node => node is not AnonymousFunctionExpressionSyntax) - .Any(node => node.IsKind(SyntaxKind.StackAllocArrayCreationExpression)); - - if (containsStackAlloc) - { - return false; - } + return false; } if (AssignmentSupportsStylePreference( @@ -321,7 +317,7 @@ protected override bool AssignmentSupportsStylePreference( return declaredType.Equals(initializerType) && declaredType is { - Name: nameof(Func) or nameof(Action), + Name: nameof(Func<>) or nameof(Action<>), ContainingSymbol: INamespaceSymbol { Name: nameof(System), ContainingNamespace.IsGlobalNamespace: true } }; } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeCleanup/CodeCleanupOptions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeCleanup/CodeCleanupOptions.cs index 243677ebb6796..f84aa6942abf1 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeCleanup/CodeCleanupOptions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeCleanup/CodeCleanupOptions.cs @@ -3,10 +3,10 @@ // See the LICENSE file in the project root for more information. using System.Runtime.Serialization; -using Microsoft.CodeAnalysis.Formatting; -using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.AddImport; +using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.OrganizeImports; +using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CodeCleanup; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleHelpers.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleHelpers.cs index 2230937ca52dd..1aab1eef909d5 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleHelpers.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleHelpers.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; @@ -157,8 +158,8 @@ public static PerLanguageOption2> CreatePerLanguageEditorCon private static readonly BidirectionalMap s_unusedExpressionAssignmentPreferenceMap = new( [ - KeyValuePairUtil.Create("discard_variable", UnusedValuePreference.DiscardVariable), - KeyValuePairUtil.Create("unused_local_variable", UnusedValuePreference.UnusedLocalVariable), + KeyValuePair.Create("discard_variable", UnusedValuePreference.DiscardVariable), + KeyValuePair.Create("unused_local_variable", UnusedValuePreference.UnusedLocalVariable), ]); internal static EditorConfigValueSerializer> GetUnusedValuePreferenceSerializer(CodeStyleOption2 defaultValue) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOptions2.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOptions2.cs index 26084a44ee77c..fad4732c822d7 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOptions2.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOptions2.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.Formatting; @@ -169,8 +170,8 @@ private static PerLanguageOption2> CreateQualifyAccessOpt private static readonly BidirectionalMap s_unusedParametersPreferenceMap = new( [ - KeyValuePairUtil.Create("non_public", UnusedParametersPreference.NonPublicMethods), - KeyValuePairUtil.Create("all", UnusedParametersPreference.AllMethods), + KeyValuePair.Create("non_public", UnusedParametersPreference.NonPublicMethods), + KeyValuePair.Create("all", UnusedParametersPreference.AllMethods), ]); internal static readonly PerLanguageOption2> UnusedParameters = CreatePerLanguageOption( @@ -197,10 +198,10 @@ private static PerLanguageOption2> CreateQualifyAccessOpt private static readonly BidirectionalMap s_accessibilityModifiersRequiredMap = new( [ - KeyValuePairUtil.Create("never", CodeStyle.AccessibilityModifiersRequired.Never), - KeyValuePairUtil.Create("always", CodeStyle.AccessibilityModifiersRequired.Always), - KeyValuePairUtil.Create("for_non_interface_members", CodeStyle.AccessibilityModifiersRequired.ForNonInterfaceMembers), - KeyValuePairUtil.Create("omit_if_default", CodeStyle.AccessibilityModifiersRequired.OmitIfDefault), + KeyValuePair.Create("never", CodeStyle.AccessibilityModifiersRequired.Never), + KeyValuePair.Create("always", CodeStyle.AccessibilityModifiersRequired.Always), + KeyValuePair.Create("for_non_interface_members", CodeStyle.AccessibilityModifiersRequired.ForNonInterfaceMembers), + KeyValuePair.Create("omit_if_default", CodeStyle.AccessibilityModifiersRequired.OmitIfDefault), ]); internal static readonly PerLanguageOption2> AccessibilityModifiersRequired = CreatePerLanguageOption( @@ -243,8 +244,8 @@ private static PerLanguageOption2> CreateQualifyAccessOpt private static readonly BidirectionalMap s_parenthesesPreferenceMap = new( [ - KeyValuePairUtil.Create("always_for_clarity", ParenthesesPreference.AlwaysForClarity), - KeyValuePairUtil.Create("never_if_unnecessary", ParenthesesPreference.NeverIfUnnecessary), + KeyValuePair.Create("always_for_clarity", ParenthesesPreference.AlwaysForClarity), + KeyValuePair.Create("never_if_unnecessary", ParenthesesPreference.NeverIfUnnecessary), ]); private static PerLanguageOption2> CreateParenthesesOption(CodeStyleOption2 defaultValue, string name) @@ -296,8 +297,8 @@ private static PerLanguageOption2> Creat private static readonly BidirectionalMap s_forEachExplicitCastInSourcePreferencePreferenceMap = new( [ - KeyValuePairUtil.Create("always", ForEachExplicitCastInSourcePreference.Always), - KeyValuePairUtil.Create("when_strongly_typed", ForEachExplicitCastInSourcePreference.WhenStronglyTyped), + KeyValuePair.Create("always", ForEachExplicitCastInSourcePreference.Always), + KeyValuePair.Create("when_strongly_typed", ForEachExplicitCastInSourcePreference.WhenStronglyTyped), ]); internal static readonly Option2> ForEachExplicitCastInSource = CreateOption( diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/IIntervalTree`1.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/IIntervalTree`1.cs index ee0b094caf66d..f918c4cd07eb4 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/IIntervalTree`1.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/IIntervalTree`1.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Generic; +using Microsoft.CodeAnalysis.Collections; namespace Microsoft.CodeAnalysis.Shared.Collections; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/IntervalTreeAlgorithms`2.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/IntervalTreeAlgorithms`2.cs index 07f7610edd7d7..2cfd7222d377d 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/IntervalTreeAlgorithms`2.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/IntervalTreeAlgorithms`2.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Collections; namespace Microsoft.CodeAnalysis.Shared.Collections; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/IntervalTreeHelpers.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/IntervalTreeHelpers.cs index b6ede2a21c306..92e530e792885 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/IntervalTreeHelpers.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/IntervalTreeHelpers.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/MutableIntervalTree`1.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/MutableIntervalTree`1.cs index b209ea59ee183..4723005ed4c9a 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/MutableIntervalTree`1.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/MutableIntervalTree`1.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; namespace Microsoft.CodeAnalysis.Shared.Collections; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/SimpleMutableIntervalTree`2.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/SimpleMutableIntervalTree`2.cs index c42a6b2646820..65ab9d942f104 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/SimpleMutableIntervalTree`2.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/SimpleMutableIntervalTree`2.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Collections; namespace Microsoft.CodeAnalysis.Shared.Collections; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CompilerExtensions.projitems b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CompilerExtensions.projitems index e1f2f2e635b9a..6f9309d886cb3 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CompilerExtensions.projitems +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CompilerExtensions.projitems @@ -18,7 +18,6 @@ - @@ -163,6 +162,7 @@ + @@ -210,6 +210,7 @@ + @@ -367,6 +368,8 @@ + + @@ -450,7 +453,6 @@ - @@ -546,7 +548,7 @@ - + \ No newline at end of file diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Diagnostics/DiagnosticCategory.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Diagnostics/DiagnosticCategory.cs index 175977edc1cab..82ffcae98cf4b 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Diagnostics/DiagnosticCategory.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Diagnostics/DiagnosticCategory.cs @@ -4,7 +4,7 @@ namespace Microsoft.CodeAnalysis.Diagnostics; -internal static class DiagnosticCategory +internal static partial class DiagnosticCategory { public const string Style = nameof(Style); public const string CodeQuality = nameof(CodeQuality); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Editing/Modifiers.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Editing/Modifiers.cs new file mode 100644 index 0000000000000..1c53a2d21bd55 --- /dev/null +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Editing/Modifiers.cs @@ -0,0 +1,36 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; + +namespace Microsoft.CodeAnalysis.Editing; + +[Flags] +internal enum Modifiers +{ + // WARNING: Do not reorder these values. The code style layer takes a dependency on this. Sharing instances of + // this, with the workspace layer. It is fine to add values to the end of this enum. +#pragma warning disable format + None = 0, + Static = 1 << 0, + Abstract = 1 << 1, + New = 1 << 2, + Unsafe = 1 << 3, + ReadOnly = 1 << 4, + Virtual = 1 << 5, + Override = 1 << 6, + Sealed = 1 << 7, + Const = 1 << 8, + WithEvents = 1 << 9, + Partial = 1 << 10, + Async = 1 << 11, + WriteOnly = 1 << 12, + Ref = 1 << 13, + Volatile = 1 << 14, + Extern = 1 << 15, + Required = 1 << 16, + File = 1 << 17, + Fixed = 1 << 18, +#pragma warning restore format +} diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EditorConfig/LanguageExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EditorConfig/LanguageExtensions.cs index f2f7e7f03b438..9cc0027cb0de1 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EditorConfig/LanguageExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EditorConfig/LanguageExtensions.cs @@ -5,6 +5,7 @@ using System.IO; namespace Microsoft.CodeAnalysis.EditorConfig; + using static Microsoft.CodeAnalysis.EditorConfig.LanguageConstants; internal static class LanguageExtensions diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/VirtualChars/VirtualCharSequence.Chunks.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/VirtualChars/VirtualCharSequence.Chunks.cs index 04fea4f3aa879..b40f123143b97 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/VirtualChars/VirtualCharSequence.Chunks.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/VirtualChars/VirtualCharSequence.Chunks.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using System.Linq; using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.Collections; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/DiagnosticSeverityExtensions_Shared.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/DiagnosticSeverityExtensions_Shared.cs index 4b717c36220c7..e9efc4898c3c2 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/DiagnosticSeverityExtensions_Shared.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/DiagnosticSeverityExtensions_Shared.cs @@ -8,26 +8,6 @@ namespace Microsoft.CodeAnalysis.Diagnostics; internal static partial class DiagnosticSeverityExtensions { - /// - /// Returns the equivalent for a value. - /// - /// The value. - /// - /// The equivalent for the value. - /// - /// - /// If is not one of the expected values. - /// - public static ReportDiagnostic ToReportDiagnostic(this DiagnosticSeverity diagnosticSeverity) - => diagnosticSeverity switch - { - DiagnosticSeverity.Hidden => ReportDiagnostic.Hidden, - DiagnosticSeverity.Info => ReportDiagnostic.Info, - DiagnosticSeverity.Warning => ReportDiagnostic.Warn, - DiagnosticSeverity.Error => ReportDiagnostic.Error, - _ => throw ExceptionUtilities.UnexpectedValue(diagnosticSeverity), - }; - public static string ToEditorConfigString(this DiagnosticSeverity diagnosticSeverity) { return diagnosticSeverity switch diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ReadOnlySpanExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ReadOnlySpanExtensions.cs index 25c56a2b6abff..541b344f11298 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ReadOnlySpanExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ReadOnlySpanExtensions.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; -using System.Text; namespace Microsoft.CodeAnalysis.Shared.Extensions; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ReportDiagnosticExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ReportDiagnosticExtensions.cs index 5200414715f38..c7a5617a7ac62 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ReportDiagnosticExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ReportDiagnosticExtensions.cs @@ -9,64 +9,6 @@ namespace Microsoft.CodeAnalysis.Diagnostics; internal static partial class ReportDiagnosticExtensions { - /// - /// Returns the equivalent for a value. - /// - /// The value. - /// - /// The equivalent for a value; otherwise, - /// if does not contain a direct equivalent for - /// . - /// - /// - /// If is not one of the expected values. - /// - public static DiagnosticSeverity? ToDiagnosticSeverity(this ReportDiagnostic reportDiagnostic) - { - switch (reportDiagnostic) - { - case ReportDiagnostic.Error: - return DiagnosticSeverity.Error; - - case ReportDiagnostic.Warn: - return DiagnosticSeverity.Warning; - - case ReportDiagnostic.Info: - return DiagnosticSeverity.Info; - - case ReportDiagnostic.Hidden: - return DiagnosticSeverity.Hidden; - - case ReportDiagnostic.Suppress: - case ReportDiagnostic.Default: - return null; - - default: - throw ExceptionUtilities.UnexpectedValue(reportDiagnostic); - } - } - - /// - /// Applies a default severity to a value. - /// - /// The value. - /// The default severity. - /// - /// If is , returns - /// . - /// -or- - /// Otherwise, returns if it has a non-default value. - /// - public static ReportDiagnostic WithDefaultSeverity(this ReportDiagnostic reportDiagnostic, DiagnosticSeverity defaultSeverity) - { - if (reportDiagnostic != ReportDiagnostic.Default) - { - return reportDiagnostic; - } - - return defaultSeverity.ToReportDiagnostic(); - } - public static string ToEditorConfigString(this ReportDiagnostic reportDiagnostic) { return reportDiagnostic switch diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SemanticModelExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SemanticModelExtensions.cs index 1066ff3e16470..731ad29aec5bb 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SemanticModelExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SemanticModelExtensions.cs @@ -12,7 +12,7 @@ using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; -#if !CODE_STYLE +#if WORKSPACE using Humanizer; #endif @@ -204,7 +204,7 @@ private static bool TryGeneratePluralizedNameFromTypeArgument( public static string Pluralize(string word) { -#if CODE_STYLE +#if !WORKSPACE return word; #else return word.Pluralize(); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SymbolInfoExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SymbolInfoExtensions.cs index f0ee4c3271d18..2908b53500d9b 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SymbolInfoExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SymbolInfoExtensions.cs @@ -4,6 +4,7 @@ using System.Collections.Immutable; using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Collections; using Roslyn.Utilities; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SymbolUsageInfo.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SymbolUsageInfo.cs index d558d96e2734c..8f485357cbb8b 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SymbolUsageInfo.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SymbolUsageInfo.cs @@ -2,10 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Diagnostics; using System.Runtime.Serialization; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis; @@ -15,7 +13,7 @@ namespace Microsoft.CodeAnalysis; /// For methods, fields, properties, events, locals and parameters, this corresponds to values from . /// [DataContract] -internal readonly struct SymbolUsageInfo : IEquatable +internal readonly record struct SymbolUsageInfo { public static readonly SymbolUsageInfo None = Create(ValueUsageInfo.None); @@ -45,28 +43,4 @@ public bool IsReadFrom() public bool IsWrittenTo() => ValueUsageInfoOpt.HasValue && ValueUsageInfoOpt.Value.IsWrittenTo(); - - public bool IsNameOnly() - => ValueUsageInfoOpt.HasValue && ValueUsageInfoOpt.Value.IsNameOnly(); - - public override bool Equals(object? obj) - => obj is SymbolUsageInfo && Equals((SymbolUsageInfo)obj); - - public bool Equals(SymbolUsageInfo other) - { - if (ValueUsageInfoOpt.HasValue) - { - return other.ValueUsageInfoOpt.HasValue && - ValueUsageInfoOpt.Value == other.ValueUsageInfoOpt.Value; - } - else - { - RoslynDebug.Assert(TypeOrNamespaceUsageInfoOpt.HasValue); - return other.TypeOrNamespaceUsageInfoOpt.HasValue && - TypeOrNamespaceUsageInfoOpt.Value == other.TypeOrNamespaceUsageInfoOpt.Value; - } - } - - public override int GetHashCode() - => Hash.Combine(((int?)ValueUsageInfoOpt)?.GetHashCode() ?? 0, ((int?)TypeOrNamespaceUsageInfoOpt)?.GetHashCode() ?? 0); } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/LValueFlowCaptureProvider.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/LValueFlowCaptureProvider.cs index 280bacbad0382..9a3db1b33857e 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/LValueFlowCaptureProvider.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/LValueFlowCaptureProvider.cs @@ -7,9 +7,9 @@ using System.Collections.Immutable; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; -using Roslyn.Utilities; #if DEBUG +using System.Collections.Generic; using System.Diagnostics; #endif diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/SymbolUsageAnalysis/SymbolUsageAnalysis.DataFlowAnalyzer.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/SymbolUsageAnalysis/SymbolUsageAnalysis.DataFlowAnalyzer.cs index 04da50b602cb2..1b3786cbde67d 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/SymbolUsageAnalysis/SymbolUsageAnalysis.DataFlowAnalyzer.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/SymbolUsageAnalysis/SymbolUsageAnalysis.DataFlowAnalyzer.cs @@ -8,7 +8,6 @@ using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FlowAnalysis.SymbolUsageAnalysis; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/FormattingOptions2.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/FormattingOptions2.cs index 94cb4ad8f07b7..8fbb0c04794c1 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/FormattingOptions2.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/FormattingOptions2.cs @@ -8,8 +8,7 @@ using Microsoft.CodeAnalysis.Indentation; using Microsoft.CodeAnalysis.CodeStyle; -#if CODE_STYLE -using WorkspacesResources = Microsoft.CodeAnalysis.CodeStyleResources; +#if !WORKSPACE using PublicIndentStyle = Microsoft.CodeAnalysis.Formatting.FormattingOptions2.IndentStyle; #else using PublicIndentStyle = Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle; diff --git a/src/Workspaces/Core/Portable/Formatting/VisualBasic/VisualBasicSyntaxFormattingOptions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/VisualBasic/VisualBasicSyntaxFormattingOptions.cs similarity index 100% rename from src/Workspaces/Core/Portable/Formatting/VisualBasic/VisualBasicSyntaxFormattingOptions.cs rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/VisualBasic/VisualBasicSyntaxFormattingOptions.cs diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Log/Logger.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Log/Logger.cs index d1619ce5f6eba..1c697130eabf3 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Log/Logger.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Log/Logger.cs @@ -3,8 +3,8 @@ // See the LICENSE file in the project root for more information. using System; -using System.Threading; using System.Diagnostics.CodeAnalysis; +using System.Threading; #if !CODE_STYLE using System.Linq; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/Naming/IdentifierNameParts.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/Naming/IdentifierNameParts.cs index a4049bc0b136e..474d067b1b20e 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/Naming/IdentifierNameParts.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/Naming/IdentifierNameParts.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.NamingStyles; using Microsoft.CodeAnalysis.Shared.Collections; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingStyle.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingStyle.cs index 57d4d16d1a82e..5ce61ae95a951 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingStyle.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingStyle.cs @@ -11,6 +11,7 @@ using System.Linq; using System.Runtime.Serialization; using System.Xml.Linq; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingStyleOptions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingStyleOptions.cs index 462121f29d92e..2f1dce39ef3f0 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingStyleOptions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingStyleOptions.cs @@ -2,11 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Immutable; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Options; -using System.Collections.Immutable; -#if !CODE_STYLE +#if WORKSPACE using Microsoft.CodeAnalysis.Host; #endif @@ -33,7 +33,7 @@ internal static class NamingStyleOptions } internal interface NamingStylePreferencesProvider -#if !CODE_STYLE +#if WORKSPACE : OptionsProvider #endif { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/Serialization/NamingStylePreferences.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/Serialization/NamingStylePreferences.cs index 44d53e8491d43..808e7372d023f 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/Serialization/NamingStylePreferences.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/Serialization/NamingStylePreferences.cs @@ -23,8 +23,69 @@ namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; internal sealed class NamingStylePreferences : IEquatable { private const int s_serializationVersion = 5; + [DataMember(Order = 0)] + public readonly ImmutableArray SymbolSpecifications; + + [DataMember(Order = 1)] + public readonly ImmutableArray NamingStyles; + + [DataMember(Order = 2)] + public ImmutableArray SerializableNamingRules + { + get + { + if (field.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize( + ref field, + Rules.NamingRules.SelectAsArray(static rule => new SerializableNamingRule + { + SymbolSpecificationID = rule.SymbolSpecification.ID, + NamingStyleID = rule.NamingStyle.ID, + EnforcementLevel = rule.EnforcementLevel, + })); + } + + return field; + } + } - private static readonly string _defaultNamingPreferencesString = $@" + public readonly NamingStyleRules Rules; + + // used for deserialization + public NamingStylePreferences( + ImmutableArray symbolSpecifications, + ImmutableArray namingStyles, + ImmutableArray serializableRules) + { + Contract.ThrowIfFalse(serializableRules.IsEmpty == namingStyles.IsEmpty); + Contract.ThrowIfFalse(serializableRules.IsEmpty == symbolSpecifications.IsEmpty); + + SymbolSpecifications = symbolSpecifications; + NamingStyles = namingStyles; + SerializableNamingRules = serializableRules; + + Rules = new NamingStyleRules( + serializableRules.SelectAsArray(static (rule, arg) => new NamingRule( + arg.symbolSpecifications.Single(static (s, id) => s.ID == id, rule.SymbolSpecificationID), + arg.namingStyles.Single(static (s, id) => s.ID == id, rule.NamingStyleID), + rule.EnforcementLevel), (symbolSpecifications, namingStyles))); + } + + public NamingStylePreferences( + ImmutableArray symbolSpecifications, + ImmutableArray namingStyles, + ImmutableArray namingRules) + { + Contract.ThrowIfFalse(namingRules.IsEmpty == namingStyles.IsEmpty); + Contract.ThrowIfFalse(namingRules.IsEmpty == symbolSpecifications.IsEmpty); + + SymbolSpecifications = symbolSpecifications; + NamingStyles = namingStyles; + Rules = new NamingStyleRules(namingRules); + } + + public static string DefaultNamingPreferencesString { get; } = $@" @@ -271,75 +332,9 @@ internal sealed class NamingStylePreferences : IEquatable "; - [DataMember(Order = 0)] - public readonly ImmutableArray SymbolSpecifications; - - [DataMember(Order = 1)] - public readonly ImmutableArray NamingStyles; - - [DataMember(Order = 2)] - public ImmutableArray SerializableNamingRules - { - get - { - if (_lazySerializableRules.IsDefault) - { - ImmutableInterlocked.InterlockedInitialize( - ref _lazySerializableRules, - Rules.NamingRules.SelectAsArray(static rule => new SerializableNamingRule - { - SymbolSpecificationID = rule.SymbolSpecification.ID, - NamingStyleID = rule.NamingStyle.ID, - EnforcementLevel = rule.EnforcementLevel, - })); - } - - return _lazySerializableRules; - } - } - - private ImmutableArray _lazySerializableRules; - - public readonly NamingStyleRules Rules; - - // used for deserialization - public NamingStylePreferences( - ImmutableArray symbolSpecifications, - ImmutableArray namingStyles, - ImmutableArray serializableRules) - { - Contract.ThrowIfFalse(serializableRules.IsEmpty == namingStyles.IsEmpty); - Contract.ThrowIfFalse(serializableRules.IsEmpty == symbolSpecifications.IsEmpty); - - SymbolSpecifications = symbolSpecifications; - NamingStyles = namingStyles; - _lazySerializableRules = serializableRules; - - Rules = new NamingStyleRules( - serializableRules.SelectAsArray(static (rule, arg) => new NamingRule( - arg.symbolSpecifications.Single(static (s, id) => s.ID == id, rule.SymbolSpecificationID), - arg.namingStyles.Single(static (s, id) => s.ID == id, rule.NamingStyleID), - rule.EnforcementLevel), (symbolSpecifications, namingStyles))); - } - - public NamingStylePreferences( - ImmutableArray symbolSpecifications, - ImmutableArray namingStyles, - ImmutableArray namingRules) - { - Contract.ThrowIfFalse(namingRules.IsEmpty == namingStyles.IsEmpty); - Contract.ThrowIfFalse(namingRules.IsEmpty == symbolSpecifications.IsEmpty); - - SymbolSpecifications = symbolSpecifications; - NamingStyles = namingStyles; - Rules = new NamingStyleRules(namingRules); - } - public static NamingStylePreferences Default { get; } = FromXElement(XElement.Parse(DefaultNamingPreferencesString)); public static NamingStylePreferences Empty { get; } = new([], [], ImmutableArray.Empty); - public static string DefaultNamingPreferencesString => _defaultNamingPreferencesString; - public bool IsEmpty => Rules.NamingRules.IsEmpty; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/Serialization/SymbolSpecification.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/Serialization/SymbolSpecification.cs index 053076aea4699..0baf9cde23283 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/Serialization/SymbolSpecification.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/Serialization/SymbolSpecification.cs @@ -6,20 +6,15 @@ using System; using System.Collections.Immutable; +using System.Diagnostics; using System.Linq; +using System.Runtime.Serialization; using System.Xml.Linq; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; -using System.Runtime.Serialization; -using System.Diagnostics; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Editing; -#else -using Microsoft.CodeAnalysis.Editing; -#endif namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; @@ -99,9 +94,9 @@ public bool AppliesTo(ISymbol symbol) ApplicableAccessibilityList.Contains(GetAccessibility(symbol)); public bool AppliesTo(SymbolKind symbolKind, Accessibility accessibility) - => this.AppliesTo(new SymbolKindOrTypeKind(symbolKind), new DeclarationModifiers(), accessibility); + => this.AppliesTo(new SymbolKindOrTypeKind(symbolKind), Modifiers.None, accessibility); - public bool AppliesTo(SymbolKindOrTypeKind kind, DeclarationModifiers modifiers, Accessibility? accessibility) + public bool AppliesTo(SymbolKindOrTypeKind kind, Modifiers modifiers, Accessibility? accessibility) { if (!ApplicableSymbolKindList.Any(static (k, kind) => k.Equals(kind), kind)) { @@ -122,32 +117,32 @@ public bool AppliesTo(SymbolKindOrTypeKind kind, DeclarationModifiers modifiers, return true; } - private static DeclarationModifiers CollapseModifiers(ImmutableArray requiredModifierList) + private static Modifiers CollapseModifiers(ImmutableArray requiredModifierList) { if (requiredModifierList == default) { - return new DeclarationModifiers(); + return Modifiers.None; } - var result = new DeclarationModifiers(); + var result = Modifiers.None; foreach (var modifier in requiredModifierList) { switch (modifier.ModifierKindWrapper) { case ModifierKindEnum.IsAbstract: - result = result.WithIsAbstract(true); + result |= Modifiers.Abstract; break; case ModifierKindEnum.IsStatic: - result = result.WithIsStatic(true); + result |= Modifiers.Static; break; case ModifierKindEnum.IsAsync: - result = result.WithAsync(true); + result |= Modifiers.Async; break; case ModifierKindEnum.IsReadOnly: - result = result.WithIsReadOnly(true); + result |= Modifiers.ReadOnly; break; case ModifierKindEnum.IsConst: - result = result.WithIsConst(true); + result |= Modifiers.Const; break; } } @@ -456,29 +451,29 @@ public static implicit operator SymbolKindOrTypeKind(MethodKind symbolKind) [DataMember(Order = 0)] public readonly ModifierKindEnum ModifierKindWrapper; - internal DeclarationModifiers Modifier { get; } + internal Modifiers Modifiers { get; } - public ModifierKind(DeclarationModifiers modifier) + public ModifierKind(Modifiers modifier) { - this.Modifier = modifier; + this.Modifiers = modifier; - if (modifier.IsAbstract) + if (modifier.HasFlag(Modifiers.Abstract)) { ModifierKindWrapper = ModifierKindEnum.IsAbstract; } - else if (modifier.IsStatic) + else if (modifier.HasFlag(Modifiers.Static)) { ModifierKindWrapper = ModifierKindEnum.IsStatic; } - else if (modifier.IsAsync) + else if (modifier.HasFlag(Modifiers.Async)) { ModifierKindWrapper = ModifierKindEnum.IsAsync; } - else if (modifier.IsReadOnly) + else if (modifier.HasFlag(Modifiers.ReadOnly)) { ModifierKindWrapper = ModifierKindEnum.IsReadOnly; } - else if (modifier.IsConst) + else if (modifier.HasFlag(Modifiers.Const)) { ModifierKindWrapper = ModifierKindEnum.IsConst; } @@ -492,29 +487,29 @@ public ModifierKind(ModifierKindEnum modifierKind) { ModifierKindWrapper = modifierKind; - Modifier = new DeclarationModifiers( - isAbstract: ModifierKindWrapper == ModifierKindEnum.IsAbstract, - isStatic: ModifierKindWrapper == ModifierKindEnum.IsStatic, - isAsync: ModifierKindWrapper == ModifierKindEnum.IsAsync, - isReadOnly: ModifierKindWrapper == ModifierKindEnum.IsReadOnly, - isConst: ModifierKindWrapper == ModifierKindEnum.IsConst); + Modifiers = + (ModifierKindWrapper == ModifierKindEnum.IsAbstract ? Modifiers.Abstract : 0) | + (ModifierKindWrapper == ModifierKindEnum.IsStatic ? Modifiers.Static : 0) | + (ModifierKindWrapper == ModifierKindEnum.IsAsync ? Modifiers.Async : 0) | + (ModifierKindWrapper == ModifierKindEnum.IsReadOnly ? Modifiers.ReadOnly : 0) | + (ModifierKindWrapper == ModifierKindEnum.IsConst ? Modifiers.Const : 0); } public bool MatchesSymbol(ISymbol symbol) { - if ((Modifier.IsAbstract && symbol.IsAbstract) || - (Modifier.IsStatic && symbol.IsStatic)) + if ((Modifiers.HasFlag(Modifiers.Abstract) && symbol.IsAbstract) || + (Modifiers.HasFlag(Modifiers.Static) && symbol.IsStatic)) { return true; } var kind = symbol.Kind; - if (Modifier.IsAsync && kind == SymbolKind.Method && ((IMethodSymbol)symbol).IsAsync) + if (Modifiers.HasFlag(Modifiers.Async) && kind == SymbolKind.Method && ((IMethodSymbol)symbol).IsAsync) { return true; } - if (Modifier.IsReadOnly) + if (Modifiers.HasFlag(Modifiers.ReadOnly)) { if (kind == SymbolKind.Field && ((IFieldSymbol)symbol).IsReadOnly) { @@ -522,7 +517,7 @@ public bool MatchesSymbol(ISymbol symbol) } } - if (Modifier.IsConst) + if (Modifiers.HasFlag(Modifiers.Const)) { if ((kind == SymbolKind.Field && ((IFieldSymbol)symbol).IsConst) || (kind == SymbolKind.Local && ((ILocalSymbol)symbol).IsConst)) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfigValueSerializer.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfigValueSerializer.cs index dd1d27c9aa13d..fc68ec1e178bc 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfigValueSerializer.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfigValueSerializer.cs @@ -8,6 +8,7 @@ using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; +using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Options; @@ -127,7 +128,7 @@ public static EditorConfigValueSerializer CreateSerializerForEnum(IEnumera { var map = new BidirectionalMap(entries, StringComparer.OrdinalIgnoreCase); var alternativeMap = ImmutableDictionary.Empty.WithComparers(keyComparer: StringComparer.OrdinalIgnoreCase) - .AddRange(alternativeEntries.Select(static p => KeyValuePairUtil.Create(p.name, p.value))); + .AddRange(alternativeEntries.Select(static p => KeyValuePair.Create(p.name, p.value))); return CreateSerializerForEnum(map, alternativeMap); } @@ -203,4 +204,13 @@ public static void Serialize(IDictionary builder, IOption2 optio builder[option.Definition.ConfigName] = option.Definition.Serializer.Serialize(value); } } + + public static EditorConfigValueSerializer? ConvertEnumSerializer(EditorConfigValueSerializer serializer) + where TFromEnum : struct, Enum + where TToEnum : struct, Enum + { + return new( + value => serializer.ParseValue(value).ConvertEnum(), + value => serializer.SerializeValue(EnumValueUtilities.ConvertEnum(value))); + } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfigValueSerializer`1.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfigValueSerializer`1.cs index d6575265c3869..d85e24c848b76 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfigValueSerializer`1.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfigValueSerializer`1.cs @@ -20,6 +20,9 @@ internal sealed class EditorConfigValueSerializer( parseValue: _ => throw new NotSupportedException("Option does not support serialization to editorconfig format"), serializeValue: _ => throw new NotSupportedException("Option does not support serialization to editorconfig format")); + public readonly Func> ParseValue = parseValue; + public readonly Func SerializeValue = serializeValue; + private readonly ConcurrentDictionary> _cachedValues = []; bool IEditorConfigValueSerializer.TryParse(string value, out object? result) @@ -36,7 +39,7 @@ bool IEditorConfigValueSerializer.TryParse(string value, out object? result) internal bool TryParseValue(string value, [MaybeNullWhen(false)] out T result) { - var optionalValue = _cachedValues.GetOrAdd(value, parseValue); + var optionalValue = _cachedValues.GetOrAdd(value, ParseValue); if (optionalValue.HasValue) { result = optionalValue.Value; @@ -51,13 +54,13 @@ internal bool TryParseValue(string value, [MaybeNullWhen(false)] out T result) public string GetEditorConfigStringValue(T value) { - var editorConfigStringForValue = serializeValue(value); + var editorConfigStringForValue = SerializeValue(value); Contract.ThrowIfTrue(RoslynString.IsNullOrEmpty(editorConfigStringForValue)); return editorConfigStringForValue; } public string Serialize(T value) - => serializeValue(value); + => SerializeValue(value); string IEditorConfigValueSerializer.Serialize(object? value) => GetEditorConfigStringValue((T)value!); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/IOption2.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/IOption2.cs index 1a84ff88c804b..ad11d76fea972 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/IOption2.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/IOption2.cs @@ -14,14 +14,14 @@ namespace Microsoft.CodeAnalysis.Options; /// set of interface members. /// internal interface IOption2 : IEquatable -#if !CODE_STYLE +#if WORKSPACE , IOption #endif { OptionDefinition Definition { get; } IPublicOption? PublicOption { get; } -#if CODE_STYLE +#if !WORKSPACE bool IsPerLanguage { get; } #endif } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/Option2.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/Option2.cs index 0e4634707a473..09de41bde1c88 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/Option2.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/Option2.cs @@ -24,7 +24,7 @@ internal interface ISingleValuedOption : IOption2 /// /// Note that this property is not (and should not be) used for computing option values or storing options. /// - public string? LanguageName { get; } + string? LanguageName { get; } } /// @@ -75,7 +75,7 @@ private void VerifyNamingConvention() public T DefaultValue => Definition.DefaultValue; OptionDefinition IOption2.Definition => Definition; -#if CODE_STYLE +#if !WORKSPACE bool IOption2.IsPerLanguage => false; #else string IOption.Feature => "config"; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionDefinition.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionDefinition.cs index 0ef0bfb8a9e03..48af6723289e5 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionDefinition.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionDefinition.cs @@ -96,7 +96,7 @@ public static bool IsSupportedOptionType(Type type) type == typeof(long?) || type.IsEnum || Nullable.GetUnderlyingType(type)?.IsEnum == true || -#if !CODE_STYLE +#if WORKSPACE typeof(ICodeStyleOption).IsAssignableFrom(type) || #endif typeof(ICodeStyleOption2).IsAssignableFrom(type) || diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/PerLanguageOption2.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/PerLanguageOption2.cs index d386d13f47bbd..93bb91c0466a9 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/PerLanguageOption2.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/PerLanguageOption2.cs @@ -64,7 +64,7 @@ private void VerifyNamingConvention() OptionDefinition IOption2.Definition => Definition; public T DefaultValue => Definition.DefaultValue; -#if CODE_STYLE +#if !WORKSPACE bool IOption2.IsPerLanguage => true; #else string IOption.Feature => "config"; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/PublicOptionFactory.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/PublicOptionFactory.cs index aba0e3e615fe6..1e1248f497538 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/PublicOptionFactory.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/PublicOptionFactory.cs @@ -9,7 +9,7 @@ namespace Microsoft.CodeAnalysis.Options; internal static class PublicOptionFactory { -#if CODE_STYLE +#if !WORKSPACE #pragma warning disable IDE0060 // Remove unused parameter // Stubs to avoid #ifdefs at call sites. diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Serialization/ObjectWriter.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Serialization/ObjectWriter.cs index 31e1adb719e71..e263b058a1106 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Serialization/ObjectWriter.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Serialization/ObjectWriter.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#pragma warning disable CS0419 // Ambiguous reference in cref attribute + using System; using System.Diagnostics; using System.IO; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Serialization/TextEncodingKind.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Serialization/TextEncodingKind.cs index 092aaa2bb709e..ab661b8211b49 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Serialization/TextEncodingKind.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Serialization/TextEncodingKind.cs @@ -2,8 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Text; using System.Diagnostics; +using System.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/FileBannerFacts/AbstractFileBannerFacts.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/FileBannerFacts/AbstractFileBannerFacts.cs index 422832c267aac..cc647e49070e6 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/FileBannerFacts/AbstractFileBannerFacts.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/FileBannerFacts/AbstractFileBannerFacts.cs @@ -4,9 +4,9 @@ using System.Collections.Generic; using System.Collections.Immutable; -using System.Threading; using System.Diagnostics; using System.Linq; +using System.Threading; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.LanguageService; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/HeaderFacts/AbstractHeaderFacts.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/HeaderFacts/AbstractHeaderFacts.cs index 519d3137097db..ffa922916a00e 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/HeaderFacts/AbstractHeaderFacts.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/HeaderFacts/AbstractHeaderFacts.cs @@ -6,6 +6,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Linq; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/RefactoringHelpers/AbstractRefactoringHelpers.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/RefactoringHelpers/AbstractRefactoringHelpers.cs new file mode 100644 index 0000000000000..76f4859972f71 --- /dev/null +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/RefactoringHelpers/AbstractRefactoringHelpers.cs @@ -0,0 +1,612 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.LanguageService; +using Microsoft.CodeAnalysis.Shared.Extensions; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.CodeRefactorings; + +internal abstract class AbstractRefactoringHelpers : IRefactoringHelpers + where TExpressionSyntax : SyntaxNode + where TArgumentSyntax : SyntaxNode + where TExpressionStatementSyntax : SyntaxNode +{ + protected abstract ISyntaxFacts SyntaxFacts { get; } + protected abstract IHeaderFacts HeaderFacts { get; } + + public abstract bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration); + + private static void AddNode(bool allowEmptyNodes, ref TemporaryArray result, TSyntaxNode node) where TSyntaxNode : SyntaxNode + { + if (!allowEmptyNodes && node.Span.IsEmpty) + return; + + result.Add(node); + } + + /// + /// Trims leading and trailing whitespace from . + /// + /// + /// Returns unchanged in case . + /// Returns empty Span with original in case it contains only whitespace. + /// + private static TextSpan GetTrimmedTextSpan(SourceText sourceText, TextSpan span) + { + if (span.IsEmpty) + return span; + + var start = span.Start; + var end = span.End; + + while (start < end && char.IsWhiteSpace(sourceText[end - 1])) + end--; + + while (start < end && char.IsWhiteSpace(sourceText[start])) + start++; + + return TextSpan.FromBounds(start, end); + } + + public void AddRelevantNodes( + SourceText sourceText, SyntaxNode root, TextSpan selectionRaw, bool allowEmptyNodes, int maxCount, ref TemporaryArray result, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode + { + // Given selection is trimmed first to enable over-selection that spans multiple lines. Since trailing whitespace ends + // at newline boundary over-selection to e.g. a line after LocalFunctionStatement would cause FindNode to find enclosing + // block's Node. That is because in addition to LocalFunctionStatement the selection would also contain trailing trivia + // (whitespace) of following statement. + + var syntaxFacts = this.SyntaxFacts; + var headerFacts = this.HeaderFacts; + var selectionTrimmed = GetTrimmedTextSpan(sourceText, selectionRaw); + + // If user selected only whitespace we don't want to return anything. We could do following: + // 1) Consider token that owns (as its trivia) the whitespace. + // 2) Consider start/beginning of whitespace as location (empty selection) + // Option 1) can't be used all the time and 2) can be confusing for users. Therefore bailing out is the + // most consistent option. + if (selectionTrimmed.IsEmpty && !selectionRaw.IsEmpty) + return; + + // Every time a Node is considered an extractNodes method is called to add all nodes around the original one + // that should also be considered. + // + // That enables us to e.g. return node `b` when Node `var a = b;` is being considered without a complex (and potentially + // lang. & situation dependent) into Children descending code here. We can't just try extracted Node because we might + // want the whole node `var a = b;` + + // Handle selections: + // - Most/the whole wanted Node is selected (e.g. `C [|Fun() {}|]` + // - The smallest node whose FullSpan includes the whole (trimmed) selection + // - Using FullSpan is important because it handles over-selection with comments + // - Travels upwards through same-sized (FullSpan) nodes, extracting + // - Token with wanted Node as direct parent is selected (e.g. IdentifierToken for LocalFunctionStatement: `C [|Fun|]() {}`) + // Note: Whether we have selection or location has to be checked against original selection because selecting just + // whitespace could collapse selectionTrimmed into and empty Location. But we don't want `[| |]token` + // registering as ` [||]token`. + if (!selectionTrimmed.IsEmpty) + { + AddRelevantNodesForSelection(syntaxFacts, root, selectionTrimmed, allowEmptyNodes, maxCount, ref result, cancellationToken); + } + else + { + var location = selectionTrimmed.Start; + + // No more selection -> Handle what current selection is touching: + // + // Consider touching only for empty selections. Otherwise `[|C|] methodName(){}` would be considered as + // touching the Method's Node (through the left edge, see below) which is something the user probably + // didn't want since they specifically selected only the return type. + // + // What the selection is touching is used in two ways. + // - Firstly, it is used to handle situation where it touches a Token whose direct ancestor is wanted + // Node. While having the (even empty) selection inside such token or to left of such Token is already + // handle by code above touching it from right `C methodName[||](){}` isn't (the FindNode for that + // returns Args node). + // + // - Secondly, it is used for left/right edge climbing. E.g. `[||]C methodName(){}` the touching token's + // direct ancestor is TypeNode for the return type but it is still reasonable to expect that the user + // might want to be given refactorings for the whole method (as he has caret on the edge of it). + // Therefore we travel the Node tree upwards and as long as we're on the left edge of a Node's span we + // consider such node & potentially continue traveling upwards. The situation for right edge (`C + // methodName(){}[||]`) is analogical. E.g. for right edge `C methodName(){}[||]`: CloseBraceToken -> + // BlockSyntax -> LocalFunctionStatement -> null (higher node doesn't end on position anymore) Note: + // left-edge climbing needs to handle AttributeLists explicitly, see below for more information. + // + // - Thirdly, if location isn't touching anything, we move the location to the token in whose trivia + // location is in. more about that below. + // + // - Fourthly, if we're in an expression / argument we consider touching a parent expression whenever + // we're within it as long as it is on the first line of such expression (arbitrary heuristic). + + // In addition to per-node extr also check if current location (if selection is empty) is in a header of + // higher level desired node once. We do that only for locations because otherwise `[|int|] A { get; + // set; }) would trigger all refactorings for Property Decl. We cannot check this any sooner because the + // above code could've changed current location. + AddNonHiddenCorrectTypeNodes(ExtractNodesInHeader(root, location, headerFacts), allowEmptyNodes, maxCount, ref result, cancellationToken); + if (result.Count >= maxCount) + return; + + var (tokenToLeft, tokenToRight) = GetTokensToLeftAndRight(sourceText, root, location); + + // Add Nodes for touching tokens as described above. + AddNodesForTokenToRight(syntaxFacts, root, allowEmptyNodes, maxCount, ref result, tokenToRight, cancellationToken); + if (result.Count >= maxCount) + return; + + AddNodesForTokenToLeft(syntaxFacts, allowEmptyNodes, maxCount, ref result, tokenToLeft, cancellationToken); + if (result.Count >= maxCount) + return; + + // If the wanted node is an expression syntax -> traverse upwards even if location is deep within a SyntaxNode. + // We want to treat more types like expressions, e.g.: ArgumentSyntax should still trigger even if deep-in. + if (IsWantedTypeExpressionLike()) + { + // Reason to treat Arguments (and potentially others) as Expression-like: + // https://github.com/dotnet/roslyn/pull/37295#issuecomment-516145904 + AddNodesDeepIn(sourceText, root, location, allowEmptyNodes, maxCount, ref result, cancellationToken); + } + } + } + + private static bool IsWantedTypeExpressionLike() where TSyntaxNode : SyntaxNode + { + var wantedType = typeof(TSyntaxNode); + + var expressionType = typeof(TExpressionSyntax); + var argumentType = typeof(TArgumentSyntax); + var expressionStatementType = typeof(TExpressionStatementSyntax); + + return IsAEqualOrSubclassOfB(wantedType, expressionType) || + IsAEqualOrSubclassOfB(wantedType, argumentType) || + IsAEqualOrSubclassOfB(wantedType, expressionStatementType); + + static bool IsAEqualOrSubclassOfB(Type a, Type b) + { + return a == b || a.IsSubclassOf(b); + } + } + + private (SyntaxToken tokenToLeft, SyntaxToken tokenToRight) GetTokensToLeftAndRight( + SourceText sourceText, SyntaxNode root, int location) + { + // get Token for current location + var tokenOnLocation = root.FindToken(location); + + var syntaxKinds = this.SyntaxFacts.SyntaxKinds; + if (tokenOnLocation.RawKind == syntaxKinds.CommaToken && location >= tokenOnLocation.Span.End) + { + var commaToken = tokenOnLocation; + + // A couple of scenarios to care about: + // + // X,$$ Y + // + // In this case, consider the user on the Y node. + // + // X,$$ + // Y + // + // In this case, consider the user on the X node. + var nextToken = commaToken.GetNextToken(); + var previousToken = commaToken.GetPreviousToken(); + if (nextToken != default && !commaToken.TrailingTrivia.Any(t => t.RawKind == syntaxKinds.EndOfLineTrivia)) + { + return (tokenToLeft: default, tokenToRight: nextToken); + } + else if (previousToken != default && previousToken.Span.End == commaToken.Span.Start) + { + return (tokenToLeft: previousToken, tokenToRight: default); + } + } + + // Gets a token that is directly to the right of current location or that encompasses current location (`[||]tokenToRightOrIn` or `tok[||]enToRightOrIn`) + var tokenToRight = tokenOnLocation.Span.Contains(location) + ? tokenOnLocation + : default; + + // A token can be to the left only when there's either no tokenDirectlyToRightOrIn or there's one directly starting at current location. + // Otherwise (otherwise tokenToRightOrIn is also left from location, e.g: `tok[||]enToRightOrIn`) + var tokenToLeft = default(SyntaxToken); + if (tokenToRight == default || tokenToRight.FullSpan.Start == location) + { + var previousToken = tokenOnLocation.Span.End == location + ? tokenOnLocation + : tokenOnLocation.GetPreviousToken(includeZeroWidth: true); + + tokenToLeft = previousToken.Span.End == location + ? previousToken + : default; + } + + // If both tokens directly to left & right are empty -> we're somewhere in the middle of whitespace. + // Since there wouldn't be (m)any other refactorings we can try to offer at least the ones for (semantically) + // closest token/Node. Thus, we move the location to the token in whose `.FullSpan` the original location was. + if (tokenToLeft == default && + tokenToRight == default && + IsAcceptableLineDistanceAway(sourceText, tokenOnLocation, location)) + { + // tokenOnLocation: token in whose trivia location is at + if (tokenOnLocation.Span.Start >= location) + { + tokenToRight = tokenOnLocation; + } + else + { + tokenToLeft = tokenOnLocation; + } + } + + return (tokenToLeft, tokenToRight); + + static bool IsAcceptableLineDistanceAway( + SourceText sourceText, SyntaxToken tokenOnLocation, int location) + { + // assume non-trivia token can't span multiple lines + var tokenLine = sourceText.Lines.GetLineFromPosition(tokenOnLocation.Span.Start); + var locationLine = sourceText.Lines.GetLineFromPosition(location); + + // Change location to nearest token only if the token is off by one line or less + var lineDistance = tokenLine.LineNumber - locationLine.LineNumber; + if (lineDistance is not 0 and not 1) + return false; + + // Note: being a line below a tokenOnLocation is impossible in current model as whitespace + // trailing trivia ends on new line. Which is fine because if you're a line _after_ some node + // you usually don't want refactorings for what's above you. + + if (lineDistance == 1) + { + // position is one line above the node of interest. This is fine if that + // line is blank. Otherwise, if it isn't (i.e. it contains comments, + // directives, or other trivia), then it's not likely the user is selecting + // this entry. + return locationLine.IsEmptyOrWhitespace(); + } + + // On hte same line. This position is acceptable. + return true; + } + } + + private void AddNodesForTokenToLeft( + ISyntaxFacts syntaxFacts, + bool allowEmptyNodes, + int maxCount, + ref TemporaryArray result, + SyntaxToken tokenToLeft, + CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode + { + var location = tokenToLeft.Span.End; + + // there could be multiple (n) tokens to the left if first n-1 are Empty -> iterate over all of them + while (tokenToLeft != default) + { + var leftNode = tokenToLeft.Parent; + do + { + // Consider either a Node that is: + // - Ancestor Node of such Token as long as their span ends on location (it's still on the edge) + AddNonHiddenCorrectTypeNodes(ExtractNodesSimple(leftNode, syntaxFacts), allowEmptyNodes, maxCount, ref result, cancellationToken); + if (result.Count >= maxCount) + return; + + leftNode = leftNode?.Parent; + if (leftNode is null) + break; + + if (leftNode.GetLastToken().Span.End != location && leftNode.Span.End != location) + break; + } + while (true); + + // as long as current tokenToLeft is empty -> its previous token is also tokenToLeft + tokenToLeft = tokenToLeft.Span.IsEmpty + ? tokenToLeft.GetPreviousToken(includeZeroWidth: true) + : default; + } + } + + private void AddNodesForTokenToRight( + ISyntaxFacts syntaxFacts, + SyntaxNode root, + bool allowEmptyNodes, + int maxCount, + ref TemporaryArray result, + SyntaxToken tokenToRightOrIn, + CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode + { + var location = tokenToRightOrIn.Span.Start; + + if (tokenToRightOrIn != default) + { + var rightNode = tokenToRightOrIn.Parent; + do + { + // Consider either a Node that is: + // - Parent of touched Token (location can be within) + // - Ancestor Node of such Token as long as their span starts on location (it's still on the edge) + AddNonHiddenCorrectTypeNodes(ExtractNodesSimple(rightNode, syntaxFacts), allowEmptyNodes, maxCount, ref result, cancellationToken); + if (result.Count >= maxCount) + return; + + rightNode = rightNode?.Parent; + if (rightNode == null) + break; + + // The edge climbing for node to the right needs to handle Attributes e.g.: + // [Test1] + // //Comment1 + // [||]object Property1 { get; set; } + // In essence: + // - On the left edge of the node (-> left edge of first AttributeLists) + // - On the left edge of the node sans AttributeLists (& as everywhere comments) + if (rightNode.Span.Start != location) + { + var rightNodeSpanWithoutAttributes = syntaxFacts.GetSpanWithoutAttributes(root, rightNode); + if (rightNodeSpanWithoutAttributes.Start != location) + break; + } + } + while (true); + } + } + + private void AddRelevantNodesForSelection( + ISyntaxFacts syntaxFacts, + SyntaxNode root, + TextSpan selectionTrimmed, + bool allowEmptyNodes, + int maxCount, + ref TemporaryArray result, + CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode + { + var selectionNode = root.FindNode(selectionTrimmed, getInnermostNodeForTie: true); + var prevNode = selectionNode; + do + { + var nonHiddenExtractedSelectedNodes = ExtractNodesSimple(selectionNode, syntaxFacts).OfType().Where(n => !n.OverlapsHiddenPosition(cancellationToken)); + foreach (var nonHiddenExtractedNode in nonHiddenExtractedSelectedNodes) + { + // For selections we need to handle an edge case where only AttributeLists are within selection (e.g. `Func([|[in][out]|] arg1);`). + // In that case the smallest encompassing node is still the whole argument node but it's hard to justify showing refactorings for it + // if user selected only its attributes. + + // Selection contains only AttributeLists -> don't consider current Node + var spanWithoutAttributes = syntaxFacts.GetSpanWithoutAttributes(root, nonHiddenExtractedNode); + if (!selectionTrimmed.IntersectsWith(spanWithoutAttributes)) + { + break; + } + + AddNode(allowEmptyNodes, ref result, nonHiddenExtractedNode); + if (result.Count >= maxCount) + return; + } + + prevNode = selectionNode; + selectionNode = selectionNode.Parent; + } + while (selectionNode != null && prevNode.FullWidth() == selectionNode.FullWidth()); + } + + /// + /// Extractor function that retrieves all nodes that should be considered for extraction of given current node. + /// + /// The rationale is that when user selects e.g. entire local declaration statement [|var a = b;|] it is reasonable + /// to provide refactoring for `b` node. Similarly for other types of refactorings. + /// + /// + /// + /// Should also return given node. + /// + protected virtual IEnumerable ExtractNodesSimple(SyntaxNode? node, ISyntaxFacts syntaxFacts) + { + if (node == null) + { + yield break; + } + + // First return the node itself so that it is considered + yield return node; + + // REMARKS: + // The set of currently attempted extractions is in no way exhaustive and covers only cases + // that were found to be relevant for refactorings that were moved to `TryGetSelectedNodeAsync`. + // Feel free to extend it / refine current heuristics. + + // `var a = b;` | `var a = b`; + if (syntaxFacts.IsLocalDeclarationStatement(node) || syntaxFacts.IsLocalDeclarationStatement(node.Parent)) + { + var localDeclarationStatement = syntaxFacts.IsLocalDeclarationStatement(node) ? node : node.Parent!; + + // Check if there's only one variable being declared, otherwise following transformation + // would go through which isn't reasonable since we can't say the first one specifically + // is wanted. + // `var a = 1, `c = 2, d = 3`; + // -> `var a = 1`, c = 2, d = 3; + var variables = syntaxFacts.GetVariablesOfLocalDeclarationStatement(localDeclarationStatement); + if (variables.Count == 1) + { + var declaredVariable = variables.First(); + + // -> `a = b` + yield return declaredVariable; + + // -> `b` + var initializer = syntaxFacts.GetInitializerOfVariableDeclarator(declaredVariable); + if (initializer != null) + { + var value = syntaxFacts.GetValueOfEqualsValueClause(initializer); + if (value != null) + { + yield return value; + } + } + } + } + + // var `a = b`; + if (syntaxFacts.IsVariableDeclarator(node)) + { + // -> `b` + var initializer = syntaxFacts.GetInitializerOfVariableDeclarator(node); + if (initializer != null) + { + var value = syntaxFacts.GetValueOfEqualsValueClause(initializer); + if (value != null) + { + yield return value; + } + } + } + + // `a = b;` + // -> `b` + if (syntaxFacts.IsSimpleAssignmentStatement(node)) + { + syntaxFacts.GetPartsOfAssignmentExpressionOrStatement(node, out _, out _, out var rightSide); + yield return rightSide; + } + + // `a();` + // -> a() + if (syntaxFacts.IsExpressionStatement(node)) + { + yield return syntaxFacts.GetExpressionOfExpressionStatement(node); + } + + // `a()`; + // -> `a();` + if (syntaxFacts.IsExpressionStatement(node.Parent)) + { + yield return node.Parent; + } + } + + /// + /// Extractor function that checks and retrieves all nodes current location is in a header. + /// + protected virtual IEnumerable ExtractNodesInHeader(SyntaxNode root, int location, IHeaderFacts headerFacts) + { + // Header: [Test] `public int a` { get; set; } + if (headerFacts.IsOnPropertyDeclarationHeader(root, location, out var propertyDeclaration)) + yield return propertyDeclaration; + + // Header: public C([Test]`int a = 42`) {} + if (headerFacts.IsOnParameterHeader(root, location, out var parameter)) + yield return parameter; + + // Header: `public I.C([Test]int a = 42)` {} + if (headerFacts.IsOnMethodHeader(root, location, out var method)) + yield return method; + + // Header: `static C([Test]int a = 42)` {} + if (headerFacts.IsOnLocalFunctionHeader(root, location, out var localFunction)) + yield return localFunction; + + // Header: `var a = `3,` b = `5,` c = `7 + 3``; + if (headerFacts.IsOnLocalDeclarationHeader(root, location, out var localDeclaration)) + yield return localDeclaration; + + // Header: `if(...)`{ }; + if (headerFacts.IsOnIfStatementHeader(root, location, out var ifStatement)) + yield return ifStatement; + + // Header: `foreach (var a in b)` { } + if (headerFacts.IsOnForeachHeader(root, location, out var foreachStatement)) + yield return foreachStatement; + + if (headerFacts.IsOnTypeHeader(root, location, out var typeDeclaration)) + yield return typeDeclaration; + } + + private static void AddNodesDeepIn( + SourceText sourceText, + SyntaxNode root, + int position, + bool allowEmptyNodes, + int maxCount, + ref TemporaryArray result, + CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode + { + // If we're deep inside we don't have to deal with being on edges (that gets dealt by TryGetSelectedNodeAsync) + // -> can simply FindToken -> proceed testing its ancestors + var token = root.FindTokenOnRightOfPosition(position, true); + + // traverse upwards and add all parents if of correct type + var ancestor = token.Parent; + while (ancestor != null) + { + if (ancestor is TSyntaxNode typedAncestor) + { + var argumentStartLine = sourceText.Lines.GetLineFromPosition(typedAncestor.Span.Start).LineNumber; + var caretLine = sourceText.Lines.GetLineFromPosition(position).LineNumber; + + if (argumentStartLine == caretLine && !typedAncestor.OverlapsHiddenPosition(cancellationToken)) + { + AddNode(allowEmptyNodes, ref result, typedAncestor); + if (result.Count >= maxCount) + return; + } + else if (argumentStartLine < caretLine) + { + // higher level nodes will have Span starting at least on the same line -> can bail out + return; + } + } + + ancestor = ancestor.Parent; + } + } + + private static void AddNonHiddenCorrectTypeNodes( + IEnumerable nodes, bool allowEmptyNodes, int maxCount, ref TemporaryArray result, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode + { + foreach (var node in nodes) + { + if (node is TSyntaxNode typedNode && + !node.OverlapsHiddenPosition(cancellationToken)) + { + AddNode(allowEmptyNodes, ref result, typedNode); + if (result.Count >= maxCount) + return; + } + } + } + + public bool IsOnTypeHeader(SyntaxNode root, int position, bool fullHeader, [NotNullWhen(true)] out SyntaxNode? typeDeclaration) + => HeaderFacts.IsOnTypeHeader(root, position, fullHeader, out typeDeclaration); + + public bool IsOnPropertyDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? propertyDeclaration) + => HeaderFacts.IsOnPropertyDeclarationHeader(root, position, out propertyDeclaration); + + public bool IsOnParameterHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? parameter) + => HeaderFacts.IsOnParameterHeader(root, position, out parameter); + + public bool IsOnMethodHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? method) + => HeaderFacts.IsOnMethodHeader(root, position, out method); + + public bool IsOnLocalFunctionHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localFunction) + => HeaderFacts.IsOnLocalFunctionHeader(root, position, out localFunction); + + public bool IsOnLocalDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localDeclaration) + => HeaderFacts.IsOnLocalDeclarationHeader(root, position, out localDeclaration); + + public bool IsOnIfStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? ifStatement) + => HeaderFacts.IsOnIfStatementHeader(root, position, out ifStatement); + + public bool IsOnWhileStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? whileStatement) + => HeaderFacts.IsOnWhileStatementHeader(root, position, out whileStatement); + + public bool IsOnForeachHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? foreachStatement) + => HeaderFacts.IsOnForeachHeader(root, position, out foreachStatement); +} diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/RefactoringHelpers/IRefactoringHelpers.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/RefactoringHelpers/IRefactoringHelpers.cs new file mode 100644 index 0000000000000..8908bf2dc59be --- /dev/null +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/RefactoringHelpers/IRefactoringHelpers.cs @@ -0,0 +1,56 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.LanguageService; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.CodeRefactorings; + +/// +/// Contains helpers related to asking intuitive semantic questions about a users intent +/// based on the position of their caret or span of their selection. +/// +internal interface IRefactoringHelpers : IHeaderFacts +{ + /// + /// True if the user is on a blank line where a member could go inside a type declaration. + /// This will be between members and not ever inside a member. + /// + bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration); + + /// + /// + /// Returns an array of instances for refactoring given specified selection + /// in document. determines if the returned nodes will can have empty spans + /// or not. + /// + /// + /// A instance is returned if: - Selection is zero-width and inside/touching + /// a Token with direct parent of type . - Selection is zero-width and + /// touching a Token whose ancestor of type ends/starts precisely on current + /// selection. - Selection is zero-width and in whitespace that corresponds to a Token whose direct ancestor is + /// of type of type . - Selection is zero-width and in a header (defined by + /// ISyntaxFacts helpers) of an node of type of type . - Token whose direct + /// parent of type is selected. - Selection is zero-width and wanted node is + /// an expression / argument with selection within such syntax node (arbitrarily deep) on its first line. - + /// Whole node of a type is selected. + /// + /// + /// Attempts extracting a Node of type for each Node it considers (see + /// above). E.g. extracts initializer expressions from declarations and assignments, Property declaration from + /// any header node, etc. + /// + /// + /// Note: this function trims all whitespace from both the beginning and the end of given . The trimmed version is then used to determine relevant . It also + /// handles incomplete selections of tokens gracefully. Over-selection containing leading comments is also + /// handled correctly. + /// + /// + void AddRelevantNodes( + SourceText sourceText, SyntaxNode root, TextSpan selection, bool allowEmptyNodes, int maxCount, ref TemporaryArray result, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode; +} diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SemanticFacts/ISemanticFacts.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SemanticFacts/ISemanticFacts.cs index 7db9c7e856f5e..810927c0e5d8a 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SemanticFacts/ISemanticFacts.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SemanticFacts/ISemanticFacts.cs @@ -121,7 +121,7 @@ internal partial interface ISemanticFacts bool TryGetPrimaryConstructor(INamedTypeSymbol typeSymbol, [NotNullWhen(true)] out IMethodSymbol? primaryConstructor); -#if !CODE_STYLE +#if WORKSPACE /// /// Given a location in a document, returns the symbol that intercepts the original symbol called at that location. diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/AbstractDocumentationCommentService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/AbstractDocumentationCommentService.cs index dc7b3a1f74f77..d1c835e39fee3 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/AbstractDocumentationCommentService.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/AbstractDocumentationCommentService.cs @@ -3,9 +3,9 @@ // See the LICENSE file in the project root for more information. using System.Linq; +using System.Text; using System.Threading; using Roslyn.Utilities; -using System.Text; namespace Microsoft.CodeAnalysis.LanguageService; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ISyntaxFactsExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ISyntaxFactsExtensions.cs index 7c00e010eb54a..f6a2d095ea2ce 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ISyntaxFactsExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ISyntaxFactsExtensions.cs @@ -159,9 +159,9 @@ private static bool IsOnSingleLine(string value) public static bool ContainsInterleavedDirective( this ISyntaxFacts syntaxFacts, ImmutableArray nodes, CancellationToken cancellationToken) { - if (nodes.Length > 0) + if (nodes is [var firstNode, ..] and [.., var lastNode]) { - var span = TextSpan.FromBounds(nodes.First().Span.Start, nodes.Last().Span.End); + var span = TextSpan.FromBounds(firstNode.Span.Start, lastNode.Span.End); foreach (var node in nodes) { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ISyntaxKinds.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ISyntaxKinds.cs index 71cdf02df8537..41981d1cb8dfd 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ISyntaxKinds.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ISyntaxKinds.cs @@ -161,11 +161,13 @@ internal interface ISyntaxKinds int ReferenceNotEqualsExpression { get; } int SimpleAssignmentExpression { get; } int SimpleMemberAccessExpression { get; } + int? SizeOfExpression { get; } int? SuppressNullableWarningExpression { get; } int TernaryConditionalExpression { get; } int ThisExpression { get; } int? ThrowExpression { get; } int TupleExpression { get; } + int TypeOfExpression { get; } #endregion diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.AssemblySymbolKey.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.AssemblySymbolKey.cs index 83f6b5b141fa2..c398c186cd23b 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.AssemblySymbolKey.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.AssemblySymbolKey.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Microsoft.CodeAnalysis.Shared.Extensions; - namespace Microsoft.CodeAnalysis; internal partial struct SymbolKey diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.EventSymbolKey.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.EventSymbolKey.cs index ec572d6ebba0b..05db680762dec 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.EventSymbolKey.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.EventSymbolKey.cs @@ -14,7 +14,9 @@ public sealed override void Create(IEventSymbol symbol, SymbolKeyWriter visitor) { visitor.WriteString(symbol.MetadataName); visitor.WriteSymbolKey(symbol.ContainingType); +#if !ROSLYN_4_12_OR_LOWER visitor.WriteBoolean(symbol.PartialDefinitionPart is not null); +#endif } protected sealed override SymbolKeyResolution Resolve( @@ -22,7 +24,9 @@ protected sealed override SymbolKeyResolution Resolve( { var metadataName = reader.ReadString(); var containingTypeResolution = reader.ReadSymbolKey(contextualSymbol?.ContainingType, out var containingTypeFailureReason); +#if !ROSLYN_4_12_OR_LOWER var isPartialImplementationPart = reader.ReadBoolean(); +#endif if (containingTypeFailureReason != null) { @@ -32,6 +36,7 @@ protected sealed override SymbolKeyResolution Resolve( using var events = GetMembersOfNamedType(containingTypeResolution, metadataName); +#if !ROSLYN_4_12_OR_LOWER if (isPartialImplementationPart) { for (var i = 0; i < events.Builder.Count; i++) @@ -40,6 +45,7 @@ protected sealed override SymbolKeyResolution Resolve( events.Builder[i] = candidate.PartialImplementationPart ?? candidate; } } +#endif return CreateResolution(events, $"({nameof(EventSymbolKey)} '{metadataName}' not found)", out failureReason); } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.NamedTypeSymbolKey.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.NamedTypeSymbolKey.cs index 6bca171a77198..d6a1aed307481 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.NamedTypeSymbolKey.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.NamedTypeSymbolKey.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Collections.Immutable; - namespace Microsoft.CodeAnalysis; internal partial struct SymbolKey @@ -17,8 +15,10 @@ public sealed override void Create(INamedTypeSymbol symbol, SymbolKeyWriter visi visitor.WriteSymbolKey(symbol.ContainingSymbol); visitor.WriteString(symbol.Name); visitor.WriteInteger(symbol.Arity); +#if !ROSLYN_4_12_OR_LOWER // Include the metadata name for extensions. We need this to uniquely find it when resolving. visitor.WriteString(symbol.IsExtension ? symbol.MetadataName : null); +#endif // Include the file path for 'file-local' types. We need this to uniquely find it when resolving. visitor.WriteString(symbol.IsFileLocal ? symbol.DeclaringSyntaxReferences[0].SyntaxTree.FilePath : null); visitor.WriteBoolean(symbol.IsUnboundGenericType); @@ -35,7 +35,11 @@ protected sealed override SymbolKeyResolution Resolve( var containingSymbolResolution = reader.ReadSymbolKey(contextualSymbol?.ContainingSymbol, out var containingSymbolFailureReason); var name = reader.ReadRequiredString(); var arity = reader.ReadInteger(); +#if !ROSLYN_4_12_OR_LOWER var extensionMetadataName = reader.ReadString(); +#else + string? extensionMetadataName = null; +#endif var filePath = reader.ReadString(); var isUnboundGenericType = reader.ReadBoolean(); var isNativeIntegerType = reader.ReadBoolean(); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.ParameterSymbolKey.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.ParameterSymbolKey.cs index 56d5d72914c2d..e5ac0aa083f74 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.ParameterSymbolKey.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.ParameterSymbolKey.cs @@ -69,9 +69,11 @@ protected sealed override SymbolKeyResolution Resolve( } break; +#if !ROSLYN_4_12_OR_LOWER case INamedTypeSymbol { IsExtension: true, ExtensionParameter: { } extensionParameter }: Resolve(result, reader, metadataName, ordinal, [extensionParameter]); break; +#endif } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.PreprocessingSymbolKey.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.PreprocessingSymbolKey.cs index 11137f869770f..a9e637b6a486b 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.PreprocessingSymbolKey.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.PreprocessingSymbolKey.cs @@ -15,8 +15,13 @@ public sealed override void Create(IPreprocessingSymbol symbol, SymbolKeyWriter protected sealed override SymbolKeyResolution Resolve(SymbolKeyReader reader, IPreprocessingSymbol? contextualSymbol, out string? failureReason) { +#if !ROSLYN_4_12_OR_LOWER failureReason = null; return new SymbolKeyResolution(reader.Compilation.CreatePreprocessingSymbol(reader.ReadRequiredString())); +#else + failureReason = "Preprocessing symbols are not supported in this version of Roslyn."; + return default; +#endif } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.TupleTypeSymbolKey.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.TupleTypeSymbolKey.cs index 10114d6fcccbf..253ac22d34be0 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.TupleTypeSymbolKey.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.TupleTypeSymbolKey.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Linq; using System.Collections.Immutable; using System.Diagnostics; +using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.cs index 551ee7a466d5b..c7dbb3c64bda7 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#pragma warning disable CS0419 // Ambiguous reference in cref attribute + using System; using System.Collections.Generic; using System.Collections.Immutable; @@ -337,7 +339,7 @@ public override readonly int GetHashCode() { var position = GetDataStartPosition(_symbolKeyData); -#if NETSTANDARD +#if !NET var hashCode = 0; foreach (var ch in _symbolKeyData[position..]) hashCode = Hash.Combine(ch, hashCode); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKeyResolution.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKeyResolution.cs index 759448ef05fca..294422fdce90c 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKeyResolution.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKeyResolution.cs @@ -17,19 +17,17 @@ namespace Microsoft.CodeAnalysis; /// internal readonly partial struct SymbolKeyResolution { - private readonly ImmutableArray _candidateSymbols; - internal SymbolKeyResolution(ISymbol? symbol) { Symbol = symbol; - _candidateSymbols = default; + CandidateSymbols = default; CandidateReason = CandidateReason.None; } internal SymbolKeyResolution(ImmutableArray candidateSymbols, CandidateReason candidateReason) { Symbol = null; - _candidateSymbols = candidateSymbols; + CandidateSymbols = candidateSymbols; CandidateReason = candidateReason; } @@ -37,7 +35,7 @@ internal SymbolKeyResolution(ImmutableArray candidateSymbols, Candidate public ISymbol? Symbol { get; } public CandidateReason CandidateReason { get; } - public ImmutableArray CandidateSymbols => _candidateSymbols.NullToEmpty(); + public ImmutableArray CandidateSymbols => field.NullToEmpty(); public Enumerator GetEnumerator() => new(this); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/System.Text/Rune.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/System.Text/Rune.cs index 6630aef9059f8..3d6279a170601 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/System.Text/Rune.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/System.Text/Rune.cs @@ -1147,7 +1147,7 @@ public static UnicodeCategory GetUnicodeCategory(Rune value) private static UnicodeCategory GetUnicodeCategoryNonAscii(Rune value) { Debug.Assert(!value.IsAscii, "Shouldn't use this non-optimized code path for ASCII characters."); -#if !NETSTANDARD2_0 +#if NET return CharUnicodeInfo.GetUnicodeCategory(value.Value); #else if (value.IsBmp) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/System.Text/Utf16Utility.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/System.Text/Utf16Utility.cs index 5fec2f300b4f6..e600cd9285e6d 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/System.Text/Utf16Utility.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/System.Text/Utf16Utility.cs @@ -10,8 +10,8 @@ #if !NETCOREAPP -using System.Runtime.CompilerServices; using System.Diagnostics; +using System.Runtime.CompilerServices; namespace System.Text.Unicode; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AbstractSpeculationAnalyzer.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AbstractSpeculationAnalyzer.cs index 87ed543ae0abf..32e26d5b023c0 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AbstractSpeculationAnalyzer.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AbstractSpeculationAnalyzer.cs @@ -45,8 +45,6 @@ internal abstract class AbstractSpeculationAnalyzer< private readonly bool _skipVerificationForReplacedNode; private readonly bool _failOnOverloadResolutionFailuresInOriginalCode; private readonly bool _isNewSemanticModelSpeculativeModel; - - private SyntaxNode? _lazySemanticRootOfOriginalExpression; private TExpressionSyntax? _lazyReplacedExpression; private SyntaxNode? _lazySemanticRootOfReplacedExpression; private SemanticModel? _lazySpeculativeSemanticModel; @@ -87,7 +85,7 @@ public AbstractSpeculationAnalyzer( _failOnOverloadResolutionFailuresInOriginalCode = failOnOverloadResolutionFailuresInOriginalCode; _isNewSemanticModelSpeculativeModel = true; _lazyReplacedExpression = null; - _lazySemanticRootOfOriginalExpression = null; + SemanticRootOfOriginalExpression = null; _lazySemanticRootOfReplacedExpression = null; _lazySpeculativeSemanticModel = null; } @@ -134,18 +132,21 @@ protected abstract void GetForEachSymbols( /// field initializer, default parameter initializer or type syntax node. /// It serves as the root node for all semantic analysis for this syntax replacement. /// + [AllowNull] public SyntaxNode SemanticRootOfOriginalExpression { get { - if (_lazySemanticRootOfOriginalExpression == null) + if (field == null) { - _lazySemanticRootOfOriginalExpression = GetSemanticRootForSpeculation(this.OriginalExpression); - RoslynDebug.AssertNotNull(_lazySemanticRootOfOriginalExpression); + field = GetSemanticRootForSpeculation(this.OriginalExpression); + RoslynDebug.AssertNotNull(field); } - return _lazySemanticRootOfOriginalExpression; + return field; } + + private set; } /// diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BKTree.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BKTree.cs index 981ec07005aee..5689f33f846d1 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BKTree.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BKTree.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Collections; namespace Roslyn.Utilities; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BidirectionalMap.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BidirectionalMap.cs index d6b4dfafeb387..3f6d367a7ac44 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BidirectionalMap.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BidirectionalMap.cs @@ -22,13 +22,13 @@ internal sealed class BidirectionalMap : IBidirectionalMap> pairs, IEqualityComparer? keyComparer = null, IEqualityComparer? valueComparer = null) : this(forwardMap: ImmutableDictionary.CreateRange(keyComparer, pairs), - backwardMap: ImmutableDictionary.CreateRange(valueComparer, pairs.Select(static p => KeyValuePairUtil.Create(p.Value, p.Key)))) + backwardMap: ImmutableDictionary.CreateRange(valueComparer, pairs.Select(static p => KeyValuePair.Create(p.Value, p.Key)))) { } public BidirectionalMap(IEnumerable<(TKey key, TValue value)> pairs, IEqualityComparer? keyComparer = null, IEqualityComparer? valueComparer = null) - : this(forwardMap: ImmutableDictionary.CreateRange(keyComparer, pairs.Select(static p => KeyValuePairUtil.Create(p.key, p.value))), - backwardMap: ImmutableDictionary.CreateRange(valueComparer, pairs.Select(static p => KeyValuePairUtil.Create(p.value, p.key)))) + : this(forwardMap: ImmutableDictionary.CreateRange(keyComparer, pairs.Select(static p => KeyValuePair.Create(p.key, p.value))), + backwardMap: ImmutableDictionary.CreateRange(valueComparer, pairs.Select(static p => KeyValuePair.Create(p.value, p.key)))) { } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/CompilerUtilities/ImmutableDictionaryExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/CompilerUtilities/ImmutableDictionaryExtensions.cs index ff8fde045be6b..5f8c972b89df7 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/CompilerUtilities/ImmutableDictionaryExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/CompilerUtilities/ImmutableDictionaryExtensions.cs @@ -3,7 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; -using Roslyn.Utilities; +using System.Collections.Generic; namespace Microsoft.CodeAnalysis; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/EnumValueUtilities.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/EnumValueUtilities.cs index a29bad9237d4d..e105fbb34ffb0 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/EnumValueUtilities.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/EnumValueUtilities.cs @@ -7,6 +7,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis; using Roslyn.Utilities; @@ -138,4 +139,14 @@ private static bool LooksLikeFlagsEnum(List existingConstants) return false; } + + public static TToEnum ConvertEnum(TFromEnum value) + where TFromEnum : struct, Enum + where TToEnum : struct, Enum + { + // Ensure that this is only called for enums that are actually compatible with each other. + Contract.ThrowIfTrue(typeof(TFromEnum).GetEnumUnderlyingType() != typeof(TToEnum).GetEnumUnderlyingType()); + + return Unsafe.As(ref value); + } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/EnumerableConditionalWeakTable.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/EnumerableConditionalWeakTable.cs index b4f2fca4d6ae8..6c725e3caa07e 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/EnumerableConditionalWeakTable.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/EnumerableConditionalWeakTable.cs @@ -122,7 +122,7 @@ public IEnumerator> GetEnumerator() { if (item.TryGetTarget(out var box)) { - yield return KeyValuePairUtil.Create(box.Key, box.Value); + yield return KeyValuePair.Create(box.Key, box.Value); } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/InterceptsLocationUtilities.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/InterceptsLocationUtilities.cs index bc05ee6b27832..8ac5651dcf18b 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/InterceptsLocationUtilities.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/InterceptsLocationUtilities.cs @@ -5,6 +5,7 @@ using System; using System.Buffers.Binary; using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/OptionalExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/OptionalExtensions.cs index 46b3036f1d731..1085220ddfa74 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/OptionalExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/OptionalExtensions.cs @@ -2,7 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Shared.Utilities; namespace Roslyn.Utilities; @@ -10,4 +12,14 @@ internal static class OptionalExtensions { internal static T GetValueOrDefault(this Optional optional) where T : struct => optional.Value; + + public static Optional ConvertEnum(this Optional optional) + where TFromEnum : struct, Enum + where TToEnum : struct, Enum + { + if (!optional.HasValue) + return default; + + return EnumValueUtilities.ConvertEnum(optional.Value); + } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/PooledBuilderExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/PooledBuilderExtensions.cs index f32490474b7fa..01042b6a8acc0 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/PooledBuilderExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/PooledBuilderExtensions.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ProducerConsumer.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ProducerConsumer.cs index 1a4db11380ff3..82eb56d9089cc 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ProducerConsumer.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ProducerConsumer.cs @@ -5,7 +5,6 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; -using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ReferenceCountedDisposable.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ReferenceCountedDisposable.cs index e1d76bd0d909d..0aec4cb6f8ce8 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ReferenceCountedDisposable.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ReferenceCountedDisposable.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#pragma warning disable CS0419 // Ambiguous reference in cref attribute + using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; @@ -115,7 +117,7 @@ private ReferenceCountedDisposable(T instance, BoxedReferenceCount referenceCoun /// it returns after any code invokes . /// /// The target object. - public T Target => _instance ?? throw new ObjectDisposedException(nameof(ReferenceCountedDisposable)); + public T Target => _instance ?? throw new ObjectDisposedException(nameof(ReferenceCountedDisposable<>)); /// /// Increments the reference count for the disposable object, and returns a new disposable reference to it. diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/StringBreaker.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/StringBreaker.cs index 15590b525d033..798cbf5b91bd5 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/StringBreaker.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/StringBreaker.cs @@ -3,7 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; -using Microsoft.CodeAnalysis.Shared.Collections; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Shared.Utilities; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/WeakEvent`1.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/WeakEvent`1.cs index 4fdaab9f238ab..690e5e15869ad 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/WeakEvent`1.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/WeakEvent`1.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections.Generic; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Compilation/CompilationExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Compilation/CompilationExtensions.cs index 0915710e67a7b..deb8e86fa466f 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Compilation/CompilationExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Compilation/CompilationExtensions.cs @@ -19,8 +19,8 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; +using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Diagnostics/DiagnosticSeverityExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Diagnostics/DiagnosticSeverityExtensions.cs new file mode 100644 index 0000000000000..8c685a52a258d --- /dev/null +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Diagnostics/DiagnosticSeverityExtensions.cs @@ -0,0 +1,30 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal static partial class DiagnosticSeverityExtensions +{ + /// + /// Returns the equivalent for a value. + /// + /// The value. + /// + /// The equivalent for the value. + /// + /// + /// If is not one of the expected values. + /// + public static ReportDiagnostic ToReportDiagnostic(this DiagnosticSeverity diagnosticSeverity) + => diagnosticSeverity switch + { + DiagnosticSeverity.Hidden => ReportDiagnostic.Hidden, + DiagnosticSeverity.Info => ReportDiagnostic.Info, + DiagnosticSeverity.Warning => ReportDiagnostic.Warn, + DiagnosticSeverity.Error => ReportDiagnostic.Error, + _ => throw ExceptionUtilities.UnexpectedValue(diagnosticSeverity), + }; +} diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Diagnostics/ReportDiagnosticExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Diagnostics/ReportDiagnosticExtensions.cs new file mode 100644 index 0000000000000..fc668d07c5fc3 --- /dev/null +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Diagnostics/ReportDiagnosticExtensions.cs @@ -0,0 +1,68 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal static partial class ReportDiagnosticExtensions +{ + /// + /// Returns the equivalent for a value. + /// + /// The value. + /// + /// The equivalent for a value; otherwise, + /// if does not contain a direct equivalent for + /// . + /// + /// + /// If is not one of the expected values. + /// + public static DiagnosticSeverity? ToDiagnosticSeverity(this ReportDiagnostic reportDiagnostic) + { + switch (reportDiagnostic) + { + case ReportDiagnostic.Error: + return DiagnosticSeverity.Error; + + case ReportDiagnostic.Warn: + return DiagnosticSeverity.Warning; + + case ReportDiagnostic.Info: + return DiagnosticSeverity.Info; + + case ReportDiagnostic.Hidden: + return DiagnosticSeverity.Hidden; + + case ReportDiagnostic.Suppress: + case ReportDiagnostic.Default: + return null; + + default: + throw ExceptionUtilities.UnexpectedValue(reportDiagnostic); + } + } + + /// + /// Applies a default severity to a value. + /// + /// The value. + /// The default severity. + /// + /// If is , returns + /// . + /// -or- + /// Otherwise, returns if it has a non-default value. + /// + public static ReportDiagnostic WithDefaultSeverity(this ReportDiagnostic reportDiagnostic, DiagnosticSeverity defaultSeverity) + { + if (reportDiagnostic != ReportDiagnostic.Default) + { + return reportDiagnostic; + } + + return defaultSeverity.ToReportDiagnostic(); + } +} diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Microsoft.CodeAnalysis.Extensions.projitems b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Microsoft.CodeAnalysis.Extensions.projitems index 30c6a58bcbf27..0411282359f37 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Microsoft.CodeAnalysis.Extensions.projitems +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Microsoft.CodeAnalysis.Extensions.projitems @@ -11,6 +11,8 @@ + + @@ -52,4 +54,7 @@ + + + \ No newline at end of file diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/IParameterSymbolExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/IParameterSymbolExtensions.cs index efd4bece73548..f6626dc614c31 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/IParameterSymbolExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/IParameterSymbolExtensions.cs @@ -4,6 +4,7 @@ #nullable enable +using System.Linq; using System.Threading; namespace Microsoft.CodeAnalysis.Shared.Extensions; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ISymbolExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ISymbolExtensions.cs index a8ba7ef3681ce..c6ba0e34aaafd 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ISymbolExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ISymbolExtensions.cs @@ -4,6 +4,7 @@ #nullable enable #pragma warning disable RS1024 // Use 'SymbolEqualityComparer' when comparing symbols (https://github.com/dotnet/roslyn/issues/78583) +#pragma warning disable CS0419 // Ambiguous reference in cref attribute using System; using System.Collections.Generic; @@ -12,7 +13,6 @@ using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ITypeSymbolExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ITypeSymbolExtensions.cs index 66f23193e84ea..5bfd70b0f1cd4 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ITypeSymbolExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/ITypeSymbolExtensions.cs @@ -40,20 +40,12 @@ public static bool CanAddNullCheck([NotNullWhen(returnValue: true)] this ITypeSy return isNullableValueType || isNonNullableReferenceType; } - public static IList GetAllInterfacesIncludingThis(this ITypeSymbol type) + public static ImmutableArray GetAllInterfacesIncludingThis(this ITypeSymbol type) { var allInterfaces = type.AllInterfaces; - if (type is INamedTypeSymbol namedType && namedType.TypeKind == TypeKind.Interface && !allInterfaces.Contains(namedType)) - { - var result = new List(allInterfaces.Length + 1) - { - namedType - }; - result.AddRange(allInterfaces); - return result; - } - - return allInterfaces; + return type is INamedTypeSymbol { TypeKind: TypeKind.Interface } namedType && !allInterfaces.Contains(namedType) + ? [namedType, .. allInterfaces] + : allInterfaces; } public static bool IsAbstractClass([NotNullWhen(returnValue: true)] this ITypeSymbol? symbol) @@ -749,7 +741,7 @@ public static bool IsSpanOrReadOnlySpan([NotNullWhen(true)] this ITypeSymbol? ty public static bool IsSpan([NotNullWhen(true)] this ITypeSymbol? type) => type is INamedTypeSymbol { - Name: nameof(Span), + Name: nameof(Span<>), TypeArguments.Length: 1, ContainingNamespace: { Name: nameof(System), ContainingNamespace.IsGlobalNamespace: true } }; @@ -757,7 +749,7 @@ public static bool IsSpan([NotNullWhen(true)] this ITypeSymbol? type) public static bool IsReadOnlySpan([NotNullWhen(true)] this ISymbol? symbol) => symbol is INamedTypeSymbol { - Name: nameof(ReadOnlySpan), + Name: nameof(ReadOnlySpan<>), TypeArguments.Length: 1, ContainingNamespace: { Name: nameof(System), ContainingNamespace.IsGlobalNamespace: true } }; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/SymbolEquivalenceComparer.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/SymbolEquivalenceComparer.cs index 91276b5f2f337..2f0ccbfdfc50d 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/SymbolEquivalenceComparer.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Extensions/Symbols/SymbolEquivalenceComparer.cs @@ -8,7 +8,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; -using Microsoft.CodeAnalysis.Shared.Collections; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; @@ -241,10 +241,18 @@ private static bool IsPartialPropertyImplementationPart(IPropertySymbol symbol) => symbol.PartialDefinitionPart != null; private static bool IsPartialEventDefinitionPart(IEventSymbol symbol) +#if !ROSLYN_4_12_OR_LOWER => symbol.PartialImplementationPart != null; +#else + => false; +#endif private static bool IsPartialEventImplementationPart(IEventSymbol symbol) +#if !ROSLYN_4_12_OR_LOWER => symbol.PartialDefinitionPart != null; +#else + => false; +#endif private static TypeKind GetTypeKind(INamedTypeSymbol x) => x.TypeKind switch diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Extensions/ParenthesizedExpressionSyntaxExtensions.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Extensions/ParenthesizedExpressionSyntaxExtensions.vb index da471f2baced0..aa7af3efb7949 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Extensions/ParenthesizedExpressionSyntaxExtensions.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Extensions/ParenthesizedExpressionSyntaxExtensions.vb @@ -346,6 +346,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions ' Cases: ' (1 + 1) * 8 ' (1 + 1).ToString + ' (1 + 1)?.ToString ' (1 + 1)() If TypeOf expression Is BinaryExpressionSyntax OrElse TypeOf expression Is UnaryExpressionSyntax Then @@ -353,6 +354,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions Dim parentExpression = TryCast(node.Parent, ExpressionSyntax) If parentExpression IsNot Nothing Then If parentExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) OrElse + parentExpression.IsKind(SyntaxKind.ConditionalAccessExpression) OrElse parentExpression.IsKind(SyntaxKind.InvocationExpression) Then Return False End If diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Extensions/SyntaxNodeExtensions.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Extensions/SyntaxNodeExtensions.vb index 0574feab90895..2247d9dcbbdf6 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Extensions/SyntaxNodeExtensions.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Extensions/SyntaxNodeExtensions.vb @@ -1040,9 +1040,6 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions Return TryCast(node, ConditionalAccessExpressionSyntax) End Function - ''' - ''' - ''' Friend Function GetRootConditionalAccessExpression(node As ExpressionSyntax) As ConditionalAccessExpressionSyntax ' Once we've walked up the entire RHS, now we continually walk up the conditional accesses until we're at @@ -1295,5 +1292,16 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions Return node End If End Function + + Friend Function GetAccessorList(declaration As SyntaxNode) As SyntaxList(Of AccessorBlockSyntax) + Select Case declaration.Kind + Case SyntaxKind.PropertyBlock + Return DirectCast(declaration, PropertyBlockSyntax).Accessors + Case SyntaxKind.EventBlock + Return DirectCast(declaration, EventBlockSyntax).Accessors + Case Else + Return Nothing + End Select + End Function End Module End Namespace diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/DefaultOperationProvider.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/DefaultOperationProvider.vb similarity index 100% rename from src/Workspaces/VisualBasic/Portable/Formatting/DefaultOperationProvider.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/DefaultOperationProvider.vb diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/AggregatedFormattingResult.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/AggregatedFormattingResult.vb similarity index 96% rename from src/Workspaces/VisualBasic/Portable/Formatting/Engine/AggregatedFormattingResult.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/AggregatedFormattingResult.vb index 18aeb9d68ef7e..049959a128c8c 100644 --- a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/AggregatedFormattingResult.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/AggregatedFormattingResult.vb @@ -5,7 +5,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Shared.Collections -Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting Friend Class AggregatedFormattingResult diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/FormattingResult.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/FormattingResult.vb similarity index 100% rename from src/Workspaces/VisualBasic/Portable/Formatting/Engine/FormattingResult.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/FormattingResult.vb diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.AbstractLineBreakTrivia.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/TriviaDataFactory.AbstractLineBreakTrivia.vb similarity index 98% rename from src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.AbstractLineBreakTrivia.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/TriviaDataFactory.AbstractLineBreakTrivia.vb index 7a86870f4d57d..44b002c10e48e 100644 --- a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.AbstractLineBreakTrivia.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/TriviaDataFactory.AbstractLineBreakTrivia.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.Collections -Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Text diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.Analyzer.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/TriviaDataFactory.Analyzer.vb similarity index 100% rename from src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.Analyzer.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/TriviaDataFactory.Analyzer.vb diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.CodeShapeAnalyzer.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/TriviaDataFactory.CodeShapeAnalyzer.vb similarity index 99% rename from src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.CodeShapeAnalyzer.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/TriviaDataFactory.CodeShapeAnalyzer.vb index 19694d2b63abb..7b41c6bfd62f3 100644 --- a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.CodeShapeAnalyzer.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/TriviaDataFactory.CodeShapeAnalyzer.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.ComplexTrivia.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/TriviaDataFactory.ComplexTrivia.vb similarity index 98% rename from src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.ComplexTrivia.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/TriviaDataFactory.ComplexTrivia.vb index 71c51db59f694..c11656e55941e 100644 --- a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.ComplexTrivia.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/TriviaDataFactory.ComplexTrivia.vb @@ -3,8 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Text diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.FormattedComplexTrivia.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/TriviaDataFactory.FormattedComplexTrivia.vb similarity index 100% rename from src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.FormattedComplexTrivia.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/TriviaDataFactory.FormattedComplexTrivia.vb diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.LineContinuationTrivia.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/TriviaDataFactory.LineContinuationTrivia.vb similarity index 96% rename from src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.LineContinuationTrivia.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/TriviaDataFactory.LineContinuationTrivia.vb index 52007299afb51..1cd35b96ffef1 100644 --- a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.LineContinuationTrivia.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/TriviaDataFactory.LineContinuationTrivia.vb @@ -3,8 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Formatting Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.ModifiedComplexTrivia.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/TriviaDataFactory.ModifiedComplexTrivia.vb similarity index 100% rename from src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.ModifiedComplexTrivia.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/TriviaDataFactory.ModifiedComplexTrivia.vb diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.TriviaRewriter.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/TriviaDataFactory.TriviaRewriter.vb similarity index 100% rename from src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.TriviaRewriter.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/TriviaDataFactory.TriviaRewriter.vb diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/TriviaDataFactory.vb similarity index 99% rename from src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/TriviaDataFactory.vb index 3475c8aad1dc2..022bbd240e391 100644 --- a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/TriviaDataFactory.vb @@ -3,8 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading -Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Formatting Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/VisualBasicTriviaFormatter.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/VisualBasicTriviaFormatter.vb similarity index 100% rename from src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/VisualBasicTriviaFormatter.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/Trivia/VisualBasicTriviaFormatter.vb diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/VisualBasicFormatEngine.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/VisualBasicFormatEngine.vb similarity index 100% rename from src/Workspaces/VisualBasic/Portable/Formatting/Engine/VisualBasicFormatEngine.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/VisualBasicFormatEngine.vb diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/VisualBasicStructuredTriviaFormatEngine.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/VisualBasicStructuredTriviaFormatEngine.vb similarity index 98% rename from src/Workspaces/VisualBasic/Portable/Formatting/Engine/VisualBasicStructuredTriviaFormatEngine.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/VisualBasicStructuredTriviaFormatEngine.vb index e683b19beacec..cf17f5629f2e8 100644 --- a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/VisualBasicStructuredTriviaFormatEngine.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Engine/VisualBasicStructuredTriviaFormatEngine.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading -Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.VisualBasic.LanguageService diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/FormattingHelpers.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/FormattingHelpers.vb similarity index 100% rename from src/Workspaces/VisualBasic/Portable/Formatting/FormattingHelpers.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/FormattingHelpers.vb diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Rules/AdjustSpaceFormattingRule.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Rules/AdjustSpaceFormattingRule.vb similarity index 100% rename from src/Workspaces/VisualBasic/Portable/Formatting/Rules/AdjustSpaceFormattingRule.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Rules/AdjustSpaceFormattingRule.vb diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Rules/AlignTokensFormattingRule.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Rules/AlignTokensFormattingRule.vb similarity index 100% rename from src/Workspaces/VisualBasic/Portable/Formatting/Rules/AlignTokensFormattingRule.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Rules/AlignTokensFormattingRule.vb diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Rules/BaseFormattingRule.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Rules/BaseFormattingRule.vb similarity index 100% rename from src/Workspaces/VisualBasic/Portable/Formatting/Rules/BaseFormattingRule.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Rules/BaseFormattingRule.vb diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Rules/ElasticTriviaFormattingRule.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Rules/ElasticTriviaFormattingRule.vb similarity index 100% rename from src/Workspaces/VisualBasic/Portable/Formatting/Rules/ElasticTriviaFormattingRule.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Rules/ElasticTriviaFormattingRule.vb diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Rules/NodeBasedFormattingRule.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Rules/NodeBasedFormattingRule.vb similarity index 100% rename from src/Workspaces/VisualBasic/Portable/Formatting/Rules/NodeBasedFormattingRule.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Rules/NodeBasedFormattingRule.vb diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Rules/StructuredTriviaFormattingRule.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Rules/StructuredTriviaFormattingRule.vb similarity index 100% rename from src/Workspaces/VisualBasic/Portable/Formatting/Rules/StructuredTriviaFormattingRule.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/Rules/StructuredTriviaFormattingRule.vb diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/VisualBasicSyntaxFormatting.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/VisualBasicSyntaxFormatting.vb similarity index 96% rename from src/Workspaces/VisualBasic/Portable/Formatting/VisualBasicSyntaxFormatting.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/VisualBasicSyntaxFormatting.vb index b18158661bcd0..9818661a06b80 100644 --- a/src/Workspaces/VisualBasic/Portable/Formatting/VisualBasicSyntaxFormatting.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Formatting/VisualBasicSyntaxFormatting.vb @@ -4,12 +4,10 @@ Imports System.Collections.Immutable Imports System.Threading -Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Shared.Collections -Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting Friend Class VisualBasicSyntaxFormatting diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Helpers/RemoveUnnecessaryImports/VisualBasicRemoveUnnecessaryImportsRewriter.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Helpers/RemoveUnnecessaryImports/VisualBasicRemoveUnnecessaryImportsRewriter.vb index 1ed6d9ec39234..dafe21b40cf77 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Helpers/RemoveUnnecessaryImports/VisualBasicRemoveUnnecessaryImportsRewriter.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Helpers/RemoveUnnecessaryImports/VisualBasicRemoveUnnecessaryImportsRewriter.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.Shared.Helpers.RemoveUnnecessaryImports Imports Microsoft.CodeAnalysis.VisualBasic.LanguageService Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Helpers/RemoveUnnecessaryImports/VisualBasicUnnecessaryImportsProvider.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Helpers/RemoveUnnecessaryImports/VisualBasicUnnecessaryImportsProvider.vb index a52b4433ed953..33dac229647c6 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Helpers/RemoveUnnecessaryImports/VisualBasicUnnecessaryImportsProvider.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Helpers/RemoveUnnecessaryImports/VisualBasicUnnecessaryImportsProvider.vb @@ -4,7 +4,6 @@ Imports System.Collections.Immutable Imports System.Threading -Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.RemoveUnnecessaryImports Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/RoslynAnalyzers/Utilities/Refactoring.VisualBasic/VisualBasicRefactoringHelpers.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/RefactoringHelpers/VisualBasicRefactoringHelpers.vb similarity index 51% rename from src/RoslynAnalyzers/Utilities/Refactoring.VisualBasic/VisualBasicRefactoringHelpers.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/RefactoringHelpers/VisualBasicRefactoringHelpers.vb index 91f2e11240276..db77a9665a326 100644 --- a/src/RoslynAnalyzers/Utilities/Refactoring.VisualBasic/VisualBasicRefactoringHelpers.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/RefactoringHelpers/VisualBasicRefactoringHelpers.vb @@ -2,24 +2,66 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.CodeRefactorings +Imports Microsoft.CodeAnalysis.LanguageService +Imports Microsoft.CodeAnalysis.Text +Imports Microsoft.CodeAnalysis.VisualBasic.LanguageService Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -Namespace Global.Analyzer.Utilities - +Namespace Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings Friend NotInheritable Class VisualBasicRefactoringHelpers Inherits AbstractRefactoringHelpers(Of ExpressionSyntax, ArgumentSyntax, ExpressionStatementSyntax) - Public Shared ReadOnly Property Instance As New VisualBasicRefactoringHelpers() + Public Shared ReadOnly Instance As New VisualBasicRefactoringHelpers() Private Sub New() End Sub - Protected Overrides ReadOnly Property SyntaxFacts As ISyntaxFacts - Get - Return VisualBasicSyntaxFacts.Instance - End Get - End Property + Protected Overrides ReadOnly Property HeaderFacts As IHeaderFacts = VisualBasicHeaderFacts.Instance + Protected Overrides ReadOnly Property SyntaxFacts As ISyntaxFacts = VisualBasicSyntaxFacts.Instance + + Public Overrides Function IsBetweenTypeMembers(sourceText As SourceText, root As SyntaxNode, position As Integer, ByRef typeDeclaration As SyntaxNode) As Boolean + Dim token = root.FindToken(position) + Dim typeDecl = token.GetAncestor(Of TypeBlockSyntax) + typeDeclaration = typeDecl + + If typeDecl IsNot Nothing Then + Dim start = If(typeDecl.Implements.LastOrDefault()?.Span.End, + If(typeDecl.Inherits.LastOrDefault()?.Span.End, + typeDecl.BlockStatement.Span.End)) + + If position >= start AndAlso + position <= typeDecl.EndBlockStatement.Span.Start Then + + Dim line = sourceText.Lines.GetLineFromPosition(position) + If Not line.IsEmptyOrWhitespace() Then + Return False + End If + + Dim member = typeDecl.Members.FirstOrDefault(Function(d) d.FullSpan.Contains(position)) + If member Is Nothing Then + ' There are no members, Or we're after the last member. + Return True + Else + ' We're within a member. Make sure we're in the leading whitespace of + ' the member. + If position < member.SpanStart Then + For Each trivia In member.GetLeadingTrivia() + If Not trivia.IsWhitespaceOrEndOfLine() Then + Return False + End If + + If trivia.FullSpan.Contains(position) Then + Return True + End If + Next + End If + End If + End If + End If + + Return False + End Function Protected Overrides Iterator Function ExtractNodesSimple(node As SyntaxNode, syntaxFacts As ISyntaxFacts) As IEnumerable(Of SyntaxNode) For Each baseExtraction In MyBase.ExtractNodesSimple(node, syntaxFacts) @@ -57,10 +99,8 @@ Namespace Global.Analyzer.Utilities End Function - Private Shared Function IsIdentifierOfParameter(node As SyntaxNode) As Boolean + Public Shared Function IsIdentifierOfParameter(node As SyntaxNode) As Boolean Return (TypeOf node Is ModifiedIdentifierSyntax) AndAlso (TypeOf node.Parent Is ParameterSyntax) AndAlso (CType(node.Parent, ParameterSyntax).Identifier Is node) End Function - End Class - End Namespace diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SemanticFacts/VisualBasicSemanticFacts.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SemanticFacts/VisualBasicSemanticFacts.vb index 1db91249f50e2..cbf06956d9bd7 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SemanticFacts/VisualBasicSemanticFacts.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SemanticFacts/VisualBasicSemanticFacts.vb @@ -307,7 +307,11 @@ Namespace Microsoft.CodeAnalysis.VisualBasic End Function Private Shared Function CreatePreprocessingSymbol(model As SemanticModel, token As SyntaxToken) As IPreprocessingSymbol +#If Not ROSLYN_4_12_OR_LOWER Then Return model.Compilation.CreatePreprocessingSymbol(token.ValueText) +#Else + return nothing +#End If End Function Friend Shared Function IsWithinPreprocessorConditionalExpression(node As IdentifierNameSyntax) As Boolean @@ -335,7 +339,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic Return False End Function -#If Not CODE_STYLE Then +#If VISUAL_BASIC_WORKSPACE Then Public Function GetInterceptorSymbolAsync(document As Document, position As Integer, cancellationToken As CancellationToken) As Task(Of ISymbol) Implements ISemanticFacts.GetInterceptorSymbolAsync ' VB does not support interceptors diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicAccessibilityFacts.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicAccessibilityFacts.vb index f94864032defc..775da2c8954da 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicAccessibilityFacts.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicAccessibilityFacts.vb @@ -2,15 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -#If CODE_STYLE Then -Imports Microsoft.CodeAnalysis.Internal.Editing -#Else -Imports Microsoft.CodeAnalysis.Editing -#End If - Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageService Friend Class VisualBasicAccessibilityFacts Implements IAccessibilityFacts @@ -94,7 +89,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageService Dim tokens = GetModifierTokens(declaration) Dim acc As Accessibility - Dim mods As DeclarationModifiers + Dim mods As Modifiers Dim isDefault As Boolean GetAccessibilityAndModifiers(tokens, acc, mods, isDefault) Return acc @@ -182,9 +177,9 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageService End Select End Function - Public Shared Sub GetAccessibilityAndModifiers(modifierTokens As SyntaxTokenList, ByRef accessibility As Accessibility, ByRef modifiers As DeclarationModifiers, ByRef isDefault As Boolean) + Public Shared Sub GetAccessibilityAndModifiers(modifierTokens As SyntaxTokenList, ByRef accessibility As Accessibility, ByRef modifiers As Modifiers, ByRef isDefault As Boolean) accessibility = Accessibility.NotApplicable - modifiers = DeclarationModifiers.None + modifiers = Modifiers.None isDefault = False For Each token In modifierTokens @@ -214,29 +209,29 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageService accessibility = Accessibility.Protected End If Case SyntaxKind.MustInheritKeyword, SyntaxKind.MustOverrideKeyword - modifiers = modifiers Or DeclarationModifiers.Abstract + modifiers = modifiers Or Modifiers.Abstract Case SyntaxKind.ShadowsKeyword - modifiers = modifiers Or DeclarationModifiers.[New] + modifiers = modifiers Or Modifiers.[New] Case SyntaxKind.OverridesKeyword - modifiers = modifiers Or DeclarationModifiers.Override + modifiers = modifiers Or Modifiers.Override Case SyntaxKind.OverridableKeyword - modifiers = modifiers Or DeclarationModifiers.Virtual + modifiers = modifiers Or Modifiers.Virtual Case SyntaxKind.SharedKeyword - modifiers = modifiers Or DeclarationModifiers.Static + modifiers = modifiers Or Modifiers.Static Case SyntaxKind.AsyncKeyword - modifiers = modifiers Or DeclarationModifiers.Async + modifiers = modifiers Or Modifiers.Async Case SyntaxKind.ConstKeyword - modifiers = modifiers Or DeclarationModifiers.Const + modifiers = modifiers Or Modifiers.Const Case SyntaxKind.ReadOnlyKeyword - modifiers = modifiers Or DeclarationModifiers.ReadOnly + modifiers = modifiers Or Modifiers.ReadOnly Case SyntaxKind.WriteOnlyKeyword - modifiers = modifiers Or DeclarationModifiers.WriteOnly + modifiers = modifiers Or Modifiers.WriteOnly Case SyntaxKind.NotInheritableKeyword, SyntaxKind.NotOverridableKeyword - modifiers = modifiers Or DeclarationModifiers.Sealed + modifiers = modifiers Or Modifiers.Sealed Case SyntaxKind.WithEventsKeyword - modifiers = modifiers Or DeclarationModifiers.WithEvents + modifiers = modifiers Or Modifiers.WithEvents Case SyntaxKind.PartialKeyword - modifiers = modifiers Or DeclarationModifiers.Partial + modifiers = modifiers Or Modifiers.Partial End Select Next End Sub diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxFacts.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxFacts.vb index adb019471d925..05044d486c833 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxFacts.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxFacts.vb @@ -3,23 +3,16 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable +Imports System.Diagnostics.CodeAnalysis Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts -Imports System.Diagnostics.CodeAnalysis - -#If CODE_STYLE Then -Imports Microsoft.CodeAnalysis.Internal.Editing -Imports Microsoft.CodeAnalysis.Collections -#Else -Imports Microsoft.CodeAnalysis.Editing -Imports Microsoft.CodeAnalysis.Collections -#End If Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageService Friend Class VisualBasicSyntaxFacts diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxKinds.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxKinds.vb index 0641f531b5c81..104f2d01b47a5 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxKinds.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxKinds.vb @@ -120,11 +120,13 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageService Public ReadOnly Property ReferenceNotEqualsExpression As Integer = SyntaxKind.IsNotExpression Implements ISyntaxKinds.ReferenceNotEqualsExpression Public ReadOnly Property SimpleAssignmentExpression As Integer = SyntaxKind.SimpleAssignmentStatement Implements ISyntaxKinds.SimpleAssignmentExpression Public ReadOnly Property SimpleMemberAccessExpression As Integer = SyntaxKind.SimpleMemberAccessExpression Implements ISyntaxKinds.SimpleMemberAccessExpression + Public ReadOnly Property SizeOfExpression As Integer? Implements ISyntaxKinds.SizeOfExpression Public ReadOnly Property SuppressNullableWarningExpression As Integer? Implements ISyntaxKinds.SuppressNullableWarningExpression Public ReadOnly Property TernaryConditionalExpression As Integer = SyntaxKind.TernaryConditionalExpression Implements ISyntaxKinds.TernaryConditionalExpression Public ReadOnly Property ThisExpression As Integer = SyntaxKind.MeExpression Implements ISyntaxKinds.ThisExpression Public ReadOnly Property ThrowExpression As Integer? Implements ISyntaxKinds.ThrowExpression Public ReadOnly Property TupleExpression As Integer = SyntaxKind.TupleExpression Implements ISyntaxKinds.TupleExpression + Public ReadOnly Property TypeOfExpression As Integer = SyntaxKind.GetTypeExpression Implements ISyntaxKinds.TypeOfExpression Public ReadOnly Property AndPattern As Integer? Implements ISyntaxKinds.AndPattern Public ReadOnly Property ConstantPattern As Integer? Implements ISyntaxKinds.ConstantPattern diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Simplification/VisualBasicSimplification.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Simplification/VisualBasicSimplification.vb index e82f2b4561f7e..49740f29e564f 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Simplification/VisualBasicSimplification.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Simplification/VisualBasicSimplification.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Simplification diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/VisualBasicCompilerExtensions.projitems b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/VisualBasicCompilerExtensions.projitems index b927e9d48a300..97df05dc81bd9 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/VisualBasicCompilerExtensions.projitems +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/VisualBasicCompilerExtensions.projitems @@ -26,10 +26,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + @@ -60,4 +84,7 @@ + + + \ No newline at end of file diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CSharpWorkspaceExtensions.projitems b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CSharpWorkspaceExtensions.projitems index 2db3182cbc458..60ac10a5da8bc 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CSharpWorkspaceExtensions.projitems +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CSharpWorkspaceExtensions.projitems @@ -86,6 +86,7 @@ + diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/CSharpCodeGenerationHelpers.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/CSharpCodeGenerationHelpers.cs index 75d972a22f057..12421618da5cf 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/CSharpCodeGenerationHelpers.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/CSharpCodeGenerationHelpers.cs @@ -172,14 +172,15 @@ public static SyntaxList Insert( CSharpCodeGenerationContextInfo info, IList? availableIndices, Func, TDeclaration?>? after = null, - Func, TDeclaration?>? before = null) + Func, TDeclaration?>? before = null, + Func, int, bool>? canPlaceAtIndex = null) where TDeclaration : SyntaxNode { var index = GetInsertionIndex( declarationList, declaration, info, availableIndices, CSharpDeclarationComparer.WithoutNamesInstance, CSharpDeclarationComparer.WithNamesInstance, - after, before); + after, before, canPlaceAtIndex); availableIndices?.Insert(index, true); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/CSharpCodeGenerationService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/CSharpCodeGenerationService.cs index 2a2dace9c17a9..7334ce1a85a21 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/CSharpCodeGenerationService.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/CSharpCodeGenerationService.cs @@ -454,13 +454,13 @@ private static SyntaxList RemoveAttributeFromAttributeLists if (attributes.Count == 1) { // Remove the entire attribute list. - ComputePositionAndTriviaForRemoveAttributeList(attributeList, (SyntaxTrivia t) => t.IsKind(SyntaxKind.EndOfLineTrivia), out positionOfRemovedNode, out trivia); + ComputePositionAndTriviaForRemoveAttributeList(attributeList, t => t.IsKind(SyntaxKind.EndOfLineTrivia), out positionOfRemovedNode, out trivia); newAttributeLists = attributeLists.Where(aList => aList != attributeList); } else { // Remove just the given attribute from the attribute list. - ComputePositionAndTriviaForRemoveAttributeFromAttributeList(attributeToRemove, (SyntaxToken t) => t.IsKind(SyntaxKind.CommaToken), out positionOfRemovedNode, out trivia); + ComputePositionAndTriviaForRemoveAttributeFromAttributeList(attributeToRemove, t => t.IsKind(SyntaxKind.CommaToken), out positionOfRemovedNode, out trivia); var newAttributes = SeparatedList(attributes.Where(a => a != attributeToRemove)); var newAttributeList = attributeList.WithAttributes(newAttributes); newAttributeLists = attributeLists.Select(attrList => attrList == attributeList ? newAttributeList : attrList); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/ConversionGenerator.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/ConversionGenerator.cs index e40946c3756a7..362f2becc54af 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/ConversionGenerator.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/ConversionGenerator.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.CodeGeneration; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/NamedTypeGenerator.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/NamedTypeGenerator.cs index 31c4d36df8885..a97d4b64fd1aa 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/NamedTypeGenerator.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/NamedTypeGenerator.cs @@ -59,7 +59,11 @@ public static CompilationUnitSyntax AddNamedTypeTo( CancellationToken cancellationToken) { var declaration = GenerateNamedTypeDeclaration(service, namedType, CodeGenerationDestination.CompilationUnit, info, cancellationToken); - var members = Insert(destination.Members, declaration, info, availableIndices); + var members = Insert( + destination.Members, declaration, info, availableIndices, + // We're adding a named type to a compilation unit. If there are any global statements, we must place it after them. + after: static members => members.LastOrDefault(m => m is GlobalStatementSyntax), + canPlaceAtIndex: static (members, index) => index >= members.Count || members[index] is not GlobalStatementSyntax); return destination.WithMembers(members); } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/OperatorGenerator.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/OperatorGenerator.cs index 66f7fa65c6632..10337796ebaa3 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/OperatorGenerator.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/OperatorGenerator.cs @@ -10,7 +10,6 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Shared.Collections; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeRefactorings/CSharpRefactoringHelpersService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeRefactorings/CSharpRefactoringHelpersService.cs index d6f17829e39d6..ee2123b3ea092 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeRefactorings/CSharpRefactoringHelpersService.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeRefactorings/CSharpRefactoringHelpersService.cs @@ -3,19 +3,10 @@ // See the LICENSE file in the project root for more information. using System; -using System.Collections.Generic; using System.Composition; -using System.Diagnostics.CodeAnalysis; -using System.Linq; using Microsoft.CodeAnalysis.CodeRefactorings; -using Microsoft.CodeAnalysis.CSharp.Extensions; -using Microsoft.CodeAnalysis.CSharp.LanguageService; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; -using Microsoft.CodeAnalysis.LanguageService; -using Microsoft.CodeAnalysis.Shared.Extensions; -using Microsoft.CodeAnalysis.Text; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings; @@ -24,89 +15,5 @@ namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings; [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] internal sealed class CSharpRefactoringHelpersService() : AbstractRefactoringHelpersService { - protected override IHeaderFacts HeaderFacts => CSharpHeaderFacts.Instance; - - public override bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration) - { - var token = root.FindToken(position); - var typeDecl = token.GetAncestor(); - typeDeclaration = typeDecl; - - if (typeDecl == null) - return false; - - RoslynDebug.AssertNotNull(typeDeclaration); - if (position < typeDecl.OpenBraceToken.Span.End || - position > typeDecl.CloseBraceToken.Span.Start) - { - return false; - } - - var line = sourceText.Lines.GetLineFromPosition(position); - if (!line.IsEmptyOrWhitespace()) - return false; - - var member = typeDecl.Members.FirstOrDefault(d => d.FullSpan.Contains(position)); - if (member == null) - { - // There are no members, or we're after the last member. - return true; - } - else - { - // We're within a member. Make sure we're in the leading whitespace of - // the member. - if (position < member.SpanStart) - { - foreach (var trivia in member.GetLeadingTrivia()) - { - if (!trivia.IsWhitespaceOrEndOfLine()) - return false; - - if (trivia.FullSpan.Contains(position)) - return true; - } - } - } - - return false; - } - - protected override IEnumerable ExtractNodesSimple(SyntaxNode? node, ISyntaxFactsService syntaxFacts) - { - if (node == null) - { - yield break; - } - - foreach (var extractedNode in base.ExtractNodesSimple(node, syntaxFacts)) - { - yield return extractedNode; - } - - // `var a = b;` - // -> `var a = b`; - if (node is LocalDeclarationStatementSyntax localDeclaration) - { - yield return localDeclaration.Declaration; - } - - // var `a = b`; - if (node is VariableDeclaratorSyntax declarator) - { - var declaration = declarator.Parent; - if (declaration?.Parent is LocalDeclarationStatementSyntax localDeclarationStatement) - { - var variables = syntaxFacts.GetVariablesOfLocalDeclarationStatement(localDeclarationStatement); - if (variables.Count == 1) - { - // -> `var a = b`; - yield return declaration; - - // -> `var a = b;` - yield return localDeclarationStatement; - } - } - } - } + protected override IRefactoringHelpers RefactoringHelpers { get; } = CSharpRefactoringHelpers.Instance; } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/CompilationUnitSyntaxExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/CompilationUnitSyntaxExtensions.cs index 19ef52954751c..38bb144fc7df3 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/CompilationUnitSyntaxExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/CompilationUnitSyntaxExtensions.cs @@ -55,8 +55,8 @@ private static TextSpan GetUsingsSpan(CompilationUnitSyntax root, BaseNamespaceD else { var start = 0; - var end = root.Members.Any() - ? root.Members.First().GetFirstToken().Span.End + var end = root.Members is [var firstMember, ..] + ? firstMember.GetFirstToken().Span.End : root.Span.End; return TextSpan.FromBounds(start, end); } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/InternalExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/InternalExtensions.cs index 8f7a5c42e8f7a..5e8e3e0d8a118 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/InternalExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/InternalExtensions.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; -using System.Threading; namespace Microsoft.CodeAnalysis.CSharp; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/TypeDeclarationSyntaxExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/TypeDeclarationSyntaxExtensions.cs index a182161fcd7c0..aeb4af55c77d1 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/TypeDeclarationSyntaxExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/TypeDeclarationSyntaxExtensions.cs @@ -22,7 +22,7 @@ public static IList GetInsertionIndices(this TypeDeclarationSyntax destina var members = destination.Members; var indices = new List(); - if (members.Count == 0) + if (members is not [var firstMember, ..]) { var start = destination.OpenBraceToken.Span.End; var end = GetEndToken(destination).SpanStart; @@ -32,7 +32,7 @@ public static IList GetInsertionIndices(this TypeDeclarationSyntax destina else { var start = destination.OpenBraceToken.Span.End; - var end = destination.Members.First().SpanStart; + var end = firstMember.SpanStart; indices.Add(!destination.OverlapsHiddenPosition(TextSpan.FromBounds(start, end), cancellationToken)); for (var i = 0; i < members.Count - 1; i++) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Indentation/CSharpIndentationService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Indentation/CSharpIndentationService.cs index d6c46dcb91dc6..67edc4d42e236 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Indentation/CSharpIndentationService.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Indentation/CSharpIndentationService.cs @@ -171,13 +171,11 @@ private static bool IsBracketedArgumentListMissingBrackets(BracketedArgumentList private static void ReplaceCaseIndentationRules(List list, SyntaxNode node) { - if (node is not SwitchSectionSyntax section || section.Statements.Count == 0) - { + if (node is not SwitchSectionSyntax { Statements: [var firstStatement, ..] and [.., var lastStatement] }) return; - } - var startToken = section.Statements.First().GetFirstToken(includeZeroWidth: true); - var endToken = section.Statements.Last().GetLastToken(includeZeroWidth: true); + var startToken = firstStatement.GetFirstToken(includeZeroWidth: true); + var endToken = lastStatement.GetLastToken(includeZeroWidth: true); for (var i = 0; i < list.Count; i++) { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpRemoveUnnecessaryImportsService.Rewriter.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpRemoveUnnecessaryImportsService.Rewriter.cs index 3fe15eb795dba..ae41f6216372a 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpRemoveUnnecessaryImportsService.Rewriter.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpRemoveUnnecessaryImportsService.Rewriter.cs @@ -231,11 +231,11 @@ private SyntaxNode VisitBaseNamespaceDeclaration( var resultNamespace = namespaceDeclaration.WithUsings(finalUsings); if (finalUsings.Count == 0 && resultNamespace.Externs.Count == 0 && - resultNamespace.Members.Count >= 1) + resultNamespace.Members is [var firstMember, ..]) { // We've removed all the usings and now the first thing in the namespace is a // type. In this case, remove any newlines preceding the type. - var firstToken = resultNamespace.Members.First().GetFirstToken(); + var firstToken = firstMember.GetFirstToken(); var newFirstToken = RemoveUnnecessaryImportsHelpers.StripNewLines(CSharpSyntaxFacts.Instance, firstToken); resultNamespace = resultNamespace.ReplaceToken(firstToken, newFirstToken); } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpSyntaxKindsServiceFactory.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpSyntaxKindsServiceFactory.cs index cf92eadfea7de..335b9f5621eb2 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpSyntaxKindsServiceFactory.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpSyntaxKindsServiceFactory.cs @@ -11,14 +11,10 @@ namespace Microsoft.CodeAnalysis.CSharp.LanguageService; [ExportLanguageServiceFactory(typeof(ISyntaxKindsService), LanguageNames.CSharp), Shared] -internal sealed class CSharpSyntaxKindsServiceFactory : ILanguageServiceFactory +[method: ImportingConstructor] +[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] +internal sealed class CSharpSyntaxKindsServiceFactory() : ILanguageServiceFactory { - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public CSharpSyntaxKindsServiceFactory() - { - } - public ILanguageService CreateLanguageService(HostLanguageServices languageServices) => CSharpSyntaxKindsService.Instance; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpTypeInferenceService.TypeInferrer.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpTypeInferenceService.TypeInferrer.cs index 85325ad9d36d0..18958cbf5669e 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpTypeInferenceService.TypeInferrer.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpTypeInferenceService.TypeInferrer.cs @@ -10,6 +10,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageService; @@ -1723,13 +1724,13 @@ private IEnumerable InferTypeForExpressionOfMemberAccessExpre // then we can figure out what 'goo' should be based on teh await // context. var name = memberAccessExpression.Name.Identifier.Value; - if (name.Equals(nameof(Task.ConfigureAwait)) && + if (name.Equals(nameof(Task<>.ConfigureAwait)) && memberAccessExpression?.Parent is InvocationExpressionSyntax invocation && memberAccessExpression.Parent.IsParentKind(SyntaxKind.AwaitExpression)) { return InferTypes(invocation); } - else if (name.Equals(nameof(Task.ContinueWith))) + else if (name.Equals(nameof(Task<>.ContinueWith))) { // goo.ContinueWith(...) // We want to infer Task. For now, we'll just do Task, diff --git a/src/Workspaces/CSharp/Portable/SemanticModelReuse/CSharpSemanticModelReuseLanguageService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/SemanticModelReuse/CSharpSemanticModelReuseLanguageService.cs similarity index 100% rename from src/Workspaces/CSharp/Portable/SemanticModelReuse/CSharpSemanticModelReuseLanguageService.cs rename to src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/SemanticModelReuse/CSharpSemanticModelReuseLanguageService.cs diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Utilities/SyntaxKindSet.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Utilities/SyntaxKindSet.cs index 95132cee10230..c1e0a0be0d0ec 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Utilities/SyntaxKindSet.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Utilities/SyntaxKindSet.cs @@ -88,7 +88,9 @@ internal sealed class SyntaxKindSet public static readonly ISet NonEnumTypeDeclarations = new HashSet(SyntaxFacts.EqualityComparer) { SyntaxKind.ClassDeclaration, +#if !ROSLYN_4_12_OR_LOWER SyntaxKind.ExtensionBlockDeclaration, +#endif SyntaxKind.InterfaceDeclaration, SyntaxKind.RecordDeclaration, SyntaxKind.RecordStructDeclaration, diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/AddImport/AddImportPlacementOptionsProviders.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/AddImport/AddImportPlacementOptionsProviders.cs index 4b2884d241e92..e64cf3f5eca9d 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/AddImport/AddImportPlacementOptionsProviders.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/AddImport/AddImportPlacementOptionsProviders.cs @@ -15,7 +15,7 @@ internal static class AddImportPlacementOptionsProviders // modern span mapper at our disposal, we do allow it as that host span mapper can handle mapping // our edit to their domain appropriate. public static bool AllowImportsInHiddenRegions(this Document document) -#if CODE_STYLE +#if !WORKSPACE => AddImportPlacementOptions.Default.AllowInHiddenRegions; #else => document.DocumentServiceProvider.GetService()?.SupportsMappingImportDirectives == true; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/SyntaxEditorBasedCodeFixProvider.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/SyntaxEditorBasedCodeFixProvider.cs index 5d96c89405d29..5314240865867 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/SyntaxEditorBasedCodeFixProvider.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/SyntaxEditorBasedCodeFixProvider.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Immutable; +using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; @@ -20,6 +21,10 @@ internal abstract partial class SyntaxEditorBasedCodeFixProvider(bool supportsFi private readonly bool _supportsFixAll = supportsFixAll; +#if WORKSPACE + protected virtual CodeActionCleanup Cleanup => CodeActionCleanup.Default; +#endif + public sealed override FixAllProvider? GetFixAllProvider() { if (!_supportsFixAll) @@ -42,7 +47,11 @@ internal abstract partial class SyntaxEditorBasedCodeFixProvider(bool supportsFi return await FixAllAsync(document, filteredDiagnostics, fixAllContext.CancellationToken).ConfigureAwait(false); }, - s_defaultSupportedFixAllScopes); + s_defaultSupportedFixAllScopes +#if WORKSPACE + , this.Cleanup +#endif + ); } protected void RegisterCodeFix(CodeFixContext context, string title, string equivalenceKey, Diagnostic? diagnostic = null) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/AbstractCodeGenerationService_FindDeclaration.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/AbstractCodeGenerationService_FindDeclaration.cs index 87fff6b2c2f82..ae0d5d0109fd3 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/AbstractCodeGenerationService_FindDeclaration.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/AbstractCodeGenerationService_FindDeclaration.cs @@ -82,7 +82,7 @@ private bool CanAddTo( return false; } -#if !CODE_STYLE +#if WORKSPACE // If we are avoiding generating into files marked as generated (but are still regular files) // then check accordingly. This is distinct from the prior check in that we as a fallback // will generate into these files is we have no alternative. diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/CodeGenerationHelpers.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/CodeGenerationHelpers.cs index 476a0c1001178..1e653b7a55cab 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/CodeGenerationHelpers.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/CodeGenerationHelpers.cs @@ -193,11 +193,14 @@ public static int GetInsertionIndex( IComparer comparerWithoutNameCheck, IComparer comparerWithNameCheck, Func, TDeclaration?>? after = null, - Func, TDeclaration?>? before = null) + Func, TDeclaration?>? before = null, + Func, int, bool>? canPlaceAtIndex = null) where TDeclaration : SyntaxNode { Contract.ThrowIfTrue(availableIndices != null && availableIndices.Count != declarationList.Count + 1); + canPlaceAtIndex ??= static (_, _) => true; + // Try to strictly obey the after option by inserting immediately after the member containing the location if (info.Context.AfterThisLocation?.SourceTree is { } afterSourceTree && afterSourceTree.FilePath == declarationList.FirstOrDefault()?.SyntaxTree.FilePath) @@ -207,10 +210,8 @@ public static int GetInsertionIndex( { var index = declarationList.IndexOf(afterMember); index = GetPreferredIndex(index + 1, availableIndices, forward: true); - if (index != -1) - { + if (index != -1 && canPlaceAtIndex(declarationList, index)) return index; - } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/CodeGenerationSymbolFactory.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/CodeGenerationSymbolFactory.cs index 87d8dd398a3eb..0ff5137322795 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/CodeGenerationSymbolFactory.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/CodeGenerationSymbolFactory.cs @@ -6,13 +6,8 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; -using Microsoft.CodeAnalysis.Shared.Extensions; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Editing; -#else using Microsoft.CodeAnalysis.Editing; -#endif +using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CodeGeneration; @@ -392,7 +387,7 @@ public static IMethodSymbol CreateAccessorSymbol( return CreateMethodSymbol( attributes, accessibility, - new DeclarationModifiers(isAbstract: statements == null), + DeclarationModifiers.None.WithIsAbstract(statements == null), returnType: null, refKind: RefKind.None, explicitInterfaceImplementations: default, @@ -475,7 +470,7 @@ public static CodeGenerationNamedTypeSymbol CreateDelegateTypeSymbol( var invokeMethod = CreateMethodSymbol( attributes: default, accessibility: Accessibility.Public, - modifiers: new DeclarationModifiers(), + modifiers: DeclarationModifiers.None, returnType: returnType, refKind: refKind, explicitInterfaceImplementations: default, diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationAbstractMethodSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationAbstractMethodSymbol.cs index a8617012efe32..57c8c7b7210fc 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationAbstractMethodSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationAbstractMethodSymbol.cs @@ -6,12 +6,7 @@ using System.Collections.Immutable; using System.Reflection.Metadata; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Editing; -#else using Microsoft.CodeAnalysis.Editing; -#endif namespace Microsoft.CodeAnalysis.CodeGeneration; @@ -104,7 +99,9 @@ public virtual ImmutableArray ReturnTypeCustomModifiers public bool IsConditional => false; +#if !ROSLYN_4_12_OR_LOWER public bool IsIterator => false; +#endif public SignatureCallingConvention CallingConvention => SignatureCallingConvention.Default; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationAbstractNamedTypeSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationAbstractNamedTypeSymbol.cs index 445328ff50423..e695ebff662a4 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationAbstractNamedTypeSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationAbstractNamedTypeSymbol.cs @@ -7,12 +7,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Editing; -#else using Microsoft.CodeAnalysis.Editing; -#endif namespace Microsoft.CodeAnalysis.CodeGeneration; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationConstructorSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationConstructorSymbol.cs index 3d4c238631dd2..ea91a926966f6 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationConstructorSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationConstructorSymbol.cs @@ -3,12 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Editing; -#else using Microsoft.CodeAnalysis.Editing; -#endif namespace Microsoft.CodeAnalysis.CodeGeneration; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationConversionSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationConversionSymbol.cs index f063c96b3f67a..d88fabd96fa10 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationConversionSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationConversionSymbol.cs @@ -3,12 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Editing; -#else using Microsoft.CodeAnalysis.Editing; -#endif namespace Microsoft.CodeAnalysis.CodeGeneration; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationEventSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationEventSymbol.cs index 2c05b57bbc671..bb9b4f82e8da0 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationEventSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationEventSymbol.cs @@ -4,11 +4,7 @@ using System.Collections.Immutable; -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Editing; -#else using Microsoft.CodeAnalysis.Editing; -#endif namespace Microsoft.CodeAnalysis.CodeGeneration; @@ -59,11 +55,13 @@ public override TResult Accept(SymbolVisitor null; +#if !ROSLYN_4_12_OR_LOWER public IEventSymbol? PartialImplementationPart => null; public IEventSymbol? PartialDefinitionPart => null; public bool IsPartialDefinition => false; +#endif public static ImmutableArray TypeCustomModifiers => []; } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationFieldSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationFieldSymbol.cs index c888a0582895d..a00ec303fdff6 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationFieldSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationFieldSymbol.cs @@ -5,12 +5,7 @@ #nullable disable using System.Collections.Immutable; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Editing; -#else using Microsoft.CodeAnalysis.Editing; -#endif namespace Microsoft.CodeAnalysis.CodeGeneration; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationMethodSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationMethodSymbol.cs index 4ec90fc9612cc..6791fe51e6f70 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationMethodSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationMethodSymbol.cs @@ -7,12 +7,7 @@ using System; using System.Collections.Immutable; using System.Diagnostics; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Editing; -#else using Microsoft.CodeAnalysis.Editing; -#endif namespace Microsoft.CodeAnalysis.CodeGeneration; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamedTypeSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamedTypeSymbol.cs index 2b1c38add159a..5e6d984cfcb4b 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamedTypeSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamedTypeSymbol.cs @@ -8,13 +8,8 @@ using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; -using Roslyn.Utilities; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Editing; -#else using Microsoft.CodeAnalysis.Editing; -#endif +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGeneration; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamespaceInfo.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamespaceInfo.cs index a7a6c8d26e368..93f9aa73cd232 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamespaceInfo.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamespaceInfo.cs @@ -7,7 +7,6 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.Collections; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGeneration; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamespaceOrTypeSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamespaceOrTypeSymbol.cs index 0330b8cba065d..0c033d09f820f 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamespaceOrTypeSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamespaceOrTypeSymbol.cs @@ -3,12 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Editing; -#else using Microsoft.CodeAnalysis.Editing; -#endif namespace Microsoft.CodeAnalysis.CodeGeneration; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamespaceSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamespaceSymbol.cs index 418fa8aa45b37..5f07cb19ec6cf 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamespaceSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamespaceSymbol.cs @@ -8,7 +8,6 @@ using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Collections; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGeneration; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationOperatorSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationOperatorSymbol.cs index ada9dde7c160a..e57f3c68aa734 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationOperatorSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationOperatorSymbol.cs @@ -3,12 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Editing; -#else using Microsoft.CodeAnalysis.Editing; -#endif namespace Microsoft.CodeAnalysis.CodeGeneration; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationParameterSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationParameterSymbol.cs index 6b3d2911d8a35..37675ec4564fc 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationParameterSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationParameterSymbol.cs @@ -5,12 +5,7 @@ #nullable disable using System.Collections.Immutable; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Editing; -#else using Microsoft.CodeAnalysis.Editing; -#endif namespace Microsoft.CodeAnalysis.CodeGeneration; @@ -23,7 +18,7 @@ internal sealed class CodeGenerationParameterSymbol( string name, bool isOptional, bool hasDefaultValue, - object defaultValue) : CodeGenerationSymbol(containingType?.ContainingAssembly, containingType, attributes, Accessibility.NotApplicable, new DeclarationModifiers(), name), IParameterSymbol + object defaultValue) : CodeGenerationSymbol(containingType?.ContainingAssembly, containingType, attributes, Accessibility.NotApplicable, DeclarationModifiers.None, name), IParameterSymbol { public RefKind RefKind { get; } = refKind; public bool IsParams { get; } = isParams; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationPropertySymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationPropertySymbol.cs index 4f013a06b8a4e..1c6501d043bf7 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationPropertySymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationPropertySymbol.cs @@ -5,12 +5,7 @@ #nullable disable using System.Collections.Immutable; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Editing; -#else using Microsoft.CodeAnalysis.Editing; -#endif namespace Microsoft.CodeAnalysis.CodeGeneration; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationSymbol.cs index 57b2a22d08f2d..b847c436c356c 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationSymbol.cs @@ -9,13 +9,8 @@ using System.Globalization; using System.Runtime.CompilerServices; using System.Threading; -using Microsoft.CodeAnalysis.Shared.Extensions; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Editing; -#else using Microsoft.CodeAnalysis.Editing; -#endif +using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CodeGeneration; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationTypeSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationTypeSymbol.cs index 281eb98632cdb..52f4359e86f22 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationTypeSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationTypeSymbol.cs @@ -5,12 +5,7 @@ #nullable disable using System.Collections.Immutable; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Editing; -#else using Microsoft.CodeAnalysis.Editing; -#endif namespace Microsoft.CodeAnalysis.CodeGeneration; @@ -47,9 +42,11 @@ public ImmutableArray AllInterfaces public bool IsNativeIntegerType => false; +#if !ROSLYN_4_12_OR_LOWER public bool IsExtension => false; public IParameterSymbol ExtensionParameter => null; +#endif public static ImmutableArray TupleElementTypes => default; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeRefactorings/AbstractRefactoringHelpersService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeRefactorings/AbstractRefactoringHelpersService.cs index 2372d41935977..79cc39aeea7fc 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeRefactorings/AbstractRefactoringHelpersService.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeRefactorings/AbstractRefactoringHelpersService.cs @@ -2,14 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Shared.Collections; -using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeRefactorings; @@ -19,581 +16,38 @@ internal abstract class AbstractRefactoringHelpersService this.RefactoringHelpers.IsBetweenTypeMembers(sourceText, root, position, out typeDeclaration); - private static void AddNode(bool allowEmptyNodes, ref TemporaryArray result, TSyntaxNode node) where TSyntaxNode : SyntaxNode - { - if (!allowEmptyNodes && node.Span.IsEmpty) - return; - - result.Add(node); - } - - public void AddRelevantNodes( - ParsedDocument document, TextSpan selectionRaw, bool allowEmptyNodes, int maxCount, ref TemporaryArray result, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode - { - // Given selection is trimmed first to enable over-selection that spans multiple lines. Since trailing whitespace ends - // at newline boundary over-selection to e.g. a line after LocalFunctionStatement would cause FindNode to find enclosing - // block's Node. That is because in addition to LocalFunctionStatement the selection would also contain trailing trivia - // (whitespace) of following statement. - - var root = document.Root; - - var syntaxFacts = document.LanguageServices.GetRequiredService(); - var headerFacts = document.LanguageServices.GetRequiredService(); - var selectionTrimmed = CodeRefactoringHelpers.GetTrimmedTextSpan(document, selectionRaw); - - // If user selected only whitespace we don't want to return anything. We could do following: - // 1) Consider token that owns (as its trivia) the whitespace. - // 2) Consider start/beginning of whitespace as location (empty selection) - // Option 1) can't be used all the time and 2) can be confusing for users. Therefore bailing out is the - // most consistent option. - if (selectionTrimmed.IsEmpty && !selectionRaw.IsEmpty) - return; - - // Every time a Node is considered an extractNodes method is called to add all nodes around the original one - // that should also be considered. - // - // That enables us to e.g. return node `b` when Node `var a = b;` is being considered without a complex (and potentially - // lang. & situation dependent) into Children descending code here. We can't just try extracted Node because we might - // want the whole node `var a = b;` - - // Handle selections: - // - Most/the whole wanted Node is selected (e.g. `C [|Fun() {}|]` - // - The smallest node whose FullSpan includes the whole (trimmed) selection - // - Using FullSpan is important because it handles over-selection with comments - // - Travels upwards through same-sized (FullSpan) nodes, extracting - // - Token with wanted Node as direct parent is selected (e.g. IdentifierToken for LocalFunctionStatement: `C [|Fun|]() {}`) - // Note: Whether we have selection or location has to be checked against original selection because selecting just - // whitespace could collapse selectionTrimmed into and empty Location. But we don't want `[| |]token` - // registering as ` [||]token`. - if (!selectionTrimmed.IsEmpty) - { - AddRelevantNodesForSelection(syntaxFacts, root, selectionTrimmed, allowEmptyNodes, maxCount, ref result, cancellationToken); - } - else - { - var location = selectionTrimmed.Start; - - // No more selection -> Handle what current selection is touching: - // - // Consider touching only for empty selections. Otherwise `[|C|] methodName(){}` would be considered as - // touching the Method's Node (through the left edge, see below) which is something the user probably - // didn't want since they specifically selected only the return type. - // - // What the selection is touching is used in two ways. - // - Firstly, it is used to handle situation where it touches a Token whose direct ancestor is wanted - // Node. While having the (even empty) selection inside such token or to left of such Token is already - // handle by code above touching it from right `C methodName[||](){}` isn't (the FindNode for that - // returns Args node). - // - // - Secondly, it is used for left/right edge climbing. E.g. `[||]C methodName(){}` the touching token's - // direct ancestor is TypeNode for the return type but it is still reasonable to expect that the user - // might want to be given refactorings for the whole method (as he has caret on the edge of it). - // Therefore we travel the Node tree upwards and as long as we're on the left edge of a Node's span we - // consider such node & potentially continue traveling upwards. The situation for right edge (`C - // methodName(){}[||]`) is analogical. E.g. for right edge `C methodName(){}[||]`: CloseBraceToken -> - // BlockSyntax -> LocalFunctionStatement -> null (higher node doesn't end on position anymore) Note: - // left-edge climbing needs to handle AttributeLists explicitly, see below for more information. - // - // - Thirdly, if location isn't touching anything, we move the location to the token in whose trivia - // location is in. more about that below. - // - // - Fourthly, if we're in an expression / argument we consider touching a parent expression whenever - // we're within it as long as it is on the first line of such expression (arbitrary heuristic). - - // In addition to per-node extr also check if current location (if selection is empty) is in a header of - // higher level desired node once. We do that only for locations because otherwise `[|int|] A { get; - // set; }) would trigger all refactorings for Property Decl. We cannot check this any sooner because the - // above code could've changed current location. - AddNonHiddenCorrectTypeNodes(ExtractNodesInHeader(root, location, headerFacts), allowEmptyNodes, maxCount, ref result, cancellationToken); - if (result.Count >= maxCount) - return; - - var (tokenToLeft, tokenToRight) = GetTokensToLeftAndRight(document, root, location); - - // Add Nodes for touching tokens as described above. - AddNodesForTokenToRight(syntaxFacts, root, allowEmptyNodes, maxCount, ref result, tokenToRight, cancellationToken); - if (result.Count >= maxCount) - return; - - AddNodesForTokenToLeft(syntaxFacts, allowEmptyNodes, maxCount, ref result, tokenToLeft, cancellationToken); - if (result.Count >= maxCount) - return; - - // If the wanted node is an expression syntax -> traverse upwards even if location is deep within a SyntaxNode. - // We want to treat more types like expressions, e.g.: ArgumentSyntax should still trigger even if deep-in. - if (IsWantedTypeExpressionLike()) - { - // Reason to treat Arguments (and potentially others) as Expression-like: - // https://github.com/dotnet/roslyn/pull/37295#issuecomment-516145904 - AddNodesDeepIn(document, location, allowEmptyNodes, maxCount, ref result, cancellationToken); - } - } - } - - private static bool IsWantedTypeExpressionLike() where TSyntaxNode : SyntaxNode - { - var wantedType = typeof(TSyntaxNode); - - var expressionType = typeof(TExpressionSyntax); - var argumentType = typeof(TArgumentSyntax); - var expressionStatementType = typeof(TExpressionStatementSyntax); - - return IsAEqualOrSubclassOfB(wantedType, expressionType) || - IsAEqualOrSubclassOfB(wantedType, argumentType) || - IsAEqualOrSubclassOfB(wantedType, expressionStatementType); - - static bool IsAEqualOrSubclassOfB(Type a, Type b) - { - return a == b || a.IsSubclassOf(b); - } - } - - private static (SyntaxToken tokenToLeft, SyntaxToken tokenToRight) GetTokensToLeftAndRight( - ParsedDocument document, - SyntaxNode root, - int location) - { - // get Token for current location - var tokenOnLocation = root.FindToken(location); - - var syntaxKinds = document.LanguageServices.GetRequiredService(); - if (tokenOnLocation.RawKind == syntaxKinds.CommaToken && location >= tokenOnLocation.Span.End) - { - var commaToken = tokenOnLocation; - - // A couple of scenarios to care about: - // - // X,$$ Y - // - // In this case, consider the user on the Y node. - // - // X,$$ - // Y - // - // In this case, consider the user on the X node. - var nextToken = commaToken.GetNextToken(); - var previousToken = commaToken.GetPreviousToken(); - if (nextToken != default && !commaToken.TrailingTrivia.Any(t => t.RawKind == syntaxKinds.EndOfLineTrivia)) - { - return (tokenToLeft: default, tokenToRight: nextToken); - } - else if (previousToken != default && previousToken.Span.End == commaToken.Span.Start) - { - return (tokenToLeft: previousToken, tokenToRight: default); - } - } - - // Gets a token that is directly to the right of current location or that encompasses current location (`[||]tokenToRightOrIn` or `tok[||]enToRightOrIn`) - var tokenToRight = tokenOnLocation.Span.Contains(location) - ? tokenOnLocation - : default; - - // A token can be to the left only when there's either no tokenDirectlyToRightOrIn or there's one directly starting at current location. - // Otherwise (otherwise tokenToRightOrIn is also left from location, e.g: `tok[||]enToRightOrIn`) - var tokenToLeft = default(SyntaxToken); - if (tokenToRight == default || tokenToRight.FullSpan.Start == location) - { - var previousToken = tokenOnLocation.Span.End == location - ? tokenOnLocation - : tokenOnLocation.GetPreviousToken(includeZeroWidth: true); - - tokenToLeft = previousToken.Span.End == location - ? previousToken - : default; - } - - // If both tokens directly to left & right are empty -> we're somewhere in the middle of whitespace. - // Since there wouldn't be (m)any other refactorings we can try to offer at least the ones for (semantically) - // closest token/Node. Thus, we move the location to the token in whose `.FullSpan` the original location was. - if (tokenToLeft == default && tokenToRight == default) - { - var sourceText = document.Text; - - if (IsAcceptableLineDistanceAway(sourceText, tokenOnLocation, location)) - { - // tokenOnLocation: token in whose trivia location is at - if (tokenOnLocation.Span.Start >= location) - { - tokenToRight = tokenOnLocation; - } - else - { - tokenToLeft = tokenOnLocation; - } - } - } - - return (tokenToLeft, tokenToRight); - - static bool IsAcceptableLineDistanceAway( - SourceText sourceText, SyntaxToken tokenOnLocation, int location) - { - // assume non-trivia token can't span multiple lines - var tokenLine = sourceText.Lines.GetLineFromPosition(tokenOnLocation.Span.Start); - var locationLine = sourceText.Lines.GetLineFromPosition(location); - - // Change location to nearest token only if the token is off by one line or less - var lineDistance = tokenLine.LineNumber - locationLine.LineNumber; - if (lineDistance is not 0 and not 1) - return false; - - // Note: being a line below a tokenOnLocation is impossible in current model as whitespace - // trailing trivia ends on new line. Which is fine because if you're a line _after_ some node - // you usually don't want refactorings for what's above you. - - if (lineDistance == 1) - { - // position is one line above the node of interest. This is fine if that - // line is blank. Otherwise, if it isn't (i.e. it contains comments, - // directives, or other trivia), then it's not likely the user is selecting - // this entry. - return locationLine.IsEmptyOrWhitespace(); - } - - // On hte same line. This position is acceptable. - return true; - } - } - - private void AddNodesForTokenToLeft( - ISyntaxFactsService syntaxFacts, - bool allowEmptyNodes, - int maxCount, - ref TemporaryArray result, - SyntaxToken tokenToLeft, - CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode - { - var location = tokenToLeft.Span.End; - - // there could be multiple (n) tokens to the left if first n-1 are Empty -> iterate over all of them - while (tokenToLeft != default) - { - var leftNode = tokenToLeft.Parent; - do - { - // Consider either a Node that is: - // - Ancestor Node of such Token as long as their span ends on location (it's still on the edge) - AddNonHiddenCorrectTypeNodes(ExtractNodesSimple(leftNode, syntaxFacts), allowEmptyNodes, maxCount, ref result, cancellationToken); - if (result.Count >= maxCount) - return; - - leftNode = leftNode?.Parent; - if (leftNode is null) - break; - - if (leftNode.GetLastToken().Span.End != location && leftNode.Span.End != location) - break; - } - while (true); - - // as long as current tokenToLeft is empty -> its previous token is also tokenToLeft - tokenToLeft = tokenToLeft.Span.IsEmpty - ? tokenToLeft.GetPreviousToken(includeZeroWidth: true) - : default; - } - } - - private void AddNodesForTokenToRight( - ISyntaxFactsService syntaxFacts, - SyntaxNode root, - bool allowEmptyNodes, - int maxCount, - ref TemporaryArray result, - SyntaxToken tokenToRightOrIn, - CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode - { - var location = tokenToRightOrIn.Span.Start; - - if (tokenToRightOrIn != default) - { - var rightNode = tokenToRightOrIn.Parent; - do - { - // Consider either a Node that is: - // - Parent of touched Token (location can be within) - // - Ancestor Node of such Token as long as their span starts on location (it's still on the edge) - AddNonHiddenCorrectTypeNodes(ExtractNodesSimple(rightNode, syntaxFacts), allowEmptyNodes, maxCount, ref result, cancellationToken); - if (result.Count >= maxCount) - return; - - rightNode = rightNode?.Parent; - if (rightNode == null) - break; - - // The edge climbing for node to the right needs to handle Attributes e.g.: - // [Test1] - // //Comment1 - // [||]object Property1 { get; set; } - // In essence: - // - On the left edge of the node (-> left edge of first AttributeLists) - // - On the left edge of the node sans AttributeLists (& as everywhere comments) - if (rightNode.Span.Start != location) - { - var rightNodeSpanWithoutAttributes = syntaxFacts.GetSpanWithoutAttributes(root, rightNode); - if (rightNodeSpanWithoutAttributes.Start != location) - break; - } - } - while (true); - } - } - - private void AddRelevantNodesForSelection( - ISyntaxFactsService syntaxFacts, - SyntaxNode root, - TextSpan selectionTrimmed, - bool allowEmptyNodes, - int maxCount, - ref TemporaryArray result, - CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode - { - var selectionNode = root.FindNode(selectionTrimmed, getInnermostNodeForTie: true); - var prevNode = selectionNode; - do - { - var nonHiddenExtractedSelectedNodes = ExtractNodesSimple(selectionNode, syntaxFacts).OfType().Where(n => !n.OverlapsHiddenPosition(cancellationToken)); - foreach (var nonHiddenExtractedNode in nonHiddenExtractedSelectedNodes) - { - // For selections we need to handle an edge case where only AttributeLists are within selection (e.g. `Func([|[in][out]|] arg1);`). - // In that case the smallest encompassing node is still the whole argument node but it's hard to justify showing refactorings for it - // if user selected only its attributes. - - // Selection contains only AttributeLists -> don't consider current Node - var spanWithoutAttributes = syntaxFacts.GetSpanWithoutAttributes(root, nonHiddenExtractedNode); - if (!selectionTrimmed.IntersectsWith(spanWithoutAttributes)) - { - break; - } - - AddNode(allowEmptyNodes, ref result, nonHiddenExtractedNode); - if (result.Count >= maxCount) - return; - } - - prevNode = selectionNode; - selectionNode = selectionNode.Parent; - } - while (selectionNode != null && prevNode.FullWidth() == selectionNode.FullWidth()); - } - - /// - /// Extractor function that retrieves all nodes that should be considered for extraction of given current node. - /// - /// The rationale is that when user selects e.g. entire local declaration statement [|var a = b;|] it is reasonable - /// to provide refactoring for `b` node. Similarly for other types of refactorings. - /// - /// - /// - /// Should also return given node. - /// - protected virtual IEnumerable ExtractNodesSimple(SyntaxNode? node, ISyntaxFactsService syntaxFacts) - { - if (node == null) - { - yield break; - } - - // First return the node itself so that it is considered - yield return node; - - // REMARKS: - // The set of currently attempted extractions is in no way exhaustive and covers only cases - // that were found to be relevant for refactorings that were moved to `TryGetSelectedNodeAsync`. - // Feel free to extend it / refine current heuristics. - - // `var a = b;` | `var a = b`; - if (syntaxFacts.IsLocalDeclarationStatement(node) || syntaxFacts.IsLocalDeclarationStatement(node.Parent)) - { - var localDeclarationStatement = syntaxFacts.IsLocalDeclarationStatement(node) ? node : node.Parent!; - - // Check if there's only one variable being declared, otherwise following transformation - // would go through which isn't reasonable since we can't say the first one specifically - // is wanted. - // `var a = 1, `c = 2, d = 3`; - // -> `var a = 1`, c = 2, d = 3; - var variables = syntaxFacts.GetVariablesOfLocalDeclarationStatement(localDeclarationStatement); - if (variables.Count == 1) - { - var declaredVariable = variables.First(); - - // -> `a = b` - yield return declaredVariable; - - // -> `b` - var initializer = syntaxFacts.GetInitializerOfVariableDeclarator(declaredVariable); - if (initializer != null) - { - var value = syntaxFacts.GetValueOfEqualsValueClause(initializer); - if (value != null) - { - yield return value; - } - } - } - } - - // var `a = b`; - if (syntaxFacts.IsVariableDeclarator(node)) - { - // -> `b` - var initializer = syntaxFacts.GetInitializerOfVariableDeclarator(node); - if (initializer != null) - { - var value = syntaxFacts.GetValueOfEqualsValueClause(initializer); - if (value != null) - { - yield return value; - } - } - } - - // `a = b;` - // -> `b` - if (syntaxFacts.IsSimpleAssignmentStatement(node)) - { - syntaxFacts.GetPartsOfAssignmentExpressionOrStatement(node, out _, out _, out var rightSide); - yield return rightSide; - } - - // `a();` - // -> a() - if (syntaxFacts.IsExpressionStatement(node)) - { - yield return syntaxFacts.GetExpressionOfExpressionStatement(node); - } - - // `a()`; - // -> `a();` - if (syntaxFacts.IsExpressionStatement(node.Parent)) - { - yield return node.Parent; - } - } - - /// - /// Extractor function that checks and retrieves all nodes current location is in a header. - /// - protected virtual IEnumerable ExtractNodesInHeader(SyntaxNode root, int location, IHeaderFactsService headerFacts) - { - // Header: [Test] `public int a` { get; set; } - if (headerFacts.IsOnPropertyDeclarationHeader(root, location, out var propertyDeclaration)) - yield return propertyDeclaration; - - // Header: public C([Test]`int a = 42`) {} - if (headerFacts.IsOnParameterHeader(root, location, out var parameter)) - yield return parameter; - - // Header: `public I.C([Test]int a = 42)` {} - if (headerFacts.IsOnMethodHeader(root, location, out var method)) - yield return method; - - // Header: `static C([Test]int a = 42)` {} - if (headerFacts.IsOnLocalFunctionHeader(root, location, out var localFunction)) - yield return localFunction; - - // Header: `var a = `3,` b = `5,` c = `7 + 3``; - if (headerFacts.IsOnLocalDeclarationHeader(root, location, out var localDeclaration)) - yield return localDeclaration; - - // Header: `if(...)`{ }; - if (headerFacts.IsOnIfStatementHeader(root, location, out var ifStatement)) - yield return ifStatement; - - // Header: `foreach (var a in b)` { } - if (headerFacts.IsOnForeachHeader(root, location, out var foreachStatement)) - yield return foreachStatement; - - if (headerFacts.IsOnTypeHeader(root, location, out var typeDeclaration)) - yield return typeDeclaration; - } - - private static void AddNodesDeepIn( - ParsedDocument document, - int position, - bool allowEmptyNodes, - int maxCount, - ref TemporaryArray result, - CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode - { - // If we're deep inside we don't have to deal with being on edges (that gets dealt by TryGetSelectedNodeAsync) - // -> can simply FindToken -> proceed testing its ancestors - var root = document.Root; - if (root is null) - throw new NotSupportedException(WorkspaceExtensionsResources.Document_does_not_support_syntax_trees); - - var token = root.FindTokenOnRightOfPosition(position, true); - - // traverse upwards and add all parents if of correct type - var ancestor = token.Parent; - while (ancestor != null) - { - if (ancestor is TSyntaxNode typedAncestor) - { - var sourceText = document.Text; - - var argumentStartLine = sourceText.Lines.GetLineFromPosition(typedAncestor.Span.Start).LineNumber; - var caretLine = sourceText.Lines.GetLineFromPosition(position).LineNumber; - - if (argumentStartLine == caretLine && !typedAncestor.OverlapsHiddenPosition(cancellationToken)) - { - AddNode(allowEmptyNodes, ref result, typedAncestor); - if (result.Count >= maxCount) - return; - } - else if (argumentStartLine < caretLine) - { - // higher level nodes will have Span starting at least on the same line -> can bail out - return; - } - } - - ancestor = ancestor.Parent; - } - } - - private static void AddNonHiddenCorrectTypeNodes( - IEnumerable nodes, bool allowEmptyNodes, int maxCount, ref TemporaryArray result, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode - { - foreach (var node in nodes) - { - if (node is TSyntaxNode typedNode && - !node.OverlapsHiddenPosition(cancellationToken)) - { - AddNode(allowEmptyNodes, ref result, typedNode); - if (result.Count >= maxCount) - return; - } - } - } + public void AddRelevantNodes(SourceText sourceText, SyntaxNode root, TextSpan selection, bool allowEmptyNodes, int maxCount, ref TemporaryArray result, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode + => this.RefactoringHelpers.AddRelevantNodes(sourceText, root, selection, allowEmptyNodes, maxCount, ref result, cancellationToken); public bool IsOnTypeHeader(SyntaxNode root, int position, bool fullHeader, [NotNullWhen(true)] out SyntaxNode? typeDeclaration) - => HeaderFacts.IsOnTypeHeader(root, position, fullHeader, out typeDeclaration); + => this.RefactoringHelpers.IsOnTypeHeader(root, position, fullHeader, out typeDeclaration); public bool IsOnPropertyDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? propertyDeclaration) - => HeaderFacts.IsOnPropertyDeclarationHeader(root, position, out propertyDeclaration); + => this.RefactoringHelpers.IsOnPropertyDeclarationHeader(root, position, out propertyDeclaration); public bool IsOnParameterHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? parameter) - => HeaderFacts.IsOnParameterHeader(root, position, out parameter); + => this.RefactoringHelpers.IsOnParameterHeader(root, position, out parameter); public bool IsOnMethodHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? method) - => HeaderFacts.IsOnMethodHeader(root, position, out method); + => this.RefactoringHelpers.IsOnMethodHeader(root, position, out method); public bool IsOnLocalFunctionHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localFunction) - => HeaderFacts.IsOnLocalFunctionHeader(root, position, out localFunction); + => this.RefactoringHelpers.IsOnLocalFunctionHeader(root, position, out localFunction); public bool IsOnLocalDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localDeclaration) - => HeaderFacts.IsOnLocalDeclarationHeader(root, position, out localDeclaration); + => this.RefactoringHelpers.IsOnLocalDeclarationHeader(root, position, out localDeclaration); public bool IsOnIfStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? ifStatement) - => HeaderFacts.IsOnIfStatementHeader(root, position, out ifStatement); + => this.RefactoringHelpers.IsOnIfStatementHeader(root, position, out ifStatement); public bool IsOnWhileStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? whileStatement) - => HeaderFacts.IsOnWhileStatementHeader(root, position, out whileStatement); + => this.RefactoringHelpers.IsOnWhileStatementHeader(root, position, out whileStatement); public bool IsOnForeachHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? foreachStatement) - => HeaderFacts.IsOnForeachHeader(root, position, out foreachStatement); + => this.RefactoringHelpers.IsOnForeachHeader(root, position, out foreachStatement); } diff --git a/src/Features/Core/Portable/CodeRefactorings/CodeRefactoringContextExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeRefactorings/CodeRefactoringContextExtensions.cs similarity index 97% rename from src/Features/Core/Portable/CodeRefactorings/CodeRefactoringContextExtensions.cs rename to src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeRefactorings/CodeRefactoringContextExtensions.cs index 5cd4ae09ae54d..25c14a692c811 100644 --- a/src/Features/Core/Portable/CodeRefactorings/CodeRefactoringContextExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeRefactorings/CodeRefactoringContextExtensions.cs @@ -7,7 +7,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; -using Microsoft.CodeAnalysis.Shared.Collections; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeRefactorings; @@ -25,14 +25,15 @@ public static void RegisterRefactorings( { foreach (var action in actions) { +#if WORKSPACE if (applicableToSpan != null) { context.RegisterRefactoring(action, applicableToSpan.Value); + continue; } - else - { - context.RegisterRefactoring(action); - } +#endif + + context.RegisterRefactoring(action); } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeRefactorings/CodeRefactoringHelpers.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeRefactorings/CodeRefactoringHelpers.cs index 54a227a9b3410..76e336bca079c 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeRefactorings/CodeRefactoringHelpers.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeRefactorings/CodeRefactoringHelpers.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; @@ -24,7 +23,7 @@ internal static class CodeRefactoringHelpers /// name="selection"/> is treated more as a caret location. /// /// - /// It's intended to be used in conjunction with that, for + /// It's intended to be used in conjunction with IRefactoringHelpers.AddRelevantNodes that, for /// non-empty selections, returns the smallest encompassing node. A node that can, for certain refactorings, be too /// large given user-selection even though it is the smallest that can be retrieved. /// @@ -93,29 +92,4 @@ public static bool IsNodeUnderselected(SyntaxNode? node, TextSpan selection) // but fires up e.g.: `1 + [|2 + 3|]`. return beginningNode.Span.End <= selection.Start || endNode.Span.Start >= selection.End; } - - /// - /// Trims leading and trailing whitespace from . - /// - /// - /// Returns unchanged in case . - /// Returns empty Span with original in case it contains only whitespace. - /// - public static TextSpan GetTrimmedTextSpan(ParsedDocument document, TextSpan span) - { - if (span.IsEmpty) - return span; - - var sourceText = document.Text; - var start = span.Start; - var end = span.End; - - while (start < end && char.IsWhiteSpace(sourceText[end - 1])) - end--; - - while (start < end && char.IsWhiteSpace(sourceText[start])) - start++; - - return TextSpan.FromBounds(start, end); - } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeRefactorings/IRefactoringHelpersService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeRefactorings/IRefactoringHelpersService.cs index abdf86630343b..9c719c90429fd 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeRefactorings/IRefactoringHelpersService.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeRefactorings/IRefactoringHelpersService.cs @@ -2,56 +2,23 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Diagnostics.CodeAnalysis; using System.Threading; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Host; -using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeRefactorings; -/// -/// Contains helpers related to asking intuitive semantic questions about a users intent -/// based on the position of their caret or span of their selection. -/// -internal interface IRefactoringHelpersService : IHeaderFactsService, ILanguageService +internal interface IRefactoringHelpersService : IRefactoringHelpers, ILanguageService { - /// - /// True if the user is on a blank line where a member could go inside a type declaration. - /// This will be between members and not ever inside a member. - /// - bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration); +} - /// - /// - /// Returns an array of instances for refactoring given specified selection - /// in document. determines if the returned nodes will can have empty spans - /// or not. - /// - /// - /// A instance is returned if: - Selection is zero-width and inside/touching - /// a Token with direct parent of type . - Selection is zero-width and - /// touching a Token whose ancestor of type ends/starts precisely on current - /// selection. - Selection is zero-width and in whitespace that corresponds to a Token whose direct ancestor is - /// of type of type . - Selection is zero-width and in a header (defined by - /// ISyntaxFacts helpers) of an node of type of type . - Token whose direct - /// parent of type is selected. - Selection is zero-width and wanted node is - /// an expression / argument with selection within such syntax node (arbitrarily deep) on its first line. - - /// Whole node of a type is selected. - /// - /// - /// Attempts extracting a Node of type for each Node it considers (see - /// above). E.g. extracts initializer expressions from declarations and assignments, Property declaration from - /// any header node, etc. - /// - /// - /// Note: this function trims all whitespace from both the beginning and the end of given . The trimmed version is then used to determine relevant . It also - /// handles incomplete selections of tokens gracefully. Over-selection containing leading comments is also - /// handled correctly. - /// - /// - void AddRelevantNodes( - ParsedDocument document, TextSpan selection, bool allowEmptyNodes, int maxCount, ref TemporaryArray result, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode; +internal static class IRefactoringHelpersServiceExtensions +{ + public static void AddRelevantNodes( + this IRefactoringHelpersService service, ParsedDocument document, TextSpan selection, bool allowEmptyNodes, int maxCount, ref TemporaryArray result, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode + { + service.AddRelevantNodes(document.Text, document.Root, selection, allowEmptyNodes, maxCount, ref result, cancellationToken); + } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Editing/ImportAdderService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Editing/ImportAdderService.cs index 91ee326561e99..9b9f8f0a575f1 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Editing/ImportAdderService.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Editing/ImportAdderService.cs @@ -179,7 +179,7 @@ private async Task AddImportDirectivesFromSymbolAnnotationsAsync( var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); -#if CODE_STYLE +#if !WORKSPACE var model = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); #else var model = await document.GetRequiredNullableDisabledSemanticModelAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Editing/ModifierExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Editing/ModifierExtensions.cs new file mode 100644 index 0000000000000..7c23ddfc8c0be --- /dev/null +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Editing/ModifierExtensions.cs @@ -0,0 +1,19 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis.Editing; + +internal static class ModifierExtensions +{ + public static DeclarationModifiers ToDeclarationModifiers(this Modifiers modifiers) + { +#if WORKSPACE + return new DeclarationModifiers(modifiers); +#else + return Unsafe.As(ref modifiers); +#endif + } +} diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/DocumentExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/DocumentExtensions.cs index 98679691b2719..b0d1c227211fd 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/DocumentExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/DocumentExtensions.cs @@ -11,7 +11,6 @@ using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.SemanticModelReuse; using Microsoft.CodeAnalysis.Text; -using Roslyn.Utilities; using Microsoft.CodeAnalysis.Options; #if DEBUG @@ -40,7 +39,7 @@ public static async ValueTask GetRequiredSemanticModelAsync(this return semanticModel ?? throw new InvalidOperationException(string.Format(WorkspaceExtensionsResources.SyntaxTree_is_required_to_accomplish_the_task_but_is_not_supported_by_document_0, document.Name)); } -#if !CODE_STYLE +#if WORKSPACE public static async ValueTask GetRequiredNullableDisabledSemanticModelAsync(this Document document, CancellationToken cancellationToken) { @@ -64,7 +63,7 @@ public static async ValueTask GetRequiredSyntaxTreeAsync(this Docume return syntaxTree ?? throw new InvalidOperationException(string.Format(WorkspaceExtensionsResources.SyntaxTree_is_required_to_accomplish_the_task_but_is_not_supported_by_document_0, document.Name)); } -#if !CODE_STYLE +#if WORKSPACE public static SyntaxTree GetRequiredSyntaxTreeSynchronously(this Document document, CancellationToken cancellationToken) { var syntaxTree = document.GetSyntaxTreeSynchronously(cancellationToken); @@ -81,7 +80,7 @@ public static async ValueTask GetRequiredSyntaxRootAsync(this Docume return root ?? throw new InvalidOperationException(string.Format(WorkspaceExtensionsResources.SyntaxTree_is_required_to_accomplish_the_task_but_is_not_supported_by_document_0, document.Name)); } -#if !CODE_STYLE +#if WORKSPACE public static SyntaxNode GetRequiredSyntaxRootSynchronously(this Document document, CancellationToken cancellationToken) { var root = document.GetSyntaxRootSynchronously(cancellationToken); @@ -195,7 +194,7 @@ public static async Task VerifyNoErrorsAsync(this Document newDocument, string m } #endif -#if !CODE_STYLE +#if WORKSPACE public static bool IsGeneratedCode(this Document document, CancellationToken cancellationToken) { var generatedCodeRecognitionService = document.GetLanguageService(); @@ -220,7 +219,7 @@ public static IEnumerable GetLinkedDocuments(this Document document) } } -#if CODE_STYLE +#if !WORKSPACE public static async ValueTask GetHostAnalyzerConfigOptionsAsync(this Document document, CancellationToken cancellationToken) { var syntaxTree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/ISolutionExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/ISolutionExtensions.cs index 20de0eebe91b8..7cd8fbc03720f 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/ISolutionExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/ISolutionExtensions.cs @@ -51,7 +51,7 @@ public static Document GetRequiredDocument(this Solution solution, DocumentId do if (documentId is null) throw new ArgumentNullException(nameof(documentId)); -#if !CODE_STYLE +#if WORKSPACE if (documentId.IsSourceGenerated) { // If we get a source-generated DocumentId, we can give a different exception to make it clear the type of failure this is; otherwise a failure of @@ -64,7 +64,7 @@ public static Document GetRequiredDocument(this Solution solution, DocumentId do return solution.GetDocument(documentId) ?? throw CreateDocumentNotFoundException(); } -#if !CODE_STYLE +#if WORKSPACE /// /// Returns the for the given if it exists and has been generated. /// @@ -86,7 +86,10 @@ public static SourceGeneratedDocument GetRequiredSourceGeneratedDocumentForAlrea return sourceGeneratedDocument; } - public static async ValueTask GetRequiredDocumentAsync(this Solution solution, DocumentId documentId, bool includeSourceGenerated = false, CancellationToken cancellationToken = default) + public static ValueTask GetRequiredDocumentAsync(this Solution solution, DocumentId documentId, CancellationToken cancellationToken) + => GetRequiredDocumentAsync(solution, documentId, includeSourceGenerated: false, cancellationToken); + + public static async ValueTask GetRequiredDocumentAsync(this Solution solution, DocumentId documentId, bool includeSourceGenerated, CancellationToken cancellationToken) => (await solution.GetDocumentAsync(documentId, includeSourceGenerated, cancellationToken).ConfigureAwait(false)) ?? throw CreateDocumentNotFoundException(); public static async ValueTask GetRequiredTextDocumentAsync(this Solution solution, DocumentId documentId, CancellationToken cancellationToken = default) @@ -105,7 +108,7 @@ public static TextDocument GetRequiredTextDocument(this Solution solution, Docum private static Exception CreateDocumentNotFoundException() => new InvalidOperationException(WorkspaceExtensionsResources.The_solution_does_not_contain_the_specified_document); -#if !CODE_STYLE +#if WORKSPACE public static Solution WithUpToDateSourceGeneratorDocuments(this Solution solution, IEnumerable projectIds) { // If the solution is already in automatic mode, then SG documents are already always up to date. diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/ISymbolExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/ISymbolExtensions.cs index 0136c0a0542c8..65420a376407d 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/ISymbolExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/ISymbolExtensions.cs @@ -2,11 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Editing; -#else using Microsoft.CodeAnalysis.Editing; -#endif namespace Microsoft.CodeAnalysis.Shared.Extensions; @@ -14,13 +10,13 @@ internal static partial class ISymbolExtensions { public static DeclarationModifiers GetSymbolModifiers(this ISymbol symbol) { - return new DeclarationModifiers( - isStatic: symbol.IsStatic, - isAbstract: symbol.IsAbstract, - isUnsafe: symbol.RequiresUnsafeModifier(), - isVirtual: symbol.IsVirtual, - isOverride: symbol.IsOverride, - isSealed: symbol.IsSealed, - isRequired: symbol.IsRequired()); + return DeclarationModifiers.None + .WithIsStatic(symbol.IsStatic) + .WithIsAbstract(symbol.IsAbstract) + .WithIsUnsafe(symbol.RequiresUnsafeModifier()) + .WithIsVirtual(symbol.IsVirtual) + .WithIsOverride(symbol.IsOverride) + .WithIsSealed(symbol.IsSealed) + .WithIsRequired(symbol.IsRequired()); } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/ProjectExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/ProjectExtensions.cs index cc5b2d7b12c6d..139ac3336f761 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/ProjectExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/ProjectExtensions.cs @@ -33,7 +33,7 @@ public static TLanguageService GetRequiredLanguageService(this /// Gets extended host language services, which includes language services from . /// public static HostLanguageServices GetExtendedLanguageServices(this Project project) -#if CODE_STYLE +#if !WORKSPACE => project.Solution.Workspace.Services.GetExtendedLanguageServices(project.Language); #else => project.Solution.Services.GetExtendedLanguageServices(project.Language); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/SyntaxGeneratorExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/SyntaxGeneratorExtensions.cs index 605627f735c8c..5e6c2639f2132 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/SyntaxGeneratorExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/SyntaxGeneratorExtensions.cs @@ -11,12 +11,6 @@ using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Simplification; -#if CODE_STYLE -using DeclarationModifiers = Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers; -#else -using DeclarationModifiers = Microsoft.CodeAnalysis.Editing.DeclarationModifiers; -#endif - namespace Microsoft.CodeAnalysis.Shared.Extensions; internal static partial class SyntaxGeneratorExtensions @@ -77,7 +71,7 @@ public static SyntaxNode GetDefaultEqualityComparer( { var equalityComparerType = compilation.EqualityComparerOfTType(); var typeExpression = equalityComparerType == null - ? factory.GenericName(nameof(EqualityComparer), type) + ? factory.GenericName(nameof(EqualityComparer<>), type) : generatorInternal.Type(equalityComparerType.Construct(type), typeContext: false); return factory.MemberAccessExpression(typeExpression, factory.IdentifierName(DefaultName)); @@ -299,7 +293,7 @@ public static ImmutableArray CreateFieldsForParameters( result.Add(CodeGenerationSymbolFactory.CreateFieldSymbol( attributes: default, accessibility: Accessibility.Private, - modifiers: new DeclarationModifiers(isUnsafe: !isContainedInUnsafeType && parameter.RequiresUnsafeModifier()), + modifiers: DeclarationModifiers.None.WithIsUnsafe(!isContainedInUnsafeType && parameter.RequiresUnsafeModifier()), type: parameter.Type, name: fieldName)); } @@ -321,7 +315,7 @@ public static ImmutableArray CreatePropertiesForParameters( result.Add(CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: default, accessibility: Accessibility.Public, - modifiers: new DeclarationModifiers(isUnsafe: !isContainedInUnsafeType && parameter.RequiresUnsafeModifier()), + modifiers: DeclarationModifiers.None.WithIsUnsafe(!isContainedInUnsafeType && parameter.RequiresUnsafeModifier()), type: parameter.Type, refKind: RefKind.None, explicitInterfaceImplementations: [], diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/SyntaxGeneratorExtensions_CreateEqualsMethod.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/SyntaxGeneratorExtensions_CreateEqualsMethod.cs index 3919fc0d6a83b..950a1e368f09c 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/SyntaxGeneratorExtensions_CreateEqualsMethod.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/SyntaxGeneratorExtensions_CreateEqualsMethod.cs @@ -11,6 +11,7 @@ using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; +using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; @@ -19,12 +20,6 @@ using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; -#if CODE_STYLE -using DeclarationModifiers = Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers; -#else -using DeclarationModifiers = Microsoft.CodeAnalysis.Editing.DeclarationModifiers; -#endif - namespace Microsoft.CodeAnalysis.Shared.Extensions; internal static partial class SyntaxGeneratorExtensions @@ -51,7 +46,7 @@ public static IMethodSymbol CreateEqualsMethod(this Compilation compilation, Imm return CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, accessibility: Accessibility.Public, - modifiers: new DeclarationModifiers(isOverride: true), + modifiers: DeclarationModifiers.Override, returnType: compilation.GetSpecialType(SpecialType.System_Boolean), refKind: RefKind.None, explicitInterfaceImplementations: default, @@ -91,7 +86,7 @@ public static IMethodSymbol CreateIEquatableEqualsMethod( { return CodeGenerationSymbolFactory.CreateMethodSymbol( methodSymbol, - modifiers: new DeclarationModifiers(), + modifiers: DeclarationModifiers.None, explicitInterfaceImplementations: [methodSymbol], parameters: parameters, statements: statements); @@ -100,7 +95,7 @@ public static IMethodSymbol CreateIEquatableEqualsMethod( { return CodeGenerationSymbolFactory.CreateMethodSymbol( methodSymbol, - modifiers: new DeclarationModifiers(), + modifiers: DeclarationModifiers.None, parameters: parameters, statements: statements); } @@ -480,7 +475,7 @@ public static ImmutableArray CreateMemberDelegatingConstructor( var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default, accessibility: accessibility, - modifiers: new DeclarationModifiers(isUnsafe: !isContainedInUnsafeType && parameters.Any(static p => p.RequiresUnsafeModifier())), + modifiers: DeclarationModifiers.None.WithIsUnsafe(!isContainedInUnsafeType && parameters.Any(static p => p.RequiresUnsafeModifier())), typeName: typeName, parameters: parameters, statements: statements, diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/TextDocumentExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/TextDocumentExtensions.cs index 41c0b04ef29ae..1f769a4a6ef23 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/TextDocumentExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/TextDocumentExtensions.cs @@ -2,8 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Threading.Tasks; using System.Threading; +using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; @@ -11,7 +11,7 @@ namespace Microsoft.CodeAnalysis.Shared.Extensions; internal static partial class TextDocumentExtensions { -#if CODE_STYLE +#if !WORKSPACE public static ValueTask GetValueTextAsync(this TextDocument document, CancellationToken cancellationToken) { if (document.TryGetText(out var text)) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Formatting/ISyntaxFormattingService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Formatting/ISyntaxFormattingService.cs index 8e284c80f1d95..9a03b1bc75cf5 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Formatting/ISyntaxFormattingService.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Formatting/ISyntaxFormattingService.cs @@ -2,11 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Threading; using System.Collections.Immutable; +using System.Threading; using Microsoft.CodeAnalysis.Host; -using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Indentation; +using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Formatting; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Indentation/AbstractIndentationService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Indentation/AbstractIndentationService.cs index 6d83b3ceff91d..85ba113214fec 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Indentation/AbstractIndentationService.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Indentation/AbstractIndentationService.cs @@ -42,7 +42,7 @@ private Indenter GetIndenter(ParsedDocument document, int lineNumber, Indentatio var lineToBeIndented = document.Text.Lines[lineNumber]; -#if CODE_STYLE +#if !WORKSPACE var baseIndentationRule = NoOpFormattingRule.Instance; #else var formattingRuleFactory = document.SolutionServices.GetRequiredService(); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/GeneratedCodeRecognition/AbstractGeneratedCodeRecognitionService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/GeneratedCodeRecognition/AbstractGeneratedCodeRecognitionService.cs index ba5e45e4b2486..9b7948a46d809 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/GeneratedCodeRecognition/AbstractGeneratedCodeRecognitionService.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/GeneratedCodeRecognition/AbstractGeneratedCodeRecognitionService.cs @@ -13,7 +13,7 @@ namespace Microsoft.CodeAnalysis.GeneratedCodeRecognition; internal abstract class AbstractGeneratedCodeRecognitionService : IGeneratedCodeRecognitionService { -#if !CODE_STYLE +#if WORKSPACE public bool IsGeneratedCode(Document document, CancellationToken cancellationToken) { var syntaxTree = document.GetSyntaxTreeSynchronously(cancellationToken); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/GeneratedCodeRecognition/IGeneratedCodeRecognitionService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/GeneratedCodeRecognition/IGeneratedCodeRecognitionService.cs index 05f5c1c44aba1..6406974aaea27 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/GeneratedCodeRecognition/IGeneratedCodeRecognitionService.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/GeneratedCodeRecognition/IGeneratedCodeRecognitionService.cs @@ -10,7 +10,7 @@ namespace Microsoft.CodeAnalysis.GeneratedCodeRecognition; internal interface IGeneratedCodeRecognitionService : ILanguageService { -#if !CODE_STYLE +#if WORKSPACE bool IsGeneratedCode(Document document, CancellationToken cancellationToken); #endif diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/MoveDeclarationNearReference/AbstractMoveDeclarationNearReferenceService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/MoveDeclarationNearReference/AbstractMoveDeclarationNearReferenceService.cs index d742c69c03060..4d9f82714b6fa 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/MoveDeclarationNearReference/AbstractMoveDeclarationNearReferenceService.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/MoveDeclarationNearReference/AbstractMoveDeclarationNearReferenceService.cs @@ -5,6 +5,7 @@ #nullable disable using System.Collections.Immutable; +using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; @@ -176,9 +177,9 @@ private static void MergeDeclarationAndAssignment( private static ImmutableArray GetMergedTrivia( IFileBannerFactsService bannerService, TStatementSyntax statement1, TStatementSyntax statement2) { - return bannerService.GetLeadingBlankLines(statement2).Concat( - bannerService.GetTriviaAfterLeadingBlankLines(statement1)).Concat( - bannerService.GetTriviaAfterLeadingBlankLines(statement2)); + return [.. bannerService.GetLeadingBlankLines(statement2), + .. bannerService.GetTriviaAfterLeadingBlankLines(statement1), + .. bannerService.GetTriviaAfterLeadingBlankLines(statement2)]; } private bool CrossesMeaningfulBlock(State state) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsService.cs index eaa1a47979f85..fee350bac007a 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsService.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsService.cs @@ -7,7 +7,6 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Extensions; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.RemoveUnnecessaryImports; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/SemanticsFactsService/AbstractSemanticFactsService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/SemanticsFactsService/AbstractSemanticFactsService.cs index 4274201c8822f..12f64b48eb158 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/SemanticsFactsService/AbstractSemanticFactsService.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/SemanticsFactsService/AbstractSemanticFactsService.cs @@ -261,7 +261,7 @@ public IPreprocessingSymbol GetPreprocessingSymbol(SemanticModel semanticModel, public bool TryGetPrimaryConstructor(INamedTypeSymbol typeSymbol, [NotNullWhen(true)] out IMethodSymbol primaryConstructor) => SemanticFacts.TryGetPrimaryConstructor(typeSymbol, out primaryConstructor); -#if !CODE_STYLE +#if WORKSPACE public Task GetInterceptorSymbolAsync(Document document, int position, CancellationToken cancellationToken) => SemanticFacts.GetInterceptorSymbolAsync(document, position, cancellationToken); diff --git a/src/Workspaces/Core/Portable/SemanticModelReuse/AbstractSemanticModelReuseLanguageService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/SemanticModelReuse/AbstractSemanticModelReuseLanguageService.cs similarity index 96% rename from src/Workspaces/Core/Portable/SemanticModelReuse/AbstractSemanticModelReuseLanguageService.cs rename to src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/SemanticModelReuse/AbstractSemanticModelReuseLanguageService.cs index fa8f5a5360b00..634a0b63126f0 100644 --- a/src/Workspaces/Core/Portable/SemanticModelReuse/AbstractSemanticModelReuseLanguageService.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/SemanticModelReuse/AbstractSemanticModelReuseLanguageService.cs @@ -6,10 +6,13 @@ using System.Diagnostics; using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.PooledObjects; +#if WORKSPACE +using Microsoft.CodeAnalysis.Internal.Log; +#endif + namespace Microsoft.CodeAnalysis.SemanticModelReuse; internal abstract class AbstractSemanticModelReuseLanguageService< @@ -20,7 +23,9 @@ internal abstract class AbstractSemanticModelReuseLanguageService< where TBasePropertyDeclarationSyntax : TMemberDeclarationSyntax where TAccessorDeclarationSyntax : SyntaxNode { +#if WORKSPACE private readonly CountLogAggregator _logAggregator = new(); +#endif protected abstract ISyntaxFacts SyntaxFacts { get; } @@ -32,11 +37,13 @@ internal abstract class AbstractSemanticModelReuseLanguageService< public void Dispose() { +#if WORKSPACE Logger.Log(FunctionId.SemanticModelReuseLanguageService_TryGetSpeculativeSemanticModelAsync_Equivalent, KeyValueLogMessage.Create(static (m, _logAggregator) => { foreach (var kv in _logAggregator) m[kv.Key.ToString()] = kv.Value.GetCount(); }, _logAggregator)); +#endif } public async Task TryGetSpeculativeSemanticModelAsync(SemanticModel previousSemanticModel, SyntaxNode currentBodyNode, CancellationToken cancellationToken) @@ -48,7 +55,10 @@ public void Dispose() // then something very bad happened as we did that document.Project.GetDependentSemanticVersionAsync was // still the same. Log information so we can be alerted if this isn't being as successful as we expect. var isEquivalentTo = previousSyntaxTree.IsEquivalentTo(currentSyntaxTree, topLevel: true); + +#if WORKSPACE _logAggregator.IncreaseCount(isEquivalentTo); +#endif if (!isEquivalentTo) return null; @@ -71,13 +81,13 @@ public void Dispose() // Given that the common use case for us is continuously editing/typing inside a method body, we believe we can be conservative // in creating speculative model with those kind of trivia change, by requiring the method body block not to shift position, // w/o sacrificing performance in those common scenarios. - if (previousBodyNode.SpanStart != currentBodyNode.SpanStart) + if (previousBodyNode?.SpanStart != currentBodyNode.SpanStart) return null; return TryGetSpeculativeSemanticModelWorker(previousSemanticModel, previousBodyNode, currentBodyNode); } - protected SyntaxNode GetPreviousBodyNode(SyntaxNode previousRoot, SyntaxNode currentRoot, SyntaxNode currentBodyNode) + protected SyntaxNode? GetPreviousBodyNode(SyntaxNode previousRoot, SyntaxNode currentRoot, SyntaxNode currentBodyNode) { if (currentBodyNode is TAccessorDeclarationSyntax currentAccessor) { diff --git a/src/Workspaces/Core/Portable/SemanticModelReuse/ISemanticModelReuseLanguageService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/SemanticModelReuse/ISemanticModelReuseLanguageService.cs similarity index 100% rename from src/Workspaces/Core/Portable/SemanticModelReuse/ISemanticModelReuseLanguageService.cs rename to src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/SemanticModelReuse/ISemanticModelReuseLanguageService.cs diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/WorkspaceServices/SemanticModelReuse/ISemanticModelReuseWorkspaceService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/SemanticModelReuse/ISemanticModelReuseWorkspaceService.cs similarity index 100% rename from src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/WorkspaceServices/SemanticModelReuse/ISemanticModelReuseWorkspaceService.cs rename to src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/SemanticModelReuse/ISemanticModelReuseWorkspaceService.cs diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/WorkspaceServices/SemanticModelReuse/SemanticModelReuseWorkspaceServiceFactory.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/SemanticModelReuse/SemanticModelReuseWorkspaceServiceFactory.cs similarity index 100% rename from src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/WorkspaceServices/SemanticModelReuse/SemanticModelReuseWorkspaceServiceFactory.cs rename to src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/SemanticModelReuse/SemanticModelReuseWorkspaceServiceFactory.cs diff --git a/src/Workspaces/Core/Portable/SemanticModelReuse/SemanticModelWorkspaceServiceFactory.SemanticModelWorkspaceService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/SemanticModelReuse/SemanticModelWorkspaceServiceFactory.SemanticModelWorkspaceService.cs similarity index 98% rename from src/Workspaces/Core/Portable/SemanticModelReuse/SemanticModelWorkspaceServiceFactory.SemanticModelWorkspaceService.cs rename to src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/SemanticModelReuse/SemanticModelWorkspaceServiceFactory.SemanticModelWorkspaceService.cs index 8be7d9d051cdb..f4b99fa77d247 100644 --- a/src/Workspaces/Core/Portable/SemanticModelReuse/SemanticModelWorkspaceServiceFactory.SemanticModelWorkspaceService.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/SemanticModelReuse/SemanticModelWorkspaceServiceFactory.SemanticModelWorkspaceService.cs @@ -3,12 +3,12 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SemanticModelReuse; @@ -61,7 +61,12 @@ private sealed class SemanticModelReuseWorkspaceService : ISemanticModelReuseWor public SemanticModelReuseWorkspaceService(Workspace workspace) { _workspace = workspace; + +#if ROSLYN_4_12_OR_LOWER + _workspace.WorkspaceChanged += (sender, e) => +#else _workspace.RegisterWorkspaceChangedHandler((e) => +#endif { // if our map points at documents not in the current solution, then we want to clear things out. // this way we don't hold onto semantic models past, say, the c#/vb solutions closing. @@ -78,7 +83,12 @@ public SemanticModelReuseWorkspaceService(Workspace workspace) return; } } - }); + } +#if ROSLYN_4_12_OR_LOWER + ; +#else + ); +#endif } public async ValueTask ReuseExistingSpeculativeModelAsync(Document document, SyntaxNode node, CancellationToken cancellationToken) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/ParsedDocument.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/ParsedDocument.cs index 4706251f3c9eb..c655e9a564f0b 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/ParsedDocument.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/ParsedDocument.cs @@ -35,7 +35,7 @@ public static async ValueTask CreateAsync(Document document, Can return new ParsedDocument(document.Id, text, root, document.Project.GetExtendedLanguageServices()); } -#if !CODE_STYLE +#if WORKSPACE public static ParsedDocument CreateSynchronously(Document document, CancellationToken cancellationToken) { var text = document.GetTextSynchronously(cancellationToken); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/ILayeredServiceMetadata.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/ILayeredServiceMetadata.cs index bdbb52959390f..0ba932eb35785 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/ILayeredServiceMetadata.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/ILayeredServiceMetadata.cs @@ -8,7 +8,7 @@ namespace Microsoft.CodeAnalysis.Host.Mef; internal interface ILayeredServiceMetadata { - public IReadOnlyList WorkspaceKinds { get; } - public string Layer { get; } - public string ServiceType { get; } + IReadOnlyList WorkspaceKinds { get; } + string Layer { get; } + string ServiceType { get; } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/LanguageServiceMetadata.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/LanguageServiceMetadata.cs index 914f89c0b6ce7..51cad39078a46 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/LanguageServiceMetadata.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/LanguageServiceMetadata.cs @@ -26,7 +26,7 @@ internal sealed class LanguageServiceMetadata(IDictionary data) public string Layer { get; } = (string?)data.GetValueOrDefault(nameof(ExportLanguageServiceAttribute.Layer)) ?? ServiceLayer.Default; public IReadOnlyList WorkspaceKinds { get; } = (IReadOnlyList)data[ -#if CODE_STYLE +#if !WORKSPACE "WorkspaceKinds" #else nameof(ExportLanguageServiceAttribute.WorkspaceKinds) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/LayeredServiceUtilities.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/LayeredServiceUtilities.cs index b614df6eec4ec..bd1f0e6f290dd 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/LayeredServiceUtilities.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/LayeredServiceUtilities.cs @@ -5,7 +5,8 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; -using Microsoft.CodeAnalysis.Shared.Collections; +using System.Linq; +using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host.Mef; @@ -40,7 +41,7 @@ public static (Lazy? lazyService, bool usesFactory } } -#if !CODE_STYLE +#if WORKSPACE // test layer overrides all other layers and workspace kinds: service = servicesOfMatchingType.SingleOrDefault(static lz => lz.lazyService?.Metadata.Layer == ServiceLayer.Test); if (service.lazyService != null) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/MefWorkspaceServices.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/MefWorkspaceServices.cs index e276d79f32e1d..68901dbc1bec2 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/MefWorkspaceServices.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/MefWorkspaceServices.cs @@ -163,7 +163,7 @@ private ImmutableArray ComputeSupportedLanguages() public override IEnumerable SupportedLanguages => ComputeSupportedLanguages(); -#if CODE_STYLE +#if !WORKSPACE internal ImmutableArray SupportedLanguagesArray => ComputeSupportedLanguages(); #else internal override ImmutableArray SupportedLanguagesArray => ComputeSupportedLanguages(); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/WorkspaceServiceMetadata.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/WorkspaceServiceMetadata.cs index 3b040b1dde080..4095059a716b8 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/WorkspaceServiceMetadata.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/WorkspaceServiceMetadata.cs @@ -15,7 +15,7 @@ internal sealed class WorkspaceServiceMetadata(IDictionary data) public string Layer { get; } = (string)data[nameof(ExportWorkspaceServiceAttribute.Layer)]; public IReadOnlyList WorkspaceKinds { get; } = (IReadOnlyList)data[ -#if CODE_STYLE +#if !WORKSPACE "WorkspaceKinds" #else nameof(ExportLanguageServiceAttribute.WorkspaceKinds) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/WorkspaceExtensions.projitems b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/WorkspaceExtensions.projitems index f0502fd1b4058..bcd7a64cba81f 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/WorkspaceExtensions.projitems +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/WorkspaceExtensions.projitems @@ -14,9 +14,11 @@ + + @@ -150,11 +152,14 @@ - - + + + + + diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/CodeGeneration/ParameterGenerator.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/CodeGeneration/ParameterGenerator.vb index 00cb89a8f3b55..134b1147ca88e 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/CodeGeneration/ParameterGenerator.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/CodeGeneration/ParameterGenerator.vb @@ -4,7 +4,6 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeGeneration -Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/CodeGeneration/VisualBasicCodeGenerationService.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/CodeGeneration/VisualBasicCodeGenerationService.vb index b01506434ada5..6f0339b104f48 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/CodeGeneration/VisualBasicCodeGenerationService.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/CodeGeneration/VisualBasicCodeGenerationService.vb @@ -9,7 +9,6 @@ Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Host -Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/CodeRefactorings/VisualBasicRefactoringHelpersService.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/CodeRefactorings/VisualBasicRefactoringHelpersService.vb index 0539a9d7f2ad4..113c5ea4e6e56 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/CodeRefactorings/VisualBasicRefactoringHelpersService.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/CodeRefactorings/VisualBasicRefactoringHelpersService.vb @@ -4,11 +4,8 @@ Imports System.Composition Imports Microsoft.CodeAnalysis.CodeRefactorings -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Host.Mef -Imports Microsoft.CodeAnalysis.LanguageService -Imports Microsoft.CodeAnalysis.VisualBasic.LanguageService -Imports Microsoft.CodeAnalysis.Text +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings @@ -20,89 +17,6 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings Public Sub New() End Sub - Protected Overrides ReadOnly Property HeaderFacts As IHeaderFacts = VisualBasicHeaderFacts.Instance - - Public Overrides Function IsBetweenTypeMembers(sourceText As SourceText, root As SyntaxNode, position As Integer, ByRef typeDeclaration As SyntaxNode) As Boolean - Dim token = root.FindToken(position) - Dim typeDecl = token.GetAncestor(Of TypeBlockSyntax) - typeDeclaration = typeDecl - - If typeDecl IsNot Nothing Then - Dim start = If(typeDecl.Implements.LastOrDefault()?.Span.End, - If(typeDecl.Inherits.LastOrDefault()?.Span.End, - typeDecl.BlockStatement.Span.End)) - - If position >= start AndAlso - position <= typeDecl.EndBlockStatement.Span.Start Then - - Dim line = sourceText.Lines.GetLineFromPosition(position) - If Not line.IsEmptyOrWhitespace() Then - Return False - End If - - Dim member = typeDecl.Members.FirstOrDefault(Function(d) d.FullSpan.Contains(position)) - If member Is Nothing Then - ' There are no members, Or we're after the last member. - Return True - Else - ' We're within a member. Make sure we're in the leading whitespace of - ' the member. - If position < member.SpanStart Then - For Each trivia In member.GetLeadingTrivia() - If Not trivia.IsWhitespaceOrEndOfLine() Then - Return False - End If - - If trivia.FullSpan.Contains(position) Then - Return True - End If - Next - End If - End If - End If - End If - - Return False - End Function - - Protected Overrides Iterator Function ExtractNodesSimple(node As SyntaxNode, syntaxFacts As ISyntaxFactsService) As IEnumerable(Of SyntaxNode) - For Each baseExtraction In MyBase.ExtractNodesSimple(node, syntaxFacts) - Yield baseExtraction - Next - - ' VB's arguments can have identifiers nested in ModifiedArgument -> we want - ' identifiers to represent parent node -> need to extract. - If IsIdentifierOfParameter(node) Then - Yield node.Parent - End If - - ' In VB Statement both for/foreach are split into Statement (header) and the rest - ' selecting the header should still count for the whole blockSyntax - If TypeOf node Is ForEachStatementSyntax And TypeOf node.Parent Is ForEachBlockSyntax Then - Dim foreachStatement = CType(node, ForEachStatementSyntax) - Yield foreachStatement.Parent - End If - - If TypeOf node Is ForStatementSyntax And TypeOf node.Parent Is ForBlockSyntax Then - Dim forStatement = CType(node, ForStatementSyntax) - Yield forStatement.Parent - End If - - If TypeOf node Is VariableDeclaratorSyntax Then - Dim declarator = CType(node, VariableDeclaratorSyntax) - If TypeOf declarator.Parent Is LocalDeclarationStatementSyntax Then - Dim localDeclarationStatement = CType(declarator.Parent, LocalDeclarationStatementSyntax) - ' Only return the whole localDeclarationStatement if there's just one declarator with just one name - If localDeclarationStatement.Declarators.Count = 1 And localDeclarationStatement.Declarators.First().Names.Count = 1 Then - Yield localDeclarationStatement - End If - End If - End If - - End Function - - Public Shared Function IsIdentifierOfParameter(node As SyntaxNode) As Boolean - Return (TypeOf node Is ModifiedIdentifierSyntax) AndAlso (TypeOf node.Parent Is ParameterSyntax) AndAlso (CType(node.Parent, ParameterSyntax).Identifier Is node) - End Function + Protected Overrides ReadOnly Property RefactoringHelpers As IRefactoringHelpers = VisualBasicRefactoringHelpers.Instance End Class End Namespace diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/ContextQuery/VisualBasicSyntaxContextExtensions.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/ContextQuery/VisualBasicSyntaxContextExtensions.vb index b928016845b83..4d4a99541d9b8 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/ContextQuery/VisualBasicSyntaxContextExtensions.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/ContextQuery/VisualBasicSyntaxContextExtensions.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices -Imports System.Threading Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Indentation/VisualBasicIndentationService.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Indentation/VisualBasicIndentationService.vb index a34c8cba6f539..70eee4a5538fc 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Indentation/VisualBasicIndentationService.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Indentation/VisualBasicIndentationService.vb @@ -8,7 +8,6 @@ Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Indentation -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicAddImportsService.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicAddImportsService.vb index 29919d098b506..d4b30e66e2693 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicAddImportsService.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicAddImportsService.vb @@ -7,7 +7,6 @@ Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.AddImport Imports Microsoft.CodeAnalysis.CodeStyle -Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Options diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicSyntaxFactsService.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicSyntaxFactsService.vb index 7b4f4eb28f320..90ac602fb2ece 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicSyntaxFactsService.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicSyntaxFactsService.vb @@ -6,7 +6,6 @@ Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.LanguageService Namespace Microsoft.CodeAnalysis.VisualBasic diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicSyntaxGeneratorInternal.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicSyntaxGeneratorInternal.vb index bfc40c9847c00..2f45d9c8a3b49 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicSyntaxGeneratorInternal.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicSyntaxGeneratorInternal.vb @@ -16,7 +16,7 @@ Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration - Friend Class VisualBasicSyntaxGeneratorInternal + Friend NotInheritable Class VisualBasicSyntaxGeneratorInternal Inherits SyntaxGeneratorInternal Public Shared ReadOnly Instance As New VisualBasicSyntaxGeneratorInternal() diff --git a/src/Workspaces/VisualBasic/Portable/SemanticModelReuse/VisualBasicSemanticModelReuseLanguageService.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/SemanticModelReuse/VisualBasicSemanticModelReuseLanguageService.vb similarity index 96% rename from src/Workspaces/VisualBasic/Portable/SemanticModelReuse/VisualBasicSemanticModelReuseLanguageService.vb rename to src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/SemanticModelReuse/VisualBasicSemanticModelReuseLanguageService.vb index f2b17231d5975..5730200c899c3 100644 --- a/src/Workspaces/VisualBasic/Portable/SemanticModelReuse/VisualBasicSemanticModelReuseLanguageService.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/SemanticModelReuse/VisualBasicSemanticModelReuseLanguageService.vb @@ -6,7 +6,6 @@ Imports System.Composition Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageService Imports Microsoft.CodeAnalysis.SemanticModelReuse -Imports Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Imports Microsoft.CodeAnalysis.VisualBasic.LanguageService Imports Microsoft.CodeAnalysis.VisualBasic.Syntax @@ -35,7 +34,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.SemanticModelReuse Protected Overrides Function GetAccessors(member As DeclarationStatementSyntax) As SyntaxList(Of AccessorBlockSyntax) Contract.ThrowIfFalse(TypeOf member Is PropertyBlockSyntax OrElse TypeOf member Is EventBlockSyntax) - Return VisualBasicSyntaxGenerator.GetAccessorList(member) + Return GetAccessorList(member) End Function Public Overrides Function TryGetContainingMethodBodyForSpeculation(node As SyntaxNode) As SyntaxNode diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/VisualBasicWorkspaceExtensions.projitems b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/VisualBasicWorkspaceExtensions.projitems index 60d98682fafa9..f1ea2654a14ca 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/VisualBasicWorkspaceExtensions.projitems +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/VisualBasicWorkspaceExtensions.projitems @@ -85,6 +85,7 @@ + @@ -98,7 +99,6 @@ - diff --git a/src/Workspaces/VisualBasic/Portable/Classification/ClassificationHelpers.vb b/src/Workspaces/VisualBasic/Portable/Classification/ClassificationHelpers.vb index 8a263cb8ca829..7cb010fec1d82 100644 --- a/src/Workspaces/VisualBasic/Portable/Classification/ClassificationHelpers.vb +++ b/src/Workspaces/VisualBasic/Portable/Classification/ClassificationHelpers.vb @@ -5,7 +5,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.Collections -Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities diff --git a/src/Workspaces/VisualBasic/Portable/Classification/SyntaxClassification/ImportAliasClauseSyntaxClassifier.vb b/src/Workspaces/VisualBasic/Portable/Classification/SyntaxClassification/ImportAliasClauseSyntaxClassifier.vb index d023385a411c0..fd6ff1431911f 100644 --- a/src/Workspaces/VisualBasic/Portable/Classification/SyntaxClassification/ImportAliasClauseSyntaxClassifier.vb +++ b/src/Workspaces/VisualBasic/Portable/Classification/SyntaxClassification/ImportAliasClauseSyntaxClassifier.vb @@ -7,7 +7,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.Classification.Classifiers Imports Microsoft.CodeAnalysis.Collections -Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Workspaces/VisualBasic/Portable/Classification/Worker.vb b/src/Workspaces/VisualBasic/Portable/Classification/Worker.vb index cffae99c9adda..dda3822db9151 100644 --- a/src/Workspaces/VisualBasic/Portable/Classification/Worker.vb +++ b/src/Workspaces/VisualBasic/Portable/Classification/Worker.vb @@ -5,7 +5,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.Collections -Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/NormalizeModifiersOrOperatorsCodeCleanupProvider.vb b/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/NormalizeModifiersOrOperatorsCodeCleanupProvider.vb index 190aa7bd1dece..50ca94561ed4f 100644 --- a/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/NormalizeModifiersOrOperatorsCodeCleanupProvider.vb +++ b/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/NormalizeModifiersOrOperatorsCodeCleanupProvider.vb @@ -7,7 +7,6 @@ Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Host diff --git a/src/Workspaces/VisualBasic/Portable/CodeGeneration/VisualBasicSyntaxGenerator.vb b/src/Workspaces/VisualBasic/Portable/CodeGeneration/VisualBasicSyntaxGenerator.vb index 3a3e8ca3030b7..e778643388cce 100644 --- a/src/Workspaces/VisualBasic/Portable/CodeGeneration/VisualBasicSyntaxGenerator.vb +++ b/src/Workspaces/VisualBasic/Portable/CodeGeneration/VisualBasicSyntaxGenerator.vb @@ -2365,8 +2365,10 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Return mods End Function - Private Shared Sub GetAccessibilityAndModifiers(modifierTokens As SyntaxTokenList, ByRef accessibility As Accessibility, ByRef modifiers As DeclarationModifiers, ByRef isDefault As Boolean) + Private Shared Sub GetAccessibilityAndModifiers(modifierTokens As SyntaxTokenList, ByRef accessibility As Accessibility, ByRef declarationModifiers As DeclarationModifiers, ByRef isDefault As Boolean) + Dim modifiers As Modifiers VisualBasicAccessibilityFacts.GetAccessibilityAndModifiers(modifierTokens, accessibility, modifiers, isDefault) + declarationModifiers = modifiers.ToDeclarationModifiers() End Sub Private Shared Function GetModifierTokens(declaration As SyntaxNode) As SyntaxTokenList @@ -3028,7 +3030,6 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration End Function Public Overrides Function InsertAccessors(declaration As SyntaxNode, index As Integer, accessors As IEnumerable(Of SyntaxNode)) As SyntaxNode - Dim currentList = GetAccessorList(declaration) Dim newList = AsAccessorList(accessors, declaration.Kind) @@ -3039,17 +3040,6 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration End If End Function - Friend Shared Function GetAccessorList(declaration As SyntaxNode) As SyntaxList(Of AccessorBlockSyntax) - Select Case declaration.Kind - Case SyntaxKind.PropertyBlock - Return DirectCast(declaration, PropertyBlockSyntax).Accessors - Case SyntaxKind.EventBlock - Return DirectCast(declaration, EventBlockSyntax).Accessors - Case Else - Return Nothing - End Select - End Function - Private Shared Function WithAccessorList(declaration As SyntaxNode, accessorList As SyntaxList(Of AccessorBlockSyntax)) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.PropertyBlock diff --git a/src/Workspaces/VisualBasic/Portable/Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj b/src/Workspaces/VisualBasic/Portable/Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj index 43aeb17ae3230..6367ff3942296 100644 --- a/src/Workspaces/VisualBasic/Portable/Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj +++ b/src/Workspaces/VisualBasic/Portable/Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj @@ -4,6 +4,7 @@ Library $(NetRoslynSourceBuild);netstandard2.0 + $(DefineConstants),VISUAL_BASIC_WORKSPACE full diff --git a/src/Workspaces/VisualBasic/Portable/OrganizeImports/VisualBasicOrganizeImportsService.Rewriter.vb b/src/Workspaces/VisualBasic/Portable/OrganizeImports/VisualBasicOrganizeImportsService.Rewriter.vb index 0a5ac4d008349..2e2b692c39590 100644 --- a/src/Workspaces/VisualBasic/Portable/OrganizeImports/VisualBasicOrganizeImportsService.Rewriter.vb +++ b/src/Workspaces/VisualBasic/Portable/OrganizeImports/VisualBasicOrganizeImportsService.Rewriter.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.OrganizeImports -Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities @@ -17,8 +16,6 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.OrganizeImports Private ReadOnly _separateGroups As Boolean Private ReadOnly _newLineTrivia As SyntaxTrivia - Public ReadOnly TextChanges As IList(Of TextChange) = New List(Of TextChange)() - Public Sub New(options As OrganizeImportsOptions) _placeSystemNamespaceFirst = options.PlaceSystemNamespaceFirst _separateGroups = options.SeparateImportDirectiveGroups @@ -30,53 +27,13 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.OrganizeImports Dim organizedImports = ImportsOrganizer.Organize( node.Imports, _placeSystemNamespaceFirst, _separateGroups, _newLineTrivia) - Dim result = node.WithImports(organizedImports) - If result IsNot node Then - AddTextChange(node.Imports, organizedImports) - End If - - Return result + Return node.WithImports(organizedImports) End Function Public Overrides Function VisitImportsStatement(node As ImportsStatementSyntax) As SyntaxNode Dim organizedImportsClauses = ImportsOrganizer.Organize(node.ImportsClauses) - Dim result = node.WithImportsClauses(organizedImportsClauses) - If result IsNot node Then - AddTextChange(node.ImportsClauses, organizedImportsClauses) - End If - - Return result - End Function - - Private Sub AddTextChange(Of TSyntax As SyntaxNode)(list As SeparatedSyntaxList(Of TSyntax), - organizedList As SeparatedSyntaxList(Of TSyntax)) - If list.Count > 0 Then - Me.TextChanges.Add(New TextChange(GetTextSpan(list), GetNewText(organizedList))) - End If - End Sub - - Private Sub AddTextChange(Of TSyntax As SyntaxNode)(list As SyntaxList(Of TSyntax), - organizedList As SyntaxList(Of TSyntax)) - If list.Count > 0 Then - Me.TextChanges.Add(New TextChange(GetTextSpan(list), GetNewText(organizedList))) - End If - End Sub - - Private Shared Function GetNewText(Of TSyntax As SyntaxNode)(organizedList As SyntaxList(Of TSyntax)) As String - Return String.Join(String.Empty, organizedList.[Select](Function(t) t.ToFullString())) - End Function - - Private Shared Function GetNewText(Of TSyntax As SyntaxNode)(organizedList As SeparatedSyntaxList(Of TSyntax)) As String - Return String.Join(String.Empty, organizedList.GetWithSeparators().[Select](Function(t) t.ToFullString())) - End Function - - Private Shared Function GetTextSpan(Of TSyntax As SyntaxNode)(list As SyntaxList(Of TSyntax)) As TextSpan - Return TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.[End]) - End Function - - Private Shared Function GetTextSpan(Of TSyntax As SyntaxNode)(list As SeparatedSyntaxList(Of TSyntax)) As TextSpan - Return TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.[End]) + Return node.WithImportsClauses(organizedImportsClauses) End Function End Class End Class diff --git a/src/Workspaces/VisualBasic/Portable/OrganizeImports/VisualBasicOrganizeImportsService.vb b/src/Workspaces/VisualBasic/Portable/OrganizeImports/VisualBasicOrganizeImportsService.vb index ded1ba9f8b98d..cad2e89c9df64 100644 --- a/src/Workspaces/VisualBasic/Portable/OrganizeImports/VisualBasicOrganizeImportsService.vb +++ b/src/Workspaces/VisualBasic/Portable/OrganizeImports/VisualBasicOrganizeImportsService.vb @@ -9,7 +9,7 @@ Imports Microsoft.CodeAnalysis.OrganizeImports Namespace Microsoft.CodeAnalysis.VisualBasic.OrganizeImports - Partial Friend Class VisualBasicOrganizeImportsService + Partial Friend NotInheritable Class VisualBasicOrganizeImportsService Implements IOrganizeImportsService @@ -24,16 +24,9 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.OrganizeImports Return document.WithSyntaxRoot(newRoot) End Function - Public ReadOnly Property SortImportsDisplayStringWithAccelerator As String Implements IOrganizeImportsService.SortImportsDisplayStringWithAccelerator - Get - Return VBWorkspaceResources.Sort_Imports - End Get - End Property + Public ReadOnly Property SortImportsDisplayStringWithAccelerator As String = VBWorkspaceResources.Sort_Imports_with_accelerator Implements IOrganizeImportsService.SortImportsDisplayStringWithAccelerator + Public ReadOnly Property SortImportsDisplayStringWithoutAccelerator As String = VBWorkspaceResources.Sort_Imports Implements IOrganizeImportsService.SortImportsDisplayStringWithoutAccelerator - Public ReadOnly Property SortAndRemoveUnusedImportsDisplayStringWithAccelerator As String Implements IOrganizeImportsService.SortAndRemoveUnusedImportsDisplayStringWithAccelerator - Get - Return VBWorkspaceResources.Remove_and_Sort_Imports - End Get - End Property + Public ReadOnly Property SortAndRemoveUnusedImportsDisplayStringWithAccelerator As String = VBWorkspaceResources.Remove_and_Sort_Imports Implements IOrganizeImportsService.SortAndRemoveUnusedImportsDisplayStringWithAccelerator End Class End Namespace diff --git a/src/Workspaces/VisualBasic/Portable/Serialization/VisualBasicOptionsSerializationService.vb b/src/Workspaces/VisualBasic/Portable/Serialization/VisualBasicOptionsSerializationService.vb index 64a3846fe7955..5aa54ee9529f6 100644 --- a/src/Workspaces/VisualBasic/Portable/Serialization/VisualBasicOptionsSerializationService.vb +++ b/src/Workspaces/VisualBasic/Portable/Serialization/VisualBasicOptionsSerializationService.vb @@ -115,7 +115,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Serialization For i = 0 To count - 1 Dim key = reader.ReadString() Dim value = reader.ReadScalarValue() - builder.Add(KeyValuePairUtil.Create(key, value)) + builder.Add(KeyValuePair.Create(key, value)) Next Dim options = New VisualBasicParseOptions(languageVersion, documentationMode, kind, builder.MoveToImmutable()) diff --git a/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/AbstractVisualBasicReducer.AbstractReductionRewriter.vb b/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/AbstractVisualBasicReducer.AbstractReductionRewriter.vb index f3679ddea88ce..66a7bcb547629 100644 --- a/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/AbstractVisualBasicReducer.AbstractReductionRewriter.vb +++ b/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/AbstractVisualBasicReducer.AbstractReductionRewriter.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/AbstractVisualBasicReducer.vb b/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/AbstractVisualBasicReducer.vb index 48cfeb1d708e5..7c128e25a6a87 100644 --- a/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/AbstractVisualBasicReducer.vb +++ b/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/AbstractVisualBasicReducer.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.LanguageService -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.LanguageService diff --git a/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicCallReducer.vb b/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicCallReducer.vb index 22e148896c827..8ffd0968063b3 100644 --- a/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicCallReducer.vb +++ b/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicCallReducer.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicEscapingReducer.vb b/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicEscapingReducer.vb index 4ec5796c97fd7..97c79f4d6f126 100644 --- a/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicEscapingReducer.vb +++ b/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicEscapingReducer.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicExtensionMethodReducer.vb b/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicExtensionMethodReducer.vb index 24ee11bf608f1..819c6a0f97b4e 100644 --- a/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicExtensionMethodReducer.vb +++ b/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicExtensionMethodReducer.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicInferredMemberNameReducer.Rewriter.vb b/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicInferredMemberNameReducer.Rewriter.vb index 26ff8009b40c2..c75c05b146e03 100644 --- a/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicInferredMemberNameReducer.Rewriter.vb +++ b/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicInferredMemberNameReducer.Rewriter.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicMiscellaneousReducer.vb b/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicMiscellaneousReducer.vb index f87a4abdfe1b9..14767e10b25f7 100644 --- a/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicMiscellaneousReducer.vb +++ b/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicMiscellaneousReducer.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicVariableDeclaratorReducer.vb b/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicVariableDeclaratorReducer.vb index 247431b559bac..39dca4dd155ce 100644 --- a/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicVariableDeclaratorReducer.vb +++ b/src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicVariableDeclaratorReducer.vb @@ -5,7 +5,6 @@ Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.Formatting -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.Text diff --git a/src/Workspaces/VisualBasic/Portable/Simplification/Simplifiers/AbstractVisualBasicSimplifier.vb b/src/Workspaces/VisualBasic/Portable/Simplification/Simplifiers/AbstractVisualBasicSimplifier.vb index 20748ca737186..ca74fcd253b0e 100644 --- a/src/Workspaces/VisualBasic/Portable/Simplification/Simplifiers/AbstractVisualBasicSimplifier.vb +++ b/src/Workspaces/VisualBasic/Portable/Simplification/Simplifiers/AbstractVisualBasicSimplifier.vb @@ -4,7 +4,6 @@ Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.Simplification.Simplifiers Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Workspaces/VisualBasic/Portable/Simplification/Simplifiers/ExpressionSimplifier.vb b/src/Workspaces/VisualBasic/Portable/Simplification/Simplifiers/ExpressionSimplifier.vb index f7b6cd943910b..0cf3cee963e2e 100644 --- a/src/Workspaces/VisualBasic/Portable/Simplification/Simplifiers/ExpressionSimplifier.vb +++ b/src/Workspaces/VisualBasic/Portable/Simplification/Simplifiers/ExpressionSimplifier.vb @@ -6,7 +6,6 @@ Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeStyle -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax diff --git a/src/Workspaces/VisualBasic/Portable/Simplification/Simplifiers/NameSimplifier.vb b/src/Workspaces/VisualBasic/Portable/Simplification/Simplifiers/NameSimplifier.vb index ff296801f59ae..32d07fc49c72c 100644 --- a/src/Workspaces/VisualBasic/Portable/Simplification/Simplifiers/NameSimplifier.vb +++ b/src/Workspaces/VisualBasic/Portable/Simplification/Simplifiers/NameSimplifier.vb @@ -6,7 +6,6 @@ Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeStyle -Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.Text diff --git a/src/Workspaces/VisualBasic/Portable/VBWorkspaceResources.resx b/src/Workspaces/VisualBasic/Portable/VBWorkspaceResources.resx index 43f8dc0e878d5..58bf69ddc0e94 100644 --- a/src/Workspaces/VisualBasic/Portable/VBWorkspaceResources.resx +++ b/src/Workspaces/VisualBasic/Portable/VBWorkspaceResources.resx @@ -255,9 +255,12 @@ R&emove and Sort Imports - + &Sort Imports + + Sort Imports + VB Coding Conventions diff --git a/src/Workspaces/VisualBasic/Portable/Workspace/LanguageServices/VisualBasicSyntaxTreeFactoryService.vb b/src/Workspaces/VisualBasic/Portable/Workspace/LanguageServices/VisualBasicSyntaxTreeFactoryService.vb index 6b810e4587f7a..0535d17e05393 100644 --- a/src/Workspaces/VisualBasic/Portable/Workspace/LanguageServices/VisualBasicSyntaxTreeFactoryService.vb +++ b/src/Workspaces/VisualBasic/Portable/Workspace/LanguageServices/VisualBasicSyntaxTreeFactoryService.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Composition -Imports System.IO Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis.Host diff --git a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.cs.xlf b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.cs.xlf index 8f1c14134a046..a2e8ba063502c 100644 --- a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.cs.xlf +++ b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.cs.xlf @@ -13,8 +13,13 @@ + Sort Imports + Sort Imports + + + &Sort Imports - &Seřadit importy + &Sort Imports diff --git a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.de.xlf b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.de.xlf index 3b85f06265d2b..175b1a3187e1b 100644 --- a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.de.xlf +++ b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.de.xlf @@ -13,8 +13,13 @@ + Sort Imports + Sort Imports + + + &Sort Imports - Importe &sortieren + &Sort Imports diff --git a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.es.xlf b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.es.xlf index f8f920679f207..492c4a4c3526f 100644 --- a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.es.xlf +++ b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.es.xlf @@ -13,8 +13,13 @@ + Sort Imports + Sort Imports + + + &Sort Imports - Orde&nar instrucciones Import + &Sort Imports diff --git a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.fr.xlf b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.fr.xlf index cba9986390434..8b73a2f1394f3 100644 --- a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.fr.xlf +++ b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.fr.xlf @@ -13,8 +13,13 @@ + Sort Imports + Sort Imports + + + &Sort Imports - &Trier les import + &Sort Imports diff --git a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.it.xlf b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.it.xlf index 0668a338c5f4e..7157d29d7f340 100644 --- a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.it.xlf +++ b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.it.xlf @@ -13,8 +13,13 @@ + Sort Imports + Sort Imports + + + &Sort Imports - Or&dina import + &Sort Imports diff --git a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.ja.xlf b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.ja.xlf index 5924be0c13286..a563e92624552 100644 --- a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.ja.xlf +++ b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.ja.xlf @@ -13,8 +13,13 @@ + Sort Imports + Sort Imports + + + &Sort Imports - インポートの並べ替え(&S) + &Sort Imports diff --git a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.ko.xlf b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.ko.xlf index cc645230fa24d..844d6f0b0158d 100644 --- a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.ko.xlf +++ b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.ko.xlf @@ -13,8 +13,13 @@ + Sort Imports + Sort Imports + + + &Sort Imports - 가져오기 정렬(&S) + &Sort Imports diff --git a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.pl.xlf b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.pl.xlf index 70bdac61bff28..94e17ff6cd304 100644 --- a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.pl.xlf +++ b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.pl.xlf @@ -13,8 +13,13 @@ + Sort Imports + Sort Imports + + + &Sort Imports - &Sortuj importy + &Sort Imports diff --git a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.pt-BR.xlf b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.pt-BR.xlf index 07d03ccdfcdf8..4d414589885cc 100644 --- a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.pt-BR.xlf +++ b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.pt-BR.xlf @@ -13,8 +13,13 @@ + Sort Imports + Sort Imports + + + &Sort Imports - Cla&ssificar Importações + &Sort Imports diff --git a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.ru.xlf b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.ru.xlf index 79fca3c4d8de2..e151ef4452e1b 100644 --- a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.ru.xlf +++ b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.ru.xlf @@ -13,8 +13,13 @@ + Sort Imports + Sort Imports + + + &Sort Imports - &Сортировать импорты + &Sort Imports diff --git a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.tr.xlf b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.tr.xlf index e257b03cd0866..874dc2a30ea26 100644 --- a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.tr.xlf +++ b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.tr.xlf @@ -13,8 +13,13 @@ + Sort Imports + Sort Imports + + + &Sort Imports - İçeri Aktarmaları &Sırala + &Sort Imports diff --git a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.zh-Hans.xlf b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.zh-Hans.xlf index 2227c1d84eb5e..2ab0556470768 100644 --- a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.zh-Hans.xlf +++ b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.zh-Hans.xlf @@ -13,8 +13,13 @@ + Sort Imports + Sort Imports + + + &Sort Imports - 对导入项排序(&S) + &Sort Imports diff --git a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.zh-Hant.xlf b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.zh-Hant.xlf index 458c31aa88bbc..515d4452206bf 100644 --- a/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.zh-Hant.xlf +++ b/src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.zh-Hant.xlf @@ -13,8 +13,13 @@ + Sort Imports + Sort Imports + + + &Sort Imports - 排序 Import(&S) + &Sort Imports diff --git a/src/Workspaces/VisualBasicTest/CaseCorrection/CaseCorrectionTests.vb b/src/Workspaces/VisualBasicTest/CaseCorrection/CaseCorrectionTests.vb index adf3d1b402d4e..1ebbdc558168b 100644 --- a/src/Workspaces/VisualBasicTest/CaseCorrection/CaseCorrectionTests.vb +++ b/src/Workspaces/VisualBasicTest/CaseCorrection/CaseCorrectionTests.vb @@ -2,11 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.Test.Utilities -Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.VisualBasic -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit diff --git a/src/Workspaces/VisualBasicTest/CodeGeneration/AddImportsTests.vb b/src/Workspaces/VisualBasicTest/CodeGeneration/AddImportsTests.vb index e28c0e358f468..3c4d7e7216e03 100644 --- a/src/Workspaces/VisualBasicTest/CodeGeneration/AddImportsTests.vb +++ b/src/Workspaces/VisualBasicTest/CodeGeneration/AddImportsTests.vb @@ -4,7 +4,6 @@ Imports System.Threading Imports Microsoft.CodeAnalysis.AddImport -Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Simplification diff --git a/src/Workspaces/VisualBasicTest/Formatting/FormattingTests.vb b/src/Workspaces/VisualBasicTest/Formatting/FormattingTests.vb index ff2a248e8a530..895a9ce5ebe79 100644 --- a/src/Workspaces/VisualBasicTest/Formatting/FormattingTests.vb +++ b/src/Workspaces/VisualBasicTest/Formatting/FormattingTests.vb @@ -3,7 +3,6 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading -Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Test.Utilities diff --git a/src/Workspaces/VisualBasicTest/Formatting/VisualBasicFormattingTestBase.vb b/src/Workspaces/VisualBasicTest/Formatting/VisualBasicFormattingTestBase.vb index 761cff6eebbbe..0427517f509b2 100644 --- a/src/Workspaces/VisualBasicTest/Formatting/VisualBasicFormattingTestBase.vb +++ b/src/Workspaces/VisualBasicTest/Formatting/VisualBasicFormattingTestBase.vb @@ -5,14 +5,12 @@ Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Collections -Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.UnitTests.Formatting Imports Microsoft.CodeAnalysis.VisualBasic.Formatting Imports Roslyn.Test.Utilities -Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Formatting Public Class VisualBasicFormattingTestBase diff --git a/src/Workspaces/VisualBasicTest/OrganizeImports/OrganizeImportsTests.vb b/src/Workspaces/VisualBasicTest/OrganizeImports/OrganizeImportsTests.vb index 9b1ff4e47b630..14664f5cc09cb 100644 --- a/src/Workspaces/VisualBasicTest/OrganizeImports/OrganizeImportsTests.vb +++ b/src/Workspaces/VisualBasicTest/OrganizeImports/OrganizeImportsTests.vb @@ -3,17 +3,15 @@ ' See the LICENSE file in the project root for more information. Imports System.Threading -Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Formatting -Imports Microsoft.CodeAnalysis.VisualBasic.Formatting +Imports Microsoft.CodeAnalysis.OrganizeImports +Imports Microsoft.CodeAnalysis.[Shared].Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text -Imports Microsoft.CodeAnalysis.Options +Imports Microsoft.CodeAnalysis.UnitTests +Imports Microsoft.CodeAnalysis.VisualBasic.Formatting Imports Roslyn.Test.Utilities Imports Xunit -Imports Microsoft.CodeAnalysis.[Shared].Extensions -Imports Microsoft.CodeAnalysis.OrganizeImports -Imports Microsoft.CodeAnalysis.UnitTests Namespace Microsoft.CodeAnalysis.VisualBasic.Workspaces.UnitTests.OrganizeImports <[UseExportProvider]> diff --git a/src/Workspaces/VisualBasicTest/VisualBasicExtensionsTests.vb b/src/Workspaces/VisualBasicTest/VisualBasicExtensionsTests.vb index 7f372fb4a0353..acc9d461d47e8 100644 --- a/src/Workspaces/VisualBasicTest/VisualBasicExtensionsTests.vb +++ b/src/Workspaces/VisualBasicTest/VisualBasicExtensionsTests.vb @@ -3,10 +3,10 @@ ' See the LICENSE file in the project root for more information. Imports System.Text +Imports System.Threading +Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.SyntaxTreeExtensions Imports Roslyn.Test.Utilities Imports Xunit -Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.SyntaxTreeExtensions -Imports System.Threading Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests